

Doc AWS SDK Examples GitHub リポジトリには、他にも SDK の例があります。 [AWS](https://github.com/awsdocs/aws-doc-sdk-examples)

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

# SDK を使用した AWS SDKs別のコード例
<a name="code_example_library_by_sdk"></a>

次のコード例は、 AWS Software Development Kit (SDK) AWS のサービス で を使用する方法を示しています。このセクションは SDK 言語ごとにまとめられています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [SDK for .NET](csharp_3_code_examples.md)
+ [SDK for .NET (v4)](csharp_4_code_examples.md)
+ [AWS CLI Bash スクリプトを使用する](bash_2_code_examples.md)
+ [SDK for C\$1\$1](cpp_1_code_examples.md)
+ [AWS CLI](cli_2_code_examples.md)
+ [SDK for Go V2](go_2_code_examples.md)
+ [SDK for JavaScript (v2)](javascript_2_code_examples.md)
+ [SDK for JavaScript (v3)](javascript_3_code_examples.md)
+ [SDK for Java 2.x](java_2_code_examples.md)
+ [SDK for Kotlin](kotlin_1_code_examples.md)
+ [SDK for PHP](php_3_code_examples.md)
+ [Tools for PowerShell V4](powershell_4_code_examples.md)
+ [Tools for PowerShell V5](powershell_5_code_examples.md)
+ [SDK for Python (Boto3)](python_3_code_examples.md)
+ [SDK for Ruby](ruby_3_code_examples.md)
+ [SDK for Rust](rust_1_code_examples.md)
+ [SDK for SAP ABAP](sap-abap_1_code_examples.md)
+ [SDK for Swift](swift_1_code_examples.md)

# のコード例 SDK for .NET
<a name="csharp_3_code_examples"></a>

次のコード例は、 AWS SDK for .NET で を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [SDK for .NET デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/welcome.html) ** – で .NET を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23dotnet)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](csharp_3_acm_code_examples.md)
+ [API ゲートウェイ](csharp_3_api-gateway_code_examples.md)
+ [Aurora](csharp_3_aurora_code_examples.md)
+ [Auto Scaling](csharp_3_auto-scaling_code_examples.md)
+ [Amazon Bedrock ランタイム](csharp_3_bedrock-runtime_code_examples.md)
+ [CloudWatch Logs](csharp_3_cloudwatch-logs_code_examples.md)
+ [Amazon Cognito ID プロバイダー](csharp_3_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](csharp_3_comprehend_code_examples.md)
+ [Amazon DocumentDB](csharp_3_docdb_code_examples.md)
+ [DynamoDB](csharp_3_dynamodb_code_examples.md)
+ [Amazon EC2](csharp_3_ec2_code_examples.md)
+ [Amazon ECS](csharp_3_ecs_code_examples.md)
+ [Elastic Load Balancing - バージョン 2](csharp_3_elastic-load-balancing-v2_code_examples.md)
+ [EventBridge](csharp_3_eventbridge_code_examples.md)
+ [EventBridge スケジューラ](csharp_3_scheduler_code_examples.md)
+ [Amazon Glacier](csharp_3_glacier_code_examples.md)
+ [AWS Glue](csharp_3_glue_code_examples.md)
+ [IAM](csharp_3_iam_code_examples.md)
+ [Amazon Keyspaces](csharp_3_keyspaces_code_examples.md)
+ [Kinesis](csharp_3_kinesis_code_examples.md)
+ [AWS KMS](csharp_3_kms_code_examples.md)
+ [Lambda](csharp_3_lambda_code_examples.md)
+ [MediaConvert](csharp_3_mediaconvert_code_examples.md)
+ [Amazon MSK](csharp_3_kafka_code_examples.md)
+ [組織](csharp_3_organizations_code_examples.md)
+ [パートナーセントラル](csharp_3_partnercentral-selling_code_examples.md)
+ [Amazon Pinpoint](csharp_3_pinpoint_code_examples.md)
+ [Amazon Polly](csharp_3_polly_code_examples.md)
+ [Amazon RDS](csharp_3_rds_code_examples.md)
+ [Amazon RDS データサービス](csharp_3_rds-data_code_examples.md)
+ [Amazon Rekognition](csharp_3_rekognition_code_examples.md)
+ [Route 53 ドメイン登録](csharp_3_route-53-domains_code_examples.md)
+ [Amazon S3](csharp_3_s3_code_examples.md)
+ [SageMaker AI](csharp_3_sagemaker_code_examples.md)
+ [Secrets Manager](csharp_3_secrets-manager_code_examples.md)
+ [Amazon SES](csharp_3_ses_code_examples.md)
+ [Amazon SES API v2](csharp_3_sesv2_code_examples.md)
+ [Amazon SNS](csharp_3_sns_code_examples.md)
+ [Amazon SQS](csharp_3_sqs_code_examples.md)
+ [ステップ関数](csharp_3_sfn_code_examples.md)
+ [AWS STS](csharp_3_sts_code_examples.md)
+ [サポート](csharp_3_support_code_examples.md)
+ [Amazon Textract](csharp_3_textract_code_examples.md)
+ [Amazon Transcribe](csharp_3_transcribe_code_examples.md)
+ [Amazon Translate](csharp_3_translate_code_examples.md)

# を使用した ACM の例 SDK for .NET
<a name="csharp_3_acm_code_examples"></a>

次のコード例は、ACM AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeCertificate`
<a name="acm_DescribeCertificate_csharp_3_topic"></a>

次のコード例は、`DescribeCertificate` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/ACM#code-examples)での設定と実行の方法を確認してください。

```
using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.CertificateManager;
using Amazon.CertificateManager.Model;

namespace DescribeCertificate
{
    class DescribeCertificate
    {
        // The following example retrieves and displays the metadata for a
        // certificate using the AWS Certificate Manager (ACM) service.

        // Specify your AWS Region (an example Region is shown).
        private static readonly RegionEndpoint ACMRegion = RegionEndpoint.USEast1;
        private static AmazonCertificateManagerClient _client;

        static void Main(string[] args)
        {
            _client = new Amazon.CertificateManager.AmazonCertificateManagerClient(ACMRegion);

            var describeCertificateReq = new DescribeCertificateRequest();
            // The ARN used here is just an example. Replace it with the ARN of
            // a certificate that exists on your account.
            describeCertificateReq.CertificateArn =
                "arn:aws:acm:us-east-1:123456789012:certificate/8cfd7dae-9b6a-2d07-92bc-1c309EXAMPLE";

            var certificateDetailResp =
                DescribeCertificateResponseAsync(client: _client, request: describeCertificateReq);
            var certificateDetail = certificateDetailResp.Result.Certificate;

            if (certificateDetail is not null)
            {
                DisplayCertificateDetails(certificateDetail);
            }
        }

        /// <summary>
        /// Displays detailed metadata about a certificate retrieved
        /// using the ACM service.
        /// </summary>
        /// <param name="certificateDetail">The object that contains details
        /// returned from the call to DescribeCertificateAsync.</param>
        static void DisplayCertificateDetails(CertificateDetail certificateDetail)
        {
            Console.WriteLine("\nCertificate Details: ");
            Console.WriteLine($"Certificate Domain: {certificateDetail.DomainName}");
            Console.WriteLine($"Certificate Arn: {certificateDetail.CertificateArn}");
            Console.WriteLine($"Certificate Subject: {certificateDetail.Subject}");
            Console.WriteLine($"Certificate Status: {certificateDetail.Status}");
            foreach (var san in certificateDetail.SubjectAlternativeNames)
            {
                Console.WriteLine($"Certificate SubjectAlternativeName: {san}");
            }
        }

        /// <summary>
        /// Retrieves the metadata associated with the ACM service certificate.
        /// </summary>
        /// <param name="client">An AmazonCertificateManagerClient object
        /// used to call DescribeCertificateResponse.</param>
        /// <param name="request">The DescribeCertificateRequest object that
        /// will be passed to the method call.</param>
        /// <returns></returns>
        static async Task<DescribeCertificateResponse> DescribeCertificateResponseAsync(
            AmazonCertificateManagerClient client, DescribeCertificateRequest request)
        {
            var response = new DescribeCertificateResponse();

            try
            {
                response = await client.DescribeCertificateAsync(request);
            }
            catch (InvalidArnException)
            {
                Console.WriteLine($"Error: The ARN specified is invalid.");
            }
            catch (ResourceNotFoundException)
            {
                Console.WriteLine($"Error: The specified certificate could not be found.");
            }

            return response;
        }
    }

}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeCertificate](https://docs.aws.amazon.com/goto/DotNetSDKV3/acm-2015-12-08/DescribeCertificate)」を参照してください。

### `ListCertificates`
<a name="acm_ListCertificates_csharp_3_topic"></a>

次のコード例は、`ListCertificates` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/ACM#code-examples)での設定と実行の方法を確認してください。

```
using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.CertificateManager;
using Amazon.CertificateManager.Model;

namespace ListCertificates
{
    // The following example retrieves and displays a list of the
    // certificates defined for the default account using the AWS
    // Certificate Manager (ACM) service.
    class ListCertificates
    {
        // Specify your AWS Region (an example Region is shown).

        private static readonly RegionEndpoint ACMRegion = RegionEndpoint.USEast1;
        private static AmazonCertificateManagerClient _client;

        static void Main(string[] args)
        {
            _client = new AmazonCertificateManagerClient(ACMRegion);
            var certificateList = ListCertificatesResponseAsync(client: _client);

            Console.WriteLine("Certificate Summary List\n");

            foreach (var certificate in certificateList.Result.CertificateSummaryList)
            {
                Console.WriteLine($"Certificate Domain: {certificate.DomainName}");
                Console.WriteLine($"Certificate ARN: {certificate.CertificateArn}\n");
            }
        }

        /// <summary>
        /// Retrieves a list of the certificates defined in this Region.
        /// </summary>
        /// <param name="client">The ACM client object passed to the
        /// ListCertificateResAsync method call.</param>
        /// <param name="request"></param>
        /// <returns>The ListCertificatesResponse.</returns>
        static async Task<ListCertificatesResponse> ListCertificatesResponseAsync(
            AmazonCertificateManagerClient client)
        {
            var request = new ListCertificatesRequest();

            var response = await client.ListCertificatesAsync(request);
            return response;
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンスの*「[ListCertificates](https://docs.aws.amazon.com/goto/DotNetSDKV3/acm-2015-12-08/ListCertificates)」を参照してください。

# を使用した API Gateway の例 SDK for .NET
<a name="csharp_3_api-gateway_code_examples"></a>

次のコード例は、API Gateway AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_csharp_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for .NET**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_csharp_3_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for .NET**  
 .NET SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-dotnet-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# を使用した Aurora の例 SDK for .NET
<a name="csharp_3_aurora_code_examples"></a>

次のコード例は、Aurora AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_csharp_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 を使用して AWS SDK for .NET 、Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful .NET バックエンドと対話します。  
+ React ウェブアプリケーションを AWS サービスに統合します。
+ Aurora テーブルの項目を一覧表示、更新、削除します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/AuroraItemTracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# を使用した Auto Scaling の例 SDK for .NET
<a name="csharp_3_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AttachLoadBalancerTargetGroups`
<a name="auto-scaling_AttachLoadBalancerTargetGroups_csharp_3_topic"></a>

次のコード例は、`AttachLoadBalancerTargetGroups` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
    /// The
    /// </summary>
    /// <param name="autoScalingGroupName">The name of the Auto Scaling group.</param>
    /// <param name="targetGroupArn">The Arn for the target group.</param>
    /// <returns>Async task.</returns>
    public async Task AttachLoadBalancerToGroup(string autoScalingGroupName, string targetGroupArn)
    {
        await _amazonAutoScaling.AttachLoadBalancerTargetGroupsAsync(
            new AttachLoadBalancerTargetGroupsRequest()
            {
                AutoScalingGroupName = autoScalingGroupName,
                TargetGroupARNs = new List<string>() { targetGroupArn }
            });
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_csharp_3_topic"></a>

次のコード例は、`DeleteAutoScalingGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。
Auto Scaling グループの最小サイズをゼロに更新し、グループ内のすべてのインスタンスを終了して、グループを削除します。  

```
    /// <summary>
    /// Try to terminate an instance by its Id.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task TryTerminateInstanceById(string instanceId)
    {
        var stopping = false;
        Console.WriteLine($"Stopping {instanceId}...");
        while (!stopping)
        {
            try
            {
                await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(
                    new TerminateInstanceInAutoScalingGroupRequest()
                    {
                        InstanceId = instanceId,
                        ShouldDecrementDesiredCapacity = false
                    });
                stopping = true;
            }
            catch (ScalingActivityInProgressException)
            {
                Console.WriteLine($"Scaling activity in progress for {instanceId}. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress,
    /// waits and retries until the group is successfully deleted.
    /// </summary>
    /// <param name="groupName">The name of the group to try to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TryDeleteGroupByName(string groupName)
    {
        var stopped = false;
        while (!stopped)
        {
            try
            {
                await _amazonAutoScaling.DeleteAutoScalingGroupAsync(
                    new DeleteAutoScalingGroupRequest()
                    {
                        AutoScalingGroupName = groupName
                    });
                stopped = true;
            }
            catch (Exception e)
                when ((e is ScalingActivityInProgressException)
                      || (e is Amazon.AutoScaling.Model.ResourceInUseException))
            {
                Console.WriteLine($"Some instances are still running. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Terminate instances and delete the Auto Scaling group by name.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TerminateAndDeleteAutoScalingGroupWithName(string groupName)
    {
        var describeGroupsResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { groupName }
            });
        if (describeGroupsResponse.AutoScalingGroups.Any())
        {
            // Update the size to 0.
            await _amazonAutoScaling.UpdateAutoScalingGroupAsync(
                new UpdateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    MinSize = 0
                });
            var group = describeGroupsResponse.AutoScalingGroups[0];
            foreach (var instance in group.Instances)
            {
                await TryTerminateInstanceById(instance.InstanceId);
            }

            await TryDeleteGroupByName(groupName);
        }
        else
        {
            Console.WriteLine($"No groups found with name {groupName}.");
        }
    }
```

```
    /// <summary>
    /// Delete an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAutoScalingGroupAsync(
        string groupName)
    {
        var deleteAutoScalingGroupRequest = new DeleteAutoScalingGroupRequest
        {
            AutoScalingGroupName = groupName,
            ForceDelete = true,
        };

        var response = await _amazonAutoScaling.DeleteAutoScalingGroupAsync(deleteAutoScalingGroupRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You successfully deleted {groupName}");
            return true;
        }

        Console.WriteLine($"Couldn't delete {groupName}.");
        return false;
    }
```
+  詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_csharp_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
    static async Task Main(string[] args)
    {
        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();


        // Set up dependency injection for the AWS services.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonIdentityManagementService>()
                    .AddAWSService<IAmazonDynamoDB>()
                    .AddAWSService<IAmazonElasticLoadBalancingV2>()
                    .AddAWSService<IAmazonSimpleSystemsManagement>()
                    .AddAWSService<IAmazonAutoScaling>()
                    .AddAWSService<IAmazonEC2>()
                    .AddTransient<AutoScalerWrapper>()
                    .AddTransient<ElasticLoadBalancerWrapper>()
                    .AddTransient<SmParameterWrapper>()
                    .AddTransient<Recommendations>()
                    .AddSingleton<IConfiguration>(_configuration)
            )
            .Build();

        ServicesSetup(host);
        ResourcesSetup();

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Welcome to the Resilient Architecture Example Scenario.");
            Console.WriteLine(new string('-', 80));
            await Deploy(true);

            Console.WriteLine("Now let's begin the scenario.");
            Console.WriteLine(new string('-', 80));
            await Demo(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Finally, let's clean up our resources.");
            Console.WriteLine(new string('-', 80));

            await DestroyResources(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Resilient Architecture Example Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            await DestroyResources(true);
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Setup any common resources, also used for integration testing.
    /// </summary>
    public static void ResourcesSetup()
    {
        _httpClient = new HttpClient();
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _elasticLoadBalancerWrapper = host.Services.GetRequiredService<ElasticLoadBalancerWrapper>();
        _iamClient = host.Services.GetRequiredService<IAmazonIdentityManagementService>();
        _recommendations = host.Services.GetRequiredService<Recommendations>();
        _autoScalerWrapper = host.Services.GetRequiredService<AutoScalerWrapper>();
        _smParameterWrapper = host.Services.GetRequiredService<SmParameterWrapper>();
    }

    /// <summary>
    /// Deploy necessary resources for the scenario.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> Deploy(bool interactive)
    {
        var protocol = "HTTP";
        var port = 80;
        var sshPort = 22;

        Console.WriteLine(
            "\nFor this demo, we'll use the AWS SDK for .NET to create several AWS resources\n" +
            "to set up a load-balanced web service endpoint and explore some ways to make it resilient\n" +
            "against various kinds of failures.\n\n" +
            "Some of the resources create by this demo are:\n");

        Console.WriteLine(
            "\t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.");
        Console.WriteLine(
            "\t* An EC2 launch template that defines EC2 instances that each contain a Python web server.");
        Console.WriteLine(
            "\t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.");
        Console.WriteLine(
            "\t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.");
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to start deploying resources.");
        if (interactive)
            Console.ReadLine();

        // Create and populate the DynamoDB table.
        var databaseTableName = _configuration["databaseName"];
        var recommendationsPath = Path.Join(_configuration["resourcePath"],
            "recommendations_objects.json");
        Console.WriteLine($"Creating and populating a DynamoDB table named {databaseTableName}.");
        await _recommendations.CreateDatabaseWithName(databaseTableName);
        await _recommendations.PopulateDatabase(databaseTableName, recommendationsPath);
        Console.WriteLine(new string('-', 80));

        // Create the EC2 Launch Template.

        Console.WriteLine(
            $"Creating an EC2 launch template that runs 'server_startup_script.sh' when an instance starts.\n"
            + "\nThis script starts a Python web server defined in the `server.py` script. The web server\n"
            + "listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.\n"
            + "For demo purposes, this server is run as the root user. In production, the best practice is to\n"
            + "run a web server, such as Apache, with least-privileged credentials.");
        Console.WriteLine(
            "\nThe template also defines an IAM policy that each instance uses to assume a role that grants\n"
            + "permissions to access the DynamoDB recommendation table and Systems Manager parameters\n"
            + "that control the flow of the demo.");

        var startupScriptPath = Path.Join(_configuration["resourcePath"],
            "server_startup_script.sh");
        var instancePolicyPath = Path.Join(_configuration["resourcePath"],
            "instance_policy.json");
        await _autoScalerWrapper.CreateTemplate(startupScriptPath, instancePolicyPath);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different\n"
            + "Availability Zone.\n");
        var zones = await _autoScalerWrapper.DescribeAvailabilityZones();
        await _autoScalerWrapper.CreateGroupOfSize(3, _autoScalerWrapper.GroupName, zones);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "At this point, you have EC2 instances created. Once each instance starts, it listens for\n"
            + "HTTP requests. You can see these instances in the console or continue with the demo.\n");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue.");
        if (interactive)
            Console.ReadLine();

        Console.WriteLine("Creating variables that control the flow of the demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine(
            "\nCreating an Elastic Load Balancing target group and load balancer. The target group\n"
            + "defines how the load balancer connects to instances. The load balancer provides a\n"
            + "single endpoint where clients connect and dispatches requests to instances in the group.");

        var defaultVpc = await _autoScalerWrapper.GetDefaultVpc();
        var subnets = await _autoScalerWrapper.GetAllVpcSubnetsForZones(defaultVpc.VpcId, zones);
        var subnetIds = subnets.Select(s => s.SubnetId).ToList();
        var targetGroup = await _elasticLoadBalancerWrapper.CreateTargetGroupOnVpc(_elasticLoadBalancerWrapper.TargetGroupName, protocol, port, defaultVpc.VpcId);

        await _elasticLoadBalancerWrapper.CreateLoadBalancerAndListener(_elasticLoadBalancerWrapper.LoadBalancerName, subnetIds, targetGroup);
        await _autoScalerWrapper.AttachLoadBalancerToGroup(_autoScalerWrapper.GroupName, targetGroup.TargetGroupArn);
        Console.WriteLine("\nVerifying access to the load balancer endpoint...");
        var endPoint = await _elasticLoadBalancerWrapper.GetEndpointForLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
        var loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);

        if (!loadBalancerAccess)
        {
            Console.WriteLine("\nCouldn't connect to the load balancer, verifying that the port is open...");

            var ipString = await _httpClient.GetStringAsync("https://checkip.amazonaws.com");
            ipString = ipString.Trim();

            var defaultSecurityGroup = await _autoScalerWrapper.GetDefaultSecurityGroupForVpc(defaultVpc);
            var portIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, port, ipString);
            var sshPortIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, sshPort, ipString);

            if (!portIsOpen)
            {
                Console.WriteLine(
                    "\nFor this example to work, the default security group for your default VPC must\n"
                    + "allows access from this computer. You can either add it automatically from this\n"
                    + "example or add it yourself using the AWS Management Console.\n");

                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound traffic from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, port, ipString);
                }
            }

            if (!sshPortIsOpen)
            {
                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound SSH traffic for debugging from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, sshPort, ipString);
                }
            }
            loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);
        }

        if (loadBalancerAccess)
        {
            Console.WriteLine("Your load balancer is ready. You can access it by browsing to:");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        else
        {
            Console.WriteLine(
                "\nCouldn't get a successful response from the load balancer endpoint. Troubleshoot by\n"
                + "manually verifying that your VPC and security group are configured correctly and that\n"
                + "you can successfully make a GET request to the load balancer endpoint:\n");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue with the demo.");
        if (interactive)
            Console.ReadLine();
        return true;
    }

    /// <summary>
    /// Demonstrate the steps of the scenario.
    /// </summary>
    /// <param name="interactive">True to run as an interactive scenario.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> Demo(bool interactive)
    {
        var ssmOnlyPolicy = Path.Join(_configuration["resourcePath"],
            "ssm_only_policy.json");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Resetting parameters to starting values for demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine("\nThis part of the demonstration shows how to toggle different parts of the system\n" +
                          "to create situations where the web service fails, and shows how using a resilient\n" +
                          "architecture can keep the web service running in spite of these failures.");
        Console.WriteLine(new string('-', 88));
        Console.WriteLine("At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine($"The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.\n" +
                          $"The table name is contained in a Systems Manager parameter named '{_smParameterWrapper.TableParameter}'.\n" +
                          $"To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");
        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as\n" +
                          "healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Instead of failing when the recommendation service fails, the web service can return a static response.");
        Console.WriteLine("While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.FailureResponseParameter, "static");

        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a static response.");
        Console.WriteLine("The service still reports as healthy because health checks are still shallow.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Let's reinstate the recommendation service.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, _smParameterWrapper.TableName);
        Console.WriteLine(
            "\nLet's also substitute bad credentials for one of the instances in the target group so that it can't\n" +
            "access the DynamoDB recommendation table.\n"
        );
        await _autoScalerWrapper.CreateInstanceProfileWithName(
            _autoScalerWrapper.BadCredsPolicyName,
            _autoScalerWrapper.BadCredsRoleName,
            _autoScalerWrapper.BadCredsProfileName,
            ssmOnlyPolicy,
            new List<string> { "AmazonSSMManagedInstanceCore" }
        );
        var instances = await _autoScalerWrapper.GetInstancesByGroupName(_autoScalerWrapper.GroupName);
        var badInstanceId = instances.First();
        var instanceProfile = await _autoScalerWrapper.GetInstanceProfile(badInstanceId);
        Console.WriteLine(
            $"Replacing the profile for instance {badInstanceId} with a profile that contains\n" +
            "bad credentials...\n"
        );
        await _autoScalerWrapper.ReplaceInstanceProfile(
            badInstanceId,
            _autoScalerWrapper.BadCredsProfileName,
            instanceProfile.AssociationId
        );
        Console.WriteLine(
            "Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,\n" +
            "depending on which instance is selected by the load balancer.\n"
        );
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nLet's implement a deep health check. For this demo, a deep health check tests whether");
        Console.WriteLine("the web service can access the DynamoDB table that it depends on for recommendations. Note that");
        Console.WriteLine("the deep health check is only for ELB routing and not for Auto Scaling instance health.");
        Console.WriteLine("This kind of deep health check is not recommended for Auto Scaling instance health, because it");
        Console.WriteLine("risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.");

        Console.WriteLine("\nBy implementing deep health checks, the load balancer can detect when one of the instances is failing");
        Console.WriteLine("and take that instance out of rotation.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.HealthCheckParameter, "deep");

        Console.WriteLine($"\nNow, checking target health indicates that the instance with bad credentials ({badInstanceId})");
        Console.WriteLine("is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy");
        Console.WriteLine("instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because");
        Console.WriteLine("the load balancer takes unhealthy instances out of its rotation.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nBecause the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy");
        Console.WriteLine("instance is to terminate it and let the auto scaler start a new instance to replace it.");

        await _autoScalerWrapper.TryTerminateInstanceById(badInstanceId);

        Console.WriteLine($"\nEven while the instance is terminating and the new instance is starting, sending a GET");
        Console.WriteLine("request to the web service continues to get a successful recommendation response because");
        Console.WriteLine("starts and reports as healthy, it is included in the load balancing rotation.");
        Console.WriteLine("Note that terminating and replacing an instance typically takes several minutes, during which time you");
        Console.WriteLine("can see the changing health check status until the new instance is running and healthy.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nIf the recommendation service fails now, deep health checks mean all instances report as unhealthy.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");

        Console.WriteLine($"\nWhen all instances are unhealthy, the load balancer continues to route requests even to");
        Console.WriteLine("unhealthy instances, allowing them to fail open and return a static response rather than fail");
        Console.WriteLine("closed and report failure to the customer.");

        if (interactive)
            await DemoActionChoices();
        await _smParameterWrapper.Reset();

        Console.WriteLine(new string('-', 80));
        return true;
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="interactive">True to ask the user for cleanup.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> DestroyResources(bool interactive)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine(
            "To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources\n" +
            "that were created for this demo."
        );

        if (!interactive || GetYesNoResponse("Do you want to clean up all demo resources? (y/n) "))
        {
            await _elasticLoadBalancerWrapper.DeleteLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
            await _elasticLoadBalancerWrapper.DeleteTargetGroupByName(_elasticLoadBalancerWrapper.TargetGroupName);
            await _autoScalerWrapper.TerminateAndDeleteAutoScalingGroupWithName(_autoScalerWrapper.GroupName);
            await _autoScalerWrapper.DeleteKeyPairByName(_autoScalerWrapper.KeyPairName);
            await _autoScalerWrapper.DeleteTemplateByName(_autoScalerWrapper.LaunchTemplateName);
            await _autoScalerWrapper.DeleteInstanceProfile(
                _autoScalerWrapper.BadCredsProfileName,
                _autoScalerWrapper.BadCredsRoleName
            );
            await _recommendations.DestroyDatabaseByName(_recommendations.TableName);
        }
        else
        {
            Console.WriteLine(
                "Ok, we'll leave the resources intact.\n" +
                "Don't forget to delete them when you're done with them or you might incur unexpected charges."
            );
        }

        Console.WriteLine(new string('-', 80));
        return true;
    }
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Amazon EC2 Auto Scaling and EC2 management methods.
/// </summary>
public class AutoScalerWrapper
{
    private readonly IAmazonAutoScaling _amazonAutoScaling;
    private readonly IAmazonEC2 _amazonEc2;
    private readonly IAmazonSimpleSystemsManagement _amazonSsm;
    private readonly IAmazonIdentityManagementService _amazonIam;
    private readonly ILogger<AutoScalerWrapper> _logger;

    private readonly string _instanceType = "";
    private readonly string _amiParam = "";
    private readonly string _launchTemplateName = "";
    private readonly string _groupName = "";
    private readonly string _instancePolicyName = "";
    private readonly string _instanceRoleName = "";
    private readonly string _instanceProfileName = "";
    private readonly string _badCredsProfileName = "";
    private readonly string _badCredsRoleName = "";
    private readonly string _badCredsPolicyName = "";
    private readonly string _keyPairName = "";

    public string GroupName => _groupName;
    public string KeyPairName => _keyPairName;
    public string LaunchTemplateName => _launchTemplateName;
    public string InstancePolicyName => _instancePolicyName;
    public string BadCredsProfileName => _badCredsProfileName;
    public string BadCredsRoleName => _badCredsRoleName;
    public string BadCredsPolicyName => _badCredsPolicyName;

    /// <summary>
    /// Constructor for the AutoScalerWrapper.
    /// </summary>
    /// <param name="amazonAutoScaling">The injected AutoScaling client.</param>
    /// <param name="amazonEc2">The injected EC2 client.</param>
    /// <param name="amazonIam">The injected IAM client.</param>
    /// <param name="amazonSsm">The injected SSM client.</param>
    public AutoScalerWrapper(
        IAmazonAutoScaling amazonAutoScaling,
        IAmazonEC2 amazonEc2,
        IAmazonSimpleSystemsManagement amazonSsm,
        IAmazonIdentityManagementService amazonIam,
        IConfiguration configuration,
        ILogger<AutoScalerWrapper> logger)
    {
        _amazonAutoScaling = amazonAutoScaling;
        _amazonEc2 = amazonEc2;
        _amazonSsm = amazonSsm;
        _amazonIam = amazonIam;
        _logger = logger;

        var prefix = configuration["resourcePrefix"];
        _instanceType = configuration["instanceType"];
        _amiParam = configuration["amiParam"];

        _launchTemplateName = prefix + "-template";
        _groupName = prefix + "-group";
        _instancePolicyName = prefix + "-pol";
        _instanceRoleName = prefix + "-role";
        _instanceProfileName = prefix + "-prof";
        _badCredsPolicyName = prefix + "-bc-pol";
        _badCredsRoleName = prefix + "-bc-role";
        _badCredsProfileName = prefix + "-bc-prof";
        _keyPairName = prefix + "-key-pair";
    }

    /// <summary>
    /// Create a policy, role, and profile that is associated with instances with a specified name.
    /// An instance's associated profile defines a role that is assumed by the
    /// instance.The role has attached policies that specify the AWS permissions granted to
    /// clients that run on the instance.
    /// </summary>
    /// <param name="policyName">Name to use for the policy.</param>
    /// <param name="roleName">Name to use for the role.</param>
    /// <param name="profileName">Name to use for the profile.</param>
    /// <param name="ssmOnlyPolicyFile">Path to a policy file for SSM.</param>
    /// <param name="awsManagedPolicies">AWS Managed policies to be attached to the role.</param>
    /// <returns>The Arn of the profile.</returns>
    public async Task<string> CreateInstanceProfileWithName(
        string policyName,
        string roleName,
        string profileName,
        string ssmOnlyPolicyFile,
        List<string>? awsManagedPolicies = null)
    {

        var assumeRoleDoc = "{" +
                                   "\"Version\": \"2012-10-17\"," +
                                   "\"Statement\": [{" +
                                        "\"Effect\": \"Allow\"," +
                                        "\"Principal\": {" +
                                        "\"Service\": [" +
                                            "\"ec2.amazonaws.com\"" +
                                        "]" +
                                        "}," +
                                   "\"Action\": \"sts:AssumeRole\"" +
                                   "}]" +
                               "}";

        var policyDocument = await File.ReadAllTextAsync(ssmOnlyPolicyFile);

        var policyArn = "";

        try
        {
            var createPolicyResult = await _amazonIam.CreatePolicyAsync(
                new CreatePolicyRequest
                {
                    PolicyName = policyName,
                    PolicyDocument = policyDocument
                });
            policyArn = createPolicyResult.Policy.Arn;
        }
        catch (EntityAlreadyExistsException)
        {
            // The policy already exists, so we look it up to get the Arn.
            var policiesPaginator = _amazonIam.Paginators.ListPolicies(
                new ListPoliciesRequest()
                {
                    Scope = PolicyScopeType.Local
                });
            // Get the entire list using the paginator.
            await foreach (var policy in policiesPaginator.Policies)
            {
                if (policy.PolicyName.Equals(policyName))
                {
                    policyArn = policy.Arn;
                }
            }

            if (policyArn == null)
            {
                throw new InvalidOperationException("Policy not found");
            }
        }

        try
        {
            await _amazonIam.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = assumeRoleDoc,
            });
            await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
            {
                RoleName = roleName,
                PolicyArn = policyArn
            });
            if (awsManagedPolicies != null)
            {
                foreach (var awsPolicy in awsManagedPolicies)
                {
                    await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
                    {
                        PolicyArn = $"arn:aws:iam::aws:policy/{awsPolicy}",
                        RoleName = roleName
                    });
                }
            }
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Role already exists.");
        }

        string profileArn = "";
        try
        {
            var profileCreateResponse = await _amazonIam.CreateInstanceProfileAsync(
                new CreateInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            // Allow time for the profile to be ready.
            profileArn = profileCreateResponse.InstanceProfile.Arn;
            Thread.Sleep(10000);
            await _amazonIam.AddRoleToInstanceProfileAsync(
                new AddRoleToInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });

        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Policy already exists.");
            var profileGetResponse = await _amazonIam.GetInstanceProfileAsync(
                new GetInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            profileArn = profileGetResponse.InstanceProfile.Arn;
        }
        return profileArn;
    }

    /// <summary>
    /// Create a new key pair and save the file.
    /// </summary>
    /// <param name="newKeyPairName">The name of the new key pair.</param>
    /// <returns>Async task.</returns>
    public async Task CreateKeyPair(string newKeyPairName)
    {
        try
        {
            var keyResponse = await _amazonEc2.CreateKeyPairAsync(
                new CreateKeyPairRequest() { KeyName = newKeyPairName });
            await File.WriteAllTextAsync($"{newKeyPairName}.pem",
                keyResponse.KeyPair.KeyMaterial);
            Console.WriteLine($"Created key pair {newKeyPairName}.");
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine("Key pair already exists.");
        }
    }

    /// <summary>
    /// Delete the key pair and file by name.
    /// </summary>
    /// <param name="deleteKeyPairName">The key pair to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteKeyPairByName(string deleteKeyPairName)
    {
        try
        {
            await _amazonEc2.DeleteKeyPairAsync(
                new DeleteKeyPairRequest() { KeyName = deleteKeyPairName });
            File.Delete($"{deleteKeyPairName}.pem");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"Key pair {deleteKeyPairName} not found.");
        }
    }

    /// <summary>
    /// Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling.
    /// The launch template specifies a Bash script in its user data field that runs after
    /// the instance is started. This script installs the Python packages and starts a Python
    /// web server on the instance.
    /// </summary>
    /// <param name="startupScriptPath">The path to a Bash script file that is run.</param>
    /// <param name="instancePolicyPath">The path to a permissions policy to create and attach to the profile.</param>
    /// <returns>The template object.</returns>
    public async Task<Amazon.EC2.Model.LaunchTemplate> CreateTemplate(string startupScriptPath, string instancePolicyPath)
    {
        try
        {
            await CreateKeyPair(_keyPairName);
            await CreateInstanceProfileWithName(_instancePolicyName, _instanceRoleName,
                _instanceProfileName, instancePolicyPath);

            var startServerText = await File.ReadAllTextAsync(startupScriptPath);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(startServerText);

            var amiLatest = await _amazonSsm.GetParameterAsync(
                new GetParameterRequest() { Name = _amiParam });
            var amiId = amiLatest.Parameter.Value;
            var launchTemplateResponse = await _amazonEc2.CreateLaunchTemplateAsync(
                new CreateLaunchTemplateRequest()
                {
                    LaunchTemplateName = _launchTemplateName,
                    LaunchTemplateData = new RequestLaunchTemplateData()
                    {
                        InstanceType = _instanceType,
                        ImageId = amiId,
                        IamInstanceProfile =
                            new
                                LaunchTemplateIamInstanceProfileSpecificationRequest()
                            {
                                Name = _instanceProfileName
                            },
                        KeyName = _keyPairName,
                        UserData = System.Convert.ToBase64String(plainTextBytes)
                    }
                });
            return launchTemplateResponse.LaunchTemplate;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.AlreadyExistsException")
            {
                _logger.LogError($"Could not create the template, the name {_launchTemplateName} already exists. " +
                                 $"Please try again with a unique name.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get a list of Availability Zones in the AWS Region of the Amazon EC2 Client.
    /// </summary>
    /// <returns>A list of availability zones.</returns>
    public async Task<List<string>> DescribeAvailabilityZones()
    {
        try
        {
            var zoneResponse = await _amazonEc2.DescribeAvailabilityZonesAsync(
                new DescribeAvailabilityZonesRequest());
            return zoneResponse.AvailabilityZones.Select(z => z.ZoneName).ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            _logger.LogError($"An Amazon EC2 error occurred while listing availability zones.: {ec2Exception.Message}");
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while listing availability zones.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Create an EC2 Auto Scaling group of a specified size and name.
    /// </summary>
    /// <param name="groupSize">The size for the group.</param>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="availabilityZones">The availability zones for the group.</param>
    /// <returns>Async task.</returns>
    public async Task CreateGroupOfSize(int groupSize, string groupName, List<string> availabilityZones)
    {
        try
        {
            await _amazonAutoScaling.CreateAutoScalingGroupAsync(
                new CreateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    AvailabilityZones = availabilityZones,
                    LaunchTemplate =
                        new Amazon.AutoScaling.Model.LaunchTemplateSpecification()
                        {
                            LaunchTemplateName = _launchTemplateName,
                            Version = "$Default"
                        },
                    MaxSize = groupSize,
                    MinSize = groupSize
                });
            Console.WriteLine($"Created EC2 Auto Scaling group {groupName} with size {groupSize}.");
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine($"EC2 Auto Scaling group {groupName} already exists.");
        }
    }

    /// <summary>
    /// Get the default VPC for the account.
    /// </summary>
    /// <returns>The default VPC object.</returns>
    public async Task<Vpc> GetDefaultVpc()
    {
        try
        {
            var vpcResponse = await _amazonEc2.DescribeVpcsAsync(
                new DescribeVpcsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("is-default", new List<string>() { "true" })
                    }
                });
            return vpcResponse.Vpcs[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "UnauthorizedOperation")
            {
                _logger.LogError(ec2Exception, $"You do not have the necessary permissions to describe VPCs.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the vpcs.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get all the subnets for a Vpc in a set of availability zones.
    /// </summary>
    /// <param name="vpcId">The Id of the Vpc.</param>
    /// <param name="availabilityZones">The list of availability zones.</param>
    /// <returns>The collection of subnet objects.</returns>
    public async Task<List<Subnet>> GetAllVpcSubnetsForZones(string vpcId, List<string> availabilityZones)
    {
        try
        {
            var subnets = new List<Subnet>();
            var subnetPaginator = _amazonEc2.Paginators.DescribeSubnets(
                new DescribeSubnetsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("vpc-id", new List<string>() { vpcId }),
                        new("availability-zone", availabilityZones),
                        new("default-for-az", new List<string>() { "true" })
                    }
                });

            // Get the entire list using the paginator.
            await foreach (var subnet in subnetPaginator.Subnets)
            {
                subnets.Add(subnet);
            }

            return subnets;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidVpcID.NotFound")
            {
                _logger.LogError(ec2Exception, $"The specified VPC ID {vpcId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the subnets.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Delete a launch template by name.
    /// </summary>
    /// <param name="templateName">The name of the template to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTemplateByName(string templateName)
    {
        try
        {
            await _amazonEc2.DeleteLaunchTemplateAsync(
                new DeleteLaunchTemplateRequest()
                {
                    LaunchTemplateName = templateName
                });
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.NotFoundException")
            {
                _logger.LogError(
                    $"Could not delete the template, the name {_launchTemplateName} was not found.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while deleting the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Detaches a role from an instance profile, detaches policies from the role,
    /// and deletes all the resources.
    /// </summary>
    /// <param name="profileName">The name of the profile to delete.</param>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteInstanceProfile(string profileName, string roleName)
    {
        try
        {
            await _amazonIam.RemoveRoleFromInstanceProfileAsync(
                new RemoveRoleFromInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });
            await _amazonIam.DeleteInstanceProfileAsync(
                new DeleteInstanceProfileRequest() { InstanceProfileName = profileName });
            var attachedPolicies = await _amazonIam.ListAttachedRolePoliciesAsync(
                new ListAttachedRolePoliciesRequest() { RoleName = roleName });
            foreach (var policy in attachedPolicies.AttachedPolicies)
            {
                await _amazonIam.DetachRolePolicyAsync(
                    new DetachRolePolicyRequest()
                    {
                        RoleName = roleName,
                        PolicyArn = policy.PolicyArn
                    });
                // Delete the custom policies only.
                if (!policy.PolicyArn.StartsWith("arn:aws:iam::aws"))
                {
                    await _amazonIam.DeletePolicyAsync(
                        new Amazon.IdentityManagement.Model.DeletePolicyRequest()
                        {
                            PolicyArn = policy.PolicyArn
                        });
                }
            }

            await _amazonIam.DeleteRoleAsync(
                new DeleteRoleRequest() { RoleName = roleName });
        }
        catch (NoSuchEntityException)
        {
            Console.WriteLine($"Instance profile {profileName} does not exist.");
        }
    }

    /// <summary>
    /// Gets data about the instances in an EC2 Auto Scaling group by its group name.
    /// </summary>
    /// <param name="group">The name of the auto scaling group.</param>
    /// <returns>A collection of instance Ids.</returns>
    public async Task<IEnumerable<string>> GetInstancesByGroupName(string group)
    {
        var instanceResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { group }
            });
        var instanceIds = instanceResponse.AutoScalingGroups.SelectMany(
            g => g.Instances.Select(i => i.InstanceId));
        return instanceIds;
    }

    /// <summary>
    /// Get the instance profile association data for an instance.
    /// </summary>
    /// <param name="instanceId">The Id of the instance.</param>
    /// <returns>Instance profile associations data.</returns>
    public async Task<IamInstanceProfileAssociation> GetInstanceProfile(string instanceId)
    {
        try
        {
            var response = await _amazonEc2.DescribeIamInstanceProfileAssociationsAsync(
                new DescribeIamInstanceProfileAssociationsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("instance-id", new List<string>() { instanceId })
                    },
                });
            return response.IamInstanceProfileAssociations[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Try to terminate an instance by its Id.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task TryTerminateInstanceById(string instanceId)
    {
        var stopping = false;
        Console.WriteLine($"Stopping {instanceId}...");
        while (!stopping)
        {
            try
            {
                await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(
                    new TerminateInstanceInAutoScalingGroupRequest()
                    {
                        InstanceId = instanceId,
                        ShouldDecrementDesiredCapacity = false
                    });
                stopping = true;
            }
            catch (ScalingActivityInProgressException)
            {
                Console.WriteLine($"Scaling activity in progress for {instanceId}. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress,
    /// waits and retries until the group is successfully deleted.
    /// </summary>
    /// <param name="groupName">The name of the group to try to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TryDeleteGroupByName(string groupName)
    {
        var stopped = false;
        while (!stopped)
        {
            try
            {
                await _amazonAutoScaling.DeleteAutoScalingGroupAsync(
                    new DeleteAutoScalingGroupRequest()
                    {
                        AutoScalingGroupName = groupName
                    });
                stopped = true;
            }
            catch (Exception e)
                when ((e is ScalingActivityInProgressException)
                      || (e is Amazon.AutoScaling.Model.ResourceInUseException))
            {
                Console.WriteLine($"Some instances are still running. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Terminate instances and delete the Auto Scaling group by name.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TerminateAndDeleteAutoScalingGroupWithName(string groupName)
    {
        var describeGroupsResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { groupName }
            });
        if (describeGroupsResponse.AutoScalingGroups.Any())
        {
            // Update the size to 0.
            await _amazonAutoScaling.UpdateAutoScalingGroupAsync(
                new UpdateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    MinSize = 0
                });
            var group = describeGroupsResponse.AutoScalingGroups[0];
            foreach (var instance in group.Instances)
            {
                await TryTerminateInstanceById(instance.InstanceId);
            }

            await TryDeleteGroupByName(groupName);
        }
        else
        {
            Console.WriteLine($"No groups found with name {groupName}.");
        }
    }


    /// <summary>
    /// Get the default security group for a specified Vpc.
    /// </summary>
    /// <param name="vpc">The Vpc to search.</param>
    /// <returns>The default security group.</returns>
    public async Task<SecurityGroup> GetDefaultSecurityGroupForVpc(Vpc vpc)
    {
        var groupResponse = await _amazonEc2.DescribeSecurityGroupsAsync(
            new DescribeSecurityGroupsRequest()
            {
                Filters = new List<Amazon.EC2.Model.Filter>()
                {
                    new ("group-name", new List<string>() { "default" }),
                    new ("vpc-id", new List<string>() { vpc.VpcId })
                }
            });
        return groupResponse.SecurityGroups[0];
    }

    /// <summary>
    /// Verify the default security group of a Vpc allows ingress from the calling computer.
    /// This can be done by allowing ingress from this computer's IP address.
    /// In some situations, such as connecting from a corporate network, you must instead specify
    /// a prefix list Id. You can also temporarily open the port to any IP address while running this example.
    /// If you do, be sure to remove public access when you're done.
    /// </summary>
    /// <param name="vpc">The group to check.</param>
    /// <param name="port">The port to verify.</param>
    /// <param name="ipAddress">This computer's IP address.</param>
    /// <returns>True if the ip address is allowed on the group.</returns>
    public bool VerifyInboundPortForGroup(SecurityGroup group, int port, string ipAddress)
    {
        var portIsOpen = false;
        foreach (var ipPermission in group.IpPermissions)
        {
            if (ipPermission.FromPort == port)
            {
                foreach (var ipRange in ipPermission.Ipv4Ranges)
                {
                    var cidr = ipRange.CidrIp;
                    if (cidr.StartsWith(ipAddress) || cidr == "0.0.0.0/0")
                    {
                        portIsOpen = true;
                    }
                }

                if (ipPermission.PrefixListIds.Any())
                {
                    portIsOpen = true;
                }

                if (!portIsOpen)
                {
                    Console.WriteLine("The inbound rule does not appear to be open to either this computer's IP\n" +
                                      "address, to all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                }
                else
                {
                    break;
                }
            }
        }

        return portIsOpen;
    }

    /// <summary>
    /// Add an ingress rule to the specified security group that allows access on the
    /// specified port from the specified IP address.
    /// </summary>
    /// <param name="groupId">The Id of the security group to modify.</param>
    /// <param name="port">The port to open.</param>
    /// <param name="ipAddress">The IP address to allow access.</param>
    /// <returns>Async task.</returns>
    public async Task OpenInboundPort(string groupId, int port, string ipAddress)
    {
        await _amazonEc2.AuthorizeSecurityGroupIngressAsync(
            new AuthorizeSecurityGroupIngressRequest()
            {
                GroupId = groupId,
                IpPermissions = new List<IpPermission>()
                {
                    new IpPermission()
                    {
                        FromPort = port,
                        ToPort = port,
                        IpProtocol = "tcp",
                        Ipv4Ranges = new List<IpRange>()
                        {
                            new IpRange() { CidrIp = $"{ipAddress}/32" }
                        }
                    }
                }
            });
    }

    /// <summary>
    /// Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
    /// The
    /// </summary>
    /// <param name="autoScalingGroupName">The name of the Auto Scaling group.</param>
    /// <param name="targetGroupArn">The Arn for the target group.</param>
    /// <returns>Async task.</returns>
    public async Task AttachLoadBalancerToGroup(string autoScalingGroupName, string targetGroupArn)
    {
        await _amazonAutoScaling.AttachLoadBalancerTargetGroupsAsync(
            new AttachLoadBalancerTargetGroupsRequest()
            {
                AutoScalingGroupName = autoScalingGroupName,
                TargetGroupARNs = new List<string>() { targetGroupArn }
            });
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEc2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Elastic Load Balancer actions.
/// </summary>
public class ElasticLoadBalancerWrapper
{
    private readonly IAmazonElasticLoadBalancingV2 _amazonElasticLoadBalancingV2;
    private string? _endpoint = null;
    private readonly string _targetGroupName = "";
    private readonly string _loadBalancerName = "";
    HttpClient _httpClient = new();

    public string TargetGroupName => _targetGroupName;
    public string LoadBalancerName => _loadBalancerName;

    /// <summary>
    /// Constructor for the Elastic Load Balancer wrapper.
    /// </summary>
    /// <param name="amazonElasticLoadBalancingV2">The injected load balancing v2 client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public ElasticLoadBalancerWrapper(
        IAmazonElasticLoadBalancingV2 amazonElasticLoadBalancingV2,
        IConfiguration configuration)
    {
        _amazonElasticLoadBalancingV2 = amazonElasticLoadBalancingV2;
        var prefix = configuration["resourcePrefix"];
        _targetGroupName = prefix + "-tg";
        _loadBalancerName = prefix + "-lb";
    }

    /// <summary>
    /// Get the HTTP Endpoint of a load balancer by its name.
    /// </summary>
    /// <param name="loadBalancerName">The name of the load balancer.</param>
    /// <returns>The HTTP endpoint.</returns>
    public async Task<string> GetEndpointForLoadBalancerByName(string loadBalancerName)
    {
        if (_endpoint == null)
        {
            var endpointResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { loadBalancerName }
                    });
            _endpoint = endpointResponse.LoadBalancers[0].DNSName;
        }

        return _endpoint;
    }

    /// <summary>
    /// Return the GET response for an endpoint as text.
    /// </summary>
    /// <param name="endpoint">The endpoint for the request.</param>
    /// <returns>The request response.</returns>
    public async Task<string> GetEndPointResponse(string endpoint)
    {
        var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
        var textResponse = await endpointResponse.Content.ReadAsStringAsync();
        return textResponse!;
    }

    /// <summary>
    /// Get the target health for a group by name.
    /// </summary>
    /// <param name="groupName">The name of the group.</param>
    /// <returns>The collection of health descriptions.</returns>
    public async Task<List<TargetHealthDescription>> CheckTargetHealthForGroup(string groupName)
    {
        List<TargetHealthDescription> result = null!;
        try
        {
            var groupResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                    new DescribeTargetGroupsRequest()
                    {
                        Names = new List<string>() { groupName }
                    });
            var healthResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetHealthAsync(
                    new DescribeTargetHealthRequest()
                    {
                        TargetGroupArn = groupResponse.TargetGroups[0].TargetGroupArn
                    });
            ;
            result = healthResponse.TargetHealthDescriptions;
        }
        catch (TargetGroupNotFoundException)
        {
            Console.WriteLine($"Target group {groupName} not found.");
        }
        return result;
    }

    /// <summary>
    /// Create an Elastic Load Balancing target group. The target group specifies how the load balancer forwards
    /// requests to instances in the group and how instance health is checked.
    ///
    /// To speed up this demo, the health check is configured with shortened times and lower thresholds. In production,
    /// you might want to decrease the sensitivity of your health checks to avoid unwanted failures.
    /// </summary>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="protocol">The protocol, such as HTTP.</param>
    /// <param name="port">The port to use to forward requests, such as 80.</param>
    /// <param name="vpcId">The Id of the Vpc in which the load balancer exists.</param>
    /// <returns>The new TargetGroup object.</returns>
    public async Task<TargetGroup> CreateTargetGroupOnVpc(string groupName, ProtocolEnum protocol, int port, string vpcId)
    {
        var createResponse = await _amazonElasticLoadBalancingV2.CreateTargetGroupAsync(
            new CreateTargetGroupRequest()
            {
                Name = groupName,
                Protocol = protocol,
                Port = port,
                HealthCheckPath = "/healthcheck",
                HealthCheckIntervalSeconds = 10,
                HealthCheckTimeoutSeconds = 5,
                HealthyThresholdCount = 2,
                UnhealthyThresholdCount = 2,
                VpcId = vpcId
            });
        var targetGroup = createResponse.TargetGroups[0];
        return targetGroup;
    }

    /// <summary>
    /// Create an Elastic Load Balancing load balancer that uses the specified subnets
    /// and forwards requests to the specified target group.
    /// </summary>
    /// <param name="name">The name for the new load balancer.</param>
    /// <param name="subnetIds">Subnets for the load balancer.</param>
    /// <param name="targetGroup">Target group for forwarded requests.</param>
    /// <returns>The new LoadBalancer object.</returns>
    public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup)
    {
        var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync(
            new CreateLoadBalancerRequest()
            {
                Name = name,
                Subnets = subnetIds
            });
        var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn;

        // Wait for load balancer to be available.
        var loadBalancerReady = false;
        while (!loadBalancerReady)
        {
            try
            {
                var describeResponse =
                    await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                        new DescribeLoadBalancersRequest()
                        {
                            Names = new List<string>() { name }
                        });

                var loadBalancerState = describeResponse.LoadBalancers[0].State.Code;

                loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active;
            }
            catch (LoadBalancerNotFoundException)
            {
                loadBalancerReady = false;
            }
            Thread.Sleep(10000);
        }
        // Create the listener.
        await _amazonElasticLoadBalancingV2.CreateListenerAsync(
            new CreateListenerRequest()
            {
                LoadBalancerArn = loadBalancerArn,
                Protocol = targetGroup.Protocol,
                Port = targetGroup.Port,
                DefaultActions = new List<Action>()
                {
                    new Action()
                    {
                        Type = ActionTypeEnum.Forward,
                        TargetGroupArn = targetGroup.TargetGroupArn
                    }
                }
            });
        return createLbResponse.LoadBalancers[0];
    }

    /// <summary>
    /// Verify this computer can successfully send a GET request to the
    /// load balancer endpoint.
    /// </summary>
    /// <param name="endpoint">The endpoint to check.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> VerifyLoadBalancerEndpoint(string endpoint)
    {
        var success = false;
        var retries = 3;
        while (!success && retries > 0)
        {
            try
            {
                var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
                Console.WriteLine($"Response: {endpointResponse.StatusCode}.");

                if (endpointResponse.IsSuccessStatusCode)
                {
                    success = true;
                }
                else
                {
                    retries = 0;
                }
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Connection error, retrying...");
                retries--;
                Thread.Sleep(10000);
            }
        }

        return success;
    }

    /// <summary>
    /// Delete a load balancer by its specified name.
    /// </summary>
    /// <param name="name">The name of the load balancer to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteLoadBalancerByName(string name)
    {
        try
        {
            var describeLoadBalancerResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { name }
                    });
            var lbArn = describeLoadBalancerResponse.LoadBalancers[0].LoadBalancerArn;
            await _amazonElasticLoadBalancingV2.DeleteLoadBalancerAsync(
                new DeleteLoadBalancerRequest()
                {
                    LoadBalancerArn = lbArn
                }
            );
        }
        catch (LoadBalancerNotFoundException)
        {
            Console.WriteLine($"Load balancer {name} not found.");
        }
    }

    /// <summary>
    /// Delete a TargetGroup by its specified name.
    /// </summary>
    /// <param name="groupName">Name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTargetGroupByName(string groupName)
    {
        var done = false;
        while (!done)
        {
            try
            {
                var groupResponse =
                    await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                        new DescribeTargetGroupsRequest()
                        {
                            Names = new List<string>() { groupName }
                        });

                var targetArn = groupResponse.TargetGroups[0].TargetGroupArn;
                await _amazonElasticLoadBalancingV2.DeleteTargetGroupAsync(
                    new DeleteTargetGroupRequest() { TargetGroupArn = targetArn });
                Console.WriteLine($"Deleted load balancing target group {groupName}.");
                done = true;
            }
            catch (TargetGroupNotFoundException)
            {
                Console.WriteLine(
                    $"Target group {groupName} not found, could not delete.");
                done = true;
            }
            catch (ResourceInUseException)
            {
                Console.WriteLine("Target group not yet released, waiting...");
                Thread.Sleep(10000);
            }
        }
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
/// <summary>
/// Encapsulates a DynamoDB table to use as a service that recommends books, movies, and songs.
/// </summary>
public class Recommendations
{
    private readonly IAmazonDynamoDB _amazonDynamoDb;
    private readonly DynamoDBContext _context;
    private readonly string _tableName;

    public string TableName => _tableName;

    /// <summary>
    /// Constructor for the Recommendations service.
    /// </summary>
    /// <param name="amazonDynamoDb">The injected DynamoDb client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public Recommendations(IAmazonDynamoDB amazonDynamoDb, IConfiguration configuration)
    {
        _amazonDynamoDb = amazonDynamoDb;
        _context = new DynamoDBContext(_amazonDynamoDb);
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Create the DynamoDb table with a specified name.
    /// </summary>
    /// <param name="tableName">The name for the table.</param>
    /// <returns>True when ready.</returns>
    public async Task<bool> CreateDatabaseWithName(string tableName)
    {
        try
        {
            Console.Write($"Creating table {tableName}...");
            var createRequest = new CreateTableRequest()
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                    {
                        new AttributeDefinition()
                        {
                            AttributeName = "MediaType",
                            AttributeType = ScalarAttributeType.S
                        },
                        new AttributeDefinition()
                        {
                            AttributeName = "ItemId",
                            AttributeType = ScalarAttributeType.N
                        }
                    },
                KeySchema = new List<KeySchemaElement>()
                    {
                        new KeySchemaElement()
                        {
                            AttributeName = "MediaType",
                            KeyType = KeyType.HASH
                        },
                        new KeySchemaElement()
                        {
                            AttributeName = "ItemId",
                            KeyType = KeyType.RANGE
                        }
                    },
                ProvisionedThroughput = new ProvisionedThroughput()
                {
                    ReadCapacityUnits = 5,
                    WriteCapacityUnits = 5
                }
            };
            await _amazonDynamoDb.CreateTableAsync(createRequest);

            // Wait until the table is ACTIVE and then report success.
            Console.Write("\nWaiting for table to become active...");

            var request = new DescribeTableRequest
            {
                TableName = tableName
            };

            TableStatus status;
            do
            {
                Thread.Sleep(2000);

                var describeTableResponse = await _amazonDynamoDb.DescribeTableAsync(request);
                status = describeTableResponse.Table.TableStatus;

                Console.Write(".");
            }
            while (status != "ACTIVE");

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException)
        {
            Console.WriteLine($"Table {tableName} already exists.");
            return false;
        }
    }

    /// <summary>
    /// Populate the database table with data from a specified path.
    /// </summary>
    /// <param name="databaseTableName">The name of the table.</param>
    /// <param name="recommendationsPath">The path of the recommendations data.</param>
    /// <returns>Async task.</returns>
    public async Task PopulateDatabase(string databaseTableName, string recommendationsPath)
    {
        var recommendationsText = await File.ReadAllTextAsync(recommendationsPath);
        var records =
            JsonSerializer.Deserialize<RecommendationModel[]>(recommendationsText);
        var batchWrite = _context.CreateBatchWrite<RecommendationModel>();

        foreach (var record in records!)
        {
            batchWrite.AddPutItem(record);
        }

        await batchWrite.ExecuteAsync();
    }

    /// <summary>
    /// Delete the recommendation table by name.
    /// </summary>
    /// <param name="tableName">The name of the recommendation table.</param>
    /// <returns>Async task.</returns>
    public async Task DestroyDatabaseByName(string tableName)
    {
        try
        {
            await _amazonDynamoDb.DeleteTableAsync(
                new DeleteTableRequest() { TableName = tableName });
            Console.WriteLine($"Table {tableName} was deleted.");
        }
        catch (ResourceNotFoundException)
        {
            Console.WriteLine($"Table {tableName} not found");
        }
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Systems Manager parameter operations. This example uses these parameters
/// to drive the demonstration of resilient architecture, such as failure of a dependency or
/// how the service responds to a health check.
/// </summary>
public class SmParameterWrapper
{
    private readonly IAmazonSimpleSystemsManagement _amazonSimpleSystemsManagement;

    private readonly string _tableParameter = "doc-example-resilient-architecture-table";
    private readonly string _failureResponseParameter = "doc-example-resilient-architecture-failure-response";
    private readonly string _healthCheckParameter = "doc-example-resilient-architecture-health-check";
    private readonly string _tableName = "";

    public string TableParameter => _tableParameter;
    public string TableName => _tableName;
    public string HealthCheckParameter => _healthCheckParameter;
    public string FailureResponseParameter => _failureResponseParameter;

    /// <summary>
    /// Constructor for the SmParameterWrapper.
    /// </summary>
    /// <param name="amazonSimpleSystemsManagement">The injected Simple Systems Management client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public SmParameterWrapper(IAmazonSimpleSystemsManagement amazonSimpleSystemsManagement, IConfiguration configuration)
    {
        _amazonSimpleSystemsManagement = amazonSimpleSystemsManagement;
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Reset the Systems Manager parameters to starting values for the demo.
    /// </summary>
    /// <returns>Async task.</returns>
    public async Task Reset()
    {
        await this.PutParameterByName(_tableParameter, _tableName);
        await this.PutParameterByName(_failureResponseParameter, "none");
        await this.PutParameterByName(_healthCheckParameter, "shallow");
    }

    /// <summary>
    /// Set the value of a named Systems Manager parameter.
    /// </summary>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="value">The value to set.</param>
    /// <returns>Async task.</returns>
    public async Task PutParameterByName(string name, string value)
    {
        await _amazonSimpleSystemsManagement.PutParameterAsync(
            new PutParameterRequest() { Name = name, Value = value, Overwrite = true });
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# を使用した Amazon Bedrock ランタイムの例 SDK for .NET
<a name="csharp_3_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイム AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)
+ [Amazon Nova](#amazon_nova)
+ [Amazon Nova Canvas](#amazon_nova_canvas)
+ [Anthropic Claude](#anthropic_claude)
+ [Cohere Command](#cohere_command)
+ [Meta Llama](#meta_llama)
+ [Mistral AI](#mistral_ai)

## シナリオ
<a name="scenarios"></a>

### Amazon Bedrock 基盤モデルとやりとりするためのプレイグラウンドアプリケーションを作成します。
<a name="cross_FMPlayground_csharp_3_topic"></a>

次のコード例は、さまざまな方法で Amazon Bedrock 基盤モデルと相互作用するプレイグラウンドを作成する方法を示しています。

**SDK for .NET**  
 .NET 基盤モデル (FM) プレイグラウンドは、C\$1 コードから Amazon Bedrock を使用する方法を紹介する.NET MAUI Blazor サンプルアプリケーションです。この例は、.NET 開発者と C\$1 開発者が Amazon Bedrock を使用して生成 AI 対応アプリケーションを構築する方法を示しています。次の 4 つのプレイグラウンドを使用して Amazon Bedrock 基盤モデルをテストしたり操作したりできます。  
+ テキストプレイグラウンド。
+ チャットプレイグラウンド。
+ ボイスチャットプレイグラウンド。
+ イメージプレイグラウンド。
この例には、アクセスできる基盤モデルとその特性も一覧表示されています。ソースコードとデプロイ手順については、[GitHub](https://github.com/build-on-aws/dotnet-fm-playground) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock ランタイム

### Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUse_csharp_3_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario#code-examples)での設定と実行の方法を確認してください。
シナリオフローのプライマリ実行。このシナリオはユーザー、Amazon Bedrock Converse API、気象ツールの間の会話を調整します。  

```
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;
using Amazon.Runtime.Documents;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;

namespace ConverseToolScenario;

public static class ConverseToolScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
    The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user
    input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.
   */

    public static BedrockActionsWrapper _bedrockActionsWrapper = null!;
    public static WeatherTool _weatherTool = null!;
    public static bool _interactive = true;

    // Change this string to use a different model with Converse API.
    private static string model_id = "amazon.nova-lite-v1:0";

    private static string system_prompt = @"
        You are a weather assistant that provides current weather data for user-specified locations using only
        the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
        If the user specifies a state, country, or region, infer the locations of cities within that state.
        If the user provides coordinates, infer the approximate location and refer to it in your response.
        To use the tool, you strictly apply the provided tool specification.

        - Explain your step-by-step process, and give brief updates before each step.
        - Only use the Weather_Tool for data. Never guess or make up information. 
        - Repeat the tool use for subsequent requests if necessary.
        - If the tool errors, apologize, explain weather is unavailable, and suggest other options.
        - Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
          emojis where appropriate.
        - Only respond to weather queries. Remind off-topic users of your purpose. 
        - Never claim to search online, access external data, or use tools besides Weather_Tool.
        - Complete the entire process until you have all required data before sending the complete response.
    "
    ;

    private static string default_prompt = "What is the weather like in Seattle?";

    // The maximum number of recursive calls allowed in the tool use function.
    // This helps prevent infinite loops and potential performance issues.
    private static int max_recursions = 5;

    public static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Error)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddHttpClient()
                    .AddSingleton<IAmazonBedrockRuntime>(_ => new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1)) // Specify a region that has access to the chosen model.
                    .AddTransient<BedrockActionsWrapper>()
                    .AddTransient<WeatherTool>()
                    .RemoveAll<IHttpMessageHandlerBuilderFilter>()
            )
            .Build();

        ServicesSetup(host);

        try
        {
            await RunConversationAsync();

        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            Console.WriteLine(new string('-', 80));
        }
        finally
        {
            Console.WriteLine(
                "Amazon Bedrock Converse API with Tool Use Feature Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _bedrockActionsWrapper = host.Services.GetRequiredService<BedrockActionsWrapper>();
        _weatherTool = host.Services.GetRequiredService<WeatherTool>();
    }

    /// <summary>
    /// Starts the conversation with the user and handles the interaction with Bedrock.
    /// </summary>
    /// <returns>The conversation array.</returns>
    public static async Task<List<Message>> RunConversationAsync()
    {
        // Print the greeting and a short user guide
        PrintHeader();

        // Start with an empty conversation
        var conversation = new List<Message>();

        // Get the first user input
        var userInput = await GetUserInputAsync();

        while (userInput != null)
        {
            // Create a new message with the user input and append it to the conversation
            var message = new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userInput } } };
            conversation.Add(message);

            // Send the conversation to Amazon Bedrock
            var bedrockResponse = await SendConversationToBedrock(conversation);

            // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0
            await ProcessModelResponseAsync(bedrockResponse, conversation, max_recursions);

            // Repeat the loop until the user decides to exit the application
            userInput = await GetUserInputAsync();
        }

        PrintFooter();
        return conversation;
    }

    /// <summary>
    /// Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response.
    /// </summary>
    /// <param name="conversation">The conversation history including the next message to send.</param>
    /// <returns>The response from Amazon Bedrock.</returns>
    private static async Task<ConverseResponse> SendConversationToBedrock(List<Message> conversation)
    {
        Console.WriteLine("\tCalling Bedrock...");

        // Send the conversation, system prompt, and tool configuration, and return the response
        return await _bedrockActionsWrapper.SendConverseRequestAsync(model_id, system_prompt, conversation, _weatherTool.GetToolSpec());
    }

    /// <summary>
    /// Processes the response received via Amazon Bedrock and performs the necessary actions based on the stop reason.
    /// </summary>
    /// <param name="modelResponse">The model's response returned via Amazon Bedrock.</param>
    /// <param name="conversation">The conversation history.</param>
    /// <param name="maxRecursion">The maximum number of recursive calls allowed.</param>
    private static async Task ProcessModelResponseAsync(ConverseResponse modelResponse, List<Message> conversation, int maxRecursion)
    {
        if (maxRecursion <= 0)
        {
            // Stop the process, the number of recursive calls could indicate an infinite loop
            Console.WriteLine("\tWarning: Maximum number of recursions reached. Please try again.");
        }

        // Append the model's response to the ongoing conversation
        conversation.Add(modelResponse.Output.Message);

        if (modelResponse.StopReason == "tool_use")
        {
            // If the stop reason is "tool_use", forward everything to the tool use handler
            await HandleToolUseAsync(modelResponse.Output, conversation, maxRecursion - 1);
        }

        if (modelResponse.StopReason == "end_turn")
        {
            // If the stop reason is "end_turn", print the model's response text, and finish the process
            PrintModelResponse(modelResponse.Output.Message.Content[0].Text);
            if (!_interactive)
            {
                default_prompt = "x";
            }
        }
    }

    /// <summary>
    /// Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock.
    /// The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing.
    /// </summary>
    /// <param name="modelResponse">The model's response containing the tool use request.</param>
    /// <param name="conversation">The conversation history.</param>
    /// <param name="maxRecursion">The maximum number of recursive calls allowed.</param>
    public static async Task HandleToolUseAsync(ConverseOutput modelResponse, List<Message> conversation, int maxRecursion)
    {
        // Initialize an empty list of tool results
        var toolResults = new List<ContentBlock>();

        // The model's response can consist of multiple content blocks
        foreach (var contentBlock in modelResponse.Message.Content)
        {
            if (!String.IsNullOrEmpty(contentBlock.Text))
            {
                // If the content block contains text, print it to the console
                PrintModelResponse(contentBlock.Text);
            }

            if (contentBlock.ToolUse != null)
            {
                // If the content block is a tool use request, forward it to the tool
                var toolResponse = await InvokeTool(contentBlock.ToolUse);

                // Add the tool use ID and the tool's response to the list of results
                toolResults.Add(new ContentBlock
                {
                    ToolResult = new ToolResultBlock()
                    {
                        ToolUseId = toolResponse.ToolUseId,
                        Content = new List<ToolResultContentBlock>()
                            { new ToolResultContentBlock { Json = toolResponse.Content } }
                    }
                });
            }
        }

        // Embed the tool results in a new user message
        var message = new Message() { Role = ConversationRole.User, Content = toolResults };

        // Append the new message to the ongoing conversation
        conversation.Add(message);

        // Send the conversation to Amazon Bedrock
        var response = await SendConversationToBedrock(conversation);

        // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0
        await ProcessModelResponseAsync(response, conversation, maxRecursion);
    }

    /// <summary>
    /// Invokes the specified tool with the given payload and returns the tool's response.
    /// If the requested tool does not exist, an error message is returned.
    /// </summary>
    /// <param name="payload">The payload containing the tool name and input data.</param>
    /// <returns>The tool's response or an error message.</returns>
    public static async Task<ToolResponse> InvokeTool(ToolUseBlock payload)
    {
        var toolName = payload.Name;

        if (toolName == "Weather_Tool")
        {
            var inputData = payload.Input.AsDictionary();
            PrintToolUse(toolName, inputData);

            // Invoke the weather tool with the input data provided
            var weatherResponse = await _weatherTool.FetchWeatherDataAsync(inputData["latitude"].ToString(), inputData["longitude"].ToString());
            return new ToolResponse { ToolUseId = payload.ToolUseId, Content = weatherResponse };
        }
        else
        {
            var errorMessage = $"\tThe requested tool with name '{toolName}' does not exist.";
            return new ToolResponse { ToolUseId = payload.ToolUseId, Content = new { error = true, message = errorMessage } };
        }
    }


    /// <summary>
    /// Prompts the user for input and returns the user's response.
    /// Returns null if the user enters 'x' to exit.
    /// </summary>
    /// <param name="prompt">The prompt to display to the user.</param>
    /// <returns>The user's input or null if the user chooses to exit.</returns>
    private static async Task<string?> GetUserInputAsync(string prompt = "\tYour weather info request:")
    {
        var userInput = default_prompt;
        if (_interactive)
        {
            Console.WriteLine(new string('*', 80));
            Console.WriteLine($"{prompt} (x to exit): \n\t");
            userInput = Console.ReadLine();
        }

        if (string.IsNullOrWhiteSpace(userInput))
        {
            prompt = "\tPlease enter your weather info request, e.g. the name of a city";
            return await GetUserInputAsync(prompt);
        }

        if (userInput.ToLowerInvariant() == "x")
        {
            return null;
        }

        return userInput;
    }

    /// <summary>
    /// Logs the welcome message and usage guide for the tool use demo.
    /// </summary>
    public static void PrintHeader()
    {
        Console.WriteLine(@"
        =================================================
        Welcome to the Amazon Bedrock Tool Use demo!
        =================================================

        This assistant provides current weather information for user-specified locations.
        You can ask for weather details by providing the location name or coordinates. Weather information
        will be provided using a custom Tool and open-meteo API.

        Example queries:
        - What's the weather like in New York?
        - Current weather for latitude 40.70, longitude -74.01
        - Is it warmer in Rome or Barcelona today?

        To exit the program, simply type 'x' and press Enter.

        P.S.: You're not limited to single locations, or even to using English!
        Have fun and experiment with the app!
        ");
    }

    /// <summary>
    /// Logs the footer information for the tool use demo.
    /// </summary>
    public static void PrintFooter()
    {
        Console.WriteLine(@"
        =================================================
        Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you
        learned something new, or got some inspiration for your own apps today!

        For more Bedrock examples in different programming languages, have a look at:
        https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html
        =================================================
        ");
    }

    /// <summary>
    /// Logs information about the tool use.
    /// </summary>
    /// <param name="toolName">The name of the tool being used.</param>
    /// <param name="inputData">The input data for the tool.</param>
    public static void PrintToolUse(string toolName, Dictionary<string, Document> inputData)
    {
        Console.WriteLine($"\n\tInvoking tool: {toolName} with input: {inputData["latitude"].ToString()}, {inputData["longitude"].ToString()}...\n");
    }

    /// <summary>
    /// Logs the model's response.
    /// </summary>
    /// <param name="message">The model's response message.</param>
    public static void PrintModelResponse(string message)
    {
        Console.WriteLine("\tThe model's response:\n");
        Console.WriteLine(message);
        Console.WriteLine();
    }
}
```
デモで使用される気象ツール。このファイルはツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
using Amazon.BedrockRuntime.Model;
using Amazon.Runtime.Documents;
using Microsoft.Extensions.Logging;

namespace ConverseToolScenario;

/// <summary>
/// Weather tool that will be invoked when requested by the Bedrock response.
/// </summary>
public class WeatherTool
{
    private readonly ILogger<WeatherTool> _logger;
    private readonly IHttpClientFactory _httpClientFactory;

    public WeatherTool(ILogger<WeatherTool> logger, IHttpClientFactory httpClientFactory)
    {
        _logger = logger;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// Returns the JSON Schema specification for the Weather tool. The tool specification
    /// defines the input schema and describes the tool's functionality.
    /// For more information, see https://json-schema.org/understanding-json-schema/reference.
    /// </summary>
    /// <returns>The tool specification for the Weather tool.</returns>
    public ToolSpecification GetToolSpec()
    {
        ToolSpecification toolSpecification = new ToolSpecification();

        toolSpecification.Name = "Weather_Tool";
        toolSpecification.Description = "Get the current weather for a given location, based on its WGS84 coordinates.";

        Document toolSpecDocument = Document.FromObject(
            new
            {
                type = "object",
                properties = new
                {
                    latitude = new
                    {
                        type = "string",
                        description = "Geographical WGS84 latitude of the location."
                    },
                    longitude = new
                    {
                        type = "string",
                        description = "Geographical WGS84 longitude of the location."
                    }
                },
                required = new[] { "latitude", "longitude" }
            });

        toolSpecification.InputSchema = new ToolInputSchema() { Json = toolSpecDocument };
        return toolSpecification;
    }

    /// <summary>
    /// Fetches weather data for the given latitude and longitude using the Open-Meteo API.
    /// Returns the weather data or an error message if the request fails.
    /// </summary>
    /// <param name="latitude">The latitude of the location.</param>
    /// <param name="longitude">The longitude of the location.</param>
    /// <returns>The weather data or an error message.</returns>
    public async Task<Document> FetchWeatherDataAsync(string latitude, string longitude)
    {
        string endpoint = "https://api.open-meteo.com/v1/forecast";

        try
        {
            var httpClient = _httpClientFactory.CreateClient();
            var response = await httpClient.GetAsync($"{endpoint}?latitude={latitude}&longitude={longitude}&current_weather=True");
            response.EnsureSuccessStatusCode();
            var weatherData = await response.Content.ReadAsStringAsync();

            Document weatherDocument = Document.FromObject(
                new { weather_data = weatherData });

            return weatherDocument;
        }
        catch (HttpRequestException e)
        {
            _logger.LogError(e, "Error fetching weather data: {Message}", e.Message);
            throw;
        }
        catch (Exception e)
        {
            _logger.LogError(e, "Unexpected error fetching weather data: {Message}", e.Message);
            throw;
        }
    }
}
```
ツール設定を使用する Converse API アクション。  

```
/// <summary>
/// Wrapper class for interacting with the Amazon Bedrock Converse API.
/// </summary>
public class BedrockActionsWrapper
{
    private readonly IAmazonBedrockRuntime _bedrockClient;
    private readonly ILogger<BedrockActionsWrapper> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="BedrockActionsWrapper"/> class.
    /// </summary>
    /// <param name="bedrockClient">The Bedrock Converse API client.</param>
    /// <param name="logger">The logger instance.</param>
    public BedrockActionsWrapper(IAmazonBedrockRuntime bedrockClient, ILogger<BedrockActionsWrapper> logger)
    {
        _bedrockClient = bedrockClient;
        _logger = logger;
    }

    /// <summary>
    /// Sends a Converse request to the Amazon Bedrock Converse API.
    /// </summary>
    /// <param name="modelId">The Bedrock Model Id.</param>
    /// <param name="systemPrompt">A system prompt instruction.</param>
    /// <param name="conversation">The array of messages in the conversation.</param>
    /// <param name="toolSpec">The specification for a tool.</param>
    /// <returns>The response of the model.</returns>
    public async Task<ConverseResponse> SendConverseRequestAsync(string modelId, string systemPrompt, List<Message> conversation, ToolSpecification toolSpec)
    {
        try
        {
            var request = new ConverseRequest()
            {
                ModelId = modelId,
                System = new List<SystemContentBlock>()
                {
                    new SystemContentBlock()
                    {
                        Text = systemPrompt
                    }
                },
                Messages = conversation,
                ToolConfig = new ToolConfiguration()
                {
                    Tools = new List<Tool>()
                    {
                        new Tool()
                        {
                            ToolSpec = toolSpec
                        }
                    }
                }
            };

            var response = await _bedrockClient.ConverseAsync(request);

            return response;
        }
        catch (ModelNotReadyException ex)
        {
            _logger.LogError(ex, "Model not ready, please wait and try again.");
            throw;
        }
        catch (AmazonBedrockRuntimeException ex)
        {
            _logger.LogError(ex, "Error occurred while sending Converse request.");
            throw;
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Amazon Nova
<a name="amazon_nova"></a>

### Converse
<a name="bedrock-runtime_Converse_AmazonNovaText_csharp_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Amazon Nova.

using System;
using System.Collections.Generic;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Amazon Nova Lite.
var modelId = "amazon.nova-lite-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseAsync(request);

    // Extract and print the response text.
    string responseText = response?.Output?.Message?.Content?[0]?.Text ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
ツール設定を含む Bedrock の Converse API を使用して Amazon Nova にメッセージの会話を送信します。  

```
/// <summary>
/// Wrapper class for interacting with the Amazon Bedrock Converse API.
/// </summary>
public class BedrockActionsWrapper
{
    private readonly IAmazonBedrockRuntime _bedrockClient;
    private readonly ILogger<BedrockActionsWrapper> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="BedrockActionsWrapper"/> class.
    /// </summary>
    /// <param name="bedrockClient">The Bedrock Converse API client.</param>
    /// <param name="logger">The logger instance.</param>
    public BedrockActionsWrapper(IAmazonBedrockRuntime bedrockClient, ILogger<BedrockActionsWrapper> logger)
    {
        _bedrockClient = bedrockClient;
        _logger = logger;
    }

    /// <summary>
    /// Sends a Converse request to the Amazon Bedrock Converse API.
    /// </summary>
    /// <param name="modelId">The Bedrock Model Id.</param>
    /// <param name="systemPrompt">A system prompt instruction.</param>
    /// <param name="conversation">The array of messages in the conversation.</param>
    /// <param name="toolSpec">The specification for a tool.</param>
    /// <returns>The response of the model.</returns>
    public async Task<ConverseResponse> SendConverseRequestAsync(string modelId, string systemPrompt, List<Message> conversation, ToolSpecification toolSpec)
    {
        try
        {
            var request = new ConverseRequest()
            {
                ModelId = modelId,
                System = new List<SystemContentBlock>()
                {
                    new SystemContentBlock()
                    {
                        Text = systemPrompt
                    }
                },
                Messages = conversation,
                ToolConfig = new ToolConfiguration()
                {
                    Tools = new List<Tool>()
                    {
                        new Tool()
                        {
                            ToolSpec = toolSpec
                        }
                    }
                }
            };

            var response = await _bedrockClient.ConverseAsync(request);

            return response;
        }
        catch (ModelNotReadyException ex)
        {
            _logger.LogError(ex, "Model not ready, please wait and try again.");
            throw;
        }
        catch (AmazonBedrockRuntimeException ex)
        {
            _logger.LogError(ex, "Error occurred while sending Converse request.");
            throw;
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AmazonNovaText_csharp_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Amazon Nova
// and print the response stream.

using System;
using System.Collections.Generic;
using System.Linq;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Amazon Nova Lite.
var modelId = "amazon.nova-lite-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseStreamRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var chunk in response.Stream.AsEnumerable())
    {
        if (chunk is ContentBlockDeltaEvent)
        {
            Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text);
        }
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### シナリオ: Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUseDemo_AmazonNova_csharp_3_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario#code-examples)での設定と実行の方法を確認してください。
シナリオフローのプライマリ実行。このシナリオはユーザー、Amazon Bedrock Converse API、気象ツールの間の会話を調整します。  

```
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;
using Amazon.Runtime.Documents;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;

namespace ConverseToolScenario;

public static class ConverseToolScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
    The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user
    input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.
   */

    public static BedrockActionsWrapper _bedrockActionsWrapper = null!;
    public static WeatherTool _weatherTool = null!;
    public static bool _interactive = true;

    // Change this string to use a different model with Converse API.
    private static string model_id = "amazon.nova-lite-v1:0";

    private static string system_prompt = @"
        You are a weather assistant that provides current weather data for user-specified locations using only
        the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
        If the user specifies a state, country, or region, infer the locations of cities within that state.
        If the user provides coordinates, infer the approximate location and refer to it in your response.
        To use the tool, you strictly apply the provided tool specification.

        - Explain your step-by-step process, and give brief updates before each step.
        - Only use the Weather_Tool for data. Never guess or make up information. 
        - Repeat the tool use for subsequent requests if necessary.
        - If the tool errors, apologize, explain weather is unavailable, and suggest other options.
        - Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
          emojis where appropriate.
        - Only respond to weather queries. Remind off-topic users of your purpose. 
        - Never claim to search online, access external data, or use tools besides Weather_Tool.
        - Complete the entire process until you have all required data before sending the complete response.
    "
    ;

    private static string default_prompt = "What is the weather like in Seattle?";

    // The maximum number of recursive calls allowed in the tool use function.
    // This helps prevent infinite loops and potential performance issues.
    private static int max_recursions = 5;

    public static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Error)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddHttpClient()
                    .AddSingleton<IAmazonBedrockRuntime>(_ => new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1)) // Specify a region that has access to the chosen model.
                    .AddTransient<BedrockActionsWrapper>()
                    .AddTransient<WeatherTool>()
                    .RemoveAll<IHttpMessageHandlerBuilderFilter>()
            )
            .Build();

        ServicesSetup(host);

        try
        {
            await RunConversationAsync();

        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            Console.WriteLine(new string('-', 80));
        }
        finally
        {
            Console.WriteLine(
                "Amazon Bedrock Converse API with Tool Use Feature Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _bedrockActionsWrapper = host.Services.GetRequiredService<BedrockActionsWrapper>();
        _weatherTool = host.Services.GetRequiredService<WeatherTool>();
    }

    /// <summary>
    /// Starts the conversation with the user and handles the interaction with Bedrock.
    /// </summary>
    /// <returns>The conversation array.</returns>
    public static async Task<List<Message>> RunConversationAsync()
    {
        // Print the greeting and a short user guide
        PrintHeader();

        // Start with an empty conversation
        var conversation = new List<Message>();

        // Get the first user input
        var userInput = await GetUserInputAsync();

        while (userInput != null)
        {
            // Create a new message with the user input and append it to the conversation
            var message = new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userInput } } };
            conversation.Add(message);

            // Send the conversation to Amazon Bedrock
            var bedrockResponse = await SendConversationToBedrock(conversation);

            // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0
            await ProcessModelResponseAsync(bedrockResponse, conversation, max_recursions);

            // Repeat the loop until the user decides to exit the application
            userInput = await GetUserInputAsync();
        }

        PrintFooter();
        return conversation;
    }

    /// <summary>
    /// Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response.
    /// </summary>
    /// <param name="conversation">The conversation history including the next message to send.</param>
    /// <returns>The response from Amazon Bedrock.</returns>
    private static async Task<ConverseResponse> SendConversationToBedrock(List<Message> conversation)
    {
        Console.WriteLine("\tCalling Bedrock...");

        // Send the conversation, system prompt, and tool configuration, and return the response
        return await _bedrockActionsWrapper.SendConverseRequestAsync(model_id, system_prompt, conversation, _weatherTool.GetToolSpec());
    }

    /// <summary>
    /// Processes the response received via Amazon Bedrock and performs the necessary actions based on the stop reason.
    /// </summary>
    /// <param name="modelResponse">The model's response returned via Amazon Bedrock.</param>
    /// <param name="conversation">The conversation history.</param>
    /// <param name="maxRecursion">The maximum number of recursive calls allowed.</param>
    private static async Task ProcessModelResponseAsync(ConverseResponse modelResponse, List<Message> conversation, int maxRecursion)
    {
        if (maxRecursion <= 0)
        {
            // Stop the process, the number of recursive calls could indicate an infinite loop
            Console.WriteLine("\tWarning: Maximum number of recursions reached. Please try again.");
        }

        // Append the model's response to the ongoing conversation
        conversation.Add(modelResponse.Output.Message);

        if (modelResponse.StopReason == "tool_use")
        {
            // If the stop reason is "tool_use", forward everything to the tool use handler
            await HandleToolUseAsync(modelResponse.Output, conversation, maxRecursion - 1);
        }

        if (modelResponse.StopReason == "end_turn")
        {
            // If the stop reason is "end_turn", print the model's response text, and finish the process
            PrintModelResponse(modelResponse.Output.Message.Content[0].Text);
            if (!_interactive)
            {
                default_prompt = "x";
            }
        }
    }

    /// <summary>
    /// Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock.
    /// The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing.
    /// </summary>
    /// <param name="modelResponse">The model's response containing the tool use request.</param>
    /// <param name="conversation">The conversation history.</param>
    /// <param name="maxRecursion">The maximum number of recursive calls allowed.</param>
    public static async Task HandleToolUseAsync(ConverseOutput modelResponse, List<Message> conversation, int maxRecursion)
    {
        // Initialize an empty list of tool results
        var toolResults = new List<ContentBlock>();

        // The model's response can consist of multiple content blocks
        foreach (var contentBlock in modelResponse.Message.Content)
        {
            if (!String.IsNullOrEmpty(contentBlock.Text))
            {
                // If the content block contains text, print it to the console
                PrintModelResponse(contentBlock.Text);
            }

            if (contentBlock.ToolUse != null)
            {
                // If the content block is a tool use request, forward it to the tool
                var toolResponse = await InvokeTool(contentBlock.ToolUse);

                // Add the tool use ID and the tool's response to the list of results
                toolResults.Add(new ContentBlock
                {
                    ToolResult = new ToolResultBlock()
                    {
                        ToolUseId = toolResponse.ToolUseId,
                        Content = new List<ToolResultContentBlock>()
                            { new ToolResultContentBlock { Json = toolResponse.Content } }
                    }
                });
            }
        }

        // Embed the tool results in a new user message
        var message = new Message() { Role = ConversationRole.User, Content = toolResults };

        // Append the new message to the ongoing conversation
        conversation.Add(message);

        // Send the conversation to Amazon Bedrock
        var response = await SendConversationToBedrock(conversation);

        // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0
        await ProcessModelResponseAsync(response, conversation, maxRecursion);
    }

    /// <summary>
    /// Invokes the specified tool with the given payload and returns the tool's response.
    /// If the requested tool does not exist, an error message is returned.
    /// </summary>
    /// <param name="payload">The payload containing the tool name and input data.</param>
    /// <returns>The tool's response or an error message.</returns>
    public static async Task<ToolResponse> InvokeTool(ToolUseBlock payload)
    {
        var toolName = payload.Name;

        if (toolName == "Weather_Tool")
        {
            var inputData = payload.Input.AsDictionary();
            PrintToolUse(toolName, inputData);

            // Invoke the weather tool with the input data provided
            var weatherResponse = await _weatherTool.FetchWeatherDataAsync(inputData["latitude"].ToString(), inputData["longitude"].ToString());
            return new ToolResponse { ToolUseId = payload.ToolUseId, Content = weatherResponse };
        }
        else
        {
            var errorMessage = $"\tThe requested tool with name '{toolName}' does not exist.";
            return new ToolResponse { ToolUseId = payload.ToolUseId, Content = new { error = true, message = errorMessage } };
        }
    }


    /// <summary>
    /// Prompts the user for input and returns the user's response.
    /// Returns null if the user enters 'x' to exit.
    /// </summary>
    /// <param name="prompt">The prompt to display to the user.</param>
    /// <returns>The user's input or null if the user chooses to exit.</returns>
    private static async Task<string?> GetUserInputAsync(string prompt = "\tYour weather info request:")
    {
        var userInput = default_prompt;
        if (_interactive)
        {
            Console.WriteLine(new string('*', 80));
            Console.WriteLine($"{prompt} (x to exit): \n\t");
            userInput = Console.ReadLine();
        }

        if (string.IsNullOrWhiteSpace(userInput))
        {
            prompt = "\tPlease enter your weather info request, e.g. the name of a city";
            return await GetUserInputAsync(prompt);
        }

        if (userInput.ToLowerInvariant() == "x")
        {
            return null;
        }

        return userInput;
    }

    /// <summary>
    /// Logs the welcome message and usage guide for the tool use demo.
    /// </summary>
    public static void PrintHeader()
    {
        Console.WriteLine(@"
        =================================================
        Welcome to the Amazon Bedrock Tool Use demo!
        =================================================

        This assistant provides current weather information for user-specified locations.
        You can ask for weather details by providing the location name or coordinates. Weather information
        will be provided using a custom Tool and open-meteo API.

        Example queries:
        - What's the weather like in New York?
        - Current weather for latitude 40.70, longitude -74.01
        - Is it warmer in Rome or Barcelona today?

        To exit the program, simply type 'x' and press Enter.

        P.S.: You're not limited to single locations, or even to using English!
        Have fun and experiment with the app!
        ");
    }

    /// <summary>
    /// Logs the footer information for the tool use demo.
    /// </summary>
    public static void PrintFooter()
    {
        Console.WriteLine(@"
        =================================================
        Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you
        learned something new, or got some inspiration for your own apps today!

        For more Bedrock examples in different programming languages, have a look at:
        https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html
        =================================================
        ");
    }

    /// <summary>
    /// Logs information about the tool use.
    /// </summary>
    /// <param name="toolName">The name of the tool being used.</param>
    /// <param name="inputData">The input data for the tool.</param>
    public static void PrintToolUse(string toolName, Dictionary<string, Document> inputData)
    {
        Console.WriteLine($"\n\tInvoking tool: {toolName} with input: {inputData["latitude"].ToString()}, {inputData["longitude"].ToString()}...\n");
    }

    /// <summary>
    /// Logs the model's response.
    /// </summary>
    /// <param name="message">The model's response message.</param>
    public static void PrintModelResponse(string message)
    {
        Console.WriteLine("\tThe model's response:\n");
        Console.WriteLine(message);
        Console.WriteLine();
    }
}
```
デモで使用される気象ツール。このファイルはツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
using Amazon.BedrockRuntime.Model;
using Amazon.Runtime.Documents;
using Microsoft.Extensions.Logging;

namespace ConverseToolScenario;

/// <summary>
/// Weather tool that will be invoked when requested by the Bedrock response.
/// </summary>
public class WeatherTool
{
    private readonly ILogger<WeatherTool> _logger;
    private readonly IHttpClientFactory _httpClientFactory;

    public WeatherTool(ILogger<WeatherTool> logger, IHttpClientFactory httpClientFactory)
    {
        _logger = logger;
        _httpClientFactory = httpClientFactory;
    }

    /// <summary>
    /// Returns the JSON Schema specification for the Weather tool. The tool specification
    /// defines the input schema and describes the tool's functionality.
    /// For more information, see https://json-schema.org/understanding-json-schema/reference.
    /// </summary>
    /// <returns>The tool specification for the Weather tool.</returns>
    public ToolSpecification GetToolSpec()
    {
        ToolSpecification toolSpecification = new ToolSpecification();

        toolSpecification.Name = "Weather_Tool";
        toolSpecification.Description = "Get the current weather for a given location, based on its WGS84 coordinates.";

        Document toolSpecDocument = Document.FromObject(
            new
            {
                type = "object",
                properties = new
                {
                    latitude = new
                    {
                        type = "string",
                        description = "Geographical WGS84 latitude of the location."
                    },
                    longitude = new
                    {
                        type = "string",
                        description = "Geographical WGS84 longitude of the location."
                    }
                },
                required = new[] { "latitude", "longitude" }
            });

        toolSpecification.InputSchema = new ToolInputSchema() { Json = toolSpecDocument };
        return toolSpecification;
    }

    /// <summary>
    /// Fetches weather data for the given latitude and longitude using the Open-Meteo API.
    /// Returns the weather data or an error message if the request fails.
    /// </summary>
    /// <param name="latitude">The latitude of the location.</param>
    /// <param name="longitude">The longitude of the location.</param>
    /// <returns>The weather data or an error message.</returns>
    public async Task<Document> FetchWeatherDataAsync(string latitude, string longitude)
    {
        string endpoint = "https://api.open-meteo.com/v1/forecast";

        try
        {
            var httpClient = _httpClientFactory.CreateClient();
            var response = await httpClient.GetAsync($"{endpoint}?latitude={latitude}&longitude={longitude}&current_weather=True");
            response.EnsureSuccessStatusCode();
            var weatherData = await response.Content.ReadAsStringAsync();

            Document weatherDocument = Document.FromObject(
                new { weather_data = weatherData });

            return weatherDocument;
        }
        catch (HttpRequestException e)
        {
            _logger.LogError(e, "Error fetching weather data: {Message}", e.Message);
            throw;
        }
        catch (Exception e)
        {
            _logger.LogError(e, "Unexpected error fetching weather data: {Message}", e.Message);
            throw;
        }
    }
}
```
ツール設定を使用する Converse API アクション。  

```
/// <summary>
/// Wrapper class for interacting with the Amazon Bedrock Converse API.
/// </summary>
public class BedrockActionsWrapper
{
    private readonly IAmazonBedrockRuntime _bedrockClient;
    private readonly ILogger<BedrockActionsWrapper> _logger;

    /// <summary>
    /// Initializes a new instance of the <see cref="BedrockActionsWrapper"/> class.
    /// </summary>
    /// <param name="bedrockClient">The Bedrock Converse API client.</param>
    /// <param name="logger">The logger instance.</param>
    public BedrockActionsWrapper(IAmazonBedrockRuntime bedrockClient, ILogger<BedrockActionsWrapper> logger)
    {
        _bedrockClient = bedrockClient;
        _logger = logger;
    }

    /// <summary>
    /// Sends a Converse request to the Amazon Bedrock Converse API.
    /// </summary>
    /// <param name="modelId">The Bedrock Model Id.</param>
    /// <param name="systemPrompt">A system prompt instruction.</param>
    /// <param name="conversation">The array of messages in the conversation.</param>
    /// <param name="toolSpec">The specification for a tool.</param>
    /// <returns>The response of the model.</returns>
    public async Task<ConverseResponse> SendConverseRequestAsync(string modelId, string systemPrompt, List<Message> conversation, ToolSpecification toolSpec)
    {
        try
        {
            var request = new ConverseRequest()
            {
                ModelId = modelId,
                System = new List<SystemContentBlock>()
                {
                    new SystemContentBlock()
                    {
                        Text = systemPrompt
                    }
                },
                Messages = conversation,
                ToolConfig = new ToolConfiguration()
                {
                    Tools = new List<Tool>()
                    {
                        new Tool()
                        {
                            ToolSpec = toolSpec
                        }
                    }
                }
            };

            var response = await _bedrockClient.ConverseAsync(request);

            return response;
        }
        catch (ModelNotReadyException ex)
        {
            _logger.LogError(ex, "Model not ready, please wait and try again.");
            throw;
        }
        catch (AmazonBedrockRuntimeException ex)
        {
            _logger.LogError(ex, "Error occurred while sending Converse request.");
            throw;
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Amazon Nova Canvas
<a name="amazon_nova_canvas"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AmazonNovaImageGeneration_csharp_3_topic"></a>

以下のコード例は、Amazon Bedrock で Amazon Nova Canvas を呼び出して画像を生成する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Nova Canvas で画像を作成します。  

```
// Use the native inference API to create an image with Amazon Nova Canvas.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID.
var modelId = "amazon.nova-canvas-v1:0";

// Define the image generation prompt for the model.
var prompt = "A stylized picture of a cute old steampunk robot.";

// Create a random seed between 0 and 858,993,459
int seed = new Random().Next(0, 858993460);

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    taskType = "TEXT_IMAGE",
    textToImageParams = new
    {
        text = prompt
    },
    imageGenerationConfig = new
    {
        seed,
        quality = "standard",
        width = 512,
        height = 512,
        numberOfImages = 1
    }
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var response = await client.InvokeModelAsync(request);

    // Decode the response body.
    var modelResponse = await JsonNode.ParseAsync(response.Body);

    // Extract the image data.
    var base64Image = modelResponse["images"]?[0].ToString() ?? "";

    // Save the image in a local folder
    string savedPath = AmazonNovaCanvas.InvokeModel.SaveBase64Image(base64Image);
    Console.WriteLine($"Image saved to: {savedPath}");
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Anthropic Claude
<a name="anthropic_claude"></a>

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_AnthropicClaude_csharp_3_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Anthropic Claude
// and print the response stream.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Claude 3 Haiku.
var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    anthropic_version = "bedrock-2023-05-31",
    max_tokens = 512,
    temperature = 0.5,
    messages = new[]
    {
        new { role = "user", content = userMessage }
    }
});

// Create a request with the model ID, the user message, and an inference configuration.
var request = new InvokeModelWithResponseStreamRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var streamingResponse = await client.InvokeModelWithResponseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var item in streamingResponse.Body)
    {
        var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes);
        var text = chunk["delta"]?["text"] ?? "";
        Console.Write(text);
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

## Cohere Command
<a name="cohere_command"></a>

### InvokeModel: コマンド R および R\$1
<a name="bedrock-runtime_InvokeModel_CohereCommandR_csharp_3_topic"></a>

次のコード例は、Invoke Model API を使用して Cohere Command R および R\$1 にテキストメッセージを送信する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Cohere Command R.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Command R.
var modelId = "cohere.command-r-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    message = userMessage,
    max_tokens = 512,
    temperature = 0.5
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var response = await client.InvokeModelAsync(request);

    // Decode the response body.
    var modelResponse = await JsonNode.ParseAsync(response.Body);

    // Extract and print the response text.
    var responseText = modelResponse["text"] ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream: コマンド R および R\$1
<a name="bedrock-runtime_InvokeModelWithResponseStream_CohereCommandR_csharp_3_topic"></a>

次のコード例は、レスポンスストリームで Invoke Model API を使用して、Cohere Command にテキストメッセージを送信する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Cohere Command R
// and print the response stream.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Command R.
var modelId = "cohere.command-r-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    message = userMessage,
    max_tokens = 512,
    temperature = 0.5
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelWithResponseStreamRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var streamingResponse = await client.InvokeModelWithResponseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var item in streamingResponse.Body)
    {
        var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes);
        var text = chunk["text"] ?? "";
        Console.Write(text);
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Meta Llama
<a name="meta_llama"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MetaLlama3_csharp_3_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Meta Llama 3.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USWest2);

// Set the model ID, e.g., Llama 3 70b Instruct.
var modelId = "meta.llama3-70b-instruct-v1:0";

// Define the prompt for the model.
var prompt = "Describe the purpose of a 'hello world' program in one line.";

// Embed the prompt in Llama 2's instruction format.
var formattedPrompt = $@"
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
{prompt}
<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    prompt = formattedPrompt,
    max_gen_len = 512,
    temperature = 0.5
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var response = await client.InvokeModelAsync(request);

    // Decode the response body.
    var modelResponse = await JsonNode.ParseAsync(response.Body);

    // Extract and print the response text.
    var responseText = modelResponse["generation"] ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_MetaLlama3_csharp_3_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Meta Llama 3
// and print the response stream.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USWest2);

// Set the model ID, e.g., Llama 3 70b Instruct.
var modelId = "meta.llama3-70b-instruct-v1:0";

// Define the prompt for the model.
var prompt = "Describe the purpose of a 'hello world' program in one line.";

// Embed the prompt in Llama 2's instruction format.
var formattedPrompt = $@"
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
{prompt}
<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    prompt = formattedPrompt,
    max_gen_len = 512,
    temperature = 0.5
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelWithResponseStreamRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var streamingResponse = await client.InvokeModelWithResponseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var item in streamingResponse.Body)
    {
        var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes);
        var text = chunk["generation"] ?? "";
        Console.Write(text);
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

## Mistral AI
<a name="mistral_ai"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MistralAi_csharp_3_topic"></a>

次のコード例は、Invoke Model API を使用して Mistral モデルにテキストメッセージを送信する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Mistral.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Mistral Large.
var modelId = "mistral.mistral-large-2402-v1:0";

// Define the prompt for the model.
var prompt = "Describe the purpose of a 'hello world' program in one line.";

// Embed the prompt in Mistral's instruction format.
var formattedPrompt = $"<s>[INST] {prompt} [/INST]";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    prompt = formattedPrompt,
    max_tokens = 512,
    temperature = 0.5
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var response = await client.InvokeModelAsync(request);

    // Decode the response body.
    var modelResponse = await JsonNode.ParseAsync(response.Body);

    // Extract and print the response text.
    var responseText = modelResponse["outputs"]?[0]?["text"] ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_MistralAi_csharp_3_topic"></a>

次のコード例は、Invoke Model API を使用して Mistral AI モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Mistral
// and print the response stream.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Mistral Large.
var modelId = "mistral.mistral-large-2402-v1:0";

// Define the prompt for the model.
var prompt = "Describe the purpose of a 'hello world' program in one line.";

// Embed the prompt in Mistral's instruction format.
var formattedPrompt = $"<s>[INST] {prompt} [/INST]";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    prompt = formattedPrompt,
    max_tokens = 512,
    temperature = 0.5
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelWithResponseStreamRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var streamingResponse = await client.InvokeModelWithResponseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var item in streamingResponse.Body)
    {
        var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes);
        var text = chunk["outputs"]?[0]?["text"] ?? "";
        Console.Write(text);
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

# を使用した CloudWatch Logs の例 SDK for .NET
<a name="csharp_3_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssociateKmsKey`
<a name="cloudwatch-logs_AssociateKmsKey_csharp_3_topic"></a>

次のコード例は、`AssociateKmsKey` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Shows how to associate an AWS Key Management Service (AWS KMS) key with
    /// an Amazon CloudWatch Logs log group.
    /// </summary>
    public class AssociateKmsKey
    {
        public static async Task Main()
        {
            // This client object will be associated with the same AWS Region
            // as the default user on this system. If you need to use a
            // different AWS Region, pass it as a parameter to the client
            // constructor.
            var client = new AmazonCloudWatchLogsClient();

            string kmsKeyId = "arn:aws:kms:us-west-2:<account-number>:key/7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4";
            string groupName = "cloudwatchlogs-example-loggroup";

            var request = new AssociateKmsKeyRequest
            {
                KmsKeyId = kmsKeyId,
                LogGroupName = groupName,
            };

            var response = await client.AssociateKmsKeyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully associated KMS key ID: {kmsKeyId} with log group: {groupName}.");
            }
            else
            {
                Console.WriteLine("Could not make the association between: {kmsKeyId} and {groupName}.");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」にある「[AssociateKmsKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/AssociateKmsKey)」を参照してください。

### `CancelExportTask`
<a name="cloudwatch-logs_CancelExportTask_csharp_3_topic"></a>

次のコード例は、`CancelExportTask` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Shows how to cancel an Amazon CloudWatch Logs export task.
    /// </summary>
    public class CancelExportTask
    {
        public static async Task Main()
        {
            // This client object will be associated with the same AWS Region
            // as the default user on this system. If you need to use a
            // different AWS Region, pass it as a parameter to the client
            // constructor.
            var client = new AmazonCloudWatchLogsClient();
            string taskId = "exampleTaskId";

            var request = new CancelExportTaskRequest
            {
                TaskId = taskId,
            };

            var response = await client.CancelExportTaskAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"{taskId} successfully canceled.");
            }
            else
            {
                Console.WriteLine($"{taskId} could not be canceled.");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CancelExportTask](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/CancelExportTask)」を参照してください。

### `CreateExportTask`
<a name="cloudwatch-logs_CreateExportTask_csharp_3_topic"></a>

次のコード例は、`CreateExportTask` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Shows how to create an Export Task to export the contents of the Amazon
    /// CloudWatch Logs to the specified Amazon Simple Storage Service (Amazon S3)
    /// bucket.
    /// </summary>
    public class CreateExportTask
    {
        public static async Task Main()
        {
            // This client object will be associated with the same AWS Region
            // as the default user on this system. If you need to use a
            // different AWS Region, pass it as a parameter to the client
            // constructor.
            var client = new AmazonCloudWatchLogsClient();
            string taskName = "export-task-example";
            string logGroupName = "cloudwatchlogs-example-loggroup";
            string destination = "amzn-s3-demo-bucket";
            var fromTime = 1437584472382;
            var toTime = 1437584472833;

            var request = new CreateExportTaskRequest
            {
                From = fromTime,
                To = toTime,
                TaskName = taskName,
                LogGroupName = logGroupName,
                Destination = destination,
            };

            var response = await client.CreateExportTaskAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"The task, {taskName} with ID: " +
                                  $"{response.TaskId} has been created successfully.");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateExportTask](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/CreateExportTask)」を参照してください。

### `CreateLogGroup`
<a name="cloudwatch-logs_CreateLogGroup_csharp_3_topic"></a>

次のコード例は、`CreateLogGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Shows how to create an Amazon CloudWatch Logs log group.
    /// </summary>
    public class CreateLogGroup
    {
        public static async Task Main()
        {
            // This client object will be associated with the same AWS Region
            // as the default user on this system. If you need to use a
            // different AWS Region, pass it as a parameter to the client
            // constructor.
            var client = new AmazonCloudWatchLogsClient();

            string logGroupName = "cloudwatchlogs-example-loggroup";

            var request = new CreateLogGroupRequest
            {
                LogGroupName = logGroupName,
            };

            var response = await client.CreateLogGroupAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully create log group with ID: {logGroupName}.");
            }
            else
            {
                Console.WriteLine("Could not create log group.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateLogGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/CreateLogGroup)」を参照してください。

### `CreateLogStream`
<a name="cloudwatch-logs_CreateLogStream_csharp_3_topic"></a>

次のコード例は、`CreateLogStream` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Shows how to create an Amazon CloudWatch Logs stream for a CloudWatch
    /// log group.
    /// </summary>
    public class CreateLogStream
    {
        public static async Task Main()
        {
            // This client object will be associated with the same AWS Region
            // as the default user on this system. If you need to use a
            // different AWS Region, pass it as a parameter to the client
            // constructor.
            var client = new AmazonCloudWatchLogsClient();
            string logGroupName = "cloudwatchlogs-example-loggroup";
            string logStreamName = "cloudwatchlogs-example-logstream";

            var request = new CreateLogStreamRequest
            {
                LogGroupName = logGroupName,
                LogStreamName = logStreamName,
            };

            var response = await client.CreateLogStreamAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"{logStreamName} successfully created for {logGroupName}.");
            }
            else
            {
                Console.WriteLine("Could not create stream.");
            }
        }
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス**」の「[CreateLogStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/CreateLogStream)」を参照してください。

### `DeleteLogGroup`
<a name="cloudwatch-logs_DeleteLogGroup_csharp_3_topic"></a>

次のコード例は、`DeleteLogGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Uses the Amazon CloudWatch Logs Service to delete an existing
    /// CloudWatch Logs log group.
    /// </summary>
    public class DeleteLogGroup
    {
        public static async Task Main()
        {
            var client = new AmazonCloudWatchLogsClient();
            string logGroupName = "cloudwatchlogs-example-loggroup";

            var request = new DeleteLogGroupRequest
            {
                LogGroupName = logGroupName,
            };

            var response = await client.DeleteLogGroupAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully deleted CloudWatch log group, {logGroupName}.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteLogGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/DeleteLogGroup)」を参照してください。

### `DescribeExportTasks`
<a name="cloudwatch-logs_DescribeExportTasks_csharp_3_topic"></a>

次のコード例は、`DescribeExportTasks` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Shows how to retrieve a list of information about Amazon CloudWatch
    /// Logs export tasks.
    /// </summary>
    public class DescribeExportTasks
    {
        public static async Task Main()
        {
            // This client object will be associated with the same AWS Region
            // as the default user on this system. If you need to use a
            // different AWS Region, pass it as a parameter to the client
            // constructor.
            var client = new AmazonCloudWatchLogsClient();

            var request = new DescribeExportTasksRequest
            {
                Limit = 5,
            };

            var response = new DescribeExportTasksResponse();

            do
            {
                response = await client.DescribeExportTasksAsync(request);
                response.ExportTasks.ForEach(t =>
                {
                    Console.WriteLine($"{t.TaskName} with ID: {t.TaskId} has status: {t.Status}");
                });
            }
            while (response.NextToken is not null);
        }
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」**の「[DescribeExportTasks](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/DescribeExportTasks)」を参照してください。

### `DescribeLogGroups`
<a name="cloudwatch-logs_DescribeLogGroups_csharp_3_topic"></a>

次のコード例は、`DescribeLogGroups` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/CloudWatchLogs#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.CloudWatchLogs;
    using Amazon.CloudWatchLogs.Model;

    /// <summary>
    /// Retrieves information about existing Amazon CloudWatch Logs log groups
    /// and displays the information on the console.
    /// </summary>
    public class DescribeLogGroups
    {
        public static async Task Main()
        {
            // Creates a CloudWatch Logs client using the default
            // user. If you need to work with resources in another
            // AWS Region than the one defined for the default user,
            // pass the AWS Region as a parameter to the client constructor.
            var client = new AmazonCloudWatchLogsClient();

            bool done = false;
            string newToken = null;

            var request = new DescribeLogGroupsRequest
            {
                Limit = 5,
            };

            DescribeLogGroupsResponse response;

            do
            {
                if (newToken is not null)
                {
                    request.NextToken = newToken;
                }

                response = await client.DescribeLogGroupsAsync(request);

                response.LogGroups.ForEach(lg =>
                {
                    Console.WriteLine($"{lg.LogGroupName} is associated with the key: {lg.KmsKeyId}.");
                    Console.WriteLine($"Created on: {lg.CreationTime.Date.Date}");
                    Console.WriteLine($"Date for this group will be stored for: {lg.RetentionInDays} days.\n");
                });

                if (response.NextToken is null)
                {
                    done = true;
                }
                else
                {
                    newToken = response.NextToken;
                }
            }
            while (!done);
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeLogGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/DescribeLogGroups)」を参照してください。

### `StartLiveTail`
<a name="cloudwatch-logs_StartLiveTail_csharp_3_topic"></a>

次のコード例は、`StartLiveTail` を使用する方法を示しています。

**SDK for .NET**  
必要なファイルを含めます。  

```
using Amazon;
using Amazon.CloudWatchLogs;
using Amazon.CloudWatchLogs.Model;
```
Live Tail セッションを開始します。  

```
            var client = new AmazonCloudWatchLogsClient();
            var request = new StartLiveTailRequest
            {
                LogGroupIdentifiers = logGroupIdentifiers,
                LogStreamNames = logStreamNames,
                LogEventFilterPattern = filterPattern,
            };

            var response = await client.StartLiveTailAsync(request);

            // Catch if request fails
            if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Failed to start live tail session");
                return;
            }
```
Live Tail セッションのイベントは 2 つの方法で処理できます。  

```
            /* Method 1
            * 1). Asynchronously loop through the event stream
            * 2). Set a timer to dispose the stream and stop the Live Tail session at the end.
            */
            var eventStream = response.ResponseStream;
            var task = Task.Run(() => 
            {
                foreach (var item in eventStream)
                {
                    if (item is LiveTailSessionUpdate liveTailSessionUpdate)
                    {
                        foreach (var sessionResult in liveTailSessionUpdate.SessionResults)
                        {
                            Console.WriteLine("Message : {0}", sessionResult.Message);
                        }
                    }
                    if (item is LiveTailSessionStart)
                    {
                        Console.WriteLine("Live Tail session started");
                    }
                    // On-stream exceptions are processed here
                    if (item is CloudWatchLogsEventStreamException)
                    {
                        Console.WriteLine($"ERROR: {item}");
                    }
                }
            });
            // Close the stream to stop the session after a timeout
            if (!task.Wait(TimeSpan.FromSeconds(10))){
                eventStream.Dispose();
                Console.WriteLine("End of line");
            }
```

```
            /* Method 2
            * 1). Add event handlers to each event variable
            * 2). Start processing the stream and wait for a timeout using AutoResetEvent
            */
            AutoResetEvent endEvent = new AutoResetEvent(false);
            var eventStream = response.ResponseStream;
            using (eventStream) // automatically disposes the stream to stop the session after execution finishes
            {
                eventStream.SessionStartReceived += (sender, e) =>
                {
                    Console.WriteLine("LiveTail session started");
                };
                eventStream.SessionUpdateReceived += (sender, e) =>
                {   
                    foreach (LiveTailSessionLogEvent logEvent in e.EventStreamEvent.SessionResults){
                        Console.WriteLine("Message: {0}", logEvent.Message);
                    }
                };
                // On-stream exceptions are captured here
                eventStream.ExceptionReceived += (sender, e) => 
                {
                    Console.WriteLine($"ERROR: {e.EventStreamException.Message}");
                };

                eventStream.StartProcessing();
                // Stream events for this amount of time.
                endEvent.WaitOne(TimeSpan.FromSeconds(10));
                Console.WriteLine("End of line");
            }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[StartLiveTail](https://docs.aws.amazon.com/goto/DotNetSDKV3/logs-2014-03-28/StartLiveTail)」を参照してください。

# を使用した Amazon Cognito ID プロバイダーの例 SDK for .NET
<a name="csharp_3_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダー AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AdminGetUser`
<a name="cognito-identity-provider_AdminGetUser_csharp_3_topic"></a>

次のコード例は、`AdminGetUser` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the specified user from an Amazon Cognito user pool with administrator access.
    /// </summary>
    /// <param name="userName">The name of the user.</param>
    /// <param name="poolId">The Id of the Amazon Cognito user pool.</param>
    /// <returns>Async task.</returns>
    public async Task<UserStatusType> GetAdminUserAsync(string userName, string poolId)
    {
        AdminGetUserRequest userRequest = new AdminGetUserRequest
        {
            Username = userName,
            UserPoolId = poolId,
        };

        var response = await _cognitoService.AdminGetUserAsync(userRequest);

        Console.WriteLine($"User status {response.UserStatus}");
        return response.UserStatus;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AdminGetUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AdminGetUser)」を参照してください。

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_csharp_3_topic"></a>

次のコード例は、`AdminInitiateAuth` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Initiate an admin auth request.
    /// </summary>
    /// <param name="clientId">The client ID to use.</param>
    /// <param name="userPoolId">The ID of the user pool.</param>
    /// <param name="userName">The username to authenticate.</param>
    /// <param name="password">The user's password.</param>
    /// <returns>The session to use in challenge-response.</returns>
    public async Task<string> AdminInitiateAuthAsync(string clientId, string userPoolId, string userName, string password)
    {
        var authParameters = new Dictionary<string, string>();
        authParameters.Add("USERNAME", userName);
        authParameters.Add("PASSWORD", password);

        var request = new AdminInitiateAuthRequest
        {
            ClientId = clientId,
            UserPoolId = userPoolId,
            AuthParameters = authParameters,
            AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
        };

        var response = await _cognitoService.AdminInitiateAuthAsync(request);
        return response.Session;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AdminInitiateAuth](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AdminInitiateAuth)」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_csharp_3_topic"></a>

次のコード例は、`AdminRespondToAuthChallenge` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Respond to an admin authentication challenge.
    /// </summary>
    /// <param name="userName">The name of the user.</param>
    /// <param name="clientId">The client ID.</param>
    /// <param name="mfaCode">The multi-factor authentication code.</param>
    /// <param name="session">The current application session.</param>
    /// <param name="clientId">The user pool ID.</param>
    /// <returns>The result of the authentication response.</returns>
    public async Task<AuthenticationResultType> AdminRespondToAuthChallengeAsync(
        string userName,
        string clientId,
        string mfaCode,
        string session,
        string userPoolId)
    {
        Console.WriteLine("SOFTWARE_TOKEN_MFA challenge is generated");

        var challengeResponses = new Dictionary<string, string>();
        challengeResponses.Add("USERNAME", userName);
        challengeResponses.Add("SOFTWARE_TOKEN_MFA_CODE", mfaCode);

        var respondToAuthChallengeRequest = new AdminRespondToAuthChallengeRequest
        {
            ChallengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA,
            ClientId = clientId,
            ChallengeResponses = challengeResponses,
            Session = session,
            UserPoolId = userPoolId,
        };

        var response = await _cognitoService.AdminRespondToAuthChallengeAsync(respondToAuthChallengeRequest);
        Console.WriteLine($"Response to Authentication {response.AuthenticationResult.TokenType}");
        return response.AuthenticationResult;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)」を参照してください。

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_csharp_3_topic"></a>

次のコード例は、`AssociateSoftwareToken` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get an MFA token to authenticate the user with the authenticator.
    /// </summary>
    /// <param name="session">The session name.</param>
    /// <returns>The session name.</returns>
    public async Task<string> AssociateSoftwareTokenAsync(string session)
    {
        var softwareTokenRequest = new AssociateSoftwareTokenRequest
        {
            Session = session,
        };

        var tokenResponse = await _cognitoService.AssociateSoftwareTokenAsync(softwareTokenRequest);
        var secretCode = tokenResponse.SecretCode;

        Console.WriteLine($"Use the following secret code to set up the authenticator: {secretCode}");

        return tokenResponse.Session;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AssociateSoftwareToken](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AssociateSoftwareToken)」を参照してください。

### `ConfirmDevice`
<a name="cognito-identity-provider_ConfirmDevice_csharp_3_topic"></a>

次のコード例は、`ConfirmDevice` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Initiates and confirms tracking of the device.
    /// </summary>
    /// <param name="accessToken">The user's access token.</param>
    /// <param name="deviceKey">The key of the device from Amazon Cognito.</param>
    /// <param name="deviceName">The device name.</param>
    /// <returns></returns>
    public async Task<bool> ConfirmDeviceAsync(string accessToken, string deviceKey, string deviceName)
    {
        var request = new ConfirmDeviceRequest
        {
            AccessToken = accessToken,
            DeviceKey = deviceKey,
            DeviceName = deviceName
        };

        var response = await _cognitoService.ConfirmDeviceAsync(request);
        return response.UserConfirmationNecessary;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ConfirmDevice](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ConfirmDevice)」を参照してください。

### `ConfirmSignUp`
<a name="cognito-identity-provider_ConfirmSignUp_csharp_3_topic"></a>

次のコード例は、`ConfirmSignUp` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Confirm that the user has signed up.
    /// </summary>
    /// <param name="clientId">The Id of this application.</param>
    /// <param name="code">The confirmation code sent to the user.</param>
    /// <param name="userName">The username.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ConfirmSignupAsync(string clientId, string code, string userName)
    {
        var signUpRequest = new ConfirmSignUpRequest
        {
            ClientId = clientId,
            ConfirmationCode = code,
            Username = userName,
        };

        var response = await _cognitoService.ConfirmSignUpAsync(signUpRequest);
        if (response.HttpStatusCode == HttpStatusCode.OK)
        {
            Console.WriteLine($"{userName} was confirmed");
            return true;
        }
        return false;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ConfirmSignUp](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ConfirmSignUp)」を参照してください。

### `InitiateAuth`
<a name="cognito-identity-provider_InitiateAuth_csharp_3_topic"></a>

次のコード例は、`InitiateAuth` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Initiate authorization.
    /// </summary>
    /// <param name="clientId">The client Id of the application.</param>
    /// <param name="userName">The name of the user who is authenticating.</param>
    /// <param name="password">The password for the user who is authenticating.</param>
    /// <returns>The response from the initiate auth request.</returns>
    public async Task<InitiateAuthResponse> InitiateAuthAsync(string clientId, string userName, string password)
    {
        var authParameters = new Dictionary<string, string>();
        authParameters.Add("USERNAME", userName);
        authParameters.Add("PASSWORD", password);

        var authRequest = new InitiateAuthRequest

        {
            ClientId = clientId,
            AuthParameters = authParameters,
            AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
        };

        var response = await _cognitoService.InitiateAuthAsync(authRequest);
        Console.WriteLine($"Result Challenge is : {response.ChallengeName}");

        return response;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[InitiateAuth](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/InitiateAuth)」を参照してください。

### `ListUsers`
<a name="cognito-identity-provider_ListUsers_csharp_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of users for the Amazon Cognito user pool.
    /// </summary>
    /// <param name="userPoolId">The user pool ID.</param>
    /// <returns>A list of users.</returns>
    public async Task<List<UserType>> ListUsersAsync(string userPoolId)
    {
        var request = new ListUsersRequest
        {
            UserPoolId = userPoolId
        };

        var users = new List<UserType>();

        var usersPaginator = _cognitoService.Paginators.ListUsers(request);
        await foreach (var response in usersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ListUsers)」を参照してください。

### `ResendConfirmationCode`
<a name="cognito-identity-provider_ResendConfirmationCode_csharp_3_topic"></a>

次のコード例は、`ResendConfirmationCode` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Send a new confirmation code to a user.
    /// </summary>
    /// <param name="clientId">The Id of the client application.</param>
    /// <param name="userName">The username of user who will receive the code.</param>
    /// <returns>The delivery details.</returns>
    public async Task<CodeDeliveryDetailsType> ResendConfirmationCodeAsync(string clientId, string userName)
    {
        var codeRequest = new ResendConfirmationCodeRequest
        {
            ClientId = clientId,
            Username = userName,
        };

        var response = await _cognitoService.ResendConfirmationCodeAsync(codeRequest);

        Console.WriteLine($"Method of delivery is {response.CodeDeliveryDetails.DeliveryMedium}");

        return response.CodeDeliveryDetails;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ResendConfirmationCode](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ResendConfirmationCode)」を参照してください。

### `SignUp`
<a name="cognito-identity-provider_SignUp_csharp_3_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Sign up a new user.
    /// </summary>
    /// <param name="clientId">The client Id of the application.</param>
    /// <param name="userName">The username to use.</param>
    /// <param name="password">The user's password.</param>
    /// <param name="email">The email address of the user.</param>
    /// <returns>A Boolean value indicating whether the user was confirmed.</returns>
    public async Task<bool> SignUpAsync(string clientId, string userName, string password, string email)
    {
        var userAttrs = new AttributeType
        {
            Name = "email",
            Value = email,
        };

        var userAttrsList = new List<AttributeType>();

        userAttrsList.Add(userAttrs);

        var signUpRequest = new SignUpRequest
        {
            UserAttributes = userAttrsList,
            Username = userName,
            ClientId = clientId,
            Password = password
        };

        var response = await _cognitoService.SignUpAsync(signUpRequest);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[SignUp](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/SignUp)」を参照してください。

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_csharp_3_topic"></a>

次のコード例は、`VerifySoftwareToken` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Verify the TOTP and register for MFA.
    /// </summary>
    /// <param name="session">The name of the session.</param>
    /// <param name="code">The MFA code.</param>
    /// <returns>The status of the software token.</returns>
    public async Task<VerifySoftwareTokenResponseType> VerifySoftwareTokenAsync(string session, string code)
    {
        var tokenRequest = new VerifySoftwareTokenRequest
        {
            UserCode = code,
            Session = session,
        };

        var verifyResponse = await _cognitoService.VerifySoftwareTokenAsync(tokenRequest);

        return verifyResponse.Status;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[VerifySoftwareToken](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/VerifySoftwareToken)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### MFA を必要とするユーザープールでユーザーをサインアップする
<a name="cognito-identity-provider_Scenario_SignUpUserWithMfa_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。
+ MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。
+ パスワードと MFA コードを使用してサインインします。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Cognito#code-examples)での設定と実行の方法を確認してください。

```
namespace CognitoBasics;

public class CognitoBasics
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon Cognito.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonCognitoIdentityProvider>()
            .AddTransient<CognitoWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<CognitoBasics>();

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        var cognitoWrapper = host.Services.GetRequiredService<CognitoWrapper>();

        Console.WriteLine(new string('-', 80));
        UiMethods.DisplayOverview();
        Console.WriteLine(new string('-', 80));

        // clientId - The app client Id value that you get from the AWS CDK script.
        var clientId = configuration["ClientId"]; // "*** REPLACE WITH CLIENT ID VALUE FROM CDK SCRIPT";

        // poolId - The pool Id that you get from the AWS CDK script.
        var poolId = configuration["PoolId"]!; // "*** REPLACE WITH POOL ID VALUE FROM CDK SCRIPT";
        var userName = configuration["UserName"];
        var password = configuration["Password"];
        var email = configuration["Email"];

        // If the username wasn't set in the configuration file,
        // get it from the user now.
        if (userName is null)
        {
            do
            {
                Console.Write("Username: ");
                userName = Console.ReadLine();
            }
            while (string.IsNullOrEmpty(userName));
        }
        Console.WriteLine($"\nUsername: {userName}");

        // If the password wasn't set in the configuration file,
        // get it from the user now.
        if (password is null)
        {
            do
            {
                Console.Write("Password: ");
                password = Console.ReadLine();
            }
            while (string.IsNullOrEmpty(password));
        }

        // If the email address wasn't set in the configuration file,
        // get it from the user now.
        if (email is null)
        {
            do
            {
                Console.Write("Email: ");
                email = Console.ReadLine();
            } while (string.IsNullOrEmpty(email));
        }

        // Now sign up the user.
        Console.WriteLine($"\nSigning up {userName} with email address: {email}");
        await cognitoWrapper.SignUpAsync(clientId, userName, password, email);

        // Add the user to the user pool.
        Console.WriteLine($"Adding {userName} to the user pool");
        await cognitoWrapper.GetAdminUserAsync(userName, poolId);

        UiMethods.DisplayTitle("Get confirmation code");
        Console.WriteLine($"Conformation code sent to {userName}.");
        Console.Write("Would you like to send a new code? (Y/N) ");
        var answer = Console.ReadLine();

        if (answer!.ToLower() == "y")
        {
            await cognitoWrapper.ResendConfirmationCodeAsync(clientId, userName);
            Console.WriteLine("Sending a new confirmation code");
        }

        Console.Write("Enter confirmation code (from Email): ");
        var code = Console.ReadLine();

        await cognitoWrapper.ConfirmSignupAsync(clientId, code, userName);

        UiMethods.DisplayTitle("Checking status");
        Console.WriteLine($"Rechecking the status of {userName} in the user pool");
        await cognitoWrapper.GetAdminUserAsync(userName, poolId);

        Console.WriteLine($"Setting up authenticator for {userName} in the user pool");
        var setupResponse = await cognitoWrapper.InitiateAuthAsync(clientId, userName, password);

        var setupSession = await cognitoWrapper.AssociateSoftwareTokenAsync(setupResponse.Session);
        Console.Write("Enter the 6-digit code displayed in Google Authenticator: ");
        var setupCode = Console.ReadLine();

        var setupResult = await cognitoWrapper.VerifySoftwareTokenAsync(setupSession, setupCode);
        Console.WriteLine($"Setup status: {setupResult}");

        Console.WriteLine($"Now logging in {userName} in the user pool");
        var authSession = await cognitoWrapper.AdminInitiateAuthAsync(clientId, poolId, userName, password);

        Console.Write("Enter a new 6-digit code displayed in Google Authenticator: ");
        var authCode = Console.ReadLine();

        var authResult = await cognitoWrapper.AdminRespondToAuthChallengeAsync(userName, clientId, authCode, authSession, poolId);
        Console.WriteLine($"Authenticated and received access token: {authResult.AccessToken}");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Cognito scenario is complete.");
        Console.WriteLine(new string('-', 80));
    }
}


using System.Net;

namespace CognitoActions;

/// <summary>
/// Methods to perform Amazon Cognito Identity Provider actions.
/// </summary>
public class CognitoWrapper
{
    private readonly IAmazonCognitoIdentityProvider _cognitoService;

    /// <summary>
    /// Constructor for the wrapper class containing Amazon Cognito actions.
    /// </summary>
    /// <param name="cognitoService">The Amazon Cognito client object.</param>
    public CognitoWrapper(IAmazonCognitoIdentityProvider cognitoService)
    {
        _cognitoService = cognitoService;
    }

    /// <summary>
    /// List the Amazon Cognito user pools for an account.
    /// </summary>
    /// <returns>A list of UserPoolDescriptionType objects.</returns>
    public async Task<List<UserPoolDescriptionType>> ListUserPoolsAsync()
    {
        var userPools = new List<UserPoolDescriptionType>();

        var userPoolsPaginator = _cognitoService.Paginators.ListUserPools(new ListUserPoolsRequest());

        await foreach (var response in userPoolsPaginator.Responses)
        {
            userPools.AddRange(response.UserPools);
        }

        return userPools;
    }


    /// <summary>
    /// Get a list of users for the Amazon Cognito user pool.
    /// </summary>
    /// <param name="userPoolId">The user pool ID.</param>
    /// <returns>A list of users.</returns>
    public async Task<List<UserType>> ListUsersAsync(string userPoolId)
    {
        var request = new ListUsersRequest
        {
            UserPoolId = userPoolId
        };

        var users = new List<UserType>();

        var usersPaginator = _cognitoService.Paginators.ListUsers(request);
        await foreach (var response in usersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }


    /// <summary>
    /// Respond to an admin authentication challenge.
    /// </summary>
    /// <param name="userName">The name of the user.</param>
    /// <param name="clientId">The client ID.</param>
    /// <param name="mfaCode">The multi-factor authentication code.</param>
    /// <param name="session">The current application session.</param>
    /// <param name="clientId">The user pool ID.</param>
    /// <returns>The result of the authentication response.</returns>
    public async Task<AuthenticationResultType> AdminRespondToAuthChallengeAsync(
        string userName,
        string clientId,
        string mfaCode,
        string session,
        string userPoolId)
    {
        Console.WriteLine("SOFTWARE_TOKEN_MFA challenge is generated");

        var challengeResponses = new Dictionary<string, string>();
        challengeResponses.Add("USERNAME", userName);
        challengeResponses.Add("SOFTWARE_TOKEN_MFA_CODE", mfaCode);

        var respondToAuthChallengeRequest = new AdminRespondToAuthChallengeRequest
        {
            ChallengeName = ChallengeNameType.SOFTWARE_TOKEN_MFA,
            ClientId = clientId,
            ChallengeResponses = challengeResponses,
            Session = session,
            UserPoolId = userPoolId,
        };

        var response = await _cognitoService.AdminRespondToAuthChallengeAsync(respondToAuthChallengeRequest);
        Console.WriteLine($"Response to Authentication {response.AuthenticationResult.TokenType}");
        return response.AuthenticationResult;
    }


    /// <summary>
    /// Verify the TOTP and register for MFA.
    /// </summary>
    /// <param name="session">The name of the session.</param>
    /// <param name="code">The MFA code.</param>
    /// <returns>The status of the software token.</returns>
    public async Task<VerifySoftwareTokenResponseType> VerifySoftwareTokenAsync(string session, string code)
    {
        var tokenRequest = new VerifySoftwareTokenRequest
        {
            UserCode = code,
            Session = session,
        };

        var verifyResponse = await _cognitoService.VerifySoftwareTokenAsync(tokenRequest);

        return verifyResponse.Status;
    }


    /// <summary>
    /// Get an MFA token to authenticate the user with the authenticator.
    /// </summary>
    /// <param name="session">The session name.</param>
    /// <returns>The session name.</returns>
    public async Task<string> AssociateSoftwareTokenAsync(string session)
    {
        var softwareTokenRequest = new AssociateSoftwareTokenRequest
        {
            Session = session,
        };

        var tokenResponse = await _cognitoService.AssociateSoftwareTokenAsync(softwareTokenRequest);
        var secretCode = tokenResponse.SecretCode;

        Console.WriteLine($"Use the following secret code to set up the authenticator: {secretCode}");

        return tokenResponse.Session;
    }


    /// <summary>
    /// Initiate an admin auth request.
    /// </summary>
    /// <param name="clientId">The client ID to use.</param>
    /// <param name="userPoolId">The ID of the user pool.</param>
    /// <param name="userName">The username to authenticate.</param>
    /// <param name="password">The user's password.</param>
    /// <returns>The session to use in challenge-response.</returns>
    public async Task<string> AdminInitiateAuthAsync(string clientId, string userPoolId, string userName, string password)
    {
        var authParameters = new Dictionary<string, string>();
        authParameters.Add("USERNAME", userName);
        authParameters.Add("PASSWORD", password);

        var request = new AdminInitiateAuthRequest
        {
            ClientId = clientId,
            UserPoolId = userPoolId,
            AuthParameters = authParameters,
            AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
        };

        var response = await _cognitoService.AdminInitiateAuthAsync(request);
        return response.Session;
    }

    /// <summary>
    /// Initiate authorization.
    /// </summary>
    /// <param name="clientId">The client Id of the application.</param>
    /// <param name="userName">The name of the user who is authenticating.</param>
    /// <param name="password">The password for the user who is authenticating.</param>
    /// <returns>The response from the initiate auth request.</returns>
    public async Task<InitiateAuthResponse> InitiateAuthAsync(string clientId, string userName, string password)
    {
        var authParameters = new Dictionary<string, string>();
        authParameters.Add("USERNAME", userName);
        authParameters.Add("PASSWORD", password);

        var authRequest = new InitiateAuthRequest

        {
            ClientId = clientId,
            AuthParameters = authParameters,
            AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
        };

        var response = await _cognitoService.InitiateAuthAsync(authRequest);
        Console.WriteLine($"Result Challenge is : {response.ChallengeName}");

        return response;
    }

    /// <summary>
    /// Confirm that the user has signed up.
    /// </summary>
    /// <param name="clientId">The Id of this application.</param>
    /// <param name="code">The confirmation code sent to the user.</param>
    /// <param name="userName">The username.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ConfirmSignupAsync(string clientId, string code, string userName)
    {
        var signUpRequest = new ConfirmSignUpRequest
        {
            ClientId = clientId,
            ConfirmationCode = code,
            Username = userName,
        };

        var response = await _cognitoService.ConfirmSignUpAsync(signUpRequest);
        if (response.HttpStatusCode == HttpStatusCode.OK)
        {
            Console.WriteLine($"{userName} was confirmed");
            return true;
        }
        return false;
    }


    /// <summary>
    /// Initiates and confirms tracking of the device.
    /// </summary>
    /// <param name="accessToken">The user's access token.</param>
    /// <param name="deviceKey">The key of the device from Amazon Cognito.</param>
    /// <param name="deviceName">The device name.</param>
    /// <returns></returns>
    public async Task<bool> ConfirmDeviceAsync(string accessToken, string deviceKey, string deviceName)
    {
        var request = new ConfirmDeviceRequest
        {
            AccessToken = accessToken,
            DeviceKey = deviceKey,
            DeviceName = deviceName
        };

        var response = await _cognitoService.ConfirmDeviceAsync(request);
        return response.UserConfirmationNecessary;
    }


    /// <summary>
    /// Send a new confirmation code to a user.
    /// </summary>
    /// <param name="clientId">The Id of the client application.</param>
    /// <param name="userName">The username of user who will receive the code.</param>
    /// <returns>The delivery details.</returns>
    public async Task<CodeDeliveryDetailsType> ResendConfirmationCodeAsync(string clientId, string userName)
    {
        var codeRequest = new ResendConfirmationCodeRequest
        {
            ClientId = clientId,
            Username = userName,
        };

        var response = await _cognitoService.ResendConfirmationCodeAsync(codeRequest);

        Console.WriteLine($"Method of delivery is {response.CodeDeliveryDetails.DeliveryMedium}");

        return response.CodeDeliveryDetails;
    }


    /// <summary>
    /// Get the specified user from an Amazon Cognito user pool with administrator access.
    /// </summary>
    /// <param name="userName">The name of the user.</param>
    /// <param name="poolId">The Id of the Amazon Cognito user pool.</param>
    /// <returns>Async task.</returns>
    public async Task<UserStatusType> GetAdminUserAsync(string userName, string poolId)
    {
        AdminGetUserRequest userRequest = new AdminGetUserRequest
        {
            Username = userName,
            UserPoolId = poolId,
        };

        var response = await _cognitoService.AdminGetUserAsync(userRequest);

        Console.WriteLine($"User status {response.UserStatus}");
        return response.UserStatus;
    }


    /// <summary>
    /// Sign up a new user.
    /// </summary>
    /// <param name="clientId">The client Id of the application.</param>
    /// <param name="userName">The username to use.</param>
    /// <param name="password">The user's password.</param>
    /// <param name="email">The email address of the user.</param>
    /// <returns>A Boolean value indicating whether the user was confirmed.</returns>
    public async Task<bool> SignUpAsync(string clientId, string userName, string password, string email)
    {
        var userAttrs = new AttributeType
        {
            Name = "email",
            Value = email,
        };

        var userAttrsList = new List<AttributeType>();

        userAttrsList.Add(userAttrs);

        var signUpRequest = new SignUpRequest
        {
            UserAttributes = userAttrsList,
            Username = userName,
            ClientId = clientId,
            Password = password
        };

        var response = await _cognitoService.SignUpAsync(signUpRequest);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }

}
```
+ API の詳細については、「AWS SDK for .NET API リファレンス**」の以下のトピックを参照してください。
  + [AdminGetUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AdminGetUser)
  + [AdminInitiateAuth](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AdminInitiateAuth)
  + [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)
  + [AssociateSoftwareToken](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/AssociateSoftwareToken)
  + [ConfirmDevice](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ConfirmDevice)
  + [ConfirmSignUp](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ConfirmSignUp)
  + [InitiateAuth](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/InitiateAuth)
  + [ListUsers](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ListUsers)
  + [ResendConfirmationCode](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/ResendConfirmationCode)
  + [RespondToAuthChallenge](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/RespondToAuthChallenge)
  + [SignUp](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/SignUp)
  + [VerifySoftwareToken](https://docs.aws.amazon.com/goto/DotNetSDKV3/cognito-idp-2016-04-18/VerifySoftwareToken)

# を使用した Amazon Comprehend の例 SDK for .NET
<a name="csharp_3_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DetectDominantLanguage`
<a name="comprehend_DetectDominantLanguage_csharp_3_topic"></a>

次のコード例は、`DetectDominantLanguage` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Comprehend/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Comprehend;
    using Amazon.Comprehend.Model;

    /// <summary>
    /// This example calls the Amazon Comprehend service to determine the
    /// dominant language.
    /// </summary>
    public static class DetectDominantLanguage
    {
        /// <summary>
        /// Calls Amazon Comprehend to determine the dominant language used in
        /// the sample text.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle.";

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            Console.WriteLine("Calling DetectDominantLanguage\n");
            var detectDominantLanguageRequest = new DetectDominantLanguageRequest()
            {
                Text = text,
            };

            var detectDominantLanguageResponse = await comprehendClient.DetectDominantLanguageAsync(detectDominantLanguageRequest);
            foreach (var dl in detectDominantLanguageResponse.Languages)
            {
                Console.WriteLine($"Language Code: {dl.LanguageCode}, Score: {dl.Score}");
            }

            Console.WriteLine("Done");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DetectDominantLanguage](https://docs.aws.amazon.com/goto/DotNetSDKV3/comprehend-2017-11-27/DetectDominantLanguage)」を参照してください。

### `DetectEntities`
<a name="comprehend_DetectEntities_csharp_3_topic"></a>

次のコード例は、`DetectEntities` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Comprehend/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Comprehend;
    using Amazon.Comprehend.Model;

    /// <summary>
    /// This example shows how to use the AmazonComprehend service detect any
    /// entities in submitted text.
    /// </summary>
    public static class DetectEntities
    {
        /// <summary>
        /// The main method calls the DetectEntitiesAsync method to find any
        /// entities in the sample code.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient();

            Console.WriteLine("Calling DetectEntities\n");
            var detectEntitiesRequest = new DetectEntitiesRequest()
            {
                Text = text,
                LanguageCode = "en",
            };
            var detectEntitiesResponse = await comprehendClient.DetectEntitiesAsync(detectEntitiesRequest);

            foreach (var e in detectEntitiesResponse.Entities)
            {
                Console.WriteLine($"Text: {e.Text}, Type: {e.Type}, Score: {e.Score}, BeginOffset: {e.BeginOffset}, EndOffset: {e.EndOffset}");
            }

            Console.WriteLine("Done");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DetectEntities](https://docs.aws.amazon.com/goto/DotNetSDKV3/comprehend-2017-11-27/DetectEntities)」を参照してください。

### `DetectKeyPhrases`
<a name="comprehend_DetectKeyPhrases_csharp_3_topic"></a>

次のコード例は、`DetectKeyPhrases` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Comprehend/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Comprehend;
    using Amazon.Comprehend.Model;

    /// <summary>
    /// This example shows how to use the Amazon Comprehend service to
    /// search text for key phrases.
    /// </summary>
    public static class DetectKeyPhrase
    {
        /// <summary>
        /// This method calls the Amazon Comprehend method DetectKeyPhrasesAsync
        /// to detect any key phrases in the sample text.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            // Call DetectKeyPhrases API
            Console.WriteLine("Calling DetectKeyPhrases");
            var detectKeyPhrasesRequest = new DetectKeyPhrasesRequest()
            {
                Text = text,
                LanguageCode = "en",
            };
            var detectKeyPhrasesResponse = await comprehendClient.DetectKeyPhrasesAsync(detectKeyPhrasesRequest);
            foreach (var kp in detectKeyPhrasesResponse.KeyPhrases)
            {
                Console.WriteLine($"Text: {kp.Text}, Score: {kp.Score}, BeginOffset: {kp.BeginOffset}, EndOffset: {kp.EndOffset}");
            }

            Console.WriteLine("Done");
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DetectKeyPhrases](https://docs.aws.amazon.com/goto/DotNetSDKV3/comprehend-2017-11-27/DetectKeyPhrases)」を参照してください。

### `DetectPiiEntities`
<a name="comprehend_DetectPiiEntities_csharp_3_topic"></a>

次のコード例は、`DetectPiiEntities` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Comprehend/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Comprehend;
    using Amazon.Comprehend.Model;

    /// <summary>
    /// This example shows how to use the Amazon Comprehend service to find
    /// personally identifiable information (PII) within text submitted to the
    /// DetectPiiEntitiesAsync method.
    /// </summary>
    public class DetectingPII
    {
        /// <summary>
        /// This method calls the DetectPiiEntitiesAsync method to locate any
        /// personally dientifiable information within the supplied text.
        /// </summary>
        public static async Task Main()
        {
            var comprehendClient = new AmazonComprehendClient();
            var text = @"Hello Paul Santos. The latest statement for your
                        credit card account 1111-0000-1111-0000 was
                        mailed to 123 Any Street, Seattle, WA 98109.";

            var request = new DetectPiiEntitiesRequest
            {
                Text = text,
                LanguageCode = "EN",
            };

            var response = await comprehendClient.DetectPiiEntitiesAsync(request);

            if (response.Entities.Count > 0)
            {
                foreach (var entity in response.Entities)
                {
                    var entityValue = text.Substring(entity.BeginOffset, entity.EndOffset - entity.BeginOffset);
                    Console.WriteLine($"{entity.Type}: {entityValue}");
                }
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DetectPIIEntities](https://docs.aws.amazon.com/goto/DotNetSDKV3/comprehend-2017-11-27/DetectPiiEntities)」を参照してください。

### `DetectSentiment`
<a name="comprehend_DetectSentiment_csharp_3_topic"></a>

次のコード例は、`DetectSentiment` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Comprehend/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Comprehend;
    using Amazon.Comprehend.Model;

    /// <summary>
    /// This example shows how to detect the overall sentiment of the supplied
    /// text using the Amazon Comprehend service.
    /// </summary>
    public static class DetectSentiment
    {
        /// <summary>
        /// This method calls the DetetectSentimentAsync method to analyze the
        /// supplied text and determine the overal sentiment.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient(Amazon.RegionEndpoint.USWest2);

            // Call DetectKeyPhrases API
            Console.WriteLine("Calling DetectSentiment");
            var detectSentimentRequest = new DetectSentimentRequest()
            {
                Text = text,
                LanguageCode = "en",
            };
            var detectSentimentResponse = await comprehendClient.DetectSentimentAsync(detectSentimentRequest);
            Console.WriteLine($"Sentiment: {detectSentimentResponse.Sentiment}");
            Console.WriteLine("Done");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DetectSentiment](https://docs.aws.amazon.com/goto/DotNetSDKV3/comprehend-2017-11-27/DetectSentiment)」を参照してください。

### `DetectSyntax`
<a name="comprehend_DetectSyntax_csharp_3_topic"></a>

次のコード例は、`DetectSyntax` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Comprehend/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Comprehend;
    using Amazon.Comprehend.Model;

    /// <summary>
    /// This example shows how to use Amazon Comprehend to detect syntax
    /// elements by calling the DetectSyntaxAsync method.
    /// </summary>
    public class DetectingSyntax
    {
        /// <summary>
        /// This method calls DetectSynaxAsync to identify the syntax elements
        /// in the sample text.
        /// </summary>
        public static async Task Main()
        {
            string text = "It is raining today in Seattle";

            var comprehendClient = new AmazonComprehendClient();

            // Call DetectSyntax API
            Console.WriteLine("Calling DetectSyntaxAsync\n");
            var detectSyntaxRequest = new DetectSyntaxRequest()
            {
                Text = text,
                LanguageCode = "en",
            };
            DetectSyntaxResponse detectSyntaxResponse = await comprehendClient.DetectSyntaxAsync(detectSyntaxRequest);
            foreach (SyntaxToken s in detectSyntaxResponse.SyntaxTokens)
            {
                Console.WriteLine($"Text: {s.Text}, PartOfSpeech: {s.PartOfSpeech.Tag}, BeginOffset: {s.BeginOffset}, EndOffset: {s.EndOffset}");
            }

            Console.WriteLine("Done");
        }
    }
```
+  API の詳細については、「[AWS SDK for .NET API リファレンス](https://docs.aws.amazon.com/goto/DotNetSDKV3/comprehend-2017-11-27/DetectSyntax)」の「*DetectSyntax*」を参照してください。

### `StartTopicsDetectionJob`
<a name="comprehend_StartTopicsDetectionJob_csharp_3_topic"></a>

次のコード例は、`StartTopicsDetectionJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Comprehend/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Comprehend;
    using Amazon.Comprehend.Model;

    /// <summary>
    /// This example scans the documents in an Amazon Simple Storage Service
    /// (Amazon S3) bucket and analyzes it for topics. The results are stored
    /// in another bucket and then the resulting job properties are displayed
    /// on the screen. This example was created using the AWS SDK for .NEt
    /// version 3.7 and .NET Core version 5.0.
    /// </summary>
    public static class TopicModeling
    {
        /// <summary>
        /// This methos calls a topic detection job by calling the Amazon
        /// Comprehend StartTopicsDetectionJobRequest.
        /// </summary>
        public static async Task Main()
        {
            var comprehendClient = new AmazonComprehendClient();

            string inputS3Uri = "s3://input bucket/input path";
            InputFormat inputDocFormat = InputFormat.ONE_DOC_PER_FILE;
            string outputS3Uri = "s3://output bucket/output path";
            string dataAccessRoleArn = "arn:aws:iam::account ID:role/data access role";
            int numberOfTopics = 10;

            var startTopicsDetectionJobRequest = new StartTopicsDetectionJobRequest()
            {
                InputDataConfig = new InputDataConfig()
                {
                    S3Uri = inputS3Uri,
                    InputFormat = inputDocFormat,
                },
                OutputDataConfig = new OutputDataConfig()
                {
                    S3Uri = outputS3Uri,
                },
                DataAccessRoleArn = dataAccessRoleArn,
                NumberOfTopics = numberOfTopics,
            };

            var startTopicsDetectionJobResponse = await comprehendClient.StartTopicsDetectionJobAsync(startTopicsDetectionJobRequest);

            var jobId = startTopicsDetectionJobResponse.JobId;
            Console.WriteLine("JobId: " + jobId);

            var describeTopicsDetectionJobRequest = new DescribeTopicsDetectionJobRequest()
            {
                JobId = jobId,
            };

            var describeTopicsDetectionJobResponse = await comprehendClient.DescribeTopicsDetectionJobAsync(describeTopicsDetectionJobRequest);
            PrintJobProperties(describeTopicsDetectionJobResponse.TopicsDetectionJobProperties);

            var listTopicsDetectionJobsResponse = await comprehendClient.ListTopicsDetectionJobsAsync(new ListTopicsDetectionJobsRequest());
            foreach (var props in listTopicsDetectionJobsResponse.TopicsDetectionJobPropertiesList)
            {
                PrintJobProperties(props);
            }
        }

        /// <summary>
        /// This method is a helper method that displays the job properties
        /// from the call to StartTopicsDetectionJobRequest.
        /// </summary>
        /// <param name="props">A list of properties from the call to
        /// StartTopicsDetectionJobRequest.</param>
        private static void PrintJobProperties(TopicsDetectionJobProperties props)
        {
            Console.WriteLine($"JobId: {props.JobId}, JobName: {props.JobName}, JobStatus: {props.JobStatus}");
            Console.WriteLine($"NumberOfTopics: {props.NumberOfTopics}\nInputS3Uri: {props.InputDataConfig.S3Uri}");
            Console.WriteLine($"InputFormat: {props.InputDataConfig.InputFormat}, OutputS3Uri: {props.OutputDataConfig.S3Uri}");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[StartTopicsDetectionJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/comprehend-2017-11-27/StartTopicsDetectionJob)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_csharp_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for .NET**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/FeedbackSentimentAnalyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# を使用した Amazon DocumentDB の例 SDK for .NET
<a name="csharp_3_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_csharp_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Amazon DocumentDB イベントの消費。  

```
using Amazon.Lambda.Core;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
//Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace LambdaDocDb;

public class Function
{
    
     /// <summary>
    /// Lambda function entry point to process Amazon DocumentDB events.
    /// </summary>
    /// <param name="event">The Amazon DocumentDB event.</param>
    /// <param name="context">The Lambda context object.</param>
    /// <returns>A string to indicate successful processing.</returns>
    public string FunctionHandler(Event evnt, ILambdaContext context)
    {
        
        foreach (var record in evnt.Events)
        {
            ProcessDocumentDBEvent(record, context);
        }

        return "OK";
    }

     private void ProcessDocumentDBEvent(DocumentDBEventRecord record, ILambdaContext context)
    {
        
        var eventData = record.Event;
        var operationType = eventData.OperationType;
        var databaseName = eventData.Ns.Db;
        var collectionName = eventData.Ns.Coll;
        var fullDocument = JsonSerializer.Serialize(eventData.FullDocument, new JsonSerializerOptions { WriteIndented = true });

        context.Logger.LogLine($"Operation type: {operationType}");
        context.Logger.LogLine($"Database: {databaseName}");
        context.Logger.LogLine($"Collection: {collectionName}");
        context.Logger.LogLine($"Full document:\n{fullDocument}");
    }



    public class Event
    {
        [JsonPropertyName("eventSourceArn")]
        public string EventSourceArn { get; set; }

        [JsonPropertyName("events")]
        public List<DocumentDBEventRecord> Events { get; set; }

        [JsonPropertyName("eventSource")]
        public string EventSource { get; set; }
    }

    public class DocumentDBEventRecord
    {
        [JsonPropertyName("event")]
        public EventData Event { get; set; }
    }

    public class EventData
    {
        [JsonPropertyName("_id")]
        public IdData Id { get; set; }

        [JsonPropertyName("clusterTime")]
        public ClusterTime ClusterTime { get; set; }

        [JsonPropertyName("documentKey")]
        public DocumentKey DocumentKey { get; set; }

        [JsonPropertyName("fullDocument")]
        public Dictionary<string, object> FullDocument { get; set; }

        [JsonPropertyName("ns")]
        public Namespace Ns { get; set; }

        [JsonPropertyName("operationType")]
        public string OperationType { get; set; }
    }

    public class IdData
    {
        [JsonPropertyName("_data")]
        public string Data { get; set; }
    }

    public class ClusterTime
    {
        [JsonPropertyName("$timestamp")]
        public Timestamp Timestamp { get; set; }
    }

    public class Timestamp
    {
        [JsonPropertyName("t")]
        public long T { get; set; }

        [JsonPropertyName("i")]
        public int I { get; set; }
    }

    public class DocumentKey
    {
        [JsonPropertyName("_id")]
        public Id Id { get; set; }
    }

    public class Id
    {
        [JsonPropertyName("$oid")]
        public string Oid { get; set; }
    }

    public class Namespace
    {
        [JsonPropertyName("db")]
        public string Db { get; set; }

        [JsonPropertyName("coll")]
        public string Coll { get; set; }
    }
}
```

# を使用した DynamoDB の例 SDK for .NET
<a name="csharp_3_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## アクション
<a name="actions"></a>

### `BatchExecuteStatement`
<a name="dynamodb_BatchExecuteStatement_csharp_3_topic"></a>

次のコード例は、`BatchExecuteStatement` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb#code-examples)での設定と実行の方法を確認してください。
INSERT ステートメントのバッチを使用して項目を追加します。  

```
        /// <summary>
        /// Inserts movies imported from a JSON file into the movie table by
        /// using an Amazon DynamoDB PartiQL INSERT statement.
        /// </summary>
        /// <param name="tableName">The name of the table into which the movie
        /// information will be inserted.</param>
        /// <param name="movieFileName">The name of the JSON file that contains
        /// movie information.</param>
        /// <returns>A Boolean value that indicates the success or failure of
        /// the insert operation.</returns>
        public static async Task<bool> InsertMovies(string tableName, string movieFileName)
        {
            // Get the list of movies from the JSON file.
            var movies = ImportMovies(movieFileName);

            var success = false;

            if (movies is not null)
            {
                // Insert the movies in a batch using PartiQL. Because the
                // batch can contain a maximum of 25 items, insert 25 movies
                // at a time.
                string insertBatch = $"INSERT INTO {tableName} VALUE {{'title': ?, 'year': ?}}";
                var statements = new List<BatchStatementRequest>();

                try
                {
                    for (var indexOffset = 0; indexOffset < 250; indexOffset += 25)
                    {
                        for (var i = indexOffset; i < indexOffset + 25; i++)
                        {
                            statements.Add(new BatchStatementRequest
                            {
                                Statement = insertBatch,
                                Parameters = new List<AttributeValue>
                                {
                                    new AttributeValue { S = movies[i].Title },
                                    new AttributeValue { N = movies[i].Year.ToString() },
                                },
                            });
                        }

                        var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
                        {
                            Statements = statements,
                        });

                        // Wait between batches for movies to be successfully added.
                        System.Threading.Thread.Sleep(3000);

                        success = response.HttpStatusCode == System.Net.HttpStatusCode.OK;

                        // Clear the list of statements for the next batch.
                        statements.Clear();
                    }
                }
                catch (AmazonDynamoDBException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            return success;
        }

        /// <summary>
        /// Loads the contents of a JSON file into a list of movies to be
        /// added to the DynamoDB table.
        /// </summary>
        /// <param name="movieFileName">The full path to the JSON file.</param>
        /// <returns>A generic list of movie objects.</returns>
        public static List<Movie> ImportMovies(string movieFileName)
        {
            if (!File.Exists(movieFileName))
            {
                return null!;
            }

            using var sr = new StreamReader(movieFileName);
            string json = sr.ReadToEnd();
            var allMovies = JsonConvert.DeserializeObject<List<Movie>>(json);

            if (allMovies is not null)
            {
                // Return the first 250 entries.
                return allMovies.GetRange(0, 250);
            }
            else
            {
                return null!;
            }
        }
```
SELECT ステートメントのバッチを使用して項目を取得します。  

```
        /// <summary>
        /// Gets movies from the movie table by
        /// using an Amazon DynamoDB PartiQL SELECT statement.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="title1">The title of the first movie.</param>
        /// <param name="title2">The title of the second movie.</param>
        /// <param name="year1">The year of the first movie.</param>
        /// <param name="year2">The year of the second movie.</param>
        /// <returns>True if successful.</returns>
        public static async Task<bool> GetBatch(
            string tableName,
            string title1,
            string title2,
            int year1,
            int year2)
        {
            var getBatch = $"SELECT * FROM {tableName} WHERE title = ? AND year = ?";
            var statements = new List<BatchStatementRequest>
            {
                new BatchStatementRequest
                {
                    Statement = getBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title1 },
                        new AttributeValue { N = year1.ToString() },
                    },
                },

                new BatchStatementRequest
                {
                    Statement = getBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title2 },
                        new AttributeValue { N = year2.ToString() },
                    },
                }
            };

            var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
            {
                Statements = statements,
            });

            if (response.Responses.Count > 0)
            {
                response.Responses.ForEach(r =>
                {
                    if (r.Item.Any())
                    {
                        Console.WriteLine($"{r.Item["title"]}\t{r.Item["year"]}");
                    }
                });
                return true;
            }
            else
            {
                Console.WriteLine($"Couldn't find either {title1} or {title2}.");
                return false;
            }

        }
```
UPDATE ステートメントのバッチを使用して項目を更新します。  

```
        /// <summary>
        /// Updates information for multiple movies.
        /// </summary>
        /// <param name="tableName">The name of the table containing the
        /// movies to be updated.</param>
        /// <param name="producer1">The producer name for the first movie
        /// to update.</param>
        /// <param name="title1">The title of the first movie.</param>
        /// <param name="year1">The year that the first movie was released.</param>
        /// <param name="producer2">The producer name for the second
        /// movie to update.</param>
        /// <param name="title2">The title of the second movie.</param>
        /// <param name="year2">The year that the second movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the update.</returns>
        public static async Task<bool> UpdateBatch(
            string tableName,
            string producer1,
            string title1,
            int year1,
            string producer2,
            string title2,
            int year2)
        {

            string updateBatch = $"UPDATE {tableName} SET Producer=? WHERE title = ? AND year = ?";
            var statements = new List<BatchStatementRequest>
            {
                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = producer1 },
                        new AttributeValue { S = title1 },
                        new AttributeValue { N = year1.ToString() },
                    },
                },

                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = producer2 },
                        new AttributeValue { S = title2 },
                        new AttributeValue { N = year2.ToString() },
                    },
                }
            };

            var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
            {
                Statements = statements,
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
```
DELETE ステートメントのバッチを使用して項目を削除します。  

```
        /// <summary>
        /// Deletes multiple movies using a PartiQL BatchExecuteAsync
        /// statement.
        /// </summary>
        /// <param name="tableName">The name of the table containing the
        /// moves that will be deleted.</param>
        /// <param name="title1">The title of the first movie.</param>
        /// <param name="year1">The year the first movie was released.</param>
        /// <param name="title2">The title of the second movie.</param>
        /// <param name="year2">The year the second movie was released.</param>
        /// <returns>A Boolean value indicating the success of the operation.</returns>
        public static async Task<bool> DeleteBatch(
            string tableName,
            string title1,
            int year1,
            string title2,
            int year2)
        {

            string updateBatch = $"DELETE FROM {tableName} WHERE title = ? AND year = ?";
            var statements = new List<BatchStatementRequest>
            {
                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title1 },
                        new AttributeValue { N = year1.ToString() },
                    },
                },

                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title2 },
                        new AttributeValue { N = year2.ToString() },
                    },
                }
            };

            var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
            {
                Statements = statements,
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_csharp_3_topic"></a>

次のコード例は、`BatchGetItem` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
using System;
using System.Collections.Generic;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;

namespace LowLevelBatchGet
{
    public class LowLevelBatchGet
    {
        private static readonly string _table1Name = "Forum";
        private static readonly string _table2Name = "Thread";

        public static async void RetrieveMultipleItemsBatchGet(AmazonDynamoDBClient client)
        {
            var request = new BatchGetItemRequest
            {
                RequestItems = new Dictionary<string, KeysAndAttributes>()
            {
                { _table1Name,
                  new KeysAndAttributes
                  {
                      Keys = new List<Dictionary<string, AttributeValue> >()
                      {
                          new Dictionary<string, AttributeValue>()
                          {
                              { "Name", new AttributeValue {
                            S = "Amazon DynamoDB"
                        } }
                          },
                          new Dictionary<string, AttributeValue>()
                          {
                              { "Name", new AttributeValue {
                            S = "Amazon S3"
                        } }
                          }
                      }
                  }},
                {
                    _table2Name,
                    new KeysAndAttributes
                    {
                        Keys = new List<Dictionary<string, AttributeValue> >()
                        {
                            new Dictionary<string, AttributeValue>()
                            {
                                { "ForumName", new AttributeValue {
                                      S = "Amazon DynamoDB"
                                  } },
                                { "Subject", new AttributeValue {
                                      S = "DynamoDB Thread 1"
                                  } }
                            },
                            new Dictionary<string, AttributeValue>()
                            {
                                { "ForumName", new AttributeValue {
                                      S = "Amazon DynamoDB"
                                  } },
                                { "Subject", new AttributeValue {
                                      S = "DynamoDB Thread 2"
                                  } }
                            },
                            new Dictionary<string, AttributeValue>()
                            {
                                { "ForumName", new AttributeValue {
                                      S = "Amazon S3"
                                  } },
                                { "Subject", new AttributeValue {
                                      S = "S3 Thread 1"
                                  } }
                            }
                        }
                    }
                }
            }
            };

            BatchGetItemResponse response;
            do
            {
                Console.WriteLine("Making request");
                response = await client.BatchGetItemAsync(request);

                // Check the response.
                var responses = response.Responses; // Attribute list in the response.

                foreach (var tableResponse in responses)
                {
                    var tableResults = tableResponse.Value;
                    Console.WriteLine("Items retrieved from table {0}", tableResponse.Key);
                    foreach (var item1 in tableResults)
                    {
                        PrintItem(item1);
                    }
                }

                // Any unprocessed keys? could happen if you exceed ProvisionedThroughput or some other error.
                Dictionary<string, KeysAndAttributes> unprocessedKeys = response.UnprocessedKeys;
                foreach (var unprocessedTableKeys in unprocessedKeys)
                {
                    // Print table name.
                    Console.WriteLine(unprocessedTableKeys.Key);
                    // Print unprocessed primary keys.
                    foreach (var key in unprocessedTableKeys.Value.Keys)
                    {
                        PrintItem(key);
                    }
                }

                request.RequestItems = unprocessedKeys;
            } while (response.UnprocessedKeys.Count > 0);
        }

        private static void PrintItem(Dictionary<string, AttributeValue> attributeList)
        {
            foreach (KeyValuePair<string, AttributeValue> kvp in attributeList)
            {
                string attributeName = kvp.Key;
                AttributeValue value = kvp.Value;

                Console.WriteLine(
                    attributeName + " " +
                    (value.S == null ? "" : "S=[" + value.S + "]") +
                    (value.N == null ? "" : "N=[" + value.N + "]") +
                    (value.SS == null ? "" : "SS=[" + string.Join(",", value.SS.ToArray()) + "]") +
                    (value.NS == null ? "" : "NS=[" + string.Join(",", value.NS.ToArray()) + "]")
                    );
            }
            Console.WriteLine("************************************************");
        }

        static void Main()
        {
            var client = new AmazonDynamoDBClient();

            RetrieveMultipleItemsBatchGet(client);
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[BatchGetItem](https://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/BatchGetItem)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_csharp_3_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    private static async Task GetTableInformation()
    {
        Console.WriteLine("\n*** Retrieving table information ***");

        var response = await Client.DescribeTableAsync(new DescribeTableRequest
        {
            TableName = ExampleTableName
        });

        var table = response.Table;
        Console.WriteLine($"Name: {table.TableName}");
        Console.WriteLine($"# of items: {table.ItemCount}");

    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[DescribeTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/DescribeTable)」を参照してください。

### `ExecuteStatement`
<a name="dynamodb_ExecuteStatement_csharp_3_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb#code-examples)での設定と実行の方法を確認してください。
INSERT ステートメントを使用して項目を追加します。  

```
        /// <summary>
        /// Inserts a single movie into the movies table.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="movieTitle">The title of the movie to insert.</param>
        /// <param name="year">The year that the movie was released.</param>
        /// <returns>A Boolean value that indicates the success or failure of
        /// the INSERT operation.</returns>
        public static async Task<bool> InsertSingleMovie(string tableName, string movieTitle, int year)
        {
            string insertBatch = $"INSERT INTO {tableName} VALUE {{'title': ?, 'year': ?}}";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = insertBatch,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
```
SELECT ステートメントを使用して項目を取得します。  

```
        /// <summary>
        /// Uses a PartiQL SELECT statement to retrieve a single movie from the
        /// movie database.
        /// </summary>
        /// <param name="tableName">The name of the movie table.</param>
        /// <param name="movieTitle">The title of the movie to retrieve.</param>
        /// <returns>A list of movie data. If no movie matches the supplied
        /// title, the list is empty.</returns>
        public static async Task<List<Dictionary<string, AttributeValue>>> GetSingleMovie(string tableName, string movieTitle)
        {
            string selectSingle = $"SELECT * FROM {tableName} WHERE title = ?";
            var parameters = new List<AttributeValue>
            {
                new AttributeValue { S = movieTitle },
            };

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = selectSingle,
                Parameters = parameters,
            });

            return response.Items;
        }
```
SELECT ステートメントを使用して項目の一覧を取得します。  

```
        /// <summary>
        /// Retrieve multiple movies by year using a SELECT statement.
        /// </summary>
        /// <param name="tableName">The name of the movie table.</param>
        /// <param name="year">The year the movies were released.</param>
        /// <returns></returns>
        public static async Task<List<Dictionary<string, AttributeValue>>> GetMovies(string tableName, int year)
        {
            string selectSingle = $"SELECT * FROM {tableName} WHERE year = ?";
            var parameters = new List<AttributeValue>
            {
                new AttributeValue { N = year.ToString() },
            };

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = selectSingle,
                Parameters = parameters,
            });

            return response.Items;
        }
```
UPDATE ステートメントを使用して項目を更新します。  

```
        /// <summary>
        /// Updates a single movie in the table, adding information for the
        /// producer.
        /// </summary>
        /// <param name="tableName">the name of the table.</param>
        /// <param name="producer">The name of the producer.</param>
        /// <param name="movieTitle">The movie title.</param>
        /// <param name="year">The year the movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the
        /// UPDATE operation.</returns>
        public static async Task<bool> UpdateSingleMovie(string tableName, string producer, string movieTitle, int year)
        {
            string insertSingle = $"UPDATE {tableName} SET Producer=? WHERE title = ? AND year = ?";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = insertSingle,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = producer },
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
```
DELETE ステートメントを使用して映画を 1 つ削除します。  

```
        /// <summary>
        /// Deletes a single movie from the table.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="movieTitle">The title of the movie to delete.</param>
        /// <param name="year">The year that the movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the
        /// DELETE operation.</returns>
        public static async Task<bool> DeleteSingleMovie(string tableName, string movieTitle, int year)
        {
            var deleteSingle = $"DELETE FROM {tableName} WHERE title = ? AND year = ?";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = deleteSingle,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[ExecuteStatement](https://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_csharp_3_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    private static async Task ListMyTables()
    {
        Console.WriteLine("\n*** Listing tables ***");

        string lastTableNameEvaluated = null;
        do
        {
            var response = await Client.ListTablesAsync(new ListTablesRequest
            {
                Limit = 2,
                ExclusiveStartTableName = lastTableNameEvaluated
            });

            foreach (var name in response.TableNames)
            {
                Console.WriteLine(name);
            }

            lastTableNameEvaluated = response.LastEvaluatedTableName;
        } while (lastTableNameEvaluated != null);
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListTables](https://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/ListTables)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_csharp_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for .NET**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_csharp_3_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 Amazon DynamoDB .NET API を使用して、DynamoDB 作業データを追跡する動的ウェブアプリケーションを作成する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/DynamoDbItemTracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_csharp_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Before you run this example, download 'movies.json' from
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.02.html,
// and put it in the same folder as the example.

// Separator for the console display.
var SepBar = new string('-', 80);
const string tableName = "movie_table";
const string movieFileName = @"..\..\..\..\..\..\..\..\resources\sample_files\movies.json";

DisplayInstructions();

// Create the table and wait for it to be active.
Console.WriteLine($"Creating the movie table: {tableName}");

var success = await DynamoDBMethods.CreateMovieTableAsync(tableName);
if (success)
{
    Console.WriteLine($"Successfully created table: {tableName}.");
}

WaitForEnter();

// Add movie information to the table from moviedata.json. See the
// instructions at the top of this file to download the JSON file.
Console.WriteLine($"Inserting movies into the new table. Please wait...");
success = await PartiQLBatchMethods.InsertMovies(tableName, movieFileName);
if (success)
{
    Console.WriteLine("Movies successfully added to the table.");
}
else
{
    Console.WriteLine("Movies could not be added to the table.");
}

WaitForEnter();

// Update multiple movies by using the BatchExecute statement.
var title1 = "Star Wars";
var year1 = 1977;
var title2 = "Wizard of Oz";
var year2 = 1939;

Console.WriteLine($"Updating two movies with producer information: {title1} and {title2}.");
success = await PartiQLBatchMethods.GetBatch(tableName, title1, title2, year1, year2);
if (success)
{
    Console.WriteLine($"Successfully retrieved {title1} and {title2}.");
}
else
{
    Console.WriteLine("Select statement failed.");
}

WaitForEnter();

// Update multiple movies by using the BatchExecute statement.
var producer1 = "LucasFilm";
var producer2 = "MGM";

Console.WriteLine($"Updating two movies with producer information: {title1} and {title2}.");
success = await PartiQLBatchMethods.UpdateBatch(tableName, producer1, title1, year1, producer2, title2, year2);
if (success)
{
    Console.WriteLine($"Successfully updated {title1} and {title2}.");
}
else
{
    Console.WriteLine("Update failed.");
}

WaitForEnter();

// Delete multiple movies by using the BatchExecute statement.
Console.WriteLine($"Now we will delete {title1} and {title2} from the table.");
success = await PartiQLBatchMethods.DeleteBatch(tableName, title1, year1, title2, year2);

if (success)
{
    Console.WriteLine($"Deleted {title1} and {title2}");
}
else
{
    Console.WriteLine($"could not delete {title1} or {title2}");
}

WaitForEnter();

// DNow that the PartiQL Batch scenario is complete, delete the movie table.
success = await DynamoDBMethods.DeleteTableAsync(tableName);

if (success)
{
    Console.WriteLine($"Successfully deleted {tableName}");
}
else
{
    Console.WriteLine($"Could not delete {tableName}");
}

/// <summary>
/// Displays the description of the application on the console.
/// </summary>
void DisplayInstructions()
{
    Console.Clear();
    Console.WriteLine();
    Console.Write(new string(' ', 24));
    Console.WriteLine("DynamoDB PartiQL Basics Example");
    Console.WriteLine(SepBar);
    Console.WriteLine("This demo application shows the basics of using Amazon DynamoDB with the AWS SDK for");
    Console.WriteLine(".NET version 3.7 and .NET 6.");
    Console.WriteLine(SepBar);
    Console.WriteLine("Creates a table by using the CreateTable method.");
    Console.WriteLine("Gets multiple movies by using a PartiQL SELECT statement.");
    Console.WriteLine("Updates multiple movies by using the ExecuteBatch method.");
    Console.WriteLine("Deletes multiple movies by using a PartiQL DELETE statement.");
    Console.WriteLine("Cleans up the resources created for the demo by deleting the table.");
    Console.WriteLine(SepBar);

    WaitForEnter();
}

/// <summary>
/// Simple method to wait for the <Enter> key to be pressed.
/// </summary>
void WaitForEnter()
{
    Console.WriteLine("\nPress <Enter> to continue.");
    Console.Write(SepBar);
    _ = Console.ReadLine();
}


        /// <summary>
        /// Gets movies from the movie table by
        /// using an Amazon DynamoDB PartiQL SELECT statement.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="title1">The title of the first movie.</param>
        /// <param name="title2">The title of the second movie.</param>
        /// <param name="year1">The year of the first movie.</param>
        /// <param name="year2">The year of the second movie.</param>
        /// <returns>True if successful.</returns>
        public static async Task<bool> GetBatch(
            string tableName,
            string title1,
            string title2,
            int year1,
            int year2)
        {
            var getBatch = $"SELECT * FROM {tableName} WHERE title = ? AND year = ?";
            var statements = new List<BatchStatementRequest>
            {
                new BatchStatementRequest
                {
                    Statement = getBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title1 },
                        new AttributeValue { N = year1.ToString() },
                    },
                },

                new BatchStatementRequest
                {
                    Statement = getBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title2 },
                        new AttributeValue { N = year2.ToString() },
                    },
                }
            };

            var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
            {
                Statements = statements,
            });

            if (response.Responses.Count > 0)
            {
                response.Responses.ForEach(r =>
                {
                    if (r.Item.Any())
                    {
                        Console.WriteLine($"{r.Item["title"]}\t{r.Item["year"]}");
                    }
                });
                return true;
            }
            else
            {
                Console.WriteLine($"Couldn't find either {title1} or {title2}.");
                return false;
            }

        }

        /// <summary>
        /// Inserts movies imported from a JSON file into the movie table by
        /// using an Amazon DynamoDB PartiQL INSERT statement.
        /// </summary>
        /// <param name="tableName">The name of the table into which the movie
        /// information will be inserted.</param>
        /// <param name="movieFileName">The name of the JSON file that contains
        /// movie information.</param>
        /// <returns>A Boolean value that indicates the success or failure of
        /// the insert operation.</returns>
        public static async Task<bool> InsertMovies(string tableName, string movieFileName)
        {
            // Get the list of movies from the JSON file.
            var movies = ImportMovies(movieFileName);

            var success = false;

            if (movies is not null)
            {
                // Insert the movies in a batch using PartiQL. Because the
                // batch can contain a maximum of 25 items, insert 25 movies
                // at a time.
                string insertBatch = $"INSERT INTO {tableName} VALUE {{'title': ?, 'year': ?}}";
                var statements = new List<BatchStatementRequest>();

                try
                {
                    for (var indexOffset = 0; indexOffset < 250; indexOffset += 25)
                    {
                        for (var i = indexOffset; i < indexOffset + 25; i++)
                        {
                            statements.Add(new BatchStatementRequest
                            {
                                Statement = insertBatch,
                                Parameters = new List<AttributeValue>
                                {
                                    new AttributeValue { S = movies[i].Title },
                                    new AttributeValue { N = movies[i].Year.ToString() },
                                },
                            });
                        }

                        var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
                        {
                            Statements = statements,
                        });

                        // Wait between batches for movies to be successfully added.
                        System.Threading.Thread.Sleep(3000);

                        success = response.HttpStatusCode == System.Net.HttpStatusCode.OK;

                        // Clear the list of statements for the next batch.
                        statements.Clear();
                    }
                }
                catch (AmazonDynamoDBException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            return success;
        }

        /// <summary>
        /// Loads the contents of a JSON file into a list of movies to be
        /// added to the DynamoDB table.
        /// </summary>
        /// <param name="movieFileName">The full path to the JSON file.</param>
        /// <returns>A generic list of movie objects.</returns>
        public static List<Movie> ImportMovies(string movieFileName)
        {
            if (!File.Exists(movieFileName))
            {
                return null!;
            }

            using var sr = new StreamReader(movieFileName);
            string json = sr.ReadToEnd();
            var allMovies = JsonConvert.DeserializeObject<List<Movie>>(json);

            if (allMovies is not null)
            {
                // Return the first 250 entries.
                return allMovies.GetRange(0, 250);
            }
            else
            {
                return null!;
            }
        }

        /// <summary>
        /// Updates information for multiple movies.
        /// </summary>
        /// <param name="tableName">The name of the table containing the
        /// movies to be updated.</param>
        /// <param name="producer1">The producer name for the first movie
        /// to update.</param>
        /// <param name="title1">The title of the first movie.</param>
        /// <param name="year1">The year that the first movie was released.</param>
        /// <param name="producer2">The producer name for the second
        /// movie to update.</param>
        /// <param name="title2">The title of the second movie.</param>
        /// <param name="year2">The year that the second movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the update.</returns>
        public static async Task<bool> UpdateBatch(
            string tableName,
            string producer1,
            string title1,
            int year1,
            string producer2,
            string title2,
            int year2)
        {

            string updateBatch = $"UPDATE {tableName} SET Producer=? WHERE title = ? AND year = ?";
            var statements = new List<BatchStatementRequest>
            {
                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = producer1 },
                        new AttributeValue { S = title1 },
                        new AttributeValue { N = year1.ToString() },
                    },
                },

                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = producer2 },
                        new AttributeValue { S = title2 },
                        new AttributeValue { N = year2.ToString() },
                    },
                }
            };

            var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
            {
                Statements = statements,
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }

        /// <summary>
        /// Deletes multiple movies using a PartiQL BatchExecuteAsync
        /// statement.
        /// </summary>
        /// <param name="tableName">The name of the table containing the
        /// moves that will be deleted.</param>
        /// <param name="title1">The title of the first movie.</param>
        /// <param name="year1">The year the first movie was released.</param>
        /// <param name="title2">The title of the second movie.</param>
        /// <param name="year2">The year the second movie was released.</param>
        /// <returns>A Boolean value indicating the success of the operation.</returns>
        public static async Task<bool> DeleteBatch(
            string tableName,
            string title1,
            int year1,
            string title2,
            int year2)
        {

            string updateBatch = $"DELETE FROM {tableName} WHERE title = ? AND year = ?";
            var statements = new List<BatchStatementRequest>
            {
                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title1 },
                        new AttributeValue { N = year1.ToString() },
                    },
                },

                new BatchStatementRequest
                {
                    Statement = updateBatch,
                    Parameters = new List<AttributeValue>
                    {
                        new AttributeValue { S = title2 },
                        new AttributeValue { N = year2.ToString() },
                    },
                }
            };

            var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
            {
                Statements = statements,
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」**の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_csharp_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
namespace PartiQL_Basics_Scenario
{
    public class PartiQLMethods
    {
        private static readonly AmazonDynamoDBClient Client = new AmazonDynamoDBClient();


        /// <summary>
        /// Inserts movies imported from a JSON file into the movie table by
        /// using an Amazon DynamoDB PartiQL INSERT statement.
        /// </summary>
        /// <param name="tableName">The name of the table where the movie
        /// information will be inserted.</param>
        /// <param name="movieFileName">The name of the JSON file that contains
        /// movie information.</param>
        /// <returns>A Boolean value that indicates the success or failure of
        /// the insert operation.</returns>
        public static async Task<bool> InsertMovies(string tableName, string movieFileName)
        {
            // Get the list of movies from the JSON file.
            var movies = ImportMovies(movieFileName);

            var success = false;

            if (movies is not null)
            {
                // Insert the movies in a batch using PartiQL. Because the
                // batch can contain a maximum of 25 items, insert 25 movies
                // at a time.
                string insertBatch = $"INSERT INTO {tableName} VALUE {{'title': ?, 'year': ?}}";
                var statements = new List<BatchStatementRequest>();

                try
                {
                    for (var indexOffset = 0; indexOffset < 250; indexOffset += 25)
                    {
                        for (var i = indexOffset; i < indexOffset + 25; i++)
                        {
                            statements.Add(new BatchStatementRequest
                            {
                                Statement = insertBatch,
                                Parameters = new List<AttributeValue>
                                {
                                    new AttributeValue { S = movies[i].Title },
                                    new AttributeValue { N = movies[i].Year.ToString() },
                                },
                            });
                        }

                        var response = await Client.BatchExecuteStatementAsync(new BatchExecuteStatementRequest
                        {
                            Statements = statements,
                        });

                        // Wait between batches for movies to be successfully added.
                        System.Threading.Thread.Sleep(3000);

                        success = response.HttpStatusCode == System.Net.HttpStatusCode.OK;

                        // Clear the list of statements for the next batch.
                        statements.Clear();
                    }
                }
                catch (AmazonDynamoDBException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            return success;
        }

        /// <summary>
        /// Loads the contents of a JSON file into a list of movies to be
        /// added to the DynamoDB table.
        /// </summary>
        /// <param name="movieFileName">The full path to the JSON file.</param>
        /// <returns>A generic list of movie objects.</returns>
        public static List<Movie> ImportMovies(string movieFileName)
        {
            if (!File.Exists(movieFileName))
            {
                return null!;
            }

            using var sr = new StreamReader(movieFileName);
            string json = sr.ReadToEnd();
            var allMovies = JsonConvert.DeserializeObject<List<Movie>>(json);

            if (allMovies is not null)
            {
                // Return the first 250 entries.
                return allMovies.GetRange(0, 250);
            }
            else
            {
                return null!;
            }
        }



        /// <summary>
        /// Uses a PartiQL SELECT statement to retrieve a single movie from the
        /// movie database.
        /// </summary>
        /// <param name="tableName">The name of the movie table.</param>
        /// <param name="movieTitle">The title of the movie to retrieve.</param>
        /// <returns>A list of movie data. If no movie matches the supplied
        /// title, the list is empty.</returns>
        public static async Task<List<Dictionary<string, AttributeValue>>> GetSingleMovie(string tableName, string movieTitle)
        {
            string selectSingle = $"SELECT * FROM {tableName} WHERE title = ?";
            var parameters = new List<AttributeValue>
            {
                new AttributeValue { S = movieTitle },
            };

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = selectSingle,
                Parameters = parameters,
            });

            return response.Items;
        }



        /// <summary>
        /// Retrieve multiple movies by year using a SELECT statement.
        /// </summary>
        /// <param name="tableName">The name of the movie table.</param>
        /// <param name="year">The year the movies were released.</param>
        /// <returns></returns>
        public static async Task<List<Dictionary<string, AttributeValue>>> GetMovies(string tableName, int year)
        {
            string selectSingle = $"SELECT * FROM {tableName} WHERE year = ?";
            var parameters = new List<AttributeValue>
            {
                new AttributeValue { N = year.ToString() },
            };

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = selectSingle,
                Parameters = parameters,
            });

            return response.Items;
        }


        /// <summary>
        /// Inserts a single movie into the movies table.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="movieTitle">The title of the movie to insert.</param>
        /// <param name="year">The year that the movie was released.</param>
        /// <returns>A Boolean value that indicates the success or failure of
        /// the INSERT operation.</returns>
        public static async Task<bool> InsertSingleMovie(string tableName, string movieTitle, int year)
        {
            string insertBatch = $"INSERT INTO {tableName} VALUE {{'title': ?, 'year': ?}}";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = insertBatch,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }



        /// <summary>
        /// Updates a single movie in the table, adding information for the
        /// producer.
        /// </summary>
        /// <param name="tableName">the name of the table.</param>
        /// <param name="producer">The name of the producer.</param>
        /// <param name="movieTitle">The movie title.</param>
        /// <param name="year">The year the movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the
        /// UPDATE operation.</returns>
        public static async Task<bool> UpdateSingleMovie(string tableName, string producer, string movieTitle, int year)
        {
            string insertSingle = $"UPDATE {tableName} SET Producer=? WHERE title = ? AND year = ?";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = insertSingle,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = producer },
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }



        /// <summary>
        /// Deletes a single movie from the table.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="movieTitle">The title of the movie to delete.</param>
        /// <param name="year">The year that the movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the
        /// DELETE operation.</returns>
        public static async Task<bool> DeleteSingleMovie(string tableName, string movieTitle, int year)
        {
            var deleteSingle = $"DELETE FROM {tableName} WHERE title = ? AND year = ?";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = deleteSingle,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }


        /// <summary>
        /// Displays the list of movies returned from a database query.
        /// </summary>
        /// <param name="items">The list of movie information to display.</param>
        private static void DisplayMovies(List<Dictionary<string, AttributeValue>> items)
        {
            if (items.Count > 0)
            {
                Console.WriteLine($"Found {items.Count} movies.");
                items.ForEach(item => Console.WriteLine($"{item["year"].N}\t{item["title"].S}"));
            }
            else
            {
                Console.WriteLine($"Didn't find a movie that matched the supplied criteria.");
            }
        }


    }
}



        /// <summary>
        /// Uses a PartiQL SELECT statement to retrieve a single movie from the
        /// movie database.
        /// </summary>
        /// <param name="tableName">The name of the movie table.</param>
        /// <param name="movieTitle">The title of the movie to retrieve.</param>
        /// <returns>A list of movie data. If no movie matches the supplied
        /// title, the list is empty.</returns>
        public static async Task<List<Dictionary<string, AttributeValue>>> GetSingleMovie(string tableName, string movieTitle)
        {
            string selectSingle = $"SELECT * FROM {tableName} WHERE title = ?";
            var parameters = new List<AttributeValue>
            {
                new AttributeValue { S = movieTitle },
            };

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = selectSingle,
                Parameters = parameters,
            });

            return response.Items;
        }



        /// <summary>
        /// Inserts a single movie into the movies table.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="movieTitle">The title of the movie to insert.</param>
        /// <param name="year">The year that the movie was released.</param>
        /// <returns>A Boolean value that indicates the success or failure of
        /// the INSERT operation.</returns>
        public static async Task<bool> InsertSingleMovie(string tableName, string movieTitle, int year)
        {
            string insertBatch = $"INSERT INTO {tableName} VALUE {{'title': ?, 'year': ?}}";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = insertBatch,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }



        /// <summary>
        /// Updates a single movie in the table, adding information for the
        /// producer.
        /// </summary>
        /// <param name="tableName">the name of the table.</param>
        /// <param name="producer">The name of the producer.</param>
        /// <param name="movieTitle">The movie title.</param>
        /// <param name="year">The year the movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the
        /// UPDATE operation.</returns>
        public static async Task<bool> UpdateSingleMovie(string tableName, string producer, string movieTitle, int year)
        {
            string insertSingle = $"UPDATE {tableName} SET Producer=? WHERE title = ? AND year = ?";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = insertSingle,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = producer },
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }



        /// <summary>
        /// Deletes a single movie from the table.
        /// </summary>
        /// <param name="tableName">The name of the table.</param>
        /// <param name="movieTitle">The title of the movie to delete.</param>
        /// <param name="year">The year that the movie was released.</param>
        /// <returns>A Boolean value that indicates the success of the
        /// DELETE operation.</returns>
        public static async Task<bool> DeleteSingleMovie(string tableName, string movieTitle, int year)
        {
            var deleteSingle = $"DELETE FROM {tableName} WHERE title = ? AND year = ?";

            var response = await Client.ExecuteStatementAsync(new ExecuteStatementRequest
            {
                Statement = deleteSingle,
                Parameters = new List<AttributeValue>
                {
                    new AttributeValue { S = movieTitle },
                    new AttributeValue { N = year.ToString() },
                },
            });

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ExecuteStatement](https://docs.aws.amazon.com/goto/DotNetSDKV3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### ドキュメントモデルを使用する
<a name="dynamodb_MidLevelInterface_csharp_3_topic"></a>

次のコード例は、DynamoDB と AWS SDK のドキュメントモデルを使用して、作成、読み取り、更新、削除 (CRUD) およびバッチオペレーションを実行する方法を示しています。

詳細については、「[ドキュメントモデル](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKMidLevel.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb/mid-level-api#code-examples)での設定と実行の方法を確認してください。
ドキュメントモデルを使用して CRUD オペレーションを実行します。  

```
    /// <summary>
    /// Performs CRUD operations on an Amazon DynamoDB table.
    /// </summary>
    public class MidlevelItemCRUD
    {
        public static async Task Main()
        {
            var tableName = "ProductCatalog";
            var sampleBookId = 555;

            var client = new AmazonDynamoDBClient();
            var productCatalog = LoadTable(client, tableName);

            await CreateBookItem(productCatalog, sampleBookId);
            RetrieveBook(productCatalog, sampleBookId);

            // Couple of sample updates.
            UpdateMultipleAttributes(productCatalog, sampleBookId);
            UpdateBookPriceConditionally(productCatalog, sampleBookId);

            // Delete.
            await DeleteBook(productCatalog, sampleBookId);
        }

        /// <summary>
        /// Loads the contents of a DynamoDB table.
        /// </summary>
        /// <param name="client">An initialized DynamoDB client object.</param>
        /// <param name="tableName">The name of the table to load.</param>
        /// <returns>A DynamoDB table object.</returns>
        public static Table LoadTable(IAmazonDynamoDB client, string tableName)
        {
            Table productCatalog = Table.LoadTable(client, tableName);
            return productCatalog;
        }

        /// <summary>
        /// Creates an example book item and adds it to the DynamoDB table
        /// ProductCatalog.
        /// </summary>
        /// <param name="productCatalog">A DynamoDB table object.</param>
        /// <param name="sampleBookId">An integer value representing the book's ID.</param>
        public static async Task CreateBookItem(Table productCatalog, int sampleBookId)
        {
            Console.WriteLine("\n*** Executing CreateBookItem() ***");
            var book = new Document
            {
                ["Id"] = sampleBookId,
                ["Title"] = "Book " + sampleBookId,
                ["Price"] = 19.99,
                ["ISBN"] = "111-1111111111",
                ["Authors"] = new List<string> { "Author 1", "Author 2", "Author 3" },
                ["PageCount"] = 500,
                ["Dimensions"] = "8.5x11x.5",
                ["InPublication"] = new DynamoDBBool(true),
                ["InStock"] = new DynamoDBBool(false),
                ["QuantityOnHand"] = 0,
            };

            // Adds the book to the ProductCatalog table.
            await productCatalog.PutItemAsync(book);
        }

        /// <summary>
        /// Retrieves an item, a book, from the DynamoDB ProductCatalog table.
        /// </summary>
        /// <param name="productCatalog">A DynamoDB table object.</param>
        /// <param name="sampleBookId">An integer value representing the book's ID.</param>
        public static async void RetrieveBook(
          Table productCatalog,
          int sampleBookId)
        {
            Console.WriteLine("\n*** Executing RetrieveBook() ***");

            // Optional configuration.
            var config = new GetItemOperationConfig
            {
                AttributesToGet = new List<string> { "Id", "ISBN", "Title", "Authors", "Price" },
                ConsistentRead = true,
            };

            Document document = await productCatalog.GetItemAsync(sampleBookId, config);
            Console.WriteLine("RetrieveBook: Printing book retrieved...");
            PrintDocument(document);
        }

        /// <summary>
        /// Updates multiple attributes for a book and writes the changes to the
        /// DynamoDB table ProductCatalog.
        /// </summary>
        /// <param name="productCatalog">A DynamoDB table object.</param>
        /// <param name="sampleBookId">An integer value representing the book's ID.</param>
        public static async void UpdateMultipleAttributes(
          Table productCatalog,
          int sampleBookId)
        {
            Console.WriteLine("\nUpdating multiple attributes....");
            int partitionKey = sampleBookId;

            var book = new Document
            {
                ["Id"] = partitionKey,

                // List of attribute updates.
                // The following replaces the existing authors list.
                ["Authors"] = new List<string> { "Author x", "Author y" },
                ["newAttribute"] = "New Value",
                ["ISBN"] = null, // Remove it.
            };

            // Optional parameters.
            var config = new UpdateItemOperationConfig
            {
                // Gets updated item in response.
                ReturnValues = ReturnValues.AllNewAttributes,
            };

            Document updatedBook = await productCatalog.UpdateItemAsync(book, config);
            Console.WriteLine("UpdateMultipleAttributes: Printing item after updates ...");
            PrintDocument(updatedBook);
        }

        /// <summary>
        /// Updates a book item if it meets the specified criteria.
        /// </summary>
        /// <param name="productCatalog">A DynamoDB table object.</param>
        /// <param name="sampleBookId">An integer value representing the book's ID.</param>
        public static async void UpdateBookPriceConditionally(
          Table productCatalog,
          int sampleBookId)
        {
            Console.WriteLine("\n*** Executing UpdateBookPriceConditionally() ***");

            int partitionKey = sampleBookId;

            var book = new Document
            {
                ["Id"] = partitionKey,
                ["Price"] = 29.99,
            };

            // For conditional price update, creating a condition expression.
            var expr = new Expression
            {
                ExpressionStatement = "Price = :val",
            };
            expr.ExpressionAttributeValues[":val"] = 19.00;

            // Optional parameters.
            var config = new UpdateItemOperationConfig
            {
                ConditionalExpression = expr,
                ReturnValues = ReturnValues.AllNewAttributes,
            };

            Document updatedBook = await productCatalog.UpdateItemAsync(book, config);
            Console.WriteLine("UpdateBookPriceConditionally: Printing item whose price was conditionally updated");
            PrintDocument(updatedBook);
        }

        /// <summary>
        /// Deletes the book with the supplied Id value from the DynamoDB table
        /// ProductCatalog.
        /// </summary>
        /// <param name="productCatalog">A DynamoDB table object.</param>
        /// <param name="sampleBookId">An integer value representing the book's ID.</param>
        public static async Task DeleteBook(
          Table productCatalog,
          int sampleBookId)
        {
            Console.WriteLine("\n*** Executing DeleteBook() ***");

            // Optional configuration.
            var config = new DeleteItemOperationConfig
            {
                // Returns the deleted item.
                ReturnValues = ReturnValues.AllOldAttributes,
            };
            Document document = await productCatalog.DeleteItemAsync(sampleBookId, config);
            Console.WriteLine("DeleteBook: Printing deleted just deleted...");

            PrintDocument(document);
        }

        /// <summary>
        /// Prints the information for the supplied DynamoDB document.
        /// </summary>
        /// <param name="updatedDocument">A DynamoDB document object.</param>
        public static void PrintDocument(Document updatedDocument)
        {
            if (updatedDocument is null)
            {
                return;
            }

            foreach (var attribute in updatedDocument.GetAttributeNames())
            {
                string stringValue = null;
                var value = updatedDocument[attribute];

                if (value is null)
                {
                    continue;
                }

                if (value is Primitive)
                {
                    stringValue = value.AsPrimitive().Value.ToString();
                }
                else if (value is PrimitiveList)
                {
                    stringValue = string.Join(",", (from primitive
                      in value.AsPrimitiveList().Entries
                                                    select primitive.Value).ToArray());
                }

                Console.WriteLine($"{attribute} - {stringValue}", attribute, stringValue);
            }
        }
    }
```
ドキュメントモデルを使用してバッチ書き込みオペレーションを実行します。  

```
    /// <summary>
    /// Shows how to use mid-level Amazon DynamoDB API calls to perform batch
    /// operations.
    /// </summary>
    public class MidLevelBatchWriteItem
    {
        public static async Task Main()
        {
            IAmazonDynamoDB client = new AmazonDynamoDBClient();

            await SingleTableBatchWrite(client);
            await MultiTableBatchWrite(client);
        }

        /// <summary>
        /// Perform a batch operation on a single DynamoDB table.
        /// </summary>
        /// <param name="client">An initialized DynamoDB object.</param>
        public static async Task SingleTableBatchWrite(IAmazonDynamoDB client)
        {
            Table productCatalog = Table.LoadTable(client, "ProductCatalog");
            var batchWrite = productCatalog.CreateBatchWrite();

            var book1 = new Document
            {
                ["Id"] = 902,
                ["Title"] = "My book1 in batch write using .NET helper classes",
                ["ISBN"] = "902-11-11-1111",
                ["Price"] = 10,
                ["ProductCategory"] = "Book",
                ["Authors"] = new List<string> { "Author 1", "Author 2", "Author 3" },
                ["Dimensions"] = "8.5x11x.5",
                ["InStock"] = new DynamoDBBool(true),
                ["QuantityOnHand"] = new DynamoDBNull(), // Quantity is unknown at this time.
            };

            batchWrite.AddDocumentToPut(book1);

            // Specify delete item using overload that takes PK.
            batchWrite.AddKeyToDelete(12345);
            Console.WriteLine("Performing batch write in SingleTableBatchWrite()");
            await batchWrite.ExecuteAsync();
        }

        /// <summary>
        /// Perform a batch operation involving multiple DynamoDB tables.
        /// </summary>
        /// <param name="client">An initialized DynamoDB client object.</param>
        public static async Task MultiTableBatchWrite(IAmazonDynamoDB client)
        {
            // Specify item to add in the Forum table.
            Table forum = Table.LoadTable(client, "Forum");
            var forumBatchWrite = forum.CreateBatchWrite();

            var forum1 = new Document
            {
                ["Name"] = "Test BatchWrite Forum",
                ["Threads"] = 0,
            };
            forumBatchWrite.AddDocumentToPut(forum1);

            // Specify item to add in the Thread table.
            Table thread = Table.LoadTable(client, "Thread");
            var threadBatchWrite = thread.CreateBatchWrite();

            var thread1 = new Document
            {
                ["ForumName"] = "S3 forum",
                ["Subject"] = "My sample question",
                ["Message"] = "Message text",
                ["KeywordTags"] = new List<string> { "S3", "Bucket" },
            };
            threadBatchWrite.AddDocumentToPut(thread1);

            // Specify item to delete from the Thread table.
            threadBatchWrite.AddKeyToDelete("someForumName", "someSubject");

            // Create multi-table batch.
            var superBatch = new MultiTableDocumentBatchWrite();
            superBatch.AddBatch(forumBatchWrite);
            superBatch.AddBatch(threadBatchWrite);
            Console.WriteLine("Performing batch write in MultiTableBatchWrite()");

            // Execute the batch.
            await superBatch.ExecuteAsync();
        }
    }
```
ドキュメントモデルを使用してテーブルをスキャンします。  

```
    /// <summary>
    /// Shows how to use mid-level Amazon DynamoDB API calls to scan a DynamoDB
    /// table for values.
    /// </summary>
    public class MidLevelScanOnly
    {
        public static async Task Main()
        {
            IAmazonDynamoDB client = new AmazonDynamoDBClient();

            Table productCatalogTable = Table.LoadTable(client, "ProductCatalog");

            await FindProductsWithNegativePrice(productCatalogTable);
            await FindProductsWithNegativePriceWithConfig(productCatalogTable);
        }

        /// <summary>
        /// Retrieves any products that have a negative price in a DynamoDB table.
        /// </summary>
        /// <param name="productCatalogTable">A DynamoDB table object.</param>
        public static async Task FindProductsWithNegativePrice(
          Table productCatalogTable)
        {
            // Assume there is a price error. So we scan to find items priced < 0.
            var scanFilter = new ScanFilter();
            scanFilter.AddCondition("Price", ScanOperator.LessThan, 0);

            Search search = productCatalogTable.Scan(scanFilter);

            do
            {
                var documentList = await search.GetNextSetAsync();
                Console.WriteLine("\nFindProductsWithNegativePrice: printing ............");

                foreach (var document in documentList)
                {
                    PrintDocument(document);
                }
            }
            while (!search.IsDone);
        }

        /// <summary>
        /// Finds any items in the ProductCatalog table using a DynamoDB
        /// configuration object.
        /// </summary>
        /// <param name="productCatalogTable">A DynamoDB table object.</param>
        public static async Task FindProductsWithNegativePriceWithConfig(
          Table productCatalogTable)
        {
            // Assume there is a price error. So we scan to find items priced < 0.
            var scanFilter = new ScanFilter();
            scanFilter.AddCondition("Price", ScanOperator.LessThan, 0);

            var config = new ScanOperationConfig()
            {
                Filter = scanFilter,
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string> { "Title", "Id" },
            };

            Search search = productCatalogTable.Scan(config);

            do
            {
                var documentList = await search.GetNextSetAsync();
                Console.WriteLine("\nFindProductsWithNegativePriceWithConfig: printing ............");

                foreach (var document in documentList)
                {
                    PrintDocument(document);
                }
            }
            while (!search.IsDone);
        }

        /// <summary>
        /// Displays the details of the passed DynamoDB document object on the
        /// console.
        /// </summary>
        /// <param name="document">A DynamoDB document object.</param>
        public static void PrintDocument(Document document)
        {
            Console.WriteLine();
            foreach (var attribute in document.GetAttributeNames())
            {
                string stringValue = null;
                var value = document[attribute];
                if (value is Primitive)
                {
                    stringValue = value.AsPrimitive().Value.ToString();
                }
                else if (value is PrimitiveList)
                {
                    stringValue = string.Join(",", (from primitive
                      in value.AsPrimitiveList().Entries
                                                    select primitive.Value).ToArray());
                }

                Console.WriteLine($"{attribute} - {stringValue}");
            }
        }
    }
```
ドキュメントモデルを使用して、テーブルをクエリおよびスキャンする。  

```
    /// <summary>
    /// Shows how to perform mid-level query procedures on an Amazon DynamoDB
    /// table.
    /// </summary>
    public class MidLevelQueryAndScan
    {
        public static async Task Main()
        {
            IAmazonDynamoDB client = new AmazonDynamoDBClient();

            // Query examples.
            Table replyTable = Table.LoadTable(client, "Reply");
            string forumName = "Amazon DynamoDB";
            string threadSubject = "DynamoDB Thread 2";

            await FindRepliesInLast15Days(replyTable);
            await FindRepliesInLast15DaysWithConfig(replyTable, forumName, threadSubject);
            await FindRepliesPostedWithinTimePeriod(replyTable, forumName, threadSubject);

            // Get Example.
            Table productCatalogTable = Table.LoadTable(client, "ProductCatalog");
            int productId = 101;

            await GetProduct(productCatalogTable, productId);
        }

        /// <summary>
        /// Retrieves information about a product from the DynamoDB table
        /// ProductCatalog based on the product ID and displays the information
        /// on the console.
        /// </summary>
        /// <param name="tableName">The name of the table from which to retrieve
        /// product information.</param>
        /// <param name="productId">The ID of the product to retrieve.</param>
        public static async Task GetProduct(Table tableName, int productId)
        {
            Console.WriteLine("*** Executing GetProduct() ***");
            Document productDocument = await tableName.GetItemAsync(productId);
            if (productDocument != null)
            {
                PrintDocument(productDocument);
            }
            else
            {
                Console.WriteLine("Error: product " + productId + " does not exist");
            }
        }

        /// <summary>
        /// Retrieves replies from the passed DynamoDB table object.
        /// </summary>
        /// <param name="table">The table we want to query.</param>
        public static async Task FindRepliesInLast15Days(
          Table table)
        {
            DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15);
            var filter = new QueryFilter("Id", QueryOperator.Equal, "Id");
            filter.AddCondition("ReplyDateTime", QueryOperator.GreaterThan, twoWeeksAgoDate);

            // Use Query overloads that take the minimum required query parameters.
            Search search = table.Query(filter);

            do
            {
                var documentSet = await search.GetNextSetAsync();
                Console.WriteLine("\nFindRepliesInLast15Days: printing ............");

                foreach (var document in documentSet)
                {
                    PrintDocument(document);
                }
            }
            while (!search.IsDone);
        }

        /// <summary>
        /// Retrieve replies made during a specific time period.
        /// </summary>
        /// <param name="table">The table we want to query.</param>
        /// <param name="forumName">The name of the forum that we're interested in.</param>
        /// <param name="threadSubject">The subject of the thread, which we are
        /// searching for replies.</param>
        public static async Task FindRepliesPostedWithinTimePeriod(
          Table table,
          string forumName,
          string threadSubject)
        {
            DateTime startDate = DateTime.UtcNow.Subtract(new TimeSpan(21, 0, 0, 0));
            DateTime endDate = DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0));

            var filter = new QueryFilter("Id", QueryOperator.Equal, forumName + "#" + threadSubject);
            filter.AddCondition("ReplyDateTime", QueryOperator.Between, startDate, endDate);

            var config = new QueryOperationConfig()
            {
                Limit = 2, // 2 items/page.
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string>
        {
          "Message",
          "ReplyDateTime",
          "PostedBy",
        },
                ConsistentRead = true,
                Filter = filter,
            };

            Search search = table.Query(config);

            do
            {
                var documentList = await search.GetNextSetAsync();
                Console.WriteLine("\nFindRepliesPostedWithinTimePeriod: printing replies posted within dates: {0} and {1} ............", startDate, endDate);

                foreach (var document in documentList)
                {
                    PrintDocument(document);
                }
            }
            while (!search.IsDone);
        }

        /// <summary>
        /// Perform a query for replies made in the last 15 days using a DynamoDB
        /// QueryOperationConfig object.
        /// </summary>
        /// <param name="table">The table we want to query.</param>
        /// <param name="forumName">The name of the forum that we're interested in.</param>
        /// <param name="threadName">The bane of the thread that we are searching
        /// for replies.</param>
        public static async Task FindRepliesInLast15DaysWithConfig(
          Table table,
          string forumName,
          string threadName)
        {
            DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15);
            var filter = new QueryFilter("Id", QueryOperator.Equal, forumName + "#" + threadName);
            filter.AddCondition("ReplyDateTime", QueryOperator.GreaterThan, twoWeeksAgoDate);

            var config = new QueryOperationConfig()
            {
                Filter = filter,

                // Optional parameters.
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string>
                {
                  "Message",
                  "ReplyDateTime",
                  "PostedBy",
                },
                ConsistentRead = true,
            };

            Search search = table.Query(config);

            do
            {
                var documentSet = await search.GetNextSetAsync();
                Console.WriteLine("\nFindRepliesInLast15DaysWithConfig: printing ............");

                foreach (var document in documentSet)
                {
                    PrintDocument(document);
                }
            }
            while (!search.IsDone);
        }

        /// <summary>
        /// Displays the contents of the passed DynamoDB document on the console.
        /// </summary>
        /// <param name="document">A DynamoDB document to display.</param>
        public static void PrintDocument(Document document)
        {
            Console.WriteLine();
            foreach (var attribute in document.GetAttributeNames())
            {
                string stringValue = null;
                var value = document[attribute];

                if (value is Primitive)
                {
                    stringValue = value.AsPrimitive().Value.ToString();
                }
                else if (value is PrimitiveList)
                {
                    stringValue = string.Join(",", (from primitive
                      in value.AsPrimitiveList().Entries
                                                    select primitive.Value).ToArray());
                }

                Console.WriteLine($"{attribute} - {stringValue}");
            }
        }
    }
```

### 高レベルのオブジェクト永続性モデルを使用する
<a name="dynamodb_HighLevelInterface_csharp_3_topic"></a>

次のコード例は、DynamoDB と AWS SDK のオブジェクト永続性モデルを使用して、作成、読み取り、更新、削除 (CRUD) およびバッチオペレーションを実行する方法を示しています。

詳細については、「[オブジェクト永続性モデル](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DotNetSDKHighLevel.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/dynamodb/high-level-api#code-examples)での設定と実行の方法を確認してください。
高レベルのオブジェクト永続性モデルを使用して CRUD オペレーションを実行します。  

```
    /// <summary>
    /// Shows how to perform high-level CRUD operations on an Amazon DynamoDB
    /// table.
    /// </summary>
    public class HighLevelItemCrud
    {
        public static async Task Main()
        {
            var client = new AmazonDynamoDBClient();
            DynamoDBContext context = new DynamoDBContext(client);
            await PerformCRUDOperations(context);
        }

        public static async Task PerformCRUDOperations(IDynamoDBContext context)
        {
            int bookId = 1001; // Some unique value.
            Book myBook = new Book
            {
                Id = bookId,
                Title = "object persistence-AWS SDK for.NET SDK-Book 1001",
                Isbn = "111-1111111001",
                BookAuthors = new List<string> { "Author 1", "Author 2" },
            };

            // Save the book to the ProductCatalog table.
            await context.SaveAsync(myBook);

            // Retrieve the book from the ProductCatalog table.
            Book bookRetrieved = await context.LoadAsync<Book>(bookId);

            // Update some properties.
            bookRetrieved.Isbn = "222-2222221001";

            // Update existing authors list with the following values.
            bookRetrieved.BookAuthors = new List<string> { " Author 1", "Author x" };
            await context.SaveAsync(bookRetrieved);

            // Retrieve the updated book. This time, add the optional
            // ConsistentRead parameter using DynamoDBContextConfig object.
            await context.LoadAsync<Book>(bookId, new DynamoDBContextConfig
            {
                ConsistentRead = true,
            });

            // Delete the book.
            await context.DeleteAsync<Book>(bookId);

            // Try to retrieve deleted book. It should return null.
            Book deletedBook = await context.LoadAsync<Book>(bookId, new DynamoDBContextConfig
            {
                ConsistentRead = true,
            });

            if (deletedBook == null)
            {
                Console.WriteLine("Book is deleted");
            }
        }
    }
```
高レベルのオブジェクト永続性モデルを使用してバッチ書き込みオペレーションを実行します。  

```
    /// <summary>
    /// Performs high-level batch write operations to an Amazon DynamoDB table.
    /// This example was written using the AWS SDK for .NET version 3.7 and .NET
    /// Core 5.0.
    /// </summary>
    public class HighLevelBatchWriteItem
    {
        public static async Task SingleTableBatchWrite(IDynamoDBContext context)
        {
            Book book1 = new Book
            {
                Id = 902,
                InPublication = true,
                Isbn = "902-11-11-1111",
                PageCount = "100",
                Price = 10,
                ProductCategory = "Book",
                Title = "My book3 in batch write",
            };

            Book book2 = new Book
            {
                Id = 903,
                InPublication = true,
                Isbn = "903-11-11-1111",
                PageCount = "200",
                Price = 10,
                ProductCategory = "Book",
                Title = "My book4 in batch write",
            };

            var bookBatch = context.CreateBatchWrite<Book>();
            bookBatch.AddPutItems(new List<Book> { book1, book2 });

            Console.WriteLine("Adding two books to ProductCatalog table.");
            await bookBatch.ExecuteAsync();
        }

        public static async Task MultiTableBatchWrite(IDynamoDBContext context)
        {
            // New Forum item.
            Forum newForum = new Forum
            {
                Name = "Test BatchWrite Forum",
                Threads = 0,
            };
            var forumBatch = context.CreateBatchWrite<Forum>();
            forumBatch.AddPutItem(newForum);

            // New Thread item.
            Thread newThread = new Thread
            {
                ForumName = "S3 forum",
                Subject = "My sample question",
                KeywordTags = new List<string> { "S3", "Bucket" },
                Message = "Message text",
            };

            DynamoDBOperationConfig config = new DynamoDBOperationConfig();
            config.SkipVersionCheck = true;
            var threadBatch = context.CreateBatchWrite<Thread>(config);
            threadBatch.AddPutItem(newThread);
            threadBatch.AddDeleteKey("some partition key value", "some sort key value");

            var superBatch = new MultiTableBatchWrite(forumBatch, threadBatch);

            Console.WriteLine("Performing batch write in MultiTableBatchWrite().");
            await superBatch.ExecuteAsync();
        }

        public static async Task Main()
        {
            AmazonDynamoDBClient client = new AmazonDynamoDBClient();
            DynamoDBContext context = new DynamoDBContext(client);

            await SingleTableBatchWrite(context);
            await MultiTableBatchWrite(context);
        }
    }
```
オブジェクト永続性モデルを使用して、任意のデータをテーブルにマッピングします。  

```
    /// <summary>
    /// Shows how to map arbitrary data to an Amazon DynamoDB table.
    /// </summary>
    public class HighLevelMappingArbitraryData
    {
        /// <summary>
        /// Creates a book, adds it to the DynamoDB ProductCatalog table, retrieves
        /// the new book from the table, updates the dimensions and writes the
        /// changed item back to the table.
        /// </summary>
        /// <param name="context">The DynamoDB context object used to write and
        /// read data from the table.</param>
        public static async Task AddRetrieveUpdateBook(IDynamoDBContext context)
        {
            // Create a book.
            DimensionType myBookDimensions = new DimensionType()
            {
                Length = 8M,
                Height = 11M,
                Thickness = 0.5M,
            };

            Book myBook = new Book
            {
                Id = 501,
                Title = "AWS SDK for .NET Object Persistence Model Handling Arbitrary Data",
                Isbn = "999-9999999999",
                BookAuthors = new List<string> { "Author 1", "Author 2" },
                Dimensions = myBookDimensions,
            };

            // Add the book to the DynamoDB table ProductCatalog.
            await context.SaveAsync(myBook);

            // Retrieve the book.
            Book bookRetrieved = await context.LoadAsync<Book>(501);

            // Update the book dimensions property.
            bookRetrieved.Dimensions.Height += 1;
            bookRetrieved.Dimensions.Length += 1;
            bookRetrieved.Dimensions.Thickness += 0.2M;

            // Write the changed item to the table.
            await context.SaveAsync(bookRetrieved);
        }

        public static async Task Main()
        {
            var client = new AmazonDynamoDBClient();
            DynamoDBContext context = new DynamoDBContext(client);
            await AddRetrieveUpdateBook(context);
        }
    }
```
高レベルのオブジェクト永続性モデルを使用してテーブルをクエリおよびスキャンします。  

```
    /// <summary>
    /// Shows how to perform high-level query and scan operations to Amazon
    /// DynamoDB tables.
    /// </summary>
    public class HighLevelQueryAndScan
    {
        public static async Task Main()
        {
            var client = new AmazonDynamoDBClient();

            DynamoDBContext context = new DynamoDBContext(client);

            // Get an item.
            await GetBook(context, 101);

            // Sample forum and thread to test queries.
            string forumName = "Amazon DynamoDB";
            string threadSubject = "DynamoDB Thread 1";

            // Sample queries.
            await FindRepliesInLast15Days(context, forumName, threadSubject);
            await FindRepliesPostedWithinTimePeriod(context, forumName, threadSubject);

            // Scan table.
            await FindProductsPricedLessThanZero(context);
        }

        public static async Task GetBook(IDynamoDBContext context, int productId)
        {
            Book bookItem = await context.LoadAsync<Book>(productId);

            Console.WriteLine("\nGetBook: Printing result.....");
            Console.WriteLine($"Title: {bookItem.Title} \n ISBN:{bookItem.Isbn} \n No. of pages: {bookItem.PageCount}");
        }

        /// <summary>
        /// Queries a DynamoDB table to find replies posted within the last 15 days.
        /// </summary>
        /// <param name="context">The DynamoDB context used to perform the query.</param>
        /// <param name="forumName">The name of the forum that we're interested in.</param>
        /// <param name="threadSubject">The thread object containing the query parameters.</param>
        public static async Task FindRepliesInLast15Days(
          IDynamoDBContext context,
          string forumName,
          string threadSubject)
        {
            string replyId = $"{forumName} #{threadSubject}";
            DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15);

            List<object> times = new List<object>();
            times.Add(twoWeeksAgoDate);

            List<ScanCondition> scs = new List<ScanCondition>();
            var sc = new ScanCondition("PostedBy", ScanOperator.GreaterThan, times.ToArray());
            scs.Add(sc);

            var cfg = new DynamoDBOperationConfig
            {
                QueryFilter = scs,
            };

            AsyncSearch<Reply> response = context.QueryAsync<Reply>(replyId, cfg);
            IEnumerable<Reply> latestReplies = await response.GetRemainingAsync();

            Console.WriteLine("\nReplies in last 15 days:");

            foreach (Reply r in latestReplies)
            {
                Console.WriteLine($"{r.Id}\t{r.PostedBy}\t{r.Message}\t{r.ReplyDateTime}");
            }
        }

        /// <summary>
        /// Queries for replies posted within a specific time period.
        /// </summary>
        /// <param name="context">The DynamoDB context used to perform the query.</param>
        /// <param name="forumName">The name of the forum that we're interested in.</param>
        /// <param name="threadSubject">Information about the subject that we're
        /// interested in.</param>
        public static async Task FindRepliesPostedWithinTimePeriod(
          IDynamoDBContext context,
          string forumName,
          string threadSubject)
        {
            string forumId = forumName + "#" + threadSubject;
            Console.WriteLine("\nReplies posted within time period:");

            DateTime startDate = DateTime.UtcNow - TimeSpan.FromDays(30);
            DateTime endDate = DateTime.UtcNow - TimeSpan.FromDays(1);

            List<object> times = new List<object>();
            times.Add(startDate);
            times.Add(endDate);

            List<ScanCondition> scs = new List<ScanCondition>();
            var sc = new ScanCondition("LastPostedBy", ScanOperator.Between, times.ToArray());
            scs.Add(sc);

            var cfg = new DynamoDBOperationConfig
            {
                QueryFilter = scs,
            };

            AsyncSearch<Reply> response = context.QueryAsync<Reply>(forumId, cfg);
            IEnumerable<Reply> repliesInAPeriod = await response.GetRemainingAsync();

            foreach (Reply r in repliesInAPeriod)
            {
                Console.WriteLine("{r.Id}\t{r.PostedBy}\t{r.Message}\t{r.ReplyDateTime}");
            }
        }

        /// <summary>
        /// Queries the DynamoDB ProductCatalog table for products costing less
        /// than zero.
        /// </summary>
        /// <param name="context">The DynamoDB context object used to perform the
        /// query.</param>
        public static async Task FindProductsPricedLessThanZero(IDynamoDBContext context)
        {
            int price = 0;

            List<ScanCondition> scs = new List<ScanCondition>();
            var sc1 = new ScanCondition("Price", ScanOperator.LessThan, price);
            var sc2 = new ScanCondition("ProductCategory", ScanOperator.Equal, "Book");
            scs.Add(sc1);
            scs.Add(sc2);

            AsyncSearch<Book> response = context.ScanAsync<Book>(scs);

            IEnumerable<Book> itemsWithWrongPrice = await response.GetRemainingAsync();

            Console.WriteLine("\nFindProductsPricedLessThanZero: Printing result.....");

            foreach (Book r in itemsWithWrongPrice)
            {
                Console.WriteLine($"{r.Id}\t{r.Title}\t{r.Price}\t{r.Isbn}");
            }
        }
    }
```

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_csharp_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での DynamoDB イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Text.Json;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace AWSLambda_DDB;

public class Function
{
    public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
    {
        context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records...");

        foreach (var record in dynamoEvent.Records)
        {
            context.Logger.LogInformation($"Event ID: {record.EventID}");
            context.Logger.LogInformation($"Event Name: {record.EventName}");

            context.Logger.LogInformation(JsonSerializer.Serialize(record));
        }

        context.Logger.LogInformation("Stream processing complete.");
    }
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_csharp_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での DynamoDB のバッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Text.Json;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace AWSLambda_DDB;

public class Function
{
    public StreamsEventResponse FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)

    {
        context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records...");
        List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new List<StreamsEventResponse.BatchItemFailure>();
        StreamsEventResponse streamsEventResponse = new StreamsEventResponse();

        foreach (var record in dynamoEvent.Records)
        {
            try
            {
                var sequenceNumber = record.Dynamodb.SequenceNumber;
                context.Logger.LogInformation(sequenceNumber);
            }
            catch (Exception ex)
            {
                context.Logger.LogError(ex.Message);
                batchItemFailures.Add(new StreamsEventResponse.BatchItemFailure() { ItemIdentifier = record.Dynamodb.SequenceNumber });
            }
        }

        if (batchItemFailures.Count > 0)
        {
            streamsEventResponse.BatchItemFailures = batchItemFailures;
        }

        context.Logger.LogInformation("Stream processing complete.");
        return streamsEventResponse;
    }
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_csharp_3_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for .NET**  
 .NET SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-dotnet-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# を使用した Amazon EC2 の例 SDK for .NET
<a name="csharp_3_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトでシナリオを実行します。  

```
/// <summary>
/// Show Amazon Elastic Compute Cloud (Amazon EC2) Basics actions.
/// </summary>
public class EC2Basics
{
    public static ILogger<EC2Basics> _logger = null!;
    public static EC2Wrapper _ec2Wrapper = null!;
    public static SsmWrapper _ssmWrapper = null!;
    public static UiMethods _uiMethods = null!;

    public static string associationId = null!;
    public static string allocationId = null!;
    public static string instanceId = null!;
    public static string keyPairName = null!;
    public static string groupName = null!;
    public static string tempFileName = null!;
    public static string secGroupId = null!;
    public static bool isInteractive = true;

    /// <summary>
    /// Perform the actions defined for the Amazon EC2 Basics scenario.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    /// <returns>A Task object.</returns>
    public static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon EC2 and Amazon Simple Systems
        // Management (Amazon SSM) Service.
        using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonEC2>()
                    .AddAWSService<IAmazonSimpleSystemsManagement>()
                    .AddTransient<EC2Wrapper>()
                    .AddTransient<SsmWrapper>()
            )
            .Build();

        SetUpServices(host);

        var uniqueName = Guid.NewGuid().ToString();
        keyPairName = "mvp-example-key-pair" + uniqueName;
        groupName = "ec2-scenario-group" + uniqueName;
        var groupDescription = "A security group created for the EC2 Basics scenario.";

        try
        {
            // Start the scenario.
            _uiMethods.DisplayOverview();
            _uiMethods.PressEnter(isInteractive);

            // Create the key pair.
            _uiMethods.DisplayTitle("Create RSA key pair");
            Console.Write("Let's create an RSA key pair that you can be use to ");
            Console.WriteLine("securely connect to your EC2 instance.");
            var keyPair = await _ec2Wrapper.CreateKeyPair(keyPairName);

            // Save key pair information to a temporary file.
            tempFileName = _ec2Wrapper.SaveKeyPair(keyPair);

            Console.WriteLine(
                $"Created the key pair: {keyPair.KeyName} and saved it to: {tempFileName}");
            string? answer = "";
            if (isInteractive)
            {
                do
                {
                    Console.Write("Would you like to list your existing key pairs? ");
                    answer = Console.ReadLine();
                } while (answer!.ToLower() != "y" && answer.ToLower() != "n");
            }

            if (!isInteractive || answer == "y")
            {
                // List existing key pairs.
                _uiMethods.DisplayTitle("Existing key pairs");

                // Passing an empty string to the DescribeKeyPairs method will return
                // a list of all existing key pairs.
                var keyPairs = await _ec2Wrapper.DescribeKeyPairs("");
                keyPairs.ForEach(kp =>
                {
                    Console.WriteLine(
                        $"{kp.KeyName} created at: {kp.CreateTime} Fingerprint: {kp.KeyFingerprint}");
                });
            }

            _uiMethods.PressEnter(isInteractive);

            // Create the security group.
            Console.WriteLine(
                "Let's create a security group to manage access to your instance.");
            secGroupId = await _ec2Wrapper.CreateSecurityGroup(groupName, groupDescription);
            Console.WriteLine(
                "Let's add rules to allow all HTTP and HTTPS inbound traffic and to allow SSH only from your current IP address.");

            _uiMethods.DisplayTitle("Security group information");
            var secGroups = await _ec2Wrapper.DescribeSecurityGroups(secGroupId);

            Console.WriteLine($"Created security group {groupName} in your default VPC.");
            secGroups.ForEach(group =>
            {
                _ec2Wrapper.DisplaySecurityGroupInfoAsync(group);
            });
            _uiMethods.PressEnter(isInteractive);

            Console.WriteLine(
                "Now we'll authorize the security group we just created so that it can");
            Console.WriteLine("access the EC2 instances you create.");
            await _ec2Wrapper.AuthorizeSecurityGroupIngress(groupName);

            secGroups = await _ec2Wrapper.DescribeSecurityGroups(secGroupId);
            Console.WriteLine($"Now let's look at the permissions again.");
            secGroups.ForEach(group =>
            {
                _ec2Wrapper.DisplaySecurityGroupInfoAsync(group);
            });
            _uiMethods.PressEnter(isInteractive);

            // Get list of available Amazon Linux 2 Amazon Machine Images (AMIs).
            var parameters =
                await _ssmWrapper.GetParametersByPath(
                    "/aws/service/ami-amazon-linux-latest");

            List<string> imageIds = parameters.Select(param => param.Value).ToList();

            var images = await _ec2Wrapper.DescribeImages(imageIds);

            var i = 1;
            images.ForEach(image =>
            {
                Console.WriteLine($"\t{i++}\t{image.Description}");
            });

            int choice = 1;
            bool validNumber = false;
            if (isInteractive)
            {
                do
                {
                    Console.Write("Please select an image: ");
                    var selImage = Console.ReadLine();
                    validNumber = int.TryParse(selImage, out choice);
                } while (!validNumber);
            }

            var selectedImage = images[choice - 1];

            // Display available instance types.
            _uiMethods.DisplayTitle("Instance Types");
            var instanceTypes =
                await _ec2Wrapper.DescribeInstanceTypes(selectedImage.Architecture);

            i = 1;
            instanceTypes.ForEach(instanceType =>
            {
                Console.WriteLine($"\t{i++}\t{instanceType.InstanceType}");
            });
            if (isInteractive)
            {
                do
                {
                    Console.Write("Please select an instance type: ");
                    var selImage = Console.ReadLine();
                    validNumber = int.TryParse(selImage, out choice);
                } while (!validNumber);
            }

            var selectedInstanceType = instanceTypes[choice - 1].InstanceType;

            // Create an EC2 instance.
            _uiMethods.DisplayTitle("Creating an EC2 Instance");
            instanceId = await _ec2Wrapper.RunInstances(selectedImage.ImageId,
                selectedInstanceType, keyPairName, secGroupId);

            _uiMethods.PressEnter(isInteractive);

            var instance = await _ec2Wrapper.DescribeInstance(instanceId);
            _uiMethods.DisplayTitle("New Instance Information");
            _ec2Wrapper.DisplayInstanceInformation(instance);

            Console.WriteLine(
                "\nYou can use SSH to connect to your instance. For example:");
            Console.WriteLine(
                $"\tssh -i {tempFileName} ec2-user@{instance.PublicIpAddress}");

            _uiMethods.PressEnter(isInteractive);

            Console.WriteLine(
                "Now we'll stop the instance and then start it again to see what's changed.");

            await _ec2Wrapper.StopInstances(instanceId);

            Console.WriteLine("Now let's start it up again.");
            await _ec2Wrapper.StartInstances(instanceId);

            Console.WriteLine("\nLet's see what changed.");

            instance = await _ec2Wrapper.DescribeInstance(instanceId);
            _uiMethods.DisplayTitle("New Instance Information");
            _ec2Wrapper.DisplayInstanceInformation(instance);

            Console.WriteLine("\nNotice the change in the SSH information:");
            Console.WriteLine(
                $"\tssh -i {tempFileName} ec2-user@{instance.PublicIpAddress}");

            _uiMethods.PressEnter(isInteractive);

            Console.WriteLine(
                "Now we will stop the instance again. Then we will create and associate an");
            Console.WriteLine("Elastic IP address to use with our instance.");

            await _ec2Wrapper.StopInstances(instanceId);
            _uiMethods.PressEnter(isInteractive);

            _uiMethods.DisplayTitle("Allocate Elastic IP address");
            Console.WriteLine(
                "You can allocate an Elastic IP address and associate it with your instance\nto keep a consistent IP address even when your instance restarts.");
            var allocationResponse = await _ec2Wrapper.AllocateAddress();
            allocationId = allocationResponse.AllocationId;
            Console.WriteLine(
                "Now we will associate the Elastic IP address with our instance.");
            associationId = await _ec2Wrapper.AssociateAddress(allocationId, instanceId);

            // Start the instance again.
            Console.WriteLine("Now let's start the instance again.");
            await _ec2Wrapper.StartInstances(instanceId);

            Console.WriteLine("\nLet's see what changed.");

            instance = await _ec2Wrapper.DescribeInstance(instanceId);
            _uiMethods.DisplayTitle("Instance information");
            _ec2Wrapper.DisplayInstanceInformation(instance);

            Console.WriteLine("\nHere is the SSH information:");
            Console.WriteLine(
                $"\tssh -i {tempFileName} ec2-user@{instance.PublicIpAddress}");

            Console.WriteLine("Let's stop and start the instance again.");
            _uiMethods.PressEnter(isInteractive);

            await _ec2Wrapper.StopInstances(instanceId);

            Console.WriteLine("\nThe instance has stopped.");

            Console.WriteLine("Now let's start it up again.");
            await _ec2Wrapper.StartInstances(instanceId);

            instance = await _ec2Wrapper.DescribeInstance(instanceId);
            _uiMethods.DisplayTitle("New Instance Information");
            _ec2Wrapper.DisplayInstanceInformation(instance);
            Console.WriteLine("Note that the IP address did not change this time.");
            _uiMethods.PressEnter(isInteractive);

            await Cleanup();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "There was a problem with the scenario, starting cleanup.");
            await Cleanup();
        }

        _uiMethods.DisplayTitle("EC2 Basics Scenario completed.");
        _uiMethods.PressEnter(isInteractive);
    }

    /// <summary>
    /// Set up the services and logging.
    /// </summary>
    /// <param name="host"></param>
    public static void SetUpServices(IHost host)
    {
        var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        });
        _logger = new Logger<EC2Basics>(loggerFactory);

        // Now the client is available for injection.
        _ec2Wrapper = host.Services.GetRequiredService<EC2Wrapper>();
        _ssmWrapper = host.Services.GetRequiredService<SsmWrapper>();
        _uiMethods = new UiMethods();
    }

    /// <summary>
    /// Clean up any resources from the scenario.
    /// </summary>
    /// <returns></returns>
    public static async Task Cleanup()
    {
        _uiMethods.DisplayTitle("Clean up resources");
        Console.WriteLine("Now let's clean up the resources we created.");

        Console.WriteLine("Disassociate the Elastic IP address and release it.");
        // Disassociate the Elastic IP address.
        await _ec2Wrapper.DisassociateIp(associationId);

        // Delete the Elastic IP address.
        await _ec2Wrapper.ReleaseAddress(allocationId);

        // Terminate the instance.
        Console.WriteLine("Terminating the instance we created.");
        await _ec2Wrapper.TerminateInstances(instanceId);

        // Delete the security group.
        Console.WriteLine($"Deleting the Security Group: {groupName}.");
        await _ec2Wrapper.DeleteSecurityGroup(secGroupId);

        // Delete the RSA key pair.
        Console.WriteLine($"Deleting the key pair: {keyPairName}");
        await _ec2Wrapper.DeleteKeyPair(keyPairName);
        Console.WriteLine("Deleting the temporary file with the key information.");
        _ec2Wrapper.DeleteTempFile(tempFileName);
        _uiMethods.PressEnter(isInteractive);
    }
}
```
EC2 アクションをラップするクラスを定義します。  

```
/// <summary>
/// Methods of this class perform Amazon Elastic Compute Cloud (Amazon EC2).
/// </summary>
public class EC2Wrapper
{
    private readonly IAmazonEC2 _amazonEC2;
    private readonly ILogger<EC2Wrapper> _logger;

    /// <summary>
    /// Constructor for the EC2Wrapper class.
    /// </summary>
    /// <param name="amazonScheduler">The injected EC2 client.</param>
    /// <param name="logger">The injected logger.</param>
    public EC2Wrapper(IAmazonEC2 amazonService, ILogger<EC2Wrapper> logger)
    {
        _amazonEC2 = amazonService;
        _logger = logger;
    }

    /// <summary>
    /// Allocates an Elastic IP address that can be associated with an Amazon EC2
    // instance. By using an Elastic IP address, you can keep the public IP address
    // constant even when you restart the associated instance.
    /// </summary>
    /// <returns>The response object for the allocated address.</returns>
    public async Task<AllocateAddressResponse> AllocateAddress()
    {
        var request = new AllocateAddressRequest();

        try
        {
            var response = await _amazonEC2.AllocateAddressAsync(request);
            Console.WriteLine($"Allocated IP: {response.PublicIp} with allocation ID {response.AllocationId}.");
            return response;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "AddressLimitExceeded")
            {
                // For more information on Elastic IP address quotas, see:
                // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-instance-addressing-limit
                _logger.LogError($"Unable to allocate Elastic IP, address limit exceeded. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while allocating Elastic IP.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Associates an Elastic IP address with an instance. When this association is
    /// created, the Elastic IP's public IP address is immediately used as the public
    /// IP address of the associated instance.
    /// </summary>
    /// <param name="allocationId">The allocation Id of an Elastic IP address.</param>
    /// <param name="instanceId">The instance Id of the EC2 instance to
    /// associate the address with.</param>
    /// <returns>The association Id that represents
    /// the association of the Elastic IP address with an instance.</returns>
    public async Task<string> AssociateAddress(string allocationId, string instanceId)
    {
        try
        {
            var request = new AssociateAddressRequest
            {
                AllocationId = allocationId,
                InstanceId = instanceId
            };

            var response = await _amazonEC2.AssociateAddressAsync(request);
            return response.AssociationId;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to associate address. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while associating the Elastic IP.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Authorize the local computer ingress to EC2 instances associated
    /// with the virtual private cloud (VPC) security group.
    /// </summary>
    /// <param name="groupName">The name of the security group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AuthorizeSecurityGroupIngress(string groupName)
    {
        try
        {
            // Get the IP address for the local computer.
            var ipAddress = await GetIpAddress();
            Console.WriteLine($"Your IP address is: {ipAddress}");
            var ipRanges =
                new List<IpRange> { new IpRange { CidrIp = $"{ipAddress}/32" } };
            var permission = new IpPermission
            {
                Ipv4Ranges = ipRanges,
                IpProtocol = "tcp",
                FromPort = 22,
                ToPort = 22
            };
            var permissions = new List<IpPermission> { permission };
            var response = await _amazonEC2.AuthorizeSecurityGroupIngressAsync(
                new AuthorizeSecurityGroupIngressRequest(groupName, permissions));
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidPermission.Duplicate")
            {
                _logger.LogError(
                    $"The ingress rule already exists. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while authorizing ingress.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Authorize the local computer for ingress to
    /// the Amazon EC2 SecurityGroup.
    /// </summary>
    /// <returns>The IPv4 address of the computer running the scenario.</returns>
    private static async Task<string> GetIpAddress()
    {
        var httpClient = new HttpClient();
        var ipString = await httpClient.GetStringAsync("https://checkip.amazonaws.com");

        // The IP address is returned with a new line
        // character on the end. Trim off the whitespace and
        // return the value to the caller.
        return ipString.Trim();
    }

    /// <summary>
    /// Create an Amazon EC2 key pair with a specified name.
    /// </summary>
    /// <param name="keyPairName">The name for the new key pair.</param>
    /// <returns>The Amazon EC2 key pair created.</returns>
    public async Task<KeyPair?> CreateKeyPair(string keyPairName)
    {
        try
        {
            var request = new CreateKeyPairRequest { KeyName = keyPairName, };

            var response = await _amazonEC2.CreateKeyPairAsync(request);

            var kp = response.KeyPair;
            // Return the key pair so it can be saved if needed.

            // Wait until the key pair exists.
            int retries = 5;
            while (retries-- > 0)
            {
                Console.WriteLine($"Checking for new KeyPair {keyPairName}...");
                var keyPairs = await DescribeKeyPairs(keyPairName);
                if (keyPairs.Any())
                {
                    return kp;
                }

                Thread.Sleep(5000);
                retries--;
            }
            _logger.LogError($"Unable to find newly created KeyPair {keyPairName}.");
            throw new DoesNotExistException("KeyPair not found");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.Duplicate")
            {
                _logger.LogError(
                    $"A key pair called {keyPairName} already exists.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating the key pair.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Save KeyPair information to a temporary file.
    /// </summary>
    /// <param name="keyPair">The name of the key pair.</param>
    /// <returns>The full path to the temporary file.</returns>
    public string SaveKeyPair(KeyPair keyPair)
    {
        var tempPath = Path.GetTempPath();
        var tempFileName = $"{tempPath}\\{Path.GetRandomFileName()}";
        var pemFileName = Path.ChangeExtension(tempFileName, "pem");

        // Save the key pair to a file in a temporary folder.
        using var stream = new FileStream(pemFileName, FileMode.Create);
        using var writer = new StreamWriter(stream);
        writer.WriteLine(keyPair.KeyMaterial);

        return pemFileName;
    }

    /// <summary>
    /// Create an Amazon EC2 security group with a specified name and description.
    /// </summary>
    /// <param name="groupName">The name for the new security group.</param>
    /// <param name="groupDescription">A description of the new security group.</param>
    /// <returns>The group Id of the new security group.</returns>
    public async Task<string> CreateSecurityGroup(string groupName, string groupDescription)
    {
        try
        {
            var response = await _amazonEC2.CreateSecurityGroupAsync(
                new CreateSecurityGroupRequest(groupName, groupDescription));

            // Wait until the security group exists.
            int retries = 5;
            while (retries-- > 0)
            {
                var groups = await DescribeSecurityGroups(response.GroupId);
                if (groups.Any())
                {
                    return response.GroupId;
                }

                Thread.Sleep(5000);
                retries--;
            }
            _logger.LogError($"Unable to find newly created group {groupName}.");
            throw new DoesNotExistException("security group not found");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "ResourceAlreadyExists")
            {
                _logger.LogError(
                    $"A security group with the name {groupName} already exists. {ec2Exception.Message}");
            }
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating the security group.: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Create a new Amazon EC2 VPC.
    /// </summary>
    /// <param name="cidrBlock">The CIDR block for the new security group.</param>
    /// <returns>The VPC Id of the new VPC.</returns>
    public async Task<string?> CreateVPC(string cidrBlock)
    {

        try
        {
            var response = await _amazonEC2.CreateVpcAsync(new CreateVpcRequest
            {
                CidrBlock = cidrBlock,
            });

            Vpc vpc = response.Vpc;
            Console.WriteLine($"Created VPC with ID: {vpc.VpcId}.");
            return vpc.VpcId;
        }
        catch (AmazonEC2Exception ex)
        {
            Console.WriteLine($"Couldn't create VPC because: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Delete an Amazon EC2 key pair.
    /// </summary>
    /// <param name="keyPairName">The name of the key pair to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteKeyPair(string keyPairName)
    {
        try
        {
            await _amazonEC2.DeleteKeyPairAsync(new DeleteKeyPairRequest(keyPairName)).ConfigureAwait(false);
            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.NotFound")
            {
                _logger.LogError($"KeyPair {keyPairName} does not exist and cannot be deleted. Please verify the key pair name and try again.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the key pair because: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Delete the temporary file where the key pair information was saved.
    /// </summary>
    /// <param name="tempFileName">The path to the temporary file.</param>
    public void DeleteTempFile(string tempFileName)
    {
        if (File.Exists(tempFileName))
        {
            File.Delete(tempFileName);
        }
    }

    /// <summary>
    /// Delete an Amazon EC2 security group.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteSecurityGroup(string groupId)
    {
        try
        {
            var response =
                await _amazonEC2.DeleteSecurityGroupAsync(
                    new DeleteSecurityGroupRequest { GroupId = groupId });
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroup.NotFound")
            {
                _logger.LogError(
                    $"Security Group {groupId} does not exist and cannot be deleted. Please verify the ID and try again.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the security group because: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Delete an Amazon EC2 VPC.
    /// </summary>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteVpc(string vpcId)
    {
        var request = new DeleteVpcRequest
        {
            VpcId = vpcId,
        };

        var response = await _amazonEC2.DeleteVpcAsync(request);

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    /// <summary>
    /// Get information about existing Amazon EC2 images.
    /// </summary>
    /// <returns>A list of image information.</returns>
    public async Task<List<Image>> DescribeImages(List<string>? imageIds)
    {
        var request = new DescribeImagesRequest();
        if (imageIds is not null)
        {
            // If the imageIds list is not null, add the list
            // to the request object.
            request.ImageIds = imageIds;
        }

        var response = await _amazonEC2.DescribeImagesAsync(request);
        return response.Images;
    }

    /// <summary>
    /// Display the information returned by DescribeImages.
    /// </summary>
    /// <param name="images">The list of image information to display.</param>
    public void DisplayImageInfo(List<Image> images)
    {
        images.ForEach(image =>
        {
            Console.WriteLine($"{image.Name} Created on: {image.CreationDate}");
        });

    }

    /// <summary>
    /// Get information about an Amazon EC2 instance.
    /// </summary>
    /// <param name="instanceId">The instance Id of the EC2 instance.</param>
    /// <returns>An EC2 instance.</returns>
    public async Task<Instance> DescribeInstance(string instanceId)
    {
        var response = await _amazonEC2.DescribeInstancesAsync(
            new DescribeInstancesRequest { InstanceIds = new List<string> { instanceId } });
        return response.Reservations[0].Instances[0];
    }

    /// <summary>
    /// Display EC2 instance information.
    /// </summary>
    /// <param name="instance">The instance Id of the EC2 instance.</param>
    public void DisplayInstanceInformation(Instance instance)
    {
        Console.WriteLine($"ID: {instance.InstanceId}");
        Console.WriteLine($"Image ID: {instance.ImageId}");
        Console.WriteLine($"{instance.InstanceType}");
        Console.WriteLine($"Key Name: {instance.KeyName}");
        Console.WriteLine($"VPC ID: {instance.VpcId}");
        Console.WriteLine($"Public IP: {instance.PublicIpAddress}");
        Console.WriteLine($"State: {instance.State.Name}");
    }

    /// <summary>
    /// Get information about EC2 instances with a particular state.
    /// </summary>
    /// <param name="tagName">The name of the tag to filter on.</param>
    /// <param name="tagValue">The value of the tag to look for.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> GetInstancesWithState(string state)
    {
        try
        {
            // Filters the results of the instance list.
            var filters = new List<Filter>
            {
                new Filter
                {
                    Name = $"instance-state-name",
                    Values = new List<string> { state, },
                },
            };
            var request = new DescribeInstancesRequest { Filters = filters, };

            Console.WriteLine($"\nShowing instances with state {state}");
            var paginator = _amazonEC2.Paginators.DescribeInstances(request);

            await foreach (var response in paginator.Responses)
            {
                foreach (var reservation in response.Reservations)
                {
                    foreach (var instance in reservation.Instances)
                    {
                        Console.Write($"Instance ID: {instance.InstanceId} ");
                        Console.WriteLine($"\tCurrent State: {instance.State.Name}");
                    }
                }
            }

            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidParameterValue")
            {
                _logger.LogError(
                    $"Invalid parameter value for filtering instances.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't list instances because: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Describe the instance types available.
    /// </summary>
    /// <returns>A list of instance type information.</returns>
    public async Task<List<InstanceTypeInfo>> DescribeInstanceTypes(ArchitectureValues architecture)
    {
        try
        {
            var request = new DescribeInstanceTypesRequest();

            var filters = new List<Filter>
            {
                new Filter("processor-info.supported-architecture",
                    new List<string> { architecture.ToString() })
            };
            filters.Add(new Filter("instance-type", new() { "*.micro", "*.small" }));

            request.Filters = filters;
            var instanceTypes = new List<InstanceTypeInfo>();

            var paginator = _amazonEC2.Paginators.DescribeInstanceTypes(request);
            await foreach (var instanceType in paginator.InstanceTypes)
            {
                instanceTypes.Add(instanceType);
            }

            return instanceTypes;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidParameterValue")
            {
                _logger.LogError(
                    $"Parameters are invalid. Ensure architecture and size strings conform to DescribeInstanceTypes API reference.");
            }

            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the security group because: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get information about an Amazon EC2 key pair.
    /// </summary>
    /// <param name="keyPairName">The name of the key pair.</param>
    /// <returns>A list of key pair information.</returns>
    public async Task<List<KeyPairInfo>> DescribeKeyPairs(string keyPairName)
    {
        try
        {
            var request = new DescribeKeyPairsRequest();
            if (!string.IsNullOrEmpty(keyPairName))
            {
                request = new DescribeKeyPairsRequest
                {
                    KeyNames = new List<string> { keyPairName }
                };
            }

            var response = await _amazonEC2.DescribeKeyPairsAsync(request);
            return response.KeyPairs.ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.NotFound")
            {
                _logger.LogError(
                    $"A key pair called {keyPairName} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while describing the key pair.: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Retrieve information for one or all Amazon EC2 security group.
    /// </summary>
    /// <param name="groupId">The optional Id of a specific Amazon EC2 security group.</param>
    /// <returns>A list of security group information.</returns>
    public async Task<List<SecurityGroup>> DescribeSecurityGroups(string groupId)
    {
        try
        {
            var securityGroups = new List<SecurityGroup>();
            var request = new DescribeSecurityGroupsRequest();

            if (!string.IsNullOrEmpty(groupId))
            {
                var groupIds = new List<string> { groupId };
                request.GroupIds = groupIds;
            }

            var paginatorForSecurityGroups =
                _amazonEC2.Paginators.DescribeSecurityGroups(request);

            await foreach (var securityGroup in paginatorForSecurityGroups.SecurityGroups)
            {
                securityGroups.Add(securityGroup);
            }

            return securityGroups;

        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroup.NotFound")
            {
                _logger.LogError(
                    $"A security group {groupId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while listing security groups. {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Display the information returned by the call to
    /// DescribeSecurityGroupsAsync.
    /// </summary>
    /// <param name="securityGroup">A list of security group information.</param>
    public void DisplaySecurityGroupInfoAsync(SecurityGroup securityGroup)
    {
        Console.WriteLine($"{securityGroup.GroupName}");
        Console.WriteLine("Ingress permissions:");
        securityGroup.IpPermissions.ForEach(permission =>
        {
            Console.WriteLine($"\tFromPort: {permission.FromPort}");
            Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");

            Console.Write($"\tIpv4Ranges: ");
            permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });

            Console.WriteLine($"\n\tIpv6Ranges:");
            permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });

            Console.Write($"\n\tPrefixListIds: ");
            permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));

            Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
        });
        Console.WriteLine("Egress permissions:");
        securityGroup.IpPermissionsEgress.ForEach(permission =>
        {
            Console.WriteLine($"\tFromPort: {permission.FromPort}");
            Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");

            Console.Write($"\tIpv4Ranges: ");
            permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });

            Console.WriteLine($"\n\tIpv6Ranges:");
            permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });

            Console.Write($"\n\tPrefixListIds: ");
            permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));

            Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
        });
    }


    /// <summary>
    /// Disassociate an Elastic IP address from an EC2 instance.
    /// </summary>
    /// <param name="associationId">The association Id.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DisassociateIp(string associationId)
    {
        try
        {
            var response = await _amazonEC2.DisassociateAddressAsync(
                new DisassociateAddressRequest { AssociationId = associationId });
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidAssociationID.NotFound")
            {
                _logger.LogError(
                    $"AssociationId is invalid, unable to disassociate address. {ec2Exception.Message}");
            }

            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while disassociating the Elastic IP.: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Reboot a specific EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the instance that will be rebooted.</param>
    /// <returns>Async Task.</returns>
    public async Task<bool> RebootInstances(string ec2InstanceId)
    {
        try
        {
            var request = new RebootInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.RebootInstancesAsync(request);

            // Wait for the instance to be running.
            Console.Write("Waiting for the instance to start.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Running);

            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId {ec2InstanceId} is invalid, unable to reboot. {ec2Exception.Message}");
            }
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while rebooting the instance {ec2InstanceId}.: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Release an Elastic IP address. After the Elastic IP address is released,
    /// it can no longer be used.
    /// </summary>
    /// <param name="allocationId">The allocation Id of the Elastic IP address.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ReleaseAddress(string allocationId)
    {
        try
        {
            var request = new ReleaseAddressRequest { AllocationId = allocationId };

            var response = await _amazonEC2.ReleaseAddressAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidAllocationID.NotFound")
            {
                _logger.LogError(
                    $"AllocationId {allocationId} was not found. {ec2Exception.Message}");
            }

            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while releasing the AllocationId {allocationId}.: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Create and run an EC2 instance.
    /// </summary>
    /// <param name="ImageId">The image Id of the image used as a basis for the
    /// EC2 instance.</param>
    /// <param name="instanceType">The instance type of the EC2 instance to create.</param>
    /// <param name="keyName">The name of the key pair to associate with the
    /// instance.</param>
    /// <param name="groupId">The Id of the Amazon EC2 security group that will be
    /// allowed to interact with the new EC2 instance.</param>
    /// <returns>The instance Id of the new EC2 instance.</returns>
    public async Task<string> RunInstances(string imageId, string instanceType, string keyName, string groupId)
    {
        try
        {
            var request = new RunInstancesRequest
            {
                ImageId = imageId,
                InstanceType = instanceType,
                KeyName = keyName,
                MinCount = 1,
                MaxCount = 1,
                SecurityGroupIds = new List<string> { groupId }
            };
            var response = await _amazonEC2.RunInstancesAsync(request);
            var instanceId = response.Reservation.Instances[0].InstanceId;

            Console.Write("Waiting for the instance to start.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);

            return instanceId;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroupId.NotFound")
            {
                _logger.LogError(
                    $"GroupId {groupId} was not found. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while running the instance.: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Start an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the Amazon EC2 instance
    /// to start.</param>
    /// <returns>Async task.</returns>
    public async Task StartInstances(string ec2InstanceId)
    {
        try
        {
            var request = new StartInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.StartInstancesAsync(request);

            Console.Write("Waiting for instance to start. ");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Running);
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to start. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while starting the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Stop an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the EC2 instance to
    /// stop.</param>
    /// <returns>Async task.</returns>
    public async Task StopInstances(string ec2InstanceId)
    {
        try
        {
            var request = new StopInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.StopInstancesAsync(request);
            Console.Write("Waiting for the instance to stop.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Stopped);

            Console.WriteLine("\nThe instance has stopped.");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to stop. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while stopping the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Terminate an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the EC2 instance
    /// to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task<List<InstanceStateChange>> TerminateInstances(string ec2InstanceId)
    {
        try
        {
            var request = new TerminateInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId }
            };

            var response = await _amazonEC2.TerminateInstancesAsync(request);
            Console.Write("Waiting for the instance to terminate.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Terminated);

            Console.WriteLine($"\nThe instance {ec2InstanceId} has been terminated.");
            return response.TerminatingInstances;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to terminate. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while terminating the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }

}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AllocateAddress)
  + [AssociateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AssociateAddress)
  + [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AuthorizeSecurityGroupIngress)
  + [CreateKeyPair](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateKeyPair)
  + [CreateSecurityGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateSecurityGroup)
  + [DeleteKeyPair](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteKeyPair)
  + [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteSecurityGroup)
  + [DescribeImages](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeImages)
  + [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstanceTypes)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstances)
  + [DescribeKeyPairs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeKeyPairs)
  + [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSecurityGroups)
  + [DisassociateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DisassociateAddress)
  + [ReleaseAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReleaseAddress)
  + [RunInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RunInstances)
  + [StartInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/StartInstances)
  + [StopInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/StopInstances)
  + [TerminateInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/TerminateInstances)
  + [UnmonitorInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/UnmonitorInstances)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_csharp_3_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Allocates an Elastic IP address that can be associated with an Amazon EC2
    // instance. By using an Elastic IP address, you can keep the public IP address
    // constant even when you restart the associated instance.
    /// </summary>
    /// <returns>The response object for the allocated address.</returns>
    public async Task<AllocateAddressResponse> AllocateAddress()
    {
        var request = new AllocateAddressRequest();

        try
        {
            var response = await _amazonEC2.AllocateAddressAsync(request);
            Console.WriteLine($"Allocated IP: {response.PublicIp} with allocation ID {response.AllocationId}.");
            return response;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "AddressLimitExceeded")
            {
                // For more information on Elastic IP address quotas, see:
                // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#using-instance-addressing-limit
                _logger.LogError($"Unable to allocate Elastic IP, address limit exceeded. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while allocating Elastic IP.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[AllocateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AllocateAddress)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_csharp_3_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Associates an Elastic IP address with an instance. When this association is
    /// created, the Elastic IP's public IP address is immediately used as the public
    /// IP address of the associated instance.
    /// </summary>
    /// <param name="allocationId">The allocation Id of an Elastic IP address.</param>
    /// <param name="instanceId">The instance Id of the EC2 instance to
    /// associate the address with.</param>
    /// <returns>The association Id that represents
    /// the association of the Elastic IP address with an instance.</returns>
    public async Task<string> AssociateAddress(string allocationId, string instanceId)
    {
        try
        {
            var request = new AssociateAddressRequest
            {
                AllocationId = allocationId,
                InstanceId = instanceId
            };

            var response = await _amazonEC2.AssociateAddressAsync(request);
            return response.AssociationId;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to associate address. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while associating the Elastic IP.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[AssociateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AssociateAddress)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_csharp_3_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Authorize the local computer ingress to EC2 instances associated
    /// with the virtual private cloud (VPC) security group.
    /// </summary>
    /// <param name="groupName">The name of the security group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AuthorizeSecurityGroupIngress(string groupName)
    {
        try
        {
            // Get the IP address for the local computer.
            var ipAddress = await GetIpAddress();
            Console.WriteLine($"Your IP address is: {ipAddress}");
            var ipRanges =
                new List<IpRange> { new IpRange { CidrIp = $"{ipAddress}/32" } };
            var permission = new IpPermission
            {
                Ipv4Ranges = ipRanges,
                IpProtocol = "tcp",
                FromPort = 22,
                ToPort = 22
            };
            var permissions = new List<IpPermission> { permission };
            var response = await _amazonEC2.AuthorizeSecurityGroupIngressAsync(
                new AuthorizeSecurityGroupIngressRequest(groupName, permissions));
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidPermission.Duplicate")
            {
                _logger.LogError(
                    $"The ingress rule already exists. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while authorizing ingress.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Authorize the local computer for ingress to
    /// the Amazon EC2 SecurityGroup.
    /// </summary>
    /// <returns>The IPv4 address of the computer running the scenario.</returns>
    private static async Task<string> GetIpAddress()
    {
        var httpClient = new HttpClient();
        var ipString = await httpClient.GetStringAsync("https://checkip.amazonaws.com");

        // The IP address is returned with a new line
        // character on the end. Trim off the whitespace and
        // return the value to the caller.
        return ipString.Trim();
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/AuthorizeSecurityGroupIngress)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_csharp_3_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an Amazon EC2 key pair with a specified name.
    /// </summary>
    /// <param name="keyPairName">The name for the new key pair.</param>
    /// <returns>The Amazon EC2 key pair created.</returns>
    public async Task<KeyPair?> CreateKeyPair(string keyPairName)
    {
        try
        {
            var request = new CreateKeyPairRequest { KeyName = keyPairName, };

            var response = await _amazonEC2.CreateKeyPairAsync(request);

            var kp = response.KeyPair;
            // Return the key pair so it can be saved if needed.

            // Wait until the key pair exists.
            int retries = 5;
            while (retries-- > 0)
            {
                Console.WriteLine($"Checking for new KeyPair {keyPairName}...");
                var keyPairs = await DescribeKeyPairs(keyPairName);
                if (keyPairs.Any())
                {
                    return kp;
                }

                Thread.Sleep(5000);
                retries--;
            }
            _logger.LogError($"Unable to find newly created KeyPair {keyPairName}.");
            throw new DoesNotExistException("KeyPair not found");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.Duplicate")
            {
                _logger.LogError(
                    $"A key pair called {keyPairName} already exists.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating the key pair.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Save KeyPair information to a temporary file.
    /// </summary>
    /// <param name="keyPair">The name of the key pair.</param>
    /// <returns>The full path to the temporary file.</returns>
    public string SaveKeyPair(KeyPair keyPair)
    {
        var tempPath = Path.GetTempPath();
        var tempFileName = $"{tempPath}\\{Path.GetRandomFileName()}";
        var pemFileName = Path.ChangeExtension(tempFileName, "pem");

        // Save the key pair to a file in a temporary folder.
        using var stream = new FileStream(pemFileName, FileMode.Create);
        using var writer = new StreamWriter(stream);
        writer.WriteLine(keyPair.KeyMaterial);

        return pemFileName;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[CreateKeyPair](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateKeyPair)」を参照してください。

### `CreateLaunchTemplate`
<a name="ec2_CreateLaunchTemplate_csharp_3_topic"></a>

次のコード例は、`CreateLaunchTemplate` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling.
    /// The launch template specifies a Bash script in its user data field that runs after
    /// the instance is started. This script installs the Python packages and starts a Python
    /// web server on the instance.
    /// </summary>
    /// <param name="startupScriptPath">The path to a Bash script file that is run.</param>
    /// <param name="instancePolicyPath">The path to a permissions policy to create and attach to the profile.</param>
    /// <returns>The template object.</returns>
    public async Task<Amazon.EC2.Model.LaunchTemplate> CreateTemplate(string startupScriptPath, string instancePolicyPath)
    {
        try
        {
            await CreateKeyPair(_keyPairName);
            await CreateInstanceProfileWithName(_instancePolicyName, _instanceRoleName,
                _instanceProfileName, instancePolicyPath);

            var startServerText = await File.ReadAllTextAsync(startupScriptPath);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(startServerText);

            var amiLatest = await _amazonSsm.GetParameterAsync(
                new GetParameterRequest() { Name = _amiParam });
            var amiId = amiLatest.Parameter.Value;
            var launchTemplateResponse = await _amazonEc2.CreateLaunchTemplateAsync(
                new CreateLaunchTemplateRequest()
                {
                    LaunchTemplateName = _launchTemplateName,
                    LaunchTemplateData = new RequestLaunchTemplateData()
                    {
                        InstanceType = _instanceType,
                        ImageId = amiId,
                        IamInstanceProfile =
                            new
                                LaunchTemplateIamInstanceProfileSpecificationRequest()
                            {
                                Name = _instanceProfileName
                            },
                        KeyName = _keyPairName,
                        UserData = System.Convert.ToBase64String(plainTextBytes)
                    }
                });
            return launchTemplateResponse.LaunchTemplate;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.AlreadyExistsException")
            {
                _logger.LogError($"Could not create the template, the name {_launchTemplateName} already exists. " +
                                 $"Please try again with a unique name.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateLaunchTemplate)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_csharp_3_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an Amazon EC2 security group with a specified name and description.
    /// </summary>
    /// <param name="groupName">The name for the new security group.</param>
    /// <param name="groupDescription">A description of the new security group.</param>
    /// <returns>The group Id of the new security group.</returns>
    public async Task<string> CreateSecurityGroup(string groupName, string groupDescription)
    {
        try
        {
            var response = await _amazonEC2.CreateSecurityGroupAsync(
                new CreateSecurityGroupRequest(groupName, groupDescription));

            // Wait until the security group exists.
            int retries = 5;
            while (retries-- > 0)
            {
                var groups = await DescribeSecurityGroups(response.GroupId);
                if (groups.Any())
                {
                    return response.GroupId;
                }

                Thread.Sleep(5000);
                retries--;
            }
            _logger.LogError($"Unable to find newly created group {groupName}.");
            throw new DoesNotExistException("security group not found");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "ResourceAlreadyExists")
            {
                _logger.LogError(
                    $"A security group with the name {groupName} already exists. {ec2Exception.Message}");
            }
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating the security group.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[CreateSecurityGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateSecurityGroup)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_csharp_3_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an Amazon EC2 key pair.
    /// </summary>
    /// <param name="keyPairName">The name of the key pair to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteKeyPair(string keyPairName)
    {
        try
        {
            await _amazonEC2.DeleteKeyPairAsync(new DeleteKeyPairRequest(keyPairName)).ConfigureAwait(false);
            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.NotFound")
            {
                _logger.LogError($"KeyPair {keyPairName} does not exist and cannot be deleted. Please verify the key pair name and try again.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the key pair because: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Delete the temporary file where the key pair information was saved.
    /// </summary>
    /// <param name="tempFileName">The path to the temporary file.</param>
    public void DeleteTempFile(string tempFileName)
    {
        if (File.Exists(tempFileName))
        {
            File.Delete(tempFileName);
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteKeyPair](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteKeyPair)」を参照してください。

### `DeleteLaunchTemplate`
<a name="ec2_DeleteLaunchTemplate_csharp_3_topic"></a>

次のコード例は、`DeleteLaunchTemplate` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a launch template by name.
    /// </summary>
    /// <param name="templateName">The name of the template to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTemplateByName(string templateName)
    {
        try
        {
            await _amazonEc2.DeleteLaunchTemplateAsync(
                new DeleteLaunchTemplateRequest()
                {
                    LaunchTemplateName = templateName
                });
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.NotFoundException")
            {
                _logger.LogError(
                    $"Could not delete the template, the name {_launchTemplateName} was not found.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while deleting the template.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteLaunchTemplate)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_csharp_3_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an Amazon EC2 security group.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteSecurityGroup(string groupId)
    {
        try
        {
            var response =
                await _amazonEC2.DeleteSecurityGroupAsync(
                    new DeleteSecurityGroupRequest { GroupId = groupId });
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroup.NotFound")
            {
                _logger.LogError(
                    $"Security Group {groupId} does not exist and cannot be deleted. Please verify the ID and try again.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the security group because: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteSecurityGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteSecurityGroup)」を参照してください。

### `DescribeAvailabilityZones`
<a name="ec2_DescribeAvailabilityZones_csharp_3_topic"></a>

次のコード例は、`DescribeAvailabilityZones` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of Availability Zones in the AWS Region of the Amazon EC2 Client.
    /// </summary>
    /// <returns>A list of availability zones.</returns>
    public async Task<List<string>> DescribeAvailabilityZones()
    {
        try
        {
            var zoneResponse = await _amazonEc2.DescribeAvailabilityZonesAsync(
                new DescribeAvailabilityZonesRequest());
            return zoneResponse.AvailabilityZones.Select(z => z.ZoneName).ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            _logger.LogError($"An Amazon EC2 error occurred while listing availability zones.: {ec2Exception.Message}");
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while listing availability zones.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeAvailabilityZones)」を参照してください。

### `DescribeIamInstanceProfileAssociations`
<a name="ec2_DescribeIamInstanceProfileAssociations_csharp_3_topic"></a>

次のコード例は、`DescribeIamInstanceProfileAssociations` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the instance profile association data for an instance.
    /// </summary>
    /// <param name="instanceId">The Id of the instance.</param>
    /// <returns>Instance profile associations data.</returns>
    public async Task<IamInstanceProfileAssociation> GetInstanceProfile(string instanceId)
    {
        try
        {
            var response = await _amazonEc2.DescribeIamInstanceProfileAssociationsAsync(
                new DescribeIamInstanceProfileAssociationsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("instance-id", new List<string>() { instanceId })
                    },
                });
            return response.IamInstanceProfileAssociations[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_csharp_3_topic"></a>

次のコード例は、`DescribeInstanceTypes` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe the instance types available.
    /// </summary>
    /// <returns>A list of instance type information.</returns>
    public async Task<List<InstanceTypeInfo>> DescribeInstanceTypes(ArchitectureValues architecture)
    {
        try
        {
            var request = new DescribeInstanceTypesRequest();

            var filters = new List<Filter>
            {
                new Filter("processor-info.supported-architecture",
                    new List<string> { architecture.ToString() })
            };
            filters.Add(new Filter("instance-type", new() { "*.micro", "*.small" }));

            request.Filters = filters;
            var instanceTypes = new List<InstanceTypeInfo>();

            var paginator = _amazonEC2.Paginators.DescribeInstanceTypes(request);
            await foreach (var instanceType in paginator.InstanceTypes)
            {
                instanceTypes.Add(instanceType);
            }

            return instanceTypes;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidParameterValue")
            {
                _logger.LogError(
                    $"Parameters are invalid. Ensure architecture and size strings conform to DescribeInstanceTypes API reference.");
            }

            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete the security group because: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeInstanceTypes](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstanceTypes)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_csharp_3_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about EC2 instances with a particular state.
    /// </summary>
    /// <param name="tagName">The name of the tag to filter on.</param>
    /// <param name="tagValue">The value of the tag to look for.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> GetInstancesWithState(string state)
    {
        try
        {
            // Filters the results of the instance list.
            var filters = new List<Filter>
            {
                new Filter
                {
                    Name = $"instance-state-name",
                    Values = new List<string> { state, },
                },
            };
            var request = new DescribeInstancesRequest { Filters = filters, };

            Console.WriteLine($"\nShowing instances with state {state}");
            var paginator = _amazonEC2.Paginators.DescribeInstances(request);

            await foreach (var response in paginator.Responses)
            {
                foreach (var reservation in response.Reservations)
                {
                    foreach (var instance in reservation.Instances)
                    {
                        Console.Write($"Instance ID: {instance.InstanceId} ");
                        Console.WriteLine($"\tCurrent State: {instance.State.Name}");
                    }
                }
            }

            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidParameterValue")
            {
                _logger.LogError(
                    $"Invalid parameter value for filtering instances.");
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't list instances because: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[DescribeInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstances)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_csharp_3_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about an Amazon EC2 key pair.
    /// </summary>
    /// <param name="keyPairName">The name of the key pair.</param>
    /// <returns>A list of key pair information.</returns>
    public async Task<List<KeyPairInfo>> DescribeKeyPairs(string keyPairName)
    {
        try
        {
            var request = new DescribeKeyPairsRequest();
            if (!string.IsNullOrEmpty(keyPairName))
            {
                request = new DescribeKeyPairsRequest
                {
                    KeyNames = new List<string> { keyPairName }
                };
            }

            var response = await _amazonEC2.DescribeKeyPairsAsync(request);
            return response.KeyPairs.ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidKeyPair.NotFound")
            {
                _logger.LogError(
                    $"A key pair called {keyPairName} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while describing the key pair.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeKeyPairs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeKeyPairs)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_csharp_3_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Retrieve information for one or all Amazon EC2 security group.
    /// </summary>
    /// <param name="groupId">The optional Id of a specific Amazon EC2 security group.</param>
    /// <returns>A list of security group information.</returns>
    public async Task<List<SecurityGroup>> DescribeSecurityGroups(string groupId)
    {
        try
        {
            var securityGroups = new List<SecurityGroup>();
            var request = new DescribeSecurityGroupsRequest();

            if (!string.IsNullOrEmpty(groupId))
            {
                var groupIds = new List<string> { groupId };
                request.GroupIds = groupIds;
            }

            var paginatorForSecurityGroups =
                _amazonEC2.Paginators.DescribeSecurityGroups(request);

            await foreach (var securityGroup in paginatorForSecurityGroups.SecurityGroups)
            {
                securityGroups.Add(securityGroup);
            }

            return securityGroups;

        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroup.NotFound")
            {
                _logger.LogError(
                    $"A security group {groupId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while listing security groups. {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Display the information returned by the call to
    /// DescribeSecurityGroupsAsync.
    /// </summary>
    /// <param name="securityGroup">A list of security group information.</param>
    public void DisplaySecurityGroupInfoAsync(SecurityGroup securityGroup)
    {
        Console.WriteLine($"{securityGroup.GroupName}");
        Console.WriteLine("Ingress permissions:");
        securityGroup.IpPermissions.ForEach(permission =>
        {
            Console.WriteLine($"\tFromPort: {permission.FromPort}");
            Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");

            Console.Write($"\tIpv4Ranges: ");
            permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });

            Console.WriteLine($"\n\tIpv6Ranges:");
            permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });

            Console.Write($"\n\tPrefixListIds: ");
            permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));

            Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
        });
        Console.WriteLine("Egress permissions:");
        securityGroup.IpPermissionsEgress.ForEach(permission =>
        {
            Console.WriteLine($"\tFromPort: {permission.FromPort}");
            Console.WriteLine($"\tIpProtocol: {permission.IpProtocol}");

            Console.Write($"\tIpv4Ranges: ");
            permission.Ipv4Ranges.ForEach(range => { Console.Write($"{range.CidrIp} "); });

            Console.WriteLine($"\n\tIpv6Ranges:");
            permission.Ipv6Ranges.ForEach(range => { Console.Write($"{range.CidrIpv6} "); });

            Console.Write($"\n\tPrefixListIds: ");
            permission.PrefixListIds.ForEach(id => Console.Write($"{id.Id} "));

            Console.WriteLine($"\n\tTo Port: {permission.ToPort}");
        });
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

### `DescribeSubnets`
<a name="ec2_DescribeSubnets_csharp_3_topic"></a>

次のコード例は、`DescribeSubnets` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get all the subnets for a Vpc in a set of availability zones.
    /// </summary>
    /// <param name="vpcId">The Id of the Vpc.</param>
    /// <param name="availabilityZones">The list of availability zones.</param>
    /// <returns>The collection of subnet objects.</returns>
    public async Task<List<Subnet>> GetAllVpcSubnetsForZones(string vpcId, List<string> availabilityZones)
    {
        try
        {
            var subnets = new List<Subnet>();
            var subnetPaginator = _amazonEc2.Paginators.DescribeSubnets(
                new DescribeSubnetsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("vpc-id", new List<string>() { vpcId }),
                        new("availability-zone", availabilityZones),
                        new("default-for-az", new List<string>() { "true" })
                    }
                });

            // Get the entire list using the paginator.
            await foreach (var subnet in subnetPaginator.Subnets)
            {
                subnets.Add(subnet);
            }

            return subnets;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidVpcID.NotFound")
            {
                _logger.LogError(ec2Exception, $"The specified VPC ID {vpcId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the subnets.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeSubnets](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSubnets)」を参照してください。

### `DescribeVpcs`
<a name="ec2_DescribeVpcs_csharp_3_topic"></a>

次のコード例は、`DescribeVpcs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the default VPC for the account.
    /// </summary>
    /// <returns>The default VPC object.</returns>
    public async Task<Vpc> GetDefaultVpc()
    {
        try
        {
            var vpcResponse = await _amazonEc2.DescribeVpcsAsync(
                new DescribeVpcsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("is-default", new List<string>() { "true" })
                    }
                });
            return vpcResponse.Vpcs[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "UnauthorizedOperation")
            {
                _logger.LogError(ec2Exception, $"You do not have the necessary permissions to describe VPCs.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the vpcs.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeVpcs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeVpcs)」を参照してください。

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_csharp_3_topic"></a>

次のコード例は、`DisassociateAddress` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Disassociate an Elastic IP address from an EC2 instance.
    /// </summary>
    /// <param name="associationId">The association Id.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DisassociateIp(string associationId)
    {
        try
        {
            var response = await _amazonEC2.DisassociateAddressAsync(
                new DisassociateAddressRequest { AssociationId = associationId });
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidAssociationID.NotFound")
            {
                _logger.LogError(
                    $"AssociationId is invalid, unable to disassociate address. {ec2Exception.Message}");
            }

            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while disassociating the Elastic IP.: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DisassociateAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DisassociateAddress)」を参照してください。

### `RebootInstances`
<a name="ec2_RebootInstances_csharp_3_topic"></a>

次のコード例は、`RebootInstances` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。
ID でインスタンスを再起動します。  

```
    /// <summary>
    /// Reboot a specific EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the instance that will be rebooted.</param>
    /// <returns>Async Task.</returns>
    public async Task<bool> RebootInstances(string ec2InstanceId)
    {
        try
        {
            var request = new RebootInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.RebootInstancesAsync(request);

            // Wait for the instance to be running.
            Console.Write("Waiting for the instance to start.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Running);

            return true;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId {ec2InstanceId} is invalid, unable to reboot. {ec2Exception.Message}");
            }
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while rebooting the instance {ec2InstanceId}.: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
インスタンスのプロファイルを置き換えて再起動し、ウェブサーバーを再起動します。  

```
    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[RebootInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RebootInstances)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_csharp_3_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Release an Elastic IP address. After the Elastic IP address is released,
    /// it can no longer be used.
    /// </summary>
    /// <param name="allocationId">The allocation Id of the Elastic IP address.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ReleaseAddress(string allocationId)
    {
        try
        {
            var request = new ReleaseAddressRequest { AllocationId = allocationId };

            var response = await _amazonEC2.ReleaseAddressAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidAllocationID.NotFound")
            {
                _logger.LogError(
                    $"AllocationId {allocationId} was not found. {ec2Exception.Message}");
            }

            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while releasing the AllocationId {allocationId}.: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[ReleaseAddress](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReleaseAddress)」を参照してください。

### `ReplaceIamInstanceProfileAssociation`
<a name="ec2_ReplaceIamInstanceProfileAssociation_csharp_3_topic"></a>

次のコード例は、`ReplaceIamInstanceProfileAssociation` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_csharp_3_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create and run an EC2 instance.
    /// </summary>
    /// <param name="ImageId">The image Id of the image used as a basis for the
    /// EC2 instance.</param>
    /// <param name="instanceType">The instance type of the EC2 instance to create.</param>
    /// <param name="keyName">The name of the key pair to associate with the
    /// instance.</param>
    /// <param name="groupId">The Id of the Amazon EC2 security group that will be
    /// allowed to interact with the new EC2 instance.</param>
    /// <returns>The instance Id of the new EC2 instance.</returns>
    public async Task<string> RunInstances(string imageId, string instanceType, string keyName, string groupId)
    {
        try
        {
            var request = new RunInstancesRequest
            {
                ImageId = imageId,
                InstanceType = instanceType,
                KeyName = keyName,
                MinCount = 1,
                MaxCount = 1,
                SecurityGroupIds = new List<string> { groupId }
            };
            var response = await _amazonEC2.RunInstancesAsync(request);
            var instanceId = response.Reservation.Instances[0].InstanceId;

            Console.Write("Waiting for the instance to start.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);

            return instanceId;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidGroupId.NotFound")
            {
                _logger.LogError(
                    $"GroupId {groupId} was not found. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while running the instance.: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[RunInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RunInstances)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_csharp_3_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Start an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the Amazon EC2 instance
    /// to start.</param>
    /// <returns>Async task.</returns>
    public async Task StartInstances(string ec2InstanceId)
    {
        try
        {
            var request = new StartInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.StartInstancesAsync(request);

            Console.Write("Waiting for instance to start. ");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Running);
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to start. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while starting the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[StartInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/StartInstances)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_csharp_3_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Stop an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the EC2 instance to
    /// stop.</param>
    /// <returns>Async task.</returns>
    public async Task StopInstances(string ec2InstanceId)
    {
        try
        {
            var request = new StopInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId },
            };

            await _amazonEC2.StopInstancesAsync(request);
            Console.Write("Waiting for the instance to stop.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Stopped);

            Console.WriteLine("\nThe instance has stopped.");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to stop. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while stopping the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[StopInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/StopInstances)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_csharp_3_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EC2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Terminate an EC2 instance.
    /// </summary>
    /// <param name="ec2InstanceId">The instance Id of the EC2 instance
    /// to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task<List<InstanceStateChange>> TerminateInstances(string ec2InstanceId)
    {
        try
        {
            var request = new TerminateInstancesRequest
            {
                InstanceIds = new List<string> { ec2InstanceId }
            };

            var response = await _amazonEC2.TerminateInstancesAsync(request);
            Console.Write("Waiting for the instance to terminate.");
            await WaitForInstanceState(ec2InstanceId, InstanceStateName.Terminated);

            Console.WriteLine($"\nThe instance {ec2InstanceId} has been terminated.");
            return response.TerminatingInstances;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceId")
            {
                _logger.LogError(
                    $"InstanceId is invalid, unable to terminate. {ec2Exception.Message}");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while terminating the instance.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEC2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[TerminateInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/TerminateInstances)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_csharp_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
    static async Task Main(string[] args)
    {
        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();


        // Set up dependency injection for the AWS services.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonIdentityManagementService>()
                    .AddAWSService<IAmazonDynamoDB>()
                    .AddAWSService<IAmazonElasticLoadBalancingV2>()
                    .AddAWSService<IAmazonSimpleSystemsManagement>()
                    .AddAWSService<IAmazonAutoScaling>()
                    .AddAWSService<IAmazonEC2>()
                    .AddTransient<AutoScalerWrapper>()
                    .AddTransient<ElasticLoadBalancerWrapper>()
                    .AddTransient<SmParameterWrapper>()
                    .AddTransient<Recommendations>()
                    .AddSingleton<IConfiguration>(_configuration)
            )
            .Build();

        ServicesSetup(host);
        ResourcesSetup();

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Welcome to the Resilient Architecture Example Scenario.");
            Console.WriteLine(new string('-', 80));
            await Deploy(true);

            Console.WriteLine("Now let's begin the scenario.");
            Console.WriteLine(new string('-', 80));
            await Demo(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Finally, let's clean up our resources.");
            Console.WriteLine(new string('-', 80));

            await DestroyResources(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Resilient Architecture Example Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            await DestroyResources(true);
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Setup any common resources, also used for integration testing.
    /// </summary>
    public static void ResourcesSetup()
    {
        _httpClient = new HttpClient();
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _elasticLoadBalancerWrapper = host.Services.GetRequiredService<ElasticLoadBalancerWrapper>();
        _iamClient = host.Services.GetRequiredService<IAmazonIdentityManagementService>();
        _recommendations = host.Services.GetRequiredService<Recommendations>();
        _autoScalerWrapper = host.Services.GetRequiredService<AutoScalerWrapper>();
        _smParameterWrapper = host.Services.GetRequiredService<SmParameterWrapper>();
    }

    /// <summary>
    /// Deploy necessary resources for the scenario.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> Deploy(bool interactive)
    {
        var protocol = "HTTP";
        var port = 80;
        var sshPort = 22;

        Console.WriteLine(
            "\nFor this demo, we'll use the AWS SDK for .NET to create several AWS resources\n" +
            "to set up a load-balanced web service endpoint and explore some ways to make it resilient\n" +
            "against various kinds of failures.\n\n" +
            "Some of the resources create by this demo are:\n");

        Console.WriteLine(
            "\t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.");
        Console.WriteLine(
            "\t* An EC2 launch template that defines EC2 instances that each contain a Python web server.");
        Console.WriteLine(
            "\t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.");
        Console.WriteLine(
            "\t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.");
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to start deploying resources.");
        if (interactive)
            Console.ReadLine();

        // Create and populate the DynamoDB table.
        var databaseTableName = _configuration["databaseName"];
        var recommendationsPath = Path.Join(_configuration["resourcePath"],
            "recommendations_objects.json");
        Console.WriteLine($"Creating and populating a DynamoDB table named {databaseTableName}.");
        await _recommendations.CreateDatabaseWithName(databaseTableName);
        await _recommendations.PopulateDatabase(databaseTableName, recommendationsPath);
        Console.WriteLine(new string('-', 80));

        // Create the EC2 Launch Template.

        Console.WriteLine(
            $"Creating an EC2 launch template that runs 'server_startup_script.sh' when an instance starts.\n"
            + "\nThis script starts a Python web server defined in the `server.py` script. The web server\n"
            + "listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.\n"
            + "For demo purposes, this server is run as the root user. In production, the best practice is to\n"
            + "run a web server, such as Apache, with least-privileged credentials.");
        Console.WriteLine(
            "\nThe template also defines an IAM policy that each instance uses to assume a role that grants\n"
            + "permissions to access the DynamoDB recommendation table and Systems Manager parameters\n"
            + "that control the flow of the demo.");

        var startupScriptPath = Path.Join(_configuration["resourcePath"],
            "server_startup_script.sh");
        var instancePolicyPath = Path.Join(_configuration["resourcePath"],
            "instance_policy.json");
        await _autoScalerWrapper.CreateTemplate(startupScriptPath, instancePolicyPath);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different\n"
            + "Availability Zone.\n");
        var zones = await _autoScalerWrapper.DescribeAvailabilityZones();
        await _autoScalerWrapper.CreateGroupOfSize(3, _autoScalerWrapper.GroupName, zones);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "At this point, you have EC2 instances created. Once each instance starts, it listens for\n"
            + "HTTP requests. You can see these instances in the console or continue with the demo.\n");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue.");
        if (interactive)
            Console.ReadLine();

        Console.WriteLine("Creating variables that control the flow of the demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine(
            "\nCreating an Elastic Load Balancing target group and load balancer. The target group\n"
            + "defines how the load balancer connects to instances. The load balancer provides a\n"
            + "single endpoint where clients connect and dispatches requests to instances in the group.");

        var defaultVpc = await _autoScalerWrapper.GetDefaultVpc();
        var subnets = await _autoScalerWrapper.GetAllVpcSubnetsForZones(defaultVpc.VpcId, zones);
        var subnetIds = subnets.Select(s => s.SubnetId).ToList();
        var targetGroup = await _elasticLoadBalancerWrapper.CreateTargetGroupOnVpc(_elasticLoadBalancerWrapper.TargetGroupName, protocol, port, defaultVpc.VpcId);

        await _elasticLoadBalancerWrapper.CreateLoadBalancerAndListener(_elasticLoadBalancerWrapper.LoadBalancerName, subnetIds, targetGroup);
        await _autoScalerWrapper.AttachLoadBalancerToGroup(_autoScalerWrapper.GroupName, targetGroup.TargetGroupArn);
        Console.WriteLine("\nVerifying access to the load balancer endpoint...");
        var endPoint = await _elasticLoadBalancerWrapper.GetEndpointForLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
        var loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);

        if (!loadBalancerAccess)
        {
            Console.WriteLine("\nCouldn't connect to the load balancer, verifying that the port is open...");

            var ipString = await _httpClient.GetStringAsync("https://checkip.amazonaws.com");
            ipString = ipString.Trim();

            var defaultSecurityGroup = await _autoScalerWrapper.GetDefaultSecurityGroupForVpc(defaultVpc);
            var portIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, port, ipString);
            var sshPortIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, sshPort, ipString);

            if (!portIsOpen)
            {
                Console.WriteLine(
                    "\nFor this example to work, the default security group for your default VPC must\n"
                    + "allows access from this computer. You can either add it automatically from this\n"
                    + "example or add it yourself using the AWS Management Console.\n");

                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound traffic from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, port, ipString);
                }
            }

            if (!sshPortIsOpen)
            {
                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound SSH traffic for debugging from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, sshPort, ipString);
                }
            }
            loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);
        }

        if (loadBalancerAccess)
        {
            Console.WriteLine("Your load balancer is ready. You can access it by browsing to:");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        else
        {
            Console.WriteLine(
                "\nCouldn't get a successful response from the load balancer endpoint. Troubleshoot by\n"
                + "manually verifying that your VPC and security group are configured correctly and that\n"
                + "you can successfully make a GET request to the load balancer endpoint:\n");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue with the demo.");
        if (interactive)
            Console.ReadLine();
        return true;
    }

    /// <summary>
    /// Demonstrate the steps of the scenario.
    /// </summary>
    /// <param name="interactive">True to run as an interactive scenario.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> Demo(bool interactive)
    {
        var ssmOnlyPolicy = Path.Join(_configuration["resourcePath"],
            "ssm_only_policy.json");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Resetting parameters to starting values for demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine("\nThis part of the demonstration shows how to toggle different parts of the system\n" +
                          "to create situations where the web service fails, and shows how using a resilient\n" +
                          "architecture can keep the web service running in spite of these failures.");
        Console.WriteLine(new string('-', 88));
        Console.WriteLine("At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine($"The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.\n" +
                          $"The table name is contained in a Systems Manager parameter named '{_smParameterWrapper.TableParameter}'.\n" +
                          $"To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");
        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as\n" +
                          "healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Instead of failing when the recommendation service fails, the web service can return a static response.");
        Console.WriteLine("While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.FailureResponseParameter, "static");

        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a static response.");
        Console.WriteLine("The service still reports as healthy because health checks are still shallow.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Let's reinstate the recommendation service.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, _smParameterWrapper.TableName);
        Console.WriteLine(
            "\nLet's also substitute bad credentials for one of the instances in the target group so that it can't\n" +
            "access the DynamoDB recommendation table.\n"
        );
        await _autoScalerWrapper.CreateInstanceProfileWithName(
            _autoScalerWrapper.BadCredsPolicyName,
            _autoScalerWrapper.BadCredsRoleName,
            _autoScalerWrapper.BadCredsProfileName,
            ssmOnlyPolicy,
            new List<string> { "AmazonSSMManagedInstanceCore" }
        );
        var instances = await _autoScalerWrapper.GetInstancesByGroupName(_autoScalerWrapper.GroupName);
        var badInstanceId = instances.First();
        var instanceProfile = await _autoScalerWrapper.GetInstanceProfile(badInstanceId);
        Console.WriteLine(
            $"Replacing the profile for instance {badInstanceId} with a profile that contains\n" +
            "bad credentials...\n"
        );
        await _autoScalerWrapper.ReplaceInstanceProfile(
            badInstanceId,
            _autoScalerWrapper.BadCredsProfileName,
            instanceProfile.AssociationId
        );
        Console.WriteLine(
            "Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,\n" +
            "depending on which instance is selected by the load balancer.\n"
        );
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nLet's implement a deep health check. For this demo, a deep health check tests whether");
        Console.WriteLine("the web service can access the DynamoDB table that it depends on for recommendations. Note that");
        Console.WriteLine("the deep health check is only for ELB routing and not for Auto Scaling instance health.");
        Console.WriteLine("This kind of deep health check is not recommended for Auto Scaling instance health, because it");
        Console.WriteLine("risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.");

        Console.WriteLine("\nBy implementing deep health checks, the load balancer can detect when one of the instances is failing");
        Console.WriteLine("and take that instance out of rotation.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.HealthCheckParameter, "deep");

        Console.WriteLine($"\nNow, checking target health indicates that the instance with bad credentials ({badInstanceId})");
        Console.WriteLine("is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy");
        Console.WriteLine("instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because");
        Console.WriteLine("the load balancer takes unhealthy instances out of its rotation.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nBecause the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy");
        Console.WriteLine("instance is to terminate it and let the auto scaler start a new instance to replace it.");

        await _autoScalerWrapper.TryTerminateInstanceById(badInstanceId);

        Console.WriteLine($"\nEven while the instance is terminating and the new instance is starting, sending a GET");
        Console.WriteLine("request to the web service continues to get a successful recommendation response because");
        Console.WriteLine("starts and reports as healthy, it is included in the load balancing rotation.");
        Console.WriteLine("Note that terminating and replacing an instance typically takes several minutes, during which time you");
        Console.WriteLine("can see the changing health check status until the new instance is running and healthy.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nIf the recommendation service fails now, deep health checks mean all instances report as unhealthy.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");

        Console.WriteLine($"\nWhen all instances are unhealthy, the load balancer continues to route requests even to");
        Console.WriteLine("unhealthy instances, allowing them to fail open and return a static response rather than fail");
        Console.WriteLine("closed and report failure to the customer.");

        if (interactive)
            await DemoActionChoices();
        await _smParameterWrapper.Reset();

        Console.WriteLine(new string('-', 80));
        return true;
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="interactive">True to ask the user for cleanup.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> DestroyResources(bool interactive)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine(
            "To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources\n" +
            "that were created for this demo."
        );

        if (!interactive || GetYesNoResponse("Do you want to clean up all demo resources? (y/n) "))
        {
            await _elasticLoadBalancerWrapper.DeleteLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
            await _elasticLoadBalancerWrapper.DeleteTargetGroupByName(_elasticLoadBalancerWrapper.TargetGroupName);
            await _autoScalerWrapper.TerminateAndDeleteAutoScalingGroupWithName(_autoScalerWrapper.GroupName);
            await _autoScalerWrapper.DeleteKeyPairByName(_autoScalerWrapper.KeyPairName);
            await _autoScalerWrapper.DeleteTemplateByName(_autoScalerWrapper.LaunchTemplateName);
            await _autoScalerWrapper.DeleteInstanceProfile(
                _autoScalerWrapper.BadCredsProfileName,
                _autoScalerWrapper.BadCredsRoleName
            );
            await _recommendations.DestroyDatabaseByName(_recommendations.TableName);
        }
        else
        {
            Console.WriteLine(
                "Ok, we'll leave the resources intact.\n" +
                "Don't forget to delete them when you're done with them or you might incur unexpected charges."
            );
        }

        Console.WriteLine(new string('-', 80));
        return true;
    }
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Amazon EC2 Auto Scaling and EC2 management methods.
/// </summary>
public class AutoScalerWrapper
{
    private readonly IAmazonAutoScaling _amazonAutoScaling;
    private readonly IAmazonEC2 _amazonEc2;
    private readonly IAmazonSimpleSystemsManagement _amazonSsm;
    private readonly IAmazonIdentityManagementService _amazonIam;
    private readonly ILogger<AutoScalerWrapper> _logger;

    private readonly string _instanceType = "";
    private readonly string _amiParam = "";
    private readonly string _launchTemplateName = "";
    private readonly string _groupName = "";
    private readonly string _instancePolicyName = "";
    private readonly string _instanceRoleName = "";
    private readonly string _instanceProfileName = "";
    private readonly string _badCredsProfileName = "";
    private readonly string _badCredsRoleName = "";
    private readonly string _badCredsPolicyName = "";
    private readonly string _keyPairName = "";

    public string GroupName => _groupName;
    public string KeyPairName => _keyPairName;
    public string LaunchTemplateName => _launchTemplateName;
    public string InstancePolicyName => _instancePolicyName;
    public string BadCredsProfileName => _badCredsProfileName;
    public string BadCredsRoleName => _badCredsRoleName;
    public string BadCredsPolicyName => _badCredsPolicyName;

    /// <summary>
    /// Constructor for the AutoScalerWrapper.
    /// </summary>
    /// <param name="amazonAutoScaling">The injected AutoScaling client.</param>
    /// <param name="amazonEc2">The injected EC2 client.</param>
    /// <param name="amazonIam">The injected IAM client.</param>
    /// <param name="amazonSsm">The injected SSM client.</param>
    public AutoScalerWrapper(
        IAmazonAutoScaling amazonAutoScaling,
        IAmazonEC2 amazonEc2,
        IAmazonSimpleSystemsManagement amazonSsm,
        IAmazonIdentityManagementService amazonIam,
        IConfiguration configuration,
        ILogger<AutoScalerWrapper> logger)
    {
        _amazonAutoScaling = amazonAutoScaling;
        _amazonEc2 = amazonEc2;
        _amazonSsm = amazonSsm;
        _amazonIam = amazonIam;
        _logger = logger;

        var prefix = configuration["resourcePrefix"];
        _instanceType = configuration["instanceType"];
        _amiParam = configuration["amiParam"];

        _launchTemplateName = prefix + "-template";
        _groupName = prefix + "-group";
        _instancePolicyName = prefix + "-pol";
        _instanceRoleName = prefix + "-role";
        _instanceProfileName = prefix + "-prof";
        _badCredsPolicyName = prefix + "-bc-pol";
        _badCredsRoleName = prefix + "-bc-role";
        _badCredsProfileName = prefix + "-bc-prof";
        _keyPairName = prefix + "-key-pair";
    }

    /// <summary>
    /// Create a policy, role, and profile that is associated with instances with a specified name.
    /// An instance's associated profile defines a role that is assumed by the
    /// instance.The role has attached policies that specify the AWS permissions granted to
    /// clients that run on the instance.
    /// </summary>
    /// <param name="policyName">Name to use for the policy.</param>
    /// <param name="roleName">Name to use for the role.</param>
    /// <param name="profileName">Name to use for the profile.</param>
    /// <param name="ssmOnlyPolicyFile">Path to a policy file for SSM.</param>
    /// <param name="awsManagedPolicies">AWS Managed policies to be attached to the role.</param>
    /// <returns>The Arn of the profile.</returns>
    public async Task<string> CreateInstanceProfileWithName(
        string policyName,
        string roleName,
        string profileName,
        string ssmOnlyPolicyFile,
        List<string>? awsManagedPolicies = null)
    {

        var assumeRoleDoc = "{" +
                                   "\"Version\": \"2012-10-17\"," +
                                   "\"Statement\": [{" +
                                        "\"Effect\": \"Allow\"," +
                                        "\"Principal\": {" +
                                        "\"Service\": [" +
                                            "\"ec2.amazonaws.com\"" +
                                        "]" +
                                        "}," +
                                   "\"Action\": \"sts:AssumeRole\"" +
                                   "}]" +
                               "}";

        var policyDocument = await File.ReadAllTextAsync(ssmOnlyPolicyFile);

        var policyArn = "";

        try
        {
            var createPolicyResult = await _amazonIam.CreatePolicyAsync(
                new CreatePolicyRequest
                {
                    PolicyName = policyName,
                    PolicyDocument = policyDocument
                });
            policyArn = createPolicyResult.Policy.Arn;
        }
        catch (EntityAlreadyExistsException)
        {
            // The policy already exists, so we look it up to get the Arn.
            var policiesPaginator = _amazonIam.Paginators.ListPolicies(
                new ListPoliciesRequest()
                {
                    Scope = PolicyScopeType.Local
                });
            // Get the entire list using the paginator.
            await foreach (var policy in policiesPaginator.Policies)
            {
                if (policy.PolicyName.Equals(policyName))
                {
                    policyArn = policy.Arn;
                }
            }

            if (policyArn == null)
            {
                throw new InvalidOperationException("Policy not found");
            }
        }

        try
        {
            await _amazonIam.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = assumeRoleDoc,
            });
            await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
            {
                RoleName = roleName,
                PolicyArn = policyArn
            });
            if (awsManagedPolicies != null)
            {
                foreach (var awsPolicy in awsManagedPolicies)
                {
                    await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
                    {
                        PolicyArn = $"arn:aws:iam::aws:policy/{awsPolicy}",
                        RoleName = roleName
                    });
                }
            }
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Role already exists.");
        }

        string profileArn = "";
        try
        {
            var profileCreateResponse = await _amazonIam.CreateInstanceProfileAsync(
                new CreateInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            // Allow time for the profile to be ready.
            profileArn = profileCreateResponse.InstanceProfile.Arn;
            Thread.Sleep(10000);
            await _amazonIam.AddRoleToInstanceProfileAsync(
                new AddRoleToInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });

        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Policy already exists.");
            var profileGetResponse = await _amazonIam.GetInstanceProfileAsync(
                new GetInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            profileArn = profileGetResponse.InstanceProfile.Arn;
        }
        return profileArn;
    }

    /// <summary>
    /// Create a new key pair and save the file.
    /// </summary>
    /// <param name="newKeyPairName">The name of the new key pair.</param>
    /// <returns>Async task.</returns>
    public async Task CreateKeyPair(string newKeyPairName)
    {
        try
        {
            var keyResponse = await _amazonEc2.CreateKeyPairAsync(
                new CreateKeyPairRequest() { KeyName = newKeyPairName });
            await File.WriteAllTextAsync($"{newKeyPairName}.pem",
                keyResponse.KeyPair.KeyMaterial);
            Console.WriteLine($"Created key pair {newKeyPairName}.");
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine("Key pair already exists.");
        }
    }

    /// <summary>
    /// Delete the key pair and file by name.
    /// </summary>
    /// <param name="deleteKeyPairName">The key pair to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteKeyPairByName(string deleteKeyPairName)
    {
        try
        {
            await _amazonEc2.DeleteKeyPairAsync(
                new DeleteKeyPairRequest() { KeyName = deleteKeyPairName });
            File.Delete($"{deleteKeyPairName}.pem");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"Key pair {deleteKeyPairName} not found.");
        }
    }

    /// <summary>
    /// Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling.
    /// The launch template specifies a Bash script in its user data field that runs after
    /// the instance is started. This script installs the Python packages and starts a Python
    /// web server on the instance.
    /// </summary>
    /// <param name="startupScriptPath">The path to a Bash script file that is run.</param>
    /// <param name="instancePolicyPath">The path to a permissions policy to create and attach to the profile.</param>
    /// <returns>The template object.</returns>
    public async Task<Amazon.EC2.Model.LaunchTemplate> CreateTemplate(string startupScriptPath, string instancePolicyPath)
    {
        try
        {
            await CreateKeyPair(_keyPairName);
            await CreateInstanceProfileWithName(_instancePolicyName, _instanceRoleName,
                _instanceProfileName, instancePolicyPath);

            var startServerText = await File.ReadAllTextAsync(startupScriptPath);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(startServerText);

            var amiLatest = await _amazonSsm.GetParameterAsync(
                new GetParameterRequest() { Name = _amiParam });
            var amiId = amiLatest.Parameter.Value;
            var launchTemplateResponse = await _amazonEc2.CreateLaunchTemplateAsync(
                new CreateLaunchTemplateRequest()
                {
                    LaunchTemplateName = _launchTemplateName,
                    LaunchTemplateData = new RequestLaunchTemplateData()
                    {
                        InstanceType = _instanceType,
                        ImageId = amiId,
                        IamInstanceProfile =
                            new
                                LaunchTemplateIamInstanceProfileSpecificationRequest()
                            {
                                Name = _instanceProfileName
                            },
                        KeyName = _keyPairName,
                        UserData = System.Convert.ToBase64String(plainTextBytes)
                    }
                });
            return launchTemplateResponse.LaunchTemplate;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.AlreadyExistsException")
            {
                _logger.LogError($"Could not create the template, the name {_launchTemplateName} already exists. " +
                                 $"Please try again with a unique name.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get a list of Availability Zones in the AWS Region of the Amazon EC2 Client.
    /// </summary>
    /// <returns>A list of availability zones.</returns>
    public async Task<List<string>> DescribeAvailabilityZones()
    {
        try
        {
            var zoneResponse = await _amazonEc2.DescribeAvailabilityZonesAsync(
                new DescribeAvailabilityZonesRequest());
            return zoneResponse.AvailabilityZones.Select(z => z.ZoneName).ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            _logger.LogError($"An Amazon EC2 error occurred while listing availability zones.: {ec2Exception.Message}");
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while listing availability zones.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Create an EC2 Auto Scaling group of a specified size and name.
    /// </summary>
    /// <param name="groupSize">The size for the group.</param>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="availabilityZones">The availability zones for the group.</param>
    /// <returns>Async task.</returns>
    public async Task CreateGroupOfSize(int groupSize, string groupName, List<string> availabilityZones)
    {
        try
        {
            await _amazonAutoScaling.CreateAutoScalingGroupAsync(
                new CreateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    AvailabilityZones = availabilityZones,
                    LaunchTemplate =
                        new Amazon.AutoScaling.Model.LaunchTemplateSpecification()
                        {
                            LaunchTemplateName = _launchTemplateName,
                            Version = "$Default"
                        },
                    MaxSize = groupSize,
                    MinSize = groupSize
                });
            Console.WriteLine($"Created EC2 Auto Scaling group {groupName} with size {groupSize}.");
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine($"EC2 Auto Scaling group {groupName} already exists.");
        }
    }

    /// <summary>
    /// Get the default VPC for the account.
    /// </summary>
    /// <returns>The default VPC object.</returns>
    public async Task<Vpc> GetDefaultVpc()
    {
        try
        {
            var vpcResponse = await _amazonEc2.DescribeVpcsAsync(
                new DescribeVpcsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("is-default", new List<string>() { "true" })
                    }
                });
            return vpcResponse.Vpcs[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "UnauthorizedOperation")
            {
                _logger.LogError(ec2Exception, $"You do not have the necessary permissions to describe VPCs.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the vpcs.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get all the subnets for a Vpc in a set of availability zones.
    /// </summary>
    /// <param name="vpcId">The Id of the Vpc.</param>
    /// <param name="availabilityZones">The list of availability zones.</param>
    /// <returns>The collection of subnet objects.</returns>
    public async Task<List<Subnet>> GetAllVpcSubnetsForZones(string vpcId, List<string> availabilityZones)
    {
        try
        {
            var subnets = new List<Subnet>();
            var subnetPaginator = _amazonEc2.Paginators.DescribeSubnets(
                new DescribeSubnetsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("vpc-id", new List<string>() { vpcId }),
                        new("availability-zone", availabilityZones),
                        new("default-for-az", new List<string>() { "true" })
                    }
                });

            // Get the entire list using the paginator.
            await foreach (var subnet in subnetPaginator.Subnets)
            {
                subnets.Add(subnet);
            }

            return subnets;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidVpcID.NotFound")
            {
                _logger.LogError(ec2Exception, $"The specified VPC ID {vpcId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the subnets.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Delete a launch template by name.
    /// </summary>
    /// <param name="templateName">The name of the template to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTemplateByName(string templateName)
    {
        try
        {
            await _amazonEc2.DeleteLaunchTemplateAsync(
                new DeleteLaunchTemplateRequest()
                {
                    LaunchTemplateName = templateName
                });
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.NotFoundException")
            {
                _logger.LogError(
                    $"Could not delete the template, the name {_launchTemplateName} was not found.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while deleting the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Detaches a role from an instance profile, detaches policies from the role,
    /// and deletes all the resources.
    /// </summary>
    /// <param name="profileName">The name of the profile to delete.</param>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteInstanceProfile(string profileName, string roleName)
    {
        try
        {
            await _amazonIam.RemoveRoleFromInstanceProfileAsync(
                new RemoveRoleFromInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });
            await _amazonIam.DeleteInstanceProfileAsync(
                new DeleteInstanceProfileRequest() { InstanceProfileName = profileName });
            var attachedPolicies = await _amazonIam.ListAttachedRolePoliciesAsync(
                new ListAttachedRolePoliciesRequest() { RoleName = roleName });
            foreach (var policy in attachedPolicies.AttachedPolicies)
            {
                await _amazonIam.DetachRolePolicyAsync(
                    new DetachRolePolicyRequest()
                    {
                        RoleName = roleName,
                        PolicyArn = policy.PolicyArn
                    });
                // Delete the custom policies only.
                if (!policy.PolicyArn.StartsWith("arn:aws:iam::aws"))
                {
                    await _amazonIam.DeletePolicyAsync(
                        new Amazon.IdentityManagement.Model.DeletePolicyRequest()
                        {
                            PolicyArn = policy.PolicyArn
                        });
                }
            }

            await _amazonIam.DeleteRoleAsync(
                new DeleteRoleRequest() { RoleName = roleName });
        }
        catch (NoSuchEntityException)
        {
            Console.WriteLine($"Instance profile {profileName} does not exist.");
        }
    }

    /// <summary>
    /// Gets data about the instances in an EC2 Auto Scaling group by its group name.
    /// </summary>
    /// <param name="group">The name of the auto scaling group.</param>
    /// <returns>A collection of instance Ids.</returns>
    public async Task<IEnumerable<string>> GetInstancesByGroupName(string group)
    {
        var instanceResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { group }
            });
        var instanceIds = instanceResponse.AutoScalingGroups.SelectMany(
            g => g.Instances.Select(i => i.InstanceId));
        return instanceIds;
    }

    /// <summary>
    /// Get the instance profile association data for an instance.
    /// </summary>
    /// <param name="instanceId">The Id of the instance.</param>
    /// <returns>Instance profile associations data.</returns>
    public async Task<IamInstanceProfileAssociation> GetInstanceProfile(string instanceId)
    {
        try
        {
            var response = await _amazonEc2.DescribeIamInstanceProfileAssociationsAsync(
                new DescribeIamInstanceProfileAssociationsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("instance-id", new List<string>() { instanceId })
                    },
                });
            return response.IamInstanceProfileAssociations[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Try to terminate an instance by its Id.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task TryTerminateInstanceById(string instanceId)
    {
        var stopping = false;
        Console.WriteLine($"Stopping {instanceId}...");
        while (!stopping)
        {
            try
            {
                await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(
                    new TerminateInstanceInAutoScalingGroupRequest()
                    {
                        InstanceId = instanceId,
                        ShouldDecrementDesiredCapacity = false
                    });
                stopping = true;
            }
            catch (ScalingActivityInProgressException)
            {
                Console.WriteLine($"Scaling activity in progress for {instanceId}. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress,
    /// waits and retries until the group is successfully deleted.
    /// </summary>
    /// <param name="groupName">The name of the group to try to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TryDeleteGroupByName(string groupName)
    {
        var stopped = false;
        while (!stopped)
        {
            try
            {
                await _amazonAutoScaling.DeleteAutoScalingGroupAsync(
                    new DeleteAutoScalingGroupRequest()
                    {
                        AutoScalingGroupName = groupName
                    });
                stopped = true;
            }
            catch (Exception e)
                when ((e is ScalingActivityInProgressException)
                      || (e is Amazon.AutoScaling.Model.ResourceInUseException))
            {
                Console.WriteLine($"Some instances are still running. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Terminate instances and delete the Auto Scaling group by name.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TerminateAndDeleteAutoScalingGroupWithName(string groupName)
    {
        var describeGroupsResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { groupName }
            });
        if (describeGroupsResponse.AutoScalingGroups.Any())
        {
            // Update the size to 0.
            await _amazonAutoScaling.UpdateAutoScalingGroupAsync(
                new UpdateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    MinSize = 0
                });
            var group = describeGroupsResponse.AutoScalingGroups[0];
            foreach (var instance in group.Instances)
            {
                await TryTerminateInstanceById(instance.InstanceId);
            }

            await TryDeleteGroupByName(groupName);
        }
        else
        {
            Console.WriteLine($"No groups found with name {groupName}.");
        }
    }


    /// <summary>
    /// Get the default security group for a specified Vpc.
    /// </summary>
    /// <param name="vpc">The Vpc to search.</param>
    /// <returns>The default security group.</returns>
    public async Task<SecurityGroup> GetDefaultSecurityGroupForVpc(Vpc vpc)
    {
        var groupResponse = await _amazonEc2.DescribeSecurityGroupsAsync(
            new DescribeSecurityGroupsRequest()
            {
                Filters = new List<Amazon.EC2.Model.Filter>()
                {
                    new ("group-name", new List<string>() { "default" }),
                    new ("vpc-id", new List<string>() { vpc.VpcId })
                }
            });
        return groupResponse.SecurityGroups[0];
    }

    /// <summary>
    /// Verify the default security group of a Vpc allows ingress from the calling computer.
    /// This can be done by allowing ingress from this computer's IP address.
    /// In some situations, such as connecting from a corporate network, you must instead specify
    /// a prefix list Id. You can also temporarily open the port to any IP address while running this example.
    /// If you do, be sure to remove public access when you're done.
    /// </summary>
    /// <param name="vpc">The group to check.</param>
    /// <param name="port">The port to verify.</param>
    /// <param name="ipAddress">This computer's IP address.</param>
    /// <returns>True if the ip address is allowed on the group.</returns>
    public bool VerifyInboundPortForGroup(SecurityGroup group, int port, string ipAddress)
    {
        var portIsOpen = false;
        foreach (var ipPermission in group.IpPermissions)
        {
            if (ipPermission.FromPort == port)
            {
                foreach (var ipRange in ipPermission.Ipv4Ranges)
                {
                    var cidr = ipRange.CidrIp;
                    if (cidr.StartsWith(ipAddress) || cidr == "0.0.0.0/0")
                    {
                        portIsOpen = true;
                    }
                }

                if (ipPermission.PrefixListIds.Any())
                {
                    portIsOpen = true;
                }

                if (!portIsOpen)
                {
                    Console.WriteLine("The inbound rule does not appear to be open to either this computer's IP\n" +
                                      "address, to all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                }
                else
                {
                    break;
                }
            }
        }

        return portIsOpen;
    }

    /// <summary>
    /// Add an ingress rule to the specified security group that allows access on the
    /// specified port from the specified IP address.
    /// </summary>
    /// <param name="groupId">The Id of the security group to modify.</param>
    /// <param name="port">The port to open.</param>
    /// <param name="ipAddress">The IP address to allow access.</param>
    /// <returns>Async task.</returns>
    public async Task OpenInboundPort(string groupId, int port, string ipAddress)
    {
        await _amazonEc2.AuthorizeSecurityGroupIngressAsync(
            new AuthorizeSecurityGroupIngressRequest()
            {
                GroupId = groupId,
                IpPermissions = new List<IpPermission>()
                {
                    new IpPermission()
                    {
                        FromPort = port,
                        ToPort = port,
                        IpProtocol = "tcp",
                        Ipv4Ranges = new List<IpRange>()
                        {
                            new IpRange() { CidrIp = $"{ipAddress}/32" }
                        }
                    }
                }
            });
    }

    /// <summary>
    /// Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
    /// The
    /// </summary>
    /// <param name="autoScalingGroupName">The name of the Auto Scaling group.</param>
    /// <param name="targetGroupArn">The Arn for the target group.</param>
    /// <returns>Async task.</returns>
    public async Task AttachLoadBalancerToGroup(string autoScalingGroupName, string targetGroupArn)
    {
        await _amazonAutoScaling.AttachLoadBalancerTargetGroupsAsync(
            new AttachLoadBalancerTargetGroupsRequest()
            {
                AutoScalingGroupName = autoScalingGroupName,
                TargetGroupARNs = new List<string>() { targetGroupArn }
            });
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEc2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Elastic Load Balancer actions.
/// </summary>
public class ElasticLoadBalancerWrapper
{
    private readonly IAmazonElasticLoadBalancingV2 _amazonElasticLoadBalancingV2;
    private string? _endpoint = null;
    private readonly string _targetGroupName = "";
    private readonly string _loadBalancerName = "";
    HttpClient _httpClient = new();

    public string TargetGroupName => _targetGroupName;
    public string LoadBalancerName => _loadBalancerName;

    /// <summary>
    /// Constructor for the Elastic Load Balancer wrapper.
    /// </summary>
    /// <param name="amazonElasticLoadBalancingV2">The injected load balancing v2 client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public ElasticLoadBalancerWrapper(
        IAmazonElasticLoadBalancingV2 amazonElasticLoadBalancingV2,
        IConfiguration configuration)
    {
        _amazonElasticLoadBalancingV2 = amazonElasticLoadBalancingV2;
        var prefix = configuration["resourcePrefix"];
        _targetGroupName = prefix + "-tg";
        _loadBalancerName = prefix + "-lb";
    }

    /// <summary>
    /// Get the HTTP Endpoint of a load balancer by its name.
    /// </summary>
    /// <param name="loadBalancerName">The name of the load balancer.</param>
    /// <returns>The HTTP endpoint.</returns>
    public async Task<string> GetEndpointForLoadBalancerByName(string loadBalancerName)
    {
        if (_endpoint == null)
        {
            var endpointResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { loadBalancerName }
                    });
            _endpoint = endpointResponse.LoadBalancers[0].DNSName;
        }

        return _endpoint;
    }

    /// <summary>
    /// Return the GET response for an endpoint as text.
    /// </summary>
    /// <param name="endpoint">The endpoint for the request.</param>
    /// <returns>The request response.</returns>
    public async Task<string> GetEndPointResponse(string endpoint)
    {
        var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
        var textResponse = await endpointResponse.Content.ReadAsStringAsync();
        return textResponse!;
    }

    /// <summary>
    /// Get the target health for a group by name.
    /// </summary>
    /// <param name="groupName">The name of the group.</param>
    /// <returns>The collection of health descriptions.</returns>
    public async Task<List<TargetHealthDescription>> CheckTargetHealthForGroup(string groupName)
    {
        List<TargetHealthDescription> result = null!;
        try
        {
            var groupResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                    new DescribeTargetGroupsRequest()
                    {
                        Names = new List<string>() { groupName }
                    });
            var healthResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetHealthAsync(
                    new DescribeTargetHealthRequest()
                    {
                        TargetGroupArn = groupResponse.TargetGroups[0].TargetGroupArn
                    });
            ;
            result = healthResponse.TargetHealthDescriptions;
        }
        catch (TargetGroupNotFoundException)
        {
            Console.WriteLine($"Target group {groupName} not found.");
        }
        return result;
    }

    /// <summary>
    /// Create an Elastic Load Balancing target group. The target group specifies how the load balancer forwards
    /// requests to instances in the group and how instance health is checked.
    ///
    /// To speed up this demo, the health check is configured with shortened times and lower thresholds. In production,
    /// you might want to decrease the sensitivity of your health checks to avoid unwanted failures.
    /// </summary>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="protocol">The protocol, such as HTTP.</param>
    /// <param name="port">The port to use to forward requests, such as 80.</param>
    /// <param name="vpcId">The Id of the Vpc in which the load balancer exists.</param>
    /// <returns>The new TargetGroup object.</returns>
    public async Task<TargetGroup> CreateTargetGroupOnVpc(string groupName, ProtocolEnum protocol, int port, string vpcId)
    {
        var createResponse = await _amazonElasticLoadBalancingV2.CreateTargetGroupAsync(
            new CreateTargetGroupRequest()
            {
                Name = groupName,
                Protocol = protocol,
                Port = port,
                HealthCheckPath = "/healthcheck",
                HealthCheckIntervalSeconds = 10,
                HealthCheckTimeoutSeconds = 5,
                HealthyThresholdCount = 2,
                UnhealthyThresholdCount = 2,
                VpcId = vpcId
            });
        var targetGroup = createResponse.TargetGroups[0];
        return targetGroup;
    }

    /// <summary>
    /// Create an Elastic Load Balancing load balancer that uses the specified subnets
    /// and forwards requests to the specified target group.
    /// </summary>
    /// <param name="name">The name for the new load balancer.</param>
    /// <param name="subnetIds">Subnets for the load balancer.</param>
    /// <param name="targetGroup">Target group for forwarded requests.</param>
    /// <returns>The new LoadBalancer object.</returns>
    public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup)
    {
        var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync(
            new CreateLoadBalancerRequest()
            {
                Name = name,
                Subnets = subnetIds
            });
        var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn;

        // Wait for load balancer to be available.
        var loadBalancerReady = false;
        while (!loadBalancerReady)
        {
            try
            {
                var describeResponse =
                    await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                        new DescribeLoadBalancersRequest()
                        {
                            Names = new List<string>() { name }
                        });

                var loadBalancerState = describeResponse.LoadBalancers[0].State.Code;

                loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active;
            }
            catch (LoadBalancerNotFoundException)
            {
                loadBalancerReady = false;
            }
            Thread.Sleep(10000);
        }
        // Create the listener.
        await _amazonElasticLoadBalancingV2.CreateListenerAsync(
            new CreateListenerRequest()
            {
                LoadBalancerArn = loadBalancerArn,
                Protocol = targetGroup.Protocol,
                Port = targetGroup.Port,
                DefaultActions = new List<Action>()
                {
                    new Action()
                    {
                        Type = ActionTypeEnum.Forward,
                        TargetGroupArn = targetGroup.TargetGroupArn
                    }
                }
            });
        return createLbResponse.LoadBalancers[0];
    }

    /// <summary>
    /// Verify this computer can successfully send a GET request to the
    /// load balancer endpoint.
    /// </summary>
    /// <param name="endpoint">The endpoint to check.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> VerifyLoadBalancerEndpoint(string endpoint)
    {
        var success = false;
        var retries = 3;
        while (!success && retries > 0)
        {
            try
            {
                var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
                Console.WriteLine($"Response: {endpointResponse.StatusCode}.");

                if (endpointResponse.IsSuccessStatusCode)
                {
                    success = true;
                }
                else
                {
                    retries = 0;
                }
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Connection error, retrying...");
                retries--;
                Thread.Sleep(10000);
            }
        }

        return success;
    }

    /// <summary>
    /// Delete a load balancer by its specified name.
    /// </summary>
    /// <param name="name">The name of the load balancer to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteLoadBalancerByName(string name)
    {
        try
        {
            var describeLoadBalancerResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { name }
                    });
            var lbArn = describeLoadBalancerResponse.LoadBalancers[0].LoadBalancerArn;
            await _amazonElasticLoadBalancingV2.DeleteLoadBalancerAsync(
                new DeleteLoadBalancerRequest()
                {
                    LoadBalancerArn = lbArn
                }
            );
        }
        catch (LoadBalancerNotFoundException)
        {
            Console.WriteLine($"Load balancer {name} not found.");
        }
    }

    /// <summary>
    /// Delete a TargetGroup by its specified name.
    /// </summary>
    /// <param name="groupName">Name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTargetGroupByName(string groupName)
    {
        var done = false;
        while (!done)
        {
            try
            {
                var groupResponse =
                    await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                        new DescribeTargetGroupsRequest()
                        {
                            Names = new List<string>() { groupName }
                        });

                var targetArn = groupResponse.TargetGroups[0].TargetGroupArn;
                await _amazonElasticLoadBalancingV2.DeleteTargetGroupAsync(
                    new DeleteTargetGroupRequest() { TargetGroupArn = targetArn });
                Console.WriteLine($"Deleted load balancing target group {groupName}.");
                done = true;
            }
            catch (TargetGroupNotFoundException)
            {
                Console.WriteLine(
                    $"Target group {groupName} not found, could not delete.");
                done = true;
            }
            catch (ResourceInUseException)
            {
                Console.WriteLine("Target group not yet released, waiting...");
                Thread.Sleep(10000);
            }
        }
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
/// <summary>
/// Encapsulates a DynamoDB table to use as a service that recommends books, movies, and songs.
/// </summary>
public class Recommendations
{
    private readonly IAmazonDynamoDB _amazonDynamoDb;
    private readonly DynamoDBContext _context;
    private readonly string _tableName;

    public string TableName => _tableName;

    /// <summary>
    /// Constructor for the Recommendations service.
    /// </summary>
    /// <param name="amazonDynamoDb">The injected DynamoDb client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public Recommendations(IAmazonDynamoDB amazonDynamoDb, IConfiguration configuration)
    {
        _amazonDynamoDb = amazonDynamoDb;
        _context = new DynamoDBContext(_amazonDynamoDb);
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Create the DynamoDb table with a specified name.
    /// </summary>
    /// <param name="tableName">The name for the table.</param>
    /// <returns>True when ready.</returns>
    public async Task<bool> CreateDatabaseWithName(string tableName)
    {
        try
        {
            Console.Write($"Creating table {tableName}...");
            var createRequest = new CreateTableRequest()
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                    {
                        new AttributeDefinition()
                        {
                            AttributeName = "MediaType",
                            AttributeType = ScalarAttributeType.S
                        },
                        new AttributeDefinition()
                        {
                            AttributeName = "ItemId",
                            AttributeType = ScalarAttributeType.N
                        }
                    },
                KeySchema = new List<KeySchemaElement>()
                    {
                        new KeySchemaElement()
                        {
                            AttributeName = "MediaType",
                            KeyType = KeyType.HASH
                        },
                        new KeySchemaElement()
                        {
                            AttributeName = "ItemId",
                            KeyType = KeyType.RANGE
                        }
                    },
                ProvisionedThroughput = new ProvisionedThroughput()
                {
                    ReadCapacityUnits = 5,
                    WriteCapacityUnits = 5
                }
            };
            await _amazonDynamoDb.CreateTableAsync(createRequest);

            // Wait until the table is ACTIVE and then report success.
            Console.Write("\nWaiting for table to become active...");

            var request = new DescribeTableRequest
            {
                TableName = tableName
            };

            TableStatus status;
            do
            {
                Thread.Sleep(2000);

                var describeTableResponse = await _amazonDynamoDb.DescribeTableAsync(request);
                status = describeTableResponse.Table.TableStatus;

                Console.Write(".");
            }
            while (status != "ACTIVE");

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException)
        {
            Console.WriteLine($"Table {tableName} already exists.");
            return false;
        }
    }

    /// <summary>
    /// Populate the database table with data from a specified path.
    /// </summary>
    /// <param name="databaseTableName">The name of the table.</param>
    /// <param name="recommendationsPath">The path of the recommendations data.</param>
    /// <returns>Async task.</returns>
    public async Task PopulateDatabase(string databaseTableName, string recommendationsPath)
    {
        var recommendationsText = await File.ReadAllTextAsync(recommendationsPath);
        var records =
            JsonSerializer.Deserialize<RecommendationModel[]>(recommendationsText);
        var batchWrite = _context.CreateBatchWrite<RecommendationModel>();

        foreach (var record in records!)
        {
            batchWrite.AddPutItem(record);
        }

        await batchWrite.ExecuteAsync();
    }

    /// <summary>
    /// Delete the recommendation table by name.
    /// </summary>
    /// <param name="tableName">The name of the recommendation table.</param>
    /// <returns>Async task.</returns>
    public async Task DestroyDatabaseByName(string tableName)
    {
        try
        {
            await _amazonDynamoDb.DeleteTableAsync(
                new DeleteTableRequest() { TableName = tableName });
            Console.WriteLine($"Table {tableName} was deleted.");
        }
        catch (ResourceNotFoundException)
        {
            Console.WriteLine($"Table {tableName} not found");
        }
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Systems Manager parameter operations. This example uses these parameters
/// to drive the demonstration of resilient architecture, such as failure of a dependency or
/// how the service responds to a health check.
/// </summary>
public class SmParameterWrapper
{
    private readonly IAmazonSimpleSystemsManagement _amazonSimpleSystemsManagement;

    private readonly string _tableParameter = "doc-example-resilient-architecture-table";
    private readonly string _failureResponseParameter = "doc-example-resilient-architecture-failure-response";
    private readonly string _healthCheckParameter = "doc-example-resilient-architecture-health-check";
    private readonly string _tableName = "";

    public string TableParameter => _tableParameter;
    public string TableName => _tableName;
    public string HealthCheckParameter => _healthCheckParameter;
    public string FailureResponseParameter => _failureResponseParameter;

    /// <summary>
    /// Constructor for the SmParameterWrapper.
    /// </summary>
    /// <param name="amazonSimpleSystemsManagement">The injected Simple Systems Management client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public SmParameterWrapper(IAmazonSimpleSystemsManagement amazonSimpleSystemsManagement, IConfiguration configuration)
    {
        _amazonSimpleSystemsManagement = amazonSimpleSystemsManagement;
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Reset the Systems Manager parameters to starting values for the demo.
    /// </summary>
    /// <returns>Async task.</returns>
    public async Task Reset()
    {
        await this.PutParameterByName(_tableParameter, _tableName);
        await this.PutParameterByName(_failureResponseParameter, "none");
        await this.PutParameterByName(_healthCheckParameter, "shallow");
    }

    /// <summary>
    /// Set the value of a named Systems Manager parameter.
    /// </summary>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="value">The value to set.</param>
    /// <returns>Async task.</returns>
    public async Task PutParameterByName(string name, string value)
    {
        await _amazonSimpleSystemsManagement.PutParameterAsync(
            new PutParameterRequest() { Name = name, Value = value, Overwrite = true });
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# を使用した Amazon ECS の例 SDK for .NET
<a name="csharp_3_ecs_code_examples"></a>

次のコード例は、Amazon ECS AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `ListClusters`
<a name="ecs_ListClusters_csharp_3_topic"></a>

次のコード例は、`ListClusters` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/ECS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List cluster ARNs available.
    /// </summary>
    /// <returns>The ARN list of clusters.</returns>
    public async Task<List<string>> GetClusterARNSAsync()
    {

        Console.WriteLine("Getting a list of all the clusters in your AWS account...");
        List<string> clusterArnList = new List<string>();
        // Get a list of all the clusters in your AWS account
        try
        {

            var listClustersResponse = _ecsClient.Paginators.ListClusters(new ListClustersRequest
            {
            });

            var clusterArns = listClustersResponse.ClusterArns;

            // Print the ARNs of the clusters
            await foreach (var clusterArn in clusterArns)
            {
                clusterArnList.Add(clusterArn);
            }

            if (clusterArnList.Count == 0)
            {
                _logger.LogWarning("No clusters found in your AWS account.");
            }
            return clusterArnList;
        }
        catch (Exception e)
        {
            _logger.LogError($"An error occurred while getting a list of all the clusters in your AWS account. {e.InnerException}");
            throw new Exception($"An error occurred while getting a list of all the clusters in your AWS account. {e.InnerException}");
        }
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」の「[ListClusters](https://docs.aws.amazon.com/goto/DotNetSDKV3/ecs-2014-11-13/ListClusters)」を参照してください。

### `ListServices`
<a name="ecs_ListServices_csharp_3_topic"></a>

次のコード例は、`ListServices` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/ECS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List service ARNs available.
    /// </summary>
    /// <param name="clusterARN">The arn of the ECS cluster.</param>
    /// <returns>The ARN list of services in given cluster.</returns>
    public async Task<List<string>> GetServiceARNSAsync(string clusterARN)
    {
        List<string> serviceArns = new List<string>();

        var request = new ListServicesRequest
        {
            Cluster = clusterARN
        };
        // Call the ListServices API operation and get the list of service ARNs
        var serviceList = _ecsClient.Paginators.ListServices(request);

        await foreach (var serviceARN in serviceList.ServiceArns)
        {
            if (serviceARN is null)
                continue;

            serviceArns.Add(serviceARN);
        }

        if (serviceArns.Count == 0)
        {
            _logger.LogWarning($"No services found in cluster {clusterARN} .");
        }

        return serviceArns;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListServices](https://docs.aws.amazon.com/goto/DotNetSDKV3/ecs-2014-11-13/ListServices)」を参照してください。

### `ListTasks`
<a name="ecs_ListTasks_csharp_3_topic"></a>

次のコード例は、`ListTasks` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/ECS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List task ARNs available.
    /// </summary>
    /// <param name="clusterARN">The arn of the ECS cluster.</param>
    /// <returns>The ARN list of tasks in given cluster.</returns>
    public async Task<List<string>> GetTaskARNsAsync(string clusterARN)
    {
        // Set up the request to describe the tasks in the service
        var listTasksRequest = new ListTasksRequest
        {
            Cluster = clusterARN
        };
        List<string> taskArns = new List<string>();

        // Call the ListTasks API operation and get the list of task ARNs
        var tasks = _ecsClient.Paginators.ListTasks(listTasksRequest);

        await foreach (var task in tasks.TaskArns)
        {
            if (task is null)
                continue;


            taskArns.Add(task);
        }

        if (taskArns.Count == 0)
        {
            _logger.LogWarning("No tasks found in cluster: " + clusterARN);
        }

        return taskArns;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListTasks](https://docs.aws.amazon.com/goto/DotNetSDKV3/ecs-2014-11-13/ListTasks)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### クラスター、サービス、タスクの ARN 情報を取得する
<a name="ecs_Scenario_GetClustersServicesAndTasks_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ すべてのクラスターのリストを取得する。
+ クラスターのサービスを取得する。
+ クラスターのタスクを取得する。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/ECS#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
using Amazon.ECS;
using ECSActions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;

namespace ECSScenario;

public class ECSScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.


    This .NET example performs the following tasks:
        1. List ECS Cluster ARNs.
        2. List services in every cluster
        3. List Task ARNs in every cluster.
    */

    private static ILogger logger = null!;
    private static ECSWrapper _ecsWrapper = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
        .Build();

        ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        });

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<ECSScenario>();

        var loggerECSWarpper = LoggerFactory.Create(builder => { builder.AddConsole(); })
          .CreateLogger<ECSWrapper>();

        var amazonECSClient = new AmazonECSClient();

        _ecsWrapper = new ECSWrapper(amazonECSClient, loggerECSWarpper);

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the Amazon ECS example scenario.");
        Console.WriteLine(new string('-', 80));

        try
        {
            await ListClusterARNs();
            await ListServiceARNs();
            await ListTaskARNs();

        }
        catch (Exception ex)
        {
            logger.LogError(ex, "There was a problem executing the scenario.");
        }
    }

    /// <summary>
    /// List ECS Cluster ARNs
    /// </summary>
    private static async Task ListClusterARNs()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"1. List Cluster ARNs from ECS.");
        var arns = await _ecsWrapper.GetClusterARNSAsync();

        foreach (var arn in arns)
        {
            Console.WriteLine($"Cluster arn: {arn}");
            Console.WriteLine($"Cluster name: {arn.Split("/").Last()}");
        }

        Console.WriteLine(new string('-', 80));
    }


    /// <summary>
    /// List services in every cluster
    /// </summary>
    private static async Task ListServiceARNs()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"2. List Service ARNs in every cluster.");
        var clusterARNs = await _ecsWrapper.GetClusterARNSAsync();

        foreach (var clusterARN in clusterARNs)
        {
            Console.WriteLine($"Getting services for cluster name: {clusterARN.Split("/").Last()}");
            Console.WriteLine(new string('.', 5));


            var serviceARNs = await _ecsWrapper.GetServiceARNSAsync(clusterARN);

            foreach (var serviceARN in serviceARNs)
            {
                Console.WriteLine($"Service arn: {serviceARN}");
                Console.WriteLine($"Service name: {serviceARN.Split("/").Last()}");
            }
        }

        Console.WriteLine(new string('-', 80));
    }


    /// <summary>
    /// List tasks in every cluster
    /// </summary>
    private static async Task ListTaskARNs()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"3. List Task ARNs in every cluster.");
        var clusterARNs = await _ecsWrapper.GetClusterARNSAsync();

        foreach (var clusterARN in clusterARNs)
        {
            Console.WriteLine($"Getting tasks for cluster name: {clusterARN.Split("/").Last()}");
            Console.WriteLine(new string('.', 5));

            var taskARNs = await _ecsWrapper.GetTaskARNsAsync(clusterARN);

            foreach (var taskARN in taskARNs)
            {
                Console.WriteLine($"Task arn: {taskARN}");
            }
        }
        Console.WriteLine(new string('-', 80));
    }
}
```
Amazon ECS アクションを管理するためにシナリオによって呼び出されるラッパーメソッド。  

```
using Amazon.ECS;
using Amazon.ECS.Model;
using Microsoft.Extensions.Logging;

namespace ECSActions;

public class ECSWrapper
{
    private readonly AmazonECSClient _ecsClient;
    private readonly ILogger<ECSWrapper> _logger;

    /// <summary>
    /// Constructor for the ECS wrapper.
    /// </summary>
    /// <param name="ecsClient">The injected ECS client.</param>
    /// <param name="logger">The injected logger for the wrapper.</param>
    public ECSWrapper(AmazonECSClient ecsClient, ILogger<ECSWrapper> logger)

    {
        _logger = logger;
        _ecsClient = ecsClient;
    }

    /// <summary>
    /// List cluster ARNs available.
    /// </summary>
    /// <returns>The ARN list of clusters.</returns>
    public async Task<List<string>> GetClusterARNSAsync()
    {

        Console.WriteLine("Getting a list of all the clusters in your AWS account...");
        List<string> clusterArnList = new List<string>();
        // Get a list of all the clusters in your AWS account
        try
        {

            var listClustersResponse = _ecsClient.Paginators.ListClusters(new ListClustersRequest
            {
            });

            var clusterArns = listClustersResponse.ClusterArns;

            // Print the ARNs of the clusters
            await foreach (var clusterArn in clusterArns)
            {
                clusterArnList.Add(clusterArn);
            }

            if (clusterArnList.Count == 0)
            {
                _logger.LogWarning("No clusters found in your AWS account.");
            }
            return clusterArnList;
        }
        catch (Exception e)
        {
            _logger.LogError($"An error occurred while getting a list of all the clusters in your AWS account. {e.InnerException}");
            throw new Exception($"An error occurred while getting a list of all the clusters in your AWS account. {e.InnerException}");
        }
    }

    /// <summary>
    /// List service ARNs available.
    /// </summary>
    /// <param name="clusterARN">The arn of the ECS cluster.</param>
    /// <returns>The ARN list of services in given cluster.</returns>
    public async Task<List<string>> GetServiceARNSAsync(string clusterARN)
    {
        List<string> serviceArns = new List<string>();

        var request = new ListServicesRequest
        {
            Cluster = clusterARN
        };
        // Call the ListServices API operation and get the list of service ARNs
        var serviceList = _ecsClient.Paginators.ListServices(request);

        await foreach (var serviceARN in serviceList.ServiceArns)
        {
            if (serviceARN is null)
                continue;

            serviceArns.Add(serviceARN);
        }

        if (serviceArns.Count == 0)
        {
            _logger.LogWarning($"No services found in cluster {clusterARN} .");
        }

        return serviceArns;
    }

    /// <summary>
    /// List task ARNs available.
    /// </summary>
    /// <param name="clusterARN">The arn of the ECS cluster.</param>
    /// <returns>The ARN list of tasks in given cluster.</returns>
    public async Task<List<string>> GetTaskARNsAsync(string clusterARN)
    {
        // Set up the request to describe the tasks in the service
        var listTasksRequest = new ListTasksRequest
        {
            Cluster = clusterARN
        };
        List<string> taskArns = new List<string>();

        // Call the ListTasks API operation and get the list of task ARNs
        var tasks = _ecsClient.Paginators.ListTasks(listTasksRequest);

        await foreach (var task in tasks.TaskArns)
        {
            if (task is null)
                continue;


            taskArns.Add(task);
        }

        if (taskArns.Count == 0)
        {
            _logger.LogWarning("No tasks found in cluster: " + clusterARN);
        }

        return taskArns;
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [ListClusters](https://docs.aws.amazon.com/goto/DotNetSDKV3/ecs-2014-11-13/ListClusters)
  + [ListServices](https://docs.aws.amazon.com/goto/DotNetSDKV3/ecs-2014-11-13/ListServices)
  + [ListTasks](https://docs.aws.amazon.com/goto/DotNetSDKV3/ecs-2014-11-13/ListTasks)

# を使用した Elastic Load Balancing - バージョン 2 の例 SDK for .NET
<a name="csharp_3_elastic-load-balancing-v2_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 2 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateListener`
<a name="elastic-load-balancing-v2_CreateListener_csharp_3_topic"></a>

次のコード例は、`CreateListener` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an Elastic Load Balancing load balancer that uses the specified subnets
    /// and forwards requests to the specified target group.
    /// </summary>
    /// <param name="name">The name for the new load balancer.</param>
    /// <param name="subnetIds">Subnets for the load balancer.</param>
    /// <param name="targetGroup">Target group for forwarded requests.</param>
    /// <returns>The new LoadBalancer object.</returns>
    public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup)
    {
        var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync(
            new CreateLoadBalancerRequest()
            {
                Name = name,
                Subnets = subnetIds
            });
        var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn;

        // Wait for load balancer to be available.
        var loadBalancerReady = false;
        while (!loadBalancerReady)
        {
            try
            {
                var describeResponse =
                    await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                        new DescribeLoadBalancersRequest()
                        {
                            Names = new List<string>() { name }
                        });

                var loadBalancerState = describeResponse.LoadBalancers[0].State.Code;

                loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active;
            }
            catch (LoadBalancerNotFoundException)
            {
                loadBalancerReady = false;
            }
            Thread.Sleep(10000);
        }
        // Create the listener.
        await _amazonElasticLoadBalancingV2.CreateListenerAsync(
            new CreateListenerRequest()
            {
                LoadBalancerArn = loadBalancerArn,
                Protocol = targetGroup.Protocol,
                Port = targetGroup.Port,
                DefaultActions = new List<Action>()
                {
                    new Action()
                    {
                        Type = ActionTypeEnum.Forward,
                        TargetGroupArn = targetGroup.TargetGroupArn
                    }
                }
            });
        return createLbResponse.LoadBalancers[0];
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateListener](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateListener)」を参照してください。

### `CreateLoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_csharp_3_topic"></a>

次のコード例は、`CreateLoadBalancer` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an Elastic Load Balancing load balancer that uses the specified subnets
    /// and forwards requests to the specified target group.
    /// </summary>
    /// <param name="name">The name for the new load balancer.</param>
    /// <param name="subnetIds">Subnets for the load balancer.</param>
    /// <param name="targetGroup">Target group for forwarded requests.</param>
    /// <returns>The new LoadBalancer object.</returns>
    public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup)
    {
        var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync(
            new CreateLoadBalancerRequest()
            {
                Name = name,
                Subnets = subnetIds
            });
        var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn;

        // Wait for load balancer to be available.
        var loadBalancerReady = false;
        while (!loadBalancerReady)
        {
            try
            {
                var describeResponse =
                    await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                        new DescribeLoadBalancersRequest()
                        {
                            Names = new List<string>() { name }
                        });

                var loadBalancerState = describeResponse.LoadBalancers[0].State.Code;

                loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active;
            }
            catch (LoadBalancerNotFoundException)
            {
                loadBalancerReady = false;
            }
            Thread.Sleep(10000);
        }
        // Create the listener.
        await _amazonElasticLoadBalancingV2.CreateListenerAsync(
            new CreateListenerRequest()
            {
                LoadBalancerArn = loadBalancerArn,
                Protocol = targetGroup.Protocol,
                Port = targetGroup.Port,
                DefaultActions = new List<Action>()
                {
                    new Action()
                    {
                        Type = ActionTypeEnum.Forward,
                        TargetGroupArn = targetGroup.TargetGroupArn
                    }
                }
            });
        return createLbResponse.LoadBalancers[0];
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)」を参照してください。

### `CreateTargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_csharp_3_topic"></a>

次のコード例は、`CreateTargetGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an Elastic Load Balancing target group. The target group specifies how the load balancer forwards
    /// requests to instances in the group and how instance health is checked.
    ///
    /// To speed up this demo, the health check is configured with shortened times and lower thresholds. In production,
    /// you might want to decrease the sensitivity of your health checks to avoid unwanted failures.
    /// </summary>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="protocol">The protocol, such as HTTP.</param>
    /// <param name="port">The port to use to forward requests, such as 80.</param>
    /// <param name="vpcId">The Id of the Vpc in which the load balancer exists.</param>
    /// <returns>The new TargetGroup object.</returns>
    public async Task<TargetGroup> CreateTargetGroupOnVpc(string groupName, ProtocolEnum protocol, int port, string vpcId)
    {
        var createResponse = await _amazonElasticLoadBalancingV2.CreateTargetGroupAsync(
            new CreateTargetGroupRequest()
            {
                Name = groupName,
                Protocol = protocol,
                Port = port,
                HealthCheckPath = "/healthcheck",
                HealthCheckIntervalSeconds = 10,
                HealthCheckTimeoutSeconds = 5,
                HealthyThresholdCount = 2,
                UnhealthyThresholdCount = 2,
                VpcId = vpcId
            });
        var targetGroup = createResponse.TargetGroups[0];
        return targetGroup;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)」を参照してください。

### `DeleteLoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_csharp_3_topic"></a>

次のコード例は、`DeleteLoadBalancer` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a load balancer by its specified name.
    /// </summary>
    /// <param name="name">The name of the load balancer to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteLoadBalancerByName(string name)
    {
        try
        {
            var describeLoadBalancerResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { name }
                    });
            var lbArn = describeLoadBalancerResponse.LoadBalancers[0].LoadBalancerArn;
            await _amazonElasticLoadBalancingV2.DeleteLoadBalancerAsync(
                new DeleteLoadBalancerRequest()
                {
                    LoadBalancerArn = lbArn
                }
            );
        }
        catch (LoadBalancerNotFoundException)
        {
            Console.WriteLine($"Load balancer {name} not found.");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)」を参照してください。

### `DeleteTargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_csharp_3_topic"></a>

次のコード例は、`DeleteTargetGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a TargetGroup by its specified name.
    /// </summary>
    /// <param name="groupName">Name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTargetGroupByName(string groupName)
    {
        var done = false;
        while (!done)
        {
            try
            {
                var groupResponse =
                    await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                        new DescribeTargetGroupsRequest()
                        {
                            Names = new List<string>() { groupName }
                        });

                var targetArn = groupResponse.TargetGroups[0].TargetGroupArn;
                await _amazonElasticLoadBalancingV2.DeleteTargetGroupAsync(
                    new DeleteTargetGroupRequest() { TargetGroupArn = targetArn });
                Console.WriteLine($"Deleted load balancing target group {groupName}.");
                done = true;
            }
            catch (TargetGroupNotFoundException)
            {
                Console.WriteLine(
                    $"Target group {groupName} not found, could not delete.");
                done = true;
            }
            catch (ResourceInUseException)
            {
                Console.WriteLine("Target group not yet released, waiting...");
                Thread.Sleep(10000);
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)」を参照してください。

### `DescribeLoadBalancers`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_csharp_3_topic"></a>

次のコード例は、`DescribeLoadBalancers` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the HTTP Endpoint of a load balancer by its name.
    /// </summary>
    /// <param name="loadBalancerName">The name of the load balancer.</param>
    /// <returns>The HTTP endpoint.</returns>
    public async Task<string> GetEndpointForLoadBalancerByName(string loadBalancerName)
    {
        if (_endpoint == null)
        {
            var endpointResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { loadBalancerName }
                    });
            _endpoint = endpointResponse.LoadBalancers[0].DNSName;
        }

        return _endpoint;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeLoadBalancers](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)」を参照してください。

### `DescribeTargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_csharp_3_topic"></a>

次のコード例は、`DescribeTargetHealth` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/ElasticLoadBalancerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the target health for a group by name.
    /// </summary>
    /// <param name="groupName">The name of the group.</param>
    /// <returns>The collection of health descriptions.</returns>
    public async Task<List<TargetHealthDescription>> CheckTargetHealthForGroup(string groupName)
    {
        List<TargetHealthDescription> result = null!;
        try
        {
            var groupResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                    new DescribeTargetGroupsRequest()
                    {
                        Names = new List<string>() { groupName }
                    });
            var healthResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetHealthAsync(
                    new DescribeTargetHealthRequest()
                    {
                        TargetGroupArn = groupResponse.TargetGroups[0].TargetGroupArn
                    });
            ;
            result = healthResponse.TargetHealthDescriptions;
        }
        catch (TargetGroupNotFoundException)
        {
            Console.WriteLine($"Target group {groupName} not found.");
        }
        return result;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeTargetHealth](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_csharp_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
    static async Task Main(string[] args)
    {
        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();


        // Set up dependency injection for the AWS services.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonIdentityManagementService>()
                    .AddAWSService<IAmazonDynamoDB>()
                    .AddAWSService<IAmazonElasticLoadBalancingV2>()
                    .AddAWSService<IAmazonSimpleSystemsManagement>()
                    .AddAWSService<IAmazonAutoScaling>()
                    .AddAWSService<IAmazonEC2>()
                    .AddTransient<AutoScalerWrapper>()
                    .AddTransient<ElasticLoadBalancerWrapper>()
                    .AddTransient<SmParameterWrapper>()
                    .AddTransient<Recommendations>()
                    .AddSingleton<IConfiguration>(_configuration)
            )
            .Build();

        ServicesSetup(host);
        ResourcesSetup();

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Welcome to the Resilient Architecture Example Scenario.");
            Console.WriteLine(new string('-', 80));
            await Deploy(true);

            Console.WriteLine("Now let's begin the scenario.");
            Console.WriteLine(new string('-', 80));
            await Demo(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Finally, let's clean up our resources.");
            Console.WriteLine(new string('-', 80));

            await DestroyResources(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Resilient Architecture Example Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            await DestroyResources(true);
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Setup any common resources, also used for integration testing.
    /// </summary>
    public static void ResourcesSetup()
    {
        _httpClient = new HttpClient();
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _elasticLoadBalancerWrapper = host.Services.GetRequiredService<ElasticLoadBalancerWrapper>();
        _iamClient = host.Services.GetRequiredService<IAmazonIdentityManagementService>();
        _recommendations = host.Services.GetRequiredService<Recommendations>();
        _autoScalerWrapper = host.Services.GetRequiredService<AutoScalerWrapper>();
        _smParameterWrapper = host.Services.GetRequiredService<SmParameterWrapper>();
    }

    /// <summary>
    /// Deploy necessary resources for the scenario.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> Deploy(bool interactive)
    {
        var protocol = "HTTP";
        var port = 80;
        var sshPort = 22;

        Console.WriteLine(
            "\nFor this demo, we'll use the AWS SDK for .NET to create several AWS resources\n" +
            "to set up a load-balanced web service endpoint and explore some ways to make it resilient\n" +
            "against various kinds of failures.\n\n" +
            "Some of the resources create by this demo are:\n");

        Console.WriteLine(
            "\t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.");
        Console.WriteLine(
            "\t* An EC2 launch template that defines EC2 instances that each contain a Python web server.");
        Console.WriteLine(
            "\t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.");
        Console.WriteLine(
            "\t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.");
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to start deploying resources.");
        if (interactive)
            Console.ReadLine();

        // Create and populate the DynamoDB table.
        var databaseTableName = _configuration["databaseName"];
        var recommendationsPath = Path.Join(_configuration["resourcePath"],
            "recommendations_objects.json");
        Console.WriteLine($"Creating and populating a DynamoDB table named {databaseTableName}.");
        await _recommendations.CreateDatabaseWithName(databaseTableName);
        await _recommendations.PopulateDatabase(databaseTableName, recommendationsPath);
        Console.WriteLine(new string('-', 80));

        // Create the EC2 Launch Template.

        Console.WriteLine(
            $"Creating an EC2 launch template that runs 'server_startup_script.sh' when an instance starts.\n"
            + "\nThis script starts a Python web server defined in the `server.py` script. The web server\n"
            + "listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.\n"
            + "For demo purposes, this server is run as the root user. In production, the best practice is to\n"
            + "run a web server, such as Apache, with least-privileged credentials.");
        Console.WriteLine(
            "\nThe template also defines an IAM policy that each instance uses to assume a role that grants\n"
            + "permissions to access the DynamoDB recommendation table and Systems Manager parameters\n"
            + "that control the flow of the demo.");

        var startupScriptPath = Path.Join(_configuration["resourcePath"],
            "server_startup_script.sh");
        var instancePolicyPath = Path.Join(_configuration["resourcePath"],
            "instance_policy.json");
        await _autoScalerWrapper.CreateTemplate(startupScriptPath, instancePolicyPath);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different\n"
            + "Availability Zone.\n");
        var zones = await _autoScalerWrapper.DescribeAvailabilityZones();
        await _autoScalerWrapper.CreateGroupOfSize(3, _autoScalerWrapper.GroupName, zones);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "At this point, you have EC2 instances created. Once each instance starts, it listens for\n"
            + "HTTP requests. You can see these instances in the console or continue with the demo.\n");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue.");
        if (interactive)
            Console.ReadLine();

        Console.WriteLine("Creating variables that control the flow of the demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine(
            "\nCreating an Elastic Load Balancing target group and load balancer. The target group\n"
            + "defines how the load balancer connects to instances. The load balancer provides a\n"
            + "single endpoint where clients connect and dispatches requests to instances in the group.");

        var defaultVpc = await _autoScalerWrapper.GetDefaultVpc();
        var subnets = await _autoScalerWrapper.GetAllVpcSubnetsForZones(defaultVpc.VpcId, zones);
        var subnetIds = subnets.Select(s => s.SubnetId).ToList();
        var targetGroup = await _elasticLoadBalancerWrapper.CreateTargetGroupOnVpc(_elasticLoadBalancerWrapper.TargetGroupName, protocol, port, defaultVpc.VpcId);

        await _elasticLoadBalancerWrapper.CreateLoadBalancerAndListener(_elasticLoadBalancerWrapper.LoadBalancerName, subnetIds, targetGroup);
        await _autoScalerWrapper.AttachLoadBalancerToGroup(_autoScalerWrapper.GroupName, targetGroup.TargetGroupArn);
        Console.WriteLine("\nVerifying access to the load balancer endpoint...");
        var endPoint = await _elasticLoadBalancerWrapper.GetEndpointForLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
        var loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);

        if (!loadBalancerAccess)
        {
            Console.WriteLine("\nCouldn't connect to the load balancer, verifying that the port is open...");

            var ipString = await _httpClient.GetStringAsync("https://checkip.amazonaws.com");
            ipString = ipString.Trim();

            var defaultSecurityGroup = await _autoScalerWrapper.GetDefaultSecurityGroupForVpc(defaultVpc);
            var portIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, port, ipString);
            var sshPortIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, sshPort, ipString);

            if (!portIsOpen)
            {
                Console.WriteLine(
                    "\nFor this example to work, the default security group for your default VPC must\n"
                    + "allows access from this computer. You can either add it automatically from this\n"
                    + "example or add it yourself using the AWS Management Console.\n");

                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound traffic from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, port, ipString);
                }
            }

            if (!sshPortIsOpen)
            {
                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound SSH traffic for debugging from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, sshPort, ipString);
                }
            }
            loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);
        }

        if (loadBalancerAccess)
        {
            Console.WriteLine("Your load balancer is ready. You can access it by browsing to:");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        else
        {
            Console.WriteLine(
                "\nCouldn't get a successful response from the load balancer endpoint. Troubleshoot by\n"
                + "manually verifying that your VPC and security group are configured correctly and that\n"
                + "you can successfully make a GET request to the load balancer endpoint:\n");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue with the demo.");
        if (interactive)
            Console.ReadLine();
        return true;
    }

    /// <summary>
    /// Demonstrate the steps of the scenario.
    /// </summary>
    /// <param name="interactive">True to run as an interactive scenario.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> Demo(bool interactive)
    {
        var ssmOnlyPolicy = Path.Join(_configuration["resourcePath"],
            "ssm_only_policy.json");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Resetting parameters to starting values for demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine("\nThis part of the demonstration shows how to toggle different parts of the system\n" +
                          "to create situations where the web service fails, and shows how using a resilient\n" +
                          "architecture can keep the web service running in spite of these failures.");
        Console.WriteLine(new string('-', 88));
        Console.WriteLine("At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine($"The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.\n" +
                          $"The table name is contained in a Systems Manager parameter named '{_smParameterWrapper.TableParameter}'.\n" +
                          $"To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");
        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as\n" +
                          "healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Instead of failing when the recommendation service fails, the web service can return a static response.");
        Console.WriteLine("While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.FailureResponseParameter, "static");

        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a static response.");
        Console.WriteLine("The service still reports as healthy because health checks are still shallow.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Let's reinstate the recommendation service.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, _smParameterWrapper.TableName);
        Console.WriteLine(
            "\nLet's also substitute bad credentials for one of the instances in the target group so that it can't\n" +
            "access the DynamoDB recommendation table.\n"
        );
        await _autoScalerWrapper.CreateInstanceProfileWithName(
            _autoScalerWrapper.BadCredsPolicyName,
            _autoScalerWrapper.BadCredsRoleName,
            _autoScalerWrapper.BadCredsProfileName,
            ssmOnlyPolicy,
            new List<string> { "AmazonSSMManagedInstanceCore" }
        );
        var instances = await _autoScalerWrapper.GetInstancesByGroupName(_autoScalerWrapper.GroupName);
        var badInstanceId = instances.First();
        var instanceProfile = await _autoScalerWrapper.GetInstanceProfile(badInstanceId);
        Console.WriteLine(
            $"Replacing the profile for instance {badInstanceId} with a profile that contains\n" +
            "bad credentials...\n"
        );
        await _autoScalerWrapper.ReplaceInstanceProfile(
            badInstanceId,
            _autoScalerWrapper.BadCredsProfileName,
            instanceProfile.AssociationId
        );
        Console.WriteLine(
            "Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,\n" +
            "depending on which instance is selected by the load balancer.\n"
        );
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nLet's implement a deep health check. For this demo, a deep health check tests whether");
        Console.WriteLine("the web service can access the DynamoDB table that it depends on for recommendations. Note that");
        Console.WriteLine("the deep health check is only for ELB routing and not for Auto Scaling instance health.");
        Console.WriteLine("This kind of deep health check is not recommended for Auto Scaling instance health, because it");
        Console.WriteLine("risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.");

        Console.WriteLine("\nBy implementing deep health checks, the load balancer can detect when one of the instances is failing");
        Console.WriteLine("and take that instance out of rotation.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.HealthCheckParameter, "deep");

        Console.WriteLine($"\nNow, checking target health indicates that the instance with bad credentials ({badInstanceId})");
        Console.WriteLine("is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy");
        Console.WriteLine("instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because");
        Console.WriteLine("the load balancer takes unhealthy instances out of its rotation.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nBecause the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy");
        Console.WriteLine("instance is to terminate it and let the auto scaler start a new instance to replace it.");

        await _autoScalerWrapper.TryTerminateInstanceById(badInstanceId);

        Console.WriteLine($"\nEven while the instance is terminating and the new instance is starting, sending a GET");
        Console.WriteLine("request to the web service continues to get a successful recommendation response because");
        Console.WriteLine("starts and reports as healthy, it is included in the load balancing rotation.");
        Console.WriteLine("Note that terminating and replacing an instance typically takes several minutes, during which time you");
        Console.WriteLine("can see the changing health check status until the new instance is running and healthy.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nIf the recommendation service fails now, deep health checks mean all instances report as unhealthy.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");

        Console.WriteLine($"\nWhen all instances are unhealthy, the load balancer continues to route requests even to");
        Console.WriteLine("unhealthy instances, allowing them to fail open and return a static response rather than fail");
        Console.WriteLine("closed and report failure to the customer.");

        if (interactive)
            await DemoActionChoices();
        await _smParameterWrapper.Reset();

        Console.WriteLine(new string('-', 80));
        return true;
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="interactive">True to ask the user for cleanup.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> DestroyResources(bool interactive)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine(
            "To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources\n" +
            "that were created for this demo."
        );

        if (!interactive || GetYesNoResponse("Do you want to clean up all demo resources? (y/n) "))
        {
            await _elasticLoadBalancerWrapper.DeleteLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
            await _elasticLoadBalancerWrapper.DeleteTargetGroupByName(_elasticLoadBalancerWrapper.TargetGroupName);
            await _autoScalerWrapper.TerminateAndDeleteAutoScalingGroupWithName(_autoScalerWrapper.GroupName);
            await _autoScalerWrapper.DeleteKeyPairByName(_autoScalerWrapper.KeyPairName);
            await _autoScalerWrapper.DeleteTemplateByName(_autoScalerWrapper.LaunchTemplateName);
            await _autoScalerWrapper.DeleteInstanceProfile(
                _autoScalerWrapper.BadCredsProfileName,
                _autoScalerWrapper.BadCredsRoleName
            );
            await _recommendations.DestroyDatabaseByName(_recommendations.TableName);
        }
        else
        {
            Console.WriteLine(
                "Ok, we'll leave the resources intact.\n" +
                "Don't forget to delete them when you're done with them or you might incur unexpected charges."
            );
        }

        Console.WriteLine(new string('-', 80));
        return true;
    }
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Amazon EC2 Auto Scaling and EC2 management methods.
/// </summary>
public class AutoScalerWrapper
{
    private readonly IAmazonAutoScaling _amazonAutoScaling;
    private readonly IAmazonEC2 _amazonEc2;
    private readonly IAmazonSimpleSystemsManagement _amazonSsm;
    private readonly IAmazonIdentityManagementService _amazonIam;
    private readonly ILogger<AutoScalerWrapper> _logger;

    private readonly string _instanceType = "";
    private readonly string _amiParam = "";
    private readonly string _launchTemplateName = "";
    private readonly string _groupName = "";
    private readonly string _instancePolicyName = "";
    private readonly string _instanceRoleName = "";
    private readonly string _instanceProfileName = "";
    private readonly string _badCredsProfileName = "";
    private readonly string _badCredsRoleName = "";
    private readonly string _badCredsPolicyName = "";
    private readonly string _keyPairName = "";

    public string GroupName => _groupName;
    public string KeyPairName => _keyPairName;
    public string LaunchTemplateName => _launchTemplateName;
    public string InstancePolicyName => _instancePolicyName;
    public string BadCredsProfileName => _badCredsProfileName;
    public string BadCredsRoleName => _badCredsRoleName;
    public string BadCredsPolicyName => _badCredsPolicyName;

    /// <summary>
    /// Constructor for the AutoScalerWrapper.
    /// </summary>
    /// <param name="amazonAutoScaling">The injected AutoScaling client.</param>
    /// <param name="amazonEc2">The injected EC2 client.</param>
    /// <param name="amazonIam">The injected IAM client.</param>
    /// <param name="amazonSsm">The injected SSM client.</param>
    public AutoScalerWrapper(
        IAmazonAutoScaling amazonAutoScaling,
        IAmazonEC2 amazonEc2,
        IAmazonSimpleSystemsManagement amazonSsm,
        IAmazonIdentityManagementService amazonIam,
        IConfiguration configuration,
        ILogger<AutoScalerWrapper> logger)
    {
        _amazonAutoScaling = amazonAutoScaling;
        _amazonEc2 = amazonEc2;
        _amazonSsm = amazonSsm;
        _amazonIam = amazonIam;
        _logger = logger;

        var prefix = configuration["resourcePrefix"];
        _instanceType = configuration["instanceType"];
        _amiParam = configuration["amiParam"];

        _launchTemplateName = prefix + "-template";
        _groupName = prefix + "-group";
        _instancePolicyName = prefix + "-pol";
        _instanceRoleName = prefix + "-role";
        _instanceProfileName = prefix + "-prof";
        _badCredsPolicyName = prefix + "-bc-pol";
        _badCredsRoleName = prefix + "-bc-role";
        _badCredsProfileName = prefix + "-bc-prof";
        _keyPairName = prefix + "-key-pair";
    }

    /// <summary>
    /// Create a policy, role, and profile that is associated with instances with a specified name.
    /// An instance's associated profile defines a role that is assumed by the
    /// instance.The role has attached policies that specify the AWS permissions granted to
    /// clients that run on the instance.
    /// </summary>
    /// <param name="policyName">Name to use for the policy.</param>
    /// <param name="roleName">Name to use for the role.</param>
    /// <param name="profileName">Name to use for the profile.</param>
    /// <param name="ssmOnlyPolicyFile">Path to a policy file for SSM.</param>
    /// <param name="awsManagedPolicies">AWS Managed policies to be attached to the role.</param>
    /// <returns>The Arn of the profile.</returns>
    public async Task<string> CreateInstanceProfileWithName(
        string policyName,
        string roleName,
        string profileName,
        string ssmOnlyPolicyFile,
        List<string>? awsManagedPolicies = null)
    {

        var assumeRoleDoc = "{" +
                                   "\"Version\": \"2012-10-17\"," +
                                   "\"Statement\": [{" +
                                        "\"Effect\": \"Allow\"," +
                                        "\"Principal\": {" +
                                        "\"Service\": [" +
                                            "\"ec2.amazonaws.com\"" +
                                        "]" +
                                        "}," +
                                   "\"Action\": \"sts:AssumeRole\"" +
                                   "}]" +
                               "}";

        var policyDocument = await File.ReadAllTextAsync(ssmOnlyPolicyFile);

        var policyArn = "";

        try
        {
            var createPolicyResult = await _amazonIam.CreatePolicyAsync(
                new CreatePolicyRequest
                {
                    PolicyName = policyName,
                    PolicyDocument = policyDocument
                });
            policyArn = createPolicyResult.Policy.Arn;
        }
        catch (EntityAlreadyExistsException)
        {
            // The policy already exists, so we look it up to get the Arn.
            var policiesPaginator = _amazonIam.Paginators.ListPolicies(
                new ListPoliciesRequest()
                {
                    Scope = PolicyScopeType.Local
                });
            // Get the entire list using the paginator.
            await foreach (var policy in policiesPaginator.Policies)
            {
                if (policy.PolicyName.Equals(policyName))
                {
                    policyArn = policy.Arn;
                }
            }

            if (policyArn == null)
            {
                throw new InvalidOperationException("Policy not found");
            }
        }

        try
        {
            await _amazonIam.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = assumeRoleDoc,
            });
            await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
            {
                RoleName = roleName,
                PolicyArn = policyArn
            });
            if (awsManagedPolicies != null)
            {
                foreach (var awsPolicy in awsManagedPolicies)
                {
                    await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
                    {
                        PolicyArn = $"arn:aws:iam::aws:policy/{awsPolicy}",
                        RoleName = roleName
                    });
                }
            }
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Role already exists.");
        }

        string profileArn = "";
        try
        {
            var profileCreateResponse = await _amazonIam.CreateInstanceProfileAsync(
                new CreateInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            // Allow time for the profile to be ready.
            profileArn = profileCreateResponse.InstanceProfile.Arn;
            Thread.Sleep(10000);
            await _amazonIam.AddRoleToInstanceProfileAsync(
                new AddRoleToInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });

        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Policy already exists.");
            var profileGetResponse = await _amazonIam.GetInstanceProfileAsync(
                new GetInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            profileArn = profileGetResponse.InstanceProfile.Arn;
        }
        return profileArn;
    }

    /// <summary>
    /// Create a new key pair and save the file.
    /// </summary>
    /// <param name="newKeyPairName">The name of the new key pair.</param>
    /// <returns>Async task.</returns>
    public async Task CreateKeyPair(string newKeyPairName)
    {
        try
        {
            var keyResponse = await _amazonEc2.CreateKeyPairAsync(
                new CreateKeyPairRequest() { KeyName = newKeyPairName });
            await File.WriteAllTextAsync($"{newKeyPairName}.pem",
                keyResponse.KeyPair.KeyMaterial);
            Console.WriteLine($"Created key pair {newKeyPairName}.");
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine("Key pair already exists.");
        }
    }

    /// <summary>
    /// Delete the key pair and file by name.
    /// </summary>
    /// <param name="deleteKeyPairName">The key pair to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteKeyPairByName(string deleteKeyPairName)
    {
        try
        {
            await _amazonEc2.DeleteKeyPairAsync(
                new DeleteKeyPairRequest() { KeyName = deleteKeyPairName });
            File.Delete($"{deleteKeyPairName}.pem");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"Key pair {deleteKeyPairName} not found.");
        }
    }

    /// <summary>
    /// Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling.
    /// The launch template specifies a Bash script in its user data field that runs after
    /// the instance is started. This script installs the Python packages and starts a Python
    /// web server on the instance.
    /// </summary>
    /// <param name="startupScriptPath">The path to a Bash script file that is run.</param>
    /// <param name="instancePolicyPath">The path to a permissions policy to create and attach to the profile.</param>
    /// <returns>The template object.</returns>
    public async Task<Amazon.EC2.Model.LaunchTemplate> CreateTemplate(string startupScriptPath, string instancePolicyPath)
    {
        try
        {
            await CreateKeyPair(_keyPairName);
            await CreateInstanceProfileWithName(_instancePolicyName, _instanceRoleName,
                _instanceProfileName, instancePolicyPath);

            var startServerText = await File.ReadAllTextAsync(startupScriptPath);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(startServerText);

            var amiLatest = await _amazonSsm.GetParameterAsync(
                new GetParameterRequest() { Name = _amiParam });
            var amiId = amiLatest.Parameter.Value;
            var launchTemplateResponse = await _amazonEc2.CreateLaunchTemplateAsync(
                new CreateLaunchTemplateRequest()
                {
                    LaunchTemplateName = _launchTemplateName,
                    LaunchTemplateData = new RequestLaunchTemplateData()
                    {
                        InstanceType = _instanceType,
                        ImageId = amiId,
                        IamInstanceProfile =
                            new
                                LaunchTemplateIamInstanceProfileSpecificationRequest()
                            {
                                Name = _instanceProfileName
                            },
                        KeyName = _keyPairName,
                        UserData = System.Convert.ToBase64String(plainTextBytes)
                    }
                });
            return launchTemplateResponse.LaunchTemplate;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.AlreadyExistsException")
            {
                _logger.LogError($"Could not create the template, the name {_launchTemplateName} already exists. " +
                                 $"Please try again with a unique name.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get a list of Availability Zones in the AWS Region of the Amazon EC2 Client.
    /// </summary>
    /// <returns>A list of availability zones.</returns>
    public async Task<List<string>> DescribeAvailabilityZones()
    {
        try
        {
            var zoneResponse = await _amazonEc2.DescribeAvailabilityZonesAsync(
                new DescribeAvailabilityZonesRequest());
            return zoneResponse.AvailabilityZones.Select(z => z.ZoneName).ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            _logger.LogError($"An Amazon EC2 error occurred while listing availability zones.: {ec2Exception.Message}");
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while listing availability zones.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Create an EC2 Auto Scaling group of a specified size and name.
    /// </summary>
    /// <param name="groupSize">The size for the group.</param>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="availabilityZones">The availability zones for the group.</param>
    /// <returns>Async task.</returns>
    public async Task CreateGroupOfSize(int groupSize, string groupName, List<string> availabilityZones)
    {
        try
        {
            await _amazonAutoScaling.CreateAutoScalingGroupAsync(
                new CreateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    AvailabilityZones = availabilityZones,
                    LaunchTemplate =
                        new Amazon.AutoScaling.Model.LaunchTemplateSpecification()
                        {
                            LaunchTemplateName = _launchTemplateName,
                            Version = "$Default"
                        },
                    MaxSize = groupSize,
                    MinSize = groupSize
                });
            Console.WriteLine($"Created EC2 Auto Scaling group {groupName} with size {groupSize}.");
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine($"EC2 Auto Scaling group {groupName} already exists.");
        }
    }

    /// <summary>
    /// Get the default VPC for the account.
    /// </summary>
    /// <returns>The default VPC object.</returns>
    public async Task<Vpc> GetDefaultVpc()
    {
        try
        {
            var vpcResponse = await _amazonEc2.DescribeVpcsAsync(
                new DescribeVpcsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("is-default", new List<string>() { "true" })
                    }
                });
            return vpcResponse.Vpcs[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "UnauthorizedOperation")
            {
                _logger.LogError(ec2Exception, $"You do not have the necessary permissions to describe VPCs.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the vpcs.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get all the subnets for a Vpc in a set of availability zones.
    /// </summary>
    /// <param name="vpcId">The Id of the Vpc.</param>
    /// <param name="availabilityZones">The list of availability zones.</param>
    /// <returns>The collection of subnet objects.</returns>
    public async Task<List<Subnet>> GetAllVpcSubnetsForZones(string vpcId, List<string> availabilityZones)
    {
        try
        {
            var subnets = new List<Subnet>();
            var subnetPaginator = _amazonEc2.Paginators.DescribeSubnets(
                new DescribeSubnetsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("vpc-id", new List<string>() { vpcId }),
                        new("availability-zone", availabilityZones),
                        new("default-for-az", new List<string>() { "true" })
                    }
                });

            // Get the entire list using the paginator.
            await foreach (var subnet in subnetPaginator.Subnets)
            {
                subnets.Add(subnet);
            }

            return subnets;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidVpcID.NotFound")
            {
                _logger.LogError(ec2Exception, $"The specified VPC ID {vpcId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the subnets.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Delete a launch template by name.
    /// </summary>
    /// <param name="templateName">The name of the template to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTemplateByName(string templateName)
    {
        try
        {
            await _amazonEc2.DeleteLaunchTemplateAsync(
                new DeleteLaunchTemplateRequest()
                {
                    LaunchTemplateName = templateName
                });
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.NotFoundException")
            {
                _logger.LogError(
                    $"Could not delete the template, the name {_launchTemplateName} was not found.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while deleting the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Detaches a role from an instance profile, detaches policies from the role,
    /// and deletes all the resources.
    /// </summary>
    /// <param name="profileName">The name of the profile to delete.</param>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteInstanceProfile(string profileName, string roleName)
    {
        try
        {
            await _amazonIam.RemoveRoleFromInstanceProfileAsync(
                new RemoveRoleFromInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });
            await _amazonIam.DeleteInstanceProfileAsync(
                new DeleteInstanceProfileRequest() { InstanceProfileName = profileName });
            var attachedPolicies = await _amazonIam.ListAttachedRolePoliciesAsync(
                new ListAttachedRolePoliciesRequest() { RoleName = roleName });
            foreach (var policy in attachedPolicies.AttachedPolicies)
            {
                await _amazonIam.DetachRolePolicyAsync(
                    new DetachRolePolicyRequest()
                    {
                        RoleName = roleName,
                        PolicyArn = policy.PolicyArn
                    });
                // Delete the custom policies only.
                if (!policy.PolicyArn.StartsWith("arn:aws:iam::aws"))
                {
                    await _amazonIam.DeletePolicyAsync(
                        new Amazon.IdentityManagement.Model.DeletePolicyRequest()
                        {
                            PolicyArn = policy.PolicyArn
                        });
                }
            }

            await _amazonIam.DeleteRoleAsync(
                new DeleteRoleRequest() { RoleName = roleName });
        }
        catch (NoSuchEntityException)
        {
            Console.WriteLine($"Instance profile {profileName} does not exist.");
        }
    }

    /// <summary>
    /// Gets data about the instances in an EC2 Auto Scaling group by its group name.
    /// </summary>
    /// <param name="group">The name of the auto scaling group.</param>
    /// <returns>A collection of instance Ids.</returns>
    public async Task<IEnumerable<string>> GetInstancesByGroupName(string group)
    {
        var instanceResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { group }
            });
        var instanceIds = instanceResponse.AutoScalingGroups.SelectMany(
            g => g.Instances.Select(i => i.InstanceId));
        return instanceIds;
    }

    /// <summary>
    /// Get the instance profile association data for an instance.
    /// </summary>
    /// <param name="instanceId">The Id of the instance.</param>
    /// <returns>Instance profile associations data.</returns>
    public async Task<IamInstanceProfileAssociation> GetInstanceProfile(string instanceId)
    {
        try
        {
            var response = await _amazonEc2.DescribeIamInstanceProfileAssociationsAsync(
                new DescribeIamInstanceProfileAssociationsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("instance-id", new List<string>() { instanceId })
                    },
                });
            return response.IamInstanceProfileAssociations[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Try to terminate an instance by its Id.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task TryTerminateInstanceById(string instanceId)
    {
        var stopping = false;
        Console.WriteLine($"Stopping {instanceId}...");
        while (!stopping)
        {
            try
            {
                await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(
                    new TerminateInstanceInAutoScalingGroupRequest()
                    {
                        InstanceId = instanceId,
                        ShouldDecrementDesiredCapacity = false
                    });
                stopping = true;
            }
            catch (ScalingActivityInProgressException)
            {
                Console.WriteLine($"Scaling activity in progress for {instanceId}. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress,
    /// waits and retries until the group is successfully deleted.
    /// </summary>
    /// <param name="groupName">The name of the group to try to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TryDeleteGroupByName(string groupName)
    {
        var stopped = false;
        while (!stopped)
        {
            try
            {
                await _amazonAutoScaling.DeleteAutoScalingGroupAsync(
                    new DeleteAutoScalingGroupRequest()
                    {
                        AutoScalingGroupName = groupName
                    });
                stopped = true;
            }
            catch (Exception e)
                when ((e is ScalingActivityInProgressException)
                      || (e is Amazon.AutoScaling.Model.ResourceInUseException))
            {
                Console.WriteLine($"Some instances are still running. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Terminate instances and delete the Auto Scaling group by name.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TerminateAndDeleteAutoScalingGroupWithName(string groupName)
    {
        var describeGroupsResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { groupName }
            });
        if (describeGroupsResponse.AutoScalingGroups.Any())
        {
            // Update the size to 0.
            await _amazonAutoScaling.UpdateAutoScalingGroupAsync(
                new UpdateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    MinSize = 0
                });
            var group = describeGroupsResponse.AutoScalingGroups[0];
            foreach (var instance in group.Instances)
            {
                await TryTerminateInstanceById(instance.InstanceId);
            }

            await TryDeleteGroupByName(groupName);
        }
        else
        {
            Console.WriteLine($"No groups found with name {groupName}.");
        }
    }


    /// <summary>
    /// Get the default security group for a specified Vpc.
    /// </summary>
    /// <param name="vpc">The Vpc to search.</param>
    /// <returns>The default security group.</returns>
    public async Task<SecurityGroup> GetDefaultSecurityGroupForVpc(Vpc vpc)
    {
        var groupResponse = await _amazonEc2.DescribeSecurityGroupsAsync(
            new DescribeSecurityGroupsRequest()
            {
                Filters = new List<Amazon.EC2.Model.Filter>()
                {
                    new ("group-name", new List<string>() { "default" }),
                    new ("vpc-id", new List<string>() { vpc.VpcId })
                }
            });
        return groupResponse.SecurityGroups[0];
    }

    /// <summary>
    /// Verify the default security group of a Vpc allows ingress from the calling computer.
    /// This can be done by allowing ingress from this computer's IP address.
    /// In some situations, such as connecting from a corporate network, you must instead specify
    /// a prefix list Id. You can also temporarily open the port to any IP address while running this example.
    /// If you do, be sure to remove public access when you're done.
    /// </summary>
    /// <param name="vpc">The group to check.</param>
    /// <param name="port">The port to verify.</param>
    /// <param name="ipAddress">This computer's IP address.</param>
    /// <returns>True if the ip address is allowed on the group.</returns>
    public bool VerifyInboundPortForGroup(SecurityGroup group, int port, string ipAddress)
    {
        var portIsOpen = false;
        foreach (var ipPermission in group.IpPermissions)
        {
            if (ipPermission.FromPort == port)
            {
                foreach (var ipRange in ipPermission.Ipv4Ranges)
                {
                    var cidr = ipRange.CidrIp;
                    if (cidr.StartsWith(ipAddress) || cidr == "0.0.0.0/0")
                    {
                        portIsOpen = true;
                    }
                }

                if (ipPermission.PrefixListIds.Any())
                {
                    portIsOpen = true;
                }

                if (!portIsOpen)
                {
                    Console.WriteLine("The inbound rule does not appear to be open to either this computer's IP\n" +
                                      "address, to all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                }
                else
                {
                    break;
                }
            }
        }

        return portIsOpen;
    }

    /// <summary>
    /// Add an ingress rule to the specified security group that allows access on the
    /// specified port from the specified IP address.
    /// </summary>
    /// <param name="groupId">The Id of the security group to modify.</param>
    /// <param name="port">The port to open.</param>
    /// <param name="ipAddress">The IP address to allow access.</param>
    /// <returns>Async task.</returns>
    public async Task OpenInboundPort(string groupId, int port, string ipAddress)
    {
        await _amazonEc2.AuthorizeSecurityGroupIngressAsync(
            new AuthorizeSecurityGroupIngressRequest()
            {
                GroupId = groupId,
                IpPermissions = new List<IpPermission>()
                {
                    new IpPermission()
                    {
                        FromPort = port,
                        ToPort = port,
                        IpProtocol = "tcp",
                        Ipv4Ranges = new List<IpRange>()
                        {
                            new IpRange() { CidrIp = $"{ipAddress}/32" }
                        }
                    }
                }
            });
    }

    /// <summary>
    /// Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
    /// The
    /// </summary>
    /// <param name="autoScalingGroupName">The name of the Auto Scaling group.</param>
    /// <param name="targetGroupArn">The Arn for the target group.</param>
    /// <returns>Async task.</returns>
    public async Task AttachLoadBalancerToGroup(string autoScalingGroupName, string targetGroupArn)
    {
        await _amazonAutoScaling.AttachLoadBalancerTargetGroupsAsync(
            new AttachLoadBalancerTargetGroupsRequest()
            {
                AutoScalingGroupName = autoScalingGroupName,
                TargetGroupARNs = new List<string>() { targetGroupArn }
            });
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEc2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Elastic Load Balancer actions.
/// </summary>
public class ElasticLoadBalancerWrapper
{
    private readonly IAmazonElasticLoadBalancingV2 _amazonElasticLoadBalancingV2;
    private string? _endpoint = null;
    private readonly string _targetGroupName = "";
    private readonly string _loadBalancerName = "";
    HttpClient _httpClient = new();

    public string TargetGroupName => _targetGroupName;
    public string LoadBalancerName => _loadBalancerName;

    /// <summary>
    /// Constructor for the Elastic Load Balancer wrapper.
    /// </summary>
    /// <param name="amazonElasticLoadBalancingV2">The injected load balancing v2 client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public ElasticLoadBalancerWrapper(
        IAmazonElasticLoadBalancingV2 amazonElasticLoadBalancingV2,
        IConfiguration configuration)
    {
        _amazonElasticLoadBalancingV2 = amazonElasticLoadBalancingV2;
        var prefix = configuration["resourcePrefix"];
        _targetGroupName = prefix + "-tg";
        _loadBalancerName = prefix + "-lb";
    }

    /// <summary>
    /// Get the HTTP Endpoint of a load balancer by its name.
    /// </summary>
    /// <param name="loadBalancerName">The name of the load balancer.</param>
    /// <returns>The HTTP endpoint.</returns>
    public async Task<string> GetEndpointForLoadBalancerByName(string loadBalancerName)
    {
        if (_endpoint == null)
        {
            var endpointResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { loadBalancerName }
                    });
            _endpoint = endpointResponse.LoadBalancers[0].DNSName;
        }

        return _endpoint;
    }

    /// <summary>
    /// Return the GET response for an endpoint as text.
    /// </summary>
    /// <param name="endpoint">The endpoint for the request.</param>
    /// <returns>The request response.</returns>
    public async Task<string> GetEndPointResponse(string endpoint)
    {
        var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
        var textResponse = await endpointResponse.Content.ReadAsStringAsync();
        return textResponse!;
    }

    /// <summary>
    /// Get the target health for a group by name.
    /// </summary>
    /// <param name="groupName">The name of the group.</param>
    /// <returns>The collection of health descriptions.</returns>
    public async Task<List<TargetHealthDescription>> CheckTargetHealthForGroup(string groupName)
    {
        List<TargetHealthDescription> result = null!;
        try
        {
            var groupResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                    new DescribeTargetGroupsRequest()
                    {
                        Names = new List<string>() { groupName }
                    });
            var healthResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetHealthAsync(
                    new DescribeTargetHealthRequest()
                    {
                        TargetGroupArn = groupResponse.TargetGroups[0].TargetGroupArn
                    });
            ;
            result = healthResponse.TargetHealthDescriptions;
        }
        catch (TargetGroupNotFoundException)
        {
            Console.WriteLine($"Target group {groupName} not found.");
        }
        return result;
    }

    /// <summary>
    /// Create an Elastic Load Balancing target group. The target group specifies how the load balancer forwards
    /// requests to instances in the group and how instance health is checked.
    ///
    /// To speed up this demo, the health check is configured with shortened times and lower thresholds. In production,
    /// you might want to decrease the sensitivity of your health checks to avoid unwanted failures.
    /// </summary>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="protocol">The protocol, such as HTTP.</param>
    /// <param name="port">The port to use to forward requests, such as 80.</param>
    /// <param name="vpcId">The Id of the Vpc in which the load balancer exists.</param>
    /// <returns>The new TargetGroup object.</returns>
    public async Task<TargetGroup> CreateTargetGroupOnVpc(string groupName, ProtocolEnum protocol, int port, string vpcId)
    {
        var createResponse = await _amazonElasticLoadBalancingV2.CreateTargetGroupAsync(
            new CreateTargetGroupRequest()
            {
                Name = groupName,
                Protocol = protocol,
                Port = port,
                HealthCheckPath = "/healthcheck",
                HealthCheckIntervalSeconds = 10,
                HealthCheckTimeoutSeconds = 5,
                HealthyThresholdCount = 2,
                UnhealthyThresholdCount = 2,
                VpcId = vpcId
            });
        var targetGroup = createResponse.TargetGroups[0];
        return targetGroup;
    }

    /// <summary>
    /// Create an Elastic Load Balancing load balancer that uses the specified subnets
    /// and forwards requests to the specified target group.
    /// </summary>
    /// <param name="name">The name for the new load balancer.</param>
    /// <param name="subnetIds">Subnets for the load balancer.</param>
    /// <param name="targetGroup">Target group for forwarded requests.</param>
    /// <returns>The new LoadBalancer object.</returns>
    public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup)
    {
        var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync(
            new CreateLoadBalancerRequest()
            {
                Name = name,
                Subnets = subnetIds
            });
        var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn;

        // Wait for load balancer to be available.
        var loadBalancerReady = false;
        while (!loadBalancerReady)
        {
            try
            {
                var describeResponse =
                    await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                        new DescribeLoadBalancersRequest()
                        {
                            Names = new List<string>() { name }
                        });

                var loadBalancerState = describeResponse.LoadBalancers[0].State.Code;

                loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active;
            }
            catch (LoadBalancerNotFoundException)
            {
                loadBalancerReady = false;
            }
            Thread.Sleep(10000);
        }
        // Create the listener.
        await _amazonElasticLoadBalancingV2.CreateListenerAsync(
            new CreateListenerRequest()
            {
                LoadBalancerArn = loadBalancerArn,
                Protocol = targetGroup.Protocol,
                Port = targetGroup.Port,
                DefaultActions = new List<Action>()
                {
                    new Action()
                    {
                        Type = ActionTypeEnum.Forward,
                        TargetGroupArn = targetGroup.TargetGroupArn
                    }
                }
            });
        return createLbResponse.LoadBalancers[0];
    }

    /// <summary>
    /// Verify this computer can successfully send a GET request to the
    /// load balancer endpoint.
    /// </summary>
    /// <param name="endpoint">The endpoint to check.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> VerifyLoadBalancerEndpoint(string endpoint)
    {
        var success = false;
        var retries = 3;
        while (!success && retries > 0)
        {
            try
            {
                var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
                Console.WriteLine($"Response: {endpointResponse.StatusCode}.");

                if (endpointResponse.IsSuccessStatusCode)
                {
                    success = true;
                }
                else
                {
                    retries = 0;
                }
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Connection error, retrying...");
                retries--;
                Thread.Sleep(10000);
            }
        }

        return success;
    }

    /// <summary>
    /// Delete a load balancer by its specified name.
    /// </summary>
    /// <param name="name">The name of the load balancer to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteLoadBalancerByName(string name)
    {
        try
        {
            var describeLoadBalancerResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { name }
                    });
            var lbArn = describeLoadBalancerResponse.LoadBalancers[0].LoadBalancerArn;
            await _amazonElasticLoadBalancingV2.DeleteLoadBalancerAsync(
                new DeleteLoadBalancerRequest()
                {
                    LoadBalancerArn = lbArn
                }
            );
        }
        catch (LoadBalancerNotFoundException)
        {
            Console.WriteLine($"Load balancer {name} not found.");
        }
    }

    /// <summary>
    /// Delete a TargetGroup by its specified name.
    /// </summary>
    /// <param name="groupName">Name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTargetGroupByName(string groupName)
    {
        var done = false;
        while (!done)
        {
            try
            {
                var groupResponse =
                    await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                        new DescribeTargetGroupsRequest()
                        {
                            Names = new List<string>() { groupName }
                        });

                var targetArn = groupResponse.TargetGroups[0].TargetGroupArn;
                await _amazonElasticLoadBalancingV2.DeleteTargetGroupAsync(
                    new DeleteTargetGroupRequest() { TargetGroupArn = targetArn });
                Console.WriteLine($"Deleted load balancing target group {groupName}.");
                done = true;
            }
            catch (TargetGroupNotFoundException)
            {
                Console.WriteLine(
                    $"Target group {groupName} not found, could not delete.");
                done = true;
            }
            catch (ResourceInUseException)
            {
                Console.WriteLine("Target group not yet released, waiting...");
                Thread.Sleep(10000);
            }
        }
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
/// <summary>
/// Encapsulates a DynamoDB table to use as a service that recommends books, movies, and songs.
/// </summary>
public class Recommendations
{
    private readonly IAmazonDynamoDB _amazonDynamoDb;
    private readonly DynamoDBContext _context;
    private readonly string _tableName;

    public string TableName => _tableName;

    /// <summary>
    /// Constructor for the Recommendations service.
    /// </summary>
    /// <param name="amazonDynamoDb">The injected DynamoDb client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public Recommendations(IAmazonDynamoDB amazonDynamoDb, IConfiguration configuration)
    {
        _amazonDynamoDb = amazonDynamoDb;
        _context = new DynamoDBContext(_amazonDynamoDb);
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Create the DynamoDb table with a specified name.
    /// </summary>
    /// <param name="tableName">The name for the table.</param>
    /// <returns>True when ready.</returns>
    public async Task<bool> CreateDatabaseWithName(string tableName)
    {
        try
        {
            Console.Write($"Creating table {tableName}...");
            var createRequest = new CreateTableRequest()
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                    {
                        new AttributeDefinition()
                        {
                            AttributeName = "MediaType",
                            AttributeType = ScalarAttributeType.S
                        },
                        new AttributeDefinition()
                        {
                            AttributeName = "ItemId",
                            AttributeType = ScalarAttributeType.N
                        }
                    },
                KeySchema = new List<KeySchemaElement>()
                    {
                        new KeySchemaElement()
                        {
                            AttributeName = "MediaType",
                            KeyType = KeyType.HASH
                        },
                        new KeySchemaElement()
                        {
                            AttributeName = "ItemId",
                            KeyType = KeyType.RANGE
                        }
                    },
                ProvisionedThroughput = new ProvisionedThroughput()
                {
                    ReadCapacityUnits = 5,
                    WriteCapacityUnits = 5
                }
            };
            await _amazonDynamoDb.CreateTableAsync(createRequest);

            // Wait until the table is ACTIVE and then report success.
            Console.Write("\nWaiting for table to become active...");

            var request = new DescribeTableRequest
            {
                TableName = tableName
            };

            TableStatus status;
            do
            {
                Thread.Sleep(2000);

                var describeTableResponse = await _amazonDynamoDb.DescribeTableAsync(request);
                status = describeTableResponse.Table.TableStatus;

                Console.Write(".");
            }
            while (status != "ACTIVE");

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException)
        {
            Console.WriteLine($"Table {tableName} already exists.");
            return false;
        }
    }

    /// <summary>
    /// Populate the database table with data from a specified path.
    /// </summary>
    /// <param name="databaseTableName">The name of the table.</param>
    /// <param name="recommendationsPath">The path of the recommendations data.</param>
    /// <returns>Async task.</returns>
    public async Task PopulateDatabase(string databaseTableName, string recommendationsPath)
    {
        var recommendationsText = await File.ReadAllTextAsync(recommendationsPath);
        var records =
            JsonSerializer.Deserialize<RecommendationModel[]>(recommendationsText);
        var batchWrite = _context.CreateBatchWrite<RecommendationModel>();

        foreach (var record in records!)
        {
            batchWrite.AddPutItem(record);
        }

        await batchWrite.ExecuteAsync();
    }

    /// <summary>
    /// Delete the recommendation table by name.
    /// </summary>
    /// <param name="tableName">The name of the recommendation table.</param>
    /// <returns>Async task.</returns>
    public async Task DestroyDatabaseByName(string tableName)
    {
        try
        {
            await _amazonDynamoDb.DeleteTableAsync(
                new DeleteTableRequest() { TableName = tableName });
            Console.WriteLine($"Table {tableName} was deleted.");
        }
        catch (ResourceNotFoundException)
        {
            Console.WriteLine($"Table {tableName} not found");
        }
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Systems Manager parameter operations. This example uses these parameters
/// to drive the demonstration of resilient architecture, such as failure of a dependency or
/// how the service responds to a health check.
/// </summary>
public class SmParameterWrapper
{
    private readonly IAmazonSimpleSystemsManagement _amazonSimpleSystemsManagement;

    private readonly string _tableParameter = "doc-example-resilient-architecture-table";
    private readonly string _failureResponseParameter = "doc-example-resilient-architecture-failure-response";
    private readonly string _healthCheckParameter = "doc-example-resilient-architecture-health-check";
    private readonly string _tableName = "";

    public string TableParameter => _tableParameter;
    public string TableName => _tableName;
    public string HealthCheckParameter => _healthCheckParameter;
    public string FailureResponseParameter => _failureResponseParameter;

    /// <summary>
    /// Constructor for the SmParameterWrapper.
    /// </summary>
    /// <param name="amazonSimpleSystemsManagement">The injected Simple Systems Management client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public SmParameterWrapper(IAmazonSimpleSystemsManagement amazonSimpleSystemsManagement, IConfiguration configuration)
    {
        _amazonSimpleSystemsManagement = amazonSimpleSystemsManagement;
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Reset the Systems Manager parameters to starting values for the demo.
    /// </summary>
    /// <returns>Async task.</returns>
    public async Task Reset()
    {
        await this.PutParameterByName(_tableParameter, _tableName);
        await this.PutParameterByName(_failureResponseParameter, "none");
        await this.PutParameterByName(_healthCheckParameter, "shallow");
    }

    /// <summary>
    /// Set the value of a named Systems Manager parameter.
    /// </summary>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="value">The value to set.</param>
    /// <returns>Async task.</returns>
    public async Task PutParameterByName(string name, string value)
    {
        await _amazonSimpleSystemsManagement.PutParameterAsync(
            new PutParameterRequest() { Name = name, Value = value, Overwrite = true });
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# を使用した EventBridge の例 SDK for .NET
<a name="csharp_3_eventbridge_code_examples"></a>

次のコード例は、EventBridge AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello EventBridge
<a name="eventbridge_Hello_csharp_3_topic"></a>

次のコード例は、EventBridge の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.EventBridge;
using Amazon.EventBridge.Model;

namespace EventBridgeActions;

public static class HelloEventBridge
{
    static async Task Main(string[] args)
    {
        var eventBridgeClient = new AmazonEventBridgeClient();

        Console.WriteLine($"Hello Amazon EventBridge! Following are some of your EventBuses:");
        Console.WriteLine();

        // You can use await and any of the async methods to get a response.
        // Let's get the first five event buses.
        var response = await eventBridgeClient.ListEventBusesAsync(
            new ListEventBusesRequest()
            {
                Limit = 5
            });

        foreach (var eventBus in response.EventBuses)
        {
            Console.WriteLine($"\tEventBus: {eventBus.Name}");
            Console.WriteLine($"\tArn: {eventBus.Arn}");
            Console.WriteLine($"\tPolicy: {eventBus.Policy}");
            Console.WriteLine();
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListEventBuses](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/ListEventBuses)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="eventbridge_Scenario_GettingStarted_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ルールを作成して、ターゲットを追加する。
+ ルールを有効化および無効化する。
+ ルールとターゲットを一覧表示して更新する。
+ イベントを送信して、リソースをクリーンアップする。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
サーバーレスサンプルリポジトリで完全な例を見つけて、設定と実行の方法を確認してください。  

```
public class EventBridgeScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This .NET example performs the following tasks with Amazon EventBridge:
    - Create a rule.
    - Add a target to a rule.
    - Enable and disable rules.
    - List rules and targets.
    - Update rules and targets.
    - Send events.
    - Delete the rule.
    */

    private static ILogger logger = null!;
    private static EventBridgeWrapper _eventBridgeWrapper = null!;
    private static IConfiguration _configuration = null!;

    private static IAmazonIdentityManagementService? _iamClient = null!;
    private static IAmazonSimpleNotificationService? _snsClient = null!;
    private static IAmazonS3 _s3Client = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon EventBridge.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonEventBridge>()
            .AddAWSService<IAmazonIdentityManagementService>()
            .AddAWSService<IAmazonS3>()
            .AddAWSService<IAmazonSimpleNotificationService>()
            .AddTransient<EventBridgeWrapper>()
            )
            .Build();

        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<EventBridgeScenario>();

        ServicesSetup(host);

        string topicArn = "";
        string roleArn = "";

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the Amazon EventBridge example scenario.");
        Console.WriteLine(new string('-', 80));

        try
        {
            roleArn = await CreateRole();

            await CreateBucketWithEventBridgeEvents();

            await AddEventRule(roleArn);

            await ListEventRules();

            topicArn = await CreateSnsTopic();

            var email = await SubscribeToSnsTopic(topicArn);

            await AddSnsTarget(topicArn);

            await ListTargets();

            await ListRulesForTarget(topicArn);

            await UploadS3File(_s3Client);

            await ChangeRuleState(false);

            await GetRuleState();

            await UpdateSnsEventRule(topicArn);

            await ChangeRuleState(true);

            await UploadS3File(_s3Client);

            await UpdateToCustomRule(topicArn);

            await TriggerCustomRule(email);

            await CleanupResources(topicArn);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "There was a problem executing the scenario.");
            await CleanupResources(topicArn);
        }
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("The Amazon EventBridge example scenario is complete.");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _eventBridgeWrapper = host.Services.GetRequiredService<EventBridgeWrapper>();
        _snsClient = host.Services.GetRequiredService<IAmazonSimpleNotificationService>();
        _s3Client = host.Services.GetRequiredService<IAmazonS3>();
        _iamClient = host.Services.GetRequiredService<IAmazonIdentityManagementService>();
    }

    /// <summary>
    /// Create a role to be used by EventBridge.
    /// </summary>
    /// <returns>The role Amazon Resource Name (ARN).</returns>
    public static async Task<string> CreateRole()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Creating a role to use with EventBridge and attaching managed policy AmazonEventBridgeFullAccess.");
        Console.WriteLine(new string('-', 80));

        var roleName = _configuration["roleName"];

        var assumeRolePolicy = "{" +
                                  "\"Version\": \"2012-10-17\"," +
                                  "\"Statement\": [{" +
                                  "\"Effect\": \"Allow\"," +
                                  "\"Principal\": {" +
                                  $"\"Service\": \"events.amazonaws.com\"" +
                                  "}," +
                                  "\"Action\": \"sts:AssumeRole\"" +
                                  "}]" +
                                  "}";

        var roleResult = await _iamClient!.CreateRoleAsync(
            new CreateRoleRequest()
            {
                AssumeRolePolicyDocument = assumeRolePolicy,
                Path = "/",
                RoleName = roleName
            });

        await _iamClient.AttachRolePolicyAsync(
            new AttachRolePolicyRequest()
            {
                PolicyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess",
                RoleName = roleName
            });
        // Allow time for the role to be ready.
        Thread.Sleep(10000);
        return roleResult.Role.Arn;
    }

    /// <summary>
    /// Create an Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events enabled.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CreateBucketWithEventBridgeEvents()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Creating an S3 bucket with EventBridge events enabled.");

        var testBucketName = _configuration["testBucketName"];

        var bucketExists = await Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async(_s3Client,
            testBucketName);

        if (!bucketExists)
        {
            await _s3Client.PutBucketAsync(new PutBucketRequest()
            {
                BucketName = testBucketName,
                UseClientRegion = true
            });
        }

        await _s3Client.PutBucketNotificationAsync(new PutBucketNotificationRequest()
        {
            BucketName = testBucketName,
            EventBridgeConfiguration = new EventBridgeConfiguration()
        });

        Console.WriteLine($"\tAdded bucket {testBucketName} with EventBridge events enabled.");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Create and upload a file to an S3 bucket to trigger an event.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task UploadS3File(IAmazonS3 s3Client)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Uploading a file to the test bucket. This will trigger a subscription email.");

        var testBucketName = _configuration["testBucketName"];

        var fileName = $"example_upload_{DateTime.UtcNow.Ticks}.txt";

        // Create the file if it does not already exist.
        if (!File.Exists(fileName))
        {
            await using StreamWriter sw = File.CreateText(fileName);
            await sw.WriteLineAsync(
                "This is a sample file for testing uploads.");
        }

        await s3Client.PutObjectAsync(new PutObjectRequest()
        {
            FilePath = fileName,
            BucketName = testBucketName
        });

        Console.WriteLine($"\tPress Enter to continue.");
        Console.ReadLine();

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Create an Amazon Simple Notification Service (Amazon SNS) topic to use as an EventBridge target.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task<string> CreateSnsTopic()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine(
            "Creating an Amazon Simple Notification Service (Amazon SNS) topic for email subscriptions.");

        var topicName = _configuration["topicName"];

        string topicPolicy = "{" +
                             "\"Version\": \"2012-10-17\"," +
                             "\"Statement\": [{" +
                             "\"Sid\": \"EventBridgePublishTopic\"," +
                             "\"Effect\": \"Allow\"," +
                             "\"Principal\": {" +
                             $"\"Service\": \"events.amazonaws.com\"" +
                             "}," +
                             "\"Resource\": \"*\"," +
                             "\"Action\": \"sns:Publish\"" +
                             "}]" +
                             "}";

        var topicAttributes = new Dictionary<string, string>()
        {
            { "Policy", topicPolicy }
        };

        var topicResponse = await _snsClient!.CreateTopicAsync(new CreateTopicRequest()
        {
            Name = topicName,
            Attributes = topicAttributes

        });

        Console.WriteLine($"\tAdded topic {topicName} for email subscriptions.");

        Console.WriteLine(new string('-', 80));

        return topicResponse.TopicArn;
    }

    /// <summary>
    /// Subscribe a user email to an SNS topic.
    /// </summary>
    /// <param name="topicArn">The ARN of the SNS topic.</param>
    /// <returns>The user's email.</returns>
    private static async Task<string> SubscribeToSnsTopic(string topicArn)
    {
        Console.WriteLine(new string('-', 80));


        string email = "";
        while (string.IsNullOrEmpty(email))
        {
            Console.WriteLine("Enter your email to subscribe to the Amazon SNS topic:");
            email = Console.ReadLine()!;
        }

        var subscriptions = new List<string>();
        var paginatedSubscriptions = _snsClient!.Paginators.ListSubscriptionsByTopic(
            new ListSubscriptionsByTopicRequest()
            {
                TopicArn = topicArn
            });

        // Get the entire list using the paginator.
        await foreach (var subscription in paginatedSubscriptions.Subscriptions)
        {
            subscriptions.Add(subscription.Endpoint);
        }

        if (subscriptions.Contains(email))
        {
            Console.WriteLine($"\tYour email is already subscribed.");
            Console.WriteLine(new string('-', 80));
            return email;
        }

        await _snsClient.SubscribeAsync(new SubscribeRequest()
        {
            TopicArn = topicArn,
            Protocol = "email",
            Endpoint = email
        });

        Console.WriteLine($"Use the link in the email you received to confirm your subscription, then press Enter to continue.");

        Console.ReadLine();

        Console.WriteLine(new string('-', 80));
        return email;
    }

    /// <summary>
    /// Add a rule which triggers when a file is uploaded to an S3 bucket.
    /// </summary>
    /// <param name="roleArn">The ARN of the role used by EventBridge.</param>
    /// <returns>Async task.</returns>
    private static async Task AddEventRule(string roleArn)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Creating an EventBridge event that sends an email when an Amazon S3 object is created.");

        var eventRuleName = _configuration["eventRuleName"];
        var testBucketName = _configuration["testBucketName"];

        await _eventBridgeWrapper.PutS3UploadRule(roleArn, eventRuleName, testBucketName);
        Console.WriteLine($"\tAdded event rule {eventRuleName} for bucket {testBucketName}.");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Add an SNS target to the rule.
    /// </summary>
    /// <param name="topicArn">The ARN of the SNS topic.</param>
    /// <returns>Async task.</returns>
    private static async Task AddSnsTarget(string topicArn)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Adding a target to the rule to that sends an email when the rule is triggered.");

        var eventRuleName = _configuration["eventRuleName"];
        var testBucketName = _configuration["testBucketName"];
        var topicName = _configuration["topicName"];
        await _eventBridgeWrapper.AddSnsTargetToRule(eventRuleName, topicArn);
        Console.WriteLine($"\tAdded event rule {eventRuleName} with Amazon SNS target {topicName} for bucket {testBucketName}.");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List the event rules on the default event bus.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListEventRules()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Current event rules:");

        var rules = await _eventBridgeWrapper.ListAllRulesForEventBus();
        rules.ForEach(r => Console.WriteLine($"\tRule: {r.Name} Description: {r.Description} State: {r.State}"));

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Update the event target to use a transform.
    /// </summary>
    /// <param name="topicArn">The SNS topic ARN target to update.</param>
    /// <returns>Async task.</returns>
    private static async Task UpdateSnsEventRule(string topicArn)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Let's update the event target with a transform.");

        var eventRuleName = _configuration["eventRuleName"];
        var testBucketName = _configuration["testBucketName"];

        await _eventBridgeWrapper.UpdateS3UploadRuleTargetWithTransform(eventRuleName, topicArn);
        Console.WriteLine($"\tUpdated event rule {eventRuleName} with Amazon SNS target {topicArn} for bucket {testBucketName}.");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Update the rule to use a custom event pattern.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task UpdateToCustomRule(string topicArn)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Updating the event pattern to be triggered by a custom event instead.");

        var eventRuleName = _configuration["eventRuleName"];

        await _eventBridgeWrapper.UpdateCustomEventPattern(eventRuleName);

        Console.WriteLine($"\tUpdated event rule {eventRuleName} to custom pattern.");
        await _eventBridgeWrapper.UpdateCustomRuleTargetWithTransform(eventRuleName,
            topicArn);

        Console.WriteLine($"\tUpdated event target {topicArn}.");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Send rule events for a custom rule using the user's email address.
    /// </summary>
    /// <param name="email">The email address to include.</param>
    /// <returns>Async task.</returns>
    private static async Task TriggerCustomRule(string email)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Sending an event to trigger the rule. This will trigger a subscription email.");

        await _eventBridgeWrapper.PutCustomEmailEvent(email);

        Console.WriteLine($"\tEvents have been sent. Press Enter to continue.");
        Console.ReadLine();

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List all of the targets for a rule.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListTargets()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("List all of the targets for a particular rule.");

        var eventRuleName = _configuration["eventRuleName"];
        var targets = await _eventBridgeWrapper.ListAllTargetsOnRule(eventRuleName);
        targets.ForEach(t => Console.WriteLine($"\tTarget: {t.Arn} Id: {t.Id} Input: {t.Input}"));

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List all of the rules for a particular target.
    /// </summary>
    /// <param name="topicArn">The ARN of the SNS topic.</param>
    /// <returns>Async task.</returns>
    private static async Task ListRulesForTarget(string topicArn)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("List all of the rules for a particular target.");

        var rules = await _eventBridgeWrapper.ListAllRuleNamesByTarget(topicArn);
        rules.ForEach(r => Console.WriteLine($"\tRule: {r}"));

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Enable or disable a particular rule.
    /// </summary>
    /// <param name="isEnabled">True to enable the rule, otherwise false.</param>
    /// <returns>Async task.</returns>
    private static async Task ChangeRuleState(bool isEnabled)
    {
        Console.WriteLine(new string('-', 80));
        var eventRuleName = _configuration["eventRuleName"];

        if (!isEnabled)
        {
            Console.WriteLine($"Disabling the rule: {eventRuleName}");
            await _eventBridgeWrapper.DisableRuleByName(eventRuleName);
        }
        else
        {
            Console.WriteLine($"Enabling the rule: {eventRuleName}");
            await _eventBridgeWrapper.EnableRuleByName(eventRuleName);
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Get the current state of the rule.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task GetRuleState()
    {
        Console.WriteLine(new string('-', 80));
        var eventRuleName = _configuration["eventRuleName"];

        var state = await _eventBridgeWrapper.GetRuleStateByRuleName(eventRuleName);
        Console.WriteLine($"Rule {eventRuleName} is in current state {state}.");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="topicArn">The ARN of the SNS topic to clean up.</param>
    /// <returns>Async task.</returns>
    private static async Task CleanupResources(string topicArn)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Clean up resources.");

        var eventRuleName = _configuration["eventRuleName"];
        if (GetYesNoResponse($"\tDelete all targets and event rule {eventRuleName}? (y/n)"))
        {
            Console.WriteLine($"\tRemoving all targets from the event rule.");
            await _eventBridgeWrapper.RemoveAllTargetsFromRule(eventRuleName);

            Console.WriteLine($"\tDeleting event rule.");
            await _eventBridgeWrapper.DeleteRuleByName(eventRuleName);
        }

        var topicName = _configuration["topicName"];
        if (GetYesNoResponse($"\tDelete Amazon SNS subscription topic {topicName}? (y/n)"))
        {
            Console.WriteLine($"\tDeleting topic.");
            await _snsClient!.DeleteTopicAsync(new DeleteTopicRequest()
            {
                TopicArn = topicArn
            });
        }

        var bucketName = _configuration["testBucketName"];
        if (GetYesNoResponse($"\tDelete Amazon S3 bucket {bucketName}? (y/n)"))
        {
            Console.WriteLine($"\tDeleting bucket.");
            // Delete all objects in the bucket.
            var deleteList = await _s3Client.ListObjectsV2Async(new ListObjectsV2Request()
            {
                BucketName = bucketName
            });
            await _s3Client.DeleteObjectsAsync(new DeleteObjectsRequest()
            {
                BucketName = bucketName,
                Objects = deleteList.S3Objects
                    .Select(o => new KeyVersion { Key = o.Key }).ToList()
            });
            // Now delete the bucket.
            await _s3Client.DeleteBucketAsync(new DeleteBucketRequest()
            {
                BucketName = bucketName
            });
        }

        var roleName = _configuration["roleName"];
        if (GetYesNoResponse($"\tDelete role {roleName}? (y/n)"))
        {
            Console.WriteLine($"\tDetaching policy and deleting role.");

            await _iamClient!.DetachRolePolicyAsync(new DetachRolePolicyRequest()
            {
                RoleName = roleName,
                PolicyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess",
            });

            await _iamClient!.DeleteRoleAsync(new DeleteRoleRequest()
            {
                RoleName = roleName
            });
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null &&
                       ynResponse.Equals("y",
                           StringComparison.InvariantCultureIgnoreCase);
        return response;
    }
}
```
EventBridge オペレーションをラップするクラスを作成します。  

```
/// <summary>
/// Wrapper for Amazon EventBridge operations.
/// </summary>
public class EventBridgeWrapper
{
    private readonly IAmazonEventBridge _amazonEventBridge;
    private readonly ILogger<EventBridgeWrapper> _logger;

    /// <summary>
    /// Constructor for the EventBridge wrapper.
    /// </summary>
    /// <param name="amazonEventBridge">The injected EventBridge client.</param>
    /// <param name="logger">The injected logger for the wrapper.</param>
    public EventBridgeWrapper(IAmazonEventBridge amazonEventBridge, ILogger<EventBridgeWrapper> logger)

    {
        _amazonEventBridge = amazonEventBridge;
        _logger = logger;
    }

    /// <summary>
    /// Get the state for a rule by the rule name.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <param name="eventBusName">The optional name of the event bus. If empty, uses the default event bus.</param>
    /// <returns>The state of the rule.</returns>
    public async Task<RuleState> GetRuleStateByRuleName(string ruleName, string? eventBusName = null)
    {
        var ruleResponse = await _amazonEventBridge.DescribeRuleAsync(
            new DescribeRuleRequest()
            {
                Name = ruleName,
                EventBusName = eventBusName
            });
        return ruleResponse.State;
    }

    /// <summary>
    /// Enable a particular rule on an event bus.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> EnableRuleByName(string ruleName)
    {
        var ruleResponse = await _amazonEventBridge.EnableRuleAsync(
            new EnableRuleRequest()
            {
                Name = ruleName
            });
        return ruleResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Disable a particular rule on an event bus.
    /// </summary
    /// <param name="ruleName">The name of the rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DisableRuleByName(string ruleName)
    {
        var ruleResponse = await _amazonEventBridge.DisableRuleAsync(
            new DisableRuleRequest()
            {
                Name = ruleName
            });
        return ruleResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// List the rules on an event bus.
    /// </summary>
    /// <param name="eventBusArn">The optional ARN of the event bus. If empty, uses the default event bus.</param>
    /// <returns>The list of rules.</returns>
    public async Task<List<Rule>> ListAllRulesForEventBus(string? eventBusArn = null)
    {
        var results = new List<Rule>();
        var request = new ListRulesRequest()
        {
            EventBusName = eventBusArn
        };
        // Get all of the pages of rules.
        ListRulesResponse response;
        do
        {
            response = await _amazonEventBridge.ListRulesAsync(request);
            results.AddRange(response.Rules);
            request.NextToken = response.NextToken;

        } while (response.NextToken is not null);

        return results;
    }

    /// <summary>
    /// List all of the targets matching a rule by name.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <returns>The list of targets.</returns>
    public async Task<List<Target>> ListAllTargetsOnRule(string ruleName)
    {
        var results = new List<Target>();
        var request = new ListTargetsByRuleRequest()
        {
            Rule = ruleName
        };
        ListTargetsByRuleResponse response;
        do
        {
            response = await _amazonEventBridge.ListTargetsByRuleAsync(request);
            results.AddRange(response.Targets);
            request.NextToken = response.NextToken;

        } while (response.NextToken is not null);

        return results;
    }

    /// <summary>
    /// List names of all rules matching a target.
    /// </summary>
    /// <param name="targetArn">The ARN of the target.</param>
    /// <returns>The list of rule names.</returns>
    public async Task<List<string>> ListAllRuleNamesByTarget(string targetArn)
    {
        var results = new List<string>();
        var request = new ListRuleNamesByTargetRequest()
        {
            TargetArn = targetArn
        };
        ListRuleNamesByTargetResponse response;
        do
        {
            response = await _amazonEventBridge.ListRuleNamesByTargetAsync(request);
            results.AddRange(response.RuleNames);
            request.NextToken = response.NextToken;

        } while (response.NextToken is not null);

        return results;
    }

    /// <summary>
    /// Create a new event rule that triggers when an Amazon S3 object is created in a bucket.
    /// </summary>
    /// <param name="roleArn">The ARN of the role.</param>
    /// <param name="ruleName">The name to give the rule.</param>
    /// <param name="bucketName">The name of the bucket to trigger the event.</param>
    /// <returns>The ARN of the new rule.</returns>
    public async Task<string> PutS3UploadRule(string roleArn, string ruleName, string bucketName)
    {
        string eventPattern = "{" +
                                "\"source\": [\"aws.s3\"]," +
                                    "\"detail-type\": [\"Object Created\"]," +
                                    "\"detail\": {" +
                                        "\"bucket\": {" +
                                            "\"name\": [\"" + bucketName + "\"]" +
                                        "}" +
                                    "}" +
                              "}";

        var response = await _amazonEventBridge.PutRuleAsync(
            new PutRuleRequest()
            {
                Name = ruleName,
                Description = "Example S3 upload rule for EventBridge",
                RoleArn = roleArn,
                EventPattern = eventPattern
            });

        return response.RuleArn;
    }

    /// <summary>
    /// Update an Amazon S3 object created rule with a transform on the target.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <param name="targetArn">The ARN of the target.</param>
    /// <param name="eventBusArn">Optional event bus ARN. If empty, uses the default event bus.</param>
    /// <returns>The ID of the target.</returns>
    public async Task<string> UpdateS3UploadRuleTargetWithTransform(string ruleName, string targetArn, string? eventBusArn = null)
    {
        var targetID = Guid.NewGuid().ToString();

        var targets = new List<Target>
        {
            new Target()
            {
                Id = targetID,
                Arn = targetArn,
                InputTransformer = new InputTransformer()
                {
                    InputPathsMap = new Dictionary<string, string>()
                    {
                        {"bucket", "$.detail.bucket.name"},
                        {"time", "$.time"}
                    },
                    InputTemplate = "\"Notification: an object was uploaded to bucket <bucket> at <time>.\""
                }
            }
        };
        var response = await _amazonEventBridge.PutTargetsAsync(
            new PutTargetsRequest()
            {
                EventBusName = eventBusArn,
                Rule = ruleName,
                Targets = targets,
            });
        if (response.FailedEntryCount > 0)
        {
            response.FailedEntries.ForEach(e =>
            {
                _logger.LogError(
                    $"Failed to add target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}");
            });
        }
        return targetID;
    }

    /// <summary>
    /// Update a custom rule with a transform on the target.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <param name="targetArn">The ARN of the target.</param>
    /// <param name="eventBusArn">Optional event bus ARN. If empty, uses the default event bus.</param>
    /// <returns>The ID of the target.</returns>
    public async Task<string> UpdateCustomRuleTargetWithTransform(string ruleName, string targetArn, string? eventBusArn = null)
    {
        var targetID = Guid.NewGuid().ToString();

        var targets = new List<Target>
        {
            new Target()
            {
                Id = targetID,
                Arn = targetArn,
                InputTransformer = new InputTransformer()
                {
                    InputTemplate = "\"Notification: sample event was received.\""
                }
            }
        };
        var response = await _amazonEventBridge.PutTargetsAsync(
            new PutTargetsRequest()
            {
                EventBusName = eventBusArn,
                Rule = ruleName,
                Targets = targets,
            });
        if (response.FailedEntryCount > 0)
        {
            response.FailedEntries.ForEach(e =>
            {
                _logger.LogError(
                    $"Failed to add target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}");
            });
        }
        return targetID;
    }

    /// <summary>
    /// Add an event to the event bus that includes an email, message, and time.
    /// </summary>
    /// <param name="email">The email to use in the event detail of the custom event.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutCustomEmailEvent(string email)
    {
        var eventDetail = new
        {
            UserEmail = email,
            Message = "This event was generated by example code.",
            UtcTime = DateTime.UtcNow.ToString("g")
        };
        var response = await _amazonEventBridge.PutEventsAsync(
            new PutEventsRequest()
            {
                Entries = new List<PutEventsRequestEntry>()
                {
                    new PutEventsRequestEntry()
                    {
                        Source = "ExampleSource",
                        Detail = JsonSerializer.Serialize(eventDetail),
                        DetailType = "ExampleType"
                    }
                }
            });

        return response.FailedEntryCount == 0;
    }

    /// <summary>
    /// Update a rule to use a custom defined event pattern.
    /// </summary>
    /// <param name="ruleName">The name of the rule to update.</param>
    /// <returns>The ARN of the updated rule.</returns>
    public async Task<string> UpdateCustomEventPattern(string ruleName)
    {
        string customEventsPattern = "{" +
                                     "\"source\": [\"ExampleSource\"]," +
                                     "\"detail-type\": [\"ExampleType\"]" +
                                     "}";

        var response = await _amazonEventBridge.PutRuleAsync(
            new PutRuleRequest()
            {
                Name = ruleName,
                Description = "Custom test rule",
                EventPattern = customEventsPattern
            });

        return response.RuleArn;
    }

    /// <summary>
    /// Add an Amazon SNS target topic to a rule.
    /// </summary>
    /// <param name="ruleName">The name of the rule to update.</param>
    /// <param name="targetArn">The ARN of the Amazon SNS target.</param>
    /// <param name="eventBusArn">The optional event bus name, uses default if empty.</param>
    /// <returns>The ID of the target.</returns>
    public async Task<string> AddSnsTargetToRule(string ruleName, string targetArn, string? eventBusArn = null)
    {
        var targetID = Guid.NewGuid().ToString();

        // Create the list of targets and add a new target.
        var targets = new List<Target>
        {
            new Target()
            {
                Arn = targetArn,
                Id = targetID
            }
        };

        // Add the targets to the rule.
        var response = await _amazonEventBridge.PutTargetsAsync(
            new PutTargetsRequest()
            {
                EventBusName = eventBusArn,
                Rule = ruleName,
                Targets = targets,
            });

        if (response.FailedEntryCount > 0)
        {
            response.FailedEntries.ForEach(e =>
            {
                _logger.LogError(
                    $"Failed to add target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}");
            });
        }

        return targetID;
    }

    /// <summary>
    /// Delete an event rule by name.
    /// </summary>
    /// <param name="ruleName">The name of the event rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> RemoveAllTargetsFromRule(string ruleName)
    {
        var targetIds = new List<string>();
        var request = new ListTargetsByRuleRequest()
        {
            Rule = ruleName
        };
        ListTargetsByRuleResponse targetsResponse;
        do
        {
            targetsResponse = await _amazonEventBridge.ListTargetsByRuleAsync(request);
            targetIds.AddRange(targetsResponse.Targets.Select(t => t.Id));
            request.NextToken = targetsResponse.NextToken;

        } while (targetsResponse.NextToken is not null);

        var removeResponse = await _amazonEventBridge.RemoveTargetsAsync(
            new RemoveTargetsRequest()
            {
                Rule = ruleName,
                Ids = targetIds
            });

        if (removeResponse.FailedEntryCount > 0)
        {
            removeResponse.FailedEntries.ForEach(e =>
            {
                _logger.LogError(
                    $"Failed to remove target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}");
            });
        }

        return removeResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Delete an event rule by name.
    /// </summary>
    /// <param name="ruleName">The name of the event rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteRuleByName(string ruleName)
    {
        var response = await _amazonEventBridge.DeleteRuleAsync(
            new DeleteRuleRequest()
            {
                Name = ruleName
            });

        return response.HttpStatusCode == HttpStatusCode.OK;
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [DeleteRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/DeleteRule)
  + [DescribeRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/DescribeRule)
  + [DisableRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/DisableRule)
  + [EnableRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/EnableRule)
  + [ListRuleNamesByTarget](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/ListRuleNamesByTarget)
  + [ListRules](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/ListRules)
  + [ListTargetsByRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/ListTargetsByRule)
  + [PutEvents](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/PutEvents)
  + [PutRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/PutRule)
  + [PutTargets](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/PutTargets)

## アクション
<a name="actions"></a>

### `DeleteRule`
<a name="eventbridge_DeleteRule_csharp_3_topic"></a>

次のコード例は、`DeleteRule` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
その名前でルールを削除します。  

```
    /// <summary>
    /// Delete an event rule by name.
    /// </summary>
    /// <param name="ruleName">The name of the event rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteRuleByName(string ruleName)
    {
        var response = await _amazonEventBridge.DeleteRuleAsync(
            new DeleteRuleRequest()
            {
                Name = ruleName
            });

        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/DeleteRule)」を参照してください。

### `DescribeRule`
<a name="eventbridge_DescribeRule_csharp_3_topic"></a>

次のコード例は、`DescribeRule` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
ルールの説明を使用してルールの状態を取得します。  

```
    /// <summary>
    /// Get the state for a rule by the rule name.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <param name="eventBusName">The optional name of the event bus. If empty, uses the default event bus.</param>
    /// <returns>The state of the rule.</returns>
    public async Task<RuleState> GetRuleStateByRuleName(string ruleName, string? eventBusName = null)
    {
        var ruleResponse = await _amazonEventBridge.DescribeRuleAsync(
            new DescribeRuleRequest()
            {
                Name = ruleName,
                EventBusName = eventBusName
            });
        return ruleResponse.State;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/DescribeRule)」を参照してください。

### `DisableRule`
<a name="eventbridge_DisableRule_csharp_3_topic"></a>

次のコード例は、`DisableRule` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
そのルール名でルールを無効化します。  

```
    /// <summary>
    /// Disable a particular rule on an event bus.
    /// </summary
    /// <param name="ruleName">The name of the rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DisableRuleByName(string ruleName)
    {
        var ruleResponse = await _amazonEventBridge.DisableRuleAsync(
            new DisableRuleRequest()
            {
                Name = ruleName
            });
        return ruleResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DisableRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/DisableRule)」を参照してください。

### `EnableRule`
<a name="eventbridge_EnableRule_csharp_3_topic"></a>

次のコード例は、`EnableRule` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
そのルール名でルールを有効化します。  

```
    /// <summary>
    /// Enable a particular rule on an event bus.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> EnableRuleByName(string ruleName)
    {
        var ruleResponse = await _amazonEventBridge.EnableRuleAsync(
            new EnableRuleRequest()
            {
                Name = ruleName
            });
        return ruleResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[EnableRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/EnableRule)」を参照してください。

### `ListRuleNamesByTarget`
<a name="eventbridge_ListRuleNamesByTarget_csharp_3_topic"></a>

次のコード例は、`ListRuleNamesByTarget` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
ターゲットを使用してすべてのルール名を一覧表示します。  

```
    /// <summary>
    /// List names of all rules matching a target.
    /// </summary>
    /// <param name="targetArn">The ARN of the target.</param>
    /// <returns>The list of rule names.</returns>
    public async Task<List<string>> ListAllRuleNamesByTarget(string targetArn)
    {
        var results = new List<string>();
        var request = new ListRuleNamesByTargetRequest()
        {
            TargetArn = targetArn
        };
        ListRuleNamesByTargetResponse response;
        do
        {
            response = await _amazonEventBridge.ListRuleNamesByTargetAsync(request);
            results.AddRange(response.RuleNames);
            request.NextToken = response.NextToken;

        } while (response.NextToken is not null);

        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListRuleNamesByTarget](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/ListRuleNamesByTarget)」を参照してください。

### `ListRules`
<a name="eventbridge_ListRules_csharp_3_topic"></a>

次のコード例は、`ListRules` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
イベントバスのルールをすべて一覧表示します。  

```
    /// <summary>
    /// List the rules on an event bus.
    /// </summary>
    /// <param name="eventBusArn">The optional ARN of the event bus. If empty, uses the default event bus.</param>
    /// <returns>The list of rules.</returns>
    public async Task<List<Rule>> ListAllRulesForEventBus(string? eventBusArn = null)
    {
        var results = new List<Rule>();
        var request = new ListRulesRequest()
        {
            EventBusName = eventBusArn
        };
        // Get all of the pages of rules.
        ListRulesResponse response;
        do
        {
            response = await _amazonEventBridge.ListRulesAsync(request);
            results.AddRange(response.Rules);
            request.NextToken = response.NextToken;

        } while (response.NextToken is not null);

        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListRules](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/ListRules)」を参照してください。

### `ListTargetsByRule`
<a name="eventbridge_ListTargetsByRule_csharp_3_topic"></a>

次のコード例は、`ListTargetsByRule` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
ルール名を使用してルールのすべてのターゲットを一覧表示します。  

```
    /// <summary>
    /// List all of the targets matching a rule by name.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <returns>The list of targets.</returns>
    public async Task<List<Target>> ListAllTargetsOnRule(string ruleName)
    {
        var results = new List<Target>();
        var request = new ListTargetsByRuleRequest()
        {
            Rule = ruleName
        };
        ListTargetsByRuleResponse response;
        do
        {
            response = await _amazonEventBridge.ListTargetsByRuleAsync(request);
            results.AddRange(response.Targets);
            request.NextToken = response.NextToken;

        } while (response.NextToken is not null);

        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListTargetsByRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/ListTargetsByRule)」を参照してください。

### `PutEvents`
<a name="eventbridge_PutEvents_csharp_3_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
ルールのカスタムパターンに一致するイベントを送信します。  

```
    /// <summary>
    /// Add an event to the event bus that includes an email, message, and time.
    /// </summary>
    /// <param name="email">The email to use in the event detail of the custom event.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutCustomEmailEvent(string email)
    {
        var eventDetail = new
        {
            UserEmail = email,
            Message = "This event was generated by example code.",
            UtcTime = DateTime.UtcNow.ToString("g")
        };
        var response = await _amazonEventBridge.PutEventsAsync(
            new PutEventsRequest()
            {
                Entries = new List<PutEventsRequestEntry>()
                {
                    new PutEventsRequestEntry()
                    {
                        Source = "ExampleSource",
                        Detail = JsonSerializer.Serialize(eventDetail),
                        DetailType = "ExampleType"
                    }
                }
            });

        return response.FailedEntryCount == 0;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/PutEvents)」を参照してください。

### `PutRule`
<a name="eventbridge_PutRule_csharp_3_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
Amazon Simple Storage Service バケットにオブジェクトが追加されたときにトリガーするルールを作成します。  

```
    /// <summary>
    /// Create a new event rule that triggers when an Amazon S3 object is created in a bucket.
    /// </summary>
    /// <param name="roleArn">The ARN of the role.</param>
    /// <param name="ruleName">The name to give the rule.</param>
    /// <param name="bucketName">The name of the bucket to trigger the event.</param>
    /// <returns>The ARN of the new rule.</returns>
    public async Task<string> PutS3UploadRule(string roleArn, string ruleName, string bucketName)
    {
        string eventPattern = "{" +
                                "\"source\": [\"aws.s3\"]," +
                                    "\"detail-type\": [\"Object Created\"]," +
                                    "\"detail\": {" +
                                        "\"bucket\": {" +
                                            "\"name\": [\"" + bucketName + "\"]" +
                                        "}" +
                                    "}" +
                              "}";

        var response = await _amazonEventBridge.PutRuleAsync(
            new PutRuleRequest()
            {
                Name = ruleName,
                Description = "Example S3 upload rule for EventBridge",
                RoleArn = roleArn,
                EventPattern = eventPattern
            });

        return response.RuleArn;
    }
```
カスタムパターンを使用するルールを作成します。  

```
    /// <summary>
    /// Update a rule to use a custom defined event pattern.
    /// </summary>
    /// <param name="ruleName">The name of the rule to update.</param>
    /// <returns>The ARN of the updated rule.</returns>
    public async Task<string> UpdateCustomEventPattern(string ruleName)
    {
        string customEventsPattern = "{" +
                                     "\"source\": [\"ExampleSource\"]," +
                                     "\"detail-type\": [\"ExampleType\"]" +
                                     "}";

        var response = await _amazonEventBridge.PutRuleAsync(
            new PutRuleRequest()
            {
                Name = ruleName,
                Description = "Custom test rule",
                EventPattern = customEventsPattern
            });

        return response.RuleArn;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutRule](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/PutRule)」を参照してください。

### `PutTargets`
<a name="eventbridge_PutTargets_csharp_3_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
Amazon SNS トピックをルールのターゲットとして追加します。  

```
    /// <summary>
    /// Add an Amazon SNS target topic to a rule.
    /// </summary>
    /// <param name="ruleName">The name of the rule to update.</param>
    /// <param name="targetArn">The ARN of the Amazon SNS target.</param>
    /// <param name="eventBusArn">The optional event bus name, uses default if empty.</param>
    /// <returns>The ID of the target.</returns>
    public async Task<string> AddSnsTargetToRule(string ruleName, string targetArn, string? eventBusArn = null)
    {
        var targetID = Guid.NewGuid().ToString();

        // Create the list of targets and add a new target.
        var targets = new List<Target>
        {
            new Target()
            {
                Arn = targetArn,
                Id = targetID
            }
        };

        // Add the targets to the rule.
        var response = await _amazonEventBridge.PutTargetsAsync(
            new PutTargetsRequest()
            {
                EventBusName = eventBusArn,
                Rule = ruleName,
                Targets = targets,
            });

        if (response.FailedEntryCount > 0)
        {
            response.FailedEntries.ForEach(e =>
            {
                _logger.LogError(
                    $"Failed to add target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}");
            });
        }

        return targetID;
    }
```
ルールのターゲットにインプットトランスフォーマーを追加します。  

```
    /// <summary>
    /// Update an Amazon S3 object created rule with a transform on the target.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <param name="targetArn">The ARN of the target.</param>
    /// <param name="eventBusArn">Optional event bus ARN. If empty, uses the default event bus.</param>
    /// <returns>The ID of the target.</returns>
    public async Task<string> UpdateS3UploadRuleTargetWithTransform(string ruleName, string targetArn, string? eventBusArn = null)
    {
        var targetID = Guid.NewGuid().ToString();

        var targets = new List<Target>
        {
            new Target()
            {
                Id = targetID,
                Arn = targetArn,
                InputTransformer = new InputTransformer()
                {
                    InputPathsMap = new Dictionary<string, string>()
                    {
                        {"bucket", "$.detail.bucket.name"},
                        {"time", "$.time"}
                    },
                    InputTemplate = "\"Notification: an object was uploaded to bucket <bucket> at <time>.\""
                }
            }
        };
        var response = await _amazonEventBridge.PutTargetsAsync(
            new PutTargetsRequest()
            {
                EventBusName = eventBusArn,
                Rule = ruleName,
                Targets = targets,
            });
        if (response.FailedEntryCount > 0)
        {
            response.FailedEntries.ForEach(e =>
            {
                _logger.LogError(
                    $"Failed to add target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}");
            });
        }
        return targetID;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/PutTargets)」を参照してください。

### `RemoveTargets`
<a name="eventbridge_RemoveTargets_csharp_3_topic"></a>

次のコード例は、`RemoveTargets` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。
ルール名を使用してルールのすべてのターゲットを削除します。  

```
    /// <summary>
    /// Delete an event rule by name.
    /// </summary>
    /// <param name="ruleName">The name of the event rule.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> RemoveAllTargetsFromRule(string ruleName)
    {
        var targetIds = new List<string>();
        var request = new ListTargetsByRuleRequest()
        {
            Rule = ruleName
        };
        ListTargetsByRuleResponse targetsResponse;
        do
        {
            targetsResponse = await _amazonEventBridge.ListTargetsByRuleAsync(request);
            targetIds.AddRange(targetsResponse.Targets.Select(t => t.Id));
            request.NextToken = targetsResponse.NextToken;

        } while (targetsResponse.NextToken is not null);

        var removeResponse = await _amazonEventBridge.RemoveTargetsAsync(
            new RemoveTargetsRequest()
            {
                Rule = ruleName,
                Ids = targetIds
            });

        if (removeResponse.FailedEntryCount > 0)
        {
            removeResponse.FailedEntries.ForEach(e =>
            {
                _logger.LogError(
                    $"Failed to remove target {e.TargetId}: {e.ErrorMessage}, code {e.ErrorCode}");
            });
        }

        return removeResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス**」の「[RemoveTargets](https://docs.aws.amazon.com/goto/DotNetSDKV3/eventbridge-2015-10-07/RemoveTargets)」を参照してください。

# を使用した EventBridge スケジューラの例 SDK for .NET
<a name="csharp_3_scheduler_code_examples"></a>

次のコード例は、EventBridge スケジューラ AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello EventBridge スケジューラ
<a name="scheduler_hello_csharp_3_topic"></a>

次のコード例は、EventBridge スケジューラの使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge Scheduler#code-examples)での設定と実行の方法を確認してください。

```
public static class HelloScheduler
{
    static async Task Main(string[] args)
    {
        // Use the AWS .NET Core Setup package to set up dependency injection for the EventBridge Scheduler service.
        // Use your AWS profile name, or leave it blank to use the default profile.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonScheduler>()
            ).Build();

        // Now the client is available for injection.
        var schedulerClient = host.Services.GetRequiredService<IAmazonScheduler>();

        // You can use await and any of the async methods to get a response, or a paginator to list schedules or groups.
        var results = new List<ScheduleSummary>();
        var paginateSchedules = schedulerClient.Paginators.ListSchedules(
            new ListSchedulesRequest());
        Console.WriteLine(
            $"Hello AWS Scheduler! Let's list schedules in your account.");
        // Get the entire list using the paginator.
        await foreach (var schedule in paginateSchedules.Schedules)
        {
            results.Add(schedule);
        }
        Console.WriteLine($"\tTotal of {results.Count} schedule(s) available.");
        results.ForEach(s => Console.WriteLine($"\tSchedule: {s.Name}"));
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListSchedules](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/ListSchedules)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateSchedule`
<a name="scheduler_CreateSchedule_csharp_3_topic"></a>

次のコード例は、`CreateSchedule` を使用する方法を説明しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge Scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates a new schedule in Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule.</param>
    /// <param name="scheduleExpression">The schedule expression that defines when the schedule should run.</param>
    /// <param name="scheduleGroupName">The name of the schedule group to which the schedule should be added.</param>
    /// <param name="deleteAfterCompletion">Indicates whether to delete the schedule after completion.</param>
    /// <param name="useFlexibleTimeWindow">Indicates whether to use a flexible time window for the schedule.</param>
    /// <param name="targetArn">ARN of the event target.</param>
    /// <param name="roleArn">Execution Role ARN.</param>
    /// <returns>True if the schedule was created successfully, false otherwise.</returns>
    public async Task<bool> CreateScheduleAsync(
            string name,
            string scheduleExpression,
            string scheduleGroupName,
            string targetArn,
            string roleArn,
            string input,
            bool deleteAfterCompletion = false,
            bool useFlexibleTimeWindow = false)
    {
        try
        {
            int hoursToRun = 1;
            int flexibleTimeWindowMinutes = 10;

            var request = new CreateScheduleRequest
            {
                Name = name,
                ScheduleExpression = scheduleExpression,
                GroupName = scheduleGroupName,
                Target = new Target { Arn = targetArn, RoleArn = roleArn, Input = input },
                ActionAfterCompletion = deleteAfterCompletion
                    ? ActionAfterCompletion.DELETE
                    : ActionAfterCompletion.NONE,
                StartDate = DateTime.UtcNow, // Ignored for one-time schedules.
                EndDate =
                    DateTime.UtcNow
                        .AddHours(hoursToRun) // Ignored for one-time schedules.
            };
            // Allow a flexible time window if the caller specifies it.
            request.FlexibleTimeWindow = new FlexibleTimeWindow
            {
                Mode = useFlexibleTimeWindow
                    ? FlexibleTimeWindowMode.FLEXIBLE
                    : FlexibleTimeWindowMode.OFF,
                MaximumWindowInMinutes = useFlexibleTimeWindow
                    ? flexibleTimeWindowMinutes
                    : null
            };

            var response = await _amazonScheduler.CreateScheduleAsync(request);

            Console.WriteLine($"Successfully created schedule '{name}' " +
                              $"in schedule group '{scheduleGroupName}': {response.ScheduleArn}.");
            return true;
        }
        catch (ConflictException ex)
        {
            // If the name is not unique, a ConflictException will be thrown.
            _logger.LogError($"Failed to create schedule '{name}' due to a conflict. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating schedule '{name}' " +
                             $"in schedule group '{scheduleGroupName}': {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*「[CreateSchedule](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/CreateSchedule)」を参照してください。

### `CreateScheduleGroup`
<a name="scheduler_CreateScheduleGroup_csharp_3_topic"></a>

次のコード例は、`CreateScheduleGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge Scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates a new schedule group in Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule group.</param>
    /// <returns>True if the schedule group was created successfully, false otherwise.</returns>
    public async Task<bool> CreateScheduleGroupAsync(string name)
    {
        try
        {
            var request = new CreateScheduleGroupRequest { Name = name };

            var response = await _amazonScheduler.CreateScheduleGroupAsync(request);

            Console.WriteLine($"Successfully created schedule group '{name}': {response.ScheduleGroupArn}.");
            return true;

        }
        catch (ConflictException ex)
        {
            // If the name is not unique, a ConflictException will be thrown.
            _logger.LogError($"Failed to create schedule group '{name}' due to a conflict. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating schedule group '{name}': {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateScheduleGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/CreateScheduleGroup)」を参照してください。

### `DeleteSchedule`
<a name="scheduler_DeleteSchedule_csharp_3_topic"></a>

次のコード例は、`DeleteSchedule` を使用する方法を説明しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge Scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes an existing schedule from Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule to delete.</param>
    /// <param name="groupName">The group name of the schedule to delete.</param>
    /// <returns>True if the schedule was deleted successfully, false otherwise.</returns>
    public async Task<bool> DeleteScheduleAsync(string name, string groupName)
    {
        try
        {
            var request = new DeleteScheduleRequest
            {
                Name = name,
                GroupName = groupName
            };

            await _amazonScheduler.DeleteScheduleAsync(request);

            Console.WriteLine($"Successfully deleted schedule with name '{name}'.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError(
                $"Failed to delete schedule with ID '{name}' because the resource was not found: {ex.Message}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while deleting schedule with ID '{name}': {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteSchedule](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/DeleteSchedule)」を参照してください。

### `DeleteScheduleGroup`
<a name="scheduler_DeleteScheduleGroup_csharp_3_topic"></a>

次のコード例は、`DeleteScheduleGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge Scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes an existing schedule group from Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule group to delete.</param>
    /// <returns>True if the schedule group was deleted successfully, false otherwise.</returns>
    public async Task<bool> DeleteScheduleGroupAsync(string name)
    {
        try
        {
            var request = new DeleteScheduleGroupRequest { Name = name };

            await _amazonScheduler.DeleteScheduleGroupAsync(request);

            Console.WriteLine($"Successfully deleted schedule group '{name}'.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError(
                $"Failed to delete schedule group '{name}' because the resource was not found: {ex.Message}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while deleting schedule group '{name}': {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteScheduleGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/DeleteScheduleGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 予定されているイベント
<a name="scheduler_ScheduledEventsScenario_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 必要なリソースを使用して CloudFormation スタックをデプロイします。
+ EventBridge スケジューラのスケジュールグループを作成します。
+ 柔軟な時間枠で 1 回限りの EventBridge スケジューラのスケジュールを作成します。
+ 指定されたレートで定期的な EventBridge スケジューラのスケジュールを作成します。
+ EventBridge スケジューラのスケジュールとスケジュールグループを削除します。
+ リソースをクリーンアップしてスタックを削除します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge Scheduler#code-examples)での設定と実行の方法を確認してください。
シナリオを実行します。  

```
using System.Text.RegularExpressions;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.Scheduler;
using Amazon.Scheduler.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
using SchedulerActions;
using Exception = System.Exception;

namespace SchedulerScenario;

public class SchedulerWorkflow
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.
    This .NET code example performs the following tasks for the Amazon EventBridge Scheduler workflow:

    1. Prepare the Application:
       - Prompt the user for an email address to use for the subscription for the SNS topic subscription.
       - Prompt the user for a name for the Cloud Formation stack.
       - Deploy the Cloud Formation template in resources/cfn_template.yaml for resource creation.
       - Store the outputs of the stack into variables for use in the scenario.
       - Create a schedule group for all schedules.

    2. Create one-time Schedule:
       - Create a one-time schedule to send an initial event.
       - Use a Flexible Time Window and set the schedule to delete after completion.
       - Wait for the user to receive the event email from SNS.

    3. Create a time-based schedule:
       - Prompt the user for how many X times per Y hours a recurring event should be scheduled.
       - Create the scheduled event for X times per hour for Y hours.
       - Wait for the user to receive the event email from SNS.
       - Delete the schedule when the user is finished.

    4. Clean up:
       - Prompt the user for y/n answer if they want to destroy the stack and clean up all resources.
       - Delete the schedule group.
       - Destroy the Cloud Formation stack and wait until the stack has been removed.
    */

    public static ILogger<SchedulerWorkflow> _logger = null!;
    public static SchedulerWrapper _schedulerWrapper = null!;
    public static IAmazonCloudFormation _amazonCloudFormation = null!;

    private static string _roleArn = null!;
    private static string _snsTopicArn = null!;

    public static bool _interactive = true;
    private static string _stackName = "default-scheduler-scenario-stack-name";
    private static string _scheduleGroupName = "scenario-schedules-group";
    private static string _stackResourcePath = "../../../../../../scenarios/features/eventbridge_scheduler/resources/cfn_template.yaml";

    public static async Task Main(string[] args)
    {
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonScheduler>()
                    .AddAWSService<IAmazonCloudFormation>()
                    .AddTransient<SchedulerWrapper>()
            )
            .Build();

        if (_interactive)
        {
            _logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
                .CreateLogger<SchedulerWorkflow>();

            _schedulerWrapper = host.Services.GetRequiredService<SchedulerWrapper>();
            _amazonCloudFormation = host.Services.GetRequiredService<IAmazonCloudFormation>();
        }

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the Amazon EventBridge Scheduler Scenario.");
        Console.WriteLine(new string('-', 80));

        try
        {
            Console.WriteLine(new string('-', 80));
            var prepareSuccess = await PrepareApplication();
            Console.WriteLine(new string('-', 80));

            if (prepareSuccess)
            {
                Console.WriteLine(new string('-', 80));
                await CreateOneTimeSchedule();
                Console.WriteLine(new string('-', 80));

                Console.WriteLine(new string('-', 80));
                await CreateRecurringSchedule();
                Console.WriteLine(new string('-', 80));
            }

            Console.WriteLine(new string('-', 80));
            await Cleanup();
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "There was a problem with the scenario, initiating cleanup...");
            _interactive = false;
            await Cleanup();
        }

        Console.WriteLine("Amazon EventBridge Scheduler scenario completed.");
    }

    /// <summary>
    /// Prepares the application by creating the necessary resources.
    /// </summary>
    /// <returns>True if the application was prepared successfully.</returns>
    public static async Task<bool> PrepareApplication()
    {
        Console.WriteLine("Preparing the application...");
        try
        {
            // Prompt the user for an email address to use for the subscription.
            Console.WriteLine("\nThis example creates resources in a CloudFormation stack, including an SNS topic" +
                          "\nthat will be subscribed to the EventBridge Scheduler events. " +
                          "\n\nYou will need to confirm the subscription in order to receive event emails. ");

            var emailAddress = PromptUserForEmail();

            // Prompt the user for a name for the CloudFormation stack
            _stackName = PromptUserForStackName();

            // Deploy the CloudFormation stack
            var deploySuccess = await DeployCloudFormationStack(_stackName, emailAddress);

            if (deploySuccess)
            {
                // Create a schedule group for all schedules
                await _schedulerWrapper.CreateScheduleGroupAsync(_scheduleGroupName);

                Console.WriteLine("Application preparation complete.");
                return true;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while preparing the application.");
        }
        Console.WriteLine("Application preparation failed.");
        return false;
    }

    /// <summary>
    /// Deploys the CloudFormation stack with the necessary resources.
    /// </summary>
    /// <param name="stackName">The name of the CloudFormation stack.</param>
    /// <param name="email">The email to use for the subscription.</param>
    /// <returns>True if the stack was deployed successfully.</returns>
    private static async Task<bool> DeployCloudFormationStack(string stackName, string email)
    {
        Console.WriteLine($"\nDeploying CloudFormation stack: {stackName}");

        try
        {
            var request = new CreateStackRequest
            {
                StackName = stackName,
                TemplateBody = await File.ReadAllTextAsync(_stackResourcePath),
                Capabilities = { Capability.CAPABILITY_NAMED_IAM }
            };

            // If an email is provided, set the parameter.
            if (!string.IsNullOrWhiteSpace(email))
            {
                request.Parameters = new List<Parameter>()
                {
                    new() { ParameterKey = "email", ParameterValue = email }
                };
            }

            var response = await _amazonCloudFormation.CreateStackAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"CloudFormation stack creation started: {stackName}");

                // Wait for the stack to be in CREATE_COMPLETE state
                bool stackCreated = await WaitForStackCompletion(response.StackId);

                if (stackCreated)
                {
                    // Retrieve the output values
                    var success = await GetStackOutputs(response.StackId);
                    return success;
                }
                else
                {
                    _logger.LogError($"CloudFormation stack creation failed: {stackName}");
                    return false;
                }
            }
            else
            {
                _logger.LogError($"Failed to create CloudFormation stack: {stackName}");
                return false;
            }
        }
        catch (AlreadyExistsException)
        {
            _logger.LogWarning($"CloudFormation stack '{stackName}' already exists. Please provide a unique name.");
            var newStackName = PromptUserForStackName();
            return await DeployCloudFormationStack(newStackName, email);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while deploying the CloudFormation stack: {stackName}");
            return false;
        }
    }

    /// <summary>
    /// Waits for the CloudFormation stack to be in the CREATE_COMPLETE state.
    /// </summary>
    /// <param name="client">The CloudFormation client.</param>
    /// <param name="stackId">The ID of the CloudFormation stack.</param>
    /// <returns>True if the stack was created successfully.</returns>
    private static async Task<bool> WaitForStackCompletion(string stackId)
    {
        int retryCount = 0;
        const int maxRetries = 10;
        const int retryDelay = 30000; // 30 seconds.

        while (retryCount < maxRetries)
        {
            var describeStacksRequest = new DescribeStacksRequest
            {
                StackName = stackId
            };

            var describeStacksResponse = await _amazonCloudFormation.DescribeStacksAsync(describeStacksRequest);

            if (describeStacksResponse.Stacks.Count > 0)
            {
                if (describeStacksResponse.Stacks[0].StackStatus == StackStatus.CREATE_COMPLETE)
                {
                    Console.WriteLine("CloudFormation stack creation complete.");
                    return true;
                }
                if (describeStacksResponse.Stacks[0].StackStatus == StackStatus.CREATE_FAILED ||
                         describeStacksResponse.Stacks[0].StackStatus == StackStatus.ROLLBACK_COMPLETE)
                {
                    Console.WriteLine("CloudFormation stack creation failed.");
                    return false;
                }
            }

            Console.WriteLine("Waiting for CloudFormation stack creation to complete...");
            await Task.Delay(retryDelay);
            retryCount++;
        }

        _logger.LogError("Timed out waiting for CloudFormation stack creation to complete.");
        return false;
    }

    /// <summary>
    /// Retrieves the output values from the CloudFormation stack.
    /// </summary>
    /// <param name="stackId">The ID of the CloudFormation stack.</param>
    private static async Task<bool> GetStackOutputs(string stackId)
    {
        try
        {
            var describeStacksRequest = new DescribeStacksRequest { StackName = stackId };

            var describeStacksResponse =
                await _amazonCloudFormation.DescribeStacksAsync(describeStacksRequest);

            if (describeStacksResponse.Stacks.Count > 0)
            {
                var stack = describeStacksResponse.Stacks[0];
                _roleArn = GetStackOutputValue(stack, "RoleARN");
                _snsTopicArn = GetStackOutputValue(stack, "SNStopicARN");
                return true;
            }
            else
            {
                _logger.LogError($"No stack found for stack outputs: {stackId}");
                return false;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(
                ex, $"Failed to retrieve CloudFormation stack outputs: {stackId}");
            return false;
        }
    }

    /// <summary>
    /// Get an output value by key from a CloudFormation stack.
    /// </summary>
    /// <param name="stack">The CloudFormation stack.</param>
    /// <param name="outputKey">The key of the output.</param>
    /// <returns>The value as a string.</returns>
    private static string GetStackOutputValue(Stack stack, string outputKey)
    {
        var output = stack.Outputs.First(o => o.OutputKey == outputKey);
        var outputValue = output.OutputValue;
        Console.WriteLine($"Stack output {outputKey}: {outputValue}");
        return outputValue;
    }

    /// <summary>
    /// Creates a one-time schedule to send an initial event.
    /// </summary>
    /// <returns>True if the one-time schedule was created successfully.</returns>
    public static async Task<bool> CreateOneTimeSchedule()
    {
        var scheduleName =
            PromptUserForResourceName("Enter a name for the one-time schedule:");

        Console.WriteLine($"Creating a one-time schedule named '{scheduleName}' " +
                          $"\nto send an initial event in 1 minute with a flexible time window...");
        try
        {
            // Create a one-time schedule with a flexible time
            // window set to delete after completion.
            // You may also set a timezone instead of using UTC.
            var scheduledTime = DateTime.UtcNow.AddMinutes(1).ToString("s");

            var createSuccess = await _schedulerWrapper.CreateScheduleAsync(
                scheduleName,
                $"at({scheduledTime})",
                _scheduleGroupName,
                _snsTopicArn,
                _roleArn,
                $"One time scheduled event test from schedule {scheduleName}.",
                true,
                useFlexibleTimeWindow: true);

            Console.WriteLine($"Subscription email will receive an email from this event.");
            Console.WriteLine($"You must confirm your subscription to receive event emails.");

            Console.WriteLine($"One-time schedule '{scheduleName}' created successfully.");
            return createSuccess;
        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError(ex, $"The target with ARN '{_snsTopicArn}' was not found.");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while creating the one-time schedule '{scheduleName}'.");
            return false;
        }
    }

    /// <summary>
    /// Create a recurring schedule to send events at a specified rate in minutes.
    /// </summary>
    /// <returns>True if the recurring schedule was created successfully.</returns>
    public static async Task<bool> CreateRecurringSchedule()
    {
        Console.WriteLine("Creating a recurring schedule to send events for one hour...");

        try
        {
            // Prompt the user for a schedule name.
            var scheduleName =
                PromptUserForResourceName("Enter a name for the recurring schedule: ");

            // Prompt the user for the schedule rate (in minutes).
            var scheduleRateInMinutes =
                PromptUserForInteger("Enter the desired schedule rate (in minutes): ");

            // Create the recurring schedule.
            var createSuccess = await _schedulerWrapper.CreateScheduleAsync(
                scheduleName,
                $"rate({scheduleRateInMinutes} minutes)",
                _scheduleGroupName,
                _snsTopicArn,
                _roleArn,
                $"Recurrent event test from schedule {scheduleName}.");

            Console.WriteLine($"Subscription email will receive an email from this event.");
            Console.WriteLine($"You must confirm your subscription to receive event emails.");

            // Delete the schedule when the user is finished.
            if (!_interactive || GetYesNoResponse($"Are you ready to delete the '{scheduleName}' schedule? (y/n)"))
            {
                await _schedulerWrapper.DeleteScheduleAsync(scheduleName, _scheduleGroupName);
            }

            return createSuccess;
        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError(ex, $"The target with ARN '{_snsTopicArn}' was not found.");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while creating the recurring schedule.");
            return false;
        }
    }

    /// <summary>
    /// Cleans up the resources created during the scenario.
    /// </summary>
    /// <returns>True if the cleanup was successful.</returns>
    public static async Task<bool> Cleanup()
    {
        // Prompt the user to confirm cleanup.
        var cleanup = !_interactive || GetYesNoResponse(
            "Do you want to delete all resources created by this scenario? (y/n) ");
        if (cleanup)
        {
            try
            {
                // Delete the schedule group.
                var groupDeleteSuccess = await _schedulerWrapper.DeleteScheduleGroupAsync(_scheduleGroupName);

                // Destroy the CloudFormation stack and wait for it to be removed.
                var stackDeleteSuccess = await DeleteCloudFormationStack(_stackName, false);

                return groupDeleteSuccess && stackDeleteSuccess;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex,
                    "An error occurred while cleaning up the resources.");
                return false;
            }
        }
        _logger.LogInformation("EventBridge Scheduler scenario is complete.");
        return true;
    }

    /// <summary>
    /// Delete the resources in the stack and wait for confirmation.
    /// </summary>
    /// <param name="stackName">The name of the stack.</param>
    /// <param name="forceDelete">True to force delete the stack.</param>
    /// <returns>True if successful.</returns>
    private static async Task<bool> DeleteCloudFormationStack(string stackName, bool forceDelete)
    {
        var request = new DeleteStackRequest
        {
            StackName = stackName,
        };

        if (forceDelete)
        {
            request.DeletionMode = DeletionMode.FORCE_DELETE_STACK;
        }

        await _amazonCloudFormation.DeleteStackAsync(request);
        Console.WriteLine($"CloudFormation stack '{_stackName}' is being deleted. This may take a few minutes.");

        bool stackDeleted = await WaitForStackDeletion(_stackName, forceDelete);

        if (stackDeleted)
        {
            Console.WriteLine($"CloudFormation stack '{_stackName}' has been deleted.");
            return true;
        }
        else
        {
            _logger.LogError($"Failed to delete CloudFormation stack '{_stackName}'.");
            return false;
        }
    }

    /// <summary>
    /// Wait for the stack to be deleted.
    /// </summary>
    /// <param name="stackName">The name of the stack.</param>
    /// <param name="forceDelete">True to force delete the stack.</param>
    /// <returns>True if successful.</returns>
    private static async Task<bool> WaitForStackDeletion(string stackName, bool forceDelete)
    {
        int retryCount = 0;
        const int maxRetries = 10;
        const int retryDelay = 30000; // 30 seconds

        while (retryCount < maxRetries)
        {
            var describeStacksRequest = new DescribeStacksRequest
            {
                StackName = stackName
            };

            try
            {
                var describeStacksResponse = await _amazonCloudFormation.DescribeStacksAsync(describeStacksRequest);

                if (describeStacksResponse.Stacks.Count == 0 || describeStacksResponse.Stacks[0].StackStatus == StackStatus.DELETE_COMPLETE)
                {
                    return true;
                }
                if (!forceDelete && describeStacksResponse.Stacks[0].StackStatus == StackStatus.DELETE_FAILED)
                {
                    // Try one time to force delete.
                    return await DeleteCloudFormationStack(stackName, true);
                }
            }
            catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "ValidationError")
            {
                // Stack does not exist, so it has been successfully deleted.
                return true;
            }

            Console.WriteLine($"Waiting for CloudFormation stack '{stackName}' to be deleted...");
            await Task.Delay(retryDelay);
            retryCount++;
        }

        _logger.LogError($"Timed out waiting for CloudFormation stack '{stackName}' to be deleted.");
        return false;
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase);
        return response;
    }

    /// <summary>
    /// Prompt the user for a valid email address.
    /// </summary>
    /// <returns>The valid email address.</returns>
    private static string PromptUserForEmail()
    {
        if (_interactive)
        {
            Console.WriteLine("Enter an email address to use for event subscriptions: ");

            string email = Console.ReadLine()!;

            if (!IsValidEmail(email))
            {
                Console.WriteLine("Invalid email address. Please try again.");
                return PromptUserForEmail();
            }
            return email;
        }
        // Used when running without user prompts.
        return "";
    }

    /// <summary>
    /// Prompt the user for a non-empty stack name.
    /// </summary>
    /// <returns>The valid stack name</returns>
    private static string PromptUserForStackName()
    {
        Console.WriteLine("Enter a name for the AWS Cloud Formation Stack: ");
        if (_interactive)
        {
            string stackName = Console.ReadLine()!;
            var regex = "[a-zA-Z][-a-zA-Z0-9]|arn:[-a-zA-Z0-9:/._+]";
            if (!Regex.IsMatch(stackName, regex))
            {
                Console.WriteLine(
                    $"Invalid stack name. Please use a name that matches the pattern {regex}.");
                return PromptUserForStackName();
            }

            return stackName;
        }
        // Used when running without user prompts.
        return _stackName;
    }

    /// <summary>
    /// Prompt the user for a non-empty resource name.
    /// </summary>
    /// <returns>The valid stack name</returns>
    private static string PromptUserForResourceName(string prompt)
    {
        if (_interactive)
        {
            Console.WriteLine(prompt);
            string resourceName = Console.ReadLine()!;
            var regex = "[0-9a-zA-Z-_.]+";
            if (!Regex.IsMatch(resourceName, regex))
            {
                Console.WriteLine($"Invalid resource name. Please use a name that matches the pattern {regex}.");
                return PromptUserForResourceName(prompt);
            }
            return resourceName!;
        }
        // Used when running without user prompts.
        return "resource-" + Guid.NewGuid();
    }

    /// <summary>
    /// Prompt the user for a non-empty resource name.
    /// </summary>
    /// <returns>The valid stack name</returns>
    private static int PromptUserForInteger(string prompt)
    {
        if (_interactive)
        {
            Console.WriteLine(prompt);
            string stringResponse = Console.ReadLine()!;
            if (string.IsNullOrWhiteSpace(stringResponse) ||
                !Int32.TryParse(stringResponse, out var intResponse))
            {
                Console.WriteLine($"Invalid integer. ");
                return PromptUserForInteger(prompt);
            }
            return intResponse!;
        }
        // Used when running without user prompts.
        return 1;
    }

    /// <summary>
    /// Use System Mail to check for a valid email address.
    /// </summary>
    /// <param name="email">The string to verify.</param>
    /// <returns>True if a valid email address.</returns>
    private static bool IsValidEmail(string email)
    {
        try
        {
            var mailAddress = new System.Net.Mail.MailAddress(email);
            return mailAddress.Address == email;
        }
        catch
        {
            // Invalid emails will cause an exception, return false.
            return false;
        }
    }
}
```
サービスオペレーション用のラッパー  

```
using Amazon.Scheduler;
using Amazon.Scheduler.Model;
using Microsoft.Extensions.Logging;

namespace SchedulerActions;

/// <summary>
/// Wrapper class for Amazon EventBridge Scheduler operations.
/// </summary>
public class SchedulerWrapper
{
    private readonly IAmazonScheduler _amazonScheduler;
    private readonly ILogger<SchedulerWrapper> _logger;

    /// <summary>
    /// Constructor for the SchedulerWrapper class.
    /// </summary>
    /// <param name="amazonScheduler">The injected EventBridge Scheduler client.</param>
    /// <param name="logger">The injected logger.</param>
    public SchedulerWrapper(IAmazonScheduler amazonScheduler, ILogger<SchedulerWrapper> logger)
    {
        _amazonScheduler = amazonScheduler;
        _logger = logger;
    }

    /// <summary>
    /// Creates a new schedule in Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule.</param>
    /// <param name="scheduleExpression">The schedule expression that defines when the schedule should run.</param>
    /// <param name="scheduleGroupName">The name of the schedule group to which the schedule should be added.</param>
    /// <param name="deleteAfterCompletion">Indicates whether to delete the schedule after completion.</param>
    /// <param name="useFlexibleTimeWindow">Indicates whether to use a flexible time window for the schedule.</param>
    /// <param name="targetArn">ARN of the event target.</param>
    /// <param name="roleArn">Execution Role ARN.</param>
    /// <returns>True if the schedule was created successfully, false otherwise.</returns>
    public async Task<bool> CreateScheduleAsync(
            string name,
            string scheduleExpression,
            string scheduleGroupName,
            string targetArn,
            string roleArn,
            string input,
            bool deleteAfterCompletion = false,
            bool useFlexibleTimeWindow = false)
    {
        try
        {
            int hoursToRun = 1;
            int flexibleTimeWindowMinutes = 10;

            var request = new CreateScheduleRequest
            {
                Name = name,
                ScheduleExpression = scheduleExpression,
                GroupName = scheduleGroupName,
                Target = new Target { Arn = targetArn, RoleArn = roleArn, Input = input },
                ActionAfterCompletion = deleteAfterCompletion
                    ? ActionAfterCompletion.DELETE
                    : ActionAfterCompletion.NONE,
                StartDate = DateTime.UtcNow, // Ignored for one-time schedules.
                EndDate =
                    DateTime.UtcNow
                        .AddHours(hoursToRun) // Ignored for one-time schedules.
            };
            // Allow a flexible time window if the caller specifies it.
            request.FlexibleTimeWindow = new FlexibleTimeWindow
            {
                Mode = useFlexibleTimeWindow
                    ? FlexibleTimeWindowMode.FLEXIBLE
                    : FlexibleTimeWindowMode.OFF,
                MaximumWindowInMinutes = useFlexibleTimeWindow
                    ? flexibleTimeWindowMinutes
                    : null
            };

            var response = await _amazonScheduler.CreateScheduleAsync(request);

            Console.WriteLine($"Successfully created schedule '{name}' " +
                              $"in schedule group '{scheduleGroupName}': {response.ScheduleArn}.");
            return true;
        }
        catch (ConflictException ex)
        {
            // If the name is not unique, a ConflictException will be thrown.
            _logger.LogError($"Failed to create schedule '{name}' due to a conflict. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating schedule '{name}' " +
                             $"in schedule group '{scheduleGroupName}': {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Creates a new schedule group in Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule group.</param>
    /// <returns>True if the schedule group was created successfully, false otherwise.</returns>
    public async Task<bool> CreateScheduleGroupAsync(string name)
    {
        try
        {
            var request = new CreateScheduleGroupRequest { Name = name };

            var response = await _amazonScheduler.CreateScheduleGroupAsync(request);

            Console.WriteLine($"Successfully created schedule group '{name}': {response.ScheduleGroupArn}.");
            return true;

        }
        catch (ConflictException ex)
        {
            // If the name is not unique, a ConflictException will be thrown.
            _logger.LogError($"Failed to create schedule group '{name}' due to a conflict. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while creating schedule group '{name}': {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Deletes an existing schedule from Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule to delete.</param>
    /// <param name="groupName">The group name of the schedule to delete.</param>
    /// <returns>True if the schedule was deleted successfully, false otherwise.</returns>
    public async Task<bool> DeleteScheduleAsync(string name, string groupName)
    {
        try
        {
            var request = new DeleteScheduleRequest
            {
                Name = name,
                GroupName = groupName
            };

            await _amazonScheduler.DeleteScheduleAsync(request);

            Console.WriteLine($"Successfully deleted schedule with name '{name}'.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError(
                $"Failed to delete schedule with ID '{name}' because the resource was not found: {ex.Message}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while deleting schedule with ID '{name}': {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Deletes an existing schedule group from Amazon EventBridge Scheduler.
    /// </summary>
    /// <param name="name">The name of the schedule group to delete.</param>
    /// <returns>True if the schedule group was deleted successfully, false otherwise.</returns>
    public async Task<bool> DeleteScheduleGroupAsync(string name)
    {
        try
        {
            var request = new DeleteScheduleGroupRequest { Name = name };

            await _amazonScheduler.DeleteScheduleGroupAsync(request);

            Console.WriteLine($"Successfully deleted schedule group '{name}'.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError(
                $"Failed to delete schedule group '{name}' because the resource was not found: {ex.Message}");
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(
                $"An error occurred while deleting schedule group '{name}': {ex.Message}");
            return false;
        }
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateSchedule](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/CreateSchedule)
  + [CreateScheduleGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/CreateScheduleGroup)
  + [DeleteSchedule](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/DeleteSchedule)
  + [DeleteScheduleGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/scheduler-2021-06-30/DeleteScheduleGroups)

# を使用した Amazon Glacier の例 SDK for .NET
<a name="csharp_3_glacier_code_examples"></a>

次のコード例は、Amazon Glacier AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Glacier
<a name="glacier_Hello_csharp_3_topic"></a>

次のコード例は、Amazon Glacier の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/EventBridge#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.Glacier;
using Amazon.Glacier.Model;

namespace GlacierActions;

public static class HelloGlacier
{
    static async Task Main()
    {
        var glacierService = new AmazonGlacierClient();

        Console.WriteLine("Hello Amazon Glacier!");
        Console.WriteLine("Let's list your Glacier vaults:");

        // You can use await and any of the async methods to get a response.
        // Let's get the vaults using a paginator.
        var glacierVaultPaginator = glacierService.Paginators.ListVaults(
            new ListVaultsRequest { AccountId = "-" });

        await foreach (var vault in glacierVaultPaginator.VaultList)
        {
            Console.WriteLine($"{vault.CreationDate}:{vault.VaultName}, ARN:{vault.VaultARN}");
        }
    }
}
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[ListVaults](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/ListVaults)」を参照してください。

## アクション
<a name="actions"></a>

### `AddTagsToVault`
<a name="glacier_AddTagsToVault_csharp_3_topic"></a>

次のコード例は、`AddTagsToVault` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Add tags to the items in an Amazon S3 Glacier vault.
    /// </summary>
    /// <param name="vaultName">The name of the vault to add tags to.</param>
    /// <param name="key">The name of the object to tag.</param>
    /// <param name="value">The tag value to add.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AddTagsToVaultAsync(string vaultName, string key, string value)
    {
        var request = new AddTagsToVaultRequest
        {
            Tags = new Dictionary<string, string>
                {
                    { key, value },
                },
            AccountId = "-",
            VaultName = vaultName,
        };

        var response = await _glacierService.AddTagsToVaultAsync(request);
        return response.HttpStatusCode == HttpStatusCode.NoContent;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[AddTagsToVault](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/AddTagsToVault)」を参照してください。

### `CreateVault`
<a name="glacier_CreateVault_csharp_3_topic"></a>

次のコード例は、`CreateVault` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an Amazon S3 Glacier vault.
    /// </summary>
    /// <param name="vaultName">The name of the vault to create.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateVaultAsync(string vaultName)
    {
        var request = new CreateVaultRequest
        {
            // Setting the AccountId to "-" means that
            // the account associated with the current
            // account will be used.
            AccountId = "-",
            VaultName = vaultName,
        };

        var response = await _glacierService.CreateVaultAsync(request);

        Console.WriteLine($"Created {vaultName} at: {response.Location}");

        return response.HttpStatusCode == HttpStatusCode.Created;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateVault](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/CreateVault)」を参照してください。

### `DescribeVault`
<a name="glacier_DescribeVault_csharp_3_topic"></a>

次のコード例は、`DescribeVault` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe an Amazon S3 Glacier vault.
    /// </summary>
    /// <param name="vaultName">The name of the vault to describe.</param>
    /// <returns>The Amazon Resource Name (ARN) of the vault.</returns>
    public async Task<string> DescribeVaultAsync(string vaultName)
    {
        var request = new DescribeVaultRequest
        {
            AccountId = "-",
            VaultName = vaultName,
        };

        var response = await _glacierService.DescribeVaultAsync(request);

        // Display the information about the vault.
        Console.WriteLine($"{response.VaultName}\tARN: {response.VaultARN}");
        Console.WriteLine($"Created on: {response.CreationDate}\tNumber of Archives: {response.NumberOfArchives}\tSize (in bytes): {response.SizeInBytes}");
        if (response.LastInventoryDate != DateTime.MinValue)
        {
            Console.WriteLine($"Last inventory: {response.LastInventoryDate}");
        }

        return response.VaultARN;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeVault](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/DescribeVault)」を参照してください。

### `InitiateJob`
<a name="glacier_InitiateJob_csharp_3_topic"></a>

次のコード例は、`InitiateJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。
ボールトからアーカイブを取得します。この例では ArchiveTransferManager クラスを使用しています。API の詳細については、「[ArchiveTransferManager](https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Glacier/TArchiveTransferManager)」を参照してください。  

```
    /// <summary>
    /// Download an archive from an Amazon S3 Glacier vault using the Archive
    /// Transfer Manager.
    /// </summary>
    /// <param name="vaultName">The name of the vault containing the object.</param>
    /// <param name="archiveId">The Id of the archive to download.</param>
    /// <param name="localFilePath">The local directory where the file will
    /// be stored after download.</param>
    /// <returns>Async Task.</returns>
    public async Task<bool> DownloadArchiveWithArchiveManagerAsync(string vaultName, string archiveId, string localFilePath)
    {
        try
        {
            var manager = new ArchiveTransferManager(_glacierService);

            var options = new DownloadOptions
            {
                StreamTransferProgress = Progress!,
            };

            // Download an archive.
            Console.WriteLine("Initiating the archive retrieval job and then polling SQS queue for the archive to be available.");
            Console.WriteLine("When the archive is available, downloading will begin.");
            await manager.DownloadAsync(vaultName, archiveId, localFilePath, options);

            return true;
        }
        catch (AmazonGlacierException ex)
        {
            Console.WriteLine(ex.Message);
            return false;
        }
    }

    /// <summary>
    /// Event handler to track the progress of the Archive Transfer Manager.
    /// </summary>
    /// <param name="sender">The object that raised the event.</param>
    /// <param name="args">The argument values from the object that raised the
    /// event.</param>
    static void Progress(object sender, StreamTransferProgressArgs args)
    {
        if (args.PercentDone != _currentPercentage)
        {
            _currentPercentage = args.PercentDone;
            Console.WriteLine($"Downloaded {_currentPercentage}%");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[InitiateJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/InitiateJob)」を参照してください。

### `ListJobs`
<a name="glacier_ListJobs_csharp_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List Amazon S3 Glacier jobs.
    /// </summary>
    /// <param name="vaultName">The name of the vault to list jobs for.</param>
    /// <returns>A list of Amazon S3 Glacier jobs.</returns>
    public async Task<List<GlacierJobDescription>> ListJobsAsync(string vaultName)
    {
        var request = new ListJobsRequest
        {
            // Using a hyphen "-" for the Account Id will
            // cause the SDK to use the Account Id associated
            // with the current account.
            AccountId = "-",
            VaultName = vaultName,
        };

        var response = await _glacierService.ListJobsAsync(request);

        return response.JobList;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/ListJobs)」を参照してください。

### `ListTagsForVault`
<a name="glacier_ListTagsForVault_csharp_3_topic"></a>

次のコード例は、`ListTagsForVault` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List tags for an Amazon S3 Glacier vault.
    /// </summary>
    /// <param name="vaultName">The name of the vault to list tags for.</param>
    /// <returns>A dictionary listing the tags attached to each object in the
    /// vault and its tags.</returns>
    public async Task<Dictionary<string, string>> ListTagsForVaultAsync(string vaultName)
    {
        var request = new ListTagsForVaultRequest
        {
            // Using a hyphen "-" for the Account Id will
            // cause the SDK to use the Account Id associated
            // with the default user.
            AccountId = "-",
            VaultName = vaultName,
        };

        var response = await _glacierService.ListTagsForVaultAsync(request);

        return response.Tags;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListTagsForVault](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/ListTagsForVault)」を参照してください。

### `ListVaults`
<a name="glacier_ListVaults_csharp_3_topic"></a>

次のコード例は、`ListVaults` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List the Amazon S3 Glacier vaults associated with the current account.
    /// </summary>
    /// <returns>A list containing information about each vault.</returns>
    public async Task<List<DescribeVaultOutput>> ListVaultsAsync()
    {
        var glacierVaultPaginator = _glacierService.Paginators.ListVaults(
            new ListVaultsRequest { AccountId = "-" });
        var vaultList = new List<DescribeVaultOutput>();

        await foreach (var vault in glacierVaultPaginator.VaultList)
        {
            vaultList.Add(vault);
        }

        return vaultList;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListVaults](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/ListVaults)」を参照してください。

### `UploadArchive`
<a name="glacier_UploadArchive_csharp_3_topic"></a>

次のコード例は、`UploadArchive` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glacier#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Upload an object to an Amazon S3 Glacier vault.
    /// </summary>
    /// <param name="vaultName">The name of the Amazon S3 Glacier vault to upload
    /// the archive to.</param>
    /// <param name="archiveFilePath">The file path of the archive to upload to the vault.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<string> UploadArchiveWithArchiveManager(string vaultName, string archiveFilePath)
    {
        try
        {
            var manager = new ArchiveTransferManager(_glacierService);

            // Upload an archive.
            var response = await manager.UploadAsync(vaultName, "upload archive test", archiveFilePath);
            return response.ArchiveId;
        }
        catch (AmazonGlacierException ex)
        {
            Console.WriteLine(ex.Message);
            return string.Empty;
        }
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[UploadArchive](https://docs.aws.amazon.com/goto/DotNetSDKV3/glacier-2012-06-01/UploadArchive)」を参照してください。

# AWS Glue を使用した の例 SDK for .NET
<a name="csharp_3_glue_code_examples"></a>

次のコード例は、 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Glueは
<a name="glue_Hello_csharp_3_topic"></a>

次のコード例は、 AWS Glueの使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
namespace GlueActions;

public class HelloGlue
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for AWS Glue.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonGlue>()
                .AddTransient<GlueWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<HelloGlue>();
        var glueClient = host.Services.GetRequiredService<IAmazonGlue>();

        var request = new ListJobsRequest();

        var jobNames = new List<string>();

        do
        {
            var response = await glueClient.ListJobsAsync(request);
            jobNames.AddRange(response.JobNames);
            request.NextToken = response.NextToken;
        }
        while (request.NextToken is not null);

        Console.Clear();
        Console.WriteLine("Hello, Glue. Let's list your existing Glue Jobs:");
        if (jobNames.Count == 0)
        {
            Console.WriteLine("You don't have any AWS Glue jobs.");
        }
        else
        {
            jobNames.ForEach(Console.WriteLine);
        }
    }
}
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/ListJobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。
シナリオで使用される AWS Glue 関数をラップするクラスを作成します。  

```
using System.Net;

namespace GlueActions;

public class GlueWrapper
{
    private readonly IAmazonGlue _amazonGlue;

    /// <summary>
    /// Constructor for the AWS Glue actions wrapper.
    /// </summary>
    /// <param name="amazonGlue"></param>
    public GlueWrapper(IAmazonGlue amazonGlue)
    {
        _amazonGlue = amazonGlue;
    }

    /// <summary>
    /// Create an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name for the crawler.</param>
    /// <param name="crawlerDescription">A description of the crawler.</param>
    /// <param name="role">The AWS Identity and Access Management (IAM) role to
    /// be assumed by the crawler.</param>
    /// <param name="schedule">The schedule on which the crawler will be executed.</param>
    /// <param name="s3Path">The path to the Amazon Simple Storage Service (Amazon S3)
    /// bucket where the Python script has been stored.</param>
    /// <param name="dbName">The name to use for the database that will be
    /// created by the crawler.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateCrawlerAsync(
        string crawlerName,
        string crawlerDescription,
        string role,
        string schedule,
        string s3Path,
        string dbName)
    {
        var s3Target = new S3Target
        {
            Path = s3Path,
        };

        var targetList = new List<S3Target>
        {
            s3Target,
        };

        var targets = new CrawlerTargets
        {
            S3Targets = targetList,
        };

        var crawlerRequest = new CreateCrawlerRequest
        {
            DatabaseName = dbName,
            Name = crawlerName,
            Description = crawlerDescription,
            Targets = targets,
            Role = role,
            Schedule = schedule,
        };

        var response = await _amazonGlue.CreateCrawlerAsync(crawlerRequest);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Create an AWS Glue job.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <param name="roleName">The name of the IAM role to be assumed by
    /// the job.</param>
    /// <param name="description">A description of the job.</param>
    /// <param name="scriptUrl">The URL to the script.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateJobAsync(string dbName, string tableName, string bucketUrl, string jobName, string roleName, string description, string scriptUrl)
    {
        var command = new JobCommand
        {
            PythonVersion = "3",
            Name = "glueetl",
            ScriptLocation = scriptUrl,
        };

        var arguments = new Dictionary<string, string>
        {
            { "--input_database", dbName },
            { "--input_table", tableName },
            { "--output_bucket_url", bucketUrl }
        };

        var request = new CreateJobRequest
        {
            Command = command,
            DefaultArguments = arguments,
            Description = description,
            GlueVersion = "3.0",
            Name = jobName,
            NumberOfWorkers = 10,
            Role = roleName,
            WorkerType = "G.1X"
        };

        var response = await _amazonGlue.CreateJobAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name of the crawler.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteCrawlerAsync(string crawlerName)
    {
        var response = await _amazonGlue.DeleteCrawlerAsync(new DeleteCrawlerRequest { Name = crawlerName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete the AWS Glue database.
    /// </summary>
    /// <param name="dbName">The name of the database.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteDatabaseAsync(string dbName)
    {
        var response = await _amazonGlue.DeleteDatabaseAsync(new DeleteDatabaseRequest { Name = dbName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an AWS Glue job.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteJobAsync(string jobName)
    {
        var response = await _amazonGlue.DeleteJobAsync(new DeleteJobRequest { JobName = jobName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete a table from an AWS Glue database.
    /// </summary>
    /// <param name="tableName">The table to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteTableAsync(string dbName, string tableName)
    {
        var response = await _amazonGlue.DeleteTableAsync(new DeleteTableRequest { Name = tableName, DatabaseName = dbName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Get information about an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name of the crawler.</param>
    /// <returns>A Crawler object describing the crawler.</returns>
    public async Task<Crawler?> GetCrawlerAsync(string crawlerName)
    {
        var crawlerRequest = new GetCrawlerRequest
        {
            Name = crawlerName,
        };

        var response = await _amazonGlue.GetCrawlerAsync(crawlerRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            var databaseName = response.Crawler.DatabaseName;
            Console.WriteLine($"{crawlerName} has the database {databaseName}");
            return response.Crawler;
        }

        Console.WriteLine($"No information regarding {crawlerName} could be found.");
        return null;
    }


    /// <summary>
    /// Get information about the state of an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name of the crawler.</param>
    /// <returns>A value describing the state of the crawler.</returns>
    public async Task<CrawlerState> GetCrawlerStateAsync(string crawlerName)
    {
        var response = await _amazonGlue.GetCrawlerAsync(
            new GetCrawlerRequest { Name = crawlerName });
        return response.Crawler.State;
    }


    /// <summary>
    /// Get information about an AWS Glue database.
    /// </summary>
    /// <param name="dbName">The name of the database.</param>
    /// <returns>A Database object containing information about the database.</returns>
    public async Task<Database> GetDatabaseAsync(string dbName)
    {
        var databasesRequest = new GetDatabaseRequest
        {
            Name = dbName,
        };

        var response = await _amazonGlue.GetDatabaseAsync(databasesRequest);
        return response.Database;
    }


    /// <summary>
    /// Get information about a specific AWS Glue job run.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <param name="jobRunId">The Id of the job run.</param>
    /// <returns>A JobRun object with information about the job run.</returns>
    public async Task<JobRun> GetJobRunAsync(string jobName, string jobRunId)
    {
        var response = await _amazonGlue.GetJobRunAsync(new GetJobRunRequest { JobName = jobName, RunId = jobRunId });
        return response.JobRun;
    }


    /// <summary>
    /// Get information about all AWS Glue runs of a specific job.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <returns>A list of JobRun objects.</returns>
    public async Task<List<JobRun>> GetJobRunsAsync(string jobName)
    {
        var jobRuns = new List<JobRun>();

        var request = new GetJobRunsRequest
        {
            JobName = jobName,
        };

        // No need to loop to get all the log groups--the SDK does it for us behind the scenes
        var paginatorForJobRuns =
            _amazonGlue.Paginators.GetJobRuns(request);

        await foreach (var response in paginatorForJobRuns.Responses)
        {
            response.JobRuns.ForEach(jobRun =>
            {
                jobRuns.Add(jobRun);
            });
        }

        return jobRuns;
    }


    /// <summary>
    /// Get a list of tables for an AWS Glue database.
    /// </summary>
    /// <param name="dbName">The name of the database.</param>
    /// <returns>A list of Table objects.</returns>
    public async Task<List<Table>> GetTablesAsync(string dbName)
    {
        var request = new GetTablesRequest { DatabaseName = dbName };
        var tables = new List<Table>();

        // Get a paginator for listing the tables.
        var tablePaginator = _amazonGlue.Paginators.GetTables(request);

        await foreach (var response in tablePaginator.Responses)
        {
            tables.AddRange(response.TableList);
        }

        return tables;
    }


    /// <summary>
    /// List AWS Glue jobs using a paginator.
    /// </summary>
    /// <returns>A list of AWS Glue job names.</returns>
    public async Task<List<string>> ListJobsAsync()
    {
        var jobNames = new List<string>();

        var listJobsPaginator = _amazonGlue.Paginators.ListJobs(new ListJobsRequest { MaxResults = 10 });
        await foreach (var response in listJobsPaginator.Responses)
        {
            jobNames.AddRange(response.JobNames);
        }

        return jobNames;
    }


    /// <summary>
    /// Start an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name of the crawler.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> StartCrawlerAsync(string crawlerName)
    {
        var crawlerRequest = new StartCrawlerRequest
        {
            Name = crawlerName,
        };

        var response = await _amazonGlue.StartCrawlerAsync(crawlerRequest);

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Start an AWS Glue job run.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <returns>A string representing the job run Id.</returns>
    public async Task<string> StartJobRunAsync(
        string jobName,
        string inputDatabase,
        string inputTable,
        string bucketName)
    {
        var request = new StartJobRunRequest
        {
            JobName = jobName,
            Arguments = new Dictionary<string, string>
            {
                {"--input_database", inputDatabase},
                {"--input_table", inputTable},
                {"--output_bucket_url", $"s3://{bucketName}/"}
            }
        };

        var response = await _amazonGlue.StartJobRunAsync(request);
        return response.JobRunId;
    }

}
```
シナリオを実行するクラスを作成します。  

```
global using Amazon.Glue;
global using GlueActions;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;



using Amazon.Glue.Model;
using Amazon.S3;
using Amazon.S3.Model;

namespace GlueBasics;

public class GlueBasics
{
    private static ILogger logger = null!;
    private static IConfiguration _configuration = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for AWS Glue.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonGlue>()
            .AddTransient<GlueWrapper>()
            .AddTransient<UiWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
        .CreateLogger<GlueBasics>();

        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        // These values are stored in settings.json
        // Once you have run the CDK script to deploy the resources,
        // edit the file to set "BucketName", "RoleName", and "ScriptURL"
        // to the appropriate values. Also set "CrawlerName" to the name
        // you want to give the crawler when it is created.
        string bucketName = _configuration["BucketName"]!;
        string bucketUrl = _configuration["BucketUrl"]!;
        string crawlerName = _configuration["CrawlerName"]!;
        string roleName = _configuration["RoleName"]!;
        string sourceData = _configuration["SourceData"]!;
        string dbName = _configuration["DbName"]!;
        string cron = _configuration["Cron"]!;
        string scriptUrl = _configuration["ScriptURL"]!;
        string jobName = _configuration["JobName"]!;

        var wrapper = host.Services.GetRequiredService<GlueWrapper>();
        var uiWrapper = host.Services.GetRequiredService<UiWrapper>();

        uiWrapper.DisplayOverview();
        uiWrapper.PressEnter();

        // Create the crawler and wait for it to be ready.
        uiWrapper.DisplayTitle("Create AWS Glue crawler");
        Console.WriteLine("Let's begin by creating the AWS Glue crawler.");

        var crawlerDescription = "Crawler created for the AWS Glue Basics scenario.";
        var crawlerCreated = await wrapper.CreateCrawlerAsync(crawlerName, crawlerDescription, roleName, cron, sourceData, dbName);
        if (crawlerCreated)
        {
            Console.WriteLine($"The crawler: {crawlerName} has been created. Now let's wait until it's ready.");
            CrawlerState crawlerState;
            do
            {
                crawlerState = await wrapper.GetCrawlerStateAsync(crawlerName);
            }
            while (crawlerState != "READY");
            Console.WriteLine($"The crawler {crawlerName} is now ready for use.");
        }
        else
        {
            Console.WriteLine($"Couldn't create crawler {crawlerName}.");
            return; // Exit the application.
        }

        uiWrapper.DisplayTitle("Start AWS Glue crawler");
        Console.WriteLine("Now let's wait until the crawler has successfully started.");
        var crawlerStarted = await wrapper.StartCrawlerAsync(crawlerName);
        if (crawlerStarted)
        {
            CrawlerState crawlerState;
            do
            {
                crawlerState = await wrapper.GetCrawlerStateAsync(crawlerName);
            }
            while (crawlerState != "READY");
            Console.WriteLine($"The crawler {crawlerName} is now ready for use.");
        }
        else
        {
            Console.WriteLine($"Couldn't start the crawler {crawlerName}.");
            return; // Exit the application.
        }

        uiWrapper.PressEnter();

        Console.WriteLine($"\nLet's take a look at the database: {dbName}");
        var database = await wrapper.GetDatabaseAsync(dbName);

        if (database != null)
        {
            uiWrapper.DisplayTitle($"{database.Name} Details");
            Console.WriteLine($"{database.Name} created on {database.CreateTime}");
            Console.WriteLine(database.Description);
        }

        uiWrapper.PressEnter();

        var tables = await wrapper.GetTablesAsync(dbName);
        if (tables.Count > 0)
        {
            tables.ForEach(table =>
            {
                Console.WriteLine($"{table.Name}\tCreated: {table.CreateTime}\tUpdated: {table.UpdateTime}");
            });
        }

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Create AWS Glue job");
        Console.WriteLine("Creating a new AWS Glue job.");
        var description = "An AWS Glue job created using the AWS SDK for .NET";
        await wrapper.CreateJobAsync(dbName, tables[0].Name, bucketUrl, jobName, roleName, description, scriptUrl);

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Starting AWS Glue job");
        Console.WriteLine("Starting the new AWS Glue job...");
        var jobRunId = await wrapper.StartJobRunAsync(jobName, dbName, tables[0].Name, bucketName);
        var jobRunComplete = false;
        var jobRun = new JobRun();
        do
        {
            jobRun = await wrapper.GetJobRunAsync(jobName, jobRunId);
            if (jobRun.JobRunState == "SUCCEEDED" || jobRun.JobRunState == "STOPPED" ||
                jobRun.JobRunState == "FAILED" || jobRun.JobRunState == "TIMEOUT")
            {
                jobRunComplete = true;
            }
        } while (!jobRunComplete);

        uiWrapper.DisplayTitle($"Data in {bucketName}");

        // Get the list of data stored in the S3 bucket.
        var s3Client = new AmazonS3Client();

        var response = await s3Client.ListObjectsAsync(new ListObjectsRequest { BucketName = bucketName });
        response.S3Objects.ForEach(s3Object =>
        {
            Console.WriteLine(s3Object.Key);
        });

        uiWrapper.DisplayTitle("AWS Glue jobs");
        var jobNames = await wrapper.ListJobsAsync();
        jobNames.ForEach(jobName =>
        {
            Console.WriteLine(jobName);
        });

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Get AWS Glue job run information");
        Console.WriteLine("Getting information about the AWS Glue job.");
        var jobRuns = await wrapper.GetJobRunsAsync(jobName);

        jobRuns.ForEach(jobRun =>
        {
            Console.WriteLine($"{jobRun.JobName}\t{jobRun.JobRunState}\t{jobRun.CompletedOn}");
        });

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Deleting resources");
        Console.WriteLine("Deleting the AWS Glue job used by the example.");
        await wrapper.DeleteJobAsync(jobName);

        Console.WriteLine("Deleting the tables from the database.");
        tables.ForEach(async table =>
        {
            await wrapper.DeleteTableAsync(dbName, table.Name);
        });

        Console.WriteLine("Deleting the database.");
        await wrapper.DeleteDatabaseAsync(dbName);

        Console.WriteLine("Deleting the AWS Glue crawler.");
        await wrapper.DeleteCrawlerAsync(crawlerName);

        Console.WriteLine("The AWS Glue scenario has completed.");
        uiWrapper.PressEnter();
    }
}


namespace GlueBasics;

public class UiWrapper
{
    public readonly string SepBar = new string('-', Console.WindowWidth);

    /// <summary>
    /// Show information about the scenario.
    /// </summary>
    public void DisplayOverview()
    {
        Console.Clear();
        DisplayTitle("Amazon Glue: get started with crawlers and jobs");

        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t 1. Create a crawler, pass it the IAM role and the URL to the public S3 bucket that contains the source data");
        Console.WriteLine("\t 2. Start the crawler.");
        Console.WriteLine("\t 3. Get the database created by the crawler and the tables in the database.");
        Console.WriteLine("\t 4. Create a job.");
        Console.WriteLine("\t 5. Start a job run.");
        Console.WriteLine("\t 6. Wait for the job run to complete.");
        Console.WriteLine("\t 7. Show the data stored in the bucket.");
        Console.WriteLine("\t 8. List jobs for the account.");
        Console.WriteLine("\t 9. Get job run details for the job that was run.");
        Console.WriteLine("\t10. Delete the demo job.");
        Console.WriteLine("\t11. Delete the database and tables created for the demo.");
        Console.WriteLine("\t12. Delete the crawler.");
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPlease press <Enter> to continue. ");
        _ = Console.ReadLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter">The string to center on the screen.</param>
    /// <returns>The string padded to make it center on the screen.</returns>
    public string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(SepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(SepBar);
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/CreateCrawler)
  + [CreateJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/CreateJob)
  + [DeleteCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteCrawler)
  + [DeleteDatabase](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteDatabase)
  + [DeleteJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteJob)
  + [DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteTable)
  + [GetCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetCrawler)
  + [GetDatabase](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetDatabase)
  + [GetDatabases](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetDatabases)
  + [GetJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetJob)
  + [GetJobRun](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetJobRun)
  + [GetJobRuns](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetJobRuns)
  + [GetTables](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetTables)
  + [ListJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/ListJobs)
  + [StartCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/StartCrawler)
  + [StartJobRun](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/StartJobRun)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_csharp_3_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name for the crawler.</param>
    /// <param name="crawlerDescription">A description of the crawler.</param>
    /// <param name="role">The AWS Identity and Access Management (IAM) role to
    /// be assumed by the crawler.</param>
    /// <param name="schedule">The schedule on which the crawler will be executed.</param>
    /// <param name="s3Path">The path to the Amazon Simple Storage Service (Amazon S3)
    /// bucket where the Python script has been stored.</param>
    /// <param name="dbName">The name to use for the database that will be
    /// created by the crawler.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateCrawlerAsync(
        string crawlerName,
        string crawlerDescription,
        string role,
        string schedule,
        string s3Path,
        string dbName)
    {
        var s3Target = new S3Target
        {
            Path = s3Path,
        };

        var targetList = new List<S3Target>
        {
            s3Target,
        };

        var targets = new CrawlerTargets
        {
            S3Targets = targetList,
        };

        var crawlerRequest = new CreateCrawlerRequest
        {
            DatabaseName = dbName,
            Name = crawlerName,
            Description = crawlerDescription,
            Targets = targets,
            Role = role,
            Schedule = schedule,
        };

        var response = await _amazonGlue.CreateCrawlerAsync(crawlerRequest);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[CreateCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/CreateCrawler)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_csharp_3_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an AWS Glue job.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <param name="roleName">The name of the IAM role to be assumed by
    /// the job.</param>
    /// <param name="description">A description of the job.</param>
    /// <param name="scriptUrl">The URL to the script.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateJobAsync(string dbName, string tableName, string bucketUrl, string jobName, string roleName, string description, string scriptUrl)
    {
        var command = new JobCommand
        {
            PythonVersion = "3",
            Name = "glueetl",
            ScriptLocation = scriptUrl,
        };

        var arguments = new Dictionary<string, string>
        {
            { "--input_database", dbName },
            { "--input_table", tableName },
            { "--output_bucket_url", bucketUrl }
        };

        var request = new CreateJobRequest
        {
            Command = command,
            DefaultArguments = arguments,
            Description = description,
            GlueVersion = "3.0",
            Name = jobName,
            NumberOfWorkers = 10,
            Role = roleName,
            WorkerType = "G.1X"
        };

        var response = await _amazonGlue.CreateJobAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[CreateJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/CreateJob)」を参照してください。**

### `DeleteCrawler`
<a name="glue_DeleteCrawler_csharp_3_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name of the crawler.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteCrawlerAsync(string crawlerName)
    {
        var response = await _amazonGlue.DeleteCrawlerAsync(new DeleteCrawlerRequest { Name = crawlerName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[DeleteCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteCrawler)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_csharp_3_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete the AWS Glue database.
    /// </summary>
    /// <param name="dbName">The name of the database.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteDatabaseAsync(string dbName)
    {
        var response = await _amazonGlue.DeleteDatabaseAsync(new DeleteDatabaseRequest { Name = dbName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteDatabase](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteDatabase)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_csharp_3_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を説明しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an AWS Glue job.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteJobAsync(string jobName)
    {
        var response = await _amazonGlue.DeleteJobAsync(new DeleteJobRequest { JobName = jobName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteJob)」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_csharp_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a table from an AWS Glue database.
    /// </summary>
    /// <param name="tableName">The table to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteTableAsync(string dbName, string tableName)
    {
        var response = await _amazonGlue.DeleteTableAsync(new DeleteTableRequest { Name = tableName, DatabaseName = dbName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/DeleteTable)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_csharp_3_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name of the crawler.</param>
    /// <returns>A Crawler object describing the crawler.</returns>
    public async Task<Crawler?> GetCrawlerAsync(string crawlerName)
    {
        var crawlerRequest = new GetCrawlerRequest
        {
            Name = crawlerName,
        };

        var response = await _amazonGlue.GetCrawlerAsync(crawlerRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            var databaseName = response.Crawler.DatabaseName;
            Console.WriteLine($"{crawlerName} has the database {databaseName}");
            return response.Crawler;
        }

        Console.WriteLine($"No information regarding {crawlerName} could be found.");
        return null;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetCrawler)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_csharp_3_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about an AWS Glue database.
    /// </summary>
    /// <param name="dbName">The name of the database.</param>
    /// <returns>A Database object containing information about the database.</returns>
    public async Task<Database> GetDatabaseAsync(string dbName)
    {
        var databasesRequest = new GetDatabaseRequest
        {
            Name = dbName,
        };

        var response = await _amazonGlue.GetDatabaseAsync(databasesRequest);
        return response.Database;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetDatabase](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetDatabase)」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_csharp_3_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about a specific AWS Glue job run.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <param name="jobRunId">The Id of the job run.</param>
    /// <returns>A JobRun object with information about the job run.</returns>
    public async Task<JobRun> GetJobRunAsync(string jobName, string jobRunId)
    {
        var response = await _amazonGlue.GetJobRunAsync(new GetJobRunRequest { JobName = jobName, RunId = jobRunId });
        return response.JobRun;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetJobRun](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetJobRun)」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_csharp_3_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about all AWS Glue runs of a specific job.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <returns>A list of JobRun objects.</returns>
    public async Task<List<JobRun>> GetJobRunsAsync(string jobName)
    {
        var jobRuns = new List<JobRun>();

        var request = new GetJobRunsRequest
        {
            JobName = jobName,
        };

        // No need to loop to get all the log groups--the SDK does it for us behind the scenes
        var paginatorForJobRuns =
            _amazonGlue.Paginators.GetJobRuns(request);

        await foreach (var response in paginatorForJobRuns.Responses)
        {
            response.JobRuns.ForEach(jobRun =>
            {
                jobRuns.Add(jobRun);
            });
        }

        return jobRuns;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetJobRuns](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetJobRuns)」を参照してください。

### `GetTables`
<a name="glue_GetTables_csharp_3_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of tables for an AWS Glue database.
    /// </summary>
    /// <param name="dbName">The name of the database.</param>
    /// <returns>A list of Table objects.</returns>
    public async Task<List<Table>> GetTablesAsync(string dbName)
    {
        var request = new GetTablesRequest { DatabaseName = dbName };
        var tables = new List<Table>();

        // Get a paginator for listing the tables.
        var tablePaginator = _amazonGlue.Paginators.GetTables(request);

        await foreach (var response in tablePaginator.Responses)
        {
            tables.AddRange(response.TableList);
        }

        return tables;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetTables](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/GetTables)」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_csharp_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List AWS Glue jobs using a paginator.
    /// </summary>
    /// <returns>A list of AWS Glue job names.</returns>
    public async Task<List<string>> ListJobsAsync()
    {
        var jobNames = new List<string>();

        var listJobsPaginator = _amazonGlue.Paginators.ListJobs(new ListJobsRequest { MaxResults = 10 });
        await foreach (var response in listJobsPaginator.Responses)
        {
            jobNames.AddRange(response.JobNames);
        }

        return jobNames;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/ListJobs)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_csharp_3_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Start an AWS Glue crawler.
    /// </summary>
    /// <param name="crawlerName">The name of the crawler.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> StartCrawlerAsync(string crawlerName)
    {
        var crawlerRequest = new StartCrawlerRequest
        {
            Name = crawlerName,
        };

        var response = await _amazonGlue.StartCrawlerAsync(crawlerRequest);

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[StartCrawler](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/StartCrawler)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_csharp_3_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Glue#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Start an AWS Glue job run.
    /// </summary>
    /// <param name="jobName">The name of the job.</param>
    /// <returns>A string representing the job run Id.</returns>
    public async Task<string> StartJobRunAsync(
        string jobName,
        string inputDatabase,
        string inputTable,
        string bucketName)
    {
        var request = new StartJobRunRequest
        {
            JobName = jobName,
            Arguments = new Dictionary<string, string>
            {
                {"--input_database", inputDatabase},
                {"--input_table", inputTable},
                {"--output_bucket_url", $"s3://{bucketName}/"}
            }
        };

        var response = await _amazonGlue.StartJobRunAsync(request);
        return response.JobRunId;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[StartJobRun](https://docs.aws.amazon.com/goto/DotNetSDKV3/glue-2017-03-31/StartJobRun)」を参照してください。

# を使用した IAM の例 SDK for .NET
<a name="csharp_3_iam_code_examples"></a>

次のコード例は、IAM AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_csharp_3_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
namespace IAMActions;

public class HelloIAM
{
    static async Task Main(string[] args)
    {
        // Getting started with AWS Identity and Access Management (IAM). List
        // the policies for the account.
        var iamClient = new AmazonIdentityManagementServiceClient();

        var listPoliciesPaginator = iamClient.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        Console.WriteLine("Here are the policies defined for your account:\n");
        policies.ForEach(policy =>
        {
            Console.WriteLine($"Created: {policy.CreateDate}\t{policy.PolicyName}\t{policy.Description}");
        });
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListPolicies)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_csharp_3_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
global using Amazon.IdentityManagement;
global using Amazon.S3;
global using Amazon.SecurityToken;
global using IAMActions;
global using IamScenariosCommon;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;


namespace IAMActions;

public class IAMWrapper
{
    private readonly IAmazonIdentityManagementService _IAMService;

    /// <summary>
    /// Constructor for the IAMWrapper class.
    /// </summary>
    /// <param name="IAMService">An IAM client object.</param>
    public IAMWrapper(IAmazonIdentityManagementService IAMService)
    {
        _IAMService = IAMService;
    }

    /// <summary>
    /// Attach an IAM policy to a role.
    /// </summary>
    /// <param name="policyArn">The policy to attach.</param>
    /// <param name="roleName">The role that the policy will be attached to.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AttachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.AttachRolePolicyAsync(new AttachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Create an IAM access key for a user.
    /// </summary>
    /// <param name="userName">The username for which to create the IAM access
    /// key.</param>
    /// <returns>The AccessKey.</returns>
    public async Task<AccessKey> CreateAccessKeyAsync(string userName)
    {
        var response = await _IAMService.CreateAccessKeyAsync(new CreateAccessKeyRequest
        {
            UserName = userName,
        });

        return response.AccessKey;

    }


    /// <summary>
    /// Create an IAM policy.
    /// </summary>
    /// <param name="policyName">The name to give the new IAM policy.</param>
    /// <param name="policyDocument">The policy document for the new policy.</param>
    /// <returns>The new IAM policy object.</returns>
    public async Task<ManagedPolicy> CreatePolicyAsync(string policyName, string policyDocument)
    {
        var response = await _IAMService.CreatePolicyAsync(new CreatePolicyRequest
        {
            PolicyDocument = policyDocument,
            PolicyName = policyName,
        });

        return response.Policy;
    }


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


    /// <summary>
    /// Create an IAM service-linked role.
    /// </summary>
    /// <param name="serviceName">The name of the AWS Service.</param>
    /// <param name="description">A description of the IAM service-linked role.</param>
    /// <returns>The IAM role that was created.</returns>
    public async Task<Role> CreateServiceLinkedRoleAsync(string serviceName, string description)
    {
        var request = new CreateServiceLinkedRoleRequest
        {
            AWSServiceName = serviceName,
            Description = description
        };

        var response = await _IAMService.CreateServiceLinkedRoleAsync(request);
        return response.Role;
    }


    /// <summary>
    /// Create an IAM user.
    /// </summary>
    /// <param name="userName">The username for the new IAM user.</param>
    /// <returns>The IAM user that was created.</returns>
    public async Task<User> CreateUserAsync(string userName)
    {
        var response = await _IAMService.CreateUserAsync(new CreateUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// Delete an IAM user's access key.
    /// </summary>
    /// <param name="accessKeyId">The Id for the IAM access key.</param>
    /// <param name="userName">The username of the user that owns the IAM
    /// access key.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAccessKeyAsync(string accessKeyId, string userName)
    {
        var response = await _IAMService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest
        {
            AccessKeyId = accessKeyId,
            UserName = userName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM policy.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the policy to
    /// delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeletePolicyAsync(string policyArn)
    {
        var response = await _IAMService.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRoleAsync(string roleName)
    {
        var response = await _IAMService.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM role policy.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="policyName">The name of the IAM role policy to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRolePolicyAsync(string roleName, string policyName)
    {
        var response = await _IAMService.DeleteRolePolicyAsync(new DeleteRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user.
    /// </summary>
    /// <param name="userName">The username of the IAM user to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserAsync(string userName)
    {
        var response = await _IAMService.DeleteUserAsync(new DeleteUserRequest { UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an IAM user policy.
    /// </summary>
    /// <param name="policyName">The name of the IAM policy to delete.</param>
    /// <param name="userName">The username of the IAM user.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserPolicyAsync(string policyName, string userName)
    {
        var response = await _IAMService.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policyName, UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Detach an IAM policy from an IAM role.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DetachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.DetachRolePolicyAsync(new DetachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Gets the IAM password policy for an AWS account.
    /// </summary>
    /// <returns>The PasswordPolicy for the AWS account.</returns>
    public async Task<PasswordPolicy> GetAccountPasswordPolicyAsync()
    {
        var response = await _IAMService.GetAccountPasswordPolicyAsync(new GetAccountPasswordPolicyRequest());
        return response.PasswordPolicy;
    }


    /// <summary>
    /// Get information about an IAM policy.
    /// </summary>
    /// <param name="policyArn">The IAM policy to retrieve information for.</param>
    /// <returns>The IAM policy.</returns>
    public async Task<ManagedPolicy> GetPolicyAsync(string policyArn)
    {

        var response = await _IAMService.GetPolicyAsync(new GetPolicyRequest { PolicyArn = policyArn });
        return response.Policy;
    }


    /// <summary>
    /// Get information about an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to retrieve information
    /// for.</param>
    /// <returns>The IAM role that was retrieved.</returns>
    public async Task<Role> GetRoleAsync(string roleName)
    {
        var response = await _IAMService.GetRoleAsync(new GetRoleRequest
        {
            RoleName = roleName,
        });

        return response.Role;
    }


    /// <summary>
    /// Get information about an IAM user.
    /// </summary>
    /// <param name="userName">The username of the user.</param>
    /// <returns>An IAM user object.</returns>
    public async Task<User> GetUserAsync(string userName)
    {
        var response = await _IAMService.GetUserAsync(new GetUserRequest { UserName = userName });
        return response.User;
    }


    /// <summary>
    /// List the IAM role policies that are attached to an IAM role.
    /// </summary>
    /// <param name="roleName">The IAM role to list IAM policies for.</param>
    /// <returns>A list of the IAM policies attached to the IAM role.</returns>
    public async Task<List<AttachedPolicyType>> ListAttachedRolePoliciesAsync(string roleName)
    {
        var attachedPolicies = new List<AttachedPolicyType>();
        var attachedRolePoliciesPaginator = _IAMService.Paginators.ListAttachedRolePolicies(new ListAttachedRolePoliciesRequest { RoleName = roleName });

        await foreach (var response in attachedRolePoliciesPaginator.Responses)
        {
            attachedPolicies.AddRange(response.AttachedPolicies);
        }

        return attachedPolicies;
    }


    /// <summary>
    /// List IAM groups.
    /// </summary>
    /// <returns>A list of IAM groups.</returns>
    public async Task<List<Group>> ListGroupsAsync()
    {
        var groupsPaginator = _IAMService.Paginators.ListGroups(new ListGroupsRequest());
        var groups = new List<Group>();

        await foreach (var response in groupsPaginator.Responses)
        {
            groups.AddRange(response.Groups);
        }

        return groups;
    }


    /// <summary>
    /// List IAM policies.
    /// </summary>
    /// <returns>A list of the IAM policies.</returns>
    public async Task<List<ManagedPolicy>> ListPoliciesAsync()
    {
        var listPoliciesPaginator = _IAMService.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        return policies;
    }


    /// <summary>
    /// List IAM role policies.
    /// </summary>
    /// <param name="roleName">The IAM role for which to list IAM policies.</param>
    /// <returns>A list of IAM policy names.</returns>
    public async Task<List<string>> ListRolePoliciesAsync(string roleName)
    {
        var listRolePoliciesPaginator = _IAMService.Paginators.ListRolePolicies(new ListRolePoliciesRequest { RoleName = roleName });
        var policyNames = new List<string>();

        await foreach (var response in listRolePoliciesPaginator.Responses)
        {
            policyNames.AddRange(response.PolicyNames);
        }

        return policyNames;
    }


    /// <summary>
    /// List IAM roles.
    /// </summary>
    /// <returns>A list of IAM roles.</returns>
    public async Task<List<Role>> ListRolesAsync()
    {
        var listRolesPaginator = _IAMService.Paginators.ListRoles(new ListRolesRequest());
        var roles = new List<Role>();

        await foreach (var response in listRolesPaginator.Responses)
        {
            roles.AddRange(response.Roles);
        }

        return roles;
    }


    /// <summary>
    /// List SAML authentication providers.
    /// </summary>
    /// <returns>A list of SAML providers.</returns>
    public async Task<List<SAMLProviderListEntry>> ListSAMLProvidersAsync()
    {
        var response = await _IAMService.ListSAMLProvidersAsync(new ListSAMLProvidersRequest());
        return response.SAMLProviderList;
    }


    /// <summary>
    /// List IAM users.
    /// </summary>
    /// <returns>A list of IAM users.</returns>
    public async Task<List<User>> ListUsersAsync()
    {
        var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest());
        var users = new List<User>();

        await foreach (var response in listUsersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }


    /// <summary>
    /// Update the inline policy document embedded in a role.
    /// </summary>
    /// <param name="policyName">The name of the policy to embed.</param>
    /// <param name="roleName">The name of the role to update.</param>
    /// <param name="policyDocument">The policy document that defines the role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutRolePolicyAsync(string policyName, string roleName, string policyDocument)
    {
        var request = new PutRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutRolePolicyAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Add or update an inline policy document that is embedded in an IAM user.
    /// </summary>
    /// <param name="userName">The name of the IAM user.</param>
    /// <param name="policyName">The name of the IAM policy.</param>
    /// <param name="policyDocument">The policy document defining the IAM policy.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutUserPolicyAsync(string userName, string policyName, string policyDocument)
    {
        var request = new PutUserPolicyRequest
        {
            UserName = userName,
            PolicyName = policyName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutUserPolicyAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    /// <summary>
    /// Wait for a new access key to be ready to use.
    /// </summary>
    /// <param name="accessKeyId">The Id of the access key.</param>
    /// <returns>A boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitUntilAccessKeyIsReady(string accessKeyId)
    {
        var keyReady = false;

        do
        {
            try
            {
                var response = await _IAMService.GetAccessKeyLastUsedAsync(
                    new GetAccessKeyLastUsedRequest { AccessKeyId = accessKeyId });
                if (response.UserName is not null)
                {
                    keyReady = true;
                }
            }
            catch (NoSuchEntityException)
            {
                keyReady = false;
            }
        } while (!keyReady);

        return keyReady;
    }
}



using Microsoft.Extensions.Configuration;

namespace IAMBasics;

public class IAMBasics
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the AWS service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonIdentityManagementService>()
            .AddTransient<IAMWrapper>()
            .AddTransient<UIWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<IAMBasics>();


        IConfiguration configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        // Values needed for user, role, and policies.
        string userName = configuration["UserName"]!;
        string s3PolicyName = configuration["S3PolicyName"]!;
        string roleName = configuration["RoleName"]!;


        var iamWrapper = host.Services.GetRequiredService<IAMWrapper>();
        var uiWrapper = host.Services.GetRequiredService<UIWrapper>();

        uiWrapper.DisplayBasicsOverview();
        uiWrapper.PressEnter();

        // First create a user. By default, the new user has
        // no permissions.
        uiWrapper.DisplayTitle("Create User");
        Console.WriteLine($"Creating a new user with user name: {userName}.");
        var user = await iamWrapper.CreateUserAsync(userName);
        var userArn = user.Arn;

        Console.WriteLine($"Successfully created user: {userName} with ARN: {userArn}.");
        uiWrapper.WaitABit(15, "Now let's wait for the user to be ready for use.");

        // Define a role policy document that allows the new user
        // to assume the role.
        string assumeRolePolicyDocument = "{" +
          "\"Version\": \"2012-10-17\"," +
          "\"Statement\": [{" +
              "\"Effect\": \"Allow\"," +
              "\"Principal\": {" +
              $"	\"AWS\": \"{userArn}\"" +
              "}," +
              "\"Action\": \"sts:AssumeRole\"" +
          "}]" +
        "}";

        // Permissions to list all buckets.
        string policyDocument = "{" +
            "\"Version\": \"2012-10-17\"," +
            "	\"Statement\" : [{" +
                "	\"Action\" : [\"s3:ListAllMyBuckets\"]," +
                "	\"Effect\" : \"Allow\"," +
                "	\"Resource\" : \"*\"" +
            "}]" +
        "}";

        // Create an AccessKey for the user.
        uiWrapper.DisplayTitle("Create access key");
        Console.WriteLine("Now let's create an access key for the new user.");
        var accessKey = await iamWrapper.CreateAccessKeyAsync(userName);

        var accessKeyId = accessKey.AccessKeyId;
        var secretAccessKey = accessKey.SecretAccessKey;

        Console.WriteLine($"We have created the access key with Access key id: {accessKeyId}.");

        Console.WriteLine("Now let's wait until the IAM access key is ready to use.");
        var keyReady = await iamWrapper.WaitUntilAccessKeyIsReady(accessKeyId);

        // Now try listing the Amazon Simple Storage Service (Amazon S3)
        // buckets. This should fail at this point because the user doesn't
        // have permissions to perform this task.
        uiWrapper.DisplayTitle("Try to display Amazon S3 buckets");
        Console.WriteLine("Now let's try to display a list of the user's Amazon S3 buckets.");
        var s3Client1 = new AmazonS3Client(accessKeyId, secretAccessKey);
        var stsClient1 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        var s3Wrapper = new S3Wrapper(s3Client1, stsClient1);
        var buckets = await s3Wrapper.ListMyBucketsAsync();

        Console.WriteLine(buckets is null
            ? "As expected, the call to list the buckets has returned a null list."
            : "Something went wrong. This shouldn't have worked.");

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Create IAM role");
        Console.WriteLine($"Creating the role: {roleName}");

        // Creating an IAM role to allow listing the S3 buckets. A role name
        // is not case sensitive and must be unique to the account for which it
        // is created.
        var roleArn = await iamWrapper.CreateRoleAsync(roleName, assumeRolePolicyDocument);

        uiWrapper.PressEnter();

        // Create a policy with permissions to list S3 buckets.
        uiWrapper.DisplayTitle("Create IAM policy");
        Console.WriteLine($"Creating the policy: {s3PolicyName}");
        Console.WriteLine("with permissions to list the Amazon S3 buckets for the account.");
        var policy = await iamWrapper.CreatePolicyAsync(s3PolicyName, policyDocument);

        // Wait 15 seconds for the IAM policy to be available.
        uiWrapper.WaitABit(15, "Waiting for the policy to be available.");

        // Attach the policy to the role you created earlier.
        uiWrapper.DisplayTitle("Attach new IAM policy");
        Console.WriteLine("Now let's attach the policy to the role.");
        await iamWrapper.AttachRolePolicyAsync(policy.Arn, roleName);

        // Wait 15 seconds for the role to be updated.
        Console.WriteLine();
        uiWrapper.WaitABit(15, "Waiting for the policy to be attached.");

        // Use the AWS Security Token Service (AWS STS) to have the user
        // assume the role we created.
        var stsClient2 = new AmazonSecurityTokenServiceClient(accessKeyId, secretAccessKey);

        // Wait for the new credentials to become valid.
        uiWrapper.WaitABit(10, "Waiting for the credentials to be valid.");

        var assumedRoleCredentials = await s3Wrapper.AssumeS3RoleAsync("temporary-session", roleArn);

        // Try again to list the buckets using the client created with
        // the new user's credentials. This time, it should work.
        var s3Client2 = new AmazonS3Client(assumedRoleCredentials);

        s3Wrapper.UpdateClients(s3Client2, stsClient2);

        buckets = await s3Wrapper.ListMyBucketsAsync();

        uiWrapper.DisplayTitle("List Amazon S3 buckets");
        Console.WriteLine("This time we should have buckets to list.");
        if (buckets is not null)
        {
            buckets.ForEach(bucket =>
            {
                Console.WriteLine($"{bucket.BucketName} created: {bucket.CreationDate}");
            });
        }

        uiWrapper.PressEnter();

        // Now clean up all the resources used in the example.
        uiWrapper.DisplayTitle("Clean up resources");
        Console.WriteLine("Thank you for watching. The IAM Basics demo is complete.");
        Console.WriteLine("Please wait while we clean up the resources we created.");

        await iamWrapper.DetachRolePolicyAsync(policy.Arn, roleName);

        await iamWrapper.DeletePolicyAsync(policy.Arn);

        await iamWrapper.DeleteRoleAsync(roleName);

        await iamWrapper.DeleteAccessKeyAsync(accessKeyId, userName);

        await iamWrapper.DeleteUserAsync(userName);

        uiWrapper.PressEnter();

        Console.WriteLine("All done cleaning up our resources. Thank you for your patience.");
    }
}


namespace IamScenariosCommon;

using System.Net;

/// <summary>
/// A class to perform Amazon Simple Storage Service (Amazon S3) actions for
/// the IAM Basics scenario.
/// </summary>
public class S3Wrapper
{
    private IAmazonS3 _s3Service;
    private IAmazonSecurityTokenService _stsService;

    /// <summary>
    /// Constructor for the S3Wrapper class.
    /// </summary>
    /// <param name="s3Service">An Amazon S3 client object.</param>
    /// <param name="stsService">An AWS Security Token Service (AWS STS)
    /// client object.</param>
    public S3Wrapper(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }

    /// <summary>
    /// Assumes an AWS Identity and Access Management (IAM) role that allows
    /// Amazon S3 access for the current session.
    /// </summary>
    /// <param name="roleSession">A string representing the current session.</param>
    /// <param name="roleToAssume">The name of the IAM role to assume.</param>
    /// <returns>Credentials for the newly assumed IAM role.</returns>
    public async Task<Credentials> AssumeS3RoleAsync(string roleSession, string roleToAssume)
    {
        // Create the request to use with the AssumeRoleAsync call.
        var request = new AssumeRoleRequest()
        {
            RoleSessionName = roleSession,
            RoleArn = roleToAssume,
        };

        var response = await _stsService.AssumeRoleAsync(request);

        return response.Credentials;
    }


    /// <summary>
    /// Delete an S3 bucket.
    /// </summary>
    /// <param name="bucketName">Name of the S3 bucket to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteBucketAsync(string bucketName)
    {
        var result = await _s3Service.DeleteBucketAsync(new DeleteBucketRequest { BucketName = bucketName });
        return result.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// List the buckets that are owned by the user's account.
    /// </summary>
    /// <returns>Async Task.</returns>
    public async Task<List<S3Bucket>?> ListMyBucketsAsync()
    {
        try
        {
            // Get the list of buckets accessible by the new user.
            var response = await _s3Service.ListBucketsAsync();

            return response.Buckets;
        }
        catch (AmazonS3Exception ex)
        {
            // Something else went wrong. Display the error message.
            Console.WriteLine($"Error: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Create a new S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name for the new bucket.</param>
    /// <returns>A Boolean value indicating whether the action completed
    /// successfully.</returns>
    public async Task<bool> PutBucketAsync(string bucketName)
    {
        var response = await _s3Service.PutBucketAsync(new PutBucketRequest { BucketName = bucketName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Update the client objects with new client objects. This is available
    /// because the scenario uses the methods of this class without and then
    /// with the proper permissions to list S3 buckets.
    /// </summary>
    /// <param name="s3Service">The Amazon S3 client object.</param>
    /// <param name="stsService">The AWS STS client object.</param>
    public void UpdateClients(IAmazonS3 s3Service, IAmazonSecurityTokenService stsService)
    {
        _s3Service = s3Service;
        _stsService = stsService;
    }
}


namespace IamScenariosCommon;

public class UIWrapper
{
    public readonly string SepBar = new('-', Console.WindowWidth);

    /// <summary>
    /// Show information about the IAM Groups scenario.
    /// </summary>
    public void DisplayGroupsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to the IAM Groups Demo");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates an Amazon Identity and Access Management (IAM) group.");
        Console.WriteLine("\t2. Adds an IAM policy to the IAM group giving it full access to Amazon S3.");
        Console.WriteLine("\t3. Creates a new IAM user.");
        Console.WriteLine("\t4. Creates an IAM access key for the user.");
        Console.WriteLine("\t5. Adds the user to the IAM group.");
        Console.WriteLine("\t6. Lists the buckets on the account.");
        Console.WriteLine("\t7. Proves that the user has full Amazon S3 access by creating a bucket.");
        Console.WriteLine("\t8. List the buckets again to show the new bucket.");
        Console.WriteLine("\t9. Cleans up all the resources created.");
    }

    /// <summary>
    /// Show information about the IAM Basics scenario.
    /// </summary>
    public void DisplayBasicsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to IAM Basics");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates a user with no permissions.");
        Console.WriteLine("\t2. Creates a role and policy that grant s3:ListAllMyBuckets permission.");
        Console.WriteLine("\t3. Grants the user permission to assume the role.");
        Console.WriteLine("\t4. Creates an S3 client object as the user and tries to list buckets (this will fail).");
        Console.WriteLine("\t5. Gets temporary credentials by assuming the role.");
        Console.WriteLine("\t6. Creates a new S3 client object with the temporary credentials and lists the buckets (this will succeed).");
        Console.WriteLine("\t7. Deletes all the resources.");
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPress <Enter> to continue. ");
        _ = Console.ReadLine();
        Console.WriteLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter">The string to be centered.</param>
    /// <returns>The padded string.</returns>
    public string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title, and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(SepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(SepBar);
    }

    /// <summary>
    /// Display a countdown and wait for a number of seconds.
    /// </summary>
    /// <param name="numSeconds">The number of seconds to wait.</param>
    public void WaitABit(int numSeconds, string msg)
    {
        Console.WriteLine(msg);

        // Wait for the requested number of seconds.
        for (int i = numSeconds; i > 0; i--)
        {
            System.Threading.Thread.Sleep(1000);
            Console.Write($"{i}...");
        }

        PressEnter();
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_csharp_3_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Attach an IAM policy to a role.
    /// </summary>
    /// <param name="policyArn">The policy to attach.</param>
    /// <param name="roleName">The role that the policy will be attached to.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AttachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.AttachRolePolicyAsync(new AttachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AttachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/AttachRolePolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_csharp_3_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an IAM access key for a user.
    /// </summary>
    /// <param name="userName">The username for which to create the IAM access
    /// key.</param>
    /// <returns>The AccessKey.</returns>
    public async Task<AccessKey> CreateAccessKeyAsync(string userName)
    {
        var response = await _IAMService.CreateAccessKeyAsync(new CreateAccessKeyRequest
        {
            UserName = userName,
        });

        return response.AccessKey;

    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateAccessKey)」を参照してください。

### `CreateInstanceProfile`
<a name="iam_CreateInstanceProfile_csharp_3_topic"></a>

次のコード例は、`CreateInstanceProfile` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a policy, role, and profile that is associated with instances with a specified name.
    /// An instance's associated profile defines a role that is assumed by the
    /// instance.The role has attached policies that specify the AWS permissions granted to
    /// clients that run on the instance.
    /// </summary>
    /// <param name="policyName">Name to use for the policy.</param>
    /// <param name="roleName">Name to use for the role.</param>
    /// <param name="profileName">Name to use for the profile.</param>
    /// <param name="ssmOnlyPolicyFile">Path to a policy file for SSM.</param>
    /// <param name="awsManagedPolicies">AWS Managed policies to be attached to the role.</param>
    /// <returns>The Arn of the profile.</returns>
    public async Task<string> CreateInstanceProfileWithName(
        string policyName,
        string roleName,
        string profileName,
        string ssmOnlyPolicyFile,
        List<string>? awsManagedPolicies = null)
    {

        var assumeRoleDoc = "{" +
                                   "\"Version\": \"2012-10-17\"," +
                                   "\"Statement\": [{" +
                                        "\"Effect\": \"Allow\"," +
                                        "\"Principal\": {" +
                                        "\"Service\": [" +
                                            "\"ec2.amazonaws.com\"" +
                                        "]" +
                                        "}," +
                                   "\"Action\": \"sts:AssumeRole\"" +
                                   "}]" +
                               "}";

        var policyDocument = await File.ReadAllTextAsync(ssmOnlyPolicyFile);

        var policyArn = "";

        try
        {
            var createPolicyResult = await _amazonIam.CreatePolicyAsync(
                new CreatePolicyRequest
                {
                    PolicyName = policyName,
                    PolicyDocument = policyDocument
                });
            policyArn = createPolicyResult.Policy.Arn;
        }
        catch (EntityAlreadyExistsException)
        {
            // The policy already exists, so we look it up to get the Arn.
            var policiesPaginator = _amazonIam.Paginators.ListPolicies(
                new ListPoliciesRequest()
                {
                    Scope = PolicyScopeType.Local
                });
            // Get the entire list using the paginator.
            await foreach (var policy in policiesPaginator.Policies)
            {
                if (policy.PolicyName.Equals(policyName))
                {
                    policyArn = policy.Arn;
                }
            }

            if (policyArn == null)
            {
                throw new InvalidOperationException("Policy not found");
            }
        }

        try
        {
            await _amazonIam.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = assumeRoleDoc,
            });
            await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
            {
                RoleName = roleName,
                PolicyArn = policyArn
            });
            if (awsManagedPolicies != null)
            {
                foreach (var awsPolicy in awsManagedPolicies)
                {
                    await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
                    {
                        PolicyArn = $"arn:aws:iam::aws:policy/{awsPolicy}",
                        RoleName = roleName
                    });
                }
            }
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Role already exists.");
        }

        string profileArn = "";
        try
        {
            var profileCreateResponse = await _amazonIam.CreateInstanceProfileAsync(
                new CreateInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            // Allow time for the profile to be ready.
            profileArn = profileCreateResponse.InstanceProfile.Arn;
            Thread.Sleep(10000);
            await _amazonIam.AddRoleToInstanceProfileAsync(
                new AddRoleToInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });

        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Policy already exists.");
            var profileGetResponse = await _amazonIam.GetInstanceProfileAsync(
                new GetInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            profileArn = profileGetResponse.InstanceProfile.Arn;
        }
        return profileArn;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateInstanceProfile)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_csharp_3_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an IAM policy.
    /// </summary>
    /// <param name="policyName">The name to give the new IAM policy.</param>
    /// <param name="policyDocument">The policy document for the new policy.</param>
    /// <returns>The new IAM policy object.</returns>
    public async Task<ManagedPolicy> CreatePolicyAsync(string policyName, string policyDocument)
    {
        var response = await _IAMService.CreatePolicyAsync(new CreatePolicyRequest
        {
            PolicyDocument = policyDocument,
            PolicyName = policyName,
        });

        return response.Policy;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_csharp_3_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <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](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateRole)」を参照してください。**

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_csharp_3_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an IAM service-linked role.
    /// </summary>
    /// <param name="serviceName">The name of the AWS Service.</param>
    /// <param name="description">A description of the IAM service-linked role.</param>
    /// <returns>The IAM role that was created.</returns>
    public async Task<Role> CreateServiceLinkedRoleAsync(string serviceName, string description)
    {
        var request = new CreateServiceLinkedRoleRequest
        {
            AWSServiceName = serviceName,
            Description = description
        };

        var response = await _IAMService.CreateServiceLinkedRoleAsync(request);
        return response.Role;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateServiceLinkedRole)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_csharp_3_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an IAM user.
    /// </summary>
    /// <param name="userName">The username for the new IAM user.</param>
    /// <returns>The IAM user that was created.</returns>
    public async Task<User> CreateUserAsync(string userName)
    {
        var response = await _IAMService.CreateUserAsync(new CreateUserRequest { UserName = userName });
        return response.User;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_csharp_3_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an IAM user's access key.
    /// </summary>
    /// <param name="accessKeyId">The Id for the IAM access key.</param>
    /// <param name="userName">The username of the user that owns the IAM
    /// access key.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAccessKeyAsync(string accessKeyId, string userName)
    {
        var response = await _IAMService.DeleteAccessKeyAsync(new DeleteAccessKeyRequest
        {
            AccessKeyId = accessKeyId,
            UserName = userName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteAccessKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteAccessKey)」を参照してください。

### `DeleteInstanceProfile`
<a name="iam_DeleteInstanceProfile_csharp_3_topic"></a>

次のコード例は、`DeleteInstanceProfile` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService/AutoScalerActions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Detaches a role from an instance profile, detaches policies from the role,
    /// and deletes all the resources.
    /// </summary>
    /// <param name="profileName">The name of the profile to delete.</param>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteInstanceProfile(string profileName, string roleName)
    {
        try
        {
            await _amazonIam.RemoveRoleFromInstanceProfileAsync(
                new RemoveRoleFromInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });
            await _amazonIam.DeleteInstanceProfileAsync(
                new DeleteInstanceProfileRequest() { InstanceProfileName = profileName });
            var attachedPolicies = await _amazonIam.ListAttachedRolePoliciesAsync(
                new ListAttachedRolePoliciesRequest() { RoleName = roleName });
            foreach (var policy in attachedPolicies.AttachedPolicies)
            {
                await _amazonIam.DetachRolePolicyAsync(
                    new DetachRolePolicyRequest()
                    {
                        RoleName = roleName,
                        PolicyArn = policy.PolicyArn
                    });
                // Delete the custom policies only.
                if (!policy.PolicyArn.StartsWith("arn:aws:iam::aws"))
                {
                    await _amazonIam.DeletePolicyAsync(
                        new Amazon.IdentityManagement.Model.DeletePolicyRequest()
                        {
                            PolicyArn = policy.PolicyArn
                        });
                }
            }

            await _amazonIam.DeleteRoleAsync(
                new DeleteRoleRequest() { RoleName = roleName });
        }
        catch (NoSuchEntityException)
        {
            Console.WriteLine($"Instance profile {profileName} does not exist.");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteInstanceProfile)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_csharp_3_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an IAM policy.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the policy to
    /// delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeletePolicyAsync(string policyArn)
    {
        var response = await _IAMService.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeletePolicy)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_csharp_3_topic"></a>

次のコード例は、`DeleteRole` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRoleAsync(string roleName)
    {
        var response = await _IAMService.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRole)」を参照してください。

### `DeleteRolePolicy`
<a name="iam_DeleteRolePolicy_csharp_3_topic"></a>

次のコード例は、`DeleteRolePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an IAM role policy.
    /// </summary>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <param name="policyName">The name of the IAM role policy to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteRolePolicyAsync(string roleName, string policyName)
    {
        var response = await _IAMService.DeleteRolePolicyAsync(new DeleteRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteRolePolicy)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_csharp_3_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an IAM user.
    /// </summary>
    /// <param name="userName">The username of the IAM user to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserAsync(string userName)
    {
        var response = await _IAMService.DeleteUserAsync(new DeleteUserRequest { UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUser)」を参照してください。

### `DeleteUserPolicy`
<a name="iam_DeleteUserPolicy_csharp_3_topic"></a>

次のコード例は、`DeleteUserPolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an IAM user policy.
    /// </summary>
    /// <param name="policyName">The name of the IAM policy to delete.</param>
    /// <param name="userName">The username of the IAM user.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteUserPolicyAsync(string policyName, string userName)
    {
        var response = await _IAMService.DeleteUserPolicyAsync(new DeleteUserPolicyRequest { PolicyName = policyName, UserName = userName });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteUserPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteUserPolicy)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_csharp_3_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Detach an IAM policy from an IAM role.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param>
    /// <param name="roleName">The name of the IAM role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DetachRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _IAMService.DetachRolePolicyAsync(new DetachRolePolicyRequest
        {
            PolicyArn = policyArn,
            RoleName = roleName,
        });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DetachRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DetachRolePolicy)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_csharp_3_topic"></a>

次のコード例は、`GetAccountPasswordPolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Gets the IAM password policy for an AWS account.
    /// </summary>
    /// <returns>The PasswordPolicy for the AWS account.</returns>
    public async Task<PasswordPolicy> GetAccountPasswordPolicyAsync()
    {
        var response = await _IAMService.GetAccountPasswordPolicyAsync(new GetAccountPasswordPolicyRequest());
        return response.PasswordPolicy;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetAccountPasswordPolicy)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_csharp_3_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about an IAM policy.
    /// </summary>
    /// <param name="policyArn">The IAM policy to retrieve information for.</param>
    /// <returns>The IAM policy.</returns>
    public async Task<ManagedPolicy> GetPolicyAsync(string policyArn)
    {

        var response = await _IAMService.GetPolicyAsync(new GetPolicyRequest { PolicyArn = policyArn });
        return response.Policy;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetPolicy)」を参照してください。

### `GetRole`
<a name="iam_GetRole_csharp_3_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to retrieve information
    /// for.</param>
    /// <returns>The IAM role that was retrieved.</returns>
    public async Task<Role> GetRoleAsync(string roleName)
    {
        var response = await _IAMService.GetRoleAsync(new GetRoleRequest
        {
            RoleName = roleName,
        });

        return response.Role;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetRole)」を参照してください。

### `GetUser`
<a name="iam_GetUser_csharp_3_topic"></a>

次のコード例は、`GetUser` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about an IAM user.
    /// </summary>
    /// <param name="userName">The username of the user.</param>
    /// <returns>An IAM user object.</returns>
    public async Task<User> GetUserAsync(string userName)
    {
        var response = await _IAMService.GetUserAsync(new GetUserRequest { UserName = userName });
        return response.User;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetUser](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/GetUser)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_csharp_3_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List the IAM role policies that are attached to an IAM role.
    /// </summary>
    /// <param name="roleName">The IAM role to list IAM policies for.</param>
    /// <returns>A list of the IAM policies attached to the IAM role.</returns>
    public async Task<List<AttachedPolicyType>> ListAttachedRolePoliciesAsync(string roleName)
    {
        var attachedPolicies = new List<AttachedPolicyType>();
        var attachedRolePoliciesPaginator = _IAMService.Paginators.ListAttachedRolePolicies(new ListAttachedRolePoliciesRequest { RoleName = roleName });

        await foreach (var response in attachedRolePoliciesPaginator.Responses)
        {
            attachedPolicies.AddRange(response.AttachedPolicies);
        }

        return attachedPolicies;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListAttachedRolePolicies)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_csharp_3_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List IAM groups.
    /// </summary>
    /// <returns>A list of IAM groups.</returns>
    public async Task<List<Group>> ListGroupsAsync()
    {
        var groupsPaginator = _IAMService.Paginators.ListGroups(new ListGroupsRequest());
        var groups = new List<Group>();

        await foreach (var response in groupsPaginator.Responses)
        {
            groups.AddRange(response.Groups);
        }

        return groups;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListGroups)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_csharp_3_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List IAM policies.
    /// </summary>
    /// <returns>A list of the IAM policies.</returns>
    public async Task<List<ManagedPolicy>> ListPoliciesAsync()
    {
        var listPoliciesPaginator = _IAMService.Paginators.ListPolicies(new ListPoliciesRequest());
        var policies = new List<ManagedPolicy>();

        await foreach (var response in listPoliciesPaginator.Responses)
        {
            policies.AddRange(response.Policies);
        }

        return policies;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListPolicies)」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_csharp_3_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List IAM role policies.
    /// </summary>
    /// <param name="roleName">The IAM role for which to list IAM policies.</param>
    /// <returns>A list of IAM policy names.</returns>
    public async Task<List<string>> ListRolePoliciesAsync(string roleName)
    {
        var listRolePoliciesPaginator = _IAMService.Paginators.ListRolePolicies(new ListRolePoliciesRequest { RoleName = roleName });
        var policyNames = new List<string>();

        await foreach (var response in listRolePoliciesPaginator.Responses)
        {
            policyNames.AddRange(response.PolicyNames);
        }

        return policyNames;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListRolePolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListRolePolicies)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_csharp_3_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List IAM roles.
    /// </summary>
    /// <returns>A list of IAM roles.</returns>
    public async Task<List<Role>> ListRolesAsync()
    {
        var listRolesPaginator = _IAMService.Paginators.ListRoles(new ListRolesRequest());
        var roles = new List<Role>();

        await foreach (var response in listRolesPaginator.Responses)
        {
            roles.AddRange(response.Roles);
        }

        return roles;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListRoles](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListRoles)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_csharp_3_topic"></a>

次のコード例は、`ListSAMLProviders` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List SAML authentication providers.
    /// </summary>
    /// <returns>A list of SAML providers.</returns>
    public async Task<List<SAMLProviderListEntry>> ListSAMLProvidersAsync()
    {
        var response = await _IAMService.ListSAMLProvidersAsync(new ListSAMLProvidersRequest());
        return response.SAMLProviderList;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListSAMLProviders](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListSAMLProviders)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_csharp_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List IAM users.
    /// </summary>
    /// <returns>A list of IAM users.</returns>
    public async Task<List<User>> ListUsersAsync()
    {
        var listUsersPaginator = _IAMService.Paginators.ListUsers(new ListUsersRequest());
        var users = new List<User>();

        await foreach (var response in listUsersPaginator.Responses)
        {
            users.AddRange(response.Users);
        }

        return users;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/ListUsers)」を参照してください。

### `PutRolePolicy`
<a name="iam_PutRolePolicy_csharp_3_topic"></a>

次のコード例は、`PutRolePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/IAM#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Update the inline policy document embedded in a role.
    /// </summary>
    /// <param name="policyName">The name of the policy to embed.</param>
    /// <param name="roleName">The name of the role to update.</param>
    /// <param name="policyDocument">The policy document that defines the role.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> PutRolePolicyAsync(string policyName, string roleName, string policyDocument)
    {
        var request = new PutRolePolicyRequest
        {
            PolicyName = policyName,
            RoleName = roleName,
            PolicyDocument = policyDocument
        };

        var response = await _IAMService.PutRolePolicyAsync(request);
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[PutRolePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/PutRolePolicy)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_csharp_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/ResilientService#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
    static async Task Main(string[] args)
    {
        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();


        // Set up dependency injection for the AWS services.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonIdentityManagementService>()
                    .AddAWSService<IAmazonDynamoDB>()
                    .AddAWSService<IAmazonElasticLoadBalancingV2>()
                    .AddAWSService<IAmazonSimpleSystemsManagement>()
                    .AddAWSService<IAmazonAutoScaling>()
                    .AddAWSService<IAmazonEC2>()
                    .AddTransient<AutoScalerWrapper>()
                    .AddTransient<ElasticLoadBalancerWrapper>()
                    .AddTransient<SmParameterWrapper>()
                    .AddTransient<Recommendations>()
                    .AddSingleton<IConfiguration>(_configuration)
            )
            .Build();

        ServicesSetup(host);
        ResourcesSetup();

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Welcome to the Resilient Architecture Example Scenario.");
            Console.WriteLine(new string('-', 80));
            await Deploy(true);

            Console.WriteLine("Now let's begin the scenario.");
            Console.WriteLine(new string('-', 80));
            await Demo(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Finally, let's clean up our resources.");
            Console.WriteLine(new string('-', 80));

            await DestroyResources(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Resilient Architecture Example Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            await DestroyResources(true);
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Setup any common resources, also used for integration testing.
    /// </summary>
    public static void ResourcesSetup()
    {
        _httpClient = new HttpClient();
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _elasticLoadBalancerWrapper = host.Services.GetRequiredService<ElasticLoadBalancerWrapper>();
        _iamClient = host.Services.GetRequiredService<IAmazonIdentityManagementService>();
        _recommendations = host.Services.GetRequiredService<Recommendations>();
        _autoScalerWrapper = host.Services.GetRequiredService<AutoScalerWrapper>();
        _smParameterWrapper = host.Services.GetRequiredService<SmParameterWrapper>();
    }

    /// <summary>
    /// Deploy necessary resources for the scenario.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> Deploy(bool interactive)
    {
        var protocol = "HTTP";
        var port = 80;
        var sshPort = 22;

        Console.WriteLine(
            "\nFor this demo, we'll use the AWS SDK for .NET to create several AWS resources\n" +
            "to set up a load-balanced web service endpoint and explore some ways to make it resilient\n" +
            "against various kinds of failures.\n\n" +
            "Some of the resources create by this demo are:\n");

        Console.WriteLine(
            "\t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.");
        Console.WriteLine(
            "\t* An EC2 launch template that defines EC2 instances that each contain a Python web server.");
        Console.WriteLine(
            "\t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.");
        Console.WriteLine(
            "\t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.");
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to start deploying resources.");
        if (interactive)
            Console.ReadLine();

        // Create and populate the DynamoDB table.
        var databaseTableName = _configuration["databaseName"];
        var recommendationsPath = Path.Join(_configuration["resourcePath"],
            "recommendations_objects.json");
        Console.WriteLine($"Creating and populating a DynamoDB table named {databaseTableName}.");
        await _recommendations.CreateDatabaseWithName(databaseTableName);
        await _recommendations.PopulateDatabase(databaseTableName, recommendationsPath);
        Console.WriteLine(new string('-', 80));

        // Create the EC2 Launch Template.

        Console.WriteLine(
            $"Creating an EC2 launch template that runs 'server_startup_script.sh' when an instance starts.\n"
            + "\nThis script starts a Python web server defined in the `server.py` script. The web server\n"
            + "listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.\n"
            + "For demo purposes, this server is run as the root user. In production, the best practice is to\n"
            + "run a web server, such as Apache, with least-privileged credentials.");
        Console.WriteLine(
            "\nThe template also defines an IAM policy that each instance uses to assume a role that grants\n"
            + "permissions to access the DynamoDB recommendation table and Systems Manager parameters\n"
            + "that control the flow of the demo.");

        var startupScriptPath = Path.Join(_configuration["resourcePath"],
            "server_startup_script.sh");
        var instancePolicyPath = Path.Join(_configuration["resourcePath"],
            "instance_policy.json");
        await _autoScalerWrapper.CreateTemplate(startupScriptPath, instancePolicyPath);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different\n"
            + "Availability Zone.\n");
        var zones = await _autoScalerWrapper.DescribeAvailabilityZones();
        await _autoScalerWrapper.CreateGroupOfSize(3, _autoScalerWrapper.GroupName, zones);
        Console.WriteLine(new string('-', 80));

        Console.WriteLine(
            "At this point, you have EC2 instances created. Once each instance starts, it listens for\n"
            + "HTTP requests. You can see these instances in the console or continue with the demo.\n");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue.");
        if (interactive)
            Console.ReadLine();

        Console.WriteLine("Creating variables that control the flow of the demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine(
            "\nCreating an Elastic Load Balancing target group and load balancer. The target group\n"
            + "defines how the load balancer connects to instances. The load balancer provides a\n"
            + "single endpoint where clients connect and dispatches requests to instances in the group.");

        var defaultVpc = await _autoScalerWrapper.GetDefaultVpc();
        var subnets = await _autoScalerWrapper.GetAllVpcSubnetsForZones(defaultVpc.VpcId, zones);
        var subnetIds = subnets.Select(s => s.SubnetId).ToList();
        var targetGroup = await _elasticLoadBalancerWrapper.CreateTargetGroupOnVpc(_elasticLoadBalancerWrapper.TargetGroupName, protocol, port, defaultVpc.VpcId);

        await _elasticLoadBalancerWrapper.CreateLoadBalancerAndListener(_elasticLoadBalancerWrapper.LoadBalancerName, subnetIds, targetGroup);
        await _autoScalerWrapper.AttachLoadBalancerToGroup(_autoScalerWrapper.GroupName, targetGroup.TargetGroupArn);
        Console.WriteLine("\nVerifying access to the load balancer endpoint...");
        var endPoint = await _elasticLoadBalancerWrapper.GetEndpointForLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
        var loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);

        if (!loadBalancerAccess)
        {
            Console.WriteLine("\nCouldn't connect to the load balancer, verifying that the port is open...");

            var ipString = await _httpClient.GetStringAsync("https://checkip.amazonaws.com");
            ipString = ipString.Trim();

            var defaultSecurityGroup = await _autoScalerWrapper.GetDefaultSecurityGroupForVpc(defaultVpc);
            var portIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, port, ipString);
            var sshPortIsOpen = _autoScalerWrapper.VerifyInboundPortForGroup(defaultSecurityGroup, sshPort, ipString);

            if (!portIsOpen)
            {
                Console.WriteLine(
                    "\nFor this example to work, the default security group for your default VPC must\n"
                    + "allows access from this computer. You can either add it automatically from this\n"
                    + "example or add it yourself using the AWS Management Console.\n");

                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound traffic from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, port, ipString);
                }
            }

            if (!sshPortIsOpen)
            {
                if (!interactive || GetYesNoResponse(
                        "Do you want to add a rule to the security group to allow inbound SSH traffic for debugging from your computer's IP address?"))
                {
                    await _autoScalerWrapper.OpenInboundPort(defaultSecurityGroup.GroupId, sshPort, ipString);
                }
            }
            loadBalancerAccess = await _elasticLoadBalancerWrapper.VerifyLoadBalancerEndpoint(endPoint);
        }

        if (loadBalancerAccess)
        {
            Console.WriteLine("Your load balancer is ready. You can access it by browsing to:");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        else
        {
            Console.WriteLine(
                "\nCouldn't get a successful response from the load balancer endpoint. Troubleshoot by\n"
                + "manually verifying that your VPC and security group are configured correctly and that\n"
                + "you can successfully make a GET request to the load balancer endpoint:\n");
            Console.WriteLine($"\thttp://{endPoint}\n");
        }
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you're ready to continue with the demo.");
        if (interactive)
            Console.ReadLine();
        return true;
    }

    /// <summary>
    /// Demonstrate the steps of the scenario.
    /// </summary>
    /// <param name="interactive">True to run as an interactive scenario.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> Demo(bool interactive)
    {
        var ssmOnlyPolicy = Path.Join(_configuration["resourcePath"],
            "ssm_only_policy.json");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Resetting parameters to starting values for demo.");
        await _smParameterWrapper.Reset();

        Console.WriteLine("\nThis part of the demonstration shows how to toggle different parts of the system\n" +
                          "to create situations where the web service fails, and shows how using a resilient\n" +
                          "architecture can keep the web service running in spite of these failures.");
        Console.WriteLine(new string('-', 88));
        Console.WriteLine("At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine($"The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.\n" +
                          $"The table name is contained in a Systems Manager parameter named '{_smParameterWrapper.TableParameter}'.\n" +
                          $"To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");
        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as\n" +
                          "healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Instead of failing when the recommendation service fails, the web service can return a static response.");
        Console.WriteLine("While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.FailureResponseParameter, "static");

        Console.WriteLine("\nNow, sending a GET request to the load balancer endpoint returns a static response.");
        Console.WriteLine("The service still reports as healthy because health checks are still shallow.");
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("Let's reinstate the recommendation service.\n");
        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, _smParameterWrapper.TableName);
        Console.WriteLine(
            "\nLet's also substitute bad credentials for one of the instances in the target group so that it can't\n" +
            "access the DynamoDB recommendation table.\n"
        );
        await _autoScalerWrapper.CreateInstanceProfileWithName(
            _autoScalerWrapper.BadCredsPolicyName,
            _autoScalerWrapper.BadCredsRoleName,
            _autoScalerWrapper.BadCredsProfileName,
            ssmOnlyPolicy,
            new List<string> { "AmazonSSMManagedInstanceCore" }
        );
        var instances = await _autoScalerWrapper.GetInstancesByGroupName(_autoScalerWrapper.GroupName);
        var badInstanceId = instances.First();
        var instanceProfile = await _autoScalerWrapper.GetInstanceProfile(badInstanceId);
        Console.WriteLine(
            $"Replacing the profile for instance {badInstanceId} with a profile that contains\n" +
            "bad credentials...\n"
        );
        await _autoScalerWrapper.ReplaceInstanceProfile(
            badInstanceId,
            _autoScalerWrapper.BadCredsProfileName,
            instanceProfile.AssociationId
        );
        Console.WriteLine(
            "Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,\n" +
            "depending on which instance is selected by the load balancer.\n"
        );
        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nLet's implement a deep health check. For this demo, a deep health check tests whether");
        Console.WriteLine("the web service can access the DynamoDB table that it depends on for recommendations. Note that");
        Console.WriteLine("the deep health check is only for ELB routing and not for Auto Scaling instance health.");
        Console.WriteLine("This kind of deep health check is not recommended for Auto Scaling instance health, because it");
        Console.WriteLine("risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.");

        Console.WriteLine("\nBy implementing deep health checks, the load balancer can detect when one of the instances is failing");
        Console.WriteLine("and take that instance out of rotation.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.HealthCheckParameter, "deep");

        Console.WriteLine($"\nNow, checking target health indicates that the instance with bad credentials ({badInstanceId})");
        Console.WriteLine("is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy");
        Console.WriteLine("instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because");
        Console.WriteLine("the load balancer takes unhealthy instances out of its rotation.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nBecause the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy");
        Console.WriteLine("instance is to terminate it and let the auto scaler start a new instance to replace it.");

        await _autoScalerWrapper.TryTerminateInstanceById(badInstanceId);

        Console.WriteLine($"\nEven while the instance is terminating and the new instance is starting, sending a GET");
        Console.WriteLine("request to the web service continues to get a successful recommendation response because");
        Console.WriteLine("starts and reports as healthy, it is included in the load balancing rotation.");
        Console.WriteLine("Note that terminating and replacing an instance typically takes several minutes, during which time you");
        Console.WriteLine("can see the changing health check status until the new instance is running and healthy.");

        if (interactive)
            await DemoActionChoices();

        Console.WriteLine("\nIf the recommendation service fails now, deep health checks mean all instances report as unhealthy.");

        await _smParameterWrapper.PutParameterByName(_smParameterWrapper.TableParameter, "this-is-not-a-table");

        Console.WriteLine($"\nWhen all instances are unhealthy, the load balancer continues to route requests even to");
        Console.WriteLine("unhealthy instances, allowing them to fail open and return a static response rather than fail");
        Console.WriteLine("closed and report failure to the customer.");

        if (interactive)
            await DemoActionChoices();
        await _smParameterWrapper.Reset();

        Console.WriteLine(new string('-', 80));
        return true;
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="interactive">True to ask the user for cleanup.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> DestroyResources(bool interactive)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine(
            "To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources\n" +
            "that were created for this demo."
        );

        if (!interactive || GetYesNoResponse("Do you want to clean up all demo resources? (y/n) "))
        {
            await _elasticLoadBalancerWrapper.DeleteLoadBalancerByName(_elasticLoadBalancerWrapper.LoadBalancerName);
            await _elasticLoadBalancerWrapper.DeleteTargetGroupByName(_elasticLoadBalancerWrapper.TargetGroupName);
            await _autoScalerWrapper.TerminateAndDeleteAutoScalingGroupWithName(_autoScalerWrapper.GroupName);
            await _autoScalerWrapper.DeleteKeyPairByName(_autoScalerWrapper.KeyPairName);
            await _autoScalerWrapper.DeleteTemplateByName(_autoScalerWrapper.LaunchTemplateName);
            await _autoScalerWrapper.DeleteInstanceProfile(
                _autoScalerWrapper.BadCredsProfileName,
                _autoScalerWrapper.BadCredsRoleName
            );
            await _recommendations.DestroyDatabaseByName(_recommendations.TableName);
        }
        else
        {
            Console.WriteLine(
                "Ok, we'll leave the resources intact.\n" +
                "Don't forget to delete them when you're done with them or you might incur unexpected charges."
            );
        }

        Console.WriteLine(new string('-', 80));
        return true;
    }
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Amazon EC2 Auto Scaling and EC2 management methods.
/// </summary>
public class AutoScalerWrapper
{
    private readonly IAmazonAutoScaling _amazonAutoScaling;
    private readonly IAmazonEC2 _amazonEc2;
    private readonly IAmazonSimpleSystemsManagement _amazonSsm;
    private readonly IAmazonIdentityManagementService _amazonIam;
    private readonly ILogger<AutoScalerWrapper> _logger;

    private readonly string _instanceType = "";
    private readonly string _amiParam = "";
    private readonly string _launchTemplateName = "";
    private readonly string _groupName = "";
    private readonly string _instancePolicyName = "";
    private readonly string _instanceRoleName = "";
    private readonly string _instanceProfileName = "";
    private readonly string _badCredsProfileName = "";
    private readonly string _badCredsRoleName = "";
    private readonly string _badCredsPolicyName = "";
    private readonly string _keyPairName = "";

    public string GroupName => _groupName;
    public string KeyPairName => _keyPairName;
    public string LaunchTemplateName => _launchTemplateName;
    public string InstancePolicyName => _instancePolicyName;
    public string BadCredsProfileName => _badCredsProfileName;
    public string BadCredsRoleName => _badCredsRoleName;
    public string BadCredsPolicyName => _badCredsPolicyName;

    /// <summary>
    /// Constructor for the AutoScalerWrapper.
    /// </summary>
    /// <param name="amazonAutoScaling">The injected AutoScaling client.</param>
    /// <param name="amazonEc2">The injected EC2 client.</param>
    /// <param name="amazonIam">The injected IAM client.</param>
    /// <param name="amazonSsm">The injected SSM client.</param>
    public AutoScalerWrapper(
        IAmazonAutoScaling amazonAutoScaling,
        IAmazonEC2 amazonEc2,
        IAmazonSimpleSystemsManagement amazonSsm,
        IAmazonIdentityManagementService amazonIam,
        IConfiguration configuration,
        ILogger<AutoScalerWrapper> logger)
    {
        _amazonAutoScaling = amazonAutoScaling;
        _amazonEc2 = amazonEc2;
        _amazonSsm = amazonSsm;
        _amazonIam = amazonIam;
        _logger = logger;

        var prefix = configuration["resourcePrefix"];
        _instanceType = configuration["instanceType"];
        _amiParam = configuration["amiParam"];

        _launchTemplateName = prefix + "-template";
        _groupName = prefix + "-group";
        _instancePolicyName = prefix + "-pol";
        _instanceRoleName = prefix + "-role";
        _instanceProfileName = prefix + "-prof";
        _badCredsPolicyName = prefix + "-bc-pol";
        _badCredsRoleName = prefix + "-bc-role";
        _badCredsProfileName = prefix + "-bc-prof";
        _keyPairName = prefix + "-key-pair";
    }

    /// <summary>
    /// Create a policy, role, and profile that is associated with instances with a specified name.
    /// An instance's associated profile defines a role that is assumed by the
    /// instance.The role has attached policies that specify the AWS permissions granted to
    /// clients that run on the instance.
    /// </summary>
    /// <param name="policyName">Name to use for the policy.</param>
    /// <param name="roleName">Name to use for the role.</param>
    /// <param name="profileName">Name to use for the profile.</param>
    /// <param name="ssmOnlyPolicyFile">Path to a policy file for SSM.</param>
    /// <param name="awsManagedPolicies">AWS Managed policies to be attached to the role.</param>
    /// <returns>The Arn of the profile.</returns>
    public async Task<string> CreateInstanceProfileWithName(
        string policyName,
        string roleName,
        string profileName,
        string ssmOnlyPolicyFile,
        List<string>? awsManagedPolicies = null)
    {

        var assumeRoleDoc = "{" +
                                   "\"Version\": \"2012-10-17\"," +
                                   "\"Statement\": [{" +
                                        "\"Effect\": \"Allow\"," +
                                        "\"Principal\": {" +
                                        "\"Service\": [" +
                                            "\"ec2.amazonaws.com\"" +
                                        "]" +
                                        "}," +
                                   "\"Action\": \"sts:AssumeRole\"" +
                                   "}]" +
                               "}";

        var policyDocument = await File.ReadAllTextAsync(ssmOnlyPolicyFile);

        var policyArn = "";

        try
        {
            var createPolicyResult = await _amazonIam.CreatePolicyAsync(
                new CreatePolicyRequest
                {
                    PolicyName = policyName,
                    PolicyDocument = policyDocument
                });
            policyArn = createPolicyResult.Policy.Arn;
        }
        catch (EntityAlreadyExistsException)
        {
            // The policy already exists, so we look it up to get the Arn.
            var policiesPaginator = _amazonIam.Paginators.ListPolicies(
                new ListPoliciesRequest()
                {
                    Scope = PolicyScopeType.Local
                });
            // Get the entire list using the paginator.
            await foreach (var policy in policiesPaginator.Policies)
            {
                if (policy.PolicyName.Equals(policyName))
                {
                    policyArn = policy.Arn;
                }
            }

            if (policyArn == null)
            {
                throw new InvalidOperationException("Policy not found");
            }
        }

        try
        {
            await _amazonIam.CreateRoleAsync(new CreateRoleRequest()
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = assumeRoleDoc,
            });
            await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
            {
                RoleName = roleName,
                PolicyArn = policyArn
            });
            if (awsManagedPolicies != null)
            {
                foreach (var awsPolicy in awsManagedPolicies)
                {
                    await _amazonIam.AttachRolePolicyAsync(new AttachRolePolicyRequest()
                    {
                        PolicyArn = $"arn:aws:iam::aws:policy/{awsPolicy}",
                        RoleName = roleName
                    });
                }
            }
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Role already exists.");
        }

        string profileArn = "";
        try
        {
            var profileCreateResponse = await _amazonIam.CreateInstanceProfileAsync(
                new CreateInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            // Allow time for the profile to be ready.
            profileArn = profileCreateResponse.InstanceProfile.Arn;
            Thread.Sleep(10000);
            await _amazonIam.AddRoleToInstanceProfileAsync(
                new AddRoleToInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });

        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine("Policy already exists.");
            var profileGetResponse = await _amazonIam.GetInstanceProfileAsync(
                new GetInstanceProfileRequest()
                {
                    InstanceProfileName = profileName
                });
            profileArn = profileGetResponse.InstanceProfile.Arn;
        }
        return profileArn;
    }

    /// <summary>
    /// Create a new key pair and save the file.
    /// </summary>
    /// <param name="newKeyPairName">The name of the new key pair.</param>
    /// <returns>Async task.</returns>
    public async Task CreateKeyPair(string newKeyPairName)
    {
        try
        {
            var keyResponse = await _amazonEc2.CreateKeyPairAsync(
                new CreateKeyPairRequest() { KeyName = newKeyPairName });
            await File.WriteAllTextAsync($"{newKeyPairName}.pem",
                keyResponse.KeyPair.KeyMaterial);
            Console.WriteLine($"Created key pair {newKeyPairName}.");
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine("Key pair already exists.");
        }
    }

    /// <summary>
    /// Delete the key pair and file by name.
    /// </summary>
    /// <param name="deleteKeyPairName">The key pair to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteKeyPairByName(string deleteKeyPairName)
    {
        try
        {
            await _amazonEc2.DeleteKeyPairAsync(
                new DeleteKeyPairRequest() { KeyName = deleteKeyPairName });
            File.Delete($"{deleteKeyPairName}.pem");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine($"Key pair {deleteKeyPairName} not found.");
        }
    }

    /// <summary>
    /// Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling.
    /// The launch template specifies a Bash script in its user data field that runs after
    /// the instance is started. This script installs the Python packages and starts a Python
    /// web server on the instance.
    /// </summary>
    /// <param name="startupScriptPath">The path to a Bash script file that is run.</param>
    /// <param name="instancePolicyPath">The path to a permissions policy to create and attach to the profile.</param>
    /// <returns>The template object.</returns>
    public async Task<Amazon.EC2.Model.LaunchTemplate> CreateTemplate(string startupScriptPath, string instancePolicyPath)
    {
        try
        {
            await CreateKeyPair(_keyPairName);
            await CreateInstanceProfileWithName(_instancePolicyName, _instanceRoleName,
                _instanceProfileName, instancePolicyPath);

            var startServerText = await File.ReadAllTextAsync(startupScriptPath);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(startServerText);

            var amiLatest = await _amazonSsm.GetParameterAsync(
                new GetParameterRequest() { Name = _amiParam });
            var amiId = amiLatest.Parameter.Value;
            var launchTemplateResponse = await _amazonEc2.CreateLaunchTemplateAsync(
                new CreateLaunchTemplateRequest()
                {
                    LaunchTemplateName = _launchTemplateName,
                    LaunchTemplateData = new RequestLaunchTemplateData()
                    {
                        InstanceType = _instanceType,
                        ImageId = amiId,
                        IamInstanceProfile =
                            new
                                LaunchTemplateIamInstanceProfileSpecificationRequest()
                            {
                                Name = _instanceProfileName
                            },
                        KeyName = _keyPairName,
                        UserData = System.Convert.ToBase64String(plainTextBytes)
                    }
                });
            return launchTemplateResponse.LaunchTemplate;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.AlreadyExistsException")
            {
                _logger.LogError($"Could not create the template, the name {_launchTemplateName} already exists. " +
                                 $"Please try again with a unique name.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get a list of Availability Zones in the AWS Region of the Amazon EC2 Client.
    /// </summary>
    /// <returns>A list of availability zones.</returns>
    public async Task<List<string>> DescribeAvailabilityZones()
    {
        try
        {
            var zoneResponse = await _amazonEc2.DescribeAvailabilityZonesAsync(
                new DescribeAvailabilityZonesRequest());
            return zoneResponse.AvailabilityZones.Select(z => z.ZoneName).ToList();
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            _logger.LogError($"An Amazon EC2 error occurred while listing availability zones.: {ec2Exception.Message}");
            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while listing availability zones.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Create an EC2 Auto Scaling group of a specified size and name.
    /// </summary>
    /// <param name="groupSize">The size for the group.</param>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="availabilityZones">The availability zones for the group.</param>
    /// <returns>Async task.</returns>
    public async Task CreateGroupOfSize(int groupSize, string groupName, List<string> availabilityZones)
    {
        try
        {
            await _amazonAutoScaling.CreateAutoScalingGroupAsync(
                new CreateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    AvailabilityZones = availabilityZones,
                    LaunchTemplate =
                        new Amazon.AutoScaling.Model.LaunchTemplateSpecification()
                        {
                            LaunchTemplateName = _launchTemplateName,
                            Version = "$Default"
                        },
                    MaxSize = groupSize,
                    MinSize = groupSize
                });
            Console.WriteLine($"Created EC2 Auto Scaling group {groupName} with size {groupSize}.");
        }
        catch (EntityAlreadyExistsException)
        {
            Console.WriteLine($"EC2 Auto Scaling group {groupName} already exists.");
        }
    }

    /// <summary>
    /// Get the default VPC for the account.
    /// </summary>
    /// <returns>The default VPC object.</returns>
    public async Task<Vpc> GetDefaultVpc()
    {
        try
        {
            var vpcResponse = await _amazonEc2.DescribeVpcsAsync(
                new DescribeVpcsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("is-default", new List<string>() { "true" })
                    }
                });
            return vpcResponse.Vpcs[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "UnauthorizedOperation")
            {
                _logger.LogError(ec2Exception, $"You do not have the necessary permissions to describe VPCs.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the vpcs.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get all the subnets for a Vpc in a set of availability zones.
    /// </summary>
    /// <param name="vpcId">The Id of the Vpc.</param>
    /// <param name="availabilityZones">The list of availability zones.</param>
    /// <returns>The collection of subnet objects.</returns>
    public async Task<List<Subnet>> GetAllVpcSubnetsForZones(string vpcId, List<string> availabilityZones)
    {
        try
        {
            var subnets = new List<Subnet>();
            var subnetPaginator = _amazonEc2.Paginators.DescribeSubnets(
                new DescribeSubnetsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("vpc-id", new List<string>() { vpcId }),
                        new("availability-zone", availabilityZones),
                        new("default-for-az", new List<string>() { "true" })
                    }
                });

            // Get the entire list using the paginator.
            await foreach (var subnet in subnetPaginator.Subnets)
            {
                subnets.Add(subnet);
            }

            return subnets;
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidVpcID.NotFound")
            {
                _logger.LogError(ec2Exception, $"The specified VPC ID {vpcId} does not exist.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while describing the subnets.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Delete a launch template by name.
    /// </summary>
    /// <param name="templateName">The name of the template to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTemplateByName(string templateName)
    {
        try
        {
            await _amazonEc2.DeleteLaunchTemplateAsync(
                new DeleteLaunchTemplateRequest()
                {
                    LaunchTemplateName = templateName
                });
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidLaunchTemplateName.NotFoundException")
            {
                _logger.LogError(
                    $"Could not delete the template, the name {_launchTemplateName} was not found.");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while deleting the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Detaches a role from an instance profile, detaches policies from the role,
    /// and deletes all the resources.
    /// </summary>
    /// <param name="profileName">The name of the profile to delete.</param>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteInstanceProfile(string profileName, string roleName)
    {
        try
        {
            await _amazonIam.RemoveRoleFromInstanceProfileAsync(
                new RemoveRoleFromInstanceProfileRequest()
                {
                    InstanceProfileName = profileName,
                    RoleName = roleName
                });
            await _amazonIam.DeleteInstanceProfileAsync(
                new DeleteInstanceProfileRequest() { InstanceProfileName = profileName });
            var attachedPolicies = await _amazonIam.ListAttachedRolePoliciesAsync(
                new ListAttachedRolePoliciesRequest() { RoleName = roleName });
            foreach (var policy in attachedPolicies.AttachedPolicies)
            {
                await _amazonIam.DetachRolePolicyAsync(
                    new DetachRolePolicyRequest()
                    {
                        RoleName = roleName,
                        PolicyArn = policy.PolicyArn
                    });
                // Delete the custom policies only.
                if (!policy.PolicyArn.StartsWith("arn:aws:iam::aws"))
                {
                    await _amazonIam.DeletePolicyAsync(
                        new Amazon.IdentityManagement.Model.DeletePolicyRequest()
                        {
                            PolicyArn = policy.PolicyArn
                        });
                }
            }

            await _amazonIam.DeleteRoleAsync(
                new DeleteRoleRequest() { RoleName = roleName });
        }
        catch (NoSuchEntityException)
        {
            Console.WriteLine($"Instance profile {profileName} does not exist.");
        }
    }

    /// <summary>
    /// Gets data about the instances in an EC2 Auto Scaling group by its group name.
    /// </summary>
    /// <param name="group">The name of the auto scaling group.</param>
    /// <returns>A collection of instance Ids.</returns>
    public async Task<IEnumerable<string>> GetInstancesByGroupName(string group)
    {
        var instanceResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { group }
            });
        var instanceIds = instanceResponse.AutoScalingGroups.SelectMany(
            g => g.Instances.Select(i => i.InstanceId));
        return instanceIds;
    }

    /// <summary>
    /// Get the instance profile association data for an instance.
    /// </summary>
    /// <param name="instanceId">The Id of the instance.</param>
    /// <returns>Instance profile associations data.</returns>
    public async Task<IamInstanceProfileAssociation> GetInstanceProfile(string instanceId)
    {
        try
        {
            var response = await _amazonEc2.DescribeIamInstanceProfileAssociationsAsync(
                new DescribeIamInstanceProfileAssociationsRequest()
                {
                    Filters = new List<Amazon.EC2.Model.Filter>()
                    {
                        new("instance-id", new List<string>() { instanceId })
                    },
                });
            return response.IamInstanceProfileAssociations[0];
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while creating the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Replace the profile associated with a running instance. After the profile is replaced, the instance
    /// is rebooted to ensure that it uses the new profile. When the instance is ready, Systems Manager is
    /// used to restart the Python web server.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to update.</param>
    /// <param name="credsProfileName">The name of the new profile to associate with the specified instance.</param>
    /// <param name="associationId">The Id of the existing profile association for the instance.</param>
    /// <returns>Async task.</returns>
    public async Task ReplaceInstanceProfile(string instanceId, string credsProfileName, string associationId)
    {
        try
        {
            await _amazonEc2.ReplaceIamInstanceProfileAssociationAsync(
                new ReplaceIamInstanceProfileAssociationRequest()
                {
                    AssociationId = associationId,
                    IamInstanceProfile = new IamInstanceProfileSpecification()
                    {
                        Name = credsProfileName
                    }
                });
            // Allow time before resetting.
            Thread.Sleep(25000);

            await _amazonEc2.RebootInstancesAsync(
                new RebootInstancesRequest(new List<string>() { instanceId }));
            Thread.Sleep(25000);
            var instanceReady = false;
            var retries = 5;
            while (retries-- > 0 && !instanceReady)
            {
                var instancesPaginator =
                    _amazonSsm.Paginators.DescribeInstanceInformation(
                        new DescribeInstanceInformationRequest());
                // Get the entire list using the paginator.
                await foreach (var instance in instancesPaginator.InstanceInformationList)
                {
                    instanceReady = instance.InstanceId == instanceId;
                    if (instanceReady)
                    {
                        break;
                    }
                }
            }
            Console.WriteLine("Waiting for instance to be running.");
            await WaitForInstanceState(instanceId, InstanceStateName.Running);
            Console.WriteLine("Instance ready.");
            Console.WriteLine($"Sending restart command to instance {instanceId}");
            await _amazonSsm.SendCommandAsync(
                new SendCommandRequest()
                {
                    InstanceIds = new List<string>() { instanceId },
                    DocumentName = "AWS-RunShellScript",
                    Parameters = new Dictionary<string, List<string>>()
                    {
                        {
                            "commands",
                            new List<string>() { "cd / && sudo python3 server.py 80" }
                        }
                    }
                });
            Console.WriteLine($"Restarted the web server on instance {instanceId}");
        }
        catch (AmazonEC2Exception ec2Exception)
        {
            if (ec2Exception.ErrorCode == "InvalidInstanceID.NotFound")
            {
                _logger.LogError(ec2Exception, $"Instance {instanceId} not found");
            }

            throw;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while replacing the template.: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Try to terminate an instance by its Id.
    /// </summary>
    /// <param name="instanceId">The Id of the instance to terminate.</param>
    /// <returns>Async task.</returns>
    public async Task TryTerminateInstanceById(string instanceId)
    {
        var stopping = false;
        Console.WriteLine($"Stopping {instanceId}...");
        while (!stopping)
        {
            try
            {
                await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(
                    new TerminateInstanceInAutoScalingGroupRequest()
                    {
                        InstanceId = instanceId,
                        ShouldDecrementDesiredCapacity = false
                    });
                stopping = true;
            }
            catch (ScalingActivityInProgressException)
            {
                Console.WriteLine($"Scaling activity in progress for {instanceId}. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Tries to delete the EC2 Auto Scaling group. If the group is in use or in progress,
    /// waits and retries until the group is successfully deleted.
    /// </summary>
    /// <param name="groupName">The name of the group to try to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TryDeleteGroupByName(string groupName)
    {
        var stopped = false;
        while (!stopped)
        {
            try
            {
                await _amazonAutoScaling.DeleteAutoScalingGroupAsync(
                    new DeleteAutoScalingGroupRequest()
                    {
                        AutoScalingGroupName = groupName
                    });
                stopped = true;
            }
            catch (Exception e)
                when ((e is ScalingActivityInProgressException)
                      || (e is Amazon.AutoScaling.Model.ResourceInUseException))
            {
                Console.WriteLine($"Some instances are still running. Waiting...");
                Thread.Sleep(10000);
            }
        }
    }

    /// <summary>
    /// Terminate instances and delete the Auto Scaling group by name.
    /// </summary>
    /// <param name="groupName">The name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task TerminateAndDeleteAutoScalingGroupWithName(string groupName)
    {
        var describeGroupsResponse = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(
            new DescribeAutoScalingGroupsRequest()
            {
                AutoScalingGroupNames = new List<string>() { groupName }
            });
        if (describeGroupsResponse.AutoScalingGroups.Any())
        {
            // Update the size to 0.
            await _amazonAutoScaling.UpdateAutoScalingGroupAsync(
                new UpdateAutoScalingGroupRequest()
                {
                    AutoScalingGroupName = groupName,
                    MinSize = 0
                });
            var group = describeGroupsResponse.AutoScalingGroups[0];
            foreach (var instance in group.Instances)
            {
                await TryTerminateInstanceById(instance.InstanceId);
            }

            await TryDeleteGroupByName(groupName);
        }
        else
        {
            Console.WriteLine($"No groups found with name {groupName}.");
        }
    }


    /// <summary>
    /// Get the default security group for a specified Vpc.
    /// </summary>
    /// <param name="vpc">The Vpc to search.</param>
    /// <returns>The default security group.</returns>
    public async Task<SecurityGroup> GetDefaultSecurityGroupForVpc(Vpc vpc)
    {
        var groupResponse = await _amazonEc2.DescribeSecurityGroupsAsync(
            new DescribeSecurityGroupsRequest()
            {
                Filters = new List<Amazon.EC2.Model.Filter>()
                {
                    new ("group-name", new List<string>() { "default" }),
                    new ("vpc-id", new List<string>() { vpc.VpcId })
                }
            });
        return groupResponse.SecurityGroups[0];
    }

    /// <summary>
    /// Verify the default security group of a Vpc allows ingress from the calling computer.
    /// This can be done by allowing ingress from this computer's IP address.
    /// In some situations, such as connecting from a corporate network, you must instead specify
    /// a prefix list Id. You can also temporarily open the port to any IP address while running this example.
    /// If you do, be sure to remove public access when you're done.
    /// </summary>
    /// <param name="vpc">The group to check.</param>
    /// <param name="port">The port to verify.</param>
    /// <param name="ipAddress">This computer's IP address.</param>
    /// <returns>True if the ip address is allowed on the group.</returns>
    public bool VerifyInboundPortForGroup(SecurityGroup group, int port, string ipAddress)
    {
        var portIsOpen = false;
        foreach (var ipPermission in group.IpPermissions)
        {
            if (ipPermission.FromPort == port)
            {
                foreach (var ipRange in ipPermission.Ipv4Ranges)
                {
                    var cidr = ipRange.CidrIp;
                    if (cidr.StartsWith(ipAddress) || cidr == "0.0.0.0/0")
                    {
                        portIsOpen = true;
                    }
                }

                if (ipPermission.PrefixListIds.Any())
                {
                    portIsOpen = true;
                }

                if (!portIsOpen)
                {
                    Console.WriteLine("The inbound rule does not appear to be open to either this computer's IP\n" +
                                      "address, to all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                }
                else
                {
                    break;
                }
            }
        }

        return portIsOpen;
    }

    /// <summary>
    /// Add an ingress rule to the specified security group that allows access on the
    /// specified port from the specified IP address.
    /// </summary>
    /// <param name="groupId">The Id of the security group to modify.</param>
    /// <param name="port">The port to open.</param>
    /// <param name="ipAddress">The IP address to allow access.</param>
    /// <returns>Async task.</returns>
    public async Task OpenInboundPort(string groupId, int port, string ipAddress)
    {
        await _amazonEc2.AuthorizeSecurityGroupIngressAsync(
            new AuthorizeSecurityGroupIngressRequest()
            {
                GroupId = groupId,
                IpPermissions = new List<IpPermission>()
                {
                    new IpPermission()
                    {
                        FromPort = port,
                        ToPort = port,
                        IpProtocol = "tcp",
                        Ipv4Ranges = new List<IpRange>()
                        {
                            new IpRange() { CidrIp = $"{ipAddress}/32" }
                        }
                    }
                }
            });
    }

    /// <summary>
    /// Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
    /// The
    /// </summary>
    /// <param name="autoScalingGroupName">The name of the Auto Scaling group.</param>
    /// <param name="targetGroupArn">The Arn for the target group.</param>
    /// <returns>Async task.</returns>
    public async Task AttachLoadBalancerToGroup(string autoScalingGroupName, string targetGroupArn)
    {
        await _amazonAutoScaling.AttachLoadBalancerTargetGroupsAsync(
            new AttachLoadBalancerTargetGroupsRequest()
            {
                AutoScalingGroupName = autoScalingGroupName,
                TargetGroupARNs = new List<string>() { targetGroupArn }
            });
    }

    /// <summary>
    /// Wait until an EC2 instance is in a specified state.
    /// </summary>
    /// <param name="instanceId">The instance Id.</param>
    /// <param name="stateName">The state to wait for.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> WaitForInstanceState(string instanceId, InstanceStateName stateName)
    {
        var request = new DescribeInstancesRequest
        {
            InstanceIds = new List<string> { instanceId }
        };

        // Wait until the instance is in the specified state.
        var hasState = false;
        do
        {
            // Wait 5 seconds.
            Thread.Sleep(5000);

            // Check for the desired state.
            var response = await _amazonEc2.DescribeInstancesAsync(request);
            var instance = response.Reservations[0].Instances[0];
            hasState = instance.State.Name == stateName;
            Console.Write(". ");
        } while (!hasState);

        return hasState;
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Elastic Load Balancer actions.
/// </summary>
public class ElasticLoadBalancerWrapper
{
    private readonly IAmazonElasticLoadBalancingV2 _amazonElasticLoadBalancingV2;
    private string? _endpoint = null;
    private readonly string _targetGroupName = "";
    private readonly string _loadBalancerName = "";
    HttpClient _httpClient = new();

    public string TargetGroupName => _targetGroupName;
    public string LoadBalancerName => _loadBalancerName;

    /// <summary>
    /// Constructor for the Elastic Load Balancer wrapper.
    /// </summary>
    /// <param name="amazonElasticLoadBalancingV2">The injected load balancing v2 client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public ElasticLoadBalancerWrapper(
        IAmazonElasticLoadBalancingV2 amazonElasticLoadBalancingV2,
        IConfiguration configuration)
    {
        _amazonElasticLoadBalancingV2 = amazonElasticLoadBalancingV2;
        var prefix = configuration["resourcePrefix"];
        _targetGroupName = prefix + "-tg";
        _loadBalancerName = prefix + "-lb";
    }

    /// <summary>
    /// Get the HTTP Endpoint of a load balancer by its name.
    /// </summary>
    /// <param name="loadBalancerName">The name of the load balancer.</param>
    /// <returns>The HTTP endpoint.</returns>
    public async Task<string> GetEndpointForLoadBalancerByName(string loadBalancerName)
    {
        if (_endpoint == null)
        {
            var endpointResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { loadBalancerName }
                    });
            _endpoint = endpointResponse.LoadBalancers[0].DNSName;
        }

        return _endpoint;
    }

    /// <summary>
    /// Return the GET response for an endpoint as text.
    /// </summary>
    /// <param name="endpoint">The endpoint for the request.</param>
    /// <returns>The request response.</returns>
    public async Task<string> GetEndPointResponse(string endpoint)
    {
        var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
        var textResponse = await endpointResponse.Content.ReadAsStringAsync();
        return textResponse!;
    }

    /// <summary>
    /// Get the target health for a group by name.
    /// </summary>
    /// <param name="groupName">The name of the group.</param>
    /// <returns>The collection of health descriptions.</returns>
    public async Task<List<TargetHealthDescription>> CheckTargetHealthForGroup(string groupName)
    {
        List<TargetHealthDescription> result = null!;
        try
        {
            var groupResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                    new DescribeTargetGroupsRequest()
                    {
                        Names = new List<string>() { groupName }
                    });
            var healthResponse =
                await _amazonElasticLoadBalancingV2.DescribeTargetHealthAsync(
                    new DescribeTargetHealthRequest()
                    {
                        TargetGroupArn = groupResponse.TargetGroups[0].TargetGroupArn
                    });
            ;
            result = healthResponse.TargetHealthDescriptions;
        }
        catch (TargetGroupNotFoundException)
        {
            Console.WriteLine($"Target group {groupName} not found.");
        }
        return result;
    }

    /// <summary>
    /// Create an Elastic Load Balancing target group. The target group specifies how the load balancer forwards
    /// requests to instances in the group and how instance health is checked.
    ///
    /// To speed up this demo, the health check is configured with shortened times and lower thresholds. In production,
    /// you might want to decrease the sensitivity of your health checks to avoid unwanted failures.
    /// </summary>
    /// <param name="groupName">The name for the group.</param>
    /// <param name="protocol">The protocol, such as HTTP.</param>
    /// <param name="port">The port to use to forward requests, such as 80.</param>
    /// <param name="vpcId">The Id of the Vpc in which the load balancer exists.</param>
    /// <returns>The new TargetGroup object.</returns>
    public async Task<TargetGroup> CreateTargetGroupOnVpc(string groupName, ProtocolEnum protocol, int port, string vpcId)
    {
        var createResponse = await _amazonElasticLoadBalancingV2.CreateTargetGroupAsync(
            new CreateTargetGroupRequest()
            {
                Name = groupName,
                Protocol = protocol,
                Port = port,
                HealthCheckPath = "/healthcheck",
                HealthCheckIntervalSeconds = 10,
                HealthCheckTimeoutSeconds = 5,
                HealthyThresholdCount = 2,
                UnhealthyThresholdCount = 2,
                VpcId = vpcId
            });
        var targetGroup = createResponse.TargetGroups[0];
        return targetGroup;
    }

    /// <summary>
    /// Create an Elastic Load Balancing load balancer that uses the specified subnets
    /// and forwards requests to the specified target group.
    /// </summary>
    /// <param name="name">The name for the new load balancer.</param>
    /// <param name="subnetIds">Subnets for the load balancer.</param>
    /// <param name="targetGroup">Target group for forwarded requests.</param>
    /// <returns>The new LoadBalancer object.</returns>
    public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup)
    {
        var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync(
            new CreateLoadBalancerRequest()
            {
                Name = name,
                Subnets = subnetIds
            });
        var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn;

        // Wait for load balancer to be available.
        var loadBalancerReady = false;
        while (!loadBalancerReady)
        {
            try
            {
                var describeResponse =
                    await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                        new DescribeLoadBalancersRequest()
                        {
                            Names = new List<string>() { name }
                        });

                var loadBalancerState = describeResponse.LoadBalancers[0].State.Code;

                loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active;
            }
            catch (LoadBalancerNotFoundException)
            {
                loadBalancerReady = false;
            }
            Thread.Sleep(10000);
        }
        // Create the listener.
        await _amazonElasticLoadBalancingV2.CreateListenerAsync(
            new CreateListenerRequest()
            {
                LoadBalancerArn = loadBalancerArn,
                Protocol = targetGroup.Protocol,
                Port = targetGroup.Port,
                DefaultActions = new List<Action>()
                {
                    new Action()
                    {
                        Type = ActionTypeEnum.Forward,
                        TargetGroupArn = targetGroup.TargetGroupArn
                    }
                }
            });
        return createLbResponse.LoadBalancers[0];
    }

    /// <summary>
    /// Verify this computer can successfully send a GET request to the
    /// load balancer endpoint.
    /// </summary>
    /// <param name="endpoint">The endpoint to check.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> VerifyLoadBalancerEndpoint(string endpoint)
    {
        var success = false;
        var retries = 3;
        while (!success && retries > 0)
        {
            try
            {
                var endpointResponse = await _httpClient.GetAsync($"http://{endpoint}");
                Console.WriteLine($"Response: {endpointResponse.StatusCode}.");

                if (endpointResponse.IsSuccessStatusCode)
                {
                    success = true;
                }
                else
                {
                    retries = 0;
                }
            }
            catch (HttpRequestException)
            {
                Console.WriteLine("Connection error, retrying...");
                retries--;
                Thread.Sleep(10000);
            }
        }

        return success;
    }

    /// <summary>
    /// Delete a load balancer by its specified name.
    /// </summary>
    /// <param name="name">The name of the load balancer to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteLoadBalancerByName(string name)
    {
        try
        {
            var describeLoadBalancerResponse =
                await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync(
                    new DescribeLoadBalancersRequest()
                    {
                        Names = new List<string>() { name }
                    });
            var lbArn = describeLoadBalancerResponse.LoadBalancers[0].LoadBalancerArn;
            await _amazonElasticLoadBalancingV2.DeleteLoadBalancerAsync(
                new DeleteLoadBalancerRequest()
                {
                    LoadBalancerArn = lbArn
                }
            );
        }
        catch (LoadBalancerNotFoundException)
        {
            Console.WriteLine($"Load balancer {name} not found.");
        }
    }

    /// <summary>
    /// Delete a TargetGroup by its specified name.
    /// </summary>
    /// <param name="groupName">Name of the group to delete.</param>
    /// <returns>Async task.</returns>
    public async Task DeleteTargetGroupByName(string groupName)
    {
        var done = false;
        while (!done)
        {
            try
            {
                var groupResponse =
                    await _amazonElasticLoadBalancingV2.DescribeTargetGroupsAsync(
                        new DescribeTargetGroupsRequest()
                        {
                            Names = new List<string>() { groupName }
                        });

                var targetArn = groupResponse.TargetGroups[0].TargetGroupArn;
                await _amazonElasticLoadBalancingV2.DeleteTargetGroupAsync(
                    new DeleteTargetGroupRequest() { TargetGroupArn = targetArn });
                Console.WriteLine($"Deleted load balancing target group {groupName}.");
                done = true;
            }
            catch (TargetGroupNotFoundException)
            {
                Console.WriteLine(
                    $"Target group {groupName} not found, could not delete.");
                done = true;
            }
            catch (ResourceInUseException)
            {
                Console.WriteLine("Target group not yet released, waiting...");
                Thread.Sleep(10000);
            }
        }
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
/// <summary>
/// Encapsulates a DynamoDB table to use as a service that recommends books, movies, and songs.
/// </summary>
public class Recommendations
{
    private readonly IAmazonDynamoDB _amazonDynamoDb;
    private readonly DynamoDBContext _context;
    private readonly string _tableName;

    public string TableName => _tableName;

    /// <summary>
    /// Constructor for the Recommendations service.
    /// </summary>
    /// <param name="amazonDynamoDb">The injected DynamoDb client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public Recommendations(IAmazonDynamoDB amazonDynamoDb, IConfiguration configuration)
    {
        _amazonDynamoDb = amazonDynamoDb;
        _context = new DynamoDBContext(_amazonDynamoDb);
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Create the DynamoDb table with a specified name.
    /// </summary>
    /// <param name="tableName">The name for the table.</param>
    /// <returns>True when ready.</returns>
    public async Task<bool> CreateDatabaseWithName(string tableName)
    {
        try
        {
            Console.Write($"Creating table {tableName}...");
            var createRequest = new CreateTableRequest()
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                    {
                        new AttributeDefinition()
                        {
                            AttributeName = "MediaType",
                            AttributeType = ScalarAttributeType.S
                        },
                        new AttributeDefinition()
                        {
                            AttributeName = "ItemId",
                            AttributeType = ScalarAttributeType.N
                        }
                    },
                KeySchema = new List<KeySchemaElement>()
                    {
                        new KeySchemaElement()
                        {
                            AttributeName = "MediaType",
                            KeyType = KeyType.HASH
                        },
                        new KeySchemaElement()
                        {
                            AttributeName = "ItemId",
                            KeyType = KeyType.RANGE
                        }
                    },
                ProvisionedThroughput = new ProvisionedThroughput()
                {
                    ReadCapacityUnits = 5,
                    WriteCapacityUnits = 5
                }
            };
            await _amazonDynamoDb.CreateTableAsync(createRequest);

            // Wait until the table is ACTIVE and then report success.
            Console.Write("\nWaiting for table to become active...");

            var request = new DescribeTableRequest
            {
                TableName = tableName
            };

            TableStatus status;
            do
            {
                Thread.Sleep(2000);

                var describeTableResponse = await _amazonDynamoDb.DescribeTableAsync(request);
                status = describeTableResponse.Table.TableStatus;

                Console.Write(".");
            }
            while (status != "ACTIVE");

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException)
        {
            Console.WriteLine($"Table {tableName} already exists.");
            return false;
        }
    }

    /// <summary>
    /// Populate the database table with data from a specified path.
    /// </summary>
    /// <param name="databaseTableName">The name of the table.</param>
    /// <param name="recommendationsPath">The path of the recommendations data.</param>
    /// <returns>Async task.</returns>
    public async Task PopulateDatabase(string databaseTableName, string recommendationsPath)
    {
        var recommendationsText = await File.ReadAllTextAsync(recommendationsPath);
        var records =
            JsonSerializer.Deserialize<RecommendationModel[]>(recommendationsText);
        var batchWrite = _context.CreateBatchWrite<RecommendationModel>();

        foreach (var record in records!)
        {
            batchWrite.AddPutItem(record);
        }

        await batchWrite.ExecuteAsync();
    }

    /// <summary>
    /// Delete the recommendation table by name.
    /// </summary>
    /// <param name="tableName">The name of the recommendation table.</param>
    /// <returns>Async task.</returns>
    public async Task DestroyDatabaseByName(string tableName)
    {
        try
        {
            await _amazonDynamoDb.DeleteTableAsync(
                new DeleteTableRequest() { TableName = tableName });
            Console.WriteLine($"Table {tableName} was deleted.");
        }
        catch (ResourceNotFoundException)
        {
            Console.WriteLine($"Table {tableName} not found");
        }
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
/// <summary>
/// Encapsulates Systems Manager parameter operations. This example uses these parameters
/// to drive the demonstration of resilient architecture, such as failure of a dependency or
/// how the service responds to a health check.
/// </summary>
public class SmParameterWrapper
{
    private readonly IAmazonSimpleSystemsManagement _amazonSimpleSystemsManagement;

    private readonly string _tableParameter = "doc-example-resilient-architecture-table";
    private readonly string _failureResponseParameter = "doc-example-resilient-architecture-failure-response";
    private readonly string _healthCheckParameter = "doc-example-resilient-architecture-health-check";
    private readonly string _tableName = "";

    public string TableParameter => _tableParameter;
    public string TableName => _tableName;
    public string HealthCheckParameter => _healthCheckParameter;
    public string FailureResponseParameter => _failureResponseParameter;

    /// <summary>
    /// Constructor for the SmParameterWrapper.
    /// </summary>
    /// <param name="amazonSimpleSystemsManagement">The injected Simple Systems Management client.</param>
    /// <param name="configuration">The injected configuration.</param>
    public SmParameterWrapper(IAmazonSimpleSystemsManagement amazonSimpleSystemsManagement, IConfiguration configuration)
    {
        _amazonSimpleSystemsManagement = amazonSimpleSystemsManagement;
        _tableName = configuration["databaseName"]!;
    }

    /// <summary>
    /// Reset the Systems Manager parameters to starting values for the demo.
    /// </summary>
    /// <returns>Async task.</returns>
    public async Task Reset()
    {
        await this.PutParameterByName(_tableParameter, _tableName);
        await this.PutParameterByName(_failureResponseParameter, "none");
        await this.PutParameterByName(_healthCheckParameter, "shallow");
    }

    /// <summary>
    /// Set the value of a named Systems Manager parameter.
    /// </summary>
    /// <param name="name">The name of the parameter.</param>
    /// <param name="value">The value to set.</param>
    /// <returns>Async task.</returns>
    public async Task PutParameterByName(string name, string value)
    {
        await _amazonSimpleSystemsManagement.PutParameterAsync(
            new PutParameterRequest() { Name = name, Value = value, Overwrite = true });
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/DotNetSDKV3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/DotNetSDKV3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/DotNetSDKV3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# を使用した Amazon Keyspaces の例 SDK for .NET
<a name="csharp_3_keyspaces_code_examples"></a>

次のコード例は、Amazon Keyspaces AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Keyspaces
<a name="keyspaces_Hello_csharp_3_topic"></a>

次のコード例は、Amazon Keyspaces の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
namespace KeyspacesActions;

public class HelloKeyspaces
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon Keyspaces (for Apache Cassandra).
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonKeyspaces>()
                .AddTransient<KeyspacesWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<HelloKeyspaces>();

        var keyspacesClient = host.Services.GetRequiredService<IAmazonKeyspaces>();
        var keyspacesWrapper = new KeyspacesWrapper(keyspacesClient);

        Console.WriteLine("Hello, Amazon Keyspaces! Let's list your keyspaces:");
        await keyspacesWrapper.ListKeyspaces();
    }
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListKeyspaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/ListKeyspaces)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="keyspaces_Scenario_GetStartedKeyspaces_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キースペースとテーブルを作成する。テーブルスキーマにはムービーデータが保存され、ポイントインタイムリカバリが有効になっています。
+ SigV4 認証による安全な TLS 接続を使用してキースペースに接続します。
+ テーブルに対してクエリを実行します。ムービーデータを追加、取得、更新します。
+ テーブルを更新する。視聴したムービーを追跡する列を追加します。
+ テーブルを以前の状態に戻し、リソースをクリーンアップします。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
global using System.Security.Cryptography.X509Certificates;
global using Amazon.Keyspaces;
global using Amazon.Keyspaces.Model;
global using KeyspacesActions;
global using KeyspacesScenario;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;
global using Newtonsoft.Json;


namespace KeyspacesBasics;

/// <summary>
/// Amazon Keyspaces (for Apache Cassandra) scenario. Shows some of the basic
/// actions performed with Amazon Keyspaces.
/// </summary>
public class KeyspacesBasics
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonKeyspaces>()
            .AddTransient<KeyspacesWrapper>()
            .AddTransient<CassandraWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<KeyspacesBasics>();

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        var keyspacesWrapper = host.Services.GetRequiredService<KeyspacesWrapper>();
        var uiMethods = new UiMethods();

        var keyspaceName = configuration["KeyspaceName"];
        var tableName = configuration["TableName"];

        bool success; // Used to track the results of some operations.

        uiMethods.DisplayOverview();
        uiMethods.PressEnter();

        // Create the keyspace.
        var keyspaceArn = await keyspacesWrapper.CreateKeyspace(keyspaceName);

        // Wait for the keyspace to be available. GetKeyspace results in a
        // resource not found error until it is ready for use.
        try
        {
            var getKeyspaceArn = "";
            Console.Write($"Created {keyspaceName}. Waiting for it to become available. ");
            do
            {
                getKeyspaceArn = await keyspacesWrapper.GetKeyspace(keyspaceName);
                Console.Write(". ");
            } while (getKeyspaceArn != keyspaceArn);
        }
        catch (ResourceNotFoundException)
        {
            Console.WriteLine("Waiting for keyspace to be created.");
        }

        Console.WriteLine($"\nThe keyspace {keyspaceName} is ready for use.");

        uiMethods.PressEnter();

        // Create the table.
        // First define the schema.
        var allColumns = new List<ColumnDefinition>
        {
            new ColumnDefinition { Name = "title", Type = "text" },
            new ColumnDefinition { Name = "year", Type = "int" },
            new ColumnDefinition { Name = "release_date", Type = "timestamp" },
            new ColumnDefinition { Name = "plot", Type = "text" },
        };

        var partitionKeys = new List<PartitionKey>
        {
            new PartitionKey { Name = "year", },
            new PartitionKey { Name = "title" },
        };

        var tableSchema = new SchemaDefinition
        {
            AllColumns = allColumns,
            PartitionKeys = partitionKeys,
        };

        var tableArn = await keyspacesWrapper.CreateTable(keyspaceName, tableSchema, tableName);

        // Wait for the table to be active.
        try
        {
            var resp = new GetTableResponse();
            Console.Write("Waiting for the new table to be active. ");
            do
            {
                try
                {
                    resp = await keyspacesWrapper.GetTable(keyspaceName, tableName);
                    Console.Write(".");
                }
                catch (ResourceNotFoundException)
                {
                    Console.Write(".");
                }
            } while (resp.Status != TableStatus.ACTIVE);

            // Display the table's schema.
            Console.WriteLine($"\nTable {tableName} has been created in {keyspaceName}");
            Console.WriteLine("Let's take a look at the schema.");
            uiMethods.DisplayTitle("All columns");
            resp.SchemaDefinition.AllColumns.ForEach(column =>
            {
                Console.WriteLine($"{column.Name,-40}\t{column.Type,-20}");
            });

            uiMethods.DisplayTitle("Cluster keys");
            resp.SchemaDefinition.ClusteringKeys.ForEach(clusterKey =>
            {
                Console.WriteLine($"{clusterKey.Name,-40}\t{clusterKey.OrderBy,-20}");
            });

            uiMethods.DisplayTitle("Partition keys");
            resp.SchemaDefinition.PartitionKeys.ForEach(partitionKey =>
            {
                Console.WriteLine($"{partitionKey.Name}");
            });

            uiMethods.PressEnter();
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }

        // Access Apache Cassandra using the Cassandra drive for C#.
        var cassandraWrapper = host.Services.GetRequiredService<CassandraWrapper>();
        var movieFilePath = configuration["MovieFile"];

        Console.WriteLine("Let's add some movies to the table we created.");
        var inserted = await cassandraWrapper.InsertIntoMovieTable(keyspaceName, tableName, movieFilePath);

        uiMethods.PressEnter();

        Console.WriteLine("Added the following movies to the table:");
        var rows = await cassandraWrapper.GetMovies(keyspaceName, tableName);
        uiMethods.DisplayTitle("All Movies");

        foreach (var row in rows)
        {
            var title = row.GetValue<string>("title");
            var year = row.GetValue<int>("year");
            var plot = row.GetValue<string>("plot");
            var release_date = row.GetValue<DateTime>("release_date");
            Console.WriteLine($"{release_date}\t{title}\t{year}\n{plot}");
            Console.WriteLine(uiMethods.SepBar);
        }

        // Update the table schema
        uiMethods.DisplayTitle("Update table schema");
        Console.WriteLine("Now we will update the table to add a boolean field called watched.");

        // First save the current time as a UTC Date so the original
        // table can be restored later.
        var timeChanged = DateTime.UtcNow;

        // Now update the schema.
        var resourceArn = await keyspacesWrapper.UpdateTable(keyspaceName, tableName);
        uiMethods.PressEnter();

        Console.WriteLine("Now let's mark some of the movies as watched.");

        // Pick some files to mark as watched.
        var movieToWatch = rows[2].GetValue<string>("title");
        var watchedMovieYear = rows[2].GetValue<int>("year");
        var changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear);

        movieToWatch = rows[6].GetValue<string>("title");
        watchedMovieYear = rows[6].GetValue<int>("year");
        changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear);

        movieToWatch = rows[9].GetValue<string>("title");
        watchedMovieYear = rows[9].GetValue<int>("year");
        changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear);

        movieToWatch = rows[10].GetValue<string>("title");
        watchedMovieYear = rows[10].GetValue<int>("year");
        changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear);

        movieToWatch = rows[13].GetValue<string>("title");
        watchedMovieYear = rows[13].GetValue<int>("year");
        changedRows = await cassandraWrapper.MarkMovieAsWatched(keyspaceName, tableName, movieToWatch, watchedMovieYear);

        uiMethods.DisplayTitle("Watched movies");
        Console.WriteLine("These movies have been marked as watched:");
        rows = await cassandraWrapper.GetWatchedMovies(keyspaceName, tableName);
        foreach (var row in rows)
        {
            var title = row.GetValue<string>("title");
            var year = row.GetValue<int>("year");
            Console.WriteLine($"{title,-40}\t{year,8}");
        }
        uiMethods.PressEnter();

        Console.WriteLine("We can restore the table to its previous state but that can take up to 20 minutes to complete.");
        string answer;
        do
        {
            Console.WriteLine("Do you want to restore the table? (y/n)");
            answer = Console.ReadLine();
        } while (answer.ToLower() != "y" && answer.ToLower() != "n");

        if (answer == "y")
        {
            var restoredTableName = $"{tableName}_restored";
            var restoredTableArn = await keyspacesWrapper.RestoreTable(
                keyspaceName,
                tableName,
                restoredTableName,
                timeChanged);
            // Loop and call GetTable until the table is gone. Once it has been
            // deleted completely, GetTable will raise a ResourceNotFoundException.
            bool wasRestored = false;

            try
            {
                do
                {
                    var resp = await keyspacesWrapper.GetTable(keyspaceName, restoredTableName);
                    wasRestored = (resp.Status == TableStatus.ACTIVE);
                } while (!wasRestored);
            }
            catch (ResourceNotFoundException)
            {
                // If the restored table raised an error, it isn't
                // ready yet.
                Console.Write(".");
            }
        }

        uiMethods.DisplayTitle("Clean up resources.");

        // Delete the table.
        success = await keyspacesWrapper.DeleteTable(keyspaceName, tableName);

        Console.WriteLine($"Table {tableName} successfully deleted from {keyspaceName}.");
        Console.WriteLine("Waiting for the table to be removed completely. ");

        // Loop and call GetTable until the table is gone. Once it has been
        // deleted completely, GetTable will raise a ResourceNotFoundException.
        bool wasDeleted = false;

        try
        {
            do
            {
                var resp = await keyspacesWrapper.GetTable(keyspaceName, tableName);
            } while (!wasDeleted);
        }
        catch (ResourceNotFoundException ex)
        {
            wasDeleted = true;
            Console.WriteLine($"{ex.Message} indicates that the table has been deleted.");
        }

        // Delete the keyspace.
        success = await keyspacesWrapper.DeleteKeyspace(keyspaceName);
        Console.WriteLine("The keyspace has been deleted and the demo is now complete.");
    }
}
```

```
namespace KeyspacesActions;

/// <summary>
/// Performs Amazon Keyspaces (for Apache Cassandra) actions.
/// </summary>
public class KeyspacesWrapper
{
    private readonly IAmazonKeyspaces _amazonKeyspaces;

    /// <summary>
    /// Constructor for the KeyspaceWrapper.
    /// </summary>
    /// <param name="amazonKeyspaces">An Amazon Keyspaces client object.</param>
    public KeyspacesWrapper(IAmazonKeyspaces amazonKeyspaces)
    {
        _amazonKeyspaces = amazonKeyspaces;
    }

    /// <summary>
    /// Create a new keyspace.
    /// </summary>
    /// <param name="keyspaceName">The name for the new keyspace.</param>
    /// <returns>The Amazon Resource Name (ARN) of the new keyspace.</returns>
    public async Task<string> CreateKeyspace(string keyspaceName)
    {
        var response =
            await _amazonKeyspaces.CreateKeyspaceAsync(
                new CreateKeyspaceRequest { KeyspaceName = keyspaceName });
        return response.ResourceArn;
    }


    /// <summary>
    /// Create a new Amazon Keyspaces table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace where the table will be created.</param>
    /// <param name="schema">The schema for the new table.</param>
    /// <param name="tableName">The name of the new table.</param>
    /// <returns>The Amazon Resource Name (ARN) of the new table.</returns>
    public async Task<string> CreateTable(string keyspaceName, SchemaDefinition schema, string tableName)
    {
        var request = new CreateTableRequest
        {
            KeyspaceName = keyspaceName,
            SchemaDefinition = schema,
            TableName = tableName,
            PointInTimeRecovery = new PointInTimeRecovery { Status = PointInTimeRecoveryStatus.ENABLED }
        };

        var response = await _amazonKeyspaces.CreateTableAsync(request);
        return response.ResourceArn;
    }


    /// <summary>
    /// Delete an existing keyspace.
    /// </summary>
    /// <param name="keyspaceName"></param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteKeyspace(string keyspaceName)
    {
        var response = await _amazonKeyspaces.DeleteKeyspaceAsync(
            new DeleteKeyspaceRequest { KeyspaceName = keyspaceName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete an Amazon Keyspaces table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteTable(string keyspaceName, string tableName)
    {
        var response = await _amazonKeyspaces.DeleteTableAsync(
            new DeleteTableRequest { KeyspaceName = keyspaceName, TableName = tableName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }


    /// <summary>
    /// Get data about a keyspace.
    /// </summary>
    /// <param name="keyspaceName">The name of the keyspace.</param>
    /// <returns>The Amazon Resource Name (ARN) of the keyspace.</returns>
    public async Task<string> GetKeyspace(string keyspaceName)
    {
        var response = await _amazonKeyspaces.GetKeyspaceAsync(
            new GetKeyspaceRequest { KeyspaceName = keyspaceName });
        return response.ResourceArn;
    }


    /// <summary>
    /// Get information about an Amazon Keyspaces table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the Amazon Keyspaces table.</param>
    /// <returns>The response containing data about the table.</returns>
    public async Task<GetTableResponse> GetTable(string keyspaceName, string tableName)
    {
        var response = await _amazonKeyspaces.GetTableAsync(
            new GetTableRequest { KeyspaceName = keyspaceName, TableName = tableName });
        return response;
    }


    /// <summary>
    /// Lists all keyspaces for the account.
    /// </summary>
    /// <returns>Async task.</returns>
    public async Task ListKeyspaces()
    {
        var paginator = _amazonKeyspaces.Paginators.ListKeyspaces(new ListKeyspacesRequest());

        Console.WriteLine("{0, -30}\t{1}", "Keyspace name", "Keyspace ARN");
        Console.WriteLine(new string('-', Console.WindowWidth));
        await foreach (var keyspace in paginator.Keyspaces)
        {
            Console.WriteLine($"{keyspace.KeyspaceName,-30}\t{keyspace.ResourceArn}");
        }
    }


    /// <summary>
    /// Lists the Amazon Keyspaces tables in a keyspace.
    /// </summary>
    /// <param name="keyspaceName">The name of the keyspace.</param>
    /// <returns>A list of TableSummary objects.</returns>
    public async Task<List<TableSummary>> ListTables(string keyspaceName)
    {
        var response = await _amazonKeyspaces.ListTablesAsync(new ListTablesRequest { KeyspaceName = keyspaceName });
        response.Tables.ForEach(table =>
        {
            Console.WriteLine($"{table.KeyspaceName}\t{table.TableName}\t{table.ResourceArn}");
        });

        return response.Tables;
    }


    /// <summary>
    /// Restores the specified table to the specified point in time.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table to restore.</param>
    /// <param name="timestamp">The time to which the table will be restored.</param>
    /// <returns>The Amazon Resource Name (ARN) of the restored table.</returns>
    public async Task<string> RestoreTable(string keyspaceName, string tableName, string restoredTableName, DateTime timestamp)
    {
        var request = new RestoreTableRequest
        {
            RestoreTimestamp = timestamp,
            SourceKeyspaceName = keyspaceName,
            SourceTableName = tableName,
            TargetKeyspaceName = keyspaceName,
            TargetTableName = restoredTableName
        };

        var response = await _amazonKeyspaces.RestoreTableAsync(request);
        return response.RestoredTableARN;
    }


    /// <summary>
    /// Updates the movie table to add a boolean column named watched.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table to change.</param>
    /// <returns>The Amazon Resource Name (ARN) of the updated table.</returns>
    public async Task<string> UpdateTable(string keyspaceName, string tableName)
    {
        var newColumn = new ColumnDefinition { Name = "watched", Type = "boolean" };
        var request = new UpdateTableRequest
        {
            KeyspaceName = keyspaceName,
            TableName = tableName,
            AddColumns = new List<ColumnDefinition> { newColumn }
        };
        var response = await _amazonKeyspaces.UpdateTableAsync(request);
        return response.ResourceArn;
    }

}
```

```
using System.Net;
using Cassandra;

namespace KeyspacesScenario;

/// <summary>
/// Class to perform CRUD methods on an Amazon Keyspaces (for Apache Cassandra) database.
///
/// NOTE: This sample uses a plain text authenticator for example purposes only.
/// Recommended best practice is to use a SigV4 authentication plugin, if available.
/// </summary>
public class CassandraWrapper
{
    private readonly IConfiguration _configuration;
    private readonly string _localPathToFile;
    private const string _certLocation = "https://certs.secureserver.net/repository/sf-class2-root.crt";
    private const string _certFileName = "sf-class2-root.crt";
    private readonly X509Certificate2Collection _certCollection;
    private X509Certificate2 _amazoncert;
    private Cluster _cluster;

    // User name and password for the service.
    private string _userName = null!;
    private string _pwd = null!;

    public CassandraWrapper()
    {
        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        _localPathToFile = Path.GetTempPath();

        // Get the Starfield digital certificate and save it locally.
        var client = new WebClient();
        client.DownloadFile(_certLocation, $"{_localPathToFile}/{_certFileName}");

        //var httpClient = new HttpClient();
        //var httpResult = httpClient.Get(fileUrl);
        //using var resultStream = await httpResult.Content.ReadAsStreamAsync();
        //using var fileStream = File.Create(pathToSave);
        //resultStream.CopyTo(fileStream);

        _certCollection = new X509Certificate2Collection();
        _amazoncert = new X509Certificate2($"{_localPathToFile}/{_certFileName}");

        // Get the user name and password stored in the configuration file.
        _userName = _configuration["UserName"]!;
        _pwd = _configuration["Password"]!;

        // For a list of Service Endpoints for Amazon Keyspaces, see:
        // https://docs.aws.amazon.com/keyspaces/latest/devguide/programmatic.endpoints.html
        var awsEndpoint = _configuration["ServiceEndpoint"];

        _cluster = Cluster.Builder()
            .AddContactPoints(awsEndpoint)
            .WithPort(9142)
            .WithAuthProvider(new PlainTextAuthProvider(_userName, _pwd))
            .WithSSL(new SSLOptions().SetCertificateCollection(_certCollection))
            .WithQueryOptions(
                new QueryOptions()
                    .SetConsistencyLevel(ConsistencyLevel.LocalQuorum)
                    .SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial))
            .Build();
    }

    /// <summary>
    /// Loads the contents of a JSON file into a list of movies to be
    /// added to the Apache Cassandra table.
    /// </summary>
    /// <param name="movieFileName">The full path to the JSON file.</param>
    /// <returns>A list of movie objects.</returns>
    public List<Movie> ImportMoviesFromJson(string movieFileName, int numToImport = 0)
    {
        if (!File.Exists(movieFileName))
        {
            return null!;
        }

        using var sr = new StreamReader(movieFileName);
        string json = sr.ReadToEnd();

        var allMovies = JsonConvert.DeserializeObject<List<Movie>>(json);

        // If numToImport = 0, return all movies in the collection.
        if (numToImport == 0)
        {
            // Now return the entire list of movies.
            return allMovies;
        }
        else
        {
            // Now return the first numToImport entries.
            return allMovies.GetRange(0, numToImport);
        }
    }

    /// <summary>
    /// Insert movies into the movie table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="movieTableName">The Amazon Keyspaces table.</param>
    /// <param name="movieFilePath">The path to the resource file containing
    /// movie data to insert into the table.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> InsertIntoMovieTable(string keyspaceName, string movieTableName, string movieFilePath, int numToImport = 20)
    {
        // Get some movie data from the movies.json file
        var movies = ImportMoviesFromJson(movieFilePath, numToImport);

        var session = _cluster.Connect(keyspaceName);

        string insertCql;

        RowSet rs;

        // Now we insert the numToImport movies into the table.
        foreach (var movie in movies)
        {
            // Escape single quote characters in the plot.
            insertCql = $"INSERT INTO {keyspaceName}.{movieTableName} (title, year, release_date, plot) values($${movie.Title}$$, {movie.Year}, '{movie.Info.Release_Date.ToString("yyyy-MM-dd")}', $${movie.Info.Plot}$$)";
            rs = await session.ExecuteAsync(new SimpleStatement(insertCql));
        }

        return true;
    }

    /// <summary>
    /// Gets all of the movies in the movies table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table.</param>
    /// <returns>A list of row objects containing movie data.</returns>
    public async Task<List<Row>> GetMovies(string keyspaceName, string tableName)
    {
        var session = _cluster.Connect();
        RowSet rs;
        try
        {
            rs = await session.ExecuteAsync(new SimpleStatement($"SELECT * FROM {keyspaceName}.{tableName}"));

            // Extract the row data from the returned RowSet.
            var rows = rs.GetRows().ToList();
            return rows;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return null!;
        }
    }

    /// <summary>
    /// Mark a movie in the movie table as watched.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table.</param>
    /// <param name="title">The title of the movie to mark as watched.</param>
    /// <param name="year">The year the movie was released.</param>
    /// <returns>A set of rows containing the changed data.</returns>
    public async Task<List<Row>> MarkMovieAsWatched(string keyspaceName, string tableName, string title, int year)
    {
        var session = _cluster.Connect();
        string updateCql = $"UPDATE {keyspaceName}.{tableName} SET watched=true WHERE title = $${title}$$ AND year = {year};";
        var rs = await session.ExecuteAsync(new SimpleStatement(updateCql));
        var rows = rs.GetRows().ToList();
        return rows;
    }

    /// <summary>
    /// Retrieve the movies in the movies table where watched is true.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table.</param>
    /// <returns>A list of row objects containing information about movies
    /// where watched is true.</returns>
    public async Task<List<Row>> GetWatchedMovies(string keyspaceName, string tableName)
    {
        var session = _cluster.Connect();
        RowSet rs;
        try
        {
            rs = await session.ExecuteAsync(new SimpleStatement($"SELECT title, year, plot FROM {keyspaceName}.{tableName} WHERE watched = true ALLOW FILTERING"));

            // Extract the row data from the returned RowSet.
            var rows = rs.GetRows().ToList();
            return rows;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return null!;
        }
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateKeyspace](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/CreateKeyspace)
  + [CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/CreateTable)
  + [DeleteKeyspace](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/DeleteKeyspace)
  + [DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/DeleteTable)
  + [GetKeyspace](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/GetKeyspace)
  + [GetTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/GetTable)
  + [ListKeyspaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/ListKeyspaces)
  + [ListTables](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/ListTables)
  + [RestoreTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/RestoreTable)
  + [UpdateTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/UpdateTable)

## アクション
<a name="actions"></a>

### `CreateKeyspace`
<a name="keyspaces_CreateKeyspace_csharp_3_topic"></a>

次のコード例は、`CreateKeyspace` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a new keyspace.
    /// </summary>
    /// <param name="keyspaceName">The name for the new keyspace.</param>
    /// <returns>The Amazon Resource Name (ARN) of the new keyspace.</returns>
    public async Task<string> CreateKeyspace(string keyspaceName)
    {
        var response =
            await _amazonKeyspaces.CreateKeyspaceAsync(
                new CreateKeyspaceRequest { KeyspaceName = keyspaceName });
        return response.ResourceArn;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateKeyspace](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/CreateKeyspace)」を参照してください。

### `CreateTable`
<a name="keyspaces_CreateTable_csharp_3_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a new Amazon Keyspaces table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace where the table will be created.</param>
    /// <param name="schema">The schema for the new table.</param>
    /// <param name="tableName">The name of the new table.</param>
    /// <returns>The Amazon Resource Name (ARN) of the new table.</returns>
    public async Task<string> CreateTable(string keyspaceName, SchemaDefinition schema, string tableName)
    {
        var request = new CreateTableRequest
        {
            KeyspaceName = keyspaceName,
            SchemaDefinition = schema,
            TableName = tableName,
            PointInTimeRecovery = new PointInTimeRecovery { Status = PointInTimeRecoveryStatus.ENABLED }
        };

        var response = await _amazonKeyspaces.CreateTableAsync(request);
        return response.ResourceArn;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/CreateTable)」を参照してください。

### `DeleteKeyspace`
<a name="keyspaces_DeleteKeyspace_csharp_3_topic"></a>

次のコード例は、`DeleteKeyspace` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an existing keyspace.
    /// </summary>
    /// <param name="keyspaceName"></param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteKeyspace(string keyspaceName)
    {
        var response = await _amazonKeyspaces.DeleteKeyspaceAsync(
            new DeleteKeyspaceRequest { KeyspaceName = keyspaceName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」の「[DeleteKeyspace](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/DeleteKeyspace)」を参照してください。

### `DeleteTable`
<a name="keyspaces_DeleteTable_csharp_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an Amazon Keyspaces table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table to delete.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteTable(string keyspaceName, string tableName)
    {
        var response = await _amazonKeyspaces.DeleteTableAsync(
            new DeleteTableRequest { KeyspaceName = keyspaceName, TableName = tableName });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/DeleteTable)」を参照してください。

### `GetKeyspace`
<a name="keyspaces_GetKeyspace_csharp_3_topic"></a>

次のコード例は、`GetKeyspace` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get data about a keyspace.
    /// </summary>
    /// <param name="keyspaceName">The name of the keyspace.</param>
    /// <returns>The Amazon Resource Name (ARN) of the keyspace.</returns>
    public async Task<string> GetKeyspace(string keyspaceName)
    {
        var response = await _amazonKeyspaces.GetKeyspaceAsync(
            new GetKeyspaceRequest { KeyspaceName = keyspaceName });
        return response.ResourceArn;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetKeyspace](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/GetKeyspace)」を参照してください。

### `GetTable`
<a name="keyspaces_GetTable_csharp_3_topic"></a>

次のコード例は、`GetTable` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about an Amazon Keyspaces table.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the Amazon Keyspaces table.</param>
    /// <returns>The response containing data about the table.</returns>
    public async Task<GetTableResponse> GetTable(string keyspaceName, string tableName)
    {
        var response = await _amazonKeyspaces.GetTableAsync(
            new GetTableRequest { KeyspaceName = keyspaceName, TableName = tableName });
        return response;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/GetTable)」を参照してください。

### `ListKeyspaces`
<a name="keyspaces_ListKeyspaces_csharp_3_topic"></a>

次のコード例は、`ListKeyspaces` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Lists all keyspaces for the account.
    /// </summary>
    /// <returns>Async task.</returns>
    public async Task ListKeyspaces()
    {
        var paginator = _amazonKeyspaces.Paginators.ListKeyspaces(new ListKeyspacesRequest());

        Console.WriteLine("{0, -30}\t{1}", "Keyspace name", "Keyspace ARN");
        Console.WriteLine(new string('-', Console.WindowWidth));
        await foreach (var keyspace in paginator.Keyspaces)
        {
            Console.WriteLine($"{keyspace.KeyspaceName,-30}\t{keyspace.ResourceArn}");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListKeyspaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/ListKeyspaces)」を参照してください。

### `ListTables`
<a name="keyspaces_ListTables_csharp_3_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Lists the Amazon Keyspaces tables in a keyspace.
    /// </summary>
    /// <param name="keyspaceName">The name of the keyspace.</param>
    /// <returns>A list of TableSummary objects.</returns>
    public async Task<List<TableSummary>> ListTables(string keyspaceName)
    {
        var response = await _amazonKeyspaces.ListTablesAsync(new ListTablesRequest { KeyspaceName = keyspaceName });
        response.Tables.ForEach(table =>
        {
            Console.WriteLine($"{table.KeyspaceName}\t{table.TableName}\t{table.ResourceArn}");
        });

        return response.Tables;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListTables](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/ListTables)」を参照してください。

### `RestoreTable`
<a name="keyspaces_RestoreTable_csharp_3_topic"></a>

次のコード例は、`RestoreTable` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Restores the specified table to the specified point in time.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table to restore.</param>
    /// <param name="timestamp">The time to which the table will be restored.</param>
    /// <returns>The Amazon Resource Name (ARN) of the restored table.</returns>
    public async Task<string> RestoreTable(string keyspaceName, string tableName, string restoredTableName, DateTime timestamp)
    {
        var request = new RestoreTableRequest
        {
            RestoreTimestamp = timestamp,
            SourceKeyspaceName = keyspaceName,
            SourceTableName = tableName,
            TargetKeyspaceName = keyspaceName,
            TargetTableName = restoredTableName
        };

        var response = await _amazonKeyspaces.RestoreTableAsync(request);
        return response.RestoredTableARN;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンスの*の「[RestoreTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/RestoreTable)」を参照してください。

### `UpdateTable`
<a name="keyspaces_UpdateTable_csharp_3_topic"></a>

次のコード例は、`UpdateTable` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Updates the movie table to add a boolean column named watched.
    /// </summary>
    /// <param name="keyspaceName">The keyspace containing the table.</param>
    /// <param name="tableName">The name of the table to change.</param>
    /// <returns>The Amazon Resource Name (ARN) of the updated table.</returns>
    public async Task<string> UpdateTable(string keyspaceName, string tableName)
    {
        var newColumn = new ColumnDefinition { Name = "watched", Type = "boolean" };
        var request = new UpdateTableRequest
        {
            KeyspaceName = keyspaceName,
            TableName = tableName,
            AddColumns = new List<ColumnDefinition> { newColumn }
        };
        var response = await _amazonKeyspaces.UpdateTableAsync(request);
        return response.ResourceArn;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[UpdateTable](https://docs.aws.amazon.com/goto/DotNetSDKV3/keyspaces-2022-02-10/UpdateTable)」を参照してください。

# を使用した Kinesis の例 SDK for .NET
<a name="csharp_3_kinesis_code_examples"></a>

次のコード例は、Kinesis AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `AddTagsToStream`
<a name="kinesis_AddTagsToStream_csharp_3_topic"></a>

次のコード例は、`AddTagsToStream` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// This example shows how to apply key/value pairs to an Amazon Kinesis
    /// stream.
    /// </summary>
    public class TagStream
    {
        public static async Task Main()
        {
            IAmazonKinesis client = new AmazonKinesisClient();

            string streamName = "AmazonKinesisStream";
            var tags = new Dictionary<string, string>
            {
                { "Project", "Sample Kinesis Project" },
                { "Application", "Sample Kinesis App" },
            };

            var success = await ApplyTagsToStreamAsync(client, streamName, tags);

            if (success)
            {
                Console.WriteLine($"Taggs successfully added to {streamName}.");
            }
            else
            {
                Console.WriteLine("Tags were not added to the stream.");
            }
        }

        /// <summary>
        /// Applies the set of tags to the named Kinesis stream.
        /// </summary>
        /// <param name="client">The initialized Kinesis client.</param>
        /// <param name="streamName">The name of the Kinesis stream to which
        /// the tags will be attached.</param>
        /// <param name="tags">A sictionary containing key/value pairs which
        /// will be used to create the Kinesis tags.</param>
        /// <returns>A Boolean value which represents the success or failure
        /// of AddTagsToStreamAsync.</returns>
        public static async Task<bool> ApplyTagsToStreamAsync(
            IAmazonKinesis client,
            string streamName,
            Dictionary<string, string> tags)
        {
            var request = new AddTagsToStreamRequest
            {
                StreamName = streamName,
                Tags = tags,
            };

            var response = await client.AddTagsToStreamAsync(request);

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[AddTagsToStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/AddTagsToStream)」を参照してください。

### `CreateStream`
<a name="kinesis_CreateStream_csharp_3_topic"></a>

次のコード例は、`CreateStream` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// This example shows how to create a new Amazon Kinesis stream.
    /// </summary>
    public class CreateStream
    {
        public static async Task Main()
        {
            IAmazonKinesis client = new AmazonKinesisClient();

            string streamName = "AmazonKinesisStream";
            int shardCount = 1;

            var success = await CreateNewStreamAsync(client, streamName, shardCount);
            if (success)
            {
                Console.WriteLine($"The stream, {streamName} successfully created.");
            }
        }

        /// <summary>
        /// Creates a new Kinesis stream.
        /// </summary>
        /// <param name="client">An initialized Kinesis client.</param>
        /// <param name="streamName">The name for the new stream.</param>
        /// <param name="shardCount">The number of shards the new stream will
        /// use. The throughput of the stream is a function of the number of
        /// shards; more shards are required for greater provisioned
        /// throughput.</param>
        /// <returns>A Boolean value indicating whether the stream was created.</returns>
        public static async Task<bool> CreateNewStreamAsync(IAmazonKinesis client, string streamName, int shardCount)
        {
            var request = new CreateStreamRequest
            {
                StreamName = streamName,
                ShardCount = shardCount,
            };

            var response = await client.CreateStreamAsync(request);

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/CreateStream)」を参照してください。

### `DeleteStream`
<a name="kinesis_DeleteStream_csharp_3_topic"></a>

次のコード例は、`DeleteStream` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// Shows how to delete an Amazon Kinesis stream.
    /// </summary>
    public class DeleteStream
    {
        public static async Task Main()
        {
            IAmazonKinesis client = new AmazonKinesisClient();
            string streamName = "AmazonKinesisStream";

            var success = await DeleteStreamAsync(client, streamName);

            if (success)
            {
                Console.WriteLine($"Stream, {streamName} successfully deleted.");
            }
            else
            {
                Console.WriteLine("Stream not deleted.");
            }
        }

        /// <summary>
        /// Deletes a Kinesis stream.
        /// </summary>
        /// <param name="client">An initialized Kinesis client object.</param>
        /// <param name="streamName">The name of the string to delete.</param>
        /// <returns>A Boolean value representing the success of the operation.</returns>
        public static async Task<bool> DeleteStreamAsync(IAmazonKinesis client, string streamName)
        {
            // If EnforceConsumerDeletion is true, any consumers
            // of this stream will also be deleted. If it is set
            // to false and this stream has any consumers, the
            // call will fail with a ResourceInUseException.
            var request = new DeleteStreamRequest
            {
                StreamName = streamName,
                EnforceConsumerDeletion = true,
            };

            var response = await client.DeleteStreamAsync(request);

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/DeleteStream)」を参照してください。

### `DeregisterStreamConsumer`
<a name="kinesis_DeregisterStreamConsumer_csharp_3_topic"></a>

次のコード例は、`DeregisterStreamConsumer` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// Shows how to deregister a consumer from an Amazon Kinesis stream.
    /// </summary>
    public class DeregisterConsumer
    {
        public static async Task Main(string[] args)
        {
            IAmazonKinesis client = new AmazonKinesisClient();

            string streamARN = "arn:aws:kinesis:us-west-2:000000000000:stream/AmazonKinesisStream";
            string consumerName = "CONSUMER_NAME";
            string consumerARN = "arn:aws:kinesis:us-west-2:000000000000:stream/AmazonKinesisStream/consumer/CONSUMER_NAME:000000000000";

            var success = await DeregisterConsumerAsync(client, streamARN, consumerARN, consumerName);

            if (success)
            {
                Console.WriteLine($"{consumerName} successfully deregistered.");
            }
            else
            {
                Console.WriteLine($"{consumerName} was not successfully deregistered.");
            }
        }

        /// <summary>
        /// Deregisters a consumer from a Kinesis stream.
        /// </summary>
        /// <param name="client">An initialized Kinesis client object.</param>
        /// <param name="streamARN">The ARN of a Kinesis stream.</param>
        /// <param name="consumerARN">The ARN of the consumer.</param>
        /// <param name="consumerName">The name of the consumer.</param>
        /// <returns>A Boolean value representing the success of the operation.</returns>
        public static async Task<bool> DeregisterConsumerAsync(
            IAmazonKinesis client,
            string streamARN,
            string consumerARN,
            string consumerName)
        {
            var request = new DeregisterStreamConsumerRequest
            {
                StreamARN = streamARN,
                ConsumerARN = consumerARN,
                ConsumerName = consumerName,
            };

            var response = await client.DeregisterStreamConsumerAsync(request);

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeregisterStreamConsumer](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/DeregisterStreamConsumer)」を参照してください。

### `ListStreamConsumers`
<a name="kinesis_ListStreamConsumers_csharp_3_topic"></a>

次のコード例は、`ListStreamConsumers` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// List the consumers of an Amazon Kinesis stream.
    /// </summary>
    public class ListConsumers
    {
        public static async Task Main()
        {
            IAmazonKinesis client = new AmazonKinesisClient();

            string streamARN = "arn:aws:kinesis:us-east-2:000000000000:stream/AmazonKinesisStream";
            int maxResults = 10;

            var consumers = await ListConsumersAsync(client, streamARN, maxResults);

            if (consumers.Count > 0)
            {
                consumers
                    .ForEach(c => Console.WriteLine($"Name: {c.ConsumerName} ARN: {c.ConsumerARN}"));
            }
            else
            {
                Console.WriteLine("No consumers found.");
            }
        }

        /// <summary>
        /// Retrieve a list of the consumers for a Kinesis stream.
        /// </summary>
        /// <param name="client">An initialized Kinesis client object.</param>
        /// <param name="streamARN">The ARN of the stream for which we want to
        /// retrieve a list of clients.</param>
        /// <param name="maxResults">The maximum number of results to return.</param>
        /// <returns>A list of Consumer objects.</returns>
        public static async Task<List<Consumer>> ListConsumersAsync(IAmazonKinesis client, string streamARN, int maxResults)
        {
            var request = new ListStreamConsumersRequest
            {
                StreamARN = streamARN,
                MaxResults = maxResults,
            };

            var response = await client.ListStreamConsumersAsync(request);

            return response.Consumers;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の [ListStreamConsumers](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/ListStreamConsumers)を参照してください。

### `ListStreams`
<a name="kinesis_ListStreams_csharp_3_topic"></a>

次のコード例は、`ListStreams` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// Retrieves and displays a list of existing Amazon Kinesis streams.
    /// </summary>
    public class ListStreams
    {
        public static async Task Main(string[] args)
        {
            IAmazonKinesis client = new AmazonKinesisClient();
            var response = await client.ListStreamsAsync(new ListStreamsRequest());

            List<string> streamNames = response.StreamNames;

            if (streamNames.Count > 0)
            {
                streamNames
                    .ForEach(s => Console.WriteLine($"Stream name: {s}"));
            }
            else
            {
                Console.WriteLine("No streams were found.");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListStreams](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/ListStreams)」を参照してください。

### `ListTagsForStream`
<a name="kinesis_ListTagsForStream_csharp_3_topic"></a>

次のコード例は、`ListTagsForStream` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// Shows how to list the tags that have been attached to an Amazon Kinesis
    /// stream.
    /// </summary>
    public class ListTags
    {
        public static async Task Main()
        {
            IAmazonKinesis client = new AmazonKinesisClient();
            string streamName = "AmazonKinesisStream";

            await ListTagsAsync(client, streamName);
        }

        /// <summary>
        /// List the tags attached to a Kinesis stream.
        /// </summary>
        /// <param name="client">An initialized Kinesis client object.</param>
        /// <param name="streamName">The name of the Kinesis stream for which you
        /// wish to display tags.</param>
        public static async Task ListTagsAsync(IAmazonKinesis client, string streamName)
        {
            var request = new ListTagsForStreamRequest
            {
                StreamName = streamName,
                Limit = 10,
            };

            var response = await client.ListTagsForStreamAsync(request);
            DisplayTags(response.Tags);

            while (response.HasMoreTags)
            {
                request.ExclusiveStartTagKey = response.Tags[response.Tags.Count - 1].Key;
                response = await client.ListTagsForStreamAsync(request);
            }
        }

        /// <summary>
        /// Displays the items in a list of Kinesis tags.
        /// </summary>
        /// <param name="tags">A list of the Tag objects to be displayed.</param>
        public static void DisplayTags(List<Tag> tags)
        {
            tags
                .ForEach(t => Console.WriteLine($"Key: {t.Key} Value: {t.Value}"));
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListTagsForStream](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/ListTagsForStream)」を参照してください。

### `RegisterStreamConsumer`
<a name="kinesis_RegisterStreamConsumer_csharp_3_topic"></a>

次のコード例は、`RegisterStreamConsumer` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Kinesis#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Kinesis;
    using Amazon.Kinesis.Model;

    /// <summary>
    /// This example shows how to register a consumer to an Amazon Kinesis
    /// stream.
    /// </summary>
    public class RegisterConsumer
    {
        public static async Task Main()
        {
            IAmazonKinesis client = new AmazonKinesisClient();
            string consumerName = "NEW_CONSUMER_NAME";
            string streamARN = "arn:aws:kinesis:us-east-2:000000000000:stream/AmazonKinesisStream";

            var consumer = await RegisterConsumerAsync(client, consumerName, streamARN);

            if (consumer is not null)
            {
                Console.WriteLine($"{consumer.ConsumerName}");
            }
        }

        /// <summary>
        /// Registers the consumer to a Kinesis stream.
        /// </summary>
        /// <param name="client">The initialized Kinesis client object.</param>
        /// <param name="consumerName">A string representing the consumer.</param>
        /// <param name="streamARN">The ARN of the stream.</param>
        /// <returns>A Consumer object that contains information about the consumer.</returns>
        public static async Task<Consumer> RegisterConsumerAsync(IAmazonKinesis client, string consumerName, string streamARN)
        {
            var request = new RegisterStreamConsumerRequest
            {
                ConsumerName = consumerName,
                StreamARN = streamARN,
            };

            var response = await client.RegisterStreamConsumerAsync(request);
            return response.Consumer;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[スRegisterStreamConsumer](https://docs.aws.amazon.com/goto/DotNetSDKV3/kinesis-2013-12-02/RegisterStreamConsumer)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_csharp_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.KinesisEvents;
using AWS.Lambda.Powertools.Logging;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace KinesisIntegrationSampleCode;

public class Function
{
    // Powertools Logger requires an environment variables against your function
    // POWERTOOLS_SERVICE_NAME
    [Logging(LogEvent = true)]
    public async Task FunctionHandler(KinesisEvent evnt, ILambdaContext context)
    {
        if (evnt.Records.Count == 0)
        {
            Logger.LogInformation("Empty Kinesis Event received");
            return;
        }

        foreach (var record in evnt.Records)
        {
            try
            {
                Logger.LogInformation($"Processed Event with EventId: {record.EventId}");
                string data = await GetRecordDataAsync(record.Kinesis, context);
                Logger.LogInformation($"Data: {data}");
                // TODO: Do interesting work based on the new data
            }
            catch (Exception ex)
            {
                Logger.LogError($"An error occurred {ex.Message}");
                throw;
            }
        }
        Logger.LogInformation($"Successfully processed {evnt.Records.Count} records.");
    }

    private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context)
    {
        byte[] bytes = record.Data.ToArray();
        string data = Encoding.UTF8.GetString(bytes);
        await Task.CompletedTask; //Placeholder for actual async work
        return data;
    }
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_csharp_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using System.Text;
using System.Text.Json.Serialization;
using Amazon.Lambda.Core;
using Amazon.Lambda.KinesisEvents;
using AWS.Lambda.Powertools.Logging;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace KinesisIntegration;

public class Function
{
    // Powertools Logger requires an environment variables against your function
    // POWERTOOLS_SERVICE_NAME
    [Logging(LogEvent = true)]
    public async Task<StreamsEventResponse> FunctionHandler(KinesisEvent evnt, ILambdaContext context)
    {
        if (evnt.Records.Count == 0)
        {
            Logger.LogInformation("Empty Kinesis Event received");
            return new StreamsEventResponse();
        }

        foreach (var record in evnt.Records)
        {
            try
            {
                Logger.LogInformation($"Processed Event with EventId: {record.EventId}");
                string data = await GetRecordDataAsync(record.Kinesis, context);
                Logger.LogInformation($"Data: {data}");
                // TODO: Do interesting work based on the new data
            }
            catch (Exception ex)
            {
                Logger.LogError($"An error occurred {ex.Message}");
                /* Since we are working with streams, we can return the failed item immediately.
                   Lambda will immediately begin to retry processing from this failed item onwards. */
                return new StreamsEventResponse
                {
                    BatchItemFailures = new List<StreamsEventResponse.BatchItemFailure>
                    {
                        new StreamsEventResponse.BatchItemFailure { ItemIdentifier = record.Kinesis.SequenceNumber }
                    }
                };
            }
        }
        Logger.LogInformation($"Successfully processed {evnt.Records.Count} records.");
        return new StreamsEventResponse();
    }

    private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context)
    {
        byte[] bytes = record.Data.ToArray();
        string data = Encoding.UTF8.GetString(bytes);
        await Task.CompletedTask; //Placeholder for actual async work
        return data;
    }
}

public class StreamsEventResponse
{
    [JsonPropertyName("batchItemFailures")]
    public IList<BatchItemFailure> BatchItemFailures { get; set; }
    public class BatchItemFailure
    {
        [JsonPropertyName("itemIdentifier")]
        public string ItemIdentifier { get; set; }
    }
}
```

# AWS KMS を使用した の例 SDK for .NET
<a name="csharp_3_kms_code_examples"></a>

次のコード例は、 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateAlias`
<a name="kms_CreateAlias_csharp_3_topic"></a>

次のコード例は、`CreateAlias` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// Creates an alias for an AWS Key Management Service (AWS KMS) key.
    /// </summary>
    public class CreateAlias
    {
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The alias name must start with alias/ and can be
            // up to 256 alphanumeric characters long.
            var aliasName = "alias/ExampleAlias";

            // The value supplied as the TargetKeyId can be either
            // the key ID or key Amazon Resource Name (ARN) of the
            // AWS KMS key.
            var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab";

            var request = new CreateAliasRequest
            {
                AliasName = aliasName,
                TargetKeyId = keyId,
            };

            var response = await client.CreateAliasAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Alias, {aliasName}, successfully created.");
            }
            else
            {
                Console.WriteLine($"Could not create alias.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の[CreateAlias](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/CreateAlias)を参照してください。

### `CreateGrant`
<a name="kms_CreateGrant_csharp_3_topic"></a>

次のコード例は、`CreateGrant` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The identity that is given permission to perform the operations
            // specified in the grant.
            var grantee = "arn:aws:iam::111122223333:role/ExampleRole";

            // The identifier of the AWS KMS key to which the grant applies. You
            // can use the key ID or the Amazon Resource Name (ARN) of the KMS key.
            var keyId = "7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4";

            var request = new CreateGrantRequest
            {
                GranteePrincipal = grantee,
                KeyId = keyId,

                // A list of operations that the grant allows.
                Operations = new List<string>
                {
                    "Encrypt",
                    "Decrypt",
                },
            };

            var response = await client.CreateGrantAsync(request);

            string grantId = response.GrantId; // The unique identifier of the grant.
            string grantToken = response.GrantToken; // The grant token.

            Console.WriteLine($"Id: {grantId}, Token: {grantToken}");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の[CreateGrant](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/CreateGrant)を参照してください。

### `CreateKey`
<a name="kms_CreateKey_csharp_3_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// Shows how to create a new AWS Key Management Service (AWS KMS)
    /// key.
    /// </summary>
    public class CreateKey
    {
        public static async Task Main()
        {
            // Note that if you need to create a Key in an AWS Region
            // other than the Region defined for the default user, you need to
            // pass the Region to the client constructor.
            var client = new AmazonKeyManagementServiceClient();

            // The call to CreateKeyAsync will create a symmetrical AWS KMS
            // key. For more information about symmetrical and asymmetrical
            // keys, see:
            //
            // https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-choose.html
            var response = await client.CreateKeyAsync(new CreateKeyRequest());

            // The KeyMetadata object contains information about the new AWS KMS key.
            KeyMetadata keyMetadata = response.KeyMetadata;

            if (keyMetadata is not null)
            {
                Console.WriteLine($"KMS Key: {keyMetadata.KeyId} was successfully created.");
            }
            else
            {
                Console.WriteLine("Could not create KMS Key.");
            }
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[CreateKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/CreateKey)」を参照してください。

### `DescribeKey`
<a name="kms_DescribeKey_csharp_3_topic"></a>

次のコード例は、`DescribeKey` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// Retrieve information about an AWS Key Management Service (AWS KMS) key.
    /// You can supply either the key Id or the key Amazon Resource Name (ARN)
    /// to the DescribeKeyRequest KeyId property.
    /// </summary>
    public class DescribeKey
    {
        public static async Task Main()
        {
            var keyId = "7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4";
            var request = new DescribeKeyRequest
            {
                KeyId = keyId,
            };

            var client = new AmazonKeyManagementServiceClient();

            var response = await client.DescribeKeyAsync(request);
            var metadata = response.KeyMetadata;

            Console.WriteLine($"{metadata.KeyId} created on: {metadata.CreationDate}");
            Console.WriteLine($"State: {metadata.KeyState}");
            Console.WriteLine($"{metadata.Description}");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の [DescribeKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/DescribeKey)を参照してください。

### `DisableKey`
<a name="kms_DisableKey_csharp_3_topic"></a>

次のコード例は、`DisableKey` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// Disable an AWS Key Management Service (AWS KMS) key and then retrieve
    /// the key's status to show that it has been disabled.
    /// </summary>
    public class DisableKey
    {
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The identifier of the AWS KMS key to disable. You can use the
            // key Id or the Amazon Resource Name (ARN) of the AWS KMS key.
            var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab";

            var request = new DisableKeyRequest
            {
                KeyId = keyId,
            };

            var response = await client.DisableKeyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                // Retrieve information about the key to show that it has now
                // been disabled.
                var describeResponse = await client.DescribeKeyAsync(new DescribeKeyRequest
                {
                    KeyId = keyId,
                });
                Console.WriteLine($"{describeResponse.KeyMetadata.KeyId} - state: {describeResponse.KeyMetadata.KeyState}");
            }
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DisableKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/DisableKey)」を参照してください。

### `EnableKey`
<a name="kms_EnableKey_csharp_3_topic"></a>

次のコード例は、`EnableKey` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// Enable an AWS Key Management Service (AWS KMS) key.
    /// </summary>
    public class EnableKey
    {
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The identifier of the AWS KMS key to enable. You can use the
            // key Id or the Amazon Resource Name (ARN) of the AWS KMS key.
            var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab";

            var request = new EnableKeyRequest
            {
                KeyId = keyId,
            };

            var response = await client.EnableKeyAsync(request);
            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                // Retrieve information about the key to show that it has now
                // been enabled.
                var describeResponse = await client.DescribeKeyAsync(new DescribeKeyRequest
                {
                    KeyId = keyId,
                });
                Console.WriteLine($"{describeResponse.KeyMetadata.KeyId} - state: {describeResponse.KeyMetadata.KeyState}");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[EnableKey](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/EnableKey)」を参照してください。

### `ListAliases`
<a name="kms_ListAliases_csharp_3_topic"></a>

次のコード例は、`ListAliases` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// List the AWS Key Management Service (AWS KMS) aliases that have been defined for
    /// the keys in the same AWS Region as the default user. If you want to list
    /// the aliases in a different Region, pass the Region to the client
    /// constructor.
    /// </summary>
    public class ListAliases
    {
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();
            var request = new ListAliasesRequest();
            var response = new ListAliasesResponse();

            do
            {
                response = await client.ListAliasesAsync(request);

                response.Aliases.ForEach(alias =>
                {
                    Console.WriteLine($"Created: {alias.CreationDate} Last Update: {alias.LastUpdatedDate} Name: {alias.AliasName}");
                });

                request.Marker = response.NextMarker;
            }
            while (response.Truncated);
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListAliases](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/ListAliases)」を参照してください。

### `ListGrants`
<a name="kms_ListGrants_csharp_3_topic"></a>

次のコード例は、`ListGrants` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// List the AWS Key Management Service (AWS KMS) grants that are associated with
    /// a specific key.
    /// </summary>
    public class ListGrants
    {
        public static async Task Main()
        {
            // The identifier of the AWS KMS key to disable. You can use the
            // key Id or the Amazon Resource Name (ARN) of the AWS KMS key.
            var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab";
            var client = new AmazonKeyManagementServiceClient();
            var request = new ListGrantsRequest
            {
                KeyId = keyId,
            };

            var response = new ListGrantsResponse();

            do
            {
                response = await client.ListGrantsAsync(request);

                response.Grants.ForEach(grant =>
                {
                    Console.WriteLine($"{grant.GrantId}");
                });

                request.Marker = response.NextMarker;
            }
            while (response.Truncated);
        }
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」の「[ListGrants](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/ListGrants)」を参照してください。

### `ListKeys`
<a name="kms_ListKeys_csharp_3_topic"></a>

次のコード例は、`ListKeys` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/KMS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.KeyManagementService;
    using Amazon.KeyManagementService.Model;

    /// <summary>
    /// List the AWS Key Managements Service (AWS KMS) keys for the AWS Region
    /// of the default user. To list keys in another AWS Region, supply the Region
    /// as a parameter to the client constructor.
    /// </summary>
    public class ListKeys
    {
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();
            var request = new ListKeysRequest();
            var response = new ListKeysResponse();

            do
            {
                response = await client.ListKeysAsync(request);

                response.Keys.ForEach(key =>
                {
                    Console.WriteLine($"ID: {key.KeyId}, {key.KeyArn}");
                });

                // Set the Marker property when response.Truncated is true
                // in order to get the next keys.
                request.Marker = response.NextMarker;
            }
            while (response.Truncated);
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListKeys](https://docs.aws.amazon.com/goto/DotNetSDKV3/kms-2014-11-01/ListKeys)」を参照してください。

# を使用した Lambda の例 SDK for .NET
<a name="csharp_3_lambda_code_examples"></a>

次のコード例は、Lambda AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## はじめに
<a name="get_started"></a>

### Hello Lambda
<a name="lambda_Hello_csharp_3_topic"></a>

次のコード例は、Lambda の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
namespace LambdaActions;

using Amazon.Lambda;

public class HelloLambda
{
    static async Task Main(string[] args)
    {
        var lambdaClient = new AmazonLambdaClient();

        Console.WriteLine("Hello AWS Lambda");
        Console.WriteLine("Let's get started with AWS Lambda by listing your existing Lambda functions:");

        var response = await lambdaClient.ListFunctionsAsync();
        response.Functions.ForEach(function =>
        {
            Console.WriteLine($"{function.FunctionName}\t{function.Description}");
        });
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListFunctions)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。
Lambda アクションを実行するメソッドを作成します。  

```
namespace LambdaActions;

using Amazon.Lambda;
using Amazon.Lambda.Model;

/// <summary>
/// A class that implements AWS Lambda methods.
/// </summary>
public class LambdaWrapper
{
    private readonly IAmazonLambda _lambdaService;

    /// <summary>
    /// Constructor for the LambdaWrapper class.
    /// </summary>
    /// <param name="lambdaService">An initialized Lambda service client.</param>
    public LambdaWrapper(IAmazonLambda lambdaService)
    {
        _lambdaService = lambdaService;
    }

    /// <summary>
    /// Creates a new Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the function.</param>
    /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3)
    /// bucket where the zip file containing the code is located.</param>
    /// <param name="s3Key">The Amazon S3 key of the zip file.</param>
    /// <param name="role">The Amazon Resource Name (ARN) of a role with the
    /// appropriate Lambda permissions.</param>
    /// <param name="handler">The name of the handler function.</param>
    /// <returns>The Amazon Resource Name (ARN) of the newly created
    /// Lambda function.</returns>
    public async Task<string> CreateLambdaFunctionAsync(
        string functionName,
        string s3Bucket,
        string s3Key,
        string role,
        string handler)
    {
        // Defines the location for the function code.
        // S3Bucket - The S3 bucket where the file containing
        //            the source code is stored.
        // S3Key    - The name of the file containing the code.
        var functionCode = new FunctionCode
        {
            S3Bucket = s3Bucket,
            S3Key = s3Key,
        };

        var createFunctionRequest = new CreateFunctionRequest
        {
            FunctionName = functionName,
            Description = "Created by the Lambda .NET API",
            Code = functionCode,
            Handler = handler,
            Runtime = Runtime.Dotnet6,
            Role = role,
        };

        var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest);
        return reponse.FunctionArn;
    }


    /// <summary>
    /// Delete an AWS Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to
    /// delete.</param>
    /// <returns>A Boolean value that indicates the success of the action.</returns>
    public async Task<bool> DeleteFunctionAsync(string functionName)
    {
        var request = new DeleteFunctionRequest
        {
            FunctionName = functionName,
        };

        var response = await _lambdaService.DeleteFunctionAsync(request);

        // A return value of NoContent means that the request was processed.
        // In this case, the function was deleted, and the return value
        // is intentionally blank.
        return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent;
    }


    /// <summary>
    /// Gets information about a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function for
    /// which to retrieve information.</param>
    /// <returns>Async Task.</returns>
    public async Task<FunctionConfiguration> GetFunctionAsync(string functionName)
    {
        var functionRequest = new GetFunctionRequest
        {
            FunctionName = functionName,
        };

        var response = await _lambdaService.GetFunctionAsync(functionRequest);
        return response.Configuration;
    }


    /// <summary>
    /// Invoke a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to
    /// invoke.</param
    /// <param name="parameters">The parameter values that will be passed to the function.</param>
    /// <returns>A System Threading Task.</returns>
    public async Task<string> InvokeFunctionAsync(
        string functionName,
        string parameters)
    {
        var payload = parameters;
        var request = new InvokeRequest
        {
            FunctionName = functionName,
            Payload = payload,
        };

        var response = await _lambdaService.InvokeAsync(request);
        MemoryStream stream = response.Payload;
        string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray());
        return returnValue;
    }


    /// <summary>
    /// Get a list of Lambda functions.
    /// </summary>
    /// <returns>A list of FunctionConfiguration objects.</returns>
    public async Task<List<FunctionConfiguration>> ListFunctionsAsync()
    {
        var functionList = new List<FunctionConfiguration>();

        var functionPaginator =
            _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest());
        await foreach (var function in functionPaginator.Functions)
        {
            functionList.Add(function);
        }

        return functionList;
    }


    /// <summary>
    /// Update an existing Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to update.</param>
    /// <param name="bucketName">The bucket where the zip file containing
    /// the Lambda function code is stored.</param>
    /// <param name="key">The key name of the source code file.</param>
    /// <returns>Async Task.</returns>
    public async Task UpdateFunctionCodeAsync(
        string functionName,
        string bucketName,
        string key)
    {
        var functionCodeRequest = new UpdateFunctionCodeRequest
        {
            FunctionName = functionName,
            Publish = true,
            S3Bucket = bucketName,
            S3Key = key,
        };

        var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest);
        Console.WriteLine($"The Function was last modified at {response.LastModified}.");
    }


    /// <summary>
    /// Update the code of a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the function to update.</param>
    /// <param name="functionHandler">The code that performs the function's actions.</param>
    /// <param name="environmentVariables">A dictionary of environment variables.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> UpdateFunctionConfigurationAsync(
        string functionName,
        string functionHandler,
        Dictionary<string, string> environmentVariables)
    {
        var request = new UpdateFunctionConfigurationRequest
        {
            Handler = functionHandler,
            FunctionName = functionName,
            Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables },
        };

        var response = await _lambdaService.UpdateFunctionConfigurationAsync(request);

        Console.WriteLine(response.LastModified);

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


}
```
シナリオを実行する関数を作成します。  

```
global using System.Threading.Tasks;
global using Amazon.IdentityManagement;
global using Amazon.Lambda;
global using LambdaActions;
global using LambdaScenarioCommon;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;


using Amazon.Lambda.Model;
using Microsoft.Extensions.Configuration;

namespace LambdaBasics;

public class LambdaBasics
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonLambda>()
            .AddAWSService<IAmazonIdentityManagementService>()
            .AddTransient<LambdaWrapper>()
            .AddTransient<LambdaRoleWrapper>()
            .AddTransient<UIWrapper>()
        )
        .Build();

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
            true) // Optionally load local settings.
        .Build();


        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<LambdaBasics>();

        var lambdaWrapper = host.Services.GetRequiredService<LambdaWrapper>();
        var lambdaRoleWrapper = host.Services.GetRequiredService<LambdaRoleWrapper>();
        var uiWrapper = host.Services.GetRequiredService<UIWrapper>();

        string functionName = configuration["FunctionName"]!;
        string roleName = configuration["RoleName"]!;
        string policyDocument = "{" +
            " \"Version\": \"2012-10-17\"," +
            " \"Statement\": [ " +
            "    {" +
            "        \"Effect\": \"Allow\"," +
            "        \"Principal\": {" +
            "            \"Service\": \"lambda.amazonaws.com\" " +
            "    }," +
            "        \"Action\": \"sts:AssumeRole\" " +
            "    }" +
            "]" +
        "}";

        var incrementHandler = configuration["IncrementHandler"];
        var calculatorHandler = configuration["CalculatorHandler"];
        var bucketName = configuration["BucketName"];
        var incrementKey = configuration["IncrementKey"];
        var calculatorKey = configuration["CalculatorKey"];
        var policyArn = configuration["PolicyArn"];

        uiWrapper.DisplayLambdaBasicsOverview();

        // Create the policy to use with the AWS Lambda functions and then attach the
        // policy to a new role.
        var roleArn = await lambdaRoleWrapper.CreateLambdaRoleAsync(roleName, policyDocument);

        Console.WriteLine("Waiting for role to become active.");
        uiWrapper.WaitABit(15, "Wait until the role is active before trying to use it.");

        // Attach the appropriate AWS Identity and Access Management (IAM) role policy to the new role.
        var success = await lambdaRoleWrapper.AttachLambdaRolePolicyAsync(policyArn, roleName);
        uiWrapper.WaitABit(10, "Allow time for the IAM policy to be attached to the role.");

        // Create the Lambda function using a zip file stored in an Amazon Simple Storage Service
        // (Amazon S3) bucket.
        uiWrapper.DisplayTitle("Create Lambda Function");
        Console.WriteLine($"Creating the AWS Lambda function: {functionName}.");
        var lambdaArn = await lambdaWrapper.CreateLambdaFunctionAsync(
            functionName,
            bucketName,
            incrementKey,
            roleArn,
            incrementHandler);

        Console.WriteLine("Waiting for the new function to be available.");
        Console.WriteLine($"The AWS Lambda ARN is {lambdaArn}");

        // Get the Lambda function.
        Console.WriteLine($"Getting the {functionName} AWS Lambda function.");
        FunctionConfiguration config;
        do
        {
            config = await lambdaWrapper.GetFunctionAsync(functionName);
            Console.Write(".");
        }
        while (config.State != State.Active);

        Console.WriteLine($"\nThe function, {functionName} has been created.");
        Console.WriteLine($"The runtime of this Lambda function is {config.Runtime}.");

        uiWrapper.PressEnter();

        // List the Lambda functions.
        uiWrapper.DisplayTitle("Listing all Lambda functions.");
        var functions = await lambdaWrapper.ListFunctionsAsync();
        DisplayFunctionList(functions);

        uiWrapper.DisplayTitle("Invoke increment function");
        Console.WriteLine("Now that it has been created, invoke the Lambda increment function.");
        string? value;
        do
        {
            Console.Write("Enter a value to increment: ");
            value = Console.ReadLine();
        }
        while (string.IsNullOrEmpty(value));

        string functionParameters = "{" +
            "\"action\": \"increment\", " +
            "\"x\": \"" + value + "\"" +
        "}";
        var answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters);
        Console.WriteLine($"{value} + 1 = {answer}.");

        uiWrapper.DisplayTitle("Update function");
        Console.WriteLine("Now update the Lambda function code.");
        await lambdaWrapper.UpdateFunctionCodeAsync(functionName, bucketName, calculatorKey);

        do
        {
            config = await lambdaWrapper.GetFunctionAsync(functionName);
            Console.Write(".");
        }
        while (config.LastUpdateStatus == LastUpdateStatus.InProgress);

        await lambdaWrapper.UpdateFunctionConfigurationAsync(
            functionName,
            calculatorHandler,
            new Dictionary<string, string> { { "LOG_LEVEL", "DEBUG" } });

        do
        {
            config = await lambdaWrapper.GetFunctionAsync(functionName);
            Console.Write(".");
        }
        while (config.LastUpdateStatus == LastUpdateStatus.InProgress);

        uiWrapper.DisplayTitle("Call updated function");
        Console.WriteLine("Now call the updated function...");

        bool done = false;

        do
        {
            string? opSelected;

            Console.WriteLine("Select the operation to perform:");
            Console.WriteLine("\t1. add");
            Console.WriteLine("\t2. subtract");
            Console.WriteLine("\t3. multiply");
            Console.WriteLine("\t4. divide");
            Console.WriteLine("\tOr enter \"q\" to quit.");
            Console.WriteLine("Enter the number (1, 2, 3, 4, or q) of the operation you want to perform: ");
            do
            {
                Console.Write("Your choice? ");
                opSelected = Console.ReadLine();
            }
            while (opSelected == string.Empty);

            var operation = (opSelected) switch
            {
                "1" => "add",
                "2" => "subtract",
                "3" => "multiply",
                "4" => "divide",
                "q" => "quit",
                _ => "add",
            };

            if (operation == "quit")
            {
                done = true;
            }
            else
            {
                // Get two numbers and an action from the user.
                value = string.Empty;
                do
                {
                    Console.Write("Enter the first value: ");
                    value = Console.ReadLine();
                }
                while (value == string.Empty);

                string? value2;
                do
                {
                    Console.Write("Enter a second value: ");
                    value2 = Console.ReadLine();
                }
                while (value2 == string.Empty);

                functionParameters = "{" +
                    "\"action\": \"" + operation + "\", " +
                    "\"x\": \"" + value + "\"," +
                    "\"y\": \"" + value2 + "\"" +
                "}";

                answer = await lambdaWrapper.InvokeFunctionAsync(functionName, functionParameters);
                Console.WriteLine($"The answer when we {operation} the two numbers is: {answer}.");
            }

            uiWrapper.PressEnter();
        } while (!done);

        // Delete the function created earlier.

        uiWrapper.DisplayTitle("Clean up resources");
        // Detach the IAM policy from the IAM role.
        Console.WriteLine("First detach the IAM policy from the role.");
        success = await lambdaRoleWrapper.DetachLambdaRolePolicyAsync(policyArn, roleName);
        uiWrapper.WaitABit(15, "Let's wait for the policy to be fully detached from the role.");

        Console.WriteLine("Delete the AWS Lambda function.");
        success = await lambdaWrapper.DeleteFunctionAsync(functionName);
        if (success)
        {
            Console.WriteLine($"The {functionName} function was deleted.");
        }
        else
        {
            Console.WriteLine($"Could not remove the function {functionName}");
        }

        // Now delete the IAM role created for use with the functions
        // created by the application.
        Console.WriteLine("Now we can delete the role that we created.");
        success = await lambdaRoleWrapper.DeleteLambdaRoleAsync(roleName);
        if (success)
        {
            Console.WriteLine("The role has been successfully removed.");
        }
        else
        {
            Console.WriteLine("Couldn't delete the role.");
        }

        Console.WriteLine("The Lambda Scenario is now complete.");
        uiWrapper.PressEnter();

        // Displays a formatted list of existing functions returned by the
        // LambdaMethods.ListFunctions.
        void DisplayFunctionList(List<FunctionConfiguration> functions)
        {
            functions.ForEach(functionConfig =>
            {
                Console.WriteLine($"{functionConfig.FunctionName}\t{functionConfig.Description}");
            });
        }
    }
}


namespace LambdaActions;

using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;

public class LambdaRoleWrapper
{
    private readonly IAmazonIdentityManagementService _lambdaRoleService;

    public LambdaRoleWrapper(IAmazonIdentityManagementService lambdaRoleService)
    {
        _lambdaRoleService = lambdaRoleService;
    }

    /// <summary>
    /// Attach an AWS Identity and Access Management (IAM) role policy to the
    /// IAM role to be assumed by the AWS Lambda functions created for the scenario.
    /// </summary>
    /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param>
    /// <param name="roleName">The name of the IAM role to attach the IAM policy to.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> AttachLambdaRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _lambdaRoleService.AttachRolePolicyAsync(new AttachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    /// <summary>
    /// Create a new IAM role.
    /// </summary>
    /// <param name="roleName">The name of the IAM role to create.</param>
    /// <param name="policyDocument">The policy document for the new IAM role.</param>
    /// <returns>A string representing the ARN for newly created role.</returns>
    public async Task<string> CreateLambdaRoleAsync(string roleName, string policyDocument)
    {
        var request = new CreateRoleRequest
        {
            AssumeRolePolicyDocument = policyDocument,
            RoleName = roleName,
        };

        var response = await _lambdaRoleService.CreateRoleAsync(request);
        return response.Role.Arn;
    }

    /// <summary>
    /// Deletes an IAM role.
    /// </summary>
    /// <param name="roleName">The name of the role to delete.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> DeleteLambdaRoleAsync(string roleName)
    {
        var request = new DeleteRoleRequest
        {
            RoleName = roleName,
        };

        var response = await _lambdaRoleService.DeleteRoleAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    public async Task<bool> DetachLambdaRolePolicyAsync(string policyArn, string roleName)
    {
        var response = await _lambdaRoleService.DetachRolePolicyAsync(new DetachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
}


namespace LambdaScenarioCommon;

public class UIWrapper
{
    public readonly string SepBar = new('-', Console.WindowWidth);

    /// <summary>
    /// Show information about the AWS Lambda Basics scenario.
    /// </summary>
    public void DisplayLambdaBasicsOverview()
    {
        Console.Clear();

        DisplayTitle("Welcome to AWS Lambda Basics");
        Console.WriteLine("This example application does the following:");
        Console.WriteLine("\t1. Creates an AWS Identity and Access Management (IAM) role that will be assumed by the functions we create.");
        Console.WriteLine("\t2. Attaches an IAM role policy that has Lambda permissions.");
        Console.WriteLine("\t3. Creates a Lambda function that increments the value passed to it.");
        Console.WriteLine("\t4. Calls the increment function and passes a value.");
        Console.WriteLine("\t5. Updates the code so that the function is a simple calculator.");
        Console.WriteLine("\t6. Calls the calculator function with the values entered.");
        Console.WriteLine("\t7. Deletes the Lambda function.");
        Console.WriteLine("\t7. Detaches the IAM role policy.");
        Console.WriteLine("\t8. Deletes the IAM role.");
        PressEnter();
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPress <Enter> to continue. ");
        _ = Console.ReadLine();
        Console.WriteLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter">The string to be centered.</param>
    /// <returns>The padded string.</returns>
    public string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(SepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(SepBar);
    }

    /// <summary>
    /// Display a countdown and wait for a number of seconds.
    /// </summary>
    /// <param name="numSeconds">The number of seconds to wait.</param>
    public void WaitABit(int numSeconds, string msg)
    {
        Console.WriteLine(msg);

        // Wait for the requested number of seconds.
        for (int i = numSeconds; i > 0; i--)
        {
            System.Threading.Thread.Sleep(1000);
            Console.Write($"{i}...");
        }

        PressEnter();
    }
}
```
数値をインクリメントする Lambda ハンドラーを定義します。  

```
using Amazon.Lambda.Core;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace LambdaIncrement;

public class Function
{

    /// <summary>
    /// A simple function increments the integer parameter.
    /// </summary>
    /// <param name="input">A JSON string containing an action, which must be
    /// "increment" and a string representing the value to increment.</param>
    /// <param name="context">The context object passed by Lambda containing
    /// information about invocation, function, and execution environment.</param>
    /// <returns>A string representing the incremented value of the parameter.</returns>
    public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context)
    {
        if (input["action"] == "increment")
        {
            int inputValue = Convert.ToInt32(input["x"]);
            return inputValue + 1;
        }
        else
        {
            return 0;
        }
    }
}
```
算術演算を実行する 2 番目の Lambda ハンドラーを定義します。  

```
using Amazon.Lambda.Core;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace LambdaCalculator;

public class Function
{

    /// <summary>
    /// A simple function that takes two number in string format and performs
    /// the requested arithmetic function.
    /// </summary>
    /// <param name="input">JSON data containing an action, and x and y values.
    /// Valid actions include: add, subtract, multiply, and divide.</param>
    /// <param name="context">The context object passed by Lambda containing
    /// information about invocation, function, and execution environment.</param>
    /// <returns>A string representing the results of the calculation.</returns>
    public int FunctionHandler(Dictionary<string, string> input, ILambdaContext context)
    {
        var action = input["action"];
        int x = Convert.ToInt32(input["x"]);
        int y = Convert.ToInt32(input["y"]);
        int result;
        switch (action)
        {
            case "add":
                result = x + y;
                break;
            case "subtract":
                result = x - y;
                break;
            case "multiply":
                result = x * y;
                break;
            case "divide":
                if (y == 0)
                {
                    Console.Error.WriteLine("Divide by zero error.");
                    result = 0;
                }
                else
                    result = x / y;
                break;
            default:
                Console.Error.WriteLine($"{action} is not a valid operation.");
                result = 0;
                break;
        }
        return result;
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/CreateFunction)
  + [DeleteFunction](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteFunction)
  + [GetFunction](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetFunction)
  + [Invoke](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/Invoke)
  + [ListFunctions](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListFunctions)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionCode)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionConfiguration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_csharp_3_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates a new Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the function.</param>
    /// <param name="s3Bucket">The Amazon Simple Storage Service (Amazon S3)
    /// bucket where the zip file containing the code is located.</param>
    /// <param name="s3Key">The Amazon S3 key of the zip file.</param>
    /// <param name="role">The Amazon Resource Name (ARN) of a role with the
    /// appropriate Lambda permissions.</param>
    /// <param name="handler">The name of the handler function.</param>
    /// <returns>The Amazon Resource Name (ARN) of the newly created
    /// Lambda function.</returns>
    public async Task<string> CreateLambdaFunctionAsync(
        string functionName,
        string s3Bucket,
        string s3Key,
        string role,
        string handler)
    {
        // Defines the location for the function code.
        // S3Bucket - The S3 bucket where the file containing
        //            the source code is stored.
        // S3Key    - The name of the file containing the code.
        var functionCode = new FunctionCode
        {
            S3Bucket = s3Bucket,
            S3Key = s3Key,
        };

        var createFunctionRequest = new CreateFunctionRequest
        {
            FunctionName = functionName,
            Description = "Created by the Lambda .NET API",
            Code = functionCode,
            Handler = handler,
            Runtime = Runtime.Dotnet6,
            Role = role,
        };

        var reponse = await _lambdaService.CreateFunctionAsync(createFunctionRequest);
        return reponse.FunctionArn;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[CreateFunction](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/CreateFunction)」を参照してください。**

### `DeleteFunction`
<a name="lambda_DeleteFunction_csharp_3_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an AWS Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to
    /// delete.</param>
    /// <returns>A Boolean value that indicates the success of the action.</returns>
    public async Task<bool> DeleteFunctionAsync(string functionName)
    {
        var request = new DeleteFunctionRequest
        {
            FunctionName = functionName,
        };

        var response = await _lambdaService.DeleteFunctionAsync(request);

        // A return value of NoContent means that the request was processed.
        // In this case, the function was deleted, and the return value
        // is intentionally blank.
        return response.HttpStatusCode == System.Net.HttpStatusCode.NoContent;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteFunction](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/DeleteFunction)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_csharp_3_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Gets information about a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function for
    /// which to retrieve information.</param>
    /// <returns>Async Task.</returns>
    public async Task<FunctionConfiguration> GetFunctionAsync(string functionName)
    {
        var functionRequest = new GetFunctionRequest
        {
            FunctionName = functionName,
        };

        var response = await _lambdaService.GetFunctionAsync(functionRequest);
        return response.Configuration;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetFunction](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/GetFunction)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_csharp_3_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Invoke a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to
    /// invoke.</param
    /// <param name="parameters">The parameter values that will be passed to the function.</param>
    /// <returns>A System Threading Task.</returns>
    public async Task<string> InvokeFunctionAsync(
        string functionName,
        string parameters)
    {
        var payload = parameters;
        var request = new InvokeRequest
        {
            FunctionName = functionName,
            Payload = payload,
        };

        var response = await _lambdaService.InvokeAsync(request);
        MemoryStream stream = response.Payload;
        string returnValue = System.Text.Encoding.UTF8.GetString(stream.ToArray());
        return returnValue;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[Invoke](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/Invoke)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_csharp_3_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of Lambda functions.
    /// </summary>
    /// <returns>A list of FunctionConfiguration objects.</returns>
    public async Task<List<FunctionConfiguration>> ListFunctionsAsync()
    {
        var functionList = new List<FunctionConfiguration>();

        var functionPaginator =
            _lambdaService.Paginators.ListFunctions(new ListFunctionsRequest());
        await foreach (var function in functionPaginator.Functions)
        {
            functionList.Add(function);
        }

        return functionList;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/ListFunctions)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_csharp_3_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Update an existing Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the Lambda function to update.</param>
    /// <param name="bucketName">The bucket where the zip file containing
    /// the Lambda function code is stored.</param>
    /// <param name="key">The key name of the source code file.</param>
    /// <returns>Async Task.</returns>
    public async Task UpdateFunctionCodeAsync(
        string functionName,
        string bucketName,
        string key)
    {
        var functionCodeRequest = new UpdateFunctionCodeRequest
        {
            FunctionName = functionName,
            Publish = true,
            S3Bucket = bucketName,
            S3Key = key,
        };

        var response = await _lambdaService.UpdateFunctionCodeAsync(functionCodeRequest);
        Console.WriteLine($"The Function was last modified at {response.LastModified}.");
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[UpdateFunctionCode](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionCode)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_csharp_3_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Lambda#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Update the code of a Lambda function.
    /// </summary>
    /// <param name="functionName">The name of the function to update.</param>
    /// <param name="functionHandler">The code that performs the function's actions.</param>
    /// <param name="environmentVariables">A dictionary of environment variables.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> UpdateFunctionConfigurationAsync(
        string functionName,
        string functionHandler,
        Dictionary<string, string> environmentVariables)
    {
        var request = new UpdateFunctionConfigurationRequest
        {
            Handler = functionHandler,
            FunctionName = functionName,
            Environment = new Amazon.Lambda.Model.Environment { Variables = environmentVariables },
        };

        var response = await _lambdaService.UpdateFunctionConfigurationAsync(request);

        Console.WriteLine(response.LastModified);

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/lambda-2015-03-31/UpdateFunctionConfiguration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_csharp_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for .NET**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_csharp_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for .NET**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/FeedbackSentimentAnalyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

### S3 Object Lambda でデータを変換する
<a name="cross_ServerlessS3DataTransformation_csharp_3_topic"></a>

次のコード例では、S3 Object Lambda でアプリケーションのデータを変換する方法を示しています。

**SDK for .NET**  
 オブジェクトがリクエストしたクライアントまたはアプリケーションのニーズに合うように、標準の S3 GET リクエストにカスタムコードを追加し、S3 から取得したリクエストされたオブジェクトを変更する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/S3ObjectLambdaFunction) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Lambda
+ Amazon S3

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_csharp_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda 関数での Amazon RDS データベースへの接続。  

```
using System.Data;
using System.Text.Json;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using MySql.Data.MySqlClient;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace aws_rds;

public class InputModel
{
    public string key1 { get; set; }
    public string key2 { get; set; }
}

public class Function
{
    /// <summary>
    // Handles the Lambda function execution for connecting to RDS using IAM authentication.
    /// </summary>
    /// <param name="input">The input event data passed to the Lambda function</param>
    /// <param name="context">The Lambda execution context that provides runtime information</param>
    /// <returns>A response object containing the execution result</returns>

    public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
    {
        // Sample Input: {"body": "{\"key1\":\"20\", \"key2\":\"25\"}"}
        var input = JsonSerializer.Deserialize<InputModel>(request.Body);

        /// Obtain authentication token
        var authToken = RDSAuthTokenGenerator.GenerateAuthToken(
            Environment.GetEnvironmentVariable("RDS_ENDPOINT"),
            Convert.ToInt32(Environment.GetEnvironmentVariable("RDS_PORT")),
            Environment.GetEnvironmentVariable("RDS_USERNAME")
        );

        /// Build the Connection String with the Token 
        string connectionString = $"Server={Environment.GetEnvironmentVariable("RDS_ENDPOINT")};" +
                                  $"Port={Environment.GetEnvironmentVariable("RDS_PORT")};" +
                                  $"Uid={Environment.GetEnvironmentVariable("RDS_USERNAME")};" +
                                  $"Pwd={authToken};";


        try
        {
            await using var connection = new MySqlConnection(connectionString);
            await connection.OpenAsync();

            const string sql = "SELECT @param1 + @param2 AS Sum";

            await using var command = new MySqlCommand(sql, connection);
            command.Parameters.AddWithValue("@param1", int.Parse(input.key1 ?? "0"));
            command.Parameters.AddWithValue("@param2", int.Parse(input.key2 ?? "0"));

            await using var reader = await command.ExecuteReaderAsync();
            if (await reader.ReadAsync())
            {
                int result = reader.GetInt32("Sum");

                //Sample Response: {"statusCode":200,"body":"{\"message\":\"The sum is: 45\"}","isBase64Encoded":false}
                return new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = JsonSerializer.Serialize(new { message = $"The sum is: {result}" })
                };
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }

        return new APIGatewayProxyResponse
        {
            StatusCode = 500,
            Body = JsonSerializer.Serialize(new { error = "Internal server error" })
        };
    }
}
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_csharp_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.KinesisEvents;
using AWS.Lambda.Powertools.Logging;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace KinesisIntegrationSampleCode;

public class Function
{
    // Powertools Logger requires an environment variables against your function
    // POWERTOOLS_SERVICE_NAME
    [Logging(LogEvent = true)]
    public async Task FunctionHandler(KinesisEvent evnt, ILambdaContext context)
    {
        if (evnt.Records.Count == 0)
        {
            Logger.LogInformation("Empty Kinesis Event received");
            return;
        }

        foreach (var record in evnt.Records)
        {
            try
            {
                Logger.LogInformation($"Processed Event with EventId: {record.EventId}");
                string data = await GetRecordDataAsync(record.Kinesis, context);
                Logger.LogInformation($"Data: {data}");
                // TODO: Do interesting work based on the new data
            }
            catch (Exception ex)
            {
                Logger.LogError($"An error occurred {ex.Message}");
                throw;
            }
        }
        Logger.LogInformation($"Successfully processed {evnt.Records.Count} records.");
    }

    private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context)
    {
        byte[] bytes = record.Data.ToArray();
        string data = Encoding.UTF8.GetString(bytes);
        await Task.CompletedTask; //Placeholder for actual async work
        return data;
    }
}
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_csharp_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での DynamoDB イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Text.Json;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace AWSLambda_DDB;

public class Function
{
    public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
    {
        context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records...");

        foreach (var record in dynamoEvent.Records)
        {
            context.Logger.LogInformation($"Event ID: {record.EventID}");
            context.Logger.LogInformation($"Event Name: {record.EventName}");

            context.Logger.LogInformation(JsonSerializer.Serialize(record));
        }

        context.Logger.LogInformation("Stream processing complete.");
    }
}
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_csharp_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Amazon DocumentDB イベントの消費。  

```
using Amazon.Lambda.Core;
using System.Text.Json;
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
//Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace LambdaDocDb;

public class Function
{
    
     /// <summary>
    /// Lambda function entry point to process Amazon DocumentDB events.
    /// </summary>
    /// <param name="event">The Amazon DocumentDB event.</param>
    /// <param name="context">The Lambda context object.</param>
    /// <returns>A string to indicate successful processing.</returns>
    public string FunctionHandler(Event evnt, ILambdaContext context)
    {
        
        foreach (var record in evnt.Events)
        {
            ProcessDocumentDBEvent(record, context);
        }

        return "OK";
    }

     private void ProcessDocumentDBEvent(DocumentDBEventRecord record, ILambdaContext context)
    {
        
        var eventData = record.Event;
        var operationType = eventData.OperationType;
        var databaseName = eventData.Ns.Db;
        var collectionName = eventData.Ns.Coll;
        var fullDocument = JsonSerializer.Serialize(eventData.FullDocument, new JsonSerializerOptions { WriteIndented = true });

        context.Logger.LogLine($"Operation type: {operationType}");
        context.Logger.LogLine($"Database: {databaseName}");
        context.Logger.LogLine($"Collection: {collectionName}");
        context.Logger.LogLine($"Full document:\n{fullDocument}");
    }



    public class Event
    {
        [JsonPropertyName("eventSourceArn")]
        public string EventSourceArn { get; set; }

        [JsonPropertyName("events")]
        public List<DocumentDBEventRecord> Events { get; set; }

        [JsonPropertyName("eventSource")]
        public string EventSource { get; set; }
    }

    public class DocumentDBEventRecord
    {
        [JsonPropertyName("event")]
        public EventData Event { get; set; }
    }

    public class EventData
    {
        [JsonPropertyName("_id")]
        public IdData Id { get; set; }

        [JsonPropertyName("clusterTime")]
        public ClusterTime ClusterTime { get; set; }

        [JsonPropertyName("documentKey")]
        public DocumentKey DocumentKey { get; set; }

        [JsonPropertyName("fullDocument")]
        public Dictionary<string, object> FullDocument { get; set; }

        [JsonPropertyName("ns")]
        public Namespace Ns { get; set; }

        [JsonPropertyName("operationType")]
        public string OperationType { get; set; }
    }

    public class IdData
    {
        [JsonPropertyName("_data")]
        public string Data { get; set; }
    }

    public class ClusterTime
    {
        [JsonPropertyName("$timestamp")]
        public Timestamp Timestamp { get; set; }
    }

    public class Timestamp
    {
        [JsonPropertyName("t")]
        public long T { get; set; }

        [JsonPropertyName("i")]
        public int I { get; set; }
    }

    public class DocumentKey
    {
        [JsonPropertyName("_id")]
        public Id Id { get; set; }
    }

    public class Id
    {
        [JsonPropertyName("$oid")]
        public string Oid { get; set; }
    }

    public class Namespace
    {
        [JsonPropertyName("db")]
        public string Db { get; set; }

        [JsonPropertyName("coll")]
        public string Coll { get; set; }
    }
}
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_csharp_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Amazon MSK イベントの消費。  

```
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.KafkaEvents;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace MSKLambda;

public class Function
{
    
    
    /// <param name="input">The event for the Lambda function handler to process.</param>
    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    /// <returns></returns>
    public void FunctionHandler(KafkaEvent evnt, ILambdaContext context)
    {

        foreach (var record in evnt.Records)
        {
            Console.WriteLine("Key:" + record.Key); 
            foreach (var eventRecord in record.Value)
            {
                var valueBytes = eventRecord.Value.ToArray();    
                var valueText = Encoding.UTF8.GetString(valueBytes);
                
                Console.WriteLine("Message:" + valueText);
            }
        }
    }
    

}
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_csharp_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
.NET を使用して Lambda で S3 イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using System;
using Amazon.Lambda.S3Events;
using System.Web;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace S3Integration
{
    public class Function
    {
        private static AmazonS3Client _s3Client;
        public Function() : this(null)
        {
        }

        internal Function(AmazonS3Client s3Client)
        {
            _s3Client = s3Client ?? new AmazonS3Client();
        }

        public async Task<string> Handler(S3Event evt, ILambdaContext context)
        {
            try
            {
                if (evt.Records.Count <= 0)
                {
                    context.Logger.LogLine("Empty S3 Event received");
                    return string.Empty;
                }

                var bucket = evt.Records[0].S3.Bucket.Name;
                var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key);

                context.Logger.LogLine($"Request is for {bucket} and {key}");

                var objectResult = await _s3Client.GetObjectAsync(bucket, key);

                context.Logger.LogLine($"Returning {objectResult.Key}");

                return objectResult.Key;
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"Error processing request - {e.Message}");

                return string.Empty;
            }
        }
    }
}
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_csharp_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を検索し、設定および実行する方法を確認してください。
.NET を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.Lambda.Core;
using Amazon.Lambda.SNSEvents;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SnsIntegration;

public class Function
{
    public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context)
    {
        foreach (var record in evnt.Records)
        {
            await ProcessRecordAsync(record, context);
        }
        context.Logger.LogInformation("done");
    }

    private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
    {
        try
        {
            context.Logger.LogInformation($"Processed record {record.Sns.Message}");

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
        catch (Exception e)
        {
            //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ.
            context.Logger.LogError($"An error occurred");
            throw;
        }
    }
}
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_csharp_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SqsIntegrationSampleCode
{
    public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context)
    {
        foreach (var message in evnt.Records)
        {
            await ProcessMessageAsync(message, context);
        }

        context.Logger.LogInformation("done");
    }

    private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context)
    {
        try
        {
            context.Logger.LogInformation($"Processed message {message.Body}");

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
        catch (Exception e)
        {
            //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ.
            context.Logger.LogError($"An error occurred");
            throw;
        }

    }
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_csharp_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using System.Text;
using System.Text.Json.Serialization;
using Amazon.Lambda.Core;
using Amazon.Lambda.KinesisEvents;
using AWS.Lambda.Powertools.Logging;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace KinesisIntegration;

public class Function
{
    // Powertools Logger requires an environment variables against your function
    // POWERTOOLS_SERVICE_NAME
    [Logging(LogEvent = true)]
    public async Task<StreamsEventResponse> FunctionHandler(KinesisEvent evnt, ILambdaContext context)
    {
        if (evnt.Records.Count == 0)
        {
            Logger.LogInformation("Empty Kinesis Event received");
            return new StreamsEventResponse();
        }

        foreach (var record in evnt.Records)
        {
            try
            {
                Logger.LogInformation($"Processed Event with EventId: {record.EventId}");
                string data = await GetRecordDataAsync(record.Kinesis, context);
                Logger.LogInformation($"Data: {data}");
                // TODO: Do interesting work based on the new data
            }
            catch (Exception ex)
            {
                Logger.LogError($"An error occurred {ex.Message}");
                /* Since we are working with streams, we can return the failed item immediately.
                   Lambda will immediately begin to retry processing from this failed item onwards. */
                return new StreamsEventResponse
                {
                    BatchItemFailures = new List<StreamsEventResponse.BatchItemFailure>
                    {
                        new StreamsEventResponse.BatchItemFailure { ItemIdentifier = record.Kinesis.SequenceNumber }
                    }
                };
            }
        }
        Logger.LogInformation($"Successfully processed {evnt.Records.Count} records.");
        return new StreamsEventResponse();
    }

    private async Task<string> GetRecordDataAsync(KinesisEvent.Record record, ILambdaContext context)
    {
        byte[] bytes = record.Data.ToArray();
        string data = Encoding.UTF8.GetString(bytes);
        await Task.CompletedTask; //Placeholder for actual async work
        return data;
    }
}

public class StreamsEventResponse
{
    [JsonPropertyName("batchItemFailures")]
    public IList<BatchItemFailure> BatchItemFailures { get; set; }
    public class BatchItemFailure
    {
        [JsonPropertyName("itemIdentifier")]
        public string ItemIdentifier { get; set; }
    }
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_csharp_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での DynamoDB のバッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System.Text.Json;
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace AWSLambda_DDB;

public class Function
{
    public StreamsEventResponse FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)

    {
        context.Logger.LogInformation($"Beginning to process {dynamoEvent.Records.Count} records...");
        List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new List<StreamsEventResponse.BatchItemFailure>();
        StreamsEventResponse streamsEventResponse = new StreamsEventResponse();

        foreach (var record in dynamoEvent.Records)
        {
            try
            {
                var sequenceNumber = record.Dynamodb.SequenceNumber;
                context.Logger.LogInformation(sequenceNumber);
            }
            catch (Exception ex)
            {
                context.Logger.LogError(ex.Message);
                batchItemFailures.Add(new StreamsEventResponse.BatchItemFailure() { ItemIdentifier = record.Dynamodb.SequenceNumber });
            }
        }

        if (batchItemFailures.Count > 0)
        {
            streamsEventResponse.BatchItemFailures = batchItemFailures;
        }

        context.Logger.LogInformation("Stream processing complete.");
        return streamsEventResponse;
    }
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_csharp_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace sqsSample;

public class Function
{
    public async Task<SQSBatchResponse> FunctionHandler(SQSEvent evnt, ILambdaContext context)
    {
        List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new List<SQSBatchResponse.BatchItemFailure>();
        foreach(var message in evnt.Records)
        {
            try
            {
                //process your message
                await ProcessMessageAsync(message, context);
            }
            catch (System.Exception)
            {
                //Add failed message identifier to the batchItemFailures list
                batchItemFailures.Add(new SQSBatchResponse.BatchItemFailure{ItemIdentifier=message.MessageId}); 
            }
        }
        return new SQSBatchResponse(batchItemFailures);
    }

    private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context)
    {
        if (String.IsNullOrEmpty(message.Body))
        {
            throw new Exception("No Body in SQS Message.");
        }
        context.Logger.LogInformation($"Processed message {message.Body}");
        // TODO: Do interesting work based on the new message
        await Task.CompletedTask;
    }
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_csharp_3_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for .NET**  
 .NET SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-dotnet-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# を使用した MediaConvert の例 SDK for .NET
<a name="csharp_3_mediaconvert_code_examples"></a>

次のコード例は、MediaConvert AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello MediaConvert
<a name="mediaconvert_Hello_csharp_3_topic"></a>

次のコード例は、 AWS Elemental MediaConvertの使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/MediaConvert#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.MediaConvert;
using Amazon.MediaConvert.Model;

namespace MediaConvertActions;

public static class HelloMediaConvert
{
    static async Task Main(string[] args)
    {
        // Create the client using the default profile.
        var mediaConvertClient = new AmazonMediaConvertClient();

        Console.WriteLine($"Hello AWS Elemental MediaConvert! Your MediaConvert Jobs are:");
        Console.WriteLine();

        // You can use await and any of the async methods to get a response.
        // Let's get some MediaConvert jobs.
        var response = await mediaConvertClient.ListJobsAsync(
            new ListJobsRequest()
            {
                MaxResults = 10
            }
            );

        foreach (var job in response.Jobs)
        {
            Console.WriteLine($"\tJob: {job.Id} status {job.Status}");
            Console.WriteLine();
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeEndpoints](https://docs.aws.amazon.com/goto/DotNetSDKV3/mediaconvert-2017-08-29/DescribeEndpoints)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateJob`
<a name="mediaconvert_CreateJob_csharp_3_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/MediaConvert#code-examples)での設定と実行の方法を確認してください。
ファイルの場所、クライアント、ラッパーを設定します。  

```
        // MediaConvert role Amazon Resource Name (ARN).
        // For information on creating this role, see
        // https://docs.aws.amazon.com/mediaconvert/latest/ug/creating-the-iam-role-in-mediaconvert-configured.html.
        var mediaConvertRole = _configuration["mediaConvertRoleARN"];

        // Include the file input and output locations in settings.json or settings.local.json.
        var fileInput = _configuration["fileInput"];
        var fileOutput = _configuration["fileOutput"];

        AmazonMediaConvertClient mcClient = new AmazonMediaConvertClient();

        var wrapper = new MediaConvertWrapper(mcClient);
```

```
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Creating job for input file {fileInput}.");
        var jobId = await wrapper.CreateJob(mediaConvertRole!, fileInput!, fileOutput!);
        Console.WriteLine($"Created job with Job ID: {jobId}");
        Console.WriteLine(new string('-', 80));
```
ラッパーメソッドを使用してジョブを作成し、ジョブ ID を返します。  

```
    /// <summary>
    /// Create a job to convert a media file.
    /// </summary>
    /// <param name="mediaConvertRole">The Amazon Resource Name (ARN) of the media convert role, as specified here:
    /// https://docs.aws.amazon.com/mediaconvert/latest/ug/creating-the-iam-role-in-mediaconvert-configured.html</param>
    /// <param name="fileInput">The Amazon Simple Storage Service (Amazon S3) location of the input media file.</param>
    /// <param name="fileOutput">The Amazon S3 location for the output media file.</param>
    /// <returns>The ID of the new job.</returns>
    public async Task<string> CreateJob(string mediaConvertRole, string fileInput,
        string fileOutput)
    {
        CreateJobRequest createJobRequest = new CreateJobRequest
        {
            Role = mediaConvertRole
        };

        createJobRequest.UserMetadata.Add("Customer", "Amazon");

        JobSettings jobSettings = new JobSettings
        {
            AdAvailOffset = 0,
            TimecodeConfig = new TimecodeConfig
            {
                Source = TimecodeSource.EMBEDDED
            }
        };
        createJobRequest.Settings = jobSettings;

        #region OutputGroup

        OutputGroup ofg = new OutputGroup
        {
            Name = "File Group",
            OutputGroupSettings = new OutputGroupSettings
            {
                Type = OutputGroupType.FILE_GROUP_SETTINGS,
                FileGroupSettings = new FileGroupSettings
                {
                    Destination = fileOutput
                }
            }
        };

        Output output = new Output
        {
            NameModifier = "_1"
        };

        #region VideoDescription

        VideoDescription vdes = new VideoDescription
        {
            ScalingBehavior = ScalingBehavior.DEFAULT,
            TimecodeInsertion = VideoTimecodeInsertion.DISABLED,
            AntiAlias = AntiAlias.ENABLED,
            Sharpness = 50,
            AfdSignaling = AfdSignaling.NONE,
            DropFrameTimecode = DropFrameTimecode.ENABLED,
            RespondToAfd = RespondToAfd.NONE,
            ColorMetadata = ColorMetadata.INSERT,
            CodecSettings = new VideoCodecSettings
            {
                Codec = VideoCodec.H_264
            }
        };
        output.VideoDescription = vdes;

        H264Settings h264 = new H264Settings
        {
            InterlaceMode = H264InterlaceMode.PROGRESSIVE,
            NumberReferenceFrames = 3,
            Syntax = H264Syntax.DEFAULT,
            Softness = 0,
            GopClosedCadence = 1,
            GopSize = 90,
            Slices = 1,
            GopBReference = H264GopBReference.DISABLED,
            SlowPal = H264SlowPal.DISABLED,
            SpatialAdaptiveQuantization = H264SpatialAdaptiveQuantization.ENABLED,
            TemporalAdaptiveQuantization = H264TemporalAdaptiveQuantization.ENABLED,
            FlickerAdaptiveQuantization = H264FlickerAdaptiveQuantization.DISABLED,
            EntropyEncoding = H264EntropyEncoding.CABAC,
            Bitrate = 5000000,
            FramerateControl = H264FramerateControl.SPECIFIED,
            RateControlMode = H264RateControlMode.CBR,
            CodecProfile = H264CodecProfile.MAIN,
            Telecine = H264Telecine.NONE,
            MinIInterval = 0,
            AdaptiveQuantization = H264AdaptiveQuantization.HIGH,
            CodecLevel = H264CodecLevel.AUTO,
            FieldEncoding = H264FieldEncoding.PAFF,
            SceneChangeDetect = H264SceneChangeDetect.ENABLED,
            QualityTuningLevel = H264QualityTuningLevel.SINGLE_PASS,
            FramerateConversionAlgorithm =
                H264FramerateConversionAlgorithm.DUPLICATE_DROP,
            UnregisteredSeiTimecode = H264UnregisteredSeiTimecode.DISABLED,
            GopSizeUnits = H264GopSizeUnits.FRAMES,
            ParControl = H264ParControl.SPECIFIED,
            NumberBFramesBetweenReferenceFrames = 2,
            RepeatPps = H264RepeatPps.DISABLED,
            FramerateNumerator = 30,
            FramerateDenominator = 1,
            ParNumerator = 1,
            ParDenominator = 1
        };
        output.VideoDescription.CodecSettings.H264Settings = h264;

        #endregion VideoDescription

        #region AudioDescription

        AudioDescription ades = new AudioDescription
        {
            LanguageCodeControl = AudioLanguageCodeControl.FOLLOW_INPUT,
            // This name matches one specified in the following Inputs.
            AudioSourceName = "Audio Selector 1",
            CodecSettings = new AudioCodecSettings
            {
                Codec = AudioCodec.AAC
            }
        };

        AacSettings aac = new AacSettings
        {
            AudioDescriptionBroadcasterMix = AacAudioDescriptionBroadcasterMix.NORMAL,
            RateControlMode = AacRateControlMode.CBR,
            CodecProfile = AacCodecProfile.LC,
            CodingMode = AacCodingMode.CODING_MODE_2_0,
            RawFormat = AacRawFormat.NONE,
            SampleRate = 48000,
            Specification = AacSpecification.MPEG4,
            Bitrate = 64000
        };
        ades.CodecSettings.AacSettings = aac;
        output.AudioDescriptions.Add(ades);

        #endregion AudioDescription

        #region Mp4 Container

        output.ContainerSettings = new ContainerSettings
        {
            Container = ContainerType.MP4
        };
        Mp4Settings mp4 = new Mp4Settings
        {
            CslgAtom = Mp4CslgAtom.INCLUDE,
            FreeSpaceBox = Mp4FreeSpaceBox.EXCLUDE,
            MoovPlacement = Mp4MoovPlacement.PROGRESSIVE_DOWNLOAD
        };
        output.ContainerSettings.Mp4Settings = mp4;

        #endregion Mp4 Container

        ofg.Outputs.Add(output);
        createJobRequest.Settings.OutputGroups.Add(ofg);

        #endregion OutputGroup

        #region Input

        Input input = new Input
        {
            FilterEnable = InputFilterEnable.AUTO,
            PsiControl = InputPsiControl.USE_PSI,
            FilterStrength = 0,
            DeblockFilter = InputDeblockFilter.DISABLED,
            DenoiseFilter = InputDenoiseFilter.DISABLED,
            TimecodeSource = InputTimecodeSource.EMBEDDED,
            FileInput = fileInput
        };

        AudioSelector audsel = new AudioSelector
        {
            Offset = 0,
            DefaultSelection = AudioDefaultSelection.NOT_DEFAULT,
            ProgramSelection = 1,
            SelectorType = AudioSelectorType.TRACK
        };
        audsel.Tracks.Add(1);
        input.AudioSelectors.Add("Audio Selector 1", audsel);

        input.VideoSelector = new VideoSelector
        {
            ColorSpace = ColorSpace.FOLLOW
        };

        createJobRequest.Settings.Inputs.Add(input);

        #endregion Input

        CreateJobResponse createJobResponse =
            await _amazonMediaConvert.CreateJobAsync(createJobRequest);

        var jobId = createJobResponse.Job.Id;

        return jobId;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/mediaconvert-2017-08-29/CreateJob)」を参照してください。

### `GetJob`
<a name="mediaconvert_GetJob_csharp_3_topic"></a>

次のコード例は、`GetJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/MediaConvert#code-examples)での設定と実行の方法を確認してください。
ファイルの場所、クライアント、ラッパーを設定します。  

```
        // MediaConvert role Amazon Resource Name (ARN).
        // For information on creating this role, see
        // https://docs.aws.amazon.com/mediaconvert/latest/ug/creating-the-iam-role-in-mediaconvert-configured.html.
        var mediaConvertRole = _configuration["mediaConvertRoleARN"];

        // Include the file input and output locations in settings.json or settings.local.json.
        var fileInput = _configuration["fileInput"];
        var fileOutput = _configuration["fileOutput"];

        AmazonMediaConvertClient mcClient = new AmazonMediaConvertClient();

        var wrapper = new MediaConvertWrapper(mcClient);
```
ID でジョブを取得する。  

```
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Getting job information for Job ID {jobId}");
        var job = await wrapper.GetJobById(jobId);
        Console.WriteLine($"Job {job.Id} created on {job.CreatedAt:d} has status {job.Status}.");
        Console.WriteLine(new string('-', 80));
```

```
    /// <summary>
    /// Get the job information for a job by its ID.
    /// </summary>
    /// <param name="jobId">The ID of the job.</param>
    /// <returns>The Job object.</returns>
    public async Task<Job> GetJobById(string jobId)
    {
        var jobResponse = await _amazonMediaConvert.GetJobAsync(
                new GetJobRequest
                {
                    Id = jobId
                });

        return jobResponse.Job;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/mediaconvert-2017-08-29/GetJob)」を参照してください。

### `ListJobs`
<a name="mediaconvert_ListJobs_csharp_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/MediaConvert#code-examples)での設定と実行の方法を確認してください。
ファイルの場所、クライアント、ラッパーを設定します。  

```
        // MediaConvert role Amazon Resource Name (ARN).
        // For information on creating this role, see
        // https://docs.aws.amazon.com/mediaconvert/latest/ug/creating-the-iam-role-in-mediaconvert-configured.html.
        var mediaConvertRole = _configuration["mediaConvertRoleARN"];

        // Include the file input and output locations in settings.json or settings.local.json.
        var fileInput = _configuration["fileInput"];
        var fileOutput = _configuration["fileOutput"];

        AmazonMediaConvertClient mcClient = new AmazonMediaConvertClient();

        var wrapper = new MediaConvertWrapper(mcClient);
```
特定のステータスのジョブを一覧表示します。  

```
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Listing all complete jobs.");
        var completeJobs = await wrapper.ListAllJobsByStatus(JobStatus.COMPLETE);
        completeJobs.ForEach(j =>
        {
            Console.WriteLine($"Job {j.Id} created on {j.CreatedAt:d} has status {j.Status}.");
        });
```
ページネーターを使用してジョブを一覧表示します。  

```
    /// <summary>
    /// List all of the jobs with a particular status using a paginator.
    /// </summary>
    /// <param name="status">The status to use when listing jobs.</param>
    /// <returns>The list of jobs matching the status.</returns>
    public async Task<List<Job>> ListAllJobsByStatus(JobStatus? status = null)
    {
        var returnedJobs = new List<Job>();

        var paginatedJobs = _amazonMediaConvert.Paginators.ListJobs(
                new ListJobsRequest
                {
                    Status = status
                });

        // Get the entire list using the paginator.
        await foreach (var job in paginatedJobs.Jobs)
        {
            returnedJobs.Add(job);
        }

        return returnedJobs;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/mediaconvert-2017-08-29/ListJobs)」を参照してください。

# を使用した Amazon MSK の例 SDK for .NET
<a name="csharp_3_kafka_code_examples"></a>

次のコード例は、Amazon MSK AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_csharp_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での Amazon MSK イベントの消費。  

```
using System.Text;
using Amazon.Lambda.Core;
using Amazon.Lambda.KafkaEvents;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace MSKLambda;

public class Function
{
    
    
    /// <param name="input">The event for the Lambda function handler to process.</param>
    /// <param name="context">The ILambdaContext that provides methods for logging and describing the Lambda environment.</param>
    /// <returns></returns>
    public void FunctionHandler(KafkaEvent evnt, ILambdaContext context)
    {

        foreach (var record in evnt.Records)
        {
            Console.WriteLine("Key:" + record.Key); 
            foreach (var eventRecord in record.Value)
            {
                var valueBytes = eventRecord.Value.ToArray();    
                var valueText = Encoding.UTF8.GetString(valueBytes);
                
                Console.WriteLine("Message:" + valueText);
            }
        }
    }
    

}
```

# を使用した Organizations の例 SDK for .NET
<a name="csharp_3_organizations_code_examples"></a>

次のコード例は、Organizations AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AttachPolicy`
<a name="organizations_AttachPolicy_csharp_3_topic"></a>

次のコード例は、`AttachPolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to attach an AWS Organizations policy to an organization,
    /// an organizational unit, or an account.
    /// </summary>
    public class AttachPolicy
    {
        /// <summary>
        /// Initializes the Organizations client object and then calls the
        /// AttachPolicyAsync method to attach the policy to the root
        /// organization.
        /// </summary>
        public static async Task Main()
        {
            IAmazonOrganizations client = new AmazonOrganizationsClient();
            var policyId = "p-00000000";
            var targetId = "r-0000";

            var request = new AttachPolicyRequest
            {
                PolicyId = policyId,
                TargetId = targetId,
            };

            var response = await client.AttachPolicyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully attached Policy ID {policyId} to Target ID: {targetId}.");
            }
            else
            {
                Console.WriteLine("Was not successful in attaching the policy.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンスの*「[AttachPolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/AttachPolicy)」を参照してください。

### `CreateAccount`
<a name="organizations_CreateAccount_csharp_3_topic"></a>

次のコード例は、`CreateAccount` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates a new AWS Organizations account.
    /// </summary>
    public class CreateAccount
    {
        /// <summary>
        /// Initializes an Organizations client object and uses it to create
        /// the new account with the name specified in accountName.
        /// </summary>
        public static async Task Main()
        {
            IAmazonOrganizations client = new AmazonOrganizationsClient();
            var accountName = "ExampleAccount";
            var email = "someone@example.com";

            var request = new CreateAccountRequest
            {
                AccountName = accountName,
                Email = email,
            };

            var response = await client.CreateAccountAsync(request);
            var status = response.CreateAccountStatus;

            Console.WriteLine($"The staus of {status.AccountName} is {status.State}.");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateAccount](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreateAccount)」を参照してください。

### `CreateOrganization`
<a name="organizations_CreateOrganization_csharp_3_topic"></a>

次のコード例は、`CreateOrganization` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates an organization in AWS Organizations.
    /// </summary>
    public class CreateOrganization
    {
        /// <summary>
        /// Creates an Organizations client object and then uses it to create
        /// a new organization with the default user as the administrator, and
        /// then displays information about the new organization.
        /// </summary>
        public static async Task Main()
        {
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var response = await client.CreateOrganizationAsync(new CreateOrganizationRequest
            {
                FeatureSet = "ALL",
            });

            Organization newOrg = response.Organization;

            Console.WriteLine($"Organization: {newOrg.Id} Main Accoount: {newOrg.MasterAccountId}");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateOrganization](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreateOrganization)」を参照してください。

### `CreateOrganizationalUnit`
<a name="organizations_CreateOrganizationalUnit_csharp_3_topic"></a>

次のコード例は、`CreateOrganizationalUnit` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates a new organizational unit in AWS Organizations.
    /// </summary>
    public class CreateOrganizationalUnit
    {
        /// <summary>
        /// Initializes an Organizations client object and then uses it to call
        /// the CreateOrganizationalUnit method. If the call succeeds, it
        /// displays information about the new organizational unit.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var orgUnitName = "ProductDevelopmentUnit";

            var request = new CreateOrganizationalUnitRequest
            {
                Name = orgUnitName,
                ParentId = "r-0000",
            };

            var response = await client.CreateOrganizationalUnitAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully created organizational unit: {orgUnitName}.");
                Console.WriteLine($"Organizational unit {orgUnitName} Details");
                Console.WriteLine($"ARN: {response.OrganizationalUnit.Arn} Id: {response.OrganizationalUnit.Id}");
            }
            else
            {
                Console.WriteLine("Could not create new organizational unit.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateOrganizationalUnit](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreateOrganizationalUnit)」を参照してください。

### `CreatePolicy`
<a name="organizations_CreatePolicy_csharp_3_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Creates a new AWS Organizations Policy.
    /// </summary>
    public class CreatePolicy
    {
        /// <summary>
        /// Initializes the AWS Organizations client object, uses it to
        /// create a new Organizations Policy, and then displays information
        /// about the newly created Policy.
        /// </summary>
        public static async Task Main()
        {
            IAmazonOrganizations client = new AmazonOrganizationsClient();
            var policyContent = "{" +
                "   \"Version\": \"2012-10-17\"," +
                "	\"Statement\" : [{" +
                    "	\"Action\" : [\"s3:*\"]," +
                    "	\"Effect\" : \"Allow\"," +
                    "	\"Resource\" : \"*\"" +
                "}]" +
            "}";

            try
            {
                var response = await client.CreatePolicyAsync(new CreatePolicyRequest
                {
                    Content = policyContent,
                    Description = "Enables admins of attached accounts to delegate all Amazon S3 permissions",
                    Name = "AllowAllS3Actions",
                    Type = "SERVICE_CONTROL_POLICY",
                });

                Policy policy = response.Policy;
                Console.WriteLine($"{policy.PolicySummary.Name} has the following content: {policy.Content}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/CreatePolicy)」を参照してください。

### `DeleteOrganization`
<a name="organizations_DeleteOrganization_csharp_3_topic"></a>

次のコード例は、`DeleteOrganization` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to delete an existing organization using the AWS
    /// Organizations Service.
    /// </summary>
    public class DeleteOrganization
    {
        /// <summary>
        /// Initializes the Organizations client and then calls
        /// DeleteOrganizationAsync to delete the organization.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var response = await client.DeleteOrganizationAsync(new DeleteOrganizationRequest());

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Successfully deleted organization.");
            }
            else
            {
                Console.WriteLine("Could not delete organization.");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteOrganization](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DeleteOrganization)」を参照してください。

### `DeleteOrganizationalUnit`
<a name="organizations_DeleteOrganizationalUnit_csharp_3_topic"></a>

次のコード例は、`DeleteOrganizationalUnit` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to delete an existing AWS Organizations organizational unit.
    /// </summary>
    public class DeleteOrganizationalUnit
    {
        /// <summary>
        /// Initializes the Organizations client object and calls
        /// DeleteOrganizationalUnitAsync to delete the organizational unit
        /// with the selected ID.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var orgUnitId = "ou-0000-00000000";

            var request = new DeleteOrganizationalUnitRequest
            {
                OrganizationalUnitId = orgUnitId,
            };

            var response = await client.DeleteOrganizationalUnitAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully deleted the organizational unit with ID: {orgUnitId}.");
            }
            else
            {
                Console.WriteLine($"Could not delete the organizational unit with ID: {orgUnitId}.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteOrganizationalUnit](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DeleteOrganizationalUnit)」を参照してください。

### `DeletePolicy`
<a name="organizations_DeletePolicy_csharp_3_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Deletes an existing AWS Organizations policy.
    /// </summary>
    public class DeletePolicy
    {
        /// <summary>
        /// Initializes the Organizations client object and then uses it to
        /// delete the policy with the specified policyId.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var policyId = "p-00000000";

            var request = new DeletePolicyRequest
            {
                PolicyId = policyId,
            };

            var response = await client.DeletePolicyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully deleted Policy: {policyId}.");
            }
            else
            {
                Console.WriteLine($"Could not delete Policy: {policyId}.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeletePolicy](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DeletePolicy)」を参照してください。

### `DetachPolicy`
<a name="organizations_DetachPolicy_csharp_3_topic"></a>

次のコード例は、`DetachPolicy` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to detach a policy from an AWS Organizations organization,
    /// organizational unit, or account.
    /// </summary>
    public class DetachPolicy
    {
        /// <summary>
        /// Initializes the Organizations client object and uses it to call
        /// DetachPolicyAsync to detach the policy.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var policyId = "p-00000000";
            var targetId = "r-0000";

            var request = new DetachPolicyRequest
            {
                PolicyId = policyId,
                TargetId = targetId,
            };

            var response = await client.DetachPolicyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Successfully detached policy with Policy Id: {policyId}.");
            }
            else
            {
                Console.WriteLine("Could not detach the policy.");
            }
        }
    }
```
+  API の詳細については、[AWS SDK for .NET API リファレンス](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/DetachPolicy) の「*DetachPolicy*」を参照してください。

### `ListAccounts`
<a name="organizations_ListAccounts_csharp_3_topic"></a>

次のコード例は、`ListAccounts` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Uses the AWS Organizations service to list the accounts associated
    /// with the default account.
    /// </summary>
    public class ListAccounts
    {
        /// <summary>
        /// Creates the Organizations client and then calls its
        /// ListAccountsAsync method.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var request = new ListAccountsRequest
            {
                MaxResults = 5,
            };

            var response = new ListAccountsResponse();
            try
            {
                do
                {
                    response = await client.ListAccountsAsync(request);
                    response.Accounts.ForEach(a => DisplayAccounts(a));
                    if (response.NextToken is not null)
                    {
                        request.NextToken = response.NextToken;
                    }
                }
                while (response.NextToken is not null);
            }
            catch (AWSOrganizationsNotInUseException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Displays information about an Organizations account.
        /// </summary>
        /// <param name="account">An Organizations account for which to display
        /// information on the console.</param>
        private static void DisplayAccounts(Account account)
        {
            string accountInfo = $"{account.Id} {account.Name}\t{account.Status}";

            Console.WriteLine(accountInfo);
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListAccounts](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/ListAccounts)」を参照してください。

### `ListOrganizationalUnitsForParent`
<a name="organizations_ListOrganizationalUnitsForParent_csharp_3_topic"></a>

次のコード例は、`ListOrganizationalUnitsForParent` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Lists the AWS Organizations organizational units that belong to an
    /// organization.
    /// </summary>
    public class ListOrganizationalUnitsForParent
    {
        /// <summary>
        /// Initializes the Organizations client object and then uses it to
        /// call the ListOrganizationalUnitsForParentAsync method to retrieve
        /// the list of organizational units.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            var parentId = "r-0000";

            var request = new ListOrganizationalUnitsForParentRequest
            {
                ParentId = parentId,
                MaxResults = 5,
            };

            var response = new ListOrganizationalUnitsForParentResponse();
            try
            {
                do
                {
                    response = await client.ListOrganizationalUnitsForParentAsync(request);
                    response.OrganizationalUnits.ForEach(u => DisplayOrganizationalUnit(u));
                    if (response.NextToken is not null)
                    {
                        request.NextToken = response.NextToken;
                    }
                }
                while (response.NextToken is not null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Displays information about an Organizations organizational unit.
        /// </summary>
        /// <param name="unit">The OrganizationalUnit for which to display
        /// information.</param>
        public static void DisplayOrganizationalUnit(OrganizationalUnit unit)
        {
            string accountInfo = $"{unit.Id} {unit.Name}\t{unit.Arn}";

            Console.WriteLine(accountInfo);
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListOrganizationalUnitsForParent](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/ListOrganizationalUnitsForParent)」を参照してください。

### `ListPolicies`
<a name="organizations_ListPolicies_csharp_3_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Organizations#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Organizations;
    using Amazon.Organizations.Model;

    /// <summary>
    /// Shows how to list the AWS Organizations policies associated with an
    /// organization.
    /// </summary>
    public class ListPolicies
    {
        /// <summary>
        /// Initializes an Organizations client object, and then calls its
        /// ListPoliciesAsync method.
        /// </summary>
        public static async Task Main()
        {
            // Create the client object using the default account.
            IAmazonOrganizations client = new AmazonOrganizationsClient();

            // The value for the Filter parameter is required and must must be
            // one of the following:
            //     AISERVICES_OPT_OUT_POLICY
            //     BACKUP_POLICY
            //     SERVICE_CONTROL_POLICY
            //     TAG_POLICY
            var request = new ListPoliciesRequest
            {
                Filter = "SERVICE_CONTROL_POLICY",
                MaxResults = 5,
            };

            var response = new ListPoliciesResponse();
            try
            {
                do
                {
                    response = await client.ListPoliciesAsync(request);
                    response.Policies.ForEach(p => DisplayPolicies(p));
                    if (response.NextToken is not null)
                    {
                        request.NextToken = response.NextToken;
                    }
                }
                while (response.NextToken is not null);
            }
            catch (AWSOrganizationsNotInUseException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Displays information about the Organizations policies associated
        /// with an organization.
        /// </summary>
        /// <param name="policy">An Organizations policy summary to display
        /// information on the console.</param>
        private static void DisplayPolicies(PolicySummary policy)
        {
            string policyInfo = $"{policy.Id} {policy.Name}\t{policy.Description}";

            Console.WriteLine(policyInfo);
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/DotNetSDKV3/organizations-2016-11-28/ListPolicies)」を参照してください。

# を使用した Partner Central の例 SDK for .NET
<a name="csharp_3_partnercentral-selling_code_examples"></a>

次のコード例は、 Partner Central AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateOpportunity`
<a name="partnercentral-selling_CreateOpportunity_csharp_3_topic"></a>

次のコード例は、`CreateOpportunity` を使用する方法を示しています。

**SDK for .NET**  
オポチュニティを作成します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// PDX-License-Identifier: Apache-2.0

using System;
using Newtonsoft.Json;
using Amazon;
using Amazon.Runtime;
using Amazon.PartnerCentralSelling;
using Amazon.PartnerCentralSelling.Model;

namespace AWSExample
{
    class Program
    {
        static readonly string catalogToUse = "AWS";
        static async Task Main(string[] args)
        {
            // Initialize credentials from .aws/credentials file
            var credentials = new Amazon.Runtime.CredentialManagement.SharedCredentialsFile();
            if (credentials.TryGetProfile("default", out var profile))
            {
                AWSCredentials awsCredentials = profile.GetAWSCredentials(credentials);

                var client = new AmazonPartnerCentralSellingClient(awsCredentials);

                var request = new CreateOpportunityRequest
                {
                    Catalog = catalogToUse,
                    Origin = "Partner Referral",
                    Customer = new Customer
                    {
                        Account = new Account
                        {
                            Address = new Address
                            {
                                CountryCode = "US",
                                PostalCode = "99502",
                                StateOrRegion = "Alaska"
                            },
                            CompanyName = "TestCompanyName",
                            Duns = "123456789",
                            WebsiteUrl = "www.test.io",
                            Industry = "Automotive"
                        },
                        Contacts = new List<Contact>
                        {
                            new Contact
                            {
                                Email = "test@test.io",
                                FirstName = "John  ",
                                LastName = "Doe",
                                Phone = "+14444444444",
                                BusinessTitle = "test title"
                            }
                        }
                    },
                    LifeCycle = new LifeCycle
                    {
                        ReviewStatus = "Submitted",
                        TargetCloseDate = "2024-12-30"
                    },
                    Marketing = new Marketing
                    {
                        Source = "None"
                    },
                    OpportunityType = "Net New Business",
                    PrimaryNeedsFromAws = new List<string> { "Co-Sell - Architectural Validation" },
                    Project = new Project
                    {
                        Title = "Moin Test UUID",
                        CustomerBusinessProblem = "Sandbox is not working as expected",
                        CustomerUseCase = "AI Machine Learning and Analytics",
                        DeliveryModels = new List<string> { "SaaS or PaaS" },
                        ExpectedCustomerSpend = new List<ExpectedCustomerSpend>
                        {
                            new ExpectedCustomerSpend
                            {
                                Amount = "2000.0",
                                CurrencyCode = "USD",
                                Frequency = "Monthly",
                                TargetCompany = "Ibexlabs"
                            }
                        },
                        SalesActivities = new List<string> { "Initialized discussions with customer" }
                    }
                };

                try
                {
                    var response = await client.CreateOpportunityAsync(request);
                    Console.WriteLine(response.HttpStatusCode);
                    string formattedJson = JsonConvert.SerializeObject(response, Formatting.Indented);
                    Console.WriteLine(formattedJson);
                }
                catch (ValidationException ex)
                {
                    Console.WriteLine("Validation error: " + ex.Message);
                }
                catch (AmazonPartnerCentralSellingException e)
                {
                    Console.WriteLine("Failed:");
                    Console.WriteLine(e.RequestId);
                    Console.WriteLine(e.ErrorCode);
                    Console.WriteLine(e.Message);
                }
            }
            else
            {
                Console.WriteLine("Profile not found.");
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateOpportunity](https://docs.aws.amazon.com/goto/DotNetSDKV3/partnercentral-selling-2022-07-26/CreateOpportunity)」を参照してください。

### `GetOpportunity`
<a name="partnercentral-selling_GetOpportunity_csharp_3_topic"></a>

次のコード例は、`GetOpportunity` を使用する方法を示しています。

**SDK for .NET**  
オポチュニティを取得します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// PDX-License-Identifier: Apache-2.0

using System;
using Newtonsoft.Json;
using Amazon;
using Amazon.Runtime;
using Amazon.PartnerCentralSelling;
using Amazon.PartnerCentralSelling.Model;

namespace AWSExample
{
    class Program
    {
        static readonly string catalogToUse = "AWS";
        static readonly string identifier = "O1111111";
        static async Task Main(string[] args)
        {
            // Initialize credentials from .aws/credentials file
            var credentials = new Amazon.Runtime.CredentialManagement.SharedCredentialsFile();
            if (credentials.TryGetProfile("default", out var profile))
            {
                AWSCredentials awsCredentials = profile.GetAWSCredentials(credentials);

                var client = new AmazonPartnerCentralSellingClient(awsCredentials);

                var request = new GetOpportunityRequest
                {
                    Catalog = catalogToUse,
                    Identifier = identifier
                };

                try {
                    var response = await client.GetOpportunityAsync(request);
                    Console.WriteLine(response.HttpStatusCode);
                    string formattedJson = JsonConvert.SerializeObject(response, Formatting.Indented);
                    Console.WriteLine(formattedJson);
                } catch(ValidationException ex) {
                    Console.WriteLine("Validation error: " + ex.Message);
                } catch (AmazonPartnerCentralSellingException e) {
                    Console.WriteLine("Failed:");
                    Console.WriteLine(e.RequestId);
                    Console.WriteLine(e.ErrorCode);
                    Console.WriteLine(e.Message);
                }
            }
            else
            {
                Console.WriteLine("Profile not found.");
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetOpportunity](https://docs.aws.amazon.com/goto/DotNetSDKV3/partnercentral-selling-2022-07-26/GetOpportunity)」を参照してください。

### `ListOpportunities`
<a name="partnercentral-selling_ListOpportunities_csharp_3_topic"></a>

次のコード例は、`ListOpportunities` を使用する方法を示しています。

**SDK for .NET**  
オポチュニティを一覧表示します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// PDX-License-Identifier: Apache-2.0

using System;
using Newtonsoft.Json;
using Amazon;
using Amazon.Runtime;
using Amazon.PartnerCentralSelling;
using Amazon.PartnerCentralSelling.Model;

namespace AWSExample
{
    class Program
    {
        static readonly string catalogToUse = "Sandbox";
        static async Task Main(string[] args)
        {
            // Initialize credentials from .aws/credentials file
            var credentials = new Amazon.Runtime.CredentialManagement.SharedCredentialsFile();
            if (credentials.TryGetProfile("default", out var profile))
            {
                AWSCredentials awsCredentials = profile.GetAWSCredentials(credentials);

                //var config = new AmazonPartnerCentralSellingConfig()
                //{
                //    ServiceURL = "https://partnercentral-selling.us-east-1.api.aws",
                //};
                //var client = new AmazonPartnerCentralSellingClient(awsCredentials, config);
                var client = new AmazonPartnerCentralSellingClient(awsCredentials);
                var request = new ListOpportunitiesRequest
                {
                    Catalog = catalogToUse,
                    MaxResults = 2
                };

                try {
                    var response = await client.ListOpportunitiesAsync(request);
                    Console.WriteLine(response.HttpStatusCode);
                    foreach (var opportunity in response.OpportunitySummaries)
                    {
                        Console.WriteLine("Opportunity id: " + opportunity.Id);
                    }
                    string formattedJson = JsonConvert.SerializeObject(response.OpportunitySummaries, Formatting.Indented);
                    Console.WriteLine(formattedJson);
                } catch(ValidationException ex) {
                    Console.WriteLine("Validation error: " + ex.Message);
                } catch (AmazonPartnerCentralSellingException e) {
                    Console.WriteLine("Failed:");
                    Console.WriteLine(e.RequestId);
                    Console.WriteLine(e.ErrorCode);
                    Console.WriteLine(e.Message);
                }
            }
            else
            {
                Console.WriteLine("Profile not found.");
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListOpportunities](https://docs.aws.amazon.com/goto/DotNetSDKV3/partnercentral-selling-2022-07-26/ListOpportunities)」を参照してください。

# を使用した Amazon Pinpoint の例 SDK for .NET
<a name="csharp_3_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendMessages`
<a name="pinpoint_SendMessages_csharp_3_topic"></a>

次のコード例は、`SendMessages` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Pinpoint#code-examples)での設定と実行の方法を確認してください。
E メールメッセージを送信します。  

```
using Amazon;
using Amazon.Pinpoint;
using Amazon.Pinpoint.Model;
using Microsoft.Extensions.Configuration;

namespace SendEmailMessage;

public class SendEmailMainClass
{
    public static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("settings.json") // Load test settings from .json file.
        .AddJsonFile("settings.local.json",
            true) // Optionally load local settings.
        .Build();

        // The AWS Region that you want to use to send the email. For a list of
        // AWS Regions where the Amazon Pinpoint API is available, see 
        // https://docs.aws.amazon.com/pinpoint/latest/apireference/
        string region = "us-east-1";

        // The "From" address. This address has to be verified in Amazon Pinpoint 
        // in the region you're using to send email.
        string senderAddress = configuration["SenderAddress"]!;

        // The address on the "To" line. If your Amazon Pinpoint account is in
        // the sandbox, this address also has to be verified. 
        string toAddress = configuration["ToAddress"]!;

        // The Amazon Pinpoint project/application ID to use when you send this message.
        // Make sure that the SMS channel is enabled for the project or application
        // that you choose.
        string appId = configuration["AppId"]!;

        try
        {
            await SendEmailMessage(region, appId, toAddress, senderAddress);
        }
        catch (Exception ex)
        {
            Console.WriteLine("The message wasn't sent. Error message: " + ex.Message);
        }
    }

    public static async Task<MessageResponse> SendEmailMessage(
        string region, string appId, string toAddress, string senderAddress)
    {
        var client = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region));

        // The subject line of the email.
        string subject = "Amazon Pinpoint Email test";

        // The body of the email for recipients whose email clients don't 
        // support HTML content.
        string textBody = @"Amazon Pinpoint Email Test (.NET)"
                          + "\n---------------------------------"
                          + "\nThis email was sent using the Amazon Pinpoint API using the AWS SDK for .NET.";

        // The body of the email for recipients whose email clients support
        // HTML content.
        string htmlBody = @"<html>"
                          + "\n<head></head>"
                          + "\n<body>"
                          + "\n  <h1>Amazon Pinpoint Email Test (AWS SDK for .NET)</h1>"
                          + "\n  <p>This email was sent using the "
                          + "\n    <a href='https://aws.amazon.com/pinpoint/'>Amazon Pinpoint</a> API "
                          + "\n    using the <a href='https://aws.amazon.com/sdk-for-net/'>AWS SDK for .NET</a>"
                          + "\n  </p>"
                          + "\n</body>"
                          + "\n</html>";

        // The character encoding the you want to use for the subject line and
        // message body of the email.
        string charset = "UTF-8";

        var sendRequest = new SendMessagesRequest
        {
            ApplicationId = appId,
            MessageRequest = new MessageRequest
            {
                Addresses = new Dictionary<string, AddressConfiguration>
                {
                    {
                        toAddress,
                        new AddressConfiguration
                        {
                            ChannelType = ChannelType.EMAIL
                        }
                    }
                },
                MessageConfiguration = new DirectMessageConfiguration
                {
                    EmailMessage = new EmailMessage
                    {
                        FromAddress = senderAddress,
                        SimpleEmail = new SimpleEmail
                        {
                            HtmlPart = new SimpleEmailPart
                            {
                                Charset = charset,
                                Data = htmlBody
                            },
                            TextPart = new SimpleEmailPart
                            {
                                Charset = charset,
                                Data = textBody
                            },
                            Subject = new SimpleEmailPart
                            {
                                Charset = charset,
                                Data = subject
                            }
                        }
                    }
                }
            }
        };
        Console.WriteLine("Sending message...");
        SendMessagesResponse response = await client.SendMessagesAsync(sendRequest);
        Console.WriteLine("Message sent!");
        return response.MessageResponse;
    }
}
```
SMS メッセージを送信します。  

```
using Amazon;
using Amazon.Pinpoint;
using Amazon.Pinpoint.Model;
using Microsoft.Extensions.Configuration;

namespace SendSmsMessage;

public class SendSmsMessageMainClass
{
    public static async Task Main(string[] args)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        // The AWS Region that you want to use to send the message. For a list of
        // AWS Regions where the Amazon Pinpoint API is available, see
        // https://docs.aws.amazon.com/pinpoint/latest/apireference/
        string region = "us-east-1";

        // The phone number or short code to send the message from. The phone number
        // or short code that you specify has to be associated with your Amazon Pinpoint
        // account. For best results, specify long codes in E.164 format.
        string originationNumber = configuration["OriginationNumber"]!;

        // The recipient's phone number.  For best results, you should specify the
        // phone number in E.164 format.
        string destinationNumber = configuration["DestinationNumber"]!;

        // The Pinpoint project/ application ID to use when you send this message.
        // Make sure that the SMS channel is enabled for the project or application
        // that you choose.
        string appId = configuration["AppId"]!;

        // The type of SMS message that you want to send. If you plan to send
        // time-sensitive content, specify TRANSACTIONAL. If you plan to send
        // marketing-related content, specify PROMOTIONAL.
        MessageType messageType = MessageType.TRANSACTIONAL;

        // The registered keyword associated with the originating short code.
        string? registeredKeyword = configuration["RegisteredKeyword"];

        // The sender ID to use when sending the message. Support for sender ID
        // varies by country or region. For more information, see
        // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html
        string? senderId = configuration["SenderId"];

        try
        {
            var response = await SendSmsMessage(region, appId, destinationNumber,
                originationNumber, registeredKeyword, senderId, messageType);
            Console.WriteLine($"Message sent to {response.MessageResponse.Result.Count} recipient(s).");
            foreach (var messageResultValue in
                     response.MessageResponse.Result.Select(r => r.Value))
            {
                Console.WriteLine($"{messageResultValue.MessageId} Status: {messageResultValue.DeliveryStatus}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("The message wasn't sent. Error message: " + ex.Message);
        }
    }

    public static async Task<SendMessagesResponse> SendSmsMessage(
        string region, string appId, string destinationNumber, string originationNumber,
        string? keyword, string? senderId, MessageType messageType)
    {

        // The content of the SMS message.
        string message = "This message was sent through Amazon Pinpoint using" +
                         " the AWS SDK for .NET. Reply STOP to opt out.";


        var client = new AmazonPinpointClient(RegionEndpoint.GetBySystemName(region));

        SendMessagesRequest sendRequest = new SendMessagesRequest
        {
            ApplicationId = appId,
            MessageRequest = new MessageRequest
            {
                Addresses =
                    new Dictionary<string, AddressConfiguration>
                    {
                        {
                            destinationNumber,
                            new AddressConfiguration { ChannelType = ChannelType.SMS }
                        }
                    },
                MessageConfiguration = new DirectMessageConfiguration
                {
                    SMSMessage = new SMSMessage
                    {
                        Body = message,
                        MessageType = MessageType.TRANSACTIONAL,
                        OriginationNumber = originationNumber,
                        SenderId = senderId,
                        Keyword = keyword
                    }
                }
            }
        };
        SendMessagesResponse response = await client.SendMessagesAsync(sendRequest);
        return response;
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[SendMessage](https://docs.aws.amazon.com/goto/DotNetSDKV3/pinpoint-2016-12-01/SendMessages)」を参照してください。

# を使用した Amazon Polly の例 SDK for .NET
<a name="csharp_3_polly_code_examples"></a>

次のコード例は、Amazon Polly AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DeleteLexicon`
<a name="polly_DeleteLexicon_csharp_3_topic"></a>

次のコード例は、`DeleteLexicon` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Polly#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Polly;
    using Amazon.Polly.Model;

    /// <summary>
    /// Deletes an existing Amazon Polly lexicon using the AWS SDK for .NET.
    /// </summary>
    public class DeleteLexicon
    {
        public static async Task Main()
        {
            string lexiconName = "SampleLexicon";

            var client = new AmazonPollyClient();

            var success = await DeletePollyLexiconAsync(client, lexiconName);

            if (success)
            {
                Console.WriteLine($"Successfully deleted {lexiconName}.");
            }
            else
            {
                Console.WriteLine($"Could not delete {lexiconName}.");
            }
        }

        /// <summary>
        /// Deletes the named Amazon Polly lexicon.
        /// </summary>
        /// <param name="client">The initialized Amazon Polly client object.</param>
        /// <param name="lexiconName">The name of the Amazon Polly lexicon to
        /// delete.</param>
        /// <returns>A Boolean value indicating the success of the operation.</returns>
        public static async Task<bool> DeletePollyLexiconAsync(
            AmazonPollyClient client,
            string lexiconName)
        {
            var deleteLexiconRequest = new DeleteLexiconRequest()
            {
                Name = lexiconName,
            };

            var response = await client.DeleteLexiconAsync(deleteLexiconRequest);

            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteLexicon](https://docs.aws.amazon.com/goto/DotNetSDKV3/polly-2016-06-10/DeleteLexicon)」を参照してください。

### `DescribeVoices`
<a name="polly_DescribeVoices_csharp_3_topic"></a>

次のコード例は、`DescribeVoices` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Polly#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Polly;
    using Amazon.Polly.Model;

    public class DescribeVoices
    {
        public static async Task Main()
        {
            var client = new AmazonPollyClient();

            var allVoicesRequest = new DescribeVoicesRequest();
            var enUsVoicesRequest = new DescribeVoicesRequest()
            {
                LanguageCode = "en-US",
            };

            try
            {
                string nextToken;
                do
                {
                    var allVoicesResponse = await client.DescribeVoicesAsync(allVoicesRequest);
                    nextToken = allVoicesResponse.NextToken;
                    allVoicesRequest.NextToken = nextToken;

                    Console.WriteLine("\nAll voices: ");
                    allVoicesResponse.Voices.ForEach(voice =>
                    {
                        DisplayVoiceInfo(voice);
                    });
                }
                while (nextToken is not null);

                do
                {
                    var enUsVoicesResponse = await client.DescribeVoicesAsync(enUsVoicesRequest);
                    nextToken = enUsVoicesResponse.NextToken;
                    enUsVoicesRequest.NextToken = nextToken;

                    Console.WriteLine("\nen-US voices: ");
                    enUsVoicesResponse.Voices.ForEach(voice =>
                    {
                        DisplayVoiceInfo(voice);
                    });
                }
                while (nextToken is not null);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught: " + ex.Message);
            }
        }

        public static void DisplayVoiceInfo(Voice voice)
        {
            Console.WriteLine($" Name: {voice.Name}\tGender: {voice.Gender}\tLanguageName: {voice.LanguageName}");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeVoices](https://docs.aws.amazon.com/goto/DotNetSDKV3/polly-2016-06-10/DescribeVoices)」を参照してください。

### `GetLexicon`
<a name="polly_GetLexicon_csharp_3_topic"></a>

次のコード例は、`GetLexicon` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Polly#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Polly;
    using Amazon.Polly.Model;

    /// <summary>
    /// Retrieves information about a specific Amazon Polly lexicon.
    /// </summary>
    public class GetLexicon
    {
        public static async Task Main(string[] args)
        {
            string lexiconName = "SampleLexicon";

            var client = new AmazonPollyClient();

            await GetPollyLexiconAsync(client, lexiconName);
        }

        public static async Task GetPollyLexiconAsync(AmazonPollyClient client, string lexiconName)
        {
            var getLexiconRequest = new GetLexiconRequest()
            {
                Name = lexiconName,
            };

            try
            {
                var response = await client.GetLexiconAsync(getLexiconRequest);
                Console.WriteLine($"Lexicon:\n Name: {response.Lexicon.Name}");
                Console.WriteLine($"Content: {response.Lexicon.Content}");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetLexicon](https://docs.aws.amazon.com/goto/DotNetSDKV3/polly-2016-06-10/GetLexicon)」を参照してください。

### `ListLexicons`
<a name="polly_ListLexicons_csharp_3_topic"></a>

次のコード例は、`ListLexicons` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Polly#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Polly;
    using Amazon.Polly.Model;

    /// <summary>
    /// Lists the Amazon Polly lexicons that have been defined. By default,
    /// lists the lexicons that are defined in the same AWS Region as the default
    /// user. To view Amazon Polly lexicons that are defined in a different AWS
    /// Region, supply it as a parameter to the Amazon Polly constructor.
    /// </summary>
    public class ListLexicons
    {
        public static async Task Main()
        {
            var client = new AmazonPollyClient();
            var request = new ListLexiconsRequest();

            try
            {
                Console.WriteLine("All voices: ");

                do
                {
                    var response = await client.ListLexiconsAsync(request);
                    request.NextToken = response.NextToken;

                    response.Lexicons.ForEach(lexicon =>
                    {
                        var attributes = lexicon.Attributes;
                        Console.WriteLine($"Name: {lexicon.Name}");
                        Console.WriteLine($"\tAlphabet: {attributes.Alphabet}");
                        Console.WriteLine($"\tLanguageCode: {attributes.LanguageCode}");
                        Console.WriteLine($"\tLastModified: {attributes.LastModified}");
                        Console.WriteLine($"\tLexemesCount: {attributes.LexemesCount}");
                        Console.WriteLine($"\tLexiconArn: {attributes.LexiconArn}");
                        Console.WriteLine($"\tSize: {attributes.Size}");
                    });
                }
                while (request.NextToken is not null);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListLexicons](https://docs.aws.amazon.com/goto/DotNetSDKV3/polly-2016-06-10/ListLexicons)」を参照してください。

### `PutLexicon`
<a name="polly_PutLexicon_csharp_3_topic"></a>

次のコード例は、`PutLexicon` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Polly#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Polly;
    using Amazon.Polly.Model;

    /// <summary>
    /// Creates a new Amazon Polly lexicon using the AWS SDK for .NET.
    /// </summary>
    public class PutLexicon
    {
        public static async Task Main()
        {
            string lexiconContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<lexicon version=\"1.0\" xmlns=\"http://www.w3.org/2005/01/pronunciation-lexicon\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
                "xsi:schemaLocation=\"http://www.w3.org/2005/01/pronunciation-lexicon http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd\" " +
                "alphabet=\"ipa\" xml:lang=\"en-US\">" +
                "<lexeme><grapheme>test1</grapheme><alias>test2</alias></lexeme>" +
                "</lexicon>";
            string lexiconName = "SampleLexicon";

            var client = new AmazonPollyClient();
            var putLexiconRequest = new PutLexiconRequest()
            {
                Name = lexiconName,
                Content = lexiconContent,
            };

            try
            {
                var response = await client.PutLexiconAsync(putLexiconRequest);
                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine($"Successfully created Lexicon: {lexiconName}.");
                }
                else
                {
                    Console.WriteLine($"Could not create Lexicon: {lexiconName}.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught: " + ex.Message);
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutLexicon](https://docs.aws.amazon.com/goto/DotNetSDKV3/polly-2016-06-10/PutLexicon)」を参照してください。

### `SynthesizeSpeech`
<a name="polly_SynthesizeSpeech_csharp_3_topic"></a>

次のコード例は、`SynthesizeSpeech` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Polly#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Polly;
    using Amazon.Polly.Model;

    public class SynthesizeSpeech
    {
        public static async Task Main()
        {
            string outputFileName = "speech.mp3";
            string text = "Twas brillig, and the slithy toves did gyre and gimbol in the wabe";

            var client = new AmazonPollyClient();
            var response = await PollySynthesizeSpeech(client, text);

            WriteSpeechToStream(response.AudioStream, outputFileName);
        }

        /// <summary>
        /// Calls the Amazon Polly SynthesizeSpeechAsync method to convert text
        /// to speech.
        /// </summary>
        /// <param name="client">The Amazon Polly client object used to connect
        /// to the Amazon Polly service.</param>
        /// <param name="text">The text to convert to speech.</param>
        /// <returns>A SynthesizeSpeechResponse object that includes an AudioStream
        /// object with the converted text.</returns>
        private static async Task<SynthesizeSpeechResponse> PollySynthesizeSpeech(IAmazonPolly client, string text)
        {
            var synthesizeSpeechRequest = new SynthesizeSpeechRequest()
            {
                OutputFormat = OutputFormat.Mp3,
                VoiceId = VoiceId.Joanna,
                Text = text,
            };

            var synthesizeSpeechResponse =
                await client.SynthesizeSpeechAsync(synthesizeSpeechRequest);

            return synthesizeSpeechResponse;
        }

        /// <summary>
        /// Writes the AudioStream returned from the call to
        /// SynthesizeSpeechAsync to a file in MP3 format.
        /// </summary>
        /// <param name="audioStream">The AudioStream returned from the
        /// call to the SynthesizeSpeechAsync method.</param>
        /// <param name="outputFileName">The full path to the file in which to
        /// save the audio stream.</param>
        private static void WriteSpeechToStream(Stream audioStream, string outputFileName)
        {
            var outputStream = new FileStream(
                outputFileName,
                FileMode.Create,
                FileAccess.Write);
            byte[] buffer = new byte[2 * 1024];
            int readBytes;

            while ((readBytes = audioStream.Read(buffer, 0, 2 * 1024)) > 0)
            {
                outputStream.Write(buffer, 0, readBytes);
            }

            // Flushes the buffer to avoid losing the last second or so of
            // the synthesized text.
            outputStream.Flush();
            Console.WriteLine($"Saved {outputFileName} to disk.");
        }
    }
```
 AWS SDK を使用して Amazon Polly で音声マークを使用してテキストから音声を合成します。  

```
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Polly;
    using Amazon.Polly.Model;

    public class SynthesizeSpeechMarks
    {
        public static async Task Main()
        {
            var client = new AmazonPollyClient();
            string outputFileName = "speechMarks.json";

            var synthesizeSpeechRequest = new SynthesizeSpeechRequest()
            {
                OutputFormat = OutputFormat.Json,
                SpeechMarkTypes = new List<string>
                {
                    SpeechMarkType.Viseme,
                    SpeechMarkType.Word,
                },
                VoiceId = VoiceId.Joanna,
                Text = "This is a sample text to be synthesized.",
            };

            try
            {
                using (var outputStream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write))
                {
                    var synthesizeSpeechResponse = await client.SynthesizeSpeechAsync(synthesizeSpeechRequest);
                    var buffer = new byte[2 * 1024];
                    int readBytes;

                    var inputStream = synthesizeSpeechResponse.AudioStream;
                    while ((readBytes = inputStream.Read(buffer, 0, 2 * 1024)) > 0)
                    {
                        outputStream.Write(buffer, 0, readBytes);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[SynthesizeSpeech](https://docs.aws.amazon.com/goto/DotNetSDKV3/polly-2016-06-10/SynthesizeSpeech)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_csharp_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for .NET**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/FeedbackSentimentAnalyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# を使用した Amazon RDS の例 SDK for .NET
<a name="csharp_3_rds_code_examples"></a>

次のコード例は、Amazon RDS AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon RDS
<a name="rds_Hello_csharp_3_topic"></a>

次のコード例は、Amazon RDS の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
using System;
using System.Threading.Tasks;
using Amazon.RDS;
using Amazon.RDS.Model;

namespace RDSActions;

public static class HelloRds
{
    static async Task Main(string[] args)
    {
        var rdsClient = new AmazonRDSClient();

        Console.WriteLine($"Hello Amazon RDS! Following are some of your DB instances:");
        Console.WriteLine();

        // You can use await and any of the async methods to get a response.
        // Let's get the first twenty DB instances.
        var response = await rdsClient.DescribeDBInstancesAsync(
            new DescribeDBInstancesRequest()
            {
                MaxRecords = 20 // Must be between 20 and 100.
            });

        foreach (var instance in response.DBInstances)
        {
            Console.WriteLine($"\tDB name: {instance.DBName}");
            Console.WriteLine($"\tArn: {instance.DBInstanceArn}");
            Console.WriteLine($"\tIdentifier: {instance.DBInstanceIdentifier}");
            Console.WriteLine();
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="rds_Scenario_GetStartedInstances_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム DB パラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用するように設定した DB インスタンスを作成します。DB インスタンスにはデータベースも含まれています。
+ インスタンスのスナップショットを取得します。
+ インスタンスとパラメータグループを削除します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
/// <summary>
/// Scenario for RDS DB instance example.
/// </summary>
public class RDSInstanceScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This .NET example performs the following tasks:
    1.  Returns a list of the available DB engine families using the DescribeDBEngineVersionsAsync method.
    2.  Selects an engine family and creates a custom DB parameter group using the CreateDBParameterGroupAsync method.
    3.  Gets the parameter groups using the DescribeDBParameterGroupsAsync method.
    4.  Gets parameters in the group using the DescribeDBParameters method.
    5.  Parses and displays parameters in the group.
    6.  Modifies both the auto_increment_offset and auto_increment_increment parameters
        using the ModifyDBParameterGroupAsync method.
    7.  Gets and displays the updated parameters using the DescribeDBParameters method with a source of "user".
    8.  Gets a list of allowed engine versions using the DescribeDBEngineVersionsAsync method.
    9.  Displays and selects from a list of micro instance classes available for the selected engine and version.
    10. Creates an RDS DB instance that contains a MySql database and uses the parameter group
        using the CreateDBInstanceAsync method.
    11. Waits for DB instance to be ready using the DescribeDBInstancesAsync method.
    12. Prints out the connection endpoint string for the new DB instance.
    13. Creates a snapshot of the DB instance using the CreateDBSnapshotAsync method.
    14. Waits for DB snapshot to be ready using the DescribeDBSnapshots method.
    15. Deletes the DB instance using the DeleteDBInstanceAsync method.
    16. Waits for DB instance to be deleted using the DescribeDbInstances method.
    17. Deletes the parameter group using the DeleteDBParameterGroupAsync.
    */

    private static readonly string sepBar = new('-', 80);
    private static RDSWrapper rdsWrapper = null!;
    private static ILogger logger = null!;
    private static readonly string engine = "mysql";
    static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon RDS service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonRDS>()
                    .AddTransient<RDSWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        }).CreateLogger<RDSInstanceScenario>();

        rdsWrapper = host.Services.GetRequiredService<RDSWrapper>();

        Console.WriteLine(sepBar);
        Console.WriteLine(
            "Welcome to the Amazon Relational Database Service (Amazon RDS) DB instance scenario example.");
        Console.WriteLine(sepBar);

        try
        {
            var parameterGroupFamily = await ChooseParameterGroupFamily();

            var parameterGroup = await CreateDbParameterGroup(parameterGroupFamily);

            var parameters = await DescribeParametersInGroup(parameterGroup.DBParameterGroupName,
                new List<string> { "auto_increment_offset", "auto_increment_increment" });

            await ModifyParameters(parameterGroup.DBParameterGroupName, parameters);

            await DescribeUserSourceParameters(parameterGroup.DBParameterGroupName);

            var engineVersionChoice = await ChooseDbEngineVersion(parameterGroupFamily);

            var instanceChoice = await ChooseDbInstanceClass(engine, engineVersionChoice.EngineVersion);

            var newInstanceIdentifier = "Example-Instance-" + DateTime.Now.Ticks;

            var newInstance = await CreateRdsNewInstance(parameterGroup, engine, engineVersionChoice.EngineVersion,
                instanceChoice.DBInstanceClass, newInstanceIdentifier);
            if (newInstance != null)
            {
                DisplayConnectionString(newInstance);

                await CreateSnapshot(newInstance);

                await DeleteRdsInstance(newInstance);
            }

            await DeleteParameterGroup(parameterGroup);

            Console.WriteLine("Scenario complete.");
            Console.WriteLine(sepBar);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "There was a problem executing the scenario.");
        }
    }

    /// <summary>
    /// Choose the RDS DB parameter group family from a list of available options.
    /// </summary>
    /// <returns>The selected parameter group family.</returns>
    public static async Task<string> ChooseParameterGroupFamily()
    {
        Console.WriteLine(sepBar);
        // 1. Get a list of available engines.
        var engines = await rdsWrapper.DescribeDBEngineVersions(engine);

        Console.WriteLine("1. The following is a list of available DB parameter group families:");
        int i = 1;
        var parameterGroupFamilies = engines.GroupBy(e => e.DBParameterGroupFamily).ToList();
        foreach (var parameterGroupFamily in parameterGroupFamilies)
        {
            // List the available parameter group families.
            Console.WriteLine(
                $"\t{i}. Family: {parameterGroupFamily.Key}");
            i++;
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > parameterGroupFamilies.Count)
        {
            Console.WriteLine("Select an available DB parameter group family by entering a number from the list above:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }
        var parameterGroupFamilyChoice = parameterGroupFamilies[choiceNumber - 1];
        Console.WriteLine(sepBar);
        return parameterGroupFamilyChoice.Key;
    }

    /// <summary>
    /// Create and get information on a DB parameter group.
    /// </summary>
    /// <param name="dbParameterGroupFamily">The DBParameterGroupFamily for the new DB parameter group.</param>
    /// <returns>The new DBParameterGroup.</returns>
    public static async Task<DBParameterGroup> CreateDbParameterGroup(string dbParameterGroupFamily)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine($"2. Create new DB parameter group with family {dbParameterGroupFamily}:");

        var parameterGroup = await rdsWrapper.CreateDBParameterGroup(
            "ExampleParameterGroup-" + DateTime.Now.Ticks,
            dbParameterGroupFamily, "New example parameter group");

        var groupInfo =
            await rdsWrapper.DescribeDBParameterGroups(parameterGroup
                .DBParameterGroupName);

        Console.WriteLine(
            $"3. New DB parameter group: \n\t{groupInfo[0].Description}, \n\tARN {groupInfo[0].DBParameterGroupArn}");
        Console.WriteLine(sepBar);
        return parameterGroup;
    }

    /// <summary>
    /// Get and describe parameters from a DBParameterGroup.
    /// </summary>
    /// <param name="parameterGroupName">Name of the DBParameterGroup.</param>
    /// <param name="parameterNames">Optional specific names of parameters to describe.</param>
    /// <returns>The list of requested parameters.</returns>
    public static async Task<List<Parameter>> DescribeParametersInGroup(string parameterGroupName, List<string>? parameterNames = null)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine("4. Get some parameters from the group.");
        Console.WriteLine(sepBar);

        var parameters =
            await rdsWrapper.DescribeDBParameters(parameterGroupName);

        var matchingParameters =
            parameters.Where(p => parameterNames == null || parameterNames.Contains(p.ParameterName)).ToList();

        Console.WriteLine("5. Parameter information:");
        matchingParameters.ForEach(p =>
            Console.WriteLine(
                $"\n\tParameter: {p.ParameterName}." +
                $"\n\tDescription: {p.Description}." +
                $"\n\tAllowed Values: {p.AllowedValues}." +
                $"\n\tValue: {p.ParameterValue}."));

        Console.WriteLine(sepBar);

        return matchingParameters;
    }

    /// <summary>
    /// Modify a parameter from a DBParameterGroup.
    /// </summary>
    /// <param name="parameterGroupName">Name of the DBParameterGroup.</param>
    /// <param name="parameters">The parameters to modify.</param>
    /// <returns>Async task.</returns>
    public static async Task ModifyParameters(string parameterGroupName, List<Parameter> parameters)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine("6. Modify some parameters in the group.");

        foreach (var p in parameters)
        {
            if (p.IsModifiable && p.DataType == "integer")
            {
                int newValue = 0;
                while (newValue == 0)
                {
                    Console.WriteLine(
                        $"Enter a new value for {p.ParameterName} from the allowed values {p.AllowedValues} ");

                    var choice = Console.ReadLine();
                    Int32.TryParse(choice, out newValue);
                }

                p.ParameterValue = newValue.ToString();
            }
        }

        await rdsWrapper.ModifyDBParameterGroup(parameterGroupName, parameters);

        Console.WriteLine(sepBar);
    }

    /// <summary>
    /// Describe the user source parameters in the group.
    /// </summary>
    /// <param name="parameterGroupName">Name of the DBParameterGroup.</param>
    /// <returns>Async task.</returns>
    public static async Task DescribeUserSourceParameters(string parameterGroupName)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine("7. Describe user source parameters in the group.");

        var parameters =
            await rdsWrapper.DescribeDBParameters(parameterGroupName, "user");


        parameters.ForEach(p =>
            Console.WriteLine(
                $"\n\tParameter: {p.ParameterName}." +
                $"\n\tDescription: {p.Description}." +
                $"\n\tAllowed Values: {p.AllowedValues}." +
                $"\n\tValue: {p.ParameterValue}."));

        Console.WriteLine(sepBar);
    }


    /// <summary>
    /// Choose a DB engine version.
    /// </summary>
    /// <param name="dbParameterGroupFamily">DB parameter group family for engine choice.</param>
    /// <returns>The selected engine version.</returns>
    public static async Task<DBEngineVersion> ChooseDbEngineVersion(string dbParameterGroupFamily)
    {
        Console.WriteLine(sepBar);
        // Get a list of allowed engines.
        var allowedEngines =
            await rdsWrapper.DescribeDBEngineVersions(engine, dbParameterGroupFamily);

        Console.WriteLine($"Available DB engine versions for parameter group family {dbParameterGroupFamily}:");
        int i = 1;
        foreach (var version in allowedEngines)
        {
            Console.WriteLine(
                $"\t{i}. Engine: {version.Engine} Version {version.EngineVersion}.");
            i++;
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > allowedEngines.Count)
        {
            Console.WriteLine("8. Select an available DB engine version by entering a number from the list above:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }

        var engineChoice = allowedEngines[choiceNumber - 1];
        Console.WriteLine(sepBar);
        return engineChoice;
    }

    /// <summary>
    /// Choose a DB instance class for a particular engine and engine version.
    /// </summary>
    /// <param name="engine">DB engine for DB instance choice.</param>
    /// <param name="engineVersion">DB engine version for DB instance choice.</param>
    /// <returns>The selected orderable DB instance option.</returns>
    public static async Task<OrderableDBInstanceOption> ChooseDbInstanceClass(string engine, string engineVersion)
    {
        Console.WriteLine(sepBar);
        // Get a list of allowed DB instance classes.
        var allowedInstances =
            await rdsWrapper.DescribeOrderableDBInstanceOptions(engine, engineVersion);

        Console.WriteLine($"8. Available micro DB instance classes for engine {engine} and version {engineVersion}:");
        int i = 1;

        // Filter to micro instances for this example.
        allowedInstances = allowedInstances
            .Where(i => i.DBInstanceClass.Contains("micro")).ToList();

        foreach (var instance in allowedInstances)
        {
            Console.WriteLine(
                $"\t{i}. Instance class: {instance.DBInstanceClass} (storage type {instance.StorageType})");
            i++;
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > allowedInstances.Count)
        {
            Console.WriteLine("9. Select an available DB instance class by entering a number from the list above:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }

        var instanceChoice = allowedInstances[choiceNumber - 1];
        Console.WriteLine(sepBar);
        return instanceChoice;
    }

    /// <summary>
    /// Create a new RDS DB instance.
    /// </summary>
    /// <param name="parameterGroup">Parameter group to use for the DB instance.</param>
    /// <param name="engineName">Engine to use for the DB instance.</param>
    /// <param name="engineVersion">Engine version to use for the DB instance.</param>
    /// <param name="instanceClass">Instance class to use for the DB instance.</param>
    /// <param name="instanceIdentifier">Instance identifier to use for the DB instance.</param>
    /// <returns>The new DB instance.</returns>
    public static async Task<DBInstance?> CreateRdsNewInstance(DBParameterGroup parameterGroup,
        string engineName, string engineVersion, string instanceClass, string instanceIdentifier)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine($"10. Create a new DB instance with identifier {instanceIdentifier}.");
        bool isInstanceReady = false;
        DBInstance newInstance;
        var instances = await rdsWrapper.DescribeDBInstances();
        isInstanceReady = instances.FirstOrDefault(i =>
            i.DBInstanceIdentifier == instanceIdentifier)?.DBInstanceStatus == "available";

        if (isInstanceReady)
        {
            Console.WriteLine("Instance already created.");
            newInstance = instances.First(i => i.DBInstanceIdentifier == instanceIdentifier);
        }
        else
        {
            Console.WriteLine("Please enter an admin user name:");
            var username = Console.ReadLine();

            Console.WriteLine("Please enter an admin password:");
            var password = Console.ReadLine();

            newInstance = await rdsWrapper.CreateDBInstance(
                "ExampleInstance",
                instanceIdentifier,
                parameterGroup.DBParameterGroupName,
                engineName,
                engineVersion,
                instanceClass,
                20,
                username,
                password
            );

            // 11. Wait for the DB instance to be ready.

            Console.WriteLine("11. Waiting for DB instance to be ready...");
            while (!isInstanceReady)
            {
                instances = await rdsWrapper.DescribeDBInstances(instanceIdentifier);
                isInstanceReady = instances.FirstOrDefault()?.DBInstanceStatus == "available";
                newInstance = instances.First();
                Thread.Sleep(30000);
            }
        }

        Console.WriteLine(sepBar);
        return newInstance;
    }

    /// <summary>
    /// Display a connection string for an RDS DB instance.
    /// </summary>
    /// <param name="instance">The DB instance to use to get a connection string.</param>
    public static void DisplayConnectionString(DBInstance instance)
    {
        Console.WriteLine(sepBar);
        // Display the connection string.
        Console.WriteLine("12. New DB instance connection string: ");
        Console.WriteLine(
            $"\n{engine} -h {instance.Endpoint.Address} -P {instance.Endpoint.Port} "
            + $"-u {instance.MasterUsername} -p [YOUR PASSWORD]\n");

        Console.WriteLine(sepBar);
    }

    /// <summary>
    /// Create a snapshot from an RDS DB instance.
    /// </summary>
    /// <param name="instance">DB instance to use when creating a snapshot.</param>
    /// <returns>The snapshot object.</returns>
    public static async Task<DBSnapshot> CreateSnapshot(DBInstance instance)
    {
        Console.WriteLine(sepBar);
        // Create a snapshot.
        Console.WriteLine($"13. Creating snapshot from DB instance {instance.DBInstanceIdentifier}.");
        var snapshot = await rdsWrapper.CreateDBSnapshot(instance.DBInstanceIdentifier, "ExampleSnapshot-" + DateTime.Now.Ticks);

        // Wait for the snapshot to be available
        bool isSnapshotReady = false;

        Console.WriteLine($"14. Waiting for snapshot to be ready...");
        while (!isSnapshotReady)
        {
            var snapshots = await rdsWrapper.DescribeDBSnapshots(instance.DBInstanceIdentifier);
            isSnapshotReady = snapshots.FirstOrDefault()?.Status == "available";
            snapshot = snapshots.First();
            Thread.Sleep(30000);
        }

        Console.WriteLine(
            $"Snapshot {snapshot.DBSnapshotIdentifier} status is {snapshot.Status}.");
        Console.WriteLine(sepBar);
        return snapshot;
    }

    /// <summary>
    /// Delete an RDS DB instance.
    /// </summary>
    /// <param name="instance">The DB instance to delete.</param>
    /// <returns>Async task.</returns>
    public static async Task DeleteRdsInstance(DBInstance newInstance)
    {
        Console.WriteLine(sepBar);
        // Delete the DB instance.
        Console.WriteLine($"15. Delete the DB instance {newInstance.DBInstanceIdentifier}.");
        await rdsWrapper.DeleteDBInstance(newInstance.DBInstanceIdentifier);

        // Wait for the DB instance to delete.
        Console.WriteLine($"16. Waiting for the DB instance to delete...");
        bool isInstanceDeleted = false;

        while (!isInstanceDeleted)
        {
            var instance = await rdsWrapper.DescribeDBInstances();
            isInstanceDeleted = instance.All(i => i.DBInstanceIdentifier != newInstance.DBInstanceIdentifier);
            Thread.Sleep(30000);
        }

        Console.WriteLine("DB instance deleted.");
        Console.WriteLine(sepBar);
    }

    /// <summary>
    /// Delete a DB parameter group.
    /// </summary>
    /// <param name="parameterGroup">The parameter group to delete.</param>
    /// <returns>Async task.</returns>
    public static async Task DeleteParameterGroup(DBParameterGroup parameterGroup)
    {
        Console.WriteLine(sepBar);
        // Delete the parameter group.
        Console.WriteLine($"17. Delete the DB parameter group {parameterGroup.DBParameterGroupName}.");
        await rdsWrapper.DeleteDBParameterGroup(parameterGroup.DBParameterGroupName);

        Console.WriteLine(sepBar);
    }
```
DB インスタンスアクションのシナリオで使用されるラッパーメソッド。  

```
/// <summary>
/// Wrapper methods to use Amazon Relational Database Service (Amazon RDS) with DB instance operations.
/// </summary>
public partial class RDSWrapper
{
    private readonly IAmazonRDS _amazonRDS;
    public RDSWrapper(IAmazonRDS amazonRDS)
    {
        _amazonRDS = amazonRDS;
    }


    /// <summary>
    /// Get a list of DB engine versions for a particular DB engine.
    /// </summary>
    /// <param name="engine">Name of the engine.</param>
    /// <param name="dbParameterGroupFamily">Optional parameter group family name.</param>
    /// <returns>List of DBEngineVersions.</returns>
    public async Task<List<DBEngineVersion>> DescribeDBEngineVersions(string engine,
        string dbParameterGroupFamily = null)
    {
        var response = await _amazonRDS.DescribeDBEngineVersionsAsync(
            new DescribeDBEngineVersionsRequest()
            {
                Engine = engine,
                DBParameterGroupFamily = dbParameterGroupFamily
            });
        return response.DBEngineVersions;
    }



    /// <summary>
    /// Get a list of orderable DB instance options for a specific
    /// engine and engine version.
    /// </summary>
    /// <param name="engine">Name of the engine.</param>
    /// <param name="engineVersion">Version of the engine.</param>
    /// <returns>List of OrderableDBInstanceOptions.</returns>
    public async Task<List<OrderableDBInstanceOption>> DescribeOrderableDBInstanceOptions(string engine, string engineVersion)
    {
        // Use a paginator to get a list of DB instance options.
        var results = new List<OrderableDBInstanceOption>();
        var paginateInstanceOptions = _amazonRDS.Paginators.DescribeOrderableDBInstanceOptions(
            new DescribeOrderableDBInstanceOptionsRequest()
            {
                Engine = engine,
                EngineVersion = engineVersion,
            });
        // Get the entire list using the paginator.
        await foreach (var instanceOptions in paginateInstanceOptions.OrderableDBInstanceOptions)
        {
            results.Add(instanceOptions);
        }
        return results;
    }



    /// <summary>
    /// Returns a list of DB instances.
    /// </summary>
    /// <param name="dbInstanceIdentifier">Optional name of a specific DB instance.</param>
    /// <returns>List of DB instances.</returns>
    public async Task<List<DBInstance>> DescribeDBInstances(string dbInstanceIdentifier = null)
    {
        var results = new List<DBInstance>();
        var instancesPaginator = _amazonRDS.Paginators.DescribeDBInstances(
            new DescribeDBInstancesRequest
            {
                DBInstanceIdentifier = dbInstanceIdentifier
            });
        // Get the entire list using the paginator.
        await foreach (var instances in instancesPaginator.DBInstances)
        {
            results.Add(instances);
        }
        return results;
    }



    /// <summary>
    /// Create an RDS DB instance with a particular set of properties. Use the action DescribeDBInstancesAsync
    /// to determine when the DB instance is ready to use.
    /// </summary>
    /// <param name="dbName">Name for the DB instance.</param>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <param name="parameterGroupName">DB parameter group to associate with the instance.</param>
    /// <param name="dbEngine">The engine for the DB instance.</param>
    /// <param name="dbEngineVersion">Version for the DB instance.</param>
    /// <param name="instanceClass">Class for the DB instance.</param>
    /// <param name="allocatedStorage">The amount of storage in gibibytes (GiB) to allocate to the DB instance.</param>
    /// <param name="adminName">Admin user name.</param>
    /// <param name="adminPassword">Admin user password.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> CreateDBInstance(string dbName, string dbInstanceIdentifier,
        string parameterGroupName, string dbEngine, string dbEngineVersion,
        string instanceClass, int allocatedStorage, string adminName, string adminPassword)
    {
        var response = await _amazonRDS.CreateDBInstanceAsync(
            new CreateDBInstanceRequest()
            {
                DBName = dbName,
                DBInstanceIdentifier = dbInstanceIdentifier,
                DBParameterGroupName = parameterGroupName,
                Engine = dbEngine,
                EngineVersion = dbEngineVersion,
                DBInstanceClass = instanceClass,
                AllocatedStorage = allocatedStorage,
                MasterUsername = adminName,
                MasterUserPassword = adminPassword
            });

        return response.DBInstance;
    }



    /// <summary>
    /// Delete a particular DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> DeleteDBInstance(string dbInstanceIdentifier)
    {
        var response = await _amazonRDS.DeleteDBInstanceAsync(
            new DeleteDBInstanceRequest()
            {
                DBInstanceIdentifier = dbInstanceIdentifier,
                SkipFinalSnapshot = true,
                DeleteAutomatedBackups = true
            });

        return response.DBInstance;
    }
```
DB パラメータグループのシナリオで使用されるラッパーメソッド。  

```
/// <summary>
/// Wrapper methods to use Amazon Relational Database Service (Amazon RDS) with parameter groups.
/// </summary>
public partial class RDSWrapper
{

    /// <summary>
    /// Get descriptions of DB parameter groups.
    /// </summary>
    /// <param name="name">Optional name of the DB parameter group to describe.</param>
    /// <returns>The list of DB parameter group descriptions.</returns>
    public async Task<List<DBParameterGroup>> DescribeDBParameterGroups(string name = null)
    {
        var response = await _amazonRDS.DescribeDBParameterGroupsAsync(
            new DescribeDBParameterGroupsRequest()
            {
                DBParameterGroupName = name
            });
        return response.DBParameterGroups;
    }



    /// <summary>
    /// Create a new DB parameter group. Use the action DescribeDBParameterGroupsAsync
    /// to determine when the DB parameter group is ready to use.
    /// </summary>
    /// <param name="name">Name of the DB parameter group.</param>
    /// <param name="family">Family of the DB parameter group.</param>
    /// <param name="description">Description of the DB parameter group.</param>
    /// <returns>The new DB parameter group.</returns>
    public async Task<DBParameterGroup> CreateDBParameterGroup(
        string name, string family, string description)
    {
        var response = await _amazonRDS.CreateDBParameterGroupAsync(
            new CreateDBParameterGroupRequest()
            {
                DBParameterGroupName = name,
                DBParameterGroupFamily = family,
                Description = description
            });
        return response.DBParameterGroup;
    }



    /// <summary>
    /// Update a DB parameter group. Use the action DescribeDBParameterGroupsAsync
    /// to determine when the DB parameter group is ready to use.
    /// </summary>
    /// <param name="name">Name of the DB parameter group.</param>
    /// <param name="parameters">List of parameters. Maximum of 20 per request.</param>
    /// <returns>The updated DB parameter group name.</returns>
    public async Task<string> ModifyDBParameterGroup(
        string name, List<Parameter> parameters)
    {
        var response = await _amazonRDS.ModifyDBParameterGroupAsync(
            new ModifyDBParameterGroupRequest()
            {
                DBParameterGroupName = name,
                Parameters = parameters,
            });
        return response.DBParameterGroupName;
    }



    /// <summary>
    /// Delete a DB parameter group. The group cannot be a default DB parameter group
    /// or be associated with any DB instances.
    /// </summary>
    /// <param name="name">Name of the DB parameter group.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteDBParameterGroup(string name)
    {
        var response = await _amazonRDS.DeleteDBParameterGroupAsync(
            new DeleteDBParameterGroupRequest()
            {
                DBParameterGroupName = name,
            });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }



    /// <summary>
    /// Get a list of DB parameters from a specific parameter group.
    /// </summary>
    /// <param name="dbParameterGroupName">Name of a specific DB parameter group.</param>
    /// <param name="source">Optional source for selecting parameters.</param>
    /// <returns>List of parameter values.</returns>
    public async Task<List<Parameter>> DescribeDBParameters(string dbParameterGroupName, string source = null)
    {
        var results = new List<Parameter>();
        var paginateParameters = _amazonRDS.Paginators.DescribeDBParameters(
            new DescribeDBParametersRequest()
            {
                DBParameterGroupName = dbParameterGroupName,
                Source = source
            });
        // Get the entire list using the paginator.
        await foreach (var parameters in paginateParameters.Parameters)
        {
            results.Add(parameters);
        }
        return results;
    }
```
DB スナップショットアクションのシナリオで使用されるラッパーメソッド。  

```
/// <summary>
/// Wrapper methods to use Amazon Relational Database Service (Amazon RDS) with snapshots.
/// </summary>
public partial class RDSWrapper
{

    /// <summary>
    /// Create a snapshot of a DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <param name="snapshotIdentifier">Identifier for the snapshot.</param>
    /// <returns>DB snapshot object.</returns>
    public async Task<DBSnapshot> CreateDBSnapshot(string dbInstanceIdentifier, string snapshotIdentifier)
    {
        var response = await _amazonRDS.CreateDBSnapshotAsync(
            new CreateDBSnapshotRequest()
            {
                DBSnapshotIdentifier = snapshotIdentifier,
                DBInstanceIdentifier = dbInstanceIdentifier
            });

        return response.DBSnapshot;
    }



    /// <summary>
    /// Return a list of DB snapshots for a particular DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <returns>List of DB snapshots.</returns>
    public async Task<List<DBSnapshot>> DescribeDBSnapshots(string dbInstanceIdentifier)
    {
        var results = new List<DBSnapshot>();
        var snapshotsPaginator = _amazonRDS.Paginators.DescribeDBSnapshots(
            new DescribeDBSnapshotsRequest()
            {
                DBInstanceIdentifier = dbInstanceIdentifier
            });

        // Get the entire list using the paginator.
        await foreach (var snapshots in snapshotsPaginator.DBSnapshots)
        {
            results.Add(snapshots);
        }
        return results;
    }
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/CreateDBInstance)
  + [CreateDBParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/CreateDBParameterGroup)
  + [CreateDBSnapshot](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/CreateDBSnapshot)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DeleteDBInstance)
  + [DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DeleteDBParameterGroup)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBInstances)
  + [DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBParameterGroups)
  + [DescribeDBParameters](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBParameters)
  + [DescribeDBSnapshots](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBSnapshots)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/ModifyDBParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_csharp_3_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an RDS DB instance with a particular set of properties. Use the action DescribeDBInstancesAsync
    /// to determine when the DB instance is ready to use.
    /// </summary>
    /// <param name="dbName">Name for the DB instance.</param>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <param name="parameterGroupName">DB parameter group to associate with the instance.</param>
    /// <param name="dbEngine">The engine for the DB instance.</param>
    /// <param name="dbEngineVersion">Version for the DB instance.</param>
    /// <param name="instanceClass">Class for the DB instance.</param>
    /// <param name="allocatedStorage">The amount of storage in gibibytes (GiB) to allocate to the DB instance.</param>
    /// <param name="adminName">Admin user name.</param>
    /// <param name="adminPassword">Admin user password.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> CreateDBInstance(string dbName, string dbInstanceIdentifier,
        string parameterGroupName, string dbEngine, string dbEngineVersion,
        string instanceClass, int allocatedStorage, string adminName, string adminPassword)
    {
        var response = await _amazonRDS.CreateDBInstanceAsync(
            new CreateDBInstanceRequest()
            {
                DBName = dbName,
                DBInstanceIdentifier = dbInstanceIdentifier,
                DBParameterGroupName = parameterGroupName,
                Engine = dbEngine,
                EngineVersion = dbEngineVersion,
                DBInstanceClass = instanceClass,
                AllocatedStorage = allocatedStorage,
                MasterUsername = adminName,
                MasterUserPassword = adminPassword
            });

        return response.DBInstance;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `CreateDBParameterGroup`
<a name="rds_CreateDBParameterGroup_csharp_3_topic"></a>

次のコード例は、`CreateDBParameterGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a new DB parameter group. Use the action DescribeDBParameterGroupsAsync
    /// to determine when the DB parameter group is ready to use.
    /// </summary>
    /// <param name="name">Name of the DB parameter group.</param>
    /// <param name="family">Family of the DB parameter group.</param>
    /// <param name="description">Description of the DB parameter group.</param>
    /// <returns>The new DB parameter group.</returns>
    public async Task<DBParameterGroup> CreateDBParameterGroup(
        string name, string family, string description)
    {
        var response = await _amazonRDS.CreateDBParameterGroupAsync(
            new CreateDBParameterGroupRequest()
            {
                DBParameterGroupName = name,
                DBParameterGroupFamily = family,
                Description = description
            });
        return response.DBParameterGroup;
    }
```
+  詳細については、**「AWS SDK for .NET API リファレンス」の「[CreateDBParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/CreateDBParameterGroup)」を参照してください。

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_csharp_3_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a snapshot of a DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <param name="snapshotIdentifier">Identifier for the snapshot.</param>
    /// <returns>DB snapshot object.</returns>
    public async Task<DBSnapshot> CreateDBSnapshot(string dbInstanceIdentifier, string snapshotIdentifier)
    {
        var response = await _amazonRDS.CreateDBSnapshotAsync(
            new CreateDBSnapshotRequest()
            {
                DBSnapshotIdentifier = snapshotIdentifier,
                DBInstanceIdentifier = dbInstanceIdentifier
            });

        return response.DBSnapshot;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[CreateDBSnapshot](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/CreateDBSnapshot)」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_csharp_3_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a particular DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> DeleteDBInstance(string dbInstanceIdentifier)
    {
        var response = await _amazonRDS.DeleteDBInstanceAsync(
            new DeleteDBInstanceRequest()
            {
                DBInstanceIdentifier = dbInstanceIdentifier,
                SkipFinalSnapshot = true,
                DeleteAutomatedBackups = true
            });

        return response.DBInstance;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DeleteDBParameterGroup`
<a name="rds_DeleteDBParameterGroup_csharp_3_topic"></a>

次のコード例は、`DeleteDBParameterGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a DB parameter group. The group cannot be a default DB parameter group
    /// or be associated with any DB instances.
    /// </summary>
    /// <param name="name">Name of the DB parameter group.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteDBParameterGroup(string name)
    {
        var response = await _amazonRDS.DeleteDBParameterGroupAsync(
            new DeleteDBParameterGroupRequest()
            {
                DBParameterGroupName = name,
            });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  詳細については、**「AWS SDK for .NET API リファレンス」の「[DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DeleteDBParameterGroup)」を参照してください。

### `DescribeDBEngineVersions`
<a name="rds_DescribeDBEngineVersions_csharp_3_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of DB engine versions for a particular DB engine.
    /// </summary>
    /// <param name="engine">Name of the engine.</param>
    /// <param name="dbParameterGroupFamily">Optional parameter group family name.</param>
    /// <returns>List of DBEngineVersions.</returns>
    public async Task<List<DBEngineVersion>> DescribeDBEngineVersions(string engine,
        string dbParameterGroupFamily = null)
    {
        var response = await _amazonRDS.DescribeDBEngineVersionsAsync(
            new DescribeDBEngineVersionsRequest()
            {
                Engine = engine,
                DBParameterGroupFamily = dbParameterGroupFamily
            });
        return response.DBEngineVersions;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_csharp_3_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Returns a list of DB instances.
    /// </summary>
    /// <param name="dbInstanceIdentifier">Optional name of a specific DB instance.</param>
    /// <returns>List of DB instances.</returns>
    public async Task<List<DBInstance>> DescribeDBInstances(string dbInstanceIdentifier = null)
    {
        var results = new List<DBInstance>();
        var instancesPaginator = _amazonRDS.Paginators.DescribeDBInstances(
            new DescribeDBInstancesRequest
            {
                DBInstanceIdentifier = dbInstanceIdentifier
            });
        // Get the entire list using the paginator.
        await foreach (var instances in instancesPaginator.DBInstances)
        {
            results.Add(instances);
        }
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_csharp_3_topic"></a>

次のコード例は、`DescribeDBParameterGroups` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get descriptions of DB parameter groups.
    /// </summary>
    /// <param name="name">Optional name of the DB parameter group to describe.</param>
    /// <returns>The list of DB parameter group descriptions.</returns>
    public async Task<List<DBParameterGroup>> DescribeDBParameterGroups(string name = null)
    {
        var response = await _amazonRDS.DescribeDBParameterGroupsAsync(
            new DescribeDBParameterGroupsRequest()
            {
                DBParameterGroupName = name
            });
        return response.DBParameterGroups;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBParameterGroups)」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_csharp_3_topic"></a>

次のコード例は、`DescribeDBParameters` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of DB parameters from a specific parameter group.
    /// </summary>
    /// <param name="dbParameterGroupName">Name of a specific DB parameter group.</param>
    /// <param name="source">Optional source for selecting parameters.</param>
    /// <returns>List of parameter values.</returns>
    public async Task<List<Parameter>> DescribeDBParameters(string dbParameterGroupName, string source = null)
    {
        var results = new List<Parameter>();
        var paginateParameters = _amazonRDS.Paginators.DescribeDBParameters(
            new DescribeDBParametersRequest()
            {
                DBParameterGroupName = dbParameterGroupName,
                Source = source
            });
        // Get the entire list using the paginator.
        await foreach (var parameters in paginateParameters.Parameters)
        {
            results.Add(parameters);
        }
        return results;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DescribeDBParameters](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBParameters)」を参照してください。

### `DescribeDBSnapshots`
<a name="rds_DescribeDBSnapshots_csharp_3_topic"></a>

次のコード例は、`DescribeDBSnapshots` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Return a list of DB snapshots for a particular DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <returns>List of DB snapshots.</returns>
    public async Task<List<DBSnapshot>> DescribeDBSnapshots(string dbInstanceIdentifier)
    {
        var results = new List<DBSnapshot>();
        var snapshotsPaginator = _amazonRDS.Paginators.DescribeDBSnapshots(
            new DescribeDBSnapshotsRequest()
            {
                DBInstanceIdentifier = dbInstanceIdentifier
            });

        // Get the entire list using the paginator.
        await foreach (var snapshots in snapshotsPaginator.DBSnapshots)
        {
            results.Add(snapshots);
        }
        return results;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DescribeDBSnapshots](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeDBSnapshots)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="rds_DescribeOrderableDBInstanceOptions_csharp_3_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of orderable DB instance options for a specific
    /// engine and engine version.
    /// </summary>
    /// <param name="engine">Name of the engine.</param>
    /// <param name="engineVersion">Version of the engine.</param>
    /// <returns>List of OrderableDBInstanceOptions.</returns>
    public async Task<List<OrderableDBInstanceOption>> DescribeOrderableDBInstanceOptions(string engine, string engineVersion)
    {
        // Use a paginator to get a list of DB instance options.
        var results = new List<OrderableDBInstanceOption>();
        var paginateInstanceOptions = _amazonRDS.Paginators.DescribeOrderableDBInstanceOptions(
            new DescribeOrderableDBInstanceOptionsRequest()
            {
                Engine = engine,
                EngineVersion = engineVersion,
            });
        // Get the entire list using the paginator.
        await foreach (var instanceOptions in paginateInstanceOptions.OrderableDBInstanceOptions)
        {
            results.Add(instanceOptions);
        }
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBParameterGroup`
<a name="rds_ModifyDBParameterGroup_csharp_3_topic"></a>

次のコード例は、`ModifyDBParameterGroup` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/RDS#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Update a DB parameter group. Use the action DescribeDBParameterGroupsAsync
    /// to determine when the DB parameter group is ready to use.
    /// </summary>
    /// <param name="name">Name of the DB parameter group.</param>
    /// <param name="parameters">List of parameters. Maximum of 20 per request.</param>
    /// <returns>The updated DB parameter group name.</returns>
    public async Task<string> ModifyDBParameterGroup(
        string name, List<Parameter> parameters)
    {
        var response = await _amazonRDS.ModifyDBParameterGroupAsync(
            new ModifyDBParameterGroupRequest()
            {
                DBParameterGroupName = name,
                Parameters = parameters,
            });
        return response.DBParameterGroupName;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV3/rds-2014-10-31/ModifyDBParameterGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_csharp_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 を使用して AWS SDK for .NET 、Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful .NET バックエンドと対話します。  
+ React ウェブアプリケーションを AWS サービスに統合します。
+ Aurora テーブルの項目を一覧表示、更新、削除します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/AuroraItemTracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_csharp_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda 関数での Amazon RDS データベースへの接続。  

```
using System.Data;
using System.Text.Json;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using MySql.Data.MySqlClient;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace aws_rds;

public class InputModel
{
    public string key1 { get; set; }
    public string key2 { get; set; }
}

public class Function
{
    /// <summary>
    // Handles the Lambda function execution for connecting to RDS using IAM authentication.
    /// </summary>
    /// <param name="input">The input event data passed to the Lambda function</param>
    /// <param name="context">The Lambda execution context that provides runtime information</param>
    /// <returns>A response object containing the execution result</returns>

    public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
    {
        // Sample Input: {"body": "{\"key1\":\"20\", \"key2\":\"25\"}"}
        var input = JsonSerializer.Deserialize<InputModel>(request.Body);

        /// Obtain authentication token
        var authToken = RDSAuthTokenGenerator.GenerateAuthToken(
            Environment.GetEnvironmentVariable("RDS_ENDPOINT"),
            Convert.ToInt32(Environment.GetEnvironmentVariable("RDS_PORT")),
            Environment.GetEnvironmentVariable("RDS_USERNAME")
        );

        /// Build the Connection String with the Token 
        string connectionString = $"Server={Environment.GetEnvironmentVariable("RDS_ENDPOINT")};" +
                                  $"Port={Environment.GetEnvironmentVariable("RDS_PORT")};" +
                                  $"Uid={Environment.GetEnvironmentVariable("RDS_USERNAME")};" +
                                  $"Pwd={authToken};";


        try
        {
            await using var connection = new MySqlConnection(connectionString);
            await connection.OpenAsync();

            const string sql = "SELECT @param1 + @param2 AS Sum";

            await using var command = new MySqlCommand(sql, connection);
            command.Parameters.AddWithValue("@param1", int.Parse(input.key1 ?? "0"));
            command.Parameters.AddWithValue("@param2", int.Parse(input.key2 ?? "0"));

            await using var reader = await command.ExecuteReaderAsync();
            if (await reader.ReadAsync())
            {
                int result = reader.GetInt32("Sum");

                //Sample Response: {"statusCode":200,"body":"{\"message\":\"The sum is: 45\"}","isBase64Encoded":false}
                return new APIGatewayProxyResponse
                {
                    StatusCode = 200,
                    Body = JsonSerializer.Serialize(new { message = $"The sum is: {result}" })
                };
            }

        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }

        return new APIGatewayProxyResponse
        {
            StatusCode = 500,
            Body = JsonSerializer.Serialize(new { error = "Internal server error" })
        };
    }
}
```

# を使用した Amazon RDS Data Service の例 SDK for .NET
<a name="csharp_3_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_csharp_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 を使用して AWS SDK for .NET 、Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful .NET バックエンドと対話します。  
+ React ウェブアプリケーションを AWS サービスに統合します。
+ Aurora テーブルの項目を一覧表示、更新、削除します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/AuroraItemTracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# を使用した Amazon Rekognition の例 SDK for .NET
<a name="csharp_3_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CompareFaces`
<a name="rekognition_CompareFaces_csharp_3_topic"></a>

次のコード例は、`CompareFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を比較する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to compare faces in two images.
    /// </summary>
    public class CompareFaces
    {
        public static async Task Main()
        {
            float similarityThreshold = 70F;
            string sourceImage = "source.jpg";
            string targetImage = "target.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            Amazon.Rekognition.Model.Image imageSource = new Amazon.Rekognition.Model.Image();

            try
            {
                using FileStream fs = new FileStream(sourceImage, FileMode.Open, FileAccess.Read);
                byte[] data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
                imageSource.Bytes = new MemoryStream(data);
            }
            catch (Exception)
            {
                Console.WriteLine($"Failed to load source image: {sourceImage}");
                return;
            }

            Amazon.Rekognition.Model.Image imageTarget = new Amazon.Rekognition.Model.Image();

            try
            {
                using FileStream fs = new FileStream(targetImage, FileMode.Open, FileAccess.Read);
                byte[] data = new byte[fs.Length];
                data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
                imageTarget.Bytes = new MemoryStream(data);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to load target image: {targetImage}");
                Console.WriteLine(ex.Message);
                return;
            }

            var compareFacesRequest = new CompareFacesRequest
            {
                SourceImage = imageSource,
                TargetImage = imageTarget,
                SimilarityThreshold = similarityThreshold,
            };

            // Call operation
            var compareFacesResponse = await rekognitionClient.CompareFacesAsync(compareFacesRequest);

            // Display results
            compareFacesResponse.FaceMatches.ForEach(match =>
            {
                ComparedFace face = match.Face;
                BoundingBox position = face.BoundingBox;
                Console.WriteLine($"Face at {position.Left} {position.Top} matches with {match.Similarity}% confidence.");
            });

            Console.WriteLine($"Found {compareFacesResponse.UnmatchedFaces.Count} face(s) that did not match.");
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[CompareFaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/CompareFaces)」を参照してください。

### `CreateCollection`
<a name="rekognition_CreateCollection_csharp_3_topic"></a>

次のコード例は、`CreateCollection` を使用する方法を示しています。

詳細については、「[コレクションを作成する](https://docs.aws.amazon.com/rekognition/latest/dg/create-collection-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses Amazon Rekognition to create a collection to which you can add
    /// faces using the IndexFaces operation.
    /// </summary>
    public class CreateCollection
    {
        public static async Task Main()
        {
            var rekognitionClient = new AmazonRekognitionClient();

            string collectionId = "MyCollection";
            Console.WriteLine("Creating collection: " + collectionId);

            var createCollectionRequest = new CreateCollectionRequest
            {
                CollectionId = collectionId,
            };

            CreateCollectionResponse createCollectionResponse = await rekognitionClient.CreateCollectionAsync(createCollectionRequest);
            Console.WriteLine($"CollectionArn : {createCollectionResponse.CollectionArn}");
            Console.WriteLine($"Status code : {createCollectionResponse.StatusCode}");
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[CreateCollection](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/CreateCollection)」を参照してください。

### `DeleteCollection`
<a name="rekognition_DeleteCollection_csharp_3_topic"></a>

次のコード例は、`DeleteCollection` を使用する方法を示しています。

詳細については、「[コレクションを削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-collection-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to delete an existing collection.
    /// </summary>
    public class DeleteCollection
    {
        public static async Task Main()
        {
            var rekognitionClient = new AmazonRekognitionClient();

            string collectionId = "MyCollection";
            Console.WriteLine("Deleting collection: " + collectionId);

            var deleteCollectionRequest = new DeleteCollectionRequest()
            {
                CollectionId = collectionId,
            };

            var deleteCollectionResponse = await rekognitionClient.DeleteCollectionAsync(deleteCollectionRequest);
            Console.WriteLine($"{collectionId}: {deleteCollectionResponse.StatusCode}");
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DeleteCollection](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/DeleteCollection)」を参照してください。

### `DeleteFaces`
<a name="rekognition_DeleteFaces_csharp_3_topic"></a>

次のコード例は、`DeleteFaces` を使用する方法を示しています。

詳細については、「[コレクションから顔を削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-faces-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to delete one or more faces from
    /// a Rekognition collection.
    /// </summary>
    public class DeleteFaces
    {
        public static async Task Main()
        {
            string collectionId = "MyCollection";
            var faces = new List<string> { "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" };

            var rekognitionClient = new AmazonRekognitionClient();

            var deleteFacesRequest = new DeleteFacesRequest()
            {
                CollectionId = collectionId,
                FaceIds = faces,
            };

            DeleteFacesResponse deleteFacesResponse = await rekognitionClient.DeleteFacesAsync(deleteFacesRequest);
            deleteFacesResponse.DeletedFaces.ForEach(face =>
            {
                Console.WriteLine($"FaceID: {face}");
            });
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DeleteFaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/DeleteFaces)」を参照してください。

### `DescribeCollection`
<a name="rekognition_DescribeCollection_csharp_3_topic"></a>

次のコード例は、`DescribeCollection` を使用する方法を示しています。

詳細については、「[コレクションを定義する](https://docs.aws.amazon.com/rekognition/latest/dg/describe-collection-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to describe the contents of a
    /// collection.
    /// </summary>
    public class DescribeCollection
    {
        public static async Task Main()
        {
            var rekognitionClient = new AmazonRekognitionClient();

            string collectionId = "MyCollection";
            Console.WriteLine($"Describing collection: {collectionId}");

            var describeCollectionRequest = new DescribeCollectionRequest()
            {
                CollectionId = collectionId,
            };

            var describeCollectionResponse = await rekognitionClient.DescribeCollectionAsync(describeCollectionRequest);
            Console.WriteLine($"Collection ARN: {describeCollectionResponse.CollectionARN}");
            Console.WriteLine($"Face count: {describeCollectionResponse.FaceCount}");
            Console.WriteLine($"Face model version: {describeCollectionResponse.FaceModelVersion}");
            Console.WriteLine($"Created: {describeCollectionResponse.CreationTimestamp}");
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DescribeCollection](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/DescribeCollection)」を参照してください。

### `DetectFaces`
<a name="rekognition_DetectFaces_csharp_3_topic"></a>

次のコード例は、`DetectFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を検出する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to detect faces within an image
    /// stored in an Amazon Simple Storage Service (Amazon S3) bucket.
    /// </summary>
    public class DetectFaces
    {
        public static async Task Main()
        {
            string photo = "input.jpg";
            string bucket = "amzn-s3-demo-bucket";

            var rekognitionClient = new AmazonRekognitionClient();

            var detectFacesRequest = new DetectFacesRequest()
            {
                Image = new Image()
                {
                    S3Object = new S3Object()
                    {
                        Name = photo,
                        Bucket = bucket,
                    },
                },

                // Attributes can be "ALL" or "DEFAULT".
                // "DEFAULT": BoundingBox, Confidence, Landmarks, Pose, and Quality.
                // "ALL": See https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Rekognition/TFaceDetail.html
                Attributes = new List<string>() { "ALL" },
            };

            try
            {
                DetectFacesResponse detectFacesResponse = await rekognitionClient.DetectFacesAsync(detectFacesRequest);
                bool hasAll = detectFacesRequest.Attributes.Contains("ALL");
                foreach (FaceDetail face in detectFacesResponse.FaceDetails)
                {
                    Console.WriteLine($"BoundingBox: top={face.BoundingBox.Left} left={face.BoundingBox.Top} width={face.BoundingBox.Width} height={face.BoundingBox.Height}");
                    Console.WriteLine($"Confidence: {face.Confidence}");
                    Console.WriteLine($"Landmarks: {face.Landmarks.Count}");
                    Console.WriteLine($"Pose: pitch={face.Pose.Pitch} roll={face.Pose.Roll} yaw={face.Pose.Yaw}");
                    Console.WriteLine($"Brightness: {face.Quality.Brightness}\tSharpness: {face.Quality.Sharpness}");

                    if (hasAll)
                    {
                        Console.WriteLine($"Estimated age is between {face.AgeRange.Low} and {face.AgeRange.High} years old.");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
```
イメージ内のすべての顔の境界ボックス情報を表示します。  

```
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to display the details of the
    /// bounding boxes around the faces detected in an image.
    /// </summary>
    public class ImageOrientationBoundingBox
    {
        public static async Task Main()
        {
            string photo = @"D:\Development\AWS-Examples\Rekognition\target.jpg"; // "photo.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            var image = new Amazon.Rekognition.Model.Image();
            try
            {
                using var fs = new FileStream(photo, FileMode.Open, FileAccess.Read);
                byte[] data = null;
                data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
                image.Bytes = new MemoryStream(data);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to load file " + photo);
                return;
            }

            int height;
            int width;

            // Used to extract original photo width/height
            using (var imageBitmap = new Bitmap(photo))
            {
                height = imageBitmap.Height;
                width = imageBitmap.Width;
            }

            Console.WriteLine("Image Information:");
            Console.WriteLine(photo);
            Console.WriteLine("Image Height: " + height);
            Console.WriteLine("Image Width: " + width);

            try
            {
                var detectFacesRequest = new DetectFacesRequest()
                {
                    Image = image,
                    Attributes = new List<string>() { "ALL" },
                };

                DetectFacesResponse detectFacesResponse = await rekognitionClient.DetectFacesAsync(detectFacesRequest);
                detectFacesResponse.FaceDetails.ForEach(face =>
                {
                    Console.WriteLine("Face:");
                    ShowBoundingBoxPositions(
                        height,
                        width,
                        face.BoundingBox,
                        detectFacesResponse.OrientationCorrection);

                    Console.WriteLine($"BoundingBox: top={face.BoundingBox.Left} left={face.BoundingBox.Top} width={face.BoundingBox.Width} height={face.BoundingBox.Height}");
                    Console.WriteLine($"The detected face is estimated to be between {face.AgeRange.Low} and {face.AgeRange.High} years old.\n");
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Display the bounding box information for an image.
        /// </summary>
        /// <param name="imageHeight">The height of the image.</param>
        /// <param name="imageWidth">The width of the image.</param>
        /// <param name="box">The bounding box for a face found within the image.</param>
        /// <param name="rotation">The rotation of the face's bounding box.</param>
        public static void ShowBoundingBoxPositions(int imageHeight, int imageWidth, BoundingBox box, string rotation)
        {
            float left;
            float top;

            if (rotation == null)
            {
                Console.WriteLine("No estimated orientation. Check Exif data.");
                return;
            }

            // Calculate face position based on image orientation.
            switch (rotation)
            {
                case "ROTATE_0":
                    left = imageWidth * box.Left;
                    top = imageHeight * box.Top;
                    break;
                case "ROTATE_90":
                    left = imageHeight * (1 - (box.Top + box.Height));
                    top = imageWidth * box.Left;
                    break;
                case "ROTATE_180":
                    left = imageWidth - (imageWidth * (box.Left + box.Width));
                    top = imageHeight * (1 - (box.Top + box.Height));
                    break;
                case "ROTATE_270":
                    left = imageHeight * box.Top;
                    top = imageWidth * (1 - box.Left - box.Width);
                    break;
                default:
                    Console.WriteLine("No estimated orientation information. Check Exif data.");
                    return;
            }

            // Display face location information.
            Console.WriteLine($"Left: {left}");
            Console.WriteLine($"Top: {top}");
            Console.WriteLine($"Face Width: {imageWidth * box.Width}");
            Console.WriteLine($"Face Height: {imageHeight * box.Height}");
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DetectFaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/DetectFaces)」を参照してください。

### `DetectLabels`
<a name="rekognition_DetectLabels_csharp_3_topic"></a>

次のコード例は、`DetectLabels` を使用する方法を示しています。

詳細については、「[イメージ内のラベルを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to detect labels within an image
    /// stored in an Amazon Simple Storage Service (Amazon S3) bucket.
    /// </summary>
    public class DetectLabels
    {
        public static async Task Main()
        {
            string photo = "del_river_02092020_01.jpg"; // "input.jpg";
            string bucket = "amzn-s3-demo-bucket"; // "bucket";

            var rekognitionClient = new AmazonRekognitionClient();

            var detectlabelsRequest = new DetectLabelsRequest
            {
                Image = new Image()
                {
                    S3Object = new S3Object()
                    {
                        Name = photo,
                        Bucket = bucket,
                    },
                },
                MaxLabels = 10,
                MinConfidence = 75F,
            };

            try
            {
                DetectLabelsResponse detectLabelsResponse = await rekognitionClient.DetectLabelsAsync(detectlabelsRequest);
                Console.WriteLine("Detected labels for " + photo);
                foreach (Label label in detectLabelsResponse.Labels)
                {
                    Console.WriteLine($"Name: {label.Name} Confidence: {label.Confidence}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
```
コンピュータに保存されているイメージファイル内のラベルを検出します。  

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to detect labels within an image
    /// stored locally.
    /// </summary>
    public class DetectLabelsLocalFile
    {
        public static async Task Main()
        {
            string photo = "input.jpg";

            var image = new Amazon.Rekognition.Model.Image();
            try
            {
                using var fs = new FileStream(photo, FileMode.Open, FileAccess.Read);
                byte[] data = null;
                data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
                image.Bytes = new MemoryStream(data);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to load file " + photo);
                return;
            }

            var rekognitionClient = new AmazonRekognitionClient();

            var detectlabelsRequest = new DetectLabelsRequest
            {
                Image = image,
                MaxLabels = 10,
                MinConfidence = 77F,
            };

            try
            {
                DetectLabelsResponse detectLabelsResponse = await rekognitionClient.DetectLabelsAsync(detectlabelsRequest);
                Console.WriteLine($"Detected labels for {photo}");
                foreach (Label label in detectLabelsResponse.Labels)
                {
                    Console.WriteLine($"{label.Name}: {label.Confidence}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DetectLabels](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/DetectLabels)」を参照してください。

### `DetectModerationLabels`
<a name="rekognition_DetectModerationLabels_csharp_3_topic"></a>

次のコード例は、`DetectModerationLabels` を使用する方法を示しています。

詳細については、「[不適切なイメージを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-images.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to detect unsafe content in a
    /// JPEG or PNG format image.
    /// </summary>
    public class DetectModerationLabels
    {
        public static async Task Main(string[] args)
        {
            string photo = "input.jpg";
            string bucket = "amzn-s3-demo-bucket";

            var rekognitionClient = new AmazonRekognitionClient();

            var detectModerationLabelsRequest = new DetectModerationLabelsRequest()
            {
                Image = new Image()
                {
                    S3Object = new S3Object()
                    {
                        Name = photo,
                        Bucket = bucket,
                    },
                },
                MinConfidence = 60F,
            };

            try
            {
                var detectModerationLabelsResponse = await rekognitionClient.DetectModerationLabelsAsync(detectModerationLabelsRequest);
                Console.WriteLine("Detected labels for " + photo);
                foreach (ModerationLabel label in detectModerationLabelsResponse.ModerationLabels)
                {
                    Console.WriteLine($"Label: {label.Name}");
                    Console.WriteLine($"Confidence: {label.Confidence}");
                    Console.WriteLine($"Parent: {label.ParentName}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DetectModerationLabels](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/DetectModerationLabels)」を参照してください。

### `DetectText`
<a name="rekognition_DetectText_csharp_3_topic"></a>

次のコード例は、`DetectText` を使用する方法を示しています。

詳細については、「[イメージ内のテキストを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/text-detecting-text-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to detect text in an image. The
    /// example was created using the AWS SDK for .NET version 3.7 and .NET
    /// Core 5.0.
    /// </summary>
    public class DetectText
    {
        public static async Task Main()
        {
            string photo = "Dad_photographer.jpg"; // "input.jpg";
            string bucket = "amzn-s3-demo-bucket"; // "bucket";

            var rekognitionClient = new AmazonRekognitionClient();

            var detectTextRequest = new DetectTextRequest()
            {
                Image = new Image()
                {
                    S3Object = new S3Object()
                    {
                        Name = photo,
                        Bucket = bucket,
                    },
                },
            };

            try
            {
                DetectTextResponse detectTextResponse = await rekognitionClient.DetectTextAsync(detectTextRequest);
                Console.WriteLine($"Detected lines and words for {photo}");
                detectTextResponse.TextDetections.ForEach(text =>
                {
                    Console.WriteLine($"Detected: {text.DetectedText}");
                    Console.WriteLine($"Confidence: {text.Confidence}");
                    Console.WriteLine($"Id : {text.Id}");
                    Console.WriteLine($"Parent Id: {text.ParentId}");
                    Console.WriteLine($"Type: {text.Type}");
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[DetectText](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/DetectText)」を参照してください。

### `GetCelebrityInfo`
<a name="rekognition_GetCelebrityInfo_csharp_3_topic"></a>

次のコード例は、`GetCelebrityInfo` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Shows how to use Amazon Rekognition to retrieve information about the
    /// celebrity identified by the supplied celebrity Id.
    /// </summary>
    public class CelebrityInfo
    {
        public static async Task Main()
        {
            string celebId = "nnnnnnnn";

            var rekognitionClient = new AmazonRekognitionClient();

            var celebrityInfoRequest = new GetCelebrityInfoRequest
            {
                Id = celebId,
            };

            Console.WriteLine($"Getting information for celebrity: {celebId}");

            var celebrityInfoResponse = await rekognitionClient.GetCelebrityInfoAsync(celebrityInfoRequest);

            // Display celebrity information.
            Console.WriteLine($"celebrity name: {celebrityInfoResponse.Name}");
            Console.WriteLine("Further information (if available):");
            celebrityInfoResponse.Urls.ForEach(url =>
            {
                Console.WriteLine(url);
            });
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[GetCelebrityInfo](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/GetCelebrityInfo)」を参照してください。

### `IndexFaces`
<a name="rekognition_IndexFaces_csharp_3_topic"></a>

次のコード例は、`IndexFaces` を使用する方法を示しています。

詳細については、「[コレクションに顔を追加する](https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to detect faces in an image
    /// that has been uploaded to an Amazon Simple Storage Service (Amazon S3)
    /// bucket and then adds the information to a collection.
    /// </summary>
    public class AddFaces
    {
        public static async Task Main()
        {
            string collectionId = "MyCollection2";
            string bucket = "amzn-s3-demo-bucket";
            string photo = "input.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            var image = new Image
            {
                S3Object = new S3Object
                {
                    Bucket = bucket,
                    Name = photo,
                },
            };

            var indexFacesRequest = new IndexFacesRequest
            {
                Image = image,
                CollectionId = collectionId,
                ExternalImageId = photo,
                DetectionAttributes = new List<string>() { "ALL" },
            };

            IndexFacesResponse indexFacesResponse = await rekognitionClient.IndexFacesAsync(indexFacesRequest);

            Console.WriteLine($"{photo} added");
            foreach (FaceRecord faceRecord in indexFacesResponse.FaceRecords)
            {
                Console.WriteLine($"Face detected: Faceid is {faceRecord.Face.FaceId}");
            }
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[IndexFaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/IndexFaces)」を参照してください。

### `ListCollections`
<a name="rekognition_ListCollections_csharp_3_topic"></a>

次のコード例は、`ListCollections` を使用する方法を示しています。

コレクションの詳細については、「[コレクションを一覧表示する](https://docs.aws.amazon.com/rekognition/latest/dg/list-collection-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses Amazon Rekognition to list the collection IDs in the
    /// current account.
    /// </summary>
    public class ListCollections
    {
        public static async Task Main()
        {
            var rekognitionClient = new AmazonRekognitionClient();

            Console.WriteLine("Listing collections");
            int limit = 10;

            var listCollectionsRequest = new ListCollectionsRequest
            {
                MaxResults = limit,
            };

            var listCollectionsResponse = new ListCollectionsResponse();

            do
            {
                if (listCollectionsResponse is not null)
                {
                    listCollectionsRequest.NextToken = listCollectionsResponse.NextToken;
                }

                listCollectionsResponse = await rekognitionClient.ListCollectionsAsync(listCollectionsRequest);

                listCollectionsResponse.CollectionIds.ForEach(id =>
                {
                    Console.WriteLine(id);
                });
            }
            while (listCollectionsResponse.NextToken is not null);
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[ListCollections](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/ListCollections)」を参照してください。

### `ListFaces`
<a name="rekognition_ListFaces_csharp_3_topic"></a>

次のコード例は、`ListFaces` を使用する方法を示しています。

詳細については、「[コレクションに顔を保存する](https://docs.aws.amazon.com/rekognition/latest/dg/list-faces-in-collection-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to retrieve the list of faces
    /// stored in a collection.
    /// </summary>
    public class ListFaces
    {
        public static async Task Main()
        {
            string collectionId = "MyCollection2";

            var rekognitionClient = new AmazonRekognitionClient();

            var listFacesResponse = new ListFacesResponse();
            Console.WriteLine($"Faces in collection {collectionId}");

            var listFacesRequest = new ListFacesRequest
            {
                CollectionId = collectionId,
                MaxResults = 1,
            };

            do
            {
                listFacesResponse = await rekognitionClient.ListFacesAsync(listFacesRequest);
                listFacesResponse.Faces.ForEach(face =>
                {
                    Console.WriteLine(face.FaceId);
                });

                listFacesRequest.NextToken = listFacesResponse.NextToken;
            }
            while (!string.IsNullOrEmpty(listFacesResponse.NextToken));
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[ListFaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/ListFaces)」を参照してください。

### `RecognizeCelebrities`
<a name="rekognition_RecognizeCelebrities_csharp_3_topic"></a>

次のコード例は、`RecognizeCelebrities` を使用する方法を示しています。

詳細については、「[イメージ内で有名人を認識する](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-procedure-image.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Shows how to use Amazon Rekognition to identify celebrities in a photo.
    /// </summary>
    public class CelebritiesInImage
    {
        public static async Task Main(string[] args)
        {
            string photo = "moviestars.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            var recognizeCelebritiesRequest = new RecognizeCelebritiesRequest();

            var img = new Amazon.Rekognition.Model.Image();
            byte[] data = null;
            try
            {
                using var fs = new FileStream(photo, FileMode.Open, FileAccess.Read);
                data = new byte[fs.Length];
                fs.Read(data, 0, (int)fs.Length);
            }
            catch (Exception)
            {
                Console.WriteLine($"Failed to load file {photo}");
                return;
            }

            img.Bytes = new MemoryStream(data);
            recognizeCelebritiesRequest.Image = img;

            Console.WriteLine($"Looking for celebrities in image {photo}\n");

            var recognizeCelebritiesResponse = await rekognitionClient.RecognizeCelebritiesAsync(recognizeCelebritiesRequest);

            Console.WriteLine($"{recognizeCelebritiesResponse.CelebrityFaces.Count} celebrity(s) were recognized.\n");
            recognizeCelebritiesResponse.CelebrityFaces.ForEach(celeb =>
            {
                Console.WriteLine($"Celebrity recognized: {celeb.Name}");
                Console.WriteLine($"Celebrity ID: {celeb.Id}");
                BoundingBox boundingBox = celeb.Face.BoundingBox;
                Console.WriteLine($"position: {boundingBox.Left} {boundingBox.Top}");
                Console.WriteLine("Further information (if available):");
                celeb.Urls.ForEach(url =>
                {
                    Console.WriteLine(url);
                });
            });

            Console.WriteLine($"{recognizeCelebritiesResponse.UnrecognizedFaces.Count} face(s) were unrecognized.");
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[RecognizeCelebrities](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/RecognizeCelebrities)」を参照してください。

### `SearchFaces`
<a name="rekognition_SearchFaces_csharp_3_topic"></a>

次のコード例は、`SearchFaces` を使用する方法を示しています。

詳細については、[顔 (フェイス ID) を検索する](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-id-procedure.html) を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to find faces in an image that
    /// match the face Id provided in the method request.
    /// </summary>
    public class SearchFacesMatchingId
    {
        public static async Task Main()
        {
            string collectionId = "MyCollection";
            string faceId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

            var rekognitionClient = new AmazonRekognitionClient();

            // Search collection for faces matching the face id.
            var searchFacesRequest = new SearchFacesRequest
            {
                CollectionId = collectionId,
                FaceId = faceId,
                FaceMatchThreshold = 70F,
                MaxFaces = 2,
            };

            SearchFacesResponse searchFacesResponse = await rekognitionClient.SearchFacesAsync(searchFacesRequest);

            Console.WriteLine("Face matching faceId " + faceId);

            Console.WriteLine("Matche(s): ");
            searchFacesResponse.FaceMatches.ForEach(face =>
            {
                Console.WriteLine($"FaceId: {face.Face.FaceId} Similarity: {face.Similarity}");
            });
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[SearchFaces](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/SearchFaces)」を参照してください。

### `SearchFacesByImage`
<a name="rekognition_SearchFacesByImage_csharp_3_topic"></a>

次のコード例は、`SearchFacesByImage` を使用する方法を示しています。

詳細については、「[顔を検索する (イメージ)](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-image-procedure.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Rekognition/#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Rekognition;
    using Amazon.Rekognition.Model;

    /// <summary>
    /// Uses the Amazon Rekognition Service to search for images matching those
    /// in a collection.
    /// </summary>
    public class SearchFacesMatchingImage
    {
        public static async Task Main()
        {
            string collectionId = "MyCollection";
            string bucket = "amzn-s3-demo-bucket";
            string photo = "input.jpg";

            var rekognitionClient = new AmazonRekognitionClient();

            // Get an image object from S3 bucket.
            var image = new Image()
            {
                S3Object = new S3Object()
                {
                    Bucket = bucket,
                    Name = photo,
                },
            };

            var searchFacesByImageRequest = new SearchFacesByImageRequest()
            {
                CollectionId = collectionId,
                Image = image,
                FaceMatchThreshold = 70F,
                MaxFaces = 2,
            };

            SearchFacesByImageResponse searchFacesByImageResponse = await rekognitionClient.SearchFacesByImageAsync(searchFacesByImageRequest);

            Console.WriteLine("Faces matching largest face in image from " + photo);
            searchFacesByImageResponse.FaceMatches.ForEach(face =>
            {
                Console.WriteLine($"FaceId: {face.Face.FaceId}, Similarity: {face.Similarity}");
            });
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[SearchFacesByImage](https://docs.aws.amazon.com/goto/DotNetSDKV3/rekognition-2016-06-27/SearchFacesByImage)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_csharp_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for .NET**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_csharp_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for .NET**  
 Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内から、Amazon Rekognition を使用してカテゴリ別にオブジェクトを識別するアプリケーションを、Amazon Rekognition .NET API を使用して作成する方法を示します。アプリケーションは、Amazon Simple Email Service (Amazon SES) を使用して、結果を記載した E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAnalyzerApp) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

# を使用した Route 53 ドメイン登録の例 SDK for .NET
<a name="csharp_3_route-53-domains_code_examples"></a>

次のコード例は、Route 53 ドメイン登録 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### ハロー Route 53 ドメイン登録
<a name="route-53-domains_Hello_csharp_3_topic"></a>

次のコード例は、Route 53 ドメイン登録の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
public static class HelloRoute53Domains
{
    static async Task Main(string[] args)
    {
        // Use the AWS .NET Core Setup package to set up dependency injection for the Amazon Route 53 domain registration service.
        // Use your AWS profile name, or leave it blank to use the default profile.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonRoute53Domains>()
            ).Build();

        // Now the client is available for injection.
        var route53Client = host.Services.GetRequiredService<IAmazonRoute53Domains>();

        // You can use await and any of the async methods to get a response.
        var response = await route53Client.ListPricesAsync(new ListPricesRequest { Tld = "com" });
        Console.WriteLine($"Hello Amazon Route 53 Domains! Following are prices for .com domain operations:");
        var comPrices = response.Prices.FirstOrDefault();
        if (comPrices != null)
        {
            Console.WriteLine($"\tRegistration: {comPrices.RegistrationPrice?.Price} {comPrices.RegistrationPrice?.Currency}");
            Console.WriteLine($"\tRenewal: {comPrices.RenewalPrice?.Price} {comPrices.RenewalPrice?.Currency}");
        }
    }
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListPrices](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ListPrices)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="route-53-domains_Scenario_GetStartedRoute53Domains_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 現在のドメインを一覧表示し、過去 1 年間の操作を一覧表示します。
+ 過去 1 年間の請求記録とドメインタイプの価格を表示します。
+ ドメインの候補を取得します。
+ ドメインの可用性と移管可能性を確認します。
+ オプションで、ドメイン登録をリクエストします。
+ 操作の詳細を入手します。
+ オプションで、ドメインの詳細を取得します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
public static class Route53DomainScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This .NET example performs the following tasks:
        1. List current domains.
        2. List operations in the past year.
        3. View billing for the account in the past year.
        4. View prices for domain types.
        5. Get domain suggestions.
        6. Check domain availability.
        7. Check domain transferability.
        8. Optionally, request a domain registration.
        9. Get an operation detail.
       10. Optionally, get a domain detail.
   */

    private static Route53Wrapper _route53Wrapper = null!;
    private static IConfiguration _configuration = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
                    .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonRoute53Domains>()
                .AddTransient<Route53Wrapper>()
            )
            .Build();

        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();

        var logger = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        }).CreateLogger(typeof(Route53DomainScenario));

        _route53Wrapper = host.Services.GetRequiredService<Route53Wrapper>();

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the Amazon Route 53 domains example scenario.");
        Console.WriteLine(new string('-', 80));

        try
        {
            await ListDomains();
            await ListOperations();
            await ListBillingRecords();
            await ListPrices();
            await ListDomainSuggestions();
            await CheckDomainAvailability();
            await CheckDomainTransferability();
            var operationId = await RequestDomainRegistration();
            await GetOperationalDetail(operationId);
            await GetDomainDetails();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "There was a problem executing the scenario.");
        }

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("The Amazon Route 53 domains example scenario is complete.");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List account registered domains.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListDomains()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"1. List account domains.");
        var domains = await _route53Wrapper.ListDomains();
        for (int i = 0; i < domains.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {domains[i].DomainName}");
        }

        if (!domains.Any())
        {
            Console.WriteLine("\tNo domains found in this account.");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List domain operations in the past year.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListOperations()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"2. List account domain operations in the past year.");
        var operations = await _route53Wrapper.ListOperations(
            DateTime.Today.AddYears(-1));
        for (int i = 0; i < operations.Count; i++)
        {
            Console.WriteLine($"\tOperation Id: {operations[i].OperationId}");
            Console.WriteLine($"\tStatus: {operations[i].Status}");
            Console.WriteLine($"\tDate: {operations[i].SubmittedDate}");
        }
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List billing in the past year.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListBillingRecords()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"3. View billing for the account in the past year.");
        var billingRecords = await _route53Wrapper.ViewBilling(
            DateTime.Today.AddYears(-1),
            DateTime.Today);
        for (int i = 0; i < billingRecords.Count; i++)
        {
            Console.WriteLine($"\tBill Date: {billingRecords[i].BillDate.ToShortDateString()}");
            Console.WriteLine($"\tOperation: {billingRecords[i].Operation}");
            Console.WriteLine($"\tPrice: {billingRecords[i].Price}");
        }
        if (!billingRecords.Any())
        {
            Console.WriteLine("\tNo billing records found in this account for the past year.");
        }
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List prices for a few domain types.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListPrices()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"4. View prices for domain types.");
        var domainTypes = new List<string> { "net", "com", "org", "co" };

        var prices = await _route53Wrapper.ListPrices(domainTypes);
        foreach (var pr in prices)
        {
            Console.WriteLine($"\tName: {pr.Name}");
            Console.WriteLine($"\tRegistration: {pr.RegistrationPrice?.Price} {pr.RegistrationPrice?.Currency}");
            Console.WriteLine($"\tRenewal: {pr.RenewalPrice?.Price} {pr.RenewalPrice?.Currency}");
            Console.WriteLine($"\tTransfer: {pr.TransferPrice?.Price} {pr.TransferPrice?.Currency}");
            Console.WriteLine($"\tChange Ownership: {pr.ChangeOwnershipPrice?.Price} {pr.ChangeOwnershipPrice?.Currency}");
            Console.WriteLine($"\tRestoration: {pr.RestorationPrice?.Price} {pr.RestorationPrice?.Currency}");
            Console.WriteLine();
        }
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List domain suggestions for a domain name.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListDomainSuggestions()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"5. Get domain suggestions.");
        string? domainName = null;
        while (domainName == null || string.IsNullOrWhiteSpace(domainName))
        {
            Console.WriteLine($"Enter a domain name to get available domain suggestions.");
            domainName = Console.ReadLine();
        }

        var suggestions = await _route53Wrapper.GetDomainSuggestions(domainName, true, 5);
        foreach (var suggestion in suggestions)
        {
            Console.WriteLine($"\tSuggestion Name: {suggestion.DomainName}");
            Console.WriteLine($"\tAvailability: {suggestion.Availability}");
        }
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Check availability for a domain name.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CheckDomainAvailability()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"6. Check domain availability.");
        string? domainName = null;
        while (domainName == null || string.IsNullOrWhiteSpace(domainName))
        {
            Console.WriteLine($"Enter a domain name to check domain availability.");
            domainName = Console.ReadLine();
        }

        var availability = await _route53Wrapper.CheckDomainAvailability(domainName);
        Console.WriteLine($"\tAvailability: {availability}");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Check transferability for a domain name.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CheckDomainTransferability()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"7. Check domain transferability.");
        string? domainName = null;
        while (domainName == null || string.IsNullOrWhiteSpace(domainName))
        {
            Console.WriteLine($"Enter a domain name to check domain transferability.");
            domainName = Console.ReadLine();
        }

        var transferability = await _route53Wrapper.CheckDomainTransferability(domainName);
        Console.WriteLine($"\tTransferability: {transferability}");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Check transferability for a domain name.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task<string?> RequestDomainRegistration()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"8. Optionally, request a domain registration.");

        Console.WriteLine($"\tNote: This example uses domain request settings in settings.json.");
        Console.WriteLine($"\tTo change the domain registration settings, set the values in that file.");
        Console.WriteLine($"\tRemember, registering an actual domain will incur an account billing cost.");
        Console.WriteLine($"\tWould you like to begin a domain registration? (y/n)");
        var ynResponse = Console.ReadLine();
        if (ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase))
        {
            string domainName = _configuration["DomainName"];
            ContactDetail contact = new ContactDetail();
            contact.CountryCode = CountryCode.FindValue(_configuration["Contact:CountryCode"]);
            contact.ContactType = ContactType.FindValue(_configuration["Contact:ContactType"]);

            _configuration.GetSection("Contact").Bind(contact);

            var operationId = await _route53Wrapper.RegisterDomain(
                domainName,
                Convert.ToBoolean(_configuration["AutoRenew"]),
                Convert.ToInt32(_configuration["DurationInYears"]),
                contact);
            if (operationId != null)
            {
                Console.WriteLine(
                    $"\tRegistration requested. Operation Id: {operationId}");
            }

            return operationId;
        }

        Console.WriteLine(new string('-', 80));
        return null;
    }

    /// <summary>
    /// Get details for an operation.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task GetOperationalDetail(string? operationId)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"9. Get an operation detail.");

        var operationDetails =
            await _route53Wrapper.GetOperationDetail(operationId);

        Console.WriteLine(operationDetails);

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Optionally, get details for a registered domain.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task<string?> GetDomainDetails()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"10. Get details on a domain.");

        Console.WriteLine($"\tNote: you must have a registered domain to get details.");
        Console.WriteLine($"\tWould you like to get domain details? (y/n)");
        var ynResponse = Console.ReadLine();
        if (ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase))
        {
            string? domainName = null;
            while (domainName == null)
            {
                Console.WriteLine($"\tEnter a domain name to get details.");
                domainName = Console.ReadLine();
            }

            var domainDetails = await _route53Wrapper.GetDomainDetail(domainName);
            Console.WriteLine(domainDetails);
        }

        Console.WriteLine(new string('-', 80));
        return null;
    }
}
```
Route 53 のドメイン登録アクションにシナリオが使用するラッパーメソッド。  

```
public class Route53Wrapper
{
    private readonly IAmazonRoute53Domains _amazonRoute53Domains;
    private readonly ILogger<Route53Wrapper> _logger;
    public Route53Wrapper(IAmazonRoute53Domains amazonRoute53Domains, ILogger<Route53Wrapper> logger)
    {
        _amazonRoute53Domains = amazonRoute53Domains;
        _logger = logger;
    }


    /// <summary>
    /// List prices for domain type operations.
    /// </summary>
    /// <param name="domainTypes">Domain types to include in the results.</param>
    /// <returns>The list of domain prices.</returns>
    public async Task<List<DomainPrice>> ListPrices(List<string> domainTypes)
    {
        var results = new List<DomainPrice>();
        var paginatePrices = _amazonRoute53Domains.Paginators.ListPrices(new ListPricesRequest());
        // Get the entire list using the paginator.
        await foreach (var prices in paginatePrices.Prices)
        {
            results.Add(prices);
        }
        return results.Where(p => domainTypes.Contains(p.Name)).ToList();
    }


    /// <summary>
    /// Check the availability of a domain name.
    /// </summary>
    /// <param name="domain">The domain to check for availability.</param>
    /// <returns>An availability result string.</returns>
    public async Task<string> CheckDomainAvailability(string domain)
    {
        var result = await _amazonRoute53Domains.CheckDomainAvailabilityAsync(
            new CheckDomainAvailabilityRequest
            {
                DomainName = domain
            }
        );
        return result.Availability.Value;
    }


    /// <summary>
    /// Check the transferability of a domain name.
    /// </summary>
    /// <param name="domain">The domain to check for transferability.</param>
    /// <returns>A transferability result string.</returns>
    public async Task<string> CheckDomainTransferability(string domain)
    {
        var result = await _amazonRoute53Domains.CheckDomainTransferabilityAsync(
            new CheckDomainTransferabilityRequest
            {
                DomainName = domain
            }
        );
        return result.Transferability.Transferable.Value;
    }


    /// <summary>
    /// Get a list of suggestions for a given domain.
    /// </summary>
    /// <param name="domain">The domain to check for suggestions.</param>
    /// <param name="onlyAvailable">If true, only returns available domains.</param>
    /// <param name="suggestionCount">The number of suggestions to return. Defaults to the max of 50.</param>
    /// <returns>A collection of domain suggestions.</returns>
    public async Task<List<DomainSuggestion>> GetDomainSuggestions(string domain, bool onlyAvailable, int suggestionCount = 50)
    {
        var result = await _amazonRoute53Domains.GetDomainSuggestionsAsync(
            new GetDomainSuggestionsRequest
            {
                DomainName = domain,
                OnlyAvailable = onlyAvailable,
                SuggestionCount = suggestionCount
            }
        );
        return result.SuggestionsList;
    }


    /// <summary>
    /// Get details for a domain action operation.
    /// </summary>
    /// <param name="operationId">The operational Id.</param>
    /// <returns>A string describing the operational details.</returns>
    public async Task<string> GetOperationDetail(string? operationId)
    {
        if (operationId == null)
            return "Unable to get operational details because ID is null.";
        try
        {
            var operationDetails =
                await _amazonRoute53Domains.GetOperationDetailAsync(
                    new GetOperationDetailRequest
                    {
                        OperationId = operationId
                    }
                );

            var details = $"\tOperation {operationId}:\n" +
                          $"\tFor domain {operationDetails.DomainName} on {operationDetails.SubmittedDate.ToShortDateString()}.\n" +
                          $"\tMessage is {operationDetails.Message}.\n" +
                          $"\tStatus is {operationDetails.Status}.\n";

            return details;
        }
        catch (AmazonRoute53DomainsException ex)
        {
            return $"Unable to get operation details. Here's why: {ex.Message}.";
        }
    }


    /// <summary>
    /// Initiate a domain registration request.
    /// </summary>
    /// <param name="contact">Contact details.</param>
    /// <param name="domainName">The domain name to register.</param>
    /// <param name="autoRenew">True if the domain should automatically renew.</param>
    /// <param name="duration">The duration in years for the domain registration.</param>
    /// <returns>The operation Id.</returns>
    public async Task<string?> RegisterDomain(string domainName, bool autoRenew, int duration, ContactDetail contact)
    {
        // This example uses the same contact information for admin, registrant, and tech contacts.
        try
        {
            var result = await _amazonRoute53Domains.RegisterDomainAsync(
                new RegisterDomainRequest()
                {
                    AdminContact = contact,
                    RegistrantContact = contact,
                    TechContact = contact,
                    DomainName = domainName,
                    AutoRenew = autoRenew,
                    DurationInYears = duration,
                    PrivacyProtectAdminContact = false,
                    PrivacyProtectRegistrantContact = false,
                    PrivacyProtectTechContact = false
                }
            );
            return result.OperationId;
        }
        catch (InvalidInputException)
        {
            _logger.LogInformation($"Unable to request registration for domain {domainName}");
            return null;
        }
    }


    /// <summary>
    /// View billing records for the account between a start and end date.
    /// </summary>
    /// <param name="startDate">The start date for billing results.</param>
    /// <param name="endDate">The end date for billing results.</param>
    /// <returns>A collection of billing records.</returns>
    public async Task<List<BillingRecord>> ViewBilling(DateTime startDate, DateTime endDate)
    {
        var results = new List<BillingRecord>();
        var paginateBilling = _amazonRoute53Domains.Paginators.ViewBilling(
            new ViewBillingRequest()
            {
                Start = startDate,
                End = endDate
            });

        // Get the entire list using the paginator.
        await foreach (var billingRecords in paginateBilling.BillingRecords)
        {
            results.Add(billingRecords);
        }
        return results;
    }


    /// <summary>
    /// List the domains for the account.
    /// </summary>
    /// <returns>A collection of domain summary records.</returns>
    public async Task<List<DomainSummary>> ListDomains()
    {
        var results = new List<DomainSummary>();
        var paginateDomains = _amazonRoute53Domains.Paginators.ListDomains(
            new ListDomainsRequest());

        // Get the entire list using the paginator.
        await foreach (var domain in paginateDomains.Domains)
        {
            results.Add(domain);
        }
        return results;
    }


    /// <summary>
    /// List operations for the account that are submitted after a specified date.
    /// </summary>
    /// <returns>A collection of operation summary records.</returns>
    public async Task<List<OperationSummary>> ListOperations(DateTime submittedSince)
    {
        var results = new List<OperationSummary>();
        var paginateOperations = _amazonRoute53Domains.Paginators.ListOperations(
            new ListOperationsRequest()
            {
                SubmittedSince = submittedSince
            });

        // Get the entire list using the paginator.
        await foreach (var operations in paginateOperations.Operations)
        {
            results.Add(operations);
        }
        return results;
    }


    /// <summary>
    /// Get details for a domain.
    /// </summary>
    /// <returns>A string with detail information about the domain.</returns>
    public async Task<string> GetDomainDetail(string domainName)
    {
        try
        {
            var result = await _amazonRoute53Domains.GetDomainDetailAsync(
                new GetDomainDetailRequest()
                {
                    DomainName = domainName
                });
            var details = $"\tDomain {domainName}:\n" +
                          $"\tCreated on {result.CreationDate.ToShortDateString()}.\n" +
                          $"\tAdmin contact is {result.AdminContact.Email}.\n" +
                          $"\tAuto-renew is {result.AutoRenew}.\n";

            return details;
        }
        catch (InvalidInputException)
        {
            return $"Domain {domainName} was not found in your account.";
        }
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CheckDomainAvailability](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/CheckDomainAvailability)
  + [CheckDomainTransferability](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/CheckDomainTransferability)
  + [GetDomainDetail](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/GetDomainDetail)
  + [GetDomainSuggestions](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/GetDomainSuggestions)
  + [GetOperationDetail](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/GetOperationDetail)
  + [ListDomains](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ListDomains)
  + [ListOperations](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ListOperations)
  + [ListPrices](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ListPrices)
  + [RegisterDomain](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/RegisterDomain)
  + [ViewBilling](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ViewBilling)

## アクション
<a name="actions"></a>

### `CheckDomainAvailability`
<a name="route-53-domains_CheckDomainAvailability_csharp_3_topic"></a>

次のコード例は、`CheckDomainAvailability` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Check the availability of a domain name.
    /// </summary>
    /// <param name="domain">The domain to check for availability.</param>
    /// <returns>An availability result string.</returns>
    public async Task<string> CheckDomainAvailability(string domain)
    {
        var result = await _amazonRoute53Domains.CheckDomainAvailabilityAsync(
            new CheckDomainAvailabilityRequest
            {
                DomainName = domain
            }
        );
        return result.Availability.Value;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[CheckDomainAvailability](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/CheckDomainAvailability)」を参照してください。

### `CheckDomainTransferability`
<a name="route-53-domains_CheckDomainTransferability_csharp_3_topic"></a>

次のコード例は、`CheckDomainTransferability` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Check the transferability of a domain name.
    /// </summary>
    /// <param name="domain">The domain to check for transferability.</param>
    /// <returns>A transferability result string.</returns>
    public async Task<string> CheckDomainTransferability(string domain)
    {
        var result = await _amazonRoute53Domains.CheckDomainTransferabilityAsync(
            new CheckDomainTransferabilityRequest
            {
                DomainName = domain
            }
        );
        return result.Transferability.Transferable.Value;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[CheckDomainTransferability](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/CheckDomainTransferability)」を参照してください。

### `GetDomainDetail`
<a name="route-53-domains_GetDomainDetail_csharp_3_topic"></a>

次のコード例は、`GetDomainDetail` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get details for a domain.
    /// </summary>
    /// <returns>A string with detail information about the domain.</returns>
    public async Task<string> GetDomainDetail(string domainName)
    {
        try
        {
            var result = await _amazonRoute53Domains.GetDomainDetailAsync(
                new GetDomainDetailRequest()
                {
                    DomainName = domainName
                });
            var details = $"\tDomain {domainName}:\n" +
                          $"\tCreated on {result.CreationDate.ToShortDateString()}.\n" +
                          $"\tAdmin contact is {result.AdminContact.Email}.\n" +
                          $"\tAuto-renew is {result.AutoRenew}.\n";

            return details;
        }
        catch (InvalidInputException)
        {
            return $"Domain {domainName} was not found in your account.";
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetDomainDetail](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/GetDomainDetail)」を参照してください。

### `GetDomainSuggestions`
<a name="route-53-domains_GetDomainSuggestions_csharp_3_topic"></a>

次のコード例は、`GetDomainSuggestions` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of suggestions for a given domain.
    /// </summary>
    /// <param name="domain">The domain to check for suggestions.</param>
    /// <param name="onlyAvailable">If true, only returns available domains.</param>
    /// <param name="suggestionCount">The number of suggestions to return. Defaults to the max of 50.</param>
    /// <returns>A collection of domain suggestions.</returns>
    public async Task<List<DomainSuggestion>> GetDomainSuggestions(string domain, bool onlyAvailable, int suggestionCount = 50)
    {
        var result = await _amazonRoute53Domains.GetDomainSuggestionsAsync(
            new GetDomainSuggestionsRequest
            {
                DomainName = domain,
                OnlyAvailable = onlyAvailable,
                SuggestionCount = suggestionCount
            }
        );
        return result.SuggestionsList;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetDomainSuggestions](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/GetDomainSuggestions)」を参照してください。

### `GetOperationDetail`
<a name="route-53-domains_GetOperationDetail_csharp_3_topic"></a>

次のコード例は、`GetOperationDetail` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get details for a domain action operation.
    /// </summary>
    /// <param name="operationId">The operational Id.</param>
    /// <returns>A string describing the operational details.</returns>
    public async Task<string> GetOperationDetail(string? operationId)
    {
        if (operationId == null)
            return "Unable to get operational details because ID is null.";
        try
        {
            var operationDetails =
                await _amazonRoute53Domains.GetOperationDetailAsync(
                    new GetOperationDetailRequest
                    {
                        OperationId = operationId
                    }
                );

            var details = $"\tOperation {operationId}:\n" +
                          $"\tFor domain {operationDetails.DomainName} on {operationDetails.SubmittedDate.ToShortDateString()}.\n" +
                          $"\tMessage is {operationDetails.Message}.\n" +
                          $"\tStatus is {operationDetails.Status}.\n";

            return details;
        }
        catch (AmazonRoute53DomainsException ex)
        {
            return $"Unable to get operation details. Here's why: {ex.Message}.";
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[GetOperationDetail](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/GetOperationDetail)」を参照してください。

### `ListDomains`
<a name="route-53-domains_ListDomains_csharp_3_topic"></a>

次のコード例は、`ListDomains` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List the domains for the account.
    /// </summary>
    /// <returns>A collection of domain summary records.</returns>
    public async Task<List<DomainSummary>> ListDomains()
    {
        var results = new List<DomainSummary>();
        var paginateDomains = _amazonRoute53Domains.Paginators.ListDomains(
            new ListDomainsRequest());

        // Get the entire list using the paginator.
        await foreach (var domain in paginateDomains.Domains)
        {
            results.Add(domain);
        }
        return results;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListDomains](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ListDomains)」を参照してください。

### `ListOperations`
<a name="route-53-domains_ListOperations_csharp_3_topic"></a>

次のコード例は、`ListOperations` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List operations for the account that are submitted after a specified date.
    /// </summary>
    /// <returns>A collection of operation summary records.</returns>
    public async Task<List<OperationSummary>> ListOperations(DateTime submittedSince)
    {
        var results = new List<OperationSummary>();
        var paginateOperations = _amazonRoute53Domains.Paginators.ListOperations(
            new ListOperationsRequest()
            {
                SubmittedSince = submittedSince
            });

        // Get the entire list using the paginator.
        await foreach (var operations in paginateOperations.Operations)
        {
            results.Add(operations);
        }
        return results;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListOperations](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ListOperations)」を参照してください。

### `ListPrices`
<a name="route-53-domains_ListPrices_csharp_3_topic"></a>

次のコード例は、`ListPrices` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List prices for domain type operations.
    /// </summary>
    /// <param name="domainTypes">Domain types to include in the results.</param>
    /// <returns>The list of domain prices.</returns>
    public async Task<List<DomainPrice>> ListPrices(List<string> domainTypes)
    {
        var results = new List<DomainPrice>();
        var paginatePrices = _amazonRoute53Domains.Paginators.ListPrices(new ListPricesRequest());
        // Get the entire list using the paginator.
        await foreach (var prices in paginatePrices.Prices)
        {
            results.Add(prices);
        }
        return results.Where(p => domainTypes.Contains(p.Name)).ToList();
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListPrices](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ListPrices)」を参照してください。

### `RegisterDomain`
<a name="route-53-domains_RegisterDomain_csharp_3_topic"></a>

次のコード例は、`RegisterDomain` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Initiate a domain registration request.
    /// </summary>
    /// <param name="contact">Contact details.</param>
    /// <param name="domainName">The domain name to register.</param>
    /// <param name="autoRenew">True if the domain should automatically renew.</param>
    /// <param name="duration">The duration in years for the domain registration.</param>
    /// <returns>The operation Id.</returns>
    public async Task<string?> RegisterDomain(string domainName, bool autoRenew, int duration, ContactDetail contact)
    {
        // This example uses the same contact information for admin, registrant, and tech contacts.
        try
        {
            var result = await _amazonRoute53Domains.RegisterDomainAsync(
                new RegisterDomainRequest()
                {
                    AdminContact = contact,
                    RegistrantContact = contact,
                    TechContact = contact,
                    DomainName = domainName,
                    AutoRenew = autoRenew,
                    DurationInYears = duration,
                    PrivacyProtectAdminContact = false,
                    PrivacyProtectRegistrantContact = false,
                    PrivacyProtectTechContact = false
                }
            );
            return result.OperationId;
        }
        catch (InvalidInputException)
        {
            _logger.LogInformation($"Unable to request registration for domain {domainName}");
            return null;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[RegisterDomain](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/RegisterDomain)」を参照してください。

### `ViewBilling`
<a name="route-53-domains_ViewBilling_csharp_3_topic"></a>

次のコード例は、`ViewBilling` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Route53#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// View billing records for the account between a start and end date.
    /// </summary>
    /// <param name="startDate">The start date for billing results.</param>
    /// <param name="endDate">The end date for billing results.</param>
    /// <returns>A collection of billing records.</returns>
    public async Task<List<BillingRecord>> ViewBilling(DateTime startDate, DateTime endDate)
    {
        var results = new List<BillingRecord>();
        var paginateBilling = _amazonRoute53Domains.Paginators.ViewBilling(
            new ViewBillingRequest()
            {
                Start = startDate,
                End = endDate
            });

        // Get the entire list using the paginator.
        await foreach (var billingRecords in paginateBilling.BillingRecords)
        {
            results.Add(billingRecords);
        }
        return results;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ViewBilling](https://docs.aws.amazon.com/goto/DotNetSDKV3/route53domains-2014-05-15/ViewBilling)」を参照してください。

# を使用した Amazon S3 の例 SDK for .NET
<a name="csharp_3_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_csharp_3_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。
条件付きリクエストを使用してオブジェクトをコピーします。  

```
    /// <summary>
    /// Copies an object from one Amazon S3 bucket to another with a conditional request.
    /// </summary>
    /// <param name="sourceKey">The key of the source object to copy.</param>
    /// <param name="destKey">The key of the destination object.</param>
    /// <param name="sourceBucket">The source bucket of the object.</param>
    /// <param name="destBucket">The destination bucket of the object.</param>
    /// <param name="conditionType">The type of condition to apply, e.g. 'CopySourceIfMatch', 'CopySourceIfNoneMatch', 'CopySourceIfModifiedSince', 'CopySourceIfUnmodifiedSince'.</param>
    /// <param name="conditionDateValue">The value to use for the condition for dates.</param>
    /// <param name="etagConditionalValue">The value to use for the condition for etags.</param>
    /// <returns>True if the conditional copy is successful, False otherwise.</returns>
    public async Task<bool> CopyObjectConditional(string sourceKey, string destKey, string sourceBucket, string destBucket,
        S3ConditionType conditionType, DateTime? conditionDateValue = null, string? etagConditionalValue = null)
    {
        try
        {
            var copyObjectRequest = new CopyObjectRequest
            {
                DestinationBucket = destBucket,
                DestinationKey = destKey,
                SourceBucket = sourceBucket,
                SourceKey = sourceKey
            };

            switch (conditionType)
            {
                case S3ConditionType.IfMatch:
                    copyObjectRequest.ETagToMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfNoneMatch:
                    copyObjectRequest.ETagToNotMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfModifiedSince:
                    copyObjectRequest.ModifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                case S3ConditionType.IfUnmodifiedSince:
                    copyObjectRequest.UnmodifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(conditionType), conditionType, null);
            }

            await _amazonS3.CopyObjectAsync(copyObjectRequest);
            _logger.LogInformation($"Conditional copy successful for key {destKey} in bucket {destBucket}.");
            return true;
        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "PreconditionFailed")
            {
                _logger.LogError("Conditional copy failed: Precondition failed");
            }
            else if (e.ErrorCode == "304")
            {
                _logger.LogError("Conditional copy failed: Object not modified");
            }
            else
            {
                _logger.LogError($"Unexpected error: {e.ErrorCode}");
                throw;
            }
            return false;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[CopyObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CopyObject)」を参照してください。**

### `CreateBucket`
<a name="s3_CreateBucket_csharp_3_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。
オブジェクトロックを有効にしてバケットを作成します。  

```
    /// <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;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateBucket](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CreateBucket)」を参照してください。

### `DeleteBucketCors`
<a name="s3_DeleteBucketCors_csharp_3_topic"></a>

次の例は、`DeleteBucketCors` を使用する方法を説明しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// Deletes a CORS configuration from an Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used
        /// to delete the CORS configuration from the bucket.</param>
        private static async Task DeleteCORSConfigurationAsync(AmazonS3Client client)
        {
            DeleteCORSConfigurationRequest request = new DeleteCORSConfigurationRequest()
            {
                BucketName = BucketName,
            };
            await client.DeleteCORSConfigurationAsync(request);
        }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DeleteBucketCors](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/DeleteBucketCors)」を参照してください。**

### `DeleteBucketLifecycle`
<a name="s3_DeleteBucketLifecycle_csharp_3_topic"></a>

次のコード例は、`DeleteBucketLifecycle` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// This method removes the Lifecycle configuration from the named
        /// S3 bucket.
        /// </summary>
        /// <param name="client">The S3 client object used to call
        /// the RemoveLifecycleConfigAsync method.</param>
        /// <param name="bucketName">A string representing the name of the
        /// S3 bucket from which the configuration will be removed.</param>
        public static async Task RemoveLifecycleConfigAsync(IAmazonS3 client, string bucketName)
        {
            var request = new DeleteLifecycleConfigurationRequest()
            {
                BucketName = bucketName,
            };
            await client.DeleteLifecycleConfigurationAsync(request);
        }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteBucketLifecycle](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/DeleteBucketLifecycle)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_csharp_3_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。
バージョニング非対応の S3 バケットからオブジェクトを削除します。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to delete an object from a non-versioned Amazon
    /// Simple Storage Service (Amazon S3) bucket.
    /// </summary>
    public class DeleteObject
    {
        /// <summary>
        /// The Main method initializes the necessary variables and then calls
        /// the DeleteObjectNonVersionedBucketAsync method to delete the object
        /// named by the keyName parameter.
        /// </summary>
        public static async Task Main()
        {
            const string bucketName = "amzn-s3-demo-bucket";
            const string keyName = "testfile.txt";

            // If the Amazon S3 bucket is located in an AWS Region other than the
            // Region of the default account, define the AWS Region for the
            // Amazon S3 bucket in your call to the AmazonS3Client constructor.
            // For example RegionEndpoint.USWest2.
            IAmazonS3 client = new AmazonS3Client();
            await DeleteObjectNonVersionedBucketAsync(client, bucketName, keyName);
        }

        /// <summary>
        /// The DeleteObjectNonVersionedBucketAsync takes care of deleting the
        /// desired object from the named bucket.
        /// </summary>
        /// <param name="client">An initialized Amazon S3 client used to delete
        /// an object from an Amazon S3 bucket.</param>
        /// <param name="bucketName">The name of the bucket from which the
        /// object will be deleted.</param>
        /// <param name="keyName">The name of the object to delete.</param>
        public static async Task DeleteObjectNonVersionedBucketAsync(IAmazonS3 client, string bucketName, string keyName)
        {
            try
            {
                var deleteObjectRequest = new DeleteObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                };

                Console.WriteLine($"Deleting object: {keyName}");
                await client.DeleteObjectAsync(deleteObjectRequest);
                Console.WriteLine($"Object: {keyName} deleted from {bucketName}.");
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' when deleting an object.");
            }
        }
    }
```
バージョニングされた S3 バケットからオブジェクトを削除します。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example creates an object in an Amazon Simple Storage Service
    /// (Amazon S3) bucket and then deletes the object version that was
    /// created.
    /// </summary>
    public class DeleteObjectVersion
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";
            string keyName = "verstioned-object.txt";

            // If the AWS Region of the default user is different from the AWS
            // Region of the Amazon S3 bucket, pass the AWS Region of the
            // bucket region to the Amazon S3 client object's constructor.
            // Define it like this:
            //      RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
            IAmazonS3 client = new AmazonS3Client();

            await CreateAndDeleteObjectVersionAsync(client, bucketName, keyName);
        }

        /// <summary>
        /// This method creates and then deletes a versioned object.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to
        /// create and delete the object.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket where the
        /// object will be created and deleted.</param>
        /// <param name="keyName">The key name of the object to create.</param>
        public static async Task CreateAndDeleteObjectVersionAsync(IAmazonS3 client, string bucketName, string keyName)
        {
            try
            {
                // Add a sample object.
                string versionID = await PutAnObject(client, bucketName, keyName);

                // Delete the object by specifying an object key and a version ID.
                DeleteObjectRequest request = new DeleteObjectRequest()
                {
                    BucketName = bucketName,
                    Key = keyName,
                    VersionId = versionID,
                };

                Console.WriteLine("Deleting an object");
                await client.DeleteObjectAsync(request);
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }

        /// <summary>
        /// This method is used to create the temporary Amazon S3 object.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 object which will be used
        /// to create the temporary Amazon S3 object.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket where the object
        /// will be created.</param>
        /// <param name="objectKey">The name of the Amazon S3 object co create.</param>
        /// <returns>The Version ID of the created object.</returns>
        public static async Task<string> PutAnObject(IAmazonS3 client, string bucketName, string objectKey)
        {
            PutObjectRequest request = new PutObjectRequest()
            {
                BucketName = bucketName,
                Key = objectKey,
                ContentBody = "This is the content body!",
            };

            PutObjectResponse response = await client.PutObjectAsync(request);
            return response.VersionId;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_csharp_3_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。
バージョニング非対応の S3 バケットから複数のオブジェクトを削除します。  

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to delete multiple objects from an Amazon Simple
    /// Storage Service (Amazon S3) bucket.
    /// </summary>
    public class DeleteMultipleObjects
    {
        /// <summary>
        /// The Main method initializes the Amazon S3 client and the name of
        /// the bucket and then passes those values to MultiObjectDeleteAsync.
        /// </summary>
        public static async Task Main()
        {
            const string bucketName = "amzn-s3-demo-bucket";

            // If the Amazon S3 bucket from which you wish to delete objects is not
            // located in the same AWS Region as the default user, define the
            // AWS Region for the Amazon S3 bucket as a parameter to the client
            // constructor.
            IAmazonS3 s3Client = new AmazonS3Client();

            await MultiObjectDeleteAsync(s3Client, bucketName);
        }

        /// <summary>
        /// This method uses the passed Amazon S3 client to first create and then
        /// delete three files from the named bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// Amazon S3 methods.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket where objects
        /// will be created and then deleted.</param>
        public static async Task MultiObjectDeleteAsync(IAmazonS3 client, string bucketName)
        {
            // Create three sample objects which we will then delete.
            var keysAndVersions = await PutObjectsAsync(client, 3, bucketName);

            // Now perform the multi-object delete, passing the key names and
            // version IDs. Since we are working with a non-versioned bucket,
            // the object keys collection includes null version IDs.
            DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest
            {
                BucketName = bucketName,
                Objects = keysAndVersions,
            };

            // You can add a specific object key to the delete request using the
            // AddKey method of the multiObjectDeleteRequest.
            try
            {
                DeleteObjectsResponse response = await client.DeleteObjectsAsync(multiObjectDeleteRequest);
                Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count);
            }
            catch (DeleteObjectsException e)
            {
                PrintDeletionErrorStatus(e);
            }
        }

        /// <summary>
        /// Prints the list of errors raised by the call to DeleteObjectsAsync.
        /// </summary>
        /// <param name="ex">A collection of exceptions returned by the call to
        /// DeleteObjectsAsync.</param>
        public static void PrintDeletionErrorStatus(DeleteObjectsException ex)
        {
            DeleteObjectsResponse errorResponse = ex.Response;
            Console.WriteLine("x {0}", errorResponse.DeletedObjects.Count);

            Console.WriteLine($"Successfully deleted {errorResponse.DeletedObjects.Count}.");
            Console.WriteLine($"No. of objects failed to delete = {errorResponse.DeleteErrors.Count}");

            Console.WriteLine("Printing error data...");
            foreach (DeleteError deleteError in errorResponse.DeleteErrors)
            {
                Console.WriteLine($"Object Key: {deleteError.Key}\t{deleteError.Code}\t{deleteError.Message}");
            }
        }

        /// <summary>
        /// This method creates simple text file objects that can be used in
        /// the delete method.
        /// </summary>
        /// <param name="client">The Amazon S3 client used to call PutObjectAsync.</param>
        /// <param name="number">The number of objects to create.</param>
        /// <param name="bucketName">The name of the bucket where the objects
        /// will be created.</param>
        /// <returns>A list of keys (object keys) and versions that the calling
        /// method will use to delete the newly created files.</returns>
        public static async Task<List<KeyVersion>> PutObjectsAsync(IAmazonS3 client, int number, string bucketName)
        {
            List<KeyVersion> keys = new List<KeyVersion>();
            for (int i = 0; i < number; i++)
            {
                string key = "ExampleObject-" + new System.Random().Next();
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = key,
                    ContentBody = "This is the content body!",
                };

                PutObjectResponse response = await client.PutObjectAsync(request);

                // For non-versioned bucket operations, we only need the
                // object key.
                KeyVersion keyVersion = new KeyVersion
                {
                    Key = key,
                };
                keys.Add(keyVersion);
            }

            return keys;
        }
    }
```
バージョニングされた S3 バケットから複数のオブジェクトを削除します。  

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to delete objects in a version-enabled Amazon
    /// Simple StorageService (Amazon S3) bucket.
    /// </summary>
    public class DeleteMultipleObjects
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";

            // If the AWS Region for your Amazon S3 bucket is different from
            // the AWS Region of the default user, define the AWS Region for
            // the Amazon S3 bucket and pass it to the client constructor
            // like this:
            // RegionEndpoint bucketRegion = RegionEndpoint.USWest2;
            IAmazonS3 s3Client;

            s3Client = new AmazonS3Client();
            await DeleteMultipleObjectsFromVersionedBucketAsync(s3Client, bucketName);
        }

        /// <summary>
        /// This method removes multiple versions and objects from a
        /// version-enabled Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and
        /// RemoveDeleteMarkersAsync.</param>
        /// <param name="bucketName">The name of the bucket from which to delete
        /// objects.</param>
        public static async Task DeleteMultipleObjectsFromVersionedBucketAsync(IAmazonS3 client, string bucketName)
        {
            // Delete objects (specifying object version in the request).
            await DeleteObjectVersionsAsync(client, bucketName);

            // Delete objects (without specifying object version in the request).
            var deletedObjects = await DeleteObjectsAsync(client, bucketName);

            // Additional exercise - remove the delete markers Amazon S3 returned from
            // the preceding response. This results in the objects reappearing
            // in the bucket (you can verify the appearance/disappearance of
            // objects in the console).
            await RemoveDeleteMarkersAsync(client, bucketName, deletedObjects);
        }

        /// <summary>
        /// Creates and then deletes non-versioned Amazon S3 objects and then deletes
        /// them again. The method returns a list of the Amazon S3 objects deleted.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// PubObjectsAsync and NonVersionedDeleteAsync.</param>
        /// <param name="bucketName">The name of the bucket where the objects
        /// will be created and then deleted.</param>
        /// <returns>A list of DeletedObjects.</returns>
        public static async Task<List<DeletedObject>> DeleteObjectsAsync(IAmazonS3 client, string bucketName)
        {
            // Upload the sample objects.
            var keysAndVersions2 = await PutObjectsAsync(client, bucketName, 3);

            // Delete objects using only keys. Amazon S3 creates a delete marker and
            // returns its version ID in the response.
            List<DeletedObject> deletedObjects = await NonVersionedDeleteAsync(client, bucketName, keysAndVersions2);
            return deletedObjects;
        }

        /// <summary>
        /// This method creates several temporary objects and then deletes them.
        /// </summary>
        /// <param name="client">The S3 client.</param>
        /// <param name="bucketName">Name of the bucket.</param>
        /// <returns>Async task.</returns>
        public static async Task DeleteObjectVersionsAsync(IAmazonS3 client, string bucketName)
        {
            // Upload the sample objects.
            var keysAndVersions1 = await PutObjectsAsync(client, bucketName, 3);

            // Delete the specific object versions.
            await VersionedDeleteAsync(client, bucketName, keysAndVersions1);
        }

        /// <summary>
        /// Displays the list of information about deleted files to the console.
        /// </summary>
        /// <param name="e">Error information from the delete process.</param>
        private static void DisplayDeletionErrors(DeleteObjectsException e)
        {
            var errorResponse = e.Response;
            Console.WriteLine($"No. of objects successfully deleted = {errorResponse.DeletedObjects.Count}");
            Console.WriteLine($"No. of objects failed to delete = {errorResponse.DeleteErrors.Count}");
            Console.WriteLine("Printing error data...");
            foreach (var deleteError in errorResponse.DeleteErrors)
            {
                Console.WriteLine($"Object Key: {deleteError.Key}\t{deleteError.Code}\t{deleteError.Message}");
            }
        }

        /// <summary>
        /// Delete multiple objects from a version-enabled bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and
        /// RemoveDeleteMarkersAsync.</param>
        /// <param name="bucketName">The name of the bucket from which to delete
        /// objects.</param>
        /// <param name="keys">A list of key names for the objects to delete.</param>
        private static async Task VersionedDeleteAsync(IAmazonS3 client, string bucketName, List<KeyVersion> keys)
        {
            var multiObjectDeleteRequest = new DeleteObjectsRequest
            {
                BucketName = bucketName,
                Objects = keys, // This includes the object keys and specific version IDs.
            };

            try
            {
                Console.WriteLine("Executing VersionedDelete...");
                DeleteObjectsResponse response = await client.DeleteObjectsAsync(multiObjectDeleteRequest);
                Console.WriteLine($"Successfully deleted all the {response.DeletedObjects.Count} items");
            }
            catch (DeleteObjectsException ex)
            {
                DisplayDeletionErrors(ex);
            }
        }

        /// <summary>
        /// Deletes multiple objects from a non-versioned Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and
        /// RemoveDeleteMarkersAsync.</param>
        /// <param name="bucketName">The name of the bucket from which to delete
        /// objects.</param>
        /// <param name="keys">A list of key names for the objects to delete.</param>
        /// <returns>A list of the deleted objects.</returns>
        private static async Task<List<DeletedObject>> NonVersionedDeleteAsync(IAmazonS3 client, string bucketName, List<KeyVersion> keys)
        {
            // Create a request that includes only the object key names.
            DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest();
            multiObjectDeleteRequest.BucketName = bucketName;

            foreach (var key in keys)
            {
                multiObjectDeleteRequest.AddKey(key.Key);
            }

            // Execute DeleteObjectsAsync.
            // The DeleteObjectsAsync method adds a delete marker for each
            // object deleted. You can verify that the objects were removed
            // using the Amazon S3 console.
            DeleteObjectsResponse response;
            try
            {
                Console.WriteLine("Executing NonVersionedDelete...");
                response = await client.DeleteObjectsAsync(multiObjectDeleteRequest);
                Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count);
            }
            catch (DeleteObjectsException ex)
            {
                DisplayDeletionErrors(ex);
                throw; // Some deletions failed. Investigate before continuing.
            }

            // This response contains the DeletedObjects list which we use to delete the delete markers.
            return response.DeletedObjects;
        }

        /// <summary>
        /// Deletes the markers left after deleting the temporary objects.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and
        /// RemoveDeleteMarkersAsync.</param>
        /// <param name="bucketName">The name of the bucket from which to delete
        /// objects.</param>
        /// <param name="deletedObjects">A list of the objects that were deleted.</param>
        private static async Task RemoveDeleteMarkersAsync(IAmazonS3 client, string bucketName, List<DeletedObject> deletedObjects)
        {
            var keyVersionList = new List<KeyVersion>();

            foreach (var deletedObject in deletedObjects)
            {
                KeyVersion keyVersion = new KeyVersion
                {
                    Key = deletedObject.Key,
                    VersionId = deletedObject.DeleteMarkerVersionId,
                };
                keyVersionList.Add(keyVersion);
            }

            // Create another request to delete the delete markers.
            var multiObjectDeleteRequest = new DeleteObjectsRequest
            {
                BucketName = bucketName,
                Objects = keyVersionList,
            };

            // Now, delete the delete marker to bring your objects back to the bucket.
            try
            {
                Console.WriteLine("Removing the delete markers .....");
                var deleteObjectResponse = await client.DeleteObjectsAsync(multiObjectDeleteRequest);
                Console.WriteLine($"Successfully deleted the {deleteObjectResponse.DeletedObjects.Count} delete markers");
            }
            catch (DeleteObjectsException ex)
            {
                DisplayDeletionErrors(ex);
            }
        }

        /// <summary>
        /// Create temporary Amazon S3 objects to show how object deletion wors in an
        /// Amazon S3 bucket with versioning enabled.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// PutObjectAsync to create temporary objects for the example.</param>
        /// <param name="bucketName">A string representing the name of the S3
        /// bucket where we will create the temporary objects.</param>
        /// <param name="number">The number of temporary objects to create.</param>
        /// <returns>A list of the KeyVersion objects.</returns>
        private static async Task<List<KeyVersion>> PutObjectsAsync(IAmazonS3 client, string bucketName, int number)
        {
            var keys = new List<KeyVersion>();

            for (var i = 0; i < number; i++)
            {
                string key = "ObjectToDelete-" + new System.Random().Next();
                PutObjectRequest request = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = key,
                    ContentBody = "This is the content body!",
                };

                var response = await client.PutObjectAsync(request);
                KeyVersion keyVersion = new KeyVersion
                {
                    Key = key,
                    VersionId = response.VersionId,
                };

                keys.Add(keyVersion);
            }

            return keys;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/DeleteObjects)」を参照してください。**

### `GetBucketAcl`
<a name="s3_GetBucketAcl_csharp_3_topic"></a>

次のコード例は、`GetBucketAcl` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// Get the access control list (ACL) for the new bucket.
        /// </summary>
        /// <param name="client">The initialized client object used to get the
        /// access control list (ACL) of the bucket.</param>
        /// <param name="newBucketName">The name of the newly created bucket.</param>
        /// <returns>An S3AccessControlList.</returns>
        public static async Task<S3AccessControlList> GetACLForBucketAsync(IAmazonS3 client, string newBucketName)
        {
            // Retrieve bucket ACL to show that the ACL was properly applied to
            // the new bucket.
            GetACLResponse getACLResponse = await client.GetACLAsync(new GetACLRequest
            {
                BucketName = newBucketName,
            });

            return getACLResponse.AccessControlList;
        }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetBucketAcl](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetBucketAcl)」を参照してください。

### `GetBucketCors`
<a name="s3_GetBucketCors_csharp_3_topic"></a>

次のコード例は、`GetBucketCors` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// Retrieve the CORS configuration applied to the Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used
        /// to retrieve the CORS configuration.</param>
        /// <returns>The created CORS configuration object.</returns>
        private static async Task<CORSConfiguration> RetrieveCORSConfigurationAsync(AmazonS3Client client)
        {
            GetCORSConfigurationRequest request = new GetCORSConfigurationRequest()
            {
                BucketName = BucketName,
            };
            var response = await client.GetCORSConfigurationAsync(request);
            var configuration = response.Configuration;
            PrintCORSRules(configuration);
            return configuration;
        }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[GetBucketCors](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetBucketCors)」を参照してください。**

### `GetBucketEncryption`
<a name="s3_GetBucketEncryption_csharp_3_topic"></a>

次のコード例は、`GetBucketEncryption` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/PutBucketEncryption#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get and print the encryption settings of a bucket.
    /// </summary>
    /// <param name="bucketName">Name of the bucket.</param>
    /// <returns>Async task.</returns>
    public static async Task GetEncryptionSettings(string bucketName)
    {
        // Check and print the bucket encryption settings.
        Console.WriteLine($"Getting encryption settings for bucket {bucketName}.");

        try
        {
            var settings =
                await _s3Client.GetBucketEncryptionAsync(
                    new GetBucketEncryptionRequest() { BucketName = bucketName });

            foreach (var encryptionSettings in settings?.ServerSideEncryptionConfiguration?.ServerSideEncryptionRules!)
            {
                Console.WriteLine(
                    $"\tAlgorithm: {encryptionSettings.ServerSideEncryptionByDefault.ServerSideEncryptionAlgorithm}");
                Console.WriteLine(
                    $"\tKey: {encryptionSettings.ServerSideEncryptionByDefault.ServerSideEncryptionKeyManagementServiceKeyId}");
            }
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine(ex.ErrorCode == "InvalidBucketName"
                ? $"Bucket {bucketName} was not found."
                : $"Unable to get bucket encryption for bucket {bucketName}, {ex.Message}");
        }
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」の「[GetBucketEncryption](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetBucketEncryption)」を参照してください。**

### `GetBucketLifecycleConfiguration`
<a name="s3_GetBucketLifecycleConfiguration_csharp_3_topic"></a>

次のコード例は、`GetBucketLifecycleConfiguration` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// Returns a configuration object for the supplied bucket name.
        /// </summary>
        /// <param name="client">The S3 client object used to call
        /// the GetLifecycleConfigurationAsync method.</param>
        /// <param name="bucketName">The name of the S3 bucket for which a
        /// configuration will be created.</param>
        /// <returns>Returns a new LifecycleConfiguration object.</returns>
        public static async Task<LifecycleConfiguration> RetrieveLifecycleConfigAsync(IAmazonS3 client, string bucketName)
        {
            var request = new GetLifecycleConfigurationRequest()
            {
                BucketName = bucketName,
            };
            var response = await client.GetLifecycleConfigurationAsync(request);
            var configuration = response.Configuration;
            return configuration;
        }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetBucketLifecycleConfiguration)」を参照してください。

### `GetBucketWebsite`
<a name="s3_GetBucketWebsite_csharp_3_topic"></a>

次のコード例は、`GetBucketWebsite` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
                // Get the website configuration.
                GetBucketWebsiteRequest getRequest = new GetBucketWebsiteRequest()
                {
                    BucketName = bucketName,
                };
                GetBucketWebsiteResponse getResponse = await client.GetBucketWebsiteAsync(getRequest);
                Console.WriteLine($"Index document: {getResponse.WebsiteConfiguration.IndexDocumentSuffix}");
                Console.WriteLine($"Error document: {getResponse.WebsiteConfiguration.ErrorDocument}");
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetBucketWebsite](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetBucketWebsite)」を参照してください。

### `GetObject`
<a name="s3_GetObject_csharp_3_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。
条件付きリクエストを使用してオブジェクトを取得します。  

```
    /// <summary>
    /// Retrieves an object from Amazon S3 with a conditional request.
    /// </summary>
    /// <param name="objectKey">The key of the object to retrieve.</param>
    /// <param name="sourceBucket">The source bucket of the object.</param>
    /// <param name="conditionType">The type of condition: 'IfMatch', 'IfNoneMatch', 'IfModifiedSince', 'IfUnmodifiedSince'.</param>
    /// <param name="conditionDateValue">The value to use for the condition for dates.</param>
    /// <param name="etagConditionalValue">The value to use for the condition for etags.</param>
    /// <returns>True if the conditional read is successful, False otherwise.</returns>
    public async Task<bool> GetObjectConditional(string objectKey, string sourceBucket,
        S3ConditionType conditionType, DateTime? conditionDateValue = null, string? etagConditionalValue = null)
    {
        try
        {
            var getObjectRequest = new GetObjectRequest
            {
                BucketName = sourceBucket,
                Key = objectKey
            };

            switch (conditionType)
            {
                case S3ConditionType.IfMatch:
                    getObjectRequest.EtagToMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfNoneMatch:
                    getObjectRequest.EtagToNotMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfModifiedSince:
                    getObjectRequest.ModifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                case S3ConditionType.IfUnmodifiedSince:
                    getObjectRequest.UnmodifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(conditionType), conditionType, null);
            }

            var response = await _amazonS3.GetObjectAsync(getObjectRequest);
            var sampleBytes = new byte[20];
            await response.ResponseStream.ReadAsync(sampleBytes, 0, 20);
            _logger.LogInformation($"Conditional read successful. Here are the first 20 bytes of the object:\n{System.Text.Encoding.UTF8.GetString(sampleBytes)}");
            return true;
        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "PreconditionFailed")
            {
                _logger.LogError("Conditional read failed: Precondition failed");
            }
            else if (e.ErrorCode == "NotModified")
            {
                _logger.LogError("Conditional read failed: Object not modified");
            }
            else
            {
                _logger.LogError($"Unexpected error: {e.ErrorCode}");
                throw;
            }
            return false;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[GetObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObject)」を参照してください。**

### `GetObjectLegalHold`
<a name="s3_GetObjectLegalHold_csharp_3_topic"></a>

次のコード例は、`GetObjectLegalHold` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ObjectLockScenario#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the legal hold details for an S3 object.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The object key.</param>
    /// <returns>The object legal hold details.</returns>
    public async Task<ObjectLockLegalHold> GetObjectLegalHold(string bucketName,
        string objectKey)
    {
        try
        {
            var request = new GetObjectLegalHoldRequest()
            {
                BucketName = bucketName,
                Key = objectKey
            };

            var response = await _amazonS3.GetObjectLegalHoldAsync(request);
            Console.WriteLine($"\tObject legal hold for {objectKey} in {bucketName}: " +
                              $"\n\tStatus: {response.LegalHold.Status}");
            return response.LegalHold;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to fetch legal hold: '{ex.Message}'");
            return new ObjectLockLegalHold();
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetObjectLegalHold](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectLegalHold)」を参照してください。

### `GetObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_csharp_3_topic"></a>

次のコード例は、`GetObjectLockConfiguration` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ObjectLockScenario#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the object lock configuration details for an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket to get details.</param>
    /// <returns>The bucket's object lock configuration details.</returns>
    public async Task<ObjectLockConfiguration> GetBucketObjectLockConfiguration(string bucketName)
    {
        try
        {
            var request = new GetObjectLockConfigurationRequest()
            {
                BucketName = bucketName
            };

            var response = await _amazonS3.GetObjectLockConfigurationAsync(request);
            Console.WriteLine($"\tBucket object lock config for {bucketName} in {bucketName}: " +
                              $"\n\tEnabled: {response.ObjectLockConfiguration.ObjectLockEnabled}" +
                              $"\n\tRule: {response.ObjectLockConfiguration.Rule?.DefaultRetention}");

            return response.ObjectLockConfiguration;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to fetch object lock config: '{ex.Message}'");
            return new ObjectLockConfiguration();
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetObjectLockConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectLockConfiguration)」を参照してください。

### `GetObjectRetention`
<a name="s3_GetObjectRetention_csharp_3_topic"></a>

次のコード例は、`GetObjectRetention` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ObjectLockScenario#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the retention period for an S3 object.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The object key.</param>
    /// <returns>The object retention details.</returns>
    public async Task<ObjectLockRetention> GetObjectRetention(string bucketName,
        string objectKey)
    {
        try
        {
            var request = new GetObjectRetentionRequest()
            {
                BucketName = bucketName,
                Key = objectKey
            };

            var response = await _amazonS3.GetObjectRetentionAsync(request);
            Console.WriteLine($"\tObject retention for {objectKey} in {bucketName}: " +
                              $"\n\t{response.Retention.Mode} until {response.Retention.RetainUntilDate:d}.");
            return response.Retention;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to fetch object lock retention: '{ex.Message}'");
            return new ObjectLockRetention();
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetObjectRetention](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectRetention)」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_csharp_3_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
namespace ListBucketsExample
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example uses the AWS SDK for .NET to list the Amazon Simple Storage
    /// Service (Amazon S3) buckets belonging to the default account.
    /// </summary>
    public class ListBuckets
    {
        private static IAmazonS3 _s3Client;

        /// <summary>
        /// Get a list of the buckets owned by the default user.
        /// </summary>
        /// <param name="client">An initialized Amazon S3 client object.</param>
        /// <returns>The response from the ListingBuckets call that contains a
        /// list of the buckets owned by the default user.</returns>
        public static async Task<ListBucketsResponse> GetBuckets(IAmazonS3 client)
        {
            return await client.ListBucketsAsync();
        }

        /// <summary>
        /// This method lists the name and creation date for the buckets in
        /// the passed List of S3 buckets.
        /// </summary>
        /// <param name="bucketList">A List of S3 bucket objects.</param>
        public static void DisplayBucketList(List<S3Bucket> bucketList)
        {
            bucketList
                .ForEach(b => Console.WriteLine($"Bucket name: {b.BucketName}, created on: {b.CreationDate}"));
        }

        public static async Task Main()
        {
            // The client uses the AWS Region of the default user.
            // If the Region where the buckets were created is different,
            // pass the Region to the client constructor. For example:
            // _s3Client = new AmazonS3Client(RegionEndpoint.USEast1);
            _s3Client = new AmazonS3Client();
            var response = await GetBuckets(_s3Client);
            DisplayBucketList(response.Buckets);
        }
    }
}
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/ListBuckets)」を参照してください。**

### `ListObjectVersions`
<a name="s3_ListObjectVersions_csharp_3_topic"></a>

次のコード例は、`ListObjectVersions` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example lists the versions of the objects in a version enabled
    /// Amazon Simple Storage Service (Amazon S3) bucket.
    /// </summary>
    public class ListObjectVersions
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";

            // If the AWS Region where your bucket is defined is different from
            // the AWS Region where the Amazon S3 bucket is defined, pass the constant
            // for the AWS Region to the client constructor like this:
            //      var client = new AmazonS3Client(RegionEndpoint.USWest2);
            IAmazonS3 client = new AmazonS3Client();
            await GetObjectListWithAllVersionsAsync(client, bucketName);
        }

        /// <summary>
        /// This method lists all versions of the objects within an Amazon S3
        /// version enabled bucket.
        /// </summary>
        /// <param name="client">The initialized client object used to call
        /// ListVersionsAsync.</param>
        /// <param name="bucketName">The name of the version enabled Amazon S3 bucket
        /// for which you want to list the versions of the contained objects.</param>
        public static async Task GetObjectListWithAllVersionsAsync(IAmazonS3 client, string bucketName)
        {
            try
            {
                // When you instantiate the ListVersionRequest, you can
                // optionally specify a key name prefix in the request
                // if you want a list of object versions of a specific object.

                // For this example we set a small limit in MaxKeys to return
                // a small list of versions.
                ListVersionsRequest request = new ListVersionsRequest()
                {
                    BucketName = bucketName,
                    MaxKeys = 2,
                };

                do
                {
                    ListVersionsResponse response = await client.ListVersionsAsync(request);

                    // Process response.
                    foreach (S3ObjectVersion entry in response.Versions)
                    {
                        Console.WriteLine($"key: {entry.Key} size: {entry.Size}");
                    }

                    // If response is truncated, set the marker to get the next
                    // set of keys.
                    if (response.IsTruncated)
                    {
                        request.KeyMarker = response.NextKeyMarker;
                        request.VersionIdMarker = response.NextVersionIdMarker;
                    }
                    else
                    {
                        request = null;
                    }
                }
                while (request != null);
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error: '{ex.Message}'");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListObjectVersions](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/ListObjectVersions)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_csharp_3_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。
ページネーターを使用してオブジェクトを一覧表示します。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// The following example lists objects in an Amazon Simple Storage
    /// Service (Amazon S3) bucket.
    /// </summary>
    public class ListObjectsPaginator
    {
        private const string BucketName = "amzn-s3-demo-bucket";

        public static async Task Main()
        {
            IAmazonS3 s3Client = new AmazonS3Client();

            Console.WriteLine($"Listing the objects contained in {BucketName}:\n");
            await ListingObjectsAsync(s3Client, BucketName);
        }

        /// <summary>
        /// This method uses a paginator to retrieve the list of objects in an
        /// an Amazon S3 bucket.
        /// </summary>
        /// <param name="client">An Amazon S3 client object.</param>
        /// <param name="bucketName">The name of the S3 bucket whose objects
        /// you want to list.</param>
        public static async Task ListingObjectsAsync(IAmazonS3 client, string bucketName)
        {
            var listObjectsV2Paginator = client.Paginators.ListObjectsV2(new ListObjectsV2Request
            {
                BucketName = bucketName,
            });

            await foreach (var response in listObjectsV2Paginator.Responses)
            {
                Console.WriteLine($"HttpStatusCode: {response.HttpStatusCode}");
                Console.WriteLine($"Number of Keys: {response.KeyCount}");
                foreach (var entry in response.S3Objects)
                {
                    Console.WriteLine($"Key = {entry.Key} Size = {entry.Size}");
                }
            }
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[ListObjectsV2](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/ListObjectsV2)」を参照してください。**

### `PutBucketAccelerateConfiguration`
<a name="s3_PutBucketAccelerateConfiguration_csharp_3_topic"></a>

次のコード例は、`PutBucketAccelerateConfiguration` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// Amazon Simple Storage Service (Amazon S3) Transfer Acceleration is a
    /// bucket-level feature that enables you to perform faster data transfers
    /// to Amazon S3. This example shows how to configure Transfer
    /// Acceleration.
    /// </summary>
    public class TransferAcceleration
    {
        /// <summary>
        /// The main method initializes the client object and sets the
        /// Amazon Simple Storage Service (Amazon S3) bucket name before
        /// calling EnableAccelerationAsync.
        /// </summary>
        public static async Task Main()
        {
            var s3Client = new AmazonS3Client();
            const string bucketName = "amzn-s3-demo-bucket";

            await EnableAccelerationAsync(s3Client, bucketName);
        }

        /// <summary>
        /// This method sets the configuration to enable transfer acceleration
        /// for the bucket referred to in the bucketName parameter.
        /// </summary>
        /// <param name="client">An Amazon S3 client used to enable the
        /// acceleration on an Amazon S3 bucket.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket for which the
        /// method will be enabling acceleration.</param>
        private static async Task EnableAccelerationAsync(AmazonS3Client client, string bucketName)
        {
            try
            {
                var putRequest = new PutBucketAccelerateConfigurationRequest
                {
                    BucketName = bucketName,
                    AccelerateConfiguration = new AccelerateConfiguration
                    {
                        Status = BucketAccelerateStatus.Enabled,
                    },
                };
                await client.PutBucketAccelerateConfigurationAsync(putRequest);

                var getRequest = new GetBucketAccelerateConfigurationRequest
                {
                    BucketName = bucketName,
                };
                var response = await client.GetBucketAccelerateConfigurationAsync(getRequest);

                Console.WriteLine($"Acceleration state = '{response.Status}' ");
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error occurred. Message:'{ex.Message}' when setting transfer acceleration");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[PutBucketAccelerateConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketAccelerateConfiguration)」を参照してください。

### `PutBucketAcl`
<a name="s3_PutBucketAcl_csharp_3_topic"></a>

次のコード例は、`PutBucketAcl` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// Creates an Amazon S3 bucket with an ACL to control access to the
        /// bucket and the objects stored in it.
        /// </summary>
        /// <param name="client">The initialized client object used to create
        /// an Amazon S3 bucket, with an ACL applied to the bucket.
        /// </param>
        /// <param name="region">The AWS Region where the bucket will be created.</param>
        /// <param name="newBucketName">The name of the bucket to create.</param>
        /// <returns>A boolean value indicating success or failure.</returns>
        public static async Task<bool> CreateBucketUseCannedACLAsync(IAmazonS3 client, S3Region region, string newBucketName)
        {
            try
            {
                // Create a new Amazon S3 bucket with Canned ACL.
                var putBucketRequest = new PutBucketRequest()
                {
                    BucketName = newBucketName,
                    BucketRegion = region,
                    CannedACL = S3CannedACL.LogDeliveryWrite,
                };

                PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest);

                return putBucketResponse.HttpStatusCode == System.Net.HttpStatusCode.OK;
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Amazon S3 error: {ex.Message}");
            }

            return false;
        }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutBucketAcl](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketAcl)」を参照してください。

### `PutBucketCors`
<a name="s3_PutBucketCors_csharp_3_topic"></a>

次のコード例は、`PutBucketCors` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// Add CORS configuration to the Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used
        /// to apply the CORS configuration to an Amazon S3 bucket.</param>
        /// <param name="configuration">The CORS configuration to apply.</param>
        private static async Task PutCORSConfigurationAsync(AmazonS3Client client, CORSConfiguration configuration)
        {
            PutCORSConfigurationRequest request = new PutCORSConfigurationRequest()
            {
                BucketName = BucketName,
                Configuration = configuration,
            };

            _ = await client.PutCORSConfigurationAsync(request);
        }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[PutBucketCors](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketCors)」を参照してください。**

### `PutBucketEncryption`
<a name="s3_PutBucketEncryption_csharp_3_topic"></a>

次のコード例は、`PutBucketEncryption` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/PutBucketEncryption#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Set the bucket server side encryption to use AWSKMS with a customer-managed key id.
    /// </summary>
    /// <param name="bucketName">Name of the bucket.</param>
    /// <param name="kmsKeyId">The Id of the KMS Key.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> SetBucketServerSideEncryption(string bucketName, string kmsKeyId)
    {
        var serverSideEncryptionByDefault = new ServerSideEncryptionConfiguration
        {
            ServerSideEncryptionRules = new List<ServerSideEncryptionRule>
            {
                new ServerSideEncryptionRule
                {
                    ServerSideEncryptionByDefault = new ServerSideEncryptionByDefault
                    {
                        ServerSideEncryptionAlgorithm = ServerSideEncryptionMethod.AWSKMS,
                        ServerSideEncryptionKeyManagementServiceKeyId = kmsKeyId
                    }
                }
            }
        };
        try
        {
            var encryptionResponse = await _s3Client.PutBucketEncryptionAsync(new PutBucketEncryptionRequest
            {
                BucketName = bucketName,
                ServerSideEncryptionConfiguration = serverSideEncryptionByDefault,
            });
            
            return encryptionResponse.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine(ex.ErrorCode == "AccessDenied"
                ? $"This account does not have permission to set encryption on {bucketName}, please try again."
                : $"Unable to set bucket encryption for bucket {bucketName}, {ex.Message}");
        }
        return false;
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」の「[PutBucketEncryption](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketEncryption)」を参照してください。**

### `PutBucketLifecycleConfiguration`
<a name="s3_PutBucketLifecycleConfiguration_csharp_3_topic"></a>

次のコード例は、`PutBucketLifecycleConfiguration` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
        /// <summary>
        /// Adds lifecycle configuration information to the S3 bucket named in
        /// the bucketName parameter.
        /// </summary>
        /// <param name="client">The S3 client used to call the
        /// PutLifecycleConfigurationAsync method.</param>
        /// <param name="bucketName">A string representing the S3 bucket to
        /// which configuration information will be added.</param>
        /// <param name="configuration">A LifecycleConfiguration object that
        /// will be applied to the S3 bucket.</param>
        public static async Task AddExampleLifecycleConfigAsync(IAmazonS3 client, string bucketName, LifecycleConfiguration configuration)
        {
            var request = new PutLifecycleConfigurationRequest()
            {
                BucketName = bucketName,
                Configuration = configuration,
            };
            var response = await client.PutLifecycleConfigurationAsync(request);
        }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketLifecycleConfiguration)」を参照してください。

### `PutBucketLogging`
<a name="s3_PutBucketLogging_csharp_3_topic"></a>

次のコード例は、`PutBucketLogging` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;
    using Microsoft.Extensions.Configuration;

    /// <summary>
    /// This example shows how to enable logging on an Amazon Simple Storage
    /// Service (Amazon S3) bucket. You need to have two Amazon S3 buckets for
    /// this example. The first is the bucket for which you wish to enable
    /// logging, and the second is the location where you want to store the
    /// logs.
    /// </summary>
    public class ServerAccessLogging
    {
        private static IConfiguration _configuration = null!;

        public static async Task Main()
        {
            LoadConfig();

            string bucketName = _configuration["BucketName"];
            string logBucketName = _configuration["LogBucketName"];
            string logObjectKeyPrefix = _configuration["LogObjectKeyPrefix"];
            string accountId = _configuration["AccountId"];

            // If the AWS Region defined for your default user is different
            // from the Region where your Amazon S3 bucket is located,
            // pass the Region name to the Amazon S3 client object's constructor.
            // For example: RegionEndpoint.USWest2 or RegionEndpoint.USEast2.
            IAmazonS3 client = new AmazonS3Client();

            try
            {
                // Update bucket policy for target bucket to allow delivery of logs to it.
                await SetBucketPolicyToAllowLogDelivery(
                    client,
                    bucketName,
                    logBucketName,
                    logObjectKeyPrefix,
                    accountId);

                // Enable logging on the source bucket.
                await EnableLoggingAsync(
                    client,
                    bucketName,
                    logBucketName,
                    logObjectKeyPrefix);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }
        }

        /// <summary>
        /// This method grants appropriate permissions for logging to the
        /// Amazon S3 bucket where the logs will be stored.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client which will be used
        /// to apply the bucket policy.</param>
        /// <param name="sourceBucketName">The name of the source bucket.</param>
        /// <param name="logBucketName">The name of the bucket where logging
        /// information will be stored.</param>
        /// <param name="logPrefix">The logging prefix where the logs should be delivered.</param>
        /// <param name="accountId">The account id of the account where the source bucket exists.</param>
        /// <returns>Async task.</returns>
        public static async Task SetBucketPolicyToAllowLogDelivery(
            IAmazonS3 client,
            string sourceBucketName,
            string logBucketName,
            string logPrefix,
            string accountId)
        {
            var resourceArn = @"""arn:aws:s3:::" + logBucketName + "/" + logPrefix + @"*""";

            var newPolicy = @"{
                                ""Statement"":[{
                                ""Sid"": ""S3ServerAccessLogsPolicy"",
                                ""Effect"": ""Allow"",
                                ""Principal"": { ""Service"": ""logging.s3.amazonaws.com"" },
                                ""Action"": [""s3:PutObject""],
                                ""Resource"": [" + resourceArn + @"],
                                ""Condition"": {
                                ""ArnLike"": { ""aws:SourceArn"": ""arn:aws:s3:::" + sourceBucketName + @""" },
                                ""StringEquals"": { ""aws:SourceAccount"": """ + accountId + @""" }
                                        }
                                    }]
                                }";
            Console.WriteLine($"The policy to apply to bucket {logBucketName} to enable logging:");
            Console.WriteLine(newPolicy);

            PutBucketPolicyRequest putRequest = new PutBucketPolicyRequest
            {
                BucketName = logBucketName,
                Policy = newPolicy,
            };
            await client.PutBucketPolicyAsync(putRequest);
            Console.WriteLine("Policy applied.");
        }

        /// <summary>
        /// This method enables logging for an Amazon S3 bucket. Logs will be stored
        /// in the bucket you selected for logging. Selected prefix
        /// will be prepended to each log object.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client which will be used
        /// to configure and apply logging to the selected Amazon S3 bucket.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket for which you
        /// wish to enable logging.</param>
        /// <param name="logBucketName">The name of the Amazon S3 bucket where logging
        /// information will be stored.</param>
        /// <param name="logObjectKeyPrefix">The prefix to prepend to each
        /// object key.</param>
        /// <returns>Async task.</returns>
        public static async Task EnableLoggingAsync(
            IAmazonS3 client,
            string bucketName,
            string logBucketName,
            string logObjectKeyPrefix)
        {
            Console.WriteLine($"Enabling logging for bucket {bucketName}.");
            var loggingConfig = new S3BucketLoggingConfig
            {
                TargetBucketName = logBucketName,
                TargetPrefix = logObjectKeyPrefix,
            };

            var putBucketLoggingRequest = new PutBucketLoggingRequest
            {
                BucketName = bucketName,
                LoggingConfig = loggingConfig,
            };
            await client.PutBucketLoggingAsync(putBucketLoggingRequest);
            Console.WriteLine($"Logging enabled.");
        }

        /// <summary>
        /// Loads configuration from settings files.
        /// </summary>
        public static void LoadConfig()
        {
            _configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("settings.json") // Load settings from .json file.
                .AddJsonFile("settings.local.json", true) // Optionally, load local settings.
                .Build();
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[PutBucketLogging](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketLogging)」を参照してください。

### `PutBucketNotificationConfiguration`
<a name="s3_PutBucketNotificationConfiguration_csharp_3_topic"></a>

次のコード例は、`PutBucketNotificationConfiguration` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to enable notifications for an Amazon Simple
    /// Storage Service (Amazon S3) bucket.
    /// </summary>
    public class EnableNotifications
    {
        public static async Task Main()
        {
            const string bucketName = "amzn-s3-demo-bucket1";
            const string snsTopic = "arn:aws:sns:us-east-2:0123456789ab:bucket-notify";
            const string sqsQueue = "arn:aws:sqs:us-east-2:0123456789ab:Example_Queue";

            IAmazonS3 client = new AmazonS3Client(Amazon.RegionEndpoint.USEast2);
            await EnableNotificationAsync(client, bucketName, snsTopic, sqsQueue);
        }

        /// <summary>
        /// This method makes the call to the PutBucketNotificationAsync method.
        /// </summary>
        /// <param name="client">An initialized Amazon S3 client used to call
        /// the PutBucketNotificationAsync method.</param>
        /// <param name="bucketName">The name of the bucket for which
        /// notifications will be turned on.</param>
        /// <param name="snsTopic">The ARN for the Amazon Simple Notification
        /// Service (Amazon SNS) topic associated with the S3 bucket.</param>
        /// <param name="sqsQueue">The ARN of the Amazon Simple Queue Service
        /// (Amazon SQS) queue to which notifications will be pushed.</param>
        public static async Task EnableNotificationAsync(
            IAmazonS3 client,
            string bucketName,
            string snsTopic,
            string sqsQueue)
        {
            try
            {
                // The bucket for which we are setting up notifications.
                var request = new PutBucketNotificationRequest()
                {
                    BucketName = bucketName,
                };

                // Defines the topic to use when sending a notification.
                var topicConfig = new TopicConfiguration()
                {
                    Events = new List<EventType> { EventType.ObjectCreatedCopy },
                    Topic = snsTopic,
                };
                request.TopicConfigurations = new List<TopicConfiguration>
                {
                    topicConfig,
                };
                request.QueueConfigurations = new List<QueueConfiguration>
                {
                    new QueueConfiguration()
                    {
                        Events = new List<EventType> { EventType.ObjectCreatedPut },
                        Queue = sqsQueue,
                    },
                };

                // Now apply the notification settings to the bucket.
                PutBucketNotificationResponse response = await client.PutBucketNotificationAsync(request);
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[PutBucketNotificationConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketNotificationConfiguration)」を参照してください。

### `PutBucketWebsite`
<a name="s3_PutBucketWebsite_csharp_3_topic"></a>

次のコード例は、`PutBucketWebsite` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
                // Put the website configuration.
                PutBucketWebsiteRequest putRequest = new PutBucketWebsiteRequest()
                {
                    BucketName = bucketName,
                    WebsiteConfiguration = new WebsiteConfiguration()
                    {
                        IndexDocumentSuffix = indexDocumentSuffix,
                        ErrorDocument = errorDocument,
                    },
                };
                PutBucketWebsiteResponse response = await client.PutBucketWebsiteAsync(putRequest);
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「*PutBucketWebsite*」を参照してください。[https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketWebsite](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketWebsite)

### `PutObject`
<a name="s3_PutObject_csharp_3_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。
サーバー側の暗号化を使用してオブジェクトをアップロードします。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to upload an object to an Amazon Simple Storage
    /// Service (Amazon S3) bucket with server-side encryption enabled.
    /// </summary>
    public class ServerSideEncryption
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";
            string keyName = "samplefile.txt";

            // If the AWS Region defined for your default user is different
            // from the Region where your Amazon S3 bucket is located,
            // pass the Region name to the Amazon S3 client object's constructor.
            // For example: RegionEndpoint.USWest2.
            IAmazonS3 client = new AmazonS3Client();

            await WritingAnObjectAsync(client, bucketName, keyName);
        }

        /// <summary>
        /// Upload a sample object include a setting for encryption.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to
        /// to upload a file and apply server-side encryption.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket where the
        /// encrypted object will reside.</param>
        /// <param name="keyName">The name for the object that you want to
        /// create in the supplied bucket.</param>
        public static async Task WritingAnObjectAsync(IAmazonS3 client, string bucketName, string keyName)
        {
            try
            {
                var putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                    ContentBody = "sample text",
                    ServerSideEncryptionMethod = ServerSideEncryptionMethod.AES256,
                };

                var putResponse = await client.PutObjectAsync(putRequest);

                // Determine the encryption state of an object.
                GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                };
                GetObjectMetadataResponse response = await client.GetObjectMetadataAsync(metadataRequest);
                ServerSideEncryptionMethod objectEncryption = response.ServerSideEncryptionMethod;

                Console.WriteLine($"Encryption method used: {0}", objectEncryption.ToString());
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error: '{ex.Message}' when writing an object");
            }
        }
    }
```
条件付きリクエストを使用してオブジェクトを配置します。  

```
    /// <summary>
    /// Uploads an object to Amazon S3 with a conditional request. Prevents overwrite using an IfNoneMatch condition for the object key.
    /// </summary>
    /// <param name="objectKey">The key of the object to upload.</param>
    /// <param name="bucket">The source bucket of the object.</param>
    /// <param name="content">The content to upload as a string.</param>
    /// <returns>The ETag if the conditional write is successful, empty otherwise.</returns>
    public async Task<string> PutObjectConditional(string objectKey, string bucket, string content)
    {
        try
        {
            var putObjectRequest = new PutObjectRequest
            {
                BucketName = bucket,
                Key = objectKey,
                ContentBody = content,
                IfNoneMatch = "*"
            };

            var putResult = await _amazonS3.PutObjectAsync(putObjectRequest);
            _logger.LogInformation($"Conditional write successful for key {objectKey} in bucket {bucket}.");
            return putResult.ETag;
        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "PreconditionFailed")
            {
                _logger.LogError("Conditional write failed: Precondition failed");
            }
            else
            {
                _logger.LogError($"Unexpected error: {e.ErrorCode}");
                throw;
            }
            return string.Empty;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObject)」を参照してください。

### `PutObjectLegalHold`
<a name="s3_PutObjectLegalHold_csharp_3_topic"></a>

次のコード例は、`PutObjectLegalHold` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ObjectLockScenario#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Set or modify a legal hold on an object in an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The key of the object.</param>
    /// <param name="holdStatus">The On or Off status for the legal hold.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyObjectLegalHold(string bucketName,
        string objectKey, ObjectLockLegalHoldStatus holdStatus)
    {
        try
        {
            var request = new PutObjectLegalHoldRequest()
            {
                BucketName = bucketName,
                Key = objectKey,
                LegalHold = new ObjectLockLegalHold()
                {
                    Status = holdStatus
                }
            };

            var response = await _amazonS3.PutObjectLegalHoldAsync(request);
            Console.WriteLine($"\tModified legal hold for {objectKey} in {bucketName}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tError modifying legal hold: '{ex.Message}'");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutObjectLegalHold](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObjectLegalHold)」を参照してください。

### `PutObjectLockConfiguration`
<a name="s3_PutObjectLockConfiguration_csharp_3_topic"></a>

次のコード例は、`PutObjectLockConfiguration` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ObjectLockScenario#code-examples)での設定と実行の方法を確認してください。
バケットのオブジェクトロック設定を指定します。  

```
    /// <summary>
    /// Enable object lock on an existing bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket to modify.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> EnableObjectLockOnBucket(string bucketName)
    {
        try
        {
            // First, enable Versioning on the bucket.
            await _amazonS3.PutBucketVersioningAsync(new PutBucketVersioningRequest()
            {
                BucketName = bucketName,
                VersioningConfig = new S3BucketVersioningConfig()
                {
                    EnableMfaDelete = false,
                    Status = VersionStatus.Enabled
                }
            });

            var request = new PutObjectLockConfigurationRequest()
            {
                BucketName = bucketName,
                ObjectLockConfiguration = new ObjectLockConfiguration()
                {
                    ObjectLockEnabled = new ObjectLockEnabled("Enabled"),
                },
            };

            var response = await _amazonS3.PutObjectLockConfigurationAsync(request);
            Console.WriteLine($"\tAdded an object lock policy to bucket {bucketName}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error modifying object lock: '{ex.Message}'");
            return false;
        }
    }
```
バケットのデフォルトの保存期間を設定します。  

```
    /// <summary>
    /// Set or modify a retention period on an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket to modify.</param>
    /// <param name="retention">The retention mode.</param>
    /// <param name="retainUntilDate">The date for retention until.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyBucketDefaultRetention(string bucketName, bool enableObjectLock, ObjectLockRetentionMode retention, DateTime retainUntilDate)
    {
        var enabledString = enableObjectLock ? "Enabled" : "Disabled";
        var timeDifference = retainUntilDate.Subtract(DateTime.Now);
        try
        {
            // First, enable Versioning on the bucket.
            await _amazonS3.PutBucketVersioningAsync(new PutBucketVersioningRequest()
            {
                BucketName = bucketName,
                VersioningConfig = new S3BucketVersioningConfig()
                {
                    EnableMfaDelete = false,
                    Status = VersionStatus.Enabled
                }
            });

            var request = new PutObjectLockConfigurationRequest()
            {
                BucketName = bucketName,
                ObjectLockConfiguration = new ObjectLockConfiguration()
                {
                    ObjectLockEnabled = new ObjectLockEnabled(enabledString),
                    Rule = new ObjectLockRule()
                    {
                        DefaultRetention = new DefaultRetention()
                        {
                            Mode = retention,
                            Days = timeDifference.Days // Can be specified in days or years but not both.
                        }
                    }
                }
            };

            var response = await _amazonS3.PutObjectLockConfigurationAsync(request);
            Console.WriteLine($"\tAdded a default retention to bucket {bucketName}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tError modifying object lock: '{ex.Message}'");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutObjectLockConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObjectLockConfiguration)」を参照してください。

### `PutObjectRetention`
<a name="s3_PutObjectRetention_csharp_3_topic"></a>

次のコード例は、`PutObjectRetention` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ObjectLockScenario#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Set or modify a retention period on an object in an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The key of the object.</param>
    /// <param name="retention">The retention mode.</param>
    /// <param name="retainUntilDate">The date retention expires.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyObjectRetentionPeriod(string bucketName,
        string objectKey, ObjectLockRetentionMode retention, DateTime retainUntilDate)
    {
        try
        {
            var request = new PutObjectRetentionRequest()
            {
                BucketName = bucketName,
                Key = objectKey,
                Retention = new ObjectLockRetention()
                {
                    Mode = retention,
                    RetainUntilDate = retainUntilDate
                }
            };

            var response = await _amazonS3.PutObjectRetentionAsync(request);
            Console.WriteLine($"\tSet retention for {objectKey} in {bucketName} until {retainUntilDate:d}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tError modifying retention period: '{ex.Message}'");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutObjectRetention](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObjectRetention)」を参照してください。

### `RestoreObject`
<a name="s3_RestoreObject_csharp_3_topic"></a>

次のコード例は、`RestoreObject` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to restore an archived object in an Amazon
    /// Simple Storage Service (Amazon S3) bucket.
    /// </summary>
    public class RestoreArchivedObject
    {
        public static void Main()
        {
            string bucketName = "amzn-s3-demo-bucket";
            string objectKey = "archived-object.txt";

            // Specify your bucket region (an example region is shown).
            RegionEndpoint bucketRegion = RegionEndpoint.USWest2;

            IAmazonS3 client = new AmazonS3Client(bucketRegion);
            RestoreObjectAsync(client, bucketName, objectKey).Wait();
        }

        /// <summary>
        /// This method restores an archived object from an Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// RestoreObjectAsync.</param>
        /// <param name="bucketName">A string representing the name of the
        /// bucket where the object was located before it was archived.</param>
        /// <param name="objectKey">A string representing the name of the
        /// archived object to restore.</param>
        public static async Task RestoreObjectAsync(IAmazonS3 client, string bucketName, string objectKey)
        {
            try
            {
                var restoreRequest = new RestoreObjectRequest
                {
                    BucketName = bucketName,
                    Key = objectKey,
                    Days = 2,
                };
                RestoreObjectResponse response = await client.RestoreObjectAsync(restoreRequest);

                // Check the status of the restoration.
                await CheckRestorationStatusAsync(client, bucketName, objectKey);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                Console.WriteLine($"Error: {amazonS3Exception.Message}");
            }
        }

        /// <summary>
        /// This method retrieves the status of the object's restoration.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// GetObjectMetadataAsync.</param>
        /// <param name="bucketName">A string representing the name of the Amazon
        /// S3 bucket which contains the archived object.</param>
        /// <param name="objectKey">A string representing the name of the
        /// archived object you want to restore.</param>
        public static async Task CheckRestorationStatusAsync(IAmazonS3 client, string bucketName, string objectKey)
        {
            GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest()
            {
                BucketName = bucketName,
                Key = objectKey,
            };

            GetObjectMetadataResponse response = await client.GetObjectMetadataAsync(metadataRequest);

            var restStatus = response.RestoreInProgress ? "in-progress" : "finished or failed";
            Console.WriteLine($"Restoration status: {restStatus}");
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[RestoreObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/RestoreObject)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_csharp_3_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/#code-examples)での設定と実行の方法を確認してください。
Amazon S3 アクションを期間限定で実行できる署名付き URL を生成します。  

```
    using System;
    using Amazon;
    using Amazon.S3;
    using Amazon.S3.Model;

    public class GenPresignedUrl
    {
        public static void Main()
        {
            const string bucketName = "amzn-s3-demo-bucket";
            const string objectKey = "sample.txt";

            // Specify how long the presigned URL lasts, in hours
            const double timeoutDuration = 12;

            // Specify the AWS Region of your Amazon S3 bucket. If it is
            // different from the Region defined for the default user,
            // pass the Region to the constructor for the client. For
            // example: new AmazonS3Client(RegionEndpoint.USEast1);

            // If using the Region us-east-1, and server-side encryption with AWS KMS, you must specify Signature Version 4.
            // Region us-east-1 defaults to Signature Version 2 unless explicitly set to Version 4 as shown below.
            // For more details, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingAWSSDK.html#specify-signature-version
            // and https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Amazon/TAWSConfigsS3.html
            AWSConfigsS3.UseSignatureVersion4 = true;
            IAmazonS3 s3Client = new AmazonS3Client(RegionEndpoint.USEast1);

            string urlString = GeneratePresignedURL(s3Client, bucketName, objectKey, timeoutDuration);
            Console.WriteLine($"The generated URL is: {urlString}.");
        }

        /// <summary>
        /// Generate a presigned URL that can be used to access the file named
        /// in the objectKey parameter for the amount of time specified in the
        /// duration parameter.
        /// </summary>
        /// <param name="client">An initialized S3 client object used to call
        /// the GetPresignedUrl method.</param>
        /// <param name="bucketName">The name of the S3 bucket containing the
        /// object for which to create the presigned URL.</param>
        /// <param name="objectKey">The name of the object to access with the
        /// presigned URL.</param>
        /// <param name="duration">The length of time for which the presigned
        /// URL will be valid.</param>
        /// <returns>A string representing the generated presigned URL.</returns>
        public static string GeneratePresignedURL(IAmazonS3 client, string bucketName, string objectKey, double duration)
        {
            string urlString = string.Empty;
            try
            {
                var request = new GetPreSignedUrlRequest()
                {
                    BucketName = bucketName,
                    Key = objectKey,
                    Expires = DateTime.UtcNow.AddHours(duration),
                };
                urlString = client.GetPreSignedURL(request);
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error:'{ex.Message}'");
            }

            return urlString;
        }
    }
```
署名済み URL を生成し、その URL を使用してアップロードを実行します。  

```
    using System;
    using System.IO;
    using System.Net.Http;
    using System.Threading.Tasks;
    using Amazon;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to upload an object to an Amazon Simple Storage
    /// Service (Amazon S3) bucket using a presigned URL. The code first
    /// creates a presigned URL and then uses it to upload an object to an
    /// Amazon S3 bucket using that URL.
    /// </summary>
    public class UploadUsingPresignedURL
    {
        private static HttpClient httpClient = new HttpClient();

        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";
            string keyName = "samplefile.txt";
            string filePath = $"source\\{keyName}";

            // Specify how long the signed URL will be valid in hours.
            double timeoutDuration = 12;

            // Specify the AWS Region of your Amazon S3 bucket. If it is
            // different from the Region defined for the default user,
            // pass the Region to the constructor for the client. For
            // example: new AmazonS3Client(RegionEndpoint.USEast1);

            // If using the Region us-east-1, and server-side encryption with AWS KMS, you must specify Signature Version 4.
            // Region us-east-1 defaults to Signature Version 2 unless explicitly set to Version 4 as shown below.
            // For more details, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingAWSSDK.html#specify-signature-version
            // and https://docs.aws.amazon.com/sdkfornet/v3/apidocs/items/Amazon/TAWSConfigsS3.html
            AWSConfigsS3.UseSignatureVersion4 = true;
            IAmazonS3 client = new AmazonS3Client(RegionEndpoint.USEast1);

            var url = GeneratePreSignedURL(client, bucketName, keyName, timeoutDuration);
            var success = await UploadObject(filePath, url);

            if (success)
            {
                Console.WriteLine("Upload succeeded.");
            }
            else
            {
                Console.WriteLine("Upload failed.");
            }
        }

        /// <summary>
        /// Uploads an object to an Amazon S3 bucket using the presigned URL passed in
        /// the url parameter.
        /// </summary>
        /// <param name="filePath">The path (including file name) to the local
        /// file you want to upload.</param>
        /// <param name="url">The presigned URL that will be used to upload the
        /// file to the Amazon S3 bucket.</param>
        /// <returns>A Boolean value indicating the success or failure of the
        /// operation, based on the HttpWebResponse.</returns>
        public static async Task<bool> UploadObject(string filePath, string url)
        {
            using var streamContent = new StreamContent(
                new FileStream(filePath, FileMode.Open, FileAccess.Read));

            var response = await httpClient.PutAsync(url, streamContent);
            return response.IsSuccessStatusCode;
        }

        /// <summary>
        /// Generates a presigned URL which will be used to upload an object to
        /// an Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// GetPreSignedURL.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket to which the
        /// presigned URL will point.</param>
        /// <param name="objectKey">The name of the file that will be uploaded.</param>
        /// <param name="duration">How long (in hours) the presigned URL will
        /// be valid.</param>
        /// <returns>The generated URL.</returns>
        public static string GeneratePreSignedURL(
            IAmazonS3 client,
            string bucketName,
            string objectKey,
            double duration)
        {
            var request = new GetPreSignedUrlRequest
            {
                BucketName = bucketName,
                Key = objectKey,
                Verb = HttpVerb.PUT,
                Expires = DateTime.UtcNow.AddHours(duration),
            };

            string url = client.GetPreSignedURL(request);
            return url;
        }
    }
```

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_csharp_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for .NET**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_csharp_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for .NET**  
 Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内から、Amazon Rekognition を使用してカテゴリ別にオブジェクトを識別するアプリケーションを、Amazon Rekognition .NET API を使用して作成する方法を示します。アプリケーションは、Amazon Simple Email Service (Amazon SES) を使用して、結果を記載した E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAnalyzerApp) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 暗号化の開始方法
<a name="s3_Encryption_csharp_3_topic"></a>

次のコード例は、Amazon S3 オブジェクトの暗号化を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/SSEClientEncryptionExample#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.IO;
    using System.Security.Cryptography;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to apply client encryption to an object in an
    /// Amazon Simple Storage Service (Amazon S3) bucket.
    /// </summary>
    public class SSEClientEncryption
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";
            string keyName = "exampleobject.txt";
            string copyTargetKeyName = "examplecopy.txt";

            // If the AWS Region defined for your default user is different
            // from the Region where your Amazon S3 bucket is located,
            // pass the Region name to the Amazon S3 client object's constructor.
            // For example: RegionEndpoint.USWest2.
            IAmazonS3 client = new AmazonS3Client();

            try
            {
                // Create an encryption key.
                Aes aesEncryption = Aes.Create();
                aesEncryption.KeySize = 256;
                aesEncryption.GenerateKey();
                string base64Key = Convert.ToBase64String(aesEncryption.Key);

                // Upload the object.
                PutObjectRequest putObjectRequest = await UploadObjectAsync(client, bucketName, keyName, base64Key);

                // Download the object and verify that its contents match what you uploaded.
                await DownloadObjectAsync(client, bucketName, keyName, base64Key, putObjectRequest);

                // Get object metadata and verify that the object uses AES-256 encryption.
                await GetObjectMetadataAsync(client, bucketName, keyName, base64Key);

                // Copy both the source and target objects using server-side encryption with
                // an encryption key.
                await CopyObjectAsync(client, bucketName, keyName, copyTargetKeyName, aesEncryption, base64Key);
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }

        /// <summary>
        /// Uploads an object to an Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// PutObjectAsync.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket to which the
        /// object will be uploaded.</param>
        /// <param name="keyName">The name of the object to upload to the Amazon S3
        /// bucket.</param>
        /// <param name="base64Key">The encryption key.</param>
        /// <returns>The PutObjectRequest object for use by DownloadObjectAsync.</returns>
        public static async Task<PutObjectRequest> UploadObjectAsync(
            IAmazonS3 client,
            string bucketName,
            string keyName,
            string base64Key)
        {
            PutObjectRequest putObjectRequest = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = keyName,
                ContentBody = "sample text",
                ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
                ServerSideEncryptionCustomerProvidedKey = base64Key,
            };
            PutObjectResponse putObjectResponse = await client.PutObjectAsync(putObjectRequest);
            return putObjectRequest;
        }

        /// <summary>
        /// Downloads an encrypted object from an Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// GetObjectAsync.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket where the object
        /// is located.</param>
        /// <param name="keyName">The name of the Amazon S3 object to download.</param>
        /// <param name="base64Key">The encryption key used to encrypt the
        /// object.</param>
        /// <param name="putObjectRequest">The PutObjectRequest used to upload
        /// the object.</param>
        public static async Task DownloadObjectAsync(
            IAmazonS3 client,
            string bucketName,
            string keyName,
            string base64Key,
            PutObjectRequest putObjectRequest)
        {
            GetObjectRequest getObjectRequest = new GetObjectRequest
            {
                BucketName = bucketName,
                Key = keyName,

                // Provide encryption information for the object stored in Amazon S3.
                ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
                ServerSideEncryptionCustomerProvidedKey = base64Key,
            };

            using (GetObjectResponse getResponse = await client.GetObjectAsync(getObjectRequest))
            using (StreamReader reader = new StreamReader(getResponse.ResponseStream))
            {
                string content = reader.ReadToEnd();
                if (string.Compare(putObjectRequest.ContentBody, content) == 0)
                {
                    Console.WriteLine("Object content is same as we uploaded");
                }
                else
                {
                    Console.WriteLine("Error...Object content is not same.");
                }

                if (getResponse.ServerSideEncryptionCustomerMethod == ServerSideEncryptionCustomerMethod.AES256)
                {
                    Console.WriteLine("Object encryption method is AES256, same as we set");
                }
                else
                {
                    Console.WriteLine("Error...Object encryption method is not the same as AES256 we set");
                }
            }
        }

        /// <summary>
        /// Retrieves the metadata associated with an Amazon S3 object.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used
        /// to call GetObjectMetadataAsync.</param>
        /// <param name="bucketName">The name of the Amazon S3 bucket containing the
        /// object for which we want to retrieve metadata.</param>
        /// <param name="keyName">The name of the object for which we wish to
        /// retrieve the metadata.</param>
        /// <param name="base64Key">The encryption key associated with the
        /// object.</param>
        public static async Task GetObjectMetadataAsync(
            IAmazonS3 client,
            string bucketName,
            string keyName,
            string base64Key)
        {
            GetObjectMetadataRequest getObjectMetadataRequest = new GetObjectMetadataRequest
            {
                BucketName = bucketName,
                Key = keyName,

                // The object stored in Amazon S3 is encrypted, so provide the necessary encryption information.
                ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
                ServerSideEncryptionCustomerProvidedKey = base64Key,
            };

            GetObjectMetadataResponse getObjectMetadataResponse = await client.GetObjectMetadataAsync(getObjectMetadataRequest);
            Console.WriteLine("The object metadata show encryption method used is: {0}", getObjectMetadataResponse.ServerSideEncryptionCustomerMethod);
        }

        /// <summary>
        /// Copies an encrypted object from one Amazon S3 bucket to another.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// CopyObjectAsync.</param>
        /// <param name="bucketName">The Amazon S3 bucket containing the object
        /// to copy.</param>
        /// <param name="keyName">The name of the object to copy.</param>
        /// <param name="copyTargetKeyName">The Amazon S3 bucket to which the object
        /// will be copied.</param>
        /// <param name="aesEncryption">The encryption type to use.</param>
        /// <param name="base64Key">The encryption key to use.</param>
        public static async Task CopyObjectAsync(
            IAmazonS3 client,
            string bucketName,
            string keyName,
            string copyTargetKeyName,
            Aes aesEncryption,
            string base64Key)
        {
            aesEncryption.GenerateKey();
            string copyBase64Key = Convert.ToBase64String(aesEncryption.Key);

            CopyObjectRequest copyRequest = new CopyObjectRequest
            {
                SourceBucket = bucketName,
                SourceKey = keyName,
                DestinationBucket = bucketName,
                DestinationKey = copyTargetKeyName,

                // Information about the source object's encryption.
                CopySourceServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
                CopySourceServerSideEncryptionCustomerProvidedKey = base64Key,

                // Information about the target object's encryption.
                ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
                ServerSideEncryptionCustomerProvidedKey = copyBase64Key,
            };
            await client.CopyObjectAsync(copyRequest);
        }
    }
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CopyObject)
  + [GetObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObject)
  + [GetObjectMetadata](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectMetadata)

### タグの使用開始
<a name="s3_Scenario_Tagging_csharp_3_topic"></a>

次のコード例は、Amazon S3 オブジェクトのタグの使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/ObjectTagExample#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to work with tags in Amazon Simple Storage
    /// Service (Amazon S3) objects.
    /// </summary>
    public class ObjectTag
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";
            string keyName = "newobject.txt";
            string filePath = @"*** file path ***";

            // Specify your bucket region (an example region is shown).
            RegionEndpoint bucketRegion = RegionEndpoint.USWest2;

            var client = new AmazonS3Client(bucketRegion);
            await PutObjectsWithTagsAsync(client, bucketName, keyName, filePath);
        }

        /// <summary>
        /// This method uploads an object with tags. It then shows the tag
        /// values, changes the tags, and shows the new tags.
        /// </summary>
        /// <param name="client">The Initialized Amazon S3 client object used
        /// to call the methods to create and change an objects tags.</param>
        /// <param name="bucketName">A string representing the name of the
        /// bucket where the object will be stored.</param>
        /// <param name="keyName">A string representing the key name of the
        /// object to be tagged.</param>
        /// <param name="filePath">The directory location and file name of the
        /// object to be uploaded to the Amazon S3 bucket.</param>
        public static async Task PutObjectsWithTagsAsync(IAmazonS3 client, string bucketName, string keyName, string filePath)
        {
            try
            {
                // Create an object with tags.
                var putRequest = new PutObjectRequest
                {
                    BucketName = bucketName,
                    Key = keyName,
                    FilePath = filePath,
                    TagSet = new List<Tag>
                    {
                        new Tag { Key = "Keyx1", Value = "Value1" },
                        new Tag { Key = "Keyx2", Value = "Value2" },
                    },
                };

                PutObjectResponse response = await client.PutObjectAsync(putRequest);

                // Now retrieve the new object's tags.
                GetObjectTaggingRequest getTagsRequest = new GetObjectTaggingRequest()
                {
                    BucketName = bucketName,
                    Key = keyName,
                };

                GetObjectTaggingResponse objectTags = await client.GetObjectTaggingAsync(getTagsRequest);

                // Display the tag values.
                objectTags.Tagging
                    .ForEach(t => Console.WriteLine($"Key: {t.Key}, Value: {t.Value}"));

                Tagging newTagSet = new Tagging()
                {
                    TagSet = new List<Tag>
                    {
                        new Tag { Key = "Key3", Value = "Value3" },
                        new Tag { Key = "Key4", Value = "Value4" },
                    },
                };

                PutObjectTaggingRequest putObjTagsRequest = new PutObjectTaggingRequest()
                {
                    BucketName = bucketName,
                    Key = keyName,
                    Tagging = newTagSet,
                };

                PutObjectTaggingResponse response2 = await client.PutObjectTaggingAsync(putObjTagsRequest);

                // Retrieve the tags again and show the values.
                GetObjectTaggingRequest getTagsRequest2 = new GetObjectTaggingRequest()
                {
                    BucketName = bucketName,
                    Key = keyName,
                };
                GetObjectTaggingResponse objectTags2 = await client.GetObjectTaggingAsync(getTagsRequest2);

                objectTags2.Tagging
                    .ForEach(t => Console.WriteLine($"Key: {t.Key}, Value: {t.Value}"));
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine(
                        $"Error: '{ex.Message}'");
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetObjectTagging](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectTagging)」を参照してください。

### Amazon S3 オブジェクトをロックする
<a name="s3_Scenario_ObjectLock_csharp_3_topic"></a>

次のコード例は、S3 オブジェクトロック機能を操作する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ObjectLockScenario#code-examples)での設定と実行の方法を確認してください。
Amazon S3 オブジェクトロック機能を示すインタラクティブなシナリオを実行します。  

```
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;

namespace S3ObjectLockScenario;

public static class S3ObjectLockWorkflow
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This .NET example performs the following tasks:
        1. Create test Amazon Simple Storage Service (S3) buckets with different lock policies.
        2. Upload sample objects to each bucket.
        3. Set some Legal Hold and Retention Periods on objects and buckets.
        4. Investigate lock policies by viewing settings or attempting to delete or overwrite objects.
        5. Clean up objects and buckets.
   */

    public static S3ActionsWrapper _s3ActionsWrapper = null!;
    public static IConfiguration _configuration = null!;
    private static string _resourcePrefix = null!;
    private static string noLockBucketName = null!;
    private static string lockEnabledBucketName = null!;
    private static string retentionAfterCreationBucketName = null!;
    private static List<string> bucketNames = new List<string>();
    private static List<string> fileNames = new List<string>();

    public static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonS3>()
                    .AddTransient<S3ActionsWrapper>()
            )
            .Build();

        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();

        ConfigurationSetup();

        ServicesSetup(host);

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Welcome to the Amazon Simple Storage Service (S3) Object Locking Feature Scenario.");
            Console.WriteLine(new string('-', 80));
            await Setup(true);

            await DemoActionChoices();

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Cleaning up resources.");
            Console.WriteLine(new string('-', 80));
            await Cleanup(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Amazon S3 Object Locking Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem: {ex.Message}");
            await Cleanup(true);
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _s3ActionsWrapper = host.Services.GetRequiredService<S3ActionsWrapper>();
    }

    /// <summary>
    /// Any setup operations needed.
    /// </summary>
    public static void ConfigurationSetup()
    {
        _resourcePrefix = _configuration["resourcePrefix"] ?? "dotnet-example";

        noLockBucketName = _resourcePrefix + "-no-lock";
        lockEnabledBucketName = _resourcePrefix + "-lock-enabled";
        retentionAfterCreationBucketName = _resourcePrefix + "-retention-after-creation";

        bucketNames.Add(noLockBucketName);
        bucketNames.Add(lockEnabledBucketName);
        bucketNames.Add(retentionAfterCreationBucketName);
    }

    // <summary>
    /// Deploy necessary resources for the scenario.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> Setup(bool interactive)
    {
        Console.WriteLine(
            "\nFor this scenario, we will use the AWS SDK for .NET to create several S3\n" +
            "buckets and files to demonstrate working with S3 locking features.\n");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you are ready to start.");
        if (interactive)
            Console.ReadLine();

        Console.WriteLine("\nS3 buckets can be created either with or without object lock enabled.");
        await _s3ActionsWrapper.CreateBucketWithObjectLock(noLockBucketName, false);
        await _s3ActionsWrapper.CreateBucketWithObjectLock(lockEnabledBucketName, true);
        await _s3ActionsWrapper.CreateBucketWithObjectLock(retentionAfterCreationBucketName, false);

        Console.WriteLine("Press Enter to continue.");
        if (interactive)
            Console.ReadLine();

        Console.WriteLine("\nA bucket can be configured to use object locking with a default retention period.");
        await _s3ActionsWrapper.ModifyBucketDefaultRetention(retentionAfterCreationBucketName, true,
            ObjectLockRetentionMode.Governance, DateTime.UtcNow.AddDays(1));

        Console.WriteLine("Press Enter to continue.");
        if (interactive)
            Console.ReadLine();

        Console.WriteLine("\nObject lock policies can also be added to existing buckets.");
        await _s3ActionsWrapper.EnableObjectLockOnBucket(lockEnabledBucketName);

        Console.WriteLine("Press Enter to continue.");
        if (interactive)
            Console.ReadLine();

        // Upload some files to the buckets.
        Console.WriteLine("\nNow let's add some test files:");
        var fileName = _configuration["exampleFileName"] ?? "exampleFile.txt";
        int fileCount = 2;
        // Create the file if it does not already exist.
        if (!File.Exists(fileName))
        {
            await using StreamWriter sw = File.CreateText(fileName);
            await sw.WriteLineAsync(
                "This is a sample file for uploading to a bucket.");
        }

        foreach (var bucketName in bucketNames)
        {
            for (int i = 0; i < fileCount; i++)
            {
                var numberedFileName = Path.GetFileNameWithoutExtension(fileName) + i + Path.GetExtension(fileName);
                fileNames.Add(numberedFileName);
                await _s3ActionsWrapper.UploadFileAsync(bucketName, numberedFileName, fileName);
            }
        }
        Console.WriteLine("Press Enter to continue.");
        if (interactive)
            Console.ReadLine();

        if (!interactive)
            return true;
        Console.WriteLine("\nNow we can set some object lock policies on individual files:");
        foreach (var bucketName in bucketNames)
        {
            for (int i = 0; i < fileNames.Count; i++)
            {
                // No modifications to the objects in the first bucket.
                if (bucketName != bucketNames[0])
                {
                    var exampleFileName = fileNames[i];
                    switch (i)
                    {
                        case 0:
                            {
                                var question =
                                    $"\nWould you like to add a legal hold to {exampleFileName} in {bucketName}? (y/n)";
                                if (GetYesNoResponse(question))
                                {
                                    // Set a legal hold.
                                    await _s3ActionsWrapper.ModifyObjectLegalHold(bucketName, exampleFileName, ObjectLockLegalHoldStatus.On);

                                }
                                break;
                            }
                        case 1:
                            {
                                var question =
                                    $"\nWould you like to add a 1 day Governance retention period to {exampleFileName} in {bucketName}? (y/n)" +
                                    "\nReminder: Only a user with the s3:BypassGovernanceRetention permission will be able to delete this file or its bucket until the retention period has expired.";
                                if (GetYesNoResponse(question))
                                {
                                    // Set a Governance mode retention period for 1 day.
                                    await _s3ActionsWrapper.ModifyObjectRetentionPeriod(
                                        bucketName, exampleFileName,
                                        ObjectLockRetentionMode.Governance,
                                        DateTime.UtcNow.AddDays(1));
                                }
                                break;
                            }
                    }
                }
            }
        }
        Console.WriteLine(new string('-', 80));
        return true;
    }

    // <summary>
    /// List all of the current buckets and objects.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>The list of buckets and objects.</returns>
    public static async Task<List<S3ObjectVersion>> ListBucketsAndObjects(bool interactive)
    {
        var allObjects = new List<S3ObjectVersion>();
        foreach (var bucketName in bucketNames)
        {
            var objectsInBucket = await _s3ActionsWrapper.ListBucketObjectsAndVersions(bucketName);
            foreach (var objectKey in objectsInBucket.Versions)
            {
                allObjects.Add(objectKey);
            }
        }

        if (interactive)
        {
            Console.WriteLine("\nCurrent buckets and objects:\n");
            int i = 0;
            foreach (var bucketObject in allObjects)
            {
                i++;
                Console.WriteLine(
                    $"{i}: {bucketObject.Key} \n\tBucket: {bucketObject.BucketName}\n\tVersion: {bucketObject.VersionId}");
            }
        }

        return allObjects;
    }

    /// <summary>
    /// Present the user with the demo action choices.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task<bool> DemoActionChoices()
    {
        var choices = new string[]{
            "List all files in buckets.",
            "Attempt to delete a file.",
            "Attempt to delete a file with retention period bypass.",
            "Attempt to overwrite a file.",
            "View the object and bucket retention settings for a file.",
            "View the legal hold settings for a file.",
            "Finish the scenario."};

        var choice = 0;
        // Keep asking the user until they choose to move on.
        while (choice != 6)
        {
            Console.WriteLine(new string('-', 80));
            choice = GetChoiceResponse(
                "\nExplore the S3 locking features by selecting one of the following choices:"
                , choices);
            Console.WriteLine(new string('-', 80));
            switch (choice)
            {
                case 0:
                    {
                        await ListBucketsAndObjects(true);
                        break;
                    }
                case 1:
                    {
                        Console.WriteLine("\nEnter the number of the object to delete:");
                        var allFiles = await ListBucketsAndObjects(true);
                        var fileChoice = GetChoiceResponse(null, allFiles.Select(f => f.Key).ToArray());
                        await _s3ActionsWrapper.DeleteObjectFromBucket(allFiles[fileChoice].BucketName, allFiles[fileChoice].Key, false, allFiles[fileChoice].VersionId);
                        break;
                    }
                case 2:
                    {
                        Console.WriteLine("\nEnter the number of the object to delete:");
                        var allFiles = await ListBucketsAndObjects(true);
                        var fileChoice = GetChoiceResponse(null, allFiles.Select(f => f.Key).ToArray());
                        await _s3ActionsWrapper.DeleteObjectFromBucket(allFiles[fileChoice].BucketName, allFiles[fileChoice].Key, true, allFiles[fileChoice].VersionId);
                        break;
                    }
                case 3:
                    {
                        var allFiles = await ListBucketsAndObjects(true);
                        Console.WriteLine("\nEnter the number of the object to overwrite:");
                        var fileChoice = GetChoiceResponse(null, allFiles.Select(f => f.Key).ToArray());
                        // Create the file if it does not already exist.
                        if (!File.Exists(allFiles[fileChoice].Key))
                        {
                            await using StreamWriter sw = File.CreateText(allFiles[fileChoice].Key);
                            await sw.WriteLineAsync(
                                "This is a sample file for uploading to a bucket.");
                        }
                        await _s3ActionsWrapper.UploadFileAsync(allFiles[fileChoice].BucketName, allFiles[fileChoice].Key, allFiles[fileChoice].Key);
                        break;
                    }
                case 4:
                    {
                        var allFiles = await ListBucketsAndObjects(true);
                        Console.WriteLine("\nEnter the number of the object and bucket to view:");
                        var fileChoice = GetChoiceResponse(null, allFiles.Select(f => f.Key).ToArray());
                        await _s3ActionsWrapper.GetObjectRetention(allFiles[fileChoice].BucketName, allFiles[fileChoice].Key);
                        await _s3ActionsWrapper.GetBucketObjectLockConfiguration(allFiles[fileChoice].BucketName);
                        break;
                    }
                case 5:
                    {
                        var allFiles = await ListBucketsAndObjects(true);
                        Console.WriteLine("\nEnter the number of the object to view:");
                        var fileChoice = GetChoiceResponse(null, allFiles.Select(f => f.Key).ToArray());
                        await _s3ActionsWrapper.GetObjectLegalHold(allFiles[fileChoice].BucketName, allFiles[fileChoice].Key);
                        break;
                    }
            }
        }
        return true;
    }

    // <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> Cleanup(bool interactive)
    {
        Console.WriteLine(new string('-', 80));

        if (!interactive || GetYesNoResponse("Do you want to clean up all files and buckets? (y/n) "))
        {
            // Remove all locks and delete all buckets and objects.
            var allFiles = await ListBucketsAndObjects(false);
            foreach (var fileInfo in allFiles)
            {
                // Check for a legal hold.
                var legalHold = await _s3ActionsWrapper.GetObjectLegalHold(fileInfo.BucketName, fileInfo.Key);
                if (legalHold?.Status?.Value == ObjectLockLegalHoldStatus.On)
                {
                    await _s3ActionsWrapper.ModifyObjectLegalHold(fileInfo.BucketName, fileInfo.Key, ObjectLockLegalHoldStatus.Off);
                }

                // Check for a retention period.
                var retention = await _s3ActionsWrapper.GetObjectRetention(fileInfo.BucketName, fileInfo.Key);
                var hasRetentionPeriod = retention?.Mode == ObjectLockRetentionMode.Governance && retention.RetainUntilDate > DateTime.UtcNow.Date;
                await _s3ActionsWrapper.DeleteObjectFromBucket(fileInfo.BucketName, fileInfo.Key, hasRetentionPeriod, fileInfo.VersionId);
            }

            foreach (var bucketName in bucketNames)
            {
                await _s3ActionsWrapper.DeleteBucketByName(bucketName);
            }

        }
        else
        {
            Console.WriteLine(
                "Ok, we'll leave the resources intact.\n" +
                "Don't forget to delete them when you're done with them or you might incur unexpected charges."
            );
        }

        Console.WriteLine(new string('-', 80));
        return true;
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase);
        return response;
    }

    /// <summary>
    /// Helper method to get a choice response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <param name="choices">The choices to print on the console.</param>
    /// <returns>The index of the selected choice</returns>
    private static int GetChoiceResponse(string? question, string[] choices)
    {
        if (question != null)
        {
            Console.WriteLine(question);

            for (int i = 0; i < choices.Length; i++)
            {
                Console.WriteLine($"\t{i + 1}. {choices[i]}");
            }
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > choices.Length)
        {
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }

        return choiceNumber - 1;
    }
}
```
S3 関数のラッパークラス。  

```
using System.Net;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Configuration;

namespace S3ObjectLockScenario;

/// <summary>
/// Encapsulate the Amazon S3 operations.
/// </summary>
public class S3ActionsWrapper
{
    private readonly IAmazonS3 _amazonS3;

    /// <summary>
    /// Constructor for the S3ActionsWrapper.
    /// </summary>
    /// <param name="amazonS3">The injected S3 client.</param>
    public S3ActionsWrapper(IAmazonS3 amazonS3, IConfiguration configuration)
    {
        _amazonS3 = amazonS3;
    }

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

    /// <summary>
    /// Enable object lock on an existing bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket to modify.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> EnableObjectLockOnBucket(string bucketName)
    {
        try
        {
            // First, enable Versioning on the bucket.
            await _amazonS3.PutBucketVersioningAsync(new PutBucketVersioningRequest()
            {
                BucketName = bucketName,
                VersioningConfig = new S3BucketVersioningConfig()
                {
                    EnableMfaDelete = false,
                    Status = VersionStatus.Enabled
                }
            });

            var request = new PutObjectLockConfigurationRequest()
            {
                BucketName = bucketName,
                ObjectLockConfiguration = new ObjectLockConfiguration()
                {
                    ObjectLockEnabled = new ObjectLockEnabled("Enabled"),
                },
            };

            var response = await _amazonS3.PutObjectLockConfigurationAsync(request);
            Console.WriteLine($"\tAdded an object lock policy to bucket {bucketName}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error modifying object lock: '{ex.Message}'");
            return false;
        }
    }

    /// <summary>
    /// Set or modify a retention period on an object in an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The key of the object.</param>
    /// <param name="retention">The retention mode.</param>
    /// <param name="retainUntilDate">The date retention expires.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyObjectRetentionPeriod(string bucketName,
        string objectKey, ObjectLockRetentionMode retention, DateTime retainUntilDate)
    {
        try
        {
            var request = new PutObjectRetentionRequest()
            {
                BucketName = bucketName,
                Key = objectKey,
                Retention = new ObjectLockRetention()
                {
                    Mode = retention,
                    RetainUntilDate = retainUntilDate
                }
            };

            var response = await _amazonS3.PutObjectRetentionAsync(request);
            Console.WriteLine($"\tSet retention for {objectKey} in {bucketName} until {retainUntilDate:d}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tError modifying retention period: '{ex.Message}'");
            return false;
        }
    }

    /// <summary>
    /// Set or modify a retention period on an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket to modify.</param>
    /// <param name="retention">The retention mode.</param>
    /// <param name="retainUntilDate">The date for retention until.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyBucketDefaultRetention(string bucketName, bool enableObjectLock, ObjectLockRetentionMode retention, DateTime retainUntilDate)
    {
        var enabledString = enableObjectLock ? "Enabled" : "Disabled";
        var timeDifference = retainUntilDate.Subtract(DateTime.Now);
        try
        {
            // First, enable Versioning on the bucket.
            await _amazonS3.PutBucketVersioningAsync(new PutBucketVersioningRequest()
            {
                BucketName = bucketName,
                VersioningConfig = new S3BucketVersioningConfig()
                {
                    EnableMfaDelete = false,
                    Status = VersionStatus.Enabled
                }
            });

            var request = new PutObjectLockConfigurationRequest()
            {
                BucketName = bucketName,
                ObjectLockConfiguration = new ObjectLockConfiguration()
                {
                    ObjectLockEnabled = new ObjectLockEnabled(enabledString),
                    Rule = new ObjectLockRule()
                    {
                        DefaultRetention = new DefaultRetention()
                        {
                            Mode = retention,
                            Days = timeDifference.Days // Can be specified in days or years but not both.
                        }
                    }
                }
            };

            var response = await _amazonS3.PutObjectLockConfigurationAsync(request);
            Console.WriteLine($"\tAdded a default retention to bucket {bucketName}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tError modifying object lock: '{ex.Message}'");
            return false;
        }
    }

    /// <summary>
    /// Get the retention period for an S3 object.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The object key.</param>
    /// <returns>The object retention details.</returns>
    public async Task<ObjectLockRetention> GetObjectRetention(string bucketName,
        string objectKey)
    {
        try
        {
            var request = new GetObjectRetentionRequest()
            {
                BucketName = bucketName,
                Key = objectKey
            };

            var response = await _amazonS3.GetObjectRetentionAsync(request);
            Console.WriteLine($"\tObject retention for {objectKey} in {bucketName}: " +
                              $"\n\t{response.Retention.Mode} until {response.Retention.RetainUntilDate:d}.");
            return response.Retention;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to fetch object lock retention: '{ex.Message}'");
            return new ObjectLockRetention();
        }
    }

    /// <summary>
    /// Set or modify a legal hold on an object in an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The key of the object.</param>
    /// <param name="holdStatus">The On or Off status for the legal hold.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyObjectLegalHold(string bucketName,
        string objectKey, ObjectLockLegalHoldStatus holdStatus)
    {
        try
        {
            var request = new PutObjectLegalHoldRequest()
            {
                BucketName = bucketName,
                Key = objectKey,
                LegalHold = new ObjectLockLegalHold()
                {
                    Status = holdStatus
                }
            };

            var response = await _amazonS3.PutObjectLegalHoldAsync(request);
            Console.WriteLine($"\tModified legal hold for {objectKey} in {bucketName}.");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tError modifying legal hold: '{ex.Message}'");
            return false;
        }
    }

    /// <summary>
    /// Get the legal hold details for an S3 object.
    /// </summary>
    /// <param name="bucketName">The bucket of the object.</param>
    /// <param name="objectKey">The object key.</param>
    /// <returns>The object legal hold details.</returns>
    public async Task<ObjectLockLegalHold> GetObjectLegalHold(string bucketName,
        string objectKey)
    {
        try
        {
            var request = new GetObjectLegalHoldRequest()
            {
                BucketName = bucketName,
                Key = objectKey
            };

            var response = await _amazonS3.GetObjectLegalHoldAsync(request);
            Console.WriteLine($"\tObject legal hold for {objectKey} in {bucketName}: " +
                              $"\n\tStatus: {response.LegalHold.Status}");
            return response.LegalHold;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to fetch legal hold: '{ex.Message}'");
            return new ObjectLockLegalHold();
        }
    }

    /// <summary>
    /// Get the object lock configuration details for an S3 bucket.
    /// </summary>
    /// <param name="bucketName">The bucket to get details.</param>
    /// <returns>The bucket's object lock configuration details.</returns>
    public async Task<ObjectLockConfiguration> GetBucketObjectLockConfiguration(string bucketName)
    {
        try
        {
            var request = new GetObjectLockConfigurationRequest()
            {
                BucketName = bucketName
            };

            var response = await _amazonS3.GetObjectLockConfigurationAsync(request);
            Console.WriteLine($"\tBucket object lock config for {bucketName} in {bucketName}: " +
                              $"\n\tEnabled: {response.ObjectLockConfiguration.ObjectLockEnabled}" +
                              $"\n\tRule: {response.ObjectLockConfiguration.Rule?.DefaultRetention}");

            return response.ObjectLockConfiguration;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to fetch object lock config: '{ex.Message}'");
            return new ObjectLockConfiguration();
        }
    }

    /// <summary>
    /// Upload a file from the local computer to an Amazon S3 bucket.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to use.</param>
    /// <param name="objectName">The object to upload.</param>
    /// <param name="filePath">The path, including file name, of the object to upload.</param>
    /// <returns>True if success.<returns>
    public async Task<bool> UploadFileAsync(string bucketName, string objectName, string filePath)
    {
        var request = new PutObjectRequest
        {
            BucketName = bucketName,
            Key = objectName,
            FilePath = filePath,
            ChecksumAlgorithm = ChecksumAlgorithm.SHA256
        };

        var response = await _amazonS3.PutObjectAsync(request);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"\tSuccessfully uploaded {objectName} to {bucketName}.");
            return true;
        }
        else
        {
            Console.WriteLine($"\tCould not upload {objectName} to {bucketName}.");
            return false;
        }
    }

    /// <summary>
    /// List bucket objects and versions.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to use.</param>
    /// <returns>The list of objects and versions.</returns>
    public async Task<ListVersionsResponse> ListBucketObjectsAndVersions(string bucketName)
    {
        var request = new ListVersionsRequest()
        {
            BucketName = bucketName
        };

        var response = await _amazonS3.ListVersionsAsync(request);
        return response;
    }

    /// <summary>
    /// Delete an object from a specific bucket.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to use.</param>
    /// <param name="objectKey">The key of the object to delete.</param>
    /// <param name="hasRetention">True if the object has retention settings.</param>
    /// <param name="versionId">Optional versionId.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteObjectFromBucket(string bucketName, string objectKey, bool hasRetention, string? versionId = null)
    {
        try
        {
            var request = new DeleteObjectRequest()
            {
                BucketName = bucketName,
                Key = objectKey,
                VersionId = versionId,
            };
            if (hasRetention)
            {
                // Set the BypassGovernanceRetention header
                // if the file has retention settings.
                request.BypassGovernanceRetention = true;
            }
            await _amazonS3.DeleteObjectAsync(request);
            Console.WriteLine(
                $"Deleted {objectKey} in {bucketName}.");
            return true;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to delete object {objectKey} in bucket {bucketName}: " + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// Delete a specific bucket.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to use.</param>
    /// <param name="objectKey">The key of the object to delete.</param>
    /// <param name="versionId">Optional versionId.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteBucketByName(string bucketName)
    {
        try
        {
            var request = new DeleteBucketRequest() { BucketName = bucketName, };
            var response = await _amazonS3.DeleteBucketAsync(request);
            Console.WriteLine($"\tDelete for {bucketName} complete.");
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to delete bucket {bucketName}: " + ex.Message);
            return false;
        }

    }

}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [GetObjectLegalHold](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectLegalHold)
  + [GetObjectLockConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectLockConfiguration)
  + [GetObjectRetention](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectRetention)
  + [PutObjectLegalHold](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObjectLegalHold)
  + [PutObjectLockConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObjectLockConfiguration)
  + [PutObjectRetention](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObjectRetention)

### 条件付きリクエストの実行
<a name="s3_Scenario_ConditionalRequests_csharp_3_topic"></a>

次のコード例は、Amazon S3 リクエストに前提条件を追加する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/scenarios/S3ConditionalRequestsScenario#code-examples)での設定と実行の方法を確認してください。
Amazon S3 の条件付きリクエスト機能を示すインタラクティブなシナリオを実行します。  

```
using Amazon.S3;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;

namespace S3ConditionalRequestsScenario;

public static class S3ConditionalRequestsScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This example demonstrates the use of conditional requests for S3 operations.
    You can use conditional requests to add preconditions to S3 read requests to return or copy
    an object based on its Entity tag (ETag), or last modified date. 
    You can use a conditional write requests to prevent overwrites by ensuring 
    there is no existing object with the same key. 
   */

    public static S3ActionsWrapper _s3ActionsWrapper = null!;
    public static IConfiguration _configuration = null!;
    public static string _resourcePrefix = null!;
    public static string _sourceBucketName = null!;
    public static string _destinationBucketName = null!;
    public static string _sampleObjectKey = null!;
    public static string _sampleObjectEtag = null!;
    public static bool _interactive = true;


    public static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonS3>()
                    .AddTransient<S3ActionsWrapper>()
            )
            .Build();

        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();

        ServicesSetup(host);

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Welcome to the Amazon Simple Storage Service (S3) Conditional Requests Feature Scenario.");
            Console.WriteLine(new string('-', 80));
            ConfigurationSetup();
            _sampleObjectEtag = await Setup(_sourceBucketName, _destinationBucketName, _sampleObjectKey);

            await DisplayDemoChoices(_sourceBucketName, _destinationBucketName, _sampleObjectKey, _sampleObjectEtag, 0);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Cleaning up resources.");
            Console.WriteLine(new string('-', 80));
            await Cleanup(true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Amazon S3 Conditional Requests Feature Scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem: {ex.Message}");
            await CleanupScenario(_sourceBucketName, _destinationBucketName);
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _s3ActionsWrapper = host.Services.GetRequiredService<S3ActionsWrapper>();
    }

    /// <summary>
    /// Any setup operations needed.
    /// </summary>
    public static void ConfigurationSetup()
    {
        _resourcePrefix = _configuration["resourcePrefix"] ?? "dotnet-example";

        _sourceBucketName = _resourcePrefix + "-source";
        _destinationBucketName = _resourcePrefix + "-dest";
        _sampleObjectKey = _resourcePrefix + "-sample-object.txt";
    }

    /// <summary>
    /// Sets up the scenario by creating a source and destination bucket, and uploading a test file to the source bucket.
    /// </summary>
    /// <param name="sourceBucket">The name of the source bucket.</param>
    /// <param name="destBucket">The name of the destination bucket.</param>
    /// <param name="objectKey">The name of the test file to add to the source bucket.</param>
    /// <returns>The ETag of the uploaded test file.</returns>
    public static async Task<string> Setup(string sourceBucket, string destBucket, string objectKey)
    {
        Console.WriteLine(
            "\nFor this scenario, we will use the AWS SDK for .NET to create several S3\n" +
            "buckets and files to demonstrate working with S3 conditional requests.\n" +
            "This example demonstrates the use of conditional requests for S3 operations.\r\n" +
            "You can use conditional requests to add preconditions to S3 read requests to return or copy\r\n" +
            "an object based on its Entity tag (ETag), or last modified date. \r\n" +
            "You can use a conditional write requests to prevent overwrites by ensuring \r\n" +
            "there is no existing object with the same key. \r\n\r\n" +
            "This example will allow you to perform conditional reads\r\n" +
            "and writes that will succeed or fail based on your selected options.\r\n\r\n" +
            "Sample buckets and a sample object will be created as part of the example.");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Press Enter when you are ready to start.");
        if (_interactive)
            Console.ReadLine();

        await _s3ActionsWrapper.CreateBucketWithName(sourceBucket);
        await _s3ActionsWrapper.CreateBucketWithName(destBucket);

        var eTag = await _s3ActionsWrapper.PutObjectConditional(objectKey, sourceBucket,
            "Test file content.");

        return eTag;
    }

    /// <summary>
    /// Cleans up the scenario by deleting the source and destination buckets.
    /// </summary>
    /// <param name="sourceBucket">The name of the source bucket.</param>
    /// <param name="destBucket">The name of the destination bucket.</param>
    public static async Task CleanupScenario(string sourceBucket, string destBucket)
    {
        await _s3ActionsWrapper.CleanupBucketByName(sourceBucket);
        await _s3ActionsWrapper.CleanupBucketByName(destBucket);
    }

    /// <summary>
    /// Displays a list of the objects in the test buckets.
    /// </summary>
    /// <param name="sourceBucket">The name of the source bucket.</param>
    /// <param name="destBucket">The name of the destination bucket.</param>
    public static async Task DisplayBuckets(string sourceBucket, string destBucket)
    {
        await _s3ActionsWrapper.ListBucketContentsByName(sourceBucket);
        await _s3ActionsWrapper.ListBucketContentsByName(destBucket);
    }

    /// <summary>
    /// Displays the menu of conditional request options for the user.
    /// </summary>
    /// <param name="sourceBucket">The name of the source bucket.</param>
    /// <param name="destBucket">The name of the destination bucket.</param>
    /// <param name="objectKey">The key of the test object in the source bucket.</param>
    /// <param name="etag">The ETag of the test object in the source bucket.</param>
    public static async Task DisplayDemoChoices(string sourceBucket, string destBucket, string objectKey, string etag, int defaultChoice)
    {
        var actions = new[]
        {
            "Print a list of bucket items.",
            "Perform a conditional read.",
            "Perform a conditional copy.",
            "Perform a conditional write.",
            "Clean up and exit."
        };

        var conditions = new[]
        {
            "If-Match: using the object's ETag. This condition should succeed.",
            "If-None-Match: using the object's ETag. This condition should fail.",
            "If-Modified-Since: using yesterday's date. This condition should succeed.",
            "If-Unmodified-Since: using yesterday's date. This condition should fail."
        };

        var conditionTypes = new[]
        {
            S3ConditionType.IfMatch,
            S3ConditionType.IfNoneMatch,
            S3ConditionType.IfModifiedSince,
            S3ConditionType.IfUnmodifiedSince,
        };

        var yesterdayDate = DateTime.UtcNow.AddDays(-1);

        int choice;
        while ((choice = GetChoiceResponse("\nExplore the S3 conditional request  features by selecting one of the following choices:", actions, defaultChoice)) != 4)
        {
            switch (choice)
            {
                case 0:
                    Console.WriteLine("Listing the objects and buckets.");
                    await DisplayBuckets(sourceBucket, destBucket);
                    break;
                case 1:
                    int conditionTypeIndex = GetChoiceResponse("Perform a conditional read:", conditions, 1);
                    if (conditionTypeIndex == 0 || conditionTypeIndex == 1)
                    {
                        await _s3ActionsWrapper.GetObjectConditional(objectKey, sourceBucket, conditionTypes[conditionTypeIndex], null, _sampleObjectEtag);
                    }
                    else if (conditionTypeIndex == 2 || conditionTypeIndex == 3)
                    {
                        await _s3ActionsWrapper.GetObjectConditional(objectKey, sourceBucket, conditionTypes[conditionTypeIndex], yesterdayDate);
                    }
                    break;
                case 2:
                    int copyConditionTypeIndex = GetChoiceResponse("Perform a conditional copy:", conditions, 1);
                    string destKey = GetStringResponse("Enter an object key:", "sampleObjectKey");
                    if (copyConditionTypeIndex == 0 || copyConditionTypeIndex == 1)
                    {
                        await _s3ActionsWrapper.CopyObjectConditional(objectKey, destKey, sourceBucket, destBucket, conditionTypes[copyConditionTypeIndex], null, etag);
                    }
                    else if (copyConditionTypeIndex == 2 || copyConditionTypeIndex == 3)
                    {
                        await _s3ActionsWrapper.CopyObjectConditional(objectKey, destKey, sourceBucket, destBucket, conditionTypes[copyConditionTypeIndex], yesterdayDate);
                    }
                    break;
                case 3:
                    Console.WriteLine("Perform a conditional write using IfNoneMatch condition on the object key.");
                    Console.WriteLine("If the key is a duplicate, the write will fail.");
                    string newObjectKey = GetStringResponse("Enter an object key:", "newObjectKey");
                    await _s3ActionsWrapper.PutObjectConditional(newObjectKey, sourceBucket, "Conditional write example data.");
                    break;
            }

            if (!_interactive)
            {
                break;
            }
        }

        Console.WriteLine("Proceeding to cleanup.");
    }

    // <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="interactive">True to run as interactive.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> Cleanup(bool interactive)
    {
        Console.WriteLine(new string('-', 80));

        if (!interactive || GetYesNoResponse("Do you want to clean up all files and buckets? (y/n) "))
        {
            await _s3ActionsWrapper.CleanUpBucketByName(_sourceBucketName);
            await _s3ActionsWrapper.CleanUpBucketByName(_destinationBucketName);

        }
        else
        {
            Console.WriteLine(
                "Ok, we'll leave the resources intact.\n" +
                "Don't forget to delete them when you're done with them or you might incur unexpected charges."
            );
        }

        Console.WriteLine(new string('-', 80));
        return true;
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase);
        return response;
    }

    /// <summary>
    /// Helper method to get a choice response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <param name="choices">The choices to print on the console.</param>
    /// <returns>The index of the selected choice</returns>
    private static int GetChoiceResponse(string? question, string[] choices, int defaultChoice)
    {
        if (question != null)
        {
            Console.WriteLine(question);

            for (int i = 0; i < choices.Length; i++)
            {
                Console.WriteLine($"\t{i + 1}. {choices[i]}");
            }
        }

        if (!_interactive)
            return defaultChoice;

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > choices.Length)
        {
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }

        return choiceNumber - 1;
    }

    /// <summary>
    /// Get a string response from the user.
    /// </summary>
    /// <param name="question">The question to print.</param>
    /// <param name="defaultAnswer">A default answer to use when not interactive.</param>
    /// <returns>The string response.</returns>
    public static string GetStringResponse(string? question, string defaultAnswer)
    {
        string? answer = "";
        if (_interactive)
        {
            do
            {
                Console.WriteLine(question);
                answer = Console.ReadLine();
            } while (string.IsNullOrWhiteSpace(answer));
        }
        else
        {
            answer = defaultAnswer;
        }

        return answer;
    }
}
```
S3 関数のラッパークラス。  

```
using System.Net;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Logging;

namespace S3ConditionalRequestsScenario;

/// <summary>
/// Encapsulate the Amazon S3 operations.
/// </summary>
public class S3ActionsWrapper
{
    private readonly IAmazonS3 _amazonS3;
    private readonly ILogger<S3ActionsWrapper> _logger;

    /// <summary>
    /// Constructor for the S3ActionsWrapper.
    /// </summary>
    /// <param name="amazonS3">The injected S3 client.</param>
    /// <param name="logger">The class logger.</param>
    public S3ActionsWrapper(IAmazonS3 amazonS3, ILogger<S3ActionsWrapper> logger)
    {
        _amazonS3 = amazonS3;
        _logger = logger;
    }

    /// <summary>
    /// Retrieves an object from Amazon S3 with a conditional request.
    /// </summary>
    /// <param name="objectKey">The key of the object to retrieve.</param>
    /// <param name="sourceBucket">The source bucket of the object.</param>
    /// <param name="conditionType">The type of condition: 'IfMatch', 'IfNoneMatch', 'IfModifiedSince', 'IfUnmodifiedSince'.</param>
    /// <param name="conditionDateValue">The value to use for the condition for dates.</param>
    /// <param name="etagConditionalValue">The value to use for the condition for etags.</param>
    /// <returns>True if the conditional read is successful, False otherwise.</returns>
    public async Task<bool> GetObjectConditional(string objectKey, string sourceBucket,
        S3ConditionType conditionType, DateTime? conditionDateValue = null, string? etagConditionalValue = null)
    {
        try
        {
            var getObjectRequest = new GetObjectRequest
            {
                BucketName = sourceBucket,
                Key = objectKey
            };

            switch (conditionType)
            {
                case S3ConditionType.IfMatch:
                    getObjectRequest.EtagToMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfNoneMatch:
                    getObjectRequest.EtagToNotMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfModifiedSince:
                    getObjectRequest.ModifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                case S3ConditionType.IfUnmodifiedSince:
                    getObjectRequest.UnmodifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(conditionType), conditionType, null);
            }

            var response = await _amazonS3.GetObjectAsync(getObjectRequest);
            var sampleBytes = new byte[20];
            await response.ResponseStream.ReadAsync(sampleBytes, 0, 20);
            _logger.LogInformation($"Conditional read successful. Here are the first 20 bytes of the object:\n{System.Text.Encoding.UTF8.GetString(sampleBytes)}");
            return true;
        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "PreconditionFailed")
            {
                _logger.LogError("Conditional read failed: Precondition failed");
            }
            else if (e.ErrorCode == "NotModified")
            {
                _logger.LogError("Conditional read failed: Object not modified");
            }
            else
            {
                _logger.LogError($"Unexpected error: {e.ErrorCode}");
                throw;
            }
            return false;
        }
    }

    /// <summary>
    /// Uploads an object to Amazon S3 with a conditional request. Prevents overwrite using an IfNoneMatch condition for the object key.
    /// </summary>
    /// <param name="objectKey">The key of the object to upload.</param>
    /// <param name="bucket">The source bucket of the object.</param>
    /// <param name="content">The content to upload as a string.</param>
    /// <returns>The ETag if the conditional write is successful, empty otherwise.</returns>
    public async Task<string> PutObjectConditional(string objectKey, string bucket, string content)
    {
        try
        {
            var putObjectRequest = new PutObjectRequest
            {
                BucketName = bucket,
                Key = objectKey,
                ContentBody = content,
                IfNoneMatch = "*"
            };

            var putResult = await _amazonS3.PutObjectAsync(putObjectRequest);
            _logger.LogInformation($"Conditional write successful for key {objectKey} in bucket {bucket}.");
            return putResult.ETag;
        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "PreconditionFailed")
            {
                _logger.LogError("Conditional write failed: Precondition failed");
            }
            else
            {
                _logger.LogError($"Unexpected error: {e.ErrorCode}");
                throw;
            }
            return string.Empty;
        }
    }

    /// <summary>
    /// Copies an object from one Amazon S3 bucket to another with a conditional request.
    /// </summary>
    /// <param name="sourceKey">The key of the source object to copy.</param>
    /// <param name="destKey">The key of the destination object.</param>
    /// <param name="sourceBucket">The source bucket of the object.</param>
    /// <param name="destBucket">The destination bucket of the object.</param>
    /// <param name="conditionType">The type of condition to apply, e.g. 'CopySourceIfMatch', 'CopySourceIfNoneMatch', 'CopySourceIfModifiedSince', 'CopySourceIfUnmodifiedSince'.</param>
    /// <param name="conditionDateValue">The value to use for the condition for dates.</param>
    /// <param name="etagConditionalValue">The value to use for the condition for etags.</param>
    /// <returns>True if the conditional copy is successful, False otherwise.</returns>
    public async Task<bool> CopyObjectConditional(string sourceKey, string destKey, string sourceBucket, string destBucket,
        S3ConditionType conditionType, DateTime? conditionDateValue = null, string? etagConditionalValue = null)
    {
        try
        {
            var copyObjectRequest = new CopyObjectRequest
            {
                DestinationBucket = destBucket,
                DestinationKey = destKey,
                SourceBucket = sourceBucket,
                SourceKey = sourceKey
            };

            switch (conditionType)
            {
                case S3ConditionType.IfMatch:
                    copyObjectRequest.ETagToMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfNoneMatch:
                    copyObjectRequest.ETagToNotMatch = etagConditionalValue;
                    break;
                case S3ConditionType.IfModifiedSince:
                    copyObjectRequest.ModifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                case S3ConditionType.IfUnmodifiedSince:
                    copyObjectRequest.UnmodifiedSinceDateUtc = conditionDateValue.GetValueOrDefault();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(conditionType), conditionType, null);
            }

            await _amazonS3.CopyObjectAsync(copyObjectRequest);
            _logger.LogInformation($"Conditional copy successful for key {destKey} in bucket {destBucket}.");
            return true;
        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "PreconditionFailed")
            {
                _logger.LogError("Conditional copy failed: Precondition failed");
            }
            else if (e.ErrorCode == "304")
            {
                _logger.LogError("Conditional copy failed: Object not modified");
            }
            else
            {
                _logger.LogError($"Unexpected error: {e.ErrorCode}");
                throw;
            }
            return false;
        }
    }

    /// <summary>
    /// Create a new Amazon S3 bucket with a specified name and check that the bucket is ready.
    /// </summary>
    /// <param name="bucketName">The name of the bucket to create.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> CreateBucketWithName(string bucketName)
    {
        Console.WriteLine($"\tCreating bucket {bucketName}.");
        try
        {
            var request = new PutBucketRequest
            {
                BucketName = bucketName,
                UseClientRegion = true
            };

            await _amazonS3.PutBucketAsync(request);
            var bucketReady = false;
            var retries = 5;
            while (!bucketReady && retries > 0)
            {
                Thread.Sleep(5000);
                bucketReady = await Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async(_amazonS3, bucketName);
                retries--;
            }

            return bucketReady;
        }
        catch (BucketAlreadyExistsException ex)
        {
            Console.WriteLine($"Bucket already exists: '{ex.Message}'");
            return true;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error creating bucket: '{ex.Message}'");
            return false;
        }
    }

    /// <summary>
    /// Cleans up objects and deletes the bucket by name.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <returns>Async task.</returns>
    public async Task CleanupBucketByName(string bucketName)
    {
        try
        {
            var listObjectsResponse = await _amazonS3.ListObjectsV2Async(new ListObjectsV2Request { BucketName = bucketName });
            foreach (var obj in listObjectsResponse.S3Objects)
            {
                await _amazonS3.DeleteObjectAsync(new DeleteObjectRequest { BucketName = bucketName, Key = obj.Key });
            }
            await _amazonS3.DeleteBucketAsync(new DeleteBucketRequest { BucketName = bucketName });
            Console.WriteLine($"Cleaned up bucket: {bucketName}.");
        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "NoSuchBucket")
            {
                Console.WriteLine($"Bucket {bucketName} does not exist, skipping cleanup.");
            }
            else
            {
                Console.WriteLine($"Error deleting bucket: {e.ErrorCode}");
                throw;
            }
        }
    }

    /// <summary>
    /// List the contents of the bucket with their ETag.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <returns>Async task.</returns>
    public async Task<List<S3Object>> ListBucketContentsByName(string bucketName)
    {
        var results = new List<S3Object>();
        try
        {
            Console.WriteLine($"\t Items in bucket {bucketName}");
            var listObjectsResponse = await _amazonS3.ListObjectsV2Async(new ListObjectsV2Request { BucketName = bucketName });
            if (listObjectsResponse.S3Objects.Count == 0)
            {
                Console.WriteLine("\t\tNo objects found.");
            }
            else
            {
                foreach (var obj in listObjectsResponse.S3Objects)
                {
                    Console.WriteLine($"\t\t object: {obj.Key} ETag {obj.ETag}");
                }
            }
            results = listObjectsResponse.S3Objects;

        }
        catch (AmazonS3Exception e)
        {
            if (e.ErrorCode == "NoSuchBucket")
            {
                _logger.LogError($"Bucket {bucketName} does not exist.");
            }
            else
            {
                _logger.LogError($"Error listing bucket and objects: {e.ErrorCode}");
                throw;
            }
        }

        return results;
    }

    /// <summary>
    /// Delete an object from a specific bucket.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to use.</param>
    /// <param name="objectKey">The key of the object to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteObjectFromBucket(string bucketName, string objectKey)
    {
        try
        {
            var request = new DeleteObjectRequest()
            {
                BucketName = bucketName,
                Key = objectKey
            };
            await _amazonS3.DeleteObjectAsync(request);
            Console.WriteLine($"Deleted {objectKey} in {bucketName}.");
            return true;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to delete object {objectKey} in bucket {bucketName}: " + ex.Message);
            return false;
        }
    }

    /// <summary>
    /// Delete a specific bucket by deleting the objects and then the bucket itself.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to use.</param>
    /// <param name="objectKey">The key of the object to delete.</param>
    /// <param name="versionId">Optional versionId.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> CleanUpBucketByName(string bucketName)
    {
        try
        {
            var allFiles = await ListBucketContentsByName(bucketName);

            foreach (var fileInfo in allFiles)
            {
                await DeleteObjectFromBucket(fileInfo.BucketName, fileInfo.Key);
            }

            var request = new DeleteBucketRequest() { BucketName = bucketName, };
            var response = await _amazonS3.DeleteBucketAsync(request);
            Console.WriteLine($"\tDelete for {bucketName} complete.");
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"\tUnable to delete bucket {bucketName}: " + ex.Message);
            return false;
        }

    }

}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CopyObject)
  + [GetObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObject)
  + [PutObject](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObject)

### アクセスコントロールリスト (ACL) の管理
<a name="s3_Scenario_ManageACLs_csharp_3_topic"></a>

次のコード例は、Amazon S3 バケットのアクセスコントロールリスト (ACL) を管理する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/ManageACLsExample#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to manage Amazon Simple Storage Service
    /// (Amazon S3) access control lists (ACLs) to control Amazon S3 bucket
    /// access.
    /// </summary>
    public class ManageACLs
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket1";
            string newBucketName = "amzn-s3-demo-bucket2";
            string keyName = "sample-object.txt";
            string emailAddress = "someone@example.com";

            // If the AWS Region where your bucket is located is different from
            // the Region defined for the default user, pass the Amazon S3 bucket's
            // name to the client constructor. It should look like this:
            // RegionEndpoint bucketRegion = RegionEndpoint.USEast1;
            IAmazonS3 client = new AmazonS3Client();

            await TestBucketObjectACLsAsync(client, bucketName, newBucketName, keyName, emailAddress);
        }

        /// <summary>
        /// Creates a new Amazon S3 bucket with a canned ACL, then retrieves the ACL
        /// information and then adds a new ACL to one of the objects in the
        /// Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to call
        /// methods to create a bucket, get an ACL, and add a different ACL to
        /// one of the objects.</param>
        /// <param name="bucketName">A string representing the original Amazon S3
        /// bucket name.</param>
        /// <param name="newBucketName">A string representing the name of the
        /// new bucket that will be created.</param>
        /// <param name="keyName">A string representing the key name of an Amazon S3
        /// object for which we will change the ACL.</param>
        /// <param name="emailAddress">A string representing the email address
        /// belonging to the person to whom access to the Amazon S3 bucket will be
        /// granted.</param>
        public static async Task TestBucketObjectACLsAsync(
            IAmazonS3 client,
            string bucketName,
            string newBucketName,
            string keyName,
            string emailAddress)
        {
            try
            {
                // Create a new Amazon S3 bucket and specify canned ACL.
                var success = await CreateBucketWithCannedACLAsync(client, newBucketName);

                // Get the ACL on a bucket.
                await GetBucketACLAsync(client, bucketName);

                // Add (replace) the ACL on an object in a bucket.
                await AddACLToExistingObjectAsync(client, bucketName, keyName, emailAddress);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                Console.WriteLine($"Exception: {amazonS3Exception.Message}");
            }
        }

        /// <summary>
        /// Creates a new Amazon S3 bucket with a canned ACL attached.
        /// </summary>
        /// <param name="client">The initialized client object used to call
        /// PutBucketAsync.</param>
        /// <param name="newBucketName">A string representing the name of the
        /// new Amazon S3 bucket.</param>
        /// <returns>Returns a boolean value indicating success or failure.</returns>
        public static async Task<bool> CreateBucketWithCannedACLAsync(IAmazonS3 client, string newBucketName)
        {
            var request = new PutBucketRequest()
            {
                BucketName = newBucketName,
                BucketRegion = S3Region.EUWest1,

                // Add a canned ACL.
                CannedACL = S3CannedACL.LogDeliveryWrite,
            };

            var response = await client.PutBucketAsync(request);
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }


        /// <summary>
        /// Retrieves the ACL associated with the Amazon S3 bucket name in the
        /// bucketName parameter.
        /// </summary>
        /// <param name="client">The initialized client object used to call
        /// PutBucketAsync.</param>
        /// <param name="bucketName">The Amazon S3 bucket for which we want to get the
        /// ACL list.</param>
        /// <returns>Returns an S3AccessControlList returned from the call to
        /// GetACLAsync.</returns>
        public static async Task<S3AccessControlList> GetBucketACLAsync(IAmazonS3 client, string bucketName)
        {
            GetACLResponse response = await client.GetACLAsync(new GetACLRequest
            {
                BucketName = bucketName,
            });

            return response.AccessControlList;
        }



        /// <summary>
        /// Adds a new ACL to an existing object in the Amazon S3 bucket.
        /// </summary>
        /// <param name="client">The initialized client object used to call
        /// PutBucketAsync.</param>
        /// <param name="bucketName">A string representing the name of the Amazon S3
        /// bucket containing the object to which we want to apply a new ACL.</param>
        /// <param name="keyName">A string representing the name of the object
        /// to which we want to apply the new ACL.</param>
        /// <param name="emailAddress">The email address of the person to whom
        /// we will be applying to whom access will be granted.</param>
        public static async Task AddACLToExistingObjectAsync(IAmazonS3 client, string bucketName, string keyName, string emailAddress)
        {
            // Retrieve the ACL for an object.
            GetACLResponse aclResponse = await client.GetACLAsync(new GetACLRequest
            {
                BucketName = bucketName,
                Key = keyName,
            });

            S3AccessControlList acl = aclResponse.AccessControlList;

            // Retrieve the owner.
            Owner owner = acl.Owner;

            // Clear existing grants.
            acl.Grants.Clear();

            // Add a grant to reset the owner's full permission
            // (the previous clear statement removed all permissions).
            var fullControlGrant = new S3Grant
            {
                Grantee = new S3Grantee { CanonicalUser = acl.Owner.Id },
            };
            acl.AddGrant(fullControlGrant.Grantee, S3Permission.FULL_CONTROL);

            // Specify email to identify grantee for granting permissions.
            var grantUsingEmail = new S3Grant
            {
                Grantee = new S3Grantee { EmailAddress = emailAddress },
                Permission = S3Permission.WRITE_ACP,
            };

            // Specify log delivery group as grantee.
            var grantLogDeliveryGroup = new S3Grant
            {
                Grantee = new S3Grantee { URI = "http://acs.amazonaws.com/groups/s3/LogDelivery" },
                Permission = S3Permission.WRITE,
            };

            // Create a new ACL.
            var newAcl = new S3AccessControlList
            {
                Grants = new List<S3Grant> { grantUsingEmail, grantLogDeliveryGroup },
                Owner = owner,
            };

            // Set the new ACL. We're throwing away the response here.
            _ = await client.PutACLAsync(new PutACLRequest
            {
                BucketName = bucketName,
                Key = keyName,
                AccessControlList = newAcl,
            });
        }

    }
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [GetBucketAcl](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetBucketAcl)
  + [GetObjectAcl](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectAcl)
  + [PutBucketAcl](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutBucketAcl)
  + [PutObjectAcl](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/PutObjectAcl)

### マルチパートコピーを実行する
<a name="s3_MultipartCopy_csharp_3_topic"></a>

次のコード例は、Amazon S3 オブジェクトのマルチパートコピーを実行する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/MPUapiCopyObjExample#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// This example shows how to perform a multi-part copy from one Amazon
    /// Simple Storage Service (Amazon S3) bucket to another.
    /// </summary>
    public class MPUapiCopyObj
    {
        private const string SourceBucket = "amzn-s3-demo-bucket1";
        private const string TargetBucket = "amzn-s3-demo-bucket2";
        private const string SourceObjectKey = "example.mov";
        private const string TargetObjectKey = "copied_video_file.mov";

        /// <summary>
        /// This method starts the multi-part upload.
        /// </summary>
        public static async Task Main()
        {
            var s3Client = new AmazonS3Client();
            Console.WriteLine("Copying object...");
            await MPUCopyObjectAsync(s3Client);
        }

        /// <summary>
        /// This method uses the passed client object to perform a multipart
        /// copy operation.
        /// </summary>
        /// <param name="client">An Amazon S3 client object that will be used
        /// to perform the copy.</param>
        public static async Task MPUCopyObjectAsync(AmazonS3Client client)
        {
            // Create a list to store the copy part responses.
            var copyResponses = new List<CopyPartResponse>();

            // Setup information required to initiate the multipart upload.
            var initiateRequest = new InitiateMultipartUploadRequest
            {
                BucketName = TargetBucket,
                Key = TargetObjectKey,
            };

            // Initiate the upload.
            InitiateMultipartUploadResponse initResponse =
                await client.InitiateMultipartUploadAsync(initiateRequest);

            // Save the upload ID.
            string uploadId = initResponse.UploadId;

            try
            {
                // Get the size of the object.
                var metadataRequest = new GetObjectMetadataRequest
                {
                    BucketName = SourceBucket,
                    Key = SourceObjectKey,
                };

                GetObjectMetadataResponse metadataResponse =
                    await client.GetObjectMetadataAsync(metadataRequest);
                var objectSize = metadataResponse.ContentLength; // Length in bytes.

                // Copy the parts.
                var partSize = 5 * (long)Math.Pow(2, 20); // Part size is 5 MB.

                long bytePosition = 0;
                for (int i = 1; bytePosition < objectSize; i++)
                {
                    var copyRequest = new CopyPartRequest
                    {
                        DestinationBucket = TargetBucket,
                        DestinationKey = TargetObjectKey,
                        SourceBucket = SourceBucket,
                        SourceKey = SourceObjectKey,
                        UploadId = uploadId,
                        FirstByte = bytePosition,
                        LastByte = bytePosition + partSize - 1 >= objectSize ? objectSize - 1 : bytePosition + partSize - 1,
                        PartNumber = i,
                    };

                    copyResponses.Add(await client.CopyPartAsync(copyRequest));

                    bytePosition += partSize;
                }

                // Set up to complete the copy.
                var completeRequest = new CompleteMultipartUploadRequest
                {
                    BucketName = TargetBucket,
                    Key = TargetObjectKey,
                    UploadId = initResponse.UploadId,
                };
                completeRequest.AddPartETags(copyResponses);

                // Complete the copy.
                CompleteMultipartUploadResponse completeUploadResponse =
                    await client.CompleteMultipartUploadAsync(completeRequest);
            }
            catch (AmazonS3Exception e)
            {
                Console.WriteLine($"Error encountered on server. Message:'{e.Message}' when writing an object");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Unknown encountered on server. Message:'{e.Message}' when writing an object");
            }
        }
    }
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CompleteMultipartUpload](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CompleteMultipartUpload)
  + [CreateMultipartUpload](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/CreateMultipartUpload)
  + [GetObjectMetadata](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/GetObjectMetadata)
  + [UploadPartCopy](https://docs.aws.amazon.com/goto/DotNetSDKV3/s3-2006-03-01/UploadPartCopy)

### S3 Object Lambda でデータを変換する
<a name="cross_ServerlessS3DataTransformation_csharp_3_topic"></a>

次のコード例では、S3 Object Lambda でアプリケーションのデータを変換する方法を示しています。

**SDK for .NET**  
 オブジェクトがリクエストしたクライアントまたはアプリケーションのニーズに合うように、標準の S3 GET リクエストにカスタムコードを追加し、S3 から取得したリクエストされたオブジェクトを変更する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/S3ObjectLambdaFunction) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Lambda
+ Amazon S3

### 大きなファイルをアップロードまたはダウンロードする
<a name="s3_Scenario_UsingLargeFiles_csharp_3_topic"></a>

次のコード例は、Amazon S3 との間で大きなファイルをアップロードまたはダウンロードする方法を示しています。

詳細については、「[マルチパートアップロードを使用したオブジェクトのアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-upload-object.html)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/S3/#code-examples)での設定と実行の方法を確認してください。
Amazon S3 TransferUtility を使用して、S3 バケットとの間でファイルを転送する関数を呼び出します。  

```
global using System.Text;
global using Amazon.S3;
global using Amazon.S3.Model;
global using Amazon.S3.Transfer;
global using TransferUtilityBasics;



// This Amazon S3 client uses the default user credentials
// defined for this computer.
using Microsoft.Extensions.Configuration;

IAmazonS3 client = new AmazonS3Client();
var transferUtil = new TransferUtility(client);
IConfiguration _configuration;

_configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("settings.json") // Load test settings from JSON file.
    .AddJsonFile("settings.local.json",
        true) // Optionally load local settings.
    .Build();

// Edit the values in settings.json to use an S3 bucket and files that
// exist on your AWS account and on the local computer where you
// run this scenario.
var bucketName = _configuration["BucketName"];
var localPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\TransferFolder";

DisplayInstructions();

PressEnter();

Console.WriteLine();

// Upload a single file to an S3 bucket.
DisplayTitle("Upload a single file");

var fileToUpload = _configuration["FileToUpload"];
Console.WriteLine($"Uploading {fileToUpload} to the S3 bucket, {bucketName}.");

var success = await TransferMethods.UploadSingleFileAsync(transferUtil, bucketName, fileToUpload, localPath);
if (success)
{
    Console.WriteLine($"Successfully uploaded the file, {fileToUpload} to {bucketName}.");
}

PressEnter();

// Upload a local directory to an S3 bucket.
DisplayTitle("Upload all files from a local directory");
Console.WriteLine("Upload all the files in a local folder to an S3 bucket.");
const string keyPrefix = "UploadFolder";
var uploadPath = $"{localPath}\\UploadFolder";

Console.WriteLine($"Uploading the files in {uploadPath} to {bucketName}");
DisplayTitle($"{uploadPath} files");
DisplayLocalFiles(uploadPath);
Console.WriteLine();

PressEnter();

success = await TransferMethods.UploadFullDirectoryAsync(transferUtil, bucketName, keyPrefix, uploadPath);
if (success)
{
    Console.WriteLine($"Successfully uploaded the files in {uploadPath} to {bucketName}.");
    Console.WriteLine($"{bucketName} currently contains the following files:");
    await DisplayBucketFiles(client, bucketName, keyPrefix);
    Console.WriteLine();
}

PressEnter();

// Download a single file from an S3 bucket.
DisplayTitle("Download a single file");
Console.WriteLine("Now we will download a single file from an S3 bucket.");

var keyName = _configuration["FileToDownload"];

Console.WriteLine($"Downloading {keyName} from {bucketName}.");

success = await TransferMethods.DownloadSingleFileAsync(transferUtil, bucketName, keyName, localPath);
if (success)
{
    Console.WriteLine("$Successfully downloaded the file, {keyName} from {bucketName}.");
}

PressEnter();

// Download the contents of a directory from an S3 bucket.
DisplayTitle("Download the contents of an S3 bucket");
var s3Path = _configuration["S3Path"];
var downloadPath = $"{localPath}\\{s3Path}";

Console.WriteLine($"Downloading the contents of {bucketName}\\{s3Path}");
Console.WriteLine($"{bucketName}\\{s3Path} contains the following files:");
await DisplayBucketFiles(client, bucketName, s3Path);
Console.WriteLine();

success = await TransferMethods.DownloadS3DirectoryAsync(transferUtil, bucketName, s3Path, downloadPath);
if (success)
{
    Console.WriteLine($"Downloaded the files in {bucketName} to {downloadPath}.");
    Console.WriteLine($"{downloadPath} now contains the following files:");
    DisplayLocalFiles(downloadPath);
}

Console.WriteLine("\nThe TransferUtility Basics application has completed.");
PressEnter();

// Displays the title for a section of the scenario.
static void DisplayTitle(string titleText)
{
    var sepBar = new string('-', Console.WindowWidth);

    Console.WriteLine(sepBar);
    Console.WriteLine(CenterText(titleText));
    Console.WriteLine(sepBar);
}

// Displays a description of the actions to be performed by the scenario.
static void DisplayInstructions()
{
    var sepBar = new string('-', Console.WindowWidth);

    DisplayTitle("Amazon S3 Transfer Utility Basics");
    Console.WriteLine("This program shows how to use the Amazon S3 Transfer Utility.");
    Console.WriteLine("It performs the following actions:");
    Console.WriteLine("\t1. Upload a single object to an S3 bucket.");
    Console.WriteLine("\t2. Upload an entire directory from the local computer to an\n\t  S3 bucket.");
    Console.WriteLine("\t3. Download a single object from an S3 bucket.");
    Console.WriteLine("\t4. Download the objects in an S3 bucket to a local directory.");
    Console.WriteLine($"\n{sepBar}");
}

// Pauses the scenario.
static void PressEnter()
{
    Console.WriteLine("Press <Enter> to continue.");
    _ = Console.ReadLine();
    Console.WriteLine("\n");
}

// Returns the string textToCenter, padded on the left with spaces
// that center the text on the console display.
static string CenterText(string textToCenter)
{
    var centeredText = new StringBuilder();
    var screenWidth = Console.WindowWidth;
    centeredText.Append(new string(' ', (int)(screenWidth - textToCenter.Length) / 2));
    centeredText.Append(textToCenter);
    return centeredText.ToString();
}

// Displays a list of file names included in the specified path.
static void DisplayLocalFiles(string localPath)
{
    var fileList = Directory.GetFiles(localPath);
    if (fileList.Length > 0)
    {
        foreach (var fileName in fileList)
        {
            Console.WriteLine(fileName);
        }
    }
}

// Displays a list of the files in the specified S3 bucket and prefix.
static async Task DisplayBucketFiles(IAmazonS3 client, string bucketName, string s3Path)
{
    ListObjectsV2Request request = new()
    {
        BucketName = bucketName,
        Prefix = s3Path,
        MaxKeys = 5,
    };

    var response = new ListObjectsV2Response();

    do
    {
        response = await client.ListObjectsV2Async(request);

        response.S3Objects
            .ForEach(obj => Console.WriteLine($"{obj.Key}"));

        // If the response is truncated, set the request ContinuationToken
        // from the NextContinuationToken property of the response.
        request.ContinuationToken = response.NextContinuationToken;
    } while (response.IsTruncated);
}
```
1 つのファイルをアップロードします。  

```
        /// <summary>
        /// Uploads a single file from the local computer to an S3 bucket.
        /// </summary>
        /// <param name="transferUtil">The transfer initialized TransferUtility
        /// object.</param>
        /// <param name="bucketName">The name of the S3 bucket where the file
        /// will be stored.</param>
        /// <param name="fileName">The name of the file to upload.</param>
        /// <param name="localPath">The local path where the file is stored.</param>
        /// <returns>A boolean value indicating the success of the action.</returns>
        public static async Task<bool> UploadSingleFileAsync(
            TransferUtility transferUtil,
            string bucketName,
            string fileName,
            string localPath)
        {
            if (File.Exists($"{localPath}\\{fileName}"))
            {
                try
                {
                    await transferUtil.UploadAsync(new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        Key = fileName,
                        FilePath = $"{localPath}\\{fileName}",
                    });

                    return true;
                }
                catch (AmazonS3Exception s3Ex)
                {
                    Console.WriteLine($"Could not upload {fileName} from {localPath} because:");
                    Console.WriteLine(s3Ex.Message);
                    return false;
                }
            }
            else
            {
                Console.WriteLine($"{fileName} does not exist in {localPath}");
                return false;
            }
        }
```
ローカルディレクトリ全体をアップロードします。  

```
        /// <summary>
        /// Uploads all the files in a local directory to a directory in an S3
        /// bucket.
        /// </summary>
        /// <param name="transferUtil">The transfer initialized TransferUtility
        /// object.</param>
        /// <param name="bucketName">The name of the S3 bucket where the files
        /// will be stored.</param>
        /// <param name="keyPrefix">The key prefix is the S3 directory where
        /// the files will be stored.</param>
        /// <param name="localPath">The local directory that contains the files
        /// to be uploaded.</param>
        /// <returns>A Boolean value representing the success of the action.</returns>
        public static async Task<bool> UploadFullDirectoryAsync(
            TransferUtility transferUtil,
            string bucketName,
            string keyPrefix,
            string localPath)
        {
            if (Directory.Exists(localPath))
            {
                try
                {
                    await transferUtil.UploadDirectoryAsync(new TransferUtilityUploadDirectoryRequest
                    {
                        BucketName = bucketName,
                        KeyPrefix = keyPrefix,
                        Directory = localPath,
                    });

                    return true;
                }
                catch (AmazonS3Exception s3Ex)
                {
                    Console.WriteLine($"Can't upload the contents of {localPath} because:");
                    Console.WriteLine(s3Ex?.Message);
                    return false;
                }
            }
            else
            {
                Console.WriteLine($"The directory {localPath} does not exist.");
                return false;
            }
        }
```
1 つのファイルをダウンロードします。  

```
        /// <summary>
        /// Download a single file from an S3 bucket to the local computer.
        /// </summary>
        /// <param name="transferUtil">The transfer initialized TransferUtility
        /// object.</param>
        /// <param name="bucketName">The name of the S3 bucket containing the
        /// file to download.</param>
        /// <param name="keyName">The name of the file to download.</param>
        /// <param name="localPath">The path on the local computer where the
        /// downloaded file will be saved.</param>
        /// <returns>A Boolean value indicating the results of the action.</returns>
        public static async Task<bool> DownloadSingleFileAsync(
        TransferUtility transferUtil,
            string bucketName,
            string keyName,
            string localPath)
        {
            await transferUtil.DownloadAsync(new TransferUtilityDownloadRequest
            {
                BucketName = bucketName,
                Key = keyName,
                FilePath = $"{localPath}\\{keyName}",
            });

            return (File.Exists($"{localPath}\\{keyName}"));
        }
```
S3 バケットの内容をダウンロードします。  

```
        /// <summary>
        /// Downloads the contents of a directory in an S3 bucket to a
        /// directory on the local computer.
        /// </summary>
        /// <param name="transferUtil">The transfer initialized TransferUtility
        /// object.</param>
        /// <param name="bucketName">The bucket containing the files to download.</param>
        /// <param name="s3Path">The S3 directory where the files are located.</param>
        /// <param name="localPath">The local path to which the files will be
        /// saved.</param>
        /// <returns>A Boolean value representing the success of the action.</returns>
        public static async Task<bool> DownloadS3DirectoryAsync(
            TransferUtility transferUtil,
            string bucketName,
            string s3Path,
            string localPath)
        {
            int fileCount = 0;

            // If the directory doesn't exist, it will be created.
            if (Directory.Exists(s3Path))
            {
                var files = Directory.GetFiles(localPath);
                fileCount = files.Length;
            }

            await transferUtil.DownloadDirectoryAsync(new TransferUtilityDownloadDirectoryRequest
            {
                BucketName = bucketName,
                LocalDirectory = localPath,
                S3Directory = s3Path,
            });

            if (Directory.Exists(localPath))
            {
                var files = Directory.GetFiles(localPath);
                if (files.Length > fileCount)
                {
                    return true;
                }

                // No change in the number of files. Assume
                // the download failed.
                return false;
            }

            // The local directory doesn't exist. No files
            // were downloaded.
            return false;
        }
```
TransferUtility を使用してアップロードの進行状況を追跡します。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Transfer;

    /// <summary>
    /// This example shows how to track the progress of a multipart upload
    /// using the Amazon Simple Storage Service (Amazon S3) TransferUtility to
    /// upload to an Amazon S3 bucket.
    /// </summary>
    public class TrackMPUUsingHighLevelAPI
    {
        public static async Task Main()
        {
            string bucketName = "amzn-s3-demo-bucket";
            string keyName = "sample_pic.png";
            string path = "filepath/directory/";
            string filePath = $"{path}{keyName}";

            // If the AWS Region defined for your default user is different
            // from the Region where your Amazon S3 bucket is located,
            // pass the Region name to the Amazon S3 client object's constructor.
            // For example: RegionEndpoint.USWest2 or RegionEndpoint.USEast2.
            IAmazonS3 client = new AmazonS3Client();

            await TrackMPUAsync(client, bucketName, filePath, keyName);
        }

        /// <summary>
        /// Starts an Amazon S3 multipart upload and assigns an event handler to
        /// track the progress of the upload.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 client object used to
        /// perform the multipart upload.</param>
        /// <param name="bucketName">The name of the bucket to which to upload
        /// the file.</param>
        /// <param name="filePath">The path, including the file name of the
        /// file to be uploaded to the Amazon S3 bucket.</param>
        /// <param name="keyName">The file name to be used in the
        /// destination Amazon S3 bucket.</param>
        public static async Task TrackMPUAsync(
            IAmazonS3 client,
            string bucketName,
            string filePath,
            string keyName)
        {
            try
            {
                var fileTransferUtility = new TransferUtility(client);

                // Use TransferUtilityUploadRequest to configure options.
                // In this example we subscribe to an event.
                var uploadRequest =
                    new TransferUtilityUploadRequest
                    {
                        BucketName = bucketName,
                        FilePath = filePath,
                        Key = keyName,
                    };

                uploadRequest.UploadProgressEvent +=
                    new EventHandler<UploadProgressArgs>(
                        UploadRequest_UploadPartProgressEvent);

                await fileTransferUtility.UploadAsync(uploadRequest);
                Console.WriteLine("Upload completed");
            }
            catch (AmazonS3Exception ex)
            {
                Console.WriteLine($"Error:: {ex.Message}");
            }
        }

        /// <summary>
        /// Event handler to check the progress of the multipart upload.
        /// </summary>
        /// <param name="sender">The object that raised the event.</param>
        /// <param name="e">The object that contains multipart upload
        /// information.</param>
        public static void UploadRequest_UploadPartProgressEvent(object sender, UploadProgressArgs e)
        {
            // Process event.
            Console.WriteLine($"{e.TransferredBytes}/{e.TotalBytes}");
        }
    }
```
暗号化したオブジェクトをアップロードします。  

```
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Security.Cryptography;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Model;

    /// <summary>
    /// Uses the Amazon Simple Storage Service (Amazon S3) low level API to
    /// perform a multipart upload to an Amazon S3 bucket.
    /// </summary>
    public class SSECLowLevelMPUcopyObject
    {
        public static async Task Main()
        {
            string existingBucketName = "amzn-s3-demo-bucket";
            string sourceKeyName = "sample_file.txt";
            string targetKeyName = "sample_file_copy.txt";
            string filePath = $"sample\\{targetKeyName}";

            // If the AWS Region defined for your default user is different
            // from the Region where your Amazon S3 bucket is located,
            // pass the Region name to the Amazon S3 client object's constructor.
            // For example: RegionEndpoint.USEast1.
            IAmazonS3 client = new AmazonS3Client();

            // Create the encryption key.
            var base64Key = CreateEncryptionKey();

            await CreateSampleObjUsingClientEncryptionKeyAsync(
                client,
                existingBucketName,
                sourceKeyName,
                filePath,
                base64Key);
        }

        /// <summary>
        /// Creates the encryption key to use with the multipart upload.
        /// </summary>
        /// <returns>A string containing the base64-encoded key for encrypting
        /// the multipart upload.</returns>
        public static string CreateEncryptionKey()
        {
            Aes aesEncryption = Aes.Create();
            aesEncryption.KeySize = 256;
            aesEncryption.GenerateKey();
            string base64Key = Convert.ToBase64String(aesEncryption.Key);
            return base64Key;
        }

        /// <summary>
        /// Creates and uploads an object using a multipart upload.
        /// </summary>
        /// <param name="client">The initialized Amazon S3 object used to
        /// initialize and perform the multipart upload.</param>
        /// <param name="existingBucketName">The name of the bucket to which
        /// the object will be uploaded.</param>
        /// <param name="sourceKeyName">The source object name.</param>
        /// <param name="filePath">The location of the source object.</param>
        /// <param name="base64Key">The encryption key to use with the upload.</param>
        public static async Task CreateSampleObjUsingClientEncryptionKeyAsync(
            IAmazonS3 client,
            string existingBucketName,
            string sourceKeyName,
            string filePath,
            string base64Key)
        {
            List<UploadPartResponse> uploadResponses = new List<UploadPartResponse>();

            InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
            {
                BucketName = existingBucketName,
                Key = sourceKeyName,
                ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
                ServerSideEncryptionCustomerProvidedKey = base64Key,
            };

            InitiateMultipartUploadResponse initResponse =
               await client.InitiateMultipartUploadAsync(initiateRequest);

            long contentLength = new FileInfo(filePath).Length;
            long partSize = 5 * (long)Math.Pow(2, 20); // 5 MB

            try
            {
                long filePosition = 0;
                for (int i = 1; filePosition < contentLength; i++)
                {
                    UploadPartRequest uploadRequest = new UploadPartRequest
                    {
                        BucketName = existingBucketName,
                        Key = sourceKeyName,
                        UploadId = initResponse.UploadId,
                        PartNumber = i,
                        PartSize = partSize,
                        FilePosition = filePosition,
                        FilePath = filePath,
                        ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.AES256,
                        ServerSideEncryptionCustomerProvidedKey = base64Key,
                    };

                    // Upload part and add response to our list.
                    uploadResponses.Add(await client.UploadPartAsync(uploadRequest));

                    filePosition += partSize;
                }

                CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
                {
                    BucketName = existingBucketName,
                    Key = sourceKeyName,
                    UploadId = initResponse.UploadId,
                };
                completeRequest.AddPartETags(uploadResponses);

                CompleteMultipartUploadResponse completeUploadResponse =
                    await client.CompleteMultipartUploadAsync(completeRequest);
            }
            catch (Exception exception)
            {
                Console.WriteLine($"Exception occurred: {exception.Message}");

                // If there was an error, abort the multipart upload.
                AbortMultipartUploadRequest abortMPURequest = new AbortMultipartUploadRequest
                {
                    BucketName = existingBucketName,
                    Key = sourceKeyName,
                    UploadId = initResponse.UploadId,
                };

                await client.AbortMultipartUploadAsync(abortMPURequest);
            }
        }
    }
```

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_csharp_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
.NET を使用して Lambda で S3 イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.S3;
using System;
using Amazon.Lambda.S3Events;
using System.Web;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace S3Integration
{
    public class Function
    {
        private static AmazonS3Client _s3Client;
        public Function() : this(null)
        {
        }

        internal Function(AmazonS3Client s3Client)
        {
            _s3Client = s3Client ?? new AmazonS3Client();
        }

        public async Task<string> Handler(S3Event evt, ILambdaContext context)
        {
            try
            {
                if (evt.Records.Count <= 0)
                {
                    context.Logger.LogLine("Empty S3 Event received");
                    return string.Empty;
                }

                var bucket = evt.Records[0].S3.Bucket.Name;
                var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key);

                context.Logger.LogLine($"Request is for {bucket} and {key}");

                var objectResult = await _s3Client.GetObjectAsync(bucket, key);

                context.Logger.LogLine($"Returning {objectResult.Key}");

                return objectResult.Key;
            }
            catch (Exception e)
            {
                context.Logger.LogLine($"Error processing request - {e.Message}");

                return string.Empty;
            }
        }
    }
}
```

# を使用した SageMaker AI の例 SDK for .NET
<a name="csharp_3_sagemaker_code_examples"></a>

次のコード例は、SageMaker AI AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello SageMaker AI
<a name="sagemaker_Hello_csharp_3_topic"></a>

次のコード例は、SageMaker AI の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SageMaker#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.SageMaker;
using Amazon.SageMaker.Model;

namespace SageMakerActions;

public static class HelloSageMaker
{
    static async Task Main(string[] args)
    {
        var sageMakerClient = new AmazonSageMakerClient();

        Console.WriteLine($"Hello Amazon SageMaker! Let's list some of your notebook instances:");
        Console.WriteLine();

        // You can use await and any of the async methods to get a response.
        // Let's get the first five notebook instances.
        var response = await sageMakerClient.ListNotebookInstancesAsync(
            new ListNotebookInstancesRequest()
            {
                MaxResults = 5
            });

        if (!response.NotebookInstances.Any())
        {
            Console.WriteLine($"No notebook instances found.");
            Console.WriteLine("See https://docs.aws.amazon.com/sagemaker/latest/dg/howitworks-create-ws.html to create one.");
        }

        foreach (var notebookInstance in response.NotebookInstances)
        {
            Console.WriteLine($"\tInstance: {notebookInstance.NotebookInstanceName}");
            Console.WriteLine($"\tArn: {notebookInstance.NotebookInstanceArn}");
            Console.WriteLine($"\tCreation Date: {notebookInstance.CreationTime.ToShortDateString()}");
            Console.WriteLine();
        }
    }
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListNotebookInstances](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/ListNotebookInstances)」を参照してください。

## アクション
<a name="actions"></a>

### `CreatePipeline`
<a name="sagemaker_CreatePipeline_csharp_3_topic"></a>

次のコード例は、`CreatePipeline` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SageMaker#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a pipeline from a JSON definition, or update it if the pipeline already exists.
    /// </summary>
    /// <returns>The Amazon Resource Name (ARN) of the pipeline.</returns>
    public async Task<string> SetupPipeline(string pipelineJson, string roleArn, string name, string description, string displayName)
    {
        try
        {
            var updateResponse = await _amazonSageMaker.UpdatePipelineAsync(
                new UpdatePipelineRequest()
                {
                    PipelineDefinition = pipelineJson,
                    PipelineDescription = description,
                    PipelineDisplayName = displayName,
                    PipelineName = name,
                    RoleArn = roleArn
                });
            return updateResponse.PipelineArn;
        }
        catch (Amazon.SageMaker.Model.ResourceNotFoundException)
        {
            var createResponse = await _amazonSageMaker.CreatePipelineAsync(
                new CreatePipelineRequest()
                {
                    PipelineDefinition = pipelineJson,
                    PipelineDescription = description,
                    PipelineDisplayName = displayName,
                    PipelineName = name,
                    RoleArn = roleArn
                });

            return createResponse.PipelineArn;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreatePipeline](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/CreatePipeline)」を参照してください。

### `DeletePipeline`
<a name="sagemaker_DeletePipeline_csharp_3_topic"></a>

次のコード例は、`DeletePipeline` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SageMaker#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a SageMaker pipeline by name.
    /// </summary>
    /// <param name="pipelineName">The name of the pipeline to delete.</param>
    /// <returns>The ARN of the pipeline.</returns>
    public async Task<string> DeletePipelineByName(string pipelineName)
    {
        var deleteResponse = await _amazonSageMaker.DeletePipelineAsync(
            new DeletePipelineRequest()
            {
                PipelineName = pipelineName
            });

        return deleteResponse.PipelineArn;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeletePipeline](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/DeletePipeline)」を参照してください。

### `DescribePipelineExecution`
<a name="sagemaker_DescribePipelineExecution_csharp_3_topic"></a>

次のコード例は、`DescribePipelineExecution` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SageMaker#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Check the status of a run.
    /// </summary>
    /// <param name="pipelineExecutionArn">The ARN.</param>
    /// <returns>The status of the pipeline.</returns>
    public async Task<PipelineExecutionStatus> CheckPipelineExecutionStatus(string pipelineExecutionArn)
    {
        var describeResponse = await _amazonSageMaker.DescribePipelineExecutionAsync(
            new DescribePipelineExecutionRequest()
            {
                PipelineExecutionArn = pipelineExecutionArn
            });

        return describeResponse.PipelineExecutionStatus;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribePipelineExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/DescribePipelineExecution)」を参照してください。

### `StartPipelineExecution`
<a name="sagemaker_StartPipelineExecution_csharp_3_topic"></a>

次のコード例は、`StartPipelineExecution` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SageMaker#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Run a pipeline with input and output file locations.
    /// </summary>
    /// <param name="queueUrl">The URL for the queue to use for pipeline callbacks.</param>
    /// <param name="inputLocationUrl">The input location in Amazon Simple Storage Service (Amazon S3).</param>
    /// <param name="outputLocationUrl">The output location in Amazon S3.</param>
    /// <param name="pipelineName">The name of the pipeline.</param>
    /// <param name="executionRoleArn">The ARN of the role.</param>
    /// <returns>The ARN of the pipeline run.</returns>
    public async Task<string> ExecutePipeline(
        string queueUrl,
        string inputLocationUrl,
        string outputLocationUrl,
        string pipelineName,
        string executionRoleArn)
    {
        var inputConfig = new VectorEnrichmentJobInputConfig()
        {
            DataSourceConfig = new()
            {
                S3Data = new VectorEnrichmentJobS3Data()
                {
                    S3Uri = inputLocationUrl
                }
            },
            DocumentType = VectorEnrichmentJobDocumentType.CSV
        };

        var exportConfig = new ExportVectorEnrichmentJobOutputConfig()
        {
            S3Data = new VectorEnrichmentJobS3Data()
            {
                S3Uri = outputLocationUrl
            }
        };

        var jobConfig = new VectorEnrichmentJobConfig()
        {
            ReverseGeocodingConfig = new ReverseGeocodingConfig()
            {
                XAttributeName = "Longitude",
                YAttributeName = "Latitude"
            }
        };

#pragma warning disable SageMaker1002 // Property value does not match required pattern is allowed here to match the pipeline definition.
        var startExecutionResponse = await _amazonSageMaker.StartPipelineExecutionAsync(
            new StartPipelineExecutionRequest()
            {
                PipelineName = pipelineName,
                PipelineExecutionDisplayName = pipelineName + "-example-execution",
                PipelineParameters = new List<Parameter>()
                {
                    new Parameter() { Name = "parameter_execution_role", Value = executionRoleArn },
                    new Parameter() { Name = "parameter_queue_url", Value = queueUrl },
                    new Parameter() { Name = "parameter_vej_input_config", Value = JsonSerializer.Serialize(inputConfig) },
                    new Parameter() { Name = "parameter_vej_export_config", Value = JsonSerializer.Serialize(exportConfig) },
                    new Parameter() { Name = "parameter_step_1_vej_config", Value = JsonSerializer.Serialize(jobConfig) }
                }
            });
#pragma warning restore SageMaker1002
        return startExecutionResponse.PipelineExecutionArn;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[StartPipelineExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/StartPipelineExecution)」を参照してください。

### `UpdatePipeline`
<a name="sagemaker_UpdatePipeline_csharp_3_topic"></a>

次のコード例は、`UpdatePipeline` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SageMaker#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a pipeline from a JSON definition, or update it if the pipeline already exists.
    /// </summary>
    /// <returns>The Amazon Resource Name (ARN) of the pipeline.</returns>
    public async Task<string> SetupPipeline(string pipelineJson, string roleArn, string name, string description, string displayName)
    {
        try
        {
            var updateResponse = await _amazonSageMaker.UpdatePipelineAsync(
                new UpdatePipelineRequest()
                {
                    PipelineDefinition = pipelineJson,
                    PipelineDescription = description,
                    PipelineDisplayName = displayName,
                    PipelineName = name,
                    RoleArn = roleArn
                });
            return updateResponse.PipelineArn;
        }
        catch (Amazon.SageMaker.Model.ResourceNotFoundException)
        {
            var createResponse = await _amazonSageMaker.CreatePipelineAsync(
                new CreatePipelineRequest()
                {
                    PipelineDefinition = pipelineJson,
                    PipelineDescription = description,
                    PipelineDisplayName = displayName,
                    PipelineName = name,
                    RoleArn = roleArn
                });

            return createResponse.PipelineArn;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[UpdatePipeline](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/UpdatePipeline)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 地理空間ジョブとパイプラインの使用を開始する
<a name="sagemaker_Scenario_Pipelines_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パイプラインのリソースを設定します。
+ 地理空間ジョブを実行するパイプラインを設定します。
+ パイプラインの実行を開始します。
+ ジョブ実行のステータスをモニタリングします。
+ パイプラインの出力を表示します。
+ リソースをクリーンアップします。

詳細については、[「Community.aws で SDK を使用して SageMaker パイプラインを作成および実行する AWS SDKs](https://community.aws/posts/create-and-run-sagemaker-pipelines-using-aws-sdks)」を参照してください。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SageMaker#code-examples)での設定と実行の方法を確認してください。
SageMaker AI オペレーションをラップするクラスを作成します。  

```
using System.Text.Json;
using Amazon.SageMaker;
using Amazon.SageMaker.Model;
using Amazon.SageMakerGeospatial;
using Amazon.SageMakerGeospatial.Model;

namespace SageMakerActions;

/// <summary>
/// Wrapper class for Amazon SageMaker actions and logic.
/// </summary>
public class SageMakerWrapper
{
    private readonly IAmazonSageMaker _amazonSageMaker;
    public SageMakerWrapper(IAmazonSageMaker amazonSageMaker)
    {
        _amazonSageMaker = amazonSageMaker;
    }

    /// <summary>
    /// Create a pipeline from a JSON definition, or update it if the pipeline already exists.
    /// </summary>
    /// <returns>The Amazon Resource Name (ARN) of the pipeline.</returns>
    public async Task<string> SetupPipeline(string pipelineJson, string roleArn, string name, string description, string displayName)
    {
        try
        {
            var updateResponse = await _amazonSageMaker.UpdatePipelineAsync(
                new UpdatePipelineRequest()
                {
                    PipelineDefinition = pipelineJson,
                    PipelineDescription = description,
                    PipelineDisplayName = displayName,
                    PipelineName = name,
                    RoleArn = roleArn
                });
            return updateResponse.PipelineArn;
        }
        catch (Amazon.SageMaker.Model.ResourceNotFoundException)
        {
            var createResponse = await _amazonSageMaker.CreatePipelineAsync(
                new CreatePipelineRequest()
                {
                    PipelineDefinition = pipelineJson,
                    PipelineDescription = description,
                    PipelineDisplayName = displayName,
                    PipelineName = name,
                    RoleArn = roleArn
                });

            return createResponse.PipelineArn;
        }
    }

    /// <summary>
    /// Run a pipeline with input and output file locations.
    /// </summary>
    /// <param name="queueUrl">The URL for the queue to use for pipeline callbacks.</param>
    /// <param name="inputLocationUrl">The input location in Amazon Simple Storage Service (Amazon S3).</param>
    /// <param name="outputLocationUrl">The output location in Amazon S3.</param>
    /// <param name="pipelineName">The name of the pipeline.</param>
    /// <param name="executionRoleArn">The ARN of the role.</param>
    /// <returns>The ARN of the pipeline run.</returns>
    public async Task<string> ExecutePipeline(
        string queueUrl,
        string inputLocationUrl,
        string outputLocationUrl,
        string pipelineName,
        string executionRoleArn)
    {
        var inputConfig = new VectorEnrichmentJobInputConfig()
        {
            DataSourceConfig = new()
            {
                S3Data = new VectorEnrichmentJobS3Data()
                {
                    S3Uri = inputLocationUrl
                }
            },
            DocumentType = VectorEnrichmentJobDocumentType.CSV
        };

        var exportConfig = new ExportVectorEnrichmentJobOutputConfig()
        {
            S3Data = new VectorEnrichmentJobS3Data()
            {
                S3Uri = outputLocationUrl
            }
        };

        var jobConfig = new VectorEnrichmentJobConfig()
        {
            ReverseGeocodingConfig = new ReverseGeocodingConfig()
            {
                XAttributeName = "Longitude",
                YAttributeName = "Latitude"
            }
        };

#pragma warning disable SageMaker1002 // Property value does not match required pattern is allowed here to match the pipeline definition.
        var startExecutionResponse = await _amazonSageMaker.StartPipelineExecutionAsync(
            new StartPipelineExecutionRequest()
            {
                PipelineName = pipelineName,
                PipelineExecutionDisplayName = pipelineName + "-example-execution",
                PipelineParameters = new List<Parameter>()
                {
                    new Parameter() { Name = "parameter_execution_role", Value = executionRoleArn },
                    new Parameter() { Name = "parameter_queue_url", Value = queueUrl },
                    new Parameter() { Name = "parameter_vej_input_config", Value = JsonSerializer.Serialize(inputConfig) },
                    new Parameter() { Name = "parameter_vej_export_config", Value = JsonSerializer.Serialize(exportConfig) },
                    new Parameter() { Name = "parameter_step_1_vej_config", Value = JsonSerializer.Serialize(jobConfig) }
                }
            });
#pragma warning restore SageMaker1002
        return startExecutionResponse.PipelineExecutionArn;
    }

    /// <summary>
    /// Check the status of a run.
    /// </summary>
    /// <param name="pipelineExecutionArn">The ARN.</param>
    /// <returns>The status of the pipeline.</returns>
    public async Task<PipelineExecutionStatus> CheckPipelineExecutionStatus(string pipelineExecutionArn)
    {
        var describeResponse = await _amazonSageMaker.DescribePipelineExecutionAsync(
            new DescribePipelineExecutionRequest()
            {
                PipelineExecutionArn = pipelineExecutionArn
            });

        return describeResponse.PipelineExecutionStatus;
    }

    /// <summary>
    /// Delete a SageMaker pipeline by name.
    /// </summary>
    /// <param name="pipelineName">The name of the pipeline to delete.</param>
    /// <returns>The ARN of the pipeline.</returns>
    public async Task<string> DeletePipelineByName(string pipelineName)
    {
        var deleteResponse = await _amazonSageMaker.DeletePipelineAsync(
            new DeletePipelineRequest()
            {
                PipelineName = pipelineName
            });

        return deleteResponse.PipelineArn;
    }
}
```
SageMaker Ai パイプラインからのコールバックを処理する関数を作成します。  

```
using System.Text.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;
using Amazon.SageMaker;
using Amazon.SageMaker.Model;
using Amazon.SageMakerGeospatial;
using Amazon.SageMakerGeospatial.Model;

// Assembly attribute to enable the AWS Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SageMakerLambda;

/// <summary>
/// The AWS Lambda function handler for the Amazon SageMaker pipeline.
/// </summary>
public class SageMakerLambdaFunction
{
    /// <summary>
    /// Default constructor. This constructor is used by AWS Lambda to construct the instance. When invoked in a Lambda environment
    /// the AWS credentials will come from the AWS Identity and Access Management (IAM) role associated with the function. The AWS Region will be set to the
    /// Region that the Lambda function is running in.
    /// </summary>
    public SageMakerLambdaFunction()
    {
    }

    /// <summary>
    /// The AWS Lambda function handler that processes events from the SageMaker pipeline and starts a job or export.
    /// </summary>
    /// <param name="request">The custom SageMaker pipeline request object.</param>
    /// <param name="context">The Lambda context.</param>
    /// <returns>The dictionary of output parameters.</returns>
    public async Task<Dictionary<string, string>> FunctionHandler(PipelineRequest request, ILambdaContext context)
    {
        var geoSpatialClient = new AmazonSageMakerGeospatialClient();
        var sageMakerClient = new AmazonSageMakerClient();
        var responseDictionary = new Dictionary<string, string>();
        context.Logger.LogInformation("Function handler started with request: " + JsonSerializer.Serialize(request));
        if (request.Records != null && request.Records.Any())
        {
            context.Logger.LogInformation("Records found, this is a queue event. Processing the queue records.");
            foreach (var message in request.Records)
            {
                await ProcessMessageAsync(message, context, geoSpatialClient, sageMakerClient);
            }
        }
        else if (!string.IsNullOrEmpty(request.vej_export_config))
        {
            context.Logger.LogInformation("Export configuration found, this is an export. Start the Vector Enrichment Job (VEJ) export.");

            var outputConfig =
                JsonSerializer.Deserialize<ExportVectorEnrichmentJobOutputConfig>(
                    request.vej_export_config);

            var exportResponse = await geoSpatialClient.ExportVectorEnrichmentJobAsync(
                new ExportVectorEnrichmentJobRequest()
                {
                    Arn = request.vej_arn,
                    ExecutionRoleArn = request.Role,
                    OutputConfig = outputConfig
                });
            context.Logger.LogInformation($"Export response: {JsonSerializer.Serialize(exportResponse)}");
            responseDictionary = new Dictionary<string, string>
            {
                { "export_eoj_status", exportResponse.ExportStatus.ToString() },
                { "vej_arn", exportResponse.Arn }
            };
        }
        else if (!string.IsNullOrEmpty(request.vej_name))
        {
            context.Logger.LogInformation("Vector Enrichment Job name found, starting the job.");
            var inputConfig =
                JsonSerializer.Deserialize<VectorEnrichmentJobInputConfig>(
                    request.vej_input_config);

            var jobConfig =
                JsonSerializer.Deserialize<VectorEnrichmentJobConfig>(
                    request.vej_config);

            var jobResponse = await geoSpatialClient.StartVectorEnrichmentJobAsync(
                new StartVectorEnrichmentJobRequest()
                {
                    ExecutionRoleArn = request.Role,
                    InputConfig = inputConfig,
                    Name = request.vej_name,
                    JobConfig = jobConfig

                });
            context.Logger.LogInformation("Job response: " + JsonSerializer.Serialize(jobResponse));
            responseDictionary = new Dictionary<string, string>
            {
                { "vej_arn", jobResponse.Arn },
                { "statusCode", jobResponse.HttpStatusCode.ToString() }
            };
        }
        return responseDictionary;
    }

    /// <summary>
    /// Process a queue message and check the status of a SageMaker job.
    /// </summary>
    /// <param name="message">The queue message.</param>
    /// <param name="context">The Lambda context.</param>
    /// <param name="geoClient">The SageMaker GeoSpatial client.</param>
    /// <param name="sageMakerClient">The SageMaker client.</param>
    /// <returns>Async task.</returns>
    private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context,
        AmazonSageMakerGeospatialClient geoClient, AmazonSageMakerClient sageMakerClient)
    {
        context.Logger.LogInformation($"Processed message {message.Body}");

        // Get information about the SageMaker job.
        var payload = JsonSerializer.Deserialize<QueuePayload>(message.Body);
        context.Logger.LogInformation($"Payload token {payload!.token}");
        var token = payload.token;

        if (payload.arguments.ContainsKey("vej_arn"))
        {
            // Use the job ARN and the token to get the job status.
            var job_arn = payload.arguments["vej_arn"];
            context.Logger.LogInformation($"Token: {token}, arn {job_arn}");

            var jobInfo = geoClient.GetVectorEnrichmentJobAsync(
                new GetVectorEnrichmentJobRequest()
                {
                    Arn = job_arn
                });
            context.Logger.LogInformation("Job info: " + JsonSerializer.Serialize(jobInfo));
            if (jobInfo.Result.Status == VectorEnrichmentJobStatus.COMPLETED)
            {
                context.Logger.LogInformation($"Status completed, resuming pipeline...");
                await sageMakerClient.SendPipelineExecutionStepSuccessAsync(
                    new SendPipelineExecutionStepSuccessRequest()
                    {
                        CallbackToken = token,
                        OutputParameters = new List<OutputParameter>()
                        {
                            new OutputParameter()
                                { Name = "export_status", Value = jobInfo.Result.Status }
                        }
                    });
            }
            else if (jobInfo.Result.Status == VectorEnrichmentJobStatus.FAILED)
            {
                context.Logger.LogInformation($"Status failed, stopping pipeline...");
                await sageMakerClient.SendPipelineExecutionStepFailureAsync(
                    new SendPipelineExecutionStepFailureRequest()
                    {
                        CallbackToken = token,
                        FailureReason = jobInfo.Result.ErrorDetails.ErrorMessage
                    });
            }
            else if (jobInfo.Result.Status == VectorEnrichmentJobStatus.IN_PROGRESS)
            {
                // Put this message back in the queue to reprocess later.
                context.Logger.LogInformation(
                    $"Status still in progress, check back later.");
                throw new("Job still running.");
            }
        }
    }
}
```
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
public static class PipelineWorkflow
{
    public static IAmazonIdentityManagementService _iamClient = null!;
    public static SageMakerWrapper _sageMakerWrapper = null!;
    public static IAmazonSQS _sqsClient = null!;
    public static IAmazonS3 _s3Client = null!;
    public static IAmazonLambda _lambdaClient = null!;
    public static IConfiguration _configuration = null!;

    public static string lambdaFunctionName = "SageMakerExampleFunction";
    public static string sageMakerRoleName = "SageMakerExampleRole";
    public static string lambdaRoleName = "SageMakerExampleLambdaRole";

    private static string[] lambdaRolePolicies = null!;
    private static string[] sageMakerRolePolicies = null!;

    static async Task Main(string[] args)
    {
        var options = new AWSOptions() { Region = RegionEndpoint.USWest2 };
        // Set up dependency injection for the AWS service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonIdentityManagementService>(options)
                    .AddAWSService<IAmazonEC2>(options)
                    .AddAWSService<IAmazonSageMaker>(options)
                    .AddAWSService<IAmazonSageMakerGeospatial>(options)
                    .AddAWSService<IAmazonSQS>(options)
                    .AddAWSService<IAmazonS3>(options)
                    .AddAWSService<IAmazonLambda>(options)
                    .AddTransient<SageMakerWrapper>()
        )
        .Build();

        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();

        ServicesSetup(host);
        string queueUrl = "";
        string queueName = _configuration["queueName"];
        string bucketName = _configuration["bucketName"];
        var pipelineName = _configuration["pipelineName"];

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine(
                "Welcome to the Amazon SageMaker pipeline example scenario.");
            Console.WriteLine(
                "\nThis example scenario will guide you through setting up and running an" +
                "\nAmazon SageMaker pipeline. The pipeline uses an AWS Lambda function and an" +
                "\nAmazon SQS Queue. It runs a vector enrichment reverse geocode job to" +
                "\nreverse geocode addresses in an input file and store the results in an export file.");
            Console.WriteLine(new string('-', 80));

            Console.WriteLine(new string('-', 80));
            Console.WriteLine(
                "First, we will set up the roles, functions, and queue needed by the SageMaker pipeline.");
            Console.WriteLine(new string('-', 80));

            var lambdaRoleArn = await CreateLambdaRole();
            var sageMakerRoleArn = await CreateSageMakerRole();
            var functionArn = await SetupLambda(lambdaRoleArn, true);
            queueUrl = await SetupQueue(queueName);
            await SetupBucket(bucketName);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Now we can create and run our pipeline.");
            Console.WriteLine(new string('-', 80));

            await SetupPipeline(sageMakerRoleArn, functionArn, pipelineName);
            var executionArn = await ExecutePipeline(queueUrl, sageMakerRoleArn, pipelineName, bucketName);
            await WaitForPipelineExecution(executionArn);

            await GetOutputResults(bucketName);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("The pipeline has completed. To view the pipeline and runs " +
                              "in SageMaker Studio, follow these instructions:" +
                              "\nhttps://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-studio.html");
            Console.WriteLine(new string('-', 80));

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Finally, let's clean up our resources.");
            Console.WriteLine(new string('-', 80));

            await CleanupResources(true, queueUrl, pipelineName, bucketName);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("SageMaker pipeline scenario is complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            await CleanupResources(true, queueUrl, pipelineName, bucketName);
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _sageMakerWrapper = host.Services.GetRequiredService<SageMakerWrapper>();
        _iamClient = host.Services.GetRequiredService<IAmazonIdentityManagementService>();
        _sqsClient = host.Services.GetRequiredService<IAmazonSQS>();
        _s3Client = host.Services.GetRequiredService<IAmazonS3>();
        _lambdaClient = host.Services.GetRequiredService<IAmazonLambda>();
    }

    /// <summary>
    /// Set up AWS Lambda, either by updating an existing function or creating a new function.
    /// </summary>
    /// <param name="roleArn">The role Amazon Resource Name (ARN) to use for the Lambda function.</param>
    /// <param name="askUser">True to ask the user before updating.</param>
    /// <returns>The ARN of the function.</returns>
    public static async Task<string> SetupLambda(string roleArn, bool askUser)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Setting up the Lambda function for the pipeline.");
        var handlerName = "SageMakerLambda::SageMakerLambda.SageMakerLambdaFunction::FunctionHandler";
        var functionArn = "";
        try
        {
            var functionInfo = await _lambdaClient.GetFunctionAsync(new GetFunctionRequest()
            {
                FunctionName = lambdaFunctionName
            });

            var updateFunction = true;
            if (askUser)
            {
                updateFunction = GetYesNoResponse(
                    $"\tThe Lambda function {lambdaFunctionName} already exists, do you want to update it?");
            }

            if (updateFunction)
            {
                // Update the Lambda function.
                using var zipMemoryStream = new MemoryStream(await File.ReadAllBytesAsync("SageMakerLambda.zip"));
                await _lambdaClient.UpdateFunctionCodeAsync(
                    new UpdateFunctionCodeRequest()
                    {
                        FunctionName = lambdaFunctionName,
                        ZipFile = zipMemoryStream,
                    });
            }

            functionArn = functionInfo.Configuration.FunctionArn;
        }
        catch (ResourceNotFoundException)
        {
            Console.WriteLine($"\tThe Lambda function {lambdaFunctionName} was not found, creating the new function.");

            // Create the function if it does not already exist.
            using var zipMemoryStream = new MemoryStream(await File.ReadAllBytesAsync("SageMakerLambda.zip"));
            var createResult = await _lambdaClient.CreateFunctionAsync(
                new CreateFunctionRequest()
                {
                    FunctionName = lambdaFunctionName,
                    Runtime = Runtime.Dotnet6,
                    Description = "SageMaker example function.",
                    Code = new FunctionCode()
                    {
                        ZipFile = zipMemoryStream
                    },
                    Handler = handlerName,
                    Role = roleArn,
                    Timeout = 30
                });

            functionArn = createResult.FunctionArn;
        }

        Console.WriteLine($"\tLambda ready with ARN {functionArn}.");
        Console.WriteLine(new string('-', 80));
        return functionArn;
    }

    /// <summary>
    /// Create a role to be used by AWS Lambda. Does not create the role if it already exists.
    /// </summary>
    /// <returns>The role ARN.</returns>
    public static async Task<string> CreateLambdaRole()
    {
        Console.WriteLine(new string('-', 80));

        lambdaRolePolicies = new string[]{
            "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess",
            "arn:aws:iam::aws:policy/AmazonSQSFullAccess",
            "arn:aws:iam::aws:policy/service-role/" + "AmazonSageMakerGeospatialFullAccess",
            "arn:aws:iam::aws:policy/service-role/" + "AmazonSageMakerServiceCatalogProductsLambdaServiceRolePolicy",
            "arn:aws:iam::aws:policy/service-role/" + "AWSLambdaSQSQueueExecutionRole"
        };

        var roleArn = await GetRoleArnIfExists(lambdaRoleName);
        if (!string.IsNullOrEmpty(roleArn))
        {
            return roleArn;
        }

        Console.WriteLine("\tCreating a role to for AWS Lambda to use.");

        var assumeRolePolicy = "{" +
                               "\"Version\": \"2012-10-17\"," +
                               "\"Statement\": [{" +
                                    "\"Effect\": \"Allow\"," +
                                    "\"Principal\": {" +
                                        $"\"Service\": [" +
                                            "\"sagemaker.amazonaws.com\"," +
                                            "\"sagemaker-geospatial.amazonaws.com\"," +
                                            "\"lambda.amazonaws.com\"," +
                                            "\"s3.amazonaws.com\"" +
                                        "]" +
                                    "}," +
                                    "\"Action\": \"sts:AssumeRole\"" +
                               "}]" +
                            "}";

        var roleResult = await _iamClient!.CreateRoleAsync(
            new CreateRoleRequest()
            {
                AssumeRolePolicyDocument = assumeRolePolicy,
                Path = "/",
                RoleName = lambdaRoleName
            });
        foreach (var policy in lambdaRolePolicies)
        {
            await _iamClient.AttachRolePolicyAsync(
                new AttachRolePolicyRequest()
                {
                    PolicyArn = policy,
                    RoleName = lambdaRoleName
                });
        }

        // Allow time for the role to be ready.
        Thread.Sleep(10000);
        Console.WriteLine($"\tRole ready with ARN {roleResult.Role.Arn}.");
        Console.WriteLine(new string('-', 80));

        return roleResult.Role.Arn;
    }


    /// <summary>
    /// Create a role to be used by SageMaker.
    /// </summary>
    /// <returns>The role Amazon Resource Name (ARN).</returns>
    public static async Task<string> CreateSageMakerRole()
    {
        Console.WriteLine(new string('-', 80));

        sageMakerRolePolicies = new string[]{
            "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess",
            "arn:aws:iam::aws:policy/AmazonSageMakerGeospatialFullAccess",
        };

        var roleArn = await GetRoleArnIfExists(sageMakerRoleName);
        if (!string.IsNullOrEmpty(roleArn))
        {
            return roleArn;
        }

        Console.WriteLine("\tCreating a role to use with SageMaker.");

        var assumeRolePolicy = "{" +
                                        "\"Version\": \"2012-10-17\"," +
                                        "\"Statement\": [{" +
                                            "\"Effect\": \"Allow\"," +
                                            "\"Principal\": {" +
                                                $"\"Service\": [" +
                                                    "\"sagemaker.amazonaws.com\"," +
                                                    "\"sagemaker-geospatial.amazonaws.com\"," +
                                                    "\"lambda.amazonaws.com\"," +
                                                    "\"s3.amazonaws.com\"" +
                                                "]" +
                                            "}," +
                                            "\"Action\": \"sts:AssumeRole\"" +
                                        "}]" +
                                    "}";

        var roleResult = await _iamClient!.CreateRoleAsync(
            new CreateRoleRequest()
            {
                AssumeRolePolicyDocument = assumeRolePolicy,
                Path = "/",
                RoleName = sageMakerRoleName
            });

        foreach (var policy in sageMakerRolePolicies)
        {
            await _iamClient.AttachRolePolicyAsync(
                new AttachRolePolicyRequest()
                {
                    PolicyArn = policy,
                    RoleName = sageMakerRoleName
                });
        }

        // Allow time for the role to be ready.
        Thread.Sleep(10000);
        Console.WriteLine($"\tRole ready with ARN {roleResult.Role.Arn}.");
        Console.WriteLine(new string('-', 80));
        return roleResult.Role.Arn;
    }

    /// <summary>
    /// Set up the SQS queue to use with the pipeline.
    /// </summary>
    /// <param name="queueName">The name for the queue.</param>
    /// <returns>The URL for the queue.</returns>
    public static async Task<string> SetupQueue(string queueName)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Setting up queue {queueName}.");

        try
        {
            var queueInfo = await _sqsClient.GetQueueUrlAsync(new GetQueueUrlRequest()
            { QueueName = queueName });
            return queueInfo.QueueUrl;
        }
        catch (QueueDoesNotExistException)
        {
            var attrs = new Dictionary<string, string>
            {
                {
                    QueueAttributeName.DelaySeconds,
                    "5"
                },
                {
                    QueueAttributeName.ReceiveMessageWaitTimeSeconds,
                    "5"
                },
                {
                    QueueAttributeName.VisibilityTimeout,
                    "300"
                },
            };

            var request = new CreateQueueRequest
            {
                Attributes = attrs,
                QueueName = queueName,
            };

            var response = await _sqsClient.CreateQueueAsync(request);
            Thread.Sleep(10000);
            await ConnectLambda(response.QueueUrl);
            Console.WriteLine($"\tQueue ready with Url {response.QueueUrl}.");
            Console.WriteLine(new string('-', 80));
            return response.QueueUrl;
        }
    }

    /// <summary>
    /// Connect the queue to the Lambda function as an event source.
    /// </summary>
    /// <param name="queueUrl">The URL for the queue.</param>
    /// <returns>Async task.</returns>
    public static async Task ConnectLambda(string queueUrl)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Connecting the Lambda function and queue for the pipeline.");

        var queueAttributes = await _sqsClient.GetQueueAttributesAsync(
            new GetQueueAttributesRequest() { QueueUrl = queueUrl, AttributeNames = new List<string>() { "All" } });
        var queueArn = queueAttributes.QueueARN;

        var eventSource = await _lambdaClient.ListEventSourceMappingsAsync(
             new ListEventSourceMappingsRequest()
             {
                 FunctionName = lambdaFunctionName
             });

        if (!eventSource.EventSourceMappings.Any())
        {
            // Only add the event source mapping if it does not already exist.
            await _lambdaClient.CreateEventSourceMappingAsync(
                new CreateEventSourceMappingRequest()
                {
                    EventSourceArn = queueArn,
                    FunctionName = lambdaFunctionName,
                    Enabled = true
                });
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Set up the bucket to use for pipeline input and output.
    /// </summary>
    /// <param name="bucketName">The name for the bucket.</param>
    /// <returns>Async task.</returns>
    public static async Task SetupBucket(string bucketName)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Setting up bucket {bucketName}.");

        var bucketExists = await Amazon.S3.Util.AmazonS3Util.DoesS3BucketExistV2Async(_s3Client,
            bucketName);

        if (!bucketExists)
        {
            await _s3Client.PutBucketAsync(new PutBucketRequest()
            {
                BucketName = bucketName,
                BucketRegion = S3Region.USWest2
            });

            Thread.Sleep(5000);

            await _s3Client.PutObjectAsync(new PutObjectRequest()
            {
                BucketName = bucketName,
                Key = "samplefiles/latlongtest.csv",
                FilePath = "latlongtest.csv"
            });
        }

        Console.WriteLine($"\tBucket {bucketName} ready.");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Display some results from the output directory.
    /// </summary>
    /// <param name="bucketName">The name for the bucket.</param>
    /// <returns>Async task.</returns>
    public static async Task<string> GetOutputResults(string bucketName)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Getting output results {bucketName}.");
        string outputKey = "";
        Thread.Sleep(15000);
        var outputFiles = await _s3Client.ListObjectsAsync(
              new ListObjectsRequest()
              {
                  BucketName = bucketName,
                  Prefix = "outputfiles/"
              });

        if (outputFiles.S3Objects.Any())
        {
            var sampleOutput = outputFiles.S3Objects.OrderBy(s => s.LastModified).Last();
            Console.WriteLine($"\tOutput file: {sampleOutput.Key}");
            var outputSampleResponse = await _s3Client.GetObjectAsync(
                new GetObjectRequest()
                {
                    BucketName = bucketName,
                    Key = sampleOutput.Key
                });
            outputKey = sampleOutput.Key;
            StreamReader reader = new StreamReader(outputSampleResponse.ResponseStream);
            await reader.ReadLineAsync();
            Console.WriteLine("\tOutput file contents: \n");
            for (int i = 0; i < 10; i++)
            {
                if (!reader.EndOfStream)
                {
                    Console.WriteLine("\t" + await reader.ReadLineAsync());
                }
            }
        }

        Console.WriteLine(new string('-', 80));
        return outputKey;
    }

    /// <summary>
    /// Create a pipeline from the example pipeline JSON
    /// that includes the Lambda, callback, processing, and export jobs.
    /// </summary>
    /// <param name="roleArn">The ARN of the role for the pipeline.</param>
    /// <param name="functionArn">The ARN of the Lambda function for the pipeline.</param>
    /// <param name="pipelineName">The name for the pipeline.</param>
    /// <returns>The ARN of the pipeline.</returns>
    public static async Task<string> SetupPipeline(string roleArn, string functionArn, string pipelineName)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Setting up the pipeline.");

        var pipelineJson = await File.ReadAllTextAsync("GeoSpatialPipeline.json");

        // Add the correct function ARN instead of the placeholder.
        pipelineJson = pipelineJson.Replace("*FUNCTION_ARN*", functionArn);

        var pipelineArn = await _sageMakerWrapper.SetupPipeline(pipelineJson, roleArn, pipelineName,
            "sdk example pipeline", pipelineName);

        Console.WriteLine($"\tPipeline set up with ARN {pipelineArn}.");
        Console.WriteLine(new string('-', 80));

        return pipelineArn;
    }

    /// <summary>
    /// Start a pipeline run with job configurations.
    /// </summary>
    /// <param name="queueUrl">The URL for the queue used in the pipeline.</param>
    /// <param name="roleArn">The ARN of the role.</param>
    /// <param name="pipelineName">The name of the pipeline.</param>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <returns>The pipeline run ARN.</returns>
    public static async Task<string> ExecutePipeline(
        string queueUrl,
        string roleArn,
        string pipelineName,
        string bucketName)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Starting pipeline execution.");

        var input = $"s3://{bucketName}/samplefiles/latlongtest.csv";
        var output = $"s3://{bucketName}/outputfiles/";

        var executionARN =
            await _sageMakerWrapper.ExecutePipeline(queueUrl, input, output,
                pipelineName, roleArn);

        Console.WriteLine($"\tRun started with ARN {executionARN}.");
        Console.WriteLine(new string('-', 80));

        return executionARN;
    }

    /// <summary>
    /// Wait for a pipeline run to complete.
    /// </summary>
    /// <param name="executionArn">The pipeline run ARN.</param>
    /// <returns>Async task.</returns>
    public static async Task WaitForPipelineExecution(string executionArn)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Waiting for pipeline to finish.");

        PipelineExecutionStatus status;
        do
        {
            status = await _sageMakerWrapper.CheckPipelineExecutionStatus(executionArn);
            Thread.Sleep(30000);
            Console.WriteLine($"\tStatus is {status}.");
        } while (status == PipelineExecutionStatus.Executing);

        Console.WriteLine($"\tPipeline finished with status {status}.");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <param name="askUser">True to ask the user for cleanup.</param>
    /// <param name="queueUrl">The URL of the queue to clean up.</param>
    /// <param name="pipelineName">The name of the pipeline.</param>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> CleanupResources(
        bool askUser,
        string queueUrl,
        string pipelineName,
        string bucketName)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Clean up resources.");

        if (!askUser || GetYesNoResponse($"\tDelete pipeline {pipelineName}? (y/n)"))
        {
            Console.WriteLine($"\tDeleting pipeline.");
            // Delete the pipeline.
            await _sageMakerWrapper.DeletePipelineByName(pipelineName);
        }

        if (!string.IsNullOrEmpty(queueUrl) && (!askUser || GetYesNoResponse($"\tDelete queue {queueUrl}? (y/n)")))
        {
            Console.WriteLine($"\tDeleting queue.");
            // Delete the queue.
            await _sqsClient.DeleteQueueAsync(new DeleteQueueRequest(queueUrl));
        }

        if (!askUser || GetYesNoResponse($"\tDelete Amazon S3 bucket {bucketName}? (y/n)"))
        {
            Console.WriteLine($"\tDeleting bucket.");
            // Delete all objects in the bucket.
            var deleteList = await _s3Client.ListObjectsV2Async(new ListObjectsV2Request()
            {
                BucketName = bucketName
            });
            if (deleteList.KeyCount > 0)
            {
                await _s3Client.DeleteObjectsAsync(new DeleteObjectsRequest()
                {
                    BucketName = bucketName,
                    Objects = deleteList.S3Objects
                        .Select(o => new KeyVersion { Key = o.Key }).ToList()
                });
            }

            // Now delete the bucket.
            await _s3Client.DeleteBucketAsync(new DeleteBucketRequest()
            {
                BucketName = bucketName
            });
        }

        if (!askUser || GetYesNoResponse($"\tDelete lambda {lambdaFunctionName}? (y/n)"))
        {
            Console.WriteLine($"\tDeleting lambda function.");

            await _lambdaClient.DeleteFunctionAsync(new DeleteFunctionRequest()
            {
                FunctionName = lambdaFunctionName
            });
        }

        if (!askUser || GetYesNoResponse($"\tDelete role {lambdaRoleName}? (y/n)"))
        {
            Console.WriteLine($"\tDetaching policies and deleting role.");

            foreach (var policy in lambdaRolePolicies)
            {
                await _iamClient!.DetachRolePolicyAsync(new DetachRolePolicyRequest()
                {
                    RoleName = lambdaRoleName,
                    PolicyArn = policy
                });
            }

            await _iamClient!.DeleteRoleAsync(new DeleteRoleRequest()
            {
                RoleName = lambdaRoleName
            });
        }

        if (!askUser || GetYesNoResponse($"\tDelete role {sageMakerRoleName}? (y/n)"))
        {
            Console.WriteLine($"\tDetaching policies and deleting role.");

            foreach (var policy in sageMakerRolePolicies)
            {
                await _iamClient!.DetachRolePolicyAsync(new DetachRolePolicyRequest()
                {
                    RoleName = sageMakerRoleName,
                    PolicyArn = policy
                });
            }

            await _iamClient!.DeleteRoleAsync(new DeleteRoleRequest()
            {
                RoleName = sageMakerRoleName
            });
        }

        Console.WriteLine(new string('-', 80));
        return true;
    }

    /// <summary>
    /// Helper method to get a role's ARN if it already exists.
    /// </summary>
    /// <param name="roleName">The name of the AWS Identity and Access Management (IAM) Role to look for.</param>
    /// <returns>The role ARN if it exists, otherwise an empty string.</returns>
    private static async Task<string> GetRoleArnIfExists(string roleName)
    {
        Console.WriteLine($"Checking for role named {roleName}.");

        try
        {
            var existingRole = await _iamClient.GetRoleAsync(new GetRoleRequest()
            {
                RoleName = lambdaRoleName
            });
            return existingRole.Role.Arn;
        }
        catch (NoSuchEntityException)
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null &&
                       ynResponse.Equals("y",
                           StringComparison.InvariantCultureIgnoreCase);
        return response;
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreatePipeline](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/CreatePipeline)
  + [DeletePipeline](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/DeletePipeline)
  + [DescribePipelineExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/DescribePipelineExecution)
  + [StartPipelineExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/StartPipelineExecution)
  + [UpdatePipeline](https://docs.aws.amazon.com/goto/DotNetSDKV3/sagemaker-2017-07-24/UpdatePipeline)

# を使用した Secrets Manager の例 SDK for .NET
<a name="csharp_3_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_csharp_3_topic"></a>

次のコード例は、`GetSecretValue` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SecretsManager#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.SecretsManager;
    using Amazon.SecretsManager.Model;

    /// <summary>
    /// This example uses the Amazon Web Service Secrets Manager to retrieve
    /// the secret value for the provided secret name.
    /// </summary>
    public class GetSecretValue
    {
        /// <summary>
        /// The main method initializes the necessary values and then calls
        /// the GetSecretAsync and DecodeString methods to get the decoded
        /// secret value for the secret named in secretName.
        /// </summary>
        public static async Task Main()
        {
            string secretName = "<<{{MySecretName}}>>";
            string secret;

            IAmazonSecretsManager client = new AmazonSecretsManagerClient();

            var response = await GetSecretAsync(client, secretName);

            if (response is not null)
            {
                secret = DecodeString(response);

                if (!string.IsNullOrEmpty(secret))
                {
                    Console.WriteLine($"The decoded secret value is: {secret}.");
                }
                else
                {
                    Console.WriteLine("No secret value was returned.");
                }
            }
        }

        /// <summary>
        /// Retrieves the secret value given the name of the secret to
        /// retrieve.
        /// </summary>
        /// <param name="client">The client object used to retrieve the secret
        /// value for the given secret name.</param>
        /// <param name="secretName">The name of the secret value to retrieve.</param>
        /// <returns>The GetSecretValueReponse object returned by
        /// GetSecretValueAsync.</returns>
        public static async Task<GetSecretValueResponse> GetSecretAsync(
            IAmazonSecretsManager client,
            string secretName)
        {
            GetSecretValueRequest request = new GetSecretValueRequest()
            {
                SecretId = secretName,
                VersionStage = "AWSCURRENT", // VersionStage defaults to AWSCURRENT if unspecified.
            };

            GetSecretValueResponse response = null;

            // For the sake of simplicity, this example handles only the most
            // general SecretsManager exception.
            try
            {
                response = await client.GetSecretValueAsync(request);
            }
            catch (AmazonSecretsManagerException e)
            {
                Console.WriteLine($"Error: {e.Message}");
            }

            return response;
        }

        /// <summary>
        /// Decodes the secret returned by the call to GetSecretValueAsync and
        /// returns it to the calling program.
        /// </summary>
        /// <param name="response">A GetSecretValueResponse object containing
        /// the requested secret value returned by GetSecretValueAsync.</param>
        /// <returns>A string representing the decoded secret value.</returns>
        public static string DecodeString(GetSecretValueResponse response)
        {
            // Decrypts secret using the associated AWS Key Management Service
            // Customer Master Key (CMK.) Depending on whether the secret is a
            // string or binary value, one of these fields will be populated.
            if (response.SecretString is not null)
            {
                var secret = response.SecretString;
                return secret;
            }
            else if (response.SecretBinary is not null)
            {
                var memoryStream = response.SecretBinary;
                StreamReader reader = new StreamReader(memoryStream);
                string decodedBinarySecret = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(reader.ReadToEnd()));
                return decodedBinarySecret;
            }
            else
            {
                return string.Empty;
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetSecretValue](https://docs.aws.amazon.com/goto/DotNetSDKV3/secretsmanager-2017-10-17/GetSecretValue)」を参照してください。

# を使用した Amazon SES の例 SDK for .NET
<a name="csharp_3_ses_code_examples"></a>

次のコード例は、Amazon SES AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateTemplate`
<a name="ses_CreateTemplate_csharp_3_topic"></a>

次のコード例は、`CreateTemplate` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an email template.
    /// </summary>
    /// <param name="name">Name of the template.</param>
    /// <param name="subject">Email subject.</param>
    /// <param name="text">Email body text.</param>
    /// <param name="html">Email HTML body text.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> CreateEmailTemplateAsync(string name, string subject, string text,
        string html)
    {
        var success = false;
        try
        {
            var response = await _amazonSimpleEmailService.CreateTemplateAsync(
                new CreateTemplateRequest
                {
                    Template = new Template
                    {
                        TemplateName = name,
                        SubjectPart = subject,
                        TextPart = text,
                        HtmlPart = html
                    }
                });
            success = response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (Exception ex)
        {
            Console.WriteLine("CreateEmailTemplateAsync failed with exception: " + ex.Message);
        }

        return success;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/CreateTemplate)」を参照してください。

### `DeleteIdentity`
<a name="ses_DeleteIdentity_csharp_3_topic"></a>

次のコード例は、`DeleteIdentity` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an email identity.
    /// </summary>
    /// <param name="identityEmail">The identity email to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteIdentityAsync(string identityEmail)
    {
        var success = false;
        try
        {
            var response = await _amazonSimpleEmailService.DeleteIdentityAsync(
                new DeleteIdentityRequest
                {
                    Identity = identityEmail
                });
            success = response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (Exception ex)
        {
            Console.WriteLine("DeleteIdentityAsync failed with exception: " + ex.Message);
        }

        return success;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteIdentity](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/DeleteIdentity)」を参照してください。

### `DeleteTemplate`
<a name="ses_DeleteTemplate_csharp_3_topic"></a>

次のコード例は、`DeleteTemplate` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an email template.
    /// </summary>
    /// <param name="templateName">Name of the template.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteEmailTemplateAsync(string templateName)
    {
        var success = false;
        try
        {
            var response = await _amazonSimpleEmailService.DeleteTemplateAsync(
                new DeleteTemplateRequest
                {
                    TemplateName = templateName
                });
            success = response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (Exception ex)
        {
            Console.WriteLine("DeleteEmailTemplateAsync failed with exception: " + ex.Message);
        }

        return success;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*のの「[DeleteTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/DeleteTemplate)」を参照してください。

### `GetIdentityVerificationAttributes`
<a name="ses_GetIdentityVerificationAttributes_csharp_3_topic"></a>

次のコード例は、`GetIdentityVerificationAttributes` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get identity verification status for an email.
    /// </summary>
    /// <returns>The verification status of the email.</returns>
    public async Task<VerificationStatus> GetIdentityStatusAsync(string email)
    {
        var result = VerificationStatus.TemporaryFailure;
        try
        {
            var response =
                await _amazonSimpleEmailService.GetIdentityVerificationAttributesAsync(
                    new GetIdentityVerificationAttributesRequest
                    {
                        Identities = new List<string> { email }
                    });

            if (response.VerificationAttributes.ContainsKey(email))
                result = response.VerificationAttributes[email].VerificationStatus;
        }
        catch (Exception ex)
        {
            Console.WriteLine("GetIdentityStatusAsync failed with exception: " + ex.Message);
        }

        return result;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*.」の「[GetIdentityVerificationAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/GetIdentityVerificationAttributes)」を参照してください。

### `GetSendQuota`
<a name="ses_GetSendQuota_csharp_3_topic"></a>

次のコード例は、`GetSendQuota` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information on the current account's send quota.
    /// </summary>
    /// <returns>The send quota response data.</returns>
    public async Task<GetSendQuotaResponse> GetSendQuotaAsync()
    {
        var result = new GetSendQuotaResponse();
        try
        {
            var response = await _amazonSimpleEmailService.GetSendQuotaAsync(
                new GetSendQuotaRequest());
            result = response;
        }
        catch (Exception ex)
        {
            Console.WriteLine("GetSendQuotaAsync failed with exception: " + ex.Message);
        }

        return result;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetSendQuota](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/GetSendQuota)」を参照してください。

### `ListIdentities`
<a name="ses_ListIdentities_csharp_3_topic"></a>

次のコード例は、`ListIdentities` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the identities of a specified type for the current account.
    /// </summary>
    /// <param name="identityType">IdentityType to list.</param>
    /// <returns>The list of identities.</returns>
    public async Task<List<string>> ListIdentitiesAsync(IdentityType identityType)
    {
        var result = new List<string>();
        try
        {
            var response = await _amazonSimpleEmailService.ListIdentitiesAsync(
                new ListIdentitiesRequest
                {
                    IdentityType = identityType
                });
            result = response.Identities;
        }
        catch (Exception ex)
        {
            Console.WriteLine("ListIdentitiesAsync failed with exception: " + ex.Message);
        }

        return result;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[ListIdentities](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/ListIdentities)」を参照してください。

### `ListTemplates`
<a name="ses_ListTemplates_csharp_3_topic"></a>

次のコード例は、`ListTemplates` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List email templates for the current account.
    /// </summary>
    /// <returns>A list of template metadata.</returns>
    public async Task<List<TemplateMetadata>> ListEmailTemplatesAsync()
    {
        var result = new List<TemplateMetadata>();
        try
        {
            var response = await _amazonSimpleEmailService.ListTemplatesAsync(
                new ListTemplatesRequest());
            result = response.TemplatesMetadata;
        }
        catch (Exception ex)
        {
            Console.WriteLine("ListEmailTemplatesAsync failed with exception: " + ex.Message);
        }

        return result;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListTemplates](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/ListTemplates)」を参照してください。

### `SendEmail`
<a name="ses_SendEmail_csharp_3_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    ///  Send an email by using Amazon SES.
    /// </summary>
    /// <param name="toAddresses">List of recipients.</param>
    /// <param name="ccAddresses">List of cc recipients.</param>
    /// <param name="bccAddresses">List of bcc recipients.</param>
    /// <param name="bodyHtml">Body of the email in HTML.</param>
    /// <param name="bodyText">Body of the email in plain text.</param>
    /// <param name="subject">Subject line of the email.</param>
    /// <param name="senderAddress">From address.</param>
    /// <returns>The messageId of the email.</returns>
    public async Task<string> SendEmailAsync(List<string> toAddresses,
        List<string> ccAddresses, List<string> bccAddresses,
        string bodyHtml, string bodyText, string subject, string senderAddress)
    {
        var messageId = "";
        try
        {
            var response = await _amazonSimpleEmailService.SendEmailAsync(
                new SendEmailRequest
                {
                    Destination = new Destination
                    {
                        BccAddresses = bccAddresses,
                        CcAddresses = ccAddresses,
                        ToAddresses = toAddresses
                    },
                    Message = new Message
                    {
                        Body = new Body
                        {
                            Html = new Content
                            {
                                Charset = "UTF-8",
                                Data = bodyHtml
                            },
                            Text = new Content
                            {
                                Charset = "UTF-8",
                                Data = bodyText
                            }
                        },
                        Subject = new Content
                        {
                            Charset = "UTF-8",
                            Data = subject
                        }
                    },
                    Source = senderAddress
                });
            messageId = response.MessageId;
        }
        catch (Exception ex)
        {
            Console.WriteLine("SendEmailAsync failed with exception: " + ex.Message);
        }

        return messageId;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[SendEmail](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/SendEmail)」を参照してください。

### `SendTemplatedEmail`
<a name="ses_SendTemplatedEmail_csharp_3_topic"></a>

次のコード例は、`SendTemplatedEmail` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Send an email using a template.
    /// </summary>
    /// <param name="sender">Address of the sender.</param>
    /// <param name="recipients">Addresses of the recipients.</param>
    /// <param name="templateName">Name of the email template.</param>
    /// <param name="templateDataObject">Data for the email template.</param>
    /// <returns>The messageId of the email.</returns>
    public async Task<string> SendTemplateEmailAsync(string sender, List<string> recipients,
        string templateName, object templateDataObject)
    {
        var messageId = "";
        try
        {
            // Template data should be serialized JSON from either a class or a dynamic object.
            var templateData = JsonSerializer.Serialize(templateDataObject);

            var response = await _amazonSimpleEmailService.SendTemplatedEmailAsync(
                new SendTemplatedEmailRequest
                {
                    Source = sender,
                    Destination = new Destination
                    {
                        ToAddresses = recipients
                    },
                    Template = templateName,
                    TemplateData = templateData
                });
            messageId = response.MessageId;
        }
        catch (Exception ex)
        {
            Console.WriteLine("SendTemplateEmailAsync failed with exception: " + ex.Message);
        }

        return messageId;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[SendTemplatedEmail](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/SendTemplatedEmail)」を参照してください。

### `VerifyEmailIdentity`
<a name="ses_VerifyEmailIdentity_csharp_3_topic"></a>

次のコード例は、`VerifyEmailIdentity` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SES#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Starts verification of an email identity. This request sends an email
    /// from Amazon SES to the specified email address. To complete
    /// verification, follow the instructions in the email.
    /// </summary>
    /// <param name="recipientEmailAddress">Email address to verify.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> VerifyEmailIdentityAsync(string recipientEmailAddress)
    {
        var success = false;
        try
        {
            var response = await _amazonSimpleEmailService.VerifyEmailIdentityAsync(
                new VerifyEmailIdentityRequest
                {
                    EmailAddress = recipientEmailAddress
                });

            success = response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (Exception ex)
        {
            Console.WriteLine("VerifyEmailIdentityAsync failed with exception: " + ex.Message);
        }

        return success;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[VerifyEmailIdentity](https://docs.aws.amazon.com/goto/DotNetSDKV3/email-2010-12-01/VerifyEmailIdentity)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_csharp_3_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 Amazon DynamoDB .NET API を使用して、DynamoDB 作業データを追跡する動的ウェブアプリケーションを作成する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/DynamoDbItemTracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_csharp_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 を使用して AWS SDK for .NET 、Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful .NET バックエンドと対話します。  
+ React ウェブアプリケーションを AWS サービスに統合します。
+ Aurora テーブルの項目を一覧表示、更新、削除します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/AuroraItemTracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_csharp_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for .NET**  
 Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内から、Amazon Rekognition を使用してカテゴリ別にオブジェクトを識別するアプリケーションを、Amazon Rekognition .NET API を使用して作成する方法を示します。アプリケーションは、Amazon Simple Email Service (Amazon SES) を使用して、結果を記載した E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAnalyzerApp) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

# を使用した Amazon SES API v2 の例 SDK for .NET
<a name="csharp_3_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateContact`
<a name="sesv2_CreateContact_csharp_3_topic"></a>

次のコード例は、`CreateContact` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates a contact and adds it to the specified contact list.
    /// </summary>
    /// <param name="emailAddress">The email address of the contact.</param>
    /// <param name="contactListName">The name of the contact list.</param>
    /// <returns>The response from the CreateContact operation.</returns>
    public async Task<bool> CreateContactAsync(string emailAddress, string contactListName)
    {
        var request = new CreateContactRequest
        {
            EmailAddress = emailAddress,
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.CreateContactAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Contact with email address {emailAddress} already exists in the contact list {contactListName}.");
            Console.WriteLine(ex.Message);
            return true;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The contact list {contactListName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the contact: {ex.Message}");
        }
        return false;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateContact](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateContact)」を参照してください。

### `CreateContactList`
<a name="sesv2_CreateContactList_csharp_3_topic"></a>

次のコード例は、`CreateContactList` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates a contact list with the specified name.
    /// </summary>
    /// <param name="contactListName">The name of the contact list.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> CreateContactListAsync(string contactListName)
    {
        var request = new CreateContactListRequest
        {
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.CreateContactListAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Contact list with name {contactListName} already exists.");
            Console.WriteLine(ex.Message);
            return true;
        }
        catch (LimitExceededException ex)
        {
            Console.WriteLine("The limit for contact lists has been exceeded.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the contact list: {ex.Message}");
        }
        return false;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateContactList](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateContactList)」を参照してください。

### `CreateEmailIdentity`
<a name="sesv2_CreateEmailIdentity_csharp_3_topic"></a>

次のコード例は、`CreateEmailIdentity` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates an email identity (email address or domain) and starts the verification process.
    /// </summary>
    /// <param name="emailIdentity">The email address or domain to create and verify.</param>
    /// <returns>The response from the CreateEmailIdentity operation.</returns>
    public async Task<CreateEmailIdentityResponse> CreateEmailIdentityAsync(string emailIdentity)
    {
        var request = new CreateEmailIdentityRequest
        {
            EmailIdentity = emailIdentity
        };

        try
        {
            var response = await _sesClient.CreateEmailIdentityAsync(request);
            return response;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Email identity {emailIdentity} already exists.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (ConcurrentModificationException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} is being modified by another operation or thread.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (LimitExceededException ex)
        {
            Console.WriteLine("The limit for email identities has been exceeded.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} does not exist.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the email identity: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateEmailIdentity](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateEmailIdentity)」を参照してください。

### `CreateEmailTemplate`
<a name="sesv2_CreateEmailTemplate_csharp_3_topic"></a>

次のコード例は、`CreateEmailTemplate` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates an email template with the specified content.
    /// </summary>
    /// <param name="templateName">The name of the email template.</param>
    /// <param name="subject">The subject of the email template.</param>
    /// <param name="htmlContent">The HTML content of the email template.</param>
    /// <param name="textContent">The text content of the email template.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> CreateEmailTemplateAsync(string templateName, string subject, string htmlContent, string textContent)
    {
        var request = new CreateEmailTemplateRequest
        {
            TemplateName = templateName,
            TemplateContent = new EmailTemplateContent
            {
                Subject = subject,
                Html = htmlContent,
                Text = textContent
            }
        };

        try
        {
            var response = await _sesClient.CreateEmailTemplateAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Email template with name {templateName} already exists.");
            Console.WriteLine(ex.Message);
        }
        catch (LimitExceededException ex)
        {
            Console.WriteLine("The limit for email templates has been exceeded.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the email template: {ex.Message}");
        }

        return false;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateEmailTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateEmailTemplate)」を参照してください。

### `DeleteContactList`
<a name="sesv2_DeleteContactList_csharp_3_topic"></a>

次のコード例は、`DeleteContactList` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes a contact list and all contacts within it.
    /// </summary>
    /// <param name="contactListName">The name of the contact list to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteContactListAsync(string contactListName)
    {
        var request = new DeleteContactListRequest
        {
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.DeleteContactListAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (ConcurrentModificationException ex)
        {
            Console.WriteLine($"The contact list {contactListName} is being modified by another operation or thread.");
            Console.WriteLine(ex.Message);
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The contact list {contactListName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting the contact list: {ex.Message}");
        }

        return false;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteContactList](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/DeleteContactList)」を参照してください。

### `DeleteEmailIdentity`
<a name="sesv2_DeleteEmailIdentity_csharp_3_topic"></a>

次のコード例は、`DeleteEmailIdentity` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes an email identity (email address or domain).
    /// </summary>
    /// <param name="emailIdentity">The email address or domain to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteEmailIdentityAsync(string emailIdentity)
    {
        var request = new DeleteEmailIdentityRequest
        {
            EmailIdentity = emailIdentity
        };

        try
        {
            var response = await _sesClient.DeleteEmailIdentityAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (ConcurrentModificationException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} is being modified by another operation or thread.");
            Console.WriteLine(ex.Message);
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting the email identity: {ex.Message}");
        }

        return false;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteEmailIdentity](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/DeleteEmailIdentity)」を参照してください。

### `DeleteEmailTemplate`
<a name="sesv2_DeleteEmailTemplate_csharp_3_topic"></a>

次のコード例は、`DeleteEmailTemplate` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes an email template.
    /// </summary>
    /// <param name="templateName">The name of the email template to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteEmailTemplateAsync(string templateName)
    {
        var request = new DeleteEmailTemplateRequest
        {
            TemplateName = templateName
        };

        try
        {
            var response = await _sesClient.DeleteEmailTemplateAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The email template {templateName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting the email template: {ex.Message}");
        }

        return false;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteEmailTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/DeleteEmailTemplate)」を参照してください。

### `ListContacts`
<a name="sesv2_ListContacts_csharp_3_topic"></a>

次のコード例は、`ListContacts` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Lists the contacts in the specified contact list.
    /// </summary>
    /// <param name="contactListName">The name of the contact list.</param>
    /// <returns>The list of contacts response from the ListContacts operation.</returns>
    public async Task<List<Contact>> ListContactsAsync(string contactListName)
    {
        var request = new ListContactsRequest
        {
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.ListContactsAsync(request);
            return response.Contacts;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The contact list {contactListName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while listing the contacts: {ex.Message}");
        }

        return new List<Contact>();
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListContacts](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/ListContacts)」を参照してください。

### `SendEmail`
<a name="sesv2_SendEmail_csharp_3_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Sends an email with the specified content and options.
    /// </summary>
    /// <param name="fromEmailAddress">The email address to send the email from.</param>
    /// <param name="toEmailAddresses">The email addresses to send the email to.</param>
    /// <param name="subject">The subject of the email.</param>
    /// <param name="htmlContent">The HTML content of the email.</param>
    /// <param name="textContent">The text content of the email.</param>
    /// <param name="templateName">The name of the email template to use (optional).</param>
    /// <param name="templateData">The data to replace placeholders in the email template (optional).</param>
    /// <param name="contactListName">The name of the contact list for unsubscribe functionality (optional).</param>
    /// <returns>The MessageId response from the SendEmail operation.</returns>
    public async Task<string> SendEmailAsync(string fromEmailAddress, List<string> toEmailAddresses, string? subject,
        string? htmlContent, string? textContent, string? templateName = null, string? templateData = null, string? contactListName = null)
    {
        var request = new SendEmailRequest
        {
            FromEmailAddress = fromEmailAddress
        };

        if (toEmailAddresses.Any())
        {
            request.Destination = new Destination { ToAddresses = toEmailAddresses };
        }

        if (!string.IsNullOrEmpty(templateName))
        {
            request.Content = new EmailContent()
            {
                Template = new Template
                {
                    TemplateName = templateName,
                    TemplateData = templateData
                }
            };
        }
        else
        {
            request.Content = new EmailContent
            {
                Simple = new Message
                {
                    Subject = new Content { Data = subject },
                    Body = new Body
                    {
                        Html = new Content { Data = htmlContent },
                        Text = new Content { Data = textContent }
                    }
                }
            };
        }

        if (!string.IsNullOrEmpty(contactListName))
        {
            request.ListManagementOptions = new ListManagementOptions
            {
                ContactListName = contactListName
            };
        }

        try
        {
            var response = await _sesClient.SendEmailAsync(request);
            return response.MessageId;
        }
        catch (AccountSuspendedException ex)
        {
            Console.WriteLine("The account's ability to send email has been permanently restricted.");
            Console.WriteLine(ex.Message);
        }
        catch (MailFromDomainNotVerifiedException ex)
        {
            Console.WriteLine("The sending domain is not verified.");
            Console.WriteLine(ex.Message);
        }
        catch (MessageRejectedException ex)
        {
            Console.WriteLine("The message content is invalid.");
            Console.WriteLine(ex.Message);
        }
        catch (SendingPausedException ex)
        {
            Console.WriteLine("The account's ability to send email is currently paused.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while sending the email: {ex.Message}");
        }

        return string.Empty;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[SendEmail](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/SendEmail)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ニュースレターのシナリオ
<a name="sesv2_NewsletterWorkflow_csharp_3_topic"></a>

以下のコード例は、Amazon SES API v2 のニュースレターのシナリオを実行する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SESv2#code-examples)での設定と実行の方法を確認してください。
シナリオを実行します。  

```
using System.Diagnostics;
using System.Text.RegularExpressions;
using Amazon.SimpleEmailV2;
using Amazon.SimpleEmailV2.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;

namespace Sesv2Scenario;

public static class NewsletterWorkflow
{
    /*
      This scenario demonstrates how to use the Amazon Simple Email Service (SES) v2 to send a coupon newsletter to a list of subscribers.
      The scenario performs the following tasks:

      1. Prepare the application:
         - Create a verified email identity for sending and replying to emails.
         - Create a contact list to store the subscribers' email addresses.
         - Create an email template for the coupon newsletter.

      2. Gather subscriber email addresses:
         - Prompt the user for a base email address.
         - Create 3 variants of the email address using subaddress extensions (e.g., user+ses-weekly-newsletter-1@example.com).
         - Add each variant as a contact to the contact list.
         - Send a welcome email to each new contact.

      3. Send the coupon newsletter:
         - Retrieve the list of contacts from the contact list.
         - Send the coupon newsletter using the email template to each contact.

      4. Monitor and review:
         - Provide instructions for the user to review the sending activity and metrics in the AWS console.

      5. Clean up resources:
         - Delete the contact list (which also deletes all contacts within it).
         - Delete the email template.
         - Optionally delete the verified email identity.

    */

    public static SESv2Wrapper _sesv2Wrapper;
    public static string? _baseEmailAddress = null;
    public static string? _verifiedEmail = null;
    private static string _contactListName = "weekly-coupons-newsletter";
    private static string _templateName = "weekly-coupons";
    private static string _subject = "Weekly Coupons Newsletter";
    private static string _htmlContentFile = "coupon-newsletter.html";
    private static string _textContentFile = "coupon-newsletter.txt";
    private static string _htmlWelcomeFile = "welcome.html";
    private static string _textWelcomeFile = "welcome.txt";
    private static string _couponsDataFile = "sample_coupons.json";

    // Relative location of the resources folder.
    private static string _resourcesFilePathLocation = "../../../../resources/";

    public static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonSimpleEmailServiceV2>()
                    .AddTransient<SESv2Wrapper>()
            )
            .Build();

        ServicesSetup(host);

        try
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Welcome to the Amazon SES v2 Coupon Newsletter Scenario.");
            Console.WriteLine("This scenario demonstrates how to use the Amazon Simple Email Service (SES) v2 " +
                              "\r\nto send a coupon newsletter to a list of subscribers.");

            // Prepare the application.
            var emailIdentity = await PrepareApplication();

            // Gather subscriber email addresses.
            await GatherSubscriberEmailAddresses(emailIdentity);

            // Send the coupon newsletter.
            await SendCouponNewsletter(emailIdentity);

            // Monitor and review.
            MonitorAndReview(true);

            // Clean up resources.
            await Cleanup(emailIdentity, true);

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("Amazon SES v2 Coupon Newsletter scenario is complete.");
            Console.WriteLine(new string('-', 80));
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        _sesv2Wrapper = host.Services.GetRequiredService<SESv2Wrapper>();
    }

    /// <summary>
    /// Set up the resources for the scenario.
    /// </summary>
    /// <returns>The email address of the verified identity.</returns>
    public static async Task<string?> PrepareApplication()
    {
        var htmlContent = await File.ReadAllTextAsync(_resourcesFilePathLocation + _htmlContentFile);
        var textContent = await File.ReadAllTextAsync(_resourcesFilePathLocation + _textContentFile);

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("1. In this step, we will prepare the application:" +
                          "\r\n  - Create a verified email identity for sending and replying to emails." +
                          "\r\n  - Create a contact list to store the subscribers' email addresses." +
                          "\r\n  - Create an email template for the coupon newsletter.\r\n");

        // Prompt the user for a verified email address.
        while (!IsEmail(_verifiedEmail))
        {
            Console.Write("Enter a verified email address or an email to verify: ");
            _verifiedEmail = Console.ReadLine();
        }

        try
        {
            // Create an email identity and start the verification process.
            await _sesv2Wrapper.CreateEmailIdentityAsync(_verifiedEmail);
            Console.WriteLine($"Identity {_verifiedEmail} created.");
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine($"Identity {_verifiedEmail} already exists.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error creating email identity: {ex.Message}");
        }

        // Create a contact list.
        try
        {
            await _sesv2Wrapper.CreateContactListAsync(_contactListName);
            Console.WriteLine($"Contact list {_contactListName} created.");
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine($"Contact list {_contactListName} already exists.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error creating contact list: {ex.Message}");
        }

        // Create an email template.
        try
        {
            await _sesv2Wrapper.CreateEmailTemplateAsync(_templateName, _subject, htmlContent, textContent);
            Console.WriteLine($"Email template {_templateName} created.");
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine($"Email template {_templateName} already exists.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error creating email template: {ex.Message}");
        }

        return _verifiedEmail;
    }

    /// <summary>
    /// Generate subscriber addresses and send welcome emails.
    /// </summary>
    /// <param name="fromEmailAddress">The verified email address from PrepareApplication.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> GatherSubscriberEmailAddresses(string fromEmailAddress)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("2. In Step 2, we will gather subscriber email addresses:" +
                          "\r\n  - Prompt the user for a base email address." +
                          "\r\n  - Create 3 variants of the email address using subaddress extensions (e.g., user+ses-weekly-newsletter-1@example.com)." +
                          "\r\n  - Add each variant as a contact to the contact list." +
                          "\r\n  - Send a welcome email to each new contact.\r\n");

        // Prompt the user for a base email address.
        while (!IsEmail(_baseEmailAddress))
        {
            Console.Write("Enter a base email address (e.g., user@example.com): ");
            _baseEmailAddress = Console.ReadLine();
        }

        // Create 3 variants of the email address using +ses-weekly-newsletter-1, +ses-weekly-newsletter-2, etc.
        var baseEmailAddressParts = _baseEmailAddress!.Split("@");
        for (int i = 1; i <= 3; i++)
        {
            string emailAddress = $"{baseEmailAddressParts[0]}+ses-weekly-newsletter-{i}@{baseEmailAddressParts[1]}";

            try
            {
                // Create a contact with the email address in the contact list.
                await _sesv2Wrapper.CreateContactAsync(emailAddress, _contactListName);
                Console.WriteLine($"Contact {emailAddress} added to the {_contactListName} contact list.");
            }
            catch (AlreadyExistsException)
            {
                Console.WriteLine($"Contact {emailAddress} already exists in the {_contactListName} contact list.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error creating contact {emailAddress}: {ex.Message}");
                return false;
            }

            // Send a welcome email to the new contact.
            try
            {
                string subject = "Welcome to the Weekly Coupons Newsletter";
                string htmlContent = await File.ReadAllTextAsync(_resourcesFilePathLocation + _htmlWelcomeFile);
                string textContent = await File.ReadAllTextAsync(_resourcesFilePathLocation + _textWelcomeFile);

                await _sesv2Wrapper.SendEmailAsync(fromEmailAddress, new List<string> { emailAddress }, subject, htmlContent, textContent);
                Console.WriteLine($"Welcome email sent to {emailAddress}.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending welcome email to {emailAddress}: {ex.Message}");
                return false;
            }

            // Wait 2 seconds before sending the next email (if the account is in the SES Sandbox).
            await Task.Delay(2000);
        }

        return true;
    }

    /// <summary>
    ///  Send the coupon newsletter to the subscribers in the contact list.
    /// </summary>
    /// <param name="fromEmailAddress">The verified email address from PrepareApplication.</param>
    /// <returns>True if successful.</returns>
    public static async Task<bool> SendCouponNewsletter(string fromEmailAddress)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("3. In this step, we will send the coupon newsletter:" +
                          "\r\n  - Retrieve the list of contacts from the contact list." +
                          "\r\n  - Send the coupon newsletter using the email template to each contact.\r\n");


        // Retrieve the list of contacts from the contact list.
        var contacts = await _sesv2Wrapper.ListContactsAsync(_contactListName);
        if (!contacts.Any())
        {
            Console.WriteLine($"No contacts found in the {_contactListName} contact list.");
            return false;
        }

        // Load the coupon data from the sample_coupons.json file.
        string couponsData = await File.ReadAllTextAsync(_resourcesFilePathLocation + _couponsDataFile);

        // Send the coupon newsletter to each contact using the email template.
        try
        {
            foreach (var contact in contacts)
            {
                // To use the Contact List for list management, send to only one address at a time.
                await _sesv2Wrapper.SendEmailAsync(fromEmailAddress,
                    new List<string> { contact.EmailAddress },
                    null, null, null, _templateName, couponsData, _contactListName);
            }

            Console.WriteLine($"Coupon newsletter sent to contact list {_contactListName}.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error sending coupon newsletter to contact list {_contactListName}: {ex.Message}");
            return false;
        }

        return true;
    }

    /// <summary>
    /// Provide instructions for monitoring sending activity and metrics.
    /// </summary>
    /// <param name="interactive">True to run in interactive mode.</param>
    /// <returns>True if successful.</returns>
    public static bool MonitorAndReview(bool interactive)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("4. In step 4, we will monitor and review:" +
                          "\r\n  - Provide instructions for the user to review the sending activity and metrics in the AWS console.\r\n");

        Console.WriteLine("Review your sending activity using the SES Homepage in the AWS console.");
        Console.WriteLine("Press Enter to open the SES Homepage in your default browser...");
        if (interactive)
        {
            Console.ReadLine();
            try
            {
                // Open the SES Homepage in the default browser.
                Process.Start(new ProcessStartInfo
                {
                    FileName = "https://console.aws.amazon.com/ses/home",
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error opening the SES Homepage: {ex.Message}");
                return false;
            }
        }

        Console.WriteLine("Review the sending activity and email metrics, then press Enter to continue...");
        if (interactive)
            Console.ReadLine();
        return true;
    }

    /// <summary>
    /// Clean up the resources used in the scenario.
    /// </summary>
    /// <param name="verifiedEmailAddress">The verified email address from PrepareApplication.</param>
    /// <param name="interactive">True if interactive.</param>
    /// <returns>Async task.</returns>
    public static async Task<bool> Cleanup(string verifiedEmailAddress, bool interactive)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("5. Finally, we clean up resources:" +
                          "\r\n  - Delete the contact list (which also deletes all contacts within it)." +
                          "\r\n  - Delete the email template." +
                          "\r\n  - Optionally delete the verified email identity.\r\n");

        Console.WriteLine("Cleaning up resources...");

        // Delete the contact list (this also deletes all contacts in the list).
        try
        {
            await _sesv2Wrapper.DeleteContactListAsync(_contactListName);
            Console.WriteLine($"Contact list {_contactListName} deleted.");
        }
        catch (NotFoundException)
        {
            Console.WriteLine($"Contact list {_contactListName} not found.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error deleting contact list {_contactListName}: {ex.Message}");
            return false;
        }

        // Delete the email template.
        try
        {
            await _sesv2Wrapper.DeleteEmailTemplateAsync(_templateName);
            Console.WriteLine($"Email template {_templateName} deleted.");
        }
        catch (NotFoundException)
        {
            Console.WriteLine($"Email template {_templateName} not found.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error deleting email template {_templateName}: {ex.Message}");
            return false;
        }

        // Ask the user if they want to delete the email identity.
        var deleteIdentity = !interactive ||
            GetYesNoResponse(
                $"Do you want to delete the email identity {verifiedEmailAddress}? (y/n) ");
        if (deleteIdentity)
        {
            try
            {
                await _sesv2Wrapper.DeleteEmailIdentityAsync(verifiedEmailAddress);
                Console.WriteLine($"Email identity {verifiedEmailAddress} deleted.");
            }
            catch (NotFoundException)
            {
                Console.WriteLine(
                    $"Email identity {verifiedEmailAddress} not found.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(
                    $"Error deleting email identity {verifiedEmailAddress}: {ex.Message}");
                return false;
            }
        }
        else
        {
            Console.WriteLine(
                $"Skipping deletion of email identity {verifiedEmailAddress}.");
        }

        return true;
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase);
        return response;
    }

    /// <summary>
    /// Simple check to verify a string is an email address.
    /// </summary>
    /// <param name="email">The string to verify.</param>
    /// <returns>True if a valid email.</returns>
    private static bool IsEmail(string? email)
    {
        if (string.IsNullOrEmpty(email))
            return false;
        return Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase);
    }
}
```
サービスオペレーション用のラッパー  

```
using System.Net;
using Amazon.SimpleEmailV2;
using Amazon.SimpleEmailV2.Model;

namespace Sesv2Scenario;

/// <summary>
/// Wrapper class for Amazon Simple Email Service (SES) v2 operations.
/// </summary>
public class SESv2Wrapper
{

    private readonly IAmazonSimpleEmailServiceV2 _sesClient;

    /// <summary>
    /// Constructor for the SESv2Wrapper.
    /// </summary>
    /// <param name="sesClient">The injected SES v2 client.</param>
    public SESv2Wrapper(IAmazonSimpleEmailServiceV2 sesClient)
    {
        _sesClient = sesClient;
    }

    /// <summary>
    /// Creates a contact and adds it to the specified contact list.
    /// </summary>
    /// <param name="emailAddress">The email address of the contact.</param>
    /// <param name="contactListName">The name of the contact list.</param>
    /// <returns>The response from the CreateContact operation.</returns>
    public async Task<bool> CreateContactAsync(string emailAddress, string contactListName)
    {
        var request = new CreateContactRequest
        {
            EmailAddress = emailAddress,
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.CreateContactAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Contact with email address {emailAddress} already exists in the contact list {contactListName}.");
            Console.WriteLine(ex.Message);
            return true;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The contact list {contactListName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the contact: {ex.Message}");
        }
        return false;
    }

    /// <summary>
    /// Creates a contact list with the specified name.
    /// </summary>
    /// <param name="contactListName">The name of the contact list.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> CreateContactListAsync(string contactListName)
    {
        var request = new CreateContactListRequest
        {
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.CreateContactListAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Contact list with name {contactListName} already exists.");
            Console.WriteLine(ex.Message);
            return true;
        }
        catch (LimitExceededException ex)
        {
            Console.WriteLine("The limit for contact lists has been exceeded.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the contact list: {ex.Message}");
        }
        return false;
    }

    /// <summary>
    /// Creates an email identity (email address or domain) and starts the verification process.
    /// </summary>
    /// <param name="emailIdentity">The email address or domain to create and verify.</param>
    /// <returns>The response from the CreateEmailIdentity operation.</returns>
    public async Task<CreateEmailIdentityResponse> CreateEmailIdentityAsync(string emailIdentity)
    {
        var request = new CreateEmailIdentityRequest
        {
            EmailIdentity = emailIdentity
        };

        try
        {
            var response = await _sesClient.CreateEmailIdentityAsync(request);
            return response;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Email identity {emailIdentity} already exists.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (ConcurrentModificationException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} is being modified by another operation or thread.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (LimitExceededException ex)
        {
            Console.WriteLine("The limit for email identities has been exceeded.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} does not exist.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the email identity: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Creates an email template with the specified content.
    /// </summary>
    /// <param name="templateName">The name of the email template.</param>
    /// <param name="subject">The subject of the email template.</param>
    /// <param name="htmlContent">The HTML content of the email template.</param>
    /// <param name="textContent">The text content of the email template.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> CreateEmailTemplateAsync(string templateName, string subject, string htmlContent, string textContent)
    {
        var request = new CreateEmailTemplateRequest
        {
            TemplateName = templateName,
            TemplateContent = new EmailTemplateContent
            {
                Subject = subject,
                Html = htmlContent,
                Text = textContent
            }
        };

        try
        {
            var response = await _sesClient.CreateEmailTemplateAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (AlreadyExistsException ex)
        {
            Console.WriteLine($"Email template with name {templateName} already exists.");
            Console.WriteLine(ex.Message);
        }
        catch (LimitExceededException ex)
        {
            Console.WriteLine("The limit for email templates has been exceeded.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating the email template: {ex.Message}");
        }

        return false;
    }

    /// <summary>
    /// Deletes a contact list and all contacts within it.
    /// </summary>
    /// <param name="contactListName">The name of the contact list to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteContactListAsync(string contactListName)
    {
        var request = new DeleteContactListRequest
        {
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.DeleteContactListAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (ConcurrentModificationException ex)
        {
            Console.WriteLine($"The contact list {contactListName} is being modified by another operation or thread.");
            Console.WriteLine(ex.Message);
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The contact list {contactListName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting the contact list: {ex.Message}");
        }

        return false;
    }

    /// <summary>
    /// Deletes an email identity (email address or domain).
    /// </summary>
    /// <param name="emailIdentity">The email address or domain to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteEmailIdentityAsync(string emailIdentity)
    {
        var request = new DeleteEmailIdentityRequest
        {
            EmailIdentity = emailIdentity
        };

        try
        {
            var response = await _sesClient.DeleteEmailIdentityAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (ConcurrentModificationException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} is being modified by another operation or thread.");
            Console.WriteLine(ex.Message);
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The email identity {emailIdentity} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting the email identity: {ex.Message}");
        }

        return false;
    }

    /// <summary>
    /// Deletes an email template.
    /// </summary>
    /// <param name="templateName">The name of the email template to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteEmailTemplateAsync(string templateName)
    {
        var request = new DeleteEmailTemplateRequest
        {
            TemplateName = templateName
        };

        try
        {
            var response = await _sesClient.DeleteEmailTemplateAsync(request);
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The email template {templateName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting the email template: {ex.Message}");
        }

        return false;
    }

    /// <summary>
    /// Lists the contacts in the specified contact list.
    /// </summary>
    /// <param name="contactListName">The name of the contact list.</param>
    /// <returns>The list of contacts response from the ListContacts operation.</returns>
    public async Task<List<Contact>> ListContactsAsync(string contactListName)
    {
        var request = new ListContactsRequest
        {
            ContactListName = contactListName
        };

        try
        {
            var response = await _sesClient.ListContactsAsync(request);
            return response.Contacts;
        }
        catch (NotFoundException ex)
        {
            Console.WriteLine($"The contact list {contactListName} does not exist.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while listing the contacts: {ex.Message}");
        }

        return new List<Contact>();
    }

    /// <summary>
    /// Sends an email with the specified content and options.
    /// </summary>
    /// <param name="fromEmailAddress">The email address to send the email from.</param>
    /// <param name="toEmailAddresses">The email addresses to send the email to.</param>
    /// <param name="subject">The subject of the email.</param>
    /// <param name="htmlContent">The HTML content of the email.</param>
    /// <param name="textContent">The text content of the email.</param>
    /// <param name="templateName">The name of the email template to use (optional).</param>
    /// <param name="templateData">The data to replace placeholders in the email template (optional).</param>
    /// <param name="contactListName">The name of the contact list for unsubscribe functionality (optional).</param>
    /// <returns>The MessageId response from the SendEmail operation.</returns>
    public async Task<string> SendEmailAsync(string fromEmailAddress, List<string> toEmailAddresses, string? subject,
        string? htmlContent, string? textContent, string? templateName = null, string? templateData = null, string? contactListName = null)
    {
        var request = new SendEmailRequest
        {
            FromEmailAddress = fromEmailAddress
        };

        if (toEmailAddresses.Any())
        {
            request.Destination = new Destination { ToAddresses = toEmailAddresses };
        }

        if (!string.IsNullOrEmpty(templateName))
        {
            request.Content = new EmailContent()
            {
                Template = new Template
                {
                    TemplateName = templateName,
                    TemplateData = templateData
                }
            };
        }
        else
        {
            request.Content = new EmailContent
            {
                Simple = new Message
                {
                    Subject = new Content { Data = subject },
                    Body = new Body
                    {
                        Html = new Content { Data = htmlContent },
                        Text = new Content { Data = textContent }
                    }
                }
            };
        }

        if (!string.IsNullOrEmpty(contactListName))
        {
            request.ListManagementOptions = new ListManagementOptions
            {
                ContactListName = contactListName
            };
        }

        try
        {
            var response = await _sesClient.SendEmailAsync(request);
            return response.MessageId;
        }
        catch (AccountSuspendedException ex)
        {
            Console.WriteLine("The account's ability to send email has been permanently restricted.");
            Console.WriteLine(ex.Message);
        }
        catch (MailFromDomainNotVerifiedException ex)
        {
            Console.WriteLine("The sending domain is not verified.");
            Console.WriteLine(ex.Message);
        }
        catch (MessageRejectedException ex)
        {
            Console.WriteLine("The message content is invalid.");
            Console.WriteLine(ex.Message);
        }
        catch (SendingPausedException ex)
        {
            Console.WriteLine("The account's ability to send email is currently paused.");
            Console.WriteLine(ex.Message);
        }
        catch (TooManyRequestsException ex)
        {
            Console.WriteLine("Too many requests were made. Please try again later.");
            Console.WriteLine(ex.Message);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while sending the email: {ex.Message}");
        }

        return string.Empty;
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateContact](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateContact)
  + [CreateContactList](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateContactList)
  + [CreateEmailIdentity](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateEmailIdentity)
  + [CreateEmailTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/CreateEmailTemplate)
  + [DeleteContactList](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/DeleteContactList)
  + [DeleteEmailIdentity](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/DeleteEmailIdentity)
  + [DeleteEmailTemplate](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/DeleteEmailTemplate)
  + [ListContacts](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/ListContacts)
  + [SendEmail.simple](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/SendEmail.simple)
  + [SendEmail.template](https://docs.aws.amazon.com/goto/DotNetSDKV3/sesv2-2019-09-27/SendEmail.template)

# を使用した Amazon SNS の例 SDK for .NET
<a name="csharp_3_sns_code_examples"></a>

次のコード例は、Amazon SNS AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SNS
<a name="sns_Hello_csharp_3_topic"></a>

次のコード例は、Amazon SNS の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;

namespace SNSActions;

public static class HelloSNS
{
    static async Task Main(string[] args)
    {
        var snsClient = new AmazonSimpleNotificationServiceClient();

        Console.WriteLine($"Hello Amazon SNS! Following are some of your topics:");
        Console.WriteLine();

        // You can use await and any of the async methods to get a response.
        // Let's get a list of topics.
        var response = await snsClient.ListTopicsAsync(
            new ListTopicsRequest());

        foreach (var topic in response.Topics)
        {
            Console.WriteLine($"\tTopic ARN: {topic.TopicArn}");
            Console.WriteLine();
        }
    }
}
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[ListTopics](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/ListTopics)」を参照してください。

## アクション
<a name="actions"></a>

### `CheckIfPhoneNumberIsOptedOut`
<a name="sns_CheckIfPhoneNumberIsOptedOut_csharp_3_topic"></a>

次のコード例は、`CheckIfPhoneNumberIsOptedOut` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example shows how to use the Amazon Simple Notification Service
    /// (Amazon SNS) to check whether a phone number has been opted out.
    /// </summary>
    public class IsPhoneNumOptedOut
    {
        public static async Task Main()
        {
            string phoneNumber = "+15551112222";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            await CheckIfOptedOutAsync(client, phoneNumber);
        }

        /// <summary>
        /// Checks to see if the supplied phone number has been opted out.
        /// </summary>
        /// <param name="client">The initialized Amazon SNS Client object used
        /// to check if the phone number has been opted out.</param>
        /// <param name="phoneNumber">A string representing the phone number
        /// to check.</param>
        public static async Task CheckIfOptedOutAsync(IAmazonSimpleNotificationService client, string phoneNumber)
        {
            var request = new CheckIfPhoneNumberIsOptedOutRequest
            {
                PhoneNumber = phoneNumber,
            };

            try
            {
                var response = await client.CheckIfPhoneNumberIsOptedOutAsync(request);

                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    string optOutStatus = response.IsOptedOut ? "opted out" : "not opted out.";
                    Console.WriteLine($"The phone number: {phoneNumber} is {optOutStatus}");
                }
            }
            catch (AuthorizationErrorException ex)
            {
                Console.WriteLine($"{ex.Message}");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CheckIfPhoneNumberIsOptedOut](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CheckIfPhoneNumberIsOptedOut)」を参照してください。

### `CreateTopic`
<a name="sns_CreateTopic_csharp_3_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。
トピックを作成して、個別の名前を付けます。  

```
    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](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_csharp_3_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
トピック ARN でトピックを削除します。  

```
    /// <summary>
    /// Delete a topic by its topic ARN.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteTopicByArn(string topicArn)
    {
        var deleteResponse = await _amazonSNSClient.DeleteTopicAsync(
            new DeleteTopicRequest()
            {
                TopicArn = topicArn
            });
        return deleteResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/DeleteTopic)」を参照してください。

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_csharp_3_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;

    /// <summary>
    /// This example shows how to retrieve the attributes of an Amazon Simple
    /// Notification Service (Amazon SNS) topic.
    /// </summary>
    public class GetTopicAttributes
    {
        public static async Task Main()
        {
            string topicArn = "arn:aws:sns:us-west-2:000000000000:ExampleSNSTopic";
            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            var attributes = await GetTopicAttributesAsync(client, topicArn);
            DisplayTopicAttributes(attributes);
        }

        /// <summary>
        /// Given the ARN of the Amazon SNS topic, this method retrieves the topic
        /// attributes.
        /// </summary>
        /// <param name="client">The initialized Amazon SNS client object used
        /// to retrieve the attributes for the Amazon SNS topic.</param>
        /// <param name="topicArn">The ARN of the topic for which to retrieve
        /// the attributes.</param>
        /// <returns>A Dictionary of topic attributes.</returns>
        public static async Task<Dictionary<string, string>> GetTopicAttributesAsync(
            IAmazonSimpleNotificationService client,
            string topicArn)
        {
            var response = await client.GetTopicAttributesAsync(topicArn);

            return response.Attributes;
        }

        /// <summary>
        /// This method displays the attributes for an Amazon SNS topic.
        /// </summary>
        /// <param name="topicAttributes">A Dictionary containing the
        /// attributes for an Amazon SNS topic.</param>
        public static void DisplayTopicAttributes(Dictionary<string, string> topicAttributes)
        {
            foreach (KeyValuePair<string, string> entry in topicAttributes)
            {
                Console.WriteLine($"{entry.Key}: {entry.Value}\n");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetTopicAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/GetTopicAttributes)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_csharp_3_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example will retrieve a list of the existing Amazon Simple
    /// Notification Service (Amazon SNS) subscriptions.
    /// </summary>
    public class ListSubscriptions
    {
        public static async Task Main()
        {
            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            Console.WriteLine("Enter a topic ARN to list subscriptions for a specific topic, " +
                              "or press Enter to list subscriptions for all topics.");
            var topicArn = Console.ReadLine();
            Console.WriteLine();

            var subscriptions = await GetSubscriptionsListAsync(client, topicArn);

            DisplaySubscriptionList(subscriptions);
        }

        /// <summary>
        /// Gets a list of the existing Amazon SNS subscriptions, optionally by specifying a topic ARN.
        /// </summary>
        /// <param name="client">The initialized Amazon SNS client object used
        /// to obtain the list of subscriptions.</param>
        /// <param name="topicArn">The optional ARN of a specific topic. Defaults to null.</param>
        /// <returns>A list containing information about each subscription.</returns>
        public static async Task<List<Subscription>> GetSubscriptionsListAsync(IAmazonSimpleNotificationService client, string topicArn = null)
        {
            var results = new List<Subscription>();

            if (!string.IsNullOrEmpty(topicArn))
            {
                var paginateByTopic = client.Paginators.ListSubscriptionsByTopic(
                    new ListSubscriptionsByTopicRequest()
                    {
                        TopicArn = topicArn,
                    });

                // Get the entire list using the paginator.
                await foreach (var subscription in paginateByTopic.Subscriptions)
                {
                    results.Add(subscription);
                }
            }
            else
            {
                var paginateAllSubscriptions = client.Paginators.ListSubscriptions(new ListSubscriptionsRequest());

                // Get the entire list using the paginator.
                await foreach (var subscription in paginateAllSubscriptions.Subscriptions)
                {
                    results.Add(subscription);
                }
            }

            return results;
        }

        /// <summary>
        /// Display a list of Amazon SNS subscription information.
        /// </summary>
        /// <param name="subscriptionList">A list containing details for existing
        /// Amazon SNS subscriptions.</param>
        public static void DisplaySubscriptionList(List<Subscription> subscriptionList)
        {
            foreach (var subscription in subscriptionList)
            {
                Console.WriteLine($"Owner: {subscription.Owner}");
                Console.WriteLine($"Subscription ARN: {subscription.SubscriptionArn}");
                Console.WriteLine($"Topic ARN: {subscription.TopicArn}");
                Console.WriteLine($"Endpoint: {subscription.Endpoint}");
                Console.WriteLine($"Protocol: {subscription.Protocol}");
                Console.WriteLine();
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListSubscriptions](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/ListSubscriptions)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_csharp_3_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// Lists the Amazon Simple Notification Service (Amazon SNS)
    /// topics for the current account.
    /// </summary>
    public class ListSNSTopics
    {
        public static async Task Main()
        {
            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            await GetTopicListAsync(client);
        }

        /// <summary>
        /// Retrieves the list of Amazon SNS topics in groups of up to 100
        /// topics.
        /// </summary>
        /// <param name="client">The initialized Amazon SNS client object used
        /// to retrieve the list of topics.</param>
        public static async Task GetTopicListAsync(IAmazonSimpleNotificationService client)
        {
            // If there are more than 100 Amazon SNS topics, the call to
            // ListTopicsAsync will return a value to pass to the
            // method to retrieve the next 100 (or less) topics.
            string nextToken = string.Empty;

            do
            {
                var response = await client.ListTopicsAsync(nextToken);
                DisplayTopicsList(response.Topics);
                nextToken = response.NextToken;
            }
            while (!string.IsNullOrEmpty(nextToken));
        }

        /// <summary>
        /// Displays the list of Amazon SNS Topic ARNs.
        /// </summary>
        /// <param name="topicList">The list of Topic ARNs.</param>
        public static void DisplayTopicsList(List<Topic> topicList)
        {
            foreach (var topic in topicList)
            {
                Console.WriteLine($"{topic.TopicArn}");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListTopics](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/ListTopics)」を参照してください。

### `Publish`
<a name="sns_Publish_csharp_3_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。
トピックへのメッセージの発行  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example publishes a message to an Amazon Simple Notification
    /// Service (Amazon SNS) topic.
    /// </summary>
    public class PublishToSNSTopic
    {
        public static async Task Main()
        {
            string topicArn = "arn:aws:sns:us-east-2:000000000000:ExampleSNSTopic";
            string messageText = "This is an example message to publish to the ExampleSNSTopic.";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            await PublishToTopicAsync(client, topicArn, messageText);
        }

        /// <summary>
        /// Publishes a message to an Amazon SNS topic.
        /// </summary>
        /// <param name="client">The initialized client object used to publish
        /// to the Amazon SNS topic.</param>
        /// <param name="topicArn">The ARN of the topic.</param>
        /// <param name="messageText">The text of the message.</param>
        public static async Task PublishToTopicAsync(
            IAmazonSimpleNotificationService client,
            string topicArn,
            string messageText)
        {
            var request = new PublishRequest
            {
                TopicArn = topicArn,
                Message = messageText,
            };

            var response = await client.PublishAsync(request);

            Console.WriteLine($"Successfully published message ID: {response.MessageId}");
        }
    }
```
グループ、重複、属性のオプションを指定してトピックにメッセージを発行します。  

```
    /// <summary>
    /// Publish messages using user settings.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task PublishMessages()
    {
        Console.WriteLine("Now we can publish messages.");

        var keepSendingMessages = true;
        string? deduplicationId = null;
        string? toneAttribute = null;
        while (keepSendingMessages)
        {
            Console.WriteLine();
            var message = GetUserResponse("Enter a message to publish.", "This is a sample message");

            if (_useFifoTopic)
            {
                Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." +
                                  "\r\nAll messages within the same group will be received in the order " +
                                  "they were published.");

                Console.WriteLine();
                var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1");

                if (!_useContentBasedDeduplication)
                {
                    Console.WriteLine("Because you are not using content-based deduplication, " +
                                      "you must enter a deduplication ID.");

                    Console.WriteLine("Enter a deduplication ID for this message.");
                    deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1");
                }

                if (GetYesNoResponse("Add an attribute to this message?"))
                {
                    Console.WriteLine("Enter a number for an attribute.");
                    for (int i = 0; i < _tones.Length; i++)
                    {
                        Console.WriteLine($"\t{i + 1}. {_tones[i]}");
                    }

                    var selection = GetUserResponse("", "1");
                    int.TryParse(selection, out var selectionNumber);

                    if (selectionNumber > 0 && selectionNumber < _tones.Length)
                    {
                        toneAttribute = _tones[selectionNumber - 1];
                    }
                }

                var messageID = await SnsWrapper.PublishToTopicWithAttribute(
                    _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId);

                Console.WriteLine($"Message published with id {messageID}.");
            }

            keepSendingMessages = GetYesNoResponse("Send another message?", false);
        }
    }
```
ユーザーの選択を発行アクションに適用します。  

```
    /// <summary>
    /// Publish a message to a topic with an attribute and optional deduplication and group IDs.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="message">The message to publish.</param>
    /// <param name="attributeName">The optional attribute for the message.</param>
    /// <param name="attributeValue">The optional attribute value for the message.</param>
    /// <param name="deduplicationId">The optional deduplication ID for the message.</param>
    /// <param name="groupId">The optional group ID for the message.</param>
    /// <returns>The ID of the message published.</returns>
    public async Task<string> PublishToTopicWithAttribute(
        string topicArn,
        string message,
        string? attributeName = null,
        string? attributeValue = null,
        string? deduplicationId = null,
        string? groupId = null)
    {
        var publishRequest = new PublishRequest()
        {
            TopicArn = topicArn,
            Message = message,
            MessageDeduplicationId = deduplicationId,
            MessageGroupId = groupId
        };

        if (attributeValue != null)
        {
            // Add the string attribute if it exists.
            publishRequest.MessageAttributes =
                new Dictionary<string, MessageAttributeValue>
                {
                    { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} }
                };
        }

        var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest);
        return publishResponse.MessageId;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[発行](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_csharp_3_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
        /// <summary>
        /// Creates a new subscription to a topic.
        /// </summary>
        /// <param name="client">The initialized Amazon SNS client object, used
        /// to create an Amazon SNS subscription.</param>
        /// <param name="topicArn">The ARN of the topic to subscribe to.</param>
        /// <returns>A SubscribeResponse object which includes the subscription
        /// ARN for the new subscription.</returns>
        public static async Task<SubscribeResponse> TopicSubscribeAsync(
            IAmazonSimpleNotificationService client,
            string topicArn)
        {
            SubscribeRequest request = new SubscribeRequest()
            {
                TopicArn = topicArn,
                ReturnSubscriptionArn = true,
                Protocol = "email",
                Endpoint = "recipient@example.com",
            };

            var response = await client.SubscribeAsync(request);

            return response;
        }
```
オプションのフィルターでトピックにキューをサブスクライブします。  

```
    /// <summary>
    /// Subscribe a queue to a topic with optional filters.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <returns>The ARN of the new subscription.</returns>
    public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn)
    {
        var subscribeRequest = new SubscribeRequest()
        {
            TopicArn = topicArn,
            Protocol = "sqs",
            Endpoint = queueArn
        };

        if (!string.IsNullOrEmpty(filterPolicy))
        {
            subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } };
        }

        var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest);
        return subscribeResponse.SubscriptionArn;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[Subscribe](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Subscribe)」を参照してください。

### `Unsubscribe`
<a name="sns_Unsubscribe_csharp_3_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
サブスクリプション ARN でトピックからサブスクライブを解除します。  

```
    /// <summary>
    /// Unsubscribe from a topic by a subscription ARN.
    /// </summary>
    /// <param name="subscriptionArn">The ARN of the subscription.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> UnsubscribeByArn(string subscriptionArn)
    {
        var unsubscribeResponse = await _amazonSNSClient.UnsubscribeAsync(
            new UnsubscribeRequest()
            {
                SubscriptionArn = subscriptionArn
            });
        return unsubscribeResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[Unsubscribe](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Unsubscribe)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon SNS アプリケーションの構築
<a name="cross_SnsPublishSubscription_csharp_3_topic"></a>

次のコード例は、サブスクリプションとパブリッシュ機能を持ち、メッセージを翻訳するアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 Amazon Simple Notification Service .NET API を使用して、サブスクリプションおよびパブリッシュ機能を持つウェブアプリケーションを作成する方法を説明します。さらに、このサンプルアプリケーションではメッセージを翻訳します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/SubscribePublishTranslate) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon SNS
+ Amazon Translate

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_csharp_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for .NET**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/PhotoAssetManager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### SMS テキストメッセージを発行する
<a name="sns_PublishTextSMS_csharp_3_topic"></a>

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。

```
namespace SNSMessageExample
{
    using System;
    using System.Threading.Tasks;
    using Amazon;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    public class SNSMessage
    {
        private AmazonSimpleNotificationServiceClient snsClient;

        /// <summary>
        /// Initializes a new instance of the <see cref="SNSMessage"/> class.
        /// Constructs a new SNSMessage object initializing the Amazon Simple
        /// Notification Service (Amazon SNS) client using the supplied
        /// Region endpoint.
        /// </summary>
        /// <param name="regionEndpoint">The Amazon Region endpoint to use in
        /// sending test messages with this object.</param>
        public SNSMessage(RegionEndpoint regionEndpoint)
        {
            snsClient = new AmazonSimpleNotificationServiceClient(regionEndpoint);
        }

        /// <summary>
        /// Sends the SMS message passed in the text parameter to the phone number
        /// in phoneNum.
        /// </summary>
        /// <param name="phoneNum">The ten-digit phone number to which the text
        /// message will be sent.</param>
        /// <param name="text">The text of the message to send.</param>
        /// <returns>Async task.</returns>
        public async Task SendTextMessageAsync(string phoneNum, string text)
        {
            if (string.IsNullOrEmpty(phoneNum) || string.IsNullOrEmpty(text))
            {
                return;
            }

            // Now actually send the message.
            var request = new PublishRequest
            {
                Message = text,
                PhoneNumber = phoneNum,
            };

            try
            {
                var response = await snsClient.PublishAsync(request);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending message: {ex}");
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Publish](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)」を参照してください。

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
/// <summary>
/// Console application to run a feature scenario for topics and queues.
/// </summary>
public static class TopicsAndQueues
{
    private static bool _useFifoTopic = false;
    private static bool _useContentBasedDeduplication = false;
    private static string _topicName = null!;
    private static string _topicArn = null!;

    private static readonly int _queueCount = 2;
    private static readonly string[] _queueUrls = new string[_queueCount];
    private static readonly string[] _subscriptionArns = new string[_queueCount];
    private static readonly string[] _tones = { "cheerful", "funny", "serious", "sincere" };
    public static SNSWrapper SnsWrapper { get; set; } = null!;
    public static SQSWrapper SqsWrapper { get; set; } = null!;
    public static bool UseConsole { get; set; } = true;
    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon EventBridge.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonSQS>()
                    .AddAWSService<IAmazonSimpleNotificationService>()
                    .AddTransient<SNSWrapper>()
                    .AddTransient<SQSWrapper>()
            )
            .Build();

        ServicesSetup(host);
        PrintDescription();

        await RunScenario();

    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        SnsWrapper = host.Services.GetRequiredService<SNSWrapper>();
        SqsWrapper = host.Services.GetRequiredService<SQSWrapper>();
    }

    /// <summary>
    /// Run the scenario for working with topics and queues.
    /// </summary>
    /// <returns>True if successful.</returns>
    public static async Task<bool> RunScenario()
    {
        try
        {
            await SetupTopic();

            await SetupQueues();

            await PublishMessages();

            foreach (var queueUrl in _queueUrls)
            {
                var messages = await PollForMessages(queueUrl);
                if (messages.Any())
                {
                    await DeleteMessages(queueUrl, messages);
                }
            }
            await CleanupResources();

            Console.WriteLine("Messaging with topics and queues scenario is complete.");
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            await CleanupResources();
            Console.WriteLine(new string('-', 80));
            return false;
        }
    }

    /// <summary>
    /// Print a description for the tasks in the scenario.
    /// </summary>
    /// <returns>Async task.</returns>
    private static void PrintDescription()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Welcome to messaging with topics and queues.");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"In this scenario, you will create an SNS topic and subscribe {_queueCount} SQS queues to the topic." +
                          $"\r\nYou can select from several options for configuring the topic and the subscriptions for the 2 queues." +
                          $"\r\nYou can then post to the topic and see the results in the queues.\r\n");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Set up the SNS topic to be used with the queues.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task<string> SetupTopic()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"SNS topics can be configured as FIFO (First-In-First-Out)." +
                          $"\r\nFIFO topics deliver messages in order and support deduplication and message filtering." +
                          $"\r\nYou can then post to the topic and see the results in the queues.\r\n");

        _useFifoTopic = GetYesNoResponse("Would you like to work with FIFO topics?");

        if (_useFifoTopic)
        {
            Console.WriteLine(new string('-', 80));
            _topicName = GetUserResponse("Enter a name for your SNS topic: ", "example-topic");
            Console.WriteLine(
                "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.\r\n");

            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"Because you have chosen a FIFO topic, deduplication is supported." +
                              $"\r\nDeduplication IDs are either set in the message or automatically generated " +
                              $"\r\nfrom content using a hash function.\r\n" +
                              $"\r\nIf a message is successfully published to an SNS FIFO topic, any message " +
                              $"\r\npublished and determined to have the same deduplication ID, " +
                              $"\r\nwithin the five-minute deduplication interval, is accepted but not delivered.\r\n" +
                              $"\r\nFor more information about deduplication, " +
                              $"\r\nsee https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.");

            _useContentBasedDeduplication = GetYesNoResponse("Use content-based deduplication instead of entering a deduplication ID?");
            Console.WriteLine(new string('-', 80));
        }

        _topicArn = await SnsWrapper.CreateTopicWithName(_topicName, _useFifoTopic, _useContentBasedDeduplication);

        Console.WriteLine($"Your new topic with the name {_topicName}" +
                          $"\r\nand Amazon Resource Name (ARN) {_topicArn}" +
                          $"\r\nhas been created.\r\n");

        Console.WriteLine(new string('-', 80));
        return _topicArn;
    }

    /// <summary>
    /// Set up the queues.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task SetupQueues()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Now you will create {_queueCount} Amazon Simple Queue Service (Amazon SQS) queues to subscribe to the topic.");

        // Repeat this section for each queue.
        for (int i = 0; i < _queueCount; i++)
        {
            var queueName = GetUserResponse("Enter a name for an Amazon SQS queue: ", $"example-queue-{i}");
            if (_useFifoTopic)
            {
                // Only explain this once.
                if (i == 0)
                {
                    Console.WriteLine(
                        "Because you have selected a FIFO topic, '.fifo' must be appended to the queue name.");
                }

                var queueUrl = await SqsWrapper.CreateQueueWithName(queueName, _useFifoTopic);

                _queueUrls[i] = queueUrl;

                Console.WriteLine($"Your new queue with the name {queueName}" +
                                  $"\r\nand queue URL {queueUrl}" +
                                  $"\r\nhas been created.\r\n");

                if (i == 0)
                {
                    Console.WriteLine(
                        $"The queue URL is used to retrieve the queue ARN,\r\n" +
                        $"which is used to create a subscription.");
                    Console.WriteLine(new string('-', 80));
                }

                var queueArn = await SqsWrapper.GetQueueArnByUrl(queueUrl);

                if (i == 0)
                {
                    Console.WriteLine(
                        $"An AWS Identity and Access Management (IAM) policy must be attached to an SQS queue, enabling it to receive\r\n" +
                        $"messages from an SNS topic");
                }

                await SqsWrapper.SetQueuePolicyForTopic(queueArn, _topicArn, queueUrl);

                await SetupFilters(i, queueArn, queueName);
            }
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Set up filters with user options for a queue.
    /// </summary>
    /// <param name="queueCount">The number of this queue.</param>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <param name="queueName">The name of the queue.</param>
    /// <returns>Async Task.</returns>
    public static async Task SetupFilters(int queueCount, string queueArn, string queueName)
    {
        if (_useFifoTopic)
        {
            Console.WriteLine(new string('-', 80));
            // Only explain this once.
            if (queueCount == 0)
            {
                Console.WriteLine(
                    "Subscriptions to a FIFO topic can have filters." +
                    "If you add a filter to this subscription, then only the filtered messages " +
                    "will be received in the queue.");

                Console.WriteLine(
                    "For information about message filtering, " +
                    "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html");

                Console.WriteLine(
                    "For this example, you can filter messages by a" +
                    "TONE attribute.");
            }

            var useFilter = GetYesNoResponse($"Filter messages for {queueName}'s subscription to the topic?");

            string? filterPolicy = null;
            if (useFilter)
            {
                filterPolicy = CreateFilterPolicy();
            }
            var subscriptionArn = await SnsWrapper.SubscribeTopicWithFilter(_topicArn, filterPolicy,
                queueArn);
            _subscriptionArns[queueCount] = subscriptionArn;

            Console.WriteLine(
                $"The queue {queueName} has been subscribed to the topic {_topicName} " +
                $"with the subscription ARN {subscriptionArn}");
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Use user input to create a filter policy for a subscription.
    /// </summary>
    /// <returns>The serialized filter policy.</returns>
    public static string CreateFilterPolicy()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine(
            $"You can filter messages by one or more of the following" +
            $"TONE attributes.");

        List<string> filterSelections = new List<string>();

        var selectionNumber = 0;
        do
        {
            Console.WriteLine(
                $"Enter a number to add a TONE filter, or enter 0 to stop adding filters.");
            for (int i = 0; i < _tones.Length; i++)
            {
                Console.WriteLine($"\t{i + 1}. {_tones[i]}");
            }

            var selection = GetUserResponse("", filterSelections.Any() ? "0" : "1");
            int.TryParse(selection, out selectionNumber);
            if (selectionNumber > 0 && !filterSelections.Contains(_tones[selectionNumber - 1]))
            {
                filterSelections.Add(_tones[selectionNumber - 1]);
            }
        } while (selectionNumber != 0);

        var filters = new Dictionary<string, List<string>>
        {
            { "tone", filterSelections }
        };
        string filterPolicy = JsonSerializer.Serialize(filters);
        return filterPolicy;
    }

    /// <summary>
    /// Publish messages using user settings.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task PublishMessages()
    {
        Console.WriteLine("Now we can publish messages.");

        var keepSendingMessages = true;
        string? deduplicationId = null;
        string? toneAttribute = null;
        while (keepSendingMessages)
        {
            Console.WriteLine();
            var message = GetUserResponse("Enter a message to publish.", "This is a sample message");

            if (_useFifoTopic)
            {
                Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." +
                                  "\r\nAll messages within the same group will be received in the order " +
                                  "they were published.");

                Console.WriteLine();
                var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1");

                if (!_useContentBasedDeduplication)
                {
                    Console.WriteLine("Because you are not using content-based deduplication, " +
                                      "you must enter a deduplication ID.");

                    Console.WriteLine("Enter a deduplication ID for this message.");
                    deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1");
                }

                if (GetYesNoResponse("Add an attribute to this message?"))
                {
                    Console.WriteLine("Enter a number for an attribute.");
                    for (int i = 0; i < _tones.Length; i++)
                    {
                        Console.WriteLine($"\t{i + 1}. {_tones[i]}");
                    }

                    var selection = GetUserResponse("", "1");
                    int.TryParse(selection, out var selectionNumber);

                    if (selectionNumber > 0 && selectionNumber < _tones.Length)
                    {
                        toneAttribute = _tones[selectionNumber - 1];
                    }
                }

                var messageID = await SnsWrapper.PublishToTopicWithAttribute(
                    _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId);

                Console.WriteLine($"Message published with id {messageID}.");
            }

            keepSendingMessages = GetYesNoResponse("Send another message?", false);
        }
    }

    /// <summary>
    /// Poll for the published messages to see the results of the user's choices.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task<List<Message>> PollForMessages(string queueUrl)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Now the SQS queue at {queueUrl} will be polled to retrieve the messages." +
                          "\r\nPress any key to continue.");
        if (UseConsole)
        {
            Console.ReadLine();
        }

        var moreMessages = true;
        var messages = new List<Message>();
        while (moreMessages)
        {
            var newMessages = await SqsWrapper.ReceiveMessagesByUrl(queueUrl, 10);

            moreMessages = newMessages.Any();
            if (moreMessages)
            {
                messages.AddRange(newMessages);
            }
        }

        Console.WriteLine($"{messages.Count} message(s) were received by the queue at {queueUrl}.");

        foreach (var message in messages)
        {
            Console.WriteLine("\tMessage:" +
                              $"\n\t{message.Body}");
        }

        Console.WriteLine(new string('-', 80));
        return messages;
    }

    /// <summary>
    /// Delete the message using handles in a batch.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task DeleteMessages(string queueUrl, List<Message> messages)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Now we can delete the messages in this queue in a batch.");
        await SqsWrapper.DeleteMessageBatchByUrl(queueUrl, messages);
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CleanupResources()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Clean up resources.");

        try
        {
            foreach (var queueUrl in _queueUrls)
            {
                if (!string.IsNullOrEmpty(queueUrl))
                {
                    var deleteQueue =
                        GetYesNoResponse($"Delete queue with url {queueUrl}?");
                    if (deleteQueue)
                    {
                        await SqsWrapper.DeleteQueueByUrl(queueUrl);
                    }
                }
            }

            foreach (var subscriptionArn in _subscriptionArns)
            {
                if (!string.IsNullOrEmpty(subscriptionArn))
                {
                    await SnsWrapper.UnsubscribeByArn(subscriptionArn);
                }
            }

            var deleteTopic = GetYesNoResponse($"Delete topic {_topicName}?");
            if (deleteTopic)
            {
                await SnsWrapper.DeleteTopicByArn(_topicArn);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Unable to clean up resources. Here's why: {ex.Message}.");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <param name="defaultAnswer">Optional default answer to use.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question, bool defaultAnswer = true)
    {
        if (UseConsole)
        {
            Console.WriteLine(question);
            var ynResponse = Console.ReadLine();
            var response = ynResponse != null &&
                           ynResponse.Equals("y",
                               StringComparison.InvariantCultureIgnoreCase);
            return response;
        }
        // If not using the console, use the default.
        return defaultAnswer;
    }

    /// <summary>
    /// Helper method to get a string response from the user through the console.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <param name="defaultAnswer">Optional default answer to use.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static string GetUserResponse(string question, string defaultAnswer)
    {
        if (UseConsole)
        {
            var response = "";
            while (string.IsNullOrEmpty(response))
            {
                Console.WriteLine(question);
                response = Console.ReadLine();
            }
            return response;
        }
        // If not using the console, use the default.
        return defaultAnswer;
    }
}
```
 Amazon SQS オペレーションをラップするクラスを作成します。  

```
/// <summary>
/// Wrapper for Amazon Simple Queue Service (SQS) operations.
/// </summary>
public class SQSWrapper
{
    private readonly IAmazonSQS _amazonSQSClient;

    /// <summary>
    /// Constructor for the Amazon SQS wrapper.
    /// </summary>
    /// <param name="amazonSQS">The injected Amazon SQS client.</param>
    public SQSWrapper(IAmazonSQS amazonSQS)
    {
        _amazonSQSClient = amazonSQS;
    }

    /// <summary>
    /// Create a queue with a specific name.
    /// </summary>
    /// <param name="queueName">The name for the queue.</param>
    /// <param name="useFifoQueue">True to use a FIFO queue.</param>
    /// <returns>The url for the queue.</returns>
    public async Task<string> CreateQueueWithName(string queueName, bool useFifoQueue)
    {
        int maxMessage = 256 * 1024;
        var queueAttributes = new Dictionary<string, string>
        {
            {
                QueueAttributeName.MaximumMessageSize,
                maxMessage.ToString()
            }
        };

        var createQueueRequest = new CreateQueueRequest()
        {
            QueueName = queueName,
            Attributes = queueAttributes
        };

        if (useFifoQueue)
        {
            // Update the name if it is not correct for a FIFO queue.
            if (!queueName.EndsWith(".fifo"))
            {
                createQueueRequest.QueueName = queueName + ".fifo";
            }

            // Add an attribute for a FIFO queue.
            createQueueRequest.Attributes.Add(
                QueueAttributeName.FifoQueue, "true");
        }

        var createResponse = await _amazonSQSClient.CreateQueueAsync(
            new CreateQueueRequest()
            {
                QueueName = queueName
            });
        return createResponse.QueueUrl;
    }

    /// <summary>
    /// Get the ARN for a queue from its URL.
    /// </summary>
    /// <param name="queueUrl">The URL of the queue.</param>
    /// <returns>The ARN of the queue.</returns>
    public async Task<string> GetQueueArnByUrl(string queueUrl)
    {
        var getAttributesRequest = new GetQueueAttributesRequest()
        {
            QueueUrl = queueUrl,
            AttributeNames = new List<string>() { QueueAttributeName.QueueArn }
        };

        var getAttributesResponse = await _amazonSQSClient.GetQueueAttributesAsync(
            getAttributesRequest);

        return getAttributesResponse.QueueARN;
    }

    /// <summary>
    /// Set the policy attribute of a queue for a topic.
    /// </summary>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="queueUrl">The url for the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl)
    {
        var queuePolicy = "{" +
                                "\"Version\": \"2012-10-17\"," +
                                "\"Statement\": [{" +
                                     "\"Effect\": \"Allow\"," +
                                     "\"Principal\": {" +
                                         $"\"Service\": " +
                                             "\"sns.amazonaws.com\"" +
                                            "}," +
                                     "\"Action\": \"sqs:SendMessage\"," +
                                     $"\"Resource\": \"{queueArn}\"," +
                                      "\"Condition\": {" +
                                           "\"ArnEquals\": {" +
                                                $"\"aws:SourceArn\": \"{topicArn}\"" +
                                            "}" +
                                        "}" +
                                "}]" +
                             "}";
        var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync(
            new SetQueueAttributesRequest()
            {
                QueueUrl = queueUrl,
                Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } }
            });
        return attributesResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Receive messages from a queue by its URL.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>The list of messages.</returns>
    public async Task<List<Message>> ReceiveMessagesByUrl(string queueUrl, int maxMessages)
    {
        // Setting WaitTimeSeconds to non-zero enables long polling.
        // For information about long polling, see
        // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html
        var messageResponse = await _amazonSQSClient.ReceiveMessageAsync(
            new ReceiveMessageRequest()
            {
                QueueUrl = queueUrl,
                MaxNumberOfMessages = maxMessages,
                WaitTimeSeconds = 1
            });
        return messageResponse.Messages;
    }

    /// <summary>
    /// Delete a batch of messages from a queue by its url.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteMessageBatchByUrl(string queueUrl, List<Message> messages)
    {
        var deleteRequest = new DeleteMessageBatchRequest()
        {
            QueueUrl = queueUrl,
            Entries = new List<DeleteMessageBatchRequestEntry>()
        };
        foreach (var message in messages)
        {
            deleteRequest.Entries.Add(new DeleteMessageBatchRequestEntry()
            {
                ReceiptHandle = message.ReceiptHandle,
                Id = message.MessageId
            });
        }

        var deleteResponse = await _amazonSQSClient.DeleteMessageBatchAsync(deleteRequest);

        return deleteResponse.Failed.Any();
    }

    /// <summary>
    /// Delete a queue by its URL.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteQueueByUrl(string queueUrl)
    {
        var deleteResponse = await _amazonSQSClient.DeleteQueueAsync(
            new DeleteQueueRequest()
            {
                QueueUrl = queueUrl
            });
        return deleteResponse.HttpStatusCode == HttpStatusCode.OK;
    }
}
```
 Amazon SNS オペレーションをラップするクラスを作成します。  

```
/// <summary>
/// Wrapper for Amazon Simple Notification Service (SNS) operations.
/// </summary>
public class SNSWrapper
{
    private readonly IAmazonSimpleNotificationService _amazonSNSClient;

    /// <summary>
    /// Constructor for the Amazon SNS wrapper.
    /// </summary>
    /// <param name="amazonSQS">The injected Amazon SNS client.</param>
    public SNSWrapper(IAmazonSimpleNotificationService amazonSNS)
    {
        _amazonSNSClient = amazonSNS;
    }

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

    /// <summary>
    /// Subscribe a queue to a topic with optional filters.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <returns>The ARN of the new subscription.</returns>
    public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn)
    {
        var subscribeRequest = new SubscribeRequest()
        {
            TopicArn = topicArn,
            Protocol = "sqs",
            Endpoint = queueArn
        };

        if (!string.IsNullOrEmpty(filterPolicy))
        {
            subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } };
        }

        var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest);
        return subscribeResponse.SubscriptionArn;
    }

    /// <summary>
    /// Publish a message to a topic with an attribute and optional deduplication and group IDs.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="message">The message to publish.</param>
    /// <param name="attributeName">The optional attribute for the message.</param>
    /// <param name="attributeValue">The optional attribute value for the message.</param>
    /// <param name="deduplicationId">The optional deduplication ID for the message.</param>
    /// <param name="groupId">The optional group ID for the message.</param>
    /// <returns>The ID of the message published.</returns>
    public async Task<string> PublishToTopicWithAttribute(
        string topicArn,
        string message,
        string? attributeName = null,
        string? attributeValue = null,
        string? deduplicationId = null,
        string? groupId = null)
    {
        var publishRequest = new PublishRequest()
        {
            TopicArn = topicArn,
            Message = message,
            MessageDeduplicationId = deduplicationId,
            MessageGroupId = groupId
        };

        if (attributeValue != null)
        {
            // Add the string attribute if it exists.
            publishRequest.MessageAttributes =
                new Dictionary<string, MessageAttributeValue>
                {
                    { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} }
                };
        }

        var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest);
        return publishResponse.MessageId;
    }


    /// <summary>
    /// Unsubscribe from a topic by a subscription ARN.
    /// </summary>
    /// <param name="subscriptionArn">The ARN of the subscription.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> UnsubscribeByArn(string subscriptionArn)
    {
        var unsubscribeResponse = await _amazonSNSClient.UnsubscribeAsync(
            new UnsubscribeRequest()
            {
                SubscriptionArn = subscriptionArn
            });
        return unsubscribeResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Delete a topic by its topic ARN.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteTopicByArn(string topicArn)
    {
        var deleteResponse = await _amazonSNSClient.DeleteTopicAsync(
            new DeleteTopicRequest()
            {
                TopicArn = topicArn
            });
        return deleteResponse.HttpStatusCode == HttpStatusCode.OK;
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Unsubscribe)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_csharp_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を検索し、設定および実行する方法を確認してください。
.NET を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.Lambda.Core;
using Amazon.Lambda.SNSEvents;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SnsIntegration;

public class Function
{
    public async Task FunctionHandler(SNSEvent evnt, ILambdaContext context)
    {
        foreach (var record in evnt.Records)
        {
            await ProcessRecordAsync(record, context);
        }
        context.Logger.LogInformation("done");
    }

    private async Task ProcessRecordAsync(SNSEvent.SNSRecord record, ILambdaContext context)
    {
        try
        {
            context.Logger.LogInformation($"Processed record {record.Sns.Message}");

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
        catch (Exception e)
        {
            //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ.
            context.Logger.LogError($"An error occurred");
            throw;
        }
    }
}
```

# を使用した Amazon SQS の例 SDK for .NET
<a name="csharp_3_sqs_code_examples"></a>

次のコード例は、Amazon SQS AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SQS
<a name="sqs_Hello_csharp_3_topic"></a>

次のコード例は、Amazon SQS の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.SQS;
using Amazon.SQS.Model;

namespace SQSActions;

public static class HelloSQS
{
    static async Task Main(string[] args)
    {
        var sqsClient = new AmazonSQSClient();

        Console.WriteLine($"Hello Amazon SQS! Following are some of your queues:");
        Console.WriteLine();

        // You can use await and any of the async methods to get a response.
        // Let's get the first five queues.
        var response = await sqsClient.ListQueuesAsync(
            new ListQueuesRequest()
            {
                MaxResults = 5
            });

        foreach (var queue in response.QueueUrls)
        {
            Console.WriteLine($"\tQueue Url: {queue}");
            Console.WriteLine();
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListQueues](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/ListQueues)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateQueue`
<a name="sqs_CreateQueue_csharp_3_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
特定の名前を持つキューを作成します。  

```
    /// <summary>
    /// Create a queue with a specific name.
    /// </summary>
    /// <param name="queueName">The name for the queue.</param>
    /// <param name="useFifoQueue">True to use a FIFO queue.</param>
    /// <returns>The url for the queue.</returns>
    public async Task<string> CreateQueueWithName(string queueName, bool useFifoQueue)
    {
        int maxMessage = 256 * 1024;
        var queueAttributes = new Dictionary<string, string>
        {
            {
                QueueAttributeName.MaximumMessageSize,
                maxMessage.ToString()
            }
        };

        var createQueueRequest = new CreateQueueRequest()
        {
            QueueName = queueName,
            Attributes = queueAttributes
        };

        if (useFifoQueue)
        {
            // Update the name if it is not correct for a FIFO queue.
            if (!queueName.EndsWith(".fifo"))
            {
                createQueueRequest.QueueName = queueName + ".fifo";
            }

            // Add an attribute for a FIFO queue.
            createQueueRequest.Attributes.Add(
                QueueAttributeName.FifoQueue, "true");
        }

        var createResponse = await _amazonSQSClient.CreateQueueAsync(
            new CreateQueueRequest()
            {
                QueueName = queueName
            });
        return createResponse.QueueUrl;
    }
```
Amazon SQS キューを作成して、そこにメッセージを送信します。  

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon;
    using Amazon.SQS;
    using Amazon.SQS.Model;

    public class CreateSendExample
    {
        // Specify your AWS Region (an example Region is shown).
        private static readonly string QueueName = "Example_Queue";
        private static readonly RegionEndpoint ServiceRegion = RegionEndpoint.USWest2;
        private static IAmazonSQS client;

        public static async Task Main()
        {
            client = new AmazonSQSClient(ServiceRegion);
            var createQueueResponse = await CreateQueue(client, QueueName);

            string queueUrl = createQueueResponse.QueueUrl;

            Dictionary<string, MessageAttributeValue> messageAttributes = new Dictionary<string, MessageAttributeValue>
            {
                { "Title",   new MessageAttributeValue { DataType = "String", StringValue = "The Whistler" } },
                { "Author",  new MessageAttributeValue { DataType = "String", StringValue = "John Grisham" } },
                { "WeeksOn", new MessageAttributeValue { DataType = "Number", StringValue = "6" } },
            };

            string messageBody = "Information about current NY Times fiction bestseller for week of 12/11/2016.";

            var sendMsgResponse = await SendMessage(client, queueUrl, messageBody, messageAttributes);
        }

        /// <summary>
        /// Creates a new Amazon SQS queue using the queue name passed to it
        /// in queueName.
        /// </summary>
        /// <param name="client">An SQS client object used to send the message.</param>
        /// <param name="queueName">A string representing the name of the queue
        /// to create.</param>
        /// <returns>A CreateQueueResponse that contains information about the
        /// newly created queue.</returns>
        public static async Task<CreateQueueResponse> CreateQueue(IAmazonSQS client, string queueName)
        {
            var request = new CreateQueueRequest
            {
                QueueName = queueName,
                Attributes = new Dictionary<string, string>
                {
                    { "DelaySeconds", "60" },
                    { "MessageRetentionPeriod", "86400" },
                },
            };

            var response = await client.CreateQueueAsync(request);
            Console.WriteLine($"Created a queue with URL : {response.QueueUrl}");

            return response;
        }

        /// <summary>
        /// Sends a message to an SQS queue.
        /// </summary>
        /// <param name="client">An SQS client object used to send the message.</param>
        /// <param name="queueUrl">The URL of the queue to which to send the
        /// message.</param>
        /// <param name="messageBody">A string representing the body of the
        /// message to be sent to the queue.</param>
        /// <param name="messageAttributes">Attributes for the message to be
        /// sent to the queue.</param>
        /// <returns>A SendMessageResponse object that contains information
        /// about the message that was sent.</returns>
        public static async Task<SendMessageResponse> SendMessage(
            IAmazonSQS client,
            string queueUrl,
            string messageBody,
            Dictionary<string, MessageAttributeValue> messageAttributes)
        {
            var sendMessageRequest = new SendMessageRequest
            {
                DelaySeconds = 10,
                MessageAttributes = messageAttributes,
                MessageBody = messageBody,
                QueueUrl = queueUrl,
            };

            var response = await client.SendMessageAsync(sendMessageRequest);
            Console.WriteLine($"Sent a message with id : {response.MessageId}");

            return response;
        }
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[CreateQueue](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/CreateQueue)」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_csharp_3_topic"></a>

次のコード例は、`DeleteMessage` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SQS#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューからメッセージを受信し、メッセージを削除します。  

```
        public static async Task Main()
        {
            // If the AWS Region you want to use is different from
            // the AWS Region defined for the default user, supply
            // the specify your AWS Region to the client constructor.
            var client = new AmazonSQSClient();
            string queueName = "Example_Queue";

            var queueUrl = await GetQueueUrl(client, queueName);
            Console.WriteLine($"The SQS queue's URL is {queueUrl}");

            var response = await ReceiveAndDeleteMessage(client, queueUrl);

            Console.WriteLine($"Message: {response.Messages[0]}");
        }

        /// <summary>
        /// Retrieve the queue URL for the queue named in the queueName
        /// property using the client object.
        /// </summary>
        /// <param name="client">The Amazon SQS client used to retrieve the
        /// queue URL.</param>
        /// <param name="queueName">A string representing  name of the queue
        /// for which to retrieve the URL.</param>
        /// <returns>The URL of the queue.</returns>
        public static async Task<string> GetQueueUrl(IAmazonSQS client, string queueName)
        {
            var request = new GetQueueUrlRequest
            {
                QueueName = queueName,
            };

            GetQueueUrlResponse response = await client.GetQueueUrlAsync(request);
            return response.QueueUrl;
        }

        /// <summary>
        /// Retrieves the message from the quque at the URL passed in the
        /// queueURL parameters using the client.
        /// </summary>
        /// <param name="client">The SQS client used to retrieve a message.</param>
        /// <param name="queueUrl">The URL of the queue from which to retrieve
        /// a message.</param>
        /// <returns>The response from the call to ReceiveMessageAsync.</returns>
        public static async Task<ReceiveMessageResponse> ReceiveAndDeleteMessage(IAmazonSQS client, string queueUrl)
        {
            // Receive a single message from the queue.
            var receiveMessageRequest = new ReceiveMessageRequest
            {
                AttributeNames = { "SentTimestamp" },
                MaxNumberOfMessages = 1,
                MessageAttributeNames = { "All" },
                QueueUrl = queueUrl,
                VisibilityTimeout = 0,
                WaitTimeSeconds = 0,
            };

            var receiveMessageResponse = await client.ReceiveMessageAsync(receiveMessageRequest);

            // Delete the received message from the queue.
            var deleteMessageRequest = new DeleteMessageRequest
            {
                QueueUrl = queueUrl,
                ReceiptHandle = receiveMessageResponse.Messages[0].ReceiptHandle,
            };

            await client.DeleteMessageAsync(deleteMessageRequest);

            return receiveMessageResponse;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteMessage](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/DeleteMessage)」を参照してください。

### `DeleteMessageBatch`
<a name="sqs_DeleteMessageBatch_csharp_3_topic"></a>

次のコード例は、`DeleteMessageBatch` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a batch of messages from a queue by its url.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteMessageBatchByUrl(string queueUrl, List<Message> messages)
    {
        var deleteRequest = new DeleteMessageBatchRequest()
        {
            QueueUrl = queueUrl,
            Entries = new List<DeleteMessageBatchRequestEntry>()
        };
        foreach (var message in messages)
        {
            deleteRequest.Entries.Add(new DeleteMessageBatchRequestEntry()
            {
                ReceiptHandle = message.ReceiptHandle,
                Id = message.MessageId
            });
        }

        var deleteResponse = await _amazonSQSClient.DeleteMessageBatchAsync(deleteRequest);

        return deleteResponse.Failed.Any();
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteMessageBatch](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/DeleteMessageBatch)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_csharp_3_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
URL を使用してキューを削除します。  

```
    /// <summary>
    /// Delete a queue by its URL.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteQueueByUrl(string queueUrl)
    {
        var deleteResponse = await _amazonSQSClient.DeleteQueueAsync(
            new DeleteQueueRequest()
            {
                QueueUrl = queueUrl
            });
        return deleteResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[DeleteQueue](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/DeleteQueue)」を参照してください。

### `GetQueueAttributes`
<a name="sqs_GetQueueAttributes_csharp_3_topic"></a>

次のコード例は、`GetQueueAttributes` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the ARN for a queue from its URL.
    /// </summary>
    /// <param name="queueUrl">The URL of the queue.</param>
    /// <returns>The ARN of the queue.</returns>
    public async Task<string> GetQueueArnByUrl(string queueUrl)
    {
        var getAttributesRequest = new GetQueueAttributesRequest()
        {
            QueueUrl = queueUrl,
            AttributeNames = new List<string>() { QueueAttributeName.QueueArn }
        };

        var getAttributesResponse = await _amazonSQSClient.GetQueueAttributesAsync(
            getAttributesRequest);

        return getAttributesResponse.QueueARN;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetQueueAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/GetQueueAttributes)」を参照してください。

### `GetQueueUrl`
<a name="sqs_GetQueueUrl_csharp_3_topic"></a>

次のコード例は、`GetQueueUrl` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SQS#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SQS;
    using Amazon.SQS.Model;

    public class GetQueueUrl
    {
        /// <summary>
        /// Initializes the Amazon SQS client object and then calls the
        /// GetQueueUrlAsync method to retrieve the URL of an Amazon SQS
        /// queue.
        /// </summary>
        public static async Task Main()
        {
            // If the Amazon SQS message queue is not in the same AWS Region as your
            // default user, you need to provide the AWS Region as a parameter to the
            // client constructor.
            var client = new AmazonSQSClient();

            string queueName = "New-Example-Queue";

            try
            {
                var response = await client.GetQueueUrlAsync(queueName);

                if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
                {
                    Console.WriteLine($"The URL for {queueName} is: {response.QueueUrl}");
                }
            }
            catch (QueueDoesNotExistException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine($"The queue {queueName} was not found.");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetQueueUrl](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/GetQueueUrl)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_csharp_3_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
URL を使用してキューからメッセージを受信します。  

```
    /// <summary>
    /// Receive messages from a queue by its URL.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>The list of messages.</returns>
    public async Task<List<Message>> ReceiveMessagesByUrl(string queueUrl, int maxMessages)
    {
        // Setting WaitTimeSeconds to non-zero enables long polling.
        // For information about long polling, see
        // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html
        var messageResponse = await _amazonSQSClient.ReceiveMessageAsync(
            new ReceiveMessageRequest()
            {
                QueueUrl = queueUrl,
                MaxNumberOfMessages = maxMessages,
                WaitTimeSeconds = 1
            });
        return messageResponse.Messages;
    }
```
Amazon SQS キューからメッセージを受信し、メッセージを削除します。  

```
        public static async Task Main()
        {
            // If the AWS Region you want to use is different from
            // the AWS Region defined for the default user, supply
            // the specify your AWS Region to the client constructor.
            var client = new AmazonSQSClient();
            string queueName = "Example_Queue";

            var queueUrl = await GetQueueUrl(client, queueName);
            Console.WriteLine($"The SQS queue's URL is {queueUrl}");

            var response = await ReceiveAndDeleteMessage(client, queueUrl);

            Console.WriteLine($"Message: {response.Messages[0]}");
        }

        /// <summary>
        /// Retrieve the queue URL for the queue named in the queueName
        /// property using the client object.
        /// </summary>
        /// <param name="client">The Amazon SQS client used to retrieve the
        /// queue URL.</param>
        /// <param name="queueName">A string representing  name of the queue
        /// for which to retrieve the URL.</param>
        /// <returns>The URL of the queue.</returns>
        public static async Task<string> GetQueueUrl(IAmazonSQS client, string queueName)
        {
            var request = new GetQueueUrlRequest
            {
                QueueName = queueName,
            };

            GetQueueUrlResponse response = await client.GetQueueUrlAsync(request);
            return response.QueueUrl;
        }

        /// <summary>
        /// Retrieves the message from the quque at the URL passed in the
        /// queueURL parameters using the client.
        /// </summary>
        /// <param name="client">The SQS client used to retrieve a message.</param>
        /// <param name="queueUrl">The URL of the queue from which to retrieve
        /// a message.</param>
        /// <returns>The response from the call to ReceiveMessageAsync.</returns>
        public static async Task<ReceiveMessageResponse> ReceiveAndDeleteMessage(IAmazonSQS client, string queueUrl)
        {
            // Receive a single message from the queue.
            var receiveMessageRequest = new ReceiveMessageRequest
            {
                AttributeNames = { "SentTimestamp" },
                MaxNumberOfMessages = 1,
                MessageAttributeNames = { "All" },
                QueueUrl = queueUrl,
                VisibilityTimeout = 0,
                WaitTimeSeconds = 0,
            };

            var receiveMessageResponse = await client.ReceiveMessageAsync(receiveMessageRequest);

            // Delete the received message from the queue.
            var deleteMessageRequest = new DeleteMessageRequest
            {
                QueueUrl = queueUrl,
                ReceiptHandle = receiveMessageResponse.Messages[0].ReceiptHandle,
            };

            await client.DeleteMessageAsync(deleteMessageRequest);

            return receiveMessageResponse;
        }
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[ReceiveMessage](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/ReceiveMessage)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_csharp_3_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SQS#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューを作成して、そこにメッセージを送信します。  

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon;
    using Amazon.SQS;
    using Amazon.SQS.Model;

    public class CreateSendExample
    {
        // Specify your AWS Region (an example Region is shown).
        private static readonly string QueueName = "Example_Queue";
        private static readonly RegionEndpoint ServiceRegion = RegionEndpoint.USWest2;
        private static IAmazonSQS client;

        public static async Task Main()
        {
            client = new AmazonSQSClient(ServiceRegion);
            var createQueueResponse = await CreateQueue(client, QueueName);

            string queueUrl = createQueueResponse.QueueUrl;

            Dictionary<string, MessageAttributeValue> messageAttributes = new Dictionary<string, MessageAttributeValue>
            {
                { "Title",   new MessageAttributeValue { DataType = "String", StringValue = "The Whistler" } },
                { "Author",  new MessageAttributeValue { DataType = "String", StringValue = "John Grisham" } },
                { "WeeksOn", new MessageAttributeValue { DataType = "Number", StringValue = "6" } },
            };

            string messageBody = "Information about current NY Times fiction bestseller for week of 12/11/2016.";

            var sendMsgResponse = await SendMessage(client, queueUrl, messageBody, messageAttributes);
        }

        /// <summary>
        /// Creates a new Amazon SQS queue using the queue name passed to it
        /// in queueName.
        /// </summary>
        /// <param name="client">An SQS client object used to send the message.</param>
        /// <param name="queueName">A string representing the name of the queue
        /// to create.</param>
        /// <returns>A CreateQueueResponse that contains information about the
        /// newly created queue.</returns>
        public static async Task<CreateQueueResponse> CreateQueue(IAmazonSQS client, string queueName)
        {
            var request = new CreateQueueRequest
            {
                QueueName = queueName,
                Attributes = new Dictionary<string, string>
                {
                    { "DelaySeconds", "60" },
                    { "MessageRetentionPeriod", "86400" },
                },
            };

            var response = await client.CreateQueueAsync(request);
            Console.WriteLine($"Created a queue with URL : {response.QueueUrl}");

            return response;
        }

        /// <summary>
        /// Sends a message to an SQS queue.
        /// </summary>
        /// <param name="client">An SQS client object used to send the message.</param>
        /// <param name="queueUrl">The URL of the queue to which to send the
        /// message.</param>
        /// <param name="messageBody">A string representing the body of the
        /// message to be sent to the queue.</param>
        /// <param name="messageAttributes">Attributes for the message to be
        /// sent to the queue.</param>
        /// <returns>A SendMessageResponse object that contains information
        /// about the message that was sent.</returns>
        public static async Task<SendMessageResponse> SendMessage(
            IAmazonSQS client,
            string queueUrl,
            string messageBody,
            Dictionary<string, MessageAttributeValue> messageAttributes)
        {
            var sendMessageRequest = new SendMessageRequest
            {
                DelaySeconds = 10,
                MessageAttributes = messageAttributes,
                MessageBody = messageBody,
                QueueUrl = queueUrl,
            };

            var response = await client.SendMessageAsync(sendMessageRequest);
            Console.WriteLine($"Sent a message with id : {response.MessageId}");

            return response;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[SendMessage](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/SendMessage)」を参照してください。**

### `SetQueueAttributes`
<a name="sqs_SetQueueAttributes_csharp_3_topic"></a>

次のコード例は、`SetQueueAttributes` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
トピックのキューのポリシー属性を設定します。  

```
    /// <summary>
    /// Set the policy attribute of a queue for a topic.
    /// </summary>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="queueUrl">The url for the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl)
    {
        var queuePolicy = "{" +
                                "\"Version\": \"2012-10-17\"," +
                                "\"Statement\": [{" +
                                     "\"Effect\": \"Allow\"," +
                                     "\"Principal\": {" +
                                         $"\"Service\": " +
                                             "\"sns.amazonaws.com\"" +
                                            "}," +
                                     "\"Action\": \"sqs:SendMessage\"," +
                                     $"\"Resource\": \"{queueArn}\"," +
                                      "\"Condition\": {" +
                                           "\"ArnEquals\": {" +
                                                $"\"aws:SourceArn\": \"{topicArn}\"" +
                                            "}" +
                                        "}" +
                                "}]" +
                             "}";
        var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync(
            new SetQueueAttributesRequest()
            {
                QueueUrl = queueUrl,
                Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } }
            });
        return attributesResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[SetQueueAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/SetQueueAttributes)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
/// <summary>
/// Console application to run a feature scenario for topics and queues.
/// </summary>
public static class TopicsAndQueues
{
    private static bool _useFifoTopic = false;
    private static bool _useContentBasedDeduplication = false;
    private static string _topicName = null!;
    private static string _topicArn = null!;

    private static readonly int _queueCount = 2;
    private static readonly string[] _queueUrls = new string[_queueCount];
    private static readonly string[] _subscriptionArns = new string[_queueCount];
    private static readonly string[] _tones = { "cheerful", "funny", "serious", "sincere" };
    public static SNSWrapper SnsWrapper { get; set; } = null!;
    public static SQSWrapper SqsWrapper { get; set; } = null!;
    public static bool UseConsole { get; set; } = true;
    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon EventBridge.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonSQS>()
                    .AddAWSService<IAmazonSimpleNotificationService>()
                    .AddTransient<SNSWrapper>()
                    .AddTransient<SQSWrapper>()
            )
            .Build();

        ServicesSetup(host);
        PrintDescription();

        await RunScenario();

    }

    /// <summary>
    /// Populate the services for use within the console application.
    /// </summary>
    /// <param name="host">The services host.</param>
    private static void ServicesSetup(IHost host)
    {
        SnsWrapper = host.Services.GetRequiredService<SNSWrapper>();
        SqsWrapper = host.Services.GetRequiredService<SQSWrapper>();
    }

    /// <summary>
    /// Run the scenario for working with topics and queues.
    /// </summary>
    /// <returns>True if successful.</returns>
    public static async Task<bool> RunScenario()
    {
        try
        {
            await SetupTopic();

            await SetupQueues();

            await PublishMessages();

            foreach (var queueUrl in _queueUrls)
            {
                var messages = await PollForMessages(queueUrl);
                if (messages.Any())
                {
                    await DeleteMessages(queueUrl, messages);
                }
            }
            await CleanupResources();

            Console.WriteLine("Messaging with topics and queues scenario is complete.");
            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"There was a problem running the scenario: {ex.Message}");
            await CleanupResources();
            Console.WriteLine(new string('-', 80));
            return false;
        }
    }

    /// <summary>
    /// Print a description for the tasks in the scenario.
    /// </summary>
    /// <returns>Async task.</returns>
    private static void PrintDescription()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Welcome to messaging with topics and queues.");

        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"In this scenario, you will create an SNS topic and subscribe {_queueCount} SQS queues to the topic." +
                          $"\r\nYou can select from several options for configuring the topic and the subscriptions for the 2 queues." +
                          $"\r\nYou can then post to the topic and see the results in the queues.\r\n");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Set up the SNS topic to be used with the queues.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task<string> SetupTopic()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"SNS topics can be configured as FIFO (First-In-First-Out)." +
                          $"\r\nFIFO topics deliver messages in order and support deduplication and message filtering." +
                          $"\r\nYou can then post to the topic and see the results in the queues.\r\n");

        _useFifoTopic = GetYesNoResponse("Would you like to work with FIFO topics?");

        if (_useFifoTopic)
        {
            Console.WriteLine(new string('-', 80));
            _topicName = GetUserResponse("Enter a name for your SNS topic: ", "example-topic");
            Console.WriteLine(
                "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.\r\n");

            Console.WriteLine(new string('-', 80));
            Console.WriteLine($"Because you have chosen a FIFO topic, deduplication is supported." +
                              $"\r\nDeduplication IDs are either set in the message or automatically generated " +
                              $"\r\nfrom content using a hash function.\r\n" +
                              $"\r\nIf a message is successfully published to an SNS FIFO topic, any message " +
                              $"\r\npublished and determined to have the same deduplication ID, " +
                              $"\r\nwithin the five-minute deduplication interval, is accepted but not delivered.\r\n" +
                              $"\r\nFor more information about deduplication, " +
                              $"\r\nsee https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.");

            _useContentBasedDeduplication = GetYesNoResponse("Use content-based deduplication instead of entering a deduplication ID?");
            Console.WriteLine(new string('-', 80));
        }

        _topicArn = await SnsWrapper.CreateTopicWithName(_topicName, _useFifoTopic, _useContentBasedDeduplication);

        Console.WriteLine($"Your new topic with the name {_topicName}" +
                          $"\r\nand Amazon Resource Name (ARN) {_topicArn}" +
                          $"\r\nhas been created.\r\n");

        Console.WriteLine(new string('-', 80));
        return _topicArn;
    }

    /// <summary>
    /// Set up the queues.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task SetupQueues()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Now you will create {_queueCount} Amazon Simple Queue Service (Amazon SQS) queues to subscribe to the topic.");

        // Repeat this section for each queue.
        for (int i = 0; i < _queueCount; i++)
        {
            var queueName = GetUserResponse("Enter a name for an Amazon SQS queue: ", $"example-queue-{i}");
            if (_useFifoTopic)
            {
                // Only explain this once.
                if (i == 0)
                {
                    Console.WriteLine(
                        "Because you have selected a FIFO topic, '.fifo' must be appended to the queue name.");
                }

                var queueUrl = await SqsWrapper.CreateQueueWithName(queueName, _useFifoTopic);

                _queueUrls[i] = queueUrl;

                Console.WriteLine($"Your new queue with the name {queueName}" +
                                  $"\r\nand queue URL {queueUrl}" +
                                  $"\r\nhas been created.\r\n");

                if (i == 0)
                {
                    Console.WriteLine(
                        $"The queue URL is used to retrieve the queue ARN,\r\n" +
                        $"which is used to create a subscription.");
                    Console.WriteLine(new string('-', 80));
                }

                var queueArn = await SqsWrapper.GetQueueArnByUrl(queueUrl);

                if (i == 0)
                {
                    Console.WriteLine(
                        $"An AWS Identity and Access Management (IAM) policy must be attached to an SQS queue, enabling it to receive\r\n" +
                        $"messages from an SNS topic");
                }

                await SqsWrapper.SetQueuePolicyForTopic(queueArn, _topicArn, queueUrl);

                await SetupFilters(i, queueArn, queueName);
            }
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Set up filters with user options for a queue.
    /// </summary>
    /// <param name="queueCount">The number of this queue.</param>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <param name="queueName">The name of the queue.</param>
    /// <returns>Async Task.</returns>
    public static async Task SetupFilters(int queueCount, string queueArn, string queueName)
    {
        if (_useFifoTopic)
        {
            Console.WriteLine(new string('-', 80));
            // Only explain this once.
            if (queueCount == 0)
            {
                Console.WriteLine(
                    "Subscriptions to a FIFO topic can have filters." +
                    "If you add a filter to this subscription, then only the filtered messages " +
                    "will be received in the queue.");

                Console.WriteLine(
                    "For information about message filtering, " +
                    "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html");

                Console.WriteLine(
                    "For this example, you can filter messages by a" +
                    "TONE attribute.");
            }

            var useFilter = GetYesNoResponse($"Filter messages for {queueName}'s subscription to the topic?");

            string? filterPolicy = null;
            if (useFilter)
            {
                filterPolicy = CreateFilterPolicy();
            }
            var subscriptionArn = await SnsWrapper.SubscribeTopicWithFilter(_topicArn, filterPolicy,
                queueArn);
            _subscriptionArns[queueCount] = subscriptionArn;

            Console.WriteLine(
                $"The queue {queueName} has been subscribed to the topic {_topicName} " +
                $"with the subscription ARN {subscriptionArn}");
            Console.WriteLine(new string('-', 80));
        }
    }

    /// <summary>
    /// Use user input to create a filter policy for a subscription.
    /// </summary>
    /// <returns>The serialized filter policy.</returns>
    public static string CreateFilterPolicy()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine(
            $"You can filter messages by one or more of the following" +
            $"TONE attributes.");

        List<string> filterSelections = new List<string>();

        var selectionNumber = 0;
        do
        {
            Console.WriteLine(
                $"Enter a number to add a TONE filter, or enter 0 to stop adding filters.");
            for (int i = 0; i < _tones.Length; i++)
            {
                Console.WriteLine($"\t{i + 1}. {_tones[i]}");
            }

            var selection = GetUserResponse("", filterSelections.Any() ? "0" : "1");
            int.TryParse(selection, out selectionNumber);
            if (selectionNumber > 0 && !filterSelections.Contains(_tones[selectionNumber - 1]))
            {
                filterSelections.Add(_tones[selectionNumber - 1]);
            }
        } while (selectionNumber != 0);

        var filters = new Dictionary<string, List<string>>
        {
            { "tone", filterSelections }
        };
        string filterPolicy = JsonSerializer.Serialize(filters);
        return filterPolicy;
    }

    /// <summary>
    /// Publish messages using user settings.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task PublishMessages()
    {
        Console.WriteLine("Now we can publish messages.");

        var keepSendingMessages = true;
        string? deduplicationId = null;
        string? toneAttribute = null;
        while (keepSendingMessages)
        {
            Console.WriteLine();
            var message = GetUserResponse("Enter a message to publish.", "This is a sample message");

            if (_useFifoTopic)
            {
                Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." +
                                  "\r\nAll messages within the same group will be received in the order " +
                                  "they were published.");

                Console.WriteLine();
                var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1");

                if (!_useContentBasedDeduplication)
                {
                    Console.WriteLine("Because you are not using content-based deduplication, " +
                                      "you must enter a deduplication ID.");

                    Console.WriteLine("Enter a deduplication ID for this message.");
                    deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1");
                }

                if (GetYesNoResponse("Add an attribute to this message?"))
                {
                    Console.WriteLine("Enter a number for an attribute.");
                    for (int i = 0; i < _tones.Length; i++)
                    {
                        Console.WriteLine($"\t{i + 1}. {_tones[i]}");
                    }

                    var selection = GetUserResponse("", "1");
                    int.TryParse(selection, out var selectionNumber);

                    if (selectionNumber > 0 && selectionNumber < _tones.Length)
                    {
                        toneAttribute = _tones[selectionNumber - 1];
                    }
                }

                var messageID = await SnsWrapper.PublishToTopicWithAttribute(
                    _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId);

                Console.WriteLine($"Message published with id {messageID}.");
            }

            keepSendingMessages = GetYesNoResponse("Send another message?", false);
        }
    }

    /// <summary>
    /// Poll for the published messages to see the results of the user's choices.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task<List<Message>> PollForMessages(string queueUrl)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Now the SQS queue at {queueUrl} will be polled to retrieve the messages." +
                          "\r\nPress any key to continue.");
        if (UseConsole)
        {
            Console.ReadLine();
        }

        var moreMessages = true;
        var messages = new List<Message>();
        while (moreMessages)
        {
            var newMessages = await SqsWrapper.ReceiveMessagesByUrl(queueUrl, 10);

            moreMessages = newMessages.Any();
            if (moreMessages)
            {
                messages.AddRange(newMessages);
            }
        }

        Console.WriteLine($"{messages.Count} message(s) were received by the queue at {queueUrl}.");

        foreach (var message in messages)
        {
            Console.WriteLine("\tMessage:" +
                              $"\n\t{message.Body}");
        }

        Console.WriteLine(new string('-', 80));
        return messages;
    }

    /// <summary>
    /// Delete the message using handles in a batch.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task DeleteMessages(string queueUrl, List<Message> messages)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Now we can delete the messages in this queue in a batch.");
        await SqsWrapper.DeleteMessageBatchByUrl(queueUrl, messages);
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Clean up the resources from the scenario.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CleanupResources()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Clean up resources.");

        try
        {
            foreach (var queueUrl in _queueUrls)
            {
                if (!string.IsNullOrEmpty(queueUrl))
                {
                    var deleteQueue =
                        GetYesNoResponse($"Delete queue with url {queueUrl}?");
                    if (deleteQueue)
                    {
                        await SqsWrapper.DeleteQueueByUrl(queueUrl);
                    }
                }
            }

            foreach (var subscriptionArn in _subscriptionArns)
            {
                if (!string.IsNullOrEmpty(subscriptionArn))
                {
                    await SnsWrapper.UnsubscribeByArn(subscriptionArn);
                }
            }

            var deleteTopic = GetYesNoResponse($"Delete topic {_topicName}?");
            if (deleteTopic)
            {
                await SnsWrapper.DeleteTopicByArn(_topicArn);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Unable to clean up resources. Here's why: {ex.Message}.");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <param name="defaultAnswer">Optional default answer to use.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question, bool defaultAnswer = true)
    {
        if (UseConsole)
        {
            Console.WriteLine(question);
            var ynResponse = Console.ReadLine();
            var response = ynResponse != null &&
                           ynResponse.Equals("y",
                               StringComparison.InvariantCultureIgnoreCase);
            return response;
        }
        // If not using the console, use the default.
        return defaultAnswer;
    }

    /// <summary>
    /// Helper method to get a string response from the user through the console.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <param name="defaultAnswer">Optional default answer to use.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static string GetUserResponse(string question, string defaultAnswer)
    {
        if (UseConsole)
        {
            var response = "";
            while (string.IsNullOrEmpty(response))
            {
                Console.WriteLine(question);
                response = Console.ReadLine();
            }
            return response;
        }
        // If not using the console, use the default.
        return defaultAnswer;
    }
}
```
 Amazon SQS オペレーションをラップするクラスを作成します。  

```
/// <summary>
/// Wrapper for Amazon Simple Queue Service (SQS) operations.
/// </summary>
public class SQSWrapper
{
    private readonly IAmazonSQS _amazonSQSClient;

    /// <summary>
    /// Constructor for the Amazon SQS wrapper.
    /// </summary>
    /// <param name="amazonSQS">The injected Amazon SQS client.</param>
    public SQSWrapper(IAmazonSQS amazonSQS)
    {
        _amazonSQSClient = amazonSQS;
    }

    /// <summary>
    /// Create a queue with a specific name.
    /// </summary>
    /// <param name="queueName">The name for the queue.</param>
    /// <param name="useFifoQueue">True to use a FIFO queue.</param>
    /// <returns>The url for the queue.</returns>
    public async Task<string> CreateQueueWithName(string queueName, bool useFifoQueue)
    {
        int maxMessage = 256 * 1024;
        var queueAttributes = new Dictionary<string, string>
        {
            {
                QueueAttributeName.MaximumMessageSize,
                maxMessage.ToString()
            }
        };

        var createQueueRequest = new CreateQueueRequest()
        {
            QueueName = queueName,
            Attributes = queueAttributes
        };

        if (useFifoQueue)
        {
            // Update the name if it is not correct for a FIFO queue.
            if (!queueName.EndsWith(".fifo"))
            {
                createQueueRequest.QueueName = queueName + ".fifo";
            }

            // Add an attribute for a FIFO queue.
            createQueueRequest.Attributes.Add(
                QueueAttributeName.FifoQueue, "true");
        }

        var createResponse = await _amazonSQSClient.CreateQueueAsync(
            new CreateQueueRequest()
            {
                QueueName = queueName
            });
        return createResponse.QueueUrl;
    }

    /// <summary>
    /// Get the ARN for a queue from its URL.
    /// </summary>
    /// <param name="queueUrl">The URL of the queue.</param>
    /// <returns>The ARN of the queue.</returns>
    public async Task<string> GetQueueArnByUrl(string queueUrl)
    {
        var getAttributesRequest = new GetQueueAttributesRequest()
        {
            QueueUrl = queueUrl,
            AttributeNames = new List<string>() { QueueAttributeName.QueueArn }
        };

        var getAttributesResponse = await _amazonSQSClient.GetQueueAttributesAsync(
            getAttributesRequest);

        return getAttributesResponse.QueueARN;
    }

    /// <summary>
    /// Set the policy attribute of a queue for a topic.
    /// </summary>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="queueUrl">The url for the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl)
    {
        var queuePolicy = "{" +
                                "\"Version\": \"2012-10-17\"," +
                                "\"Statement\": [{" +
                                     "\"Effect\": \"Allow\"," +
                                     "\"Principal\": {" +
                                         $"\"Service\": " +
                                             "\"sns.amazonaws.com\"" +
                                            "}," +
                                     "\"Action\": \"sqs:SendMessage\"," +
                                     $"\"Resource\": \"{queueArn}\"," +
                                      "\"Condition\": {" +
                                           "\"ArnEquals\": {" +
                                                $"\"aws:SourceArn\": \"{topicArn}\"" +
                                            "}" +
                                        "}" +
                                "}]" +
                             "}";
        var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync(
            new SetQueueAttributesRequest()
            {
                QueueUrl = queueUrl,
                Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } }
            });
        return attributesResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Receive messages from a queue by its URL.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>The list of messages.</returns>
    public async Task<List<Message>> ReceiveMessagesByUrl(string queueUrl, int maxMessages)
    {
        // Setting WaitTimeSeconds to non-zero enables long polling.
        // For information about long polling, see
        // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html
        var messageResponse = await _amazonSQSClient.ReceiveMessageAsync(
            new ReceiveMessageRequest()
            {
                QueueUrl = queueUrl,
                MaxNumberOfMessages = maxMessages,
                WaitTimeSeconds = 1
            });
        return messageResponse.Messages;
    }

    /// <summary>
    /// Delete a batch of messages from a queue by its url.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteMessageBatchByUrl(string queueUrl, List<Message> messages)
    {
        var deleteRequest = new DeleteMessageBatchRequest()
        {
            QueueUrl = queueUrl,
            Entries = new List<DeleteMessageBatchRequestEntry>()
        };
        foreach (var message in messages)
        {
            deleteRequest.Entries.Add(new DeleteMessageBatchRequestEntry()
            {
                ReceiptHandle = message.ReceiptHandle,
                Id = message.MessageId
            });
        }

        var deleteResponse = await _amazonSQSClient.DeleteMessageBatchAsync(deleteRequest);

        return deleteResponse.Failed.Any();
    }

    /// <summary>
    /// Delete a queue by its URL.
    /// </summary>
    /// <param name="queueUrl">The url of the queue.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteQueueByUrl(string queueUrl)
    {
        var deleteResponse = await _amazonSQSClient.DeleteQueueAsync(
            new DeleteQueueRequest()
            {
                QueueUrl = queueUrl
            });
        return deleteResponse.HttpStatusCode == HttpStatusCode.OK;
    }
}
```
 Amazon SNS オペレーションをラップするクラスを作成します。  

```
/// <summary>
/// Wrapper for Amazon Simple Notification Service (SNS) operations.
/// </summary>
public class SNSWrapper
{
    private readonly IAmazonSimpleNotificationService _amazonSNSClient;

    /// <summary>
    /// Constructor for the Amazon SNS wrapper.
    /// </summary>
    /// <param name="amazonSQS">The injected Amazon SNS client.</param>
    public SNSWrapper(IAmazonSimpleNotificationService amazonSNS)
    {
        _amazonSNSClient = amazonSNS;
    }

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

    /// <summary>
    /// Subscribe a queue to a topic with optional filters.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param>
    /// <param name="queueArn">The ARN of the queue.</param>
    /// <returns>The ARN of the new subscription.</returns>
    public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn)
    {
        var subscribeRequest = new SubscribeRequest()
        {
            TopicArn = topicArn,
            Protocol = "sqs",
            Endpoint = queueArn
        };

        if (!string.IsNullOrEmpty(filterPolicy))
        {
            subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } };
        }

        var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest);
        return subscribeResponse.SubscriptionArn;
    }

    /// <summary>
    /// Publish a message to a topic with an attribute and optional deduplication and group IDs.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="message">The message to publish.</param>
    /// <param name="attributeName">The optional attribute for the message.</param>
    /// <param name="attributeValue">The optional attribute value for the message.</param>
    /// <param name="deduplicationId">The optional deduplication ID for the message.</param>
    /// <param name="groupId">The optional group ID for the message.</param>
    /// <returns>The ID of the message published.</returns>
    public async Task<string> PublishToTopicWithAttribute(
        string topicArn,
        string message,
        string? attributeName = null,
        string? attributeValue = null,
        string? deduplicationId = null,
        string? groupId = null)
    {
        var publishRequest = new PublishRequest()
        {
            TopicArn = topicArn,
            Message = message,
            MessageDeduplicationId = deduplicationId,
            MessageGroupId = groupId
        };

        if (attributeValue != null)
        {
            // Add the string attribute if it exists.
            publishRequest.MessageAttributes =
                new Dictionary<string, MessageAttributeValue>
                {
                    { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} }
                };
        }

        var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest);
        return publishResponse.MessageId;
    }


    /// <summary>
    /// Unsubscribe from a topic by a subscription ARN.
    /// </summary>
    /// <param name="subscriptionArn">The ARN of the subscription.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> UnsubscribeByArn(string subscriptionArn)
    {
        var unsubscribeResponse = await _amazonSNSClient.UnsubscribeAsync(
            new UnsubscribeRequest()
            {
                SubscriptionArn = subscriptionArn
            });
        return unsubscribeResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Delete a topic by its topic ARN.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteTopicByArn(string topicArn)
    {
        var deleteResponse = await _amazonSNSClient.DeleteTopicAsync(
            new DeleteTopicRequest()
            {
                TopicArn = topicArn
            });
        return deleteResponse.HttpStatusCode == HttpStatusCode.OK;
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/DotNetSDKV3/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Unsubscribe)

### Amazon SQS で .NET の AWS メッセージ処理フレームワークを使用する
<a name="cross_MessageProcessingFrameworkTutorial_csharp_3_topic"></a>

次のコード例は、Message Processing Framework for .NET を使用して Amazon SQS AWS メッセージを発行および受信するアプリケーションを作成する方法を示しています。

**SDK for .NET**  
Message AWS Processing Framework for .NET のチュートリアルを提供します。このチュートリアルでは、ユーザーが Amazon SQS メッセージを発行できるウェブアプリケーションと、メッセージを受信するコマンドラインアプリケーションを作成します。  
完全なソースコードとセットアップと実行の手順については、 AWS SDK for .NET デベロッパーガイドの[チュートリアル全体](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/msg-proc-fw-get-started.html)と [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/MessageProcessingFramework) の例を参照してください。  

**この例で使用されているサービス**
+ Amazon SQS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_csharp_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
﻿using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;


// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace SqsIntegrationSampleCode
{
    public async Task FunctionHandler(SQSEvent evnt, ILambdaContext context)
    {
        foreach (var message in evnt.Records)
        {
            await ProcessMessageAsync(message, context);
        }

        context.Logger.LogInformation("done");
    }

    private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context)
    {
        try
        {
            context.Logger.LogInformation($"Processed message {message.Body}");

            // TODO: Do interesting work based on the new message
            await Task.CompletedTask;
        }
        catch (Exception e)
        {
            //You can use Dead Letter Queue to handle failures. By configuring a Lambda DLQ.
            context.Logger.LogError($"An error occurred");
            throw;
        }

    }
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_csharp_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
.NET を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using Amazon.Lambda.Core;
using Amazon.Lambda.SQSEvents;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace sqsSample;

public class Function
{
    public async Task<SQSBatchResponse> FunctionHandler(SQSEvent evnt, ILambdaContext context)
    {
        List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new List<SQSBatchResponse.BatchItemFailure>();
        foreach(var message in evnt.Records)
        {
            try
            {
                //process your message
                await ProcessMessageAsync(message, context);
            }
            catch (System.Exception)
            {
                //Add failed message identifier to the batchItemFailures list
                batchItemFailures.Add(new SQSBatchResponse.BatchItemFailure{ItemIdentifier=message.MessageId}); 
            }
        }
        return new SQSBatchResponse(batchItemFailures);
    }

    private async Task ProcessMessageAsync(SQSEvent.SQSMessage message, ILambdaContext context)
    {
        if (String.IsNullOrEmpty(message.Body))
        {
            throw new Exception("No Body in SQS Message.");
        }
        context.Logger.LogInformation($"Processed message {message.Body}");
        // TODO: Do interesting work based on the new message
        await Task.CompletedTask;
    }
}
```

# を使用した Step Functions の例 SDK for .NET
<a name="csharp_3_sfn_code_examples"></a>

次のコード例は、Step Functions AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Step Functions
<a name="sfn_Hello_csharp_3_topic"></a>

次のコード例は、Step Functions の使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
namespace StepFunctionsActions;

using Amazon.StepFunctions;
using Amazon.StepFunctions.Model;

public class HelloStepFunctions
{
    static async Task Main()
    {
        var stepFunctionsClient = new AmazonStepFunctionsClient();

        Console.Clear();
        Console.WriteLine("Welcome to AWS Step Functions");
        Console.WriteLine("Let's list up to 10 of your state machines:");
        var stateMachineListRequest = new ListStateMachinesRequest { MaxResults = 10 };

        // Get information for up to 10 Step Functions state machines.
        var response = await stepFunctionsClient.ListStateMachinesAsync(stateMachineListRequest);

        if (response.StateMachines.Count > 0)
        {
            response.StateMachines.ForEach(stateMachine =>
            {
                Console.WriteLine($"State Machine Name: {stateMachine.Name}\tAmazon Resource Name (ARN): {stateMachine.StateMachineArn}");
            });
        }
        else
        {
            Console.WriteLine("\tNo state machines were found.");
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListStateMachines](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/ListStateMachines)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="sfn_Scenario_GetStartedStateMachines_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ アクティビティを作成します。
+ 以前に作成したアクティビティをステップとして含む Amazon States Language 定義からステートマシンを作成します。
+ ステートマシンを実行し、ユーザー入力でアクティビティに応答します。
+ 実行が完了したら最終ステータスと出力を取得して、リソースをクリーンアップします。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
global using System.Text.Json;
global using Amazon.StepFunctions;
global using Microsoft.Extensions.Configuration;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;
global using StepFunctionsActions;
global using LogLevel = Microsoft.Extensions.Logging.LogLevel;



using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.StepFunctions.Model;

namespace StepFunctionsBasics;

public class StepFunctionsBasics
{
    private static ILogger _logger = null!;
    private static IConfigurationRoot _configuration = null!;
    private static IAmazonIdentityManagementService _iamService = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for AWS Step Functions.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonStepFunctions>()
                    .AddAWSService<IAmazonIdentityManagementService>()
                    .AddTransient<StepFunctionsWrapper>()
            )
            .Build();

        _logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<StepFunctionsBasics>();

        // Load configuration settings.
        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        var activityName = _configuration["ActivityName"];
        var stateMachineName = _configuration["StateMachineName"];

        var roleName = _configuration["RoleName"];
        var repoBaseDir = _configuration["RepoBaseDir"];
        var jsonFilePath = _configuration["JsonFilePath"];
        var jsonFileName = _configuration["JsonFileName"];

        var uiMethods = new UiMethods();
        var stepFunctionsWrapper = host.Services.GetRequiredService<StepFunctionsWrapper>();

        _iamService = host.Services.GetRequiredService<IAmazonIdentityManagementService>();

        // Load definition for the state machine from a JSON file.
        var stateDefinitionJson = File.ReadAllText($"{repoBaseDir}{jsonFilePath}{jsonFileName}");

        Console.Clear();
        uiMethods.DisplayOverview();
        uiMethods.PressEnter();

        uiMethods.DisplayTitle("Create activity");
        Console.WriteLine("Let's start by creating an activity.");
        string activityArn;
        string stateMachineArn;

        // Check to see if the activity already exists.
        var activityList = await stepFunctionsWrapper.ListActivitiesAsync();
        var existingActivity = activityList.FirstOrDefault(activity => activity.Name == activityName);
        if (existingActivity is not null)
        {
            activityArn = existingActivity.ActivityArn;
            Console.WriteLine($"Activity, {activityName}, already exists.");
        }
        else
        {
            activityArn = await stepFunctionsWrapper.CreateActivity(activityName);
        }

        // Swap the placeholder in the JSON file with the Amazon Resource Name (ARN)
        // of the recently created activity.
        var stateDefinition = stateDefinitionJson.Replace("{{DOC_EXAMPLE_ACTIVITY_ARN}}", activityArn);

        uiMethods.DisplayTitle("Create state machine");
        Console.WriteLine("Now we'll create a state machine.");

        // Find or create an IAM role that can be assumed by Step Functions.
        var role = await GetOrCreateStateMachineRole(roleName);

        // See if the state machine already exists.
        var stateMachineList = await stepFunctionsWrapper.ListStateMachinesAsync();
        var existingStateMachine =
            stateMachineList.FirstOrDefault(stateMachine => stateMachine.Name == stateMachineName);
        if (existingStateMachine is not null)
        {
            Console.WriteLine($"State machine, {stateMachineName}, already exists.");
            stateMachineArn = existingStateMachine.StateMachineArn;
        }
        else
        {
            // Create the state machine.
            stateMachineArn =
                await stepFunctionsWrapper.CreateStateMachine(stateMachineName, stateDefinition, role.Arn);
            uiMethods.PressEnter();
        }

        Console.WriteLine("The state machine has been created.");
        var describeStateMachineResponse = await stepFunctionsWrapper.DescribeStateMachineAsync(stateMachineArn);

        Console.WriteLine($"{describeStateMachineResponse.Name}\t{describeStateMachineResponse.StateMachineArn}");
        Console.WriteLine($"Current status: {describeStateMachineResponse.Status}");
        Console.WriteLine($"Amazon Resource Name (ARN) of the role assumed by the state machine: {describeStateMachineResponse.RoleArn}");

        var userName = string.Empty;
        Console.Write("Before we start the state machine, tell me what should ChatSFN call you? ");
        userName = Console.ReadLine();

        // Keep asking until the user enters a string value.
        while (string.IsNullOrEmpty(userName))
        {
            Console.Write("Enter your name: ");
            userName = Console.ReadLine();
        }

        var executionJson = @"{""name"": """ + userName + @"""}";

        // Start the state machine execution.
        Console.WriteLine("Now we'll start execution of the state machine.");
        var executionArn = await stepFunctionsWrapper.StartExecutionAsync(executionJson, stateMachineArn);
        Console.WriteLine("State machine started.");

        Console.WriteLine($"Thank you, {userName}. Now let's get started...");
        uiMethods.PressEnter();

        uiMethods.DisplayTitle("ChatSFN");

        var isDone = false;
        var response = new GetActivityTaskResponse();
        var taskToken = string.Empty;
        var userChoice = string.Empty;

        while (!isDone)
        {
            response = await stepFunctionsWrapper.GetActivityTaskAsync(activityArn, "MvpWorker");
            taskToken = response.TaskToken;

            // Parse the returned JSON string.
            var taskJsonResponse = JsonDocument.Parse(response.Input);
            var taskJsonObject = taskJsonResponse.RootElement;
            var message = taskJsonObject.GetProperty("message").GetString();
            var actions = taskJsonObject.GetProperty("actions").EnumerateArray().Select(x => x.ToString()).ToList();
            Console.WriteLine($"\n{message}\n");

            // Prompt the user for another choice.
            Console.WriteLine("ChatSFN: What would you like me to do?");
            actions.ForEach(action => Console.WriteLine($"\t{action}"));
            Console.Write($"\n{userName}, tell me your choice: ");
            userChoice = Console.ReadLine();
            if (userChoice?.ToLower() == "done")
            {
                isDone = true;
            }

            Console.WriteLine($"You have selected: {userChoice}");
            var jsonResponse = @"{""action"": """ + userChoice + @"""}";

            await stepFunctionsWrapper.SendTaskSuccessAsync(taskToken, jsonResponse);
        }

        await stepFunctionsWrapper.StopExecution(executionArn);
        Console.WriteLine("Now we will wait for the execution to stop.");
        DescribeExecutionResponse executionResponse;
        do
        {
            executionResponse = await stepFunctionsWrapper.DescribeExecutionAsync(executionArn);
        } while (executionResponse.Status == ExecutionStatus.RUNNING);

        Console.WriteLine("State machine stopped.");
        uiMethods.PressEnter();

        uiMethods.DisplayTitle("State machine executions");
        Console.WriteLine("Now let's take a look at the execution values for the state machine.");

        // List the executions.
        var executions = await stepFunctionsWrapper.ListExecutionsAsync(stateMachineArn);

        uiMethods.DisplayTitle("Step function execution values");
        executions.ForEach(execution =>
        {
            Console.WriteLine($"{execution.Name}\t{execution.StartDate} to {execution.StopDate}");
        });

        uiMethods.PressEnter();

        // Now delete the state machine and the activity.
        uiMethods.DisplayTitle("Clean up resources");
        Console.WriteLine("Deleting the state machine...");

        await stepFunctionsWrapper.DeleteStateMachine(stateMachineArn);
        Console.WriteLine("State machine deleted.");

        Console.WriteLine("Deleting the activity...");
        await stepFunctionsWrapper.DeleteActivity(activityArn);
        Console.WriteLine("Activity deleted.");

        Console.WriteLine("The Amazon Step Functions scenario is now complete.");
    }

    static async Task<Role> GetOrCreateStateMachineRole(string roleName)
    {
        // Define the policy document for the role.
        var stateMachineRolePolicy = @"{
         ""Version"": ""2012-10-17"",
        ""Statement"": [{
            ""Sid"": """",
            ""Effect"": ""Allow"",
            ""Principal"": {
                ""Service"": ""states.amazonaws.com""},
            ""Action"": ""sts:AssumeRole""}]}";

        var role = new Role();
        var roleExists = false;

        try
        {
            var getRoleResponse = await _iamService.GetRoleAsync(new GetRoleRequest { RoleName = roleName });
            roleExists = true;
            role = getRoleResponse.Role;
        }
        catch (NoSuchEntityException)
        {
            // The role doesn't exist. Create it.
            Console.WriteLine($"Role, {roleName} doesn't exist. Creating it...");
        }

        if (!roleExists)
        {
            var request = new CreateRoleRequest
            {
                RoleName = roleName,
                AssumeRolePolicyDocument = stateMachineRolePolicy,
            };

            var createRoleResponse = await _iamService.CreateRoleAsync(request);
            role = createRoleResponse.Role;
        }

        return role;
    }
}


namespace StepFunctionsBasics;

/// <summary>
/// Some useful methods to make screen display easier.
/// </summary>
public class UiMethods
{
    private readonly string _sepBar = new('-', Console.WindowWidth);

    /// <summary>
    /// Show information about the scenario.
    /// </summary>
    public void DisplayOverview()
    {
        Console.Clear();
        DisplayTitle("Welcome to the AWS Step Functions Demo");

        Console.WriteLine("This example application will do the following:");
        Console.WriteLine("\t 1. Create an activity.");
        Console.WriteLine("\t 2. Create a state machine.");
        Console.WriteLine("\t 3. Start an execution.");
        Console.WriteLine("\t 4. Run the worker, then stop it.");
        Console.WriteLine("\t 5. List executions.");
        Console.WriteLine("\t 6. Clean up the resources created for the example.");
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPress <Enter> to continue.");
        _ = Console.ReadLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter"></param>
    /// <returns></returns>
    private string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title, and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(_sepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(_sepBar);
    }
}
```
ステートマシンとアクティビティアクションをラップするクラスを定義します。  

```
namespace StepFunctionsActions;

using Amazon.StepFunctions;
using Amazon.StepFunctions.Model;

/// <summary>
/// Wrapper that performs AWS Step Functions actions.
/// </summary>
public class StepFunctionsWrapper
{
    private readonly IAmazonStepFunctions _amazonStepFunctions;

    /// <summary>
    /// The constructor for the StepFunctionsWrapper. Initializes the
    /// client object passed to it.
    /// </summary>
    /// <param name="amazonStepFunctions">An initialized Step Functions client object.</param>
    public StepFunctionsWrapper(IAmazonStepFunctions amazonStepFunctions)
    {
        _amazonStepFunctions = amazonStepFunctions;
    }

    /// <summary>
    /// Create a Step Functions activity using the supplied name.
    /// </summary>
    /// <param name="activityName">The name for the new Step Functions activity.</param>
    /// <returns>The Amazon Resource Name (ARN) for the new activity.</returns>
    public async Task<string> CreateActivity(string activityName)
    {
        var response = await _amazonStepFunctions.CreateActivityAsync(new CreateActivityRequest { Name = activityName });
        return response.ActivityArn;
    }


    /// <summary>
    /// Create a Step Functions state machine.
    /// </summary>
    /// <param name="stateMachineName">Name for the new Step Functions state
    /// machine.</param>
    /// <param name="definition">A JSON string that defines the Step Functions
    /// state machine.</param>
    /// <param name="roleArn">The Amazon Resource Name (ARN) of the role.</param>
    /// <returns></returns>
    public async Task<string> CreateStateMachine(string stateMachineName, string definition, string roleArn)
    {
        var request = new CreateStateMachineRequest
        {
            Name = stateMachineName,
            Definition = definition,
            RoleArn = roleArn
        };

        var response =
            await _amazonStepFunctions.CreateStateMachineAsync(request);
        return response.StateMachineArn;
    }


    /// <summary>
    /// Delete a Step Machine activity.
    /// </summary>
    /// <param name="activityArn">The Amazon Resource Name (ARN) of
    /// the activity.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteActivity(string activityArn)
    {
        var response = await _amazonStepFunctions.DeleteActivityAsync(new DeleteActivityRequest { ActivityArn = activityArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Delete a Step Functions state machine.
    /// </summary>
    /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the
    /// state machine.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteStateMachine(string stateMachineArn)
    {
        var response = await _amazonStepFunctions.DeleteStateMachineAsync(new DeleteStateMachineRequest
        { StateMachineArn = stateMachineArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Retrieve information about the specified Step Functions execution.
    /// </summary>
    /// <param name="executionArn">The Amazon Resource Name (ARN) of the
    /// Step Functions execution.</param>
    /// <returns>The API response returned by the API.</returns>
    public async Task<DescribeExecutionResponse> DescribeExecutionAsync(string executionArn)
    {
        var response = await _amazonStepFunctions.DescribeExecutionAsync(new DescribeExecutionRequest { ExecutionArn = executionArn });
        return response;
    }


    /// <summary>
    /// Retrieve information about the specified Step Functions state machine.
    /// </summary>
    /// <param name="StateMachineArn">The Amazon Resource Name (ARN) of the
    /// Step Functions state machine to retrieve.</param>
    /// <returns>Information about the specified Step Functions state machine.</returns>
    public async Task<DescribeStateMachineResponse> DescribeStateMachineAsync(string StateMachineArn)
    {
        var response = await _amazonStepFunctions.DescribeStateMachineAsync(new DescribeStateMachineRequest { StateMachineArn = StateMachineArn });
        return response;
    }


    /// <summary>
    /// Retrieve a task with the specified Step Functions activity
    /// with the specified Amazon Resource Name (ARN).
    /// </summary>
    /// <param name="activityArn">The Amazon Resource Name (ARN) of
    /// the Step Functions activity.</param>
    /// <param name="workerName">The name of the Step Functions worker.</param>
    /// <returns>The response from the Step Functions activity.</returns>
    public async Task<GetActivityTaskResponse> GetActivityTaskAsync(string activityArn, string workerName)
    {
        var response = await _amazonStepFunctions.GetActivityTaskAsync(new GetActivityTaskRequest
        { ActivityArn = activityArn, WorkerName = workerName });
        return response;
    }


    /// <summary>
    /// List the Step Functions activities for the current account.
    /// </summary>
    /// <returns>A list of ActivityListItems.</returns>
    public async Task<List<ActivityListItem>> ListActivitiesAsync()
    {
        var request = new ListActivitiesRequest();
        var activities = new List<ActivityListItem>();

        do
        {
            var response = await _amazonStepFunctions.ListActivitiesAsync(request);

            if (response.NextToken is not null)
            {
                request.NextToken = response.NextToken;
            }

            activities.AddRange(response.Activities);
        }
        while (request.NextToken is not null);

        return activities;
    }


    /// <summary>
    /// Retrieve information about executions of a Step Functions
    /// state machine.
    /// </summary>
    /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the
    /// Step Functions state machine.</param>
    /// <returns>A list of ExecutionListItem objects.</returns>
    public async Task<List<ExecutionListItem>> ListExecutionsAsync(string stateMachineArn)
    {
        var executions = new List<ExecutionListItem>();
        ListExecutionsResponse response;
        var request = new ListExecutionsRequest { StateMachineArn = stateMachineArn };

        do
        {
            response = await _amazonStepFunctions.ListExecutionsAsync(request);
            executions.AddRange(response.Executions);
            if (response.NextToken is not null)
            {
                request.NextToken = response.NextToken;
            }
        } while (response.NextToken is not null);

        return executions;
    }


    /// <summary>
    /// Retrieve a list of Step Functions state machines.
    /// </summary>
    /// <returns>A list of StateMachineListItem objects.</returns>
    public async Task<List<StateMachineListItem>> ListStateMachinesAsync()
    {
        var stateMachines = new List<StateMachineListItem>();
        var listStateMachinesPaginator =
            _amazonStepFunctions.Paginators.ListStateMachines(new ListStateMachinesRequest());

        await foreach (var response in listStateMachinesPaginator.Responses)
        {
            stateMachines.AddRange(response.StateMachines);
        }

        return stateMachines;
    }


    /// <summary>
    /// Indicate that the Step Functions task, indicated by the
    /// task token, has completed successfully.
    /// </summary>
    /// <param name="taskToken">Identifies the task.</param>
    /// <param name="taskResponse">The response received from executing the task.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> SendTaskSuccessAsync(string taskToken, string taskResponse)
    {
        var response = await _amazonStepFunctions.SendTaskSuccessAsync(new SendTaskSuccessRequest
        { TaskToken = taskToken, Output = taskResponse });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Start execution of an AWS Step Functions state machine.
    /// </summary>
    /// <param name="executionName">The name to use for the execution.</param>
    /// <param name="executionJson">The JSON string to pass for execution.</param>
    /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the
    /// Step Functions state machine.</param>
    /// <returns>The Amazon Resource Name (ARN) of the AWS Step Functions
    /// execution.</returns>
    public async Task<string> StartExecutionAsync(string executionJson, string stateMachineArn)
    {
        var executionRequest = new StartExecutionRequest
        {
            Input = executionJson,
            StateMachineArn = stateMachineArn
        };

        var response = await _amazonStepFunctions.StartExecutionAsync(executionRequest);
        return response.ExecutionArn;
    }


    /// <summary>
    /// Stop execution of a Step Functions workflow.
    /// </summary>
    /// <param name="executionArn">The Amazon Resource Name (ARN) of
    /// the Step Functions execution to stop.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> StopExecution(string executionArn)
    {
        var response =
            await _amazonStepFunctions.StopExecutionAsync(new StopExecutionRequest { ExecutionArn = executionArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateActivity](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/CreateActivity)
  + [CreateStateMachine](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/CreateStateMachine)
  + [DeleteActivity](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DeleteActivity)
  + [DeleteStateMachine](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DeleteStateMachine)
  + [DescribeExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DescribeExecution)
  + [DescribeStateMachine](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DescribeStateMachine)
  + [GetActivityTask](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/GetActivityTask)
  + [ListActivities](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/ListActivities)
  + [ListStateMachines](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/ListStateMachines)
  + [SendTaskSuccess](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/SendTaskSuccess)
  + [StartExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/StartExecution)
  + [StopExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/StopExecution)

## アクション
<a name="actions"></a>

### `CreateActivity`
<a name="sfn_CreateActivity_csharp_3_topic"></a>

次のコード例は、`CreateActivity` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a Step Functions activity using the supplied name.
    /// </summary>
    /// <param name="activityName">The name for the new Step Functions activity.</param>
    /// <returns>The Amazon Resource Name (ARN) for the new activity.</returns>
    public async Task<string> CreateActivity(string activityName)
    {
        var response = await _amazonStepFunctions.CreateActivityAsync(new CreateActivityRequest { Name = activityName });
        return response.ActivityArn;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateActivity](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/CreateActivity)」を参照してください。

### `CreateStateMachine`
<a name="sfn_CreateStateMachine_csharp_3_topic"></a>

次のコード例は、`CreateStateMachine` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a Step Functions state machine.
    /// </summary>
    /// <param name="stateMachineName">Name for the new Step Functions state
    /// machine.</param>
    /// <param name="definition">A JSON string that defines the Step Functions
    /// state machine.</param>
    /// <param name="roleArn">The Amazon Resource Name (ARN) of the role.</param>
    /// <returns></returns>
    public async Task<string> CreateStateMachine(string stateMachineName, string definition, string roleArn)
    {
        var request = new CreateStateMachineRequest
        {
            Name = stateMachineName,
            Definition = definition,
            RoleArn = roleArn
        };

        var response =
            await _amazonStepFunctions.CreateStateMachineAsync(request);
        return response.StateMachineArn;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateStateMachine](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/CreateStateMachine)」を参照してください。

### `DeleteActivity`
<a name="sfn_DeleteActivity_csharp_3_topic"></a>

次のコード例は、`DeleteActivity` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a Step Machine activity.
    /// </summary>
    /// <param name="activityArn">The Amazon Resource Name (ARN) of
    /// the activity.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteActivity(string activityArn)
    {
        var response = await _amazonStepFunctions.DeleteActivityAsync(new DeleteActivityRequest { ActivityArn = activityArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteActivity](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DeleteActivity)」を参照してください。

### `DeleteStateMachine`
<a name="sfn_DeleteStateMachine_csharp_3_topic"></a>

次のコード例は、`DeleteStateMachine` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a Step Functions state machine.
    /// </summary>
    /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the
    /// state machine.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteStateMachine(string stateMachineArn)
    {
        var response = await _amazonStepFunctions.DeleteStateMachineAsync(new DeleteStateMachineRequest
        { StateMachineArn = stateMachineArn });
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteStateMachine](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DeleteStateMachine)」を参照してください。

### `DescribeExecution`
<a name="sfn_DescribeExecution_csharp_3_topic"></a>

次のコード例は、`DescribeExecution` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Retrieve information about the specified Step Functions execution.
    /// </summary>
    /// <param name="executionArn">The Amazon Resource Name (ARN) of the
    /// Step Functions execution.</param>
    /// <returns>The API response returned by the API.</returns>
    public async Task<DescribeExecutionResponse> DescribeExecutionAsync(string executionArn)
    {
        var response = await _amazonStepFunctions.DescribeExecutionAsync(new DescribeExecutionRequest { ExecutionArn = executionArn });
        return response;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DescribeExecution)」を参照してください。

### `DescribeStateMachine`
<a name="sfn_DescribeStateMachine_csharp_3_topic"></a>

次のコード例は、`DescribeStateMachine` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Retrieve information about the specified Step Functions state machine.
    /// </summary>
    /// <param name="StateMachineArn">The Amazon Resource Name (ARN) of the
    /// Step Functions state machine to retrieve.</param>
    /// <returns>Information about the specified Step Functions state machine.</returns>
    public async Task<DescribeStateMachineResponse> DescribeStateMachineAsync(string StateMachineArn)
    {
        var response = await _amazonStepFunctions.DescribeStateMachineAsync(new DescribeStateMachineRequest { StateMachineArn = StateMachineArn });
        return response;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeStateMachine](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/DescribeStateMachine)」を参照してください。

### `GetActivityTask`
<a name="sfn_GetActivityTask_csharp_3_topic"></a>

次のコード例は、`GetActivityTask` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Retrieve a task with the specified Step Functions activity
    /// with the specified Amazon Resource Name (ARN).
    /// </summary>
    /// <param name="activityArn">The Amazon Resource Name (ARN) of
    /// the Step Functions activity.</param>
    /// <param name="workerName">The name of the Step Functions worker.</param>
    /// <returns>The response from the Step Functions activity.</returns>
    public async Task<GetActivityTaskResponse> GetActivityTaskAsync(string activityArn, string workerName)
    {
        var response = await _amazonStepFunctions.GetActivityTaskAsync(new GetActivityTaskRequest
        { ActivityArn = activityArn, WorkerName = workerName });
        return response;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetActivityTask](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/GetActivityTask)」を参照してください。

### `ListActivities`
<a name="sfn_ListActivities_csharp_3_topic"></a>

次のコード例は、`ListActivities` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List the Step Functions activities for the current account.
    /// </summary>
    /// <returns>A list of ActivityListItems.</returns>
    public async Task<List<ActivityListItem>> ListActivitiesAsync()
    {
        var request = new ListActivitiesRequest();
        var activities = new List<ActivityListItem>();

        do
        {
            var response = await _amazonStepFunctions.ListActivitiesAsync(request);

            if (response.NextToken is not null)
            {
                request.NextToken = response.NextToken;
            }

            activities.AddRange(response.Activities);
        }
        while (request.NextToken is not null);

        return activities;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListActivities](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/ListActivities)」を参照してください。

### `ListExecutions`
<a name="sfn_ListExecutions_csharp_3_topic"></a>

次のコード例は、`ListExecutions` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Retrieve information about executions of a Step Functions
    /// state machine.
    /// </summary>
    /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the
    /// Step Functions state machine.</param>
    /// <returns>A list of ExecutionListItem objects.</returns>
    public async Task<List<ExecutionListItem>> ListExecutionsAsync(string stateMachineArn)
    {
        var executions = new List<ExecutionListItem>();
        ListExecutionsResponse response;
        var request = new ListExecutionsRequest { StateMachineArn = stateMachineArn };

        do
        {
            response = await _amazonStepFunctions.ListExecutionsAsync(request);
            executions.AddRange(response.Executions);
            if (response.NextToken is not null)
            {
                request.NextToken = response.NextToken;
            }
        } while (response.NextToken is not null);

        return executions;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListExecutions](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/ListExecutions)」を参照してください。

### `ListStateMachines`
<a name="sfn_ListStateMachines_csharp_3_topic"></a>

次のコード例は、`ListStateMachines` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Retrieve a list of Step Functions state machines.
    /// </summary>
    /// <returns>A list of StateMachineListItem objects.</returns>
    public async Task<List<StateMachineListItem>> ListStateMachinesAsync()
    {
        var stateMachines = new List<StateMachineListItem>();
        var listStateMachinesPaginator =
            _amazonStepFunctions.Paginators.ListStateMachines(new ListStateMachinesRequest());

        await foreach (var response in listStateMachinesPaginator.Responses)
        {
            stateMachines.AddRange(response.StateMachines);
        }

        return stateMachines;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListStateMachines](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/ListStateMachines)」を参照してください。

### `SendTaskSuccess`
<a name="sfn_SendTaskSuccess_csharp_3_topic"></a>

次のコード例は、`SendTaskSuccess` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Indicate that the Step Functions task, indicated by the
    /// task token, has completed successfully.
    /// </summary>
    /// <param name="taskToken">Identifies the task.</param>
    /// <param name="taskResponse">The response received from executing the task.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> SendTaskSuccessAsync(string taskToken, string taskResponse)
    {
        var response = await _amazonStepFunctions.SendTaskSuccessAsync(new SendTaskSuccessRequest
        { TaskToken = taskToken, Output = taskResponse });

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[SendTaskSuccess](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/SendTaskSuccess)」を参照してください。

### `StartExecution`
<a name="sfn_StartExecution_csharp_3_topic"></a>

次のコード例は、`StartExecution` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/StepFunctions#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Start execution of an AWS Step Functions state machine.
    /// </summary>
    /// <param name="executionName">The name to use for the execution.</param>
    /// <param name="executionJson">The JSON string to pass for execution.</param>
    /// <param name="stateMachineArn">The Amazon Resource Name (ARN) of the
    /// Step Functions state machine.</param>
    /// <returns>The Amazon Resource Name (ARN) of the AWS Step Functions
    /// execution.</returns>
    public async Task<string> StartExecutionAsync(string executionJson, string stateMachineArn)
    {
        var executionRequest = new StartExecutionRequest
        {
            Input = executionJson,
            StateMachineArn = stateMachineArn
        };

        var response = await _amazonStepFunctions.StartExecutionAsync(executionRequest);
        return response.ExecutionArn;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[StartExecution](https://docs.aws.amazon.com/goto/DotNetSDKV3/states-2016-11-23/StartExecution)」を参照してください。

# AWS STS を使用した の例 SDK for .NET
<a name="csharp_3_sts_code_examples"></a>

次のコード例は、 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_csharp_3_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/STS#code-examples)での設定と実行の方法を確認してください。

```
using System;
using System.Threading.Tasks;
using Amazon;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;

namespace AssumeRoleExample
{
    class AssumeRole
    {
        /// <summary>
        /// This example shows how to use the AWS Security Token
        /// Service (AWS STS) to assume an IAM role.
        ///
        /// NOTE: It is important that the role that will be assumed has a
        /// trust relationship with the account that will assume the role.
        ///
        /// Before you run the example, you need to create the role you want to
        /// assume and have it trust the IAM account that will assume that role.
        ///
        /// See https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html
        /// for help in working with roles.
        /// </summary>

        // A region property may be used if the profile or credentials loaded do not specify a region,
        // or to use a specific region.
        private static readonly RegionEndpoint REGION = RegionEndpoint.USWest2;

        static async Task Main()
        {
            // Create the SecurityToken client and then display the identity of the
            // default user.
            var roleArnToAssume = "arn:aws:iam::123456789012:role/testAssumeRole";

            var client = new Amazon.SecurityToken.AmazonSecurityTokenServiceClient(REGION);

            // Get and display the information about the identity of the default user.
            var callerIdRequest = new GetCallerIdentityRequest();
            var caller = await client.GetCallerIdentityAsync(callerIdRequest);
            Console.WriteLine($"Original Caller: {caller.Arn}");

            // Create the request to use with the AssumeRoleAsync call.
            var assumeRoleReq = new AssumeRoleRequest()
            {
                DurationSeconds = 1600,
                RoleSessionName = "Session1",
                RoleArn = roleArnToAssume
            };

            var assumeRoleRes = await client.AssumeRoleAsync(assumeRoleReq);

            // Now create a new client based on the credentials of the caller assuming the role.
            var client2 = new AmazonSecurityTokenServiceClient(credentials: assumeRoleRes.Credentials, REGION);

            // Get and display information about the caller that has assumed the defined role.
            var caller2 = await client2.GetCallerIdentityAsync(callerIdRequest);
            Console.WriteLine($"AssumedRole Caller: {caller2.Arn}");
        }
    }
}
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/DotNetSDKV3/sts-2011-06-15/AssumeRole)」を参照してください。**

# サポート を使用した の例 SDK for .NET
<a name="csharp_3_support_code_examples"></a>

次のコード例は、 AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち サポートは
<a name="support_Hello_csharp_3_topic"></a>

次のコード例は、 サポートの使用を開始する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.AWSSupport;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

public static class HelloSupport
{
    static async Task Main(string[] args)
    {
        // Use the AWS .NET Core Setup package to set up dependency injection for the AWS Support service.
        // Use your AWS profile name, or leave it blank to use the default profile.
        // You must have one of the following AWS Support plans: Business, Enterprise On-Ramp, or Enterprise. Otherwise, an exception will be thrown.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonAWSSupport>()
            ).Build();

        // Now the client is available for injection.
        var supportClient = host.Services.GetRequiredService<IAmazonAWSSupport>();

        // You can use await and any of the async methods to get a response.
        var response = await supportClient.DescribeServicesAsync();
        Console.WriteLine($"\tHello AWS Support! There are {response.Services.Count} services available.");
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeServices](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeServices)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="support_Scenario_GetStartedSupportCases_csharp_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ケースの利用可能なサービスと重要度レベルを取得して表示します。
+ 選択したサービス、カテゴリ、重要度レベルを使用してサポートケースを作成する方法
+ 当日のオープンケースのリストを取得して表示する方法
+ 新しいケースに添付セットとコミュニケーションを追加する方法
+ ケースの新しい添付ファイルとコミュニケーションについて説明する方法
+ ケースを解決する方法
+ 当日の解決済みケースのリストを取得して表示します。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
/// <summary>
/// Hello AWS Support example.
/// </summary>
public static class SupportCaseScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.
    To use the AWS Support API, you must have one of the following AWS Support plans: Business, Enterprise On-Ramp, or Enterprise.

    This .NET example performs the following tasks:
    1.  Get and display services. Select a service from the list.
    2.  Select a category from the selected service.
    3.  Get and display severity levels and select a severity level from the list.
    4.  Create a support case using the selected service, category, and severity level.
    5.  Get and display a list of open support cases for the current day.
    6.  Create an attachment set with a sample text file to add to the case.
    7.  Add a communication with the attachment to the support case.
    8.  List the communications of the support case.
    9.  Describe the attachment set.
    10. Resolve the support case.
    11. Get a list of resolved cases for the current day.
   */

    private static SupportWrapper _supportWrapper = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the AWS Support service.
        // Use your AWS profile name, or leave it blank to use the default profile.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonAWSSupport>(new AWSOptions() { Profile = "default" })
                    .AddTransient<SupportWrapper>()
            )
            .Build();

        var logger = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        }).CreateLogger(typeof(SupportCaseScenario));

        _supportWrapper = host.Services.GetRequiredService<SupportWrapper>();

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the AWS Support case example scenario.");
        Console.WriteLine(new string('-', 80));

        try
        {
            var apiSupported = await _supportWrapper.VerifySubscription();
            if (!apiSupported)
            {
                logger.LogError("You must have a Business, Enterprise On-Ramp, or Enterprise Support " +
                                 "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these examples.");
                return;
            }

            var service = await DisplayAndSelectServices();

            var category = DisplayAndSelectCategories(service);

            var severityLevel = await DisplayAndSelectSeverity();

            var caseId = await CreateSupportCase(service, category, severityLevel);

            await DescribeTodayOpenCases();

            var attachmentSetId = await CreateAttachmentSet();

            await AddCommunicationToCase(attachmentSetId, caseId);

            var attachmentId = await ListCommunicationsForCase(caseId);

            await DescribeCaseAttachment(attachmentId);

            await ResolveCase(caseId);

            await DescribeTodayResolvedCases();

            Console.WriteLine(new string('-', 80));
            Console.WriteLine("AWS Support case example scenario complete.");
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "There was a problem executing the scenario.");
        }
    }

    /// <summary>
    /// List some available services from AWS Support, and select a service for the example.
    /// </summary>
    /// <returns>The selected service.</returns>
    private static async Task<Service> DisplayAndSelectServices()
    {
        Console.WriteLine(new string('-', 80));
        var services = await _supportWrapper.DescribeServices();
        Console.WriteLine($"AWS Support client returned {services.Count} services.");

        Console.WriteLine($"1. Displaying first 10 services:");
        for (int i = 0; i < 10 && i < services.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {services[i].Name}");
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > services.Count)
        {
            Console.WriteLine(
                "Select an example support service by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }
        Console.WriteLine(new string('-', 80));

        return services[choiceNumber - 1];
    }

    /// <summary>
    /// List the available categories for a service and select a category for the example.
    /// </summary>
    /// <param name="service">Service to use for displaying categories.</param>
    /// <returns>The selected category.</returns>
    private static Category DisplayAndSelectCategories(Service service)
    {
        Console.WriteLine(new string('-', 80));

        Console.WriteLine($"2. Available support categories for Service \"{service.Name}\":");
        for (int i = 0; i < service.Categories.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {service.Categories[i].Name}");
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > service.Categories.Count)
        {
            Console.WriteLine(
                "Select an example support category by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }

        Console.WriteLine(new string('-', 80));

        return service.Categories[choiceNumber - 1];
    }

    /// <summary>
    /// List available severity levels from AWS Support, and select a level for the example.
    /// </summary>
    /// <returns>The selected severity level.</returns>
    private static async Task<SeverityLevel> DisplayAndSelectSeverity()
    {
        Console.WriteLine(new string('-', 80));
        var severityLevels = await _supportWrapper.DescribeSeverityLevels();

        Console.WriteLine($"3. Get and display available severity levels:");
        for (int i = 0; i < 10 && i < severityLevels.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {severityLevels[i].Name}");
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > severityLevels.Count)
        {
            Console.WriteLine(
                "Select an example severity level by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }
        Console.WriteLine(new string('-', 80));

        return severityLevels[choiceNumber - 1];
    }

    /// <summary>
    /// Create an example support case.
    /// </summary>
    /// <param name="service">Service to use for the new case.</param>
    /// <param name="category">Category to use for the new case.</param>
    /// <param name="severity">Severity to use for the new case.</param>
    /// <returns>The caseId of the new support case.</returns>
    private static async Task<string> CreateSupportCase(Service service,
        Category category, SeverityLevel severity)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"4. Create an example support case" +
                          $" with the following settings:" +
                          $" \n\tService: {service.Name}, Category: {category.Name} " +
                          $"and Severity Level: {severity.Name}.");
        var caseId = await _supportWrapper.CreateCase(service.Code, category.Code, severity.Code,
            "Example case for testing, ignore.", "This is my example support case.");

        Console.WriteLine($"\tNew case created with ID {caseId}");

        Console.WriteLine(new string('-', 80));

        return caseId;
    }

    /// <summary>
    /// List open cases for the current day.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task DescribeTodayOpenCases()
    {
        Console.WriteLine($"5. List the open support cases for the current day.");
        // Describe the cases. If it is empty, try again and allow time for the new case to appear.
        List<CaseDetails> currentOpenCases = null!;
        while (currentOpenCases == null || currentOpenCases.Count == 0)
        {
            Thread.Sleep(1000);
            currentOpenCases = await _supportWrapper.DescribeCases(
                new List<string>(),
                null,
                false,
                false,
                DateTime.UtcNow.Date,
                DateTime.UtcNow);
        }

        foreach (var openCase in currentOpenCases)
        {
            Console.WriteLine($"\tCase: {openCase.CaseId} created {openCase.TimeCreated}");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Create an attachment set for a support case.
    /// </summary>
    /// <returns>The attachment set id.</returns>
    private static async Task<string> CreateAttachmentSet()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"6. Create an attachment set for a support case.");
        var fileName = "example_attachment.txt";

        // Create the file if it does not already exist.
        if (!File.Exists(fileName))
        {
            await using StreamWriter sw = File.CreateText(fileName);
            await sw.WriteLineAsync(
                "This is a sample file for attachment to a support case.");
        }

        await using var ms = new MemoryStream(await File.ReadAllBytesAsync(fileName));

        var attachmentSetId = await _supportWrapper.AddAttachmentToSet(
            ms,
            fileName);

        Console.WriteLine($"\tNew attachment set created with id: \n\t{attachmentSetId.Substring(0, 65)}...");

        Console.WriteLine(new string('-', 80));

        return attachmentSetId;
    }

    /// <summary>
    /// Add an attachment set and communication to a case.
    /// </summary>
    /// <param name="attachmentSetId">Id of the attachment set.</param>
    /// <param name="caseId">Id of the case to receive the attachment set.</param>
    /// <returns>Async task.</returns>
    private static async Task AddCommunicationToCase(string attachmentSetId, string caseId)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"7. Add attachment set and communication to {caseId}.");

        await _supportWrapper.AddCommunicationToCase(
            caseId,
            "This is an example communication added to a support case.",
            attachmentSetId);

        Console.WriteLine($"\tNew attachment set and communication added to {caseId}");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List the communications for a case.
    /// </summary>
    /// <param name="caseId">Id of the case to describe.</param>
    /// <returns>An attachment id.</returns>
    private static async Task<string> ListCommunicationsForCase(string caseId)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"8. List communications for case {caseId}.");

        var communications = await _supportWrapper.DescribeCommunications(caseId);
        var attachmentId = "";
        foreach (var communication in communications)
        {
            Console.WriteLine(
                $"\tCommunication created on: {communication.TimeCreated} has {communication.AttachmentSet.Count} attachments.");
            if (communication.AttachmentSet.Any())
            {
                attachmentId = communication.AttachmentSet.First().AttachmentId;
            }
        }

        Console.WriteLine(new string('-', 80));
        return attachmentId;
    }

    /// <summary>
    /// Describe an attachment by id.
    /// </summary>
    /// <param name="attachmentId">Id of the attachment to describe.</param>
    /// <returns>Async task.</returns>
    private static async Task DescribeCaseAttachment(string attachmentId)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"9. Describe the attachment set.");

        var attachment = await _supportWrapper.DescribeAttachment(attachmentId);
        var data = Encoding.ASCII.GetString(attachment.Data.ToArray());
        Console.WriteLine($"\tAttachment includes {attachment.FileName} with data: \n\t{data}");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Resolve the support case.
    /// </summary>
    /// <param name="caseId">Id of the case to resolve.</param>
    /// <returns>Async task.</returns>
    private static async Task ResolveCase(string caseId)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"10. Resolve case {caseId}.");

        var status = await _supportWrapper.ResolveCase(caseId);
        Console.WriteLine($"\tCase {caseId} has final status {status}");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List resolved cases for the current day.
    /// </summary>
    /// <returns>Async Task.</returns>
    private static async Task DescribeTodayResolvedCases()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"11. List the resolved support cases for the current day.");
        var currentCases = await _supportWrapper.DescribeCases(
            new List<string>(),
            null,
            false,
            true,
            DateTime.UtcNow.Date,
            DateTime.UtcNow);

        foreach (var currentCase in currentCases)
        {
            if (currentCase.Status == "resolved")
            {
                Console.WriteLine(
                    $"\tCase: {currentCase.CaseId}: status {currentCase.Status}");
            }
        }

        Console.WriteLine(new string('-', 80));
    }
}
```
 サポート アクションのシナリオで使用されるラッパーメソッド。  

```
/// <summary>
/// Wrapper methods to use AWS Support for working with support cases.
/// </summary>
public class SupportWrapper
{
    private readonly IAmazonAWSSupport _amazonSupport;
    public SupportWrapper(IAmazonAWSSupport amazonSupport)
    {
        _amazonSupport = amazonSupport;
    }


    /// <summary>
    /// Get the descriptions of AWS services.
    /// </summary>
    /// <param name="name">Optional language for services.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <returns>The list of AWS service descriptions.</returns>
    public async Task<List<Service>> DescribeServices(string language = "en")
    {
        var response = await _amazonSupport.DescribeServicesAsync(
            new DescribeServicesRequest()
            {
                Language = language
            });
        return response.Services;
    }



    /// <summary>
    /// Get the descriptions of support severity levels.
    /// </summary>
    /// <param name="name">Optional language for severity levels.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <returns>The list of support severity levels.</returns>
    public async Task<List<SeverityLevel>> DescribeSeverityLevels(string language = "en")
    {
        var response = await _amazonSupport.DescribeSeverityLevelsAsync(
            new DescribeSeverityLevelsRequest()
            {
                Language = language
            });
        return response.SeverityLevels;
    }



    /// <summary>
    /// Create a new support case.
    /// </summary>
    /// <param name="serviceCode">Service code for the new case.</param>
    /// <param name="categoryCode">Category for the new case.</param>
    /// <param name="severityCode">Severity code for the new case.</param>
    /// <param name="subject">Subject of the new case.</param>
    /// <param name="body">Body text of the new case.</param>
    /// <param name="language">Optional language support for your case.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <param name="attachmentSetId">Optional Id for an attachment set for the new case.</param>
    /// <param name="issueType">Optional issue type for the new case. Options are "customer-service" or "technical".</param>
    /// <returns>The caseId of the new support case.</returns>
    public async Task<string> CreateCase(string serviceCode, string categoryCode, string severityCode, string subject,
        string body, string language = "en", string? attachmentSetId = null, string issueType = "customer-service")
    {
        var response = await _amazonSupport.CreateCaseAsync(
            new CreateCaseRequest()
            {
                ServiceCode = serviceCode,
                CategoryCode = categoryCode,
                SeverityCode = severityCode,
                Subject = subject,
                Language = language,
                AttachmentSetId = attachmentSetId,
                IssueType = issueType,
                CommunicationBody = body
            });
        return response.CaseId;
    }



    /// <summary>
    /// Add an attachment to a set, or create a new attachment set if one does not exist.
    /// </summary>
    /// <param name="data">The data for the attachment.</param>
    /// <param name="fileName">The file name for the attachment.</param>
    /// <param name="attachmentSetId">Optional setId for the attachment. Creates a new attachment set if empty.</param>
    /// <returns>The setId of the attachment.</returns>
    public async Task<string> AddAttachmentToSet(MemoryStream data, string fileName, string? attachmentSetId = null)
    {
        var response = await _amazonSupport.AddAttachmentsToSetAsync(
            new AddAttachmentsToSetRequest
            {
                AttachmentSetId = attachmentSetId,
                Attachments = new List<Attachment>
                {
                    new Attachment
                    {
                        Data = data,
                        FileName = fileName
                    }
                }
            });
        return response.AttachmentSetId;
    }



    /// <summary>
    /// Get description of a specific attachment.
    /// </summary>
    /// <param name="attachmentId">Id of the attachment, usually fetched by describing the communications of a case.</param>
    /// <returns>The attachment object.</returns>
    public async Task<Attachment> DescribeAttachment(string attachmentId)
    {
        var response = await _amazonSupport.DescribeAttachmentAsync(
            new DescribeAttachmentRequest()
            {
                AttachmentId = attachmentId
            });
        return response.Attachment;
    }



    /// <summary>
    /// Add communication to a case, including optional attachment set ID and CC email addresses.
    /// </summary>
    /// <param name="caseId">Id for the support case.</param>
    /// <param name="body">Body text of the communication.</param>
    /// <param name="attachmentSetId">Optional Id for an attachment set.</param>
    /// <param name="ccEmailAddresses">Optional list of CC email addresses.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> AddCommunicationToCase(string caseId, string body,
        string? attachmentSetId = null, List<string>? ccEmailAddresses = null)
    {
        var response = await _amazonSupport.AddCommunicationToCaseAsync(
            new AddCommunicationToCaseRequest()
            {
                CaseId = caseId,
                CommunicationBody = body,
                AttachmentSetId = attachmentSetId,
                CcEmailAddresses = ccEmailAddresses
            });
        return response.Result;
    }



    /// <summary>
    /// Describe the communications for a case, optionally with a date filter.
    /// </summary>
    /// <param name="caseId">The ID of the support case.</param>
    /// <param name="afterTime">The optional start date for a filtered search.</param>
    /// <param name="beforeTime">The optional end date for a filtered search.</param>
    /// <returns>The list of communications for the case.</returns>
    public async Task<List<Communication>> DescribeCommunications(string caseId, DateTime? afterTime = null, DateTime? beforeTime = null)
    {
        var results = new List<Communication>();
        var paginateCommunications = _amazonSupport.Paginators.DescribeCommunications(
            new DescribeCommunicationsRequest()
            {
                CaseId = caseId,
                AfterTime = afterTime?.ToString("s"),
                BeforeTime = beforeTime?.ToString("s")
            });
        // Get the entire list using the paginator.
        await foreach (var communications in paginateCommunications.Communications)
        {
            results.Add(communications);
        }
        return results;
    }



    /// <summary>
    /// Get case details for a list of case ids, optionally with date filters.
    /// </summary>
    /// <param name="caseIds">The list of case IDs.</param>
    /// <param name="displayId">Optional display ID.</param>
    /// <param name="includeCommunication">True to include communication. Defaults to true.</param>
    /// <param name="includeResolvedCases">True to include resolved cases. Defaults to false.</param>
    /// <param name="afterTime">The optional start date for a filtered search.</param>
    /// <param name="beforeTime">The optional end date for a filtered search.</param>
    /// <param name="language">Optional language support for your case.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <returns>A list of CaseDetails.</returns>
    public async Task<List<CaseDetails>> DescribeCases(List<string> caseIds, string? displayId = null, bool includeCommunication = true,
        bool includeResolvedCases = false, DateTime? afterTime = null, DateTime? beforeTime = null,
        string language = "en")
    {
        var results = new List<CaseDetails>();
        var paginateCases = _amazonSupport.Paginators.DescribeCases(
            new DescribeCasesRequest()
            {
                CaseIdList = caseIds,
                DisplayId = displayId,
                IncludeCommunications = includeCommunication,
                IncludeResolvedCases = includeResolvedCases,
                AfterTime = afterTime?.ToString("s"),
                BeforeTime = beforeTime?.ToString("s"),
                Language = language
            });
        // Get the entire list using the paginator.
        await foreach (var cases in paginateCases.Cases)
        {
            results.Add(cases);
        }
        return results;
    }



    /// <summary>
    /// Resolve a support case by caseId.
    /// </summary>
    /// <param name="caseId">Id for the support case.</param>
    /// <returns>The final status of the case after resolving.</returns>
    public async Task<string> ResolveCase(string caseId)
    {
        var response = await _amazonSupport.ResolveCaseAsync(
            new ResolveCaseRequest()
            {
                CaseId = caseId
            });
        return response.FinalCaseStatus;
    }


    /// <summary>
    /// Verify the support level for AWS Support API access.
    /// </summary>
    /// <returns>True if the subscription level supports API access.</returns>
    public async Task<bool> VerifySubscription()
    {
        try
        {
            var response = await _amazonSupport.DescribeServicesAsync(
                new DescribeServicesRequest()
                {
                    Language = "en"
                });
            return response.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (Amazon.AWSSupport.AmazonAWSSupportException ex)
        {
            if (ex.ErrorCode == "SubscriptionRequiredException")
            {
                return false;
            }
            else throw;
        }
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AddAttachmentsToSet](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/AddAttachmentsToSet)
  + [AddCommunicationToCase](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/AddCommunicationToCase)
  + [CreateCase](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/CreateCase)
  + [DescribeAttachment](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeAttachment)
  + [DescribeCases](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeCases)
  + [DescribeCommunications](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeCommunications)
  + [DescribeServices](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeServices)
  + [DescribeSeverityLevels](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeSeverityLevels)
  + [ResolveCase](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/ResolveCase)

## アクション
<a name="actions"></a>

### `AddAttachmentsToSet`
<a name="support_AddAttachmentsToSet_csharp_3_topic"></a>

次のコード例は、`AddAttachmentsToSet` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Add an attachment to a set, or create a new attachment set if one does not exist.
    /// </summary>
    /// <param name="data">The data for the attachment.</param>
    /// <param name="fileName">The file name for the attachment.</param>
    /// <param name="attachmentSetId">Optional setId for the attachment. Creates a new attachment set if empty.</param>
    /// <returns>The setId of the attachment.</returns>
    public async Task<string> AddAttachmentToSet(MemoryStream data, string fileName, string? attachmentSetId = null)
    {
        var response = await _amazonSupport.AddAttachmentsToSetAsync(
            new AddAttachmentsToSetRequest
            {
                AttachmentSetId = attachmentSetId,
                Attachments = new List<Attachment>
                {
                    new Attachment
                    {
                        Data = data,
                        FileName = fileName
                    }
                }
            });
        return response.AttachmentSetId;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AddAttachmentsToSet](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/AddAttachmentsToSet)」を参照してください。

### `AddCommunicationToCase`
<a name="support_AddCommunicationToCase_csharp_3_topic"></a>

次のコード例は、`AddCommunicationToCase` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Add communication to a case, including optional attachment set ID and CC email addresses.
    /// </summary>
    /// <param name="caseId">Id for the support case.</param>
    /// <param name="body">Body text of the communication.</param>
    /// <param name="attachmentSetId">Optional Id for an attachment set.</param>
    /// <param name="ccEmailAddresses">Optional list of CC email addresses.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> AddCommunicationToCase(string caseId, string body,
        string? attachmentSetId = null, List<string>? ccEmailAddresses = null)
    {
        var response = await _amazonSupport.AddCommunicationToCaseAsync(
            new AddCommunicationToCaseRequest()
            {
                CaseId = caseId,
                CommunicationBody = body,
                AttachmentSetId = attachmentSetId,
                CcEmailAddresses = ccEmailAddresses
            });
        return response.Result;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AddCommunicationToCase](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/AddCommunicationToCase)」を参照してください。

### `CreateCase`
<a name="support_CreateCase_csharp_3_topic"></a>

次のコード例は、`CreateCase` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a new support case.
    /// </summary>
    /// <param name="serviceCode">Service code for the new case.</param>
    /// <param name="categoryCode">Category for the new case.</param>
    /// <param name="severityCode">Severity code for the new case.</param>
    /// <param name="subject">Subject of the new case.</param>
    /// <param name="body">Body text of the new case.</param>
    /// <param name="language">Optional language support for your case.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <param name="attachmentSetId">Optional Id for an attachment set for the new case.</param>
    /// <param name="issueType">Optional issue type for the new case. Options are "customer-service" or "technical".</param>
    /// <returns>The caseId of the new support case.</returns>
    public async Task<string> CreateCase(string serviceCode, string categoryCode, string severityCode, string subject,
        string body, string language = "en", string? attachmentSetId = null, string issueType = "customer-service")
    {
        var response = await _amazonSupport.CreateCaseAsync(
            new CreateCaseRequest()
            {
                ServiceCode = serviceCode,
                CategoryCode = categoryCode,
                SeverityCode = severityCode,
                Subject = subject,
                Language = language,
                AttachmentSetId = attachmentSetId,
                IssueType = issueType,
                CommunicationBody = body
            });
        return response.CaseId;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateCase](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/CreateCase)」を参照してください。

### `DescribeAttachment`
<a name="support_DescribeAttachment_csharp_3_topic"></a>

次のコード例は、`DescribeAttachment` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get description of a specific attachment.
    /// </summary>
    /// <param name="attachmentId">Id of the attachment, usually fetched by describing the communications of a case.</param>
    /// <returns>The attachment object.</returns>
    public async Task<Attachment> DescribeAttachment(string attachmentId)
    {
        var response = await _amazonSupport.DescribeAttachmentAsync(
            new DescribeAttachmentRequest()
            {
                AttachmentId = attachmentId
            });
        return response.Attachment;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeAttachment](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeAttachment)」を参照してください。

### `DescribeCases`
<a name="support_DescribeCases_csharp_3_topic"></a>

次のコード例は、`DescribeCases` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get case details for a list of case ids, optionally with date filters.
    /// </summary>
    /// <param name="caseIds">The list of case IDs.</param>
    /// <param name="displayId">Optional display ID.</param>
    /// <param name="includeCommunication">True to include communication. Defaults to true.</param>
    /// <param name="includeResolvedCases">True to include resolved cases. Defaults to false.</param>
    /// <param name="afterTime">The optional start date for a filtered search.</param>
    /// <param name="beforeTime">The optional end date for a filtered search.</param>
    /// <param name="language">Optional language support for your case.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <returns>A list of CaseDetails.</returns>
    public async Task<List<CaseDetails>> DescribeCases(List<string> caseIds, string? displayId = null, bool includeCommunication = true,
        bool includeResolvedCases = false, DateTime? afterTime = null, DateTime? beforeTime = null,
        string language = "en")
    {
        var results = new List<CaseDetails>();
        var paginateCases = _amazonSupport.Paginators.DescribeCases(
            new DescribeCasesRequest()
            {
                CaseIdList = caseIds,
                DisplayId = displayId,
                IncludeCommunications = includeCommunication,
                IncludeResolvedCases = includeResolvedCases,
                AfterTime = afterTime?.ToString("s"),
                BeforeTime = beforeTime?.ToString("s"),
                Language = language
            });
        // Get the entire list using the paginator.
        await foreach (var cases in paginateCases.Cases)
        {
            results.Add(cases);
        }
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeCases](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeCases)」を参照してください。

### `DescribeCommunications`
<a name="support_DescribeCommunications_csharp_3_topic"></a>

次のコード例は、`DescribeCommunications` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe the communications for a case, optionally with a date filter.
    /// </summary>
    /// <param name="caseId">The ID of the support case.</param>
    /// <param name="afterTime">The optional start date for a filtered search.</param>
    /// <param name="beforeTime">The optional end date for a filtered search.</param>
    /// <returns>The list of communications for the case.</returns>
    public async Task<List<Communication>> DescribeCommunications(string caseId, DateTime? afterTime = null, DateTime? beforeTime = null)
    {
        var results = new List<Communication>();
        var paginateCommunications = _amazonSupport.Paginators.DescribeCommunications(
            new DescribeCommunicationsRequest()
            {
                CaseId = caseId,
                AfterTime = afterTime?.ToString("s"),
                BeforeTime = beforeTime?.ToString("s")
            });
        // Get the entire list using the paginator.
        await foreach (var communications in paginateCommunications.Communications)
        {
            results.Add(communications);
        }
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeCommunications](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeCommunications)」を参照してください。

### `DescribeServices`
<a name="support_DescribeServices_csharp_3_topic"></a>

次のコード例は、`DescribeServices` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the descriptions of AWS services.
    /// </summary>
    /// <param name="name">Optional language for services.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <returns>The list of AWS service descriptions.</returns>
    public async Task<List<Service>> DescribeServices(string language = "en")
    {
        var response = await _amazonSupport.DescribeServicesAsync(
            new DescribeServicesRequest()
            {
                Language = language
            });
        return response.Services;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeServices](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeServices)」を参照してください。

### `DescribeSeverityLevels`
<a name="support_DescribeSeverityLevels_csharp_3_topic"></a>

次のコード例は、`DescribeSeverityLevels` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the descriptions of support severity levels.
    /// </summary>
    /// <param name="name">Optional language for severity levels.
    /// Currently Chinese (“zh”), English ("en"), Japanese ("ja") and Korean (“ko”) are supported.</param>
    /// <returns>The list of support severity levels.</returns>
    public async Task<List<SeverityLevel>> DescribeSeverityLevels(string language = "en")
    {
        var response = await _amazonSupport.DescribeSeverityLevelsAsync(
            new DescribeSeverityLevelsRequest()
            {
                Language = language
            });
        return response.SeverityLevels;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeSeverityLevels](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/DescribeSeverityLevels)」を参照してください。

### `ResolveCase`
<a name="support_ResolveCase_csharp_3_topic"></a>

次のコード例は、`ResolveCase` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Support#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Resolve a support case by caseId.
    /// </summary>
    /// <param name="caseId">Id for the support case.</param>
    /// <returns>The final status of the case after resolving.</returns>
    public async Task<string> ResolveCase(string caseId)
    {
        var response = await _amazonSupport.ResolveCaseAsync(
            new ResolveCaseRequest()
            {
                CaseId = caseId
            });
        return response.FinalCaseStatus;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ResolveCase](https://docs.aws.amazon.com/goto/DotNetSDKV3/support-2013-04-15/ResolveCase)」を参照してください。

# を使用した Amazon Textract の例 SDK for .NET
<a name="csharp_3_textract_code_examples"></a>

次のコード例は、Amazon Textract AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_csharp_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for .NET**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/FeedbackSentimentAnalyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# を使用した Amazon Transcribe の例 SDK for .NET
<a name="csharp_3_transcribe_code_examples"></a>

次のコード例は、Amazon Transcribe AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateVocabulary`
<a name="transcribe_CreateVocabulary_csharp_3_topic"></a>

次のコード例は、`CreateVocabulary` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a custom vocabulary using a list of phrases. Custom vocabularies
    /// improve transcription accuracy for one or more specific words.
    /// </summary>
    /// <param name="languageCode">The language code of the vocabulary.</param>
    /// <param name="phrases">Phrases to use in the vocabulary.</param>
    /// <param name="vocabularyName">Name for the vocabulary.</param>
    /// <returns>The state of the custom vocabulary.</returns>
    public async Task<VocabularyState> CreateCustomVocabulary(LanguageCode languageCode,
        List<string> phrases, string vocabularyName)
    {
        var response = await _amazonTranscribeService.CreateVocabularyAsync(
            new CreateVocabularyRequest
            {
                LanguageCode = languageCode,
                Phrases = phrases,
                VocabularyName = vocabularyName
            });
        return response.VocabularyState;
    }
```
+  API の詳細については、[AWS SDK for .NET API リファレンス](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/CreateVocabulary)の「*CreateVocabulary*」を参照してください。

### `DeleteMedicalTranscriptionJob`
<a name="transcribe_DeleteMedicalTranscriptionJob_csharp_3_topic"></a>

次のコード例は、`DeleteMedicalTranscriptionJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a medical transcription job. Also deletes the transcript associated with the job.
    /// </summary>
    /// <param name="jobName">Name of the medical transcription job to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteMedicalTranscriptionJob(string jobName)
    {
        var response = await _amazonTranscribeService.DeleteMedicalTranscriptionJobAsync(
            new DeleteMedicalTranscriptionJobRequest()
            {
                MedicalTranscriptionJobName = jobName
            });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteMedicalTranscriptionJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/DeleteMedicalTranscriptionJob)」を参照してください。

### `DeleteTranscriptionJob`
<a name="transcribe_DeleteTranscriptionJob_csharp_3_topic"></a>

次のコード例は、`DeleteTranscriptionJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a transcription job. Also deletes the transcript associated with the job.
    /// </summary>
    /// <param name="jobName">Name of the transcription job to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteTranscriptionJob(string jobName)
    {
        var response = await _amazonTranscribeService.DeleteTranscriptionJobAsync(
            new DeleteTranscriptionJobRequest()
            {
                TranscriptionJobName = jobName
            });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DeleteTranscriptionJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/DeleteTranscriptionJob)」を参照してください。

### `DeleteVocabulary`
<a name="transcribe_DeleteVocabulary_csharp_3_topic"></a>

次のコード例は、`DeleteVocabulary` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an existing custom vocabulary.
    /// </summary>
    /// <param name="vocabularyName">Name of the vocabulary to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteCustomVocabulary(string vocabularyName)
    {
        var response = await _amazonTranscribeService.DeleteVocabularyAsync(
            new DeleteVocabularyRequest
            {
                VocabularyName = vocabularyName
            });
        return response.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteVocabulary](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/DeleteVocabulary)」を参照してください。

### `GetTranscriptionJob`
<a name="transcribe_GetTranscriptionJob_csharp_3_topic"></a>

次のコード例は、`GetTranscriptionJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get details about a transcription job.
    /// </summary>
    /// <param name="jobName">A unique name for the transcription job.</param>
    /// <returns>A TranscriptionJob instance with information on the requested job.</returns>
    public async Task<TranscriptionJob> GetTranscriptionJob(string jobName)
    {
        var response = await _amazonTranscribeService.GetTranscriptionJobAsync(
            new GetTranscriptionJobRequest()
            {
                TranscriptionJobName = jobName
            });
        return response.TranscriptionJob;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetTranscriptionJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/GetTranscriptionJob)」を参照してください。

### `GetVocabulary`
<a name="transcribe_GetVocabulary_csharp_3_topic"></a>

次のコード例は、`GetVocabulary` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information about a custom vocabulary.
    /// </summary>
    /// <param name="vocabularyName">Name of the vocabulary.</param>
    /// <returns>The state of the custom vocabulary.</returns>
    public async Task<VocabularyState> GetCustomVocabulary(string vocabularyName)
    {
        var response = await _amazonTranscribeService.GetVocabularyAsync(
            new GetVocabularyRequest()
            {
                VocabularyName = vocabularyName
            });
        return response.VocabularyState;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetVocabulary](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/GetVocabulary)」を参照してください。

### `ListMedicalTranscriptionJobs`
<a name="transcribe_ListMedicalTranscriptionJobs_csharp_3_topic"></a>

次のコード例は、`ListMedicalTranscriptionJobs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List medical transcription jobs, optionally with a name filter.
    /// </summary>
    /// <param name="jobNameContains">Optional name filter for the medical transcription jobs.</param>
    /// <returns>A list of summaries about medical transcription jobs.</returns>
    public async Task<List<MedicalTranscriptionJobSummary>> ListMedicalTranscriptionJobs(
        string? jobNameContains = null)
    {
        var response = await _amazonTranscribeService.ListMedicalTranscriptionJobsAsync(
            new ListMedicalTranscriptionJobsRequest()
            {
                JobNameContains = jobNameContains
            });
        return response.MedicalTranscriptionJobSummaries;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListMedicalTranscriptionJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/ListMedicalTranscriptionJobs)」を参照してください。

### `ListTranscriptionJobs`
<a name="transcribe_ListTranscriptionJobs_csharp_3_topic"></a>

次のコード例は、`ListTranscriptionJobs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List transcription jobs, optionally with a name filter.
    /// </summary>
    /// <param name="jobNameContains">Optional name filter for the transcription jobs.</param>
    /// <returns>A list of transcription job summaries.</returns>
    public async Task<List<TranscriptionJobSummary>> ListTranscriptionJobs(string? jobNameContains = null)
    {
        var response = await _amazonTranscribeService.ListTranscriptionJobsAsync(
            new ListTranscriptionJobsRequest()
            {
                JobNameContains = jobNameContains
            });
        return response.TranscriptionJobSummaries;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListTranscriptionJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/ListTranscriptionJobs)」を参照してください。

### `ListVocabularies`
<a name="transcribe_ListVocabularies_csharp_3_topic"></a>

次のコード例は、`ListVocabularies` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List custom vocabularies for the current account. Optionally specify a name
    /// filter and a specific state to filter the vocabularies list.
    /// </summary>
    /// <param name="nameContains">Optional string the vocabulary name must contain.</param>
    /// <param name="stateEquals">Optional state of the vocabulary.</param>
    /// <returns>List of information about the vocabularies.</returns>
    public async Task<List<VocabularyInfo>> ListCustomVocabularies(string? nameContains = null,
        VocabularyState? stateEquals = null)
    {
        var response = await _amazonTranscribeService.ListVocabulariesAsync(
            new ListVocabulariesRequest()
            {
                NameContains = nameContains,
                StateEquals = stateEquals
            });
        return response.Vocabularies;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListVocabularies](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/ListVocabularies)」を参照してください。

### `StartMedicalTranscriptionJob`
<a name="transcribe_StartMedicalTranscriptionJob_csharp_3_topic"></a>

次のコード例は、`StartMedicalTranscriptionJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Start a medical transcription job for a media file. This method returns
    /// as soon as the job is started.
    /// </summary>
    /// <param name="jobName">A unique name for the medical transcription job.</param>
    /// <param name="mediaFileUri">The URI of the media file, typically an Amazon S3 location.</param>
    /// <param name="mediaFormat">The format of the media file.</param>
    /// <param name="outputBucketName">Location for the output, typically an Amazon S3 location.</param>
    /// <param name="transcriptionType">Conversation or dictation transcription type.</param>
    /// <returns>A MedicalTransactionJob instance with information on the new job.</returns>
    public async Task<MedicalTranscriptionJob> StartMedicalTranscriptionJob(
        string jobName, string mediaFileUri,
        MediaFormat mediaFormat, string outputBucketName, Amazon.TranscribeService.Type transcriptionType)
    {
        var response = await _amazonTranscribeService.StartMedicalTranscriptionJobAsync(
            new StartMedicalTranscriptionJobRequest()
            {
                MedicalTranscriptionJobName = jobName,
                Media = new Media()
                {
                    MediaFileUri = mediaFileUri
                },
                MediaFormat = mediaFormat,
                LanguageCode =
                    LanguageCode
                        .EnUS, // The value must be en-US for medical transcriptions.
                OutputBucketName = outputBucketName,
                OutputKey =
                    jobName, // The value is a key used to fetch the output of the transcription.
                Specialty = Specialty.PRIMARYCARE, // The value PRIMARYCARE must be set.
                Type = transcriptionType
            });
        return response.MedicalTranscriptionJob;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[StartMedicalTranscriptionJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/StartMedicalTranscriptionJob)」を参照してください。

### `StartTranscriptionJob`
<a name="transcribe_StartTranscriptionJob_csharp_3_topic"></a>

次のコード例は、`StartTranscriptionJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Start a transcription job for a media file. This method returns
    /// as soon as the job is started.
    /// </summary>
    /// <param name="jobName">A unique name for the transcription job.</param>
    /// <param name="mediaFileUri">The URI of the media file, typically an Amazon S3 location.</param>
    /// <param name="mediaFormat">The format of the media file.</param>
    /// <param name="languageCode">The language code of the media file, such as en-US.</param>
    /// <param name="vocabularyName">Optional name of a custom vocabulary.</param>
    /// <returns>A TranscriptionJob instance with information on the new job.</returns>
    public async Task<TranscriptionJob> StartTranscriptionJob(string jobName, string mediaFileUri,
        MediaFormat mediaFormat, LanguageCode languageCode, string? vocabularyName)
    {
        var response = await _amazonTranscribeService.StartTranscriptionJobAsync(
            new StartTranscriptionJobRequest()
            {
                TranscriptionJobName = jobName,
                Media = new Media()
                {
                    MediaFileUri = mediaFileUri
                },
                MediaFormat = mediaFormat,
                LanguageCode = languageCode,
                Settings = vocabularyName != null ? new Settings()
                {
                    VocabularyName = vocabularyName
                } : null
            });
        return response.TranscriptionJob;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[StartTranscriptionJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/StartTranscriptionJob)」を参照してください。

### `UpdateVocabulary`
<a name="transcribe_UpdateVocabulary_csharp_3_topic"></a>

次のコード例は、`UpdateVocabulary` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Transcribe#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Update a custom vocabulary with new values. Update overwrites all existing information.
    /// </summary>
    /// <param name="languageCode">The language code of the vocabulary.</param>
    /// <param name="phrases">Phrases to use in the vocabulary.</param>
    /// <param name="vocabularyName">Name for the vocabulary.</param>
    /// <returns>The state of the custom vocabulary.</returns>
    public async Task<VocabularyState> UpdateCustomVocabulary(LanguageCode languageCode,
        List<string> phrases, string vocabularyName)
    {
        var response = await _amazonTranscribeService.UpdateVocabularyAsync(
            new UpdateVocabularyRequest()
            {
                LanguageCode = languageCode,
                Phrases = phrases,
                VocabularyName = vocabularyName
            });
        return response.VocabularyState;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[UpdateVocabulary](https://docs.aws.amazon.com/goto/DotNetSDKV3/transcribe-2017-10-26/UpdateVocabulary)」を参照してください。

# を使用した Amazon Translate の例 SDK for .NET
<a name="csharp_3_translate_code_examples"></a>

次のコード例は、Amazon Translate AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DescribeTextTranslationJob`
<a name="translate_DescribeTextTranslationJob_csharp_3_topic"></a>

次のコード例は、`DescribeTextTranslationJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Translate#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Translate;
    using Amazon.Translate.Model;

    /// <summary>
    /// The following example shows how to retrieve the details of
    /// a text translation job using Amazon Translate.
    /// </summary>
    public class DescribeTextTranslation
    {
        public static async Task Main()
        {
            var client = new AmazonTranslateClient();

            // The Job Id is generated when the text translation job is started
            // with a call to the StartTextTranslationJob method.
            var jobId = "1234567890abcdef01234567890abcde";

            var request = new DescribeTextTranslationJobRequest
            {
                JobId = jobId,
            };

            var jobProperties = await DescribeTranslationJobAsync(client, request);

            DisplayTranslationJobDetails(jobProperties);
        }

        /// <summary>
        /// Retrieve information about an Amazon Translate text translation job.
        /// </summary>
        /// <param name="client">The initialized Amazon Translate client object.</param>
        /// <param name="request">The DescribeTextTranslationJobRequest object.</param>
        /// <returns>The TextTranslationJobProperties object containing
        /// information about the text translation job..</returns>
        public static async Task<TextTranslationJobProperties> DescribeTranslationJobAsync(
            AmazonTranslateClient client,
            DescribeTextTranslationJobRequest request)
        {
            var response = await client.DescribeTextTranslationJobAsync(request);
            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                return response.TextTranslationJobProperties;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// Displays the properties of the text translation job.
        /// </summary>
        /// <param name="jobProperties">The properties of the text translation
        /// job returned by the call to DescribeTextTranslationJobAsync.</param>
        public static void DisplayTranslationJobDetails(TextTranslationJobProperties jobProperties)
        {
            if (jobProperties is null)
            {
                Console.WriteLine("No text translation job properties found.");
                return;
            }

            // Display the details of the text translation job.
            Console.WriteLine($"{jobProperties.JobId}: {jobProperties.JobName}");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeTextTranslationJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/translate-2017-07-01/DescribeTextTranslationJob)」を参照してください。

### `ListTextTranslationJobs`
<a name="translate_ListTextTranslationJobs_csharp_3_topic"></a>

次のコード例は、`ListTextTranslationJobs` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Translate#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Translate;
    using Amazon.Translate.Model;

    /// <summary>
    /// List Amazon Translate translation jobs, along with details about each job.
    /// </summary>
    public class ListTranslationJobs
    {
        public static async Task Main()
        {
            var client = new AmazonTranslateClient();
            var filter = new TextTranslationJobFilter
            {
                JobStatus = "COMPLETED",
            };

            var request = new ListTextTranslationJobsRequest
            {
                MaxResults = 10,
                Filter = filter,
            };

            await ListJobsAsync(client, request);
        }

        /// <summary>
        /// List Amazon Translate text translation jobs.
        /// </summary>
        /// <param name="client">The initialized Amazon Translate client object.</param>
        /// <param name="request">An Amazon Translate
        /// ListTextTranslationJobsRequest object detailing which text
        /// translation jobs are of interest.</param>
        public static async Task ListJobsAsync(
            AmazonTranslateClient client,
            ListTextTranslationJobsRequest request)
        {
            ListTextTranslationJobsResponse response;

            do
            {
                response = await client.ListTextTranslationJobsAsync(request);
                ShowTranslationJobDetails(response.TextTranslationJobPropertiesList);

                request.NextToken = response.NextToken;
            }
            while (response.NextToken is not null);
        }

        /// <summary>
        /// List existing translation job details.
        /// </summary>
        /// <param name="properties">A list of Amazon Translate text
        /// translation jobs.</param>
        public static void ShowTranslationJobDetails(List<TextTranslationJobProperties> properties)
        {
            properties.ForEach(prop =>
            {
                Console.WriteLine($"{prop.JobId}: {prop.JobName}");
                Console.WriteLine($"Status: {prop.JobStatus}");
                Console.WriteLine($"Submitted time: {prop.SubmittedTime}");
            });
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListTextTranslationJobs](https://docs.aws.amazon.com/goto/DotNetSDKV3/translate-2017-07-01/ListTextTranslationJobs)」を参照してください。

### `StartTextTranslationJob`
<a name="translate_StartTextTranslationJob_csharp_3_topic"></a>

次のコード例は、`StartTextTranslationJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Translate#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Amazon.Translate;
    using Amazon.Translate.Model;

    /// <summary>
    /// This example shows how to use Amazon Translate to process the files in
    /// an Amazon Simple Storage Service (Amazon S3) bucket. The translated results
    /// will also be stored in an Amazon S3 bucket.
    /// </summary>
    public class BatchTranslate
    {
        public static async Task Main()
        {
            var contentType = "text/plain";

            // Set this variable to an S3 bucket location with a folder."
            // Input files must be in a folder and not at the bucket root."
            var s3InputUri = "s3://amzn-s3-demo-bucket1/FOLDER/";
            var s3OutputUri = "s3://amzn-s3-demo-bucket2/";

            // This role must have permissions to read the source bucket and to read and
            // write to the destination bucket where the translated text will be stored.
            var dataAccessRoleArn = "arn:aws:iam::0123456789ab:role/S3TranslateRole";

            var client = new AmazonTranslateClient();

            var inputConfig = new InputDataConfig
            {
                ContentType = contentType,
                S3Uri = s3InputUri,
            };

            var outputConfig = new OutputDataConfig
            {
                S3Uri = s3OutputUri,
            };

            var request = new StartTextTranslationJobRequest
            {
                JobName = "ExampleTranslationJob",
                DataAccessRoleArn = dataAccessRoleArn,
                InputDataConfig = inputConfig,
                OutputDataConfig = outputConfig,
                SourceLanguageCode = "en",
                TargetLanguageCodes = new List<string> { "fr" },
            };

            var response = await StartTextTranslationAsync(client, request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"{response.JobId}: {response.JobStatus}");
            }
        }

        /// <summary>
        /// Start the Amazon Translate text translation job.
        /// </summary>
        /// <param name="client">The initialized AmazonTranslateClient object.</param>
        /// <param name="request">The request object that includes details such
        /// as source and destination bucket names and the IAM Role that will
        /// be used to access the buckets.</param>
        /// <returns>The StartTextTranslationResponse object that includes the
        /// details of the request response.</returns>
        public static async Task<StartTextTranslationJobResponse> StartTextTranslationAsync(AmazonTranslateClient client, StartTextTranslationJobRequest request)
        {
            var response = await client.StartTextTranslationJobAsync(request);
            return response;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[StartTextTranslationJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/translate-2017-07-01/StartTextTranslationJob)」を参照してください。

### `StopTextTranslationJob`
<a name="translate_StopTextTranslationJob_csharp_3_topic"></a>

次のコード例は、`StopTextTranslationJob` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Translate#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.Threading.Tasks;
    using Amazon.Translate;
    using Amazon.Translate.Model;

    /// <summary>
    /// Shows how to stop a running Amazon Translation Service text translation
    /// job.
    /// </summary>
    public class StopTextTranslationJob
    {
        public static async Task Main()
        {
            var client = new AmazonTranslateClient();
            var jobId = "1234567890abcdef01234567890abcde";

            var request = new StopTextTranslationJobRequest
            {
                JobId = jobId,
            };

            await StopTranslationJobAsync(client, request);
        }

        /// <summary>
        /// Sends a request to stop a text translation job.
        /// </summary>
        /// <param name="client">Initialized AmazonTrnslateClient object.</param>
        /// <param name="request">The request object to be passed to the
        /// StopTextJobAsync method.</param>
        public static async Task StopTranslationJobAsync(
            AmazonTranslateClient client,
            StopTextTranslationJobRequest request)
        {
            var response = await client.StopTextTranslationJobAsync(request);
            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"{response.JobId} as status: {response.JobStatus}");
            }
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[StopTextTranslationJob](https://docs.aws.amazon.com/goto/DotNetSDKV3/translate-2017-07-01/StopTextTranslationJob)」を参照してください。

### `TranslateText`
<a name="translate_TranslateText_csharp_3_topic"></a>

次のコード例は、`TranslateText` を使用する方法を示しています。

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/Translate#code-examples)での設定と実行の方法を確認してください。

```
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Amazon.S3;
    using Amazon.S3.Transfer;
    using Amazon.Translate;
    using Amazon.Translate.Model;

    /// <summary>
    /// Take text from a file stored a Amazon Simple Storage Service (Amazon S3)
    /// object and translate it using the Amazon Transfer Service.
    /// </summary>
    public class TranslateText
    {
        public static async Task Main()
        {
            // If the region you want to use is different from the region
            // defined for the default user, supply it as a parameter to the
            // Amazon Translate client object constructor.
            var client = new AmazonTranslateClient();

            // Set the source language to "auto" to request Amazon Translate to
            // automatically detect te language of the source text.

            // You can get a list of the languages supposed by Amazon Translate
            // in the Amazon Translate Developer's Guide here:
            //      https://docs.aws.amazon.com/translate/latest/dg/what-is.html
            string srcLang = "en"; // English.
            string destLang = "fr"; // French.

            // The Amazon Simple Storage Service (Amazon S3) bucket where the
            // source text file is stored.
            string srcBucket = "amzn-s3-demo-bucket";
            string srcTextFile = "source.txt";

            var srcText = await GetSourceTextAsync(srcBucket, srcTextFile);
            var destText = await TranslatingTextAsync(client, srcLang, destLang, srcText);

            ShowText(srcText, destText);
        }

        /// <summary>
        /// Use the Amazon S3 TransferUtility to retrieve the text to translate
        /// from an object in an S3 bucket.
        /// </summary>
        /// <param name="srcBucket">The name of the S3 bucket where the
        /// text is stored.
        /// </param>
        /// <param name="srcTextFile">The key of the S3 object that
        /// contains the text to translate.</param>
        /// <returns>A string representing the source text.</returns>
        public static async Task<string> GetSourceTextAsync(string srcBucket, string srcTextFile)
        {
            string srcText = string.Empty;

            var s3Client = new AmazonS3Client();
            TransferUtility utility = new TransferUtility(s3Client);

            using var stream = await utility.OpenStreamAsync(srcBucket, srcTextFile);

            StreamReader file = new System.IO.StreamReader(stream);

            srcText = file.ReadToEnd();
            return srcText;
        }

        /// <summary>
        /// Use the Amazon Translate Service to translate the document from the
        /// source language to the specified destination language.
        /// </summary>
        /// <param name="client">The Amazon Translate Service client used to
        /// perform the translation.</param>
        /// <param name="srcLang">The language of the source text.</param>
        /// <param name="destLang">The destination language for the translated
        /// text.</param>
        /// <param name="text">A string representing the text to ranslate.</param>
        /// <returns>The text that has been translated to the destination
        /// language.</returns>
        public static async Task<string> TranslatingTextAsync(AmazonTranslateClient client, string srcLang, string destLang, string text)
        {
            var request = new TranslateTextRequest
            {
                SourceLanguageCode = srcLang,
                TargetLanguageCode = destLang,
                Text = text,
            };

            var response = await client.TranslateTextAsync(request);

            return response.TranslatedText;
        }

        /// <summary>
        /// Show the original text followed by the translated text.
        /// </summary>
        /// <param name="srcText">The original text to be translated.</param>
        /// <param name="destText">The translated text.</param>
        public static void ShowText(string srcText, string destText)
        {
            Console.WriteLine("Source text:");
            Console.WriteLine(srcText);
            Console.WriteLine();
            Console.WriteLine("Translated text:");
            Console.WriteLine(destText);
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[TranslateText](https://docs.aws.amazon.com/goto/DotNetSDKV3/translate-2017-07-01/TranslateText)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon SNS アプリケーションの構築
<a name="cross_SnsPublishSubscription_csharp_3_topic"></a>

次のコード例は、サブスクリプションとパブリッシュ機能を持ち、メッセージを翻訳するアプリケーションを作成する方法を示しています。

**SDK for .NET**  
 Amazon Simple Notification Service .NET API を使用して、サブスクリプションおよびパブリッシュ機能を持つウェブアプリケーションを作成する方法を説明します。さらに、このサンプルアプリケーションではメッセージを翻訳します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/SubscribePublishTranslate) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon SNS
+ Amazon Translate

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_csharp_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for .NET**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/FeedbackSentimentAnalyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for .NET (v4) のコード例
<a name="csharp_4_code_examples"></a>

次のコード例は、 で AWS SDK for .NET (v4) を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [SDK for .NET (v4) デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-net/v4/developer-guide/welcome.html) ** – で .NET を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23dotnet)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [Aurora](csharp_4_aurora_code_examples.md)
+ [Auto Scaling](csharp_4_auto-scaling_code_examples.md)
+ [Amazon Bedrock](csharp_4_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](csharp_4_bedrock-runtime_code_examples.md)
+ [CloudFormation](csharp_4_cloudformation_code_examples.md)
+ [CloudWatch](csharp_4_cloudwatch_code_examples.md)
+ [CloudWatch Logs](csharp_4_cloudwatch-logs_code_examples.md)
+ [Amazon Cognito ID プロバイダー](csharp_4_cognito-identity-provider_code_examples.md)
+ [AWS Control Tower](csharp_4_controltower_code_examples.md)
+ [DynamoDB](csharp_4_dynamodb_code_examples.md)
+ [Amazon EC2](csharp_4_ec2_code_examples.md)
+ [Amazon ECS](csharp_4_ecs_code_examples.md)
+ [AWS IoT](csharp_4_iot_code_examples.md)
+ [AWS IoT data](csharp_4_iot-data-plane_code_examples.md)
+ [Amazon Redshift](csharp_4_redshift_code_examples.md)
+ [Amazon S3](csharp_4_s3_code_examples.md)

# SDK for .NET (v4) を使用した Aurora の例
<a name="csharp_4_aurora_code_examples"></a>

次のコード例は、Aurora で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Aurora
<a name="aurora_Hello_csharp_4_topic"></a>

次のコード例は、Aurora の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.RDS;
using Amazon.RDS.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace AuroraActions;

public static class HelloAurora
{
    static async Task Main(string[] args)
    {
        // Use the AWS .NET Core Setup package to set up dependency injection for the
        // Amazon Relational Database Service (Amazon RDS).
        // Use your AWS profile name, or leave it blank to use the default profile.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonRDS>()
            ).Build();

        // Now the client is available for injection. Fetching it directly here for example purposes only.
        var rdsClient = host.Services.GetRequiredService<IAmazonRDS>();

        // You can use await and any of the async methods to get a response.
        var response = await rdsClient.DescribeDBClustersAsync(new DescribeDBClustersRequest { IncludeShared = true });
        Console.WriteLine($"Hello Amazon RDS Aurora! Let's list some clusters in this account:");
        if (response.DBClusters == null)
        {
            Console.WriteLine($"\tNo clusters found.");
        }
        else
        {
            foreach (var cluster in response.DBClusters)
            {
                Console.WriteLine(
                    $"\tCluster: database: {cluster.DatabaseName} identifier: {cluster.DBClusterIdentifier}.");
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="aurora_Scenario_GetStartedClusters_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム Aurora DB クラスターパラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用する DB クラスターを作成する
+ データベースを含む DB インスタンスを作成します。
+ DB クラスターのスナップショットを作成して、リソースをクリーンアップします。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
using Amazon.RDS;
using Amazon.RDS.Model;
using AuroraActions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;

namespace AuroraScenario;

/// <summary>
/// Scenario for Amazon Aurora examples.
/// </summary>
public class AuroraScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    This .NET example performs the following tasks:
    1.  Return a list of the available DB engine families for Aurora MySql using the DescribeDBEngineVersionsAsync method.
    2.  Select an engine family and create a custom DB cluster parameter group using the CreateDBClusterParameterGroupAsync method.
    3.  Get the parameter group using the DescribeDBClusterParameterGroupsAsync method.
    4.  Get some parameters in the group using the DescribeDBClusterParametersAsync method.
    5.  Parse and display some parameters in the group.
    6.  Modify the auto_increment_offset and auto_increment_increment parameters
        using the ModifyDBClusterParameterGroupAsync method.
    7.  Get and display the updated parameters using the DescribeDBClusterParametersAsync method with a source of "user".
    8.  Get a list of allowed engine versions using the DescribeDBEngineVersionsAsync method.
    9.  Create an Aurora DB cluster that contains a MySql database and uses the parameter group.
        using the CreateDBClusterAsync method.
    10. Wait for the DB cluster to be ready using the DescribeDBClustersAsync method.
    11. Display and select from a list of instance classes available for the selected engine and version
        using the paginated DescribeOrderableDBInstanceOptions method.
    12. Create a database instance in the cluster using the CreateDBInstanceAsync method.
    13. Wait for the DB instance to be ready using the DescribeDBInstances method.
    14. Display the connection endpoint string for the new DB cluster.
    15. Create a snapshot of the DB cluster using the CreateDBClusterSnapshotAsync method.
    16. Wait for DB snapshot to be ready using the DescribeDBClusterSnapshotsAsync method.
    17. Delete the DB instance using the DeleteDBInstanceAsync method.
    18. Delete the DB cluster using the DeleteDBClusterAsync method.
    19. Wait for DB cluster to be deleted using the DescribeDBClustersAsync methods.
    20. Delete the cluster parameter group using the DeleteDBClusterParameterGroupAsync.
    */

    private static readonly string sepBar = new('-', 80);
    private static AuroraWrapper auroraWrapper = null!;
    private static ILogger logger = null!;
    private static readonly string engine = "aurora-mysql";
    static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon Relational Database Service (Amazon RDS).
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonRDS>()
                    .AddTransient<AuroraWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        }).CreateLogger<AuroraScenario>();

        auroraWrapper = host.Services.GetRequiredService<AuroraWrapper>();

        Console.WriteLine(sepBar);
        Console.WriteLine(
            "Welcome to the Amazon Aurora: get started with DB clusters example.");
        Console.WriteLine(sepBar);

        DBClusterParameterGroup parameterGroup = null!;
        DBCluster? newCluster = null;
        DBInstance? newInstance = null;

        try
        {
            var parameterGroupFamily = await ChooseParameterGroupFamilyAsync();

            parameterGroup = await CreateDBParameterGroupAsync(parameterGroupFamily);

            var parameters = await DescribeParametersInGroupAsync(parameterGroup.DBClusterParameterGroupName,
                new List<string> { "auto_increment_offset", "auto_increment_increment" });

            await ModifyParametersAsync(parameterGroup.DBClusterParameterGroupName, parameters);

            await DescribeUserSourceParameters(parameterGroup.DBClusterParameterGroupName);

            var engineVersionChoice = await ChooseDBEngineVersionAsync(parameterGroupFamily);

            var newClusterIdentifier = "Example-Cluster-" + DateTime.Now.Ticks;

            newCluster = await CreateNewCluster
            (
                parameterGroup,
                engine,
                engineVersionChoice.EngineVersion,
                newClusterIdentifier
            );

            var instanceClassChoice = await ChooseDBInstanceClass(engine, engineVersionChoice.EngineVersion);

            var newInstanceIdentifier = "Example-Instance-" + DateTime.Now.Ticks;

            newInstance = await CreateNewInstance(
                newClusterIdentifier,
                engine,
                engineVersionChoice.EngineVersion,
                instanceClassChoice.DBInstanceClass,
                newInstanceIdentifier
            );

            DisplayConnectionString(newCluster!);
            await CreateSnapshot(newCluster!);
            await CleanupResources(newInstance, newCluster, parameterGroup);

            Console.WriteLine("Scenario complete.");
            Console.WriteLine(sepBar);
        }
        catch (Exception ex)
        {
            await CleanupResources(newInstance, newCluster, parameterGroup);
            logger.LogError(ex, "There was a problem executing the scenario.");
        }
    }

    /// <summary>
    /// Choose the Aurora DB parameter group family from a list of available options.
    /// </summary>
    /// <returns>The selected parameter group family.</returns>
    public static async Task<string> ChooseParameterGroupFamilyAsync()
    {
        Console.WriteLine(sepBar);
        // 1. Get a list of available engines.
        var engines = await auroraWrapper.DescribeDBEngineVersionsForEngineAsync(engine);

        Console.WriteLine($"1. The following is a list of available DB parameter group families for engine {engine}:");

        var parameterGroupFamilies =
            engines.GroupBy(e => e.DBParameterGroupFamily).ToList();
        for (var i = 1; i <= parameterGroupFamilies.Count; i++)
        {
            var parameterGroupFamily = parameterGroupFamilies[i - 1];
            // List the available parameter group families.
            Console.WriteLine(
                $"\t{i}. Family: {parameterGroupFamily.Key}");
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > parameterGroupFamilies.Count)
        {
            Console.WriteLine("2. Select an available DB parameter group family by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }
        var parameterGroupFamilyChoice = parameterGroupFamilies[choiceNumber - 1];
        Console.WriteLine(sepBar);
        return parameterGroupFamilyChoice.Key;
    }

    /// <summary>
    /// Create and get information on a DB parameter group.
    /// </summary>
    /// <param name="dbParameterGroupFamily">The DBParameterGroupFamily for the new DB parameter group.</param>
    /// <returns>The new DBParameterGroup.</returns>
    public static async Task<DBClusterParameterGroup> CreateDBParameterGroupAsync(string dbParameterGroupFamily)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine($"2. Create new DB parameter group with family {dbParameterGroupFamily}:");

        var parameterGroup = await auroraWrapper.CreateCustomClusterParameterGroupAsync(
            dbParameterGroupFamily,
            "ExampleParameterGroup-" + DateTime.Now.Ticks,
            "New example parameter group");

        var groupInfo =
            await auroraWrapper.DescribeCustomDBClusterParameterGroupAsync(parameterGroup.DBClusterParameterGroupName);

        Console.WriteLine(
            $"3. New DB parameter group created: \n\t{groupInfo?.Description}, \n\tARN {groupInfo?.DBClusterParameterGroupName}");
        Console.WriteLine(sepBar);
        return parameterGroup;
    }

    /// <summary>
    /// Get and describe parameters from a DBParameterGroup.
    /// </summary>
    /// <param name="parameterGroupName">The name of the DBParameterGroup.</param>
    /// <param name="parameterNames">Optional specific names of parameters to describe.</param>
    /// <returns>The list of requested parameters.</returns>
    public static async Task<List<Parameter>> DescribeParametersInGroupAsync(string parameterGroupName, List<string>? parameterNames = null)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine("4. Get some parameters from the group.");
        Console.WriteLine(sepBar);

        var parameters =
            await auroraWrapper.DescribeDBClusterParametersInGroupAsync(parameterGroupName);

        var matchingParameters =
            parameters.Where(p => parameterNames == null || parameterNames.Contains(p.ParameterName)).ToList();

        Console.WriteLine("5. Parameter information:");
        matchingParameters.ForEach(p =>
            Console.WriteLine(
                $"\n\tParameter: {p.ParameterName}." +
                $"\n\tDescription: {p.Description}." +
                $"\n\tAllowed Values: {p.AllowedValues}." +
                $"\n\tValue: {p.ParameterValue}."));

        Console.WriteLine(sepBar);

        return matchingParameters;
    }

    /// <summary>
    /// Modify a parameter from a DBParameterGroup.
    /// </summary>
    /// <param name="parameterGroupName">Name of the DBParameterGroup.</param>
    /// <param name="parameters">The parameters to modify.</param>
    /// <returns>Async task.</returns>
    public static async Task ModifyParametersAsync(string parameterGroupName, List<Parameter> parameters)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine("6. Modify some parameters in the group.");

        await auroraWrapper.ModifyIntegerParametersInGroupAsync(parameterGroupName, parameters);

        Console.WriteLine(sepBar);
    }

    /// <summary>
    /// Describe the user source parameters in the group.
    /// </summary>
    /// <param name="parameterGroupName">The name of the DBParameterGroup.</param>
    /// <returns>Async task.</returns>
    public static async Task DescribeUserSourceParameters(string parameterGroupName)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine("7. Describe updated user source parameters in the group.");

        var parameters =
            await auroraWrapper.DescribeDBClusterParametersInGroupAsync(parameterGroupName, "user");

        parameters.ForEach(p =>
            Console.WriteLine(
                $"\n\tParameter: {p.ParameterName}." +
                $"\n\tDescription: {p.Description}." +
                $"\n\tAllowed Values: {p.AllowedValues}." +
                $"\n\tValue: {p.ParameterValue}."));

        Console.WriteLine(sepBar);
    }

    /// <summary>
    /// Choose a DB engine version.
    /// </summary>
    /// <param name="dbParameterGroupFamily">DB parameter group family for engine choice.</param>
    /// <returns>The selected engine version.</returns>
    public static async Task<DBEngineVersion> ChooseDBEngineVersionAsync(string dbParameterGroupFamily)
    {
        Console.WriteLine(sepBar);
        // Get a list of allowed engines.
        var allowedEngines =
            await auroraWrapper.DescribeDBEngineVersionsForEngineAsync(engine, dbParameterGroupFamily);

        Console.WriteLine($"Available DB engine versions for parameter group family {dbParameterGroupFamily}:");
        int i = 1;
        foreach (var version in allowedEngines)
        {
            Console.WriteLine(
                $"\t{i}. {version.DBEngineVersionDescription}.");
            i++;
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > allowedEngines.Count)
        {
            Console.WriteLine("8. Select an available DB engine version by entering a number from the list above:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }

        var engineChoice = allowedEngines[choiceNumber - 1];
        Console.WriteLine(sepBar);
        return engineChoice;
    }

    /// <summary>
    /// Create a new RDS DB cluster.
    /// </summary>
    /// <param name="parameterGroup">Parameter group to use for the DB cluster.</param>
    /// <param name="engineName">Engine to use for the DB cluster.</param>
    /// <param name="engineVersion">Engine version to use for the DB cluster.</param>
    /// <param name="clusterIdentifier">Cluster identifier to use for the DB cluster.</param>
    /// <returns>The new DB cluster.</returns>
    public static async Task<DBCluster?> CreateNewCluster(DBClusterParameterGroup parameterGroup,
        string engineName, string engineVersion, string clusterIdentifier)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine($"9. Create a new DB cluster with identifier {clusterIdentifier}.");

        DBCluster newCluster;
        var clusters = await auroraWrapper.DescribeDBClustersPagedAsync();
        var isClusterCreated = clusters.Any(i => i.DBClusterIdentifier == clusterIdentifier);

        if (isClusterCreated)
        {
            Console.WriteLine("Cluster already created.");
            newCluster = clusters.First(i => i.DBClusterIdentifier == clusterIdentifier);
        }
        else
        {
            Console.WriteLine("Enter an admin username:");
            var username = Console.ReadLine();

            Console.WriteLine("Enter an admin password:");
            var password = Console.ReadLine();

            newCluster = await auroraWrapper.CreateDBClusterWithAdminAsync(
                "ExampleDatabase",
                clusterIdentifier,
                parameterGroup.DBClusterParameterGroupName,
                engineName,
                engineVersion,
                username!,
                password!
            );

            Console.WriteLine("10. Waiting for DB cluster to be ready...");
            while (newCluster.Status != "available")
            {
                Console.Write(".");
                Thread.Sleep(5000);
                clusters = await auroraWrapper.DescribeDBClustersPagedAsync(clusterIdentifier);
                newCluster = clusters.First();
            }
        }

        Console.WriteLine(sepBar);
        return newCluster;
    }

    /// <summary>
    /// Choose a DB instance class for a particular engine and engine version.
    /// </summary>
    /// <param name="engine">DB engine for DB instance choice.</param>
    /// <param name="engineVersion">DB engine version for DB instance choice.</param>
    /// <returns>The selected orderable DB instance option.</returns>
    public static async Task<OrderableDBInstanceOption> ChooseDBInstanceClass(string engine, string engineVersion)
    {
        Console.WriteLine(sepBar);
        // Get a list of allowed DB instance classes.
        var allowedInstances =
            await auroraWrapper.DescribeOrderableDBInstanceOptionsPagedAsync(engine, engineVersion);

        Console.WriteLine($"Available DB instance classes for engine {engine} and version {engineVersion}:");
        int i = 1;

        foreach (var instance in allowedInstances)
        {
            Console.WriteLine(
                $"\t{i}. Instance class: {instance.DBInstanceClass} (storage type {instance.StorageType})");
            i++;
        }

        var choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > allowedInstances.Count)
        {
            Console.WriteLine("11. Select an available DB instance class by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out choiceNumber);
        }

        var instanceChoice = allowedInstances[choiceNumber - 1];
        Console.WriteLine(sepBar);
        return instanceChoice;
    }

    /// <summary>
    /// Create a new DB instance.
    /// </summary>
    /// <param name="engineName">Engine to use for the DB instance.</param>
    /// <param name="engineVersion">Engine version to use for the DB instance.</param>
    /// <param name="instanceClass">Instance class to use for the DB instance.</param>
    /// <param name="instanceIdentifier">Instance identifier to use for the DB instance.</param>
    /// <returns>The new DB instance.</returns>
    public static async Task<DBInstance?> CreateNewInstance(
        string clusterIdentifier,
        string engineName,
        string engineVersion,
        string instanceClass,
        string instanceIdentifier)
    {
        Console.WriteLine(sepBar);
        Console.WriteLine($"12. Create a new DB instance with identifier {instanceIdentifier}.");
        bool isInstanceReady = false;
        DBInstance newInstance;
        var instances = await auroraWrapper.DescribeDBInstancesPagedAsync();
        isInstanceReady = instances.FirstOrDefault(i =>
            i.DBInstanceIdentifier == instanceIdentifier)?.DBInstanceStatus == "available";

        if (isInstanceReady)
        {
            Console.WriteLine("Instance already created.");
            newInstance = instances.First(i => i.DBInstanceIdentifier == instanceIdentifier);
        }
        else
        {
            newInstance = await auroraWrapper.CreateDBInstanceInClusterAsync(
                clusterIdentifier,
                instanceIdentifier,
                engineName,
                engineVersion,
                instanceClass
            );

            Console.WriteLine("13. Waiting for DB instance to be ready...");
            while (!isInstanceReady)
            {
                Console.Write(".");
                Thread.Sleep(5000);
                instances = await auroraWrapper.DescribeDBInstancesPagedAsync(instanceIdentifier);
                isInstanceReady = instances.FirstOrDefault()?.DBInstanceStatus == "available";
                newInstance = instances.First();
            }
        }

        Console.WriteLine(sepBar);
        return newInstance;
    }

    /// <summary>
    /// Display a connection string for an Amazon RDS DB cluster.
    /// </summary>
    /// <param name="cluster">The DB cluster to use to get a connection string.</param>
    public static void DisplayConnectionString(DBCluster cluster)
    {
        Console.WriteLine(sepBar);
        // Display the connection string.
        Console.WriteLine("14. New DB cluster connection string: ");
        Console.WriteLine(
            $"\n{engine} -h {cluster.Endpoint} -P {cluster.Port} "
            + $"-u {cluster.MasterUsername} -p [YOUR PASSWORD]\n");

        Console.WriteLine(sepBar);
    }

    /// <summary>
    /// Create a snapshot from an Amazon RDS DB cluster.
    /// </summary>
    /// <param name="cluster">DB cluster to use when creating a snapshot.</param>
    /// <returns>The snapshot object.</returns>
    public static async Task<DBClusterSnapshot> CreateSnapshot(DBCluster cluster)
    {
        Console.WriteLine(sepBar);
        // Create a snapshot.
        Console.WriteLine($"15. Creating snapshot from DB cluster {cluster.DBClusterIdentifier}.");
        var snapshot = await auroraWrapper.CreateClusterSnapshotByIdentifierAsync(
            cluster.DBClusterIdentifier,
            "ExampleSnapshot-" + DateTime.Now.Ticks);

        // Wait for the snapshot to be available.
        bool isSnapshotReady = false;

        Console.WriteLine($"16. Waiting for snapshot to be ready...");
        while (!isSnapshotReady)
        {
            Console.Write(".");
            Thread.Sleep(5000);
            var snapshots =
                await auroraWrapper.DescribeDBClusterSnapshotsByIdentifierAsync(cluster.DBClusterIdentifier);
            isSnapshotReady = snapshots.FirstOrDefault()?.Status == "available";
            snapshot = snapshots.First();
        }

        Console.WriteLine(
            $"Snapshot {snapshot.DBClusterSnapshotIdentifier} status is {snapshot.Status}.");
        Console.WriteLine(sepBar);
        return snapshot;
    }

    /// <summary>
    /// Clean up resources from the scenario.
    /// </summary>
    /// <param name="newInstance">The instance to clean up.</param>
    /// <param name="newCluster">The cluster to clean up.</param>
    /// <param name="parameterGroup">The parameter group to clean up.</param>
    /// <returns>Async Task.</returns>
    private static async Task CleanupResources(
        DBInstance? newInstance,
        DBCluster? newCluster,
        DBClusterParameterGroup? parameterGroup)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"Clean up resources.");

        if (newInstance is not null && GetYesNoResponse($"\tClean up instance {newInstance.DBInstanceIdentifier}? (y/n)"))
        {
            // Delete the DB instance.
            Console.WriteLine($"17. Deleting the DB instance {newInstance.DBInstanceIdentifier}.");
            await auroraWrapper.DeleteDBInstanceByIdentifierAsync(newInstance.DBInstanceIdentifier);
        }

        if (newCluster is not null && GetYesNoResponse($"\tClean up cluster {newCluster.DBClusterIdentifier}? (y/n)"))
        {
            // Delete the DB cluster.
            Console.WriteLine($"18. Deleting the DB cluster {newCluster.DBClusterIdentifier}.");
            await auroraWrapper.DeleteDBClusterByIdentifierAsync(newCluster.DBClusterIdentifier);

            // Wait for the DB cluster to delete.
            Console.WriteLine($"19. Waiting for the DB cluster to delete...");
            bool isClusterDeleted = false;

            while (!isClusterDeleted)
            {
                Console.Write(".");
                Thread.Sleep(5000);
                var cluster = await auroraWrapper.DescribeDBClustersPagedAsync();
                isClusterDeleted = cluster.All(i => i.DBClusterIdentifier != newCluster.DBClusterIdentifier);
            }

            Console.WriteLine("DB cluster deleted.");
        }

        if (parameterGroup is not null && GetYesNoResponse($"\tClean up parameter group? (y/n)"))
        {
            Console.WriteLine($"20. Deleting the DB parameter group {parameterGroup.DBClusterParameterGroupName}.");
            await auroraWrapper.DeleteClusterParameterGroupByNameAsync(parameterGroup.DBClusterParameterGroupName);
            Console.WriteLine("Parameter group deleted.");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null &&
                       ynResponse.Equals("y",
                           StringComparison.InvariantCultureIgnoreCase);
        return response;
    }
```
Aurora アクションを管理するためにシナリオによって呼び出されるラッパーメソッド。  

```
using Amazon.RDS;
using Amazon.RDS.Model;

namespace AuroraActions;

/// <summary>
/// Wrapper for the Amazon Aurora cluster client operations.
/// </summary>
public class AuroraWrapper
{
    private readonly IAmazonRDS _amazonRDS;
    public AuroraWrapper(IAmazonRDS amazonRDS)
    {
        _amazonRDS = amazonRDS;
    }

    /// <summary>
    /// Get a list of DB engine versions for a particular DB engine.
    /// </summary>
    /// <param name="engine">The name of the engine.</param>
    /// <param name="parameterGroupFamily">Optional parameter group family name.</param>
    /// <returns>A list of DBEngineVersions.</returns>
    public async Task<List<DBEngineVersion>> DescribeDBEngineVersionsForEngineAsync(string engine,
        string? parameterGroupFamily = null)
    {
        var response = await _amazonRDS.DescribeDBEngineVersionsAsync(
            new DescribeDBEngineVersionsRequest()
            {
                Engine = engine,
                DBParameterGroupFamily = parameterGroupFamily
            });
        return response.DBEngineVersions;
    }

    /// <summary>
    /// Create a custom cluster parameter group.
    /// </summary>
    /// <param name="parameterGroupFamily">The family of the parameter group.</param>
    /// <param name="groupName">The name for the new parameter group.</param>
    /// <param name="description">A description for the new parameter group.</param>
    /// <returns>The new parameter group object.</returns>
    public async Task<DBClusterParameterGroup> CreateCustomClusterParameterGroupAsync(
        string parameterGroupFamily,
        string groupName,
        string description)
    {
        var request = new CreateDBClusterParameterGroupRequest
        {
            DBParameterGroupFamily = parameterGroupFamily,
            DBClusterParameterGroupName = groupName,
            Description = description,
        };

        var response = await _amazonRDS.CreateDBClusterParameterGroupAsync(request);
        return response.DBClusterParameterGroup;
    }

    /// <summary>
    /// Describe the cluster parameters in a parameter group.
    /// </summary>
    /// <param name="groupName">The name of the parameter group.</param>
    /// <param name="source">The optional name of the source filter.</param>
    /// <returns>The collection of parameters.</returns>
    public async Task<List<Parameter>> DescribeDBClusterParametersInGroupAsync(string groupName, string? source = null)
    {
        var paramList = new List<Parameter>();

        DescribeDBClusterParametersResponse response;
        var request = new DescribeDBClusterParametersRequest
        {
            DBClusterParameterGroupName = groupName,
            Source = source,
        };

        // Get the full list if there are multiple pages.
        do
        {
            response = await _amazonRDS.DescribeDBClusterParametersAsync(request);
            paramList.AddRange(response.Parameters);

            request.Marker = response.Marker;
        }
        while (response.Marker is not null);

        return paramList;
    }

    /// <summary>
    /// Get the description of a DB cluster parameter group by name.
    /// </summary>
    /// <param name="name">The name of the DB parameter group to describe.</param>
    /// <returns>The parameter group description.</returns>
    public async Task<DBClusterParameterGroup?> DescribeCustomDBClusterParameterGroupAsync(string name)
    {
        var response = await _amazonRDS.DescribeDBClusterParameterGroupsAsync(
            new DescribeDBClusterParameterGroupsRequest()
            {
                DBClusterParameterGroupName = name
            });
        return response.DBClusterParameterGroups.FirstOrDefault();
    }

    /// <summary>
    /// Modify the specified integer parameters with new values from user input.
    /// </summary>
    /// <param name="groupName">The group name for the parameters.</param>
    /// <param name="parameters">The list of integer parameters to modify.</param>
    /// <param name="newValue">Optional int value to set for parameters.</param>
    /// <returns>The name of the group that was modified.</returns>
    public async Task<string> ModifyIntegerParametersInGroupAsync(string groupName, List<Parameter> parameters, int newValue = 0)
    {
        foreach (var p in parameters)
        {
            if (p.IsModifiable.GetValueOrDefault() && p.DataType == "integer")
            {
                while (newValue == 0)
                {
                    Console.WriteLine(
                        $"Enter a new value for {p.ParameterName} from the allowed values {p.AllowedValues} ");

                    var choice = Console.ReadLine();
                    int.TryParse(choice, out newValue);
                }

                p.ParameterValue = newValue.ToString();
            }
        }

        var request = new ModifyDBClusterParameterGroupRequest
        {
            Parameters = parameters,
            DBClusterParameterGroupName = groupName,
        };

        var result = await _amazonRDS.ModifyDBClusterParameterGroupAsync(request);
        return result.DBClusterParameterGroupName;
    }


    /// <summary>
    /// Get a list of orderable DB instance options for a specific
    /// engine and engine version.
    /// </summary>
    /// <param name="engine">Name of the engine.</param>
    /// <param name="engineVersion">Version of the engine.</param>
    /// <returns>List of OrderableDBInstanceOptions.</returns>
    public async Task<List<OrderableDBInstanceOption>> DescribeOrderableDBInstanceOptionsPagedAsync(string engine, string engineVersion)
    {
        // Use a paginator to get a list of DB instance options.
        var results = new List<OrderableDBInstanceOption>();
        var paginateInstanceOptions = _amazonRDS.Paginators.DescribeOrderableDBInstanceOptions(
            new DescribeOrderableDBInstanceOptionsRequest()
            {
                Engine = engine,
                EngineVersion = engineVersion,
            });
        // Get the entire list using the paginator.
        await foreach (var instanceOptions in paginateInstanceOptions.OrderableDBInstanceOptions)
        {
            results.Add(instanceOptions);
        }
        return results;
    }

    /// <summary>
    /// Delete a particular parameter group by name.
    /// </summary>
    /// <param name="groupName">The name of the parameter group.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteClusterParameterGroupByNameAsync(string groupName)
    {
        var request = new DeleteDBClusterParameterGroupRequest
        {
            DBClusterParameterGroupName = groupName,
        };

        var response = await _amazonRDS.DeleteDBClusterParameterGroupAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }

    /// <summary>
    /// Create a new cluster and database.
    /// </summary>
    /// <param name="dbName">The name of the new database.</param>
    /// <param name="clusterIdentifier">The identifier of the cluster.</param>
    /// <param name="parameterGroupName">The name of the parameter group.</param>
    /// <param name="dbEngine">The engine to use for the new cluster.</param>
    /// <param name="dbEngineVersion">The version of the engine to use.</param>
    /// <param name="adminName">The admin username.</param>
    /// <param name="adminPassword">The primary admin password.</param>
    /// <returns>The cluster object.</returns>
    public async Task<DBCluster> CreateDBClusterWithAdminAsync(
        string dbName,
        string clusterIdentifier,
        string parameterGroupName,
        string dbEngine,
        string dbEngineVersion,
        string adminName,
        string adminPassword)
    {
        var request = new CreateDBClusterRequest
        {
            DatabaseName = dbName,
            DBClusterIdentifier = clusterIdentifier,
            DBClusterParameterGroupName = parameterGroupName,
            Engine = dbEngine,
            EngineVersion = dbEngineVersion,
            MasterUsername = adminName,
            MasterUserPassword = adminPassword,
        };

        var response = await _amazonRDS.CreateDBClusterAsync(request);
        return response.DBCluster;
    }

    /// <summary>
    /// Returns a list of DB instances.
    /// </summary>
    /// <param name="dbInstanceIdentifier">Optional name of a specific DB instance.</param>
    /// <returns>List of DB instances.</returns>
    public async Task<List<DBInstance>> DescribeDBInstancesPagedAsync(string? dbInstanceIdentifier = null)
    {
        var results = new List<DBInstance>();
        var instancesPaginator = _amazonRDS.Paginators.DescribeDBInstances(
            new DescribeDBInstancesRequest
            {
                DBInstanceIdentifier = dbInstanceIdentifier
            });
        // Get the entire list using the paginator.
        await foreach (var instances in instancesPaginator.DBInstances)
        {
            results.Add(instances);
        }
        return results;
    }

    /// <summary>
    /// Returns a list of DB clusters.
    /// </summary>
    /// <param name="dbInstanceIdentifier">Optional name of a specific DB cluster.</param>
    /// <returns>List of DB clusters.</returns>
    public async Task<List<DBCluster>> DescribeDBClustersPagedAsync(string? dbClusterIdentifier = null)
    {
        var results = new List<DBCluster>();

        DescribeDBClustersResponse response;
        DescribeDBClustersRequest request = new DescribeDBClustersRequest
        {
            DBClusterIdentifier = dbClusterIdentifier
        };
        // Get the full list if there are multiple pages.
        do
        {
            response = await _amazonRDS.DescribeDBClustersAsync(request);
            if (response.DBClusters != null)
            {
                results.AddRange(response.DBClusters);
            }
            request.Marker = response.Marker;
        }
        while (response.Marker is not null);
        return results;
    }

    /// <summary>
    /// Create an Amazon Relational Database Service (Amazon RDS) DB instance
    /// with a particular set of properties. Use the action DescribeDBInstancesAsync
    /// to determine when the DB instance is ready to use.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <param name="dbEngine">The engine for the DB instance.</param>
    /// <param name="dbEngineVersion">Version for the DB instance.</param>
    /// <param name="instanceClass">Class for the DB instance.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> CreateDBInstanceInClusterAsync(
        string dbClusterIdentifier,
        string dbInstanceIdentifier,
        string dbEngine,
        string dbEngineVersion,
        string instanceClass)
    {
        // When creating the instance within a cluster, do not specify the name or size.
        var response = await _amazonRDS.CreateDBInstanceAsync(
            new CreateDBInstanceRequest()
            {
                DBClusterIdentifier = dbClusterIdentifier,
                DBInstanceIdentifier = dbInstanceIdentifier,
                Engine = dbEngine,
                EngineVersion = dbEngineVersion,
                DBInstanceClass = instanceClass
            });

        return response.DBInstance;
    }

    /// <summary>
    /// Create a snapshot of a cluster.
    /// </summary>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <param name="snapshotIdentifier">Identifier for the snapshot.</param>
    /// <returns>DB snapshot object.</returns>
    public async Task<DBClusterSnapshot> CreateClusterSnapshotByIdentifierAsync(string dbClusterIdentifier, string snapshotIdentifier)
    {
        var response = await _amazonRDS.CreateDBClusterSnapshotAsync(
            new CreateDBClusterSnapshotRequest()
            {
                DBClusterIdentifier = dbClusterIdentifier,
                DBClusterSnapshotIdentifier = snapshotIdentifier,
            });

        return response.DBClusterSnapshot;
    }

    /// <summary>
    /// Return a list of DB snapshots for a particular DB cluster.
    /// </summary>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <returns>List of DB snapshots.</returns>
    public async Task<List<DBClusterSnapshot>> DescribeDBClusterSnapshotsByIdentifierAsync(string dbClusterIdentifier)
    {
        var results = new List<DBClusterSnapshot>();

        DescribeDBClusterSnapshotsResponse response;
        DescribeDBClusterSnapshotsRequest request = new DescribeDBClusterSnapshotsRequest
        {
            DBClusterIdentifier = dbClusterIdentifier
        };
        // Get the full list if there are multiple pages.
        do
        {
            response = await _amazonRDS.DescribeDBClusterSnapshotsAsync(request);
            results.AddRange(response.DBClusterSnapshots);
            request.Marker = response.Marker;
        }
        while (response.Marker is not null);
        return results;
    }

    /// <summary>
    /// Delete a particular DB cluster.
    /// </summary>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <returns>DB cluster object.</returns>
    public async Task<DBCluster> DeleteDBClusterByIdentifierAsync(string dbClusterIdentifier)
    {
        var response = await _amazonRDS.DeleteDBClusterAsync(
            new DeleteDBClusterRequest()
            {
                DBClusterIdentifier = dbClusterIdentifier,
                SkipFinalSnapshot = true
            });

        return response.DBCluster;
    }

    /// <summary>
    /// Delete a particular DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> DeleteDBInstanceByIdentifierAsync(string dbInstanceIdentifier)
    {
        var response = await _amazonRDS.DeleteDBInstanceAsync(
            new DeleteDBInstanceRequest()
            {
                DBInstanceIdentifier = dbInstanceIdentifier,
                SkipFinalSnapshot = true,
                DeleteAutomatedBackups = true
            });

        return response.DBInstance;
    }
}
```
+ API の詳細については、「AWS SDK for .NET API リファレンス**」の以下のトピックを参照してください。
  + [CreateDBCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBCluster)
  + [CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBClusterParameterGroup)
  + [CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBClusterSnapshot)
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBInstance)
  + [DeleteDBCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DeleteDBCluster)
  + [DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DeleteDBClusterParameterGroup)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DeleteDBInstance)
  + [DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusterParameterGroups)
  + [DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusterParameters)
  + [DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusterSnapshots)
  + [DescribeDBClusters](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusters)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBInstances)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/ModifyDBClusterParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="aurora_CreateDBCluster_csharp_4_topic"></a>

次の例は、`CreateDBCluster` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a new cluster and database.
    /// </summary>
    /// <param name="dbName">The name of the new database.</param>
    /// <param name="clusterIdentifier">The identifier of the cluster.</param>
    /// <param name="parameterGroupName">The name of the parameter group.</param>
    /// <param name="dbEngine">The engine to use for the new cluster.</param>
    /// <param name="dbEngineVersion">The version of the engine to use.</param>
    /// <param name="adminName">The admin username.</param>
    /// <param name="adminPassword">The primary admin password.</param>
    /// <returns>The cluster object.</returns>
    public async Task<DBCluster> CreateDBClusterWithAdminAsync(
        string dbName,
        string clusterIdentifier,
        string parameterGroupName,
        string dbEngine,
        string dbEngineVersion,
        string adminName,
        string adminPassword)
    {
        var request = new CreateDBClusterRequest
        {
            DatabaseName = dbName,
            DBClusterIdentifier = clusterIdentifier,
            DBClusterParameterGroupName = parameterGroupName,
            Engine = dbEngine,
            EngineVersion = dbEngineVersion,
            MasterUsername = adminName,
            MasterUserPassword = adminPassword,
        };

        var response = await _amazonRDS.CreateDBClusterAsync(request);
        return response.DBCluster;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateDBCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBCluster)」を参照してください。

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_csharp_4_topic"></a>

次の例は、`CreateDBClusterParameterGroup` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a custom cluster parameter group.
    /// </summary>
    /// <param name="parameterGroupFamily">The family of the parameter group.</param>
    /// <param name="groupName">The name for the new parameter group.</param>
    /// <param name="description">A description for the new parameter group.</param>
    /// <returns>The new parameter group object.</returns>
    public async Task<DBClusterParameterGroup> CreateCustomClusterParameterGroupAsync(
        string parameterGroupFamily,
        string groupName,
        string description)
    {
        var request = new CreateDBClusterParameterGroupRequest
        {
            DBParameterGroupFamily = parameterGroupFamily,
            DBClusterParameterGroupName = groupName,
            Description = description,
        };

        var response = await _amazonRDS.CreateDBClusterParameterGroupAsync(request);
        return response.DBClusterParameterGroup;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBClusterParameterGroup)」を参照してください。

### `CreateDBClusterSnapshot`
<a name="aurora_CreateDBClusterSnapshot_csharp_4_topic"></a>

次の例は、`CreateDBClusterSnapshot` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a snapshot of a cluster.
    /// </summary>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <param name="snapshotIdentifier">Identifier for the snapshot.</param>
    /// <returns>DB snapshot object.</returns>
    public async Task<DBClusterSnapshot> CreateClusterSnapshotByIdentifierAsync(string dbClusterIdentifier, string snapshotIdentifier)
    {
        var response = await _amazonRDS.CreateDBClusterSnapshotAsync(
            new CreateDBClusterSnapshotRequest()
            {
                DBClusterIdentifier = dbClusterIdentifier,
                DBClusterSnapshotIdentifier = snapshotIdentifier,
            });

        return response.DBClusterSnapshot;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBClusterSnapshot)」を参照してください。

### `CreateDBInstance`
<a name="aurora_CreateDBInstance_csharp_4_topic"></a>

次の例は、`CreateDBInstance` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create an Amazon Relational Database Service (Amazon RDS) DB instance
    /// with a particular set of properties. Use the action DescribeDBInstancesAsync
    /// to determine when the DB instance is ready to use.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <param name="dbEngine">The engine for the DB instance.</param>
    /// <param name="dbEngineVersion">Version for the DB instance.</param>
    /// <param name="instanceClass">Class for the DB instance.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> CreateDBInstanceInClusterAsync(
        string dbClusterIdentifier,
        string dbInstanceIdentifier,
        string dbEngine,
        string dbEngineVersion,
        string instanceClass)
    {
        // When creating the instance within a cluster, do not specify the name or size.
        var response = await _amazonRDS.CreateDBInstanceAsync(
            new CreateDBInstanceRequest()
            {
                DBClusterIdentifier = dbClusterIdentifier,
                DBInstanceIdentifier = dbInstanceIdentifier,
                Engine = dbEngine,
                EngineVersion = dbEngineVersion,
                DBInstanceClass = instanceClass
            });

        return response.DBInstance;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `DeleteDBCluster`
<a name="aurora_DeleteDBCluster_csharp_4_topic"></a>

次の例は、`DeleteDBCluster` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a particular DB cluster.
    /// </summary>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <returns>DB cluster object.</returns>
    public async Task<DBCluster> DeleteDBClusterByIdentifierAsync(string dbClusterIdentifier)
    {
        var response = await _amazonRDS.DeleteDBClusterAsync(
            new DeleteDBClusterRequest()
            {
                DBClusterIdentifier = dbClusterIdentifier,
                SkipFinalSnapshot = true
            });

        return response.DBCluster;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteDBCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DeleteDBCluster)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_csharp_4_topic"></a>

次の例は、`DeleteDBClusterParameterGroup` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a particular parameter group by name.
    /// </summary>
    /// <param name="groupName">The name of the parameter group.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteClusterParameterGroupByNameAsync(string groupName)
    {
        var request = new DeleteDBClusterParameterGroupRequest
        {
            DBClusterParameterGroupName = groupName,
        };

        var response = await _amazonRDS.DeleteDBClusterParameterGroupAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DeleteDBClusterParameterGroup)」を参照してください。

### `DeleteDBInstance`
<a name="aurora_DeleteDBInstance_csharp_4_topic"></a>

次の例は、`DeleteDBInstance` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a particular DB instance.
    /// </summary>
    /// <param name="dbInstanceIdentifier">DB instance identifier.</param>
    /// <returns>DB instance object.</returns>
    public async Task<DBInstance> DeleteDBInstanceByIdentifierAsync(string dbInstanceIdentifier)
    {
        var response = await _amazonRDS.DeleteDBInstanceAsync(
            new DeleteDBInstanceRequest()
            {
                DBInstanceIdentifier = dbInstanceIdentifier,
                SkipFinalSnapshot = true,
                DeleteAutomatedBackups = true
            });

        return response.DBInstance;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DescribeDBClusterParameterGroups`
<a name="aurora_DescribeDBClusterParameterGroups_csharp_4_topic"></a>

次の例は、`DescribeDBClusterParameterGroups` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the description of a DB cluster parameter group by name.
    /// </summary>
    /// <param name="name">The name of the DB parameter group to describe.</param>
    /// <returns>The parameter group description.</returns>
    public async Task<DBClusterParameterGroup?> DescribeCustomDBClusterParameterGroupAsync(string name)
    {
        var response = await _amazonRDS.DescribeDBClusterParameterGroupsAsync(
            new DescribeDBClusterParameterGroupsRequest()
            {
                DBClusterParameterGroupName = name
            });
        return response.DBClusterParameterGroups.FirstOrDefault();
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusterParameterGroups)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_csharp_4_topic"></a>

次の例は、`DescribeDBClusterParameters` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe the cluster parameters in a parameter group.
    /// </summary>
    /// <param name="groupName">The name of the parameter group.</param>
    /// <param name="source">The optional name of the source filter.</param>
    /// <returns>The collection of parameters.</returns>
    public async Task<List<Parameter>> DescribeDBClusterParametersInGroupAsync(string groupName, string? source = null)
    {
        var paramList = new List<Parameter>();

        DescribeDBClusterParametersResponse response;
        var request = new DescribeDBClusterParametersRequest
        {
            DBClusterParameterGroupName = groupName,
            Source = source,
        };

        // Get the full list if there are multiple pages.
        do
        {
            response = await _amazonRDS.DescribeDBClusterParametersAsync(request);
            paramList.AddRange(response.Parameters);

            request.Marker = response.Marker;
        }
        while (response.Marker is not null);

        return paramList;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusterParameters)」を参照してください。

### `DescribeDBClusterSnapshots`
<a name="aurora_DescribeDBClusterSnapshots_csharp_4_topic"></a>

次の例は、`DescribeDBClusterSnapshots` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Return a list of DB snapshots for a particular DB cluster.
    /// </summary>
    /// <param name="dbClusterIdentifier">DB cluster identifier.</param>
    /// <returns>List of DB snapshots.</returns>
    public async Task<List<DBClusterSnapshot>> DescribeDBClusterSnapshotsByIdentifierAsync(string dbClusterIdentifier)
    {
        var results = new List<DBClusterSnapshot>();

        DescribeDBClusterSnapshotsResponse response;
        DescribeDBClusterSnapshotsRequest request = new DescribeDBClusterSnapshotsRequest
        {
            DBClusterIdentifier = dbClusterIdentifier
        };
        // Get the full list if there are multiple pages.
        do
        {
            response = await _amazonRDS.DescribeDBClusterSnapshotsAsync(request);
            results.AddRange(response.DBClusterSnapshots);
            request.Marker = response.Marker;
        }
        while (response.Marker is not null);
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusterSnapshots)」を参照してください。

### `DescribeDBClusters`
<a name="aurora_DescribeDBClusters_csharp_4_topic"></a>

次の例は、`DescribeDBClusters` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Returns a list of DB clusters.
    /// </summary>
    /// <param name="dbInstanceIdentifier">Optional name of a specific DB cluster.</param>
    /// <returns>List of DB clusters.</returns>
    public async Task<List<DBCluster>> DescribeDBClustersPagedAsync(string? dbClusterIdentifier = null)
    {
        var results = new List<DBCluster>();

        DescribeDBClustersResponse response;
        DescribeDBClustersRequest request = new DescribeDBClustersRequest
        {
            DBClusterIdentifier = dbClusterIdentifier
        };
        // Get the full list if there are multiple pages.
        do
        {
            response = await _amazonRDS.DescribeDBClustersAsync(request);
            if (response.DBClusters != null)
            {
                results.AddRange(response.DBClusters);
            }
            request.Marker = response.Marker;
        }
        while (response.Marker is not null);
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBClusters)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_csharp_4_topic"></a>

次の例は、`DescribeDBEngineVersions` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of DB engine versions for a particular DB engine.
    /// </summary>
    /// <param name="engine">The name of the engine.</param>
    /// <param name="parameterGroupFamily">Optional parameter group family name.</param>
    /// <returns>A list of DBEngineVersions.</returns>
    public async Task<List<DBEngineVersion>> DescribeDBEngineVersionsForEngineAsync(string engine,
        string? parameterGroupFamily = null)
    {
        var response = await _amazonRDS.DescribeDBEngineVersionsAsync(
            new DescribeDBEngineVersionsRequest()
            {
                Engine = engine,
                DBParameterGroupFamily = parameterGroupFamily
            });
        return response.DBEngineVersions;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="aurora_DescribeDBInstances_csharp_4_topic"></a>

次の例は、`DescribeDBInstances` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Returns a list of DB instances.
    /// </summary>
    /// <param name="dbInstanceIdentifier">Optional name of a specific DB instance.</param>
    /// <returns>List of DB instances.</returns>
    public async Task<List<DBInstance>> DescribeDBInstancesPagedAsync(string? dbInstanceIdentifier = null)
    {
        var results = new List<DBInstance>();
        var instancesPaginator = _amazonRDS.Paginators.DescribeDBInstances(
            new DescribeDBInstancesRequest
            {
                DBInstanceIdentifier = dbInstanceIdentifier
            });
        // Get the entire list using the paginator.
        await foreach (var instances in instancesPaginator.DBInstances)
        {
            results.Add(instances);
        }
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="aurora_DescribeOrderableDBInstanceOptions_csharp_4_topic"></a>

次の例は、`DescribeOrderableDBInstanceOptions` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of orderable DB instance options for a specific
    /// engine and engine version.
    /// </summary>
    /// <param name="engine">Name of the engine.</param>
    /// <param name="engineVersion">Version of the engine.</param>
    /// <returns>List of OrderableDBInstanceOptions.</returns>
    public async Task<List<OrderableDBInstanceOption>> DescribeOrderableDBInstanceOptionsPagedAsync(string engine, string engineVersion)
    {
        // Use a paginator to get a list of DB instance options.
        var results = new List<OrderableDBInstanceOption>();
        var paginateInstanceOptions = _amazonRDS.Paginators.DescribeOrderableDBInstanceOptions(
            new DescribeOrderableDBInstanceOptionsRequest()
            {
                Engine = engine,
                EngineVersion = engineVersion,
            });
        // Get the entire list using the paginator.
        await foreach (var instanceOptions in paginateInstanceOptions.OrderableDBInstanceOptions)
        {
            results.Add(instanceOptions);
        }
        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_csharp_4_topic"></a>

次の例は、`ModifyDBClusterParameterGroup` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Aurora#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Modify the specified integer parameters with new values from user input.
    /// </summary>
    /// <param name="groupName">The group name for the parameters.</param>
    /// <param name="parameters">The list of integer parameters to modify.</param>
    /// <param name="newValue">Optional int value to set for parameters.</param>
    /// <returns>The name of the group that was modified.</returns>
    public async Task<string> ModifyIntegerParametersInGroupAsync(string groupName, List<Parameter> parameters, int newValue = 0)
    {
        foreach (var p in parameters)
        {
            if (p.IsModifiable.GetValueOrDefault() && p.DataType == "integer")
            {
                while (newValue == 0)
                {
                    Console.WriteLine(
                        $"Enter a new value for {p.ParameterName} from the allowed values {p.AllowedValues} ");

                    var choice = Console.ReadLine();
                    int.TryParse(choice, out newValue);
                }

                p.ParameterValue = newValue.ToString();
            }
        }

        var request = new ModifyDBClusterParameterGroupRequest
        {
            Parameters = parameters,
            DBClusterParameterGroupName = groupName,
        };

        var result = await _amazonRDS.ModifyDBClusterParameterGroupAsync(request);
        return result.DBClusterParameterGroupName;
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/rds-2014-10-31/ModifyDBClusterParameterGroup)」を参照してください。

# SDK for .NET (v4) を使用した Auto Scaling の例
<a name="csharp_4_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにちは、Auto Scaling
<a name="auto-scaling_Hello_csharp_4_topic"></a>

次のコード例は、Auto Scaling の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
namespace AutoScalingActions;

using Amazon.AutoScaling;

public class HelloAutoScaling
{
    /// <summary>
    /// Hello Amazon EC2 Auto Scaling. List EC2 Auto Scaling groups.
    /// </summary>
    /// <param name="args"></param>
    /// <returns>Async Task.</returns>
    static async Task Main(string[] args)
    {
        var client = new AmazonAutoScalingClient();

        Console.WriteLine("Welcome to Amazon EC2 Auto Scaling.");
        Console.WriteLine("Let's get a description of your Auto Scaling groups.");

        var response = await client.DescribeAutoScalingGroupsAsync();

        if (response.AutoScalingGroups == null || response.AutoScalingGroups.Count == 0)
        {
            Console.WriteLine("Sorry, you don't have any Amazon EC2 Auto Scaling groups.");
            return;
        }
        response.AutoScalingGroups.ForEach(autoScalingGroup =>
        {
            Console.WriteLine($"{autoScalingGroup.AutoScalingGroupName}\t{autoScalingGroup.AvailabilityZones}");
        });

    }
}
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="auto-scaling_Scenario_GroupsAndInstances_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 起動テンプレートとアベイラビリティーゾーンを使用して、Amazon EC2 Auto Scaling グループを作成し、実行中のインスタンスに関する情報を取得します。
+ Amazon CloudWatch メトリクスの収集を有効にします。
+ グループの希望するキャパシティを更新し、インスタンスが起動するのを待ちます。
+  グループ内の最も古いインスタンスを削除します。
+ ユーザーのリクエストやキャパシティの変更に応じて発生するスケーリングアクティビティを一覧表示します。
+ CloudWatch メトリクスの統計を取得して、リソースをクリーンアップします。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
global using Amazon.AutoScaling;
global using Amazon.AutoScaling.Model;
global using Amazon.CloudWatch;
global using AutoScalingActions;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Hosting;
global using Microsoft.Extensions.Logging;
global using Microsoft.Extensions.Logging.Console;
global using Microsoft.Extensions.Logging.Debug;



using Amazon.EC2;
using Microsoft.Extensions.Configuration;
using Host = Microsoft.Extensions.Hosting.Host;

namespace AutoScalingBasics;

public class AutoScalingBasics
{

    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon EC2 Auto Scaling, Amazon
        // CloudWatch, and Amazon EC2.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonAutoScaling>()
                .AddAWSService<IAmazonCloudWatch>()
                .AddAWSService<IAmazonEC2>()
                .AddTransient<AutoScalingWrapper>()
                .AddTransient<CloudWatchWrapper>()
                .AddTransient<EC2Wrapper>()
                .AddTransient<UIWrapper>()
            )
            .Build();


        var autoScalingWrapper = host.Services.GetRequiredService<AutoScalingWrapper>();
        var cloudWatchWrapper = host.Services.GetRequiredService<CloudWatchWrapper>();
        var ec2Wrapper = host.Services.GetRequiredService<EC2Wrapper>();
        var uiWrapper = host.Services.GetRequiredService<UIWrapper>();

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load test settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally load local settings.
            .Build();

        var imageId = configuration["ImageId"];
        var instanceType = configuration["InstanceType"];
        var launchTemplateName = configuration["LaunchTemplateName"];

        launchTemplateName += Guid.NewGuid().ToString();

        // The name of the Auto Scaling group.
        var groupName = configuration["GroupName"];

        uiWrapper.DisplayTitle("Auto Scaling Basics");
        uiWrapper.DisplayAutoScalingBasicsDescription();

        // Create the launch template and save the template Id to use when deleting the
        // launch template at the end of the application.
        var launchTemplateId = await ec2Wrapper.CreateLaunchTemplateAsync(imageId!, instanceType!, launchTemplateName);

        // Confirm that the template was created by asking for a description of it.
        await ec2Wrapper.DescribeLaunchTemplateAsync(launchTemplateName);

        uiWrapper.PressEnter();

        var availabilityZones = await ec2Wrapper.ListAvailabilityZonesAsync();

        Console.WriteLine($"Creating an Auto Scaling group named {groupName}.");
        await autoScalingWrapper.CreateAutoScalingGroupAsync(
            groupName!,
            launchTemplateName,
            availabilityZones[0].ZoneName);

        // Keep checking the details of the new group until its lifecycle state
        // is "InService".
        Console.WriteLine($"Waiting for the Auto Scaling group to be active.");

        List<AutoScalingInstanceDetails> instanceDetails;

        do
        {
            instanceDetails = await autoScalingWrapper.DescribeAutoScalingInstancesAsync(groupName!);
        }
        while (instanceDetails.Count <= 0);

        Console.WriteLine($"Auto scaling group {groupName} successfully created.");
        Console.WriteLine($"{instanceDetails.Count} instances were created for the group.");

        // Display the details of the Auto Scaling group.
        instanceDetails.ForEach(detail =>
        {
            Console.WriteLine($"Group name: {detail.AutoScalingGroupName}");
        });

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Metrics collection");
        Console.WriteLine($"Enable metrics collection for {groupName}");
        await autoScalingWrapper.EnableMetricsCollectionAsync(groupName!);

        // Show the metrics that are collected for the group.

        // Update the maximum size of the group to three instances.
        Console.WriteLine("--- Update the Auto Scaling group to increase max size to 3 ---");
        int maxSize = 3;
        await autoScalingWrapper.UpdateAutoScalingGroupAsync(groupName!, launchTemplateName, maxSize);

        Console.WriteLine("--- Describe all Auto Scaling groups to show the current state of the group ---");
        var groups = await autoScalingWrapper.DescribeAutoScalingGroupsAsync(groupName!);

        uiWrapper.DisplayGroupDetails(groups!);

        uiWrapper.PressEnter();

        uiWrapper.DisplayTitle("Describe account limits");
        await autoScalingWrapper.DescribeAccountLimitsAsync();

        uiWrapper.WaitABit(60, "Waiting for the resources to be ready.");

        uiWrapper.DisplayTitle("Set desired capacity");
        int desiredCapacity = 2;
        await autoScalingWrapper.SetDesiredCapacityAsync(groupName!, desiredCapacity);

        Console.WriteLine("Get the two instance Id values");

        // Empty the group before getting the details again.
        groups.Clear();
        groups = await autoScalingWrapper.DescribeAutoScalingGroupsAsync(groupName!);
        if (groups.Any())
        {
            foreach (AutoScalingGroup group in groups)
            {
                Console.WriteLine($"The group name is {group.AutoScalingGroupName}");
                Console.WriteLine($"The group ARN is {group.AutoScalingGroupARN}");
                var instances = group.Instances;
                foreach (Amazon.AutoScaling.Model.Instance instance in instances)
                {
                    Console.WriteLine($"The instance id is {instance.InstanceId}");
                    Console.WriteLine($"The lifecycle state is {instance.LifecycleState}");
                }
            }
        }

        uiWrapper.DisplayTitle("Scaling Activities");
        Console.WriteLine("Let's list the scaling activities that have occurred for the group.");
        var activities = await autoScalingWrapper.DescribeScalingActivitiesAsync(groupName!);
        if (activities.Any())
        {
            activities.ForEach(activity =>
            {
                Console.WriteLine($"The activity Id is {activity.ActivityId}");
                Console.WriteLine($"The activity details are {activity.Details}");
            });
        }

        // Display the Amazon CloudWatch metrics that have been collected.
        var metrics = await cloudWatchWrapper.GetCloudWatchMetricsAsync(groupName!);
        if (metrics.Any())
        {
            Console.WriteLine($"Metrics collected for {groupName}:");
            metrics.ForEach(metric =>
            {
                Console.Write($"Metric name: {metric.MetricName}\t");
                Console.WriteLine($"Namespace: {metric.Namespace}");
            });
        }

        var dataPoints = await cloudWatchWrapper.GetMetricStatisticsAsync(groupName!);
        if (dataPoints.Any())
        {
            Console.WriteLine("Details for the metrics collected:");
            dataPoints.ForEach(detail => { Console.WriteLine(detail); });
        }

        // Disable metrics collection.
        Console.WriteLine("Disabling the collection of metrics for {groupName}.");
        var success = await autoScalingWrapper.DisableMetricsCollectionAsync(groupName!);

        if (success)
        {
            Console.WriteLine($"Successfully stopped metrics collection for {groupName}.");
        }
        else
        {
            Console.WriteLine($"Could not stop metrics collection for {groupName}.");
        }

        // Terminate all instances in the group.
        uiWrapper.DisplayTitle("Terminating Auto Scaling instances");
        Console.WriteLine("Now terminating all instances in the Auto Scaling group.");

        if (groups is not null)
        {
            groups.ForEach(group =>
            {
                // Only delete instances in the AutoScaling group we created.
                if (group.AutoScalingGroupName == groupName)
                {
                    group.Instances.ForEach(async instance =>
                    {
                        await autoScalingWrapper.TerminateInstanceInAutoScalingGroupAsync(instance.InstanceId);
                    });
                }
            });
        }

        // After all instances are terminated, delete the group.
        uiWrapper.DisplayTitle("Clean up resources");
        Console.WriteLine("Deleting the Auto Scaling group.");
        await autoScalingWrapper.DeleteAutoScalingGroupAsync(groupName!);

        // Delete the launch template.
        var deletedLaunchTemplateName = await ec2Wrapper.DeleteLaunchTemplateAsync(launchTemplateId);

        if (deletedLaunchTemplateName == launchTemplateName)
        {
            Console.WriteLine("Successfully deleted the launch template.");
        }

        Console.WriteLine("The demo is now concluded.");
    }
}


namespace AutoScalingBasics;

/// <summary>
/// A class to provide user interface methods for the EC2 AutoScaling Basics
/// scenario.
/// </summary>
public class UIWrapper
{
    public readonly string SepBar = new('-', Console.WindowWidth);

    /// <summary>
    /// Describe the steps in the EC2 AutoScaling Basics scenario.
    /// </summary>
    public void DisplayAutoScalingBasicsDescription()
    {
        Console.WriteLine("This code example performs the following operations:");
        Console.WriteLine(" 1. Creates an Amazon EC2 launch template.");
        Console.WriteLine(" 2. Creates an Auto Scaling group.");
        Console.WriteLine(" 3. Shows the details of the new Auto Scaling group");
        Console.WriteLine("    to show that only one instance was created.");
        Console.WriteLine(" 4. Enables metrics collection.");
        Console.WriteLine(" 5. Updates the Auto Scaling group to increase the");
        Console.WriteLine("    capacity to three.");
        Console.WriteLine(" 6. Describes Auto Scaling groups again to show the");
        Console.WriteLine("    current state of the group.");
        Console.WriteLine(" 7. Changes the desired capacity of the Auto Scaling");
        Console.WriteLine("    group to use an additional instance.");
        Console.WriteLine(" 8. Shows that there are now instances in the group.");
        Console.WriteLine(" 9. Lists the scaling activities that have occurred for the group.");
        Console.WriteLine("10. Displays the Amazon CloudWatch metrics that have");
        Console.WriteLine("    been collected.");
        Console.WriteLine("11. Disables metrics collection.");
        Console.WriteLine("12. Terminates all instances in the Auto Scaling group.");
        Console.WriteLine("13. Deletes the Auto Scaling group.");
        Console.WriteLine("14. Deletes the Amazon EC2 launch template.");
        PressEnter();
    }

    /// <summary>
    /// Display information about the Amazon Ec2 AutoScaling groups passed
    /// in the list of AutoScalingGroup objects.
    /// </summary>
    /// <param name="groups">A list of AutoScalingGroup objects.</param>
    public void DisplayGroupDetails(List<AutoScalingGroup> groups)
    {
        if (groups is null)
            return;

        groups.ForEach(group =>
        {
            Console.WriteLine($"Group name:\t{group.AutoScalingGroupName}");
            Console.WriteLine($"Group created:\t{group.CreatedTime}");
            Console.WriteLine($"Maximum number of instances:\t{group.MaxSize}");
            Console.WriteLine($"Desired number of instances:\t{group.DesiredCapacity}");
        });
    }

    /// <summary>
    /// Display a message and wait until the user presses enter.
    /// </summary>
    public void PressEnter()
    {
        Console.Write("\nPress <Enter> to continue. ");
        _ = Console.ReadLine();
        Console.WriteLine();
    }

    /// <summary>
    /// Pad a string with spaces to center it on the console display.
    /// </summary>
    /// <param name="strToCenter">The string to be centered.</param>
    /// <returns>The padded string.</returns>
    public string CenterString(string strToCenter)
    {
        var padAmount = (Console.WindowWidth - strToCenter.Length) / 2;
        var leftPad = new string(' ', padAmount);
        return $"{leftPad}{strToCenter}";
    }

    /// <summary>
    /// Display a line of hyphens, the centered text of the title and another
    /// line of hyphens.
    /// </summary>
    /// <param name="strTitle">The string to be displayed.</param>
    public void DisplayTitle(string strTitle)
    {
        Console.WriteLine(SepBar);
        Console.WriteLine(CenterString(strTitle));
        Console.WriteLine(SepBar);
    }

    /// <summary>
    /// Display a countdown and wait for a number of seconds.
    /// </summary>
    /// <param name="numSeconds">The number of seconds to wait.</param>
    public void WaitABit(int numSeconds, string msg)
    {
        Console.WriteLine(msg);

        // Wait for the requested number of seconds.
        for (int i = numSeconds; i > 0; i--)
        {
            System.Threading.Thread.Sleep(1000);
            Console.Write($"{i}...");
        }

        PressEnter();
    }
}
```
起動テンプレートとメトリクスを管理するためにシナリオによって呼び出される関数を定義します。これらの関数は、Auto Scaling、Amazon EC2、および CloudWatch アクションをラップします。  

```
namespace AutoScalingActions;

using Amazon.AutoScaling;
using Amazon.AutoScaling.Model;

/// <summary>
/// A class that includes methods to perform Amazon EC2 Auto Scaling
/// actions.
/// </summary>
public class AutoScalingWrapper
{
    private readonly IAmazonAutoScaling _amazonAutoScaling;

    /// <summary>
    /// Constructor for the AutoScalingWrapper class.
    /// </summary>
    /// <param name="amazonAutoScaling">The injected Amazon EC2 Auto Scaling client.</param>
    public AutoScalingWrapper(IAmazonAutoScaling amazonAutoScaling)
    {
        _amazonAutoScaling = amazonAutoScaling;
    }


    /// <summary>
    /// Create a new Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name to use for the new Auto Scaling
    /// group.</param>
    /// <param name="launchTemplateName">The name of the Amazon EC2 Auto Scaling
    /// launch template to use to create instances in the group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateAutoScalingGroupAsync(
        string groupName,
        string launchTemplateName,
        string availabilityZone)
    {
        var templateSpecification = new LaunchTemplateSpecification
        {
            LaunchTemplateName = launchTemplateName,
        };

        var zoneList = new List<string>
            {
                availabilityZone,
            };

        var request = new CreateAutoScalingGroupRequest
        {
            AutoScalingGroupName = groupName,
            AvailabilityZones = zoneList,
            LaunchTemplate = templateSpecification,
            MaxSize = 6,
            MinSize = 1
        };
        try
        {
            var response = await _amazonAutoScaling.CreateAutoScalingGroupAsync(request);
            Console.WriteLine($"{groupName} Auto Scaling Group created");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine($"{groupName} Auto Scaling Group already exists.");
            return true;
        }
    }



    /// <summary>
    /// Retrieve information about Amazon EC2 Auto Scaling quotas to the
    /// active AWS account.
    /// </summary>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DescribeAccountLimitsAsync()
    {
        var response = await _amazonAutoScaling.DescribeAccountLimitsAsync();
        Console.WriteLine("The maximum number of Auto Scaling groups is " + response.MaxNumberOfAutoScalingGroups);
        Console.WriteLine("The current number of Auto Scaling groups is " + response.NumberOfAutoScalingGroups);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }



    /// <summary>
    /// Retrieve a list of the Amazon EC2 Auto Scaling activities for an
    /// Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling activities.</returns>
    public async Task<List<Activity>> DescribeScalingActivitiesAsync(
        string groupName)
    {
        var activities = new List<Activity>();
        var scalingActivitiesRequest = new DescribeScalingActivitiesRequest
        {
            AutoScalingGroupName = groupName,
            MaxRecords = 10,
        };

        var response = await _amazonAutoScaling.DescribeScalingActivitiesAsync(scalingActivitiesRequest);
        if (response.Activities != null)
        {
            activities = response.Activities;
        }
        return activities;
    }



    /// <summary>
    /// Get data about the instances in an Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling details.</returns>
    public async Task<List<AutoScalingInstanceDetails>> DescribeAutoScalingInstancesAsync(
        string groupName)
    {
        var groups = await DescribeAutoScalingGroupsAsync(groupName);
        var instanceIds = new List<string>();
        var instanceDetails = new List<AutoScalingInstanceDetails>();
        if (groups != null)
        {
            groups.ForEach(group =>
            {
                if (group.AutoScalingGroupName == groupName && group.Instances != null)
                {
                    group.Instances.ForEach(instance =>
                    {
                        instanceIds.Add(instance.InstanceId);
                    });
                }
            });

            var scalingGroupsRequest = new DescribeAutoScalingInstancesRequest
            {
                MaxRecords = 10,
                InstanceIds = instanceIds,
            };

            var response =
                await _amazonAutoScaling.DescribeAutoScalingInstancesAsync(
                    scalingGroupsRequest);
            if (response.AutoScalingInstances != null)
            {
                instanceDetails = response.AutoScalingInstances;
            }
        }

        return instanceDetails;
    }



    /// <summary>
    /// Retrieve a list of information about Amazon EC2 Auto Scaling groups.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling groups.</returns>
    public async Task<List<AutoScalingGroup>> DescribeAutoScalingGroupsAsync(
        string groupName)
    {
        var groups = new List<AutoScalingGroup>();
        var groupList = new List<string>
            {
                groupName,
            };

        var request = new DescribeAutoScalingGroupsRequest
        {
            AutoScalingGroupNames = groupList,
        };

        var response = await _amazonAutoScaling.DescribeAutoScalingGroupsAsync(request);
        if (response.AutoScalingGroups != null)
        {
            groups = response.AutoScalingGroups;
        }

        return groups;
    }


    /// <summary>
    /// Delete an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> DeleteAutoScalingGroupAsync(
        string groupName)
    {
        var deleteAutoScalingGroupRequest = new DeleteAutoScalingGroupRequest
        {
            AutoScalingGroupName = groupName,
            ForceDelete = true,
        };

        var response = await _amazonAutoScaling.DeleteAutoScalingGroupAsync(deleteAutoScalingGroupRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You successfully deleted {groupName}");
            return true;
        }

        Console.WriteLine($"Couldn't delete {groupName}.");
        return false;
    }


    /// <summary>
    /// Disable the collection of metric data for an Amazon EC2 Auto Scaling
    /// group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <returns>A Boolean value that indicates the success or failure of
    /// the operation.</returns>
    public async Task<bool> DisableMetricsCollectionAsync(string groupName)
    {
        var request = new DisableMetricsCollectionRequest
        {
            AutoScalingGroupName = groupName,
        };

        var response = await _amazonAutoScaling.DisableMetricsCollectionAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Enable the collection of metric data for an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> EnableMetricsCollectionAsync(string groupName)
    {
        var listMetrics = new List<string>
            {
                "GroupMaxSize",
            };

        var collectionRequest = new EnableMetricsCollectionRequest
        {
            AutoScalingGroupName = groupName,
            Metrics = listMetrics,
            Granularity = "1Minute",
        };

        var response = await _amazonAutoScaling.EnableMetricsCollectionAsync(collectionRequest);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Set the desired capacity of an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <param name="desiredCapacity">The desired capacity for the Auto
    /// Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> SetDesiredCapacityAsync(
        string groupName,
        int desiredCapacity)
    {
        var capacityRequest = new SetDesiredCapacityRequest
        {
            AutoScalingGroupName = groupName,
            DesiredCapacity = desiredCapacity,
        };

        var response = await _amazonAutoScaling.SetDesiredCapacityAsync(capacityRequest);
        Console.WriteLine($"You have set the DesiredCapacity to {desiredCapacity}.");

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }


    /// <summary>
    /// Terminate all instances in the Auto Scaling group in preparation for
    /// deleting the group.
    /// </summary>
    /// <param name="instanceId">The instance Id of the instance to terminate.</param>
    /// <returns>A Boolean value that indicates the success or failure of
    /// the operation.</returns>
    public async Task<bool> TerminateInstanceInAutoScalingGroupAsync(
        string instanceId)
    {
        var request = new TerminateInstanceInAutoScalingGroupRequest
        {
            InstanceId = instanceId,
            ShouldDecrementDesiredCapacity = false,
        };

        var response = await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(request);

        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You have terminated the instance: {instanceId}");
            return true;
        }

        Console.WriteLine($"Could not terminate {instanceId}");
        return false;
    }


    /// <summary>
    /// Update the capacity of an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <param name="launchTemplateName">The name of the EC2 launch template.</param>
    /// <param name="maxSize">The maximum number of instances that can be
    /// created for the Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> UpdateAutoScalingGroupAsync(
        string groupName,
        string launchTemplateName,
        int maxSize)
    {
        var templateSpecification = new LaunchTemplateSpecification
        {
            LaunchTemplateName = launchTemplateName,
        };

        var groupRequest = new UpdateAutoScalingGroupRequest
        {
            MaxSize = maxSize,
            AutoScalingGroupName = groupName,
            LaunchTemplate = templateSpecification,
        };

        var response = await _amazonAutoScaling.UpdateAutoScalingGroupAsync(groupRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You successfully updated the Auto Scaling group {groupName}.");
            return true;
        }
        else
        {
            return false;
        }
    }

}


namespace AutoScalingActions;

using Amazon.EC2;
using Amazon.EC2.Model;

public class EC2Wrapper
{
    private readonly IAmazonEC2 _amazonEc2;

    /// <summary>
    /// Constructor for the EC2Wrapper class.
    /// </summary>
    /// <param name="amazonEc2">The injected Amazon EC2 client.</param>
    public EC2Wrapper(IAmazonEC2 amazonEc2)
    {
        _amazonEc2 = amazonEc2;
    }

    /// <summary>
    /// Create a new Amazon EC2 launch template.
    /// </summary>
    /// <param name="imageId">The image Id to use for instances launched
    /// using the Amazon EC2 launch template.</param>
    /// <param name="instanceType">The type of EC2 instances to create.</param>
    /// <param name="launchTemplateName">The name of the launch template.</param>
    /// <returns>Returns the TemplateID of the new launch template.</returns>
    public async Task<string> CreateLaunchTemplateAsync(
        string imageId,
        string instanceType,
        string launchTemplateName)
    {
        var request = new CreateLaunchTemplateRequest
        {
            LaunchTemplateData = new RequestLaunchTemplateData
            {
                ImageId = imageId,
                InstanceType = instanceType,
            },
            LaunchTemplateName = launchTemplateName,
        };

        var response = await _amazonEc2.CreateLaunchTemplateAsync(request);

        return response.LaunchTemplate.LaunchTemplateId;
    }

    /// <summary>
    /// Delete an Amazon EC2 launch template.
    /// </summary>
    /// <param name="launchTemplateId">The TemplateId of the launch template to
    /// delete.</param>
    /// <returns>The name of the EC2 launch template that was deleted.</returns>
    public async Task<string> DeleteLaunchTemplateAsync(string launchTemplateId)
    {
        var request = new DeleteLaunchTemplateRequest
        {
            LaunchTemplateId = launchTemplateId,
        };

        var response = await _amazonEc2.DeleteLaunchTemplateAsync(request);
        return response.LaunchTemplate.LaunchTemplateName;
    }

    /// <summary>
    /// Retrieve information about an EC2 launch template.
    /// </summary>
    /// <param name="launchTemplateName">The name of the EC2 launch template.</param>
    /// <returns>A Boolean value that indicates the success or failure of
    /// the operation.</returns>
    public async Task<bool> DescribeLaunchTemplateAsync(string launchTemplateName)
    {
        var request = new DescribeLaunchTemplatesRequest
        {
            LaunchTemplateNames = new List<string> { launchTemplateName, },
        };

        var response = await _amazonEc2.DescribeLaunchTemplatesAsync(request);

        if (response.LaunchTemplates is not null)
        {
            response.LaunchTemplates.ForEach(template =>
            {
                Console.Write($"{template.LaunchTemplateName}\t");
                Console.WriteLine(template.LaunchTemplateId);
            });

            return true;
        }

        return false;
    }

    /// <summary>
    /// Retrieve the availability zones for the current region.
    /// </summary>
    /// <returns>A collection of availability zones.</returns>
    public async Task<List<AvailabilityZone>> ListAvailabilityZonesAsync()
    {
        var response = await _amazonEc2.DescribeAvailabilityZonesAsync(
            new DescribeAvailabilityZonesRequest());

        return response.AvailabilityZones;
    }
}


namespace AutoScalingActions;

using Amazon.CloudWatch;
using Amazon.CloudWatch.Model;

/// <summary>
/// Contains methods to access Amazon CloudWatch metrics for the
/// Amazon EC2 Auto Scaling basics scenario.
/// </summary>
public class CloudWatchWrapper
{
    private readonly IAmazonCloudWatch _amazonCloudWatch;

    /// <summary>
    /// Constructor for the CloudWatchWrapper.
    /// </summary>
    /// <param name="amazonCloudWatch">The injected CloudWatch client.</param>
    public CloudWatchWrapper(IAmazonCloudWatch amazonCloudWatch)
    {
        _amazonCloudWatch = amazonCloudWatch;
    }

    /// <summary>
    /// Retrieve the metrics information collection for the Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <returns>A list of Metrics collected for the Auto Scaling group.</returns>
    public async Task<List<Metric>> GetCloudWatchMetricsAsync(string groupName)
    {
        var metrics = new List<Metric>();
        var filter = new DimensionFilter
        {
            Name = "AutoScalingGroupName",
            Value = $"{groupName}",
        };

        var request = new ListMetricsRequest
        {
            MetricName = "AutoScalingGroupName",
            Dimensions = new List<DimensionFilter> { filter },
            Namespace = "AWS/AutoScaling",
        };

        var response = await _amazonCloudWatch.ListMetricsAsync(request);
        if (response.Metrics != null)
        {
            metrics = response.Metrics;
        }
        return metrics;
    }

    /// <summary>
    /// Retrieve the metric data collected for an Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of data points.</returns>
    public async Task<List<Datapoint>> GetMetricStatisticsAsync(string groupName)
    {
        var dataPoints = new List<Datapoint>();
        var metricDimensions = new List<Dimension>
            {
                new Dimension
                {
                    Name = "AutoScalingGroupName",
                    Value = $"{groupName}",
                },
            };

        // The start time will be yesterday.
        var startTime = DateTime.UtcNow.AddDays(-1);

        var request = new GetMetricStatisticsRequest
        {
            MetricName = "AutoScalingGroupName",
            Dimensions = metricDimensions,
            Namespace = "AWS/AutoScaling",
            Period = 60, // 60 seconds.
            Statistics = new List<string>() { "Minimum" },
            StartTimeUtc = startTime,
            EndTimeUtc = DateTime.UtcNow,
        };

        var response = await _amazonCloudWatch.GetMetricStatisticsAsync(request);
        if (response.Datapoints != null)
        {
            dataPoints = response.Datapoints;
        }

        return dataPoints;
    }

}
```
+ API の詳細については、「AWS SDK for .NET API リファレンス**」の以下のトピックを参照してください。
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeAutoScalingInstances)
  + [DescribeScalingActivities](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeScalingActivities)
  + [DisableMetricsCollection](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DisableMetricsCollection)
  + [EnableMetricsCollection](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/EnableMetricsCollection)
  + [SetDesiredCapacity](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/SetDesiredCapacity)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/UpdateAutoScalingGroup)

## アクション
<a name="actions"></a>

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_csharp_4_topic"></a>

次の例は、`CreateAutoScalingGroup` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a new Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name to use for the new Auto Scaling
    /// group.</param>
    /// <param name="launchTemplateName">The name of the Amazon EC2 Auto Scaling
    /// launch template to use to create instances in the group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> CreateAutoScalingGroupAsync(
        string groupName,
        string launchTemplateName,
        string availabilityZone)
    {
        var templateSpecification = new LaunchTemplateSpecification
        {
            LaunchTemplateName = launchTemplateName,
        };

        var zoneList = new List<string>
            {
                availabilityZone,
            };

        var request = new CreateAutoScalingGroupRequest
        {
            AutoScalingGroupName = groupName,
            AvailabilityZones = zoneList,
            LaunchTemplate = templateSpecification,
            MaxSize = 6,
            MinSize = 1
        };
        try
        {
            var response = await _amazonAutoScaling.CreateAutoScalingGroupAsync(request);
            Console.WriteLine($"{groupName} Auto Scaling Group created");
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AlreadyExistsException)
        {
            Console.WriteLine($"{groupName} Auto Scaling Group already exists.");
            return true;
        }
    }
```
+  詳細については、*AWS SDK for .NET API リファレンス*の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_csharp_4_topic"></a>

次の例は、`DescribeAutoScalingGroups` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get data about the instances in an Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling details.</returns>
    public async Task<List<AutoScalingInstanceDetails>> DescribeAutoScalingInstancesAsync(
        string groupName)
    {
        var groups = await DescribeAutoScalingGroupsAsync(groupName);
        var instanceIds = new List<string>();
        var instanceDetails = new List<AutoScalingInstanceDetails>();
        if (groups != null)
        {
            groups.ForEach(group =>
            {
                if (group.AutoScalingGroupName == groupName && group.Instances != null)
                {
                    group.Instances.ForEach(instance =>
                    {
                        instanceIds.Add(instance.InstanceId);
                    });
                }
            });

            var scalingGroupsRequest = new DescribeAutoScalingInstancesRequest
            {
                MaxRecords = 10,
                InstanceIds = instanceIds,
            };

            var response =
                await _amazonAutoScaling.DescribeAutoScalingInstancesAsync(
                    scalingGroupsRequest);
            if (response.AutoScalingInstances != null)
            {
                instanceDetails = response.AutoScalingInstances;
            }
        }

        return instanceDetails;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_csharp_4_topic"></a>

次の例は、`DescribeAutoScalingInstances` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get data about the instances in an Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling details.</returns>
    public async Task<List<AutoScalingInstanceDetails>> DescribeAutoScalingInstancesAsync(
        string groupName)
    {
        var groups = await DescribeAutoScalingGroupsAsync(groupName);
        var instanceIds = new List<string>();
        var instanceDetails = new List<AutoScalingInstanceDetails>();
        if (groups != null)
        {
            groups.ForEach(group =>
            {
                if (group.AutoScalingGroupName == groupName && group.Instances != null)
                {
                    group.Instances.ForEach(instance =>
                    {
                        instanceIds.Add(instance.InstanceId);
                    });
                }
            });

            var scalingGroupsRequest = new DescribeAutoScalingInstancesRequest
            {
                MaxRecords = 10,
                InstanceIds = instanceIds,
            };

            var response =
                await _amazonAutoScaling.DescribeAutoScalingInstancesAsync(
                    scalingGroupsRequest);
            if (response.AutoScalingInstances != null)
            {
                instanceDetails = response.AutoScalingInstances;
            }
        }

        return instanceDetails;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_csharp_4_topic"></a>

次の例は、`DescribeScalingActivities` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Retrieve a list of the Amazon EC2 Auto Scaling activities for an
    /// Amazon EC2 Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Amazon EC2 Auto Scaling group.</param>
    /// <returns>A list of Amazon EC2 Auto Scaling activities.</returns>
    public async Task<List<Activity>> DescribeScalingActivitiesAsync(
        string groupName)
    {
        var activities = new List<Activity>();
        var scalingActivitiesRequest = new DescribeScalingActivitiesRequest
        {
            AutoScalingGroupName = groupName,
            MaxRecords = 10,
        };

        var response = await _amazonAutoScaling.DescribeScalingActivitiesAsync(scalingActivitiesRequest);
        if (response.Activities != null)
        {
            activities = response.Activities;
        }
        return activities;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_csharp_4_topic"></a>

次の例は、`DisableMetricsCollection` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Disable the collection of metric data for an Amazon EC2 Auto Scaling
    /// group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <returns>A Boolean value that indicates the success or failure of
    /// the operation.</returns>
    public async Task<bool> DisableMetricsCollectionAsync(string groupName)
    {
        var request = new DisableMetricsCollectionRequest
        {
            AutoScalingGroupName = groupName,
        };

        var response = await _amazonAutoScaling.DisableMetricsCollectionAsync(request);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_csharp_4_topic"></a>

次の例は、`EnableMetricsCollection` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Enable the collection of metric data for an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> EnableMetricsCollectionAsync(string groupName)
    {
        var listMetrics = new List<string>
            {
                "GroupMaxSize",
            };

        var collectionRequest = new EnableMetricsCollectionRequest
        {
            AutoScalingGroupName = groupName,
            Metrics = listMetrics,
            Granularity = "1Minute",
        };

        var response = await _amazonAutoScaling.EnableMetricsCollectionAsync(collectionRequest);
        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_csharp_4_topic"></a>

次の例は、`SetDesiredCapacity` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Set the desired capacity of an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <param name="desiredCapacity">The desired capacity for the Auto
    /// Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> SetDesiredCapacityAsync(
        string groupName,
        int desiredCapacity)
    {
        var capacityRequest = new SetDesiredCapacityRequest
        {
            AutoScalingGroupName = groupName,
            DesiredCapacity = desiredCapacity,
        };

        var response = await _amazonAutoScaling.SetDesiredCapacityAsync(capacityRequest);
        Console.WriteLine($"You have set the DesiredCapacity to {desiredCapacity}.");

        return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_csharp_4_topic"></a>

次の例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Terminate all instances in the Auto Scaling group in preparation for
    /// deleting the group.
    /// </summary>
    /// <param name="instanceId">The instance Id of the instance to terminate.</param>
    /// <returns>A Boolean value that indicates the success or failure of
    /// the operation.</returns>
    public async Task<bool> TerminateInstanceInAutoScalingGroupAsync(
        string instanceId)
    {
        var request = new TerminateInstanceInAutoScalingGroupRequest
        {
            InstanceId = instanceId,
            ShouldDecrementDesiredCapacity = false,
        };

        var response = await _amazonAutoScaling.TerminateInstanceInAutoScalingGroupAsync(request);

        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You have terminated the instance: {instanceId}");
            return true;
        }

        Console.WriteLine($"Could not terminate {instanceId}");
        return false;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_csharp_4_topic"></a>

次の例は、`UpdateAutoScalingGroup` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/AutoScaling#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Update the capacity of an Auto Scaling group.
    /// </summary>
    /// <param name="groupName">The name of the Auto Scaling group.</param>
    /// <param name="launchTemplateName">The name of the EC2 launch template.</param>
    /// <param name="maxSize">The maximum number of instances that can be
    /// created for the Auto Scaling group.</param>
    /// <returns>A Boolean value indicating the success of the action.</returns>
    public async Task<bool> UpdateAutoScalingGroupAsync(
        string groupName,
        string launchTemplateName,
        int maxSize)
    {
        var templateSpecification = new LaunchTemplateSpecification
        {
            LaunchTemplateName = launchTemplateName,
        };

        var groupRequest = new UpdateAutoScalingGroupRequest
        {
            MaxSize = maxSize,
            AutoScalingGroupName = groupName,
            LaunchTemplate = templateSpecification,
        };

        var response = await _amazonAutoScaling.UpdateAutoScalingGroupAsync(groupRequest);
        if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
        {
            Console.WriteLine($"You successfully updated the Auto Scaling group {groupName}.");
            return true;
        }
        else
        {
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/DotNetSDKV4/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。

# SDK for .NET (v4) を使用した Amazon Bedrock の例
<a name="csharp_4_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Bedrock
<a name="bedrock_Hello_csharp_4_topic"></a>

次のコード例は、Amazon Bedrock の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock#code-examples)での設定と実行の方法を確認してください。

```
using Amazon;
using Amazon.Bedrock;
using Amazon.Bedrock.Model;

namespace BedrockActions;

/// <summary>
/// This example shows how to list foundation models.
/// </summary>
internal class HelloBedrock
{
    /// <summary>
    /// Main method to call the ListFoundationModelsAsync method.
    /// </summary>
    /// <param name="args"> The command line arguments. </param>
    static async Task Main(string[] args)
    {
        // Specify a region endpoint where Amazon Bedrock is available. For a list of supported region see https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html#bedrock-regions
        AmazonBedrockClient bedrockClient = new(RegionEndpoint.USWest2);

        await ListFoundationModelsAsync(bedrockClient);

    }


    /// <summary>
    /// List foundation models.
    /// </summary>
    /// <param name="bedrockClient"> The Amazon Bedrock client. </param>
    private static async Task ListFoundationModelsAsync(AmazonBedrockClient bedrockClient)
    {
        Console.WriteLine("List foundation models with no filter.");

        try
        {
            var response = await bedrockClient.ListFoundationModelsAsync(new ListFoundationModelsRequest()
            {
            });

            if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                foreach (var fm in response.ModelSummaries)
                {
                    WriteToConsole(fm);
                }
            }
            else
            {
                Console.WriteLine("Something wrong happened");
            }
        }
        catch (AmazonBedrockException e)
        {
            Console.WriteLine(e.Message);
        }
    }


    /// <summary>
    /// Write the foundation model summary to console.
    /// </summary>
    /// <param name="foundationModel"> The foundation model summary to write to console. </param>
    private static void WriteToConsole(FoundationModelSummary foundationModel)
    {
        Console.WriteLine($"{foundationModel.ModelId}, Customization: {string.Join(", ", foundationModel.CustomizationsSupported)}, Stream: {foundationModel.ResponseStreamingSupported}, Input: {string.Join(", ", foundationModel.InputModalities)}, Output: {string.Join(", ", foundationModel.OutputModalities)}");
    }
}
```
+  API の詳細については、「AWS SDK for .NET API リファレンス**」の「[ListFoundationModels](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-2023-04-20/ListFoundationModels)」を参照してください。

## アクション
<a name="actions"></a>

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_csharp_4_topic"></a>

次の例は、`ListFoundationModels` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock#code-examples)での設定と実行の方法を確認してください。
利用可能な Bedrock 基盤モデルを一覧表示します。  

```
    /// <summary>
    /// List foundation models.
    /// </summary>
    /// <param name="bedrockClient"> The Amazon Bedrock client. </param>
    private static async Task ListFoundationModelsAsync(AmazonBedrockClient bedrockClient)
    {
        Console.WriteLine("List foundation models with no filter.");

        try
        {
            var response = await bedrockClient.ListFoundationModelsAsync(new ListFoundationModelsRequest()
            {
            });

            if (response?.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                foreach (var fm in response.ModelSummaries)
                {
                    WriteToConsole(fm);
                }
            }
            else
            {
                Console.WriteLine("Something wrong happened");
            }
        }
        catch (AmazonBedrockException e)
        {
            Console.WriteLine(e.Message);
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListFoundationModels](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-2023-04-20/ListFoundationModels)」を参照してください。

# SDK for .NET (v4) を使用した Amazon Bedrock ランタイムの例
<a name="csharp_4_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイムで AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [Anthropic Claude](#anthropic_claude)
+ [Cohere Command](#cohere_command)
+ [Meta Llama](#meta_llama)
+ [Mistral AI](#mistral_ai)

## Anthropic Claude
<a name="anthropic_claude"></a>

### Converse
<a name="bedrock-runtime_Converse_AnthropicClaude_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Anthropic Claude.

using System;
using System.Collections.Generic;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Claude 3 Haiku.
var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseAsync(request);

    // Extract and print the response text.
    string responseText = response?.Output?.Message?.Content?[0]?.Text ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AnthropicClaude_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Anthropic Claude
// and print the response stream.

using System;
using System.Collections.Generic;
using System.Linq;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Claude 3 Haiku.
var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseStreamRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var chunk in response.Stream.AsEnumerable())
    {
        if (chunk is ContentBlockDeltaEvent)
        {
            Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text);
        }
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AnthropicClaude_csharp_4_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Anthropic Claude.

using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Claude 3 Haiku.
var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

//Format the request payload using the model's native structure.
var nativeRequest = JsonSerializer.Serialize(new
{
    anthropic_version = "bedrock-2023-05-31",
    max_tokens = 512,
    temperature = 0.5,
    messages = new[]
    {
        new { role = "user", content = userMessage }
    }
});

// Create a request with the model ID and the model's native request payload.
var request = new InvokeModelRequest()
{
    ModelId = modelId,
    Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)),
    ContentType = "application/json"
};

try
{
    // Send the request to the Bedrock Runtime and wait for the response.
    var response = await client.InvokeModelAsync(request);

    // Decode the response body.
    var modelResponse = await JsonNode.ParseAsync(response.Body);

    // Extract and print the response text.
    var responseText = modelResponse["content"]?[0]?["text"] ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Cohere Command
<a name="cohere_command"></a>

### Converse
<a name="bedrock-runtime_Converse_CohereCommand_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Cohere Command.

using System;
using System.Collections.Generic;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Command R.
var modelId = "cohere.command-r-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseAsync(request);

    // Extract and print the response text.
    string responseText = response?.Output?.Message?.Content?[0]?.Text ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_CohereCommand_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Cohere Command
// and print the response stream.

using System;
using System.Collections.Generic;
using System.Linq;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Command R.
var modelId = "cohere.command-r-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseStreamRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var chunk in response.Stream.AsEnumerable())
    {
        if (chunk is ContentBlockDeltaEvent)
        {
            Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text);
        }
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ConverseStream](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

## Meta Llama
<a name="meta_llama"></a>

### Converse
<a name="bedrock-runtime_Converse_MetaLlama_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Meta Llama.

using System;
using System.Collections.Generic;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Llama 3 8b Instruct.
var modelId = "meta.llama3-8b-instruct-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseAsync(request);

    // Extract and print the response text.
    string responseText = response?.Output?.Message?.Content?[0]?.Text ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_MetaLlama_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Meta Llama
// and print the response stream.

using System;
using System.Collections.Generic;
using System.Linq;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Llama 3 8b Instruct.
var modelId = "meta.llama3-8b-instruct-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseStreamRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var chunk in response.Stream.AsEnumerable())
    {
        if (chunk is ContentBlockDeltaEvent)
        {
            Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text);
        }
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

## Mistral AI
<a name="mistral_ai"></a>

### Converse
<a name="bedrock-runtime_Converse_Mistral_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Mistral.

using System;
using System.Collections.Generic;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Mistral Large.
var modelId = "mistral.mistral-large-2402-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseAsync(request);

    // Extract and print the response text.
    string responseText = response?.Output?.Message?.Content?[0]?.Text ?? "";
    Console.WriteLine(responseText);
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_Mistral_csharp_4_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Mistral
// and print the response stream.

using System;
using System.Collections.Generic;
using System.Linq;
using Amazon;
using Amazon.BedrockRuntime;
using Amazon.BedrockRuntime.Model;

// Create a Bedrock Runtime client in the AWS Region you want to use.
var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);

// Set the model ID, e.g., Mistral Large.
var modelId = "mistral.mistral-large-2402-v1:0";

// Define the user message.
var userMessage = "Describe the purpose of a 'hello world' program in one line.";

// Create a request with the model ID, the user message, and an inference configuration.
var request = new ConverseStreamRequest
{
    ModelId = modelId,
    Messages = new List<Message>
    {
        new Message
        {
            Role = ConversationRole.User,
            Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } }
        }
    },
    InferenceConfig = new InferenceConfiguration()
    {
        MaxTokens = 512,
        Temperature = 0.5F,
        TopP = 0.9F
    }
};

try
{
    // Send the request to the Bedrock Runtime and wait for the result.
    var response = await client.ConverseStreamAsync(request);

    // Extract and print the streamed response text in real-time.
    foreach (var chunk in response.Stream.AsEnumerable())
    {
        if (chunk is ContentBlockDeltaEvent)
        {
            Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text);
        }
    }
}
catch (AmazonBedrockRuntimeException e)
{
    Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}");
    throw;
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/DotNetSDKV4/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

# CloudFormation SDK for .NET (v4) を使用した例
<a name="csharp_4_cloudformation_code_examples"></a>

次のコード例は、 で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています CloudFormation。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)

## はじめに
<a name="get_started"></a>

### こんにち CloudFormationは
<a name="cloudformation_Hello_csharp_4_topic"></a>

次のコード例は、 CloudFormationの使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudFormation#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.Runtime;

namespace CloudFormationActions;

public static class HelloCloudFormation
{
    public static IAmazonCloudFormation _amazonCloudFormation = null!;

    static async Task Main(string[] args)
    {
        // Create the CloudFormation client
        _amazonCloudFormation = new AmazonCloudFormationClient();
        Console.WriteLine($"\nIn Region: {_amazonCloudFormation.Config.RegionEndpoint}");

        // List the resources for each stack
        await ListResources();
    }

    /// <summary>
    /// Method to list stack resources and other information.
    /// </summary>
    /// <returns>True if successful.</returns>
    public static async Task<bool> ListResources()
    {
        try
        {
            Console.WriteLine("Getting CloudFormation stack information...");

            // Get all stacks using the stack paginator.
            var paginatorForDescribeStacks =
                _amazonCloudFormation.Paginators.DescribeStacks(
                    new DescribeStacksRequest());
            if (paginatorForDescribeStacks.Stacks != null)
            {
                await foreach (Stack stack in paginatorForDescribeStacks.Stacks)
                {
                    // Basic information for each stack
                    Console.WriteLine(
                        "\n------------------------------------------------");
                    Console.WriteLine($"\nStack: {stack.StackName}");
                    Console.WriteLine($"  Status: {stack.StackStatus.Value}");
                    Console.WriteLine($"  Created: {stack.CreationTime}");

                    // The tags of each stack (etc.)
                    if (stack.Tags != null && stack.Tags.Count > 0)
                    {
                        Console.WriteLine("  Tags:");
                        foreach (Tag tag in stack.Tags)
                            Console.WriteLine($"    {tag.Key}, {tag.Value}");
                    }

                    // The resources of each stack
                    DescribeStackResourcesResponse responseDescribeResources =
                        await _amazonCloudFormation.DescribeStackResourcesAsync(
                            new DescribeStackResourcesRequest
                            {
                                StackName = stack.StackName
                            });
                    if (responseDescribeResources.StackResources != null && responseDescribeResources.StackResources.Count > 0)
                    {
                        Console.WriteLine("  Resources:");
                        foreach (StackResource resource in responseDescribeResources
                                     .StackResources)
                            Console.WriteLine(
                                $"    {resource.LogicalResourceId}: {resource.ResourceStatus}");
                    }
                }
            }

            Console.WriteLine("\n------------------------------------------------");
            return true;
        }
        catch (AmazonCloudFormationException ex)
        {
            Console.WriteLine("Unable to get stack information:\n" + ex.Message);
            return false;
        }
        catch (AmazonServiceException ex)
        {
            if (ex.Message.Contains("Unable to get IAM security credentials"))
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("If you are usnig SSO, be sure to install" +
                                  " the AWSSDK.SSO and AWSSDK.SSOOIDC packages.");
            }
            else
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return false;
        }
        catch (ArgumentNullException ex)
        {
            if (ex.Message.Contains("Options property cannot be empty: ClientName"))
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("If you are using SSO, have you logged in?");
            }
            else
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return false;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeStackResources](https://docs.aws.amazon.com/goto/DotNetSDKV4/cloudformation-2010-05-15/DescribeStackResources)」を参照してください。

# SDK for .NET (v4) を使用した CloudWatch の例
<a name="csharp_4_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello CloudWatch
<a name="cloudwatch_Hello_csharp_4_topic"></a>

次のコード例は、CloudWatch の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.CloudWatch;
using Amazon.CloudWatch.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CloudWatchActions;

public static class HelloCloudWatch
{
    static async Task Main(string[] args)
    {
        // Use the AWS .NET Core Setup package to set up dependency injection for the Amazon CloudWatch service.
        // Use your AWS profile name, or leave it blank to use the default profile.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonCloudWatch>()
            ).Build();

        // Now the client is available for injection.
        var cloudWatchClient = host.Services.GetRequiredService<IAmazonCloudWatch>();

        // You can use await and any of the async methods to get a response.
        var metricNamespace = "AWS/Billing";
        var response = await cloudWatchClient.ListMetricsAsync(new ListMetricsRequest
        {
            Namespace = metricNamespace
        });
        Console.WriteLine($"Hello Amazon CloudWatch! Following are some metrics available in the {metricNamespace} namespace:");
        Console.WriteLine();
        if (response.Metrics != null)
        {
            foreach (var metric in response.Metrics.Take(5))
            {
                Console.WriteLine($"\tMetric: {metric.MetricName}");
                Console.WriteLine($"\tNamespace: {metric.Namespace}");
                Console.WriteLine(
                    $"\tDimensions: {string.Join(", ", metric.Dimensions.Select(m => $"{m.Name}:{m.Value}"))}");
                Console.WriteLine();
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListMetrics](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/ListMetrics)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="cloudwatch_GetStartedMetricsDashboardsAlarms_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ CloudWatch の名前空間とメトリクスを一覧表示します。
+ メトリクスと予想請求額の統計の取得
+ ダッシュボードの作成と更新
+ メトリクスの作成とデータの追加
+ アラームの作成/トリガーとアラーム履歴の表示
+ 異常ディテクターの追加
+ メトリクス画像を取得し、リソースをクリーンアップします。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
public class CloudWatchScenario
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.

    To enable billing metrics and statistics for this example, make sure billing alerts are enabled for your account:
    https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics

    This .NET example performs the following tasks:
        1. List and select a CloudWatch namespace.
        2. List and select a CloudWatch metric.
        3. Get statistics for a CloudWatch metric.
        4. Get estimated billing statistics for the last week.
        5. Create a new CloudWatch dashboard with two metrics.
        6. List current CloudWatch dashboards.
        7. Create a CloudWatch custom metric and add metric data.
        8. Add the custom metric to the dashboard.
        9. Create a CloudWatch alarm for the custom metric.
       10. Describe current CloudWatch alarms.
       11. Get recent data for the custom metric.
       12. Add data to the custom metric to trigger the alarm.
       13. Wait for an alarm state.
       14. Get history for the CloudWatch alarm.
       15. Add an anomaly detector.
       16. Describe current anomaly detectors.
       17. Get and display a metric image.
       18. Clean up resources.
    */

    private static ILogger logger = null!;
    private static CloudWatchWrapper _cloudWatchWrapper = null!;
    private static IConfiguration _configuration = null!;
    private static readonly List<string> _statTypes = new List<string> { "SampleCount", "Average", "Sum", "Minimum", "Maximum" };
    private static SingleMetricAnomalyDetector? anomalyDetector = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
            services.AddAWSService<IAmazonCloudWatch>()
            .AddTransient<CloudWatchWrapper>()
        )
        .Build();

        _configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("settings.json") // Load settings from .json file.
            .AddJsonFile("settings.local.json",
                true) // Optionally, load local settings.
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<CloudWatchScenario>();

        _cloudWatchWrapper = host.Services.GetRequiredService<CloudWatchWrapper>();

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the Amazon CloudWatch example scenario.");
        Console.WriteLine(new string('-', 80));

        try
        {
            var selectedNamespace = await SelectNamespace();
            var selectedMetric = await SelectMetric(selectedNamespace);
            await GetAndDisplayMetricStatistics(selectedNamespace, selectedMetric);
            await GetAndDisplayEstimatedBilling();
            await CreateDashboardWithMetrics();
            await ListDashboards();
            await CreateNewCustomMetric();
            await AddMetricToDashboard();
            await CreateMetricAlarm();
            await DescribeAlarms();
            await GetCustomMetricData();
            await AddMetricDataForAlarm();
            await CheckForMetricAlarm();
            await GetAlarmHistory();
            anomalyDetector = await AddAnomalyDetector();
            await DescribeAnomalyDetectors();
            await GetAndOpenMetricImage();
            await CleanupResources();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "There was a problem executing the scenario.");
            await CleanupResources();
        }

    }

    /// <summary>
    /// Select a namespace.
    /// </summary>
    /// <returns>The selected namespace.</returns>
    private static async Task<string> SelectNamespace()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"1. Select a CloudWatch Namespace from a list of Namespaces.");
        var metrics = await _cloudWatchWrapper.ListMetrics();
        // Get a distinct list of namespaces.
        var namespaces = metrics.Select(m => m.Namespace).Distinct().ToList();
        for (int i = 0; i < namespaces.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {namespaces[i]}");
        }

        var namespaceChoiceNumber = 0;
        while (namespaceChoiceNumber < 1 || namespaceChoiceNumber > namespaces.Count)
        {
            Console.WriteLine(
                "Select a namespace by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out namespaceChoiceNumber);
        }

        var selectedNamespace = namespaces[namespaceChoiceNumber - 1];

        Console.WriteLine(new string('-', 80));

        return selectedNamespace;
    }

    /// <summary>
    /// Select a metric from a namespace.
    /// </summary>
    /// <param name="metricNamespace">The namespace for metrics.</param>
    /// <returns>The metric name.</returns>
    private static async Task<Metric> SelectMetric(string metricNamespace)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"2. Select a CloudWatch metric from a namespace.");

        var namespaceMetrics = await _cloudWatchWrapper.ListMetrics(metricNamespace);

        for (int i = 0; i < namespaceMetrics.Count && i < 15; i++)
        {
            var dimensionsWithValues = namespaceMetrics[i].Dimensions
                .Where(d => !string.Equals("None", d.Value));
            Console.WriteLine($"\t{i + 1}. {namespaceMetrics[i].MetricName} " +
                              $"{string.Join(", :", dimensionsWithValues.Select(d => d.Value))}");
        }

        var metricChoiceNumber = 0;
        while (metricChoiceNumber < 1 || metricChoiceNumber > namespaceMetrics.Count)
        {
            Console.WriteLine(
                "Select a metric by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out metricChoiceNumber);
        }

        var selectedMetric = namespaceMetrics[metricChoiceNumber - 1];

        Console.WriteLine(new string('-', 80));

        return selectedMetric;
    }

    /// <summary>
    /// Get and display metric statistics for a specific metric.
    /// </summary>
    /// <param name="metricNamespace">The namespace for metrics.</param>
    /// <param name="metric">The CloudWatch metric.</param>
    /// <returns>Async task.</returns>
    private static async Task GetAndDisplayMetricStatistics(string metricNamespace, Metric metric)
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"3. Get CloudWatch metric statistics for the last day.");

        for (int i = 0; i < _statTypes.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {_statTypes[i]}");
        }

        var statisticChoiceNumber = 0;
        while (statisticChoiceNumber < 1 || statisticChoiceNumber > _statTypes.Count)
        {
            Console.WriteLine(
                "Select a metric statistic by entering a number from the preceding list:");
            var choice = Console.ReadLine();
            Int32.TryParse(choice, out statisticChoiceNumber);
        }

        var selectedStatistic = _statTypes[statisticChoiceNumber - 1];
        var statisticsList = new List<string> { selectedStatistic };

        var metricStatistics = await _cloudWatchWrapper.GetMetricStatistics(metricNamespace, metric.MetricName, statisticsList, metric.Dimensions, 1, 60);

        if (!metricStatistics.Any())
        {
            Console.WriteLine($"No {selectedStatistic} statistics found for {metric} in namespace {metricNamespace}.");
        }

        metricStatistics = metricStatistics.OrderBy(s => s.Timestamp).ToList();
        for (int i = 0; i < metricStatistics.Count && i < 10; i++)
        {
            var metricStat = metricStatistics[i];
            var statValue = metricStat.GetType().GetProperty(selectedStatistic)!.GetValue(metricStat, null);
            Console.WriteLine($"\t{i + 1}. Timestamp {metricStatistics[i].Timestamp:G} {selectedStatistic}: {statValue}");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Get and display estimated billing statistics.
    /// </summary>
    /// <param name="metricNamespace">The namespace for metrics.</param>
    /// <param name="metric">The CloudWatch metric.</param>
    /// <returns>Async task.</returns>
    private static async Task GetAndDisplayEstimatedBilling()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"4. Get CloudWatch estimated billing for the last week.");

        var billingStatistics = await SetupBillingStatistics();

        for (int i = 0; i < billingStatistics.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. Timestamp {billingStatistics[i].Timestamp:G} : {billingStatistics[i].Maximum}");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Get billing statistics using a call to a wrapper class.
    /// </summary>
    /// <returns>A collection of billing statistics.</returns>
    private static async Task<List<Datapoint>> SetupBillingStatistics()
    {
        // Make a request for EstimatedCharges with a period of one day for the past seven days.
        var billingStatistics = await _cloudWatchWrapper.GetMetricStatistics(
            "AWS/Billing",
            "EstimatedCharges",
            new List<string>() { "Maximum" },
            new List<Dimension>() { new Dimension { Name = "Currency", Value = "USD" } },
            7,
            86400);

        billingStatistics = billingStatistics.OrderBy(n => n.Timestamp).ToList();

        return billingStatistics;
    }

    /// <summary>
    /// Create a dashboard with metrics.
    /// </summary>
    /// <param name="metricNamespace">The namespace for metrics.</param>
    /// <param name="metric">The CloudWatch metric.</param>
    /// <returns>Async task.</returns>
    private static async Task CreateDashboardWithMetrics()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"5. Create a new CloudWatch dashboard with metrics.");
        var dashboardName = _configuration["dashboardName"];
        var newDashboard = new DashboardModel();
        _configuration.GetSection("dashboardExampleBody").Bind(newDashboard);
        var newDashboardString = JsonSerializer.Serialize(
            newDashboard,
            new JsonSerializerOptions
            {
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
            });
        var validationMessages =
            await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString);

        Console.WriteLine(validationMessages.Any() ? $"\tValidation messages:" : null);
        for (int i = 0; i < validationMessages.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {validationMessages[i].Message}");
        }
        Console.WriteLine($"\tDashboard {dashboardName} was created.");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// List dashboards.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task ListDashboards()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"6. List the CloudWatch dashboards in the current account.");

        var dashboards = await _cloudWatchWrapper.ListDashboards();

        for (int i = 0; i < dashboards.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {dashboards[i].DashboardName}");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Create and add data for a new custom metric.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CreateNewCustomMetric()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"7. Create and add data for a new custom metric.");

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];

        var customData = await PutRandomMetricData(customMetricName, customMetricNamespace);

        var valuesString = string.Join(',', customData.Select(d => d.Value));
        Console.WriteLine($"\tAdded metric values for for metric {customMetricName}: \n\t{valuesString}");

        Console.WriteLine(new string('-', 80));
    }


    /// <summary>
    /// Add some metric data using a call to a wrapper class.
    /// </summary>
    /// <param name="customMetricName">The metric name.</param>
    /// <param name="customMetricNamespace">The metric namespace.</param>
    /// <returns></returns>
    private static async Task<List<MetricDatum>> PutRandomMetricData(string customMetricName,
        string customMetricNamespace)
    {
        List<MetricDatum> customData = new List<MetricDatum>();
        Random rnd = new Random();

        // Add 10 random values up to 100, starting with a timestamp 15 minutes in the past.
        var utcNowMinus15 = DateTime.UtcNow.AddMinutes(-15);
        for (int i = 0; i < 10; i++)
        {
            var metricValue = rnd.Next(0, 100);
            customData.Add(
                new MetricDatum
                {
                    MetricName = customMetricName,
                    Value = metricValue,
                    TimestampUtc = utcNowMinus15.AddMinutes(i)
                }
            );
        }

        await _cloudWatchWrapper.PutMetricData(customMetricNamespace, customData);
        return customData;
    }

    /// <summary>
    /// Add the custom metric to the dashboard.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task AddMetricToDashboard()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"8. Add the new custom metric to the dashboard.");

        var dashboardName = _configuration["dashboardName"];

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];

        var validationMessages = await SetupDashboard(customMetricNamespace, customMetricName, dashboardName);

        Console.WriteLine(validationMessages.Any() ? $"\tValidation messages:" : null);
        for (int i = 0; i < validationMessages.Count; i++)
        {
            Console.WriteLine($"\t{i + 1}. {validationMessages[i].Message}");
        }
        Console.WriteLine($"\tDashboard {dashboardName} updated with metric {customMetricName}.");
        Console.WriteLine(new string('-', 80));
    }


    /// <summary>
    /// Set up a dashboard using a call to the wrapper class.
    /// </summary>
    /// <param name="customMetricNamespace">The metric namespace.</param>
    /// <param name="customMetricName">The metric name.</param>
    /// <param name="dashboardName">The name of the dashboard.</param>
    /// <returns>A list of validation messages.</returns>
    private static async Task<List<DashboardValidationMessage>> SetupDashboard(
        string customMetricNamespace, string customMetricName, string dashboardName)
    {
        // Get the dashboard model from configuration.
        var newDashboard = new DashboardModel();
        _configuration.GetSection("dashboardExampleBody").Bind(newDashboard);

        // Add a new metric to the dashboard.
        newDashboard.Widgets.Add(new Widget
        {
            Height = 8,
            Width = 8,
            Y = 8,
            X = 0,
            Type = "metric",
            Properties = new Properties
            {
                Metrics = new List<List<object>>
                    { new() { customMetricNamespace, customMetricName } },
                View = "timeSeries",
                Region = "us-east-1",
                Stat = "Sum",
                Period = 86400,
                YAxis = new YAxis { Left = new Left { Min = 0, Max = 100 } },
                Title = "Custom Metric Widget",
                LiveData = true,
                Sparkline = true,
                Trend = true,
                Stacked = false,
                SetPeriodToTimeRange = false
            }
        });

        var newDashboardString = JsonSerializer.Serialize(newDashboard,
            new JsonSerializerOptions
            { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
        var validationMessages =
            await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString);

        return validationMessages;
    }

    /// <summary>
    /// Create a CloudWatch alarm for the new metric.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CreateMetricAlarm()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"9. Create a CloudWatch alarm for the new metric.");

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];

        var alarmName = _configuration["exampleAlarmName"];
        var accountId = _configuration["accountId"];
        var region = _configuration["region"];
        var emailTopic = _configuration["emailTopic"];
        var alarmActions = new List<string>();

        if (GetYesNoResponse(
                $"\tAdd an email action for topic {emailTopic} to alarm {alarmName}? (y/n)"))
        {
            _cloudWatchWrapper.AddEmailAlarmAction(accountId, region, emailTopic, alarmActions);
        }

        await _cloudWatchWrapper.PutMetricEmailAlarm(
            "Example metric alarm",
            alarmName,
            ComparisonOperator.GreaterThanOrEqualToThreshold,
            customMetricName,
            customMetricNamespace,
            100,
            alarmActions);

        Console.WriteLine($"\tAlarm {alarmName} added for metric {customMetricName}.");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Describe Alarms.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task DescribeAlarms()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"10. Describe CloudWatch alarms in the current account.");

        var alarms = await _cloudWatchWrapper.DescribeAlarms();
        alarms = alarms.OrderByDescending(a => a.StateUpdatedTimestamp).ToList();

        for (int i = 0; i < alarms.Count && i < 10; i++)
        {
            var alarm = alarms[i];
            Console.WriteLine($"\t{i + 1}. {alarm.AlarmName}");
            Console.WriteLine($"\tState: {alarm.StateValue} for {alarm.MetricName} {alarm.ComparisonOperator} {alarm.Threshold}");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Get the recent data for the metric.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task GetCustomMetricData()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"11. Get current data for new custom metric.");

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];
        var accountId = _configuration["accountId"];

        var query = new List<MetricDataQuery>
        {
            new MetricDataQuery
            {
                AccountId = accountId,
                Id = "m1",
                Label = "Custom Metric Data",
                MetricStat = new MetricStat
                {
                    Metric = new Metric
                    {
                        MetricName = customMetricName,
                        Namespace = customMetricNamespace,
                    },
                    Period = 1,
                    Stat = "Maximum"
                }
            }
        };

        var metricData = await _cloudWatchWrapper.GetMetricData(
            20,
            true,
            DateTime.UtcNow.AddMinutes(1),
            20,
            query);

        for (int i = 0; i < metricData.Count; i++)
        {
            if (metricData[i].Values != null)
            {
                for (int j = 0; j < metricData[i].Values.Count; j++)
                {
                    Console.WriteLine(
                        $"\tTimestamp {metricData[i].Timestamps[j]:G} Value: {metricData[i].Values[j]}");
                }
            }
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Add metric data to trigger an alarm.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task AddMetricDataForAlarm()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"12. Add metric data to the custom metric to trigger an alarm.");

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];
        var nowUtc = DateTime.UtcNow;
        List<MetricDatum> customData = new List<MetricDatum>
        {
            new MetricDatum
            {
                MetricName = customMetricName,
                Value = 101,
                TimestampUtc = nowUtc.AddMinutes(-2)
            },
            new MetricDatum
            {
                MetricName = customMetricName,
                Value = 101,
                TimestampUtc = nowUtc.AddMinutes(-1)
            },
            new MetricDatum
            {
                MetricName = customMetricName,
                Value = 101,
                TimestampUtc = nowUtc
            }
        };
        var valuesString = string.Join(',', customData.Select(d => d.Value));
        Console.WriteLine($"\tAdded metric values for for metric {customMetricName}: \n\t{valuesString}");
        await _cloudWatchWrapper.PutMetricData(customMetricNamespace, customData);

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Check for a metric alarm using the DescribeAlarmsForMetric action.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task CheckForMetricAlarm()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"13. Checking for an alarm state.");

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];
        var hasAlarm = false;
        var retries = 10;
        while (!hasAlarm && retries > 0)
        {
            var alarms = await _cloudWatchWrapper.DescribeAlarmsForMetric(customMetricNamespace, customMetricName);
            hasAlarm = alarms.Any(a => a.StateValue == StateValue.ALARM);
            retries--;
            Thread.Sleep(20000);
        }

        Console.WriteLine(hasAlarm
            ? $"\tAlarm state found for {customMetricName}."
            : $"\tNo Alarm state found for {customMetricName} after 10 retries.");

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Get history for an alarm.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task GetAlarmHistory()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"14. Get alarm history.");

        var exampleAlarmName = _configuration["exampleAlarmName"];

        var alarmHistory = await _cloudWatchWrapper.DescribeAlarmHistory(exampleAlarmName, 2);

        for (int i = 0; i < alarmHistory.Count; i++)
        {
            var history = alarmHistory[i];
            Console.WriteLine($"\t{i + 1}. {history.HistorySummary}, time {history.Timestamp:g}");
        }
        if (!alarmHistory.Any())
        {
            Console.WriteLine($"\tNo alarm history data found for {exampleAlarmName}.");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Add an anomaly detector.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task<SingleMetricAnomalyDetector> AddAnomalyDetector()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"15. Add an anomaly detector.");

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];

        var detector = new SingleMetricAnomalyDetector
        {
            MetricName = customMetricName,
            Namespace = customMetricNamespace,
            Stat = "Maximum"
        };
        await _cloudWatchWrapper.PutAnomalyDetector(detector);
        Console.WriteLine($"\tAdded anomaly detector for metric {customMetricName}.");

        Console.WriteLine(new string('-', 80));
        return detector;
    }

    /// <summary>
    /// Describe anomaly detectors.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task DescribeAnomalyDetectors()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"16. Describe anomaly detectors in the current account.");

        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];

        var detectors = await _cloudWatchWrapper.DescribeAnomalyDetectors(customMetricNamespace, customMetricName);

        for (int i = 0; i < detectors.Count; i++)
        {
            var detector = detectors[i];
            Console.WriteLine($"\t{i + 1}. {detector.SingleMetricAnomalyDetector.MetricName}, state {detector.StateValue}");
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Fetch and open a metrics image for a CloudWatch metric and namespace.
    /// </summary>
    /// <returns>Async task.</returns>
    private static async Task GetAndOpenMetricImage()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("17. Get a metric image from CloudWatch.");

        Console.WriteLine($"\tGetting Image data for custom metric.");
        var customMetricNamespace = _configuration["customMetricNamespace"];
        var customMetricName = _configuration["customMetricName"];

        var memoryStream = await _cloudWatchWrapper.GetTimeSeriesMetricImage(customMetricNamespace, customMetricName, "Maximum", 10);
        var file = _cloudWatchWrapper.SaveMetricImage(memoryStream, "MetricImages");

        ProcessStartInfo info = new ProcessStartInfo();

        Console.WriteLine($"\tFile saved as {Path.GetFileName(file)}.");
        Console.WriteLine($"\tPress enter to open the image.");
        Console.ReadLine();
        info.FileName = Path.Combine("ms-photos://", file);
        info.UseShellExecute = true;
        info.CreateNoWindow = true;
        info.Verb = string.Empty;

        Process.Start(info);

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Clean up created resources.
    /// </summary>
    /// <param name="metricNamespace">The namespace for metrics.</param>
    /// <param name="metric">The CloudWatch metric.</param>
    /// <returns>Async task.</returns>
    private static async Task CleanupResources()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine($"18. Clean up resources.");

        var dashboardName = _configuration["dashboardName"];
        if (GetYesNoResponse($"\tDelete dashboard {dashboardName}? (y/n)"))
        {
            Console.WriteLine($"\tDeleting dashboard.");
            var dashboardList = new List<string> { dashboardName };
            await _cloudWatchWrapper.DeleteDashboards(dashboardList);
        }

        var alarmName = _configuration["exampleAlarmName"];
        if (GetYesNoResponse($"\tDelete alarm {alarmName}? (y/n)"))
        {
            Console.WriteLine($"\tCleaning up alarms.");
            var alarms = new List<string> { alarmName };
            await _cloudWatchWrapper.DeleteAlarms(alarms);
        }

        if (GetYesNoResponse($"\tDelete anomaly detector? (y/n)") && anomalyDetector != null)
        {
            Console.WriteLine($"\tCleaning up anomaly detector.");

            await _cloudWatchWrapper.DeleteAnomalyDetector(
                anomalyDetector);
        }

        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Get a yes or no response from the user.
    /// </summary>
    /// <param name="question">The question string to print on the console.</param>
    /// <returns>True if the user responds with a yes.</returns>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null &&
                       ynResponse.Equals("y",
                           StringComparison.InvariantCultureIgnoreCase);
        return response;
    }
}
```
CloudWatch アクションのシナリオで使用されるラッパーメソッドです。  

```
/// <summary>
/// Wrapper class for Amazon CloudWatch methods.
/// </summary>
public class CloudWatchWrapper
{
    private readonly IAmazonCloudWatch _amazonCloudWatch;
    private readonly ILogger<CloudWatchWrapper> _logger;

    /// <summary>
    /// Constructor for the CloudWatch wrapper.
    /// </summary>
    /// <param name="amazonCloudWatch">The injected CloudWatch client.</param>
    /// <param name="logger">The injected logger for the wrapper.</param>
    public CloudWatchWrapper(IAmazonCloudWatch amazonCloudWatch, ILogger<CloudWatchWrapper> logger)

    {
        _logger = logger;
        _amazonCloudWatch = amazonCloudWatch;
    }

    /// <summary>
    /// List metrics available, optionally within a namespace.
    /// </summary>
    /// <param name="metricNamespace">Optional CloudWatch namespace to use when listing metrics.</param>
    /// <param name="filter">Optional dimension filter.</param>
    /// <param name="metricName">Optional metric name filter.</param>
    /// <returns>The list of metrics.</returns>
    public async Task<List<Metric>> ListMetrics(string? metricNamespace = null, DimensionFilter? filter = null, string? metricName = null)
    {
        var results = new List<Metric>();
        var paginateMetrics = _amazonCloudWatch.Paginators.ListMetrics(
            new ListMetricsRequest
            {
                Namespace = metricNamespace,
                Dimensions = filter != null ? new List<DimensionFilter> { filter } : null,
                MetricName = metricName
            });
        // Get the entire list using the paginator.
        await foreach (var metric in paginateMetrics.Metrics)
        {
            results.Add(metric);
        }

        return results;
    }

    /// <summary>
    /// Wrapper to get statistics for a specific CloudWatch metric.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricName">The name of the metric.</param>
    /// <param name="statistics">The list of statistics to include.</param>
    /// <param name="dimensions">The list of dimensions to include.</param>
    /// <param name="days">The number of days in the past to include.</param>
    /// <param name="period">The period for the data.</param>
    /// <returns>A list of DataPoint objects for the statistics.</returns>
    public async Task<List<Datapoint>> GetMetricStatistics(string metricNamespace,
        string metricName, List<string> statistics, List<Dimension> dimensions, int days, int period)
    {
        var metricStatistics = await _amazonCloudWatch.GetMetricStatisticsAsync(
            new GetMetricStatisticsRequest()
            {
                Namespace = metricNamespace,
                MetricName = metricName,
                Dimensions = dimensions,
                Statistics = statistics,
                StartTimeUtc = DateTime.UtcNow.AddDays(-days),
                EndTimeUtc = DateTime.UtcNow,
                Period = period
            });

        return metricStatistics.Datapoints ?? new List<Datapoint>();
    }

    /// <summary>
    /// Wrapper to create or add to a dashboard with metrics.
    /// </summary>
    /// <param name="dashboardName">The name for the dashboard.</param>
    /// <param name="dashboardBody">The metric data in JSON for the dashboard.</param>
    /// <returns>A list of validation messages for the dashboard.</returns>
    public async Task<List<DashboardValidationMessage>> PutDashboard(string dashboardName,
        string dashboardBody)
    {
        // Updating a dashboard replaces all contents.
        // Best practice is to include a text widget indicating this dashboard was created programmatically.
        var dashboardResponse = await _amazonCloudWatch.PutDashboardAsync(
            new PutDashboardRequest()
            {
                DashboardName = dashboardName,
                DashboardBody = dashboardBody
            });

        return dashboardResponse.DashboardValidationMessages ?? new List<DashboardValidationMessage>();
    }


    /// <summary>
    /// Get information on a dashboard.
    /// </summary>
    /// <param name="dashboardName">The name of the dashboard.</param>
    /// <returns>A JSON object with dashboard information.</returns>
    public async Task<string> GetDashboard(string dashboardName)
    {
        var dashboardResponse = await _amazonCloudWatch.GetDashboardAsync(
            new GetDashboardRequest()
            {
                DashboardName = dashboardName
            });

        return dashboardResponse.DashboardBody;
    }


    /// <summary>
    /// Get a list of dashboards.
    /// </summary>
    /// <returns>A list of DashboardEntry objects.</returns>
    public async Task<List<DashboardEntry>> ListDashboards()
    {
        var results = new List<DashboardEntry>();
        var paginateDashboards = _amazonCloudWatch.Paginators.ListDashboards(
            new ListDashboardsRequest());
        // Get the entire list using the paginator.
        await foreach (var data in paginateDashboards.DashboardEntries)
        {
            results.Add(data);
        }

        return results;
    }

    /// <summary>
    /// Wrapper to add metric data to a CloudWatch metric.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricData">A data object for the metric data.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutMetricData(string metricNamespace,
        List<MetricDatum> metricData)
    {
        var putDataResponse = await _amazonCloudWatch.PutMetricDataAsync(
            new PutMetricDataRequest()
            {
                MetricData = metricData,
                Namespace = metricNamespace,
            });

        return putDataResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Get an image for a metric graphed over time.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metric">The name of the metric.</param>
    /// <param name="stat">The name of the stat to chart.</param>
    /// <param name="period">The period to use for the chart.</param>
    /// <returns>A memory stream for the chart image.</returns>
    public async Task<MemoryStream> GetTimeSeriesMetricImage(string metricNamespace, string metric, string stat, int period)
    {
        var metricImageWidget = new
        {
            title = "Example Metric Graph",
            view = "timeSeries",
            stacked = false,
            period = period,
            width = 1400,
            height = 600,
            metrics = new List<List<object>>
                { new() { metricNamespace, metric, new { stat } } }
        };

        var metricImageWidgetString = JsonSerializer.Serialize(metricImageWidget);
        var imageResponse = await _amazonCloudWatch.GetMetricWidgetImageAsync(
            new GetMetricWidgetImageRequest()
            {
                MetricWidget = metricImageWidgetString
            });

        return imageResponse.MetricWidgetImage;
    }

    /// <summary>
    /// Save a metric image to a file.
    /// </summary>
    /// <param name="memoryStream">The MemoryStream for the metric image.</param>
    /// <param name="metricName">The name of the metric.</param>
    /// <returns>The path to the file.</returns>
    public string SaveMetricImage(MemoryStream memoryStream, string metricName)
    {
        var metricFileName = $"{metricName}_{DateTime.Now.Ticks}.png";
        using var sr = new StreamReader(memoryStream);
        // Writes the memory stream to a file.
        File.WriteAllBytes(metricFileName, memoryStream.ToArray());
        var filePath = Path.Join(AppDomain.CurrentDomain.BaseDirectory,
            metricFileName);
        return filePath;
    }

    /// <summary>
    /// Get data for CloudWatch metrics.
    /// </summary>
    /// <param name="minutesOfData">The number of minutes of data to include.</param>
    /// <param name="useDescendingTime">True to return the data descending by time.</param>
    /// <param name="endDateUtc">The end date for the data, in UTC.</param>
    /// <param name="maxDataPoints">The maximum data points to include.</param>
    /// <param name="dataQueries">Optional data queries to include.</param>
    /// <returns>A list of the requested metric data.</returns>
    public async Task<List<MetricDataResult>> GetMetricData(int minutesOfData, bool useDescendingTime, DateTime? endDateUtc = null,
        int maxDataPoints = 0, List<MetricDataQuery>? dataQueries = null)
    {
        var metricData = new List<MetricDataResult>();
        // If no end time is provided, use the current time for the end time.
        endDateUtc ??= DateTime.UtcNow;
        var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(endDateUtc.Value.ToLocalTime());
        var startTimeUtc = endDateUtc.Value.AddMinutes(-minutesOfData);
        // The timezone string should be in the format +0000, so use the timezone offset to format it correctly.
        var timeZoneString = $"{timeZoneOffset.Hours:D2}{timeZoneOffset.Minutes:D2}";
        // Add the plus sign for positive offsets.
        timeZoneString = timeZoneString.StartsWith('-') ? timeZoneString : "+" + timeZoneString;
        var paginatedMetricData = _amazonCloudWatch.Paginators.GetMetricData(
            new GetMetricDataRequest()
            {
                StartTimeUtc = startTimeUtc,
                EndTimeUtc = endDateUtc.Value,
                LabelOptions = new LabelOptions { Timezone = timeZoneString },
                ScanBy = useDescendingTime ? ScanBy.TimestampDescending : ScanBy.TimestampAscending,
                MaxDatapoints = maxDataPoints,
                MetricDataQueries = dataQueries,
            });

        if (paginatedMetricData.MetricDataResults != null)
        {
            await foreach (var data in paginatedMetricData.MetricDataResults)
            {
                metricData.Add(data);
            }
        }

        return metricData;
    }

    /// <summary>
    /// Add a metric alarm to send an email when the metric passes a threshold.
    /// </summary>
    /// <param name="alarmDescription">A description of the alarm.</param>
    /// <param name="alarmName">The name for the alarm.</param>
    /// <param name="comparison">The type of comparison to use.</param>
    /// <param name="metricName">The name of the metric for the alarm.</param>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="threshold">The threshold value for the alarm.</param>
    /// <param name="alarmActions">Optional actions to execute when in an alarm state.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutMetricEmailAlarm(string alarmDescription, string alarmName, ComparisonOperator comparison,
        string metricName, string metricNamespace, double threshold, List<string> alarmActions = null!)
    {
        try
        {
            var putEmailAlarmResponse = await _amazonCloudWatch.PutMetricAlarmAsync(
                new PutMetricAlarmRequest()
                {
                    AlarmActions = alarmActions,
                    AlarmDescription = alarmDescription,
                    AlarmName = alarmName,
                    ComparisonOperator = comparison,
                    Threshold = threshold,
                    Namespace = metricNamespace,
                    MetricName = metricName,
                    EvaluationPeriods = 1,
                    Period = 10,
                    Statistic = new Statistic("Maximum"),
                    DatapointsToAlarm = 1,
                    TreatMissingData = "ignore"
                });
            return putEmailAlarmResponse.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (LimitExceededException lex)
        {
            _logger.LogError(lex, $"Unable to add alarm {alarmName}. Alarm quota has already been reached.");
        }

        return false;
    }

    /// <summary>
    /// Add specific email actions to a list of action strings for a CloudWatch alarm.
    /// </summary>
    /// <param name="accountId">The AccountId for the alarm.</param>
    /// <param name="region">The region for the alarm.</param>
    /// <param name="emailTopicName">An Amazon Simple Notification Service (SNS) topic for the alarm email.</param>
    /// <param name="alarmActions">Optional list of existing alarm actions to append to.</param>
    /// <returns>A list of string actions for an alarm.</returns>
    public List<string> AddEmailAlarmAction(string accountId, string region,
        string emailTopicName, List<string>? alarmActions = null)
    {
        alarmActions ??= new List<string>();
        var snsAlarmAction = $"arn:aws:sns:{region}:{accountId}:{emailTopicName}";
        alarmActions.Add(snsAlarmAction);
        return alarmActions;
    }

    /// <summary>
    /// Describe the current alarms, optionally filtered by state.
    /// </summary>
    /// <param name="stateValue">Optional filter for alarm state.</param>
    /// <returns>The list of alarm data.</returns>
    public async Task<List<MetricAlarm>> DescribeAlarms(StateValue? stateValue = null)
    {
        List<MetricAlarm> alarms = new List<MetricAlarm>();
        var paginatedDescribeAlarms = _amazonCloudWatch.Paginators.DescribeAlarms(
            new DescribeAlarmsRequest()
            {
                StateValue = stateValue
            });

        await foreach (var data in paginatedDescribeAlarms.MetricAlarms)
        {
            alarms.Add(data);
        }
        return alarms;
    }

    /// <summary>
    /// Describe the current alarms for a specific metric.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricName">The name of the metric.</param>
    /// <returns>The list of alarm data.</returns>
    public async Task<List<MetricAlarm>> DescribeAlarmsForMetric(string metricNamespace, string metricName)
    {
        var alarmsResult = await _amazonCloudWatch.DescribeAlarmsForMetricAsync(
            new DescribeAlarmsForMetricRequest()
            {
                Namespace = metricNamespace,
                MetricName = metricName
            });

        return alarmsResult.MetricAlarms ?? new List<MetricAlarm>();
    }

    /// <summary>
    /// Describe the history of an alarm for a number of days in the past.
    /// </summary>
    /// <param name="alarmName">The name of the alarm.</param>
    /// <param name="historyDays">The number of days in the past.</param>
    /// <returns>The list of alarm history data.</returns>
    public async Task<List<AlarmHistoryItem>> DescribeAlarmHistory(string alarmName, int historyDays)
    {
        List<AlarmHistoryItem> alarmHistory = new List<AlarmHistoryItem>();
        var paginatedAlarmHistory = _amazonCloudWatch.Paginators.DescribeAlarmHistory(
            new DescribeAlarmHistoryRequest()
            {
                AlarmName = alarmName,
                EndDateUtc = DateTime.UtcNow,
                HistoryItemType = HistoryItemType.StateUpdate,
                StartDateUtc = DateTime.UtcNow.AddDays(-historyDays)
            });

        await foreach (var data in paginatedAlarmHistory.AlarmHistoryItems)
        {
            alarmHistory.Add(data);
        }
        return alarmHistory;
    }

    /// <summary>
    /// Delete a list of alarms from CloudWatch.
    /// </summary>
    /// <param name="alarmNames">A list of names of alarms to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteAlarms(List<string> alarmNames)
    {
        var deleteAlarmsResult = await _amazonCloudWatch.DeleteAlarmsAsync(
            new DeleteAlarmsRequest()
            {
                AlarmNames = alarmNames
            });

        return deleteAlarmsResult.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Disable the actions for a list of alarms from CloudWatch.
    /// </summary>
    /// <param name="alarmNames">A list of names of alarms.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DisableAlarmActions(List<string> alarmNames)
    {
        var disableAlarmActionsResult = await _amazonCloudWatch.DisableAlarmActionsAsync(
            new DisableAlarmActionsRequest()
            {
                AlarmNames = alarmNames
            });

        return disableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Enable the actions for a list of alarms from CloudWatch.
    /// </summary>
    /// <param name="alarmNames">A list of names of alarms.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> EnableAlarmActions(List<string> alarmNames)
    {
        var enableAlarmActionsResult = await _amazonCloudWatch.EnableAlarmActionsAsync(
            new EnableAlarmActionsRequest()
            {
                AlarmNames = alarmNames
            });

        return enableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Add an anomaly detector for a single metric.
    /// </summary>
    /// <param name="anomalyDetector">A single metric anomaly detector.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector)
    {
        var putAlarmDetectorResult = await _amazonCloudWatch.PutAnomalyDetectorAsync(
            new PutAnomalyDetectorRequest()
            {
                SingleMetricAnomalyDetector = anomalyDetector
            });

        return putAlarmDetectorResult.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Describe anomaly detectors for a metric and namespace.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricName">The metric of the anomaly detectors.</param>
    /// <returns>The list of detectors.</returns>
    public async Task<List<AnomalyDetector>> DescribeAnomalyDetectors(string metricNamespace, string metricName)
    {
        List<AnomalyDetector> detectors = new List<AnomalyDetector>();
        var paginatedDescribeAnomalyDetectors = _amazonCloudWatch.Paginators.DescribeAnomalyDetectors(
            new DescribeAnomalyDetectorsRequest()
            {
                MetricName = metricName,
                Namespace = metricNamespace
            });

        await foreach (var data in paginatedDescribeAnomalyDetectors.AnomalyDetectors)
        {
            detectors.Add(data);
        }

        return detectors;
    }

    /// <summary>
    /// Delete a single metric anomaly detector.
    /// </summary>
    /// <param name="anomalyDetector">The anomaly detector to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector)
    {
        var deleteAnomalyDetectorResponse = await _amazonCloudWatch.DeleteAnomalyDetectorAsync(
            new DeleteAnomalyDetectorRequest()
            {
                SingleMetricAnomalyDetector = anomalyDetector
            });

        return deleteAnomalyDetectorResponse.HttpStatusCode == HttpStatusCode.OK;
    }

    /// <summary>
    /// Delete a list of CloudWatch dashboards.
    /// </summary>
    /// <param name="dashboardNames">List of dashboard names to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteDashboards(List<string> dashboardNames)
    {
        var deleteDashboardsResponse = await _amazonCloudWatch.DeleteDashboardsAsync(
            new DeleteDashboardsRequest()
            {
                DashboardNames = dashboardNames
            });

        return deleteDashboardsResponse.HttpStatusCode == HttpStatusCode.OK;
    }
}
```
シナリオの settings.json 値の例。  

```
{
  "dashboardName": "example-new-dashboard",
  "exampleAlarmName": "example-metric-alarm",
  "accountId": "1234567890",
  "region": "us-east-1",
  "emailTopic": "Default_CloudWatch_Alarms_Topic",
  "customMetricNamespace": "example-namespace",
  "customMetricName": "example-custom-metric",
  "dashboardExampleBody": {
    "widgets": [
      {
        "height": 6,
        "width": 6,
        "y": 0,
        "x": 0,
        "type": "text",
        "properties": {
          "markdown": "# Code Example Dashboard \nThis dashboard was created by example code.\n"
        }
      },
      {
        "height": 8,
        "width": 8,
        "y": 0,
        "x": 6,
        "type": "metric",
        "properties": {
          "metrics": [
            [
              "AWS/Billing",
              "EstimatedCharges",
              "Currency",
              "USD",
              { "region": "us-east-1" }
            ]
          ],
          "view": "timeSeries",
          "region": "us-east-1",
          "stat": "Maximum",
          "period": 86400,
          "yAxis": {
            "left": {
              "min": 0,
              "max": 100
            }
          },
          "stacked": false,
          "title": "Estimated Billing",
          "setPeriodToTimeRange": false,
          "liveData": true,
          "sparkline": true,
          "trend": true
        }
      },
      {
        "height": 8,
        "width": 8,
        "y": 0,
        "x": 14,
        "type": "metric",
        "properties": {
          "metrics": [
            [ "AWS/Usage", "CallCount", "Type", "API", "Resource", "ListMetrics", "Service", "CloudWatch", "Class", "None" ],
            [ "...", "GetMetricStatistics", ".", ".", ".", "." ],
            [ "...", "GetMetricData", ".", ".", ".", "." ],
            [ "...", "PutDashboard", ".", ".", ".", "." ],
            [ "...", "PutMetricData", ".", ".", ".", "." ]
          ],
          "view": "timeSeries",
          "yAxis": {
            "left": {
              "min": 0,
              "max": 200
            }
          },
          "stacked": false,
          "region": "us-east-1",
          "stat": "Sum",
          "period": 300,
          "title": "CloudWatch Usage",
          "setPeriodToTimeRange": false,
          "liveData": true,
          "sparkline": true,
          "trend": true
        }
      }
    ]
  }
}
```
+ API の詳細については、「AWS SDK for .NET API リファレンス**」の以下のトピックを参照してください。
  + [DeleteAlarms](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DeleteAlarms)
  + [DeleteAnomalyDetector](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DeleteAnomalyDetector)
  + [DeleteDashboards](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DeleteDashboards)
  + [DescribeAlarmHistory](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAlarmHistory)
  + [DescribeAlarms](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAlarms)
  + [DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAlarmsForMetric)
  + [DescribeAnomalyDetectors](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAnomalyDetectors)
  + [GetMetricData](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/GetMetricData)
  + [GetMetricStatistics](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/GetMetricStatistics)
  + [GetMetricWidgetImage](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/GetMetricWidgetImage)
  + [ListMetrics](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/ListMetrics)
  + [PutAnomalyDetector](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutAnomalyDetector)
  + [PutDashboard](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutDashboard)
  + [PutMetricAlarm](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutMetricAlarm)
  + [PutMetricData](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutMetricData)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_csharp_4_topic"></a>

次の例は、`DeleteAlarms` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a list of alarms from CloudWatch.
    /// </summary>
    /// <param name="alarmNames">A list of names of alarms to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteAlarms(List<string> alarmNames)
    {
        var deleteAlarmsResult = await _amazonCloudWatch.DeleteAlarmsAsync(
            new DeleteAlarmsRequest()
            {
                AlarmNames = alarmNames
            });

        return deleteAlarmsResult.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteAlarms](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DeleteAlarms)」を参照してください。

### `DeleteAnomalyDetector`
<a name="cloudwatch_DeleteAnomalyDetector_csharp_4_topic"></a>

次の例は、`DeleteAnomalyDetector` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a single metric anomaly detector.
    /// </summary>
    /// <param name="anomalyDetector">The anomaly detector to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector)
    {
        var deleteAnomalyDetectorResponse = await _amazonCloudWatch.DeleteAnomalyDetectorAsync(
            new DeleteAnomalyDetectorRequest()
            {
                SingleMetricAnomalyDetector = anomalyDetector
            });

        return deleteAnomalyDetectorResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteAnomalyDetector](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DeleteAnomalyDetector)」を参照してください。

### `DeleteDashboards`
<a name="cloudwatch_DeleteDashboards_csharp_4_topic"></a>

次の例は、`DeleteDashboards` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete a list of CloudWatch dashboards.
    /// </summary>
    /// <param name="dashboardNames">List of dashboard names to delete.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteDashboards(List<string> dashboardNames)
    {
        var deleteDashboardsResponse = await _amazonCloudWatch.DeleteDashboardsAsync(
            new DeleteDashboardsRequest()
            {
                DashboardNames = dashboardNames
            });

        return deleteDashboardsResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteDashboards](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DeleteDashboards)」を参照してください。

### `DescribeAlarmHistory`
<a name="cloudwatch_DescribeAlarmHistory_csharp_4_topic"></a>

次の例は、`DescribeAlarmHistory` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe the history of an alarm for a number of days in the past.
    /// </summary>
    /// <param name="alarmName">The name of the alarm.</param>
    /// <param name="historyDays">The number of days in the past.</param>
    /// <returns>The list of alarm history data.</returns>
    public async Task<List<AlarmHistoryItem>> DescribeAlarmHistory(string alarmName, int historyDays)
    {
        List<AlarmHistoryItem> alarmHistory = new List<AlarmHistoryItem>();
        var paginatedAlarmHistory = _amazonCloudWatch.Paginators.DescribeAlarmHistory(
            new DescribeAlarmHistoryRequest()
            {
                AlarmName = alarmName,
                EndDateUtc = DateTime.UtcNow,
                HistoryItemType = HistoryItemType.StateUpdate,
                StartDateUtc = DateTime.UtcNow.AddDays(-historyDays)
            });

        await foreach (var data in paginatedAlarmHistory.AlarmHistoryItems)
        {
            alarmHistory.Add(data);
        }
        return alarmHistory;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeAlarmHistory](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAlarmHistory)」を参照してください。

### `DescribeAlarms`
<a name="cloudwatch_DescribeAlarms_csharp_4_topic"></a>

次の例は、`DescribeAlarms` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe the current alarms, optionally filtered by state.
    /// </summary>
    /// <param name="stateValue">Optional filter for alarm state.</param>
    /// <returns>The list of alarm data.</returns>
    public async Task<List<MetricAlarm>> DescribeAlarms(StateValue? stateValue = null)
    {
        List<MetricAlarm> alarms = new List<MetricAlarm>();
        var paginatedDescribeAlarms = _amazonCloudWatch.Paginators.DescribeAlarms(
            new DescribeAlarmsRequest()
            {
                StateValue = stateValue
            });

        await foreach (var data in paginatedDescribeAlarms.MetricAlarms)
        {
            alarms.Add(data);
        }
        return alarms;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DescribeAlarms](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAlarms)」を参照してください。**

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_csharp_4_topic"></a>

次の例は、`DescribeAlarmsForMetric` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe the current alarms for a specific metric.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricName">The name of the metric.</param>
    /// <returns>The list of alarm data.</returns>
    public async Task<List<MetricAlarm>> DescribeAlarmsForMetric(string metricNamespace, string metricName)
    {
        var alarmsResult = await _amazonCloudWatch.DescribeAlarmsForMetricAsync(
            new DescribeAlarmsForMetricRequest()
            {
                Namespace = metricNamespace,
                MetricName = metricName
            });

        return alarmsResult.MetricAlarms ?? new List<MetricAlarm>();
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAlarmsForMetric)」を参照してください。

### `DescribeAnomalyDetectors`
<a name="cloudwatch_DescribeAnomalyDetectors_csharp_4_topic"></a>

次の例は、`DescribeAnomalyDetectors` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe anomaly detectors for a metric and namespace.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricName">The metric of the anomaly detectors.</param>
    /// <returns>The list of detectors.</returns>
    public async Task<List<AnomalyDetector>> DescribeAnomalyDetectors(string metricNamespace, string metricName)
    {
        List<AnomalyDetector> detectors = new List<AnomalyDetector>();
        var paginatedDescribeAnomalyDetectors = _amazonCloudWatch.Paginators.DescribeAnomalyDetectors(
            new DescribeAnomalyDetectorsRequest()
            {
                MetricName = metricName,
                Namespace = metricNamespace
            });

        await foreach (var data in paginatedDescribeAnomalyDetectors.AnomalyDetectors)
        {
            detectors.Add(data);
        }

        return detectors;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeAnomalyDetectors](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DescribeAnomalyDetectors)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_csharp_4_topic"></a>

次の例は、`DisableAlarmActions` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Disable the actions for a list of alarms from CloudWatch.
    /// </summary>
    /// <param name="alarmNames">A list of names of alarms.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DisableAlarmActions(List<string> alarmNames)
    {
        var disableAlarmActionsResult = await _amazonCloudWatch.DisableAlarmActionsAsync(
            new DisableAlarmActionsRequest()
            {
                AlarmNames = alarmNames
            });

        return disableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API 詳細については、**AWS SDK for .NET API リファレンスの「[DisableAlarmActions](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/DisableAlarmActions)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_csharp_4_topic"></a>

次の例は、`EnableAlarmActions` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Enable the actions for a list of alarms from CloudWatch.
    /// </summary>
    /// <param name="alarmNames">A list of names of alarms.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> EnableAlarmActions(List<string> alarmNames)
    {
        var enableAlarmActionsResult = await _amazonCloudWatch.EnableAlarmActionsAsync(
            new EnableAlarmActionsRequest()
            {
                AlarmNames = alarmNames
            });

        return enableAlarmActionsResult.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[EnableAlarmActions](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/EnableAlarmActions)」を参照してください。

### `GetDashboard`
<a name="cloudwatch_GetDashboard_csharp_4_topic"></a>

次の例は、`GetDashboard` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get information on a dashboard.
    /// </summary>
    /// <param name="dashboardName">The name of the dashboard.</param>
    /// <returns>A JSON object with dashboard information.</returns>
    public async Task<string> GetDashboard(string dashboardName)
    {
        var dashboardResponse = await _amazonCloudWatch.GetDashboardAsync(
            new GetDashboardRequest()
            {
                DashboardName = dashboardName
            });

        return dashboardResponse.DashboardBody;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetDashboard](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/GetDashboard)」を参照してください。

### `GetMetricData`
<a name="cloudwatch_GetMetricData_csharp_4_topic"></a>

次の例は、`GetMetricData` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get data for CloudWatch metrics.
    /// </summary>
    /// <param name="minutesOfData">The number of minutes of data to include.</param>
    /// <param name="useDescendingTime">True to return the data descending by time.</param>
    /// <param name="endDateUtc">The end date for the data, in UTC.</param>
    /// <param name="maxDataPoints">The maximum data points to include.</param>
    /// <param name="dataQueries">Optional data queries to include.</param>
    /// <returns>A list of the requested metric data.</returns>
    public async Task<List<MetricDataResult>> GetMetricData(int minutesOfData, bool useDescendingTime, DateTime? endDateUtc = null,
        int maxDataPoints = 0, List<MetricDataQuery>? dataQueries = null)
    {
        var metricData = new List<MetricDataResult>();
        // If no end time is provided, use the current time for the end time.
        endDateUtc ??= DateTime.UtcNow;
        var timeZoneOffset = TimeZoneInfo.Local.GetUtcOffset(endDateUtc.Value.ToLocalTime());
        var startTimeUtc = endDateUtc.Value.AddMinutes(-minutesOfData);
        // The timezone string should be in the format +0000, so use the timezone offset to format it correctly.
        var timeZoneString = $"{timeZoneOffset.Hours:D2}{timeZoneOffset.Minutes:D2}";
        // Add the plus sign for positive offsets.
        timeZoneString = timeZoneString.StartsWith('-') ? timeZoneString : "+" + timeZoneString;
        var paginatedMetricData = _amazonCloudWatch.Paginators.GetMetricData(
            new GetMetricDataRequest()
            {
                StartTimeUtc = startTimeUtc,
                EndTimeUtc = endDateUtc.Value,
                LabelOptions = new LabelOptions { Timezone = timeZoneString },
                ScanBy = useDescendingTime ? ScanBy.TimestampDescending : ScanBy.TimestampAscending,
                MaxDatapoints = maxDataPoints,
                MetricDataQueries = dataQueries,
            });

        if (paginatedMetricData.MetricDataResults != null)
        {
            await foreach (var data in paginatedMetricData.MetricDataResults)
            {
                metricData.Add(data);
            }
        }

        return metricData;
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetMetricData](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/GetMetricData)」を参照してください。

### `GetMetricStatistics`
<a name="cloudwatch_GetMetricStatistics_csharp_4_topic"></a>

次の例は、`GetMetricStatistics` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get billing statistics using a call to a wrapper class.
    /// </summary>
    /// <returns>A collection of billing statistics.</returns>
    private static async Task<List<Datapoint>> SetupBillingStatistics()
    {
        // Make a request for EstimatedCharges with a period of one day for the past seven days.
        var billingStatistics = await _cloudWatchWrapper.GetMetricStatistics(
            "AWS/Billing",
            "EstimatedCharges",
            new List<string>() { "Maximum" },
            new List<Dimension>() { new Dimension { Name = "Currency", Value = "USD" } },
            7,
            86400);

        billingStatistics = billingStatistics.OrderBy(n => n.Timestamp).ToList();

        return billingStatistics;
    }

    /// <summary>
    /// Wrapper to get statistics for a specific CloudWatch metric.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricName">The name of the metric.</param>
    /// <param name="statistics">The list of statistics to include.</param>
    /// <param name="dimensions">The list of dimensions to include.</param>
    /// <param name="days">The number of days in the past to include.</param>
    /// <param name="period">The period for the data.</param>
    /// <returns>A list of DataPoint objects for the statistics.</returns>
    public async Task<List<Datapoint>> GetMetricStatistics(string metricNamespace,
        string metricName, List<string> statistics, List<Dimension> dimensions, int days, int period)
    {
        var metricStatistics = await _amazonCloudWatch.GetMetricStatisticsAsync(
            new GetMetricStatisticsRequest()
            {
                Namespace = metricNamespace,
                MetricName = metricName,
                Dimensions = dimensions,
                Statistics = statistics,
                StartTimeUtc = DateTime.UtcNow.AddDays(-days),
                EndTimeUtc = DateTime.UtcNow,
                Period = period
            });

        return metricStatistics.Datapoints ?? new List<Datapoint>();
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetMetricStatistics](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/GetMetricStatistics)」を参照してください。

### `GetMetricWidgetImage`
<a name="cloudwatch_GetMetricWidgetImage_csharp_4_topic"></a>

次の例は、`GetMetricWidgetImage` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get an image for a metric graphed over time.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metric">The name of the metric.</param>
    /// <param name="stat">The name of the stat to chart.</param>
    /// <param name="period">The period to use for the chart.</param>
    /// <returns>A memory stream for the chart image.</returns>
    public async Task<MemoryStream> GetTimeSeriesMetricImage(string metricNamespace, string metric, string stat, int period)
    {
        var metricImageWidget = new
        {
            title = "Example Metric Graph",
            view = "timeSeries",
            stacked = false,
            period = period,
            width = 1400,
            height = 600,
            metrics = new List<List<object>>
                { new() { metricNamespace, metric, new { stat } } }
        };

        var metricImageWidgetString = JsonSerializer.Serialize(metricImageWidget);
        var imageResponse = await _amazonCloudWatch.GetMetricWidgetImageAsync(
            new GetMetricWidgetImageRequest()
            {
                MetricWidget = metricImageWidgetString
            });

        return imageResponse.MetricWidgetImage;
    }

    /// <summary>
    /// Save a metric image to a file.
    /// </summary>
    /// <param name="memoryStream">The MemoryStream for the metric image.</param>
    /// <param name="metricName">The name of the metric.</param>
    /// <returns>The path to the file.</returns>
    public string SaveMetricImage(MemoryStream memoryStream, string metricName)
    {
        var metricFileName = $"{metricName}_{DateTime.Now.Ticks}.png";
        using var sr = new StreamReader(memoryStream);
        // Writes the memory stream to a file.
        File.WriteAllBytes(metricFileName, memoryStream.ToArray());
        var filePath = Path.Join(AppDomain.CurrentDomain.BaseDirectory,
            metricFileName);
        return filePath;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetMetricWidgetImage](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/GetMetricWidgetImage)」を参照してください。

### `ListDashboards`
<a name="cloudwatch_ListDashboards_csharp_4_topic"></a>

次の例は、`ListDashboards` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get a list of dashboards.
    /// </summary>
    /// <returns>A list of DashboardEntry objects.</returns>
    public async Task<List<DashboardEntry>> ListDashboards()
    {
        var results = new List<DashboardEntry>();
        var paginateDashboards = _amazonCloudWatch.Paginators.ListDashboards(
            new ListDashboardsRequest());
        // Get the entire list using the paginator.
        await foreach (var data in paginateDashboards.DashboardEntries)
        {
            results.Add(data);
        }

        return results;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ListDashboards](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/ListDashboards)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_csharp_4_topic"></a>

次の例は、`ListMetrics` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List metrics available, optionally within a namespace.
    /// </summary>
    /// <param name="metricNamespace">Optional CloudWatch namespace to use when listing metrics.</param>
    /// <param name="filter">Optional dimension filter.</param>
    /// <param name="metricName">Optional metric name filter.</param>
    /// <returns>The list of metrics.</returns>
    public async Task<List<Metric>> ListMetrics(string? metricNamespace = null, DimensionFilter? filter = null, string? metricName = null)
    {
        var results = new List<Metric>();
        var paginateMetrics = _amazonCloudWatch.Paginators.ListMetrics(
            new ListMetricsRequest
            {
                Namespace = metricNamespace,
                Dimensions = filter != null ? new List<DimensionFilter> { filter } : null,
                MetricName = metricName
            });
        // Get the entire list using the paginator.
        await foreach (var metric in paginateMetrics.Metrics)
        {
            results.Add(metric);
        }

        return results;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[ListMetrics](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/ListMetrics)」を参照してください。

### `PutAnomalyDetector`
<a name="cloudwatch_PutAnomalyDetector_csharp_4_topic"></a>

次の例は、`PutAnomalyDetector` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Add an anomaly detector for a single metric.
    /// </summary>
    /// <param name="anomalyDetector">A single metric anomaly detector.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutAnomalyDetector(SingleMetricAnomalyDetector anomalyDetector)
    {
        var putAlarmDetectorResult = await _amazonCloudWatch.PutAnomalyDetectorAsync(
            new PutAnomalyDetectorRequest()
            {
                SingleMetricAnomalyDetector = anomalyDetector
            });

        return putAlarmDetectorResult.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutAnomalyDetector](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutAnomalyDetector)」を参照してください。

### `PutDashboard`
<a name="cloudwatch_PutDashboard_csharp_4_topic"></a>

次の例は、`PutDashboard` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Set up a dashboard using a call to the wrapper class.
    /// </summary>
    /// <param name="customMetricNamespace">The metric namespace.</param>
    /// <param name="customMetricName">The metric name.</param>
    /// <param name="dashboardName">The name of the dashboard.</param>
    /// <returns>A list of validation messages.</returns>
    private static async Task<List<DashboardValidationMessage>> SetupDashboard(
        string customMetricNamespace, string customMetricName, string dashboardName)
    {
        // Get the dashboard model from configuration.
        var newDashboard = new DashboardModel();
        _configuration.GetSection("dashboardExampleBody").Bind(newDashboard);

        // Add a new metric to the dashboard.
        newDashboard.Widgets.Add(new Widget
        {
            Height = 8,
            Width = 8,
            Y = 8,
            X = 0,
            Type = "metric",
            Properties = new Properties
            {
                Metrics = new List<List<object>>
                    { new() { customMetricNamespace, customMetricName } },
                View = "timeSeries",
                Region = "us-east-1",
                Stat = "Sum",
                Period = 86400,
                YAxis = new YAxis { Left = new Left { Min = 0, Max = 100 } },
                Title = "Custom Metric Widget",
                LiveData = true,
                Sparkline = true,
                Trend = true,
                Stacked = false,
                SetPeriodToTimeRange = false
            }
        });

        var newDashboardString = JsonSerializer.Serialize(newDashboard,
            new JsonSerializerOptions
            { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
        var validationMessages =
            await _cloudWatchWrapper.PutDashboard(dashboardName, newDashboardString);

        return validationMessages;
    }

    /// <summary>
    /// Wrapper to create or add to a dashboard with metrics.
    /// </summary>
    /// <param name="dashboardName">The name for the dashboard.</param>
    /// <param name="dashboardBody">The metric data in JSON for the dashboard.</param>
    /// <returns>A list of validation messages for the dashboard.</returns>
    public async Task<List<DashboardValidationMessage>> PutDashboard(string dashboardName,
        string dashboardBody)
    {
        // Updating a dashboard replaces all contents.
        // Best practice is to include a text widget indicating this dashboard was created programmatically.
        var dashboardResponse = await _amazonCloudWatch.PutDashboardAsync(
            new PutDashboardRequest()
            {
                DashboardName = dashboardName,
                DashboardBody = dashboardBody
            });

        return dashboardResponse.DashboardValidationMessages ?? new List<DashboardValidationMessage>();
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[PutDashboard](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutDashboard)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_csharp_4_topic"></a>

次の例は、`PutMetricAlarm` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Add a metric alarm to send an email when the metric passes a threshold.
    /// </summary>
    /// <param name="alarmDescription">A description of the alarm.</param>
    /// <param name="alarmName">The name for the alarm.</param>
    /// <param name="comparison">The type of comparison to use.</param>
    /// <param name="metricName">The name of the metric for the alarm.</param>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="threshold">The threshold value for the alarm.</param>
    /// <param name="alarmActions">Optional actions to execute when in an alarm state.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutMetricEmailAlarm(string alarmDescription, string alarmName, ComparisonOperator comparison,
        string metricName, string metricNamespace, double threshold, List<string> alarmActions = null!)
    {
        try
        {
            var putEmailAlarmResponse = await _amazonCloudWatch.PutMetricAlarmAsync(
                new PutMetricAlarmRequest()
                {
                    AlarmActions = alarmActions,
                    AlarmDescription = alarmDescription,
                    AlarmName = alarmName,
                    ComparisonOperator = comparison,
                    Threshold = threshold,
                    Namespace = metricNamespace,
                    MetricName = metricName,
                    EvaluationPeriods = 1,
                    Period = 10,
                    Statistic = new Statistic("Maximum"),
                    DatapointsToAlarm = 1,
                    TreatMissingData = "ignore"
                });
            return putEmailAlarmResponse.HttpStatusCode == HttpStatusCode.OK;
        }
        catch (LimitExceededException lex)
        {
            _logger.LogError(lex, $"Unable to add alarm {alarmName}. Alarm quota has already been reached.");
        }

        return false;
    }

    /// <summary>
    /// Add specific email actions to a list of action strings for a CloudWatch alarm.
    /// </summary>
    /// <param name="accountId">The AccountId for the alarm.</param>
    /// <param name="region">The region for the alarm.</param>
    /// <param name="emailTopicName">An Amazon Simple Notification Service (SNS) topic for the alarm email.</param>
    /// <param name="alarmActions">Optional list of existing alarm actions to append to.</param>
    /// <returns>A list of string actions for an alarm.</returns>
    public List<string> AddEmailAlarmAction(string accountId, string region,
        string emailTopicName, List<string>? alarmActions = null)
    {
        alarmActions ??= new List<string>();
        var snsAlarmAction = $"arn:aws:sns:{region}:{accountId}:{emailTopicName}";
        alarmActions.Add(snsAlarmAction);
        return alarmActions;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[PutMetricAlarm](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutMetricAlarm)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_csharp_4_topic"></a>

次の例は、`PutMetricData` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatch#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Add some metric data using a call to a wrapper class.
    /// </summary>
    /// <param name="customMetricName">The metric name.</param>
    /// <param name="customMetricNamespace">The metric namespace.</param>
    /// <returns></returns>
    private static async Task<List<MetricDatum>> PutRandomMetricData(string customMetricName,
        string customMetricNamespace)
    {
        List<MetricDatum> customData = new List<MetricDatum>();
        Random rnd = new Random();

        // Add 10 random values up to 100, starting with a timestamp 15 minutes in the past.
        var utcNowMinus15 = DateTime.UtcNow.AddMinutes(-15);
        for (int i = 0; i < 10; i++)
        {
            var metricValue = rnd.Next(0, 100);
            customData.Add(
                new MetricDatum
                {
                    MetricName = customMetricName,
                    Value = metricValue,
                    TimestampUtc = utcNowMinus15.AddMinutes(i)
                }
            );
        }

        await _cloudWatchWrapper.PutMetricData(customMetricNamespace, customData);
        return customData;
    }

    /// <summary>
    /// Wrapper to add metric data to a CloudWatch metric.
    /// </summary>
    /// <param name="metricNamespace">The namespace of the metric.</param>
    /// <param name="metricData">A data object for the metric data.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> PutMetricData(string metricNamespace,
        List<MetricDatum> metricData)
    {
        var putDataResponse = await _amazonCloudWatch.PutMetricDataAsync(
            new PutMetricDataRequest()
            {
                MetricData = metricData,
                Namespace = metricNamespace,
            });

        return putDataResponse.HttpStatusCode == HttpStatusCode.OK;
    }
```
+  API の詳細については、**AWS SDK for .NET API リファレンスの「[PutMetricData](https://docs.aws.amazon.com/goto/DotNetSDKV4/monitoring-2010-08-01/PutMetricData)」を参照してください。

# SDK for .NET (v4) を使用した CloudWatch Logs の例
<a name="csharp_4_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `GetQueryResults`
<a name="cloudwatch-logs_GetQueryResults_csharp_4_topic"></a>

次の例は、`GetQueryResults` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatchLogs/LargeQuery#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Gets the results of a CloudWatch Logs Insights query.
    /// </summary>
    /// <param name="queryId">The ID of the query.</param>
    /// <returns>The query results response.</returns>
    public async Task<GetQueryResultsResponse?> GetQueryResultsAsync(string queryId)
    {
        try
        {
            var request = new GetQueryResultsRequest
            {
                QueryId = queryId
            };

            var response = await _amazonCloudWatchLogs.GetQueryResultsAsync(request);
            return response;
        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError($"Query not found: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while getting query results: {ex.Message}");
            return null;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[GetQueryResults](https://docs.aws.amazon.com/goto/DotNetSDKV4/logs-2014-03-28/GetQueryResults)」を参照してください。

### `StartQuery`
<a name="cloudwatch-logs_StartQuery_csharp_4_topic"></a>

次の例は、`StartQuery` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatchLogs/LargeQuery#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Starts a CloudWatch Logs Insights query.
    /// </summary>
    /// <param name="logGroupName">The name of the log group to query.</param>
    /// <param name="queryString">The CloudWatch Logs Insights query string.</param>
    /// <param name="startTime">The start time for the query (seconds since epoch).</param>
    /// <param name="endTime">The end time for the query (seconds since epoch).</param>
    /// <param name="limit">The maximum number of results to return.</param>
    /// <returns>The query ID if successful, null otherwise.</returns>
    public async Task<string?> StartQueryAsync(
        string logGroupName,
        string queryString,
        long startTime,
        long endTime,
        int limit = 10000)
    {
        try
        {
            var request = new StartQueryRequest
            {
                LogGroupName = logGroupName,
                QueryString = queryString,
                StartTime = startTime,
                EndTime = endTime,
                Limit = limit
            };

            var response = await _amazonCloudWatchLogs.StartQueryAsync(request);
            return response.QueryId;
        }
        catch (InvalidParameterException ex)
        {
            _logger.LogError($"Invalid parameter for query: {ex.Message}");
            return null;
        }
        catch (ResourceNotFoundException ex)
        {
            _logger.LogError($"Log group not found: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"An error occurred while starting query: {ex.Message}");
            return null;
        }
    }
```
+  API の詳細については、「**AWS SDK for .NET API リファレンス」の「[StartQuery](https://docs.aws.amazon.com/goto/DotNetSDKV4/logs-2014-03-28/StartQuery)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 大規模なクエリを実行する
<a name="cloudwatch-logs_Scenario_BigQuery_csharp_4_topic"></a>

次のコード例は、CloudWatch Logs を使用して 10,000 を超えるレコードをクエリする方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/CloudWatchLogs/LargeQuery#code-examples)での設定と実行の方法を確認してください。
これは、大規模なクエリシナリオを示すメインワークフローです。  

```
using System.Diagnostics;
using System.Text.RegularExpressions;
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.CloudWatchLogs;
using Amazon.CloudWatchLogs.Model;
using CloudWatchLogsActions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace CloudWatchLogsScenario;

public class LargeQueryWorkflow
{
    /*
    Before running this .NET code example, set up your development environment, including your credentials.
    This .NET code example performs the following tasks for the CloudWatch Logs Large Query workflow:

    1. Prepare the Application:
       - Prompt the user to deploy CloudFormation stack and generate sample logs.
       - Deploy the CloudFormation template for resource creation.
       - Generate 50,000 sample log entries using CloudWatch Logs API.
       - Wait 5 minutes for logs to be fully ingested.

    2. Execute Large Query:
       - Perform recursive queries to retrieve all logs using binary search.
       - Display progress for each query executed.
       - Show total execution time and logs found.

    3. Clean up:
       - Prompt the user to delete the CloudFormation stack and all resources.
       - Destroy the CloudFormation stack and wait until removed.
    */

    public static ILogger<LargeQueryWorkflow> _logger = null!;
    public static CloudWatchLogsWrapper _wrapper = null!;
    public static IAmazonCloudFormation _amazonCloudFormation = null!;

    private static string _logGroupName = "/workflows/cloudwatch-logs/large-query";
    private static string _logStreamName = "stream1";
    private static long _queryStartDate;
    private static long _queryEndDate;

    public static bool _interactive = true;
    public static string _stackName = "CloudWatchLargeQueryStack";
    private static string _stackResourcePath = "../../../../../../../scenarios/features/cloudwatch_logs_large_query/resources/stack.yaml";

    public static async Task Main(string[] args)
    {
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter("Microsoft", LogLevel.Information))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonCloudWatchLogs>()
                    .AddAWSService<IAmazonCloudFormation>()
                    .AddTransient<CloudWatchLogsWrapper>()
            )
            .Build();

        if (_interactive)
        {
            _logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
                .CreateLogger<LargeQueryWorkflow>();

            _wrapper = host.Services.GetRequiredService<CloudWatchLogsWrapper>();
            _amazonCloudFormation = host.Services.GetRequiredService<IAmazonCloudFormation>();
        }

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the CloudWatch Logs Large Query Scenario.");
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("This scenario demonstrates how to perform large-scale queries on");
        Console.WriteLine("CloudWatch Logs using recursive binary search to retrieve more than");
        Console.WriteLine("the 10,000 result limit.");
        Console.WriteLine();

        try
        {
            Console.WriteLine(new string('-', 80));
            var prepareSuccess = await PrepareApplication();
            Console.WriteLine(new string('-', 80));

            if (prepareSuccess)
            {
                Console.WriteLine(new string('-', 80));
                await ExecuteLargeQuery();
                Console.WriteLine(new string('-', 80));
            }

            Console.WriteLine(new string('-', 80));
            await Cleanup();
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "There was a problem with the scenario, initiating cleanup...");
            _interactive = false;
            await Cleanup();
        }

        Console.WriteLine("CloudWatch Logs Large Query scenario completed.");
    }

    /// <summary>
    /// Runs the scenario workflow. Used for testing.
    /// </summary>
    public static async Task RunScenario()
    {
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the CloudWatch Logs Large Query Scenario.");
        Console.WriteLine(new string('-', 80));
        Console.WriteLine("This scenario demonstrates how to perform large-scale queries on");
        Console.WriteLine("CloudWatch Logs using recursive binary search to retrieve more than");
        Console.WriteLine("the 10,000 result limit.");
        Console.WriteLine();

        try
        {
            Console.WriteLine(new string('-', 80));
            var prepareSuccess = await PrepareApplication();
            Console.WriteLine(new string('-', 80));

            if (prepareSuccess)
            {
                Console.WriteLine(new string('-', 80));
                await ExecuteLargeQuery();
                Console.WriteLine(new string('-', 80));
            }

            Console.WriteLine(new string('-', 80));
            await Cleanup();
            Console.WriteLine(new string('-', 80));
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "There was a problem with the scenario, initiating cleanup...");
            _interactive = false;
            await Cleanup();
        }

        Console.WriteLine("CloudWatch Logs Large Query scenario completed.");
    }

    /// <summary>
    /// Prepares the application by creating the necessary resources.
    /// </summary>
    /// <returns>True if the application was prepared successfully.</returns>
    public static async Task<bool> PrepareApplication()
    {
        Console.WriteLine("Preparing the application...");
        Console.WriteLine();

        try
        {
            var deployStack = !_interactive || GetYesNoResponse(
                "Would you like to deploy the CloudFormation stack and generate sample logs? (y/n) ");

            if (deployStack)
            {
                if (_interactive)
                {
                    Console.Write(
                        $"Enter a path for the CloudFormation stack resource .yaml file (or press Enter for default '{_stackResourcePath}'): ");
                    string? inputPath = Console.ReadLine();
                    if (!string.IsNullOrWhiteSpace(inputPath))
                    {
                        _stackResourcePath = inputPath;
                    }
                }

                _stackName = PromptUserForStackName();

                var deploySuccess = await DeployCloudFormationStack(_stackName);

                if (deploySuccess)
                {
                    Console.WriteLine();
                    Console.WriteLine("Generating 50,000 sample log entries...");
                    var generateSuccess = await GenerateSampleLogs();

                    if (generateSuccess)
                    {
                        Console.WriteLine();
                        Console.WriteLine("Sample logs created. Waiting 5 minutes for logs to be fully ingested...");
                        await WaitWithCountdown(300);

                        Console.WriteLine("Application preparation complete.");
                        return true;
                    }
                }
            }
            else
            {
                _logGroupName = PromptUserForInput("Enter the log group name ", _logGroupName);
                _logStreamName = PromptUserForInput("Enter the log stream name ", _logStreamName);

                var startDateMs = PromptUserForLong("Enter the query start date (milliseconds since epoch): ");
                var endDateMs = PromptUserForLong("Enter the query end date (milliseconds since epoch): ");

                _queryStartDate = startDateMs / 1000;
                _queryEndDate = endDateMs / 1000;

                Console.WriteLine("Application preparation complete.");
                return true;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while preparing the application.");
        }

        Console.WriteLine("Application preparation failed.");
        return false;
    }

    /// <summary>
    /// Deploys the CloudFormation stack with the necessary resources.
    /// </summary>
    /// <param name="stackName">The name of the CloudFormation stack.</param>
    /// <returns>True if the stack was deployed successfully.</returns>
    private static async Task<bool> DeployCloudFormationStack(string stackName)
    {
        Console.WriteLine($"\nDeploying CloudFormation stack: {stackName}");

        try
        {
            var request = new CreateStackRequest
            {
                StackName = stackName,
                TemplateBody = await File.ReadAllTextAsync(_stackResourcePath)
            };

            var response = await _amazonCloudFormation.CreateStackAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"CloudFormation stack creation started: {stackName}");

                bool stackCreated = await WaitForStackCompletion(response.StackId);

                if (stackCreated)
                {
                    Console.WriteLine("CloudFormation stack created successfully.");
                    return true;
                }
                else
                {
                    _logger.LogError($"CloudFormation stack creation failed: {stackName}");
                    return false;
                }
            }
            else
            {
                _logger.LogError($"Failed to create CloudFormation stack: {stackName}");
                return false;
            }
        }
        catch (AlreadyExistsException)
        {
            _logger.LogWarning($"CloudFormation stack '{stackName}' already exists. Please provide a unique name.");
            var newStackName = PromptUserForStackName();
            return await DeployCloudFormationStack(newStackName);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"An error occurred while deploying the CloudFormation stack: {stackName}");
            return false;
        }
    }

    /// <summary>
    /// Waits for the CloudFormation stack to be in the CREATE_COMPLETE state.
    /// </summary>
    /// <param name="stackId">The ID of the CloudFormation stack.</param>
    /// <returns>True if the stack was created successfully.</returns>
    private static async Task<bool> WaitForStackCompletion(string stackId)
    {
        int retryCount = 0;
        const int maxRetries = 30;
        const int retryDelay = 10000;

        while (retryCount < maxRetries)
        {
            var describeStacksRequest = new DescribeStacksRequest
            {
                StackName = stackId
            };

            var describeStacksResponse = await _amazonCloudFormation.DescribeStacksAsync(describeStacksRequest);

            if (describeStacksResponse.Stacks.Count > 0)
            {
                if (describeStacksResponse.Stacks[0].StackStatus == StackStatus.CREATE_COMPLETE)
                {
                    return true;
                }
                if (describeStacksResponse.Stacks[0].StackStatus == StackStatus.CREATE_FAILED ||
                    describeStacksResponse.Stacks[0].StackStatus == StackStatus.ROLLBACK_COMPLETE)
                {
                    return false;
                }
            }

            Console.WriteLine("Waiting for CloudFormation stack creation to complete...");
            await Task.Delay(retryDelay);
            retryCount++;
        }

        _logger.LogError("Timed out waiting for CloudFormation stack creation to complete.");
        return false;
    }

    /// <summary>
    /// Generates sample logs directly using CloudWatch Logs API.
    /// Creates 50,000 log entries spanning 5 minutes.
    /// </summary>
    /// <returns>True if logs were generated successfully.</returns>
    private static async Task<bool> GenerateSampleLogs()
    {
        const int totalEntries = 50000;
        const int entriesPerBatch = 10000;
        const int fiveMinutesMs = 5 * 60 * 1000;

        try
        {
            // Calculate timestamps
            var startTimeMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            var timestampIncrement = fiveMinutesMs / totalEntries;

            Console.WriteLine($"Generating {totalEntries} log entries...");

            var entryCount = 0;
            var currentTimestamp = startTimeMs;
            var numBatches = totalEntries / entriesPerBatch;

            // Generate and upload logs in batches
            for (int batchNum = 0; batchNum < numBatches; batchNum++)
            {
                var logEvents = new List<InputLogEvent>();

                for (int i = 0; i < entriesPerBatch; i++)
                {
                    logEvents.Add(new InputLogEvent
                    {
                        Timestamp = DateTimeOffset.FromUnixTimeMilliseconds(currentTimestamp).UtcDateTime,
                        Message = $"Entry {entryCount}"
                    });

                    entryCount++;
                    currentTimestamp += timestampIncrement;
                }

                // Upload batch
                var success = await _wrapper.PutLogEventsAsync(_logGroupName, _logStreamName, logEvents);
                if (!success)
                {
                    _logger.LogError($"Failed to upload batch {batchNum + 1}/{numBatches}");
                    return false;
                }

                Console.WriteLine($"Uploaded batch {batchNum + 1}/{numBatches}");
            }

            // Set query date range (convert milliseconds to seconds for query API)
            _queryStartDate = startTimeMs / 1000;
            _queryEndDate = (currentTimestamp - timestampIncrement) / 1000;

            Console.WriteLine($"Query start date: {DateTimeOffset.FromUnixTimeSeconds(_queryStartDate):yyyy-MM-ddTHH:mm:ss.fffZ}");
            Console.WriteLine($"Query end date: {DateTimeOffset.FromUnixTimeSeconds(_queryEndDate):yyyy-MM-ddTHH:mm:ss.fffZ}");
            Console.WriteLine($"Successfully uploaded {totalEntries} log entries");

            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred while generating sample logs.");
            return false;
        }
    }

    /// <summary>
    /// Executes the large query workflow.
    /// </summary>
    public static async Task ExecuteLargeQuery()
    {
        Console.WriteLine("Starting recursive query to retrieve all logs...");
        Console.WriteLine();

        var queryLimit = PromptUserForInteger("Enter the query limit (max 10000) ", 10000);
        if (queryLimit > 10000) queryLimit = 10000;

        var queryString = "fields @timestamp, @message | sort @timestamp asc";

        var stopwatch = Stopwatch.StartNew();
        var allResults = await PerformLargeQuery(_logGroupName, queryString, _queryStartDate, _queryEndDate, queryLimit);
        stopwatch.Stop();

        Console.WriteLine();
        Console.WriteLine($"Queries finished in {stopwatch.Elapsed.TotalSeconds:F3} seconds.");
        Console.WriteLine($"Total logs found: {allResults.Count}");

        // Check for duplicates
        Console.WriteLine();
        Console.WriteLine("Checking for duplicate logs...");
        var duplicates = FindDuplicateLogs(allResults);
        if (duplicates.Count > 0)
        {
            Console.WriteLine($"WARNING: Found {duplicates.Count} duplicate log entries!");
            Console.WriteLine("Duplicate entries (showing first 10):");
            foreach (var dup in duplicates.Take(10))
            {
                Console.WriteLine($"  [{dup.Timestamp}] {dup.Message} (appears {dup.Count} times)");
            }

            var uniqueCount = allResults.Count - duplicates.Sum(d => d.Count - 1);
            Console.WriteLine($"Unique logs: {uniqueCount}");
        }
        else
        {
            Console.WriteLine("No duplicates found. All logs are unique.");
        }
        Console.WriteLine();

        var viewSample = !_interactive || GetYesNoResponse("Would you like to see a sample of the logs? (y/n) ");
        if (viewSample)
        {
            Console.WriteLine();
            Console.WriteLine($"Sample logs (first 10 of {allResults.Count}):");
            for (int i = 0; i < Math.Min(10, allResults.Count); i++)
            {
                var timestamp = allResults[i].Find(f => f.Field == "@timestamp")?.Value ?? "N/A";
                var message = allResults[i].Find(f => f.Field == "@message")?.Value ?? "N/A";
                Console.WriteLine($"[{timestamp}] {message}");
            }
        }
    }

    /// <summary>
    /// Performs a large query using recursive binary search.
    /// </summary>
    private static async Task<List<List<ResultField>>> PerformLargeQuery(
        string logGroupName,
        string queryString,
        long startTime,
        long endTime,
        int limit)
    {
        var queryId = await _wrapper.StartQueryAsync(logGroupName, queryString, startTime, endTime, limit);
        if (queryId == null)
        {
            return new List<List<ResultField>>();
        }

        var results = await PollQueryResults(queryId);
        if (results == null || results.Count == 0)
        {
            return new List<List<ResultField>>();
        }

        var startDate = DateTimeOffset.FromUnixTimeSeconds(startTime).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
        var endDate = DateTimeOffset.FromUnixTimeSeconds(endTime).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
        Console.WriteLine($"Query date range: {startDate} ({startTime}s) to {endDate} ({endTime}s). Found {results.Count} logs.");

        if (results.Count < limit)
        {
            Console.WriteLine($"  -> Returning {results.Count} logs (less than limit of {limit})");
            return results;
        }

        Console.WriteLine($"  -> Hit limit of {limit}. Need to split and recurse.");

        // Get the timestamp of the last log (sorted to find the actual last one)
        var lastLogTimestamp = GetLastLogTimestamp(results);
        if (lastLogTimestamp == null)
        {
            Console.WriteLine($"  -> No timestamp found in results. Returning {results.Count} logs.");
            return results;
        }

        Console.WriteLine($"  -> Last log timestamp: {lastLogTimestamp}");

        // Parse the timestamp and add 1 millisecond to avoid querying the same log again
        var lastLogDate = DateTimeOffset.Parse(lastLogTimestamp + " +0000");
        Console.WriteLine($"  -> Last log as DateTimeOffset: {lastLogDate:yyyy-MM-ddTHH:mm:ss.fffZ} ({lastLogDate.ToUnixTimeSeconds()}s)");

        var offsetLastLogDate = lastLogDate.AddMilliseconds(1);
        Console.WriteLine($"  -> Offset timestamp (last + 1ms): {offsetLastLogDate:yyyy-MM-ddTHH:mm:ss.fffZ} ({offsetLastLogDate.ToUnixTimeSeconds()}s)");

        // Convert to seconds, but round UP to the next second to avoid overlapping with logs in the same second
        // This ensures we don't re-query logs that share the same second as the last log
        var offsetLastLogTime = offsetLastLogDate.ToUnixTimeSeconds();
        if (offsetLastLogDate.Millisecond > 0)
        {
            offsetLastLogTime++; // Move to the next full second
            Console.WriteLine($"  -> Adjusted to next full second: {offsetLastLogTime}s ({DateTimeOffset.FromUnixTimeSeconds(offsetLastLogTime):yyyy-MM-ddTHH:mm:ss.fffZ})");
        }

        Console.WriteLine($"  -> Comparing: offsetLastLogTime={offsetLastLogTime}s vs endTime={endTime}s");
        Console.WriteLine($"  -> End time as date: {DateTimeOffset.FromUnixTimeSeconds(endTime):yyyy-MM-ddTHH:mm:ss.fffZ}");

        // Check if there's any time range left to query
        if (offsetLastLogTime >= endTime)
        {
            Console.WriteLine($"  -> No time range left to query. Offset time ({offsetLastLogTime}s) >= end time ({endTime}s)");
            return results;
        }

        // Split the remaining date range in half
        var (range1Start, range1End, range2Start, range2End) = SplitDateRange(offsetLastLogTime, endTime);

        var range1StartDate = DateTimeOffset.FromUnixTimeSeconds(range1Start).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
        var range1EndDate = DateTimeOffset.FromUnixTimeSeconds(range1End).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
        var range2StartDate = DateTimeOffset.FromUnixTimeSeconds(range2Start).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
        var range2EndDate = DateTimeOffset.FromUnixTimeSeconds(range2End).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");

        Console.WriteLine($"  -> Splitting remaining range:");
        Console.WriteLine($"     Range 1: {range1StartDate} ({range1Start}s) to {range1EndDate} ({range1End}s)");
        Console.WriteLine($"     Range 2: {range2StartDate} ({range2Start}s) to {range2EndDate} ({range2End}s)");

        // Query both halves recursively
        Console.WriteLine($"  -> Querying range 1...");
        var results1 = await PerformLargeQuery(logGroupName, queryString, range1Start, range1End, limit);
        Console.WriteLine($"  -> Range 1 returned {results1.Count} logs");

        Console.WriteLine($"  -> Querying range 2...");
        var results2 = await PerformLargeQuery(logGroupName, queryString, range2Start, range2End, limit);
        Console.WriteLine($"  -> Range 2 returned {results2.Count} logs");

        // Combine all results
        var allResults = new List<List<ResultField>>(results);
        allResults.AddRange(results1);
        allResults.AddRange(results2);

        Console.WriteLine($"  -> Combined total: {allResults.Count} logs ({results.Count} + {results1.Count} + {results2.Count})");

        return allResults;
    }

    /// <summary>
    /// Gets the timestamp string of the most recent log from a list of logs.
    /// Sorts timestamps to find the actual last one.
    /// </summary>
    private static string? GetLastLogTimestamp(List<List<ResultField>> logs)
    {
        var timestamps = logs
            .Select(log => log.Find(f => f.Field == "@timestamp")?.Value)
            .Where(t => !string.IsNullOrEmpty(t))
            .OrderBy(t => t)
            .ToList();

        if (timestamps.Count == 0)
        {
            return null;
        }

        return timestamps[timestamps.Count - 1];
    }

    /// <summary>
    /// Splits a date range in half.
    /// Range 2 starts at midpoint + 1 second to avoid overlap.
    /// </summary>
    private static (long range1Start, long range1End, long range2Start, long range2End) SplitDateRange(long startTime, long endTime)
    {
        var midpoint = startTime + (endTime - startTime) / 2;
        // Range 2 starts at midpoint + 1 to avoid querying the same second twice
        return (startTime, midpoint, midpoint + 1, endTime);
    }

    /// <summary>
    /// Polls for query results until complete.
    /// </summary>
    private static async Task<List<List<ResultField>>?> PollQueryResults(string queryId)
    {
        int retryCount = 0;
        const int maxRetries = 60;
        const int retryDelay = 1000;

        while (retryCount < maxRetries)
        {
            var response = await _wrapper.GetQueryResultsAsync(queryId);
            if (response == null)
            {
                return null;
            }

            if (response.Status == QueryStatus.Complete)
            {
                return response.Results;
            }

            if (response.Status == QueryStatus.Failed ||
                response.Status == QueryStatus.Cancelled ||
                response.Status == QueryStatus.Timeout ||
                response.Status == QueryStatus.Unknown)
            {
                _logger.LogError($"Query failed with status: {response.Status}");
                return null;
            }

            await Task.Delay(retryDelay);
            retryCount++;
        }

        _logger.LogError("Timed out waiting for query results.");
        return null;
    }

    /// <summary>
    /// Cleans up the resources created during the scenario.
    /// </summary>
    public static async Task<bool> Cleanup()
    {
        var cleanup = !_interactive || GetYesNoResponse(
            "Do you want to delete the CloudFormation stack and all resources? (y/n) ");

        if (cleanup)
        {
            try
            {
                var stackDeleteSuccess = await DeleteCloudFormationStack(_stackName, false);
                return stackDeleteSuccess;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "An error occurred while cleaning up the resources.");
                return false;
            }
        }

        Console.WriteLine($"Resources will remain. Stack name: {_stackName}, Log group: {_logGroupName}");
        _logger.LogInformation("CloudWatch Logs Large Query scenario is complete.");
        return true;
    }

    /// <summary>
    /// Deletes the CloudFormation stack and waits for confirmation.
    /// </summary>
    private static async Task<bool> DeleteCloudFormationStack(string stackName, bool forceDelete)
    {
        var request = new DeleteStackRequest
        {
            StackName = stackName,
        };

        if (forceDelete)
        {
            request.DeletionMode = DeletionMode.FORCE_DELETE_STACK;
        }

        await _amazonCloudFormation.DeleteStackAsync(request);
        Console.WriteLine($"CloudFormation stack '{stackName}' is being deleted. This may take a few minutes.");

        bool stackDeleted = await WaitForStackDeletion(stackName, forceDelete);

        if (stackDeleted)
        {
            Console.WriteLine($"CloudFormation stack '{stackName}' has been deleted.");
            return true;
        }
        else
        {
            _logger.LogError($"Failed to delete CloudFormation stack '{stackName}'.");
            return false;
        }
    }

    /// <summary>
    /// Waits for the stack to be deleted.
    /// </summary>
    private static async Task<bool> WaitForStackDeletion(string stackName, bool forceDelete)
    {
        int retryCount = 0;
        const int maxRetries = 30;
        const int retryDelay = 10000;

        while (retryCount < maxRetries)
        {
            var describeStacksRequest = new DescribeStacksRequest
            {
                StackName = stackName
            };

            try
            {
                var describeStacksResponse = await _amazonCloudFormation.DescribeStacksAsync(describeStacksRequest);

                if (describeStacksResponse.Stacks.Count == 0 ||
                    describeStacksResponse.Stacks[0].StackStatus == StackStatus.DELETE_COMPLETE)
                {
                    return true;
                }

                if (!forceDelete && describeStacksResponse.Stacks[0].StackStatus == StackStatus.DELETE_FAILED)
                {
                    return await DeleteCloudFormationStack(stackName, true);
                }
            }
            catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "ValidationError")
            {
                return true;
            }

            Console.WriteLine($"Waiting for CloudFormation stack '{stackName}' to be deleted...");
            await Task.Delay(retryDelay);
            retryCount++;
        }

        _logger.LogError($"Timed out waiting for CloudFormation stack '{stackName}' to be deleted.");
        return false;
    }

    /// <summary>
    /// Waits with a countdown display.
    /// </summary>
    private static async Task WaitWithCountdown(int seconds)
    {
        for (int i = seconds; i > 0; i--)
        {
            Console.Write($"\rWaiting: {i} seconds remaining...  ");
            await Task.Delay(1000);
        }
        Console.WriteLine("\rWait complete.                      ");
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase);
        return response;
    }

    /// <summary>
    /// Prompts the user for a stack name.
    /// </summary>
    private static string PromptUserForStackName()
    {
        if (_interactive)
        {
            Console.Write($"Enter a name for the CloudFormation stack (press Enter for default '{_stackName}'): ");
            string? input = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(input))
            {
                var regex = "[a-zA-Z][-a-zA-Z0-9]*";
                if (!Regex.IsMatch(input, regex))
                {
                    Console.WriteLine($"Invalid stack name. Using default: {_stackName}");
                    return _stackName;
                }
                return input;
            }
        }
        return _stackName;
    }

    /// <summary>
    /// Prompts the user for input with a default value.
    /// </summary>
    private static string PromptUserForInput(string prompt, string defaultValue)
    {
        if (_interactive)
        {
            Console.Write($"{prompt}(press Enter for default '{defaultValue}'): ");
            string? input = Console.ReadLine();
            return string.IsNullOrWhiteSpace(input) ? defaultValue : input;
        }
        return defaultValue;
    }

    /// <summary>
    /// Prompts the user for an integer value.
    /// </summary>
    private static int PromptUserForInteger(string prompt, int defaultValue)
    {
        if (_interactive)
        {
            Console.Write($"{prompt}(press Enter for default '{defaultValue}'): ");
            string? input = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(input) || !int.TryParse(input, out var result))
            {
                return defaultValue;
            }
            return result;
        }
        return defaultValue;
    }

    /// <summary>
    /// Prompts the user for a long value.
    /// </summary>
    private static long PromptUserForLong(string prompt)
    {
        if (_interactive)
        {
            Console.Write(prompt);
            string? input = Console.ReadLine();
            if (long.TryParse(input, out var result))
            {
                return result;
            }
        }
        return 0;
    }

    /// <summary>
    /// Finds duplicate log entries based on timestamp and message.
    /// </summary>
    private static List<(string Timestamp, string Message, int Count)> FindDuplicateLogs(List<List<ResultField>> logs)
    {
        var logSignatures = new Dictionary<string, int>();

        foreach (var log in logs)
        {
            var timestamp = log.Find(f => f.Field == "@timestamp")?.Value ?? "";
            var message = log.Find(f => f.Field == "@message")?.Value ?? "";
            var signature = $"{timestamp}|{message}";

            if (logSignatures.ContainsKey(signature))
            {
                logSignatures[signature]++;
            }
            else
            {
                logSignatures[signature] = 1;
            }
        }

        return logSignatures
            .Where(kvp => kvp.Value > 1)
            .Select(kvp =>
            {
                var parts = kvp.Key.Split('|');
                return (Timestamp: parts[0], Message: parts[1], Count: kvp.Value);
            })
            .OrderByDescending(x => x.Count)
            .ToList();
    }
}
```
+ API の詳細については、「AWS SDK for .NET API リファレンス**」の以下のトピックを参照してください。
  + [GetQueryResults](https://docs.aws.amazon.com/goto/DotNetSDKV4/logs-2014-03-28/GetQueryResults)
  + [StartQuery](https://docs.aws.amazon.com/goto/DotNetSDKV4/logs-2014-03-28/StartQuery)

# SDK for .NET (v4) を使用した Amazon Cognito ID プロバイダーの例
<a name="csharp_4_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListUserPools`
<a name="cognito-identity-provider_ListUserPools_csharp_4_topic"></a>

次の例は、`ListUserPools` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Cognito#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List the Amazon Cognito user pools for an account.
    /// </summary>
    /// <returns>A list of UserPoolDescriptionType objects.</returns>
    public async Task<List<UserPoolDescriptionType>> ListUserPoolsAsync()
    {
        var userPools = new List<UserPoolDescriptionType>();

        var userPoolsPaginator = _cognitoService.Paginators.ListUserPools(new ListUserPoolsRequest());

        await foreach (var response in userPoolsPaginator.Responses)
        {
            userPools.AddRange(response.UserPools);
        }

        return userPools;
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[ListUserPools](https://docs.aws.amazon.com/goto/DotNetSDKV4/cognito-idp-2016-04-18/ListUserPools)」を参照してください。**

# AWS Control Tower SDK for .NET (v4) を使用した例
<a name="csharp_4_controltower_code_examples"></a>

次のコード例は、 で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Control Tower。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Control Towerは
<a name="controltower_Hello_csharp_4_topic"></a>

次のコード例は、 AWS Control Towerの使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.ControlTower;
using Amazon.ControlTower.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;

namespace ControlTowerActions;

/// <summary>
/// A class that introduces the AWS Control Tower by listing the
/// available baselines for the account.
/// </summary>
public class HelloControlTower
{
    private static ILogger logger = null!;

    static async Task Main(string[] args)
    {
        // Set up dependency injection for AWS Control Tower.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonControlTower>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<HelloControlTower>();

        var amazonClient = host.Services.GetRequiredService<IAmazonControlTower>();

        Console.Clear();
        Console.WriteLine("Hello, AWS Control Tower! Let's list available baselines:");
        Console.WriteLine();

        var baselines = new List<BaselineSummary>();

        try
        {
            var baselinesPaginator = amazonClient.Paginators.ListBaselines(new ListBaselinesRequest());

            await foreach (var response in baselinesPaginator.Responses)
            {
                baselines.AddRange(response.Baselines);
            }

            Console.WriteLine($"{baselines.Count} baseline(s) retrieved.");
            foreach (var baseline in baselines)
            {
                Console.WriteLine($"\t{baseline.Name}");
            }
        }
        catch (Amazon.ControlTower.Model.AccessDeniedException)
        {
            Console.WriteLine("Access denied. Please ensure you have the necessary permissions.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListBaselines](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListBaselines)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="controltower_Scenario_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ランディングゾーンを一覧表示します。
+ ベースラインを一覧表示、有効化、取得、リセット、無効化する。
+ コントロールを一覧表示、有効化、取得、無効化する。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。
 AWS Control Tower 機能を示すインタラクティブなシナリオを実行します。  

```
using Amazon.ControlCatalog;
using Amazon.ControlTower;
using Amazon.ControlTower.Model;
using Amazon.Organizations;
using Amazon.Organizations.Model;
using Amazon.SecurityToken;
using Amazon.SecurityToken.Model;
using ControlTowerActions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace ControlTowerBasics;

/// <summary>
/// Scenario class for AWS Control Tower basics.
/// </summary>
public class ControlTowerBasics
{
    public static bool isInteractive = true;
    public static ILogger logger = null!;
    public static IAmazonOrganizations? orgClient = null;
    public static IAmazonSecurityTokenService? stsClient = null;
    public static ControlTowerWrapper? wrapper = null;
    private static string? ouArn;
    private static bool useLandingZone = false;

    /// <summary>
    /// Main entry point for the AWS Control Tower basics scenario.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    public static async Task Main(string[] args)
    {
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonControlTower>()
                .AddAWSService<IAmazonControlCatalog>()
                .AddAWSService<IAmazonOrganizations>()
                .AddAWSService<IAmazonSecurityTokenService>()
                .AddTransient<ControlTowerWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<ControlTowerBasics>();

        wrapper = host.Services.GetRequiredService<ControlTowerWrapper>();
        orgClient = host.Services.GetRequiredService<IAmazonOrganizations>();
        stsClient = host.Services.GetRequiredService<IAmazonSecurityTokenService>();

        await RunScenario();
    }

    /// <summary>
    /// Runs the example scenario.
    /// </summary>
    public static async Task RunScenario()
    {
        Console.WriteLine(new string('-', 88));
        Console.WriteLine("\tWelcome to the AWS Control Tower with ControlCatalog example scenario.");
        Console.WriteLine(new string('-', 88));
        Console.WriteLine("This demo will walk you through working with AWS Control Tower for landing zones,");
        Console.WriteLine("managing baselines, and working with controls.");

        try
        {
            var accountId = (await stsClient!.GetCallerIdentityAsync(new GetCallerIdentityRequest())).Account;
            Console.WriteLine($"\nAccount ID: {accountId}");

            Console.WriteLine("\nSome demo operations require the use of a landing zone.");
            Console.WriteLine("You can use an existing landing zone or opt out of these operations in the demo.");
            Console.WriteLine("For instructions on how to set up a landing zone,");
            Console.WriteLine("see https://docs.aws.amazon.com/controltower/latest/userguide/getting-started-from-console.html");

            // List available landing zones
            var landingZones = await wrapper!.ListLandingZonesAsync();
            if (landingZones.Count > 0)
            {
                Console.WriteLine("\nAvailable Landing Zones:");
                for (int i = 0; i < landingZones.Count; i++)
                {
                    Console.WriteLine($"{i + 1}. {landingZones[i].Arn}");
                }

                Console.Write($"\nDo you want to use the first landing zone in the list ({landingZones[0].Arn})? (y/n): ");
                if (GetUserConfirmation())
                {
                    useLandingZone = true;
                    Console.WriteLine($"Using landing zone: {landingZones[0].Arn}");
                    ouArn = await SetupOrganizationAsync();
                }
            }

            // Managing Baselines
            Console.WriteLine("\nManaging Baselines:");
            var baselines = await wrapper.ListBaselinesAsync();
            Console.WriteLine("\nListing available Baselines:");
            BaselineSummary? controlTowerBaseline = null;
            foreach (var baseline in baselines)
            {
                if (baseline.Name == "AWSControlTowerBaseline")
                    controlTowerBaseline = baseline;
                Console.WriteLine($"  - {baseline.Name}");
            }

            EnabledBaselineSummary? identityCenterBaseline = null;
            string? baselineArn = null;

            if (useLandingZone && ouArn != null)
            {
                Console.WriteLine("\nListing enabled baselines:");
                var enabledBaselines = await wrapper.ListEnabledBaselinesAsync();
                foreach (var baseline in enabledBaselines)
                {
                    if (baseline.BaselineIdentifier.Contains("baseline/LN25R72TTG6IGPTQ"))
                        identityCenterBaseline = baseline;
                    Console.WriteLine($"  - {baseline.BaselineIdentifier}");
                }

                if (controlTowerBaseline != null)
                {
                    Console.Write("\nDo you want to enable the Control Tower Baseline? (y/n): ");
                    if (GetUserConfirmation())
                    {
                        Console.WriteLine("\nEnabling Control Tower Baseline.");
                        var icBaselineArn = identityCenterBaseline?.Arn;
                        baselineArn = await wrapper.EnableBaselineAsync(ouArn,
                            controlTowerBaseline.Arn, "5.0", icBaselineArn ?? "");
                        var alreadyEnabled = false;
                        if (baselineArn != null)
                        {
                            Console.WriteLine($"Enabled baseline ARN: {baselineArn}");
                        }
                        else
                        {
                            // Find the enabled baseline
                            foreach (var enabled in enabledBaselines)
                            {
                                if (enabled.BaselineIdentifier == controlTowerBaseline.Arn)
                                {
                                    baselineArn = enabled.Arn;
                                    alreadyEnabled = true;
                                    Console.WriteLine("No change, the selected baseline was already enabled.");
                                    break;
                                }
                            }
                        }

                        if (baselineArn != null)
                        {
                            Console.Write("\nDo you want to reset the Control Tower Baseline? (y/n): ");
                            if (GetUserConfirmation())
                            {
                                Console.WriteLine($"\nResetting Control Tower Baseline: {baselineArn}");
                                var operationId = await wrapper.ResetEnabledBaselineAsync(baselineArn);
                                Console.WriteLine($"Reset baseline operation id: {operationId}");
                            }

                            Console.Write("\nDo you want to disable the Control Tower Baseline? (y/n): ");
                            if (GetUserConfirmation())
                            {
                                Console.WriteLine($"Disabling baseline ARN: {baselineArn}");
                                var operationId = await wrapper.DisableBaselineAsync(baselineArn);
                                Console.WriteLine($"Disabled baseline operation id: {operationId}");
                                if (alreadyEnabled)
                                {
                                    Console.WriteLine($"\nRe-enabling Control Tower Baseline: {baselineArn}");
                                    // Re-enable the Control Tower baseline if it was originally enabled.
                                    await wrapper.EnableBaselineAsync(ouArn,
                                        controlTowerBaseline.Arn, "5.0", icBaselineArn ?? "");
                                }
                            }
                        }
                    }
                }
            }

            // Managing Controls
            Console.WriteLine("\nManaging Controls:");
            var controls = await wrapper.ListControlsAsync();
            Console.WriteLine("\nListing first 5 available Controls:");
            for (int i = 0; i < Math.Min(5, controls.Count); i++)
            {
                Console.WriteLine($"{i + 1}. {controls[i].Name} - {controls[i].Arn}");
            }

            if (useLandingZone && ouArn != null)
            {
                var enabledControls = await wrapper.ListEnabledControlsAsync(ouArn);
                Console.WriteLine("\nListing enabled controls:");
                for (int i = 0; i < enabledControls.Count; i++)
                {
                    Console.WriteLine($"{i + 1}. {enabledControls[i].ControlIdentifier}");
                }

                // Find first non-enabled control
                var enabledControlArns = enabledControls.Select(c => c.Arn).ToHashSet();
                var controlArn = controls.FirstOrDefault(c => !enabledControlArns.Contains(c.Arn))?.Arn;

                if (controlArn != null)
                {
                    Console.Write($"\nDo you want to enable the control {controlArn}? (y/n): ");
                    if (GetUserConfirmation())
                    {
                        Console.WriteLine($"\nEnabling control: {controlArn}");
                        var operationId = await wrapper.EnableControlAsync(controlArn, ouArn);
                        if (operationId != null)
                        {
                            Console.WriteLine($"Enabled control with operation id: {operationId}");

                            Console.Write("\nDo you want to disable the control? (y/n): ");
                            if (GetUserConfirmation())
                            {
                                Console.WriteLine("\nDisabling the control...");
                                var disableOpId = await wrapper.DisableControlAsync(controlArn, ouArn);
                                Console.WriteLine($"Disable operation ID: {disableOpId}");
                            }
                        }
                    }
                }
            }

            Console.WriteLine("\nThis concludes the example scenario.");
            Console.WriteLine("Thanks for watching!");
            Console.WriteLine(new string('-', 88));
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An error occurred during the Control Tower scenario.");
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }

    /// <summary>
    /// Sets up AWS Organizations and creates or finds a Sandbox OU.
    /// </summary>
    /// <returns>The ARN of the Sandbox organizational unit.</returns>
    private static async Task<string> SetupOrganizationAsync()
    {
        Console.WriteLine("\nChecking organization status...");

        try
        {
            var orgResponse = await orgClient!.DescribeOrganizationAsync(new DescribeOrganizationRequest());
            var orgId = orgResponse.Organization.Id;
            Console.WriteLine($"Account is part of organization: {orgId}");
        }
        catch (AWSOrganizationsNotInUseException)
        {
            Console.WriteLine("No organization found. Creating a new organization...");
            var createResponse = await orgClient!.CreateOrganizationAsync(new CreateOrganizationRequest { FeatureSet = OrganizationFeatureSet.ALL });
            var orgId = createResponse.Organization.Id;
            Console.WriteLine($"Created new organization: {orgId}");
        }

        // Look for Sandbox OU
        var roots = await orgClient.ListRootsAsync(new ListRootsRequest());
        var rootId = roots.Roots[0].Id;

        Console.WriteLine("Checking for Sandbox OU...");
        var ous = await orgClient.ListOrganizationalUnitsForParentAsync(new ListOrganizationalUnitsForParentRequest { ParentId = rootId });
        var sandboxOu = ous.OrganizationalUnits.FirstOrDefault(ou => ou.Name == "Sandbox");

        if (sandboxOu == null)
        {
            Console.WriteLine("Creating Sandbox OU...");
            var createOuResponse = await orgClient.CreateOrganizationalUnitAsync(new CreateOrganizationalUnitRequest { ParentId = rootId, Name = "Sandbox" });
            sandboxOu = createOuResponse.OrganizationalUnit;
            Console.WriteLine($"Created new Sandbox OU: {sandboxOu.Id}");
        }
        else
        {
            Console.WriteLine($"Found existing Sandbox OU: {sandboxOu.Id}");
        }

        return sandboxOu.Arn;
    }

    /// <summary>
    /// Gets user confirmation by waiting for input or returning true if not interactive.
    /// </summary>
    /// <returns>True if user enters 'y' or if isInteractive is false, otherwise false.</returns>
    private static bool GetUserConfirmation()
    {
        return Console.ReadLine()?.ToLower() == "y" || !isInteractive;
    }
}
```
Aurora アクションを管理するためにシナリオによって呼び出されるラッパーメソッド。  

```
using Amazon.ControlCatalog;
using Amazon.ControlCatalog.Model;
using Amazon.ControlTower;
using Amazon.ControlTower.Model;
using ValidationException = Amazon.ControlTower.Model.ValidationException;

namespace ControlTowerActions;

/// <summary>
/// Methods to perform AWS Control Tower actions.
/// </summary>
public class ControlTowerWrapper
{
    private readonly IAmazonControlTower _controlTowerService;
    private readonly IAmazonControlCatalog _controlCatalogService;

    /// <summary>
    /// Constructor for the wrapper class containing AWS Control Tower actions.
    /// </summary>
    /// <param name="controlTowerService">The AWS Control Tower client object.</param>
    /// <param name="controlCatalogService">The AWS Control Catalog client object.</param>
    public ControlTowerWrapper(IAmazonControlTower controlTowerService, IAmazonControlCatalog controlCatalogService)
    {
        _controlTowerService = controlTowerService;
        _controlCatalogService = controlCatalogService;
    }

    /// <summary>
    /// List the AWS Control Tower landing zones for an account.
    /// </summary>
    /// <returns>A list of LandingZoneSummary objects.</returns>
    public async Task<List<LandingZoneSummary>> ListLandingZonesAsync()
    {
        try
        {
            var landingZones = new List<LandingZoneSummary>();

            var landingZonesPaginator = _controlTowerService.Paginators.ListLandingZones(new ListLandingZonesRequest());

            await foreach (var response in landingZonesPaginator.Responses)
            {
                landingZones.AddRange(response.LandingZones);
            }

            return landingZones;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list landing zones. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// List all baselines.
    /// </summary>
    /// <returns>A list of baseline summaries.</returns>
    public async Task<List<BaselineSummary>> ListBaselinesAsync()
    {
        try
        {
            var baselines = new List<BaselineSummary>();

            var baselinesPaginator = _controlTowerService.Paginators.ListBaselines(new ListBaselinesRequest());

            await foreach (var response in baselinesPaginator.Responses)
            {
                baselines.AddRange(response.Baselines);
            }

            return baselines;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list baselines. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// List all enabled baselines.
    /// </summary>
    /// <returns>A list of enabled baseline summaries.</returns>
    public async Task<List<EnabledBaselineSummary>> ListEnabledBaselinesAsync()
    {
        try
        {
            var enabledBaselines = new List<EnabledBaselineSummary>();

            var enabledBaselinesPaginator = _controlTowerService.Paginators.ListEnabledBaselines(new ListEnabledBaselinesRequest());

            await foreach (var response in enabledBaselinesPaginator.Responses)
            {
                enabledBaselines.AddRange(response.EnabledBaselines);
            }

            return enabledBaselines;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list enabled baselines. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Enable a baseline for the specified target.
    /// </summary>
    /// <param name="targetIdentifier">The ARN of the target.</param>
    /// <param name="baselineIdentifier">The identifier of baseline to enable.</param>
    /// <param name="baselineVersion">The version of baseline to enable.</param>
    /// <param name="identityCenterBaseline">The identifier of identity center baseline if it is enabled.</param>
    /// <returns>The enabled baseline ARN or null.</returns>
    public async Task<string?> EnableBaselineAsync(string targetIdentifier, string baselineIdentifier, string baselineVersion, string identityCenterBaseline)
    {
        try
        {
            var parameters = new List<EnabledBaselineParameter>();
            if (!string.IsNullOrEmpty(identityCenterBaseline))
            {
                parameters.Add(
                    new EnabledBaselineParameter
                    {
                        Key = "IdentityCenterEnabledBaselineArn",
                        Value = identityCenterBaseline
                    });
            }
            var request = new EnableBaselineRequest
            {
                BaselineIdentifier = baselineIdentifier,
                BaselineVersion = baselineVersion,
                TargetIdentifier = targetIdentifier,
                Parameters = parameters
            };

            var response = await _controlTowerService.EnableBaselineAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetBaselineOperationAsync(operationId);
                Console.WriteLine($"Baseline operation status: {status}");
                if (status == BaselineOperationStatus.SUCCEEDED || status == BaselineOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return response.Arn;
        }
        catch (ValidationException ex)
        {
            if (ex.Message.Contains("already enabled"))
                Console.WriteLine("Baseline is already enabled for this target");
            else { Console.WriteLine(ex.Message); }
            // Write the message and return null if baseline cannot be enabled.
            return null;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't enable baseline. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Disable a baseline for a specific target and wait for the operation to complete.
    /// </summary>
    /// <param name="enabledBaselineIdentifier">The identifier of the baseline to disable.</param>
    /// <returns>The operation ID or null if there was a conflict.</returns>
    public async Task<string?> DisableBaselineAsync(string enabledBaselineIdentifier)
    {
        try
        {
            var request = new DisableBaselineRequest
            {
                EnabledBaselineIdentifier = enabledBaselineIdentifier
            };

            var response = await _controlTowerService.DisableBaselineAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetBaselineOperationAsync(operationId);
                Console.WriteLine($"Baseline operation status: {status}");
                if (status == BaselineOperationStatus.SUCCEEDED || status == BaselineOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (ConflictException ex)
        {
            Console.WriteLine($"Conflict disabling baseline: {ex.Message}. Skipping disable step.");
            return null;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't disable baseline. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Reset an enabled baseline for a specific target.
    /// </summary>
    /// <param name="enabledBaselineIdentifier">The identifier of the enabled baseline to reset.</param>
    /// <returns>The operation ID.</returns>
    public async Task<string> ResetEnabledBaselineAsync(string enabledBaselineIdentifier)
    {
        try
        {
            var request = new ResetEnabledBaselineRequest
            {
                EnabledBaselineIdentifier = enabledBaselineIdentifier
            };

            var response = await _controlTowerService.ResetEnabledBaselineAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetBaselineOperationAsync(operationId);
                Console.WriteLine($"Baseline operation status: {status}");
                if (status == BaselineOperationStatus.SUCCEEDED || status == BaselineOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Target not found, unable to reset enabled baseline.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't reset enabled baseline. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Get the status of a baseline operation.
    /// </summary>
    /// <param name="operationId">The ID of the baseline operation.</param>
    /// <returns>The operation status.</returns>
    public async Task<BaselineOperationStatus> GetBaselineOperationAsync(string operationId)
    {
        try
        {
            var request = new GetBaselineOperationRequest
            {
                OperationIdentifier = operationId
            };

            var response = await _controlTowerService.GetBaselineOperationAsync(request);
            return response.BaselineOperation.Status;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Operation not found.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't get baseline operation status. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// List enabled controls for a target organizational unit.
    /// </summary>
    /// <param name="targetIdentifier">The target organizational unit identifier.</param>
    /// <returns>A list of enabled control summaries.</returns>
    public async Task<List<EnabledControlSummary>> ListEnabledControlsAsync(string targetIdentifier)
    {
        try
        {
            var request = new ListEnabledControlsRequest
            {
                TargetIdentifier = targetIdentifier
            };

            var enabledControls = new List<EnabledControlSummary>();

            var enabledControlsPaginator = _controlTowerService.Paginators.ListEnabledControls(request);

            await foreach (var response in enabledControlsPaginator.Responses)
            {
                enabledControls.AddRange(response.EnabledControls);
            }

            return enabledControls;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException ex) when (ex.Message.Contains("not registered with AWS Control Tower"))
        {
            Console.WriteLine("AWS Control Tower must be enabled to work with enabling controls.");
            return new List<EnabledControlSummary>();
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list enabled controls. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Enable a control for a specified target.
    /// </summary>
    /// <param name="controlArn">The ARN of the control to enable.</param>
    /// <param name="targetIdentifier">The identifier of the target (e.g., OU ARN).</param>
    /// <returns>The operation ID or null if already enabled.</returns>
    public async Task<string?> EnableControlAsync(string controlArn, string targetIdentifier)
    {
        try
        {
            Console.WriteLine(controlArn);
            Console.WriteLine(targetIdentifier);

            var request = new EnableControlRequest
            {
                ControlIdentifier = controlArn,
                TargetIdentifier = targetIdentifier
            };

            var response = await _controlTowerService.EnableControlAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetControlOperationAsync(operationId);
                Console.WriteLine($"Control operation status: {status}");
                if (status == ControlOperationStatus.SUCCEEDED || status == ControlOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (Amazon.ControlTower.Model.ValidationException ex) when (ex.Message.Contains("already enabled"))
        {
            Console.WriteLine("Control is already enabled for this target");
            return null;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException ex) when (ex.Message.Contains("not registered with AWS Control Tower"))
        {
            Console.WriteLine("AWS Control Tower must be enabled to work with enabling controls.");
            return null;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't enable control. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Disable a control for a specified target.
    /// </summary>
    /// <param name="controlArn">The ARN of the control to disable.</param>
    /// <param name="targetIdentifier">The identifier of the target (e.g., OU ARN).</param>
    /// <returns>The operation ID.</returns>
    public async Task<string> DisableControlAsync(string controlArn, string targetIdentifier)
    {
        try
        {
            var request = new DisableControlRequest
            {
                ControlIdentifier = controlArn,
                TargetIdentifier = targetIdentifier
            };

            var response = await _controlTowerService.DisableControlAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetControlOperationAsync(operationId);
                Console.WriteLine($"Control operation status: {status}");
                if (status == ControlOperationStatus.SUCCEEDED || status == ControlOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Control not found.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't disable control. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// Get the status of a control operation.
    /// </summary>
    /// <param name="operationId">The ID of the control operation.</param>
    /// <returns>The operation status.</returns>
    public async Task<ControlOperationStatus> GetControlOperationAsync(string operationId)
    {
        try
        {
            var request = new GetControlOperationRequest
            {
                OperationIdentifier = operationId
            };

            var response = await _controlTowerService.GetControlOperationAsync(request);
            return response.ControlOperation.Status;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Operation not found.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't get control operation status. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }


    /// <summary>
    /// List all controls in the Control Tower control catalog.
    /// </summary>
    /// <returns>A list of control summaries.</returns>
    public async Task<List<ControlSummary>> ListControlsAsync()
    {
        try
        {
            var controls = new List<ControlSummary>();

            var controlsPaginator = _controlCatalogService.Paginators.ListControls(new Amazon.ControlCatalog.Model.ListControlsRequest());

            await foreach (var response in controlsPaginator.Responses)
            {
                controls.AddRange(response.Controls);
            }

            return controls;
        }
        catch (AmazonControlCatalogException ex)
        {
            Console.WriteLine($"Couldn't list controls. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }

}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateLandingZone](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/CreateLandingZone)
  + [DeleteLandingZone](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/DeleteLandingZone)
  + [DisableBaseline](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/DisableBaseline)
  + [DisableControl](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/DisableControl)
  + [EnableBaseline](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/EnableBaseline)
  + [EnableControl](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/EnableControl)
  + [GetControlOperation](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/GetControlOperation)
  + [GetLandingZoneOperation](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/GetLandingZoneOperation)
  + [ListBaselines](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListBaselines)
  + [ListEnabledBaselines](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListEnabledBaselines)
  + [ListEnabledControls](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListEnabledControls)
  + [ListLandingZones](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListLandingZones)
  + [ResetEnabledBaseline](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ResetEnabledBaseline)

## アクション
<a name="actions"></a>

### `DisableBaseline`
<a name="controltower_DisableBaseline_csharp_4_topic"></a>

次の例は、`DisableBaseline` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Disable a baseline for a specific target and wait for the operation to complete.
    /// </summary>
    /// <param name="enabledBaselineIdentifier">The identifier of the baseline to disable.</param>
    /// <returns>The operation ID or null if there was a conflict.</returns>
    public async Task<string?> DisableBaselineAsync(string enabledBaselineIdentifier)
    {
        try
        {
            var request = new DisableBaselineRequest
            {
                EnabledBaselineIdentifier = enabledBaselineIdentifier
            };

            var response = await _controlTowerService.DisableBaselineAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetBaselineOperationAsync(operationId);
                Console.WriteLine($"Baseline operation status: {status}");
                if (status == BaselineOperationStatus.SUCCEEDED || status == BaselineOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (ConflictException ex)
        {
            Console.WriteLine($"Conflict disabling baseline: {ex.Message}. Skipping disable step.");
            return null;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't disable baseline. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DisableBaseline](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/DisableBaseline)」を参照してください。

### `DisableControl`
<a name="controltower_DisableControl_csharp_4_topic"></a>

次の例は、`DisableControl` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Disable a control for a specified target.
    /// </summary>
    /// <param name="controlArn">The ARN of the control to disable.</param>
    /// <param name="targetIdentifier">The identifier of the target (e.g., OU ARN).</param>
    /// <returns>The operation ID.</returns>
    public async Task<string> DisableControlAsync(string controlArn, string targetIdentifier)
    {
        try
        {
            var request = new DisableControlRequest
            {
                ControlIdentifier = controlArn,
                TargetIdentifier = targetIdentifier
            };

            var response = await _controlTowerService.DisableControlAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetControlOperationAsync(operationId);
                Console.WriteLine($"Control operation status: {status}");
                if (status == ControlOperationStatus.SUCCEEDED || status == ControlOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Control not found.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't disable control. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DisableControl](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/DisableControl)」を参照してください。

### `EnableBaseline`
<a name="controltower_EnableBaseline_csharp_4_topic"></a>

次の例は、`EnableBaseline` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Enable a baseline for the specified target.
    /// </summary>
    /// <param name="targetIdentifier">The ARN of the target.</param>
    /// <param name="baselineIdentifier">The identifier of baseline to enable.</param>
    /// <param name="baselineVersion">The version of baseline to enable.</param>
    /// <param name="identityCenterBaseline">The identifier of identity center baseline if it is enabled.</param>
    /// <returns>The enabled baseline ARN or null.</returns>
    public async Task<string?> EnableBaselineAsync(string targetIdentifier, string baselineIdentifier, string baselineVersion, string identityCenterBaseline)
    {
        try
        {
            var parameters = new List<EnabledBaselineParameter>();
            if (!string.IsNullOrEmpty(identityCenterBaseline))
            {
                parameters.Add(
                    new EnabledBaselineParameter
                    {
                        Key = "IdentityCenterEnabledBaselineArn",
                        Value = identityCenterBaseline
                    });
            }
            var request = new EnableBaselineRequest
            {
                BaselineIdentifier = baselineIdentifier,
                BaselineVersion = baselineVersion,
                TargetIdentifier = targetIdentifier,
                Parameters = parameters
            };

            var response = await _controlTowerService.EnableBaselineAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetBaselineOperationAsync(operationId);
                Console.WriteLine($"Baseline operation status: {status}");
                if (status == BaselineOperationStatus.SUCCEEDED || status == BaselineOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return response.Arn;
        }
        catch (ValidationException ex)
        {
            if (ex.Message.Contains("already enabled"))
                Console.WriteLine("Baseline is already enabled for this target");
            else { Console.WriteLine(ex.Message); }
            // Write the message and return null if baseline cannot be enabled.
            return null;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't enable baseline. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[EnableBaseline](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/EnableBaseline)」を参照してください。

### `EnableControl`
<a name="controltower_EnableControl_csharp_4_topic"></a>

次の例は、`EnableControl` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Enable a control for a specified target.
    /// </summary>
    /// <param name="controlArn">The ARN of the control to enable.</param>
    /// <param name="targetIdentifier">The identifier of the target (e.g., OU ARN).</param>
    /// <returns>The operation ID or null if already enabled.</returns>
    public async Task<string?> EnableControlAsync(string controlArn, string targetIdentifier)
    {
        try
        {
            Console.WriteLine(controlArn);
            Console.WriteLine(targetIdentifier);

            var request = new EnableControlRequest
            {
                ControlIdentifier = controlArn,
                TargetIdentifier = targetIdentifier
            };

            var response = await _controlTowerService.EnableControlAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetControlOperationAsync(operationId);
                Console.WriteLine($"Control operation status: {status}");
                if (status == ControlOperationStatus.SUCCEEDED || status == ControlOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (Amazon.ControlTower.Model.ValidationException ex) when (ex.Message.Contains("already enabled"))
        {
            Console.WriteLine("Control is already enabled for this target");
            return null;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException ex) when (ex.Message.Contains("not registered with AWS Control Tower"))
        {
            Console.WriteLine("AWS Control Tower must be enabled to work with enabling controls.");
            return null;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't enable control. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[EnableControl](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/EnableControl)」を参照してください。

### `GetBaselineOperation`
<a name="controltower_GetBaselineOperation_csharp_4_topic"></a>

次の例は、`GetBaselineOperation` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the status of a baseline operation.
    /// </summary>
    /// <param name="operationId">The ID of the baseline operation.</param>
    /// <returns>The operation status.</returns>
    public async Task<BaselineOperationStatus> GetBaselineOperationAsync(string operationId)
    {
        try
        {
            var request = new GetBaselineOperationRequest
            {
                OperationIdentifier = operationId
            };

            var response = await _controlTowerService.GetBaselineOperationAsync(request);
            return response.BaselineOperation.Status;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Operation not found.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't get baseline operation status. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetBaselineOperation](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/GetBaselineOperation)」を参照してください。

### `GetControlOperation`
<a name="controltower_GetControlOperation_csharp_4_topic"></a>

次の例は、`GetControlOperation` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the status of a control operation.
    /// </summary>
    /// <param name="operationId">The ID of the control operation.</param>
    /// <returns>The operation status.</returns>
    public async Task<ControlOperationStatus> GetControlOperationAsync(string operationId)
    {
        try
        {
            var request = new GetControlOperationRequest
            {
                OperationIdentifier = operationId
            };

            var response = await _controlTowerService.GetControlOperationAsync(request);
            return response.ControlOperation.Status;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Operation not found.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't get control operation status. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[GetControlOperation](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/GetControlOperation)」を参照してください。

### `ListBaselines`
<a name="controltower_ListBaselines_csharp_4_topic"></a>

次の例は、`ListBaselines` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List all baselines.
    /// </summary>
    /// <returns>A list of baseline summaries.</returns>
    public async Task<List<BaselineSummary>> ListBaselinesAsync()
    {
        try
        {
            var baselines = new List<BaselineSummary>();

            var baselinesPaginator = _controlTowerService.Paginators.ListBaselines(new ListBaselinesRequest());

            await foreach (var response in baselinesPaginator.Responses)
            {
                baselines.AddRange(response.Baselines);
            }

            return baselines;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list baselines. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListBaselines](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListBaselines)」を参照してください。

### `ListEnabledBaselines`
<a name="controltower_ListEnabledBaselines_csharp_4_topic"></a>

次の例は、`ListEnabledBaselines` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List all enabled baselines.
    /// </summary>
    /// <returns>A list of enabled baseline summaries.</returns>
    public async Task<List<EnabledBaselineSummary>> ListEnabledBaselinesAsync()
    {
        try
        {
            var enabledBaselines = new List<EnabledBaselineSummary>();

            var enabledBaselinesPaginator = _controlTowerService.Paginators.ListEnabledBaselines(new ListEnabledBaselinesRequest());

            await foreach (var response in enabledBaselinesPaginator.Responses)
            {
                enabledBaselines.AddRange(response.EnabledBaselines);
            }

            return enabledBaselines;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list enabled baselines. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListEnabledBaselines](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListEnabledBaselines)」を参照してください。

### `ListEnabledControls`
<a name="controltower_ListEnabledControls_csharp_4_topic"></a>

次の例は、`ListEnabledControls` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List enabled controls for a target organizational unit.
    /// </summary>
    /// <param name="targetIdentifier">The target organizational unit identifier.</param>
    /// <returns>A list of enabled control summaries.</returns>
    public async Task<List<EnabledControlSummary>> ListEnabledControlsAsync(string targetIdentifier)
    {
        try
        {
            var request = new ListEnabledControlsRequest
            {
                TargetIdentifier = targetIdentifier
            };

            var enabledControls = new List<EnabledControlSummary>();

            var enabledControlsPaginator = _controlTowerService.Paginators.ListEnabledControls(request);

            await foreach (var response in enabledControlsPaginator.Responses)
            {
                enabledControls.AddRange(response.EnabledControls);
            }

            return enabledControls;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException ex) when (ex.Message.Contains("not registered with AWS Control Tower"))
        {
            Console.WriteLine("AWS Control Tower must be enabled to work with enabling controls.");
            return new List<EnabledControlSummary>();
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list enabled controls. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListEnabledControls](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListEnabledControls)」を参照してください。

### `ListLandingZones`
<a name="controltower_ListLandingZones_csharp_4_topic"></a>

次の例は、`ListLandingZones` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List the AWS Control Tower landing zones for an account.
    /// </summary>
    /// <returns>A list of LandingZoneSummary objects.</returns>
    public async Task<List<LandingZoneSummary>> ListLandingZonesAsync()
    {
        try
        {
            var landingZones = new List<LandingZoneSummary>();

            var landingZonesPaginator = _controlTowerService.Paginators.ListLandingZones(new ListLandingZonesRequest());

            await foreach (var response in landingZonesPaginator.Responses)
            {
                landingZones.AddRange(response.LandingZones);
            }

            return landingZones;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't list landing zones. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ListLandingZones](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ListLandingZones)」を参照してください。

### `ResetEnabledBaseline`
<a name="controltower_ResetEnabledBaseline_csharp_4_topic"></a>

次の例は、`ResetEnabledBaseline` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ControlTower#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Reset an enabled baseline for a specific target.
    /// </summary>
    /// <param name="enabledBaselineIdentifier">The identifier of the enabled baseline to reset.</param>
    /// <returns>The operation ID.</returns>
    public async Task<string> ResetEnabledBaselineAsync(string enabledBaselineIdentifier)
    {
        try
        {
            var request = new ResetEnabledBaselineRequest
            {
                EnabledBaselineIdentifier = enabledBaselineIdentifier
            };

            var response = await _controlTowerService.ResetEnabledBaselineAsync(request);
            var operationId = response.OperationIdentifier;

            // Wait for operation to complete
            while (true)
            {
                var status = await GetBaselineOperationAsync(operationId);
                Console.WriteLine($"Baseline operation status: {status}");
                if (status == BaselineOperationStatus.SUCCEEDED || status == BaselineOperationStatus.FAILED)
                {
                    break;
                }
                await Task.Delay(30000); // Wait 30 seconds
            }

            return operationId;
        }
        catch (Amazon.ControlTower.Model.ResourceNotFoundException)
        {
            Console.WriteLine("Target not found, unable to reset enabled baseline.");
            throw;
        }
        catch (AmazonControlTowerException ex)
        {
            Console.WriteLine($"Couldn't reset enabled baseline. Here's why: {ex.ErrorCode}: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[ResetEnabledBaseline](https://docs.aws.amazon.com/goto/DotNetSDKV4/controltower-2018-05-10/ResetEnabledBaseline)」を参照してください。

# SDK for .NET (v4) を使用した DynamoDB の例
<a name="csharp_4_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello DynamoDB
<a name="dynamodb_Hello_csharp_4_topic"></a>

次のコード例は、DynamoDB の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Microsoft.Extensions.DependencyInjection;

namespace DynamoDBActions;

/// <summary>
/// A simple example that demonstrates basic DynamoDB operations.
/// </summary>
public class HelloDynamoDB
{
    /// <summary>
    /// HelloDynamoDB lists the existing DynamoDB tables for the default user.
    /// </summary>
    /// <param name="args">Command line arguments</param>
    /// <returns>Async task.</returns>
    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon DynamoDB.
        using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonDynamoDB>()
            )
            .Build();

        // Now the client is available for injection.
        var dynamoDbClient = host.Services.GetRequiredService<IAmazonDynamoDB>();

        try
        {
            var request = new ListTablesRequest();
            var tableNames = new List<string>();

            var paginatorForTables = dynamoDbClient.Paginators.ListTables(request);

            await foreach (var tableName in paginatorForTables.TableNames)
            {
                tableNames.Add(tableName);
            }

            Console.WriteLine("Welcome to the DynamoDB Hello Service example. " +
                              "\nLet's list your DynamoDB tables:");
            tableNames.ForEach(table =>
            {
                Console.WriteLine($"Table: {table}");
            });
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB service error occurred while listing tables. {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while listing tables. {ex.Message}");
        }
    }
}
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[ListTables](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/ListTables)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
/// <summary>
/// This example application performs the following basic Amazon DynamoDB
/// functions:
///     CreateTableAsync
///     PutItemAsync
///     UpdateItemAsync
///     BatchWriteItemAsync
///     GetItemAsync
///     DeleteItemAsync
///     Query
///     Scan
///     DeleteItemAsync.
/// </summary>
public class DynamoDbBasics
{
    public static bool IsInteractive = true;

    // Separator for the console display.
    private static readonly string SepBar = new string('-', 80);

    /// <summary>
    /// The main entry point for the DynamoDB Basics example application.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    public static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon DynamoDB.
        using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonDynamoDB>()
                    .AddTransient<DynamoDbWrapper>())
            .Build();

        // Now the wrapper is available for injection.
        var dynamoDbWrapper = host.Services.GetRequiredService<DynamoDbWrapper>();

        var tableName = "movie_table";

        var movieFileName = @"movies.json";

        DisplayInstructions();

        // Create a new table and wait for it to be active.
        Console.WriteLine($"Creating the new table: {tableName}");

        var success = await dynamoDbWrapper.CreateMovieTableAsync(tableName);

        Console.WriteLine(success
            ? $"\nTable: {tableName} successfully created."
            : $"\nCould not create {tableName}.");

        WaitForEnter();

        // Add a single new movie to the table.
        var newMovie = new Movie
        {
            Year = 2021,
            Title = "Spider-Man: No Way Home",
        };

        success = await dynamoDbWrapper.PutItemAsync(newMovie, tableName);
        if (success)
        {
            Console.WriteLine($"Added {newMovie.Title} to the table.");
        }
        else
        {
            Console.WriteLine("Could not add movie to table.");
        }

        WaitForEnter();

        // Update the new movie by adding a plot and rank.
        var newInfo = new MovieInfo
        {
            Plot = "With Spider-Man's identity now revealed, Peter asks" +
                   "Doctor Strange for help. When a spell goes wrong, dangerous" +
                   "foes from other worlds start to appear, forcing Peter to" +
                   "discover what it truly means to be Spider-Man.",
            Rank = 9,
        };

        success = await dynamoDbWrapper.UpdateItemAsync(newMovie, newInfo, tableName);
        if (success)
        {
            Console.WriteLine($"Successfully updated the movie: {newMovie.Title}");
        }
        else
        {
            Console.WriteLine("Could not update the movie.");
        }

        WaitForEnter();

        // Add a batch of movies to the DynamoDB table from a list of
        // movies in a JSON file.
        var itemCount = await dynamoDbWrapper.BatchWriteItemsAsync(movieFileName, tableName);
        Console.WriteLine($"Added {itemCount} movies to the table.");

        WaitForEnter();

        // Get a movie by key. (partition + sort)
        var lookupMovie = new Movie
        {
            Title = "Jurassic Park",
            Year = 1993,
        };

        Console.WriteLine("Looking for the movie \"Jurassic Park\".");
        var item = await dynamoDbWrapper.GetItemAsync(lookupMovie, tableName);
        if (item?.Count > 0)
        {
            dynamoDbWrapper.DisplayItem(item);
        }
        else
        {
            Console.WriteLine($"Couldn't find {lookupMovie.Title}");
        }

        WaitForEnter();

        // Delete a movie.
        var movieToDelete = new Movie
        {
            Title = "The Town",
            Year = 2010,
        };

        success = await dynamoDbWrapper.DeleteItemAsync(tableName, movieToDelete);

        if (success)
        {
            Console.WriteLine($"Successfully deleted {movieToDelete.Title}.");
        }
        else
        {
            Console.WriteLine($"Could not delete {movieToDelete.Title}.");
        }

        WaitForEnter();

        // Use Query to find all the movies released in 2010.
        int findYear = 2010;
        Console.WriteLine($"Movies released in {findYear}");
        var queryCount = await dynamoDbWrapper.QueryMoviesAsync(tableName, findYear);
        Console.WriteLine($"Found {queryCount} movies released in {findYear}");

        WaitForEnter();

        // Use Scan to get a list of movies from 2001 to 2011.
        int startYear = 2001;
        int endYear = 2011;
        var scanCount = await dynamoDbWrapper.ScanTableAsync(tableName, startYear, endYear);
        Console.WriteLine($"Found {scanCount} movies released between {startYear} and {endYear}");

        WaitForEnter();

        // Delete the table.
        success = await dynamoDbWrapper.DeleteTableAsync(tableName);

        if (success)
        {
            Console.WriteLine($"Successfully deleted {tableName}");
        }
        else
        {
            Console.WriteLine($"Could not delete {tableName}");
        }

        Console.WriteLine("The DynamoDB Basics example application is complete.");

        WaitForEnter();
    }

    /// <summary>
    /// Displays the description of the application on the console.
    /// </summary>
    private static void DisplayInstructions()
    {
        if (!IsInteractive)
        {
            return;
        }

        Console.Clear();
        Console.WriteLine();
        Console.Write(new string(' ', 28));
        Console.WriteLine("DynamoDB Basics Example");
        Console.WriteLine(SepBar);
        Console.WriteLine("This demo application shows the basics of using DynamoDB with the AWS SDK.");
        Console.WriteLine(SepBar);
        Console.WriteLine("The application does the following:");
        Console.WriteLine("\t1. Creates a table with partition: year and sort:title.");
        Console.WriteLine("\t2. Adds a single movie to the table.");
        Console.WriteLine("\t3. Adds movies to the table from moviedata.json.");
        Console.WriteLine("\t4. Updates the rating and plot of the movie that was just added.");
        Console.WriteLine("\t5. Gets a movie using its key (partition + sort).");
        Console.WriteLine("\t6. Deletes a movie.");
        Console.WriteLine("\t7. Uses QueryAsync to return all movies released in a given year.");
        Console.WriteLine("\t8. Uses ScanAsync to return all movies released within a range of years.");
        Console.WriteLine("\t9. Finally, it deletes the table that was just created.");
        WaitForEnter();
    }

    /// <summary>
    /// Simple method to wait for the Enter key to be pressed.
    /// </summary>
    private static void WaitForEnter()
    {
        if (IsInteractive)
        {
            Console.WriteLine("\nPress <Enter> to continue.");
            Console.WriteLine(SepBar);
            _ = Console.ReadLine();
        }
    }
}
```
挿入されたクライアントをテーブルオペレーションに使用します。  

```
using System.Text.Json;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;

namespace DynamoDBActions;

/// <summary>
/// Methods of this class perform Amazon DynamoDB operations.
/// </summary>
public class DynamoDbWrapper
{
    private readonly IAmazonDynamoDB _amazonDynamoDB;

    /// <summary>
    /// Constructor for the DynamoDbWrapper class.
    /// </summary>
    /// <param name="amazonDynamoDB">The injected DynamoDB client.</param>
    public DynamoDbWrapper(IAmazonDynamoDB amazonDynamoDB)
    {
        _amazonDynamoDB = amazonDynamoDB;
    }
```
ムービーデータを含めるテーブルを作成します。  

```
    /// <summary>
    /// Creates a new Amazon DynamoDB table and then waits for the new
    /// table to become active.
    /// </summary>
    /// <param name="tableName">The name of the table to create.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> CreateMovieTableAsync(string tableName)
    {
        try
        {
            var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                {
                    new AttributeDefinition
                    {
                        AttributeName = "title",
                        AttributeType = ScalarAttributeType.S,
                    },
                    new AttributeDefinition
                    {
                        AttributeName = "year",
                        AttributeType = ScalarAttributeType.N,
                    },
                },
                KeySchema = new List<KeySchemaElement>()
                {
                    new KeySchemaElement
                    {
                        AttributeName = "year",
                        KeyType = KeyType.HASH,
                    },
                    new KeySchemaElement
                    {
                        AttributeName = "title",
                        KeyType = KeyType.RANGE,
                    },
                },
                BillingMode = BillingMode.PAY_PER_REQUEST,
            });

            // Wait until the table is ACTIVE and then report success.
            Console.Write("Waiting for table to become active...");

            var request = new DescribeTableRequest
            {
                TableName = response.TableDescription.TableName,
            };

            TableStatus status;

            int sleepDuration = 2000;

            do
            {
                Thread.Sleep(sleepDuration);

                var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request);
                status = describeTableResponse.Table.TableStatus;

                Console.Write(".");
            }
            while (status != "ACTIVE");

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException ex)
        {
            Console.WriteLine($"Table {tableName} already exists. {ex.Message}");
            throw;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
    }
```
1 つのムービーをテーブルに追加します。  

```
    /// <summary>
    /// Adds a new item to the table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing informtation for
    /// the movie to add to the table.</param>
    /// <param name="tableName">The name of the table where the item will be added.</param>
    /// <returns>A Boolean value that indicates the results of adding the item.</returns>
    public async Task<bool> PutItemAsync(Movie newMovie, string tableName)
    {
        try
        {
            var item = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };

            var request = new PutItemRequest
            {
                TableName = tableName,
                Item = item,
            };

            await _amazonDynamoDB.PutItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while putting item. {ex.Message}");
            throw;
        }
    }
```
テーブルの 1 つの項目を更新します。  

```
    /// <summary>
    /// Updates an existing item in the movies table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing information for
    /// the movie to update.</param>
    /// <param name="newInfo">A MovieInfo object that contains the
    /// information that will be changed.</param>
    /// <param name="tableName">The name of the table that contains the movie.</param>
    /// <returns>A Boolean value that indicates the success of the operation.</returns>
    public async Task<bool> UpdateItemAsync(
        Movie newMovie,
        MovieInfo newInfo,
        string tableName)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };
            var updates = new Dictionary<string, AttributeValueUpdate>
            {
                ["info.plot"] = new AttributeValueUpdate
                {
                    Action = AttributeAction.PUT,
                    Value = new AttributeValue { S = newInfo.Plot },
                },

                ["info.rating"] = new AttributeValueUpdate
                {
                    Action = AttributeAction.PUT,
                    Value = new AttributeValue { N = newInfo.Rank.ToString() },
                },
            };

            var request = new UpdateItemRequest
            {
                AttributeUpdates = updates,
                Key = key,
                TableName = tableName,
            };

            await _amazonDynamoDB.UpdateItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while updating item. {ex.Message}");
            throw;
        }
    }
```
ムービーテーブルから 1 つの項目を取得します。  

```
    /// <summary>
    /// Gets information about an existing movie from the table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing information about
    /// the movie to retrieve.</param>
    /// <param name="tableName">The name of the table containing the movie.</param>
    /// <returns>A Dictionary object containing information about the item
    /// retrieved.</returns>
    public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };

            var request = new GetItemRequest
            {
                Key = key,
                TableName = tableName,
            };

            var response = await _amazonDynamoDB.GetItemAsync(request);
            return response.Item;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return new Dictionary<string, AttributeValue>();
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while getting item. {ex.Message}");
            throw;
        }
    }
```
項目のバッチをムービーテーブルに書き込みます。  

```
    /// <summary>
    /// Loads the contents of a JSON file into a list of movies to be
    /// added to the DynamoDB table.
    /// </summary>
    /// <param name="movieFileName">The name of the JSON file.</param>
    /// <returns>A generic list of movie objects.</returns>
    public List<Movie> ImportMovies(string movieFileName)
    {
        var moviesList = new List<Movie>();
        if (!File.Exists(movieFileName))
        {
            return moviesList;
        }

        using var sr = new StreamReader(movieFileName);
        string json = sr.ReadToEnd();
        var allMovies = JsonSerializer.Deserialize<List<Movie>>(
            json,
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

        // Now return the first 250 entries.
        if (allMovies != null && allMovies.Any())
        {
            moviesList = allMovies.GetRange(0, 250);
        }
        return moviesList;
    }

    /// <summary>
    /// Writes 250 items to the movie table.
    /// </summary>
    /// <param name="movieFileName">A string containing the full path to
    /// the JSON file containing movie data.</param>
    /// <param name="tableName">The name of the table to write items to.</param>
    /// <returns>A long integer value representing the number of movies
    /// imported from the JSON file.</returns>
    public async Task<long> BatchWriteItemsAsync(
        string movieFileName, string tableName)
    {
        try
        {
            var movies = ImportMovies(movieFileName);
            if (!movies.Any())
            {
                Console.WriteLine("Couldn't find the JSON file with movie data.");
                return 0;
            }

            var context = new DynamoDBContextBuilder()
                // Optional call to provide a specific instance of IAmazonDynamoDB
                .WithDynamoDBClient(() => _amazonDynamoDB)
                .Build();

            var movieBatch = context.CreateBatchWrite<Movie>(
                new BatchWriteConfig()
                {
                    OverrideTableName = tableName
                });
            movieBatch.AddPutItems(movies);

            Console.WriteLine("Adding imported movies to the table.");
            await movieBatch.ExecuteAsync();

            return movies.Count;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table was not found during batch write operation. {ex.Message}");
            throw;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred during batch write operation. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred during batch write operation. {ex.Message}");
            throw;
        }
    }
```
テーブルから 1 つの項目を削除します。  

```
    /// <summary>
    /// Deletes a single item from a DynamoDB table.
    /// </summary>
    /// <param name="tableName">The name of the table from which the item
    /// will be deleted.</param>
    /// <param name="movieToDelete">A movie object containing the title and
    /// year of the movie to delete.</param>
    /// <returns>A Boolean value indicating the success or failure of the
    /// delete operation.</returns>
    public async Task<bool> DeleteItemAsync(
        string tableName,
        Movie movieToDelete)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = movieToDelete.Title },
                ["year"] = new AttributeValue { N = movieToDelete.Year.ToString() },
            };

            var request = new DeleteItemRequest { TableName = tableName, Key = key, };

            await _amazonDynamoDB.DeleteItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while deleting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting item. {ex.Message}");
            throw;
        }
    }
```
特定の年にリリースされたムービーのテーブルにクエリを実行します。  

```
    /// <summary>
    /// Queries the table for movies released in a particular year and
    /// then displays the information for the movies returned.
    /// </summary>
    /// <param name="tableName">The name of the table to query.</param>
    /// <param name="year">The release year for which we want to
    /// view movies.</param>
    /// <returns>The number of movies that match the query.</returns>
    public async Task<int> QueryMoviesAsync(string tableName, int year)
    {
        try
        {
            var movieTable = new TableBuilder(_amazonDynamoDB, tableName)
                .AddHashKey("year", DynamoDBEntryType.Numeric)
                .AddRangeKey("title", DynamoDBEntryType.String)
                .Build();

            var filter = new QueryFilter("year", QueryOperator.Equal, year);

            Console.WriteLine("\nFind movies released in: {year}:");

            var config = new QueryOperationConfig()
            {
                Limit = 10, // 10 items per page.
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string>
                {
                    "title",
                    "year",
                },
                ConsistentRead = true,
                Filter = filter,
            };

            // Value used to track how many movies match the
            // supplied criteria.
            var moviesFound = 0;

            var search = movieTable.Query(config);
            do
            {
                var movieList = await search.GetNextSetAsync();
                moviesFound += movieList.Count;

                foreach (var movie in movieList)
                {
                    DisplayDocument(movie);
                }
            }
            while (!search.IsDone);

            return moviesFound;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return 0;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while querying movies. {ex.Message}");
            throw;
        }
    }
```
数年にわたってリリースされたムービーのテーブルをスキャンします。  

```
    /// <summary>
    /// Scans the table for movies released between the specified years.
    /// </summary>
    /// <param name="tableName">The name of the table to scan.</param>
    /// <param name="startYear">The starting year for the range.</param>
    /// <param name="endYear">The ending year for the range.</param>
    /// <returns>The number of movies found in the specified year range.</returns>
    public async Task<int> ScanTableAsync(
        string tableName,
        int startYear,
        int endYear)
    {
        try
        {
            var request = new ScanRequest
            {
                TableName = tableName,
                ExpressionAttributeNames = new Dictionary<string, string>
                {
                    { "#yr", "year" },
                },
                ExpressionAttributeValues = new Dictionary<string, AttributeValue>
                {
                    { ":y_a", new AttributeValue { N = startYear.ToString() } },
                    { ":y_z", new AttributeValue { N = endYear.ToString() } },
                },
                FilterExpression = "#yr between :y_a and :y_z",
                ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs",
                Limit = 10 // Set a limit to demonstrate using the LastEvaluatedKey.
            };

            // Keep track of how many movies were found.
            int foundCount = 0;

            var response = new ScanResponse();
            do
            {
                response = await _amazonDynamoDB.ScanAsync(request);
                foundCount += response.Items.Count;
                response.Items.ForEach(i => DisplayItem(i));
                request.ExclusiveStartKey = response.LastEvaluatedKey;
            }
            while (response?.LastEvaluatedKey?.Count > 0);
            return foundCount;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return 0;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while scanning table. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while scanning table. {ex.Message}");
            throw;
        }
    }
```
ムービーテーブルを削除します。  

```
    /// <summary>
    /// Deletes a DynamoDB table.
    /// </summary>
    /// <param name="tableName">The name of the table to delete.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> DeleteTableAsync(string tableName)
    {
        try
        {
            var request = new DeleteTableRequest
            {
                TableName = tableName,
            };

            var response = await _amazonDynamoDB.DeleteTableAsync(request);

            Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
    }
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/BatchWriteItem)
  + [CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/CreateTable)
  + [DeleteItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteItem)
  + [DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Scan)
  + [UpdateItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/UpdateItem)

## アクション
<a name="actions"></a>

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_csharp_4_topic"></a>

次の例は、`BatchWriteItem` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。
項目のバッチをムービーテーブルに書き込みます。  

```
    /// <summary>
    /// Loads the contents of a JSON file into a list of movies to be
    /// added to the DynamoDB table.
    /// </summary>
    /// <param name="movieFileName">The name of the JSON file.</param>
    /// <returns>A generic list of movie objects.</returns>
    public List<Movie> ImportMovies(string movieFileName)
    {
        var moviesList = new List<Movie>();
        if (!File.Exists(movieFileName))
        {
            return moviesList;
        }

        using var sr = new StreamReader(movieFileName);
        string json = sr.ReadToEnd();
        var allMovies = JsonSerializer.Deserialize<List<Movie>>(
            json,
            new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            });

        // Now return the first 250 entries.
        if (allMovies != null && allMovies.Any())
        {
            moviesList = allMovies.GetRange(0, 250);
        }
        return moviesList;
    }

    /// <summary>
    /// Writes 250 items to the movie table.
    /// </summary>
    /// <param name="movieFileName">A string containing the full path to
    /// the JSON file containing movie data.</param>
    /// <param name="tableName">The name of the table to write items to.</param>
    /// <returns>A long integer value representing the number of movies
    /// imported from the JSON file.</returns>
    public async Task<long> BatchWriteItemsAsync(
        string movieFileName, string tableName)
    {
        try
        {
            var movies = ImportMovies(movieFileName);
            if (!movies.Any())
            {
                Console.WriteLine("Couldn't find the JSON file with movie data.");
                return 0;
            }

            var context = new DynamoDBContextBuilder()
                // Optional call to provide a specific instance of IAmazonDynamoDB
                .WithDynamoDBClient(() => _amazonDynamoDB)
                .Build();

            var movieBatch = context.CreateBatchWrite<Movie>(
                new BatchWriteConfig()
                {
                    OverrideTableName = tableName
                });
            movieBatch.AddPutItems(movies);

            Console.WriteLine("Adding imported movies to the table.");
            await movieBatch.ExecuteAsync();

            return movies.Count;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table was not found during batch write operation. {ex.Message}");
            throw;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred during batch write operation. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred during batch write operation. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[BatchWriteItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。**

### `CreateTable`
<a name="dynamodb_CreateTable_csharp_4_topic"></a>

次の例は、`CreateTable` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates a new Amazon DynamoDB table and then waits for the new
    /// table to become active.
    /// </summary>
    /// <param name="tableName">The name of the table to create.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> CreateMovieTableAsync(string tableName)
    {
        try
        {
            var response = await _amazonDynamoDB.CreateTableAsync(new CreateTableRequest
            {
                TableName = tableName,
                AttributeDefinitions = new List<AttributeDefinition>()
                {
                    new AttributeDefinition
                    {
                        AttributeName = "title",
                        AttributeType = ScalarAttributeType.S,
                    },
                    new AttributeDefinition
                    {
                        AttributeName = "year",
                        AttributeType = ScalarAttributeType.N,
                    },
                },
                KeySchema = new List<KeySchemaElement>()
                {
                    new KeySchemaElement
                    {
                        AttributeName = "year",
                        KeyType = KeyType.HASH,
                    },
                    new KeySchemaElement
                    {
                        AttributeName = "title",
                        KeyType = KeyType.RANGE,
                    },
                },
                BillingMode = BillingMode.PAY_PER_REQUEST,
            });

            // Wait until the table is ACTIVE and then report success.
            Console.Write("Waiting for table to become active...");

            var request = new DescribeTableRequest
            {
                TableName = response.TableDescription.TableName,
            };

            TableStatus status;

            int sleepDuration = 2000;

            do
            {
                Thread.Sleep(sleepDuration);

                var describeTableResponse = await _amazonDynamoDB.DescribeTableAsync(request);
                status = describeTableResponse.Table.TableStatus;

                Console.Write(".");
            }
            while (status != "ACTIVE");

            return status == TableStatus.ACTIVE;
        }
        catch (ResourceInUseException ex)
        {
            Console.WriteLine($"Table {tableName} already exists. {ex.Message}");
            throw;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while creating table {tableName}. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[CreateTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_csharp_4_topic"></a>

次の例は、`DeleteItem` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes a single item from a DynamoDB table.
    /// </summary>
    /// <param name="tableName">The name of the table from which the item
    /// will be deleted.</param>
    /// <param name="movieToDelete">A movie object containing the title and
    /// year of the movie to delete.</param>
    /// <returns>A Boolean value indicating the success or failure of the
    /// delete operation.</returns>
    public async Task<bool> DeleteItemAsync(
        string tableName,
        Movie movieToDelete)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = movieToDelete.Title },
                ["year"] = new AttributeValue { N = movieToDelete.Year.ToString() },
            };

            var request = new DeleteItemRequest { TableName = tableName, Key = key, };

            await _amazonDynamoDB.DeleteItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while deleting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting item. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DeleteItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteItem)」を参照してください。**

### `DeleteTable`
<a name="dynamodb_DeleteTable_csharp_4_topic"></a>

次の例は、`DeleteTable` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes a DynamoDB table.
    /// </summary>
    /// <param name="tableName">The name of the table to delete.</param>
    /// <returns>A Boolean value indicating the success of the operation.</returns>
    public async Task<bool> DeleteTableAsync(string tableName)
    {
        try
        {
            var request = new DeleteTableRequest
            {
                TableName = tableName,
            };

            var response = await _amazonDynamoDB.DeleteTableAsync(request);

            Console.WriteLine($"Table {response.TableDescription.TableName} successfully deleted.");
            return true;

        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found and cannot be deleted. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while deleting table {tableName}. {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_csharp_4_topic"></a>

次の例は、`GetItem` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Gets information about an existing movie from the table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing information about
    /// the movie to retrieve.</param>
    /// <param name="tableName">The name of the table containing the movie.</param>
    /// <returns>A Dictionary object containing information about the item
    /// retrieved.</returns>
    public async Task<Dictionary<string, AttributeValue>> GetItemAsync(Movie newMovie, string tableName)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };

            var request = new GetItemRequest
            {
                Key = key,
                TableName = tableName,
            };

            var response = await _amazonDynamoDB.GetItemAsync(request);
            return response.Item;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return new Dictionary<string, AttributeValue>();
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while getting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while getting item. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/GetItem)」を参照してください。**

### `PutItem`
<a name="dynamodb_PutItem_csharp_4_topic"></a>

次の例は、`PutItem` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Adds a new item to the table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing informtation for
    /// the movie to add to the table.</param>
    /// <param name="tableName">The name of the table where the item will be added.</param>
    /// <returns>A Boolean value that indicates the results of adding the item.</returns>
    public async Task<bool> PutItemAsync(Movie newMovie, string tableName)
    {
        try
        {
            var item = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };

            var request = new PutItemRequest
            {
                TableName = tableName,
                Item = item,
            };

            await _amazonDynamoDB.PutItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while putting item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while putting item. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/PutItem)」を参照してください。**

### `Query`
<a name="dynamodb_Query_csharp_4_topic"></a>

次の例は、`Query` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Queries the table for movies released in a particular year and
    /// then displays the information for the movies returned.
    /// </summary>
    /// <param name="tableName">The name of the table to query.</param>
    /// <param name="year">The release year for which we want to
    /// view movies.</param>
    /// <returns>The number of movies that match the query.</returns>
    public async Task<int> QueryMoviesAsync(string tableName, int year)
    {
        try
        {
            var movieTable = new TableBuilder(_amazonDynamoDB, tableName)
                .AddHashKey("year", DynamoDBEntryType.Numeric)
                .AddRangeKey("title", DynamoDBEntryType.String)
                .Build();

            var filter = new QueryFilter("year", QueryOperator.Equal, year);

            Console.WriteLine("\nFind movies released in: {year}:");

            var config = new QueryOperationConfig()
            {
                Limit = 10, // 10 items per page.
                Select = SelectValues.SpecificAttributes,
                AttributesToGet = new List<string>
                {
                    "title",
                    "year",
                },
                ConsistentRead = true,
                Filter = filter,
            };

            // Value used to track how many movies match the
            // supplied criteria.
            var moviesFound = 0;

            var search = movieTable.Query(config);
            do
            {
                var movieList = await search.GetNextSetAsync();
                moviesFound += movieList.Count;

                foreach (var movie in movieList)
                {
                    DisplayDocument(movie);
                }
            }
            while (!search.IsDone);

            return moviesFound;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return 0;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while querying movies. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while querying movies. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[Query](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Query)」を参照してください。**

### `Scan`
<a name="dynamodb_Scan_csharp_4_topic"></a>

次の例は、`Scan` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Scans the table for movies released between the specified years.
    /// </summary>
    /// <param name="tableName">The name of the table to scan.</param>
    /// <param name="startYear">The starting year for the range.</param>
    /// <param name="endYear">The ending year for the range.</param>
    /// <returns>The number of movies found in the specified year range.</returns>
    public async Task<int> ScanTableAsync(
        string tableName,
        int startYear,
        int endYear)
    {
        try
        {
            var request = new ScanRequest
            {
                TableName = tableName,
                ExpressionAttributeNames = new Dictionary<string, string>
                {
                    { "#yr", "year" },
                },
                ExpressionAttributeValues = new Dictionary<string, AttributeValue>
                {
                    { ":y_a", new AttributeValue { N = startYear.ToString() } },
                    { ":y_z", new AttributeValue { N = endYear.ToString() } },
                },
                FilterExpression = "#yr between :y_a and :y_z",
                ProjectionExpression = "#yr, title, info.actors[0], info.directors, info.running_time_secs",
                Limit = 10 // Set a limit to demonstrate using the LastEvaluatedKey.
            };

            // Keep track of how many movies were found.
            int foundCount = 0;

            var response = new ScanResponse();
            do
            {
                response = await _amazonDynamoDB.ScanAsync(request);
                foundCount += response.Items.Count;
                response.Items.ForEach(i => DisplayItem(i));
                request.ExclusiveStartKey = response.LastEvaluatedKey;
            }
            while (response?.LastEvaluatedKey?.Count > 0);
            return foundCount;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} was not found. {ex.Message}");
            return 0;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while scanning table. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while scanning table. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[Scan](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/Scan)」を参照してください。**

### `UpdateItem`
<a name="dynamodb_UpdateItem_csharp_4_topic"></a>

次の例は、`UpdateItem` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/DynamoDB#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Updates an existing item in the movies table.
    /// </summary>
    /// <param name="newMovie">A Movie object containing information for
    /// the movie to update.</param>
    /// <param name="newInfo">A MovieInfo object that contains the
    /// information that will be changed.</param>
    /// <param name="tableName">The name of the table that contains the movie.</param>
    /// <returns>A Boolean value that indicates the success of the operation.</returns>
    public async Task<bool> UpdateItemAsync(
        Movie newMovie,
        MovieInfo newInfo,
        string tableName)
    {
        try
        {
            var key = new Dictionary<string, AttributeValue>
            {
                ["title"] = new AttributeValue { S = newMovie.Title },
                ["year"] = new AttributeValue { N = newMovie.Year.ToString() },
            };
            var updates = new Dictionary<string, AttributeValueUpdate>
            {
                ["info.plot"] = new AttributeValueUpdate
                {
                    Action = AttributeAction.PUT,
                    Value = new AttributeValue { S = newInfo.Plot },
                },

                ["info.rating"] = new AttributeValueUpdate
                {
                    Action = AttributeAction.PUT,
                    Value = new AttributeValue { N = newInfo.Rank.ToString() },
                },
            };

            var request = new UpdateItemRequest
            {
                AttributeUpdates = updates,
                Key = key,
                TableName = tableName,
            };

            await _amazonDynamoDB.UpdateItemAsync(request);
            return true;
        }
        catch (ResourceNotFoundException ex)
        {
            Console.WriteLine($"Table {tableName} or item was not found. {ex.Message}");
            return false;
        }
        catch (AmazonDynamoDBException ex)
        {
            Console.WriteLine($"An Amazon DynamoDB error occurred while updating item. {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while updating item. {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの**「[UpdateItem](https://docs.aws.amazon.com/goto/DotNetSDKV4/dynamodb-2012-08-10/UpdateItem)」を参照してください。

# SDK for .NET (v4) を使用した Amazon EC2 の例
<a name="csharp_4_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_csharp_4_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/EC2#code-examples)での設定と実行の方法を確認してください。

```
namespace EC2Actions;

public class HelloEc2
{
    /// <summary>
    /// HelloEc2 lists the existing security groups for the default users.
    /// </summary>
    /// <param name="args">Command line arguments</param>
    /// <returns>Async task.</returns>
    static async Task Main(string[] args)
    {
        // Set up dependency injection for Amazon Elastic Compute Cloud (Amazon EC2).
        using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonEC2>()
                .AddTransient<EC2Wrapper>()
            )
            .Build();

        // Now the client is available for injection.
        var ec2Client = host.Services.GetRequiredService<IAmazonEC2>();

        try
        {
            // Retrieve information for up to 10 Amazon EC2 security groups.
            var request = new DescribeSecurityGroupsRequest { MaxResults = 10 };
            var securityGroups = new List<SecurityGroup>();

            var paginatorForSecurityGroups =
                ec2Client.Paginators.DescribeSecurityGroups(request);

            await foreach (var securityGroup in paginatorForSecurityGroups.SecurityGroups)
            {
                securityGroups.Add(securityGroup);
            }

            // Now print the security groups returned by the call to
            // DescribeSecurityGroupsAsync.
            Console.WriteLine("Welcome to the EC2 Hello Service example. " +
                              "\nLet's list your Security Groups:");
            securityGroups.ForEach(group =>
            {
                Console.WriteLine(
                    $"Security group: {group.GroupName} ID: {group.GroupId}");
            });
        }
        catch (AmazonEC2Exception ex)
        {
            Console.WriteLine($"An Amazon EC2 service error occurred while listing security groups. {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred while listing security groups. {ex.Message}");
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/DotNetSDKV4/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

# SDK for .NET (v4) を使用した Amazon ECS の例
<a name="csharp_4_ecs_code_examples"></a>

次のコード例は、Amazon ECS で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)

## はじめに
<a name="get_started"></a>

### Hello Amazon ECS
<a name="ecs_Hello_csharp_4_topic"></a>

次のコード例は、Amazon ECS の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/ECS#code-examples)での設定と実行の方法を確認してください。

```
using Amazon.ECS;
using Amazon.ECS.Model;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.Extensions.Logging.Debug;

namespace ECSActions;

/// <summary>
/// A class that introduces the Amazon ECS Client by listing the
/// cluster ARNs for the account.
/// </summary>
public class HelloECS
{
    static async System.Threading.Tasks.Task Main(string[] args)
    {
        // Use the AWS .NET Core Setup package to set up dependency injection for the Amazon ECS client.
        // Use your AWS profile name, or leave it blank to use the default profile.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureLogging(logging =>
                logging.AddFilter("System", LogLevel.Debug)
                    .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information)
                    .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace))
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonECS>()
            )
            .Build();

        var amazonECSClient = host.Services.GetRequiredService<IAmazonECS>();

        Console.WriteLine($"Hello Amazon ECS! Following are some cluster ARNS available in the your account");
        Console.WriteLine();

        var clusters = new List<string>();

        var clustersPaginator = amazonECSClient.Paginators.ListClusters(new ListClustersRequest());

        await foreach (var response in clustersPaginator.Responses)
        {
            clusters.AddRange(response.ClusterArns);
        }

        if (clusters.Count > 0)
        {
            clusters.ForEach(cluster =>
            {
                Console.WriteLine($"\tARN: {cluster}");
                Console.WriteLine($"Cluster Name: {cluster.Split("/").Last()}");
                Console.WriteLine();
            });
        }
        else
        {
            Console.WriteLine("No clusters were found.");
        }

    }
}
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」の「[ListClusters](https://docs.aws.amazon.com/goto/DotNetSDKV4/ecs-2014-11-13/ListClusters)」を参照してください。

# AWS IoT SDK for .NET (v4) を使用した例
<a name="csharp_4_iot_code_examples"></a>

次のコード例は、 で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoTは
<a name="iot_Hello_csharp_4_topic"></a>

次のコード例は、 AWS IoTの使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
/// <summary>
/// Hello AWS IoT example.
/// </summary>
public class HelloIoT
{
    /// <summary>
    /// Main method to run the Hello IoT example.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    /// <returns>A Task object.</returns>
    public static async Task Main(string[] args)
    {
        var iotClient = new AmazonIoTClient();

        try
        {
            Console.WriteLine("Hello AWS IoT! Let's list your IoT Things:");
            Console.WriteLine(new string('-', 80));

            // Use pages of 10.
            var request = new ListThingsRequest()
            {
                MaxResults = 10
            };
            var response = await iotClient.ListThingsAsync(request);

            // Since there is not a built-in paginator, use the NextMarker to paginate.
            bool hasMoreResults = true;

            var things = new List<ThingAttribute>();
            while (hasMoreResults)
            {
                things.AddRange(response.Things);

                // If NextMarker is not null, there are more results. Get the next page of results.
                if (!String.IsNullOrEmpty(response.NextMarker))
                {
                    request.Marker = response.NextMarker;
                    response = await iotClient.ListThingsAsync(request);
                }
                else
                    hasMoreResults = false;
            }

            if (things is { Count: > 0 })
            {
                Console.WriteLine($"Found {things.Count} IoT Things:");
                foreach (var thing in things)
                {
                    Console.WriteLine($"- Thing Name: {thing.ThingName}");
                    Console.WriteLine($"  Thing ARN: {thing.ThingArn}");
                    Console.WriteLine($"  Thing Type: {thing.ThingTypeName ?? "No type specified"}");
                    Console.WriteLine($"  Version: {thing.Version}");

                    if (thing.Attributes?.Count > 0)
                    {
                        Console.WriteLine("  Attributes:");
                        foreach (var attr in thing.Attributes)
                        {
                            Console.WriteLine($"    {attr.Key}: {attr.Value}");
                        }
                    }
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("No IoT Things found in your account.");
                Console.WriteLine("You can create IoT Things using the IoT Basics scenario example.");
            }

            Console.WriteLine("Hello IoT completed successfully.");
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            Console.WriteLine($"Request throttled, please try again later: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't list Things. Here's why: {ex.Message}");
        }
    }
}
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[listThings](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/listThings)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iot_Scenario_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT モノを作成します。
+ デバイス証明書を生成します。
+ 属性を使用して AWS IoT モノを更新します。
+ 一意のエンドポイントを返します。
+  AWS IoT 証明書を一覧表示します。
+  AWS IoT シャドウを更新します。
+ 状態情報を書き込みます。
+ ルールを作成する｡
+ ルールを一覧表示します。
+ モノの名前を使用してモノを検索します。
+  AWS IoT モノを削除します。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。
 AWS IoT 機能を示すインタラクティブなシナリオを実行します。  

```
/// <summary>
/// Scenario class for AWS IoT basics.
/// </summary>
public class IoTBasics
{
    public static bool IsInteractive = true;
    public static IoTWrapper? Wrapper = null;
    public static IAmazonCloudFormation? CloudFormationClient = null;
    public static ILogger<IoTBasics> logger = null!;
    private static IoTWrapper _iotWrapper = null!;
    private static IAmazonCloudFormation _amazonCloudFormation = null!;
    private static ILogger<IoTBasics> _logger = null!;

    private static string _stackName = "IoTBasicsStack";
    private static string _stackResourcePath = "../../../../../../scenarios/basics/iot/iot_usecase/resources/cfn_template.yaml";

    /// <summary>
    /// Main method for the IoT Basics scenario.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    /// <returns>A Task object.</returns>
    public static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonIoT>(new AWSOptions() { Region = RegionEndpoint.USEast1 })
                    .AddAWSService<IAmazonCloudFormation>()
                        .AddTransient<IoTWrapper>()
                        .AddLogging(builder => builder.AddConsole())
                        .AddSingleton<IAmazonIotData>(sp =>
                        {
                            var iotService = sp.GetRequiredService<IAmazonIoT>();
                            var request = new DescribeEndpointRequest
                            {
                                EndpointType = "iot:Data-ATS"
                            };
                            var response = iotService.DescribeEndpointAsync(request).Result;
                            return new AmazonIotDataClient($"https://{response.EndpointAddress}/");
                        })
            )
            .Build();

        logger = LoggerFactory.Create(builder => builder.AddConsole())
            .CreateLogger<IoTBasics>();

        Wrapper = host.Services.GetRequiredService<IoTWrapper>();
        CloudFormationClient = host.Services.GetRequiredService<IAmazonCloudFormation>();

        // Set the private fields for backwards compatibility
        _logger = logger;
        _iotWrapper = Wrapper;
        _amazonCloudFormation = CloudFormationClient;

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("Welcome to the AWS IoT example scenario.");
        Console.WriteLine("This example program demonstrates various interactions with the AWS Internet of Things (IoT) Core service.");
        Console.WriteLine();
        if (IsInteractive)
        {
            Console.WriteLine("Press Enter to continue...");
            Console.ReadLine();
        }
        Console.WriteLine(new string('-', 80));

        try
        {
            await RunScenarioAsync();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "There was a problem running the scenario.");
            Console.WriteLine($"\nAn error occurred: {ex.Message}");
        }

        Console.WriteLine(new string('-', 80));
        Console.WriteLine("The AWS IoT scenario has successfully completed.");
        Console.WriteLine(new string('-', 80));
    }

    /// <summary>
    /// Run the IoT Basics scenario.
    /// </summary>
    /// <returns>A Task object.</returns>
    public static async Task RunScenarioAsync()
    {
        // Use static properties if available, otherwise use private fields
        var iotWrapper = Wrapper ?? _iotWrapper;
        var cloudFormationClient = CloudFormationClient ?? _amazonCloudFormation;
        var scenarioLogger = logger ?? _logger;

        await RunScenarioInternalAsync(iotWrapper, cloudFormationClient, scenarioLogger);
    }

    /// <summary>
    /// Internal method to run the IoT Basics scenario with injected dependencies.
    /// </summary>
    /// <param name="iotWrapper">The IoT wrapper instance.</param>
    /// <param name="cloudFormationClient">The CloudFormation client instance.</param>
    /// <param name="scenarioLogger">The logger instance.</param>
    /// <returns>A Task object.</returns>
    private static async Task RunScenarioInternalAsync(IoTWrapper iotWrapper, IAmazonCloudFormation cloudFormationClient, ILogger<IoTBasics> scenarioLogger)
    {
        string thingName = $"iot-thing-{Guid.NewGuid():N}";
        string certificateArn = "";
        string certificateId = "";
        string ruleName = $"iotruledefault";
        string snsTopicArn = "";

        try
        {
            // Step 1: Create an AWS IoT Thing
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("1. Create an AWS IoT Thing.");
            Console.WriteLine("An AWS IoT Thing represents a virtual entity in the AWS IoT service that can be associated with a physical device.");
            Console.WriteLine();

            if (IsInteractive)
            {
                Console.Write("Enter Thing name: ");
                var userInput = Console.ReadLine();
                if (!string.IsNullOrEmpty(userInput))
                    thingName = userInput;
            }
            else
            {
                Console.WriteLine($"Using default Thing name: {thingName}");
            }

            var thingArn = await iotWrapper.CreateThingAsync(thingName);
            Console.WriteLine($"{thingName} was successfully created. The ARN value is {thingArn}");
            Console.WriteLine(new string('-', 80));

            // Step 1.1: List AWS IoT Things
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("2. List AWS IoT Things.");
            Console.WriteLine("Now let's list the IoT Things to see the Thing we just created.");
            Console.WriteLine();
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var things = await iotWrapper.ListThingsAsync();
            Console.WriteLine($"Found {things.Count} IoT Things:");
            foreach (var thing in things.Take(10)) // Show first 10 things
            {
                Console.WriteLine($"Thing Name: {thing.ThingName}");
                Console.WriteLine($"Thing ARN: {thing.ThingArn}");
                if (thing.Attributes != null && thing.Attributes.Any())
                {
                    Console.WriteLine("Attributes:");
                    foreach (var attr in thing.Attributes)
                    {
                        Console.WriteLine($"  {attr.Key}: {attr.Value}");
                    }
                }
                Console.WriteLine("--------------");
            }
            Console.WriteLine();
            Console.WriteLine(new string('-', 80));

            // Step 2: Generate a Device Certificate
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("3. Generate a device certificate.");
            Console.WriteLine("A device certificate performs a role in securing the communication between devices (Things) and the AWS IoT platform.");
            Console.WriteLine();

            var createCert = "y";
            if (IsInteractive)
            {
                Console.Write($"Do you want to create a certificate for {thingName}? (y/n)");
                createCert = Console.ReadLine();
            }
            else
            {
                Console.WriteLine($"Creating certificate for {thingName}...");
            }

            if (createCert?.ToLower() == "y")
            {
                var certificateResult = await iotWrapper.CreateKeysAndCertificateAsync();
                if (certificateResult.HasValue)
                {
                    var (certArn, certPem, certId) = certificateResult.Value;
                    certificateArn = certArn;
                    certificateId = certId;

                    Console.WriteLine($"\nCertificate:");
                    // Show only first few lines of certificate for brevity
                    var lines = certPem.Split('\n');
                    for (int i = 0; i < Math.Min(lines.Length, 5); i++)
                    {
                        Console.WriteLine(lines[i]);
                    }
                    if (lines.Length > 5)
                    {
                        Console.WriteLine("...");
                    }

                    Console.WriteLine($"\nCertificate ARN:");
                    Console.WriteLine(certificateArn);

                    // Step 3: Attach the Certificate to the AWS IoT Thing
                    Console.WriteLine("Attach the certificate to the AWS IoT Thing.");
                    var attachResult = await iotWrapper.AttachThingPrincipalAsync(thingName, certificateArn);
                    if (attachResult)
                    {
                        Console.WriteLine("Certificate attached to Thing successfully.");
                    }
                    else
                    {
                        Console.WriteLine("Failed to attach certificate to Thing.");
                    }

                    Console.WriteLine("Thing Details:");
                    Console.WriteLine($"Thing Name: {thingName}");
                    Console.WriteLine($"Thing ARN: {thingArn}");
                }
                else
                {
                    Console.WriteLine("Failed to create certificate.");
                }
            }
            Console.WriteLine(new string('-', 80));

            // Step 4: Update an AWS IoT Thing with Attributes
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("4. Update an AWS IoT Thing with Attributes.");
            Console.WriteLine("IoT Thing attributes, represented as key-value pairs, offer a pivotal advantage in facilitating efficient data");
            Console.WriteLine("management and retrieval within the AWS IoT ecosystem.");
            Console.WriteLine();
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var attributes = new Dictionary<string, string>
            {
                { "Location", "Seattle" },
                { "DeviceType", "Sensor" },
                { "Firmware", "1.2.3" }
            };

            await iotWrapper.UpdateThingAsync(thingName, attributes);
            Console.WriteLine("Thing attributes updated successfully.");
            Console.WriteLine(new string('-', 80));

            // Step 5: Return a unique endpoint specific to the Amazon Web Services account
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("5. Return a unique endpoint specific to the Amazon Web Services account.");
            Console.WriteLine();
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var endpoint = await iotWrapper.DescribeEndpointAsync();
            if (endpoint != null)
            {
                var subdomain = endpoint.Split('.')[0];
                Console.WriteLine($"Extracted subdomain: {subdomain}");
                Console.WriteLine($"Full Endpoint URL: https://{endpoint}");
            }
            else
            {
                Console.WriteLine("Failed to retrieve endpoint.");
            }
            Console.WriteLine(new string('-', 80));

            // Step 6: List your AWS IoT certificates
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("6. List your AWS IoT certificates");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var certificates = await iotWrapper.ListCertificatesAsync();
            foreach (var cert in certificates.Take(5)) // Show first 5 certificates
            {
                Console.WriteLine($"Cert id: {cert.CertificateId}");
                Console.WriteLine($"Cert Arn: {cert.CertificateArn}");
            }
            Console.WriteLine();
            Console.WriteLine(new string('-', 80));

            // Step 7: Create an IoT shadow
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("7. Update an IoT shadow that refers to a digital representation or virtual twin of a physical IoT device");
            Console.WriteLine();
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var shadowPayload = JsonSerializer.Serialize(new
            {
                state = new
                {
                    desired = new
                    {
                        temperature = 25,
                        humidity = 50
                    }
                }
            });

            await iotWrapper.UpdateThingShadowAsync(thingName, shadowPayload);
            Console.WriteLine("Thing Shadow updated successfully.");
            Console.WriteLine(new string('-', 80));

            // Step 8: Write out the state information, in JSON format
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("8. Write out the state information, in JSON format.");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var shadowData = await iotWrapper.GetThingShadowAsync(thingName);
            Console.WriteLine($"Received Shadow Data: {shadowData}");
            Console.WriteLine(new string('-', 80));

            // Step 9: Set up resources (SNS topic and IAM role) and create a rule
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("9. Set up resources and create a rule");
            Console.WriteLine();

            // Deploy CloudFormation stack to create SNS topic and IAM role
            Console.WriteLine("Deploying CloudFormation stack to create SNS topic and IAM role...");

            var deployStack = !IsInteractive || GetYesNoResponse("Would you like to deploy the CloudFormation stack? (y/n) ");
            if (deployStack)
            {
                if (IsInteractive)
                {
                    Console.Write(
                        $"Enter stack resource file path (or press Enter for default '{_stackResourcePath}'): ");
                    var userResourcePath = Console.ReadLine();
                    if (!string.IsNullOrEmpty(userResourcePath))
                        _stackResourcePath = userResourcePath;
                }

                _stackName = PromptUserForStackName();

                var deploySuccess = await DeployCloudFormationStack(_stackName, cloudFormationClient, scenarioLogger);

                if (deploySuccess)
                {
                    // Get stack outputs
                    var stackOutputs = await GetStackOutputs(_stackName, cloudFormationClient, scenarioLogger);
                    if (stackOutputs != null)
                    {
                        snsTopicArn = stackOutputs["SNSTopicArn"];
                        string roleArn = stackOutputs["RoleArn"];

                        Console.WriteLine($"Successfully deployed stack. SNS topic: {snsTopicArn}");
                        Console.WriteLine($"Successfully deployed stack. IAM role: {roleArn}");

                        if (IsInteractive)
                        {
                            Console.Write($"Enter Rule name (press Enter for default '{ruleName}'): ");
                            var userRuleName = Console.ReadLine();
                            if (!string.IsNullOrEmpty(userRuleName))
                                ruleName = userRuleName;
                        }
                        else
                        {
                            Console.WriteLine($"Using default rule name: {ruleName}");
                        }

                        // Now create the IoT rule with the CloudFormation outputs
                        var ruleResult = await iotWrapper.CreateTopicRuleAsync(ruleName, snsTopicArn, roleArn);
                        if (ruleResult)
                        {
                            Console.WriteLine("IoT Rule created successfully.");
                        }
                        else
                        {
                            Console.WriteLine("Failed to create IoT rule.");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Failed to get stack outputs. Skipping rule creation.");
                    }
                }
                else
                {
                    Console.WriteLine("Failed to deploy CloudFormation stack. Skipping rule creation.");
                }
            }
            else
            {
                Console.WriteLine("Skipping CloudFormation stack deployment and rule creation.");
            }
            Console.WriteLine(new string('-', 80));

            // Step 10: List your rules
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("10. List your rules.");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var rules = await iotWrapper.ListTopicRulesAsync();
            Console.WriteLine("List of IoT Rules:");
            foreach (var rule in rules.Take(5)) // Show first 5 rules
            {
                Console.WriteLine($"Rule Name: {rule.RuleName}");
                Console.WriteLine($"Rule ARN: {rule.RuleArn}");
                Console.WriteLine("--------------");
            }
            Console.WriteLine();
            Console.WriteLine(new string('-', 80));

            // Step 11: Search things using the Thing name
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("11. Search things using the Thing name.");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }

            var searchResults = await iotWrapper.SearchIndexAsync($"thingName:{thingName}");
            if (searchResults.Any())
            {
                Console.WriteLine($"Thing id found using search is {searchResults.First().ThingId}");
            }
            else
            {
                Console.WriteLine($"No search results found for Thing: {thingName}");
            }
            Console.WriteLine(new string('-', 80));

            // Step 12: Cleanup - Detach and delete certificate
            if (!string.IsNullOrEmpty(certificateArn))
            {
                Console.WriteLine(new string('-', 80));
                var deleteCert = "y";
                if (IsInteractive)
                {
                    Console.Write($"Do you want to detach and delete the certificate for {thingName}? (y/n)");
                    deleteCert = Console.ReadLine();
                }
                else
                {
                    Console.WriteLine($"Detaching and deleting certificate for {thingName}...");
                }

                if (deleteCert?.ToLower() == "y")
                {
                    Console.WriteLine("12. You selected to detach and delete the certificate.");
                    if (IsInteractive)
                    {
                        Console.WriteLine("Press Enter to continue...");
                        Console.ReadLine();
                    }

                    await iotWrapper.DetachThingPrincipalAsync(thingName, certificateArn);
                    Console.WriteLine($"{certificateArn} was successfully removed from {thingName}");

                    await iotWrapper.DeleteCertificateAsync(certificateId);
                    Console.WriteLine($"{certificateArn} was successfully deleted.");
                }
                Console.WriteLine(new string('-', 80));
            }

            // Step 13: Delete the AWS IoT Thing
            Console.WriteLine(new string('-', 80));
            Console.WriteLine("13. Delete the AWS IoT Thing.");
            var deleteThing = "y";
            if (IsInteractive)
            {
                Console.Write($"Do you want to delete the IoT Thing? (y/n)");
                deleteThing = Console.ReadLine();
            }
            else
            {
                Console.WriteLine($"Deleting IoT Thing {thingName}...");
            }

            if (deleteThing?.ToLower() == "y")
            {
                await iotWrapper.DeleteThingAsync(thingName);
                Console.WriteLine($"Deleted Thing {thingName}");
            }
            Console.WriteLine(new string('-', 80));

            // Step 14: Clean up CloudFormation stack
            if (!string.IsNullOrEmpty(snsTopicArn))
            {
                Console.WriteLine(new string('-', 80));
                Console.WriteLine("14. Clean up CloudFormation stack.");
                Console.WriteLine("Deleting the CloudFormation stack and all resources...");

                var cleanup = !IsInteractive || GetYesNoResponse("Do you want to delete the CloudFormation stack and all resources? (y/n) ");
                if (cleanup)
                {
                    var ruleCleanupSuccess = await iotWrapper.DeleteTopicRuleAsync(ruleName);

                    var stackCleanupSuccess = await DeleteCloudFormationStack(_stackName, cloudFormationClient, scenarioLogger);
                    if (ruleCleanupSuccess && stackCleanupSuccess)
                    {
                        Console.WriteLine("Successfully cleaned up CloudFormation stack and all resources.");
                    }
                    else
                    {
                        Console.WriteLine("Some cleanup operations failed. Check the logs for details.");
                    }
                }
                else
                {
                    Console.WriteLine($"Resources will remain. Stack name: {_stackName}");
                }
                Console.WriteLine(new string('-', 80));
            }
        }
        catch (Exception ex)
        {
            scenarioLogger.LogError(ex, "Error occurred during scenario execution.");

            // Cleanup on error
            if (!string.IsNullOrEmpty(certificateArn) && !string.IsNullOrEmpty(thingName))
            {
                try
                {
                    await iotWrapper.DetachThingPrincipalAsync(thingName, certificateArn);
                    await iotWrapper.DeleteCertificateAsync(certificateId);
                }
                catch (Exception cleanupEx)
                {
                    scenarioLogger.LogError(cleanupEx, "Error during cleanup.");
                }
            }

            if (!string.IsNullOrEmpty(thingName))
            {
                try
                {
                    await iotWrapper.DeleteThingAsync(thingName);
                }
                catch (Exception cleanupEx)
                {
                    scenarioLogger.LogError(cleanupEx, "Error during Thing cleanup.");
                }
            }

            // Clean up CloudFormation stack on error
            if (!string.IsNullOrEmpty(snsTopicArn))
            {
                try
                {
                    await _iotWrapper.DeleteTopicRuleAsync(ruleName);
                    await DeleteCloudFormationStack(_stackName, cloudFormationClient, scenarioLogger);
                }
                catch (Exception cleanupEx)
                {
                    scenarioLogger.LogError(cleanupEx, "Error during CloudFormation stack cleanup.");
                }
            }

            throw;
        }
    }

    /// <summary>
    /// Deploys the CloudFormation stack with the necessary resources.
    /// </summary>
    /// <param name="stackName">The name of the CloudFormation stack.</param>
    /// <param name="cloudFormationClient">The CloudFormation client.</param>
    /// <param name="scenarioLogger">The logger.</param>
    /// <returns>True if the stack was deployed successfully.</returns>
    private static async Task<bool> DeployCloudFormationStack(string stackName, IAmazonCloudFormation cloudFormationClient, ILogger<IoTBasics> scenarioLogger)
    {
        Console.WriteLine($"\nDeploying CloudFormation stack: {stackName}");

        try
        {
            var request = new CreateStackRequest
            {
                StackName = stackName,
                TemplateBody = await File.ReadAllTextAsync(_stackResourcePath),
                Capabilities = new List<string> { Capability.CAPABILITY_NAMED_IAM }
            };

            var response = await cloudFormationClient.CreateStackAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"CloudFormation stack creation started: {stackName}");

                bool stackCreated = await WaitForStackCompletion(response.StackId, cloudFormationClient, scenarioLogger);

                if (stackCreated)
                {
                    Console.WriteLine("CloudFormation stack created successfully.");
                    return true;
                }
                else
                {
                    scenarioLogger.LogError($"CloudFormation stack creation failed: {stackName}");
                    return false;
                }
            }
            else
            {
                scenarioLogger.LogError($"Failed to create CloudFormation stack: {stackName}");
                return false;
            }
        }
        catch (AlreadyExistsException)
        {
            scenarioLogger.LogWarning($"CloudFormation stack '{stackName}' already exists. Please provide a unique name.");
            var newStackName = PromptUserForStackName();
            return await DeployCloudFormationStack(newStackName, cloudFormationClient, scenarioLogger);
        }
        catch (Exception ex)
        {
            scenarioLogger.LogError(ex, $"An error occurred while deploying the CloudFormation stack: {stackName}");
            return false;
        }
    }

    /// <summary>
    /// Waits for the CloudFormation stack to be in the CREATE_COMPLETE state.
    /// </summary>
    /// <param name="stackId">The ID of the CloudFormation stack.</param>
    /// <param name="cloudFormationClient">The CloudFormation client.</param>
    /// <param name="scenarioLogger">The logger.</param>
    /// <returns>True if the stack was created successfully.</returns>
    private static async Task<bool> WaitForStackCompletion(string stackId, IAmazonCloudFormation cloudFormationClient, ILogger<IoTBasics> scenarioLogger)
    {
        int retryCount = 0;
        const int maxRetries = 30;
        const int retryDelay = 10000;

        while (retryCount < maxRetries)
        {
            var describeStacksRequest = new DescribeStacksRequest
            {
                StackName = stackId
            };

            var describeStacksResponse = await cloudFormationClient.DescribeStacksAsync(describeStacksRequest);

            if (describeStacksResponse.Stacks.Count > 0)
            {
                if (describeStacksResponse.Stacks[0].StackStatus == StackStatus.CREATE_COMPLETE)
                {
                    return true;
                }
                if (describeStacksResponse.Stacks[0].StackStatus == StackStatus.CREATE_FAILED ||
                    describeStacksResponse.Stacks[0].StackStatus == StackStatus.ROLLBACK_COMPLETE)
                {
                    return false;
                }
            }

            Console.WriteLine("Waiting for CloudFormation stack creation to complete...");
            await Task.Delay(retryDelay);
            retryCount++;
        }

        scenarioLogger.LogError("Timed out waiting for CloudFormation stack creation to complete.");
        return false;
    }

    /// <summary>
    /// Gets the outputs from the CloudFormation stack.
    /// </summary>
    /// <param name="stackName">The name of the CloudFormation stack.</param>
    /// <param name="cloudFormationClient">The CloudFormation client.</param>
    /// <param name="scenarioLogger">The logger.</param>
    /// <returns>A dictionary of stack outputs.</returns>
    private static async Task<Dictionary<string, string>?> GetStackOutputs(string stackName, IAmazonCloudFormation cloudFormationClient, ILogger<IoTBasics> scenarioLogger)
    {
        try
        {
            var describeStacksRequest = new DescribeStacksRequest
            {
                StackName = stackName
            };

            var response = await cloudFormationClient.DescribeStacksAsync(describeStacksRequest);

            if (response.Stacks.Count > 0)
            {
                var outputs = new Dictionary<string, string>();
                foreach (var output in response.Stacks[0].Outputs)
                {
                    outputs[output.OutputKey] = output.OutputValue;
                }
                return outputs;
            }

            return null;
        }
        catch (Exception ex)
        {
            scenarioLogger.LogError(ex, $"Failed to get stack outputs for {stackName}");
            return null;
        }
    }

    /// <summary>
    /// Deletes the CloudFormation stack and waits for confirmation.
    /// </summary>
    /// <param name="stackName">The name of the CloudFormation stack.</param>
    /// <param name="cloudFormationClient">The CloudFormation client.</param>
    /// <param name="scenarioLogger">The logger.</param>
    /// <returns>True if the stack was deleted successfully.</returns>
    private static async Task<bool> DeleteCloudFormationStack(string stackName, IAmazonCloudFormation cloudFormationClient, ILogger<IoTBasics> scenarioLogger)
    {
        try
        {
            var request = new DeleteStackRequest
            {
                StackName = stackName
            };

            await cloudFormationClient.DeleteStackAsync(request);
            Console.WriteLine($"CloudFormation stack '{stackName}' is being deleted. This may take a few minutes.");

            bool stackDeleted = await WaitForStackDeletion(stackName, cloudFormationClient, scenarioLogger);

            if (stackDeleted)
            {
                Console.WriteLine($"CloudFormation stack '{stackName}' has been deleted.");
                return true;
            }
            else
            {
                scenarioLogger.LogError($"Failed to delete CloudFormation stack '{stackName}'.");
                return false;
            }
        }
        catch (Exception ex)
        {
            scenarioLogger.LogError(ex, $"An error occurred while deleting the CloudFormation stack: {stackName}");
            return false;
        }
    }

    /// <summary>
    /// Waits for the stack to be deleted.
    /// </summary>
    /// <param name="stackName">The name of the CloudFormation stack.</param>
    /// <param name="cloudFormationClient">The CloudFormation client.</param>
    /// <param name="scenarioLogger">The logger.</param>
    /// <returns>True if the stack was deleted successfully.</returns>
    private static async Task<bool> WaitForStackDeletion(string stackName, IAmazonCloudFormation cloudFormationClient, ILogger<IoTBasics> scenarioLogger)
    {
        int retryCount = 0;
        const int maxRetries = 30;
        const int retryDelay = 10000;

        while (retryCount < maxRetries)
        {
            var describeStacksRequest = new DescribeStacksRequest
            {
                StackName = stackName
            };

            try
            {
                var describeStacksResponse = await cloudFormationClient.DescribeStacksAsync(describeStacksRequest);

                if (describeStacksResponse.Stacks.Count == 0 ||
                    describeStacksResponse.Stacks[0].StackStatus == StackStatus.DELETE_COMPLETE)
                {
                    return true;
                }
            }
            catch (AmazonCloudFormationException ex) when (ex.ErrorCode == "ValidationError")
            {
                return true;
            }

            Console.WriteLine($"Waiting for CloudFormation stack '{stackName}' to be deleted...");
            await Task.Delay(retryDelay);
            retryCount++;
        }

        scenarioLogger.LogError($"Timed out waiting for CloudFormation stack '{stackName}' to be deleted.");
        return false;
    }

    /// <summary>
    /// Helper method to get a yes or no response from the user.
    /// </summary>
    private static bool GetYesNoResponse(string question)
    {
        Console.WriteLine(question);
        var ynResponse = Console.ReadLine();
        var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase);
        return response;
    }

    /// <summary>
    /// Prompts the user for a stack name.
    /// </summary>
    private static string PromptUserForStackName()
    {
        if (IsInteractive)
        {
            Console.Write($"Enter a name for the CloudFormation stack (press Enter for default '{_stackName}'): ");
            string? input = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(input))
            {
                var regex = new System.Text.RegularExpressions.Regex("[a-zA-Z][-a-zA-Z0-9]*");
                if (!regex.IsMatch(input))
                {
                    Console.WriteLine($"Invalid stack name. Using default: {_stackName}");
                    return _stackName;
                }
                return input;
            }
        }
        return _stackName;
    }
}
```
 AWS IoT SDK メソッドのラッパークラス。  

```
/// <summary>
/// Wrapper methods to use Amazon IoT Core with .NET.
/// </summary>
public class IoTWrapper
{
    private readonly IAmazonIoT _amazonIoT;
    private readonly IAmazonIotData _amazonIotData;
    private readonly ILogger<IoTWrapper> _logger;

    /// <summary>
    /// Constructor for the IoT wrapper.
    /// </summary>
    /// <param name="amazonIoT">The injected IoT client.</param>
    /// <param name="amazonIotData">The injected IoT Data client.</param>
    /// <param name="logger">The injected logger.</param>
    public IoTWrapper(IAmazonIoT amazonIoT, IAmazonIotData amazonIotData, ILogger<IoTWrapper> logger)
    {
        _amazonIoT = amazonIoT;
        _amazonIotData = amazonIotData;
        _logger = logger;
    }

    /// <summary>
    /// Creates an AWS IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing to create.</param>
    /// <returns>The ARN of the Thing created, or null if creation failed.</returns>
    public async Task<string?> CreateThingAsync(string thingName)
    {
        try
        {
            var request = new CreateThingRequest
            {
                ThingName = thingName
            };

            var response = await _amazonIoT.CreateThingAsync(request);
            _logger.LogInformation($"Created Thing {thingName} with ARN {response.ThingArn}");
            return response.ThingArn;
        }
        catch (Amazon.IoT.Model.ResourceAlreadyExistsException ex)
        {
            _logger.LogWarning($"Thing {thingName} already exists: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't create Thing {thingName}. Here's why: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Creates a device certificate for AWS IoT.
    /// </summary>
    /// <returns>The certificate details including ARN and certificate PEM, or null if creation failed.</returns>
    public async Task<(string CertificateArn, string CertificatePem, string CertificateId)?> CreateKeysAndCertificateAsync()
    {
        try
        {
            var request = new CreateKeysAndCertificateRequest
            {
                SetAsActive = true
            };

            var response = await _amazonIoT.CreateKeysAndCertificateAsync(request);
            _logger.LogInformation($"Created certificate with ARN {response.CertificateArn}");
            return (response.CertificateArn, response.CertificatePem, response.CertificateId);
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't create certificate. Here's why: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Attaches a certificate to an IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <param name="certificateArn">The ARN of the certificate to attach.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> AttachThingPrincipalAsync(string thingName, string certificateArn)
    {
        try
        {
            var request = new AttachThingPrincipalRequest
            {
                ThingName = thingName,
                Principal = certificateArn
            };

            await _amazonIoT.AttachThingPrincipalAsync(request);
            _logger.LogInformation($"Attached certificate {certificateArn} to Thing {thingName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot attach certificate - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't attach certificate to Thing. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Updates an IoT Thing with attributes.
    /// </summary>
    /// <param name="thingName">The name of the Thing to update.</param>
    /// <param name="attributes">Dictionary of attributes to add.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> UpdateThingAsync(string thingName, Dictionary<string, string> attributes)
    {
        try
        {
            var request = new UpdateThingRequest
            {
                ThingName = thingName,
                AttributePayload = new AttributePayload
                {
                    Attributes = attributes,
                    Merge = true
                }
            };

            await _amazonIoT.UpdateThingAsync(request);
            _logger.LogInformation($"Updated Thing {thingName} with attributes");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot update Thing - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't update Thing attributes. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Gets the AWS IoT endpoint URL.
    /// </summary>
    /// <returns>The endpoint URL, or null if retrieval failed.</returns>
    public async Task<string?> DescribeEndpointAsync()
    {
        try
        {
            var request = new DescribeEndpointRequest
            {
                EndpointType = "iot:Data-ATS"
            };

            var response = await _amazonIoT.DescribeEndpointAsync(request);
            _logger.LogInformation($"Retrieved endpoint: {response.EndpointAddress}");
            return response.EndpointAddress;
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't describe endpoint. Here's why: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Lists all certificates associated with the account.
    /// </summary>
    /// <returns>List of certificate information, or empty list if listing failed.</returns>
    public async Task<List<Certificate>> ListCertificatesAsync()
    {
        try
        {
            var request = new ListCertificatesRequest();
            var response = await _amazonIoT.ListCertificatesAsync(request);

            _logger.LogInformation($"Retrieved {response.Certificates.Count} certificates");
            return response.Certificates;
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return new List<Certificate>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't list certificates. Here's why: {ex.Message}");
            return new List<Certificate>();
        }
    }

    /// <summary>
    /// Updates the Thing's shadow with new state information.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <param name="shadowPayload">The shadow payload in JSON format.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> UpdateThingShadowAsync(string thingName, string shadowPayload)
    {
        try
        {
            var request = new UpdateThingShadowRequest
            {
                ThingName = thingName,
                Payload = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(shadowPayload))
            };

            await _amazonIotData.UpdateThingShadowAsync(request);
            _logger.LogInformation($"Updated shadow for Thing {thingName}");
            return true;
        }
        catch (Amazon.IotData.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot update Thing shadow - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't update Thing shadow. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Gets the Thing's shadow information.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <returns>The shadow data as a string, or null if retrieval failed.</returns>
    public async Task<string?> GetThingShadowAsync(string thingName)
    {
        try
        {
            var request = new GetThingShadowRequest
            {
                ThingName = thingName
            };

            var response = await _amazonIotData.GetThingShadowAsync(request);
            using var reader = new StreamReader(response.Payload);
            var shadowData = await reader.ReadToEndAsync();

            _logger.LogInformation($"Retrieved shadow for Thing {thingName}");
            return shadowData;
        }
        catch (Amazon.IotData.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot get Thing shadow - resource not found: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't get Thing shadow. Here's why: {ex.Message}");
            return null;
        }
    }

    /// <summary>
    /// Creates an IoT topic rule.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <param name="snsTopicArn">The ARN of the SNS topic for the action.</param>
    /// <param name="roleArn">The ARN of the IAM role.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> CreateTopicRuleAsync(string ruleName, string snsTopicArn, string roleArn)
    {
        try
        {
            var request = new CreateTopicRuleRequest
            {
                RuleName = ruleName,
                TopicRulePayload = new TopicRulePayload
                {
                    Sql = "SELECT * FROM 'topic/subtopic'",
                    Description = $"Rule created by .NET example: {ruleName}",
                    Actions = new List<Amazon.IoT.Model.Action>
                    {
                        new Amazon.IoT.Model.Action
                        {
                            Sns = new SnsAction
                            {
                                TargetArn = snsTopicArn,
                                RoleArn = roleArn
                            }
                        }
                    },
                    RuleDisabled = false
                }
            };

            await _amazonIoT.CreateTopicRuleAsync(request);
            _logger.LogInformation($"Created IoT rule {ruleName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceAlreadyExistsException ex)
        {
            _logger.LogWarning($"Rule {ruleName} already exists: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't create topic rule. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Deletes an IoT topic rule.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> DeleteTopicRuleAsync(string ruleName)
    {
        try
        {
            var request = new DeleteTopicRuleRequest
            {
                RuleName = ruleName,
            };

            await _amazonIoT.DeleteTopicRuleAsync(request);
            _logger.LogInformation($"Deleted IoT rule {ruleName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogWarning($"Rule {ruleName} not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't delete topic rule. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Lists all IoT topic rules.
    /// </summary>
    /// <returns>List of topic rules, or empty list if listing failed.</returns>
    public async Task<List<TopicRuleListItem>> ListTopicRulesAsync()
    {
        try
        {
            var request = new ListTopicRulesRequest();
            var response = await _amazonIoT.ListTopicRulesAsync(request);

            _logger.LogInformation($"Retrieved {response.Rules.Count} IoT rules");
            return response.Rules;
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return new List<TopicRuleListItem>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't list topic rules. Here's why: {ex.Message}");
            return new List<TopicRuleListItem>();
        }
    }

    /// <summary>
    /// Searches for IoT Things using the search index.
    /// </summary>
    /// <param name="queryString">The search query string.</param>
    /// <returns>List of Things that match the search criteria, or empty list if search failed.</returns>
    public async Task<List<ThingDocument>> SearchIndexAsync(string queryString)
    {
        try
        {
            // First, try to perform the search
            var request = new SearchIndexRequest
            {
                QueryString = queryString
            };

            var response = await _amazonIoT.SearchIndexAsync(request);
            _logger.LogInformation($"Search found {response.Things.Count} Things");
            return response.Things;
        }
        catch (Amazon.IoT.Model.IndexNotReadyException ex)
        {
            _logger.LogWarning($"Search index not ready, setting up indexing configuration: {ex.Message}");
            return await SetupIndexAndRetrySearchAsync(queryString);
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex) when (ex.Message.Contains("index") || ex.Message.Contains("Index"))
        {
            _logger.LogWarning($"Search index not configured, setting up indexing configuration: {ex.Message}");
            return await SetupIndexAndRetrySearchAsync(queryString);
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return new List<ThingDocument>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't search index. Here's why: {ex.Message}");
            return new List<ThingDocument>();
        }
    }

    /// <summary>
    /// Sets up the indexing configuration and retries the search after waiting for the index to be ready.
    /// </summary>
    /// <param name="queryString">The search query string.</param>
    /// <returns>List of Things that match the search criteria, or empty list if setup/search failed.</returns>
    private async Task<List<ThingDocument>> SetupIndexAndRetrySearchAsync(string queryString)
    {
        try
        {
            // Update indexing configuration to REGISTRY mode
            _logger.LogInformation("Setting up IoT search indexing configuration...");
            await _amazonIoT.UpdateIndexingConfigurationAsync(
                new UpdateIndexingConfigurationRequest()
                {
                    ThingIndexingConfiguration = new ThingIndexingConfiguration()
                    {
                        ThingIndexingMode = ThingIndexingMode.REGISTRY
                    }
                });

            _logger.LogInformation("Indexing configuration updated. Waiting for index to be ready...");

            // Wait for the index to be set up - this can take some time
            const int maxRetries = 10;
            const int retryDelaySeconds = 10;

            for (int attempt = 1; attempt <= maxRetries; attempt++)
            {
                try
                {
                    _logger.LogInformation($"Waiting for index to be ready (attempt {attempt}/{maxRetries})...");
                    await Task.Delay(TimeSpan.FromSeconds(retryDelaySeconds));

                    // Try to get the current indexing configuration to see if it's ready
                    var configResponse = await _amazonIoT.GetIndexingConfigurationAsync(new GetIndexingConfigurationRequest());
                    if (configResponse.ThingIndexingConfiguration?.ThingIndexingMode == ThingIndexingMode.REGISTRY)
                    {
                        // Try the search again
                        var request = new SearchIndexRequest
                        {
                            QueryString = queryString
                        };

                        var response = await _amazonIoT.SearchIndexAsync(request);
                        _logger.LogInformation($"Search found {response.Things.Count} Things after index setup");
                        return response.Things;
                    }
                }
                catch (Amazon.IoT.Model.IndexNotReadyException)
                {
                    // Index still not ready, continue waiting
                    _logger.LogInformation("Index still not ready, continuing to wait...");
                    continue;
                }
                catch (Amazon.IoT.Model.InvalidRequestException ex) when (ex.Message.Contains("index") || ex.Message.Contains("Index"))
                {
                    // Index still not ready, continue waiting
                    _logger.LogInformation("Index still not ready, continuing to wait...");
                    continue;
                }
            }

            _logger.LogWarning("Timeout waiting for search index to be ready after configuration update");
            return new List<ThingDocument>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't set up search index configuration. Here's why: {ex.Message}");
            return new List<ThingDocument>();
        }
    }

    /// <summary>
    /// Detaches a certificate from an IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <param name="certificateArn">The ARN of the certificate to detach.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> DetachThingPrincipalAsync(string thingName, string certificateArn)
    {
        try
        {
            var request = new DetachThingPrincipalRequest
            {
                ThingName = thingName,
                Principal = certificateArn
            };

            await _amazonIoT.DetachThingPrincipalAsync(request);
            _logger.LogInformation($"Detached certificate {certificateArn} from Thing {thingName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot detach certificate - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't detach certificate from Thing. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Deletes an IoT certificate.
    /// </summary>
    /// <param name="certificateId">The ID of the certificate to delete.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> DeleteCertificateAsync(string certificateId)
    {
        try
        {
            // First, update the certificate to inactive state
            var updateRequest = new UpdateCertificateRequest
            {
                CertificateId = certificateId,
                NewStatus = CertificateStatus.INACTIVE
            };
            await _amazonIoT.UpdateCertificateAsync(updateRequest);

            // Then delete the certificate
            var deleteRequest = new DeleteCertificateRequest
            {
                CertificateId = certificateId
            };

            await _amazonIoT.DeleteCertificateAsync(deleteRequest);
            _logger.LogInformation($"Deleted certificate {certificateId}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot delete certificate - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't delete certificate. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Deletes an IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing to delete.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> DeleteThingAsync(string thingName)
    {
        try
        {
            var request = new DeleteThingRequest
            {
                ThingName = thingName
            };

            await _amazonIoT.DeleteThingAsync(request);
            _logger.LogInformation($"Deleted Thing {thingName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot delete Thing - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't delete Thing. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Lists IoT Things with pagination support.
    /// </summary>
    /// <returns>List of Things, or empty list if listing failed.</returns>
    public async Task<List<ThingAttribute>> ListThingsAsync()
    {
        try
        {
            // Use pages of 10.
            var request = new ListThingsRequest()
            {
                MaxResults = 10
            };
            var response = await _amazonIoT.ListThingsAsync(request);

            // Since there is not a built-in paginator, use the NextMarker to paginate.
            bool hasMoreResults = true;

            var things = new List<ThingAttribute>();
            while (hasMoreResults)
            {
                things.AddRange(response.Things);

                // If NextMarker is not null, there are more results. Get the next page of results.
                if (!String.IsNullOrEmpty(response.NextMarker))
                {
                    request.Marker = response.NextMarker;
                    response = await _amazonIoT.ListThingsAsync(request);
                }
                else
                    hasMoreResults = false;
            }

            _logger.LogInformation($"Retrieved {things.Count} Things");
            return things;
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return new List<ThingAttribute>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't list Things. Here's why: {ex.Message}");
            return new List<ThingAttribute>();
        }
    }

}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [AttachThingPrincipal](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/AttachThingPrincipal)
  + [CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/CreateKeysAndCertificate)
  + [CreateThing](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/CreateThing)
  + [CreateTopicRule](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/CreateTopicRule)
  + [DeleteCertificate](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DeleteCertificate)
  + [DeleteThing](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DeleteThing)
  + [DeleteTopicRule](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DeleteTopicRule)
  + [DescribeEndpoint](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DescribeEndpoint)
  + [DescribeThing](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DescribeThing)
  + [DetachThingPrincipal](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DetachThingPrincipal)
  + [ListCertificates](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/ListCertificates)
  + [ListThings](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/ListThings)
  + [SearchIndex](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/SearchIndex)
  + [UpdateIndexingConfiguration](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/UpdateIndexingConfiguration)
  + [UpdateThing](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/UpdateThing)

## アクション
<a name="actions"></a>

### `AttachThingPrincipal`
<a name="iot_AttachThingPrincipal_csharp_4_topic"></a>

次の例は、`AttachThingPrincipal` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Attaches a certificate to an IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <param name="certificateArn">The ARN of the certificate to attach.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> AttachThingPrincipalAsync(string thingName, string certificateArn)
    {
        try
        {
            var request = new AttachThingPrincipalRequest
            {
                ThingName = thingName,
                Principal = certificateArn
            };

            await _amazonIoT.AttachThingPrincipalAsync(request);
            _logger.LogInformation($"Attached certificate {certificateArn} to Thing {thingName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot attach certificate - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't attach certificate to Thing. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[AttachThingPrincipal](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/AttachThingPrincipal)」を参照してください。

### `CreateKeysAndCertificate`
<a name="iot_CreateKeysAndCertificate_csharp_4_topic"></a>

次の例は、`CreateKeysAndCertificate` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates a device certificate for AWS IoT.
    /// </summary>
    /// <returns>The certificate details including ARN and certificate PEM, or null if creation failed.</returns>
    public async Task<(string CertificateArn, string CertificatePem, string CertificateId)?> CreateKeysAndCertificateAsync()
    {
        try
        {
            var request = new CreateKeysAndCertificateRequest
            {
                SetAsActive = true
            };

            var response = await _amazonIoT.CreateKeysAndCertificateAsync(request);
            _logger.LogInformation($"Created certificate with ARN {response.CertificateArn}");
            return (response.CertificateArn, response.CertificatePem, response.CertificateId);
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't create certificate. Here's why: {ex.Message}");
            return null;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/CreateKeysAndCertificate)」を参照してください。

### `CreateThing`
<a name="iot_CreateThing_csharp_4_topic"></a>

次の例は、`CreateThing` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates an AWS IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing to create.</param>
    /// <returns>The ARN of the Thing created, or null if creation failed.</returns>
    public async Task<string?> CreateThingAsync(string thingName)
    {
        try
        {
            var request = new CreateThingRequest
            {
                ThingName = thingName
            };

            var response = await _amazonIoT.CreateThingAsync(request);
            _logger.LogInformation($"Created Thing {thingName} with ARN {response.ThingArn}");
            return response.ThingArn;
        }
        catch (Amazon.IoT.Model.ResourceAlreadyExistsException ex)
        {
            _logger.LogWarning($"Thing {thingName} already exists: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't create Thing {thingName}. Here's why: {ex.Message}");
            return null;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateThing](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/CreateThing)」を参照してください。

### `CreateTopicRule`
<a name="iot_CreateTopicRule_csharp_4_topic"></a>

次の例は、`CreateTopicRule` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Creates an IoT topic rule.
    /// </summary>
    /// <param name="ruleName">The name of the rule.</param>
    /// <param name="snsTopicArn">The ARN of the SNS topic for the action.</param>
    /// <param name="roleArn">The ARN of the IAM role.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> CreateTopicRuleAsync(string ruleName, string snsTopicArn, string roleArn)
    {
        try
        {
            var request = new CreateTopicRuleRequest
            {
                RuleName = ruleName,
                TopicRulePayload = new TopicRulePayload
                {
                    Sql = "SELECT * FROM 'topic/subtopic'",
                    Description = $"Rule created by .NET example: {ruleName}",
                    Actions = new List<Amazon.IoT.Model.Action>
                    {
                        new Amazon.IoT.Model.Action
                        {
                            Sns = new SnsAction
                            {
                                TargetArn = snsTopicArn,
                                RoleArn = roleArn
                            }
                        }
                    },
                    RuleDisabled = false
                }
            };

            await _amazonIoT.CreateTopicRuleAsync(request);
            _logger.LogInformation($"Created IoT rule {ruleName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceAlreadyExistsException ex)
        {
            _logger.LogWarning($"Rule {ruleName} already exists: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't create topic rule. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateTopicRule](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/CreateTopicRule)」を参照してください。

### `DeleteCertificate`
<a name="iot_DeleteCertificate_csharp_4_topic"></a>

次の例は、`DeleteCertificate` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes an IoT certificate.
    /// </summary>
    /// <param name="certificateId">The ID of the certificate to delete.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> DeleteCertificateAsync(string certificateId)
    {
        try
        {
            // First, update the certificate to inactive state
            var updateRequest = new UpdateCertificateRequest
            {
                CertificateId = certificateId,
                NewStatus = CertificateStatus.INACTIVE
            };
            await _amazonIoT.UpdateCertificateAsync(updateRequest);

            // Then delete the certificate
            var deleteRequest = new DeleteCertificateRequest
            {
                CertificateId = certificateId
            };

            await _amazonIoT.DeleteCertificateAsync(deleteRequest);
            _logger.LogInformation($"Deleted certificate {certificateId}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot delete certificate - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't delete certificate. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteCertificate](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DeleteCertificate)」を参照してください。

### `DeleteThing`
<a name="iot_DeleteThing_csharp_4_topic"></a>

次の例は、`DeleteThing` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Deletes an IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing to delete.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> DeleteThingAsync(string thingName)
    {
        try
        {
            var request = new DeleteThingRequest
            {
                ThingName = thingName
            };

            await _amazonIoT.DeleteThingAsync(request);
            _logger.LogInformation($"Deleted Thing {thingName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot delete Thing - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't delete Thing. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「DeleteThing」を参照してください。[https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DeleteThing](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DeleteThing)

### `DescribeEndpoint`
<a name="iot_DescribeEndpoint_csharp_4_topic"></a>

次の例は、`DescribeEndpoint` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Gets the AWS IoT endpoint URL.
    /// </summary>
    /// <returns>The endpoint URL, or null if retrieval failed.</returns>
    public async Task<string?> DescribeEndpointAsync()
    {
        try
        {
            var request = new DescribeEndpointRequest
            {
                EndpointType = "iot:Data-ATS"
            };

            var response = await _amazonIoT.DescribeEndpointAsync(request);
            _logger.LogInformation($"Retrieved endpoint: {response.EndpointAddress}");
            return response.EndpointAddress;
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't describe endpoint. Here's why: {ex.Message}");
            return null;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeEndpoint](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DescribeEndpoint)」を参照してください。

### `DetachThingPrincipal`
<a name="iot_DetachThingPrincipal_csharp_4_topic"></a>

次の例は、`DetachThingPrincipal` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Detaches a certificate from an IoT Thing.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <param name="certificateArn">The ARN of the certificate to detach.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> DetachThingPrincipalAsync(string thingName, string certificateArn)
    {
        try
        {
            var request = new DetachThingPrincipalRequest
            {
                ThingName = thingName,
                Principal = certificateArn
            };

            await _amazonIoT.DetachThingPrincipalAsync(request);
            _logger.LogInformation($"Detached certificate {certificateArn} from Thing {thingName}");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot detach certificate - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't detach certificate from Thing. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DetachThingPrincipal](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/DetachThingPrincipal)」を参照してください。

### `ListCertificates`
<a name="iot_ListCertificates_csharp_4_topic"></a>

次の例は、`ListCertificates` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Lists all certificates associated with the account.
    /// </summary>
    /// <returns>List of certificate information, or empty list if listing failed.</returns>
    public async Task<List<Certificate>> ListCertificatesAsync()
    {
        try
        {
            var request = new ListCertificatesRequest();
            var response = await _amazonIoT.ListCertificatesAsync(request);

            _logger.LogInformation($"Retrieved {response.Certificates.Count} certificates");
            return response.Certificates;
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return new List<Certificate>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't list certificates. Here's why: {ex.Message}");
            return new List<Certificate>();
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンスの*「[ListCertificates](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/ListCertificates)」を参照してください。

### `ListThings`
<a name="iot_ListThings_csharp_4_topic"></a>

次の例は、`ListThings` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Lists IoT Things with pagination support.
    /// </summary>
    /// <returns>List of Things, or empty list if listing failed.</returns>
    public async Task<List<ThingAttribute>> ListThingsAsync()
    {
        try
        {
            // Use pages of 10.
            var request = new ListThingsRequest()
            {
                MaxResults = 10
            };
            var response = await _amazonIoT.ListThingsAsync(request);

            // Since there is not a built-in paginator, use the NextMarker to paginate.
            bool hasMoreResults = true;

            var things = new List<ThingAttribute>();
            while (hasMoreResults)
            {
                things.AddRange(response.Things);

                // If NextMarker is not null, there are more results. Get the next page of results.
                if (!String.IsNullOrEmpty(response.NextMarker))
                {
                    request.Marker = response.NextMarker;
                    response = await _amazonIoT.ListThingsAsync(request);
                }
                else
                    hasMoreResults = false;
            }

            _logger.LogInformation($"Retrieved {things.Count} Things");
            return things;
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return new List<ThingAttribute>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't list Things. Here's why: {ex.Message}");
            return new List<ThingAttribute>();
        }
    }
```
+  API の詳細については、*AWS SDK for .NET 「 API リファレンス*」の[ListThings](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/ListThings)」を参照してください。

### `SearchIndex`
<a name="iot_SearchIndex_csharp_4_topic"></a>

次の例は、`SearchIndex` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Searches for IoT Things using the search index.
    /// </summary>
    /// <param name="queryString">The search query string.</param>
    /// <returns>List of Things that match the search criteria, or empty list if search failed.</returns>
    public async Task<List<ThingDocument>> SearchIndexAsync(string queryString)
    {
        try
        {
            // First, try to perform the search
            var request = new SearchIndexRequest
            {
                QueryString = queryString
            };

            var response = await _amazonIoT.SearchIndexAsync(request);
            _logger.LogInformation($"Search found {response.Things.Count} Things");
            return response.Things;
        }
        catch (Amazon.IoT.Model.IndexNotReadyException ex)
        {
            _logger.LogWarning($"Search index not ready, setting up indexing configuration: {ex.Message}");
            return await SetupIndexAndRetrySearchAsync(queryString);
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex) when (ex.Message.Contains("index") || ex.Message.Contains("Index"))
        {
            _logger.LogWarning($"Search index not configured, setting up indexing configuration: {ex.Message}");
            return await SetupIndexAndRetrySearchAsync(queryString);
        }
        catch (Amazon.IoT.Model.ThrottlingException ex)
        {
            _logger.LogWarning($"Request throttled, please try again later: {ex.Message}");
            return new List<ThingDocument>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't search index. Here's why: {ex.Message}");
            return new List<ThingDocument>();
        }
    }

    /// <summary>
    /// Sets up the indexing configuration and retries the search after waiting for the index to be ready.
    /// </summary>
    /// <param name="queryString">The search query string.</param>
    /// <returns>List of Things that match the search criteria, or empty list if setup/search failed.</returns>
    private async Task<List<ThingDocument>> SetupIndexAndRetrySearchAsync(string queryString)
    {
        try
        {
            // Update indexing configuration to REGISTRY mode
            _logger.LogInformation("Setting up IoT search indexing configuration...");
            await _amazonIoT.UpdateIndexingConfigurationAsync(
                new UpdateIndexingConfigurationRequest()
                {
                    ThingIndexingConfiguration = new ThingIndexingConfiguration()
                    {
                        ThingIndexingMode = ThingIndexingMode.REGISTRY
                    }
                });

            _logger.LogInformation("Indexing configuration updated. Waiting for index to be ready...");

            // Wait for the index to be set up - this can take some time
            const int maxRetries = 10;
            const int retryDelaySeconds = 10;

            for (int attempt = 1; attempt <= maxRetries; attempt++)
            {
                try
                {
                    _logger.LogInformation($"Waiting for index to be ready (attempt {attempt}/{maxRetries})...");
                    await Task.Delay(TimeSpan.FromSeconds(retryDelaySeconds));

                    // Try to get the current indexing configuration to see if it's ready
                    var configResponse = await _amazonIoT.GetIndexingConfigurationAsync(new GetIndexingConfigurationRequest());
                    if (configResponse.ThingIndexingConfiguration?.ThingIndexingMode == ThingIndexingMode.REGISTRY)
                    {
                        // Try the search again
                        var request = new SearchIndexRequest
                        {
                            QueryString = queryString
                        };

                        var response = await _amazonIoT.SearchIndexAsync(request);
                        _logger.LogInformation($"Search found {response.Things.Count} Things after index setup");
                        return response.Things;
                    }
                }
                catch (Amazon.IoT.Model.IndexNotReadyException)
                {
                    // Index still not ready, continue waiting
                    _logger.LogInformation("Index still not ready, continuing to wait...");
                    continue;
                }
                catch (Amazon.IoT.Model.InvalidRequestException ex) when (ex.Message.Contains("index") || ex.Message.Contains("Index"))
                {
                    // Index still not ready, continue waiting
                    _logger.LogInformation("Index still not ready, continuing to wait...");
                    continue;
                }
            }

            _logger.LogWarning("Timeout waiting for search index to be ready after configuration update");
            return new List<ThingDocument>();
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't set up search index configuration. Here's why: {ex.Message}");
            return new List<ThingDocument>();
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[SearchIndex](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/SearchIndex)」を参照してください。

### `UpdateThing`
<a name="iot_UpdateThing_csharp_4_topic"></a>

次の例は、`UpdateThing` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Updates an IoT Thing with attributes.
    /// </summary>
    /// <param name="thingName">The name of the Thing to update.</param>
    /// <param name="attributes">Dictionary of attributes to add.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> UpdateThingAsync(string thingName, Dictionary<string, string> attributes)
    {
        try
        {
            var request = new UpdateThingRequest
            {
                ThingName = thingName,
                AttributePayload = new AttributePayload
                {
                    Attributes = attributes,
                    Merge = true
                }
            };

            await _amazonIoT.UpdateThingAsync(request);
            _logger.LogInformation($"Updated Thing {thingName} with attributes");
            return true;
        }
        catch (Amazon.IoT.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot update Thing - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't update Thing attributes. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[UpdateThing](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-2015-05-28/UpdateThing)」を参照してください。

# AWS IoT data SDK for .NET (v4) を使用した例
<a name="csharp_4_iot-data-plane_code_examples"></a>

次のコード例は、 で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT data。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetThingShadow`
<a name="iot-data-plane_GetThingShadow_csharp_4_topic"></a>

次の例は、`GetThingShadow` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Gets the Thing's shadow information.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <returns>The shadow data as a string, or null if retrieval failed.</returns>
    public async Task<string?> GetThingShadowAsync(string thingName)
    {
        try
        {
            var request = new GetThingShadowRequest
            {
                ThingName = thingName
            };

            var response = await _amazonIotData.GetThingShadowAsync(request);
            using var reader = new StreamReader(response.Payload);
            var shadowData = await reader.ReadToEndAsync();

            _logger.LogInformation($"Retrieved shadow for Thing {thingName}");
            return shadowData;
        }
        catch (Amazon.IotData.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot get Thing shadow - resource not found: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't get Thing shadow. Here's why: {ex.Message}");
            return null;
        }
    }
```
+  API の詳細については、「* API リファレンスAWS SDK for .NET *」の「[GetThingShadow](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-data-2015-05-28/GetThingShadow)」を参照してください。

### `UpdateThingShadow`
<a name="iot-data-plane_UpdateThingShadow_csharp_4_topic"></a>

次の例は、`UpdateThingShadow` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/IoT#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Updates the Thing's shadow with new state information.
    /// </summary>
    /// <param name="thingName">The name of the Thing.</param>
    /// <param name="shadowPayload">The shadow payload in JSON format.</param>
    /// <returns>True if successful, false otherwise.</returns>
    public async Task<bool> UpdateThingShadowAsync(string thingName, string shadowPayload)
    {
        try
        {
            var request = new UpdateThingShadowRequest
            {
                ThingName = thingName,
                Payload = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(shadowPayload))
            };

            await _amazonIotData.UpdateThingShadowAsync(request);
            _logger.LogInformation($"Updated shadow for Thing {thingName}");
            return true;
        }
        catch (Amazon.IotData.Model.ResourceNotFoundException ex)
        {
            _logger.LogError($"Cannot update Thing shadow - resource not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError($"Couldn't update Thing shadow. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス**」の「[UpdateThingShadow](https://docs.aws.amazon.com/goto/DotNetSDKV4/iot-data-2015-05-28/UpdateThingShadow)」を参照してください。

# SDK for .NET (v4) を使用した Amazon Redshift の例
<a name="csharp_4_redshift_code_examples"></a>

次のコード例は、Amazon Redshift で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Redshift
<a name="redshift_Hello_csharp_4_topic"></a>

次のコード例は、Amazon Redshift の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Main method to run the Hello Amazon Redshift example.
    /// </summary>
    /// <param name="args">Command line arguments (not used).</param>
    public static async Task Main(string[] args)
    {
        var redshiftClient = new AmazonRedshiftClient();

        Console.WriteLine("Hello, Amazon Redshift! Let's list available clusters:");

        var clusters = new List<Cluster>();

        try
        {
            // Use pagination to retrieve all clusters.
            var clustersPaginator = redshiftClient.Paginators.DescribeClusters(new DescribeClustersRequest());

            await foreach (var response in clustersPaginator.Responses)
            {
                if (response.Clusters != null)
                    clusters.AddRange(response.Clusters);
            }

            Console.WriteLine($"{clusters.Count} cluster(s) retrieved.");

            foreach (var cluster in clusters)
            {
                Console.WriteLine($"\t{cluster.ClusterIdentifier} (Status: {cluster.ClusterStatus})");
            }
        }
        catch (AmazonRedshiftException ex)
        {
            Console.WriteLine($"Couldn't list clusters. Here's why: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeClusters](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/DescribeClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="redshift_Scenario_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Redshift クラスターを作成します。
+ クラスター内のデータベースを一覧表示します。
+ Movies という名前のテーブルを作成します。
+ Movies テーブルにデータを入力します。
+ Movies テーブルに対して年に基づくクエリを実行します。
+ Redshift クラスターを変更します。
+ Amazon Redshift クラスターを削除します。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。
オペレーションを管理する Redshift ラッパークラスを作成します。  

```
/// <summary>
/// Wrapper class for Amazon Redshift operations.
/// </summary>
public class RedshiftWrapper
{
    private readonly IAmazonRedshift _redshiftClient;
    private readonly IAmazonRedshiftDataAPIService _redshiftDataClient;

    /// <summary>
    /// Constructor for RedshiftWrapper.
    /// </summary>
    /// <param name="redshiftClient">Amazon Redshift client.</param>
    /// <param name="redshiftDataClient">Amazon Redshift Data API client.</param>
    public RedshiftWrapper(IAmazonRedshift redshiftClient, IAmazonRedshiftDataAPIService redshiftDataClient)
    {
        _redshiftClient = redshiftClient;
        _redshiftDataClient = redshiftDataClient;
    }

    /// <summary>
    /// Create a new Amazon Redshift cluster.
    /// </summary>
    /// <param name="clusterIdentifier">The identifier for the cluster.</param>
    /// <param name="databaseName">The name of the database.</param>
    /// <param name="masterUsername">The master username.</param>
    /// <param name="masterUserPassword">The master user password.</param>
    /// <param name="nodeType">The node type for the cluster.</param>
    /// <returns>The cluster that was created.</returns>
    public async Task<Cluster> CreateClusterAsync(string clusterIdentifier, string databaseName,
        string masterUsername, string masterUserPassword, string nodeType = "ra3.large")
    {
        try
        {
            var request = new CreateClusterRequest
            {
                ClusterIdentifier = clusterIdentifier,
                DBName = databaseName,
                MasterUsername = masterUsername,
                MasterUserPassword = masterUserPassword,
                NodeType = nodeType,
                NumberOfNodes = 1,
                ClusterType = "single-node"
            };

            var response = await _redshiftClient.CreateClusterAsync(request);
            Console.WriteLine($"Created cluster {clusterIdentifier}");
            return response.Cluster;
        }
        catch (ClusterAlreadyExistsException ex)
        {
            Console.WriteLine($"Cluster already exists: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't create cluster. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Describe Amazon Redshift clusters.
    /// </summary>
    /// <param name="clusterIdentifier">Optional cluster identifier to describe a specific cluster.</param>
    /// <returns>A list of clusters.</returns>
    public async Task<List<Cluster>> DescribeClustersAsync(string? clusterIdentifier = null)
    {
        try
        {
            var clusters = new List<Cluster>();
            var request = new DescribeClustersRequest();
            if (!string.IsNullOrEmpty(clusterIdentifier))
            {
                request.ClusterIdentifier = clusterIdentifier;
            }

            var clustersPaginator = _redshiftClient.Paginators.DescribeClusters(request);
            await foreach (var response in clustersPaginator.Responses)
            {
                if (response.Clusters != null)
                    clusters.AddRange(response.Clusters);
            }

            Console.WriteLine($"{clusters.Count} cluster(s) retrieved.");
            foreach (var cluster in clusters)
            {
                Console.WriteLine($"\t{cluster.ClusterIdentifier} (Status: {cluster.ClusterStatus})");
            }

            return clusters;
        }
        catch (ClusterNotFoundException ex)
        {
            Console.WriteLine($"Cluster {clusterIdentifier} not found: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't describe clusters. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Modify an Amazon Redshift cluster.
    /// </summary>
    /// <param name="clusterIdentifier">The identifier for the cluster.</param>
    /// <param name="preferredMaintenanceWindow">The preferred maintenance window.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyClusterAsync(string clusterIdentifier, string preferredMaintenanceWindow)
    {
        try
        {
            var request = new ModifyClusterRequest
            {
                ClusterIdentifier = clusterIdentifier,
                PreferredMaintenanceWindow = preferredMaintenanceWindow
            };

            var response = await _redshiftClient.ModifyClusterAsync(request);
            Console.WriteLine($"The modified cluster was successfully modified and has {response.Cluster.PreferredMaintenanceWindow} as the maintenance window");
            return true;
        }
        catch (ClusterNotFoundException ex)
        {
            Console.WriteLine($"Cluster {clusterIdentifier} not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't modify cluster. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// Delete an Amazon Redshift cluster without a final snapshot.
    /// </summary>
    /// <param name="clusterIdentifier">The identifier for the cluster.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteClusterWithoutSnapshotAsync(string clusterIdentifier)
    {
        try
        {
            var request = new DeleteClusterRequest
            {
                ClusterIdentifier = clusterIdentifier,
                SkipFinalClusterSnapshot = true
            };

            var response = await _redshiftClient.DeleteClusterAsync(request);
            Console.WriteLine($"The {clusterIdentifier} was deleted");
            return true;
        }
        catch (ClusterNotFoundException ex)
        {
            Console.WriteLine($"Cluster not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete cluster. Here's why: {ex.Message}");
            return false;
        }
    }

    /// <summary>
    /// List databases in a Redshift cluster.
    /// </summary>
    /// <param name="clusterIdentifier">The cluster identifier.</param>
    /// <param name="dbUser">The database user.</param>
    /// <param name="dbUser">The database name for authentication.</param>
    /// <returns>A list of database names.</returns>
    public async Task<List<string>> ListDatabasesAsync(string clusterIdentifier, string dbUser, string databaseName)
    {
        try
        {
            var request = new ListDatabasesRequest
            {
                ClusterIdentifier = clusterIdentifier,
                DbUser = dbUser,
                Database = databaseName
            };

            var response = await _redshiftDataClient.ListDatabasesAsync(request);
            var databases = new List<string>();

            foreach (var database in response.Databases)
            {
                Console.WriteLine($"The database name is : {database}");
                databases.Add(database);
            }

            return databases;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ValidationException ex)
        {
            Console.WriteLine($"Validation error: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't list databases. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Create a table in the Redshift database.
    /// </summary>
    /// <param name="clusterIdentifier">The cluster identifier.</param>
    /// <param name="database">The database name.</param>
    /// <param name="dbUser">The database user.</param>
    /// <returns>The statement ID.</returns>
    public async Task<string> CreateTableAsync(string clusterIdentifier, string database, string dbUser)
    {
        try
        {
            var sqlStatement = @"
                CREATE TABLE Movies (
                    id INTEGER PRIMARY KEY,
                    title VARCHAR(250) NOT NULL,
                    year INTEGER NOT NULL
                )";

            var request = new ExecuteStatementRequest
            {
                ClusterIdentifier = clusterIdentifier,
                Database = database,
                DbUser = dbUser,
                Sql = sqlStatement
            };

            var response = await _redshiftDataClient.ExecuteStatementAsync(request);
            await WaitForStatementToCompleteAsync(response.Id);
            Console.WriteLine("Table created: Movies");
            return response.Id;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ValidationException ex)
        {
            Console.WriteLine($"Validation error: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't create table. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Insert a record into the Movies table using parameterized query.
    /// </summary>
    /// <param name="clusterIdentifier">The cluster identifier.</param>
    /// <param name="database">The database name.</param>
    /// <param name="dbUser">The database user.</param>
    /// <param name="id">The movie ID.</param>
    /// <param name="title">The movie title.</param>
    /// <param name="year">The movie year.</param>
    /// <returns>The statement ID.</returns>
    public async Task<string> InsertMovieAsync(string clusterIdentifier, string database, string dbUser,
        int id, string title, int year)
    {
        try
        {
            var sqlStatement = "INSERT INTO Movies (id, title, year) VALUES (:id, :title, :year)";

            var request = new ExecuteStatementRequest
            {
                ClusterIdentifier = clusterIdentifier,
                Database = database,
                DbUser = dbUser,
                Sql = sqlStatement,
                Parameters = new List<SqlParameter>
                {
                    new SqlParameter { Name = "id", Value = id.ToString() },
                    new SqlParameter { Name = "title", Value = title },
                    new SqlParameter { Name = "year", Value = year.ToString() }
                }
            };

            var response = await _redshiftDataClient.ExecuteStatementAsync(request);
            await WaitForStatementToCompleteAsync(response.Id);
            Console.WriteLine($"Inserted: {title} ({year})");
            return response.Id;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ValidationException ex)
        {
            Console.WriteLine($"Validation error: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't insert movie. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Query movies by year using parameterized query.
    /// </summary>
    /// <param name="clusterIdentifier">The cluster identifier.</param>
    /// <param name="database">The database name.</param>
    /// <param name="dbUser">The database user.</param>
    /// <param name="year">The year to query.</param>
    /// <returns>A list of movie titles.</returns>
    public async Task<List<string>> QueryMoviesByYearAsync(string clusterIdentifier, string database,
        string dbUser, int year)
    {
        try
        {
            var sqlStatement = "SELECT title FROM Movies WHERE year = :year";

            var request = new ExecuteStatementRequest
            {
                ClusterIdentifier = clusterIdentifier,
                Database = database,
                DbUser = dbUser,
                Sql = sqlStatement,
                Parameters = new List<SqlParameter>
                {
                    new SqlParameter { Name = "year", Value = year.ToString() }
                }
            };

            var response = await _redshiftDataClient.ExecuteStatementAsync(request);
            Console.WriteLine($"The identifier of the statement is {response.Id}");

            await WaitForStatementToCompleteAsync(response.Id);

            var results = await GetStatementResultAsync(response.Id);
            var movieTitles = new List<string>();

            foreach (var row in results)
            {
                if (row.Count > 0)
                {
                    var title = row[0].StringValue;
                    Console.WriteLine($"The Movie title field is {title}");
                    movieTitles.Add(title);
                }
            }

            return movieTitles;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ValidationException ex)
        {
            Console.WriteLine($"Validation error: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't query movies. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Describe a statement execution.
    /// </summary>
    /// <param name="statementId">The statement ID.</param>
    /// <returns>The statement description.</returns>
    public async Task<DescribeStatementResponse> DescribeStatementAsync(string statementId)
    {
        try
        {
            var request = new DescribeStatementRequest
            {
                Id = statementId
            };

            var response = await _redshiftDataClient.DescribeStatementAsync(request);
            return response;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ResourceNotFoundException ex)
        {
            Console.WriteLine($"Statement not found: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't describe statement. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Get the results of a statement execution.
    /// </summary>
    /// <param name="statementId">The statement ID.</param>
    /// <returns>A list of result rows.</returns>
    public async Task<List<List<Field>>> GetStatementResultAsync(string statementId)
    {
        try
        {
            var request = new GetStatementResultRequest
            {
                Id = statementId
            };

            var response = await _redshiftDataClient.GetStatementResultAsync(request);
            return response.Records;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ResourceNotFoundException ex)
        {
            Console.WriteLine($"Statement not found: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't get statement result. Here's why: {ex.Message}");
            throw;
        }
    }

    /// <summary>
    /// Wait for a statement to complete execution.
    /// </summary>
    /// <param name="statementId">The statement ID.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    private async Task WaitForStatementToCompleteAsync(string statementId)
    {
        var status = StatusString.SUBMITTED;
        DescribeStatementResponse? response = null;

        while (status == StatusString.SUBMITTED || status == StatusString.PICKED || status == StatusString.STARTED)
        {
            await Task.Delay(1000); // Wait 1 second
            response = await DescribeStatementAsync(statementId);
            status = response.Status;
            Console.WriteLine($"...{status}");
        }

        if (status == StatusString.FINISHED)
        {
            Console.WriteLine("The statement is finished!");
        }
        else
        {
            var errorMessage = response?.Error ?? "Unknown error";
            Console.WriteLine($"The statement failed with status: {status}");
            Console.WriteLine($"Error message: {errorMessage}");
        }
    }

    /// <summary>
    /// Wait for a cluster to become available.
    /// </summary>
    /// <param name="clusterIdentifier">The cluster identifier.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    public async Task WaitForClusterAvailableAsync(string clusterIdentifier)
    {
        Console.WriteLine($"Wait until {clusterIdentifier} is available. This may take a few minutes.");

        var startTime = DateTime.Now;
        var clusters = await DescribeClustersAsync(clusterIdentifier);

        while (clusters[0].ClusterStatus != "available")
        {
            var elapsed = DateTime.Now - startTime;
            Console.WriteLine($"Elapsed Time: {elapsed:mm\\:ss} - Waiting for cluster...");

            await Task.Delay(5000); // Wait 5 seconds
            clusters = await DescribeClustersAsync(clusterIdentifier);
        }

        var totalElapsed = DateTime.Now - startTime;
        Console.WriteLine($"Cluster is available! Total Elapsed Time: {totalElapsed:mm\\:ss}");
    }
}
```
Redshift の基本機能を示すインタラクティブなシナリオを実行します。  

```
/// <summary>
/// Amazon Redshift Getting Started Scenario.
/// </summary>
public class RedshiftBasics
{
    public static bool IsInteractive = true;
    public static RedshiftWrapper? Wrapper = null;
    public static ILogger logger = null!;
    private static readonly string _moviesFilePath = "../../../../../../resources/sample_files/movies.json";

    /// <summary>
    /// Main method for the Amazon Redshift Getting Started scenario.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    public static async Task Main(string[] args)
    {
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonRedshift>()
                    .AddAWSService<IAmazonRedshiftDataAPIService>()
                    .AddTransient<RedshiftWrapper>()
            )
            .Build();

        logger = LoggerFactory.Create(builder => { builder.AddConsole(); })
            .CreateLogger<RedshiftBasics>();

        Wrapper = host.Services.GetRequiredService<RedshiftWrapper>();

        await RunScenarioAsync();
    }

    /// <summary>
    /// Run the complete Amazon Redshift scenario.
    /// </summary>
    public static async Task RunScenarioAsync()
    {
        // Set all variables to default values
        string userName = "awsuser";
        string userPassword = "AwsUser1000";
        string clusterIdentifier = "redshift-cluster-movies";
        var databaseName = "dev";
        int recordCount = 50;
        int year = 2013;
        try
        {
            Console.WriteLine(
                "================================================================================");
            Console.WriteLine("Welcome to the Amazon Redshift SDK Getting Started scenario.");
            Console.WriteLine(
                "This .NET program demonstrates how to interact with Amazon Redshift by using the AWS SDK for .NET.");
            Console.WriteLine("Let's get started...");
            Console.WriteLine(
                "================================================================================");

            // Step 1: Get user credentials (if interactive)
            if (IsInteractive)
            {
                Console.WriteLine("Please enter a user name for the cluster (default is awsuser):");
                var userInput = Console.ReadLine();
                if (!string.IsNullOrEmpty(userInput))
                    userName = userInput;

                Console.WriteLine("================================================================================");
                Console.WriteLine("Please enter a user password for the cluster (default is AwsUser1000):");
                var passwordInput = Console.ReadLine();
                if (!string.IsNullOrEmpty(passwordInput))
                    userPassword = passwordInput;

                Console.WriteLine("================================================================================");

                // Step 2: Get cluster identifier
                Console.WriteLine("Enter a cluster id value (default is redshift-cluster-movies):");
                var clusterInput = Console.ReadLine();
                if (!string.IsNullOrEmpty(clusterInput))
                    clusterIdentifier = clusterInput;
            }
            else
            {
                Console.WriteLine($"Using default values: userName={userName}, clusterIdentifier={clusterIdentifier}");
            }

            // Step 3: Create Redshift cluster
            await Wrapper!.CreateClusterAsync(clusterIdentifier, databaseName, userName, userPassword);
            Console.WriteLine("================================================================================");

            // Step 4: Wait for cluster to become available
            Console.WriteLine("================================================================================");
            await Wrapper.WaitForClusterAvailableAsync(clusterIdentifier);
            Console.WriteLine("================================================================================");

            // Step 5: List databases
            Console.WriteLine("================================================================================");
            Console.WriteLine($" When you created {clusterIdentifier}, the dev database is created by default and used in this scenario.");
            Console.WriteLine(" To create a custom database, you need to have a CREATEDB privilege.");
            Console.WriteLine(" For more information, see the documentation here: https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_DATABASE.html.");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }
            Console.WriteLine("================================================================================");

            Console.WriteLine("================================================================================");
            Console.WriteLine($"List databases in {clusterIdentifier}");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }
            await Wrapper.ListDatabasesAsync(clusterIdentifier, userName, databaseName);
            Console.WriteLine("================================================================================");

            // Step 6: Create Movies table
            Console.WriteLine("================================================================================");
            Console.WriteLine("Now you will create a table named Movies.");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }
            await Wrapper.CreateTableAsync(clusterIdentifier, databaseName, userName);
            Console.WriteLine("================================================================================");

            // Step 7: Populate the Movies table
            Console.WriteLine("================================================================================");
            Console.WriteLine("Populate the Movies table using the Movies.json file.");

            if (IsInteractive)
            {
                Console.WriteLine("Specify the number of records you would like to add to the Movies Table.");
                Console.WriteLine("Please enter a value between 50 and 200.");
                Console.Write("Enter a value: ");

                var recordCountInput = Console.ReadLine();
                if (int.TryParse(recordCountInput, out var inputCount) && inputCount is >= 50 and <= 200)
                {
                    recordCount = inputCount;
                }
                else
                {
                    Console.WriteLine($"Invalid input. Using default value of {recordCount}.");
                }
            }
            else
            {
                Console.WriteLine($"Using default record count: {recordCount}");
            }

            await PopulateMoviesTableAsync(clusterIdentifier, databaseName, userName, recordCount);
            Console.WriteLine($"{recordCount} records were added to the Movies table.");
            Console.WriteLine("================================================================================");

            // Step 8 & 9: Query movies by year
            Console.WriteLine("================================================================================");
            Console.WriteLine("Query the Movies table by year. Enter a value between 2012-2014.");

            if (IsInteractive)
            {
                Console.Write("Enter a year: ");
                var yearInput = Console.ReadLine();
                if (int.TryParse(yearInput, out var inputYear) && inputYear is >= 2012 and <= 2014)
                {
                    year = inputYear;
                }
                else
                {
                    Console.WriteLine($"Invalid input. Using default value of {year}.");
                }
            }
            else
            {
                Console.WriteLine($"Using default year: {year}");
            }

            await Wrapper.QueryMoviesByYearAsync(clusterIdentifier, databaseName, userName, year);
            Console.WriteLine("================================================================================");

            // Step 10: Modify the cluster
            Console.WriteLine("================================================================================");
            Console.WriteLine("Now you will modify the Redshift cluster.");
            if (IsInteractive)
            {
                Console.WriteLine("Press Enter to continue...");
                Console.ReadLine();
            }
            await Wrapper.ModifyClusterAsync(clusterIdentifier, "wed:07:30-wed:08:00");
            Console.WriteLine("================================================================================");

            // Step 11 & 12: Delete cluster confirmation
            Console.WriteLine("================================================================================");
            if (IsInteractive)
            {
                Console.WriteLine("Would you like to delete the Amazon Redshift cluster? (y/n)");
                var deleteResponse = Console.ReadLine();
                if (deleteResponse?.ToLower() == "y")
                {
                    await Wrapper.DeleteClusterWithoutSnapshotAsync(clusterIdentifier);
                }
            }
            else
            {
                Console.WriteLine("Deleting the Amazon Redshift cluster...");
                await Wrapper.DeleteClusterWithoutSnapshotAsync(clusterIdentifier);
            }
            Console.WriteLine("================================================================================");

            Console.WriteLine("================================================================================");
            Console.WriteLine("This concludes the Amazon Redshift SDK Getting Started scenario.");
            Console.WriteLine("================================================================================");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred during the scenario: {ex.Message}");
            Console.WriteLine("Deleting the Amazon Redshift cluster...");
            await Wrapper!.DeleteClusterWithoutSnapshotAsync(clusterIdentifier);
            throw;
        }
    }

    /// <summary>
    /// Populate the Movies table with data from the JSON file.
    /// </summary>
    /// <param name="clusterIdentifier">The cluster identifier.</param>
    /// <param name="database">The database name.</param>
    /// <param name="dbUser">The database user.</param>
    /// <param name="recordCount">Number of records to insert.</param>
    private static async Task PopulateMoviesTableAsync(string clusterIdentifier, string database, string dbUser, int recordCount)
    {
        if (!File.Exists(_moviesFilePath))
        {
            throw new FileNotFoundException($"Required movies data file not found at: {_moviesFilePath}");
        }

        var jsonContent = await File.ReadAllTextAsync(_moviesFilePath);
        var options = new JsonSerializerOptions
        {
            PropertyNameCaseInsensitive = true
        };
        var movies = JsonSerializer.Deserialize<List<Movie>>(jsonContent, options);

        if (movies == null || movies.Count == 0)
        {
            throw new InvalidOperationException("Failed to parse movies JSON file or file is empty.");
        }

        var insertCount = Math.Min(recordCount, movies.Count);

        for (int i = 0; i < insertCount; i++)
        {
            var movie = movies[i];
            await Wrapper!.InsertMovieAsync(clusterIdentifier, database, dbUser, i, movie.Title, movie.Year);
        }
    }

    /// <summary>
    /// Movie data model.
    /// </summary>
    private class Movie
    {
        public string Title { get; set; } = string.Empty;
        public int Year { get; set; }
    }
}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CreateCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/CreateCluster)
  + [DescribeClusters](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/DescribeClusters)
  + [DescribeStatement](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/DescribeStatement)
  + [ExecuteStatement](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/ExecuteStatement)
  + [GetStatementResult](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/GetStatementResult)
  + [ListDatabasesPaginator](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/ListDatabasesPaginator)
  + [ModifyCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/ModifyCluster)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="redshift_CreateCluster_csharp_4_topic"></a>

次の例は、`CreateCluster` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Create a new Amazon Redshift cluster.
    /// </summary>
    /// <param name="clusterIdentifier">The identifier for the cluster.</param>
    /// <param name="databaseName">The name of the database.</param>
    /// <param name="masterUsername">The master username.</param>
    /// <param name="masterUserPassword">The master user password.</param>
    /// <param name="nodeType">The node type for the cluster.</param>
    /// <returns>The cluster that was created.</returns>
    public async Task<Cluster> CreateClusterAsync(string clusterIdentifier, string databaseName,
        string masterUsername, string masterUserPassword, string nodeType = "ra3.large")
    {
        try
        {
            var request = new CreateClusterRequest
            {
                ClusterIdentifier = clusterIdentifier,
                DBName = databaseName,
                MasterUsername = masterUsername,
                MasterUserPassword = masterUserPassword,
                NodeType = nodeType,
                NumberOfNodes = 1,
                ClusterType = "single-node"
            };

            var response = await _redshiftClient.CreateClusterAsync(request);
            Console.WriteLine($"Created cluster {clusterIdentifier}");
            return response.Cluster;
        }
        catch (ClusterAlreadyExistsException ex)
        {
            Console.WriteLine($"Cluster already exists: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't create cluster. Here's why: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CreateCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/CreateCluster)」を参照してください。

### `DeleteCluster`
<a name="redshift_DeleteCluster_csharp_4_topic"></a>

次の例は、`DeleteCluster` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete an Amazon Redshift cluster without a final snapshot.
    /// </summary>
    /// <param name="clusterIdentifier">The identifier for the cluster.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> DeleteClusterWithoutSnapshotAsync(string clusterIdentifier)
    {
        try
        {
            var request = new DeleteClusterRequest
            {
                ClusterIdentifier = clusterIdentifier,
                SkipFinalClusterSnapshot = true
            };

            var response = await _redshiftClient.DeleteClusterAsync(request);
            Console.WriteLine($"The {clusterIdentifier} was deleted");
            return true;
        }
        catch (ClusterNotFoundException ex)
        {
            Console.WriteLine($"Cluster not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't delete cluster. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DeleteCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/DeleteCluster)」を参照してください。

### `DescribeClusters`
<a name="redshift_DescribeClusters_csharp_4_topic"></a>

次の例は、`DescribeClusters` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe Amazon Redshift clusters.
    /// </summary>
    /// <param name="clusterIdentifier">Optional cluster identifier to describe a specific cluster.</param>
    /// <returns>A list of clusters.</returns>
    public async Task<List<Cluster>> DescribeClustersAsync(string? clusterIdentifier = null)
    {
        try
        {
            var clusters = new List<Cluster>();
            var request = new DescribeClustersRequest();
            if (!string.IsNullOrEmpty(clusterIdentifier))
            {
                request.ClusterIdentifier = clusterIdentifier;
            }

            var clustersPaginator = _redshiftClient.Paginators.DescribeClusters(request);
            await foreach (var response in clustersPaginator.Responses)
            {
                if (response.Clusters != null)
                    clusters.AddRange(response.Clusters);
            }

            Console.WriteLine($"{clusters.Count} cluster(s) retrieved.");
            foreach (var cluster in clusters)
            {
                Console.WriteLine($"\t{cluster.ClusterIdentifier} (Status: {cluster.ClusterStatus})");
            }

            return clusters;
        }
        catch (ClusterNotFoundException ex)
        {
            Console.WriteLine($"Cluster {clusterIdentifier} not found: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't describe clusters. Here's why: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[DescribeClusters](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/DescribeClusters)」を参照してください。

### `DescribeStatement`
<a name="redshift_DescribeStatement_csharp_4_topic"></a>

次の例は、`DescribeStatement` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Describe a statement execution.
    /// </summary>
    /// <param name="statementId">The statement ID.</param>
    /// <returns>The statement description.</returns>
    public async Task<DescribeStatementResponse> DescribeStatementAsync(string statementId)
    {
        try
        {
            var request = new DescribeStatementRequest
            {
                Id = statementId
            };

            var response = await _redshiftDataClient.DescribeStatementAsync(request);
            return response;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ResourceNotFoundException ex)
        {
            Console.WriteLine($"Statement not found: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't describe statement. Here's why: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[DescribeStatement](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/DescribeStatement)」を参照してください。

### `GetStatementResult`
<a name="redshift_GetStatementResult_csharp_4_topic"></a>

次の例は、`GetStatementResult` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Get the results of a statement execution.
    /// </summary>
    /// <param name="statementId">The statement ID.</param>
    /// <returns>A list of result rows.</returns>
    public async Task<List<List<Field>>> GetStatementResultAsync(string statementId)
    {
        try
        {
            var request = new GetStatementResultRequest
            {
                Id = statementId
            };

            var response = await _redshiftDataClient.GetStatementResultAsync(request);
            return response.Records;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ResourceNotFoundException ex)
        {
            Console.WriteLine($"Statement not found: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't get statement result. Here's why: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、**「AWS SDK for .NET API リファレンス」の「[GetStatementResult](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/GetStatementResult)」を参照してください。

### `ListDatabases`
<a name="redshift_ListDatabases_csharp_4_topic"></a>

次の例は、`ListDatabases` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// List databases in a Redshift cluster.
    /// </summary>
    /// <param name="clusterIdentifier">The cluster identifier.</param>
    /// <param name="dbUser">The database user.</param>
    /// <param name="dbUser">The database name for authentication.</param>
    /// <returns>A list of database names.</returns>
    public async Task<List<string>> ListDatabasesAsync(string clusterIdentifier, string dbUser, string databaseName)
    {
        try
        {
            var request = new ListDatabasesRequest
            {
                ClusterIdentifier = clusterIdentifier,
                DbUser = dbUser,
                Database = databaseName
            };

            var response = await _redshiftDataClient.ListDatabasesAsync(request);
            var databases = new List<string>();

            foreach (var database in response.Databases)
            {
                Console.WriteLine($"The database name is : {database}");
                databases.Add(database);
            }

            return databases;
        }
        catch (Amazon.RedshiftDataAPIService.Model.ValidationException ex)
        {
            Console.WriteLine($"Validation error: {ex.Message}");
            throw;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't list databases. Here's why: {ex.Message}");
            throw;
        }
    }
```
+  API の詳細については、「AWS SDK for .NET API リファレンス」の「[ListDatabases](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/ListDatabases)」を参照してください。**

### `ModifyCluster`
<a name="redshift_ModifyCluster_csharp_4_topic"></a>

次の例は、`ModifyCluster` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/Redshift#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Modify an Amazon Redshift cluster.
    /// </summary>
    /// <param name="clusterIdentifier">The identifier for the cluster.</param>
    /// <param name="preferredMaintenanceWindow">The preferred maintenance window.</param>
    /// <returns>True if successful.</returns>
    public async Task<bool> ModifyClusterAsync(string clusterIdentifier, string preferredMaintenanceWindow)
    {
        try
        {
            var request = new ModifyClusterRequest
            {
                ClusterIdentifier = clusterIdentifier,
                PreferredMaintenanceWindow = preferredMaintenanceWindow
            };

            var response = await _redshiftClient.ModifyClusterAsync(request);
            Console.WriteLine($"The modified cluster was successfully modified and has {response.Cluster.PreferredMaintenanceWindow} as the maintenance window");
            return true;
        }
        catch (ClusterNotFoundException ex)
        {
            Console.WriteLine($"Cluster {clusterIdentifier} not found: {ex.Message}");
            return false;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't modify cluster. Here's why: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[ModifyCluster](https://docs.aws.amazon.com/goto/DotNetSDKV4/redshift-2012-12-01/ModifyCluster)」を参照してください。

# SDK for .NET (v4) を使用した Amazon S3 の例
<a name="csharp_4_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS SDK for .NET (v4) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_csharp_4_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
/// <summary>
/// Hello Amazon Simple Storage Service
// (Amazon S3) example.
/// </summary>
public class HelloS3
{
    /// <summary>
    /// Main method to run the Hello S3 example.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    /// <returns>A Task object.</returns>
    public static async Task Main(string[] args)
    {
        var s3Client = new AmazonS3Client();

        try
        {
            Console.WriteLine("Hello Amazon S3! Let's list your buckets:");
            Console.WriteLine(new string('-', 80));

            // Use the built-in paginator to list buckets
            var request = new ListBucketsRequest();
            var paginator = s3Client.Paginators.ListBuckets(request);

            var buckets = new List<S3Bucket>();

            await foreach (var response in paginator.Responses)
            {
                buckets.AddRange(response.Buckets);
            }

            if (buckets.Any())
            {
                Console.WriteLine($"Found {buckets.Count} S3 buckets:");
                Console.WriteLine();

                foreach (var bucket in buckets)
                {
                    Console.WriteLine($"- Bucket Name: {bucket.BucketName}");
                    Console.WriteLine($"  Creation Date: {bucket.CreationDate:yyyy-MM-dd HH:mm:ss UTC}");
                    Console.WriteLine();
                }
            }
            else
            {
                Console.WriteLine("No S3 buckets found in your account.");
            }

            Console.WriteLine("Hello S3 completed successfully.");
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"S3 service error occurred: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Couldn't list S3 buckets. Here's why: {ex.Message}");
        }
    }
}
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/ListBuckets)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_csharp_4_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。
Amazon S3 機能を示すインタラクティブなシナリオを実行します。  

```
public class S3_Basics
{
    public static bool IsInteractive = true;
    public static string BucketName = null!;
    public static string TempFilePath = null!;
    public static S3Wrapper _s3Wrapper = null!;
    public static ILogger<S3_Basics> _logger = null!;

    public static async Task Main(string[] args)
    {
        // Set up dependency injection for the Amazon service.
        using var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonS3>()
                    .AddTransient<S3Wrapper>()
                    .AddLogging(builder => builder.AddConsole()))
            .Build();

        _logger = LoggerFactory.Create(builder => builder.AddConsole())
            .CreateLogger<S3_Basics>();

        _s3Wrapper = host.Services.GetRequiredService<S3Wrapper>();

        var sepBar = new string('-', 45);

        Console.WriteLine(sepBar);
        Console.WriteLine("Amazon Simple Storage Service (Amazon S3) basic");
        Console.WriteLine("procedures. This application will:");
        Console.WriteLine("\n\t1. Create a bucket");
        Console.WriteLine("\n\t2. Upload an object to the new bucket");
        Console.WriteLine("\n\t3. Copy the uploaded object to a folder in the bucket");
        Console.WriteLine("\n\t4. List the items in the new bucket");
        Console.WriteLine("\n\t5. Delete all the items in the bucket");
        Console.WriteLine("\n\t6. Delete the bucket");
        Console.WriteLine(sepBar);

        await RunScenario(_s3Wrapper, _logger);

        Console.WriteLine(sepBar);
        Console.WriteLine("The Amazon S3 scenario has successfully completed.");
        Console.WriteLine(sepBar);
    }

    /// <summary>
    /// Run the S3 Basics scenario with injected dependencies.
    /// </summary>
    /// <param name="s3Wrapper">The S3 wrapper instance.</param>
    /// <param name="scenarioLogger">The logger instance.</param>
    /// <returns>A Task object.</returns>
    public static async Task RunScenario(S3Wrapper s3Wrapper, ILogger<S3_Basics> scenarioLogger)
    {
        string bucketName = BucketName;
        string filePath = TempFilePath;
        string keyName = string.Empty;

        var sepBar = new string('-', 45);

        try
        {
            // Create a bucket.
            Console.WriteLine($"\n{sepBar}");
            Console.WriteLine("\nCreate a new Amazon S3 bucket.\n");
            Console.WriteLine(sepBar);

            if (IsInteractive)
            {
                Console.Write("Please enter a name for the new bucket: ");
                bucketName = Console.ReadLine();
            }
            else
            {
                Console.WriteLine($"Using bucket name: {bucketName}");
            }

            var success = await s3Wrapper.CreateBucketAsync(bucketName);
            if (success)
            {
                Console.WriteLine($"Successfully created bucket: {bucketName}.\n");
            }
            else
            {
                Console.WriteLine($"Could not create bucket: {bucketName}.\n");
            }

            Console.WriteLine(sepBar);
            Console.WriteLine("Upload a file to the new bucket.");
            Console.WriteLine(sepBar);

            if (IsInteractive)
            {
                // Get the local path and filename for the file to upload.
                while (string.IsNullOrEmpty(filePath))
                {
                    Console.Write("Please enter the path and filename of the file to upload: ");
                    filePath = Console.ReadLine();

                    // Confirm that the file exists on the local computer.
                    if (!File.Exists(filePath))
                    {
                        Console.WriteLine($"Couldn't find {filePath}. Try again.\n");
                        filePath = string.Empty;
                    }
                }
            }
            else
            {
                // Use the public variable if set, otherwise create a temp file
                if (!string.IsNullOrEmpty(TempFilePath))
                {
                    filePath = TempFilePath;
                    Console.WriteLine($"Using provided test file: {filePath}");
                }
                else
                {
                    // Create a temporary test file for non-interactive mode
                    filePath = Path.GetTempFileName();
                    var testContent = "This is a test file for S3 basics scenario.\nGenerated on: " + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss UTC");
                    await File.WriteAllTextAsync(filePath, testContent);
                    Console.WriteLine($"Created temporary test file: {filePath}");
                }
            }

            // Get the file name from the full path.
            keyName = Path.GetFileName(filePath);

            success = await s3Wrapper.UploadFileAsync(bucketName, keyName, filePath);

            if (success)
            {
                Console.WriteLine($"Successfully uploaded {keyName} from {filePath} to {bucketName}.\n");
            }
            else
            {
                Console.WriteLine($"Could not upload {keyName}.\n");
            }

            // Set up download path
            string downloadPath = string.Empty;

            if (IsInteractive)
            {
                // Now get a new location where we can save the file.
                while (string.IsNullOrEmpty(downloadPath))
                {
                    // First get the path to which the file will be downloaded.
                    Console.Write("Please enter the path where the file will be downloaded: ");
                    downloadPath = Console.ReadLine();

                    // Confirm that the file doesn't already exist on the local computer.
                    if (File.Exists($"{downloadPath}\\{keyName}"))
                    {
                        Console.WriteLine($"Sorry, the file already exists in that location.\n");
                        downloadPath = string.Empty;
                    }
                }
            }
            else
            {
                downloadPath = Path.GetTempPath();
                var downloadFile = Path.Combine(downloadPath, keyName);
                if (File.Exists(downloadFile))
                {
                    File.Delete(downloadFile);
                }

                Console.WriteLine($"Using download path: {downloadPath}");
            }

            // Download an object from a bucket.
            success = await s3Wrapper.DownloadObjectFromBucketAsync(bucketName, keyName, downloadPath);

            if (success)
            {
                Console.WriteLine($"Successfully downloaded {keyName}.\n");
            }
            else
            {
                Console.WriteLine($"Sorry, could not download {keyName}.\n");
            }

            // Copy the object to a different folder in the bucket.
            string folderName = string.Empty;

            if (IsInteractive)
            {
                while (string.IsNullOrEmpty(folderName))
                {
                    Console.Write("Please enter the name of the folder to copy your object to: ");
                    folderName = Console.ReadLine();
                }
            }
            else
            {
                folderName = "test-folder";
                Console.WriteLine($"Using folder name: {folderName}");
            }

            await s3Wrapper.CopyObjectInBucketAsync(bucketName, keyName, folderName);

            // List the objects in the bucket.
            await s3Wrapper.ListBucketContentsAsync(bucketName);

            // Delete the contents of the bucket.
            if (IsInteractive)
            {
                Console.WriteLine("Press <Enter> when you are ready to delete the bucket contents.");
                _ = Console.ReadLine();
            }

            var deleteContentsSuccess = await s3Wrapper.DeleteBucketContentsAsync(bucketName);
            if (deleteContentsSuccess)
            {
                Console.WriteLine($"Successfully deleted contents of {bucketName}.\n");
            }
            else
            {
                Console.WriteLine($"Sorry, could not delete contents of {bucketName}.\n");
            }

            if (IsInteractive)
            {
                // Deleting the bucket too quickly after separately deleting its contents can
                // cause an error that the bucket isn't empty. To delete contents and bucket in one
                // operation, use AmazonS3Util.DeleteS3BucketWithObjectsAsync
                Console.WriteLine("Press <Enter> when you are ready to delete the bucket.");
                _ = Console.ReadLine();
            }
            else
            {
                // Add a small delay for non-interactive mode to ensure objects are fully deleted.
                Console.WriteLine("Waiting a moment for objects to be fully deleted...");
                await Task.Delay(2000);
            }

            // Delete the bucket.
            var deleteSuccess = await s3Wrapper.DeleteBucketAsync(bucketName);
            if (deleteSuccess)
            {
                Console.WriteLine($"Successfully deleted {bucketName}.\n");
            }
            else
            {
                Console.WriteLine($"Sorry, could not delete {bucketName}.\n");
            }

            // Clean up temporary files in non-interactive mode
            if (!IsInteractive)
            {
                try
                {
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                        Console.WriteLine("Cleaned up temporary test file.");
                    }

                    var downloadFile = Path.Combine(downloadPath, keyName);
                    if (File.Exists(downloadFile))
                    {
                        File.Delete(downloadFile);
                        Console.WriteLine("Cleaned up downloaded test file.");
                    }
                }
                catch (Exception ex)
                {
                    scenarioLogger.LogWarning(ex, "Failed to clean up temporary files.");
                }
            }
        }
        catch (Exception ex)
        {
            scenarioLogger.LogError(ex, "An error occurred during the S3 scenario execution.");

            // Clean up on error - delete bucket if it exists
            try
            {
                if (!string.IsNullOrEmpty(bucketName))
                {
                    await s3Wrapper.DeleteBucketContentsAsync(bucketName);
                    await s3Wrapper.DeleteBucketAsync(bucketName);
                }
            }
            catch (Exception cleanupEx)
            {
                scenarioLogger.LogError(cleanupEx, "Error during cleanup.");
            }

            // Clean up temporary files in non-interactive mode
            if (!IsInteractive)
            {
                try
                {
                    if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }
                }
                catch (Exception fileCleanupEx)
                {
                    scenarioLogger.LogWarning(fileCleanupEx, "Failed to clean up temporary files during error handling.");
                }
            }

            throw;
        }
    }
}
```
Amazon S3 SDK メソッドのラッパークラス。  

```
using Amazon.S3;
using Amazon.S3.Model;

namespace S3_Actions;

/// <summary>
/// This class contains all of the methods for working with Amazon Simple
/// Storage Service (Amazon S3) buckets.
/// </summary>
public class S3Wrapper
{
    private readonly IAmazonS3 _amazonS3;

    /// <summary>
    /// Initializes a new instance of the <see cref="S3Wrapper"/> class.
    /// </summary>
    /// <param name="amazonS3">An initialized Amazon S3 client object.</param>
    public S3Wrapper(IAmazonS3 amazonS3)
    {
        _amazonS3 = amazonS3;
    }


    /// <summary>
    /// Shows how to create a new Amazon S3 bucket.
    /// </summary>
    /// <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 async Task<bool> CreateBucketAsync(string bucketName)
    {
        try
        {
            var request = new PutBucketRequest
            {
                BucketName = bucketName,
                UseClientRegion = true,
            };

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



    /// <summary>
    /// Shows how to upload a file from the local computer to an Amazon S3
    /// bucket.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to which the object
    /// will be uploaded.</param>
    /// <param name="objectName">The object to upload.</param>
    /// <param name="filePath">The path, including file name, of the object
    /// on the local computer to upload.</param>
    /// <returns>A boolean value indicating the success or failure of the
    /// upload procedure.</returns>
    public async Task<bool> UploadFileAsync(
        string bucketName,
        string objectName,
        string filePath)
    {
        try
        {
            var request = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = objectName,
                FilePath = filePath,
            };

            var response = await _amazonS3.PutObjectAsync(request);
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error uploading {objectName}: {ex.Message}");
            return false;
        }
    }



    /// <summary>
    /// Shows how to download an object from an Amazon S3 bucket to the
    /// local computer.
    /// </summary>
    /// <param name="bucketName">The name of the bucket where the object is
    /// currently stored.</param>
    /// <param name="objectName">The name of the object to download.</param>
    /// <param name="filePath">The path, including filename, where the
    /// downloaded object will be stored.</param>
    /// <returns>A boolean value indicating the success or failure of the
    /// download process.</returns>
    public async Task<bool> DownloadObjectFromBucketAsync(
        string bucketName,
        string objectName,
        string filePath)
    {
        var request = new GetObjectRequest
        {
            BucketName = bucketName,
            Key = objectName,
        };

        using GetObjectResponse response = await _amazonS3.GetObjectAsync(request);

        try
        {
            // Save object to local file
            await response.WriteResponseStreamToFileAsync($"{filePath}\\{objectName}", true, CancellationToken.None);
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error saving {objectName}: {ex.Message}");
            return false;
        }
    }



    /// <summary>
    /// Copies an object in an Amazon S3 bucket to a folder within the
    /// same bucket.
    /// </summary>
    /// <param name="bucketName">The name of the Amazon S3 bucket where the
    /// object to copy is located.</param>
    /// <param name="objectName">The object to be copied.</param>
    /// <param name="folderName">The folder to which the object will
    /// be copied.</param>
    /// <returns>A boolean value that indicates the success or failure of
    /// the copy operation.</returns>
    public async Task<bool> CopyObjectInBucketAsync(
        string bucketName,
        string objectName,
        string folderName)
    {
        try
        {
            var request = new CopyObjectRequest
            {
                SourceBucket = bucketName,
                SourceKey = objectName,
                DestinationBucket = bucketName,
                DestinationKey = $"{folderName}\\{objectName}",
            };
            var response = await _amazonS3.CopyObjectAsync(request);
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error copying object: '{ex.Message}'");
            return false;
        }
    }



    /// <summary>
    /// Shows how to list the objects in an Amazon S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket for which to list.
    /// <param name="printList">True to print out the list.
    /// <returns>The collection of objects.</returns>
    public async Task<List<S3Object>?> ListBucketContentsAsync(string bucketName, bool printList = true)
    {
        try
        {
            var request = new ListObjectsV2Request
            {
                BucketName = bucketName,
                MaxKeys = 5,
            };

            if (printList)
            {
                Console.WriteLine("--------------------------------------");
                Console.WriteLine($"Listing the contents of {bucketName}:");
                Console.WriteLine("--------------------------------------");
            }

            var listObjectsV2Paginator = _amazonS3.Paginators.ListObjectsV2(new ListObjectsV2Request
            {
                BucketName = bucketName,
            });
            var s3Objects = new List<S3Object>();
            await foreach (var response in listObjectsV2Paginator.Responses)
            {
                if (response.S3Objects != null)
                {
                    s3Objects.AddRange(response.S3Objects);
                }
            }

            if (printList)
            {
                Console.WriteLine($"Number of Objects: {s3Objects.Count}");
                foreach (var entry in s3Objects)
                {
                    Console.WriteLine($"Key = {entry.Key} Size = {entry.Size}");
                }
            }

            return s3Objects;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects.");
            return null;
        }
    }



    /// <summary>
    /// Delete all of the objects stored in an existing Amazon S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket from which the
    /// contents will be deleted.</param>
    /// <returns>A boolean value that represents the success or failure of
    /// deleting all of the objects in the bucket.</returns>
    public async Task<bool> DeleteBucketContentsAsync(string bucketName)
    {
        // Iterate over the contents of the bucket and delete all objects.
        try
        {
            // Delete all objects in the bucket.
            var deleteList = await ListBucketContentsAsync(bucketName, false);
            if (deleteList != null && deleteList.Any())
            {
                await _amazonS3.DeleteObjectsAsync(new DeleteObjectsRequest()
                {
                    BucketName = bucketName,
                    Objects = deleteList.Select(o => new KeyVersion { Key = o.Key }).ToList(),
                });
            }

            return true;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error deleting objects: {ex.Message}");
            return false;
        }
    }



    /// <summary>
    /// Shows how to delete an Amazon S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the Amazon S3 bucket to delete.</param>
    /// <returns>A boolean value that represents the success or failure of
    /// the delete operation.</returns>
    public async Task<bool> DeleteBucketAsync(string bucketName)
    {
        try
        {
            var request = new DeleteBucketRequest { BucketName = bucketName, };

            await _amazonS3.DeleteBucketAsync(request);
            return true;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error deleting bucket: {ex.Message}");
            return false;
        }
    }

}
```
+ API の詳細については、「*AWS SDK for .NET API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/GetObject)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/ListObjectsV2)
  + [PutObject](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_csharp_4_topic"></a>

次の例は、`CopyObject` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Copies an object in an Amazon S3 bucket to a folder within the
    /// same bucket.
    /// </summary>
    /// <param name="bucketName">The name of the Amazon S3 bucket where the
    /// object to copy is located.</param>
    /// <param name="objectName">The object to be copied.</param>
    /// <param name="folderName">The folder to which the object will
    /// be copied.</param>
    /// <returns>A boolean value that indicates the success or failure of
    /// the copy operation.</returns>
    public async Task<bool> CopyObjectInBucketAsync(
        string bucketName,
        string objectName,
        string folderName)
    {
        try
        {
            var request = new CopyObjectRequest
            {
                SourceBucket = bucketName,
                SourceKey = objectName,
                DestinationBucket = bucketName,
                DestinationKey = $"{folderName}\\{objectName}",
            };
            var response = await _amazonS3.CopyObjectAsync(request);
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error copying object: '{ex.Message}'");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[CopyObject](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/CopyObject)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_csharp_4_topic"></a>

次の例は、`CreateBucket` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Shows how to create a new Amazon S3 bucket.
    /// </summary>
    /// <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 async Task<bool> CreateBucketAsync(string bucketName)
    {
        try
        {
            var request = new PutBucketRequest
            {
                BucketName = bucketName,
                UseClientRegion = true,
            };

            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;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[CreateBucket](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/CreateBucket)」を参照してください。**

### `CreatePresignedPost`
<a name="s3_CreatePresignedPost_csharp_4_topic"></a>

次の例は、`CreatePresignedPost` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。
署名付き POST URL を作成します。  

```
    /// <summary>
    /// Create a presigned POST URL with conditions.
    /// </summary>
    /// <param name="s3Client">The Amazon S3 client.</param>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="objectKey">The object key (path) where the uploaded file will be stored.</param>
    /// <param name="expires">When the presigned URL expires.</param>
    /// <param name="fields">Dictionary of fields to add to the form.</param>
    /// <param name="conditions">List of conditions to apply.</param>
    /// <returns>A CreatePresignedPostResponse object with URL and form fields.</returns>
    public async Task<CreatePresignedPostResponse> CreatePresignedPostAsync(
        IAmazonS3 s3Client,
        string bucketName,
        string objectKey,
        DateTime expires,
        Dictionary<string, string>? fields = null,
        List<S3PostCondition>? conditions = null)
    {
        var request = new CreatePresignedPostRequest
        {
            BucketName = bucketName,
            Key = objectKey,
            Expires = expires
        };

        // Add custom fields if provided
        if (fields != null)
        {
            foreach (var field in fields)
            {
                request.Fields.Add(field.Key, field.Value);
            }
        }

        // Add conditions if provided
        if (conditions != null)
        {
            foreach (var condition in conditions)
            {
                request.Conditions.Add(condition);
            }
        }

        return await s3Client.CreatePresignedPostAsync(request);
    }
```
+  API の詳細については、「*AWS SDK for .NET API リファレンス*」の「[CreatePresignedPost](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/CreatePresignedPost)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_csharp_4_topic"></a>

次の例は、`DeleteBucket` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Shows how to delete an Amazon S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the Amazon S3 bucket to delete.</param>
    /// <returns>A boolean value that represents the success or failure of
    /// the delete operation.</returns>
    public async Task<bool> DeleteBucketAsync(string bucketName)
    {
        try
        {
            var request = new DeleteBucketRequest { BucketName = bucketName, };

            await _amazonS3.DeleteBucketAsync(request);
            return true;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error deleting bucket: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DeleteBucket](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/DeleteBucket)」を参照してください。**

### `DeleteObjects`
<a name="s3_DeleteObjects_csharp_4_topic"></a>

次の例は、`DeleteObjects` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Delete all of the objects stored in an existing Amazon S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket from which the
    /// contents will be deleted.</param>
    /// <returns>A boolean value that represents the success or failure of
    /// deleting all of the objects in the bucket.</returns>
    public async Task<bool> DeleteBucketContentsAsync(string bucketName)
    {
        // Iterate over the contents of the bucket and delete all objects.
        try
        {
            // Delete all objects in the bucket.
            var deleteList = await ListBucketContentsAsync(bucketName, false);
            if (deleteList != null && deleteList.Any())
            {
                await _amazonS3.DeleteObjectsAsync(new DeleteObjectsRequest()
                {
                    BucketName = bucketName,
                    Objects = deleteList.Select(o => new KeyVersion { Key = o.Key }).ToList(),
                });
            }

            return true;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error deleting objects: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/DeleteObjects)」を参照してください。**

### `GetObject`
<a name="s3_GetObject_csharp_4_topic"></a>

次の例は、`GetObject` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Shows how to download an object from an Amazon S3 bucket to the
    /// local computer.
    /// </summary>
    /// <param name="bucketName">The name of the bucket where the object is
    /// currently stored.</param>
    /// <param name="objectName">The name of the object to download.</param>
    /// <param name="filePath">The path, including filename, where the
    /// downloaded object will be stored.</param>
    /// <returns>A boolean value indicating the success or failure of the
    /// download process.</returns>
    public async Task<bool> DownloadObjectFromBucketAsync(
        string bucketName,
        string objectName,
        string filePath)
    {
        var request = new GetObjectRequest
        {
            BucketName = bucketName,
            Key = objectName,
        };

        using GetObjectResponse response = await _amazonS3.GetObjectAsync(request);

        try
        {
            // Save object to local file
            await response.WriteResponseStreamToFileAsync($"{filePath}\\{objectName}", true, CancellationToken.None);
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error saving {objectName}: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for .NET API リファレンス*の「[GetObject](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/GetObject)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_csharp_4_topic"></a>

次の例は、`ListObjectsV2` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Shows how to list the objects in an Amazon S3 bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket for which to list.
    /// <param name="printList">True to print out the list.
    /// <returns>The collection of objects.</returns>
    public async Task<List<S3Object>?> ListBucketContentsAsync(string bucketName, bool printList = true)
    {
        try
        {
            var request = new ListObjectsV2Request
            {
                BucketName = bucketName,
                MaxKeys = 5,
            };

            if (printList)
            {
                Console.WriteLine("--------------------------------------");
                Console.WriteLine($"Listing the contents of {bucketName}:");
                Console.WriteLine("--------------------------------------");
            }

            var listObjectsV2Paginator = _amazonS3.Paginators.ListObjectsV2(new ListObjectsV2Request
            {
                BucketName = bucketName,
            });
            var s3Objects = new List<S3Object>();
            await foreach (var response in listObjectsV2Paginator.Responses)
            {
                if (response.S3Objects != null)
                {
                    s3Objects.AddRange(response.S3Objects);
                }
            }

            if (printList)
            {
                Console.WriteLine($"Number of Objects: {s3Objects.Count}");
                foreach (var entry in s3Objects)
                {
                    Console.WriteLine($"Key = {entry.Key} Size = {entry.Size}");
                }
            }

            return s3Objects;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error encountered on server. Message:'{ex.Message}' getting list of objects.");
            return null;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[ListObjectsV2](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/ListObjectsV2)」を参照してください。**

### `PutObject`
<a name="s3_PutObject_csharp_4_topic"></a>

次の例は、`PutObject` を使用する方法を説明しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3#code-examples)での設定と実行の方法を確認してください。

```
    /// <summary>
    /// Shows how to upload a file from the local computer to an Amazon S3
    /// bucket.
    /// </summary>
    /// <param name="bucketName">The Amazon S3 bucket to which the object
    /// will be uploaded.</param>
    /// <param name="objectName">The object to upload.</param>
    /// <param name="filePath">The path, including file name, of the object
    /// on the local computer to upload.</param>
    /// <returns>A boolean value indicating the success or failure of the
    /// upload procedure.</returns>
    public async Task<bool> UploadFileAsync(
        string bucketName,
        string objectName,
        string filePath)
    {
        try
        {
            var request = new PutObjectRequest
            {
                BucketName = bucketName,
                Key = objectName,
                FilePath = filePath,
            };

            var response = await _amazonS3.PutObjectAsync(request);
            return response.HttpStatusCode == System.Net.HttpStatusCode.OK;
        }
        catch (AmazonS3Exception ex)
        {
            Console.WriteLine($"Error uploading {objectName}: {ex.Message}");
            return false;
        }
    }
```
+  API の詳細については、AWS SDK for .NET API リファレンスの「[PutObject](https://docs.aws.amazon.com/goto/DotNetSDKV4/s3-2006-03-01/PutObject)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_csharp_4_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for .NET (v4)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv4/S3/Scenarios/S3_CreatePresignedPost#code-examples)での設定と実行の方法を確認してください。
署名付き POST URL を作成してブラウザからの直接アップロードに使用します。  

```
/// <summary>
/// Scenario demonstrating the complete workflow for presigned POST URLs:
/// 1. Create an S3 bucket
/// 2. Create a presigned POST URL
/// 3. Upload a file using the presigned POST URL
/// 4. Clean up resources
/// </summary>
public class CreatePresignedPostBasics
{
    public static ILogger<CreatePresignedPostBasics> _logger = null!;
    public static S3Wrapper _s3Wrapper = null!;
    public static UiMethods _uiMethods = null!;
    public static IHttpClientFactory _httpClientFactory = null!;
    public static bool _isInteractive = true;
    public static string? _bucketName;
    public static string? _objectKey;

    /// <summary>
    /// Set up the services and logging.
    /// </summary>
    /// <param name="host">The IHost instance.</param>
    public static void SetUpServices(IHost host)
    {
        var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole();
        });
        _logger = new Logger<CreatePresignedPostBasics>(loggerFactory);

        _s3Wrapper = host.Services.GetRequiredService<S3Wrapper>();
        _httpClientFactory = host.Services.GetRequiredService<IHttpClientFactory>();
        _uiMethods = new UiMethods();
    }

    /// <summary>
    /// Perform the actions defined for the Amazon S3 Presigned POST scenario.
    /// </summary>
    /// <param name="args">Command line arguments.</param>
    /// <returns>A Task object.</returns>
    public static async Task Main(string[] args)
    {
        _isInteractive = !args.Contains("--non-interactive");

        // Set up dependency injection for Amazon S3
        using var host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
            .ConfigureServices((_, services) =>
                services.AddAWSService<IAmazonS3>()
                    .AddTransient<S3Wrapper>()
                    .AddHttpClient()
            )
            .Build();

        SetUpServices(host);

        try
        {
            // Display overview
            _uiMethods.DisplayOverview();
            _uiMethods.PressEnter(_isInteractive);

            // Step 1: Create bucket
            await CreateBucketAsync();
            _uiMethods.PressEnter(_isInteractive);

            // Step 2: Create presigned URL
            _uiMethods.DisplayTitle("Step 2: Create presigned POST URL");
            var response = await CreatePresignedPostAsync();
            _uiMethods.PressEnter(_isInteractive);

            // Step 3: Display URL and fields
            _uiMethods.DisplayTitle("Step 3: Presigned POST URL details");
            DisplayPresignedPostFields(response);
            _uiMethods.PressEnter(_isInteractive);

            // Step 4: Upload file
            _uiMethods.DisplayTitle("Step 4: Upload test file using presigned POST URL");
            await UploadFileAsync(response);
            _uiMethods.PressEnter(_isInteractive);

            // Step 5: Verify file exists
            await VerifyFileExistsAsync();
            _uiMethods.PressEnter(_isInteractive);

            // Step 6: Cleanup
            _uiMethods.DisplayTitle("Step 6: Clean up resources");
            await CleanupAsync();

            _uiMethods.DisplayTitle("S3 Presigned POST Scenario completed successfully!");
            _uiMethods.PressEnter(_isInteractive);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in scenario");
            Console.WriteLine($"Error: {ex.Message}");

            // Attempt cleanup if there was an error
            if (!string.IsNullOrEmpty(_bucketName))
            {
                _uiMethods.DisplayTitle("Cleaning up resources after error");
                await _s3Wrapper.DeleteBucketAsync(_bucketName);
                Console.WriteLine($"Cleaned up bucket: {_bucketName}");
            }
        }
    }

    /// <summary>
    /// Create an S3 bucket for the scenario.
    /// </summary>
    private static async Task CreateBucketAsync()
    {
        _uiMethods.DisplayTitle("Step 1: Create an S3 bucket");

        // Generate a default bucket name for the scenario
        var defaultBucketName = $"presigned-post-demo-{DateTime.Now:yyyyMMddHHmmss}".ToLower();

        // Prompt user for bucket name or use default in non-interactive mode
        _bucketName = _uiMethods.GetUserInput(
            $"Enter S3 bucket name (or press Enter for '{defaultBucketName}'): ",
            defaultBucketName,
            _isInteractive);

        // Basic validation to ensure bucket name is not empty
        if (string.IsNullOrWhiteSpace(_bucketName))
        {
            _bucketName = defaultBucketName;
        }

        Console.WriteLine($"Creating bucket: {_bucketName}");

        await _s3Wrapper.CreateBucketAsync(_bucketName);

        Console.WriteLine($"Successfully created bucket: {_bucketName}");
    }


    /// <summary>
    /// Create a presigned POST URL.
    /// </summary>
    private static async Task<CreatePresignedPostResponse> CreatePresignedPostAsync()
    {
        _objectKey = "example-upload.txt";
        var expiration = DateTime.UtcNow.AddMinutes(10); // Short expiration for the demo

        Console.WriteLine($"Creating presigned POST URL for {_bucketName}/{_objectKey}");
        Console.WriteLine($"Expiration: {expiration} UTC");

        var s3Client = _s3Wrapper.GetS3Client();

        var response = await _s3Wrapper.CreatePresignedPostAsync(
            s3Client, _bucketName!, _objectKey, expiration);

        Console.WriteLine("Successfully created presigned POST URL");
        return response;
    }

    /// <summary>
    /// Upload a file using the presigned POST URL.
    /// </summary>
    private static async Task UploadFileAsync(CreatePresignedPostResponse response)
    {

        // Create a temporary test file to upload
        string testFilePath = Path.GetTempFileName();
        string testContent = "This is a test file for the S3 presigned POST scenario.";

        await File.WriteAllTextAsync(testFilePath, testContent);
        Console.WriteLine($"Created test file at: {testFilePath}");

        // Upload the file using the presigned POST URL
        Console.WriteLine("\nUploading file using the presigned POST URL...");
        var uploadResult = await UploadFileWithPresignedPostAsync(response, testFilePath);

        // Display the upload result
        if (uploadResult.Success)
        {
            Console.WriteLine($"Upload successful! Status code: {uploadResult.StatusCode}");
        }
        else
        {
            Console.WriteLine($"Upload failed with status code: {uploadResult.StatusCode}");
            Console.WriteLine($"Error: {uploadResult.Response}");
            throw new Exception("File upload failed");
        }

        // Clean up the temporary file
        File.Delete(testFilePath);
        Console.WriteLine("Temporary file deleted");
    }

    /// <summary>
    /// Helper method to upload a file using a presigned POST URL.
    /// </summary>
    private static async Task<(bool Success, HttpStatusCode StatusCode, string Response)> UploadFileWithPresignedPostAsync(
        CreatePresignedPostResponse response,
        string filePath)
    {
        try
        {
            _logger.LogInformation("Uploading file {filePath} using presigned POST URL", filePath);

            using var httpClient = _httpClientFactory.CreateClient();
            using var formContent = new MultipartFormDataContent();

            // Add all the fields from the presigned POST response
            foreach (var field in response.Fields)
            {
                formContent.Add(new StringContent(field.Value), field.Key);
            }

            // Add the file content
            var fileStream = File.OpenRead(filePath);
            var fileName = Path.GetFileName(filePath);
            var fileContent = new StreamContent(fileStream);
            fileContent.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
            formContent.Add(fileContent, "file", fileName);

            // Send the POST request
            var httpResponse = await httpClient.PostAsync(response.Url, formContent);
            var responseContent = await httpResponse.Content.ReadAsStringAsync();

            // Log and return the result
            _logger.LogInformation("Upload completed with status code {statusCode}", httpResponse.StatusCode);

            return (httpResponse.IsSuccessStatusCode, httpResponse.StatusCode, responseContent);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error uploading file");
            return (false, HttpStatusCode.InternalServerError, ex.Message);
        }
    }

    /// <summary>
    /// Verify that the uploaded file exists in the S3 bucket.
    /// </summary>
    private static async Task VerifyFileExistsAsync()
    {
        _uiMethods.DisplayTitle("Step 5: Verify uploaded file exists");

        Console.WriteLine($"Checking if file exists at {_bucketName}/{_objectKey}...");

        try
        {
            var metadata = await _s3Wrapper.GetObjectMetadataAsync(_bucketName!, _objectKey!);

            Console.WriteLine($"File verification successful! File exists in the bucket.");
            Console.WriteLine($"File size: {metadata.ContentLength} bytes");
            Console.WriteLine($"File type: {metadata.Headers.ContentType}");
            Console.WriteLine($"Last modified: {metadata.LastModified}");
        }
        catch (AmazonS3Exception ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            Console.WriteLine($"Error: File was not found in the bucket.");
            throw;
        }
    }

    private static void DisplayPresignedPostFields(CreatePresignedPostResponse response)
    {
        Console.WriteLine($"Presigned POST URL: {response.Url}");
        Console.WriteLine("Form fields to include:");

        foreach (var field in response.Fields)
        {
            Console.WriteLine($"  {field.Key}: {field.Value}");
        }
    }

    /// <summary>
    /// Clean up resources created by the scenario.
    /// </summary>
    private static async Task CleanupAsync()
    {
        if (!string.IsNullOrEmpty(_bucketName))
        {
            Console.WriteLine($"Deleting bucket {_bucketName} and its contents...");
            bool result = await _s3Wrapper.DeleteBucketAsync(_bucketName);

            if (result)
            {
                Console.WriteLine("Bucket deleted successfully");
            }
            else
            {
                Console.WriteLine("Failed to delete bucket - it may have been already deleted");
            }
        }
    }
}
```

# Bash スクリプト AWS CLI を使用した のコード例
<a name="bash_2_code_examples"></a>

次のコード例は、 AWS Command Line Interface で Bash スクリプトを使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [Bash スクリプトを使用したAWS CLI デベロッパーガイド](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) ** — AWSで Bash を使用する方法の詳細。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23bash)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [AWS Batch](bash_2_batch_code_examples.md)
+ [AWS Cloud Map](bash_2_servicediscovery_code_examples.md)
+ [CloudFront](bash_2_cloudfront_code_examples.md)
+ [DynamoDB](bash_2_dynamodb_code_examples.md)
+ [Amazon EC2](bash_2_ec2_code_examples.md)
+ [HealthImaging](bash_2_medical-imaging_code_examples.md)
+ [IAM](bash_2_iam_code_examples.md)
+ [AWS KMS](bash_2_kms_code_examples.md)
+ [Lightsail](bash_2_lightsail_code_examples.md)
+ [Amazon S3](bash_2_s3_code_examples.md)
+ [AWS STS](bash_2_sts_code_examples.md)

# AWS Batch Bash スクリプト AWS CLI で を使用する例
<a name="bash_2_batch_code_examples"></a>

次のコード例は、Bash スクリプト AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Batch。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Batch と Fargate の使用を開始する
<a name="fargate_GettingStarted_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ECS タスク用の IAM 実行ロールを作成する
+ マネージド型の Fargate コンピューティング環境を作成する
+ 優先度設定を使用してジョブキューを作成する
+ コンテナ化されたワークロードのジョブ定義を登録する
+ バッチジョブ実行の送信とモニタリング
+ CloudWatch Logs でジョブ出力を表示する
+ 適切な依存関係の順序でリソースをクリーンアップする

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/011-getting-started-batch-fargate)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# AWS Batch Fargate Getting Started Script - Fixed Version
# This script demonstrates creating AWS Batch resources with Fargate orchestration
#
# HIGH SEVERITY FIXES APPLIED:
# 1. Added IAM role propagation delay after role creation
# 2. Added resource state validation before deletion attempts

set -e  # Exit on any error

# Configuration
SCRIPT_NAME="batch-fargate-tutorial"
LOG_FILE="${SCRIPT_NAME}-$(date +%Y%m%d-%H%M%S).log"
RANDOM_SUFFIX=$(openssl rand -hex 6)
COMPUTE_ENV_NAME="batch-fargate-compute-${RANDOM_SUFFIX}"
JOB_QUEUE_NAME="batch-fargate-queue-${RANDOM_SUFFIX}"
JOB_DEF_NAME="batch-fargate-jobdef-${RANDOM_SUFFIX}"
JOB_NAME="batch-hello-world-${RANDOM_SUFFIX}"
ROLE_NAME="BatchEcsTaskExecutionRole-${RANDOM_SUFFIX}"
TRUST_POLICY_FILE="batch-trust-policy-${RANDOM_SUFFIX}.json"

# Array to track created resources for cleanup
CREATED_RESOURCES=()

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Error handling function
handle_error() {
    log "ERROR: Script failed at line $1"
    log "Attempting to clean up resources created so far..."
    cleanup_resources
    exit 1
}

# Set up error handling
trap 'handle_error $LINENO' ERR

# Function to wait for resource to be ready
wait_for_compute_env() {
    local env_name=$1
    log "Waiting for compute environment $env_name to be VALID..."
    
    while true; do
        local status=$(aws batch describe-compute-environments \
            --compute-environments "$env_name" \
            --query 'computeEnvironments[0].status' \
            --output text 2>/dev/null || echo "NOT_FOUND")
        
        if [ "$status" = "VALID" ]; then
            log "Compute environment $env_name is ready"
            break
        elif [ "$status" = "INVALID" ] || [ "$status" = "NOT_FOUND" ]; then
            log "ERROR: Compute environment $env_name failed to create properly"
            return 1
        fi
        
        log "Compute environment status: $status. Waiting 10 seconds..."
        sleep 10
    done
}

# Function to wait for job queue to be ready
wait_for_job_queue() {
    local queue_name=$1
    log "Waiting for job queue $queue_name to be VALID..."
    
    while true; do
        local state=$(aws batch describe-job-queues \
            --job-queues "$queue_name" \
            --query 'jobQueues[0].state' \
            --output text 2>/dev/null || echo "NOT_FOUND")
        
        if [ "$state" = "ENABLED" ]; then
            log "Job queue $queue_name is ready"
            break
        elif [ "$state" = "DISABLED" ] || [ "$state" = "NOT_FOUND" ]; then
            log "ERROR: Job queue $queue_name failed to create properly"
            return 1
        fi
        
        log "Job queue state: $state. Waiting 10 seconds..."
        sleep 10
    done
}

# Function to wait for job completion
wait_for_job() {
    local job_id=$1
    log "Waiting for job $job_id to complete..."
    
    while true; do
        local status=$(aws batch describe-jobs \
            --jobs "$job_id" \
            --query 'jobs[0].status' \
            --output text 2>/dev/null || echo "NOT_FOUND")
        
        if [ "$status" = "SUCCEEDED" ]; then
            log "Job $job_id completed successfully"
            break
        elif [ "$status" = "FAILED" ]; then
            log "ERROR: Job $job_id failed"
            return 1
        fi
        
        log "Job status: $status. Waiting 30 seconds..."
        sleep 30
    done
}

# FIXED: Added function to wait for resource state before deletion
wait_for_resource_state() {
    local resource_type=$1
    local resource_name=$2
    local expected_state=$3
    local max_attempts=30
    local attempt=0
    
    log "Waiting for $resource_type $resource_name to reach state: $expected_state"
    
    while [ $attempt -lt $max_attempts ]; do
        local current_state=""
        
        case $resource_type in
            "JOB_QUEUE")
                current_state=$(aws batch describe-job-queues \
                    --job-queues "$resource_name" \
                    --query 'jobQueues[0].state' \
                    --output text 2>/dev/null || echo "NOT_FOUND")
                ;;
            "COMPUTE_ENV")
                current_state=$(aws batch describe-compute-environments \
                    --compute-environments "$resource_name" \
                    --query 'computeEnvironments[0].status' \
                    --output text 2>/dev/null || echo "NOT_FOUND")
                ;;
        esac
        
        if [ "$current_state" = "$expected_state" ]; then
            log "$resource_type $resource_name is now in state: $expected_state"
            return 0
        fi
        
        log "$resource_type $resource_name state: $current_state (waiting for $expected_state)"
        sleep 10
        ((attempt++))
    done
    
    log "WARNING: $resource_type $resource_name did not reach expected state after $max_attempts attempts"
    return 1
}

# Cleanup function
cleanup_resources() {
    log "Starting cleanup of created resources..."
    
    # Clean up in reverse order of creation
    for ((i=${#CREATED_RESOURCES[@]}-1; i>=0; i--)); do
        local resource="${CREATED_RESOURCES[i]}"
        local resource_type=$(echo "$resource" | cut -d: -f1)
        local resource_name=$(echo "$resource" | cut -d: -f2)
        
        log "Cleaning up $resource_type: $resource_name"
        
        case $resource_type in
            "JOB_QUEUE")
                # FIXED: Validate state before deletion
                aws batch update-job-queue --job-queue "$resource_name" --state DISABLED 2>/dev/null || true
                wait_for_resource_state "JOB_QUEUE" "$resource_name" "DISABLED" || true
                aws batch delete-job-queue --job-queue "$resource_name" 2>/dev/null || true
                ;;
            "COMPUTE_ENV")
                # FIXED: Validate state before deletion
                aws batch update-compute-environment --compute-environment "$resource_name" --state DISABLED 2>/dev/null || true
                wait_for_resource_state "COMPUTE_ENV" "$resource_name" "DISABLED" || true
                aws batch delete-compute-environment --compute-environment "$resource_name" 2>/dev/null || true
                ;;
            "IAM_ROLE")
                aws iam detach-role-policy --role-name "$resource_name" --policy-arn "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy" 2>/dev/null || true
                aws iam delete-role --role-name "$resource_name" 2>/dev/null || true
                ;;
            "FILE")
                rm -f "$resource_name" 2>/dev/null || true
                ;;
        esac
    done
    
    log "Cleanup completed"
}

# Main script execution
main() {
    log "Starting AWS Batch Fargate tutorial script - Fixed Version"
    log "Log file: $LOG_FILE"
    
    # Get AWS account ID
    log "Getting AWS account ID..."
    ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
    log "Account ID: $ACCOUNT_ID"
    
    # Get default VPC and subnets
    log "Getting default VPC and subnets..."
    DEFAULT_VPC=$(aws ec2 describe-vpcs \
        --filters "Name=is-default,Values=true" \
        --query 'Vpcs[0].VpcId' \
        --output text)
    
    if [ "$DEFAULT_VPC" = "None" ] || [ "$DEFAULT_VPC" = "null" ]; then
        log "ERROR: No default VPC found. Please create a VPC first."
        exit 1
    fi
    
    log "Default VPC: $DEFAULT_VPC"
    
    # Get subnets in the default VPC
    SUBNETS=$(aws ec2 describe-subnets \
        --filters "Name=vpc-id,Values=$DEFAULT_VPC" \
        --query 'Subnets[*].SubnetId' \
        --output text)
    
    if [ -z "$SUBNETS" ]; then
        log "ERROR: No subnets found in default VPC"
        exit 1
    fi
    
    # Convert tab/space-separated subnets to JSON array format
    SUBNET_ARRAY=$(echo "$SUBNETS" | tr '\t ' '\n' | sed 's/^/"/;s/$/"/' | paste -sd ',' -)
    log "Subnets: $SUBNETS"
    log "Subnet array: [$SUBNET_ARRAY]"
    
    # Get default security group for the VPC
    DEFAULT_SG=$(aws ec2 describe-security-groups \
        --filters "Name=vpc-id,Values=$DEFAULT_VPC" "Name=group-name,Values=default" \
        --query 'SecurityGroups[0].GroupId' \
        --output text)
    
    if [ "$DEFAULT_SG" = "None" ] || [ "$DEFAULT_SG" = "null" ]; then
        log "ERROR: No default security group found in VPC"
        exit 1
    fi
    
    log "Default security group: $DEFAULT_SG"
    
    # Step 1: Create IAM execution role
    log "Step 1: Creating IAM execution role..."
    
    # Create trust policy document
    cat > "$TRUST_POLICY_FILE" << EOF
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ecs-tasks.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
    CREATED_RESOURCES+=("FILE:$TRUST_POLICY_FILE")
    
    # Create the role
    aws iam create-role \
        --role-name "$ROLE_NAME" \
        --assume-role-policy-document "file://$TRUST_POLICY_FILE"
    CREATED_RESOURCES+=("IAM_ROLE:$ROLE_NAME")
    
    # Attach policy
    aws iam attach-role-policy \
        --role-name "$ROLE_NAME" \
        --policy-arn "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
    
    log "IAM role created: $ROLE_NAME"
    
    # FIXED: Wait for IAM role propagation
    log "Waiting for IAM role propagation (15 seconds)..."
    sleep 15
    
    # Step 2: Create compute environment
    log "Step 2: Creating Fargate compute environment..."
    
    aws batch create-compute-environment \
        --compute-environment-name "$COMPUTE_ENV_NAME" \
        --type MANAGED \
        --state ENABLED \
        --compute-resources "{
            \"type\": \"FARGATE\",
            \"maxvCpus\": 256,
            \"subnets\": [$SUBNET_ARRAY],
            \"securityGroupIds\": [\"$DEFAULT_SG\"]
        }"
    CREATED_RESOURCES+=("COMPUTE_ENV:$COMPUTE_ENV_NAME")
    
    # Wait for compute environment to be ready
    wait_for_compute_env "$COMPUTE_ENV_NAME"
    
    # Step 3: Create job queue
    log "Step 3: Creating job queue..."
    
    aws batch create-job-queue \
        --job-queue-name "$JOB_QUEUE_NAME" \
        --state ENABLED \
        --priority 900 \
        --compute-environment-order order=1,computeEnvironment="$COMPUTE_ENV_NAME"
    CREATED_RESOURCES+=("JOB_QUEUE:$JOB_QUEUE_NAME")
    
    # Wait for job queue to be ready
    wait_for_job_queue "$JOB_QUEUE_NAME"
    
    # Step 4: Create job definition
    log "Step 4: Creating job definition..."
    
    aws batch register-job-definition \
        --job-definition-name "$JOB_DEF_NAME" \
        --type container \
        --platform-capabilities FARGATE \
        --container-properties "{
            \"image\": \"busybox\",
            \"resourceRequirements\": [
                {\"type\": \"VCPU\", \"value\": \"0.25\"},
                {\"type\": \"MEMORY\", \"value\": \"512\"}
            ],
            \"command\": [\"echo\", \"hello world\"],
            \"networkConfiguration\": {
                \"assignPublicIp\": \"ENABLED\"
            },
            \"executionRoleArn\": \"arn:aws:iam::${ACCOUNT_ID}:role/${ROLE_NAME}\"
        }"
    
    log "Job definition created: $JOB_DEF_NAME"
    
    # Step 5: Submit job
    log "Step 5: Submitting job..."
    
    JOB_ID=$(aws batch submit-job \
        --job-name "$JOB_NAME" \
        --job-queue "$JOB_QUEUE_NAME" \
        --job-definition "$JOB_DEF_NAME" \
        --query 'jobId' \
        --output text)
    
    log "Job submitted with ID: $JOB_ID"
    
    # Step 6: Wait for job completion and view output
    log "Step 6: Waiting for job completion..."
    wait_for_job "$JOB_ID"
    
    # Get log stream name
    log "Getting job logs..."
    LOG_STREAM=$(aws batch describe-jobs \
        --jobs "$JOB_ID" \
        --query 'jobs[0].attempts[0].taskProperties.containers[0].logStreamName' \
        --output text)
    
    if [ "$LOG_STREAM" != "None" ] && [ "$LOG_STREAM" != "null" ]; then
        log "Log stream: $LOG_STREAM"
        log "Job output:"
        aws logs get-log-events \
            --log-group-name "/aws/batch/job" \
            --log-stream-name "$LOG_STREAM" \
            --query 'events[*].message' \
            --output text | tee -a "$LOG_FILE"
    else
        log "No log stream available for job"
    fi
    
    log "Tutorial completed successfully!"
    
    # Show created resources
    echo ""
    echo "==========================================="
    echo "CREATED RESOURCES"
    echo "==========================================="
    echo "The following resources were created:"
    for resource in "${CREATED_RESOURCES[@]}"; do
        echo "  - $resource"
    done
    echo ""
    echo "==========================================="
    echo "CLEANUP CONFIRMATION"
    echo "==========================================="
    echo "Do you want to clean up all created resources? (y/n): "
    read -r CLEANUP_CHOICE
    
    if [[ "$CLEANUP_CHOICE" =~ ^[Yy]$ ]]; then
        cleanup_resources
        log "All resources have been cleaned up"
    else
        log "Resources left intact. You can clean them up manually later."
        echo "To clean up manually, run the following commands:"
        echo "aws batch update-job-queue --job-queue $JOB_QUEUE_NAME --state DISABLED"
        echo "aws batch delete-job-queue --job-queue $JOB_QUEUE_NAME"
        echo "aws batch update-compute-environment --compute-environment $COMPUTE_ENV_NAME --state DISABLED"
        echo "aws batch delete-compute-environment --compute-environment $COMPUTE_ENV_NAME"
        echo "aws iam detach-role-policy --role-name $ROLE_NAME --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
        echo "aws iam delete-role --role-name $ROLE_NAME"
    fi
}

# Run main function
main "$@"
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateComputeEnvironment](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/CreateComputeEnvironment)
  + [CreateJobQueue](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/CreateJobQueue)
  + [DeleteComputeEnvironment](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/DeleteComputeEnvironment)
  + [DeleteJobQueue](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/DeleteJobQueue)
  + [DescribeComputeEnvironments](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/DescribeComputeEnvironments)
  + [DescribeJobQueues](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/DescribeJobQueues)
  + [DescribeJobs](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/DescribeJobs)
  + [RegisterJobDefinition](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/RegisterJobDefinition)
  + [SubmitJob](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/SubmitJob)
  + [UpdateComputeEnvironment](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/UpdateComputeEnvironment)
  + [UpdateJobQueue](https://docs.aws.amazon.com/goto/aws-cli/batch-2016-08-10/UpdateJobQueue)

# AWS Cloud Map Bash スクリプト AWS CLI で を使用する例
<a name="bash_2_servicediscovery_code_examples"></a>

次のコード例は、Bash スクリプト AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Cloud Map。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Cloud Map カスタム属性
<a name="cloudmap_CustomAttributes_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ API ベースのサービス検出用の HTTP 名前空間を作成する
+ DynamoDB テーブルを作成し、カスタム属性を持つデータサービスとして登録する
+ データを読み書きするための Lambda 関数を作成する
+ アクションベースの検出用のカスタム属性を使用して Lambda 関数をサービスインスタンスとして登録する
+ カスタム属性を使用してサービスを検出するクライアントアプリケーションを構築する
+ Lambda 関数、DynamoDB テーブル、Cloud Map サービスを含むすべてのリソースをクリーンアップする

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/004-cloudmap-custom-attributes)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# AWS Cloud Map Tutorial Script
# This script demonstrates how to use AWS Cloud Map for service discovery with custom attributes

# Set up logging
LOG_FILE="cloudmap-tutorial.log"
echo "AWS Cloud Map Tutorial Script" > $LOG_FILE
echo "Started at $(date)" >> $LOG_FILE

# Array to track created resources for cleanup
CREATED_RESOURCES=()

# Function to log commands and their output
log_cmd() {
  echo "$ $1" | tee -a $LOG_FILE
  eval "$1" | tee -a $LOG_FILE
}

# Function to handle errors
handle_error() {
  local LINE=$1
  echo "An error occurred at line $LINE" | tee -a $LOG_FILE
  echo "Resources created so far:" | tee -a $LOG_FILE
  for resource in "${CREATED_RESOURCES[@]}"; do
    echo "- $resource" | tee -a $LOG_FILE
  done
  echo "Attempting to clean up resources..." | tee -a $LOG_FILE
  cleanup
  exit 1
}

# Set up error handling
trap 'handle_error $LINENO' ERR

# Helper function to wait for Cloud Map operations to complete
wait_for_operation() {
  local OPERATION_ID=$1
  local TIMEOUT=300  # 5 minutes timeout
  local START_TIME=$(date +%s)
  
  while true; do
    local STATUS=$(aws servicediscovery get-operation --operation-id $OPERATION_ID --query 'Operation.Status' --output text)
    
    if [ "$STATUS" == "SUCCESS" ]; then
      echo "Operation completed successfully" | tee -a $LOG_FILE
      break
    elif [ "$STATUS" == "FAIL" ]; then
      echo "Operation failed" | tee -a $LOG_FILE
      return 1
    fi
    
    local CURRENT_TIME=$(date +%s)
    if [ $((CURRENT_TIME - START_TIME)) -gt $TIMEOUT ]; then
      echo "Operation timed out" | tee -a $LOG_FILE
      return 1
    fi
    
    sleep 5
  done
  
  return 0
}

# Function to clean up resources
cleanup() {
  echo "Cleaning up resources..." | tee -a $LOG_FILE
  
  # Reverse the order of created resources for proper deletion
  for ((i=${#CREATED_RESOURCES[@]}-1; i>=0; i--)); do
    resource="${CREATED_RESOURCES[$i]}"
    echo "Deleting $resource..." | tee -a $LOG_FILE
    
    if [[ $resource == "instance:"* ]]; then
      # Extract service ID and instance ID
      SERVICE_ID=$(echo $resource | cut -d':' -f2)
      INSTANCE_ID=$(echo $resource | cut -d':' -f3)
      
      # Check if instance exists before trying to deregister
      INSTANCE_EXISTS=$(aws servicediscovery list-instances --service-id $SERVICE_ID --query "Instances[?Id=='$INSTANCE_ID'].Id" --output text 2>/dev/null || echo "")
      if [[ -n "$INSTANCE_EXISTS" ]]; then
        OPERATION_ID=$(aws servicediscovery deregister-instance --service-id $SERVICE_ID --instance-id $INSTANCE_ID --query 'OperationId' --output text)
        
        # Wait for deregistration to complete
        echo "Waiting for instance deregistration to complete..." | tee -a $LOG_FILE
        wait_for_operation $OPERATION_ID
      else
        echo "Instance $INSTANCE_ID already deregistered" | tee -a $LOG_FILE
      fi
    elif [[ $resource == "lambda:"* ]]; then
      # Extract function name
      FUNCTION_NAME=$(echo $resource | cut -d':' -f2)
      aws lambda delete-function --function-name $FUNCTION_NAME
    elif [[ $resource == "role:"* ]]; then
      # Extract role name
      ROLE_NAME=$(echo $resource | cut -d':' -f2)
      
      # Detach all policies first
      for POLICY_ARN in $(aws iam list-attached-role-policies --role-name $ROLE_NAME --query 'AttachedPolicies[*].PolicyArn' --output text); do
        aws iam detach-role-policy --role-name $ROLE_NAME --policy-arn $POLICY_ARN
      done
      
      # Delete the role
      aws iam delete-role --role-name $ROLE_NAME
    elif [[ $resource == "dynamodb:"* ]]; then
      # Extract table name
      TABLE_NAME=$(echo $resource | cut -d':' -f2)
      aws dynamodb delete-table --table-name $TABLE_NAME
      
      # Wait for table deletion to complete
      echo "Waiting for DynamoDB table deletion to complete..." | tee -a $LOG_FILE
      aws dynamodb wait table-not-exists --table-name $TABLE_NAME
    fi
  done
  
  # Handle services separately to ensure all instances are deregistered first
  for ((i=${#CREATED_RESOURCES[@]}-1; i>=0; i--)); do
    resource="${CREATED_RESOURCES[$i]}"
    if [[ $resource == "service:"* ]]; then
      # Extract service ID
      SERVICE_ID=$(echo $resource | cut -d':' -f2)
      echo "Deleting service $SERVICE_ID..." | tee -a $LOG_FILE
      
      # Make sure all instances are deregistered
      INSTANCES=$(aws servicediscovery list-instances --service-id $SERVICE_ID --query 'Instances[*].Id' --output text)
      if [[ -n "$INSTANCES" ]]; then
        echo "Service still has instances. Waiting before deletion..." | tee -a $LOG_FILE
        sleep 10
      fi
      
      # Try to delete the service
      aws servicediscovery delete-service --id $SERVICE_ID
      sleep 5
    fi
  done
  
  # Handle namespaces last to ensure all services are deleted first
  for ((i=${#CREATED_RESOURCES[@]}-1; i>=0; i--)); do
    resource="${CREATED_RESOURCES[$i]}"
    if [[ $resource == "namespace:"* ]]; then
      # Extract namespace ID
      NAMESPACE_ID=$(echo $resource | cut -d':' -f2)
      echo "Deleting namespace $NAMESPACE_ID..." | tee -a $LOG_FILE
      
      # Check if namespace still has services
      SERVICES=$(aws servicediscovery list-services --filters "Name=NAMESPACE_ID,Values=$NAMESPACE_ID,Condition=EQ" --query 'Services[*].Id' --output text)
      if [[ -n "$SERVICES" ]]; then
        echo "Namespace still has services. Deleting them first..." | tee -a $LOG_FILE
        for SERVICE_ID in $SERVICES; do
          echo "Deleting service $SERVICE_ID..." | tee -a $LOG_FILE
          aws servicediscovery delete-service --id $SERVICE_ID
        done
        sleep 5
      fi
      
      # Try to delete the namespace
      OPERATION_ID=$(aws servicediscovery delete-namespace --id $NAMESPACE_ID --query 'OperationId' --output text 2>/dev/null || echo "")
      if [[ -n "$OPERATION_ID" ]]; then
        echo "Waiting for namespace deletion to complete..." | tee -a $LOG_FILE
        wait_for_operation $OPERATION_ID
      else
        echo "Failed to delete namespace or namespace already deleted" | tee -a $LOG_FILE
      fi
    fi
  done
  
  echo "Cleanup complete" | tee -a $LOG_FILE
}

# Step 1: Create an AWS Cloud Map namespace
echo "Step 1: Creating AWS Cloud Map namespace..." | tee -a $LOG_FILE

# Check if namespace already exists
NAMESPACE_ID=$(aws servicediscovery list-namespaces --query "Namespaces[?Name=='cloudmap-tutorial'].Id" --output text)

if [[ -z "$NAMESPACE_ID" || "$NAMESPACE_ID" == "None" ]]; then
  log_cmd "aws servicediscovery create-http-namespace --name cloudmap-tutorial --creator-request-id namespace-request"
  OPERATION_ID=$(aws servicediscovery create-http-namespace --name cloudmap-tutorial --creator-request-id namespace-request --query 'OperationId' --output text)

  # Wait for namespace creation to complete
  echo "Waiting for namespace creation to complete..." | tee -a $LOG_FILE
  wait_for_operation $OPERATION_ID

  # Get the namespace ID
  NAMESPACE_ID=$(aws servicediscovery list-namespaces --query "Namespaces[?Name=='cloudmap-tutorial'].Id" --output text)
  echo "Namespace created with ID: $NAMESPACE_ID" | tee -a $LOG_FILE
else
  echo "Namespace cloudmap-tutorial already exists with ID: $NAMESPACE_ID" | tee -a $LOG_FILE
fi

CREATED_RESOURCES+=("namespace:$NAMESPACE_ID")

# Step 2: Create a DynamoDB table
echo "Step 2: Creating DynamoDB table..." | tee -a $LOG_FILE

# Check if table already exists
TABLE_EXISTS=$(aws dynamodb describe-table --table-name cloudmap 2>&1 || echo "NOT_EXISTS")

if [[ $TABLE_EXISTS == *"ResourceNotFoundException"* || $TABLE_EXISTS == "NOT_EXISTS" ]]; then
  log_cmd "aws dynamodb create-table --table-name cloudmap --attribute-definitions AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --billing-mode PAY_PER_REQUEST"
  
  # Wait for DynamoDB table to become active
  echo "Waiting for DynamoDB table to become active..." | tee -a $LOG_FILE
  aws dynamodb wait table-exists --table-name cloudmap
else
  echo "DynamoDB table cloudmap already exists" | tee -a $LOG_FILE
fi

CREATED_RESOURCES+=("dynamodb:cloudmap")

# Step 3: Create an AWS Cloud Map data service
echo "Step 3: Creating AWS Cloud Map data service..." | tee -a $LOG_FILE

# Get all services in the namespace
echo "Listing all services in namespace $NAMESPACE_ID..." | tee -a $LOG_FILE
SERVICES=$(aws servicediscovery list-services --filters "Name=NAMESPACE_ID,Values=$NAMESPACE_ID,Condition=EQ" --query 'Services[*].[Id,Name]' --output text)
echo "Services found: $SERVICES" | tee -a $LOG_FILE

# Check if data service already exists
DATA_SERVICE_ID=""
while read -r id name || [[ -n "$id" ]]; do
  echo "Checking service: ID=$id, Name=$name" | tee -a $LOG_FILE
  if [[ "$name" == "data-service" ]]; then
    DATA_SERVICE_ID="$id"
    break
  fi
done <<< "$SERVICES"

if [[ -z "$DATA_SERVICE_ID" ]]; then
  echo "Data service does not exist, creating it..." | tee -a $LOG_FILE
  # Create the service and capture the ID directly
  echo "$ aws servicediscovery create-service --name data-service --namespace-id $NAMESPACE_ID --creator-request-id data-service-request" | tee -a $LOG_FILE
  CREATE_OUTPUT=$(aws servicediscovery create-service --name data-service --namespace-id $NAMESPACE_ID --creator-request-id data-service-request)
  echo "$CREATE_OUTPUT" | tee -a $LOG_FILE
  
  # Extract the service ID using AWS CLI query
  DATA_SERVICE_ID=$(aws servicediscovery list-services --filters "Name=NAMESPACE_ID,Values=$NAMESPACE_ID,Condition=EQ" --query "Services[?Name=='data-service'].Id" --output text)
  echo "Data service created with ID: $DATA_SERVICE_ID" | tee -a $LOG_FILE
else
  echo "Data service already exists with ID: $DATA_SERVICE_ID" | tee -a $LOG_FILE
fi

CREATED_RESOURCES+=("service:$DATA_SERVICE_ID")

# Register DynamoDB table as a service instance
echo "Registering DynamoDB table as a service instance..." | tee -a $LOG_FILE

# Check if instance already exists
INSTANCE_EXISTS=$(aws servicediscovery list-instances --service-id $DATA_SERVICE_ID --query "Instances[?Id=='data-instance'].Id" --output text)

if [[ -z "$INSTANCE_EXISTS" ]]; then
  log_cmd "aws servicediscovery register-instance --service-id $DATA_SERVICE_ID --instance-id data-instance --attributes tablename=cloudmap,region=$(aws configure get region)"
  OPERATION_ID=$(aws servicediscovery register-instance --service-id $DATA_SERVICE_ID --instance-id data-instance --attributes tablename=cloudmap,region=$(aws configure get region) --query 'OperationId' --output text)

  # Wait for instance registration to complete
  echo "Waiting for instance registration to complete..." | tee -a $LOG_FILE
  wait_for_operation $OPERATION_ID
else
  echo "Instance data-instance already exists" | tee -a $LOG_FILE
fi

CREATED_RESOURCES+=("instance:$DATA_SERVICE_ID:data-instance")

# Step 4: Create an IAM role for Lambda
echo "Step 4: Creating IAM role for Lambda..." | tee -a $LOG_FILE

# Create a trust policy for Lambda
cat > lambda-trust-policy.json << EOF
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF

# Check if role already exists
echo "Checking if IAM role already exists..." | tee -a $LOG_FILE
ROLE_EXISTS=$(aws iam get-role --role-name cloudmap-tutorial-role 2>&1 || echo "NOT_EXISTS")

if [[ $ROLE_EXISTS == *"NoSuchEntity"* || $ROLE_EXISTS == "NOT_EXISTS" ]]; then
    log_cmd "aws iam create-role --role-name cloudmap-tutorial-role --assume-role-policy-document file://lambda-trust-policy.json"
else
    echo "Role cloudmap-tutorial-role already exists, using existing role" | tee -a $LOG_FILE
fi

# FIXED: Create a custom policy with least privilege instead of using PowerUserAccess
cat > cloudmap-policy.json << EOF
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:PutItem",
        "dynamodb:GetItem",
        "dynamodb:Scan"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/cloudmap"
    },
    {
      "Effect": "Allow",
      "Action": [
        "servicediscovery:DiscoverInstances"
      ],
      "Resource": "*"
    }
  ]
}
EOF

# Check if policy already exists
POLICY_ARN=$(aws iam list-policies --query "Policies[?PolicyName=='CloudMapTutorialPolicy'].Arn" --output text)

if [[ -z "$POLICY_ARN" ]]; then
  echo "Creating CloudMapTutorialPolicy..." | tee -a $LOG_FILE
  echo "$ aws iam create-policy --policy-name CloudMapTutorialPolicy --policy-document file://cloudmap-policy.json" | tee -a $LOG_FILE
  CREATE_OUTPUT=$(aws iam create-policy --policy-name CloudMapTutorialPolicy --policy-document file://cloudmap-policy.json)
  echo "$CREATE_OUTPUT" | tee -a $LOG_FILE
  POLICY_ARN=$(aws iam list-policies --query "Policies[?PolicyName=='CloudMapTutorialPolicy'].Arn" --output text)
else
  echo "Policy CloudMapTutorialPolicy already exists with ARN: $POLICY_ARN" | tee -a $LOG_FILE
fi

echo "$ aws iam attach-role-policy --role-name cloudmap-tutorial-role --policy-arn $POLICY_ARN" | tee -a $LOG_FILE
aws iam attach-role-policy --role-name cloudmap-tutorial-role --policy-arn $POLICY_ARN | tee -a $LOG_FILE

echo "$ aws iam attach-role-policy --role-name cloudmap-tutorial-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" | tee -a $LOG_FILE
aws iam attach-role-policy --role-name cloudmap-tutorial-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole | tee -a $LOG_FILE

# Wait for role to propagate
echo "Waiting for IAM role to propagate..." | tee -a $LOG_FILE
sleep 10

ROLE_ARN=$(aws iam get-role --role-name cloudmap-tutorial-role --query 'Role.Arn' --output text)
CREATED_RESOURCES+=("role:cloudmap-tutorial-role")

# Step 5: Create an AWS Cloud Map app service
echo "Step 5: Creating AWS Cloud Map app service..." | tee -a $LOG_FILE

# Get all services in the namespace
SERVICES=$(aws servicediscovery list-services --filters "Name=NAMESPACE_ID,Values=$NAMESPACE_ID,Condition=EQ" --query 'Services[*].[Id,Name]' --output text)

# Check if app service already exists
APP_SERVICE_ID=""
while read -r id name || [[ -n "$id" ]]; do
  if [[ "$name" == "app-service" ]]; then
    APP_SERVICE_ID="$id"
    break
  fi
done <<< "$SERVICES"

if [[ -z "$APP_SERVICE_ID" ]]; then
  echo "App service does not exist, creating it..." | tee -a $LOG_FILE
  # Create the service and capture the ID directly
  echo "$ aws servicediscovery create-service --name app-service --namespace-id $NAMESPACE_ID --creator-request-id app-service-request" | tee -a $LOG_FILE
  CREATE_OUTPUT=$(aws servicediscovery create-service --name app-service --namespace-id $NAMESPACE_ID --creator-request-id app-service-request)
  echo "$CREATE_OUTPUT" | tee -a $LOG_FILE
  
  # Extract the service ID using AWS CLI query
  APP_SERVICE_ID=$(aws servicediscovery list-services --filters "Name=NAMESPACE_ID,Values=$NAMESPACE_ID,Condition=EQ" --query "Services[?Name=='app-service'].Id" --output text)
  echo "App service created with ID: $APP_SERVICE_ID" | tee -a $LOG_FILE
else
  echo "App service already exists with ID: $APP_SERVICE_ID" | tee -a $LOG_FILE
fi

CREATED_RESOURCES+=("service:$APP_SERVICE_ID")

# Step 6: Create a Lambda function to write data
echo "Step 6: Creating Lambda function to write data..." | tee -a $LOG_FILE

# Create Lambda function code
cat > writefunction.py << EOF
import boto3
import json
import random

def lambda_handler(event, context):
    # Use AWS Cloud Map to discover the DynamoDB table
    serviceclient = boto3.client('servicediscovery')
    
    # Discover the data service instance
    response = serviceclient.discover_instances(
        NamespaceName='cloudmap-tutorial',
        ServiceName='data-service'
    )
    
    # Extract table name and region from the instance attributes
    tablename = response['Instances'][0]['Attributes']['tablename']
    region = response['Instances'][0]['Attributes']['region']
    
    # Create DynamoDB client in the specified region
    dynamodb = boto3.resource('dynamodb', region_name=region)
    table = dynamodb.Table(tablename)
    
    # Write data to the table
    table.put_item(
        Item={
            'id': str(random.randint(1,100)),
            'todo': event
        }
    )
    
    return {
        'statusCode': 200,
        'body': json.dumps('Data written successfully!')
    }
EOF

# Zip the function code
log_cmd "zip writefunction.zip writefunction.py"

# Create the Lambda function
FUNCTION_EXISTS=$(aws lambda list-functions --query "Functions[?FunctionName=='writefunction'].FunctionName" --output text)
if [[ -z "$FUNCTION_EXISTS" ]]; then
  log_cmd "aws lambda create-function --function-name writefunction --runtime python3.12 --role $ROLE_ARN --handler writefunction.lambda_handler --zip-file fileb://writefunction.zip --architectures x86_64"

  # Wait for the Lambda function to be active before updating
  echo "Waiting for Lambda function to become active..." | tee -a $LOG_FILE
  function_state="Pending"
  while [ "$function_state" == "Pending" ]; do
      sleep 5
      function_state=$(aws lambda get-function --function-name writefunction --query 'Configuration.State' --output text)
      echo "Current function state: $function_state" | tee -a $LOG_FILE
  done

  # Update the function timeout
  log_cmd "aws lambda update-function-configuration --function-name writefunction --timeout 5"
else
  echo "Lambda function writefunction already exists" | tee -a $LOG_FILE
fi
CREATED_RESOURCES+=("lambda:writefunction")

# Step 7: Register the Lambda write function as an AWS Cloud Map service instance
echo "Step 7: Registering Lambda write function as a service instance..." | tee -a $LOG_FILE

# Check if instance already exists
INSTANCE_EXISTS=$(aws servicediscovery list-instances --service-id $APP_SERVICE_ID --query "Instances[?Id=='write-instance'].Id" --output text)

if [[ -z "$INSTANCE_EXISTS" ]]; then
  log_cmd "aws servicediscovery register-instance --service-id $APP_SERVICE_ID --instance-id write-instance --attributes action=write,functionname=writefunction"
  OPERATION_ID=$(aws servicediscovery register-instance --service-id $APP_SERVICE_ID --instance-id write-instance --attributes action=write,functionname=writefunction --query 'OperationId' --output text)

  # Wait for instance registration to complete
  echo "Waiting for write instance registration to complete..." | tee -a $LOG_FILE
  wait_for_operation $OPERATION_ID
else
  echo "Instance write-instance already exists" | tee -a $LOG_FILE
fi

CREATED_RESOURCES+=("instance:$APP_SERVICE_ID:write-instance")

# Step 8: Create a Lambda function to read data
echo "Step 8: Creating Lambda function to read data..." | tee -a $LOG_FILE

# Create Lambda function code
cat > readfunction.py << EOF
import boto3
import json

def lambda_handler(event, context):
    # Use AWS Cloud Map to discover the DynamoDB table
    serviceclient = boto3.client('servicediscovery')
    
    # Discover the data service instance
    response = serviceclient.discover_instances(
        NamespaceName='cloudmap-tutorial',
        ServiceName='data-service'
    )
    
    # Extract table name and region from the instance attributes
    tablename = response['Instances'][0]['Attributes']['tablename']
    region = response['Instances'][0]['Attributes']['region']
    
    # Create DynamoDB client in the specified region
    dynamodb = boto3.resource('dynamodb', region_name=region)
    table = dynamodb.Table(tablename)
    
    # Read data from the table
    response = table.scan()
    
    return {
        'statusCode': 200,
        'body': json.dumps(response['Items'])
    }
EOF

# Zip the function code
log_cmd "zip readfunction.zip readfunction.py"

# Create the Lambda function
FUNCTION_EXISTS=$(aws lambda list-functions --query "Functions[?FunctionName=='readfunction'].FunctionName" --output text)
if [[ -z "$FUNCTION_EXISTS" ]]; then
  log_cmd "aws lambda create-function --function-name readfunction --runtime python3.12 --role $ROLE_ARN --handler readfunction.lambda_handler --zip-file fileb://readfunction.zip --architectures x86_64"

  # Wait for the Lambda function to be active before updating
  echo "Waiting for Lambda function to become active..." | tee -a $LOG_FILE
  function_state="Pending"
  while [ "$function_state" == "Pending" ]; do
      sleep 5
      function_state=$(aws lambda get-function --function-name readfunction --query 'Configuration.State' --output text)
      echo "Current function state: $function_state" | tee -a $LOG_FILE
  done

  # Update the function timeout
  log_cmd "aws lambda update-function-configuration --function-name readfunction --timeout 5"
else
  echo "Lambda function readfunction already exists" | tee -a $LOG_FILE
fi
CREATED_RESOURCES+=("lambda:readfunction")

# Step 9: Register the Lambda read function as an AWS Cloud Map service instance
echo "Step 9: Registering Lambda read function as a service instance..." | tee -a $LOG_FILE

# Check if instance already exists
INSTANCE_EXISTS=$(aws servicediscovery list-instances --service-id $APP_SERVICE_ID --query "Instances[?Id=='read-instance'].Id" --output text)

if [[ -z "$INSTANCE_EXISTS" ]]; then
  log_cmd "aws servicediscovery register-instance --service-id $APP_SERVICE_ID --instance-id read-instance --attributes action=read,functionname=readfunction"
  OPERATION_ID=$(aws servicediscovery register-instance --service-id $APP_SERVICE_ID --instance-id read-instance --attributes action=read,functionname=readfunction --query 'OperationId' --output text)

  # Wait for read instance registration to complete
  echo "Waiting for read instance registration to complete..." | tee -a $LOG_FILE
  wait_for_operation $OPERATION_ID
else
  echo "Instance read-instance already exists" | tee -a $LOG_FILE
fi

CREATED_RESOURCES+=("instance:$APP_SERVICE_ID:read-instance")

# Step 10: Create Python clients to interact with the services
echo "Step 10: Creating Python clients..." | tee -a $LOG_FILE

cat > writeclient.py << EOF
import boto3

serviceclient = boto3.client('servicediscovery')

response = serviceclient.discover_instances(NamespaceName='cloudmap-tutorial', ServiceName='app-service', QueryParameters={ 'action': 'write' })

functionname = response["Instances"][0]["Attributes"]["functionname"]

lambdaclient = boto3.client('lambda')

resp = lambdaclient.invoke(FunctionName=functionname, Payload='"This is a test data"')

print(resp["Payload"].read())
EOF

cat > readclient.py << EOF
import boto3

serviceclient = boto3.client('servicediscovery')

response = serviceclient.discover_instances(NamespaceName='cloudmap-tutorial', ServiceName='app-service', QueryParameters={ 'action': 'read' })

functionname = response["Instances"][0]["Attributes"]["functionname"]

lambdaclient = boto3.client('lambda')

resp = lambdaclient.invoke(FunctionName=functionname, InvocationType='RequestResponse')

print(resp["Payload"].read())
EOF

echo "Running write client..." | tee -a $LOG_FILE
log_cmd "python3 writeclient.py"

echo "Running read client..." | tee -a $LOG_FILE
log_cmd "python3 readclient.py"

# Step 11: Clean up resources
echo "Resources created:" | tee -a $LOG_FILE
for resource in "${CREATED_RESOURCES[@]}"; do
  echo "- $resource" | tee -a $LOG_FILE
done

echo "" | tee -a $LOG_FILE
echo "==========================================" | tee -a $LOG_FILE
echo "CLEANUP CONFIRMATION" | tee -a $LOG_FILE
echo "==========================================" | tee -a $LOG_FILE
echo "Do you want to clean up all created resources? (y/n): " | tee -a $LOG_FILE
read -r CLEANUP_CONFIRM
if [[ $CLEANUP_CONFIRM == "y" || $CLEANUP_CONFIRM == "Y" ]]; then
  cleanup
else
  echo "Resources were not cleaned up. You can manually clean them up later." | tee -a $LOG_FILE
fi

echo "Script completed at $(date)" | tee -a $LOG_FILE
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateHttpNamespace](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/CreateHttpNamespace)
  + [CreateService](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/CreateService)
  + [DeleteNamespace](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/DeleteNamespace)
  + [DeleteService](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/DeleteService)
  + [DeregisterInstance](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/DeregisterInstance)
  + [GetOperation](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/GetOperation)
  + [ListNamespaces](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/ListNamespaces)
  + [ListServices](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/ListServices)
  + [RegisterInstance](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/RegisterInstance)

### Cloud Map サービス検出
<a name="cloudmap_ServiceDiscovery_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Route 53 ホストゾーン統合を使用してパブリック DNS 名前空間を作成する
+ DNS クエリと API コールを介して検出可能なサービスを作成する
+ さまざまな検出設定でサービスインスタンスを登録する
+ DNS クエリと Cloud Map API の両方を使用してサービスを検出する
+ dig コマンドと API コールを使用してサービス検出を検証する
+ 適切な順序でリソースをクリーンアップする (インスタンス、サービス、名前空間)

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/010-cloudmap-service-discovery)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# AWS Cloud Map Private Namespace Tutorial Script
# This script demonstrates how to use AWS Cloud Map for service discovery
# with DNS queries and API calls

# Exit on error
set -e

# Configuration
REGION="us-east-2"
NAMESPACE_NAME="cloudmap-tutorial.com"
LOG_FILE="cloudmap-tutorial.log"
CREATOR_REQUEST_ID=$(date +%s)

# Function to log messages
log() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | tee -a "$LOG_FILE"
}

# Function to check operation status
check_operation() {
    local operation_id="$1"
    local status=""
    
    log "Checking operation status for $operation_id..."
    
    while [[ "$status" != "SUCCESS" ]]; do
        sleep 5
        status=$(aws servicediscovery get-operation \
            --operation-id "$operation_id" \
            --region "$REGION" \
            --query "Operation.Status" \
            --output text)
        
        log "Operation status: $status"
        
        if [[ "$status" == "FAIL" ]]; then
            log "Operation failed. Exiting."
            exit 1
        fi
    done
    
    log "Operation completed successfully."
}

# Function to clean up resources
cleanup() {
    log "Starting cleanup process..."
    
    if [[ -n "$FIRST_INSTANCE_ID" ]]; then
        log "Deregistering first service instance..."
        aws servicediscovery deregister-instance \
            --service-id "$PUBLIC_SERVICE_ID" \
            --instance-id "$FIRST_INSTANCE_ID" \
            --region "$REGION" || log "Failed to deregister first instance"
    fi
    
    if [[ -n "$SECOND_INSTANCE_ID" ]]; then
        log "Deregistering second service instance..."
        aws servicediscovery deregister-instance \
            --service-id "$BACKEND_SERVICE_ID" \
            --instance-id "$SECOND_INSTANCE_ID" \
            --region "$REGION" || log "Failed to deregister second instance"
    fi
    
    if [[ -n "$PUBLIC_SERVICE_ID" ]]; then
        log "Deleting public service..."
        aws servicediscovery delete-service \
            --id "$PUBLIC_SERVICE_ID" \
            --region "$REGION" || log "Failed to delete public service"
    fi
    
    if [[ -n "$BACKEND_SERVICE_ID" ]]; then
        log "Deleting backend service..."
        aws servicediscovery delete-service \
            --id "$BACKEND_SERVICE_ID" \
            --region "$REGION" || log "Failed to delete backend service"
    fi
    
    if [[ -n "$NAMESPACE_ID" ]]; then
        log "Deleting namespace..."
        aws servicediscovery delete-namespace \
            --id "$NAMESPACE_ID" \
            --region "$REGION" || log "Failed to delete namespace"
    fi
    
    log "Cleanup completed."
}

# Set up trap for cleanup on script exit
trap cleanup EXIT INT TERM

# Initialize log file
> "$LOG_FILE"
log "Starting AWS Cloud Map tutorial script"

# Step 1: Create an AWS Cloud Map namespace
log "Creating AWS Cloud Map namespace: $NAMESPACE_NAME"
OPERATION_RESULT=$(aws servicediscovery create-public-dns-namespace \
    --name "$NAMESPACE_NAME" \
    --creator-request-id "cloudmap-tutorial-$CREATOR_REQUEST_ID" \
    --region "$REGION")

OPERATION_ID=$(echo "$OPERATION_RESULT" | jq -r '.OperationId')
log "Namespace creation initiated. Operation ID: $OPERATION_ID"

# Check operation status
check_operation "$OPERATION_ID"

# Get the namespace ID
log "Getting namespace ID..."
NAMESPACE_ID=$(aws servicediscovery list-namespaces \
    --region "$REGION" \
    --query "Namespaces[?Name=='$NAMESPACE_NAME'].Id" \
    --output text)

log "Namespace ID: $NAMESPACE_ID"

# Get the hosted zone ID
log "Getting Route 53 hosted zone ID..."
HOSTED_ZONE_ID=$(aws route53 list-hosted-zones-by-name \
    --dns-name "$NAMESPACE_NAME" \
    --query "HostedZones[0].Id" \
    --output text | sed 's|/hostedzone/||')

log "Hosted Zone ID: $HOSTED_ZONE_ID"

# Step 2: Create the AWS Cloud Map services
log "Creating public service..."
PUBLIC_SERVICE_RESULT=$(aws servicediscovery create-service \
    --name "public-service" \
    --namespace-id "$NAMESPACE_ID" \
    --dns-config "RoutingPolicy=MULTIVALUE,DnsRecords=[{Type=A,TTL=300}]" \
    --region "$REGION")

PUBLIC_SERVICE_ID=$(echo "$PUBLIC_SERVICE_RESULT" | jq -r '.Service.Id')
log "Public service created. Service ID: $PUBLIC_SERVICE_ID"

log "Creating backend service..."
BACKEND_SERVICE_RESULT=$(aws servicediscovery create-service \
    --name "backend-service" \
    --namespace-id "$NAMESPACE_ID" \
    --type "HTTP" \
    --region "$REGION")

BACKEND_SERVICE_ID=$(echo "$BACKEND_SERVICE_RESULT" | jq -r '.Service.Id')
log "Backend service created. Service ID: $BACKEND_SERVICE_ID"

# Step 3: Register the AWS Cloud Map service instances
log "Registering first service instance..."
FIRST_INSTANCE_RESULT=$(aws servicediscovery register-instance \
    --service-id "$PUBLIC_SERVICE_ID" \
    --instance-id "first" \
    --attributes "AWS_INSTANCE_IPV4=192.168.2.1" \
    --region "$REGION")

FIRST_INSTANCE_ID="first"
FIRST_OPERATION_ID=$(echo "$FIRST_INSTANCE_RESULT" | jq -r '.OperationId')
log "First instance registration initiated. Operation ID: $FIRST_OPERATION_ID"

# Check operation status
check_operation "$FIRST_OPERATION_ID"

log "Registering second service instance..."
SECOND_INSTANCE_RESULT=$(aws servicediscovery register-instance \
    --service-id "$BACKEND_SERVICE_ID" \
    --instance-id "second" \
    --attributes "service-name=backend" \
    --region "$REGION")

SECOND_INSTANCE_ID="second"
SECOND_OPERATION_ID=$(echo "$SECOND_INSTANCE_RESULT" | jq -r '.OperationId')
log "Second instance registration initiated. Operation ID: $SECOND_OPERATION_ID"

# Check operation status
check_operation "$SECOND_OPERATION_ID"

# Step 4: Discover the AWS Cloud Map service instances
log "Getting Route 53 name servers..."
NAME_SERVERS=$(aws route53 get-hosted-zone \
    --id "$HOSTED_ZONE_ID" \
    --query "DelegationSet.NameServers[0]" \
    --output text)

log "Name server: $NAME_SERVERS"

log "Using dig to query DNS records (this will be simulated)..."
log "Command: dig @$NAME_SERVERS public-service.$NAMESPACE_NAME"
log "Expected output would show: public-service.$NAMESPACE_NAME. 300 IN A 192.168.2.1"

log "Using AWS CLI to discover backend service instances..."
DISCOVER_RESULT=$(aws servicediscovery discover-instances \
    --namespace-name "$NAMESPACE_NAME" \
    --service-name "backend-service" \
    --region "$REGION")

log "Discovery result: $(echo "$DISCOVER_RESULT" | jq -c '.')"

# Display created resources
log "Resources created:"
log "- Namespace: $NAMESPACE_NAME (ID: $NAMESPACE_ID)"
log "- Public Service: public-service (ID: $PUBLIC_SERVICE_ID)"
log "- Backend Service: backend-service (ID: $BACKEND_SERVICE_ID)"
log "- Service Instance: first (Service: public-service)"
log "- Service Instance: second (Service: backend-service)"

# Ask user if they want to clean up resources
read -p "Do you want to clean up all created resources? (y/n): " CLEANUP_RESPONSE

if [[ "$CLEANUP_RESPONSE" == "y" || "$CLEANUP_RESPONSE" == "Y" ]]; then
    log "User confirmed cleanup. Proceeding with resource deletion."
    # Cleanup function will be called automatically on exit
else
    log "User chose not to clean up resources. Exiting without cleanup."
    trap - EXIT
    exit 0
fi
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreatePublicDnsNamespace](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/CreatePublicDnsNamespace)
  + [CreateService](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/CreateService)
  + [DeleteNamespace](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/DeleteNamespace)
  + [DeleteService](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/DeleteService)
  + [DeregisterInstance](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/DeregisterInstance)
  + [DiscoverInstances](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/DiscoverInstances)
  + [GetOperation](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/GetOperation)
  + [ListNamespaces](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/ListNamespaces)
  + [RegisterInstance](https://docs.aws.amazon.com/goto/aws-cli/servicediscovery-2017-03-14/RegisterInstance)

# Bash スクリプト AWS CLI で を使用する CloudFront の例
<a name="bash_2_cloudfront_code_examples"></a>

次のコード例は、CloudFront AWS Command Line Interface で Bash スクリプトで を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### CloudFront の開始方法
<a name="cloudfront_GettingStarted_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ コンテンツストレージ用の Amazon S3 バケットを作成する
+ サンプルコンテンツを S3 バケットにアップロードする
+ 安全な S3 アクセスのためのオリジンアクセスコントロール (OAC) を作成する
+ S3 をオリジンとして使用して CloudFront ディストリビューションを作成する
+ S3 バケットポリシーを更新して、CloudFront アクセスを許可する
+ ディストリビューションのデプロイを待機し、コンテンツアクセスをテストする
+ ディストリビューション、OAC、S3 バケットなどのリソースをクリーンアップする

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/005-cloudfront-gettingstarted)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# CloudFront Getting Started Tutorial Script
# This script creates an S3 bucket, uploads sample content, creates a CloudFront distribution with OAC,
# and demonstrates how to access content through CloudFront.

# Set up logging
LOG_FILE="cloudfront-tutorial.log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "Starting CloudFront Getting Started Tutorial at $(date)"

# Function to handle errors
handle_error() {
    echo "ERROR: $1"
    echo "Resources created before error:"
    if [ -n "$BUCKET_NAME" ]; then
        echo "- S3 Bucket: $BUCKET_NAME"
    fi
    if [ -n "$OAC_ID" ]; then
        echo "- CloudFront Origin Access Control: $OAC_ID"
    fi
    if [ -n "$DISTRIBUTION_ID" ]; then
        echo "- CloudFront Distribution: $DISTRIBUTION_ID"
    fi
    
    echo "Attempting to clean up resources..."
    cleanup
    exit 1
}

# Function to clean up resources
cleanup() {
    echo "Cleaning up resources..."
    
    if [ -n "$DISTRIBUTION_ID" ]; then
        echo "Disabling CloudFront distribution $DISTRIBUTION_ID..."
        
        # Get the current configuration and ETag
        ETAG=$(aws cloudfront get-distribution-config --id "$DISTRIBUTION_ID" --query 'ETag' --output text)
        if [ $? -ne 0 ]; then
            echo "Failed to get distribution config. Continuing with cleanup..."
        else
            # Create a modified configuration with Enabled=false
            aws cloudfront get-distribution-config --id "$DISTRIBUTION_ID" | \
            jq '.DistributionConfig.Enabled = false' > temp_disabled_config.json
            
            # Update the distribution to disable it
            aws cloudfront update-distribution \
                --id "$DISTRIBUTION_ID" \
                --distribution-config file://<(jq '.DistributionConfig' temp_disabled_config.json) \
                --if-match "$ETAG"
                
            if [ $? -ne 0 ]; then
                echo "Failed to disable distribution. Continuing with cleanup..."
            else
                echo "Waiting for distribution to be disabled (this may take several minutes)..."
                aws cloudfront wait distribution-deployed --id "$DISTRIBUTION_ID"
                
                # Delete the distribution
                ETAG=$(aws cloudfront get-distribution-config --id "$DISTRIBUTION_ID" --query 'ETag' --output text)
                aws cloudfront delete-distribution --id "$DISTRIBUTION_ID" --if-match "$ETAG"
                if [ $? -ne 0 ]; then
                    echo "Failed to delete distribution. You may need to delete it manually."
                else
                    echo "CloudFront distribution deleted."
                fi
            fi
        fi
    fi
    
    if [ -n "$OAC_ID" ]; then
        echo "Deleting Origin Access Control $OAC_ID..."
        OAC_ETAG=$(aws cloudfront get-origin-access-control --id "$OAC_ID" --query 'ETag' --output text 2>/dev/null)
        if [ $? -ne 0 ]; then
            echo "Failed to get Origin Access Control ETag. You may need to delete it manually."
        else
            aws cloudfront delete-origin-access-control --id "$OAC_ID" --if-match "$OAC_ETAG"
            if [ $? -ne 0 ]; then
                echo "Failed to delete Origin Access Control. You may need to delete it manually."
            else
                echo "Origin Access Control deleted."
            fi
        fi
    fi
    
    if [ -n "$BUCKET_NAME" ]; then
        echo "Deleting S3 bucket $BUCKET_NAME and its contents..."
        aws s3 rm "s3://$BUCKET_NAME" --recursive
        if [ $? -ne 0 ]; then
            echo "Failed to remove bucket contents. Continuing with bucket deletion..."
        fi
        
        aws s3 rb "s3://$BUCKET_NAME"
        if [ $? -ne 0 ]; then
            echo "Failed to delete bucket. You may need to delete it manually."
        else
            echo "S3 bucket deleted."
        fi
    fi
    
    # Clean up temporary files
    rm -f temp_disabled_config.json
    rm -rf temp_content
}

# Generate a random identifier for the bucket name
RANDOM_ID=$(openssl rand -hex 6)
BUCKET_NAME="cloudfront-${RANDOM_ID}"
echo "Using bucket name: $BUCKET_NAME"

# Create a temporary directory for content
TEMP_DIR="temp_content"
mkdir -p "$TEMP_DIR/css"
if [ $? -ne 0 ]; then
    handle_error "Failed to create temporary directory"
fi

# Step 1: Create an S3 bucket
echo "Creating S3 bucket: $BUCKET_NAME"
aws s3 mb "s3://$BUCKET_NAME"
if [ $? -ne 0 ]; then
    handle_error "Failed to create S3 bucket"
fi

# Step 2: Create sample content
echo "Creating sample content..."
cat > "$TEMP_DIR/index.html" << 'EOF'
<!DOCTYPE html>
<html>
<head>
    <title>Hello World</title>
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
    <h1>Hello world!</h1>
</body>
</html>
EOF

cat > "$TEMP_DIR/css/styles.css" << 'EOF'
body {
    font-family: Arial, sans-serif;
    margin: 40px;
    background-color: #f5f5f5;
}
h1 {
    color: #333;
    text-align: center;
}
EOF

# Step 3: Upload content to the S3 bucket
echo "Uploading content to S3 bucket..."
aws s3 cp "$TEMP_DIR/" "s3://$BUCKET_NAME/" --recursive
if [ $? -ne 0 ]; then
    handle_error "Failed to upload content to S3 bucket"
fi

# Step 4: Create Origin Access Control
echo "Creating Origin Access Control..."
OAC_RESPONSE=$(aws cloudfront create-origin-access-control \
    --origin-access-control-config Name="oac-for-$BUCKET_NAME",SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3)

if [ $? -ne 0 ]; then
    handle_error "Failed to create Origin Access Control"
fi

OAC_ID=$(echo "$OAC_RESPONSE" | jq -r '.OriginAccessControl.Id')
echo "Created Origin Access Control with ID: $OAC_ID"

# Step 5: Create CloudFront distribution
echo "Creating CloudFront distribution..."

# Get AWS account ID for bucket policy
ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' --output text)
if [ $? -ne 0 ]; then
    handle_error "Failed to get AWS account ID"
fi

# Create distribution configuration
cat > distribution-config.json << EOF
{
    "CallerReference": "cli-tutorial-$(date +%s)",
    "Origins": {
        "Quantity": 1,
        "Items": [
            {
                "Id": "S3-$BUCKET_NAME",
                "DomainName": "$BUCKET_NAME.s3.amazonaws.com",
                "S3OriginConfig": {
                    "OriginAccessIdentity": ""
                },
                "OriginAccessControlId": "$OAC_ID"
            }
        ]
    },
    "DefaultCacheBehavior": {
        "TargetOriginId": "S3-$BUCKET_NAME",
        "ViewerProtocolPolicy": "redirect-to-https",
        "AllowedMethods": {
            "Quantity": 2,
            "Items": ["GET", "HEAD"],
            "CachedMethods": {
                "Quantity": 2,
                "Items": ["GET", "HEAD"]
            }
        },
        "DefaultTTL": 86400,
        "MinTTL": 0,
        "MaxTTL": 31536000,
        "Compress": true,
        "ForwardedValues": {
            "QueryString": false,
            "Cookies": {
                "Forward": "none"
            }
        }
    },
    "Comment": "CloudFront distribution for tutorial",
    "Enabled": true,
    "WebACLId": ""
}
EOF

DIST_RESPONSE=$(aws cloudfront create-distribution --distribution-config file://distribution-config.json)
if [ $? -ne 0 ]; then
    handle_error "Failed to create CloudFront distribution"
fi

DISTRIBUTION_ID=$(echo "$DIST_RESPONSE" | jq -r '.Distribution.Id')
DOMAIN_NAME=$(echo "$DIST_RESPONSE" | jq -r '.Distribution.DomainName')

echo "Created CloudFront distribution with ID: $DISTRIBUTION_ID"
echo "CloudFront domain name: $DOMAIN_NAME"

# Step 6: Update S3 bucket policy
echo "Updating S3 bucket policy..."
cat > bucket-policy.json << EOF
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowCloudFrontServicePrincipal",
            "Effect": "Allow",
            "Principal": {
                "Service": "cloudfront.amazonaws.com"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::$BUCKET_NAME/*",
            "Condition": {
                "StringEquals": {
                    "AWS:SourceArn": "arn:aws:cloudfront::$ACCOUNT_ID:distribution/$DISTRIBUTION_ID"
                }
            }
        }
    ]
}
EOF

aws s3api put-bucket-policy --bucket "$BUCKET_NAME" --policy file://bucket-policy.json
if [ $? -ne 0 ]; then
    handle_error "Failed to update S3 bucket policy"
fi

# Step 7: Wait for distribution to deploy
echo "Waiting for CloudFront distribution to deploy (this may take 5-10 minutes)..."
aws cloudfront wait distribution-deployed --id "$DISTRIBUTION_ID"
if [ $? -ne 0 ]; then
    echo "Warning: Distribution deployment wait timed out. The distribution may still be deploying."
else
    echo "CloudFront distribution is now deployed."
fi

# Step 8: Display access information
echo ""
echo "===== CloudFront Distribution Setup Complete ====="
echo "You can access your content at: https://$DOMAIN_NAME/index.html"
echo ""
echo "Resources created:"
echo "- S3 Bucket: $BUCKET_NAME"
echo "- CloudFront Origin Access Control: $OAC_ID"
echo "- CloudFront Distribution: $DISTRIBUTION_ID"
echo ""

# Ask user if they want to clean up resources
read -p "Do you want to clean up all resources created by this script? (y/n): " CLEANUP_RESPONSE
if [[ "$CLEANUP_RESPONSE" =~ ^[Yy] ]]; then
    cleanup
    echo "All resources have been cleaned up."
else
    echo "Resources will not be cleaned up. You can manually delete them later."
    echo "To access your content, visit: https://$DOMAIN_NAME/index.html"
fi

echo "Tutorial completed at $(date)"
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateDistribution](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/CreateDistribution)
  + [CreateOriginAccessControl](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/CreateOriginAccessControl)
  + [DeleteDistribution](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/DeleteDistribution)
  + [DeleteOriginAccessControl](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/DeleteOriginAccessControl)
  + [GetDistribution](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/GetDistribution)
  + [GetDistributionConfig](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/GetDistributionConfig)
  + [GetOriginAccessControl](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/GetOriginAccessControl)
  + [UpdateDistribution](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/UpdateDistribution)
  + [WaitDistributionDeployed](https://docs.aws.amazon.com/goto/aws-cli/cloudfront-2020-05-31/WaitDistributionDeployed)

# Bash スクリプト AWS CLI で を使用する DynamoDB の例
<a name="bash_2_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS Command Line Interface で Bash スクリプトで を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。
DynamoDB の開始シナリオ。  

```
###############################################################################
# function dynamodb_getting_started_movies
#
# Scenario to create an Amazon DynamoDB table and perform a series of operations on the table.
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function dynamodb_getting_started_movies() {

  source ./dynamodb_operations.sh

  key_schema_json_file="dynamodb_key_schema.json"
  attribute_definitions_json_file="dynamodb_attr_def.json"
  item_json_file="movie_item.json"
  key_json_file="movie_key.json"
  batch_json_file="batch.json"
  attribute_names_json_file="attribute_names.json"
  attributes_values_json_file="attribute_values.json"

  echo_repeat "*" 88
  echo
  echo "Welcome to the Amazon DynamoDB getting started demo."
  echo
  echo_repeat "*" 88
  echo

  local table_name
  echo -n "Enter a name for a new DynamoDB table: "
  get_input
  table_name=$get_input_result

  echo '[
  {"AttributeName": "year", "KeyType": "HASH"},
   {"AttributeName": "title", "KeyType": "RANGE"}
  ]' >"$key_schema_json_file"

  echo '[
  {"AttributeName": "year", "AttributeType": "N"},
   {"AttributeName": "title", "AttributeType": "S"}
  ]' >"$attribute_definitions_json_file"

  if dynamodb_create_table -n "$table_name" -a "$attribute_definitions_json_file" \
    -k "$key_schema_json_file" 1>/dev/null; then
    echo "Created a DynamoDB table named $table_name"
  else
    errecho "The table failed to create. This demo will exit."
    clean_up
    return 1
  fi

  echo "Waiting for the table to become active...."

  if dynamodb_wait_table_active -n "$table_name"; then
    echo "The table is now active."
  else
    errecho "The table failed to become active. This demo will exit."
    cleanup "$table_name"
    return 1
  fi

  echo
  echo_repeat "*" 88
  echo

  echo -n "Enter the title of a movie you want to add to the table: "
  get_input
  local added_title
  added_title=$get_input_result

  local added_year
  get_int_input "What year was it released? "
  added_year=$get_input_result

  local rating
  get_float_input "On a scale of 1 - 10, how do you rate it? " "1" "10"
  rating=$get_input_result

  local plot
  echo -n "Summarize the plot for me: "
  get_input
  plot=$get_input_result

  echo '{
    "year": {"N" :"'"$added_year"'"},
    "title": {"S" :  "'"$added_title"'"},
    "info": {"M" : {"plot": {"S" : "'"$plot"'"}, "rating": {"N" :"'"$rating"'"} } }
   }' >"$item_json_file"

  if dynamodb_put_item -n "$table_name" -i "$item_json_file"; then
    echo "The movie '$added_title' was successfully added to the table '$table_name'."
  else
    errecho "Put item failed. This demo will exit."
    clean_up "$table_name"
    return 1
  fi

  echo
  echo_repeat "*" 88
  echo

  echo "Let's update your movie '$added_title'."
  get_float_input "You rated it $rating, what new rating would you give it? " "1" "10"
  rating=$get_input_result

  echo -n "You summarized the plot as '$plot'."
  echo "What would you say now? "
  get_input
  plot=$get_input_result

  echo '{
    "year": {"N" :"'"$added_year"'"},
    "title": {"S" :  "'"$added_title"'"}
    }' >"$key_json_file"

  echo '{
    ":r": {"N" :"'"$rating"'"},
    ":p": {"S" : "'"$plot"'"}
   }' >"$item_json_file"

  local update_expression="SET info.rating = :r, info.plot = :p"

  if dynamodb_update_item -n "$table_name" -k "$key_json_file" -e "$update_expression" -v "$item_json_file"; then
    echo "Updated '$added_title' with new attributes."
  else
    errecho "Update item failed. This demo will exit."
    clean_up "$table_name"
    return 1
  fi

  echo
  echo_repeat "*" 88
  echo

  echo "We will now use batch write to upload 150 movie entries into the table."

  local batch_json
  for batch_json in movie_files/movies_*.json; do
    echo "{ \"$table_name\" : $(<"$batch_json") }" >"$batch_json_file"
    if dynamodb_batch_write_item -i "$batch_json_file" 1>/dev/null; then
      echo "Entries in $batch_json added to table."
    else
      errecho "Batch write failed. This demo will exit."
      clean_up "$table_name"
      return 1
    fi
  done

  local title="The Lord of the Rings: The Fellowship of the Ring"
  local year="2001"

  if get_yes_no_input "Let's move on...do you want to get info about '$title'? (y/n) "; then
    echo '{
  "year": {"N" :"'"$year"'"},
  "title": {"S" :  "'"$title"'"}
  }' >"$key_json_file"
    local info
    info=$(dynamodb_get_item -n "$table_name" -k "$key_json_file")

    # shellcheck disable=SC2181
    if [[ ${?} -ne 0 ]]; then
      errecho "Get item failed. This demo will exit."
      clean_up "$table_name"
      return 1
    fi

    echo "Here is what I found:"
    echo "$info"
  fi

  local ask_for_year=true
  while [[ "$ask_for_year" == true ]]; do
    echo "Let's get a list of movies released in a given year."
    get_int_input "Enter a year between 1972 and 2018: " "1972" "2018"
    year=$get_input_result
    echo '{
    "#n": "year"
    }' >"$attribute_names_json_file"

    echo '{
    ":v": {"N" :"'"$year"'"}
    }' >"$attributes_values_json_file"

    response=$(dynamodb_query -n "$table_name" -k "#n=:v" -a "$attribute_names_json_file" -v "$attributes_values_json_file")

    # shellcheck disable=SC2181
    if [[ ${?} -ne 0 ]]; then
      errecho "Query table failed. This demo will exit."
      clean_up "$table_name"
      return 1
    fi

    echo "Here is what I found:"
    echo "$response"

    if ! get_yes_no_input "Try another year? (y/n) "; then
      ask_for_year=false
    fi
  done

  echo "Now let's scan for movies released in a range of years. Enter a year: "
  get_int_input "Enter a year between 1972 and 2018: " "1972" "2018"
  local start=$get_input_result

  get_int_input "Enter another year: " "1972" "2018"
  local end=$get_input_result

  echo '{
    "#n": "year"
    }' >"$attribute_names_json_file"

  echo '{
    ":v1": {"N" : "'"$start"'"},
    ":v2": {"N" : "'"$end"'"}
    }' >"$attributes_values_json_file"

  response=$(dynamodb_scan -n "$table_name" -f "#n BETWEEN :v1 AND :v2" -a "$attribute_names_json_file" -v "$attributes_values_json_file")

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    errecho "Scan table failed. This demo will exit."
    clean_up "$table_name"
    return 1
  fi

  echo "Here is what I found:"
  echo "$response"

  echo
  echo_repeat "*" 88
  echo

  echo "Let's remove your movie '$added_title' from the table."

  if get_yes_no_input "Do you want to remove '$added_title'? (y/n) "; then
    echo '{
  "year": {"N" :"'"$added_year"'"},
  "title": {"S" :  "'"$added_title"'"}
  }' >"$key_json_file"

    if ! dynamodb_delete_item -n "$table_name" -k "$key_json_file"; then
      errecho "Delete item failed. This demo will exit."
      clean_up "$table_name"
      return 1
    fi
  fi

  if get_yes_no_input "Do you want to delete the table '$table_name'? (y/n) "; then
    if ! clean_up "$table_name"; then
      return 1
    fi
  else
    if ! clean_up; then
      return 1
    fi
  fi

  return 0
}
```
このシナリオで使用される DynamoDB 関数。  

```
###############################################################################
# function dynamodb_create_table
#
# This function creates an Amazon DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table to create.
#       -a attribute_definitions -- JSON file path of a list of attributes and their types.
#       -k key_schema -- JSON file path of a list of attributes and their key types.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function dynamodb_create_table() {
  local table_name attribute_definitions key_schema response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_create_table"
    echo "Creates an Amazon DynamoDB table with on-demand billing."
    echo " -n table_name  -- The name of the table to create."
    echo " -a attribute_definitions -- JSON file path of a list of attributes and their types."
    echo " -k key_schema -- JSON file path of a list of attributes and their key types."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:a:k:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      a) attribute_definitions="${OPTARG}" ;;
      k) key_schema="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_definitions" ]]; then
    errecho "ERROR: You must provide an attribute definitions json file path the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$key_schema" ]]; then
    errecho "ERROR: You must provide a key schema json file path the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    attribute_definitions:   $attribute_definitions"
  iecho "    key_schema:   $key_schema"
  iecho ""

  response=$(aws dynamodb create-table \
    --table-name "$table_name" \
    --attribute-definitions file://"$attribute_definitions" \
    --billing-mode PAY_PER_REQUEST \
    --key-schema file://"$key_schema" )

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-table operation failed.$response"
    return 1
  fi

  return 0
}

###############################################################################
# function dynamodb_describe_table
#
# This function returns the status of a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#
#  Response:
#       - TableStatus:
#     And:
#       0 - Table is active.
#       1 - If it fails.
###############################################################################
function dynamodb_describe_table {
  local table_name
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_describe_table"
    echo "Describe the status of a DynamoDB table."
    echo "  -n table_name  -- The name of the table."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  local table_status
    table_status=$(
      aws dynamodb describe-table \
        --table-name "$table_name" \
        --output text \
        --query 'Table.TableStatus'
    )

   local error_code=${?}

    if [[ $error_code -ne 0 ]]; then
      aws_cli_error_log "$error_code"
      errecho "ERROR: AWS reports describe-table operation failed.$table_status"
      return 1
    fi

  echo "$table_status"

  return 0
}

##############################################################################
# function dynamodb_put_item
#
# This function puts an item into a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -i item  -- Path to json file containing the item values.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
##############################################################################
function dynamodb_put_item() {
  local table_name item response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_put_item"
    echo "Put an item into a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -i item  -- Path to json file containing the item values."
    echo ""
  }

  while getopts "n:i:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      i) item="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$item" ]]; then
    errecho "ERROR: You must provide an item with the -i parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    item:   $item"
  iecho ""
  iecho ""

  response=$(aws dynamodb put-item \
    --table-name "$table_name" \
    --item file://"$item")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports put-item operation failed.$response"
    return 1
  fi

  return 0

}

##############################################################################
# function dynamodb_update_item
#
# This function updates an item in a DynamoDB table.
#
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to update.
#       -e update expression  -- An expression that defines one or more attributes to be updated.
#       -v values  -- Path to json file containing the update values.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
#############################################################################
function dynamodb_update_item() {
  local table_name keys update_expression values response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_update_item"
    echo "Update an item in a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to update."
    echo " -e update expression  -- An expression that defines one or more attributes to be updated."
    echo " -v values  -- Path to json file containing the update values."
    echo ""
  }

  while getopts "n:k:e:v:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      e) update_expression="${OPTARG}" ;;
      v) values="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$keys" ]]; then
    errecho "ERROR: You must provide a keys json file path the -k parameter."
    usage
    return 1
  fi
  if [[ -z "$update_expression" ]]; then
    errecho "ERROR: You must provide an update expression with the -e parameter."
    usage
    return 1
  fi

  if [[ -z "$values" ]]; then
    errecho "ERROR: You must provide a values json file path the -v parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    keys:   $keys"
  iecho "    update_expression:   $update_expression"
  iecho "    values:   $values"

  response=$(aws dynamodb update-item \
    --table-name "$table_name" \
    --key file://"$keys" \
    --update-expression "$update_expression" \
    --expression-attribute-values file://"$values")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports update-item operation failed.$response"
    return 1
  fi

  return 0

}

##############################################################################
# function dynamodb_batch_write_item
#
# This function writes a batch of items into a DynamoDB table.
#
# Parameters:
#       -i item  -- Path to json file containing the items to write.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
############################################################################
function dynamodb_batch_write_item() {
  local item response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_batch_write_item"
    echo "Write a batch of items into a DynamoDB table."
    echo " -i item  -- Path to json file containing the items to write."
    echo ""
  }
  while getopts "i:h" option; do
    case "${option}" in
      i) item="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$item" ]]; then
    errecho "ERROR: You must provide an item with the -i parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    item:   $item"
  iecho ""

  response=$(aws dynamodb batch-write-item \
    --request-items file://"$item")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports batch-write-item operation failed.$response"
    return 1
  fi

  return 0
}

#############################################################################
# function dynamodb_get_item
#
# This function gets an item from a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to get.
#       [-q query]  -- Optional JMESPath query expression.
#
#  Returns:
#       The item as text output.
#  And:
#       0 - If successful.
#       1 - If it fails.
############################################################################
function dynamodb_get_item() {
  local table_name keys query response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_get_item"
    echo "Get an item from a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to get."
    echo " [-q query]  -- Optional JMESPath query expression."
    echo ""
  }
  query=""
  while getopts "n:k:q:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      q) query="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$keys" ]]; then
    errecho "ERROR: You must provide a keys json file path the -k parameter."
    usage
    return 1
  fi

  if [[ -n "$query" ]]; then
    response=$(aws dynamodb get-item \
      --table-name "$table_name" \
      --key file://"$keys" \
      --output text \
      --query "$query")
  else
    response=$(
      aws dynamodb get-item \
        --table-name "$table_name" \
        --key file://"$keys" \
        --output text
    )
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports get-item operation failed.$response"
    return 1
  fi

  if [[ -n "$query" ]]; then
    echo "$response" | sed "/^\t/s/\t//1" # Remove initial tab that the JMSEPath query inserts on some strings.
  else
    echo "$response"
  fi

  return 0
}

#############################################################################
# function dynamodb_query
#
# This function queries a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k key_condition_expression -- The key condition expression.
#       -a attribute_names -- Path to JSON file containing the attribute names.
#       -v attribute_values -- Path to JSON file containing the attribute values.
#       [-p projection_expression]  -- Optional projection expression.
#
#  Returns:
#       The items as json output.
#  And:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_query() {
  local table_name key_condition_expression attribute_names attribute_values projection_expression response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_query"
    echo "Query a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k key_condition_expression -- The key condition expression."
    echo " -a attribute_names -- Path to JSON file containing the attribute names."
    echo " -v attribute_values -- Path to JSON file containing the attribute values."
    echo " [-p projection_expression]  -- Optional projection expression."
    echo ""
  }

  while getopts "n:k:a:v:p:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) key_condition_expression="${OPTARG}" ;;
      a) attribute_names="${OPTARG}" ;;
      v) attribute_values="${OPTARG}" ;;
      p) projection_expression="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$key_condition_expression" ]]; then
    errecho "ERROR: You must provide a key condition expression with the -k parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_names" ]]; then
    errecho "ERROR: You must provide a attribute names with the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_values" ]]; then
    errecho "ERROR: You must provide a attribute values with the -v parameter."
    usage
    return 1
  fi

  if [[ -z "$projection_expression" ]]; then
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values")
  else
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values" \
      --projection-expression "$projection_expression")
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports query operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}

#############################################################################
# function dynamodb_scan
#
# This function scans a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -f filter_expression  -- The filter expression.
#       -a expression_attribute_names -- Path to JSON file containing the expression attribute names.
#       -v expression_attribute_values -- Path to JSON file containing the expression attribute values.
#       [-p projection_expression]  -- Optional projection expression.
#
#  Returns:
#       The items as json output.
#  And:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_scan() {
  local table_name filter_expression expression_attribute_names expression_attribute_values projection_expression response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_scan"
    echo "Scan a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -f filter_expression  -- The filter expression."
    echo " -a expression_attribute_names -- Path to JSON file containing the expression attribute names."
    echo " -v expression_attribute_values -- Path to JSON file containing the expression attribute values."
    echo " [-p projection_expression]  -- Optional projection expression."
    echo ""
  }

  while getopts "n:f:a:v:p:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      f) filter_expression="${OPTARG}" ;;
      a) expression_attribute_names="${OPTARG}" ;;
      v) expression_attribute_values="${OPTARG}" ;;
      p) projection_expression="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$filter_expression" ]]; then
    errecho "ERROR: You must provide a filter expression with the -f parameter."
    usage
    return 1
  fi

  if [[ -z "$expression_attribute_names" ]]; then
    errecho "ERROR: You must provide expression attribute names with the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$expression_attribute_values" ]]; then
    errecho "ERROR: You must provide expression attribute values with the -v parameter."
    usage
    return 1
  fi

  if [[ -z "$projection_expression" ]]; then
    response=$(aws dynamodb scan \
      --table-name "$table_name" \
      --filter-expression "$filter_expression" \
      --expression-attribute-names file://"$expression_attribute_names" \
      --expression-attribute-values file://"$expression_attribute_values")
  else
    response=$(aws dynamodb scan \
      --table-name "$table_name" \
      --filter-expression "$filter_expression" \
      --expression-attribute-names file://"$expression_attribute_names" \
      --expression-attribute-values file://"$expression_attribute_values" \
      --projection-expression "$projection_expression")
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports scan operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}

##############################################################################
# function dynamodb_delete_item
#
# This function deletes an item from a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to delete.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_delete_item() {
  local table_name keys response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_delete_item"
    echo "Delete an item from a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to delete."
    echo ""
  }
  while getopts "n:k:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$keys" ]]; then
    errecho "ERROR: You must provide a keys json file path the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    keys:   $keys"
  iecho ""

  response=$(aws dynamodb delete-item \
    --table-name "$table_name" \
    --key file://"$keys")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-item operation failed.$response"
    return 1
  fi

  return 0

}

###############################################################################
# function dynamodb_delete_table
#
# This function deletes a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table to delete.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function dynamodb_delete_table() {
  local table_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function dynamodb_delete_table"
    echo "Deletes an Amazon DynamoDB table."
    echo " -n table_name  -- The name of the table to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho ""

  response=$(aws dynamodb delete-table \
    --table-name "$table_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-table operation failed.$response"
    return 1
  fi

  return 0
}
```
このシナリオで使用されるユーティリティ関数。  

```
###############################################################################
# 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 aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/BatchWriteItem)
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DeleteItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteItem)
  + [DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Scan)
  + [UpdateItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateItem)

## アクション
<a name="actions"></a>

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_bash_2_topic"></a>

次の例は、`BatchGetItem` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
#############################################################################
# function dynamodb_batch_get_item
#
# This function gets a batch of items from a DynamoDB table.
#
# Parameters:
#       -i item  -- Path to json file containing the keys of the items to get.
#
#  Returns:
#       The items as json output.
#  And:
#       0 - If successful.
#       1 - If it fails.
##########################################################################
function dynamodb_batch_get_item() {
  local item response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_batch_get_item"
    echo "Get a batch of items from a DynamoDB table."
    echo " -i item  -- Path to json file containing the keys of the items to get."
    echo ""
  }

  while getopts "i:h" option; do
    case "${option}" in
      i) item="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$item" ]]; then
    errecho "ERROR: You must provide an item with the -i parameter."
    usage
    return 1
  fi

  response=$(aws dynamodb batch-get-item \
    --request-items file://"$item")
  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports batch-get-item operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/BatchGetItem)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_bash_2_topic"></a>

次の例は、`BatchWriteItem` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
##############################################################################
# function dynamodb_batch_write_item
#
# This function writes a batch of items into a DynamoDB table.
#
# Parameters:
#       -i item  -- Path to json file containing the items to write.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
############################################################################
function dynamodb_batch_write_item() {
  local item response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_batch_write_item"
    echo "Write a batch of items into a DynamoDB table."
    echo " -i item  -- Path to json file containing the items to write."
    echo ""
  }
  while getopts "i:h" option; do
    case "${option}" in
      i) item="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$item" ]]; then
    errecho "ERROR: You must provide an item with the -i parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    item:   $item"
  iecho ""

  response=$(aws dynamodb batch-write-item \
    --request-items file://"$item")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports batch-write-item operation failed.$response"
    return 1
  fi

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchWriteItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。

### `CreateTable`
<a name="dynamodb_CreateTable_bash_2_topic"></a>

次の例は、`CreateTable` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function dynamodb_create_table
#
# This function creates an Amazon DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table to create.
#       -a attribute_definitions -- JSON file path of a list of attributes and their types.
#       -k key_schema -- JSON file path of a list of attributes and their key types.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function dynamodb_create_table() {
  local table_name attribute_definitions key_schema response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_create_table"
    echo "Creates an Amazon DynamoDB table with on-demand billing."
    echo " -n table_name  -- The name of the table to create."
    echo " -a attribute_definitions -- JSON file path of a list of attributes and their types."
    echo " -k key_schema -- JSON file path of a list of attributes and their key types."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:a:k:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      a) attribute_definitions="${OPTARG}" ;;
      k) key_schema="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_definitions" ]]; then
    errecho "ERROR: You must provide an attribute definitions json file path the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$key_schema" ]]; then
    errecho "ERROR: You must provide a key schema json file path the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    attribute_definitions:   $attribute_definitions"
  iecho "    key_schema:   $key_schema"
  iecho ""

  response=$(aws dynamodb create-table \
    --table-name "$table_name" \
    --attribute-definitions file://"$attribute_definitions" \
    --billing-mode PAY_PER_REQUEST \
    --key-schema file://"$key_schema" )

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-table operation failed.$response"
    return 1
  fi

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_bash_2_topic"></a>

次の例は、`DeleteItem` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
##############################################################################
# function dynamodb_delete_item
#
# This function deletes an item from a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to delete.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_delete_item() {
  local table_name keys response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_delete_item"
    echo "Delete an item from a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to delete."
    echo ""
  }
  while getopts "n:k:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$keys" ]]; then
    errecho "ERROR: You must provide a keys json file path the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    keys:   $keys"
  iecho ""

  response=$(aws dynamodb delete-item \
    --table-name "$table_name" \
    --key file://"$keys")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-item operation failed.$response"
    return 1
  fi

  return 0

}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteItem)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_bash_2_topic"></a>

次の例は、`DeleteTable` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function dynamodb_delete_table
#
# This function deletes a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table to delete.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function dynamodb_delete_table() {
  local table_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function dynamodb_delete_table"
    echo "Deletes an Amazon DynamoDB table."
    echo " -n table_name  -- The name of the table to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho ""

  response=$(aws dynamodb delete-table \
    --table-name "$table_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-table operation failed.$response"
    return 1
  fi

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_bash_2_topic"></a>

次の例は、`DescribeTable` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function dynamodb_describe_table
#
# This function returns the status of a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#
#  Response:
#       - TableStatus:
#     And:
#       0 - Table is active.
#       1 - If it fails.
###############################################################################
function dynamodb_describe_table {
  local table_name
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_describe_table"
    echo "Describe the status of a DynamoDB table."
    echo "  -n table_name  -- The name of the table."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  local table_status
    table_status=$(
      aws dynamodb describe-table \
        --table-name "$table_name" \
        --output text \
        --query 'Table.TableStatus'
    )

   local error_code=${?}

    if [[ $error_code -ne 0 ]]; then
      aws_cli_error_log "$error_code"
      errecho "ERROR: AWS reports describe-table operation failed.$table_status"
      return 1
    fi

  echo "$table_status"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_bash_2_topic"></a>

次の例は、`GetItem` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
#############################################################################
# function dynamodb_get_item
#
# This function gets an item from a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to get.
#       [-q query]  -- Optional JMESPath query expression.
#
#  Returns:
#       The item as text output.
#  And:
#       0 - If successful.
#       1 - If it fails.
############################################################################
function dynamodb_get_item() {
  local table_name keys query response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_get_item"
    echo "Get an item from a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to get."
    echo " [-q query]  -- Optional JMESPath query expression."
    echo ""
  }
  query=""
  while getopts "n:k:q:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      q) query="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$keys" ]]; then
    errecho "ERROR: You must provide a keys json file path the -k parameter."
    usage
    return 1
  fi

  if [[ -n "$query" ]]; then
    response=$(aws dynamodb get-item \
      --table-name "$table_name" \
      --key file://"$keys" \
      --output text \
      --query "$query")
  else
    response=$(
      aws dynamodb get-item \
        --table-name "$table_name" \
        --key file://"$keys" \
        --output text
    )
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports get-item operation failed.$response"
    return 1
  fi

  if [[ -n "$query" ]]; then
    echo "$response" | sed "/^\t/s/\t//1" # Remove initial tab that the JMSEPath query inserts on some strings.
  else
    echo "$response"
  fi

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_bash_2_topic"></a>

次の例は、`ListTables` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
##############################################################################
# function dynamodb_list_tables
#
# This function lists all the tables in a DynamoDB.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_list_tables() {
  response=$(aws dynamodb list-tables \
    --output text \
    --query "TableNames")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports batch-write-item operation failed.$response"
    return 1
  fi

  echo "$response" | tr -s "[:space:]" "\n"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTables](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_bash_2_topic"></a>

次の例は、`PutItem` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
##############################################################################
# function dynamodb_put_item
#
# This function puts an item into a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -i item  -- Path to json file containing the item values.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
##############################################################################
function dynamodb_put_item() {
  local table_name item response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_put_item"
    echo "Put an item into a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -i item  -- Path to json file containing the item values."
    echo ""
  }

  while getopts "n:i:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      i) item="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$item" ]]; then
    errecho "ERROR: You must provide an item with the -i parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    item:   $item"
  iecho ""
  iecho ""

  response=$(aws dynamodb put-item \
    --table-name "$table_name" \
    --item file://"$item")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports put-item operation failed.$response"
    return 1
  fi

  return 0

}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)」を参照してください。

### `Query`
<a name="dynamodb_Query_bash_2_topic"></a>

次の例は、`Query` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
#############################################################################
# function dynamodb_query
#
# This function queries a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k key_condition_expression -- The key condition expression.
#       -a attribute_names -- Path to JSON file containing the attribute names.
#       -v attribute_values -- Path to JSON file containing the attribute values.
#       [-p projection_expression]  -- Optional projection expression.
#
#  Returns:
#       The items as json output.
#  And:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_query() {
  local table_name key_condition_expression attribute_names attribute_values projection_expression response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_query"
    echo "Query a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k key_condition_expression -- The key condition expression."
    echo " -a attribute_names -- Path to JSON file containing the attribute names."
    echo " -v attribute_values -- Path to JSON file containing the attribute values."
    echo " [-p projection_expression]  -- Optional projection expression."
    echo ""
  }

  while getopts "n:k:a:v:p:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) key_condition_expression="${OPTARG}" ;;
      a) attribute_names="${OPTARG}" ;;
      v) attribute_values="${OPTARG}" ;;
      p) projection_expression="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$key_condition_expression" ]]; then
    errecho "ERROR: You must provide a key condition expression with the -k parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_names" ]]; then
    errecho "ERROR: You must provide a attribute names with the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$attribute_values" ]]; then
    errecho "ERROR: You must provide a attribute values with the -v parameter."
    usage
    return 1
  fi

  if [[ -z "$projection_expression" ]]; then
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values")
  else
    response=$(aws dynamodb query \
      --table-name "$table_name" \
      --key-condition-expression "$key_condition_expression" \
      --expression-attribute-names file://"$attribute_names" \
      --expression-attribute-values file://"$attribute_values" \
      --projection-expression "$projection_expression")
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports query operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Query](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_bash_2_topic"></a>

次の例は、`Scan` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
#############################################################################
# function dynamodb_scan
#
# This function scans a DynamoDB table.
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -f filter_expression  -- The filter expression.
#       -a expression_attribute_names -- Path to JSON file containing the expression attribute names.
#       -v expression_attribute_values -- Path to JSON file containing the expression attribute values.
#       [-p projection_expression]  -- Optional projection expression.
#
#  Returns:
#       The items as json output.
#  And:
#       0 - If successful.
#       1 - If it fails.
###########################################################################
function dynamodb_scan() {
  local table_name filter_expression expression_attribute_names expression_attribute_values projection_expression response
  local option OPTARG # Required to use getopts command in a function.

  # ######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_scan"
    echo "Scan a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -f filter_expression  -- The filter expression."
    echo " -a expression_attribute_names -- Path to JSON file containing the expression attribute names."
    echo " -v expression_attribute_values -- Path to JSON file containing the expression attribute values."
    echo " [-p projection_expression]  -- Optional projection expression."
    echo ""
  }

  while getopts "n:f:a:v:p:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      f) filter_expression="${OPTARG}" ;;
      a) expression_attribute_names="${OPTARG}" ;;
      v) expression_attribute_values="${OPTARG}" ;;
      p) projection_expression="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$filter_expression" ]]; then
    errecho "ERROR: You must provide a filter expression with the -f parameter."
    usage
    return 1
  fi

  if [[ -z "$expression_attribute_names" ]]; then
    errecho "ERROR: You must provide expression attribute names with the -a parameter."
    usage
    return 1
  fi

  if [[ -z "$expression_attribute_values" ]]; then
    errecho "ERROR: You must provide expression attribute values with the -v parameter."
    usage
    return 1
  fi

  if [[ -z "$projection_expression" ]]; then
    response=$(aws dynamodb scan \
      --table-name "$table_name" \
      --filter-expression "$filter_expression" \
      --expression-attribute-names file://"$expression_attribute_names" \
      --expression-attribute-values file://"$expression_attribute_values")
  else
    response=$(aws dynamodb scan \
      --table-name "$table_name" \
      --filter-expression "$filter_expression" \
      --expression-attribute-names file://"$expression_attribute_names" \
      --expression-attribute-values file://"$expression_attribute_values" \
      --projection-expression "$projection_expression")
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports scan operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Scan](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Scan)」を参照してください。

### `UpdateItem`
<a name="dynamodb_UpdateItem_bash_2_topic"></a>

次の例は、`UpdateItem` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
##############################################################################
# function dynamodb_update_item
#
# This function updates an item in a DynamoDB table.
#
#
# Parameters:
#       -n table_name  -- The name of the table.
#       -k keys  -- Path to json file containing the keys that identify the item to update.
#       -e update expression  -- An expression that defines one or more attributes to be updated.
#       -v values  -- Path to json file containing the update values.
#
#  Returns:
#       0 - If successful.
#       1 - If it fails.
#############################################################################
function dynamodb_update_item() {
  local table_name keys update_expression values response
  local option OPTARG # Required to use getopts command in a function.

  #######################################
  # Function usage explanation
  #######################################
  function usage() {
    echo "function dynamodb_update_item"
    echo "Update an item in a DynamoDB table."
    echo " -n table_name  -- The name of the table."
    echo " -k keys  -- Path to json file containing the keys that identify the item to update."
    echo " -e update expression  -- An expression that defines one or more attributes to be updated."
    echo " -v values  -- Path to json file containing the update values."
    echo ""
  }

  while getopts "n:k:e:v:h" option; do
    case "${option}" in
      n) table_name="${OPTARG}" ;;
      k) keys="${OPTARG}" ;;
      e) update_expression="${OPTARG}" ;;
      v) values="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$table_name" ]]; then
    errecho "ERROR: You must provide a table name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$keys" ]]; then
    errecho "ERROR: You must provide a keys json file path the -k parameter."
    usage
    return 1
  fi
  if [[ -z "$update_expression" ]]; then
    errecho "ERROR: You must provide an update expression with the -e parameter."
    usage
    return 1
  fi

  if [[ -z "$values" ]]; then
    errecho "ERROR: You must provide a values json file path the -v parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    table_name:   $table_name"
  iecho "    keys:   $keys"
  iecho "    update_expression:   $update_expression"
  iecho "    values:   $values"

  response=$(aws dynamodb update-item \
    --table-name "$table_name" \
    --key file://"$keys" \
    --update-expression "$update_expression" \
    --expression-attribute-values file://"$values")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports update-item operation failed.$response"
    return 1
  fi

  return 0

}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# 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 aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# See https://docs.aws.amazon.com/cli/latest/topic/return-codes.html#cli-aws-help-return-codes.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateItem)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### グローバルセカンダリインデックスの高度なシナリオ
<a name="dynamodb_Scenario_GSIAdvanced_bash_2_topic"></a>

次のコード例は、グローバルセカンダリインデックスの高度な設定の操作方法を示しています。
+ 複数の GSI を含むテーブルを作成します。
+ オンデマンドキャパシティと GSI を含むテーブルを作成します。
+ 複数の GSI を含むテーブルに項目を配置します。
+ 異なる条件で複数の GSI をクエリします。

**AWS CLI Bash スクリプトを使用する**  
複数の GSI を含むテーブルを作成します。  

```
# Create a table with multiple GSIs
aws dynamodb create-table \
    --table-name MusicLibrary \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
        AttributeName=AlbumTitle,AttributeType=S \
        AttributeName=Genre,AttributeType=S \
        AttributeName=Year,AttributeType=N \
    --key-schema \
        AttributeName=Artist,KeyType=HASH \
        AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST \
    --global-secondary-indexes \
        "[
            {
                \"IndexName\": \"AlbumIndex\",
                \"KeySchema\": [{\"AttributeName\":\"AlbumTitle\",\"KeyType\":\"HASH\"}],
                \"Projection\": {\"ProjectionType\":\"ALL\"}
            },
            {
                \"IndexName\": \"GenreYearIndex\",
                \"KeySchema\": [
                    {\"AttributeName\":\"Genre\",\"KeyType\":\"HASH\"},
                    {\"AttributeName\":\"Year\",\"KeyType\":\"RANGE\"}
                ],
                \"Projection\": {\"ProjectionType\":\"INCLUDE\",\"NonKeyAttributes\":[\"Artist\",\"SongTitle\"]}
            }
        ]"
```
オンデマンドキャパシティと GSI を含むテーブルを作成します。  

```
# Create a table with on-demand capacity and GSI
aws dynamodb create-table \
    --table-name MusicOnDemand \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
        AttributeName=Genre,AttributeType=S \
    --key-schema \
        AttributeName=Artist,KeyType=HASH \
        AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST \
    --global-secondary-indexes \
        "[
            {
                \"IndexName\": \"GenreIndex\",
                \"KeySchema\": [{\"AttributeName\":\"Genre\",\"KeyType\":\"HASH\"}],
                \"Projection\": {\"ProjectionType\":\"ALL\"}
            }
        ]"
```
複数の GSI を含むテーブルに項目を配置します。  

```
# Add items to MusicLibrary table
aws dynamodb put-item \
    --table-name MusicLibrary \
    --item '{
        "Artist": {"S": "The Beatles"},
        "SongTitle": {"S": "Hey Jude"},
        "AlbumTitle": {"S": "Past Masters"},
        "Genre": {"S": "Rock"},
        "Year": {"N": "1968"}
    }'

aws dynamodb put-item \
    --table-name MusicLibrary \
    --item '{
        "Artist": {"S": "Miles Davis"},
        "SongTitle": {"S": "So What"},
        "AlbumTitle": {"S": "Kind of Blue"},
        "Genre": {"S": "Jazz"},
        "Year": {"N": "1959"}
    }'
```
複数の GSI を含むテーブルの項目をクエリします。  

```
# Query the AlbumIndex GSI
echo "Querying AlbumIndex GSI:"
aws dynamodb query \
    --table-name MusicLibrary \
    --index-name AlbumIndex \
    --key-condition-expression "AlbumTitle = :album" \
    --expression-attribute-values '{":album":{"S":"Kind of Blue"}}'

# Query the GenreYearIndex GSI with a range condition
echo "Querying GenreYearIndex GSI with range condition:"
aws dynamodb query \
    --table-name MusicLibrary \
    --index-name GenreYearIndex \
    --key-condition-expression "Genre = :genre AND #yr > :year" \
    --expression-attribute-names '{"#yr": "Year"}' \
    --expression-attribute-values '{":genre":{"S":"Rock"},":year":{"N":"1965"}}'
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query)

### MRSC グローバルテーブルの作成と管理
<a name="dynamodb_Scenario_MRSCGlobalTables_bash_2_topic"></a>

次のコード例は、マルチリージョンの強力な整合性 (MRSC) を備えた DynamoDB グローバルテーブルを作成および管理する方法を示しています。
+ マルチリージョンの強力な整合性を備えたテーブルを作成します。
+ MRSC 設定とレプリカのステータスを確認します。
+ 即時読み取りでリージョン間の強力な整合性をテストします。
+ MRSC 保証を使用して条件付き書き込みを実行します。
+ MRSC グローバルテーブルリソースをクリーンアップします。

**AWS CLI Bash スクリプトを使用する**  
マルチリージョンの強力な整合性を備えたテーブルを作成します。  

```
# Step 1: Create a new table in us-east-2 (primary region for MRSC)
# Note: Table must be empty when enabling MRSC
aws dynamodb create-table \
    --table-name MusicTable \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
    --key-schema \
        AttributeName=Artist,KeyType=HASH \
        AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST \
    --region us-east-2

# Wait for table to become active
aws dynamodb wait table-exists --table-name MusicTable --region us-east-2

# Step 2: Add replica and witness with Multi-Region Strong Consistency
# MRSC requires exactly three replicas in supported regions
aws dynamodb update-table \
    --table-name MusicTable \
    --replica-updates '[{"Create": {"RegionName": "us-east-1"}}]' \
    --global-table-witness-updates '[{"Create": {"RegionName": "us-west-2"}}]' \
    --multi-region-consistency STRONG \
    --region us-east-2
```
MRSC 設定とレプリカのステータスを確認します。  

```
# Verify the global table configuration and MRSC setting
aws dynamodb describe-table \
    --table-name MusicTable \
    --region us-east-2 \
    --query 'Table.{TableName:TableName,TableStatus:TableStatus,MultiRegionConsistency:MultiRegionConsistency,Replicas:Replicas[*],GlobalTableWitnesses:GlobalTableWitnesses[*].{Region:RegionName,Status:ReplicaStatus}}'
```
リージョン間の即時読み取りの強力な整合性をテストします。  

```
# Write an item to the primary region
aws dynamodb put-item \
    --table-name MusicTable \
    --item '{"Artist": {"S":"The Beatles"},"SongTitle": {"S":"Hey Jude"},"Album": {"S":"The Beatles 1967-1970"},"Year": {"N":"1968"}}' \
    --region us-east-2

# Read the item from replica region to verify strong consistency (cannot read or write to witness)
# No wait time needed - MRSC provides immediate consistency
echo "Reading from us-east-1 (immediate consistency):"
aws dynamodb get-item \
    --table-name MusicTable \
    --key '{"Artist": {"S":"The Beatles"},"SongTitle": {"S":"Hey Jude"}}' \
    --consistent-read \
    --region us-east-1
```
MRSC 保証を使用して条件付き書き込みを実行します。  

```
# Perform a conditional update from a different region
# This demonstrates that conditions work consistently across all regions
aws dynamodb update-item \
    --table-name MusicTable \
    --key '{"Artist": {"S":"The Beatles"},"SongTitle": {"S":"Hey Jude"}}' \
    --update-expression "SET #rating = :rating" \
    --condition-expression "attribute_exists(Artist)" \
    --expression-attribute-names '{"#rating": "Rating"}' \
    --expression-attribute-values '{":rating": {"N":"5"}}' \
    --region us-east-1
```
MRSC グローバルテーブルリソースをクリーンアップします。  

```
# Remove replica tables (must be done before deleting the primary table)
aws dynamodb update-table \
    --table-name MusicTable \
    --replica-updates '[{"Delete": {"RegionName": "us-east-1"}}]' \
    --global-table-witness-updates '[{"Delete": {"RegionName": "us-west-2"}}]' \
    --region us-east-2

# Wait for replicas to be deleted
echo "Waiting for replicas to be deleted..."
sleep 30

# Delete the primary table
aws dynamodb delete-table \
    --table-name MusicTable \
    --region us-east-2
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)
  + [UpdateItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateItem)
  + [UpdateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateTable)

### グローバルセカンダリインデックスを管理する
<a name="dynamodb_Scenario_GSILifecycle_bash_2_topic"></a>

次のコード例は、グローバルセカンダリインデックスのライフサイクル全体を管理する方法を示しています。
+ グローバルセカンダリインデックスを含むテーブルを作成します。
+ 新しい GSI を既存のテーブルに追加します。
+ GSI ウォームスループットを更新 (増加) します。
+ GSI を使用してデータをクエリします。
+ GSI を削除します。

**AWS CLI Bash スクリプトを使用する**  
グローバルセカンダリインデックスを含むテーブルを作成します。  

```
# Create a table with a GSI
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
        AttributeName=AlbumTitle,AttributeType=S \
    --key-schema \
        AttributeName=Artist,KeyType=HASH \
        AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST \
    --global-secondary-indexes \
        "IndexName=AlbumIndex,\
        KeySchema=[{AttributeName=AlbumTitle,KeyType=HASH}],\
        Projection={ProjectionType=ALL}"
```
新しい (オンデマンド) GSI を既存のテーブルに追加します。  

```
# Add a new GSI to an existing table
aws dynamodb update-table \
    --table-name MusicCollection \
    --attribute-definitions \
        AttributeName=Genre,AttributeType=S \
    --global-secondary-index-updates \
        "[{\"Create\":{\"IndexName\":\"GenreIndex\",\
        \"KeySchema\":[{\"AttributeName\":\"Genre\",\"KeyType\":\"HASH\"}],\
        \"Projection\":{\"ProjectionType\":\"ALL\"}}}]"
```
GSI ウォームスループットを更新 (増加) します。  

```
# Increase the warm throughput of a GSI (default values are 12k reads, 4k writes)
aws dynamodb update-table \
    --table-name MusicCollection \
    --global-secondary-index-updates \
        "[{\"Update\":{\"IndexName\":\"AlbumIndex\",\
        \"WarmThroughput\":{\"ReadUnitsPerSecond\":15000,\"WriteUnitsPerSecond\":6000}}}]"
```
GSI を使用してデータをクエリします。  

```
# Query the AlbumIndex GSI
aws dynamodb query \
    --table-name MusicCollection \
    --index-name AlbumIndex \
    --key-condition-expression "AlbumTitle = :album" \
    --expression-attribute-values '{":album":{"S":"Let It Be"}}'

# Query the GenreIndex GSI
aws dynamodb query \
    --table-name MusicCollection \
    --index-name GenreIndex \
    --key-condition-expression "Genre = :genre" \
    --expression-attribute-values '{":genre":{"S":"Jazz"}}'
```
GSI を削除します。  

```
# Delete a GSI from a table
aws dynamodb update-table \
    --table-name MusicCollection \
    --global-secondary-index-updates \
        "[{\"Delete\":{\"IndexName\":\"GenreIndex\"}}]"
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)
  + [クエリ](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query)
  + [UpdateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateTable)

### リソースベースのポリシーを管理する
<a name="dynamodb_Scenario_ResourcePolicyLifecycle_bash_2_topic"></a>

次のコード例は、DynamoDB テーブルのリソースベースのポリシーのライフサイクル全体を管理する方法を示しています。
+ リソースポリシーを含むテーブルを作成します。
+ リソースポリシーを取得します。
+ リソースポリシーを更新します。
+ リソースポリシーを削除します。

**AWS CLI Bash スクリプトを使用する**  
リソースポリシーを含むテーブルを作成します。  

```
# Step 1: Create a DynamoDB table
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
    --key-schema \
        AttributeName=Artist,KeyType=HASH \
        AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST

# Step 2: Create a resource-based policy document
cat > policy.json << 'EOF'
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:role/DynamoDBReadOnly"
      },
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:BatchGetItem",
        "dynamodb:Query",
        "dynamodb:Scan"
      ],
      "Resource": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection"
    }
  ]
}
EOF

# Step 3: Attach the resource-based policy to the table
aws dynamodb put-resource-policy \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \
    --policy file://policy.json
```
リソースポリシーを取得します。  

```
# Get the resource-based policy attached to a table
aws dynamodb get-resource-policy \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection
```
リソースポリシーを更新します。  

```
# Step 1: Create an updated policy document
cat > updated-policy.json << 'EOF'
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::123456789012:role/DynamoDBReadOnly",
          "arn:aws:iam::123456789012:role/DynamoDBAnalytics"
        ]
      },
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:BatchGetItem",
        "dynamodb:Query",
        "dynamodb:Scan"
      ],
      "Resource": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection"
    }
  ]
}
EOF

# Step 2: Update the resource-based policy on the table
aws dynamodb put-resource-policy \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \
    --policy file://updated-policy.json
```
リソースポリシーを削除します。  

```
# Delete the resource-based policy from a table
aws dynamodb delete-resource-policy \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DeleteResourcePolicy](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteResourcePolicy)
  + [GetResourcePolicy](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetResourcePolicy)
  + [PutResourcePolicy](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutResourcePolicy)

### 属性ベースのアクセス制御を設定する
<a name="dynamodb_Scenario_ABACSetup_bash_2_topic"></a>

次のコード例は、DynamoDB の属性ベースのアクセス制御 (ABAC) を実装する方法を示しています。
+ ABAC の IAM ポリシーを作成します。
+ さまざまな部門のタグを含むテーブルを作成します。
+ タグに基づいてテーブルを一覧表示およびフィルタリングします。

**AWS CLI Bash スクリプトを使用する**  
ABAC の IAM ポリシーを作成します。  

```
# Step 1: Create a policy document for ABAC
cat > abac-policy.json << 'EOF'
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:BatchGetItem",
        "dynamodb:Query",
        "dynamodb:Scan"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Department": "${aws:PrincipalTag/Department}"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:PutItem",
        "dynamodb:UpdateItem",
        "dynamodb:DeleteItem",
        "dynamodb:BatchWriteItem"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Department": "${aws:PrincipalTag/Department}",
          "aws:ResourceTag/Environment": "Development"
        }
      }
    }
  ]
}
EOF

# Step 2: Create the IAM policy
aws iam create-policy \
    --policy-name DynamoDBDepartmentBasedAccess \
    --policy-document file://abac-policy.json
```
さまざまな部門のタグを含むテーブルを作成します。  

```
# Create a DynamoDB table with tags for ABAC
aws dynamodb create-table \
    --table-name FinanceData \
    --attribute-definitions \
        AttributeName=RecordID,AttributeType=S \
    --key-schema \
        AttributeName=RecordID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --tags \
        Key=Department,Value=Finance \
        Key=Environment,Value=Development

# Create another table with different tags
aws dynamodb create-table \
    --table-name MarketingData \
    --attribute-definitions \
        AttributeName=RecordID,AttributeType=S \
    --key-schema \
        AttributeName=RecordID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --tags \
        Key=Department,Value=Marketing \
        Key=Environment,Value=Production
```
タグに基づいてテーブルを一覧表示およびフィルタリングします。  

```
# List all DynamoDB tables
echo "Listing all tables:"
aws dynamodb list-tables

# Get ARNs for all tables
echo -e "\nGetting ARNs for all tables:"
TABLE_ARNS=$(aws dynamodb list-tables --query "TableNames[*]" --output text | xargs -I {} aws dynamodb describe-table --table-name {} --query "Table.TableArn" --output text)

# For each table ARN, list its tags
echo -e "\nListing tags for each table:"
for ARN in $TABLE_ARNS; do
    TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}')
    echo -e "\nTags for table: $TABLE_NAME"
    aws dynamodb list-tags-of-resource --resource-arn $ARN
done

# Example: Find tables with a specific tag
echo -e "\nFinding tables with Environment=Production tag:"
for ARN in $TABLE_ARNS; do
    TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}')
    TAGS=$(aws dynamodb list-tags-of-resource --resource-arn $ARN --query "Tags[?Key=='Environment' && Value=='Production']" --output text)
    if [ ! -z "$TAGS" ]; then
        echo "Table with Production tag: $TABLE_NAME"
    fi
done
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [ListTables](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/ListTables)

### ローカルセカンダリインデックスを操作する
<a name="dynamodb_Scenario_LSIExamples_bash_2_topic"></a>

次のコード例は、ローカルセカンダリインデックスを含むテーブルを作成およびクエリする方法を示しています。
+ ローカルセカンダリインデックス (LSI) を含むテーブルを作成します。
+ 射影タイプが異なる複数の LSI を含むテーブルを作成します。
+ LSI を使用してデータをクエリします。

**AWS CLI Bash スクリプトを使用する**  
ローカルセカンダリインデックスを含むテーブルを作成します。  

```
# Create a table with a Local Secondary Index
aws dynamodb create-table \
    --table-name CustomerOrders \
    --attribute-definitions \
        AttributeName=CustomerID,AttributeType=S \
        AttributeName=OrderID,AttributeType=S \
        AttributeName=OrderDate,AttributeType=S \
    --key-schema \
        AttributeName=CustomerID,KeyType=HASH \
        AttributeName=OrderID,KeyType=RANGE \
    --local-secondary-indexes \
        "IndexName=OrderDateIndex,\
        KeySchema=[{AttributeName=CustomerID,KeyType=HASH},{AttributeName=OrderDate,KeyType=RANGE}],\
        Projection={ProjectionType=ALL}" \
    --billing-mode PAY_PER_REQUEST
```
複数の LSI を含むテーブルを作成します。  

```
# Create a table with multiple Local Secondary Indexes
aws dynamodb create-table \
    --table-name CustomerDetails \
    --attribute-definitions \
        AttributeName=CustomerID,AttributeType=S \
        AttributeName=Name,AttributeType=S \
        AttributeName=Email,AttributeType=S \
        AttributeName=RegistrationDate,AttributeType=S \
    --key-schema \
        AttributeName=CustomerID,KeyType=HASH \
        AttributeName=Name,KeyType=RANGE \
    --local-secondary-indexes \
        "[
            {
                \"IndexName\": \"EmailIndex\",
                \"KeySchema\": [
                    {\"AttributeName\":\"CustomerID\",\"KeyType\":\"HASH\"},
                    {\"AttributeName\":\"Email\",\"KeyType\":\"RANGE\"}
                ],
                \"Projection\": {\"ProjectionType\":\"INCLUDE\",\"NonKeyAttributes\":[\"Address\",\"Phone\"]}
            },
            {
                \"IndexName\": \"RegistrationIndex\",
                \"KeySchema\": [
                    {\"AttributeName\":\"CustomerID\",\"KeyType\":\"HASH\"},
                    {\"AttributeName\":\"RegistrationDate\",\"KeyType\":\"RANGE\"}
                ],
                \"Projection\": {\"ProjectionType\":\"KEYS_ONLY\"}
            }
        ]" \
    --billing-mode PAY_PER_REQUEST
```
LSI を使用してデータをクエリします。  

```
# Query the OrderDateIndex LSI
aws dynamodb query \
    --table-name CustomerOrders \
    --index-name OrderDateIndex \
    --key-condition-expression "CustomerID = :custId AND OrderDate BETWEEN :date1 AND :date2" \
    --expression-attribute-values '{
        ":custId": {"S": "C1"},
        ":date1": {"S": "2023-01-01"},
        ":date2": {"S": "2023-02-01"}
    }'

# Query with a filter expression
aws dynamodb query \
    --table-name CustomerOrders \
    --index-name OrderDateIndex \
    --key-condition-expression "CustomerID = :custId" \
    --filter-expression "Amount > :amount" \
    --expression-attribute-values '{
        ":custId": {"S": "C1"},
        ":amount": {"N": "150"}
    }'
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [クエリ](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/Query)

### Streams と Time-to-Live を操作する
<a name="dynamodb_Scenario_StreamsAndTTL_bash_2_topic"></a>

次のコード例は、DynamoDB Streams 機能と Time-to-Live 機能を管理する方法を示しています。
+ Streams を有効にしてテーブルを作成します。
+ Streams について説明します。
+ Streams を処理する Lambda 関数を作成します。
+ テーブルで TTL を有効にします。
+ TTL 属性を持つ項目を追加します。
+ TTL 設定について説明します。

**AWS CLI Bash スクリプトを使用する**  
Streams を有効にしてテーブルを作成します。  

```
# Create a table with DynamoDB Streams enabled
aws dynamodb create-table \
    --table-name StreamsDemo \
    --attribute-definitions \
        AttributeName=ID,AttributeType=S \
    --key-schema \
        AttributeName=ID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
```
Streams について説明します。  

```
# Get information about the stream
aws dynamodb describe-table \
    --table-name StreamsDemo \
    --query "Table.StreamSpecification"

# Get the stream ARN
STREAM_ARN=$(aws dynamodb describe-table \
    --table-name StreamsDemo \
    --query "Table.LatestStreamArn" \
    --output text)

echo "Stream ARN: $STREAM_ARN"

# Describe the stream
aws dynamodbstreams describe-stream \
    --stream-arn $STREAM_ARN
```
Streams の Lambda 関数を作成します。  

```
# Step 1: Create an IAM role for the Lambda function
cat > trust-policy.json << 'EOF'
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF

aws iam create-role \
    --role-name DynamoDBStreamsLambdaRole \
    --assume-role-policy-document file://trust-policy.json

# Step 2: Attach permissions to the role
aws iam attach-role-policy \
    --role-name DynamoDBStreamsLambdaRole \
    --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole

# Step 3: Create a Lambda function (code would be in a separate file)
echo "Lambda function creation would be done separately with appropriate code"

# Step 4: Create an event source mapping
echo "Example command to create event source mapping:"
echo "aws lambda create-event-source-mapping \\"
echo "    --function-name ProcessDynamoDBRecords \\"
echo "    --event-source $STREAM_ARN \\"
echo "    --batch-size 100 \\"
echo "    --starting-position LATEST"
```
テーブルで TTL を有効にします。  

```
# Create a table for TTL demonstration
aws dynamodb create-table \
    --table-name TTLDemo \
    --attribute-definitions \
        AttributeName=ID,AttributeType=S \
    --key-schema \
        AttributeName=ID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST

# Wait for table to become active
aws dynamodb wait table-exists --table-name TTLDemo

# Enable TTL on the table
aws dynamodb update-time-to-live \
    --table-name TTLDemo \
    --time-to-live-specification "Enabled=true, AttributeName=ExpirationTime"
```
TTL 属性を持つ項目を追加します。  

```
# Calculate expiration time (current time + 1 day in seconds)
EXPIRATION_TIME=$(date -d "+1 day" +%s)

# Add an item with TTL attribute
aws dynamodb put-item \
    --table-name TTLDemo \
    --item '{
        "ID": {"S": "item1"},
        "Data": {"S": "This item will expire in 1 day"},
        "ExpirationTime": {"N": "'$EXPIRATION_TIME'"}
    }'

# Add an item that expires in 1 hour
EXPIRATION_TIME_HOUR=$(date -d "+1 hour" +%s)
aws dynamodb put-item \
    --table-name TTLDemo \
    --item '{
        "ID": {"S": "item2"},
        "Data": {"S": "This item will expire in 1 hour"},
        "ExpirationTime": {"N": "'$EXPIRATION_TIME_HOUR'"}
    }'
```
TTL 設定について説明します。  

```
# Describe TTL settings for a table
aws dynamodb describe-time-to-live \
    --table-name TTLDemo
```
+ API の詳細については、「*AWS CLI コマンドリファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)
  + [DescribeTimeToLive](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTimeToLive)
  + [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)
  + [UpdateTimeToLive](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateTimeToLive)

### グローバルテーブルとマルチリージョンレプリケーションの最終的な一貫性 (MREC) を操作する
<a name="dynamodb_Scenario_MultiRegionReplication_bash_2_topic"></a>

次のコード例は、最終的な一貫性を備えたマルチリージョンレプリケーション (MREC) を使用して DynamoDB グローバルテーブルを管理する方法を示しています。
+ マルチリージョンレプリケーション (MREC)を備えたテーブルを作成します。
+ レプリカテーブルの項目を配置および取得します。
+ レプリカを一つずつ削除します。
+ テーブルを削除してクリーンアップします。

**AWS CLI Bash スクリプトを使用する**  
マルチリージョンレプリケーションを備えたテーブルを作成します。  

```
# Step 1: Create a new table (MusicTable) in US East (Ohio), with DynamoDB Streams enabled (NEW_AND_OLD_IMAGES)
aws dynamodb create-table \
    --table-name MusicTable \
    --attribute-definitions \
        AttributeName=Artist,AttributeType=S \
        AttributeName=SongTitle,AttributeType=S \
    --key-schema \
        AttributeName=Artist,KeyType=HASH \
        AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST \
    --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES \
    --region us-east-2

# Step 2: Create an identical MusicTable table in US East (N. Virginia)
aws dynamodb update-table --table-name MusicTable --cli-input-json \
'{
  "ReplicaUpdates":
  [
    {
      "Create": {
        "RegionName": "us-east-1"
      }
    }
  ]
}' \
--region us-east-2

# Step 3: Create a table in Europe (Ireland)
aws dynamodb update-table --table-name MusicTable --cli-input-json \
'{
  "ReplicaUpdates":
  [
    {
      "Create": {
        "RegionName": "eu-west-1"
      }
    }
  ]
}' \
--region us-east-2
```
マルチリージョンテーブルについて説明します。  

```
# Step 4: View the list of replicas created using describe-table
aws dynamodb describe-table \
    --table-name MusicTable \
    --region us-east-2 \
    --query 'Table.{TableName:TableName,TableStatus:TableStatus,MultiRegionConsistency:MultiRegionConsistency,Replicas:Replicas[*].{Region:RegionName,Status:ReplicaStatus}}'
```
レプリカテーブルに項目を配置します。  

```
# Step 5: To verify that replication is working, add a new item to the Music table in US East (Ohio)
aws dynamodb put-item \
    --table-name MusicTable \
    --item '{"Artist": {"S":"item_1"},"SongTitle": {"S":"Song Value 1"}}' \
    --region us-east-2
```
レプリカテーブルから項目を取得します。  

```
# Step 6: Wait for a few seconds, and then check to see whether the item has been 
# successfully replicated to US East (N. Virginia) and Europe (Ireland)
aws dynamodb get-item \
    --table-name MusicTable \
    --key '{"Artist": {"S":"item_1"},"SongTitle": {"S":"Song Value 1"}}' \
    --region us-east-1

aws dynamodb get-item \
    --table-name MusicTable \
    --key '{"Artist": {"S":"item_1"},"SongTitle": {"S":"Song Value 1"}}' \
    --region eu-west-1
```
レプリカを削除します。  

```
# Step 7: Delete the replica table in Europe (Ireland) Region
aws dynamodb update-table --table-name MusicTable --cli-input-json \
'{
  "ReplicaUpdates":
  [
    {
      "Delete": {
        "RegionName": "eu-west-1"
      }
    }
  ]
}' \
--region us-east-2

# Delete the replica table in US East (N. Virginia) Region
aws dynamodb update-table --table-name MusicTable --cli-input-json \
'{
  "ReplicaUpdates":
  [
    {
      "Delete": {
        "RegionName": "us-east-1"
      }
    }
  ]
}' \
--region us-east-2
```
テーブルを削除してクリーンアップします。  

```
# Clean up: Delete the primary table
aws dynamodb delete-table --table-name MusicTable --region us-east-2

echo "Global table demonstration complete."
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DeleteTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)
  + [UpdateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateTable)

### リソースのタグ付けを操作する
<a name="dynamodb_Scenario_TaggingExamples_bash_2_topic"></a>

次のコード例は、DynamoDB リソースのタグを管理する方法を示しています。
+ タグを含むテーブルを作成します。
+ リソースのタグを一覧表示します。
+ リソースにタグを追加します。
+ リソースからタグを削除します。
+ テーブルをタグでフィルタリングします。

**AWS CLI Bash スクリプトを使用する**  
タグを含むテーブルを作成します。  

```
# Create a table with tags
aws dynamodb create-table \
    --table-name TaggedTable \
    --attribute-definitions \
        AttributeName=ID,AttributeType=S \
    --key-schema \
        AttributeName=ID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --tags \
        Key=Environment,Value=Production \
        Key=Project,Value=Analytics \
        Key=Owner,Value=DataTeam
```
リソースのタグを一覧表示します。  

```
# Get the table ARN
TABLE_ARN=$(aws dynamodb describe-table \
    --table-name TaggedTable \
    --query "Table.TableArn" \
    --output text)

# List tags for the table
aws dynamodb list-tags-of-resource \
    --resource-arn $TABLE_ARN
```
リソースにタグを追加します。  

```
# Add tags to an existing table
aws dynamodb tag-resource \
    --resource-arn $TABLE_ARN \
    --tags \
        Key=CostCenter,Value=12345 \
        Key=BackupSchedule,Value=Daily
```
リソースからタグを削除します。  

```
# Remove tags from a table
aws dynamodb untag-resource \
    --resource-arn $TABLE_ARN \
    --tag-keys Owner BackupSchedule
```
テーブルをタグでフィルタリングします。  

```
# Create another table with different tags
aws dynamodb create-table \
    --table-name AnotherTaggedTable \
    --attribute-definitions \
        AttributeName=ID,AttributeType=S \
    --key-schema \
        AttributeName=ID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --tags \
        Key=Environment,Value=Development \
        Key=Project,Value=Testing

# Wait for table to become active
aws dynamodb wait table-exists --table-name AnotherTaggedTable

# List all tables
echo "All tables:"
aws dynamodb list-tables

# Get ARNs for all tables
echo -e "\nFiltering tables by Environment=Production tag:"
TABLE_ARNS=$(aws dynamodb list-tables --query "TableNames[*]" --output text | xargs -I {} aws dynamodb describe-table --table-name {} --query "Table.TableArn" --output text)

# Find tables with specific tag
for ARN in $TABLE_ARNS; do
    TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}')
    TAGS=$(aws dynamodb list-tags-of-resource --resource-arn $ARN --query "Tags[?Key=='Environment' && Value=='Production']" --output text)
    if [ ! -z "$TAGS" ]; then
        echo "Table with Production tag: $TABLE_NAME"
    fi
done
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [ListTagsOfResource](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/ListTagsOfResource)
  + [TagResource](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/TagResource)
  + [UntagResource](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UntagResource)

### テーブルの暗号化を操作する
<a name="dynamodb_Scenario_EncryptionExamples_bash_2_topic"></a>

次のコード例は、DynamoDB テーブルの暗号化オプションを管理する方法を示しています。
+ デフォルトの暗号化を使用してテーブルを作成します。
+ カスタマーマネージド CMK を使用してテーブルを作成します。
+ テーブルの暗号化設定を更新します。
+ テーブルの暗号化について説明します。

**AWS CLI Bash スクリプトを使用する**  
デフォルトの暗号化を使用してテーブルを作成します。  

```
# Create a table with default encryption (AWS owned key)
aws dynamodb create-table \
    --table-name CustomerData \
    --attribute-definitions \
        AttributeName=CustomerID,AttributeType=S \
    --key-schema \
        AttributeName=CustomerID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --sse-specification Enabled=true,SSEType=KMS
```
カスタマーマネージド CMK を使用してテーブルを作成します。  

```
# Step 1: Create a customer managed key in KMS
aws kms create-key \
    --description "Key for DynamoDB table encryption" \
    --key-usage ENCRYPT_DECRYPT \
    --customer-master-key-spec SYMMETRIC_DEFAULT

# Store the key ID for later use
KEY_ID=$(aws kms list-keys --query "Keys[?contains(KeyArn, 'Key for DynamoDB')].KeyId" --output text)

# Step 2: Create a table with the customer managed key
aws dynamodb create-table \
    --table-name SensitiveData \
    --attribute-definitions \
        AttributeName=RecordID,AttributeType=S \
    --key-schema \
        AttributeName=RecordID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=$KEY_ID
```
テーブルの暗号化を更新します。  

```
# Update a table to use a different KMS key
aws dynamodb update-table \
    --table-name CustomerData \
    --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=$KEY_ID
```
テーブルの暗号化について説明します。  

```
# Describe the table to see encryption settings
aws dynamodb describe-table \
    --table-name CustomerData \
    --query "Table.SSEDescription"
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateKey](https://docs.aws.amazon.com/goto/aws-cli/kms-2014-11-01/CreateKey)
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)
  + [UpdateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateTable)

# Bash スクリプト AWS CLI で を使用する Amazon EC2 の例
<a name="bash_2_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS Command Line Interface で Bash スクリプトで を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
###############################################################################
# function get_started_with_ec2_instances
#
# Runs an interactive scenario that shows how to get started using EC2 instances.
#
#     "EC2 access" permissions are needed to run this code.
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function get_started_with_ec2_instances() {
  # Requires version 4 for mapfile.
  local required_version=4.0

  # Get the current Bash version
  # Check if BASH_VERSION is set
  local current_version
  if [[ -n "$BASH_VERSION" ]]; then
    # Convert BASH_VERSION to a number for comparison
    current_version=$BASH_VERSION
  else
    # Get the current Bash version using the bash command
    current_version=$(bash --version | head -n 1 | awk '{ print $4 }')
  fi

  # Convert version strings to numbers for comparison
  local required_version_num current_version_num
  required_version_num=$(echo "$required_version" | awk -F. '{ print ($1 * 10000) + ($2 * 100) + $3 }')
  current_version_num=$(echo "$current_version" | awk -F. '{ print ($1 * 10000) + ($2 * 100) + $3 }')

  # Compare versions
  if ((current_version_num < required_version_num)); then
    echo "Error: This script requires Bash version $required_version or higher."
    echo "Your current Bash version is number is $current_version."
    exit 1
  fi

  {
    if [ "$EC2_OPERATIONS_SOURCED" != "True" ]; then

      source ./ec2_operations.sh
    fi
  }

  echo_repeat "*" 88
  echo "Welcome to the Amazon Elastic Compute Cloud (Amazon EC2) get started with instances demo."
  echo_repeat "*" 88
  echo

  echo "Let's create an RSA key pair that you can be use to securely connect to "
  echo "your EC2 instance."

  echo -n "Enter a unique name for your key: "
  get_input
  local key_name
  key_name=$get_input_result

  local temp_dir
  temp_dir=$(mktemp -d)
  local key_file_name="$temp_dir/${key_name}.pem"

  if ec2_create_keypair -n "${key_name}" -f "${key_file_name}"; then
    echo "Created a key pair $key_name and saved the private key to $key_file_name"
    echo
  else
    errecho "The key pair failed to create. This demo will exit."
    return 1
  fi

  chmod 400 "${key_file_name}"

  if yes_no_input "Do you want to list some of your key pairs? (y/n) "; then
    local keys_and_fingerprints
    keys_and_fingerprints="$(ec2_describe_key_pairs)" && {
      local image_name_and_id
      while IFS=$'\n' read -r image_name_and_id; do
        local entries
        IFS=$'\t' read -ra entries <<<"$image_name_and_id"
        echo "Found rsa key ${entries[0]} with fingerprint:"
        echo "     ${entries[1]}"
      done <<<"$keys_and_fingerprints"

    }
  fi

  echo_repeat "*" 88
  echo_repeat "*" 88

  echo "Let's create a security group to manage access to your instance."
  echo -n "Enter a unique name for your security group: "
  get_input
  local security_group_name
  security_group_name=$get_input_result
  local security_group_id
  security_group_id=$(ec2_create_security_group -n "$security_group_name" \
    -d "Security group for EC2 instance") || {
    errecho "The security failed to create. This demo will exit."
    clean_up "$key_name" "$key_file_name"
    return 1
  }

  echo "Security group created with ID $security_group_id"
  echo

  local public_ip
  public_ip=$(curl -s http://checkip.amazonaws.com)

  echo "Let's add a rule to allow SSH only from your current IP address."
  echo "Your public IP address is $public_ip"
  echo -n "press return to add this rule to your security group."
  get_input

  if ! ec2_authorize_security_group_ingress -g "$security_group_id" -i "$public_ip" -p tcp -f 22 -t 22; then
    errecho "The security group rules failed to update. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id"
    return 1
  fi

  echo "Security group rules updated"

  local security_group_description
  security_group_description="$(ec2_describe_security_groups -g "${security_group_id}")" || {
    errecho "Failed to describe security groups. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id"
    return 1
  }

  mapfile -t parameters <<<"$security_group_description"
  IFS=$'\t' read -ra entries <<<"${parameters[0]}"
  echo "Security group: ${entries[0]}"
  echo "    ID: ${entries[1]}"
  echo "    VPC: ${entries[2]}"
  echo "Inbound permissions:"
  IFS=$'\t' read -ra entries <<<"${parameters[1]}"
  echo "    IpProtocol: ${entries[0]}"
  echo "    FromPort: ${entries[1]}"
  echo "    ToPort: ${entries[2]}"
  echo "    CidrIp: ${parameters[2]}"

  local parameters
  parameters="$(ssm_get_parameters_by_path -p "/aws/service/ami-amazon-linux-latest")" || {
    errecho "Failed to get parameters. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id"
    return 1

  }

  local image_ids=""
  mapfile -t parameters <<<"$parameters"
  for image_name_and_id in "${parameters[@]}"; do
    IFS=$'\t' read -ra values <<<"$image_name_and_id"
    if [[ "${values[0]}" == *"amzn2"* ]]; then
      image_ids+="${values[1]} "
    fi
  done

  local images
  images="$(ec2_describe_images -i "$image_ids")" || {
    errecho "Failed to describe images. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id"
    return 1

  }

  new_line_and_tab_to_list "$images"
  local images=("${list_result[@]}")

  # Get the size of the array
  local images_count=${#images[@]}

  if ((images_count == 0)); then
    errecho "No images found. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id"
    return 1
  fi

  echo_repeat "*" 88
  echo_repeat "*" 88

  echo "Let's create an instance from an Amazon Linux 2 AMI. Here are some options:"
  for ((i = 0; i < images_count; i += 3)); do
    echo "$(((i / 3) + 1)) - ${images[$i]}"
  done

  integer_input "Please enter the number of the AMI you want to use: " 1 "$((images_count / 3))"
  local choice=$get_input_result
  choice=$(((choice - 1) * 3))

  echo "Great choice."
  echo

  local architecture=${images[$((choice + 1))]}
  local image_id=${images[$((choice + 2))]}
  echo "Here are some instance types that support the ${architecture} architecture of the image:"
  response="$(ec2_describe_instance_types -a "${architecture}" -t "*.micro,*.small")" || {
    errecho "Failed to describe instance types. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id"
    return 1
  }

  local instance_types
  mapfile -t instance_types <<<"$response"

  # Get the size of the array
  local instance_types_count=${#instance_types[@]}

  echo "Here are some options:"
  for ((i = 0; i < instance_types_count; i++)); do
    echo "$((i + 1)) - ${instance_types[$i]}"
  done

  integer_input "Which one do you want to use? " 1 "${#instance_types[@]}
"
  choice=$get_input_result
  local instance_type=${instance_types[$((choice - 1))]}
  echo "Another great choice."
  echo

  echo "Creating your instance and waiting for it to start..."
  local instance_id
  instance_id=$(ec2_run_instances -i "$image_id" -t "$instance_type" -k "$key_name" -s "$security_group_id") || {
    errecho "Failed to run instance. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id"
    return 1
  }

  ec2_wait_for_instance_running -i "$instance_id"
  echo "Your instance is ready:"
  echo

  local instance_details
  instance_details="$(ec2_describe_instances -i "${instance_id}")"

  echo
  print_instance_details "${instance_details}"

  local public_ip
  public_ip=$(echo "${instance_details}" | awk '{print $6}')
  echo
  echo "You can use SSH to connect to your instance"
  echo "If the connection attempt times out, you might have to manually update the SSH ingress rule"
  echo "for your IP address in the AWS Management Console."
  connect_to_instance "$key_file_name" "$public_ip"

  echo -n "Press Enter when you're ready to continue the demo: "
  get_input

  echo_repeat "*" 88
  echo_repeat "*" 88

  echo "Let's stop and start your instance to see what changes."
  echo "Stopping your instance and waiting until it's stopped..."
  ec2_stop_instances -i "$instance_id"
  ec2_wait_for_instance_stopped -i "$instance_id"

  echo "Your instance is stopped. Restarting..."

  ec2_start_instances -i "$instance_id"
  ec2_wait_for_instance_running -i "$instance_id"

  echo "Your instance is running again."
  local instance_details
  instance_details="$(ec2_describe_instances -i "${instance_id}")"

  print_instance_details "${instance_details}"

  public_ip=$(echo "${instance_details}" | awk '{print $6}')

  echo "Every time your instance is restarted, its public IP address changes"
  connect_to_instance "$key_file_name" "$public_ip"

  echo -n "Press Enter when you're ready to continue the demo: "
  get_input

  echo_repeat "*" 88
  echo_repeat "*" 88

  echo "You can allocate an Elastic IP address and associate it with your instance"
  echo "to keep a consistent IP address even when your instance restarts."

  local result
  result=$(ec2_allocate_address -d vpc) || {
    errecho "Failed to allocate an address. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id" "$instance_id"
    return 1
  }

  local elastic_ip allocation_id
  elastic_ip=$(echo "$result" | awk '{print $1}')
  allocation_id=$(echo "$result" | awk '{print $2}')

  echo "Allocated static Elastic IP address: $elastic_ip"

  local association_id
  association_id=$(ec2_associate_address -i "$instance_id" -a "$allocation_id") || {
    errecho "Failed to associate an address. This demo will exit."
    clean_up "$key_name" "$key_file_name" "$security_group_id" "$instance_id" "$allocation_id"
    return 1
  }

  echo "Associated your Elastic IP with your instance."
  echo "You can now use SSH to connect to your instance by using the Elastic IP."
  connect_to_instance "$key_file_name" "$elastic_ip"

  echo -n "Press Enter when you're ready to continue the demo: "
  get_input

  echo_repeat "*" 88
  echo_repeat "*" 88

  echo "Let's stop and start your instance to see what changes."
  echo "Stopping your instance and waiting until it's stopped..."
  ec2_stop_instances -i "$instance_id"
  ec2_wait_for_instance_stopped -i "$instance_id"

  echo "Your instance is stopped. Restarting..."

  ec2_start_instances -i "$instance_id"
  ec2_wait_for_instance_running -i "$instance_id"

  echo "Your instance is running again."
  local instance_details
  instance_details="$(ec2_describe_instances -i "${instance_id}")"

  print_instance_details "${instance_details}"

  echo "Because you have associated an Elastic IP with your instance, you can"
  echo "connect by using a consistent IP address after the instance restarts."
  connect_to_instance "$key_file_name" "$elastic_ip"

  echo -n "Press Enter when you're ready to continue the demo: "
  get_input

  echo_repeat "*" 88
  echo_repeat "*" 88

  if yes_no_input "Do you want to delete the resources created in this demo: (y/n) "; then
    clean_up "$key_name" "$key_file_name" "$security_group_id" "$instance_id" \
      "$allocation_id" "$association_id"
  else
    echo "The following resources were not deleted."
    echo "Key pair: $key_name"
    echo "Key file: $key_file_name"
    echo "Security group: $security_group_id"
    echo "Instance: $instance_id"
    echo "Elastic IP address: $elastic_ip"
  fi
}

###############################################################################
# function clean_up
#
# This function cleans up the created resources.
#     $1 - The name of the ec2 key pair to delete.
#     $2 - The name of the key file to delete.
#     $3 - The ID of the security group to delete.
#     $4 - The ID of the instance to terminate.
#     $5 - The ID of the elastic IP address to release.
#     $6 - The ID of the elastic IP address to disassociate.
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function clean_up() {
  local result=0
  local key_pair_name=$1
  local key_file_name=$2
  local security_group_id=$3
  local instance_id=$4
  local allocation_id=$5
  local association_id=$6

  if [ -n "$association_id" ]; then
    # bashsupport disable=BP2002
    if (ec2_disassociate_address -a "$association_id"); then
      echo "Disassociated elastic IP address with ID $association_id"
    else
      errecho "The elastic IP address disassociation failed."
      result=1
    fi
  fi

  if [ -n "$allocation_id" ]; then
    # bashsupport disable=BP2002
    if (ec2_release_address -a "$allocation_id"); then
      echo "Released elastic IP address with ID $allocation_id"
    else
      errecho "The elastic IP address release failed."
      result=1
    fi
  fi

  if [ -n "$instance_id" ]; then
    # bashsupport disable=BP2002
    if (ec2_terminate_instances -i "$instance_id"); then
      echo "Started terminating instance with ID $instance_id"

      ec2_wait_for_instance_terminated -i "$instance_id"
    else
      errecho "The instance terminate failed."
      result=1
    fi
  fi

  if [ -n "$security_group_id" ]; then
    # bashsupport disable=BP2002
    if (ec2_delete_security_group -i "$security_group_id"); then
      echo "Deleted security group with ID $security_group_id"
    else
      errecho "The security group delete failed."
      result=1
    fi
  fi

  if [ -n "$key_pair_name" ]; then
    # bashsupport disable=BP2002
    if (ec2_delete_keypair -n "$key_pair_name"); then
      echo "Deleted key pair named $key_pair_name"
    else
      errecho "The key pair delete failed."
      result=1
    fi
  fi

  if [ -n "$key_file_name" ]; then
    rm -f "$key_file_name"
  fi

  return $result
}

###############################################################################
# function ssm_get_parameters_by_path
#
# This function retrieves one or more parameters from the AWS Systems Manager Parameter Store
# by specifying a parameter path.
#
# Parameters:
#       -p parameter_path - The path of the parameter(s) to retrieve.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ssm_get_parameters_by_path() {
  local parameter_path response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ssm_get_parameters_by_path"
    echo "Retrieves one or more parameters from the AWS Systems Manager Parameter Store by specifying a parameter path."
    echo "  -p parameter_path - The path of the parameter(s) to retrieve."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "p:h" option; do
    case "${option}" in
      p) parameter_path="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$parameter_path" ]]; then
    errecho "ERROR: You must provide a parameter path with the -p parameter."
    usage
    return 1
  fi

  response=$(aws ssm get-parameters-by-path \
    --path "$parameter_path" \
    --query "Parameters[*].[Name, Value]" \
    --output text) || {
    aws_cli_error_log $?
    errecho "ERROR: AWS reports get-parameters-by-path operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}

###############################################################################
# function print_instance_details
#
# This function prints the details of an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       instance_details - The instance details in the format "InstanceId ImageId InstanceType KeyName VpcId PublicIpAddress State.Name".
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function print_instance_details() {
  local instance_details="$1"

  if [[ -z "${instance_details}" ]]; then
    echo "Error: Missing required instance details argument."
    return 1
  fi

  local instance_id image_id instance_type key_name vpc_id public_ip state
  instance_id=$(echo "${instance_details}" | awk '{print $1}')
  image_id=$(echo "${instance_details}" | awk '{print $2}')
  instance_type=$(echo "${instance_details}" | awk '{print $3}')
  key_name=$(echo "${instance_details}" | awk '{print $4}')
  vpc_id=$(echo "${instance_details}" | awk '{print $5}')
  public_ip=$(echo "${instance_details}" | awk '{print $6}')
  state=$(echo "${instance_details}" | awk '{print $7}')

  echo "    ID: ${instance_id}"
  echo "    Image ID: ${image_id}"
  echo "    Instance type: ${instance_type}"
  echo "    Key name: ${key_name}"
  echo "    VPC ID: ${vpc_id}"
  echo "    Public IP: ${public_ip}"
  echo "    State: ${state}"

  return 0
}

###############################################################################
# function connect_to_instance
#
# This function displays the public IP address of an Amazon Elastic Compute Cloud (Amazon EC2) instance and prompts the user to connect to the instance via SSH.
#
# Parameters:
#       $1 - The name of the key file used to connect to the instance.
#       $2 - The public IP address of the instance.
#
# Returns:
#       None
###############################################################################
function connect_to_instance() {
  local key_file_name="$1"
  local public_ip="$2"

  # Validate the input parameters
  if [[ -z "$key_file_name" ]]; then
    echo "ERROR: You must provide a key file name as the first argument." >&2
    return 1
  fi

  if [[ -z "$public_ip" ]]; then
    echo "ERROR: You must provide a public IP address as the second argument." >&2
    return 1
  fi

  # Display the public IP address and connection command
  echo "To connect, run the following command:"
  echo "    ssh -i ${key_file_name} ec2-user@${public_ip}"

  # Prompt the user to connect to the instance
  if yes_no_input "Do you want to connect now? (y/n) "; then
    echo "After you have connected, you can return to this example by typing 'exit'"
    ssh -i "${key_file_name}" ec2-user@"${public_ip}"
  fi
}

###############################################################################
# function get_input
#
# This function gets user input from the command line.
#
# Outputs:
#   User input to stdout.
#
# Returns:
#       0
###############################################################################
function get_input() {

  if [ -z "${mock_input+x}" ]; then
    read -r get_input_result
  else

    if [ "$mock_input_array_index" -lt ${#mock_input_array[@]} ]; then
      get_input_result="${mock_input_array[$mock_input_array_index]}"
      # bashsupport disable=BP2001
      # shellcheck disable=SC2206
      ((mock_input_array_index++))
      echo -n "$get_input_result"
    else
      echo "MOCK_INPUT_ARRAY has no more elements" 1>&2
      return 1
    fi
  fi

  return 0
}

###############################################################################
# function yes_no_input
#
# This function requests a yes/no answer from the user, following to a prompt.
#
# Parameters:
#       $1 - The prompt.
#
# Returns:
#       0 - If yes.
#       1 - If no.
###############################################################################
function yes_no_input() {
  if [ -z "$1" ]; then
    echo "Internal error yes_no_input"
    return 1
  fi

  local index=0
  local response="N"
  while [[ $index -lt 10 ]]; do
    index=$((index + 1))
    echo -n "$1"
    if ! get_input; then
      return 1
    fi
    response=$(echo "$get_input_result" | tr '[:upper:]' '[:lower:]')
    if [ "$response" = "y" ] || [ "$response" = "n" ]; then
      break
    else
      echo -e "\nPlease enter or 'y' or 'n'."
    fi
  done

  echo

  if [ "$response" = "y" ]; then
    return 0
  else
    return 1
  fi
}

###############################################################################
# function integer_input
#
# This function prompts the user to enter an integer within a specified range
# and validates the input.
#
# Parameters:
#       $1 - The prompt message to display to the user.
#       $2 - The minimum value of the accepted range.
#       $3 - The maximum value of the accepted range.
#
# Returns:
#       The valid integer input from the user.
#       If the input is invalid or out of range, the function will continue
#       prompting the user until a valid input is provided.
###############################################################################
function integer_input() {
  local prompt="$1"
  local min_value="$2"
  local max_value="$3"
  local input=""

  while true; do
    # Display the prompt message and wait for user input
    echo -n "$prompt"

    if ! get_input; then
      return 1
    fi

    input="$get_input_result"

    # Check if the input is a valid integer
    if [[ "$input" =~ ^-?[0-9]+$ ]]; then
      # Check if the input is within the specified range
      if ((input >= min_value && input <= max_value)); then
        return 0
      else
        echo "Error: Input, $input, must be between $min_value and $max_value."
      fi
    else
      echo "Error: Invalid input- $input. Please enter an integer."
    fi
  done
}
###############################################################################
# function new_line_and_tab_to_list
#
# This function takes a string input containing newlines and tabs, and
# converts it into a list (array) of elements.
#
# Parameters:
#       $1 - The input string containing newlines and tabs.
#
# Returns:
#       The resulting list (array) is stored in the global variable
#       'list_result'.
###############################################################################
function new_line_and_tab_to_list() {
  local input=$1
  export list_result

  list_result=()
  mapfile -t lines <<<"$input"
  local line
  for line in "${lines[@]}"; do
    IFS=$'\t' read -ra parameters <<<"$line"
    list_result+=("${parameters[@]}")
  done
}

###############################################################################
# function echo_repeat
#
# This function prints a string 'n' times to stdout.
#
# Parameters:
#       $1 - The string.
#       $2 - Number of times to print the string.
#
# Outputs:
#   String 'n' times to stdout.
#
# Returns:
#       0
###############################################################################
function echo_repeat() {
  local end=$2
  for ((i = 0; i < end; i++)); do
    echo -n "$1"
  done
  echo
}
```
このシナリオで使用される DynamoDB 関数。  

```
###############################################################################
# function ec2_create_keypair
#
# This function creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair
# and writes it to a file.
#
# Parameters:
#       -n key_pair_name - A key pair name.
#       -f file_path - File to store the key pair.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_create_keypair() {
  local key_pair_name file_path response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_create_keypair"
    echo "Creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair"
    echo " and writes it to a file."
    echo "  -n key_pair_name - A key pair name."
    echo "  -f file_path - File to store the key pair."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:f:h" option; do
    case "${option}" in
      n) key_pair_name="${OPTARG}" ;;
      f) file_path="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$file_path" ]]; then
    errecho "ERROR: You must provide a file path with the -f parameter."
    usage
    return 1
  fi

  response=$(aws ec2 create-key-pair \
    --key-name "$key_pair_name" \
    --query 'KeyMaterial' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  }

  if [[ -n "$file_path" ]]; then
    echo "$response" >"$file_path"
  fi

  return 0
}

###############################################################################
# function ec2_describe_key_pairs
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs.
#
# Parameters:
#       -h - Display help.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_key_pairs() {
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_key_pairs"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "h" option; do
    case "${option}" in
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local response

  response=$(aws ec2 describe-key-pairs \
    --query 'KeyPairs[*].[KeyName, KeyFingerprint]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-key-pairs operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}

###############################################################################
# function ec2_create_security_group
#
# This function creates an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -n security_group_name - The name of the security group.
#       -d security_group_description - The description of the security group.
#
# Returns:
#       The ID of the created security group, or an error message if the operation fails.
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_create_security_group() {
  local security_group_name security_group_description response

  # Function to display usage information
  function usage() {
    echo "function ec2_create_security_group"
    echo "Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -n security_group_name - The name of the security group."
    echo "  -d security_group_description - The description of the security group."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "n:d:h" option; do
    case "${option}" in
      n) security_group_name="${OPTARG}" ;;
      d) security_group_description="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$security_group_name" ]]; then
    errecho "ERROR: You must provide a security group name with the -n parameter."
    return 1
  fi

  if [[ -z "$security_group_description" ]]; then
    errecho "ERROR: You must provide a security group description with the -d parameter."
    return 1
  fi

  # Create the security group
  response=$(aws ec2 create-security-group \
    --group-name "$security_group_name" \
    --description "$security_group_description" \
    --query "GroupId" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports create-security-group operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}

###############################################################################
# function ec2_describe_security_groups
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups.
#
# Parameters:
#       -g security_group_id - The ID of the security group to describe (optional).
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_security_groups() {
  local security_group_id response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_security_groups"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups."
    echo "  -g security_group_id - The ID of the security group to describe (optional)."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "g:h" option; do
    case "${option}" in
      g) security_group_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local query="SecurityGroups[*].[GroupName, GroupId, VpcId, IpPermissions[*].[IpProtocol, FromPort, ToPort, IpRanges[*].CidrIp]]"

  if [[ -n "$security_group_id" ]]; then
    response=$(aws ec2 describe-security-groups --group-ids "$security_group_id" --query "${query}" --output text)
  else
    response=$(aws ec2 describe-security-groups --query "${query}" --output text)
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports describe-security-groups operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function ec2_authorize_security_group_ingress
#
# This function authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -g security_group_id - The ID of the security group.
#       -i ip_address - The IP address or CIDR block to authorize.
#       -p protocol - The protocol to authorize (e.g., tcp, udp, icmp).
#       -f from_port - The start of the port range to authorize.
#       -t to_port - The end of the port range to authorize.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_authorize_security_group_ingress() {
  local security_group_id ip_address protocol from_port to_port response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_authorize_security_group_ingress"
    echo "Authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -g security_group_id - The ID of the security group."
    echo "  -i ip_address - The IP address or CIDR block to authorize."
    echo "  -p protocol - The protocol to authorize (e.g., tcp, udp, icmp)."
    echo "  -f from_port - The start of the port range to authorize."
    echo "  -t to_port - The end of the port range to authorize."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "g:i:p:f:t:h" option; do
    case "${option}" in
      g) security_group_id="${OPTARG}" ;;
      i) ip_address="${OPTARG}" ;;
      p) protocol="${OPTARG}" ;;
      f) from_port="${OPTARG}" ;;
      t) to_port="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -g parameter."
    usage
    return 1
  fi

  if [[ -z "$ip_address" ]]; then
    errecho "ERROR: You must provide an IP address or CIDR block with the -i parameter."
    usage
    return 1
  fi

  if [[ -z "$protocol" ]]; then
    errecho "ERROR: You must provide a protocol with the -p parameter."
    usage
    return 1
  fi

  if [[ -z "$from_port" ]]; then
    errecho "ERROR: You must provide a start port with the -f parameter."
    usage
    return 1
  fi

  if [[ -z "$to_port" ]]; then
    errecho "ERROR: You must provide an end port with the -t parameter."
    usage
    return 1
  fi

  response=$(aws ec2 authorize-security-group-ingress \
    --group-id "$security_group_id" \
    --cidr "${ip_address}/32" \
    --protocol "$protocol" \
    --port "$from_port-$to_port" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports authorize-security-group-ingress operation failed.$response"
    return 1
  }

  return 0
}

###############################################################################
# function ec2_describe_images
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images.
#
# Parameters:
#       -i image_ids - A space-separated  list of image IDs (optional).
#       -h - Display help.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_images() {
  local image_ids response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_images"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images."
    echo "  -i image_ids - A space-separated list of image IDs (optional)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) image_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local aws_cli_args=()

  if [[ -n "$image_ids" ]]; then
    # shellcheck disable=SC2206
    aws_cli_args+=("--image-ids" $image_ids)
  fi

  response=$(aws ec2 describe-images \
    "${aws_cli_args[@]}" \
    --query 'Images[*].[Description,Architecture,ImageId]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-images operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}

###############################################################################
# ec2_describe_instance_types
#
# This function describes EC2 instance types filtered by processor architecture
# and optionally by instance type. It takes the following arguments:
#
# -a, --architecture ARCHITECTURE  Specify the processor architecture (e.g., x86_64)
# -t, --type INSTANCE_TYPE         Comma-separated list of instance types (e.g., t2.micro)
# -h, --help                       Show the usage help
#
# The function prints the instance type and supported architecture for each
# matching instance type.
###############################################################################
function ec2_describe_instance_types() {
  local architecture=""
  local instance_types=""

  # bashsupport disable=BP5008
  function usage() {
    echo "Usage: ec2_describe_instance_types [-a|--architecture ARCHITECTURE] [-t|--type INSTANCE_TYPE] [-h|--help]"
    echo "  -a, --architecture ARCHITECTURE  Specify the processor architecture (e.g., x86_64)"
    echo "  -t, --type INSTANCE_TYPE         Comma-separated list of instance types (e.g., t2.micro)"
    echo "  -h, --help                       Show this help message"
  }

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -a | --architecture)
        architecture="$2"
        shift 2
        ;;
      -t | --type)
        instance_types="$2"
        shift 2
        ;;
      -h | --help)
        usage
        return 0
        ;;
      *)
        echo "Unknown argument: $1"
        return 1
        ;;
    esac
  done

  if [[ -z "$architecture" ]]; then
    errecho "Error: Architecture not specified."
    usage
    return 1
  fi

  if [[ -z "$instance_types" ]]; then
    errecho "Error: Instance type not specified."
    usage
    return 1
  fi

  local tmp_json_file="temp_ec2.json"
  echo -n '[
    {
      "Name": "processor-info.supported-architecture",
      "Values": [' >"$tmp_json_file"

  local items
  IFS=',' read -ra items <<<"$architecture"
  local array_size
  array_size=${#items[@]}
  for i in $(seq 0 $((array_size - 1))); do
    echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file"
    if [[ $i -lt $((array_size - 1)) ]]; then
      echo -n ',' >>"$tmp_json_file"
    fi
  done
  echo -n ']},
    {
    "Name": "instance-type",
      "Values": [' >>"$tmp_json_file"
  IFS=',' read -ra items <<<"$instance_types"
  local array_size
  array_size=${#items[@]}
  for i in $(seq 0 $((array_size - 1))); do
    echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file"
    if [[ $i -lt $((array_size - 1)) ]]; then
      echo -n ',' >>"$tmp_json_file"
    fi
  done

  echo -n ']}]' >>"$tmp_json_file"

  local response
  response=$(aws ec2 describe-instance-types --filters file://"$tmp_json_file" \
    --query 'InstanceTypes[*].[InstanceType]' --output text)

  local error_code=$?

  rm "$tmp_json_file"

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    echo "ERROR: AWS reports describe-instance-types operation failed."
    return 1
  fi

  echo "$response"
  return 0
}

###############################################################################
# function ec2_run_instances
#
# This function launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i image_id - The ID of the Amazon Machine Image (AMI) to use.
#       -t instance_type - The instance type to use (e.g., t2.micro).
#       -k key_pair_name - The name of the key pair to use.
#       -s security_group_id - The ID of the security group to use.
#       -c count - The number of instances to launch (default: 1).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_run_instances() {
  local image_id instance_type key_pair_name security_group_id count response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_run_instances"
    echo "Launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i image_id - The ID of the Amazon Machine Image (AMI) to use."
    echo "  -t instance_type - The instance type to use (e.g., t2.micro)."
    echo "  -k key_pair_name - The name of the key pair to use."
    echo "  -s security_group_id - The ID of the security group to use."
    echo "  -c count - The number of instances to launch (default: 1)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:t:k:s:c:h" option; do
    case "${option}" in
      i) image_id="${OPTARG}" ;;
      t) instance_type="${OPTARG}" ;;
      k) key_pair_name="${OPTARG}" ;;
      s) security_group_id="${OPTARG}" ;;
      c) count="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$image_id" ]]; then
    errecho "ERROR: You must provide an Amazon Machine Image (AMI) ID with the -i parameter."
    usage
    return 1
  fi

  if [[ -z "$instance_type" ]]; then
    errecho "ERROR: You must provide an instance type with the -t parameter."
    usage
    return 1
  fi

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key pair name with the -k parameter."
    usage
    return 1
  fi

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -s parameter."
    usage
    return 1
  fi

  if [[ -z "$count" ]]; then
    count=1
  fi

  response=$(aws ec2 run-instances \
    --image-id "$image_id" \
    --instance-type "$instance_type" \
    --key-name "$key_pair_name" \
    --security-group-ids "$security_group_id" \
    --count "$count" \
    --query 'Instances[*].[InstanceId]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports run-instances operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}

###############################################################################
# function ec2_describe_instances
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID of the instance to describe (optional).
#       -q query - The query to filter the response (optional).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_instances() {
  local instance_id query response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_instances"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID of the instance to describe (optional)."
    echo "  -q query - The query to filter the response (optional)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:q:h" option; do
    case "${option}" in
      i) instance_id="${OPTARG}" ;;
      q) query="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local aws_cli_args=()

  if [[ -n "$instance_id" ]]; then
    # shellcheck disable=SC2206
    aws_cli_args+=("--instance-ids" $instance_id)
  fi

  local query_arg=""
  if [[ -n "$query" ]]; then
    query_arg="--query '$query'"
  else
    query_arg="--query Reservations[*].Instances[*].[InstanceId,ImageId,InstanceType,KeyName,VpcId,PublicIpAddress,State.Name]"
  fi

  # shellcheck disable=SC2086
  response=$(aws ec2 describe-instances \
    "${aws_cli_args[@]}" \
    $query_arg \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-instances operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}

###############################################################################
# function ec2_stop_instances
#
# This function stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID(s) of the instance(s) to stop (comma-separated).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_stop_instances() {
  local instance_ids
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_stop_instances"
    echo "Stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID(s) of the instance(s) to stop (comma-separated)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$instance_ids" ]]; then
    errecho "ERROR: You must provide one or more instance IDs with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 stop-instances \
    --instance-ids "${instance_ids}") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports stop-instances operation failed with $response."
    return 1
  }

  return 0
}

###############################################################################
# function ec2_start_instances
#
# This function starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID(s) of the instance(s) to start (comma-separated).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_start_instances() {
  local instance_ids
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_start_instances"
    echo "Starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID(s) of the instance(s) to start (comma-separated)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$instance_ids" ]]; then
    errecho "ERROR: You must provide one or more instance IDs with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 start-instances \
    --instance-ids "${instance_ids}") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports start-instances operation failed with $response."
    return 1
  }

  return 0
}

###############################################################################
# function ec2_allocate_address
#
# This function allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region.
#
# Parameters:
#       -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard').
#
# Returns:
#       The allocated Elastic IP address, or an error message if the operation fails.
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_allocate_address() {
  local domain response

  # Function to display usage information
  function usage() {
    echo "function ec2_allocate_address"
    echo "Allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region."
    echo "  -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard')."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "d:h" option; do
    case "${option}" in
      d) domain="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$domain" ]]; then
    errecho "ERROR: You must provide a domain with the -d parameter (either 'vpc' or 'standard')."
    return 1
  fi

  if [[ "$domain" != "vpc" && "$domain" != "standard" ]]; then
    errecho "ERROR: Invalid domain value. Must be either 'vpc' or 'standard'."
    return 1
  fi

  # Allocate the Elastic IP address
  response=$(aws ec2 allocate-address \
    --domain "$domain" \
    --query "[PublicIp,AllocationId]" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports allocate-address operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}

###############################################################################
# function ec2_associate_address
#
# This function associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a allocation_id - The allocation ID of the Elastic IP address to associate.
#       -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_associate_address() {
  local allocation_id instance_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_associate_address"
    echo "Associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a allocation_id - The allocation ID of the Elastic IP address to associate."
    echo "  -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:i:h" option; do
    case "${option}" in
      a) allocation_id="${OPTARG}" ;;
      i) instance_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$allocation_id" ]]; then
    errecho "ERROR: You must provide an allocation ID with the -a parameter."
    return 1
  fi

  if [[ -z "$instance_id" ]]; then
    errecho "ERROR: You must provide an instance ID with the -i parameter."
    return 1
  fi

  # Associate the Elastic IP address
  response=$(aws ec2 associate-address \
    --allocation-id "$allocation_id" \
    --instance-id "$instance_id" \
    --query "AssociationId" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports associate-address operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}

###############################################################################
# function ec2_disassociate_address
#
# This function disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a association_id - The association ID that represents the association of the Elastic IP address with an instance.
#
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_disassociate_address() {
  local association_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_disassociate_address"
    echo "Disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a association_id - The association ID that represents the association of the Elastic IP address with an instance."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:h" option; do
    case "${option}" in
      a) association_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$association_id" ]]; then
    errecho "ERROR: You must provide an association ID with the -a parameter."
    return 1
  fi

  response=$(aws ec2 disassociate-address \
    --association-id "$association_id") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports disassociate-address operation failed."
    errecho "$response"
    return 1
  }

  return 0
}

###############################################################################
# function ec2_release_address
#
# This function releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a allocation_id - The allocation ID of the Elastic IP address to release.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_release_address() {
  local allocation_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_release_address"
    echo "Releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a allocation_id - The allocation ID of the Elastic IP address to release."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:h" option; do
    case "${option}" in
      a) allocation_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$allocation_id" ]]; then
    errecho "ERROR: You must provide an allocation ID with the -a parameter."
    return 1
  fi

  response=$(aws ec2 release-address \
    --allocation-id "$allocation_id") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports release-address operation failed."
    errecho "$response"
    return 1
  }

  return 0
}

###############################################################################
# function ec2_terminate_instances
#
# This function terminates one or more Amazon Elastic Compute Cloud (Amazon EC2)
# instances using the AWS CLI.
#
# Parameters:
#       -i instance_ids - A space-separated list of instance IDs.
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_terminate_instances() {
  local instance_ids response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_terminate_instances"
    echo "Terminates one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_ids - A space-separated list of instance IDs."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Check if instance ID is provided
  if [[ -z "${instance_ids}" ]]; then
    echo "Error: Missing required instance IDs parameter."
    usage
    return 1
  fi

  # shellcheck disable=SC2086
  response=$(aws ec2 terminate-instances \
    "--instance-ids" $instance_ids \
    --query 'TerminatingInstances[*].[InstanceId,CurrentState.Name]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports terminate-instances operation failed.$response"
    return 1
  }

  return 0
}

###############################################################################
# function ec2_delete_security_group
#
# This function deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -i security_group_id - The ID of the security group to delete.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_delete_security_group() {
  local security_group_id response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_delete_security_group"
    echo "Deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -i security_group_id - The ID of the security group to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) security_group_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 delete-security-group --group-id "$security_group_id" --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports delete-security-group operation failed.$response"
    return 1
  }

  return 0
}

###############################################################################
# function ec2_delete_keypair
#
# This function deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair.
#
# Parameters:
#       -n key_pair_name - A key pair name.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_delete_keypair() {
  local key_pair_name response

  local option OPTARG # Required to use getopts command in a function.
  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_delete_keypair"
    echo "Deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair."
    echo "  -n key_pair_name - A key pair name."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) key_pair_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key pair name with the -n parameter."
    usage
    return 1
  fi

  response=$(aws ec2 delete-key-pair \
    --key-name "$key_pair_name") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports delete-key-pair operation failed.$response"
    return 1
  }

  return 0
}
```
このシナリオで使用されるユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AllocateAddress)
  + [AssociateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AssociateAddress)
  + [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AuthorizeSecurityGroupIngress)
  + [CreateKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateKeyPair)
  + [CreateSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSecurityGroup)
  + [DeleteKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteKeyPair)
  + [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteSecurityGroup)
  + [DescribeImages](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeImages)
  + [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInstanceTypes)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInstances)
  + [DescribeKeyPairs](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeKeyPairs)
  + [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeSecurityGroups)
  + [DisassociateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DisassociateAddress)
  + [ReleaseAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ReleaseAddress)
  + [RunInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/RunInstances)
  + [StartInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/StartInstances)
  + [StopInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/StopInstances)
  + [TerminateInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/TerminateInstances)
  + [UnmonitorInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/UnmonitorInstances)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_bash_2_topic"></a>

次の例は、`AllocateAddress` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_allocate_address
#
# This function allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region.
#
# Parameters:
#       -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard').
#
# Returns:
#       The allocated Elastic IP address, or an error message if the operation fails.
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_allocate_address() {
  local domain response

  # Function to display usage information
  function usage() {
    echo "function ec2_allocate_address"
    echo "Allocates an Elastic IP address for use with Amazon Elastic Compute Cloud (Amazon EC2) instances in a specific AWS Region."
    echo "  -d domain - The domain for the Elastic IP address (either 'vpc' or 'standard')."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "d:h" option; do
    case "${option}" in
      d) domain="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$domain" ]]; then
    errecho "ERROR: You must provide a domain with the -d parameter (either 'vpc' or 'standard')."
    return 1
  fi

  if [[ "$domain" != "vpc" && "$domain" != "standard" ]]; then
    errecho "ERROR: Invalid domain value. Must be either 'vpc' or 'standard'."
    return 1
  fi

  # Allocate the Elastic IP address
  response=$(aws ec2 allocate-address \
    --domain "$domain" \
    --query "[PublicIp,AllocationId]" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports allocate-address operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AllocateAddress)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_bash_2_topic"></a>

次の例は、`AssociateAddress` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_associate_address
#
# This function associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a allocation_id - The allocation ID of the Elastic IP address to associate.
#       -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_associate_address() {
  local allocation_id instance_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_associate_address"
    echo "Associates an Elastic IP address with an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a allocation_id - The allocation ID of the Elastic IP address to associate."
    echo "  -i instance_id - The ID of the EC2 instance to associate the Elastic IP address with."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:i:h" option; do
    case "${option}" in
      a) allocation_id="${OPTARG}" ;;
      i) instance_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$allocation_id" ]]; then
    errecho "ERROR: You must provide an allocation ID with the -a parameter."
    return 1
  fi

  if [[ -z "$instance_id" ]]; then
    errecho "ERROR: You must provide an instance ID with the -i parameter."
    return 1
  fi

  # Associate the Elastic IP address
  response=$(aws ec2 associate-address \
    --allocation-id "$allocation_id" \
    --instance-id "$instance_id" \
    --query "AssociationId" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports associate-address operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AssociateAddress)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_bash_2_topic"></a>

次の例は、`AuthorizeSecurityGroupIngress` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_authorize_security_group_ingress
#
# This function authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -g security_group_id - The ID of the security group.
#       -i ip_address - The IP address or CIDR block to authorize.
#       -p protocol - The protocol to authorize (e.g., tcp, udp, icmp).
#       -f from_port - The start of the port range to authorize.
#       -t to_port - The end of the port range to authorize.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_authorize_security_group_ingress() {
  local security_group_id ip_address protocol from_port to_port response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_authorize_security_group_ingress"
    echo "Authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -g security_group_id - The ID of the security group."
    echo "  -i ip_address - The IP address or CIDR block to authorize."
    echo "  -p protocol - The protocol to authorize (e.g., tcp, udp, icmp)."
    echo "  -f from_port - The start of the port range to authorize."
    echo "  -t to_port - The end of the port range to authorize."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "g:i:p:f:t:h" option; do
    case "${option}" in
      g) security_group_id="${OPTARG}" ;;
      i) ip_address="${OPTARG}" ;;
      p) protocol="${OPTARG}" ;;
      f) from_port="${OPTARG}" ;;
      t) to_port="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -g parameter."
    usage
    return 1
  fi

  if [[ -z "$ip_address" ]]; then
    errecho "ERROR: You must provide an IP address or CIDR block with the -i parameter."
    usage
    return 1
  fi

  if [[ -z "$protocol" ]]; then
    errecho "ERROR: You must provide a protocol with the -p parameter."
    usage
    return 1
  fi

  if [[ -z "$from_port" ]]; then
    errecho "ERROR: You must provide a start port with the -f parameter."
    usage
    return 1
  fi

  if [[ -z "$to_port" ]]; then
    errecho "ERROR: You must provide an end port with the -t parameter."
    usage
    return 1
  fi

  response=$(aws ec2 authorize-security-group-ingress \
    --group-id "$security_group_id" \
    --cidr "${ip_address}/32" \
    --protocol "$protocol" \
    --port "$from_port-$to_port" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports authorize-security-group-ingress operation failed.$response"
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AuthorizeSecurityGroupIngress)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_bash_2_topic"></a>

次の例は、`CreateKeyPair` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_create_keypair
#
# This function creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair
# and writes it to a file.
#
# Parameters:
#       -n key_pair_name - A key pair name.
#       -f file_path - File to store the key pair.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_create_keypair() {
  local key_pair_name file_path response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_create_keypair"
    echo "Creates an Amazon Elastic Compute Cloud (Amazon EC2) ED25519 or 2048-bit RSA key pair"
    echo " and writes it to a file."
    echo "  -n key_pair_name - A key pair name."
    echo "  -f file_path - File to store the key pair."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:f:h" option; do
    case "${option}" in
      n) key_pair_name="${OPTARG}" ;;
      f) file_path="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key name with the -n parameter."
    usage
    return 1
  fi

  if [[ -z "$file_path" ]]; then
    errecho "ERROR: You must provide a file path with the -f parameter."
    usage
    return 1
  fi

  response=$(aws ec2 create-key-pair \
    --key-name "$key_pair_name" \
    --query 'KeyMaterial' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  }

  if [[ -n "$file_path" ]]; then
    echo "$response" >"$file_path"
  fi

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateKeyPair)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_bash_2_topic"></a>

次の例は、`CreateSecurityGroup` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_create_security_group
#
# This function creates an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -n security_group_name - The name of the security group.
#       -d security_group_description - The description of the security group.
#
# Returns:
#       The ID of the created security group, or an error message if the operation fails.
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_create_security_group() {
  local security_group_name security_group_description response

  # Function to display usage information
  function usage() {
    echo "function ec2_create_security_group"
    echo "Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -n security_group_name - The name of the security group."
    echo "  -d security_group_description - The description of the security group."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "n:d:h" option; do
    case "${option}" in
      n) security_group_name="${OPTARG}" ;;
      d) security_group_description="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$security_group_name" ]]; then
    errecho "ERROR: You must provide a security group name with the -n parameter."
    return 1
  fi

  if [[ -z "$security_group_description" ]]; then
    errecho "ERROR: You must provide a security group description with the -d parameter."
    return 1
  fi

  # Create the security group
  response=$(aws ec2 create-security-group \
    --group-name "$security_group_name" \
    --description "$security_group_description" \
    --query "GroupId" \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports create-security-group operation failed."
    errecho "$response"
    return 1
  }

  echo "$response"
  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSecurityGroup)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_bash_2_topic"></a>

次の例は、`DeleteKeyPair` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_delete_keypair
#
# This function deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair.
#
# Parameters:
#       -n key_pair_name - A key pair name.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_delete_keypair() {
  local key_pair_name response

  local option OPTARG # Required to use getopts command in a function.
  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_delete_keypair"
    echo "Deletes an Amazon EC2 ED25519 or 2048-bit RSA key pair."
    echo "  -n key_pair_name - A key pair name."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) key_pair_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key pair name with the -n parameter."
    usage
    return 1
  fi

  response=$(aws ec2 delete-key-pair \
    --key-name "$key_pair_name") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports delete-key-pair operation failed.$response"
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteKeyPair)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_bash_2_topic"></a>

次の例は、`DeleteSecurityGroup` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_delete_security_group
#
# This function deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Parameters:
#       -i security_group_id - The ID of the security group to delete.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_delete_security_group() {
  local security_group_id response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_delete_security_group"
    echo "Deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group."
    echo "  -i security_group_id - The ID of the security group to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) security_group_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 delete-security-group --group-id "$security_group_id" --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports delete-security-group operation failed.$response"
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteSecurityGroup)」を参照してください。

### `DescribeImages`
<a name="ec2_DescribeImages_bash_2_topic"></a>

次の例は、`DescribeImages` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_describe_images
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images.
#
# Parameters:
#       -i image_ids - A space-separated  list of image IDs (optional).
#       -h - Display help.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_images() {
  local image_ids response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_images"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) images."
    echo "  -i image_ids - A space-separated list of image IDs (optional)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) image_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local aws_cli_args=()

  if [[ -n "$image_ids" ]]; then
    # shellcheck disable=SC2206
    aws_cli_args+=("--image-ids" $image_ids)
  fi

  response=$(aws ec2 describe-images \
    "${aws_cli_args[@]}" \
    --query 'Images[*].[Description,Architecture,ImageId]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-images operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeImages](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeImages)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_bash_2_topic"></a>

次の例は、`DescribeInstanceTypes` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# ec2_describe_instance_types
#
# This function describes EC2 instance types filtered by processor architecture
# and optionally by instance type. It takes the following arguments:
#
# -a, --architecture ARCHITECTURE  Specify the processor architecture (e.g., x86_64)
# -t, --type INSTANCE_TYPE         Comma-separated list of instance types (e.g., t2.micro)
# -h, --help                       Show the usage help
#
# The function prints the instance type and supported architecture for each
# matching instance type.
###############################################################################
function ec2_describe_instance_types() {
  local architecture=""
  local instance_types=""

  # bashsupport disable=BP5008
  function usage() {
    echo "Usage: ec2_describe_instance_types [-a|--architecture ARCHITECTURE] [-t|--type INSTANCE_TYPE] [-h|--help]"
    echo "  -a, --architecture ARCHITECTURE  Specify the processor architecture (e.g., x86_64)"
    echo "  -t, --type INSTANCE_TYPE         Comma-separated list of instance types (e.g., t2.micro)"
    echo "  -h, --help                       Show this help message"
  }

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -a | --architecture)
        architecture="$2"
        shift 2
        ;;
      -t | --type)
        instance_types="$2"
        shift 2
        ;;
      -h | --help)
        usage
        return 0
        ;;
      *)
        echo "Unknown argument: $1"
        return 1
        ;;
    esac
  done

  if [[ -z "$architecture" ]]; then
    errecho "Error: Architecture not specified."
    usage
    return 1
  fi

  if [[ -z "$instance_types" ]]; then
    errecho "Error: Instance type not specified."
    usage
    return 1
  fi

  local tmp_json_file="temp_ec2.json"
  echo -n '[
    {
      "Name": "processor-info.supported-architecture",
      "Values": [' >"$tmp_json_file"

  local items
  IFS=',' read -ra items <<<"$architecture"
  local array_size
  array_size=${#items[@]}
  for i in $(seq 0 $((array_size - 1))); do
    echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file"
    if [[ $i -lt $((array_size - 1)) ]]; then
      echo -n ',' >>"$tmp_json_file"
    fi
  done
  echo -n ']},
    {
    "Name": "instance-type",
      "Values": [' >>"$tmp_json_file"
  IFS=',' read -ra items <<<"$instance_types"
  local array_size
  array_size=${#items[@]}
  for i in $(seq 0 $((array_size - 1))); do
    echo -n '"'"${items[$i]}"'"' >>"$tmp_json_file"
    if [[ $i -lt $((array_size - 1)) ]]; then
      echo -n ',' >>"$tmp_json_file"
    fi
  done

  echo -n ']}]' >>"$tmp_json_file"

  local response
  response=$(aws ec2 describe-instance-types --filters file://"$tmp_json_file" \
    --query 'InstanceTypes[*].[InstanceType]' --output text)

  local error_code=$?

  rm "$tmp_json_file"

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    echo "ERROR: AWS reports describe-instance-types operation failed."
    return 1
  fi

  echo "$response"
  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceTypes](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInstanceTypes)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_bash_2_topic"></a>

次の例は、`DescribeInstances` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_describe_instances
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID of the instance to describe (optional).
#       -q query - The query to filter the response (optional).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_instances() {
  local instance_id query response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_instances"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID of the instance to describe (optional)."
    echo "  -q query - The query to filter the response (optional)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:q:h" option; do
    case "${option}" in
      i) instance_id="${OPTARG}" ;;
      q) query="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local aws_cli_args=()

  if [[ -n "$instance_id" ]]; then
    # shellcheck disable=SC2206
    aws_cli_args+=("--instance-ids" $instance_id)
  fi

  local query_arg=""
  if [[ -n "$query" ]]; then
    query_arg="--query '$query'"
  else
    query_arg="--query Reservations[*].Instances[*].[InstanceId,ImageId,InstanceType,KeyName,VpcId,PublicIpAddress,State.Name]"
  fi

  # shellcheck disable=SC2086
  response=$(aws ec2 describe-instances \
    "${aws_cli_args[@]}" \
    $query_arg \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-instances operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInstances)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_bash_2_topic"></a>

次の例は、`DescribeKeyPairs` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_describe_key_pairs
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs.
#
# Parameters:
#       -h - Display help.
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_key_pairs() {
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_key_pairs"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) key pairs."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "h" option; do
    case "${option}" in
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local response

  response=$(aws ec2 describe-key-pairs \
    --query 'KeyPairs[*].[KeyName, KeyFingerprint]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports describe-key-pairs operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeKeyPairs](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeKeyPairs)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_bash_2_topic"></a>

次の例は、`DescribeSecurityGroups` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_describe_security_groups
#
# This function describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups.
#
# Parameters:
#       -g security_group_id - The ID of the security group to describe (optional).
#
# And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_describe_security_groups() {
  local security_group_id response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_describe_security_groups"
    echo "Describes one or more Amazon Elastic Compute Cloud (Amazon EC2) security groups."
    echo "  -g security_group_id - The ID of the security group to describe (optional)."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "g:h" option; do
    case "${option}" in
      g) security_group_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local query="SecurityGroups[*].[GroupName, GroupId, VpcId, IpPermissions[*].[IpProtocol, FromPort, ToPort, IpRanges[*].CidrIp]]"

  if [[ -n "$security_group_id" ]]; then
    response=$(aws ec2 describe-security-groups --group-ids "$security_group_id" --query "${query}" --output text)
  else
    response=$(aws ec2 describe-security-groups --query "${query}" --output text)
  fi

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports describe-security-groups operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_bash_2_topic"></a>

次の例は、`DisassociateAddress` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_disassociate_address
#
# This function disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a association_id - The association ID that represents the association of the Elastic IP address with an instance.
#
# And:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_disassociate_address() {
  local association_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_disassociate_address"
    echo "Disassociates an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a association_id - The association ID that represents the association of the Elastic IP address with an instance."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:h" option; do
    case "${option}" in
      a) association_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$association_id" ]]; then
    errecho "ERROR: You must provide an association ID with the -a parameter."
    return 1
  fi

  response=$(aws ec2 disassociate-address \
    --association-id "$association_id") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports disassociate-address operation failed."
    errecho "$response"
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DisassociateAddress)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_bash_2_topic"></a>

次の例は、`ReleaseAddress` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_release_address
#
# This function releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Parameters:
#       -a allocation_id - The allocation ID of the Elastic IP address to release.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
#
###############################################################################
function ec2_release_address() {
  local allocation_id response

  # Function to display usage information
  function usage() {
    echo "function ec2_release_address"
    echo "Releases an Elastic IP address from an Amazon Elastic Compute Cloud (Amazon EC2) instance."
    echo "  -a allocation_id - The allocation ID of the Elastic IP address to release."
    echo ""
  }

  # Parse the command-line arguments
  while getopts "a:h" option; do
    case "${option}" in
      a) allocation_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Validate the input parameters
  if [[ -z "$allocation_id" ]]; then
    errecho "ERROR: You must provide an allocation ID with the -a parameter."
    return 1
  fi

  response=$(aws ec2 release-address \
    --allocation-id "$allocation_id") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports release-address operation failed."
    errecho "$response"
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReleaseAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ReleaseAddress)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_bash_2_topic"></a>

次の例は、`RunInstances` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_run_instances
#
# This function launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i image_id - The ID of the Amazon Machine Image (AMI) to use.
#       -t instance_type - The instance type to use (e.g., t2.micro).
#       -k key_pair_name - The name of the key pair to use.
#       -s security_group_id - The ID of the security group to use.
#       -c count - The number of instances to launch (default: 1).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_run_instances() {
  local image_id instance_type key_pair_name security_group_id count response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_run_instances"
    echo "Launches one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i image_id - The ID of the Amazon Machine Image (AMI) to use."
    echo "  -t instance_type - The instance type to use (e.g., t2.micro)."
    echo "  -k key_pair_name - The name of the key pair to use."
    echo "  -s security_group_id - The ID of the security group to use."
    echo "  -c count - The number of instances to launch (default: 1)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:t:k:s:c:h" option; do
    case "${option}" in
      i) image_id="${OPTARG}" ;;
      t) instance_type="${OPTARG}" ;;
      k) key_pair_name="${OPTARG}" ;;
      s) security_group_id="${OPTARG}" ;;
      c) count="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$image_id" ]]; then
    errecho "ERROR: You must provide an Amazon Machine Image (AMI) ID with the -i parameter."
    usage
    return 1
  fi

  if [[ -z "$instance_type" ]]; then
    errecho "ERROR: You must provide an instance type with the -t parameter."
    usage
    return 1
  fi

  if [[ -z "$key_pair_name" ]]; then
    errecho "ERROR: You must provide a key pair name with the -k parameter."
    usage
    return 1
  fi

  if [[ -z "$security_group_id" ]]; then
    errecho "ERROR: You must provide a security group ID with the -s parameter."
    usage
    return 1
  fi

  if [[ -z "$count" ]]; then
    count=1
  fi

  response=$(aws ec2 run-instances \
    --image-id "$image_id" \
    --instance-type "$instance_type" \
    --key-name "$key_pair_name" \
    --security-group-ids "$security_group_id" \
    --count "$count" \
    --query 'Instances[*].[InstanceId]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports run-instances operation failed.$response"
    return 1
  }

  echo "$response"

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RunInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/RunInstances)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_bash_2_topic"></a>

次の例は、`StartInstances` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_start_instances
#
# This function starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID(s) of the instance(s) to start (comma-separated).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_start_instances() {
  local instance_ids
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_start_instances"
    echo "Starts one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID(s) of the instance(s) to start (comma-separated)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$instance_ids" ]]; then
    errecho "ERROR: You must provide one or more instance IDs with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 start-instances \
    --instance-ids "${instance_ids}") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports start-instances operation failed with $response."
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/StartInstances)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_bash_2_topic"></a>

次の例は、`StopInstances` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_stop_instances
#
# This function stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances.
#
# Parameters:
#       -i instance_id - The ID(s) of the instance(s) to stop (comma-separated).
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_stop_instances() {
  local instance_ids
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_stop_instances"
    echo "Stops one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_id - The ID(s) of the instance(s) to stop (comma-separated)."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$instance_ids" ]]; then
    errecho "ERROR: You must provide one or more instance IDs with the -i parameter."
    usage
    return 1
  fi

  response=$(aws ec2 stop-instances \
    --instance-ids "${instance_ids}") || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports stop-instances operation failed with $response."
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/StopInstances)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_bash_2_topic"></a>

次の例は、`TerminateInstances` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/ec2#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function ec2_terminate_instances
#
# This function terminates one or more Amazon Elastic Compute Cloud (Amazon EC2)
# instances using the AWS CLI.
#
# Parameters:
#       -i instance_ids - A space-separated list of instance IDs.
#       -h - Display help.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function ec2_terminate_instances() {
  local instance_ids response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function ec2_terminate_instances"
    echo "Terminates one or more Amazon Elastic Compute Cloud (Amazon EC2) instances."
    echo "  -i instance_ids - A space-separated list of instance IDs."
    echo "  -h - Display help."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) instance_ids="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  # Check if instance ID is provided
  if [[ -z "${instance_ids}" ]]; then
    echo "Error: Missing required instance IDs parameter."
    usage
    return 1
  fi

  # shellcheck disable=SC2086
  response=$(aws ec2 terminate-instances \
    "--instance-ids" $instance_ids \
    --query 'TerminatingInstances[*].[InstanceId,CurrentState.Name]' \
    --output text) || {
    aws_cli_error_log ${?}
    errecho "ERROR: AWS reports terminate-instances operation failed.$response"
    return 1
  }

  return 0
}
```
この例で使用されているユーティリティ関数。  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

##############################################################################
# function aws_cli_error_log()
#
# This function is used to log the error messages from the AWS CLI.
#
# The function expects the following argument:
#         $1 - The error code returned by the AWS CLI.
#
#  Returns:
#          0: - Success.
#
##############################################################################
function aws_cli_error_log() {
  local err_code=$1
  errecho "Error code : $err_code"
  if [ "$err_code" == 1 ]; then
    errecho "  One or more S3 transfers failed."
  elif [ "$err_code" == 2 ]; then
    errecho "  Command line failed to parse."
  elif [ "$err_code" == 130 ]; then
    errecho "  Process received SIGINT."
  elif [ "$err_code" == 252 ]; then
    errecho "  Command syntax invalid."
  elif [ "$err_code" == 253 ]; then
    errecho "  The system environment or configuration was invalid."
  elif [ "$err_code" == 254 ]; then
    errecho "  The service returned an error."
  elif [ "$err_code" == 255 ]; then
    errecho "  255 is a catch-all error."
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TerminateInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/TerminateInstances)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### プライベートサブネットおよび NAT ゲートウェイを持つ VPC を作成する
<a name="vpc_GettingStartedPrivate_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ CLI を使用してプライベートサブネットおよび NAT ゲートウェイを持つ VPC を作成します。
+ VPC、サブネット、ルートテーブル、NAT ゲートウェイなど、必要なコンポーネントを設定します。
+ 適切なアクセスとセキュリティのためにセキュリティグループと IAM ロールを設定します。
+ CLI コマンドを使用して、これらのリソースの作成と設定を自動化します。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/008-vpc-private-servers-gs)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# VPC with Private Subnets and NAT Gateways (IMDSv2 Compliant Version)
# This script creates a VPC with public and private subnets in two Availability Zones,
# NAT gateways, an internet gateway, route tables, a VPC endpoint for S3,
# security groups, a launch template, an Auto Scaling group, and an Application Load Balancer.

# Set up logging
LOG_FILE="vpc-private-subnets-nat.log"
exec > >(tee -a "$LOG_FILE") 2>&1

# Cleanup function to delete all created resources
cleanup_resources() {
  echo "Cleaning up resources..."
  
  # Delete Auto Scaling group if it exists
  if [ -n "${ASG_NAME:-}" ]; then
    echo "Deleting Auto Scaling group: $ASG_NAME"
    aws autoscaling delete-auto-scaling-group --auto-scaling-group-name "$ASG_NAME" --force-delete
    echo "Waiting for Auto Scaling group to be deleted..."
    aws autoscaling wait auto-scaling-groups-deleted --auto-scaling-group-names "$ASG_NAME"
  fi
  
  # Delete load balancer if it exists
  if [ -n "${LB_ARN:-}" ]; then
    echo "Deleting load balancer: $LB_ARN"
    aws elbv2 delete-load-balancer --load-balancer-arn "$LB_ARN"
    # Wait for load balancer to be deleted
    sleep 30
  fi
  
  # Delete target group if it exists
  if [ -n "${TARGET_GROUP_ARN:-}" ]; then
    echo "Deleting target group: $TARGET_GROUP_ARN"
    aws elbv2 delete-target-group --target-group-arn "$TARGET_GROUP_ARN"
  fi
  
  # Delete launch template if it exists
  if [ -n "${LAUNCH_TEMPLATE_NAME:-}" ]; then
    echo "Deleting launch template: $LAUNCH_TEMPLATE_NAME"
    aws ec2 delete-launch-template --launch-template-name "$LAUNCH_TEMPLATE_NAME"
  fi
  
  # Delete NAT Gateways if they exist
  if [ -n "${NAT_GW1_ID:-}" ]; then
    echo "Deleting NAT Gateway 1: $NAT_GW1_ID"
    aws ec2 delete-nat-gateway --nat-gateway-id "$NAT_GW1_ID"
  fi
  
  if [ -n "${NAT_GW2_ID:-}" ]; then
    echo "Deleting NAT Gateway 2: $NAT_GW2_ID"
    aws ec2 delete-nat-gateway --nat-gateway-id "$NAT_GW2_ID"
  fi
  
  # Wait for NAT Gateways to be deleted
  if [ -n "${NAT_GW1_ID:-}" ] || [ -n "${NAT_GW2_ID:-}" ]; then
    echo "Waiting for NAT Gateways to be deleted..."
    sleep 60
  fi
  
  # Release Elastic IPs if they exist
  if [ -n "${EIP1_ALLOC_ID:-}" ]; then
    echo "Releasing Elastic IP 1: $EIP1_ALLOC_ID"
    aws ec2 release-address --allocation-id "$EIP1_ALLOC_ID"
  fi
  
  if [ -n "${EIP2_ALLOC_ID:-}" ]; then
    echo "Releasing Elastic IP 2: $EIP2_ALLOC_ID"
    aws ec2 release-address --allocation-id "$EIP2_ALLOC_ID"
  fi
  
  # Delete VPC endpoint if it exists
  if [ -n "${VPC_ENDPOINT_ID:-}" ]; then
    echo "Deleting VPC endpoint: $VPC_ENDPOINT_ID"
    aws ec2 delete-vpc-endpoints --vpc-endpoint-ids "$VPC_ENDPOINT_ID"
  fi
  
  # Delete security groups if they exist
  if [ -n "${APP_SG_ID:-}" ]; then
    echo "Deleting application security group: $APP_SG_ID"
    aws ec2 delete-security-group --group-id "$APP_SG_ID"
  fi
  
  if [ -n "${LB_SG_ID:-}" ]; then
    echo "Deleting load balancer security group: $LB_SG_ID"
    aws ec2 delete-security-group --group-id "$LB_SG_ID"
  fi
  
  # Detach and delete Internet Gateway if it exists
  if [ -n "${IGW_ID:-}" ] && [ -n "${VPC_ID:-}" ]; then
    echo "Detaching Internet Gateway: $IGW_ID from VPC: $VPC_ID"
    aws ec2 detach-internet-gateway --internet-gateway-id "$IGW_ID" --vpc-id "$VPC_ID"
    echo "Deleting Internet Gateway: $IGW_ID"
    aws ec2 delete-internet-gateway --internet-gateway-id "$IGW_ID"
  fi
  
  # Delete route table associations and route tables if they exist
  if [ -n "${PUBLIC_RT_ASSOC1_ID:-}" ]; then
    echo "Disassociating public route table from subnet 1: $PUBLIC_RT_ASSOC1_ID"
    aws ec2 disassociate-route-table --association-id "$PUBLIC_RT_ASSOC1_ID"
  fi
  
  if [ -n "${PUBLIC_RT_ASSOC2_ID:-}" ]; then
    echo "Disassociating public route table from subnet 2: $PUBLIC_RT_ASSOC2_ID"
    aws ec2 disassociate-route-table --association-id "$PUBLIC_RT_ASSOC2_ID"
  fi
  
  if [ -n "${PRIVATE_RT1_ASSOC_ID:-}" ]; then
    echo "Disassociating private route table 1: $PRIVATE_RT1_ASSOC_ID"
    aws ec2 disassociate-route-table --association-id "$PRIVATE_RT1_ASSOC_ID"
  fi
  
  if [ -n "${PRIVATE_RT2_ASSOC_ID:-}" ]; then
    echo "Disassociating private route table 2: $PRIVATE_RT2_ASSOC_ID"
    aws ec2 disassociate-route-table --association-id "$PRIVATE_RT2_ASSOC_ID"
  fi
  
  if [ -n "${PUBLIC_RT_ID:-}" ]; then
    echo "Deleting public route table: $PUBLIC_RT_ID"
    aws ec2 delete-route-table --route-table-id "$PUBLIC_RT_ID"
  fi
  
  if [ -n "${PRIVATE_RT1_ID:-}" ]; then
    echo "Deleting private route table 1: $PRIVATE_RT1_ID"
    aws ec2 delete-route-table --route-table-id "$PRIVATE_RT1_ID"
  fi
  
  if [ -n "${PRIVATE_RT2_ID:-}" ]; then
    echo "Deleting private route table 2: $PRIVATE_RT2_ID"
    aws ec2 delete-route-table --route-table-id "$PRIVATE_RT2_ID"
  fi
  
  # Delete subnets if they exist
  if [ -n "${PUBLIC_SUBNET1_ID:-}" ]; then
    echo "Deleting public subnet 1: $PUBLIC_SUBNET1_ID"
    aws ec2 delete-subnet --subnet-id "$PUBLIC_SUBNET1_ID"
  fi
  
  if [ -n "${PUBLIC_SUBNET2_ID:-}" ]; then
    echo "Deleting public subnet 2: $PUBLIC_SUBNET2_ID"
    aws ec2 delete-subnet --subnet-id "$PUBLIC_SUBNET2_ID"
  fi
  
  if [ -n "${PRIVATE_SUBNET1_ID:-}" ]; then
    echo "Deleting private subnet 1: $PRIVATE_SUBNET1_ID"
    aws ec2 delete-subnet --subnet-id "$PRIVATE_SUBNET1_ID"
  fi
  
  if [ -n "${PRIVATE_SUBNET2_ID:-}" ]; then
    echo "Deleting private subnet 2: $PRIVATE_SUBNET2_ID"
    aws ec2 delete-subnet --subnet-id "$PRIVATE_SUBNET2_ID"
  fi
  
  # Delete VPC if it exists
  if [ -n "${VPC_ID:-}" ]; then
    echo "Deleting VPC: $VPC_ID"
    aws ec2 delete-vpc --vpc-id "$VPC_ID"
  fi
  
  echo "Cleanup completed."
}

# Error handling function
handle_error() {
  echo "ERROR: $1"
  echo "Attempting to clean up resources..."
  cleanup_resources
  exit 1
}

# Function to check command success
check_command() {
  if [ $? -ne 0 ]; then
    handle_error "$1"
  fi
}

# Generate a random identifier for resource names
RANDOM_ID=$(openssl rand -hex 4)
echo "Using random identifier: $RANDOM_ID"

# Create VPC
echo "Creating VPC..."
VPC_RESULT=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --tag-specifications "ResourceType=vpc,Tags=[{Key=Name,Value=ProductionVPC-$RANDOM_ID}]")
check_command "Failed to create VPC"

VPC_ID=$(echo "$VPC_RESULT" | jq -r '.Vpc.VpcId')
echo "VPC created with ID: $VPC_ID"

# Get Availability Zones
echo "Getting Availability Zones..."
AZ_RESULT=$(aws ec2 describe-availability-zones --query 'AvailabilityZones[0:2].ZoneName' --output text)
check_command "Failed to get Availability Zones"

# Convert space-separated output to array
read -r -a AZS <<< "$AZ_RESULT"
AZ1=${AZS[0]}
AZ2=${AZS[1]}
echo "Using Availability Zones: $AZ1 and $AZ2"

# Create subnets
echo "Creating subnets..."
PUBLIC_SUBNET1_RESULT=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.0.0.0/24 --availability-zone "$AZ1" --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=PublicSubnet1-$RANDOM_ID}]")
check_command "Failed to create public subnet 1"
PUBLIC_SUBNET1_ID=$(echo "$PUBLIC_SUBNET1_RESULT" | jq -r '.Subnet.SubnetId')

PRIVATE_SUBNET1_RESULT=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.0.1.0/24 --availability-zone "$AZ1" --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=PrivateSubnet1-$RANDOM_ID}]")
check_command "Failed to create private subnet 1"
PRIVATE_SUBNET1_ID=$(echo "$PRIVATE_SUBNET1_RESULT" | jq -r '.Subnet.SubnetId')

PUBLIC_SUBNET2_RESULT=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.0.2.0/24 --availability-zone "$AZ2" --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=PublicSubnet2-$RANDOM_ID}]")
check_command "Failed to create public subnet 2"
PUBLIC_SUBNET2_ID=$(echo "$PUBLIC_SUBNET2_RESULT" | jq -r '.Subnet.SubnetId')

PRIVATE_SUBNET2_RESULT=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.0.3.0/24 --availability-zone "$AZ2" --tag-specifications "ResourceType=subnet,Tags=[{Key=Name,Value=PrivateSubnet2-$RANDOM_ID}]")
check_command "Failed to create private subnet 2"
PRIVATE_SUBNET2_ID=$(echo "$PRIVATE_SUBNET2_RESULT" | jq -r '.Subnet.SubnetId')

echo "Subnets created with IDs:"
echo "Public Subnet 1: $PUBLIC_SUBNET1_ID"
echo "Private Subnet 1: $PRIVATE_SUBNET1_ID"
echo "Public Subnet 2: $PUBLIC_SUBNET2_ID"
echo "Private Subnet 2: $PRIVATE_SUBNET2_ID"

# Create Internet Gateway
echo "Creating Internet Gateway..."
IGW_RESULT=$(aws ec2 create-internet-gateway --tag-specifications "ResourceType=internet-gateway,Tags=[{Key=Name,Value=ProductionIGW-$RANDOM_ID}]")
check_command "Failed to create Internet Gateway"
IGW_ID=$(echo "$IGW_RESULT" | jq -r '.InternetGateway.InternetGatewayId')
echo "Internet Gateway created with ID: $IGW_ID"

# Attach Internet Gateway to VPC
echo "Attaching Internet Gateway to VPC..."
aws ec2 attach-internet-gateway --internet-gateway-id "$IGW_ID" --vpc-id "$VPC_ID"
check_command "Failed to attach Internet Gateway to VPC"

# Create route tables
echo "Creating route tables..."
PUBLIC_RT_RESULT=$(aws ec2 create-route-table --vpc-id "$VPC_ID" --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=PublicRouteTable-$RANDOM_ID}]")
check_command "Failed to create public route table"
PUBLIC_RT_ID=$(echo "$PUBLIC_RT_RESULT" | jq -r '.RouteTable.RouteTableId')

PRIVATE_RT1_RESULT=$(aws ec2 create-route-table --vpc-id "$VPC_ID" --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=PrivateRouteTable1-$RANDOM_ID}]")
check_command "Failed to create private route table 1"
PRIVATE_RT1_ID=$(echo "$PRIVATE_RT1_RESULT" | jq -r '.RouteTable.RouteTableId')

PRIVATE_RT2_RESULT=$(aws ec2 create-route-table --vpc-id "$VPC_ID" --tag-specifications "ResourceType=route-table,Tags=[{Key=Name,Value=PrivateRouteTable2-$RANDOM_ID}]")
check_command "Failed to create private route table 2"
PRIVATE_RT2_ID=$(echo "$PRIVATE_RT2_RESULT" | jq -r '.RouteTable.RouteTableId')

echo "Route tables created with IDs:"
echo "Public Route Table: $PUBLIC_RT_ID"
echo "Private Route Table 1: $PRIVATE_RT1_ID"
echo "Private Route Table 2: $PRIVATE_RT2_ID"

# Add route to Internet Gateway in public route table
echo "Adding route to Internet Gateway in public route table..."
aws ec2 create-route --route-table-id "$PUBLIC_RT_ID" --destination-cidr-block 0.0.0.0/0 --gateway-id "$IGW_ID"
check_command "Failed to add route to Internet Gateway"

# Associate subnets with route tables
echo "Associating subnets with route tables..."
PUBLIC_RT_ASSOC1_RESULT=$(aws ec2 associate-route-table --route-table-id "$PUBLIC_RT_ID" --subnet-id "$PUBLIC_SUBNET1_ID")
check_command "Failed to associate public subnet 1 with route table"
PUBLIC_RT_ASSOC1_ID=$(echo "$PUBLIC_RT_ASSOC1_RESULT" | jq -r '.AssociationId')

PUBLIC_RT_ASSOC2_RESULT=$(aws ec2 associate-route-table --route-table-id "$PUBLIC_RT_ID" --subnet-id "$PUBLIC_SUBNET2_ID")
check_command "Failed to associate public subnet 2 with route table"
PUBLIC_RT_ASSOC2_ID=$(echo "$PUBLIC_RT_ASSOC2_RESULT" | jq -r '.AssociationId')

PRIVATE_RT1_ASSOC_RESULT=$(aws ec2 associate-route-table --route-table-id "$PRIVATE_RT1_ID" --subnet-id "$PRIVATE_SUBNET1_ID")
check_command "Failed to associate private subnet 1 with route table"
PRIVATE_RT1_ASSOC_ID=$(echo "$PRIVATE_RT1_ASSOC_RESULT" | jq -r '.AssociationId')

PRIVATE_RT2_ASSOC_RESULT=$(aws ec2 associate-route-table --route-table-id "$PRIVATE_RT2_ID" --subnet-id "$PRIVATE_SUBNET2_ID")
check_command "Failed to associate private subnet 2 with route table"
PRIVATE_RT2_ASSOC_ID=$(echo "$PRIVATE_RT2_ASSOC_RESULT" | jq -r '.AssociationId')

echo "Route table associations created with IDs:"
echo "Public Subnet 1 Association: $PUBLIC_RT_ASSOC1_ID"
echo "Public Subnet 2 Association: $PUBLIC_RT_ASSOC2_ID"
echo "Private Subnet 1 Association: $PRIVATE_RT1_ASSOC_ID"
echo "Private Subnet 2 Association: $PRIVATE_RT2_ASSOC_ID"

# Create NAT Gateways
echo "Creating NAT Gateways..."

# Allocate Elastic IPs for NAT Gateways
echo "Allocating Elastic IPs for NAT Gateways..."
EIP1_RESULT=$(aws ec2 allocate-address --domain vpc --tag-specifications "ResourceType=elastic-ip,Tags=[{Key=Name,Value=NAT1-EIP-$RANDOM_ID}]")
check_command "Failed to allocate Elastic IP 1"
EIP1_ALLOC_ID=$(echo "$EIP1_RESULT" | jq -r '.AllocationId')

EIP2_RESULT=$(aws ec2 allocate-address --domain vpc --tag-specifications "ResourceType=elastic-ip,Tags=[{Key=Name,Value=NAT2-EIP-$RANDOM_ID}]")
check_command "Failed to allocate Elastic IP 2"
EIP2_ALLOC_ID=$(echo "$EIP2_RESULT" | jq -r '.AllocationId')

echo "Elastic IPs allocated with IDs:"
echo "EIP 1 Allocation ID: $EIP1_ALLOC_ID"
echo "EIP 2 Allocation ID: $EIP2_ALLOC_ID"

# Create NAT Gateways
echo "Creating NAT Gateway in public subnet 1..."
NAT_GW1_RESULT=$(aws ec2 create-nat-gateway --subnet-id "$PUBLIC_SUBNET1_ID" --allocation-id "$EIP1_ALLOC_ID" --tag-specifications "ResourceType=natgateway,Tags=[{Key=Name,Value=NAT-Gateway1-$RANDOM_ID}]")
check_command "Failed to create NAT Gateway 1"
NAT_GW1_ID=$(echo "$NAT_GW1_RESULT" | jq -r '.NatGateway.NatGatewayId')

echo "Creating NAT Gateway in public subnet 2..."
NAT_GW2_RESULT=$(aws ec2 create-nat-gateway --subnet-id "$PUBLIC_SUBNET2_ID" --allocation-id "$EIP2_ALLOC_ID" --tag-specifications "ResourceType=natgateway,Tags=[{Key=Name,Value=NAT-Gateway2-$RANDOM_ID}]")
check_command "Failed to create NAT Gateway 2"
NAT_GW2_ID=$(echo "$NAT_GW2_RESULT" | jq -r '.NatGateway.NatGatewayId')

echo "NAT Gateways created with IDs:"
echo "NAT Gateway 1: $NAT_GW1_ID"
echo "NAT Gateway 2: $NAT_GW2_ID"

# Wait for NAT Gateways to be available
echo "Waiting for NAT Gateways to be available..."
aws ec2 wait nat-gateway-available --nat-gateway-ids "$NAT_GW1_ID"
check_command "NAT Gateway 1 did not become available"
aws ec2 wait nat-gateway-available --nat-gateway-ids "$NAT_GW2_ID"
check_command "NAT Gateway 2 did not become available"
echo "NAT Gateways are now available"

# Add routes to NAT Gateways in private route tables
echo "Adding routes to NAT Gateways in private route tables..."
aws ec2 create-route --route-table-id "$PRIVATE_RT1_ID" --destination-cidr-block 0.0.0.0/0 --nat-gateway-id "$NAT_GW1_ID"
check_command "Failed to add route to NAT Gateway 1"

aws ec2 create-route --route-table-id "$PRIVATE_RT2_ID" --destination-cidr-block 0.0.0.0/0 --nat-gateway-id "$NAT_GW2_ID"
check_command "Failed to add route to NAT Gateway 2"

# Create VPC Endpoint for S3
echo "Creating VPC Endpoint for S3..."
S3_PREFIX_LIST_ID=$(aws ec2 describe-prefix-lists --filters "Name=prefix-list-name,Values=com.amazonaws.$(aws configure get region).s3" --query 'PrefixLists[0].PrefixListId' --output text)
check_command "Failed to get S3 prefix list ID"

VPC_ENDPOINT_RESULT=$(aws ec2 create-vpc-endpoint --vpc-id "$VPC_ID" --service-name "com.amazonaws.$(aws configure get region).s3" --route-table-ids "$PRIVATE_RT1_ID" "$PRIVATE_RT2_ID" --tag-specifications "ResourceType=vpc-endpoint,Tags=[{Key=Name,Value=S3-Endpoint-$RANDOM_ID}]")
check_command "Failed to create VPC endpoint for S3"
VPC_ENDPOINT_ID=$(echo "$VPC_ENDPOINT_RESULT" | jq -r '.VpcEndpoint.VpcEndpointId')
echo "VPC Endpoint created with ID: $VPC_ENDPOINT_ID"

# Create security groups
echo "Creating security groups..."
LB_SG_RESULT=$(aws ec2 create-security-group --group-name "LoadBalancerSG-$RANDOM_ID" --description "Security group for the load balancer" --vpc-id "$VPC_ID" --tag-specifications "ResourceType=security-group,Tags=[{Key=Name,Value=LoadBalancerSG-$RANDOM_ID}]")
check_command "Failed to create load balancer security group"
LB_SG_ID=$(echo "$LB_SG_RESULT" | jq -r '.GroupId')

# Allow inbound HTTP traffic from anywhere to the load balancer
aws ec2 authorize-security-group-ingress --group-id "$LB_SG_ID" --protocol tcp --port 80 --cidr 0.0.0.0/0
check_command "Failed to authorize ingress to load balancer security group"

APP_SG_RESULT=$(aws ec2 create-security-group --group-name "AppServerSG-$RANDOM_ID" --description "Security group for the application servers" --vpc-id "$VPC_ID" --tag-specifications "ResourceType=security-group,Tags=[{Key=Name,Value=AppServerSG-$RANDOM_ID}]")
check_command "Failed to create application server security group"
APP_SG_ID=$(echo "$APP_SG_RESULT" | jq -r '.GroupId')

# Allow inbound HTTP traffic from the load balancer security group to the application servers
aws ec2 authorize-security-group-ingress --group-id "$APP_SG_ID" --protocol tcp --port 80 --source-group "$LB_SG_ID"
check_command "Failed to authorize ingress to application server security group"

echo "Security groups created with IDs:"
echo "Load Balancer Security Group: $LB_SG_ID"
echo "Application Server Security Group: $APP_SG_ID"

# Create a launch template
echo "Creating launch template..."

# Create user data script with IMDSv2 support
cat > user-data.sh << 'EOF'
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd

# Use IMDSv2 with session token
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
AZ=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
HOSTNAME=$(hostname -f)

echo "<h1>Hello from $HOSTNAME in $AZ</h1>" > /var/www/html/index.html
EOF

# Encode user data
USER_DATA=$(base64 -w 0 user-data.sh)

# Get latest Amazon Linux 2 AMI
echo "Getting latest Amazon Linux 2 AMI..."
AMI_ID=$(aws ec2 describe-images --owners amazon --filters "Name=name,Values=amzn2-ami-hvm-*-x86_64-gp2" "Name=state,Values=available" --query 'sort_by(Images, &CreationDate)[-1].ImageId' --output text)
check_command "Failed to get latest Amazon Linux 2 AMI"
echo "Using AMI: $AMI_ID"

# Create launch template with IMDSv2 required
LAUNCH_TEMPLATE_NAME="AppServerTemplate-$RANDOM_ID"
echo "Creating launch template: $LAUNCH_TEMPLATE_NAME"

aws ec2 create-launch-template \
  --launch-template-name "$LAUNCH_TEMPLATE_NAME" \
  --version-description "Initial version" \
  --tag-specifications "ResourceType=launch-template,Tags=[{Key=Name,Value=$LAUNCH_TEMPLATE_NAME}]" \
  --launch-template-data "{
    \"NetworkInterfaces\": [{
      \"DeviceIndex\": 0,
      \"Groups\": [\"$APP_SG_ID\"],
      \"DeleteOnTermination\": true
    }],
    \"ImageId\": \"$AMI_ID\",
    \"InstanceType\": \"t3.micro\",
    \"UserData\": \"$USER_DATA\",
    \"MetadataOptions\": {
      \"HttpTokens\": \"required\",
      \"HttpEndpoint\": \"enabled\"
    },
    \"TagSpecifications\": [{
      \"ResourceType\": \"instance\",
      \"Tags\": [{
        \"Key\": \"Name\",
        \"Value\": \"AppServer-$RANDOM_ID\"
      }]
    }]
  }"
check_command "Failed to create launch template"

# Create target group
echo "Creating target group..."
TARGET_GROUP_NAME="AppTargetGroup-$RANDOM_ID"
TARGET_GROUP_RESULT=$(aws elbv2 create-target-group \
  --name "$TARGET_GROUP_NAME" \
  --protocol HTTP \
  --port 80 \
  --vpc-id "$VPC_ID" \
  --target-type instance \
  --health-check-protocol HTTP \
  --health-check-path "/" \
  --health-check-port traffic-port)
check_command "Failed to create target group"
TARGET_GROUP_ARN=$(echo "$TARGET_GROUP_RESULT" | jq -r '.TargetGroups[0].TargetGroupArn')
echo "Target group created with ARN: $TARGET_GROUP_ARN"

# Create load balancer
echo "Creating load balancer..."
LB_NAME="AppLoadBalancer-$RANDOM_ID"
LB_RESULT=$(aws elbv2 create-load-balancer \
  --name "$LB_NAME" \
  --subnets "$PUBLIC_SUBNET1_ID" "$PUBLIC_SUBNET2_ID" \
  --security-groups "$LB_SG_ID" \
  --tags "Key=Name,Value=$LB_NAME")
check_command "Failed to create load balancer"
LB_ARN=$(echo "$LB_RESULT" | jq -r '.LoadBalancers[0].LoadBalancerArn')
echo "Load balancer created with ARN: $LB_ARN"

# Wait for load balancer to be active
echo "Waiting for load balancer to be active..."
aws elbv2 wait load-balancer-available --load-balancer-arns "$LB_ARN"
check_command "Load balancer did not become available"

# Create listener
echo "Creating listener..."
LISTENER_RESULT=$(aws elbv2 create-listener \
  --load-balancer-arn "$LB_ARN" \
  --protocol HTTP \
  --port 80 \
  --default-actions "Type=forward,TargetGroupArn=$TARGET_GROUP_ARN")
check_command "Failed to create listener"
LISTENER_ARN=$(echo "$LISTENER_RESULT" | jq -r '.Listeners[0].ListenerArn')
echo "Listener created with ARN: $LISTENER_ARN"

# Create Auto Scaling group
echo "Creating Auto Scaling group..."
ASG_NAME="AppAutoScalingGroup-$RANDOM_ID"
aws autoscaling create-auto-scaling-group \
  --auto-scaling-group-name "$ASG_NAME" \
  --launch-template "LaunchTemplateName=$LAUNCH_TEMPLATE_NAME,Version=\$Latest" \
  --min-size 2 \
  --max-size 4 \
  --desired-capacity 2 \
  --vpc-zone-identifier "$PRIVATE_SUBNET1_ID,$PRIVATE_SUBNET2_ID" \
  --target-group-arns "$TARGET_GROUP_ARN" \
  --health-check-type ELB \
  --health-check-grace-period 300 \
  --tags "Key=Name,Value=AppServer-$RANDOM_ID,PropagateAtLaunch=true"
check_command "Failed to create Auto Scaling group"
echo "Auto Scaling group created with name: $ASG_NAME"

# Get load balancer DNS name
LB_DNS_NAME=$(aws elbv2 describe-load-balancers --load-balancer-arns "$LB_ARN" --query 'LoadBalancers[0].DNSName' --output text)
check_command "Failed to get load balancer DNS name"

echo ""
echo "==========================================="
echo "DEPLOYMENT COMPLETE"
echo "==========================================="
echo "VPC ID: $VPC_ID"
echo "Public Subnet 1: $PUBLIC_SUBNET1_ID (AZ: $AZ1)"
echo "Private Subnet 1: $PRIVATE_SUBNET1_ID (AZ: $AZ1)"
echo "Public Subnet 2: $PUBLIC_SUBNET2_ID (AZ: $AZ2)"
echo "Private Subnet 2: $PRIVATE_SUBNET2_ID (AZ: $AZ2)"
echo "NAT Gateway 1: $NAT_GW1_ID"
echo "NAT Gateway 2: $NAT_GW2_ID"
echo "Load Balancer: $LB_NAME"
echo "Auto Scaling Group: $ASG_NAME"
echo ""
echo "Your application will be available at: http://$LB_DNS_NAME"
echo "It may take a few minutes for the instances to launch and pass health checks."
echo ""

# Add health check monitoring
echo "==========================================="
echo "MONITORING INSTANCE HEALTH AND LOAD BALANCER"
echo "==========================================="
echo "Waiting for instances to launch and pass health checks..."
echo "This may take 3-5 minutes. Checking every 30 seconds..."

# Monitor instance health and load balancer accessibility
MAX_ATTEMPTS=10
ATTEMPT=1
HEALTHY_INSTANCES=0

while [ $ATTEMPT -le $MAX_ATTEMPTS ] && [ $HEALTHY_INSTANCES -lt 2 ]; do
  echo "Check attempt $ATTEMPT of $MAX_ATTEMPTS..."
  
  # Check Auto Scaling group instances
  echo "Checking Auto Scaling group instances..."
  ASG_INSTANCES=$(aws autoscaling describe-auto-scaling-groups --auto-scaling-group-names "$ASG_NAME" --query 'AutoScalingGroups[0].Instances[*].[InstanceId,HealthStatus]' --output json)
  echo "ASG Instances status:"
  echo "$ASG_INSTANCES" | jq -r '.[] | "Instance: \(.[0]), Health: \(.[1])"'
  
  # Check target group health
  echo "Checking target group health..."
  TARGET_HEALTH=$(aws elbv2 describe-target-health --target-group-arn "$TARGET_GROUP_ARN" --output json)
  echo "Target health status:"
  echo "$TARGET_HEALTH" | jq -r '.TargetHealthDescriptions[] | "Instance: \(.Target.Id), State: \(.TargetHealth.State), Reason: \(.TargetHealth.Reason // "N/A"), Description: \(.TargetHealth.Description // "N/A")"'
  
  # Count healthy instances
  HEALTHY_INSTANCES=$(echo "$TARGET_HEALTH" | jq -r '[.TargetHealthDescriptions[] | select(.TargetHealth.State=="healthy")] | length')
  echo "Number of healthy instances: $HEALTHY_INSTANCES of 2 expected"
  
  # Check if we have healthy instances
  if [ $HEALTHY_INSTANCES -ge 2 ]; then
    echo "All instances are healthy!"
    
    # Test load balancer accessibility
    echo "Testing load balancer accessibility..."
    HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://$LB_DNS_NAME")
    
    if [ "$HTTP_STATUS" = "200" ]; then
      echo "Load balancer is accessible! HTTP Status: $HTTP_STATUS"
      echo "You can access your application at: http://$LB_DNS_NAME"
      
      # Try to get the content to verify IMDSv2 is working
      echo "Fetching content to verify IMDSv2 functionality..."
      CONTENT=$(curl -s "http://$LB_DNS_NAME")
      echo "Response from server:"
      echo "$CONTENT"
      
      # Check if the content contains the expected pattern
      if [[ "$CONTENT" == *"Hello from"* && "$CONTENT" == *"in"* ]]; then
        echo "IMDSv2 is working correctly! The instance was able to access metadata using the token-based approach."
      else
        echo "Warning: Content doesn't match expected pattern. IMDSv2 functionality could not be verified."
      fi
      
      break
    else
      echo "Load balancer returned HTTP status: $HTTP_STATUS"
      echo "Will try again in 30 seconds..."
    fi
  else
    echo "Waiting for instances to become healthy..."
    echo "Will check again in 30 seconds..."
  fi
  
  ATTEMPT=$((ATTEMPT+1))
  
  if [ $ATTEMPT -le $MAX_ATTEMPTS ]; then
    sleep 30
  fi
done

if [ $HEALTHY_INSTANCES -lt 2 ]; then
  echo "Warning: Not all instances are healthy after maximum attempts."
  echo "You may need to wait longer or check for configuration issues."
fi

echo "To test your application, run:"
echo "curl http://$LB_DNS_NAME"
echo ""
echo "==========================================="
echo "CLEANUP CONFIRMATION"
echo "==========================================="
echo "Do you want to clean up all created resources? (y/n): "
read -r CLEANUP_CHOICE

if [[ "$CLEANUP_CHOICE" =~ ^[Yy]$ ]]; then
  cleanup_resources
  echo "All resources have been deleted."
else
  echo "Resources will not be deleted. You can manually delete them later."
  echo "To delete resources, run this script again and choose to clean up."
fi
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AllocateAddress)
  + [AssociateRouteTable](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AssociateRouteTable)
  + [AttachInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AttachInternetGateway)
  + [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AuthorizeSecurityGroupIngress)
  + [CreateInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateInternetGateway)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateNatGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateNatGateway)
  + [CreateRoute](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateRoute)
  + [CreateRouteTable](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateRouteTable)
  + [CreateSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSecurityGroup)
  + [CreateSubnet](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSubnet)
  + [CreateVpc](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateVpc)
  + [CreateVpcEndpoint](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateVpcEndpoint)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteAutoScalingGroup)
  + [DeleteInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteInternetGateway)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteLoadBalancer)
  + [DeleteNatGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteNatGateway)
  + [DeleteRouteTable](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteRouteTable)
  + [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteSecurityGroup)
  + [DeleteSubnet](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteSubnet)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteTargetGroup)
  + [DeleteVpc](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteVpc)
  + [DeleteVpcEndpoints](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteVpcEndpoints)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeImages](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeImages)
  + [DescribePrefixLists](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribePrefixLists)
  + [DetachInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DetachInternetGateway)
  + [ReleaseAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ReleaseAddress)

### Amazon VPC の使用を開始する
<a name="vpc_GettingStartedCLI_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  アカウントの設定
+ VPC の作成と設定
+ ネットワークを設定する
+ セキュリティの設定
+ リソースのデプロイ
+ テストと検証
+ リソースをクリーンアップする
+ 本番稼働への影響を考慮する
+ セキュリティへの影響を考慮する

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/002-vpc-gs)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# VPC Creation Script
# This script creates a VPC with public and private subnets, internet gateway, NAT gateway, and security groups

# Set up logging
LOG_FILE="vpc_creation.log"
exec > >(tee -a "$LOG_FILE") 2>&1

# Function to handle errors
handle_error() {
  echo "ERROR: $1"
  echo "Resources created before error:"
  for resource in "${CREATED_RESOURCES[@]}"
  do
    echo "- $resource"
  done
  
  echo "Attempting to clean up resources..."
  cleanup_resources
  exit 1
}

# Function to clean up resources
cleanup_resources() {
  echo "Cleaning up resources in reverse order..."
  
  # Reverse the array to delete in reverse order of creation
  for ((i=${#CREATED_RESOURCES[@]}-1; i>=0; i--))
  do
    resource="${CREATED_RESOURCES[$i]}"
    resource_type=$(echo "$resource" | cut -d':' -f1)
    resource_id=$(echo "$resource" | cut -d':' -f2)
    
    case "$resource_type" in
      "INSTANCE")
        echo "Terminating EC2 instance: $resource_id"
        aws ec2 terminate-instances --instance-ids "$resource_id" || echo "Failed to terminate instance: $resource_id"
        # Wait for instance to terminate
        echo "Waiting for instance to terminate..."
        aws ec2 wait instance-terminated --instance-ids "$resource_id" || echo "Failed to wait for instance termination: $resource_id"
        ;;
      "KEY_PAIR")
        echo "Deleting key pair: $resource_id"
        aws ec2 delete-key-pair --key-name "$resource_id" || echo "Failed to delete key pair: $resource_id"
        # Remove the .pem file if it exists
        if [ -f "${resource_id}.pem" ]; then
          rm -f "${resource_id}.pem"
        fi
        ;;
      "NAT_GATEWAY")
        echo "Deleting NAT Gateway: $resource_id"
        aws ec2 delete-nat-gateway --nat-gateway-id "$resource_id" || echo "Failed to delete NAT Gateway: $resource_id"
        # NAT Gateway deletion takes time, wait for it to complete
        echo "Waiting for NAT Gateway to be deleted..."
        aws ec2 wait nat-gateway-deleted --nat-gateway-ids "$resource_id" || echo "Failed to wait for NAT Gateway deletion: $resource_id"
        ;;
      "EIP")
        echo "Releasing Elastic IP: $resource_id"
        aws ec2 release-address --allocation-id "$resource_id" || echo "Failed to release Elastic IP: $resource_id"
        ;;
      "ROUTE_TABLE_ASSOCIATION")
        echo "Disassociating Route Table: $resource_id"
        aws ec2 disassociate-route-table --association-id "$resource_id" || echo "Failed to disassociate Route Table: $resource_id"
        ;;
      "ROUTE_TABLE")
        echo "Deleting Route Table: $resource_id"
        aws ec2 delete-route-table --route-table-id "$resource_id" || echo "Failed to delete Route Table: $resource_id"
        ;;
      "INTERNET_GATEWAY")
        echo "Detaching Internet Gateway: $resource_id from VPC: $VPC_ID"
        aws ec2 detach-internet-gateway --internet-gateway-id "$resource_id" --vpc-id "$VPC_ID" || echo "Failed to detach Internet Gateway: $resource_id"
        echo "Deleting Internet Gateway: $resource_id"
        aws ec2 delete-internet-gateway --internet-gateway-id "$resource_id" || echo "Failed to delete Internet Gateway: $resource_id"
        ;;
      "SECURITY_GROUP")
        echo "Deleting Security Group: $resource_id"
        aws ec2 delete-security-group --group-id "$resource_id" || echo "Failed to delete Security Group: $resource_id"
        ;;
      "SUBNET")
        echo "Deleting Subnet: $resource_id"
        aws ec2 delete-subnet --subnet-id "$resource_id" || echo "Failed to delete Subnet: $resource_id"
        ;;
      "VPC")
        echo "Deleting VPC: $resource_id"
        aws ec2 delete-vpc --vpc-id "$resource_id" || echo "Failed to delete VPC: $resource_id"
        ;;
    esac
  done
}

# Initialize array to track created resources
CREATED_RESOURCES=()

echo "Starting VPC creation script at $(date)"

# Verify AWS CLI configuration
echo "Verifying AWS CLI configuration..."
aws configure list || handle_error "AWS CLI is not properly configured"

# Verify identity and permissions
echo "Verifying identity and permissions..."
if ! aws sts get-caller-identity; then
  echo "ERROR: Unable to verify AWS identity. This could be due to:"
  echo "  - Expired credentials"
  echo "  - Missing or invalid AWS credentials"
  echo "  - Insufficient permissions"
  echo ""
  echo "Please run 'aws configure' to update your credentials or check your IAM permissions."
  exit 1
fi

# Create VPC
echo "Creating VPC with CIDR block 10.0.0.0/16..."
VPC_ID=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=MyVPC}]' --query 'Vpc.VpcId' --output text)

if [ -z "$VPC_ID" ]; then
  handle_error "Failed to create VPC"
fi

CREATED_RESOURCES+=("VPC:$VPC_ID")
echo "VPC created with ID: $VPC_ID"

# Enable DNS support and hostnames
echo "Enabling DNS support and hostnames for VPC..."
aws ec2 modify-vpc-attribute --vpc-id "$VPC_ID" --enable-dns-support || handle_error "Failed to enable DNS support"
aws ec2 modify-vpc-attribute --vpc-id "$VPC_ID" --enable-dns-hostnames || handle_error "Failed to enable DNS hostnames"

# Get available Availability Zones
echo "Getting available Availability Zones..."
AZ1=$(aws ec2 describe-availability-zones --query 'AvailabilityZones[0].ZoneName' --output text)
AZ2=$(aws ec2 describe-availability-zones --query 'AvailabilityZones[1].ZoneName' --output text)

if [ -z "$AZ1" ] || [ -z "$AZ2" ]; then
  handle_error "Failed to get Availability Zones"
fi

echo "Using Availability Zones: $AZ1 and $AZ2"

# Create public subnets
echo "Creating public subnet in $AZ1..."
PUBLIC_SUBNET_AZ1=$(aws ec2 create-subnet \
  --vpc-id "$VPC_ID" \
  --cidr-block 10.0.0.0/24 \
  --availability-zone "$AZ1" \
  --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=Public-Subnet-AZ1}]' \
  --query 'Subnet.SubnetId' \
  --output text)

if [ -z "$PUBLIC_SUBNET_AZ1" ]; then
  handle_error "Failed to create public subnet in AZ1"
fi

CREATED_RESOURCES+=("SUBNET:$PUBLIC_SUBNET_AZ1")
echo "Public subnet created in $AZ1 with ID: $PUBLIC_SUBNET_AZ1"

echo "Creating public subnet in $AZ2..."
PUBLIC_SUBNET_AZ2=$(aws ec2 create-subnet \
  --vpc-id "$VPC_ID" \
  --cidr-block 10.0.1.0/24 \
  --availability-zone "$AZ2" \
  --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=Public-Subnet-AZ2}]' \
  --query 'Subnet.SubnetId' \
  --output text)

if [ -z "$PUBLIC_SUBNET_AZ2" ]; then
  handle_error "Failed to create public subnet in AZ2"
fi

CREATED_RESOURCES+=("SUBNET:$PUBLIC_SUBNET_AZ2")
echo "Public subnet created in $AZ2 with ID: $PUBLIC_SUBNET_AZ2"

# Create private subnets
echo "Creating private subnet in $AZ1..."
PRIVATE_SUBNET_AZ1=$(aws ec2 create-subnet \
  --vpc-id "$VPC_ID" \
  --cidr-block 10.0.2.0/24 \
  --availability-zone "$AZ1" \
  --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=Private-Subnet-AZ1}]' \
  --query 'Subnet.SubnetId' \
  --output text)

if [ -z "$PRIVATE_SUBNET_AZ1" ]; then
  handle_error "Failed to create private subnet in AZ1"
fi

CREATED_RESOURCES+=("SUBNET:$PRIVATE_SUBNET_AZ1")
echo "Private subnet created in $AZ1 with ID: $PRIVATE_SUBNET_AZ1"

echo "Creating private subnet in $AZ2..."
PRIVATE_SUBNET_AZ2=$(aws ec2 create-subnet \
  --vpc-id "$VPC_ID" \
  --cidr-block 10.0.3.0/24 \
  --availability-zone "$AZ2" \
  --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=Private-Subnet-AZ2}]' \
  --query 'Subnet.SubnetId' \
  --output text)

if [ -z "$PRIVATE_SUBNET_AZ2" ]; then
  handle_error "Failed to create private subnet in AZ2"
fi

CREATED_RESOURCES+=("SUBNET:$PRIVATE_SUBNET_AZ2")
echo "Private subnet created in $AZ2 with ID: $PRIVATE_SUBNET_AZ2"

# Create Internet Gateway
echo "Creating Internet Gateway..."
IGW_ID=$(aws ec2 create-internet-gateway \
  --tag-specifications 'ResourceType=internet-gateway,Tags=[{Key=Name,Value=MyIGW}]' \
  --query 'InternetGateway.InternetGatewayId' \
  --output text)

if [ -z "$IGW_ID" ]; then
  handle_error "Failed to create Internet Gateway"
fi

CREATED_RESOURCES+=("INTERNET_GATEWAY:$IGW_ID")
echo "Internet Gateway created with ID: $IGW_ID"

# Attach Internet Gateway to VPC
echo "Attaching Internet Gateway to VPC..."
aws ec2 attach-internet-gateway --internet-gateway-id "$IGW_ID" --vpc-id "$VPC_ID" || handle_error "Failed to attach Internet Gateway to VPC"

# Create public route table
echo "Creating public route table..."
PUBLIC_RT=$(aws ec2 create-route-table \
  --vpc-id "$VPC_ID" \
  --tag-specifications 'ResourceType=route-table,Tags=[{Key=Name,Value=Public-RT}]' \
  --query 'RouteTable.RouteTableId' \
  --output text)

if [ -z "$PUBLIC_RT" ]; then
  handle_error "Failed to create public route table"
fi

CREATED_RESOURCES+=("ROUTE_TABLE:$PUBLIC_RT")
echo "Public route table created with ID: $PUBLIC_RT"

# Add route to Internet Gateway
echo "Adding route to Internet Gateway in public route table..."
aws ec2 create-route --route-table-id "$PUBLIC_RT" --destination-cidr-block 0.0.0.0/0 --gateway-id "$IGW_ID" || handle_error "Failed to add route to Internet Gateway"

# Associate public subnets with public route table
echo "Associating public subnet in $AZ1 with public route table..."
PUBLIC_RT_ASSOC_1=$(aws ec2 associate-route-table --route-table-id "$PUBLIC_RT" --subnet-id "$PUBLIC_SUBNET_AZ1" --query 'AssociationId' --output text)

if [ -z "$PUBLIC_RT_ASSOC_1" ]; then
  handle_error "Failed to associate public subnet in AZ1 with public route table"
fi

CREATED_RESOURCES+=("ROUTE_TABLE_ASSOCIATION:$PUBLIC_RT_ASSOC_1")

echo "Associating public subnet in $AZ2 with public route table..."
PUBLIC_RT_ASSOC_2=$(aws ec2 associate-route-table --route-table-id "$PUBLIC_RT" --subnet-id "$PUBLIC_SUBNET_AZ2" --query 'AssociationId' --output text)

if [ -z "$PUBLIC_RT_ASSOC_2" ]; then
  handle_error "Failed to associate public subnet in AZ2 with public route table"
fi

CREATED_RESOURCES+=("ROUTE_TABLE_ASSOCIATION:$PUBLIC_RT_ASSOC_2")

# Create private route table
echo "Creating private route table..."
PRIVATE_RT=$(aws ec2 create-route-table \
  --vpc-id "$VPC_ID" \
  --tag-specifications 'ResourceType=route-table,Tags=[{Key=Name,Value=Private-RT}]' \
  --query 'RouteTable.RouteTableId' \
  --output text)

if [ -z "$PRIVATE_RT" ]; then
  handle_error "Failed to create private route table"
fi

CREATED_RESOURCES+=("ROUTE_TABLE:$PRIVATE_RT")
echo "Private route table created with ID: $PRIVATE_RT"

# Associate private subnets with private route table
echo "Associating private subnet in $AZ1 with private route table..."
PRIVATE_RT_ASSOC_1=$(aws ec2 associate-route-table --route-table-id "$PRIVATE_RT" --subnet-id "$PRIVATE_SUBNET_AZ1" --query 'AssociationId' --output text)

if [ -z "$PRIVATE_RT_ASSOC_1" ]; then
  handle_error "Failed to associate private subnet in AZ1 with private route table"
fi

CREATED_RESOURCES+=("ROUTE_TABLE_ASSOCIATION:$PRIVATE_RT_ASSOC_1")

echo "Associating private subnet in $AZ2 with private route table..."
PRIVATE_RT_ASSOC_2=$(aws ec2 associate-route-table --route-table-id "$PRIVATE_RT" --subnet-id "$PRIVATE_SUBNET_AZ2" --query 'AssociationId' --output text)

if [ -z "$PRIVATE_RT_ASSOC_2" ]; then
  handle_error "Failed to associate private subnet in AZ2 with private route table"
fi

CREATED_RESOURCES+=("ROUTE_TABLE_ASSOCIATION:$PRIVATE_RT_ASSOC_2")

# Allocate Elastic IP for NAT Gateway
echo "Allocating Elastic IP for NAT Gateway..."
EIP_ALLOC=$(aws ec2 allocate-address --domain vpc --query 'AllocationId' --output text)

if [ -z "$EIP_ALLOC" ]; then
  handle_error "Failed to allocate Elastic IP"
fi

CREATED_RESOURCES+=("EIP:$EIP_ALLOC")
echo "Elastic IP allocated with ID: $EIP_ALLOC"

# Create NAT Gateway
echo "Creating NAT Gateway in public subnet in $AZ1..."
NAT_GW=$(aws ec2 create-nat-gateway \
  --subnet-id "$PUBLIC_SUBNET_AZ1" \
  --allocation-id "$EIP_ALLOC" \
  --tag-specifications 'ResourceType=natgateway,Tags=[{Key=Name,Value=MyNATGateway}]' \
  --query 'NatGateway.NatGatewayId' \
  --output text)

if [ -z "$NAT_GW" ]; then
  handle_error "Failed to create NAT Gateway"
fi

CREATED_RESOURCES+=("NAT_GATEWAY:$NAT_GW")
echo "NAT Gateway created with ID: $NAT_GW"

# Wait for NAT Gateway to be available
echo "Waiting for NAT Gateway to be available..."
aws ec2 wait nat-gateway-available --nat-gateway-ids "$NAT_GW" || handle_error "NAT Gateway did not become available"

# Add route to NAT Gateway in private route table
echo "Adding route to NAT Gateway in private route table..."
aws ec2 create-route --route-table-id "$PRIVATE_RT" --destination-cidr-block 0.0.0.0/0 --nat-gateway-id "$NAT_GW" || handle_error "Failed to add route to NAT Gateway"

# Enable auto-assign public IP for instances in public subnets
echo "Enabling auto-assign public IP for instances in public subnet in $AZ1..."
aws ec2 modify-subnet-attribute --subnet-id "$PUBLIC_SUBNET_AZ1" --map-public-ip-on-launch || handle_error "Failed to enable auto-assign public IP for public subnet in AZ1"

echo "Enabling auto-assign public IP for instances in public subnet in $AZ2..."
aws ec2 modify-subnet-attribute --subnet-id "$PUBLIC_SUBNET_AZ2" --map-public-ip-on-launch || handle_error "Failed to enable auto-assign public IP for public subnet in AZ2"

# Create security group for web servers
echo "Creating security group for web servers..."
WEB_SG=$(aws ec2 create-security-group \
  --group-name "WebServerSG-$(date +%s)" \
  --description "Security group for web servers" \
  --vpc-id "$VPC_ID" \
  --query 'GroupId' \
  --output text)

if [ -z "$WEB_SG" ]; then
  handle_error "Failed to create security group for web servers"
fi

CREATED_RESOURCES+=("SECURITY_GROUP:$WEB_SG")
echo "Security group for web servers created with ID: $WEB_SG"

# Allow HTTP and HTTPS traffic
echo "Allowing HTTP traffic to web servers security group..."
aws ec2 authorize-security-group-ingress --group-id "$WEB_SG" --protocol tcp --port 80 --cidr 0.0.0.0/0 || handle_error "Failed to allow HTTP traffic"

echo "Allowing HTTPS traffic to web servers security group..."
aws ec2 authorize-security-group-ingress --group-id "$WEB_SG" --protocol tcp --port 443 --cidr 0.0.0.0/0 || handle_error "Failed to allow HTTPS traffic"

# Note: In a production environment, you should restrict the source IP ranges for security
echo "NOTE: In a production environment, you should restrict the source IP ranges for HTTP and HTTPS traffic"

# Create security group for database servers
echo "Creating security group for database servers..."
DB_SG=$(aws ec2 create-security-group \
  --group-name "DBServerSG-$(date +%s)" \
  --description "Security group for database servers" \
  --vpc-id "$VPC_ID" \
  --query 'GroupId' \
  --output text)

if [ -z "$DB_SG" ]; then
  handle_error "Failed to create security group for database servers"
fi

CREATED_RESOURCES+=("SECURITY_GROUP:$DB_SG")
echo "Security group for database servers created with ID: $DB_SG"

# Allow MySQL/Aurora traffic from web servers only
echo "Allowing MySQL/Aurora traffic from web servers to database servers..."
aws ec2 authorize-security-group-ingress --group-id "$DB_SG" --protocol tcp --port 3306 --source-group "$WEB_SG" || handle_error "Failed to allow MySQL/Aurora traffic"

# Verify VPC configuration
echo "Verifying VPC configuration..."
echo "VPC:"
aws ec2 describe-vpcs --vpc-id "$VPC_ID" || handle_error "Failed to describe VPC"

echo "Subnets:"
aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC_ID" || handle_error "Failed to describe subnets"

echo "Route tables:"
aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$VPC_ID" || handle_error "Failed to describe route tables"

echo "Internet gateway:"
aws ec2 describe-internet-gateways --filters "Name=attachment.vpc-id,Values=$VPC_ID" || handle_error "Failed to describe Internet Gateway"

echo "NAT gateway:"
aws ec2 describe-nat-gateways --filter "Name=vpc-id,Values=$VPC_ID" || handle_error "Failed to describe NAT Gateway"

echo "Security groups:"
aws ec2 describe-security-groups --filters "Name=vpc-id,Values=$VPC_ID" || handle_error "Failed to describe security groups"

echo ""
# Summary of created resources
echo "VPC creation completed successfully!"
echo "Summary of created resources:"
echo "- VPC: $VPC_ID"
echo "- Public Subnet in $AZ1: $PUBLIC_SUBNET_AZ1"
echo "- Public Subnet in $AZ2: $PUBLIC_SUBNET_AZ2"
echo "- Private Subnet in $AZ1: $PRIVATE_SUBNET_AZ1"
echo "- Private Subnet in $AZ2: $PRIVATE_SUBNET_AZ2"
echo "- Internet Gateway: $IGW_ID"
echo "- Public Route Table: $PUBLIC_RT"
echo "- Private Route Table: $PRIVATE_RT"
echo "- Elastic IP: $EIP_ALLOC"
echo "- NAT Gateway: $NAT_GW"
echo "- Web Servers Security Group: $WEB_SG"
echo "- Database Servers Security Group: $DB_SG"

# Deploy EC2 instances
echo ""
echo "Deploying EC2 instances..."

# Create key pair for SSH access
KEY_NAME="vpc-tutorial-key-$(date +%s)"
echo "Creating key pair $KEY_NAME..."
aws ec2 create-key-pair --key-name "$KEY_NAME" --query 'KeyMaterial' --output text > "${KEY_NAME}.pem" || handle_error "Failed to create key pair"
chmod 400 "${KEY_NAME}.pem"
echo "Key pair saved to ${KEY_NAME}.pem"
CREATED_RESOURCES+=("KEY_PAIR:$KEY_NAME")

# Get latest Amazon Linux 2 AMI
echo "Getting latest Amazon Linux 2 AMI..."
AMI_ID=$(aws ec2 describe-images --owners amazon \
  --filters "Name=name,Values=amzn2-ami-hvm-*-x86_64-gp2" "Name=state,Values=available" \
  --query "sort_by(Images, &CreationDate)[-1].ImageId" --output text) || handle_error "Failed to get AMI"
echo "Using AMI: $AMI_ID"

# Launch web server in public subnet
echo "Launching web server in public subnet..."
WEB_INSTANCE=$(aws ec2 run-instances \
  --image-id "$AMI_ID" \
  --count 1 \
  --instance-type t2.micro \
  --key-name "$KEY_NAME" \
  --security-group-ids "$WEB_SG" \
  --subnet-id "$PUBLIC_SUBNET_AZ1" \
  --associate-public-ip-address \
  --user-data '#!/bin/bash
    yum update -y
    yum install -y httpd
    systemctl start httpd
    systemctl enable httpd
    echo "<h1>Hello from $(hostname -f) in the public subnet</h1>" > /var/www/html/index.html' \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=WebServer}]' \
  --query 'Instances[0].InstanceId' \
  --output text) || handle_error "Failed to launch web server"
echo "Web server instance created with ID: $WEB_INSTANCE"
CREATED_RESOURCES+=("INSTANCE:$WEB_INSTANCE")

# Wait for web server to be running
echo "Waiting for web server to be running..."
aws ec2 wait instance-running --instance-ids "$WEB_INSTANCE"

# Get web server public IP
WEB_PUBLIC_IP=$(aws ec2 describe-instances --instance-ids "$WEB_INSTANCE" \
  --query 'Reservations[0].Instances[0].PublicIpAddress' --output text)
echo "Web server public IP: $WEB_PUBLIC_IP"
echo "You can access the web server at: http://$WEB_PUBLIC_IP"

# Launch database server in private subnet
echo "Launching database server in private subnet..."
DB_INSTANCE=$(aws ec2 run-instances \
  --image-id "$AMI_ID" \
  --count 1 \
  --instance-type t2.micro \
  --key-name "$KEY_NAME" \
  --security-group-ids "$DB_SG" \
  --subnet-id "$PRIVATE_SUBNET_AZ1" \
  --user-data '#!/bin/bash
    yum update -y
    yum install -y mariadb-server
    systemctl start mariadb
    systemctl enable mariadb' \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=DBServer}]' \
  --query 'Instances[0].InstanceId' \
  --output text) || handle_error "Failed to launch database server"
echo "Database server instance created with ID: $DB_INSTANCE"
CREATED_RESOURCES+=("INSTANCE:$DB_INSTANCE")

# Wait for database server to be running
echo "Waiting for database server to be running..."
aws ec2 wait instance-running --instance-ids "$DB_INSTANCE"

# Get database server private IP
DB_PRIVATE_IP=$(aws ec2 describe-instances --instance-ids "$DB_INSTANCE" \
  --query 'Reservations[0].Instances[0].PrivateIpAddress' --output text)
echo "Database server private IP: $DB_PRIVATE_IP"

echo "EC2 instances deployed successfully!"
echo "- Web Server (Public): $WEB_INSTANCE ($WEB_PUBLIC_IP)"
echo "- Database Server (Private): $DB_INSTANCE ($DB_PRIVATE_IP)"
echo ""
echo "Note: To connect to the web server: ssh -i ${KEY_NAME}.pem ec2-user@$WEB_PUBLIC_IP"
echo "To connect to the database server, you must first connect to the web server, then use it as a bastion host."
echo "==========================================="
echo "CLEANUP CONFIRMATION"
echo "==========================================="
echo "Do you want to clean up all created resources? (y/n): "
read -r CLEANUP_CHOICE
if [[ "$CLEANUP_CHOICE" =~ ^[Yy]$ ]]; then
  echo "Cleaning up resources..."
  cleanup_resources
  echo "All resources have been cleaned up."
else
  echo "Resources will not be cleaned up. You can manually clean them up later."
fi

echo "Script completed at $(date)"
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AllocateAddress)
  + [AssociateRouteTable](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AssociateRouteTable)
  + [AttachInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AttachInternetGateway)
  + [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/AuthorizeSecurityGroupIngress)
  + [CreateInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateInternetGateway)
  + [CreateKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateKeyPair)
  + [CreateNatGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateNatGateway)
  + [CreateRoute](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateRoute)
  + [CreateRouteTable](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateRouteTable)
  + [CreateSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSecurityGroup)
  + [CreateSubnet](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSubnet)
  + [CreateVpc](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateVpc)
  + [DeleteInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteInternetGateway)
  + [DeleteKeyPair](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteKeyPair)
  + [DeleteNatGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteNatGateway)
  + [DeleteRouteTable](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteRouteTable)
  + [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteSecurityGroup)
  + [DeleteSubnet](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteSubnet)
  + [DeleteVpc](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteVpc)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeImages](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeImages)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInstances)
  + [DescribeInternetGateways](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeInternetGateways)
  + [DescribeNatGateways](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeNatGateways)
  + [DescribeRouteTables](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeRouteTables)
  + [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeSecurityGroups)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeSubnets)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeVpcs)
  + [DetachInternetGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DetachInternetGateway)
  + [DisassociateRouteTable](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DisassociateRouteTable)
  + [ModifySubnetAttribute](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ModifySubnetAttribute)
  + [ModifyVpcAttribute](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ModifyVpcAttribute)
  + [ReleaseAddress](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ReleaseAddress)
  + [RunInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/RunInstances)
  + [TerminateInstances](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/TerminateInstances)

### Transit Gateway を開始する
<a name="vpc_TransitGatewayGettingStarted_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ DNS サポートとデフォルトのルートテーブル設定を使用して Transit Gateway を作成する
+ Transit Gateway が使用可能になるまで待機する
+ サブネットを使用して Transit Gateway に 2 つの VPC をアタッチする
+ VPC アタッチメントが使用可能になるまで待機する
+ Transit Gateway を介して VPC の間にルートを追加する
+ VPC リソース間の接続をテストする
+ ルート、アタッチメント、Transit Gateway などのリソースをクリーンアップする

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/012-transitgateway-gettingstarted)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# Amazon VPC Transit Gateway CLI Script
# This script demonstrates how to create a transit gateway and connect two VPCs
# Modified to work with older AWS CLI versions that don't support transit gateway wait commands

# Error handling
set -e
LOG_FILE="transit-gateway-tutorial.log"
exec > >(tee -a "$LOG_FILE") 2>&1

# Function to wait for transit gateway to be available
wait_for_tgw() {
  local tgw_id=$1
  echo "Waiting for Transit Gateway $tgw_id to become available..."
  
  while true; do
    status=$(aws ec2 describe-transit-gateways --transit-gateway-ids "$tgw_id" --query "TransitGateways[0].State" --output text)
    echo "Current status: $status"
    
    if [ "$status" = "available" ]; then
      echo "Transit Gateway is now available"
      break
    fi
    
    echo "Waiting for transit gateway to become available. Current state: $status"
    sleep 10
  done
}

# Function to wait for transit gateway attachment to be available
wait_for_tgw_attachment() {
  local attachment_id=$1
  echo "Waiting for Transit Gateway Attachment $attachment_id to become available..."
  
  while true; do
    status=$(aws ec2 describe-transit-gateway-vpc-attachments --transit-gateway-attachment-ids "$attachment_id" --query "TransitGatewayVpcAttachments[0].State" --output text)
    echo "Current status: $status"
    
    if [ "$status" = "available" ]; then
      echo "Transit Gateway Attachment is now available"
      break
    fi
    
    echo "Waiting for transit gateway attachment to become available. Current state: $status"
    sleep 10
  done
}

# Function to wait for transit gateway attachment to be deleted
wait_for_tgw_attachment_deleted() {
  local attachment_id=$1
  echo "Waiting for Transit Gateway Attachment $attachment_id to be deleted..."
  
  while true; do
    # Check if the attachment still exists
    count=$(aws ec2 describe-transit-gateway-vpc-attachments --filters "Name=transit-gateway-attachment-id,Values=$attachment_id" --query "length(TransitGatewayVpcAttachments)" --output text)
    
    if [ "$count" = "0" ]; then
      echo "Transit Gateway Attachment has been deleted"
      break
    fi
    
    status=$(aws ec2 describe-transit-gateway-vpc-attachments --transit-gateway-attachment-ids "$attachment_id" --query "TransitGatewayVpcAttachments[0].State" --output text 2>/dev/null || echo "deleted")
    
    if [ "$status" = "deleted" ]; then
      echo "Transit Gateway Attachment has been deleted"
      break
    fi
    
    echo "Waiting for transit gateway attachment to be deleted. Current state: $status"
    sleep 10
  done
}

# Function to clean up resources
cleanup() {
  echo "Error occurred. Cleaning up resources..."
  
  # Delete resources in reverse order
  if [ ! -z "$TGW_ATTACHMENT_1_ID" ]; then
    echo "Deleting Transit Gateway VPC Attachment 1: $TGW_ATTACHMENT_1_ID"
    aws ec2 delete-transit-gateway-vpc-attachment --transit-gateway-attachment-id "$TGW_ATTACHMENT_1_ID" || true
    wait_for_tgw_attachment_deleted "$TGW_ATTACHMENT_1_ID" || true
  fi
  
  if [ ! -z "$TGW_ATTACHMENT_2_ID" ]; then
    echo "Deleting Transit Gateway VPC Attachment 2: $TGW_ATTACHMENT_2_ID"
    aws ec2 delete-transit-gateway-vpc-attachment --transit-gateway-attachment-id "$TGW_ATTACHMENT_2_ID" || true
    wait_for_tgw_attachment_deleted "$TGW_ATTACHMENT_2_ID" || true
  fi
  
  if [ ! -z "$TGW_ID" ]; then
    echo "Deleting Transit Gateway: $TGW_ID"
    aws ec2 delete-transit-gateway --transit-gateway-id "$TGW_ID" || true
  fi
  
  exit 1
}

# Set up trap for error handling
trap cleanup ERR

echo "=== Amazon VPC Transit Gateway Tutorial ==="
echo "This script will create a transit gateway and connect two VPCs"
echo ""

# Get a valid availability zone dynamically
echo "Getting available AZ in current region..."
AZ=$(aws ec2 describe-availability-zones --query "AvailabilityZones[0].ZoneName" --output text)
echo "Using availability zone: $AZ"

# Check if VPCs exist
echo "Checking for existing VPCs..."
VPC1_ID=$(aws ec2 describe-vpcs --filters "Name=tag:Name,Values=VPC1" --query "Vpcs[0].VpcId" --output text)
VPC2_ID=$(aws ec2 describe-vpcs --filters "Name=tag:Name,Values=VPC2" --query "Vpcs[0].VpcId" --output text)

if [ "$VPC1_ID" == "None" ] || [ -z "$VPC1_ID" ]; then
  echo "Creating VPC1..."
  VPC1_ID=$(aws ec2 create-vpc --cidr-block 10.1.0.0/16 --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=VPC1}]' --query Vpc.VpcId --output text)
  echo "Created VPC1: $VPC1_ID"
  
  # Create a subnet in VPC1
  echo "Creating subnet in VPC1..."
  SUBNET1_ID=$(aws ec2 create-subnet --vpc-id "$VPC1_ID" --cidr-block 10.1.0.0/24 --availability-zone "$AZ" --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=VPC1-Subnet}]' --query Subnet.SubnetId --output text)
  echo "Created subnet in VPC1: $SUBNET1_ID"
else
  echo "Using existing VPC1: $VPC1_ID"
  SUBNET1_ID=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC1_ID" --query "Subnets[0].SubnetId" --output text)
  if [ "$SUBNET1_ID" == "None" ] || [ -z "$SUBNET1_ID" ]; then
    echo "Creating subnet in VPC1..."
    SUBNET1_ID=$(aws ec2 create-subnet --vpc-id "$VPC1_ID" --cidr-block 10.1.0.0/24 --availability-zone "$AZ" --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=VPC1-Subnet}]' --query Subnet.SubnetId --output text)
    echo "Created subnet in VPC1: $SUBNET1_ID"
  else
    echo "Using existing subnet in VPC1: $SUBNET1_ID"
  fi
fi

if [ "$VPC2_ID" == "None" ] || [ -z "$VPC2_ID" ]; then
  echo "Creating VPC2..."
  VPC2_ID=$(aws ec2 create-vpc --cidr-block 10.2.0.0/16 --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=VPC2}]' --query Vpc.VpcId --output text)
  echo "Created VPC2: $VPC2_ID"
  
  # Create a subnet in VPC2
  echo "Creating subnet in VPC2..."
  SUBNET2_ID=$(aws ec2 create-subnet --vpc-id "$VPC2_ID" --cidr-block 10.2.0.0/24 --availability-zone "$AZ" --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=VPC2-Subnet}]' --query Subnet.SubnetId --output text)
  echo "Created subnet in VPC2: $SUBNET2_ID"
else
  echo "Using existing VPC2: $VPC2_ID"
  SUBNET2_ID=$(aws ec2 describe-subnets --filters "Name=vpc-id,Values=$VPC2_ID" --query "Subnets[0].SubnetId" --output text)
  if [ "$SUBNET2_ID" == "None" ] || [ -z "$SUBNET2_ID" ]; then
    echo "Creating subnet in VPC2..."
    SUBNET2_ID=$(aws ec2 create-subnet --vpc-id "$VPC2_ID" --cidr-block 10.2.0.0/24 --availability-zone "$AZ" --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=VPC2-Subnet}]' --query Subnet.SubnetId --output text)
    echo "Created subnet in VPC2: $SUBNET2_ID"
  else
    echo "Using existing subnet in VPC2: $SUBNET2_ID"
  fi
fi

# Get route tables for each VPC
RTB1_ID=$(aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$VPC1_ID" --query "RouteTables[0].RouteTableId" --output text)
RTB2_ID=$(aws ec2 describe-route-tables --filters "Name=vpc-id,Values=$VPC2_ID" --query "RouteTables[0].RouteTableId" --output text)

echo "Route table for VPC1: $RTB1_ID"
echo "Route table for VPC2: $RTB2_ID"

# Step 1: Create the transit gateway
echo "Creating Transit Gateway..."
TGW_ID=$(aws ec2 create-transit-gateway \
  --description "My Transit Gateway" \
  --options AmazonSideAsn=64512,AutoAcceptSharedAttachments=disable,DefaultRouteTableAssociation=enable,DefaultRouteTablePropagation=enable,VpnEcmpSupport=enable,DnsSupport=enable,MulticastSupport=disable \
  --tag-specifications 'ResourceType=transit-gateway,Tags=[{Key=Name,Value=MyTransitGateway}]' \
  --query TransitGateway.TransitGatewayId \
  --output text)

echo "Created Transit Gateway: $TGW_ID"

# Wait for the transit gateway to become available
wait_for_tgw "$TGW_ID"

# Step 2: Attach VPCs to the transit gateway
echo "Attaching VPC1 to Transit Gateway..."
TGW_ATTACHMENT_1_ID=$(aws ec2 create-transit-gateway-vpc-attachment \
  --transit-gateway-id "$TGW_ID" \
  --vpc-id "$VPC1_ID" \
  --subnet-ids "$SUBNET1_ID" \
  --tag-specifications 'ResourceType=transit-gateway-attachment,Tags=[{Key=Name,Value=VPC1-Attachment}]' \
  --query TransitGatewayVpcAttachment.TransitGatewayAttachmentId \
  --output text)

echo "Created Transit Gateway VPC Attachment for VPC1: $TGW_ATTACHMENT_1_ID"

echo "Attaching VPC2 to Transit Gateway..."
TGW_ATTACHMENT_2_ID=$(aws ec2 create-transit-gateway-vpc-attachment \
  --transit-gateway-id "$TGW_ID" \
  --vpc-id "$VPC2_ID" \
  --subnet-ids "$SUBNET2_ID" \
  --tag-specifications 'ResourceType=transit-gateway-attachment,Tags=[{Key=Name,Value=VPC2-Attachment}]' \
  --query TransitGatewayVpcAttachment.TransitGatewayAttachmentId \
  --output text)

echo "Created Transit Gateway VPC Attachment for VPC2: $TGW_ATTACHMENT_2_ID"

# Wait for the attachments to become available
wait_for_tgw_attachment "$TGW_ATTACHMENT_1_ID"
wait_for_tgw_attachment "$TGW_ATTACHMENT_2_ID"

# Step 3: Add routes between the transit gateway and VPCs
echo "Adding route from VPC1 to VPC2 via Transit Gateway..."
aws ec2 create-route \
  --route-table-id "$RTB1_ID" \
  --destination-cidr-block 10.2.0.0/16 \
  --transit-gateway-id "$TGW_ID"

echo "Adding route from VPC2 to VPC1 via Transit Gateway..."
aws ec2 create-route \
  --route-table-id "$RTB2_ID" \
  --destination-cidr-block 10.1.0.0/16 \
  --transit-gateway-id "$TGW_ID"

echo "Routes added successfully"

# Step 4: Display information for testing
echo ""
echo "=== Transit Gateway Setup Complete ==="
echo "Transit Gateway ID: $TGW_ID"
echo "VPC1 ID: $VPC1_ID"
echo "VPC2 ID: $VPC2_ID"
echo ""
echo "To test connectivity:"
echo "1. Launch an EC2 instance in each VPC"
echo "2. Configure security groups to allow ICMP traffic"
echo "3. Connect to one instance and ping the other instance's private IP"
echo ""

# Prompt user before cleanup
read -p "Press Enter to view created resources, or Ctrl+C to exit without cleanup..."

echo ""
echo "=== Resources Created ==="
echo "Transit Gateway: $TGW_ID"
echo "VPC1: $VPC1_ID"
echo "VPC2: $VPC2_ID"
echo "Subnet in VPC1: $SUBNET1_ID"
echo "Subnet in VPC2: $SUBNET2_ID"
echo "Transit Gateway Attachment for VPC1: $TGW_ATTACHMENT_1_ID"
echo "Transit Gateway Attachment for VPC2: $TGW_ATTACHMENT_2_ID"
echo ""

read -p "Do you want to clean up these resources? (y/n): " CLEANUP_CONFIRM
if [[ $CLEANUP_CONFIRM == "y" || $CLEANUP_CONFIRM == "Y" ]]; then
  echo "Starting cleanup..."
  
  # Delete routes
  echo "Deleting routes..."
  aws ec2 delete-route --route-table-id "$RTB1_ID" --destination-cidr-block 10.2.0.0/16
  aws ec2 delete-route --route-table-id "$RTB2_ID" --destination-cidr-block 10.1.0.0/16
  
  # Delete transit gateway attachments
  echo "Deleting Transit Gateway VPC Attachment for VPC1: $TGW_ATTACHMENT_1_ID"
  aws ec2 delete-transit-gateway-vpc-attachment --transit-gateway-attachment-id "$TGW_ATTACHMENT_1_ID"
  
  echo "Deleting Transit Gateway VPC Attachment for VPC2: $TGW_ATTACHMENT_2_ID"
  aws ec2 delete-transit-gateway-vpc-attachment --transit-gateway-attachment-id "$TGW_ATTACHMENT_2_ID"
  
  # Wait for attachments to be deleted
  wait_for_tgw_attachment_deleted "$TGW_ATTACHMENT_1_ID"
  wait_for_tgw_attachment_deleted "$TGW_ATTACHMENT_2_ID"
  
  # Delete transit gateway
  echo "Deleting Transit Gateway: $TGW_ID"
  aws ec2 delete-transit-gateway --transit-gateway-id "$TGW_ID"
  
  echo "Cleanup completed successfully"
else
  echo "Skipping cleanup. Resources will continue to incur charges until manually deleted."
fi

echo "Tutorial completed. See $LOG_FILE for detailed logs."
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateRoute](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateRoute)
  + [CreateSubnet](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateSubnet)
  + [CreateTransitGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateTransitGateway)
  + [CreateTransitGatewayVpcAttachment](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateTransitGatewayVpcAttachment)
  + [CreateVpc](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateVpc)
  + [DeleteRoute](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteRoute)
  + [DeleteTransitGateway](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteTransitGateway)
  + [DeleteTransitGatewayVpcAttachment](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteTransitGatewayVpcAttachment)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeRouteTables](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeRouteTables)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTransitGatewayAttachments](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeTransitGatewayAttachments)
  + [DescribeTransitGatewayVpcAttachments](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeTransitGatewayVpcAttachments)
  + [DescribeTransitGateways](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeTransitGateways)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeVpcs)

### VPC IPAM の開始方法
<a name="vpc_GettingStartedIpam_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ CLI を使用して Amazon VPC IP Address Manager (IPAM) をセットアップおよび設定します。
+ オペレーションリージョン (例: us-east-1、us-west-2) がある IPAM を作成します。
+ IPAM のプライベートスコープ ID を取得します。
+ IPv4 プール (最上位、リージョン、開発プール) の階層構造を作成します。
+ CIDR ブロックを各プールにプロビジョニングします (例: 10.0.0.0/8、10.0.0.0/16、10.0.0.0/24)。
+ IPAM プールから割り当てられた CIDR を使用して VPC を作成します。
+ IPAM プールの割り当てと VPC の作成を確認します。
+ アクセス許可エラー、CIDR 割り当ての失敗、依存関係違反などの一般的な問題をトラブルシューティングします。
+ 不要な料金が発生しないように、IPAM リソース (VPC、プール、CIDR、IPAM) をクリーンアップします。
+ 高度な IPAM 機能の次のステップについて説明します。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/009-vpc-ipam-gs)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# IPAM Getting Started CLI Script - Version 7
# This script creates an IPAM, creates a hierarchy of IP address pools, and allocates a CIDR to a VPC
# Fixed to correctly identify the private scope ID, wait for resources to be available, add locale to development pool,
# use the correct parameter names for VPC creation, and wait for CIDR provisioning to complete

# Set up logging
LOG_FILE="ipam_script.log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "Starting IPAM setup script at $(date)"
echo "All commands and outputs will be logged to $LOG_FILE"

# Function to handle errors
handle_error() {
    echo "ERROR: $1"
    echo "Attempting to clean up resources..."
    cleanup_resources
    exit 1
}

# Function to clean up resources
cleanup_resources() {
    echo ""
    echo "==========================================="
    echo "RESOURCES CREATED:"
    echo "==========================================="
    
    if [ -n "$VPC_ID" ]; then
        echo "VPC: $VPC_ID"
    fi
    
    if [ -n "$DEV_POOL_ID" ]; then
        echo "Development Pool: $DEV_POOL_ID"
    fi
    
    if [ -n "$REGIONAL_POOL_ID" ]; then
        echo "Regional Pool: $REGIONAL_POOL_ID"
    fi
    
    if [ -n "$TOP_POOL_ID" ]; then
        echo "Top-level Pool: $TOP_POOL_ID"
    fi
    
    if [ -n "$IPAM_ID" ]; then
        echo "IPAM: $IPAM_ID"
    fi
    
    echo ""
    echo "==========================================="
    echo "CLEANUP CONFIRMATION"
    echo "==========================================="
    echo "Do you want to clean up all created resources? (y/n): "
    read -r CLEANUP_CHOICE
    
    if [[ "$CLEANUP_CHOICE" =~ ^[Yy]$ ]]; then
        echo "Starting cleanup..."
        
        # Delete resources in reverse order of creation to handle dependencies
        
        if [ -n "$VPC_ID" ]; then
            echo "Deleting VPC: $VPC_ID"
            aws ec2 delete-vpc --vpc-id "$VPC_ID" || echo "Failed to delete VPC"
            echo "Waiting for VPC to be deleted..."
            sleep 10
        fi
        
        if [ -n "$DEV_POOL_ID" ]; then
            echo "Deleting Development Pool: $DEV_POOL_ID"
            # First deprovision any CIDRs from the pool
            CIDRS=$(aws ec2 get-ipam-pool-cidrs --ipam-pool-id "$DEV_POOL_ID" --query 'IpamPoolCidrs[].Cidr' --output text)
            for CIDR in $CIDRS; do
                echo "Deprovisioning CIDR $CIDR from Development Pool"
                aws ec2 deprovision-ipam-pool-cidr --ipam-pool-id "$DEV_POOL_ID" --cidr "$CIDR" || echo "Failed to deprovision CIDR $CIDR"
                sleep 5
            done
            aws ec2 delete-ipam-pool --ipam-pool-id "$DEV_POOL_ID" || echo "Failed to delete Development Pool"
            echo "Waiting for Development Pool to be deleted..."
            sleep 10
        fi
        
        if [ -n "$REGIONAL_POOL_ID" ]; then
            echo "Deleting Regional Pool: $REGIONAL_POOL_ID"
            # First deprovision any CIDRs from the pool
            CIDRS=$(aws ec2 get-ipam-pool-cidrs --ipam-pool-id "$REGIONAL_POOL_ID" --query 'IpamPoolCidrs[].Cidr' --output text)
            for CIDR in $CIDRS; do
                echo "Deprovisioning CIDR $CIDR from Regional Pool"
                aws ec2 deprovision-ipam-pool-cidr --ipam-pool-id "$REGIONAL_POOL_ID" --cidr "$CIDR" || echo "Failed to deprovision CIDR $CIDR"
                sleep 5
            done
            aws ec2 delete-ipam-pool --ipam-pool-id "$REGIONAL_POOL_ID" || echo "Failed to delete Regional Pool"
            echo "Waiting for Regional Pool to be deleted..."
            sleep 10
        fi
        
        if [ -n "$TOP_POOL_ID" ]; then
            echo "Deleting Top-level Pool: $TOP_POOL_ID"
            # First deprovision any CIDRs from the pool
            CIDRS=$(aws ec2 get-ipam-pool-cidrs --ipam-pool-id "$TOP_POOL_ID" --query 'IpamPoolCidrs[].Cidr' --output text)
            for CIDR in $CIDRS; do
                echo "Deprovisioning CIDR $CIDR from Top-level Pool"
                aws ec2 deprovision-ipam-pool-cidr --ipam-pool-id "$TOP_POOL_ID" --cidr "$CIDR" || echo "Failed to deprovision CIDR $CIDR"
                sleep 5
            done
            aws ec2 delete-ipam-pool --ipam-pool-id "$TOP_POOL_ID" || echo "Failed to delete Top-level Pool"
            echo "Waiting for Top-level Pool to be deleted..."
            sleep 10
        fi
        
        if [ -n "$IPAM_ID" ]; then
            echo "Deleting IPAM: $IPAM_ID"
            aws ec2 delete-ipam --ipam-id "$IPAM_ID" || echo "Failed to delete IPAM"
        fi
        
        echo "Cleanup completed."
    else
        echo "Cleanup skipped. Resources will remain in your account."
    fi
}

# Function to wait for a pool to be in the 'create-complete' state
wait_for_pool() {
    local pool_id=$1
    local max_attempts=30
    local attempt=1
    local state=""
    
    echo "Waiting for pool $pool_id to be available..."
    
    while [ $attempt -le $max_attempts ]; do
        state=$(aws ec2 describe-ipam-pools --ipam-pool-ids "$pool_id" --query 'IpamPools[0].State' --output text)
        
        if [ "$state" = "create-complete" ]; then
            echo "Pool $pool_id is now available (state: $state)"
            return 0
        fi
        
        echo "Attempt $attempt/$max_attempts: Pool $pool_id is in state: $state. Waiting..."
        sleep 10
        ((attempt++))
    done
    
    echo "Timed out waiting for pool $pool_id to be available"
    return 1
}

# Function to wait for a CIDR to be fully provisioned
wait_for_cidr_provisioning() {
    local pool_id=$1
    local cidr=$2
    local max_attempts=30
    local attempt=1
    local state=""
    
    echo "Waiting for CIDR $cidr to be fully provisioned in pool $pool_id..."
    
    while [ $attempt -le $max_attempts ]; do
        state=$(aws ec2 get-ipam-pool-cidrs --ipam-pool-id "$pool_id" --query "IpamPoolCidrs[?Cidr=='$cidr'].State" --output text)
        
        if [ "$state" = "provisioned" ]; then
            echo "CIDR $cidr is now fully provisioned (state: $state)"
            return 0
        fi
        
        echo "Attempt $attempt/$max_attempts: CIDR $cidr is in state: $state. Waiting..."
        sleep 10
        ((attempt++))
    done
    
    echo "Timed out waiting for CIDR $cidr to be provisioned"
    return 1
}

# Step 1: Create an IPAM
echo "Creating IPAM..."
IPAM_RESULT=$(aws ec2 create-ipam \
    --description "My IPAM" \
    --operating-regions RegionName=us-east-1 RegionName=us-west-2)

if [ $? -ne 0 ]; then
    handle_error "Failed to create IPAM"
fi

IPAM_ID=$(echo "$IPAM_RESULT" | grep -o '"IpamId": "[^"]*' | cut -d'"' -f4)
echo "IPAM created with ID: $IPAM_ID"

# Wait for IPAM to be created and available
echo "Waiting for IPAM to be available..."
sleep 20

# Step 2: Get the IPAM Scope ID - FIXED to correctly identify the private scope
echo "Getting IPAM Scope ID..."
SCOPE_RESULT=$(aws ec2 describe-ipams --ipam-id "$IPAM_ID")

if [ $? -ne 0 ]; then
    handle_error "Failed to get IPAM details"
fi

# Extract the private scope ID directly from the IPAM details
PRIVATE_SCOPE_ID=$(echo "$SCOPE_RESULT" | grep -o '"PrivateDefaultScopeId": "[^"]*' | cut -d'"' -f4)
echo "Private Scope ID: $PRIVATE_SCOPE_ID"

if [ -z "$PRIVATE_SCOPE_ID" ]; then
    handle_error "Failed to get Private Scope ID"
fi

# Step 3: Create a Top-Level IPv4 Pool
echo "Creating Top-level IPv4 Pool..."
TOP_POOL_RESULT=$(aws ec2 create-ipam-pool \
    --ipam-scope-id "$PRIVATE_SCOPE_ID" \
    --address-family ipv4 \
    --description "Top-level pool")

if [ $? -ne 0 ]; then
    handle_error "Failed to create Top-level Pool"
fi

TOP_POOL_ID=$(echo "$TOP_POOL_RESULT" | grep -o '"IpamPoolId": "[^"]*' | cut -d'"' -f4)
echo "Top-level Pool created with ID: $TOP_POOL_ID"

# Wait for the top-level pool to be available
if ! wait_for_pool "$TOP_POOL_ID"; then
    handle_error "Top-level Pool did not become available in time"
fi

# Provision CIDR to the top-level pool
echo "Provisioning CIDR to Top-level Pool..."
TOP_POOL_CIDR="10.0.0.0/8"
PROVISION_RESULT=$(aws ec2 provision-ipam-pool-cidr \
    --ipam-pool-id "$TOP_POOL_ID" \
    --cidr "$TOP_POOL_CIDR")

if [ $? -ne 0 ]; then
    handle_error "Failed to provision CIDR to Top-level Pool"
fi

echo "$PROVISION_RESULT"

# Wait for the CIDR to be fully provisioned
if ! wait_for_cidr_provisioning "$TOP_POOL_ID" "$TOP_POOL_CIDR"; then
    handle_error "CIDR provisioning to Top-level Pool did not complete in time"
fi

# Step 4: Create a Regional IPv4 Pool
echo "Creating Regional IPv4 Pool..."
REGIONAL_POOL_RESULT=$(aws ec2 create-ipam-pool \
    --ipam-scope-id "$PRIVATE_SCOPE_ID" \
    --source-ipam-pool-id "$TOP_POOL_ID" \
    --locale us-east-1 \
    --address-family ipv4 \
    --description "Regional pool in us-east-1")

if [ $? -ne 0 ]; then
    handle_error "Failed to create Regional Pool"
fi

REGIONAL_POOL_ID=$(echo "$REGIONAL_POOL_RESULT" | grep -o '"IpamPoolId": "[^"]*' | cut -d'"' -f4)
echo "Regional Pool created with ID: $REGIONAL_POOL_ID"

# Wait for the regional pool to be available
if ! wait_for_pool "$REGIONAL_POOL_ID"; then
    handle_error "Regional Pool did not become available in time"
fi

# Provision CIDR to the regional pool
echo "Provisioning CIDR to Regional Pool..."
REGIONAL_POOL_CIDR="10.0.0.0/16"
PROVISION_RESULT=$(aws ec2 provision-ipam-pool-cidr \
    --ipam-pool-id "$REGIONAL_POOL_ID" \
    --cidr "$REGIONAL_POOL_CIDR")

if [ $? -ne 0 ]; then
    handle_error "Failed to provision CIDR to Regional Pool"
fi

echo "$PROVISION_RESULT"

# Wait for the CIDR to be fully provisioned
if ! wait_for_cidr_provisioning "$REGIONAL_POOL_ID" "$REGIONAL_POOL_CIDR"; then
    handle_error "CIDR provisioning to Regional Pool did not complete in time"
fi

# Step 5: Create a Development IPv4 Pool - FIXED to include locale
echo "Creating Development IPv4 Pool..."
DEV_POOL_RESULT=$(aws ec2 create-ipam-pool \
    --ipam-scope-id "$PRIVATE_SCOPE_ID" \
    --source-ipam-pool-id "$REGIONAL_POOL_ID" \
    --locale us-east-1 \
    --address-family ipv4 \
    --description "Development pool")

if [ $? -ne 0 ]; then
    handle_error "Failed to create Development Pool"
fi

DEV_POOL_ID=$(echo "$DEV_POOL_RESULT" | grep -o '"IpamPoolId": "[^"]*' | cut -d'"' -f4)
echo "Development Pool created with ID: $DEV_POOL_ID"

# Wait for the development pool to be available
if ! wait_for_pool "$DEV_POOL_ID"; then
    handle_error "Development Pool did not become available in time"
fi

# Provision CIDR to the development pool
echo "Provisioning CIDR to Development Pool..."
DEV_POOL_CIDR="10.0.0.0/24"
PROVISION_RESULT=$(aws ec2 provision-ipam-pool-cidr \
    --ipam-pool-id "$DEV_POOL_ID" \
    --cidr "$DEV_POOL_CIDR")

if [ $? -ne 0 ]; then
    handle_error "Failed to provision CIDR to Development Pool"
fi

echo "$PROVISION_RESULT"

# Wait for the CIDR to be fully provisioned
if ! wait_for_cidr_provisioning "$DEV_POOL_ID" "$DEV_POOL_CIDR"; then
    handle_error "CIDR provisioning to Development Pool did not complete in time"
fi

# Step 6: Create a VPC Using an IPAM Pool CIDR - FIXED to use the correct parameter names and a smaller netmask length
echo "Creating VPC using IPAM Pool CIDR..."
VPC_RESULT=$(aws ec2 create-vpc \
    --ipv4-ipam-pool-id "$DEV_POOL_ID" \
    --ipv4-netmask-length 26 \
    --tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=IPAM-VPC}]')

if [ $? -ne 0 ]; then
    handle_error "Failed to create VPC"
fi

VPC_ID=$(echo "$VPC_RESULT" | grep -o '"VpcId": "[^"]*' | cut -d'"' -f4)
echo "VPC created with ID: $VPC_ID"

# Step 7: Verify the IPAM Pool Allocation
echo "Verifying IPAM Pool Allocation..."
ALLOCATION_RESULT=$(aws ec2 get-ipam-pool-allocations \
    --ipam-pool-id "$DEV_POOL_ID")

if [ $? -ne 0 ]; then
    handle_error "Failed to verify IPAM Pool Allocation"
fi

echo "IPAM Pool Allocation verified:"
echo "$ALLOCATION_RESULT" | grep -A 5 "Allocations"

echo ""
echo "IPAM setup completed successfully!"
echo ""

# Prompt for cleanup
cleanup_resources

echo "Script completed at $(date)"
exit 0
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateIpam](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateIpam)
  + [CreateIpamPool](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateIpamPool)
  + [CreateVpc](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/CreateVpc)
  + [DeleteIpam](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteIpam)
  + [DeleteIpamPool](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteIpamPool)
  + [DeleteVpc](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeleteVpc)
  + [DeprovisionIpamPoolCidr](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DeprovisionIpamPoolCidr)
  + [DescribeIpamPools](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeIpamPools)
  + [DescribeIpams](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeIpams)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/DescribeVpcs)
  + [GetIpamPoolAllocations](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/GetIpamPoolAllocations)
  + [GetIpamPoolCidrs](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/GetIpamPoolCidrs)
  + [ProvisionIpamPoolCidr](https://docs.aws.amazon.com/goto/aws-cli/ec2-2016-11-15/ProvisionIpamPoolCidr)

# Bash スクリプト AWS CLI で を使用した HealthImaging の例
<a name="bash_2_medical-imaging_code_examples"></a>

次のコード例は、HealthImaging AWS Command Line Interface で Bash スクリプトで を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDatastore`
<a name="medical-imaging_CreateDatastore_bash_2_topic"></a>

次の例は、`CreateDatastore` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function imaging_create_datastore
#
# This function creates an AWS HealthImaging data store for importing DICOM P10 files.
#
# Parameters:
#       -n data_store_name - The name of the data store.
#
# Returns:
#       The datastore ID.
#    And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function imaging_create_datastore() {
  local datastore_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function imaging_create_datastore"
    echo "Creates an AWS HealthImaging data store for importing DICOM P10 files."
    echo "  -n data_store_name - The name of the data store."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) datastore_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$datastore_name" ]]; then
    errecho "ERROR: You must provide a data store name with the -n parameter."
    usage
    return 1
  fi

  response=$(aws medical-imaging create-datastore \
    --datastore-name "$datastore_name" \
    --output text \
    --query 'datastoreId')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports medical-imaging create-datastore operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[CreateDatastore](https://docs.aws.amazon.com/goto/aws-cli/medical-imaging-2023-07-19/CreateDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `DeleteDatastore`
<a name="medical-imaging_DeleteDatastore_bash_2_topic"></a>

次の例は、`DeleteDatastore` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function imaging_delete_datastore
#
# This function deletes an AWS HealthImaging data store.
#
# Parameters:
#       -i datastore_id - The ID of the data store.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function imaging_delete_datastore() {
  local datastore_id response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function imaging_delete_datastore"
    echo "Deletes an AWS HealthImaging data store."
    echo "  -i datastore_id - The ID of the data store."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) datastore_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$datastore_id" ]]; then
    errecho "ERROR: You must provide a data store ID with the -i parameter."
    usage
    return 1
  fi

  response=$(aws medical-imaging delete-datastore \
    --datastore-id "$datastore_id")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports medical-imaging delete-datastore operation failed.$response"
    return 1
  fi

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDatastore](https://docs.aws.amazon.com/goto/aws-cli/medical-imaging-2023-07-19/DeleteDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetDatastore`
<a name="medical-imaging_GetDatastore_bash_2_topic"></a>

次の例は、`GetDatastore` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function imaging_get_datastore
#
# Get a data store's properties.
#
# Parameters:
#       -i data_store_id - The ID of the data store.
#
# Returns:
#       [datastore_name, datastore_id, datastore_status, datastore_arn,  created_at, updated_at]
#    And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function imaging_get_datastore() {
  local datastore_id option OPTARG # Required to use getopts command in a function.
  local error_code
  # bashsupport disable=BP5008
  function usage() {
    echo "function imaging_get_datastore"
    echo "Gets a data store's properties."
    echo "  -i datastore_id - The ID of the data store."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "i:h" option; do
    case "${option}" in
      i) datastore_id="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$datastore_id" ]]; then
    errecho "ERROR: You must provide a data store ID with the -i parameter."
    usage
    return 1
  fi

  local response

  response=$(
    aws medical-imaging get-datastore \
      --datastore-id "$datastore_id" \
      --output text \
      --query "[ datastoreProperties.datastoreName,  datastoreProperties.datastoreId, datastoreProperties.datastoreStatus, datastoreProperties.datastoreArn,  datastoreProperties.createdAt, datastoreProperties.updatedAt]"
  )
  error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports list-datastores operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDatastore](https://docs.aws.amazon.com/goto/aws-cli/medical-imaging-2023-07-19/GetDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListDatastores`
<a name="medical-imaging_ListDatastores_bash_2_topic"></a>

次の例は、`ListDatastores` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function imaging_list_datastores
#
# List the HealthImaging data stores in the account.
#
# Returns:
#       [[datastore_name, datastore_id, datastore_status]]
#    And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function imaging_list_datastores() {
  local option OPTARG # Required to use getopts command in a function.
  local error_code
  # bashsupport disable=BP5008
  function usage() {
    echo "function imaging_list_datastores"
    echo "Lists the AWS HealthImaging data stores in the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "h" option; do
    case "${option}" in
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local response
  response=$(aws medical-imaging list-datastores \
    --output text \
    --query "datastoreSummaries[*][datastoreName, datastoreId, datastoreStatus]")
  error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports list-datastores operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[ListDatastores](https://docs.aws.amazon.com/goto/aws-cli/medical-imaging-2023-07-19/ListDatastores)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/medical-imaging#code-examples)での設定と実行の方法を確認してください。

# Bash スクリプト AWS CLI で を使用する IAM の例
<a name="bash_2_iam_code_examples"></a>

次のコード例は、IAM AWS Command Line Interface で Bash スクリプトで を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_bash_2_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function iam_create_user_assume_role
#
# Scenario to create an IAM user, create an IAM role, and apply the role to the user.
#
#     "IAM access" permissions are needed to run this code.
#     "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
#           create a custom policy).
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function iam_create_user_assume_role() {
  {
    if [ "$IAM_OPERATIONS_SOURCED" != "True" ]; then

      source ./iam_operations.sh
    fi
  }

  echo_repeat "*" 88
  echo "Welcome to the IAM create user and assume role demo."
  echo
  echo "This demo will create an IAM user, create an IAM role, and apply the role to the user."
  echo_repeat "*" 88
  echo

  echo -n "Enter a name for a new IAM user: "
  get_input
  user_name=$get_input_result

  local user_arn
  user_arn=$(iam_create_user -u "$user_name")

  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created demo IAM user named $user_name"
  else
    errecho "$user_arn"
    errecho "The user failed to create. This demo will exit."
    return 1
  fi

  local access_key_response
  access_key_response=$(iam_create_user_access_key -u "$user_name")
  # shellcheck disable=SC2181
  if [[ ${?} != 0 ]]; then
    errecho "The access key failed to create. This demo will exit."
    clean_up "$user_name"
    return 1
  fi

  IFS=$'\t ' read -r -a access_key_values <<<"$access_key_response"
  local key_name=${access_key_values[0]}
  local key_secret=${access_key_values[1]}

  echo "Created access key named $key_name"

  echo "Wait 10 seconds for the user to be ready."
  sleep 10
  echo_repeat "*" 88
  echo

  local iam_role_name
  iam_role_name=$(generate_random_name "test-role")
  echo "Creating a role named $iam_role_name with user $user_name as the principal."

  local assume_role_policy_document="{
    \"Version\": \"2012-10-17\",
    \"Statement\": [{
        \"Effect\": \"Allow\",
        \"Principal\": {\"AWS\": \"$user_arn\"},
        \"Action\": \"sts:AssumeRole\"
        }]
    }"

  local role_arn
  role_arn=$(iam_create_role -n "$iam_role_name" -p "$assume_role_policy_document")

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created IAM role named $iam_role_name"
  else
    errecho "The role failed to create. This demo will exit."
    clean_up "$user_name" "$key_name"
    return 1
  fi

  local policy_name
  policy_name=$(generate_random_name "test-policy")
  local policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]}"

  local policy_arn
  policy_arn=$(iam_create_policy -n "$policy_name" -p "$policy_document")
  # shellcheck disable=SC2181
  if [[ ${?} == 0 ]]; then
    echo "Created  IAM policy named $policy_name"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name"
    return 1
  fi

  if (iam_attach_role_policy -n "$iam_role_name" -p "$policy_arn"); then
    echo "Attached policy $policy_arn to role $iam_role_name"
  else
    errecho "The policy failed to attach."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn"
    return 1
  fi

  local assume_role_policy_document="{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"$role_arn\"}]}"

  local assume_role_policy_name
  assume_role_policy_name=$(generate_random_name "test-assume-role-")

  # shellcheck disable=SC2181
  local assume_role_policy_arn
  assume_role_policy_arn=$(iam_create_policy -n "$assume_role_policy_name" -p "$assume_role_policy_document")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Created  IAM policy named $assume_role_policy_name for sts assume role"
  else
    errecho "The policy failed to create."
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn"
    return 1
  fi

  echo "Wait 10 seconds to give AWS time to propagate these new resources and connections."
  sleep 10
  echo_repeat "*" 88
  echo

  echo "Try to list buckets without the new user assuming the role."
  echo_repeat "*" 88
  echo

  # Set the environment variables for the created user.
  # bashsupport disable=BP2001
  export AWS_ACCESS_KEY_ID=$key_name
  # bashsupport disable=BP2001
  export AWS_SECRET_ACCESS_KEY=$key_secret

  local buckets
  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. This should not have happened."
  else
    errecho "Because the role with permissions has not been assumed, listing buckets failed."
  fi

  echo
  echo_repeat "*" 88
  echo "Now assume the role $iam_role_name and list the buckets."
  echo_repeat "*" 88
  echo

  local credentials

  credentials=$(sts_assume_role -r "$role_arn" -n "AssumeRoleDemoSession")
  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    echo "Assumed role $iam_role_name"
  else
    errecho "Failed to assume role."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  IFS=$'\t ' read -r -a credentials <<<"$credentials"

  export AWS_ACCESS_KEY_ID=${credentials[0]}
  export AWS_SECRET_ACCESS_KEY=${credentials[1]}
  # bashsupport disable=BP2001
  export AWS_SESSION_TOKEN=${credentials[2]}

  buckets=$(s3_list_buckets)

  # shellcheck disable=SC2181
  if [ ${?} == 0 ]; then
    local bucket_count
    bucket_count=$(echo "$buckets" | wc -w | xargs)
    echo "There are $bucket_count buckets in the account. Listing buckets succeeded because of "
    echo "the assumed role."
  else
    errecho "Failed to list buckets. This should not happen."
    export AWS_ACCESS_KEY_ID=""
    export AWS_SECRET_ACCESS_KEY=""
    export AWS_SESSION_TOKEN=""
    clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"
    return 1
  fi

  local result=0
  export AWS_ACCESS_KEY_ID=""
  export AWS_SECRET_ACCESS_KEY=""

  echo
  echo_repeat "*" 88
  echo "The created resources will now be deleted."
  echo_repeat "*" 88
  echo

  clean_up "$user_name" "$key_name" "$iam_role_name" "$policy_arn" "$policy_arn" "$assume_role_policy_arn"

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    result=1
  fi

  return $result
}
```
このシナリオで使用される IAM 関数。  

```
###############################################################################
# function iam_user_exists
#
# This function checks to see if the specified AWS Identity and Access Management (IAM) user already exists.
#
# Parameters:
#       $1 - The name of the IAM user to check.
#
# Returns:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_user_exists() {
  local user_name
  user_name=$1

  # Check whether the IAM user already exists.
  # We suppress all output - we're interested only in the return code.

  local errors
  errors=$(aws iam get-user \
    --user-name "$user_name" 2>&1 >/dev/null)

  local error_code=${?}

  if [[ $error_code -eq 0 ]]; then
    return 0 # 0 in Bash script means true.
  else
    if [[ $errors != *"error"*"(NoSuchEntity)"* ]]; then
      aws_cli_error_log $error_code
      errecho "Error calling iam get-user $errors"
    fi

    return 1 # 1 in Bash script means false.
  fi
}

###############################################################################
# function iam_create_user
#
# This function creates the specified IAM user, unless
# it already exists.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       The ARN of the user.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user"
    echo "Creates an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user. It must be unique within the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user already exists, we don't want to try to create it.
  if (iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name already exists in the account."
    return 1
  fi

  response=$(aws iam create-user --user-name "$user_name" \
    --output text \
    --query 'User.Arn')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-user operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_create_user_access_key
#
# This function creates an IAM access key for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#       [-f file_name] -- The optional file name for the access key output.
#
# Returns:
#       [access_key_id access_key_secret]
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user_access_key() {
  local user_name file_name 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) key pair."
    echo "  -u user_name   The name of the IAM user."
    echo "  [-f file_name]   Optional file name for the access key output."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:f:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      f) file_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam create-access-key \
    --user-name "$user_name" \
    --output text)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  fi

  if [[ -n "$file_name" ]]; then
    echo "$response" >"$file_name"
  fi

  local key_id key_secret
  # shellcheck disable=SC2086
  key_id=$(echo $response | cut -f 2 -d ' ')
  # shellcheck disable=SC2086
  key_secret=$(echo $response | cut -f 4 -d ' ')

  echo "$key_id $key_secret"

  return 0
}

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

###############################################################################
# function iam_create_policy
#
# This function creates an IAM policy.
#
# Parameters:
#       -n policy_name -- The name of the IAM policy.
#       -p policy_json -- The policy document.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_policy() {
  local policy_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_policy"
    echo "Creates an AWS Identity and Access Management (IAM) policy."
    echo "  -n policy_name   The name of the IAM policy."
    echo "  -p policy_json -- The policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) policy_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_name" ]]; then
    errecho "ERROR: You must provide a policy 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-policy \
    --policy-name "$policy_name" \
    --policy-document "$policy_document" \
    --output text \
    --query Policy.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"
}

###############################################################################
# function iam_attach_role_policy
#
# This function attaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_attach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_attach_role_policy"
    echo "Attaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${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_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam attach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports attach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_detach_role_policy
#
# This function detaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_detach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_detach_role_policy"
    echo "Detaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${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_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam detach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports detach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}

###############################################################################
# function iam_delete_policy
#
# This function deletes an IAM policy.
#
# Parameters:
#       -n policy_arn -- The name of the IAM policy arn.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_policy() {
  local policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_policy"
    echo "Deletes an AWS Identity and Access Management (IAM) policy"
    echo "  -n policy_arn -- The name of the IAM policy arn."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy arn with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Policy arn:  $policy_arn"
  iecho ""

  response=$(aws iam delete-policy \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-policy operation failed.\n$response"
    return 1
  fi

  iecho "delete-policy response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_role
#
# This function deletes an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_role() {
  local role_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_role"
    echo "Deletes an AWS Identity and Access Management (IAM) role"
    echo "  -n role_name -- The name of the IAM role."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  echo "role_name:$role_name"
  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Role name:  $role_name"
  iecho ""

  response=$(aws iam delete-role \
    --role-name "$role_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-role operation failed.\n$response"
    return 1
  fi

  iecho "delete-role response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_access_key
#
# This function deletes an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to delete.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_access_key() {
  local user_name access_key response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_access_key"
    echo "Deletes an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:k:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      k) access_key="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  if [[ -z "$access_key" ]]; then
    errecho "ERROR: You must provide an access key with the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Username:   $user_name"
  iecho "    Access key:   $access_key"
  iecho ""

  response=$(aws iam delete-access-key \
    --user-name "$user_name" \
    --access-key-id "$access_key")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-access-key operation failed.\n$response"
    return 1
  fi

  iecho "delete-access-key response:$response"
  iecho

  return 0
}

###############################################################################
# function iam_delete_user
#
# This function deletes the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_user"
    echo "Deletes an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user does not exist, we don't want to try to delete it.
  if (! iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name does not exist in the account."
    return 1
  fi

  response=$(aws iam delete-user \
    --user-name "$user_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-user operation failed.$response"
    return 1
  fi

  iecho "delete-user response:$response"
  iecho

  return 0
}
```
+ API の詳細については、「*AWS CLI コマンドリファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_bash_2_topic"></a>

次の例は、`AttachRolePolicy` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_attach_role_policy
#
# This function attaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_attach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_attach_role_policy"
    echo "Attaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${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_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam attach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports attach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_bash_2_topic"></a>

次の例は、`CreateAccessKey` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_create_user_access_key
#
# This function creates an IAM access key for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#       [-f file_name] -- The optional file name for the access key output.
#
# Returns:
#       [access_key_id access_key_secret]
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user_access_key() {
  local user_name file_name 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) key pair."
    echo "  -u user_name   The name of the IAM user."
    echo "  [-f file_name]   Optional file name for the access key output."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:f:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      f) file_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam create-access-key \
    --user-name "$user_name" \
    --output text)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-access-key operation failed.$response"
    return 1
  fi

  if [[ -n "$file_name" ]]; then
    echo "$response" >"$file_name"
  fi

  local key_id key_secret
  # shellcheck disable=SC2086
  key_id=$(echo $response | cut -f 2 -d ' ')
  # shellcheck disable=SC2086
  key_secret=$(echo $response | cut -f 4 -d ' ')

  echo "$key_id $key_secret"

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateAccessKey)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_bash_2_topic"></a>

次の例は、`CreatePolicy` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_create_policy
#
# This function creates an IAM policy.
#
# Parameters:
#       -n policy_name -- The name of the IAM policy.
#       -p policy_json -- The policy document.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_policy() {
  local policy_name policy_document response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_policy"
    echo "Creates an AWS Identity and Access Management (IAM) policy."
    echo "  -n policy_name   The name of the IAM policy."
    echo "  -p policy_json -- The policy document."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) policy_name="${OPTARG}" ;;
      p) policy_document="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_name" ]]; then
    errecho "ERROR: You must provide a policy 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-policy \
    --policy-name "$policy_name" \
    --policy-document "$policy_document" \
    --output text \
    --query Policy.Arn)

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_bash_2_topic"></a>

次の例は、`CreateRole` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# 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](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)」を参照してください。**

### `CreateUser`
<a name="iam_CreateUser_bash_2_topic"></a>

次の例は、`CreateUser` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# 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 iam_create_user
#
# This function creates the specified IAM user, unless
# it already exists.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       The ARN of the user.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_create_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_create_user"
    echo "Creates an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user. It must be unique within the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user already exists, we don't want to try to create it.
  if (iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name already exists in the account."
    return 1
  fi

  response=$(aws iam create-user --user-name "$user_name" \
    --output text \
    --query 'User.Arn')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports create-user operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_bash_2_topic"></a>

次の例は、`DeleteAccessKey` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_delete_access_key
#
# This function deletes an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to delete.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_access_key() {
  local user_name access_key response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_access_key"
    echo "Deletes an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to delete."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:k:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      k) access_key="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  if [[ -z "$access_key" ]]; then
    errecho "ERROR: You must provide an access key with the -k parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Username:   $user_name"
  iecho "    Access key:   $access_key"
  iecho ""

  response=$(aws iam delete-access-key \
    --user-name "$user_name" \
    --access-key-id "$access_key")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-access-key operation failed.\n$response"
    return 1
  fi

  iecho "delete-access-key response:$response"
  iecho

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteAccessKey)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_bash_2_topic"></a>

次の例は、`DeletePolicy` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# 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 iam_delete_policy
#
# This function deletes an IAM policy.
#
# Parameters:
#       -n policy_arn -- The name of the IAM policy arn.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_policy() {
  local policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_policy"
    echo "Deletes an AWS Identity and Access Management (IAM) policy"
    echo "  -n policy_arn -- The name of the IAM policy arn."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) policy_arn="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$policy_arn" ]]; then
    errecho "ERROR: You must provide a policy arn with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Policy arn:  $policy_arn"
  iecho ""

  response=$(aws iam delete-policy \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-policy operation failed.\n$response"
    return 1
  fi

  iecho "delete-policy response:$response"
  iecho

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeletePolicy)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_bash_2_topic"></a>

次の例は、`DeleteRole` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# 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 iam_delete_role
#
# This function deletes an IAM role.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_role() {
  local role_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_role"
    echo "Deletes an AWS Identity and Access Management (IAM) role"
    echo "  -n role_name -- The name of the IAM role."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  echo "role_name:$role_name"
  if [[ -z "$role_name" ]]; then
    errecho "ERROR: You must provide a role name with the -n parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    Role name:  $role_name"
  iecho ""

  response=$(aws iam delete-role \
    --role-name "$role_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-role operation failed.\n$response"
    return 1
  fi

  iecho "delete-role response:$response"
  iecho

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteRole)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_bash_2_topic"></a>

次の例は、`DeleteUser` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# 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 iam_delete_user
#
# This function deletes the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user to create.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_delete_user() {
  local user_name response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_delete_user"
    echo "Deletes an AWS Identity and Access Management (IAM) user. You must supply a username:"
    echo "  -u user_name    The name of the user."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  iecho "Parameters:\n"
  iecho "    User name:   $user_name"
  iecho ""

  # If the user does not exist, we don't want to try to delete it.
  if (! iam_user_exists "$user_name"); then
    errecho "ERROR: A user with that name does not exist in the account."
    return 1
  fi

  response=$(aws iam delete-user \
    --user-name "$user_name")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports delete-user operation failed.$response"
    return 1
  fi

  iecho "delete-user response:$response"
  iecho

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DeleteUser)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_bash_2_topic"></a>

次の例は、`DetachRolePolicy` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_detach_role_policy
#
# This function detaches an IAM policy to a tole.
#
# Parameters:
#       -n role_name -- The name of the IAM role.
#       -p policy_ARN -- The IAM policy document ARN..
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_detach_role_policy() {
  local role_name policy_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_detach_role_policy"
    echo "Detaches an AWS Identity and Access Management (IAM) policy to an IAM role."
    echo "  -n role_name   The name of the IAM role."
    echo "  -p policy_ARN -- The IAM policy document ARN."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "n:p:h" option; do
    case "${option}" in
      n) role_name="${OPTARG}" ;;
      p) policy_arn="${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_arn" ]]; then
    errecho "ERROR: You must provide a policy ARN with the -p parameter."
    usage
    return 1
  fi

  response=$(aws iam detach-role-policy \
    --role-name "$role_name" \
    --policy-arn "$policy_arn")

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports detach-role-policy operation failed.\n$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/DetachRolePolicy)」を参照してください。

### `GetUser`
<a name="iam_GetUser_bash_2_topic"></a>

次の例は、`GetUser` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_user_exists
#
# This function checks to see if the specified AWS Identity and Access Management (IAM) user already exists.
#
# Parameters:
#       $1 - The name of the IAM user to check.
#
# Returns:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_user_exists() {
  local user_name
  user_name=$1

  # Check whether the IAM user already exists.
  # We suppress all output - we're interested only in the return code.

  local errors
  errors=$(aws iam get-user \
    --user-name "$user_name" 2>&1 >/dev/null)

  local error_code=${?}

  if [[ $error_code -eq 0 ]]; then
    return 0 # 0 in Bash script means true.
  else
    if [[ $errors != *"error"*"(NoSuchEntity)"* ]]; then
      aws_cli_error_log $error_code
      errecho "Error calling iam get-user $errors"
    fi

    return 1 # 1 in Bash script means false.
  fi
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUser](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/GetUser)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_bash_2_topic"></a>

次の例は、`ListAccessKeys` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_list_access_keys
#
# This function lists the access keys for the specified user.
#
# Parameters:
#       -u user_name -- The name of the IAM user.
#
# Returns:
#       access_key_ids
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_list_access_keys() {

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_list_access_keys"
    echo "Lists the AWS Identity and Access Management (IAM) access key IDs for the specified user."
    echo "  -u user_name   The name of the IAM user."
    echo ""
  }

  local user_name response
  local option OPTARG # Required to use getopts command in a function.
  # Retrieve the calling parameters.
  while getopts "u:h" option; do
    case "${option}" in
      u) user_name="${OPTARG}" ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  if [[ -z "$user_name" ]]; then
    errecho "ERROR: You must provide a username with the -u parameter."
    usage
    return 1
  fi

  response=$(aws iam list-access-keys \
    --user-name "$user_name" \
    --output text \
    --query 'AccessKeyMetadata[].AccessKeyId')

  local error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports list-access-keys operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessKeys](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/ListAccessKeys)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_bash_2_topic"></a>

次の例は、`ListUsers` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function iam_list_users
#
# List the IAM users in the account.
#
# Returns:
#       The list of users names
#    And:
#       0 - If the user already exists.
#       1 - If the user doesn't exist.
###############################################################################
function iam_list_users() {
  local option OPTARG # Required to use getopts command in a function.
  local error_code
  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_list_users"
    echo "Lists the AWS Identity and Access Management (IAM) user in the account."
    echo ""
  }

  # Retrieve the calling parameters.
  while getopts "h" option; do
    case "${option}" in
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done
  export OPTIND=1

  local response

  response=$(aws iam list-users \
    --output text \
    --query "Users[].UserName")
  error_code=${?}

  if [[ $error_code -ne 0 ]]; then
    aws_cli_error_log $error_code
    errecho "ERROR: AWS reports list-users operation failed.$response"
    return 1
  fi

  echo "$response"

  return 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsers](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/ListUsers)」を参照してください。

### `UpdateAccessKey`
<a name="iam_UpdateAccessKey_bash_2_topic"></a>

次の例は、`UpdateAccessKey` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function iam_update_access_key
#
# This function can activate or deactivate an IAM access key for the specified IAM user.
#
# Parameters:
#       -u user_name  -- The name of the user.
#       -k access_key -- The access key to update.
#       -a            -- Activate the selected access key.
#       -d            -- Deactivate the selected access key.
#
# Example:
#       # To deactivate the selected access key for IAM user Bob
#       iam_update_access_key -u Bob -k AKIAIOSFODNN7EXAMPLE -d 
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function iam_update_access_key() {
  local user_name access_key status response
  local option OPTARG # Required to use getopts command in a function.
  local activate_flag=false deactivate_flag=false

  # bashsupport disable=BP5008
  function usage() {
    echo "function iam_update_access_key"
    echo "Updates the status of an AWS Identity and Access Management (IAM) access key for the specified IAM user"
    echo "  -u user_name    The name of the user."
    echo "  -k access_key   The access key to update."
    echo "  -a              Activate the access key."
    echo "  -d              Deactivate the access key."
    echo ""
  }

  # Retrieve the calling parameters.
    while getopts "u:k:adh" option; do
      case "${option}" in
        u) user_name="${OPTARG}" ;;
        k) access_key="${OPTARG}" ;;
        a) activate_flag=true ;;
        d) deactivate_flag=true ;;
        h)
          usage
          return 0
          ;;
        \?)
          echo "Invalid parameter"
          usage
          return 1
          ;;
      esac
    done
    export OPTIND=1
  
   # Validate input parameters
    if [[ -z "$user_name" ]]; then
      errecho "ERROR: You must provide a username with the -u parameter."
      usage
      return 1
    fi
  
    if [[ -z "$access_key" ]]; then
      errecho "ERROR: You must provide an access key with the -k parameter."
      usage
      return 1
    fi

    # Ensure that only -a or -d is specified
    if [[ "$activate_flag" == true && "$deactivate_flag" == true ]]; then
      errecho "ERROR: You cannot specify both -a (activate) and -d (deactivate) at the same time."
      usage
      return 1
    fi
  
    # If neither -a nor -d is provided, return an error
    if [[ "$activate_flag" == false && "$deactivate_flag" == false ]]; then
      errecho "ERROR: You must specify either -a (activate) or -d (deactivate)."
      usage
      return 1
    fi

    # Determine the status based on the flag
    if [[ "$activate_flag" == true ]]; then
      status="Active"
    elif [[ "$deactivate_flag" == true ]]; then
      status="Inactive"
    fi
  
    iecho "Parameters:\n"
    iecho "    Username:   $user_name"
    iecho "    Access key: $access_key"
    iecho "    New status: $status"
    iecho ""
  
    # Update the access key status
    response=$(aws iam update-access-key \
      --user-name "$user_name" \
      --access-key-id "$access_key" \
      --status "$status" 2>&1)
  
    local error_code=${?}
  
    if [[ $error_code -ne 0 ]]; then
      aws_cli_error_log $error_code
      errecho "ERROR: AWS reports update-access-key operation failed.\n$response"
      return 1
    fi
  
    iecho "update-access-key response: $response"
    iecho
  
    return 0
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateAccessKey](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/UpdateAccessKey)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 属性ベースのアクセス制御を設定する
<a name="dynamodb_Scenario_ABACSetup_bash_2_topic"></a>

次のコード例は、DynamoDB の属性ベースのアクセス制御 (ABAC) を実装する方法を示しています。
+ ABAC の IAM ポリシーを作成します。
+ さまざまな部門のタグを含むテーブルを作成します。
+ タグに基づいてテーブルを一覧表示およびフィルタリングします。

**AWS CLI Bash スクリプトを使用する**  
ABAC の IAM ポリシーを作成します。  

```
# Step 1: Create a policy document for ABAC
cat > abac-policy.json << 'EOF'
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:GetItem",
        "dynamodb:BatchGetItem",
        "dynamodb:Query",
        "dynamodb:Scan"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Department": "${aws:PrincipalTag/Department}"
        }
      }
    },
    {
      "Effect": "Allow",
      "Action": [
        "dynamodb:PutItem",
        "dynamodb:UpdateItem",
        "dynamodb:DeleteItem",
        "dynamodb:BatchWriteItem"
      ],
      "Resource": "arn:aws:dynamodb:*:*:table/*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/Department": "${aws:PrincipalTag/Department}",
          "aws:ResourceTag/Environment": "Development"
        }
      }
    }
  ]
}
EOF

# Step 2: Create the IAM policy
aws iam create-policy \
    --policy-name DynamoDBDepartmentBasedAccess \
    --policy-document file://abac-policy.json
```
さまざまな部門のタグを含むテーブルを作成します。  

```
# Create a DynamoDB table with tags for ABAC
aws dynamodb create-table \
    --table-name FinanceData \
    --attribute-definitions \
        AttributeName=RecordID,AttributeType=S \
    --key-schema \
        AttributeName=RecordID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --tags \
        Key=Department,Value=Finance \
        Key=Environment,Value=Development

# Create another table with different tags
aws dynamodb create-table \
    --table-name MarketingData \
    --attribute-definitions \
        AttributeName=RecordID,AttributeType=S \
    --key-schema \
        AttributeName=RecordID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --tags \
        Key=Department,Value=Marketing \
        Key=Environment,Value=Production
```
タグに基づいてテーブルを一覧表示およびフィルタリングします。  

```
# List all DynamoDB tables
echo "Listing all tables:"
aws dynamodb list-tables

# Get ARNs for all tables
echo -e "\nGetting ARNs for all tables:"
TABLE_ARNS=$(aws dynamodb list-tables --query "TableNames[*]" --output text | xargs -I {} aws dynamodb describe-table --table-name {} --query "Table.TableArn" --output text)

# For each table ARN, list its tags
echo -e "\nListing tags for each table:"
for ARN in $TABLE_ARNS; do
    TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}')
    echo -e "\nTags for table: $TABLE_NAME"
    aws dynamodb list-tags-of-resource --resource-arn $ARN
done

# Example: Find tables with a specific tag
echo -e "\nFinding tables with Environment=Production tag:"
for ARN in $TABLE_ARNS; do
    TABLE_NAME=$(echo $ARN | awk -F/ '{print $2}')
    TAGS=$(aws dynamodb list-tags-of-resource --resource-arn $ARN --query "Tags[?Key=='Environment' && Value=='Production']" --output text)
    if [ ! -z "$TAGS" ]; then
        echo "Table with Production tag: $TABLE_NAME"
    fi
done
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreatePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreatePolicy)
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [ListTables](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/ListTables)

### Streams と Time-to-Live を操作する
<a name="dynamodb_Scenario_StreamsAndTTL_bash_2_topic"></a>

次のコード例は、DynamoDB Streams 機能と Time-to-Live 機能を管理する方法を示しています。
+ Streams を有効にしてテーブルを作成します。
+ Streams について説明します。
+ Streams を処理する Lambda 関数を作成します。
+ テーブルで TTL を有効にします。
+ TTL 属性を持つ項目を追加します。
+ TTL 設定について説明します。

**AWS CLI Bash スクリプトを使用する**  
Streams を有効にしてテーブルを作成します。  

```
# Create a table with DynamoDB Streams enabled
aws dynamodb create-table \
    --table-name StreamsDemo \
    --attribute-definitions \
        AttributeName=ID,AttributeType=S \
    --key-schema \
        AttributeName=ID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --stream-specification StreamEnabled=true,StreamViewType=NEW_AND_OLD_IMAGES
```
Streams について説明します。  

```
# Get information about the stream
aws dynamodb describe-table \
    --table-name StreamsDemo \
    --query "Table.StreamSpecification"

# Get the stream ARN
STREAM_ARN=$(aws dynamodb describe-table \
    --table-name StreamsDemo \
    --query "Table.LatestStreamArn" \
    --output text)

echo "Stream ARN: $STREAM_ARN"

# Describe the stream
aws dynamodbstreams describe-stream \
    --stream-arn $STREAM_ARN
```
Streams の Lambda 関数を作成します。  

```
# Step 1: Create an IAM role for the Lambda function
cat > trust-policy.json << 'EOF'
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF

aws iam create-role \
    --role-name DynamoDBStreamsLambdaRole \
    --assume-role-policy-document file://trust-policy.json

# Step 2: Attach permissions to the role
aws iam attach-role-policy \
    --role-name DynamoDBStreamsLambdaRole \
    --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole

# Step 3: Create a Lambda function (code would be in a separate file)
echo "Lambda function creation would be done separately with appropriate code"

# Step 4: Create an event source mapping
echo "Example command to create event source mapping:"
echo "aws lambda create-event-source-mapping \\"
echo "    --function-name ProcessDynamoDBRecords \\"
echo "    --event-source $STREAM_ARN \\"
echo "    --batch-size 100 \\"
echo "    --starting-position LATEST"
```
テーブルで TTL を有効にします。  

```
# Create a table for TTL demonstration
aws dynamodb create-table \
    --table-name TTLDemo \
    --attribute-definitions \
        AttributeName=ID,AttributeType=S \
    --key-schema \
        AttributeName=ID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST

# Wait for table to become active
aws dynamodb wait table-exists --table-name TTLDemo

# Enable TTL on the table
aws dynamodb update-time-to-live \
    --table-name TTLDemo \
    --time-to-live-specification "Enabled=true, AttributeName=ExpirationTime"
```
TTL 属性を持つ項目を追加します。  

```
# Calculate expiration time (current time + 1 day in seconds)
EXPIRATION_TIME=$(date -d "+1 day" +%s)

# Add an item with TTL attribute
aws dynamodb put-item \
    --table-name TTLDemo \
    --item '{
        "ID": {"S": "item1"},
        "Data": {"S": "This item will expire in 1 day"},
        "ExpirationTime": {"N": "'$EXPIRATION_TIME'"}
    }'

# Add an item that expires in 1 hour
EXPIRATION_TIME_HOUR=$(date -d "+1 hour" +%s)
aws dynamodb put-item \
    --table-name TTLDemo \
    --item '{
        "ID": {"S": "item2"},
        "Data": {"S": "This item will expire in 1 hour"},
        "ExpirationTime": {"N": "'$EXPIRATION_TIME_HOUR'"}
    }'
```
TTL 設定について説明します。  

```
# Describe TTL settings for a table
aws dynamodb describe-time-to-live \
    --table-name TTLDemo
```
+ API の詳細については、「*AWS CLI コマンドリファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/AttachRolePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/aws-cli/iam-2010-05-08/CreateRole)
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)
  + [DescribeTimeToLive](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTimeToLive)
  + [PutItem](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/PutItem)
  + [UpdateTimeToLive](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateTimeToLive)

# AWS KMS Bash スクリプト AWS CLI で を使用する例
<a name="bash_2_kms_code_examples"></a>

次のコード例は、Bash スクリプト AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### テーブルの暗号化を操作する
<a name="dynamodb_Scenario_EncryptionExamples_bash_2_topic"></a>

次のコード例は、DynamoDB テーブルの暗号化オプションを管理する方法を示しています。
+ デフォルトの暗号化を使用してテーブルを作成します。
+ カスタマーマネージド CMK を使用してテーブルを作成します。
+ テーブルの暗号化設定を更新します。
+ テーブルの暗号化について説明します。

**AWS CLI Bash スクリプトを使用する**  
デフォルトの暗号化を使用してテーブルを作成します。  

```
# Create a table with default encryption (AWS owned key)
aws dynamodb create-table \
    --table-name CustomerData \
    --attribute-definitions \
        AttributeName=CustomerID,AttributeType=S \
    --key-schema \
        AttributeName=CustomerID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --sse-specification Enabled=true,SSEType=KMS
```
カスタマーマネージド CMK を使用してテーブルを作成します。  

```
# Step 1: Create a customer managed key in KMS
aws kms create-key \
    --description "Key for DynamoDB table encryption" \
    --key-usage ENCRYPT_DECRYPT \
    --customer-master-key-spec SYMMETRIC_DEFAULT

# Store the key ID for later use
KEY_ID=$(aws kms list-keys --query "Keys[?contains(KeyArn, 'Key for DynamoDB')].KeyId" --output text)

# Step 2: Create a table with the customer managed key
aws dynamodb create-table \
    --table-name SensitiveData \
    --attribute-definitions \
        AttributeName=RecordID,AttributeType=S \
    --key-schema \
        AttributeName=RecordID,KeyType=HASH \
    --billing-mode PAY_PER_REQUEST \
    --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=$KEY_ID
```
テーブルの暗号化を更新します。  

```
# Update a table to use a different KMS key
aws dynamodb update-table \
    --table-name CustomerData \
    --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=$KEY_ID
```
テーブルの暗号化について説明します。  

```
# Describe the table to see encryption settings
aws dynamodb describe-table \
    --table-name CustomerData \
    --query "Table.SSEDescription"
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CreateKey](https://docs.aws.amazon.com/goto/aws-cli/kms-2014-11-01/CreateKey)
  + [CreateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/CreateTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/DescribeTable)
  + [UpdateTable](https://docs.aws.amazon.com/goto/aws-cli/dynamodb-2012-08-10/UpdateTable)

# Lightsail Bash スクリプト AWS CLI で を使用する例
<a name="bash_2_lightsail_code_examples"></a>

次のコード例は、 AWS Command Line Interface で Bash スクリプトを使用してアクションを実行し、一般的なシナリオを実装する方法を示していますLightsail。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Lightsail の開始方法
<a name="lightsail_GettingStarted_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ インスタンス作成に使用できるブループリントとバンドルを調べる
+ Amazon Linux 2023 で Lightsail インスタンスを作成する
+ インスタンスが実行中になるまでステータスをモニタリングする
+ SSH アクセス用のデフォルトキーペアをダウンロードする
+ 追加のブロックストレージディスクを作成してアタッチする
+ バックアップ用にインスタンスのスナップショットを作成する
+ 継続的な料金が発生しないようにリソースをクリーンアップする

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/001-lightsail-gs)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# Amazon Lightsail Getting Started CLI Script
# This script demonstrates how to create and manage Lightsail resources using the AWS CLI

# FIXES APPLIED:
# 1. Added polling mechanism to check disk state before attaching
# 2. Added polling mechanism to check snapshot state before proceeding with cleanup
# 3. Set AWS_REGION variable to us-west-2 for consistent region usage

# Set AWS region
export AWS_REGION="us-west-2"
echo "Using AWS region: $AWS_REGION"

# Set up logging
LOG_FILE="lightsail-script.log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "Starting Lightsail Getting Started script at $(date)"

# Error handling function
handle_error() {
  echo "ERROR: $1"
  echo "Attempting to clean up resources..."
  cleanup_resources
  exit 1
}

# Function to check if a command succeeded
check_status() {
  if [ $? -ne 0 ]; then
    handle_error "$1"
  fi
}

# Generate a random identifier for resource names
RANDOM_ID=$(openssl rand -hex 4)
INSTANCE_NAME="LightsailInstance-${RANDOM_ID}"
DISK_NAME="LightsailDisk-${RANDOM_ID}"
SNAPSHOT_NAME="LightsailSnapshot-${RANDOM_ID}"

# Array to track created resources
declare -a CREATED_RESOURCES

# Function to add a resource to the tracking array
track_resource() {
  CREATED_RESOURCES+=("$1:$2")
  echo "Created $1: $2"
}

# Function to clean up resources
cleanup_resources() {
  echo "Resources created by this script:"
  for resource in "${CREATED_RESOURCES[@]}"; do
    echo "  $resource"
  done
  
  # Reverse the array to delete resources in reverse order
  for (( idx=${#CREATED_RESOURCES[@]}-1 ; idx>=0 ; idx-- )); do
    IFS=':' read -r type name <<< "${CREATED_RESOURCES[idx]}"
    
    case "$type" in
      "instance_snapshot")
        echo "Deleting instance snapshot: $name"
        aws lightsail delete-instance-snapshot --instance-snapshot-name "$name" --region $AWS_REGION
        ;;
      "disk_snapshot")
        echo "Deleting disk snapshot: $name"
        aws lightsail delete-disk-snapshot --disk-snapshot-name "$name" --region $AWS_REGION
        ;;
      "disk")
        echo "Detaching disk: $name"
        aws lightsail detach-disk --disk-name "$name" --region $AWS_REGION
        sleep 10 # Wait for detach to complete
        echo "Deleting disk: $name"
        aws lightsail delete-disk --disk-name "$name" --region $AWS_REGION
        ;;
      "instance")
        echo "Deleting instance: $name"
        # Check instance state before attempting to delete
        INSTANCE_STATE=$(aws lightsail get-instance-state --instance-name "$name" --region $AWS_REGION --query 'state.name' --output text 2>/dev/null)
        if [ "$INSTANCE_STATE" == "pending" ]; then
          echo "Instance is in pending state. Waiting for it to be ready before deleting..."
          MAX_WAIT=30
          WAITED=0
          while [ "$INSTANCE_STATE" == "pending" ] && [ $WAITED -lt $MAX_WAIT ]; do
            sleep 10
            WAITED=$((WAITED+1))
            INSTANCE_STATE=$(aws lightsail get-instance-state --instance-name "$name" --region $AWS_REGION --query 'state.name' --output text 2>/dev/null)
            echo "Instance state: $INSTANCE_STATE"
          done
        fi
        aws lightsail delete-instance --instance-name "$name" --region $AWS_REGION
        ;;
    esac
  done
  
  echo "Cleanup completed"
}

# Step 1: Verify AWS CLI configuration
echo "Step 1: Verifying AWS CLI configuration"
aws configure list
check_status "Failed to verify AWS CLI configuration"

# Step 2: Get available blueprints and bundles
echo "Step 2: Getting available blueprints and bundles"
echo "Available blueprints (showing first 5):"
aws lightsail get-blueprints --region $AWS_REGION --query 'blueprints[0:5].[blueprintId,name]' --output table
check_status "Failed to get blueprints"

echo "Available bundles (showing first 5):"
aws lightsail get-bundles --region $AWS_REGION --query 'bundles[0:5].[bundleId,name,price]' --output table
check_status "Failed to get bundles"

# Get available regions and availability zones
echo "Getting available regions and availability zones"
# Use a specific availability zone in us-west-2 region
AVAILABILITY_ZONE="us-west-2a"
echo "Using availability zone: $AVAILABILITY_ZONE"

# Step 3: Create a Lightsail instance
echo "Step 3: Creating Lightsail instance: $INSTANCE_NAME"
aws lightsail create-instances \
  --instance-names "$INSTANCE_NAME" \
  --availability-zone "$AVAILABILITY_ZONE" \
  --blueprint-id amazon_linux_2023 \
  --bundle-id nano_3_0 \
  --region $AWS_REGION
check_status "Failed to create Lightsail instance"
track_resource "instance" "$INSTANCE_NAME"

# Wait for the instance to be in a running state
echo "Waiting for instance to be in running state..."
# Wait for the instance to be ready (polling approach)
MAX_ATTEMPTS=30
ATTEMPTS=0
while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; do
  STATUS=$(aws lightsail get-instance-state --instance-name "$INSTANCE_NAME" --region $AWS_REGION --query 'state.name' --output text)
  if [ "$STATUS" == "running" ]; then
    echo "Instance is now running"
    break
  fi
  echo "Instance status: $STATUS. Waiting..."
  ATTEMPTS=$((ATTEMPTS+1))
  sleep 10
done

if [ $ATTEMPTS -eq $MAX_ATTEMPTS ]; then
  handle_error "Instance failed to reach running state after 5 minutes"
fi

# Get instance details
echo "Getting instance details"
INSTANCE_IP=$(aws lightsail get-instance --instance-name "$INSTANCE_NAME" --region $AWS_REGION --query 'instance.publicIpAddress' --output text)
check_status "Failed to get instance IP address"
echo "Instance IP address: $INSTANCE_IP"

# Step 4: Download the default key pair
echo "Step 4: Downloading default key pair"
KEY_FILE="lightsail_key_${RANDOM_ID}.pem"
aws lightsail download-default-key-pair --region $AWS_REGION --output text > "$KEY_FILE"
check_status "Failed to download key pair"
chmod 400 "$KEY_FILE"
check_status "Failed to set permissions on key pair"
echo "Key pair downloaded to $KEY_FILE"

echo "To connect to your instance, use:"
echo "ssh -i $KEY_FILE ec2-user@$INSTANCE_IP"

# Step 5: Create a block storage disk
echo "Step 5: Creating block storage disk: $DISK_NAME"
aws lightsail create-disk \
  --disk-name "$DISK_NAME" \
  --availability-zone "$AVAILABILITY_ZONE" \
  --size-in-gb 8 \
  --region $AWS_REGION
check_status "Failed to create disk"
track_resource "disk" "$DISK_NAME"

# FIX: Wait for the disk to be available using polling instead of fixed sleep
echo "Waiting for disk to be available..."
MAX_ATTEMPTS=30
ATTEMPTS=0
while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; do
  DISK_STATE=$(aws lightsail get-disk --disk-name "$DISK_NAME" --region $AWS_REGION --query 'disk.state' --output text 2>/dev/null)
  if [ "$DISK_STATE" == "available" ]; then
    echo "Disk is now available"
    break
  fi
  echo "Disk status: $DISK_STATE. Waiting..."
  ATTEMPTS=$((ATTEMPTS+1))
  sleep 10
done

if [ $ATTEMPTS -eq $MAX_ATTEMPTS ]; then
  handle_error "Disk failed to become available after 5 minutes"
fi

# Attach the disk to the instance
echo "Attaching disk to instance"
aws lightsail attach-disk \
  --disk-name "$DISK_NAME" \
  --instance-name "$INSTANCE_NAME" \
  --disk-path /dev/xvdf \
  --region $AWS_REGION
check_status "Failed to attach disk to instance"

echo "Disk attached. To format and mount the disk, connect to your instance and run:"
echo "sudo mkfs -t ext4 /dev/xvdf"
echo "sudo mkdir -p /mnt/my-data"
echo "sudo mount /dev/xvdf /mnt/my-data"
echo "sudo chown ec2-user:ec2-user /mnt/my-data"

# Step 6: Create a snapshot of the instance
echo "Step 6: Creating snapshot of the instance: $SNAPSHOT_NAME"
aws lightsail create-instance-snapshot \
  --instance-name "$INSTANCE_NAME" \
  --instance-snapshot-name "$SNAPSHOT_NAME" \
  --region $AWS_REGION
check_status "Failed to create instance snapshot"
track_resource "instance_snapshot" "$SNAPSHOT_NAME"

# FIX: Wait for the snapshot to complete using polling instead of fixed sleep
echo "Waiting for snapshot to complete... (this may take several minutes)"
MAX_ATTEMPTS=60  # Increased timeout for snapshot creation
ATTEMPTS=0
while [ $ATTEMPTS -lt $MAX_ATTEMPTS ]; do
  SNAPSHOT_STATE=$(aws lightsail get-instance-snapshot --instance-snapshot-name "$SNAPSHOT_NAME" --region $AWS_REGION --query 'instanceSnapshot.state' --output text 2>/dev/null)
  if [ "$SNAPSHOT_STATE" == "completed" ]; then
    echo "Snapshot creation completed"
    break
  fi
  echo "Snapshot status: $SNAPSHOT_STATE. Waiting... ($ATTEMPTS/$MAX_ATTEMPTS)"
  ATTEMPTS=$((ATTEMPTS+1))
  sleep 10
done

if [ $ATTEMPTS -eq $MAX_ATTEMPTS ]; then
  echo "Warning: Snapshot creation is taking longer than expected but will continue in the background."
  echo "You can check its status later with: aws lightsail get-instance-snapshot --instance-snapshot-name $SNAPSHOT_NAME --region $AWS_REGION"
fi

# Step 7: Clean up resources
echo "Step 7: Clean up resources"
echo "The script has created the following resources:"
for resource in "${CREATED_RESOURCES[@]}"; do
  echo "  $resource"
done

read -p "Do you want to clean up these resources? (y/n): " CLEANUP_CONFIRM
if [[ "$CLEANUP_CONFIRM" == "y" || "$CLEANUP_CONFIRM" == "Y" ]]; then
  cleanup_resources
else
  echo "Resources will not be cleaned up. You can manually delete them later."
  echo "To clean up manually, use the following commands:"
  echo "aws lightsail delete-instance-snapshot --instance-snapshot-name $SNAPSHOT_NAME --region $AWS_REGION"
  echo "aws lightsail detach-disk --disk-name $DISK_NAME --region $AWS_REGION"
  echo "aws lightsail delete-disk --disk-name $DISK_NAME --region $AWS_REGION"
  echo "aws lightsail delete-instance --instance-name $INSTANCE_NAME --region $AWS_REGION"
fi

echo "Script completed at $(date)"
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [AttachDisk](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/AttachDisk)
  + [CreateDisk](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/CreateDisk)
  + [CreateInstanceSnapshot](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/CreateInstanceSnapshot)
  + [CreateInstances](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/CreateInstances)
  + [DeleteDisk](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/DeleteDisk)
  + [DeleteInstance](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/DeleteInstance)
  + [DeleteInstanceSnapshot](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/DeleteInstanceSnapshot)
  + [DetachDisk](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/DetachDisk)
  + [DownloadDefaultKeyPair](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/DownloadDefaultKeyPair)
  + [GetBlueprints](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/GetBlueprints)
  + [GetBundles](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/GetBundles)
  + [GetDisk](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/GetDisk)
  + [GetInstance](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/GetInstance)
  + [GetInstanceSnapshot](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/GetInstanceSnapshot)
  + [GetInstanceState](https://docs.aws.amazon.com/goto/aws-cli/lightsail-2016-11-28/GetInstanceState)

# Bash スクリプトで を使用する Amazon S3 の例 AWS CLI
<a name="bash_2_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS Command Line Interface で Bash スクリプトで を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function s3_getting_started
#
# This function creates, copies, and deletes S3 buckets and objects.
#
# Returns:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function s3_getting_started() {
  {
    if [ "$BUCKET_OPERATIONS_SOURCED" != "True" ]; then
      cd bucket-lifecycle-operations || exit

      source ./bucket_operations.sh
      cd ..
    fi
  }

  echo_repeat "*" 88
  echo "Welcome to the Amazon S3 getting started demo."
  echo_repeat "*" 88
    echo "A unique bucket will be created by appending a Universally Unique Identifier to a bucket name prefix."
    echo -n "Enter a prefix for the S3 bucket that will be used in this demo: "
    get_input
    bucket_name_prefix=$get_input_result
  local bucket_name
  bucket_name=$(generate_random_name "$bucket_name_prefix")

  local region_code
  region_code=$(aws configure get region)

  if create_bucket -b "$bucket_name" -r "$region_code"; then
    echo "Created demo bucket named $bucket_name"
  else
    errecho "The bucket failed to create. This demo will exit."
    return 1
  fi

  local file_name
  while [ -z "$file_name" ]; do
    echo -n "Enter a file you want to upload to your bucket: "
    get_input
    file_name=$get_input_result

    if [ ! -f "$file_name" ]; then
      echo "Could not find file $file_name. Are you sure it exists?"
      file_name=""
    fi
  done

  local key
  key="$(basename "$file_name")"

  local result=0
  if copy_file_to_bucket "$bucket_name" "$file_name" "$key"; then
    echo "Uploaded file $file_name into bucket $bucket_name with key $key."
  else
    result=1
  fi

  local destination_file
  destination_file="$file_name.download"
  if yes_no_input "Would you like to download $key to the file $destination_file? (y/n) "; then
    if download_object_from_bucket "$bucket_name" "$destination_file" "$key"; then
      echo "Downloaded $key in the bucket $bucket_name to the file $destination_file."
    else
      result=1
    fi
  fi

  if yes_no_input "Would you like to copy $key a new object key in your bucket? (y/n) "; then
    local to_key
    to_key="demo/$key"
    if copy_item_in_bucket "$bucket_name" "$key" "$to_key"; then
      echo "Copied $key in the bucket $bucket_name to the  $to_key."
    else
      result=1
    fi
  fi

  local bucket_items
  bucket_items=$(list_items_in_bucket "$bucket_name")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    result=1
  fi

  echo "Your bucket contains the following items."
  echo -e "Name\t\tSize"
  echo "$bucket_items"

  if yes_no_input "Delete the bucket, $bucket_name, as well as the objects in it? (y/n) "; then
    bucket_items=$(echo "$bucket_items" | cut -f 1)

    if delete_items_in_bucket "$bucket_name" "$bucket_items"; then
      echo "The following items were deleted from the bucket $bucket_name"
      echo "$bucket_items"
    else
      result=1
    fi

    if delete_bucket "$bucket_name"; then
      echo "Deleted the bucket $bucket_name"
    else
      result=1
    fi
  fi

  return $result
}
```
このシナリオで使用される Amazon S3 関数。  

```
###############################################################################
# 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
}

###############################################################################
# function copy_file_to_bucket
#
# This function creates a file in the specified bucket.
#
# Parameters:
#       $1 - The name of the bucket to copy the file to.
#       $2 - The path and file name of the local file to copy to the bucket.
#       $3 - The key (name) to call the copy of the file in the bucket.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function copy_file_to_bucket() {
  local response bucket_name source_file destination_file_name
  bucket_name=$1
  source_file=$2
  destination_file_name=$3

  response=$(aws s3api put-object \
    --bucket "$bucket_name" \
    --body "$source_file" \
    --key "$destination_file_name")

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    errecho "ERROR: AWS reports put-object operation failed.\n$response"
    return 1
  fi
}

###############################################################################
# function download_object_from_bucket
#
# This function downloads an object in a bucket to a file.
#
# Parameters:
#       $1 - The name of the bucket to download the object from.
#       $2 - The path and file name to store the downloaded bucket.
#       $3 - The key (name) of the object in the bucket.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function download_object_from_bucket() {
  local bucket_name=$1
  local destination_file_name=$2
  local object_name=$3
  local response

  response=$(aws s3api get-object \
    --bucket "$bucket_name" \
    --key "$object_name" \
    "$destination_file_name")

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    errecho "ERROR: AWS reports put-object operation failed.\n$response"
    return 1
  fi
}

###############################################################################
# function copy_item_in_bucket
#
# This function creates a copy of the specified file in the same bucket.
#
# Parameters:
#       $1 - The name of the bucket to copy the file from and to.
#       $2 - The key of the source file to copy.
#       $3 - The key of the destination file.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function copy_item_in_bucket() {
  local bucket_name=$1
  local source_key=$2
  local destination_key=$3
  local response

  response=$(aws s3api copy-object \
    --bucket "$bucket_name" \
    --copy-source "$bucket_name/$source_key" \
    --key "$destination_key")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    errecho "ERROR:  AWS reports s3api copy-object operation failed.\n$response"
    return 1
  fi
}

###############################################################################
# function list_items_in_bucket
#
# This function displays a list of the files in the bucket with each file's
# size. The function uses the --query parameter to retrieve only the key and
# size fields from the Contents collection.
#
# Parameters:
#       $1 - The name of the bucket.
#
# Returns:
#       The list of files in text format.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function list_items_in_bucket() {
  local bucket_name=$1
  local response

  response=$(aws s3api list-objects \
    --bucket "$bucket_name" \
    --output text \
    --query 'Contents[].{Key: Key, Size: Size}')

  # shellcheck disable=SC2181
  if [[ ${?} -eq 0 ]]; then
    echo "$response"
  else
    errecho "ERROR: AWS reports s3api list-objects operation failed.\n$response"
    return 1
  fi
}

###############################################################################
# function delete_items_in_bucket
#
# This function deletes the specified list of keys from the specified bucket.
#
# Parameters:
#       $1 - The name of the bucket.
#       $2 - A list of keys in the bucket to delete.

# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function delete_items_in_bucket() {
  local bucket_name=$1
  local keys=$2
  local response

  # Create the JSON for the items to delete.
  local delete_items
  delete_items="{\"Objects\":["
  for key in $keys; do
    delete_items="$delete_items{\"Key\": \"$key\"},"
  done
  delete_items=${delete_items%?} # Remove the final comma.
  delete_items="$delete_items]}"

  response=$(aws s3api delete-objects \
    --bucket "$bucket_name" \
    --delete "$delete_items")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    errecho "ERROR:  AWS reports s3api delete-object operation failed.\n$response"
    return 1
  fi
}

###############################################################################
# function delete_bucket
#
# This function deletes the specified bucket.
#
# Parameters:
#       $1 - The name of the bucket.

# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function delete_bucket() {
  local bucket_name=$1
  local response

  response=$(aws s3api delete-bucket \
    --bucket "$bucket_name")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    errecho "ERROR: AWS reports s3api delete-bucket failed.\n$response"
    return 1
  fi
}
```
+ API の詳細については、「*AWS CLI コマンドリファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/GetObject)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/ListObjectsV2)
  + [PutObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_bash_2_topic"></a>

次の例は、`CopyObject` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function copy_item_in_bucket
#
# This function creates a copy of the specified file in the same bucket.
#
# Parameters:
#       $1 - The name of the bucket to copy the file from and to.
#       $2 - The key of the source file to copy.
#       $3 - The key of the destination file.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function copy_item_in_bucket() {
  local bucket_name=$1
  local source_key=$2
  local destination_key=$3
  local response

  response=$(aws s3api copy-object \
    --bucket "$bucket_name" \
    --copy-source "$bucket_name/$source_key" \
    --key "$destination_key")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    errecho "ERROR:  AWS reports s3api copy-object operation failed.\n$response"
    return 1
  fi
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CopyObject)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_bash_2_topic"></a>

次の例は、`CreateBucket` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# 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
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CreateBucket)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_bash_2_topic"></a>

次の例は、`DeleteBucket` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function delete_bucket
#
# This function deletes the specified bucket.
#
# Parameters:
#       $1 - The name of the bucket.

# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function delete_bucket() {
  local bucket_name=$1
  local response

  response=$(aws s3api delete-bucket \
    --bucket "$bucket_name")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    errecho "ERROR: AWS reports s3api delete-bucket failed.\n$response"
    return 1
  fi
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/DeleteBucket)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_bash_2_topic"></a>

次の例は、`DeleteObject` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function delete_item_in_bucket
#
# This function deletes the specified file from the specified bucket.
#
# Parameters:
#       $1 - The name of the bucket.
#       $2 - The key (file name) in the bucket to delete.

# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function delete_item_in_bucket() {
  local bucket_name=$1
  local key=$2
  local response

  response=$(aws s3api delete-object \
    --bucket "$bucket_name" \
    --key "$key")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    errecho "ERROR:  AWS reports s3api delete-object operation failed.\n$response"
    return 1
  fi
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_bash_2_topic"></a>

次の例は、`DeleteObjects` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function delete_items_in_bucket
#
# This function deletes the specified list of keys from the specified bucket.
#
# Parameters:
#       $1 - The name of the bucket.
#       $2 - A list of keys in the bucket to delete.

# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function delete_items_in_bucket() {
  local bucket_name=$1
  local keys=$2
  local response

  # Create the JSON for the items to delete.
  local delete_items
  delete_items="{\"Objects\":["
  for key in $keys; do
    delete_items="$delete_items{\"Key\": \"$key\"},"
  done
  delete_items=${delete_items%?} # Remove the final comma.
  delete_items="$delete_items]}"

  response=$(aws s3api delete-objects \
    --bucket "$bucket_name" \
    --delete "$delete_items")

  # shellcheck disable=SC2181
  if [[ $? -ne 0 ]]; then
    errecho "ERROR:  AWS reports s3api delete-object operation failed.\n$response"
    return 1
  fi
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteObjects](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/DeleteObjects)」を参照してください。

### `GetObject`
<a name="s3_GetObject_bash_2_topic"></a>

次の例は、`GetObject` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function download_object_from_bucket
#
# This function downloads an object in a bucket to a file.
#
# Parameters:
#       $1 - The name of the bucket to download the object from.
#       $2 - The path and file name to store the downloaded bucket.
#       $3 - The key (name) of the object in the bucket.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function download_object_from_bucket() {
  local bucket_name=$1
  local destination_file_name=$2
  local object_name=$3
  local response

  response=$(aws s3api get-object \
    --bucket "$bucket_name" \
    --key "$object_name" \
    "$destination_file_name")

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    errecho "ERROR: AWS reports put-object operation failed.\n$response"
    return 1
  fi
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/GetObject)」を参照してください。

### `HeadBucket`
<a name="s3_HeadBucket_bash_2_topic"></a>

次の例は、`HeadBucket` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function bucket_exists
#
# This function checks to see if the specified bucket already exists.
#
# Parameters:
#       $1 - The name of the bucket to check.
#
# Returns:
#       0 - If the bucket already exists.
#       1 - If the bucket doesn't exist.
###############################################################################
function bucket_exists() {
  local bucket_name
  bucket_name=$1

  # Check whether the bucket already exists.
  # We suppress all output - we're interested only in the return code.

  if aws s3api head-bucket \
    --bucket "$bucket_name" \
    >/dev/null 2>&1; then
    return 0 # 0 in Bash script means true.
  else
    return 1 # 1 in Bash script means false.
  fi
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[HeadBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/HeadBucket)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_bash_2_topic"></a>

次の例は、`ListObjectsV2` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function list_items_in_bucket
#
# This function displays a list of the files in the bucket with each file's
# size. The function uses the --query parameter to retrieve only the key and
# size fields from the Contents collection.
#
# Parameters:
#       $1 - The name of the bucket.
#
# Returns:
#       The list of files in text format.
#     And:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function list_items_in_bucket() {
  local bucket_name=$1
  local response

  response=$(aws s3api list-objects \
    --bucket "$bucket_name" \
    --output text \
    --query 'Contents[].{Key: Key, Size: Size}')

  # shellcheck disable=SC2181
  if [[ ${?} -eq 0 ]]; then
    echo "$response"
  else
    errecho "ERROR: AWS reports s3api list-objects operation failed.\n$response"
    return 1
  fi
}
```
+  API の詳細については、「AWS CLI API リファレンス」の「[ListObjectsV2](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/ListObjectsV2)」を参照してください。**

### `PutObject`
<a name="s3_PutObject_bash_2_topic"></a>

次の例は、`PutObject` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/s3#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# function errecho
#
# This function outputs everything sent to it to STDERR (standard error output).
###############################################################################
function errecho() {
  printf "%s\n" "$*" 1>&2
}

###############################################################################
# function copy_file_to_bucket
#
# This function creates a file in the specified bucket.
#
# Parameters:
#       $1 - The name of the bucket to copy the file to.
#       $2 - The path and file name of the local file to copy to the bucket.
#       $3 - The key (name) to call the copy of the file in the bucket.
#
# Returns:
#       0 - If successful.
#       1 - If it fails.
###############################################################################
function copy_file_to_bucket() {
  local response bucket_name source_file destination_file_name
  bucket_name=$1
  source_file=$2
  destination_file_name=$3

  response=$(aws s3api put-object \
    --bucket "$bucket_name" \
    --body "$source_file" \
    --key "$destination_file_name")

  # shellcheck disable=SC2181
  if [[ ${?} -ne 0 ]]; then
    errecho "ERROR: AWS reports put-object operation failed.\n$response"
    return 1
  fi
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/PutObject)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### S3 の開始方法
<a name="s3_GettingStarted_bash_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 一意の命名とリージョン設定を使用して S3 バケットを作成する
+ パブリックアクセスブロックを含むバケットセキュリティ設定を構成する
+ データ保護のためにバージョニングとデフォルトの暗号化を有効にする
+ カスタムメタデータの有無にかかわらずオブジェクトをアップロードする
+ バケットからローカルストレージにオブジェクトをダウンロードする
+ バケット内のオブジェクトをコピーしてフォルダにデータを整理する
+ 特定のプレフィックスを持つバケットコンテンツとオブジェクトを一覧表示する
+ リソース管理のためにバケットにタグを追加する
+ バージョニングされたオブジェクトを含むすべてのリソースをクリーンアップする

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。[デベロッパーチュートリアルのサンプル](https://github.com/aws-samples/sample-developer-tutorials/tree/main/tuts/003-s3-gettingstarted)レポジトリで用例一覧を検索し、設定と実行の方法を確認してください。

```
#!/bin/bash

# Amazon S3 Getting Started Tutorial Script
# This script demonstrates basic S3 operations including:
# - Creating a bucket
# - Configuring bucket settings
# - Uploading, downloading, and copying objects
# - Deleting objects and buckets

# Latest fixes:
# 1. Fixed folder creation using temporary file
# 2. Corrected versioned object deletion in cleanup
# 3. Improved error handling for cleanup operations

# Set up error handling
set -e
trap 'cleanup_handler $?' EXIT

# Log file setup
LOG_FILE="s3-tutorial-$(date +%Y%m%d-%H%M%S).log"
exec > >(tee -a "$LOG_FILE") 2>&1

# Function to log messages
log() {
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] $1"
}

# Function to handle errors
handle_error() {
    log "ERROR: $1"
    exit 1
}

# Function to check if a bucket exists
bucket_exists() {
    if aws s3api head-bucket --bucket "$1" 2>/dev/null; then
        return 0
    else
        return 1
    fi
}

# Function to delete all versions of objects in a bucket
delete_all_versions() {
    local bucket=$1
    log "Deleting all object versions from bucket $bucket..."
    
    # Get and delete all versions
    versions=$(aws s3api list-object-versions --bucket "$bucket" --query 'Versions[].{Key:Key,VersionId:VersionId}' --output json 2>/dev/null)
    if [ -n "$versions" ] && [ "$versions" != "null" ]; then
        echo "{\"Objects\": $versions}" | aws s3api delete-objects --bucket "$bucket" --delete file:///dev/stdin >/dev/null 2>&1 || log "Warning: Some versions could not be deleted"
    fi
    
    # Get and delete all delete markers
    markers=$(aws s3api list-object-versions --bucket "$bucket" --query 'DeleteMarkers[].{Key:Key,VersionId:VersionId}' --output json 2>/dev/null)
    if [ -n "$markers" ] && [ "$markers" != "null" ]; then
        echo "{\"Objects\": $markers}" | aws s3api delete-objects --bucket "$bucket" --delete file:///dev/stdin >/dev/null 2>&1 || log "Warning: Some delete markers could not be deleted"
    fi
}

# Function to handle cleanup on exit
cleanup_handler() {
    local exit_code=$1
    
    # Only run cleanup if it hasn't been run already
    if [ -z "$CLEANUP_DONE" ]; then
        cleanup
    fi
    
    exit $exit_code
}

# Function to clean up resources
cleanup() {
    log "Starting cleanup process..."
    CLEANUP_DONE=1
    
    # List all resources created for confirmation
    log "Resources created:"
    if [ -n "$BUCKET_NAME" ]; then
        log "- S3 Bucket: $BUCKET_NAME"
        
        # Only try to list objects if the bucket exists
        if bucket_exists "$BUCKET_NAME"; then
            # Check if any objects were created
            OBJECTS=$(aws s3api list-objects-v2 --bucket "$BUCKET_NAME" --query 'Contents[].Key' --output text 2>/dev/null || echo "")
            if [ -n "$OBJECTS" ]; then
                log "- Objects in bucket:"
                echo "$OBJECTS" | tr '\t' '\n' | while read -r obj; do
                    log "  - $obj"
                done
            fi
            
            # Ask for confirmation before cleanup
            read -p "Do you want to proceed with cleanup and delete all resources? (y/n): " confirm
            if [[ $confirm != [yY] && $confirm != [yY][eE][sS] ]]; then
                log "Cleanup aborted by user."
                return
            fi
            
            # Delete all versions of objects
            delete_all_versions "$BUCKET_NAME"
            
            # Delete the bucket
            log "Deleting bucket $BUCKET_NAME..."
            aws s3api delete-bucket --bucket "$BUCKET_NAME" || log "Warning: Failed to delete bucket"
        else
            log "Bucket $BUCKET_NAME does not exist, skipping cleanup"
        fi
    fi
    
    # Clean up local files
    log "Removing local files..."
    rm -f sample-file.txt sample-document.txt downloaded-sample-file.txt empty-file.tmp
    
    log "Cleanup completed."
}

# Generate a random bucket name
generate_bucket_name() {
    local hex_id
    hex_id=$(openssl rand -hex 6)
    echo "demo-s3-bucket-$hex_id"
}

# Main script execution
main() {
    log "Starting Amazon S3 Getting Started Tutorial"
    
    # Generate a unique bucket name
    BUCKET_NAME=$(generate_bucket_name)
    log "Generated bucket name: $BUCKET_NAME"
    
    # Step 1: Create a bucket
    log "Step 1: Creating S3 bucket..."
    
    # Get the current region or default to us-east-1
    REGION=$(aws configure get region)
    REGION=${REGION:-us-east-1}
    log "Using region: $REGION"
    
    if [ "$REGION" = "us-east-1" ]; then
        aws s3api create-bucket --bucket "$BUCKET_NAME" || handle_error "Failed to create bucket"
    else
        aws s3api create-bucket \
            --bucket "$BUCKET_NAME" \
            --region "$REGION" \
            --create-bucket-configuration LocationConstraint="$REGION" || handle_error "Failed to create bucket"
    fi
    log "Bucket created successfully"
    
    # Configure bucket settings
    log "Configuring bucket settings..."
    
    # Block public access (security best practice)
    log "Blocking public access..."
    aws s3api put-public-access-block \
        --bucket "$BUCKET_NAME" \
        --public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true" || handle_error "Failed to configure public access block"
    
    # Enable versioning
    log "Enabling versioning..."
    aws s3api put-bucket-versioning \
        --bucket "$BUCKET_NAME" \
        --versioning-configuration Status=Enabled || handle_error "Failed to enable versioning"
    
    # Set default encryption
    log "Setting default encryption..."
    aws s3api put-bucket-encryption \
        --bucket "$BUCKET_NAME" \
        --server-side-encryption-configuration '{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}' || handle_error "Failed to set encryption"
    
    # Step 2: Upload an object
    log "Step 2: Uploading objects to bucket..."
    
    # Create a sample file
    echo "This is a sample file for the S3 tutorial." > sample-file.txt
    
    # Upload the file
    aws s3api put-object \
        --bucket "$BUCKET_NAME" \
        --key "sample-file.txt" \
        --body "sample-file.txt" || handle_error "Failed to upload object"
    log "Object uploaded successfully"
    
    # Upload with metadata
    echo "This is a document with metadata." > sample-document.txt
    aws s3api put-object \
        --bucket "$BUCKET_NAME" \
        --key "documents/sample-document.txt" \
        --body "sample-document.txt" \
        --content-type "text/plain" \
        --metadata "author=AWSDocumentation,purpose=tutorial" || handle_error "Failed to upload object with metadata"
    log "Object with metadata uploaded successfully"
    
    # Step 3: Download an object
    log "Step 3: Downloading object from bucket..."
    aws s3api get-object \
        --bucket "$BUCKET_NAME" \
        --key "sample-file.txt" \
        "downloaded-sample-file.txt" || handle_error "Failed to download object"
    log "Object downloaded successfully"
    
    # Check if an object exists
    log "Checking if object exists..."
    aws s3api head-object \
        --bucket "$BUCKET_NAME" \
        --key "sample-file.txt" || handle_error "Object does not exist"
    log "Object exists"
    
    # Step 4: Copy object to a folder
    log "Step 4: Copying object to a folder..."
    
    # Create a folder structure using a temporary empty file
    log "Creating folder structure..."
    touch empty-file.tmp
    aws s3api put-object \
        --bucket "$BUCKET_NAME" \
        --key "favorite-files/" \
        --body empty-file.tmp || handle_error "Failed to create folder"
    
    # Copy the object
    log "Copying object..."
    aws s3api copy-object \
        --bucket "$BUCKET_NAME" \
        --copy-source "$BUCKET_NAME/sample-file.txt" \
        --key "favorite-files/sample-file.txt" || handle_error "Failed to copy object"
    log "Object copied successfully"
    
    # List objects in the bucket
    log "Listing all objects in the bucket..."
    aws s3api list-objects-v2 \
        --bucket "$BUCKET_NAME" \
        --query 'Contents[].Key' \
        --output table || handle_error "Failed to list objects"
    
    # List objects with a specific prefix
    log "Listing objects in the favorite-files folder..."
    aws s3api list-objects-v2 \
        --bucket "$BUCKET_NAME" \
        --prefix "favorite-files/" \
        --query 'Contents[].Key' \
        --output table || handle_error "Failed to list objects with prefix"
    
    # Add tags to the bucket
    log "Adding tags to the bucket..."
    aws s3api put-bucket-tagging \
        --bucket "$BUCKET_NAME" \
        --tagging 'TagSet=[{Key=Project,Value=S3Tutorial},{Key=Environment,Value=Demo}]' || handle_error "Failed to add tags"
    log "Tags added successfully"
    
    log "Tutorial completed successfully!"
}

# Execute the main function
main
```
+ API の詳細については、*AWS CLI コマンドリファレンス*の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/GetObject)
  + [HeadObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/HeadObject)
  + [ListObjectVersions](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/ListObjectVersions)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/ListObjectsV2)
  + [PutBucketEncryption](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/PutBucketEncryption)
  + [PutBucketTagging](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/PutBucketTagging)
  + [PutBucketVersioning](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/PutBucketVersioning)
  + [PutObject](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/PutObject)
  + [PutPublicAccessBlock](https://docs.aws.amazon.com/goto/aws-cli/s3-2006-03-01/PutPublicAccessBlock)

# AWS STS Bash スクリプト AWS CLI で を使用する例
<a name="bash_2_sts_code_examples"></a>

次のコード例は、Bash スクリプト AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_bash_2_topic"></a>

次の例は、`AssumeRole` を使用する方法を説明しています。

**AWS CLI Bash スクリプトを使用する**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/aws-cli/bash-linux/iam#code-examples)での設定と実行の方法を確認してください。

```
###############################################################################
# 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 sts_assume_role
#
# This function assumes a role in the AWS account and returns the temporary
#  credentials.
#
# Parameters:
#       -n role_session_name -- The name of the session.
#       -r role_arn -- The ARN of the role to assume.
#
# Returns:
#       [access_key_id, secret_access_key, session_token]
#     And:
#       0 - If successful.
#       1 - If an error occurred.
###############################################################################
function sts_assume_role() {
  local role_session_name role_arn response
  local option OPTARG # Required to use getopts command in a function.

  # bashsupport disable=BP5008
  function usage() {
    echo "function sts_assume_role"
    echo "Assumes a role in the AWS account and returns the temporary credentials:"
    echo "  -n role_session_name -- The name of the session."
    echo "  -r role_arn -- The ARN of the role to assume."
    echo ""
  }

  while getopts n:r:h option; do
    case "${option}" in
      n) role_session_name=${OPTARG} ;;
      r) role_arn=${OPTARG} ;;
      h)
        usage
        return 0
        ;;
      \?)
        echo "Invalid parameter"
        usage
        return 1
        ;;
    esac
  done

  response=$(aws sts assume-role \
    --role-session-name "$role_session_name" \
    --role-arn "$role_arn" \
    --output text \
    --query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]")

  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 コマンドリファレンス*」の「[AssumeRole](https://docs.aws.amazon.com/goto/aws-cli/sts-2011-06-15/AssumeRole)」を参照してください。

# SDK for C\$1\$1 のコード例
<a name="cpp_1_code_examples"></a>

次のコード例は、 AWS SDK for C\$1\$1 で を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for C\$1\$1 デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/welcome.html) ** – で C\$1\$1 を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23c-plusplus)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](cpp_1_acm_code_examples.md)
+ [API ゲートウェイ](cpp_1_api-gateway_code_examples.md)
+ [Aurora](cpp_1_aurora_code_examples.md)
+ [Auto Scaling](cpp_1_auto-scaling_code_examples.md)
+ [CloudTrail](cpp_1_cloudtrail_code_examples.md)
+ [CloudWatch](cpp_1_cloudwatch_code_examples.md)
+ [CloudWatch Logs](cpp_1_cloudwatch-logs_code_examples.md)
+ [CodeBuild](cpp_1_codebuild_code_examples.md)
+ [Amazon Cognito ID プロバイダー](cpp_1_cognito-identity-provider_code_examples.md)
+ [DynamoDB](cpp_1_dynamodb_code_examples.md)
+ [Amazon EC2](cpp_1_ec2_code_examples.md)
+ [EventBridge](cpp_1_eventbridge_code_examples.md)
+ [AWS Glue](cpp_1_glue_code_examples.md)
+ [HealthImaging](cpp_1_medical-imaging_code_examples.md)
+ [IAM](cpp_1_iam_code_examples.md)
+ [AWS IoT](cpp_1_iot_code_examples.md)
+ [AWS IoT data](cpp_1_iot-data-plane_code_examples.md)
+ [Lambda](cpp_1_lambda_code_examples.md)
+ [MediaConvert](cpp_1_mediaconvert_code_examples.md)
+ [Amazon RDS](cpp_1_rds_code_examples.md)
+ [Amazon RDS データサービス](cpp_1_rds-data_code_examples.md)
+ [Amazon Rekognition](cpp_1_rekognition_code_examples.md)
+ [Amazon S3](cpp_1_s3_code_examples.md)
+ [Secrets Manager](cpp_1_secrets-manager_code_examples.md)
+ [Amazon SES](cpp_1_ses_code_examples.md)
+ [Amazon SNS](cpp_1_sns_code_examples.md)
+ [Amazon SQS](cpp_1_sqs_code_examples.md)
+ [AWS STS](cpp_1_sts_code_examples.md)
+ [Amazon Transcribe ストリーミング](cpp_1_transcribe-streaming_code_examples.md)

# SDK for C\$1\$1 を使用した ACM の例
<a name="cpp_1_acm_code_examples"></a>

次のコード例は、ACM AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AddTagsToCertificate`
<a name="acm_AddTagsToCertificate_cpp_1_topic"></a>

次のコード例は、`AddTagsToCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Add tags to an AWS Certificate Manager (ACM) certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param tagKey: The key for the tag.
  \param tagValue: The value for the tag.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::addTagsToCertificate(const Aws::String &certificateArn,
                                       const Aws::String &tagKey,
                                       const Aws::String &tagValue,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::AddTagsToCertificateRequest request;
    Aws::Vector<Aws::ACM::Model::Tag> tags;
    Aws::ACM::Model::Tag tag;

    tag.WithKey(tagKey).WithValue(tagValue);
    tags.push_back(tag);

    request.WithCertificateArn(certificateArn).WithTags(tags);

    Aws::ACM::Model::AddTagsToCertificateOutcome outcome =
            acmClient.AddTagsToCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: addTagsToCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Success: Tag with key '" << tagKey <<
                  "' and value '" << tagValue <<
                  "' added to certificate with ARN '" <<
                  certificateArn << "'." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AddTagsToCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/AddTagsToCertificate)」を参照してください。

### `DeleteCertificate`
<a name="acm_DeleteCertificate_cpp_1_topic"></a>

次のコード例は、`DeleteCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an AWS Certificate Manager (ACM) certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::deleteCertificate(const Aws::String &certificateArn,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::DeleteCertificateRequest request;
    request.WithCertificateArn(certificateArn);

    Aws::ACM::Model::DeleteCertificateOutcome outcome =
            acmClient.DeleteCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: DeleteCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Success: The certificate with the ARN '" <<
                  certificateArn << "' is deleted." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/DeleteCertificate)」を参照してください。

### `DescribeCertificate`
<a name="acm_DescribeCertificate_cpp_1_topic"></a>

次のコード例は、`DescribeCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Describe an AWS Certificate Manager (ACM) certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::describeCertificate(const Aws::String &certificateArn,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acm_client(clientConfiguration);

    Aws::ACM::Model::DescribeCertificateRequest request;
    request.WithCertificateArn(certificateArn);

    Aws::ACM::Model::DescribeCertificateOutcome outcome =
            acm_client.DescribeCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: DescribeCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        Aws::ACM::Model::CertificateDetail certificate =
                outcome.GetResult().GetCertificate();

        std::cout << "Success: Information about certificate "
                     "with ARN '" << certificateArn << "':" << std::endl << std::endl;

        std::cout << "ARN:                 " << certificate.GetCertificateArn()
                  << std::endl;
        std::cout << "Authority ARN:       " <<
                  certificate.GetCertificateAuthorityArn() << std::endl;
        std::cout << "Created at (GMT):    " <<
                  certificate.GetCreatedAt().ToGmtString(
                          Aws::Utils::DateFormat::ISO_8601)
                  << std::endl;
        std::cout << "Domain name:         " << certificate.GetDomainName()
                  << std::endl;

        Aws::Vector<Aws::ACM::Model::DomainValidation> options =
                certificate.GetDomainValidationOptions();

        if (!options.empty()) {
            std::cout << std::endl << "Domain validation information: "
                      << std::endl << std::endl;

            for (auto &validation: options) {
                std::cout << "  Domain name:              " <<
                          validation.GetDomainName() << std::endl;

                const Aws::ACM::Model::ResourceRecord &record =
                        validation.GetResourceRecord();

                std::cout << "  Resource record name:     " <<
                          record.GetName() << std::endl;

                Aws::ACM::Model::RecordType recordType = record.GetType();
                Aws::String type;

                switch (recordType) {
                    case Aws::ACM::Model::RecordType::CNAME:
                        type = "CNAME";
                        break;
                    case Aws::ACM::Model::RecordType::NOT_SET:
                        type = "Not set";
                        break;
                    default:
                        type = "Cannot determine.";
                        break;
                }

                std::cout << "  Resource record type:     " << type <<
                          std::endl;

                std::cout << "  Resource record value:    " <<
                          record.GetValue() << std::endl;

                std::cout << "  Validation domain:        " <<
                          validation.GetValidationDomain() << std::endl;

                Aws::Vector<Aws::String> emails =
                        validation.GetValidationEmails();

                if (!emails.empty()) {
                    std::cout << "  Validation emails:" << std::endl <<
                              std::endl;

                    for (auto &email: emails) {
                        std::cout << "    " << email << std::endl;
                    }

                    std::cout << std::endl;
                }

                Aws::ACM::Model::ValidationMethod validationMethod =
                        validation.GetValidationMethod();
                Aws::String method;

                switch (validationMethod) {
                    case Aws::ACM::Model::ValidationMethod::DNS:
                        method = "DNS";
                        break;
                    case Aws::ACM::Model::ValidationMethod::EMAIL:
                        method = "Email";
                        break;
                    case Aws::ACM::Model::ValidationMethod::NOT_SET:
                        method = "Not set";
                        break;
                    default:
                        method = "Cannot determine";
                }

                std::cout << "  Validation method:        " <<
                          method << std::endl;

                Aws::ACM::Model::DomainStatus domainStatus =
                        validation.GetValidationStatus();
                Aws::String status;

                switch (domainStatus) {
                    case Aws::ACM::Model::DomainStatus::FAILED:
                        status = "Failed";
                        break;
                    case Aws::ACM::Model::DomainStatus::NOT_SET:
                        status = "Not set";
                        break;
                    case Aws::ACM::Model::DomainStatus::PENDING_VALIDATION:
                        status = "Pending validation";
                        break;
                    case Aws::ACM::Model::DomainStatus::SUCCESS:
                        status = "Success";
                        break;
                    default:
                        status = "Cannot determine";
                }

                std::cout << "  Domain validation status: " << status <<
                          std::endl << std::endl;

            }
        }

        Aws::Vector<Aws::ACM::Model::ExtendedKeyUsage> usages =
                certificate.GetExtendedKeyUsages();

        if (!usages.empty()) {
            std::cout << std::endl << "Extended key usages:" <<
                      std::endl << std::endl;

            for (auto &usage: usages) {
                Aws::ACM::Model::ExtendedKeyUsageName usageName =
                        usage.GetName();
                Aws::String name;

                switch (usageName) {
                    case Aws::ACM::Model::ExtendedKeyUsageName::ANY:
                        name = "Any";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::CODE_SIGNING:
                        name = "Code signing";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::CUSTOM:
                        name = "Custom";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::EMAIL_PROTECTION:
                        name = "Email protection";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::IPSEC_END_SYSTEM:
                        name = "IPSEC end system";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::IPSEC_TUNNEL:
                        name = "IPSEC tunnel";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::IPSEC_USER:
                        name = "IPSEC user";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::NONE:
                        name = "None";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::NOT_SET:
                        name = "Not set";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::OCSP_SIGNING:
                        name = "OCSP signing";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::TIME_STAMPING:
                        name = "Time stamping";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::TLS_WEB_CLIENT_AUTHENTICATION:
                        name = "TLS web client authentication";
                        break;
                    case Aws::ACM::Model::ExtendedKeyUsageName::TLS_WEB_SERVER_AUTHENTICATION:
                        name = "TLS web server authentication";
                        break;
                    default:
                        name = "Cannot determine";
                }

                std::cout << "  Name: " << name << std::endl;
                std::cout << "  OID:  " << usage.GetOID() <<
                          std::endl << std::endl;
            }

            std::cout << std::endl;
        }

        Aws::ACM::Model::CertificateStatus certificateStatus =
                certificate.GetStatus();
        Aws::String status;

        switch (certificateStatus) {
            case Aws::ACM::Model::CertificateStatus::EXPIRED:
                status = "Expired";
                break;
            case Aws::ACM::Model::CertificateStatus::FAILED:
                status = "Failed";
                break;
            case Aws::ACM::Model::CertificateStatus::INACTIVE:
                status = "Inactive";
                break;
            case Aws::ACM::Model::CertificateStatus::ISSUED:
                status = "Issued";
                break;
            case Aws::ACM::Model::CertificateStatus::NOT_SET:
                status = "Not set";
                break;
            case Aws::ACM::Model::CertificateStatus::PENDING_VALIDATION:
                status = "Pending validation";
                break;
            case Aws::ACM::Model::CertificateStatus::REVOKED:
                status = "Revoked";
                break;
            case Aws::ACM::Model::CertificateStatus::VALIDATION_TIMED_OUT:
                status = "Validation timed out";
                break;
            default:
                status = "Cannot determine";
        }

        std::cout << "Status:              " << status << std::endl;

        if (certificate.GetStatus() ==
            Aws::ACM::Model::CertificateStatus::FAILED) {
            Aws::ACM::Model::FailureReason failureReason =
                    certificate.GetFailureReason();
            Aws::String reason;

            switch (failureReason) {
                case Aws::ACM::Model::FailureReason::ADDITIONAL_VERIFICATION_REQUIRED:
                    reason = "Additional verification required";
                    break;
                case Aws::ACM::Model::FailureReason::CAA_ERROR:
                    reason = "CAA error";
                    break;
                case Aws::ACM::Model::FailureReason::DOMAIN_NOT_ALLOWED:
                    reason = "Domain not allowed";
                    break;
                case Aws::ACM::Model::FailureReason::DOMAIN_VALIDATION_DENIED:
                    reason = "Domain validation denied";
                    break;
                case Aws::ACM::Model::FailureReason::INVALID_PUBLIC_DOMAIN:
                    reason = "Invalid public domain";
                    break;
                case Aws::ACM::Model::FailureReason::NOT_SET:
                    reason = "Not set";
                    break;
                case Aws::ACM::Model::FailureReason::NO_AVAILABLE_CONTACTS:
                    reason = "No available contacts";
                    break;
                case Aws::ACM::Model::FailureReason::OTHER:
                    reason = "Other";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_ACCESS_DENIED:
                    reason = "PCA access denied";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_INVALID_ARGS:
                    reason = "PCA invalid args";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_INVALID_ARN:
                    reason = "PCA invalid ARN";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_INVALID_DURATION:
                    reason = "PCA invalid duration";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_INVALID_STATE:
                    reason = "PCA invalid state";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_LIMIT_EXCEEDED:
                    reason = "PCA limit exceeded";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_NAME_CONSTRAINTS_VALIDATION:
                    reason = "PCA name constraints validation";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_REQUEST_FAILED:
                    reason = "PCA request failed";
                    break;
                case Aws::ACM::Model::FailureReason::PCA_RESOURCE_NOT_FOUND:
                    reason = "PCA resource not found";
                    break;
                default:
                    reason = "Cannot determine";
            }

            std::cout << "Failure reason:      " << reason << std::endl;
        }

        if (certificate.GetStatus() == Aws::ACM::Model::CertificateStatus::REVOKED) {
            std::cout << "Revoked at (GMT):    " <<
                      certificate.GetRevokedAt().ToGmtString(
                              Aws::Utils::DateFormat::ISO_8601)
                      << std::endl;

            Aws::ACM::Model::RevocationReason revocationReason =
                    certificate.GetRevocationReason();
            Aws::String reason;

            switch (revocationReason) {
                case Aws::ACM::Model::RevocationReason::AFFILIATION_CHANGED:
                    reason = "Affiliation changed";
                    break;
                case Aws::ACM::Model::RevocationReason::A_A_COMPROMISE:
                    reason = "AA compromise";
                    break;
                case Aws::ACM::Model::RevocationReason::CA_COMPROMISE:
                    reason = "CA compromise";
                    break;
                case Aws::ACM::Model::RevocationReason::CERTIFICATE_HOLD:
                    reason = "Certificate hold";
                    break;
                case Aws::ACM::Model::RevocationReason::CESSATION_OF_OPERATION:
                    reason = "Cessation of operation";
                    break;
                case Aws::ACM::Model::RevocationReason::KEY_COMPROMISE:
                    reason = "Key compromise";
                    break;
                case Aws::ACM::Model::RevocationReason::NOT_SET:
                    reason = "Not set";
                    break;
                case Aws::ACM::Model::RevocationReason::PRIVILEGE_WITHDRAWN:
                    reason = "Privilege withdrawn";
                    break;
                case Aws::ACM::Model::RevocationReason::REMOVE_FROM_CRL:
                    reason = "Revoke from CRL";
                    break;
                case Aws::ACM::Model::RevocationReason::SUPERCEDED:
                    reason = "Superceded";
                    break;
                case Aws::ACM::Model::RevocationReason::UNSPECIFIED:
                    reason = "Unspecified";
                    break;
                default:
                    reason = "Cannot determine";
            }

            std::cout << "Revocation reason:   " << reason << std::endl;
        }

        if (certificate.GetType() == Aws::ACM::Model::CertificateType::IMPORTED) {
            std::cout << "Imported at (GMT):   " <<
                      certificate.GetImportedAt().ToGmtString(
                              Aws::Utils::DateFormat::ISO_8601)
                      << std::endl;
        }

        Aws::Vector<Aws::String> inUseBys = certificate.GetInUseBy();

        if (!inUseBys.empty()) {
            std::cout << std::endl << "In use by:" << std::endl << std::endl;

            for (auto &in_use_by: inUseBys) {
                std::cout << "  " << in_use_by << std::endl;
            }

            std::cout << std::endl;
        }

        if (certificate.GetType() == Aws::ACM::Model::CertificateType::AMAZON_ISSUED &&
            certificate.GetStatus() == Aws::ACM::Model::CertificateStatus::ISSUED) {
            std::cout << "Issued at (GMT):     " <<
                      certificate.GetIssuedAt().ToGmtString(
                              Aws::Utils::DateFormat::ISO_8601)
                      << std::endl;
        }

        std::cout << "Issuer:              " << certificate.GetIssuer() <<
                  std::endl;

        Aws::ACM::Model::KeyAlgorithm keyAlgorithm =
                certificate.GetKeyAlgorithm();
        Aws::String algorithm;

        switch (keyAlgorithm) {
            case Aws::ACM::Model::KeyAlgorithm::EC_prime256v1:
                algorithm = "P-256 (secp256r1, prime256v1)";
                break;
            case Aws::ACM::Model::KeyAlgorithm::EC_secp384r1:
                algorithm = "P-384 (secp384r1)";
                break;
            case Aws::ACM::Model::KeyAlgorithm::EC_secp521r1:
                algorithm = "P-521 (secp521r1)";
                break;
            case Aws::ACM::Model::KeyAlgorithm::NOT_SET:
                algorithm = "Not set";
                break;
            case Aws::ACM::Model::KeyAlgorithm::RSA_1024:
                algorithm = "RSA 1024";
                break;
            case Aws::ACM::Model::KeyAlgorithm::RSA_2048:
                algorithm = "RSA 2048";
                break;
            case Aws::ACM::Model::KeyAlgorithm::RSA_4096:
                algorithm = "RSA 4096";
                break;
            default:
                algorithm = "Cannot determine";
        }

        std::cout << "Key algorithm:       " << algorithm << std::endl;

        if (certificate.GetStatus() == Aws::ACM::Model::CertificateStatus::ISSUED) {
            std::cout << "Not valid after (GMT): " <<
                      certificate.GetNotAfter().ToGmtString(
                              Aws::Utils::DateFormat::ISO_8601)
                      << std::endl;
            std::cout << "Not valid before (GMT): " <<
                      certificate.GetNotBefore().ToGmtString(
                              Aws::Utils::DateFormat::ISO_8601)
                      << std::endl;
        }

        Aws::ACM::Model::CertificateTransparencyLoggingPreference loggingPreference =
                certificate.GetOptions().GetCertificateTransparencyLoggingPreference();
        Aws::String preference;

        switch (loggingPreference) {
            case Aws::ACM::Model::CertificateTransparencyLoggingPreference::DISABLED:
                preference = "Disabled";
                break;
            case Aws::ACM::Model::CertificateTransparencyLoggingPreference::ENABLED:
                preference = "Enabled";
                break;
            case Aws::ACM::Model::CertificateTransparencyLoggingPreference::NOT_SET:
                preference = "Not set";
                break;
            default:
                preference = "Cannot determine";
        }

        std::cout << "Logging preference:  " << preference << std::endl;

        std::cout << "Serial:              " << certificate.GetSerial() <<
                  std::endl;
        std::cout << "Signature algorithm: "
                  << certificate.GetSignatureAlgorithm() << std::endl;
        std::cout << "Subject:             " << certificate.GetSubject() <<
                  std::endl;

        Aws::ACM::Model::CertificateType certificateType = certificate.GetType();
        Aws::String type;

        switch (certificateType) {
            case Aws::ACM::Model::CertificateType::AMAZON_ISSUED:
                type = "Amazon issued";
                break;
            case Aws::ACM::Model::CertificateType::IMPORTED:
                type = "Imported";
                break;
            case Aws::ACM::Model::CertificateType::NOT_SET:
                type = "Not set";
                break;
            case Aws::ACM::Model::CertificateType::PRIVATE_:
                type = "Private";
                break;
            default:
                type = "Cannot determine";
        }

        std::cout << "Type:                " << type << std::endl;

        Aws::Vector<Aws::String> altNames =
                certificate.GetSubjectAlternativeNames();

        if (!altNames.empty()) {
            std::cout << std::endl << "Alternative names:" <<
                      std::endl << std::endl;

            for (auto &alt_name: altNames) {
                std::cout << "  " << alt_name << std::endl;
            }

            std::cout << std::endl;
        }
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DescribeCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/DescribeCertificate)」を参照してください。

### `ExportCertificate`
<a name="acm_ExportCertificate_cpp_1_topic"></a>

次のコード例は、`ExportCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Export an AWS Certificate Manager (ACM)  certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param passphrase: A passphrase to decrypt the exported certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::exportCertificate(const Aws::String &certificateArn,
                                    const Aws::String &passphrase,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acm_client(clientConfiguration);

    Aws::ACM::Model::ExportCertificateRequest request;
    Aws::Utils::CryptoBuffer cryptoBuffer(
            reinterpret_cast<const unsigned char *>(passphrase.c_str()),
            passphrase.length());
    request.WithCertificateArn(certificateArn).WithPassphrase(cryptoBuffer);

    Aws::ACM::Model::ExportCertificateOutcome outcome =
            acm_client.ExportCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: ExportCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Success: Information about certificate with ARN '"
                  << certificateArn << "':" << std::endl << std::endl;

        auto result = outcome.GetResult();

        std::cout << "Certificate:       " << std::endl << std::endl <<
                  result.GetCertificate() << std::endl << std::endl;
        std::cout << "Certificate chain: " << std::endl << std::endl <<
                  result.GetCertificateChain() << std::endl << std::endl;
        std::cout << "Private key:       " << std::endl << std::endl <<
                  result.GetPrivateKey() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の[ExportCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/ExportCertificate)」を参照してください。

### `GetCertificate`
<a name="acm_GetCertificate_cpp_1_topic"></a>

次のコード例は、`GetCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Get an AWS Certificate Manager (ACM) certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::getCertificate(const Aws::String &certificateArn,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::GetCertificateRequest request;
    request.WithCertificateArn(certificateArn);

    Aws::ACM::Model::GetCertificateOutcome outcome =
            acmClient.GetCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: GetCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Success: Information about certificate with ARN '"
                  << certificateArn << "':" << std::endl << std::endl;

        auto result = outcome.GetResult();

        std::cout << "Certificate: " << std::endl << std::endl <<
                  result.GetCertificate() << std::endl;
        std::cout << "Certificate chain: " << std::endl << std::endl <<
                  result.GetCertificateChain() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/GetCertificate)」を参照してください。

### `ImportCertificate`
<a name="acm_ImportCertificate_cpp_1_topic"></a>

次のコード例は、`ImportCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Import an AWS Certificate Manager (ACM) certificate.
/*!
  \param certificateFile: Path to certificate to import.
  \param privateKeyFile: Path to file containing a private key.
  \param certificateChainFile: Path to file containing a PEM encoded certificate chain.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::importCertificate(const Aws::String &certificateFile,
                                    const Aws::String &privateKeyFile,
                                    const Aws::String &certificateChainFile,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    std::ifstream certificateInStream(certificateFile.c_str());
    if (!certificateInStream) {
        std::cerr << "Error: The certificate file '" << certificateFile <<
                  "' does not exist." << std::endl;

        return false;
    }

    std::ifstream privateKeyInstream(privateKeyFile.c_str());
    if (!privateKeyInstream) {
        std::cerr << "Error: The private key file '" << privateKeyFile <<
                  "' does not exist." << std::endl;

        return false;
    }

    std::ifstream certificateChainInStream(certificateChainFile.c_str());
    if (!certificateChainInStream) {
        std::cerr << "Error: The certificate chain file '"
                  << certificateChainFile << "' does not exist." << std::endl;

        return false;
    }

    Aws::String certificate;
    certificate.assign(std::istreambuf_iterator<char>(certificateInStream),
                       std::istreambuf_iterator<char>());

    Aws::String privateKey;
    privateKey.assign(std::istreambuf_iterator<char>(privateKeyInstream),
                      std::istreambuf_iterator<char>());

    Aws::String certificateChain;
    certificateChain.assign(std::istreambuf_iterator<char>(certificateChainInStream),
                            std::istreambuf_iterator<char>());

    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::ImportCertificateRequest request;

    request.WithCertificate(Aws::Utils::ByteBuffer((unsigned char *)
                                                           certificate.c_str(),
                                                   certificate.size()))
            .WithPrivateKey(Aws::Utils::ByteBuffer((unsigned char *)
                                                           privateKey.c_str(),
                                                   privateKey.size()))
            .WithCertificateChain(Aws::Utils::ByteBuffer((unsigned char *)
                                                                 certificateChain.c_str(),
                                                         certificateChain.size()));

    Aws::ACM::Model::ImportCertificateOutcome outcome =
            acmClient.ImportCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: ImportCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;

        return false;
    }
    else {
        std::cout << "Success: Certificate associated with ARN '" <<
                  outcome.GetResult().GetCertificateArn() << "' imported."
                  << std::endl;

        return true;
    }
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[ImportCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/ImportCertificate)」を参照してください。

### `ListCertificates`
<a name="acm_ListCertificates_cpp_1_topic"></a>

次のコード例は、`ListCertificates` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! List the AWS Certificate Manager (ACM) certificates in an account.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::listCertificates(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::ListCertificatesRequest request;
    Aws::Vector<Aws::ACM::Model::CertificateSummary> allCertificates;
    Aws::String nextToken;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::ACM::Model::ListCertificatesOutcome outcome =
                acmClient.ListCertificates(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error: ListCertificates: " <<
                      outcome.GetError().GetMessage() << std::endl;

            return false;
        }
        else {
            const Aws::ACM::Model::ListCertificatesResult &result = outcome.GetResult();

            const Aws::Vector<Aws::ACM::Model::CertificateSummary> &certificates =
                    result.GetCertificateSummaryList();
            allCertificates.insert(allCertificates.end(), certificates.begin(),
                                   certificates.end());

            nextToken = result.GetNextToken();
        }
    } while (!nextToken.empty());

    if (!allCertificates.empty()) {
        for (const Aws::ACM::Model::CertificateSummary &certificate: allCertificates) {
            std::cout << "Certificate ARN: " <<
                      certificate.GetCertificateArn() << std::endl;
            std::cout << "Domain name:     " <<
                      certificate.GetDomainName() << std::endl << std::endl;
        }
    }
    else {
        std::cout << "No available certificates found in account."
                  << std::endl;
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンスの*「[ListCertificates](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/ListCertificates)」を参照してください。

### `ListTagsForCertificate`
<a name="acm_ListTagsForCertificate_cpp_1_topic"></a>

次のコード例は、`ListTagsForCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! List the tags for an AWS Certificate Manager (ACM) certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::listTagsForCertificate(const Aws::String &certificateArn,
                                         const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acm_client(clientConfiguration);

    Aws::ACM::Model::ListTagsForCertificateRequest request;
    request.WithCertificateArn(certificateArn);

    Aws::ACM::Model::ListTagsForCertificateOutcome outcome =
            acm_client.ListTagsForCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cout << "Error: ListTagsForCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;

        return false;
    }
    else {
        std::cout << "Success: Information about tags for "
                     "certificate with ARN '"
                  << certificateArn << "':" << std::endl << std::endl;

        auto result = outcome.GetResult();

        Aws::Vector<Aws::ACM::Model::Tag> tags =
                result.GetTags();

        if (tags.size() > 0) {
            for (const Aws::ACM::Model::Tag &tag: tags) {
                std::cout << "Key:   " << tag.GetKey() << std::endl;
                std::cout << "Value: " << tag.GetValue()
                          << std::endl << std::endl;
            }
        }
        else {
            std::cout << "No tags found." << std::endl;
        }

        return true;
    }
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListTagsForCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/ListTagsForCertificate)」を参照してください。

### `RemoveTagsFromCertificate`
<a name="acm_RemoveTagsFromCertificate_cpp_1_topic"></a>

次のコード例は、`RemoveTagsFromCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Remove a tag from an ACM certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param tagKey: The key for the tag.
  \param tagValue: The value for the tag.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::removeTagsFromCertificate(const Aws::String &certificateArn,
                                            const Aws::String &tagKey,
                                            const Aws::String &tagValue,
                                            const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::Vector<Aws::ACM::Model::Tag> tags;

    Aws::ACM::Model::Tag tag;
    tag.SetKey(tagKey);

    tags.push_back(tag);

    Aws::ACM::Model::RemoveTagsFromCertificateRequest request;
    request.WithCertificateArn(certificateArn)
            .WithTags(tags);

    Aws::ACM::Model::RemoveTagsFromCertificateOutcome outcome =
            acmClient.RemoveTagsFromCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: RemoveTagFromCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;

        return false;
    }
    else {
        std::cout << "Success: Tag with key '" << tagKey << "' removed from "
                  << "certificate with ARN '" << certificateArn << "'." << std::endl;

        return true;
    }
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[RemoveTagsFromCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/RemoveTagsFromCertificate)」を参照してください。

### `RenewCertificate`
<a name="acm_RenewCertificate_cpp_1_topic"></a>

次のコード例は、`RenewCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Renew an AWS Certificate Manager (ACM) certificate.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::renewCertificate(const Aws::String &certificateArn,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::RenewCertificateRequest request;
    request.SetCertificateArn(certificateArn);

    Aws::ACM::Model::RenewCertificateOutcome outcome =
            acmClient.RenewCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: RenewCertificate: " <<
                  outcome.GetError().GetMessage() << std::endl;

        return false;
    }
    else {
        std::cout << "Success: Renewed certificate with ARN '"
                  << certificateArn << "'." << std::endl;

        return true;
    }
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[RenewCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/RenewCertificate)」を参照してください。

### `RequestCertificate`
<a name="acm_RequestCertificate_cpp_1_topic"></a>

次のコード例は、`RequestCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Request an AWS Certificate Manager (ACM) certificate.
/*!
  \param domainName: A fully qualified domain name.
  \param idempotencyToken: Customer chosen string for idempotency.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::requestCertificate(const Aws::String &domainName,
                                     const Aws::String &idempotencyToken,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::RequestCertificateRequest request;
    request.WithDomainName(domainName)
            .WithIdempotencyToken(idempotencyToken);

    Aws::ACM::Model::RequestCertificateOutcome outcome =
            acmClient.RequestCertificate(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "RequestCertificate error: " <<
                  outcome.GetError().GetMessage() << std::endl;

        return false;
    }
    else {
        std::cout << "Success: The newly requested certificate's "
                     "ARN is '" <<
                  outcome.GetResult().GetCertificateArn() <<
                  "'." << std::endl;

        return true;
    }
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[RequestCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/RequestCertificate)」を参照してください。

### `ResendValidationEmail`
<a name="acm_ResendValidationEmail_cpp_1_topic"></a>

次のコード例は、`ResendValidationEmail` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Resend the email that requests domain ownership validation.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param domainName: A fully qualified domain name.
  \param validationDomain: The base validation domain that will act as the suffix
                            of the email addresses.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::resendValidationEmail(const Aws::String &certificateArn,
                                        const Aws::String &domainName,
                                        const Aws::String &validationDomain,
                                        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::ResendValidationEmailRequest request;
    request.WithCertificateArn(certificateArn)
            .WithDomain(domainName)
            .WithValidationDomain(validationDomain);

    Aws::ACM::Model::ResendValidationEmailOutcome outcome =
            acmClient.ResendValidationEmail(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "ResendValidationEmail error: " <<
                  outcome.GetError().GetMessage() << std::endl;

        return false;
    }
    else {
        std::cout << "Success: The validation email has been resent."
                  << std::endl;

        return true;
    }
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ResendValidationEmail](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/ResendValidationEmail)」を参照してください。

### `UpdateCertificateOptions`
<a name="acm_UpdateCertificateOptions_cpp_1_topic"></a>

次のコード例は、`UpdateCertificateOptions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
//! Update an AWS Certificate Manager (ACM) certificate option.
/*!
  \param certificateArn: The Amazon Resource Name (ARN) of a certificate.
  \param loggingEnabled: Boolean specifying logging enabled.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::ACM::updateCertificateOption(const Aws::String &certificateArn,
                                          bool loggingEnabled,
                                          const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::ACM::ACMClient acmClient(clientConfiguration);

    Aws::ACM::Model::UpdateCertificateOptionsRequest request;
    request.SetCertificateArn(certificateArn);

    Aws::ACM::Model::CertificateOptions options;

    if (loggingEnabled) {
        options.SetCertificateTransparencyLoggingPreference(
                Aws::ACM::Model::CertificateTransparencyLoggingPreference::ENABLED);
    }
    else {
        options.SetCertificateTransparencyLoggingPreference(
                Aws::ACM::Model::CertificateTransparencyLoggingPreference::DISABLED);
    }

    request.SetOptions(options);

    Aws::ACM::Model::UpdateCertificateOptionsOutcome outcome =
            acmClient.UpdateCertificateOptions(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "UpdateCertificateOption error: " <<
                  outcome.GetError().GetMessage() << std::endl;

        return false;
    }
    else {
        std::cout << "Success: The option '"
                  << (loggingEnabled ? "enabled" : "disabled") << "' has been set for "
                                                                  "the certificate with the ARN '"
                  << certificateArn << "'."
                  << std::endl;

        return true;
    }
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[UpdateCertificateOptions](https://docs.aws.amazon.com/goto/SdkForCpp/acm-2015-12-08/UpdateCertificateOptions)」を参照してください。

# SDK for C\$1\$1 を使用した API Gateway の例
<a name="cpp_1_api-gateway_code_examples"></a>

次のコード例は、API Gateway AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_cpp_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for C\$1\$1**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

# SDK for C\$1\$1 を使用した Aurora の例
<a name="cpp_1_aurora_code_examples"></a>

次のコード例は、Aurora AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Aurora
<a name="aurora_Hello_cpp_1_topic"></a>

次のコード例は、Aurora の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora/hello_aurora#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS rds)

# Set this project's name.
project("hello_aurora")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_aurora.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1aurora.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/rds/RDSClient.h>
#include <aws/rds/model/DescribeDBClustersRequest.h>
#include <iostream>

/*
 *  A "Hello Aurora" starter application which initializes an Amazon Relational Database Service (Amazon RDS) client
 *  and describes the Amazon Aurora (Aurora) clusters.
 *
 *  main function
 *
 *  Usage: 'hello_aurora'
 *
 */
int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::RDS::RDSClient rdsClient(clientConfig);

        Aws::String marker; // Used for pagination.
        std::vector<Aws::String> clusterIds;
        do {
            Aws::RDS::Model::DescribeDBClustersRequest request;

            Aws::RDS::Model::DescribeDBClustersOutcome outcome =
                    rdsClient.DescribeDBClusters(request);

            if (outcome.IsSuccess()) {
                for (auto &cluster: outcome.GetResult().GetDBClusters()) {
                    clusterIds.push_back(cluster.GetDBClusterIdentifier());
                }
                marker = outcome.GetResult().GetMarker();
            } else {
                result = 1;
                std::cerr << "Error with Aurora::GDescribeDBClusters. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                break;
            }
        } while (!marker.empty());

        std::cout << clusterIds.size() << " Aurora clusters found." << std::endl;
        for (auto &clusterId: clusterIds) {
            std::cout << "  clusterId " << clusterId << std::endl;
        }
    }

    Aws::ShutdownAPI(options); // Should only be called once.
    return 0;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="aurora_Scenario_GetStartedClusters_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム Aurora DB クラスターパラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用する DB クラスターを作成する
+ データベースを含む DB インスタンスを作成します。
+ DB クラスターのスナップショットを作成して、リソースをクリーンアップします。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Routine which creates an Amazon Aurora DB cluster and demonstrates several operations
//! on that cluster.
/*!
 \sa gettingStartedWithDBClusters()
 \param clientConfiguration: AWS client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::gettingStartedWithDBClusters(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::RDS::RDSClient client(clientConfig);

    printAsterisksLine();
    std::cout << "Welcome to the Amazon Relational Database Service (Amazon Aurora)"
              << std::endl;
    std::cout << "get started with DB clusters demo." << std::endl;
    printAsterisksLine();

    std::cout << "Checking for an existing DB cluster parameter group named '" <<
              CLUSTER_PARAMETER_GROUP_NAME << "'." << std::endl;
    Aws::String dbParameterGroupFamily("Undefined");
    bool parameterGroupFound = true;
    {
        // 1. Check if the DB cluster parameter group already exists.
        Aws::RDS::Model::DescribeDBClusterParameterGroupsRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);

        Aws::RDS::Model::DescribeDBClusterParameterGroupsOutcome outcome =
                client.DescribeDBClusterParameterGroups(request);

        if (outcome.IsSuccess()) {
            std::cout << "DB cluster parameter group named '" <<
                      CLUSTER_PARAMETER_GROUP_NAME << "' already exists." << std::endl;
            dbParameterGroupFamily = outcome.GetResult().GetDBClusterParameterGroups()[0].GetDBParameterGroupFamily();
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::RDS::RDSErrors::D_B_PARAMETER_GROUP_NOT_FOUND_FAULT) {
            std::cout << "DB cluster parameter group named '" <<
                      CLUSTER_PARAMETER_GROUP_NAME << "' does not exist." << std::endl;
            parameterGroupFound = false;
        }
        else {
            std::cerr << "Error with Aurora::DescribeDBClusterParameterGroups. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    if (!parameterGroupFound) {
        Aws::Vector<Aws::RDS::Model::DBEngineVersion> engineVersions;

        // 2. Get available parameter group families for the specified engine.
        if (!getDBEngineVersions(DB_ENGINE, NO_PARAMETER_GROUP_FAMILY,
                                 engineVersions, client)) {
            return false;
        }

        std::cout << "Getting available parameter group families for " << DB_ENGINE
                  << "."
                  << std::endl;
        std::vector<Aws::String> families;
        for (const Aws::RDS::Model::DBEngineVersion &version: engineVersions) {
            Aws::String family = version.GetDBParameterGroupFamily();
            if (std::find(families.begin(), families.end(), family) ==
                families.end()) {
                families.push_back(family);
                std::cout << "  " << families.size() << ": " << family << std::endl;
            }
        }

        int choice = askQuestionForIntRange("Which family do you want to use? ", 1,
                                            static_cast<int>(families.size()));
        dbParameterGroupFamily = families[choice - 1];
    }
    if (!parameterGroupFound) {
        // 3.  Create a DB cluster parameter group.
        Aws::RDS::Model::CreateDBClusterParameterGroupRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        request.SetDBParameterGroupFamily(dbParameterGroupFamily);
        request.SetDescription("Example cluster parameter group.");

        Aws::RDS::Model::CreateDBClusterParameterGroupOutcome outcome =
                client.CreateDBClusterParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB cluster parameter group was successfully created."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::CreateDBClusterParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    printAsterisksLine();
    std::cout << "Let's set some parameter values in your cluster parameter group."
              << std::endl;

    Aws::Vector<Aws::RDS::Model::Parameter> autoIncrementParameters;
    // 4.  Get the parameters in the DB cluster parameter group.
    if (!getDBCLusterParameters(CLUSTER_PARAMETER_GROUP_NAME, AUTO_INCREMENT_PREFIX,
                                NO_SOURCE,
                                autoIncrementParameters,
                                client)) {
        cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, "", "", client);
        return false;
    }

    Aws::Vector<Aws::RDS::Model::Parameter> updateParameters;

    for (Aws::RDS::Model::Parameter &autoIncParameter: autoIncrementParameters) {
        if (autoIncParameter.GetIsModifiable() &&
            (autoIncParameter.GetDataType() == "integer")) {
            std::cout << "The " << autoIncParameter.GetParameterName()
                      << " is described as: " <<
                      autoIncParameter.GetDescription() << "." << std::endl;
            if (autoIncParameter.ParameterValueHasBeenSet()) {
                std::cout << "The current value is "
                          << autoIncParameter.GetParameterValue()
                          << "." << std::endl;
            }
            std::vector<int> splitValues = splitToInts(
                    autoIncParameter.GetAllowedValues(), '-');
            if (splitValues.size() == 2) {
                int newValue = askQuestionForIntRange(
                        Aws::String("Enter a new value between ") +
                        autoIncParameter.GetAllowedValues() + ": ",
                        splitValues[0], splitValues[1]);
                autoIncParameter.SetParameterValue(std::to_string(newValue));
                updateParameters.push_back(autoIncParameter);

            }
            else {
                std::cerr << "Error parsing " << autoIncParameter.GetAllowedValues()
                          << std::endl;
            }
        }
    }

    {
        // 5.  Modify the auto increment parameters in the DB cluster parameter group.
        Aws::RDS::Model::ModifyDBClusterParameterGroupRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        request.SetParameters(updateParameters);

        Aws::RDS::Model::ModifyDBClusterParameterGroupOutcome outcome =
                client.ModifyDBClusterParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB cluster parameter group was successfully modified."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::ModifyDBClusterParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    }

    std::cout
            << "You can get a list of parameters you've set by specifying a source of 'user'."
            << std::endl;

    Aws::Vector<Aws::RDS::Model::Parameter> userParameters;
    // 6.  Display the modified parameters in the DB cluster parameter group.
    if (!getDBCLusterParameters(CLUSTER_PARAMETER_GROUP_NAME, NO_NAME_PREFIX, "user",
                                userParameters,
                                client)) {
        cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, "", "", client);
        return false;
    }

    for (const auto &userParameter: userParameters) {
        std::cout << "  " << userParameter.GetParameterName() << ", " <<
                  userParameter.GetDescription() << ", parameter value - "
                  << userParameter.GetParameterValue() << std::endl;
    }

    printAsterisksLine();
    std::cout << "Checking for an existing DB Cluster." << std::endl;

    Aws::RDS::Model::DBCluster dbCluster;
    // 7.  Check if the DB cluster already exists.
    if (!describeDBCluster(DB_CLUSTER_IDENTIFIER, dbCluster, client)) {
        cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, "", "", client);
        return false;
    }

    Aws::String engineVersionName;
    Aws::String engineName;
    if (dbCluster.DBClusterIdentifierHasBeenSet()) {
        std::cout << "The DB cluster already exists." << std::endl;
        engineVersionName = dbCluster.GetEngineVersion();
        engineName = dbCluster.GetEngine();

    }
    else {
        std::cout << "Let's create a DB cluster." << std::endl;
        const Aws::String administratorName = askQuestion(
                "Enter an administrator username for the database: ");
        const Aws::String administratorPassword = askQuestion(
                "Enter a password for the administrator (at least 8 characters): ");
        Aws::Vector<Aws::RDS::Model::DBEngineVersion> engineVersions;

        // 8.  Get a list of engine versions for the parameter group family.
        if (!getDBEngineVersions(DB_ENGINE, dbParameterGroupFamily, engineVersions,
                                 client)) {
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, "", "", client);
            return false;
        }

        std::cout << "The available engines for your parameter group family are:"
                  << std::endl;

        int index = 1;
        for (const Aws::RDS::Model::DBEngineVersion &engineVersion: engineVersions) {
            std::cout << "  " << index << ": " << engineVersion.GetEngineVersion()
                      << std::endl;
            ++index;
        }
        int choice = askQuestionForIntRange("Which engine do you want to use? ", 1,
                                            static_cast<int>(engineVersions.size()));
        const Aws::RDS::Model::DBEngineVersion engineVersion = engineVersions[choice -
                                                                              1];

        engineName = engineVersion.GetEngine();
        engineVersionName = engineVersion.GetEngineVersion();
        std::cout << "Creating a DB cluster named '" << DB_CLUSTER_IDENTIFIER
                  << "' and database '" << DB_NAME << "'.\n"
                  << "The DB cluster is configured to use your custom cluster parameter group '"
                  << CLUSTER_PARAMETER_GROUP_NAME << "', and \n"
                  << "selected engine version " << engineVersion.GetEngineVersion()
                  << ".\nThis typically takes several minutes." << std::endl;

        Aws::RDS::Model::CreateDBClusterRequest request;
        request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER);
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        request.SetEngine(engineName);
        request.SetEngineVersion(engineVersionName);
        request.SetMasterUsername(administratorName);
        request.SetMasterUserPassword(administratorPassword);

        Aws::RDS::Model::CreateDBClusterOutcome outcome =
                client.CreateDBCluster(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB cluster creation has started."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::CreateDBCluster. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, "", "", client);
            return false;
        }
    }

    std::cout << "Waiting for the DB cluster to become available." << std::endl;

    int counter = 0;
    // 11. Wait for the DB cluster to become available.
    do {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        ++counter;
        if (counter > 900) {
            std::cerr << "Wait for cluster to become available timed out ofter "
                      << counter
                      << " seconds." << std::endl;
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                             DB_CLUSTER_IDENTIFIER, "", client);
            return false;
        }

        dbCluster = Aws::RDS::Model::DBCluster();
        if (!describeDBCluster(DB_CLUSTER_IDENTIFIER, dbCluster, client)) {
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                             DB_CLUSTER_IDENTIFIER, "", client);
            return false;
        }

        if ((counter % 20) == 0) {
            std::cout << "Current DB cluster status is '"
                      << dbCluster.GetStatus()
                      << "' after " << counter << " seconds." << std::endl;
        }
    } while (dbCluster.GetStatus() != "available");

    if (dbCluster.GetStatus() == "available") {
        std::cout << "The DB cluster has been created." << std::endl;
    }

    printAsterisksLine();
    Aws::RDS::Model::DBInstance dbInstance;
    // 11.  Check if the DB instance already exists.
    if (!describeDBInstance(DB_INSTANCE_IDENTIFIER, dbInstance, client)) {
        cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, DB_CLUSTER_IDENTIFIER, "",
                         client);
        return false;
    }

    if (dbInstance.DbInstancePortHasBeenSet()) {
        std::cout << "The DB instance already exists." << std::endl;
    }
    else {
        std::cout << "Let's create a DB instance." << std::endl;

        Aws::String dbInstanceClass;
        // 12.  Get a list of instance classes.
        if (!chooseDBInstanceClass(engineName,
                                   engineVersionName,
                                   dbInstanceClass,
                                   client)) {
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, DB_CLUSTER_IDENTIFIER, "",
                             client);
            return false;
        }

        std::cout << "Creating a DB instance named '" << DB_INSTANCE_IDENTIFIER
                  << "' with selected DB instance class '" << dbInstanceClass
                  << "'.\nThis typically takes several minutes." << std::endl;

        // 13. Create a DB instance.
        Aws::RDS::Model::CreateDBInstanceRequest request;
        request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER);
        request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER);
        request.SetEngine(engineName);
        request.SetDBInstanceClass(dbInstanceClass);

        Aws::RDS::Model::CreateDBInstanceOutcome outcome =
                client.CreateDBInstance(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB instance creation has started."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::CreateDBInstance. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, DB_CLUSTER_IDENTIFIER, "",
                             client);
            return false;
        }
    }

    std::cout << "Waiting for the DB instance to become available." << std::endl;

    counter = 0;
    // 14. Wait for the DB instance to become available.
    do {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        ++counter;
        if (counter > 900) {
            std::cerr << "Wait for instance to become available timed out ofter "
                      << counter
                      << " seconds." << std::endl;
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                             DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client);
            return false;
        }

        dbInstance = Aws::RDS::Model::DBInstance();
        if (!describeDBInstance(DB_INSTANCE_IDENTIFIER, dbInstance, client)) {
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                             DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client);
            return false;
        }

        if ((counter % 20) == 0) {
            std::cout << "Current DB instance status is '"
                      << dbInstance.GetDBInstanceStatus()
                      << "' after " << counter << " seconds." << std::endl;
        }
    } while (dbInstance.GetDBInstanceStatus() != "available");

    if (dbInstance.GetDBInstanceStatus() == "available") {
        std::cout << "The DB instance has been created." << std::endl;
    }

    // 15. Display the connection string that can be used to connect a 'mysql' shell to the database.
    displayConnection(dbCluster);

    printAsterisksLine();

    if (askYesNoQuestion(
            "Do you want to create a snapshot of your DB cluster (y/n)? ")) {
        Aws::String snapshotID(DB_CLUSTER_IDENTIFIER + "-" +
                               Aws::String(Aws::Utils::UUID::RandomUUID()));
        {
            std::cout << "Creating a snapshot named " << snapshotID << "." << std::endl;
            std::cout << "This typically takes a few minutes." << std::endl;

            // 16. Create a snapshot of the DB cluster. (CreateDBClusterSnapshot)
            Aws::RDS::Model::CreateDBClusterSnapshotRequest request;
            request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER);
            request.SetDBClusterSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::CreateDBClusterSnapshotOutcome outcome =
                    client.CreateDBClusterSnapshot(request);

            if (outcome.IsSuccess()) {
                std::cout << "Snapshot creation has started."
                          << std::endl;
            }
            else {
                std::cerr << "Error with Aurora::CreateDBClusterSnapshot. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                                 DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }
        }

        std::cout << "Waiting for the snapshot to become available." << std::endl;

        Aws::RDS::Model::DBClusterSnapshot snapshot;
        counter = 0;
        do {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            ++counter;
            if (counter > 600) {
                std::cerr << "Wait for snapshot to be available timed out ofter "
                          << counter
                          << " seconds." << std::endl;
                cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                                 DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }

            // 17. Wait for the snapshot to become available.
            Aws::RDS::Model::DescribeDBClusterSnapshotsRequest request;
            request.SetDBClusterSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::DescribeDBClusterSnapshotsOutcome outcome =
                    client.DescribeDBClusterSnapshots(request);

            if (outcome.IsSuccess()) {
                snapshot = outcome.GetResult().GetDBClusterSnapshots()[0];
            }
            else {
                std::cerr << "Error with Aurora::DescribeDBClusterSnapshots. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                                 DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }

            if ((counter % 20) == 0) {
                std::cout << "Current snapshot status is '"
                          << snapshot.GetStatus()
                          << "' after " << counter << " seconds." << std::endl;
            }
        } while (snapshot.GetStatus() != "available");

        if (snapshot.GetStatus() != "available") {
            std::cout << "A snapshot has been created." << std::endl;
        }
    }

    printAsterisksLine();

    bool result = true;
    if (askYesNoQuestion(
            "Do you want to delete the DB cluster, DB instance, and parameter group (y/n)? ")) {
        result = cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                                  DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER,
                                  client);
    }

    return result;
}

//! Routine which gets a DB cluster description.
/*!
 \sa describeDBCluster()
 \param dbClusterIdentifier: A DB cluster identifier.
 \param clusterResult: The 'DBCluster' object containing the description.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::describeDBCluster(const Aws::String &dbClusterIdentifier,
                                       Aws::RDS::Model::DBCluster &clusterResult,
                                       const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBClustersRequest request;
    request.SetDBClusterIdentifier(dbClusterIdentifier);

    Aws::RDS::Model::DescribeDBClustersOutcome outcome =
            client.DescribeDBClusters(request);

    bool result = true;
    if (outcome.IsSuccess()) {
        clusterResult = outcome.GetResult().GetDBClusters()[0];
    }
    else if (outcome.GetError().GetErrorType() !=
             Aws::RDS::RDSErrors::D_B_CLUSTER_NOT_FOUND_FAULT) {
        result = false;
        std::cerr << "Error with Aurora::GDescribeDBClusters. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
        // This example does not log an error if the DB cluster does not exist.
        // Instead, clusterResult is set to empty.
    else {
        clusterResult = Aws::RDS::Model::DBCluster();
    }

    return result;

}


//! Routine which gets DB parameters using the 'DescribeDBClusterParameters' api.
/*!
 \sa getDBCLusterParameters()
 \param parameterGroupName: The name of the cluster parameter group.
 \param namePrefix: Prefix string to filter results by parameter name.
 \param source: A source such as 'user', ignored if empty.
 \param parametersResult: Vector of 'Parameter' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::getDBCLusterParameters(const Aws::String &parameterGroupName,
                                            const Aws::String &namePrefix,
                                            const Aws::String &source,
                                            Aws::Vector<Aws::RDS::Model::Parameter> &parametersResult,
                                            const Aws::RDS::RDSClient &client) {
    Aws::String marker; // The marker is used for pagination.
    do {
        Aws::RDS::Model::DescribeDBClusterParametersRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }
        if (!source.empty()) {
            request.SetSource(source);
        }

        Aws::RDS::Model::DescribeDBClusterParametersOutcome outcome =
                client.DescribeDBClusterParameters(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::Parameter> &parameters =
                    outcome.GetResult().GetParameters();
            for (const Aws::RDS::Model::Parameter &parameter: parameters) {
                if (!namePrefix.empty()) {
                    if (parameter.GetParameterName().find(namePrefix) == 0) {
                        parametersResult.push_back(parameter);
                    }
                }
                else {
                    parametersResult.push_back(parameter);
                }
            }

            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with Aurora::DescribeDBClusterParameters. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    return true;
}


//! Routine which gets available DB engine versions for an engine name and
//! an optional parameter group family.
/*!
 \sa getDBEngineVersions()
 \param engineName: A DB engine name.
 \param parameterGroupFamily: A parameter group family name, ignored if empty.
 \param engineVersionsResult: Vector of 'DBEngineVersion' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::getDBEngineVersions(const Aws::String &engineName,
                                         const Aws::String &parameterGroupFamily,
                                         Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersionsResult,
                                         const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBEngineVersionsRequest request;
    request.SetEngine(engineName);
    if (!parameterGroupFamily.empty()) {
        request.SetDBParameterGroupFamily(parameterGroupFamily);
    }

    engineVersionsResult.clear();
    Aws::String marker; // The marker is used for pagination.
    do {
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::RDS::Model::DescribeDBEngineVersionsOutcome outcome =
                client.DescribeDBEngineVersions(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersions =
                    outcome.GetResult().GetDBEngineVersions();

            engineVersionsResult.insert(engineVersionsResult.end(),
                                        engineVersions.begin(), engineVersions.end());
            marker  = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with Aurora::DescribeDBEngineVersionsRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    } while (!marker.empty());

    return true;
}


//! Routine which gets a DB instance description.
/*!
 \sa describeDBCluster()
 \param dbInstanceIdentifier: A DB instance identifier.
 \param instanceResult: The 'DBInstance' object containing the description.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::describeDBInstance(const Aws::String &dbInstanceIdentifier,
                                        Aws::RDS::Model::DBInstance &instanceResult,
                                        const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBInstancesRequest request;
    request.SetDBInstanceIdentifier(dbInstanceIdentifier);

    Aws::RDS::Model::DescribeDBInstancesOutcome outcome =
            client.DescribeDBInstances(request);

    bool result = true;
    if (outcome.IsSuccess()) {
        instanceResult = outcome.GetResult().GetDBInstances()[0];
    }
    else if (outcome.GetError().GetErrorType() !=
             Aws::RDS::RDSErrors::D_B_INSTANCE_NOT_FOUND_FAULT) {
        result = false;
        std::cerr << "Error with Aurora::DescribeDBInstances. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
        // This example does not log an error if the DB instance does not exist.
        // Instead, instanceResult is set to empty.
    else {
        instanceResult = Aws::RDS::Model::DBInstance();
    }

    return result;
}


//! Routine which gets available DB instance classes, displays the list
//! to the user, and returns the user selection.
/*!
 \sa chooseDBInstanceClass()
 \param engineName: The DB engine name.
 \param engineVersion: The DB engine version.
 \param dbInstanceClass: String for DB instance class chosen by the user.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::chooseDBInstanceClass(const Aws::String &engine,
                                           const Aws::String &engineVersion,
                                           Aws::String &dbInstanceClass,
                                           const Aws::RDS::RDSClient &client) {
    std::vector<Aws::String> instanceClasses;
    Aws::String marker; // The marker is used for pagination.
    do {
        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsRequest request;
        request.SetEngine(engine);
        request.SetEngineVersion(engineVersion);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsOutcome outcome =
                client.DescribeOrderableDBInstanceOptions(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::OrderableDBInstanceOption> &options =
                    outcome.GetResult().GetOrderableDBInstanceOptions();
            for (const Aws::RDS::Model::OrderableDBInstanceOption &option: options) {
                const Aws::String &instanceClass = option.GetDBInstanceClass();
                if (std::find(instanceClasses.begin(), instanceClasses.end(),
                              instanceClass) == instanceClasses.end()) {
                    instanceClasses.push_back(instanceClass);
                }
            }
            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with Aurora::DescribeOrderableDBInstanceOptions. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    std::cout << "The available DB instance classes for your database engine are:"
              << std::endl;
    for (int i = 0; i < instanceClasses.size(); ++i) {
        std::cout << "   " << i + 1 << ": " << instanceClasses[i] << std::endl;
    }

    int choice = askQuestionForIntRange(
            "Which DB instance class do you want to use? ",
            1, static_cast<int>(instanceClasses.size()));
    dbInstanceClass = instanceClasses[choice - 1];
    return true;
}

//! Routine which deletes resources created by the scenario.
/*!
\sa cleanUpResources()
\param parameterGroupName: A parameter group name, this may be empty.
\param dbInstanceIdentifier: A DB instance identifier, this may be empty.
\param client: 'RDSClient' instance.
\return bool: Successful completion.
*/
bool AwsDoc::Aurora::cleanUpResources(const Aws::String &parameterGroupName,
                                      const Aws::String &dbClusterIdentifier,
                                      const Aws::String &dbInstanceIdentifier,
                                      const Aws::RDS::RDSClient &client) {
    bool result = true;
    bool instanceDeleting = false;
    bool clusterDeleting = false;
    if (!dbInstanceIdentifier.empty()) {
        {
            // 18. Delete the DB instance.
            Aws::RDS::Model::DeleteDBInstanceRequest request;
            request.SetDBInstanceIdentifier(dbInstanceIdentifier);
            request.SetSkipFinalSnapshot(true);
            request.SetDeleteAutomatedBackups(true);

            Aws::RDS::Model::DeleteDBInstanceOutcome outcome =
                    client.DeleteDBInstance(request);

            if (outcome.IsSuccess()) {
                std::cout << "DB instance deletion has started."
                          << std::endl;
                instanceDeleting = true;
                std::cout
                        << "Waiting for DB instance to delete before deleting the parameter group."
                        << std::endl;
            }
            else {
                std::cerr << "Error with Aurora::DeleteDBInstance. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }
    }

    if (!dbClusterIdentifier.empty()) {
        {
            // 19. Delete the DB cluster.
            Aws::RDS::Model::DeleteDBClusterRequest request;
            request.SetDBClusterIdentifier(dbClusterIdentifier);
            request.SetSkipFinalSnapshot(true);

            Aws::RDS::Model::DeleteDBClusterOutcome outcome =
                    client.DeleteDBCluster(request);

            if (outcome.IsSuccess()) {
                std::cout << "DB cluster deletion has started."
                          << std::endl;
                clusterDeleting = true;
                std::cout
                        << "Waiting for DB cluster to delete before deleting the parameter group."
                        << std::endl;
                std::cout << "This may take a while." << std::endl;
            }
            else {
                std::cerr << "Error with Aurora::DeleteDBCluster. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }
    }
    int counter = 0;

    while (clusterDeleting || instanceDeleting) {
        // 20. Wait for the DB cluster and instance to be deleted.
        std::this_thread::sleep_for(std::chrono::seconds(1));
        ++counter;
        if (counter > 800) {
            std::cerr << "Wait for instance to delete timed out ofter " << counter
                      << " seconds." << std::endl;
            return false;
        }

        Aws::RDS::Model::DBInstance dbInstance = Aws::RDS::Model::DBInstance();
        if (instanceDeleting) {
            if (!describeDBInstance(dbInstanceIdentifier, dbInstance, client)) {
                return false;
            }
            instanceDeleting = dbInstance.DBInstanceIdentifierHasBeenSet();
        }

        Aws::RDS::Model::DBCluster dbCluster = Aws::RDS::Model::DBCluster();
        if (clusterDeleting) {
            if (!describeDBCluster(dbClusterIdentifier, dbCluster, client)) {
                return false;
            }

            clusterDeleting = dbCluster.DBClusterIdentifierHasBeenSet();
        }

        if ((counter % 20) == 0) {
            if (instanceDeleting) {
                std::cout << "Current DB instance status is '"
                          << dbInstance.GetDBInstanceStatus() << "." << std::endl;
            }

            if (clusterDeleting) {
                std::cout << "Current DB cluster status is '"
                          << dbCluster.GetStatus() << "." << std::endl;
            }
        }
    }

    if (!parameterGroupName.empty()) {
        // 21. Delete the DB cluster parameter group.
        Aws::RDS::Model::DeleteDBClusterParameterGroupRequest request;
        request.SetDBClusterParameterGroupName(parameterGroupName);

        Aws::RDS::Model::DeleteDBClusterParameterGroupOutcome outcome =
                client.DeleteDBClusterParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully deleted."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::DeleteDBClusterParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
    }

    return result;
}
```
+ API の詳細については、「AWS SDK for C\$1\$1 API リファレンス**」の以下のトピックを参照してください。
  + [CreateDBCluster](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBCluster)
  + [CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBClusterParameterGroup)
  + [CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBClusterSnapshot)
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBInstance)
  + [DeleteDBCluster](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBCluster)
  + [DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBClusterParameterGroup)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBInstance)
  + [DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusterParameterGroups)
  + [DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusterParameters)
  + [DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusterSnapshots)
  + [DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusters)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBInstances)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/ModifyDBClusterParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="aurora_CreateDBCluster_cpp_1_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::CreateDBClusterRequest request;
        request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER);
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        request.SetEngine(engineName);
        request.SetEngineVersion(engineVersionName);
        request.SetMasterUsername(administratorName);
        request.SetMasterUserPassword(administratorPassword);

        Aws::RDS::Model::CreateDBClusterOutcome outcome =
                client.CreateDBCluster(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB cluster creation has started."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::CreateDBCluster. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, "", "", client);
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateDBCluster](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBCluster)」を参照してください。

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_cpp_1_topic"></a>

次のコード例は、`CreateDBClusterParameterGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::CreateDBClusterParameterGroupRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        request.SetDBParameterGroupFamily(dbParameterGroupFamily);
        request.SetDescription("Example cluster parameter group.");

        Aws::RDS::Model::CreateDBClusterParameterGroupOutcome outcome =
                client.CreateDBClusterParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB cluster parameter group was successfully created."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::CreateDBClusterParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBClusterParameterGroup)」を参照してください。

### `CreateDBClusterSnapshot`
<a name="aurora_CreateDBClusterSnapshot_cpp_1_topic"></a>

次のコード例は、`CreateDBClusterSnapshot` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

            Aws::RDS::Model::CreateDBClusterSnapshotRequest request;
            request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER);
            request.SetDBClusterSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::CreateDBClusterSnapshotOutcome outcome =
                    client.CreateDBClusterSnapshot(request);

            if (outcome.IsSuccess()) {
                std::cout << "Snapshot creation has started."
                          << std::endl;
            }
            else {
                std::cerr << "Error with Aurora::CreateDBClusterSnapshot. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                                 DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBClusterSnapshot)」を参照してください。

### `CreateDBInstance`
<a name="aurora_CreateDBInstance_cpp_1_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::CreateDBInstanceRequest request;
        request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER);
        request.SetDBClusterIdentifier(DB_CLUSTER_IDENTIFIER);
        request.SetEngine(engineName);
        request.SetDBInstanceClass(dbInstanceClass);

        Aws::RDS::Model::CreateDBInstanceOutcome outcome =
                client.CreateDBInstance(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB instance creation has started."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::CreateDBInstance. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME, DB_CLUSTER_IDENTIFIER, "",
                             client);
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `DeleteDBCluster`
<a name="aurora_DeleteDBCluster_cpp_1_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

            Aws::RDS::Model::DeleteDBClusterRequest request;
            request.SetDBClusterIdentifier(dbClusterIdentifier);
            request.SetSkipFinalSnapshot(true);

            Aws::RDS::Model::DeleteDBClusterOutcome outcome =
                    client.DeleteDBCluster(request);

            if (outcome.IsSuccess()) {
                std::cout << "DB cluster deletion has started."
                          << std::endl;
                clusterDeleting = true;
                std::cout
                        << "Waiting for DB cluster to delete before deleting the parameter group."
                        << std::endl;
                std::cout << "This may take a while." << std::endl;
            }
            else {
                std::cerr << "Error with Aurora::DeleteDBCluster. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteDBCluster](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBCluster)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_cpp_1_topic"></a>

次のコード例は、`DeleteDBClusterParameterGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::DeleteDBClusterParameterGroupRequest request;
        request.SetDBClusterParameterGroupName(parameterGroupName);

        Aws::RDS::Model::DeleteDBClusterParameterGroupOutcome outcome =
                client.DeleteDBClusterParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully deleted."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::DeleteDBClusterParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBClusterParameterGroup)」を参照してください。

### `DeleteDBInstance`
<a name="aurora_DeleteDBInstance_cpp_1_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

            Aws::RDS::Model::DeleteDBInstanceRequest request;
            request.SetDBInstanceIdentifier(dbInstanceIdentifier);
            request.SetSkipFinalSnapshot(true);
            request.SetDeleteAutomatedBackups(true);

            Aws::RDS::Model::DeleteDBInstanceOutcome outcome =
                    client.DeleteDBInstance(request);

            if (outcome.IsSuccess()) {
                std::cout << "DB instance deletion has started."
                          << std::endl;
                instanceDeleting = true;
                std::cout
                        << "Waiting for DB instance to delete before deleting the parameter group."
                        << std::endl;
            }
            else {
                std::cerr << "Error with Aurora::DeleteDBInstance. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DescribeDBClusterParameterGroups`
<a name="aurora_DescribeDBClusterParameterGroups_cpp_1_topic"></a>

次のコード例は、`DescribeDBClusterParameterGroups` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::DescribeDBClusterParameterGroupsRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);

        Aws::RDS::Model::DescribeDBClusterParameterGroupsOutcome outcome =
                client.DescribeDBClusterParameterGroups(request);

        if (outcome.IsSuccess()) {
            std::cout << "DB cluster parameter group named '" <<
                      CLUSTER_PARAMETER_GROUP_NAME << "' already exists." << std::endl;
            dbParameterGroupFamily = outcome.GetResult().GetDBClusterParameterGroups()[0].GetDBParameterGroupFamily();
        }

        else {
            std::cerr << "Error with Aurora::DescribeDBClusterParameterGroups. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusterParameterGroups)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_cpp_1_topic"></a>

次のコード例は、`DescribeDBClusterParameters` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets DB parameters using the 'DescribeDBClusterParameters' api.
/*!
 \sa getDBCLusterParameters()
 \param parameterGroupName: The name of the cluster parameter group.
 \param namePrefix: Prefix string to filter results by parameter name.
 \param source: A source such as 'user', ignored if empty.
 \param parametersResult: Vector of 'Parameter' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::getDBCLusterParameters(const Aws::String &parameterGroupName,
                                            const Aws::String &namePrefix,
                                            const Aws::String &source,
                                            Aws::Vector<Aws::RDS::Model::Parameter> &parametersResult,
                                            const Aws::RDS::RDSClient &client) {
    Aws::String marker; // The marker is used for pagination.
    do {
        Aws::RDS::Model::DescribeDBClusterParametersRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }
        if (!source.empty()) {
            request.SetSource(source);
        }

        Aws::RDS::Model::DescribeDBClusterParametersOutcome outcome =
                client.DescribeDBClusterParameters(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::Parameter> &parameters =
                    outcome.GetResult().GetParameters();
            for (const Aws::RDS::Model::Parameter &parameter: parameters) {
                if (!namePrefix.empty()) {
                    if (parameter.GetParameterName().find(namePrefix) == 0) {
                        parametersResult.push_back(parameter);
                    }
                }
                else {
                    parametersResult.push_back(parameter);
                }
            }

            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with Aurora::DescribeDBClusterParameters. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusterParameters)」を参照してください。

### `DescribeDBClusterSnapshots`
<a name="aurora_DescribeDBClusterSnapshots_cpp_1_topic"></a>

次のコード例は、`DescribeDBClusterSnapshots` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

            Aws::RDS::Model::DescribeDBClusterSnapshotsRequest request;
            request.SetDBClusterSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::DescribeDBClusterSnapshotsOutcome outcome =
                    client.DescribeDBClusterSnapshots(request);

            if (outcome.IsSuccess()) {
                snapshot = outcome.GetResult().GetDBClusterSnapshots()[0];
            }
            else {
                std::cerr << "Error with Aurora::DescribeDBClusterSnapshots. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(CLUSTER_PARAMETER_GROUP_NAME,
                                 DB_CLUSTER_IDENTIFIER, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusterSnapshots)」を参照してください。

### `DescribeDBClusters`
<a name="aurora_DescribeDBClusters_cpp_1_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

//! Routine which gets a DB cluster description.
/*!
 \sa describeDBCluster()
 \param dbClusterIdentifier: A DB cluster identifier.
 \param clusterResult: The 'DBCluster' object containing the description.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::describeDBCluster(const Aws::String &dbClusterIdentifier,
                                       Aws::RDS::Model::DBCluster &clusterResult,
                                       const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBClustersRequest request;
    request.SetDBClusterIdentifier(dbClusterIdentifier);

    Aws::RDS::Model::DescribeDBClustersOutcome outcome =
            client.DescribeDBClusters(request);

    bool result = true;
    if (outcome.IsSuccess()) {
        clusterResult = outcome.GetResult().GetDBClusters()[0];
    }
    else if (outcome.GetError().GetErrorType() !=
             Aws::RDS::RDSErrors::D_B_CLUSTER_NOT_FOUND_FAULT) {
        result = false;
        std::cerr << "Error with Aurora::GDescribeDBClusters. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
        // This example does not log an error if the DB cluster does not exist.
        // Instead, clusterResult is set to empty.
    else {
        clusterResult = Aws::RDS::Model::DBCluster();
    }

    return result;

}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBClusters)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_cpp_1_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets available DB engine versions for an engine name and
//! an optional parameter group family.
/*!
 \sa getDBEngineVersions()
 \param engineName: A DB engine name.
 \param parameterGroupFamily: A parameter group family name, ignored if empty.
 \param engineVersionsResult: Vector of 'DBEngineVersion' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::getDBEngineVersions(const Aws::String &engineName,
                                         const Aws::String &parameterGroupFamily,
                                         Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersionsResult,
                                         const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBEngineVersionsRequest request;
    request.SetEngine(engineName);
    if (!parameterGroupFamily.empty()) {
        request.SetDBParameterGroupFamily(parameterGroupFamily);
    }

    engineVersionsResult.clear();
    Aws::String marker; // The marker is used for pagination.
    do {
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::RDS::Model::DescribeDBEngineVersionsOutcome outcome =
                client.DescribeDBEngineVersions(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersions =
                    outcome.GetResult().GetDBEngineVersions();

            engineVersionsResult.insert(engineVersionsResult.end(),
                                        engineVersions.begin(), engineVersions.end());
            marker  = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with Aurora::DescribeDBEngineVersionsRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    } while (!marker.empty());

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="aurora_DescribeDBInstances_cpp_1_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets a DB instance description.
/*!
 \sa describeDBCluster()
 \param dbInstanceIdentifier: A DB instance identifier.
 \param instanceResult: The 'DBInstance' object containing the description.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::describeDBInstance(const Aws::String &dbInstanceIdentifier,
                                        Aws::RDS::Model::DBInstance &instanceResult,
                                        const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBInstancesRequest request;
    request.SetDBInstanceIdentifier(dbInstanceIdentifier);

    Aws::RDS::Model::DescribeDBInstancesOutcome outcome =
            client.DescribeDBInstances(request);

    bool result = true;
    if (outcome.IsSuccess()) {
        instanceResult = outcome.GetResult().GetDBInstances()[0];
    }
    else if (outcome.GetError().GetErrorType() !=
             Aws::RDS::RDSErrors::D_B_INSTANCE_NOT_FOUND_FAULT) {
        result = false;
        std::cerr << "Error with Aurora::DescribeDBInstances. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
        // This example does not log an error if the DB instance does not exist.
        // Instead, instanceResult is set to empty.
    else {
        instanceResult = Aws::RDS::Model::DBInstance();
    }

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="aurora_DescribeOrderableDBInstanceOptions_cpp_1_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets available DB instance classes, displays the list
//! to the user, and returns the user selection.
/*!
 \sa chooseDBInstanceClass()
 \param engineName: The DB engine name.
 \param engineVersion: The DB engine version.
 \param dbInstanceClass: String for DB instance class chosen by the user.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::Aurora::chooseDBInstanceClass(const Aws::String &engine,
                                           const Aws::String &engineVersion,
                                           Aws::String &dbInstanceClass,
                                           const Aws::RDS::RDSClient &client) {
    std::vector<Aws::String> instanceClasses;
    Aws::String marker; // The marker is used for pagination.
    do {
        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsRequest request;
        request.SetEngine(engine);
        request.SetEngineVersion(engineVersion);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsOutcome outcome =
                client.DescribeOrderableDBInstanceOptions(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::OrderableDBInstanceOption> &options =
                    outcome.GetResult().GetOrderableDBInstanceOptions();
            for (const Aws::RDS::Model::OrderableDBInstanceOption &option: options) {
                const Aws::String &instanceClass = option.GetDBInstanceClass();
                if (std::find(instanceClasses.begin(), instanceClasses.end(),
                              instanceClass) == instanceClasses.end()) {
                    instanceClasses.push_back(instanceClass);
                }
            }
            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with Aurora::DescribeOrderableDBInstanceOptions. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    std::cout << "The available DB instance classes for your database engine are:"
              << std::endl;
    for (int i = 0; i < instanceClasses.size(); ++i) {
        std::cout << "   " << i + 1 << ": " << instanceClasses[i] << std::endl;
    }

    int choice = askQuestionForIntRange(
            "Which DB instance class do you want to use? ",
            1, static_cast<int>(instanceClasses.size()));
    dbInstanceClass = instanceClasses[choice - 1];
    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_cpp_1_topic"></a>

次のコード例は、`ModifyDBClusterParameterGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::ModifyDBClusterParameterGroupRequest request;
        request.SetDBClusterParameterGroupName(CLUSTER_PARAMETER_GROUP_NAME);
        request.SetParameters(updateParameters);

        Aws::RDS::Model::ModifyDBClusterParameterGroupOutcome outcome =
                client.ModifyDBClusterParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB cluster parameter group was successfully modified."
                      << std::endl;
        }
        else {
            std::cerr << "Error with Aurora::ModifyDBClusterParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/ModifyDBClusterParameterGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_cpp_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for C\$1\$1**  
 Amazon Aurora Serverless データベースに保存されている作業項目を追跡して報告するウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora Serverless データをクエリし、React アプリケーションで使用するための C\$1\$1 REST API の完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/serverless-aurora) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for C\$1\$1 を使用した自動スケーリングの例
<a name="cpp_1_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにちは、Auto Scaling
<a name="auto-scaling_Hello_cpp_1_topic"></a>

次のコード例は、Auto Scaling の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling/hello_autoscaling#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS autoscaling)

# Set this project's name.
project("hello_autoscaling")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_autoscaling.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1autoscaling.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/autoscaling/AutoScalingClient.h>
#include <aws/autoscaling/model/DescribeAutoScalingGroupsRequest.h>
#include <iostream>

/*
 *  A "Hello Autoscaling" starter application which initializes an Amazon EC2 Auto Scaling client and describes the
 *  Amazon EC2 Auto Scaling groups.
 *
 *  main function
 *
 *  Usage: 'hello_autoscaling'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::AutoScaling::AutoScalingClient autoscalingClient(clientConfig);

        std::vector<Aws::String> groupNames;
        Aws::String nextToken; // Used for pagination.

        do {

            Aws::AutoScaling::Model::DescribeAutoScalingGroupsRequest request;
            if (!nextToken.empty()) {
                request.SetNextToken(nextToken);
            }

            Aws::AutoScaling::Model::DescribeAutoScalingGroupsOutcome outcome =
                    autoscalingClient.DescribeAutoScalingGroups(request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::AutoScaling::Model::AutoScalingGroup> &autoScalingGroups =
                        outcome.GetResult().GetAutoScalingGroups();
                for (auto &group: autoScalingGroups) {
                    groupNames.push_back(group.GetAutoScalingGroupName());
                }
                nextToken = outcome.GetResult().GetNextToken();
            } else {
                std::cerr << "Error with AutoScaling::DescribeAutoScalingGroups. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = 1;
                break;
            }
        } while (!nextToken.empty());

        std::cout << "Found " << groupNames.size() << " AutoScaling groups." << std::endl;
        for (auto &groupName: groupNames) {
            std::cout << "AutoScaling group: " << groupName << std::endl;
        }

    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="auto-scaling_Scenario_GroupsAndInstances_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 起動テンプレートとアベイラビリティーゾーンを使用して、Amazon EC2 Auto Scaling グループを作成し、実行中のインスタンスに関する情報を取得します。
+ Amazon CloudWatch メトリクスの収集を有効にします。
+ グループの希望するキャパシティを更新し、インスタンスが起動するのを待ちます。
+  グループ内の最も古いインスタンスを削除します。
+ ユーザーのリクエストやキャパシティの変更に応じて発生するスケーリングアクティビティを一覧表示します。
+ CloudWatch メトリクスの統計を取得して、リソースをクリーンアップします。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
//! Routine which demonstrates using an Auto Scaling group
//! to manage Amazon EC2 instances.
/*!
  \sa groupsAndInstancesScenario()
  \param clientConfig: AWS client configuration.
  \return bool: Successful completion.
 */
bool AwsDoc::AutoScaling::groupsAndInstancesScenario(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::String templateName;
    Aws::EC2::EC2Client ec2Client(clientConfig);

    std::cout << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << " "
              << std::endl;
    std::cout
            << "Welcome to the Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling "
            << "demo for managing groups and instances." << std::endl;
    std::cout << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << " \n"
              << std::endl;

    std::cout << "This example requires an EC2 launch template." << std::endl;
    if (askYesNoQuestion(
            "Would you like to use an existing EC2 launch template (y/n)?  ")) {

        // 1. Specify the name of an existing EC2 launch template.
        templateName = askQuestion(
                "Enter the name of the existing EC2 launch template.  ");

        Aws::EC2::Model::DescribeLaunchTemplatesRequest request;
        request.AddLaunchTemplateNames(templateName);
        Aws::EC2::Model::DescribeLaunchTemplatesOutcome outcome =
                ec2Client.DescribeLaunchTemplates(request);

        if (outcome.IsSuccess()) {
            std::cout << "Validated the EC2 launch template '" << templateName
                      << "' exists by calling DescribeLaunchTemplate." << std::endl;
        }
        else {
            std::cerr << "Error validating the existence of the launch template. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    }
    else { // 2.  Or create a new EC2 launch template.
        templateName = askQuestion("Enter the name for a new EC2 launch template: ");

        Aws::EC2::Model::CreateLaunchTemplateRequest request;
        request.SetLaunchTemplateName(templateName);

        Aws::EC2::Model::RequestLaunchTemplateData requestLaunchTemplateData;
        requestLaunchTemplateData.SetInstanceType(EC2_LAUNCH_TEMPLATE_INSTANCE_TYPE);
        requestLaunchTemplateData.SetImageId(EC2_LAUNCH_TEMPLATE_IMAGE_ID);

        request.SetLaunchTemplateData(requestLaunchTemplateData);

        Aws::EC2::Model::CreateLaunchTemplateOutcome outcome =
                ec2Client.CreateLaunchTemplate(request);

        if (outcome.IsSuccess()) {
            std::cout << "The EC2 launch template '" << templateName << " was created."
                      << std::endl;
        }
        else if (outcome.GetError().GetExceptionName() ==
                 "InvalidLaunchTemplateName.AlreadyExistsException") {
            std::cout << "The EC2 template '" << templateName << "' already exists"
                      << std::endl;
        }
        else {
            std::cerr << "Error with EC2::CreateLaunchTemplate. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    }
    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);
    std::cout << "Let's create an Auto Scaling group." << std::endl;
    Aws::String groupName = askQuestion(
            "Enter a name for the Auto Scaling group:  ");
    // 3. Retrieve a list of EC2 Availability Zones.
    Aws::Vector<Aws::EC2::Model::AvailabilityZone> availabilityZones;
    {
        Aws::EC2::Model::DescribeAvailabilityZonesRequest request;

        Aws::EC2::Model::DescribeAvailabilityZonesOutcome outcome =
                ec2Client.DescribeAvailabilityZones(request);

        if (outcome.IsSuccess()) {
            std::cout
                    << "EC2 instances can be created in the following Availability Zones:"
                    << std::endl;

            availabilityZones = outcome.GetResult().GetAvailabilityZones();
            for (size_t i = 0; i < availabilityZones.size(); ++i) {
                std::cout << "   " << i + 1 << ".  "
                          << availabilityZones[i].GetZoneName() << std::endl;
            }
        }
        else {
            std::cerr << "Error with EC2::DescribeAvailabilityZones. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanupResources("", templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    int availabilityZoneChoice = askQuestionForIntRange(
            "Choose an Availability Zone:  ", 1,
            static_cast<int>(availabilityZones.size()));
    // 4. Create an Auto Scaling group with the specified Availability Zone.
    {
        Aws::AutoScaling::Model::CreateAutoScalingGroupRequest request;
        request.SetAutoScalingGroupName(groupName);
        Aws::Vector<Aws::String> availabilityGroupZones;
        availabilityGroupZones.push_back(
                availabilityZones[availabilityZoneChoice - 1].GetZoneName());
        request.SetAvailabilityZones(availabilityGroupZones);
        request.SetMaxSize(1);
        request.SetMinSize(1);

        Aws::AutoScaling::Model::LaunchTemplateSpecification launchTemplateSpecification;
        launchTemplateSpecification.SetLaunchTemplateName(templateName);
        request.SetLaunchTemplate(launchTemplateSpecification);

        Aws::AutoScaling::Model::CreateAutoScalingGroupOutcome outcome =
                autoScalingClient.CreateAutoScalingGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "Created Auto Scaling group '" << groupName << "'..."
                      << std::endl;
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::AutoScaling::AutoScalingErrors::ALREADY_EXISTS_FAULT) {
            std::cout << "Auto Scaling group '" << groupName << "' already exists."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::CreateAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanupResources("", templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    Aws::Vector<Aws::AutoScaling::Model::AutoScalingGroup> autoScalingGroups;
    if (AwsDoc::AutoScaling::describeGroup(groupName, autoScalingGroups,
                                           autoScalingClient)) {
        std::cout << "Here is the Auto Scaling group description." << std::endl;
        if (!autoScalingGroups.empty()) {
            logAutoScalingGroupInfo(autoScalingGroups);
        }
    }
    else {
        cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
        return false;
    }

    std::cout
            << "Waiting for the EC2 instance in the Auto Scaling group to become active..."
            << std::endl;
    if (!waitForInstances(groupName, autoScalingGroups, autoScalingClient)) {
        cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
        return false;
    }

    bool enableMetrics = askYesNoQuestion(
            "Do you want to collect metrics about the A"
            "Auto Scaling group during this demo (y/n)?  ");
    // 7. Optionally enable metrics collection for the Auto Scaling group.
    if (enableMetrics) {
        Aws::AutoScaling::Model::EnableMetricsCollectionRequest request;
        request.SetAutoScalingGroupName(groupName);

        request.AddMetrics("GroupMinSize");
        request.AddMetrics("GroupMaxSize");
        request.AddMetrics("GroupDesiredCapacity");
        request.AddMetrics("GroupInServiceInstances");
        request.AddMetrics("GroupTotalInstances");
        request.SetGranularity("1Minute");

        Aws::AutoScaling::Model::EnableMetricsCollectionOutcome outcome =
                autoScalingClient.EnableMetricsCollection(request);
        if (outcome.IsSuccess()) {
            std::cout << "Auto Scaling metrics have been enabled."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::EnableMetricsCollection. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    std::cout << "Let's update the maximum number of EC2 instances in '" << groupName <<
              "' from 1 to 3." << std::endl;
    askQuestion("Press enter to continue:  ", alwaysTrueTest);
    // 8. Update the Auto Scaling group, setting a new maximum size.
    {
        Aws::AutoScaling::Model::UpdateAutoScalingGroupRequest request;
        request.SetAutoScalingGroupName(groupName);
        request.SetMaxSize(3);

        Aws::AutoScaling::Model::UpdateAutoScalingGroupOutcome outcome =
                autoScalingClient.UpdateAutoScalingGroup(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error with AutoScaling::UpdateAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    if (AwsDoc::AutoScaling::describeGroup(groupName, autoScalingGroups,
                                           autoScalingClient)) {
        if (!autoScalingGroups.empty()) {
            const auto &instances = autoScalingGroups[0].GetInstances();
            std::cout
                    << "The group still has one running EC2 instance, but it can have up to 3.\n"
                    << std::endl;
            logAutoScalingGroupInfo(autoScalingGroups);
        }
        else {
            std::cerr
                    << "No EC2 launch groups were retrieved from DescribeGroup request."
                    << std::endl;
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    std::cout << "\n" << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << "\n"
              << std::endl;
    std::cout << "Let's update the desired capacity in '" << groupName <<
              "' from 1 to 2." << std::endl;
    askQuestion("Press enter to continue:  ", alwaysTrueTest);
    //  9. Update the Auto Scaling group, setting a new desired capacity.
    {
        Aws::AutoScaling::Model::SetDesiredCapacityRequest request;
        request.SetAutoScalingGroupName(groupName);
        request.SetDesiredCapacity(2);

        Aws::AutoScaling::Model::SetDesiredCapacityOutcome outcome =
                autoScalingClient.SetDesiredCapacity(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error with AutoScaling::SetDesiredCapacityRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    if (AwsDoc::AutoScaling::describeGroup(groupName, autoScalingGroups,
                                           autoScalingClient)) {
        if (!autoScalingGroups.empty()) {
            std::cout
                    << "Here is the current state of the group." << std::endl;
            logAutoScalingGroupInfo(autoScalingGroups);
        }
        else {
            std::cerr
                    << "No EC2 launch groups were retrieved from DescribeGroup request."
                    << std::endl;
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    std::cout << "Waiting for the new EC2 instance to start..." << std::endl;
    waitForInstances(groupName, autoScalingGroups, autoScalingClient);

    std::cout << "\n" << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << "\n"
              << std::endl;

    std::cout << "Let's terminate one of the EC2 instances in " << groupName << "."
              << std::endl;
    std::cout << "Because the desired capacity is 2, another EC2 instance will start "
              << "to replace the terminated EC2 instance."
              << std::endl;
    std::cout << "The currently running EC2 instances are:" << std::endl;

    if (autoScalingGroups.empty()) {
        std::cerr << "Error describing groups. No groups returned." << std::endl;
        cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
        return false;
    }

    int instanceNumber = 1;
    Aws::Vector<Aws::String> instanceIDs = instancesToInstanceIDs(
            autoScalingGroups[0].GetInstances());
    for (const Aws::String &instanceID: instanceIDs) {
        std::cout << "   " << instanceNumber << ". " << instanceID << std::endl;
        ++instanceNumber;
    }

    instanceNumber = askQuestionForIntRange("Which EC2 instance do you want to stop? ",
                                            1,
                                            static_cast<int>(instanceIDs.size()));

    // 10. Terminate an EC2 instance in the Auto Scaling group.
    {
        Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupRequest request;
        request.SetInstanceId(instanceIDs[instanceNumber - 1]);
        request.SetShouldDecrementDesiredCapacity(false);

        Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupOutcome outcome =
                autoScalingClient.TerminateInstanceInAutoScalingGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "Waiting for EC2 instance with ID '"
                      << instanceIDs[instanceNumber - 1] << "' to terminate..."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::TerminateInstanceInAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    waitForInstances(groupName, autoScalingGroups, autoScalingClient);

    std::cout << "\n" << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << "\n"
              << std::endl;
    std::cout << "Let's get a report of scaling activities for EC2 launch group '"
              << groupName << "'."
              << std::endl;
    askQuestion("Press enter to continue:  ", alwaysTrueTest);
    // 11. Get a description of activities for the Auto Scaling group.
    {
        Aws::AutoScaling::Model::DescribeScalingActivitiesRequest request;
        request.SetAutoScalingGroupName(groupName);

        Aws::Vector<Aws::AutoScaling::Model::Activity> allActivities;
        Aws::String nextToken; // Used for pagination;
        do {
            if (!nextToken.empty()) {
                request.SetNextToken(nextToken);
            }
            Aws::AutoScaling::Model::DescribeScalingActivitiesOutcome outcome =
                    autoScalingClient.DescribeScalingActivities(request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::AutoScaling::Model::Activity> &activities =
                        outcome.GetResult().GetActivities();
                allActivities.insert(allActivities.end(), activities.begin(), activities.end());
                nextToken  = outcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error with AutoScaling::DescribeScalingActivities. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
                return false;
            }
        } while (!nextToken.empty());

        std::cout << "Found " << allActivities.size() << " activities."
                  << std::endl;
        std::cout << "Activities are ordered with the most recent first."
                  << std::endl;
        for (const Aws::AutoScaling::Model::Activity &activity: allActivities) {
            std::cout << activity.GetDescription() << std::endl;
            std::cout << activity.GetDetails() << std::endl;
        }
    }

    if (enableMetrics) {
        if (!logAutoScalingMetrics(groupName, clientConfig)) {
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    std::cout << "Let's  clean up." << std::endl;
    askQuestion("Press enter to continue:  ", alwaysTrueTest);

    // 13. Disable metrics collection if enabled.
    if (enableMetrics) {
        Aws::AutoScaling::Model::DisableMetricsCollectionRequest request;
        request.SetAutoScalingGroupName(groupName);

        Aws::AutoScaling::Model::DisableMetricsCollectionOutcome outcome =
                autoScalingClient.DisableMetricsCollection(request);

        if (outcome.IsSuccess()) {
            std::cout << "Metrics collection has been disabled." << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::DisableMetricsCollection. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
            return false;
        }
    }

    return cleanupResources(groupName, templateName, autoScalingClient, ec2Client);
}

//! Routine which waits for EC2 instances in an Auto Scaling group to
//! complete startup or shutdown.
/*!
 \sa waitForInstances()
 \param groupName: An Auto Scaling group name.
 \param autoScalingGroups: Vector to receive 'AutoScalingGroup' records.
 \param client: 'AutoScalingClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::AutoScaling::waitForInstances(const Aws::String &groupName,
                                           Aws::Vector<Aws::AutoScaling::Model::AutoScalingGroup> &autoScalingGroups,
                                           const Aws::AutoScaling::AutoScalingClient &client) {
    bool ready = false;
    const std::vector<Aws::String> READY_STATES = {"InService", "Terminated"};

    int count = 0;
    int desiredCapacity = 0;
    std::this_thread::sleep_for(std::chrono::seconds(4));
    while (!ready) {
        if (WAIT_FOR_INSTANCES_TIMEOUT < count) {
            std::cerr << "Wait for instance timed out." << std::endl;
            return false;
        }

        std::this_thread::sleep_for(std::chrono::seconds(1));
        ++count;
        if (!describeGroup(groupName, autoScalingGroups, client)) {
            return false;
        }
        Aws::Vector<Aws::String> instanceIDs;
        if (!autoScalingGroups.empty()) {
            instanceIDs = instancesToInstanceIDs(autoScalingGroups[0].GetInstances());
            desiredCapacity = autoScalingGroups[0].GetDesiredCapacity();
        }

        if (instanceIDs.empty()) {
            if (desiredCapacity == 0) {
                break;
            }
            else {
                if ((count % 5) == 0) {
                    std::cout << "No instance IDs returned for group." << std::endl;
                }

                continue;
            }
        }

        // 6.  Check lifecycle state of the instances using DescribeAutoScalingInstances.
        Aws::AutoScaling::Model::DescribeAutoScalingInstancesRequest request;
        request.SetInstanceIds(instanceIDs);

        Aws::AutoScaling::Model::DescribeAutoScalingInstancesOutcome outcome =
                client.DescribeAutoScalingInstances(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::AutoScaling::Model::AutoScalingInstanceDetails> &instancesDetails =
                    outcome.GetResult().GetAutoScalingInstances();
            ready = instancesDetails.size() >= desiredCapacity;
            for (const Aws::AutoScaling::Model::AutoScalingInstanceDetails &details: instancesDetails) {
                if (!stringInVector(details.GetLifecycleState(), READY_STATES)) {
                    ready = false;
                    break;
                }
            }
            // Log the status while waiting.
            if (((count % 5) == 1) || ready) {
                logInstancesLifecycleState(instancesDetails);
            }
        }
        else {
            std::cerr << "Error with AutoScaling::DescribeAutoScalingInstances. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    if (!describeGroup(groupName, autoScalingGroups, client)) {
        return false;
    }

    return true;
}

//! Routine to cleanup resources created in 'groupsAndInstancesScenario'.
/*!
 \sa cleanupResources()
 \param groupName: Optional Auto Scaling group name.
 \param templateName: Optional EC2 launch template name.
 \param autoScalingClient: 'AutoScalingClient' instance.
 \param ec2Client: 'EC2Client' instance.
\return bool: Successful completion.
 */
bool AwsDoc::AutoScaling::cleanupResources(const Aws::String &groupName,
                                           const Aws::String &templateName,
                                           const Aws::AutoScaling::AutoScalingClient &autoScalingClient,
                                           const Aws::EC2::EC2Client &ec2Client) {
    bool result = true;

    // 14. Delete the Auto Scaling group.
    if (!groupName.empty() &&
        (askYesNoQuestion(
                Aws::String("Delete the Auto Scaling group '") + groupName +
                "'  (y/n)?"))) {
        {
            Aws::AutoScaling::Model::UpdateAutoScalingGroupRequest request;
            request.SetAutoScalingGroupName(groupName);
            request.SetMinSize(0);
            request.SetDesiredCapacity(0);

            Aws::AutoScaling::Model::UpdateAutoScalingGroupOutcome outcome =
                    autoScalingClient.UpdateAutoScalingGroup(request);

            if (outcome.IsSuccess()) {
                std::cout
                        << "The minimum size and desired capacity of the Auto Scaling group "
                        << "was set to zero before terminating the instances."
                        << std::endl;
            }
            else {
                std::cerr << "Error with AutoScaling::UpdateAutoScalingGroup. "
                          << outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
        }

        Aws::Vector<Aws::AutoScaling::Model::AutoScalingGroup> autoScalingGroups;
        if (AwsDoc::AutoScaling::describeGroup(groupName, autoScalingGroups,
                                               autoScalingClient)) {
            if (!autoScalingGroups.empty()) {
                Aws::Vector<Aws::String> instanceIDs = instancesToInstanceIDs(
                        autoScalingGroups[0].GetInstances());
                for (const Aws::String &instanceID: instanceIDs) {
                    Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupRequest request;
                    request.SetInstanceId(instanceID);
                    request.SetShouldDecrementDesiredCapacity(true);

                    Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupOutcome outcome =
                            autoScalingClient.TerminateInstanceInAutoScalingGroup(
                                    request);

                    if (outcome.IsSuccess()) {
                        std::cout << "Initiating termination of EC2 instance '"
                                  << instanceID << "'." << std::endl;
                    }
                    else {
                        std::cerr
                                << "Error with AutoScaling::TerminateInstanceInAutoScalingGroup. "
                                << outcome.GetError().GetMessage() << std::endl;
                        result = false;
                    }
                }
            }

            std::cout
                    << "Waiting for the EC2 instances to terminate before deleting the "
                    << "Auto Scaling group..." << std::endl;
            waitForInstances(groupName, autoScalingGroups, autoScalingClient);
        }

        {
            Aws::AutoScaling::Model::DeleteAutoScalingGroupRequest request;
            request.SetAutoScalingGroupName(groupName);

            Aws::AutoScaling::Model::DeleteAutoScalingGroupOutcome outcome =
                    autoScalingClient.DeleteAutoScalingGroup(request);

            if (outcome.IsSuccess()) {
                std::cout << "Auto Scaling group '" << groupName << "' was deleted."
                          << std::endl;
            }
            else {
                std::cerr << "Error with AutoScaling::DeleteAutoScalingGroup. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }
    }

    // 15. Delete the EC2 launch template.
    if (!templateName.empty() && (askYesNoQuestion(
            Aws::String("Delete the EC2 launch template '") + templateName +
            "' (y/n)?"))) {
        Aws::EC2::Model::DeleteLaunchTemplateRequest request;
        request.SetLaunchTemplateName(templateName);

        Aws::EC2::Model::DeleteLaunchTemplateOutcome outcome =
                ec2Client.DeleteLaunchTemplate(request);

        if (outcome.IsSuccess()) {
            std::cout << "EC2 launch template '" << templateName << "' was deleted."
                      << std::endl;
        }
        else {
            std::cerr << "Error with EC2::DeleteLaunchTemplate. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
    }

    return result;
}

//! Routine which retrieves Auto Scaling group descriptions.
/*!
 \sa describeGroup()
 \param groupName: An Auto Scaling group name.
 \param autoScalingGroups: Vector to receive 'AutoScalingGroup' records.
 \param client: 'AutoScalingClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::AutoScaling::describeGroup(const Aws::String &groupName,
                                        Aws::Vector<Aws::AutoScaling::Model::AutoScalingGroup> &autoScalingGroup,
                                        const Aws::AutoScaling::AutoScalingClient &client) {
    // 5. Retrieve a description of the Auto Scaling group.
    Aws::AutoScaling::Model::DescribeAutoScalingGroupsRequest request;
    Aws::Vector<Aws::String> groupNames;
    groupNames.push_back(groupName);
    request.SetAutoScalingGroupNames(groupNames);

    Aws::AutoScaling::Model::DescribeAutoScalingGroupsOutcome outcome =
            client.DescribeAutoScalingGroups(request);

    if (outcome.IsSuccess()) {
        autoScalingGroup = outcome.GetResult().GetAutoScalingGroups();
    }
    else {
        std::cerr << "Error with AutoScaling::DescribeAutoScalingGroups. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+ API の詳細については、「AWS SDK for C\$1\$1 API リファレンス**」の以下のトピックを参照してください。
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingInstances)
  + [DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeScalingActivities)
  + [DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DisableMetricsCollection)
  + [EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/EnableMetricsCollection)
  + [SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/SetDesiredCapacity)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/UpdateAutoScalingGroup)

## アクション
<a name="actions"></a>

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_cpp_1_topic"></a>

次のコード例は、`CreateAutoScalingGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::CreateAutoScalingGroupRequest request;
        request.SetAutoScalingGroupName(groupName);
        Aws::Vector<Aws::String> availabilityGroupZones;
        availabilityGroupZones.push_back(
                availabilityZones[availabilityZoneChoice - 1].GetZoneName());
        request.SetAvailabilityZones(availabilityGroupZones);
        request.SetMaxSize(1);
        request.SetMinSize(1);

        Aws::AutoScaling::Model::LaunchTemplateSpecification launchTemplateSpecification;
        launchTemplateSpecification.SetLaunchTemplateName(templateName);
        request.SetLaunchTemplate(launchTemplateSpecification);

        Aws::AutoScaling::Model::CreateAutoScalingGroupOutcome outcome =
                autoScalingClient.CreateAutoScalingGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "Created Auto Scaling group '" << groupName << "'..."
                      << std::endl;
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::AutoScaling::AutoScalingErrors::ALREADY_EXISTS_FAULT) {
            std::cout << "Auto Scaling group '" << groupName << "' already exists."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::CreateAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_cpp_1_topic"></a>

次のコード例は、`DeleteAutoScalingGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

            Aws::AutoScaling::Model::DeleteAutoScalingGroupRequest request;
            request.SetAutoScalingGroupName(groupName);

            Aws::AutoScaling::Model::DeleteAutoScalingGroupOutcome outcome =
                    autoScalingClient.DeleteAutoScalingGroup(request);

            if (outcome.IsSuccess()) {
                std::cout << "Auto Scaling group '" << groupName << "' was deleted."
                          << std::endl;
            }
            else {
                std::cerr << "Error with AutoScaling::DeleteAutoScalingGroup. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_cpp_1_topic"></a>

次のコード例は、`DescribeAutoScalingGroups` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

    Aws::AutoScaling::Model::DescribeAutoScalingGroupsRequest request;
    Aws::Vector<Aws::String> groupNames;
    groupNames.push_back(groupName);
    request.SetAutoScalingGroupNames(groupNames);

    Aws::AutoScaling::Model::DescribeAutoScalingGroupsOutcome outcome =
            client.DescribeAutoScalingGroups(request);

    if (outcome.IsSuccess()) {
        autoScalingGroup = outcome.GetResult().GetAutoScalingGroups();
    }
    else {
        std::cerr << "Error with AutoScaling::DescribeAutoScalingGroups. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_cpp_1_topic"></a>

次のコード例は、`DescribeAutoScalingInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::DescribeAutoScalingInstancesRequest request;
        request.SetInstanceIds(instanceIDs);

        Aws::AutoScaling::Model::DescribeAutoScalingInstancesOutcome outcome =
                client.DescribeAutoScalingInstances(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::AutoScaling::Model::AutoScalingInstanceDetails> &instancesDetails =
                    outcome.GetResult().GetAutoScalingInstances();

        }
        else {
            std::cerr << "Error with AutoScaling::DescribeAutoScalingInstances. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_cpp_1_topic"></a>

次のコード例は、`DescribeScalingActivities` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::DescribeScalingActivitiesRequest request;
        request.SetAutoScalingGroupName(groupName);

        Aws::Vector<Aws::AutoScaling::Model::Activity> allActivities;
        Aws::String nextToken; // Used for pagination;
        do {
            if (!nextToken.empty()) {
                request.SetNextToken(nextToken);
            }
            Aws::AutoScaling::Model::DescribeScalingActivitiesOutcome outcome =
                    autoScalingClient.DescribeScalingActivities(request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::AutoScaling::Model::Activity> &activities =
                        outcome.GetResult().GetActivities();
                allActivities.insert(allActivities.end(), activities.begin(), activities.end());
                nextToken  = outcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error with AutoScaling::DescribeScalingActivities. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

            }
        } while (!nextToken.empty());

        std::cout << "Found " << allActivities.size() << " activities."
                  << std::endl;
        std::cout << "Activities are ordered with the most recent first."
                  << std::endl;
        for (const Aws::AutoScaling::Model::Activity &activity: allActivities) {
            std::cout << activity.GetDescription() << std::endl;
            std::cout << activity.GetDetails() << std::endl;
        }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_cpp_1_topic"></a>

次のコード例は、`DisableMetricsCollection` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::DisableMetricsCollectionRequest request;
        request.SetAutoScalingGroupName(groupName);

        Aws::AutoScaling::Model::DisableMetricsCollectionOutcome outcome =
                autoScalingClient.DisableMetricsCollection(request);

        if (outcome.IsSuccess()) {
            std::cout << "Metrics collection has been disabled." << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::DisableMetricsCollection. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_cpp_1_topic"></a>

次のコード例は、`EnableMetricsCollection` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::EnableMetricsCollectionRequest request;
        request.SetAutoScalingGroupName(groupName);

        request.AddMetrics("GroupMinSize");
        request.AddMetrics("GroupMaxSize");
        request.AddMetrics("GroupDesiredCapacity");
        request.AddMetrics("GroupInServiceInstances");
        request.AddMetrics("GroupTotalInstances");
        request.SetGranularity("1Minute");

        Aws::AutoScaling::Model::EnableMetricsCollectionOutcome outcome =
                autoScalingClient.EnableMetricsCollection(request);
        if (outcome.IsSuccess()) {
            std::cout << "Auto Scaling metrics have been enabled."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::EnableMetricsCollection. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_cpp_1_topic"></a>

次のコード例は、`SetDesiredCapacity` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::SetDesiredCapacityRequest request;
        request.SetAutoScalingGroupName(groupName);
        request.SetDesiredCapacity(2);

        Aws::AutoScaling::Model::SetDesiredCapacityOutcome outcome =
                autoScalingClient.SetDesiredCapacity(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error with AutoScaling::SetDesiredCapacityRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_cpp_1_topic"></a>

次のコード例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupRequest request;
        request.SetInstanceId(instanceIDs[instanceNumber - 1]);
        request.SetShouldDecrementDesiredCapacity(false);

        Aws::AutoScaling::Model::TerminateInstanceInAutoScalingGroupOutcome outcome =
                autoScalingClient.TerminateInstanceInAutoScalingGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "Waiting for EC2 instance with ID '"
                      << instanceIDs[instanceNumber - 1] << "' to terminate..."
                      << std::endl;
        }
        else {
            std::cerr << "Error with AutoScaling::TerminateInstanceInAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_cpp_1_topic"></a>

次のコード例は、`UpdateAutoScalingGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/autoscaling#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::AutoScaling::AutoScalingClient autoScalingClient(clientConfig);

        Aws::AutoScaling::Model::UpdateAutoScalingGroupRequest request;
        request.SetAutoScalingGroupName(groupName);
        request.SetMaxSize(3);

        Aws::AutoScaling::Model::UpdateAutoScalingGroupOutcome outcome =
                autoScalingClient.UpdateAutoScalingGroup(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error with AutoScaling::UpdateAutoScalingGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForCpp/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。

# SDK for C\$1\$1 を使用した CloudTrail の例
<a name="cpp_1_cloudtrail_code_examples"></a>

次のコード例は、CloudTrail AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateTrail`
<a name="cloudtrail_CreateTrail_cpp_1_topic"></a>

次のコード例は、`CreateTrail` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
// Routine which creates an AWS CloudTrail trail.
/*!
  \param trailName: The name of the CloudTrail trail.
  \param bucketName: The Amazon S3 bucket designate for publishing logs.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::createTrail(const Aws::String trailName,
                                     const Aws::String bucketName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient trailClient(clientConfig);
    Aws::CloudTrail::Model::CreateTrailRequest request;
    request.SetName(trailName);
    request.SetS3BucketName(bucketName);

    Aws::CloudTrail::Model::CreateTrailOutcome outcome = trailClient.CreateTrail(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created trail " << trailName << std::endl;
    }
    else {
        std::cerr << "Failed to create trail " << trailName <<
                  ": " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/CreateTrail)」を参照してください。

### `DeleteTrail`
<a name="cloudtrail_DeleteTrail_cpp_1_topic"></a>

次のコード例は、`DeleteTrail` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
// Routine which deletes an AWS CloudTrail trail.
/*!
  \param trailName: The name of the CloudTrail trail.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::deleteTrail(const Aws::String trailName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient trailClient(clientConfig);

    Aws::CloudTrail::Model::DeleteTrailRequest request;
    request.SetName(trailName);

    auto outcome = trailClient.DeleteTrail(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted trail " << trailName << std::endl;
    }
    else {
        std::cerr << "Error deleting trail " << trailName << " " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DeleteTrail)」を参照してください。

### `DescribeTrail`
<a name="cloudtrail_DescribeTrail_cpp_1_topic"></a>

次のコード例は、`DescribeTrail` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
// Routine which describes the AWS CloudTrail trails in an account.
/*!
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/

bool AwsDoc::CloudTrail::describeTrails(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient cloudTrailClient(clientConfig);
    Aws::CloudTrail::Model::DescribeTrailsRequest request;

    auto outcome = cloudTrailClient.DescribeTrails(request);
    if (outcome.IsSuccess()) {
        const Aws::Vector<Aws::CloudTrail::Model::Trail> &trails = outcome.GetResult().GetTrailList();
        std::cout << trails.size() << " trail(s) found." << std::endl;
        for (const Aws::CloudTrail::Model::Trail &trail: trails) {
            std::cout << trail.GetName() << std::endl;
        }
    }
    else {
        std::cerr << "Failed to describe trails." << outcome.GetError().GetMessage()
                  << std::endl;
    }
    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeTrail](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/DescribeTrail)」を参照してください。

### `LookupEvents`
<a name="cloudtrail_LookupEvents_cpp_1_topic"></a>

次のコード例は、`LookupEvents` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
// Routine which looks up events captured by AWS CloudTrail.
/*!
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::CloudTrail::lookupEvents(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::CloudTrail::CloudTrailClient cloudtrail(clientConfig);

    Aws::String nextToken; // Used for pagination.
    Aws::Vector<Aws::CloudTrail::Model::Event> allEvents;

    Aws::CloudTrail::Model::LookupEventsRequest request;

    size_t count = 0;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::CloudTrail::Model::LookupEventsOutcome outcome = cloudtrail.LookupEvents(
                request);
        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::CloudTrail::Model::Event> &events = outcome.GetResult().GetEvents();
            count += events.size();
            allEvents.insert(allEvents.end(), events.begin(), events.end());
            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cerr << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    } while (!nextToken.empty() && count <= 50); // Limit to 50 events.

    std::cout << "Found " << allEvents.size() << " event(s)." << std::endl;

    for (auto &event: allEvents) {
        std::cout << "Event name: " << event.GetEventName() << std::endl;
        std::cout << "Event source: " << event.GetEventSource() << std::endl;
        std::cout << "Event id: " << event.GetEventId() << std::endl;
        std::cout << "Resources: " << std::endl;
        for (auto &resource: event.GetResources()) {
            std::cout << "  " << resource.GetResourceName() << std::endl;
        }
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[LookupEvents](https://docs.aws.amazon.com/goto/SdkForCpp/cloudtrail-2013-11-01/LookupEvents)」を参照してください。

# SDK for C\$1\$1 を使用した CloudWatch の例
<a name="cpp_1_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_cpp_1_topic"></a>

次のコード例は、`DeleteAlarms` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DeleteAlarmsRequest.h>
#include <iostream>
```
アラームを削除します。  

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::DeleteAlarmsRequest request;
        request.AddAlarmNames(alarm_name);

        auto outcome = cw.DeleteAlarms(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to delete CloudWatch alarm:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully deleted CloudWatch alarm " << alarm_name
                << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteAlarms](https://docs.aws.amazon.com/goto/SdkForCpp/monitoring-2010-08-01/DeleteAlarms)」を参照してください。

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_cpp_1_topic"></a>

次のコード例は、`DescribeAlarmsForMetric` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DescribeAlarmsRequest.h>
#include <aws/monitoring/model/DescribeAlarmsResult.h>
#include <iomanip>
#include <iostream>
```
アラームを記述します。  

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::DescribeAlarmsRequest request;
        request.SetMaxRecords(1);

        bool done = false;
        bool header = false;
        while (!done)
        {
            auto outcome = cw.DescribeAlarms(request);
            if (!outcome.IsSuccess())
            {
                std::cout << "Failed to describe CloudWatch alarms:" <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header)
            {
                std::cout << std::left <<
                    std::setw(32) << "Name" <<
                    std::setw(64) << "Arn" <<
                    std::setw(64) << "Description" <<
                    std::setw(20) << "LastUpdated" <<
                    std::endl;
                header = true;
            }

            const auto &alarms = outcome.GetResult().GetMetricAlarms();
            for (const auto &alarm : alarms)
            {
                std::cout << std::left <<
                    std::setw(32) << alarm.GetAlarmName() <<
                    std::setw(64) << alarm.GetAlarmArn() <<
                    std::setw(64) << alarm.GetAlarmDescription() <<
                    std::setw(20) <<
                    alarm.GetAlarmConfigurationUpdatedTimestamp().ToGmtString(
                        SIMPLE_DATE_FORMAT_STR) <<
                    std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/SdkForCpp/monitoring-2010-08-01/DescribeAlarmsForMetric)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_cpp_1_topic"></a>

次のコード例は、`DisableAlarmActions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DisableAlarmActionsRequest.h>
#include <iostream>
```
アラームアクションを無効化します。  

```
        Aws::CloudWatch::CloudWatchClient cw;

        Aws::CloudWatch::Model::DisableAlarmActionsRequest disableAlarmActionsRequest;
        disableAlarmActionsRequest.AddAlarmNames(alarm_name);

        auto disableAlarmActionsOutcome = cw.DisableAlarmActions(disableAlarmActionsRequest);
        if (!disableAlarmActionsOutcome.IsSuccess())
        {
            std::cout << "Failed to disable actions for alarm " << alarm_name <<
                ": " << disableAlarmActionsOutcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully disabled actions for alarm " <<
                alarm_name << std::endl;
        }
```
+  API 詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DisableAlarmActions](https://docs.aws.amazon.com/goto/SdkForCpp/monitoring-2010-08-01/DisableAlarmActions)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_cpp_1_topic"></a>

次のコード例は、`EnableAlarmActions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/EnableAlarmActionsRequest.h>
#include <aws/monitoring/model/PutMetricAlarmRequest.h>
#include <iostream>
```
アラームアクションを有効化します。  

```
    Aws::CloudWatch::CloudWatchClient cw;
    Aws::CloudWatch::Model::PutMetricAlarmRequest request;
    request.SetAlarmName(alarm_name);
    request.SetComparisonOperator(
        Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold);
    request.SetEvaluationPeriods(1);
    request.SetMetricName("CPUUtilization");
    request.SetNamespace("AWS/EC2");
    request.SetPeriod(60);
    request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average);
    request.SetThreshold(70.0);
    request.SetActionsEnabled(false);
    request.SetAlarmDescription("Alarm when server CPU exceeds 70%");
    request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds);
    request.AddAlarmActions(actionArn);

    Aws::CloudWatch::Model::Dimension dimension;
    dimension.SetName("InstanceId");
    dimension.SetValue(instanceId);
    request.AddDimensions(dimension);

    auto outcome = cw.PutMetricAlarm(request);
    if (!outcome.IsSuccess())
    {
        std::cout << "Failed to create CloudWatch alarm:" <<
            outcome.GetError().GetMessage() << std::endl;
        return;
    }

    Aws::CloudWatch::Model::EnableAlarmActionsRequest enable_request;
    enable_request.AddAlarmNames(alarm_name);

    auto enable_outcome = cw.EnableAlarmActions(enable_request);
    if (!enable_outcome.IsSuccess())
    {
        std::cout << "Failed to enable alarm actions:" <<
            enable_outcome.GetError().GetMessage() << std::endl;
        return;
    }

    std::cout << "Successfully created alarm " << alarm_name <<
        " and enabled actions on it." << std::endl;
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[EnableAlarmActions](https://docs.aws.amazon.com/goto/SdkForCpp/monitoring-2010-08-01/EnableAlarmActions)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_cpp_1_topic"></a>

次のコード例は、`ListMetrics` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/ListMetricsRequest.h>
#include <aws/monitoring/model/ListMetricsResult.h>
#include <iomanip>
#include <iostream>
```
メトリクスを一覧表示します。  

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::ListMetricsRequest request;

        if (argc > 1)
        {
            request.SetMetricName(argv[1]);
        }

        if (argc > 2)
        {
            request.SetNamespace(argv[2]);
        }

        bool done = false;
        bool header = false;
        while (!done)
        {
            auto outcome = cw.ListMetrics(request);
            if (!outcome.IsSuccess())
            {
                std::cout << "Failed to list CloudWatch metrics:" <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header)
            {
                std::cout << std::left << std::setw(48) << "MetricName" <<
                    std::setw(32) << "Namespace" << "DimensionNameValuePairs" <<
                    std::endl;
                header = true;
            }

            const auto &metrics = outcome.GetResult().GetMetrics();
            for (const auto &metric : metrics)
            {
                std::cout << std::left << std::setw(48) <<
                    metric.GetMetricName() << std::setw(32) <<
                    metric.GetNamespace();
                const auto &dimensions = metric.GetDimensions();
                for (auto iter = dimensions.cbegin();
                    iter != dimensions.cend(); ++iter)
                {
                    const auto &dimkv = *iter;
                    std::cout << dimkv.GetName() << " = " << dimkv.GetValue();
                    if (iter + 1 != dimensions.cend())
                    {
                        std::cout << ", ";
                    }
                }
                std::cout << std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListMetrics](https://docs.aws.amazon.com/goto/SdkForCpp/monitoring-2010-08-01/ListMetrics)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_cpp_1_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/PutMetricAlarmRequest.h>
#include <iostream>
```
メトリクスを監視するアラームを作成します。  

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::PutMetricAlarmRequest request;
        request.SetAlarmName(alarm_name);
        request.SetComparisonOperator(
            Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold);
        request.SetEvaluationPeriods(1);
        request.SetMetricName("CPUUtilization");
        request.SetNamespace("AWS/EC2");
        request.SetPeriod(60);
        request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average);
        request.SetThreshold(70.0);
        request.SetActionsEnabled(false);
        request.SetAlarmDescription("Alarm when server CPU exceeds 70%");
        request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds);

        Aws::CloudWatch::Model::Dimension dimension;
        dimension.SetName("InstanceId");
        dimension.SetValue(instanceId);

        request.AddDimensions(dimension);

        auto outcome = cw.PutMetricAlarm(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch alarm:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully created CloudWatch alarm " << alarm_name
                << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[PutMetricAlarm](https://docs.aws.amazon.com/goto/SdkForCpp/monitoring-2010-08-01/PutMetricAlarm)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_cpp_1_topic"></a>

次のコード例は、`PutMetricData` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/PutMetricDataRequest.h>
#include <iostream>
```
メトリクスにデータを配置します。  

```
        Aws::CloudWatch::CloudWatchClient cw;

        Aws::CloudWatch::Model::Dimension dimension;
        dimension.SetName("UNIQUE_PAGES");
        dimension.SetValue("URLS");

        Aws::CloudWatch::Model::MetricDatum datum;
        datum.SetMetricName("PAGES_VISITED");
        datum.SetUnit(Aws::CloudWatch::Model::StandardUnit::None);
        datum.SetValue(data_point);
        datum.AddDimensions(dimension);

        Aws::CloudWatch::Model::PutMetricDataRequest request;
        request.SetNamespace("SITE/TRAFFIC");
        request.AddMetricData(datum);

        auto outcome = cw.PutMetricData(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to put sample metric data:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully put sample metric data" << std::endl;
        }
```
+  API の詳細については、「**AWS SDK for C\$1\$1 API リファレンス」の「[PutMetricData](https://docs.aws.amazon.com/goto/SdkForCpp/monitoring-2010-08-01/PutMetricData)」を参照してください。

# SDK for C\$1\$1 を使用した CloudWatch Logs の例
<a name="cpp_1_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteSubscriptionFilter`
<a name="cloudwatch-logs_DeleteSubscriptionFilter_cpp_1_topic"></a>

次のコード例は、`DeleteSubscriptionFilter` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/logs/CloudWatchLogsClient.h>
#include <aws/logs/model/DeleteSubscriptionFilterRequest.h>
#include <iostream>
```
サブスクリプションフィルターを削除します。  

```
        Aws::CloudWatchLogs::CloudWatchLogsClient cwl;
        Aws::CloudWatchLogs::Model::DeleteSubscriptionFilterRequest request;
        request.SetFilterName(filter_name);
        request.SetLogGroupName(log_group);

        auto outcome = cwl.DeleteSubscriptionFilter(request);
        if (!outcome.IsSuccess()) {
            std::cout << "Failed to delete CloudWatch log subscription filter "
                << filter_name << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        } else {
            std::cout << "Successfully deleted CloudWatch logs subscription " <<
                "filter " << filter_name << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteSubscriptionFilter](https://docs.aws.amazon.com/goto/SdkForCpp/logs-2014-03-28/DeleteSubscriptionFilter)」を参照してください。

### `DescribeSubscriptionFilters`
<a name="cloudwatch-logs_DescribeSubscriptionFilters_cpp_1_topic"></a>

次のコード例は、`DescribeSubscriptionFilters` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/logs/CloudWatchLogsClient.h>
#include <aws/logs/model/DescribeSubscriptionFiltersRequest.h>
#include <aws/logs/model/DescribeSubscriptionFiltersResult.h>
#include <iostream>
#include <iomanip>
```
サブスクリプションフィルターを一覧表示します。  

```
        Aws::CloudWatchLogs::CloudWatchLogsClient cwl;
        Aws::CloudWatchLogs::Model::DescribeSubscriptionFiltersRequest request;
        request.SetLogGroupName(log_group);
        request.SetLimit(1);

        bool done = false;
        bool header = false;
        while (!done) {
            auto outcome = cwl.DescribeSubscriptionFilters(
                    request);
            if (!outcome.IsSuccess()) {
                std::cout << "Failed to describe CloudWatch subscription filters "
                    << "for log group " << log_group << ": " <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header) {
                std::cout << std::left << std::setw(32) << "Name" <<
                    std::setw(64) << "FilterPattern" << std::setw(64) <<
                    "DestinationArn" << std::endl;
                header = true;
            }

            const auto &filters = outcome.GetResult().GetSubscriptionFilters();
            for (const auto &filter : filters) {
                std::cout << std::left << std::setw(32) <<
                    filter.GetFilterName() << std::setw(64) <<
                    filter.GetFilterPattern() << std::setw(64) <<
                    filter.GetDestinationArn() << std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeSubscriptionFilters](https://docs.aws.amazon.com/goto/SdkForCpp/logs-2014-03-28/DescribeSubscriptionFilters)」を参照してください。

### `PutSubscriptionFilter`
<a name="cloudwatch-logs_PutSubscriptionFilter_cpp_1_topic"></a>

次のコード例は、`PutSubscriptionFilter` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/logs/CloudWatchLogsClient.h>
#include <aws/logs/model/PutSubscriptionFilterRequest.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```
サブスクリプションフィルターを作成します。  

```
        Aws::CloudWatchLogs::CloudWatchLogsClient cwl;
        Aws::CloudWatchLogs::Model::PutSubscriptionFilterRequest request;
        request.SetFilterName(filter_name);
        request.SetFilterPattern(filter_pattern);
        request.SetLogGroupName(log_group);
        request.SetDestinationArn(dest_arn);
        auto outcome = cwl.PutSubscriptionFilter(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch logs subscription filter "
                << filter_name << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully created CloudWatch logs subscription " <<
                "filter " << filter_name << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[PutSubscriptionFilter](https://docs.aws.amazon.com/goto/SdkForCpp/logs-2014-03-28/PutSubscriptionFilter)」を参照してください。

# SDK for C\$1\$1 を使用した CodeBuild の例
<a name="cpp_1_codebuild_code_examples"></a>

次のコード例は、CodeBuild AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListBuilds`
<a name="codebuild_ListBuilds_cpp_1_topic"></a>

次のコード例は、`ListBuilds` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/codebuild#code-examples)での設定と実行の方法を確認してください。

```
//! List the CodeBuild builds.
/*!
  \param sortType: 'SortOrderType' type.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::CodeBuild::listBuilds(Aws::CodeBuild::Model::SortOrderType sortType,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::CodeBuild::CodeBuildClient codeBuildClient(clientConfiguration);

    Aws::CodeBuild::Model::ListBuildsRequest listBuildsRequest;
    listBuildsRequest.SetSortOrder(sortType);

    Aws::String nextToken; // Used for pagination.

    do {
        if (!nextToken.empty()) {
            listBuildsRequest.SetNextToken(nextToken);
        }

        Aws::CodeBuild::Model::ListBuildsOutcome listBuildsOutcome = codeBuildClient.ListBuilds(
                listBuildsRequest);

        if (listBuildsOutcome.IsSuccess()) {
            const Aws::Vector<Aws::String> &ids = listBuildsOutcome.GetResult().GetIds();
            if (!ids.empty()) {

                std::cout << "Information about each build:" << std::endl;
                Aws::CodeBuild::Model::BatchGetBuildsRequest getBuildsRequest;
                getBuildsRequest.SetIds(listBuildsOutcome.GetResult().GetIds());
                Aws::CodeBuild::Model::BatchGetBuildsOutcome getBuildsOutcome = codeBuildClient.BatchGetBuilds(
                        getBuildsRequest);

                if (getBuildsOutcome.IsSuccess()) {
                    const Aws::Vector<Aws::CodeBuild::Model::Build> &builds = getBuildsOutcome.GetResult().GetBuilds();
                    std::cout << builds.size() << " build(s) found." << std::endl;
                    for (auto val: builds) {
                        std::cout << val.GetId() << std::endl;
                    }
                } else {
                    std::cerr << "Error getting builds"
                              << getBuildsOutcome.GetError().GetMessage() << std::endl;
                    return false;
                }
            } else {
                std::cout << "No builds found." << std::endl;
            }

            // Get the next token for pagination.

            nextToken = listBuildsOutcome.GetResult().GetNextToken();
        } else {
            std::cerr << "Error listing builds"
                      << listBuildsOutcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }

    } while (!nextToken.

            empty()

            );

    return true;
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[ListBuilds](https://docs.aws.amazon.com/goto/SdkForCpp/codebuild-2016-10-06/ListBuilds)」を参照してください。

### `ListProjects`
<a name="codebuild_ListProjects_cpp_1_topic"></a>

次のコード例は、`ListProjects` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/codebuild#code-examples)での設定と実行の方法を確認してください。

```
//! List the CodeBuild projects.
/*!
  \param sortType: 'SortOrderType' type.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::CodeBuild::listProjects(Aws::CodeBuild::Model::SortOrderType sortType,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::CodeBuild::CodeBuildClient codeBuildClient(clientConfiguration);

    Aws::CodeBuild::Model::ListProjectsRequest listProjectsRequest;
    listProjectsRequest.SetSortOrder(sortType);

    Aws::String nextToken; // Next token for pagination.
    Aws::Vector<Aws::String> allProjects;

    do {
        if (!nextToken.empty()) {
            listProjectsRequest.SetNextToken(nextToken);
        }

        Aws::CodeBuild::Model::ListProjectsOutcome outcome = codeBuildClient.ListProjects(
                listProjectsRequest);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::String> &projects = outcome.GetResult().GetProjects();
            allProjects.insert(allProjects.end(), projects.begin(), projects.end());
            nextToken = outcome.GetResult().GetNextToken();
        }

        else {
            std::cerr << "Error listing projects" << outcome.GetError().GetMessage()
                      << std::endl;
        }

    } while (!nextToken.empty());

    std::cout << allProjects.size() << " project(s) found." << std::endl;
    for (auto project: allProjects) {
        std::cout << project << std::endl;
    }

    return true;
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[ListProjects](https://docs.aws.amazon.com/goto/SdkForCpp/codebuild-2016-10-06/ListProjects)」を参照してください。

### `StartBuild`
<a name="codebuild_StartBuild_cpp_1_topic"></a>

次のコード例は、`StartBuild` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/codebuild#code-examples)での設定と実行の方法を確認してください。

```
//! Start an AWS CodeBuild project build.
/*!
  \param projectName: A CodeBuild project name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::CodeBuild::startBuild(const Aws::String &projectName,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::CodeBuild::CodeBuildClient codeBuildClient(clientConfiguration);

    Aws::CodeBuild::Model::StartBuildRequest startBuildRequest;
    startBuildRequest.SetProjectName(projectName);

    Aws::CodeBuild::Model::StartBuildOutcome outcome = codeBuildClient.StartBuild(
            startBuildRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully started build" << std::endl;
        std::cout << "Build ID: " << outcome.GetResult().GetBuild().GetId()
                  << std::endl;
    }

    else {
        std::cerr << "Error starting build" << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[StartBuild](https://docs.aws.amazon.com/goto/SdkForCpp/codebuild-2016-10-06/StartBuild)」を参照してください。

# SDK for C\$1\$1 を使用する Amazon Cognito ID プロバイダーの例
<a name="cpp_1_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダー AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Cognito
<a name="cognito-identity-provider_Hello_cpp_1_topic"></a>

次のコード例は、Amazon Cognito の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito/hello_cognito#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS cognito-idp)

# Set this project's name.
project("hello_cognito")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_cognito.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1cognito.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/cognito-idp/CognitoIdentityProviderClient.h>
#include <aws/cognito-idp/model/ListUserPoolsRequest.h>
#include <iostream>

/*
 *  A "Hello Cognito" starter application which initializes an Amazon Cognito client and lists the Amazon Cognito
 *  user pools.
 *
 *  main function
 *
 *  Usage: 'hello_cognito'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::CognitoIdentityProvider::CognitoIdentityProviderClient cognitoClient(clientConfig);

        Aws::String nextToken; // Used for pagination.
        std::vector<Aws::String> userPools;

        do {
            Aws::CognitoIdentityProvider::Model::ListUserPoolsRequest listUserPoolsRequest;
            if (!nextToken.empty()) {
                listUserPoolsRequest.SetNextToken(nextToken);
            }

            Aws::CognitoIdentityProvider::Model::ListUserPoolsOutcome listUserPoolsOutcome =
                    cognitoClient.ListUserPools(listUserPoolsRequest);

            if (listUserPoolsOutcome.IsSuccess()) {
                for (auto &userPool: listUserPoolsOutcome.GetResult().GetUserPools()) {

                    userPools.push_back(userPool.GetName());
                }

                nextToken = listUserPoolsOutcome.GetResult().GetNextToken();
            } else {
                std::cerr << "ListUserPools error: " << listUserPoolsOutcome.GetError().GetMessage() << std::endl;
                result = 1;
                break;
            }


        } while (!nextToken.empty());
        std::cout << userPools.size() << " user pools found." << std::endl;
        for (auto &userPool: userPools) {
            std::cout << "   user pool: " << userPool << std::endl;
        }
    }

    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListUserPools](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/ListUserPools)」を参照してください。

## アクション
<a name="actions"></a>

### `AdminGetUser`
<a name="cognito-identity-provider_AdminGetUser_cpp_1_topic"></a>

次のコード例は、`AdminGetUser` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

    Aws::CognitoIdentityProvider::Model::AdminGetUserRequest request;
    request.SetUsername(userName);
    request.SetUserPoolId(userPoolID);

    Aws::CognitoIdentityProvider::Model::AdminGetUserOutcome outcome =
            client.AdminGetUser(request);

    if (outcome.IsSuccess()) {
        std::cout << "The status for " << userName << " is " <<
                  Aws::CognitoIdentityProvider::Model::UserStatusTypeMapper::GetNameForUserStatusType(
                          outcome.GetResult().GetUserStatus()) << std::endl;
        std::cout << "Enabled is " << outcome.GetResult().GetEnabled() << std::endl;
    }
    else {
        std::cerr << "Error with CognitoIdentityProvider::AdminGetUser. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AdminGetUser](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AdminGetUser)」を参照してください。

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_cpp_1_topic"></a>

次のコード例は、`AdminInitiateAuth` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

    Aws::CognitoIdentityProvider::Model::AdminInitiateAuthRequest request;
    request.SetClientId(clientID);
    request.SetUserPoolId(userPoolID);
    request.AddAuthParameters("USERNAME", userName);
    request.AddAuthParameters("PASSWORD", password);
    request.SetAuthFlow(
            Aws::CognitoIdentityProvider::Model::AuthFlowType::ADMIN_USER_PASSWORD_AUTH);


    Aws::CognitoIdentityProvider::Model::AdminInitiateAuthOutcome outcome =
            client.AdminInitiateAuth(request);

    if (outcome.IsSuccess()) {
        std::cout << "Call to AdminInitiateAuth was successful." << std::endl;
        sessionResult = outcome.GetResult().GetSession();
    }
    else {
        std::cerr << "Error with CognitoIdentityProvider::AdminInitiateAuth. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AdminInitiateAuth](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AdminInitiateAuth)」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_cpp_1_topic"></a>

次のコード例は、`AdminRespondToAuthChallenge` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

        Aws::CognitoIdentityProvider::Model::AdminRespondToAuthChallengeRequest request;
        request.AddChallengeResponses("USERNAME", userName);
        request.AddChallengeResponses("SOFTWARE_TOKEN_MFA_CODE", mfaCode);
        request.SetChallengeName(
                Aws::CognitoIdentityProvider::Model::ChallengeNameType::SOFTWARE_TOKEN_MFA);
        request.SetClientId(clientID);
        request.SetUserPoolId(userPoolID);
        request.SetSession(session);

        Aws::CognitoIdentityProvider::Model::AdminRespondToAuthChallengeOutcome outcome =
                client.AdminRespondToAuthChallenge(request);

        if (outcome.IsSuccess()) {
            std::cout << "Here is the response to the challenge.\n" <<
                      outcome.GetResult().GetAuthenticationResult().Jsonize().View().WriteReadable()
                      << std::endl;

            accessToken = outcome.GetResult().GetAuthenticationResult().GetAccessToken();
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::AdminRespondToAuthChallenge. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)」を参照してください。

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_cpp_1_topic"></a>

次のコード例は、`AssociateSoftwareToken` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

        Aws::CognitoIdentityProvider::Model::AssociateSoftwareTokenRequest request;
        request.SetSession(session);

        Aws::CognitoIdentityProvider::Model::AssociateSoftwareTokenOutcome outcome =
                client.AssociateSoftwareToken(request);

        if (outcome.IsSuccess()) {
            std::cout
                    << "Enter this setup key into an authenticator app, for example Google Authenticator."
                    << std::endl;
            std::cout << "Setup key: " << outcome.GetResult().GetSecretCode()
                      << std::endl;
#ifdef USING_QR
            printAsterisksLine();
            std::cout << "\nOr scan the QR code in the file '" << QR_CODE_PATH << "."
                      << std::endl;

            saveQRCode(std::string("otpauth://totp/") + userName + "?secret=" +
                       outcome.GetResult().GetSecretCode());
#endif // USING_QR
            session = outcome.GetResult().GetSession();
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::AssociateSoftwareToken. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AssociateSoftwareToken](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AssociateSoftwareToken)」を参照してください。

### `ConfirmSignUp`
<a name="cognito-identity-provider_ConfirmSignUp_cpp_1_topic"></a>

次のコード例は、`ConfirmSignUp` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

        Aws::CognitoIdentityProvider::Model::ConfirmSignUpRequest request;
        request.SetClientId(clientID);
        request.SetConfirmationCode(confirmationCode);
        request.SetUsername(userName);

        Aws::CognitoIdentityProvider::Model::ConfirmSignUpOutcome outcome =
                client.ConfirmSignUp(request);

        if (outcome.IsSuccess()) {
            std::cout << "ConfirmSignup was Successful."
                      << std::endl;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::ConfirmSignUp. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ConfirmSignUp](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/ConfirmSignUp)」を参照してください。

### `DeleteUser`
<a name="cognito-identity-provider_DeleteUser_cpp_1_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

        Aws::CognitoIdentityProvider::Model::DeleteUserRequest request;
        request.SetAccessToken(accessToken);

        Aws::CognitoIdentityProvider::Model::DeleteUserOutcome outcome =
                client.DeleteUser(request);

        if (outcome.IsSuccess()) {
            std::cout << "The user " << userName << " was deleted."
                      << std::endl;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::DeleteUser. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/DeleteUser)」を参照してください。

### `ResendConfirmationCode`
<a name="cognito-identity-provider_ResendConfirmationCode_cpp_1_topic"></a>

次のコード例は、`ResendConfirmationCode` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

        Aws::CognitoIdentityProvider::Model::ResendConfirmationCodeRequest request;
        request.SetUsername(userName);
        request.SetClientId(clientID);

        Aws::CognitoIdentityProvider::Model::ResendConfirmationCodeOutcome outcome =
                client.ResendConfirmationCode(request);

        if (outcome.IsSuccess()) {
            std::cout
                    << "CognitoIdentityProvider::ResendConfirmationCode was successful."
                    << std::endl;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::ResendConfirmationCode. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ResendConfirmationCode](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/ResendConfirmationCode)」を参照してください。

### `SignUp`
<a name="cognito-identity-provider_SignUp_cpp_1_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

        Aws::CognitoIdentityProvider::Model::SignUpRequest request;
        request.AddUserAttributes(
                Aws::CognitoIdentityProvider::Model::AttributeType().WithName(
                        "email").WithValue(email));
        request.SetUsername(userName);
        request.SetPassword(password);
        request.SetClientId(clientID);
        Aws::CognitoIdentityProvider::Model::SignUpOutcome outcome =
                client.SignUp(request);

        if (outcome.IsSuccess()) {
            std::cout << "The signup request for " << userName << " was successful."
                      << std::endl;
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::CognitoIdentityProvider::CognitoIdentityProviderErrors::USERNAME_EXISTS) {
            std::cout
                    << "The username already exists. Please enter a different username."
                    << std::endl;
            userExists = true;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::SignUpRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[SignUp](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/SignUp)」を参照してください。

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_cpp_1_topic"></a>

次のコード例は、`VerifySoftwareToken` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);

        Aws::CognitoIdentityProvider::Model::VerifySoftwareTokenRequest request;
        request.SetUserCode(userCode);
        request.SetSession(session);

        Aws::CognitoIdentityProvider::Model::VerifySoftwareTokenOutcome outcome =
                client.VerifySoftwareToken(request);

        if (outcome.IsSuccess()) {
            std::cout << "Verification of the code was successful."
                      << std::endl;
            session = outcome.GetResult().GetSession();
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::VerifySoftwareToken. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[VerifySoftwareToken](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/VerifySoftwareToken)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### MFA を必要とするユーザープールでユーザーをサインアップする
<a name="cognito-identity-provider_Scenario_SignUpUserWithMfa_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。
+ MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。
+ パスワードと MFA コードを使用してサインインします。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Scenario that adds a user to an Amazon Cognito user pool.
/*!
  \sa gettingStartedWithUserPools()
  \param clientID: Client ID associated with an Amazon Cognito user pool.
  \param userPoolID: An Amazon Cognito user pool ID.
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
 */
bool AwsDoc::Cognito::gettingStartedWithUserPools(const Aws::String &clientID,
                                                  const Aws::String &userPoolID,
                                                  const Aws::Client::ClientConfiguration &clientConfig) {
    printAsterisksLine();
    std::cout
            << "Welcome to the Amazon Cognito example scenario."
            << std::endl;
    printAsterisksLine();

    std::cout
            << "This scenario will add a user to an Amazon Cognito user pool."
            << std::endl;
    const Aws::String userName = askQuestion("Enter a new username: ");
    const Aws::String password = askQuestion("Enter a new password: ");
    const Aws::String email = askQuestion("Enter a valid email for the user: ");

    std::cout << "Signing up " << userName << std::endl;

    Aws::CognitoIdentityProvider::CognitoIdentityProviderClient client(clientConfig);
    bool userExists = false;
    do {
        // 1. Add a user with a username, password, and email address.
        Aws::CognitoIdentityProvider::Model::SignUpRequest request;
        request.AddUserAttributes(
                Aws::CognitoIdentityProvider::Model::AttributeType().WithName(
                        "email").WithValue(email));
        request.SetUsername(userName);
        request.SetPassword(password);
        request.SetClientId(clientID);
        Aws::CognitoIdentityProvider::Model::SignUpOutcome outcome =
                client.SignUp(request);

        if (outcome.IsSuccess()) {
            std::cout << "The signup request for " << userName << " was successful."
                      << std::endl;
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::CognitoIdentityProvider::CognitoIdentityProviderErrors::USERNAME_EXISTS) {
            std::cout
                    << "The username already exists. Please enter a different username."
                    << std::endl;
            userExists = true;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::SignUpRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (userExists);

    printAsterisksLine();
    std::cout << "Retrieving status of " << userName << " in the user pool."
              << std::endl;
    // 2. Confirm that the user was added to the user pool.
    if (!checkAdminUserStatus(userName, userPoolID, client)) {
        return false;
    }

    std::cout << "A confirmation code was sent to " << email << "." << std::endl;

    bool resend = askYesNoQuestion("Would you like to send a new code? (y/n) ");
    if (resend) {
        // Request a resend of the confirmation code to the email address. (ResendConfirmationCode)
        Aws::CognitoIdentityProvider::Model::ResendConfirmationCodeRequest request;
        request.SetUsername(userName);
        request.SetClientId(clientID);

        Aws::CognitoIdentityProvider::Model::ResendConfirmationCodeOutcome outcome =
                client.ResendConfirmationCode(request);

        if (outcome.IsSuccess()) {
            std::cout
                    << "CognitoIdentityProvider::ResendConfirmationCode was successful."
                    << std::endl;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::ResendConfirmationCode. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    printAsterisksLine();

    {
        // 4. Send the confirmation code that's received in the email. (ConfirmSignUp)
        const Aws::String confirmationCode = askQuestion(
                "Enter the confirmation code that was emailed: ");
        Aws::CognitoIdentityProvider::Model::ConfirmSignUpRequest request;
        request.SetClientId(clientID);
        request.SetConfirmationCode(confirmationCode);
        request.SetUsername(userName);

        Aws::CognitoIdentityProvider::Model::ConfirmSignUpOutcome outcome =
                client.ConfirmSignUp(request);

        if (outcome.IsSuccess()) {
            std::cout << "ConfirmSignup was Successful."
                      << std::endl;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::ConfirmSignUp. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    std::cout << "Rechecking the status of " << userName << " in the user pool."
              << std::endl;
    if (!checkAdminUserStatus(userName, userPoolID, client)) {
        return false;
    }

    printAsterisksLine();

    std::cout << "Initiating authorization using the username and password."
              << std::endl;

    Aws::String session;
    // 5. Initiate authorization with username and password. (AdminInitiateAuth)
    if (!adminInitiateAuthorization(clientID, userPoolID,  userName, password, session, client)) {
        return false;
    }

    printAsterisksLine();

    std::cout
            << "Starting setup of time-based one-time password (TOTP) multi-factor authentication (MFA)."
            << std::endl;

    {
        // 6. Request a setup key for one-time password (TOTP)
        //    multi-factor authentication (MFA). (AssociateSoftwareToken)
        Aws::CognitoIdentityProvider::Model::AssociateSoftwareTokenRequest request;
        request.SetSession(session);

        Aws::CognitoIdentityProvider::Model::AssociateSoftwareTokenOutcome outcome =
                client.AssociateSoftwareToken(request);

        if (outcome.IsSuccess()) {
            std::cout
                    << "Enter this setup key into an authenticator app, for example Google Authenticator."
                    << std::endl;
            std::cout << "Setup key: " << outcome.GetResult().GetSecretCode()
                      << std::endl;
#ifdef USING_QR
            printAsterisksLine();
            std::cout << "\nOr scan the QR code in the file '" << QR_CODE_PATH << "."
                      << std::endl;

            saveQRCode(std::string("otpauth://totp/") + userName + "?secret=" +
                       outcome.GetResult().GetSecretCode());
#endif // USING_QR
            session = outcome.GetResult().GetSession();
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::AssociateSoftwareToken. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }
    askQuestion("Type enter to continue...", alwaysTrueTest);

    printAsterisksLine();

    {
        Aws::String userCode = askQuestion(
                "Enter the 6 digit code displayed in the authenticator app: ");

        //  7. Send the MFA code copied from an authenticator app. (VerifySoftwareToken)
        Aws::CognitoIdentityProvider::Model::VerifySoftwareTokenRequest request;
        request.SetUserCode(userCode);
        request.SetSession(session);

        Aws::CognitoIdentityProvider::Model::VerifySoftwareTokenOutcome outcome =
                client.VerifySoftwareToken(request);

        if (outcome.IsSuccess()) {
            std::cout << "Verification of the code was successful."
                      << std::endl;
            session = outcome.GetResult().GetSession();
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::VerifySoftwareToken. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    printAsterisksLine();
    std::cout << "You have completed the MFA authentication setup." << std::endl;
    std::cout << "Now, sign in." << std::endl;

    // 8. Initiate authorization again with username and password. (AdminInitiateAuth)
    if (!adminInitiateAuthorization(clientID, userPoolID, userName, password, session, client)) {
        return false;
    }

    Aws::String accessToken;
    {
        Aws::String mfaCode = askQuestion(
                "Re-enter the 6 digit code displayed in the authenticator app: ");

        // 9. Send a new MFA code copied from an authenticator app. (AdminRespondToAuthChallenge)
        Aws::CognitoIdentityProvider::Model::AdminRespondToAuthChallengeRequest request;
        request.AddChallengeResponses("USERNAME", userName);
        request.AddChallengeResponses("SOFTWARE_TOKEN_MFA_CODE", mfaCode);
        request.SetChallengeName(
                Aws::CognitoIdentityProvider::Model::ChallengeNameType::SOFTWARE_TOKEN_MFA);
        request.SetClientId(clientID);
        request.SetUserPoolId(userPoolID);
        request.SetSession(session);

        Aws::CognitoIdentityProvider::Model::AdminRespondToAuthChallengeOutcome outcome =
                client.AdminRespondToAuthChallenge(request);

        if (outcome.IsSuccess()) {
            std::cout << "Here is the response to the challenge.\n" <<
                      outcome.GetResult().GetAuthenticationResult().Jsonize().View().WriteReadable()
                      << std::endl;

            accessToken = outcome.GetResult().GetAuthenticationResult().GetAccessToken();
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::AdminRespondToAuthChallenge. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }

        std::cout << "You have successfully added a user to Amazon Cognito."
                  << std::endl;
    }

    if (askYesNoQuestion("Would you like to delete the user that you just added? (y/n) ")) {
        // 10. Delete the user that you just added. (DeleteUser)
        Aws::CognitoIdentityProvider::Model::DeleteUserRequest request;
        request.SetAccessToken(accessToken);

        Aws::CognitoIdentityProvider::Model::DeleteUserOutcome outcome =
                client.DeleteUser(request);

        if (outcome.IsSuccess()) {
            std::cout << "The user " << userName << " was deleted."
                      << std::endl;
        }
        else {
            std::cerr << "Error with CognitoIdentityProvider::DeleteUser. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    }

    return true;
}

//! Routine which checks the user status in an Amazon Cognito user pool.
/*!
 \sa checkAdminUserStatus()
 \param userName: A username.
 \param userPoolID: An Amazon Cognito user pool ID.
 \return bool: Successful completion.
 */
bool AwsDoc::Cognito::checkAdminUserStatus(const Aws::String &userName,
                                           const Aws::String &userPoolID,
                                           const Aws::CognitoIdentityProvider::CognitoIdentityProviderClient &client) {
    Aws::CognitoIdentityProvider::Model::AdminGetUserRequest request;
    request.SetUsername(userName);
    request.SetUserPoolId(userPoolID);

    Aws::CognitoIdentityProvider::Model::AdminGetUserOutcome outcome =
            client.AdminGetUser(request);

    if (outcome.IsSuccess()) {
        std::cout << "The status for " << userName << " is " <<
                  Aws::CognitoIdentityProvider::Model::UserStatusTypeMapper::GetNameForUserStatusType(
                          outcome.GetResult().GetUserStatus()) << std::endl;
        std::cout << "Enabled is " << outcome.GetResult().GetEnabled() << std::endl;
    }
    else {
        std::cerr << "Error with CognitoIdentityProvider::AdminGetUser. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}

//! Routine which starts authorization of an Amazon Cognito user.
//! This routine requires administrator credentials.
/*!
 \sa adminInitiateAuthorization()
 \param clientID: Client ID of tracked device.
 \param userPoolID: An Amazon Cognito user pool ID.
 \param userName: A username.
 \param password: A password.
 \param sessionResult: String to receive a session token.
 \return bool: Successful completion.
 */
bool AwsDoc::Cognito::adminInitiateAuthorization(const Aws::String &clientID,
                                                 const Aws::String &userPoolID,
                                                 const Aws::String &userName,
                                                 const Aws::String &password,
                                                 Aws::String &sessionResult,
                                                 const Aws::CognitoIdentityProvider::CognitoIdentityProviderClient &client) {
    Aws::CognitoIdentityProvider::Model::AdminInitiateAuthRequest request;
    request.SetClientId(clientID);
    request.SetUserPoolId(userPoolID);
    request.AddAuthParameters("USERNAME", userName);
    request.AddAuthParameters("PASSWORD", password);
    request.SetAuthFlow(
            Aws::CognitoIdentityProvider::Model::AuthFlowType::ADMIN_USER_PASSWORD_AUTH);


    Aws::CognitoIdentityProvider::Model::AdminInitiateAuthOutcome outcome =
            client.AdminInitiateAuth(request);

    if (outcome.IsSuccess()) {
        std::cout << "Call to AdminInitiateAuth was successful." << std::endl;
        sessionResult = outcome.GetResult().GetSession();
    }
    else {
        std::cerr << "Error with CognitoIdentityProvider::AdminInitiateAuth. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+ API の詳細については、「AWS SDK for C\$1\$1 API リファレンス**」の以下のトピックを参照してください。
  + [AdminGetUser](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AdminGetUser)
  + [AdminInitiateAuth](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AdminInitiateAuth)
  + [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)
  + [AssociateSoftwareToken](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/AssociateSoftwareToken)
  + [ConfirmDevice](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/ConfirmDevice)
  + [ConfirmSignUp](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/ConfirmSignUp)
  + [InitiateAuth](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/InitiateAuth)
  + [ListUsers](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/ListUsers)
  + [ResendConfirmationCode](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/ResendConfirmationCode)
  + [RespondToAuthChallenge](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/RespondToAuthChallenge)
  + [SignUp](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/SignUp)
  + [VerifySoftwareToken](https://docs.aws.amazon.com/goto/SdkForCpp/cognito-idp-2016-04-18/VerifySoftwareToken)

# SDK for C\$1\$1 を使用した DynamoDB の例
<a name="cpp_1_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello DynamoDB
<a name="dynamodb_Hello_cpp_1_topic"></a>

次のコード例は、DynamoDB の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/hello_dynamodb#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS dynamodb)

# Set this project's name.
project("hello_dynamodb")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_dynamodb.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1dynamodb.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/ListTablesRequest.h>
#include <iostream>

/*
 *  A "Hello DynamoDB" starter application which initializes an Amazon DynamoDB (DynamoDB) client and lists the
 *  DynamoDB tables.
 *
 *  main function
 *
 *  Usage: 'hello_dynamodb'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.

    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::DynamoDB::DynamoDBClient dynamodbClient(clientConfig);
        Aws::DynamoDB::Model::ListTablesRequest listTablesRequest;
        listTablesRequest.SetLimit(50);
        do {
            const Aws::DynamoDB::Model::ListTablesOutcome &outcome = dynamodbClient.ListTables(
                    listTablesRequest);
            if (!outcome.IsSuccess()) {
                std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl;
                result = 1;
                break;
            }

            for (const auto &tableName: outcome.GetResult().GetTableNames()) {
                std::cout << tableName << std::endl;
            }

            listTablesRequest.SetExclusiveStartTableName(
                    outcome.GetResult().GetLastEvaluatedTableName());

        } while (!listTablesRequest.GetExclusiveStartTableName().empty());
    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListTables](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/ListTables)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    {
        Aws::Client::ClientConfiguration clientConfig;
        //  1. Create a table with partition: year (N) and sort: title (S). (CreateTable)
        if (AwsDoc::DynamoDB::createMoviesDynamoDBTable(clientConfig)) {

            AwsDoc::DynamoDB::dynamodbGettingStartedScenario(clientConfig);

            // 9. Delete the table. (DeleteTable)
            AwsDoc::DynamoDB::deleteMoviesDynamoDBTable(clientConfig);
        }
    }

//! Scenario to modify and query a DynamoDB table.
/*!
  \sa dynamodbGettingStartedScenario()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::dynamodbGettingStartedScenario(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    std::cout << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << " "
              << std::endl;
    std::cout << "Welcome to the Amazon DynamoDB getting started demo." << std::endl;
    std::cout << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << " "
              << std::endl;

    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    // 2. Add a new movie.
    Aws::String title;
    float rating;
    int year;
    Aws::String plot;
    {
        title = askQuestion(
                "Enter the title of a movie you want to add to the table: ");
        year = askQuestionForInt("What year was it released? ");
        rating = askQuestionForFloatRange("On a scale of 1 - 10, how do you rate it? ",
                                          1, 10);
        plot = askQuestion("Summarize the plot for me: ");

        Aws::DynamoDB::Model::PutItemRequest putItemRequest;
        putItemRequest.SetTableName(MOVIE_TABLE_NAME);

        putItemRequest.AddItem(YEAR_KEY,
                               Aws::DynamoDB::Model::AttributeValue().SetN(year));
        putItemRequest.AddItem(TITLE_KEY,
                               Aws::DynamoDB::Model::AttributeValue().SetS(title));

        // Create attribute for the info map.
        Aws::DynamoDB::Model::AttributeValue infoMapAttribute;

        std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> ratingAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                ALLOCATION_TAG.c_str());
        ratingAttribute->SetN(rating);
        infoMapAttribute.AddMEntry(RATING_KEY, ratingAttribute);

        std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> plotAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                ALLOCATION_TAG.c_str());
        plotAttribute->SetS(plot);
        infoMapAttribute.AddMEntry(PLOT_KEY, plotAttribute);

        putItemRequest.AddItem(INFO_KEY, infoMapAttribute);

        Aws::DynamoDB::Model::PutItemOutcome outcome = dynamoClient.PutItem(
                putItemRequest);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to add an item: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    std::cout << "\nAdded '" << title << "' to '" << MOVIE_TABLE_NAME << "'."
              << std::endl;

    // 3. Update the rating and plot of the movie by using an update expression.
    {
        rating = askQuestionForFloatRange(
                Aws::String("\nLet's update your movie.\nYou rated it  ") +
                std::to_string(rating)
                + ", what new rating would you give it? ", 1, 10);
        plot = askQuestion(Aws::String("You summarized the plot as '") + plot +
                           "'.\nWhat would you say now? ");

        Aws::DynamoDB::Model::UpdateItemRequest request;
        request.SetTableName(MOVIE_TABLE_NAME);
        request.AddKey(TITLE_KEY, Aws::DynamoDB::Model::AttributeValue().SetS(title));
        request.AddKey(YEAR_KEY, Aws::DynamoDB::Model::AttributeValue().SetN(year));
        std::stringstream expressionStream;
        expressionStream << "set " << INFO_KEY << "." << RATING_KEY << " =:r, "
                         << INFO_KEY << "." << PLOT_KEY << " =:p";
        request.SetUpdateExpression(expressionStream.str());
        request.SetExpressionAttributeValues({
                                                     {":r", Aws::DynamoDB::Model::AttributeValue().SetN(
                                                             rating)},
                                                     {":p", Aws::DynamoDB::Model::AttributeValue().SetS(
                                                             plot)}
                                             });

        request.SetReturnValues(Aws::DynamoDB::Model::ReturnValue::UPDATED_NEW);

        const Aws::DynamoDB::Model::UpdateItemOutcome &result = dynamoClient.UpdateItem(
                request);
        if (!result.IsSuccess()) {
            std::cerr << "Error updating movie " + result.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    std::cout << "\nUpdated '" << title << "' with new attributes:" << std::endl;

    // 4. Put 250 movies in the table from moviedata.json.
    {
        std::cout << "Adding movies from a json file to the database." << std::endl;
        const size_t MAX_SIZE_FOR_BATCH_WRITE = 25;
        const size_t MOVIES_TO_WRITE = 10 * MAX_SIZE_FOR_BATCH_WRITE;
        Aws::String jsonString = getMovieJSON();
        if (!jsonString.empty()) {
            Aws::Utils::Json::JsonValue json(jsonString);
            Aws::Utils::Array<Aws::Utils::Json::JsonView> movieJsons = json.View().AsArray();
            Aws::Vector<Aws::DynamoDB::Model::WriteRequest> writeRequests;

            // To add movies with a cross-section of years, use an appropriate increment
            // value for iterating through the database.
            size_t increment = movieJsons.GetLength() / MOVIES_TO_WRITE;
            for (size_t i = 0; i < movieJsons.GetLength(); i += increment) {
                writeRequests.push_back(Aws::DynamoDB::Model::WriteRequest());
                Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> putItems = movieJsonViewToAttributeMap(
                        movieJsons[i]);
                Aws::DynamoDB::Model::PutRequest putRequest;
                putRequest.SetItem(putItems);
                writeRequests.back().SetPutRequest(putRequest);
                if (writeRequests.size() == MAX_SIZE_FOR_BATCH_WRITE) {
                    Aws::DynamoDB::Model::BatchWriteItemRequest request;
                    request.AddRequestItems(MOVIE_TABLE_NAME, writeRequests);
                    const Aws::DynamoDB::Model::BatchWriteItemOutcome &outcome = dynamoClient.BatchWriteItem(
                            request);
                    if (!outcome.IsSuccess()) {
                        std::cerr << "Unable to batch write movie data: "
                                  << outcome.GetError().GetMessage()
                                  << std::endl;
                        writeRequests.clear();
                        break;
                    }
                    else {
                        std::cout << "Added batch of " << writeRequests.size()
                                  << " movies to the database."
                                  << std::endl;
                    }
                    writeRequests.clear();
                }
            }
        }
    }

    std::cout << std::setfill('*') << std::setw(ASTERISK_FILL_WIDTH) << " "
              << std::endl;

    // 5. Get a movie by Key (partition + sort).
    {
        Aws::String titleToGet("King Kong");
        Aws::String answer = askQuestion(Aws::String(
                "Let's move on...Would you like to get info about '" + titleToGet +
                "'? (y/n) "));
        if (answer == "y") {
            Aws::DynamoDB::Model::GetItemRequest request;
            request.SetTableName(MOVIE_TABLE_NAME);
            request.AddKey(TITLE_KEY,
                           Aws::DynamoDB::Model::AttributeValue().SetS(titleToGet));
            request.AddKey(YEAR_KEY, Aws::DynamoDB::Model::AttributeValue().SetN(1933));

            const Aws::DynamoDB::Model::GetItemOutcome &result = dynamoClient.GetItem(
                    request);
            if (!result.IsSuccess()) {
                std::cerr << "Error " << result.GetError().GetMessage();
            }
            else {
                const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = result.GetResult().GetItem();
                if (!item.empty()) {
                    std::cout << "\nHere's what I found:" << std::endl;
                    printMovieInfo(item);
                }
                else {
                    std::cout << "\nThe movie was not found in the database."
                              << std::endl;
                }
            }
        }
    }

    // 6. Use Query with a key condition expression to return all movies
    //    released in a given year.
    Aws::String doAgain = "n";
    do {
        Aws::DynamoDB::Model::QueryRequest req;

        req.SetTableName(MOVIE_TABLE_NAME);

        // "year" is a DynamoDB reserved keyword and must be replaced with an
        // expression attribute name.
        req.SetKeyConditionExpression("#dynobase_year = :valueToMatch");
        req.SetExpressionAttributeNames({{"#dynobase_year", YEAR_KEY}});

        int yearToMatch = askQuestionForIntRange(
                "\nLet's get a list of movies released in"
                " a given year. Enter a year between 1972 and 2018 ",
                1972, 2018);
        Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues;
        attributeValues.emplace(":valueToMatch",
                                Aws::DynamoDB::Model::AttributeValue().SetN(
                                        yearToMatch));
        req.SetExpressionAttributeValues(attributeValues);

        const Aws::DynamoDB::Model::QueryOutcome &result = dynamoClient.Query(req);
        if (result.IsSuccess()) {
            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = result.GetResult().GetItems();
            if (!items.empty()) {
                std::cout << "\nThere were " << items.size()
                          << " movies in the database from "
                          << yearToMatch << "." << std::endl;
                for (const auto &item: items) {
                    printMovieInfo(item);
                }
                doAgain = "n";
            }
            else {
                std::cout << "\nNo movies from " << yearToMatch
                          << " were found in the database"
                          << std::endl;
                doAgain = askQuestion(Aws::String("Try another year? (y/n) "));
            }
        }
        else {
            std::cerr << "Failed to Query items: " << result.GetError().GetMessage()
                      << std::endl;
        }

    } while (doAgain == "y");

    //  7. Use Scan to return movies released within a range of years.
    //     Show how to paginate data using ExclusiveStartKey. (Scan + FilterExpression)
    {
        int startYear = askQuestionForIntRange("\nNow let's scan a range of years "
                                               "for movies in the database. Enter a start year: ",
                                               1972, 2018);
        int endYear = askQuestionForIntRange("\nEnter an end year: ",
                                             startYear, 2018);
        Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> exclusiveStartKey;
        do {
            Aws::DynamoDB::Model::ScanRequest scanRequest;
            scanRequest.SetTableName(MOVIE_TABLE_NAME);
            scanRequest.SetFilterExpression(
                    "#dynobase_year >= :startYear AND #dynobase_year <= :endYear");
            scanRequest.SetExpressionAttributeNames({{"#dynobase_year", YEAR_KEY}});

            Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues;
            attributeValues.emplace(":startYear",
                                    Aws::DynamoDB::Model::AttributeValue().SetN(
                                            startYear));
            attributeValues.emplace(":endYear",
                                    Aws::DynamoDB::Model::AttributeValue().SetN(
                                            endYear));
            scanRequest.SetExpressionAttributeValues(attributeValues);

            if (!exclusiveStartKey.empty()) {
                scanRequest.SetExclusiveStartKey(exclusiveStartKey);
            }

            const Aws::DynamoDB::Model::ScanOutcome &result = dynamoClient.Scan(
                    scanRequest);
            if (result.IsSuccess()) {
                const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = result.GetResult().GetItems();
                if (!items.empty()) {
                    std::stringstream stringStream;
                    stringStream << "\nFound " << items.size() << " movies in one scan."
                                 << " How many would you like to see? ";
                    size_t count = askQuestionForInt(stringStream.str());
                    for (size_t i = 0; i < count && i < items.size(); ++i) {
                        printMovieInfo(items[i]);
                    }
                }
                else {
                    std::cout << "\nNo movies in the database between " << startYear <<
                              " and " << endYear << "." << std::endl;
                }

                exclusiveStartKey = result.GetResult().GetLastEvaluatedKey();
                if (!exclusiveStartKey.empty()) {
                    std::cout << "Not all movies were retrieved. Scanning for more."
                              << std::endl;
                }
                else {
                    std::cout << "All movies were retrieved with this scan."
                              << std::endl;
                }
            }
            else {
                std::cerr << "Failed to Scan movies: "
                          << result.GetError().GetMessage() << std::endl;
            }
        } while (!exclusiveStartKey.empty());
    }

    // 8. Delete a movie. (DeleteItem)
    {
        std::stringstream stringStream;
        stringStream << "\nWould you like to delete the movie " << title
                     << " from the database? (y/n) ";
        Aws::String answer = askQuestion(stringStream.str());
        if (answer == "y") {
            Aws::DynamoDB::Model::DeleteItemRequest request;
            request.AddKey(YEAR_KEY, Aws::DynamoDB::Model::AttributeValue().SetN(year));
            request.AddKey(TITLE_KEY,
                           Aws::DynamoDB::Model::AttributeValue().SetS(title));
            request.SetTableName(MOVIE_TABLE_NAME);

            const Aws::DynamoDB::Model::DeleteItemOutcome &result = dynamoClient.DeleteItem(
                    request);
            if (result.IsSuccess()) {
                std::cout << "\nRemoved \"" << title << "\" from the database."
                          << std::endl;
            }
            else {
                std::cerr << "Failed to delete the movie: "
                          << result.GetError().GetMessage()
                          << std::endl;
            }
        }
    }

    return true;
}

//! Routine to convert a JsonView object to an attribute map.
/*!
  \sa movieJsonViewToAttributeMap()
  \param jsonView: Json view object.
  \return map: Map that can be used in a DynamoDB request.
 */
Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>
AwsDoc::DynamoDB::movieJsonViewToAttributeMap(
        const Aws::Utils::Json::JsonView &jsonView) {
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> result;

    if (jsonView.KeyExists(YEAR_KEY)) {
        result[YEAR_KEY].SetN(jsonView.GetInteger(YEAR_KEY));
    }
    if (jsonView.KeyExists(TITLE_KEY)) {
        result[TITLE_KEY].SetS(jsonView.GetString(TITLE_KEY));
    }
    if (jsonView.KeyExists(INFO_KEY)) {
        Aws::Map<Aws::String, const std::shared_ptr<Aws::DynamoDB::Model::AttributeValue>> infoMap;
        Aws::Utils::Json::JsonView infoView = jsonView.GetObject(INFO_KEY);
        if (infoView.KeyExists(RATING_KEY)) {
            std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> attributeValue = std::make_shared<Aws::DynamoDB::Model::AttributeValue>();
            attributeValue->SetN(infoView.GetDouble(RATING_KEY));
            infoMap.emplace(std::make_pair(RATING_KEY, attributeValue));
        }
        if (infoView.KeyExists(PLOT_KEY)) {
            std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> attributeValue = std::make_shared<Aws::DynamoDB::Model::AttributeValue>();
            attributeValue->SetS(infoView.GetString(PLOT_KEY));
            infoMap.emplace(std::make_pair(PLOT_KEY, attributeValue));
        }

        result[INFO_KEY].SetM(infoMap);
    }

    return result;
}

//! Create a DynamoDB table to be used in sample code scenarios.
/*!
  \sa createMoviesDynamoDBTable()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::createMoviesDynamoDBTable(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    bool movieTableAlreadyExisted = false;

    {
        Aws::DynamoDB::Model::CreateTableRequest request;

        Aws::DynamoDB::Model::AttributeDefinition yearAttributeDefinition;
        yearAttributeDefinition.SetAttributeName(YEAR_KEY);
        yearAttributeDefinition.SetAttributeType(
                Aws::DynamoDB::Model::ScalarAttributeType::N);
        request.AddAttributeDefinitions(yearAttributeDefinition);

        Aws::DynamoDB::Model::AttributeDefinition titleAttributeDefinition;
        yearAttributeDefinition.SetAttributeName(TITLE_KEY);
        yearAttributeDefinition.SetAttributeType(
                Aws::DynamoDB::Model::ScalarAttributeType::S);
        request.AddAttributeDefinitions(yearAttributeDefinition);

        Aws::DynamoDB::Model::KeySchemaElement yearKeySchema;
        yearKeySchema.WithAttributeName(YEAR_KEY).WithKeyType(
                Aws::DynamoDB::Model::KeyType::HASH);
        request.AddKeySchema(yearKeySchema);

        Aws::DynamoDB::Model::KeySchemaElement titleKeySchema;
        yearKeySchema.WithAttributeName(TITLE_KEY).WithKeyType(
                Aws::DynamoDB::Model::KeyType::RANGE);
        request.AddKeySchema(yearKeySchema);

        Aws::DynamoDB::Model::ProvisionedThroughput throughput;
        throughput.WithReadCapacityUnits(
                PROVISIONED_THROUGHPUT_UNITS).WithWriteCapacityUnits(
                PROVISIONED_THROUGHPUT_UNITS);
        request.SetProvisionedThroughput(throughput);
        request.SetTableName(MOVIE_TABLE_NAME);

        std::cout << "Creating table '" << MOVIE_TABLE_NAME << "'..." << std::endl;
        const Aws::DynamoDB::Model::CreateTableOutcome &result = dynamoClient.CreateTable(
                request);
        if (!result.IsSuccess()) {
            if (result.GetError().GetErrorType() ==
                Aws::DynamoDB::DynamoDBErrors::RESOURCE_IN_USE) {
                std::cout << "Table already exists." << std::endl;
                movieTableAlreadyExisted = true;
            }
            else {
                std::cerr << "Failed to create table: "
                          << result.GetError().GetMessage();
                return false;
            }
        }
    }

    // Wait for table to become active.
    if (!movieTableAlreadyExisted) {
        std::cout << "Waiting for table '" << MOVIE_TABLE_NAME
                  << "' to become active...." << std::endl;
        if (!AwsDoc::DynamoDB::waitTableActive(MOVIE_TABLE_NAME, clientConfiguration)) {
            return false;
        }
        std::cout << "Table '" << MOVIE_TABLE_NAME << "' created and active."
                  << std::endl;
    }

    return true;
}

//! Delete the DynamoDB table used for sample code scenarios.
/*!
  \sa deleteMoviesDynamoDBTable()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteMoviesDynamoDBTable(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(MOVIE_TABLE_NAME);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}

//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/BatchWriteItem)
  + [CreateTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/CreateTable)
  + [DeleteItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteItem)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Scan)
  + [UpdateItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/UpdateItem)

## アクション
<a name="actions"></a>

### `BatchExecuteStatement`
<a name="dynamodb_BatchExecuteStatement_cpp_1_topic"></a>

次のコード例は、`BatchExecuteStatement` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
INSERT ステートメントのバッチを使用して項目を追加します。  

```
    // 2. Add multiple movies using "Insert" statements. (BatchExecuteStatement)
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::vector<Aws::String> titles;
    std::vector<float> ratings;
    std::vector<int> years;
    std::vector<Aws::String> plots;
    Aws::String doAgain = "n";
    do {
        Aws::String aTitle = askQuestion(
                "Enter the title of a movie you want to add to the table: ");
        titles.push_back(aTitle);
        int aYear = askQuestionForInt("What year was it released? ");
        years.push_back(aYear);
        float aRating = askQuestionForFloatRange(
                "On a scale of 1 - 10, how do you rate it? ",
                1, 10);
        ratings.push_back(aRating);
        Aws::String aPlot = askQuestion("Summarize the plot for me: ");
        plots.push_back(aPlot);

        doAgain = askQuestion(Aws::String("Would you like to add more movies? (y/n) "));
    } while (doAgain == "y");

    std::cout << "Adding " << titles.size()
              << (titles.size() == 1 ? " movie " : " movies ")
              << "to the table using a batch \"INSERT\" statement." << std::endl;

    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());

        std::stringstream sqlStream;
        sqlStream << "INSERT INTO \"" << MOVIE_TABLE_NAME << "\" VALUE {'"
                  << TITLE_KEY << "': ?, '" << YEAR_KEY << "': ?, '"
                  << INFO_KEY << "': ?}";

        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);

            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));

            // Create attribute for the info map.
            Aws::DynamoDB::Model::AttributeValue infoMapAttribute;

            std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> ratingAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                    ALLOCATION_TAG.c_str());
            ratingAttribute->SetN(ratings[i]);
            infoMapAttribute.AddMEntry(RATING_KEY, ratingAttribute);

            std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> plotAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                    ALLOCATION_TAG.c_str());
            plotAttribute->SetS(plots[i]);
            infoMapAttribute.AddMEntry(PLOT_KEY, plotAttribute);
            attributes.push_back(infoMapAttribute);
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);

        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to add the movies: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }
```
SELECT ステートメントのバッチを使用して項目を取得します。  

```
    // 3. Get the data for multiple movies using "Select" statements. (BatchExecuteStatement)
    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());
        std::stringstream sqlStream;
        sqlStream << "SELECT * FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);
            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);

        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);
        if (outcome.IsSuccess()) {
            const Aws::DynamoDB::Model::BatchExecuteStatementResult &result = outcome.GetResult();

            const Aws::Vector<Aws::DynamoDB::Model::BatchStatementResponse> &responses = result.GetResponses();

            for (const Aws::DynamoDB::Model::BatchStatementResponse &response: responses) {
                const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = response.GetItem();

                printMovieInfo(item);
            }
        }
        else {
            std::cerr << "Failed to retrieve the movie information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }
```
UPDATE ステートメントのバッチを使用して項目を更新します。  

```
    // 4. Update the data for multiple movies using "Update" statements. (BatchExecuteStatement)

    for (size_t i = 0; i < titles.size(); ++i) {
        ratings[i] = askQuestionForFloatRange(
                Aws::String("\nLet's update your the movie, \"") + titles[i] +
                ".\nYou rated it  " + std::to_string(ratings[i])
                + ", what new rating would you give it? ", 1, 10);
    }

    std::cout << "Updating the movie with a batch \"UPDATE\" statement." << std::endl;

    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());

        std::stringstream sqlStream;
        sqlStream << "UPDATE \"" << MOVIE_TABLE_NAME << "\" SET "
                  << INFO_KEY << "." << RATING_KEY << "=? WHERE "
                  << TITLE_KEY << "=? AND " << YEAR_KEY << "=?";


        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);

            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetN(ratings[i]));
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);
        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to update movie information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }
```
DELETE ステートメントのバッチを使用して項目を削除します。  

```
    // 6. Delete multiple movies using "Delete" statements. (BatchExecuteStatement)
    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());
        std::stringstream sqlStream;
        sqlStream << "DELETE FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);
            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);

        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to delete the movies: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_cpp_1_topic"></a>

次のコード例は、`BatchGetItem` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Batch get items from different Amazon DynamoDB tables.
/*!
  \sa batchGetItem()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::batchGetItem(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::BatchGetItemRequest request;

    // Table1: Forum.
    Aws::String table1Name = "Forum";
    Aws::DynamoDB::Model::KeysAndAttributes table1KeysAndAttributes;

    // Table1: Projection expression.
    table1KeysAndAttributes.SetProjectionExpression("#n, Category, Messages, #v");

    // Table1: Expression attribute names.
    Aws::Http::HeaderValueCollection headerValueCollection;
    headerValueCollection.emplace("#n", "Name");
    headerValueCollection.emplace("#v", "Views");
    table1KeysAndAttributes.SetExpressionAttributeNames(headerValueCollection);

    // Table1: Set key name, type, and value to search.
    std::vector<Aws::String> nameValues = {"Amazon DynamoDB", "Amazon S3"};
    for (const Aws::String &name: nameValues) {
        Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> keys;
        Aws::DynamoDB::Model::AttributeValue key;
        key.SetS(name);
        keys.emplace("Name", key);
        table1KeysAndAttributes.AddKeys(keys);
    }

    Aws::Map<Aws::String, Aws::DynamoDB::Model::KeysAndAttributes> requestItems;
    requestItems.emplace(table1Name, table1KeysAndAttributes);

    // Table2: ProductCatalog.
    Aws::String table2Name = "ProductCatalog";
    Aws::DynamoDB::Model::KeysAndAttributes table2KeysAndAttributes;
    table2KeysAndAttributes.SetProjectionExpression("Title, Price, Color");

    // Table2: Set key name, type, and value to search.
    std::vector<Aws::String> idValues = {"102", "103", "201"};
    for (const Aws::String &id: idValues) {
        Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> keys;
        Aws::DynamoDB::Model::AttributeValue key;
        key.SetN(id);
        keys.emplace("Id", key);
        table2KeysAndAttributes.AddKeys(keys);
    }

    requestItems.emplace(table2Name, table2KeysAndAttributes);

    bool result = true;
    do {  // Use a do loop to handle pagination.
        request.SetRequestItems(requestItems);
        const Aws::DynamoDB::Model::BatchGetItemOutcome &outcome = dynamoClient.BatchGetItem(
                request);

        if (outcome.IsSuccess()) {
            for (const auto &responsesMapEntry: outcome.GetResult().GetResponses()) {
                Aws::String tableName = responsesMapEntry.first;
                const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &tableResults = responsesMapEntry.second;
                std::cout << "Retrieved " << tableResults.size()
                          << " responses for table '" << tableName << "'.\n"
                          << std::endl;
                if (tableName == "Forum") {

                    std::cout << "Name | Category | Message | Views" << std::endl;
                    for (const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item: tableResults) {
                        std::cout << item.at("Name").GetS() << " | ";
                        std::cout << item.at("Category").GetS() << " | ";
                        std::cout << (item.count("Message") == 0 ? "" : item.at(
                                "Messages").GetN()) << " | ";
                        std::cout << (item.count("Views") == 0 ? "" : item.at(
                                "Views").GetN()) << std::endl;
                    }
                }
                else {
                    std::cout << "Title | Price | Color" << std::endl;
                    for (const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item: tableResults) {
                        std::cout << item.at("Title").GetS() << " | ";
                        std::cout << (item.count("Price") == 0 ? "" : item.at(
                                "Price").GetN());
                        if (item.count("Color")) {
                            std::cout << " | ";
                            for (const std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> &listItem: item.at(
                                    "Color").GetL())
                                std::cout << listItem->GetS() << " ";
                        }
                        std::cout << std::endl;
                    }
                }
                std::cout << std::endl;
            }

            // If necessary, repeat request for remaining items.
            requestItems = outcome.GetResult().GetUnprocessedKeys();
        }
        else {
            std::cerr << "Batch get item failed: " << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
            break;
        }
    } while (!requestItems.empty());

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[BatchGetItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/BatchGetItem)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_cpp_1_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Batch write items from a JSON file.
/*!
  \sa batchWriteItem()
  \param jsonFilePath: JSON file path.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

/*
 * The input for this routine is a JSON file that you can download from the following URL:
 * https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SampleData.html.
 *
 * The JSON data uses the BatchWriteItem API request syntax. The JSON strings are
 * converted to AttributeValue objects. These AttributeValue objects will then generate
 * JSON strings when constructing the BatchWriteItem request, essentially outputting
 * their input.
 *
 * This is perhaps an artificial example, but it demonstrates the APIs.
 */

bool AwsDoc::DynamoDB::batchWriteItem(const Aws::String &jsonFilePath,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    std::ifstream fileStream(jsonFilePath);

    if (!fileStream) {
        std::cerr << "Error: could not open file '" << jsonFilePath << "'."
                  << std::endl;
    }

    std::stringstream stringStream;
    stringStream << fileStream.rdbuf();
    Aws::Utils::Json::JsonValue jsonValue(stringStream);

    Aws::DynamoDB::Model::BatchWriteItemRequest batchWriteItemRequest;
    Aws::Map<Aws::String, Aws::Utils::Json::JsonView> level1Map = jsonValue.View().GetAllObjects();
    for (const auto &level1Entry: level1Map) {
        const Aws::Utils::Json::JsonView &entriesView = level1Entry.second;
        const Aws::String &tableName = level1Entry.first;
        // The JSON entries at this level are as follows:
        //  key - table name
        //  value - list of request objects
        if (!entriesView.IsListType()) {
            std::cerr << "Error: JSON file entry '"
                      << tableName << "' is not a list." << std::endl;
            continue;
        }

        Aws::Utils::Array<Aws::Utils::Json::JsonView> entries = entriesView.AsArray();

        Aws::Vector<Aws::DynamoDB::Model::WriteRequest> writeRequests;
        if (AwsDoc::DynamoDB::addWriteRequests(tableName, entries,
                                               writeRequests)) {
            batchWriteItemRequest.AddRequestItems(tableName, writeRequests);
        }
    }

    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::BatchWriteItemOutcome outcome = dynamoClient.BatchWriteItem(
            batchWriteItemRequest);

    if (outcome.IsSuccess()) {
        std::cout << "DynamoDB::BatchWriteItem was successful." << std::endl;
    }
    else {
        std::cerr << "Error with DynamoDB::BatchWriteItem. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return outcome.IsSuccess();
}

//! Convert requests in JSON format to a vector of WriteRequest objects.
/*!
  \sa addWriteRequests()
  \param tableName: Name of the table for the write operations.
  \param requestsJson: Request data in JSON format.
  \param writeRequests: Vector to receive the WriteRequest objects.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::addWriteRequests(const Aws::String &tableName,
                                        const Aws::Utils::Array<Aws::Utils::Json::JsonView> &requestsJson,
                                        Aws::Vector<Aws::DynamoDB::Model::WriteRequest> &writeRequests) {
    for (size_t i = 0; i < requestsJson.GetLength(); ++i) {
        const Aws::Utils::Json::JsonView &requestsEntry = requestsJson[i];
        if (!requestsEntry.IsObject()) {
            std::cerr << "Error: incorrect requestsEntry type "
                      << requestsEntry.WriteReadable() << std::endl;
            return false;
        }

        Aws::Map<Aws::String, Aws::Utils::Json::JsonView> requestsMap = requestsEntry.GetAllObjects();

        for (const auto &request: requestsMap) {
            const Aws::String &requestType = request.first;
            const Aws::Utils::Json::JsonView &requestJsonView = request.second;

            if (requestType == "PutRequest") {
                if (!requestJsonView.ValueExists("Item")) {
                    std::cerr << "Error: item key missing for requests "
                              << requestJsonView.WriteReadable() << std::endl;
                    return false;
                }
                Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributes;
                if (!getAttributeObjectsMap(requestJsonView.GetObject("Item"),
                                            attributes)) {
                    std::cerr << "Error getting attributes "
                              << requestJsonView.WriteReadable() << std::endl;
                    return false;
                }

                Aws::DynamoDB::Model::PutRequest putRequest;
                putRequest.SetItem(attributes);
                writeRequests.push_back(
                        Aws::DynamoDB::Model::WriteRequest().WithPutRequest(
                                putRequest));
            }
            else {
                std::cerr << "Error: unimplemented request type '" << requestType
                          << "'." << std::endl;
            }
        }
    }

    return true;
}

//! Generate a map of AttributeValue objects from JSON records.
/*!
  \sa getAttributeObjectsMap()
  \param jsonView: JSONView of attribute records.
  \param writeRequests: Map to receive the AttributeValue objects.
  \return bool: Function succeeded.
 */
bool
AwsDoc::DynamoDB::getAttributeObjectsMap(const Aws::Utils::Json::JsonView &jsonView,
                                         Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &attributes) {
    Aws::Map<Aws::String, Aws::Utils::Json::JsonView> objectsMap = jsonView.GetAllObjects();
    for (const auto &entry: objectsMap) {
        const Aws::String &attributeKey = entry.first;
        const Aws::Utils::Json::JsonView &attributeJsonView = entry.second;

        if (!attributeJsonView.IsObject()) {
            std::cerr << "Error: attribute not an object "
                      << attributeJsonView.WriteReadable() << std::endl;
            return false;
        }

        attributes.emplace(attributeKey,
                           Aws::DynamoDB::Model::AttributeValue(attributeJsonView));
    }

    return true;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。**

### `CreateTable`
<a name="dynamodb_CreateTable_cpp_1_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Create an Amazon DynamoDB table.
/*!
  \sa createTable()
  \param tableName: Name for the DynamoDB table.
  \param primaryKey: Primary key for the DynamoDB table.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::createTable(const Aws::String &tableName,
                                   const Aws::String &primaryKey,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Creating table " << tableName <<
              " with a simple primary key: \"" << primaryKey << "\"." << std::endl;

    Aws::DynamoDB::Model::CreateTableRequest request;

    Aws::DynamoDB::Model::AttributeDefinition hashKey;
    hashKey.SetAttributeName(primaryKey);
    hashKey.SetAttributeType(Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey);

    Aws::DynamoDB::Model::KeySchemaElement keySchemaElement;
    keySchemaElement.WithAttributeName(primaryKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::HASH);
    request.AddKeySchema(keySchemaElement);

    Aws::DynamoDB::Model::ProvisionedThroughput throughput;
    throughput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
    request.SetProvisionedThroughput(throughput);
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::CreateTableOutcome &outcome = dynamoClient.CreateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Table \""
                  << outcome.GetResult().GetTableDescription().GetTableName() <<
                  " created!" << std::endl;
    }
    else {
        std::cerr << "Failed to create table: " << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_cpp_1_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an item from an Amazon DynamoDB table.
/*!
  \sa deleteItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::deleteItem(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteItemRequest request;

    request.AddKey(partitionKey,
                   Aws::DynamoDB::Model::AttributeValue().SetS(partitionValue));
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DeleteItemOutcome &outcome = dynamoClient.DeleteItem(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Item \"" << partitionValue << "\" deleted!" << std::endl;
    }
    else {
        std::cerr << "Failed to delete item: " << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteItem)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_cpp_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an Amazon DynamoDB table.
/*!
  \sa deleteTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteTable(const Aws::String &tableName,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_cpp_1_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Describe an Amazon DynamoDB table.
/*!
  \sa describeTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::describeTable(const Aws::String &tableName,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DescribeTableOutcome &outcome = dynamoClient.DescribeTable(
            request);

    if (outcome.IsSuccess()) {
        const Aws::DynamoDB::Model::TableDescription &td = outcome.GetResult().GetTable();
        std::cout << "Table name  : " << td.GetTableName() << std::endl;
        std::cout << "Table ARN   : " << td.GetTableArn() << std::endl;
        std::cout << "Status      : "
                  << Aws::DynamoDB::Model::TableStatusMapper::GetNameForTableStatus(
                          td.GetTableStatus()) << std::endl;
        std::cout << "Item count  : " << td.GetItemCount() << std::endl;
        std::cout << "Size (bytes): " << td.GetTableSizeBytes() << std::endl;

        const Aws::DynamoDB::Model::ProvisionedThroughputDescription &ptd = td.GetProvisionedThroughput();
        std::cout << "Throughput" << std::endl;
        std::cout << "  Read Capacity : " << ptd.GetReadCapacityUnits() << std::endl;
        std::cout << "  Write Capacity: " << ptd.GetWriteCapacityUnits() << std::endl;

        const Aws::Vector<Aws::DynamoDB::Model::AttributeDefinition> &ad = td.GetAttributeDefinitions();
        std::cout << "Attributes" << std::endl;
        for (const auto &a: ad)
            std::cout << "  " << a.GetAttributeName() << " (" <<
                      Aws::DynamoDB::Model::ScalarAttributeTypeMapper::GetNameForScalarAttributeType(
                              a.GetAttributeType()) <<
                      ")" << std::endl;
    }
    else {
        std::cerr << "Failed to describe table: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[DescribeTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/DescribeTable)」を参照してください。

### `ExecuteStatement`
<a name="dynamodb_ExecuteStatement_cpp_1_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
INSERT ステートメントを使用して項目を追加します。  

```
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    // 2. Add a new movie using an "Insert" statement. (ExecuteStatement)
    Aws::String title;
    float rating;
    int year;
    Aws::String plot;
    {
        title = askQuestion(
                "Enter the title of a movie you want to add to the table: ");
        year = askQuestionForInt("What year was it released? ");
        rating = askQuestionForFloatRange("On a scale of 1 - 10, how do you rate it? ",
                                          1, 10);
        plot = askQuestion("Summarize the plot for me: ");

        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "INSERT INTO \"" << MOVIE_TABLE_NAME << "\" VALUE {'"
                  << TITLE_KEY << "': ?, '" << YEAR_KEY << "': ?, '"
                  << INFO_KEY << "': ?}";

        request.SetStatement(sqlStream.str());

        // Create the parameter attributes.
        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));

        Aws::DynamoDB::Model::AttributeValue infoMapAttribute;

        std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> ratingAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                ALLOCATION_TAG.c_str());
        ratingAttribute->SetN(rating);
        infoMapAttribute.AddMEntry(RATING_KEY, ratingAttribute);

        std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> plotAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                ALLOCATION_TAG.c_str());
        plotAttribute->SetS(plot);
        infoMapAttribute.AddMEntry(PLOT_KEY, plotAttribute);
        attributes.push_back(infoMapAttribute);
        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to add a movie: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }
```
SELECT ステートメントを使用して項目を取得します。  

```
    //  3. Get the data for the movie using a "Select" statement. (ExecuteStatement)
    {
        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "SELECT * FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        request.SetStatement(sqlStream.str());

        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));
        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to retrieve movie information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
        else {
            // Print the retrieved movie information.
            const Aws::DynamoDB::Model::ExecuteStatementResult &result = outcome.GetResult();

            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = result.GetItems();

            if (items.size() == 1) {
                printMovieInfo(items[0]);
            }
            else {
                std::cerr << "Error: " << items.size() << " movies were retrieved. "
                          << " There should be only one movie." << std::endl;
            }
        }
    }
```
UPDATE ステートメントを使用して項目を更新します。  

```
    //  4. Update the data for the movie using an "Update" statement. (ExecuteStatement)
    {
        rating = askQuestionForFloatRange(
                Aws::String("\nLet's update your movie.\nYou rated it  ") +
                std::to_string(rating)
                + ", what new rating would you give it? ", 1, 10);

        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "UPDATE \"" << MOVIE_TABLE_NAME << "\" SET "
                  << INFO_KEY << "." << RATING_KEY << "=? WHERE "
                  << TITLE_KEY << "=? AND " << YEAR_KEY << "=?";

        request.SetStatement(sqlStream.str());

        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(rating));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));

        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to update a movie: "
                      << outcome.GetError().GetMessage();
            return false;
        }
    }
```
DELETE ステートメントを使用して項目を削除します。  

```
    // 6. Delete the movie using a "Delete" statement. (ExecuteStatement)
    {
        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "DELETE FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        request.SetStatement(sqlStream.str());

        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));
        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to delete the movie: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_cpp_1_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Get an item from an Amazon DynamoDB table.
/*!
  \sa getItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::getItem(const Aws::String &tableName,
                               const Aws::String &partitionKey,
                               const Aws::String &partitionValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::GetItemRequest request;

    // Set up the request.
    request.SetTableName(tableName);
    request.AddKey(partitionKey,
                   Aws::DynamoDB::Model::AttributeValue().SetS(partitionValue));

    // Retrieve the item's fields and values.
    const Aws::DynamoDB::Model::GetItemOutcome &outcome = dynamoClient.GetItem(request);
    if (outcome.IsSuccess()) {
        // Reference the retrieved fields/values.
        const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = outcome.GetResult().GetItem();
        if (!item.empty()) {
            // Output each retrieved field and its value.
            for (const auto &i: item)
                std::cout << "Values: " << i.first << ": " << i.second.GetS()
                          << std::endl;
        }
        else {
            std::cout << "No item found with the key " << partitionKey << std::endl;
        }
    }
    else {
        std::cerr << "Failed to get item: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/GetItem)」を参照してください。**

### `ListTables`
<a name="dynamodb_ListTables_cpp_1_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! List the Amazon DynamoDB tables for the current AWS account.
/*!
  \sa listTables()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::listTables(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::ListTablesRequest listTablesRequest;
    listTablesRequest.SetLimit(50);
    do {
        const Aws::DynamoDB::Model::ListTablesOutcome &outcome = dynamoClient.ListTables(
                listTablesRequest);
        if (!outcome.IsSuccess()) {
            std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        for (const auto &tableName: outcome.GetResult().GetTableNames())
            std::cout << tableName << std::endl;
        listTablesRequest.SetExclusiveStartTableName(
                outcome.GetResult().GetLastEvaluatedTableName());

    } while (!listTablesRequest.GetExclusiveStartTableName().empty());

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListTables](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_cpp_1_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Put an item in an Amazon DynamoDB table.
/*!
  \sa putItem()
  \param tableName: The table name.
  \param artistKey: The artist key. This is the partition key for the table.
  \param artistValue: The artist value.
  \param albumTitleKey: The album title key.
  \param albumTitleValue: The album title value.
  \param awardsKey: The awards key.
  \param awardsValue: The awards value.
  \param songTitleKey: The song title key.
  \param songTitleValue: The song title value.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::putItem(const Aws::String &tableName,
                               const Aws::String &artistKey,
                               const Aws::String &artistValue,
                               const Aws::String &albumTitleKey,
                               const Aws::String &albumTitleValue,
                               const Aws::String &awardsKey,
                               const Aws::String &awardsValue,
                               const Aws::String &songTitleKey,
                               const Aws::String &songTitleValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::PutItemRequest putItemRequest;
    putItemRequest.SetTableName(tableName);

    putItemRequest.AddItem(artistKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            artistValue)); // This is the hash key.
    putItemRequest.AddItem(albumTitleKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            albumTitleValue));
    putItemRequest.AddItem(awardsKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(awardsValue));
    putItemRequest.AddItem(songTitleKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(songTitleValue));

    const Aws::DynamoDB::Model::PutItemOutcome outcome = dynamoClient.PutItem(
            putItemRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully added Item!" << std::endl;
    }
    else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*のの「[PutItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/PutItem)」を参照してください。

### `Query`
<a name="dynamodb_Query_cpp_1_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Perform a query on an Amazon DynamoDB Table and retrieve items.
/*!
  \sa queryItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param projectionExpression: The projections expression, which is ignored if empty.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
  */

/*
 * The partition key attribute is searched with the specified value. By default, all fields and values
 * contained in the item are returned. If an optional projection expression is
 * specified on the command line, only the specified fields and values are
 * returned.
 */

bool AwsDoc::DynamoDB::queryItems(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::String &projectionExpression,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::QueryRequest request;

    request.SetTableName(tableName);

    if (!projectionExpression.empty()) {
        request.SetProjectionExpression(projectionExpression);
    }

    // Set query key condition expression.
    request.SetKeyConditionExpression(partitionKey + "= :valueToMatch");

    // Set Expression AttributeValues.
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> attributeValues;
    attributeValues.emplace(":valueToMatch", partitionValue);

    request.SetExpressionAttributeValues(attributeValues);

    bool result = true;

    // "exclusiveStartKey" is used for pagination.
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> exclusiveStartKey;
    do {
        if (!exclusiveStartKey.empty()) {
            request.SetExclusiveStartKey(exclusiveStartKey);
            exclusiveStartKey.clear();
        }
        // Perform Query operation.
        const Aws::DynamoDB::Model::QueryOutcome &outcome = dynamoClient.Query(request);
        if (outcome.IsSuccess()) {
            // Reference the retrieved items.
            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = outcome.GetResult().GetItems();
            if (!items.empty()) {
                std::cout << "Number of items retrieved from Query: " << items.size()
                          << std::endl;
                // Iterate each item and print.
                for (const auto &item: items) {
                    std::cout
                            << "******************************************************"
                            << std::endl;
                    // Output each retrieved field and its value.
                    for (const auto &i: item)
                        std::cout << i.first << ": " << i.second.GetS() << std::endl;
                }
            }
            else {
                std::cout << "No item found in table: " << tableName << std::endl;
            }

            exclusiveStartKey = outcome.GetResult().GetLastEvaluatedKey();
        }
        else {
            std::cerr << "Failed to Query items: " << outcome.GetError().GetMessage();
            result = false;
            break;
        }
    } while (!exclusiveStartKey.empty());

    return result;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Query)」を参照してください。**

### `Scan`
<a name="dynamodb_Scan_cpp_1_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Scan an Amazon DynamoDB table.
/*!
  \sa scanTable()
  \param tableName: Name for the DynamoDB table.
  \param projectionExpression: An optional projection expression, ignored if empty.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::scanTable(const Aws::String &tableName,
                                 const Aws::String &projectionExpression,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::ScanRequest request;
    request.SetTableName(tableName);

    if (!projectionExpression.empty())
        request.SetProjectionExpression(projectionExpression);

    Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> all_items;
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> last_evaluated_key; // Used for pagination;
    do {
        if (!last_evaluated_key.empty()) {
            request.SetExclusiveStartKey(last_evaluated_key);
        }
        const Aws::DynamoDB::Model::ScanOutcome &outcome = dynamoClient.Scan(request);
        if (outcome.IsSuccess()) {
            // Reference the retrieved items.
            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = outcome.GetResult().GetItems();
            all_items.insert(all_items.end(), items.begin(), items.end());

            last_evaluated_key = outcome.GetResult().GetLastEvaluatedKey();
        }
        else {
            std::cerr << "Failed to Scan items: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }

    } while (!last_evaluated_key.empty());

    if (!all_items.empty()) {
        std::cout << "Number of items retrieved from scan: " << all_items.size()
                  << std::endl;
        // Iterate each item and print.
        for (const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &itemMap: all_items) {
            std::cout << "******************************************************"
                      << std::endl;
            // Output each retrieved field and its value.
            for (const auto &itemEntry: itemMap)
                std::cout << itemEntry.first << ": " << itemEntry.second.GetS()
                          << std::endl;
        }
    }

    else {
        std::cout << "No items found in table: " << tableName << std::endl;
    }

    return true;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[Scan](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/Scan)」を参照してください。**

### `UpdateItem`
<a name="dynamodb_UpdateItem_cpp_1_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Update an Amazon DynamoDB table item.
/*!
  \sa updateItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param attributeKey: The key for the attribute to be updated.
  \param attributeValue: The value for the attribute to be updated.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
  */

/*
 *  The example code only sets/updates an attribute value. It processes
 *  the attribute value as a string, even if the value could be interpreted
 *  as a number. Also, the example code does not remove an existing attribute
 *  from the key value.
 */

bool AwsDoc::DynamoDB::updateItem(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::String &attributeKey,
                                  const Aws::String &attributeValue,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    // *** Define UpdateItem request arguments.
    // Define TableName argument.
    Aws::DynamoDB::Model::UpdateItemRequest request;
    request.SetTableName(tableName);

    // Define KeyName argument.
    Aws::DynamoDB::Model::AttributeValue attribValue;
    attribValue.SetS(partitionValue);
    request.AddKey(partitionKey, attribValue);

    // Construct the SET update expression argument.
    Aws::String update_expression("SET #a = :valueA");
    request.SetUpdateExpression(update_expression);

    // Construct attribute name argument.
    Aws::Map<Aws::String, Aws::String> expressionAttributeNames;
    expressionAttributeNames["#a"] = attributeKey;
    request.SetExpressionAttributeNames(expressionAttributeNames);

    // Construct attribute value argument.
    Aws::DynamoDB::Model::AttributeValue attributeUpdatedValue;
    attributeUpdatedValue.SetS(attributeValue);
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> expressionAttributeValues;
    expressionAttributeValues[":valueA"] = attributeUpdatedValue;
    request.SetExpressionAttributeValues(expressionAttributeValues);

    // Update the item.
    const Aws::DynamoDB::Model::UpdateItemOutcome &outcome = dynamoClient.UpdateItem(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Item was updated" << std::endl;
    } else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### `UpdateTable`
<a name="dynamodb_UpdateTable_cpp_1_topic"></a>

次のコード例は、`UpdateTable` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
//! Update a DynamoDB table.
/*!
  \sa updateTable()
  \param tableName: Name for the DynamoDB table.
  \param readCapacity: Provisioned read capacity.
  \param writeCapacity: Provisioned write capacity.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::updateTable(const Aws::String &tableName,
                                   long long readCapacity, long long writeCapacity,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Updating " << tableName << " with new provisioned throughput values"
              << std::endl;
    std::cout << "Read capacity : " << readCapacity << std::endl;
    std::cout << "Write capacity: " << writeCapacity << std::endl;

    Aws::DynamoDB::Model::UpdateTableRequest request;
    Aws::DynamoDB::Model::ProvisionedThroughput provisionedThroughput;
    provisionedThroughput.WithReadCapacityUnits(readCapacity).WithWriteCapacityUnits(
            writeCapacity);
    request.WithProvisionedThroughput(provisionedThroughput).WithTableName(tableName);

    const Aws::DynamoDB::Model::UpdateTableOutcome &outcome = dynamoClient.UpdateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated the table." << std::endl;
    } else {
        const Aws::DynamoDB::DynamoDBError &error = outcome.GetError();
        if (error.GetErrorType() == Aws::DynamoDB::DynamoDBErrors::VALIDATION &&
            error.GetMessage().find("The provisioned throughput for the table will not change") != std::string::npos) {
            std::cout << "The provisioned throughput for the table will not change." << std::endl;
        } else {
            std::cerr << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    return waitTableActive(tableName, dynamoClient);
}
```
テーブルがアクティブになるまで待機するコード。  

```
//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateTable](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/UpdateTable)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_cpp_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for C\$1\$1**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_cpp_1_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        //  1. Create a table. (CreateTable)
        if (AwsDoc::DynamoDB::createMoviesDynamoDBTable(clientConfig)) {

            AwsDoc::DynamoDB::partiqlBatchExecuteScenario(clientConfig);

            // 7. Delete the table. (DeleteTable)
            AwsDoc::DynamoDB::deleteMoviesDynamoDBTable(clientConfig);
        }

//! Scenario to modify and query a DynamoDB table using PartiQL batch statements.
/*!
  \sa partiqlBatchExecuteScenario()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::partiqlBatchExecuteScenario(
        const Aws::Client::ClientConfiguration &clientConfiguration) {

    // 2. Add multiple movies using "Insert" statements. (BatchExecuteStatement)
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::vector<Aws::String> titles;
    std::vector<float> ratings;
    std::vector<int> years;
    std::vector<Aws::String> plots;
    Aws::String doAgain = "n";
    do {
        Aws::String aTitle = askQuestion(
                "Enter the title of a movie you want to add to the table: ");
        titles.push_back(aTitle);
        int aYear = askQuestionForInt("What year was it released? ");
        years.push_back(aYear);
        float aRating = askQuestionForFloatRange(
                "On a scale of 1 - 10, how do you rate it? ",
                1, 10);
        ratings.push_back(aRating);
        Aws::String aPlot = askQuestion("Summarize the plot for me: ");
        plots.push_back(aPlot);

        doAgain = askQuestion(Aws::String("Would you like to add more movies? (y/n) "));
    } while (doAgain == "y");

    std::cout << "Adding " << titles.size()
              << (titles.size() == 1 ? " movie " : " movies ")
              << "to the table using a batch \"INSERT\" statement." << std::endl;

    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());

        std::stringstream sqlStream;
        sqlStream << "INSERT INTO \"" << MOVIE_TABLE_NAME << "\" VALUE {'"
                  << TITLE_KEY << "': ?, '" << YEAR_KEY << "': ?, '"
                  << INFO_KEY << "': ?}";

        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);

            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));

            // Create attribute for the info map.
            Aws::DynamoDB::Model::AttributeValue infoMapAttribute;

            std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> ratingAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                    ALLOCATION_TAG.c_str());
            ratingAttribute->SetN(ratings[i]);
            infoMapAttribute.AddMEntry(RATING_KEY, ratingAttribute);

            std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> plotAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                    ALLOCATION_TAG.c_str());
            plotAttribute->SetS(plots[i]);
            infoMapAttribute.AddMEntry(PLOT_KEY, plotAttribute);
            attributes.push_back(infoMapAttribute);
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);

        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to add the movies: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    std::cout << "Retrieving the movie data with a batch \"SELECT\" statement."
              << std::endl;

    // 3. Get the data for multiple movies using "Select" statements. (BatchExecuteStatement)
    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());
        std::stringstream sqlStream;
        sqlStream << "SELECT * FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);
            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);

        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);
        if (outcome.IsSuccess()) {
            const Aws::DynamoDB::Model::BatchExecuteStatementResult &result = outcome.GetResult();

            const Aws::Vector<Aws::DynamoDB::Model::BatchStatementResponse> &responses = result.GetResponses();

            for (const Aws::DynamoDB::Model::BatchStatementResponse &response: responses) {
                const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = response.GetItem();

                printMovieInfo(item);
            }
        }
        else {
            std::cerr << "Failed to retrieve the movie information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    // 4. Update the data for multiple movies using "Update" statements. (BatchExecuteStatement)

    for (size_t i = 0; i < titles.size(); ++i) {
        ratings[i] = askQuestionForFloatRange(
                Aws::String("\nLet's update your the movie, \"") + titles[i] +
                ".\nYou rated it  " + std::to_string(ratings[i])
                + ", what new rating would you give it? ", 1, 10);
    }

    std::cout << "Updating the movie with a batch \"UPDATE\" statement." << std::endl;

    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());

        std::stringstream sqlStream;
        sqlStream << "UPDATE \"" << MOVIE_TABLE_NAME << "\" SET "
                  << INFO_KEY << "." << RATING_KEY << "=? WHERE "
                  << TITLE_KEY << "=? AND " << YEAR_KEY << "=?";


        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);

            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetN(ratings[i]));
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);
        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to update movie information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    std::cout << "Retrieving the updated movie data with a batch \"SELECT\" statement."
              << std::endl;

    // 5. Get the updated data for multiple movies using "Select" statements. (BatchExecuteStatement)
    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());
        std::stringstream sqlStream;
        sqlStream << "SELECT * FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);
            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);

        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);
        if (outcome.IsSuccess()) {
            const Aws::DynamoDB::Model::BatchExecuteStatementResult &result = outcome.GetResult();

            const Aws::Vector<Aws::DynamoDB::Model::BatchStatementResponse> &responses = result.GetResponses();

            for (const Aws::DynamoDB::Model::BatchStatementResponse &response: responses) {
                const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = response.GetItem();

                printMovieInfo(item);
            }
        }
        else {
            std::cerr << "Failed to retrieve the movies information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    std::cout << "Deleting the movie data with a batch \"DELETE\" statement."
              << std::endl;

    // 6. Delete multiple movies using "Delete" statements. (BatchExecuteStatement)
    {
        Aws::Vector<Aws::DynamoDB::Model::BatchStatementRequest> statements(
                titles.size());
        std::stringstream sqlStream;
        sqlStream << "DELETE FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        std::string sql(sqlStream.str());

        for (size_t i = 0; i < statements.size(); ++i) {
            statements[i].SetStatement(sql);
            Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
            attributes.push_back(
                    Aws::DynamoDB::Model::AttributeValue().SetS(titles[i]));
            attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(years[i]));
            statements[i].SetParameters(attributes);
        }

        Aws::DynamoDB::Model::BatchExecuteStatementRequest request;

        request.SetStatements(statements);

        Aws::DynamoDB::Model::BatchExecuteStatementOutcome outcome = dynamoClient.BatchExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to delete the movies: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    return true;
}

//! Create a DynamoDB table to be used in sample code scenarios.
/*!
  \sa createMoviesDynamoDBTable()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::createMoviesDynamoDBTable(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    bool movieTableAlreadyExisted = false;

    {
        Aws::DynamoDB::Model::CreateTableRequest request;

        Aws::DynamoDB::Model::AttributeDefinition yearAttributeDefinition;
        yearAttributeDefinition.SetAttributeName(YEAR_KEY);
        yearAttributeDefinition.SetAttributeType(
                Aws::DynamoDB::Model::ScalarAttributeType::N);
        request.AddAttributeDefinitions(yearAttributeDefinition);

        Aws::DynamoDB::Model::AttributeDefinition titleAttributeDefinition;
        yearAttributeDefinition.SetAttributeName(TITLE_KEY);
        yearAttributeDefinition.SetAttributeType(
                Aws::DynamoDB::Model::ScalarAttributeType::S);
        request.AddAttributeDefinitions(yearAttributeDefinition);

        Aws::DynamoDB::Model::KeySchemaElement yearKeySchema;
        yearKeySchema.WithAttributeName(YEAR_KEY).WithKeyType(
                Aws::DynamoDB::Model::KeyType::HASH);
        request.AddKeySchema(yearKeySchema);

        Aws::DynamoDB::Model::KeySchemaElement titleKeySchema;
        yearKeySchema.WithAttributeName(TITLE_KEY).WithKeyType(
                Aws::DynamoDB::Model::KeyType::RANGE);
        request.AddKeySchema(yearKeySchema);

        Aws::DynamoDB::Model::ProvisionedThroughput throughput;
        throughput.WithReadCapacityUnits(
                PROVISIONED_THROUGHPUT_UNITS).WithWriteCapacityUnits(
                PROVISIONED_THROUGHPUT_UNITS);
        request.SetProvisionedThroughput(throughput);
        request.SetTableName(MOVIE_TABLE_NAME);

        std::cout << "Creating table '" << MOVIE_TABLE_NAME << "'..." << std::endl;
        const Aws::DynamoDB::Model::CreateTableOutcome &result = dynamoClient.CreateTable(
                request);
        if (!result.IsSuccess()) {
            if (result.GetError().GetErrorType() ==
                Aws::DynamoDB::DynamoDBErrors::RESOURCE_IN_USE) {
                std::cout << "Table already exists." << std::endl;
                movieTableAlreadyExisted = true;
            }
            else {
                std::cerr << "Failed to create table: "
                          << result.GetError().GetMessage();
                return false;
            }
        }
    }

    // Wait for table to become active.
    if (!movieTableAlreadyExisted) {
        std::cout << "Waiting for table '" << MOVIE_TABLE_NAME
                  << "' to become active...." << std::endl;
        if (!AwsDoc::DynamoDB::waitTableActive(MOVIE_TABLE_NAME, clientConfiguration)) {
            return false;
        }
        std::cout << "Table '" << MOVIE_TABLE_NAME << "' created and active."
                  << std::endl;
    }

    return true;
}

//! Delete the DynamoDB table used for sample code scenarios.
/*!
  \sa deleteMoviesDynamoDBTable()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteMoviesDynamoDBTable(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(MOVIE_TABLE_NAME);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}

//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  API の詳細については、「AWS SDK for C\$1\$1 API リファレンス」**の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_cpp_1_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        //  1. Create a table. (CreateTable)
        if (AwsDoc::DynamoDB::createMoviesDynamoDBTable(clientConfig)) {

            AwsDoc::DynamoDB::partiqlExecuteScenario(clientConfig);

            // 7. Delete the table. (DeleteTable)
            AwsDoc::DynamoDB::deleteMoviesDynamoDBTable(clientConfig);
        }

//! Scenario to modify and query a DynamoDB table using single PartiQL statements.
/*!
  \sa partiqlExecuteScenario()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::DynamoDB::partiqlExecuteScenario(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    // 2. Add a new movie using an "Insert" statement. (ExecuteStatement)
    Aws::String title;
    float rating;
    int year;
    Aws::String plot;
    {
        title = askQuestion(
                "Enter the title of a movie you want to add to the table: ");
        year = askQuestionForInt("What year was it released? ");
        rating = askQuestionForFloatRange("On a scale of 1 - 10, how do you rate it? ",
                                          1, 10);
        plot = askQuestion("Summarize the plot for me: ");

        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "INSERT INTO \"" << MOVIE_TABLE_NAME << "\" VALUE {'"
                  << TITLE_KEY << "': ?, '" << YEAR_KEY << "': ?, '"
                  << INFO_KEY << "': ?}";

        request.SetStatement(sqlStream.str());

        // Create the parameter attributes.
        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));

        Aws::DynamoDB::Model::AttributeValue infoMapAttribute;

        std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> ratingAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                ALLOCATION_TAG.c_str());
        ratingAttribute->SetN(rating);
        infoMapAttribute.AddMEntry(RATING_KEY, ratingAttribute);

        std::shared_ptr<Aws::DynamoDB::Model::AttributeValue> plotAttribute = Aws::MakeShared<Aws::DynamoDB::Model::AttributeValue>(
                ALLOCATION_TAG.c_str());
        plotAttribute->SetS(plot);
        infoMapAttribute.AddMEntry(PLOT_KEY, plotAttribute);
        attributes.push_back(infoMapAttribute);
        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to add a movie: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    std::cout << "\nAdded '" << title << "' to '" << MOVIE_TABLE_NAME << "'."
              << std::endl;

    //  3. Get the data for the movie using a "Select" statement. (ExecuteStatement)
    {
        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "SELECT * FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        request.SetStatement(sqlStream.str());

        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));
        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to retrieve movie information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
        else {
            // Print the retrieved movie information.
            const Aws::DynamoDB::Model::ExecuteStatementResult &result = outcome.GetResult();

            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = result.GetItems();

            if (items.size() == 1) {
                printMovieInfo(items[0]);
            }
            else {
                std::cerr << "Error: " << items.size() << " movies were retrieved. "
                          << " There should be only one movie." << std::endl;
            }
        }
    }

    //  4. Update the data for the movie using an "Update" statement. (ExecuteStatement)
    {
        rating = askQuestionForFloatRange(
                Aws::String("\nLet's update your movie.\nYou rated it  ") +
                std::to_string(rating)
                + ", what new rating would you give it? ", 1, 10);

        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "UPDATE \"" << MOVIE_TABLE_NAME << "\" SET "
                  << INFO_KEY << "." << RATING_KEY << "=? WHERE "
                  << TITLE_KEY << "=? AND " << YEAR_KEY << "=?";

        request.SetStatement(sqlStream.str());

        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(rating));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));

        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to update a movie: "
                      << outcome.GetError().GetMessage();
            return false;
        }
    }

    std::cout << "\nUpdated '" << title << "' with new attributes:" << std::endl;

    //  5. Get the updated data for the movie using a "Select" statement. (ExecuteStatement)
    {
        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "SELECT * FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        request.SetStatement(sqlStream.str());

        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));
        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to retrieve the movie information: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
        else {
            const Aws::DynamoDB::Model::ExecuteStatementResult &result = outcome.GetResult();

            const Aws::Vector<Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue>> &items = result.GetItems();

            if (items.size() == 1) {
                printMovieInfo(items[0]);
            }
            else {
                std::cerr << "Error: " << items.size() << " movies were retrieved. "
                          << " There should be only one movie." << std::endl;
            }
        }
    }

    std::cout << "Deleting the movie" << std::endl;

    // 6. Delete the movie using a "Delete" statement. (ExecuteStatement)
    {
        Aws::DynamoDB::Model::ExecuteStatementRequest request;
        std::stringstream sqlStream;
        sqlStream << "DELETE FROM  \"" << MOVIE_TABLE_NAME << "\" WHERE "
                  << TITLE_KEY << "=? and " << YEAR_KEY << "=?";

        request.SetStatement(sqlStream.str());

        Aws::Vector<Aws::DynamoDB::Model::AttributeValue> attributes;
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetS(title));
        attributes.push_back(Aws::DynamoDB::Model::AttributeValue().SetN(year));
        request.SetParameters(attributes);

        Aws::DynamoDB::Model::ExecuteStatementOutcome outcome = dynamoClient.ExecuteStatement(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to delete the movie: "
                      << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    std::cout << "Movie successfully deleted." << std::endl;
    return true;
}

//! Create a DynamoDB table to be used in sample code scenarios.
/*!
  \sa createMoviesDynamoDBTable()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::createMoviesDynamoDBTable(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    bool movieTableAlreadyExisted = false;

    {
        Aws::DynamoDB::Model::CreateTableRequest request;

        Aws::DynamoDB::Model::AttributeDefinition yearAttributeDefinition;
        yearAttributeDefinition.SetAttributeName(YEAR_KEY);
        yearAttributeDefinition.SetAttributeType(
                Aws::DynamoDB::Model::ScalarAttributeType::N);
        request.AddAttributeDefinitions(yearAttributeDefinition);

        Aws::DynamoDB::Model::AttributeDefinition titleAttributeDefinition;
        yearAttributeDefinition.SetAttributeName(TITLE_KEY);
        yearAttributeDefinition.SetAttributeType(
                Aws::DynamoDB::Model::ScalarAttributeType::S);
        request.AddAttributeDefinitions(yearAttributeDefinition);

        Aws::DynamoDB::Model::KeySchemaElement yearKeySchema;
        yearKeySchema.WithAttributeName(YEAR_KEY).WithKeyType(
                Aws::DynamoDB::Model::KeyType::HASH);
        request.AddKeySchema(yearKeySchema);

        Aws::DynamoDB::Model::KeySchemaElement titleKeySchema;
        yearKeySchema.WithAttributeName(TITLE_KEY).WithKeyType(
                Aws::DynamoDB::Model::KeyType::RANGE);
        request.AddKeySchema(yearKeySchema);

        Aws::DynamoDB::Model::ProvisionedThroughput throughput;
        throughput.WithReadCapacityUnits(
                PROVISIONED_THROUGHPUT_UNITS).WithWriteCapacityUnits(
                PROVISIONED_THROUGHPUT_UNITS);
        request.SetProvisionedThroughput(throughput);
        request.SetTableName(MOVIE_TABLE_NAME);

        std::cout << "Creating table '" << MOVIE_TABLE_NAME << "'..." << std::endl;
        const Aws::DynamoDB::Model::CreateTableOutcome &result = dynamoClient.CreateTable(
                request);
        if (!result.IsSuccess()) {
            if (result.GetError().GetErrorType() ==
                Aws::DynamoDB::DynamoDBErrors::RESOURCE_IN_USE) {
                std::cout << "Table already exists." << std::endl;
                movieTableAlreadyExisted = true;
            }
            else {
                std::cerr << "Failed to create table: "
                          << result.GetError().GetMessage();
                return false;
            }
        }
    }

    // Wait for table to become active.
    if (!movieTableAlreadyExisted) {
        std::cout << "Waiting for table '" << MOVIE_TABLE_NAME
                  << "' to become active...." << std::endl;
        if (!AwsDoc::DynamoDB::waitTableActive(MOVIE_TABLE_NAME, clientConfiguration)) {
            return false;
        }
        std::cout << "Table '" << MOVIE_TABLE_NAME << "' created and active."
                  << std::endl;
    }

    return true;
}

//! Delete the DynamoDB table used for sample code scenarios.
/*!
  \sa deleteMoviesDynamoDBTable()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteMoviesDynamoDBTable(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(MOVIE_TABLE_NAME);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}

//! Query a newly created DynamoDB table until it is active.
/*!
  \sa waitTableActive()
  \param waitTableActive: The DynamoDB table's name.
  \param dynamoClient: A DynamoDB client.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::waitTableActive(const Aws::String &tableName,
                                       const Aws::DynamoDB::DynamoDBClient &dynamoClient) {

    // Repeatedly call DescribeTable until table is ACTIVE.
    const int MAX_QUERIES = 20;
    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    int count = 0;
    while (count < MAX_QUERIES) {
        const Aws::DynamoDB::Model::DescribeTableOutcome &result = dynamoClient.DescribeTable(
                request);
        if (result.IsSuccess()) {
            Aws::DynamoDB::Model::TableStatus status = result.GetResult().GetTable().GetTableStatus();

            if (Aws::DynamoDB::Model::TableStatus::ACTIVE != status) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                return true;
            }
        }
        else {
            std::cerr << "Error DynamoDB::waitTableActive "
                      << result.GetError().GetMessage() << std::endl;
            return false;
        }
        count++;
    }
    return false;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForCpp/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

# SDK for C\$1\$1 を使用した Amazon EC2 の例
<a name="cpp_1_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_cpp_1_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/hello_ec2#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS ec2)

# Set this project's name.
project("hello_ec2")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_ec2.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1ec2.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeInstancesRequest.h>
#include <iomanip>
#include <iostream>

/*
 *  A "Hello EC2" starter application which initializes an Amazon Elastic Compute Cloud (Amazon EC2) client and describes
 *  the Amazon EC2 instances.
 *
 *  main function
 *
 *  Usage: 'hello_ec2'
 *
 */

int main(int argc, char **argv) {
    (void)argc;
    (void)argv;

    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::EC2::EC2Client ec2Client(clientConfig);
        Aws::EC2::Model::DescribeInstancesRequest request;
        bool header = false;
        bool done = false;
        while (!done) {
            Aws::EC2::Model::DescribeInstancesOutcome outcome = ec2Client.DescribeInstances(request);
            if (outcome.IsSuccess()) {
                if (!header) {
                    std::cout << std::left <<
                              std::setw(48) << "Name" <<
                              std::setw(20) << "ID" <<
                              std::setw(25) << "Ami" <<
                              std::setw(15) << "Type" <<
                              std::setw(15) << "State" <<
                              std::setw(15) << "Monitoring" << std::endl;
                    header = true;
                }

                const std::vector<Aws::EC2::Model::Reservation> &reservations =
                        outcome.GetResult().GetReservations();

                for (const auto &reservation: reservations) {
                    const std::vector<Aws::EC2::Model::Instance> &instances =
                            reservation.GetInstances();
                    for (const auto &instance: instances) {
                        Aws::String instanceStateString =
                                Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
                                        instance.GetState().GetName());

                        Aws::String typeString =
                                Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
                                        instance.GetInstanceType());

                        Aws::String monitorString =
                                Aws::EC2::Model::MonitoringStateMapper::GetNameForMonitoringState(
                                        instance.GetMonitoring().GetState());
                        Aws::String name = "Unknown";

                        const std::vector<Aws::EC2::Model::Tag> &tags = instance.GetTags();
                        auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
                                                     [](const Aws::EC2::Model::Tag &tag) {
                                                         return tag.GetKey() == "Name";
                                                     });
                        if (nameIter != tags.cend()) {
                            name = nameIter->GetValue();
                        }
                        std::cout <<
                                  std::setw(48) << name <<
                                  std::setw(20) << instance.GetInstanceId() <<
                                  std::setw(25) << instance.GetImageId() <<
                                  std::setw(15) << typeString <<
                                  std::setw(15) << instanceStateString <<
                                  std::setw(15) << monitorString << std::endl;
                    }
                }

                if (!outcome.GetResult().GetNextToken().empty()) {
                    request.SetNextToken(outcome.GetResult().GetNextToken());
                } else {
                    done = true;
                }
            } else {
                std::cerr << "Failed to describe EC2 instances:" <<
                          outcome.GetError().GetMessage() << std::endl;
                result = 1;
                break;
            }
        }
    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_cpp_1_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Allocate an Elastic IP address and associate it with an Amazon Elastic Compute Cloud
//! (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param[out] publicIPAddress: String to return the public IP address.
  \param[out] allocationID: String to return the allocation ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::allocateAndAssociateAddress(const Aws::String &instanceId, Aws::String &publicIPAddress,
                                              Aws::String &allocationID,
                                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::AllocateAddressRequest request;
    request.SetDomain(Aws::EC2::Model::DomainType::vpc);

    const Aws::EC2::Model::AllocateAddressOutcome outcome =
            ec2Client.AllocateAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to allocate Elastic IP address:" <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }
    const Aws::EC2::Model::AllocateAddressResponse &response = outcome.GetResult();
    allocationID = response.GetAllocationId();
    publicIPAddress = response.GetPublicIp();


    return true;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[AllocateAddress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/AllocateAddress)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_cpp_1_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

//! Associate an Elastic IP address with an EC2 instance.
/*!
  \param instanceId: An EC2 instance ID.
  \param allocationId: An Elastic IP allocation ID.
  \param[out] associationID: String to receive the association ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: True if the address was associated with the instance; otherwise, false.
 */
bool AwsDoc::EC2::associateAddress(const Aws::String &instanceId, const Aws::String &allocationId,
                                   Aws::String &associationID,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::AssociateAddressRequest request;
    request.SetInstanceId(instanceId);
    request.SetAllocationId(allocationId);

    Aws::EC2::Model::AssociateAddressOutcome outcome = ec2Client.AssociateAddress(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to associate address " << allocationId <<
                  " with instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully associated address " << allocationId <<
                  " with instance " << instanceId << std::endl;
        associationID = outcome.GetResult().GetAssociationId();
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[AssociateAddress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/AssociateAddress)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_cpp_1_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Authorize ingress to an Amazon Elastic Compute Cloud (Amazon EC2) group.
/*!
  \param groupID: The EC2 group ID.
  \param clientConfiguration: The ClientConfiguration object.
  \return bool: True if the operation was successful, false otherwise.
 */
bool
AwsDoc::EC2::authorizeSecurityGroupIngress(const Aws::String &groupID,
                                           const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest;
    authorizeSecurityGroupIngressRequest.SetGroupId(groupID);
    buildSampleIngressRule(authorizeSecurityGroupIngressRequest);

    Aws::EC2::Model::AuthorizeSecurityGroupIngressOutcome authorizeSecurityGroupIngressOutcome =
            ec2Client.AuthorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    if (authorizeSecurityGroupIngressOutcome.IsSuccess()) {
        std::cout << "Successfully authorized security group ingress." << std::endl;
    } else {
        std::cerr << "Error authorizing security group ingress: "
                  << authorizeSecurityGroupIngressOutcome.GetError().GetMessage() << std::endl;
    }

    return authorizeSecurityGroupIngressOutcome.IsSuccess();
}
```
進入ルールを構築するユーティリティ関数。  

```
//! Build a sample ingress rule.
/*!
  \param authorize_request: An 'AuthorizeSecurityGroupIngressRequest' instance.
  \return void:
 */
void buildSampleIngressRule(
        Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest &authorize_request) {
    Aws::String ingressIPRange = "203.0.113.0/24";  // Configure this for your allowed IP range.
    Aws::EC2::Model::IpRange ip_range;
    ip_range.SetCidrIp(ingressIPRange);

    Aws::EC2::Model::IpPermission permission1;
    permission1.SetIpProtocol("tcp");
    permission1.SetToPort(80);
    permission1.SetFromPort(80);
    permission1.AddIpRanges(ip_range);

    authorize_request.AddIpPermissions(permission1);

    Aws::EC2::Model::IpPermission permission2;
    permission2.SetIpProtocol("tcp");
    permission2.SetToPort(22);
    permission2.SetFromPort(22);
    permission2.AddIpRanges(ip_range);

    authorize_request.AddIpPermissions(permission2);
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/AuthorizeSecurityGroupIngress)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_cpp_1_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Create an Amazon Elastic Compute Cloud (Amazon EC2) instance key pair.
/*!
  \param keyPairName: A name for a key pair.
  \param keyFilePath: File path where the credentials are stored. Ignored if it is an empty string;
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::createKeyPair(const Aws::String &keyPairName, const Aws::String &keyFilePath,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::CreateKeyPairRequest request;
    request.SetKeyName(keyPairName);

    Aws::EC2::Model::CreateKeyPairOutcome outcome = ec2Client.CreateKeyPair(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to create key pair - "  << keyPairName << ". " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully created key pair named " <<
                  keyPairName << std::endl;
        if (!keyFilePath.empty()) {
            std::ofstream keyFile(keyFilePath.c_str());
            keyFile << outcome.GetResult().GetKeyMaterial();
            keyFile.close();
            std::cout << "Keys written to the file " <<
                      keyFilePath << std::endl;
        }

    }

    return outcome.IsSuccess();

}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[CreateKeyPair](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/CreateKeyPair)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_cpp_1_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Create a security group.
/*!
  \param groupName: A security group name.
  \param description: A description.
  \param vpcID: A virtual private cloud (VPC) ID.
  \param[out] groupIDResult: A string to receive the group ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::createSecurityGroup(const Aws::String &groupName,
                                      const Aws::String &description,
                                      const Aws::String &vpcID,
                                      Aws::String &groupIDResult,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::CreateSecurityGroupRequest request;

    request.SetGroupName(groupName);
    request.SetDescription(description);
    request.SetVpcId(vpcID);

    const Aws::EC2::Model::CreateSecurityGroupOutcome outcome =
            ec2Client.CreateSecurityGroup(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to create security group:" <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    std::cout << "Successfully created security group named " << groupName <<
              std::endl;


    groupIDResult = outcome.GetResult().GetGroupId();

    return true;
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[CreateSecurityGroup](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/CreateSecurityGroup)」を参照してください。

### `CreateTags`
<a name="ec2_CreateTags_cpp_1_topic"></a>

次のコード例は、`CreateTags` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Add or overwrite only the specified tags for the specified Amazon Elastic Compute Cloud (Amazon EC2) resource or resources.
/*!
  \param resources: The resources for the tags.
  \param tags: Vector of tags.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::createTags(const Aws::Vector<Aws::String> &resources,
                             const Aws::Vector<Aws::EC2::Model::Tag> &tags,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::CreateTagsRequest createTagsRequest;
    createTagsRequest.SetResources(resources);
    createTagsRequest.SetTags(tags);

    Aws::EC2::Model::CreateTagsOutcome outcome = ec2Client.CreateTags(createTagsRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully created tags for resources" << std::endl;
    } else {
        std::cerr << "Failed to create tags for resources, " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「 [CreateTags](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/CreateTags)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_cpp_1_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an Amazon Elastic Compute Cloud (Amazon EC2) instance key pair.
/*!
  \param keyPairName: A name for a key pair.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::EC2::deleteKeyPair(const Aws::String &keyPairName,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DeleteKeyPairRequest request;

    request.SetKeyName(keyPairName);
    const Aws::EC2::Model::DeleteKeyPairOutcome outcome = ec2Client.DeleteKeyPair(
            request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to delete key pair " << keyPairName <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted key pair named " << keyPairName <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteKeyPair](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DeleteKeyPair)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_cpp_1_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Delete a security group.
/*!
  \param securityGroupID: A security group ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::deleteSecurityGroup(const Aws::String &securityGroupID,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DeleteSecurityGroupRequest request;

    request.SetGroupId(securityGroupID);
    Aws::EC2::Model::DeleteSecurityGroupOutcome outcome = ec2Client.DeleteSecurityGroup(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to delete security group " << securityGroupID <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted security group " << securityGroupID <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteSecurityGroup](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DeleteSecurityGroup)」を参照してください。

### `DescribeAddresses`
<a name="ec2_DescribeAddresses_cpp_1_topic"></a>

次のコード例は、`DescribeAddresses` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Describe all Elastic IP addresses.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeAddresses(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeAddressesRequest request;
    Aws::EC2::Model::DescribeAddressesOutcome outcome = ec2Client.DescribeAddresses(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left << std::setw(20) << "InstanceId" <<
                  std::setw(15) << "Public IP" << std::setw(10) << "Domain" <<
                  std::setw(30) << "Allocation ID" << std::setw(25) <<
                  "NIC ID" << std::endl;

        const Aws::Vector<Aws::EC2::Model::Address> &addresses = outcome.GetResult().GetAddresses();
        for (const auto &address: addresses) {
            Aws::String domainString =
                    Aws::EC2::Model::DomainTypeMapper::GetNameForDomainType(
                            address.GetDomain());

            std::cout << std::left << std::setw(20) <<
                      address.GetInstanceId() << std::setw(15) <<
                      address.GetPublicIp() << std::setw(10) << domainString <<
                      std::setw(30) << address.GetAllocationId() << std::setw(25)
                      << address.GetNetworkInterfaceId() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe Elastic IP addresses:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DescribeAddresses](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeAddresses)」を参照してください。

### `DescribeAvailabilityZones`
<a name="ec2_DescribeAvailabilityZones_cpp_1_topic"></a>

次のコード例は、`DescribeAvailabilityZones` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! DescribeAvailabilityZones
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
int AwsDoc::EC2::describeAvailabilityZones(const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeAvailabilityZonesRequest request;
    Aws::EC2::Model::DescribeAvailabilityZonesOutcome outcome = ec2Client.DescribeAvailabilityZones(request);

    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "ZoneName" <<
                  std::setw(20) << "State" <<
                  std::setw(32) << "Region" << std::endl;

        const auto &zones =
                outcome.GetResult().GetAvailabilityZones();

        for (const auto &zone: zones) {
            Aws::String stateString =
                    Aws::EC2::Model::AvailabilityZoneStateMapper::GetNameForAvailabilityZoneState(
                            zone.GetState());
            std::cout << std::left <<
                      std::setw(32) << zone.GetZoneName() <<
                      std::setw(20) << stateString <<
                      std::setw(32) << zone.GetRegionName() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe availability zones:" <<
                  outcome.GetError().GetMessage() << std::endl;

    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeAvailabilityZones)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_cpp_1_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) instances associated with an account.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeInstances(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeInstancesRequest request;
    bool header = false;
    bool done = false;
    while (!done) {
        Aws::EC2::Model::DescribeInstancesOutcome outcome = ec2Client.DescribeInstances(request);
        if (outcome.IsSuccess()) {
            if (!header) {
                std::cout << std::left <<
                          std::setw(48) << "Name" <<
                          std::setw(20) << "ID" <<
                          std::setw(25) << "Ami" <<
                          std::setw(15) << "Type" <<
                          std::setw(15) << "State" <<
                          std::setw(15) << "Monitoring" << std::endl;
                header = true;
            }

            const std::vector<Aws::EC2::Model::Reservation> &reservations =
                    outcome.GetResult().GetReservations();

            for (const auto &reservation: reservations) {
                const std::vector<Aws::EC2::Model::Instance> &instances =
                        reservation.GetInstances();
                for (const auto &instance: instances) {
                    Aws::String instanceStateString =
                            Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
                                    instance.GetState().GetName());

                    Aws::String typeString =
                            Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
                                    instance.GetInstanceType());

                    Aws::String monitorString =
                            Aws::EC2::Model::MonitoringStateMapper::GetNameForMonitoringState(
                                    instance.GetMonitoring().GetState());
                    Aws::String name = "Unknown";

                    const std::vector<Aws::EC2::Model::Tag> &tags = instance.GetTags();
                    auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
                                                 [](const Aws::EC2::Model::Tag &tag) {
                                                     return tag.GetKey() == "Name";
                                                 });
                    if (nameIter != tags.cend()) {
                        name = nameIter->GetValue();
                    }
                    std::cout <<
                              std::setw(48) << name <<
                              std::setw(20) << instance.GetInstanceId() <<
                              std::setw(25) << instance.GetImageId() <<
                              std::setw(15) << typeString <<
                              std::setw(15) << instanceStateString <<
                              std::setw(15) << monitorString << std::endl;
                }
            }

            if (!outcome.GetResult().GetNextToken().empty()) {
                request.SetNextToken(outcome.GetResult().GetNextToken());
            } else {
                done = true;
            }
        } else {
            std::cerr << "Failed to describe EC2 instances:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    return true;
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[DescribeInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeInstances)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_cpp_1_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) instance key pairs.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeKeyPairs(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeKeyPairsRequest request;

    Aws::EC2::Model::DescribeKeyPairsOutcome outcome = ec2Client.DescribeKeyPairs(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "Name" <<
                  std::setw(64) << "Fingerprint" << std::endl;

        const std::vector<Aws::EC2::Model::KeyPairInfo> &key_pairs =
                outcome.GetResult().GetKeyPairs();
        for (const auto &key_pair: key_pairs) {
            std::cout << std::left <<
                      std::setw(32) << key_pair.GetKeyName() <<
                      std::setw(64) << key_pair.GetKeyFingerprint() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe key pairs:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeKeyPairs](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeKeyPairs)」を参照してください。

### `DescribeRegions`
<a name="ec2_DescribeRegions_cpp_1_topic"></a>

次のコード例は、`DescribeRegions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) Regions.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeRegions(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::DescribeRegionsRequest request;
    Aws::EC2::Model::DescribeRegionsOutcome outcome = ec2Client.DescribeRegions(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "RegionName" <<
                  std::setw(64) << "Endpoint" << std::endl;

        const auto &regions = outcome.GetResult().GetRegions();
        for (const auto &region: regions) {
            std::cout << std::left <<
                      std::setw(32) << region.GetRegionName() <<
                      std::setw(64) << region.GetEndpoint() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe regions:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    std::cout << std::endl;

    return outcome.IsSuccess();

}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[DescribeRegions](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeRegions)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_cpp_1_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Describe all Amazon Elastic Compute Cloud (Amazon EC2) security groups, or a specific group.
/*!
  \param groupID: A group ID, ignored if empty.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::describeSecurityGroups(const Aws::String &groupID,
                                         const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeSecurityGroupsRequest request;

    if (!groupID.empty()) {
        request.AddGroupIds(groupID);
    }

    Aws::String nextToken;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::EC2::Model::DescribeSecurityGroupsOutcome outcome = ec2Client.DescribeSecurityGroups(request);
        if (outcome.IsSuccess()) {
            std::cout << std::left <<
                      std::setw(32) << "Name" <<
                      std::setw(30) << "GroupId" <<
                      std::setw(30) << "VpcId" <<
                      std::setw(64) << "Description" << std::endl;

            const std::vector<Aws::EC2::Model::SecurityGroup> &securityGroups =
                    outcome.GetResult().GetSecurityGroups();

            for (const auto &securityGroup: securityGroups) {
                std::cout << std::left <<
                          std::setw(32) << securityGroup.GetGroupName() <<
                          std::setw(30) << securityGroup.GetGroupId() <<
                          std::setw(30) << securityGroup.GetVpcId() <<
                          std::setw(64) << securityGroup.GetDescription() <<
                          std::endl;
            }
        } else {
            std::cerr << "Failed to describe security groups:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        nextToken = outcome.GetResult().GetNextToken();
    } while (!nextToken.empty());

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

### `MonitorInstances`
<a name="ec2_MonitorInstances_cpp_1_topic"></a>

次のコード例は、`MonitorInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Enable detailed monitoring for an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceId: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::enableMonitoring(const Aws::String &instanceId,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::MonitorInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::MonitorInstancesOutcome dryRunOutcome = ec2Client.MonitorInstances(request);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to enable monitoring on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType()
               != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cerr << "Failed dry run to enable monitoring on instance " <<
                  instanceId << ": " << dryRunOutcome.GetError().GetMessage() <<
                  std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::MonitorInstancesOutcome monitorInstancesOutcome = ec2Client.MonitorInstances(request);
    if (!monitorInstancesOutcome.IsSuccess()) {
        std::cerr << "Failed to enable monitoring on instance " <<
                  instanceId << ": " <<
                  monitorInstancesOutcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully enabled monitoring on instance " <<
                  instanceId << std::endl;
    }

    return monitorInstancesOutcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[MonitorInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/MonitorInstances)」を参照してください。

### `RebootInstances`
<a name="ec2_RebootInstances_cpp_1_topic"></a>

次のコード例は、`RebootInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Reboot an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::rebootInstance(const Aws::String &instanceId,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::RebootInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::RebootInstancesOutcome dry_run_outcome = ec2Client.RebootInstances(request);
    if (dry_run_outcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to reboot on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dry_run_outcome.GetError().GetErrorType()
               != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to reboot instance " << instanceId << ": "
                  << dry_run_outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::RebootInstancesOutcome outcome = ec2Client.RebootInstances(request);
    if (!outcome.IsSuccess()) {
        std::cout << "Failed to reboot instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully rebooted instance " << instanceId <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[RebootInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/RebootInstances)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_cpp_1_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Release an Elastic IP address.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::releaseAddress(const Aws::String &allocationID,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2(clientConfiguration);

    Aws::EC2::Model::ReleaseAddressRequest request;
    request.SetAllocationId(allocationID);

    Aws::EC2::Model::ReleaseAddressOutcome outcome = ec2.ReleaseAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to release Elastic IP address " <<
                  allocationID << ":" << outcome.GetError().GetMessage() <<
                  std::endl;
    } else {
        std::cout << "Successfully released Elastic IP address " <<
                  allocationID << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[ReleaseAddress](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/ReleaseAddress)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_cpp_1_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Launch an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceName: A name for the EC2 instance.
  \param amiId: An Amazon Machine Image (AMI) identifier.
  \param[out] instanceID: String to return the instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::runInstance(const Aws::String &instanceName,
                              const Aws::String &amiId,
                              Aws::String &instanceID,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::RunInstancesRequest runRequest;
    runRequest.SetImageId(amiId);
    runRequest.SetInstanceType(Aws::EC2::Model::InstanceType::t1_micro);
    runRequest.SetMinCount(1);
    runRequest.SetMaxCount(1);

    Aws::EC2::Model::RunInstancesOutcome runOutcome = ec2Client.RunInstances(
            runRequest);
    if (!runOutcome.IsSuccess()) {
        std::cerr << "Failed to launch EC2 instance " << instanceName <<
                  " based on ami " << amiId << ":" <<
                  runOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    const Aws::Vector<Aws::EC2::Model::Instance> &instances = runOutcome.GetResult().GetInstances();
    if (instances.empty()) {
        std::cerr << "Failed to launch EC2 instance " << instanceName <<
                  " based on ami " << amiId << ":" <<
                  runOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    instanceID = instances[0].GetInstanceId();

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[RunInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/RunInstances)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_cpp_1_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Start an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::startInstance(const Aws::String &instanceId,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::StartInstancesRequest startRequest;
    startRequest.AddInstanceIds(instanceId);
    startRequest.SetDryRun(true);

    Aws::EC2::Model::StartInstancesOutcome dryRunOutcome = ec2Client.StartInstances(startRequest);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to start instance. A dry run should trigger an error."
                << std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to start instance " << instanceId << ": "
                  << dryRunOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    startRequest.SetDryRun(false);
    Aws::EC2::Model::StartInstancesOutcome startInstancesOutcome = ec2Client.StartInstances(startRequest);

    if (!startInstancesOutcome.IsSuccess()) {
        std::cout << "Failed to start instance " << instanceId << ": " <<
                  startInstancesOutcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully started instance " << instanceId <<
                  std::endl;
    }

    return startInstancesOutcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[StartInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/StartInstances)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_cpp_1_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Stop an EC2 instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::stopInstance(const Aws::String &instanceId,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::StopInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::StopInstancesOutcome dryRunOutcome = ec2Client.StopInstances(request);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to stop instance. A dry run should trigger an error."
                << std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to stop instance " << instanceId << ": "
                  << dryRunOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::StopInstancesOutcome outcome = ec2Client.StopInstances(request);
    if (!outcome.IsSuccess()) {
        std::cout << "Failed to stop instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully stopped instance " << instanceId <<
                  std::endl;
    }

    return outcome.IsSuccess();
}

void PrintUsage() {
    std::cout << "Usage: run_start_stop_instance <instance_id> <start|stop>" <<
              std::endl;
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[StopInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/StopInstances)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_cpp_1_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Terminate an Amazon Elastic Compute Cloud (Amazon EC2) instance.
/*!
  \param instanceID: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::terminateInstances(const Aws::String &instanceID,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::TerminateInstancesRequest request;
    request.SetInstanceIds({instanceID});

    Aws::EC2::Model::TerminateInstancesOutcome outcome =
            ec2Client.TerminateInstances(request);
    if (outcome.IsSuccess()) {
        std::cout << "Ec2 instance '" << instanceID <<
                  "' was terminated." << std::endl;
    } else {
        std::cerr << "Failed to terminate ec2 instance " << instanceID <<
                  ", " <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[TerminateInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/TerminateInstances)」を参照してください。

### `UnmonitorInstances`
<a name="ec2_UnmonitorInstances_cpp_1_topic"></a>

次のコード例は、`UnmonitorInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
//! Disable monitoring for an EC2 instance.
/*!
  \param instanceId: An EC2 instance ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::EC2::disableMonitoring(const Aws::String &instanceId,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::UnmonitorInstancesRequest unrequest;
    unrequest.AddInstanceIds(instanceId);
    unrequest.SetDryRun(true);

    Aws::EC2::Model::UnmonitorInstancesOutcome dryRunOutcome = ec2Client.UnmonitorInstances(unrequest);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to disable monitoring on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to disable monitoring on instance " <<
                  instanceId << ": " << dryRunOutcome.GetError().GetMessage() <<
                  std::endl;
        return false;
    }

    unrequest.SetDryRun(false);
    Aws::EC2::Model::UnmonitorInstancesOutcome unmonitorInstancesOutcome = ec2Client.UnmonitorInstances(unrequest);
    if (!unmonitorInstancesOutcome.IsSuccess()) {
        std::cout << "Failed to disable monitoring on instance " << instanceId
                  << ": " << unmonitorInstancesOutcome.GetError().GetMessage() <<
                  std::endl;
    } else {
        std::cout << "Successfully disable monitoring on instance " <<
                  instanceId << std::endl;
    }

    return unmonitorInstancesOutcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UnmonitorInstances](https://docs.aws.amazon.com/goto/SdkForCpp/ec2-2016-11-15/UnmonitorInstances)」を参照してください。

# SDK for C\$1\$1 を使用した EventBridge の例
<a name="cpp_1_eventbridge_code_examples"></a>

次のコード例は、EventBridge AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="eventbridge_PutEvents_cpp_1_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutEventsRequest.h>
#include <aws/events/model/PutEventsResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```
イベントを送信します。  

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;

        Aws::CloudWatchEvents::Model::PutEventsRequestEntry event_entry;
        event_entry.SetDetail(MakeDetails(event_key, event_value));
        event_entry.SetDetailType("sampleSubmitted");
        event_entry.AddResources(resource_arn);
        event_entry.SetSource("aws-sdk-cpp-cloudwatch-example");

        Aws::CloudWatchEvents::Model::PutEventsRequest request;
        request.AddEntries(event_entry);

        auto outcome = cwe.PutEvents(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to post CloudWatch event: " <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully posted CloudWatch event" << std::endl;
        }
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[PutEvents](https://docs.aws.amazon.com/goto/SdkForCpp/eventbridge-2015-10-07/PutEvents)」を参照してください。

### `PutRule`
<a name="eventbridge_PutRule_cpp_1_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutRuleRequest.h>
#include <aws/events/model/PutRuleResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```
ルールを作成します。  

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;
        Aws::CloudWatchEvents::Model::PutRuleRequest request;
        request.SetName(rule_name);
        request.SetRoleArn(role_arn);
        request.SetScheduleExpression("rate(5 minutes)");
        request.SetState(Aws::CloudWatchEvents::Model::RuleState::ENABLED);

        auto outcome = cwe.PutRule(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch events rule " <<
                rule_name << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully created CloudWatch events rule " <<
                rule_name << " with resulting Arn " <<
                outcome.GetResult().GetRuleArn() << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[PutRule](https://docs.aws.amazon.com/goto/SdkForCpp/eventbridge-2015-10-07/PutRule)」を参照してください。

### `PutTargets`
<a name="eventbridge_PutTargets_cpp_1_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
必要なファイルを含めます。  

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutTargetsRequest.h>
#include <aws/events/model/PutTargetsResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```
ターゲットとして追加します。  

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;

        Aws::CloudWatchEvents::Model::Target target;
        target.SetArn(lambda_arn);
        target.SetId(target_id);

        Aws::CloudWatchEvents::Model::PutTargetsRequest request;
        request.SetRule(rule_name);
        request.AddTargets(target);

        auto putTargetsOutcome = cwe.PutTargets(request);
        if (!putTargetsOutcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch events target for rule "
                << rule_name << ": " <<
                putTargetsOutcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout <<
                "Successfully created CloudWatch events target for rule "
                << rule_name << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/goto/SdkForCpp/eventbridge-2015-10-07/PutTargets)」を参照してください。

# AWS Glue SDK for C\$1\$1 を使用した例
<a name="cpp_1_glue_code_examples"></a>

次のコード例は、 AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Glueは
<a name="glue_Hello_cpp_1_topic"></a>

次のコード例は、 AWS Glueの使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue/hello_glue#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS glue)

# Set this project's name.
project("hello_glue")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_glue.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1glue.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/glue/GlueClient.h>
#include <aws/glue/model/ListJobsRequest.h>
#include <iostream>

/*
 *  A "Hello Glue" starter application which initializes an AWS Glue client and lists the
 *  AWS Glue job definitions.
 *
 *  main function
 *
 *  Usage: 'hello_glue'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::Glue::GlueClient glueClient(clientConfig);

        std::vector<Aws::String> jobs;

        Aws::String nextToken;  // Used for pagination.
        do {
            Aws::Glue::Model::ListJobsRequest listJobsRequest;
            if (!nextToken.empty()) {
                listJobsRequest.SetNextToken(nextToken);
            }

            Aws::Glue::Model::ListJobsOutcome listRunsOutcome = glueClient.ListJobs(
                    listJobsRequest);

            if (listRunsOutcome.IsSuccess()) {
                const std::vector<Aws::String> &jobNames = listRunsOutcome.GetResult().GetJobNames();
                jobs.insert(jobs.end(), jobNames.begin(), jobNames.end());

                nextToken = listRunsOutcome.GetResult().GetNextToken();
            } else {
                std::cerr << "Error listing jobs. "
                          << listRunsOutcome.GetError().GetMessage()
                          << std::endl;
                result = 1;
                break;
            }
        } while (!nextToken.empty());

        std::cout << "Your account has " << jobs.size() << " jobs."
                  << std::endl;
        for (size_t i = 0; i < jobs.size(); ++i) {
            std::cout << "   " << i + 1 << ". " << jobs[i] << std::endl;
        }
    }
    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListJobs](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/ListJobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
//! Scenario which demonstrates using AWS Glue to add a crawler and run a job.
/*!
 \\sa runGettingStartedWithGlueScenario()
 \param bucketName: An S3 bucket created in the setup.
 \param roleName: An AWS Identity and Access Management (IAM) role created in the setup.
 \param clientConfig: AWS client configuration.
 \return bool: Successful completion.
 */

bool AwsDoc::Glue::runGettingStartedWithGlueScenario(const Aws::String &bucketName,
                                                     const Aws::String &roleName,
                                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::Glue::GlueClient client(clientConfig);

    Aws::String roleArn;
    if (!getRoleArn(roleName, roleArn, clientConfig)) {
        std::cerr << "Error getting role ARN for role." << std::endl;
        return false;
    }

    // 1. Upload the job script to the S3 bucket.
    {
        std::cout << "Uploading the job script '"
                  << AwsDoc::Glue::PYTHON_SCRIPT
                  << "'." << std::endl;

        if (!AwsDoc::Glue::uploadFile(bucketName,
                                      AwsDoc::Glue::PYTHON_SCRIPT_PATH,
                                      AwsDoc::Glue::PYTHON_SCRIPT,
                                      clientConfig)) {
            std::cerr << "Error uploading the job file." << std::endl;
            return false;
        }
    }

    // 2. Create a crawler.
    {
        Aws::Glue::Model::S3Target s3Target;
        s3Target.SetPath("s3://crawler-public-us-east-1/flight/2016/csv");
        Aws::Glue::Model::CrawlerTargets crawlerTargets;
        crawlerTargets.AddS3Targets(s3Target);

        Aws::Glue::Model::CreateCrawlerRequest request;
        request.SetTargets(crawlerTargets);
        request.SetName(CRAWLER_NAME);
        request.SetDatabaseName(CRAWLER_DATABASE_NAME);
        request.SetTablePrefix(CRAWLER_DATABASE_PREFIX);
        request.SetRole(roleArn);

        Aws::Glue::Model::CreateCrawlerOutcome outcome = client.CreateCrawler(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully created the crawler." << std::endl;
        }
        else {
            std::cerr << "Error creating a crawler. " << outcome.GetError().GetMessage()
                      << std::endl;
            deleteAssets("", CRAWLER_DATABASE_NAME, "", bucketName, clientConfig);
            return false;
        }
    }

    // 3. Get a crawler.
    {
        Aws::Glue::Model::GetCrawlerRequest request;
        request.SetName(CRAWLER_NAME);

        Aws::Glue::Model::GetCrawlerOutcome outcome = client.GetCrawler(request);

        if (outcome.IsSuccess()) {
            Aws::Glue::Model::CrawlerState crawlerState = outcome.GetResult().GetCrawler().GetState();
            std::cout << "Retrieved crawler with state " <<
                      Aws::Glue::Model::CrawlerStateMapper::GetNameForCrawlerState(
                              crawlerState)
                      << "." << std::endl;
        }
        else {
            std::cerr << "Error retrieving a crawler.  "
                      << outcome.GetError().GetMessage() << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
    }

    // 4. Start a crawler.
    {
        Aws::Glue::Model::StartCrawlerRequest request;
        request.SetName(CRAWLER_NAME);

        Aws::Glue::Model::StartCrawlerOutcome outcome = client.StartCrawler(request);


        if (outcome.IsSuccess() || (Aws::Glue::GlueErrors::CRAWLER_RUNNING ==
                                    outcome.GetError().GetErrorType())) {
            if (!outcome.IsSuccess()) {
                std::cout << "Crawler was already started." << std::endl;
            }
            else {
                std::cout << "Successfully started crawler." << std::endl;
            }

            std::cout << "This may take a while to run." << std::endl;

            Aws::Glue::Model::CrawlerState crawlerState = Aws::Glue::Model::CrawlerState::NOT_SET;
            int iterations = 0;
            while (Aws::Glue::Model::CrawlerState::READY != crawlerState) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
                ++iterations;
                if ((iterations % 10) == 0) { // Log status every 10 seconds.
                    std::cout << "Crawler status " <<
                              Aws::Glue::Model::CrawlerStateMapper::GetNameForCrawlerState(
                                      crawlerState)
                              << ". After " << iterations
                              << " seconds elapsed."
                              << std::endl;
                }
                Aws::Glue::Model::GetCrawlerRequest getCrawlerRequest;
                getCrawlerRequest.SetName(CRAWLER_NAME);

                Aws::Glue::Model::GetCrawlerOutcome getCrawlerOutcome = client.GetCrawler(
                        getCrawlerRequest);

                if (getCrawlerOutcome.IsSuccess()) {
                    crawlerState = getCrawlerOutcome.GetResult().GetCrawler().GetState();
                }
                else {
                    std::cerr << "Error getting crawler.  "
                              << getCrawlerOutcome.GetError().GetMessage() << std::endl;
                    break;
                }
            }

            if (Aws::Glue::Model::CrawlerState::READY == crawlerState) {
                std::cout << "Crawler finished running after " << iterations
                          << " seconds."
                          << std::endl;
            }
        }
        else {
            std::cerr << "Error starting a crawler.  "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
    }

    // 5. Get a database.
    {
        Aws::Glue::Model::GetDatabaseRequest request;
        request.SetName(CRAWLER_DATABASE_NAME);

        Aws::Glue::Model::GetDatabaseOutcome outcome = client.GetDatabase(request);

        if (outcome.IsSuccess()) {
            const Aws::Glue::Model::Database &database = outcome.GetResult().GetDatabase();

            std::cout << "Successfully retrieve the database\n" <<
                      database.Jsonize().View().WriteReadable() << "'." << std::endl;
        }
        else {
            std::cerr << "Error getting the database.  "
                      << outcome.GetError().GetMessage() << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
    }

    // 6. Get tables.
    Aws::String tableName;
    {
        Aws::Glue::Model::GetTablesRequest request;
        request.SetDatabaseName(CRAWLER_DATABASE_NAME);
        std::vector<Aws::Glue::Model::Table> all_tables;
        Aws::String nextToken; // Used for pagination.
        do {
            Aws::Glue::Model::GetTablesOutcome outcome = client.GetTables(request);

            if (outcome.IsSuccess()) {
                const std::vector<Aws::Glue::Model::Table> &tables = outcome.GetResult().GetTableList();
                all_tables.insert(all_tables.end(), tables.begin(), tables.end());
                nextToken = outcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error getting the tables. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                             clientConfig);
                return false;
            }
        } while (!nextToken.empty());

        std::cout << "The database contains " << all_tables.size()
                  << (all_tables.size() == 1 ?
                      " table." : "tables.") << std::endl;
        std::cout << "Here is a list of the tables in the database.";
        for (size_t index = 0; index < all_tables.size(); ++index) {
            std::cout << "    " << index + 1 << ":  " << all_tables[index].GetName()
                      << std::endl;
        }

        if (!all_tables.empty()) {
            int tableIndex = askQuestionForIntRange(
                    "Enter an index to display the database detail ",
                    1, static_cast<int>(all_tables.size()));
            std::cout << all_tables[tableIndex - 1].Jsonize().View().WriteReadable()
                      << std::endl;

            tableName = all_tables[tableIndex - 1].GetName();
        }
    }

    // 7. Create a job.
    {
        Aws::Glue::Model::CreateJobRequest request;
        request.SetName(JOB_NAME);
        request.SetRole(roleArn);
        request.SetGlueVersion(GLUE_VERSION);

        Aws::Glue::Model::JobCommand command;
        command.SetName(JOB_COMMAND_NAME);
        command.SetPythonVersion(JOB_PYTHON_VERSION);
        command.SetScriptLocation(
                Aws::String("s3://") + bucketName + "/" + PYTHON_SCRIPT);
        request.SetCommand(command);

        Aws::Glue::Model::CreateJobOutcome outcome = client.CreateJob(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully created the job." << std::endl;
        }
        else {
            std::cerr << "Error creating the job. " << outcome.GetError().GetMessage()
                      << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
    }

    // 8. Start a job run.
    {
        Aws::Glue::Model::StartJobRunRequest request;
        request.SetJobName(JOB_NAME);

        Aws::Map<Aws::String, Aws::String> arguments;
        arguments["--input_database"] = CRAWLER_DATABASE_NAME;
        arguments["--input_table"] = tableName;
        arguments["--output_bucket_url"] = Aws::String("s3://") + bucketName + "/";
        request.SetArguments(arguments);

        Aws::Glue::Model::StartJobRunOutcome outcome = client.StartJobRun(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully started the job." << std::endl;

            Aws::String jobRunId = outcome.GetResult().GetJobRunId();

            int iterator = 0;
            bool done = false;
            while (!done) {
                ++iterator;
                std::this_thread::sleep_for(std::chrono::seconds(1));
                Aws::Glue::Model::GetJobRunRequest jobRunRequest;
                jobRunRequest.SetJobName(JOB_NAME);
                jobRunRequest.SetRunId(jobRunId);

                Aws::Glue::Model::GetJobRunOutcome jobRunOutcome = client.GetJobRun(
                        jobRunRequest);

                if (jobRunOutcome.IsSuccess()) {
                    const Aws::Glue::Model::JobRun &jobRun = jobRunOutcome.GetResult().GetJobRun();
                    Aws::Glue::Model::JobRunState jobRunState = jobRun.GetJobRunState();

                    if ((jobRunState == Aws::Glue::Model::JobRunState::STOPPED) ||
                        (jobRunState == Aws::Glue::Model::JobRunState::FAILED) ||
                        (jobRunState == Aws::Glue::Model::JobRunState::TIMEOUT)) {
                        std::cerr << "Error running job. "
                                  << jobRun.GetErrorMessage()
                                  << std::endl;
                        deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME,
                                     bucketName,
                                     clientConfig);
                        return false;
                    }
                    else if (jobRunState ==
                             Aws::Glue::Model::JobRunState::SUCCEEDED) {
                        std::cout << "Job run succeeded after  " << iterator <<
                                  " seconds elapsed." << std::endl;
                        done = true;
                    }
                    else if ((iterator % 10) == 0) { // Log status every 10 seconds.
                        std::cout << "Job run status " <<
                                  Aws::Glue::Model::JobRunStateMapper::GetNameForJobRunState(
                                          jobRunState) <<
                                  ". " << iterator <<
                                  " seconds elapsed." << std::endl;
                    }
                }
                else {
                    std::cerr << "Error retrieving job run state. "
                              << jobRunOutcome.GetError().GetMessage()
                              << std::endl;
                    deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME,
                                 bucketName, clientConfig);
                    return false;
                }
            }
        }
        else {
            std::cerr << "Error starting a job. " << outcome.GetError().GetMessage()
                      << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME, bucketName,
                         clientConfig);
            return false;
        }
    }

    // 9. List the output data stored in the S3 bucket.
    {
        Aws::S3::S3Client s3Client;
        Aws::S3::Model::ListObjectsV2Request request;
        request.SetBucket(bucketName);
        request.SetPrefix(OUTPUT_FILE_PREFIX);

        Aws::String continuationToken; // Used for pagination.
        std::vector<Aws::S3::Model::Object> allObjects;
        do {
            if (!continuationToken.empty()) {
                request.SetContinuationToken(continuationToken);
            }
            Aws::S3::Model::ListObjectsV2Outcome outcome = s3Client.ListObjectsV2(
                    request);

            if (outcome.IsSuccess()) {
                const std::vector<Aws::S3::Model::Object> &objects =
                        outcome.GetResult().GetContents();
                allObjects.insert(allObjects.end(), objects.begin(), objects.end());
                continuationToken = outcome.GetResult().GetNextContinuationToken();
            }
            else {
                std::cerr << "Error listing objects. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                break;
            }
        } while (!continuationToken.empty());

        std::cout << "Data from your job is in " << allObjects.size() <<
                  " files in the S3 bucket, " << bucketName << "." << std::endl;

        for (size_t i = 0; i < allObjects.size(); ++i) {
            std::cout << "    " << i + 1 << ". " << allObjects[i].GetKey()
                      << std::endl;
        }

        int objectIndex = askQuestionForIntRange(
                std::string(
                        "Enter the number of a block to download it and see the first ") +
                std::to_string(LINES_OF_RUN_FILE_TO_DISPLAY) +
                " lines of JSON output in the block: ", 1,
                static_cast<int>(allObjects.size()));

        Aws::String objectKey = allObjects[objectIndex - 1].GetKey();

        std::stringstream stringStream;
        if (getObjectFromBucket(bucketName, objectKey, stringStream,
                                clientConfig)) {
            for (int i = 0; i < LINES_OF_RUN_FILE_TO_DISPLAY && stringStream; ++i) {
                std::string line;
                std::getline(stringStream, line);
                std::cout << "    " << line << std::endl;
            }
        }
        else {
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME, bucketName,
                         clientConfig);
            return false;
        }
    }

    // 10. List all the jobs.
    Aws::String jobName;
    {
        Aws::Glue::Model::ListJobsRequest listJobsRequest;

        Aws::String nextToken;
        std::vector<Aws::String> allJobNames;

        do {
            if (!nextToken.empty()) {
                listJobsRequest.SetNextToken(nextToken);
            }
            Aws::Glue::Model::ListJobsOutcome listRunsOutcome = client.ListJobs(
                    listJobsRequest);

            if (listRunsOutcome.IsSuccess()) {
                const std::vector<Aws::String> &jobNames = listRunsOutcome.GetResult().GetJobNames();
                allJobNames.insert(allJobNames.end(), jobNames.begin(), jobNames.end());
                nextToken = listRunsOutcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error listing jobs. "
                          << listRunsOutcome.GetError().GetMessage()
                          << std::endl;
            }
        } while (!nextToken.empty());
        std::cout << "Your account has " << allJobNames.size() << " jobs."
                  << std::endl;
        for (size_t i = 0; i < allJobNames.size(); ++i) {
            std::cout << "   " << i + 1 << ". " << allJobNames[i] << std::endl;
        }
        int jobIndex = askQuestionForIntRange(
                Aws::String("Enter a number between 1 and ") +
                std::to_string(allJobNames.size()) +
                " to see the list of runs for a job: ",
                1, static_cast<int>(allJobNames.size()));

        jobName = allJobNames[jobIndex - 1];
    }

    // 11. Get the job runs for a job.
    Aws::String jobRunID;
    if (!jobName.empty()) {
        Aws::Glue::Model::GetJobRunsRequest getJobRunsRequest;
        getJobRunsRequest.SetJobName(jobName);

        Aws::String nextToken; // Used for pagination.
        std::vector<Aws::Glue::Model::JobRun> allJobRuns;
        do {
            if (!nextToken.empty()) {
                getJobRunsRequest.SetNextToken(nextToken);
            }
            Aws::Glue::Model::GetJobRunsOutcome jobRunsOutcome = client.GetJobRuns(
                    getJobRunsRequest);

            if (jobRunsOutcome.IsSuccess()) {
                const std::vector<Aws::Glue::Model::JobRun> &jobRuns = jobRunsOutcome.GetResult().GetJobRuns();
                allJobRuns.insert(allJobRuns.end(), jobRuns.begin(), jobRuns.end());

                nextToken = jobRunsOutcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error getting job runs. "
                          << jobRunsOutcome.GetError().GetMessage()
                          << std::endl;
                break;
            }
        } while (!nextToken.empty());

        std::cout << "There are " << allJobRuns.size() << " runs in the job '"
                  <<
                  jobName << "'." << std::endl;

        for (size_t i = 0; i < allJobRuns.size(); ++i) {
            std::cout << "   " << i + 1 << ". " << allJobRuns[i].GetJobName()
                      << std::endl;
        }

        int runIndex = askQuestionForIntRange(
                Aws::String("Enter a number between 1 and ") +
                std::to_string(allJobRuns.size()) +
                " to see details for a run: ",
                1, static_cast<int>(allJobRuns.size()));
        jobRunID = allJobRuns[runIndex - 1].GetId();
    }

    // 12. Get a single job run.
    if (!jobRunID.empty()) {
        Aws::Glue::Model::GetJobRunRequest jobRunRequest;
        jobRunRequest.SetJobName(jobName);
        jobRunRequest.SetRunId(jobRunID);

        Aws::Glue::Model::GetJobRunOutcome jobRunOutcome = client.GetJobRun(
                jobRunRequest);

        if (jobRunOutcome.IsSuccess()) {
            std::cout << "Displaying the job run JSON description." << std::endl;
            std::cout
                    << jobRunOutcome.GetResult().GetJobRun().Jsonize().View().WriteReadable()
                    << std::endl;
        }
        else {
            std::cerr << "Error get a job run. "
                      << jobRunOutcome.GetError().GetMessage()
                      << std::endl;
        }
    }

    return deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME, bucketName,
                        clientConfig);
}

//! Cleanup routine to delete created assets.
/*!
 \\sa deleteAssets()
 \param crawler: Name of an AWS Glue crawler.
 \param database: The name of an AWS Glue database.
 \param job: The name of an AWS Glue job.
 \param bucketName: The name of an S3 bucket.
 \param clientConfig: AWS client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::Glue::deleteAssets(const Aws::String &crawler, const Aws::String &database,
                                const Aws::String &job, const Aws::String &bucketName,
                                const Aws::Client::ClientConfiguration &clientConfig) {
    const Aws::Glue::GlueClient client(clientConfig);
    bool result = true;

    // 13. Delete a job.
    if (!job.empty()) {
        Aws::Glue::Model::DeleteJobRequest request;
        request.SetJobName(job);

        Aws::Glue::Model::DeleteJobOutcome outcome = client.DeleteJob(request);


        if (outcome.IsSuccess()) {
            std::cout << "Successfully deleted the job." << std::endl;
        }
        else {
            std::cerr << "Error deleting the job. " << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
    }

    // 14. Delete a database.
    if (!database.empty()) {
        Aws::Glue::Model::DeleteDatabaseRequest request;
        request.SetName(database);

        Aws::Glue::Model::DeleteDatabaseOutcome outcome = client.DeleteDatabase(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully deleted the database." << std::endl;
        }
        else {
            std::cerr << "Error deleting database. " << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
    }

    // 15. Delete a crawler.
    if (!crawler.empty()) {
        Aws::Glue::Model::DeleteCrawlerRequest request;
        request.SetName(crawler);

        Aws::Glue::Model::DeleteCrawlerOutcome outcome = client.DeleteCrawler(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully deleted the crawler." << std::endl;
        }
        else {
            std::cerr << "Error deleting the crawler. "
                      << outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
    }

    // 16. Delete the job script and run data from the S3 bucket.
    result &= AwsDoc::Glue::deleteAllObjectsInS3Bucket(bucketName,
                                                       clientConfig);
    return result;
}

//! Routine which uploads a file to an S3 bucket.
/*!
 \\sa uploadFile()
 \param bucketName: An S3 bucket created in the setup.
 \param filePath: The path of the file to upload.
 \param fileName The name for the uploaded file.
 \param clientConfig: AWS client configuration.
 \return bool: Successful completion.
 */
bool
AwsDoc::Glue::uploadFile(const Aws::String &bucketName,
                         const Aws::String &filePath,
                         const Aws::String &fileName,
                         const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3_client(clientConfig);

    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucketName);
    request.SetKey(fileName);

    std::shared_ptr<Aws::IOStream> inputData =
            Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
                                          filePath.c_str(),
                                          std::ios_base::in | std::ios_base::binary);

    if (!*inputData) {
        std::cerr << "Error unable to read file " << filePath << std::endl;
        return false;
    }

    request.SetBody(inputData);

    Aws::S3::Model::PutObjectOutcome outcome =
            s3_client.PutObject(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: PutObject: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Added object '" << filePath << "' to bucket '"
                  << bucketName << "'." << std::endl;
    }

    return outcome.IsSuccess();
}

//! Routine which deletes all objects in an S3 bucket.
/*!
 \\sa deleteAllObjectsInS3Bucket()
 \param bucketName: The S3 bucket name.
 \param clientConfig: AWS client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::Glue::deleteAllObjectsInS3Bucket(const Aws::String &bucketName,
                                              const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::ListObjectsV2Request listObjectsRequest;
    listObjectsRequest.SetBucket(bucketName);

    Aws::String continuationToken; // Used for pagination.
    bool result = true;
    do {
        if (!continuationToken.empty()) {
            listObjectsRequest.SetContinuationToken(continuationToken);
        }

        Aws::S3::Model::ListObjectsV2Outcome listObjectsOutcome = client.ListObjectsV2(
                listObjectsRequest);

        if (listObjectsOutcome.IsSuccess()) {
            const std::vector<Aws::S3::Model::Object> &objects = listObjectsOutcome.GetResult().GetContents();
            if (!objects.empty()) {
                Aws::S3::Model::DeleteObjectsRequest deleteObjectsRequest;
                deleteObjectsRequest.SetBucket(bucketName);

                std::vector<Aws::S3::Model::ObjectIdentifier> objectIdentifiers;
                for (const Aws::S3::Model::Object &object: objects) {
                    objectIdentifiers.push_back(
                            Aws::S3::Model::ObjectIdentifier().WithKey(
                                    object.GetKey()));
                }
                Aws::S3::Model::Delete objectsDelete;
                objectsDelete.SetObjects(objectIdentifiers);
                objectsDelete.SetQuiet(true);
                deleteObjectsRequest.SetDelete(objectsDelete);

                Aws::S3::Model::DeleteObjectsOutcome deleteObjectsOutcome =
                        client.DeleteObjects(deleteObjectsRequest);

                if (!deleteObjectsOutcome.IsSuccess()) {
                    std::cerr << "Error deleting objects. " <<
                              deleteObjectsOutcome.GetError().GetMessage() << std::endl;
                    result = false;
                    break;
                }
                else {
                    std::cout << "Successfully deleted the objects." << std::endl;

                }
            }
            else {
                std::cout << "No objects to delete in '" << bucketName << "'."
                          << std::endl;
            }

            continuationToken = listObjectsOutcome.GetResult().GetNextContinuationToken();
        }
        else {
            std::cerr << "Error listing objects. "
                      << listObjectsOutcome.GetError().GetMessage() << std::endl;
            result = false;
            break;
        }
    } while (!continuationToken.empty());

    return result;
}

//! Routine which retrieves an object from an S3 bucket.
/*!
 \\sa getObjectFromBucket()
 \param bucketName: The S3 bucket name.
 \param objectKey: The object's name.
 \param objectStream: A stream to receive the retrieved data.
 \param clientConfig: AWS client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::Glue::getObjectFromBucket(const Aws::String &bucketName,
                                       const Aws::String &objectKey,
                                       std::ostream &objectStream,
                                       const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::GetObjectRequest request;
    request.SetBucket(bucketName);
    request.SetKey(objectKey);

    Aws::S3::Model::GetObjectOutcome outcome = client.GetObject(request);


    if (outcome.IsSuccess()) {
        std::cout << "Successfully retrieved '" << objectKey << "'." << std::endl;
        auto &body = outcome.GetResult().GetBody();
        objectStream << body.rdbuf();
    }
    else {
        std::cerr << "Error retrieving object. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/CreateCrawler)
  + [CreateJob](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/CreateJob)
  + [DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/DeleteCrawler)
  + [DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/DeleteDatabase)
  + [DeleteJob](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/DeleteJob)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/DeleteTable)
  + [GetCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetCrawler)
  + [GetDatabase](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetDatabase)
  + [GetDatabases](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetDatabases)
  + [GetJob](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetJob)
  + [GetJobRun](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetJobRun)
  + [GetJobRuns](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetJobRuns)
  + [GetTables](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetTables)
  + [ListJobs](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/ListJobs)
  + [StartCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/StartCrawler)
  + [StartJobRun](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/StartJobRun)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_cpp_1_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::S3Target s3Target;
        s3Target.SetPath("s3://crawler-public-us-east-1/flight/2016/csv");
        Aws::Glue::Model::CrawlerTargets crawlerTargets;
        crawlerTargets.AddS3Targets(s3Target);

        Aws::Glue::Model::CreateCrawlerRequest request;
        request.SetTargets(crawlerTargets);
        request.SetName(CRAWLER_NAME);
        request.SetDatabaseName(CRAWLER_DATABASE_NAME);
        request.SetTablePrefix(CRAWLER_DATABASE_PREFIX);
        request.SetRole(roleArn);

        Aws::Glue::Model::CreateCrawlerOutcome outcome = client.CreateCrawler(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully created the crawler." << std::endl;
        }
        else {
            std::cerr << "Error creating a crawler. " << outcome.GetError().GetMessage()
                      << std::endl;
            deleteAssets("", CRAWLER_DATABASE_NAME, "", bucketName, clientConfig);
            return false;
        }
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[CreateCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/CreateCrawler)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_cpp_1_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::CreateJobRequest request;
        request.SetName(JOB_NAME);
        request.SetRole(roleArn);
        request.SetGlueVersion(GLUE_VERSION);

        Aws::Glue::Model::JobCommand command;
        command.SetName(JOB_COMMAND_NAME);
        command.SetPythonVersion(JOB_PYTHON_VERSION);
        command.SetScriptLocation(
                Aws::String("s3://") + bucketName + "/" + PYTHON_SCRIPT);
        request.SetCommand(command);

        Aws::Glue::Model::CreateJobOutcome outcome = client.CreateJob(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully created the job." << std::endl;
        }
        else {
            std::cerr << "Error creating the job. " << outcome.GetError().GetMessage()
                      << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[CreateJob](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/CreateJob)」を参照してください。**

### `DeleteCrawler`
<a name="glue_DeleteCrawler_cpp_1_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::DeleteCrawlerRequest request;
        request.SetName(crawler);

        Aws::Glue::Model::DeleteCrawlerOutcome outcome = client.DeleteCrawler(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully deleted the crawler." << std::endl;
        }
        else {
            std::cerr << "Error deleting the crawler. "
                      << outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/DeleteCrawler)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_cpp_1_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::DeleteDatabaseRequest request;
        request.SetName(database);

        Aws::Glue::Model::DeleteDatabaseOutcome outcome = client.DeleteDatabase(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully deleted the database." << std::endl;
        }
        else {
            std::cerr << "Error deleting database. " << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/DeleteDatabase)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_cpp_1_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::DeleteJobRequest request;
        request.SetJobName(job);

        Aws::Glue::Model::DeleteJobOutcome outcome = client.DeleteJob(request);


        if (outcome.IsSuccess()) {
            std::cout << "Successfully deleted the job." << std::endl;
        }
        else {
            std::cerr << "Error deleting the job. " << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteJob](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/DeleteJob)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_cpp_1_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::GetCrawlerRequest request;
        request.SetName(CRAWLER_NAME);

        Aws::Glue::Model::GetCrawlerOutcome outcome = client.GetCrawler(request);

        if (outcome.IsSuccess()) {
            Aws::Glue::Model::CrawlerState crawlerState = outcome.GetResult().GetCrawler().GetState();
            std::cout << "Retrieved crawler with state " <<
                      Aws::Glue::Model::CrawlerStateMapper::GetNameForCrawlerState(
                              crawlerState)
                      << "." << std::endl;
        }
        else {
            std::cerr << "Error retrieving a crawler.  "
                      << outcome.GetError().GetMessage() << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetCrawler)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_cpp_1_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::GetDatabaseRequest request;
        request.SetName(CRAWLER_DATABASE_NAME);

        Aws::Glue::Model::GetDatabaseOutcome outcome = client.GetDatabase(request);

        if (outcome.IsSuccess()) {
            const Aws::Glue::Model::Database &database = outcome.GetResult().GetDatabase();

            std::cout << "Successfully retrieve the database\n" <<
                      database.Jsonize().View().WriteReadable() << "'." << std::endl;
        }
        else {
            std::cerr << "Error getting the database.  "
                      << outcome.GetError().GetMessage() << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetDatabase](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetDatabase)」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_cpp_1_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::GetJobRunRequest jobRunRequest;
        jobRunRequest.SetJobName(jobName);
        jobRunRequest.SetRunId(jobRunID);

        Aws::Glue::Model::GetJobRunOutcome jobRunOutcome = client.GetJobRun(
                jobRunRequest);

        if (jobRunOutcome.IsSuccess()) {
            std::cout << "Displaying the job run JSON description." << std::endl;
            std::cout
                    << jobRunOutcome.GetResult().GetJobRun().Jsonize().View().WriteReadable()
                    << std::endl;
        }
        else {
            std::cerr << "Error get a job run. "
                      << jobRunOutcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetJobRun](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetJobRun)」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_cpp_1_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::GetJobRunsRequest getJobRunsRequest;
        getJobRunsRequest.SetJobName(jobName);

        Aws::String nextToken; // Used for pagination.
        std::vector<Aws::Glue::Model::JobRun> allJobRuns;
        do {
            if (!nextToken.empty()) {
                getJobRunsRequest.SetNextToken(nextToken);
            }
            Aws::Glue::Model::GetJobRunsOutcome jobRunsOutcome = client.GetJobRuns(
                    getJobRunsRequest);

            if (jobRunsOutcome.IsSuccess()) {
                const std::vector<Aws::Glue::Model::JobRun> &jobRuns = jobRunsOutcome.GetResult().GetJobRuns();
                allJobRuns.insert(allJobRuns.end(), jobRuns.begin(), jobRuns.end());

                nextToken = jobRunsOutcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error getting job runs. "
                          << jobRunsOutcome.GetError().GetMessage()
                          << std::endl;
                break;
            }
        } while (!nextToken.empty());
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetJobRuns](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetJobRuns)」を参照してください。

### `GetTables`
<a name="glue_GetTables_cpp_1_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::GetTablesRequest request;
        request.SetDatabaseName(CRAWLER_DATABASE_NAME);
        std::vector<Aws::Glue::Model::Table> all_tables;
        Aws::String nextToken; // Used for pagination.
        do {
            Aws::Glue::Model::GetTablesOutcome outcome = client.GetTables(request);

            if (outcome.IsSuccess()) {
                const std::vector<Aws::Glue::Model::Table> &tables = outcome.GetResult().GetTableList();
                all_tables.insert(all_tables.end(), tables.begin(), tables.end());
                nextToken = outcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error getting the tables. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                             clientConfig);
                return false;
            }
        } while (!nextToken.empty());

        std::cout << "The database contains " << all_tables.size()
                  << (all_tables.size() == 1 ?
                      " table." : "tables.") << std::endl;
        std::cout << "Here is a list of the tables in the database.";
        for (size_t index = 0; index < all_tables.size(); ++index) {
            std::cout << "    " << index + 1 << ":  " << all_tables[index].GetName()
                      << std::endl;
        }

        if (!all_tables.empty()) {
            int tableIndex = askQuestionForIntRange(
                    "Enter an index to display the database detail ",
                    1, static_cast<int>(all_tables.size()));
            std::cout << all_tables[tableIndex - 1].Jsonize().View().WriteReadable()
                      << std::endl;

            tableName = all_tables[tableIndex - 1].GetName();
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetTables](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/GetTables)」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_cpp_1_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::ListJobsRequest listJobsRequest;

        Aws::String nextToken;
        std::vector<Aws::String> allJobNames;

        do {
            if (!nextToken.empty()) {
                listJobsRequest.SetNextToken(nextToken);
            }
            Aws::Glue::Model::ListJobsOutcome listRunsOutcome = client.ListJobs(
                    listJobsRequest);

            if (listRunsOutcome.IsSuccess()) {
                const std::vector<Aws::String> &jobNames = listRunsOutcome.GetResult().GetJobNames();
                allJobNames.insert(allJobNames.end(), jobNames.begin(), jobNames.end());
                nextToken = listRunsOutcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "Error listing jobs. "
                          << listRunsOutcome.GetError().GetMessage()
                          << std::endl;
            }
        } while (!nextToken.empty());
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/ListJobs)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_cpp_1_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::StartCrawlerRequest request;
        request.SetName(CRAWLER_NAME);

        Aws::Glue::Model::StartCrawlerOutcome outcome = client.StartCrawler(request);


        if (outcome.IsSuccess() || (Aws::Glue::GlueErrors::CRAWLER_RUNNING ==
                                    outcome.GetError().GetErrorType())) {
            if (!outcome.IsSuccess()) {
                std::cout << "Crawler was already started." << std::endl;
            }
            else {
                std::cout << "Successfully started crawler." << std::endl;
            }

            std::cout << "This may take a while to run." << std::endl;

            Aws::Glue::Model::CrawlerState crawlerState = Aws::Glue::Model::CrawlerState::NOT_SET;
            int iterations = 0;
            while (Aws::Glue::Model::CrawlerState::READY != crawlerState) {
                std::this_thread::sleep_for(std::chrono::seconds(1));
                ++iterations;
                if ((iterations % 10) == 0) { // Log status every 10 seconds.
                    std::cout << "Crawler status " <<
                              Aws::Glue::Model::CrawlerStateMapper::GetNameForCrawlerState(
                                      crawlerState)
                              << ". After " << iterations
                              << " seconds elapsed."
                              << std::endl;
                }
                Aws::Glue::Model::GetCrawlerRequest getCrawlerRequest;
                getCrawlerRequest.SetName(CRAWLER_NAME);

                Aws::Glue::Model::GetCrawlerOutcome getCrawlerOutcome = client.GetCrawler(
                        getCrawlerRequest);

                if (getCrawlerOutcome.IsSuccess()) {
                    crawlerState = getCrawlerOutcome.GetResult().GetCrawler().GetState();
                }
                else {
                    std::cerr << "Error getting crawler.  "
                              << getCrawlerOutcome.GetError().GetMessage() << std::endl;
                    break;
                }
            }

            if (Aws::Glue::Model::CrawlerState::READY == crawlerState) {
                std::cout << "Crawler finished running after " << iterations
                          << " seconds."
                          << std::endl;
            }
        }
        else {
            std::cerr << "Error starting a crawler.  "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, "", bucketName,
                         clientConfig);
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[StartCrawler](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/StartCrawler)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_cpp_1_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Glue::GlueClient client(clientConfig);

        Aws::Glue::Model::StartJobRunRequest request;
        request.SetJobName(JOB_NAME);

        Aws::Map<Aws::String, Aws::String> arguments;
        arguments["--input_database"] = CRAWLER_DATABASE_NAME;
        arguments["--input_table"] = tableName;
        arguments["--output_bucket_url"] = Aws::String("s3://") + bucketName + "/";
        request.SetArguments(arguments);

        Aws::Glue::Model::StartJobRunOutcome outcome = client.StartJobRun(request);

        if (outcome.IsSuccess()) {
            std::cout << "Successfully started the job." << std::endl;

            Aws::String jobRunId = outcome.GetResult().GetJobRunId();

            int iterator = 0;
            bool done = false;
            while (!done) {
                ++iterator;
                std::this_thread::sleep_for(std::chrono::seconds(1));
                Aws::Glue::Model::GetJobRunRequest jobRunRequest;
                jobRunRequest.SetJobName(JOB_NAME);
                jobRunRequest.SetRunId(jobRunId);

                Aws::Glue::Model::GetJobRunOutcome jobRunOutcome = client.GetJobRun(
                        jobRunRequest);

                if (jobRunOutcome.IsSuccess()) {
                    const Aws::Glue::Model::JobRun &jobRun = jobRunOutcome.GetResult().GetJobRun();
                    Aws::Glue::Model::JobRunState jobRunState = jobRun.GetJobRunState();

                    if ((jobRunState == Aws::Glue::Model::JobRunState::STOPPED) ||
                        (jobRunState == Aws::Glue::Model::JobRunState::FAILED) ||
                        (jobRunState == Aws::Glue::Model::JobRunState::TIMEOUT)) {
                        std::cerr << "Error running job. "
                                  << jobRun.GetErrorMessage()
                                  << std::endl;
                        deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME,
                                     bucketName,
                                     clientConfig);
                        return false;
                    }
                    else if (jobRunState ==
                             Aws::Glue::Model::JobRunState::SUCCEEDED) {
                        std::cout << "Job run succeeded after  " << iterator <<
                                  " seconds elapsed." << std::endl;
                        done = true;
                    }
                    else if ((iterator % 10) == 0) { // Log status every 10 seconds.
                        std::cout << "Job run status " <<
                                  Aws::Glue::Model::JobRunStateMapper::GetNameForJobRunState(
                                          jobRunState) <<
                                  ". " << iterator <<
                                  " seconds elapsed." << std::endl;
                    }
                }
                else {
                    std::cerr << "Error retrieving job run state. "
                              << jobRunOutcome.GetError().GetMessage()
                              << std::endl;
                    deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME,
                                 bucketName, clientConfig);
                    return false;
                }
            }
        }
        else {
            std::cerr << "Error starting a job. " << outcome.GetError().GetMessage()
                      << std::endl;
            deleteAssets(CRAWLER_NAME, CRAWLER_DATABASE_NAME, JOB_NAME, bucketName,
                         clientConfig);
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[StartJobRun](https://docs.aws.amazon.com/goto/SdkForCpp/glue-2017-03-31/StartJobRun)」を参照してください。

# SDK for C\$1\$1 を使用した HealthImaging の例
<a name="cpp_1_medical-imaging_code_examples"></a>

次のコード例は、HealthImaging AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello HealthImaging
<a name="medical-imaging_Hello_cpp_1_topic"></a>

次のコード例は、HealthImaging の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS medical-imaging)

# Set this project's name.
project("hello_health-imaging")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
    # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

    # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this
    # and set the proper subdirectory to the executable location.

    AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_health_imaging.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1health\$1imaging.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/medical-imaging/MedicalImagingClient.h>
#include <aws/medical-imaging/model/ListDatastoresRequest.h>

#include <iostream>

/*
 *  A "Hello HealthImaging" starter application which initializes an AWS HealthImaging (HealthImaging) client
 *  and lists the HealthImaging data stores in the current account.
 *
 *  main function
 *
 *  Usage: 'hello_health-imaging'
 *
 */
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/platform/Environment.h>

int main(int argc, char **argv) {
    (void) argc;
    (void) argv;
    Aws::SDKOptions options;
    //   Optional: change the log level for debugging.
    //   options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;

    Aws::InitAPI(options); // Should only be called once.
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::MedicalImaging::MedicalImagingClient medicalImagingClient(clientConfig);
        Aws::MedicalImaging::Model::ListDatastoresRequest listDatastoresRequest;

        Aws::Vector<Aws::MedicalImaging::Model::DatastoreSummary> allDataStoreSummaries;
        Aws::String nextToken; // Used for paginated results.
        do {
            if (!nextToken.empty()) {
                listDatastoresRequest.SetNextToken(nextToken);
            }
            Aws::MedicalImaging::Model::ListDatastoresOutcome listDatastoresOutcome =
                    medicalImagingClient.ListDatastores(listDatastoresRequest);
            if (listDatastoresOutcome.IsSuccess()) {
                const Aws::Vector<Aws::MedicalImaging::Model::DatastoreSummary> &dataStoreSummaries =
                        listDatastoresOutcome.GetResult().GetDatastoreSummaries();
                allDataStoreSummaries.insert(allDataStoreSummaries.cend(),
                                             dataStoreSummaries.cbegin(),
                                             dataStoreSummaries.cend());
                nextToken = listDatastoresOutcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "ListDatastores error: "
                          << listDatastoresOutcome.GetError().GetMessage() << std::endl;
                break;
            }
        } while (!nextToken.empty());

        std::cout << allDataStoreSummaries.size() << " HealthImaging data "
                  << ((allDataStoreSummaries.size() == 1) ?
                      "store was retrieved." : "stores were retrieved.") << std::endl;

        for (auto const &dataStoreSummary: allDataStoreSummaries) {
            std::cout << "  Datastore: " << dataStoreSummary.GetDatastoreName()
                      << std::endl;
            std::cout << "  Datastore ID: " << dataStoreSummary.GetDatastoreId()
                      << std::endl;
        }
    }

    Aws::ShutdownAPI(options); // Should only be called once.
    return 0;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListDatastores](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/ListDatastores)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/hello_health_imaging#code-examples)での設定と実行の方法を確認してください。

## アクション
<a name="actions"></a>

### `DeleteImageSet`
<a name="medical-imaging_DeleteImageSet_cpp_1_topic"></a>

次のコード例は、`DeleteImageSet` を使用する方法を示しています。

**SDK for C\$1\$1**  

```
//! Routine which deletes an AWS HealthImaging image set.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param imageSetID: The image set ID.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
  */
bool AwsDoc::Medical_Imaging::deleteImageSet(
        const Aws::String &dataStoreID, const Aws::String &imageSetID,
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::MedicalImagingClient client(clientConfig);
    Aws::MedicalImaging::Model::DeleteImageSetRequest request;
    request.SetDatastoreId(dataStoreID);
    request.SetImageSetId(imageSetID);
    Aws::MedicalImaging::Model::DeleteImageSetOutcome outcome = client.DeleteImageSet(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted image set " << imageSetID
                  << " from data store " << dataStoreID << std::endl;
    }
    else {
        std::cerr << "Error deleting image set " << imageSetID << " from data store "
                  << dataStoreID << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteImageSet](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/DeleteImageSet)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/#code-examples)での設定と実行の方法を確認してください。

### `GetDICOMImportJob`
<a name="medical-imaging_GetDICOMImportJob_cpp_1_topic"></a>

次のコード例は、`GetDICOMImportJob` を使用する方法を示しています。

**SDK for C\$1\$1**  

```
//! Routine which gets a HealthImaging DICOM import job's properties.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param importJobID: The DICOM import job ID
  \param clientConfig: Aws client configuration.
  \return GetDICOMImportJobOutcome: The import job outcome.
*/
Aws::MedicalImaging::Model::GetDICOMImportJobOutcome
AwsDoc::Medical_Imaging::getDICOMImportJob(const Aws::String &dataStoreID,
                                           const Aws::String &importJobID,
                                           const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::MedicalImagingClient client(clientConfig);
    Aws::MedicalImaging::Model::GetDICOMImportJobRequest request;
    request.SetDatastoreId(dataStoreID);
    request.SetJobId(importJobID);
    Aws::MedicalImaging::Model::GetDICOMImportJobOutcome outcome = client.GetDICOMImportJob(
            request);
    if (!outcome.IsSuccess()) {
        std::cerr << "GetDICOMImportJob error: "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetDICOMImportJob](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/GetDICOMImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/#code-examples)での設定と実行の方法を確認してください。

### `GetImageFrame`
<a name="medical-imaging_GetImageFrame_cpp_1_topic"></a>

次のコード例は、`GetImageFrame` を使用する方法を示しています。

**SDK for C\$1\$1**  

```
//! Routine which downloads an AWS HealthImaging image frame.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param imageSetID: The image set ID.
  \param frameID: The image frame ID.
  \param jphFile: File to store the downloaded frame.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::Medical_Imaging::getImageFrame(const Aws::String &dataStoreID,
                                            const Aws::String &imageSetID,
                                            const Aws::String &frameID,
                                            const Aws::String &jphFile,
                                            const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::MedicalImagingClient client(clientConfig);

    Aws::MedicalImaging::Model::GetImageFrameRequest request;
    request.SetDatastoreId(dataStoreID);
    request.SetImageSetId(imageSetID);

    Aws::MedicalImaging::Model::ImageFrameInformation imageFrameInformation;
    imageFrameInformation.SetImageFrameId(frameID);
    request.SetImageFrameInformation(imageFrameInformation);

    Aws::MedicalImaging::Model::GetImageFrameOutcome outcome = client.GetImageFrame(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully retrieved image frame." << std::endl;
        auto &buffer = outcome.GetResult().GetImageFrameBlob();

        std::ofstream outfile(jphFile, std::ios::binary);
        outfile << buffer.rdbuf();
    }
    else {
        std::cout << "Error retrieving image frame." << outcome.GetError().GetMessage()
                  << std::endl;

    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetImageFrame](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/GetImageFrame)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/#code-examples)での設定と実行の方法を確認してください。

### `GetImageSetMetadata`
<a name="medical-imaging_GetImageSetMetadata_cpp_1_topic"></a>

次のコード例は、`GetImageSetMetadata` を使用する方法を示しています。

**SDK for C\$1\$1**  
イメージセットのメタデータを取得するためのユーティリティ関数。  

```
//! Routine which gets a HealthImaging image set's metadata.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param imageSetID: The HealthImaging image set ID.
  \param versionID: The HealthImaging image set version ID, ignored if empty.
  \param outputFilePath: The path where the metadata will be stored as gzipped json.
  \param clientConfig: Aws client configuration.
  \\return bool: Function succeeded.
*/
bool AwsDoc::Medical_Imaging::getImageSetMetadata(const Aws::String &dataStoreID,
                                                  const Aws::String &imageSetID,
                                                  const Aws::String &versionID,
                                                  const Aws::String &outputFilePath,
                                                  const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::Model::GetImageSetMetadataRequest request;
    request.SetDatastoreId(dataStoreID);
    request.SetImageSetId(imageSetID);
    if (!versionID.empty()) {
        request.SetVersionId(versionID);
    }
    Aws::MedicalImaging::MedicalImagingClient client(clientConfig);
    Aws::MedicalImaging::Model::GetImageSetMetadataOutcome outcome = client.GetImageSetMetadata(
            request);
    if (outcome.IsSuccess()) {
        std::ofstream file(outputFilePath, std::ios::binary);
        auto &metadata = outcome.GetResult().GetImageSetMetadataBlob();
        file << metadata.rdbuf();
    }
    else {
        std::cerr << "Failed to get image set metadata: "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
イメージセットのメタデータをバージョンなしで取得します。  

```
        if (AwsDoc::Medical_Imaging::getImageSetMetadata(dataStoreID, imageSetID, "", outputFilePath, clientConfig))
        {
            std::cout << "Successfully retrieved image set metadata." << std::endl;
            std::cout << "Metadata stored in: " << outputFilePath << std::endl;
        }
```
イメージセットのメタデータをバージョン付きで取得します。  

```
        if (AwsDoc::Medical_Imaging::getImageSetMetadata(dataStoreID, imageSetID, versionID, outputFilePath, clientConfig))
        {
            std::cout << "Successfully retrieved image set metadata." << std::endl;
            std::cout << "Metadata stored in: " << outputFilePath << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetImageSetMetadata](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/GetImageSetMetadata)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/#code-examples)での設定と実行の方法を確認してください。

### `SearchImageSets`
<a name="medical-imaging_SearchImageSets_cpp_1_topic"></a>

次のコード例は、`SearchImageSets` を使用する方法を示しています。

**SDK for C\$1\$1**  
画像セットを検索するためのユーティリティ関数。  

```
//! Routine which searches for image sets based on defined input attributes.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param searchCriteria: A search criteria instance.
  \param imageSetResults: Vector to receive the image set IDs.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
  */
bool AwsDoc::Medical_Imaging::searchImageSets(const Aws::String &dataStoreID,
                                              const Aws::MedicalImaging::Model::SearchCriteria &searchCriteria,
                                              Aws::Vector<Aws::String> &imageSetResults,
                                              const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::MedicalImagingClient client(clientConfig);
    Aws::MedicalImaging::Model::SearchImageSetsRequest request;
    request.SetDatastoreId(dataStoreID);
    request.SetSearchCriteria(searchCriteria);

    Aws::String nextToken; // Used for paginated results.
    bool result = true;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::MedicalImaging::Model::SearchImageSetsOutcome outcome = client.SearchImageSets(
                request);
        if (outcome.IsSuccess()) {
            for (auto &imageSetMetadataSummary: outcome.GetResult().GetImageSetsMetadataSummaries()) {
                imageSetResults.push_back(imageSetMetadataSummary.GetImageSetId());
            }

            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
    } while (!nextToken.empty());

    return result;
}
```
ユースケース \$11: EQUAL 演算子。  

```
        Aws::Vector<Aws::String> imageIDsForPatientID;
        Aws::MedicalImaging::Model::SearchCriteria searchCriteriaEqualsPatientID;
        Aws::Vector<Aws::MedicalImaging::Model::SearchFilter> patientIDSearchFilters = {
                Aws::MedicalImaging::Model::SearchFilter().WithOperator(Aws::MedicalImaging::Model::Operator::EQUAL)
                .WithValues({Aws::MedicalImaging::Model::SearchByAttributeValue().WithDICOMPatientId(patientID)})
        };

        searchCriteriaEqualsPatientID.SetFilters(patientIDSearchFilters);
        bool result = AwsDoc::Medical_Imaging::searchImageSets(dataStoreID,
                                                               searchCriteriaEqualsPatientID,
                                                               imageIDsForPatientID,
                                                               clientConfig);
        if (result) {
            std::cout << imageIDsForPatientID.size() << " image sets found for the patient with ID '"
            <<  patientID << "'." << std::endl;
            for (auto &imageSetResult : imageIDsForPatientID) {
                std::cout << "  Image set with ID '" << imageSetResult << std::endl;
            }
        }
```
ユースケース \$12: DICOMStudyDate と DICOMStudyTime を使用する BETWEEN 演算子。  

```
         Aws::MedicalImaging::Model::SearchByAttributeValue useCase2StartDate;
        useCase2StartDate.SetDICOMStudyDateAndTime(Aws::MedicalImaging::Model::DICOMStudyDateAndTime()
        .WithDICOMStudyDate("19990101")
        .WithDICOMStudyTime("000000.000"));

        Aws::MedicalImaging::Model::SearchByAttributeValue useCase2EndDate;
        useCase2EndDate.SetDICOMStudyDateAndTime(Aws::MedicalImaging::Model::DICOMStudyDateAndTime()
        .WithDICOMStudyDate(Aws::Utils::DateTime(std::chrono::system_clock::now()).ToLocalTimeString("%Y%m%d"))
        .WithDICOMStudyTime("000000.000"));

        Aws::MedicalImaging::Model::SearchFilter useCase2SearchFilter;
        useCase2SearchFilter.SetValues({useCase2StartDate, useCase2EndDate});
        useCase2SearchFilter.SetOperator(Aws::MedicalImaging::Model::Operator::BETWEEN);

        Aws::MedicalImaging::Model::SearchCriteria useCase2SearchCriteria;
        useCase2SearchCriteria.SetFilters({useCase2SearchFilter});

        Aws::Vector<Aws::String> usesCase2Results;
        result = AwsDoc::Medical_Imaging::searchImageSets(dataStoreID,
                                                          useCase2SearchCriteria,
                                                          usesCase2Results,
                                                          clientConfig);
        if (result) {
            std::cout << usesCase2Results.size() << " image sets found for between 1999/01/01 and present."
                      <<  std::endl;
            for (auto &imageSetResult : usesCase2Results) {
                std::cout << "  Image set with ID '" << imageSetResult << std::endl;
            }
        }
```
ユースケース \$13: createdAt を使用する BETWEEN 演算子。タイムスタディは以前に永続化されています。  

```
        Aws::MedicalImaging::Model::SearchByAttributeValue useCase3StartDate;
        useCase3StartDate.SetCreatedAt(Aws::Utils::DateTime("20231130T000000000Z",Aws::Utils::DateFormat::ISO_8601_BASIC));

        Aws::MedicalImaging::Model::SearchByAttributeValue useCase3EndDate;
        useCase3EndDate.SetCreatedAt(Aws::Utils::DateTime(std::chrono::system_clock::now()));

        Aws::MedicalImaging::Model::SearchFilter useCase3SearchFilter;
        useCase3SearchFilter.SetValues({useCase3StartDate, useCase3EndDate});
        useCase3SearchFilter.SetOperator(Aws::MedicalImaging::Model::Operator::BETWEEN);

        Aws::MedicalImaging::Model::SearchCriteria useCase3SearchCriteria;
        useCase3SearchCriteria.SetFilters({useCase3SearchFilter});

        Aws::Vector<Aws::String> usesCase3Results;
        result = AwsDoc::Medical_Imaging::searchImageSets(dataStoreID,
                                                          useCase3SearchCriteria,
                                                          usesCase3Results,
                                                          clientConfig);
        if (result) {
            std::cout << usesCase3Results.size() << " image sets found for created between 2023/11/30 and present."
                      <<  std::endl;
            for (auto &imageSetResult : usesCase3Results) {
                std::cout << "  Image set with ID '" << imageSetResult << std::endl;
            }
        }
```
ユースケース 4: DICOMSeriesInstanceUID で EQUAL 演算子を使用し、updatedAt で BETWEEN 演算子を使用して、updatedAt フィールドで ASC 順序にレスポンスをソートします。  

```
        Aws::MedicalImaging::Model::SearchByAttributeValue useCase4StartDate;
        useCase4StartDate.SetUpdatedAt(Aws::Utils::DateTime("20231130T000000000Z",Aws::Utils::DateFormat::ISO_8601_BASIC));

        Aws::MedicalImaging::Model::SearchByAttributeValue useCase4EndDate;
        useCase4EndDate.SetUpdatedAt(Aws::Utils::DateTime(std::chrono::system_clock::now()));

        Aws::MedicalImaging::Model::SearchFilter useCase4SearchFilterBetween;
        useCase4SearchFilterBetween.SetValues({useCase4StartDate, useCase4EndDate});
        useCase4SearchFilterBetween.SetOperator(Aws::MedicalImaging::Model::Operator::BETWEEN);

        Aws::MedicalImaging::Model::SearchByAttributeValue seriesInstanceUID;
        seriesInstanceUID.SetDICOMSeriesInstanceUID(dicomSeriesInstanceUID);

        Aws::MedicalImaging::Model::SearchFilter useCase4SearchFilterEqual;
        useCase4SearchFilterEqual.SetValues({seriesInstanceUID});
        useCase4SearchFilterEqual.SetOperator(Aws::MedicalImaging::Model::Operator::EQUAL);

        Aws::MedicalImaging::Model::SearchCriteria useCase4SearchCriteria;
        useCase4SearchCriteria.SetFilters({useCase4SearchFilterBetween, useCase4SearchFilterEqual});

        Aws::MedicalImaging::Model::Sort useCase4Sort;
        useCase4Sort.SetSortField(Aws::MedicalImaging::Model::SortField::updatedAt);
        useCase4Sort.SetSortOrder(Aws::MedicalImaging::Model::SortOrder::ASC);

        useCase4SearchCriteria.SetSort(useCase4Sort);

        Aws::Vector<Aws::String> usesCase4Results;
        result = AwsDoc::Medical_Imaging::searchImageSets(dataStoreID,
                                                          useCase4SearchCriteria,
                                                          usesCase4Results,
                                                          clientConfig);
        if (result) {
            std::cout << usesCase4Results.size() << " image sets found for EQUAL operator "
            << "on DICOMSeriesInstanceUID and BETWEEN on updatedAt and sort response\n"
            <<  "in ASC order on updatedAt field." <<  std::endl;
            for (auto &imageSetResult : usesCase4Results) {
                std::cout << "  Image set with ID '" << imageSetResult << std::endl;
            }
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[SearchImageSets](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/SearchImageSets)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/#code-examples)での設定と実行の方法を確認してください。

### `StartDICOMImportJob`
<a name="medical-imaging_StartDICOMImportJob_cpp_1_topic"></a>

次のコード例は、`StartDICOMImportJob` を使用する方法を示しています。

**SDK for C\$1\$1**  

```
//! Routine which starts a HealthImaging import job.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param inputBucketName: The name of the Amazon S3 bucket containing the DICOM files.
  \param inputDirectory: The directory in the S3 bucket containing the DICOM files.
  \param outputBucketName: The name of the S3 bucket for the output.
  \param outputDirectory: The directory in the S3 bucket to store the output.
  \param roleArn: The ARN of the IAM role with permissions for the import.
  \param importJobId: A string to receive the import job ID.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
  */
bool AwsDoc::Medical_Imaging::startDICOMImportJob(
        const Aws::String &dataStoreID, const Aws::String &inputBucketName,
        const Aws::String &inputDirectory, const Aws::String &outputBucketName,
        const Aws::String &outputDirectory, const Aws::String &roleArn,
        Aws::String &importJobId,
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::MedicalImagingClient medicalImagingClient(clientConfig);
    Aws::String inputURI = "s3://" + inputBucketName + "/" + inputDirectory + "/";
    Aws::String outputURI = "s3://" + outputBucketName + "/" + outputDirectory + "/";
    Aws::MedicalImaging::Model::StartDICOMImportJobRequest startDICOMImportJobRequest;
    startDICOMImportJobRequest.SetDatastoreId(dataStoreID);
    startDICOMImportJobRequest.SetDataAccessRoleArn(roleArn);
    startDICOMImportJobRequest.SetInputS3Uri(inputURI);
    startDICOMImportJobRequest.SetOutputS3Uri(outputURI);

    Aws::MedicalImaging::Model::StartDICOMImportJobOutcome startDICOMImportJobOutcome = medicalImagingClient.StartDICOMImportJob(
            startDICOMImportJobRequest);

    if (startDICOMImportJobOutcome.IsSuccess()) {
        importJobId = startDICOMImportJobOutcome.GetResult().GetJobId();
    }
    else {
        std::cerr << "Failed to start DICOM import job because "
                  << startDICOMImportJobOutcome.GetError().GetMessage() << std::endl;
    }

    return startDICOMImportJobOutcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[StartDICOMImportJob](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/StartDICOMImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/#code-examples)での設定と実行の方法を確認してください。

## シナリオ
<a name="scenarios"></a>

### 画像セットと画像フレームを使い始める
<a name="medical-imaging_Scenario_ImageSetsAndFrames_cpp_1_topic"></a>

次のコード例は、HealthImaging で DICOM ファイルをインポートし、画像フレームをダウンロードする方法を示しています。

実装はコマンドラインアプリケーションとして構造化されています。
+ DICOM インポート用にリソースをセットアップします。
+ DICOM ファイルをデータストアへのインポート。
+ インポートジョブの画像セット ID の取得。
+ インポートジョブの画像フレーム ID の取得。
+ イメージフレームをダウンロード、デコード、および検証します。
+ リソースをクリーンアップします。

**SDK for C\$1\$1**  
必要なリソースを持つ CloudFormation スタックを作成します。  

```
    Aws::String inputBucketName;
    Aws::String outputBucketName;
    Aws::String dataStoreId;
    Aws::String roleArn;
    Aws::String stackName;

    if (askYesNoQuestion(
            "Would you like to let this workflow create the resources for you? (y/n) ")) {
        stackName = askQuestion(
                "Enter a name for the AWS CloudFormation stack to create. ");
        Aws::String dataStoreName = askQuestion(
                "Enter a name for the HealthImaging datastore to create. ");

        Aws::Map<Aws::String, Aws::String> outputs = createCloudFormationStack(
                stackName,
                dataStoreName,
                clientConfiguration);

        if (!retrieveOutputs(outputs, dataStoreId, inputBucketName, outputBucketName,
                             roleArn)) {
            return false;
        }

        std::cout << "The following resources have been created." << std::endl;
        std::cout << "A HealthImaging datastore with ID: " << dataStoreId << "."
                  << std::endl;
        std::cout << "An Amazon S3 input bucket named: " << inputBucketName << "."
                  << std::endl;
        std::cout << "An Amazon S3 output bucket named: " << outputBucketName << "."
                  << std::endl;
        std::cout << "An IAM role with the ARN: " << roleArn << "." << std::endl;
        askQuestion("Enter return to continue.", alwaysTrueTest);
    }
    else {
        std::cout << "You have chosen to use preexisting resources:" << std::endl;
        dataStoreId = askQuestion(
                "Enter the data store ID of the HealthImaging datastore you wish to use: ");
        inputBucketName = askQuestion(
                "Enter the name of the S3 input bucket you wish to use: ");
        outputBucketName = askQuestion(
                "Enter the name of the S3 output bucket you wish to use: ");
        roleArn = askQuestion(
                "Enter the ARN for the IAM role with the proper permissions to import a DICOM series: ");
    }
```
DICOM ファイルを Amazon S3 インポートバケットにコピーします。  

```
    std::cout
            << "This workflow uses DICOM files from the National Cancer Institute Imaging Data\n"
            << "Commons (IDC) Collections." << std::endl;
    std::cout << "Here is the link to their website." << std::endl;
    std::cout << "https://registry.opendata.aws/nci-imaging-data-commons/" << std::endl;
    std::cout << "We will use DICOM files stored in an S3 bucket managed by the IDC."
              << std::endl;
    std::cout
            << "First one of the DICOM folders in the IDC collection must be copied to your\n"
               "input S3 bucket."
            << std::endl;
    std::cout << "You have the choice of one of the following "
              << IDC_ImageChoices.size() << " folders to copy." << std::endl;

    int index = 1;
    for (auto &idcChoice: IDC_ImageChoices) {
        std::cout << index << " - " << idcChoice.mDescription << std::endl;
        index++;
    }
    int choice = askQuestionForIntRange("Choose DICOM files to import: ", 1, 4);

    Aws::String fromDirectory = IDC_ImageChoices[choice - 1].mDirectory;
    Aws::String inputDirectory = "input";

    std::cout << "The files in the directory '" << fromDirectory << "' in the bucket '"
              << IDC_S3_BucketName << "' will be copied " << std::endl;
    std::cout << "to the folder '" << inputDirectory << "/" << fromDirectory
              << "' in the bucket '" << inputBucketName << "'." << std::endl;
    askQuestion("Enter return to start the copy.", alwaysTrueTest);

    if (!AwsDoc::Medical_Imaging::copySeriesBetweenBuckets(
            IDC_S3_BucketName,
            fromDirectory,
            inputBucketName,
            inputDirectory, clientConfiguration)) {
        std::cerr << "This workflow will exit because of an error." << std::endl;
        cleanup(stackName, dataStoreId, clientConfiguration);
        return false;
    }
```
DICOM ファイルを Amazon S3 データストアのにインポートします。  

```
bool AwsDoc::Medical_Imaging::startDicomImport(const Aws::String &dataStoreID,
                                               const Aws::String &inputBucketName,
                                               const Aws::String &inputDirectory,
                                               const Aws::String &outputBucketName,
                                               const Aws::String &outputDirectory,
                                               const Aws::String &roleArn,
                                               Aws::String &importJobId,
                                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    bool result = false;
    if (startDICOMImportJob(dataStoreID, inputBucketName, inputDirectory,
                            outputBucketName, outputDirectory, roleArn, importJobId,
                            clientConfiguration)) {
        std::cout << "DICOM import job started with job ID " << importJobId << "."
                  << std::endl;
        result = waitImportJobCompleted(dataStoreID, importJobId, clientConfiguration);
        if (result) {
            std::cout << "DICOM import job completed." << std::endl;

        }
    }

    return result;
}

//! Routine which starts a HealthImaging import job.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param inputBucketName: The name of the Amazon S3 bucket containing the DICOM files.
  \param inputDirectory: The directory in the S3 bucket containing the DICOM files.
  \param outputBucketName: The name of the S3 bucket for the output.
  \param outputDirectory: The directory in the S3 bucket to store the output.
  \param roleArn: The ARN of the IAM role with permissions for the import.
  \param importJobId: A string to receive the import job ID.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
  */
bool AwsDoc::Medical_Imaging::startDICOMImportJob(
        const Aws::String &dataStoreID, const Aws::String &inputBucketName,
        const Aws::String &inputDirectory, const Aws::String &outputBucketName,
        const Aws::String &outputDirectory, const Aws::String &roleArn,
        Aws::String &importJobId,
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::MedicalImagingClient medicalImagingClient(clientConfig);
    Aws::String inputURI = "s3://" + inputBucketName + "/" + inputDirectory + "/";
    Aws::String outputURI = "s3://" + outputBucketName + "/" + outputDirectory + "/";
    Aws::MedicalImaging::Model::StartDICOMImportJobRequest startDICOMImportJobRequest;
    startDICOMImportJobRequest.SetDatastoreId(dataStoreID);
    startDICOMImportJobRequest.SetDataAccessRoleArn(roleArn);
    startDICOMImportJobRequest.SetInputS3Uri(inputURI);
    startDICOMImportJobRequest.SetOutputS3Uri(outputURI);

    Aws::MedicalImaging::Model::StartDICOMImportJobOutcome startDICOMImportJobOutcome = medicalImagingClient.StartDICOMImportJob(
            startDICOMImportJobRequest);

    if (startDICOMImportJobOutcome.IsSuccess()) {
        importJobId = startDICOMImportJobOutcome.GetResult().GetJobId();
    }
    else {
        std::cerr << "Failed to start DICOM import job because "
                  << startDICOMImportJobOutcome.GetError().GetMessage() << std::endl;
    }

    return startDICOMImportJobOutcome.IsSuccess();
}


//! Routine which waits for a DICOM import job to complete.
/*!
 * @param dataStoreID: The HealthImaging data store ID.
 * @param importJobId: The import job ID.
 * @param clientConfiguration : Aws client configuration.
 * @return  bool: Function succeeded.
 */
bool AwsDoc::Medical_Imaging::waitImportJobCompleted(const Aws::String &datastoreID,
                                                     const Aws::String &importJobId,
                                                     const Aws::Client::ClientConfiguration &clientConfiguration) {

    Aws::MedicalImaging::Model::JobStatus jobStatus = Aws::MedicalImaging::Model::JobStatus::IN_PROGRESS;
    while (jobStatus == Aws::MedicalImaging::Model::JobStatus::IN_PROGRESS) {
        std::this_thread::sleep_for(std::chrono::seconds(1));

        Aws::MedicalImaging::Model::GetDICOMImportJobOutcome getDicomImportJobOutcome = getDICOMImportJob(
                datastoreID, importJobId,
                clientConfiguration);

        if (getDicomImportJobOutcome.IsSuccess()) {
            jobStatus = getDicomImportJobOutcome.GetResult().GetJobProperties().GetJobStatus();

            std::cout << "DICOM import job status: " <<
                      Aws::MedicalImaging::Model::JobStatusMapper::GetNameForJobStatus(
                              jobStatus) << std::endl;
        }
        else {
            std::cerr << "Failed to get import job status because "
                      << getDicomImportJobOutcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    return jobStatus == Aws::MedicalImaging::Model::JobStatus::COMPLETED;
}

//! Routine which gets a HealthImaging DICOM import job's properties.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param importJobID: The DICOM import job ID
  \param clientConfig: Aws client configuration.
  \return GetDICOMImportJobOutcome: The import job outcome.
*/
Aws::MedicalImaging::Model::GetDICOMImportJobOutcome
AwsDoc::Medical_Imaging::getDICOMImportJob(const Aws::String &dataStoreID,
                                           const Aws::String &importJobID,
                                           const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::MedicalImagingClient client(clientConfig);
    Aws::MedicalImaging::Model::GetDICOMImportJobRequest request;
    request.SetDatastoreId(dataStoreID);
    request.SetJobId(importJobID);
    Aws::MedicalImaging::Model::GetDICOMImportJobOutcome outcome = client.GetDICOMImportJob(
            request);
    if (!outcome.IsSuccess()) {
        std::cerr << "GetDICOMImportJob error: "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome;
}
```
DICOM インポートジョブによって作成された画像セットを取得します。  

```
bool
AwsDoc::Medical_Imaging::getImageSetsForDicomImportJob(const Aws::String &datastoreID,
                                                       const Aws::String &importJobId,
                                                       Aws::Vector<Aws::String> &imageSets,
                                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::MedicalImaging::Model::GetDICOMImportJobOutcome getDicomImportJobOutcome = getDICOMImportJob(
            datastoreID, importJobId, clientConfiguration);
    bool result = false;
    if (getDicomImportJobOutcome.IsSuccess()) {
        auto outputURI = getDicomImportJobOutcome.GetResult().GetJobProperties().GetOutputS3Uri();
        Aws::Http::URI uri(outputURI);
        const Aws::String &bucket = uri.GetAuthority();
        Aws::String key = uri.GetPath();

        Aws::S3::S3Client s3Client(clientConfiguration);
        Aws::S3::Model::GetObjectRequest objectRequest;
        objectRequest.SetBucket(bucket);
        objectRequest.SetKey(key + "/" + IMPORT_JOB_MANIFEST_FILE_NAME);

        auto getObjectOutcome = s3Client.GetObject(objectRequest);
        if (getObjectOutcome.IsSuccess()) {
            auto &data = getObjectOutcome.GetResult().GetBody();

            std::stringstream stringStream;
            stringStream << data.rdbuf();

            try {
                // Use JMESPath to extract the image set IDs.
                // https://jmespath.org/specification.html
                std::string jmesPathExpression = "jobSummary.imageSetsSummary[].imageSetId";
                jsoncons::json doc = jsoncons::json::parse(stringStream.str());

                jsoncons::json imageSetsJson = jsoncons::jmespath::search(doc,
                                                                          jmesPathExpression);\
                for (auto &imageSet: imageSetsJson.array_range()) {
                    imageSets.push_back(imageSet.as_string());
                }

                result = true;
            }
            catch (const std::exception &e) {
                std::cerr << e.what() << '\n';
            }

        }
        else {
            std::cerr << "Failed to get object because "
                      << getObjectOutcome.GetError().GetMessage() << std::endl;
        }

    }
    else {
        std::cerr << "Failed to get import job status because "
                  << getDicomImportJobOutcome.GetError().GetMessage() << std::endl;
    }

    return result;
}
```
画像セットの画像フレーム情報を取得します。  

```
bool AwsDoc::Medical_Imaging::getImageFramesForImageSet(const Aws::String &dataStoreID,
                                                        const Aws::String &imageSetID,
                                                        const Aws::String &outDirectory,
                                                        Aws::Vector<ImageFrameInfo> &imageFrames,
                                                        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::String fileName = outDirectory + "/" + imageSetID + "_metadata.json.gzip";
    bool result = false;
    if (getImageSetMetadata(dataStoreID, imageSetID, "", // Empty string for version ID.
                            fileName, clientConfiguration)) {
        try {
            std::string metadataGZip;
            {
                std::ifstream inFileStream(fileName.c_str(), std::ios::binary);
                if (!inFileStream) {
                    throw std::runtime_error("Failed to open file " + fileName);
                }

                std::stringstream stringStream;
                stringStream << inFileStream.rdbuf();
                metadataGZip = stringStream.str();
            }
            std::string metadataJson = gzip::decompress(metadataGZip.data(),
                                                        metadataGZip.size());
            // Use JMESPath to extract the image set IDs.
            // https://jmespath.org/specification.html
            jsoncons::json doc = jsoncons::json::parse(metadataJson);
            std::string jmesPathExpression = "Study.Series.*.Instances[].*[]";
            jsoncons::json instances = jsoncons::jmespath::search(doc,
                                                                  jmesPathExpression);
            for (auto &instance: instances.array_range()) {
                jmesPathExpression = "DICOM.RescaleSlope";
                std::string rescaleSlope = jsoncons::jmespath::search(instance,
                                                                      jmesPathExpression).to_string();
                jmesPathExpression = "DICOM.RescaleIntercept";
                std::string rescaleIntercept = jsoncons::jmespath::search(instance,
                                                                          jmesPathExpression).to_string();

                jmesPathExpression = "ImageFrames[][]";
                jsoncons::json imageFramesJson = jsoncons::jmespath::search(instance,
                                                                            jmesPathExpression);

                for (auto &imageFrame: imageFramesJson.array_range()) {
                    ImageFrameInfo imageFrameIDs;
                    imageFrameIDs.mImageSetId = imageSetID;
                    imageFrameIDs.mImageFrameId = imageFrame.find(
                            "ID")->value().as_string();
                    imageFrameIDs.mRescaleIntercept = rescaleIntercept;
                    imageFrameIDs.mRescaleSlope = rescaleSlope;
                    imageFrameIDs.MinPixelValue = imageFrame.find(
                            "MinPixelValue")->value().as_string();
                    imageFrameIDs.MaxPixelValue = imageFrame.find(
                            "MaxPixelValue")->value().as_string();

                    jmesPathExpression = "max_by(PixelDataChecksumFromBaseToFullResolution, &Width).Checksum";
                    jsoncons::json checksumJson = jsoncons::jmespath::search(imageFrame,
                                                                             jmesPathExpression);
                    imageFrameIDs.mFullResolutionChecksum = checksumJson.as_integer<uint32_t>();

                    imageFrames.emplace_back(imageFrameIDs);
                }
            }

            result = true;
        }
        catch (const std::exception &e) {
            std::cerr << "getImageFramesForImageSet failed because " << e.what()
                      << std::endl;
        }
    }

    return result;
}

//! Routine which gets a HealthImaging image set's metadata.
/*!
  \param dataStoreID: The HealthImaging data store ID.
  \param imageSetID: The HealthImaging image set ID.
  \param versionID: The HealthImaging image set version ID, ignored if empty.
  \param outputFilePath: The path where the metadata will be stored as gzipped json.
  \param clientConfig: Aws client configuration.
  \\return bool: Function succeeded.
*/
bool AwsDoc::Medical_Imaging::getImageSetMetadata(const Aws::String &dataStoreID,
                                                  const Aws::String &imageSetID,
                                                  const Aws::String &versionID,
                                                  const Aws::String &outputFilePath,
                                                  const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::MedicalImaging::Model::GetImageSetMetadataRequest request;
    request.SetDatastoreId(dataStoreID);
    request.SetImageSetId(imageSetID);
    if (!versionID.empty()) {
        request.SetVersionId(versionID);
    }
    Aws::MedicalImaging::MedicalImagingClient client(clientConfig);
    Aws::MedicalImaging::Model::GetImageSetMetadataOutcome outcome = client.GetImageSetMetadata(
            request);
    if (outcome.IsSuccess()) {
        std::ofstream file(outputFilePath, std::ios::binary);
        auto &metadata = outcome.GetResult().GetImageSetMetadataBlob();
        file << metadata.rdbuf();
    }
    else {
        std::cerr << "Failed to get image set metadata: "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
画像フレームをダウンロード、デコード、および検証します。  

```
bool AwsDoc::Medical_Imaging::downloadDecodeAndCheckImageFrames(
        const Aws::String &dataStoreID,
        const Aws::Vector<ImageFrameInfo> &imageFrames,
        const Aws::String &outDirectory,
        const Aws::Client::ClientConfiguration &clientConfiguration) {

    Aws::Client::ClientConfiguration clientConfiguration1(clientConfiguration);
    clientConfiguration1.executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>(
            "executor", 25);
    Aws::MedicalImaging::MedicalImagingClient medicalImagingClient(
            clientConfiguration1);

    Aws::Utils::Threading::Semaphore semaphore(0, 1);
    std::atomic<size_t> count(imageFrames.size());

    bool result = true;
    for (auto &imageFrame: imageFrames) {
        Aws::MedicalImaging::Model::GetImageFrameRequest getImageFrameRequest;
        getImageFrameRequest.SetDatastoreId(dataStoreID);
        getImageFrameRequest.SetImageSetId(imageFrame.mImageSetId);

        Aws::MedicalImaging::Model::ImageFrameInformation imageFrameInformation;
        imageFrameInformation.SetImageFrameId(imageFrame.mImageFrameId);
        getImageFrameRequest.SetImageFrameInformation(imageFrameInformation);

        auto getImageFrameAsyncLambda = [&semaphore, &result, &count, imageFrame, outDirectory](
                const Aws::MedicalImaging::MedicalImagingClient *client,
                const Aws::MedicalImaging::Model::GetImageFrameRequest &request,
                Aws::MedicalImaging::Model::GetImageFrameOutcome outcome,
                const std::shared_ptr<const Aws::Client::AsyncCallerContext> &context) {

                if (!handleGetImageFrameResult(outcome, outDirectory, imageFrame)) {
                    std::cerr << "Failed to download and convert image frame: "
                              << imageFrame.mImageFrameId << " from image set: "
                              << imageFrame.mImageSetId << std::endl;
                    result = false;
                }

                count--;
                if (count <= 0) {

                    semaphore.ReleaseAll();
                }
        }; // End of 'getImageFrameAsyncLambda' lambda.

        medicalImagingClient.GetImageFrameAsync(getImageFrameRequest,
                                                getImageFrameAsyncLambda);
    }

    if (count > 0) {
        semaphore.WaitOne();
    }

    if (result) {
        std::cout << imageFrames.size() << " image files were downloaded."
                  << std::endl;
    }

    return result;
}

bool AwsDoc::Medical_Imaging::decodeJPHFileAndValidateWithChecksum(
        const Aws::String &jphFile,
        uint32_t crc32Checksum) {
    opj_image_t *outputImage = jphImageToOpjBitmap(jphFile);
    if (!outputImage) {
        return false;
    }

    bool result = true;
    if (!verifyChecksumForImage(outputImage, crc32Checksum)) {
        std::cerr << "The checksum for the image does not match the expected value."
                  << std::endl;
        std::cerr << "File :" << jphFile << std::endl;
        result = false;
    }

    opj_image_destroy(outputImage);

    return result;
}

opj_image *
AwsDoc::Medical_Imaging::jphImageToOpjBitmap(const Aws::String &jphFile) {
    opj_stream_t *inFileStream = nullptr;
    opj_codec_t *decompressorCodec = nullptr;
    opj_image_t *outputImage = nullptr;
    try {
        std::shared_ptr<opj_dparameters> decodeParameters = std::make_shared<opj_dparameters>();
        memset(decodeParameters.get(), 0, sizeof(opj_dparameters));

        opj_set_default_decoder_parameters(decodeParameters.get());

        decodeParameters->decod_format = 1; // JP2 image format.
        decodeParameters->cod_format = 2; // BMP image format.

        std::strncpy(decodeParameters->infile, jphFile.c_str(),
                     OPJ_PATH_LEN);

        inFileStream = opj_stream_create_default_file_stream(
                decodeParameters->infile, true);
        if (!inFileStream) {
            throw std::runtime_error(
                    "Unable to create input file stream for file '" + jphFile + "'.");
        }

        decompressorCodec = opj_create_decompress(OPJ_CODEC_JP2);
        if (!decompressorCodec) {
            throw std::runtime_error("Failed to create decompression codec.");
        }

        int decodeMessageLevel = 1;
        if (!setupCodecLogging(decompressorCodec, &decodeMessageLevel)) {
            std::cerr << "Failed to setup codec logging." << std::endl;
        }

        if (!opj_setup_decoder(decompressorCodec, decodeParameters.get())) {
            throw std::runtime_error("Failed to setup decompression codec.");
        }
        if (!opj_codec_set_threads(decompressorCodec, 4)) {
            throw std::runtime_error("Failed to set decompression codec threads.");
        }

        if (!opj_read_header(inFileStream, decompressorCodec, &outputImage)) {
            throw std::runtime_error("Failed to read header.");
        }

        if (!opj_decode(decompressorCodec, inFileStream,
                        outputImage)) {
            throw std::runtime_error("Failed to decode.");
        }

        if (DEBUGGING) {
            std::cout << "image width : " << outputImage->x1 - outputImage->x0
                      << std::endl;
            std::cout << "image height : " << outputImage->y1 - outputImage->y0
                      << std::endl;
            std::cout << "number of channels: " << outputImage->numcomps
                      << std::endl;
            std::cout << "colorspace : " << outputImage->color_space << std::endl;
        }

    } catch (const std::exception &e) {
        std::cerr << e.what() << std::endl;
        if (outputImage) {
            opj_image_destroy(outputImage);
            outputImage = nullptr;
        }
    }
    if (inFileStream) {
        opj_stream_destroy(inFileStream);
    }
    if (decompressorCodec) {
        opj_destroy_codec(decompressorCodec);
    }

    return outputImage;
}

//! Template function which converts a planar image bitmap to an interleaved image bitmap and
//! then verifies the checksum of the bitmap.
/*!
 * @param image: The OpenJPEG image struct.
 * @param crc32Checksum: The CRC32 checksum.
 * @return  bool: Function succeeded.
 */
template<class myType>
bool verifyChecksumForImageForType(opj_image_t *image, uint32_t crc32Checksum) {
    uint32_t width = image->x1 - image->x0;
    uint32_t height = image->y1 - image->y0;
    uint32_t numOfChannels = image->numcomps;

    // Buffer for interleaved bitmap.
    std::vector<myType> buffer(width * height * numOfChannels);

    // Convert planar bitmap to interleaved bitmap.
    for (uint32_t channel = 0; channel < numOfChannels; channel++) {
        for (uint32_t row = 0; row < height; row++) {
            uint32_t fromRowStart = row / image->comps[channel].dy * width /
                                    image->comps[channel].dx;
            uint32_t toIndex = (row * width) * numOfChannels + channel;

            for (uint32_t col = 0; col < width; col++) {
                uint32_t fromIndex = fromRowStart + col / image->comps[channel].dx;

                buffer[toIndex] = static_cast<myType>(image->comps[channel].data[fromIndex]);

                toIndex += numOfChannels;
            }
        }
    }

    // Verify checksum.
    boost::crc_32_type crc32;
    crc32.process_bytes(reinterpret_cast<char *>(buffer.data()),
                        buffer.size() * sizeof(myType));

    bool result = crc32.checksum() == crc32Checksum;
    if (!result) {
        std::cerr << "verifyChecksumForImage, checksum mismatch, expected - "
                  << crc32Checksum << ", actual - " << crc32.checksum()
                  << std::endl;
    }

    return result;
}

//! Routine which verifies the checksum of an OpenJPEG image struct.
/*!
 * @param image: The OpenJPEG image struct.
 * @param crc32Checksum: The CRC32 checksum.
 * @return  bool: Function succeeded.
 */
bool AwsDoc::Medical_Imaging::verifyChecksumForImage(opj_image_t *image,
                                                     uint32_t crc32Checksum) {
    uint32_t channels = image->numcomps;
    bool result = false;
    if (0 < channels) {
        // Assume the precision is the same for all channels.
        uint32_t precision = image->comps[0].prec;
        bool signedData = image->comps[0].sgnd;
        uint32_t bytes = (precision + 7) / 8;

        if (signedData) {
            switch (bytes) {
                case 1 :
                    result = verifyChecksumForImageForType<int8_t>(image,
                                                                   crc32Checksum);
                    break;
                case 2 :
                    result = verifyChecksumForImageForType<int16_t>(image,
                                                                    crc32Checksum);
                    break;
                case 4 :
                    result = verifyChecksumForImageForType<int32_t>(image,
                                                                    crc32Checksum);
                    break;
                default:
                    std::cerr
                            << "verifyChecksumForImage, unsupported data type, signed bytes - "
                            << bytes << std::endl;
                    break;
            }
        }
        else {
            switch (bytes) {
                case 1 :
                    result = verifyChecksumForImageForType<uint8_t>(image,
                                                                    crc32Checksum);
                    break;
                case 2 :
                    result = verifyChecksumForImageForType<uint16_t>(image,
                                                                     crc32Checksum);
                    break;
                case 4 :
                    result = verifyChecksumForImageForType<uint32_t>(image,
                                                                     crc32Checksum);
                    break;
                default:
                    std::cerr
                            << "verifyChecksumForImage, unsupported data type, unsigned bytes - "
                            << bytes << std::endl;
                    break;
            }
        }

        if (!result) {
            std::cerr << "verifyChecksumForImage, error bytes " << bytes
                      << " signed "
                      << signedData << std::endl;
        }
    }
    else {
        std::cerr << "'verifyChecksumForImage', no channels in the image."
                  << std::endl;
    }
    return result;
}
```
リソースをクリーンアップします。  

```
bool AwsDoc::Medical_Imaging::cleanup(const Aws::String &stackName,
                                      const Aws::String &dataStoreId,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    bool result = true;

    if (!stackName.empty() && askYesNoQuestion(
            "Would you like to delete the stack " + stackName + "? (y/n)")) {
        std::cout << "Deleting the image sets in the stack." << std::endl;
        result &= emptyDatastore(dataStoreId, clientConfiguration);
        printAsterisksLine();
        std::cout << "Deleting the stack." << std::endl;
        result &= deleteStack(stackName, clientConfiguration);
    }
    return result;
}

bool AwsDoc::Medical_Imaging::emptyDatastore(const Aws::String &datastoreID,
                                             const Aws::Client::ClientConfiguration &clientConfiguration) {

    Aws::MedicalImaging::Model::SearchCriteria emptyCriteria;
    Aws::Vector<Aws::String> imageSetIDs;
    bool result = false;
    if (searchImageSets(datastoreID, emptyCriteria, imageSetIDs,
                        clientConfiguration)) {
        result = true;
        for (auto &imageSetID: imageSetIDs) {
            result &= deleteImageSet(datastoreID, imageSetID, clientConfiguration);
        }
    }

    return result;
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [DeleteImageSet](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/DeleteImageSet)
  + [GetDICOMImportJob](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/GetDICOMImportJob)
  + [GetImageFrame](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/GetImageFrame)
  + [GetImageSetMetadata](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/GetImageSetMetadata)
  + [SearchImageSets](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/SearchImageSets)
  + [StartDICOMImportJob](https://docs.aws.amazon.com/goto/SdkForCpp/medical-imaging-2023-07-19/StartDICOMImportJob)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/medical-imaging/imaging_set_and_frames_workflow#code-examples)での設定と実行の方法を確認してください。

# SDK for C\$1\$1 を使用する IAM の例
<a name="cpp_1_iam_code_examples"></a>

次のコード例は、IAM AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_cpp_1_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam/hello_iam#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS iam)

# Set this project's name.
project("hello_iam")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
    # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

    # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this
    # and set the proper subdirectory to the executables' location.

    AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_iam.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
iam.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/iam/IAMClient.h>
#include <aws/iam/model/ListPoliciesRequest.h>
#include <iostream>
#include <iomanip>

/*
 *  A "Hello IAM" starter application which initializes an AWS Identity and Access Management (IAM) client
 *  and lists the IAM policies.
 *
 *  main function
 *
 *  Usage: 'hello_iam'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        const Aws::String DATE_FORMAT("%Y-%m-%d");
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::IAM::IAMClient iamClient(clientConfig);
        Aws::IAM::Model::ListPoliciesRequest request;

        bool done = false;
        bool header = false;
        while (!done) {
            auto outcome = iamClient.ListPolicies(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Failed to list iam policies: " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = 1;
                break;
            }

            if (!header) {
                std::cout << std::left << std::setw(55) << "Name" <<
                          std::setw(30) << "ID" << std::setw(80) << "Arn" <<
                          std::setw(64) << "Description" << std::setw(12) <<
                          "CreateDate" << std::endl;
                header = true;
            }

            const auto &policies = outcome.GetResult().GetPolicies();
            for (const auto &policy: policies) {
                std::cout << std::left << std::setw(55) <<
                          policy.GetPolicyName() << std::setw(30) <<
                          policy.GetPolicyId() << std::setw(80) << policy.GetArn() <<
                          std::setw(64) << policy.GetDescription() << std::setw(12) <<
                          policy.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) <<
                          std::endl;
            }

            if (outcome.GetResult().GetIsTruncated()) {
                request.SetMarker(outcome.GetResult().GetMarker());
            } else {
                done = true;
            }
        }
    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListPolicies)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_cpp_1_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
namespace AwsDoc {
    namespace IAM {
  
        //! Cleanup by deleting created entities.
        /*!
          \sa DeleteCreatedEntities
          \param client: IAM client.
          \param role: IAM role.
          \param user: IAM user.
          \param policy: IAM policy.
        */
        static bool DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                          const Aws::IAM::Model::Role &role,
                                          const Aws::IAM::Model::User &user,
                                          const Aws::IAM::Model::Policy &policy);
    }

    static const int LIST_BUCKETS_WAIT_SEC = 20;

    static const char ALLOCATION_TAG[] = "example_code";
}

//! Scenario to create an IAM user, create an IAM role, and apply the role to the user.
// "IAM access" permissions are needed to run this code.
// "STS assume role" permissions are needed to run this code. (Note: It might be necessary to
//    create a custom policy).
/*!
  \sa iamCreateUserAssumeRoleScenario
  \param clientConfig: Aws client configuration.
  \return bool: Successful completion.
*/
bool AwsDoc::IAM::iamCreateUserAssumeRoleScenario(
        const Aws::Client::ClientConfiguration &clientConfig) {

    Aws::IAM::IAMClient client(clientConfig);
    Aws::IAM::Model::User user;
    Aws::IAM::Model::Role role;
    Aws::IAM::Model::Policy policy;

    // 1. Create a user.
    {
        Aws::IAM::Model::CreateUserRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String userName = "iam-demo-user-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetUserName(userName);

        Aws::IAM::Model::CreateUserOutcome outcome = client.CreateUser(request);
        if (!outcome.IsSuccess()) {
            std::cout << "Error creating IAM user " << userName << ":" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
        else {
            std::cout << "Successfully created IAM user " << userName << std::endl;
        }

        user = outcome.GetResult().GetUser();
    }

    // 2. Create a role.
    {
        // Get the IAM user for the current client in order to access its ARN.
        Aws::String iamUserArn;
        {
            Aws::IAM::Model::GetUserRequest request;
            Aws::IAM::Model::GetUserOutcome outcome = client.GetUser(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error getting Iam user. " <<
                          outcome.GetError().GetMessage() << std::endl;

                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }
            else {
                std::cout << "Successfully retrieved Iam user "
                          << outcome.GetResult().GetUser().GetUserName()
                          << std::endl;
            }

            iamUserArn = outcome.GetResult().GetUser().GetArn();
        }

        Aws::IAM::Model::CreateRoleRequest request;

        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleName = "iam-demo-role-" +
                               Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleName(roleName);

        // Build policy document for role.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");

        Aws::Utils::Document jsonPrincipal;
        jsonPrincipal.WithString("AWS", iamUserArn);
        jsonStatement.WithObject("Principal", jsonPrincipal);
        jsonStatement.WithString("Action", "sts:AssumeRole");
        jsonStatement.WithObject("Condition", Aws::Utils::Document());

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Setting policy for role\n   "
                  << policyDocument.View().WriteCompact() << std::endl;

        // Set role policy document as JSON string.
        request.SetAssumeRolePolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreateRoleOutcome outcome = client.CreateRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating role. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a role with name " << roleName
                      << std::endl;
        }

        role = outcome.GetResult().GetRole();
    }

    // 3. Create an IAM policy.
    {
        Aws::IAM::Model::CreatePolicyRequest request;
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String policyName = "iam-demo-policy-" +
                                 Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetPolicyName(policyName);

        // Build IAM policy document.
        Aws::Utils::Document jsonStatement;
        jsonStatement.WithString("Effect", "Allow");
        jsonStatement.WithString("Action", "s3:ListAllMyBuckets");
        jsonStatement.WithString("Resource", "arn:aws:s3:::*");

        Aws::Utils::Document policyDocument;
        policyDocument.WithString("Version", "2012-10-17");

        Aws::Utils::Array<Aws::Utils::Document> statements(1);
        statements[0] = jsonStatement;
        policyDocument.WithArray("Statement", statements);

        std::cout << "Creating a policy.\n   " << policyDocument.View().WriteCompact()
                  << std::endl;

        // Set IAM policy document as JSON string.
        request.SetPolicyDocument(policyDocument.View().WriteCompact());

        Aws::IAM::Model::CreatePolicyOutcome outcome = client.CreatePolicy(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully created a policy with name, " << policyName <<
                      "." << std::endl;
        }

        policy = outcome.GetResult().GetPolicy();
    }

    // 4. Assume the new role using the AWS Security Token Service (STS).
    Aws::STS::Model::Credentials credentials;
    {
        Aws::STS::STSClient stsClient(clientConfig);

        Aws::STS::Model::AssumeRoleRequest request;
        request.SetRoleArn(role.GetArn());
        Aws::String uuid = Aws::Utils::UUID::RandomUUID();
        Aws::String roleSessionName = "iam-demo-role-session-" +
                                      Aws::Utils::StringUtils::ToLower(uuid.c_str());
        request.SetRoleSessionName(roleSessionName);

        Aws::STS::Model::AssumeRoleOutcome assumeRoleOutcome;

        // Repeatedly call AssumeRole, because there is often a delay
        // before the role is available to be assumed.
        // Repeat at most 20 times when access is denied.
        int count = 0;
        while (true) {
            assumeRoleOutcome = stsClient.AssumeRole(request);
            if (!assumeRoleOutcome.IsSuccess()) {
                if (count > 20 ||
                    assumeRoleOutcome.GetError().GetErrorType() !=
                    Aws::STS::STSErrors::ACCESS_DENIED) {
                    std::cerr << "Error assuming role after 20 tries. " <<
                              assumeRoleOutcome.GetError().GetMessage() << std::endl;

                    DeleteCreatedEntities(client, role, user, policy);
                    return false;
                }
                std::this_thread::sleep_for(std::chrono::seconds(1));
            }
            else {
                std::cout << "Successfully assumed the role after " << count
                          << " seconds." << std::endl;
                break;
            }
            count++;
        }

        credentials = assumeRoleOutcome.GetResult().GetCredentials();
    }


    // 5. List objects in the bucket (This should fail).
    {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if (listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
            }
            else {
                std::cout
                        << "Access to list buckets denied because privileges have not been applied."
                        << std::endl;
            }
        }
        else {
            std::cerr
                    << "Successfully retrieved bucket lists when this should not happen."
                    << std::endl;
        }
    }

    // 6. Attach the policy to the role.
    {
        Aws::IAM::Model::AttachRolePolicyRequest request;
        request.SetRoleName(role.GetRoleName());
        request.WithPolicyArn(policy.GetArn());

        Aws::IAM::Model::AttachRolePolicyOutcome outcome = client.AttachRolePolicy(
                request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error creating policy. " <<
                      outcome.GetError().GetMessage() << std::endl;

            DeleteCreatedEntities(client, role, user, policy);
            return false;
        }
        else {
            std::cout << "Successfully attached the policy with name, "
                      << policy.GetPolicyName() <<
                      ", to the role, " << role.GetRoleName() << "." << std::endl;
        }
    }

    int count = 0;
    // 7. List objects in the bucket (this should succeed).
    // Repeatedly call ListBuckets, because there is often a delay
    // before the policy with ListBucket permissions has been applied to the role.
    // Repeat at most LIST_BUCKETS_WAIT_SEC times when access is denied.
    while (true) {
        Aws::S3::S3Client s3Client(
                Aws::Auth::AWSCredentials(credentials.GetAccessKeyId(),
                                          credentials.GetSecretAccessKey(),
                                          credentials.GetSessionToken()),
                Aws::MakeShared<Aws::S3::S3EndpointProvider>(ALLOCATION_TAG),
                clientConfig);
        Aws::S3::Model::ListBucketsOutcome listBucketsOutcome = s3Client.ListBuckets();
        if (!listBucketsOutcome.IsSuccess()) {
            if ((count > LIST_BUCKETS_WAIT_SEC) ||
                listBucketsOutcome.GetError().GetErrorType() !=
                Aws::S3::S3Errors::ACCESS_DENIED) {
                std::cerr << "Could not lists buckets after " << LIST_BUCKETS_WAIT_SEC << " seconds. " <<
                          listBucketsOutcome.GetError().GetMessage() << std::endl;
                DeleteCreatedEntities(client, role, user, policy);
                return false;
            }

            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        else {

            std::cout << "Successfully retrieved bucket lists after " << count
                      << " seconds." << std::endl;
            break;
        }
        count++;
    }

    // 8. Delete all the created resources.
    return DeleteCreatedEntities(client, role, user, policy);
}

bool AwsDoc::IAM::DeleteCreatedEntities(const Aws::IAM::IAMClient &client,
                                        const Aws::IAM::Model::Role &role,
                                        const Aws::IAM::Model::User &user,
                                        const Aws::IAM::Model::Policy &policy) {
    bool result = true;
    if (policy.ArnHasBeenSet()) {
        // Detach the policy from the role.
        {
            Aws::IAM::Model::DetachRolePolicyRequest request;
            request.SetPolicyArn(policy.GetArn());
            request.SetRoleName(role.GetRoleName());

            Aws::IAM::Model::DetachRolePolicyOutcome outcome = client.DetachRolePolicy(
                    request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error Detaching policy from roles. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully detached the policy with arn "
                          << policy.GetArn()
                          << " from role " << role.GetRoleName() << "." << std::endl;
            }
        }

        // Delete the policy.
        {
            Aws::IAM::Model::DeletePolicyRequest request;
            request.WithPolicyArn(policy.GetArn());

            Aws::IAM::Model::DeletePolicyOutcome outcome = client.DeletePolicy(request);
            if (!outcome.IsSuccess()) {
                std::cerr << "Error deleting policy. " <<
                          outcome.GetError().GetMessage() << std::endl;
                result = false;
            }
            else {
                std::cout << "Successfully deleted the policy with arn "
                          << policy.GetArn() << std::endl;
            }
        }

    }

    if (role.RoleIdHasBeenSet()) {
        // Delete the role.
        Aws::IAM::Model::DeleteRoleRequest request;
        request.SetRoleName(role.GetRoleName());

        Aws::IAM::Model::DeleteRoleOutcome outcome = client.DeleteRole(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting role. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the role with name "
                      << role.GetRoleName() << std::endl;
        }
    }

    if (user.ArnHasBeenSet()) {
        // Delete the user.
        Aws::IAM::Model::DeleteUserRequest request;
        request.WithUserName(user.GetUserName());

        Aws::IAM::Model::DeleteUserOutcome outcome = client.DeleteUser(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error deleting user. " <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Successfully deleted the user with name "
                      << user.GetUserName() << std::endl;
        }
    }

    return result;
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_cpp_1_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::attachRolePolicy(const Aws::String &roleName,
                                   const Aws::String &policyArn,
                                   const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::ListAttachedRolePoliciesRequest list_request;
    list_request.SetRoleName(roleName);

    bool done = false;
    while (!done) {
        auto list_outcome = iam.ListAttachedRolePolicies(list_request);
        if (!list_outcome.IsSuccess()) {
            std::cerr << "Failed to list attached policies of role " <<
                      roleName << ": " << list_outcome.GetError().GetMessage() <<
                      std::endl;
            return false;
        }

        const auto &policies = list_outcome.GetResult().GetAttachedPolicies();
        if (std::any_of(policies.cbegin(), policies.cend(),
                        [=](const Aws::IAM::Model::AttachedPolicy &policy) {
                                return policy.GetPolicyArn() == policyArn;
                        })) {
            std::cout << "Policy " << policyArn <<
                      " is already attached to role " << roleName << std::endl;
            return true;
        }

        done = !list_outcome.GetResult().GetIsTruncated();
        list_request.SetMarker(list_outcome.GetResult().GetMarker());
    }

    Aws::IAM::Model::AttachRolePolicyRequest request;
    request.SetRoleName(roleName);
    request.SetPolicyArn(policyArn);

    Aws::IAM::Model::AttachRolePolicyOutcome outcome = iam.AttachRolePolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to attach policy " << policyArn << " to role " <<
                  roleName << ": " << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully attached policy " << policyArn << " to role " <<
                  roleName << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/AttachRolePolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_cpp_1_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
Aws::String AwsDoc::IAM::createAccessKey(const Aws::String &userName,
                                         const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::CreateAccessKeyRequest request;
    request.SetUserName(userName);

    Aws::String result;
    Aws::IAM::Model::CreateAccessKeyOutcome outcome = iam.CreateAccessKey(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error creating access key for IAM user " << userName
                  << ":" << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        const auto &accessKey = outcome.GetResult().GetAccessKey();
        std::cout << "Successfully created access key for IAM user " <<
                  userName << std::endl << "  aws_access_key_id = " <<
                  accessKey.GetAccessKeyId() << std::endl <<
                  " aws_secret_access_key = " << accessKey.GetSecretAccessKey() <<
                  std::endl;
        result = accessKey.GetAccessKeyId();
    }

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccessKey)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_cpp_1_topic"></a>

次のコード例は、`CreateAccountAlias` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::createAccountAlias(const Aws::String &aliasName,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::CreateAccountAliasRequest request;
    request.SetAccountAlias(aliasName);

    Aws::IAM::Model::CreateAccountAliasOutcome outcome = iam.CreateAccountAlias(
            request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error creating account alias " << aliasName << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully created account alias " << aliasName <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateAccountAlias](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateAccountAlias)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_cpp_1_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
Aws::String AwsDoc::IAM::createPolicy(const Aws::String &policyName,
                                      const Aws::String &rsrcArn,
                                      const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::CreatePolicyRequest request;
    request.SetPolicyName(policyName);
    request.SetPolicyDocument(BuildSamplePolicyDocument(rsrcArn));

    Aws::IAM::Model::CreatePolicyOutcome outcome = iam.CreatePolicy(request);
    Aws::String result;
    if (!outcome.IsSuccess()) {
        std::cerr << "Error creating policy " << policyName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        result = outcome.GetResult().GetPolicy().GetArn();
        std::cout << "Successfully created policy " << policyName <<
                  std::endl;
    }

    return result;
}

Aws::String AwsDoc::IAM::BuildSamplePolicyDocument(const Aws::String &rsrc_arn) {
    std::stringstream stringStream;
    stringStream << "{"
                 << "  \"Version\": \"2012-10-17\","
                 << "  \"Statement\": ["
                 << "    {"
                 << "        \"Effect\": \"Allow\","
                 << "        \"Action\": \"logs:CreateLogGroup\","
                 << "        \"Resource\": \""
                 << rsrc_arn
                 << "\""
                 << "    },"
                 << "    {"
                 << "        \"Effect\": \"Allow\","
                 << "        \"Action\": ["
                 << "            \"dynamodb:DeleteItem\","
                 << "            \"dynamodb:GetItem\","
                 << "            \"dynamodb:PutItem\","
                 << "            \"dynamodb:Scan\","
                 << "            \"dynamodb:UpdateItem\""
                 << "       ],"
                 << "       \"Resource\": \""
                 << rsrc_arn
                 << "\""
                 << "    }"
                 << "   ]"
                 << "}";

    return stringStream.str();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_cpp_1_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
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\$1\$1 API リファレンスの「[CreateRole](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateRole)」を参照してください。**

### `CreateUser`
<a name="iam_CreateUser_cpp_1_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::CreateUserRequest create_request;
    create_request.SetUserName(userName);

    auto create_outcome = iam.CreateUser(create_request);
    if (!create_outcome.IsSuccess()) {
        std::cerr << "Error creating IAM user " << userName << ":" <<
                  create_outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully created IAM user " << userName << std::endl;
    }

    return create_outcome.IsSuccess();
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_cpp_1_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::deleteAccessKey(const Aws::String &userName,
                                  const Aws::String &accessKeyID,
                                  const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DeleteAccessKeyRequest request;
    request.SetUserName(userName);
    request.SetAccessKeyId(accessKeyID);

    auto outcome = iam.DeleteAccessKey(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting access key " << accessKeyID << " from user "
                  << userName << ": " << outcome.GetError().GetMessage() <<
                  std::endl;
    }
    else {
        std::cout << "Successfully deleted access key " << accessKeyID
                  << " for IAM user " << userName << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccessKey)」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_cpp_1_topic"></a>

次のコード例は、`DeleteAccountAlias` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::deleteAccountAlias(const Aws::String &accountAlias,
                                     const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DeleteAccountAliasRequest request;
    request.SetAccountAlias(accountAlias);

    const auto outcome = iam.DeleteAccountAlias(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting account alias " << accountAlias << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully deleted account alias " << accountAlias <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteAccountAlias](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteAccountAlias)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_cpp_1_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::deletePolicy(const Aws::String &policyArn,
                               const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::DeletePolicyRequest request;
    request.SetPolicyArn(policyArn);

    auto outcome = iam.DeletePolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting policy with arn " << policyArn << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully deleted policy with arn " << policyArn
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeletePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeletePolicy)」を参照してください。

### `DeleteServerCertificate`
<a name="iam_DeleteServerCertificate_cpp_1_topic"></a>

次のコード例は、`DeleteServerCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::deleteServerCertificate(const Aws::String &certificateName,
                                          const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::DeleteServerCertificateRequest request;
    request.SetServerCertificateName(certificateName);

    const auto outcome = iam.DeleteServerCertificate(request);
    bool result = true;
    if (!outcome.IsSuccess()) {
        if (outcome.GetError().GetErrorType() != Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
            std::cerr << "Error deleting server certificate " << certificateName <<
                      ": " << outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Certificate '" << certificateName
                      << "' not found." << std::endl;
        }
    }
    else {
        std::cout << "Successfully deleted server certificate " << certificateName
                  << std::endl;
    }

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteServerCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteServerCertificate)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_cpp_1_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DeleteUserRequest request;
    request.SetUserName(userName);
    auto outcome = iam.DeleteUser(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error deleting IAM user " << userName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;;
    }
    else {
        std::cout << "Successfully deleted IAM user " << userName << std::endl;
    }

    return outcome.IsSuccess();
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DeleteUser)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_cpp_1_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::DetachRolePolicyRequest detachRequest;
    detachRequest.SetRoleName(roleName);
    detachRequest.SetPolicyArn(policyArn);

    auto detachOutcome = iam.DetachRolePolicy(detachRequest);
    if (!detachOutcome.IsSuccess()) {
        std::cerr << "Failed to detach policy " << policyArn << " from role "
                  << roleName << ": " << detachOutcome.GetError().GetMessage() <<
                  std::endl;
    }
    else {
        std::cout << "Successfully detached policy " << policyArn << " from role "
                  << roleName << std::endl;
    }

    return detachOutcome.IsSuccess();
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/DetachRolePolicy)」を参照してください。

### `GetAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_cpp_1_topic"></a>

次のコード例は、`GetAccessKeyLastUsed` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::accessKeyLastUsed(const Aws::String &secretKeyID,
                                    const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::GetAccessKeyLastUsedRequest request;

    request.SetAccessKeyId(secretKeyID);

    Aws::IAM::Model::GetAccessKeyLastUsedOutcome outcome = iam.GetAccessKeyLastUsed(
            request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error querying last used time for access key " <<
                  secretKeyID << ":" << outcome.GetError().GetMessage() << std::endl;
    }
    else {
        Aws::String lastUsedTimeString =
                outcome.GetResult()
                        .GetAccessKeyLastUsed()
                        .GetLastUsedDate()
                        .ToGmtString(Aws::Utils::DateFormat::ISO_8601);
        std::cout << "Access key " << secretKeyID << " last used at time " <<
                  lastUsedTimeString << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetAccessKeyLastUsed](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/GetAccessKeyLastUsed)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_cpp_1_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::getPolicy(const Aws::String &policyArn,
                            const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::GetPolicyRequest request;
    request.SetPolicyArn(policyArn);

    auto outcome = iam.GetPolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error getting policy " << policyArn << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        const auto &policy = outcome.GetResult().GetPolicy();
        std::cout << "Name: " << policy.GetPolicyName() << std::endl <<
                  "ID: " << policy.GetPolicyId() << std::endl << "Arn: " <<
                  policy.GetArn() << std::endl << "Description: " <<
                  policy.GetDescription() << std::endl << "CreateDate: " <<
                  policy.GetCreateDate().ToGmtString(Aws::Utils::DateFormat::ISO_8601)
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/GetPolicy)」を参照してください。

### `GetServerCertificate`
<a name="iam_GetServerCertificate_cpp_1_topic"></a>

次のコード例は、`GetServerCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::getServerCertificate(const Aws::String &certificateName,
                                       const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::GetServerCertificateRequest request;
    request.SetServerCertificateName(certificateName);

    auto outcome = iam.GetServerCertificate(request);
    bool result = true;
    if (!outcome.IsSuccess()) {
        if (outcome.GetError().GetErrorType() != Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
            std::cerr << "Error getting server certificate " << certificateName <<
                      ": " << outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Certificate '" << certificateName
                      << "' not found." << std::endl;
        }
    }
    else {
        const auto &certificate = outcome.GetResult().GetServerCertificate();
        std::cout << "Name: " <<
                  certificate.GetServerCertificateMetadata().GetServerCertificateName()
                  << std::endl << "Body: " << certificate.GetCertificateBody() <<
                  std::endl << "Chain: " << certificate.GetCertificateChain() <<
                  std::endl;
    }

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetServerCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/GetServerCertificate)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_cpp_1_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::listAccessKeys(const Aws::String &userName,
                                 const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListAccessKeysRequest request;
    request.SetUserName(userName);

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListAccessKeys(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list access keys for user " << userName
                      << ": " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(32) << "UserName" <<
                      std::setw(30) << "KeyID" << std::setw(20) << "Status" <<
                      std::setw(20) << "CreateDate" << std::endl;
            header = true;
        }

        const auto &keys = outcome.GetResult().GetAccessKeyMetadata();
        const Aws::String DATE_FORMAT = "%Y-%m-%d";

        for (const auto &key: keys) {
            Aws::String statusString =
                    Aws::IAM::Model::StatusTypeMapper::GetNameForStatusType(
                            key.GetStatus());
            std::cout << std::left << std::setw(32) << key.GetUserName() <<
                      std::setw(30) << key.GetAccessKeyId() << std::setw(20) <<
                      statusString << std::setw(20) <<
                      key.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) << std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListAccessKeys](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListAccessKeys)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_cpp_1_topic"></a>

次のコード例は、`ListAccountAliases` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool
AwsDoc::IAM::listAccountAliases(const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListAccountAliasesRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListAccountAliases(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list account aliases: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        const auto &aliases = outcome.GetResult().GetAccountAliases();
        if (!header) {
            if (aliases.size() == 0) {
                std::cout << "Account has no aliases" << std::endl;
                break;
            }
            std::cout << std::left << std::setw(32) << "Alias" << std::endl;
            header = true;
        }

        for (const auto &alias: aliases) {
            std::cout << std::left << std::setw(32) << alias << std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListAccountAliases](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListAccountAliases)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_cpp_1_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::listPolicies(const Aws::Client::ClientConfiguration &clientConfig) {
    const Aws::String DATE_FORMAT("%Y-%m-%d");
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListPoliciesRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListPolicies(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list iam policies: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(55) << "Name" <<
                      std::setw(30) << "ID" << std::setw(80) << "Arn" <<
                      std::setw(64) << "Description" << std::setw(12) <<
                      "CreateDate" << std::endl;
            header = true;
        }

        const auto &policies = outcome.GetResult().GetPolicies();
        for (const auto &policy: policies) {
            std::cout << std::left << std::setw(55) <<
                      policy.GetPolicyName() << std::setw(30) <<
                      policy.GetPolicyId() << std::setw(80) << policy.GetArn() <<
                      std::setw(64) << policy.GetDescription() << std::setw(12) <<
                      policy.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) <<
                      std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListPolicies)」を参照してください。

### `ListServerCertificates`
<a name="iam_ListServerCertificates_cpp_1_topic"></a>

次のコード例は、`ListServerCertificates` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::listServerCertificates(
        const Aws::Client::ClientConfiguration &clientConfig) {
    const Aws::String DATE_FORMAT = "%Y-%m-%d";

    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListServerCertificatesRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListServerCertificates(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list server certificates: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(55) << "Name" <<
                      std::setw(30) << "ID" << std::setw(80) << "Arn" <<
                      std::setw(14) << "UploadDate" << std::setw(14) <<
                      "ExpirationDate" << std::endl;
            header = true;
        }

        const auto &certificates =
                outcome.GetResult().GetServerCertificateMetadataList();

        for (const auto &certificate: certificates) {
            std::cout << std::left << std::setw(55) <<
                      certificate.GetServerCertificateName() << std::setw(30) <<
                      certificate.GetServerCertificateId() << std::setw(80) <<
                      certificate.GetArn() << std::setw(14) <<
                      certificate.GetUploadDate().ToGmtString(DATE_FORMAT.c_str()) <<
                      std::setw(14) <<
                      certificate.GetExpiration().ToGmtString(DATE_FORMAT.c_str()) <<
                      std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListServerCertificates](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListServerCertificates)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_cpp_1_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::listUsers(const Aws::Client::ClientConfiguration &clientConfig) {
    const Aws::String DATE_FORMAT = "%Y-%m-%d";
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::ListUsersRequest request;

    bool done = false;
    bool header = false;
    while (!done) {
        auto outcome = iam.ListUsers(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Failed to list iam users:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (!header) {
            std::cout << std::left << std::setw(32) << "Name" <<
                      std::setw(30) << "ID" << std::setw(64) << "Arn" <<
                      std::setw(20) << "CreateDate" << std::endl;
            header = true;
        }

        const auto &users = outcome.GetResult().GetUsers();
        for (const auto &user: users) {
            std::cout << std::left << std::setw(32) << user.GetUserName() <<
                      std::setw(30) << user.GetUserId() << std::setw(64) <<
                      user.GetArn() << std::setw(20) <<
                      user.GetCreateDate().ToGmtString(DATE_FORMAT.c_str())
                      << std::endl;
        }

        if (outcome.GetResult().GetIsTruncated()) {
            request.SetMarker(outcome.GetResult().GetMarker());
        }
        else {
            done = true;
        }
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/ListUsers)」を参照してください。

### `PutRolePolicy`
<a name="iam_PutRolePolicy_cpp_1_topic"></a>

次のコード例は、`PutRolePolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::putRolePolicy(
        const Aws::String &roleName,
        const Aws::String &policyName,
        const Aws::String &policyDocument,
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iamClient(clientConfig);
    Aws::IAM::Model::PutRolePolicyRequest request;

    request.SetRoleName(roleName);
    request.SetPolicyName(policyName);
    request.SetPolicyDocument(policyDocument);

    Aws::IAM::Model::PutRolePolicyOutcome outcome = iamClient.PutRolePolicy(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Error putting policy on role. " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Successfully put the role policy." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[PutRolePolicy](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/PutRolePolicy)」を参照してください。

### `UpdateAccessKey`
<a name="iam_UpdateAccessKey_cpp_1_topic"></a>

次のコード例は、`UpdateAccessKey` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::updateAccessKey(const Aws::String &userName,
                                  const Aws::String &accessKeyID,
                                  Aws::IAM::Model::StatusType status,
                                  const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::UpdateAccessKeyRequest request;
    request.SetUserName(userName);
    request.SetAccessKeyId(accessKeyID);
    request.SetStatus(status);

    auto outcome = iam.UpdateAccessKey(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated status of access key "
                  << accessKeyID << " for user " << userName << std::endl;
    }
    else {
        std::cerr << "Error updated status of access key " << accessKeyID <<
                  " for user " << userName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateAccessKey](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/UpdateAccessKey)」を参照してください。

### `UpdateServerCertificate`
<a name="iam_UpdateServerCertificate_cpp_1_topic"></a>

次のコード例は、`UpdateServerCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::updateServerCertificate(const Aws::String &currentCertificateName,
                                          const Aws::String &newCertificateName,
                                          const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);
    Aws::IAM::Model::UpdateServerCertificateRequest request;
    request.SetServerCertificateName(currentCertificateName);
    request.SetNewServerCertificateName(newCertificateName);

    auto outcome = iam.UpdateServerCertificate(request);
    bool result = true;
    if (outcome.IsSuccess()) {
        std::cout << "Server certificate " << currentCertificateName
                  << " successfully renamed as " << newCertificateName
                  << std::endl;
    }
    else {
        if (outcome.GetError().GetErrorType() != Aws::IAM::IAMErrors::NO_SUCH_ENTITY) {
            std::cerr << "Error changing name of server certificate " <<
                      currentCertificateName << " to " << newCertificateName << ":" <<
                      outcome.GetError().GetMessage() << std::endl;
            result = false;
        }
        else {
            std::cout << "Certificate '" << currentCertificateName
                      << "' not found." << std::endl;
        }
    }

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateServerCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/UpdateServerCertificate)」を参照してください。

### `UpdateUser`
<a name="iam_UpdateUser_cpp_1_topic"></a>

次のコード例は、`UpdateUser` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::IAM::updateUser(const Aws::String &currentUserName,
                             const Aws::String &newUserName,
                             const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::IAM::IAMClient iam(clientConfig);

    Aws::IAM::Model::UpdateUserRequest request;
    request.SetUserName(currentUserName);
    request.SetNewUserName(newUserName);

    auto outcome = iam.UpdateUser(request);
    if (outcome.IsSuccess()) {
        std::cout << "IAM user " << currentUserName <<
                  " successfully updated with new user name " << newUserName <<
                  std::endl;
    }
    else {
        std::cerr << "Error updating user name for IAM user " << currentUserName <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateUser](https://docs.aws.amazon.com/goto/SdkForCpp/iam-2010-05-08/UpdateUser)」を参照してください。

# AWS IoT SDK for C\$1\$1 を使用した例
<a name="cpp_1_iot_code_examples"></a>

次のコード例は、 AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoTは
<a name="iot_Hello_cpp_1_topic"></a>

次のコード例は、 AWS IoTの使用を開始する方法を示しています。

**SDK for C\$1\$1**  
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS iot)

# Set this project's name.
project("hello_iot")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
    # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

    # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this
    # and set the proper subdirectory to the executables' location.

    AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_iot.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1iot.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/iot/IoTClient.h>
#include <aws/iot/model/ListThingsRequest.h>
#include <iostream>

/*
 *  A "Hello IoT" starter application which initializes an AWS IoT client and
 *  lists the AWS IoT topics in the current account.
 *
 *  main function
 *
 *  Usage: 'hello_iot'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    //  Optional: change the log level for debugging.
    //  options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::IoT::IoTClient iotClient(clientConfig);
        // List the things in the current account.
        Aws::IoT::Model::ListThingsRequest listThingsRequest;

        Aws::String nextToken; // Used for pagination.
        Aws::Vector<Aws::IoT::Model::ThingAttribute> allThings;

        do {
            if (!nextToken.empty()) {
                listThingsRequest.SetNextToken(nextToken);
            }

            Aws::IoT::Model::ListThingsOutcome listThingsOutcome = iotClient.ListThings(
                    listThingsRequest);
            if (listThingsOutcome.IsSuccess()) {
                const Aws::Vector<Aws::IoT::Model::ThingAttribute> &things = listThingsOutcome.GetResult().GetThings();
                allThings.insert(allThings.end(), things.begin(), things.end());
                nextToken = listThingsOutcome.GetResult().GetNextToken();
            }
            else {
                std::cerr << "List things failed"
                          << listThingsOutcome.GetError().GetMessage() << std::endl;
                break;
            }
        } while (!nextToken.empty());

        std::cout << allThings.size() << " thing(s) found." << std::endl;
        for (auto const &thing: allThings) {
            std::cout << thing.GetThingName() << std::endl;
        }
    }

    Aws::ShutdownAPI(options); // Should only be called once.
    return 0;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[listThings](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/listThings)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot/hello_iot#code-examples)での設定と実行の方法を確認してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iot_Scenario_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT モノを作成します。
+ デバイス証明書を生成します。
+ 属性を使用して AWS IoT モノを更新します。
+ 一意のエンドポイントを返します。
+  AWS IoT 証明書を一覧表示します。
+  AWS IoT シャドウを更新します。
+ 状態情報を書き込みます。
+ ルールを作成する｡
+ ルールを一覧表示します。
+ モノの名前を使用してモノを検索します。
+  AWS IoT モノを削除します。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot/things_and_shadows_workflow#code-examples)での設定と実行の方法を確認してください。
 AWS IoT モノを作成します。  

```
    Aws::String thingName = askQuestion("Enter a thing name: ");

    if (!createThing(thingName, clientConfiguration)) {
        std::cerr << "Exiting because createThing failed." << std::endl;
        cleanup("", "", "", "", "", false, clientConfiguration);
        return false;
    }
```

```
//! Create an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::createThing(const Aws::String &thingName,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::CreateThingRequest createThingRequest;
    createThingRequest.SetThingName(thingName);

    Aws::IoT::Model::CreateThingOutcome outcome = iotClient.CreateThing(
            createThingRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created thing " << thingName << std::endl;
    }
    else {
        std::cerr << "Failed to create thing " << thingName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
デバイス証明書を生成してアタッチします。  

```
    Aws::String certificateARN;
    Aws::String certificateID;
    if (askYesNoQuestion("Would you like to create a certificate for your thing? (y/n) ")) {
        Aws::String outputFolder;
        if (askYesNoQuestion(
                "Would you like to save the certificate and keys to file? (y/n) ")) {
            outputFolder = std::filesystem::current_path();
            outputFolder += "/device_keys_and_certificates";

            std::filesystem::create_directories(outputFolder);

            std::cout << "The certificate and keys will be saved to the folder: "
                      << outputFolder << std::endl;
        }

        if (!createKeysAndCertificate(outputFolder, certificateARN, certificateID,
                                      clientConfiguration)) {
            std::cerr << "Exiting because createKeysAndCertificate failed."
                      << std::endl;
            cleanup(thingName, "", "", "", "", false, clientConfiguration);
            return false;
        }

        std::cout << "\nNext, the certificate will be attached to the thing.\n"
                  << std::endl;
        if (!attachThingPrincipal(certificateARN, thingName, clientConfiguration)) {
            std::cerr << "Exiting because attachThingPrincipal failed." << std::endl;
            cleanup(thingName, certificateARN, certificateID, "", "",
                    false,
                    clientConfiguration);
            return false;
        }
    }
```

```
//! Create keys and certificate for an Aws IoT device.
//! This routine will save certificates and keys to an output folder, if provided.
/*!
  \param outputFolder: Location for storing output in files, ignored when string is empty.
  \param certificateARNResult: A string to receive the ARN of the created certificate.
  \param certificateID: A string to receive the ID of the created certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::createKeysAndCertificate(const Aws::String &outputFolder,
                                           Aws::String &certificateARNResult,
                                           Aws::String &certificateID,
                                           const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient client(clientConfiguration);
    Aws::IoT::Model::CreateKeysAndCertificateRequest createKeysAndCertificateRequest;

    Aws::IoT::Model::CreateKeysAndCertificateOutcome outcome =
            client.CreateKeysAndCertificate(createKeysAndCertificateRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created a certificate and keys" << std::endl;
        certificateARNResult = outcome.GetResult().GetCertificateArn();
        certificateID = outcome.GetResult().GetCertificateId();
        std::cout << "Certificate ARN: " << certificateARNResult << ", certificate ID: "
                  << certificateID << std::endl;

        if (!outputFolder.empty()) {
            std::cout << "Writing certificate and keys to the folder '" << outputFolder
                      << "'." << std::endl;
            std::cout << "Be sure these files are stored securely." << std::endl;

            Aws::String certificateFilePath = outputFolder + "/certificate.pem.crt";
            std::ofstream certificateFile(certificateFilePath);
            if (!certificateFile.is_open()) {
                std::cerr << "Error opening certificate file, '" << certificateFilePath
                          << "'."
                          << std::endl;
                return false;
            }
            certificateFile << outcome.GetResult().GetCertificatePem();
            certificateFile.close();

            const Aws::IoT::Model::KeyPair &keyPair = outcome.GetResult().GetKeyPair();

            Aws::String privateKeyFilePath = outputFolder + "/private.pem.key";
            std::ofstream privateKeyFile(privateKeyFilePath);
            if (!privateKeyFile.is_open()) {
                std::cerr << "Error opening private key file, '" << privateKeyFilePath
                          << "'."
                          << std::endl;
                return false;
            }
            privateKeyFile << keyPair.GetPrivateKey();
            privateKeyFile.close();

            Aws::String publicKeyFilePath = outputFolder + "/public.pem.key";
            std::ofstream publicKeyFile(publicKeyFilePath);
            if (!publicKeyFile.is_open()) {
                std::cerr << "Error opening public key file, '" << publicKeyFilePath
                          << "'."
                          << std::endl;
                return false;
            }
            publicKeyFile << keyPair.GetPublicKey();
        }
    }
    else {
        std::cerr << "Error creating keys and certificate: "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Attach a principal to an AWS IoT thing.
/*!
  \param principal: A principal to attach.
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::attachThingPrincipal(const Aws::String &principal,
                                       const Aws::String &thingName,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient client(clientConfiguration);
    Aws::IoT::Model::AttachThingPrincipalRequest request;
    request.SetPrincipal(principal);
    request.SetThingName(thingName);
    Aws::IoT::Model::AttachThingPrincipalOutcome outcome = client.AttachThingPrincipal(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully attached principal to thing." << std::endl;
    }
    else {
        std::cerr << "Failed to attach principal to thing." <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
 AWS IoT モノに対してさまざまなオペレーションを実行します。  

```
    if (!updateThing(thingName, { {"location", "Office"}, {"firmwareVersion", "v2.0"} }, clientConfiguration)) {
        std::cerr << "Exiting because updateThing failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, "", "", false,
                clientConfiguration);
        return false;
    }

    printAsterisksLine();

    std::cout << "Now an endpoint will be retrieved for your account.\n" << std::endl;
    std::cout << "An IoT Endpoint refers to a specific URL or Uniform Resource Locator that serves as the entry point\n"
    << "for communication between IoT devices and the AWS IoT service." << std::endl;

    askQuestion("Press Enter to continue:", alwaysTrueTest);

    Aws::String endpoint;
    if (!describeEndpoint(endpoint, clientConfiguration)) {
        std::cerr << "Exiting because getEndpoint failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, "", "", false,
                clientConfiguration);
        return false;
    }
    std::cout <<"Your endpoint is " << endpoint << "." << std::endl;
    printAsterisksLine();

    std::cout << "Now the certificates in your account will be listed." << std::endl;
    askQuestion("Press Enter to continue:", alwaysTrueTest);

    if (!listCertificates(clientConfiguration)) {
        std::cerr << "Exiting because listCertificates failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, "", "", false,
                clientConfiguration);
        return false;
    }

    printAsterisksLine();

    std::cout << "Now the shadow for the thing will be updated.\n" << std::endl;
    std::cout << "A thing shadow refers to a feature that enables you to create a virtual representation, or \"shadow,\"\n"
    << "of a physical device or thing. The thing shadow allows you to synchronize and control the state of a device between\n"
    << "the cloud and the device itself. and the AWS IoT service. For example, you can write and retrieve JSON data from a thing shadow." << std::endl;
    askQuestion("Press Enter to continue:", alwaysTrueTest);

    if (!updateThingShadow(thingName, R"({"state":{"reported":{"temperature":25,"humidity":50}}})", clientConfiguration)) {
        std::cerr << "Exiting because updateThingShadow failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, "", "", false,
                clientConfiguration);
        return false;
    }

    printAsterisksLine();

    std::cout << "Now, the state information for the shadow will be retrieved.\n" << std::endl;
    askQuestion("Press Enter to continue:", alwaysTrueTest);

    Aws::String shadowState;
    if (!getThingShadow(thingName, shadowState, clientConfiguration)) {
        std::cerr << "Exiting because getThingShadow failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, "", "", false,
                clientConfiguration);
        return false;
    }
    std::cout << "The retrieved shadow state is: " << shadowState << std::endl;

    printAsterisksLine();

    std::cout << "A rule with now be added to to the thing.\n" << std::endl;
    std::cout << "Any user who has permission to create rules will be able to access data processed by the rule." << std::endl;
    std::cout << "In this case, the rule will use an Simple Notification Service (SNS) topic and an IAM rule." << std::endl;
    std::cout << "These resources will be created using a CloudFormation template." << std::endl;
    std::cout << "Stack creation may take a few minutes." << std::endl;

    askQuestion("Press Enter to continue: ", alwaysTrueTest);
    Aws::Map<Aws::String, Aws::String> outputs =createCloudFormationStack(STACK_NAME,clientConfiguration);
    if (outputs.empty()) {
        std::cerr << "Exiting because createCloudFormationStack failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, "", "", false,
                clientConfiguration);
        return false;
    }

    // Retrieve the topic ARN and role ARN from the CloudFormation stack outputs.
    auto topicArnIter = outputs.find(SNS_TOPIC_ARN_OUTPUT);
    auto roleArnIter = outputs.find(ROLE_ARN_OUTPUT);
    if ((topicArnIter == outputs.end()) || (roleArnIter == outputs.end())) {
        std::cerr << "Exiting because output '" << SNS_TOPIC_ARN_OUTPUT <<
        "' or '" << ROLE_ARN_OUTPUT << "'not found in the CloudFormation stack."  << std::endl;
        cleanup(thingName, certificateARN, certificateID, STACK_NAME, "",
                false,
                clientConfiguration);
        return false;
    }

    Aws::String topicArn = topicArnIter->second;
    Aws::String roleArn = roleArnIter->second;
    Aws::String sqlStatement = "SELECT * FROM '";
    sqlStatement += MQTT_MESSAGE_TOPIC_FILTER;
    sqlStatement += "'";

    printAsterisksLine();

    std::cout << "Now a rule will be created.\n" << std::endl;
    std::cout << "Rules are an administrator-level action. Any user who has permission\n"
                 << "to create rules will be able to access data processed by the rule." << std::endl;
    std::cout << "In this case, the rule will use an SNS topic" << std::endl;
    std::cout << "and the following SQL statement '" << sqlStatement << "'." << std::endl;
    std::cout << "For more information on IoT SQL, see https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-reference.html" << std::endl;
    Aws::String ruleName = askQuestion("Enter a rule name: ");
    if (!createTopicRule(ruleName, topicArn, sqlStatement, roleArn, clientConfiguration)) {
        std::cerr << "Exiting because createRule failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, STACK_NAME, "",
                false,
                clientConfiguration);
        return false;
    }

    printAsterisksLine();

    std::cout << "Now your rules will be listed.\n" << std::endl;
    askQuestion("Press Enter to continue: ", alwaysTrueTest);
    if (!listTopicRules(clientConfiguration)) {
        std::cerr << "Exiting because listRules failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, STACK_NAME, ruleName,
                false,
                clientConfiguration);
        return false;
    }

    printAsterisksLine();
    Aws::String queryString = "thingName:" + thingName;
    std::cout << "Now the AWS IoT fleet index will be queried with the query\n'"
    << queryString << "'.\n" << std::endl;
    std::cout << "For query information, see https://docs.aws.amazon.com/iot/latest/developerguide/query-syntax.html" << std::endl;

    std::cout << "For this query to work, thing indexing must be enabled in your account.\n"
    << "This can be done with the awscli command line by calling 'aws iot update-indexing-configuration'\n"
       << "or it can be done programmatically." << std::endl;
    std::cout << "For more information, see https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html" << std::endl;
    if (askYesNoQuestion("Do you want to enable thing indexing in your account? (y/n) "))
    {
        Aws::IoT::Model::ThingIndexingConfiguration thingIndexingConfiguration;
        thingIndexingConfiguration.SetThingIndexingMode(Aws::IoT::Model::ThingIndexingMode::REGISTRY_AND_SHADOW);
        thingIndexingConfiguration.SetThingConnectivityIndexingMode(Aws::IoT::Model::ThingConnectivityIndexingMode::STATUS);
        // The ThingGroupIndexingConfiguration object is ignored if not set.
        Aws::IoT::Model::ThingGroupIndexingConfiguration thingGroupIndexingConfiguration;
        if (!updateIndexingConfiguration(thingIndexingConfiguration, thingGroupIndexingConfiguration, clientConfiguration)) {
            std::cerr << "Exiting because updateIndexingConfiguration failed." << std::endl;
            cleanup(thingName, certificateARN, certificateID, STACK_NAME,
                    ruleName, false,
                    clientConfiguration);
            return false;
        }
    }

    if (!searchIndex(queryString, clientConfiguration)) {

        std::cerr << "Exiting because searchIndex failed." << std::endl;
        cleanup(thingName, certificateARN, certificateID, STACK_NAME, ruleName,
                false,
                clientConfiguration);
        return false;
    }
```

```
//! Update an AWS IoT thing with attributes.
/*!
  \param thingName: The name for the thing.
  \param attributeMap: A map of key/value attributes/
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::updateThing(const Aws::String &thingName,
                              const std::map<Aws::String, Aws::String> &attributeMap,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::UpdateThingRequest request;
    request.SetThingName(thingName);
    Aws::IoT::Model::AttributePayload attributePayload;
    for (const auto &attribute: attributeMap) {
        attributePayload.AddAttributes(attribute.first, attribute.second);
    }
    request.SetAttributePayload(attributePayload);

    Aws::IoT::Model::UpdateThingOutcome outcome = iotClient.UpdateThing(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated thing " << thingName << std::endl;
    }
    else {
        std::cerr << "Failed to update thing " << thingName << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Describe the endpoint specific to the AWS account making the call.
/*!
  \param endpointResult: String to receive the endpoint result.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::describeEndpoint(Aws::String &endpointResult,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::String endpoint;
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::DescribeEndpointRequest describeEndpointRequest;
    describeEndpointRequest.SetEndpointType(
            "iot:Data-ATS"); // Recommended endpoint type.

    Aws::IoT::Model::DescribeEndpointOutcome outcome = iotClient.DescribeEndpoint(
            describeEndpointRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully described endpoint." << std::endl;
        endpointResult = outcome.GetResult().GetEndpointAddress();
    }
    else {
        std::cerr << "Error describing endpoint" << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}

//! List certificates registered in the AWS account making the call.
/*!
   \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::listCertificates(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::ListCertificatesRequest request;

    Aws::Vector<Aws::IoT::Model::Certificate> allCertificates;
    Aws::String marker; // Used to paginate results.
    do {
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::IoT::Model::ListCertificatesOutcome outcome = iotClient.ListCertificates(
                request);

        if (outcome.IsSuccess()) {
            const Aws::IoT::Model::ListCertificatesResult &result = outcome.GetResult();
            marker = result.GetNextMarker();
            allCertificates.insert(allCertificates.end(),
                                   result.GetCertificates().begin(),
                                   result.GetCertificates().end());
        }
        else {
            std::cerr << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    } while (!marker.empty());

    std::cout << allCertificates.size() << " certificate(s) found." << std::endl;

    for (auto &certificate: allCertificates) {
        std::cout << "Certificate ID: " << certificate.GetCertificateId() << std::endl;
        std::cout << "Certificate ARN: " << certificate.GetCertificateArn()
                  << std::endl;
        std::cout << std::endl;
    }

    return true;
}

//! Update the shadow of an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param document: The state information, in JSON format.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::updateThingShadow(const Aws::String &thingName,
                                    const Aws::String &document,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoTDataPlane::IoTDataPlaneClient iotDataPlaneClient(clientConfiguration);
    Aws::IoTDataPlane::Model::UpdateThingShadowRequest updateThingShadowRequest;
    updateThingShadowRequest.SetThingName(thingName);
    std::shared_ptr<std::stringstream> streamBuf = std::make_shared<std::stringstream>(
            document);
    updateThingShadowRequest.SetBody(streamBuf);
    Aws::IoTDataPlane::Model::UpdateThingShadowOutcome outcome = iotDataPlaneClient.UpdateThingShadow(
            updateThingShadowRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated thing shadow." << std::endl;
    }
    else {
        std::cerr << "Error while updating thing shadow."
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Get the shadow of an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param documentResult: String to receive the state information, in JSON format.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::getThingShadow(const Aws::String &thingName,
                                 Aws::String &documentResult,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoTDataPlane::IoTDataPlaneClient iotClient(clientConfiguration);
    Aws::IoTDataPlane::Model::GetThingShadowRequest request;
    request.SetThingName(thingName);
    auto outcome = iotClient.GetThingShadow(request);
    if (outcome.IsSuccess()) {
        std::stringstream ss;
        ss << outcome.GetResult().GetPayload().rdbuf();
        documentResult = ss.str();
    }
    else {
        std::cerr << "Error getting thing shadow: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Create an AWS IoT rule with an SNS topic as the target.
/*!
  \param ruleName: The name for the rule.
  \param snsTopic: The SNS topic ARN for the action.
  \param sql: The SQL statement used to query the topic.
  \param roleARN: The IAM role ARN for the action.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::IoT::createTopicRule(const Aws::String &ruleName,
                             const Aws::String &snsTopicARN, const Aws::String &sql,
                             const Aws::String &roleARN,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::CreateTopicRuleRequest request;
    request.SetRuleName(ruleName);

    Aws::IoT::Model::SnsAction snsAction;
    snsAction.SetTargetArn(snsTopicARN);
    snsAction.SetRoleArn(roleARN);

    Aws::IoT::Model::Action action;
    action.SetSns(snsAction);

    Aws::IoT::Model::TopicRulePayload topicRulePayload;
    topicRulePayload.SetSql(sql);
    topicRulePayload.SetActions({action});

    request.SetTopicRulePayload(topicRulePayload);
    auto outcome = iotClient.CreateTopicRule(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created topic rule " << ruleName << "." << std::endl;
    }
    else {
        std::cerr << "Error creating topic rule " << ruleName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    return outcome.IsSuccess();
}

//! Lists the AWS IoT topic rules.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::listTopicRules(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::ListTopicRulesRequest request;

    Aws::Vector<Aws::IoT::Model::TopicRuleListItem> allRules;
    Aws::String nextToken; // Used for pagination.
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::IoT::Model::ListTopicRulesOutcome outcome = iotClient.ListTopicRules(
                request);

        if (outcome.IsSuccess()) {
            const Aws::IoT::Model::ListTopicRulesResult &result = outcome.GetResult();
            allRules.insert(allRules.end(),
                            result.GetRules().cbegin(),
                            result.GetRules().cend());

            nextToken = result.GetNextToken();
        }
        else {
            std::cerr << "ListTopicRules error: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

    } while (!nextToken.empty());

    std::cout << "ListTopicRules: " << allRules.size() << " rule(s) found."
              << std::endl;
    for (auto &rule: allRules) {
        std::cout << "  Rule name: " << rule.GetRuleName() << ", rule ARN: "
                  << rule.GetRuleArn() << "." << std::endl;
    }

    return true;
}

//! Query the AWS IoT fleet index.
//! For query information, see https://docs.aws.amazon.com/iot/latest/developerguide/query-syntax.html
/*!
  \param: query: The query string.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::searchIndex(const Aws::String &query,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::SearchIndexRequest request;
    request.SetQueryString(query);

    Aws::Vector<Aws::IoT::Model::ThingDocument> allThingDocuments;
    Aws::String nextToken; // Used for pagination.
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::IoT::Model::SearchIndexOutcome outcome = iotClient.SearchIndex(request);

        if (outcome.IsSuccess()) {
            const Aws::IoT::Model::SearchIndexResult &result = outcome.GetResult();
            allThingDocuments.insert(allThingDocuments.end(),
                                     result.GetThings().cbegin(),
                                     result.GetThings().cend());
            nextToken = result.GetNextToken();

        }
        else {
            std::cerr << "Error in SearchIndex: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!nextToken.empty());

    std::cout << allThingDocuments.size() << " thing document(s) found." << std::endl;
    for (const auto thingDocument: allThingDocuments) {
        std::cout << "  Thing name: " << thingDocument.GetThingName() << "."
                  << std::endl;
    }
    return true;
}
```
リソースをクリーンアップします。  

```
bool
AwsDoc::IoT::cleanup(const Aws::String &thingName, const Aws::String &certificateARN,
                     const Aws::String &certificateID, const Aws::String &stackName,
                     const Aws::String &ruleName, bool askForConfirmation,
                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    bool result = true;

    if (!ruleName.empty() && (!askForConfirmation ||
                               askYesNoQuestion("Delete the rule '" + ruleName +
                                                "'? (y/n) "))) {
        result &= deleteTopicRule(ruleName, clientConfiguration);
    }

    Aws::CloudFormation::CloudFormationClient cloudFormationClient(clientConfiguration);

    if (!stackName.empty() && (!askForConfirmation ||
                               askYesNoQuestion(
                                       "Delete the CloudFormation stack '" + stackName +
                                       "'? (y/n) "))) {
        result &= deleteStack(stackName, clientConfiguration);
    }

    if (!certificateARN.empty() && (!askForConfirmation ||
                                    askYesNoQuestion("Delete the certificate '" +
                                                     certificateARN + "'? (y/n) "))) {
        result &= detachThingPrincipal(certificateARN, thingName, clientConfiguration);
        result &= deleteCertificate(certificateID, clientConfiguration);
    }

    if (!thingName.empty() && (!askForConfirmation ||
                               askYesNoQuestion("Delete the thing '" + thingName +
                                                "'? (y/n) "))) {
        result &= deleteThing(thingName, clientConfiguration);
    }

    return result;
}
```

```
//! Detach a principal from an AWS IoT thing.
/*!
  \param principal: A principal to detach.
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::detachThingPrincipal(const Aws::String &principal,
                                       const Aws::String &thingName,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::DetachThingPrincipalRequest detachThingPrincipalRequest;
    detachThingPrincipalRequest.SetThingName(thingName);
    detachThingPrincipalRequest.SetPrincipal(principal);

    Aws::IoT::Model::DetachThingPrincipalOutcome outcome = iotClient.DetachThingPrincipal(
            detachThingPrincipalRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully detached principal " << principal << " from thing "
                  << thingName << std::endl;
    }
    else {
        std::cerr << "Failed to detach principal " << principal << " from thing "
                  << thingName << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Delete a certificate.
/*!
  \param certificateID: The ID of a certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::deleteCertificate(const Aws::String &certificateID,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::DeleteCertificateRequest request;
    request.SetCertificateId(certificateID);

    Aws::IoT::Model::DeleteCertificateOutcome outcome = iotClient.DeleteCertificate(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted certificate " << certificateID << std::endl;
    }
    else {
        std::cerr << "Error deleting certificate " << certificateID << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Delete an AWS IoT rule.
/*!
  \param ruleName: The name for the rule.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::deleteTopicRule(const Aws::String &ruleName,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::DeleteTopicRuleRequest request;
    request.SetRuleName(ruleName);

    Aws::IoT::Model::DeleteTopicRuleOutcome outcome = iotClient.DeleteTopicRule(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted rule " << ruleName << std::endl;
    }
    else {
        std::cerr << "Failed to delete rule " << ruleName <<
                  ": " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Delete an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::deleteThing(const Aws::String &thingName,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::DeleteThingRequest request;
    request.SetThingName(thingName);
    const auto outcome = iotClient.DeleteThing(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted thing " << thingName << std::endl;
    }
    else {
        std::cerr << "Error deleting thing " << thingName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [AttachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/AttachThingPrincipal)
  + [CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/CreateKeysAndCertificate)
  + [CreateThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/CreateThing)
  + [CreateTopicRule](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/CreateTopicRule)
  + [DeleteCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DeleteCertificate)
  + [DeleteThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DeleteThing)
  + [DeleteTopicRule](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DeleteTopicRule)
  + [DescribeEndpoint](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DescribeEndpoint)
  + [DescribeThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DescribeThing)
  + [DetachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DetachThingPrincipal)
  + [ListCertificates](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/ListCertificates)
  + [ListThings](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/ListThings)
  + [SearchIndex](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/SearchIndex)
  + [UpdateIndexingConfiguration](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/UpdateIndexingConfiguration)
  + [UpdateThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/UpdateThing)

## アクション
<a name="actions"></a>

### `AttachThingPrincipal`
<a name="iot_AttachThingPrincipal_cpp_1_topic"></a>

次のコード例は、`AttachThingPrincipal` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Attach a principal to an AWS IoT thing.
/*!
  \param principal: A principal to attach.
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::attachThingPrincipal(const Aws::String &principal,
                                       const Aws::String &thingName,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient client(clientConfiguration);
    Aws::IoT::Model::AttachThingPrincipalRequest request;
    request.SetPrincipal(principal);
    request.SetThingName(thingName);
    Aws::IoT::Model::AttachThingPrincipalOutcome outcome = client.AttachThingPrincipal(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully attached principal to thing." << std::endl;
    }
    else {
        std::cerr << "Failed to attach principal to thing." <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AttachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/AttachThingPrincipal)」を参照してください。

### `CreateKeysAndCertificate`
<a name="iot_CreateKeysAndCertificate_cpp_1_topic"></a>

次のコード例は、`CreateKeysAndCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Create keys and certificate for an Aws IoT device.
//! This routine will save certificates and keys to an output folder, if provided.
/*!
  \param outputFolder: Location for storing output in files, ignored when string is empty.
  \param certificateARNResult: A string to receive the ARN of the created certificate.
  \param certificateID: A string to receive the ID of the created certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::createKeysAndCertificate(const Aws::String &outputFolder,
                                           Aws::String &certificateARNResult,
                                           Aws::String &certificateID,
                                           const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient client(clientConfiguration);
    Aws::IoT::Model::CreateKeysAndCertificateRequest createKeysAndCertificateRequest;

    Aws::IoT::Model::CreateKeysAndCertificateOutcome outcome =
            client.CreateKeysAndCertificate(createKeysAndCertificateRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created a certificate and keys" << std::endl;
        certificateARNResult = outcome.GetResult().GetCertificateArn();
        certificateID = outcome.GetResult().GetCertificateId();
        std::cout << "Certificate ARN: " << certificateARNResult << ", certificate ID: "
                  << certificateID << std::endl;

        if (!outputFolder.empty()) {
            std::cout << "Writing certificate and keys to the folder '" << outputFolder
                      << "'." << std::endl;
            std::cout << "Be sure these files are stored securely." << std::endl;

            Aws::String certificateFilePath = outputFolder + "/certificate.pem.crt";
            std::ofstream certificateFile(certificateFilePath);
            if (!certificateFile.is_open()) {
                std::cerr << "Error opening certificate file, '" << certificateFilePath
                          << "'."
                          << std::endl;
                return false;
            }
            certificateFile << outcome.GetResult().GetCertificatePem();
            certificateFile.close();

            const Aws::IoT::Model::KeyPair &keyPair = outcome.GetResult().GetKeyPair();

            Aws::String privateKeyFilePath = outputFolder + "/private.pem.key";
            std::ofstream privateKeyFile(privateKeyFilePath);
            if (!privateKeyFile.is_open()) {
                std::cerr << "Error opening private key file, '" << privateKeyFilePath
                          << "'."
                          << std::endl;
                return false;
            }
            privateKeyFile << keyPair.GetPrivateKey();
            privateKeyFile.close();

            Aws::String publicKeyFilePath = outputFolder + "/public.pem.key";
            std::ofstream publicKeyFile(publicKeyFilePath);
            if (!publicKeyFile.is_open()) {
                std::cerr << "Error opening public key file, '" << publicKeyFilePath
                          << "'."
                          << std::endl;
                return false;
            }
            publicKeyFile << keyPair.GetPublicKey();
        }
    }
    else {
        std::cerr << "Error creating keys and certificate: "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/CreateKeysAndCertificate)」を参照してください。

### `CreateThing`
<a name="iot_CreateThing_cpp_1_topic"></a>

次のコード例は、`CreateThing` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Create an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::createThing(const Aws::String &thingName,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::CreateThingRequest createThingRequest;
    createThingRequest.SetThingName(thingName);

    Aws::IoT::Model::CreateThingOutcome outcome = iotClient.CreateThing(
            createThingRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created thing " << thingName << std::endl;
    }
    else {
        std::cerr << "Failed to create thing " << thingName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/CreateThing)」を参照してください。

### `CreateTopicRule`
<a name="iot_CreateTopicRule_cpp_1_topic"></a>

次のコード例は、`CreateTopicRule` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Create an AWS IoT rule with an SNS topic as the target.
/*!
  \param ruleName: The name for the rule.
  \param snsTopic: The SNS topic ARN for the action.
  \param sql: The SQL statement used to query the topic.
  \param roleARN: The IAM role ARN for the action.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::IoT::createTopicRule(const Aws::String &ruleName,
                             const Aws::String &snsTopicARN, const Aws::String &sql,
                             const Aws::String &roleARN,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::CreateTopicRuleRequest request;
    request.SetRuleName(ruleName);

    Aws::IoT::Model::SnsAction snsAction;
    snsAction.SetTargetArn(snsTopicARN);
    snsAction.SetRoleArn(roleARN);

    Aws::IoT::Model::Action action;
    action.SetSns(snsAction);

    Aws::IoT::Model::TopicRulePayload topicRulePayload;
    topicRulePayload.SetSql(sql);
    topicRulePayload.SetActions({action});

    request.SetTopicRulePayload(topicRulePayload);
    auto outcome = iotClient.CreateTopicRule(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created topic rule " << ruleName << "." << std::endl;
    }
    else {
        std::cerr << "Error creating topic rule " << ruleName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateTopicRule](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/CreateTopicRule)」を参照してください。

### `DeleteCertificate`
<a name="iot_DeleteCertificate_cpp_1_topic"></a>

次のコード例は、`DeleteCertificate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Delete a certificate.
/*!
  \param certificateID: The ID of a certificate.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::deleteCertificate(const Aws::String &certificateID,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::DeleteCertificateRequest request;
    request.SetCertificateId(certificateID);

    Aws::IoT::Model::DeleteCertificateOutcome outcome = iotClient.DeleteCertificate(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted certificate " << certificateID << std::endl;
    }
    else {
        std::cerr << "Error deleting certificate " << certificateID << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteCertificate](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DeleteCertificate)」を参照してください。

### `DeleteThing`
<a name="iot_DeleteThing_cpp_1_topic"></a>

次のコード例は、`DeleteThing` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::deleteThing(const Aws::String &thingName,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::DeleteThingRequest request;
    request.SetThingName(thingName);
    const auto outcome = iotClient.DeleteThing(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted thing " << thingName << std::endl;
    }
    else {
        std::cerr << "Error deleting thing " << thingName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「DeleteThing」を参照してください。[https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DeleteThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DeleteThing)

### `DeleteTopicRule`
<a name="iot_DeleteTopicRule_cpp_1_topic"></a>

次のコード例は、`DeleteTopicRule` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an AWS IoT rule.
/*!
  \param ruleName: The name for the rule.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::deleteTopicRule(const Aws::String &ruleName,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::DeleteTopicRuleRequest request;
    request.SetRuleName(ruleName);

    Aws::IoT::Model::DeleteTopicRuleOutcome outcome = iotClient.DeleteTopicRule(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted rule " << ruleName << std::endl;
    }
    else {
        std::cerr << "Failed to delete rule " << ruleName <<
                  ": " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[DeleteTopicRule](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DeleteTopicRule)」を参照してください。

### `DescribeEndpoint`
<a name="iot_DescribeEndpoint_cpp_1_topic"></a>

次のコード例は、`DescribeEndpoint` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Describe the endpoint specific to the AWS account making the call.
/*!
  \param endpointResult: String to receive the endpoint result.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::describeEndpoint(Aws::String &endpointResult,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::String endpoint;
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::DescribeEndpointRequest describeEndpointRequest;
    describeEndpointRequest.SetEndpointType(
            "iot:Data-ATS"); // Recommended endpoint type.

    Aws::IoT::Model::DescribeEndpointOutcome outcome = iotClient.DescribeEndpoint(
            describeEndpointRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully described endpoint." << std::endl;
        endpointResult = outcome.GetResult().GetEndpointAddress();
    }
    else {
        std::cerr << "Error describing endpoint" << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeEndpoint](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DescribeEndpoint)」を参照してください。

### `DescribeThing`
<a name="iot_DescribeThing_cpp_1_topic"></a>

次のコード例は、`DescribeThing` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Describe an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::describeThing(const Aws::String &thingName,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::DescribeThingRequest request;
    request.SetThingName(thingName);

    Aws::IoT::Model::DescribeThingOutcome outcome = iotClient.DescribeThing(request);

    if (outcome.IsSuccess()) {
        const Aws::IoT::Model::DescribeThingResult &result = outcome.GetResult();
        std::cout << "Retrieved thing '" << result.GetThingName() << "'" << std::endl;
        std::cout << "thingArn: " << result.GetThingArn() << std::endl;
        std::cout << result.GetAttributes().size() << " attribute(s) retrieved"
                  << std::endl;
        for (const auto &attribute: result.GetAttributes()) {
            std::cout << "  attribute: " << attribute.first << "=" << attribute.second
                      << std::endl;
        }
    }
    else {
        std::cerr << "Error describing thing " << thingName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DescribeThing)」を参照してください。

### `DetachThingPrincipal`
<a name="iot_DetachThingPrincipal_cpp_1_topic"></a>

次のコード例は、`DetachThingPrincipal` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Detach a principal from an AWS IoT thing.
/*!
  \param principal: A principal to detach.
  \param thingName: The name for the thing.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::detachThingPrincipal(const Aws::String &principal,
                                       const Aws::String &thingName,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::DetachThingPrincipalRequest detachThingPrincipalRequest;
    detachThingPrincipalRequest.SetThingName(thingName);
    detachThingPrincipalRequest.SetPrincipal(principal);

    Aws::IoT::Model::DetachThingPrincipalOutcome outcome = iotClient.DetachThingPrincipal(
            detachThingPrincipalRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully detached principal " << principal << " from thing "
                  << thingName << std::endl;
    }
    else {
        std::cerr << "Failed to detach principal " << principal << " from thing "
                  << thingName << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DetachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/DetachThingPrincipal)」を参照してください。

### `ListCertificates`
<a name="iot_ListCertificates_cpp_1_topic"></a>

次のコード例は、`ListCertificates` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! List certificates registered in the AWS account making the call.
/*!
   \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::listCertificates(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::ListCertificatesRequest request;

    Aws::Vector<Aws::IoT::Model::Certificate> allCertificates;
    Aws::String marker; // Used to paginate results.
    do {
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::IoT::Model::ListCertificatesOutcome outcome = iotClient.ListCertificates(
                request);

        if (outcome.IsSuccess()) {
            const Aws::IoT::Model::ListCertificatesResult &result = outcome.GetResult();
            marker = result.GetNextMarker();
            allCertificates.insert(allCertificates.end(),
                                   result.GetCertificates().begin(),
                                   result.GetCertificates().end());
        }
        else {
            std::cerr << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    } while (!marker.empty());

    std::cout << allCertificates.size() << " certificate(s) found." << std::endl;

    for (auto &certificate: allCertificates) {
        std::cout << "Certificate ID: " << certificate.GetCertificateId() << std::endl;
        std::cout << "Certificate ARN: " << certificate.GetCertificateArn()
                  << std::endl;
        std::cout << std::endl;
    }

    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンスの*「[ListCertificates](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/ListCertificates)」を参照してください。

### `SearchIndex`
<a name="iot_SearchIndex_cpp_1_topic"></a>

次のコード例は、`SearchIndex` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Query the AWS IoT fleet index.
//! For query information, see https://docs.aws.amazon.com/iot/latest/developerguide/query-syntax.html
/*!
  \param: query: The query string.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::searchIndex(const Aws::String &query,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::SearchIndexRequest request;
    request.SetQueryString(query);

    Aws::Vector<Aws::IoT::Model::ThingDocument> allThingDocuments;
    Aws::String nextToken; // Used for pagination.
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::IoT::Model::SearchIndexOutcome outcome = iotClient.SearchIndex(request);

        if (outcome.IsSuccess()) {
            const Aws::IoT::Model::SearchIndexResult &result = outcome.GetResult();
            allThingDocuments.insert(allThingDocuments.end(),
                                     result.GetThings().cbegin(),
                                     result.GetThings().cend());
            nextToken = result.GetNextToken();

        }
        else {
            std::cerr << "Error in SearchIndex: " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!nextToken.empty());

    std::cout << allThingDocuments.size() << " thing document(s) found." << std::endl;
    for (const auto thingDocument: allThingDocuments) {
        std::cout << "  Thing name: " << thingDocument.GetThingName() << "."
                  << std::endl;
    }
    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[SearchIndex](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/SearchIndex)」を参照してください。

### `UpdateIndexingConfiguration`
<a name="iot_UpdateIndexingConfiguration_cpp_1_topic"></a>

次のコード例は、`UpdateIndexingConfiguration` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Update the indexing configuration.
/*!
  \param thingIndexingConfiguration: A ThingIndexingConfiguration object which is ignored if not set.
  \param thingGroupIndexingConfiguration: A ThingGroupIndexingConfiguration object which is ignored if not set.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::updateIndexingConfiguration(
        const Aws::IoT::Model::ThingIndexingConfiguration &thingIndexingConfiguration,
        const Aws::IoT::Model::ThingGroupIndexingConfiguration &thingGroupIndexingConfiguration,
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);

    Aws::IoT::Model::UpdateIndexingConfigurationRequest request;

    if (thingIndexingConfiguration.ThingIndexingModeHasBeenSet()) {
        request.SetThingIndexingConfiguration(thingIndexingConfiguration);
    }

    if (thingGroupIndexingConfiguration.ThingGroupIndexingModeHasBeenSet()) {
        request.SetThingGroupIndexingConfiguration(thingGroupIndexingConfiguration);
    }

    Aws::IoT::Model::UpdateIndexingConfigurationOutcome outcome = iotClient.UpdateIndexingConfiguration(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "UpdateIndexingConfiguration succeeded." << std::endl;
    }
    else {
        std::cerr << "UpdateIndexingConfiguration failed."
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[UpdateIndexingConfiguration](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/UpdateIndexingConfiguration)」を参照してください。

### `UpdateThing`
<a name="iot_UpdateThing_cpp_1_topic"></a>

次のコード例は、`UpdateThing` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Update an AWS IoT thing with attributes.
/*!
  \param thingName: The name for the thing.
  \param attributeMap: A map of key/value attributes/
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::updateThing(const Aws::String &thingName,
                              const std::map<Aws::String, Aws::String> &attributeMap,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoT::IoTClient iotClient(clientConfiguration);
    Aws::IoT::Model::UpdateThingRequest request;
    request.SetThingName(thingName);
    Aws::IoT::Model::AttributePayload attributePayload;
    for (const auto &attribute: attributeMap) {
        attributePayload.AddAttributes(attribute.first, attribute.second);
    }
    request.SetAttributePayload(attributePayload);

    Aws::IoT::Model::UpdateThingOutcome outcome = iotClient.UpdateThing(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated thing " << thingName << std::endl;
    }
    else {
        std::cerr << "Failed to update thing " << thingName << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateThing](https://docs.aws.amazon.com/goto/SdkForCpp/iot-2015-05-28/UpdateThing)」を参照してください。

# AWS IoT data SDK for C\$1\$1 を使用した例
<a name="cpp_1_iot-data-plane_code_examples"></a>

次のコード例は、 AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT data。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetThingShadow`
<a name="iot-data-plane_GetThingShadow_cpp_1_topic"></a>

次のコード例は、`GetThingShadow` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Get the shadow of an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param documentResult: String to receive the state information, in JSON format.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::getThingShadow(const Aws::String &thingName,
                                 Aws::String &documentResult,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoTDataPlane::IoTDataPlaneClient iotClient(clientConfiguration);
    Aws::IoTDataPlane::Model::GetThingShadowRequest request;
    request.SetThingName(thingName);
    auto outcome = iotClient.GetThingShadow(request);
    if (outcome.IsSuccess()) {
        std::stringstream ss;
        ss << outcome.GetResult().GetPayload().rdbuf();
        documentResult = ss.str();
    }
    else {
        std::cerr << "Error getting thing shadow: " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「* API リファレンスAWS SDK for C\$1\$1 *」の「[GetThingShadow](https://docs.aws.amazon.com/goto/SdkForCpp/iot-data-2015-05-28/GetThingShadow)」を参照してください。

### `UpdateThingShadow`
<a name="iot-data-plane_UpdateThingShadow_cpp_1_topic"></a>

次のコード例は、`UpdateThingShadow` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
//! Update the shadow of an AWS IoT thing.
/*!
  \param thingName: The name for the thing.
  \param document: The state information, in JSON format.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::IoT::updateThingShadow(const Aws::String &thingName,
                                    const Aws::String &document,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::IoTDataPlane::IoTDataPlaneClient iotDataPlaneClient(clientConfiguration);
    Aws::IoTDataPlane::Model::UpdateThingShadowRequest updateThingShadowRequest;
    updateThingShadowRequest.SetThingName(thingName);
    std::shared_ptr<std::stringstream> streamBuf = std::make_shared<std::stringstream>(
            document);
    updateThingShadowRequest.SetBody(streamBuf);
    Aws::IoTDataPlane::Model::UpdateThingShadowOutcome outcome = iotDataPlaneClient.UpdateThingShadow(
            updateThingShadowRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated thing shadow." << std::endl;
    }
    else {
        std::cerr << "Error while updating thing shadow."
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[UpdateThingShadow](https://docs.aws.amazon.com/goto/SdkForCpp/iot-data-2015-05-28/UpdateThingShadow)」を参照してください。

# SDK for C\$1\$1 を使用した Lambda の例
<a name="cpp_1_lambda_code_examples"></a>

次のコード例は、Lambda AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Lambda
<a name="lambda_Hello_cpp_1_topic"></a>

次のコード例は、Lambda の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda/hello_lambda#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS lambda)

# Set this project's name.
project("hello_lambda")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_lambda.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1lambda.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/lambda/LambdaClient.h>
#include <aws/lambda/model/ListFunctionsRequest.h>
#include <iostream>

/*
 *  A "Hello Lambda" starter application which initializes an AWS Lambda (Lambda) client and lists the Lambda functions.
 *
 *  main function
 *
 *  Usage: 'hello_lambda'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::Lambda::LambdaClient lambdaClient(clientConfig);
        std::vector<Aws::String> functions;
        Aws::String marker; // Used for pagination.

        do {
            Aws::Lambda::Model::ListFunctionsRequest request;
            if (!marker.empty()) {
                request.SetMarker(marker);
            }

            Aws::Lambda::Model::ListFunctionsOutcome outcome = lambdaClient.ListFunctions(
                    request);

            if (outcome.IsSuccess()) {
                const Aws::Lambda::Model::ListFunctionsResult &listFunctionsResult = outcome.GetResult();
                std::cout << listFunctionsResult.GetFunctions().size()
                          << " lambda functions were retrieved." << std::endl;

                for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: listFunctionsResult.GetFunctions()) {
                    functions.push_back(functionConfiguration.GetFunctionName());
                    std::cout << functions.size() << "  "
                              << functionConfiguration.GetDescription() << std::endl;
                    std::cout << "   "
                              << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime(
                                      functionConfiguration.GetRuntime()) << ": "
                              << functionConfiguration.GetHandler()
                              << std::endl;
                }
                marker = listFunctionsResult.GetNextMarker();
            } else {
                std::cerr << "Error with Lambda::ListFunctions. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = 1;
                break;
            }
        } while (!marker.empty());
    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListFunctions)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
//! Get started with functions scenario.
/*!
 \param clientConfig: AWS client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::Lambda::getStartedWithFunctionsScenario(
        const Aws::Client::ClientConfiguration &clientConfig) {

    Aws::Lambda::LambdaClient client(clientConfig);

    // 1. Create an AWS Identity and Access Management (IAM) role for Lambda function.
    Aws::String roleArn;
    if (!getIamRoleArn(roleArn, clientConfig)) {
        return false;
    }

    // 2. Create a Lambda function.
    int seconds = 0;
    do {
        Aws::Lambda::Model::CreateFunctionRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        request.SetDescription(LAMBDA_DESCRIPTION); // Optional.
#if USE_CPP_LAMBDA_FUNCTION
        request.SetRuntime(Aws::Lambda::Model::Runtime::provided_al2);
        request.SetTimeout(15);
        request.SetMemorySize(128);

        // Assume the AWS Lambda function was built in Docker with same architecture
        // as this code.
#if  defined(__x86_64__)
        request.SetArchitectures({Aws::Lambda::Model::Architecture::x86_64});
#elif defined(__aarch64__)
        request.SetArchitectures({Aws::Lambda::Model::Architecture::arm64});
#else
#error "Unimplemented architecture"
#endif // defined(architecture)
#else
        request.SetRuntime(Aws::Lambda::Model::Runtime::python3_9);
#endif
        request.SetRole(roleArn);
        request.SetHandler(LAMBDA_HANDLER_NAME);
        request.SetPublish(true);
        Aws::Lambda::Model::FunctionCode code;
        std::ifstream ifstream(INCREMENT_LAMBDA_CODE.c_str(),
                               std::ios_base::in | std::ios_base::binary);
        if (!ifstream.is_open()) {
            std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl;

#if USE_CPP_LAMBDA_FUNCTION
            std::cerr
                    << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. "
                    << std::endl;
#endif
            deleteIamRole(clientConfig);
            return false;
        }

        Aws::StringStream buffer;
        buffer << ifstream.rdbuf();

        code.SetZipFile(Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(),
                                               buffer.str().length()));
        request.SetCode(code);

        Aws::Lambda::Model::CreateFunctionOutcome outcome = client.CreateFunction(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda function was successfully created. " << seconds
                      << " seconds elapsed." << std::endl;
            break;
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::Lambda::LambdaErrors::INVALID_PARAMETER_VALUE &&
                 outcome.GetError().GetMessage().find("role") >= 0) {
            if ((seconds % 5) == 0) { // Log status every 10 seconds.
                std::cout
                        << "Waiting for the IAM role to become available as a CreateFunction parameter. "
                        << seconds
                        << " seconds elapsed." << std::endl;

                std::cout << outcome.GetError().GetMessage() << std::endl;
            }
        }
        else {
            std::cerr << "Error with CreateFunction. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            deleteIamRole(clientConfig);
            return false;
        }
        ++seconds;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    } while (60 > seconds);

    std::cout << "The current Lambda function increments 1 by an input." << std::endl;

    // 3.  Invoke the Lambda function.
    {
        int increment = askQuestionForInt("Enter an increment integer: ");

        Aws::Lambda::Model::InvokeResult invokeResult;
        Aws::Utils::Json::JsonValue jsonPayload;
        jsonPayload.WithString("action", "increment");
        jsonPayload.WithInteger("number", increment);
        if (invokeLambdaFunction(jsonPayload, Aws::Lambda::Model::LogType::Tail,
                                 invokeResult, client)) {
            Aws::Utils::Json::JsonValue jsonValue(invokeResult.GetPayload());
            Aws::Map<Aws::String, Aws::Utils::Json::JsonView> values =
                    jsonValue.View().GetAllObjects();
            auto iter = values.find("result");
            if (iter != values.end() && iter->second.IsIntegerType()) {
                {
                    std::cout << INCREMENT_RESUlT_PREFIX
                              << iter->second.AsInteger() << std::endl;
                }
            }
            else {
                std::cout << "There was an error in execution. Here is the log."
                          << std::endl;
                Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode(
                        invokeResult.GetLogResult());
                std::cout << "With log " << buffer.GetUnderlyingData() << std::endl;
            }
        }
    }

    std::cout
            << "The Lambda function will now be updated with new code. Press return to continue, ";
    Aws::String answer;
    std::getline(std::cin, answer);

    // 4.  Update the Lambda function code.
    {
        Aws::Lambda::Model::UpdateFunctionCodeRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        std::ifstream ifstream(CALCULATOR_LAMBDA_CODE.c_str(),
                               std::ios_base::in | std::ios_base::binary);
        if (!ifstream.is_open()) {
            std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl;

#if USE_CPP_LAMBDA_FUNCTION
            std::cerr
                    << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. "
                    << std::endl;
#endif
            deleteLambdaFunction(client);
            deleteIamRole(clientConfig);
            return false;
        }

        Aws::StringStream buffer;
        buffer << ifstream.rdbuf();
        request.SetZipFile(
                Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(),
                                       buffer.str().length()));
        request.SetPublish(true);

        Aws::Lambda::Model::UpdateFunctionCodeOutcome outcome = client.UpdateFunctionCode(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda code was successfully updated." << std::endl;
        }
        else {
            std::cerr << "Error with Lambda::UpdateFunctionCode. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    }

    std::cout
            << "This function uses an environment variable to control the logging level."
            << std::endl;
    std::cout
            << "UpdateFunctionConfiguration will be used to set the LOG_LEVEL to DEBUG."
            << std::endl;
    seconds = 0;

    // 5.  Update the Lambda function configuration.
    do {
        ++seconds;
        std::this_thread::sleep_for(std::chrono::seconds(1));
        Aws::Lambda::Model::UpdateFunctionConfigurationRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        Aws::Lambda::Model::Environment environment;
        environment.AddVariables("LOG_LEVEL", "DEBUG");
        request.SetEnvironment(environment);

        Aws::Lambda::Model::UpdateFunctionConfigurationOutcome outcome = client.UpdateFunctionConfiguration(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda configuration was successfully updated."
                      << std::endl;
            break;
        }

            // RESOURCE_IN_USE: function code update not completed.
        else if (outcome.GetError().GetErrorType() !=
                 Aws::Lambda::LambdaErrors::RESOURCE_IN_USE) {
            if ((seconds % 10) == 0) { // Log status every 10 seconds.
                std::cout << "Lambda function update in progress . After " << seconds
                          << " seconds elapsed." << std::endl;
            }
        }
        else {
            std::cerr << "Error with Lambda::UpdateFunctionConfiguration. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }

    } while (0 < seconds);

    if (0 > seconds) {
        std::cerr << "Function failed to become active." << std::endl;
    }
    else {
        std::cout << "Updated function active after " << seconds << " seconds."
                  << std::endl;
    }

    std::cout
            << "\nThe new code applies an arithmetic operator to two variables, x an y."
            << std::endl;
    std::vector<Aws::String> operators = {"plus", "minus", "times", "divided-by"};
    for (size_t i = 0; i < operators.size(); ++i) {
        std::cout << "   " << i + 1 << " " << operators[i] << std::endl;
    }

    // 6.  Invoke the updated Lambda function.
    do {
        int operatorIndex = askQuestionForIntRange("Select an operator index 1 - 4 ", 1,
                                                   4);
        int x = askQuestionForInt("Enter an integer for the x value ");
        int y = askQuestionForInt("Enter an integer for the y value ");

        Aws::Utils::Json::JsonValue calculateJsonPayload;
        calculateJsonPayload.WithString("action", operators[operatorIndex - 1]);
        calculateJsonPayload.WithInteger("x", x);
        calculateJsonPayload.WithInteger("y", y);
        Aws::Lambda::Model::InvokeResult calculatedResult;
        if (invokeLambdaFunction(calculateJsonPayload,
                                 Aws::Lambda::Model::LogType::Tail,
                                 calculatedResult, client)) {
            Aws::Utils::Json::JsonValue jsonValue(calculatedResult.GetPayload());
            Aws::Map<Aws::String, Aws::Utils::Json::JsonView> values =
                    jsonValue.View().GetAllObjects();
            auto iter = values.find("result");
            if (iter != values.end() && iter->second.IsIntegerType()) {
                std::cout << ARITHMETIC_RESUlT_PREFIX << x << " "
                          << operators[operatorIndex - 1] << " "
                          << y << " is " << iter->second.AsInteger() << std::endl;
            }
            else if (iter != values.end() && iter->second.IsFloatingPointType()) {
                std::cout << ARITHMETIC_RESUlT_PREFIX << x << " "
                          << operators[operatorIndex - 1] << " "
                          << y << " is " << iter->second.AsDouble() << std::endl;
            }
            else {
                std::cout << "There was an error in execution. Here is the log."
                          << std::endl;
                Aws::Utils::ByteBuffer buffer = Aws::Utils::HashingUtils::Base64Decode(
                        calculatedResult.GetLogResult());
                std::cout << "With log " << buffer.GetUnderlyingData() << std::endl;
            }
        }

        answer = askQuestion("Would you like to try another operation? (y/n) ");
    } while (answer == "y");

    std::cout
            << "A list of the lambda functions will be retrieved. Press return to continue, ";
    std::getline(std::cin, answer);

    // 7.  List the Lambda functions.

    std::vector<Aws::String> functions;
    Aws::String marker;

    do {
        Aws::Lambda::Model::ListFunctionsRequest request;
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::Lambda::Model::ListFunctionsOutcome outcome = client.ListFunctions(
                request);

        if (outcome.IsSuccess()) {
            const Aws::Lambda::Model::ListFunctionsResult &result = outcome.GetResult();
            std::cout << result.GetFunctions().size()
                      << " lambda functions were retrieved." << std::endl;

            for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: result.GetFunctions()) {
                functions.push_back(functionConfiguration.GetFunctionName());
                std::cout << functions.size() << "  "
                          << functionConfiguration.GetDescription() << std::endl;
                std::cout << "   "
                          << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime(
                                  functionConfiguration.GetRuntime()) << ": "
                          << functionConfiguration.GetHandler()
                          << std::endl;
            }
            marker = result.GetNextMarker();
        }
        else {
            std::cerr << "Error with Lambda::ListFunctions. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    } while (!marker.empty());

    // 8.  Get a Lambda function.
    if (!functions.empty()) {
        std::stringstream question;
        question << "Choose a function to retrieve between 1 and " << functions.size()
                 << " ";
        int functionIndex = askQuestionForIntRange(question.str(), 1,
                                                   static_cast<int>(functions.size()));

        Aws::String functionName = functions[functionIndex - 1];

        Aws::Lambda::Model::GetFunctionRequest request;
        request.SetFunctionName(functionName);

        Aws::Lambda::Model::GetFunctionOutcome outcome = client.GetFunction(request);

        if (outcome.IsSuccess()) {
            std::cout << "Function retrieve.\n" <<
                      outcome.GetResult().GetConfiguration().Jsonize().View().WriteReadable()
                      << std::endl;
        }
        else {
            std::cerr << "Error with Lambda::GetFunction. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    }

    std::cout << "The resources will be deleted. Press return to continue, ";
    std::getline(std::cin, answer);

    // 9.  Delete the Lambda function.
    bool result = deleteLambdaFunction(client);

    // 10. Delete the IAM role.
    return result && deleteIamRole(clientConfig);
}

//! Routine which invokes a Lambda function and returns the result.
/*!
 \param jsonPayload: Payload for invoke function.
 \param logType: Log type setting for invoke function.
 \param invokeResult: InvokeResult object to receive the result.
 \param client: Lambda client.
 \return bool: Successful completion.
 */
bool
AwsDoc::Lambda::invokeLambdaFunction(const Aws::Utils::Json::JsonValue &jsonPayload,
                                     Aws::Lambda::Model::LogType logType,
                                     Aws::Lambda::Model::InvokeResult &invokeResult,
                                     const Aws::Lambda::LambdaClient &client) {
    int seconds = 0;
    bool result = false;
    /*
     * In this example, the Invoke function can be called before recently created resources are
     * available.  The Invoke function is called repeatedly until the resources are
     * available.
     */
    do {
        Aws::Lambda::Model::InvokeRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        request.SetLogType(logType);
        std::shared_ptr<Aws::IOStream> payload = Aws::MakeShared<Aws::StringStream>(
                "FunctionTest");
        *payload << jsonPayload.View().WriteReadable();
        request.SetBody(payload);
        request.SetContentType("application/json");
        Aws::Lambda::Model::InvokeOutcome outcome = client.Invoke(request);

        if (outcome.IsSuccess()) {
            invokeResult = std::move(outcome.GetResult());
            result = true;
            break;
        }

            // ACCESS_DENIED: because the role is not available yet.
            // RESOURCE_CONFLICT: because the Lambda function is being created or updated.
        else if ((outcome.GetError().GetErrorType() ==
                  Aws::Lambda::LambdaErrors::ACCESS_DENIED) ||
                 (outcome.GetError().GetErrorType() ==
                  Aws::Lambda::LambdaErrors::RESOURCE_CONFLICT)) {
            if ((seconds % 5) == 0) { // Log status every 10 seconds.
                std::cout << "Waiting for the invoke api to be available, status " <<
                          ((outcome.GetError().GetErrorType() ==
                            Aws::Lambda::LambdaErrors::ACCESS_DENIED ?
                            "ACCESS_DENIED" : "RESOURCE_CONFLICT")) << ". " << seconds
                          << " seconds elapsed." << std::endl;
            }
        }
        else {
            std::cerr << "Error with Lambda::InvokeRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            break;
        }
        ++seconds;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    } while (seconds < 60);

    return result;
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/CreateFunction)
  + [DeleteFunction](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteFunction)
  + [GetFunction](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetFunction)
  + [Invoke](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/Invoke)
  + [ListFunctions](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListFunctions)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionCode)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionConfiguration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_cpp_1_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Lambda::LambdaClient client(clientConfig);

        Aws::Lambda::Model::CreateFunctionRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        request.SetDescription(LAMBDA_DESCRIPTION); // Optional.
#if USE_CPP_LAMBDA_FUNCTION
        request.SetRuntime(Aws::Lambda::Model::Runtime::provided_al2);
        request.SetTimeout(15);
        request.SetMemorySize(128);

        // Assume the AWS Lambda function was built in Docker with same architecture
        // as this code.
#if  defined(__x86_64__)
        request.SetArchitectures({Aws::Lambda::Model::Architecture::x86_64});
#elif defined(__aarch64__)
        request.SetArchitectures({Aws::Lambda::Model::Architecture::arm64});
#else
#error "Unimplemented architecture"
#endif // defined(architecture)
#else
        request.SetRuntime(Aws::Lambda::Model::Runtime::python3_9);
#endif
        request.SetRole(roleArn);
        request.SetHandler(LAMBDA_HANDLER_NAME);
        request.SetPublish(true);
        Aws::Lambda::Model::FunctionCode code;
        std::ifstream ifstream(INCREMENT_LAMBDA_CODE.c_str(),
                               std::ios_base::in | std::ios_base::binary);
        if (!ifstream.is_open()) {
            std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl;

#if USE_CPP_LAMBDA_FUNCTION
            std::cerr
                    << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. "
                    << std::endl;
#endif
            deleteIamRole(clientConfig);
            return false;
        }

        Aws::StringStream buffer;
        buffer << ifstream.rdbuf();

        code.SetZipFile(Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(),
                                               buffer.str().length()));
        request.SetCode(code);

        Aws::Lambda::Model::CreateFunctionOutcome outcome = client.CreateFunction(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda function was successfully created. " << seconds
                      << " seconds elapsed." << std::endl;
            break;
        }

        else {
            std::cerr << "Error with CreateFunction. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            deleteIamRole(clientConfig);
            return false;
        }
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[CreateFunction](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/CreateFunction)」を参照してください。**

### `DeleteFunction`
<a name="lambda_DeleteFunction_cpp_1_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Lambda::LambdaClient client(clientConfig);

    Aws::Lambda::Model::DeleteFunctionRequest request;
    request.SetFunctionName(LAMBDA_NAME);

    Aws::Lambda::Model::DeleteFunctionOutcome outcome = client.DeleteFunction(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "The lambda function was successfully deleted." << std::endl;
    }
    else {
        std::cerr << "Error with Lambda::DeleteFunction. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteFunction](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/DeleteFunction)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_cpp_1_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Lambda::LambdaClient client(clientConfig);

        Aws::Lambda::Model::GetFunctionRequest request;
        request.SetFunctionName(functionName);

        Aws::Lambda::Model::GetFunctionOutcome outcome = client.GetFunction(request);

        if (outcome.IsSuccess()) {
            std::cout << "Function retrieve.\n" <<
                      outcome.GetResult().GetConfiguration().Jsonize().View().WriteReadable()
                      << std::endl;
        }
        else {
            std::cerr << "Error with Lambda::GetFunction. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetFunction](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/GetFunction)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_cpp_1_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Lambda::LambdaClient client(clientConfig);

        Aws::Lambda::Model::InvokeRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        request.SetLogType(logType);
        std::shared_ptr<Aws::IOStream> payload = Aws::MakeShared<Aws::StringStream>(
                "FunctionTest");
        *payload << jsonPayload.View().WriteReadable();
        request.SetBody(payload);
        request.SetContentType("application/json");
        Aws::Lambda::Model::InvokeOutcome outcome = client.Invoke(request);

        if (outcome.IsSuccess()) {
            invokeResult = std::move(outcome.GetResult());
            result = true;
            break;
        }

        else {
            std::cerr << "Error with Lambda::InvokeRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            break;
        }
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[Invoke](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/Invoke)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_cpp_1_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Lambda::LambdaClient client(clientConfig);

    std::vector<Aws::String> functions;
    Aws::String marker;

    do {
        Aws::Lambda::Model::ListFunctionsRequest request;
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::Lambda::Model::ListFunctionsOutcome outcome = client.ListFunctions(
                request);

        if (outcome.IsSuccess()) {
            const Aws::Lambda::Model::ListFunctionsResult &result = outcome.GetResult();
            std::cout << result.GetFunctions().size()
                      << " lambda functions were retrieved." << std::endl;

            for (const Aws::Lambda::Model::FunctionConfiguration &functionConfiguration: result.GetFunctions()) {
                functions.push_back(functionConfiguration.GetFunctionName());
                std::cout << functions.size() << "  "
                          << functionConfiguration.GetDescription() << std::endl;
                std::cout << "   "
                          << Aws::Lambda::Model::RuntimeMapper::GetNameForRuntime(
                                  functionConfiguration.GetRuntime()) << ": "
                          << functionConfiguration.GetHandler()
                          << std::endl;
            }
            marker = result.GetNextMarker();
        }
        else {
            std::cerr << "Error with Lambda::ListFunctions. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    } while (!marker.empty());
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/ListFunctions)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_cpp_1_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Lambda::LambdaClient client(clientConfig);

        Aws::Lambda::Model::UpdateFunctionCodeRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        std::ifstream ifstream(CALCULATOR_LAMBDA_CODE.c_str(),
                               std::ios_base::in | std::ios_base::binary);
        if (!ifstream.is_open()) {
            std::cerr << "Error opening file " << INCREMENT_LAMBDA_CODE << "." << std::endl;

#if USE_CPP_LAMBDA_FUNCTION
            std::cerr
                    << "The cpp Lambda function must be built following the instructions in the cpp_lambda/README.md file. "
                    << std::endl;
#endif
            deleteLambdaFunction(client);
            deleteIamRole(clientConfig);
            return false;
        }

        Aws::StringStream buffer;
        buffer << ifstream.rdbuf();
        request.SetZipFile(
                Aws::Utils::ByteBuffer((unsigned char *) buffer.str().c_str(),
                                       buffer.str().length()));
        request.SetPublish(true);

        Aws::Lambda::Model::UpdateFunctionCodeOutcome outcome = client.UpdateFunctionCode(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda code was successfully updated." << std::endl;
        }
        else {
            std::cerr << "Error with Lambda::UpdateFunctionCode. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionCode)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_cpp_1_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region in which the bucket was created (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::Lambda::LambdaClient client(clientConfig);

        Aws::Lambda::Model::UpdateFunctionConfigurationRequest request;
        request.SetFunctionName(LAMBDA_NAME);
        Aws::Lambda::Model::Environment environment;
        environment.AddVariables("LOG_LEVEL", "DEBUG");
        request.SetEnvironment(environment);

        Aws::Lambda::Model::UpdateFunctionConfigurationOutcome outcome = client.UpdateFunctionConfiguration(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "The lambda configuration was successfully updated."
                      << std::endl;
            break;
        }

        else {
            std::cerr << "Error with Lambda::UpdateFunctionConfiguration. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForCpp/lambda-2015-03-31/UpdateFunctionConfiguration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_cpp_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for C\$1\$1**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

# SDK for C\$1\$1 を使用した MediaConvert の例
<a name="cpp_1_mediaconvert_code_examples"></a>

次のコード例は、MediaConvert AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateJob`
<a name="mediaconvert_CreateJob_cpp_1_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
//! Create an AWS Elemental MediaConvert job.
/*!
  \param mediaConvertRole: An Amazon Resource Name (ARN) for the AWS Identity and
                           Access Management (IAM) role for the job.
  \param fileInput: A URI to an input file that is stored in Amazon Simple Storage Service
                    (Amazon S3) or on an HTTP(S) server.
  \param fileOutput: A URI for an Amazon S3 output location and the output file name base.
  \param jobSettingsFile: An optional JSON settings file.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::MediaConvert::createJob(const Aws::String &mediaConvertRole,
                                     const Aws::String &fileInput,
                                     const Aws::String &fileOutput,
                                     const Aws::String &jobSettingsFile,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::MediaConvert::Model::CreateJobRequest createJobRequest;

    createJobRequest.SetRole(mediaConvertRole);
    Aws::Http::HeaderValueCollection hvc;
    hvc.emplace("Customer", "Amazon");
    createJobRequest.SetUserMetadata(hvc);

    if (!jobSettingsFile.empty()) // Use a JSON file for the job settings.
    {
        std::ifstream jobSettingsStream(jobSettingsFile, std::ios::ate);
        if (!jobSettingsStream) {
            std::cerr << "Unable to open the job template file." << std::endl;
            return false;
        }
        std::vector<char> buffer(jobSettingsStream.tellg());
        jobSettingsStream.seekg(0);
        jobSettingsStream.read(buffer.data(), buffer.size());
        std::string jobSettingsJSON(buffer.data(), buffer.size());
        size_t pos = jobSettingsJSON.find(INPUT_FILE_PLACEHOLDER);
        if (pos != std::string::npos) {
            jobSettingsJSON.replace(pos, strlen(INPUT_FILE_PLACEHOLDER), fileInput);
        }

        pos = jobSettingsJSON.find(OUTPUT_FILE_PLACEHOLDER);
        if (pos != std::string::npos) {
            jobSettingsJSON.replace(pos, strlen(OUTPUT_FILE_PLACEHOLDER), fileOutput);
        }
        Aws::Utils::Json::JsonValue jsonValue(jobSettingsJSON);
        Aws::MediaConvert::Model::JobSettings jobSettings(jsonValue);

        createJobRequest.SetSettings(jobSettings);
    }
    else { // Configure the job settings programmatically.
        Aws::MediaConvert::Model::JobSettings jobSettings;
        jobSettings.SetAdAvailOffset(0);
        Aws::MediaConvert::Model::TimecodeConfig timecodeConfig;
        timecodeConfig.SetSource(Aws::MediaConvert::Model::TimecodeSource::EMBEDDED);
        jobSettings.SetTimecodeConfig(timecodeConfig);

        // Configure the output group.
        Aws::MediaConvert::Model::OutputGroup outputGroup;
        outputGroup.SetName("File Group");
        Aws::MediaConvert::Model::OutputGroupSettings outputGroupSettings;
        outputGroupSettings.SetType(
                Aws::MediaConvert::Model::OutputGroupType::FILE_GROUP_SETTINGS);
        Aws::MediaConvert::Model::FileGroupSettings fileGroupSettings;
        fileGroupSettings.SetDestination(fileOutput);
        outputGroupSettings.SetFileGroupSettings(fileGroupSettings);
        outputGroup.SetOutputGroupSettings(outputGroupSettings);

        Aws::MediaConvert::Model::Output output;
        output.SetNameModifier("_1");

        Aws::MediaConvert::Model::VideoDescription videoDescription;
        videoDescription.SetScalingBehavior(
                Aws::MediaConvert::Model::ScalingBehavior::DEFAULT);
        videoDescription.SetTimecodeInsertion(
                Aws::MediaConvert::Model::VideoTimecodeInsertion::DISABLED);
        videoDescription.SetAntiAlias(Aws::MediaConvert::Model::AntiAlias::ENABLED);
        videoDescription.SetSharpness(50);
        videoDescription.SetAfdSignaling(Aws::MediaConvert::Model::AfdSignaling::NONE);
        videoDescription.SetDropFrameTimecode(
                Aws::MediaConvert::Model::DropFrameTimecode::ENABLED);
        videoDescription.SetRespondToAfd(Aws::MediaConvert::Model::RespondToAfd::NONE);
        videoDescription.SetColorMetadata(
                Aws::MediaConvert::Model::ColorMetadata::INSERT);

        Aws::MediaConvert::Model::VideoCodecSettings videoCodecSettings;
        videoCodecSettings.SetCodec(Aws::MediaConvert::Model::VideoCodec::H_264);
        Aws::MediaConvert::Model::H264Settings h264Settings;
        h264Settings.SetNumberReferenceFrames(3);
        h264Settings.SetSyntax(Aws::MediaConvert::Model::H264Syntax::DEFAULT);
        h264Settings.SetSoftness(0);
        h264Settings.SetGopClosedCadence(1);
        h264Settings.SetGopSize(90);
        h264Settings.SetSlices(1);
        h264Settings.SetGopBReference(
                Aws::MediaConvert::Model::H264GopBReference::DISABLED);
        h264Settings.SetSlowPal(Aws::MediaConvert::Model::H264SlowPal::DISABLED);
        h264Settings.SetSpatialAdaptiveQuantization(
                Aws::MediaConvert::Model::H264SpatialAdaptiveQuantization::ENABLED);
        h264Settings.SetTemporalAdaptiveQuantization(
                Aws::MediaConvert::Model::H264TemporalAdaptiveQuantization::ENABLED);
        h264Settings.SetFlickerAdaptiveQuantization(
                Aws::MediaConvert::Model::H264FlickerAdaptiveQuantization::DISABLED);
        h264Settings.SetEntropyEncoding(
                Aws::MediaConvert::Model::H264EntropyEncoding::CABAC);
        h264Settings.SetBitrate(5000000);
        h264Settings.SetFramerateControl(
                Aws::MediaConvert::Model::H264FramerateControl::SPECIFIED);
        h264Settings.SetRateControlMode(
                Aws::MediaConvert::Model::H264RateControlMode::CBR);
        h264Settings.SetCodecProfile(Aws::MediaConvert::Model::H264CodecProfile::MAIN);
        h264Settings.SetTelecine(Aws::MediaConvert::Model::H264Telecine::NONE);
        h264Settings.SetMinIInterval(0);
        h264Settings.SetAdaptiveQuantization(
                Aws::MediaConvert::Model::H264AdaptiveQuantization::HIGH);
        h264Settings.SetCodecLevel(Aws::MediaConvert::Model::H264CodecLevel::AUTO);
        h264Settings.SetFieldEncoding(
                Aws::MediaConvert::Model::H264FieldEncoding::PAFF);
        h264Settings.SetSceneChangeDetect(
                Aws::MediaConvert::Model::H264SceneChangeDetect::ENABLED);
        h264Settings.SetQualityTuningLevel(
                Aws::MediaConvert::Model::H264QualityTuningLevel::SINGLE_PASS);
        h264Settings.SetFramerateConversionAlgorithm(
                Aws::MediaConvert::Model::H264FramerateConversionAlgorithm::DUPLICATE_DROP);
        h264Settings.SetUnregisteredSeiTimecode(
                Aws::MediaConvert::Model::H264UnregisteredSeiTimecode::DISABLED);
        h264Settings.SetGopSizeUnits(
                Aws::MediaConvert::Model::H264GopSizeUnits::FRAMES);
        h264Settings.SetParControl(Aws::MediaConvert::Model::H264ParControl::SPECIFIED);
        h264Settings.SetNumberBFramesBetweenReferenceFrames(2);
        h264Settings.SetRepeatPps(Aws::MediaConvert::Model::H264RepeatPps::DISABLED);
        h264Settings.SetFramerateNumerator(30);
        h264Settings.SetFramerateDenominator(1);
        h264Settings.SetParNumerator(1);
        h264Settings.SetParDenominator(1);
        videoCodecSettings.SetH264Settings(h264Settings);
        videoDescription.SetCodecSettings(videoCodecSettings);
        output.SetVideoDescription(videoDescription);

        Aws::MediaConvert::Model::AudioDescription audioDescription;
        audioDescription.SetLanguageCodeControl(
                Aws::MediaConvert::Model::AudioLanguageCodeControl::FOLLOW_INPUT);
        audioDescription.SetAudioSourceName(AUDIO_SOURCE_NAME);
        Aws::MediaConvert::Model::AudioCodecSettings audioCodecSettings;
        audioCodecSettings.SetCodec(Aws::MediaConvert::Model::AudioCodec::AAC);
        Aws::MediaConvert::Model::AacSettings aacSettings;
        aacSettings.SetAudioDescriptionBroadcasterMix(
                Aws::MediaConvert::Model::AacAudioDescriptionBroadcasterMix::NORMAL);
        aacSettings.SetRateControlMode(
                Aws::MediaConvert::Model::AacRateControlMode::CBR);
        aacSettings.SetCodecProfile(Aws::MediaConvert::Model::AacCodecProfile::LC);
        aacSettings.SetCodingMode(
                Aws::MediaConvert::Model::AacCodingMode::CODING_MODE_2_0);
        aacSettings.SetRawFormat(Aws::MediaConvert::Model::AacRawFormat::NONE);
        aacSettings.SetSampleRate(48000);
        aacSettings.SetSpecification(Aws::MediaConvert::Model::AacSpecification::MPEG4);
        aacSettings.SetBitrate(64000);
        audioCodecSettings.SetAacSettings(aacSettings);
        audioDescription.SetCodecSettings(audioCodecSettings);
        Aws::Vector<Aws::MediaConvert::Model::AudioDescription> audioDescriptions;
        audioDescriptions.emplace_back(audioDescription);
        output.SetAudioDescriptions(audioDescriptions);

        Aws::MediaConvert::Model::ContainerSettings mp4container;
        mp4container.SetContainer(Aws::MediaConvert::Model::ContainerType::MP4);
        Aws::MediaConvert::Model::Mp4Settings mp4Settings;
        mp4Settings.SetCslgAtom(Aws::MediaConvert::Model::Mp4CslgAtom::INCLUDE);
        mp4Settings.SetFreeSpaceBox(Aws::MediaConvert::Model::Mp4FreeSpaceBox::EXCLUDE);
        mp4Settings.SetMoovPlacement(
                Aws::MediaConvert::Model::Mp4MoovPlacement::PROGRESSIVE_DOWNLOAD);
        mp4container.SetMp4Settings(mp4Settings);
        output.SetContainerSettings(mp4container);

        outputGroup.AddOutputs(output);
        jobSettings.AddOutputGroups(outputGroup);

        // Configure inputs.
        Aws::MediaConvert::Model::Input input;
        input.SetFilterEnable(Aws::MediaConvert::Model::InputFilterEnable::AUTO);
        input.SetPsiControl(Aws::MediaConvert::Model::InputPsiControl::USE_PSI);
        input.SetFilterStrength(0);
        input.SetDeblockFilter(Aws::MediaConvert::Model::InputDeblockFilter::DISABLED);
        input.SetDenoiseFilter(Aws::MediaConvert::Model::InputDenoiseFilter::DISABLED);
        input.SetTimecodeSource(
                Aws::MediaConvert::Model::InputTimecodeSource::EMBEDDED);
        input.SetFileInput(fileInput);

        Aws::MediaConvert::Model::AudioSelector audioSelector;
        audioSelector.SetOffset(0);
        audioSelector.SetDefaultSelection(
                Aws::MediaConvert::Model::AudioDefaultSelection::NOT_DEFAULT);
        audioSelector.SetProgramSelection(1);
        audioSelector.SetSelectorType(
                Aws::MediaConvert::Model::AudioSelectorType::TRACK);
        audioSelector.AddTracks(1);
        input.AddAudioSelectors(AUDIO_SOURCE_NAME, audioSelector);

        Aws::MediaConvert::Model::VideoSelector videoSelector;
        videoSelector.SetColorSpace(Aws::MediaConvert::Model::ColorSpace::FOLLOW);
        input.SetVideoSelector(videoSelector);

        jobSettings.AddInputs(input);

        createJobRequest.SetSettings(jobSettings);
    }

    Aws::MediaConvert::MediaConvertClient client(clientConfiguration);
    Aws::MediaConvert::Model::CreateJobOutcome outcome = client.CreateJob(
            createJobRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Job successfully created with ID - "
                  << outcome.GetResult().GetJob().GetId() << std::endl;
    }
    else {
        std::cerr << "Error CreateJob - " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[CreateJob](https://docs.aws.amazon.com/goto/SdkForCpp/mediaconvert-2017-08-29/CreateJob)」を参照してください。**

### `GetJob`
<a name="mediaconvert_GetJob_cpp_1_topic"></a>

次のコード例は、`GetJob` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
//! Retrieve the information for a specific completed transcoding job.
/*!
  \param jobID: A job ID.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::MediaConvert::getJob(const Aws::String &jobID,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::MediaConvert::MediaConvertClient client(clientConfiguration);

    Aws::MediaConvert::Model::GetJobRequest request;
    request.SetId(jobID);
    const Aws::MediaConvert::Model::GetJobOutcome outcome = client.GetJob(
            request);
    if (outcome.IsSuccess()) {
        std::cout << outcome.GetResult().GetJob().Jsonize().View().WriteReadable()
                  << std::endl;
    }
    else {
        std::cerr << "DescribeEndpoints error - " << outcome.GetError().GetMessage()
                  << std::endl;
    }


    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetJob](https://docs.aws.amazon.com/goto/SdkForCpp/mediaconvert-2017-08-29/GetJob)」を参照してください。

### `ListJobs`
<a name="mediaconvert_ListJobs_cpp_1_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
//! Retrieve a list of created jobs.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::MediaConvert::listJobs(
        const Aws::Client::ClientConfiguration &clientConfiguration) {

    Aws::MediaConvert::MediaConvertClient client(clientConfiguration);

    bool result = true;
    Aws::String nextToken; // Used to handle paginated results.
    do {
        Aws::MediaConvert::Model::ListJobsRequest request;
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }
        const Aws::MediaConvert::Model::ListJobsOutcome outcome = client.ListJobs(
                request);
        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::MediaConvert::Model::Job> &jobs =
                    outcome.GetResult().GetJobs();
            std::cout << jobs.size() << " jobs retrieved." << std::endl;
            for (const Aws::MediaConvert::Model::Job &job: jobs) {
                std::cout << "  " << job.Jsonize().View().WriteReadable() << std::endl;
            }

            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cerr << "DescribeEndpoints error - " << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
            break;

        }
    } while (!nextToken.empty());


    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListJobs](https://docs.aws.amazon.com/goto/SdkForCpp/mediaconvert-2017-08-29/ListJobs)」を参照してください。

# SDK for C\$1\$1 を使用した Amazon RDS の例
<a name="cpp_1_rds_code_examples"></a>

次のコード例は、Amazon RDS AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon RDS
<a name="rds_Hello_cpp_1_topic"></a>

次のコード例は、Amazon RDS の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds/hello_rds#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS rds)

# Set this project's name.
project("hello_rds")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_rds.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1rds.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/rds/RDSClient.h>
#include <aws/rds/model/DescribeDBInstancesRequest.h>
#include <iostream>

/*
 *  A "Hello Rds" starter application which initializes an Amazon Relational Database Service (Amazon RDS) client and
 *  describes the Amazon RDS instances.
 *
 *  main function
 *
 *  Usage: 'hello_rds'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::RDS::RDSClient rdsClient(clientConfig);
        Aws::String marker;
        std::vector<Aws::String> instanceDBIDs;

        do {
            Aws::RDS::Model::DescribeDBInstancesRequest request;

            if (!marker.empty()) {
                request.SetMarker(marker);
            }

            Aws::RDS::Model::DescribeDBInstancesOutcome outcome =
                    rdsClient.DescribeDBInstances(request);

            if (outcome.IsSuccess()) {
                for (auto &instance: outcome.GetResult().GetDBInstances()) {
                    instanceDBIDs.push_back(instance.GetDBInstanceIdentifier());
                }
                marker = outcome.GetResult().GetMarker();
            } else {
                result = 1;
                std::cerr << "Error with RDS::DescribeDBInstances. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                break;
            }
        } while (!marker.empty());

        std::cout << instanceDBIDs.size() << " RDS instances found." << std::endl;
        for (auto &instanceDBID: instanceDBIDs) {
            std::cout << "   Instance: " << instanceDBID << std::endl;
        }
    }

    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBInstances)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="rds_Scenario_GetStartedInstances_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム DB パラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用するように設定した DB インスタンスを作成します。DB インスタンスにはデータベースも含まれています。
+ インスタンスのスナップショットを取得します。
+ インスタンスとパラメータグループを削除します。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Routine which creates an Amazon RDS instance and demonstrates several operations
//! on that instance.
/*!
 \sa gettingStartedWithDBInstances()
 \param clientConfiguration: AWS client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::gettingStartedWithDBInstances(
        const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::RDS::RDSClient client(clientConfig);

    printAsterisksLine();
    std::cout << "Welcome to the Amazon Relational Database Service (Amazon RDS)"
              << std::endl;
    std::cout << "get started with DB instances demo." << std::endl;
    printAsterisksLine();

    std::cout << "Checking for an existing DB parameter group named '" <<
              PARAMETER_GROUP_NAME << "'." << std::endl;
    Aws::String dbParameterGroupFamily("Undefined");
    bool parameterGroupFound = true;
    {
        // 1. Check if the DB parameter group already exists.
        Aws::RDS::Model::DescribeDBParameterGroupsRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);

        Aws::RDS::Model::DescribeDBParameterGroupsOutcome outcome =
                client.DescribeDBParameterGroups(request);

        if (outcome.IsSuccess()) {
            std::cout << "DB parameter group named '" <<
                      PARAMETER_GROUP_NAME << "' already exists." << std::endl;
            dbParameterGroupFamily = outcome.GetResult().GetDBParameterGroups()[0].GetDBParameterGroupFamily();
        }
        else if (outcome.GetError().GetErrorType() ==
                 Aws::RDS::RDSErrors::D_B_PARAMETER_GROUP_NOT_FOUND_FAULT) {
            std::cout << "DB parameter group named '" <<
                      PARAMETER_GROUP_NAME << "' does not exist." << std::endl;
            parameterGroupFound = false;
        }
        else {
            std::cerr << "Error with RDS::DescribeDBParameterGroups. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    if (!parameterGroupFound) {
        Aws::Vector<Aws::RDS::Model::DBEngineVersion> engineVersions;

        // 2. Get available engine versions for the specified engine.
        if (!getDBEngineVersions(DB_ENGINE, NO_PARAMETER_GROUP_FAMILY,
                                 engineVersions, client)) {
            return false;
        }

        std::cout << "Getting available database engine versions for " << DB_ENGINE
                  << "."
                  << std::endl;
        std::vector<Aws::String> families;
        for (const Aws::RDS::Model::DBEngineVersion &version: engineVersions) {
            Aws::String family = version.GetDBParameterGroupFamily();
            if (std::find(families.begin(), families.end(), family) ==
                families.end()) {
                families.push_back(family);
                std::cout << "  " << families.size() << ": " << family << std::endl;
            }
        }

        int choice = askQuestionForIntRange("Which family do you want to use? ", 1,
                                            static_cast<int>(families.size()));
        dbParameterGroupFamily = families[choice - 1];
    }
    if (!parameterGroupFound) {
        // 3.  Create a DB parameter group.
        Aws::RDS::Model::CreateDBParameterGroupRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        request.SetDBParameterGroupFamily(dbParameterGroupFamily);
        request.SetDescription("Example parameter group.");

        Aws::RDS::Model::CreateDBParameterGroupOutcome outcome =
                client.CreateDBParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully created."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::CreateDBParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    }

    printAsterisksLine();
    std::cout << "Let's set some parameter values in your parameter group."
              << std::endl;

    Aws::String marker;
    Aws::Vector<Aws::RDS::Model::Parameter> autoIncrementParameters;
    // 4.  Get the parameters in the DB parameter group.
    if (!getDBParameters(PARAMETER_GROUP_NAME, AUTO_INCREMENT_PREFIX, NO_SOURCE,
                         autoIncrementParameters,
                         client)) {
        cleanUpResources(PARAMETER_GROUP_NAME, "", client);
        return false;
    }

    Aws::Vector<Aws::RDS::Model::Parameter> updateParameters;

    for (Aws::RDS::Model::Parameter &autoIncParameter: autoIncrementParameters) {
        if (autoIncParameter.GetIsModifiable() &&
            (autoIncParameter.GetDataType() == "integer")) {
            std::cout << "The " << autoIncParameter.GetParameterName()
                      << " is described as: " <<
                      autoIncParameter.GetDescription() << "." << std::endl;
            if (autoIncParameter.ParameterValueHasBeenSet()) {
                std::cout << "The current value is "
                          << autoIncParameter.GetParameterValue()
                          << "." << std::endl;
            }
            std::vector<int> splitValues = splitToInts(
                    autoIncParameter.GetAllowedValues(), '-');
            if (splitValues.size() == 2) {
                int newValue = askQuestionForIntRange(
                        Aws::String("Enter a new value in the range ") +
                        autoIncParameter.GetAllowedValues() + ": ",
                        splitValues[0], splitValues[1]);
                autoIncParameter.SetParameterValue(std::to_string(newValue));
                updateParameters.push_back(autoIncParameter);

            }
            else {
                std::cerr << "Error parsing " << autoIncParameter.GetAllowedValues()
                          << std::endl;
            }
        }
    }

    {
        // 5.  Modify the auto increment parameters in the group.
        Aws::RDS::Model::ModifyDBParameterGroupRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        request.SetParameters(updateParameters);

        Aws::RDS::Model::ModifyDBParameterGroupOutcome outcome =
                client.ModifyDBParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully modified."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::ModifyDBParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
    }

    std::cout
            << "You can get a list of parameters you've set by specifying a source of 'user'."
            << std::endl;

    Aws::Vector<Aws::RDS::Model::Parameter> userParameters;
    // 6.  Display the modified parameters in the group.
    if (!getDBParameters(PARAMETER_GROUP_NAME, NO_NAME_PREFIX, "user", userParameters,
                         client)) {
        cleanUpResources(PARAMETER_GROUP_NAME, "", client);
        return false;
    }

    for (const auto &userParameter: userParameters) {
        std::cout << "  " << userParameter.GetParameterName() << ", " <<
                  userParameter.GetDescription() << ", parameter value - "
                  << userParameter.GetParameterValue() << std::endl;
    }

    printAsterisksLine();
    std::cout << "Checking for an existing DB instance." << std::endl;

    Aws::RDS::Model::DBInstance dbInstance;
    // 7.  Check if the DB instance already exists.
    if (!describeDBInstance(DB_INSTANCE_IDENTIFIER, dbInstance, client)) {
        cleanUpResources(PARAMETER_GROUP_NAME, "", client);
        return false;
    }

    if (dbInstance.DbInstancePortHasBeenSet()) {
        std::cout << "The DB instance already exists." << std::endl;
    }
    else {
        std::cout << "Let's create a DB instance." << std::endl;
        const Aws::String administratorName = askQuestion(
                "Enter an administrator username for the database: ");
        const Aws::String administratorPassword = askQuestion(
                "Enter a password for the administrator (at least 8 characters): ");
        Aws::Vector<Aws::RDS::Model::DBEngineVersion> engineVersions;

        // 8.  Get a list of available engine versions.
        if (!getDBEngineVersions(DB_ENGINE, dbParameterGroupFamily, engineVersions,
                                 client)) {
            cleanUpResources(PARAMETER_GROUP_NAME, "", client);
            return false;
        }

        std::cout << "The available engines for your parameter group are:" << std::endl;

        int index = 1;
        for (const Aws::RDS::Model::DBEngineVersion &engineVersion: engineVersions) {
            std::cout << "  " << index << ": " << engineVersion.GetEngineVersion()
                      << std::endl;
            ++index;
        }
        int choice = askQuestionForIntRange("Which engine do you want to use? ", 1,
                                            static_cast<int>(engineVersions.size()));
        const Aws::RDS::Model::DBEngineVersion engineVersion = engineVersions[choice -
                                                                              1];

        Aws::String dbInstanceClass;
        // 9.  Get a list of micro instance classes.
        if (!chooseMicroDBInstanceClass(engineVersion.GetEngine(),
                                        engineVersion.GetEngineVersion(),
                                        dbInstanceClass,
                                        client)) {
            cleanUpResources(PARAMETER_GROUP_NAME, "", client);
            return false;
        }

        std::cout << "Creating a DB instance named '" << DB_INSTANCE_IDENTIFIER
                  << "' and database '" << DB_NAME << "'.\n"
                  << "The DB instance is configured to use your custom parameter group '"
                  << PARAMETER_GROUP_NAME << "',\n"
                  << "selected engine version " << engineVersion.GetEngineVersion()
                  << ",\n"
                  << "selected DB instance class '" << dbInstanceClass << "',"
                  << " and " << DB_ALLOCATED_STORAGE << " GiB of " << DB_STORAGE_TYPE
                  << " storage.\nThis typically takes several minutes." << std::endl;

        Aws::RDS::Model::CreateDBInstanceRequest request;
        request.SetDBName(DB_NAME);
        request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER);
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        request.SetEngine(engineVersion.GetEngine());
        request.SetEngineVersion(engineVersion.GetEngineVersion());
        request.SetDBInstanceClass(dbInstanceClass);
        request.SetStorageType(DB_STORAGE_TYPE);
        request.SetAllocatedStorage(DB_ALLOCATED_STORAGE);
        request.SetMasterUsername(administratorName);
        request.SetMasterUserPassword(administratorPassword);

        Aws::RDS::Model::CreateDBInstanceOutcome outcome =
                client.CreateDBInstance(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB instance creation has started."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::CreateDBInstance. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanUpResources(PARAMETER_GROUP_NAME, "", client);
            return false;
        }
    }

    std::cout << "Waiting for the DB instance to become available." << std::endl;

    int counter = 0;
    // 11. Wait for the DB instance to become available.
    do {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        ++counter;
        if (counter > 900) {
            std::cerr << "Wait for instance to become available timed out ofter "
                      << counter
                      << " seconds." << std::endl;
            cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
            return false;
        }

        dbInstance = Aws::RDS::Model::DBInstance();
        if (!describeDBInstance(DB_INSTANCE_IDENTIFIER, dbInstance, client)) {
            cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
            return false;
        }

        if ((counter % 20) == 0) {
            std::cout << "Current DB instance status is '"
                      << dbInstance.GetDBInstanceStatus()
                      << "' after " << counter << " seconds." << std::endl;
        }
    } while (dbInstance.GetDBInstanceStatus() != "available");

    if (dbInstance.GetDBInstanceStatus() == "available") {
        std::cout << "The DB instance has been created." << std::endl;
    }

    printAsterisksLine();

    // 12. Display the connection string that can be used to connect a 'mysql' shell to the database.
    displayConnection(dbInstance);

    printAsterisksLine();

    if (askYesNoQuestion(
            "Do you want to create a snapshot of your DB instance (y/n)? ")) {
        Aws::String snapshotID(DB_INSTANCE_IDENTIFIER + "-" +
                               Aws::String(Aws::Utils::UUID::RandomUUID()));
        {
            std::cout << "Creating a snapshot named " << snapshotID << "." << std::endl;
            std::cout << "This typically takes a few minutes." << std::endl;

            // 13. Create a snapshot of the DB instance.
            Aws::RDS::Model::CreateDBSnapshotRequest request;
            request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER);
            request.SetDBSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::CreateDBSnapshotOutcome outcome =
                    client.CreateDBSnapshot(request);

            if (outcome.IsSuccess()) {
                std::cout << "Snapshot creation has started."
                          << std::endl;
            }
            else {
                std::cerr << "Error with RDS::CreateDBSnapshot. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }
        }

        std::cout << "Waiting for snapshot to become available." << std::endl;

        Aws::RDS::Model::DBSnapshot snapshot;
        counter = 0;
        do {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            ++counter;
            if (counter > 600) {
                std::cerr << "Wait for snapshot to be available timed out ofter "
                          << counter
                          << " seconds." << std::endl;
                cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }

            // 14. Wait for the snapshot to become available.
            Aws::RDS::Model::DescribeDBSnapshotsRequest request;
            request.SetDBSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::DescribeDBSnapshotsOutcome outcome =
                    client.DescribeDBSnapshots(request);

            if (outcome.IsSuccess()) {
                snapshot = outcome.GetResult().GetDBSnapshots()[0];
            }
            else {
                std::cerr << "Error with RDS::DescribeDBSnapshots. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }

            if ((counter % 20) == 0) {
                std::cout << "Current snapshot status is '"
                          << snapshot.GetStatus()
                          << "' after " << counter << " seconds." << std::endl;
            }
        } while (snapshot.GetStatus() != "available");

        if (snapshot.GetStatus() != "available") {
            std::cout << "A snapshot has been created." << std::endl;
        }
    }

    printAsterisksLine();

    bool result = true;
    if (askYesNoQuestion(
            "Do you want to delete the DB instance and parameter group (y/n)? ")) {
        result = cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
    }

    return result;
}


//! Routine which gets DB parameters using the 'DescribeDBParameters' api.
/*!
 \sa getDBParameters()
 \param parameterGroupName: The name of the parameter group.
 \param namePrefix: Prefix string to filter results by parameter name.
 \param source: A source such as 'user', ignored if empty.
 \param parametersResult: Vector of 'Parameter' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::getDBParameters(const Aws::String &parameterGroupName,
                                  const Aws::String &namePrefix,
                                  const Aws::String &source,
                                  Aws::Vector<Aws::RDS::Model::Parameter> &parametersResult,
                                  const Aws::RDS::RDSClient &client) {
    Aws::String marker;
    do {
        Aws::RDS::Model::DescribeDBParametersRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }
        if (!source.empty()) {
            request.SetSource(source);
        }

        Aws::RDS::Model::DescribeDBParametersOutcome outcome =
                client.DescribeDBParameters(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::Parameter> &parameters =
                    outcome.GetResult().GetParameters();
            for (const Aws::RDS::Model::Parameter &parameter: parameters) {
                if (!namePrefix.empty()) {
                    if (parameter.GetParameterName().find(namePrefix) == 0) {
                        parametersResult.push_back(parameter);
                    }
                }
                else {
                    parametersResult.push_back(parameter);
                }
            }

            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with RDS::DescribeDBParameters. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    return true;
}


//! Routine which gets available DB engine versions for an engine name and
//! an optional parameter group family.
/*!
 \sa getDBEngineVersions()
 \param engineName: A DB engine name.
 \param parameterGroupFamily: A parameter group family name, ignored if empty.
 \param engineVersionsResult: Vector of 'DBEngineVersion' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::getDBEngineVersions(const Aws::String &engineName,
                                      const Aws::String &parameterGroupFamily,
                                      Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersionsResult,
                                      const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBEngineVersionsRequest request;
    request.SetEngine(engineName);
    if (!parameterGroupFamily.empty()) {
        request.SetDBParameterGroupFamily(parameterGroupFamily);
    }

    engineVersionsResult.clear();
    Aws::String marker; // Used for pagination.

    do {
        if (!marker.empty()) {
            request.SetMarker(marker);
        }


        Aws::RDS::Model::DescribeDBEngineVersionsOutcome outcome =
                client.DescribeDBEngineVersions(request);

        if (outcome.IsSuccess()) {
            auto &engineVersions = outcome.GetResult().GetDBEngineVersions();
            engineVersionsResult.insert(engineVersionsResult.end(), engineVersions.begin(),
                                        engineVersions.end());
            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with RDS::DescribeDBEngineVersionsRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }

    } while (!marker.empty());


    return true;
}


//! Routine which gets a DB instance description.
/*!
 \sa describeDBInstance()
 \param dbInstanceIdentifier: A DB instance identifier.
 \param instanceResult: The 'DBInstance' object containing the description.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::describeDBInstance(const Aws::String &dbInstanceIdentifier,
                                     Aws::RDS::Model::DBInstance &instanceResult,
                                     const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBInstancesRequest request;
    request.SetDBInstanceIdentifier(dbInstanceIdentifier);

    Aws::RDS::Model::DescribeDBInstancesOutcome outcome =
            client.DescribeDBInstances(request);

    bool result = true;
    if (outcome.IsSuccess()) {
        instanceResult = outcome.GetResult().GetDBInstances()[0];
    }
    else if (outcome.GetError().GetErrorType() !=
             Aws::RDS::RDSErrors::D_B_INSTANCE_NOT_FOUND_FAULT) {
        result = false;
        std::cerr << "Error with RDS::DescribeDBInstances. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
        // This example does not log an error if the DB instance does not exist.
        // Instead, instanceResult is set to empty.
    else {
        instanceResult = Aws::RDS::Model::DBInstance();
    }

    return result;
}


//! Routine which gets available 'micro' DB instance classes, displays the list
//! to the user, and returns the user selection.
/*!
 \sa chooseMicroDBInstanceClass()
 \param engineName: The DB engine name.
 \param engineVersion: The DB engine version.
 \param dbInstanceClass: String for DB instance class chosen by the user.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::chooseMicroDBInstanceClass(const Aws::String &engine,
                                             const Aws::String &engineVersion,
                                             Aws::String &dbInstanceClass,
                                             const Aws::RDS::RDSClient &client) {
    std::vector<Aws::String> instanceClasses;
    Aws::String marker;
    do {
        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsRequest request;
        request.SetEngine(engine);
        request.SetEngineVersion(engineVersion);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsOutcome outcome =
                client.DescribeOrderableDBInstanceOptions(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::OrderableDBInstanceOption> &options =
                    outcome.GetResult().GetOrderableDBInstanceOptions();
            for (const Aws::RDS::Model::OrderableDBInstanceOption &option: options) {
                const Aws::String &instanceClass = option.GetDBInstanceClass();
                if (instanceClass.find("micro") != std::string::npos) {
                    if (std::find(instanceClasses.begin(), instanceClasses.end(),
                                  instanceClass) ==
                        instanceClasses.end()) {
                        instanceClasses.push_back(instanceClass);
                    }
                }
            }
            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with RDS::DescribeOrderableDBInstanceOptions. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    std::cout << "The available micro DB instance classes for your database engine are:"
              << std::endl;
    for (int i = 0; i < instanceClasses.size(); ++i) {
        std::cout << "   " << i + 1 << ": " << instanceClasses[i] << std::endl;
    }

    int choice = askQuestionForIntRange(
            "Which micro DB instance class do you want to use? ",
            1, static_cast<int>(instanceClasses.size()));
    dbInstanceClass = instanceClasses[choice - 1];
    return true;
}

//! Routine which deletes resources created by the scenario.
/*!
\sa cleanUpResources()
\param parameterGroupName: A parameter group name, this may be empty.
\param dbInstanceIdentifier: A DB instance identifier, this may be empty.
\param client: 'RDSClient' instance.
\return bool: Successful completion.
*/
bool AwsDoc::RDS::cleanUpResources(const Aws::String &parameterGroupName,
                                   const Aws::String &dbInstanceIdentifier,
                                   const Aws::RDS::RDSClient &client) {
    bool result = true;
    if (!dbInstanceIdentifier.empty()) {
        {
            // 15. Delete the DB instance.
            Aws::RDS::Model::DeleteDBInstanceRequest request;
            request.SetDBInstanceIdentifier(dbInstanceIdentifier);
            request.SetSkipFinalSnapshot(true);
            request.SetDeleteAutomatedBackups(true);

            Aws::RDS::Model::DeleteDBInstanceOutcome outcome =
                    client.DeleteDBInstance(request);

            if (outcome.IsSuccess()) {
                std::cout << "DB instance deletion has started."
                          << std::endl;
            }
            else {
                std::cerr << "Error with RDS::DeleteDBInstance. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }

        std::cout
                << "Waiting for DB instance to delete before deleting the parameter group."
                << std::endl;
        std::cout << "This may take a while." << std::endl;

        int counter = 0;
        Aws::RDS::Model::DBInstance dbInstance;
        do {
            std::this_thread::sleep_for(std::chrono::seconds(1));
            ++counter;
            if (counter > 800) {
                std::cerr << "Wait for instance to delete timed out ofter " << counter
                          << " seconds." << std::endl;
                return false;
            }

            dbInstance = Aws::RDS::Model::DBInstance();
            // 16. Wait for the DB instance to be deleted.
            if (!describeDBInstance(dbInstanceIdentifier, dbInstance, client)) {
                return false;
            }

            if (dbInstance.DBInstanceIdentifierHasBeenSet() && (counter % 20) == 0) {
                std::cout << "Current DB instance status is '"
                          << dbInstance.GetDBInstanceStatus()
                          << "' after " << counter << " seconds." << std::endl;
            }
        } while (dbInstance.DBInstanceIdentifierHasBeenSet());
    }

    if (!parameterGroupName.empty()) {
        // 17. Delete the parameter group.
        Aws::RDS::Model::DeleteDBParameterGroupRequest request;
        request.SetDBParameterGroupName(parameterGroupName);

        Aws::RDS::Model::DeleteDBParameterGroupOutcome outcome =
                client.DeleteDBParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully deleted."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::DeleteDBParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
    }

    return result;
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBInstance)
  + [CreateDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBParameterGroup)
  + [CreateDBSnapshot](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBSnapshot)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBInstance)
  + [DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBParameterGroup)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBInstances)
  + [DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBParameterGroups)
  + [DescribeDBParameters](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBParameters)
  + [DescribeDBSnapshots](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBSnapshots)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/ModifyDBParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_cpp_1_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::CreateDBInstanceRequest request;
        request.SetDBName(DB_NAME);
        request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER);
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        request.SetEngine(engineVersion.GetEngine());
        request.SetEngineVersion(engineVersion.GetEngineVersion());
        request.SetDBInstanceClass(dbInstanceClass);
        request.SetStorageType(DB_STORAGE_TYPE);
        request.SetAllocatedStorage(DB_ALLOCATED_STORAGE);
        request.SetMasterUsername(administratorName);
        request.SetMasterUserPassword(administratorPassword);

        Aws::RDS::Model::CreateDBInstanceOutcome outcome =
                client.CreateDBInstance(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB instance creation has started."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::CreateDBInstance. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            cleanUpResources(PARAMETER_GROUP_NAME, "", client);
            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `CreateDBParameterGroup`
<a name="rds_CreateDBParameterGroup_cpp_1_topic"></a>

次のコード例は、`CreateDBParameterGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::CreateDBParameterGroupRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        request.SetDBParameterGroupFamily(dbParameterGroupFamily);
        request.SetDescription("Example parameter group.");

        Aws::RDS::Model::CreateDBParameterGroupOutcome outcome =
                client.CreateDBParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully created."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::CreateDBParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[CreateDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBParameterGroup)」を参照してください。

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_cpp_1_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

            Aws::RDS::Model::CreateDBSnapshotRequest request;
            request.SetDBInstanceIdentifier(DB_INSTANCE_IDENTIFIER);
            request.SetDBSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::CreateDBSnapshotOutcome outcome =
                    client.CreateDBSnapshot(request);

            if (outcome.IsSuccess()) {
                std::cout << "Snapshot creation has started."
                          << std::endl;
            }
            else {
                std::cerr << "Error with RDS::CreateDBSnapshot. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[CreateDBSnapshot](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/CreateDBSnapshot)」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_cpp_1_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

            Aws::RDS::Model::DeleteDBInstanceRequest request;
            request.SetDBInstanceIdentifier(dbInstanceIdentifier);
            request.SetSkipFinalSnapshot(true);
            request.SetDeleteAutomatedBackups(true);

            Aws::RDS::Model::DeleteDBInstanceOutcome outcome =
                    client.DeleteDBInstance(request);

            if (outcome.IsSuccess()) {
                std::cout << "DB instance deletion has started."
                          << std::endl;
            }
            else {
                std::cerr << "Error with RDS::DeleteDBInstance. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DeleteDBParameterGroup`
<a name="rds_DeleteDBParameterGroup_cpp_1_topic"></a>

次のコード例は、`DeleteDBParameterGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::DeleteDBParameterGroupRequest request;
        request.SetDBParameterGroupName(parameterGroupName);

        Aws::RDS::Model::DeleteDBParameterGroupOutcome outcome =
                client.DeleteDBParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully deleted."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::DeleteDBParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
```
+  詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DeleteDBParameterGroup)」を参照してください。

### `DescribeDBEngineVersions`
<a name="rds_DescribeDBEngineVersions_cpp_1_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets available DB engine versions for an engine name and
//! an optional parameter group family.
/*!
 \sa getDBEngineVersions()
 \param engineName: A DB engine name.
 \param parameterGroupFamily: A parameter group family name, ignored if empty.
 \param engineVersionsResult: Vector of 'DBEngineVersion' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::getDBEngineVersions(const Aws::String &engineName,
                                      const Aws::String &parameterGroupFamily,
                                      Aws::Vector<Aws::RDS::Model::DBEngineVersion> &engineVersionsResult,
                                      const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBEngineVersionsRequest request;
    request.SetEngine(engineName);
    if (!parameterGroupFamily.empty()) {
        request.SetDBParameterGroupFamily(parameterGroupFamily);
    }

    engineVersionsResult.clear();
    Aws::String marker; // Used for pagination.

    do {
        if (!marker.empty()) {
            request.SetMarker(marker);
        }


        Aws::RDS::Model::DescribeDBEngineVersionsOutcome outcome =
                client.DescribeDBEngineVersions(request);

        if (outcome.IsSuccess()) {
            auto &engineVersions = outcome.GetResult().GetDBEngineVersions();
            engineVersionsResult.insert(engineVersionsResult.end(), engineVersions.begin(),
                                        engineVersions.end());
            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with RDS::DescribeDBEngineVersionsRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }

    } while (!marker.empty());


    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_cpp_1_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets a DB instance description.
/*!
 \sa describeDBInstance()
 \param dbInstanceIdentifier: A DB instance identifier.
 \param instanceResult: The 'DBInstance' object containing the description.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::describeDBInstance(const Aws::String &dbInstanceIdentifier,
                                     Aws::RDS::Model::DBInstance &instanceResult,
                                     const Aws::RDS::RDSClient &client) {
    Aws::RDS::Model::DescribeDBInstancesRequest request;
    request.SetDBInstanceIdentifier(dbInstanceIdentifier);

    Aws::RDS::Model::DescribeDBInstancesOutcome outcome =
            client.DescribeDBInstances(request);

    bool result = true;
    if (outcome.IsSuccess()) {
        instanceResult = outcome.GetResult().GetDBInstances()[0];
    }
    else if (outcome.GetError().GetErrorType() !=
             Aws::RDS::RDSErrors::D_B_INSTANCE_NOT_FOUND_FAULT) {
        result = false;
        std::cerr << "Error with RDS::DescribeDBInstances. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }
        // This example does not log an error if the DB instance does not exist.
        // Instead, instanceResult is set to empty.
    else {
        instanceResult = Aws::RDS::Model::DBInstance();
    }

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_cpp_1_topic"></a>

次のコード例は、`DescribeDBParameterGroups` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::DescribeDBParameterGroupsRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);

        Aws::RDS::Model::DescribeDBParameterGroupsOutcome outcome =
                client.DescribeDBParameterGroups(request);

        if (outcome.IsSuccess()) {
            std::cout << "DB parameter group named '" <<
                      PARAMETER_GROUP_NAME << "' already exists." << std::endl;
            dbParameterGroupFamily = outcome.GetResult().GetDBParameterGroups()[0].GetDBParameterGroupFamily();
        }

        else {
            std::cerr << "Error with RDS::DescribeDBParameterGroups. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBParameterGroups)」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_cpp_1_topic"></a>

次のコード例は、`DescribeDBParameters` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets DB parameters using the 'DescribeDBParameters' api.
/*!
 \sa getDBParameters()
 \param parameterGroupName: The name of the parameter group.
 \param namePrefix: Prefix string to filter results by parameter name.
 \param source: A source such as 'user', ignored if empty.
 \param parametersResult: Vector of 'Parameter' objects returned by the routine.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::getDBParameters(const Aws::String &parameterGroupName,
                                  const Aws::String &namePrefix,
                                  const Aws::String &source,
                                  Aws::Vector<Aws::RDS::Model::Parameter> &parametersResult,
                                  const Aws::RDS::RDSClient &client) {
    Aws::String marker;
    do {
        Aws::RDS::Model::DescribeDBParametersRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }
        if (!source.empty()) {
            request.SetSource(source);
        }

        Aws::RDS::Model::DescribeDBParametersOutcome outcome =
                client.DescribeDBParameters(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::Parameter> &parameters =
                    outcome.GetResult().GetParameters();
            for (const Aws::RDS::Model::Parameter &parameter: parameters) {
                if (!namePrefix.empty()) {
                    if (parameter.GetParameterName().find(namePrefix) == 0) {
                        parametersResult.push_back(parameter);
                    }
                }
                else {
                    parametersResult.push_back(parameter);
                }
            }

            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with RDS::DescribeDBParameters. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    return true;
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DescribeDBParameters](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBParameters)」を参照してください。

### `DescribeDBSnapshots`
<a name="rds_DescribeDBSnapshots_cpp_1_topic"></a>

次のコード例は、`DescribeDBSnapshots` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

            Aws::RDS::Model::DescribeDBSnapshotsRequest request;
            request.SetDBSnapshotIdentifier(snapshotID);

            Aws::RDS::Model::DescribeDBSnapshotsOutcome outcome =
                    client.DescribeDBSnapshots(request);

            if (outcome.IsSuccess()) {
                snapshot = outcome.GetResult().GetDBSnapshots()[0];
            }
            else {
                std::cerr << "Error with RDS::DescribeDBSnapshots. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUpResources(PARAMETER_GROUP_NAME, DB_INSTANCE_IDENTIFIER, client);
                return false;
            }
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DescribeDBSnapshots](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeDBSnapshots)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="rds_DescribeOrderableDBInstanceOptions_cpp_1_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);


//! Routine which gets available 'micro' DB instance classes, displays the list
//! to the user, and returns the user selection.
/*!
 \sa chooseMicroDBInstanceClass()
 \param engineName: The DB engine name.
 \param engineVersion: The DB engine version.
 \param dbInstanceClass: String for DB instance class chosen by the user.
 \param client: 'RDSClient' instance.
 \return bool: Successful completion.
 */
bool AwsDoc::RDS::chooseMicroDBInstanceClass(const Aws::String &engine,
                                             const Aws::String &engineVersion,
                                             Aws::String &dbInstanceClass,
                                             const Aws::RDS::RDSClient &client) {
    std::vector<Aws::String> instanceClasses;
    Aws::String marker;
    do {
        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsRequest request;
        request.SetEngine(engine);
        request.SetEngineVersion(engineVersion);
        if (!marker.empty()) {
            request.SetMarker(marker);
        }

        Aws::RDS::Model::DescribeOrderableDBInstanceOptionsOutcome outcome =
                client.DescribeOrderableDBInstanceOptions(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::RDS::Model::OrderableDBInstanceOption> &options =
                    outcome.GetResult().GetOrderableDBInstanceOptions();
            for (const Aws::RDS::Model::OrderableDBInstanceOption &option: options) {
                const Aws::String &instanceClass = option.GetDBInstanceClass();
                if (instanceClass.find("micro") != std::string::npos) {
                    if (std::find(instanceClasses.begin(), instanceClasses.end(),
                                  instanceClass) ==
                        instanceClasses.end()) {
                        instanceClasses.push_back(instanceClass);
                    }
                }
            }
            marker = outcome.GetResult().GetMarker();
        }
        else {
            std::cerr << "Error with RDS::DescribeOrderableDBInstanceOptions. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!marker.empty());

    std::cout << "The available micro DB instance classes for your database engine are:"
              << std::endl;
    for (int i = 0; i < instanceClasses.size(); ++i) {
        std::cout << "   " << i + 1 << ": " << instanceClasses[i] << std::endl;
    }

    int choice = askQuestionForIntRange(
            "Which micro DB instance class do you want to use? ",
            1, static_cast<int>(instanceClasses.size()));
    dbInstanceClass = instanceClasses[choice - 1];
    return true;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBParameterGroup`
<a name="rds_ModifyDBParameterGroup_cpp_1_topic"></a>

次のコード例は、`ModifyDBParameterGroup` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::RDS::RDSClient client(clientConfig);

        Aws::RDS::Model::ModifyDBParameterGroupRequest request;
        request.SetDBParameterGroupName(PARAMETER_GROUP_NAME);
        request.SetParameters(updateParameters);

        Aws::RDS::Model::ModifyDBParameterGroupOutcome outcome =
                client.ModifyDBParameterGroup(request);

        if (outcome.IsSuccess()) {
            std::cout << "The DB parameter group was successfully modified."
                      << std::endl;
        }
        else {
            std::cerr << "Error with RDS::ModifyDBParameterGroup. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
        }
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForCpp/rds-2014-10-31/ModifyDBParameterGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_cpp_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for C\$1\$1**  
 Amazon Aurora Serverless データベースに保存されている作業項目を追跡して報告するウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora Serverless データをクエリし、React アプリケーションで使用するための C\$1\$1 REST API の完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/serverless-aurora) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for C\$1\$1 を使用した Amazon RDS Data Service の例
<a name="cpp_1_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_cpp_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for C\$1\$1**  
 Amazon Aurora Serverless データベースに保存されている作業項目を追跡して報告するウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora Serverless データをクエリし、React アプリケーションで使用するための C\$1\$1 REST API の完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/serverless-aurora) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for C\$1\$1 を使用した Amazon Rekognition の例
<a name="cpp_1_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Rekognition
<a name="rekognition_Hello_cpp_1_topic"></a>

以下のコード例では、Amazon Rekognition の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rekognition/hello_rekognition#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS rekognition)

# Set this project's name.
project("hello_rekognition")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) 
     # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

     # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this 
                                    # and set the proper subdirectory to the executables' location.

     AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_rekognition.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1rekognition.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/rekognition/RekognitionClient.h>
#include <aws/rekognition/model/ListCollectionsRequest.h>
#include <iostream>

/*
 *  A "Hello Rekognition" starter application which initializes an Amazon Rekognition client and
 *  lists the Amazon Rekognition collections in the current account and region.
 *
 *  main function
 *
 *  Usage: 'hello_rekognition'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    //  Optional: change the log level for debugging.
    //  options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::Rekognition::RekognitionClient rekognitionClient(clientConfig);
        Aws::Rekognition::Model::ListCollectionsRequest request;
        Aws::Rekognition::Model::ListCollectionsOutcome outcome =
                rekognitionClient.ListCollections(request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::String>& collectionsIds = outcome.GetResult().GetCollectionIds();
            if (!collectionsIds.empty()) {
                std::cout << "collectionsIds: " << std::endl;
                for (auto &collectionId : collectionsIds) {
                    std::cout << "- " << collectionId << std::endl;
                }
            } else {
                std::cout << "No collections found" << std::endl;
            }
        } else {
            std::cerr << "Error with ListCollections: " << outcome.GetError()
                      << std::endl;
        }
    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return 0;
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[ListCollections](https://docs.aws.amazon.com/goto/SdkForCpp/rekognition-2016-06-27/ListCollections)」を参照してください。

## アクション
<a name="actions"></a>

### `DetectLabels`
<a name="rekognition_DetectLabels_cpp_1_topic"></a>

次のコード例は、`DetectLabels` を使用する方法を示しています。

詳細については、「[イメージ内のラベルを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
//! Detect instances of real-world entities within an image by using Amazon Rekognition
/*!
  \param imageBucket: The Amazon Simple Storage Service (Amazon S3) bucket containing an image.
  \param imageKey: The Amazon S3 key of an image object.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::Rekognition::detectLabels(const Aws::String &imageBucket,
                                       const Aws::String &imageKey,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::Rekognition::RekognitionClient rekognitionClient(clientConfiguration);

    Aws::Rekognition::Model::DetectLabelsRequest request;
    Aws::Rekognition::Model::S3Object s3Object;
    s3Object.SetBucket(imageBucket);
    s3Object.SetName(imageKey);

    Aws::Rekognition::Model::Image image;
    image.SetS3Object(s3Object);

    request.SetImage(image);

    const Aws::Rekognition::Model::DetectLabelsOutcome outcome = rekognitionClient.DetectLabels(request);

    if (outcome.IsSuccess()) {
        const Aws::Vector<Aws::Rekognition::Model::Label> &labels = outcome.GetResult().GetLabels();
        if (labels.empty()) {
            std::cout << "No labels detected" << std::endl;
        } else {
            for (const Aws::Rekognition::Model::Label &label: labels) {
                std::cout << label.GetName() << ": " << label.GetConfidence() << std::endl;
            }
        }
    } else {
        std::cerr << "Error while detecting labels: '"
                  << outcome.GetError().GetMessage()
                  << "'" << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DetectLabels](https://docs.aws.amazon.com/goto/SdkForCpp/rekognition-2016-06-27/DetectLabels)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_cpp_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for C\$1\$1**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

# SDK for C\$1\$1 を使用した Amazon S3 の例
<a name="cpp_1_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_cpp_1_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/hello_s3#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS s3)

# Set this project's name.
project("hello_s3")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
    # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

    # set(BIN_SUB_DIR "/Debug") # if you are building from the command line you may need to uncomment this
    # and set the proper subdirectory to the executables' location.

    AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_s3.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1s3.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <iostream>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
using namespace Aws;
using namespace Aws::Auth;

/*
 *  A "Hello S3" starter application which initializes an Amazon Simple Storage Service (Amazon S3) client
 *  and lists the Amazon S3 buckets in the selected region.
 *
 *  main function
 *
 *  Usage: 'hello_s3'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    int result = 0;
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";
               
        // You don't normally have to test that you are authenticated. But the S3 service permits anonymous requests, thus the s3Client will return "success" and 0 buckets even if you are unauthenticated, which can be confusing to a new user. 
        auto provider = Aws::MakeShared<DefaultAWSCredentialsProviderChain>("alloc-tag");
        auto creds = provider->GetAWSCredentials();
        if (creds.IsEmpty()) {
            std::cerr << "Failed authentication" << std::endl;
        }

        Aws::S3::S3Client s3Client(clientConfig);
        auto outcome = s3Client.ListBuckets();

        if (!outcome.IsSuccess()) {
            std::cerr << "Failed with error: " << outcome.GetError() << std::endl;
            result = 1;
        } else {
            std::cout << "Found " << outcome.GetResult().GetBuckets().size()
                      << " buckets\n";
            for (auto &bucket: outcome.GetResult().GetBuckets()) {
                std::cout << bucket.GetName() << std::endl;
            }
        }
    }

    Aws::ShutdownAPI(options); // Should only be called once.
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListBuckets](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/ListBuckets)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
#include <iostream>
#include <aws/core/Aws.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/CopyObjectRequest.h>
#include <aws/s3/model/CreateBucketRequest.h>
#include <aws/s3/model/DeleteBucketRequest.h>
#include <aws/s3/model/DeleteObjectRequest.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/ListObjectsV2Request.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/BucketLocationConstraint.h>
#include <aws/s3/model/CreateBucketConfiguration.h>
#include <aws/core/utils/UUID.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSAllocator.h>
#include <fstream>
#include "s3_examples.h"

namespace AwsDoc {
    namespace S3 {

        //! Delete an S3 bucket.
        /*!
          \param bucketName: The S3 bucket's name.
          \param client: An S3 client.
          \return bool: Function succeeded.
        */
        static bool
        deleteBucket(const Aws::String &bucketName, Aws::S3::S3Client &client);

        //! Delete an object in an S3 bucket.
        /*!
          \param bucketName: The S3 bucket's name.
          \param key: The key for the object in the S3 bucket.
          \param client: An S3 client.
          \return bool: Function succeeded.
         */
        static bool
        deleteObjectFromBucket(const Aws::String &bucketName, const Aws::String &key,
                               Aws::S3::S3Client &client);
    }
}


//! Scenario to create, copy, and delete S3 buckets and objects.
/*!
  \param bucketNamePrefix: A prefix for a bucket name.
  \param uploadFilePath: Path to file to upload to an Amazon S3 bucket.
  \param saveFilePath: Path for saving a downloaded S3 object.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::S3::S3_GettingStartedScenario(const Aws::String &bucketNamePrefix,
        const Aws::String &uploadFilePath,
                                           const Aws::String &saveFilePath,
                                           const Aws::Client::ClientConfiguration &clientConfig) {

    Aws::S3::S3Client client(clientConfig);

    // Create a unique bucket name which is only temporary and will be deleted.
    // Format: <bucketNamePrefix> + "-" + lowercase UUID.
    Aws::String uuid = Aws::Utils::UUID::RandomUUID();
    Aws::String bucketName = bucketNamePrefix +
                             Aws::Utils::StringUtils::ToLower(uuid.c_str());

    // 1. Create a bucket.
    {
        Aws::S3::Model::CreateBucketRequest request;
        request.SetBucket(bucketName);

        if (clientConfig.region != Aws::Region::US_EAST_1) {
            Aws::S3::Model::CreateBucketConfiguration createBucketConfiguration;
            createBucketConfiguration.WithLocationConstraint(
                    Aws::S3::Model::BucketLocationConstraintMapper::GetBucketLocationConstraintForName(
                            clientConfig.region));
            request.WithCreateBucketConfiguration(createBucketConfiguration);
        }

        Aws::S3::Model::CreateBucketOutcome outcome = client.CreateBucket(request);

        if (!outcome.IsSuccess()) {
            const Aws::S3::S3Error &err = outcome.GetError();
            std::cerr << "Error: createBucket: " <<
                      err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
            return false;
        } else {
            std::cout << "Created the bucket, '" << bucketName <<
                      "', in the region, '" << clientConfig.region << "'." << std::endl;
        }
    }

    // 2. Upload a local file to the bucket.
    Aws::String key = "key-for-test";
    {
        Aws::S3::Model::PutObjectRequest request;
        request.SetBucket(bucketName);
        request.SetKey(key);

        std::shared_ptr<Aws::FStream> input_data =
                Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
                                              uploadFilePath,
                                              std::ios_base::in |
                                              std::ios_base::binary);

        if (!input_data->is_open()) {
            std::cerr << "Error: unable to open file, '" << uploadFilePath << "'."
                      << std::endl;
            AwsDoc::S3::deleteBucket(bucketName, client);
            return false;
        }

        request.SetBody(input_data);

        Aws::S3::Model::PutObjectOutcome outcome =
                client.PutObject(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error: putObject: " <<
                      outcome.GetError().GetMessage() << std::endl;
            AwsDoc::S3::deleteObjectFromBucket(bucketName, key, client);
            AwsDoc::S3::deleteBucket(bucketName, client);
            return false;
        } else {
            std::cout << "Added the object with the key, '" << key
                      << "', to the bucket, '"
                      << bucketName << "'." << std::endl;
        }
    }

    // 3. Download the object to a local file.
    {
        Aws::S3::Model::GetObjectRequest request;
        request.SetBucket(bucketName);
        request.SetKey(key);

        Aws::S3::Model::GetObjectOutcome outcome =
                client.GetObject(request);

        if (!outcome.IsSuccess()) {
            const Aws::S3::S3Error &err = outcome.GetError();
            std::cerr << "Error: getObject: " <<
                      err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
        } else {
            std::cout << "Downloaded the object with the key, '" << key
                      << "', in the bucket, '"
                      << bucketName << "'." << std::endl;

            Aws::IOStream &ioStream = outcome.GetResultWithOwnership().
                    GetBody();
            Aws::OFStream outStream(saveFilePath,
                                    std::ios_base::out | std::ios_base::binary);
            if (!outStream.is_open()) {
                std::cout << "Error: unable to open file, '" << saveFilePath << "'."
                          << std::endl;
            } else {
                outStream << ioStream.rdbuf();
                std::cout << "Wrote the downloaded object to the file '"
                          << saveFilePath << "'." << std::endl;
            }
        }
    }

    // 4. Copy the object to a different "folder" in the bucket.
    Aws::String copiedToKey = "test-folder/" + key;
    {
        Aws::S3::Model::CopyObjectRequest request;
        request.WithBucket(bucketName)
                .WithKey(copiedToKey)
                .WithCopySource(bucketName + "/" + key);

        Aws::S3::Model::CopyObjectOutcome outcome =
                client.CopyObject(request);
        if (!outcome.IsSuccess()) {
            std::cerr << "Error: copyObject: " <<
                      outcome.GetError().GetMessage() << std::endl;
        } else {
            std::cout << "Copied the object with the key, '" << key
                      << "', to the key, '" << copiedToKey
                      << ", in the bucket, '" << bucketName << "'." << std::endl;
        }
    }

    // 5. List objects in the bucket.
    {
        Aws::S3::Model::ListObjectsV2Request request;
        request.WithBucket(bucketName);

        Aws::String continuationToken;
        Aws::Vector<Aws::S3::Model::Object> allObjects;

        do {
            if (!continuationToken.empty()) {
                request.SetContinuationToken(continuationToken);
            }
            Aws::S3::Model::ListObjectsV2Outcome outcome = client.ListObjectsV2(
                    request);

            if (!outcome.IsSuccess()) {
                std::cerr << "Error: ListObjects: " <<
                          outcome.GetError().GetMessage() << std::endl;
                break;
            } else {
                Aws::Vector<Aws::S3::Model::Object> objects =
                        outcome.GetResult().GetContents();
                allObjects.insert(allObjects.end(), objects.begin(), objects.end());
                continuationToken = outcome.GetResult().GetContinuationToken();
            }
        } while (!continuationToken.empty());

        std::cout << allObjects.size() << " objects in the bucket, '" << bucketName
                  << "':" << std::endl;

        for (Aws::S3::Model::Object &object: allObjects) {
            std::cout << "     '" << object.GetKey() << "'" << std::endl;
        }
    }

    // 6. Delete all objects in the bucket.
    // All objects in the bucket must be deleted before deleting the bucket.
    AwsDoc::S3::deleteObjectFromBucket(bucketName, copiedToKey, client);
    AwsDoc::S3::deleteObjectFromBucket(bucketName, key, client);

    // 7. Delete the bucket.
    return AwsDoc::S3::deleteBucket(bucketName, client);
}

bool AwsDoc::S3::deleteObjectFromBucket(const Aws::String &bucketName,
                                        const Aws::String &key,
                                        Aws::S3::S3Client &client) {
    Aws::S3::Model::DeleteObjectRequest request;
    request.SetBucket(bucketName);
    request.SetKey(key);

    Aws::S3::Model::DeleteObjectOutcome outcome =
            client.DeleteObject(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: deleteObject: " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Deleted the object with the key, '" << key
                  << "', from the bucket, '"
                  << bucketName << "'." << std::endl;
    }

    return outcome.IsSuccess();
}

bool
AwsDoc::S3::deleteBucket(const Aws::String &bucketName, Aws::S3::S3Client &client) {
    Aws::S3::Model::DeleteBucketRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::DeleteBucketOutcome outcome =
            client.DeleteBucket(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: deleteBucket: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Deleted the bucket, '" << bucketName << "'." << std::endl;
    }
    return outcome.IsSuccess();
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetObject)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/ListObjectsV2)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `AbortMultipartUpload`
<a name="s3_AbortMultipartUpload_cpp_1_topic"></a>

次のコード例は、`AbortMultipartUpload` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
//! Abort a multipart upload to an S3 bucket.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param uploadID: An upload ID string.
    \param client: The S3 client instance used to perform the upload operation.
    \return bool: Function succeeded.
*/

bool AwsDoc::S3::abortMultipartUpload(const Aws::String &bucket,
                                      const Aws::String &key,
                                      const Aws::String &uploadID,
                                      const Aws::S3::S3Client &client) {
    Aws::S3::Model::AbortMultipartUploadRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);
    request.SetUploadId(uploadID);

    Aws::S3::Model::AbortMultipartUploadOutcome outcome =
            client.AbortMultipartUpload(request);

    if (outcome.IsSuccess()) {
        std::cout << "Multipart upload aborted." << std::endl;
    } else {
        std::cerr << "Error aborting multipart upload: " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「AWS SDK for C\$1\$1 API リファレンス」の「[AbortMultipartUpload](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/AbortMultipartUpload)」を参照してください。**

### `CompleteMultipartUpload`
<a name="s3_CompleteMultipartUpload_cpp_1_topic"></a>

次のコード例は、`CompleteMultipartUpload` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
//! Complete a multipart upload to an S3 bucket.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param uploadID: An upload ID string.
    \param parts: A vector of CompleteParts.
    \param client: The S3 client instance used to perform the upload operation.
    \return CompleteMultipartUploadOutcome: The request outcome.
*/
Aws::S3::Model::CompleteMultipartUploadOutcome AwsDoc::S3::completeMultipartUpload(const Aws::String &bucket,
                                                                                   const Aws::String &key,
                                                                                   const Aws::String &uploadID,
                                                                                   const Aws::Vector<Aws::S3::Model::CompletedPart> &parts,
                                                                                   const Aws::S3::S3Client &client) {
    Aws::S3::Model::CompletedMultipartUpload completedMultipartUpload;
    completedMultipartUpload.SetParts(parts);

    Aws::S3::Model::CompleteMultipartUploadRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);
    request.SetUploadId(uploadID);
    request.SetMultipartUpload(completedMultipartUpload);

    Aws::S3::Model::CompleteMultipartUploadOutcome outcome =
            client.CompleteMultipartUpload(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error completing multipart upload: " << outcome.GetError().GetMessage() << std::endl;
    }
    return outcome;
}
```
+  API の詳細については、「AWS SDK for C\$1\$1 API リファレンス」の「[CompleteMultipartUpload](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CompleteMultipartUpload)」を参照してください。**

### `CopyObject`
<a name="s3_CopyObject_cpp_1_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::copyObject(const Aws::String &objectKey, const Aws::String &fromBucket, const Aws::String &toBucket,
                            const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::CopyObjectRequest request;

    request.WithCopySource(fromBucket + "/" + objectKey)
            .WithKey(objectKey)
            .WithBucket(toBucket);

    Aws::S3::Model::CopyObjectOutcome outcome = client.CopyObject(request);
    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: copyObject: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;

    } else {
        std::cout << "Successfully copied " << objectKey << " from " << fromBucket <<
                  " to " << toBucket << "." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CopyObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CopyObject)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_cpp_1_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::createBucket(const Aws::String &bucketName,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::CreateBucketRequest request;
    request.SetBucket(bucketName);

    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();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[CreateBucket](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CreateBucket)」を参照してください。**

### `CreateMultipartUpload`
<a name="s3_CreateMultipartUpload_cpp_1_topic"></a>

次のコード例は、`CreateMultipartUpload` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
//! Create a multipart upload.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param client: The S3 client instance used to perform the upload operation.
    \return Aws::String: Upload ID or empty string if failed.
*/
Aws::String
AwsDoc::S3::createMultipartUpload(const Aws::String &bucket, const Aws::String &key,
                                  Aws::S3::Model::ChecksumAlgorithm checksumAlgorithm,
                                  const Aws::S3::S3Client &client) {
    Aws::S3::Model::CreateMultipartUploadRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);

    if (checksumAlgorithm != Aws::S3::Model::ChecksumAlgorithm::NOT_SET) {
        request.SetChecksumAlgorithm(checksumAlgorithm);
    }

    Aws::S3::Model::CreateMultipartUploadOutcome outcome =
            client.CreateMultipartUpload(request);

    Aws::String uploadID;
    if (outcome.IsSuccess()) {
        uploadID = outcome.GetResult().GetUploadId();
    } else {
        std::cerr << "Error creating multipart upload: " << outcome.GetError().GetMessage() << std::endl;
    }

    return uploadID;
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[CreateMultipartUpload](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CreateMultipartUpload)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_cpp_1_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::deleteBucket(const Aws::String &bucketName,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {

    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::DeleteBucketRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::DeleteBucketOutcome outcome =
            client.DeleteBucket(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: deleteBucket: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "The bucket was deleted" << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[DeleteBucket](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteBucket)」を参照してください。**

### `DeleteBucketPolicy`
<a name="s3_DeleteBucketPolicy_cpp_1_topic"></a>

次のコード例は、`DeleteBucketPolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::deleteBucketPolicy(const Aws::String &bucketName,
                                    const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::DeleteBucketPolicyRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::DeleteBucketPolicyOutcome outcome = client.DeleteBucketPolicy(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: deleteBucketPolicy: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Policy was deleted from the bucket." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteBucketPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteBucketPolicy)」を参照してください。

### `DeleteBucketWebsite`
<a name="s3_DeleteBucketWebsite_cpp_1_topic"></a>

次のコード例は、`DeleteBucketWebsite` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::deleteBucketWebsite(const Aws::String &bucketName,
                                     const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::DeleteBucketWebsiteRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::DeleteBucketWebsiteOutcome outcome =
            client.DeleteBucketWebsite(request);

    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error: deleteBucketWebsite: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Website configuration was removed." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteBucketWebsite](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteBucketWebsite)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_cpp_1_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::deleteObject(const Aws::String &objectKey,
                              const Aws::String &fromBucket,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::DeleteObjectRequest request;

    request.WithKey(objectKey)
            .WithBucket(fromBucket);

    Aws::S3::Model::DeleteObjectOutcome outcome =
            client.DeleteObject(request);

    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error: deleteObject: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted the object." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_cpp_1_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::deleteObjects(const std::vector<Aws::String> &objectKeys,
                               const Aws::String &fromBucket,
                               const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::DeleteObjectsRequest request;

    Aws::S3::Model::Delete deleteObject;
    for (const Aws::String &objectKey: objectKeys) {
        deleteObject.AddObjects(Aws::S3::Model::ObjectIdentifier().WithKey(objectKey));
    }

    request.SetDelete(deleteObject);
    request.SetBucket(fromBucket);

    Aws::S3::Model::DeleteObjectsOutcome outcome =
            client.DeleteObjects(request);

    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error deleting objects. " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted the objects.";
        for (size_t i = 0; i < objectKeys.size(); ++i) {
            std::cout << objectKeys[i];
            if (i < objectKeys.size() - 1) {
                std::cout << ", ";
            }
        }

        std::cout << " from bucket " << fromBucket << "." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteObjects)」を参照してください。**

### `GetBucketAcl`
<a name="s3_GetBucketAcl_cpp_1_topic"></a>

次のコード例は、`GetBucketAcl` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::getBucketAcl(const Aws::String &bucketName,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetBucketAclRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::GetBucketAclOutcome outcome =
            s3Client.GetBucketAcl(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getBucketAcl: "
                  << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        Aws::Vector<Aws::S3::Model::Grant> grants =
                outcome.GetResult().GetGrants();

        for (auto it = grants.begin(); it != grants.end(); it++) {
            Aws::S3::Model::Grant grant = *it;
            Aws::S3::Model::Grantee grantee = grant.GetGrantee();

            std::cout << "For bucket " << bucketName << ": "
                      << std::endl << std::endl;

            if (grantee.TypeHasBeenSet()) {
                std::cout << "Type:          "
                          << getGranteeTypeString(grantee.GetType()) << std::endl;
            }

            if (grantee.DisplayNameHasBeenSet()) {
                std::cout << "Display name:  "
                          << grantee.GetDisplayName() << std::endl;
            }

            if (grantee.EmailAddressHasBeenSet()) {
                std::cout << "Email address: "
                          << grantee.GetEmailAddress() << std::endl;
            }

            if (grantee.IDHasBeenSet()) {
                std::cout << "ID:            "
                          << grantee.GetID() << std::endl;
            }

            if (grantee.URIHasBeenSet()) {
                std::cout << "URI:           "
                          << grantee.GetURI() << std::endl;
            }

            std::cout << "Permission:    " <<
                      getPermissionString(grant.GetPermission()) <<
                      std::endl << std::endl;
        }
    }

    return outcome.IsSuccess();
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param type: Type enumeration.
 \return String: Human-readable string.
*/

Aws::String getGranteeTypeString(const Aws::S3::Model::Type &type) {
    switch (type) {
        case Aws::S3::Model::Type::AmazonCustomerByEmail:
            return "Email address of an AWS account";
        case Aws::S3::Model::Type::CanonicalUser:
            return "Canonical user ID of an AWS account";
        case Aws::S3::Model::Type::Group:
            return "Predefined Amazon S3 group";
        case Aws::S3::Model::Type::NOT_SET:
            return "Not set";
        default:
            return "Type unknown";
    }
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param permission: Permission enumeration.
 \return String: Human-readable string.
*/

Aws::String getPermissionString(const Aws::S3::Model::Permission &permission) {
    switch (permission) {
        case Aws::S3::Model::Permission::FULL_CONTROL:
            return "Can list objects in this bucket, create/overwrite/delete "
                   "objects in this bucket, and read/write this "
                   "bucket's permissions";
        case Aws::S3::Model::Permission::NOT_SET:
            return "Permission not set";
        case Aws::S3::Model::Permission::READ:
            return "Can list objects in this bucket";
        case Aws::S3::Model::Permission::READ_ACP:
            return "Can read this bucket's permissions";
        case Aws::S3::Model::Permission::WRITE:
            return "Can create, overwrite, and delete objects in this bucket";
        case Aws::S3::Model::Permission::WRITE_ACP:
            return "Can write this bucket's permissions";
        default:
            return "Permission unknown";
    }

    return "Permission unknown";
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetBucketAcl](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetBucketAcl)」を参照してください。

### `GetBucketPolicy`
<a name="s3_GetBucketPolicy_cpp_1_topic"></a>

次のコード例は、`GetBucketPolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::getBucketPolicy(const Aws::String &bucketName,
                                 const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetBucketPolicyRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::GetBucketPolicyOutcome outcome =
            s3Client.GetBucketPolicy(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getBucketPolicy: "
                  << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        Aws::StringStream policy_stream;
        Aws::String line;

        outcome.GetResult().GetPolicy() >> line;
        policy_stream << line;

        std::cout << "Retrieve the policy for bucket '" << bucketName << "':\n\n" <<
                  policy_stream.str() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetBucketPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetBucketPolicy)」を参照してください。

### `GetBucketWebsite`
<a name="s3_GetBucketWebsite_cpp_1_topic"></a>

次のコード例は、`GetBucketWebsite` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::getWebsiteConfig(const Aws::String &bucketName,
                                  const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetBucketWebsiteRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::GetBucketWebsiteOutcome outcome =
            s3Client.GetBucketWebsite(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();

        std::cerr << "Error: GetBucketWebsite: "
                  << err.GetMessage() << std::endl;
    } else {
        Aws::S3::Model::GetBucketWebsiteResult websiteResult = outcome.GetResult();

        std::cout << "Success: GetBucketWebsite: "
                  << std::endl << std::endl
                  << "For bucket '" << bucketName << "':"
                  << std::endl
                  << "Index page : "
                  << websiteResult.GetIndexDocument().GetSuffix()
                  << std::endl
                  << "Error page: "
                  << websiteResult.GetErrorDocument().GetKey()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetBucketWebsite](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetBucketWebsite)」を参照してください。

### `GetObject`
<a name="s3_GetObject_cpp_1_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::getObject(const Aws::String &objectKey,
                           const Aws::String &fromBucket,
                           const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::GetObjectRequest request;
    request.SetBucket(fromBucket);
    request.SetKey(objectKey);

    Aws::S3::Model::GetObjectOutcome outcome =
            client.GetObject(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getObject: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully retrieved '" << objectKey << "' from '"
                  << fromBucket << "'." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetObject)」を参照してください。

### `GetObjectAcl`
<a name="s3_GetObjectAcl_cpp_1_topic"></a>

次のコード例は、`GetObjectAcl` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::getObjectAcl(const Aws::String &bucketName,
                              const Aws::String &objectKey,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetObjectAclRequest request;
    request.SetBucket(bucketName);
    request.SetKey(objectKey);

    Aws::S3::Model::GetObjectAclOutcome outcome =
            s3Client.GetObjectAcl(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getObjectAcl: "
                  << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        Aws::Vector<Aws::S3::Model::Grant> grants =
                outcome.GetResult().GetGrants();

        for (auto it = grants.begin(); it != grants.end(); it++) {
            std::cout << "For object " << objectKey << ": "
                      << std::endl << std::endl;

            Aws::S3::Model::Grant grant = *it;
            Aws::S3::Model::Grantee grantee = grant.GetGrantee();

            if (grantee.TypeHasBeenSet()) {
                std::cout << "Type:          "
                          << getGranteeTypeString(grantee.GetType()) << std::endl;
            }

            if (grantee.DisplayNameHasBeenSet()) {
                std::cout << "Display name:  "
                          << grantee.GetDisplayName() << std::endl;
            }

            if (grantee.EmailAddressHasBeenSet()) {
                std::cout << "Email address: "
                          << grantee.GetEmailAddress() << std::endl;
            }

            if (grantee.IDHasBeenSet()) {
                std::cout << "ID:            "
                          << grantee.GetID() << std::endl;
            }

            if (grantee.URIHasBeenSet()) {
                std::cout << "URI:           "
                          << grantee.GetURI() << std::endl;
            }

            std::cout << "Permission:    " <<
                      getPermissionString(grant.GetPermission()) <<
                      std::endl << std::endl;
        }
    }

    return outcome.IsSuccess();
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param type: Type enumeration.
 \return String: Human-readable string
*/
Aws::String getGranteeTypeString(const Aws::S3::Model::Type &type) {
    switch (type) {
        case Aws::S3::Model::Type::AmazonCustomerByEmail:
            return "Email address of an AWS account";
        case Aws::S3::Model::Type::CanonicalUser:
            return "Canonical user ID of an AWS account";
        case Aws::S3::Model::Type::Group:
            return "Predefined Amazon S3 group";
        case Aws::S3::Model::Type::NOT_SET:
            return "Not set";
        default:
            return "Type unknown";
    }
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param permission: Permission enumeration.
 \return String: Human-readable string
*/
Aws::String getPermissionString(const Aws::S3::Model::Permission &permission) {
    switch (permission) {
        case Aws::S3::Model::Permission::FULL_CONTROL:
            return "Can read this object's data and its metadata, "
                   "and read/write this object's permissions";
        case Aws::S3::Model::Permission::NOT_SET:
            return "Permission not set";
        case Aws::S3::Model::Permission::READ:
            return "Can read this object's data and its metadata";
        case Aws::S3::Model::Permission::READ_ACP:
            return "Can read this object's permissions";
            // case Aws::S3::Model::Permission::WRITE // Not applicable.
        case Aws::S3::Model::Permission::WRITE_ACP:
            return "Can write this object's permissions";
        default:
            return "Permission unknown";
    }
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[GetObjectAcl](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetObjectAcl)」を参照してください。

### `GetObjectAttributes`
<a name="s3_GetObjectAttributes_cpp_1_topic"></a>

次のコード例は、`GetObjectAttributes` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
// ! Routine which retrieves the hash value of an object stored in an S3 bucket.
/*!
   \param bucket: The name of the S3 bucket where the object is stored.
   \param key: The unique identifier (key) of the object within the S3 bucket.
   \param hashMethod: The hashing algorithm used to calculate the hash value of the object.
   \param[out] hashData: The retrieved hash.
   \param[out] partHashes: The part hashes if available.
   \param client: The S3 client instance used to retrieve the object.
   \return bool: Function succeeded.
*/
bool AwsDoc::S3::retrieveObjectHash(const Aws::String &bucket, const Aws::String &key,
                                    AwsDoc::S3::HASH_METHOD hashMethod,
                                    Aws::String &hashData,
                                    std::vector<Aws::String> *partHashes,
                                    const Aws::S3::S3Client &client) {
    Aws::S3::Model::GetObjectAttributesRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);

    if (hashMethod == MD5) {
        Aws::Vector<Aws::S3::Model::ObjectAttributes> attributes;
        attributes.push_back(Aws::S3::Model::ObjectAttributes::ETag);
        request.SetObjectAttributes(attributes);

        Aws::S3::Model::GetObjectAttributesOutcome outcome = client.GetObjectAttributes(
                request);
        if (outcome.IsSuccess()) {
            const Aws::S3::Model::GetObjectAttributesResult &result = outcome.GetResult();
            hashData = result.GetETag();
        } else {
            std::cerr << "Error retrieving object etag attributes." <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    } else { // hashMethod != MD5
        Aws::Vector<Aws::S3::Model::ObjectAttributes> attributes;
        attributes.push_back(Aws::S3::Model::ObjectAttributes::Checksum);
        request.SetObjectAttributes(attributes);

        Aws::S3::Model::GetObjectAttributesOutcome outcome = client.GetObjectAttributes(
                request);
        if (outcome.IsSuccess()) {
            const Aws::S3::Model::GetObjectAttributesResult &result = outcome.GetResult();
            switch (hashMethod) {
                case AwsDoc::S3::DEFAULT: // NOLINT(*-branch-clone)
                    break;  // Default is not supported.
#pragma clang diagnostic push
#pragma ide diagnostic ignored "UnreachableCode"
                case AwsDoc::S3::MD5:
                    break;  // MD5 is not supported.
#pragma clang diagnostic pop
                case AwsDoc::S3::SHA1:
                    hashData = result.GetChecksum().GetChecksumSHA1();
                    break;
                case AwsDoc::S3::SHA256:
                    hashData = result.GetChecksum().GetChecksumSHA256();
                    break;
                case AwsDoc::S3::CRC32:
                    hashData = result.GetChecksum().GetChecksumCRC32();
                    break;
                case AwsDoc::S3::CRC32C:
                    hashData = result.GetChecksum().GetChecksumCRC32C();
                    break;
                default:
                    std::cerr << "Unknown hash method." << std::endl;
                    return false;
            }
        } else {
            std::cerr << "Error retrieving object checksum attributes." <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (nullptr != partHashes) {
            attributes.clear();
            attributes.push_back(Aws::S3::Model::ObjectAttributes::ObjectParts);
            request.SetObjectAttributes(attributes);
            outcome = client.GetObjectAttributes(request);
            if (outcome.IsSuccess()) {
                const Aws::S3::Model::GetObjectAttributesResult &result = outcome.GetResult();
                const Aws::Vector<Aws::S3::Model::ObjectPart> parts = result.GetObjectParts().GetParts();
                for (const Aws::S3::Model::ObjectPart &part: parts) {
                    switch (hashMethod) {
                        case AwsDoc::S3::DEFAULT: // Default is not supported. NOLINT(*-branch-clone)
                            break;
                        case AwsDoc::S3::MD5: // MD5 is not supported.
                            break;
                        case AwsDoc::S3::SHA1:
                            partHashes->push_back(part.GetChecksumSHA1());
                            break;
                        case AwsDoc::S3::SHA256:
                            partHashes->push_back(part.GetChecksumSHA256());
                            break;
                        case AwsDoc::S3::CRC32:
                            partHashes->push_back(part.GetChecksumCRC32());
                            break;
                        case AwsDoc::S3::CRC32C:
                            partHashes->push_back(part.GetChecksumCRC32C());
                            break;
                        default:
                            std::cerr << "Unknown hash method." << std::endl;
                            return false;
                    }
                }
            } else {
                std::cerr << "Error retrieving object attributes for object parts." <<
                          outcome.GetError().GetMessage() << std::endl;
                return false;
            }
        }
    }

    return true;
}
```
+  API の詳細については、「AWS SDK for C\$1\$1 API リファレンス」の「[GetObjectAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetObjectAttributes)」を参照してください。**

### `ListBuckets`
<a name="s3_ListBuckets_cpp_1_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::listBuckets(const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    auto outcome = client.ListBuckets();

    bool result = true;
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed with error: " << outcome.GetError() << std::endl;
        result = false;
    } else {
        std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n";
        for (auto &&b: outcome.GetResult().GetBuckets()) {
            std::cout << b.GetName() << std::endl;
        }
    }

    return result;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/ListBuckets)」を参照してください。**

### `ListObjectsV2`
<a name="s3_ListObjectsV2_cpp_1_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::listObjects(const Aws::String &bucketName,
                             Aws::Vector<Aws::String> &keysResult,
                             const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::ListObjectsV2Request request;
    request.WithBucket(bucketName);

    Aws::String continuationToken; // Used for pagination.
    Aws::Vector<Aws::S3::Model::Object> allObjects;

    do {
        if (!continuationToken.empty()) {
            request.SetContinuationToken(continuationToken);
        }

        auto outcome = s3Client.ListObjectsV2(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error: listObjects: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        } else {
            Aws::Vector<Aws::S3::Model::Object> objects =
                    outcome.GetResult().GetContents();

            allObjects.insert(allObjects.end(), objects.begin(), objects.end());
            continuationToken = outcome.GetResult().GetNextContinuationToken();
        }
    } while (!continuationToken.empty());

    std::cout << allObjects.size() << " object(s) found:" << std::endl;

    for (const auto &object: allObjects) {
        std::cout << "  " << object.GetKey() << std::endl;
        keysResult.push_back(object.GetKey());
    }

    return true;
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/ListObjectsV2)」を参照してください。**

### `PutBucketAcl`
<a name="s3_PutBucketAcl_cpp_1_topic"></a>

次のコード例は、`PutBucketAcl` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::putBucketAcl(const Aws::String &bucketName, const Aws::String &ownerID,
                              const Aws::String &granteePermission,
                              const Aws::String &granteeType, const Aws::String &granteeID,
                              const Aws::String &granteeEmailAddress,
                              const Aws::String &granteeURI, const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::Owner owner;
    owner.SetID(ownerID);

    Aws::S3::Model::Grantee grantee;
    grantee.SetType(setGranteeType(granteeType));

    if (!granteeEmailAddress.empty()) {
        grantee.SetEmailAddress(granteeEmailAddress);
    }

    if (!granteeID.empty()) {
        grantee.SetID(granteeID);
    }

    if (!granteeURI.empty()) {
        grantee.SetURI(granteeURI);
    }

    Aws::S3::Model::Grant grant;
    grant.SetGrantee(grantee);
    grant.SetPermission(setGranteePermission(granteePermission));

    Aws::Vector<Aws::S3::Model::Grant> grants;
    grants.push_back(grant);

    Aws::S3::Model::AccessControlPolicy acp;
    acp.SetOwner(owner);
    acp.SetGrants(grants);

    Aws::S3::Model::PutBucketAclRequest request;
    request.SetAccessControlPolicy(acp);
    request.SetBucket(bucketName);

    Aws::S3::Model::PutBucketAclOutcome outcome =
            s3Client.PutBucketAcl(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &error = outcome.GetError();

        std::cerr << "Error: putBucketAcl: " << error.GetExceptionName()
                  << " - " << error.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully added an ACL to the bucket '" << bucketName
                  << "'." << std::endl;
    }

    return outcome.IsSuccess();
}

//! Routine which converts a human-readable string to a built-in type enumeration.
/*!
 \param access: Human readable string.
 \return Permission: A Permission enum.
*/

Aws::S3::Model::Permission setGranteePermission(const Aws::String &access) {
    if (access == "FULL_CONTROL")
        return Aws::S3::Model::Permission::FULL_CONTROL;
    if (access == "WRITE")
        return Aws::S3::Model::Permission::WRITE;
    if (access == "READ")
        return Aws::S3::Model::Permission::READ;
    if (access == "WRITE_ACP")
        return Aws::S3::Model::Permission::WRITE_ACP;
    if (access == "READ_ACP")
        return Aws::S3::Model::Permission::READ_ACP;
    return Aws::S3::Model::Permission::NOT_SET;
}

//! Routine which converts a human-readable string to a built-in type enumeration.
/*!
 \param type: Human readable string.
 \return Type: Type enumeration
*/

Aws::S3::Model::Type setGranteeType(const Aws::String &type) {
    if (type == "Amazon customer by email")
        return Aws::S3::Model::Type::AmazonCustomerByEmail;
    if (type == "Canonical user")
        return Aws::S3::Model::Type::CanonicalUser;
    if (type == "Group")
        return Aws::S3::Model::Type::Group;
    return Aws::S3::Model::Type::NOT_SET;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[PutBucketAcl](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutBucketAcl)」を参照してください。

### `PutBucketPolicy`
<a name="s3_PutBucketPolicy_cpp_1_topic"></a>

次のコード例は、`PutBucketPolicy` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::putBucketPolicy(const Aws::String &bucketName,
                                 const Aws::String &policyBody,
                                 const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    std::shared_ptr<Aws::StringStream> request_body =
            Aws::MakeShared<Aws::StringStream>("");
    *request_body << policyBody;

    Aws::S3::Model::PutBucketPolicyRequest request;
    request.SetBucket(bucketName);
    request.SetBody(request_body);

    Aws::S3::Model::PutBucketPolicyOutcome outcome =
            s3Client.PutBucketPolicy(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: putBucketPolicy: "
                  << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Set the following policy body for the bucket '" <<
                  bucketName << "':" << std::endl << std::endl;
        std::cout << policyBody << std::endl;
    }

    return outcome.IsSuccess();
}


//! Build a policy JSON string.
/*!
  \param userArn: Aws user Amazon Resource Name (ARN).
      For more information, see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns.
  \param bucketName: Name of a bucket.
  \return String: Policy as JSON string.
*/

Aws::String getPolicyString(const Aws::String &userArn,
                            const Aws::String &bucketName) {
    return
            "{\n"
            "   \"Version\":\"2012-10-17\",\n"
            "   \"Statement\":[\n"
            "       {\n"
            "           \"Sid\": \"1\",\n"
            "           \"Effect\": \"Allow\",\n"
            "           \"Principal\": {\n"
            "               \"AWS\": \""
            + userArn +
            "\"\n""           },\n"
            "           \"Action\": [ \"s3:getObject\" ],\n"
            "           \"Resource\": [ \"arn:aws:s3:::"
            + bucketName +
            "/*\" ]\n"
            "       }\n"
            "   ]\n"
            "}";
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[PutBucketPolicy](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutBucketPolicy)」を参照してください。**

### `PutBucketWebsite`
<a name="s3_PutBucketWebsite_cpp_1_topic"></a>

次のコード例は、`PutBucketWebsite` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::putWebsiteConfig(const Aws::String &bucketName,
                                  const Aws::String &indexPage, const Aws::String &errorPage,
                                  const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::IndexDocument indexDocument;
    indexDocument.SetSuffix(indexPage);

    Aws::S3::Model::ErrorDocument errorDocument;
    errorDocument.SetKey(errorPage);

    Aws::S3::Model::WebsiteConfiguration websiteConfiguration;
    websiteConfiguration.SetIndexDocument(indexDocument);
    websiteConfiguration.SetErrorDocument(errorDocument);

    Aws::S3::Model::PutBucketWebsiteRequest request;
    request.SetBucket(bucketName);
    request.SetWebsiteConfiguration(websiteConfiguration);

    Aws::S3::Model::PutBucketWebsiteOutcome outcome =
            client.PutBucketWebsite(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: PutBucketWebsite: "
                  << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Success: Set website configuration for bucket '"
                  << bucketName << "'." << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「*PutBucketWebsite*」を参照してください。[https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutBucketWebsite](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutBucketWebsite)

### `PutObject`
<a name="s3_PutObject_cpp_1_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::putObject(const Aws::String &bucketName,
                           const Aws::String &fileName,
                           const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucketName);
    //We are using the name of the file as the key for the object in the bucket.
    //However, this is just a string and can be set according to your retrieval needs.
    request.SetKey(fileName);

    std::shared_ptr<Aws::IOStream> inputData =
            Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
                                          fileName.c_str(),
                                          std::ios_base::in | std::ios_base::binary);

    if (!*inputData) {
        std::cerr << "Error unable to read file " << fileName << std::endl;
        return false;
    }

    request.SetBody(inputData);

    Aws::S3::Model::PutObjectOutcome outcome =
            s3Client.PutObject(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: putObject: " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Added object '" << fileName << "' to bucket '"
                  << bucketName << "'.";
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[PutObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutObject)」を参照してください。

### `PutObjectAcl`
<a name="s3_PutObjectAcl_cpp_1_topic"></a>

次のコード例は、`PutObjectAcl` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::S3::putObjectAcl(const Aws::String &bucketName, const Aws::String &objectKey, const Aws::String &ownerID,
                              const Aws::String &granteePermission, const Aws::String &granteeType,
                              const Aws::String &granteeID, const Aws::String &granteeEmailAddress,
                              const Aws::String &granteeURI, const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::Owner owner;
    owner.SetID(ownerID);

    Aws::S3::Model::Grantee grantee;
    grantee.SetType(setGranteeType(granteeType));

    if (!granteeEmailAddress.empty()) {
        grantee.SetEmailAddress(granteeEmailAddress);
    }

    if (!granteeID.empty()) {
        grantee.SetID(granteeID);
    }

    if (!granteeURI.empty()) {
        grantee.SetURI(granteeURI);
    }

    Aws::S3::Model::Grant grant;
    grant.SetGrantee(grantee);
    grant.SetPermission(setGranteePermission(granteePermission));

    Aws::Vector<Aws::S3::Model::Grant> grants;
    grants.push_back(grant);

    Aws::S3::Model::AccessControlPolicy acp;
    acp.SetOwner(owner);
    acp.SetGrants(grants);

    Aws::S3::Model::PutObjectAclRequest request;
    request.SetAccessControlPolicy(acp);
    request.SetBucket(bucketName);
    request.SetKey(objectKey);

    Aws::S3::Model::PutObjectAclOutcome outcome =
            s3Client.PutObjectAcl(request);

    if (!outcome.IsSuccess()) {
        auto error = outcome.GetError();
        std::cerr << "Error: putObjectAcl: " << error.GetExceptionName()
                  << " - " << error.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully added an ACL to the object '" << objectKey
                  << "' in the bucket '" << bucketName << "'." << std::endl;
    }

    return outcome.IsSuccess();
}

//! Routine which converts a human-readable string to a built-in type enumeration.
/*!
 \param access: Human readable string.
 \return Permission: Permission enumeration.
*/
Aws::S3::Model::Permission setGranteePermission(const Aws::String &access) {
    if (access == "FULL_CONTROL")
        return Aws::S3::Model::Permission::FULL_CONTROL;
    if (access == "WRITE")
        return Aws::S3::Model::Permission::WRITE;
    if (access == "READ")
        return Aws::S3::Model::Permission::READ;
    if (access == "WRITE_ACP")
        return Aws::S3::Model::Permission::WRITE_ACP;
    if (access == "READ_ACP")
        return Aws::S3::Model::Permission::READ_ACP;
    return Aws::S3::Model::Permission::NOT_SET;
}

//! Routine which converts a human-readable string to a built-in type enumeration.
/*!
 \param type: Human readable string.
 \return Type: Type enumeration.
*/
Aws::S3::Model::Type setGranteeType(const Aws::String &type) {
    if (type == "Amazon customer by email")
        return Aws::S3::Model::Type::AmazonCustomerByEmail;
    if (type == "Canonical user")
        return Aws::S3::Model::Type::CanonicalUser;
    if (type == "Group")
        return Aws::S3::Model::Type::Group;
    return Aws::S3::Model::Type::NOT_SET;
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[PutObjectAcl](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutObjectAcl)」を参照してください。

### `UploadPart`
<a name="s3_UploadPart_cpp_1_topic"></a>

次のコード例は、`UploadPart` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
//! Upload a part to an S3 bucket.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param uploadID: An upload ID string.
    \param partNumber:
    \param checksumAlgorithm: Checksum algorithm, ignored when NOT_SET.
    \param calculatedHash: A data integrity hash to set, depending on the checksum algorithm,
                            ignored when it is an empty string.
    \param body: An shared_ptr IOStream of the data to be uploaded.
    \param client: The S3 client instance used to perform the upload operation.
    \return UploadPartOutcome: The outcome.
*/

Aws::S3::Model::UploadPartOutcome AwsDoc::S3::uploadPart(const Aws::String &bucket,
                                                         const Aws::String &key,
                                                         const Aws::String &uploadID,
                                                         int partNumber,
                                                         Aws::S3::Model::ChecksumAlgorithm checksumAlgorithm,
                                                         const Aws::String &calculatedHash,
                                                         const std::shared_ptr<Aws::IOStream> &body,
                                                         const Aws::S3::S3Client &client) {
    Aws::S3::Model::UploadPartRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);
    request.SetUploadId(uploadID);
    request.SetPartNumber(partNumber);
    if (checksumAlgorithm != Aws::S3::Model::ChecksumAlgorithm::NOT_SET) {
        request.SetChecksumAlgorithm(checksumAlgorithm);
    }
    request.SetBody(body);

    if (!calculatedHash.empty()) {
        switch (checksumAlgorithm) {
            case Aws::S3::Model::ChecksumAlgorithm::NOT_SET:
                request.SetContentMD5(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::CRC32:
                request.SetChecksumCRC32(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::CRC32C:
                request.SetChecksumCRC32C(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::SHA1:
                request.SetChecksumSHA1(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::SHA256:
                request.SetChecksumSHA256(calculatedHash);
                break;
        }
    }

    return client.UploadPart(request);
}
```
+  API の詳細については、「AWS SDK for C\$1\$1 API リファレンス」の「[UploadPart](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/UploadPart)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_cpp_1_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトをダウンロードするための署名付き URL を生成します。  

```
//! Routine which demonstrates creating a pre-signed URL to download an object from an
//! Amazon Simple Storage Service (Amazon S3) bucket.
/*!
  \param bucketName: Name of the bucket.
  \param key: Name of an object key.
  \param expirationSeconds: Expiration in seconds for pre-signed URL.
  \param clientConfig: Aws client configuration.
  \return Aws::String: A pre-signed URL.
*/
Aws::String AwsDoc::S3::generatePreSignedGetObjectUrl(const Aws::String &bucketName,
                                                      const Aws::String &key,
                                                      uint64_t expirationSeconds,
                                                      const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    return client.GeneratePresignedUrl(bucketName, key, Aws::Http::HttpMethod::HTTP_GET,
                                       expirationSeconds);
}
```
libcurl を使用してダウンロードします。  

```
static size_t myCurlWriteBack(char *buffer, size_t size, size_t nitems, void *userdata) {
    Aws::StringStream *str = (Aws::StringStream *) userdata;

    if (nitems > 0) {
        str->write(buffer, size * nitems);
    }
    return size * nitems;
}

//! Utility routine to test getObject with a pre-signed URL.
/*!
  \param presignedURL: A pre-signed URL to get an object from a bucket.
  \param resultString: A string to hold the result.
  \return bool: Function succeeded.
*/
bool AwsDoc::S3::getObjectWithPresignedObjectUrl(const Aws::String &presignedURL,
                                                 Aws::String &resultString) {
    CURL *curl = curl_easy_init();
    CURLcode result;

    std::stringstream outWriteString;

    result = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &outWriteString);

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_WRITEDATA " << std::endl;
        return false;
    }

    result = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, myCurlWriteBack);

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_WRITEFUNCTION" << std::endl;
        return false;
    }

    result = curl_easy_setopt(curl, CURLOPT_URL, presignedURL.c_str());

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_URL" << std::endl;
        return false;
    }

    result = curl_easy_perform(curl);

    if (result != CURLE_OK) {
        std::cerr << "Failed to perform CURL request" << std::endl;
        return false;
    }

    resultString = outWriteString.str();

    if (resultString.find("<?xml") == 0) {
        std::cerr << "Failed to get object, response:\n" << resultString << std::endl;
        return false;
    }

    return true;
}
```
オブジェクトをアップロードするための署名付き URL を生成します。  

```
//! Routine which demonstrates creating a pre-signed URL to upload an object to an
//! Amazon Simple Storage Service (Amazon S3) bucket.
/*!
  \param bucketName: Name of the bucket.
  \param key: Name of an object key.
  \param clientConfig: Aws client configuration.
  \return Aws::String: A pre-signed URL.
*/
Aws::String AwsDoc::S3::generatePreSignedPutObjectUrl(const Aws::String &bucketName,
                                                      const Aws::String &key,
                                                      uint64_t expirationSeconds,
                                                      const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    return client.GeneratePresignedUrl(bucketName, key, Aws::Http::HttpMethod::HTTP_PUT,
                                       expirationSeconds);
}
```
libcurl を使用してアップロードします。  

```
static size_t myCurlReadBack(char *buffer, size_t size, size_t nitems, void *userdata) {
    Aws::StringStream *str = (Aws::StringStream *) userdata;

    str->read(buffer, size * nitems);

    return str->gcount();
}

static size_t myCurlWriteBack(char *buffer, size_t size, size_t nitems, void *userdata) {
    Aws::StringStream *str = (Aws::StringStream *) userdata;

    if (nitems > 0) {
        str->write(buffer, size * nitems);
    }
    return size * nitems;
}

//! Utility routine to test putObject with a pre-signed URL.
/*!
  \param presignedURL: A pre-signed URL to put an object in a bucket.
  \param data: Body of the putObject request.
  \return bool: Function succeeded.
*/
bool AwsDoc::S3::PutStringWithPresignedObjectURL(const Aws::String &presignedURL,
                                                 const Aws::String &data) {
    CURL *curl = curl_easy_init();
    CURLcode result;

    Aws::StringStream readStringStream;
    readStringStream << data;
    result = curl_easy_setopt(curl, CURLOPT_READFUNCTION, myCurlReadBack);

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_READFUNCTION" << std::endl;
        return false;
    }

    result = curl_easy_setopt(curl, CURLOPT_READDATA, &readStringStream);
    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_READDATA" << std::endl;
        return false;
    }

    result = curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                              (curl_off_t) data.size());

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_INFILESIZE_LARGE" << std::endl;
        return false;
    }

    result = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, myCurlWriteBack);

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_WRITEFUNCTION" << std::endl;
        return false;
    }

    std::stringstream outWriteString;

    result = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &outWriteString);

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_WRITEDATA " << std::endl;
        return false;
    }

    result = curl_easy_setopt(curl, CURLOPT_URL, presignedURL.c_str());

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_URL" << std::endl;
        return false;
    }

    result = curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);

    if (result != CURLE_OK) {
        std::cerr << "Failed to set CURLOPT_PUT" << std::endl;
        return false;
    }

    result = curl_easy_perform(curl);

    if (result != CURLE_OK) {
        std::cerr << "Failed to perform CURL request" << std::endl;
        return false;
    }

    std::string outString = outWriteString.str();
    if (outString.empty()) {
        std::cout << "Successfully put object." << std::endl;
        return true;
    } else {
        std::cout << "A server error was encountered, output:\n" << outString
                  << std::endl;
        return false;
    }
}
```

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_cpp_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for C\$1\$1**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### Amazon S3 オブジェクトの整合性の操作
<a name="s3_Scenario_ObjectIntegrity_cpp_1_topic"></a>

次のコード例は、S3 オブジェクトの整合性機能を操作する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/s3_object_integrity_workflow#code-examples)での設定と実行の方法を確認してください。
Amazon S3 オブジェクトの整合性機能を示すインタラクティブなシナリオを実行します。  

```
//! Routine which runs the S3 object integrity workflow.
/*!
   \param clientConfig: Aws client configuration.
   \return bool: Function succeeded.
*/
bool AwsDoc::S3::s3ObjectIntegrityWorkflow(
        const Aws::S3::S3ClientConfiguration &clientConfiguration) {

    /*
     * Create a large file to be used for multipart uploads.
     */
    if (!createLargeFileIfNotExists()) {
        std::cerr << "Workflow exiting because large file creation failed." << std::endl;
        return false;
    }

    Aws::String bucketName = TEST_BUCKET_PREFIX;
    bucketName += Aws::Utils::UUID::RandomUUID();
    bucketName = Aws::Utils::StringUtils::ToLower(bucketName.c_str());

    bucketName.resize(std::min(bucketName.size(), MAX_BUCKET_NAME_LENGTH));

    introductoryExplanations(bucketName);

    if (!AwsDoc::S3::createBucket(bucketName, clientConfiguration)) {
        std::cerr << "Workflow exiting because bucket creation failed." << std::endl;
        return false;
    }

    Aws::S3::S3ClientConfiguration s3ClientConfiguration(clientConfiguration);
    std::shared_ptr<Aws::S3::S3Client> client = Aws::MakeShared<Aws::S3::S3Client>("S3Client", s3ClientConfiguration);

    printAsterisksLine();
    std::cout << "Choose from one of the following checksum algorithms."
              << std::endl;

    for (HASH_METHOD hashMethod = DEFAULT; hashMethod <= SHA256; ++hashMethod) {
        std::cout << "  " << hashMethod << " - " << stringForHashMethod(hashMethod)
                  << std::endl;
    }

    HASH_METHOD chosenHashMethod = askQuestionForIntRange("Enter an index: ", DEFAULT,
                                                          SHA256);


    gUseCalculatedChecksum = !askYesNoQuestion(
            "Let the SDK calculate the checksum for you? (y/n) ");

    printAsterisksLine();

    std::cout << "The workflow will now upload a file using PutObject."
              << std::endl;
    std::cout << "Object integrity will be verified using the "
              << stringForHashMethod(chosenHashMethod) << " algorithm."
              << std::endl;
    if (gUseCalculatedChecksum) {
        std::cout
                << "A checksum computed by this workflow will be used for object integrity verification,"
                << std::endl;
        std::cout << "except for the TransferManager upload." << std::endl;
    } else {
        std::cout
                << "A checksum computed by the SDK will be used for object integrity verification."
                << std::endl;
    }

    pressEnterToContinue();
    printAsterisksLine();

    std::shared_ptr<Aws::IOStream> inputData =
            Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
                                          TEST_FILE,
                                          std::ios_base::in |
                                          std::ios_base::binary);

    if (!*inputData) {
        std::cerr << "Error unable to read file " << TEST_FILE << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    Hasher hasher;
    HASH_METHOD putObjectHashMethod = chosenHashMethod;
    if (putObjectHashMethod == DEFAULT) {
        putObjectHashMethod = MD5; // MD5 is the default hash method for PutObject.

        std::cout << "The default checksum algorithm for PutObject is "
                  << stringForHashMethod(putObjectHashMethod)
                  << std::endl;
    }

    // Demonstrate in code how the hash is computed.
    if (!hasher.calculateObjectHash(*inputData, putObjectHashMethod)) {
        std::cerr << "Error calculating hash for file " << TEST_FILE << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }
    Aws::String key = stringForHashMethod(putObjectHashMethod);
    key += "_";
    key += TEST_FILE_KEY;
    Aws::String localHash = hasher.getBase64HashString();

    // Upload the object with PutObject
    if (!putObjectWithHash(bucketName, key, localHash, putObjectHashMethod,
                           inputData, chosenHashMethod == DEFAULT,
                           *client)) {
        std::cerr << "Error putting file " << TEST_FILE << " to bucket "
                  << bucketName << " with key " << key << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    Aws::String retrievedHash;
    if (!retrieveObjectHash(bucketName, key,
                            putObjectHashMethod, retrievedHash,
                            nullptr, *client)) {
        std::cerr << "Error getting file " << TEST_FILE << " from bucket "
                  << bucketName << " with key " << key << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    explainPutObjectResults();
    verifyHashingResults(retrievedHash, hasher,
                         "PutObject upload", putObjectHashMethod);


    printAsterisksLine();
    pressEnterToContinue();

    key = "tr_";
    key += stringForHashMethod(chosenHashMethod) + "_" + MULTI_PART_TEST_FILE;

    introductoryTransferManagerUploadExplanations(key);

    HASH_METHOD transferManagerHashMethod = chosenHashMethod;
    if (transferManagerHashMethod == DEFAULT) {
        transferManagerHashMethod = CRC32;  // The default hash method for the TransferManager is CRC32.

        std::cout << "The default checksum algorithm for TransferManager is "
                  << stringForHashMethod(transferManagerHashMethod)
                  << std::endl;
    }

    // Upload the large file using the transfer manager.
    if (!doTransferManagerUpload(bucketName, key, transferManagerHashMethod, chosenHashMethod == DEFAULT,
                                 client)) {
        std::cerr << "Exiting because of an error in doTransferManagerUpload." << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    std::vector<Aws::String> retrievedTransferManagerPartHashes;
    Aws::String retrievedTransferManagerFinalHash;

    // Retrieve all the hashes for the TransferManager upload.
    if (!retrieveObjectHash(bucketName, key,
                            transferManagerHashMethod,
                            retrievedTransferManagerFinalHash,
                            &retrievedTransferManagerPartHashes, *client)) {
        std::cerr << "Exiting because of an error in retrieveObjectHash for TransferManager." << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    AwsDoc::S3::Hasher locallyCalculatedFinalHash;
    std::vector<Aws::String> locallyCalculatedPartHashes;

    // Calculate the hashes locally to demonstrate how TransferManager hashes are computed.
    if (!calculatePartHashesForFile(transferManagerHashMethod, MULTI_PART_TEST_FILE,
                                    UPLOAD_BUFFER_SIZE,
                                    locallyCalculatedFinalHash,
                                    locallyCalculatedPartHashes)) {
        std::cerr << "Exiting because of an error in calculatePartHashesForFile." << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    verifyHashingResults(retrievedTransferManagerFinalHash,
                         locallyCalculatedFinalHash, "TransferManager upload",
                         transferManagerHashMethod,
                         retrievedTransferManagerPartHashes,
                         locallyCalculatedPartHashes);

    printAsterisksLine();

    key = "mp_";
    key += stringForHashMethod(chosenHashMethod) + "_" + MULTI_PART_TEST_FILE;

    multiPartUploadExplanations(key, chosenHashMethod);

    pressEnterToContinue();

    std::shared_ptr<Aws::IOStream> largeFileInputData =
            Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
                                          MULTI_PART_TEST_FILE,
                                          std::ios_base::in |
                                          std::ios_base::binary);

    if (!largeFileInputData->good()) {
        std::cerr << "Error unable to read file " << TEST_FILE << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    HASH_METHOD multipartUploadHashMethod = chosenHashMethod;
    if (multipartUploadHashMethod == DEFAULT) {
        multipartUploadHashMethod = MD5;  // The default hash method for multipart uploads is MD5.

        std::cout << "The default checksum algorithm for multipart upload is "
                  << stringForHashMethod(putObjectHashMethod)
                  << std::endl;
    }

    AwsDoc::S3::Hasher hashData;
    std::vector<Aws::String> partHashes;

    if (!doMultipartUpload(bucketName, key,
                           multipartUploadHashMethod,
                           largeFileInputData, chosenHashMethod == DEFAULT,
                           hashData,
                           partHashes,
                           *client)) {
        std::cerr << "Exiting because of an error in doMultipartUpload." << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    std::cout << "Finished multipart upload of with hash method " <<
              stringForHashMethod(multipartUploadHashMethod) << std::endl;

    std::cout << "Now we will retrieve the checksums from the server." << std::endl;

    retrievedHash.clear();
    std::vector<Aws::String> retrievedPartHashes;
    if (!retrieveObjectHash(bucketName, key,
                            multipartUploadHashMethod,
                            retrievedHash, &retrievedPartHashes, *client)) {
        std::cerr << "Exiting because of an error in retrieveObjectHash for multipart." << std::endl;
        cleanUp(bucketName, clientConfiguration);
        return false;
    }

    verifyHashingResults(retrievedHash, hashData, "MultiPart upload",
                         multipartUploadHashMethod,
                         retrievedPartHashes, partHashes);

    printAsterisksLine();

    if (askYesNoQuestion("Would you like to delete the resources created in this workflow? (y/n)")) {
        return cleanUp(bucketName, clientConfiguration);
    } else {
        std::cout << "The bucket " << bucketName << " was not deleted." << std::endl;
        return true;
    }
}

//! Routine which uploads an object to an S3 bucket with different object integrity hashing methods.
/*!
   \param bucket: The name of the S3 bucket where the object will be uploaded.
   \param key: The unique identifier (key) for the object within the S3 bucket.
   \param hashData: The hash value that will be associated with the uploaded object.
   \param hashMethod: The hashing algorithm to use when calculating the hash value.
   \param body: The data content of the object being uploaded.
   \param useDefaultHashMethod: A flag indicating whether to use the default hash method or the one specified in the hashMethod parameter.
   \param client: The S3 client instance used to perform the upload operation.
   \return bool: Function succeeded.
*/
bool AwsDoc::S3::putObjectWithHash(const Aws::String &bucket, const Aws::String &key,
                                   const Aws::String &hashData,
                                   AwsDoc::S3::HASH_METHOD hashMethod,
                                   const std::shared_ptr<Aws::IOStream> &body,
                                   bool useDefaultHashMethod,
                                   const Aws::S3::S3Client &client) {
    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);
    if (!useDefaultHashMethod) {
        if (hashMethod != MD5) {
            request.SetChecksumAlgorithm(getChecksumAlgorithmForHashMethod(hashMethod));
        }
    }

    if (gUseCalculatedChecksum) {
        switch (hashMethod) {
            case AwsDoc::S3::MD5:
                request.SetContentMD5(hashData);
                break;
            case AwsDoc::S3::SHA1:
                request.SetChecksumSHA1(hashData);
                break;
            case AwsDoc::S3::SHA256:
                request.SetChecksumSHA256(hashData);
                break;
            case AwsDoc::S3::CRC32:
                request.SetChecksumCRC32(hashData);
                break;
            case AwsDoc::S3::CRC32C:
                request.SetChecksumCRC32C(hashData);
                break;
            default:
                std::cerr << "Unknown hash method." << std::endl;
                return false;
        }
    }
    request.SetBody(body);
    Aws::S3::Model::PutObjectOutcome outcome = client.PutObject(request);
    body->seekg(0, body->beg);
    if (outcome.IsSuccess()) {
        std::cout << "Object successfully uploaded." << std::endl;
    } else {
        std::cerr << "Error uploading object." <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    return outcome.IsSuccess();
}


// ! Routine which retrieves the hash value of an object stored in an S3 bucket.
/*!
   \param bucket: The name of the S3 bucket where the object is stored.
   \param key: The unique identifier (key) of the object within the S3 bucket.
   \param hashMethod: The hashing algorithm used to calculate the hash value of the object.
   \param[out] hashData: The retrieved hash.
   \param[out] partHashes: The part hashes if available.
   \param client: The S3 client instance used to retrieve the object.
   \return bool: Function succeeded.
*/
bool AwsDoc::S3::retrieveObjectHash(const Aws::String &bucket, const Aws::String &key,
                                    AwsDoc::S3::HASH_METHOD hashMethod,
                                    Aws::String &hashData,
                                    std::vector<Aws::String> *partHashes,
                                    const Aws::S3::S3Client &client) {
    Aws::S3::Model::GetObjectAttributesRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);

    if (hashMethod == MD5) {
        Aws::Vector<Aws::S3::Model::ObjectAttributes> attributes;
        attributes.push_back(Aws::S3::Model::ObjectAttributes::ETag);
        request.SetObjectAttributes(attributes);

        Aws::S3::Model::GetObjectAttributesOutcome outcome = client.GetObjectAttributes(
                request);
        if (outcome.IsSuccess()) {
            const Aws::S3::Model::GetObjectAttributesResult &result = outcome.GetResult();
            hashData = result.GetETag();
        } else {
            std::cerr << "Error retrieving object etag attributes." <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    } else { // hashMethod != MD5
        Aws::Vector<Aws::S3::Model::ObjectAttributes> attributes;
        attributes.push_back(Aws::S3::Model::ObjectAttributes::Checksum);
        request.SetObjectAttributes(attributes);

        Aws::S3::Model::GetObjectAttributesOutcome outcome = client.GetObjectAttributes(
                request);
        if (outcome.IsSuccess()) {
            const Aws::S3::Model::GetObjectAttributesResult &result = outcome.GetResult();
            switch (hashMethod) {
                case AwsDoc::S3::DEFAULT: // NOLINT(*-branch-clone)
                    break;  // Default is not supported.
#pragma clang diagnostic push
#pragma ide diagnostic ignored "UnreachableCode"
                case AwsDoc::S3::MD5:
                    break;  // MD5 is not supported.
#pragma clang diagnostic pop
                case AwsDoc::S3::SHA1:
                    hashData = result.GetChecksum().GetChecksumSHA1();
                    break;
                case AwsDoc::S3::SHA256:
                    hashData = result.GetChecksum().GetChecksumSHA256();
                    break;
                case AwsDoc::S3::CRC32:
                    hashData = result.GetChecksum().GetChecksumCRC32();
                    break;
                case AwsDoc::S3::CRC32C:
                    hashData = result.GetChecksum().GetChecksumCRC32C();
                    break;
                default:
                    std::cerr << "Unknown hash method." << std::endl;
                    return false;
            }
        } else {
            std::cerr << "Error retrieving object checksum attributes." <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        if (nullptr != partHashes) {
            attributes.clear();
            attributes.push_back(Aws::S3::Model::ObjectAttributes::ObjectParts);
            request.SetObjectAttributes(attributes);
            outcome = client.GetObjectAttributes(request);
            if (outcome.IsSuccess()) {
                const Aws::S3::Model::GetObjectAttributesResult &result = outcome.GetResult();
                const Aws::Vector<Aws::S3::Model::ObjectPart> parts = result.GetObjectParts().GetParts();
                for (const Aws::S3::Model::ObjectPart &part: parts) {
                    switch (hashMethod) {
                        case AwsDoc::S3::DEFAULT: // Default is not supported. NOLINT(*-branch-clone)
                            break;
                        case AwsDoc::S3::MD5: // MD5 is not supported.
                            break;
                        case AwsDoc::S3::SHA1:
                            partHashes->push_back(part.GetChecksumSHA1());
                            break;
                        case AwsDoc::S3::SHA256:
                            partHashes->push_back(part.GetChecksumSHA256());
                            break;
                        case AwsDoc::S3::CRC32:
                            partHashes->push_back(part.GetChecksumCRC32());
                            break;
                        case AwsDoc::S3::CRC32C:
                            partHashes->push_back(part.GetChecksumCRC32C());
                            break;
                        default:
                            std::cerr << "Unknown hash method." << std::endl;
                            return false;
                    }
                }
            } else {
                std::cerr << "Error retrieving object attributes for object parts." <<
                          outcome.GetError().GetMessage() << std::endl;
                return false;
            }
        }
    }

    return true;
}

//! Verifies the hashing results between the retrieved and local hashes.
/*!
 \param retrievedHash The hash value retrieved from the remote source.
 \param localHash The hash value calculated locally.
 \param uploadtype The type of upload (e.g., "multipart", "single-part").
 \param hashMethod The hashing method used (e.g., MD5, SHA-256).
 \param retrievedPartHashes (Optional) The list of hashes for the individual parts retrieved from the remote source.
 \param localPartHashes (Optional) The list of hashes for the individual parts calculated locally.
 */
void AwsDoc::S3::verifyHashingResults(const Aws::String &retrievedHash,
                                      const Hasher &localHash,
                                      const Aws::String &uploadtype,
                                      HASH_METHOD hashMethod,
                                      const std::vector<Aws::String> &retrievedPartHashes,
                                      const std::vector<Aws::String> &localPartHashes) {
    std::cout << "For " << uploadtype << " retrieved hash is " << retrievedHash << std::endl;
    if (!retrievedPartHashes.empty()) {
        std::cout << retrievedPartHashes.size() << " part hash(es) were also retrieved."
                  << std::endl;
        for (auto &retrievedPartHash: retrievedPartHashes) {
            std::cout << "  Part hash " << retrievedPartHash << std::endl;
        }
    }
    Aws::String hashString;
    if (hashMethod == MD5) {
        hashString = localHash.getHexHashString();
        if (!localPartHashes.empty()) {
            hashString += "-" + std::to_string(localPartHashes.size());
        }
    } else {
        hashString = localHash.getBase64HashString();
    }

    bool allMatch = true;
    if (hashString != retrievedHash) {
        std::cerr << "For " << uploadtype << ", the main hashes do not match" << std::endl;
        std::cerr << "Local hash- '" << hashString << "'" << std::endl;
        std::cerr << "Remote hash - '" << retrievedHash << "'" << std::endl;
        allMatch = false;
    }

    if (hashMethod != MD5) {
        if (localPartHashes.size() != retrievedPartHashes.size()) {
            std::cerr << "For " << uploadtype << ", the number of part hashes do not match" << std::endl;
            std::cerr << "Local number of hashes- '" << localPartHashes.size() << "'"
                      << std::endl;
            std::cerr << "Remote number of hashes - '"
                      << retrievedPartHashes.size()
                      << "'" << std::endl;
        }

        for (int i = 0; i < localPartHashes.size(); ++i) {
            if (localPartHashes[i] != retrievedPartHashes[i]) {
                std::cerr << "For " << uploadtype << ", the part hashes do not match for part " << i + 1
                          << "." << std::endl;
                std::cerr << "Local hash- '" << localPartHashes[i] << "'"
                          << std::endl;
                std::cerr << "Remote hash - '" << retrievedPartHashes[i] << "'"
                          << std::endl;
                allMatch = false;
            }
        }
    }

    if (allMatch) {
        std::cout << "For " << uploadtype << ", locally and remotely calculated hashes all match!" << std::endl;
    }

}

static void transferManagerErrorCallback(const Aws::Transfer::TransferManager *,
                                         const std::shared_ptr<const Aws::Transfer::TransferHandle> &,
                                         const Aws::Client::AWSError<Aws::S3::S3Errors> &err) {
    std::cerr << "Error during transfer: '" << err.GetMessage() << "'" << std::endl;
}

static void transferManagerStatusCallback(const Aws::Transfer::TransferManager *,
                                          const std::shared_ptr<const Aws::Transfer::TransferHandle> &handle) {
    if (handle->GetStatus() == Aws::Transfer::TransferStatus::IN_PROGRESS) {
        std::cout << "Bytes transferred: " << handle->GetBytesTransferred() << std::endl;
    }
}

//! Routine which uploads an object to an S3 bucket using the AWS C++ SDK's Transfer Manager.
/*!
   \param bucket: The name of the S3 bucket where the object will be uploaded.
   \param key: The unique identifier (key) for the object within the S3 bucket.
   \param hashMethod: The hashing algorithm to use when calculating the hash value.
   \param useDefaultHashMethod: A flag indicating whether to use the default hash method or the one specified in the hashMethod parameter.
   \param client: The S3 client instance used to perform the upload operation.
   \return bool: Function succeeded.
*/
bool
AwsDoc::S3::doTransferManagerUpload(const Aws::String &bucket, const Aws::String &key,
                                    AwsDoc::S3::HASH_METHOD hashMethod,
                                    bool useDefaultHashMethod,
                                    const std::shared_ptr<Aws::S3::S3Client> &client) {
    std::shared_ptr<Aws::Utils::Threading::PooledThreadExecutor> executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>(
            "executor", 25);
    Aws::Transfer::TransferManagerConfiguration transfer_config(executor.get());
    transfer_config.s3Client = client;
    transfer_config.bufferSize = UPLOAD_BUFFER_SIZE;
    if (!useDefaultHashMethod) {
        if (hashMethod == MD5) {
            transfer_config.computeContentMD5 = true;
        } else {
            transfer_config.checksumAlgorithm = getChecksumAlgorithmForHashMethod(
                    hashMethod);
        }
    }
    transfer_config.errorCallback = transferManagerErrorCallback;
    transfer_config.transferStatusUpdatedCallback = transferManagerStatusCallback;

    std::shared_ptr<Aws::Transfer::TransferManager> transfer_manager = Aws::Transfer::TransferManager::Create(
            transfer_config);

    std::cout << "Uploading the file..." << std::endl;
    std::shared_ptr<Aws::Transfer::TransferHandle> uploadHandle = transfer_manager->UploadFile(MULTI_PART_TEST_FILE,
                                                                                               bucket, key,
                                                                                               "text/plain",
                                                                                               Aws::Map<Aws::String, Aws::String>());
    uploadHandle->WaitUntilFinished();
    bool success =
            uploadHandle->GetStatus() == Aws::Transfer::TransferStatus::COMPLETED;
    if (!success) {
        Aws::Client::AWSError<Aws::S3::S3Errors> err = uploadHandle->GetLastError();
        std::cerr << "File upload failed:  " << err.GetMessage() << std::endl;
    }

    return success;
}

//! Routine which calculates the hash values for each part of a file being uploaded to an S3 bucket.
/*!
   \param hashMethod: The hashing algorithm to use when calculating the hash values.
   \param fileName: The path to the file for which the part hashes will be calculated.
   \param bufferSize: The size of the buffer to use when reading the file.
   \param[out] hashDataResult: The Hasher object that will store the concatenated hash value.
   \param[out] partHashes: The vector that will store the calculated hash values for each part of the file.
   \return bool: Function succeeded.
*/
bool AwsDoc::S3::calculatePartHashesForFile(AwsDoc::S3::HASH_METHOD hashMethod,
                                            const Aws::String &fileName,
                                            size_t bufferSize,
                                            AwsDoc::S3::Hasher &hashDataResult,
                                            std::vector<Aws::String> &partHashes) {
    std::ifstream fileStream(fileName.c_str(), std::ifstream::binary);
    fileStream.seekg(0, std::ifstream::end);
    size_t objectSize = fileStream.tellg();
    fileStream.seekg(0, std::ifstream::beg);
    std::vector<unsigned char> totalHashBuffer;
    size_t uploadedBytes = 0;


    while (uploadedBytes < objectSize) {
        std::vector<unsigned char> buffer(bufferSize);
        std::streamsize bytesToRead = static_cast<std::streamsize>(std::min(buffer.size(), objectSize - uploadedBytes));
        fileStream.read((char *) buffer.data(), bytesToRead);
        Aws::Utils::Stream::PreallocatedStreamBuf preallocatedStreamBuf(buffer.data(),
                                                                        bytesToRead);
        std::shared_ptr<Aws::IOStream> body =
                Aws::MakeShared<Aws::IOStream>("SampleAllocationTag",
                                               &preallocatedStreamBuf);
        Hasher hasher;
        if (!hasher.calculateObjectHash(*body, hashMethod)) {
            std::cerr << "Error calculating hash." << std::endl;
            return false;
        }
        Aws::String base64HashString = hasher.getBase64HashString();
        partHashes.push_back(base64HashString);

        Aws::Utils::ByteBuffer hashBuffer = hasher.getByteBufferHash();

        totalHashBuffer.insert(totalHashBuffer.end(), hashBuffer.GetUnderlyingData(),
                               hashBuffer.GetUnderlyingData() + hashBuffer.GetLength());

        uploadedBytes += bytesToRead;
    }

    return hashDataResult.calculateObjectHash(totalHashBuffer, hashMethod);
}

//! Create a multipart upload.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param client: The S3 client instance used to perform the upload operation.
    \return Aws::String: Upload ID or empty string if failed.
*/
Aws::String
AwsDoc::S3::createMultipartUpload(const Aws::String &bucket, const Aws::String &key,
                                  Aws::S3::Model::ChecksumAlgorithm checksumAlgorithm,
                                  const Aws::S3::S3Client &client) {
    Aws::S3::Model::CreateMultipartUploadRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);

    if (checksumAlgorithm != Aws::S3::Model::ChecksumAlgorithm::NOT_SET) {
        request.SetChecksumAlgorithm(checksumAlgorithm);
    }

    Aws::S3::Model::CreateMultipartUploadOutcome outcome =
            client.CreateMultipartUpload(request);

    Aws::String uploadID;
    if (outcome.IsSuccess()) {
        uploadID = outcome.GetResult().GetUploadId();
    } else {
        std::cerr << "Error creating multipart upload: " << outcome.GetError().GetMessage() << std::endl;
    }

    return uploadID;
}

//! Upload a part to an S3 bucket.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param uploadID: An upload ID string.
    \param partNumber:
    \param checksumAlgorithm: Checksum algorithm, ignored when NOT_SET.
    \param calculatedHash: A data integrity hash to set, depending on the checksum algorithm,
                            ignored when it is an empty string.
    \param body: An shared_ptr IOStream of the data to be uploaded.
    \param client: The S3 client instance used to perform the upload operation.
    \return UploadPartOutcome: The outcome.
*/

Aws::S3::Model::UploadPartOutcome AwsDoc::S3::uploadPart(const Aws::String &bucket,
                                                         const Aws::String &key,
                                                         const Aws::String &uploadID,
                                                         int partNumber,
                                                         Aws::S3::Model::ChecksumAlgorithm checksumAlgorithm,
                                                         const Aws::String &calculatedHash,
                                                         const std::shared_ptr<Aws::IOStream> &body,
                                                         const Aws::S3::S3Client &client) {
    Aws::S3::Model::UploadPartRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);
    request.SetUploadId(uploadID);
    request.SetPartNumber(partNumber);
    if (checksumAlgorithm != Aws::S3::Model::ChecksumAlgorithm::NOT_SET) {
        request.SetChecksumAlgorithm(checksumAlgorithm);
    }
    request.SetBody(body);

    if (!calculatedHash.empty()) {
        switch (checksumAlgorithm) {
            case Aws::S3::Model::ChecksumAlgorithm::NOT_SET:
                request.SetContentMD5(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::CRC32:
                request.SetChecksumCRC32(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::CRC32C:
                request.SetChecksumCRC32C(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::SHA1:
                request.SetChecksumSHA1(calculatedHash);
                break;
            case Aws::S3::Model::ChecksumAlgorithm::SHA256:
                request.SetChecksumSHA256(calculatedHash);
                break;
        }
    }

    return client.UploadPart(request);
}

//! Abort a multipart upload to an S3 bucket.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param uploadID: An upload ID string.
    \param client: The S3 client instance used to perform the upload operation.
    \return bool: Function succeeded.
*/

bool AwsDoc::S3::abortMultipartUpload(const Aws::String &bucket,
                                      const Aws::String &key,
                                      const Aws::String &uploadID,
                                      const Aws::S3::S3Client &client) {
    Aws::S3::Model::AbortMultipartUploadRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);
    request.SetUploadId(uploadID);

    Aws::S3::Model::AbortMultipartUploadOutcome outcome =
            client.AbortMultipartUpload(request);

    if (outcome.IsSuccess()) {
        std::cout << "Multipart upload aborted." << std::endl;
    } else {
        std::cerr << "Error aborting multipart upload: " << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}

//! Complete a multipart upload to an S3 bucket.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param uploadID: An upload ID string.
    \param parts: A vector of CompleteParts.
    \param client: The S3 client instance used to perform the upload operation.
    \return CompleteMultipartUploadOutcome: The request outcome.
*/
Aws::S3::Model::CompleteMultipartUploadOutcome AwsDoc::S3::completeMultipartUpload(const Aws::String &bucket,
                                                                                   const Aws::String &key,
                                                                                   const Aws::String &uploadID,
                                                                                   const Aws::Vector<Aws::S3::Model::CompletedPart> &parts,
                                                                                   const Aws::S3::S3Client &client) {
    Aws::S3::Model::CompletedMultipartUpload completedMultipartUpload;
    completedMultipartUpload.SetParts(parts);

    Aws::S3::Model::CompleteMultipartUploadRequest request;
    request.SetBucket(bucket);
    request.SetKey(key);
    request.SetUploadId(uploadID);
    request.SetMultipartUpload(completedMultipartUpload);

    Aws::S3::Model::CompleteMultipartUploadOutcome outcome =
            client.CompleteMultipartUpload(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error completing multipart upload: " << outcome.GetError().GetMessage() << std::endl;
    }
    return outcome;
}

//! Routine which performs a multi-part upload.
/*!
    \param bucket: The name of the S3 bucket where the object will be uploaded.
    \param key: The unique identifier (key) for the object within the S3 bucket.
    \param hashMethod: The hashing algorithm to use when calculating the hash value.
    \param ioStream: An IOStream for the data to be uploaded.
    \param useDefaultHashMethod: A flag indicating whether to use the default hash method or the one specified in the hashMethod parameter.
    \param[out] hashDataResult: The Hasher object that will store the concatenated hash value.
    \param[out] partHashes: The vector that will store the calculated hash values for each part of the file.
    \param client: The S3 client instance used to perform the upload operation.
    \return bool: Function succeeded.
*/
bool AwsDoc::S3::doMultipartUpload(const Aws::String &bucket,
                                   const Aws::String &key,
                                   AwsDoc::S3::HASH_METHOD hashMethod,
                                   const std::shared_ptr<Aws::IOStream> &ioStream,
                                   bool useDefaultHashMethod,
                                   AwsDoc::S3::Hasher &hashDataResult,
                                   std::vector<Aws::String> &partHashes,
                                   const Aws::S3::S3Client &client) {
    // Get object size.
    ioStream->seekg(0, ioStream->end);
    size_t objectSize = ioStream->tellg();
    ioStream->seekg(0, ioStream->beg);

    Aws::S3::Model::ChecksumAlgorithm checksumAlgorithm = Aws::S3::Model::ChecksumAlgorithm::NOT_SET;
    if (!useDefaultHashMethod) {
        if (hashMethod != MD5) {
            checksumAlgorithm = getChecksumAlgorithmForHashMethod(hashMethod);
        }
    }
    Aws::String uploadID = createMultipartUpload(bucket, key, checksumAlgorithm, client);
    if (uploadID.empty()) {
        return false;
    }

    std::vector<unsigned char> totalHashBuffer;
    bool uploadSucceeded = true;
    std::streamsize uploadedBytes = 0;
    int partNumber = 1;
    Aws::Vector<Aws::S3::Model::CompletedPart> parts;
    while (uploadedBytes < objectSize) {
        std::cout << "Uploading part " << partNumber << "." << std::endl;

        std::vector<unsigned char> buffer(UPLOAD_BUFFER_SIZE);
        std::streamsize bytesToRead = static_cast<std::streamsize>(std::min(buffer.size(),
                                                                            objectSize - uploadedBytes));
        ioStream->read((char *) buffer.data(), bytesToRead);
        Aws::Utils::Stream::PreallocatedStreamBuf preallocatedStreamBuf(buffer.data(),
                                                                        bytesToRead);
        std::shared_ptr<Aws::IOStream> body =
                Aws::MakeShared<Aws::IOStream>("SampleAllocationTag",
                                               &preallocatedStreamBuf);

        Hasher hasher;
        if (!hasher.calculateObjectHash(*body, hashMethod)) {
            std::cerr << "Error calculating hash." << std::endl;
            uploadSucceeded = false;
            break;
        }

        Aws::String base64HashString = hasher.getBase64HashString();
        partHashes.push_back(base64HashString);

        Aws::Utils::ByteBuffer hashBuffer = hasher.getByteBufferHash();

        totalHashBuffer.insert(totalHashBuffer.end(), hashBuffer.GetUnderlyingData(),
                               hashBuffer.GetUnderlyingData() + hashBuffer.GetLength());

        Aws::String calculatedHash;
        if (gUseCalculatedChecksum) {
            calculatedHash = base64HashString;
        }
        Aws::S3::Model::UploadPartOutcome uploadPartOutcome = uploadPart(bucket, key, uploadID, partNumber,
                                                                         checksumAlgorithm, base64HashString, body,
                                                                         client);
        if (uploadPartOutcome.IsSuccess()) {
            const Aws::S3::Model::UploadPartResult &uploadPartResult = uploadPartOutcome.GetResult();
            Aws::S3::Model::CompletedPart completedPart;
            completedPart.SetETag(uploadPartResult.GetETag());
            completedPart.SetPartNumber(partNumber);
            switch (hashMethod) {
                case AwsDoc::S3::MD5:
                    break; // Do nothing.
                case AwsDoc::S3::SHA1:
                    completedPart.SetChecksumSHA1(uploadPartResult.GetChecksumSHA1());
                    break;
                case AwsDoc::S3::SHA256:
                    completedPart.SetChecksumSHA256(uploadPartResult.GetChecksumSHA256());
                    break;
                case AwsDoc::S3::CRC32:
                    completedPart.SetChecksumCRC32(uploadPartResult.GetChecksumCRC32());
                    break;
                case AwsDoc::S3::CRC32C:
                    completedPart.SetChecksumCRC32C(uploadPartResult.GetChecksumCRC32C());
                    break;
                default:
                    std::cerr << "Unhandled hash method for completedPart." << std::endl;
                    break;
            }

            parts.push_back(completedPart);
        } else {
            std::cerr << "Error uploading part. " <<
                      uploadPartOutcome.GetError().GetMessage() << std::endl;
            uploadSucceeded = false;
            break;
        }

        uploadedBytes += bytesToRead;
        partNumber++;
    }

    if (!uploadSucceeded) {
        abortMultipartUpload(bucket, key, uploadID, client);
        return false;
    } else {

        Aws::S3::Model::CompleteMultipartUploadOutcome completeMultipartUploadOutcome = completeMultipartUpload(bucket,
                                                                                                                key,
                                                                                                                uploadID,
                                                                                                                parts,
                                                                                                                client);

        if (completeMultipartUploadOutcome.IsSuccess()) {
            std::cout << "Multipart upload completed." << std::endl;
            if (!hashDataResult.calculateObjectHash(totalHashBuffer, hashMethod)) {
                std::cerr << "Error calculating hash." << std::endl;
                return false;
            }
        } else {
            std::cerr << "Error completing multipart upload." <<
                      completeMultipartUploadOutcome.GetError().GetMessage()
                      << std::endl;
        }

        return completeMultipartUploadOutcome.IsSuccess();
    }
}

//! Routine which retrieves the string for a HASH_METHOD constant.
/*!
    \param: hashMethod: A HASH_METHOD constant.
    \return: String: A string description of the hash method.
*/
Aws::String AwsDoc::S3::stringForHashMethod(AwsDoc::S3::HASH_METHOD hashMethod) {
    switch (hashMethod) {
        case AwsDoc::S3::DEFAULT:
            return "Default";
        case AwsDoc::S3::MD5:
            return "MD5";
        case AwsDoc::S3::SHA1:
            return "SHA1";
        case AwsDoc::S3::SHA256:
            return "SHA256";
        case AwsDoc::S3::CRC32:
            return "CRC32";
        case AwsDoc::S3::CRC32C:
            return "CRC32C";
        default:
            return "Unknown";
    }
}

//! Routine that returns the ChecksumAlgorithm for a HASH_METHOD constant.
/*!
    \param: hashMethod: A HASH_METHOD constant.
    \return: ChecksumAlgorithm: The ChecksumAlgorithm enum.
*/
Aws::S3::Model::ChecksumAlgorithm
AwsDoc::S3::getChecksumAlgorithmForHashMethod(AwsDoc::S3::HASH_METHOD hashMethod) {
    Aws::S3::Model::ChecksumAlgorithm result = Aws::S3::Model::ChecksumAlgorithm::NOT_SET;
    switch (hashMethod) {
        case AwsDoc::S3::DEFAULT:
            std::cerr << "getChecksumAlgorithmForHashMethod- DEFAULT is not valid." << std::endl;
            break;  // Default is not supported.
        case AwsDoc::S3::MD5:
            break; // Ignore MD5.
        case AwsDoc::S3::SHA1:
            result = Aws::S3::Model::ChecksumAlgorithm::SHA1;
            break;
        case AwsDoc::S3::SHA256:
            result = Aws::S3::Model::ChecksumAlgorithm::SHA256;
            break;
        case AwsDoc::S3::CRC32:
            result = Aws::S3::Model::ChecksumAlgorithm::CRC32;
            break;
        case AwsDoc::S3::CRC32C:
            result = Aws::S3::Model::ChecksumAlgorithm::CRC32C;
            break;
        default:
            std::cerr << "Unknown hash method." << std::endl;
            break;

    }

    return result;
}

//! Routine which cleans up after the example is complete.
/*!
    \param bucket: The name of the S3 bucket where the object was uploaded.
    \param clientConfiguration: The client configuration for the S3 client.
    \return bool: Function succeeded.
*/
bool AwsDoc::S3::cleanUp(const Aws::String &bucketName,
                         const Aws::S3::S3ClientConfiguration &clientConfiguration) {

    Aws::Vector<Aws::String> keysResult;
    bool result = true;
    if (AwsDoc::S3::listObjects(bucketName, keysResult, clientConfiguration)) {
        if (!keysResult.empty()) {
            result = AwsDoc::S3::deleteObjects(keysResult, bucketName,
                                               clientConfiguration);
        }
    } else {
        result = false;
    }

    return result && AwsDoc::S3::deleteBucket(bucketName, clientConfiguration);
}

//! Console interaction introducing the workflow.
/*!
  \param bucketName: The name of the S3 bucket to use.
*/
void AwsDoc::S3::introductoryExplanations(const Aws::String &bucketName) {

    std::cout
            << "Welcome to the Amazon Simple Storage Service (Amazon S3) object integrity workflow."
            << std::endl;
    printAsterisksLine();
    std::cout
            << "This workflow demonstrates how Amazon S3 uses checksum values to verify the integrity of data\n";
    std::cout << "uploaded to Amazon S3 buckets" << std::endl;
    std::cout
            << "The AWS SDK for C++ automatically handles checksums.\n";
    std::cout
            << "By default it calculates a checksum that is uploaded with an object.\n"
            << "The default checksum algorithm for PutObject and MultiPart upload is an MD5 hash.\n"
            << "The default checksum algorithm for TransferManager uploads is a CRC32 checksum."
            << std::endl;
    std::cout
            << "You can override the default behavior, requiring one of the following checksums,\n";
    std::cout << "MD5, CRC32, CRC32C, SHA-1 or SHA-256." << std::endl;
    std::cout << "You can also set the checksum hash value, instead of letting the SDK calculate the value."
              << std::endl;
    std::cout
            << "For more information, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html."
            << std::endl;

    std::cout
            << "This workflow will locally compute checksums for files uploaded to an Amazon S3 bucket,\n";
    std::cout << "even when the SDK also computes the checksum." << std::endl;
    std::cout
            << "This is done to provide demonstration code for how the checksums are calculated."
            << std::endl;
    std::cout << "A bucket named '" << bucketName << "' will be created for the object uploads."
              << std::endl;
}

//! Console interaction which explains the PutObject results.
/*!
*/
void AwsDoc::S3::explainPutObjectResults() {

    std::cout << "The upload was successful.\n";
    std::cout << "If the checksums had not matched, the upload would have failed."
              << std::endl;
    std::cout
            << "The checksums calculated by the server have been retrieved using the GetObjectAttributes."
            << std::endl;
    std::cout
            << "The locally calculated checksums have been verified against the retrieved checksums."
            << std::endl;
}

//! Console interaction explaining transfer manager uploads.
/*!
  \param objectKey: The key for the object being uploaded.
*/
void AwsDoc::S3::introductoryTransferManagerUploadExplanations(
        const Aws::String &objectKey) {
    std::cout
            << "Now the workflow will demonstrate object integrity for TransferManager multi-part uploads."
            << std::endl;
    std::cout
            << "The AWS C++ SDK has a TransferManager class which simplifies multipart uploads."
            << std::endl;
    std::cout
            << "The following code lets the TransferManager handle much of the checksum configuration."
            << std::endl;

    std::cout << "An object with the key '" << objectKey
              << " will be uploaded by the TransferManager using a "
              << BUFFER_SIZE_IN_MEGABYTES << " MB buffer." << std::endl;
    if (gUseCalculatedChecksum) {
        std::cout << "For TransferManager uploads, this demo always lets the SDK calculate the hash value."
                  << std::endl;
    }

    pressEnterToContinue();
    printAsterisksLine();
}

//! Console interaction explaining multi-part uploads.
/*!
  \param objectKey: The key for the object being uploaded.
  \param chosenHashMethod: The hash method selected by the user.
*/
void AwsDoc::S3::multiPartUploadExplanations(const Aws::String &objectKey,
                                             HASH_METHOD chosenHashMethod) {
    std::cout
            << "Now we will provide an in-depth demonstration of multi-part uploading by calling the multi-part upload APIs directly."
            << std::endl;
    std::cout << "These are the same APIs used by the TransferManager when uploading large files."
              << std::endl;
    std::cout
            << "In the following code, the checksums are also calculated locally and then compared."
            << std::endl;
    std::cout
            << "For multi-part uploads, a checksum is uploaded with each part. The final checksum is a concatenation of"
            << std::endl;
    std::cout << "the checksums for each part." << std::endl;
    std::cout
            << "This is explained in the user guide, https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html,\""
            << " in the section \"Using part-level checksums for multipart uploads\"." << std::endl;

    std::cout << "Starting multipart upload of with hash method " <<
              stringForHashMethod(chosenHashMethod) << " uploading to with object key\n"
              << "'" << objectKey << "'," << std::endl;

}

//! Create a large file for doing multi-part uploads.
/*!
*/
bool AwsDoc::S3::createLargeFileIfNotExists() {
    // Generate a large file by writing this source file multiple times to a new file.
    if (std::filesystem::exists(MULTI_PART_TEST_FILE)) {
        return true;
    }

    std::ofstream newFile(MULTI_PART_TEST_FILE, std::ios::out

                                                | std::ios::binary);

    if (!newFile) {
        std::cerr << "createLargeFileIfNotExists- Error creating file " << MULTI_PART_TEST_FILE <<
                  std::endl;
        return false;
    }

    std::ifstream input(TEST_FILE, std::ios::in

                                   | std::ios::binary);
    if (!input) {
        std::cerr << "Error opening file " << TEST_FILE <<
                  std::endl;
        return false;
    }
    std::stringstream buffer;
    buffer << input.rdbuf();

    input.close();

    while (newFile.tellp() < LARGE_FILE_SIZE && !newFile.bad()) {
        buffer.seekg(std::stringstream::beg);
        newFile << buffer.rdbuf();
    }

    newFile.close();

    return true;
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [AbortMultipartUpload](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/AbortMultipartUpload)
  + [CompleteMultipartUpload](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CompleteMultipartUpload)
  + [CreateMultipartUpload](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/CreateMultipartUpload)
  + [DeleteObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/DeleteObject)
  + [GetObjectAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/GetObjectAttributes)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/PutObject)
  + [UploadPart](https://docs.aws.amazon.com/goto/SdkForCpp/s3-2006-03-01/UploadPart)

# SDK for C\$1\$1 を使用した Secrets Manager の例
<a name="cpp_1_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_cpp_1_topic"></a>

次のコード例は、`GetSecretValue` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/secrets-manager#code-examples)での設定と実行の方法を確認してください。

```
//! Retrieve an AWS Secrets Manager encrypted secret.
/*!
  \param secretID: The ID for the secret.
  \return bool: Function succeeded.
 */
bool AwsDoc::SecretsManager::getSecretValue(const Aws::String &secretID,
                                            const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SecretsManager::SecretsManagerClient secretsManagerClient(clientConfiguration);

    Aws::SecretsManager::Model::GetSecretValueRequest request;
    request.SetSecretId(secretID);

    Aws::SecretsManager::Model::GetSecretValueOutcome getSecretValueOutcome = secretsManagerClient.GetSecretValue(
            request);
    if (getSecretValueOutcome.IsSuccess()) {
        std::cout << "Secret is: "
                  << getSecretValueOutcome.GetResult().GetSecretString() << std::endl;
    }
    else {
        std::cerr << "Failed with Error: " << getSecretValueOutcome.GetError()
                  << std::endl;
    }

    return getSecretValueOutcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[GetSecretValue](https://docs.aws.amazon.com/goto/SdkForCpp/secretsmanager-2017-10-17/GetSecretValue)」を参照してください。

# SDK for C\$1\$1 を使用した Amazon SES の例
<a name="cpp_1_ses_code_examples"></a>

次のコード例は、Amazon SES AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateReceiptFilter`
<a name="ses_CreateReceiptFilter_cpp_1_topic"></a>

次のコード例は、`CreateReceiptFilter` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Create an Amazon Simple Email Service (Amazon SES) receipt filter..
/*!
  \param receiptFilterName: The name for the receipt filter.
  \param cidr: IP address or IP address range in Classless Inter-Domain Routing (CIDR) notation.
  \param policy: Block or allow enum of type ReceiptFilterPolicy.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::createReceiptFilter(const Aws::String &receiptFilterName,
                                      const Aws::String &cidr,
                                      Aws::SES::Model::ReceiptFilterPolicy policy,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);
    Aws::SES::Model::CreateReceiptFilterRequest createReceiptFilterRequest;
    Aws::SES::Model::ReceiptFilter receiptFilter;
    Aws::SES::Model::ReceiptIpFilter receiptIpFilter;
    receiptIpFilter.SetCidr(cidr);
    receiptIpFilter.SetPolicy(policy);
    receiptFilter.SetName(receiptFilterName);
    receiptFilter.SetIpFilter(receiptIpFilter);
    createReceiptFilterRequest.SetFilter(receiptFilter);
    Aws::SES::Model::CreateReceiptFilterOutcome createReceiptFilterOutcome = sesClient.CreateReceiptFilter(
            createReceiptFilterRequest);
    if (createReceiptFilterOutcome.IsSuccess()) {
        std::cout << "Successfully created receipt filter." << std::endl;
    }
    else {
        std::cerr << "Error creating receipt filter: " <<
                  createReceiptFilterOutcome.GetError().GetMessage() << std::endl;
    }

    return createReceiptFilterOutcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[CreateReceiptFilter](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/CreateReceiptFilter)」を参照してください。

### `CreateReceiptRule`
<a name="ses_CreateReceiptRule_cpp_1_topic"></a>

次のコード例は、`CreateReceiptRule` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Create an Amazon Simple Email Service (Amazon SES) receipt rule.
/*!
  \param receiptRuleName: The name for the receipt rule.
  \param s3BucketName: The name of the S3 bucket for incoming mail.
  \param s3ObjectKeyPrefix: The prefix for the objects in the S3 bucket.
  \param ruleSetName: The name of the rule set where the receipt rule is added.
  \param recipients: Aws::Vector of recipients.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::createReceiptRule(const Aws::String &receiptRuleName,
                                    const Aws::String &s3BucketName,
                                    const Aws::String &s3ObjectKeyPrefix,
                                    const Aws::String &ruleSetName,
                                    const Aws::Vector<Aws::String> &recipients,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::CreateReceiptRuleRequest createReceiptRuleRequest;

    Aws::SES::Model::S3Action s3Action;
    s3Action.SetBucketName(s3BucketName);
    s3Action.SetObjectKeyPrefix(s3ObjectKeyPrefix);

    Aws::SES::Model::ReceiptAction receiptAction;
    receiptAction.SetS3Action(s3Action);

    Aws::SES::Model::ReceiptRule receiptRule;
    receiptRule.SetName(receiptRuleName);
    receiptRule.WithRecipients(recipients);

    Aws::Vector<Aws::SES::Model::ReceiptAction> receiptActionList;
    receiptActionList.emplace_back(receiptAction);
    receiptRule.SetActions(receiptActionList);

    createReceiptRuleRequest.SetRuleSetName(ruleSetName);
    createReceiptRuleRequest.SetRule(receiptRule);

    auto outcome = sesClient.CreateReceiptRule(createReceiptRuleRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully created receipt rule." << std::endl;
    }
    else {
        std::cerr << "Error creating receipt rule. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[CreateReceiptRule](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/CreateReceiptRule)」を参照してください。

### `CreateReceiptRuleSet`
<a name="ses_CreateReceiptRuleSet_cpp_1_topic"></a>

次のコード例は、`CreateReceiptRuleSet` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Create an Amazon Simple Email Service (Amazon SES) receipt rule set.
/*!
  \param ruleSetName: The name of the rule set.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::createReceiptRuleSet(const Aws::String &ruleSetName,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::CreateReceiptRuleSetRequest createReceiptRuleSetRequest;

    createReceiptRuleSetRequest.SetRuleSetName(ruleSetName);

    Aws::SES::Model::CreateReceiptRuleSetOutcome outcome = sesClient.CreateReceiptRuleSet(
            createReceiptRuleSetRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully created receipt rule set." << std::endl;
    }
    else {
        std::cerr << "Error creating receipt rule set. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[CreateReceiptRuleSet](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/CreateReceiptRuleSet)」を参照してください。

### `CreateTemplate`
<a name="ses_CreateTemplate_cpp_1_topic"></a>

次のコード例は、`CreateTemplate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Create an Amazon Simple Email Service (Amazon SES) template.
/*!
  \param templateName: The name of the template.
  \param htmlPart: The HTML body of the email.
  \param subjectPart: The subject line of the email.
  \param textPart: The plain text version of the email.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::createTemplate(const Aws::String &templateName,
                                 const Aws::String &htmlPart,
                                 const Aws::String &subjectPart,
                                 const Aws::String &textPart,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::CreateTemplateRequest createTemplateRequest;
    Aws::SES::Model::Template aTemplate;

    aTemplate.SetTemplateName(templateName);
    aTemplate.SetHtmlPart(htmlPart);
    aTemplate.SetSubjectPart(subjectPart);
    aTemplate.SetTextPart(textPart);

    createTemplateRequest.SetTemplate(aTemplate);

    Aws::SES::Model::CreateTemplateOutcome outcome = sesClient.CreateTemplate(
            createTemplateRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully created template." << templateName << "."
                  << std::endl;
    }
    else {
        std::cerr << "Error creating template. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[CreateTemplate](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/CreateTemplate)」を参照してください。

### `DeleteIdentity`
<a name="ses_DeleteIdentity_cpp_1_topic"></a>

次のコード例は、`DeleteIdentity` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Delete the specified identity (an email address or a domain).
/*!
  \param identity: The identity to delete.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::deleteIdentity(const Aws::String &identity,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::DeleteIdentityRequest deleteIdentityRequest;

    deleteIdentityRequest.SetIdentity(identity);

    Aws::SES::Model::DeleteIdentityOutcome outcome = sesClient.DeleteIdentity(
            deleteIdentityRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted identity." << std::endl;
    }
    else {
        std::cerr << "Error deleting identity. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteIdentity](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/DeleteIdentity)」を参照してください。

### `DeleteReceiptFilter`
<a name="ses_DeleteReceiptFilter_cpp_1_topic"></a>

次のコード例は、`DeleteReceiptFilter` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an Amazon Simple Email Service (Amazon SES) receipt filter.
/*!
  \param receiptFilterName: The name for the receipt filter.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::deleteReceiptFilter(const Aws::String &receiptFilterName,
                                      const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::DeleteReceiptFilterRequest deleteReceiptFilterRequest;

    deleteReceiptFilterRequest.SetFilterName(receiptFilterName);

    Aws::SES::Model::DeleteReceiptFilterOutcome outcome = sesClient.DeleteReceiptFilter(
            deleteReceiptFilterRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted receipt filter." << std::endl;
    }
    else {
        std::cerr << "Error deleting receipt filter. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DeleteReceiptFilter](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/DeleteReceiptFilter)」を参照してください。

### `DeleteReceiptRule`
<a name="ses_DeleteReceiptRule_cpp_1_topic"></a>

次のコード例は、`DeleteReceiptRule` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an Amazon Simple Email Service (Amazon SES) receipt rule.
/*!
  \param receiptRuleName: The name for the receipt rule.
  \param receiptRuleSetName: The name for the receipt rule set.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::deleteReceiptRule(const Aws::String &receiptRuleName,
                                    const Aws::String &receiptRuleSetName,
                                    const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::DeleteReceiptRuleRequest deleteReceiptRuleRequest;

    deleteReceiptRuleRequest.SetRuleName(receiptRuleName);
    deleteReceiptRuleRequest.SetRuleSetName(receiptRuleSetName);

    Aws::SES::Model::DeleteReceiptRuleOutcome outcome = sesClient.DeleteReceiptRule(
            deleteReceiptRuleRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted receipt rule." << std::endl;
    }
    else {
        std::cout << "Error deleting receipt rule. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DeleteReceiptRule](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/DeleteReceiptRule)」を参照してください。

### `DeleteReceiptRuleSet`
<a name="ses_DeleteReceiptRuleSet_cpp_1_topic"></a>

次のコード例は、`DeleteReceiptRuleSet` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an Amazon Simple Email Service (Amazon SES) receipt rule set.
/*!
  \param receiptRuleSetName: The name for the receipt rule set.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::deleteReceiptRuleSet(const Aws::String &receiptRuleSetName,
                                       const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::DeleteReceiptRuleSetRequest deleteReceiptRuleSetRequest;

    deleteReceiptRuleSetRequest.SetRuleSetName(receiptRuleSetName);

    Aws::SES::Model::DeleteReceiptRuleSetOutcome outcome = sesClient.DeleteReceiptRuleSet(
            deleteReceiptRuleSetRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted receipt rule set." << std::endl;
    }

    else {
        std::cerr << "Error deleting receipt rule set. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[DeleteReceiptRuleSet](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/DeleteReceiptRuleSet)」を参照してください。

### `DeleteTemplate`
<a name="ses_DeleteTemplate_cpp_1_topic"></a>

次のコード例は、`DeleteTemplate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an Amazon Simple Email Service (Amazon SES) template.
/*!
  \param templateName: The name for the template.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::deleteTemplate(const Aws::String &templateName,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::DeleteTemplateRequest deleteTemplateRequest;

    deleteTemplateRequest.SetTemplateName(templateName);

    Aws::SES::Model::DeleteTemplateOutcome outcome = sesClient.DeleteTemplate(
            deleteTemplateRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted template." << std::endl;
    }
    else {
        std::cerr << "Error deleting template. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*のの「[DeleteTemplate](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/DeleteTemplate)」を参照してください。

### `GetTemplate`
<a name="ses_GetTemplate_cpp_1_topic"></a>

次のコード例は、`GetTemplate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Get a template's attributes.
/*!
  \param templateName: The name for the template.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::getTemplate(const Aws::String &templateName,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::GetTemplateRequest getTemplateRequest;

    getTemplateRequest.SetTemplateName(templateName);

    Aws::SES::Model::GetTemplateOutcome outcome = sesClient.GetTemplate(
            getTemplateRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully got template." << std::endl;
    }

    else {
        std::cerr << "Error getting template. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[GetTemplate](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/GetTemplate)」を参照してください。

### `ListIdentities`
<a name="ses_ListIdentities_cpp_1_topic"></a>

次のコード例は、`ListIdentities` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! List the identities associated with this account.
/*!
  \param identityType: The identity type enum. "NOT_SET" is a valid option.
  \param identities; A vector to receive the retrieved identities.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::listIdentities(Aws::SES::Model::IdentityType identityType,
                                 Aws::Vector<Aws::String> &identities,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::ListIdentitiesRequest listIdentitiesRequest;

    if (identityType != Aws::SES::Model::IdentityType::NOT_SET) {
        listIdentitiesRequest.SetIdentityType(identityType);
    }

    Aws::String nextToken; // Used for paginated results.
    do {
        if (!nextToken.empty()) {
            listIdentitiesRequest.SetNextToken(nextToken);
        }
        Aws::SES::Model::ListIdentitiesOutcome outcome = sesClient.ListIdentities(
                listIdentitiesRequest);

        if (outcome.IsSuccess()) {
            const auto &retrievedIdentities = outcome.GetResult().GetIdentities();
            if (!retrievedIdentities.empty()) {
                identities.insert(identities.cend(), retrievedIdentities.cbegin(),
                                  retrievedIdentities.cend());
            }
            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cout << "Error listing identities. " << outcome.GetError().GetMessage()
                      << std::endl;
            return false;
        }
    } while (!nextToken.empty());

    return true;
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[ListIdentities](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/ListIdentities)」を参照してください。

### `ListReceiptFilters`
<a name="ses_ListReceiptFilters_cpp_1_topic"></a>

次のコード例は、`ListReceiptFilters` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! List the receipt filters associated with this account.
/*!
  \param filters; A vector of "ReceiptFilter" to receive the retrieved filters.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::SES::listReceiptFilters(Aws::Vector<Aws::SES::Model::ReceiptFilter> &filters,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);
    Aws::SES::Model::ListReceiptFiltersRequest listReceiptFiltersRequest;

    Aws::SES::Model::ListReceiptFiltersOutcome outcome = sesClient.ListReceiptFilters(
            listReceiptFiltersRequest);
    if (outcome.IsSuccess()) {
        auto &retrievedFilters = outcome.GetResult().GetFilters();
        if (!retrievedFilters.empty()) {
            filters.insert(filters.cend(), retrievedFilters.cbegin(),
                           retrievedFilters.cend());
        }
    }
    else {
        std::cerr << "Error retrieving IP address filters: "
                  << outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[ListReceiptFilters](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/ListReceiptFilters)」を参照してください。

### `SendEmail`
<a name="ses_SendEmail_cpp_1_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Send an email to a list of recipients.
/*!
  \param recipients; Vector of recipient email addresses.
  \param subject: Email subject.
  \param htmlBody: Email body as HTML. At least one body data is required.
  \param textBody: Email body as plain text. At least one body data is required.
  \param senderEmailAddress: Email address of sender. Ignored if empty string.
  \param ccAddresses: Vector of cc addresses. Ignored if empty.
  \param replyToAddress: Reply to email address. Ignored if empty string.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::sendEmail(const Aws::Vector<Aws::String> &recipients,
                            const Aws::String &subject,
                            const Aws::String &htmlBody,
                            const Aws::String &textBody,
                            const Aws::String &senderEmailAddress,
                            const Aws::Vector<Aws::String> &ccAddresses,
                            const Aws::String &replyToAddress,
                            const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::Destination destination;
    if (!ccAddresses.empty()) {
        destination.WithCcAddresses(ccAddresses);
    }
    if (!recipients.empty()) {
        destination.WithToAddresses(recipients);
    }

    Aws::SES::Model::Body message_body;
    if (!htmlBody.empty()) {
        message_body.SetHtml(
                Aws::SES::Model::Content().WithCharset("UTF-8").WithData(htmlBody));
    }

    if (!textBody.empty()) {
        message_body.SetText(
                Aws::SES::Model::Content().WithCharset("UTF-8").WithData(textBody));
    }

    Aws::SES::Model::Message message;
    message.SetBody(message_body);
    message.SetSubject(
            Aws::SES::Model::Content().WithCharset("UTF-8").WithData(subject));

    Aws::SES::Model::SendEmailRequest sendEmailRequest;
    sendEmailRequest.SetDestination(destination);
    sendEmailRequest.SetMessage(message);
    if (!senderEmailAddress.empty()) {
        sendEmailRequest.SetSource(senderEmailAddress);
    }
    if (!replyToAddress.empty()) {
        sendEmailRequest.AddReplyToAddresses(replyToAddress);
    }

    auto outcome = sesClient.SendEmail(sendEmailRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully sent message with ID "
                  << outcome.GetResult().GetMessageId()
                  << "." << std::endl;
    }
    else {
        std::cerr << "Error sending message. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[SendEmail](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/SendEmail)」を参照してください。

### `SendTemplatedEmail`
<a name="ses_SendTemplatedEmail_cpp_1_topic"></a>

次のコード例は、`SendTemplatedEmail` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Send a templated email to a list of recipients.
/*!
  \param recipients; Vector of recipient email addresses.
  \param templateName: The name of the template to use.
  \param templateData: Map of key-value pairs for replacing text in template.
  \param senderEmailAddress: Email address of sender. Ignored if empty string.
  \param ccAddresses: Vector of cc addresses. Ignored if empty.
  \param replyToAddress: Reply to email address. Ignored if empty string.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::sendTemplatedEmail(const Aws::Vector<Aws::String> &recipients,
                                     const Aws::String &templateName,
                                     const Aws::Map<Aws::String, Aws::String> &templateData,
                                     const Aws::String &senderEmailAddress,
                                     const Aws::Vector<Aws::String> &ccAddresses,
                                     const Aws::String &replyToAddress,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::Destination destination;
    if (!ccAddresses.empty()) {
        destination.WithCcAddresses(ccAddresses);
    }
    if (!recipients.empty()) {
        destination.WithToAddresses(recipients);
    }

    Aws::SES::Model::SendTemplatedEmailRequest sendTemplatedEmailRequest;
    sendTemplatedEmailRequest.SetDestination(destination);
    sendTemplatedEmailRequest.SetTemplate(templateName);

    std::ostringstream templateDataStream;
    templateDataStream << "{";
    size_t dataCount = 0;
    for (auto &pair: templateData) {
        templateDataStream << "\"" << pair.first << "\":\"" << pair.second << "\"";
        dataCount++;
        if (dataCount < templateData.size()) {
            templateDataStream << ",";
        }
    }
    templateDataStream << "}";

    sendTemplatedEmailRequest.SetTemplateData(templateDataStream.str());

    if (!senderEmailAddress.empty()) {
        sendTemplatedEmailRequest.SetSource(senderEmailAddress);
    }
    if (!replyToAddress.empty()) {
        sendTemplatedEmailRequest.AddReplyToAddresses(replyToAddress);
    }

    auto outcome = sesClient.SendTemplatedEmail(sendTemplatedEmailRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully sent templated message with ID "
                  << outcome.GetResult().GetMessageId()
                  << "." << std::endl;
    }
    else {
        std::cerr << "Error sending templated message. "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[SendTemplatedEmail](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/SendTemplatedEmail)」を参照してください。

### `UpdateTemplate`
<a name="ses_UpdateTemplate_cpp_1_topic"></a>

次のコード例は、`UpdateTemplate` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Update an Amazon Simple Email Service (Amazon SES) template.
/*!
  \param templateName: The name of the template.
  \param htmlPart: The HTML body of the email.
  \param subjectPart: The subject line of the email.
  \param textPart: The plain text version of the email.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::updateTemplate(const Aws::String &templateName,
                                 const Aws::String &htmlPart,
                                 const Aws::String &subjectPart,
                                 const Aws::String &textPart,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::Template templateValues;

    templateValues.SetTemplateName(templateName);
    templateValues.SetSubjectPart(subjectPart);
    templateValues.SetHtmlPart(htmlPart);
    templateValues.SetTextPart(textPart);

    Aws::SES::Model::UpdateTemplateRequest updateTemplateRequest;
    updateTemplateRequest.SetTemplate(templateValues);

    Aws::SES::Model::UpdateTemplateOutcome outcome = sesClient.UpdateTemplate(updateTemplateRequest);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated template." << std::endl;
    } else {
        std::cerr << "Error updating template. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[UpdateTemplate](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/UpdateTemplate)」を参照してください。

### `VerifyEmailIdentity`
<a name="ses_VerifyEmailIdentity_cpp_1_topic"></a>

次のコード例は、`VerifyEmailIdentity` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
//! Add an email address to the list of identities associated with this account and
//! initiate verification.
/*!
  \param emailAddress; The email address to add.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SES::verifyEmailIdentity(const Aws::String &emailAddress,
                         const Aws::Client::ClientConfiguration &clientConfiguration)
{
    Aws::SES::SESClient sesClient(clientConfiguration);

    Aws::SES::Model::VerifyEmailIdentityRequest verifyEmailIdentityRequest;

    verifyEmailIdentityRequest.SetEmailAddress(emailAddress);

    Aws::SES::Model::VerifyEmailIdentityOutcome outcome = sesClient.VerifyEmailIdentity(verifyEmailIdentityRequest);

    if (outcome.IsSuccess())
    {
        std::cout << "Email verification initiated." << std::endl;
    }

    else
    {
        std::cerr << "Error initiating email verification. " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[VerifyEmailIdentity](https://docs.aws.amazon.com/goto/SdkForCpp/email-2010-12-01/VerifyEmailIdentity)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_cpp_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for C\$1\$1**  
 Amazon Aurora Serverless データベースに保存されている作業項目を追跡して報告するウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora Serverless データをクエリし、React アプリケーションで使用するための C\$1\$1 REST API の完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/serverless-aurora) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for C\$1\$1 を使用した Amazon SNS の例
<a name="cpp_1_sns_code_examples"></a>

次のコード例は、Amazon SNS AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon SNS
<a name="sns_Hello_cpp_1_topic"></a>

次のコード例は、Amazon SNS の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns/hello_sns#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS sns)

# Set this project's name.
project("hello_sns")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
    # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

    # set(BIN_SUB_DIR "/Debug") # If you are building from the command line you may need to uncomment this
    # and set the proper subdirectory to the executables' location.

    AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif ()

add_executable(${PROJECT_NAME}
        hello_sns.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1sns.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/sns/SNSClient.h>
#include <aws/sns/model/ListTopicsRequest.h>
#include <iostream>

/*
 *  A "Hello SNS" starter application which initializes an Amazon Simple Notification
 *  Service (Amazon SNS) client and lists the SNS topics in the current account.
 *
 *  main function
 *
 *  Usage: 'hello_sns'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::SNS::SNSClient snsClient(clientConfig);

        Aws::Vector<Aws::SNS::Model::Topic> allTopics;
        Aws::String nextToken; // Next token is used to handle a paginated response.
        do {
            Aws::SNS::Model::ListTopicsRequest request;

            if (!nextToken.empty()) {
                request.SetNextToken(nextToken);
            }

            const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics(
                    request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::SNS::Model::Topic> &paginatedTopics =
                        outcome.GetResult().GetTopics();
                if (!paginatedTopics.empty()) {
                    allTopics.insert(allTopics.cend(), paginatedTopics.cbegin(),
                                     paginatedTopics.cend());
                }
            }
            else {
                std::cerr << "Error listing topics " << outcome.GetError().GetMessage()
                          << std::endl;
                return 1;
            }

            nextToken = outcome.GetResult().GetNextToken();
        } while (!nextToken.empty());

        std::cout << "Hello Amazon SNS! You have " << allTopics.size() << " topic"
                  << (allTopics.size() == 1 ? "" : "s") << " in your account."
                  << std::endl;

        if (!allTopics.empty()) {
            std::cout << "Here are your topic ARNs." << std::endl;
            for (const Aws::SNS::Model::Topic &topic: allTopics) {
                std::cout << "  * " << topic.GetTopicArn() << std::endl;
            }
        }
    }


    Aws::ShutdownAPI(options); // Should only be called once.
    return 0;
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[ListTopics](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/ListTopics)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_cpp_1_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! 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\$1\$1 API リファレンス*の「[CreateTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/CreateTopic)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_cpp_1_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! Delete an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::deleteTopic(const Aws::String &topicARN,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::DeleteTopicRequest request;
    request.SetTopicArn(topicARN);

    const Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted the Amazon SNS topic " << topicARN << std::endl;
    }
    else {
        std::cerr << "Error deleting topic " << topicARN << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/DeleteTopic)」を参照してください。

### `GetSMSAttributes`
<a name="sns_GetSMSAttributes_cpp_1_topic"></a>

次のコード例は、`GetSMSAttributes` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! Retrieve the default settings for sending SMS messages from your AWS account by using
//! Amazon Simple Notification Service (Amazon SNS).
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::SNS::getSMSType(const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::GetSMSAttributesRequest request;
    //Set the request to only retrieve the DefaultSMSType setting.
    //Without the following line, GetSMSAttributes would retrieve all settings.
    request.AddAttributes("DefaultSMSType");

    const Aws::SNS::Model::GetSMSAttributesOutcome outcome = snsClient.GetSMSAttributes(
            request);

    if (outcome.IsSuccess()) {
        const Aws::Map<Aws::String, Aws::String> attributes =
                outcome.GetResult().GetAttributes();
        if (!attributes.empty()) {
            for (auto const &att: attributes) {
                std::cout << att.first << ":  " << att.second << std::endl;
            }
        }
        else {
            std::cout
                    << "AwsDoc::SNS::getSMSType - an empty map of attributes was retrieved."
                    << std::endl;
        }
    }
    else {
        std::cerr << "Error while getting SMS Type: '"
                  << outcome.GetError().GetMessage()
                  << "'" << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[GetSMSAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/GetSMSAttributes)」を参照してください。**

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_cpp_1_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! Retrieve the properties of an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::getTopicAttributes(const Aws::String &topicARN,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);
    Aws::SNS::Model::GetTopicAttributesRequest request;
    request.SetTopicArn(topicARN);

    const Aws::SNS::Model::GetTopicAttributesOutcome outcome = snsClient.GetTopicAttributes(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "Topic Attributes:" << std::endl;
        for (auto const &attribute: outcome.GetResult().GetAttributes()) {
            std::cout << "  * " << attribute.first << " : " << attribute.second
                      << std::endl;
        }
    }
    else {
        std::cerr << "Error while getting Topic attributes "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/GetTopicAttributes)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_cpp_1_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! Retrieve a list of Amazon Simple Notification Service (Amazon SNS) subscriptions.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::listSubscriptions(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::String nextToken; // Next token is used to handle a paginated response.
    bool result = true;
    Aws::Vector<Aws::SNS::Model::Subscription> subscriptions;
    do {
        Aws::SNS::Model::ListSubscriptionsRequest request;

        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        const Aws::SNS::Model::ListSubscriptionsOutcome outcome = snsClient.ListSubscriptions(
                request);

        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::SNS::Model::Subscription> &newSubscriptions =
                    outcome.GetResult().GetSubscriptions();
            subscriptions.insert(subscriptions.cend(), newSubscriptions.begin(),
                                 newSubscriptions.end());
        }
        else {
            std::cerr << "Error listing subscriptions "
                      << outcome.GetError().GetMessage()
                      <<
                      std::endl;
            result = false;
            break;
        }

        nextToken = outcome.GetResult().GetNextToken();
    } while (!nextToken.empty());

    if (result) {
        if (subscriptions.empty()) {
            std::cout << "No subscriptions found" << std::endl;
        }
        else {
            std::cout << "Subscriptions list:" << std::endl;
            for (auto const &subscription: subscriptions) {
                std::cout << "  * " << subscription.GetSubscriptionArn() << std::endl;
            }
        }
    }
    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListSubscriptions](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/ListSubscriptions)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_cpp_1_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! Retrieve a list of Amazon Simple Notification Service (Amazon SNS) topics.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::SNS::listTopics(const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::String nextToken; // Next token is used to handle a paginated response.
    bool result = true;
    do {
        Aws::SNS::Model::ListTopicsRequest request;

        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics(
                request);

        if (outcome.IsSuccess()) {
            std::cout << "Topics list:" << std::endl;
            for (auto const &topic: outcome.GetResult().GetTopics()) {
                std::cout << "  * " << topic.GetTopicArn() << std::endl;
            }
        }
        else {
            std::cerr << "Error listing topics " << outcome.GetError().GetMessage() <<
                      std::endl;
            result = false;
            break;
        }

        nextToken = outcome.GetResult().GetNextToken();
    } while (!nextToken.empty());

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[ListTopics](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/ListTopics)」を参照してください。

### `Publish`
<a name="sns_Publish_cpp_1_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param message: The message to publish.
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::publishToTopic(const Aws::String &message,
                                 const Aws::String &topicARN,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::PublishRequest request;
    request.SetMessage(message);
    request.SetTopicArn(topicARN);

    const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

    if (outcome.IsSuccess()) {
        std::cout << "Message published successfully with id '"
                  << outcome.GetResult().GetMessageId() << "'." << std::endl;
    }
    else {
        std::cerr << "Error while publishing message "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
属性を指定してメッセージを発行します。  

```
        static const Aws::String TONE_ATTRIBUTE("tone");
        static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious",
                                                       "sincere"};

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SNS::SNSClient snsClient(clientConfiguration);

        Aws::SNS::Model::PublishRequest request;
        request.SetTopicArn(topicARN);
        Aws::String message = askQuestion("Enter a message text to publish.  ");
        request.SetMessage(message);

        if (filteringMessages && askYesNoQuestion(
                "Add an attribute to this message? (y/n) ")) {
            for (size_t i = 0; i < TONES.size(); ++i) {
                std::cout << "  " << (i + 1) << ". " << TONES[i] << std::endl;
            }
            int selection = askQuestionForIntRange(
                    "Enter a number for an attribute. ",
                    1, static_cast<int>(TONES.size()));
            Aws::SNS::Model::MessageAttributeValue messageAttributeValue;
            messageAttributeValue.SetDataType("String");
            messageAttributeValue.SetStringValue(TONES[selection - 1]);
            request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue);
        }

        Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

        if (outcome.IsSuccess()) {
            std::cout << "Your message was successfully published." << std::endl;
        }
        else {
            std::cerr << "Error with TopicsAndQueues::Publish. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[Publish](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)」を参照してください。

### `SetSMSAttributes`
<a name="sns_SetSMSAttributes_cpp_1_topic"></a>

次のコード例は、`SetSMSAttributes` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。
Amazon SNS を使用して DefaultSMSType 属性を設定する方法。  

```
//! Set the default settings for sending SMS messages.
/*!
  \param smsType: The type of SMS message that you will send by default.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::setSMSType(const Aws::String &smsType,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::SetSMSAttributesRequest request;
    request.AddAttributes("DefaultSMSType", smsType);

    const Aws::SNS::Model::SetSMSAttributesOutcome outcome = snsClient.SetSMSAttributes(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "SMS Type set successfully " << std::endl;
    }
    else {
        std::cerr << "Error while setting SMS Type: '"
                  << outcome.GetError().GetMessage()
                  << "'" << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[SetSMSAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/SetSMSAttributes)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_cpp_1_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an email address.
/*!
  \param topicARN: An SNS topic Amazon Resource Name (ARN).
  \param emailAddress: An email address.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::subscribeEmail(const Aws::String &topicARN,
                                 const Aws::String &emailAddress,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::SubscribeRequest request;
    request.SetTopicArn(topicARN);
    request.SetProtocol("email");
    request.SetEndpoint(emailAddress);

    const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);

    if (outcome.IsSuccess()) {
        std::cout << "Subscribed successfully." << std::endl;
        std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn()
                  << "'." << std::endl;
    }
    else {
        std::cerr << "Error while subscribing " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
モバイルアプリケーションをトピックにサブスクライブします。  

```
//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to a mobile app.
/*!
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param endpointARN: The ARN for a mobile app or device endpoint.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::SNS::subscribeApp(const Aws::String &topicARN,
                          const Aws::String &endpointARN,
                          const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::SubscribeRequest request;
    request.SetTopicArn(topicARN);
    request.SetProtocol("application");
    request.SetEndpoint(endpointARN);

    const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);

    if (outcome.IsSuccess()) {
        std::cout << "Subscribed successfully." << std::endl;
        std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn()
                  << "'." << std::endl;
    }
    else {
        std::cerr << "Error while subscribing " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
Lambda 関数をトピックにサブスクライブします。  

```
//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function.
/*!
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param lambdaFunctionARN: The ARN for an AWS Lambda function.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::subscribeLambda(const Aws::String &topicARN,
                                  const Aws::String &lambdaFunctionARN,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::SubscribeRequest request;
    request.SetTopicArn(topicARN);
    request.SetProtocol("lambda");
    request.SetEndpoint(lambdaFunctionARN);

    const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);

    if (outcome.IsSuccess()) {
        std::cout << "Subscribed successfully." << std::endl;
        std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn()
                  << "'." << std::endl;
    }
    else {
        std::cerr << "Error while subscribing " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
SQS キューをトピックにサブスクライブします。  

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SNS::SNSClient snsClient(clientConfiguration);

            Aws::SNS::Model::SubscribeRequest request;
            request.SetTopicArn(topicARN);
            request.SetProtocol("sqs");
            request.SetEndpoint(queueARN);

            Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);

            if (outcome.IsSuccess()) {
                Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn();
                std::cout << "The queue '" << queueName
                          << "' has been subscribed to the topic '"
                          << "'" << topicName << "'" << std::endl;
                std::cout << "with the subscription ARN '" << subscriptionARN << "."
                          << std::endl;
                subscriptionARNS.push_back(subscriptionARN);
            }
            else {
                std::cerr << "Error with TopicsAndQueues::Subscribe. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
```
トピックにフィルターでサブスクライブします。  

```
        static const Aws::String TONE_ATTRIBUTE("tone");
        static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious",
                                                       "sincere"};

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SNS::SNSClient snsClient(clientConfiguration);

            Aws::SNS::Model::SubscribeRequest request;
            request.SetTopicArn(topicARN);
            request.SetProtocol("sqs");
            request.SetEndpoint(queueARN);
            if (isFifoTopic) {
                if (first) {
                    std::cout << "Subscriptions to a FIFO topic can have filters."
                              << std::endl;
                    std::cout
                            << "If you add a filter to this subscription, then only the filtered messages "
                            << "will be received in the queue." << std::endl;
                    std::cout << "For information about message filtering, "
                              << "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html"
                              << std::endl;
                    std::cout << "For this example, you can filter messages by a \""
                              << TONE_ATTRIBUTE << "\" attribute." << std::endl;
                }

                std::ostringstream ostringstream;
                ostringstream << "Filter messages for \"" << queueName
                              << "\"'s subscription to the topic \""
                              << topicName << "\"?  (y/n)";

                // Add filter if user answers yes.
                if (askYesNoQuestion(ostringstream.str())) {
                    Aws::String jsonPolicy = getFilterPolicyFromUser();
                    if (!jsonPolicy.empty()) {
                        filteringMessages = true;

                        std::cout << "This is the filter policy for this subscription."
                                  << std::endl;
                        std::cout << jsonPolicy << std::endl;

                        request.AddAttributes("FilterPolicy", jsonPolicy);
                    }
                    else {
                        std::cout
                                << "Because you did not select any attributes, no filter "
                                << "will be added to this subscription." << std::endl;
                    }
                }
            }  // if (isFifoTopic)
            Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);

            if (outcome.IsSuccess()) {
                Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn();
                std::cout << "The queue '" << queueName
                          << "' has been subscribed to the topic '"
                          << "'" << topicName << "'" << std::endl;
                std::cout << "with the subscription ARN '" << subscriptionARN << "."
                          << std::endl;
                subscriptionARNS.push_back(subscriptionARN);
            }
            else {
                std::cerr << "Error with TopicsAndQueues::Subscribe. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }

//! Routine that lets the user select attributes for a subscription filter policy.
/*!
 \sa getFilterPolicyFromUser()
 \return Aws::String: The filter policy as JSON.
 */
Aws::String AwsDoc::TopicsAndQueues::getFilterPolicyFromUser() {
    std::cout
            << "You can filter messages by one or more of the following \""
            << TONE_ATTRIBUTE << "\" attributes." << std::endl;

    std::vector<Aws::String> filterSelections;
    int selection;
    do {
        for (size_t j = 0; j < TONES.size(); ++j) {
            std::cout << "  " << (j + 1) << ". " << TONES[j]
                      << std::endl;
        }
        selection = askQuestionForIntRange(
                "Enter a number (or enter zero to stop adding more). ",
                0, static_cast<int>(TONES.size()));

        if (selection != 0) {
            const Aws::String &selectedTone(TONES[selection - 1]);
            // Add the tone to the selection if it is not already added.
            if (std::find(filterSelections.begin(),
                          filterSelections.end(),
                          selectedTone)
                == filterSelections.end()) {
                filterSelections.push_back(selectedTone);
            }
        }
    } while (selection != 0);

    Aws::String result;
    if (!filterSelections.empty()) {
        std::ostringstream jsonPolicyStream;
        jsonPolicyStream << "{ \"" << TONE_ATTRIBUTE << "\": [";


        for (size_t j = 0; j < filterSelections.size(); ++j) {
            jsonPolicyStream << "\"" << filterSelections[j] << "\"";
            if (j < filterSelections.size() - 1) {
                jsonPolicyStream << ",";
            }
        }
        jsonPolicyStream << "] }";

        result = jsonPolicyStream.str();
    }

    return result;
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[Subscribe](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Subscribe)」を参照してください。

### `Unsubscribe`
<a name="sns_Unsubscribe_cpp_1_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! Delete a subscription to an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param subscriptionARN: The Amazon Resource Name (ARN) for an Amazon SNS topic subscription.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::unsubscribe(const Aws::String &subscriptionARN,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::UnsubscribeRequest request;
    request.SetSubscriptionArn(subscriptionARN);

    const Aws::SNS::Model::UnsubscribeOutcome outcome = snsClient.Unsubscribe(request);

    if (outcome.IsSuccess()) {
        std::cout << "Unsubscribed successfully " << std::endl;
    }
    else {
        std::cerr << "Error while unsubscribing " << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[Unsubscribe](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Unsubscribe)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_cpp_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for C\$1\$1**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### SMS テキストメッセージを発行する
<a name="sns_PublishTextSMS_cpp_1_topic"></a>

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Publish SMS: use Amazon Simple Notification Service (Amazon SNS) to send an SMS text message to a phone number.
 * Note: This requires additional AWS configuration prior to running example. 
 * 
 *  NOTE: When you start using Amazon SNS to send SMS messages, your AWS account is in the SMS sandbox and you can only
 *  use verified destination phone numbers. See https://docs.aws.amazon.com/sns/latest/dg/sns-sms-sandbox.html.
 *  NOTE: If destination is in the US, you also have an additional restriction that you have use a dedicated
 *  origination ID (phone number). You can request an origination number using Amazon Pinpoint for a fee.
 *  See https://aws.amazon.com/blogs/compute/provisioning-and-using-10dlc-origination-numbers-with-amazon-sns/ 
 *  for more information. 
 * 
 *  <phone_number_value> input parameter uses E.164 format. 
 *  For example, in United States, this input value should be of the form: +12223334444
 */

//! Send an SMS text message to a phone number.
/*!
  \param message: The message to publish.
  \param phoneNumber: The phone number of the recipient in E.164 format.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::publishSms(const Aws::String &message,
                             const Aws::String &phoneNumber,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::PublishRequest request;
    request.SetMessage(message);
    request.SetPhoneNumber(phoneNumber);

    const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

    if (outcome.IsSuccess()) {
        std::cout << "Message published successfully with message id, '"
                  << outcome.GetResult().GetMessageId() << "'."
                  << std::endl;
    }
    else {
        std::cerr << "Error while publishing message "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[Publish](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)」を参照してください。

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Workflow for messaging with topics and queues using Amazon SNS and Amazon SQS.
/*!
 \param clientConfig Aws client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::TopicsAndQueues::messagingWithTopicsAndQueues(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    std::cout << "Welcome to messaging with topics and queues." << std::endl;
    printAsterisksLine();
    std::cout << "In this workflow, you will create an SNS topic and subscribe "
              << NUMBER_OF_QUEUES <<
              " SQS queues to the topic." << std::endl;
    std::cout
            << "You can select from several options for configuring the topic and the subscriptions for the "
            << NUMBER_OF_QUEUES << " queues." << std::endl;
    std::cout << "You can then post to the topic and see the results in the queues."
              << std::endl;

    Aws::SNS::SNSClient snsClient(clientConfiguration);

    printAsterisksLine();

    std::cout << "SNS topics can be configured as FIFO (First-In-First-Out)."
              << std::endl;
    std::cout
            << "FIFO topics deliver messages in order and support deduplication and message filtering."
            << std::endl;
    bool isFifoTopic = askYesNoQuestion(
            "Would you like to work with FIFO topics? (y/n) ");

    bool contentBasedDeduplication = false;
    Aws::String topicName;
    if (isFifoTopic) {
        printAsterisksLine();
        std::cout << "Because you have chosen a FIFO topic, deduplication is supported."
                  << std::endl;
        std::cout
                << "Deduplication IDs are either set in the message or automatically generated "
                << "from content using a hash function." << std::endl;
        std::cout
                << "If a message is successfully published to an SNS FIFO topic, any message "
                << "published and determined to have the same deduplication ID, "
                << std::endl;
        std::cout
                << "within the five-minute deduplication interval, is accepted but not delivered."
                << std::endl;
        std::cout
                << "For more information about deduplication, "
                << "see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html."
                << std::endl;
        contentBasedDeduplication = askYesNoQuestion(
                "Use content-based deduplication instead of entering a deduplication ID? (y/n) ");
    }

    printAsterisksLine();

    Aws::SQS::SQSClient sqsClient(clientConfiguration);
    Aws::Vector<Aws::String> queueURLS;
    Aws::Vector<Aws::String> subscriptionARNS;

    Aws::String topicARN;
    {
        topicName = askQuestion("Enter a name for your SNS topic. ");

        // 1.  Create an Amazon SNS topic, either FIFO or non-FIFO.
        Aws::SNS::Model::CreateTopicRequest request;

        if (isFifoTopic) {
            request.AddAttributes("FifoTopic", "true");
            if (contentBasedDeduplication) {
                request.AddAttributes("ContentBasedDeduplication", "true");
            }
            topicName = topicName + FIFO_SUFFIX;

            std::cout
                    << "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name."
                    << std::endl;
        }

        request.SetName(topicName);

        Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);

        if (outcome.IsSuccess()) {
            topicARN = outcome.GetResult().GetTopicArn();
            std::cout << "Your new topic with the name '" << topicName
                      << "' and the topic Amazon Resource Name (ARN) " << std::endl;
            std::cout << "'" << topicARN << "' has been created." << std::endl;

        }
        else {
            std::cerr << "Error with TopicsAndQueues::CreateTopic. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }
    }

    printAsterisksLine();

    std::cout << "Now you will create " << NUMBER_OF_QUEUES
              << " SQS queues to subscribe to the topic." << std::endl;
    Aws::Vector<Aws::String> queueNames;
    bool filteringMessages = false;
    bool first = true;
    for (int i = 1; i <= NUMBER_OF_QUEUES; ++i) {
        Aws::String queueURL;
        Aws::String queueName;
        {
            printAsterisksLine();
            std::ostringstream ostringstream;
            ostringstream << "Enter a name for " << (first ? "an" : "the next")
                          << " SQS queue. ";
            queueName = askQuestion(ostringstream.str());

            // 2.  Create an SQS queue.
            Aws::SQS::Model::CreateQueueRequest request;
            if (isFifoTopic) {
                request.AddAttributes(Aws::SQS::Model::QueueAttributeName::FifoQueue,
                                      "true");
                queueName = queueName + FIFO_SUFFIX;

                if (first) // Only explain this once.
                {
                    std::cout
                            << "Because you are creating a FIFO SQS queue, '.fifo' must "
                            << "be appended to the queue name." << std::endl;
                }
            }

            request.SetQueueName(queueName);
            queueNames.push_back(queueName);

            Aws::SQS::Model::CreateQueueOutcome outcome =
                    sqsClient.CreateQueue(request);

            if (outcome.IsSuccess()) {
                queueURL = outcome.GetResult().GetQueueUrl();
                std::cout << "Your new SQS queue with the name '" << queueName
                          << "' and the queue URL " << std::endl;
                std::cout << "'" << queueURL << "' has been created." << std::endl;
            }
            else {
                std::cerr << "Error with SQS::CreateQueue. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }
        queueURLS.push_back(queueURL);

        if (first) // Only explain this once.
        {
            std::cout
                    << "The queue URL is used to retrieve the queue ARN, which is "
                    << "used to create a subscription." << std::endl;
        }

        Aws::String queueARN;
        {
            // 3.  Get the SQS queue ARN attribute.
            Aws::SQS::Model::GetQueueAttributesRequest request;
            request.SetQueueUrl(queueURL);
            request.AddAttributeNames(Aws::SQS::Model::QueueAttributeName::QueueArn);

            Aws::SQS::Model::GetQueueAttributesOutcome outcome =
                    sqsClient.GetQueueAttributes(request);

            if (outcome.IsSuccess()) {
                const Aws::Map<Aws::SQS::Model::QueueAttributeName, Aws::String> &attributes =
                        outcome.GetResult().GetAttributes();
                const auto &iter = attributes.find(
                        Aws::SQS::Model::QueueAttributeName::QueueArn);
                if (iter != attributes.end()) {
                    queueARN = iter->second;
                    std::cout << "The queue ARN '" << queueARN
                              << "' has been retrieved."
                              << std::endl;
                }
                else {
                    std::cerr
                            << "Error ARN attribute not returned by GetQueueAttribute."
                            << std::endl;

                    cleanUp(topicARN,
                            queueURLS,
                            subscriptionARNS,
                            snsClient,
                            sqsClient);

                    return false;
                }
            }
            else {
                std::cerr << "Error with SQS::GetQueueAttributes. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        if (first) {
            std::cout
                    << "An IAM policy must be attached to an SQS queue, enabling it to receive "
                       "messages from an SNS topic." << std::endl;
        }

        {
            // 4.  Set the SQS queue policy attribute with a policy enabling the receipt of SNS messages.
            Aws::SQS::Model::SetQueueAttributesRequest request;
            request.SetQueueUrl(queueURL);
            Aws::String policy = createPolicyForQueue(queueARN, topicARN);
            request.AddAttributes(Aws::SQS::Model::QueueAttributeName::Policy,
                                  policy);

            Aws::SQS::Model::SetQueueAttributesOutcome outcome =
                    sqsClient.SetQueueAttributes(request);

            if (outcome.IsSuccess()) {
                std::cout << "The attributes for the queue '" << queueName
                          << "' were successfully updated." << std::endl;
            }
            else {
                std::cerr << "Error with SQS::SetQueueAttributes. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        printAsterisksLine();

        {
            // 5.  Subscribe the SQS queue to the SNS topic.
            Aws::SNS::Model::SubscribeRequest request;
            request.SetTopicArn(topicARN);
            request.SetProtocol("sqs");
            request.SetEndpoint(queueARN);
            if (isFifoTopic) {
                if (first) {
                    std::cout << "Subscriptions to a FIFO topic can have filters."
                              << std::endl;
                    std::cout
                            << "If you add a filter to this subscription, then only the filtered messages "
                            << "will be received in the queue." << std::endl;
                    std::cout << "For information about message filtering, "
                              << "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html"
                              << std::endl;
                    std::cout << "For this example, you can filter messages by a \""
                              << TONE_ATTRIBUTE << "\" attribute." << std::endl;
                }

                std::ostringstream ostringstream;
                ostringstream << "Filter messages for \"" << queueName
                              << "\"'s subscription to the topic \""
                              << topicName << "\"?  (y/n)";

                // Add filter if user answers yes.
                if (askYesNoQuestion(ostringstream.str())) {
                    Aws::String jsonPolicy = getFilterPolicyFromUser();
                    if (!jsonPolicy.empty()) {
                        filteringMessages = true;

                        std::cout << "This is the filter policy for this subscription."
                                  << std::endl;
                        std::cout << jsonPolicy << std::endl;

                        request.AddAttributes("FilterPolicy", jsonPolicy);
                    }
                    else {
                        std::cout
                                << "Because you did not select any attributes, no filter "
                                << "will be added to this subscription." << std::endl;
                    }
                }
            }  // if (isFifoTopic)
            Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);

            if (outcome.IsSuccess()) {
                Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn();
                std::cout << "The queue '" << queueName
                          << "' has been subscribed to the topic '"
                          << "'" << topicName << "'" << std::endl;
                std::cout << "with the subscription ARN '" << subscriptionARN << "."
                          << std::endl;
                subscriptionARNS.push_back(subscriptionARN);
            }
            else {
                std::cerr << "Error with TopicsAndQueues::Subscribe. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        first = false;
    }

    first = true;
    do {
        printAsterisksLine();

        // 6.  Publish a message to the SNS topic.
        Aws::SNS::Model::PublishRequest request;
        request.SetTopicArn(topicARN);
        Aws::String message = askQuestion("Enter a message text to publish.  ");
        request.SetMessage(message);
        if (isFifoTopic) {
            if (first) {
                std::cout
                        << "Because you are using a FIFO topic, you must set a message group ID."
                        << std::endl;
                std::cout
                        << "All messages within the same group will be received in the "
                        << "order they were published." << std::endl;
            }
            Aws::String messageGroupID = askQuestion(
                    "Enter a message group ID for this message. ");
            request.SetMessageGroupId(messageGroupID);
            if (!contentBasedDeduplication) {
                if (first) {
                    std::cout
                            << "Because you are not using content-based deduplication, "
                            << "you must enter a deduplication ID." << std::endl;
                }
                Aws::String deduplicationID = askQuestion(
                        "Enter a deduplication ID for this message. ");
                request.SetMessageDeduplicationId(deduplicationID);
            }
        }

        if (filteringMessages && askYesNoQuestion(
                "Add an attribute to this message? (y/n) ")) {
            for (size_t i = 0; i < TONES.size(); ++i) {
                std::cout << "  " << (i + 1) << ". " << TONES[i] << std::endl;
            }
            int selection = askQuestionForIntRange(
                    "Enter a number for an attribute. ",
                    1, static_cast<int>(TONES.size()));
            Aws::SNS::Model::MessageAttributeValue messageAttributeValue;
            messageAttributeValue.SetDataType("String");
            messageAttributeValue.SetStringValue(TONES[selection - 1]);
            request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue);
        }

        Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

        if (outcome.IsSuccess()) {
            std::cout << "Your message was successfully published." << std::endl;
        }
        else {
            std::cerr << "Error with TopicsAndQueues::Publish. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }

        first = false;
    } while (askYesNoQuestion("Post another message? (y/n) "));

    printAsterisksLine();

    std::cout << "Now the SQS queue will be polled to retrieve the messages."
              << std::endl;
    askQuestion("Press any key to continue...", alwaysTrueTest);

    for (size_t i = 0; i < queueURLS.size(); ++i) {
        // 7.  Poll an SQS queue for its messages.
        std::vector<Aws::String> messages;
        std::vector<Aws::String> receiptHandles;
        while (true) {
            Aws::SQS::Model::ReceiveMessageRequest request;
            request.SetMaxNumberOfMessages(10);
            request.SetQueueUrl(queueURLS[i]);

            // Setting WaitTimeSeconds to non-zero enables long polling.
            // For information about long polling, see
            // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html
            request.SetWaitTimeSeconds(1);
            Aws::SQS::Model::ReceiveMessageOutcome outcome =
                    sqsClient.ReceiveMessage(request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::SQS::Model::Message> &newMessages = outcome.GetResult().GetMessages();
                if (newMessages.empty()) {
                    break;
                }
                else {
                    for (const Aws::SQS::Model::Message &message: newMessages) {
                        messages.push_back(message.GetBody());
                        receiptHandles.push_back(message.GetReceiptHandle());
                    }
                }
            }
            else {
                std::cerr << "Error with SQS::ReceiveMessage. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        printAsterisksLine();

        if (messages.empty()) {
            std::cout << "No messages were ";
        }
        else if (messages.size() == 1) {
            std::cout << "One message was ";
        }
        else {
            std::cout << messages.size() << " messages were ";
        }
        std::cout << "received by the queue '" << queueNames[i]
                  << "'." << std::endl;
        for (const Aws::String &message: messages) {
            std::cout << "  Message : '" << message << "'."
                      << std::endl;
        }

        // 8.  Delete a batch of messages from an SQS queue.
        if (!receiptHandles.empty()) {
            Aws::SQS::Model::DeleteMessageBatchRequest request;
            request.SetQueueUrl(queueURLS[i]);
            int id = 1; // Ids must be unique within a batch delete request.
            for (const Aws::String &receiptHandle: receiptHandles) {
                Aws::SQS::Model::DeleteMessageBatchRequestEntry entry;
                entry.SetId(std::to_string(id));
                ++id;
                entry.SetReceiptHandle(receiptHandle);
                request.AddEntries(entry);
            }

            Aws::SQS::Model::DeleteMessageBatchOutcome outcome =
                    sqsClient.DeleteMessageBatch(request);

            if (outcome.IsSuccess()) {
                std::cout << "The batch deletion of messages was successful."
                          << std::endl;
            }
            else {
                std::cerr << "Error with SQS::DeleteMessageBatch. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }
    }

    return cleanUp(topicARN,
                   queueURLS,
                   subscriptionARNS,
                   snsClient,
                   sqsClient,
                   true); // askUser
}


bool AwsDoc::TopicsAndQueues::cleanUp(const Aws::String &topicARN,
                                      const Aws::Vector<Aws::String> &queueURLS,
                                      const Aws::Vector<Aws::String> &subscriptionARNS,
                                      const Aws::SNS::SNSClient &snsClient,
                                      const Aws::SQS::SQSClient &sqsClient,
                                      bool askUser) {
    bool result = true;
    printAsterisksLine();
    if (!queueURLS.empty() && askUser &&
        askYesNoQuestion("Delete the SQS queues? (y/n) ")) {

        for (const auto &queueURL: queueURLS) {
            // 9.  Delete an SQS queue.
            Aws::SQS::Model::DeleteQueueRequest request;
            request.SetQueueUrl(queueURL);

            Aws::SQS::Model::DeleteQueueOutcome outcome =
                    sqsClient.DeleteQueue(request);

            if (outcome.IsSuccess()) {
                std::cout << "The queue with URL '" << queueURL
                          << "' was successfully deleted." << std::endl;
            }
            else {
                std::cerr << "Error with SQS::DeleteQueue. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }

        for (const auto &subscriptionARN: subscriptionARNS) {
            // 10. Unsubscribe an SNS subscription.
            Aws::SNS::Model::UnsubscribeRequest request;
            request.SetSubscriptionArn(subscriptionARN);

            Aws::SNS::Model::UnsubscribeOutcome outcome =
                    snsClient.Unsubscribe(request);

            if (outcome.IsSuccess()) {
                std::cout << "Unsubscribe of subscription ARN '" << subscriptionARN
                          << "' was successful." << std::endl;
            }
            else {
                std::cerr << "Error with TopicsAndQueues::Unsubscribe. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }
    }

    printAsterisksLine();
    if (!topicARN.empty() && askUser &&
        askYesNoQuestion("Delete the SNS topic? (y/n) ")) {

        // 11. Delete an SNS topic.
        Aws::SNS::Model::DeleteTopicRequest request;
        request.SetTopicArn(topicARN);

        Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request);

        if (outcome.IsSuccess()) {
            std::cout << "The topic with ARN '" << topicARN
                      << "' was successfully deleted." << std::endl;
        }
        else {
            std::cerr << "Error with TopicsAndQueues::DeleteTopicRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
    }

    return result;
}

//! Create an IAM policy that gives an SQS queue permission to receive messages from an SNS topic.
/*!
 \sa createPolicyForQueue()
 \param queueARN: The SQS queue Amazon Resource Name (ARN).
 \param topicARN: The SNS topic ARN.
 \return Aws::String: The policy as JSON.
 */
Aws::String AwsDoc::TopicsAndQueues::createPolicyForQueue(const Aws::String &queueARN,
                                                          const Aws::String &topicARN) {
    std::ostringstream policyStream;
    policyStream << R"({
        "Statement": [
        {
            "Effect": "Allow",
                    "Principal": {
                "Service": "sns.amazonaws.com"
            },
            "Action": "sqs:SendMessage",
                    "Resource": ")" << queueARN << R"(",
                    "Condition": {
                "ArnEquals": {
                    "aws:SourceArn": ")" << topicARN << R"("
                }
            }
        }
        ]
    })";

    return policyStream.str();
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Unsubscribe)

# SDK for C\$1\$1 を使用した Amazon SQS の例
<a name="cpp_1_sqs_code_examples"></a>

次のコード例は、Amazon SQS AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon SQS
<a name="sqs_Hello_cpp_1_topic"></a>

次のコード例は、Amazon SQS の使用を開始する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/hello_sqs#code-examples)での設定と実行の方法を確認してください。
CMakeLists.txt CMake ファイルのコード。  

```
# Set the minimum required version of CMake for this project.
cmake_minimum_required(VERSION 3.13)

# Set the AWS service components used by this project.
set(SERVICE_COMPONENTS sqs)

# Set this project's name.
project("hello_sqs")

# Set the C++ standard to use to build this target.
# At least C++ 11 is required for the AWS SDK for C++.
set(CMAKE_CXX_STANDARD 11)

# Use the MSVC variable to determine if this is a Windows build.
set(WINDOWS_BUILD ${MSVC})

if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK.
    string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all")
    list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH})
endif ()

# Find the AWS SDK for C++ package.
find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS})

if(WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS)
    # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging.

    # set(BIN_SUB_DIR "/Debug") # If you are building from the command line you may need to uncomment this
    # and set the proper subdirectory to the executables' location.

    AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR})
endif()

add_executable(${PROJECT_NAME}
        hello_sqs.cpp)

target_link_libraries(${PROJECT_NAME}
        ${AWSSDK_LINK_LIBRARIES})
```
hello\$1sqs.cpp ソースファイルのコード。  

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/ListQueuesRequest.h>
#include <iostream>

/*
 *  A "Hello SQS" starter application that initializes an Amazon Simple Queue Service
 *  (Amazon SQS) client and lists the SQS queues in the current account.
 *
 *  main function
 *
 *  Usage: 'hello_sqs'
 *
 */

int main(int argc, char **argv) {
    Aws::SDKOptions options;
    // Optionally change the log level for debugging.
//   options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug;
    Aws::InitAPI(options); // Should only be called once.
    {
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

        Aws::SQS::SQSClient sqsClient(clientConfig);

        Aws::Vector<Aws::String> allQueueUrls;
        Aws::String nextToken; // Next token is used to handle a paginated response.
        do {
            Aws::SQS::Model::ListQueuesRequest request;

            Aws::SQS::Model::ListQueuesOutcome outcome = sqsClient.ListQueues(request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::String> &pageOfQueueUrls = outcome.GetResult().GetQueueUrls();
                if (!pageOfQueueUrls.empty()) {
                    allQueueUrls.insert(allQueueUrls.cend(), pageOfQueueUrls.cbegin(),
                                        pageOfQueueUrls.cend());
                }
            }
            else {
                std::cerr << "Error with SQS::ListQueues. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                break;
            }
            nextToken = outcome.GetResult().GetNextToken();
        } while (!nextToken.empty());


        std::cout << "Hello Amazon SQS! You have " << allQueueUrls.size() << " queue"
                  << (allQueueUrls.size() == 1 ? "" : "s") << " in your account."
                  << std::endl;

        if (!allQueueUrls.empty()) {
            std::cout << "Here are your queue URLs." << std::endl;
            for (const Aws::String &queueUrl: allQueueUrls) {
                std::cout << "  * " << queueUrl << std::endl;
            }
        }
    }

    Aws::ShutdownAPI(options); // Should only be called once.
    return 0;
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[ListQueues](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/ListQueues)」を参照してください。

## アクション
<a name="actions"></a>

### `ChangeMessageVisibility`
<a name="sqs_ChangeMessageVisibility_cpp_1_topic"></a>

次のコード例は、`ChangeMessageVisibility` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Changes the visibility timeout of a message in an Amazon Simple Queue Service
//! (Amazon SQS) queue.
/*!
  \param queueUrl: An Amazon SQS queue URL.
  \param messageReceiptHandle: A message receipt handle.
  \param visibilityTimeoutSeconds: Visibility timeout in seconds.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::changeMessageVisibility(
        const Aws::String &queue_url,
        const Aws::String &messageReceiptHandle,
        int visibilityTimeoutSeconds,
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::ChangeMessageVisibilityRequest request;
    request.SetQueueUrl(queue_url);
    request.SetReceiptHandle(messageReceiptHandle);
    request.SetVisibilityTimeout(visibilityTimeoutSeconds);

    auto outcome = sqsClient.ChangeMessageVisibility(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully changed visibility of message " <<
                  messageReceiptHandle << " from queue " << queue_url << std::endl;
    }
    else {
        std::cout << "Error changing visibility of message from queue "
                  << queue_url << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[ChangeMessageVisibility](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/ChangeMessageVisibility)」を参照してください。

### `CreateQueue`
<a name="sqs_CreateQueue_cpp_1_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Create an Amazon Simple Queue Service (Amazon SQS) queue.
/*!
  \param queueName: An Amazon SQS queue name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::createQueue(const Aws::String &queueName,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::CreateQueueRequest request;
    request.SetQueueName(queueName);

    const Aws::SQS::Model::CreateQueueOutcome outcome = sqsClient.CreateQueue(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created queue " << queueName << " with a queue URL "
                  << outcome.GetResult().GetQueueUrl() << "." << std::endl;
    }
    else {
        std::cerr << "Error creating queue " << queueName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[CreateQueue](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/CreateQueue)」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_cpp_1_topic"></a>

次のコード例は、`DeleteMessage` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Delete a message from an Amazon Simple Queue Service (Amazon SQS) queue.
/*!
  \param queueUrl: An Amazon SQS queue URL.
  \param messageReceiptHandle: A message receipt handle.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::deleteMessage(const Aws::String &queueUrl,
                                const Aws::String &messageReceiptHandle,
                                const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::DeleteMessageRequest request;
    request.SetQueueUrl(queueUrl);
    request.SetReceiptHandle(messageReceiptHandle);

    const Aws::SQS::Model::DeleteMessageOutcome outcome = sqsClient.DeleteMessage(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted message from queue " << queueUrl
                  << std::endl;
    }
    else {
        std::cerr << "Error deleting message from queue " << queueUrl << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteMessage](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/DeleteMessage)」を参照してください。

### `DeleteMessageBatch`
<a name="sqs_DeleteMessageBatch_cpp_1_topic"></a>

次のコード例は、`DeleteMessageBatch` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SQS::SQSClient sqsClient(clientConfiguration);

            Aws::SQS::Model::DeleteMessageBatchRequest request;
            request.SetQueueUrl(queueURLS[i]);
            int id = 1; // Ids must be unique within a batch delete request.
            for (const Aws::String &receiptHandle: receiptHandles) {
                Aws::SQS::Model::DeleteMessageBatchRequestEntry entry;
                entry.SetId(std::to_string(id));
                ++id;
                entry.SetReceiptHandle(receiptHandle);
                request.AddEntries(entry);
            }

            Aws::SQS::Model::DeleteMessageBatchOutcome outcome =
                    sqsClient.DeleteMessageBatch(request);

            if (outcome.IsSuccess()) {
                std::cout << "The batch deletion of messages was successful."
                          << std::endl;
            }
            else {
                std::cerr << "Error with SQS::DeleteMessageBatch. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/DeleteMessageBatch)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_cpp_1_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Delete an Amazon Simple Queue Service (Amazon SQS) queue.
/*!
  \param queueURL: An Amazon SQS queue URL.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::deleteQueue(const Aws::String &queueURL,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);
    Aws::SQS::Model::DeleteQueueRequest request;
    request.SetQueueUrl(queueURL);

    const Aws::SQS::Model::DeleteQueueOutcome outcome = sqsClient.DeleteQueue(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted queue with url " << queueURL <<
                  std::endl;
    }
    else {
        std::cerr << "Error deleting queue " << queueURL << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    return outcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[DeleteQueue](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/DeleteQueue)」を参照してください。

### `GetQueueAttributes`
<a name="sqs_GetQueueAttributes_cpp_1_topic"></a>

次のコード例は、`GetQueueAttributes` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SQS::SQSClient sqsClient(clientConfiguration);

            Aws::SQS::Model::GetQueueAttributesRequest request;
            request.SetQueueUrl(queueURL);
            request.AddAttributeNames(Aws::SQS::Model::QueueAttributeName::QueueArn);

            Aws::SQS::Model::GetQueueAttributesOutcome outcome =
                    sqsClient.GetQueueAttributes(request);

            if (outcome.IsSuccess()) {
                const Aws::Map<Aws::SQS::Model::QueueAttributeName, Aws::String> &attributes =
                        outcome.GetResult().GetAttributes();
                const auto &iter = attributes.find(
                        Aws::SQS::Model::QueueAttributeName::QueueArn);
                if (iter != attributes.end()) {
                    queueARN = iter->second;
                    std::cout << "The queue ARN '" << queueARN
                              << "' has been retrieved."
                              << std::endl;
                }

            }
            else {
                std::cerr << "Error with SQS::GetQueueAttributes. "
                          << outcome.GetError().GetMessage()
                          << std::endl;


            }
```
+  API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の「[GetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/GetQueueAttributes)」を参照してください。

### `GetQueueUrl`
<a name="sqs_GetQueueUrl_cpp_1_topic"></a>

次のコード例は、`GetQueueUrl` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Get the URL for an Amazon Simple Queue Service (Amazon SQS) queue.
/*!
  \param queueName: An Amazon SQS queue name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::getQueueUrl(const Aws::String &queueName,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::GetQueueUrlRequest request;
    request.SetQueueName(queueName);

    const Aws::SQS::Model::GetQueueUrlOutcome outcome = sqsClient.GetQueueUrl(request);
    if (outcome.IsSuccess()) {
        std::cout << "Queue " << queueName << " has url " <<
                  outcome.GetResult().GetQueueUrl() << std::endl;
    }
    else {
        std::cerr << "Error getting url for queue " << queueName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[GetQueueUrl](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/GetQueueUrl)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_cpp_1_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! List the Amazon Simple Queue Service (Amazon SQS) queues within an AWS account.
/*!
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool
AwsDoc::SQS::listQueues(const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::ListQueuesRequest listQueuesRequest;

    Aws::String nextToken; // Used for pagination.
    Aws::Vector<Aws::String> allQueueUrls;

    do {
        if (!nextToken.empty()) {
            listQueuesRequest.SetNextToken(nextToken);
        }
        const Aws::SQS::Model::ListQueuesOutcome outcome = sqsClient.ListQueues(
                listQueuesRequest);
        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::String> &queueUrls = outcome.GetResult().GetQueueUrls();
            allQueueUrls.insert(allQueueUrls.end(),
                                queueUrls.begin(),
                                queueUrls.end());

            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cerr << "Error listing queues: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

    } while (!nextToken.empty());

    std::cout << allQueueUrls.size() << " Amazon SQS queue(s) found." << std::endl;
    for (const auto &iter: allQueueUrls) {
        std::cout << " " << iter << std::endl;
    }

    return true;
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[ListQueues](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/ListQueues)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_cpp_1_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Receive a message from an Amazon Simple Queue Service (Amazon SQS) queue.
/*!
  \param queueUrl: An Amazon SQS queue URL.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::receiveMessage(const Aws::String &queueUrl,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::ReceiveMessageRequest request;
    request.SetQueueUrl(queueUrl);
    request.SetMaxNumberOfMessages(1);

    const Aws::SQS::Model::ReceiveMessageOutcome outcome = sqsClient.ReceiveMessage(
            request);
    if (outcome.IsSuccess()) {

        const Aws::Vector<Aws::SQS::Model::Message> &messages =
                outcome.GetResult().GetMessages();
        if (!messages.empty()) {
            const Aws::SQS::Model::Message &message = messages[0];
            std::cout << "Received message:" << std::endl;
            std::cout << "  MessageId: " << message.GetMessageId() << std::endl;
            std::cout << "  ReceiptHandle: " << message.GetReceiptHandle() << std::endl;
            std::cout << "  Body: " << message.GetBody() << std::endl << std::endl;
        }
        else {
            std::cout << "No messages received from queue " << queueUrl <<
                      std::endl;

        }
    }
    else {
        std::cerr << "Error receiving message from queue " << queueUrl << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
    return outcome.IsSuccess();
}
```
+  API の詳細については、**AWS SDK for C\$1\$1 API リファレンスの「[ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/ReceiveMessage)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_cpp_1_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Send a message to an Amazon Simple Queue Service (Amazon SQS) queue.
/*!
  \param queueUrl: An Amazon SQS queue URL.
  \param messageBody: A message body.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::sendMessage(const Aws::String &queueUrl,
                              const Aws::String &messageBody,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::SendMessageRequest request;
    request.SetQueueUrl(queueUrl);
    request.SetMessageBody(messageBody);

    const Aws::SQS::Model::SendMessageOutcome outcome = sqsClient.SendMessage(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully sent message to " << queueUrl <<
                  std::endl;
    }
    else {
        std::cerr << "Error sending message to " << queueUrl << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、AWS SDK for C\$1\$1 API リファレンスの「[SendMessage](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/SendMessage)」を参照してください。**

### `SetQueueAttributes`
<a name="sqs_SetQueueAttributes_cpp_1_topic"></a>

次のコード例は、`SetQueueAttributes` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Set the value for an attribute in an Amazon Simple Queue Service (Amazon SQS) queue.
/*!
  \param queueUrl: An Amazon SQS queue URL.
  \param attributeName: An attribute name enum.
  \param attribute: The attribute value as a string.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::setQueueAttributes(const Aws::String &queueURL,
                                     Aws::SQS::Model::QueueAttributeName attributeName,
                                     const Aws::String &attribute,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::SetQueueAttributesRequest request;
    request.SetQueueUrl(queueURL);
    request.AddAttributes(
            attributeName,
            attribute);

    const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully set the attribute  " <<
                  Aws::SQS::Model::QueueAttributeNameMapper::GetNameForQueueAttributeName(
                          attributeName)
                  << " with value " << attribute << " in queue " <<
                  queueURL << "." << std::endl;
    }
    else {
        std::cout << "Error setting attribute for  queue " <<
                  queueURL << ": " << outcome.GetError().GetMessage() <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
デッドレターキューを設定します。  

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Connect an Amazon Simple Queue Service (Amazon SQS) queue to an associated
//! dead-letter queue.
/*!
  \param srcQueueUrl: An Amazon SQS queue URL.
  \param deadLetterQueueARN: The Amazon Resource Name (ARN) of an Amazon SQS dead-letter queue.
  \param maxReceiveCount: The max receive count of a message before it is sent to the dead-letter queue.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::setDeadLetterQueue(const Aws::String &srcQueueUrl,
                                     const Aws::String &deadLetterQueueARN,
                                     int maxReceiveCount,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::String redrivePolicy = MakeRedrivePolicy(deadLetterQueueARN, maxReceiveCount);

    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::SetQueueAttributesRequest request;
    request.SetQueueUrl(srcQueueUrl);
    request.AddAttributes(
            Aws::SQS::Model::QueueAttributeName::RedrivePolicy,
            redrivePolicy);

    const Aws::SQS::Model::SetQueueAttributesOutcome outcome =
            sqsClient.SetQueueAttributes(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully set dead letter queue for queue  " <<
                  srcQueueUrl << " to " << deadLetterQueueARN << std::endl;
    }
    else {
        std::cerr << "Error setting dead letter queue for queue " <<
                  srcQueueUrl << ": " << outcome.GetError().GetMessage() <<
                  std::endl;
    }

    return outcome.IsSuccess();
}

//! Make a redrive policy for a dead-letter queue.
/*!
  \param queueArn: An Amazon SQS ARN for the dead-letter queue.
  \param maxReceiveCount: The max receive count of a message before it is sent to the dead-letter queue.
  \return Aws::String: Policy as JSON string.
 */
Aws::String MakeRedrivePolicy(const Aws::String &queueArn, int maxReceiveCount) {
    Aws::Utils::Json::JsonValue redrive_arn_entry;
    redrive_arn_entry.AsString(queueArn);

    Aws::Utils::Json::JsonValue max_msg_entry;
    max_msg_entry.AsInteger(maxReceiveCount);

    Aws::Utils::Json::JsonValue policy_map;
    policy_map.WithObject("deadLetterTargetArn", redrive_arn_entry);
    policy_map.WithObject("maxReceiveCount", max_msg_entry);

    return policy_map.View().WriteReadable();
}
```
ロングポーリングを使用するように Amazon SQS キューを設定します。  

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Set the wait time for an Amazon Simple Queue Service (Amazon SQS) queue poll.
/*!
  \param queueUrl: An Amazon SQS queue URL.
  \param pollTimeSeconds: The receive message wait time in seconds.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SQS::setQueueLongPollingAttribute(const Aws::String &queueURL,
                                               const Aws::String &pollTimeSeconds,
                                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::SetQueueAttributesRequest request;
    request.SetQueueUrl(queueURL);
    request.AddAttributes(
            Aws::SQS::Model::QueueAttributeName::ReceiveMessageWaitTimeSeconds,
            pollTimeSeconds);

    const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated long polling time for queue " <<
                  queueURL << " to " << pollTimeSeconds << std::endl;
    }
    else {
        std::cout << "Error updating long polling time for queue " <<
                  queueURL << ": " << outcome.GetError().GetMessage() <<
                  std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、**「AWS SDK for C\$1\$1 API リファレンス」の「[SetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/SetQueueAttributes)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_cpp_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cross-service/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

//! Workflow for messaging with topics and queues using Amazon SNS and Amazon SQS.
/*!
 \param clientConfig Aws client configuration.
 \return bool: Successful completion.
 */
bool AwsDoc::TopicsAndQueues::messagingWithTopicsAndQueues(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    std::cout << "Welcome to messaging with topics and queues." << std::endl;
    printAsterisksLine();
    std::cout << "In this workflow, you will create an SNS topic and subscribe "
              << NUMBER_OF_QUEUES <<
              " SQS queues to the topic." << std::endl;
    std::cout
            << "You can select from several options for configuring the topic and the subscriptions for the "
            << NUMBER_OF_QUEUES << " queues." << std::endl;
    std::cout << "You can then post to the topic and see the results in the queues."
              << std::endl;

    Aws::SNS::SNSClient snsClient(clientConfiguration);

    printAsterisksLine();

    std::cout << "SNS topics can be configured as FIFO (First-In-First-Out)."
              << std::endl;
    std::cout
            << "FIFO topics deliver messages in order and support deduplication and message filtering."
            << std::endl;
    bool isFifoTopic = askYesNoQuestion(
            "Would you like to work with FIFO topics? (y/n) ");

    bool contentBasedDeduplication = false;
    Aws::String topicName;
    if (isFifoTopic) {
        printAsterisksLine();
        std::cout << "Because you have chosen a FIFO topic, deduplication is supported."
                  << std::endl;
        std::cout
                << "Deduplication IDs are either set in the message or automatically generated "
                << "from content using a hash function." << std::endl;
        std::cout
                << "If a message is successfully published to an SNS FIFO topic, any message "
                << "published and determined to have the same deduplication ID, "
                << std::endl;
        std::cout
                << "within the five-minute deduplication interval, is accepted but not delivered."
                << std::endl;
        std::cout
                << "For more information about deduplication, "
                << "see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html."
                << std::endl;
        contentBasedDeduplication = askYesNoQuestion(
                "Use content-based deduplication instead of entering a deduplication ID? (y/n) ");
    }

    printAsterisksLine();

    Aws::SQS::SQSClient sqsClient(clientConfiguration);
    Aws::Vector<Aws::String> queueURLS;
    Aws::Vector<Aws::String> subscriptionARNS;

    Aws::String topicARN;
    {
        topicName = askQuestion("Enter a name for your SNS topic. ");

        // 1.  Create an Amazon SNS topic, either FIFO or non-FIFO.
        Aws::SNS::Model::CreateTopicRequest request;

        if (isFifoTopic) {
            request.AddAttributes("FifoTopic", "true");
            if (contentBasedDeduplication) {
                request.AddAttributes("ContentBasedDeduplication", "true");
            }
            topicName = topicName + FIFO_SUFFIX;

            std::cout
                    << "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name."
                    << std::endl;
        }

        request.SetName(topicName);

        Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);

        if (outcome.IsSuccess()) {
            topicARN = outcome.GetResult().GetTopicArn();
            std::cout << "Your new topic with the name '" << topicName
                      << "' and the topic Amazon Resource Name (ARN) " << std::endl;
            std::cout << "'" << topicARN << "' has been created." << std::endl;

        }
        else {
            std::cerr << "Error with TopicsAndQueues::CreateTopic. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }
    }

    printAsterisksLine();

    std::cout << "Now you will create " << NUMBER_OF_QUEUES
              << " SQS queues to subscribe to the topic." << std::endl;
    Aws::Vector<Aws::String> queueNames;
    bool filteringMessages = false;
    bool first = true;
    for (int i = 1; i <= NUMBER_OF_QUEUES; ++i) {
        Aws::String queueURL;
        Aws::String queueName;
        {
            printAsterisksLine();
            std::ostringstream ostringstream;
            ostringstream << "Enter a name for " << (first ? "an" : "the next")
                          << " SQS queue. ";
            queueName = askQuestion(ostringstream.str());

            // 2.  Create an SQS queue.
            Aws::SQS::Model::CreateQueueRequest request;
            if (isFifoTopic) {
                request.AddAttributes(Aws::SQS::Model::QueueAttributeName::FifoQueue,
                                      "true");
                queueName = queueName + FIFO_SUFFIX;

                if (first) // Only explain this once.
                {
                    std::cout
                            << "Because you are creating a FIFO SQS queue, '.fifo' must "
                            << "be appended to the queue name." << std::endl;
                }
            }

            request.SetQueueName(queueName);
            queueNames.push_back(queueName);

            Aws::SQS::Model::CreateQueueOutcome outcome =
                    sqsClient.CreateQueue(request);

            if (outcome.IsSuccess()) {
                queueURL = outcome.GetResult().GetQueueUrl();
                std::cout << "Your new SQS queue with the name '" << queueName
                          << "' and the queue URL " << std::endl;
                std::cout << "'" << queueURL << "' has been created." << std::endl;
            }
            else {
                std::cerr << "Error with SQS::CreateQueue. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }
        queueURLS.push_back(queueURL);

        if (first) // Only explain this once.
        {
            std::cout
                    << "The queue URL is used to retrieve the queue ARN, which is "
                    << "used to create a subscription." << std::endl;
        }

        Aws::String queueARN;
        {
            // 3.  Get the SQS queue ARN attribute.
            Aws::SQS::Model::GetQueueAttributesRequest request;
            request.SetQueueUrl(queueURL);
            request.AddAttributeNames(Aws::SQS::Model::QueueAttributeName::QueueArn);

            Aws::SQS::Model::GetQueueAttributesOutcome outcome =
                    sqsClient.GetQueueAttributes(request);

            if (outcome.IsSuccess()) {
                const Aws::Map<Aws::SQS::Model::QueueAttributeName, Aws::String> &attributes =
                        outcome.GetResult().GetAttributes();
                const auto &iter = attributes.find(
                        Aws::SQS::Model::QueueAttributeName::QueueArn);
                if (iter != attributes.end()) {
                    queueARN = iter->second;
                    std::cout << "The queue ARN '" << queueARN
                              << "' has been retrieved."
                              << std::endl;
                }
                else {
                    std::cerr
                            << "Error ARN attribute not returned by GetQueueAttribute."
                            << std::endl;

                    cleanUp(topicARN,
                            queueURLS,
                            subscriptionARNS,
                            snsClient,
                            sqsClient);

                    return false;
                }
            }
            else {
                std::cerr << "Error with SQS::GetQueueAttributes. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        if (first) {
            std::cout
                    << "An IAM policy must be attached to an SQS queue, enabling it to receive "
                       "messages from an SNS topic." << std::endl;
        }

        {
            // 4.  Set the SQS queue policy attribute with a policy enabling the receipt of SNS messages.
            Aws::SQS::Model::SetQueueAttributesRequest request;
            request.SetQueueUrl(queueURL);
            Aws::String policy = createPolicyForQueue(queueARN, topicARN);
            request.AddAttributes(Aws::SQS::Model::QueueAttributeName::Policy,
                                  policy);

            Aws::SQS::Model::SetQueueAttributesOutcome outcome =
                    sqsClient.SetQueueAttributes(request);

            if (outcome.IsSuccess()) {
                std::cout << "The attributes for the queue '" << queueName
                          << "' were successfully updated." << std::endl;
            }
            else {
                std::cerr << "Error with SQS::SetQueueAttributes. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        printAsterisksLine();

        {
            // 5.  Subscribe the SQS queue to the SNS topic.
            Aws::SNS::Model::SubscribeRequest request;
            request.SetTopicArn(topicARN);
            request.SetProtocol("sqs");
            request.SetEndpoint(queueARN);
            if (isFifoTopic) {
                if (first) {
                    std::cout << "Subscriptions to a FIFO topic can have filters."
                              << std::endl;
                    std::cout
                            << "If you add a filter to this subscription, then only the filtered messages "
                            << "will be received in the queue." << std::endl;
                    std::cout << "For information about message filtering, "
                              << "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html"
                              << std::endl;
                    std::cout << "For this example, you can filter messages by a \""
                              << TONE_ATTRIBUTE << "\" attribute." << std::endl;
                }

                std::ostringstream ostringstream;
                ostringstream << "Filter messages for \"" << queueName
                              << "\"'s subscription to the topic \""
                              << topicName << "\"?  (y/n)";

                // Add filter if user answers yes.
                if (askYesNoQuestion(ostringstream.str())) {
                    Aws::String jsonPolicy = getFilterPolicyFromUser();
                    if (!jsonPolicy.empty()) {
                        filteringMessages = true;

                        std::cout << "This is the filter policy for this subscription."
                                  << std::endl;
                        std::cout << jsonPolicy << std::endl;

                        request.AddAttributes("FilterPolicy", jsonPolicy);
                    }
                    else {
                        std::cout
                                << "Because you did not select any attributes, no filter "
                                << "will be added to this subscription." << std::endl;
                    }
                }
            }  // if (isFifoTopic)
            Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);

            if (outcome.IsSuccess()) {
                Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn();
                std::cout << "The queue '" << queueName
                          << "' has been subscribed to the topic '"
                          << "'" << topicName << "'" << std::endl;
                std::cout << "with the subscription ARN '" << subscriptionARN << "."
                          << std::endl;
                subscriptionARNS.push_back(subscriptionARN);
            }
            else {
                std::cerr << "Error with TopicsAndQueues::Subscribe. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        first = false;
    }

    first = true;
    do {
        printAsterisksLine();

        // 6.  Publish a message to the SNS topic.
        Aws::SNS::Model::PublishRequest request;
        request.SetTopicArn(topicARN);
        Aws::String message = askQuestion("Enter a message text to publish.  ");
        request.SetMessage(message);
        if (isFifoTopic) {
            if (first) {
                std::cout
                        << "Because you are using a FIFO topic, you must set a message group ID."
                        << std::endl;
                std::cout
                        << "All messages within the same group will be received in the "
                        << "order they were published." << std::endl;
            }
            Aws::String messageGroupID = askQuestion(
                    "Enter a message group ID for this message. ");
            request.SetMessageGroupId(messageGroupID);
            if (!contentBasedDeduplication) {
                if (first) {
                    std::cout
                            << "Because you are not using content-based deduplication, "
                            << "you must enter a deduplication ID." << std::endl;
                }
                Aws::String deduplicationID = askQuestion(
                        "Enter a deduplication ID for this message. ");
                request.SetMessageDeduplicationId(deduplicationID);
            }
        }

        if (filteringMessages && askYesNoQuestion(
                "Add an attribute to this message? (y/n) ")) {
            for (size_t i = 0; i < TONES.size(); ++i) {
                std::cout << "  " << (i + 1) << ". " << TONES[i] << std::endl;
            }
            int selection = askQuestionForIntRange(
                    "Enter a number for an attribute. ",
                    1, static_cast<int>(TONES.size()));
            Aws::SNS::Model::MessageAttributeValue messageAttributeValue;
            messageAttributeValue.SetDataType("String");
            messageAttributeValue.SetStringValue(TONES[selection - 1]);
            request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue);
        }

        Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

        if (outcome.IsSuccess()) {
            std::cout << "Your message was successfully published." << std::endl;
        }
        else {
            std::cerr << "Error with TopicsAndQueues::Publish. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }

        first = false;
    } while (askYesNoQuestion("Post another message? (y/n) "));

    printAsterisksLine();

    std::cout << "Now the SQS queue will be polled to retrieve the messages."
              << std::endl;
    askQuestion("Press any key to continue...", alwaysTrueTest);

    for (size_t i = 0; i < queueURLS.size(); ++i) {
        // 7.  Poll an SQS queue for its messages.
        std::vector<Aws::String> messages;
        std::vector<Aws::String> receiptHandles;
        while (true) {
            Aws::SQS::Model::ReceiveMessageRequest request;
            request.SetMaxNumberOfMessages(10);
            request.SetQueueUrl(queueURLS[i]);

            // Setting WaitTimeSeconds to non-zero enables long polling.
            // For information about long polling, see
            // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html
            request.SetWaitTimeSeconds(1);
            Aws::SQS::Model::ReceiveMessageOutcome outcome =
                    sqsClient.ReceiveMessage(request);

            if (outcome.IsSuccess()) {
                const Aws::Vector<Aws::SQS::Model::Message> &newMessages = outcome.GetResult().GetMessages();
                if (newMessages.empty()) {
                    break;
                }
                else {
                    for (const Aws::SQS::Model::Message &message: newMessages) {
                        messages.push_back(message.GetBody());
                        receiptHandles.push_back(message.GetReceiptHandle());
                    }
                }
            }
            else {
                std::cerr << "Error with SQS::ReceiveMessage. "
                          << outcome.GetError().GetMessage()
                          << std::endl;

                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }

        printAsterisksLine();

        if (messages.empty()) {
            std::cout << "No messages were ";
        }
        else if (messages.size() == 1) {
            std::cout << "One message was ";
        }
        else {
            std::cout << messages.size() << " messages were ";
        }
        std::cout << "received by the queue '" << queueNames[i]
                  << "'." << std::endl;
        for (const Aws::String &message: messages) {
            std::cout << "  Message : '" << message << "'."
                      << std::endl;
        }

        // 8.  Delete a batch of messages from an SQS queue.
        if (!receiptHandles.empty()) {
            Aws::SQS::Model::DeleteMessageBatchRequest request;
            request.SetQueueUrl(queueURLS[i]);
            int id = 1; // Ids must be unique within a batch delete request.
            for (const Aws::String &receiptHandle: receiptHandles) {
                Aws::SQS::Model::DeleteMessageBatchRequestEntry entry;
                entry.SetId(std::to_string(id));
                ++id;
                entry.SetReceiptHandle(receiptHandle);
                request.AddEntries(entry);
            }

            Aws::SQS::Model::DeleteMessageBatchOutcome outcome =
                    sqsClient.DeleteMessageBatch(request);

            if (outcome.IsSuccess()) {
                std::cout << "The batch deletion of messages was successful."
                          << std::endl;
            }
            else {
                std::cerr << "Error with SQS::DeleteMessageBatch. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                cleanUp(topicARN,
                        queueURLS,
                        subscriptionARNS,
                        snsClient,
                        sqsClient);

                return false;
            }
        }
    }

    return cleanUp(topicARN,
                   queueURLS,
                   subscriptionARNS,
                   snsClient,
                   sqsClient,
                   true); // askUser
}


bool AwsDoc::TopicsAndQueues::cleanUp(const Aws::String &topicARN,
                                      const Aws::Vector<Aws::String> &queueURLS,
                                      const Aws::Vector<Aws::String> &subscriptionARNS,
                                      const Aws::SNS::SNSClient &snsClient,
                                      const Aws::SQS::SQSClient &sqsClient,
                                      bool askUser) {
    bool result = true;
    printAsterisksLine();
    if (!queueURLS.empty() && askUser &&
        askYesNoQuestion("Delete the SQS queues? (y/n) ")) {

        for (const auto &queueURL: queueURLS) {
            // 9.  Delete an SQS queue.
            Aws::SQS::Model::DeleteQueueRequest request;
            request.SetQueueUrl(queueURL);

            Aws::SQS::Model::DeleteQueueOutcome outcome =
                    sqsClient.DeleteQueue(request);

            if (outcome.IsSuccess()) {
                std::cout << "The queue with URL '" << queueURL
                          << "' was successfully deleted." << std::endl;
            }
            else {
                std::cerr << "Error with SQS::DeleteQueue. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }

        for (const auto &subscriptionARN: subscriptionARNS) {
            // 10. Unsubscribe an SNS subscription.
            Aws::SNS::Model::UnsubscribeRequest request;
            request.SetSubscriptionArn(subscriptionARN);

            Aws::SNS::Model::UnsubscribeOutcome outcome =
                    snsClient.Unsubscribe(request);

            if (outcome.IsSuccess()) {
                std::cout << "Unsubscribe of subscription ARN '" << subscriptionARN
                          << "' was successful." << std::endl;
            }
            else {
                std::cerr << "Error with TopicsAndQueues::Unsubscribe. "
                          << outcome.GetError().GetMessage()
                          << std::endl;
                result = false;
            }
        }
    }

    printAsterisksLine();
    if (!topicARN.empty() && askUser &&
        askYesNoQuestion("Delete the SNS topic? (y/n) ")) {

        // 11. Delete an SNS topic.
        Aws::SNS::Model::DeleteTopicRequest request;
        request.SetTopicArn(topicARN);

        Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request);

        if (outcome.IsSuccess()) {
            std::cout << "The topic with ARN '" << topicARN
                      << "' was successfully deleted." << std::endl;
        }
        else {
            std::cerr << "Error with TopicsAndQueues::DeleteTopicRequest. "
                      << outcome.GetError().GetMessage()
                      << std::endl;
            result = false;
        }
    }

    return result;
}

//! Create an IAM policy that gives an SQS queue permission to receive messages from an SNS topic.
/*!
 \sa createPolicyForQueue()
 \param queueARN: The SQS queue Amazon Resource Name (ARN).
 \param topicARN: The SNS topic ARN.
 \return Aws::String: The policy as JSON.
 */
Aws::String AwsDoc::TopicsAndQueues::createPolicyForQueue(const Aws::String &queueARN,
                                                          const Aws::String &topicARN) {
    std::ostringstream policyStream;
    policyStream << R"({
        "Statement": [
        {
            "Effect": "Allow",
                    "Principal": {
                "Service": "sns.amazonaws.com"
            },
            "Action": "sqs:SendMessage",
                    "Resource": ")" << queueARN << R"(",
                    "Condition": {
                "ArnEquals": {
                    "aws:SourceArn": ")" << topicARN << R"("
                }
            }
        }
        ]
    })";

    return policyStream.str();
}
```
+ API の詳細については、「*AWS SDK for C\$1\$1 API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForCpp/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Unsubscribe)

# AWS STS SDK for C\$1\$1 を使用した例
<a name="cpp_1_sts_code_examples"></a>

次のコード例は、 AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_cpp_1_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sts#code-examples)での設定と実行の方法を確認してください。

```
bool AwsDoc::STS::assumeRole(const Aws::String &roleArn,
                             const Aws::String &roleSessionName,
                             const Aws::String &externalId,
                             Aws::Auth::AWSCredentials &credentials,
                             const Aws::Client::ClientConfiguration &clientConfig) {
    Aws::STS::STSClient sts(clientConfig);
    Aws::STS::Model::AssumeRoleRequest sts_req;

    sts_req.SetRoleArn(roleArn);
    sts_req.SetRoleSessionName(roleSessionName);
    sts_req.SetExternalId(externalId);

    const Aws::STS::Model::AssumeRoleOutcome outcome = sts.AssumeRole(sts_req);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error assuming IAM role. " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
    else {
        std::cout << "Credentials successfully retrieved." << std::endl;
        const Aws::STS::Model::AssumeRoleResult result = outcome.GetResult();
        const Aws::STS::Model::Credentials &temp_credentials = result.GetCredentials();

        // Store temporary credentials in return argument.
        // Note: The credentials object returned by assumeRole differs
        // from the AWSCredentials object used in most situations.
        credentials.SetAWSAccessKeyId(temp_credentials.GetAccessKeyId());
        credentials.SetAWSSecretKey(temp_credentials.GetSecretAccessKey());
        credentials.SetSessionToken(temp_credentials.GetSessionToken());
    }

    return outcome.IsSuccess();
}
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[AssumeRole](https://docs.aws.amazon.com/goto/SdkForCpp/sts-2011-06-15/AssumeRole)」を参照してください。

# SDK for C\$1\$1 を使用した Amazon Transcribe Streaming の例
<a name="cpp_1_transcribe-streaming_code_examples"></a>

次のコード例は、Amazon Transcribe Streaming AWS SDK for C\$1\$1 で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `StartStreamTranscription`
<a name="transcribe-streaming_StartStreamTranscription_cpp_1_topic"></a>

次のコード例は、`StartStreamTranscription` を使用する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。

```
int main() {
    Aws::SDKOptions options;

    Aws::InitAPI(options);
    {
        //TODO(User): Set to the region of your AWS account.
        const Aws::String region = Aws::Region::US_WEST_2;

        //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy.
        Aws::Client::ClientConfiguration config;
#ifdef _WIN32
        // ATTENTION: On Windows with the AWS C++ SDK, this example only runs if the SDK is built
        // with the curl library. 
        // For more information, see the accompanying ReadMe.
        // For more information, see "Building the SDK for Windows with curl".
        // https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup-windows.html
        //TODO(User): Update to the location of your .crt file.
        config.caFile = "C:/curl/bin/curl-ca-bundle.crt";
#endif
        config.region = region;

        TranscribeStreamingServiceClient client(config);
        StartStreamTranscriptionHandler handler;
        handler.SetOnErrorCallback(
                [](const Aws::Client::AWSError<TranscribeStreamingServiceErrors> &error) {
                        std::cerr << "ERROR: " + error.GetMessage() << std::endl;
                });
        //SetTranscriptEventCallback called for every 'chunk' of file transcripted.
        // Partial results are returned in real time.
        handler.SetTranscriptEventCallback([](const TranscriptEvent &ev) {
                for (auto &&r: ev.GetTranscript().GetResults()) {
                    if (r.GetIsPartial()) {
                        std::cout << "[partial] ";
                    }
                    else {
                        std::cout << "[Final] ";
                    }
                    for (auto &&alt: r.GetAlternatives()) {
                        std::cout << alt.GetTranscript() << std::endl;
                    }
                }
        });

        StartStreamTranscriptionRequest request;
        request.SetMediaSampleRateHertz(SAMPLE_RATE);
        request.SetLanguageCode(LanguageCode::en_US);
        request.SetMediaEncoding(
                MediaEncoding::pcm); // wav and aiff files are PCM formats.
        request.SetEventStreamHandler(handler);

        auto OnStreamReady = [](AudioStream &stream) {
                Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary);
                if (!file.is_open()) {
                    std::cerr << "Failed to open " << FILE_NAME << '\n';
                }
                std::array<char, BUFFER_SIZE> buf;
                int i = 0;
                while (file) {
                    file.read(&buf[0], buf.size());

                    if (!file)
                        std::cout << "File: only " << file.gcount() << " could be read"
                                  << std::endl;

                    Aws::Vector<unsigned char> bits{buf.begin(), buf.end()};
                    AudioEvent event(std::move(bits));
                    if (!stream) {
                        std::cerr << "Failed to create a stream" << std::endl;
                        break;
                    }
                    //The std::basic_istream::gcount() is used to count the characters in the given string. It returns
                    //the number of characters extracted by the last read() operation.
                    if (file.gcount() > 0) {
                        if (!stream.WriteAudioEvent(event)) {
                            std::cerr << "Failed to write an audio event" << std::endl;
                            break;
                        }
                    }
                    else {
                        break;
                    }
                    std::this_thread::sleep_for(std::chrono::milliseconds(
                            25)); // Slow down because we are streaming from a file.
                }
                if (!stream.WriteAudioEvent(
                        AudioEvent())) {
                    // Per the spec, we have to send an empty event (an event without a payload) at the end.
                    std::cerr << "Failed to send an empty frame" << std::endl;
                }
                else {
                    std::cout << "Successfully sent the empty frame" << std::endl;
                }
                stream.flush();
                stream.Close();
        };

        Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/);
        auto OnResponseCallback = [&signaling](
                const TranscribeStreamingServiceClient * /*unused*/,
                const Model::StartStreamTranscriptionRequest & /*unused*/,
                const Model::StartStreamTranscriptionOutcome &outcome,
                const std::shared_ptr<const Aws::Client::AsyncCallerContext> & /*unused*/) {

                if (!outcome.IsSuccess()) {
                    std::cerr << "Transcribe streaming error "
                              << outcome.GetError().GetMessage() << std::endl;
                }

                signaling.Release();
        };

        std::cout << "Starting..." << std::endl;
        client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback,
                                             nullptr /*context*/);
        signaling.WaitOne(); // Prevent the application from exiting until we're done.
        std::cout << "Done" << std::endl;
    }

    Aws::ShutdownAPI(options);

    return 0;
}
```
+  API の詳細については、「AWS SDK for C\$1\$1 API リファレンス**」の「[StartStreamTranscription](https://docs.aws.amazon.com/goto/SdkForCpp/transcribe-streaming-2017-10-26/StartStreamTranscription)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 音声ファイルの文字起こし
<a name="transcribe-streaming_Scenario_StreamEvents_File_cpp_1_topic"></a>

次のコード例は、Amazon Transcribe ストリーミングを使用してソースオーディオファイルの文字起こしを生成する方法を示しています。

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。

```
int main() {
    Aws::SDKOptions options;

    Aws::InitAPI(options);
    {
        //TODO(User): Set to the region of your AWS account.
        const Aws::String region = Aws::Region::US_WEST_2;

        //Load a profile that has been granted AmazonTranscribeFullAccess AWS managed permission policy.
        Aws::Client::ClientConfiguration config;
#ifdef _WIN32
        // ATTENTION: On Windows with the AWS C++ SDK, this example only runs if the SDK is built
        // with the curl library. 
        // For more information, see the accompanying ReadMe.
        // For more information, see "Building the SDK for Windows with curl".
        // https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup-windows.html
        //TODO(User): Update to the location of your .crt file.
        config.caFile = "C:/curl/bin/curl-ca-bundle.crt";
#endif
        config.region = region;

        TranscribeStreamingServiceClient client(config);
        StartStreamTranscriptionHandler handler;
        handler.SetOnErrorCallback(
                [](const Aws::Client::AWSError<TranscribeStreamingServiceErrors> &error) {
                        std::cerr << "ERROR: " + error.GetMessage() << std::endl;
                });
        //SetTranscriptEventCallback called for every 'chunk' of file transcripted.
        // Partial results are returned in real time.
        handler.SetTranscriptEventCallback([](const TranscriptEvent &ev) {
                for (auto &&r: ev.GetTranscript().GetResults()) {
                    if (r.GetIsPartial()) {
                        std::cout << "[partial] ";
                    }
                    else {
                        std::cout << "[Final] ";
                    }
                    for (auto &&alt: r.GetAlternatives()) {
                        std::cout << alt.GetTranscript() << std::endl;
                    }
                }
        });

        StartStreamTranscriptionRequest request;
        request.SetMediaSampleRateHertz(SAMPLE_RATE);
        request.SetLanguageCode(LanguageCode::en_US);
        request.SetMediaEncoding(
                MediaEncoding::pcm); // wav and aiff files are PCM formats.
        request.SetEventStreamHandler(handler);

        auto OnStreamReady = [](AudioStream &stream) {
                Aws::FStream file(FILE_NAME, std::ios_base::in | std::ios_base::binary);
                if (!file.is_open()) {
                    std::cerr << "Failed to open " << FILE_NAME << '\n';
                }
                std::array<char, BUFFER_SIZE> buf;
                int i = 0;
                while (file) {
                    file.read(&buf[0], buf.size());

                    if (!file)
                        std::cout << "File: only " << file.gcount() << " could be read"
                                  << std::endl;

                    Aws::Vector<unsigned char> bits{buf.begin(), buf.end()};
                    AudioEvent event(std::move(bits));
                    if (!stream) {
                        std::cerr << "Failed to create a stream" << std::endl;
                        break;
                    }
                    //The std::basic_istream::gcount() is used to count the characters in the given string. It returns
                    //the number of characters extracted by the last read() operation.
                    if (file.gcount() > 0) {
                        if (!stream.WriteAudioEvent(event)) {
                            std::cerr << "Failed to write an audio event" << std::endl;
                            break;
                        }
                    }
                    else {
                        break;
                    }
                    std::this_thread::sleep_for(std::chrono::milliseconds(
                            25)); // Slow down because we are streaming from a file.
                }
                if (!stream.WriteAudioEvent(
                        AudioEvent())) {
                    // Per the spec, we have to send an empty event (an event without a payload) at the end.
                    std::cerr << "Failed to send an empty frame" << std::endl;
                }
                else {
                    std::cout << "Successfully sent the empty frame" << std::endl;
                }
                stream.flush();
                stream.Close();
        };

        Aws::Utils::Threading::Semaphore signaling(0 /*initialCount*/, 1 /*maxCount*/);
        auto OnResponseCallback = [&signaling](
                const TranscribeStreamingServiceClient * /*unused*/,
                const Model::StartStreamTranscriptionRequest & /*unused*/,
                const Model::StartStreamTranscriptionOutcome &outcome,
                const std::shared_ptr<const Aws::Client::AsyncCallerContext> & /*unused*/) {

                if (!outcome.IsSuccess()) {
                    std::cerr << "Transcribe streaming error "
                              << outcome.GetError().GetMessage() << std::endl;
                }

                signaling.Release();
        };

        std::cout << "Starting..." << std::endl;
        client.StartStreamTranscriptionAsync(request, OnStreamReady, OnResponseCallback,
                                             nullptr /*context*/);
        signaling.WaitOne(); // Prevent the application from exiting until we're done.
        std::cout << "Done" << std::endl;
    }

    Aws::ShutdownAPI(options);

    return 0;
}
```
+  API の詳細については、「AWS SDK for C\$1\$1 API リファレンス**」の「[StartStreamTranscription](https://docs.aws.amazon.com/goto/SdkForCpp/transcribe-streaming-2017-10-26/StartStreamTranscription)」を参照してください。

# のコード例 AWS CLI
<a name="cli_2_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [AWS CLI デベロッパーガイド ](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) ** – で CLI を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](cli_2_acm_code_examples.md)
+ [API ゲートウェイ](cli_2_api-gateway_code_examples.md)
+ [API Gateway HTTP と WebSocket API](cli_2_apigatewayv2_code_examples.md)
+ [API Gateway Management API](cli_2_apigatewaymanagementapi_code_examples.md)
+ [App Mesh](cli_2_app-mesh_code_examples.md)
+ [App Runner](cli_2_apprunner_code_examples.md)
+ [AWS AppConfig](cli_2_appconfig_code_examples.md)
+ [Application Auto Scaling](cli_2_application-auto-scaling_code_examples.md)
+ [Application Discovery Service](cli_2_application-discovery-service_code_examples.md)
+ [Application Signals](cli_2_application-signals_code_examples.md)
+ [AppRegistry](cli_2_service-catalog-appregistry_code_examples.md)
+ [Athena](cli_2_athena_code_examples.md)
+ [Auto Scaling](cli_2_auto-scaling_code_examples.md)
+ [自動スケーリングプラン](cli_2_auto-scaling-plans_code_examples.md)
+ [AWS Backup](cli_2_backup_code_examples.md)
+ [AWS Batch](cli_2_batch_code_examples.md)
+ [AWS Budgets](cli_2_budgets_code_examples.md)
+ [Amazon Chime](cli_2_chime_code_examples.md)
+ [Cloud Control API](cli_2_cloudcontrol_code_examples.md)
+ [AWS Cloud Map](cli_2_servicediscovery_code_examples.md)
+ [AWS Cloud9](cli_2_cloud9_code_examples.md)
+ [CloudFormation](cli_2_cloudformation_code_examples.md)
+ [CloudFront](cli_2_cloudfront_code_examples.md)
+ [Amazon CloudSearch](cli_2_cloudsearch-domain_code_examples.md)
+ [CloudTrail](cli_2_cloudtrail_code_examples.md)
+ [CloudWatch](cli_2_cloudwatch_code_examples.md)
+ [CloudWatch Logs](cli_2_cloudwatch-logs_code_examples.md)
+ [CloudWatch Network Monitoring](cli_2_networkmonitor_code_examples.md)
+ [CloudWatch Observability Access Monitor](cli_2_oam_code_examples.md)
+ [CloudWatch Observability Admin](cli_2_observabilityadmin_code_examples.md)
+ [CloudWatch Synthetics](cli_2_synthetics_code_examples.md)
+ [CodeArtifact](cli_2_codeartifact_code_examples.md)
+ [CodeBuild](cli_2_codebuild_code_examples.md)
+ [CodeCommit](cli_2_codecommit_code_examples.md)
+ [CodeDeploy](cli_2_codedeploy_code_examples.md)
+ [CodeGuru Reviewer](cli_2_codeguru-reviewer_code_examples.md)
+ [CodePipeline](cli_2_codepipeline_code_examples.md)
+ [AWS CodeStar 通知](cli_2_codestar-notifications_code_examples.md)
+ [CodeConnections](cli_2_codestar-connections_code_examples.md)
+ [Amazon Cognito ID](cli_2_cognito-identity_code_examples.md)
+ [Amazon Cognito ID プロバイダー](cli_2_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](cli_2_comprehend_code_examples.md)
+ [Amazon Comprehend Medical](cli_2_comprehendmedical_code_examples.md)
+ [AWS Config](cli_2_config-service_code_examples.md)
+ [Amazon Connect](cli_2_connect_code_examples.md)
+ [AWS Cost and Usage Report](cli_2_cost-and-usage-report-service_code_examples.md)
+ [Cost Explorer サービス](cli_2_cost-explorer_code_examples.md)
+ [Firehose](cli_2_firehose_code_examples.md)
+ [Amazon Data Lifecycle Manager](cli_2_dlm_code_examples.md)
+ [AWS Data Pipeline](cli_2_data-pipeline_code_examples.md)
+ [DataSync](cli_2_datasync_code_examples.md)
+ [DAX](cli_2_dax_code_examples.md)
+ [検出](cli_2_detective_code_examples.md)
+ [Device Farm](cli_2_device-farm_code_examples.md)
+ [Direct Connect](cli_2_direct-connect_code_examples.md)
+ [Directory Service](cli_2_directory-service_code_examples.md)
+ [Directory Service データ](cli_2_directory-service-data_code_examples.md)
+ [AWS DMS](cli_2_database-migration-service_code_examples.md)
+ [Amazon DocumentDB](cli_2_docdb_code_examples.md)
+ [DynamoDB](cli_2_dynamodb_code_examples.md)
+ [DynamoDB Streams](cli_2_dynamodb-streams_code_examples.md)
+ [Amazon EC2](cli_2_ec2_code_examples.md)
+ [Amazon EC2 Instance Connect](cli_2_ec2-instance-connect_code_examples.md)
+ [Amazon ECR](cli_2_ecr_code_examples.md)
+ [Amazon ECR Public](cli_2_ecr-public_code_examples.md)
+ [Amazon ECS](cli_2_ecs_code_examples.md)
+ [Amazon EFS](cli_2_efs_code_examples.md)
+ [Amazon EKS](cli_2_eks_code_examples.md)
+ [(Elastic Beanstalk)](cli_2_elastic-beanstalk_code_examples.md)
+ [Elastic Load Balancing - バージョン 1](cli_2_elastic-load-balancing_code_examples.md)
+ [Elastic Load Balancing - バージョン 2](cli_2_elastic-load-balancing-v2_code_examples.md)
+ [ElastiCache](cli_2_elasticache_code_examples.md)
+ [MediaStore](cli_2_mediastore_code_examples.md)
+ [Amazon EMR](cli_2_emr_code_examples.md)
+ [Amazon EMR on EKS](cli_2_emr-containers_code_examples.md)
+ [EventBridge](cli_2_eventbridge_code_examples.md)
+ [EventBridge Pipes](cli_2_pipes_code_examples.md)
+ [Firewall Manager](cli_2_fms_code_examples.md)
+ [AWS FIS](cli_2_fis_code_examples.md)
+ [Amazon GameLift Servers](cli_2_gamelift_code_examples.md)
+ [Amazon Glacier](cli_2_glacier_code_examples.md)
+ [Global Accelerator](cli_2_global-accelerator_code_examples.md)
+ [AWS Glue](cli_2_glue_code_examples.md)
+ [GuardDuty](cli_2_guardduty_code_examples.md)
+ [AWS Health](cli_2_health_code_examples.md)
+ [HealthImaging](cli_2_medical-imaging_code_examples.md)
+ [HealthLake](cli_2_healthlake_code_examples.md)
+ [HealthOmics](cli_2_omics_code_examples.md)
+ [IAM](cli_2_iam_code_examples.md)
+ [IAM Access Analyzer](cli_2_accessanalyzer_code_examples.md)
+ [Image Builder](cli_2_imagebuilder_code_examples.md)
+ [Incident Manager](cli_2_ssm-incidents_code_examples.md)
+ [Incident Manager Contacts](cli_2_ssm-contacts_code_examples.md)
+ [Amazon Inspector](cli_2_inspector2_code_examples.md)
+ [AWS IoT](cli_2_iot_code_examples.md)
+ [Device Advisor](cli_2_iotdeviceadvisor_code_examples.md)
+ [AWS IoT data](cli_2_iot-data-plane_code_examples.md)
+ [AWS IoT Events](cli_2_iot-events_code_examples.md)
+ [AWS IoT Events-Data](cli_2_iot-events-data_code_examples.md)
+ [AWS IoT Greengrass](cli_2_greengrass_code_examples.md)
+ [AWS IoT Greengrass V2](cli_2_greengrassv2_code_examples.md)
+ [AWS IoT ジョブ SDK リリース](cli_2_iot-jobs-data-plane_code_examples.md)
+ [AWS IoT SiteWise](cli_2_iotsitewise_code_examples.md)
+ [AWS IoT Things Graph](cli_2_iotthingsgraph_code_examples.md)
+ [AWS IoT Wireless](cli_2_iot-wireless_code_examples.md)
+ [Amazon IVS](cli_2_ivs_code_examples.md)
+ [Amazon IVS Chat](cli_2_ivschat_code_examples.md)
+ [Amazon IVS Real-Time Streaming](cli_2_ivs-realtime_code_examples.md)
+ [Amazon Kendra](cli_2_kendra_code_examples.md)
+ [Kinesis](cli_2_kinesis_code_examples.md)
+ [AWS KMS](cli_2_kms_code_examples.md)
+ [Lake Formation](cli_2_lakeformation_code_examples.md)
+ [Lambda](cli_2_lambda_code_examples.md)
+ [License Manager](cli_2_license-manager_code_examples.md)
+ [Lightsail](cli_2_lightsail_code_examples.md)
+ [Macie](cli_2_macie2_code_examples.md)
+ [Amazon Managed Grafana](cli_2_grafana_code_examples.md)
+ [MediaConnect](cli_2_mediaconnect_code_examples.md)
+ [MediaConvert](cli_2_mediaconvert_code_examples.md)
+ [MediaLive](cli_2_medialive_code_examples.md)
+ [MediaPackage](cli_2_mediapackage_code_examples.md)
+ [MediaPackage VOD](cli_2_mediapackage-vod_code_examples.md)
+ [MediaStore Data Plane](cli_2_mediastore-data_code_examples.md)
+ [MediaTailor](cli_2_mediatailor_code_examples.md)
+ [MemoryDB](cli_2_memorydb_code_examples.md)
+ [Amazon MSK](cli_2_kafka_code_examples.md)
+ [Network Flow Monitor](cli_2_networkflowmonitor_code_examples.md)
+ [Network Manager](cli_2_networkmanager_code_examples.md)
+ [OpenSearch Service](cli_2_elasticsearch-service_code_examples.md)
+ [組織](cli_2_organizations_code_examples.md)
+ [AWS Outposts](cli_2_outposts_code_examples.md)
+ [AWS Payment Cryptography](cli_2_payment-cryptography_code_examples.md)
+ [AWS Payment Cryptography データプレーン](cli_2_payment-cryptography-data_code_examples.md)
+ [Amazon Pinpoint](cli_2_pinpoint_code_examples.md)
+ [Amazon Polly](cli_2_polly_code_examples.md)
+ [AWS の料金表](cli_2_pricing_code_examples.md)
+ [AWS Private CA](cli_2_acm-pca_code_examples.md)
+ [AWS Proton](cli_2_proton_code_examples.md)
+ [Amazon RDS](cli_2_rds_code_examples.md)
+ [Amazon RDS データサービス](cli_2_rds-data_code_examples.md)
+ [Amazon RDS Performance Insights](cli_2_pi_code_examples.md)
+ [Amazon Redshift](cli_2_redshift_code_examples.md)
+ [Amazon Rekognition](cli_2_rekognition_code_examples.md)
+ [AWS RAM](cli_2_ram_code_examples.md)
+ [Resource Explorer](cli_2_resource-explorer-2_code_examples.md)
+ [リソースグループ](cli_2_resource-groups_code_examples.md)
+ [リソースグループタグ付け API](cli_2_resource-groups-tagging-api_code_examples.md)
+ [Route 53](cli_2_route-53_code_examples.md)
+ [Route 53 ドメイン登録](cli_2_route-53-domains_code_examples.md)
+ [Route 53 プロファイル](cli_2_route53profiles_code_examples.md)
+ [Route 53 Resolver](cli_2_route53resolver_code_examples.md)
+ [Amazon S3](cli_2_s3_code_examples.md)
+ [Amazon S3 Control](cli_2_s3-control_code_examples.md)
+ [Secrets Manager](cli_2_secrets-manager_code_examples.md)
+ [Security Hub CSPM](cli_2_securityhub_code_examples.md)
+ [Security Lake](cli_2_securitylake_code_examples.md)
+ [AWS Serverless Application Repository](cli_2_serverlessapplicationrepository_code_examples.md)
+ [Service Catalog](cli_2_service-catalog_code_examples.md)
+ [サービスクォータ](cli_2_service-quotas_code_examples.md)
+ [Amazon SES](cli_2_ses_code_examples.md)
+ [Shield](cli_2_shield_code_examples.md)
+ [Signer](cli_2_signer_code_examples.md)
+ [Snowball Edge](cli_2_snowball_code_examples.md)
+ [Amazon SNS](cli_2_sns_code_examples.md)
+ [Amazon SQS](cli_2_sqs_code_examples.md)
+ [Storage Gateway](cli_2_storage-gateway_code_examples.md)
+ [AWS STS](cli_2_sts_code_examples.md)
+ [サポート](cli_2_support_code_examples.md)
+ [Amazon SWF](cli_2_swf_code_examples.md)
+ [Systems Manager](cli_2_ssm_code_examples.md)
+ [Amazon Textract](cli_2_textract_code_examples.md)
+ [Amazon Transcribe](cli_2_transcribe_code_examples.md)
+ [Amazon Translate](cli_2_translate_code_examples.md)
+ [Trusted Advisor](cli_2_trustedadvisor_code_examples.md)
+ [Verified Permissions](cli_2_verifiedpermissions_code_examples.md)
+ [VPC Lattice](cli_2_vpc-lattice_code_examples.md)
+ [AWS WAF Classic](cli_2_waf_code_examples.md)
+ [AWS WAF Classic Regional](cli_2_waf-regional_code_examples.md)
+ [AWS WAFV2](cli_2_wafv2_code_examples.md)
+ [WorkDocs](cli_2_workdocs_code_examples.md)
+ [Amazon WorkMail](cli_2_workmail_code_examples.md)
+ [Amazon WorkMail メッセージフロー](cli_2_workmailmessageflow_code_examples.md)
+ [WorkSpaces](cli_2_workspaces_code_examples.md)
+ [X-Ray](cli_2_xray_code_examples.md)

# を使用した ACM の例 AWS CLI
<a name="cli_2_acm_code_examples"></a>

次のコード例は、ACM AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags-to-certificate`
<a name="acm_AddTagsToCertificate_cli_2_topic"></a>

次の例では、`add-tags-to-certificate` を使用する方法を説明しています。

**AWS CLI**  
**既存の ACM 証明書にタグを追加する方法**  
次の `add-tags-to-certificate` コマンドは、指定された証明書に 2 つのタグを追加します。複数のタグは空白で区切ります。  

```
aws acm add-tags-to-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012 --tags Key=Admin,Value=Alice Key=Purpose,Value=Website
```
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AddTagsToCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/add-tags-to-certificate.html)」を参照してください。

### `delete-certificate`
<a name="acm_DeleteCertificate_cli_2_topic"></a>

次の例では、`delete-certificate` を使用する方法を説明しています。

**AWS CLI**  
**アカウントから ACM 証明書を削除する方法**  
次の `delete-certificate` コマンドは、指定した ARN の証明書を削除します。  

```
aws acm delete-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/delete-certificate.html)」を参照してください。

### `describe-certificate`
<a name="acm_DescribeCertificate_cli_2_topic"></a>

次の例では、`describe-certificate` を使用する方法を説明しています。

**AWS CLI**  
**ACM 証明書に含まれるフィールドを取得する方法**  
次の `describe-certificate` コマンドは、指定した ARN の証明書のすべてのフィールドを取得します。  

```
aws acm describe-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012
```
以下のような出力が表示されます。  

```
{
  "Certificate": {
    "CertificateArn": "arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012",
    "CreatedAt": 1446835267.0,
    "DomainName": "www.example.com",
    "DomainValidationOptions": [
      {
        "DomainName": "www.example.com",
        "ValidationDomain": "www.example.com",
        "ValidationEmails": [
          "hostmaster@example.com",
          "admin@example.com",
          "owner@example.com.whoisprivacyservice.org",
          "tech@example.com.whoisprivacyservice.org",
          "admin@example.com.whoisprivacyservice.org",
          "postmaster@example.com",
          "webmaster@example.com",
          "administrator@example.com"
        ]
      },
      {
        "DomainName": "www.example.net",
        "ValidationDomain": "www.example.net",
        "ValidationEmails": [
          "postmaster@example.net",
          "admin@example.net",
          "owner@example.net.whoisprivacyservice.org",
          "tech@example.net.whoisprivacyservice.org",
          "admin@example.net.whoisprivacyservice.org",
          "hostmaster@example.net",
          "administrator@example.net",
          "webmaster@example.net"
        ]
      }
    ],
    "InUseBy": [],
    "IssuedAt": 1446835815.0,
    "Issuer": "Amazon",
    "KeyAlgorithm": "RSA-2048",
    "NotAfter": 1478433600.0,
    "NotBefore": 1446768000.0,
    "Serial": "0f:ac:b0:a3:8d:ea:65:52:2d:7d:01:3a:39:36:db:d6",
    "SignatureAlgorithm": "SHA256WITHRSA",
    "Status": "ISSUED",
    "Subject": "CN=www.example.com",
    "SubjectAlternativeNames": [
      "www.example.com",
      "www.example.net"
    ]
  }
}
```
+  API の詳細については、**AWS CLI コマンドリファレンスの「[DescribeCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/describe-certificate.html)」を参照してください。

### `export-certificate`
<a name="acm_ExportCertificate_cli_2_topic"></a>

次の例では、`export-certificate` を使用する方法を説明しています。

**AWS CLI**  
**プライベート CA によって発行されたプライベート証明書をエクスポートする方法**  
次の `export-certificate` のコマンドは、プライベート証明書、証明書チェーン、プライベートキーをディスプレイにエクスポートします。  

```
aws acm export-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012 --passphrase file://path-to-passphrase-file
```
証明書、チェーン、プライベートキーをローカルファイルにエクスポートするには、次のコマンドを使用します。  

```
aws acm export-certificate --certificate-arn arn:aws:acm:region:sccount:certificate/12345678-1234-1234-1234-123456789012 --passphrase file://path-to-passphrase-file > c:\temp\export.txt
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExportCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/export-certificate.html)」を参照してください。

### `get-certificate`
<a name="acm_GetCertificate_cli_2_topic"></a>

次の例では、`get-certificate` を使用する方法を説明しています。

**AWS CLI**  
**ACM 証明書を取得する方法**  
次の `get-certificate` のコマンドは、指定された ARN およびチェーンの証明書を取得します。  

```
aws acm get-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012
```
以下のような出力が表示されます。  

```
{
  "Certificate": "-----BEGIN CERTIFICATE-----
MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----",

  "CertificateChain": "-----BEGIN CERTIFICATE-----
MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----",
"-----BEGIN CERTIFICATE-----
MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----",
"-----BEGIN CERTIFICATE-----
MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/get-certificate.html)」を参照してください。

### `import-certificate`
<a name="acm_ImportCertificate_cli_2_topic"></a>

次の例では、`import-certificate` を使用する方法を説明しています。

**AWS CLI**  
**ACM に証明書をインポートする方法**  
以下の `import-certificate` コマンドは、ACM に証明書をインポートします。ファイル名を使用するファイル名で置き換えます。  

```
aws acm import-certificate --certificate file://Certificate.pem --certificate-chain file://CertificateChain.pem --private-key file://PrivateKey.pem
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/import-certificate.html)」を参照してください。

### `list-certificates`
<a name="acm_ListCertificates_cli_2_topic"></a>

次の例は、`list-certificates` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントの ACM 証明書を一覧表示するには**  
次の `list-certificates` コマンドは、アカウント内の証明書の ARN を一覧表示します。  

```
aws acm list-certificates
```
このコマンドを処理すると、次のような出力が生成されます。  

```
{
    "CertificateSummaryList": [
        {
            "CertificateArn": "arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012",
            "DomainName": "www.example.com"
        },
        {
            "CertificateArn": "arn:aws:acm:region:account:certificate/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
            "DomainName": "www.example.net"
        }
    ]
}
```
`list-certificates` を呼び出すたびに表示される証明書の数を指定できます。例えば、証明書が 4 つあって一度に 2 つまでを表示する場合は、次の例のように `max-items` 引数を 2 に設定します。  

```
aws acm list-certificates --max-items 2
```
2 つの証明書 ARN と `NextToken` 値が表示されます。  

```
"CertificateSummaryList": [
  {
    "CertificateArn": "arn:aws:acm:region:account: \
            certificate/12345678-1234-1234-1234-123456789012",
    "DomainName": "www.example.com"
  },
  {
    "CertificateArn": "arn:aws:acm:region:account: \
             certificate/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "DomainName": "www.example.net"
  }
  ],
    "NextToken": "9f4d9f69-275a-41fe-b58e-2b837bd9ba48"
```
アカウント内の次の 2 つの証明書を表示するには、次の呼び出しで `NextToken` 値を設定します。  

```
aws acm list-certificates --max-items 2 --next-token 9f4d9f69-275a-41fe-b58e-2b837bd9ba48
```
`certificate-statuses` 引数を使用して出力をフィルタリングできます。以下のコマンドは、PENDING\$1VALIDATION ステータスの証明書を表示します。  

```
aws acm list-certificates --certificate-statuses PENDING_VALIDATION
```
また、`includes` 引数を使用して出力をフィルタリングすることもできます。次のコマンドは、以下のプロパティでフィルタリングされた証明書を表示します。表示される証明書:  

```
- Specify that the RSA algorithm and a 2048 bit key are used to generate key pairs.
- Contain a Key Usage extension that specifies that the certificates can be used to create digital signatures.
- Contain an Extended Key Usage extension that specifies that the certificates can be used for code signing.

aws acm list-certificates --max-items 10 --includes extendedKeyUsage=CODE_SIGNING,keyUsage=DIGITAL_SIGNATURE,keyTypes=RSA_2048
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/list-certificates.html)」を参照してください。

### `list-tags-for-certificate`
<a name="acm_ListTagsForCertificate_cli_2_topic"></a>

次の例では、`list-tags-for-certificate` を使用する方法を説明しています。

**AWS CLI**  
**ACM 証明書に適用されたタグを一覧表示する方法**  
次の `list-tags-for-certificate` コマンドは、アカウント内の証明書に適用されたタグを一覧表示します。  

```
aws acm list-tags-for-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012
```
このコマンドを処理すると、次のような出力が生成されます。  

```
{
  "Tags": [
      {
          "Value": "Website",
          "Key": "Purpose"
      },
      {
          "Value": "Alice",
          "Key": "Admin"
      }
  ]
}
```
+  API の詳細については、**AWS CLI コマンドリファレンスの「[ListTagsForCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/list-tags-for-certificate.html)」を参照してください。

### `remove-tags-from-certificate`
<a name="acm_RemoveTagsFromCertificate_cli_2_topic"></a>

次の例では、`remove-tags-from-certificate` を使用する方法を説明しています。

**AWS CLI**  
**ACM 証明書からタグを削除する方法**  
次の `remove-tags-from-certificate` のコマンドは、指定された証明書から 2 つのタグを削除します。複数のタグは空白で区切ります。  

```
aws acm remove-tags-from-certificate --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012 --tags Key=Admin,Value=Alice Key=Purpose,Value=Website
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/remove-tags-from-certificate.html)」を参照してください。

### `request-certificate`
<a name="acm_RequestCertificate_cli_2_topic"></a>

次の例では、`request-certificate` を使用する方法を説明しています。

**AWS CLI**  
**新しい ACM 証明書をリクエストする方法**  
次の `request-certificate` コマンドは、DNS 検証を使用して www.example.com ドメインの新しい証明書をリクエストします。  

```
aws acm request-certificate --domain-name www.example.com --validation-method DNS
```
べき等性トークンを入力して、`request-certificate` への呼び出しを区別できます。  

```
aws acm request-certificate --domain-name www.example.com --validation-method DNS --idempotency-token 91adc45q
```
サブジェクトの代替名を 1 つ以上入力して、複数の Apex ドメインを保護する証明書をリクエストできます。  

```
aws acm request-certificate --domain-name example.com --validation-method DNS --idempotency-token 91adc45q --subject-alternative-names www.example.net
```
ウェブサイトへのアクセスに使用できる代替名を入力することもできます。  

```
aws acm request-certificate --domain-name example.com --validation-method DNS --idempotency-token 91adc45q --subject-alternative-names www.example.com
```
アスタリスク (\$1) をワイルドカードとして使用して、同じドメイン内の複数のサブドメインの証明書を作成できます。  

```
aws acm request-certificate --domain-name example.com --validation-method DNS --idempotency-token 91adc45q --subject-alternative-names *.example.com
```
複数の代替名を入力することもできます。  

```
aws acm request-certificate --domain-name example.com --validation-method DNS --subject-alternative-names b.example.com c.example.com d.example.com
```
検証に E メールを使用している場合は、ドメイン検証オプションを入力して、検証 E メールの送信先ドメインを指定できます。  

```
aws acm request-certificate --domain-name example.com --validation-method EMAIL --subject-alternative-names www.example.com --domain-validation-options DomainName=example.com,ValidationDomain=example.com
```
次のコマンドは、新しい証明書をリクエストしたときに、証明書の透明性ロギングをオプトアウトします。  

```
aws acm request-certificate --domain-name www.example.com --validation-method DNS --options CertificateTransparencyLoggingPreference=DISABLED --idempotency-token 184627
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RequestCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/request-certificate.html)」を参照してください。

### `resend-validation-email`
<a name="acm_ResendValidationEmail_cli_2_topic"></a>

次の例では、`resend-validation-email` を使用する方法を説明しています。

**AWS CLI**  
**ACM 証明書リクエストの検証 E メールを再送信する方法**  
次の `resend-validation-email` コマンドは、Amazon 認証機関に検証 E メールを適切なアドレスに送信するように指示します。  

```
aws acm resend-validation-email --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012 --domain www.example.com --validation-domain example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResendValidationEmail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/resend-validation-email.html)」を参照してください。

### `update-certificate-options`
<a name="acm_UpdateCertificateOptions_cli_2_topic"></a>

次の例では、`update-certificate-options` を使用する方法を説明しています。

**AWS CLI**  
**証明書オプションを更新する方法**  
次の `update-certificate-options` のコマンドは、証明書の透明性ロギングからオプトアウトします。  

```
aws acm update-certificate-options --certificate-arn arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012 --options CertificateTransparencyLoggingPreference=DISABLED
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCertificateOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm/update-certificate-options.html)」を参照してください。

# を使用した API Gateway の例 AWS CLI
<a name="cli_2_api-gateway_code_examples"></a>

次のコード例は、API Gateway AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-api-key`
<a name="api-gateway_CreateApiKey_cli_2_topic"></a>

次のコード例では、`create-api-key` を使用する方法を示しています。

**AWS CLI**  
**既存の API とステージで有効になっている API キーを作成する方法**  
コマンド:  

```
aws apigateway create-api-key --name 'Dev API Key' --description 'Used for development' --enabled --stage-keys restApiId='a1b2c3d4e5',stageName='dev'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApiKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-api-key.html)」を参照してください。

### `create-authorizer`
<a name="api-gateway_CreateAuthorizer_cli_2_topic"></a>

次のコード例では、`create-authorizer` を使用する方法を示しています。

**AWS CLI**  
**例 1: API のトークンベースの API Gateway Custom Authorizer を作成する方法**  
次の `create-authorizer` の例では、トークンベースのオーソライザーを作成します。  

```
aws apigateway create-authorizer \
    --rest-api-id 1234123412 \
    --name 'First_Token_Custom_Authorizer' \
    --type TOKEN \
    --authorizer-uri 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations' \
    --identity-source 'method.request.header.Authorization' \
    --authorizer-result-ttl-in-seconds 300
```
出力:  

```
{
    "authType": "custom",
    "name": "First_Token_Custom_Authorizer",
    "authorizerUri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations",
    "authorizerResultTtlInSeconds": 300,
    "identitySource": "method.request.header.Authorization",
    "type": "TOKEN",
    "id": "z40xj0"
}
```
**例 2: API の Cognito ユーザープールベースの API Gateway Custom Authorizer を作成する方法**  
次の `create-authorizer` の例では、Cognito ユーザープールベースの API Gateway Custom Authorizer を作成します。  

```
aws apigateway create-authorizer \
    --rest-api-id 1234123412 \
    --name 'First_Cognito_Custom_Authorizer' \
    --type COGNITO_USER_POOLS \
    --provider-arns 'arn:aws:cognito-idp:us-east-1:123412341234:userpool/us-east-1_aWcZeQbuD' \
    --identity-source 'method.request.header.Authorization'
```
出力:  

```
{
    "authType": "cognito_user_pools",
    "identitySource": "method.request.header.Authorization",
    "name": "First_Cognito_Custom_Authorizer",
    "providerARNs": [
        "arn:aws:cognito-idp:us-east-1:342398297714:userpool/us-east-1_qWbZzQhzE"
    ],
    "type": "COGNITO_USER_POOLS",
    "id": "5yid1t"
}
```
**例 3: API のリクエストベースの API Gateway Custom Authorizer を作成する方法**  
次の `create-authorizer` の例では、リクエストベースのオーソライザーを作成します。  

```
aws apigateway create-authorizer \
    --rest-api-id 1234123412 \
    --name 'First_Request_Custom_Authorizer' \
    --type REQUEST \
    --authorizer-uri 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations' \
    --identity-source 'method.request.header.Authorization,context.accountId' \
    --authorizer-result-ttl-in-seconds 300
```
出力:  

```
{
    "id": "z40xj0",
    "name": "First_Request_Custom_Authorizer",
    "type": "REQUEST",
    "authType": "custom",
    "authorizerUri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:customAuthFunction/invocations",
    "identitySource": "method.request.header.Authorization,context.accountId",
    "authorizerResultTtlInSeconds": 300
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-authorizer.html)」を参照してください。

### `create-base-path-mapping`
<a name="api-gateway_CreateBasePathMapping_cli_2_topic"></a>

次のコード例では、`create-base-path-mapping` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名のベースパスマッピングを取得する方法**  
コマンド:  

```
aws apigateway create-base-path-mapping --domain-name subdomain.domain.tld --rest-api-id 1234123412 --stage prod --base-path v1
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBasePathMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-base-path-mapping.html)」を参照してください。

### `create-deployment`
<a name="api-gateway_CreateDeployment_cli_2_topic"></a>

次のコード例では、`create-deployment` を使用する方法を示しています。

**AWS CLI**  
**API に設定したリソースを新しいステージにデプロイする方法**  
コマンド:  

```
aws apigateway create-deployment --rest-api-id 1234123412 --stage-name dev --stage-description 'Development Stage' --description 'First deployment to the dev stage'
```
**API に設定したリソースを既存のステージにデプロイする方法**  
コマンド:  

```
aws apigateway create-deployment --rest-api-id 1234123412 --stage-name dev --description 'Second deployment to the dev stage'
```
**ステージ変数を使用して、API に設定したリソースを既存のステージにデプロイする方法**  
aws apigateway create-deployment --rest-api-id 1234123412 --stage-name dev --description 'Third deployment to the dev stage' --variables key='value',otherKey='otherValue'  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-deployment.html)」を参照してください。**

### `create-domain-name-access-association`
<a name="api-gateway_CreateDomainNameAccessAssociation_cli_2_topic"></a>

次のコード例は、`create-domain-name-access-association` を使用する方法を示しています。

**AWS CLI**  
**ドメイン名アクセスの関連付けを作成するには**  
次の `create-domain-name-access-association` の例では、プライベートカスタムドメイン名と VPC エンドポイントとの間にドメイン名アクセスの関連付けを作成します。  

```
aws apigateway create-domain-name-access-association \
    --domain-name-arn arn:aws:apigateway:us-west-2:111122223333:/domainnames/my.private.domain.tld+abcd1234 \
    --access-association-source vpce-abcd1234efg \
    --access-association-source-type VPCE
```
出力:  

```
{
    "domainNameAccessAssociationArn": "arn:aws:apigateway:us-west-2:012345678910:/domainnameaccessassociations/domainname/my.private.domain.tld/vpcesource/vpce-abcd1234efg
    "accessAssociationSource": "vpce-abcd1234efg",
    "accessAssociationSourceType": "VPCE",
    "domainNameArn" : "arn:aws:apigateway:us-west-2:111122223333:/domainnames/private.example.com+abcd1234"
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateDomainNameAccessAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-domain-name-access-association.html)」を参照してください。

### `create-domain-name`
<a name="api-gateway_CreateDomainName_cli_2_topic"></a>

次のコード例は、`create-domain-name` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックカスタムドメイン名を作成するには**  
次の `create-domain-name` の例では、パブリックカスタムドメイン名を作成します。  

```
aws apigateway create-domain-name \
    --domain-name 'my.domain.tld' \
    --certificate-name 'my.domain.tld cert'\
    --certificate-arn 'arn:aws:acm:us-east-1:012345678910:certificate/fb1b9770-a305-495d-aefb-27e5e101ff3'
```
出力:  

```
{
    "domainName": "my.domain.tld",
    "certificateName": "my.domain.tld cert",
    "certificateArn": "arn:aws:acm:us-east-1:012345678910:certificate/fb1b9770-a305-495d-aefb-27e5e101ff3",
    "certificateUploadDate": "2024-10-08T11:29:49-07:00",
    "distributionDomainName": "abcd1234.cloudfront.net",
    "distributionHostedZoneId": "Z2FDTNDATAQYW2",
    "endpointConfiguration": {
        "types": [
            "EDGE"
        ]
    },
    "domainNameStatus": "AVAILABLE",
    "securityPolicy": "TLS_1_2"
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのパブリック REST API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html)」を参照してください。  
**例 2: プライベートカスタムドメイン名を作成するには**  
次の `create-domain-name` の例では、プライベートカスタムドメイン名を作成します。  

```
aws apigateway create-domain-name \
    --domain-name 'my.private.domain.tld' \
    --certificate-name 'my.domain.tld cert' \
    --certificate-arn 'arn:aws:acm:us-east-1:012345678910:certificate/fb1b9770-a305-495d-aefb-27e5e101ff3' \
    --endpoint-configuration '{"types": ["PRIVATE"]}' \
    --security-policy 'TLS_1_2' \
    --policy file://policy.json
```
`policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ]
        },
        {
            "Effect": "Deny",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": [
                "execute-api:/*"
            ],
            "Condition" : {
                "StringNotEquals": {
                    "aws:SourceVpce": "vpce-abcd1234efg"
                }
            }
        }
    ]
}
```
出力:  

```
{
    "domainName": "my.private.domain.tld",
    "domainNameId": "abcd1234",
    "domainNameArn": "arn:aws:apigateway:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234",
    "certificateArn": "arn:aws:acm:us-east-1:012345678910:certificate/fb1b9770-a305-495d-aefb-27e5e101ff3",
    "certificateUploadDate": "2024-09-10T10:31:20-07:00",
    "endpointConfiguration": {
        "types": [
            "PRIVATE"
        ]
    },
    "domainNameStatus": "AVAILABLE",
    "securityPolicy": "TLS_1_2",
    "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"execute-api:Invoke\",\"Resource\":\"arn:aws:execute-api:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234\"},{\"Effect\":\"Deny\",\"Principal\":\"*\",\"Action\":\"execute-api:Invoke\",\"Resource\":\"arn:aws:execute-api:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234\",\"Condition\":{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-1a2b3c4d\"}}}]}"
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのパブリック REST API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-domain-name.html)」を参照してください。

### `create-model`
<a name="api-gateway_CreateModel_cli_2_topic"></a>

次のコード例では、`create-model` を使用する方法を示しています。

**AWS CLI**  
**API 用のモデルを作成する方法**  
コマンド:  

```
aws apigateway create-model --rest-api-id 1234123412 --name 'firstModel' --description 'The First Model' --content-type 'application/json'  --schema '{ "$schema": "http://json-schema.org/draft-04/schema#", "title": "firstModel", "type": "object", "properties": { "firstProperty" : { "type": "object", "properties": { "key": { "type": "string" } } } } }'
```
出力:  

```
{
    "contentType": "application/json",
    "description": "The First Model",
    "name": "firstModel",
    "id": "2rzg0l",
    "schema": "{ \"$schema\": \"http://json-schema.org/draft-04/schema#\", \"title\": \"firstModel\", \"type\": \"object\", \"properties\": { \"firstProperty\" : { \"type\": \"object\", \"properties\": { \"key\": { \"type\": \"string\" } } } } }"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-model.html)」を参照してください。

### `create-resource`
<a name="api-gateway_CreateResource_cli_2_topic"></a>

次のコード例では、`create-resource` を使用する方法を示しています。

**AWS CLI**  
**API でリソースを作成する方法**  
コマンド:  

```
aws apigateway create-resource --rest-api-id 1234123412 --parent-id a1b2c3 --path-part 'new-resource'
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-resource.html)」を参照してください。**

### `create-rest-api`
<a name="api-gateway_CreateRestApi_cli_2_topic"></a>

次のコード例では、`create-rest-api` を使用する方法を示しています。

**AWS CLI**  
**API を作成する方法**  
コマンド:  

```
aws apigateway create-rest-api --name 'My First API' --description 'This is my first API'
```
**既存の API から複製 API を作成する方法**  
コマンド:  

```
aws apigateway create-rest-api --name 'Copy of My First API' --description 'This is a copy of my first API' --clone-from 1234123412
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateRestApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-rest-api.html)」を参照してください。**

### `create-stage`
<a name="api-gateway_CreateStage_cli_2_topic"></a>

次のコード例では、`create-stage` を使用する方法を示しています。

**AWS CLI**  
**既存のデプロイを含む API にステージを作成する方法**  
コマンド:  

```
aws apigateway create-stage --rest-api-id 1234123412 --stage-name 'dev' --description 'Development stage' --deployment-id a1b2c3
```
**既存のデプロイとカスタムステージ変数を含む API でステージを作成する方法**  
コマンド:  

```
aws apigateway create-stage --rest-api-id 1234123412 --stage-name 'dev' --description 'Development stage' --deployment-id a1b2c3 --variables key='value',otherKey='otherValue'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-stage.html)」を参照してください。

### `create-usage-plan-key`
<a name="api-gateway_CreateUsagePlanKey_cli_2_topic"></a>

次のコード例では、`create-usage-plan-key` を使用する方法を示しています。

**AWS CLI**  
**既存の API キーを使用量プランに関連付ける**  
コマンド:  

```
aws apigateway create-usage-plan-key --usage-plan-id a1b2c3 --key-type "API_KEY" --key-id 4vq3yryqm5
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUsagePlanKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-usage-plan-key.html)」を参照してください。

### `create-usage-plan`
<a name="api-gateway_CreateUsagePlan_cli_2_topic"></a>

次のコード例では、`create-usage-plan` を使用する方法を示しています。

**AWS CLI**  
**月の初めにリセットされるスロットルとクォータの制限を使用して使用量プランを作成する方法**  
コマンド:  

```
aws apigateway create-usage-plan --name "New Usage Plan" --description "A new usage plan" --throttle burstLimit=10,rateLimit=5 --quota limit=500,offset=0,period=MONTH
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUsagePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/create-usage-plan.html)」を参照してください。

### `delete-api-key`
<a name="api-gateway_DeleteApiKey_cli_2_topic"></a>

次のコード例では、`delete-api-key` を使用する方法を示しています。

**AWS CLI**  
**API キーを削除する方法**  
コマンド:  

```
aws apigateway delete-api-key --api-key 8bklk8bl1k3sB38D9B3l0enyWT8c09B30lkq0blk
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApiKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-api-key.html)」を参照してください。

### `delete-authorizer`
<a name="api-gateway_DeleteAuthorizer_cli_2_topic"></a>

次のコード例では、`delete-authorizer` を使用する方法を示しています。

**AWS CLI**  
**API でカスタムオーソライザーを削除する方法**  
コマンド:  

```
aws apigateway delete-authorizer --rest-api-id 1234123412 --authorizer-id 7gkfbo
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-authorizer.html)」を参照してください。

### `delete-base-path-mapping`
<a name="api-gateway_DeleteBasePathMapping_cli_2_topic"></a>

次のコード例では、`delete-base-path-mapping` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名のベースパスマッピングを削除する方法**  
コマンド:  

```
aws apigateway delete-base-path-mapping --domain-name 'api.domain.tld' --base-path 'dev'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBasePathMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-base-path-mapping.html)」を参照してください。

### `delete-client-certificate`
<a name="api-gateway_DeleteClientCertificate_cli_2_topic"></a>

次のコード例では、`delete-client-certificate` を使用する方法を示しています。

**AWS CLI**  
**クライアント証明書を削除する方法**  
コマンド:  

```
aws apigateway delete-client-certificate --client-certificate-id a1b2c3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteClientCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-client-certificate.html)」を参照してください。

### `delete-deployment`
<a name="api-gateway_DeleteDeployment_cli_2_topic"></a>

次のコード例では、`delete-deployment` を使用する方法を示しています。

**AWS CLI**  
**API のデプロイを削除する方法**  
コマンド:  

```
aws apigateway delete-deployment --rest-api-id 1234123412 --deployment-id a1b2c3
```
+  API の詳細については、 コマンドリファレンスAWS CLI の「[DeleteDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-deployment.html)」を参照してください。**

### `delete-domain-name-access-association`
<a name="api-gateway_DeleteDomainNameAccessAssociation_cli_2_topic"></a>

次のコード例は、`delete-domain-name-access-association` を使用する方法を示しています。

**AWS CLI**  
**ドメイン名アクセスの関連付けを削除するには**  
次の `delete-domain-name-access-association` の例では、プライベートカスタムドメイン名と VPC エンドポイントとの間のドメイン名アクセスの関連付けを削除します。  

```
aws apigateway delete-domain-name-access-association \
    --domain-name-access-association-arn arn:aws:apigateway:us-west-2:012345678910:/domainnameaccessassociations/domainname/my.private.domain.tld/vpcesource/vpce-abcd1234efg
```
このコマンドでは何も出力されません。  
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteDomainNameAccessAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-domain-name-access-association.html)」を参照してください。

### `delete-domain-name`
<a name="api-gateway_DeleteDomainName_cli_2_topic"></a>

次のコード例は、`delete-domain-name` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名を削除する方法**  
コマンド:  

```
aws apigateway delete-domain-name --domain-name 'api.domain.tld'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-domain-name.html)」を参照してください。

### `delete-integration-response`
<a name="api-gateway_DeleteIntegrationResponse_cli_2_topic"></a>

次のコード例では、`delete-integration-response` を使用する方法を示しています。

**AWS CLI**  
**API で特定のリソース、メソッド、ステータスコードの統合レスポンスを削除する方法**  
コマンド:  

```
aws apigateway delete-integration-response --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --status-code 200
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIntegrationResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-integration-response.html)」を参照してください。

### `delete-integration`
<a name="api-gateway_DeleteIntegration_cli_2_topic"></a>

次のコード例では、`delete-integration` を使用する方法を示しています。

**AWS CLI**  
**API で特定のリソースとメソッドの統合を削除する方法**  
コマンド:  

```
aws apigateway delete-integration --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-integration.html)」を参照してください。

### `delete-method-response`
<a name="api-gateway_DeleteMethodResponse_cli_2_topic"></a>

次のコード例では、`delete-method-response` を使用する方法を示しています。

**AWS CLI**  
**API で特定のリソース、メソッド、ステータスコードのメソッドレスポンスを削除する方法**  
コマンド:  

```
aws apigateway delete-method-response --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --status-code 200
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMethodResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-method-response.html)」を参照してください。

### `delete-method`
<a name="api-gateway_DeleteMethod_cli_2_topic"></a>

次のコード例では、`delete-method` を使用する方法を示しています。

**AWS CLI**  
**API で特定のリソースのメソッドを削除する方法**  
コマンド:  

```
aws apigateway delete-method --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMethod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-method.html)」を参照してください。

### `delete-model`
<a name="api-gateway_DeleteModel_cli_2_topic"></a>

次のコード例では、`delete-model` を使用する方法を示しています。

**AWS CLI**  
**特定の API でモデルを削除する方法**  
コマンド:  

```
aws apigateway delete-model --rest-api-id 1234123412 --model-name 'customModel'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-model.html)」を参照してください。

### `delete-resource`
<a name="api-gateway_DeleteResource_cli_2_topic"></a>

次のコード例では、`delete-resource` を使用する方法を示しています。

**AWS CLI**  
**API でリソースを削除する方法**  
コマンド:  

```
aws apigateway delete-resource --rest-api-id 1234123412 --resource-id a1b2c3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-resource.html)」を参照してください。

### `delete-rest-api`
<a name="api-gateway_DeleteRestApi_cli_2_topic"></a>

次のコード例では、`delete-rest-api` を使用する方法を示しています。

**AWS CLI**  
**API を削除する方法**  
コマンド:  

```
aws apigateway delete-rest-api --rest-api-id 1234123412
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteRestApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-rest-api.html)」を参照してください。**

### `delete-stage`
<a name="api-gateway_DeleteStage_cli_2_topic"></a>

次のコード例では、`delete-stage` を使用する方法を示しています。

**AWS CLI**  
**API でインスタンスを削除する方法**  
コマンド:  

```
aws apigateway delete-stage --rest-api-id 1234123412 --stage-name 'dev'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-stage.html)」を参照してください。

### `delete-usage-plan-key`
<a name="api-gateway_DeleteUsagePlanKey_cli_2_topic"></a>

次のコード例では、`delete-usage-plan-key` を使用する方法を示しています。

**AWS CLI**  
**使用量プランから API キーを削除する方法**  
コマンド:  

```
aws apigateway delete-usage-plan-key --usage-plan-id a1b2c3 --key-id 1NbjQzMReAkeEQPNAW8r3dXsU2rDD7fc7f2Sipnu
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUsagePlanKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-usage-plan-key.html)」を参照してください。

### `delete-usage-plan`
<a name="api-gateway_DeleteUsagePlan_cli_2_topic"></a>

次のコード例では、`delete-usage-plan` を使用する方法を示しています。

**AWS CLI**  
**使用量プランを削除する方法**  
コマンド:  

```
aws apigateway delete-usage-plan --usage-plan-id a1b2c3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUsagePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/delete-usage-plan.html)」を参照してください。

### `flush-stage-authorizers-cache`
<a name="api-gateway_FlushStageAuthorizersCache_cli_2_topic"></a>

次のコード例では、`flush-stage-authorizers-cache` を使用する方法を示しています。

**AWS CLI**  
**ステージのすべてのオーソライザーキャッシュエントリをすべて消去する方法**  
コマンド:  

```
aws apigateway flush-stage-authorizers-cache --rest-api-id 1234123412 --stage-name dev
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[FlushStageAuthorizersCache](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/flush-stage-authorizers-cache.html)」を参照してください。

### `flush-stage-cache`
<a name="api-gateway_FlushStageCache_cli_2_topic"></a>

次のコード例では、`flush-stage-cache` を使用する方法を示しています。

**AWS CLI**  
**API のステージのキャッシュをすべて消去する方法**  
次の `flush-stage-cache` の例では、ステージのキャッシュをフラッシュします。  

```
aws apigateway flush-stage-cache \
    --rest-api-id 1234123412 \
    --stage-name dev
```
このコマンドでは何も出力されません。  
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway での API ステージキャッシュをフラッシュする](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-caching.html#flush-api-caching)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[FlushStageCache](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/flush-stage-cache.html)」を参照してください。

### `generate-client-certificate`
<a name="api-gateway_GenerateClientCertificate_cli_2_topic"></a>

次のコード例では、`generate-client-certificate` を使用する方法を示しています。

**AWS CLI**  
**クライアント側 SSL 証明書を作成する方法**  
コマンド:  

```
aws apigateway generate-client-certificate --description 'My First Client Certificate'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateClientCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/generate-client-certificate.html)」を参照してください。

### `get-account`
<a name="api-gateway_GetAccount_cli_2_topic"></a>

次のコード例では、`get-account` を使用する方法を示しています。

**AWS CLI**  
**API Gateway アカウント設定を取得する方法**  
コマンド:  

```
aws apigateway get-account
```
出力:  

```
{
    "cloudwatchRoleArn": "arn:aws:iam::123412341234:role/APIGatewayToCloudWatchLogsRole",
    "throttleSettings": {
        "rateLimit": 500.0,
        "burstLimit": 1000
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-account.html)」を参照してください。

### `get-api-key`
<a name="api-gateway_GetApiKey_cli_2_topic"></a>

次のコード例では、`get-api-key` を使用する方法を示しています。

**AWS CLI**  
**特定の API に関する情報を取得する方法**  
コマンド:  

```
aws apigateway get-api-key --api-key 8bklk8bl1k3sB38D9B3l0enyWT8c09B30lkq0blk
```
出力:  

```
{
    "description": "My first key",
    "enabled": true,
    "stageKeys": [
        "a1b2c3d4e5/dev",
        "e5d4c3b2a1/dev"
    ],
    "lastUpdatedDate": 1456184515,
    "createdDate": 1456184452,
    "id": "8bklk8bl1k3sB38D9B3l0enyWT8c09B30lkq0blk",
    "name": "My key"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApiKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-api-key.html)」を参照してください。

### `get-api-keys`
<a name="api-gateway_GetApiKeys_cli_2_topic"></a>

次のコード例では、`get-api-keys` を使用する方法を示しています。

**AWS CLI**  
**API キーの一覧を取得する方法**  
コマンド:  

```
aws apigateway get-api-keys
```
出力:  

```
{
    "items": [
        {
            "description": "My first key",
            "enabled": true,
            "stageKeys": [
                "a1b2c3d4e5/dev",
                "e5d4c3b2a1/dev"
            ],
            "lastUpdatedDate": 1456184515,
            "createdDate": 1456184452,
            "id": "8bklk8bl1k3sB38D9B3l0enyWT8c09B30lkq0blk",
            "name": "My key"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApiKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-api-keys.html)」を参照してください。

### `get-authorizer`
<a name="api-gateway_GetAuthorizer_cli_2_topic"></a>

次のコード例では、`get-authorizer` を使用する方法を示しています。

**AWS CLI**  
**API Gateway per-API Authorizer 設定を取得する方法**  
コマンド:  

```
aws apigateway get-authorizer --rest-api-id 1234123412 --authorizer-id gfi4n3
```
出力:  

```
{
    "authorizerResultTtlInSeconds": 300,
    "name": "MyAuthorizer",
    "type": "TOKEN",
    "identitySource": "method.request.header.Authorization",
    "authorizerUri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:authorizer_function/invocations",
    "id": "gfi4n3"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-authorizer.html)」を参照してください。

### `get-authorizers`
<a name="api-gateway_GetAuthorizers_cli_2_topic"></a>

次のコード例では、`get-authorizers` を使用する方法を示しています。

**AWS CLI**  
**REST API のオーソライザーの一覧を取得する方法**  
コマンド:  

```
aws apigateway get-authorizers --rest-api-id 1234123412
```
出力:  

```
{
    "items": [
        {
            "name": "MyAuthorizer",
            "authorizerUri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:My_Authorizer_Function/invocations",
            "authorizerResultTtlInSeconds": 300,
            "identitySource": "method.request.header.Authorization",
            "type": "TOKEN",
            "id": "gfi4n3"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthorizers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-authorizers.html)」を参照してください。

### `get-base-path-mapping`
<a name="api-gateway_GetBasePathMapping_cli_2_topic"></a>

次のコード例では、`get-base-path-mapping` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名のベースパスマッピングを取得する方法**  
コマンド:  

```
aws apigateway get-base-path-mapping --domain-name subdomain.domain.tld --base-path v1
```
出力:  

```
{
    "basePath": "v1",
    "restApiId": "1234w4321e",
    "stage": "api"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetBasePathMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-base-path-mapping.html)」を参照してください。**

### `get-base-path-mappings`
<a name="api-gateway_GetBasePathMappings_cli_2_topic"></a>

次のコード例では、`get-base-path-mappings` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名のベースパスマッピングを取得する方法**  
コマンド:  

```
aws apigateway get-base-path-mappings --domain-name subdomain.domain.tld
```
出力:  

```
{
    "items": [
        {
            "basePath": "(none)",
            "restApiId": "1234w4321e",
            "stage": "dev"
        },
        {
            "basePath": "v1",
            "restApiId": "1234w4321e",
            "stage": "api"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBasePathMappings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-base-path-mappings.html)」を参照してください。

### `get-client-certificate`
<a name="api-gateway_GetClientCertificate_cli_2_topic"></a>

次のコード例では、`get-client-certificate` を使用する方法を示しています。

**AWS CLI**  
**クライアント証明書を取得する方法**  
コマンド:  

```
aws apigateway get-client-certificate --client-certificate-id a1b2c3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetClientCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-client-certificate.html)」を参照してください。

### `get-client-certificates`
<a name="api-gateway_GetClientCertificates_cli_2_topic"></a>

次のコード例では、`get-client-certificates` を使用する方法を示しています。

**AWS CLI**  
**クライアント証明書の一覧を取得する方法**  
コマンド:  

```
aws apigateway get-client-certificates
```
出力:  

```
{
    "items": [
        {
            "pemEncodedCertificate": "-----BEGIN CERTIFICATE----- <certificate content> -----END CERTIFICATE-----",
            "clientCertificateId": "a1b2c3",
            "expirationDate": 1483556561,
            "description": "My Client Certificate",
            "createdDate": 1452020561
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetClientCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-client-certificates.html)」を参照してください。

### `get-deployment`
<a name="api-gateway_GetDeployment_cli_2_topic"></a>

次のコード例では、`get-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイの情報を取得する方法**  
コマンド:  

```
aws apigateway get-deployment --rest-api-id 1234123412 --deployment-id ztt4m2
```
出力:  

```
{
    "description": "myDeployment",
    "id": "ztt4m2",
    "createdDate": 1455218022
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-deployment.html)」を参照してください。

### `get-deployments`
<a name="api-gateway_GetDeployments_cli_2_topic"></a>

次のコード例では、`get-deployments` を使用する方法を示しています。

**AWS CLI**  
**REST API のデプロイの一覧を取得する方法**  
コマンド:  

```
aws apigateway get-deployments --rest-api-id 1234123412
```
出力:  

```
{
    "items": [
        {
            "createdDate": 1453797217,
            "id": "0a2b4c",
            "description": "Deployed my API for the first time"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-deployments.html)」を参照してください。

### `get-domain-name-access-associations`
<a name="api-gateway_GetDomainNameAccessAssociations_cli_2_topic"></a>

次のコード例は、`get-domain-name-access-associations` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのドメイン名アクセスの関連付けを一覧表示するには**  
次の `get-domain-name-access-associations` の例では、すべてのドメイン名アクセスの関連付けを一覧表示します。  

```
aws apigateway get-domain-name-access-associations
```
出力:  

```
{
    "items": [
        {
        "domainNameAccessAssociationArn": "arn:aws:apigateway:us-west-2:012345678910:/domainnameaccessassociations/domainname/my.private.domain.tld/vpcesource/vpce-abcd1234efg
        "accessAssociationSource": "vpce-abcd1234efg",
        "accessAssociationSourceType": "VPCE",
        "domainNameArn" : "arn:aws:apigateway:us-west-2:111122223333:/domainnames/private.example.com+abcd1234"
        }
    ]
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
**例 2: この AWS アカウントが所有するすべてのドメイン名アクセスの関連付けを一覧表示するには**  
次の の`get-domain-name-access-associations`例では、現在の AWS アカウントが所有するすべてのドメイン名アクセスの関連付けを一覧表示します。  

```
aws apigateway get-domain-name-access-associations \
    --resource-owner SELF
```
出力:  

```
{
    "items": [
        {
        "domainNameAccessAssociationArn": "arn:aws:apigateway:us-west-2:012345678910:/domainnameaccessassociations/domainname/my.private.domain.tld/vpcesource/vpce-abcd1234efg
        "accessAssociationSource": "vpce-abcd1234efg",
        "accessAssociationSourceType": "VPCE",
        "domainNameArn" : "arn:aws:apigateway:us-west-2:111122223333:/domainnames/private.example.com+abcd1234"
        }
    ]
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetDomainNameAccessAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-domain-name-access-associations.html)」を参照してください。

### `get-domain-name`
<a name="api-gateway_GetDomainName_cli_2_topic"></a>

次のコード例は、`get-domain-name` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックカスタムドメイン名に関する情報を取得するには**  
次の `get-domain-name` の例では、パブリックカスタムドメイン名に関する情報を取得します。  

```
aws apigateway get-domain-name \
    --domain-name api.domain.tld
```
出力:  

```
{
    "domainName": "api.domain.tld",
    "distributionDomainName": "d1a2f3a4c5o6d.cloudfront.net",
    "certificateName": "uploadedCertificate",
    "certificateUploadDate": 1462565487
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのパブリック REST API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html)」を参照してください。  
**例 2: プライベートカスタムドメイン名に関する情報を取得するには**  
次の `get-domain-name` の例では、プライベートカスタムドメイン名に関する情報を取得します。  

```
aws apigateway get-domain-name \
    --domain-name api.private.domain.tld \
    --domain-name-id abcd1234
```
出力:  

```
{
    "domainName": "my.private.domain.tld",
    "domainNameId": "abcd1234",
    "domainNameArn": "arn:aws:apigateway:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234",
    "certificateArn": "arn:aws:acm:us-east-1:012345678910:certificate/fb1b9770-a305-495d-aefb-27e5e101ff3",
    "certificateUploadDate": "2024-09-10T10:31:20-07:00",
    "endpointConfiguration": {
        "types": [
            "PRIVATE"
        ]
    },
    "domainNameStatus": "AVAILABLE",
    "securityPolicy": "TLS_1_2",
    "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"execute-api:Invoke\",\"Resource\":\"arn:aws:execute-api:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234\"},{\"Effect\":\"Deny\",\"Principal\":\"*\",\"Action\":\"execute-api:Invoke\",\"Resource\":\"arn:aws:execute-api:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234\",\"Condition\":{\"StringNotEquals\":{\"aws:SourceVpc\":\"vpc-1a2b3c4d\"}}}]}"
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのパブリック REST API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-domain-name.html)」を参照してください。

### `get-domain-names`
<a name="api-gateway_GetDomainNames_cli_2_topic"></a>

次のコード例は、`get-domain-names` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムドメイン名のリストを取得するには**  
次の `get-domain-names` コマンドは、ドメイン名のリストを取得します。  

```
aws apigateway get-domain-names
```
出力:  

```
{
    "items": [
        {
            "distributionDomainName": "d9511k3l09bkd.cloudfront.net",
            "certificateUploadDate": 1452812505,
            "certificateName": "my_custom_domain-certificate",
            "domainName": "subdomain.domain.tld"
        }
    ]
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
**例 2: この AWS アカウントが所有するカスタムドメイン名のリストを取得するには**  
次の`get-domain-names`コマンドは、この AWS アカウントが所有するドメイン名のリストを取得します。  

```
aws apigateway get-domain-names \
    --resource-owner SELF
```
出力:  

```
{
    "items": [
        {
            "domainName": "my.domain.tld",
            "domainNameArn": "arn:aws:apigateway:us-east-1::/domainnames/my.private.domain.tld",
            "certificateUploadDate": "2024-08-15T17:02:55-07:00",
            "regionalDomainName": "d-abcd1234.execute-api.us-east-1.amazonaws.com",
            "regionalHostedZoneId": "Z1UJRXOUMOOFQ8",
            "regionalCertificateArn": "arn:aws:acm:us-east-1:012345678910:certificate/fb1b9770-a305-495d-aefb-27e5e101ff3",
            "endpointConfiguration": {
                "types": [
                    "REGIONAL"
                ]
            },
            "domainNameStatus": "AVAILABLE",
            "securityPolicy": "TLS_1_2"
        },
        {
            "domainName": "my.private.domain.tld",
            "domainNameId": "abcd1234",
            "domainNameArn": "arn:aws:apigateway:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234",
            "certificateArn": "arn:aws:acm:us-east-1:012345678910:certificate/fb1b9770-a305-495d-aefb-27e5e101ff3",
            "certificateUploadDate": "2024-11-26T11:44:40-08:00",
            "endpointConfiguration": {
                "types": [
                    "PRIVATE"
                ]
            },
            "domainNameStatus": "AVAILABLE",
            "securityPolicy": "TLS_1_2"
        }
    ]
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
**例 3: ドメイン名アクセスの関連付けを作成できる他の AWS アカウントが所有するカスタムドメイン名のリストを取得するには。**  
次の`get-domain-names`コマンドは、ドメイン名アクセスの関連付けを作成するためにアクセスできる他の AWS アカウントが所有するドメイン名のリストを取得します。  

```
aws apigateway get-domain-names \
    --resource-owner OTHER_ACCOUNTS
```
出力:  

```
{
    "items": [
        {
            "domainName": "my.private.domain.tld",
            "domainNameId": "abcd1234",
            "domainNameArn": "arn:aws:apigateway:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234"
        }
    ]
}
```
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomainNames](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-domain-names.html)」を参照してください。

### `get-export`
<a name="api-gateway_GetExport_cli_2_topic"></a>

次のコード例では、`get-export` を使用する方法を示しています。

**AWS CLI**  
**ステージの JSON Swagger テンプレートを取得するには**  
コマンド:  

```
aws apigateway get-export --rest-api-id a1b2c3d4e5 --stage-name dev --export-type swagger /path/to/filename.json
```
**ステージの JSON Swagger テンプレート \$1 API Gateway Extentions を取得する方法**  
コマンド:  

```
aws apigateway get-export --parameters extensions='integrations' --rest-api-id a1b2c3d4e5 --stage-name dev --export-type swagger /path/to/filename.json
```
**ステージの JSON Swagger テンプレート \$1 Postman Extensions を取得する方法**  
コマンド:  

```
aws apigateway get-export --parameters extensions='postman' --rest-api-id a1b2c3d4e5 --stage-name dev --export-type swagger /path/to/filename.json
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetExport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-export.html)」を参照してください。

### `get-integration-response`
<a name="api-gateway_GetIntegrationResponse_cli_2_topic"></a>

次のコード例では、`get-integration-response` を使用する方法を示しています。

**AWS CLI**  
**REST API のリソースで定義された HTTP メソッドの統合レスポンス構成を取得する方法**  
コマンド:  

```
aws apigateway get-integration-response --rest-api-id 1234123412 --resource-id y9h6rt --http-method GET --status-code 200
```
出力:  

```
{
    "statusCode": "200",
    "responseTemplates": {
        "application/json": null
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIntegrationResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-integration-response.html)」を参照してください。

### `get-integration`
<a name="api-gateway_GetIntegration_cli_2_topic"></a>

次のコード例では、`get-integration` を使用する方法を示しています。

**AWS CLI**  
**REST API のリソースで定義された HTTP メソッドの統合構成を取得する方法**  
コマンド:  

```
aws apigateway get-integration --rest-api-id 1234123412 --resource-id y9h6rt --http-method GET
```
出力:  

```
{
    "httpMethod": "POST",
    "integrationResponses": {
        "200": {
            "responseTemplates": {
                "application/json": null
            },
            "statusCode": "200"
        }
    },
    "cacheKeyParameters": [],
    "type": "AWS",
    "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:My_Function/invocations",
    "cacheNamespace": "y9h6rt"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-integration.html)」を参照してください。

### `get-method-response`
<a name="api-gateway_GetMethodResponse_cli_2_topic"></a>

次のコード例では、`get-method-response` を使用する方法を示しています。

**AWS CLI**  
**REST API のリソースで定義された HTTP メソッドのメソッドレスポンスリソース構成を取得する方法**  
コマンド:  

```
aws apigateway get-method-response --rest-api-id 1234123412 --resource-id y9h6rt --http-method GET --status-code 200
```
出力:  

```
{
    "responseModels": {
        "application/json": "Empty"
    },
    "statusCode": "200"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMethodResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-method-response.html)」を参照してください。

### `get-method`
<a name="api-gateway_GetMethod_cli_2_topic"></a>

次のコード例では、`get-method` を使用する方法を示しています。

**AWS CLI**  
**REST API のリソースで定義された HTTP メソッドのメソッドリソース構成を取得する方法**  
コマンド:  

```
aws apigateway get-method --rest-api-id 1234123412 --resource-id y9h6rt --http-method GET
```
出力:  

```
{
    "apiKeyRequired": false,
    "httpMethod": "GET",
    "methodIntegration": {
        "integrationResponses": {
            "200": {
                "responseTemplates": {
                    "application/json": null
                },
                "statusCode": "200"
            }
        },
        "cacheKeyParameters": [],
        "uri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:My_Function/invocations",
        "httpMethod": "POST",
        "cacheNamespace": "y9h6rt",
        "type": "AWS"
    },
    "requestParameters": {},
    "methodResponses": {
        "200": {
            "responseModels": {
                "application/json": "Empty"
            },
            "statusCode": "200"
        }
    },
    "authorizationType": "NONE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMethod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-method.html)」を参照してください。

### `get-model-template`
<a name="api-gateway_GetModelTemplate_cli_2_topic"></a>

次のコード例では、`get-model-template` を使用する方法を示しています。

**AWS CLI**  
**REST API で定義されたモデルのマッピングテンプレートを取得する方法**  
コマンド:  

```
aws apigateway get-model-template --rest-api-id 1234123412 --model-name Empty
```
出力:  

```
{
    "value": "#set($inputRoot = $input.path('$'))\n{ }"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetModelTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-model-template.html)」を参照してください。

### `get-model`
<a name="api-gateway_GetModel_cli_2_topic"></a>

次のコード例では、`get-model` を使用する方法を示しています。

**AWS CLI**  
**REST API で定義されたモデルの構成を取得する方法**  
コマンド:  

```
aws apigateway get-model --rest-api-id 1234123412 --model-name Empty
```
出力:  

```
{
    "contentType": "application/json",
    "description": "This is a default empty schema model",
    "name": "Empty",
    "id": "etd5w5",
    "schema": "{\n  \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n  \"title\" : \"Empty Schema\",\n  \"type\" : \"object\"\n}"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-model.html)」を参照してください。

### `get-models`
<a name="api-gateway_GetModels_cli_2_topic"></a>

次のコード例では、`get-models` を使用する方法を示しています。

**AWS CLI**  
**REST API のリソースの一覧を取得する方法**  
コマンド:  

```
aws apigateway get-models --rest-api-id 1234123412
```
出力:  

```
{
    "items": [
        {
            "description": "This is a default error schema model",
            "schema": "{\n  \"$schema\" : \"http://json-schema.org/draft-04/schema#\",\n  \"title\" : \"Error Schema\",\n  \"type\" : \"object\",\n  \"properties\" : {\n    \"message\" : { \"type\" : \"string\" }\n  }\n}",
            "contentType": "application/json",
            "id": "7tpbze",
            "name": "Error"
        },
        {
            "description": "This is a default empty schema model",
            "schema": "{\n  \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n  \"title\" : \"Empty Schema\",\n  \"type\" : \"object\"\n}",
            "contentType": "application/json",
            "id": "etd5w5",
            "name": "Empty"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetModels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-models.html)」を参照してください。

### `get-resource`
<a name="api-gateway_GetResource_cli_2_topic"></a>

次のコード例では、`get-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに関する情報を取得する方法**  
コマンド:  

```
aws apigateway get-resource --rest-api-id 1234123412 --resource-id zwo0y3
```
出力:  

```
{
    "path": "/path",
    "pathPart": "path",
    "id": "zwo0y3",
    "parentId": "uyokt6ij2g"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-resource.html)」を参照してください。

### `get-resources`
<a name="api-gateway_GetResources_cli_2_topic"></a>

次のコード例では、`get-resources` を使用する方法を示しています。

**AWS CLI**  
**REST API のリソースの一覧を取得する方法**  
コマンド:  

```
aws apigateway get-resources --rest-api-id 1234123412
```
出力:  

```
{
    "items": [
        {
            "path": "/resource/subresource",
            "resourceMethods": {
                "POST": {}
            },
            "id": "024ace",
            "pathPart": "subresource",
            "parentId": "ai5b02"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-resources.html)」を参照してください。**

### `get-rest-api`
<a name="api-gateway_GetRestApi_cli_2_topic"></a>

次のコード例では、`get-rest-api` を使用する方法を示しています。

**AWS CLI**  
**API に関する情報を取得する方法**  
コマンド:  

```
aws apigateway get-rest-api --rest-api-id 1234123412
```
出力:  

```
{
    "name": "myAPI",
    "id": "o1y243m4f5",
    "createdDate": 1453416433
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRestApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-rest-api.html)」を参照してください。

### `get-rest-apis`
<a name="api-gateway_GetRestApis_cli_2_topic"></a>

次のコード例では、`get-rest-apis` を使用する方法を示しています。

**AWS CLI**  
**REST API の一覧を取得する方法**  
コマンド:  

```
aws apigateway get-rest-apis
```
出力:  

```
{
    "items": [
        {
            "createdDate": 1438884790,
            "id": "12s44z21rb",
            "name": "My First API"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetRestApis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-rest-apis.html)」を参照してください。**

### `get-sdk`
<a name="api-gateway_GetSdk_cli_2_topic"></a>

次のコード例では、`get-sdk` を使用する方法を示しています。

**AWS CLI**  
**REST API ステージの Android SDK を取得する方法**  
コマンド:  

```
aws apigateway get-sdk --rest-api-id 1234123412 --stage-name dev --sdk-type android --parameters groupId='com.mycompany',invokerPackage='com.mycompany.clientsdk',artifactId='Mycompany-client',artifactVersion='1.0.0' /path/to/android_sdk.zip
```
出力:  

```
{
    "contentType": "application/octet-stream",
    "contentDisposition": "attachment; filename=\"android_2016-02-22_23-52Z.zip\""
}
```
**REST API ステージの IOS SDK を取得する方法**  
コマンド:  

```
aws apigateway get-sdk --rest-api-id 1234123412 --stage-name dev --sdk-type objectivec --parameters classPrefix='myprefix' /path/to/iOS_sdk.zip
```
出力:  

```
{
    "contentType": "application/octet-stream",
    "contentDisposition": "attachment; filename=\"objectivec_2016-02-22_23-52Z.zip\""
}
```
**REST API ステージの Javascript SDK を取得する方法**  
コマンド:  

```
aws apigateway get-sdk --rest-api-id 1234123412 --stage-name dev --sdk-type javascript /path/to/javascript_sdk.zip
```
出力:  

```
{
    "contentType": "application/octet-stream",
    "contentDisposition": "attachment; filename=\"javascript_2016-02-22_23-52Z.zip\""
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSdk](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-sdk.html)」を参照してください。

### `get-stage`
<a name="api-gateway_GetStage_cli_2_topic"></a>

次のコード例では、`get-stage` を使用する方法を示しています。

**AWS CLI**  
**API のステージに関する情報を取得する方法**  
コマンド:  

```
aws apigateway get-stage --rest-api-id 1234123412 --stage-name dev
```
出力:  

```
{
    "stageName": "dev",
    "cacheClusterSize": "0.5",
    "cacheClusterEnabled": false,
    "cacheClusterStatus": "NOT_AVAILABLE",
    "deploymentId": "rbh1fj",
    "lastUpdatedDate": 1466802961,
    "createdDate": 1460682074,
    "methodSettings": {
        "*/*": {
            "cacheTtlInSeconds": 300,
            "loggingLevel": "INFO",
            "dataTraceEnabled": false,
            "metricsEnabled": true,
            "unauthorizedCacheControlHeaderStrategy": "SUCCEED_WITH_RESPONSE_HEADER",
            "throttlingRateLimit": 500.0,
            "cacheDataEncrypted": false,
            "cachingEnabled": false,
            "throttlingBurstLimit": 1000,
            "requireAuthorizationForCacheControl": true
        },
        "~1resource/GET": {
            "cacheTtlInSeconds": 300,
            "loggingLevel": "INFO",
            "dataTraceEnabled": false,
            "metricsEnabled": true,
            "unauthorizedCacheControlHeaderStrategy": "SUCCEED_WITH_RESPONSE_HEADER",
            "throttlingRateLimit": 500.0,
            "cacheDataEncrypted": false,
            "cachingEnabled": false,
            "throttlingBurstLimit": 1000,
            "requireAuthorizationForCacheControl": true
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-stage.html)」を参照してください。

### `get-stages`
<a name="api-gateway_GetStages_cli_2_topic"></a>

次のコード例では、`get-stages` を使用する方法を示しています。

**AWS CLI**  
**REST API のリソースの一覧を取得する方法**  
コマンド:  

```
aws apigateway get-stages --rest-api-id 1234123412
```
出力:  

```
{
    "item": [
        {
            "stageName": "dev",
            "cacheClusterSize": "0.5",
            "cacheClusterEnabled": true,
            "cacheClusterStatus": "AVAILABLE",
            "deploymentId": "123h64",
            "lastUpdatedDate": 1456185138,
            "createdDate": 1453589092,
            "methodSettings": {
                "~1resource~1subresource/POST": {
                    "cacheTtlInSeconds": 300,
                    "loggingLevel": "INFO",
                    "dataTraceEnabled": true,
                    "metricsEnabled": true,
                    "throttlingRateLimit": 500.0,
                    "cacheDataEncrypted": false,
                    "cachingEnabled": false,
                    "throttlingBurstLimit": 1000
                }
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-stages.html)」を参照してください。

### `get-usage-plan-key`
<a name="api-gateway_GetUsagePlanKey_cli_2_topic"></a>

次のコード例では、`get-usage-plan-key` を使用する方法を示しています。

**AWS CLI**  
**Usage Plan に関連付けられた API キーの詳細を取得する方法**  
コマンド:  

```
aws apigateway get-usage-plan-key --usage-plan-id a1b2c3 --key-id 1NbjQzMReAkeEQPNAW8r3dXsU2rDD7fc7f2Sipnu
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUsagePlanKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-usage-plan-key.html)」を参照してください。

### `get-usage-plan-keys`
<a name="api-gateway_GetUsagePlanKeys_cli_2_topic"></a>

次のコード例では、`get-usage-plan-keys` を使用する方法を示しています。

**AWS CLI**  
**使用量プランに関連付けられた API キーの一覧を取得する方法**  
コマンド:  

```
aws apigateway get-usage-plan-keys --usage-plan-id a1b2c3
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetUsagePlanKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-usage-plan-keys.html)」を参照してください。

### `get-usage-plan`
<a name="api-gateway_GetUsagePlan_cli_2_topic"></a>

次のコード例では、`get-usage-plan` を使用する方法を示しています。

**AWS CLI**  
**使用量プランの詳細を取得する方法**  
コマンド:  

```
aws apigateway get-usage-plan --usage-plan-id a1b2c3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUsagePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-usage-plan.html)」を参照してください。

### `get-usage-plans`
<a name="api-gateway_GetUsagePlans_cli_2_topic"></a>

次のコード例では、`get-usage-plans` を使用する方法を示しています。

**AWS CLI**  
**すべての使用量プランの詳細を取得する方法**  
コマンド:  

```
aws apigateway get-usage-plans
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUsagePlans](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-usage-plans.html)」を参照してください。

### `get-usage`
<a name="api-gateway_GetUsage_cli_2_topic"></a>

次のコード例では、`get-usage` を使用する方法を示しています。

**AWS CLI**  
**使用量プランの使用の詳細を取得する方法**  
コマンド:  

```
aws apigateway get-usage --usage-plan-id a1b2c3 --start-date "2016-08-16" --end-date "2016-08-17"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/get-usage.html)」を参照してください。

### `import-rest-api`
<a name="api-gateway_ImportRestApi_cli_2_topic"></a>

次のコード例では、`import-rest-api` を使用する方法を示しています。

**AWS CLI**  
**Swagger テンプレートをインポートして API を作成する方法**  
コマンド:  

```
aws apigateway import-rest-api --body 'file:///path/to/API_Swagger_template.json'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportRestApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/import-rest-api.html)」を参照してください。

### `put-integration-response`
<a name="api-gateway_PutIntegrationResponse_cli_2_topic"></a>

次のコード例では、`put-integration-response` を使用する方法を示しています。

**AWS CLI**  
**マッピングテンプレートを定義して、統合レスポンスをデフォルトレスポンスとして作成する方法**  
コマンド:  

```
aws apigateway put-integration-response --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --status-code 200 --selection-pattern "" --response-templates '{"application/json": "{\"json\": \"template\"}"}'
```
**regex が 400 でヘッダー値が静的に定義された統合レスポンスを作成する方法**  
コマンド:  

```
aws apigateway put-integration-response --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --status-code 400 --selection-pattern 400 --response-parameters '{"method.response.header.custom-header": "'"'"'custom-value'"'"'"}'
```
+  API の詳細については、**AWS CLI コマンドリファレンスの「[PutIntegrationResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/put-integration-response.html)」を参照してください。

### `put-integration`
<a name="api-gateway_PutIntegration_cli_2_topic"></a>

次のコード例では、`put-integration` を使用する方法を示しています。

**AWS CLI**  
**MOCK 統合リクエストを作成する方法**  
コマンド:  

```
aws apigateway put-integration --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --type MOCK --request-templates '{ "application/json": "{\"statusCode\": 200}" }'
```
**HTTP 統合リクエストを作成する方法**  
コマンド:  

```
aws apigateway put-integration --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --type HTTP --integration-http-method GET --uri 'https://domain.tld/path'
```
**Lambda 関数エンドポイントと AWS の統合リクエストを作成するには**  
コマンド:  

```
aws apigateway put-integration --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --type AWS --integration-http-method POST --uri 'arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:function_name/invocations'
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/put-integration.html)」を参照してください。**

### `put-method-response`
<a name="api-gateway_PutMethodResponse_cli_2_topic"></a>

次のコード例では、`put-method-response` を使用する方法を示しています。

**AWS CLI**  
**カスタムメソッドレスポンスヘッダーを使用して、指定したステータスコードでメソッドレスポンスを作成する方法**  
コマンド:  

```
aws apigateway put-method-response --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --status-code 400 --response-parameters "method.response.header.custom-header=false"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutMethodResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/put-method-response.html)」を参照してください。**

### `put-method`
<a name="api-gateway_PutMethod_cli_2_topic"></a>

次のコード例では、`put-method` を使用する方法を示しています。

**AWS CLI**  
**権限なし、API キーなし、カスタムメソッドリクエストヘッダーありで API 内のリソース用のメソッドを作成する方法**  
コマンド:  

```
aws apigateway put-method --rest-api-id 1234123412 --resource-id a1b2c3 --http-method PUT --authorization-type "NONE" --no-api-key-required --request-parameters "method.request.header.custom-header=false"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutMethod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/put-method.html)」を参照してください。**

### `put-rest-api`
<a name="api-gateway_PutRestApi_cli_2_topic"></a>

次のコード例では、`put-rest-api` を使用する方法を示しています。

**AWS CLI**  
**Swagger テンプレートを使用して既存の API を上書きする方法**  
コマンド:  

```
aws apigateway put-rest-api --rest-api-id 1234123412 --mode overwrite --body 'fileb:///path/to/API_Swagger_template.json'
```
**Swagger テンプレートを既存の API にマージする方法**  
コマンド:  

```
aws apigateway put-rest-api --rest-api-id 1234123412 --mode merge --body 'fileb:///path/to/API_Swagger_template.json'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRestApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/put-rest-api.html)」を参照してください。

### `reject-domain-name-access-association`
<a name="api-gateway_RejectDomainNameAccessAssociation_cli_2_topic"></a>

次のコード例は、`reject-domain-name-access-association` を使用する方法を示しています。

**AWS CLI**  
**ドメイン名アクセスの関連付けを拒否するには**  
次の `reject-domain-name-access-association` の例では、プライベートカスタムドメイン名と VPC エンドポイントとの間のドメイン名アクセスの関連付けを拒否します。  

```
aws apigateway reject-domain-name-access-association \
    --domain-name-access-association-arn arn:aws:apigateway:us-west-2:012345678910:/domainnameaccessassociations/domainname/my.private.domain.tld/vpcesource/vpce-abcd1234efg \
    --domain-name-arn arn:aws:apigateway:us-east-1:012345678910:/domainnames/my.private.domain.tld+abcd1234
```
このコマンドでは何も出力されません。  
詳細については、*Amazon API Gateway デベロッパーガイド*の「[API Gateway でのプライベート API 用のカスタムドメイン名](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-custom-domains.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[RejectDomainNameAccessAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/reject-domain-name-access-association.html)」を参照してください。

### `test-invoke-authorizer`
<a name="api-gateway_TestInvokeAuthorizer_cli_2_topic"></a>

次のコード例は、`test-invoke-authorizer` を使用する方法を示しています。

**AWS CLI**  
**必要なヘッダーと値を含むカスタムオーソライザーへのリクエストをテストする方法**  
コマンド:  

```
aws apigateway test-invoke-authorizer --rest-api-id 1234123412 --authorizer-id 5yid1t --headers Authorization='Value'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestInvokeAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/test-invoke-authorizer.html)」を参照してください。

### `test-invoke-method`
<a name="api-gateway_TestInvokeMethod_cli_2_topic"></a>

次のコード例では、`test-invoke-method` を使用する方法を示しています。

**AWS CLI**  
**GET リクエストを実行して API のルートリソースをテストする方法**  
コマンド:  

```
aws apigateway test-invoke-method --rest-api-id 1234123412 --resource-id avl5sg8fw8 --http-method GET --path-with-query-string '/'
```
**パスパラメータ値を指定して GET リクエストを実行し、API でサブリソースを呼び出すテストをする方法**  
コマンド:  

```
aws apigateway test-invoke-method --rest-api-id 1234123412 --resource-id 3gapai --http-method GET --path-with-query-string '/pets/1'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestInvokeMethod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/test-invoke-method.html)」を参照してください。

### `update-account`
<a name="api-gateway_UpdateAccount_cli_2_topic"></a>

次のコード例では、`update-account` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Logs へのログ記録用の IAM ロール ARN を変更する方法**  
コマンド:  

```
aws apigateway update-account --patch-operations op='replace',path='/cloudwatchRoleArn',value='arn:aws:iam::123412341234:role/APIGatewayToCloudWatchLogs'
```
出力:  

```
{
    "cloudwatchRoleArn": "arn:aws:iam::123412341234:role/APIGatewayToCloudWatchLogs",
    "throttleSettings": {
        "rateLimit": 1000.0,
        "burstLimit": 2000
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-account.html)」を参照してください。

### `update-api-key`
<a name="api-gateway_UpdateApiKey_cli_2_topic"></a>

次のコード例では、`update-api-key` を使用する方法を示しています。

**AWS CLI**  
**API キーの名前を変更する方法**  
コマンド:  

```
aws apigateway update-api-key --api-key sNvjQDMReA1eEQPNAW8r37XsU2rDD7fc7m2SiMnu --patch-operations op='replace',path='/name',value='newName'
```
出力:  

```
{
    "description": "currentDescription",
    "enabled": true,
    "stageKeys": [
        "41t2j324r5/dev"
    ],
    "lastUpdatedDate": 1470086052,
    "createdDate": 1445460347,
    "id": "sNvjQDMReA1vEQPNzW8r3dXsU2rrD7fcjm2SiMnu",
    "name": "newName"
}
```
**API キーを無効にする方法**  
コマンド:  

```
aws apigateway update-api-key --api-key sNvjQDMReA1eEQPNAW8r37XsU2rDD7fc7m2SiMnu --patch-operations op='replace',path='/enabled',value='false'
```
出力:  

```
{
    "description": "currentDescription",
    "enabled": false,
    "stageKeys": [
        "41t2j324r5/dev"
    ],
    "lastUpdatedDate": 1470086052,
    "createdDate": 1445460347,
    "id": "sNvjQDMReA1vEQPNzW8r3dXsU2rrD7fcjm2SiMnu",
    "name": "newName"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApiKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-api-key.html)」を参照してください。

### `update-authorizer`
<a name="api-gateway_UpdateAuthorizer_cli_2_topic"></a>

次のコード例では、`update-authorizer` を使用する方法を示しています。

**AWS CLI**  
**Custom Authorizer の名前を変更する方法**  
コマンド:  

```
aws apigateway update-authorizer --rest-api-id 1234123412 --authorizer-id gfi4n3 --patch-operations op='replace',path='/name',value='testAuthorizer'
```
出力:  

```
{
    "authType": "custom",
    "name": "testAuthorizer",
    "authorizerUri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:customAuthorizer/invocations",
    "authorizerResultTtlInSeconds": 300,
    "identitySource": "method.request.header.Authorization",
    "type": "TOKEN",
    "id": "gfi4n3"
}
```
**カスタムオーソライザーによって呼び出される Lambda 関数を変更する方法**  
コマンド:  

```
aws apigateway update-authorizer --rest-api-id 1234123412 --authorizer-id gfi4n3 --patch-operations op='replace',path='/authorizerUri',value='arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:newAuthorizer/invocations'
```
出力:  

```
{
    "authType": "custom",
    "name": "testAuthorizer",
    "authorizerUri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123412341234:function:newAuthorizer/invocations",
    "authorizerResultTtlInSeconds": 300,
    "identitySource": "method.request.header.Authorization",
    "type": "TOKEN",
    "id": "gfi4n3"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-authorizer.html)」を参照してください。

### `update-base-path-mapping`
<a name="api-gateway_UpdateBasePathMapping_cli_2_topic"></a>

次のコード例では、`update-base-path-mapping` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名のベースパスマッピングを変更する方法**  
コマンド:  

```
aws apigateway update-base-path-mapping --domain-name api.domain.tld --base-path prod --patch-operations op='replace',path='/basePath',value='v1'
```
出力:  

```
{
    "basePath": "v1",
    "restApiId": "1234123412",
    "stage": "api"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateBasePathMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-base-path-mapping.html)」を参照してください。**

### `update-client-certificate`
<a name="api-gateway_UpdateClientCertificate_cli_2_topic"></a>

次のコード例では、`update-client-certificate` を使用する方法を示しています。

**AWS CLI**  
**クライアント証明書の説明を更新する方法**  
コマンド:  

```
aws apigateway update-client-certificate --client-certificate-id a1b2c3 --patch-operations op='replace',path='/description',value='My new description'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateClientCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-client-certificate.html)」を参照してください。

### `update-deployment`
<a name="api-gateway_UpdateDeployment_cli_2_topic"></a>

次のコード例では、`update-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイの説明を変更する方法**  
コマンド:  

```
aws apigateway update-deployment --rest-api-id 1234123412 --deployment-id ztt4m2 --patch-operations op='replace',path='/description',value='newDescription'
```
出力:  

```
{
    "description": "newDescription",
    "id": "ztt4m2",
    "createdDate": 1455218022
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-deployment.html)」を参照してください。

### `update-domain-name`
<a name="api-gateway_UpdateDomainName_cli_2_topic"></a>

次のコード例では、`update-domain-name` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名の証明書を変更する方法**  
次の `update-domain-name` の例では、カスタムドメインの証明書名を変更します。  

```
aws apigateway update-domain-name \
    --domain-name api.domain.tld \
    --patch-operations op='replace',path='/certificateArn',value='arn:aws:acm:us-west-2:111122223333:certificate/CERTEXAMPLE123EXAMPLE'
```
出力:  

```
{
    "domainName": "api.domain.tld",
    "distributionDomainName": "d123456789012.cloudfront.net",
    "certificateArn": "arn:aws:acm:us-west-2:111122223333:certificate/CERTEXAMPLE123EXAMPLE",
    "certificateUploadDate": 1462565487
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[Set up Custom Domain Name for an API in API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-domain-name.html)」を参照してください。

### `update-integration-response`
<a name="api-gateway_UpdateIntegrationResponse_cli_2_topic"></a>

次のコード例では、`update-integration-response` を使用する方法を示しています。

**AWS CLI**  
**統合レスポンスヘッダーを「\$1」の静的マッピングに変更する方法**  
コマンド:  

```
aws apigateway update-integration-response --rest-api-id 1234123412 --resource-id 3gapai --http-method GET --status-code 200 --patch-operations op='replace',path='/responseParameters/method.response.header.Access-Control-Allow-Origin',value='"'"'*'"'"'
```
出力:  

```
{
    "statusCode": "200",
    "responseParameters": {
        "method.response.header.Access-Control-Allow-Origin": "'*'"
    }
}
```
**統合レスポンスヘッダーを削除する方法**  
コマンド:  

```
aws apigateway update-integration-response --rest-api-id 1234123412 --resource-id 3gapai --http-method GET --status-code 200 --patch-operations op='remove',path='/responseParameters/method.response.header.Access-Control-Allow-Origin'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIntegrationResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-integration-response.html)」を参照してください。

### `update-integration`
<a name="api-gateway_UpdateIntegration_cli_2_topic"></a>

次のコード例では、`update-integration` を使用する方法を示しています。

**AWS CLI**  
**Input Passthrough で設定された「コンテンツタイプ: application/json」マッピングテンプレートを追加する方法**  
コマンド:  

```
aws apigateway update-integration \
    --rest-api-id a1b2c3d4e5 \
    --resource-id a1b2c3 \
    --http-method POST \
    --patch-operations "op='add',path='/requestTemplates/application~1json'"
```
**カスタムテンプレートで設定された「コンテンツタイプ: application/json」マッピングテンプレートを更新 (置き換え) する方法**  
コマンド:  

```
aws apigateway update-integration \
    --rest-api-id a1b2c3d4e5 \
    --resource-id a1b2c3 \
    --http-method POST \
    --patch-operations "op='replace',path='/requestTemplates/application~1json',value='{"example": "json"}'"
```
**「コンテンツタイプ: application/json」に関連付けられたカスタムテンプレートを Input Passthrough で更新 (置き換え) する方法**  
コマンド:  

```
aws apigateway update-integration \
    --rest-api-id a1b2c3d4e5 \
    --resource-id a1b2c3 \
    --http-method POST \
    --patch-operations "op='replace',path='requestTemplates/application~1json'"
```
**「コンテンツタイプ: application/json」マッピングテンプレートを削除する方法**  
コマンド:  

```
aws apigateway update-integration \
    --rest-api-id a1b2c3d4e5 \
    --resource-id a1b2c3 \
    --http-method POST \
    --patch-operations "op='remove',path='/requestTemplates/application~1json'"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-integration.html)」を参照してください。

### `update-method-response`
<a name="api-gateway_UpdateMethodResponse_cli_2_topic"></a>

次のコード例では、`update-method-response` を使用する方法を示しています。

**AWS CLI**  
**メソッドで 200 レスポンスの新しいメソッドレスポンスヘッダーを作成し、不要として定義する方法 (デフォルト）**  
コマンド:  

```
aws apigateway update-method-response --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --status-code 200 --patch-operations op="add",path="/responseParameters/method.response.header.custom-header",value="false"
```
**メソッドで 200 レスポンスのレスポンスモデルを削除する方法**  
コマンド:  

```
aws apigateway update-method-response --rest-api-id 1234123412 --resource-id a1b2c3 --http-method GET --status-code 200 --patch-operations op="remove",path="/responseModels/application~1json"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMethodResponse](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-method-response.html)」を参照してください。

### `update-method`
<a name="api-gateway_UpdateMethod_cli_2_topic"></a>

次のコード例では、`update-method` を使用する方法を示しています。

**AWS CLI**  
**例 1: API キーを要求するようにメソッドを変更する方法**  
次の `update-method` の例では、API キーを要求するようにメソッドを変更します。  

```
aws apigateway update-method \
    --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method GET \
    --patch-operations op="replace",path="/apiKeyRequired",value="true"
```
出力:  

```
{
    "httpMethod": "GET",
    "authorizationType": "NONE",
    "apiKeyRequired": true,
    "methodResponses": {
        "200": {
            "statusCode": "200",
            "responseModels": {}
        }
    },
    "methodIntegration": {
        "type": "AWS",
        "httpMethod": "POST",
        "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789111:function:hello-world/invocations",
        "passthroughBehavior": "WHEN_NO_MATCH",
        "contentHandling": "CONVERT_TO_TEXT",
        "timeoutInMillis": 29000,
        "cacheNamespace": "h7i8j9",
        "cacheKeyParameters": [],
        "integrationResponses": {
            "200": {
                "statusCode": "200",
                "responseTemplates": {}
            }
        }
    }
}
```
**例 2: メソッドを変更して IAM 認証を要求する方法**  
次の `update-method` の例では、IAM 認証を必要とするようにメソッドを変更します。  

```
aws apigateway update-method \
    --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method GET \
    --patch-operations op="replace",path="/authorizationType",value="AWS_IAM"
```
出力:  

```
 {
    "httpMethod": "GET",
    "authorizationType": "AWS_IAM",
    "apiKeyRequired": false,
    "methodResponses": {
        "200": {
            "statusCode": "200",
            "responseModels": {}
        }
    },
    "methodIntegration": {
        "type": "AWS",
        "httpMethod": "POST",
        "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789111:function:hello-world/invocations",
        "passthroughBehavior": "WHEN_NO_MATCH",
        "contentHandling": "CONVERT_TO_TEXT",
        "timeoutInMillis": 29000,
        "cacheNamespace": "h7i8j9",
        "cacheKeyParameters": [],
        "integrationResponses": {
            "200": {
                "statusCode": "200",
                "responseTemplates": {}
            }
        }
    }
}
```
**例 3: Lambda 認証を要求するようにメソッドを変更する方法**  
次の `update-method` の例では、メソッドを必要な Lambda 認証に変更します。  

```
aws apigateway update-method --rest-api-id 1234123412 \
    --resource-id a1b2c3 \
    --http-method GET \
    --patch-operations op="replace",path="/authorizationType",value="CUSTOM" op="replace",path="/authorizerId",value="e4f5g6"
```
出力:  

```
 {
    "httpMethod": "GET",
    "authorizationType": "CUSTOM",
    "authorizerId" : "e4f5g6",
    "apiKeyRequired": false,
    "methodResponses": {
        "200": {
            "statusCode": "200",
            "responseModels": {}
        }
    },
    "methodIntegration": {
        "type": "AWS",
        "httpMethod": "POST",
        "uri": "arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:123456789111:function:hello-world/invocations",
        "passthroughBehavior": "WHEN_NO_MATCH",
        "contentHandling": "CONVERT_TO_TEXT",
        "timeoutInMillis": 29000,
        "cacheNamespace": "h7i8j9",
        "cacheKeyParameters": [],
        "integrationResponses": {
            "200": {
                "statusCode": "200",
                "responseTemplates": {}
            }
        }
    }
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway CLI と REST API を使用した使用量プランの作成、設定、テスト](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-usage-plans-with-rest-api.html)」と「[API Gateway の REST API へのアクセスの制御と管理](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMethod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-method.html)」を参照してください。

### `update-model`
<a name="api-gateway_UpdateModel_cli_2_topic"></a>

次のコード例では、`update-model` を使用する方法を示しています。

**AWS CLI**  
**API でモデルの説明を変更する方法**  
コマンド:  

```
aws apigateway update-model --rest-api-id 1234123412 --model-name 'Empty' --patch-operations op=replace,path=/description,value='New Description'
```
**API でモデルのスキーマを変更する方法**  
コマンド:  

```
aws apigateway update-model --rest-api-id 1234123412 --model-name 'Empty' --patch-operations op=replace,path=/schema,value='"{ \"$schema\": \"http://json-schema.org/draft-04/schema#\", \"title\" : \"Empty Schema\", \"type\" : \"object\" }"'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-model.html)」を参照してください。

### `update-resource`
<a name="api-gateway_UpdateResource_cli_2_topic"></a>

次のコード例では、`update-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースを移動して API 内の別の親リソースに配置する方法**  
コマンド:  

```
aws apigateway update-resource --rest-api-id 1234123412 --resource-id 1a2b3c --patch-operations op=replace,path=/parentId,value='3c2b1a'
```
出力:  

```
{
    "path": "/resource",
    "pathPart": "resource",
    "id": "1a2b3c",
    "parentId": "3c2b1a"
}
```
**API でリソース (pathPart) の名前を変更する方法**  
コマンド:  

```
aws apigateway update-resource --rest-api-id 1234123412 --resource-id 1a2b3c --patch-operations op=replace,path=/pathPart,value=newresourcename
```
出力:  

```
{
    "path": "/newresourcename",
    "pathPart": "newresourcename",
    "id": "1a2b3c",
    "parentId": "3c2b1a"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-resource.html)」を参照してください。

### `update-rest-api`
<a name="api-gateway_UpdateRestApi_cli_2_topic"></a>

次のコード例では、`update-rest-api` を使用する方法を示しています。

**AWS CLI**  
** API の名前を変更する方法**  
コマンド:  

```
aws apigateway update-rest-api --rest-api-id 1234123412 --patch-operations op=replace,path=/name,value='New Name'
```
** API の説明を変更する方法**  
コマンド:  

```
aws apigateway update-rest-api --rest-api-id 1234123412 --patch-operations op=replace,path=/description,value='New Description'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRestApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-rest-api.html)」を参照してください。

### `update-stage`
<a name="api-gateway_UpdateStage_cli_2_topic"></a>

次のコード例では、`update-stage` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースとメソッドのステージ設定を上書きする方法**  
次の `update-stage` の例では、ステージ設定を上書きし、特定のリソースとメソッドの完全なリクエスト/レスポンスログ記録をオフにします。  

```
aws apigateway update-stage \
    --rest-api-id 1234123412 \
    --stage-name 'dev' \
    --patch-operations op=replace,path=/~1resourceName/GET/logging/dataTrace,value=false
```
出力:  

```
{
    "deploymentId": "5ubd17",
    "stageName": "dev",
    "cacheClusterEnabled": false,
    "cacheClusterStatus": "NOT_AVAILABLE",
    "methodSettings": {
        "~1resourceName/GET": {
            "metricsEnabled": false,
            "dataTraceEnabled": false,
            "throttlingBurstLimit": 5000,
            "throttlingRateLimit": 10000.0,
            "cachingEnabled": false,
            "cacheTtlInSeconds": 300,
            "cacheDataEncrypted": false,
            "requireAuthorizationForCacheControl": true,
            "unauthorizedCacheControlHeaderStrategy": "SUCCEED_WITH_RESPONSE_HEADER"
        }
    },
    "tracingEnabled": false,
    "createdDate": "2022-07-18T10:11:18-07:00",
    "lastUpdatedDate": "2022-07-18T10:19:04-07:00"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[REST API にステージを設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-stages.html)」を参照してください。  
**例 2: API ステージのすべてのリソースとメソッドのステージ設定を更新する方法**  
次の `update-stage` の例では、API ステージのすべてのリソースとメソッドの完全なリクエスト/レスポンスログ記録をオンにします。  

```
aws apigateway update-stage \
    --rest-api-id 1234123412 \
    --stage-name 'dev' \
    --patch-operations 'op=replace,path=/*/*/logging/dataTrace,value=true'
```
出力:  

```
{
    "deploymentId": "5ubd17",
    "stageName": "dev",
    "cacheClusterEnabled": false,
    "cacheClusterStatus": "NOT_AVAILABLE",
    "methodSettings": {
        "*/*": {
            "metricsEnabled": false,
            "dataTraceEnabled": true,
            "throttlingBurstLimit": 5000,
            "throttlingRateLimit": 10000.0,
            "cachingEnabled": false,
            "cacheTtlInSeconds": 300,
            "cacheDataEncrypted": false,
            "requireAuthorizationForCacheControl": true,
            "unauthorizedCacheControlHeaderStrategy": "SUCCEED_WITH_RESPONSE_HEADER"
        }
    },
    "tracingEnabled": false,
    "createdDate": "2022-07-18T10:11:18-07:00",
    "lastUpdatedDate": "2022-07-18T10:31:04-07:00"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[REST API にステージを設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-stages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-stage.html)」を参照してください。

### `update-usage-plan`
<a name="api-gateway_UpdateUsagePlan_cli_2_topic"></a>

次のコード例では、`update-usage-plan` を使用する方法を示しています。

**AWS CLI**  
**使用量プランで定義された期間を変更する方法**  
コマンド:  

```
aws apigateway update-usage-plan --usage-plan-id a1b2c3 --patch-operations op="replace",path="/quota/period",value="MONTH"
```
**使用量プランで定義されているクォータ制限を変更する方法**  
コマンド:  

```
aws apigateway update-usage-plan --usage-plan-id a1b2c3 --patch-operations op="replace",path="/quota/limit",value="500"
```
**使用量プランで定義されているスロットルレート制限を変更する方法**  
コマンド:  

```
aws apigateway update-usage-plan --usage-plan-id a1b2c3 --patch-operations op="replace",path="/throttle/rateLimit",value="10"
```
**使用量プランで定義されているスロットルバースト制限を変更する方法**  
コマンド:  

```
aws apigateway update-usage-plan --usage-plan-id a1b2c3 --patch-operations op="replace",path="/throttle/burstLimit",value="20"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUsagePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-usage-plan.html)」を参照してください。

### `update-usage`
<a name="api-gateway_UpdateUsage_cli_2_topic"></a>

次のコード例では、`update-usage` を使用する方法を示しています。

**AWS CLI**  
**使用量プランで定義されている現在の期間の API キーのクォータを一時的に変更する方法**  
コマンド:  

```
aws apigateway update-usage --usage-plan-id a1b2c3 --key-id 1NbjQzMReAkeEQPNAW8r3dXsU2rDD7fc7f2Sipnu --patch-operations op="replace",path="/remaining",value="50"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-usage.html)」を参照してください。

### `update-vpc-link`
<a name="api-gateway_UpdateVpcLink_cli_2_topic"></a>

次の例は、`update-vpc-link` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 既存の VPC リンク名を更新するには**  
次の `update-vpc-link` の例では、指定された VPC リンクの名前を更新します。  

```
aws apigateway update-vpc-link  \
    --vpc-link-id ab3de6 \
    --patch-operations op=replace,path=/name,value=my-vpc-link
```
出力:  

```
{
    "id": "ab3de6",
    "name": "my-vpc-link",
    "targetArns": [
        "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/my-lb/12a456s89aaa12345"
    ],
    "status": "AVAILABLE",
    "statusMessage": "Your vpc link is ready for use",
    "tags": {}
}
```
詳細については、「*AWS CLI コマンドリファレンス*」の「[既存の VPC リンクの更新](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-vpc-link.html)」を参照してください。  
**例 2: 既存の VPC リンク名と説明を更新するには**  
次の `update-vpc-link` の例では、指定された VPC リンクの名前を更新します。  

```
aws apigateway update-vpc-link  \
    --vpc-link-id ab3de6 \
    --patch-operations op=replace,path=/name,value=my-vpc-link op=replace,path=/description,value="My custom description"
```
出力:  

```
{
    "id": "ab3de6",
    "name": "my-vpc-link",
    "description": "My custom description",
    "targetArns": [
        "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/my-lb/12a456s89aaa12345"
    ],
    "status": "AVAILABLE",
    "statusMessage": "Your vpc link is ready for use",
    "tags": {}
}
```
詳細については、「*AWS CLI コマンドリファレンス*」の「[既存の VPC リンクの更新](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-vpc-link.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVpcLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigateway/update-vpc-link.html)」を参照してください。

# を使用した API Gateway HTTP および WebSocket API の例 AWS CLI
<a name="cli_2_apigatewayv2_code_examples"></a>

次のコード例は、API Gateway HTTP および WebSocket API AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-api-mapping`
<a name="apigatewayv2_CreateApiMapping_cli_2_topic"></a>

次のコード例は、`create-api-mapping` を使用する方法を示しています。

**AWS CLI**  
**API 用に API マッピングを作成するには**  
次の `create-api-mapping` の例では、API の `test` のステージをカスタムドメイン名「`regional.example.com`」のパス「`/myApi`」にマッピングします。  

```
aws apigatewayv2 create-api-mapping \
    --domain-name regional.example.com \
    --api-mapping-key myApi \
    --api-id a1b2c3d4 \
    --stage test
```
出力:  

```
{
    "ApiId": "a1b2c3d4",
    "ApiMappingId": "0qzs2sy7bh",
    "ApiMappingKey": "myApi"
    "Stage": "test"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドレットリファレンス*」の「[CreateApiMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-api-mapping.html)」を参照してください。

### `create-api`
<a name="apigatewayv2_CreateApi_cli_2_topic"></a>

次のコード例は、`create-api` を使用する方法を示しています。

**AWS CLI**  
**HTTP API を作成する方法**  
次の `create-api` の例では、クイック作成を使用して HTTP API を作成します。クイック作成を使用して、 AWS Lambda または HTTP 統合、デフォルトのキャッチオールルート、および変更を自動的にデプロイするように設定されたデフォルトのステージで API を作成できます。次のコマンドは、クイック作成を使用して、Lambda 関数と統合する HTTP API を作成します。  

```
aws apigatewayv2 create-api \
    --name my-http-api \
    --protocol-type HTTP \
    --target arn:aws:lambda:us-west-2:123456789012:function:my-lambda-function
```
出力:  

```
{
    "ApiEndpoint": "https://a1b2c3d4.execute-api.us-west-2.amazonaws.com",
    "ApiId": "a1b2c3d4",
    "ApiKeySelectionExpression": "$request.header.x-api-key",
    "CreatedDate": "2020-04-08T19:05:45+00:00",
    "Name": "my-http-api",
    "ProtocolType": "HTTP",
    "RouteSelectionExpression": "$request.method $request.path"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway での HTTP API の開発](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop.html)」を参照してください。  
**WebSocket API を作成する方法**  
次の `create-api` の例では、指定された名前の WebSocket API を作成します。  

```
aws apigatewayv2 create-api \
    --name "myWebSocketApi" \
    --protocol-type WEBSOCKET \
    --route-selection-expression '$request.body.action'
```
出力:  

```
{
    "ApiKeySelectionExpression": "$request.header.x-api-key",
    "Name": "myWebSocketApi",
    "CreatedDate": "2018-11-15T06:23:51Z",
    "ProtocolType": "WEBSOCKET",
    "RouteSelectionExpression": "'$request.body.action'",
    "ApiId": "aabbccddee"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway での WebSocket API の作成](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-create-empty-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-api.html)」を参照してください。

### `create-authorizer`
<a name="apigatewayv2_CreateAuthorizer_cli_2_topic"></a>

次のコード例は、`create-authorizer` を使用する方法を示しています。

**AWS CLI**  
**HTTP API の JWT オーソライザーを作成する方法**  
次の `create-authorizer` の例では、Amazon Cognito を ID プロバイダーとして使用する JWT オーソライザーを作成します。  

```
aws apigatewayv2 create-authorizer \
    --name my-jwt-authorizer \
    --api-id a1b2c3d4 \
    --authorizer-type JWT \
    --identity-source '$request.header.Authorization' \
    --jwt-configuration Audience=123456abc,Issuer=https://cognito-idp.us-west-2.amazonaws.com/us-west-2_abc123
```
出力:  

```
{
    "AuthorizerId": "a1b2c3",
    "AuthorizerType": "JWT",
    "IdentitySource": [
        "$request.header.Authorization"
    ],
    "JwtConfiguration": {
        "Audience": [
            "123456abc"
        ],
        "Issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_abc123"
    },
    "Name": "my-jwt-authorizer"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[JWT オーソライザーを使用した HTTP API へのアクセスの制御](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-authorizer.html)」を参照してください。

### `create-deployment`
<a name="apigatewayv2_CreateDeployment_cli_2_topic"></a>

次のコード例は、`create-deployment` を使用する方法を示しています。

**AWS CLI**  
**API のデプロイを作成する方法**  
次の `create-deployment` の例では、API にデプロイを作成し、API の `dev` ステージにデプロイを関連付けます。  

```
aws apigatewayv2 create-deployment \
    --api-id a1b2c3d4 \
    --stage-name dev
```
出力:  

```
{
    "AutoDeployed": false,
    "CreatedDate": "2020-04-06T23:38:08Z",
    "DeploymentId": "53lz9l",
    "DeploymentStatus": "DEPLOYED"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API デプロイ](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-basic-concept.html#apigateway-definition-api-deployment)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-deployment.html)」を参照してください。**

### `create-domain-name`
<a name="apigatewayv2_CreateDomainName_cli_2_topic"></a>

次のコード例は、`create-domain-name` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名を作成する方法**  
次の `create-domain-name` の例では、API にリージョナルカスタムドメイン名を作成します。  

```
aws apigatewayv2 create-domain-name \
    --domain-name regional.example.com \
    --domain-name-configurations CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678
```
出力:  

```
{
    "ApiMappingSelectionExpression": "$request.basepath",
    "DomainName": "regional.example.com",
    "DomainNameConfigurations": [
        {
            "ApiGatewayDomainName": "d-id.execute-api.us-west-2.amazonaws.com",
            "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678",
            "EndpointType": "REGIONAL",
            "HostedZoneId": "123456789111",
            "SecurityPolicy": "TLS_1_2",
            "DomainNameStatus": "AVAILABLE"
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-domain-name.html)」を参照してください。

### `create-integration`
<a name="apigatewayv2_CreateIntegration_cli_2_topic"></a>

次のコード例は、`create-integration` を使用する方法を示しています。

**AWS CLI**  
**WebSocket API 統合を作成する方法**  
次の `create-integration` の例では、WebSocket API 用のモック統合を作成します。  

```
aws apigatewayv2 create-integration \
    --api-id aabbccddee \
    --passthrough-behavior WHEN_NO_MATCH \
    --timeout-in-millis 29000 \
    --connection-type INTERNET \
    --integration-type MOCK
```
出力:  

```
{
    "ConnectionType": "INTERNET",
    "IntegrationId": "0abcdef",
    "IntegrationResponseSelectionExpression": "${integration.response.statuscode}",
    "IntegrationType": "MOCK",
    "PassthroughBehavior": "WHEN_NO_MATCH",
    "PayloadFormatVersion": "1.0",
    "TimeoutInMillis": 29000
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway での WebSocket API 統合リクエストのセットアップ](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integration-requests.html)」を参照してください。  
**HTTP API カスタム統合を作成する方法**  
次の`create-integration`例では、HTTP API の AWS Lambda 統合を作成します。  

```
aws apigatewayv2 create-integration \
    --api-id a1b2c3d4 \
    --integration-type AWS_PROXY \
    --integration-uri arn:aws:lambda:us-west-2:123456789012:function:my-function \
    --payload-format-version 2.0
```
出力:  

```
{
    "ConnectionType": "INTERNET",
    "IntegrationId": "0abcdef",
    "IntegrationMethod": "POST",
    "IntegrationType": "AWS_PROXY",
    "IntegrationUri": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "PayloadFormatVersion": "2.0",
    "TimeoutInMillis": 30000
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-integration.html)」を参照してください。

### `create-route`
<a name="apigatewayv2_CreateRoute_cli_2_topic"></a>

次のコード例は、`create-route` を使用する方法を示しています。

**AWS CLI**  
**WebSocket または HTTP API の \$1default ルートを作成する方法**  
次の `create-route` の例では、WebSocket または HTTP API の `$default` ルートを作成します。  

```
aws apigatewayv2 create-route \
    --api-id aabbccddee \
    --route-key '$default'
```
出力:  

```
{
    "ApiKeyRequired": false,
    "AuthorizationType": "NONE",
    "RouteKey": "$default",
    "RouteId": "1122334"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[WebSocket API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-add-route.html)」を参照してください。  
**HTTP API のルートを作成する方法**  
次の `create-route` の例では、POST リクエストを受け入れる「`signup`」という名前のルートを作成します。  

```
aws apigatewayv2 create-route \
    --api-id aabbccddee \
    --route-key 'POST /signup'
```
出力:  

```
{
    "ApiKeyRequired": false,
    "AuthorizationType": "NONE",
    "RouteKey": "POST /signup",
    "RouteId": "1122334"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-route.html)」を参照してください。

### `create-routing-rule`
<a name="apigatewayv2_CreateRoutingRule_cli_2_topic"></a>

次のコード例は、`create-routing-rule` を使用する方法を示しています。

**AWS CLI**  
**ルーティングルールを作成するには**  
次の `create-routing-rule` の例では、優先度が `50` のルーティングルールを作成します。  

```
aws apigatewayv2 create-routing-rule \
    --domain-name 'regional.example.com' \
    --priority 50 \
    --conditions '[ \
        { \
            "MatchBasePaths": { \
                "AnyOf": [ \
                    "PetStoreShopper" \
                ] \
            } \
        } \
    ]' \
    --actions '[ \
        { \
            "InvokeApi": { \
                "ApiId": "abcd1234", \
                "Stage": "prod" \
            } \
        } \
    ]'
```
出力:  

```
{
    "Actions": [
        {
            "InvokeApi": {
                "ApiId": "abcd1234",
                "Stage": "prod",
                "StripBasePath": false
            }
        }
    ],
    "Conditions": [
        {
            "MatchBasePaths": {
                "AnyOf": [
                    "PetStoreShopper"
                ]
            }
        }
    ],
    "Priority": 50,
    "RoutingRuleArn": "arn:aws:apigateway:us-east-2:123456789012:/domainnames/regional.example.com/routingrules/aaa111",
    "RoutingRuleId": "aaa111"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API ステージを REST API のカスタムドメイン名に接続するためのルーティングルール](https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-routing-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoutingRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-routing-rule.html)」を参照してください。

### `create-stage`
<a name="apigatewayv2_CreateStage_cli_2_topic"></a>

次のコード例は、`create-stage` を使用する方法を示しています。

**AWS CLI**  
**ステージを作成する方法**  
次の `create-stage` の例では、 API に「dev」という名前のステージを作成します。  

```
aws apigatewayv2 create-stage \
    --api-id a1b2c3d4 \
    --stage-name dev
```
出力:  

```
{
    "CreatedDate": "2020-04-06T23:23:46Z",
    "DefaultRouteSettings": {
        "DetailedMetricsEnabled": false
    },
    "LastUpdatedDate": "2020-04-06T23:23:46Z",
    "RouteSettings": {},
    "StageName": "dev",
    "StageVariables": {},
    "Tags": {}
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-stage.html)」を参照してください。

### `create-vpc-link`
<a name="apigatewayv2_CreateVpcLink_cli_2_topic"></a>

次のコード例は、`create-vpc-link` を使用する方法を示しています。

**AWS CLI**  
**HTTP API の VPC リンクを作成する方法**  
次の `create-vpc-link` の例では、HTTP API の VPC リンクを作成します。  

```
aws apigatewayv2 create-vpc-link \
    --name MyVpcLink \
    --subnet-ids subnet-aaaa subnet-bbbb \
    --security-group-ids sg1234 sg5678
```
出力:  

```
{
    "CreatedDate": "2020-04-07T00:11:46Z",
    "Name": "MyVpcLink",
    "SecurityGroupIds": [
        "sg1234",
        "sg5678"
    ],
    "SubnetIds": [
        "subnet-aaaa",
        "subnet-bbbb"
    ],
    "Tags": {},
    "VpcLinkId": "abcd123",
    "VpcLinkStatus": "PENDING",
    "VpcLinkStatusMessage": "VPC link is provisioning ENIs",
    "VpcLinkVersion": "V2"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の VPC リンクの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vpc-links.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpcLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/create-vpc-link.html)」を参照してください。

### `delete-access-log-settings`
<a name="apigatewayv2_DeleteAccessLogSettings_cli_2_topic"></a>

次のコード例は、`delete-access-log-settings` を使用する方法を示しています。

**AWS CLI**  
**API のアクセスログ記録を無効にする方法**  
次の `delete-access-log-settings` の例では、API の `$default` ステージのアクセスログ設定を削除します。ステージのアクセスログ記録を無効にするには、そのアクセスログ設定を削除します。  

```
aws apigatewayv2 delete-access-log-settings \
    --api-id a1b2c3d4 \
    --stage-name '$default'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API 記録の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-logging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessLogSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-access-log-settings.html)」を参照してください。

### `delete-api-mapping`
<a name="apigatewayv2_DeleteApiMapping_cli_2_topic"></a>

次のコード例は、`delete-api-mapping` を使用する方法を示しています。

**AWS CLI**  
**API マッピングを削除する方法**  
次の `delete-api-mapping` の例は、カスタムドメイン名「`api.example.com`」の API マッピングを削除します。  

```
aws apigatewayv2 delete-api-mapping \
    --api-mapping-id a1b2c3 \
    --domain-name api.example.com
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApiMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-api-mapping.html)」を参照してください。

### `delete-api`
<a name="apigatewayv2_DeleteApi_cli_2_topic"></a>

次のコード例は、`delete-api` を使用する方法を示しています。

**AWS CLI**  
**API を削除する方法**  
次の `delete-api` の例は、API を削除します。  

```
aws apigatewayv2 delete-api \
    --api-id a1b2c3d4
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html)」と「[WebSocket API の使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-api.html)」を参照してください。

### `delete-authorizer`
<a name="apigatewayv2_DeleteAuthorizer_cli_2_topic"></a>

次のコード例は、`delete-authorizer` を使用する方法を示しています。

**AWS CLI**  
**オーソライザーを削除する方法**  
次の `delete-authorizer` の例では、オーソライザーを削除します。  

```
aws apigatewayv2 delete-authorizer \
    --api-id a1b2c3d4 \
    --authorizer-id a1b2c3
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[JWT オーソライザーを使用した HTTP API へのアクセスの制御](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-authorizer.html)」を参照してください。

### `delete-cors-configuration`
<a name="apigatewayv2_DeleteCorsConfiguration_cli_2_topic"></a>

次のコード例は、`delete-cors-configuration` を使用する方法を示しています。

**AWS CLI**  
**HTTP API の CORS 構成を削除する方法**  
次の `delete-cors-configuration` の例では、CORS 構成を削除することで HTTP API の CORS を無効にします。  

```
aws apigatewayv2 delete-cors-configuration \
    --api-id a1b2c3d4
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API CORS の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCorsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-cors-configuration.html)」を参照してください。

### `delete-deployment`
<a name="apigatewayv2_DeleteDeployment_cli_2_topic"></a>

次のコード例は、`delete-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイを削除する方法**  
次の `delete-deployment` の例では、API のデプロイを削除します。  

```
aws apigatewayv2 delete-deployment \
    --api-id a1b2c3d4 \
    --deployment-id a1b2c3
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API デプロイ](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-basic-concept.html#apigateway-definition-api-deployment)」を参照してください。  
+  API の詳細については、 コマンドリファレンスAWS CLI の「[DeleteDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-deployment.html)」を参照してください。**

### `delete-domain-name`
<a name="apigatewayv2_DeleteDomainName_cli_2_topic"></a>

次のコード例では、`delete-domain-name` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名を削除する方法**  
次の `delete-domain-name` の例では、カスタムドメイン名を削除します。  

```
aws apigatewayv2 delete-domain-name \
    --domain-name api.example.com
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-domain-name.html)」を参照してください。

### `delete-integration`
<a name="apigatewayv2_DeleteIntegration_cli_2_topic"></a>

次のコード例は、`delete-integration` を使用する方法を示しています。

**AWS CLI**  
**統合を削除する方法**  
次の `delete-integration` の例では、API 統合を削除します。  

```
aws apigatewayv2 delete-integration \
    --api-id a1b2c3d4 \
    --integration-id a1b2c3
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html)」と「[WebSocket API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integrations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-integration.html)」を参照してください。

### `delete-route-settings`
<a name="apigatewayv2_DeleteRouteSettings_cli_2_topic"></a>

次のコード例は、`delete-route-settings` を使用する方法を示しています。

**AWS CLI**  
**ルート設定を削除する方法**  
次の `delete-route-settings` の例では、指定されたルートのルート設定を削除します。  

```
aws apigatewayv2 delete-route-settings \
    --api-id a1b2c3d4 \
    --stage-name dev \
    --route-key 'GET /pets'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRouteSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-route-settings.html)」を参照してください。

### `delete-route`
<a name="apigatewayv2_DeleteRoute_cli_2_topic"></a>

次のコード例は、`delete-route` を使用する方法を示しています。

**AWS CLI**  
**ルートを削除する方法**  
次の `delete-route` の例では、API ルートを削除します。  

```
aws apigatewayv2 delete-route \
    --api-id a1b2c3d4 \
    --route-id a1b2c3
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-route.html)」を参照してください。

### `delete-routing-rule`
<a name="apigatewayv2_DeleteRoutingRule_cli_2_topic"></a>

次のコード例は、`delete-routing-rule` を使用する方法を示しています。

**AWS CLI**  
**ルーティングルールを削除するには**  
次の `delete-routing-rule` の例では、カスタムドメイン名のルーティングルールを削除します。  

```
aws apigatewayv2 delete-routing-rule \
    --domain-name 'regional.example.com' \
    --routing-rule-id aaa111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API ステージを REST API のカスタムドメイン名に接続するためのルーティングルール](https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-routing-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoutingRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-routing-rule.html)」を参照してください。

### `delete-stage`
<a name="apigatewayv2_DeleteStage_cli_2_topic"></a>

次のコード例は、`delete-stage` を使用する方法を示しています。

**AWS CLI**  
**ステージを削除する方法**  
次の `delete-stage` の例では、API の `test` ステージを削除します。  

```
aws apigatewayv2 delete-stage \
    --api-id a1b2c3d4 \
    --stage-name test
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-stage.html)」を参照してください。

### `delete-vpc-link`
<a name="apigatewayv2_DeleteVpcLink_cli_2_topic"></a>

次のコード例は、`delete-vpc-link` を使用する方法を示しています。

**AWS CLI**  
**HTTP API の VPC リンクを削除する方法**  
次の `delete-vpc-link` の例は、VPC リンクを削除します。  

```
aws apigatewayv2 delete-vpc-link \
    --vpc-link-id abcd123
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の VPC リンクの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vpc-links.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpcLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/delete-vpc-link.html)」を参照してください。

### `export-api`
<a name="apigatewayv2_ExportApi_cli_2_topic"></a>

次のコード例は、`export-api` を使用する方法を示しています。

**AWS CLI**  
**HTTP API の OpenAPI 定義をエクスポートする方法**  
次の `export-api` の例は、「`prod`」という名前の API ステージの OpenAPI 3.0 定義を、 「`stage-definition.yaml`」という名前の YAML ファイルにエクスポートします。エクスポートされた定義ファイルには、デフォルトで API Gateway 拡張が含まれます。  

```
aws apigatewayv2 export-api \
    --api-id a1b2c3d4 \
    --output-type YAML \
    --specification OAS30 \
    --stage-name prod \
    stage-definition.yaml
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway から HTTP API のエクスポート](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-export.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExportApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/export-api.html)」を参照してください。

### `get-api-mapping`
<a name="apigatewayv2_GetApiMapping_cli_2_topic"></a>

次のコード例は、`get-api-mapping` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名の API マッピングに関する情報を取得するには**  
次の `get-api-mapping` の例では、カスタムドメイン名「`api.example.com`」の API マッピングに関する情報を表示します。  

```
aws apigatewayv2 get-api-mapping \
    --api-mapping-id a1b2c3 \
    --domain-name api.example.com
```
出力:  

```
{
    "ApiId": "a1b2c3d4",
    "ApiMappingId": "a1b2c3d5",
    "ApiMappingKey": "myTestApi"
    "Stage": "test"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApiMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-api-mapping.html)」を参照してください。

### `get-api-mappings`
<a name="apigatewayv2_GetApiMappings_cli_2_topic"></a>

次のコード例は、`get-api-mappings` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名の API マッピングを取得する方法**  
次の `get-api-mappings` の例では、カスタムドメイン名「`api.example.com`」の API マッピングのすべてを一覧表示します。  

```
aws apigatewayv2 get-api-mappings \
    --domain-name api.example.com
```
出力:  

```
{
    "Items": [
        {
            "ApiId": "a1b2c3d4",
            "ApiMappingId": "a1b2c3d5",
            "ApiMappingKey": "myTestApi"
            "Stage": "test"
        },
        {
            "ApiId": "a5b6c7d8",
            "ApiMappingId": "a1b2c3d6",
            "ApiMappingKey": "myDevApi"
            "Stage": "dev"
        },
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApiMappings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-api-mappings.html)」を参照してください。

### `get-api`
<a name="apigatewayv2_GetApi_cli_2_topic"></a>

次のコード例は、`get-api` を使用する方法を示しています。

**AWS CLI**  
**API に関する情報を取得する方法**  
以下の `get-api` の例では、API に関する情報を表示します。  

```
aws apigatewayv2 get-api \
    --api-id a1b2c3d4
```
出力:  

```
{
    "ApiEndpoint": "https://a1b2c3d4.execute-api.us-west-2.amazonaws.com",
    "ApiId": "a1b2c3d4",
    "ApiKeySelectionExpression": "$request.header.x-api-key",
    "CreatedDate": "2020-03-28T00:32:37Z",
    "Name": "my-api",
    "ProtocolType": "HTTP",
    "RouteSelectionExpression": "$request.method $request.path",
    "Tags": {
        "department": "finance"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-api.html)」を参照してください。

### `get-apis`
<a name="apigatewayv2_GetApis_cli_2_topic"></a>

次のコード例は、`get-apis` を使用する方法を示しています。

**AWS CLI**  
**API の一覧を取得する方法**  
次の `get-apis` の例では、現在のユーザーのすべての API を一覧表示します。  

```
aws apigatewayv2 get-apis
```
出力:  

```
{
    "Items": [
        {
            "ApiEndpoint": "wss://a1b2c3d4.execute-api.us-west-2.amazonaws.com",
            "ApiId": "a1b2c3d4",
            "ApiKeySelectionExpression": "$request.header.x-api-key",
            "CreatedDate": "2020-04-07T20:21:59Z",
            "Name": "my-websocket-api",
            "ProtocolType": "WEBSOCKET",
            "RouteSelectionExpression": "$request.body.message",
            "Tags": {}
        },
        {
            "ApiEndpoint": "https://a1b2c3d5.execute-api.us-west-2.amazonaws.com",
            "ApiId": "a1b2c3d5",
            "ApiKeySelectionExpression": "$request.header.x-api-key",
            "CreatedDate": "2020-04-07T20:23:50Z",
            "Name": "my-http-api",
            "ProtocolType": "HTTP",
            "RouteSelectionExpression": "$request.method $request.path",
            "Tags": {}
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api.html)」と「[WebSocket API の使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-apis.html)」を参照してください。

### `get-authorizer`
<a name="apigatewayv2_GetAuthorizer_cli_2_topic"></a>

次のコード例は、`get-authorizer` を使用する方法を示しています。

**AWS CLI**  
**オーソライザーに関する情報を取得する方法**  
以下の `get-authorizer` の例では、オーソライザーに関する情報を表示します。  

```
aws apigatewayv2 get-authorizer \
    --api-id a1b2c3d4 \
    --authorizer-id a1b2c3
```
出力:  

```
{
    "AuthorizerId": "a1b2c3",
    "AuthorizerType": "JWT",
    "IdentitySource": [
        "$request.header.Authorization"
    ],
    "JwtConfiguration": {
        "Audience": [
            "123456abc"
        ],
        "Issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_abc123"
    },
    "Name": "my-jwt-authorizer"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[JWT オーソライザーを使用した HTTP API へのアクセスの制御](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-authorizer.html)」を参照してください。

### `get-authorizers`
<a name="apigatewayv2_GetAuthorizers_cli_2_topic"></a>

次のコード例は、`get-authorizers` を使用する方法を示しています。

**AWS CLI**  
**API のオーソライザーの一覧を取得する方法**  
次の `get-authorizers` の例では、API のすべてのオーソライザーを一覧表示します。  

```
aws apigatewayv2 get-authorizers \
    --api-id a1b2c3d4
```
出力:  

```
{
    "Items": [
        {
            "AuthorizerId": "a1b2c3",
            "AuthorizerType": "JWT",
            "IdentitySource": [
                "$request.header.Authorization"
            ],
            "JwtConfiguration": {
                "Audience": [
                    "123456abc"
                ],
                "Issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_abc123"
            },
            "Name": "my-jwt-authorizer"
        },
        {
            "AuthorizerId": "a1b2c4",
            "AuthorizerType": "JWT",
            "IdentitySource": [
                "$request.header.Authorization"
            ],
            "JwtConfiguration": {
                "Audience": [
                    "6789abcde"
                ],
                "Issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_abc234"
            },
            "Name": "new-jwt-authorizer"
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[JWT オーソライザーを使用した HTTP API へのアクセスの制御](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthorizers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-authorizers.html)」を参照してください。

### `get-deployment`
<a name="apigatewayv2_GetDeployment_cli_2_topic"></a>

次のコード例は、`get-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイの情報を取得する方法**  
以下の `get-deployment` の例では、デプロイに関する情報を表示します。  

```
aws apigatewayv2 get-deployment \
    --api-id a1b2c3d4 \
    --deployment-id abcdef
```
出力:  

```
{
    "AutoDeployed": true,
    "CreatedDate": "2020-04-07T23:58:40Z",
    "DeploymentId": "abcdef",
    "DeploymentStatus": "DEPLOYED",
    "Description": "Automatic deployment triggered by changes to the Api configuration"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API デプロイ](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-basic-concept.html#apigateway-definition-api-deployment)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-deployment.html)」を参照してください。

### `get-deployments`
<a name="apigatewayv2_GetDeployments_cli_2_topic"></a>

次のコード例は、`get-deployments` を使用する方法を示しています。

**AWS CLI**  
**デプロイの一覧を取得する方法**  
次の `get-deployments` の例では、すべての API のデプロイの一覧を表示します。  

```
aws apigatewayv2 get-deployments \
    --api-id a1b2c3d4
```
出力:  

```
{
    "Items": [
        {
            "AutoDeployed": true,
            "CreatedDate": "2020-04-07T23:58:40Z",
            "DeploymentId": "abcdef",
            "DeploymentStatus": "DEPLOYED",
            "Description": "Automatic deployment triggered by changes to the Api configuration"
        },
        {
            "AutoDeployed": true,
            "CreatedDate": "2020-04-06T00:33:00Z",
            "DeploymentId": "bcdefg",
            "DeploymentStatus": "DEPLOYED",
            "Description": "Automatic deployment triggered by changes to the Api configuration"
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API デプロイ](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-basic-concept.html#apigateway-definition-api-deployment)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-deployments.html)」を参照してください。

### `get-domain-name`
<a name="apigatewayv2_GetDomainName_cli_2_topic"></a>

次のコード例は、`get-domain-name` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名に関する情報を取得する方法**  
次の `get-domain-name` の例では、カスタムドメイン名に関する情報を表示します。  

```
aws apigatewayv2 get-domain-name \
    --domain-name api.example.com
```
出力:  

```
{
    "ApiMappingSelectionExpression": "$request.basepath",
    "DomainName": "api.example.com",
    "DomainNameConfigurations": [
        {
            "ApiGatewayDomainName": "d-1234.execute-api.us-west-2.amazonaws.com",
            "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678",
            "EndpointType": "REGIONAL",
            "HostedZoneId": "123456789111",
            "SecurityPolicy": "TLS_1_2",
            "DomainNameStatus": "AVAILABLE"
        }
    ],
    "Tags": {}
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-domain-name.html)」を参照してください。

### `get-domain-names`
<a name="apigatewayv2_GetDomainNames_cli_2_topic"></a>

次のコード例は、`get-domain-names` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名の一覧を取得する方法**  
次の `get-domain-names` の例では、現在のユーザーのすべてのカスタムドメイン名を一覧表示します。  

```
aws apigatewayv2 get-domain-names
```
出力:  

```
{
    "Items": [
        {
            "ApiMappingSelectionExpression": "$request.basepath",
            "DomainName": "api.example.com",
            "DomainNameConfigurations": [
                {
                    "ApiGatewayDomainName": "d-1234.execute-api.us-west-2.amazonaws.com",
                    "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678",
                    "EndpointType": "REGIONAL",
                    "HostedZoneId": "123456789111",
                    "SecurityPolicy": "TLS_1_2",
                    "DomainNameStatus": "AVAILABLE"
                }
            ]
        },
        {
            "ApiMappingSelectionExpression": "$request.basepath",
            "DomainName": "newApi.example.com",
            "DomainNameConfigurations": [
                {
                    "ApiGatewayDomainName": "d-5678.execute-api.us-west-2.amazonaws.com",
                    "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678",
                    "EndpointType": "REGIONAL",
                    "HostedZoneId": "123456789222",
                    "SecurityPolicy": "TLS_1_2",
                    "DomainNameStatus": "AVAILABLE"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomainNames](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-domain-names.html)」を参照してください。

### `get-integration`
<a name="apigatewayv2_GetIntegration_cli_2_topic"></a>

次のコード例は、`get-integration` を使用する方法を示しています。

**AWS CLI**  
**統合に関する情報を取得する方法**  
以下の `get-integration` の例では、統合に関する情報を表示します。  

```
aws apigatewayv2 get-integration \
    --api-id a1b2c3d4 \
    --integration-id a1b2c3
```
出力:  

```
{
    "ApiGatewayManaged": true,
    "ConnectionType": "INTERNET",
    "IntegrationId": "a1b2c3",
    "IntegrationMethod": "POST",
    "IntegrationType": "AWS_PROXY",
    "IntegrationUri": "arn:aws:lambda:us-west-2:12356789012:function:hello12",
    "PayloadFormatVersion": "2.0",
    "TimeoutInMillis": 30000
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html)」と「[WebSocket API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integrations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-integration.html)」を参照してください。

### `get-integrations`
<a name="apigatewayv2_GetIntegrations_cli_2_topic"></a>

次のコード例は、`get-integrations` を使用する方法を示しています。

**AWS CLI**  
**統合の一覧を取得する方法**  
次の `get-integrations` の例では、すべての API の統合の一覧を表示します。  

```
aws apigatewayv2 get-integrations \
    --api-id a1b2c3d4
```
出力:  

```
{
    "Items": [
        {
            "ApiGatewayManaged": true,
            "ConnectionType": "INTERNET",
            "IntegrationId": "a1b2c3",
            "IntegrationMethod": "POST",
            "IntegrationType": "AWS_PROXY",
            "IntegrationUri": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
            "PayloadFormatVersion": "2.0",
            "TimeoutInMillis": 30000
        },
        {
            "ConnectionType": "INTERNET",
            "IntegrationId": "a1b2c4",
            "IntegrationMethod": "ANY",
            "IntegrationType": "HTTP_PROXY",
            "IntegrationUri": "https://www.example.com",
            "PayloadFormatVersion": "1.0",
            "TimeoutInMillis": 30000
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html)」と「[WebSocket API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integrations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIntegrations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-integrations.html)」を参照してください。

### `get-route`
<a name="apigatewayv2_GetRoute_cli_2_topic"></a>

次のコード例は、`get-route` を使用する方法を示しています。

**AWS CLI**  
**ルートに関する情報を取得するには**  
以下の `get-route` の例では、ルートに関する情報を表示します。  

```
aws apigatewayv2 get-route \
    --api-id a1b2c3d4 \
    --route-id 72jz1wk
```
出力:  

```
{
    "ApiKeyRequired": false,
    "AuthorizationType": "NONE",
    "RouteId": "72jz1wk",
    "RouteKey": "ANY /pets",
    "Target": "integrations/a1b2c3"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-route.html)」を参照してください。

### `get-routes`
<a name="apigatewayv2_GetRoutes_cli_2_topic"></a>

次のコード例は、`get-routes` を使用する方法を示しています。

**AWS CLI**  
**ルートの一覧を取得する方法**  
次の `get-routes` の例では、API のすべてのルートの一覧を表示します。  

```
aws apigatewayv2 get-routes \
    --api-id a1b2c3d4
```
出力:  

```
{
    "Items": [
        {
            "ApiKeyRequired": false,
            "AuthorizationType": "NONE",
            "RouteId": "72jz1wk",
            "RouteKey": "ANY /admin",
            "Target": "integrations/a1b2c3"
        },
        {
            "ApiGatewayManaged": true,
            "ApiKeyRequired": false,
            "AuthorizationType": "NONE",
            "RouteId": "go65gqi",
            "RouteKey": "$default",
            "Target": "integrations/a1b2c4"
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRoutes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-routes.html)」を参照してください。

### `get-routing-rule`
<a name="apigatewayv2_GetRoutingRule_cli_2_topic"></a>

次のコード例は、`get-routing-rule` を使用する方法を示しています。

**AWS CLI**  
**ルーティングルールを取得するには**  
次の `get-routing-rule` の例では、ドメイン名のルーティングルールを取得します。  

```
aws apigatewayv2 get-routing-rule \
    --domain-name 'regional.example.com' \
    --routing-rule-id aaa111
```
出力:  

```
{
    "Actions": [
        {
            "InvokeApi": {
                "ApiId": "abcd1234",
                "Stage": "prod",
                "StripBasePath": false
            }
        }
    ],
    "Conditions": [
        {
            "MatchBasePaths": {
                "AnyOf": [
                    "PetStoreShopper"
                ]
            }
        }
    ],
    "Priority": 50,
    "RoutingRuleArn": "arn:aws:apigateway:us-east-2:123456789012:/domainnames/regional.example.com/routingrules/aaa111",
    "RoutingRuleId": "aaa111"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API ステージを REST API のカスタムドメイン名に接続するためのルーティングルール](https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-routing-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRoutingRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-routing-rule.html)」を参照してください。

### `get-stage`
<a name="apigatewayv2_GetStage_cli_2_topic"></a>

次のコード例は、`get-stage` を使用する方法を示しています。

**AWS CLI**  
**ステージに関する情報を取得するには**  
以下の `get-stage` の例では、API の `prod` ステージに関する情報を表示します。  

```
aws apigatewayv2 get-stage \
    --api-id a1b2c3d4 \
    --stage-name prod
```
出力:  

```
{
    "CreatedDate": "2020-04-08T00:36:05Z",
    "DefaultRouteSettings": {
        "DetailedMetricsEnabled": false
    },
    "DeploymentId": "x1zwyv",
    "LastUpdatedDate": "2020-04-08T00:36:13Z",
    "RouteSettings": {},
    "StageName": "prod",
    "StageVariables": {
        "function": "my-prod-function"
    },
    "Tags": {}
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-stage.html)」を参照してください。

### `get-stages`
<a name="apigatewayv2_GetStages_cli_2_topic"></a>

次のコード例は、`get-stages` を使用する方法を示しています。

**AWS CLI**  
**ステージの一覧を取得する方法**  
次の `get-stages` の例では、API のすべてのステージを一覧表示します。  

```
aws apigatewayv2 get-stages \
    --api-id a1b2c3d4
```
出力:  

```
{
    "Items": [
        {
            "ApiGatewayManaged": true,
            "AutoDeploy": true,
            "CreatedDate": "2020-04-08T00:08:44Z",
            "DefaultRouteSettings": {
                "DetailedMetricsEnabled": false
            },
            "DeploymentId": "dty748",
            "LastDeploymentStatusMessage": "Successfully deployed stage with deployment ID 'dty748'",
            "LastUpdatedDate": "2020-04-08T00:09:49Z",
            "RouteSettings": {},
            "StageName": "$default",
            "StageVariables": {},
            "Tags": {}
        },
        {
            "AutoDeploy": true,
            "CreatedDate": "2020-04-08T00:35:06Z",
            "DefaultRouteSettings": {
                "DetailedMetricsEnabled": false
            },
            "LastUpdatedDate": "2020-04-08T00:35:48Z",
            "RouteSettings": {},
            "StageName": "dev",
            "StageVariables": {
                "function": "my-dev-function"
            },
            "Tags": {}
        },
        {
            "CreatedDate": "2020-04-08T00:36:05Z",
            "DefaultRouteSettings": {
                "DetailedMetricsEnabled": false
            },
            "DeploymentId": "x1zwyv",
            "LastUpdatedDate": "2020-04-08T00:36:13Z",
            "RouteSettings": {},
            "StageName": "prod",
            "StageVariables": {
                "function": "my-prod-function"
            },
            "Tags": {}
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API のルートの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-stages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-stages.html)」を参照してください。

### `get-tags`
<a name="apigatewayv2_GetTags_cli_2_topic"></a>

次のコード例は、`get-tags` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグの一覧を取得する方法**  
次の `get-tags` の例では、API のすべてのタグを一覧表示します。  

```
aws apigatewayv2 get-tags \
    --resource-arn arn:aws:apigateway:us-west-2::/apis/a1b2c3d4
```
出力:  

```
{
    "Tags": {
        "owner": "dev-team",
        "environment": "prod"
    }
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway リソースのタグ付け](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-tags.html)」を参照してください。

### `get-vpc-link`
<a name="apigatewayv2_GetVpcLink_cli_2_topic"></a>

次のコード例は、`get-vpc-link` を使用する方法を示しています。

**AWS CLI**  
**VPC リンクに関する情報を取得する方法**  
以下の `get-vpc-link` の例では、VPC リンクに関する情報を表示します。  

```
aws apigatewayv2 get-vpc-link \
    --vpc-link-id abcd123
```
出力:  

```
{
    "CreatedDate": "2020-04-07T00:27:47Z",
    "Name": "MyVpcLink",
    "SecurityGroupIds": [
        "sg1234",
        "sg5678"
    ],
    "SubnetIds": [
        "subnet-aaaa",
        "subnet-bbbb"
    ],
    "Tags": {},
    "VpcLinkId": "abcd123",
    "VpcLinkStatus": "AVAILABLE",
    "VpcLinkStatusMessage": "VPC link is ready to route traffic",
    "VpcLinkVersion": "V2"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の VPC リンクの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vpc-links.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVpcLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-vpc-link.html)」を参照してください。

### `get-vpc-links`
<a name="apigatewayv2_GetVpcLinks_cli_2_topic"></a>

次のコード例は、`get-vpc-links` を使用する方法を示しています。

**AWS CLI**  
**VPC リンクの一覧を取得する方法**  
次の例 `get-vpc-links` では、現在のユーザーのすべての VPC リンクを一覧表示します。  

```
aws apigatewayv2 get-vpc-links
```
出力:  

```
{
    "Items": [
        {
            "CreatedDate": "2020-04-07T00:27:47Z",
            "Name": "MyVpcLink",
            "SecurityGroupIds": [
                "sg1234",
                "sg5678"
            ],
            "SubnetIds": [
                "subnet-aaaa",
                "subnet-bbbb"
            ],
            "Tags": {},
            "VpcLinkId": "abcd123",
            "VpcLinkStatus": "AVAILABLE",
            "VpcLinkStatusMessage": "VPC link is ready to route traffic",
            "VpcLinkVersion": "V2"
        }
        {
            "CreatedDate": "2020-04-07T00:27:47Z",
            "Name": "MyOtherVpcLink",
            "SecurityGroupIds": [
                "sg1234",
                "sg5678"
            ],
            "SubnetIds": [
                "subnet-aaaa",
                "subnet-bbbb"
            ],
            "Tags": {},
            "VpcLinkId": "abcd456",
            "VpcLinkStatus": "AVAILABLE",
            "VpcLinkStatusMessage": "VPC link is ready to route traffic",
            "VpcLinkVersion": "V2"
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の VPC リンクの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vpc-links.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVpcLinks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/get-vpc-links.html)」を参照してください。

### `import-api`
<a name="apigatewayv2_ImportApi_cli_2_topic"></a>

次のコード例は、`import-api` を使用する方法を示しています。

**AWS CLI**  
**HTTP API をインポートする方法**  
次の `import-api` の例では、「`api-definition.yaml`」という名前の OpenAPI 3.0 定義ファイルから HTTP API を作成します。  

```
aws apigatewayv2 import-api \
    --body file://api-definition.yaml
```
`api-definition.yaml` の内容:  

```
openapi: 3.0.1
info:
    title: My Lambda API
    version: v1.0
paths:
    /hello:
        x-amazon-apigateway-any-method:
            x-amazon-apigateway-integration:
                payloadFormatVersion: 2.0
                type: aws_proxy
                httpMethod: POST
                uri: arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:hello/invocations
                connectionType: INTERNET
```
出力:  

```
{
    "ApiEndpoint": "https://a1b2c3d4.execute-api.us-west-2.amazonaws.com",
    "ApiId": "a1b2c3d4",
    "ApiKeySelectionExpression": "$request.header.x-api-key",
    "CreatedDate": "2020-04-08T17:19:38+00:00",
    "Name": "My Lambda API",
    "ProtocolType": "HTTP",
    "RouteSelectionExpression": "$request.method $request.path",
    "Tags": {},
    "Version": "v1.0"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の OpenAPI 定義の使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-open-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/import-api.html)」を参照してください。

### `list-routing-rules`
<a name="apigatewayv2_ListRoutingRules_cli_2_topic"></a>

次のコード例は、`list-routing-rules` を使用する方法を示しています。

**AWS CLI**  
**ルーティングルールを一覧表示するには**  
次の `list-routing-rules` の例では、ドメイン名のルーティングルールを一覧表示します。  

```
aws apigatewayv2 list-routing-rules \
    --domain-name 'regional.example.com'
```
出力:  

```
{
    "RoutingRules": [
        {
            "Actions": [
                {
                    "InvokeApi": {
                        "ApiId": "abcd1234",
                        "Stage": "prod",
                        "StripBasePath": false
                    }
                }
            ],
            "Conditions": [
                {
                    "MatchBasePaths": {
                        "AnyOf": [
                            "PetStoreShopper"
                        ]
                    }
                }
            ],
            "Priority": 150,
            "RoutingRuleArn": "arn:aws:apigateway:us-east-1:123456789012:/domainnames/regional.example.com/routingrules/aaa111",
            "RoutingRuleId": "aaa111"
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API ステージを REST API のカスタムドメイン名に接続するためのルーティングルール](https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-routing-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoutingRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/list-routing-rules.html)」を参照してください。

### `put-routing-rule`
<a name="apigatewayv2_PutRoutingRule_cli_2_topic"></a>

次のコード例は、`put-routing-rule` を使用する方法を示しています。

**AWS CLI**  
**ルーティングルールを更新するには**  
次の `put-routing-rule` の例では、ルーティングルールの優先度を更新します。  

```
aws apigatewayv2 put-routing-rule \
    --domain-name 'regional.example.com' \
    --priority 150 \
    --conditions '[ \
        { \
            "MatchBasePaths": { \
                "AnyOf": [ \
                    "PetStoreShopper" \
                ] \
            } \
        } \
    ]' \
    --actions '[ \
        { \
            "InvokeApi": { \
                "ApiId": "abcd1234", \
                "Stage": "prod" \
            } \
        } \
    ]'
```
出力:  

```
{
    "Actions": [
        {
            "InvokeApi": {
                "ApiId": "abcd1234",
                "Stage": "prod",
                "StripBasePath": false
            }
        }
    ],
    "Conditions": [
        {
            "MatchBasePaths": {
                "AnyOf": [
                    "PetStoreShopper"
                ]
            }
        }
    ],
    "Priority": 150,
    "RoutingRuleArn": "arn:aws:apigateway:us-east-2:123456789012:/domainnames/regional.example.com/routingrules/aaa111",
    "RoutingRuleId": "aaa111"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API ステージを REST API のカスタムドメイン名に接続するためのルーティングルール](https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-routing-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRoutingRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/put-routing-rule.html)」を参照してください。

### `reimport-api`
<a name="apigatewayv2_ReimportApi_cli_2_topic"></a>

次のコード例は、`reimport-api` を使用する方法を示しています。

**AWS CLI**  
**HTTP API を再インポートする方法**  
次の `reimport-api` の例では、`api-definition.yaml` で指定された OpenAPI 3.0 定義を使用するように既存の HTTP API を更新します。  

```
aws apigatewayv2 reimport-api \
    --body file://api-definition.yaml \
    --api-id a1b2c3d4
```
`api-definition.yaml` の内容:  

```
openapi: 3.0.1
info:
    title: My Lambda API
    version: v1.0
paths:
    /hello:
        x-amazon-apigateway-any-method:
            x-amazon-apigateway-integration:
                payloadFormatVersion: 2.0
                type: aws_proxy
                httpMethod: POST
                uri: arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:12356789012:function:hello/invocations
                connectionType: INTERNET
```
出力:  

```
{
    "ApiEndpoint": "https://a1b2c3d4.execute-api.us-west-2.amazonaws.com",
    "ApiId": "a1b2c3d4",
    "ApiKeySelectionExpression": "$request.header.x-api-key",
    "CreatedDate": "2020-04-08T17:19:38+00:00",
    "Name": "My Lambda API",
    "ProtocolType": "HTTP",
    "RouteSelectionExpression": "$request.method $request.path",
    "Tags": {},
    "Version": "v1.0"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の OpenAPI 定義の使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-open-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReimportApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/reimport-api.html)」を参照してください。

### `tag-resource`
<a name="apigatewayv2_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグ付けする方法**  
次の `tag-resource` の例では、指定された API に「`Department`」のキー名と「`Accounting`」の値を持つタグを追加します。  

```
aws apigatewayv2 tag-resource \
    --resource-arn arn:aws:apigateway:us-west-2::/apis/a1b2c3d4 \
    --tags Department=Accounting
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway リソースのタグ付け](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="apigatewayv2_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除する**  
次の `untag-resource` の例では、キー名「`Project`」と「`Owner`」の含まれるタグを指定された API から削除します。  

```
aws apigatewayv2 untag-resource \
    --resource-arn arn:aws:apigateway:us-west-2::/apis/a1b2c3d4 \
    --tag-keys Project Owner
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway リソースのタグ付け](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/untag-resource.html)」を参照してください。

### `update-api-mapping`
<a name="apigatewayv2_UpdateApiMapping_cli_2_topic"></a>

次のコード例は、`update-api-mapping` を使用する方法を示しています。

**AWS CLI**  
**API マッピングを作成する方法**  
次の `update-api-mapping` の例では、カスタムドメイン名の API マッピングを変更します。その結果、指定された API とステージにカスタムドメイン名を使用するベース URL は `https://api.example.com/dev` になります。  

```
aws apigatewayv2 update-api-mapping \
    --api-id a1b2c3d4 \
    --stage dev \
    --domain-name api.example.com \
    --api-mapping-id 0qzs2sy7bh \
    --api-mapping-key dev
```
出力:  

```
{
    "ApiId": "a1b2c3d4",
    "ApiMappingId": "0qzs2sy7bh",
    "ApiMappingKey": "dev"
    "Stage": "dev"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApiMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-api-mapping.html)」を参照してください。

### `update-api`
<a name="apigatewayv2_UpdateApi_cli_2_topic"></a>

次のコード例は、`update-api` を使用する方法を示しています。

**AWS CLI**  
**HTTP API の CORS を有効にする方法**  
次の `update-api` の例では、指定された API の CORS 構成を更新して、`https://www.example.com` からのリクエストを許可します。  

```
aws apigatewayv2 update-api \
    --api-id a1b2c3d4 \
    --cors-configuration AllowOrigins=https://www.example.com
```
出力:  

```
{
    "ApiEndpoint": "https://a1b2c3d4.execute-api.us-west-2.amazonaws.com",
    "ApiId": "a1b2c3d4",
    "ApiKeySelectionExpression": "$request.header.x-api-key",
    "CorsConfiguration": {
        "AllowCredentials": false,
        "AllowHeaders": [
            "header1",
            "header2"
        ],
        "AllowMethods": [
            "GET",
            "OPTIONS"
        ],
        "AllowOrigins": [
            "https://www.example.com"
        ]
    },
    "CreatedDate": "2020-04-08T18:39:37+00:00",
    "Name": "my-http-api",
    "ProtocolType": "HTTP",
    "RouteSelectionExpression": "$request.method $request.path",
    "Tags": {},
    "Version": "v1.0"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API CORS の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-api.html)」を参照してください。

### `update-authorizer`
<a name="apigatewayv2_UpdateAuthorizer_cli_2_topic"></a>

次のコード例は、`update-authorizer` を使用する方法を示しています。

**AWS CLI**  
**オーソライザーを更新する方法**  
次の `update-authorizer` の例では、JWT オーソライザーの ID ソースを「`Authorization`」という名前のヘッダーに変更します。  

```
aws apigatewayv2 update-authorizer \
    --api-id a1b2c3d4 \
    --authorizer-id a1b2c3 \
    --identity-source '$request.header.Authorization'
```
出力:  

```
{
    "AuthorizerId": "a1b2c3",
    "AuthorizerType": "JWT",
    "IdentitySource": [
        "$request.header.Authorization"
    ],
    "JwtConfiguration": {
        "Audience": [
            "123456abc"
        ],
        "Issuer": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_abc123"
    },
    "Name": "my-jwt-authorizer"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[JWT オーソライザーを使用した HTTP API へのアクセスの制御](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-authorizer.html)」を参照してください。

### `update-deployment`
<a name="apigatewayv2_UpdateDeployment_cli_2_topic"></a>

次のコード例は、`update-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイの説明を変更する方法**  
次の `update-deployment` の例では、デプロイの説明を更新します。  

```
aws apigatewayv2 update-deployment \
    --api-id a1b2c3d4 \
    --deployment-id abcdef \
    --description 'Manual deployment to fix integration test failures.'
```
出力:  

```
{
    "AutoDeployed": false,
    "CreatedDate": "2020-02-05T16:21:48+00:00",
    "DeploymentId": "abcdef",
    "DeploymentStatus": "DEPLOYED",
    "Description": "Manual deployment to fix integration test failures."
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway での HTTP API の開発](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-deployment.html)」を参照してください。

### `update-domain-name`
<a name="apigatewayv2_UpdateDomainName_cli_2_topic"></a>

次のコード例は、`update-domain-name` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名を更新する方法**  
次の `update-domain-name` の例では、`api.example.com` カスタムドメイン名の新しい ACM 証明書を指定します。  

```
aws apigatewayv2 update-domain-name \
    --domain-name api.example.com \
    --domain-name-configurations CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678
```
出力:  

```
{
    "ApiMappingSelectionExpression": "$request.basepath",
    "DomainName": "regional.example.com",
    "DomainNameConfigurations": [
        {
            "ApiGatewayDomainName": "d-id.execute-api.us-west-2.amazonaws.com",
            "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678",
            "EndpointType": "REGIONAL",
            "HostedZoneId": "123456789111",
            "SecurityPolicy": "TLS_1_2",
            "DomainNameStatus": "AVAILABLE"
        }
    ]
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[API Gateway でリージョナルカスタムドメイン名を設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDomainName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-domain-name.html)」を参照してください。

### `update-integration`
<a name="apigatewayv2_UpdateIntegration_cli_2_topic"></a>

次のコード例は、`update-integration` を使用する方法を示しています。

**AWS CLI**  
**Lambda 統合を更新する方法**  
次の の`update-integration`例では、指定された AWS Lambda 関数を使用するように既存の Lambda 統合を更新します。  

```
aws apigatewayv2 update-integration \
    --api-id a1b2c3d4 \
    --integration-id a1b2c3 \
    --integration-uri arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:my-new-function/invocations
```
出力:  

```
{
    "ConnectionType": "INTERNET",
    "IntegrationId": "a1b2c3",
    "IntegrationMethod": "POST",
    "IntegrationType": "AWS_PROXY",
    "IntegrationUri": "arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:123456789012:function:my-new-function/invocations",
    "PayloadFormatVersion": "2.0",
    "TimeoutInMillis": 5000
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations.html)」と「[WebSocket API 統合の設定](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-integrations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIntegration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-integration.html)」を参照してください。

### `update-route`
<a name="apigatewayv2_UpdateRoute_cli_2_topic"></a>

次のコード例は、`update-route` を使用する方法を示しています。

**AWS CLI**  
**例 1: ルートの統合を更新する方法**  
次の `update-route` の例では、指定されたルートの統合を更新します。  

```
aws apigatewayv2 update-route \
    --api-id a1b2c3d4 \
    --route-id a1b2c3 \
    --target integrations/a1b2c6
```
出力:  

```
{
    "ApiKeyRequired": false,
    "AuthorizationType": "NONE",
    "RouteId": "a1b2c3",
    "RouteKey": "ANY /pets",
    "Target": "integrations/a1b2c6"
}
```
**例 2: ルートにオーソライザーを追加する方法**  
次の `update-route` の例では、指定されたルートを更新して、JWT オーソライザーを使用します。  

```
aws apigatewayv2 update-route \
    --api-id a1b2c3d4  \
    --route-id a1b2c3  \
    --authorization-type JWT \
    --authorizer-id a1b2c5 \
    --authorization-scopes user.id user.email
```
出力:  

```
{
    "ApiKeyRequired": false,
    "AuthorizationScopes": [
        "user.id",
        "user.email"
    ],
    "AuthorizationType": "JWT",
    "AuthorizerId": "a1b2c5",
    "OperationName": "GET HTTP",
    "RequestParameters": {},
    "RouteId": "a1b2c3",
    "RouteKey": "GET /pets",
    "Target": "integrations/a1b2c6"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[JWT オーソライザーを使用した HTTP API へのアクセスの制御](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-route.html)」を参照してください。

### `update-stage`
<a name="apigatewayv2_UpdateStage_cli_2_topic"></a>

次のコード例は、`update-stage` を使用する方法を示しています。

**AWS CLI**  
**カスタムスロットリングを設定する方法**  
次の `update-stage` の例は、API の指定されたステージとルートのカスタムスロットリングを設定します。  

```
aws apigatewayv2 update-stage \
    --api-id a1b2c3d4 \
    --stage-name dev \
    --route-settings '{"GET /pets":{"ThrottlingBurstLimit":100,"ThrottlingRateLimit":2000}}'
```
出力:  

```
{
    "CreatedDate": "2020-04-05T16:21:16+00:00",
    "DefaultRouteSettings": {
        "DetailedMetricsEnabled": false
    },
    "DeploymentId": "shktxb",
    "LastUpdatedDate": "2020-04-08T22:23:17+00:00",
    "RouteSettings": {
        "GET /pets": {
            "ThrottlingBurstLimit": 100,
            "ThrottlingRateLimit": 2000.0
        }
    },
    "StageName": "dev",
    "StageVariables": {},
    "Tags": {}
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の保護](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-protect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-stage.html)」を参照してください。

### `update-vpc-link`
<a name="apigatewayv2_UpdateVpcLink_cli_2_topic"></a>

次のコード例は、`update-vpc-link` を使用する方法を示しています。

**AWS CLI**  
**VPC リンクを更新する方法**  
次の `update-vpc-link` 例では、VPC リンクの名前を更新します。VPC リンクを作成した後は、そのセキュリティグループまたはサブネットを変更することはできません。  

```
aws apigatewayv2 update-vpc-link \
    --vpc-link-id abcd123 \
    --name MyUpdatedVpcLink
```
出力:  

```
{
    "CreatedDate": "2020-04-07T00:27:47Z",
    "Name": "MyUpdatedVpcLink",
    "SecurityGroupIds": [
        "sg1234",
        "sg5678"
    ],
    "SubnetIds": [
        "subnet-aaaa",
        "subnet-bbbb"
    ],
    "Tags": {},
    "VpcLinkId": "abcd123",
    "VpcLinkStatus": "AVAILABLE",
    "VpcLinkStatusMessage": "VPC link is ready to route traffic",
    "VpcLinkVersion": "V2"
}
```
詳細については、「*Amazon API Gateway デベロッパーガイド*」の「[HTTP API の VPC リンクの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-vpc-links.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVpcLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewayv2/update-vpc-link.html)」を参照してください。

# を使用した API Gateway Management API の例 AWS CLI
<a name="cli_2_apigatewaymanagementapi_code_examples"></a>

次のコード例は、API Gateway Management API AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-connection`
<a name="apigatewaymanagementapi_DeleteConnection_cli_2_topic"></a>

次の例では、`delete-connection` を使用する方法を説明しています。

**AWS CLI**  
**WebSocket 接続を削除する方法**  
次の `delete-connection` の例では、指定された WebSocket API からクライアントを切断します。  

```
aws apigatewaymanagementapi delete-connection \
    --connection-id L0SM9cOFvHcCIhw= \
    --endpoint-url https://aabbccddee.execute-api.us-west-2.amazonaws.com/prod
```
このコマンドでは何も出力されません。  
詳細については、「**Amazon API Gateway ディベロッパーガイド」の「[バックエンドサービスでの @connections コマンドの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewaymanagementapi/delete-connection.html)」を参照してください。

### `get-connection`
<a name="apigatewaymanagementapi_GetConnection_cli_2_topic"></a>

次の例では、`get-connection` を使用する方法を説明しています。

**AWS CLI**  
**WebSocket 接続に関する情報を取得する方法**  
次の `get-connection` 例では、指定された WebSocket API への接続について説明しています。  

```
aws apigatewaymanagementapi get-connection \
    --connection-id L0SM9cOFvHcCIhw= \
    --endpoint-url https://aabbccddee.execute-api.us-west-2.amazonaws.com/prod
```
出力:  

```
{
    "ConnectedAt": "2020-04-30T20:10:33.236Z",
    "Identity": {
        "SourceIp": "192.0.2.1"
    },
    "LastActiveAt": "2020-04-30T20:10:42.997Z"
}
```
詳細については、「**Amazon API Gateway ディベロッパーガイド」の「[バックエンドサービスでの @connections コマンドの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewaymanagementapi/get-connection.html)」を参照してください。

### `post-to-connection`
<a name="apigatewaymanagementapi_PostToConnection_cli_2_topic"></a>

次の例では、`post-to-connection` を使用する方法を説明しています。

**AWS CLI**  
**データを WebSocket 接続に送信する方法**  
次の `post-to-connection` の例では、指定した WebSocket API に接続しているクライアントにメッセージを送信します。  

```
aws apigatewaymanagementapi post-to-connection \
    --connection-id L0SM9cOFvHcCIhw= \
    --data "Hello from API Gateway!" \
    --endpoint-url https://aabbccddee.execute-api.us-west-2.amazonaws.com/prod
```
このコマンドでは何も出力されません。  
詳細については、「**Amazon API Gateway ディベロッパーガイド」の「[バックエンドサービスでの @connections コマンドの使用](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PostToConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apigatewaymanagementapi/post-to-connection.html)」を参照してください。**

# を使用した App Mesh の例 AWS CLI
<a name="cli_2_app-mesh_code_examples"></a>

次のコード例は、App Mesh AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-mesh`
<a name="app-mesh_CreateMesh_cli_2_topic"></a>

次のコード例は、`create-mesh` を使用する方法を示しています。

**AWS CLI**  
**例 1: 新しいサービスメッシュを作成する方法**  
次の `create-mesh` の例では、サービスメッシュを作成します。  

```
aws appmesh create-mesh \
    --mesh-name app1
```
出力:  

```
{
    "mesh":{
        "meshName":"app1",
        "metadata":{
            "arn":"arn:aws:appmesh:us-east-1:123456789012:mesh/app1",
            "createdAt":1563809909.282,
            "lastUpdatedAt":1563809909.282,
            "uid":"a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version":1
        },
        "spec":{},
        "status":{
            "status":"ACTIVE"
        }
    }
}
```
**例 2: 複数のタグを含む新しいサービスメッシュを作成する方法**  
次の `create-mesh` の例は、複数のタグを含むサービスメッシュを作成します。  

```
aws appmesh create-mesh \
    --mesh-name app2 \
    --tags key=key1,value=value1 key=key2,value=value2 key=key3,value=value3
```
出力:  

```
{
    "mesh":{
        "meshName":"app2",
        "metadata":{
            "arn":"arn:aws:appmesh:us-east-1:123456789012:mesh/app2",
            "createdAt":1563822121.877,
            "lastUpdatedAt":1563822121.877,
            "uid":"a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version":1
        },
        "spec":{},
        "status":{
            "status":"ACTIVE"
        }
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[サービスメッシュ](https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMesh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/create-mesh.html)」を参照してください。

### `create-route`
<a name="app-mesh_CreateRoute_cli_2_topic"></a>

次のコード例は、`create-route` を使用する方法を示しています。

**AWS CLI**  
**新しい gRPC ルートを作成する方法**  
次の `create-route` の例では、JSON 入力ファイルを使用して gRPC ルートを作成します。123 で始まるメタデータを持つ GRPC トラフィックは、serviceBgrpc という名前の仮想ノードにルーティングされます。ルートのターゲットと通信しようとしたときに特定の gRPC、HTTP、または TCP の障害が発生した場合、ルートは 3 回再試行されます。再試行するたびに 15 秒の遅延が発生します。  

```
aws appmesh create-route \
    --cli-input-json file://create-route-grpc.json
```
`create-route-grpc.json` の内容:  

```
{
    "meshName" : "apps",
    "routeName" : "grpcRoute",
    "spec" : {
       "grpcRoute" : {
          "action" : {
             "weightedTargets" : [
                {
                   "virtualNode" : "serviceBgrpc",
                   "weight" : 100
                }
             ]
          },
          "match" : {
             "metadata" : [
                {
                   "invert" : false,
                   "match" : {
                      "prefix" : "123"
                   },
                   "name" : "myMetadata"
                }
             ],
             "methodName" : "GetColor",
             "serviceName" : "com.amazonaws.services.ColorService"
          },
          "retryPolicy" : {
             "grpcRetryEvents" : [ "deadline-exceeded" ],
             "httpRetryEvents" : [ "server-error", "gateway-error" ],
             "maxRetries" : 3,
             "perRetryTimeout" : {
                "unit" : "s",
                "value" : 15
             },
             "tcpRetryEvents" : [ "connection-error" ]
          }
       },
       "priority" : 100
    },
    "virtualRouterName" : "serviceBgrpc"
}
```
出力:  

```
{
    "route": {
        "meshName": "apps",
        "metadata": {
            "arn": "arn:aws:appmesh:us-west-2:123456789012:mesh/apps/virtualRouter/serviceBgrpc/route/grpcRoute",
            "createdAt": 1572010806.008,
            "lastUpdatedAt": 1572010806.008,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "routeName": "grpcRoute",
        "spec": {
            "grpcRoute": {
                "action": {
                    "weightedTargets": [
                        {
                            "virtualNode": "serviceBgrpc",
                            "weight": 100
                        }
                    ]
                },
                "match": {
                    "metadata": [
                        {
                            "invert": false,
                            "match": {
                                "prefix": "123"
                            },
                            "name": "mymetadata"
                        }
                    ],
                    "methodName": "GetColor",
                    "serviceName": "com.amazonaws.services.ColorService"
                },
                "retryPolicy": {
                    "grpcRetryEvents": [
                        "deadline-exceeded"
                    ],
                    "httpRetryEvents": [
                        "server-error",
                        "gateway-error"
                    ],
                    "maxRetries": 3,
                    "perRetryTimeout": {
                        "unit": "s",
                        "value": 15
                    },
                    "tcpRetryEvents": [
                        "connection-error"
                    ]
                }
            },
            "priority": 100
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "serviceBgrpc"
    }
}
```
**新しい HTTP または HTTP/2 ルートを作成する方法**  
次の `create-route` の例では、JSON 入力ファイルを使用して HTTP/2 ルートを作成します。HTTP ルートを作成するには、http2Route を仕様の httpRoute に置き換えます。123 で始まるヘッダー値を持つ URL プレフィックス宛てのすべての HTTP/2 トラフィックは、serviceBhttp2 という名前の仮想ノードにルーティングされます。ルートのターゲットと通信しようとしたときに特定の HTTP または TCP の障害が発生した場合、ルートは 3 回再試行されます。再試行するたびに 15 秒の遅延が発生します。  

```
aws appmesh create-route \
    --cli-input-json file://create-route-http2.json
```
`create-route-http2.json` の内容:  

```
{
    "meshName": "apps",
    "routeName": "http2Route",
    "spec": {
        "http2Route": {
            "action": {
                "weightedTargets": [
                    {
                        "virtualNode": "serviceBhttp2",
                        "weight": 100
                    }
                ]
            },
            "match": {
                "headers": [
                    {
                        "invert": false,
                        "match": {
                            "prefix": "123"
                        },
                        "name": "clientRequestId"
                    }
                ],
                "method": "POST",
                "prefix": "/",
                "scheme": "http"
            },
            "retryPolicy": {
                "httpRetryEvents": [
                    "server-error",
                    "gateway-error"
                ],
                "maxRetries": 3,
                "perRetryTimeout": {
                    "unit": "s",
                    "value": 15
                },
                "tcpRetryEvents": [
                    "connection-error"
                ]
            }
        },
        "priority": 200
    },
    "virtualRouterName": "serviceBhttp2"
}
```
出力:  

```
{
    "route": {
        "meshName": "apps",
        "metadata": {
            "arn": "arn:aws:appmesh:us-west-2:123456789012:mesh/apps/virtualRouter/serviceBhttp2/route/http2Route",
            "createdAt": 1572011008.352,
            "lastUpdatedAt": 1572011008.352,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "routeName": "http2Route",
        "spec": {
            "http2Route": {
                "action": {
                    "weightedTargets": [
                        {
                            "virtualNode": "serviceBhttp2",
                            "weight": 100
                        }
                    ]
                },
                "match": {
                    "headers": [
                        {
                            "invert": false,
                            "match": {
                                "prefix": "123"
                            },
                            "name": "clientRequestId"
                        }
                    ],
                    "method": "POST",
                    "prefix": "/",
                    "scheme": "http"
                },
                "retryPolicy": {
                    "httpRetryEvents": [
                        "server-error",
                        "gateway-error"
                    ],
                    "maxRetries": 3,
                    "perRetryTimeout": {
                        "unit": "s",
                        "value": 15
                    },
                    "tcpRetryEvents": [
                        "connection-error"
                    ]
                }
            },
            "priority": 200
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "serviceBhttp2"
    }
}
```
**新しい TCP ルートを作成する方法**  
次の `create-route` の例では、JSON 入力ファイルを使用して TCP ルートを作成します。トラフィックの 75% は serviceBtcp という名前の仮想ノードにルーティングされ、トラフィックの 25% は serviceBv2tcp という名前の仮想ノードにルーティングされます。ターゲットごとに異なる重みを指定することは、アプリケーションの新しいバージョンのデプロイを実行する効果的な方法です。重みを調整して、最終的にすべてのトラフィックの 100% がアプリケーションの新しいバージョンを持つターゲットにルーティングされるようにできます。  

```
aws appmesh create-route \
    --cli-input-json file://create-route-tcp.json
```
create-route-tcp.json の内容:  

```
{
    "meshName": "apps",
    "routeName": "tcpRoute",
    "spec": {
        "priority": 300,
        "tcpRoute": {
            "action": {
                "weightedTargets": [
                    {
                        "virtualNode": "serviceBtcp",
                        "weight": 75
                    },
                    {
                        "virtualNode": "serviceBv2tcp",
                        "weight": 25
                    }
                ]
            }
        }
    },
    "virtualRouterName": "serviceBtcp"
}
```
出力:  

```
{
    "route": {
        "meshName": "apps",
        "metadata": {
            "arn": "arn:aws:appmesh:us-west-2:123456789012:mesh/apps/virtualRouter/serviceBtcp/route/tcpRoute",
            "createdAt": 1572011436.26,
            "lastUpdatedAt": 1572011436.26,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "routeName": "tcpRoute",
        "spec": {
            "priority": 300,
            "tcpRoute": {
                "action": {
                    "weightedTargets": [
                        {
                            "virtualNode": "serviceBtcp",
                            "weight": 75
                        },
                        {
                            "virtualNode": "serviceBv2tcp",
                            "weight": 25
                        }
                    ]
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "serviceBtcp"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[ルート](https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/create-route.html)」を参照してください。

### `create-virtual-gateway`
<a name="app-mesh_CreateVirtualGateway_cli_2_topic"></a>

次のコード例は、`create-virtual-gateway` を使用する方法を示しています。

**AWS CLI**  
**仮想ゲートウェイを作成する方法**  
次の `create-virtual-gateway` の例では、JSON 入力ファイルを使用して、ポート 9080 を使用して HTTP のリスナーを持つ仮想ゲートウェイを作成します。  

```
aws appmesh create-virtual-gateway \
    --mesh-name meshName \
    --virtual-gateway-name virtualGatewayName \
    --cli-input-json file://create-virtual-gateway.json
```
`create-virtual-gateway.json` の内容:  

```
{
    "spec": {
      "listeners": [
        {
          "portMapping": {
            "port": 9080,
            "protocol": "http"
          }
        }
      ]
    }
}
```
出力:  

```
{
    "virtualGateway": {
        "meshName": "meshName",
        "metadata": {
            "arn": "arn:aws:appmesh:us-west-2:123456789012:mesh/meshName/virtualGateway/virtualGatewayName",
            "createdAt": "2022-04-06T10:42:42.015000-05:00",
            "lastUpdatedAt": "2022-04-06T10:42:42.015000-05:00",
            "meshOwner": "123456789012",
            "resourceOwner": "123456789012",
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "listeners": [
                {
                    "portMapping": {
                        "port": 9080,
                        "protocol": "http"
                    }
                }
            ]
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualGatewayName": "virtualGatewayName"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ゲートウェイ](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVirtualGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/create-virtual-gateway.html)」を参照してください。

### `create-virtual-node`
<a name="app-mesh_CreateVirtualNode_cli_2_topic"></a>

次のコード例は、`create-virtual-node` を使用する方法を示しています。

**AWS CLI**  
**例 1: 検出に DNS を使用する新しい仮想ノードを作成する方法**  
次の `create-virtual-node` の例では、JSON 入力ファイルを使用して、サービス検出に DNS を使用する仮想ノードを作成します。  

```
aws appmesh create-virtual-node \
    --cli-input-json file://create-virtual-node-dns.json
```
`create-virtual-node-dns.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "listeners": [
            {
                "portMapping": {
                    "port": 80,
                    "protocol": "http"
                }
            }
        ],
        "serviceDiscovery": {
            "dns": {
                "hostname": "serviceBv1.svc.cluster.local"
            }
        }
    },
    "virtualNodeName": "vnServiceBv1"
}
```
出力:  

```
{
    "virtualNode": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualNode/vnServiceBv1",
            "createdAt": 1563810019.874,
            "lastUpdatedAt": 1563810019.874,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "listeners": [
                {
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ],
            "serviceDiscovery": {
                "dns": {
                    "hostname": "serviceBv1.svc.cluster.local"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualNodeName": "vnServiceBv1"
    }
}
```
**例 2: 検出に AWS Cloud Map を使用する新しい仮想ノードを作成するには**  
次の`create-virtual-node`例では、JSON 入力ファイルを使用して、サービス検出に AWS Cloud Map を使用する仮想ノードを作成します。  

```
aws appmesh create-virtual-node \
    --cli-input-json file://create-virtual-node-cloud-map.json
```
`create-virtual-node-cloud-map.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "backends": [
            {
                "virtualService": {
                    "virtualServiceName": "serviceA.svc.cluster.local"
                }
            }
        ],
        "listeners": [
            {
                "portMapping": {
                    "port": 80,
                    "protocol": "http"
                }
            }
        ],
        "serviceDiscovery": {
            "awsCloudMap": {
                "attributes": [
                    {
                        "key": "Environment",
                        "value": "Testing"
                    }
                ],
                "namespaceName": "namespace1",
                "serviceName": "serviceA"
            }
        }
    },
    "virtualNodeName": "vnServiceA"
}
```
出力:  

```
{
    "virtualNode": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualNode/vnServiceA",
            "createdAt": 1563810859.465,
            "lastUpdatedAt": 1563810859.465,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "backends": [
                {
                    "virtualService": {
                        "virtualServiceName": "serviceA.svc.cluster.local"
                    }
                }
            ],
            "listeners": [
                {
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ],
            "serviceDiscovery": {
                "awsCloudMap": {
                    "attributes": [
                        {
                            "key": "Environment",
                            "value": "Testing"
                        }
                    ],
                    "namespaceName": "namespace1",
                    "serviceName": "serviceA"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualNodeName": "vnServiceA"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ノード](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVirtualNode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/create-virtual-node.html)」を参照してください。

### `create-virtual-router`
<a name="app-mesh_CreateVirtualRouter_cli_2_topic"></a>

次のコード例は、`create-virtual-router` を使用する方法を示しています。

**AWS CLI**  
**仮想ルーターを作成する方法**  
次の `create-virtual-router` の例では、JSON 入力ファイルを使用して、ポート 80 を使用して HTTP のリスナーを持つ仮想ルーターを作成します。  

```
aws appmesh create-virtual-router \
    --cli-input-json file://create-virtual-router.json
```
`create-virtual-router.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "listeners": [
            {
                "portMapping": {
                    "port": 80,
                    "protocol": "http"
                }
            }
        ]
    },
    "virtualRouterName": "vrServiceB"
}
```
出力:  

```
{
    "virtualRouter": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB",
            "createdAt": 1563810546.59,
            "lastUpdatedAt": 1563810546.59,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "listeners": [
                {
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ]
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "vrServiceB"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ルーター](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVirtualRouter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/create-virtual-router.html)」を参照してください。

### `create-virtual-service`
<a name="app-mesh_CreateVirtualService_cli_2_topic"></a>

次のコード例は、`create-virtual-service` を使用する方法を示しています。

**AWS CLI**  
**例 1: 仮想ノードプロバイダーを使用して新しい仮想サービスを作成する方法**  
次の `create-virtual-service` の例では、JSON 入力ファイルを使用し、仮想ノードプロバイダーを使用して仮想サービスを作成します。  

```
aws appmesh create-virtual-service \
    --cli-input-json file://create-virtual-service-virtual-node.json
```
`create-virtual-service-virtual-node.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "provider": {
            "virtualNode": {
                "virtualNodeName": "vnServiceA"
            }
        }
    },
    "virtualServiceName": "serviceA.svc.cluster.local"
}
```
出力:  

```
{
    "virtualService": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualService/serviceA.svc.cluster.local",
            "createdAt": 1563810859.474,
            "lastUpdatedAt": 1563810967.179,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 2
        },
        "spec": {
            "provider": {
                "virtualNode": {
                    "virtualNodeName": "vnServiceA"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualServiceName": "serviceA.svc.cluster.local"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ノード](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html)」を参照してください。  
**例 2: 仮想ルータープロバイダーを使用して新しい仮想サービスを作成する方法**  
次の `create-virtual-service` の例では、JSON 入力ファイルを使用し、仮想ルータープロバイダーを使用して仮想サービスを作成します。  

```
aws appmesh create-virtual-service \
    --cli-input-json file://create-virtual-service-virtual-router.json
```
`create-virtual-service-virtual-router.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "provider": {
            "virtualRouter": {
                "virtualRouterName": "vrServiceB"
            }
        }
    },
    "virtualServiceName": "serviceB.svc.cluster.local"
}
```
出力:  

```
{
    "virtualService": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualService/serviceB.svc.cluster.local",
            "createdAt": 1563908363.999,
            "lastUpdatedAt": 1563908363.999,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "provider": {
                "virtualRouter": {
                    "virtualRouterName": "vrServiceB"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualServiceName": "serviceB.svc.cluster.local"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「仮想サービス<https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual\$1services.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVirtualService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/create-virtual-service.html)」を参照してください。

### `delete-mesh`
<a name="app-mesh_DeleteMesh_cli_2_topic"></a>

次のコード例は、`delete-mesh` を使用する方法を示しています。

**AWS CLI**  
**サービスメッシュを削除する方法**  
次の `delete-mesh` の例では、指定されたサービスメッシュを削除します。  

```
aws appmesh delete-mesh \
    --mesh-name app1
```
出力:  

```
{
    "mesh": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1",
            "createdAt": 1563809909.282,
            "lastUpdatedAt": 1563824981.248,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 2
        },
        "spec": {
            "egressFilter": {
                "type": "ALLOW_ALL"
            }
        },
        "status": {
            "status": "DELETED"
        }
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[サービスメッシュ](https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMesh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/delete-mesh.html)」を参照してください。

### `delete-route`
<a name="app-mesh_DeleteRoute_cli_2_topic"></a>

次のコード例は、`delete-route` を使用する方法を示しています。

**AWS CLI**  
**ルートを削除する方法**  
以下の `delete-route` 例では、指定されたルートを削除します。  

```
aws appmesh delete-route \
    --mesh-name app1 \
    --virtual-router-name vrServiceB \
    --route-name toVnServiceB-weighted
```
出力:  

```
{
    "route": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB/route/toVnServiceB-weighted",
            "createdAt": 1563811384.015,
            "lastUpdatedAt": 1563823915.936,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 3
        },
        "routeName": "toVnServiceB-weighted",
        "spec": {
            "httpRoute": {
                "action": {
                    "weightedTargets": [
                        {
                            "virtualNode": "vnServiceBv1",
                            "weight": 80
                        },
                        {
                            "virtualNode": "vnServiceBv2",
                            "weight": 20
                        }
                    ]
                },
                "match": {
                    "prefix": "/"
                }
            }
        },
        "status": {
            "status": "DELETED"
        },
        "virtualRouterName": "vrServiceB"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[ルート](https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/delete-route.html)」を参照してください。

### `delete-virtual-node`
<a name="app-mesh_DeleteVirtualNode_cli_2_topic"></a>

次のコード例は、`delete-virtual-node` を使用する方法を示しています。

**AWS CLI**  
**仮想ノードを削除する方法**  
以下の `delete-virtual-node` 例では、指定された仮想ノードを削除します。  

```
aws appmesh delete-virtual-node \
    --mesh-name app1 \
    --virtual-node-name vnServiceBv2
```
出力:  

```
{
    "virtualNode": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualNode/vnServiceBv2",
            "createdAt": 1563810117.297,
            "lastUpdatedAt": 1563824700.678,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 2
        },
        "spec": {
            "backends": [],
            "listeners": [
                {
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ],
            "serviceDiscovery": {
                "dns": {
                    "hostname": "serviceBv2.svc.cluster.local"
                }
            }
        },
        "status": {
            "status": "DELETED"
        },
        "virtualNodeName": "vnServiceBv2"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ノード](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVirtualNode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/delete-virtual-node.html)」を参照してください。

### `delete-virtual-router`
<a name="app-mesh_DeleteVirtualRouter_cli_2_topic"></a>

次のコード例は、`delete-virtual-router` を使用する方法を示しています。

**AWS CLI**  
**仮想ルーターを削除する方法**  
以下の `delete-virtual-router` 例では、指定された仮想ルーターを削除します。  

```
aws appmesh delete-virtual-router \
    --mesh-name app1 \
    --virtual-router-name vrServiceB
```
出力:  

```
{
    "virtualRouter": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB",
            "createdAt": 1563810546.59,
            "lastUpdatedAt": 1563824253.467,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 3
        },
        "spec": {
            "listeners": [
                {
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ]
        },
        "status": {
            "status": "DELETED"
        },
        "virtualRouterName": "vrServiceB"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ルーター](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVirtualRouter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/delete-virtual-router.html)」を参照してください。

### `delete-virtual-service`
<a name="app-mesh_DeleteVirtualService_cli_2_topic"></a>

次のコード例は、`delete-virtual-service` を使用する方法を示しています。

**AWS CLI**  
**仮想サービスを削除する方法**  
以下の `delete-virtual-service` の例では、指定された仮想ノードを削除します。  

```
aws appmesh delete-virtual-service \
    --mesh-name app1 \
    --virtual-service-name serviceB.svc.cluster.local
```
出力:  

```
{
    "virtualService": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualService/serviceB.svc.cluster.local",
            "createdAt": 1563908363.999,
            "lastUpdatedAt": 1563913940.866,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 3
        },
        "spec": {},
        "status": {
            "status": "DELETED"
        },
        "virtualServiceName": "serviceB.svc.cluster.local"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想サービス](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVirtualService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/delete-virtual-service.html)」を参照してください。

### `describe-mesh`
<a name="app-mesh_DescribeMesh_cli_2_topic"></a>

次のコード例は、`describe-mesh` を使用する方法を示しています。

**AWS CLI**  
**サービスメッシュを記述する方法**  
次の `describe-mesh` の例では、指定されたサービスメッシュに関する詳細情報を取得します。  

```
aws appmesh describe-mesh \
    --mesh-name app1
```
出力:  

```
{
    "mesh": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1",
            "createdAt": 1563809909.282,
            "lastUpdatedAt": 1563809909.282,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {},
        "status": {
            "status": "ACTIVE"
        }
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[サービスメッシュ](https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMesh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/describe-mesh.html)」を参照してください。

### `describe-route`
<a name="app-mesh_DescribeRoute_cli_2_topic"></a>

次のコード例は、`describe-route` を使用する方法を示しています。

**AWS CLI**  
**ルートを記述する方法**  
次の `describe-route` の例では、指定されたルートの詳細情報を返します。  

```
aws appmesh describe-route \
    --mesh-name app1 \
    --virtual-router-name vrServiceB \
    --route-name toVnServiceB-weighted
```
出力:  

```
{
    "route": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB/route/toVnServiceB-weighted",
            "createdAt": 1563811384.015,
            "lastUpdatedAt": 1563811384.015,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "routeName": "toVnServiceB-weighted",
        "spec": {
            "httpRoute": {
                "action": {
                    "weightedTargets": [
                        {
                            "virtualNode": "vnServiceBv1",
                            "weight": 90
                        },
                        {
                            "virtualNode": "vnServiceBv2",
                            "weight": 10
                        }
                    ]
                },
                "match": {
                    "prefix": "/"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "vrServiceB"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[ルート](https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/describe-route.html)」を参照してください。

### `describe-virtual-node`
<a name="app-mesh_DescribeVirtualNode_cli_2_topic"></a>

次のコード例は、`describe-virtual-node` を使用する方法を示しています。

**AWS CLI**  
**仮想ノードを記述する方法**  
次の `describe-virtual-node` の例では、指定されたバーチャルノードの詳細情報を返します。  

```
aws appmesh describe-virtual-node \
    --mesh-name app1 \
    --virtual-node-name vnServiceBv1
```
出力:  

```
{
    "virtualNode": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualNode/vnServiceBv1",
            "createdAt": 1563810019.874,
            "lastUpdatedAt": 1563810019.874,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "backends": [],
            "listeners": [
                {
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ],
            "serviceDiscovery": {
                "dns": {
                    "hostname": "serviceBv1.svc.cluster.local"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualNodeName": "vnServiceBv1"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ノード](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVirtualNode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/describe-virtual-node.html)」を参照してください。

### `describe-virtual-router`
<a name="app-mesh_DescribeVirtualRouter_cli_2_topic"></a>

次のコード例は、`describe-virtual-router` を使用する方法を示しています。

**AWS CLI**  
**仮想ルーターを記述する方法**  
次の `describe-virtual-router` の例では、指定された仮想ルーターの詳細情報を返します。  

```
aws appmesh describe-virtual-router \
    --mesh-name app1 \
    --virtual-router-name vrServiceB
```
出力:  

```
{
    "virtualRouter": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB",
            "createdAt": 1563810546.59,
            "lastUpdatedAt": 1563810546.59,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "listeners": [
                {
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ]
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "vrServiceB"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ルーター](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeVirtualRouter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/describe-virtual-router.html)」を参照してください。

### `describe-virtual-service`
<a name="app-mesh_DescribeVirtualService_cli_2_topic"></a>

次のコード例は、`describe-virtual-service` を使用する方法を示しています。

**AWS CLI**  
**仮想サービスを記述する方法**  
次の `describe-virtual-service` の例では、指定されたバーチャルサービスに関する詳細情報を返します。  

```
aws appmesh describe-virtual-service \
    --mesh-name app1 \
    --virtual-service-name serviceB.svc.cluster.local
```
出力:  

```
{
    "virtualService": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualService/serviceB.svc.cluster.local",
            "createdAt": 1563908363.999,
            "lastUpdatedAt": 1563908363.999,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 1
        },
        "spec": {
            "provider": {
                "virtualRouter": {
                    "virtualRouterName": "vrServiceB"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualServiceName": "serviceB.svc.cluster.local"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想サービス](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVirtualService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/describe-virtual-service.html)」を参照してください。

### `list-meshes`
<a name="app-mesh_ListMeshes_cli_2_topic"></a>

次のコード例は、`list-meshes` を使用する方法を示しています。

**AWS CLI**  
**サービスメッシュを一覧表示する方法**  
次の の`list-meshes`例では、現在の AWS リージョンのすべてのサービスメッシュを一覧表示します。  

```
aws appmesh list-meshes
```
出力:  

```
{
    "meshes": [
        {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1",
            "meshName": "app1"
        }
    ]
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[サービスメッシュ](https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMeshes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/list-meshes.html)」を参照してください。

### `list-routes`
<a name="app-mesh_ListRoutes_cli_2_topic"></a>

次のコード例は、`list-routes` を使用する方法を示しています。

**AWS CLI**  
**ルートを一覧表示する方法**  
次の `list-routes` の例では、指定された仮想ルーターのすべてのルートを一覧表示します。  

```
aws appmesh list-routes \
    --mesh-name app1 \
    --virtual-router-name vrServiceB
```
出力:  

```
{
    "routes": [
        {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB/route/toVnServiceB",
            "meshName": "app1",
            "routeName": "toVnServiceB-weighted",
            "virtualRouterName": "vrServiceB"
        }
    ]
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[ルート](https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoutes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/list-routes.html)」を参照してください。

### `list-tags-for-resource`
<a name="app-mesh_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示する方法**  
次の `list-tags-for-resource` の例では、指定されたリソースに割り当てられたすべてのタグを一覧表示します。  

```
aws appmesh list-tags-for-resource \
    --resource-arn arn:aws:appmesh:us-east-1:123456789012:mesh/app1
```
出力:  

```
{
    "tags": [
        {
            "key": "key1",
            "value": "value1"
        },
        {
            "key": "key2",
            "value": "value2"
        },
        {
            "key": "key3",
            "value": "value3"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/list-tags-for-resource.html)」を参照してください。

### `list-virtual-nodes`
<a name="app-mesh_ListVirtualNodes_cli_2_topic"></a>

次のコード例は、`list-virtual-nodes` を使用する方法を示しています。

**AWS CLI**  
**仮想ノードを一覧表示する方法**  
次の `list-virtual-nodes` の例では、指定されたサービスメッシュ内のすべての仮想ノードを一覧表示します。  

```
aws appmesh list-virtual-nodes \
    --mesh-name app1
```
出力:  

```
{
    "virtualNodes": [
        {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualNode/vnServiceBv1",
            "meshName": "app1",
            "virtualNodeName": "vnServiceBv1"
        },
        {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualNode/vnServiceBv2",
            "meshName": "app1",
            "virtualNodeName": "vnServiceBv2"
        }
    ]
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ノード](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVirtualNodes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/list-virtual-nodes.html)」を参照してください。

### `list-virtual-routers`
<a name="app-mesh_ListVirtualRouters_cli_2_topic"></a>

次のコード例は、`list-virtual-routers` を使用する方法を示しています。

**AWS CLI**  
**仮想ルーターを一覧表示する方法**  
次の `list-virtual-routers` の例では、指定されたサービスメッシュ内のすべての仮想ルーターを一覧表示します。  

```
aws appmesh list-virtual-routers \
    --mesh-name app1
```
出力:  

```
{
    "virtualRouters": [
        {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB",
            "meshName": "app1",
            "virtualRouterName": "vrServiceB"
        }
    ]
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ルーター](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVirtualRouters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/list-virtual-routers.html)」を参照してください。

### `list-virtual-services`
<a name="app-mesh_ListVirtualServices_cli_2_topic"></a>

次のコード例は、`list-virtual-services` を使用する方法を示しています。

**AWS CLI**  
**仮想サービスを一覧表示する方法**  
次の `list-virtual-services` の例では、指定されたサービスメッシュ内のすべての仮想サービスを一覧表示します。  

```
aws appmesh list-virtual-services \
    --mesh-name app1
```
出力:  

```
{
    "virtualServices": [
        {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualService/serviceA.svc.cluster.local",
            "meshName": "app1",
            "virtualServiceName": "serviceA.svc.cluster.local"
        },
        {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualService/serviceB.svc.cluster.local",
            "meshName": "app1",
            "virtualServiceName": "serviceB.svc.cluster.local"
        }
    ]
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想サービス](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVirtualServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/list-virtual-services.html)」を参照してください。

### `tag-resource`
<a name="app-mesh_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグ付けする方法**  
次の `tag-resource` の例では、指定されたリソースに値「`value1`」のタグ「`key1`」を追加します。  

```
aws appmesh tag-resource \
    --resource-arn arn:aws:appmesh:us-east-1:123456789012:mesh/app1 \
    --tags key=key1,value=value1
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="app-mesh_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを削除する方法**  
次の `untag-resource` の例では、指定されたリソースから「`key1`」のキーを持つタグを削除します。  

```
aws appmesh untag-resource \
    --resource-arn arn:aws:appmesh:us-east-1:123456789012:mesh/app1 \
    --tag-keys key1
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/untag-resource.html)」を参照してください。

### `update-mesh`
<a name="app-mesh_UpdateMesh_cli_2_topic"></a>

次のコード例は、`update-mesh` を使用する方法を示しています。

**AWS CLI**  
**サービスメッシュを更新する方法**  
次の `update-mesh` の例では、JSON 入力ファイルを使用してサービスメッシュを更新し、すべての外部エグレストラフィックを Envoy プロキシを介してそのまま転送できるようにします。  

```
aws appmesh update-mesh \
    --cli-input-json file://update-mesh.json
```
`update-mesh.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "egressFilter": {
            "type": "ALLOW_ALL"
        }
    }
}
```
出力:  

```
{
    "mesh": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1",
            "createdAt": 1563809909.282,
            "lastUpdatedAt": 1563812829.687,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 2
        },
        "spec": {
            "egressFilter": {
                "type": "ALLOW_ALL"
            }
        },
        "status": {
            "status": "ACTIVE"
        }
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[サービスメッシュ](https://docs.aws.amazon.com/app-mesh/latest/userguide/meshes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMesh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/update-mesh.html)」を参照してください。

### `update-route`
<a name="app-mesh_UpdateRoute_cli_2_topic"></a>

次のコード例は、`update-route` を使用する方法を示しています。

**AWS CLI**  
**ルートを更新する方法**  
次の `update-route` の例では、JSON 入力ファイルを使用してルートの重みを更新します。  

```
aws appmesh update-route \
    --cli-input-json file://update-route-weighted.json
```
`update-route-weighted.json` の内容:  

```
{
    "meshName": "app1",
    "routeName": "toVnServiceB-weighted",
    "spec": {
        "httpRoute": {
            "action": {
                "weightedTargets": [
                    {
                        "virtualNode": "vnServiceBv1",
                        "weight": 80
                    },
                    {
                        "virtualNode": "vnServiceBv2",
                        "weight": 20
                    }
                ]
            },
            "match": {
                "prefix": "/"
            }
        }
    },
    "virtualRouterName": "vrServiceB"
}
```
出力:  

```
{
    "route": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB/route/toVnServiceB-weighted",
            "createdAt": 1563811384.015,
            "lastUpdatedAt": 1563819600.022,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 2
        },
        "routeName": "toVnServiceB-weighted",
        "spec": {
            "httpRoute": {
                "action": {
                    "weightedTargets": [
                        {
                            "virtualNode": "vnServiceBv1",
                            "weight": 80
                        },
                        {
                            "virtualNode": "vnServiceBv2",
                            "weight": 20
                        }
                    ]
                },
                "match": {
                    "prefix": "/"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "vrServiceB"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[ルート](https://docs.aws.amazon.com/app-mesh/latest/userguide/routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/update-route.html)」を参照してください。

### `update-virtual-node`
<a name="app-mesh_UpdateVirtualNode_cli_2_topic"></a>

次のコード例は、`update-virtual-node` を使用する方法を示しています。

**AWS CLI**  
**仮想ノードを更新する方法**  
次の `update-virtual-node` の例では、JSON 入力ファイルを使用して、仮想ノードにヘルスチェックを追加します。  

```
aws appmesh update-virtual-node \
    --cli-input-json file://update-virtual-node.json
```
`update-virtual-node.json` の内容:  

```
{
    "clientToken": "500",
    "meshName": "app1",
    "spec": {
        "listeners": [
            {
                "healthCheck": {
                    "healthyThreshold": 5,
                    "intervalMillis": 10000,
                    "path": "/",
                    "port": 80,
                    "protocol": "http",
                    "timeoutMillis": 3000,
                    "unhealthyThreshold": 3
                },
                "portMapping": {
                    "port": 80,
                    "protocol": "http"
                }
            }
        ],
        "serviceDiscovery": {
            "dns": {
                "hostname": "serviceBv1.svc.cluster.local"
            }
        }
    },
    "virtualNodeName": "vnServiceBv1"
}
```
出力:  

```
{
    "virtualNode": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualNode/vnServiceBv1",
            "createdAt": 1563810019.874,
            "lastUpdatedAt": 1563819234.825,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 2
        },
        "spec": {
            "listeners": [
                {
                    "healthCheck": {
                        "healthyThreshold": 5,
                        "intervalMillis": 10000,
                        "path": "/",
                        "port": 80,
                        "protocol": "http",
                        "timeoutMillis": 3000,
                        "unhealthyThreshold": 3
                    },
                    "portMapping": {
                        "port": 80,
                        "protocol": "http"
                    }
                }
            ],
            "serviceDiscovery": {
                "dns": {
                    "hostname": "serviceBv1.svc.cluster.local"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualNodeName": "vnServiceBv1"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ノード](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_nodes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVirtualNode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/update-virtual-node.html)」を参照してください。

### `update-virtual-router`
<a name="app-mesh_UpdateVirtualRouter_cli_2_topic"></a>

次のコード例は、`update-virtual-router` を使用する方法を示しています。

**AWS CLI**  
**仮想ルーターの更新する方法**  
次の `update-virtual-router` の例では、JSON 入力ファイルを使用して仮想ルーターリスナーポートを更新します。  

```
aws appmesh update-virtual-router \
    --cli-input-json file://update-virtual-router.json
```
`update-virtual-router.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "listeners": [
            {
                "portMapping": {
                    "port": 8080,
                    "protocol": "http"
                }
            }
        ]
    },
    "virtualRouterName": "vrServiceB"
}
```
出力:  

```
{
    "virtualRouter": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualRouter/vrServiceB",
            "createdAt": 1563810546.59,
            "lastUpdatedAt": 1563819431.352,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 2
        },
        "spec": {
            "listeners": [
                {
                    "portMapping": {
                        "port": 8080,
                        "protocol": "http"
                    }
                }
            ]
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualRouterName": "vrServiceB"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想ルーター](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_routers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVirtualRouter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/update-virtual-router.html)」を参照してください。

### `update-virtual-service`
<a name="app-mesh_UpdateVirtualService_cli_2_topic"></a>

次のコード例は、`update-virtual-service` を使用する方法を示しています。

**AWS CLI**  
**仮想サービスを更新する方法**  
次の `update-virtual-service` の例では、JSON 入力ファイルを使用し、仮想ルータープロバイダーを使用して仮想サービスを更新します。  

```
aws appmesh update-virtual-service \
    --cli-input-json file://update-virtual-service.json
```
`update-virtual-service.json` の内容:  

```
{
    "meshName": "app1",
    "spec": {
        "provider": {
            "virtualRouter": {
                "virtualRouterName": "vrServiceA"
            }
        }
    },
    "virtualServiceName": "serviceA.svc.cluster.local"
}
```
出力:  

```
{
    "virtualService": {
        "meshName": "app1",
        "metadata": {
            "arn": "arn:aws:appmesh:us-east-1:123456789012:mesh/app1/virtualService/serviceA.svc.cluster.local",
            "createdAt": 1563810859.474,
            "lastUpdatedAt": 1563820257.411,
            "uid": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "version": 3
        },
        "spec": {
            "provider": {
                "virtualRouter": {
                    "virtualRouterName": "vrServiceA"
                }
            }
        },
        "status": {
            "status": "ACTIVE"
        },
        "virtualServiceName": "serviceA.svc.cluster.local"
    }
}
```
詳細については、「*AWS App Mesh ユーザーガイド*」の「[仮想サービス](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVirtualService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appmesh/update-virtual-service.html)」を参照してください。

# を使用した App Runner の例 AWS CLI
<a name="cli_2_apprunner_code_examples"></a>

次のコード例は、App Runner AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-custom-domain`
<a name="apprunner_AssociateCustomDomain_cli_2_topic"></a>

次の例では、`associate-custom-domain` を使用する方法を説明しています。

**AWS CLI**  
**ドメイン名と www サブドメインをサービスに関連付ける方法**  
次の `associate-custom-domain` の例では、制御するカスタムドメイン名を App Runner サービスに関連付けます。ドメイン名はルートドメイン「`example.com`」で、大文字と小文字のサブドメイン「`www.example.com`」が含まれます。  

```
aws apprunner associate-custom-domain \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
    "DomainName": "example.com",
    "EnableWWWSubdomain": true
}
```
出力:  

```
{
    "CustomDomain": {
        "CertificateValidationRecords": [
            {
                "Name": "_70d3f50a94f7c72dc28784cf55db2f6b.example.com",
                "Status": "PENDING_VALIDATION",
                "Type": "CNAME",
                "Value": "_1270c137383c6307b6832db02504c4b0.bsgbmzkfwj.acm-validations.aws."
            },
            {
                "Name": "_287870d3f50a94f7c72dc4cf55db2f6b.www.example.com",
                "Status": "PENDING_VALIDATION",
                "Type": "CNAME",
                "Value": "_832db01270c137383c6307b62504c4b0.mzkbsgbfwj.acm-validations.aws."
            }
        ],
        "DomainName": "example.com",
        "EnableWWWSubdomain": true,
        "Status": "CREATING"
    },
    "DNSTarget": "psbqam834h.us-east-1.awsapprunner.com",
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateCustomDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/associate-custom-domain.html)」を参照してください。

### `create-auto-scaling-configuration`
<a name="apprunner_CreateAutoScalingConfiguration_cli_2_topic"></a>

次の例では、`create-auto-scaling-configuration` を使用する方法を説明しています。

**AWS CLI**  
**高可用性の自動スケーリング構成を作成する方法**  
次の `create-auto-scaling-configuration` の例では、`MinSize` を 5 に構成して高可用性に最適化された自動スケーリング構成を作成します。この設定では、App Runner は AWS 、リージョンに応じて最大 5 つのアベイラビリティーゾーンにサービスインスタンスを分散しようとします。  
呼び出しは、他の設定がデフォルトに設定されている `AutoScalingConfiguration` オブジェクトを返します。この例では、「`high-availability`」という名前の構成を作成する最初の呼び出しです。リビジョンは 1 に設定され、最新のリビジョンです。  

```
aws apprunner create-auto-scaling-configuration \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "AutoScalingConfigurationName": "high-availability",
    "MinSize": 5
}
```
出力:  

```
{
    "AutoScalingConfiguration": {
        "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/1/2f50e7656d7819fead0f59672e68042e",
        "AutoScalingConfigurationName": "high-availability",
        "AutoScalingConfigurationRevision": 1,
        "CreatedAt": "2020-11-03T00:29:17Z",
        "Latest": true,
        "Status": "ACTIVE",
        "MaxConcurrency": 100,
        "MaxSize": 50,
        "MinSize": 5
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAutoScalingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/create-auto-scaling-configuration.html)」を参照してください。

### `create-connection`
<a name="apprunner_CreateConnection_cli_2_topic"></a>

次の例では、`create-connection` を使用する方法を説明しています。

**AWS CLI**  
**GitHub への接続を作成する方法**  
次の `create-connection` の例では、プライベート GitHub コードリポジトリへの接続を作成します。呼び出しが成功した後の接続ステータスは `PENDING_HANDSHAKE` です。これは、プロバイダーとの認証ハンドシェイクがまだ行われていないためです。App Runner コンソールを使用してハンドシェイクを完了します。  

```
aws apprunner create-connection \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ConnectionName": "my-github-connection",
    "ProviderType": "GITHUB"
}
```
出力:  

```
{
    "Connection": {
        "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection",
        "ConnectionName": "my-github-connection",
        "Status": "PENDING_HANDSHAKE",
        "CreatedAt": "2020-11-03T00:32:51Z",
        "ProviderType": "GITHUB"
    }
}
```
詳細については、「*AWS App Runner デベロッパーガイド*」の「[App Runner 接続の管理](https://docs.aws.amazon.com/apprunner/latest/dg/manage-connections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/create-connection.html)」を参照してください。

### `create-service`
<a name="apprunner_CreateService_cli_2_topic"></a>

次の例では、`create-service` を使用する方法を説明しています。

**AWS CLI**  
**例 1: ソースコードリポジトリサービスを作成する方法**  
次の `create-service` の例では、Python ソースコードリポジトリに基づいて App Runner サービスを作成します。  

```
aws apprunner create-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceName": "python-app",
    "SourceConfiguration": {
        "AuthenticationConfiguration": {
            "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
        },
        "AutoDeploymentsEnabled": true,
        "CodeRepository": {
            "RepositoryUrl": "https://github.com/my-account/python-hello",
            "SourceCodeVersion": {
                "Type": "BRANCH",
                "Value": "main"
            },
            "CodeConfiguration": {
                "ConfigurationSource": "API",
                "CodeConfigurationValues": {
                    "Runtime": "PYTHON_3",
                    "BuildCommand": "pip install -r requirements.txt",
                    "StartCommand": "python server.py",
                    "Port": "8080",
                    "RuntimeEnvironmentVariables": [
                        {
                            "NAME": "Jane"
                        }
                    ]
                }
            }
        }
    },
    "InstanceConfiguration": {
        "CPU": "1 vCPU",
        "Memory": "3 GB"
    }
}
```
出力:  

```
{
    "OperationId": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
    "Service": {
        "CreatedAt": "2020-11-20T19:05:25Z",
        "UpdatedAt": "2020-11-20T19:05:25Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceName": "python-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
            },
            "AutoDeploymentsEnabled": true,
            "CodeRepository": {
                "CodeConfiguration": {
                    "CodeConfigurationValues": {
                        "BuildCommand": "pip install -r requirements.txt",
                        "Port": "8080",
                        "Runtime": "PYTHON_3",
                        "RuntimeEnvironmentVariables": [
                            {
                                "NAME": "Jane"
                            }
                        ],
                        "StartCommand": "python server.py"
                    },
                    "ConfigurationSource": "Api"
                },
                "RepositoryUrl": "https://github.com/my-account/python-hello",
                "SourceCodeVersion": {
                    "Type": "BRANCH",
                    "Value": "main"
                }
            }
        },
        "Status": "OPERATION_IN_PROGRESS",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "3 GB"
        }
    }
}
```
**例 2: ソースコードリポジトリサービスを作成する方法**  
次の `create-service` の例では、Python ソースコードリポジトリに基づいて App Runner サービスを作成します。  

```
aws apprunner create-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceName": "python-app",
    "SourceConfiguration": {
        "AuthenticationConfiguration": {
            "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
        },
        "AutoDeploymentsEnabled": true,
        "CodeRepository": {
            "RepositoryUrl": "https://github.com/my-account/python-hello",
            "SourceCodeVersion": {
                "Type": "BRANCH",
                "Value": "main"
            },
            "CodeConfiguration": {
                "ConfigurationSource": "API",
                "CodeConfigurationValues": {
                    "Runtime": "PYTHON_3",
                    "BuildCommand": "pip install -r requirements.txt",
                    "StartCommand": "python server.py",
                    "Port": "8080",
                    "RuntimeEnvironmentVariables": [
                        {
                            "NAME": "Jane"
                        }
                    ]
                }
            }
        }
    },
    "InstanceConfiguration": {
        "CPU": "1 vCPU",
        "Memory": "3 GB"
    }
}
```
出力:  

```
{
    "OperationId": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
    "Service": {
        "CreatedAt": "2020-11-20T19:05:25Z",
        "UpdatedAt": "2020-11-20T19:05:25Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceName": "python-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
            },
            "AutoDeploymentsEnabled": true,
            "CodeRepository": {
                "CodeConfiguration": {
                    "CodeConfigurationValues": {
                        "BuildCommand": "pip install -r requirements.txt",
                        "Port": "8080",
                        "Runtime": "PYTHON_3",
                        "RuntimeEnvironmentVariables": [
                            {
                                "NAME": "Jane"
                            }
                        ],
                        "StartCommand": "python server.py"
                    },
                    "ConfigurationSource": "Api"
                },
                "RepositoryUrl": "https://github.com/my-account/python-hello",
                "SourceCodeVersion": {
                    "Type": "BRANCH",
                    "Value": "main"
                }
            }
        },
        "Status": "OPERATION_IN_PROGRESS",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "3 GB"
        }
    }
}
```
**例 3: ソースイメージリポジトリサービスを作成する方法**  
次の `create-service` の例では、Elastic Container Registry (ECR) に保存されているイメージに基づいて App Runner サービスを作成します。  

```
aws apprunner create-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceName": "golang-container-app",
    "SourceConfiguration": {
        "AuthenticationConfiguration": {
            "AccessRoleArn": "arn:aws:iam::123456789012:role/my-ecr-role"
        },
        "AutoDeploymentsEnabled": true,
        "ImageRepository": {
            "ImageIdentifier": "123456789012.dkr.ecr.us-east-1.amazonaws.com/golang-app:latest",
            "ImageConfiguration": {
                "Port": "8080",
                "RuntimeEnvironmentVariables": [
                    {
                        "NAME": "Jane"
                    }
                ]
            },
            "ImageRepositoryType": "ECR"
        }
    },
    "InstanceConfiguration": {
        "CPU": "1 vCPU",
        "Memory": "3 GB"
    }
}
```
出力:  

```
{
    "OperationId": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
    "Service": {
        "CreatedAt": "2020-11-06T23:15:30Z",
        "UpdatedAt": "2020-11-06T23:15:30Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/golang-container-app/51728f8a20ce46d39b25398a6c8e9d1a",
        "ServiceId": "51728f8a20ce46d39b25398a6c8e9d1a",
        "ServiceName": "golang-container-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "AccessRoleArn": "arn:aws:iam::123456789012:role/my-ecr-role"
            },
            "AutoDeploymentsEnabled": true,
            "ImageRepository": {
                "ImageIdentifier": "123456789012.dkr.ecr.us-east-1.amazonaws.com/golang-app:latest",
                "ImageConfiguration": {
                    "Port": "8080",
                    "RuntimeEnvironmentVariables": [
                        {
                            "NAME": "Jane"
                        }
                    ]
                },
                "ImageRepositoryType": "ECR"
            }
        },
        "Status": "OPERATION_IN_PROGRESS",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "3 GB"
        }
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/create-service.html)」を参照してください。**

### `delete-auto-scaling-configuration`
<a name="apprunner_DeleteAutoScalingConfiguration_cli_2_topic"></a>

次の例では、`delete-auto-scaling-configuration` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 自動スケーリング構成の最新のアクティブなリビジョンを削除する方法**  
次の `delete-auto-scaling-configuration` の例では、App Runner 自動スケーリング構成の最新アクティブリビジョンを削除します。最新のアクティブなリビジョンを削除するには、リビジョンコンポーネントなしで、構成名で終わる Amazon リソースネーム (ARN) を指定します。  
この例では、このアクションの前に 2 つのリビジョンがあります。したがって、リビジョン 2 (最新) は削除されます。ただし、削除後に最新のアクティブなリビジョンではなくなるため、`"Latest": false` が表示されるようになりました。  

```
aws apprunner delete-auto-scaling-configuration \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability"
}
```
出力:  

```
{
    "AutoScalingConfiguration": {
        "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/2/e76562f50d78042e819fead0f59672e6",
        "AutoScalingConfigurationName": "high-availability",
        "AutoScalingConfigurationRevision": 2,
        "CreatedAt": "2021-02-25T17:42:59Z",
        "DeletedAt": "2021-03-02T08:07:06Z",
        "Latest": false,
        "Status": "INACTIVE",
        "MaxConcurrency": 30,
        "MaxSize": 90,
        "MinSize": 5
    }
}
```
**例 2: 自動スケーリング構成の特定のリビジョンを削除する方法**  
次の `delete-auto-scaling-configuration` 例では、App Runner 自動スケーリング構成の特定のリビジョンを削除します。特定のリビジョンを削除するには、リビジョン番号を含む ARN を指定します。  
この例では、このアクションの前にいくつかのリビジョンがあります。アクションはリビジョン `1` を削除します。  

```
aws apprunner delete-auto-scaling-configuration \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/1"
}
```
出力:  

```
{
    "AutoScalingConfiguration": {
        "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/1/2f50e7656d7819fead0f59672e68042e",
        "AutoScalingConfigurationName": "high-availability",
        "AutoScalingConfigurationRevision": 1,
        "CreatedAt": "2020-11-03T00:29:17Z",
        "DeletedAt": "2021-03-02T08:07:06Z",
        "Latest": false,
        "Status": "INACTIVE",
        "MaxConcurrency": 100,
        "MaxSize": 50,
        "MinSize": 5
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAutoScalingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/delete-auto-scaling-configuration.html)」を参照してください。

### `delete-connection`
<a name="apprunner_DeleteConnection_cli_2_topic"></a>

次の例では、`delete-connection` を使用する方法を説明しています。

**AWS CLI**  
**接続を削除する方法**  
次の `delete-connection` の例では、App Runner 接続を削除します。正常な呼び出し後の接続ステータスは「`DELETED`」です。これは、接続が使用できなくなったためです。  

```
aws apprunner delete-connection \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection"
}
```
出力:  

```
{
    "Connection": {
        "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection",
        "ConnectionName": "my-github-connection",
        "Status": "DELETED",
        "CreatedAt": "2020-11-03T00:32:51Z",
        "ProviderType": "GITHUB"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/delete-connection.html)」を参照してください。

### `delete-service`
<a name="apprunner_DeleteService_cli_2_topic"></a>

次の例では、`delete-service` を使用する方法を説明しています。

**AWS CLI**  
**サービスを削除する方法**  
次の `delete-service` の例では、App Runner サービスを削除します。  

```
aws apprunner delete-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
出力:  

```
{
    "OperationId": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
    "Service": {
        "CreatedAt": "2020-11-20T19:05:25Z",
        "UpdatedAt": "2020-11-20T19:05:25Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceName": "python-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
            },
            "AutoDeploymentsEnabled": true,
            "CodeRepository": {
                "CodeConfiguration": {
                    "CodeConfigurationValues": {
                        "BuildCommand": "pip install -r requirements.txt",
                        "Port": "8080",
                        "Runtime": "PYTHON_3",
                        "RuntimeEnvironmentVariables": [
                            {
                                "NAME": "Jane"
                            }
                        ],
                        "StartCommand": "python server.py"
                    },
                    "ConfigurationSource": "Api"
                },
                "RepositoryUrl": "https://github.com/my-account/python-hello",
                "SourceCodeVersion": {
                    "Type": "BRANCH",
                    "Value": "main"
                }
            }
        },
        "Status": "OPERATION_IN_PROGRESS",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "3 GB"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/delete-service.html)」を参照してください。

### `describe-auto-scaling-configuration`
<a name="apprunner_DescribeAutoScalingConfiguration_cli_2_topic"></a>

次の例では、`describe-auto-scaling-configuration` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 自動スケーリング構成の最新のアクティブなリビジョンを記述する方法**  
次の `describe-auto-scaling-configuration` の例では、App Runner 自動スケーリング構成の最新アクティブリビジョンの記述を取得します。最新のアクティブなリビジョンを記述するには、リビジョンコンポーネントなしで、構成名で終わる ARN を指定します。  
この例では、2 つのリビジョンがあります。したがって、リビジョン `2` (最新) が説明されます。結果のオブジェクトには、`"Latest": true` が表示されます。  

```
aws apprunner describe-auto-scaling-configuration \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability"
}
```
出力:  

```
{
    "AutoScalingConfiguration": {
        "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/2/e76562f50d78042e819fead0f59672e6",
        "AutoScalingConfigurationName": "high-availability",
        "AutoScalingConfigurationRevision": 2,
        "CreatedAt": "2021-02-25T17:42:59Z",
        "Latest": true,
        "Status": "ACTIVE",
        "MaxConcurrency": 30,
        "MaxSize": 90,
        "MinSize": 5
    }
}
```
**例 2: 自動スケーリング構成の特定のリビジョンを記述する方法**  
次の `describe-auto-scaling-configuration` 例では、App Runner 自動スケーリング構成の特定のリビジョンの記述を取得します。特定のリビジョンを削除するには、リビジョン番号を含む ARN を記述します。  
この例では、複数のリビジョンが存在し、リビジョン `1` がクエリされます。結果のオブジェクトには、`"Latest": false` が表示されます。  

```
aws apprunner describe-auto-scaling-configuration \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/1"
}
```
出力:  

```
{
    "AutoScalingConfiguration": {
        "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/1/2f50e7656d7819fead0f59672e68042e",
        "AutoScalingConfigurationName": "high-availability",
        "AutoScalingConfigurationRevision": 1,
        "CreatedAt": "2020-11-03T00:29:17Z",
        "Latest": false,
        "Status": "ACTIVE",
        "MaxConcurrency": 100,
        "MaxSize": 50,
        "MinSize": 5
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAutoScalingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/describe-auto-scaling-configuration.html)」を参照してください。

### `describe-custom-domains`
<a name="apprunner_DescribeCustomDomains_cli_2_topic"></a>

次の例では、`describe-custom-domains` を使用する方法を説明しています。

**AWS CLI**  
**サービスに関連付けられたカスタムドメイン名の説明を取得する方法**  
次の `describe-custom-domains` の例では、App Runner サービスに関連付けられたカスタムドメイン名の説明とステータスを取得します。  

```
aws apprunner describe-custom-domains \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
    "DomainName": "example.com",
    "EnableWWWSubdomain": true
}
```
出力:  

```
{
    "CustomDomains": [
        {
            "CertificateValidationRecords": [
                {
                    "Name": "_70d3f50a94f7c72dc28784cf55db2f6b.example.com",
                    "Status": "PENDING_VALIDATION",
                    "Type": "CNAME",
                    "Value": "_1270c137383c6307b6832db02504c4b0.bsgbmzkfwj.acm-validations.aws."
                },
                {
                    "Name": "_287870d3f50a94f7c72dc4cf55db2f6b.www.example.com",
                    "Status": "PENDING_VALIDATION",
                    "Type": "CNAME",
                    "Value": "_832db01270c137383c6307b62504c4b0.mzkbsgbfwj.acm-validations.aws."
                }
            ],
            "DomainName": "example.com",
            "EnableWWWSubdomain": true,
            "Status": "PENDING_CERTIFICATE_DNS_VALIDATION"
        },
        {
            "CertificateValidationRecords": [
                {
                    "Name": "_a94f784c70d3f507c72dc28f55db2f6b.deals.example.com",
                    "Status": "SUCCESS",
                    "Type": "CNAME",
                    "Value": "_2db02504c1270c137383c6307b6834b0.bsgbmzkfwj.acm-validations.aws."
                }
            ],
            "DomainName": "deals.example.com",
            "EnableWWWSubdomain": false,
            "Status": "ACTIVE"
        }
    ],
    "DNSTarget": "psbqam834h.us-east-1.awsapprunner.com",
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/describe-custom-domains.html)」を参照してください。

### `describe-service`
<a name="apprunner_DescribeService_cli_2_topic"></a>

次の例では、`describe-service` を使用する方法を説明しています。

**AWS CLI**  
**サービスを記述する方法**  
次の `describe-service` の例では、App Runner サービスの記述を取得します。  

```
aws apprunner describe-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
出力:  

```
{
    "Service": {
        "CreatedAt": "2020-11-20T19:05:25Z",
        "UpdatedAt": "2020-11-20T19:05:25Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceName": "python-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
            },
            "AutoDeploymentsEnabled": true,
            "CodeRepository": {
                "CodeConfiguration": {
                    "CodeConfigurationValues": {
                        "BuildCommand": "pip install -r requirements.txt",
                        "Port": "8080",
                        "Runtime": "PYTHON_3",
                        "RuntimeEnvironmentVariables": [
                            {
                                "NAME": "Jane"
                            }
                        ],
                        "StartCommand": "python server.py"
                    },
                    "ConfigurationSource": "Api"
                },
                "RepositoryUrl": "https://github.com/my-account/python-hello",
                "SourceCodeVersion": {
                    "Type": "BRANCH",
                    "Value": "main"
                }
            }
        },
        "Status": "RUNNING",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "3 GB"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/describe-service.html)」を参照してください。

### `disassociate-custom-domain`
<a name="apprunner_DisassociateCustomDomain_cli_2_topic"></a>

次の例では、`disassociate-custom-domain` を使用する方法を説明しています。

**AWS CLI**  
**サービスからドメイン名の関連付けを解除する方法**  
次の `disassociate-custom-domain` 例では、App Runner サービスからドメイン「`example.com`」の関連付けを解除します。コールは、ルートドメインと関連付けられているサブドメイン「`www.example.com`」の関連付けも解除します。  

```
aws apprunner disassociate-custom-domain \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
    "DomainName": "example.com"
}
```
出力:  

```
{
    "CustomDomain": {
        "CertificateValidationRecords": [
            {
                "Name": "_70d3f50a94f7c72dc28784cf55db2f6b.example.com",
                "Status": "PENDING_VALIDATION",
                "Type": "CNAME",
                "Value": "_1270c137383c6307b6832db02504c4b0.bsgbmzkfwj.acm-validations.aws."
            },
            {
                "Name": "_287870d3f50a94f7c72dc4cf55db2f6b.www.example.com",
                "Status": "PENDING_VALIDATION",
                "Type": "CNAME",
                "Value": "_832db01270c137383c6307b62504c4b0.mzkbsgbfwj.acm-validations.aws."
            }
        ],
        "DomainName": "example.com",
        "EnableWWWSubdomain": true,
        "Status": "DELETING"
    },
    "DNSTarget": "psbqam834h.us-east-1.awsapprunner.com",
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateCustomDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/disassociate-custom-domain.html)」を参照してください。

### `list-auto-scaling-configurations`
<a name="apprunner_ListAutoScalingConfigurations_cli_2_topic"></a>

次の例では、`list-auto-scaling-configurations` を使用する方法を説明しています。

**AWS CLI**  
**App Runner 自動スケーリング構成のページ分割リストを取得する方法**  
次の の`list-auto-scaling-configurations`例では、 AWS アカウント内のすべての App Runner 自動スケーリング設定を一覧表示します。各レスポンスには、最大 5 つの自動スケーリング構成が一覧表示されます。 `AutoScalingConfigurationName` および `LatestOnly` は指定されません。これらのデフォルトにより、すべてのアクティブな構成の最新リビジョンが一覧表示されます。  
この例では、レスポンスに 2 つの結果が含まれており、追加の結果がないため、`NextToken` は返されません。  

```
aws apprunner list-auto-scaling-configurations \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "MaxResults": 5
}
```
出力:  

```
{
    "AutoScalingConfigurationSummaryList": [
        {
            "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/high-availability/2/e76562f50d78042e819fead0f59672e6",
            "AutoScalingConfigurationName": "high-availability",
            "AutoScalingConfigurationRevision": 2
        },
        {
            "AutoScalingConfigurationArn": "arn:aws:apprunner:us-east-1:123456789012:autoscalingconfiguration/low-cost/1/50d7804e7656fead0f59672e62f2e819",
            "AutoScalingConfigurationName": "low-cost",
            "AutoScalingConfigurationRevision": 1
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAutoScalingConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/list-auto-scaling-configurations.html)」を参照してください。

### `list-connections`
<a name="apprunner_ListConnections_cli_2_topic"></a>

次の例では、`list-connections` を使用する方法を説明しています。

**AWS CLI**  
**例 1: すべての接続を一覧表示する方法**  
次の の`list-connections`例では、 AWS アカウント内のすべての App Runner 接続を一覧表示します。  

```
aws apprunner list-connections
```
出力:  

```
{
    "ConnectionSummaryList": [
        {
            "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection",
            "ConnectionName": "my-github-connection",
            "Status": "AVAILABLE",
            "CreatedAt": "2020-11-03T00:32:51Z",
            "ProviderType": "GITHUB"
        },
        {
            "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-org-connection",
            "ConnectionName": "my-github-org-connection",
            "Status": "AVAILABLE",
            "CreatedAt": "2020-11-03T02:54:17Z",
            "ProviderType": "GITHUB"
        }
    ]
}
```
**例 2: 接続を名前で一覧表示する方法**  
次の `list-connections` の例では、接続をその名前で一覧表示します。  

```
aws apprunner list-connections \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ConnectionName": "my-github-org-connection"
}
```
出力:  

```
{
    "ConnectionSummaryList": [
        {
            "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-org-connection",
            "ConnectionName": "my-github-org-connection",
            "Status": "AVAILABLE",
            "CreatedAt": "2020-11-03T02:54:17Z",
            "ProviderType": "GITHUB"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/list-connections.html)」を参照してください。

### `list-operations`
<a name="apprunner_ListOperations_cli_2_topic"></a>

次の例では、`list-operations` を使用する方法を説明しています。

**AWS CLI**  
**サービスで発生したオペレーションを一覧表示する方法**  
次の `list-operations` の例では、これまでに App Runner サービスで発生したすべてのオペレーションを一覧表示します。この例では、サービスは新しく、タイプ「`CREATE_SERVICE`」のオペレーションが 1 つだけ発生しています。  

```
aws apprunner list-operations \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
出力:  

```
{
    "OperationSummaryList": [
        {
            "EndedAt": 1606156217,
            "Id": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
            "StartedAt": 1606156014,
            "Status": "SUCCEEDED",
            "TargetArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
            "Type": "CREATE_SERVICE",
            "UpdatedAt": 1606156217
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOperations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/list-operations.html)」を参照してください。

### `list-services`
<a name="apprunner_ListServices_cli_2_topic"></a>

次の例では、`list-services` を使用する方法を説明しています。

**AWS CLI**  
**App Runner サービスのページ分割一覧を取得する方法**  
次の の`list-services`例では、 AWS アカウント内のすべての App Runner サービスを一覧表示します。各レスポンスには、最大 2 つのサービスが一覧表示されます。この例では、最初のリクエストを示しています。レスポンスには、次のリクエストで使用できる 2 つの結果とトークンが含まれます。後続のレスポンスにトークンが含まれていない場合、すべてのサービスが一覧表示されます。  

```
aws apprunner list-services \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "MaxResults": 2
}
```
出力:  

```
{
    "NextToken": "eyJDdXN0b21lckFjY291bnRJZCI6IjI3MDIwNTQwMjg0NSIsIlNlcnZpY2VTdGF0dXNDb2RlIjoiUFJPVklTSU9OSU5HIiwiSGFzaEtleSI6IjI3MDIwNTQwMjg0NSNhYjhmOTRjZmUyOWE0NjBmYjg3NjBhZmQyZWU4NzU1NSJ9",
    "ServiceSummaryList": [
        {
            "CreatedAt": "2020-11-20T19:05:25Z",
            "UpdatedAt": "2020-11-23T12:41:37Z",
            "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
            "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
            "ServiceName": "python-app",
            "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
            "Status": "RUNNING"
        },
        {
            "CreatedAt": "2020-11-06T23:15:30Z",
            "UpdatedAt": "2020-11-23T13:21:22Z",
            "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/golang-container-app/ab8f94cfe29a460fb8760afd2ee87555",
            "ServiceId": "ab8f94cfe29a460fb8760afd2ee87555",
            "ServiceName": "golang-container-app",
            "ServiceUrl": "e2m8rrrx33.us-east-1.awsapprunner.com",
            "Status": "RUNNING"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/list-services.html)」を参照してください。

### `list-tags-for-resource`
<a name="apprunner_ListTagsForResource_cli_2_topic"></a>

次の例では、`list-tags-for-resource` を使用する方法を説明しています。

**AWS CLI**  
**App Runner サービスに関連付けられたタグを一覧表示する方法**  
次の `list-tags-for-resource` の例では、App Runner サービスに関連付けられたすべてのタグを一覧表示します。  

```
aws apprunner list-tags-for-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ResourceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Department",
            "Value": "Retail"
        },
        {
            "Key": "CustomerId",
            "Value": "56439872357912"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/list-tags-for-resource.html)」を参照してください。

### `pause-service`
<a name="apprunner_PauseService_cli_2_topic"></a>

次の例では、`pause-service` を使用する方法を説明しています。

**AWS CLI**  
**サービスを一時停止する方法**  
次の `pause-service` の例では、App Runner サービスを一時停止します。  

```
aws apprunner pause-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
出力:  

```
{
    "OperationId": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
    "Service": {
        "CreatedAt": "2020-11-20T19:05:25Z",
        "UpdatedAt": "2020-11-23T12:41:37Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceName": "python-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
            },
            "AutoDeploymentsEnabled": true,
            "CodeRepository": {
                "CodeConfiguration": {
                    "CodeConfigurationValues": {
                        "BuildCommand": "pip install -r requirements.txt",
                        "Port": "8080",
                        "Runtime": "PYTHON_3",
                        "RuntimeEnvironmentVariables": [
                            {
                                "NAME": "Jane"
                            }
                        ],
                        "StartCommand": "python server.py"
                    },
                    "ConfigurationSource": "Api"
                },
                "RepositoryUrl": "https://github.com/my-account/python-hello",
                "SourceCodeVersion": {
                    "Type": "BRANCH",
                    "Value": "main"
                }
            }
        },
        "Status": "OPERATION_IN_PROGRESS",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "3 GB"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PauseService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/pause-service.html)」を参照してください。

### `resume-service`
<a name="apprunner_ResumeService_cli_2_topic"></a>

次の例では、`resume-service` を使用する方法を説明しています。

**AWS CLI**  
**サービスを再開する方法**  
次の `resume-service` の例では、App Runner サービスを再開します。  

```
aws apprunner resume-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
出力:  

```
{
    "OperationId": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
    "Service": {
        "CreatedAt": "2020-11-20T19:05:25Z",
        "UpdatedAt": "2020-11-23T12:41:37Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceName": "python-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
            },
            "AutoDeploymentsEnabled": true,
            "CodeRepository": {
                "CodeConfiguration": {
                    "CodeConfigurationValues": {
                        "BuildCommand": "pip install -r requirements.txt",
                        "Port": "8080",
                        "Runtime": "PYTHON_3",
                        "RuntimeEnvironmentVariables": [
                            {
                                "NAME": "Jane"
                            }
                        ],
                        "StartCommand": "python server.py"
                    },
                    "ConfigurationSource": "Api"
                },
                "RepositoryUrl": "https://github.com/my-account/python-hello",
                "SourceCodeVersion": {
                    "Type": "BRANCH",
                    "Value": "main"
                }
            }
        },
        "Status": "OPERATION_IN_PROGRESS",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "3 GB"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResumeService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/resume-service.html)」を参照してください。

### `start-deployment`
<a name="apprunner_StartDeployment_cli_2_topic"></a>

次の例では、`start-deployment` を使用する方法を説明しています。

**AWS CLI**  
**手動デプロイを開始する方法**  
次の `start-deployment` の例では、App Runner サービスへの手動デプロイを実行します。  

```
aws apprunner start-deployment \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa"
}
```
出力:  

```
{
    "OperationId": "853a7d5b-fc9f-4730-831b-fd8037ab832a"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/start-deployment.html)」を参照してください。

### `tag-resource`
<a name="apprunner_TagResource_cli_2_topic"></a>

次の例では、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
**App Runner サービスにタグを追加する方法**  
次の `tag-resource` の例では、App Runner サービスを一時停止します。  

```
aws apprunner tag-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ResourceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
    "Tags": [
        {
            "Key": "Department",
            "Value": "Retail"
        },
        {
            "Key": "CustomerId",
            "Value": "56439872357912"
        }
    ]
}
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="apprunner_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**App Runner サービスからタグを削除する方法**  
次の `untag-resource` の例では、シークレットから 2 個のタグを削除します。  

```
aws apprunner untag-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ResourceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
    "TagKeys": [
        "Department",
        "CustomerId"
    ]
}
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/untag-resource.html)」を参照してください。

### `update-service`
<a name="apprunner_UpdateService_cli_2_topic"></a>

次の例では、`update-service` を使用する方法を説明しています。

**AWS CLI**  
**メモリサイズを更新する方法**  
次の `update-service` の例では、App Runner サービスのインスタンス (スケーリングユニット) のメモリサイズを 2048 MiB に更新します。  
呼び出しが成功すると、App Runner は非同期更新プロセスを開始します。呼び出しによって返される `Service` 構造には、この呼び出しによって適用される新しいメモリ値が反映されます。  

```
aws apprunner update-service \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
    "InstanceConfiguration": {
        "Memory": "4 GB"
    }
}
```
出力:  

```
{
    "OperationId": "17fe9f55-7e91-4097-b243-fcabbb69a4cf",
    "Service": {
        "CreatedAt": "2020-11-20T19:05:25Z",
        "UpdatedAt": "2020-11-23T12:41:37Z",
        "ServiceArn": "arn:aws:apprunner:us-east-1:123456789012:service/python-app/8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceId": "8fe1e10304f84fd2b0df550fe98a71fa",
        "ServiceName": "python-app",
        "ServiceUrl": "psbqam834h.us-east-1.awsapprunner.com",
        "SourceConfiguration": {
            "AuthenticationConfiguration": {
                "ConnectionArn": "arn:aws:apprunner:us-east-1:123456789012:connection/my-github-connection/e7656250f67242d7819feade6800f59e"
            },
            "AutoDeploymentsEnabled": true,
            "CodeRepository": {
                "CodeConfiguration": {
                    "CodeConfigurationValues": {
                        "BuildCommand": "pip install -r requirements.txt",
                        "Port": "8080",
                        "Runtime": "PYTHON_3",
                        "RuntimeEnvironmentVariables": [
                            {
                                "NAME": "Jane"
                            }
                        ],
                        "StartCommand": "python server.py"
                    },
                    "ConfigurationSource": "Api"
                },
                "RepositoryUrl": "https://github.com/my-account/python-hello",
                "SourceCodeVersion": {
                    "Type": "BRANCH",
                    "Value": "main"
                }
            }
        },
        "Status": "OPERATION_IN_PROGRESS",
        "InstanceConfiguration": {
            "CPU": "1 vCPU",
            "Memory": "4 GB"
        }
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/apprunner/update-service.html)」を参照してください。**

# AWS AppConfig を使用した の例 AWS CLI
<a name="cli_2_appconfig_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS AppConfig。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-application`
<a name="appconfig_CreateApplication_cli_2_topic"></a>

次のコード例は、`create-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを作成する方法**  
次の`create-application`例では、 AWS AppConfig でアプリケーションを作成します。  

```
aws appconfig create-application \
    --name "example-application" \
    --description "An application used for creating an example."
```
出力:  

```
{
    "Description": "An application used for creating an example.",
    "Id": "339ohji",
    "Name": "example-application"
}
```
詳細については、[AWS AppConfig ユーザーガイドの「ステップ 1: AppConfig アプリケーションの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/create-application.html)」を参照してください。

### `create-configuration-profile`
<a name="appconfig_CreateConfigurationProfile_cli_2_topic"></a>

次のコード例は、`create-configuration-profile` を使用する方法を示しています。

**AWS CLI**  
**設定プロファイルを作成する方法**  
次の `create-configuration-profile` の例は、Systems Manager の一機能である Parameter Store に保存されている設定を使用して構成プロファイルを作成します。  

```
aws appconfig create-configuration-profile \
    --application-id "339ohji" \
    --name "Example-Configuration-Profile" \
    --location-uri "ssm-parameter://Example-Parameter" \
    --retrieval-role-arn "arn:aws:iam::111122223333:role/Example-App-Config-Role"
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "Description": null,
    "Id": "ur8hx2f",
    "LocationUri": "ssm-parameter://Example-Parameter",
    "Name": "Example-Configuration-Profile",
    "RetrievalRoleArn": "arn:aws:iam::111122223333:role/Example-App-Config-Role",
    "Type": null,
    "Validators": null
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 3: 構成および構成プロファイルの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConfigurationProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/create-configuration-profile.html)」を参照してください。

### `create-environment`
<a name="appconfig_CreateEnvironment_cli_2_topic"></a>

次のコード例は、`create-environment` を使用する方法を示しています。

**AWS CLI**  
**環境を作成する方法**  
次の`create-environment`例では、create-application を使用して作成したアプリケーションを使用して Example-Environment という名前の AWS AppConfig 環境を作成します。  

```
aws appconfig create-environment \
    --application-id "339ohji" \
    --name "Example-Environment"
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "Description": null,
    "Id": "54j1r29",
    "Monitors": null,
    "Name": "Example-Environment",
    "State": "ReadyForDeployment"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 2: 環境の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-environment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/create-environment.html)」を参照してください。

### `create-extension-association`
<a name="appconfig_CreateExtensionAssociation_cli_2_topic"></a>

次のコード例は、`create-extension-association` を使用する方法を示しています。

**AWS CLI**  
**拡張機能を作成する方法**  
次の の`create-extension-association`例では、 AWS AppConfig で新しい拡張機能の関連付けを作成します。  

```
aws appconfig create-extension-association \
    --region us-west-2 \
    --extension-identifier S3-backup-extension \
    --resource-identifier "arn:aws:appconfig:us-west-2:123456789012:application/Finance" \
    --parameters S3bucket=FinanceConfigurationBackup
```
出力:  

```
{
  "Id": "a1b2c3d4",
  "ExtensionArn": "arn:aws:appconfig:us-west-2:123456789012:extension/S3-backup-extension/1",
  "ResourceArn": "arn:aws:appconfig:us-west-2:123456789012:application/Finance",
  "Parameters": {
    "S3bucket": "FinanceConfigurationBackup"
  },
  "ExtensionVersionNumber": 1
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateExtensionAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/create-extension-association.html)」を参照してください。

### `create-extension`
<a name="appconfig_CreateExtension_cli_2_topic"></a>

次のコード例は、`create-extension` を使用する方法を示しています。

**AWS CLI**  
**拡張機能を作成する方法**  
次の の`create-extension`例では、 AWS AppConfig に新しい拡張機能を作成します。  

```
aws appconfig create-extension \
    --region us-west-2 \
    --name S3-backup-extension \
    --actions PRE_CREATE_HOSTED_CONFIGURATION_VERSION=[{Name=S3backup,Uri=arn:aws:lambda:us-west-2:123456789012:function:s3backupfunction,RoleArn=arn:aws:iam::123456789012:role/appconfigextensionrole}] \
    --parameters S3bucket={Required=true}
```
出力:  

```
{
    "Id": "1A2B3C4D",
    "Name": "S3-backup-extension",
    "VersionNumber": 1,
    "Arn": "arn:aws:appconfig:us-west-2:123456789012:extension/1A2B3C4D/1",
    "Actions": {
        "PRE_CREATE_HOSTED_CONFIGURATION_VERSION": [
            {
                "Name": "S3backup",
                "Uri": "arn:aws:lambda:us-west-2:123456789012:function:s3backupfunction",
                "RoleArn": "arn:aws:iam::123456789012:role/appconfigextensionrole"
            }
        ]
    },
    "Parameters": {
        "S3bucket": {
            "Required": true
        }
    }
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateExtension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/create-extension.html)」を参照してください。

### `create-hosted-configuration-version`
<a name="appconfig_CreateHostedConfigurationVersion_cli_2_topic"></a>

次のコード例は、`create-hosted-configuration-version` を使用する方法を示しています。

**AWS CLI**  
**ホストされた構成バージョンを作成する方法**  
次の の`create-hosted-configuration-version`例では、 AWS AppConfig ホスト設定ストアに新しい設定を作成します。構成コンテンツは、まず base64 に変換する必要があります。  

```
aws appconfig create-hosted-configuration-version \
    --application-id "339ohji" \
    --configuration-profile-id "ur8hx2f" \
    --content eyAiTmFtZSI6ICJFeGFtcGxlQXBwbGljYXRpb24iLCAiSWQiOiBFeGFtcGxlSUQsICJSYW5rIjogNyB9 \
    --content-type "application/json" \
    configuration_version_output_file
```
`configuration_version_output_file` の内容:  

```
{ "Name": "ExampleApplication", "Id": ExampleID, "Rank": 7 }
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "ConfigurationProfileId": "ur8hx2f",
    "VersionNumber": "1",
    "ContentType": "application/json"
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig ホスト設定ストアについて](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html#appconfig-creating-configuration-and-profile-about-hosted-store)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateHostedConfigurationVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/create-hosted-configuration-version.html)」を参照してください。

### `delete-application`
<a name="appconfig_DeleteApplication_cli_2_topic"></a>

次のコード例は、`delete-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを削除するには**  
以下の `delete-application` の例は、指定されたスタックを削除します。  

```
aws appconfig delete-application \
--application-id 339ohji
```
このコマンドでは何も出力されません。  
詳細については、[AWS AppConfig ユーザーガイドの「ステップ 1: AppConfig アプリケーションの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/delete-application.html)」を参照してください。

### `delete-configuration-profile`
<a name="appconfig_DeleteConfigurationProfile_cli_2_topic"></a>

次のコード例は、`delete-configuration-profile` を使用する方法を示しています。

**AWS CLI**  
**構成プロファイルを削除する方法**  
次の `delete-configuration-profile` の例では、指定された構成プロファイルを削除します。  

```
aws appconfig delete-configuration-profile \
    --application-id 339ohji \
    --configuration-profile-id ur8hx2f
```
このコマンドでは何も出力されません。  
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 3: 構成および構成プロファイルの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConfigurationProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/delete-configuration-profile.html)」を参照してください。

### `delete-deployment-strategy`
<a name="appconfig_DeleteDeploymentStrategy_cli_2_topic"></a>

次のコード例は、`delete-deployment-strategy` を使用する方法を示しています。

**AWS CLI**  
**デプロイ戦略を削除する方法**  
次の `delete-deployment-strategy` の例は、指定されたデプロイ戦略を削除します。  

```
aws appconfig delete-deployment-strategy \
    --deployment-strategy-id 1225qzk
```
このコマンドでは何も出力されません。  
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 4: デプロイ戦略の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-deployment-strategy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDeploymentStrategy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/delete-deployment-strategy.html)」を参照してください。

### `delete-environment`
<a name="appconfig_DeleteEnvironment_cli_2_topic"></a>

次のコード例は、`delete-environment` を使用する方法を示しています。

**AWS CLI**  
**環境を削除する方法**  
以下の `delete-environment` の例は、指定されたアプリケーション環境を削除します。  

```
aws appconfig delete-environment \
    --application-id 339ohji \
    --environment-id 54j1r29
```
このコマンドでは何も出力されません。  
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 2: 環境の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-environment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/delete-environment.html)」を参照してください。

### `delete-extension-association`
<a name="appconfig_DeleteExtensionAssociation_cli_2_topic"></a>

次のコード例は、`delete-extension-association` を使用する方法を示しています。

**AWS CLI**  
**拡張機能の関連付けを削除する方法**  
次の の`delete-extension-association`例では、 AWS AppConfig から拡張機能の関連付けを削除します。  

```
aws appconfig delete-extension-association \
    --region us-west-2 \
    --extension-association-id a1b2c3d4
```
このコマンドでは何も出力されません。  
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteExtensionAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/delete-extension-association.html)」を参照してください。

### `delete-extension`
<a name="appconfig_DeleteExtension_cli_2_topic"></a>

次のコード例は、`delete-extension` を使用する方法を示しています。

**AWS CLI**  
**拡張機能を削除する方法**  
次の の`delete-extension`例では、 AWS AppConfig から拡張機能を削除します。  

```
aws appconfig delete-extension \
    --region us-west-2 \
    --extension-identifier S3-backup-extension
```
このコマンドでは何も出力されません。  
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteExtension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/delete-extension.html)」を参照してください。

### `delete-hosted-configuration-version`
<a name="appconfig_DeleteHostedConfigurationVersion_cli_2_topic"></a>

次のコード例は、`delete-hosted-configuration-version` を使用する方法を示しています。

**AWS CLI**  
**ホストされた構成バージョンを削除する方法**  
次の の`delete-hosted-configuration-version`例では、 AWS AppConfig ホスト設定ストアでホストされている設定バージョンを削除します。  

```
aws appconfig delete-hosted-configuration-version \
    --application-id 339ohji \
    --configuration-profile-id ur8hx2f \
    --version-number 1
```
出力:: このコマンドでは何も出力されません。  
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 3: 構成および構成プロファイルの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteHostedConfigurationVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/delete-hosted-configuration-version.html)」を参照してください。

### `get-application`
<a name="appconfig_GetApplication_cli_2_topic"></a>

次のコード例は、`get-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの詳細を一覧表示する方法**  
次の `get-application` の例では、指定されたアプリケーションの詳細を一覧表示します。  

```
aws appconfig get-application \
    --application-id 339ohji
```
出力:  

```
{
    "Description": "An application used for creating an example.",
    "Id": "339ohji",
    "Name": "example-application"
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig の仕組み](https://docs.aws.amazon.com/appconfig/latest/userguide/what-is-appconfig.html#learn-more-appconfig-how-it-works)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-application.html)」を参照してください。

### `get-configuration-profile`
<a name="appconfig_GetConfigurationProfile_cli_2_topic"></a>

次のコード例は、`get-configuration-profile` を使用する方法を示しています。

**AWS CLI**  
**構成プロファイルの詳細を取得する方法**  
次の `get-configuration-profile` の例では、指定された構成プロファイルの詳細を返します。  

```
aws appconfig get-configuration-profile \
    --application-id 339ohji \
    --configuration-profile-id ur8hx2f
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "Id": "ur8hx2f",
    "Name": "Example-Configuration-Profile",
    "LocationUri": "ssm-parameter://Example-Parameter",
    "RetrievalRoleArn": "arn:aws:iam::111122223333:role/Example-App-Config-Role"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 3: 構成および構成プロファイルの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConfigurationProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-configuration-profile.html)」を参照してください。

### `get-configuration`
<a name="appconfig_GetConfiguration_cli_2_topic"></a>

次のコード例は、`get-configuration` を使用する方法を示しています。

**AWS CLI**  
**構成の詳細を取得する方法**  
次の `get-configuration` の例では、サンプルアプリケーションの構成の詳細を返します。後続の get-configuration 呼び出しでは、 `client-configuration-version` パラメータを使用して、バージョンが変更された場合にのみアプリケーションの設定を更新します。バージョンが変更された場合にのみ設定を更新すると、get-configuration を呼び出すことで発生する超過料金を回避できます。  

```
aws appconfig get-configuration \
    --application "example-application" \
    --environment "Example-Environment" \
    --configuration "Example-Configuration-Profile" \
    --client-id "test-id" \
    configuration-output-file
```
`configuration-output-file` の内容:  

```
{ "Name": "ExampleApplication", "Id": ExampleID, "Rank": 7 }
```
出力:  

```
{
    "ConfigurationVersion": "1",
    "ContentType": "application/json"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の[「ステップ 6: 構成の受信](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-retrieving-the-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-configuration.html)」を参照してください。

### `get-deployment-strategy`
<a name="appconfig_GetDeploymentStrategy_cli_2_topic"></a>

次のコード例は、`get-deployment-strategy` を使用する方法を示しています。

**AWS CLI**  
**デプロイ戦略の詳細を取得する方法**  
次の `get-deployment-strategy` の例は、指定されたデプロイ戦略の詳細を一覧表示します。  

```
aws appconfig get-deployment-strategy \
    --deployment-strategy-id 1225qzk
```
出力:  

```
{
    "Id": "1225qzk",
    "Name": "Example-Deployment",
    "DeploymentDurationInMinutes": 15,
    "GrowthType": "LINEAR",
    "GrowthFactor": 25.0,
    "FinalBakeTimeInMinutes": 0,
    "ReplicateTo": "SSM_DOCUMENT"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 4: デプロイ戦略の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-deployment-strategy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeploymentStrategy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-deployment-strategy.html)」を参照してください。

### `get-deployment`
<a name="appconfig_GetDeployment_cli_2_topic"></a>

次のコード例は、`get-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイの詳細を取得する方法**  
次の `get-deployment` の例は、指定された環境とデプロイ内のアプリケーションへのデプロイの詳細を一覧表示します。  

```
aws appconfig get-deployment \
    --application-id 339ohji \
    --environment-id 54j1r29 \
    --deployment-number 1
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "EnvironmentId": "54j1r29",
    "DeploymentStrategyId": "1225qzk",
    "ConfigurationProfileId": "ur8hx2f",
    "DeploymentNumber": 1,
    "ConfigurationName": "Example-Configuration-Profile",
    "ConfigurationLocationUri": "ssm-parameter://Example-Parameter",
    "ConfigurationVersion": "1",
    "DeploymentDurationInMinutes": 15,
    "GrowthType": "LINEAR",
    "GrowthFactor": 25.0,
    "FinalBakeTimeInMinutes": 0,
    "State": "COMPLETE",
    "EventLog": [
        {
            "EventType": "DEPLOYMENT_COMPLETED",
            "TriggeredBy": "APPCONFIG",
            "Description": "Deployment completed",
            "OccurredAt": "2021-09-17T21:59:03.888000+00:00"
        },
        {
            "EventType": "BAKE_TIME_STARTED",
            "TriggeredBy": "APPCONFIG",
            "Description": "Deployment bake time started",
            "OccurredAt": "2021-09-17T21:58:57.722000+00:00"
        },
        {
            "EventType": "PERCENTAGE_UPDATED",
            "TriggeredBy": "APPCONFIG",
            "Description": "Configuration available to 100.00% of clients",
            "OccurredAt": "2021-09-17T21:55:56.816000+00:00"
        },
        {
            "EventType": "PERCENTAGE_UPDATED",
            "TriggeredBy": "APPCONFIG",
            "Description": "Configuration available to 75.00% of clients",
            "OccurredAt": "2021-09-17T21:52:56.567000+00:00"
        },
        {
            "EventType": "PERCENTAGE_UPDATED",
            "TriggeredBy": "APPCONFIG",
            "Description": "Configuration available to 50.00% of clients",
            "OccurredAt": "2021-09-17T21:49:55.737000+00:00"
        },
        {
            "EventType": "PERCENTAGE_UPDATED",
            "TriggeredBy": "APPCONFIG",
            "Description": "Configuration available to 25.00% of clients",
            "OccurredAt": "2021-09-17T21:46:55.187000+00:00"
        },
        {
            "EventType": "DEPLOYMENT_STARTED",
            "TriggeredBy": "USER",
            "Description": "Deployment started",
            "OccurredAt": "2021-09-17T21:43:54.205000+00:00"
        }
    ],
    "PercentageComplete": 100.0,
    "StartedAt": "2021-09-17T21:43:54.205000+00:00",
    "CompletedAt": "2021-09-17T21:59:03.888000+00:00"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の[「ステップ 5: 構成のデプロイ](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-deploying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-deployment.html)」を参照してください。

### `get-environment`
<a name="appconfig_GetEnvironment_cli_2_topic"></a>

次のコード例は、`get-environment` を使用する方法を示しています。

**AWS CLI**  
**環境の詳細を取得する方法**  
次の `get-environment` の例は、指定された環境の詳細と状態を返します。  

```
aws appconfig get-environment \
    --application-id 339ohji \
    --environment-id 54j1r29
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "Id": "54j1r29",
    "Name": "Example-Environment",
    "State": "ReadyForDeployment"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 2: 環境の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-environment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-environment.html)」を参照してください。

### `get-extension-association`
<a name="appconfig_GetExtensionAssociation_cli_2_topic"></a>

次のコード例は、`get-extension-association` を使用する方法を示しています。

**AWS CLI**  
**拡張機能の関連付けの詳細を取得する方法**  
以下の `get-extension-association` の例では、機能拡張の関連付けに関する情報を表示します。  

```
aws appconfig get-extension-association \
    --region us-west-2 \
    --extension-association-id a1b2c3d4
```
出力:  

```
{
    "Id": "a1b2c3d4",
    "ExtensionArn": "arn:aws:appconfig:us-west-2:123456789012:extension/S3-backup-extension/1",
    "ResourceArn": "arn:aws:appconfig:us-west-2:123456789012:application/Finance",
    "Parameters": {
        "S3bucket": "FinanceConfigurationBackup"
    },
    "ExtensionVersionNumber": 1
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetExtensionAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-extension-association.html)」を参照してください。

### `get-extension`
<a name="appconfig_GetExtension_cli_2_topic"></a>

次のコード例は、`get-extension` を使用する方法を示しています。

**AWS CLI**  
**拡張機能の詳細を取得する方法**  
以下の `get-extension` の例では、機能拡張に関する情報を表示します。  

```
aws appconfig get-extension \
    --region us-west-2 \
    --extension-identifier S3-backup-extension
```
出力:  

```
{
    "Id": "1A2B3C4D",
    "Name": "S3-backup-extension",
    "VersionNumber": 1,
    "Arn": "arn:aws:appconfig:us-west-2:123456789012:extension/S3-backup-extension/1",
    "Actions": {
        "PRE_CREATE_HOSTED_CONFIGURATION_VERSION": [
            {
                "Name": "S3backup",
                "Uri": "arn:aws:lambda:us-west-2:123456789012:function:S3backupfunction",
                "RoleArn": "arn:aws:iam::123456789012:role/appconfigextensionrole"
            }
        ]
    },
    "Parameters": {
        "S3bucket": {
            "Required": true
        }
    }
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetExtension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-extension.html)」を参照してください。

### `get-hosted-configuration-version`
<a name="appconfig_GetHostedConfigurationVersion_cli_2_topic"></a>

次の例は、`get-hosted-configuration-version` を使用する方法を説明しています。

**AWS CLI**  
**ホスト構成の詳細を取得する方法**  
次の の`get-hosted-configuration-version`例では、 AWS AppConfig ホスト設定の設定の詳細を取得します。  

```
aws appconfig get-hosted-configuration-version \
    --application-id 339ohji \
    --configuration-profile-id ur8hx2f \
    --version-number 1 \
    hosted-configuration-version-output
```
`hosted-configuration-version-output` の内容:  

```
{ "Name": "ExampleApplication", "Id": ExampleID, "Rank": 7 }
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "ConfigurationProfileId": "ur8hx2f",
    "VersionNumber": "1",
    "ContentType": "application/json"
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig ホスト設定ストアについて](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html#appconfig-creating-configuration-and-profile-about-hosted-store)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetHostedConfigurationVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/get-hosted-configuration-version.html)」を参照してください。

### `list-applications`
<a name="appconfig_ListApplications_cli_2_topic"></a>

次のコード例は、`list-applications` を使用する方法を示しています。

**AWS CLI**  
**使用可能なアプリケーションを一覧表示する方法**  
次の の`list-applications`例では、 AWS アカウントで使用可能なアプリケーションを一覧表示します。  

```
aws appconfig list-applications
```
出力:  

```
{
    "Items": [
        {
            "Id": "339ohji",
            "Name": "test-application",
            "Description": "An application used for creating an example."
        },
        {
            "Id": "rwalwu7",
            "Name": "Test-Application"
        }
    ]
}
```
詳細については、[AWS AppConfig ユーザーガイドの「ステップ 1: AppConfig アプリケーションの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListApplications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-applications.html)」を参照してください。

### `list-configuration-profiles`
<a name="appconfig_ListConfigurationProfiles_cli_2_topic"></a>

次のコード例は、`list-configuration-profiles` を使用する方法を示しています。

**AWS CLI**  
**使用可能な構成プロファイルを一覧表示する方法**  
次の `list-configuration-profiles` の例では、指定されたアプリケーションで使用可能な構成プロファイルを一覧表示します。  

```
aws appconfig list-configuration-profiles \
    --application-id 339ohji
```
出力:  

```
{
    "Items": [
        {
            "ApplicationId": "339ohji",
            "Id": "ur8hx2f",
            "Name": "Example-Configuration-Profile",
            "LocationUri": "ssm-parameter://Example-Parameter"
        }
    ]
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 3: 構成および構成プロファイルの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConfigurationProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-configuration-profiles.html)」を参照してください。

### `list-deployment-strategies`
<a name="appconfig_ListDeploymentStrategies_cli_2_topic"></a>

次のコード例は、`list-deployment-strategies` を使用する方法を示しています。

**AWS CLI**  
**利用可能なデプロイ戦略を一覧表示する方法**  
次の の`list-deployment-strategies`例では、 AWS アカウントで使用可能なデプロイ戦略を一覧表示します。  

```
aws appconfig list-deployment-strategies
```
出力:  

```
{
    "Items": [
        {
            "Id": "1225qzk",
            "Name": "Example-Deployment",
            "DeploymentDurationInMinutes": 15,
            "GrowthType": "LINEAR",
            "GrowthFactor": 25.0,
            "FinalBakeTimeInMinutes": 0,
            "ReplicateTo": "SSM_DOCUMENT"
        },
        {
            "Id": "AppConfig.AllAtOnce",
            "Name": "AppConfig.AllAtOnce",
            "Description": "Quick",
            "DeploymentDurationInMinutes": 0,
            "GrowthType": "LINEAR",
            "GrowthFactor": 100.0,
            "FinalBakeTimeInMinutes": 10,
            "ReplicateTo": "NONE"
        },
        {
            "Id": "AppConfig.Linear50PercentEvery30Seconds",
            "Name": "AppConfig.Linear50PercentEvery30Seconds",
            "Description": "Test/Demo",
            "DeploymentDurationInMinutes": 1,
            "GrowthType": "LINEAR",
            "GrowthFactor": 50.0,
            "FinalBakeTimeInMinutes": 1,
            "ReplicateTo": "NONE"
        },
        {
            "Id": "AppConfig.Canary10Percent20Minutes",
            "Name": "AppConfig.Canary10Percent20Minutes",
            "Description": "AWS Recommended",
            "DeploymentDurationInMinutes": 20,
            "GrowthType": "EXPONENTIAL",
            "GrowthFactor": 10.0,
            "FinalBakeTimeInMinutes": 10,
            "ReplicateTo": "NONE"
        }
    ]
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 4: デプロイ戦略の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-deployment-strategy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeploymentStrategies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-deployment-strategies.html)」を参照してください。

### `list-deployments`
<a name="appconfig_ListDeployments_cli_2_topic"></a>

次のコード例は、`list-deployments` を使用する方法を示しています。

**AWS CLI**  
**使用可能なデプロイを一覧表示する方法**  
次の の`list-deployments`例では、指定されたアプリケーションと環境の AWS アカウントで使用可能なデプロイを一覧表示します。  

```
aws appconfig list-deployments \
    --application-id 339ohji \
    --environment-id 54j1r29
```
出力:  

```
{
    "Items": [
        {
            "DeploymentNumber": 1,
            "ConfigurationName": "Example-Configuration-Profile",
            "ConfigurationVersion": "1",
            "DeploymentDurationInMinutes": 15,
            "GrowthType": "LINEAR",
            "GrowthFactor": 25.0,
            "FinalBakeTimeInMinutes": 0,
            "State": "COMPLETE",
            "PercentageComplete": 100.0,
            "StartedAt": "2021-09-17T21:43:54.205000+00:00",
            "CompletedAt": "2021-09-17T21:59:03.888000+00:00"
        }
    ]
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の[「ステップ 5: 構成のデプロイ](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-deploying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-deployments.html)」を参照してください。

### `list-environments`
<a name="appconfig_ListEnvironments_cli_2_topic"></a>

次のコード例は、`list-environments` を使用する方法を示しています。

**AWS CLI**  
**使用可能な環境を一覧表示する方法**  
次の の`list-environments`例では、指定されたアプリケーションの AWS アカウントで使用可能な環境を一覧表示します。  

```
aws appconfig list-environments \
    --application-id 339ohji
```
出力:  

```
{
    "Items": [
        {
            "ApplicationId": "339ohji",
            "Id": "54j1r29",
            "Name": "Example-Environment",
            "State": "ReadyForDeployment"
        }
    ]
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 2: 環境の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-environment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEnvironments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-environments.html)」を参照してください。

### `list-extension-associations`
<a name="appconfig_ListExtensionAssociations_cli_2_topic"></a>

次の例は、`list-extension-associations` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョンの AWS アカウント内のすべての AWS AppConfig 拡張機能の関連付けを一覧表示するには**  
次の の`list-extension-associations`例では、特定の AWS リージョンの現在の AWS アカウントのすべての AWS AppConfig 拡張機能の関連付けを一覧表示します。  

```
aws appconfig list-extension-associations \
    --region us-west-2
```
出力:  

```
{
    "Items": [
        {
            "Id": "a1b2c3d4",
            "ExtensionArn": "arn:aws:appconfig:us-west-2:123456789012:extension/S3-backup-extension/1",
            "ResourceArn": "arn:aws:appconfig:us-west-2:123456789012:application/Finance"
        }
    ]
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListExtensionAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-extension-associations.html)」を参照してください。

### `list-extensions`
<a name="appconfig_ListExtensions_cli_2_topic"></a>

次の例は、`list-extensions` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョンの AWS アカウント内のすべての AWS AppConfig 拡張機能を一覧表示するには**  
次の の`list-extensions`例では、特定の AWS リージョンの現在の AWS アカウントのすべての AWS AppConfig 拡張機能を一覧表示します。コマンドは、カスタム拡張機能とオー AWS サリングされた拡張機能を返します。  

```
aws appconfig list-extensions \
    --region us-west-2
```
出力:  

```
{
    "Items": [
        {
            "Id": "1A2B3C4D",
            "Name": "S3-backup-extension",
            "VersionNumber": 1,
            "Arn": "arn:aws:appconfig:us-west-2:123456789012:extension/1A2B3C4D/1"
        },
        {
            "Id": "AWS.AppConfig.FeatureFlags",
            "Name": "AppConfig Feature Flags Helper",
            "VersionNumber": 1,
            "Arn": "arn:aws:appconfig:us-west-2::extension/AWS.AppConfig.FeatureFlags/1",
            "Description": "Validates AppConfig feature flag data automatically against a JSON schema that includes structure and constraints. Also transforms feature flag data prior to sending to the client. This extension is automatically associated to configuration profiles with type \"AWS.AppConfig.FeatureFlags\"."
        },
        {
            "Id": "AWS.AppConfig.JiraIntegration",
            "Name": "AppConfig integration with Atlassian Jira",
            "VersionNumber": 1,
            "Arn": "arn:aws:appconfig:us-west-2::extension/AWS.AppConfig.JiraIntegration/1",
            "Description": "Exports feature flag data from AWS AppConfig into Jira. The lifecycle of each feature flag in AppConfig is tracked in Jira as an individual issue. Customers can see in Jira when flags are updated, turned on or off. Works in conjunction with the AppConfig app in the Atlassian Marketplace and is automatically associated to configuration profiles configured within that app."
        },
        {
            "Id": "AWS.AppConfig.DeploymentNotificationsToEventBridge",
            "Name": "AppConfig deployment events to Amazon EventBridge",
            "VersionNumber": 1,
            "Arn": "arn:aws:appconfig:us-west-2::extension/AWS.AppConfig.DeploymentNotificationsToEventBridge/1",
            "Description": "Sends events to Amazon EventBridge when a deployment of configuration data in AppConfig is started, completed, or rolled back. Can be associated to the following resources in AppConfig: Application, Environment, Configuration Profile."
        },
        {
            "Id": "AWS.AppConfig.DeploymentNotificationsToSqs",
            "Name": "AppConfig deployment events to Amazon SQS",
            "VersionNumber": 1,
            "Arn": "arn:aws:appconfig:us-west-2::extension/AWS.AppConfig.DeploymentNotificationsToSqs/1",
            "Description": "Sends messages to the configured Amazon SQS queue when a deployment of configuration data in AppConfig is started, completed, or rolled back. Can be associated to the following resources in AppConfig: Application, Environment, Configuration Profile."
        },
        {
            "Id": "AWS.AppConfig.DeploymentNotificationsToSns",
            "Name": "AppConfig deployment events to Amazon SNS",
            "VersionNumber": 1,
            "Description": "Sends events to the configured Amazon SNS topic when a deployment of configuration data in AppConfig is started, completed, or rolled back. Can be associated to the following resources in AppConfig: Application, Environment, Configuration Profile."
        }
    ]
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListExtensions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-extensions.html)」を参照してください。

### `list-hosted-configuration-versions`
<a name="appconfig_ListHostedConfigurationVersions_cli_2_topic"></a>

次のコード例は、`list-hosted-configuration-versions` を使用する方法を示しています。

**AWS CLI**  
**利用可能なホスト構成バージョンを一覧表示する方法**  
次の の`list-hosted-configuration-versions`例では、指定されたアプリケーションと設定プロファイルの AWS AppConfig ホスト設定ストアでホストされている設定バージョンを一覧表示します。  

```
aws appconfig list-hosted-configuration-versions \
    --application-id 339ohji \
    --configuration-profile-id ur8hx2f
```
出力:  

```
{
    "Items": [
        {
            "ApplicationId": "339ohji",
            "ConfigurationProfileId": "ur8hx2f",
            "VersionNumber": 1,
            "ContentType": "application/json"
        }
    ]
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig ホスト設定ストアについて](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html#appconfig-creating-configuration-and-profile-about-hosted-store)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHostedConfigurationVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-hosted-configuration-versions.html)」を参照してください。

### `list-tags-for-resource`
<a name="appconfig_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションのタグを一覧表示する方法**  
次の `list-tags-for-resource` の例では、指定されたアプリケーションのタグを一覧表示します。  

```
aws appconfig list-tags-for-resource \
    --resource-arn arn:aws:appconfig:us-east-1:682428703967:application/339ohji
```
出力:  

```
{
    "Tags": {
        "group1": "1"
    }
}
```
詳細については、[AWS AppConfig ユーザーガイドの「ステップ 1: AppConfig アプリケーションの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/list-tags-for-resource.html)」を参照してください。

### `start-deployment`
<a name="appconfig_StartDeployment_cli_2_topic"></a>

次のコード例は、`start-deployment` を使用する方法を示しています。

**AWS CLI**  
**構成デプロイを開始する方法**  
次の `start-deployment` の例では、指定された環境、デプロイ戦略、構成プロファイルを使用してアプリケーションへのデプロイを開始します。  

```
aws appconfig start-deployment \
    --application-id 339ohji \
    --environment-id 54j1r29 \
    --deployment-strategy-id 1225qzk \
    --configuration-profile-id ur8hx2f \
    --configuration-version 1
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "EnvironmentId": "54j1r29",
    "DeploymentStrategyId": "1225qzk",
    "ConfigurationProfileId": "ur8hx2f",
    "DeploymentNumber": 1,
    "ConfigurationName": "Example-Configuration-Profile",
    "ConfigurationLocationUri": "ssm-parameter://Example-Parameter",
    "ConfigurationVersion": "1",
    "DeploymentDurationInMinutes": 15,
    "GrowthType": "LINEAR",
    "GrowthFactor": 25.0,
    "FinalBakeTimeInMinutes": 0,
    "State": "DEPLOYING",
    "EventLog": [
        {
            "EventType": "DEPLOYMENT_STARTED",
            "TriggeredBy": "USER",
            "Description": "Deployment started",
            "OccurredAt": "2021-09-17T21:43:54.205000+00:00"
        }
    ],
    "PercentageComplete": 0.0,
    "StartedAt": "2021-09-17T21:43:54.205000+00:00"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の[「ステップ 5: 構成のデプロイ](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-deploying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/start-deployment.html)」を参照してください。

### `stop-deployment`
<a name="appconfig_StopDeployment_cli_2_topic"></a>

次のコード例は、`stop-deployment` を使用する方法を示しています。

**AWS CLI**  
**設定のデプロイを停止する方法**  
次の `stop-deployment` の例では、指定された環境へのアプリケーション設定のデプロイを停止します。  

```
aws appconfig stop-deployment \
    --application-id 339ohji \
    --environment-id 54j1r29 \
    --deployment-number 2
```
出力:  

```
{
    "DeploymentNumber": 0,
    "DeploymentDurationInMinutes": 0,
    "GrowthFactor": 0.0,
    "FinalBakeTimeInMinutes": 0,
    "PercentageComplete": 0.0
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の[「ステップ 5: 構成のデプロイ](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-deploying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/stop-deployment.html)」を参照してください。

### `tag-resource`
<a name="appconfig_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションにタグ付けする方法**  
次の `tag-resource` の例では、アプリケーションリソースにタグ付けします。  

```
aws appconfig tag-resource \
    --resource-arn arn:aws:appconfig:us-east-1:682428703967:application/339ohji \
    --tags '{"group1" : "1"}'
```
このコマンドでは何も出力されません。  
詳細については、[AWS AppConfig ユーザーガイドの「ステップ 1: AppConfig アプリケーションの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="appconfig_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションからタグを削除する方法**  
次の `untag-resource` の例では、指定されたアプリケーションから group1 のタグを削除します。  

```
aws appconfig untag-resource \
    --resource-arn arn:aws:appconfig:us-east-1:111122223333:application/339ohji \
    --tag-keys '["group1"]'
```
このコマンドでは何も出力されません。  
詳細については、[AWS AppConfig ユーザーガイドの「ステップ 1: AppConfig アプリケーションの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/untag-resource.html)」を参照してください。

### `update-application`
<a name="appconfig_UpdateApplication_cli_2_topic"></a>

次のコード例は、`update-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを更新する方法**  
次の `update-application` の例では、指定されたアプリケーションの名前を更新します。  

```
aws appconfig update-application \
    --application-id 339ohji \
    --name "Example-Application"
```
出力:  

```
{
    "Id": "339ohji",
    "Name": "Example-Application",
    "Description": "An application used for creating an example."
}
```
詳細については、[AWS AppConfig ユーザーガイドの「ステップ 1: AppConfig アプリケーションの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-application.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/update-application.html)」を参照してください。

### `update-configuration-profile`
<a name="appconfig_UpdateConfigurationProfile_cli_2_topic"></a>

次のコード例は、`update-configuration-profile` を使用する方法を示しています。

**AWS CLI**  
**構成プロファイルを更新する方法**  
次の `update-configuration-profile` の例では、指定された構成プロファイルの説明を更新します。  

```
aws appconfig update-configuration-profile \
    --application-id 339ohji \
    --configuration-profile-id ur8hx2f \
    --description "Configuration profile used for examples."
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "Id": "ur8hx2f",
    "Name": "Example-Configuration-Profile",
    "Description": "Configuration profile used for examples.",
    "LocationUri": "ssm-parameter://Example-Parameter",
    "RetrievalRoleArn": "arn:aws:iam::111122223333:role/Example-App-Config-Role"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 3: 構成および構成プロファイルの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateConfigurationProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/update-configuration-profile.html)」を参照してください。

### `update-deployment-strategy`
<a name="appconfig_UpdateDeploymentStrategy_cli_2_topic"></a>

次のコード例は、`update-deployment-strategy` を使用する方法を示しています。

**AWS CLI**  
**デプロイ戦略を更新する方法**  
次の `update-deployment-strategy` の例では、指定されたデプロイ戦略の最終ベイク時間を 20 分に更新します。  

```
aws appconfig update-deployment-strategy \
    --deployment-strategy-id 1225qzk \
    --final-bake-time-in-minutes 20
```
出力:  

```
{
    "Id": "1225qzk",
    "Name": "Example-Deployment",
    "DeploymentDurationInMinutes": 15,
    "GrowthType": "LINEAR",
    "GrowthFactor": 25.0,
    "FinalBakeTimeInMinutes": 20,
    "ReplicateTo": "SSM_DOCUMENT"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 4: デプロイ戦略の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-deployment-strategy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDeploymentStrategy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/update-deployment-strategy.html)」を参照してください。

### `update-environment`
<a name="appconfig_UpdateEnvironment_cli_2_topic"></a>

次のコード例は、`update-environment` を使用する方法を示しています。

**AWS CLI**  
**環境を更新する方法**  
次の `update-environment` の例では、環境の説明を更新します。  

```
aws appconfig update-environment \
    --application-id 339ohji \
    --environment-id 54j1r29 \
    --description "An environment for examples."
```
出力:  

```
{
    "ApplicationId": "339ohji",
    "Id": "54j1r29",
    "Name": "Example-Environment",
    "Description": "An environment for examples.",
    "State": "RolledBack"
}
```
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 2: 環境の作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-environment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/update-environment.html)」を参照してください。

### `update-extension-association`
<a name="appconfig_UpdateExtensionAssociation_cli_2_topic"></a>

次の例は、`update-extension-association` を使用する方法を説明しています。

**AWS CLI**  
** AWS AppConfig 拡張機能の関連付けを更新するには**  
次の`update-extension-association`例では、 AWS AppConfig で拡張機能の関連付けに新しいパラメータ値を追加します。  

```
aws appconfig update-extension-association \
    --region us-west-2 \
    --extension-association-id a1b2c3d4 \
    --parameters S3bucket=FinanceMobileApp
```
出力:  

```
{
    "Id": "a1b2c3d4",
    "ExtensionArn": "arn:aws:appconfig:us-west-2:123456789012:extension/S3-backup-extension/1",
    "ResourceArn": "arn:aws:appconfig:us-west-2:123456789012:application/Finance",
    "Parameters": {
        "S3bucket": "FinanceMobileApp"
    },
    "ExtensionVersionNumber": 1
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateExtensionAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/update-extension-association.html)」を参照してください。

### `update-extension`
<a name="appconfig_UpdateExtension_cli_2_topic"></a>

次の例は、`update-extension` を使用する方法を説明しています。

**AWS CLI**  
** AWS AppConfig 拡張機能を更新するには**  
次の`update-extension`例では、 AWS AppConfig の拡張機能にパラメータキーを追加します。  

```
aws appconfig update-extension \
    --region us-west-2 \
    --extension-identifier S3-backup-extension \
    --parameters S3bucket={Required=true},CampaignID={Required=false}
```
出力:  

```
{
    "Id": "1A2B3C4D",
    "Name": "S3-backup-extension",
    "VersionNumber": 1,
    "Arn": "arn:aws:appconfig:us-west-2:123456789012:extension/1A2B3C4D/1",
    "Actions": {
        "PRE_CREATE_HOSTED_CONFIGURATION_VERSION": [
            {
                "Name": "S3backup",
                "Uri": "arn:aws:lambda:us-west-2:123456789012:function:S3backupfunction",
                "RoleArn": "arn:aws:iam::123456789012:role/appconfigextensionrole"
            }
        ]
    },
    "Parameters": {
        "CampaignID": {
            "Required": false
        },
        "S3bucket": {
            "Required": true
        }
    }
}
```
詳細については、[AWS AppConfig ユーザーガイドの「AppConfig 拡張機能の使用](https://docs.aws.amazon.com/appconfig/latest/userguide/working-with-appconfig-extensions.html)」を参照してください。 *AWS AppConfig *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateExtension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/update-extension.html)」を参照してください。

### `validate-configuration`
<a name="appconfig_ValidateConfiguration_cli_2_topic"></a>

次のコード例は、`validate-configuration` を使用する方法を示しています。

**AWS CLI**  
**構成を検証する方法**  
次の `validate-configuration` の例では、構成プロファイルのバリデータを使用して構成を検証します。  

```
aws appconfig validate-configuration \
    --application-id abc1234 \
    --configuration-profile-id ur8hx2f \
    --configuration-version 1
```
このコマンドでは何も出力されません。  
詳細については、「*AWS AppConfig ユーザーガイド*」の「[ステップ 3: 構成および構成プロファイルの作成](https://docs.aws.amazon.com/appconfig/latest/userguide/appconfig-creating-configuration-and-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ValidateConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/appconfig/validate-configuration.html)」を参照してください。

# を使用した Application Auto Scaling の例 AWS CLI
<a name="cli_2_application-auto-scaling_code_examples"></a>

次のコード例は、Application Auto Scaling AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-scaling-policy`
<a name="application-auto-scaling_DeleteScalingPolicy_cli_2_topic"></a>

次のコード例は、`delete-scaling-policy` を使用する方法を示しています。

**AWS CLI**  
**スケーリングポリシーを削除する方法**  
この例では、デフォルトのクラスターで実行されている Amazon ECS サービスウェブアプリのスケーリングポリシーを削除します。  
コマンド:  

```
aws application-autoscaling delete-scaling-policy --policy-name web-app-cpu-lt-25 --scalable-dimension ecs:service:DesiredCount --resource-id service/default/web-app --service-namespace ecs
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteScalingPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/delete-scaling-policy.html)」を参照してください。

### `delete-scheduled-action`
<a name="application-auto-scaling_DeleteScheduledAction_cli_2_topic"></a>

次の例は、`delete-scheduled-action` を使用する方法を説明しています。

**AWS CLI**  
**スケジュールされたアクションを削除するには**  
次の `delete-scheduled-action` の例では、指定された Amazon AppStream 2.0 フリートから指定されたスケジュール済みアクションを削除します。  

```
aws application-autoscaling delete-scheduled-action \
    --service-namespace appstream \
    --scalable-dimension appstream:fleet:DesiredCapacity \
    --resource-id fleet/sample-fleet \
    --scheduled-action-name my-recurring-action
```
このコマンドでは何も出力されません。  
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[スケジュールされたスケーリング](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scheduled-scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteScheduledAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/delete-scheduled-action.html)」を参照してください。

### `deregister-scalable-target`
<a name="application-auto-scaling_DeregisterScalableTarget_cli_2_topic"></a>

次のコード例は、`deregister-scalable-target` を使用する方法を示しています。

**AWS CLI**  
**スケーラブルターゲットを登録解除する方法**  
この例では、デフォルトのクラスターで実行されているウェブアプリと呼ばれる Amazon ECS サービスのスケーラブルターゲットを登録解除します。  
コマンド:  

```
aws application-autoscaling deregister-scalable-target --service-namespace ecs --scalable-dimension ecs:service:DesiredCount --resource-id service/default/web-app
```
この例では、カスタムリソースのスケーラブルターゲットを登録解除します。custom-resource-id.txt ファイルにはリソース ID を識別する文字列が含まれており、これはカスタムリソースの場合、Amazon API Gateway エンドポイント経由でのカスタムリソースへのパスを表します。  
コマンド:  

```
aws application-autoscaling deregister-scalable-target --service-namespace custom-resource --scalable-dimension custom-resource:ResourceType:Property --resource-id file://~/custom-resource-id.txt
```
custom-resource-id.txt ファイルの内容:  

```
https://example.execute-api.us-west-2.amazonaws.com/prod/scalableTargetDimensions/1-23456789
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterScalableTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/deregister-scalable-target.html)」を参照してください。

### `describe-scalable-targets`
<a name="application-auto-scaling_DescribeScalableTargets_cli_2_topic"></a>

次のコード例は、`describe-scalable-targets` を使用する方法を示しています。

**AWS CLI**  
**スケーラブルターゲットを記述する方法**  
次の `describe-scalable-targets` 例では、`ecs` サービス名前空間のスケーラブルターゲットについて説明します。  

```
aws application-autoscaling describe-scalable-targets \
    --service-namespace ecs
```
出力:  

```
{
    "ScalableTargets": [
        {
            "ServiceNamespace": "ecs",
            "ScalableDimension": "ecs:service:DesiredCount",
            "ResourceId": "service/default/web-app",
            "MinCapacity": 1,
            "MaxCapacity": 10,
            "RoleARN": "arn:aws:iam::123456789012:role/aws-service-role/ecs.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_ECSService",
            "CreationTime": 1462558906.199,
            "SuspendedState": {
                "DynamicScalingOutSuspended": false,
                "ScheduledScalingSuspended": false,
                "DynamicScalingInSuspended": false
            },
            "ScalableTargetARN": "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123"
        }
    ]
}
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling と共に使用可能なAWS サービス](https://docs.aws.amazon.com/autoscaling/application/userguide/integrated-services-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScalableTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/describe-scalable-targets.html)」を参照してください。

### `describe-scaling-activities`
<a name="application-auto-scaling_DescribeScalingActivities_cli_2_topic"></a>

次のコード例は、`describe-scaling-activities` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定された Amazon ECS サービスのスケーリングアクティビティを記述する方法**  
次の `describe-scaling-activities` の例では、`default` クラスターで実行されている「`web-app`」という Amazon ECS サービスのスケーリングアクティビティについて記述します。出力には、スケーリングポリシーによって開始されたスケーリングアクティビティが表示されます。  

```
aws application-autoscaling describe-scaling-activities \
    --service-namespace ecs \
    --resource-id service/default/web-app
```
出力:  

```
{
    "ScalingActivities": [
        {
            "ScalableDimension": "ecs:service:DesiredCount",
            "Description": "Setting desired count to 1.",
            "ResourceId": "service/default/web-app",
            "ActivityId": "e6c5f7d1-dbbb-4a3f-89b2-51f33e766399",
            "StartTime": 1462575838.171,
            "ServiceNamespace": "ecs",
            "EndTime": 1462575872.111,
            "Cause": "monitor alarm web-app-cpu-lt-25 in state ALARM triggered policy web-app-cpu-lt-25",
            "StatusMessage": "Successfully set desired count to 1. Change successfully fulfilled by ecs.",
            "StatusCode": "Successful"
        }
    ]
}
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のスケーリングアクティビティ](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scaling-activities.html)」を参照してください。  
**例 2: 指定された DynamoDB テーブルのスケーリングアクティビティを記述する方法**  
次の `describe-scaling-activities` の例では、`TestTable` という DynamoDB テーブルのスケーリングアクティビティについて記述します。出力には、2 つの異なるスケジュールされたアクションによって開始されたスケーリングアクティビティが表示されます。  

```
aws application-autoscaling describe-scaling-activities \
    --service-namespace dynamodb \
    --resource-id table/TestTable
```
出力:  

```
{
    "ScalingActivities": [
        {
            "ScalableDimension": "dynamodb:table:WriteCapacityUnits",
            "Description": "Setting write capacity units to 10.",
            "ResourceId": "table/my-table",
            "ActivityId": "4d1308c0-bbcf-4514-a673-b0220ae38547",
            "StartTime": 1561574415.086,
            "ServiceNamespace": "dynamodb",
            "EndTime": 1561574449.51,
            "Cause": "maximum capacity was set to 10",
            "StatusMessage": "Successfully set write capacity units to 10. Change successfully fulfilled by dynamodb.",
            "StatusCode": "Successful"
        },
        {
            "ScalableDimension": "dynamodb:table:WriteCapacityUnits",
            "Description": "Setting min capacity to 5 and max capacity to 10",
            "ResourceId": "table/my-table",
            "ActivityId": "f2b7847b-721d-4e01-8ef0-0c8d3bacc1c7",
            "StartTime": 1561574414.644,
            "ServiceNamespace": "dynamodb",
            "Cause": "scheduled action name my-second-scheduled-action was triggered",
            "StatusMessage": "Successfully set min capacity to 5 and max capacity to 10",
            "StatusCode": "Successful"
        },
        {
            "ScalableDimension": "dynamodb:table:WriteCapacityUnits",
            "Description": "Setting write capacity units to 15.",
            "ResourceId": "table/my-table",
            "ActivityId": "d8ea4de6-9eaa-499f-b466-2cc5e681ba8b",
            "StartTime": 1561574108.904,
            "ServiceNamespace": "dynamodb",
            "EndTime": 1561574140.255,
            "Cause": "minimum capacity was set to 15",
            "StatusMessage": "Successfully set write capacity units to 15. Change successfully fulfilled by dynamodb.",
            "StatusCode": "Successful"
        },
        {
            "ScalableDimension": "dynamodb:table:WriteCapacityUnits",
            "Description": "Setting min capacity to 15 and max capacity to 20",
            "ResourceId": "table/my-table",
            "ActivityId": "3250fd06-6940-4e8e-bb1f-d494db7554d2",
            "StartTime": 1561574108.512,
            "ServiceNamespace": "dynamodb",
            "Cause": "scheduled action name my-first-scheduled-action was triggered",
            "StatusMessage": "Successfully set min capacity to 15 and max capacity to 20",
            "StatusCode": "Successful"
        }
    ]
}
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のスケーリングアクティビティ](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scaling-activities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScalingActivities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/describe-scaling-activities.html)」を参照してください。

### `describe-scaling-policies`
<a name="application-auto-scaling_DescribeScalingPolicies_cli_2_topic"></a>

次の例は、`describe-scaling-policies` を使用する方法を説明しています。

**AWS CLI**  
**スケーリングポリシーを記述する方法**  
この例では、ECS サービス名前空間のスケーリングポリシーについて記述します。  
コマンド:  

```
aws application-autoscaling describe-scaling-policies --service-namespace ecs
```
出力:  

```
{
    "ScalingPolicies": [
        {
            "PolicyName": "web-app-cpu-gt-75",
            "ScalableDimension": "ecs:service:DesiredCount",
            "ResourceId": "service/default/web-app",
            "CreationTime": 1462561899.23,
            "StepScalingPolicyConfiguration": {
                "Cooldown": 60,
                "StepAdjustments": [
                    {
                        "ScalingAdjustment": 200,
                        "MetricIntervalLowerBound": 0.0
                    }
                ],
                "AdjustmentType": "PercentChangeInCapacity"
            },
            "PolicyARN": "arn:aws:autoscaling:us-west-2:012345678910:scalingPolicy:6d8972f3-efc8-437c-92d1-6270f29a66e7:resource/ecs/service/default/web-app:policyName/web-app-cpu-gt-75",
            "PolicyType": "StepScaling",
            "Alarms": [
                {
                    "AlarmName": "web-app-cpu-gt-75",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:012345678910:alarm:web-app-cpu-gt-75"
                }
            ],
            "ServiceNamespace": "ecs"
        },
        {
            "PolicyName": "web-app-cpu-lt-25",
            "ScalableDimension": "ecs:service:DesiredCount",
            "ResourceId": "service/default/web-app",
            "CreationTime": 1462562575.099,
            "StepScalingPolicyConfiguration": {
                "Cooldown": 1,
                "StepAdjustments": [
                    {
                        "ScalingAdjustment": -50,
                        "MetricIntervalUpperBound": 0.0
                    }
                ],
                "AdjustmentType": "PercentChangeInCapacity"
            },
            "PolicyARN": "arn:aws:autoscaling:us-west-2:012345678910:scalingPolicy:6d8972f3-efc8-437c-92d1-6270f29a66e7:resource/ecs/service/default/web-app:policyName/web-app-cpu-lt-25",
            "PolicyType": "StepScaling",
            "Alarms": [
                {
                    "AlarmName": "web-app-cpu-lt-25",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:012345678910:alarm:web-app-cpu-lt-25"
                }
            ],
            "ServiceNamespace": "ecs"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScalingPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/describe-scaling-policies.html)」を参照してください。

### `describe-scheduled-actions`
<a name="application-auto-scaling_DescribeScheduledActions_cli_2_topic"></a>

次のコード例は、`describe-scheduled-actions` を使用する方法を示しています。

**AWS CLI**  
**スケジュールが設定されたアクションを記述する方法**  
次の `describe-scheduled-actions` の例では、指定されたサービス名前空間でスケジュールが設定されたアクションの詳細を表示します。  

```
aws application-autoscaling describe-scheduled-actions \
    --service-namespace dynamodb
```
出力:  

```
{
    "ScheduledActions": [
        {
            "ScalableDimension": "dynamodb:table:WriteCapacityUnits",
            "Schedule": "at(2019-05-20T18:35:00)",
            "ResourceId": "table/my-table",
            "CreationTime": 1561571888.361,
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledAction:2d36aa3b-cdf9-4565-b290-81db519b227d:resource/dynamodb/table/my-table:scheduledActionName/my-first-scheduled-action",
            "ScalableTargetAction": {
                "MinCapacity": 15,
                "MaxCapacity": 20
            },
            "ScheduledActionName": "my-first-scheduled-action",
            "ServiceNamespace": "dynamodb"
        },
        {
            "ScalableDimension": "dynamodb:table:WriteCapacityUnits",
            "Schedule": "at(2019-05-20T18:40:00)",
            "ResourceId": "table/my-table",
            "CreationTime": 1561571946.021,
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledAction:2d36aa3b-cdf9-4565-b290-81db519b227d:resource/dynamodb/table/my-table:scheduledActionName/my-second-scheduled-action",
            "ScalableTargetAction": {
                "MinCapacity": 5,
                "MaxCapacity": 10
            },
            "ScheduledActionName": "my-second-scheduled-action",
            "ServiceNamespace": "dynamodb"
        }
    ]
}
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[スケジュールされたスケーリング](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-scheduled-scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScheduledActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/describe-scheduled-actions.html)」を参照してください。

### `list-tags-for-resource`
<a name="application-auto-scaling_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**スケーラブルターゲットのタグを一覧表示する方法**  
次の `list-tags-for-resource` の例では、ARN で指定されたスケーラブルターゲットにアタッチされているタグキーの名前と値を一覧表示します。  

```
aws application-autoscaling list-tags-for-resource \
    --resource-arn arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123
```
出力:  

```
{
    "Tags": {
        "environment": "production"
    }
}
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のタグ付けサポート](https://docs.aws.amazon.com/autoscaling/application/userguide/resource-tagging-support.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/list-tags-for-resource.html)」を参照してください。

### `put-scaling-policy`
<a name="application-auto-scaling_PutScalingPolicy_cli_2_topic"></a>

次のコード例は、`put-scaling-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: 事前定義されたメトリクス指定を使用してターゲット追跡スケーリングポリシーを適用するには**  
以下の `put-scaling-policy` の例では、デフォルトクラスター内の web-app と呼ばれる Amazon ECS サービスに、事前に定義されたメトリック仕様でターゲット追跡スケーリングポリシーを適用します。このポリシーでは、サービスの平均 CPU 使用率を 75% に保ち、スケールアウトとスケールインのクールダウン期間は 60 秒です。出力には、自動的に作成された 2 つの CloudWatch アラームの ARN と名前が含まれます。  

```
aws application-autoscaling put-scaling-policy --service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/default/web-app \
--policy-name cpu75-target-tracking-scaling-policy --policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration file://config.json
```
この例では、現在のディレクトリに次の内容の config.json ファイルがあることを前提としています。  

```
{
     "TargetValue": 75.0,
     "PredefinedMetricSpecification": {
         "PredefinedMetricType": "ECSServiceAverageCPUUtilization"
     },
     "ScaleOutCooldown": 60,
    "ScaleInCooldown": 60
}
```
出力:  

```
{
    "PolicyARN": "arn:aws:autoscaling:us-west-2:012345678910:scalingPolicy:6d8972f3-efc8-437c-92d1-6270f29a66e7:resource/ecs/service/default/web-app:policyName/cpu75-target-tracking-scaling-policy",
    "Alarms": [
        {
            "AlarmARN": "arn:aws:cloudwatch:us-west-2:012345678910:alarm:TargetTracking-service/default/web-app-AlarmHigh-d4f0770c-b46e-434a-a60f-3b36d653feca",
            "AlarmName": "TargetTracking-service/default/web-app-AlarmHigh-d4f0770c-b46e-434a-a60f-3b36d653feca"
        },
        {
            "AlarmARN": "arn:aws:cloudwatch:us-west-2:012345678910:alarm:TargetTracking-service/default/web-app-AlarmLow-1b437334-d19b-4a63-a812-6c67aaf2910d",
            "AlarmName": "TargetTracking-service/default/web-app-AlarmLow-1b437334-d19b-4a63-a812-6c67aaf2910d"
        }
    ]
}
```
**例 2: カスタマイズされたメトリクス仕様を使用してターゲット追跡スケーリングポリシーを適用するには**  
以下の `put-scaling-policy` の例では、デフォルトクラスター内の web-app と呼ばれる Amazon ECS サービスに、カスタマイズされたメトリック仕様でターゲット追跡スケーリングポリシーを適用します。このポリシーでは、サービスの平均使用率を 75% に保ち、スケールアウトとスケールインのクールダウン期間は 60 秒です。出力には、自動的に作成された 2 つの CloudWatch アラームの ARN と名前が含まれます。  

```
aws application-autoscaling put-scaling-policy --service-namespace ecs \
--scalable-dimension ecs:service:DesiredCount \
--resource-id service/default/web-app \
--policy-name cms75-target-tracking-scaling-policy
--policy-type TargetTrackingScaling \
--target-tracking-scaling-policy-configuration file://config.json
```
この例では、現在のディレクトリに次の内容の config.json ファイルがあることを前提としています。  

```
{
    "TargetValue":75.0,
    "CustomizedMetricSpecification":{
        "MetricName":"MyUtilizationMetric",
        "Namespace":"MyNamespace",
        "Dimensions": [
            {
                "Name":"MyOptionalMetricDimensionName",
                "Value":"MyOptionalMetricDimensionValue"
            }
        ],
        "Statistic":"Average",
        "Unit":"Percent"
    },
    "ScaleOutCooldown": 60,
    "ScaleInCooldown": 60
}
```
出力:  

```
{
    "PolicyARN": "arn:aws:autoscaling:us-west-2:012345678910:scalingPolicy: 8784a896-b2ba-47a1-b08c-27301cc499a1:resource/ecs/service/default/web-app:policyName/cms75-target-tracking-scaling-policy",
    "Alarms": [
        {
            "AlarmARN": "arn:aws:cloudwatch:us-west-2:012345678910:alarm:TargetTracking-service/default/web-app-AlarmHigh-9bc77b56-0571-4276-ba0f-d4178882e0a0",
            "AlarmName": "TargetTracking-service/default/web-app-AlarmHigh-9bc77b56-0571-4276-ba0f-d4178882e0a0"
        },
        {
            "AlarmARN": "arn:aws:cloudwatch:us-west-2:012345678910:alarm:TargetTracking-service/default/web-app-AlarmLow-9b6ad934-6d37-438e-9e05-02836ddcbdc4",
            "AlarmName": "TargetTracking-service/default/web-app-AlarmLow-9b6ad934-6d37-438e-9e05-02836ddcbdc4"
        }
    ]
}
```
**例 3: スケールアウトにのみターゲット追跡スケーリングポリシーを適用するには**  
次の `put-scaling-policy` の例では、ターゲット追跡スケーリングポリシーを、デフォルトのクラスターで `web-app` という Amazon ECS サービスに適用します。このポリシーは、Application Load Balancer の `RequestCountPerTarget` メトリクスがしきい値を超えたときに ECS サービスをスケールアウトするために使用されます。出力には、自動的に作成された CloudWatch アラームの ARN と名前が含まれます。  

```
aws application-autoscaling put-scaling-policy \
    --service-namespace ecs \
    --scalable-dimension ecs:service:DesiredCount \
    --resource-id service/default/web-app \
    --policy-name alb-scale-out-target-tracking-scaling-policy \
    --policy-type TargetTrackingScaling \
    --target-tracking-scaling-policy-configuration file://config.json
```
`config.json` の内容:  

```
{
     "TargetValue": 1000.0,
     "PredefinedMetricSpecification": {
         "PredefinedMetricType": "ALBRequestCountPerTarget",
         "ResourceLabel": "app/EC2Co-EcsEl-1TKLTMITMM0EO/f37c06a68c1748aa/targetgroup/EC2Co-Defau-LDNM7Q3ZH1ZN/6d4ea56ca2d6a18d"
     },
     "ScaleOutCooldown": 60,
    "ScaleInCooldown": 60,
    "DisableScaleIn": true
}
```
出力:  

```
{
    "PolicyARN": "arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:6d8972f3-efc8-437c-92d1-6270f29a66e7:resource/ecs/service/default/web-app:policyName/alb-scale-out-target-tracking-scaling-policy",
    "Alarms": [
        {
            "AlarmName": "TargetTracking-service/default/web-app-AlarmHigh-d4f0770c-b46e-434a-a60f-3b36d653feca",
            "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-service/default/web-app-AlarmHigh-d4f0770c-b46e-434a-a60f-3b36d653feca"
        }
    ]
}
```
詳細については、「*AWS Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のターゲット追跡スケーリングポリシー](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-target-tracking.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutScalingPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/put-scaling-policy.html)」を参照してください。

### `put-scheduled-action`
<a name="application-auto-scaling_PutScheduledAction_cli_2_topic"></a>

次の例は、`put-scheduled-action` を使用する方法を説明しています。

**AWS CLI**  
**スケジュールされたアクションを DynamoDB テーブルに追加する方法**  
この例では、TestTable という名前の DynamoDB テーブルにスケジュールされたアクションを追加して、定期的なスケジュールに合わせてスケールアウトします。特定のスケジュール (毎日午後 12:15 (UTC)) で、現在の容量が MinCapacity に指定された値を下回る場合、Application Auto Scaling は MinCapacity で指定された値にスケールアウトします。  
コマンド:  

```
aws application-autoscaling put-scheduled-action --service-namespace dynamodb --scheduled-action-name my-recurring-action --schedule "cron(15 12 * * ? *)" --resource-id table/TestTable --scalable-dimension dynamodb:table:WriteCapacityUnits --scalable-target-action MinCapacity=6
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「スケジュールされたスケーリング」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutScheduledAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/put-scheduled-action.html)」を参照してください。

### `register-scalable-target`
<a name="application-auto-scaling_RegisterScalableTarget_cli_2_topic"></a>

次の例は、`register-scalable-target` を使用する方法を説明しています。

**AWS CLI**  
**例 1: ECS サービスをスケーラブルターゲットとして登録する方法**  
以下の `register-scalable-target` の例は、Amazon ECS サービスを Application Auto Scaling に登録します。また、スケーラブルターゲットにキー名「`environment`」と値「`production`」を含むタグを追加します。  

```
aws application-autoscaling register-scalable-target \
    --service-namespace ecs \
    --scalable-dimension ecs:service:DesiredCount \
    --resource-id service/default/web-app \
    --min-capacity 1 --max-capacity 10 \
    --tags environment=production
```
出力:  

```
{
    "ScalableTargetARN": "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123"
}
```
他の AWS サービスやカスタムリソースの例については、[AWS 「Application Auto Scaling ユーザーガイド」の「Application Auto Scaling で使用できる サービスの](https://docs.aws.amazon.com/autoscaling/application/userguide/integrated-services-list.html)*Auto Scaling*」を参照してください。  
**例 2: スケーラブルターゲットのスケーリングアクティビティを一時停止する方法**  
次の `register-scalable-target` の例では、既存のスケーラブルターゲットのスケーリングアクティビティを一時停止します。  

```
aws application-autoscaling register-scalable-target \
    --service-namespace dynamodb \
    --scalable-dimension dynamodb:table:ReadCapacityUnits \
    --resource-id table/my-table \
    --suspended-state DynamicScalingInSuspended=true,DynamicScalingOutSuspended=true,ScheduledScalingSuspended=true
```
出力:  

```
{
    "ScalableTargetARN": "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123"
}
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のスケーリングの一時停止と再開](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-suspend-resume-scaling.html)」を参照してください。  
**例 3: スケーラブルターゲットのスケーリングアクティビティを再開する方法**  
次の `register-scalable-target` の例では、既存のスケーラブルターゲットのスケーリングアクティビティを再開します。  

```
aws application-autoscaling register-scalable-target \
    --service-namespace dynamodb \
    --scalable-dimension dynamodb:table:ReadCapacityUnits \
    --resource-id table/my-table \
    --suspended-state DynamicScalingInSuspended=false,DynamicScalingOutSuspended=false,ScheduledScalingSuspended=false
```
出力:  

```
{
    "ScalableTargetARN": "arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123"
}
```
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のスケーリングの一時停止と再開](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-suspend-resume-scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterScalableTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/register-scalable-target.html)」を参照してください。

### `tag-resource`
<a name="application-auto-scaling_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**スケーラブルターゲットにタグを追加する方法**  
次の `tag-resource` の例では、ARN で指定されたスケーラブルターゲットにキー名「`environment`」と値「`production`」を含むタグを追加します。  

```
aws application-autoscaling tag-resource \
    --resource-arn arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123 \
    --tags environment=production
```
このコマンドでは何も出力されません。  
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のタグ付けサポート](https://docs.aws.amazon.com/autoscaling/application/userguide/resource-tagging-support.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="application-auto-scaling_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**スケーラブルターゲットからタグを削除する方法**  
次の `untag-resource` の例では、ARN で指定されたスケーラブルターゲットにキー名「`environment`」を含むタグペアを削除します。  

```
aws application-autoscaling untag-resource \
    --resource-arn arn:aws:application-autoscaling:us-west-2:123456789012:scalable-target/1234abcd56ab78cd901ef1234567890ab123 \
    --tag-keys "environment"
```
このコマンドでは何も出力されません。  
詳細については、「*Application Auto Scaling ユーザーガイド*」の「[Application Auto Scaling のタグ付けサポート](https://docs.aws.amazon.com/autoscaling/application/userguide/resource-tagging-support.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-autoscaling/untag-resource.html)」を参照してください。

# を使用した Application Discovery Service の例 AWS CLI
<a name="cli_2_application-discovery-service_code_examples"></a>

次のコード例は、Application Discovery Service AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-agents`
<a name="application-discovery-service_DescribeAgents_cli_2_topic"></a>

次のコード例では、`describe-agents` を使用する方法を示しています。

**AWS CLI**  
**指定された collectionStatus 状態を持つエージェントを説明する**  
この例では、コレクションステータスが「STARTED」または「STOPPED」のコレクションエージェントを記述します。  
コマンド:  

```
aws discovery describe-agents --filters name="collectionStatus",values="STARTED","STOPPED",condition="EQUALS" --max-results 3
```
出力:  

```
{
       "Snapshots": [
      {
            "version": "1.0.40.0",
            "agentType": "EC2",
            "hostName": "ip-172-31-40-234",
            "collectionStatus": "STOPPED",
            "agentNetworkInfoList": [
                {
                    "macAddress": "06:b5:97:14:fc:0d",
                    "ipAddress": "172.31.40.234"
                }
            ],
            "health": "UNKNOWN",
            "agentId": "i-003305c02a776e883",
            "registeredTime": "2016-12-09T19:05:06Z",
            "lastHealthPingTime": "2016-12-09T19:05:10Z"
        },
        {
            "version": "1.0.40.0",
            "agentType": "EC2",
            "hostName": "ip-172-31-39-64",
            "collectionStatus": "STARTED",
            "agentNetworkInfoList": [
                {
                    "macAddress": "06:a1:0e:c7:b2:73",
                    "ipAddress": "172.31.39.64"
                }
            ],
            "health": "SHUTDOWN",
            "agentId": "i-003a5e5e2b36cf8bd",
            "registeredTime": "2016-11-16T16:36:25Z",
            "lastHealthPingTime": "2016-11-16T16:47:37Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAgents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/discovery/describe-agents.html)」を参照してください。

### `describe-configurations`
<a name="application-discovery-service_DescribeConfigurations_cli_2_topic"></a>

次のコード例では、`describe-configurations` を使用する方法を示しています。

**AWS CLI**  
**選択したアセット構成の説明**  
この例では、2 つの指定されたサーバーの構成を記述します。アクションは、構成 ID からアセットのタイプを検出します。コマンドごとに許可されるアセットのタイプは 1 つだけです。  
コマンド:  

```
aws discovery describe-configurations --configuration-ids "d-server-099385097ef9fbcfb" "d-server-0c4f2dd1fee22c6c1"
```
出力:  

```
{
    "configurations": [
        {
                 "server.performance.maxCpuUsagePct": "0.0",
                 "server.performance.maxDiskReadIOPS": "0.0",
                 "server.performance.avgCpuUsagePct": "0.0",
                 "server.type": "EC2",
                 "server.performance.maxNetworkReadsPerSecondInKB": "0.19140625",
                 "server.hostName": "ip-172-31-35-152",
                 "server.configurationId": "d-server-0c4f2dd1fee22c6c1",
                 "server.tags.hasMoreValues": "false",
                 "server.performance.minFreeRAMInKB": "1543496.0",
                 "server.osVersion": "3.14.48-33.39.amzn1.x86_64",
                 "server.performance.maxDiskReadsPerSecondInKB": "0.0",
                 "server.applications": "[]",
                 "server.performance.numDisks": "1",
                 "server.performance.numCpus": "1",
                 "server.performance.numCores": "1",
                 "server.performance.maxDiskWriteIOPS": "0.0",
                 "server.performance.maxNetworkWritesPerSecondInKB": "0.82421875",
                 "server.performance.avgDiskWritesPerSecondInKB": "0.0",
                 "server.networkInterfaceInfo": "[{\"name\":\"eth0\",\"macAddress\":\"06:A7:7D:3F:54:57\",\"ipAddress\":\"172.31.35.152\",\"netMask\":\"255.255.240.0\"},{\"name\":\"lo\",\"macAddress\":\"00:00:00:00:00:00\",\"ipAddress\":\"127.0.0.1\",\"netMask\":\"255.0.0.0\"},{\"name\":\"eth0\",\"macAddress\":\"06:A7:7D:3F:54:57\",\"ipAddress\":\"fe80::4a7:7dff:fe3f:5457\"},{\"name\":\"lo\",\"macAddress\":\"00:00:00:00:00:00\",\"ipAddress\":\"::1\"}]",
                 "server.performance.avgNetworkReadsPerSecondInKB": "0.04915364583333333",
                 "server.tags": "[]",
                 "server.applications.hasMoreValues": "false",
                 "server.timeOfCreation": "2016-10-28 23:44:00.0",
                 "server.agentId": "i-4447bc1b",
                 "server.performance.maxDiskWritesPerSecondInKB": "0.0",
                 "server.performance.avgDiskReadIOPS": "0.0",
                 "server.performance.avgFreeRAMInKB": "1547210.1333333333",
                 "server.performance.avgDiskReadsPerSecondInKB": "0.0",
                 "server.performance.avgDiskWriteIOPS": "0.0",
                 "server.performance.numNetworkCards": "2",
                 "server.hypervisor": "xen",
                 "server.networkInterfaceInfo.hasMoreValues": "false",
                 "server.performance.avgNetworkWritesPerSecondInKB": "0.1380859375",
                 "server.osName": "Linux - Amazon Linux AMI release 2015.03",
                 "server.performance.totalRAMInKB": "1694732.0",
                 "server.cpuType": "x64"
        },
        {
                 "server.performance.maxCpuUsagePct": "100.0",
                 "server.performance.maxDiskReadIOPS": "0.0",
                 "server.performance.avgCpuUsagePct": "14.733333333333338",
                 "server.type": "EC2",
                 "server.performance.maxNetworkReadsPerSecondInKB": "13.400390625",
                 "server.hostName": "ip-172-31-42-208",
                 "server.configurationId": "d-server-099385097ef9fbcfb",
                 "server.tags.hasMoreValues": "false",
                 "server.performance.minFreeRAMInKB": "1531104.0",
                 "server.osVersion": "3.14.48-33.39.amzn1.x86_64",
                 "server.performance.maxDiskReadsPerSecondInKB": "0.0",
                 "server.applications": "[]",
                 "server.performance.numDisks": "1",
                 "server.performance.numCpus": "1",
                 "server.performance.numCores": "1",
                 "server.performance.maxDiskWriteIOPS": "1.0",
                 "server.performance.maxNetworkWritesPerSecondInKB": "12.271484375",
                 "server.performance.avgDiskWritesPerSecondInKB": "0.5333333333333334",
                 "server.networkInterfaceInfo": "[{\"name\":\"eth0\",\"macAddress\":\"06:4A:79:60:75:61\",\"ipAddress\":\"172.31.42.208\",\"netMask\":\"255.255.240.0\"},{\"name\":\"eth0\",\"macAddress\":\"06:4A:79:60:75:61\",\"ipAddress\":\"fe80::44a:79ff:fe60:7561\"},{\"name\":\"lo\",\"macAddress\":\"00:00:00:00:00:00\",\"ipAddress\":\"::1\"},{\"name\":\"lo\",\"macAddress\":\"00:00:00:00:00:00\",\"ipAddress\":\"127.0.0.1\",\"netMask\":\"255.0.0.0\"}]",
                 "server.performance.avgNetworkReadsPerSecondInKB": "2.8720052083333334",
                 "server.tags": "[]",
                 "server.applications.hasMoreValues": "false",
                 "server.timeOfCreation": "2016-10-28 23:44:30.0",
                 "server.agentId": "i-c142b99e",
                 "server.performance.maxDiskWritesPerSecondInKB": "4.0",
                 "server.performance.avgDiskReadIOPS": "0.0",
                 "server.performance.avgFreeRAMInKB": "1534946.4",
                 "server.performance.avgDiskReadsPerSecondInKB": "0.0",
                 "server.performance.avgDiskWriteIOPS": "0.13333333333333336",
                 "server.performance.numNetworkCards": "2",
                 "server.hypervisor": "xen",
                 "server.networkInterfaceInfo.hasMoreValues": "false",
                 "server.performance.avgNetworkWritesPerSecondInKB": "1.7977864583333332",
                 "server.osName": "Linux - Amazon Linux AMI release 2015.03",
                 "server.performance.totalRAMInKB": "1694732.0",
                 "server.cpuType": "x64"
        }
    ]
}
```
**選択したアセット構成の説明**  
この例では、2 つの指定されたアプリケーションの構成を記述します。アクションは、構成 ID からアセットのタイプを検出します。コマンドごとに許可されるアセットのタイプは 1 つだけです。  
コマンド:  

```
aws discovery describe-configurations --configuration-ids "d-application-0ac39bc0e4fad0e42" "d-application-02444a45288013764q"
```
出力:  

```
{
    "configurations": [
        {
                 "application.serverCount": "0",
                 "application.name": "Application-12345",
                 "application.lastModifiedTime": "2016-12-13 23:53:27.0",
                 "application.description": "",
                 "application.timeOfCreation": "2016-12-13 23:53:27.0",
                 "application.configurationId": "d-application-0ac39bc0e4fad0e42"
        },
        {
                 "application.serverCount": "0",
                 "application.name": "Application-67890",
                 "application.lastModifiedTime": "2016-12-13 23:53:33.0",
                 "application.description": "",
                 "application.timeOfCreation": "2016-12-13 23:53:33.0",
                 "application.configurationId": "d-application-02444a45288013764"
         }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/discovery/describe-configurations.html)」を参照してください。

### `list-configurations`
<a name="application-discovery-service_ListConfigurations_cli_2_topic"></a>

次のコード例では、`list-configurations` を使用する方法を示しています。

**AWS CLI**  
**一連のフィルタ条件を満たすサーバをすべて一覧表示する方法**  
このコマンド例では、Ubuntu を実行していない 2 つのホスト名パターンのいずれかに一致する検出されたサーバを一覧表示します。  
コマンド:  

```
aws discovery list-configurations --configuration-type SERVER --filters name="server.hostName",values="172-31-35","172-31-42",condition="CONTAINS" name="server.osName",values="Ubuntu",condition="NOT_CONTAINS"
```
出力:  

```
{
    "configurations": [
      {
            "server.osVersion": "3.14.48-33.39.amzn1.x86_64",
            "server.type": "EC2",
            "server.hostName": "ip-172-31-42-208",
            "server.timeOfCreation": "2016-10-28 23:44:30.0",
            "server.configurationId": "d-server-099385097ef9fbcfb",
            "server.osName": "Linux - Amazon Linux AMI release 2015.03",
            "server.agentId": "i-c142b99e"
        },
        {
            "server.osVersion": "3.14.48-33.39.amzn1.x86_64",
            "server.type": "EC2",
            "server.hostName": "ip-172-31-35-152",
            "server.timeOfCreation": "2016-10-28 23:44:00.0",
            "server.configurationId": "d-server-0c4f2dd1fee22c6c1",
            "server.osName": "Linux - Amazon Linux AMI release 2015.03",
            "server.agentId": "i-4447bc1b"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/discovery/list-configurations.html)」を参照してください。

# を使用した Application Signals の例 AWS CLI
<a name="cli_2_application-signals_code_examples"></a>

次のコード例は、Application Signals AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-get-service-level-objective-budget-report`
<a name="application-signals_BatchGetServiceLevelObjectiveBudgetReport_cli_2_topic"></a>

次のコード例は、`batch-get-service-level-objective-budget-report` を使用する方法を示しています。

**AWS CLI**  
**1 つ以上のサービスレベル目標 (SLO) 予算レポートを取得します。**  
次の `batch-get-service-level-objective-budget-report` 例では、1 つ以上のサービスレベル目標 (SLO) 予算レポートを取得します。  

```
aws application-signals batch-get-service-level-objective-budget-report \
--timestamp 1735059869 \
--slo-ids "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName1" "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName2"
```
出力:  

```
{
    "Timestamp": "2024-12-24T22:34:29+05:30",
    "Reports": [{
            "Arn": "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName1",
            "Name": "Your SLO Name",
            "EvaluationType": "PeriodBased",
            "BudgetStatus": "OK",
            "Attainment": 100.0,
            "TotalBudgetSeconds": 6048,
            "BudgetSecondsRemaining": 6048,
            "Sli": {
                "SliMetric": {
                    "MetricDataQueries": [{
                        "Id": "m1",
                        "MetricStat": {
                            "Metric": {
                                "Namespace": "AWS/EC2",
                                "MetricName": "CPUUtilization",
                                "Dimensions": [{
                                    "Name": "InstanceId",
                                    "Value": "i-0e098765432522"
                                }]
                            },
                            "Period": 60,
                            "Stat": "Average"
                        },
                        "ReturnData": true
                    }]
                },
                "MetricThreshold": 200.0,
                "ComparisonOperator": "LessThanOrEqualTo"
            },
            "Goal": {
                "Interval": {
                    "RollingInterval": {
                        "DurationUnit": "DAY",
                        "Duration": 7
                    }
                },
                "AttainmentGoal": 99.0,
                "WarningThreshold": 50.0
            }
        },
        {
            "Arn": "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName2",
            "Name": "test",
            "EvaluationType": "PeriodBased",
            "BudgetStatus": "BREACHED",
            "Attainment": 97.39583275,
            "TotalBudgetSeconds": 86,
            "BudgetSecondsRemaining": -2154,
            "Sli": {
                "SliMetric": {
                    "MetricDataQueries": [{
                        "Id": "cwMetric",
                        "MetricStat": {
                            "Metric": {
                                "Namespace": "AWS/EC2",
                                "MetricName": "CPUUtilization",
                                "Dimensions": [{
                                    "Name": "InstanceId",
                                    "Value": "i-0e12345678922"
                                }]
                            },
                            "Period": 300,
                            "Stat": "Average"
                        },
                        "ReturnData": true
                    }]
                },
                "MetricThreshold": 5.0,
                "ComparisonOperator": "GreaterThan"
            },
            "Goal": {
                "Interval": {
                    "RollingInterval": {
                        "DurationUnit": "DAY",
                        "Duration": 1
                    }
                },
                "AttainmentGoal": 99.9,
                "WarningThreshold": 30.0
            }
        }
    ],
    "Errors": []
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetServiceLevelObjectiveBudgetReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/batch-get-service-level-objective-budget-report.html)」を参照してください。

### `create-service-level-objective`
<a name="application-signals_CreateServiceLevelObjective_cli_2_topic"></a>

次のコード例は、`create-service-level-objective` を使用する方法を示しています。

**AWS CLI**  
**サービスレベル目標 (SLO) の作成方法**  
次の `create-service-level-objective` 例では、サービスレベル目標 (SLO) を作成します。これにより、重要なビジネスオペレーションが顧客の期待を満たしていることを確認することができます。  

```
aws application-signals create-service-level-objective \
    --name "SLOName" \
    --description "Description of your SLO" \
    --sli-config file://sli-config.json
```
`sli-config.json` の内容:  

```
{
    "SliMetricConfig": {
        "MetricDataQueries": [
            {
                "Id": "m1",
                "MetricStat": {
                    "Metric": {
                        "Namespace": "AWS/EC2",
                        "MetricName": "CPUUtilization",
                        "Dimensions": [
                            {
                                "Name": "InstanceId",
                                "Value": "i-0e5a1234561522"
                            }
                        ]
                    },
                    "Period": 60,
                    "Stat": "Average"
                },
                "ReturnData": true
            }
        ]
    },
    "MetricThreshold": 200,
    "ComparisonOperator": "LessThanOrEqualTo"
}
```
出力:  

```
{
    "Slo": {
    "Arn": "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName",
    "Name": "SLOName",
    "Description": "Description of your SLO",
    "CreatedTime": "2024-12-27T08:16:09.032000+05:30",
    "LastUpdatedTime": "2024-12-27T08:16:09.032000+05:30",
    "Sli": {
        "SliMetric": {
            "MetricDataQueries": [
                {
                    "Id": "m1",
                    "MetricStat": {
                        "Metric": {
                            "Namespace": "AWS/EC2",
                            "MetricName": "CPUUtilization",
                            "Dimensions": [
                                {
                                    "Name": "InstanceId",
                                    "Value": "i-0e59876543234522"
                                }
                            ]
                        },
                        "Period": 60,
                        "Stat": "Average"
                    },
                    "ReturnData": true
                }
            ]
        },
        "MetricThreshold": 200.0,
        "ComparisonOperator": "LessThanOrEqualTo"
    },
    "EvaluationType": "PeriodBased",
    "Goal": {
        "Interval": {
            "RollingInterval": {
                "DurationUnit": "DAY",
                "Duration": 7
            }
        },
        "AttainmentGoal": 99.0,
        "WarningThreshold": 50.0
      }
    }
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateServiceLevelObjective](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/create-service-level-objective.html)」を参照してください。

### `delete-service-level-objective`
<a name="application-signals_DeleteServiceLevelObjective_cli_2_topic"></a>

次のコード例は、`delete-service-level-objective` を使用する方法を示しています。

**AWS CLI**  
**指定されたサービスレベル目標を削除します。**  
次の `delete-service-level-objective` の例では、指定されたサービスレベル目標を削除します。  

```
aws application-signals delete-service-level-objective \
    --id "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceLevelObjective](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/delete-service-level-objective.html)」を参照してください。

### `get-service-level-objective`
<a name="application-signals_GetServiceLevelObjective_cli_2_topic"></a>

次のコード例は、`get-service-level-objective` を使用する方法を示しています。

**AWS CLI**  
**アカウントで作成された 1 つの SLO に関する情報を返す方法**  
次の `get-service-level-objective` 例では、アカウントで作成された 1 つの SLO に関する情報を返します。  

```
aws application-signals get-service-level-objective \
    --id "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName"
```
出力:  

```
{
    "Slo": {
        "Arn": "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName",
        "Name": "SLOName",
        "Description": "Description of your SLO",
        "CreatedTime": "2024-12-24T22:19:18.624000+05:30",
        "LastUpdatedTime": "2024-12-24T22:19:55.280000+05:30",
        "Sli": {
            "SliMetric": {
                "MetricDataQueries": [{
                    "Id": "m1",
                    "MetricStat": {
                        "Metric": {
                            "Namespace": "AWS/EC2",
                            "MetricName": "CPUUtilization",
                            "Dimensions": [{
                                "Name": "InstanceId",
                                "Value": "i-0e0987654321522"
                            }]
                        },
                        "Period": 60,
                        "Stat": "Average"
                    },
                    "ReturnData": true
                }]
            },
            "MetricThreshold": 200.0,
            "ComparisonOperator": "LessThanOrEqualTo"
        },
        "EvaluationType": "PeriodBased",
        "Goal": {
            "Interval": {
                "RollingInterval": {
                    "DurationUnit": "DAY",
                    "Duration": 7
                }
            },
            "AttainmentGoal": 99.0,
            "WarningThreshold": 50.0
        }
    }
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceLevelObjective](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/get-service-level-objective.html)」を参照してください。

### `get-service`
<a name="application-signals_GetService_cli_2_topic"></a>

次のコード例は、`get-service` を使用する方法を示しています。

**AWS CLI**  
**Application Signals によって検出されたサービスに関する情報を返す方法**  
次の `get-service` 例は、Application Signals によって検出されたサービスに関する情報を返します。  

```
aws application-signals get-service \
    --start-time 1732704000 \
    --end-time 1732714500 \
    --key-attributes Environment=lambda:default,Name=hello-world-python,Type=Service
```
出力:  

```
{
    "Service": {
        "KeyAttributes": {
            "Environment": "lambda:default",
            "Name": "hello-world-python",
            "Type": "Service"
        },
        "AttributeMaps": [{
            "Lambda.Function.Name": "hello-world-python",
            "PlatformType": "AWS::Lambda"
        }],
        "MetricReferences": [{
            "Namespace": "ApplicationSignals",
            "MetricType": "LATENCY",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "lambda:default"
            }, {
                "Name": "Service",
                "Value": "hello-world-python"
            }],
            "MetricName": "Latency"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "FAULT",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "lambda:default"
            }, {
                "Name": "Service",
                "Value": "hello-world-python"
            }],
            "MetricName": "Fault"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "ERROR",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "lambda:default"
            }, {
                "Name": "Service",
                "Value": "hello-world-python"
            }],
            "MetricName": "Error"
        }],
        "LogGroupReferences": [{
            "Identifier": "/aws/lambda/hello-world-python",
            "ResourceType": "AWS::Logs::LogGroup",
            "Type": "AWS::Resource"
        }]
    },
    "StartTime": "2024-11-27T10:00:00+00:00",
    "EndTime": "2024-11-27T14:00:01+00:00",
    "LogGroupReferences": [{
        "Identifier": "/aws/lambda/hello-world-python",
        "ResourceType": "AWS::Logs::LogGroup",
        "Type": "AWS::Resource"
    }]
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/get-service.html)」を参照してください。

### `list-service-dependencies`
<a name="application-signals_ListServiceDependencies_cli_2_topic"></a>

次のコード例は、`list-service-dependencies` を使用する方法を示しています。

**AWS CLI**  
**指定したサービスのサービス依存関係のリストを返す方法**  
次の `list-service-dependencies` 例は、指定したサービスのサービス依存関係のリストを返します。  

```
aws application-signals list-service-dependencies \
    --start-time 1732021200 \
    --end-time 1732107600 \
    --key-attributes Environment=api-gateway:prod, Name=PetAdoptionStatusUpdater,Type=Service
```
出力:  

```
{
    "ServiceDependencies": [{
        "OperationName": "PUT /prod",
        "DependencyKeyAttributes": {
            "Environment": "lambda:default",
            "Name": "Services-name",
            "Type": "Service"
        },
        "DependencyOperationName": "Invoke",
        "MetricReferences": [{
            "Namespace": "ApplicationSignals",
            "MetricType": "LATENCY",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "api-gateway:prod"
            }, {
                "Name": "Operation",
                "Value": "PUT /prod"
            }, {
                "Name": "RemoteEnvironment",
                "Value": "lambda:default"
            }, {
                "Name": "RemoteOperation",
                "Value": "Invoke"
            }, {
                "Name": "RemoteService",
                "Value": "Services-name"
            }, {
                "Name": "Service",
                "Value": "PetAdoptionStatusUpdater"
            }],
            "MetricName": "Latency"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "FAULT",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "api-gateway:prod"
            }, {
                "Name": "Operation",
                "Value": "PUT /prod"
            }, {
                "Name": "RemoteEnvironment",
                "Value": "lambda:default"
            }, {
                "Name": "RemoteOperation",
                "Value": "Invoke"
            }, {
                "Name": "RemoteService",
                "Value": "Services-name"
            }, {
                "Name": "Service",
                "Value": "PetAdoptionStatusUpdater"
            }],
            "MetricName": "Fault"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "ERROR",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "api-gateway:prod"
            }, {
                "Name": "Operation",
                "Value": "PUT /prod"
            }, {
                "Name": "RemoteEnvironment",
                "Value": "lambda:default"
            }, {
                "Name": "RemoteOperation",
                "Value": "Invoke"
            }, {
                "Name": "RemoteService",
                "Value": "Services-name"
            }, {
                "Name": "Service",
                "Value": "PetAdoptionStatusUpdater"
            }],
            "MetricName": "Error"
        }]
    }],
    "StartTime": "2024-11-19T13:00:00+00:00",
    "EndTime": "2024-11-20T13:00:01+00:00"
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceDependencies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/list-service-dependencies.html)」を参照してください。

### `list-service-dependents`
<a name="application-signals_ListServiceDependents_cli_2_topic"></a>

次のコード例は、`list-service-dependents` を使用する方法を示しています。

**AWS CLI**  
**指定された時間範囲内に指定されたサービスを呼び出した依存関係のリストを返す方法**  
次の `list-service-dependents` 例では、指定された時間範囲で指定されたサービスを呼び出した依存関係のリストを返します。  

```
aws application-signals list-service-dependents \
    --start-time 1732021200 \
    --end-time 1732107600 \
    --key-attributes Environment=generic:default,Name=PetSite,Type=Service
```
出力:  

```
{
    "ServiceDependents": [{
        "OperationName": "",
        "DependentKeyAttributes": {
            "Identifier": "pet-api-canary-hao",
            "ResourceType": "AWS::Synthetics::Canary",
            "Type": "AWS::Resource"
        },
        "DependentOperationName": "",
        "MetricReferences": []
    }, {
        "OperationName": "",
        "DependentKeyAttributes": {
            "Identifier": "PetSite",
            "ResourceType": "AWS::Synthetics::Canary",
            "Type": "AWS::Resource"
        },
        "DependentOperationName": "",
        "MetricReferences": []
    }],
    "StartTime": "2024-12-24T05:00:00+00:00",
    "EndTime": "2024-12-25T06:00:01+00:00"
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceDependents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/list-service-dependents.html)」を参照してください。

### `list-service-level-objectives`
<a name="application-signals_ListServiceLevelObjectives_cli_2_topic"></a>

次のコード例は、`list-service-level-objectives` を使用する方法を示しています。

**AWS CLI**  
**このアカウントで作成された SLO のリストを返します。**  
次の `list-service-level-objectives` の例では、このアカウントに作成された SLO のリストを返します。  

```
aws application-signals list-service-level-objectives
```
出力:  

```
{
    "SloSummaries": [{
        "Arn": "arn:aws:application-signals:us-east-1:123456789101:slo/test",
        "Name": "test",
        "CreatedTime": "2024-12-24T22:01:21.116000+05:30"
    }]
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceLevelObjectives](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/list-service-level-objectives.html)」を参照してください。

### `list-service-operations`
<a name="application-signals_ListServiceOperations_cli_2_topic"></a>

次のコード例は、`list-service-operations` を使用する方法を示しています。

**AWS CLI**  
**Application Signals によって検出されたこのサービスのオペレーションのリストを返す方法**  
次の `list-service-operations` 例では、Application Signals によって検出されたこのサービスのオペレーションのリストを返します。  

```
aws application-signals list-service-operations \
    --start-time 1735017423 \
    --end-time 1735103823 \
    --key-attributes Environment=generic:default,Name=payforadoption,Type=Service
```
出力:  

```
{
    "ServiceOperations": [{
        "Name": "POST /api",
        "MetricReferences": [{
            "Namespace": "ApplicationSignals",
            "MetricType": "LATENCY",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "generic:default"
            }, {
                "Name": "Operation",
                "Value": "POST /api"
            }, {
                "Name": "Service",
                "Value": "payforadoption"
            }],
            "MetricName": "Latency"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "FAULT",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "generic:default"
            }, {
                "Name": "Operation",
                "Value": "POST /api"
            }, {
                "Name": "Service",
                "Value": "payforadoption"
            }],
            "MetricName": "Fault"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "ERROR",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "generic:default"
            }, {
                "Name": "Operation",
                "Value": "POST /api"
            }, {
                "Name": "Service",
                "Value": "payforadoption"
            }],
            "MetricName": "Error"
        }]
    }],
    "StartTime": "2024-12-24T05:00:00+00:00",
    "EndTime": "2024-12-25T06:00:01+00:00"
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceOperations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/list-service-operations.html)」を参照してください。

### `list-services`
<a name="application-signals_ListServices_cli_2_topic"></a>

次のコード例は、`list-services` を使用する方法を示しています。

**AWS CLI**  
**Application Signals によって検出されたサービスのリストを返す方法**  
次の `list-services` 例では、Application Signals によって検出されたサービスのリストを返します。  

```
aws application-signals list-services \
    --start-time 1734918791 \
    --end-time 1734965591
```
出力:  

```
{
    "ServiceSummaries": [{
        "KeyAttributes": {
            "Environment": "lambda:default",
            "Name": "hello-world-python",
            "Type": "Service"
        },
        "AttributeMaps": [{
            "Lambda.Function.Name": "hello-world-python",
            "PlatformType": "AWS::Lambda"
        }],
        "MetricReferences": [{
            "Namespace": "ApplicationSignals",
            "MetricType": "LATENCY",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "lambda:default"
            }, {
                "Name": "Service",
                "Value": "hello-world-python"
            }],
            "MetricName": "Latency"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "FAULT",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "lambda:default"
            }, {
                "Name": "Service",
                "Value": "hello-world-python"
            }],
            "MetricName": "Fault"
        }, {
            "Namespace": "ApplicationSignals",
            "MetricType": "ERROR",
            "Dimensions": [{
                "Name": "Environment",
                "Value": "lambda:default"
            }, {
                "Name": "Service",
                "Value": "hello-world-python"
            }],
            "MetricName": "Error"
        }]
    }],
    "StartTime": "2024-11-27T10:00:00+00:00",
    "EndTime": "2024-11-27T14:00:01+00:00"
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/list-services.html)」を参照してください。**

### `list-tags-for-resource`
<a name="application-signals_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch リソースに関連付けられているタグを表示する方法**  
次の `list-tags-for-resource` の例では、CloudWatch リソースに関連付けられているタグを表示します。  

```
aws application-signals list-tags-for-resource \
    --resource-arn "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName"
```
出力:  

```
{
    "Tags": [{
        "Key": "test",
        "Value": "value"
    }]
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/list-tags-for-resource.html)」を参照してください。

### `start-discovery`
<a name="application-signals_StartDiscovery_cli_2_topic"></a>

次のコード例は、`start-discovery` を使用する方法を示しています。

**AWS CLI**  
**この Amazon Web Services アカウントが CloudWatch Application Signals を使用できるようにする方法**  
次の `start-discovery` 例では、サービスにリンクされたロール *AWS ServiceRoleForCloudWatchApplicationSignals* を作成することで、この Amazon Web Services アカウントが CloudWatch Application Signals を使用できるようにします。  

```
aws application-signals start-discovery
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDiscovery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/start-discovery.html)」を参照してください。

### `tag-resource`
<a name="application-signals_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**サービスレベルの目標など、指定された CloudWatch リソースに 1 つ以上のタグ (キーと値のペア) を割り当てる方法**  
次の `tag-resource` 例では、サービスレベルの目標など、指定された CloudWatch リソースに 1 つ以上のタグ (キーと値のペア) を割り当てます。  

```
aws application-signals tag-resource \
    --resource-arn "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName" \
    --tags '{"Key":"test","Value":"value"}'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="application-signals_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定したリソースから 1 つ以上のタグを削除するには**  
次の `untag-resource` 例では、指定されたリソースから 1 つ以上のタグを削除します。  

```
aws application-signals untag-resource \
    --resource-arn "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName" \
    --tag-keys "test"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/untag-resource.html)」を参照してください。

### `update-service-level-objective`
<a name="application-signals_UpdateServiceLevelObjective_cli_2_topic"></a>

次のコード例は、`update-service-level-objective` を使用する方法を示しています。

**AWS CLI**  
**既存のサービスレベル目標 (SLO) を更新するには**  
次の `update-service-level-objective` 例では、既存のサービスレベル目標 (SLO) を更新します。  

```
aws application-signals update-service-level-objective \
--cli-input-json file://update-slo.json
```
`update-slo.json` の内容:  

```
{
    "id": "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName",
    "goal": {
        "Interval": {
            "RollingInterval": {
                "DurationUnit": "DAY",
                "Duration": 7
            }
        },
        "AttainmentGoal": 90.0,
        "WarningThreshold": 50.0
    }
}
```
出力:  

```
{
    "Slo": {
        "Arn": "arn:aws:application-signals:us-east-1:123456789101:slo/SLOName",
        "Name": "SLOName",
        "Description": "Description of your SLO",
        "CreatedTime": "2024-12-24T22:19:18.624000+05:30",
        "LastUpdatedTime": "2024-12-27T08:51:38.278000+05:30",
        "Sli": {
            "SliMetric": {
                "MetricDataQueries": [{
                    "Id": "m1",
                    "MetricStat": {
                        "Metric": {
                            "Namespace": "AWS/EC2",
                            "MetricName": "CPUUtilization",
                            "Dimensions": [{
                                "Name": "InstanceId",
                                "Value": "i-00987654345222"
                            }]
                        },
                        "Period": 60,
                        "Stat": "Average"
                    },
                    "ReturnData": true
                }]
            },
            "MetricThreshold": 200.0,
            "ComparisonOperator": "LessThanOrEqualTo"
        },
        "EvaluationType": "PeriodBased",
        "Goal": {
            "Interval": {
                "RollingInterval": {
                    "DurationUnit": "DAY",
                    "Duration": 7
                }
            },
            "AttainmentGoal": 90.0,
            "WarningThreshold": 50.0
        }
    }
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Application Signals](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Application-Monitoring-Sections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServiceLevelObjective](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/application-signals/update-service-level-objective.html)」を参照してください。

# を使用した AppRegistry の例 AWS CLI
<a name="cli_2_service-catalog-appregistry_code_examples"></a>

次のコード例は、AppRegistry AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-attribute-group`
<a name="service-catalog-appregistry_AssociateAttributeGroup_cli_2_topic"></a>

次のコード例は、`associate-attribute-group` を使用する方法を示しています。

**AWS CLI**  
**属性グループを関連付けるには**  
次の の`associate-attribute-group`例では、 AWS アカウント内の特定の属性グループを AWS アカウント内の特定のアプリケーションに関連付けます。  

```
aws servicecatalog-appregistry associate-attribute-group \
    --application "ExampleApplication" \
    --attribute-group "ExampleAttributeGroup"
```
出力:  

```
{
    "applicationArn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/0ars38r6btoohvpvd9gqrptt9l",
    "attributeGroupArn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/01sj5xdwhbw54kejwnt09fnpcl"
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Associating and disassociating attribute groups](https://docs.aws.amazon.com/servicecatalog/latest/arguide/associate-attr-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateAttributeGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/associate-attribute-group.html)」を参照してください。

### `create-application`
<a name="service-catalog-appregistry_CreateApplication_cli_2_topic"></a>

次のコード例は、`create-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを作成する方法**  
次の の`create-application`例では、 AWS アカウントに新しいアプリケーションを作成します。  

```
aws servicecatalog-appregistry create-application \
    --name "ExampleApplication"
```
出力:  

```
{
    "application": {
        "id": "0ars38r6btoohvpvd9gqrptt9l",
        "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/0ars38r6btoohvpvd9gqrptt9l",
        "name": "ExampleApplication",
        "creationTime": "2023-02-28T21:10:10.820000+00:00",
        "lastUpdateTime": "2023-02-28T21:10:10.820000+00:00",
        "tags": {}
    }
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Creating applications](https://docs.aws.amazon.com/servicecatalog/latest/arguide/create-apps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/create-application.html)」を参照してください。

### `create-attribute-group`
<a name="service-catalog-appregistry_CreateAttributeGroup_cli_2_topic"></a>

次のコード例は、`create-attribute-group` を使用する方法を示しています。

**AWS CLI**  
**属性グループを作成するには**  
次の の`create-attribute-group`例では、 AWS アカウントに新しい属性グループを作成します。  

```
aws servicecatalog-appregistry create-attribute-group \
    --name "ExampleAttributeGroup" \
    --attributes '{"SomeKey1":"SomeValue1","SomeKey2":"SomeValue2"}'
```
出力:  

```
{
    "attributeGroup": {
        "id": "01sj5xdwhbw54kejwnt09fnpcl",
        "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/01sj5xdwhbw54kejwnt09fnpcl",
        "name": "ExampleAttributeGroup",
        "creationTime": "2023-02-28T20:38:01.389000+00:00",
        "lastUpdateTime": "2023-02-28T20:38:01.389000+00:00",
        "tags": {}
    }
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Creating attribute groups](https://docs.aws.amazon.com/servicecatalog/latest/arguide/create-attr-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAttributeGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/create-attribute-group.html)」を参照してください。

### `delete-application`
<a name="service-catalog-appregistry_DeleteApplication_cli_2_topic"></a>

次のコード例は、`delete-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを削除するには**  
次の の`delete-application`例では、 AWS アカウント内の特定のアプリケーションを削除します。  

```
aws servicecatalog-appregistry delete-application \
    --application "ExampleApplication3"
```
出力:  

```
{
    "application": {
        "id": "055gw7aynr1i5mbv7kjwzx5945",
        "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/055gw7aynr1i5mbv7kjwzx5945",
        "name": "ExampleApplication3",
        "creationTime": "2023-02-28T22:06:28.228000+00:00",
        "lastUpdateTime": "2023-02-28T22:06:28.228000+00:00"
    }
}
```
詳細については、「AWS Service Catalog AppRegistry 管理者ガイド」の「[Deleting applications](https://docs.aws.amazon.com/servicecatalog/latest/arguide/delete-app-details.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/delete-application.html)」を参照してください。

### `delete-attribute-group`
<a name="service-catalog-appregistry_DeleteAttributeGroup_cli_2_topic"></a>

次のコード例は、`delete-attribute-group` を使用する方法を示しています。

**AWS CLI**  
**例 8: 属性グループを削除するには**  
次の の`delete-attribute-group`例では、 AWS アカウント内の特定の属性グループを削除します。  

```
aws servicecatalog-appregistry delete-attribute-group \
    --attribute-group "ExampleAttributeGroup3"
```
出力:  

```
{
    "attributeGroup": {
        "id": "011ge6y3emyjijt8dw8jn6r0hv",
        "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/011ge6y3emyjijt8dw8jn6r0hv",
        "name": "ExampleAttributeGroup3",
        "creationTime": "2023-02-28T22:05:35.224000+00:00",
        "lastUpdateTime": "2023-02-28T22:05:35.224000+00:00"
    }
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Deleting attribute groups](https://docs.aws.amazon.com/servicecatalog/latest/arguide/delete-attr-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAttributeGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/delete-attribute-group.html)」を参照してください。

### `get-application`
<a name="service-catalog-appregistry_GetApplication_cli_2_topic"></a>

次のコード例は、`get-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを取得するには**  
次の の`get-application`例では、 AWS アカウント内の特定のアプリケーションに関するメタデータ情報を取得します。  

```
aws servicecatalog-appregistry get-application \
    --application "ExampleApplication"
```
出力:  

```
{
    "id": "0ars38r6btoohvpvd9gqrptt9l",
    "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/0ars38r6btoohvpvd9gqrptt9l",
    "name": "ExampleApplication",
    "creationTime": "2023-02-28T21:10:10.820000+00:00",
    "lastUpdateTime": "2023-02-28T21:10:10.820000+00:00",
    "associatedResourceCount": 0,
    "tags": {
        "aws:servicecatalog:applicationName": "ExampleApplication"
    },
    "integrations": {
        "resourceGroup": {
            "state": "CREATE_COMPLETE",
            "arn": "arn:aws:resource-groups:us-west-2:813737243517:group/AWS_AppRegistry_Application-ExampleApplication"
        }
    }
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Using Application details](https://docs.aws.amazon.com/servicecatalog/latest/arguide/access-app-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/get-application.html)」を参照してください。

### `get-attribute-group`
<a name="service-catalog-appregistry_GetAttributeGroup_cli_2_topic"></a>

次のコード例は、`get-attribute-group` を使用する方法を示しています。

**AWS CLI**  
**属性グループを取得するには**  
次の の`get-attribute-group`例では、 AWS アカウント内の特定の属性グループを取得します。  

```
aws servicecatalog-appregistry get-attribute-group \
    --attribute-group "ExampleAttributeGroup"
```
出力:  

```
{
    "id": "01sj5xdwhbw54kejwnt09fnpcl",
    "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/01sj5xdwhbw54kejwnt09fnpcl",
    "name": "ExampleAttributeGroup",
    "attributes": "{\"SomeKey1\":\"SomeValue1\",\"SomeKey2\":\"SomeValue2\"}",
    "creationTime": "2023-02-28T20:38:01.389000+00:00",
    "lastUpdateTime": "2023-02-28T20:38:01.389000+00:00",
    "tags": {
        "aws:servicecatalog:attributeGroupName": "ExampleAttributeGroup"
    }
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[属性グループのメタデータの管理](https://docs.aws.amazon.com/servicecatalog/latest/arguide/manage-metatdata.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAttributeGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/get-attribute-group.html)」を参照してください。

### `list-applications`
<a name="service-catalog-appregistry_ListApplications_cli_2_topic"></a>

次のコード例は、`list-applications` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを一覧表示するには**  
次の の`list-applications`例では、 AWS アカウント内のすべてのアプリケーションのリストを取得します。  

```
aws servicecatalog-appregistry list-applications
```
出力:  

```
{
    "applications": [
        {
            "id": "03axw94pjfj3uan00tcgbrxnkw",
            "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/03axw94pjfj3uan00tcgbrxnkw",
            "name": "ExampleApplication2",
            "creationTime": "2023-02-28T21:59:34.094000+00:00",
            "lastUpdateTime": "2023-02-28T21:59:34.094000+00:00"
        },
        {
            "id": "055gw7aynr1i5mbv7kjwzx5945",
            "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/055gw7aynr1i5mbv7kjwzx5945",
            "name": "ExampleApplication3",
            "creationTime": "2023-02-28T22:06:28.228000+00:00",
            "lastUpdateTime": "2023-02-28T22:06:28.228000+00:00"
        },
        {
            "id": "0ars38r6btoohvpvd9gqrptt9l",
            "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/0ars38r6btoohvpvd9gqrptt9l",
            "name": "ExampleApplication",
            "description": "This is an example application",
            "creationTime": "2023-02-28T21:10:10.820000+00:00",
            "lastUpdateTime": "2023-02-28T21:24:19.729000+00:00"
        }
    ]
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Viewing Application details](https://docs.aws.amazon.com/servicecatalog/latest/arguide/view-app-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListApplications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/list-applications.html)」を参照してください。

### `list-associated-attribute-groups`
<a name="service-catalog-appregistry_ListAssociatedAttributeGroups_cli_2_topic"></a>

次のコード例は、`list-associated-attribute-groups` を使用する方法を示しています。

**AWS CLI**  
**関連付けられた属性グループを一覧表示するには**  
次の の`list-associated-attribute-groups`例では、 AWS アカウント内の特定のアプリケーションに関連付けられている AWS アカウント内のすべての属性グループのリストを取得します。  

```
aws servicecatalog-appregistry list-associated-attribute-groups \
    --application "ExampleApplication"
```
出力:  

```
{
    "attributeGroups": [
        "01sj5xdwhbw54kejwnt09fnpcl"
    ]
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Associating and disassociating attribute groups](https://https://docs.aws.amazon.com/servicecatalog/latest/arguide/associate-attr-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssociatedAttributeGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/list-associated-attribute-groups.html)」を参照してください。

### `list-attribute-groups-for-application`
<a name="service-catalog-appregistry_ListAttributeGroupsForApplication_cli_2_topic"></a>

次のコード例は、`list-attribute-groups-for-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの属性グループを一覧表示するには**  
次の の`list-attribute-groups-for-application`例では、 AWS アカウント内の特定のアプリケーションに関連付けられている AWS アカウント内のすべての属性グループの詳細を一覧表示します。  

```
aws servicecatalog-appregistry list-attribute-groups-for-application \
    --application "ExampleApplication"
```
出力:  

```
{
    "attributeGroupsDetails": [
        {
            "id": "01sj5xdwhbw54kejwnt09fnpcl",
            "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/01sj5xdwhbw54kejwnt09fnpcl",
            "name": "ExampleAttributeGroup"
        }
    ]
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Viewing attribute group details](https://servicecatalog/latest/arguide/view-attr-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttributeGroupsForApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/list-attribute-groups-for-application.html)」を参照してください。

### `list-attribute-groups`
<a name="service-catalog-appregistry_ListAttributeGroups_cli_2_topic"></a>

次のコード例は、`list-attribute-groups` を使用する方法を示しています。

**AWS CLI**  
**属性グループを一覧表示するには**  
次の の`list-attribute-groups`例では、 AWS アカウント内のすべての属性グループのリストを取得します。  

```
aws servicecatalog-appregistry list-attribute-groups
```
出力:  

```
{
    "attributeGroups": [
        {
            "id": "011ge6y3emyjijt8dw8jn6r0hv",
            "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/011ge6y3emyjijt8dw8jn6r0hv",
            "name": "ExampleAttributeGroup3",
            "creationTime": "2023-02-28T22:05:35.224000+00:00",
            "lastUpdateTime": "2023-02-28T22:05:35.224000+00:00"
        },
        {
            "id": "01sj5xdwhbw54kejwnt09fnpcl",
            "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/01sj5xdwhbw54kejwnt09fnpcl",
            "name": "ExampleAttributeGroup",
            "description": "This is an example attribute group",
            "creationTime": "2023-02-28T20:38:01.389000+00:00",
            "lastUpdateTime": "2023-02-28T21:02:04.559000+00:00"
        },
        {
            "id": "03n1yffgq6d18vwrzxf0c70nm3",
            "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/03n1yffgq6d18vwrzxf0c70nm3",
            "name": "ExampleAttributeGroup2",
            "creationTime": "2023-02-28T21:57:30.687000+00:00",
            "lastUpdateTime": "2023-02-28T21:57:30.687000+00:00"
        }
    ]
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Viewing attribute group details](https://docs.aws.amazon.com/servicecatalog/latest/arguide/view-attr-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttributeGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/list-attribute-groups.html)」を参照してください。

### `update-application`
<a name="service-catalog-appregistry_UpdateApplication_cli_2_topic"></a>

次のコード例は、`update-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを更新する方法**  
次の の`update-application`例では、 AWS アカウント内の特定のアプリケーションを更新して説明を含めます。  

```
aws servicecatalog-appregistry update-application \
    --application "ExampleApplication" \
    --description "This is an example application"
```
出力:  

```
{
    "application": {
        "id": "0ars38r6btoohvpvd9gqrptt9l",
        "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/applications/0ars38r6btoohvpvd9gqrptt9l",
        "name": "ExampleApplication",
        "description": "This is an example application",
        "creationTime": "2023-02-28T21:10:10.820000+00:00",
        "lastUpdateTime": "2023-02-28T21:24:19.729000+00:00",
        "tags": {
            "aws:servicecatalog:applicationName": "ExampleApplication"
        }
    }
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Editing applications](https://docs.aws.amazon.com/servicecatalog/latest/arguide/edit-apps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/update-application.html)」を参照してください。

### `update-attribute-group`
<a name="service-catalog-appregistry_UpdateAttributeGroup_cli_2_topic"></a>

次のコード例は、`update-attribute-group` を使用する方法を示しています。

**AWS CLI**  
**属性グループを更新するには**  
次の の`update-attribute-group`例では、 AWS アカウント内の特定の属性グループを更新して説明を含めます。  

```
aws servicecatalog-appregistry update-attribute-group \
    --attribute-group "ExampleAttributeGroup" \
    --description "This is an example attribute group"
```
出力:  

```
{
    "attributeGroup": {
        "id": "01sj5xdwhbw54kejwnt09fnpcl",
        "arn": "arn:aws:servicecatalog:us-west-2:813737243517:/attribute-groups/01sj5xdwhbw54kejwnt09fnpcl",
        "name": "ExampleAttributeGroup",
        "description": "This is an example attribute group",
        "creationTime": "2023-02-28T20:38:01.389000+00:00",
        "lastUpdateTime": "2023-02-28T21:02:04.559000+00:00",
        "tags": {
            "aws:servicecatalog:attributeGroupName": "ExampleAttributeGroup"
        }
    }
}
```
詳細については、「*AWS Service Catalog AppRegistry 管理者ガイド*」の「[Editing attribute groups](https://docs.aws.amazon.com/servicecatalog/latest/arguide/edit-attr-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAttributeGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog-appregistry/update-attribute-group.html)」を参照してください。

# を使用した Athena の例 AWS CLI
<a name="cli_2_athena_code_examples"></a>

次のコード例は、Athena AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-get-named-query`
<a name="athena_BatchGetNamedQuery_cli_2_topic"></a>

次の例では、`batch-get-named-query` を使用する方法を説明しています。

**AWS CLI**  
**複数のクエリに関する情報を返す方法**  
次の `batch-get-named-query` 例では、指定された ID を持つ名前付きクエリに関する情報を返します。  

```
aws athena batch-get-named-query \
    --named-query-ids a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 a1b2c3d4-5678-90ab-cdef-EXAMPLE22222 a1b2c3d4-5678-90ab-cdef-EXAMPLE33333
```
出力:  

```
{
    "NamedQueries": [
        {
            "Name": "Flights Select Query",
            "Description": "Sample query to get the top 10 airports with the most number of departures since 2000",
            "Database": "sampledb",
            "QueryString": "SELECT origin, count(*) AS total_departures\nFROM\nflights_parquet\nWHERE year >= '2000'\nGROUP BY origin\nORDER BY total_departures DESC\nLIMIT 10;",
            "NamedQueryId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "WorkGroup": "primary"
        },
        {
            "Name": "Load flights table partitions",
            "Description": "Sample query to load flights table partitions using MSCK REPAIR TABLE statement",
            "Database": "sampledb",
            "QueryString": "MSCK REPAIR TABLE flights_parquet;",
            "NamedQueryId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "WorkGroup": "primary"
        },
        {
            "Name": "CloudFront Select Query",
            "Description": "Sample query to view requests per operating system during a particular time frame",
            "Database": "sampledb",
            "QueryString": "SELECT os, COUNT(*) count FROM cloudfront_logs WHERE date BETWEEN date '2014-07-05' AND date '2014-08-05' GROUP BY os;",
            "NamedQueryId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "WorkGroup": "primary"
        }
    ],
    "UnprocessedNamedQueryIds": []
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetNamedQuery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/batch-get-named-query.html)」を参照してください。

### `batch-get-query-execution`
<a name="athena_BatchGetQueryExecution_cli_2_topic"></a>

次の例では、`batch-get-query-execution` を使用する方法を説明しています。

**AWS CLI**  
**複数のクエリ実行に関する情報を返す方法**  
次の `batch-get-query-execution` の例では、指定されたクエリ ID を持つクエリのクエリ実行情報を返します。  

```
aws athena batch-get-query-execution \
    --query-execution-ids a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 a1b2c3d4-5678-90ab-cdef-EXAMPLE22222
```
出力:  

```
{
    "QueryExecutions": [
        {
            "QueryExecutionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Query": "create database if not exists webdata",
            "StatementType": "DDL",
            "ResultConfiguration": {
                "OutputLocation": "s3://amzn-s3-demo-bucket/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111.txt"
            },
            "QueryExecutionContext": {},
            "Status": {
                "State": "SUCCEEDED",
                "SubmissionDateTime": 1593470720.592,
                "CompletionDateTime": 1593470720.902
            },
            "Statistics": {
                "EngineExecutionTimeInMillis": 232,
                "DataScannedInBytes": 0,
                "TotalExecutionTimeInMillis": 310,
            "ResultConfiguration": {

                "QueryQueueTimeInMillis": 50,
                "ServiceProcessingTimeInMillis": 28
            },
            "WorkGroup": "AthenaAdmin"
        },
        {
            "QueryExecutionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "Query": "select date, location, browser, uri, status from cloudfront_logs where method = 'GET' and status = 200 and location like 'SFO%' limit 10",
            "StatementType": "DML",
            "ResultConfiguration": {
                "OutputLocation": "s3://amzn-s3-demo-bucket/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222.csv"
            },
            "QueryExecutionContext": {
                "Database": "mydatabase",
                "Catalog": "awsdatacatalog"
            },
            "Status": {
                "State": "SUCCEEDED",
                "SubmissionDateTime": 1593469842.665,
                "CompletionDateTime": 1593469846.486
            },
            "Statistics": {
                "EngineExecutionTimeInMillis": 3600,
                "DataScannedInBytes": 203089,
                "TotalExecutionTimeInMillis": 3821,
                "QueryQueueTimeInMillis": 267,
                "QueryPlanningTimeInMillis": 1175
            },
            "WorkGroup": "AthenaAdmin"
        }
    ],
    "UnprocessedQueryExecutionIds": []
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetQueryExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/batch-get-query-execution.html)」を参照してください。

### `create-data-catalog`
<a name="athena_CreateDataCatalog_cli_2_topic"></a>

次の例では、`create-data-catalog` を使用する方法を説明しています。

**AWS CLI**  
**データカタログを作成する方法**  
次の `create-data-catalog` の例では、`dynamo_db_catalog` データカタログを削除します。  

```
aws athena create-data-catalog \
    --name dynamo_db_catalog \
    --type LAMBDA \
    --description "DynamoDB Catalog" \
    --parameters function=arn:aws:lambda:us-west-2:111122223333:function:dynamo_db_lambda
```
このコマンドでは何も出力されません。結果を表示するには、`aws athena get-data-catalog --name dynamo_db_catalog` を使用します。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[カタログの登録: create-data-catalog](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-registering-a-catalog)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDataCatalog](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/create-data-catalog.html)」を参照してください。

### `create-named-query`
<a name="athena_CreateNamedQuery_cli_2_topic"></a>

次の例では、`create-named-query` を使用する方法を説明しています。

**AWS CLI**  
**名前付きクエリを作成する方法**  
次の `create-named-query` の例では、2016 年 1 月にシアトルからニューヨークへのフライトについて、出発と到着の両方が 10 分以上遅れている `flights_parquet` のテーブルにクエリを実行する `AthenaAdmin` のワークグループに保存されたクエリを作成します。テーブル内の空港コード値は二重引用符 (例:「SEA」) を含む文字列であるため、バックスラッシュでエスケープされ、一重引用符で囲まれます。  

```
aws athena create-named-query \
    --name "SEA to JFK delayed flights Jan 2016" \
    --description "Both arrival and departure delayed more than 10 minutes." \
    --database sampledb \
    --query-string "SELECT flightdate, carrier, flightnum, origin, dest, depdelayminutes, arrdelayminutes FROM sampledb.flights_parquet WHERE yr = 2016 AND month = 1 AND origin = '\"SEA\"' AND dest = '\"JFK\"' AND depdelayminutes > 10 AND arrdelayminutes > 10" \
    --work-group AthenaAdmin
```
出力:  

```
{
    "NamedQueryId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドレットリファレンス*」の「[CreateNamedQuery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/create-named-query.html)」を参照してください。

### `create-work-group`
<a name="athena_CreateWorkGroup_cli_2_topic"></a>

次の例では、`create-work-group` を使用する方法を説明しています。

**AWS CLI**  
**ワークグループを作成する方法**  
次の `create-work-group` の例では、クエリ結果の出力場所「`s3://amzn-s3-demo-bucket`」を持つ「`Data_Analyst_Group`」というワークグループを作成します。コマンドは、クエリ結果の出力場所を含むクライアント構成を上書きするワークグループを作成します。また、このコマンドは CloudWatch メトリクスを有効にし、ワークグループに 3 つのキーと値のタグペアを追加して、他のワークグループと区別します。`--configuration` 引数には、オプションを区切るカンマの前にスペースがないことに注意してください。  

```
aws athena create-work-group \
    --name Data_Analyst_Group \
    --configuration ResultConfiguration={OutputLocation="s3://amzn-s3-demo-bucket"},EnforceWorkGroupConfiguration="true",PublishCloudWatchMetricsEnabled="true" \
    --description "Workgroup for data analysts" \
    --tags Key=Division,Value=West Key=Location,Value=Seattle Key=Team,Value="Big Data"
```
このコマンドでは何も出力されません。結果を表示するには、`aws athena get-work-group --work-group Data_Analyst_Group` を使用します。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[ワークグループの管理](https://docs.aws.amazon.com/athena/latest/ug/workgroups-create-update-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWorkGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/create-work-group.html)」を参照してください。

### `delete-data-catalog`
<a name="athena_DeleteDataCatalog_cli_2_topic"></a>

次の例では、`delete-data-catalog` を使用する方法を説明しています。

**AWS CLI**  
**データカタログを削除する方法**  
次の `delete-data-catalog` の例では、`UnusedDataCatalog` データカタログを削除します。  

```
aws athena delete-data-catalog \
    --name UnusedDataCatalog
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[カタログの削除: delete-data-catalog](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-deleting-a-catalog)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDataCatalog](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/delete-data-catalog.html)」を参照してください。

### `delete-named-query`
<a name="athena_DeleteNamedQuery_cli_2_topic"></a>

次の例では、`delete-named-query` を使用する方法を説明しています。

**AWS CLI**  
**名前付きクエリを削除する方法**  
次の `delete-named-query` の例では、指定された ID を持つ名前付きクエリを削除します。  

```
aws athena delete-named-query \
    --named-query-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNamedQuery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/delete-named-query.html)」を参照してください。

### `delete-work-group`
<a name="athena_DeleteWorkGroup_cli_2_topic"></a>

次の例では、`delete-work-group` を使用する方法を説明しています。

**AWS CLI**  
**ワークグループを削除する方法**  
次の `delete-work-group` の例では、`TeamB` のワークグループを削除します。  

```
aws athena delete-work-group \
    --work-group TeamB
```
このコマンドでは何も出力されません。削除を確認するには、`aws athena list-work-groups` を使用します。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[ワークグループの管理](https://docs.aws.amazon.com/athena/latest/ug/workgroups-create-update-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWorkGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/delete-work-group.html)」を参照してください。

### `get-data-catalog`
<a name="athena_GetDataCatalog_cli_2_topic"></a>

次の例では、`get-data-catalog` を使用する方法を説明しています。

**AWS CLI**  
**データカタログに関する情報を返す方法**  
次の `get-data-catalog` の例では、`dynamo_db_catalog` データカタログのデータベースに関する情報を返します。  

```
aws athena get-data-catalog \
    --name dynamo_db_catalog
```
出力:  

```
{
    "DataCatalog": {
        "Name": "dynamo_db_catalog",
        "Description": "DynamoDB Catalog",
        "Type": "LAMBDA",
        "Parameters": {
            "catalog": "dynamo_db_catalog",
            "metadata-function": "arn:aws:lambda:us-west-2:111122223333:function:dynamo_db_lambda",
            "record-function": "arn:aws:lambda:us-west-2:111122223333:function:dynamo_db_lambda"
        }
    }
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[カタログの詳細を表示: get-data-catalog](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-showing-details-of-a-catalog)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDataCatalog](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/get-data-catalog.html)」を参照してください。

### `get-database`
<a name="athena_GetDatabase_cli_2_topic"></a>

次の例では、`get-database` を使用する方法を説明しています。

**AWS CLI**  
**データカタログ内のデータベースに関する情報を返す方法**  
次の `get-database` の例では、`AwsDataCatalog` データカタログの `sampledb` データベースに関する情報を返します。  

```
aws athena get-database \
    --catalog-name AwsDataCatalog \
    --database-name sampledb
```
出力:  

```
{
    "Database": {
        "Name": "sampledb",
        "Description": "Sample database",
        "Parameters": {
            "CreatedBy": "Athena",
            "EXTERNAL": "TRUE"
        }
    }
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[データベースの詳細を表示: get-database](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-showing-details-of-a-database)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/get-database.html)」を参照してください。

### `get-named-query`
<a name="athena_GetNamedQuery_cli_2_topic"></a>

次の例では、`get-named-query` を使用する方法を説明しています。

**AWS CLI**  
**名前付きクエリを返す方法**  
次の `get-named-query` 例では、指定された ID を持つクエリに関する情報を返します。  

```
aws athena get-named-query \
    --named-query-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "NamedQuery": {
        "Name": "CloudFront Logs - SFO",
        "Description": "Shows successful GET request data for SFO",
        "Database": "default",
        "QueryString": "select date, location, browser, uri, status from cloudfront_logs where method = 'GET' and status = 200 and location like 'SFO%' limit 10",
        "NamedQueryId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "WorkGroup": "AthenaAdmin"
    }
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetNamedQuery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/get-named-query.html)」を参照してください。

### `get-query-execution`
<a name="athena_GetQueryExecution_cli_2_topic"></a>

次の例では、`get-query-execution` を使用する方法を説明しています。

**AWS CLI**  
**クエリ実行に関する情報を返す方法**  
次の `get-query-execution` の例では、指定されたクエリ ID が持つクエリに関する情報を返します。  

```
aws athena get-query-execution \
    --query-execution-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "QueryExecution": {
        "QueryExecutionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Query": "select date, location, browser, uri, status from cloudfront_logs where method = 'GET
' and status = 200 and location like 'SFO%' limit 10",
        "StatementType": "DML",
        "ResultConfiguration": {
            "OutputLocation": "s3://amzn-s3-demo-bucket/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111.csv"
        },
        "QueryExecutionContext": {
            "Database": "mydatabase",
            "Catalog": "awsdatacatalog"
        },
        "Status": {
            "State": "SUCCEEDED",
            "SubmissionDateTime": 1593469842.665,
            "CompletionDateTime": 1593469846.486
        },
        "Statistics": {
            "EngineExecutionTimeInMillis": 3600,
            "DataScannedInBytes": 203089,
            "TotalExecutionTimeInMillis": 3821,
            "QueryQueueTimeInMillis": 267,
            "QueryPlanningTimeInMillis": 1175
        },
        "WorkGroup": "AthenaAdmin"
    }
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetQueryExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/get-query-execution.html)」を参照してください。

### `get-query-results`
<a name="athena_GetQueryResults_cli_2_topic"></a>

次の例では、`get-query-results` を使用する方法を説明しています。

**AWS CLI**  
**クエリの結果を返す方法**  
次の `get-query-results` の例では、指定されたクエリ ID が持つクエリに関する結果を返します。  

```
aws athena get-query-results \
    --query-execution-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "ResultSet": {
        "Rows": [
            {
                "Data": [
                    {
                        "VarCharValue": "date"
                    },
                    {
                        "VarCharValue": "location"
                    },
                    {
                        "VarCharValue": "browser"
                    },
                    {
                        "VarCharValue": "uri"
                    },
                    {
                        "VarCharValue": "status"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Safari"
                    },
                    {
                        "VarCharValue": "/test-image-2.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Opera"
                    },
                    {
                        "VarCharValue": "/test-image-2.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Firefox"
                    },
                    {
                        "VarCharValue": "/test-image-3.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Lynx"
                    },
                    {
                        "VarCharValue": "/test-image-3.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "IE"
                    },
                    {
                        "VarCharValue": "/test-image-2.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Opera"
                    },
                    {
                        "VarCharValue": "/test-image-1.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Chrome"
                    },
                    {
                        "VarCharValue": "/test-image-3.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Firefox"
                    },
                    {
                        "VarCharValue": "/test-image-2.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "Chrome"
                    },
                    {
                        "VarCharValue": "/test-image-3.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            },
            {
                "Data": [
                    {
                        "VarCharValue": "2014-07-05"
                    },
                    {
                        "VarCharValue": "SFO4"
                    },
                    {
                        "VarCharValue": "IE"
                    },
                    {
                        "VarCharValue": "/test-image-2.jpeg"
                    },
                    {
                        "VarCharValue": "200"
                    }
                ]
            }
        ],
        "ResultSetMetadata": {
            "ColumnInfo": [
                {
                    "CatalogName": "hive",
                    "SchemaName": "",
                    "TableName": "",
                    "Name": "date",
                    "Label": "date",
                    "Type": "date",
                    "Precision": 0,
                    "Scale": 0,
                    "Nullable": "UNKNOWN",
                    "CaseSensitive": false
                },
                {
                    "CatalogName": "hive",
                    "SchemaName": "",
                    "TableName": "",
                    "Name": "location",
                    "Label": "location",
                    "Type": "varchar",
                    "Precision": 2147483647,
                "Data": [

                    "Scale": 0,
                    "Nullable": "UNKNOWN",
                    "CaseSensitive": true
                },
                {
                    "CatalogName": "hive",
                    "SchemaName": "",
                    "TableName": "",
                    "Name": "browser",
                    "Label": "browser",
                    "Type": "varchar",
                    "Precision": 2147483647,
                    "Scale": 0,
                    "Nullable": "UNKNOWN",
                    "CaseSensitive": true
                },
                {
                    "CatalogName": "hive",
                    "SchemaName": "",
                    "TableName": "",
                    "Name": "uri",
                    "Label": "uri",
                    "Type": "varchar",
                    "Precision": 2147483647,
                    "Scale": 0,
                    "Nullable": "UNKNOWN",
                    "CaseSensitive": true
                },
                {
                    "CatalogName": "hive",
                    "SchemaName": "",
                    "TableName": "",
                    "Name": "status",
                    "Label": "status",
                    "Type": "integer",
                    "Precision": 10,
                    "Scale": 0,
                    "Nullable": "UNKNOWN",
                    "CaseSensitive": false
                }
            ]
        }
    },
    "UpdateCount": 0
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[クエリ結果、出力ファイル、クエリ履歴の使用](https://docs.aws.amazon.com/athena/latest/ug/querying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetQueryResults](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/get-query-results.html)」を参照してください。

### `get-table-metadata`
<a name="athena_GetTableMetadata_cli_2_topic"></a>

次の例では、`get-table-metadata` を使用する方法を説明しています。

**AWS CLI**  
**テーブルのメタデータ情報を返す方法**  
次の `get-table-metadata` の例では、`AwsDataCatalog` データカタログの `sampledb` データベースから、列名とそのデータ型を含む `counties` テーブルに関するメタデータ情報を返します。  

```
aws athena get-table-metadata \
    --catalog-name AwsDataCatalog \
    --database-name sampledb \
    --table-name counties
```
出力:  

```
{
    "TableMetadata": {
        "Name": "counties",
        "CreateTime": 1593559968.0,
        "LastAccessTime": 0.0,
        "TableType": "EXTERNAL_TABLE",
        "Columns": [
            {
                "Name": "name",
                "Type": "string",
                "Comment": "from deserializer"
            },
            {
                "Name": "boundaryshape",
                "Type": "binary",
                "Comment": "from deserializer"
            },
            {
                "Name": "motto",
                "Type": "string",
                "Comment": "from deserializer"
            },
            {
                "Name": "population",
                "Type": "int",
                "Comment": "from deserializer"
            }
        ],
        "PartitionKeys": [],
        "Parameters": {
            "EXTERNAL": "TRUE",
            "inputformat": "com.esri.json.hadoop.EnclosedJsonInputFormat",
            "location": "s3://amzn-s3-demo-bucket/json",
            "outputformat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
            "serde.param.serialization.format": "1",
            "serde.serialization.lib": "com.esri.hadoop.hive.serde.JsonSerde",
            "transient_lastDdlTime": "1593559968"
        }
    }
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[テーブルの詳細を表示: get-table-metadata](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-showing-details-of-a-table)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTableMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/get-table-metadata.html)」を参照してください。

### `get-work-group`
<a name="athena_GetWorkGroup_cli_2_topic"></a>

次の例では、`get-work-group` を使用する方法を説明しています。

**AWS CLI**  
**ワークグループに関する情報を返す方法**  
次の `get-work-group` の例では、`AthenaAdmin` ワークグループに関する情報を返します。  

```
aws athena get-work-group \
    --work-group AthenaAdmin
```
出力:  

```
{
    "WorkGroup": {
        "Name": "AthenaAdmin",
        "State": "ENABLED",
        "Configuration": {
            "ResultConfiguration": {
                "OutputLocation": "s3://amzn-s3-demo-bucket/"
            },
            "EnforceWorkGroupConfiguration": false,
            "PublishCloudWatchMetricsEnabled": true,
            "RequesterPaysEnabled": false
        },
        "Description": "Workgroup for Athena administrators",
        "CreationTime": 1573677174.105
    }
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[ワークグループの管理](https://docs.aws.amazon.com/athena/latest/ug/workgroups-create-update-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWorkGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/get-work-group.html)」を参照してください。

### `list-data-catalogs`
<a name="athena_ListDataCatalogs_cli_2_topic"></a>

次の例では、`list-data-catalogs` を使用する方法を説明しています。

**AWS CLI**  
**Athena に登録されているデータカタログを一覧表示する方法**  
次の `list-data-catalogs` の例では、Athena に登録されているデータカタログを一覧表示します。  

```
aws athena list-data-catalogs
```
出力:  

```
{
    "DataCatalogsSummary": [
        {
            "CatalogName": "AwsDataCatalog",
            "Type": "GLUE"
        },
        {
            "CatalogName": "cw_logs_catalog",
            "Type": "LAMBDA"
        },
        {
            "CatalogName": "cw_metrics_catalog",
            "Type": "LAMBDA"
        }
    ]
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[カタログの登録を一覧表示: list-data-catalogs](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-listing-registered-catalogs)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDataCatalogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/list-data-catalogs.html)」を参照してください。

### `list-databases`
<a name="athena_ListDatabases_cli_2_topic"></a>

次の例では、`list-databases` を使用する方法を説明しています。

**AWS CLI**  
**データカタログ内のデータベースを一覧表示する方法**  
次の `list-databases` の例では、`AwsDataCatalog` データカタログのデータベースを一覧表示します。  

```
aws athena list-databases \
    --catalog-name AwsDataCatalog
```
出力:  

```
{
    "DatabaseList": [
        {
            "Name": "default"
        },
        {
            "Name": "mydatabase"
        },
        {
            "Name": "newdb"
        },
        {
            "Name": "sampledb",
            "Description": "Sample database",
            "Parameters": {
                "CreatedBy": "Athena",
                "EXTERNAL": "TRUE"
            }
        },
        {
            "Name": "webdata"
        }
    ]
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[カタログのデータベースを一覧表示: list-databases](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-listing-databases)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDatabases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/list-databases.html)」を参照してください。

### `list-named-queries`
<a name="athena_ListNamedQueries_cli_2_topic"></a>

次の例では、`list-named-queries` を使用する方法を説明しています。

**AWS CLI**  
**ワークグループの名前付きクエリを一覧表示する方法**  
次の `list-named-queries` 例では、`AthenaAdmin` ワークグループの名前付きクエリを一覧表示します。  

```
aws athena list-named-queries \
    --work-group AthenaAdmin
```
出力:  

```
{
    "NamedQueryIds": [
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333"
    ]
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListNamedQueries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/list-named-queries.html)」を参照してください。

### `list-query-executions`
<a name="athena_ListQueryExecutions_cli_2_topic"></a>

次の例では、`list-query-executions` を使用する方法を説明しています。

**AWS CLI**  
**指定されたワークグループ内のクエリのクエリ ID を一覧表示する方法**  
次の `list-query-executions` の例では、`AthenaAdmin` ワークグループ内のクエリ ID を最大 10 個まで一覧表示します。  

```
aws athena list-query-executions \
    --work-group AthenaAdmin \
    --max-items 10
```
出力:  

```
{
    "QueryExecutionIds": [
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11110",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11114",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11115",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11116",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11117",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11118",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11119"
    ],
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0="
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[クエリ結果、出力ファイル、クエリ履歴の使用](https://docs.aws.amazon.com/athena/latest/ug/querying.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListQueryExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/list-query-executions.html)」を参照してください。

### `list-table-metadata`
<a name="athena_ListTableMetadata_cli_2_topic"></a>

次の例では、`list-table-metadata` を使用する方法を説明しています。

**AWS CLI**  
**データカタログの指定されたデータベース内のテーブルのメタデータを一覧表示する方法**  
次の `list-table-metadata` の例では、`AwsDataCatalog` データカタログの `geography` データベース内の最大 2 つのテーブルのメタデータ情報を返します。  

```
aws athena list-table-metadata \
    --catalog-name AwsDataCatalog \
    --database-name geography \
    --max-items 2
```
出力:  

```
{
    "TableMetadataList": [
        {
            "Name": "country_codes",
            "CreateTime": 1586553454.0,
            "TableType": "EXTERNAL_TABLE",
            "Columns": [
                {
                    "Name": "country",
                    "Type": "string",
                    "Comment": "geo id"
                },
                {
                    "Name": "alpha-2 code",
                    "Type": "string",
                    "Comment": "geo id2"
                },
                {
                    "Name": "alpha-3 code",
                    "Type": "string",
                    "Comment": "state name"
                },
                {
                    "Name": "numeric code",
                    "Type": "bigint",
                    "Comment": ""
                },
                {
                    "Name": "latitude",
                    "Type": "bigint",
                    "Comment": "location (latitude)"
                },
                {
                    "Name": "longitude",
                    "Type": "bigint",
                    "Comment": "location (longitude)"
                }
            ],
            "Parameters": {
                "areColumnsQuoted": "false",
                "classification": "csv",
                "columnsOrdered": "true",
                "delimiter": ",",
                "has_encrypted_data": "false",
                "inputformat": "org.apache.hadoop.mapred.TextInputFormat",
                "location": "s3://amzn-s3-demo-bucket/csv/countrycode",
                "outputformat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
                "serde.param.field.delim": ",",
                "serde.serialization.lib": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
                "skip.header.line.count": "1",
                "typeOfData": "file"
            }
        },
        {
            "Name": "county_populations",
            "CreateTime": 1586553446.0,
            "TableType": "EXTERNAL_TABLE",
            "Columns": [
                {
                    "Name": "id",
                    "Type": "string",
                    "Comment": "geo id"
                },
                {
                    "Name": "country",

                    "Name": "id2",
                    "Type": "string",
                    "Comment": "geo id2"
                },
                {
                    "Name": "county",
                    "Type": "string",
                    "Comment": "county name"
                },
                {
                    "Name": "state",
                    "Type": "string",
                    "Comment": "state name"
                },
                {
                    "Name": "population estimate 2018",
                    "Type": "string",
                    "Comment": ""
                }
            ],
            "Parameters": {
                "areColumnsQuoted": "false",
                "classification": "csv",
                "columnsOrdered": "true",
                "delimiter": ",",
                "has_encrypted_data": "false",
                "inputformat": "org.apache.hadoop.mapred.TextInputFormat",
                "location": "s3://amzn-s3-demo-bucket/csv/CountyPopulation",
                "outputformat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
                "serde.param.field.delim": ",",
                "serde.serialization.lib": "org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe",
                "skip.header.line.count": "1",
                "typeOfData": "file"
            }
        }
    ],
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ=="
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[データベース内のすべてのテーブルのメタデータを表示: list-table-metadata](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-showing-all-table-metadata)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTableMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/list-table-metadata.html)」を参照してください。

### `list-tags-for-resource`
<a name="athena_ListTagsForResource_cli_2_topic"></a>

次の例では、`list-tags-for-resource` を使用する方法を説明しています。

**AWS CLI**  
**例 1: ワークグループのタグを一覧表示する方法**  
次の `list-tags-for-resource` の例では、`Data_Analyst_Group` ワークグループのタグを一覧表示します。  

```
aws athena list-tags-for-resource \
    --resource-arn arn:aws:athena:us-west-2:111122223333:workgroup/Data_Analyst_Group
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Division",
            "Value": "West"
        },
        {
            "Key": "Team",
            "Value": "Big Data"
        },
        {
            "Key": "Location",
            "Value": "Seattle"
        }
    ]
}
```
**例 2: データカタログのタグを一覧表示する方法**  
次の `list-tags-for-resource` の例では、`dynamo_db_catalog` データカタログのタグを一覧表示します。  

```
aws athena list-tags-for-resource \
    --resource-arn arn:aws:athena:us-west-2:111122223333:datacatalog/dynamo_db_catalog
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Division",
            "Value": "Mountain"
        },
        {
            "Key": "Organization",
            "Value": "Retail"
        },
        {
            "Key": "Product_Line",
            "Value": "Shoes"
        },
        {
            "Key": "Location",
            "Value": "Denver"
        }
    ]
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[リソースのタグを一覧表示: list-tags-for-resource](https://docs.aws.amazon.com/athena/latest/ug/tags-operations.html#tags-operations-examples-cli-list-tags-for-resource)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/list-tags-for-resource.html)」を参照してください。

### `list-work-groups`
<a name="athena_ListWorkGroups_cli_2_topic"></a>

次の例では、`list-work-groups` を使用する方法を説明しています。

**AWS CLI**  
**ワークグループを一覧表示**  
次の `list-work-groups` の例では、現在のアカウントのワークグループを一覧表示します。  

```
aws athena list-work-groups
```
出力:  

```
{
    "WorkGroups": [
        {
            "Name": "Data_Analyst_Group",
            "State": "ENABLED",
            "Description": "",
            "CreationTime": 1578006683.016
        },
        {
            "Name": "AthenaAdmin",
            "State": "ENABLED",
            "Description": "",
            "CreationTime": 1573677174.105
        },
        {
            "Name": "primary",
            "State": "ENABLED",
            "Description": "",
            "CreationTime": 1567465222.723
        }
    ]
}
```
詳細については、「*Amazon Athena ユーザーガイド*」の「[ワークグループの管理](https://docs.aws.amazon.com/athena/latest/ug/workgroups-create-update-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWorkGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/list-work-groups.html)」を参照してください。

### `start-query-execution`
<a name="athena_StartQueryExecution_cli_2_topic"></a>

次の例では、`start-query-execution` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 指定されたデータベースとデータカタログ内の指定されたテーブルでワークグループでクエリを実行する方法**  
次の `start-query-execution` の例では、`AthenaAdmin` ワークグループを使用して、`AwsDataCatalog`データカタログの `cflogsdatabase` の `cloudfront_logs` テーブルでクエリを実行します。  

```
aws athena start-query-execution \
    --query-string "select date, location, browser, uri, status from cloudfront_logs where method = 'GET' and status = 200 and location like 'SFO%' limit 10" \
    --work-group "AthenaAdmin" \
    --query-execution-context Database=cflogsdatabase,Catalog=AwsDataCatalog
```
出力:  

```
{
"QueryExecutionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
**例 2: 指定されたワークグループを使用して、指定されたデータカタログにデータベースを作成するクエリを実行する方法**  
次の `start-query-execution` の例では、`AthenaAdmin` ワークグループを使用して、デフォルトのデータカタログ `AwsDataCatalog` にデータベース `newdb` を作成します。  

```
aws athena start-query-execution \
    --query-string "create database if not exists newdb" \
    --work-group "AthenaAdmin"
```
出力:  

```
{
"QueryExecutionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11112"
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
**例 3: 指定されたデータベースとデータカタログのテーブルにビューを作成するクエリを実行する方法**  
次の `start-query-execution` の例では、`cflogsdatabase` の `cloudfront_logs` テーブルに `SELECT` ステートメントを使用してビュー `cf10` を作成します。  

```
aws athena start-query-execution \
    --query-string  "CREATE OR REPLACE VIEW cf10 AS SELECT * FROM cloudfront_logs limit 10" \
    --query-execution-context Database=cflogsdatabase
```
出力:  

```
{
"QueryExecutionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11113"
}
```
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartQueryExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/start-query-execution.html)」を参照してください。

### `stop-query-execution`
<a name="athena_StopQueryExecution_cli_2_topic"></a>

次の例では、`stop-query-execution` を使用する方法を説明しています。

**AWS CLI**  
**実行中のクエリを停止する方法**  
次の `stop-query-execution` の例では、指定されたクエリ ID を持つクエリを停止します。  

```
aws athena stop-query-execution \
    --query-execution-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、*Amazon Athena ユーザーガイド*の「[Amazon Athena を使用した SQL クエリの実行](https://docs.aws.amazon.com/athena/latest/ug/querying-athena-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopQueryExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/stop-query-execution.html)」を参照してください。

### `tag-resource`
<a name="athena_TagResource_cli_2_topic"></a>

次の例では、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースにタグを追加**  
次の `tag-resource` の例では、`dynamo_db_catalog` データカタログにタグを追加します。  

```
aws athena tag-resource \
    --resource-arn arn:aws:athena:us-west-2:111122223333:datacatalog/dynamo_db_catalog \
    --tags Key=Organization,Value=Retail Key=Division,Value=Mountain Key=Product_Line,Value=Shoes Key=Location,Value=Denver
```
このコマンドでは何も出力されません。結果を表示するには、`aws athena list-tags-for-resource --resource-arn arn:aws:athena:us-west-2:111122223333:datacatalog/dynamo_db_catalog` を使用します。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[リソースにタグを追加: tag-resource](https://docs.aws.amazon.com/athena/latest/ug/tags-operations.html#tags-operations-examples-cli-tag-resource)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="athena_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除する方法**  
次の `untag-resource` の例では、`dynamo_db_catalog` データカタログリソースから `Specialization` および `Focus` キーと、関連する値を削除します。  

```
aws athena untag-resource \
    --resource-arn arn:aws:athena:us-west-2:111122223333:datacatalog/dynamo_db_catalog \
    --tag-keys Specialization Focus
```
このコマンドでは何も出力されません。`list-tags-for-resource` コマンドを使用して結果を表示します。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[リソースからタグを削除: untag-resource](https://docs.aws.amazon.com/athena/latest/ug/tags-operations.html#tags-operations-examples-cli-untag-resource)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/untag-resource.html)」を参照してください。

### `update-data-catalog`
<a name="athena_UpdateDataCatalog_cli_2_topic"></a>

次の例では、`update-data-catalog` を使用する方法を説明しています。

**AWS CLI**  
**データカタログを更新する方法**  
次の `update-data-catalog` の例では、Lambda 関数と `cw_logs_catalog` データカタログの説明を更新します。  

```
aws athena update-data-catalog \
    --name cw_logs_catalog \
    --type LAMBDA \
    --description "New CloudWatch Logs Catalog" \
    --function=arn:aws:lambda:us-west-2:111122223333:function:new_cw_logs_lambda
```
このコマンドでは何も出力されません。結果を表示するには、`aws athena get-data-catalog --name cw_logs_catalog` を使用します。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[カタログを更新: update-data-catalog](https://docs.aws.amazon.com/athena/latest/ug/datastores-hive-cli.html#datastores-hive-cli-updating-a-catalog)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDataCatalog](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/update-data-catalog.html)」を参照してください。

### `update-work-group`
<a name="athena_UpdateWorkGroup_cli_2_topic"></a>

次の例では、`update-work-group` を使用する方法を説明しています。

**AWS CLI**  
**ワークグループを更新する方法**  
次の `update-work-group` 例では、`Data_Analyst_Group` ワークグループを無効にします。ユーザーは無効なワークグループでクエリを実行または作成できませんが、メトリクス、データ使用量制限コントロール、ワークグループ設定、クエリ履歴、保存されたクエリを表示することはできます。  

```
aws athena update-work-group \
    --work-group Data_Analyst_Group \
    --state DISABLED
```
このコマンドでは何も出力されません。状態の変化を確認するには、 `aws athena get-work-group --work-group Data_Analyst_Group` を使用して出力の `State` プロパティを確認します。  
詳細については、「*Amazon Athena ユーザーガイド*」の「[ワークグループの管理](https://docs.aws.amazon.com/athena/latest/ug/workgroups-create-update-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWorkGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/update-work-group.html)」を参照してください。

# を使用した Auto Scaling の例 AWS CLI
<a name="cli_2_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `attach-instances`
<a name="auto-scaling_AttachInstances_cli_2_topic"></a>

次のコード例では、`attach-instances` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループにインスタンスをアタッチする方法**  
この例では、指定されたインスタンスを、指定された Auto Scaling グループにアタッチします。  

```
aws autoscaling attach-instances \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/attach-instances.html)」を参照してください。

### `attach-load-balancer-target-groups`
<a name="auto-scaling_AttachLoadBalancerTargetGroups_cli_2_topic"></a>

次のコード例では、`attach-load-balancer-target-groups` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループを Auto Scaling グループにアタッチする方法**  
この例では、指定されたターゲットグループを、指定された Auto Scaling グループにアタッチします。  

```
aws autoscaling attach-load-balancer-target-groups \
    --auto-scaling-group-name my-asg \
    --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Elastic Load Balancing を使用して Auto Scaling グループ内のインスタンス全体にトラフィックを分散させる](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachLoadBalancerTargetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/attach-load-balancer-target-groups.html)」を参照してください。

### `attach-load-balancers`
<a name="auto-scaling_AttachLoadBalancers_cli_2_topic"></a>

次のコード例では、`attach-load-balancers` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループに Classic Load Balancer をアタッチする方法**  
この例では、指定された Classic Load Balancer を、指定された Auto Scaling グループにアタッチします。  

```
aws autoscaling attach-load-balancers \
    --load-balancer-names my-load-balancer \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Elastic Load Balancing を使用して Auto Scaling グループ内のインスタンス全体にトラフィックを分散させる](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/attach-load-balancers.html)」を参照してください。

### `cancel-instance-refresh`
<a name="auto-scaling_CancelInstanceRefresh_cli_2_topic"></a>

次のコード例では、`cancel-instance-refresh` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの更新をキャンセルする方法**  
次の `cancel-instance-refresh` 例のは、指定された Auto Scaling グループの進行中のインスタンスの更新をキャンセルします。  

```
aws autoscaling cancel-instance-refresh \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "InstanceRefreshId": "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b"
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の[インスタンスの更新のキャンセル](https://docs.aws.amazon.com/autoscaling/ec2/userguide/cancel-instance-refresh.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelInstanceRefresh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/cancel-instance-refresh.html)」を参照してください。

### `complete-lifecycle-action`
<a name="auto-scaling_CompleteLifecycleAction_cli_2_topic"></a>

次のコード例では、`complete-lifecycle-action` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルアクションを完了する方法**  
この例では、インスタンスの起動または終了を完了できるように、指定されたライフサイクルアクションが完了したことを Amazon EC2 Auto Scaling に通知します。  

```
aws autoscaling complete-lifecycle-action \
    --lifecycle-hook-name my-launch-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-action-result CONTINUE \
    --lifecycle-action-token bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling のライフサイクルフック](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CompleteLifecycleAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/complete-lifecycle-action.html)」を参照してください。

### `create-auto-scaling-group`
<a name="auto-scaling_CreateAutoScalingGroup_cli_2_topic"></a>

次のコード例では、`create-auto-scaling-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: Auto Scaling グループを作成する方法**  
次の `create-auto-scaling-group` の例では、リージョン内の複数のアベイラビリティーゾーンのサブネット内に Auto Scaling グループを作成します。インスタンスは、指定された起動テンプレートのデフォルトバージョンで起動されます。終了ポリシーやヘルスチェック構成など、他のほとんどの構成にはデフォルトが使用されることに注意してください。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12 \
    --min-size 1 \
    --max-size 5 \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)」を参照してください。  
**例 2: Application Load Balancer、Network Load Balancer、または Gateway Load Balancer をアタッチする方法**  
この例では、予想されるトラフィックをサポートするロードバランサーのターゲットグループの ARN を指定します。ヘルスチェックタイプは、Elastic Load Balancing がインスタンスを異常として報告したときに、Auto Scaling グループがそのインスタンスを置き換えるよう `ELB` を指定します。このコマンドは、ヘルスチェックの猶予期間 (`600` 秒) も定義します。猶予期間は、新しく起動したインスタンスが早期に終了するのを防ぐのに役立ちます。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12 \
    --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/943f017f100becff \
    --health-check-type ELB \
    --health-check-grace-period 600 \
    --min-size 1 \
    --max-size 5 \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Elastic Load Balancing を使用して Auto Scaling グループ内のインスタンス全体にトラフィックを分散させる](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)」を参照してください。**  
**例 3: プレイスメントグループを指定し、起動テンプレートの最新バージョンを使用する方法**  
この例では、単一のアベイラビリティーゾーン内のプレイスメントグループ内でインスタンスを起動します。これは、HPC ワークロードを使用する低レイテンシーのグループに役立ちます。この例では、グループの最小サイズ、最大サイズ、希望する容量も指定しています。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest' \
    --min-size 1 \
    --max-size 5 \
    --desired-capacity 3 \
    --placement-group my-placement-group \
    --vpc-zone-identifier "subnet-6194ea3b"
```
このコマンドでは何も出力されません。  
詳細については、「*Linux インスタンス用 Amazon EC2 ユーザーガイド*」の「[プレイスメントグループ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html)」を参照してください。  
**例 4: 単一のインスタンスの Auto Scaling グループを指定し、特定のバージョンの起動テンプレートを使用する方法**  
この例では、単一のインスタンスが強制的に実行されるように、最小容量と最大容量を `1` に設定した Auto Scaling グループを作成します。このコマンドは、既存の ENI の ID が指定されている起動テンプレートの v1 も指定します。eth0 の既存の ENI を指定する起動テンプレートを使用する際は、リクエストにサブネット ID を指定せずに、ネットワークインターフェイスと一致する Auto Scaling グループのアベイラビリティーゾーンを指定する必要があります。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg-single-instance \
    --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='1' \
    --min-size 1 \
    --max-size 1 \
    --availability-zones us-west-2a
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)」を参照してください。  
**例 5: 別の終了ポリシーを指定する方法**  
この例では、起動構成を使用して Auto Scaling グループを作成し、最も古いインスタンスを最初に終了するように終了ポリシーを構成します。またこのコマンドは、`Role` キーと `WebServer` 値を使用して、グループとインスタンスにタグを適用します。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-configuration-name my-lc \
    --min-size 1 \
    --max-size 5 \
    --termination-policies "OldestInstance" \
    --tags "ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Role,Value=WebServer,PropagateAtLaunch=true" \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling 終了ポリシーを使用する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-termination-policies.html)」を参照してください。**  
**例 6: 起動ライフサイクルフックを指定する方法**  
この例では、インスタンス起動時のカスタムアクションをサポートするライフサイクルフックで Auto Scaling グループを設定します。  

```
aws autoscaling create-auto-scaling-group \
    --cli-input-json file://~/config.json
```
`config.json` ファイルの内容。  

```
{
    "AutoScalingGroupName": "my-asg",
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-1234567890abcde12"
    },
    "LifecycleHookSpecificationList": [{
        "LifecycleHookName": "my-launch-hook",
        "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING",
        "NotificationTargetARN": "arn:aws:sqs:us-west-2:123456789012:my-sqs-queue",
        "RoleARN": "arn:aws:iam::123456789012:role/my-notification-role",
        "NotificationMetadata": "SQS message metadata",
        "HeartbeatTimeout": 4800,
        "DefaultResult": "ABANDON"
    }],
    "MinSize": 1,
    "MaxSize": 5,
    "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782",
    "Tags": [{
        "ResourceType": "auto-scaling-group",
        "ResourceId": "my-asg",
        "PropagateAtLaunch": true,
        "Value": "test",
        "Key": "environment"
    }]
}
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling のライフサイクルフック](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)」を参照してください。  
**例 7: 終了ライフサイクルフックを指定する方法**  
次の例では、インスタンス終了時のカスタムアクションをサポートするライフサイクルフックで Auto Scaling グループを設定します。  

```
aws autoscaling create-auto-scaling-group \
    --cli-input-json file://~/config.json
```
`config.json` の内容:  

```
{
    "AutoScalingGroupName": "my-asg",
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-1234567890abcde12"
    },
    "LifecycleHookSpecificationList": [{
        "LifecycleHookName": "my-termination-hook",
        "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING",
        "HeartbeatTimeout": 120,
        "DefaultResult": "CONTINUE"
    }],
    "MinSize": 1,
    "MaxSize": 5,
    "TargetGroupARNs": [
        "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"
    ],
    "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
}
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling のライフサイクルフック](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)」を参照してください。  
**例 8: カスタム終了ポリシーを指定する方法**  
この例では、スケールイン時にどのインスタンスを安全に終了できるかを Amazon EC2 Auto Scaling に指示するカスタム Lambda 関数終了ポリシーを指定する Auto Scaling グループを作成します。  

```
aws autoscaling create-auto-scaling-group \
    --auto-scaling-group-name my-asg-single-instance \
    --launch-template LaunchTemplateName=my-template-for-auto-scaling \
    --min-size 1 \
    --max-size 5 \
    --termination-policies "arn:aws:lambda:us-west-2:123456789012:function:HelloFunction:prod" \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Lambda を使用したカスタム終了ポリシーを作成する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lambda-custom-termination-policy.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス」の「[CreateAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/create-auto-scaling-group.html)」を参照してください。*

### `create-launch-configuration`
<a name="auto-scaling_CreateLaunchConfiguration_cli_2_topic"></a>

次のコード例では、`create-launch-configuration` を使用する方法を示しています。

**AWS CLI**  
**例 1: 起動構成を作成する方法**  
この例では、シンプルな起動構成を作成します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[起動構成の作成](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-config.html)」を参照してください。  
**例 2: セキュリティグループ、キーペア、ブートストラッピングスクリプトを使用して起動構成を作成する方法**  
この例では、セキュリティグループ、キーペア、ユーザーデータに含まれるブートストラッピングスクリプトを使用して起動構成を作成します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --security-groups sg-eb2af88example \
    --key-name my-key-pair \
    --user-data file://myuserdata.txt
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[起動構成の作成](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-config.html)」を参照してください。  
**例 3: IAM ロールを使用して起動構成を作成する方法**  
この例では、IAM ロールのインスタンスプロファイル名を使用して起動構成を作成します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --iam-instance-profile my-autoscaling-role
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 インスタンスで実行されるアプリケーションに対する IAM ロール](https://docs.aws.amazon.com/autoscaling/ec2/userguide/us-iam-role.html)」を参照してください。  
**例 4: 起動構成で詳細モニタリングを有効にする方法**  
この例では、EC2 詳細モニタリングを有効にして起動構成を作成し、EC2 メトリクスを 1 分間隔で CloudWatch に送信します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --instance-monitoring Enabled=true
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling インスタンスのモニタリング設定](https://docs.aws.amazon.com/autoscaling/ec2/userguide/enable-as-instance-metrics.html)」をご参照ください。  
**例 5: スポットインスタンスを起動する起動構成を作成する方法**  
この例では、スポットインスタンスを唯一の購入オプションとして使用する起動構成を作成します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --spot-price "0.50"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[スポットインスタンスのリクエスト](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-launch-spot-instances.html)」を参照してください。  
**例 6: EC2 インスタンスを使用した起動構成を作成する方法**  
この例では、既存のインスタンスの属性に基づいて起動構成を作成します。これにより、プレイスメントテナンシーと、`--placement-tenancy` オプションと `--no-associate-public-ip-address`オプションを含めることでパブリック IP アドレスが設定されるかどうかが上書きされます。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc-from-instance \
    --instance-id i-0123a456700123456 \
    --instance-type m5.large \
    --no-associate-public-ip-address \
    --placement-tenancy dedicated
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[EC2 インスタンスを使用して起動構成を作成する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-lc-with-instanceID.html)」を参照してください。  
**例 7: Amazon EBS ボリュームのブロックデバイスマッピングを使用して起動構成を作成する方法**  
この例では、デバイス名「`/dev/sdh`」とボリュームサイズが 20 の Amazon EBS `gp3` ボリュームのブロックデバイスマッピングを使用して起動構成を作成します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --block-device-mappings '[{"DeviceName":"/dev/sdh","Ebs":{"VolumeSize":20,"VolumeType":"gp3"}}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling API リファレンス*」の「[EBS](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_Ebs.html)」を参照してください。  
JSON 形式のパラメータ値を引用するための構文については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の[「CLI AWS での文字列での引用符の使用](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html)」を参照してください。  
**例 8: インスタンスストアボリュームのブロックデバイスマッピングを使用して起動構成を作成する方法**  
この例では、デバイス名「`/dev/sdc`」のインスタンスストアボリュームとして `ephemeral1` で起動構成を作成します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --block-device-mappings '[{"DeviceName":"/dev/sdc","VirtualName":"ephemeral1"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling API リファレンス*」の「[BlockDeviceMapping](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_BlockDeviceMapping.html)」を参照してください。  
JSON 形式のパラメータ値を引用するための構文については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の[「CLI AWS での文字列での引用符の使用](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html)」を参照してください。  
**例 9: 起動構成を作成し、起動時にブロックデバイスがアタッチされないようにする方法**  
この例では、AMI のブロックデバイスマッピング（`/dev/sdf` など）で指定されたブロックデバイスを抑制する起動構成を作成します。  

```
aws autoscaling create-launch-configuration \
    --launch-configuration-name my-lc \
    --image-id ami-04d5cc9b88example \
    --instance-type m5.large \
    --block-device-mappings '[{"DeviceName":"/dev/sdf","NoDevice":""}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling API リファレンス*」の「[BlockDeviceMapping](https://docs.aws.amazon.com/autoscaling/ec2/APIReference/API_BlockDeviceMapping.html)」を参照してください。  
JSON 形式のパラメータ値を引用するための構文については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の[「CLI AWS での文字列での引用符の使用](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-quoting-strings.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateLaunchConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/create-launch-configuration.html)」を参照してください。

### `create-or-update-tags`
<a name="auto-scaling_CreateOrUpdateTags_cli_2_topic"></a>

次のコード例では、`create-or-update-tags` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループのタグを作成または変更する方法**  
この例では、指定された Auto Scaling グループに 2 つのタグを追加します。  

```
aws autoscaling create-or-update-tags \
    --tags ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Role,Value=WebServer,PropagateAtLaunch=true ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Dept,Value=Research,PropagateAtLaunch=true
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスのタグ付け](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateOrUpdateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/create-or-update-tags.html)」を参照してください。

### `delete-auto-scaling-group`
<a name="auto-scaling_DeleteAutoScalingGroup_cli_2_topic"></a>

次のコード例では、`delete-auto-scaling-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定された Auto Scaling グループを削除する方法**  
この例では、指定された Auto Scaling グループを削除します。  

```
aws autoscaling delete-auto-scaling-group \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling インフラストラクチャを削除する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-process-shutdown.html)」を参照してください。  
**例 2: 指定された Auto Scaling グループを強制的に削除する方法**  
グループ内のインスタンスが終了するのを待たずに Auto Scaling グループを削除するには、`--force-delete` オプションを使用します。  

```
aws autoscaling delete-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --force-delete
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling インフラストラクチャを削除する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-process-shutdown.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-auto-scaling-group.html)」を参照してください。

### `delete-launch-configuration`
<a name="auto-scaling_DeleteLaunchConfiguration_cli_2_topic"></a>

次のコード例では、`delete-launch-configuration` を使用する方法を示しています。

**AWS CLI**  
**起動構成を削除する方法**  
この例では、指定された起動構成を削除します。  

```
aws autoscaling delete-launch-configuration \
    --launch-configuration-name my-launch-config
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling インフラストラクチャを削除する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-process-shutdown.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLaunchConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-launch-configuration.html)」を参照してください。

### `delete-lifecycle-hook`
<a name="auto-scaling_DeleteLifecycleHook_cli_2_topic"></a>

次のコード例では、`delete-lifecycle-hook` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルフックを削除する方法**  
指定されたライフサイクルフックを削除します。  

```
aws autoscaling delete-lifecycle-hook \
    --lifecycle-hook-name my-lifecycle-hook \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLifecycleHook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-lifecycle-hook.html)」を参照してください。

### `delete-notification-configuration`
<a name="auto-scaling_DeleteNotificationConfiguration_cli_2_topic"></a>

次のコード例では、`delete-notification-configuration` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling 通知を削除する方法**  
この例では、指定された Auto Scaling グループから指定された通知を削除します。  

```
aws autoscaling delete-notification-configuration \
    --auto-scaling-group-name my-asg \
    --topic-arn arn:aws:sns:us-west-2:123456789012:my-sns-topic
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[通知設定を削除する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html#delete-settingupnotifications)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNotificationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-notification-configuration.html)」を参照してください。

### `delete-policy`
<a name="auto-scaling_DeletePolicy_cli_2_topic"></a>

次のコード例では、`delete-policy` を使用する方法を示しています。

**AWS CLI**  
**スケーリングポリシーを削除する方法**  
この例では、指定されたスケーリングポリシーを削除します。  

```
aws autoscaling delete-policy \
    --auto-scaling-group-name my-asg \
    --policy-name alb1000-target-tracking-scaling-policy
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-policy.html)」を参照してください。

### `delete-scheduled-action`
<a name="auto-scaling_DeleteScheduledAction_cli_2_topic"></a>

次のコード例では、`delete-scheduled-action` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループ用のスケジュール済みのアクションを削除する方法**  
この例では、指定された Auto Scaling グループから指定されたスケジュール済みの通知を削除します。  

```
aws autoscaling delete-scheduled-action \
    --auto-scaling-group-name my-asg \
    --scheduled-action-name my-scheduled-action
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteScheduledAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-scheduled-action.html)」を参照してください。

### `delete-tags`
<a name="auto-scaling_DeleteTags_cli_2_topic"></a>

次のコード例では、`delete-tags` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループからタグを削除する方法**  
この例では、指定された Auto Scaling グループから指定されたタグを削除します。  

```
aws autoscaling delete-tags \
    --tags ResourceId=my-asg,ResourceType=auto-scaling-group,Key=Dept,Value=Research
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスのタグ付け](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-tags.html)」を参照してください。

### `delete-warm-pool`
<a name="auto-scaling_DeleteWarmPool_cli_2_topic"></a>

次のコード例では、`delete-warm-pool` を使用する方法を示しています。

**AWS CLI**  
**例 1: ウォームプールを削除する方法**  
次の例では、指定された Auto Scaling グループのウォームプールを削除します。  

```
aws autoscaling delete-warm-pool \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Warm pools for Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html)」を参照してください。  
**例 2: ウォームプールを強制的に削除する方法**  
インスタンスが終了するのを待たずにウォームプールを削除するには、`--force-delete` オプションを使用します。  

```
aws autoscaling delete-warm-pool \
    --auto-scaling-group-name my-asg \
    --force-delete
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Warm pools for Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWarmPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/delete-warm-pool.html)」を参照してください。

### `describe-account-limits`
<a name="auto-scaling_DescribeAccountLimits_cli_2_topic"></a>

次のコード例では、`describe-account-limits` を使用する方法を示しています。

**AWS CLI**  
**Amazon EC2 Auto Scaling アカウントの制限を記述する方法**  
この例では、 AWS アカウントの Amazon EC2 Auto Scaling の制限について説明します。  

```
aws autoscaling describe-account-limits
```
出力:  

```
{
    "NumberOfLaunchConfigurations": 5,
    "MaxNumberOfLaunchConfigurations": 100,
    "NumberOfAutoScalingGroups": 3,
    "MaxNumberOfAutoScalingGroups": 20
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Amazon EC2 Auto Scaling Service Quotas](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-account-limits.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-account-limits.html)」を参照してください。

### `describe-adjustment-types`
<a name="auto-scaling_DescribeAdjustmentTypes_cli_2_topic"></a>

次のコード例では、`describe-adjustment-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能なスケーリング調整タイプを記述する方法**  
この例では、使用可能な調整タイプについて記述します。  

```
aws autoscaling describe-adjustment-types
```
出力:  

```
{
    "AdjustmentTypes": [
        {
            "AdjustmentType": "ChangeInCapacity"
        },
        {
            "AdjustmentType": "ExactCapacity"
        },
        {
            "AdjustmentType": "PercentChangeInCapacity"
        }
    ]
}
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[スケーリング調整タイプ](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html#as-scaling-adjustment)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAdjustmentTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-adjustment-types.html)」を参照してください。

### `describe-auto-scaling-groups`
<a name="auto-scaling_DescribeAutoScalingGroups_cli_2_topic"></a>

次のコード例では、`describe-auto-scaling-groups` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定された Auto Scaling グループを記述する方法**  
この例では、指定された Auto Scaling グループを記述します。  

```
aws autoscaling describe-auto-scaling-groups \
    --auto-scaling-group-names my-asg
```
出力:  

```
{
    "AutoScalingGroups": [
        {
            "AutoScalingGroupName": "my-asg",
            "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480f03:autoScalingGroupName/my-asg",
            "LaunchTemplate": {
                "LaunchTemplateName": "my-launch-template",
                "Version": "1",
                "LaunchTemplateId": "lt-1234567890abcde12"
            },
            "MinSize": 0,
            "MaxSize": 1,
            "DesiredCapacity": 1,
            "DefaultCooldown": 300,
            "AvailabilityZones": [
                "us-west-2a",
                "us-west-2b",
                "us-west-2c"
            ],
            "LoadBalancerNames": [],
            "TargetGroupARNs": [],
            "HealthCheckType": "EC2",
            "HealthCheckGracePeriod": 0,
            "Instances": [
                {
                    "InstanceId": "i-06905f55584de02da",
                    "InstanceType": "t2.micro",
                    "AvailabilityZone": "us-west-2a",
                    "HealthStatus": "Healthy",
                    "LifecycleState": "InService",
                    "ProtectedFromScaleIn": false,
                    "LaunchTemplate": {
                        "LaunchTemplateName": "my-launch-template",
                        "Version": "1",
                        "LaunchTemplateId": "lt-1234567890abcde12"
                    }
                }
            ],
            "CreatedTime": "2023-10-28T02:39:22.152Z",
            "SuspendedProcesses": [],
            "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782",
            "EnabledMetrics": [],
            "Tags": [],
            "TerminationPolicies": [
                "Default"
            ],
            "NewInstancesProtectedFromScaleIn": false,
            "ServiceLinkedRoleARN":"arn",
            "TrafficSources": []
        }
    ]
}
```
**例 2: 指定された最初の 100 個の Auto Scaling グループを記述する方法**  
この例では、指定された複数の Auto Scaling グループを記述します。最大 100 個のグループ名を指定できます。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 100 \
    --auto-scaling-group-names "group1" "group2" "group3" "group4"
```
出力例については、例 1 を参照してください。  
**例 3: 指定されたリージョンの Auto Scaling グループを記述する方法**  
この例では、指定されたリージョンの Auto Scaling グループを最大 75 グループまで記述します。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 75 \
    --region us-east-1
```
出力例については、例 1 を参照してください。  
**例 4: 指定された数の Auto Scaling グループを記述する方法**  
特定の数の Auto Scaling グループを返すには、`--max-items` オプションを使用します。  

```
aws autoscaling describe-auto-scaling-groups \
    --max-items 1
```
出力例については、例 1 を参照してください。  
出力に `NextToken` フィールドが含まれている場合は、さらに多くのグループがあることを示しています。追加のグループを取得するには、次のように、以降の呼び出しで `--starting-token` オプションを使用してこのフィールドの値を使用します。  

```
aws autoscaling describe-auto-scaling-groups \
    --starting-token Z3M3LMPEXAMPLE
```
出力例については、例 1 を参照してください。  
**例 5: 起動構成を使用している Auto Scaling グループを記述する方法**  
この例では、 `--query` オプションを使用して、起動構成を使用する Auto Scaling グループを記述します。  

```
aws autoscaling describe-auto-scaling-groups \
    --query 'AutoScalingGroups[?LaunchConfigurationName!=`null`]'
```
出力:  

```
[
    {
        "AutoScalingGroupName": "my-asg",
        "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480f03:autoScalingGroupName/my-asg",
        "LaunchConfigurationName": "my-lc",
        "MinSize": 0,
        "MaxSize": 1,
        "DesiredCapacity": 1,
        "DefaultCooldown": 300,
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2b",
            "us-west-2c"
        ],
        "LoadBalancerNames": [],
        "TargetGroupARNs": [],
        "HealthCheckType": "EC2",
        "HealthCheckGracePeriod": 0,
        "Instances": [
            {
                "InstanceId": "i-088c57934a6449037",
                "InstanceType": "t2.micro",
                "AvailabilityZone": "us-west-2c",
                "HealthStatus": "Healthy",
                "LifecycleState": "InService",
                "LaunchConfigurationName": "my-lc",
                "ProtectedFromScaleIn": false
            }
        ],
        "CreatedTime": "2023-10-28T02:39:22.152Z",
        "SuspendedProcesses": [],
        "VPCZoneIdentifier": "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782",
        "EnabledMetrics": [],
        "Tags": [],
        "TerminationPolicies": [
            "Default"
        ],
        "NewInstancesProtectedFromScaleIn": false,
        "ServiceLinkedRoleARN":"arn",
        "TrafficSources": []
    }
]
```
詳細については、*AWS 「 コマンドラインインターフェイスユーザーガイド」の*[「フィルタ AWS CLI 出力](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeAutoScalingGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-groups.html)」を参照してください。**

### `describe-auto-scaling-instances`
<a name="auto-scaling_DescribeAutoScalingInstances_cli_2_topic"></a>

次のコード例では、`describe-auto-scaling-instances` を使用する方法を示しています。

**AWS CLI**  
**例 1: 1 つまたは複数のインスタンスを記述する方法**  
この例では、指定されたインスタンスを記述します。  

```
aws autoscaling describe-auto-scaling-instances \
    --instance-ids i-06905f55584de02da
```
出力:  

```
{
    "AutoScalingInstances": [
        {
            "InstanceId": "i-06905f55584de02da",
            "InstanceType": "t2.micro",
            "AutoScalingGroupName": "my-asg",
            "AvailabilityZone": "us-west-2b",
            "LifecycleState": "InService",
            "HealthStatus": "HEALTHY",
            "ProtectedFromScaleIn": false,
            "LaunchTemplate": {
                "LaunchTemplateId": "lt-1234567890abcde12",
                "LaunchTemplateName": "my-launch-template",
                "Version": "1"
            }
        }
    ]
}
```
**例 2: 1 つまたは複数のインスタンスを記述する方法**  
この例では、`--max-items` オプションを使用して、この呼び出しで返されるインスタンスの数を指定します。  

```
aws autoscaling describe-auto-scaling-instances \
    --max-items 1
```
出力に `NextToken` フィールドが含まれている場合は、さらに多くのインスタンスがあることを示しています。追加のインスタンスを取得するには、次のように、以降の呼び出しで `--starting-token` オプションを使用してこのフィールドの値を使用します。  

```
aws autoscaling describe-auto-scaling-instances \
    --starting-token Z3M3LMPEXAMPLE
```
出力例については、例 1 を参照してください。  
**例 3: 起動構成を使用するインスタンスを記述する方法**  
この例では、 `--query` オプションを使用して、起動構成を使用するインスタンスを記述します。  

```
aws autoscaling describe-auto-scaling-instances \
    --query 'AutoScalingInstances[?LaunchConfigurationName!=`null`]'
```
出力:  

```
[
    {
        "InstanceId": "i-088c57934a6449037",
        "InstanceType": "t2.micro",
        "AutoScalingGroupName": "my-asg",
        "AvailabilityZone": "us-west-2c",
        "LifecycleState": "InService",
        "HealthStatus": "HEALTHY",
        "LaunchConfigurationName": "my-lc",
        "ProtectedFromScaleIn": false
    }
]
```
詳細については、*AWS 「 コマンドラインインターフェイスユーザーガイド」の*[「フィルタ AWS CLI 出力](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-filter.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeAutoScalingInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-instances.html)」を参照してください。**

### `describe-auto-scaling-notification-types`
<a name="auto-scaling_DescribeAutoScalingNotificationTypes_cli_2_topic"></a>

次のコード例では、`describe-auto-scaling-notification-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能な通知タイプを記述する方法**  
この例では、使用可能な通知タイプについて記述します。  

```
aws autoscaling describe-auto-scaling-notification-types
```
出力:  

```
{
    "AutoScalingNotificationTypes": [
        "autoscaling:EC2_INSTANCE_LAUNCH",
        "autoscaling:EC2_INSTANCE_LAUNCH_ERROR",
        "autoscaling:EC2_INSTANCE_TERMINATE",
        "autoscaling:EC2_INSTANCE_TERMINATE_ERROR",
        "autoscaling:TEST_NOTIFICATION"
    ]
}
```
詳細については、『*Amazon EC2 Auto Scaling ユーザーガイド*』の「[Auto Scaling グループのスケーリング時の Amazon SNS 通知の取得](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAutoScalingNotificationTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-auto-scaling-notification-types.html)」を参照してください。

### `describe-instance-refreshes`
<a name="auto-scaling_DescribeInstanceRefreshes_cli_2_topic"></a>

次のコード例では、`describe-instance-refreshes` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの更新を記述する方法**  
次の `describe-instance-refreshes` の例では、ステータスメッセージ (利用可能な場合) やステータス理由など、指定された Auto Scaling グループのすべてのインスタンス更新リクエストの記述を返します。  

```
aws autoscaling describe-instance-refreshes \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "InstanceRefreshes": [
        {
            "InstanceRefreshId": "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b",
            "AutoScalingGroupName": "my-asg",
            "Status": "InProgress",
            "StatusReason": "Waiting for instances to warm up before continuing. For example: 0e69cc3f05f825f4f is warming up.",
            "EndTime": "2023-03-23T16:42:55Z",
            "PercentageComplete": 0,
            "InstancesToUpdate": 0,
    "Preferences": {
                "MinHealthyPercentage": 100,
                "InstanceWarmup": 300,
                "CheckpointPercentages": [
                    50
                ],
                "CheckpointDelay": 3600,
                "SkipMatching": false,
                "AutoRollback": true,
                "ScaleInProtectedInstances": "Ignore",
                "StandbyInstances": "Ignore"
            }
        },
        {
            "InstanceRefreshId": "dd7728d0-5bc4-4575-96a3-1b2c52bf8bb1",
            "AutoScalingGroupName": "my-asg",
            "Status": "Successful",
            "EndTime": "2022-06-02T16:53:37Z",
            "PercentageComplete": 100,
            "InstancesToUpdate": 0,
    "Preferences": {
                "MinHealthyPercentage": 90,
                "InstanceWarmup": 300,
                "SkipMatching": true,
                "AutoRollback": true,
                "ScaleInProtectedInstances": "Ignore",
                "StandbyInstances": "Ignore"
            }
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[インスタンスの更新のステータスを確認](https://docs.aws.amazon.com/en_us/autoscaling/ec2/userguide/check-status-instance-refresh.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceRefreshes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-instance-refreshes.html)」を参照してください。

### `describe-launch-configurations`
<a name="auto-scaling_DescribeLaunchConfigurations_cli_2_topic"></a>

次のコード例では、`describe-launch-configurations` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定された起動構成を記述する方法**  
この例では、指定された起動構成について記述します。  

```
aws autoscaling describe-launch-configurations \
    --launch-configuration-names my-launch-config
```
出力:  

```
{
    "LaunchConfigurations": [
        {
            "LaunchConfigurationName": "my-launch-config",
            "LaunchConfigurationARN": "arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:98d3b196-4cf9-4e88-8ca1-8547c24ced8b:launchConfigurationName/my-launch-config",
            "ImageId": "ami-0528a5175983e7f28",
            "KeyName": "my-key-pair-uswest2",
            "SecurityGroups": [
                "sg-05eaec502fcdadc2e"
            ],
            "ClassicLinkVPCSecurityGroups": [],
            "UserData": "",
            "InstanceType": "t2.micro",
            "KernelId": "",
            "RamdiskId": "",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/xvda",
                    "Ebs": {
                        "SnapshotId": "snap-06c1606ba5ca274b1",
                        "VolumeSize": 8,
                        "VolumeType": "gp2",
                        "DeleteOnTermination": true,
                        "Encrypted": false
                    }
                }
            ],
            "InstanceMonitoring": {
                "Enabled": true
            },
            "CreatedTime": "2020-10-28T02:39:22.321Z",
            "EbsOptimized": false,
            "AssociatePublicIpAddress": true,
            "MetadataOptions": {
                "HttpTokens": "required",
                "HttpPutResponseHopLimit": 1,
                "HttpEndpoint": "disabled"
            }
        }
    ]
}
```
**例 2: 指定された数の起動構成を記述する方法**  
特定の数の起動構成を返すには、 `--max-items` オプションを使用します。  

```
aws autoscaling describe-launch-configurations \
    --max-items 1
```
出力に `NextToken` フィールドが含まれている場合、起動構成がさらに増えます。追加の起動構成を取得するには、次のように、以降の呼び出しで `--starting-token` オプションを使用してこのフィールドの値を使用します。  

```
aws autoscaling describe-launch-configurations \
    --starting-token Z3M3LMPEXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLaunchConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-launch-configurations.html)」を参照してください。

### `describe-lifecycle-hook-types`
<a name="auto-scaling_DescribeLifecycleHookTypes_cli_2_topic"></a>

次のコード例では、`describe-lifecycle-hook-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能なライフサイクルフックのタイプを記述します。**  
この例では、使用可能なライフサイクルフックのタイプを記述します。  

```
aws autoscaling describe-lifecycle-hook-types
```
出力:  

```
{
    "LifecycleHookTypes": [
        "autoscaling:EC2_INSTANCE_LAUNCHING",
        "autoscaling:EC2_INSTANCE_TERMINATING"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLifecycleHookTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-lifecycle-hook-types.html)」を参照してください。

### `describe-lifecycle-hooks`
<a name="auto-scaling_DescribeLifecycleHooks_cli_2_topic"></a>

次のコード例では、`describe-lifecycle-hooks` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルフックを記述する方法**  
指定された Auto Scaling グループのライフサイクルフックを記述します。  

```
aws autoscaling describe-lifecycle-hooks \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "LifecycleHooks": [
        {
            "GlobalTimeout": 3000,
            "HeartbeatTimeout": 30,
            "AutoScalingGroupName": "my-asg",
            "LifecycleHookName": "my-launch-hook",
            "DefaultResult": "ABANDON",
            "LifecycleTransition": "autoscaling:EC2_INSTANCE_LAUNCHING"
        },
        {
            "GlobalTimeout": 6000,
            "HeartbeatTimeout": 60,
            "AutoScalingGroupName": "my-asg",
            "LifecycleHookName": "my-termination-hook",
            "DefaultResult": "CONTINUE",
            "LifecycleTransition": "autoscaling:EC2_INSTANCE_TERMINATING"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLifecycleHooks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-lifecycle-hooks.html)」を参照してください。

### `describe-load-balancer-target-groups`
<a name="auto-scaling_DescribeLoadBalancerTargetGroups_cli_2_topic"></a>

次のコード例では、`describe-load-balancer-target-groups` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループのロードバランサーターゲットグループを記述する方法**  
この例では、指定された Auto Scaling グループにアタッチされたロードバランサーターゲットグループを記述します。  

```
aws autoscaling describe-load-balancer-target-groups \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "LoadBalancerTargetGroups": [
        {
            "LoadBalancerTargetGroupARN": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
            "State": "Added"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoadBalancerTargetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-load-balancer-target-groups.html)」を参照してください。

### `describe-load-balancers`
<a name="auto-scaling_DescribeLoadBalancers_cli_2_topic"></a>

次のコード例では、`describe-load-balancers` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループのClassic Load Balancerを記述する方法**  
指定された Auto Scaling グループの Classic Load Balancer を記述します。  

```
aws autoscaling describe-load-balancers \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "LoadBalancers": [
        {
            "State": "Added",
            "LoadBalancerName": "my-load-balancer"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-load-balancers.html)」を参照してください。

### `describe-metric-collection-types`
<a name="auto-scaling_DescribeMetricCollectionTypes_cli_2_topic"></a>

次のコード例では、`describe-metric-collection-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能なメトリクスコレクションタイプを記述する方法**  
この例では、使用可能なメトリクスコレクションタイプについて記述します。  

```
aws autoscaling describe-metric-collection-types
```
出力:  

```
{
    "Metrics": [
        {
            "Metric": "GroupMinSize"
        },
        {
            "Metric": "GroupMaxSize"
        },
        {
            "Metric": "GroupDesiredCapacity"
        },
        {
            "Metric": "GroupInServiceInstances"
        },
        {
            "Metric": "GroupInServiceCapacity"
        },
        {
            "Metric": "GroupPendingInstances"
        },
        {
            "Metric": "GroupPendingCapacity"
        },
        {
            "Metric": "GroupTerminatingInstances"
        },
        {
            "Metric": "GroupTerminatingCapacity"
        },
        {
            "Metric": "GroupStandbyInstances"
        },
        {
            "Metric": "GroupStandbyCapacity"
        },
        {
            "Metric": "GroupTotalInstances"
        },
        {
            "Metric": "GroupTotalCapacity"
        }
    ],
    "Granularities": [
        {
            "Granularity": "1Minute"
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling group metrics](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html#as-group-metrics)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMetricCollectionTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-metric-collection-types.html)」を参照してください。

### `describe-notification-configurations`
<a name="auto-scaling_DescribeNotificationConfigurations_cli_2_topic"></a>

次のコード例では、`describe-notification-configurations` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定されたグループの通知構成を記述する方法**  
この例では、指定された Auto Scaling グループの通知構成を記述します。  

```
aws autoscaling describe-notification-configurations \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "NotificationConfigurations": [
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic-2"
        },
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic"
        }
    ]
}
```
詳細については、『*Amazon EC2 Auto Scaling ユーザーガイド*』の「[Auto Scaling グループのスケーリング時の Amazon SNS 通知の取得](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html)」を参照してください。  
**例 1: 指定された数の通知構成を記述する方法**  
特定の数の通知構成を返すには、 `max-items` パラメータを使用します。  

```
aws autoscaling describe-notification-configurations \
    --auto-scaling-group-name my-auto-scaling-group \
    --max-items 1
```
出力:  

```
{
    "NotificationConfigurations": [
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic-2"
        },
        {
            "AutoScalingGroupName": "my-asg",
            "NotificationType": "autoscaling:TEST_NOTIFICATION",
            "TopicARN": "arn:aws:sns:us-west-2:123456789012:my-sns-topic"
        }
    ]
}
```
出力に `NextToken` フィールドが含まれている場合、通知構成がさらに増えます。追加の通知構成を取得するには、次のように、以降の呼び出しで `starting-token` オプションを使用してこのフィールドの値を使用します。  

```
aws autoscaling describe-notification-configurations \
    --auto-scaling-group-name my-asg \
    --starting-token Z3M3LMPEXAMPLE
```
詳細については、『*Amazon EC2 Auto Scaling ユーザーガイド*』の「[Auto Scaling グループのスケーリング時の Amazon SNS 通知の取得](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNotificationConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-notification-configurations.html)」を参照してください。

### `describe-policies`
<a name="auto-scaling_DescribePolicies_cli_2_topic"></a>

次のコード例では、`describe-policies` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定されたグループのスケーリングポリシーを記述する方法**  
この例では、指定された Auto Scaling グループのスケーリングポリシーを記述します。  

```
aws autoscaling describe-policies \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "ScalingPolicies": [
        {
            "AutoScalingGroupName": "my-asg",
            "PolicyName": "alb1000-target-tracking-scaling-policy",
            "PolicyARN": "arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:3065d9c8-9969-4bec-bb6a-3fbe5550fde6:autoScalingGroupName/my-asg:policyName/alb1000-target-tracking-scaling-policy",
            "PolicyType": "TargetTrackingScaling",
            "StepAdjustments": [],
            "Alarms": [
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmHigh-924887a9-12d7-4e01-8686-6f844d13a196",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmHigh-924887a9-12d7-4e01-8686-6f844d13a196"
                },
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmLow-f96f899d-b8e7-4d09-a010-c1aaa35da296",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmLow-f96f899d-b8e7-4d09-a010-c1aaa35da296"
                }
            ],
            "TargetTrackingConfiguration": {
                "PredefinedMetricSpecification": {
                    "PredefinedMetricType": "ALBRequestCountPerTarget",
                    "ResourceLabel": "app/my-alb/778d41231b141a0f/targetgroup/my-alb-target-group/943f017f100becff"
                },
                "TargetValue": 1000.0,
                "DisableScaleIn": false
            },
            "Enabled": true
        },
        {
            "AutoScalingGroupName": "my-asg",
            "PolicyName": "cpu40-target-tracking-scaling-policy",
            "PolicyARN": "arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:5fd26f71-39d4-4690-82a9-b8515c45cdde:autoScalingGroupName/my-asg:policyName/cpu40-target-tracking-scaling-policy",
            "PolicyType": "TargetTrackingScaling",
            "StepAdjustments": [],
            "Alarms": [
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmHigh-139f9789-37b9-42ad-bea5-b5b147d7f473",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmHigh-139f9789-37b9-42ad-bea5-b5b147d7f473"
                },
                {
                    "AlarmName": "TargetTracking-my-asg-AlarmLow-bd681c67-fc18-4c56-8468-fb8e413009c9",
                    "AlarmARN": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:TargetTracking-my-asg-AlarmLow-bd681c67-fc18-4c56-8468-fb8e413009c9"
                }
            ],
            "TargetTrackingConfiguration": {
                "PredefinedMetricSpecification": {
                    "PredefinedMetricType": "ASGAverageCPUUtilization"
                },
                "TargetValue": 40.0,
                "DisableScaleIn": false
            },
            "Enabled": true
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[ダイナミックスケーリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html)」を参照してください。  
**例 2: 指定された名前のスケーリングポリシーを記述する方法**  
特定のスケーリングポリシーを返すには、 `--policy-names` オプションを使用します。  

```
aws autoscaling describe-policies \
    --auto-scaling-group-name my-asg \
    --policy-names cpu40-target-tracking-scaling-policy
```
出力例については、例 1 を参照してください。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[ダイナミックスケーリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html)を参照してください。  
**例 3: スケーリングポリシーの数を記述する方法**  
特定の数のポリシーを返すには、`--max-items` オプションを使用します。  

```
aws autoscaling describe-policies \
    --auto-scaling-group-name my-asg \
    --max-items 1
```
出力例については、例 1 を参照してください。  
出力に `NextToken` フィールドが含まれている場合は、後続の呼び出しで `--starting-token` オプションを使用してこのフィールドの値を使用し、追加のポリシーを取得します。  

```
aws autoscaling describe-policies --auto-scaling-group-name my-asg --starting-token Z3M3LMPEXAMPLE
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[ダイナミックスケーリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scale-based-on-demand.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-policies.html)」を参照してください。

### `describe-scaling-activities`
<a name="auto-scaling_DescribeScalingActivities_cli_2_topic"></a>

次のコード例では、`describe-scaling-activities` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定されたグループのスケーリングアクティビティを記述する方法**  
この例では、指定された Auto Scaling グループのスケーリングアクティビティを記述します。  

```
aws autoscaling describe-scaling-activities \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "Activities": [
        {
            "ActivityId": "f9f2d65b-f1f2-43e7-b46d-d86756459699",
            "Description": "Launching a new EC2 instance: i-0d44425630326060f",
            "AutoScalingGroupName": "my-asg",
            "Cause": "At 2020-10-30T19:35:51Z a user request update of AutoScalingGroup constraints to min: 0, max: 16, desired: 16 changing the desired capacity from 0 to 16.  At 2020-10-30T19:36:07Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 16.",
            "StartTime": "2020-10-30T19:36:09.766Z",
            "EndTime": "2020-10-30T19:36:41Z",
            "StatusCode": "Successful",
            "Progress": 100,
            "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}"
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Verify a scaling activity for an Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-verify-scaling-activity.html)」を参照してください。  
**例 2: 削除されたグループのスケーリングアクティビティを記述する方法**  
Auto Scaling グループが削除された後にスケーリングアクティビティを説明するには、`--include-deleted-groups` オプションを追加します。  

```
aws autoscaling describe-scaling-activities \
    --auto-scaling-group-name my-asg \
    --include-deleted-groups
```
出力:  

```
{
    "Activities": [
        {
            "ActivityId": "e1f5de0e-f93e-1417-34ac-092a76fba220",
            "Description": "Launching a new EC2 instance.  Status Reason: Your Spot request price of 0.001 is lower than the minimum required Spot request fulfillment price of 0.0031. Launching EC2 instance failed.",
            "AutoScalingGroupName": "my-asg",
            "Cause": "At 2021-01-13T20:47:24Z a user request update of AutoScalingGroup constraints to min: 1, max: 5, desired: 3 changing the desired capacity from 0 to 3.  At 2021-01-13T20:47:27Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 3.",
            "StartTime": "2021-01-13T20:47:30.094Z",
            "EndTime": "2021-01-13T20:47:30Z",
            "StatusCode": "Failed",
            "StatusMessage": "Your Spot request price of 0.001 is lower than the minimum required Spot request fulfillment price of 0.0031. Launching EC2 instance failed.",
            "Progress": 100,
            "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}",
            "AutoScalingGroupState": "Deleted",
            "AutoScalingGroupARN": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:283179a2-f3ce-423d-93f6-66bb518232f7:autoScalingGroupName/my-asg"
        }
    ]
}
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling をトラブルシューティングする](https://docs.aws.amazon.com/autoscaling/ec2/userguide/CHAP_Troubleshooting.html)」を参照してください。**  
**例 3: 指定された数のスケーリングアクティビティを記述する方法**  
特定の数のアクティビティを返すには、`--max-items` オプションを使用します。  

```
aws autoscaling describe-scaling-activities \
    --max-items 1
```
出力:  

```
{
    "Activities": [
        {
            "ActivityId": "f9f2d65b-f1f2-43e7-b46d-d86756459699",
            "Description": "Launching a new EC2 instance: i-0d44425630326060f",
            "AutoScalingGroupName": "my-asg",
            "Cause": "At 2020-10-30T19:35:51Z a user request update of AutoScalingGroup constraints to min: 0, max: 16, desired: 16 changing the desired capacity from 0 to 16.  At 2020-10-30T19:36:07Z an instance was started in response to a difference between desired and actual capacity, increasing the capacity from 0 to 16.",
            "StartTime": "2020-10-30T19:36:09.766Z",
            "EndTime": "2020-10-30T19:36:41Z",
            "StatusCode": "Successful",
            "Progress": 100,
            "Details": "{\"Subnet ID\":\"subnet-5ea0c127\",\"Availability Zone\":\"us-west-2b\"}"
        }
    ]
}
```
出力に `NextToken` フィールドが含まれている場合は、さらに多くのアクティビティがあることを示しています。追加のアクティビティを取得するには、次のように、以降の呼び出しで `--starting-token` オプションを使用してこのフィールドの値を使用します。  

```
aws autoscaling describe-scaling-activities \
    --starting-token Z3M3LMPEXAMPLE
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Verify a scaling activity for an Auto Scaling group](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-verify-scaling-activity.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScalingActivities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-scaling-activities.html)」を参照してください。

### `describe-scaling-process-types`
<a name="auto-scaling_DescribeScalingProcessTypes_cli_2_topic"></a>

次のコード例では、`describe-scaling-process-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能なプロセスタイプを記述する方法**  
この例では、使用可能なプロセスタイプを記述します。  

```
aws autoscaling describe-scaling-process-types
```
出力:  

```
{
    "Processes": [
        {
            "ProcessName": "AZRebalance"
        },
        {
            "ProcessName": "AddToLoadBalancer"
        },
        {
            "ProcessName": "AlarmNotification"
        },
        {
            "ProcessName": "HealthCheck"
        },
        {
            "ProcessName": "InstanceRefresh"
        },
        {
            "ProcessName": "Launch"
        },
        {
            "ProcessName": "ReplaceUnhealthy"
        },
        {
            "ProcessName": "ScheduledActions"
        },
        {
            "ProcessName": "Terminate"
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[スケーリングプロセスの中断と再開](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScalingProcessTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-scaling-process-types.html)」を参照してください。

### `describe-scheduled-actions`
<a name="auto-scaling_DescribeScheduledActions_cli_2_topic"></a>

次のコード例では、`describe-scheduled-actions` を使用する方法を示しています。

**AWS CLI**  
**例 1: スケジュール済みのすべてのアクションを記述する方法**  
この例では、スケジュール済みのすべてのアクションを記述します。  

```
aws autoscaling describe-scheduled-actions
```
出力:  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Scheduled scaling (スケジュールされたスケーリング)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
**例 2: 指定されたグループのスケジュール済みのアクションを記述する方法**  
特定の Auto Scaling グループのスケジュール済みのアクションを説明するには、 `--auto-scaling-group-name` オプションを使用します。  

```
aws autoscaling describe-scheduled-actions \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Scheduled scaling (スケジュールされたスケーリング)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
**例 3: 指定されたスケジュール済みのアクションを記述する方法**  
特定のスケジュール済みのアクションを説明するには、`--scheduled-action-names` オプションを使用します。  

```
aws autoscaling describe-scheduled-actions \
    --scheduled-action-names my-recurring-action
```
出力:  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Scheduled scaling (スケジュールされたスケーリング)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
**例 4: 指定された開始時刻でスケジュール済みのアクションを記述する方法**  
特定の時間に開始されるスケジュール済みのアクションを説明するには、`--start-time` オプションを使用します。  

```
aws autoscaling describe-scheduled-actions \
    --start-time "2023-12-01T04:00:00Z"
```
出力:  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Scheduled scaling (スケジュールされたスケーリング)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
**例 5: 指定された時間に終了するスケジュール済みのアクションを記述する方法**  
特定の時間に終了するスケジュール済みのアクションを説明するには、`--end-time` オプションを使用します。  

```
aws autoscaling describe-scheduled-actions \
    --end-time "2023-12-01T04:00:00Z"
```
出力:  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Scheduled scaling (スケジュールされたスケーリング)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
**例 6: 指定された数のスケーリングアクティビティを記述する方法**  
特定の数のアクティビティを返すには、`--max-items` オプションを使用します。  

```
aws autoscaling describe-scheduled-actions \
    --auto-scaling-group-name my-asg \
    --max-items 1
```
出力:  

```
{
    "ScheduledUpdateGroupActions": [
        {
            "AutoScalingGroupName": "my-asg",
            "ScheduledActionName": "my-recurring-action",
            "Recurrence": "30 0 1 1,6,12 *",
            "ScheduledActionARN": "arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8e86b655-b2e6-4410-8f29-b4f094d6871c:autoScalingGroupName/my-asg:scheduledActionName/my-recurring-action",
            "StartTime": "2023-12-01T04:00:00Z",
            "Time": "2023-12-01T04:00:00Z",
            "MinSize": 1,
            "MaxSize": 6,
            "DesiredCapacity": 4,
            "TimeZone": "America/New_York"
        }
    ]
}
```
出力に `NextToken` フィールドが含まれている場合は、さらに多くのスケジュール済みのアクションがあることを示しています。追加のスケジュール済みのアクションを取得するには、次のように、以降の呼び出しで `--starting-token` オプションを使用してこのフィールドの値を使用します。  

```
aws autoscaling describe-scheduled-actions \
    --auto-scaling-group-name my-asg \
    --starting-token Z3M3LMPEXAMPLE
```
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Scheduled scaling (スケジュールされたスケーリング)](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScheduledActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-scheduled-actions.html)」を参照してください。

### `describe-tags`
<a name="auto-scaling_DescribeTags_cli_2_topic"></a>

次のコード例では、`describe-tags` を使用する方法を示しています。

**AWS CLI**  
**すべてのタグを記述する方法**  
この例では、すべてのタグを記述します。  

```
aws autoscaling describe-tags
```
出力:  

```
{
    "Tags": [
        {
            "ResourceType": "auto-scaling-group",
            "ResourceId": "my-asg",
            "PropagateAtLaunch": true,
            "Value": "Research",
            "Key": "Dept"
        },
        {
            "ResourceType": "auto-scaling-group",
            "ResourceId": "my-asg",
            "PropagateAtLaunch": true,
            "Value": "WebServer",
            "Key": "Role"
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスのタグ付け](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)」を参照してください。  
**例 2: 指定されたグループのタグを記述する方法**  
特定の Auto Scaling グループのタグを説明するには、`--filters` オプションを使用します。  

```
aws autoscaling describe-tags --filters Name=auto-scaling-group,Values=my-asg
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスのタグ付け](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)」を参照してください。  
**例 3: 指定された数のタグを記述する方法**  
特定の数のタグを返すには、`--max-items` オプションを使用します。  

```
aws autoscaling describe-tags \
    --max-items 1
```
出力に `NextToken` フィールドが含まれている場合は、さらに多くのタグがあることを示しています。追加のタグを取得するには、次のように、以降の呼び出しで `--starting-token` オプションを使用してこのフィールドの値を使用します。  

```
aws autoscaling describe-tags \
    --filters Name=auto-scaling-group,Values=my-asg \
    --starting-token Z3M3LMPEXAMPLE
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスのタグ付け](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-tags.html)」を参照してください。

### `describe-termination-policy-types`
<a name="auto-scaling_DescribeTerminationPolicyTypes_cli_2_topic"></a>

次のコード例では、`describe-termination-policy-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能な終了ポリシータイプを記述する方法**  
この例では、使用可能な終了ポリシータイプを記述します。  

```
aws autoscaling describe-termination-policy-types
```
出力:  

```
{
    "TerminationPolicyTypes": [
        "AllocationStrategy",
        "ClosestToNextInstanceHour",
        "Default",
        "NewestInstance",
        "OldestInstance",
        "OldestLaunchConfiguration",
        "OldestLaunchTemplate"
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[スケールイン時にどの Auto Scaling インスタンスを終了するか設定する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-termination.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTerminationPolicyTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-termination-policy-types.html)」を参照してください。

### `describe-warm-pool`
<a name="auto-scaling_DescribeWarmPool_cli_2_topic"></a>

次のコード例では、`describe-warm-pool` を使用する方法を示しています。

**AWS CLI**  
**ウォームプールを記述する方法**  
この例では、指定された Auto Scaling グループのウォームプールを記述します。  

```
aws autoscaling describe-warm-pool \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "WarmPoolConfiguration": {
        "MinSize": 2,
        "PoolState": "Stopped"
    },
    "Instances": [
        {
            "InstanceId": "i-070a5bbc7e7f40dc5",
            "InstanceType": "t2.micro",
            "AvailabilityZone": "us-west-2c",
            "LifecycleState": "Warmed:Pending",
            "HealthStatus": "Healthy",
            "LaunchTemplate": {
                "LaunchTemplateId": "lt-00a731f6e9fa48610",
                "LaunchTemplateName": "my-template-for-auto-scaling",
                "Version": "6"
            }
        },
        {
            "InstanceId": "i-0b52f061814d3bd2d",
            "InstanceType": "t2.micro",
            "AvailabilityZone": "us-west-2b",
            "LifecycleState": "Warmed:Pending",
            "HealthStatus": "Healthy",
            "LaunchTemplate": {
                "LaunchTemplateId": "lt-00a731f6e9fa48610",
                "LaunchTemplateName": "my-template-for-auto-scaling",
                "Version": "6"
            }
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Warm pools for Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeWarmPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/describe-warm-pool.html)」を参照してください。

### `detach-instances`
<a name="auto-scaling_DetachInstances_cli_2_topic"></a>

次のコード例では、`detach-instances` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループからインスタンスをデタッチする方法**  
この例では、指定されたインスタンスを指定された Auto Scaling グループからデタッチします。  

```
aws autoscaling detach-instances \
    --instance-ids i-030017cfa84b20135 \
    --auto-scaling-group-name my-asg \
    --should-decrement-desired-capacity
```
出力:  

```
{
    "Activities": [
        {
            "ActivityId": "5091cb52-547a-47ce-a236-c9ccbc2cb2c9",
            "AutoScalingGroupName": "my-asg",
            "Description": "Detaching EC2 instance: i-030017cfa84b20135",
            "Cause": "At 2020-10-31T17:35:04Z instance i-030017cfa84b20135 was detached in response to a user request, shrinking the capacity from 2 to 1.",
            "StartTime": "2020-04-12T15:02:16.179Z",
            "StatusCode": "InProgress",
            "Progress": 50,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/detach-instances.html)」を参照してください。

### `detach-load-balancer-target-groups`
<a name="auto-scaling_DetachLoadBalancerTargetGroups_cli_2_topic"></a>

次のコード例では、`detach-load-balancer-target-groups` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループからロードバランサーのターゲットグループをデタッチする方法**  
この例では、指定されたロードバランサーのターゲットグループを指定された Auto Scaling グループからデタッチします。  

```
aws autoscaling detach-load-balancer-target-groups \
    --auto-scaling-group-name my-asg \
    --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループへのロードバランサーのアタッチ](https://docs.aws.amazon.com/autoscaling/ec2/userguide/attach-load-balancer-asg.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachLoadBalancerTargetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/detach-load-balancer-target-groups.html)」を参照してください。

### `detach-load-balancers`
<a name="auto-scaling_DetachLoadBalancers_cli_2_topic"></a>

次のコード例では、`detach-load-balancers` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループから Classic Load Balancer をデタッチする方法**  
この例では、指定された Classic Load Balancer を指定された Auto Scaling グループからデタッチします。  

```
aws autoscaling detach-load-balancers \
    --load-balancer-names my-load-balancer \
    --auto-scaling-group-name my-asg
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループへのロードバランサーのアタッチ](https://docs.aws.amazon.com/autoscaling/ec2/userguide/attach-load-balancer-asg.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/detach-load-balancers.html)」を参照してください。

### `disable-metrics-collection`
<a name="auto-scaling_DisableMetricsCollection_cli_2_topic"></a>

次のコード例では、`disable-metrics-collection` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループのメトリクス収集を無効にする方法**  
この例では、指定された Auto Scaling グループの `GroupDesiredCapacity` メトリクスの収集を無効にします。  

```
aws autoscaling disable-metrics-collection \
    --auto-scaling-group-name my-asg \
    --metrics GroupDesiredCapacity
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスの CloudWatch メトリクスのモニタリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html)」をご参照ください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableMetricsCollection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/disable-metrics-collection.html)」を参照してください。

### `enable-metrics-collection`
<a name="auto-scaling_EnableMetricsCollection_cli_2_topic"></a>

次のコード例では、`enable-metrics-collection` を使用する方法を示しています。

**AWS CLI**  
**例 1: Auto Scaling グループのメトリクス収集を有効にする方法**  
この例では、指定された Auto Scaling グループのデータの収集を有効にします。  

```
aws autoscaling enable-metrics-collection \
    --auto-scaling-group-name my-asg \
    --granularity "1Minute"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスの CloudWatch メトリクスのモニタリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html)」をご参照ください。  
**例 2: Auto Scaling グループの指定されたメトリックスのデータを収集する方法**  
特定のメトリックスのデータを収集するには、`--metrics` オプションを使用します。  

```
aws autoscaling enable-metrics-collection \
    --auto-scaling-group-name my-asg \
    --metrics GroupDesiredCapacity --granularity "1Minute"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループとインスタンスの CloudWatch メトリクスのモニタリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-instance-monitoring.html)」をご参照ください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableMetricsCollection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/enable-metrics-collection.html)」を参照してください。

### `enter-standby`
<a name="auto-scaling_EnterStandby_cli_2_topic"></a>

次のコード例では、`enter-standby` を使用する方法を示しています。

**AWS CLI**  
**インスタンスをスタンバイモードに移行する方法**  
この例では、指定されたインスタンスをスタンバイモードにします。これは、現在稼働中のインスタンスの更新またはトラブルシューティングに役立ちます。  

```
aws autoscaling enter-standby \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg \
    --should-decrement-desired-capacity
```
出力:  

```
{
    "Activities": [
        {
            "ActivityId": "ffa056b4-6ed3-41ba-ae7c-249dfae6eba1",
            "AutoScalingGroupName": "my-asg",
            "Description": "Moving EC2 instance to Standby: i-061c63c5eb45f0416",
            "Cause": "At 2020-10-31T20:31:00Z instance i-061c63c5eb45f0416 was moved to standby in response to a user request, shrinking the capacity from 1 to 0.",
            "StartTime": "2020-10-31T20:31:00.949Z",
            "StatusCode": "InProgress",
            "Progress": 50,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Amazon EC2 Auto Scaling インスタンスのライフサイクル](https://docs.aws.amazon.com/autoscaling/ec2/userguide/detach-instance-asg.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnterStandby](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/enter-standby.html)」を参照してください。

### `execute-policy`
<a name="auto-scaling_ExecutePolicy_cli_2_topic"></a>

次のコード例では、`execute-policy` を使用する方法を示しています。

**AWS CLI**  
**スケーリングポリシーを実行する方法**  
この例では、指定された Auto Scaling グループに「`my-step-scale-out-policy`」という名前のスケーリングポリシーを実行します。  

```
aws autoscaling execute-policy \
    --auto-scaling-group-name my-asg \
    --policy-name  my-step-scale-out-policy \
    --metric-value 95 \
    --breach-threshold 80
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[ステップとシンプルなスケーリングポリシー](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExecutePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/execute-policy.html)」を参照してください。

### `exit-standby`
<a name="auto-scaling_ExitStandby_cli_2_topic"></a>

次のコード例では、`exit-standby` を使用する方法を示しています。

**AWS CLI**  
**インスタンスをスタンバイモードから移動する方法**  
指定されたインスタンスのスタンバイモードを解除します。  

```
aws autoscaling exit-standby \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "Activities": [
        {
            "ActivityId": "142928e1-a2dc-453a-9b24-b85ad6735928",
            "AutoScalingGroupName": "my-asg",
            "Description": "Moving EC2 instance out of Standby: i-061c63c5eb45f0416",
            "Cause": "At 2020-10-31T20:32:50Z instance i-061c63c5eb45f0416 was moved out of standby in response to a user request, increasing the capacity from 0 to 1.",
            "StartTime": "2020-10-31T20:32:50.222Z",
            "StatusCode": "PreInService",
            "Progress": 30,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling グループからの一時的なインスタンスの削除](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-enter-exit-standby.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExitStandby](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/exit-standby.html)」を参照してください。

### `put-lifecycle-hook`
<a name="auto-scaling_PutLifecycleHook_cli_2_topic"></a>

次のコード例では、`put-lifecycle-hook` を使用する方法を示しています。

**AWS CLI**  
**例 1: ライフサイクルフックを作成する方法**  
この例では、新しく起動した任意のインスタンスで呼び出すライフサイクルフックを作成します。タイムアウトは 4800 秒です。これは、ユーザーデータスクリプトが完了するまでインスタンスを待機状態に保つ場合や、EventBridge を使用して AWS Lambda 関数を呼び出す場合に便利です。  

```
aws autoscaling put-lifecycle-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-hook-name my-launch-hook \
    --lifecycle-transition autoscaling:EC2_INSTANCE_LAUNCHING \
    --heartbeat-timeout 4800
```
このコマンドでは何も出力されません。同じ名前のライフサイクルフックがすでに存在する場合、新しいライフサイクルフックによって上書きされます。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling のライフサイクルフック](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)」を参照してください。  
**例 2: Amazon SNS の E メールメッセージを送信してインスタンスの状態遷移を通知する方法**  
この例では、インスタンスの起動時に通知を受信するために使用する Amazon SNS トピックと IAM ロールを含むライフサイクルフックを作成します。  

```
aws autoscaling put-lifecycle-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-hook-name my-launch-hook \
    --lifecycle-transition autoscaling:EC2_INSTANCE_LAUNCHING \
    --notification-target-arn arn:aws:sns:us-west-2:123456789012:my-sns-topic \
    --role-arn arn:aws:iam::123456789012:role/my-auto-scaling-role
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling のライフサイクルフック](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)」を参照してください。  
**例 3: Amazon SQS キューにメッセージを公開する方法**  
この例では、メタデータを含むメッセージを指定された Amazon SQS キューに発行するライフサイクルフックを作成します。  

```
aws autoscaling put-lifecycle-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-hook-name my-launch-hook \
    --lifecycle-transition autoscaling:EC2_INSTANCE_LAUNCHING \
    --notification-target-arn arn:aws:sqs:us-west-2:123456789012:my-sqs-queue \
    --role-arn arn:aws:iam::123456789012:role/my-notification-role \
    --notification-metadata "SQS message metadata"
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling のライフサイクルフック](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLifecycleHook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-lifecycle-hook.html)」を参照してください。

### `put-notification-configuration`
<a name="auto-scaling_PutNotificationConfiguration_cli_2_topic"></a>

次のコード例では、`put-notification-configuration` を使用する方法を示しています。

**AWS CLI**  
**通知を追加する方法**  
この例では、指定された Auto Scaling グループに指定された通知を追加します。  

```
aws autoscaling put-notification-configuration \
    --auto-scaling-group-name my-asg \
    --topic-arn arn:aws:sns:us-west-2:123456789012:my-sns-topic \
    --notification-type autoscaling:TEST_NOTIFICATION
```
このコマンドでは何も出力されません。  
詳細については、『*Amazon EC2 Auto Scaling ユーザーガイド*』の「[Auto Scaling グループのスケーリング時の Amazon SNS 通知の取得](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ASGettingNotifications.html#as-configure-asg-for-sns)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutNotificationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-notification-configuration.html)」を参照してください。

### `put-scaling-policy`
<a name="auto-scaling_PutScalingPolicy_cli_2_topic"></a>

次のコード例では、`put-scaling-policy` を使用する方法を示しています。

**AWS CLI**  
**ターゲット追跡スケーリングポリシーを Auto Scaling グループを追加する方法**  
次の `put-scaling-policy` 例では、指定された Auto Scaling グループにターゲットトラッキングスケーリングポリシーを適用します。出力には、自動的に作成された 2 つの CloudWatch アラームの ARN と名前が含まれます。同じ名前のスケーリングポリシーが既に存在する場合は、新しいスケーリングポリシーで上書きされます。  

```
aws autoscaling put-scaling-policy --auto-scaling-group-name my-asg \
  --policy-name alb1000-target-tracking-scaling-policy \
  --policy-type TargetTrackingScaling \
  --target-tracking-configuration file://config.json
```
`config.json` の内容:  

```
{
     "TargetValue": 1000.0,
     "PredefinedMetricSpecification": {
          "PredefinedMetricType": "ALBRequestCountPerTarget",
          "ResourceLabel": "app/my-alb/778d41231b141a0f/targetgroup/my-alb-target-group/943f017f100becff"
     }
}
```
出力:  

```
{
     "PolicyARN": "arn:aws:autoscaling:region:account-id:scalingPolicy:228f02c2-c665-4bfd-aaac-8b04080bea3c:autoScalingGroupName/my-asg:policyName/alb1000-target-tracking-scaling-policy",
     "Alarms": [
         {
             "AlarmARN": "arn:aws:cloudwatch:region:account-id:alarm:TargetTracking-my-asg-AlarmHigh-fc0e4183-23ac-497e-9992-691c9980c38e",
             "AlarmName": "TargetTracking-my-asg-AlarmHigh-fc0e4183-23ac-497e-9992-691c9980c38e"
         },
         {
             "AlarmARN": "arn:aws:cloudwatch:region:account-id:alarm:TargetTracking-my-asg-AlarmLow-61a39305-ed0c-47af-bd9e-471a352ee1a2",
             "AlarmName": "TargetTracking-my-asg-AlarmLow-61a39305-ed0c-47af-bd9e-471a352ee1a2"
         }
     ]
 }
```
その他の例については、「Amazon EC2 Auto Scaling [AWS ユーザーガイド」の「コマンドラインインターフェイス (AWS CLI) のスケーリングポリシーの例](https://docs.aws.amazon.com/autoscaling/ec2/userguide/examples-scaling-policies.html)」を参照してください。 *Amazon EC2 Auto Scaling *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutScalingPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-scaling-policy.html)」を参照してください。

### `put-scheduled-update-group-action`
<a name="auto-scaling_PutScheduledUpdateGroupAction_cli_2_topic"></a>

次のコード例では、`put-scheduled-update-group-action` を使用する方法を示しています。

**AWS CLI**  
**例 1: スケジュール済みのアクションを Auto Scaling グループに追加する方法**  
この例では、指定された Auto Scaling グループから指定されたスケジュール済みの通知を追加します。  

```
aws autoscaling put-scheduled-update-group-action \
    --auto-scaling-group-name my-asg \
    --scheduled-action-name my-scheduled-action \
    --start-time "2023-05-12T08:00:00Z" \
    --min-size 2 \
    --max-size 6 \
    --desired-capacity 4
```
このコマンドでは何も出力されません。同じ名前のスケジュールされたアクションが既に存在する場合、新しいスケジュールされたアクションで上書きされます。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[スケジュールされたスケーリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
**例 2: 定期的なスケジュールを指定する方法**  
この例では、毎年 1 月、6 月、12 月の 1 日の 00:30 に実行する定期スケジュールでスケーリングするスケジュール済みのアクションを作成します。  

```
aws autoscaling put-scheduled-update-group-action \
    --auto-scaling-group-name my-asg \
    --scheduled-action-name my-recurring-action \
    --recurrence "30 0 1 1,6,12 *" \
    --min-size 2 \
    --max-size 6 \
    --desired-capacity 4
```
このコマンドでは何も出力されません。同じ名前のスケジュールされたアクションが既に存在する場合、新しいスケジュールされたアクションで上書きされます。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[スケジュールされたスケーリング](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-scheduled-scaling.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[PutScheduledUpdateGroupAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-scheduled-update-group-action.html)」を参照してください。

### `put-warm-pool`
<a name="auto-scaling_PutWarmPool_cli_2_topic"></a>

次のコード例では、`put-warm-pool` を使用する方法を示しています。

**AWS CLI**  
**ウォームプールを作成する方法**  
次の例では、特定の Auto Scaling グループのウォームプールを作成します。  

```
aws autoscaling put-warm-pool \
    --auto-scaling-group-name my-asg \
    --min-size 2
```
このコマンドでは何も出力されません。ウォームプールが既に存在する場合は、更新されます。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Warm pools for Amazon EC2 Auto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-warm-pools.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutWarmPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/put-warm-pool.html)」を参照してください。

### `record-lifecycle-action-heartbeat`
<a name="auto-scaling_RecordLifecycleActionHeartbeat_cli_2_topic"></a>

次のコード例では、`record-lifecycle-action-heartbeat` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルアクションハートビートを記録する方法**  
この例では、ライフサイクルアクションのハートビートを記録して、インスタンスを保留状態に保ちます。  

```
aws autoscaling record-lifecycle-action-heartbeat \
    --lifecycle-hook-name my-launch-hook \
    --auto-scaling-group-name my-asg \
    --lifecycle-action-token bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Amazon EC2 Auto Scaling のライフサイクルフック](https://docs.aws.amazon.com/autoscaling/ec2/userguide/lifecycle-hooks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RecordLifecycleActionHeartbeat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/record-lifecycle-action-heartbeat.html)」を参照してください。

### `resume-processes`
<a name="auto-scaling_ResumeProcesses_cli_2_topic"></a>

次のコード例では、`resume-processes` を使用する方法を示しています。

**AWS CLI**  
**停止されたプロセスを再開する方法**  
この例では、指定された Auto Scaling グループの指定された一時停止スケーリングプロセスを再開します。  

```
aws autoscaling resume-processes \
    --auto-scaling-group-name my-asg \
    --scaling-processes AlarmNotification
```
このコマンドでは何も出力されません。  
詳細については、「[Amazon EC2 Auto Scaling ユーザーガイド](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)」の「*スケーリングプロセスの中断と再開*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResumeProcesses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/resume-processes.html)」を参照してください。

### `rollback-instance-refresh`
<a name="auto-scaling_RollbackInstanceRefresh_cli_2_topic"></a>

次のコード例では、`rollback-instance-refresh` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの更新をロールバックする方法**  
次の `rollback-instance-refresh` 例では、指定された Auto Scaling グループの進行中のインスタンスの更新をロールバックします。  

```
aws autoscaling rollback-instance-refresh \
    --auto-scaling-group-name my-asg
```
出力:  

```
{
    "InstanceRefreshId": "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b"
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Undo changes with a rollback](https://docs.aws.amazon.com/autoscaling/ec2/userguide/instance-refresh-rollback.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RollbackInstanceRefresh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/rollback-instance-refresh.html)」を参照してください。

### `set-desired-capacity`
<a name="auto-scaling_SetDesiredCapacity_cli_2_topic"></a>

次のコード例では、`set-desired-capacity` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループに希望する容量を設定する方法**  
この例では、指定された Auto Scaling グループの希望する容量を設定します。  

```
aws autoscaling set-desired-capacity \
    --auto-scaling-group-name my-asg \
    --desired-capacity 2 \
    --honor-cooldown
```
正常に完了すると、このコマンドはプロンプトに戻ります。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetDesiredCapacity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/set-desired-capacity.html)」を参照してください。

### `set-instance-health`
<a name="auto-scaling_SetInstanceHealth_cli_2_topic"></a>

次のコード例では、`set-instance-health` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのヘルスステータスをチェックする方法**  
指定されたインスタンスのヘルスステータスを `Unhealthy` に設定します。  

```
aws autoscaling set-instance-health \
    --instance-id i-061c63c5eb45f0416 \
    --health-status Unhealthy
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetInstanceHealth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/set-instance-health.html)」を参照してください。

### `set-instance-protection`
<a name="auto-scaling_SetInstanceProtection_cli_2_topic"></a>

次のコード例では、`set-instance-protection` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスに対するインスタンスの保護設定を変更する方法**  
この例では、指定されたインスタンスのインスタンス保護を有効にします。  

```
aws autoscaling set-instance-protection \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg --protected-from-scale-in
```
このコマンドでは何も出力されません。  
**例 2: インスタンスに対するインスタンスの保護設定を無効にする方法**  
この例では、指定されたインスタンスのインスタンス保護を無効にします。  

```
aws autoscaling set-instance-protection \
    --instance-ids i-061c63c5eb45f0416 \
    --auto-scaling-group-name my-asg \
    --no-protected-from-scale-in
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetInstanceProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/set-instance-protection.html)」を参照してください。

### `start-instance-refresh`
<a name="auto-scaling_StartInstanceRefresh_cli_2_topic"></a>

次のコード例では、`start-instance-refresh` を使用する方法を示しています。

**AWS CLI**  
**例 1: コマンドラインパラメータを使用してインスタンスの更新を開始する方法**  
次の `start-instance-refresh` 例では、コマンドライン引数を使用してインスタンスの更新を開始します。オプションの `preferences` パラメータは、`60` 秒の `InstanceWarmup` と `50` パーセント `MinHealthyPercentage` を指定します。  

```
aws autoscaling start-instance-refresh \
    --auto-scaling-group-name my-asg \
    --preferences '{"InstanceWarmup": 60, "MinHealthyPercentage": 50}'
```
出力:  

```
{
    "InstanceRefreshId": "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b"
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[インスタンスの更新を開始](https://docs.aws.amazon.com/en_us/autoscaling/ec2/userguide/start-instance-refresh.html)」を参照してください。  
**例 2: JSON ファイルを使用してインスタンスの更新を開始する方法**  
次の `start-instance-refresh` 例では、JSON ファイルを使用してインスタンスの更新を開始します。次の例に示すように、Auto Scaling グループを指定し、JSON ファイルで必要な各種構成を定義できます。  

```
aws autoscaling start-instance-refresh \
    --cli-input-json file://config.json
```
`config.json` の内容:  

```
{
    "AutoScalingGroupName": "my-asg",
    "DesiredConfiguration": {
        "LaunchTemplate": {
            "LaunchTemplateId": "lt-068f72b729example",
            "Version": "$Default"
        }
    },
    "Preferences": {
        "InstanceWarmup": 60,
        "MinHealthyPercentage": 50,
        "AutoRollback": true,
        "ScaleInProtectedInstances": Ignore,
        "StandbyInstances": Terminate
    }
}
```
出力:  

```
{
    "InstanceRefreshId": "08b91cf7-8fa6-48af-b6a6-d227f40f1b9b"
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[インスタンスの更新を開始](https://docs.aws.amazon.com/en_us/autoscaling/ec2/userguide/start-instance-refresh.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartInstanceRefresh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/start-instance-refresh.html)」を参照してください。

### `suspend-processes`
<a name="auto-scaling_SuspendProcesses_cli_2_topic"></a>

次のコード例では、`suspend-processes` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling プロセスを一時停止する方法**  
この例では、指定された Auto Scaling グループの指定されたスケーリングプロセスを一時停止します。  

```
aws autoscaling suspend-processes \
    --auto-scaling-group-name my-asg \
    --scaling-processes AlarmNotification
```
このコマンドでは何も出力されません。  
詳細については、「[Amazon EC2 Auto Scaling ユーザーガイド](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-suspend-resume-processes.html)」の「*スケーリングプロセスの中断と再開*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SuspendProcesses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/suspend-processes.html)」を参照してください。

### `terminate-instance-in-auto-scaling-group`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_cli_2_topic"></a>

次のコード例では、`terminate-instance-in-auto-scaling-group` を使用する方法を示しています。

**AWS CLI**  
**Auto Scaling グループのインスタンスを終了する方法**  
この例では、グループのサイズを更新せずに、指定された Auto Scaling グループの指定されたインスタンスを終了します。指定されたインスタンスが終了した後、Amazon EC2 Auto Scaling は代替インスタンスを起動します。  

```
aws autoscaling terminate-instance-in-auto-scaling-group \
    --instance-id i-061c63c5eb45f0416 \
    --no-should-decrement-desired-capacity
```
出力:  

```
{
    "Activities": [
        {
            "ActivityId": "8c35d601-793c-400c-fcd0-f64a27530df7",
            "AutoScalingGroupName": "my-asg",
            "Description": "Terminating EC2 instance: i-061c63c5eb45f0416",
            "Cause": "",
            "StartTime": "2020-10-31T20:34:25.680Z",
            "StatusCode": "InProgress",
            "Progress": 0,
            "Details": "{\"Subnet ID\":\"subnet-6194ea3b\",\"Availability Zone\":\"us-west-2c\"}"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/terminate-instance-in-auto-scaling-group.html)」を参照してください。

### `update-auto-scaling-group`
<a name="auto-scaling_UpdateAutoScalingGroup_cli_2_topic"></a>

次のコード例では、`update-auto-scaling-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: Auto Scaling グループのサイズ制限を更新する方法**  
この例では、最小サイズが 2、最大サイズが 10 で、指定された Auto Scaling グループを更新します。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --min-size 2 \
    --max-size 10
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Auto Scaling グループにキャパシティの制限を設定する](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-capacity-limits.html)」を参照してください。**  
**例 2: Elastic Load Balancing ヘルスチェックを追加し、使用するアベイラビリティーゾーンとサブネットを指定する方法**  
この例では、指定された Auto Scaling グループを更新して、Elastic Load Balancing のヘルスチェックを追加します。またこのコマンドは、複数のアベイラビリティーゾーンのサブネット ID のリストを使用して、`--vpc-zone-identifier` の値も更新します。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --health-check-type ELB \
    --health-check-grace-period 600 \
    --vpc-zone-identifier "subnet-5ea0c127,subnet-6194ea3b,subnet-c934b782"
```
このコマンドでは何も出力されません。  
詳細については、「Amazon EC2 Auto Scaling ユーザーガイド」の「[Elastic Load Balancing を使用して Auto Scaling グループ内のインスタンス全体にトラフィックを分散させる](https://docs.aws.amazon.com/autoscaling/ec2/userguide/autoscaling-load-balancer.html)」を参照してください。**  
**例 3: プレイスメントグループと終了ポリシーを更新する方法**  
この例では、プレイスメントグループと終了ポリシーを更新します。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --placement-group my-placement-group \
    --termination-policies "OldestInstance"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[Auto Scaling groups](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroup.html)」を参照してください。  
**例 4: 起動テンプレートの最新バージョンを使用する方法**  
この例では、最新の起動テンプレートバージョンを使用するように、指定された Auto Scaling グループを更新します。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateId=lt-1234567890abcde12,Version='$Latest'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[起動テンプレート](https://docs.aws.amazon.com/autoscaling/ec2/userguide/LaunchTemplates.html)」を参照してください。  
**例 5: 特定のバージョンの起動テンプレートを使用する方法**  
この例では、最新バージョンやデフォルトバージョンではなく、指定された起動テンプレートのバージョンを使用するように、指定された Auto Scaling グループを更新します。  

```
aws autoscaling update-auto-scaling-group \
    --auto-scaling-group-name my-asg \
    --launch-template LaunchTemplateName=my-template-for-auto-scaling,Version='2'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「[起動テンプレート](https://docs.aws.amazon.com/autoscaling/ec2/userguide/LaunchTemplates.html)」を参照してください。  
**例 6: 混合インスタンスポリシーを定義し、容量のリバランスを有効にする方法**  
この例では、指定された Auto Scaling グループを更新して、混合インスタンスポリシーを使用し、容量のリバランスを有効にします。この構造により、スポット容量とオンデマンド容量でグループを指定し、アーキテクチャごとに異なる起動テンプレートを使用できます。  

```
aws autoscaling update-auto-scaling-group \
    --cli-input-json file://~/config.json
```
`config.json` の内容:  

```
{
    "AutoScalingGroupName": "my-asg",
    "CapacityRebalance": true,
    "MixedInstancesPolicy": {
        "LaunchTemplate": {
            "LaunchTemplateSpecification": {
                "LaunchTemplateName": "my-launch-template-for-x86",
                "Version": "$Latest"
            },
            "Overrides": [
                {
                    "InstanceType": "c6g.large",
                    "LaunchTemplateSpecification": {
                        "LaunchTemplateName": "my-launch-template-for-arm",
                        "Version": "$Latest"
                    }
                },
                {
                    "InstanceType": "c5.large"
                },
                {
                    "InstanceType": "c5a.large"
                }
            ]
        },
        "InstancesDistribution": {
            "OnDemandPercentageAboveBaseCapacity": 50,
            "SpotAllocationStrategy": "capacity-optimized"
        }
    }
}
```
このコマンドでは何も出力されません。  
詳細については「Amazon EC2 Auto Scaling ユーザーガイド」の「[複数のインスタンスタイプと購入オプションを使用する Auto Scaling グループ](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-purchase-options.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAutoScalingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling/update-auto-scaling-group.html)」を参照してください。

# を使用した Auto Scaling Plans の例 AWS CLI
<a name="cli_2_auto-scaling-plans_code_examples"></a>

次のコード例は、Auto Scaling Plans AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-scaling-plan`
<a name="auto-scaling-plans_CreateScalingPlan_cli_2_topic"></a>

次の例では、`create-scaling-plan` を使用する方法を説明しています。

**AWS CLI**  
**スケーリングプランを作成する方法**  
次の `create-scaling-plan` の例では、既に作成された JSON ファイル (config.json という名前) を使用して「`my-scaling-plan`」という名前のスケーリングプランを作成します。スケーリングプランの構造には、「`my-asg`」という名前の自動スケーリンググループのスケーリング命令が含まれています。`TagFilters` プロパティをアプリケーションソースとして指定し、予測スケーリングと動的スケーリングを有効にします。  

```
aws autoscaling-plans create-scaling-plan \
    --scaling-plan-name my-scaling-plan \
    --cli-input-json file://~/config.json
```
`config.json` ファイルの内容。  

```
{
    "ApplicationSource": {
        "TagFilters": [
            {
                "Key": "purpose",
                "Values": [
                    "my-application"
                ]
            }
        ]
    },
    "ScalingInstructions": [
        {
            "ServiceNamespace": "autoscaling",
            "ResourceId": "autoScalingGroup/my-asg",
            "ScalableDimension": "autoscaling:autoScalingGroup:DesiredCapacity",
            "ScheduledActionBufferTime": 300,
            "PredictiveScalingMaxCapacityBehavior": "SetForecastCapacityToMaxCapacity",
            "PredictiveScalingMode": "ForecastAndScale",
            "PredefinedLoadMetricSpecification": {
                "PredefinedLoadMetricType": "ASGTotalCPUUtilization"
            },
            "ScalingPolicyUpdateBehavior": "ReplaceExternalPolicies",
            "MinCapacity": 1,
            "MaxCapacity": 4,
            "TargetTrackingConfigurations": [
                {
                    "PredefinedScalingMetricSpecification": {
                        "PredefinedScalingMetricType": "ASGAverageCPUUtilization"
                    },
                    "TargetValue": 50
                }
            ]
        }
    ]
}
```
出力:  

```
{
"ScalingPlanVersion": 1
}
```
詳細については、「[AWS 自動スケーリングユーザーガイド](https://docs.aws.amazon.com/autoscaling/plans/userguide/what-is-aws-auto-scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateScalingPlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling-plans/create-scaling-plan.html)」を参照してください。

### `delete-scaling-plan`
<a name="auto-scaling-plans_DeleteScalingPlan_cli_2_topic"></a>

次の例では、`delete-scaling-plan` を使用する方法を説明しています。

**AWS CLI**  
**スケーリングプランを削除する方法**  
次の `delete-scaling-plan` の例では、指定されたスケーリングプランを削除します。  

```
aws autoscaling-plans delete-scaling-plan \
    --scaling-plan-name my-scaling-plan \
    --scaling-plan-version 1
```
このコマンドでは何も出力されません。  
詳細については、「[AWS 自動スケーリングユーザーガイド](https://docs.aws.amazon.com/autoscaling/plans/userguide/what-is-aws-auto-scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteScalingPlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling-plans/delete-scaling-plan.html)」を参照してください。

### `describe-scaling-plan-resources`
<a name="auto-scaling-plans_DescribeScalingPlanResources_cli_2_topic"></a>

次の例では、`describe-scaling-plan-resources` を使用する方法を説明しています。

**AWS CLI**  
**スケーリングプランのスケーラブルリソースを記述する方法**  
次の `describe-scaling-plan-resources` の例では、指定されたスケーリングプランに関連付けられている単一のスケーラブルリソース (自動スケーリンググループ) の詳細を表示します。  

```
aws autoscaling-plans describe-scaling-plan-resources \
    --scaling-plan-name my-scaling-plan \
    --scaling-plan-version 1
```
出力:  

```
{
    "ScalingPlanResources": [
        {
            "ScalableDimension": "autoscaling:autoScalingGroup:DesiredCapacity",
            "ScalingPlanVersion": 1,
            "ResourceId": "autoScalingGroup/my-asg",
            "ScalingStatusCode": "Active",
            "ScalingStatusMessage": "Target tracking scaling policies have been applied to the resource.",
            "ScalingPolicies": [
                {
                    "PolicyName": "AutoScaling-my-asg-b1ab65ae-4be3-4634-bd64-c7471662b251",
                    "PolicyType": "TargetTrackingScaling",
                    "TargetTrackingConfiguration": {
                        "PredefinedScalingMetricSpecification": {
                            "PredefinedScalingMetricType": "ALBRequestCountPerTarget",
                            "ResourceLabel": "app/my-alb/f37c06a68c1748aa/targetgroup/my-target-group/6d4ea56ca2d6a18d"
                        },
                        "TargetValue": 40.0
                    }
                }
            ],
            "ServiceNamespace": "autoscaling",
            "ScalingPlanName": "my-scaling-plan"
        }
    ]
}
```
詳細については、[AWS Auto Scaling とは」を参照してください。](https://docs.aws.amazon.com/autoscaling/plans/userguide/what-is-aws-auto-scaling.html) *AWS Auto Scaling ユーザーガイド*」の「」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScalingPlanResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling-plans/describe-scaling-plan-resources.html)」を参照してください。

### `describe-scaling-plans`
<a name="auto-scaling-plans_DescribeScalingPlans_cli_2_topic"></a>

次の例では、`describe-scaling-plans` を使用する方法を説明しています。

**AWS CLI**  
**スケーリングプランを記述する方法**  
次の `describe-scaling-plans` の例では、指定されたスケーリングプランの詳細を表示します。  

```
aws autoscaling-plans describe-scaling-plans \
    --scaling-plan-names scaling-plan-with-asg-and-ddb
```
出力:  

```
{
    "ScalingPlans": [
        {
            "LastMutatingRequestTime": 1565388443.963,
            "ScalingPlanVersion": 1,
            "CreationTime": 1565388443.963,
            "ScalingInstructions": [
                {
                    "ScalingPolicyUpdateBehavior": "ReplaceExternalPolicies",
                    "ScalableDimension": "autoscaling:autoScalingGroup:DesiredCapacity",
                    "TargetTrackingConfigurations": [
                        {
                            "PredefinedScalingMetricSpecification": {
                                "PredefinedScalingMetricType": "ASGAverageCPUUtilization"
                            },
                            "TargetValue": 50.0,
                            "EstimatedInstanceWarmup": 300,
                            "DisableScaleIn": false
                        }
                    ],
                    "ResourceId": "autoScalingGroup/my-asg",
                    "DisableDynamicScaling": false,
                    "MinCapacity": 1,
                    "ServiceNamespace": "autoscaling",
                    "MaxCapacity": 10
                },
                {
                    "ScalingPolicyUpdateBehavior": "ReplaceExternalPolicies",
                    "ScalableDimension": "dynamodb:table:ReadCapacityUnits",
                    "TargetTrackingConfigurations": [
                        {
                            "PredefinedScalingMetricSpecification": {
                                "PredefinedScalingMetricType": "DynamoDBReadCapacityUtilization"
                            },
                            "TargetValue": 50.0,
                            "ScaleInCooldown": 60,
                            "DisableScaleIn": false,
                            "ScaleOutCooldown": 60
                        }
                    ],
                    "ResourceId": "table/my-table",
                    "DisableDynamicScaling": false,
                    "MinCapacity": 5,
                    "ServiceNamespace": "dynamodb",
                    "MaxCapacity": 10000
                },
                {
                    "ScalingPolicyUpdateBehavior": "ReplaceExternalPolicies",
                    "ScalableDimension": "dynamodb:table:WriteCapacityUnits",
                    "TargetTrackingConfigurations": [
                        {
                            "PredefinedScalingMetricSpecification": {
                                "PredefinedScalingMetricType": "DynamoDBWriteCapacityUtilization"
                            },
                            "TargetValue": 50.0,
                            "ScaleInCooldown": 60,
                            "DisableScaleIn": false,
                            "ScaleOutCooldown": 60
                        }
                    ],
                    "ResourceId": "table/my-table",
                    "DisableDynamicScaling": false,
                    "MinCapacity": 5,
                    "ServiceNamespace": "dynamodb",
                    "MaxCapacity": 10000
                }
            ],
            "ApplicationSource": {
                "TagFilters": [
                    {
                        "Values": [
                            "my-application-id"
                        ],
                        "Key": "application"
                    }
                ]
            },
            "StatusStartTime": 1565388455.836,
            "ScalingPlanName": "scaling-plan-with-asg-and-ddb",
            "StatusMessage": "Scaling plan has been created and applied to all resources.",
            "StatusCode": "Active"
        }
    ]
}
```
詳細については、[AWS Auto Scaling とは」を参照してください。](https://docs.aws.amazon.com/autoscaling/plans/userguide/what-is-aws-auto-scaling.html) *AWS Auto Scaling ユーザーガイド*」の「」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScalingPlans](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling-plans/describe-scaling-plans.html)」を参照してください。

### `get-scaling-plan-resource-forecast-data`
<a name="auto-scaling-plans_GetScalingPlanResourceForecastData_cli_2_topic"></a>

次の例では、`get-scaling-plan-resource-forecast-data` を使用する方法を説明しています。

**AWS CLI**  
**ロード予測データを取得する方法**  
この例では、指定されたスケーリングプランに関連付けられているスケーラブルリソース (自動スケーリンググループ) のロード予測データを取得します。  

```
aws autoscaling-plans get-scaling-plan-resource-forecast-data \
    --scaling-plan-name my-scaling-plan \
    --scaling-plan-version 1 \
    --service-namespace "autoscaling" \
    --resource-id autoScalingGroup/my-asg \
    --scalable-dimension "autoscaling:autoScalingGroup:DesiredCapacity" \
    --forecast-data-type "LoadForecast" \
    --start-time "2019-08-30T00:00:00Z" \
    --end-time "2019-09-06T00:00:00Z"
```
出力:  

```
{
    "Datapoints": [...]
}
```
詳細については、[AWS Auto Scaling ](https://docs.aws.amazon.com/autoscaling/plans/userguide/what-is-aws-auto-scaling.html)*AWS ユーザーガイド」のAuto Scaling *とは」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetScalingPlanResourceForecastData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling-plans/get-scaling-plan-resource-forecast-data.html)」を参照してください。

### `update-scaling-plan`
<a name="auto-scaling-plans_UpdateScalingPlan_cli_2_topic"></a>

次の例では、`update-scaling-plan` を使用する方法を説明しています。

**AWS CLI**  
**スケーリングプランを更新する方法**  
次の `update-scaling-plan` の例では、指定されたスケーリングプランの自動スケーリンググループのスケーリングメトリクスを変更します。  

```
aws autoscaling-plans update-scaling-plan \
    --scaling-plan-name my-scaling-plan \
    --scaling-plan-version 1 \
    --scaling-instructions '{"ScalableDimension":"autoscaling:autoScalingGroup:DesiredCapacity","ResourceId":"autoScalingGroup/my-asg","ServiceNamespace":"autoscaling","TargetTrackingConfigurations":[{"PredefinedScalingMetricSpecification": {"PredefinedScalingMetricType":"ALBRequestCountPerTarget","ResourceLabel":"app/my-alb/f37c06a68c1748aa/targetgroup/my-target-group/6d4ea56ca2d6a18d"},"TargetValue":40.0}],"MinCapacity": 1,"MaxCapacity": 10}'
```
このコマンドでは何も出力されません。  
詳細については、[AWS Auto Scaling とは」を参照してください。](https://docs.aws.amazon.com/autoscaling/plans/userguide/what-is-aws-auto-scaling.html) *AWS Auto Scaling ユーザーガイド*」の「」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateScalingPlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/autoscaling-plans/update-scaling-plan.html)」を参照してください。

# AWS Backup を使用した の例 AWS CLI
<a name="cli_2_backup_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Backup。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-backup-plan`
<a name="backup_CreateBackupPlan_cli_2_topic"></a>

次の例では、`create-backup-plan` を使用する方法を説明しています。

**AWS CLI**  
**バックアッププランを作成する方法**  
次の `create-backup-plan` の例では、35 日間の保持期間を持つ指定されたバックアッププランを作成します。  

```
aws backup create-backup-plan \
--backup-plan "{\"BackupPlanName\":\"Example-Backup-Plan\",\"Rules\":[{\"RuleName\":\"DailyBackups\",\"ScheduleExpression\":\"cron(0 5 ? * * *)\",\"StartWindowMinutes\":480,\"TargetBackupVaultName\":\"Default\",\"Lifecycle\":{\"DeleteAfterDays\":35}}]}"
```
出力:  

```
{
    "BackupPlanId": "1fa3895c-a7f5-484a-a371-2dd6a1a9f729",
    "BackupPlanArn": "arn:aws:backup:us-west-2:123456789012:backup-plan:1fa3895c-a7f5-484a-a371-2dd6a1a9f729",
    "CreationDate": 1568928754.747,
    "VersionId": "ZjQ2ZTI5YWQtZDg5Yi00MzYzLWJmZTAtMDI1MzhlMDhjYjEz"
}
```
詳細については、「*AWS デベロッパーガイド*」の「[バックアッププランの作成](https://docs.aws.amazon.com/aws-backup/latest/devguide/creating-a-backup-plan.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドレットリファレンス*」の「[CreateBackupPlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/backup/create-backup-plan.html)」を参照してください。

### `create-backup-vault`
<a name="backup_CreateBackupVault_cli_2_topic"></a>

次の例では、`create-backup-vault` を使用する方法を説明しています。

**AWS CLI**  
**バックアップボールトを作成する方法**  
次の `create-backup-vault` 例では、指定された名前のバックアップボールトを作成します。  

```
aws backup create-backup-vault
    --backup-vault-name sample-vault
```
このコマンドでは何も出力されません。出力:  

```
{
    "BackupVaultName": "sample-vault",
    "BackupVaultArn": "arn:aws:backup:us-west-2:123456789012:backup-vault:sample-vault",
    "CreationDate": 1568928338.385
}
```
詳細については、「*AWS デベロッパーガイド*」の「[バックアッププランの作成](https://docs.aws.amazon.com/aws-backup/latest/devguide/creating-a-vault.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBackupVault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/backup/create-backup-vault.html)」を参照してください。

### `get-backup-plan-from-template`
<a name="backup_GetBackupPlanFromTemplate_cli_2_topic"></a>

次の例では、`get-backup-plan-from-template` を使用する方法を説明しています。

**AWS CLI**  
**テンプレートから既存のバックアッププランを取得する方法**  
次の `get-backup-plan-from-template` の例では、35 日間の保持期間を持つ日次バックアップを指定するテンプレートから既存のバックアッププランを取得します。  

```
aws backup get-backup-plan-from-template \
    --backup-plan-template-id "87c0c1ef-254d-4180-8fef-2e76a2c38aaa"
```
出力:  

```
{
    "BackupPlanDocument": {
        "Rules": [
            {
                "RuleName": "DailyBackups",
                "ScheduleExpression": "cron(0 5 ? * * *)",
                "StartWindowMinutes": 480,
                "Lifecycle": {
                    "DeleteAfterDays": 35
                }
            }
        ]
    }
}
```
詳細については、「*AWS デベロッパーガイド*」の「[バックアッププランの作成](https://docs.aws.amazon.com/aws-backup/latest/devguide/creating-a-backup-plan.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBackupPlanFromTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/backup/get-backup-plan-from-template.html)」を参照してください。

### `get-backup-plan`
<a name="backup_GetBackupPlan_cli_2_topic"></a>

次の例では、`get-backup-plan` を使用する方法を説明しています。

**AWS CLI**  
**バックアッププランの詳細を取得する方法**  
次の `get-backup-plan` の例では、指定されたバックアッププランの詳細を表示します。  

```
aws backup get-backup-plan \
    --backup-plan-id "fcbf5d8f-bd77-4f3a-9c97-f24fb3d373a5"
```
出力:  

```
{
    "BackupPlan": {
        "BackupPlanName": "Example-Backup-Plan",
        "Rules": [
            {
                "RuleName": "DailyBackups",
                "TargetBackupVaultName": "Default",
                "ScheduleExpression": "cron(0 5 ? * * *)",
                "StartWindowMinutes": 480,
                "CompletionWindowMinutes": 10080,
                "Lifecycle": {
                    "DeleteAfterDays": 35
                },
                "RuleId": "70e0ccdc-e9df-4e83-82ad-c1e5a9471cc3"
            }
        ]
    },
    "BackupPlanId": "fcbf5d8f-bd77-4f3a-9c97-f24fb3d373a5",
    "BackupPlanArn": "arn:aws:backup:us-west-2:123456789012:backup-plan:fcbf5d8f-bd77-4f3a-9c97-f24fb3d373a5",
    "VersionId": "NjQ2ZTZkODktMGVhNy00MmQ0LWE4YjktZTkwNTQ3OTkyYTcw",
    "CreationDate": 1568926091.57
}
```
詳細については、「*AWS デベロッパーガイド*」の「[バックアッププランの作成](https://docs.aws.amazon.com/aws-backup/latest/devguide/creating-a-backup-plan.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBackupPlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/backup/get-backup-plan.html)」を参照してください。

### `list-backup-jobs`
<a name="backup_ListBackupJobs_cli_2_topic"></a>

次の例では、`list-backup-jobs` を使用する方法を説明しています。

**AWS CLI**  
**例 1: すべてのバックアップジョブを一覧表示する方法**  
次の の`list-backup-jobs`例では、 AWS アカウントのバックアップジョブに関するメタデータを返します。  

```
aws backup list-backup-jobs
```
出力:  

```
{
    "BackupJobs": [
        {
            "BackupJobId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "BackupVaultName": "Default",
            "BackupVaultArn": "arn:aws:backup:us-west-2:123456789012:backup-vault:Default",
            "ResourceArn": "arn:aws:ec2:us-west-2:123456789012:instance/i-12345678901234567",
            "CreationDate": 1600721892.929,
            "State": "CREATED",
            "PercentDone": "0.0",
            "IamRoleArn": "arn:aws:iam::123456789012:role/service-role/AWSBackupDefaultServiceRole",
            "StartBy": 1600725492.929,
            "ResourceType": "EC2"
        },
        {
            "BackupJobId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "BackupVaultName": "Default",
            "BackupVaultArn": "arn:aws:backup:us-west-2:123456789012:backup-vault:Default",
            "RecoveryPointArn": "arn:aws:backup:us-west-2:123456789012:recovery-point:a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "ResourceArn": "arn:aws:elasticfilesystem:us-west-2:123456789012:file-system/fs-12345678",
            "CreationDate": 1600721724.77,
            "CompletionDate": 1600721744.488,
            "State": "COMPLETED",
            "PercentDone": "100.0",
            "BackupSizeInBytes": 71,
            "IamRoleArn": "arn:aws:iam::123456789012:role/service-role/AWSBackupDefaultServiceRole",
            "StartBy": 1600725324.77,
            "ResourceType": "EFS"
        }
    ]
}
```
詳細については、「*AWS バックアップデベロッパーガイド*」の「[バックアッププランの作成](https://https://docs.aws.amazon.com/aws-backup/latest/devguide/creating-a-backup.html)」を参照してください。  
**例 2: 完了したバックアップジョブを一覧表示する方法**  
次の の`list-backup-jobs`例では、 AWS アカウントで完了したバックアップジョブに関するメタデータを返します。  

```
aws backup list-backup-jobs \
    --by-state COMPLETED
```
出力:  

```
{
    "BackupJobs": [
        {
            "BackupJobId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "BackupVaultName": "Default",
            "BackupVaultArn": "arn:aws:backup:us-west-2:123456789012:backup-vault:Default",
            "RecoveryPointArn": "arn:aws:backup:us-west-2:123456789012:recovery-point:a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "ResourceArn": "arn:aws:elasticfilesystem:us-west-2:123456789012:file-system/fs-12345678",
            "CreationDate": 1600721724.77,
            "CompletionDate": 1600721744.488,
            "State": "COMPLETED",
            "PercentDone": "100.0",
            "BackupSizeInBytes": 71,
            "IamRoleArn": "arn:aws:iam::123456789012:role/service-role/AWSBackupDefaultServiceRole",
            "StartBy": 1600725324.77,
            "ResourceType": "EFS"
        }
    ]
}
```
詳細については、「*AWS バックアップデベロッパーガイド*」の「[バックアッププランの作成](https://https://docs.aws.amazon.com/aws-backup/latest/devguide/creating-a-backup.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBackupJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/backup/list-backup-jobs.html)」を参照してください。

# AWS Batch を使用した の例 AWS CLI
<a name="cli_2_batch_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Batch。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `cancel-job`
<a name="batch_CancelJob_cli_2_topic"></a>

次のコード例では、`cancel-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブをキャンセルする方法**  
この例では、指定されたジョブ ID のジョブをキャンセルします。  
コマンド:  

```
aws batch cancel-job --job-id bcf0b186-a532-4122-842e-2ccab8d54efb --reason "Cancelling job."
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/cancel-job.html)」を参照してください。

### `create-compute-environment`
<a name="batch_CreateComputeEnvironment_cli_2_topic"></a>

次のコード例では、`create-compute-environment` を使用する方法を示しています。

**AWS CLI**  
**オンデマンドインスタンスを使用してマネージドコンピューティング環境を作成する方法**  
この例では、オンデマンドで起動される特定の C4 インスタンスタイプを持つマネージドコンピューティング環境を作成します。コンピューティング環境は C4OnDemand と呼ばれます。  
コマンド:  

```
aws batch create-compute-environment --cli-input-json file://<path_to_json_file>/C4OnDemand.json
```
JSON ファイル形式:  

```
{
  "computeEnvironmentName": "C4OnDemand",
  "type": "MANAGED",
  "state": "ENABLED",
  "computeResources": {
    "type": "EC2",
    "minvCpus": 0,
    "maxvCpus": 128,
    "desiredvCpus": 48,
    "instanceTypes": [
      "c4.large",
      "c4.xlarge",
      "c4.2xlarge",
      "c4.4xlarge",
      "c4.8xlarge"
    ],
    "subnets": [
      "subnet-220c0e0a",
      "subnet-1a95556d",
      "subnet-978f6dce"
    ],
    "securityGroupIds": [
      "sg-cf5093b2"
    ],
    "ec2KeyPair": "id_rsa",
    "instanceRole": "ecsInstanceRole",
    "tags": {
      "Name": "Batch Instance - C4OnDemand"
    }
  },
  "serviceRole": "arn:aws:iam::012345678910:role/AWSBatchServiceRole"
}
```
出力:  

```
{
    "computeEnvironmentName": "C4OnDemand",
    "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/C4OnDemand"
}
```
**スポットインスタンスでマネージドコンピューティング環境を作成する方法**  
この例では、スポット入札価格がインスタンスタイプのオンデマンド価格の 20% 以下のときに起動される M4 インスタンスタイプを使用してマネージドコンピューティング環境を作成します。コンピューティング環境は M4Spot と呼ばれます。  
コマンド:  

```
aws batch create-compute-environment --cli-input-json file://<path_to_json_file>/M4Spot.json
```
JSON ファイル形式:  

```
{
  "computeEnvironmentName": "M4Spot",
  "type": "MANAGED",
  "state": "ENABLED",
  "computeResources": {
    "type": "SPOT",
    "spotIamFleetRole": "arn:aws:iam::012345678910:role/aws-ec2-spot-fleet-role",
    "minvCpus": 0,
    "maxvCpus": 128,
    "desiredvCpus": 4,
    "instanceTypes": [
      "m4"
    ],
    "bidPercentage": 20,
    "subnets": [
      "subnet-220c0e0a",
      "subnet-1a95556d",
      "subnet-978f6dce"
    ],
    "securityGroupIds": [
      "sg-cf5093b2"
    ],
    "ec2KeyPair": "id_rsa",
    "instanceRole": "ecsInstanceRole",
    "tags": {
      "Name": "Batch Instance - M4Spot"
    }
  },
  "serviceRole": "arn:aws:iam::012345678910:role/AWSBatchServiceRole"
}
```
出力:  

```
{
    "computeEnvironmentName": "M4Spot",
    "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/M4Spot"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateComputeEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/create-compute-environment.html)」を参照してください。

### `create-job-queue`
<a name="batch_CreateJobQueue_cli_2_topic"></a>

次のコード例では、`create-job-queue` を使用する方法を示しています。

**AWS CLI**  
**単一のコンピューティング環境で優先度の低いジョブキューを作成する方法**  
この例では、M4Spot コンピューティング環境を使用する LowPriority というジョブキューを作成します。  
コマンド:  

```
aws batch create-job-queue --cli-input-json file://<path_to_json_file>/LowPriority.json
```
JSON ファイル形式:  

```
{
  "jobQueueName": "LowPriority",
  "state": "ENABLED",
  "priority": 10,
  "computeEnvironmentOrder": [
    {
      "order": 1,
      "computeEnvironment": "M4Spot"
    }
  ]
}
```
出力:  

```
{
    "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/LowPriority",
    "jobQueueName": "LowPriority"
}
```
**2 つのコンピューティング環境で優先度の高いジョブキューを作成する方法**  
この例では、1 の順序で C4OnDemand コンピューティング環境を使用し、2 の順序で M4Spot コンピューティング環境を使用する、HighPriority というジョブキューを作成します。スケジューラは、まず C4OnDemand コンピューティング環境にジョブを配置しようとします。  
コマンド:  

```
aws batch create-job-queue --cli-input-json file://<path_to_json_file>/HighPriority.json
```
JSON ファイル形式:  

```
{
  "jobQueueName": "HighPriority",
  "state": "ENABLED",
  "priority": 1,
  "computeEnvironmentOrder": [
    {
      "order": 1,
      "computeEnvironment": "C4OnDemand"
    },
    {
      "order": 2,
      "computeEnvironment": "M4Spot"
    }
  ]
}
```
出力:  

```
{
    "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/HighPriority",
    "jobQueueName": "HighPriority"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateJobQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/create-job-queue.html)」を参照してください。

### `delete-compute-environment`
<a name="batch_DeleteComputeEnvironment_cli_2_topic"></a>

次のコード例では、`delete-compute-environment` を使用する方法を示しています。

**AWS CLI**  
**コンピューティング環境を削除する方法**  
この例では、P2OnDemand コンピューティング環境を削除します。  
コマンド:  

```
aws batch delete-compute-environment --compute-environment P2OnDemand
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteComputeEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/delete-compute-environment.html)」を参照してください。

### `delete-job-queue`
<a name="batch_DeleteJobQueue_cli_2_topic"></a>

次のコード例では、`delete-job-queue` を使用する方法を示しています。

**AWS CLI**  
**ジョブキューを削除する方法**  
この例では、GPGPU ジョブキューを削除します。  
コマンド:  

```
aws batch delete-job-queue --job-queue GPGPU
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteJobQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/delete-job-queue.html)」を参照してください。

### `deregister-job-definition`
<a name="batch_DeregisterJobDefinition_cli_2_topic"></a>

次のコード例では、`deregister-job-definition` を使用する方法を示しています。

**AWS CLI**  
**タスク定義を登録解除する方法**  
この例では、 sleep10 というジョブ定義を登録解除します。  
コマンド:  

```
aws batch deregister-job-definition --job-definition sleep10
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterJobDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/deregister-job-definition.html)」を参照してください。

### `describe-compute-environments`
<a name="batch_DescribeComputeEnvironments_cli_2_topic"></a>

次のコード例では、`describe-compute-environments` を使用する方法を示しています。

**AWS CLI**  
**コンピューティング環境を記述する方法**  
この例では、P2OnDemand コンピューティング環境を記述します。  
コマンド:  

```
aws batch describe-compute-environments --compute-environments P2OnDemand
```
出力:  

```
{
    "computeEnvironments": [
        {
            "status": "VALID",
            "serviceRole": "arn:aws:iam::012345678910:role/AWSBatchServiceRole",
            "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/P2OnDemand",
            "computeResources": {
                "subnets": [
                    "subnet-220c0e0a",
                    "subnet-1a95556d",
                    "subnet-978f6dce"
                ],
                "tags": {
                    "Name": "Batch Instance - P2OnDemand"
                },
                "desiredvCpus": 48,
                "minvCpus": 0,
                "instanceTypes": [
                    "p2"
                ],
                "securityGroupIds": [
                    "sg-cf5093b2"
                ],
                "instanceRole": "ecsInstanceRole",
                "maxvCpus": 128,
                "type": "EC2",
                "ec2KeyPair": "id_rsa"
            },
            "statusReason": "ComputeEnvironment Healthy",
            "ecsClusterArn": "arn:aws:ecs:us-east-1:012345678910:cluster/P2OnDemand_Batch_2c06f29d-d1fe-3a49-879d-42394c86effc",
            "state": "ENABLED",
            "computeEnvironmentName": "P2OnDemand",
            "type": "MANAGED"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeComputeEnvironments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/describe-compute-environments.html)」を参照してください。**

### `describe-job-definitions`
<a name="batch_DescribeJobDefinitions_cli_2_topic"></a>

次のコード例では、`describe-job-definitions` を使用する方法を示しています。

**AWS CLI**  
**アクティブなジョブ定義を記述する方法**  
この例では、アクティブなすべてのジョブ定義について記述します。  
コマンド:  

```
aws batch describe-job-definitions --status ACTIVE
```
出力:  

```
{
    "jobDefinitions": [
        {
            "status": "ACTIVE",
            "jobDefinitionArn": "arn:aws:batch:us-east-1:012345678910:job-definition/sleep60:1",
            "containerProperties": {
                "mountPoints": [],
                "parameters": {},
                "image": "busybox",
                "environment": {},
                "vcpus": 1,
                "command": [
                    "sleep",
                    "60"
                ],
                "volumes": [],
                "memory": 128,
                "ulimits": []
            },
            "type": "container",
            "jobDefinitionName": "sleep60",
            "revision": 1
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJobDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/describe-job-definitions.html)」を参照してください。

### `describe-job-queues`
<a name="batch_DescribeJobQueues_cli_2_topic"></a>

次のコード例では、`describe-job-queues` を使用する方法を示しています。

**AWS CLI**  
**ジョブキューを記述する方法**  
この例では、HighPriority ジョブキューを記述します。  
コマンド:  

```
aws batch describe-job-queues --job-queues HighPriority
```
出力:  

```
{
    "jobQueues": [
        {
            "status": "VALID",
            "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/HighPriority",
            "computeEnvironmentOrder": [
                {
                    "computeEnvironment": "arn:aws:batch:us-east-1:012345678910:compute-environment/C4OnDemand",
                    "order": 1
                }
            ],
            "statusReason": "JobQueue Healthy",
            "priority": 1,
            "state": "ENABLED",
            "jobQueueName": "HighPriority"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJobQueues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/describe-job-queues.html)」を参照してください。

### `describe-jobs`
<a name="batch_DescribeJobs_cli_2_topic"></a>

次のコード例では、`describe-jobs` を使用する方法を示しています。

**AWS CLI**  
**ジョブについて記述する方法**  
次の `describe-jobs` の例では、指定されたジョブ ID を持つジョブを記述します。  

```
aws batch describe-jobs \
    --jobs bcf0b186-a532-4122-842e-2ccab8d54efb
```
出力:  

```
{
    "jobs": [
        {
            "status": "SUBMITTED",
            "container": {
                "mountPoints": [],
                "image": "busybox",
                "environment": [],
                "vcpus": 1,
                "command": [
                    "sleep",
                    "60"
                ],
                "volumes": [],
                "memory": 128,
                "ulimits": []
            },
            "parameters": {},
            "jobDefinition": "arn:aws:batch:us-east-1:012345678910:job-definition/sleep60:1",
            "jobQueue": "arn:aws:batch:us-east-1:012345678910:job-queue/HighPriority",
            "jobId": "bcf0b186-a532-4122-842e-2ccab8d54efb",
            "dependsOn": [],
            "jobName": "example",
            "createdAt": 1480483387803
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/describe-jobs.html)」を参照してください。

### `list-jobs`
<a name="batch_ListJobs_cli_2_topic"></a>

次のコード例では、`list-jobs` を使用する方法を示しています。

**AWS CLI**  
**実行中のジョブを一覧表示する方法**  
この例では、HighPriority ジョブキューで実行中のジョブを一覧表示します。  
コマンド:  

```
aws batch list-jobs --job-queue HighPriority
```
出力:  

```
{
    "jobSummaryList": [
        {
            "jobName": "example",
            "jobId": "e66ff5fd-a1ff-4640-b1a2-0b0a142f49bb"
        }
    ]
}
```
**送信されたジョブを一覧表示する方法**  
この例では、SUBMITTED ジョブステータスの HighPriority ジョブキュー内のジョブを一覧表示します。  
コマンド:  

```
aws batch list-jobs --job-queue HighPriority --job-status SUBMITTED
```
出力:  

```
{
    "jobSummaryList": [
        {
            "jobName": "example",
            "jobId": "68f0c163-fbd4-44e6-9fd1-25b14a434786"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/list-jobs.html)」を参照してください。

### `register-job-definition`
<a name="batch_RegisterJobDefinition_cli_2_topic"></a>

次のコード例では、`register-job-definition` を使用する方法を示しています。

**AWS CLI**  
**ジョブ定義を登録する方法**  
この例では、単純なコンテナジョブのジョブ定義を登録します。  
コマンド:  

```
aws batch register-job-definition --job-definition-name sleep30 --type container --container-properties '{ "image": "busybox", "vcpus": 1, "memory": 128, "command": [ "sleep", "30"]}'
```
出力:  

```
{
    "jobDefinitionArn": "arn:aws:batch:us-east-1:012345678910:job-definition/sleep30:1",
    "jobDefinitionName": "sleep30",
    "revision": 1
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterJobDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/register-job-definition.html)」を参照してください。

### `submit-job`
<a name="batch_SubmitJob_cli_2_topic"></a>

次のコード例では、`submit-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブを送信する方法**  
この例では、example という単純なコンテナジョブを HighPriority ジョブキューに送信します。  
コマンド:  

```
aws batch submit-job --job-name example --job-queue HighPriority  --job-definition sleep60
```
出力:  

```
{
    "jobName": "example",
    "jobId": "876da822-4198-45f2-a252-6cea32512ea8"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SubmitJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/submit-job.html)」を参照してください。

### `terminate-job`
<a name="batch_TerminateJob_cli_2_topic"></a>

次のコード例では、`terminate-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブを終了する方法**  
この例では、指定されたジョブ ID でジョブを終了します。  
コマンド:  

```
aws batch terminate-job --job-id 61e743ed-35e4-48da-b2de-5c8333821c84 --reason "Terminating job."
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TerminateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/terminate-job.html)」を参照してください。

### `update-compute-environment`
<a name="batch_UpdateComputeEnvironment_cli_2_topic"></a>

次のコード例では、`update-compute-environment` を使用する方法を示しています。

**AWS CLI**  
**コンピューティング環境を作成する方法**  
この例では、削除できるように P2OnDemand コンピューティング環境を無効にします。  
コマンド:  

```
aws batch update-compute-environment --compute-environment P2OnDemand --state DISABLED
```
出力:  

```
{
    "computeEnvironmentName": "P2OnDemand",
    "computeEnvironmentArn": "arn:aws:batch:us-east-1:012345678910:compute-environment/P2OnDemand"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateComputeEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/update-compute-environment.html)」を参照してください。

### `update-job-queue`
<a name="batch_UpdateJobQueue_cli_2_topic"></a>

次のコード例では、`update-job-queue` を使用する方法を示しています。

**AWS CLI**  
**ジョブキューを作成する方法**  
この例では、削除できるようにジョブキューを無効にします。  
コマンド:  

```
aws batch update-job-queue --job-queue GPGPU --state DISABLED
```
出力:  

```
{
    "jobQueueArn": "arn:aws:batch:us-east-1:012345678910:job-queue/GPGPU",
    "jobQueueName": "GPGPU"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateJobQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/batch/update-job-queue.html)」を参照してください。

# AWS Budgets を使用した の例 AWS CLI
<a name="cli_2_budgets_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Budgets。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-budget`
<a name="budgets_CreateBudget_cli_2_topic"></a>

次のコード例では、`create-budget` を使用する方法を示しています。

**AWS CLI**  
**使用量の予算を作成する方法**  
次の `create-budget` コマンドは、コストと使用状況の予算を作成します。  

```
aws budgets create-budget \
    --account-id 111122223333 \
    --budget file://budget.json \
    --notifications-with-subscribers file://notifications-with-subscribers.json
```
`budget.json` の内容:  

```
{
    "BudgetLimit": {
        "Amount": "100",
        "Unit": "USD"
    },
    "BudgetName": "Example Tag Budget",
    "BudgetType": "COST",
    "CostFilters": {
        "TagKeyValue": [
            "user:Key$value1",
            "user:Key$value2"
        ]
    },
    "CostTypes": {
        "IncludeCredit": true,
        "IncludeDiscount": true,
        "IncludeOtherSubscription": true,
        "IncludeRecurring": true,
        "IncludeRefund": true,
        "IncludeSubscription": true,
        "IncludeSupport": true,
        "IncludeTax": true,
        "IncludeUpfront": true,
        "UseBlended": false
    },
    "TimePeriod": {
        "Start": 1477958399,
        "End": 3706473600
    },
    "TimeUnit": "MONTHLY"
}
```
`notifications-with-subscribers.json` の内容:  

```
[
    {
        "Notification": {
            "ComparisonOperator": "GREATER_THAN",
            "NotificationType": "ACTUAL",
            "Threshold": 80,
            "ThresholdType": "PERCENTAGE"
        },
        "Subscribers": [
            {
                "Address": "example@example.com",
                "SubscriptionType": "EMAIL"
            }
        ]
    }
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBudget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/create-budget.html)」を参照してください。

### `create-notification`
<a name="budgets_CreateNotification_cli_2_topic"></a>

次のコード例では、`create-notification` を使用する方法を示しています。

**AWS CLI**  
**指定されたコストと使用量の予算の通知を作成する方法**  
この例では、指定されたコストと使用量の予算の通知を作成します。  
コマンド:  

```
aws budgets create-notification --account-id 111122223333 --budget-name "Example Budget" --notification NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=80,ThresholdType=PERCENTAGE --subscriber SubscriptionType=EMAIL,Address=example@example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/create-notification.html)」を参照してください。

### `create-subscriber`
<a name="budgets_CreateSubscriber_cli_2_topic"></a>

次のコード例では、`create-subscriber` を使用する方法を示しています。

**AWS CLI**  
**コストと使用量の予算に関連付けられた通知のサブスクライバーを作成する方法**  
この例では、指定された通知のサブスクライバーを作成します。  
コマンド:  

```
aws budgets create-subscriber --account-id 111122223333 --budget-name "Example Budget" --notification NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=80,ThresholdType=PERCENTAGE --subscriber SubscriptionType=EMAIL,Address=example@example.com
```
+  API の詳細については、「*AWS CLI コマンドレットリファレンス*」の「[CreateSubscriber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/create-subscriber.html)」を参照してください。

### `delete-budget`
<a name="budgets_DeleteBudget_cli_2_topic"></a>

次のコード例では、`delete-budget` を使用する方法を示しています。

**AWS CLI**  
**使用量の予算を削除する方法**  
この例では、指定されたコストと使用量の予算を削除します。  
コマンド:  

```
aws budgets delete-budget --account-id 111122223333 --budget-name "Example Budget"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBudget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/delete-budget.html)」を参照してください。

### `delete-notification`
<a name="budgets_DeleteNotification_cli_2_topic"></a>

次のコード例では、`delete-notification` を使用する方法を示しています。

**AWS CLI**  
**予算から通知を削除する方法**  
この例では、指定された予算から指定された通知を削除します。  
コマンド:  

```
aws budgets delete-notification --account-id 111122223333 --budget-name "Example Budget" --notification NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=80,ThresholdType=PERCENTAGE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/delete-notification.html)」を参照してください。

### `delete-subscriber`
<a name="budgets_DeleteSubscriber_cli_2_topic"></a>

次のコード例では、`delete-subscriber` を使用する方法を示しています。

**AWS CLI**  
**通知からサブスクライバーを削除する方法**  
この例では、指定された通知から指定されたサブスクライバーを削除します。  
コマンド:  

```
aws budgets delete-subscriber --account-id 111122223333 --budget-name "Example Budget" --notification NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=80,ThresholdType=PERCENTAGE --subscriber SubscriptionType=EMAIL,Address=example@example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubscriber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/delete-subscriber.html)」を参照してください。

### `describe-budget`
<a name="budgets_DescribeBudget_cli_2_topic"></a>

次のコード例では、`describe-budget` を使用する方法を示しています。

**AWS CLI**  
**アカウントに関連付けられた予算を取得する方法**  
この例では、指定されたコストと使用量の予算を取得します。  
コマンド:  

```
aws budgets describe-budget --account-id 111122223333 --budget-name "Example Budget"
```
出力:  

```
{
   "Budget": {
       "CalculatedSpend": {
           "ForecastedSpend": {
               "Amount": "2641.54800000000022919266484677791595458984375",
               "Unit": "USD"
           },
           "ActualSpend": {
               "Amount": "604.4560000000000172803993336856365203857421875",
               "Unit": "USD"
           }
       },
       "BudgetType": "COST",
       "BudgetLimit": {
           "Amount": "100",
           "Unit": "USD"
       },
       "BudgetName": "Example Budget",
       "CostTypes": {
           "IncludeOtherSubscription": true,
           "IncludeUpfront": true,
           "IncludeRefund": true,
           "UseBlended": false,
           "IncludeDiscount": true,
           "UseAmortized": false,
           "IncludeTax": true,
           "IncludeCredit": true,
           "IncludeSupport": true,
           "IncludeRecurring": true,
           "IncludeSubscription": true
       },
       "TimeUnit": "MONTHLY",
       "TimePeriod": {
           "Start": 1477958399.0,
           "End": 3706473600.0
       },
       "CostFilters": {
           "AZ": [
               "us-east-1"
           ]
       }
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBudget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/describe-budget.html)」を参照してください。

### `describe-budgets`
<a name="budgets_DescribeBudgets_cli_2_topic"></a>

次のコード例では、`describe-budgets` を使用する方法を示しています。

**AWS CLI**  
**アカウントに関連付けられた予算を取得する方法**  
この例では、アカウントのコストと使用状況の予算を取得します。  
コマンド:  

```
aws budgets describe-budgets --account-id 111122223333 --max-results 20
```
出力:  

```
{
   "Budgets": [
       {
           "CalculatedSpend": {
               "ForecastedSpend": {
                   "Amount": "2641.54800000000022919266484677791595458984375",
                   "Unit": "USD"
               },
               "ActualSpend": {
                   "Amount": "604.4560000000000172803993336856365203857421875",
                   "Unit": "USD"
               }
           },
           "BudgetType": "COST",
           "BudgetLimit": {
               "Amount": "100",
               "Unit": "USD"
           },
           "BudgetName": "Example Budget",
           "CostTypes": {
               "IncludeOtherSubscription": true,
               "IncludeUpfront": true,
               "IncludeRefund": true,
               "UseBlended": false,
               "IncludeDiscount": true,
               "UseAmortized": false,
               "IncludeTax": true,
               "IncludeCredit": true,
               "IncludeSupport": true,
               "IncludeRecurring": true,
               "IncludeSubscription": true
           },
           "TimeUnit": "MONTHLY",
           "TimePeriod": {
               "Start": 1477958399.0,
               "End": 3706473600.0
           },
           "CostFilters": {
               "AZ": [
                   "us-east-1"
               ]
           }
       }
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBudgets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/describe-budgets.html)」を参照してください。

### `describe-notifications-for-budget`
<a name="budgets_DescribeNotificationsForBudget_cli_2_topic"></a>

次のコード例では、`describe-notifications-for-budget` を使用する方法を示しています。

**AWS CLI**  
**予算の通知を取得する方法**  
この例では、コストと使用状況の予算の通知を取得します。  
コマンド:  

```
aws budgets describe-notifications-for-budget --account-id 111122223333 --budget-name "Example Budget" --max-results 5
```
出力:  

```
{
   "Notifications": [
       {
           "Threshold": 80.0,
           "ComparisonOperator": "GREATER_THAN",
           "NotificationType": "ACTUAL"
       }
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNotificationsForBudget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/describe-notifications-for-budget.html)」を参照してください。

### `describe-subscribers-for-notification`
<a name="budgets_DescribeSubscribersForNotification_cli_2_topic"></a>

次のコード例では、`describe-subscribers-for-notification` を使用する方法を示しています。

**AWS CLI**  
**予算の通知のサブスクライバーを取得する方法**  
この例では、コストと使用状況の予算通知のサブスクライバーを取得します。  
コマンド:  

```
aws budgets describe-subscribers-for-notification --account-id 111122223333 --budget-name "Example Budget" --notification NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=80,ThresholdType=PERCENTAGE --max-results 5
```
出力:  

```
{
   "Subscribers": [
       {
           "SubscriptionType": "EMAIL",
           "Address": "example2@example.com"
       },
       {
           "SubscriptionType": "EMAIL",
           "Address": "example@example.com"
       }
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSubscribersForNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/describe-subscribers-for-notification.html)」を参照してください。

### `update-budget`
<a name="budgets_UpdateBudget_cli_2_topic"></a>

次のコード例では、`update-budget` を使用する方法を示しています。

**AWS CLI**  
**コストと使用状況の予算の予算を置き換える方法**  
この例では、コストと使用量の予算を新しい予算に置き換えます。  
コマンド:  

```
aws budgets update-budget --account-id 111122223333 --new-budget file://new-budget.json
```
new-budget.json:  

```
{
    "BudgetLimit": {
       "Amount": "100",
       "Unit": "USD"
    },
    "BudgetName": "Example Budget",
    "BudgetType": "COST",
    "CostFilters": {
       "AZ" : [ "us-east-1" ]
    },
    "CostTypes": {
       "IncludeCredit": false,
       "IncludeDiscount": true,
       "IncludeOtherSubscription": true,
       "IncludeRecurring": true,
       "IncludeRefund": true,
       "IncludeSubscription": true,
       "IncludeSupport": true,
       "IncludeTax": true,
       "IncludeUpfront": true,
       "UseBlended": false,
       "UseAmortized": true
    },
    "TimePeriod": {
       "Start": 1477958399,
       "End": 3706473600
    },
    "TimeUnit": "MONTHLY"
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateBudget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/update-budget.html)」を参照してください。

### `update-notification`
<a name="budgets_UpdateNotification_cli_2_topic"></a>

次のコード例では、`update-notification` を使用する方法を示しています。

**AWS CLI**  
**コストと使用量の予算の通知を置き換える方法**  
この例では、コストと使用状況の予算の 80% の通知を 90% の通知に置き換えます。  
コマンド:  

```
aws budgets update-notification --account-id 111122223333 --budget-name "Example Budget" --old-notification  NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=80,ThresholdType=PERCENTAGE --new-notification  NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=90,ThresholdType=PERCENTAGE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/update-notification.html)」を参照してください。

### `update-subscriber`
<a name="budgets_UpdateSubscriber_cli_2_topic"></a>

次のコード例では、`update-subscriber` を使用する方法を示しています。

**AWS CLI**  
**コストと使用状況の予算のサブスクライバーを置き換える方法**  
この例では、サブスクライバーをコストと使用量の予算に置き換えます。  
コマンド:  

```
aws budgets update-subscriber --account-id 111122223333 --budget-name "Example Budget" --notification NotificationType=ACTUAL,ComparisonOperator=GREATER_THAN,Threshold=80,ThresholdType=PERCENTAGE --old-subscriber SubscriptionType=EMAIL,Address=example@example.com --new-subscriber SubscriptionType=EMAIL,Address=example2@example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSubscriber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/budgets/update-subscriber.html)」を参照してください。

# を使用した Amazon Chime の例 AWS CLI
<a name="cli_2_chime_code_examples"></a>

次のコード例は、Amazon Chime AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-phone-number-with-user`
<a name="chime_AssociatePhoneNumberWithUser_cli_2_topic"></a>

次のコード例では、`associate-phone-number-with-user` を使用する方法を示しています。

**AWS CLI**  
**電話番号をユーザーに関連付ける方法**  
次の `associate-phone-number-with-user` の例では、指定された電話番号をユーザーに関連付けます。  

```
aws chime associate-phone-number-with-user \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --user-id 1ab2345c-67de-8901-f23g-45h678901j2k \
    --e164-phone-number "+12065550100"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーの電話番号の管理](https://docs.aws.amazon.com/chime/latest/ag/user-phone.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AssociatePhoneNumberWithUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/associate-phone-number-with-user.html)」を参照してください。

### `associate-signin-delegate-groups-with-account`
<a name="chime_AssociateSigninDelegateGroupsWithAccount_cli_2_topic"></a>

次のコード例は、`associate-signin-delegate-groups-with-account` を使用する方法を示しています。

**AWS CLI**  
**サインイン代理グループを関連付ける方法**  
次の `associate-signin-delegate-groups-with-account` の例では、指定されたサインイン代理グループを、指定された Amazon Chime アカウントと関連付けます。  

```
aws chime associate-signin-delegate-groups-with-account \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --signin-delegate-groups GroupName=my_users
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーアクセスと許可の管理](https://docs.aws.amazon.com/chime/latest/ag/manage-access.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateSigninDelegateGroupsWithAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/associate-signin-delegate-groups-with-account.html)」を参照してください。

### `batch-create-room-membership`
<a name="chime_BatchCreateRoomMembership_cli_2_topic"></a>

次のコード例では、`batch-create-room-membership` を使用する方法を示しています。

**AWS CLI**  
**複数のルームメンバーシップを作成する方法**  
次の `batch-create-room-membership` の例では、チャットルームのメンバーとしてチャットルームに複数のユーザーを追加します。また、管理者ロールとメンバーロールをユーザーに割り当てます。  

```
aws chime batch-create-room-membership \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j \
    --membership-item-list "MemberId=1ab2345c-67de-8901-f23g-45h678901j2k,Role=Administrator" "MemberId=2ab2345c-67de-8901-f23g-45h678901j2k,Role=Member"
```
出力:  

```
{
    "ResponseMetadata": {
        "RequestId": "169ba401-d886-475f-8b3f-e01eac6fadfb",
        "HTTPStatusCode": 201,
        "HTTPHeaders": {
            "x-amzn-requestid": "169ba401-d886-475f-8b3f-e01eac6fadfb",
            "content-type": "application/json",
            "content-length": "13",
            "date": "Mon, 02 Dec 2019 22:46:58 GMT",
            "connection": "keep-alive"
        },
        "RetryAttempts": 0
    },
    "Errors": []
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「AWS CLI * コマンドリファレンス*」の「[BatchCreateRoomMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/batch-create-room-membership.html)」を参照してください。

### `batch-delete-phone-number`
<a name="chime_BatchDeletePhoneNumber_cli_2_topic"></a>

次のコード例では、`batch-delete-phone-number` を使用する方法を示しています。

**AWS CLI**  
**複数の電話番号を削除する方法**  
次の `batch-delete-phone-number` の例では、指定された電話番号をすべて削除します。  

```
aws chime batch-delete-phone-number \
    --phone-number-ids "%2B12065550100" "%2B12065550101"
```
このコマンドでは何も出力されません。出力:  

```
{
    "PhoneNumberErrors": []
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDeletePhoneNumber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/batch-delete-phone-number.html)」を参照してください。

### `batch-suspend-user`
<a name="chime_BatchSuspendUser_cli_2_topic"></a>

次のコード例では、`batch-suspend-user` を使用する方法を示しています。

**AWS CLI**  
**複数のユーザーを一時利用停止する方法**  
次の `batch-suspend-user` の例では、指定された Amazon Chime アカウントから、一覧に記載されたユーザーを一時利用停止します。  

```
aws chime batch-suspend-user \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --user-id-list "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE" "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE" "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE"
```
出力:  

```
{
    "UserErrors": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchSuspendUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/batch-suspend-user.html)」を参照してください。

### `batch-unsuspend-user`
<a name="chime_BatchUnsuspendUser_cli_2_topic"></a>

次のコード例では、`batch-unsuspend-user` を使用する方法を示しています。

**AWS CLI**  
**複数のユーザーの一時利用停止を解除する方法**  
次の `batch-unsuspend-user` の例では、指定された Amazon Chime アカウントで、一覧に記載されたユーザーの一時利用停止を解除します。  

```
aws chime batch-unsuspend-user \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --user-id-list "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE" "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE" "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE"
```
出力:  

```
{
    "UserErrors": []
}
```
+  API の詳細については、「AWS CLI * コマンドリファレンス*」の「[BatchUnsuspendUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/batch-unsuspend-user.html)」を参照してください。

### `batch-update-phone-number`
<a name="chime_BatchUpdatePhoneNumber_cli_2_topic"></a>

次のコード例では、`batch-update-phone-number` を使用する方法を示しています。

**AWS CLI**  
**複数の電話番号製品タイプを同時に更新する方法**  
次の `batch-update-phone-number` の例では、指定されたすべての電話番号の製品タイプを更新します。  

```
aws chime batch-update-phone-number \
    --update-phone-number-request-items PhoneNumberId=%2B12065550100,ProductType=BusinessCalling PhoneNumberId=%2B12065550101,ProductType=BusinessCalling
```
出力:  

```
{
    "PhoneNumberErrors": []
}
```
**複数の電話番号呼び出し名を同時に更新する方法**  
次の `batch-update-phone-number` の例では、指定されたすべての電話番号の呼び出し名を更新します。  

```
aws chime batch-update-phone-number \
    --update-phone-number-request-items PhoneNumberId=%2B14013143874,CallingName=phonenumber1 PhoneNumberId=%2B14013144061,CallingName=phonenumber2
```
出力:  

```
{
    "PhoneNumberErrors": []
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchUpdatePhoneNumber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/batch-update-phone-number.html)」を参照してください。

### `batch-update-user`
<a name="chime_BatchUpdateUser_cli_2_topic"></a>

次のコード例では、`batch-update-user` を使用する方法を示しています。

**AWS CLI**  
**1 つのコマンドで複数のユーザーを更新する方法**  
次の `batch-update-user` の例では、指定された Amazon Chime アカウント内のリストされた各ユーザーの `LicenseType` を更新します。  

```
aws chime batch-update-user \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
    --update-user-request-items "UserId=a1b2c3d4-5678-90ab-cdef-22222EXAMPLE,LicenseType=Basic" "UserId=a1b2c3d4-5678-90ab-cdef-33333EXAMPLE,LicenseType=Basic"
```
出力:  

```
{
    "UserErrors": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchUpdateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/batch-update-user.html)」を参照してください。

### `create-account`
<a name="chime_CreateAccount_cli_2_topic"></a>

次のコード例では、`create-account` を使用する方法を示しています。

**AWS CLI**  
**アカウントを作成する方法**  
次の の`create-account`例では、管理者のアカウントの下に Amazon Chime AWS アカウントを作成します。  

```
aws chime create-account \
    --name MyChimeAccount
```
出力:  

```
{
    "Account": {
        "AwsAccountId": "111122223333",
        "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "Name": "MyChimeAccount",
        "AccountType": "Team",
        "CreatedTimestamp": "2019-01-04T17:11:22.003Z",
        "DefaultLicense": "Pro",
        "SupportedLicenses": [
            "Basic",
            "Pro"
        ],
        "SigninDelegateGroups": [
            {
                "GroupName": "myGroup"
            },
        ]
    }
}
```
詳細については、「*Amazon Chime 管理者ガイド*」の「[はじめに](https://docs.aws.amazon.com/chime/latest/ag/getting-started.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/create-account.html)」を参照してください。**

### `create-bot`
<a name="chime_CreateBot_cli_2_topic"></a>

次のコード例では、`create-bot` を使用する方法を示しています。

**AWS CLI**  
**Amazon Chime ボットを作成する方法**  
次の `create-bot` の例では、指定された Amazon Chime Enterprise アカウントのボットを作成します。  

```
aws chime create-bot \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --display-name "myBot" \
    --domain "example.com"
```
出力:  

```
{
    "Bot": {
        "BotId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "UserId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "DisplayName": "myBot (Bot)",
        "BotType": "ChatBot",
        "Disabled": false,
        "CreatedTimestamp": "2019-09-09T18:05:56.749Z",
        "UpdatedTimestamp": "2019-09-09T18:05:56.749Z",
        "BotEmail": "myBot-chimebot@example.com",
        "SecurityToken": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
    }
}
```
詳細については、「*Amazon Chime デベロッパーガイド*」の「[Amazon Chime でチャットボットを連携する](https://docs.aws.amazon.com/chime/latest/dg/integrate-bots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/create-bot.html)」を参照してください。

### `create-phone-number-order`
<a name="chime_CreatePhoneNumberOrder_cli_2_topic"></a>

次のコード例では、`create-phone-number-order` を使用する方法を示しています。

**AWS CLI**  
**電話番号の順序を作成する方法**  
次の `create-phone-number-order` の例では、指定された電話番号の順序を作成します。  

```
aws chime create-phone-number-order \
    --product-type VoiceConnector \
    --e164-phone-numbers "+12065550100" "+12065550101" "+12065550102"
```
出力:  

```
{
    "PhoneNumberOrder": {
        "PhoneNumberOrderId": "abc12345-de67-89f0-123g-h45i678j9012",
        "ProductType": "VoiceConnector",
        "Status": "Processing",
        "OrderedPhoneNumbers": [
            {
                "E164PhoneNumber": "+12065550100",
                "Status": "Processing"
            },
            {
               "E164PhoneNumber": "+12065550101",
               "Status": "Processing"
            },
            {
              "E164PhoneNumber": "+12065550102",
              "Status": "Processing"
            }
        ],
        "CreatedTimestamp": "2019-08-09T21:35:21.427Z",
        "UpdatedTimestamp": "2019-08-09T21:35:22.408Z"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePhoneNumberOrder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/create-phone-number-order.html)」を参照してください。

### `create-room-membership`
<a name="chime_CreateRoomMembership_cli_2_topic"></a>

次のコード例は、`create-room-membership` を使用する方法を示しています。

**AWS CLI**  
**ルームメンバーシップを作成する方法**  
次の `create-room-membership` の例では、指定されたユーザーをチャットルームメンバーとしてチャットルームに追加します。  

```
aws chime create-room-membership \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j \
    --member-id 1ab2345c-67de-8901-f23g-45h678901j2k
```
出力:  

```
{
    "RoomMembership": {
        "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
        "Member": {
            "MemberId": "1ab2345c-67de-8901-f23g-45h678901j2k",
            "MemberType": "User",
            "Email": "janed@example.com",
            "FullName": "Jane Doe",
            "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45"
        },
        "Role": "Member",
        "InvitedBy": "arn:aws:iam::111122223333:user/alejandro",
        "UpdatedTimestamp": "2019-12-02T22:36:41.969Z"
    }
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoomMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/create-room-membership.html)」を参照してください。

### `create-room`
<a name="chime_CreateRoom_cli_2_topic"></a>

次のコード例では、`create-room` を使用する方法を示しています。

**AWS CLI**  
**チャットルームを作成するには**  
次の `create-room` の例では、指定された Amazon Chime アカウントのチャットルームを作成します。  

```
aws chime create-room \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --name chatRoom
```
出力:  

```
{
    "Room": {
        "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
        "Name": "chatRoom",
        "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45",
        "CreatedBy": "arn:aws:iam::111122223333:user/alejandro",
        "CreatedTimestamp": "2019-12-02T22:29:31.549Z",
        "UpdatedTimestamp": "2019-12-02T22:29:31.549Z"
    }
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/create-room.html)」を参照してください。

### `create-user`
<a name="chime_CreateUser_cli_2_topic"></a>

次のコード例では、`create-user` を使用する方法を示しています。

**AWS CLI**  
**共有デバイスのユーザープロファイルを作成する方法**  
次の `create-user` の例では、指定された E メールアドレスの共有デバイスプロファイルを作成します。  

```
aws chime create-user \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --email roomdevice@example.com \
    --user-type SharedDevice
```
出力:  

```
{
    "User": {
        "UserId": "1ab2345c-67de-8901-f23g-45h678901j2k",
        "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45",
        "PrimaryEmail": "roomdevice@example.com",
        "DisplayName": "Room Device",
        "LicenseType": "Pro",
        "UserType": "SharedDevice",
        "UserRegistrationStatus": "Registered",
        "RegisteredOn": "2020-01-15T22:38:09.806Z",
        "AlexaForBusinessMetadata": {
            "IsAlexaForBusinessEnabled": false
        }
    }
}
```
ユーザー作成の詳細については、「*Amazon Chime 管理ガイド*」の「[セットアップの準備](https://docs.aws.amazon.com/chime/latest/ag/prepare-setup.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/create-user.html)」を参照してください。

### `delete-account`
<a name="chime_DeleteAccount_cli_2_topic"></a>

次のコード例は、`delete-account` を使用する方法を示しています。

**AWS CLI**  
**アカウントを削除する方法**  
次の `delete-account` の例では、指定されたアカウントを削除します。  

```
aws chime delete-account --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[アカウントの削除](https://docs.aws.amazon.com/chime/latest/ag/enterprise-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/delete-account.html)」を参照してください。

### `delete-phone-number`
<a name="chime_DeletePhoneNumber_cli_2_topic"></a>

次のコード例では、`delete-phone-number` を使用する方法を示しています。

**AWS CLI**  
**電話番号を削除する方法**  
次の `delete-phone-number` の例では、指定された電話番号を削除キューに移動します。  

```
aws chime delete-phone-number \
    --phone-number-id "+12065550100"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePhoneNumber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/delete-phone-number.html)」を参照してください。

### `delete-room-membership`
<a name="chime_DeleteRoomMembership_cli_2_topic"></a>

次のコード例は、`delete-room-membership` を使用する方法を示しています。

**AWS CLI**  
**チャットルームのメンバーとしてユーザーを削除する方法**  
次の `delete-room-membership` の例では、指定されたチャットルームから指定されたメンバーを削除します。  

```
aws chime delete-room-membership \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j \
    --member-id 1ab2345c-67de-8901-f23g-45h678901j2k
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoomMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/delete-room-membership.html)」を参照してください。

### `delete-room`
<a name="chime_DeleteRoom_cli_2_topic"></a>

次のコード例では、`delete-room` を使用する方法を示しています。

**AWS CLI**  
**チャットルームを削除する方法**  
次の `delete-room` の例では、指定されたチャットルームを削除し、チャットルームメンバーシップを削除します。  

```
aws chime delete-room \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/delete-room.html)」を参照してください。

### `disassociate-phone-number-from-user`
<a name="chime_DisassociatePhoneNumberFromUser_cli_2_topic"></a>

次のコード例は、`disassociate-phone-number-from-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーから電話番号の関連付けを解除する方法**  
次の `disassociate-phone-number-from-user` の例では、指定されたユーザーから電話番号の関連付けを解除します。  

```
aws chime disassociate-phone-number-from-user \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --user-id 1ab2345c-67de-8901-f23g-45h678901j2k
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーの電話番号の管理](https://docs.aws.amazon.com/chime/latest/ag/user-phone.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociatePhoneNumberFromUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/disassociate-phone-number-from-user.html)」を参照してください。

### `disassociate-signin-delegate-groups-from-account`
<a name="chime_DisassociateSigninDelegateGroupsFromAccount_cli_2_topic"></a>

次のコード例は、`disassociate-signin-delegate-groups-from-account` を使用する方法を示しています。

**AWS CLI**  
**サインイン代理グループの関連付けを解除する方法**  
次の `disassociate-signin-delegate-groups-from-account` の例では、指定されたサインイン代理グループと指定された Amazon Chime アカウントとの関連付けを解除します。  

```
aws chime disassociate-signin-delegate-groups-from-account \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --group-names "my_users"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーアクセスと許可の管理](https://docs.aws.amazon.com/chime/latest/ag/manage-access.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateSigninDelegateGroupsFromAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/disassociate-signin-delegate-groups-from-account.html)」を参照してください。

### `get-account-settings`
<a name="chime_GetAccountSettings_cli_2_topic"></a>

次のコード例では、`get-account-settings` を使用する方法を示しています。

**AWS CLI**  
**アカウントの設定を取得する方法**  
次の `get-account-settings` の例では、指定されたアカウントのアカウント設定を取得します。  

```
aws chime get-account-settings --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "AccountSettings": {
        "DisableRemoteControl": false,
        "EnableDialOut": false
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[Amazon Chime アカウントの管理](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccountSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-account-settings.html)」を参照してください。

### `get-account`
<a name="chime_GetAccount_cli_2_topic"></a>

次のコード例では、`get-account` を使用する方法を示しています。

**AWS CLI**  
**アカウントの詳細を取得する方法**  
次の `get-account` の例では、指定された Amazon Chime アカウントに関する詳細を取得します。  

```
aws chime get-account \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "Account": {
        "AwsAccountId": "111122223333",
        "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "Name": "EnterpriseDirectory",
        "AccountType": "EnterpriseDirectory",
        "CreatedTimestamp": "2018-12-20T18:38:02.181Z",
        "DefaultLicense": "Pro",
        "SupportedLicenses": [
            "Basic",
            "Pro"
        ],
        "SigninDelegateGroups": [
            {
                "GroupName": "myGroup"
            },
        ]
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[Amazon Chime アカウントの管理](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-account.html)」を参照してください。

### `get-bot`
<a name="chime_GetBot_cli_2_topic"></a>

次のコード例では、`get-bot` を使用する方法を示しています。

**AWS CLI**  
**ボットの詳細を取得する方法**  
次の `get-bot` の例では、指定されたポリシーの詳細を表示します。  

```
aws chime get-bot \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --bot-id 123abcd4-5ef6-789g-0h12-34j56789012k
```
出力:  

```
{
    "Bot": {
        "BotId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "UserId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "DisplayName": "myBot (Bot)",
        "BotType": "ChatBot",
        "Disabled": false,
        "CreatedTimestamp": "2019-09-09T18:05:56.749Z",
        "UpdatedTimestamp": "2019-09-09T18:05:56.749Z",
        "BotEmail": "myBot-chimebot@example.com",
        "SecurityToken": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
    }
}
```
詳細については、「[Amazon Chime デベロッパーガイド](https://docs.aws.amazon.com/chime/latest/dg/update-bots.html)」の「*チャットボットの更新*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-bot.html)」を参照してください。

### `get-global-settings`
<a name="chime_GetGlobalSettings_cli_2_topic"></a>

次のコード例では、`get-global-settings` を使用する方法を示しています。

**AWS CLI**  
**グローバル設定を取得する方法**  
次の の`get-global-settings`例では、管理者の AWS アカウントに関連付けられた Amazon Chime Business Calling と Amazon Chime Voice Connectors の通話詳細レコードを保存するために使用される S3 バケット名を取得します。  

```
aws chime get-global-settings
```
出力:  

```
{
    "BusinessCalling": {
        "CdrBucket": "s3bucket"
    },
    "VoiceConnector": {
        "CdrBucket": "s3bucket"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[グローバル設定の管理](https://docs.aws.amazon.com/chime/latest/ag/manage-global.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGlobalSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-global-settings.html)」を参照してください。

### `get-phone-number-order`
<a name="chime_GetPhoneNumberOrder_cli_2_topic"></a>

次のコード例では、`get-phone-number-order` を使用する方法を示しています。

**AWS CLI**  
**電話番号の注文の詳細を取得する方法**  
次の `get-phone-number-order` の例では、指定された電話番号の注文の詳細を表示します。  

```
aws chime get-phone-number-order \
    --phone-number-order-id abc12345-de67-89f0-123g-h45i678j9012
```
出力:  

```
{
    "PhoneNumberOrder": {
        "PhoneNumberOrderId": "abc12345-de67-89f0-123g-h45i678j9012",
        "ProductType": "VoiceConnector",
        "Status": "Partial",
        "OrderedPhoneNumbers": [
            {
              "E164PhoneNumber": "+12065550100",
              "Status": "Acquired"
            },
            {
                "E164PhoneNumber": "+12065550101",
                "Status": "Acquired"
            },
            {
                "E164PhoneNumber": "+12065550102",
                "Status": "Failed"
            }
        ],
        "CreatedTimestamp": "2019-08-09T21:35:21.427Z",
        "UpdatedTimestamp": "2019-08-09T21:35:31.926Z"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPhoneNumberOrder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-phone-number-order.html)」を参照してください。

### `get-phone-number-settings`
<a name="chime_GetPhoneNumberSettings_cli_2_topic"></a>

次のコード例では、`get-phone-number-settings` を使用する方法を示しています。

**AWS CLI**  
**アウトバウンド呼び出し名を取得する方法**  
次の の`get-phone-number-settings`例では、呼び出し元のユーザーの AWS アカウントのデフォルトのアウトバウンド呼び出し名を取得します。  

```
aws chime get-phone-number-settings
```
このコマンドでは何も出力されません。出力:  

```
{
    "CallingName": "myName",
    "CallingNameUpdatedTimestamp": "2019-10-28T18:56:42.911Z"
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPhoneNumberSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-phone-number-settings.html)」を参照してください。

### `get-phone-number`
<a name="chime_GetPhoneNumber_cli_2_topic"></a>

次のコード例では、`get-phone-number` を使用する方法を示しています。

**AWS CLI**  
**電話番号の詳細を取得する方法**  
次の `get-phone-number` の例では、指定された電話番号の詳細を表示します。  

```
aws chime get-phone-number \
    --phone-number-id +12065550100
```
出力:  

```
{
    "PhoneNumber": {
        "PhoneNumberId": "%2B12065550100",
        "E164PhoneNumber": "+12065550100",
        "Type": "Local",
        "ProductType": "VoiceConnector",
        "Status": "Unassigned",
        "Capabilities": {
            "InboundCall": true,
            "OutboundCall": true,
            "InboundSMS": true,
            "OutboundSMS": true,
            "InboundMMS": true,
            "OutboundMMS": true
        },
       "Associations": [
            {
                "Value": "abcdef1ghij2klmno3pqr4",
                "Name": "VoiceConnectorId",
                "AssociatedTimestamp": "2019-10-28T18:40:37.453Z"
            }
        ],
        "CallingNameStatus": "UpdateInProgress",
        "CreatedTimestamp": "2019-08-09T21:35:21.445Z",
        "UpdatedTimestamp": "2019-08-09T21:35:31.745Z"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPhoneNumber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-phone-number.html)」を参照してください。

### `get-room`
<a name="chime_GetRoom_cli_2_topic"></a>

次のコード例は、`get-room` を使用する方法を示しています。

**AWS CLI**  
**チャットルームの詳細を取得する方法**  
次の `get-room` の例では、指定されたチャットルームの詳細を表示します。  

```
aws chime get-room \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j
```
出力:  

```
{
    "Room": {
        "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
        "Name": "chatRoom",
        "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45",
        "CreatedBy": "arn:aws:iam::111122223333:user/alejandro",
        "CreatedTimestamp": "2019-12-02T22:29:31.549Z",
        "UpdatedTimestamp": "2019-12-02T22:29:31.549Z"
    }
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-room.html)」を参照してください。

### `get-user-settings`
<a name="chime_GetUserSettings_cli_2_topic"></a>

次のコード例では、`get-user-settings` を使用する方法を示しています。

**AWS CLI**  
**ユーザー設定を取得する方法**  
次の `get-user-settings` の例では、指定されたユーザー設定を表示します。  

```
aws chime get-user-settings \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --user-id 1ab2345c-67de-8901-f23g-45h678901j2k
```
出力:  

```
{
    "UserSettings": {
        "Telephony": {
            "InboundCalling": true,
            "OutboundCalling": true,
            "SMS": true
        }
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーの電話番号の管理](https://docs.aws.amazon.com/chime/latest/ag/user-phone.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUserSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-user-settings.html)」を参照してください。

### `get-user`
<a name="chime_GetUser_cli_2_topic"></a>

次のコード例では、`get-user` を使用する方法を示しています。

**AWS CLI**  
**ポリシーの詳細を取得する方法**  
次の `get-user` の例では、指定されたユーザーの詳細を取得します。  

```
aws chime get-user \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --user-id a1b2c3d4-5678-90ab-cdef-22222EXAMPLE
```
出力:  

```
{
    "User": {
        "UserId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
        "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "PrimaryEmail": "marthar@example.com",
        "DisplayName": "Martha Rivera",
        "LicenseType": "Pro",
        "UserRegistrationStatus": "Registered",
        "RegisteredOn": "2018-12-20T18:45:25.231Z",
        "InvitedOn": "2018-12-20T18:45:25.231Z",
        "AlexaForBusinessMetadata": {
            "IsAlexaForBusinessEnabled": False,
            "AlexaForBusinessRoomArn": "null"
        },
        "PersonalPIN": "XXXXXXXXXX"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーの管理](https://docs.aws.amazon.com/chime/latest/ag/manage-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/get-user.html)」を参照してください。

### `invite-users`
<a name="chime_InviteUsers_cli_2_topic"></a>

次のコード例は、`invite-users` を使用する方法を示しています。

**AWS CLI**  
**Amazon Chime に参加するようにユーザーを招待する方法**  
次の `invite-users` の例では、指定された Amazon Chime アカウントにユーザーを招待する E メールを送信します。  

```
aws chime invite-users \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --user-email-list "alejandror@example.com" "janed@example.com"
```
出力:  

```
{
    "Invites": [
        {
            "InviteId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
            "Status": "Pending",
            "EmailAddress": "alejandror@example.com",
            "EmailStatus": "Sent"
        }
        {
            "InviteId": "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
            "Status": "Pending",
            "EmailAddress": "janed@example.com",
            "EmailStatus": "Sent"
        }
    ]
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーの招待と一時利用停止](https://docs.aws.amazon.com/chime/latest/ag/manage-access.html#invite-users-team)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InviteUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/invite-users.html)」を参照してください。

### `list-accounts`
<a name="chime_ListAccounts_cli_2_topic"></a>

次のコード例では、`list-accounts` を使用する方法を示しています。

**AWS CLI**  
**アカウントの一覧を取得する方法**  
次の の`list-accounts`例では、管理者のアカウントの Amazon Chime AWS アカウントのリストを取得します。  

```
aws chime list-accounts
```
出力:  

```
{
    "Accounts": [
        {
            "AwsAccountId": "111122223333",
            "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "Name": "First Chime Account",
            "AccountType": "EnterpriseDirectory",
            "CreatedTimestamp": "2018-12-20T18:38:02.181Z",
            "DefaultLicense": "Pro",
            "SupportedLicenses": [
                "Basic",
                "Pro"
            ],
            "SigninDelegateGroups": [
                {
                    "GroupName": "myGroup"
                },
            ]
        },
        {
            "AwsAccountId": "111122223333",
            "AccountId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
            "Name": "Second Chime Account",
            "AccountType": "Team",
            "CreatedTimestamp": "2018-09-04T21:44:22.292Z",
            "DefaultLicense": "Pro",
            "SupportedLicenses": [
                "Basic",
                "Pro"
            ],
            "SigninDelegateGroups": [
                {
                    "GroupName": "myGroup"
                },
            ]
        }
    ]
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[Amazon Chime アカウントの管理](https://docs.aws.amazon.com/chime/latest/ag/manage-chime-account.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-accounts.html)」を参照してください。**

### `list-bots`
<a name="chime_ListBots_cli_2_topic"></a>

次のコード例では、`list-bots` を使用する方法を示しています。

**AWS CLI**  
**ボットの一覧を取得する方法**  
次の `list-bots` の例では、指定された Amazon Chime Enterprise アカウントに関連付けられているボットを一覧表示します。  

```
aws chime list-bots \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45
```
出力:  

```
{
    "Bot": {
        "BotId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "UserId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "DisplayName": "myBot (Bot)",
        "BotType": "ChatBot",
        "Disabled": false,
        "CreatedTimestamp": "2019-09-09T18:05:56.749Z",
        "UpdatedTimestamp": "2019-09-09T18:05:56.749Z",
        "BotEmail": "myBot-chimebot@example.com",
        "SecurityToken": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
    }
}
```
詳細については、「*Amazon Chime デベロッパーガイド*」の「[Amazon Chime でチャットボットを使用する](https://docs.aws.amazon.com/chime/latest/dg/use-bots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-bots.html)」を参照してください。

### `list-phone-number-orders`
<a name="chime_ListPhoneNumberOrders_cli_2_topic"></a>

次のコード例では、`list-phone-number-orders` を使用する方法を示しています。

**AWS CLI**  
**電話番号の注文を一覧表示する方法**  
次の `list-phone-number-orders` の例では、Amazon Chime 管理者のアカウントに関連付けられた電話番号の注文を一覧表示します。  

```
aws chime list-phone-number-orders
```
出力:  

```
{
    "PhoneNumberOrders": [
        {
            "PhoneNumberOrderId": "abc12345-de67-89f0-123g-h45i678j9012",
            "ProductType": "VoiceConnector",
            "Status": "Partial",
            "OrderedPhoneNumbers": [
                {
                    "E164PhoneNumber": "+12065550100",
                    "Status": "Acquired"
                },
                {
                    "E164PhoneNumber": "+12065550101",
                    "Status": "Acquired"
                },
                {
                    "E164PhoneNumber": "+12065550102",
                    "Status": "Failed"
                }
            ],
            "CreatedTimestamp": "2019-08-09T21:35:21.427Z",
            "UpdatedTimestamp": "2019-08-09T21:35:31.926Z"
        }
        {
            "PhoneNumberOrderId": "cba54321-ed76-09f5-321g-h54i876j2109",
            "ProductType": "BusinessCalling",
            "Status": "Partial",
            "OrderedPhoneNumbers": [
                {
                    "E164PhoneNumber": "+12065550103",
                    "Status": "Acquired"
                },
                {
                    "E164PhoneNumber": "+12065550104",
                    "Status": "Acquired"
                },
                {
                    "E164PhoneNumber": "+12065550105",
                    "Status": "Failed"
                }
            ],
            "CreatedTimestamp": "2019-08-09T21:35:21.427Z",
            "UpdatedTimestamp": "2019-08-09T21:35:31.926Z"
        }
    ]
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPhoneNumberOrders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-phone-number-orders.html)」を参照してください。

### `list-phone-numbers`
<a name="chime_ListPhoneNumbers_cli_2_topic"></a>

次のコード例では、`list-phone-numbers` を使用する方法を示しています。

**AWS CLI**  
**Amazon Chime アカウントの電話番号を一覧表示する方法**  
次の `list-phone-numbers` の例では、Amazon Chime アカウントに関連付けられた電話番号を一覧表示します。  

```
aws chime list-phone-numbers
```
このコマンドでは何も出力されません。出力:  

```
{
    "PhoneNumbers": [
        {
            "PhoneNumberId": "%2B12065550100",
            "E164PhoneNumber": "+12065550100",
            "Type": "Local",
            "ProductType": "VoiceConnector",
            "Status": "Assigned",
            "Capabilities": {
                "InboundCall": true,
                "OutboundCall": true,
                "InboundSMS": true,
                "OutboundSMS": true,
                "InboundMMS": true,
                "OutboundMMS": true
            },
            "Associations": [
                {
                    "Value": "abcdef1ghij2klmno3pqr4",
                    "Name": "VoiceConnectorId",
                    "AssociatedTimestamp": "2019-10-28T18:40:37.453Z"
                }
            ],
            "CallingNameStatus": "UpdateInProgress",
            "CreatedTimestamp": "2019-08-12T22:10:20.521Z",
            "UpdatedTimestamp": "2019-10-28T18:42:07.964Z"
        },
        {
            "PhoneNumberId": "%2B12065550101",
            "E164PhoneNumber": "+12065550101",
            "Type": "Local",
            "ProductType": "VoiceConnector",
            "Status": "Assigned",
            "Capabilities": {
                "InboundCall": true,
                "OutboundCall": true,
                "InboundSMS": true,
                "OutboundSMS": true,
                "InboundMMS": true,
                "OutboundMMS": true
            },
            "Associations": [
                {
                    "Value": "abcdef1ghij2klmno3pqr4",
                    "Name": "VoiceConnectorId",
                    "AssociatedTimestamp": "2019-10-28T18:40:37.511Z"
                }
            ],
            "CallingNameStatus": "UpdateInProgress",
            "CreatedTimestamp": "2019-08-12T22:10:20.521Z",
            "UpdatedTimestamp": "2019-10-28T18:42:07.960Z"
        }
    ]
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPhoneNumbers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-phone-numbers.html)」を参照してください。

### `list-room-memberships`
<a name="chime_ListRoomMemberships_cli_2_topic"></a>

次のコード例は、`list-room-memberships` を使用する方法を示しています。

**AWS CLI**  
**ルームメンバーシップを一覧表示する方法**  
次の `list-room-memberships` の例では、指定されたチャットルームのメンバーシップの詳細を一覧表示します。  

```
aws chime list-room-memberships \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j
```
出力:  

```
{
    "RoomMemberships": [
        {
            "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
            "Member": {
                "MemberId": "2ab2345c-67de-8901-f23g-45h678901j2k",
                "MemberType": "User",
                "Email": "zhangw@example.com",
                "FullName": "Zhang Wei",
                "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45"
            },
            "Role": "Member",
            "InvitedBy": "arn:aws:iam::111122223333:user/alejandro",
            "UpdatedTimestamp": "2019-12-02T22:46:58.532Z"
        },
        {
            "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
            "Member": {
                "MemberId": "1ab2345c-67de-8901-f23g-45h678901j2k",
                "MemberType": "User",
                "Email": "janed@example.com",
                "FullName": "Jane Doe",
                "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45"
            },
            "Role": "Administrator",
            "InvitedBy": "arn:aws:iam::111122223333:user/alejandro",
            "UpdatedTimestamp": "2019-12-02T22:46:58.532Z"
        }
    ]
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoomMemberships](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-room-memberships.html)」を参照してください。

### `list-rooms`
<a name="chime_ListRooms_cli_2_topic"></a>

次のコード例では、`list-rooms` を使用する方法を示しています。

**AWS CLI**  
**チャットルームを一覧表示する方法**  
次の `list-rooms` の例では、指定されたアカウントのチャットルームを一覧表示します。一覧は、指定されたメンバーが属するチャットルームにのみフィルタリングされます。  

```
aws chime list-rooms \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --member-id 1ab2345c-67de-8901-f23g-45h678901j2k
```
出力:  

```
{
    "Room": {
        "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
        "Name": "teamRoom",
        "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45",
        "CreatedBy": "arn:aws:iam::111122223333:user/alejandro",
        "CreatedTimestamp": "2019-12-02T22:29:31.549Z",
        "UpdatedTimestamp": "2019-12-02T22:33:19.310Z"
    }
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRooms](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-rooms.html)」を参照してください。

### `list-users`
<a name="chime_ListUsers_cli_2_topic"></a>

次のコード例では、`list-users` を使用する方法を示しています。

**AWS CLI**  
**アカウントのユーザーを一覧表示する方法**  
次の `list-users` の例では、指定された Amazon Chime アカウントのユーザーを一覧表示します。  

```
aws chime list-users --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "Users": [
        {
            "UserId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
            "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "PrimaryEmail": "mariag@example.com",
            "DisplayName": "Maria Garcia",
            "LicenseType": "Pro",
            "UserType": "PrivateUser",
            "UserRegistrationStatus": "Registered",
            "RegisteredOn": "2018-12-20T18:45:25.231Z"
            "AlexaForBusinessMetadata": {
                "IsAlexaForBusinessEnabled": false
            }
        },
        {
            "UserId": "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
            "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "PrimaryEmail": "richardr@example.com",
            "DisplayName": "Richard Roe",
            "LicenseType": "Pro",
            "UserType": "PrivateUser",
            "UserRegistrationStatus": "Registered",
            "RegisteredOn": "2018-12-20T18:45:45.415Z"
            "AlexaForBusinessMetadata": {
                "IsAlexaForBusinessEnabled": false
            }
        },
        {
            "UserId": "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
            "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "PrimaryEmail": "saanvis@example.com",
            "DisplayName": "Saanvi Sarkar",
            "LicenseType": "Basic",
            "UserType": "PrivateUser",
            "UserRegistrationStatus": "Registered",
            "RegisteredOn": "2018-12-20T18:46:57.747Z"
            "AlexaForBusinessMetadata": {
                "IsAlexaForBusinessEnabled": false
            }
        },
        {
            "UserId": "a1b2c3d4-5678-90ab-cdef-55555EXAMPLE",
            "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "PrimaryEmail": "wxiulan@example.com",
            "DisplayName": "Wang Xiulan",
            "LicenseType": "Basic",
            "UserType": "PrivateUser",
            "UserRegistrationStatus": "Registered",
            "RegisteredOn": "2018-12-20T18:47:15.390Z"
            "AlexaForBusinessMetadata": {
                "IsAlexaForBusinessEnabled": false
            }
        }
    ]
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーの管理](https://docs.aws.amazon.com/chime/latest/ag/manage-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/list-users.html)」を参照してください。

### `logout-user`
<a name="chime_LogoutUser_cli_2_topic"></a>

次のコード例は、`logout-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーをログアウトさせる方法**  
次の `logout-user` の例では、指定されたユーザーをログアウトさせます。  

```
aws chime logout-user \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --user-id a1b2c3d4-5678-90ab-cdef-22222EXAMPLE
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[LogoutUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/logout-user.html)」を参照してください。

### `regenerate-security-token`
<a name="chime_RegenerateSecurityToken_cli_2_topic"></a>

次のコード例は、`regenerate-security-token` を使用する方法を示しています。

**AWS CLI**  
**セキュリティトークンを再生成する方法**  
次の `regenerate-security-token` の例では、指定されたボットのセキュリティトークンを再生成します。  

```
aws chime regenerate-security-token \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --bot-id 123abcd4-5ef6-789g-0h12-34j56789012k
```
出力:  

```
{
    "Bot": {
        "BotId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "UserId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "DisplayName": "myBot (Bot)",
        "BotType": "ChatBot",
        "Disabled": false,
        "CreatedTimestamp": "2019-09-09T18:05:56.749Z",
        "UpdatedTimestamp": "2019-09-09T18:05:56.749Z",
        "BotEmail": "myBot-chimebot@example.com",
        "SecurityToken": "je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY"
    }
}
```
詳細については、「*Amazon Chime デベロッパーガイド*」の「[認証チャットボットのリクエスト](https://docs.aws.amazon.com/chime/latest/dg/auth-bots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegenerateSecurityToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/regenerate-security-token.html)」を参照してください。

### `reset-personal-pin`
<a name="chime_ResetPersonalPin_cli_2_topic"></a>

次のコード例では、`reset-personal-pin` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの個人用会議 PIN をリセットする方法**  
次の `reset-personal-pin` の例では、指定されたユーザーの個人用会議 PIN をリセットします。  

```
aws chime reset-personal-pin \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
    --user-id a1b2c3d4-5678-90ab-cdef-22222EXAMPLE
```
出力:  

```
{
    "User": {
        "UserId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
        "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "PrimaryEmail": "mateo@example.com",
        "DisplayName": "Mateo Jackson",
        "LicenseType": "Pro",
        "UserType": "PrivateUser",
        "UserRegistrationStatus": "Registered",
        "RegisteredOn": "2018-12-20T18:45:25.231Z",
        "AlexaForBusinessMetadata": {
            "IsAlexaForBusinessEnabled": False,
            "AlexaForBusinessRoomArn": "null"
        },
        "PersonalPIN": "XXXXXXXXXX"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[個人用会議 PIN の変更](https://docs.aws.amazon.com/chime/latest/ag/change-PINs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetPersonalPin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/reset-personal-pin.html)」を参照してください。

### `restore-phone-number`
<a name="chime_RestorePhoneNumber_cli_2_topic"></a>

次のコード例では、`restore-phone-number` を使用する方法を示しています。

**AWS CLI**  
**電話番号を復元する方法**  
次の `restore-phone-number` の例では、指定された電話番号を削除キューから復元します。  

```
aws chime restore-phone-number \
    --phone-number-id "+12065550100"
```
出力:  

```
{
    "PhoneNumber": {
        "PhoneNumberId": "%2B12065550100",
        "E164PhoneNumber": "+12065550100",
        "Type": "Local",
        "ProductType": "BusinessCalling",
        "Status": "Unassigned",
        "Capabilities": {
            "InboundCall": true,
            "OutboundCall": true,
            "InboundSMS": true,
            "OutboundSMS": true,
            "InboundMMS": true,
            "OutboundMMS": true
        },
        "Associations": [],
        "CreatedTimestamp": "2019-08-09T21:35:21.445Z",
        "UpdatedTimestamp": "2019-08-12T22:06:36.355Z"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestorePhoneNumber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/restore-phone-number.html)」を参照してください。

### `search-available-phone-numbers`
<a name="chime_SearchAvailablePhoneNumbers_cli_2_topic"></a>

次のコード例では、`search-available-phone-numbers` を使用する方法を示しています。

**AWS CLI**  
**使用可能な電話番号を検索する方法**  
次の `search-available-phone-numbers` の例では、使用可能な電話番号を市外局番で検索します。  

```
aws chime search-available-phone-numbers \
    --area-code "206"
```
出力:  

```
{
    "E164PhoneNumbers": [
        "+12065550100",
        "+12065550101",
        "+12065550102",
        "+12065550103",
        "+12065550104",
        "+12065550105",
        "+12065550106",
        "+12065550107",
        "+12065550108",
        "+12065550109",
    ]
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、 「*AWS CLI コマンドリファレンス*」の「[SearchAvailablePhoneNumbers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/search-available-phone-numbers.html)」を参照してください。

### `update-account-settings`
<a name="chime_UpdateAccountSettings_cli_2_topic"></a>

次のコード例では、`update-account-settings` を使用する方法を示しています。

**AWS CLI**  
**アカウントの設定を更新する方法**  
次の `update-account-settings` の例では、指定された Amazon Chime アカウントの共有画面のリモートコントロールを無効にします。  

```
aws chime update-account-settings \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --account-settings DisableRemoteControl=true
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccountSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-account-settings.html)」を参照してください。

### `update-account`
<a name="chime_UpdateAccount_cli_2_topic"></a>

次のコード例では、`update-account` を使用する方法を示しています。

**AWS CLI**  
**アカウントを更新する方法**  
次の `update-account` の例では、指定されたアカウント名を更新します。  

```
aws chime update-account \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --name MyAccountName
```
出力:  

```
{
    "Account": {
        "AwsAccountId": "111122223333",
        "AccountId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "Name": "MyAccountName",
        "AccountType": "Team",
        "CreatedTimestamp": "2018-09-04T21:44:22.292Z",
        "DefaultLicense": "Pro",
        "SupportedLicenses": [
            "Basic",
            "Pro"
        ],
        "SigninDelegateGroups": [
            {
                "GroupName": "myGroup"
            },
        ]
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[アカウントの名前変更](https://docs.aws.amazon.com/chime/latest/ag/rename-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-account.html)」を参照してください。

### `update-bot`
<a name="chime_UpdateBot_cli_2_topic"></a>

次のコード例では、`update-bot` を使用する方法を示しています。

**AWS CLI**  
**ボットを更新する方法**  
次の `update-bot` の例では、指定されたボットのステータスを更新して、実行を停止します。  

```
aws chime update-bot \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --bot-id 123abcd4-5ef6-789g-0h12-34j56789012k \
    --disabled
```
出力:  

```
{
    "Bot": {
        "BotId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "UserId": "123abcd4-5ef6-789g-0h12-34j56789012k",
        "DisplayName": "myBot (Bot)",
        "BotType": "ChatBot",
        "Disabled": true,
        "CreatedTimestamp": "2019-09-09T18:05:56.749Z",
        "UpdatedTimestamp": "2019-09-09T18:05:56.749Z",
        "BotEmail": "myBot-chimebot@example.com",
        "SecurityToken": "je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY"
    }
}
```
詳細については、「[Amazon Chime デベロッパーガイド](https://docs.aws.amazon.com/chime/latest/dg/update-bots.html)」の「*チャットボットの更新*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateBot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-bot.html)」を参照してください。

### `update-global-settings`
<a name="chime_UpdateGlobalSettings_cli_2_topic"></a>

次のコード例では、`update-global-settings` を使用する方法を示しています。

**AWS CLI**  
**グローバル設定を更新する方法**  
次の の`update-global-settings`例では、管理者の AWS アカウントに関連付けられた Amazon Chime Business Calling と Amazon Chime Voice Connector の通話詳細レコードを保存するために使用される S3 バケットを更新します。  

```
aws chime update-global-settings \
    --business-calling CdrBucket="s3bucket" \
    --voice-connector CdrBucket="s3bucket"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[グローバル設定の管理](https://docs.aws.amazon.com/chime/latest/ag/manage-global.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGlobalSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-global-settings.html)」を参照してください。

### `update-phone-number-settings`
<a name="chime_UpdatePhoneNumberSettings_cli_2_topic"></a>

次のコード例では、`update-phone-number-settings` を使用する方法を示しています。

**AWS CLI**  
**アウトバウンド呼び出し名を更新する方法**  
次の の`update-phone-number-settings`例では、管理者の AWS アカウントのデフォルトのアウトバウンド呼び出し名を更新します。  

```
aws chime update-phone-number-settings \
    --calling-name "myName"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePhoneNumberSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-phone-number-settings.html)」を参照してください。

### `update-phone-number`
<a name="chime_UpdatePhoneNumber_cli_2_topic"></a>

次のコード例では、`update-phone-number` を使用する方法を示しています。

**AWS CLI**  
**例 1: 電話番号の製品タイプを更新する方法**  
次の `update-phone-number` の例では、指定された電話番号の製品タイプを更新します。  

```
aws chime update-phone-number \
    --phone-number-id "+12065550100" \
    --product-type "BusinessCalling"
```
出力:  

```
{
    "PhoneNumber": {
        "PhoneNumberId": "%2B12065550100",
        "E164PhoneNumber": "+12065550100",
        "Type": "Local",
        "ProductType": "BusinessCalling",
        "Status": "Unassigned",
        "Capabilities": {
            "InboundCall": true,
            "OutboundCall": true,
            "InboundSMS": true,
            "OutboundSMS": true,
            "InboundMMS": true,
            "OutboundMMS": true
        },
        "Associations": [],
        "CallingName": "phonenumber1",
        "CreatedTimestamp": "2019-08-09T21:35:21.445Z",
        "UpdatedTimestamp": "2019-08-12T21:44:07.591Z"
    }
}
```
**例 2: 電話番号のアウトバウンド呼び出し名を更新する方法**  
次の `update-phone-number` の例では、指定された電話番号のアウトバウンド呼び出し名を更新します。  
aws chime update-phone-number --phone-number-id "\$112065550100" --calling-name "phonenumber2"  
出力:  

```
{
    "PhoneNumber": {
        "PhoneNumberId": "%2B12065550100",
        "E164PhoneNumber": "+12065550100",
        "Type": "Local",
        "ProductType": "BusinessCalling",
        "Status": "Unassigned",
        "Capabilities": {
            "InboundCall": true,
            "OutboundCall": true,
            "InboundSMS": true,
            "OutboundSMS": true,
            "InboundMMS": true,
            "OutboundMMS": true
        },
        "Associations": [],
        "CallingName": "phonenumber2",
        "CreatedTimestamp": "2019-08-09T21:35:21.445Z",
        "UpdatedTimestamp": "2019-08-12T21:44:07.591Z"
    }
}
```
詳細については、「*Amazon Chime 管理ガイド*」の「[電話番号の使用方法](https://docs.aws.amazon.com/chime/latest/ag/phone-numbers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePhoneNumber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-phone-number.html)」を参照してください。

### `update-room-membership`
<a name="chime_UpdateRoomMembership_cli_2_topic"></a>

次のコード例は、`update-room-membership` を使用する方法を示しています。

**AWS CLI**  
**ルームメンバーシップを更新する方法**  
次の `update-room-membership` の例では、指定されたチャットルームメンバーのロールを `Administrator` に変更します。  

```
aws chime update-room-membership \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j \
    --member-id 1ab2345c-67de-8901-f23g-45h678901j2k \
    --role Administrator
```
出力:  

```
{
    "RoomMembership": {
        "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
        "Member": {
            "MemberId": "1ab2345c-67de-8901-f23g-45h678901j2k",
            "MemberType": "User",
            "Email": "sofiamartinez@example.com",
            "FullName": "Sofia Martinez",
            "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45"
        },
        "Role": "Administrator",
        "InvitedBy": "arn:aws:iam::111122223333:user/admin",
        "UpdatedTimestamp": "2019-12-02T22:40:22.931Z"
    }
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoomMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-room-membership.html)」を参照してください。

### `update-room`
<a name="chime_UpdateRoom_cli_2_topic"></a>

次のコード例では、`update-room` を使用する方法を示しています。

**AWS CLI**  
**チャットルームを更新する方法**  
次の `update-room` の例では、指定されたチャットルームの名前を変更します。  

```
aws chime update-room \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --room-id abcd1e2d-3e45-6789-01f2-3g45h67i890j \
    --name teamRoom
```
出力:  

```
{
    "Room": {
        "RoomId": "abcd1e2d-3e45-6789-01f2-3g45h67i890j",
        "Name": "teamRoom",
        "AccountId": "12a3456b-7c89-012d-3456-78901e23fg45",
        "CreatedBy": "arn:aws:iam::111122223333:user/alejandro",
        "CreatedTimestamp": "2019-12-02T22:29:31.549Z",
        "UpdatedTimestamp": "2019-12-02T22:33:19.310Z"
    }
}
```
詳細については、「*Amazon Chime ユーザーガイド*」の「[チャットルームの作成](https://docs.aws.amazon.com/chime/latest/ug/chime-chat-room.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-room.html)」を参照してください。

### `update-user-settings`
<a name="chime_UpdateUserSettings_cli_2_topic"></a>

次のコード例では、`update-user-settings` を使用する方法を示しています。

**AWS CLI**  
**ユーザー設定を更新する方法**  
次の `update-user-settings` の例では、指定されたユーザーがインバウンドコールとアウトバウンドコールを行い、SMS メッセージを送受信できるようにします。  

```
aws chime update-user-settings \
    --account-id 12a3456b-7c89-012d-3456-78901e23fg45 \
    --user-id 1ab2345c-67de-8901-f23g-45h678901j2k \
    --user-settings "Telephony={InboundCalling=true,OutboundCalling=true,SMS=true}"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Chime 管理ガイド*」の「[ユーザーの電話番号の管理](https://docs.aws.amazon.com/chime/latest/ag/user-phone.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-user-settings.html)」を参照してください。

### `update-user`
<a name="chime_UpdateUser_cli_2_topic"></a>

次のコード例では、`update-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの詳細を更新する方法**  
この例では、指定されたユーザーの指定された詳細を更新します。  
コマンド:  

```
aws chime update-user \
    --account-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --user-id a1b2c3d4-5678-90ab-cdef-22222EXAMPLE \
    --license-type "Basic"
```
出力:  

```
{
    "User": {
        "UserId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/chime/update-user.html)」を参照してください。

# を使用した Cloud Control API の例 AWS CLI
<a name="cli_2_cloudcontrol_code_examples"></a>

次のコード例は、Cloud Control API AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-resource`
<a name="cloudcontrol_CreateResource_cli_2_topic"></a>

次の例では、`create-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースを作成する方法**  
次の`create-resource`例では、ResourceExample という名前の AWS::Kinesis::Stream リソースを作成し、保持期間は 168 時間、シャード数は 3 です。  

```
aws cloudcontrol create-resource \
    --type-name AWS::Kinesis::Stream \
    --desired-state "{\"Name\": \"ResourceExample\",\"RetentionPeriodHours\":168, \"ShardCount\":3}"
```
出力:  

```
{
    "ProgressEvent": {
        "EventTime": 1632506656.706,
        "TypeName": "AWS::Kinesis::Stream",
        "OperationStatus": "IN_PROGRESS",
        "Operation": "CREATE",
        "Identifier": "ResourceExample",
        "RequestToken": "20999d87-e304-4725-ad84-832dcbfd7fc5"
    }
}
```
詳細については、「*Cloud Control API ユーザーガイド*」の「[リソースの作成](https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-create.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudcontrol/create-resource.html)」を参照してください。**

### `delete-resource`
<a name="cloudcontrol_DeleteResource_cli_2_topic"></a>

次の例では、`delete-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースを削除する方法**  
次の`delete-resource`例では、識別子 ResourceExample を持つ a AWS::Kinesis::Stream リソースを AWS アカウントから削除します。 ResourceExample   

```
aws cloudcontrol delete-resource \
    --type-name AWS::Kinesis::Stream \
    --identifier ResourceExample
```
出力:  

```
{
    "ProgressEvent": {
        "TypeName": "AWS::Kinesis::Stream",
        "Identifier": "ResourceExample",
        "RequestToken": "e48f26ff-d0f9-4ab8-a878-120db1edf111",
        "Operation": "DELETE",
        "OperationStatus": "IN_PROGRESS",
        "EventTime": 1632950300.14
    }
}
```
詳細については、「*Cloud Control API ユーザーガイド*」の「[リソースの削除](https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudcontrol/delete-resource.html)」を参照してください。

### `get-resource-request-status`
<a name="cloudcontrol_GetResourceRequestStatus_cli_2_topic"></a>

次の例では、`get-resource-request-status` を使用する方法を説明しています。

**AWS CLI**  
**リソースリクエストのステータス情報を取得する方法**  
次の `get-resource-request-status` の例では、指定されたリソースリクエストに関するステータス情報を返します。  

```
aws cloudcontrol get-resource-request-status \
    --request-token "e1a6b86e-46bd-41ac-bfba-001234567890"
```
出力:  

```
{
    "ProgressEvent": {
        "TypeName": "AWS::Kinesis::Stream",
        "Identifier": "Demo",
        "RequestToken": "e1a6b86e-46bd-41ac-bfba-001234567890",
        "Operation": "CREATE",
        "OperationStatus": "FAILED",
        "EventTime": 1632950268.481,
        "StatusMessage": "Resource of type 'AWS::Kinesis::Stream' with identifier 'Demo' already exists.",
        "ErrorCode": "AlreadyExists"
    }
}
```
詳細については、「*Cloud Control API ユーザーガイド*」の「[リソースのオペレーションリクエストの管理](https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-manage-requests.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceRequestStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudcontrol/get-resource-request-status.html)」を参照してください。

### `get-resource`
<a name="cloudcontrol_GetResource_cli_2_topic"></a>

次の例では、`get-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースの現在の状態を取得する方法**  
次の`get-resource`例では、ResourceExample という名前の AWS::Kinesis::Stream リソースの現在の状態を返します。  

```
aws cloudcontrol get-resource \
    --type-name AWS::Kinesis::Stream \
    --identifier ResourceExample
```
出力:  

```
{
    "TypeName": "AWS::Kinesis::Stream",
    "ResourceDescription": {
        "Identifier": "ResourceExample",
        "Properties": "{\"Arn\":\"arn:aws:kinesis:us-west-2:099908667365:stream/ResourceExample\",\"RetentionPeriodHours\":168,\"Name\":\"ResourceExample\",\"ShardCount\":3}"
    }
}
```
詳細については、「*Cloud Control API ユーザーガイド*」の「[リソースの現在の状態の読み込み](https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-read.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudcontrol/get-resource.html)」を参照してください。

### `list-resource-requests`
<a name="cloudcontrol_ListResourceRequests_cli_2_topic"></a>

次の例では、`list-resource-requests` を使用する方法を説明しています。

**AWS CLI**  
**アクティブなリソースオペレーションリクエストを一覧表示する方法**  
次の の`list-resource-requests`例では、 AWS アカウントで失敗した CREATE および UPDATE オペレーションのリソースリクエストを一覧表示します。  

```
aws cloudcontrol list-resource-requests \
    --resource-request-status-filter Operations=CREATE,OperationStatuses=FAILED
```
出力:  

```
{
    "ResourceRequestStatusSummaries": [
        {
            "TypeName": "AWS::Kinesis::Stream",
            "Identifier": "Demo",
            "RequestToken": "e1a6b86e-46bd-41ac-bfba-633abcdfdbd7",
            "Operation": "CREATE",
            "OperationStatus": "FAILED",
            "EventTime": 1632950268.481,
            "StatusMessage": "Resource of type 'AWS::Kinesis::Stream' with identifier 'Demo' already exists.",
            "ErrorCode": "AlreadyExists"
        }
    ]
}
```
詳細については、「*Cloud Control API ユーザーガイド*」の「[リソースのオペレーションリクエストの管理](https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-manage-requests.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudcontrol/list-resource-requests.html)」を参照してください。

### `list-resources`
<a name="cloudcontrol_ListResources_cli_2_topic"></a>

次の例では、`list-resources` を使用する方法を説明しています。

**AWS CLI**  
**特定のタイプのリソースを一覧表示する方法**  
次の の`list-resources`例では、 AWS アカウントにプロビジョニングされた AWS::Kinesis::Stream リソースを一覧表示します。  

```
aws cloudcontrol list-resources \
    --type-name AWS::Kinesis::Stream
```
出力:  

```
{
    "TypeName": "AWS::Kinesis::Stream",
    "ResourceDescriptions": [
        {
            "Identifier": "MyKinesisStream",
            "Properties": "{\"Name\":\"MyKinesisStream\"}"
        },
        {
            "Identifier": "AnotherStream",
            "Properties": "{\"Name\":\"AnotherStream\"}"
        }
    ]
}
```
詳細については、「*Cloud Control API ユーザーガイド*」の「[リソースの検索](https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudcontrol/list-resources.html)」を参照してください。

### `update-resource`
<a name="cloudcontrol_UpdateResource_cli_2_topic"></a>

次の例では、`update-resource` を使用する方法を説明しています。

**AWS CLI**  
**既存のリソースのプロパティを更新する方法**  
次の`update-resource`例では、LogGroup という名前の an AWS::Logs::ExampleLogGroupリソースの保持ポリシーを 90 日に更新します。  

```
aws cloudcontrol update-resource \
    --type-name AWS::Logs::LogGroup \
    --identifier ExampleLogGroup \
    --patch-document "[{\"op\":\"replace\",\"path\":\"/RetentionInDays\",\"value\":90}]"
```
出力:  

```
{
    "ProgressEvent": {
        "EventTime": "2021-08-09T18:17:15.219Z",
        "TypeName": "AWS::Logs::LogGroup",
        "OperationStatus": "IN_PROGRESS",
        "Operation": "UPDATE",
        "Identifier": "ExampleLogGroup",
        "RequestToken": "5f40c577-3534-4b20-9599-0b0123456789"
    }
}
```
詳細については、「*Cloud Control API ユーザーガイド*」の「[リソースの更新](https://docs.aws.amazon.com/cloudcontrolapi/latest/userguide/resource-operations-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudcontrol/update-resource.html)」を参照してください。

# AWS Cloud Map を使用した の例 AWS CLI
<a name="cli_2_servicediscovery_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Cloud Map。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-http-namespace`
<a name="servicediscovery_CreateHttpNamespace_cli_2_topic"></a>

次のコード例は、`create-http-namespace` を使用する方法を示しています。

**AWS CLI**  
**HTTP 名前空間を作成するには**  
次の `create-http-namespace` の例では、HTTP 名前空間 `example.com` を作成します。  

```
aws servicediscovery create-http-namespace \
    --name example.com \
    --creator-request-id example-request-id
```
出力:  

```
{
    "OperationId": "gv4g5meo7ndmeh4fqskygvk23d2fijwa-k9302yzd"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。詳細については、「[get-operation](https://docs.aws.amazon.com/cli/latest/reference/servicediscovery/get-operation.html)」を参照してください。  
名前空間の作成の詳細については、[AWS 「 Cloud Map Developer Guide」の「Creating an Cloud Map namespace to group application services](https://docs.aws.amazon.com/cloud-map/latest/dg/creating-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateHttpNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/create-http-namespace.html)」を参照してください。

### `create-private-dns-namespace`
<a name="servicediscovery_CreatePrivateDnsNamespace_cli_2_topic"></a>

次のコード例は、`create-private-dns-namespace` を使用する方法を示しています。

**AWS CLI**  
**プライベート DNS 名前空間を作成するには**  
次の `create-private-dns-namespace` の例では、プライベート DNS 名前空間を作成します。  

```
aws servicediscovery create-private-dns-namespace \
    --name example.com \
    --vpc vpc-1c56417b
```
出力:  

```
{
    "OperationId": "gv4g5meo7ndmeh4fqskygvk23d2fijwa-k9302yzd"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。詳細については、「[get-operation](https://docs.aws.amazon.com/cli/latest/reference/servicediscovery/get-operation.html)」を参照してください。  
詳細については、*AWS Cloud Map デベロッパーガイド*の「[名前空間の作成](https://docs.aws.amazon.com/cloud-map/latest/dg/creating-namespaces.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePrivateDnsNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/create-private-dns-namespace.html)」を参照してください。

### `create-public-dns-namespace`
<a name="servicediscovery_CreatePublicDnsNamespace_cli_2_topic"></a>

次のコード例は、`create-public-dns-namespace` を使用する方法を示しています。

**AWS CLI**  
**パブリック DNS 名前空間を作成するには**  
次の `create-public-dns-namespace` の例では、パブリック DNS 名前空間 `example.com` を作成します。  

```
aws servicediscovery create-public-dns-namespace \
    --name example-public-dns.com \
    --creator-request-id example-public-request-id \
    --properties DnsProperties={SOA={TTL=60}}
```
出力:  

```
{
    "OperationId": "gv4g5meo7ndmeh4fqskygvk23d2fijwa-k9302yzd"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。  
名前空間の作成の詳細については、[AWS 「 Cloud Map Developer Guide」の「Creating an Cloud Map namespace to group application services](https://docs.aws.amazon.com/cloud-map/latest/dg/creating-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePublicDnsNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/create-public-dns-namespace.html)」を参照してください。

### `create-service`
<a name="servicediscovery_CreateService_cli_2_topic"></a>

次の例は、`create-service` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 名前空間 ID を使用してサービスを作成するには**  
次の `create-service` の例では、サービスを作成します。  

```
aws servicediscovery create-service \
    --name myservice \
    --namespace-id  ns-ylexjili4cdxy3xm \
    --dns-config "RoutingPolicy=MULTIVALUE,DnsRecords=[{Type=A,TTL=60}]"
```
出力:  

```
{
    "Service": {
        "Id": "srv-abcd1234xmpl5678",
        "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Name": "myservice",
        "NamespaceId": "ns-abcd1234xmpl5678",
        "DnsConfig": {
            "NamespaceId": "ns-abcd1234xmpl5678",
            "RoutingPolicy": "MULTIVALUE",
            "DnsRecords": [
                {
                    "Type": "A",
                    "TTL": 60
                }
            ]
        },
        "Type": "DNS_HTTP",
        "CreateDate": "2025-08-18T13:45:31.023000-05:00",
        "CreatorRequestId": "abcd1234-5678-90ab-cdef-xmpl12345678",
        "CreatedByAccount": "123456789012"
    }
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Creating an Cloud Map service for an application component](https://docs.aws.amazon.com/cloud-map/latest/dg/creating-services.html)」を参照してください。 *AWS *  
**例 2: 名前空間 ARN を使用してサービスを作成するには**  
次の `create-service` の例では、名前空間 ID の代わりに名前空間 ARN を使用してサービスを作成します。共有名前空間でサービスを作成するときは、名前空間 ARN を指定する必要があります。  

```
aws servicediscovery create-service \
    --name myservice-arn \
    --namespace-id arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678 \
    --dns-config "RoutingPolicy=MULTIVALUE,DnsRecords=[{Type=A,TTL=60}]"
```
出力:  

```
{
    "Service": {
        "Id": "srv-abcd1234xmpl5678",
        "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Name": "myservice-arn",
        "NamespaceId": "ns-abcd1234xmpl5678",
        "DnsConfig": {
            "NamespaceId": "ns-abcd1234xmpl5678",
            "RoutingPolicy": "MULTIVALUE",
            "DnsRecords": [
                {
                    "Type": "A",
                    "TTL": 60
                }
            ]
        },
        "Type": "DNS_HTTP",
        "CreateDate": "2025-08-18T13:45:31.023000-05:00",
        "CreatorRequestId": "abcd1234-5678-90ab-cdef-xmpl12345678",
        "CreatedByAccount": "123456789012"
    }
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/create-service.html)」を参照してください。**

### `delete-namespace`
<a name="servicediscovery_DeleteNamespace_cli_2_topic"></a>

次の例は、`delete-namespace` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 名前空間を削除するには**  
次の `delete-namespace` の例では、名前空間を削除します。  

```
aws servicediscovery delete-namespace \
    --id ns-abcd1234xmpl5678
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。詳細については、「[get-operation](https://docs.aws.amazon.com/cli/latest/reference/servicediscovery/get-operation.html)」を参照してください。  
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map 名前空間の削除](https://docs.aws.amazon.com/cloud-map/latest/dg/deleting-namespaces.html)」を参照してください。 *AWS *  
**例 2: 名前空間 ARN を使用して名前空間を削除するには**  
次の `delete-namespace` の例では、ARN を使用して名前空間を削除します。  

```
aws servicediscovery delete-namespace \
    --id arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map 名前空間の削除](https://docs.aws.amazon.com/cloud-map/latest/dg/deleting-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/delete-namespace.html)」を参照してください。

### `delete-service-attributes`
<a name="servicediscovery_DeleteServiceAttributes_cli_2_topic"></a>

次の例は、`delete-service-attributes` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービス属性を削除するには**  
次の `delete-service-attributes` の例では、指定されたサービスに関連付けられているキー `Port` を持つサービス属性を削除します。  

```
aws servicediscovery delete-service-attributes \
    --service-id srv-abcd1234xmpl5678 \
    --attributes Port
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map services](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html)」を参照してください。  
**例 2: ARN を使用してサービス属性を削除するには**  
次の `delete-service-attributes` の例では、サービス ARN を使用してサービス属性を削除します。アカウントと共有されている名前空間で作成されたサービスに関連付けられた属性を削除するには、ARN を指定する必要があります。  

```
aws servicediscovery delete-service-attributes \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678 \
    --attributes Port
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスと](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html)[共有 AWS Cloud Map 名前空間](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/delete-service-attributes.html)」を参照してください。

### `delete-service`
<a name="servicediscovery_DeleteService_cli_2_topic"></a>

次の例は、`delete-service` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスを削除するには**  
次の `delete-service` の例では、サービスを削除します。  

```
aws servicediscovery delete-service \
    --id srv-abcd1234xmpl5678
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスの削除](https://docs.aws.amazon.com/cloud-map/latest/dg/deleting-services.html)」を参照してください。 *AWS *  
**例 2: ARN を使用してサービスを削除するには**  
次の `delete-service` の例では、ARN を使用してサービスを削除します。  

```
aws servicediscovery delete-service \
    --id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスの削除](https://docs.aws.amazon.com/cloud-map/latest/dg/deleting-services.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/delete-service.html)」を参照してください。

### `deregister-instance`
<a name="servicediscovery_DeregisterInstance_cli_2_topic"></a>

次の例は、`deregister-instance` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスインスタンスの登録を解除するには**  
次の `deregister-instance` の例では、サービスインスタンスの登録を解除します。  

```
aws servicediscovery deregister-instance \
    --service-id srv-p5zdwlg5uvvzjita \
    --instance-id myservice-53
```
出力:  

```
{
    "OperationId": "4yejorelbukcjzpnr6tlmrghsjwpngf4-k98rnaiq"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。詳細については、「[get-operation](https://docs.aws.amazon.com/cli/latest/reference/servicediscovery/get-operation.html)」を参照してください。  
詳細については、「*AWS Cloud Map デベロッパーガイド*」の「[サービスインスタンスの登録解除](https://docs.aws.amazon.com/cloud-map/latest/dg/deregistering-instances.html)」を参照してください。  
**例 2: 共有名前空間のサービス ARN を使用してサービスインスタンスの登録を解除するには**  
次の `deregister-instance` の例では、サービス ID の代わりにサービス ARN を使用してサービスインスタンスの登録を解除します。アカウントと共有されている名前空間で作成されたサービスからインスタンスを登録解除するには、ARN を指定する必要があります。  

```
aws servicediscovery deregister-instance \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-p5zdwlg5uvvzjita \
    --instance-id web-server-01
```
出力:  

```
{
    "OperationId": "gv4g5meo7ndmkqjrhpn39wk42xmpl"
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」と[「Deregistering an AWS Cloud Map service instance](https://docs.aws.amazon.com/cloud-map/latest/dg/deregistering-instances.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/deregister-instance.html)」を参照してください。

### `discover-instances-revision`
<a name="servicediscovery_DiscoverInstancesRevision_cli_2_topic"></a>

次の例は、`discover-instances-revision` を使用する方法を説明しています。

**AWS CLI**  
**例 1: インスタンスのリビジョンを検出するには**  
次の `discover-instances-revision` の例では、インスタンスのリビジョンの増加を検出します。  

```
aws servicediscovery discover-instances-revision \
    --namespace-name example.com \
    --service-name myservice
```
出力:  

```
{
    "InstancesRevision": 123456
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map service instances](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-instances.html)」を参照してください。  
**例 2: 特定の所有者アカウントからインスタンスのリビジョンを検出するには**  
次の `discover-instances-revision` の例では、特定の所有者アカウントからのインスタンスのリビジョンを検出します。owner-account パラメータは、アカウントと共有されている名前空間内のインスタンスに必要です。  

```
aws servicediscovery discover-instances-revision \
    --namespace-name shared-namespace \
    --service-name shared-service \
    --owner-account 123456789111
```
出力:  

```
{
    "InstancesRevision": 1234567890
}
```
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「共有 Cloud Map 名前空間](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)*AWS と* [AWS Cloud Map サービスインスタンス](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DiscoverInstancesRevision](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/discover-instances-revision.html)」を参照してください。

### `discover-instances`
<a name="servicediscovery_DiscoverInstances_cli_2_topic"></a>

次の例は、`discover-instances` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 登録済みインスタンスを検出するには**  
次の `discover-instances` の例では、登録済みインスタンスを検出します。  

```
aws servicediscovery discover-instances \
    --namespace-name example.com \
    --service-name myservice \
    --max-results 10 \
    --health-status ALL
```
出力:  

```
{
    "Instances": [
        {
            "InstanceId": "myservice-53",
            "NamespaceName": "example.com",
            "ServiceName": "myservice",
            "HealthStatus": "UNKNOWN",
            "Attributes": {
                "AWS_INSTANCE_IPV4": "172.2.1.3",
                "AWS_INSTANCE_PORT": "808"
            }
        }
    ],
    "InstancesRevision": 85648075627387284
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map service instances](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-instances.html)」を参照してください。  
**例 2: 特定の所有者アカウントからインスタンスを検出するには**  
次の `discover-instances` の例では、特定の所有者アカウントから登録されたインスタンスを検出します。このパラメータは、アカウントと共有されている名前空間内のインスタンスを検出するために必要です。  

```
aws servicediscovery discover-instances \
    --namespace-name shared-namespace \
    --service-name shared-service \
    --owner-account 123456789111
```
出力:  

```
{
    "Instances": [
        {
            "InstanceId": "shared-instance-1234",
            "NamespaceName": "shared-namespace",
            "ServiceName": "shared-service",
            "HealthStatus": "HEALTHY",
            "Attributes": {
                "AWS_INSTANCE_IPV4": "203.0.113.75",
                "AWS_INSTANCE_PORT": "80"
            }
        }
    ],
    "InstancesRevision": 1234567890
}
```
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「共有 Cloud Map 名前空間](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)*AWS と* [AWS Cloud Map サービスインスタンス](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DiscoverInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/discover-instances.html)」を参照してください。

### `get-instance`
<a name="servicediscovery_GetInstance_cli_2_topic"></a>

次の例は、`get-instance` を使用する方法を説明しています。

**AWS CLI**  
**例 1: インスタンスの詳細を取得するには**  
次の `get-instance` の例では、サービスの属性を取得します。  

```
aws servicediscovery get-instance \
    --service-id srv-e4anhexample0004
    --instance-id i-abcd1234
```
出力:  

```
{
    "ResourceOwner": "123456789012",
    "Instance": {
        "Id": "arn:aws:servicediscovery:us-west-2:111122223333;:service/srv-e4anhexample0004",
        "Attributes": {
            "AWS_INSTANCE_IPV4": "192.0.2.44",
            "AWS_INSTANCE_PORT": "80",
            "color": "green",
            "region": "us-west-2",
            "stage": "beta"
        },
        "CreatedByAccount": "123456789012"
    }
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map service instances](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-instances.html)」を参照してください。  
**例 2: 共有名前空間のサービス ARN を使用してインスタンスの詳細を取得するには**  
次の `get-instance` の例では、サービス ID の代わりにサービス ARN を使用してインスタンスの属性を取得します。アカウントと共有されている名前空間に関連付けられたインスタンスの詳細を取得するには、ARN を指定する必要があります。この例で返されたインスタンスは、アカウント `123456789012` が所有する名前空間にアカウント `123456789111` によって登録されました。  

```
aws servicediscovery get-instance \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-p5zdwlg5uvvzjita \
    --instance-id web-server-01
```
出力:  

```
{
    "ResourceOwner": "123456789012",
    "Instance": {
        "Id": "web-server-01",
        "Attributes": {
            "AWS_INSTANCE_IPV4": "203.0.113.15",
            "AWS_INSTANCE_PORT": "80"
        },
        "CreatedByAccount": "123456789111"
    }
}
```
クロスアカウント名前空間共有の詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/get-instance.html)」を参照してください。

### `get-instances-health-status`
<a name="servicediscovery_GetInstancesHealthStatus_cli_2_topic"></a>

次の例は、`get-instances-health-status` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスに関連付けられているインスタンスのヘルスステータスを取得するには**  
次の `get-instances-health-status` の例では、指定されたサービスに関連付けられているインスタンスのヘルスステータスを取得します。  

```
aws servicediscovery get-instances-health-status \
    --service-id srv-e4anhexample0004
```
出力:  

```
{
    "Status": {
        "i-abcd1234": "HEALTHY",
        "i-abcd1235": "UNHEALTHY"
    }
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map service instances](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-instances.html)」を参照してください。  
**例 2: 共有名前空間のサービス ARN を使用してインスタンスのヘルスステータスを取得するには**  
次の `get-instances-health-status` の例では、サービス ID の代わりにサービス ARN を使用してインスタンスのヘルスステータスを取得します。リクエスタのアカウントと共有されている名前空間に関連付けられたインスタンスのヘルスステータスを取得するには、ARN を指定する必要があります。  

```
aws servicediscovery get-instances-health-status \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-p5zdwlg5uvvzjita
```
出力:  

```
{
    "Status": {
        "web-server-01": "HEALTHY",
        "web-server-02": "UNHEALTHY"
    }
}
```
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスインスタンス](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-instances.html)*AWS 」および*[「共有 Cloud Map 名前空間 AWS](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstancesHealthStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/get-instances-health-status.html)」を参照してください。

### `get-namespace`
<a name="servicediscovery_GetNamespace_cli_2_topic"></a>

次の例は、`get-namespace` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 名前空間の詳細を取得するには**  
次の `get-namespace` の例では、指定された名前空間に関する情報を取得します。  

```
aws servicediscovery get-namespace \
    --id ns-abcd1234xmpl5678
```
出力:  

```
{
    "Namespace": {
        "Id": "ns-abcd1234xmpl5678",
        "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Name": "example-http.com",
        "Type": "HTTP",
        "Description": "Example.com AWS Cloud Map HTTP Namespace",
        "Properties": {
            "DnsProperties": {},
            "HttpProperties": {
                "HttpName": "example-http.com"
            }
        },
        "CreateDate": "2024-02-23T13:35:21.874000-06:00",
        "CreatorRequestId": "abcd1234-5678-90ab-cdef-xmpl12345678"
    }
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html)」を参照してください。  
**例 2: ARN を使用して名前空間の詳細を取得するには**  
次の `get-namespace` の例では、ARN を使用して指定された名前空間に関する情報を取得します。アカウントと共有されている名前空間の詳細を取得するには、ARN を指定する必要があります。  

```
aws servicediscovery get-namespace \
    --id arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678
```
出力:  

```
{
    "Namespace": {
        "Id": "ns-abcd1234xmpl5678",
        "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Name": "example-http.com",
        "Type": "HTTP",
        "Description": "Example.com AWS Cloud Map HTTP Namespace",
        "Properties": {
            "DnsProperties": {},
            "HttpProperties": {
                "HttpName": "example-http.com"
            }
        },
        "CreateDate": "2024-02-23T13:35:21.874000-06:00",
        "CreatorRequestId": "abcd1234-5678-90ab-cdef-xmpl12345678"
    }
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/get-namespace.html)」を参照してください。

### `get-operation`
<a name="servicediscovery_GetOperation_cli_2_topic"></a>

次の例は、`get-operation` を使用する方法を説明しています。

**AWS CLI**  
**例 1: オペレーションの結果を取得するには**  
次の `get-operation` の例では、名前空間の作成オペレーションの結果を取得します。  

```
aws servicediscovery get-operation \
    --operation-id abcd1234xmpl5678abcd1234xmpl5678-abcd1234
```
出力:  

```
{
    "Operation": {
        "Id": "abcd1234xmpl5678abcd1234xmpl5678-abcd1234",
        "Type": "CREATE_NAMESPACE",
        "Status": "SUCCESS",
        "CreateDate": "2025-01-13T13:35:21.874000-06:00",
        "UpdateDate": "2025-01-13T13:36:02.469000-06:00",
        "Targets": {
            "NAMESPACE": "ns-abcd1234xmpl5678"
        }
    }
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Creating an Cloud Map namespace to group application services](https://docs.aws.amazon.com/cloud-map/latest/dg/creating-namespaces.html)」を参照してください。 *AWS *  
**例 2: 特定の所有者アカウントからオペレーションを取得するには**  
次の `get-operation` の例では、特定の名前空間所有者アカウントに関連付けられたオペレーションの結果を取得します。このパラメータは、アカウントと共有されている名前空間に関連付けられたオペレーションの結果を取得するために必要です。  

```
aws servicediscovery get-operation \
    --operation-id abcd1234xmpl5678abcd1234xmpl5678-abcd1234 \
    --owner-account 123456789111
```
出力:  

```
{
    "Operation": {
        "Id": "abcd1234xmpl5678abcd1234xmpl5678-abcd1234",
        "OwnerAccount": "123456789111",
        "Type": "CREATE_NAMESPACE",
        "Status": "SUCCESS",
        "CreateDate": "2025-01-13T13:35:21.874000-06:00",
        "UpdateDate": "2025-01-13T13:36:02.469000-06:00",
        "Targets": {
            "NAMESPACE": "ns-abcd1234xmpl5678"
        }
    }
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOperation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/get-operation.html)」を参照してください。

### `get-service-attributes`
<a name="servicediscovery_GetServiceAttributes_cli_2_topic"></a>

次の例は、`get-service-attributes` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスの属性を取得するには**  
次の `get-service-attributes` の例では、サービスの属性を取得します。  

```
aws servicediscovery get-service-attributes \
    --service-id srv-abcd1234xmpl5678
```
出力:  

```
{
    "ServiceAttributes": {
        "ServiceArn": "arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Attributes": {
            "Port": "80"
        }
    }
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map services](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html)」を参照してください。  
**例 2: ARN を使用してサービスの属性を取得するには**  
次の `get-service-attributes` の例では、ARN を使用してサービスの属性を取得します。アカウントと共有されている名前空間で作成されたサービスの属性を取得するには、ARN を指定する必要があります。  

```
aws servicediscovery get-service-attributes \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678
```
出力:  

```
{
    "ServiceAttributes": {
        "ServiceArn": "arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Attributes": {
            "Port": "80"
        }
    }
}
```
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスと](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html)[共有 AWS Cloud Map 名前空間](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/get-service-attributes.html)」を参照してください。

### `get-service`
<a name="servicediscovery_GetService_cli_2_topic"></a>

次の例は、`get-service` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスの設定を取得するには**  
次の `get-service` の例では、指定されたサービスの設定を取得します。  

```
aws servicediscovery get-service \
    --id srv-abcd1234xmpl5678
```
出力:  

```
{
    "Service": {
        "Id": "srv-abcd1234xmpl5678",
        "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Name": "test-service",
        "NamespaceId": "ns-abcd1234xmpl5678",
        "DnsConfig": {},
        "Type": "HTTP",
        "CreateDate": "2025-08-18T13:53:02.775000-05:00",
        "CreatorRequestId": "abcd1234-5678-90ab-cdef-xmpl12345678",
        "CreatedByAccount": "123456789012"
    }
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map services](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html)」を参照してください。  
**例 2: ARN を使用してサービスの設定を取得するには**  
次の `get-service` の例では、ARN を使用して指定されたサービスの設定を取得します。ARN の指定は、アカウントと共有されている名前空間で作成されたサービスに関する情報を取得するときに必要です。発信者アカウント `123456789111` は、アカウント `123456789012` によって共有されている名前空間にサービスを作成しました。  

```
aws servicediscovery get-service \
    --id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678
```
出力:  

```
{
    "Service": {
        "Id": "srv-abcd1234xmpl5678",
        "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678",
        "ResourceOwner": "123456789012",
        "Name": "test-service",
        "NamespaceId": "ns-abcd1234xmpl5678",
        "DnsConfig": {},
        "Type": "HTTP",
        "CreateDate": "2025-08-18T13:53:02.775000-05:00",
        "CreatorRequestId": "abcd1234-5678-90ab-cdef-xmpl12345678",
        "CreatedByAccount": "123456789111"
    }
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Creating an Cloud Map service for an application component](https://docs.aws.amazon.com/cloud-map/latest/dg/creating-services.html) and [Shared AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/get-service.html)」を参照してください。

### `list-instances`
<a name="servicediscovery_ListInstances_cli_2_topic"></a>

次の例は、`list-instances` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスインスタンスを一覧表示するには**  
次の `list-instances` の例では、サービスインスタンスを一覧表示します。  

```
aws servicediscovery list-instances \
    --service-id srv-qzpwvt2tfqcegapy
```
出力:  

```
{
    "Instances": [
        {
            "Id": "i-06bdabbae60f65a4e",
            "Attributes": {
                "AWS_INSTANCE_IPV4": "172.2.1.3",
                "AWS_INSTANCE_PORT": "808"
            },
            "CreatedByAccount": "123456789012"
        }
    ],
    "ResourceOwner": "123456789012"
}
```
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスインスタンスの一覧表示](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-instances.html)」を参照してください。 *AWS *  
**例 2: サービス ARN を使用してサービスインスタンスを一覧表示するには**  
次の `list-instances` の例では、サービス ID の代わりにサービス ARN を使用するサービスインスタンスを一覧表示します。アカウントと共有されている名前空間に関連付けられたインスタンスを一覧表示するには、ARN の指定が必要です。  

```
aws servicediscovery list-instances \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-p5zdwlg5uvvzjita
```
出力:  

```
{
    "ResourceOwner": "123456789012",
    "Instances": [
        {
            "Id": "web-server-01",
            "Attributes": {
                "AWS_INSTANCE_IPV4": "203.0.113.15",
                "AWS_INSTANCE_PORT": "80"
            },
            "CreatedByAccount": "123456789012"
        },
        {
            "Id": "web-server-02",
            "Attributes": {
                "AWS_INSTANCE_IPV4": "203.0.113.16",
                "AWS_INSTANCE_PORT": "80"
            },
            "CreatedByAccount": "123456789012"
        }
    ]
}
```
クロスアカウント名前空間共有の詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)*AWS 」と*[「Listing Cloud Map service instances AWS](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/list-instances.html)」を参照してください。

### `list-namespaces`
<a name="servicediscovery_ListNamespaces_cli_2_topic"></a>

次の例は、`list-namespaces` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 名前空間を一覧表示するには**  
次の `list-namespaces` の例では、名前空間を一覧表示します。  

```
aws servicediscovery list-namespaces
```
出力:  

```
{
    "Namespaces": [
        {
            "Id": "ns-abcd1234xmpl5678",
            "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678",
            "ResourceOwner": "123456789012",
            "Name": "local",
            "Type": "DNS_PRIVATE",
            "Properties": {
                "DnsProperties": {
                    "HostedZoneId": "Z06752353VBUDTC32S84S",
                    "SOA": {}
                },
                "HttpProperties": {
                    "HttpName": "local"
                 }
            },
            "CreateDate": "2023-07-17T13:37:27.872000-05:00"
        },
        {
            "Id": "ns-abcd1234xmpl9012",
            "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl9012",
            "ResourceOwner": "123456789012",
            "Name": "My-second-namespace",
            "Type": "HTTP",
            "Description": "My second namespace",
            "Properties": {
                "DnsProperties": {
                    "SOA": {}
                },
                "HttpProperties": {
                    "HttpName": "My-second-namespace"
                }
            },
            "CreateDate": "2023-11-14T10:35:47.840000-06:00"
        }
    ]
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Listing Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-namespaces.html)」を参照してください。 *AWS *  
**例 2: 他のアカウントで共有されている名前空間を一覧表示するには**  
次の の`list-namespaces`例では、 `RESOURCE_OWNER`フィルターを使用して他のアカウントによって発信者 AWS アカウントと共有されている名前空間を一覧表示します。  

```
aws servicediscovery list-namespaces \
    --filters Name=RESOURCE_OWNER,Values=OTHER_ACCOUNTS,Condition=EQ
```
出力:  

```
{
    "Namespaces": [
        {
            "Id": "ns-abcd1234xmpl5678",
            "Arn": "arn:aws:servicediscovery:us-west-2:123456789111:namespace/ns-abcd1234xmpl5678",
            "ResourceOwner": "123456789111",
            "Name": "shared-namespace",
            "Type": "HTTP",
            "Description": "Namespace shared from another account",
            "Properties": {
                "DnsProperties": {
                    "SOA": {}
                },
                "HttpProperties": {
                    "HttpName": "shared-namespace"
                }
            },
            "CreateDate": "2025-01-13T13:35:21.874000-06:00"
        }
    ]
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListNamespaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/list-namespaces.html)」を参照してください。

### `list-operations`
<a name="servicediscovery_ListOperations_cli_2_topic"></a>

次のコード例は、`list-operations` を使用する方法を示しています。

**AWS CLI**  
**指定された条件を満たすオペレーションを一覧表示するには**  
次の `list-operations` の例では、ステータスが `PENDING` または `SUCCESS` のオペレーションを一覧表示します。  

```
aws servicediscovery list-operations \
    --service-id srv-e4anhexample0004 \
    --filters Name=STATUS,Condition=IN,Values=PENDING,SUCCESS
```
出力:  

```
{
    "Operations": [
        {
            "Id": "76yy8ovhpdz0plmjzbsnqgnrqvpv2qdt-kexample",
            "Status": "SUCCESS"
        },
        {
            "Id": "prysnyzpji3u2ciy45nke83x2zanl7yk-dexample",
            "Status": "SUCCESS"
        },
        {
            "Id": "ko4ekftir7kzlbechsh7xvcdgcpk66gh-7example",
            "Status": "PENDING"
        }
    ]
}
```
詳細については、[AWS 「 クラウドマップとは」を参照してください。](https://docs.aws.amazon.com/cloud-map/latest/dg/what-is-cloud-map.html) *AWS Cloud Map デベロッパーガイド*の「」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOperations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/list-operations.html)」を参照してください。

### `list-services`
<a name="servicediscovery_ListServices_cli_2_topic"></a>

次の例は、`list-services` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスを一覧表示するには**  
次の `list-services` の例では、サービスを一覧表示します。  

```
aws servicediscovery list-services
```
出力:  

```
{
    "Services": [
        {
            "Id": "srv-p5zdwlg5uvvzjita",
            "Arn": "arn:aws:servicediscovery:us-west-2:123456789012:service/srv-p5zdwlg5uvvzjita",
            "Name": "myservice",
            "DnsConfig": {
                "RoutingPolicy": "MULTIVALUE",
                "DnsRecords": [
                    {
                        "Type": "A",
                        "TTL": 60
                    }
                ]
            },
            "CreateDate": 1587081768.334
        }
    ]
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Listing Cloud Map services in a namespace](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-services.html)」を参照してください。 *AWS *  
**例 2: 共有名前空間で作成されたサービスを一覧表示するには**  
次の の`list-services`例では、 `RESOURCE_OWNER`フィルターを使用して、他の AWS アカウント`123456789012`によって発信者アカウントと共有されている名前空間で作成されたサービスを一覧表示します。  

```
aws servicediscovery list-services \
    --filters Name=RESOURCE_OWNER,Values=OTHER_ACCOUNTS,Condition=EQ
```
出力:  

```
{
    "Services": [
        {
            "Id": "srv-abcd1234xmpl5678",
            "Arn": "arn:aws:servicediscovery:us-west-2:123456789111:service/srv-abcd1234xmpl5678",
            "ResourceOwner": "123456789111",
            "Name": "shared-service",
            "NamespaceId": "ns-abcd1234xmpl5678",
            "Type": "HTTP",
            "Description": "Service in shared namespace",
            "DnsConfig": {},
            "CreateDate": "2025-01-13T13:35:21.874000-06:00",
            "CreatorRequestId": "abcd1234-5678-90ab-cdef-xmpl12345678",
            "CreatedByAccount": "123456789012"
        }
    ]
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)*AWS 」と*[「Listing Cloud Map services in a namespace AWS](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-services.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/list-services.html)」を参照してください。**

### `list-tags-for-resource`
<a name="servicediscovery_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**指定されたリソースに関連付けられているタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定されたリソースのタグを一覧表示します。  

```
aws servicediscovery list-tags-for-resource \
    --resource-arn arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-e4anhexample0004
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Project",
            "Value": "Zeta"
        },
        {
            "Key": "Department",
            "Value": "Engineering"
        }
    ]
}
```
詳細については、[AWS 「 Cloud Map Developer Guide」の「Tagging your](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-instances.html) *AWS Cloud Map* resources」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/list-tags-for-resource.html)」を参照してください。

### `register-instance`
<a name="servicediscovery_RegisterInstance_cli_2_topic"></a>

次の例は、`register-instance` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービス ID を使用してサービスインスタンスを登録するには**  
次の `register-instance` の例では、サービスインスタンスを登録します。  

```
aws servicediscovery register-instance \
    --service-id srv-p5zdwlg5uvvzjita \
    --instance-id myservice-53 \
    --attributes=AWS_INSTANCE_IPV4=172.2.1.3,AWS_INSTANCE_PORT=808
```
出力:  

```
{
    "OperationId": "4yejorelbukcjzpnr6tlmrghsjwpngf4-k95yg2u7"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。詳細については、「[get-operation](https://docs.aws.amazon.com/cli/latest/reference/servicediscovery/get-operation.html)」を参照してください。  
インスタンスの登録の詳細については、[AWS 「 Cloud Map Developer Guide」の「Registering a resource as an Cloud Map service instance](https://docs.aws.amazon.com/cloud-map/latest/dg/registering-instances.html)」を参照してください。 *AWS *  
**例 2: サービス ARN を使用してサービスインスタンスを登録するには**  
次の `register-instance` の例では、サービス ARN を使用してサービスインスタンスを登録します。アカウントと共有されているサービスにインスタンスを登録する場合は、ARN の指定が必要です。  

```
aws servicediscovery register-instance \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-p5zdwlg5uvvzjita \
    --instance-id web-server-01 \
    --attributes=AWS_INSTANCE_IPV4=203.0.113.15,AWS_INSTANCE_PORT=80
```
出力:  

```
{
    "OperationId": "gv4g5meo7ndmkqjrhpn39wk42xmpl"
}
```
クロスアカウント名前空間共有の詳細については、[AWS 「 Cloud Map Developer Guide」の「Shared Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/register-instance.html)」を参照してください。

### `tag-resource`
<a name="servicediscovery_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定されたリソースにタグを関連付けるには**  
次の `tag-resource` の例では、指定された名前空間に値 `Engineering` を持つ `Department` タグを関連付けます。  

```
aws servicediscovery tag-resource \
    --resource-arn arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-e4anhexample0004 \
    --tags Key=Department, Value=Engineering
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Cloud Map Developer Guide」の「Tagging your](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-instances.html) *AWS Cloud Map* resources」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="servicediscovery_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定されたリソースからタグを削除するには**  
次の `untag-resource` の例では、指定された名前空間から `Department` タグを削除します。  

```
aws servicediscovery untag-resource \
    --resource-arn arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-e4anhexample0004 \
    --tags Key=Department, Value=Engineering
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Cloud Map Developer Guide」の「Tagging your](https://docs.aws.amazon.com/cloud-map/latest/dg/listing-instances.html) *AWS Cloud Map* resources」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/untag-resource.html)」を参照してください。

### `update-http-namespace`
<a name="servicediscovery_UpdateHttpNamespace_cli_2_topic"></a>

次の例は、`update-http-namespace` を使用する方法を説明しています。

**AWS CLI**  
**例 1: HTTP 名前空間を更新するには**  
次の `update-http-namespace` の例では、指定された HTTP 名前空間の説明を更新します。  

```
aws servicediscovery update-http-namespace \
    --id ns-abcd1234xmpl5678 \
    --updater-request-id abcd1234-5678-90ab-cdef-xmpl12345678 \
    --namespace Description="The updated namespace description."
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。詳細については、「[get-operation](https://docs.aws.amazon.com/cli/latest/reference/servicediscovery/get-operation.html)」を参照してください。  
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html)」を参照してください。  
**例 2: ARN を使用して HTTP 名前空間を更新するには**  
次の `update-http-namespace` の例では、ARN を使用して指定された HTTP 名前空間の説明を更新します。  

```
aws servicediscovery update-http-namespace \
    --id arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678 \
    --updater-request-id abcd1234-5678-90ab-cdef-xmpl12345678 \
    --namespace Description="The updated namespace description."
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateHttpNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/update-http-namespace.html)」を参照してください。

### `update-instance-custom-health-status`
<a name="servicediscovery_UpdateInstanceCustomHealthStatus_cli_2_topic"></a>

次の例は、`update-instance-custom-health-status` を使用する方法を説明しています。

**AWS CLI**  
**例 1: カスタムヘルスチェックを更新するには**  
次の `update-instance-custom-health-status` の例では、指定されたサービスおよびサンプルサービスインスタンスのカスタムヘルスチェックのステータスを `HEALTHY` に更新します。  

```
aws servicediscovery update-instance-custom-health-status \
    --service-id srv-e4anhexample0004 \
    --instance-id example \
    --status HEALTHY
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map service health check configuration](https://docs.aws.amazon.com/cloud-map/latest/dg/services-health-checks.html)」を参照してください。  
**例 2: サービス ARN を使用してカスタムヘルスチェックを更新するには**  
次の `update-instance-custom-health-status` の例では、サービス ARN を使用してカスタムヘルスチェックのステータスを更新します。ARN は、アカウントと共有されている名前空間に関連付けられたインスタンスのヘルスステータスを更新するときに必要です。  

```
aws servicediscovery update-instance-custom-health-status \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-p5zdwlg5uvvzjita \
    --instance-id web-server-01 \
    --status HEALTHY
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスヘルスチェック設定](https://docs.aws.amazon.com/cloud-map/latest/dg/services-health-checks.html)*AWS 」および*[「クロスアカウント Cloud Map 名前空間共有 AWS](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateInstanceCustomHealthStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/update-instance-custom-health-status.html)」を参照してください。

### `update-private-dns-namespace`
<a name="servicediscovery_UpdatePrivateDnsNamespace_cli_2_topic"></a>

次の例は、`update-private-dns-namespace` を使用する方法を説明しています。

**AWS CLI**  
**例 1: ID を使用してプライベート DNS 名前空間を更新するには**  
次の `update-private-dns-namespace` の例では、名前空間 ID を使用してプライベート DNS 名前空間の説明を更新します。  

```
aws servicediscovery update-private-dns-namespace \
    --id ns-abcd1234xmpl5678 \
    --updater-request-id abcd1234-5678-90ab-cdef-xmpl12345678 \
    --namespace Description="The updated namespace description."
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。  
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html)」を参照してください。  
**例 2: ARN を使用してプライベート DNS 名前空間を更新するには**  
次の `update-private-dns-namespace` の例では、ARN を使用してプライベート DNS 名前空間を更新します。  

```
aws servicediscovery update-private-dns-namespace \
    --id arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678 \
    --updater-request-id abcd1234-5678-90ab-cdef-xmpl12345678 \
    --namespace Description="The updated namespace description."
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePrivateDnsNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/update-private-dns-namespace.html)」を参照してください。

### `update-public-dns-namespace`
<a name="servicediscovery_UpdatePublicDnsNamespace_cli_2_topic"></a>

次の例は、`update-public-dns-namespace` を使用する方法を説明しています。

**AWS CLI**  
**例 1: ID を使用してパブリック DNS 名前空間を更新するには**  
次の `update-public-dns-namespace` の例では、名前空間 ID を使用してパブリック DNS 名前空間の説明を更新します。  

```
aws servicediscovery update-public-dns-namespace \
    --id ns-abcd1234xmpl5678 \
    --updater-request-id abcd1234-5678-90ab-cdef-xmpl12345678 \
    --namespace Description="The updated namespace description."
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。  
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html)」を参照してください。  
**例 2: ARN を使用してパブリック DNS 名前空間を更新するには**  
次の `update-public-dns-namespace` の例では、ARN を使用してパブリック DNS 名前空間を更新します。  

```
aws servicediscovery update-public-dns-namespace \
    --id arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-abcd1234xmpl5678 \
    --updater-request-id abcd1234-5678-90ab-cdef-xmpl12345678 \
    --namespace Description="The updated namespace description."
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map namespaces](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-namespaces.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePublicDnsNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/update-public-dns-namespace.html)」を参照してください。

### `update-service-attributes`
<a name="servicediscovery_UpdateServiceAttributes_cli_2_topic"></a>

次の例は、`update-service-attributes` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスを更新して属性を追加するには**  
次の `update-service-attributes` の例では、指定されたサービスを更新して、キー `Port` と値 `80` を持つサービス属性を追加します。  

```
aws servicediscovery update-service-attributes \
    --service-id srv-abcd1234xmpl5678 \
    --attributes Port=80
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Cloud Map Developer Guide*」の「[AWS Cloud Map services](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html)」を参照してください。  
**例 2: ARN を使用してサービス属性を更新するには**  
次の `update-service-attributes` の例では、ARN を使用してサービスを更新し、サービス属性を追加します。アカウントと共有されている名前空間で作成されたサービスに属性を追加するには、ARN を指定する必要があります。  

```
aws servicediscovery update-service-attributes \
    --service-id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678 \
    --attributes Port=80
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Cloud Map デベロッパーガイド」の「Cloud Map サービスと](https://docs.aws.amazon.com/cloud-map/latest/dg/working-with-services.html)[共有 AWS Cloud Map 名前空間](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServiceAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/update-service-attributes.html)」を参照してください。

### `update-service`
<a name="servicediscovery_UpdateService_cli_2_topic"></a>

次の例は、`update-service` を使用する方法を説明しています。

**AWS CLI**  
**例 1: サービスを更新するには**  
次の `update-service` の例では、 サービスを更新して `DnsConfig` および `HealthCheckConfig` 設定を更新します。  

```
aws servicediscovery update-service \
    --id srv-abcd1234xmpl5678 \
    --service "DnsConfig={DnsRecords=[{Type=A,TTL=60}]},HealthCheckConfig={Type=HTTP,ResourcePath=/,FailureThreshold=2}"
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
オペレーションが成功したことを確認するには、`get-operation` を実行します。  
サービスの更新の詳細については、[AWS 「 Cloud Map Developer Guide」の「Updating an Cloud Map service](https://docs.aws.amazon.com/cloud-map/latest/dg/editing-services.html)」を参照してください。 *AWS *  
**例 2: ARN を使用してサービスを更新するには**  
次の `update-service` の例では、ARN を使用してサービスを更新します。アカウントと共有されている名前空間で作成されるサービスには、ARN を指定する必要があります。  

```
aws servicediscovery update-service \
    --id arn:aws:servicediscovery:us-west-2:123456789012:service/srv-abcd1234xmpl5678 \
    --service "DnsConfig={DnsRecords=[{Type=A,TTL=60}]},HealthCheckConfig={Type=HTTP,ResourcePath=/,FailureThreshold=2}"
```
出力:  

```
{
    "OperationId": "abcd1234-5678-90ab-cdef-xmpl12345678"
}
```
サービスの更新の詳細については、[AWS 「 Cloud Map Developer Guide」の「Updating an Cloud Map service](https://docs.aws.amazon.com/cloud-map/latest/dg/editing-services.html) *AWS and* [Shared Cloud Map namespaces AWS](https://docs.aws.amazon.com/cloud-map/latest/dg/sharing-namespaces.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicediscovery/update-service.html)」を参照してください。**

# AWS Cloud9 を使用した の例 AWS CLI
<a name="cli_2_cloud9_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Cloud9。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-environment-ec2`
<a name="cloud9_CreateEnvironmentEc2_cli_2_topic"></a>

次の例は、`create-environment-ec2` を使用する方法を説明しています。

**AWS CLI**  
** AWS Cloud9 EC2 開発環境を作成するには**  
次の の`create-environment-ec2`例では、指定された設定で AWS Cloud9 開発環境を作成し、Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを起動してから、インスタンスから環境に接続します。  

```
aws cloud9 create-environment-ec2 \
    --name my-demo-env \
    --description "My demonstration development environment." \
    --instance-type t2.micro --image-id amazonlinux-2023-x86_64 \
    --subnet-id subnet-1fab8aEX \
    --automatic-stop-time-minutes 60 \
    --owner-arn arn:aws:iam::123456789012:user/MyDemoUser
```
出力:  

```
{
    "environmentId": "8a34f51ce1e04a08882f1e811bd706EX"
}
```
詳細については、「*AWS Cloud9 ユーザーガイド*」の「[EC2 環境の作成](https://docs.aws.amazon.com/cloud9/latest/user-guide/create-environment-main.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEnvironmentEc2](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/create-environment-ec2.html)」を参照してください。

### `create-environment-membership`
<a name="cloud9_CreateEnvironmentMembership_cli_2_topic"></a>

次の例は、`create-environment-membership` を使用する方法を説明しています。

**AWS CLI**  
**環境メンバーを AWS Cloud9 開発環境に追加するには**  
この例では、指定された環境メンバーを指定された AWS Cloud9 開発環境に追加します。  
コマンド:  

```
aws cloud9 create-environment-membership --environment-id 8a34f51ce1e04a08882f1e811bd706EX --user-arn arn:aws:iam::123456789012:user/AnotherDemoUser --permissions read-write
```
出力:  

```
{
  "membership": {
    "environmentId": "8a34f51ce1e04a08882f1e811bd706EX",
    "userId": "AIDAJ3LOROMOUXTBSU6EX",
    "userArn": "arn:aws:iam::123456789012:user/AnotherDemoUser",
    "permissions": "read-write"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEnvironmentMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/create-environment-membership.html)」を参照してください。

### `delete-environment-membership`
<a name="cloud9_DeleteEnvironmentMembership_cli_2_topic"></a>

次の例は、`delete-environment-membership` を使用する方法を説明しています。

**AWS CLI**  
** AWS Cloud9 開発環境から環境メンバーを削除するには**  
この例では、指定された AWS Cloud9 開発環境から指定された環境メンバーを削除します。  
コマンド:  

```
aws cloud9 delete-environment-membership --environment-id 8a34f51ce1e04a08882f1e811bd706EX --user-arn arn:aws:iam::123456789012:user/AnotherDemoUser
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEnvironmentMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/delete-environment-membership.html)」を参照してください。

### `delete-environment`
<a name="cloud9_DeleteEnvironment_cli_2_topic"></a>

次の例は、`delete-environment` を使用する方法を説明しています。

**AWS CLI**  
** AWS Cloud9 開発環境を削除するには**  
この例では、指定された AWS Cloud9 開発環境を削除します。環境が Amazon EC2 インスタンスに接続されている場合、インスタンスを終了します。  
コマンド:  

```
aws cloud9 delete-environment --environment-id 8a34f51ce1e04a08882f1e811bd706EX
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/delete-environment.html)」を参照してください。

### `describe-environment-memberships`
<a name="cloud9_DescribeEnvironmentMemberships_cli_2_topic"></a>

次の例は、`describe-environment-memberships` を使用する方法を説明しています。

**AWS CLI**  
** AWS Cloud9 開発環境の環境メンバーに関する情報を取得するには**  
この例では、指定された AWS Cloud9 開発環境の環境メンバーに関する情報を取得します。  
コマンド:  

```
aws cloud9 describe-environment-memberships --environment-id 8a34f51ce1e04a08882f1e811bd706EX
```
出力:  

```
{
  "memberships": [
    {
      "environmentId": "8a34f51ce1e04a08882f1e811bd706EX",
      "userId": "AIDAJ3LOROMOUXTBSU6EX",
      "userArn": "arn:aws:iam::123456789012:user/AnotherDemoUser",
      "permissions": "read-write"
    },
    {
      "environmentId": "8a34f51ce1e04a08882f1e811bd706EX",
      "userId": "AIDAJNUEDQAQWFELJDLEX",
      "userArn": "arn:aws:iam::123456789012:user/MyDemoUser",
      "permissions": "owner"
    }
  ]
}
```
** AWS Cloud9 開発環境の所有者に関する情報を取得するには**  
この例では、指定された AWS Cloud9 開発環境の所有者に関する情報を取得します。  
コマンド:  

```
aws cloud9 describe-environment-memberships --environment-id 8a34f51ce1e04a08882f1e811bd706EX --permissions owner
```
出力:  

```
{
  "memberships": [
    {
      "environmentId": "8a34f51ce1e04a08882f1e811bd706EX",
      "userId": "AIDAJNUEDQAQWFELJDLEX",
      "userArn": "arn:aws:iam::123456789012:user/MyDemoUser",
      "permissions": "owner"
    }
  ]
}
```
**multiple AWS Cloud9 開発環境の環境メンバーに関する情報を取得するには**  
この例では、multiple AWS Cloud9 開発環境の指定された環境メンバーに関する情報を取得します。  
コマンド:  

```
aws cloud9 describe-environment-memberships --user-arn arn:aws:iam::123456789012:user/MyDemoUser
```
出力:  

```
{
  "memberships": [
    {
      "environmentId": "10a75714bd494714929e7f5ec4125aEX",
      "lastAccess": 1516213427.0,
      "userId": "AIDAJNUEDQAQWFELJDLEX",
      "userArn": "arn:aws:iam::123456789012:user/MyDemoUser",
      "permissions": "owner"
    },
    {
      "environmentId": "1980b80e5f584920801c09086667f0EX",
      "lastAccess": 1516144884.0,
      "userId": "AIDAJNUEDQAQWFELJDLEX",
      "userArn": "arn:aws:iam::123456789012:user/MyDemoUser",
      "permissions": "owner"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEnvironmentMemberships](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/describe-environment-memberships.html)」を参照してください。

### `describe-environment-status`
<a name="cloud9_DescribeEnvironmentStatus_cli_2_topic"></a>

次の例は、`describe-environment-status` を使用する方法を説明しています。

**AWS CLI**  
** AWS Cloud9 開発環境のステータス情報を取得するには**  
この例では、指定された AWS Cloud9 開発環境のステータス情報を取得します。  
コマンド:  

```
aws cloud9 describe-environment-status --environment-id 685f892f431b45c2b28cb69eadcdb0EX
```
出力:  

```
{
  "status": "ready",
  "message": "Environment is ready to use"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEnvironmentStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/describe-environment-status.html)」を参照してください。

### `describe-environments`
<a name="cloud9_DescribeEnvironments_cli_2_topic"></a>

次の例は、`describe-environments` を使用する方法を説明しています。

**AWS CLI**  
** AWS Cloud9 開発環境に関する情報を取得するには**  
この例では、指定された AWS Cloud9 開発環境に関する情報を取得します。  
コマンド:  

```
aws cloud9 describe-environments --environment-ids 685f892f431b45c2b28cb69eadcdb0EX 349c86d4579e4e7298d500ff57a6b2EX
```
出力:  

```
{
  "environments": [
    {
      "id": "685f892f431b45c2b28cb69eadcdb0EX",
      "name": "my-demo-ec2-env",
      "description": "Created from CodeStar.",
      "type": "ec2",
      "arn": "arn:aws:cloud9:us-east-1:123456789012:environment:685f892f431b45c2b28cb69eadcdb0EX",
      "ownerArn": "arn:aws:iam::123456789012:user/MyDemoUser",
      "lifecycle": {
        "status": "CREATED"
      }
    },
    {
      "id": "349c86d4579e4e7298d500ff57a6b2EX",
      "name": my-demo-ssh-env",
      "description": "",
      "type": "ssh",
      "arn": "arn:aws:cloud9:us-east-1:123456789012:environment:349c86d4579e4e7298d500ff57a6b2EX",
      "ownerArn": "arn:aws:iam::123456789012:user/MyDemoUser",
      "lifecycle": {
        "status": "CREATED"
      }
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEnvironments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/describe-environments.html)」を参照してください。

### `list-environments`
<a name="cloud9_ListEnvironments_cli_2_topic"></a>

次の例は、`list-environments` を使用する方法を説明しています。

**AWS CLI**  
**利用可能な AWS Cloud9 開発環境識別子のリストを取得するには**  
この例では、利用可能な AWS Cloud9 開発環境識別子のリストを取得します。  
コマンド:  

```
aws cloud9 list-environments
```
出力:  

```
{
  "environmentIds": [
    "685f892f431b45c2b28cb69eadcdb0EX",
    "1980b80e5f584920801c09086667f0EX"
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEnvironments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/list-environments.html)」を参照してください。

### `update-environment-membership`
<a name="cloud9_UpdateEnvironmentMembership_cli_2_topic"></a>

次の例は、`update-environment-membership` を使用する方法を説明しています。

**AWS CLI**  
** AWS Cloud9 開発環境の既存の環境メンバーの設定を変更するには**  
この例では、指定された AWS Cloud9 開発環境の指定された既存の環境メンバーの設定を変更します。  
コマンド:  

```
aws cloud9 update-environment-membership --environment-id 8a34f51ce1e04a08882f1e811bd706EX --user-arn arn:aws:iam::123456789012:user/AnotherDemoUser --permissions read-only
```
出力:  

```
{
  "membership": {
    "environmentId": "8a34f51ce1e04a08882f1e811bd706EX",
    "userId": "AIDAJ3LOROMOUXTBSU6EX",
    "userArn": "arn:aws:iam::123456789012:user/AnotherDemoUser",
    "permissions": "read-only"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEnvironmentMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/update-environment-membership.html)」を参照してください。

### `update-environment`
<a name="cloud9_UpdateEnvironment_cli_2_topic"></a>

次の例は、`update-environment` を使用する方法を説明しています。

**AWS CLI**  
**既存の AWS Cloud9 開発環境の設定を変更するには**  
この例では、指定された既存の AWS Cloud9 開発環境の指定された設定を変更します。  
コマンド:  

```
aws cloud9 update-environment --environment-id 8a34f51ce1e04a08882f1e811bd706EX --name my-changed-demo-env --description "My changed demonstration development environment."
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloud9/update-environment.html)」を参照してください。

# CloudFormation を使用した の例 AWS CLI
<a name="cli_2_cloudformation_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています CloudFormation。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `activate-type`
<a name="cloudformation_ActivateType_cli_2_topic"></a>

次のコード例は、`activate-type` の使用方法を示しています。

**AWS CLI**  
**タイプをアクティブ化する方法**  
次の `activate-type` の例はサードパーティーのパブリック拡張機能をアクティブ化し、スタックテンプレートで使用できるようにします。  

```
aws cloudformation activate-type \
    --region us-west-2 \
    --type RESOURCE \
    --type-name Example::Test::1234567890abcdef0 \
    --type-name-alias Example::Test::Alias
```
出力:  

```
{
    "Arn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/Example-Test-Alias"
}
```
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ActivateType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/activate-type.html)」を参照してください。

### `batch-describe-type-configurations`
<a name="cloudformation_BatchDescribeTypeConfigurations_cli_2_topic"></a>

次のコード例は、`batch-describe-type-configurations` の使用方法を示しています。

**AWS CLI**  
**タイプ構成を一括記述する方法**  
次の `batch-describe-type-configurations` の例は、タイプのデータを設定します。  

```
aws cloudformation batch-describe-type-configurations \
    --region us-west-2 \
    --type-configuration-identifiers TypeArn="arn:aws:cloudformation:us-west-2:123456789012:type/resource/Example-Test-Type,TypeConfigurationAlias=MyConfiguration"
```
出力:  

```
{
    "Errors": [],
    "UnprocessedTypeConfigurations": [],
    "TypeConfigurations": [
        {
            "Arn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/Example-Test-Type",
            "Alias": "MyConfiguration",
            "Configuration": "{\n        \"Example\": {\n            \"ApiKey\": \"examplekey\",\n            \"ApplicationKey\": \"examplekey1\",\n            \"ApiURL\": \"exampleurl\"\n            }\n}",
            "LastUpdated": "2021-10-01T15:25:46.210000+00:00",
            "TypeArn": "arn:aws:cloudformation:us-east-1:123456789012:type/resource/Example-Test-Type"
        }
    ]
}
```
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDescribeTypeConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/batch-describe-type-configurations.html)」を参照してください。

### `cancel-update-stack`
<a name="cloudformation_CancelUpdateStack_cli_2_topic"></a>

次のコード例は、`cancel-update-stack` の使用方法を示しています。

**AWS CLI**  
**進行中のスタック更新をキャンセルする方法**  
以下の `cancel-update-stack` コマンドは、`myteststack` スタックで行われているスタック更新をキャンセルします。  

```
aws cloudformation cancel-update-stack --stack-name myteststack
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelUpdateStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/cancel-update-stack.html)」を参照してください。

### `continue-update-rollback`
<a name="cloudformation_ContinueUpdateRollback_cli_2_topic"></a>

次のコード例は、`continue-update-rollback` の使用方法を示しています。

**AWS CLI**  
**更新のロールバックを再試行する**  
以下の `continue-update-rollback` の例は、前回失敗したスタック更新からのロールバック操作を再開します。  

```
aws cloudformation continue-update-rollback \
    --stack-name my-stack
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ContinueUpdateRollback](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/continue-update-rollback.html)」を参照してください。

### `create-change-set`
<a name="cloudformation_CreateChangeSet_cli_2_topic"></a>

次のコード例は、`create-change-set` の使用方法を示しています。

**AWS CLI**  
**変更セットを作成する方法**  
次の `create-change-set` の例は、`CAPABILITY_IAM` 機能を持つ変更セットを作成します。ファイルは、IAM リソースを含むスタックを定義する現在のフォルダ内の AWS CloudFormation テンプレート`template.yaml`です。  

```
aws cloudformation create-change-set \
    --stack-name my-application \
    --change-set-name my-change-set \
    --template-body file://template.yaml \
    --capabilities CAPABILITY_IAM
```
出力:  

```
{
    "Id": "arn:aws:cloudformation:us-west-2:123456789012:changeSet/my-change-set/bc9555ba-a949-xmpl-bfb8-f41d04ec5784",
    "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-application/d0a825a0-e4cd-xmpl-b9fb-061c69e99204"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateChangeSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-change-set.html)」を参照してください。

### `create-generated-template`
<a name="cloudformation_CreateGeneratedTemplate_cli_2_topic"></a>

次の例は、`create-generated-template` を使用する方法を説明しています。

**AWS CLI**  
**スキャンしたリソースから生成済みテンプレートを作成する**  
次の `create-generated-template` の例では、スキャンされたリソースから `MyTemplate` という名前の生成済みテンプレートを作成します。  

```
aws cloudformation create-generated-template \
    --generated-template-name MyTemplate \
    --resources file://resources.json
```
`resources.json` の内容:  

```
[
    {
        "ResourceType": "AWS::EKS::Cluster",
        "LogicalResourceId":"MyCluster",
        "ResourceIdentifier": {
            "ClusterName": "MyAppClusterName"
        }
    },
    {
        "ResourceType": "AWS::AutoScaling::AutoScalingGroup",
        "LogicalResourceId":"MyASG",
        "ResourceIdentifier": {
            "AutoScalingGroupName": "MyAppASGName"
        }
    },
    {
        "ResourceType": "AWS::EKS::Nodegroup",
        "LogicalResourceId":"MyNodegroup",
        "ResourceIdentifier": {
            "NodegroupName": "MyAppNodegroupName"
        }
    },
    {
        "ResourceType": "AWS::IAM::Role",
        "LogicalResourceId":"MyRole",
        "ResourceIdentifier": {
            "RoleId": "arn:aws::iam::123456789012:role/MyAppIAMRole"
        }
    }
]
```
出力:  

```
{
  "Arn":
    "arn:aws:cloudformation:us-east-1:123456789012:generatedtemplate/7fc8512c-d8cb-4e02-b266-d39c48344e48",
  "Name": "MyTemplate"
}
```
詳細については、「AWS CloudFormation ユーザーガイド」の「[IaC ジェネレーターでスキャンされたリソースから CloudFormation テンプレートを作成する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/iac-generator-create-template-from-scanned-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGeneratedTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-generated-template.html)」を参照してください。

### `create-stack-instances`
<a name="cloudformation_CreateStackInstances_cli_2_topic"></a>

次の例は、`create-stack-instances` を使用する方法を説明しています。

**AWS CLI**  
**スタックインスタンスを作成する方法**  
次の `create-stack-instances` の例は、2 つのアカウントと 4 つのリージョンにスタックセットのインスタンスを作成します。耐障害性の設定により、一部のスタックが作成できない場合でも、すべてのアカウントとリージョンで更新が試行されます。  

```
aws cloudformation create-stack-instances \
    --stack-set-name my-stack-set \
    --accounts 123456789012 223456789012 \
    --regions us-east-1 us-east-2 us-west-1 us-west-2 \
    --operation-preferences FailureToleranceCount=7
```
出力:  

```
{
    "OperationId": "d7995c31-83c2-xmpl-a3d4-e9ca2811563f"
}
```
`create-stack-set` コマンドを使用してスタックを作成します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStackInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-stack-instances.html)」を参照してください。

### `create-stack-refactor`
<a name="cloudformation_CreateStackRefactor_cli_2_topic"></a>

次の例は、`create-stack-refactor` を使用する方法を説明しています。

**AWS CLI**  
**スタックリファクタリングオペレーションのスタック定義を作成するには**  
次の `create-stack-refactor` 例では、スタックリファクタリング用のスタック定義を作成します。  

```
aws cloudformation create-stack-refactor \
    --stack-definitions \
      StackName=Stack1,TemplateBody@=file://template1-updated.yaml \
      StackName=Stack2,TemplateBody@=file://template2-updated.yaml
```
出力:  

```
{
    "StackRefactorId": "9c384f70-4e07-4ed7-a65d-fee5eb430841"
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[スタックリファクタリング](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-refactoring.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStackRefactor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-stack-refactor.html)」を参照してください。

### `create-stack-set`
<a name="cloudformation_CreateStackSet_cli_2_topic"></a>

次の例は、`create-stack-set` を使用する方法を説明しています。

**AWS CLI**  
**スタックセットを作成する方法**  
次の の`create-stack-set`例では、指定された YAML ファイルテンプレートを使用してスタックセットを作成します。 `template.yaml`は、スタックを定義する現在のフォルダ内の AWS CloudFormation テンプレートです。  

```
aws cloudformation create-stack-set \
    --stack-set-name my-stack-set \
    --template-body file://template.yaml \
    --description "SNS topic"
```
出力:  

```
{
    "StackSetId": "my-stack-set:8d0f160b-d157-xmpl-a8e6-c0ce8e5d8cc1"
}
```
`create-stack-instances` コマンドを使用して、スタックセットにスタックインスタンスを追加します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStackSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-stack-set.html)」を参照してください。

### `create-stack`
<a name="cloudformation_CreateStack_cli_2_topic"></a>

次の例は、`create-stack` を使用する方法を説明しています。

**AWS CLI**  
** AWS CloudFormation スタックを作成するには**  
次の `create-stacks` コマンドは、`sampletemplate.json` テンプレートを使用して「`myteststack`」という名称のスタックを作成します。  

```
aws cloudformation create-stack --stack-name myteststack --template-body file://sampletemplate.json --parameters ParameterKey=KeyPairName,ParameterValue=TestKey ParameterKey=SubnetIDs,ParameterValue=SubnetID1\\,SubnetID2
```
出力:  

```
{
    "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896"
}
```
詳細については、「AWS CloudFormation ユーザーガイド」の「スタック」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-stack.html)」を参照してください。

### `deactivate-type`
<a name="cloudformation_DeactivateType_cli_2_topic"></a>

次のコード例は、`deactivate-type` の使用方法を示しています。

**AWS CLI**  
**タイプを非アクティブ化する方法**  
次の `deactivate-type` の例は、このアカウントとリージョンで以前にアクティブ化されたパブリック拡張機能を非アクティブ化します。  

```
aws cloudformation deactivate-type \
    --region us-west-2 \
    --type MODULE \
    --type-name Example::Test::Type::MODULE
```
このコマンドでは何も出力されません。  
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeactivateType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deactivate-type.html)」を参照してください。

### `delete-change-set`
<a name="cloudformation_DeleteChangeSet_cli_2_topic"></a>

次のコード例は、`delete-change-set` の使用方法を示しています。

**AWS CLI**  
**変更セットを削除する方法**  
次の `delete-change-set` の例は、変更セット名とスタック名を指定して変更セットを削除します。  

```
aws cloudformation delete-change-set \
    --stack-name my-stack \
    --change-set-name my-change-set
```
このコマンドでは何も出力されません。  
次の `delete-change-set` の例は、変更セットの完全な ARN を指定して変更セットを削除します。  

```
aws cloudformation delete-change-set \
    --change-set-name arn:aws:cloudformation:us-east-2:123456789012:changeSet/my-change-set/4eca1a01-e285-xmpl-8026-9a1967bfb4b0
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteChangeSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/delete-change-set.html)」を参照してください。

### `delete-generated-template`
<a name="cloudformation_DeleteGeneratedTemplate_cli_2_topic"></a>

次の例は、`delete-generated-template` を使用する方法を説明しています。

**AWS CLI**  
**生成されたテンプレートを削除するには**  
次の `delete-generated-template` の例では、指定されたテンプレートを削除します。  

```
aws cloudformation delete-generated-template \
    --generated-template-name MyTemplate
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[既存のリソースからテンプレートを生成する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGeneratedTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/delete-generated-template.html)」を参照してください。

### `delete-stack-instances`
<a name="cloudformation_DeleteStackInstances_cli_2_topic"></a>

次の例は、`delete-stack-instances` を使用する方法を説明しています。

**AWS CLI**  
**スタックインスタンスを削除する方法**  
次の `delete-stack-instances` の例は、2 つのリージョンの 2 つのアカウントに設定されたスタックのインスタンスを削除し、スタックを終了します。  

```
aws cloudformation delete-stack-instances \
    --stack-set-name my-stack-set \
    --accounts 123456789012 567890123456 \
    --regions us-east-1 us-west-1 \
    --no-retain-stacks
```
出力:  

```
{
    "OperationId": "ad49f10c-fd1d-413f-a20a-8de6e2fa8f27"
}
```
空のスタックセットを削除するには、`delete-stack-set` コマンドを使用します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStackInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/delete-stack-instances.html)」を参照してください。

### `delete-stack-set`
<a name="cloudformation_DeleteStackSet_cli_2_topic"></a>

次のコード例は、`delete-stack-set` の使用方法を示しています。

**AWS CLI**  
**スタックセットを削除する方法**  
次のコマンドは、指定された空のスタックセットを削除します。スタックセットは空である必要があります。  

```
aws cloudformation delete-stack-set \
    --stack-set-name my-stack-set
```
このコマンドでは何も出力されません。  
スタックセットからインスタンスを削除するには、 `delete-stack-instances` コマンドを使用します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStackSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/delete-stack-set.html)」を参照してください。

### `delete-stack`
<a name="cloudformation_DeleteStack_cli_2_topic"></a>

次のコード例は、`delete-stack` の使用方法を示しています。

**AWS CLI**  
**スタックを削除する方法**  
以下の `delete-stack` 例は、指定されたスタックを削除します。  

```
aws cloudformation delete-stack \
    --stack-name my-stack
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/delete-stack.html)」を参照してください。

### `deploy`
<a name="cloudformation_Deploy_cli_2_topic"></a>

次のコード例は、`deploy` の使用方法を示しています。

**AWS CLI**  
次のコマンドは、「`template.json`」という名前のテンプレートを「`my-new-stack`」という名称のスタックにデプロイします。  

```
aws cloudformation deploy --template-file /path_to_template/template.json --stack-name my-new-stack --parameter-overrides Key1=Value1 Key2=Value2 --tags Key1=Value1 Key2=Value2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Deploy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deploy.html)」を参照してください。

### `deregister-type`
<a name="cloudformation_DeregisterType_cli_2_topic"></a>

次のコード例は、`deregister-type` の使用方法を示しています。

**AWS CLI**  
**タイプバージョンの登録を解除する方法**  
次の `deregister-type` の例は、CloudFormation レジストリでのアクティブな使用から指定されたタイプバージョンを削除し、CloudFormation オペレーションで使用できなくなります。  

```
aws cloudformation deregister-type \
    --type RESOURCE \
    --type-name My::Logs::LogGroup \
    --version-id 00000002
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[CloudFormation レジストリの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/deregister-type.html)」を参照してください。

### `describe-account-limits`
<a name="cloudformation_DescribeAccountLimits_cli_2_topic"></a>

次のコード例は、`describe-account-limits` の使用方法を示しています。

**AWS CLI**  
**アカウント制限に関する情報を取得する方法**  
次のコマンドは、現在のアカウントのリージョン制限のリストを取得します。  

```
aws cloudformation describe-account-limits
```
出力:  

```
{
    "AccountLimits": [
        {
            "Name": "StackLimit",
            "Value": 200
        },
        {
            "Name": "StackOutputsLimit",
            "Value": 60
        },
        {
            "Name": "ConcurrentResourcesLimit",
            "Value": 2500
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-account-limits.html)」を参照してください。

### `describe-change-set`
<a name="cloudformation_DescribeChangeSet_cli_2_topic"></a>

次のコード例は、`describe-change-set` の使用方法を示しています。

**AWS CLI**  
**変更セットについて情報を取得する方法**  
次の `describe-change-set` の例は、変更セット名とスタック名で指定された変更セットの詳細を表示します。  

```
aws cloudformation describe-change-set \
    --change-set-name my-change-set \
    --stack-name my-stack
```
次の `describe-change-set` の例は、変更セットの完全な ARN で指定された変更セットの詳細を表示します。  

```
aws cloudformation describe-change-set \
    --change-set-name arn:aws:cloudformation:us-west-2:123456789012:changeSet/my-change-set/bc9555ba-a949-xmpl-bfb8-f41d04ec5784
```
出力:  

```
{
    "Changes": [
        {
            "Type": "Resource",
            "ResourceChange": {
                "Action": "Modify",
                "LogicalResourceId": "function",
                "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
                "ResourceType": "AWS::Lambda::Function",
                "Replacement": "False",
                "Scope": [
                    "Properties"
                ],
                "Details": [
                    {
                        "Target": {
                            "Attribute": "Properties",
                            "Name": "Timeout",
                            "RequiresRecreation": "Never"
                        },
                        "Evaluation": "Static",
                        "ChangeSource": "DirectModification"
                    }
                ]
            }
        }
    ],
    "ChangeSetName": "my-change-set",
    "ChangeSetId": "arn:aws:cloudformation:us-west-2:123456789012:changeSet/my-change-set/4eca1a01-e285-xmpl-8026-9a1967bfb4b0",
    "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
    "StackName": "my-stack",
    "Description": null,
    "Parameters": null,
    "CreationTime": "2019-10-02T05:20:56.651Z",
    "ExecutionStatus": "AVAILABLE",
    "Status": "CREATE_COMPLETE",
    "StatusReason": null,
    "NotificationARNs": [],
    "RollbackConfiguration": {},
    "Capabilities": [
        "CAPABILITY_IAM"
    ],
    "Tags": null
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeChangeSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-change-set.html)」を参照してください。

### `describe-generated-template`
<a name="cloudformation_DescribeGeneratedTemplate_cli_2_topic"></a>

次の例は、`describe-generated-template` を使用する方法を説明しています。

**AWS CLI**  
**生成されたテンプレートを記述するには**  
次の `describe-generated-template` の例では、指定したテンプレートについて記述しています。  

```
aws cloudformation describe-generated-template \
    --generated-template-name MyTemplate
```
出力:  

```
{
    "GeneratedTemplateId": "arn:aws:cloudformation:us-east-1:123456789012:generatedTemplate/7d881acf-f307-4ded-910e-f8fb49b96894",
    "GeneratedTemplateName": "MyTemplate",
    "Resources": [
        {
            "ResourceType": "AWS::EC2::SecurityGroup",
            "LogicalResourceId": "EC2SecurityGroup",
            "ResourceIdentifier": {
                "Id": "sg-1234567890abcdef0"
            },
            "ResourceStatus": "COMPLETE",
            "ResourceStatusReason": "Resource Template complete",
            "Warnings": []
        },
        {
            "ResourceType": "AWS::EC2::Instance",
            "LogicalResourceId": "EC2Instance",
            "ResourceIdentifier": {
                "InstanceId": "i-1234567890abcdef0"
            },
            "ResourceStatus": "COMPLETE",
            "ResourceStatusReason": "Resource Template complete",
            "Warnings": []
        },
        {
            "ResourceType": "AWS::EC2::KeyPair",
            "LogicalResourceId": "EC2KeyPairSshkeypair",
            "ResourceIdentifier": {
                "KeyName": "sshkeypair"
            },
            "ResourceStatus": "COMPLETE",
            "ResourceStatusReason": "Resource Template complete",
            "Warnings": []
        }
    ],
    "Status": "COMPLETE",
    "StatusReason": "All resources complete",
    "CreationTime": "2025-09-23T19:38:06.435000+00:00",
    "LastUpdatedTime": "2025-09-23T19:38:10.798000+00:00",
    "Progress": {
        "ResourcesSucceeded": 3,
        "ResourcesFailed": 0,
        "ResourcesProcessing": 0,
        "ResourcesPending": 0
    },
    "TemplateConfiguration": {
        "DeletionPolicy": "RETAIN",
        "UpdateReplacePolicy": "RETAIN"
    },
    "TotalWarnings": 0
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[既存のリソースからテンプレートを生成する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGeneratedTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-generated-template.html)」を参照してください。

### `describe-publisher`
<a name="cloudformation_DescribePublisher_cli_2_topic"></a>

次の例は、`describe-publisher` を使用する方法を説明しています。

**AWS CLI**  
**パブリッシャーを記述する方法**  
次の `describe-publisher` の例は、パブリッシャーの情報を設定します。  

```
aws cloudformation describe-publisher \
    --region us-west-2 \
    --publisher-id 000q6TfUovXsEMmgKowxDZLlwqr2QUsh
```
出力:  

```
{
    "PublisherId": "000q6TfUovXsEMmgKowxDZLlwqr2QUshd2e75c8c",
    "PublisherStatus": "VERIFIED",
    "IdentityProvider": "AWS_Marketplace",
    "PublisherProfile": "https://aws.amazon.com/marketplace/seller-profile?id=2c5dc1f0-17cd-4259-8e46-822a83gdtegd"
}
```
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePublisher](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-publisher.html)」を参照してください。

### `describe-resource-scan`
<a name="cloudformation_DescribeResourceScan_cli_2_topic"></a>

次の例は、`describe-resource-scan` を使用する方法を説明しています。

**AWS CLI**  
**リソーススキャンを記述するには**  
次の `describe-resource-scan` の例では、指定されたスキャン ID を持つリソースを記述します。  

```
aws cloudformation describe-resource-scan --region \
    --resource-scan-id arn:aws:cloudformation:us-east-1:123456789012:resourceScan/0a699f15-489c-43ca-a3ef-3e6ecfa5da60
```
出力:  

```
{
    "ResourceScanId": "arn:aws:cloudformation:us-east-1:123456789012:resourceScan/0a699f15-489c-43ca-a3ef-3e6ecfa5da60",
    "Status": "COMPLETE",
    "StartTime": "2025-08-21T03:10:38.485000+00:00",
    "EndTime": "2025-08-21T03:20:28.485000+00:00",
    "PercentageCompleted": 100.0,
    "ResourceTypes": [
        "AWS::CloudFront::CachePolicy",
        "AWS::CloudFront::OriginRequestPolicy",
        "AWS::EC2::DHCPOptions",
        "AWS::EC2::InternetGateway",
        "AWS::EC2::KeyPair",
        "AWS::EC2::NetworkAcl",
        "AWS::EC2::NetworkInsightsPath",
        "AWS::EC2::NetworkInterface",
        "AWS::EC2::PlacementGroup",
        "AWS::EC2::Route",
        "AWS::EC2::RouteTable",
        "AWS::EC2::SecurityGroup",
        "AWS::EC2::Subnet",
        "AWS::EC2::SubnetCidrBlock",
        "AWS::EC2::SubnetNetworkAclAssociation",
        "AWS::EC2::SubnetRouteTableAssociation",
        ...
    ],
    "ResourcesRead": 676
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[既存のリソースからテンプレートを生成する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeResourceScan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-resource-scan.html)」を参照してください。

### `describe-stack-drift-detection-status`
<a name="cloudformation_DescribeStackDriftDetectionStatus_cli_2_topic"></a>

次の例は、`describe-stack-drift-detection-status` を使用する方法を説明しています。

**AWS CLI**  
**ドリフト検出オペレーションのステータスを確認する方法**  
次の `describe-stack-drift-detection-status` の例は、ドリフト検出オペレーションのステータスを表示します。この ID を取得するには、`detect-stack-drift` コマンドを実行します。  

```
aws cloudformation describe-stack-drift-detection-status \
    --stack-drift-detection-id 1a229160-e4d9-xmpl-ab67-0a4f93df83d4
```
出力:  

```
{
    "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
    "StackDriftDetectionId": "1a229160-e4d9-xmpl-ab67-0a4f93df83d4",
    "StackDriftStatus": "DRIFTED",
    "DetectionStatus": "DETECTION_COMPLETE",
    "DriftedStackResourceCount": 1,
    "Timestamp": "2019-10-02T05:54:30.902Z"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackDriftDetectionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-drift-detection-status.html)」を参照してください。

### `describe-stack-events`
<a name="cloudformation_DescribeStackEvents_cli_2_topic"></a>

次のコード例は、`describe-stack-events` の使用方法を示しています。

**AWS CLI**  
**スタックイベントを記述する方法**  
次の `describe-stack-events` の例は、指定されたスタックの最新イベントを 2 件表示します。  

```
aws cloudformation describe-stack-events \
    --stack-name my-stack \
    --max-items 2

{
    "StackEvents": [
        {
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "EventId": "4e1516d0-e4d6-xmpl-b94f-0a51958a168c",
            "StackName": "my-stack",
            "LogicalResourceId": "my-stack",
            "PhysicalResourceId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "ResourceType": "AWS::CloudFormation::Stack",
            "Timestamp": "2019-10-02T05:34:29.556Z",
            "ResourceStatus": "UPDATE_COMPLETE"
        },
        {
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "EventId": "4dd3c810-e4d6-xmpl-bade-0aaf8b31ab7a",
            "StackName": "my-stack",
            "LogicalResourceId": "my-stack",
            "PhysicalResourceId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "ResourceType": "AWS::CloudFormation::Stack",
            "Timestamp": "2019-10-02T05:34:29.127Z",
            "ResourceStatus": "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"
        }
    ],
    "NextToken": "eyJOZXh0VG9XMPLiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ=="
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-events.html)」を参照してください。

### `describe-stack-instance`
<a name="cloudformation_DescribeStackInstance_cli_2_topic"></a>

次のコード例は、`describe-stack-instance` の使用方法を示しています。

**AWS CLI**  
**スタックインスタンスを記述する方法**  
次のコマンドは、指定されたアカウントとリージョンで指定されたスタックセットのインスタンスについて記述します。スタックセットは現在のリージョンとアカウントにあり、インスタンスはアカウント「`123456789012`」の `us-west-2` リージョンにあります。  

```
aws cloudformation describe-stack-instance \
    --stack-set-name my-stack-set \
    --stack-instance-account 123456789012 \
    --stack-instance-region us-west-2
```
出力:  

```
{
    "StackInstance": {
        "StackSetId": "enable-config:296a3360-xmpl-40af-be78-9341e95bf743",
        "Region": "us-west-2",
        "Account": "123456789012",
        "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/StackSet-enable-config-e6cac20f-xmpl-46e9-8314-53e0d4591532/4287f9a0-e615-xmpl-894a-12b31d3117be",
        "ParameterOverrides": [],
        "Status": "OUTDATED",
        "StatusReason": "ResourceLogicalId:ConfigBucket, ResourceType:AWS::S3::Bucket, ResourceStatusReason:You have attempted to create more buckets than allowed (Service: Amazon S3; Status Code: 400; Error Code: TooManyBuckets; Request ID: F7F21CXMPL580224; S3 Extended Request ID: egd/Fdt89BXMPLyiqbMNljVk55Yqqvi3NYW2nKLUVWhUGEhNfCmZdyj967lhriaG/dWMobSO40o=)."
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-instance.html)」を参照してください。

### `describe-stack-refactor`
<a name="cloudformation_DescribeStackRefactor_cli_2_topic"></a>

次の例は、`describe-stack-refactor` を使用する方法を説明しています。

**AWS CLI**  
**スタックリファクタリングオペレーションを記述するには**  
次の `describe-stack-refactor` の例では、指定されたスタックリファクタリング ID を持つスタックリファクタリングオペレーションについて記述しています。  

```
aws cloudformation describe-stack-refactor \
    --stack-refactor-id 9c384f70-4e07-4ed7-a65d-fee5eb430841
```
出力:  

```
{
    "StackRefactorId": "9c384f70-4e07-4ed7-a65d-fee5eb430841",
    "StackIds": [
        "arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1/3e6a1ff0-94b1-11f0-aa6f-0a88d2e03acf",
        "arn:aws:cloudformation:us-east-1:123456789012:stack/Stack2/5da91650-94b1-11f0-81cf-0a23500e151b"
    ],
    "ExecutionStatus": "AVAILABLE",
    "Status": "CREATE_COMPLETE"
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[スタックリファクタリング](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-refactoring.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackRefactor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-refactor.html)」を参照してください。

### `describe-stack-resource-drifts`
<a name="cloudformation_DescribeStackResourceDrifts_cli_2_topic"></a>

次の例は、`describe-stack-resource-drifts` を使用する方法を説明しています。

**AWS CLI**  
**スタック定義からドリフトしたリソースに関する情報を取得する方法**  
次のコマンドは、指定されたスタックのドリフトされたリソースに関する情報を表示します。ドリフト検出を開始するには、 `detect-stack-drift` コマンドを使用します。  

```
aws cloudformation describe-stack-resource-drifts \
    --stack-name my-stack
```
出力には、out-of-bandに変更された AWS Lambda 関数が表示されます。  

```
{
    "StackResourceDrifts": [
        {
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "LogicalResourceId": "function",
            "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
            "ResourceType": "AWS::Lambda::Function",
            "ExpectedProperties": "{\"Description\":\"Write a file to S3.\",\"Environment\":{\"Variables\":{\"bucket\":\"my-stack-bucket-1vc62xmplgguf\"}},\"Handler\":\"index.handler\",\"MemorySize\":128,\"Role\":\"arn:aws:iam::123456789012:role/my-functionRole-HIZXMPLEOM9E\",\"Runtime\":\"nodejs10.x\",\"Tags\":[{\"Key\":\"lambda:createdBy\",\"Value\":\"SAM\"}],\"Timeout\":900,\"TracingConfig\":{\"Mode\":\"Active\"}}",
            "ActualProperties": "{\"Description\":\"Write a file to S3.\",\"Environment\":{\"Variables\":{\"bucket\":\"my-stack-bucket-1vc62xmplgguf\"}},\"Handler\":\"index.handler\",\"MemorySize\":256,\"Role\":\"arn:aws:iam::123456789012:role/my-functionRole-HIZXMPLEOM9E\",\"Runtime\":\"nodejs10.x\",\"Tags\":[{\"Key\":\"lambda:createdBy\",\"Value\":\"SAM\"}],\"Timeout\":22,\"TracingConfig\":{\"Mode\":\"Active\"}}",
            "PropertyDifferences": [
                {
                    "PropertyPath": "/MemorySize",
                    "ExpectedValue": "128",
                    "ActualValue": "256",
                    "DifferenceType": "NOT_EQUAL"
                },
                {
                    "PropertyPath": "/Timeout",
                    "ExpectedValue": "900",
                    "ActualValue": "22",
                    "DifferenceType": "NOT_EQUAL"
                }
            ],
            "StackResourceDriftStatus": "MODIFIED",
            "Timestamp": "2019-10-02T05:54:44.064Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackResourceDrifts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-resource-drifts.html)」を参照してください。

### `describe-stack-resource`
<a name="cloudformation_DescribeStackResource_cli_2_topic"></a>

次のコード例は、`describe-stack-resource` の使用方法を示しています。

**AWS CLI**  
**リソースに関する情報を取得する方法**  
次の `describe-stack-resource` の例は、指定されたスタック内にある「`MyFunction`」という名称のリソースに関する詳細情報を表示します。  

```
aws cloudformation describe-stack-resource \
    --stack-name MyStack \
    --logical-resource-id MyFunction
```
出力:  

```
{
    "StackResourceDetail": {
        "StackName": "MyStack",
        "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/MyStack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
        "LogicalResourceId": "MyFunction",
        "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
        "ResourceType": "AWS::Lambda::Function",
        "LastUpdatedTimestamp": "2019-10-02T05:34:27.989Z",
        "ResourceStatus": "UPDATE_COMPLETE",
        "Metadata": "{}",
        "DriftInformation": {
            "StackResourceDriftStatus": "IN_SYNC"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-resource.html)」を参照してください。

### `describe-stack-resources`
<a name="cloudformation_DescribeStackResources_cli_2_topic"></a>

次のコード例は、`describe-stack-resources` の使用方法を示しています。

**AWS CLI**  
**リソースに関する情報を取得する方法**  
次の `describe-stack-resources` 例は、指定されたスタック内にあるリソースの詳細情報を表示します。  

```
aws cloudformation describe-stack-resources \
    --stack-name my-stack
```
出力:  

```
{
    "StackResources": [
        {
            "StackName": "my-stack",
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "LogicalResourceId": "bucket",
            "PhysicalResourceId": "my-stack-bucket-1vc62xmplgguf",
            "ResourceType": "AWS::S3::Bucket",
            "Timestamp": "2019-10-02T04:34:11.345Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "StackName": "my-stack",
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "LogicalResourceId": "function",
            "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
            "ResourceType": "AWS::Lambda::Function",
            "Timestamp": "2019-10-02T05:34:27.989Z",
            "ResourceStatus": "UPDATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "StackName": "my-stack",
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "LogicalResourceId": "functionRole",
            "PhysicalResourceId": "my-functionRole-HIZXMPLEOM9E",
            "ResourceType": "AWS::IAM::Role",
            "Timestamp": "2019-10-02T04:34:06.350Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-resources.html)」を参照してください。

### `describe-stack-set-operation`
<a name="cloudformation_DescribeStackSetOperation_cli_2_topic"></a>

次のコード例は、`describe-stack-set-operation` の使用方法を示しています。

**AWS CLI**  
**スタックセットオペレーションに関する情報を取得する方法**  
次の describe-stack-set-operation の例は、指定されたスタックセットの更新オペレーションの詳細を表示します。  

```
aws cloudformation describe-stack-set-operation \
    --stack-set-name enable-config \
    --operation-id 35d45ebc-ed88-xmpl-ab59-0197a1fc83a0
```
出力:  

```
{
    "StackSetOperation": {
        "OperationId": "35d45ebc-ed88-xmpl-ab59-0197a1fc83a0",
        "StackSetId": "enable-config:296a3360-xmpl-40af-be78-9341e95bf743",
        "Action": "UPDATE",
        "Status": "SUCCEEDED",
        "OperationPreferences": {
            "RegionOrder": [
                "us-east-1",
                "us-west-2",
                "eu-west-1",
                "us-west-1"
            ],
            "FailureToleranceCount": 7,
            "MaxConcurrentCount": 2
        },
        "AdministrationRoleARN": "arn:aws:iam::123456789012:role/AWSCloudFormationStackSetAdministrationRole",
        "ExecutionRoleName": "AWSCloudFormationStackSetExecutionRole",
        "CreationTimestamp": "2019-10-03T16:28:44.377Z",
        "EndTimestamp": "2019-10-03T16:42:08.607Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackSetOperation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-set-operation.html)」を参照してください。

### `describe-stack-set`
<a name="cloudformation_DescribeStackSet_cli_2_topic"></a>

次のコード例は、`describe-stack-set` の使用方法を示しています。

**AWS CLI**  
**リソースに関する情報を取得する方法**  
次の describe-stack-set の例は、指定されたスタックセットに関する詳細を表示します。  

```
aws cloudformation describe-stack-set \
    --stack-set-name my-stack-set
```
出力:  

```
{
    "StackSet": {
        "StackSetName": "my-stack-set",
        "StackSetId": "my-stack-set:296a3360-xmpl-40af-be78-9341e95bf743",
        "Description": "Create an Amazon SNS topic",
        "Status": "ACTIVE",
        "TemplateBody": "AWSTemplateFormatVersion: '2010-09-09'\nDescription: An AWS SNS topic\nResources:\n  topic:\n    Type: AWS::SNS::Topic",
        "Parameters": [],
        "Capabilities": [],
        "Tags": [],
        "StackSetARN": "arn:aws:cloudformation:us-west-2:123456789012:stackset/enable-config:296a3360-xmpl-40af-be78-9341e95bf743",
        "AdministrationRoleARN": "arn:aws:iam::123456789012:role/AWSCloudFormationStackSetAdministrationRole",
        "ExecutionRoleName": "AWSCloudFormationStackSetExecutionRole"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStackSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-set.html)」を参照してください。

### `describe-stacks`
<a name="cloudformation_DescribeStacks_cli_2_topic"></a>

次の例は、`describe-stacks` を使用する方法を説明しています。

**AWS CLI**  
** AWS CloudFormation スタックを記述するには**  
以下の `describe-stacks` 例は、`myteststack` スタックの概要情報を表示します。  

```
aws cloudformation describe-stacks --stack-name myteststack
```
出力:  

```
{
    "Stacks":  [
        {
            "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896",
            "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
            "Tags": [],
            "Outputs": [
                {
                    "Description": "Name of S3 bucket to hold website content",
                    "OutputKey": "BucketName",
                    "OutputValue": "myteststack-s3bucket-jssofi1zie2w"
                }
            ],
            "StackStatusReason": null,
            "CreationTime": "2013-08-23T01:02:15.422Z",
            "Capabilities": [],
            "StackName": "myteststack",
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false
        }
    ]
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「スタック」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStacks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stacks.html)」を参照してください。

### `describe-type-registration`
<a name="cloudformation_DescribeTypeRegistration_cli_2_topic"></a>

次のコード例は、`describe-type-registration` の使用方法を示しています。

**AWS CLI**  
**タイプ登録情報を表示する方法**  
次の `describe-type-registration` の例は、タイプのステータス、タイプ、バージョンなど、指定されたタイプ登録に関する情報を表示します。  

```
aws cloudformation describe-type-registration \
    --registration-token a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "ProgressStatus": "COMPLETE",
    "TypeArn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/My-Logs-LogGroup",
    "Description": "Deployment is currently in DEPLOY_STAGE of status COMPLETED; ",
    "TypeVersionArn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/My-Logs-LogGroup/00000001"
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[CloudFormation レジストリの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTypeRegistration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-type-registration.html)」を参照してください。

### `describe-type`
<a name="cloudformation_DescribeType_cli_2_topic"></a>

次のコード例は、`describe-type` の使用方法を示しています。

**AWS CLI**  
**使用状況の情報を表示する方法**  
次の `describe-type` の例は、指定されたキーペアの情報を表示します。  

```
aws cloudformation describe-type \
    --type-name My::Logs::LogGroup \
    --type RESOURCE
```
出力:  

```
{
    "SourceUrl": "https://github.com/aws-cloudformation/aws-cloudformation-resource-providers-logs.git",
    "Description": "Customized resource derived from AWS::Logs::LogGroup",
    "TimeCreated": "2019-12-03T23:29:33.321Z",
    "Visibility": "PRIVATE",
    "TypeName": "My::Logs::LogGroup",
    "LastUpdated": "2019-12-03T23:29:33.321Z",
    "DeprecatedStatus": "LIVE",
    "ProvisioningType": "FULLY_MUTABLE",
    "Type": "RESOURCE",
    "Arn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/My-Logs-LogGroup/00000001",
    "Schema": "[details omitted]"
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[CloudFormation レジストリの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-type.html)」を参照してください。

### `detect-stack-drift`
<a name="cloudformation_DetectStackDrift_cli_2_topic"></a>

次のコード例は、`detect-stack-drift` の使用方法を示しています。

**AWS CLI**  
**ドリフトしたリソースを検出する方法**  
次の `detect-stack-drift` の例は、指定されたスタックでドリフト検出を開始します。  

```
aws cloudformation detect-stack-drift \
    --stack-name my-stack
```
出力:  

```
{
    "StackDriftDetectionId": "1a229160-e4d9-xmpl-ab67-0a4f93df83d4"
}
```
その後、 `describe-stack-resource-drifts` コマンドでこの ID を使用してドリフトされたリソースを記述できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectStackDrift](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/detect-stack-drift.html)」を参照してください。

### `detect-stack-resource-drift`
<a name="cloudformation_DetectStackResourceDrift_cli_2_topic"></a>

次のコード例は、`detect-stack-resource-drift` の使用方法を示しています。

**AWS CLI**  
**リソースのドリフトを検出する方法**  
次の `detect-stack-resource-drift` の例は、ドリフト用に「`MyStack`」という名前のスタックで「`MyFunction`」という名称のリソースをチェックします。  

```
aws cloudformation detect-stack-resource-drift \
   --stack-name MyStack \
   --logical-resource-id MyFunction
```
出力には、out-of-bandに変更された AWS Lambda 関数が表示されます。  

```
{
    "StackResourceDrift": {
        "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
        "LogicalResourceId": "MyFunction",
        "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
        "ResourceType": "AWS::Lambda::Function",
        "ExpectedProperties": "{\"Description\":\"Write a file to S3.\",\"Environment\":{\"Variables\":{\"bucket\":\"my-stack-bucket-1vc62xmplgguf\"}},\"Handler\":\"index.handler\",\"MemorySize\":128,\"Role\":\"arn:aws:iam::123456789012:role/my-functionRole-HIZXMPLEOM9E\",\"Runtime\":\"nodejs10.x\",\"Tags\":[{\"Key\":\"lambda:createdBy\",\"Value\":\"SAM\"}],\"Timeout\":900,\"TracingConfig\":{\"Mode\":\"Active\"}}",
        "ActualProperties": "{\"Description\":\"Write a file to S3.\",\"Environment\":{\"Variables\":{\"bucket\":\"my-stack-bucket-1vc62xmplgguf\"}},\"Handler\":\"index.handler\",\"MemorySize\":256,\"Role\":\"arn:aws:iam::123456789012:role/my-functionRole-HIZXMPLEOM9E\",\"Runtime\":\"nodejs10.x\",\"Tags\":[{\"Key\":\"lambda:createdBy\",\"Value\":\"SAM\"}],\"Timeout\":22,\"TracingConfig\":{\"Mode\":\"Active\"}}",
        "PropertyDifferences": [
            {
                "PropertyPath": "/MemorySize",
                "ExpectedValue": "128",
                "ActualValue": "256",
                "DifferenceType": "NOT_EQUAL"
            },
            {
                "PropertyPath": "/Timeout",
                "ExpectedValue": "900",
                "ActualValue": "22",
                "DifferenceType": "NOT_EQUAL"
            }
        ],
        "StackResourceDriftStatus": "MODIFIED",
        "Timestamp": "2019-10-02T05:58:47.433Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectStackResourceDrift](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/detect-stack-resource-drift.html)」を参照してください。

### `detect-stack-set-drift`
<a name="cloudformation_DetectStackSetDrift_cli_2_topic"></a>

次のコード例は、`detect-stack-set-drift` の使用方法を示しています。

**AWS CLI**  
**スタックセットと、関連するスタックインスタンスのドリフトを検出する方法**  
次の `detect-stack-set-drift` の例は、指定されたスタックセットに対で、そのスタックセットに関連付けられたすべてのスタックインスタンスを含むドリフト検出オペレーションを開始し、ドリフトオペレーションのステータスを追跡するために使用できるオペレーション ID を返します。  

```
aws cloudformation detect-stack-set-drift \
    --stack-set-name stack-set-drift-example
```
出力:  

```
{
    "OperationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、*「AWS CloudFormation ユーザーガイド」*の[「スタックセットにおける管理されていない設定変更の検出」](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-drift.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectStackSetDrift](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/detect-stack-set-drift.html)」を参照してください。

### `estimate-template-cost`
<a name="cloudformation_EstimateTemplateCost_cli_2_topic"></a>

次のコード例は、`estimate-template-cost` の使用方法を示しています。

**AWS CLI**  
**テンプレートコストを見積もる方法**  
以下の `estimate-template-cost` の例は、現在のフォルダ内にある「`template.yaml`」という名称のテンプレートに関するコスト見積もりを生成します。  

```
aws cloudformation estimate-template-cost \
    --template-body file://template.yaml
```
出力:  

```
{
    "Url": "http://calculator.s3.amazonaws.com/calc5.html?key=cloudformation/7870825a-xmpl-4def-92e7-c4f8dd360cca"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EstimateTemplateCost](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/estimate-template-cost.html)」を参照してください。

### `execute-change-set`
<a name="cloudformation_ExecuteChangeSet_cli_2_topic"></a>

次のコード例は、`execute-change-set` の使用方法を示しています。

**AWS CLI**  
**変更セットを実行する方法**  
次の `execute-change-set` の例は、変更セット名とスタック名によって指定された変更セットを実行します。  

```
aws cloudformation execute-change-set \
    --change-set-name my-change-set \
    --stack-name my-stack
```
次の `execute-change-set` の例は、変更セットの完全な ARN で指定された変更セットを実行します。  

```
aws cloudformation execute-change-set \
    --change-set-name arn:aws:cloudformation:us-west-2:123456789012:changeSet/my-change-set/bc9555ba-a949-xmpl-bfb8-f41d04ec5784
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExecuteChangeSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/execute-change-set.html)」を参照してください。

### `execute-stack-refactor`
<a name="cloudformation_ExecuteStackRefactor_cli_2_topic"></a>

次の例は、`execute-stack-refactor` を使用する方法を説明しています。

**AWS CLI**  
**スタックリファクタリングオペレーションを完了するには**  
次の `execute-stack-refactor` の例では、指定されたスタックリファクタリング ID を使用してスタックリファクタリングオペレーションを完了します。  

```
aws cloudformation execute-stack-refactor \
    --stack-refactor-id 9c384f70-4e07-4ed7-a65d-fee5eb430841
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[スタックリファクタリング](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-refactoring.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExecuteStackRefactor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/execute-stack-refactor.html)」を参照してください。

### `get-stack-policy`
<a name="cloudformation_GetStackPolicy_cli_2_topic"></a>

次の例は、`get-stack-policy` を使用する方法を説明しています。

**AWS CLI**  
**スタックポリシーを表示する方法**  
次の `get-stack-policy` の例は、指定されたスタック用のスタックポリシーを表示します。ポリシーをスタックにアタッチするには、`set-stack-policy` コマンドを使用します。  

```
aws cloudformation get-stack-policy \
    --stack-name my-stack
```
出力:  

```
{
    "StackPolicyBody": "{\n  \"Statement\" : [\n    {\n      \"Effect\" : \"Allow\",\n      \"Action\" : \"Update:*\",\n      \"Principal\": \"*\",\n      \"Resource\" : \"*\"\n    },\n    {\n      \"Effect\" : \"Deny\",\n      \"Action\" : \"Update:*\",\n      \"Principal\": \"*\",\n      \"Resource\" : \"LogicalResourceId/bucket\"\n    }\n  ]\n}\n"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStackPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/get-stack-policy.html)」を参照してください。

### `get-template-summary`
<a name="cloudformation_GetTemplateSummary_cli_2_topic"></a>

次のコード例は、`get-template-summary` の使用方法を示しています。

**AWS CLI**  
**テンプレートの概要を表示する方法**  
次のコマンドは、指定されたテンプレートファイルのリソースとメタデータに関する概要情報を示しています。  

```
aws cloudformation get-template-summary \
   --template-body file://template.yaml
```
出力:  

```
{
    "Parameters": [],
    "Description": "A VPC and subnets.",
    "ResourceTypes": [
        "AWS::EC2::VPC",
        "AWS::EC2::Subnet",
        "AWS::EC2::Subnet",
        "AWS::EC2::RouteTable",
        "AWS::EC2::VPCEndpoint",
        "AWS::EC2::SubnetRouteTableAssociation",
        "AWS::EC2::SubnetRouteTableAssociation",
        "AWS::EC2::VPCEndpoint"
    ],
    "Version": "2010-09-09"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTemplateSummary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/get-template-summary.html)」を参照してください。

### `get-template`
<a name="cloudformation_GetTemplate_cli_2_topic"></a>

次の例は、`get-template` を使用する方法を説明しています。

**AWS CLI**  
** AWS CloudFormation スタックのテンプレート本文を表示するには**  
以下の `get-template` の例は、`myteststack` スタックのテンプレートを示しています。  

```
aws cloudformation get-template --stack-name myteststack
```
出力:  

```
{
    "TemplateBody": {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Outputs": {
            "BucketName": {
                "Description": "Name of S3 bucket to hold website content",
                "Value": {
                    "Ref": "S3Bucket"
                }
            }
        },
        "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
        "Resources": {
            "S3Bucket": {
                "Type": "AWS::S3::Bucket",
                "Properties": {
                    "AccessControl": "PublicRead"
                }
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/get-template.html)」を参照してください。

### `list-change-sets`
<a name="cloudformation_ListChangeSets_cli_2_topic"></a>

次のコード例は、`list-change-sets` の使用方法を示しています。

**AWS CLI**  
**変更セットを一覧表示する方法**  
次の `list-change-sets` の例は、指定されたスタックの保留中の変更セットの一覧を表示します。  

```
aws cloudformation list-change-sets \
   --stack-name my-stack
```
出力:  

```
{
    "Summaries": [
        {
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "StackName": "my-stack",
            "ChangeSetId": "arn:aws:cloudformation:us-west-2:123456789012:changeSet/my-change-set/70160340-7914-xmpl-bcbf-128a1fa78b5d",
            "ChangeSetName": "my-change-set",
            "ExecutionStatus": "AVAILABLE",
            "Status": "CREATE_COMPLETE",
            "CreationTime": "2019-10-02T05:38:54.297Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListChangeSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-change-sets.html)」を参照してください。

### `list-exports`
<a name="cloudformation_ListExports_cli_2_topic"></a>

次のコード例は、`list-exports` の使用方法を示しています。

**AWS CLI**  
**エクスポートを一覧表示する方法**  
次の `list-exports` の例は、現在のリージョンのスタックからのエクスポートを一覧表示します。  

```
aws cloudformation list-exports
```
出力:  

```
{
    "Exports": [
        {
            "ExportingStackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/private-vpc/99764070-b56c-xmpl-bee8-062a88d1d800",
            "Name": "private-vpc-subnet-a",
            "Value": "subnet-07b410xmplddcfa03"
        },
        {
            "ExportingStackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/private-vpc/99764070-b56c-xmpl-bee8-062a88d1d800",
            "Name": "private-vpc-subnet-b",
            "Value": "subnet-075ed3xmplebd2fb1"
        },
        {
            "ExportingStackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/private-vpc/99764070-b56c-xmpl-bee8-062a88d1d800",
            "Name": "private-vpc-vpcid",
            "Value": "vpc-011d7xmpl100e9841"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListExports](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-exports.html)」を参照してください。

### `list-generated-templates`
<a name="cloudformation_ListGeneratedTemplates_cli_2_topic"></a>

次の例は、`list-generated-templates` を使用する方法を説明しています。

**AWS CLI**  
**生成されたテンプレートを一覧表示するには**  
次の `list-generated-templates` の例では、すべての生成されたテンプレートを一覧表示します。  

```
aws cloudformation list-generated-templates
```
出力:  

```
{
    "Summaries": [
        {
            "GeneratedTemplateId": "arn:aws:cloudformation:us-east-1:123456789012:generatedtemplate/7fc8512c-d8cb-4e02-b266-d39c48344e48",
            "GeneratedTemplateName": "MyTemplate",
            "Status": "COMPLETE",
            "StatusReason": "All resources complete",
            "CreationTime": "2025-09-23T20:13:24.283000+00:00",
            "LastUpdatedTime": "2025-09-23T20:13:28.610000+00:00",
            "NumberOfResources": 4
        },
        {
            "GeneratedTemplateId": "arn:aws:cloudformation:us-east-1:123456789012:generatedTemplate/f10dd1c4-edc6-4823-8153-ab6112b8d051",
            "GeneratedTemplateName": "MyEC2InstanceTemplate",
            "Status": "COMPLETE",
            "StatusReason": "All resources complete",
            "CreationTime": "2024-08-08T19:35:49.790000+00:00",
            "LastUpdatedTime": "2024-08-08T19:35:52.207000+00:00",
            "NumberOfResources": 3
        },
        {
            "GeneratedTemplateId": "arn:aws:cloudformation:us-east-1:123456789012:generatedTemplate/e5a1c89f-7ce2-41bd-9bdf-75b7c852e3ca",
            "GeneratedTemplateName": "MyEKSNodeGroupTemplate",
            "Status": "COMPLETE",
            "StatusReason": "All resources complete",
            "CreationTime": "2024-07-16T20:39:27.883000+00:00",
            "LastUpdatedTime": "2024-07-16T20:39:35.766000+00:00",
            "NumberOfResources": 4
        }
    ]
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[既存のリソースからテンプレートを生成する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/generate-IaC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGeneratedTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-generated-templates.html)」を参照してください。

### `list-imports`
<a name="cloudformation_ListImports_cli_2_topic"></a>

次の例は、`list-imports` を使用する方法を説明しています。

**AWS CLI**  
**インポートを一覧表示する方法**  
次の `list-imports` の例は、指定されたエクスポートをインポートするスタックを一覧表示します。使用可能なエクスポートの一覧を取得するには、 `list-exports` コマンドを使用します。  

```
aws cloudformation list-imports \
    --export-name private-vpc-vpcid
```
出力:  

```
{
    "Imports": [
        "my-database-stack"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListImports](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-imports.html)」を参照してください。

### `list-resource-scan-related-resources`
<a name="cloudformation_ListResourceScanRelatedResources_cli_2_topic"></a>

次の例は、`list-resource-scan-related-resources` を使用する方法を説明しています。

**AWS CLI**  
**リソーススキャンから関連リソースを一覧表示するには**  
次の `list-resource-scan-related-resources` の例では、`resources.json` のリソースに関連する指定されたリソーススキャンのリソースを一覧表示します。  

```
aws cloudformation list-resource-scan-related-resources \
    --resource-scan-id arn:aws:cloudformation:us-east-1:123456789012:resourceScan/0a699f15-489c-43ca-a3ef-3e6ecfa5da60 \
    --resources file://resources.json
```
`resources.json` の内容:  

```
[
    {
        "ResourceType": "AWS::EKS::Cluster",
        "ResourceIdentifier": {
            "ClusterName": "MyAppClusterName"
        }
    },
    {
        "ResourceType": "AWS::AutoScaling::AutoScalingGroup",
        "ResourceIdentifier": {
            "AutoScalingGroupName": "MyAppASGName"
        }
    }
]
```
出力:  

```
{
    "RelatedResources": [
        {
            "ResourceType": "AWS::EKS::Nodegroup",
            "ResourceIdentifier": {
                "NodegroupName": "MyAppNodegroupName"
            },
            "ManagedByStack": false
        },
        {
            "ResourceType": "AWS::IAM::Role",
            "ResourceIdentifier": {
                "RoleId": "arn:aws::iam::123456789012:role/MyAppIAMRole"
            },
            "ManagedByStack": false
        }
    ]
}
```
詳細については、「AWS CloudFormation ユーザーガイド」の「[IaC ジェネレーターでスキャンされたリソースから CloudFormation テンプレートを作成する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/iac-generator-create-template-from-scanned-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceScanRelatedResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-resource-scan-related-resources.html)」を参照してください。

### `list-resource-scan-resources`
<a name="cloudformation_ListResourceScanResources_cli_2_topic"></a>

次の例は、`list-resource-scan-resources` を使用する方法を説明しています。

**AWS CLI**  
**リソーススキャンからリソースを一覧表示するには**  
次の `list-resource-scan-resources` の例では、指定されたリソーススキャンのリソースを、リソース識別子でフィルタリングして一覧表示します。  

```
aws cloudformation list-resource-scan-resources \
    --resource-scan-id arn:aws:cloudformation:us-east-1:123456789012:resourceScan/0a699f15-489c-43ca-a3ef-3e6ecfa5da60 \
    --resource-identifier MyApp
```
出力:  

```
{
    "Resources": [
        {
            "ResourceType": "AWS::EKS::Cluster",
            "ResourceIdentifier": {
                "ClusterName": "MyAppClusterName"
            },
            "ManagedByStack": false
        },
        {
            "ResourceType": "AWS::AutoScaling::AutoScalingGroup",
            "ResourceIdentifier": {
                "AutoScalingGroupName": "MyAppASGName"
            },
            "ManagedByStack": false
        }
    ]
}
```
詳細については、「AWS CloudFormation ユーザーガイド」の「[IaC ジェネレーターでスキャンされたリソースから CloudFormation テンプレートを作成する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/iac-generator-create-template-from-scanned-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceScanResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-resource-scan-resources.html)」を参照してください。

### `list-stack-instances`
<a name="cloudformation_ListStackInstances_cli_2_topic"></a>

次の例は、`list-stack-instances` を使用する方法を説明しています。

**AWS CLI**  
**スタックのインスタンスを一覧表示する方法**  
次の `list-stack-instances` の例は、指定されたスタックセットから作成されたインスタンスを一覧表示します。  

```
aws cloudformation list-stack-instances \
    --stack-set-name enable-config
```
サンプル出力には、エラーが原因で更新に失敗したスタックに関する詳細が含まれます。  

```
{
    "Summaries": [
        {
            "StackSetId": "enable-config:296a3360-xmpl-40af-be78-9341e95bf743",
            "Region": "us-west-2",
            "Account": "123456789012",
            "StackId": "arn:aws:cloudformation:ap-northeast-1:123456789012:stack/StackSet-enable-config-35a6ac50-d9f8-4084-86e4-7da34d5de4c4/a1631cd0-e5fb-xmpl-b474-0aa20f14f06e",
            "Status": "CURRENT"
        },
        {
            "StackSetId": "enable-config:296a3360-xmpl-40af-be78-9341e95bf743",
            "Region": "us-west-2",
            "Account": "123456789012",
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/StackSet-enable-config-e6cac20f-xmpl-46e9-8314-53e0d4591532/eab53680-e5fa-xmpl-ba14-0a522351f81e",
            "Status": "OUTDATED",
            "StatusReason": "ResourceLogicalId:ConfigDeliveryChannel, ResourceType:AWS::Config::DeliveryChannel, ResourceStatusReason:Failed to put delivery channel 'StackSet-enable-config-e6cac20f-xmpl-46e9-8314-53e0d4591532-ConfigDeliveryChannel-1OJWJ7XD59WR0' because the maximum number of delivery channels: 1 is reached. (Service: AmazonConfig; Status Code: 400; Error Code: MaxNumberOfDeliveryChannelsExceededException; Request ID: d14b34a0-ef7c-xmpl-acf8-8a864370ae56)."
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStackInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stack-instances.html)」を参照してください。

### `list-stack-refactor-actions`
<a name="cloudformation_ListStackRefactorActions_cli_2_topic"></a>

次の例は、`list-stack-refactor-actions` を使用する方法を説明しています。

**AWS CLI**  
**スタックリファクタリングオペレーションのアクションを一覧表示するには**  
次の `list-stack-refactor-actions` の例では、指定されたスタックリファクタリング ID を持つスタックリファクタリングオペレーションのアクションを一覧表示します。  

```
aws cloudformation list-stack-refactor-actions \
    --stack-refactor-id 9c384f70-4e07-4ed7-a65d-fee5eb430841
```
出力:  

```
{
    "StackRefactorActions": [
        {
            "Action": "MOVE",
            "Entity": "RESOURCE",
            "PhysicalResourceId": "MyTestLambdaRole",
            "Description": "No configuration changes detected.",
            "Detection": "AUTO",
            "TagResources": [],
            "UntagResources": [],
            "ResourceMapping": {
                "Source": {
                    "StackName": "arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1/3e6a1ff0-94b1-11f0-aa6f-0a88d2e03acf",
                    "LogicalResourceId": "MyLambdaRole"
                },
                "Destination": {
                    "StackName": "arn:aws:cloudformation:us-east-1:123456789012:stack/Stack2/5da91650-94b1-11f0-81cf-0a23500e151b",
                    "LogicalResourceId": "MyLambdaRole"
                }
            }
        },
        {
            "Action": "MOVE",
            "Entity": "RESOURCE",
            "PhysicalResourceId": "MyTestFunction",
            "Description": "Resource configuration changes will be validated during refactor execution.",
            "Detection": "AUTO",
            "TagResources": [
                {
                    "Key": "aws:cloudformation:stack-name",
                    "Value": "Stack2"
                },
                {
                    "Key": "aws:cloudformation:logical-id",
                    "Value": "MyFunction"
                },
                {
                    "Key": "aws:cloudformation:stack-id",
                    "Value": "arn:aws:cloudformation:us-east-1:123456789012:stack/Stack2/5da91650-94b1-11f0-81cf-0a23500e151b"
                }
            ],
            "UntagResources": [
                "aws:cloudformation:stack-name",
                "aws:cloudformation:logical-id",
                "aws:cloudformation:stack-id"
            ],
            "ResourceMapping": {
                "Source": {
                    "StackName": "arn:aws:cloudformation:us-east-1:123456789012:stack/Stack1/3e6a1ff0-94b1-11f0-aa6f-0a88d2e03acf",
                    "LogicalResourceId": "MyFunction"
                },
                "Destination": {
                    "StackName": "arn:aws:cloudformation:us-east-1:123456789012:stack/Stack2/5da91650-94b1-11f0-81cf-0a23500e151b",
                    "LogicalResourceId": "MyFunction"
                }
            }
        }
    ]
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[スタックリファクタリング](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-refactoring.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStackRefactorActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stack-refactor-actions.html)」を参照してください。

### `list-stack-resources`
<a name="cloudformation_ListStackResources_cli_2_topic"></a>

次の例は、`list-stack-resources` を使用する方法を説明しています。

**AWS CLI**  
**スタック内のリソースを一覧表示する方法**  
以下のコマンドは、指定されたスタック内にあるリソースを一覧表示します。  

```
aws cloudformation list-stack-resources \
    --stack-name my-stack
```
出力:  

```
{
    "StackResourceSummaries": [
        {
            "LogicalResourceId": "bucket",
            "PhysicalResourceId": "my-stack-bucket-1vc62xmplgguf",
            "ResourceType": "AWS::S3::Bucket",
            "LastUpdatedTimestamp": "2019-10-02T04:34:11.345Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "LogicalResourceId": "function",
            "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
            "ResourceType": "AWS::Lambda::Function",
            "LastUpdatedTimestamp": "2019-10-02T05:34:27.989Z",
            "ResourceStatus": "UPDATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "LogicalResourceId": "functionRole",
            "PhysicalResourceId": "my-functionRole-HIZXMPLEOM9E",
            "ResourceType": "AWS::IAM::Role",
            "LastUpdatedTimestamp": "2019-10-02T04:34:06.350Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStackResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stack-resources.html)」を参照してください。

### `list-stack-set-operation-results`
<a name="cloudformation_ListStackSetOperationResults_cli_2_topic"></a>

次のコード例は、`list-stack-set-operation-results` の使用方法を示しています。

**AWS CLI**  
**スタックセットオペレーション結果を一覧表示する方法**  
次のコマンドは、指定されたスタックセット内のインスタンスに対する更新オペレーションの結果を表示します。  

```
aws cloudformation list-stack-set-operation-results \
    --stack-set-name enable-config \
    --operation-id 35d45ebc-ed88-xmpl-ab59-0197a1fc83a0
```
出力:  

```
{
    "Summaries": [
        {
            "Account": "223456789012",
            "Region": "us-west-2",
            "Status": "SUCCEEDED",
            "AccountGateResult": {
                "Status": "SKIPPED",
                "StatusReason": "Function not found: arn:aws:lambda:eu-west-1:223456789012:function:AWSCloudFormationStackSetAccountGate"
            }
        },
        {
            "Account": "223456789012",
            "Region": "ap-south-1",
            "Status": "CANCELLED",
            "StatusReason": "Cancelled since failure tolerance has exceeded"
        }
    ]
}
```
**注:** アカウントゲート関数を作成しない限り、`AccountGateResult` の `SKIPPED` ステータスが正常なオペレーションとなります。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStackSetOperationResults](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stack-set-operation-results.html)」を参照してください。

### `list-stack-set-operations`
<a name="cloudformation_ListStackSetOperations_cli_2_topic"></a>

次のコード例は、`list-stack-set-operations` の使用方法を示しています。

**AWS CLI**  
**スタックセットオペレーションを一覧表示する方法**  
次の `list-stack-set-operations` の例は、指定されたスタックセットの最新のオペレーションを一覧表示します。  

```
aws cloudformation list-stack-set-operations \
    --stack-set-name my-stack-set
```
出力:  

```
{
    "Summaries": [
        {
            "OperationId": "35d45ebc-ed88-xmpl-ab59-0197a1fc83a0",
            "Action": "UPDATE",
            "Status": "SUCCEEDED",
            "CreationTimestamp": "2019-10-03T16:28:44.377Z",
            "EndTimestamp": "2019-10-03T16:42:08.607Z"
        },
        {
            "OperationId": "891aa98f-7118-xmpl-00b2-00954d1dd0d6",
            "Action": "UPDATE",
            "Status": "FAILED",
            "CreationTimestamp": "2019-10-03T15:43:53.916Z",
            "EndTimestamp": "2019-10-03T15:45:58.925Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStackSetOperations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stack-set-operations.html)」を参照してください。

### `list-stack-sets`
<a name="cloudformation_ListStackSets_cli_2_topic"></a>

次のコード例は、`list-stack-sets` の使用方法を示しています。

**AWS CLI**  
**スタックセットを一覧表示する方法**  
次の `list-stack-sets` の例は、現在のリージョンとアカウントのスタックセットを一覧表示します。  

```
aws cloudformation list-stack-sets
```
出力:  

```
{
    "Summaries": [
        {
            "StackSetName": "enable-config",
            "StackSetId": "enable-config:296a3360-xmpl-40af-be78-9341e95bf743",
            "Description": "Enable AWS Config",
            "Status": "ACTIVE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStackSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stack-sets.html)」を参照してください。

### `list-stacks`
<a name="cloudformation_ListStacks_cli_2_topic"></a>

次の例は、`list-stacks` を使用する方法を説明しています。

**AWS CLI**  
** AWS CloudFormation スタックを一覧表示するには**  
以下の `list-stacks` コマンドは、ステータスが `CREATE_COMPLETE` になっているすべてのスタックの概要を表示します。  

```
aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE
```
出力:  

```
[
    {
        "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896",
        "TemplateDescription": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
        "StackStatusReason": null,
        "CreationTime": "2013-08-26T03:27:10.190Z",
        "StackName": "myteststack",
        "StackStatus": "CREATE_COMPLETE"
    }
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStacks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stacks.html)」を参照してください。

### `list-type-registrations`
<a name="cloudformation_ListTypeRegistrations_cli_2_topic"></a>

次のコード例は、`list-type-registrations` の使用方法を示しています。

**AWS CLI**  
**タイプの登録完了済みを一覧表示する方法**  
次の `list-type-registrations` の例は、指定されたタイプの完了したタイプ登録を一覧表示します。  

```
aws cloudformation list-type-registrations \
    --type RESOURCE \
    --type-name My::Logs::LogGroup \
    --registration-status-filter COMPLETE
```
出力:  

```
{
    "RegistrationTokenList": [
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333"
    ]
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[CloudFormation レジストリの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTypeRegistrations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-type-registrations.html)」を参照してください。

### `list-type-versions`
<a name="cloudformation_ListTypeVersions_cli_2_topic"></a>

次のコード例は、`list-type-versions` の使用方法を示しています。

**AWS CLI**  
**拡張機能のバージョンを一覧表示する方法**  
次の `list-type-versions` の例は、拡張機能のバージョンに関する概要情報を返します。  

```
aws cloudformation list-type-versions \
  --endpoint https://example.com \
  --region us-west-2 \
  --type RESOURCE \
  --type-name My::Resource::Example \
  --publisher-id 123456789012
```
このコマンドでは何も出力されません。  
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTypeVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-type-versions.html)」を参照してください。

### `list-types`
<a name="cloudformation_ListTypes_cli_2_topic"></a>

次のコード例は、`list-types` の使用方法を示しています。

**AWS CLI**  
**アカウントのプライベートリソースタイプを一覧表示する方法**  
次の の`list-types`例では、現在の AWS アカウントで現在登録されているプライベートリソースタイプのリストを表示します。  

```
aws cloudformation list-types
```
出力:  

```
{
    "TypeSummaries": [
        {
            "Description": "WordPress blog resource for internal use",
            "LastUpdated": "2019-12-04T18:28:15.059Z",
            "TypeName": "My::WordPress::BlogExample",
            "TypeArn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/My-WordPress-BlogExample",
            "DefaultVersionId": "00000005",
            "Type": "RESOURCE"
        },
        {
            "Description": "Customized resource derived from AWS::Logs::LogGroup",
            "LastUpdated": "2019-12-04T18:28:15.059Z",
            "TypeName": "My::Logs::LogGroup",
            "TypeArn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/My-Logs-LogGroup",
            "DefaultVersionId": "00000003",
            "Type": "RESOURCE"
        }
    ]
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[CloudFormation レジストリの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-types.html)」を参照してください。

### `package`
<a name="cloudformation_Package_cli_2_topic"></a>

次のコード例は、`package` の使用方法を示しています。

**AWS CLI**  
次のコマンドは、ローカルアーティファクトを S3 バケット `bucket-name` にアップロードして「`template.json`」という名称のテンプレートをエクスポートし、エクスポートされたテンプレートを `packaged-template.json` に書き込みます。  

```
aws cloudformation package --template-file /path_to_template/template.json --s3-bucket bucket-name --output-template-file packaged-template.json --use-json
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Package](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/package.html)」を参照してください。

### `publish-type`
<a name="cloudformation_PublishType_cli_2_topic"></a>

次のコード例は、`publish-type` の使用方法を示しています。

**AWS CLI**  
**拡張機能を公開する方法**  
次の `publish-type` の例は、指定された拡張機能を CloudFormation レジストリにこのリージョンのパブリック拡張機能として公開します。  

```
aws cloudformation publish-type \
  --region us-west-2 \
  --type RESOURCE \
  --type-name Example::Test::1234567890abcdef0
```
出力:  

```
{
    "PublicTypeArn":"arn:aws:cloudformation:us-west-2::type/resource/000q6TfUovXsEMmgKowxDZLlwqr2QUshd2e75c8c/Example-Test-1234567890abcdef0/1.0.0"
}
```
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PublishType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/publish-type.html)」を参照してください。

### `register-publisher`
<a name="cloudformation_RegisterPublisher_cli_2_topic"></a>

次のコード例は、`register-publisher` の使用方法を示しています。

**AWS CLI**  
**パブリッシャーを登録する方法**  
次の `register-publisher` の例は、パブリッシャーを登録し、利用規約パラメータを受け入れます。  

```
aws cloudformation register-publisher \
  --region us-west-2 \
  --accept-terms-and-conditions
```
出力:  

```
{
    "PublisherId": "000q6TfUovXsEMmgKowxDZLlwqr2QUshd2e75c8c"
}
```
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterPublisher](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/register-publisher.html)」を参照してください。

### `register-type`
<a name="cloudformation_RegisterType_cli_2_topic"></a>

次のコード例は、`register-type` の使用方法を示しています。

**AWS CLI**  
**リソースタイプを登録する方法**  
次の `register-type` の例は、指定されたリソースタイプをユーザーのアカウントにプライベートリソースタイプとして登録します。  

```
aws cloudformation register-type \
    --type-name My::Organization::ResourceName \
    --schema-handler-package s3://bucket_name/my-organization-resource_name.zip \
    --type RESOURCE
```
出力:  

```
{
    "RegistrationToken": "f5525280-104e-4d35-bef5-8f1f1example"
}
```
詳細については、「*CloudFormation コマンドラインインターフェイスユーザーガイド*」の「[リソースプロバイダーの登録](https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/resource-type-register.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/register-type.html)」を参照してください。

### `set-stack-policy`
<a name="cloudformation_SetStackPolicy_cli_2_topic"></a>

次のコード例は、`set-stack-policy` の使用方法を示しています。

**AWS CLI**  
**スタックポリシーを適用する方法**  
次の `set-stack-policy` の例は、指定されたスタック内の指定されたリソースの更新を無効にします。`stack-policy.json` は、スタック内のリソースで許可されるオペレーションを定義する JSON ドキュメントです。  

```
aws cloudformation set-stack-policy \
    --stack-name my-stack \
    --stack-policy-body file://stack-policy.json
```
出力:  

```
{
  "Statement" : [
    {
      "Effect" : "Allow",
      "Action" : "Update:*",
      "Principal": "*",
      "Resource" : "*"
    },
    {
      "Effect" : "Deny",
      "Action" : "Update:*",
      "Principal": "*",
      "Resource" : "LogicalResourceId/bucket"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetStackPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/set-stack-policy.html)」を参照してください。

### `set-type-configuration`
<a name="cloudformation_SetTypeConfiguration_cli_2_topic"></a>

次のコード例は、`set-type-configuration` の使用方法を示しています。

**AWS CLI**  
**データを設定する方法**  
次の `set-type-configuration` の例は、指定されたアカウントとリージョンに登録された CloudFormation 拡張機能の設定データを指定します。  

```
aws cloudformation set-type-configuration \
    --region us-west-2 \
    --type RESOURCE \
    --type-name Example::Test::Type \
    --configuration-alias default \
    --configuration "{\"CredentialKey\": \"testUserCredential\"}"
```
出力:  

```
{
    "ConfigurationArn": "arn:aws:cloudformation:us-west-2:123456789012:type-configuration/resource/Example-Test-Type/default"
}
```
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetTypeConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/set-type-configuration.html)」を参照してください。

### `set-type-default-version`
<a name="cloudformation_SetTypeDefaultVersion_cli_2_topic"></a>

次のコード例は、`set-type-default-version` の使用方法を示しています。

**AWS CLI**  
**タイプのデフォルトバージョンを設定する方法**  
次の `set-type-default-version` の例は、このタイプのデフォルトとして使用するように指定されたタイプバージョンを設定します。  

```
aws cloudformation set-type-default-version \
    --type RESOURCE \
    --type-name My::Logs::LogGroup \
    --version-id 00000003
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[CloudFormation レジストリの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetTypeDefaultVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/set-type-default-version.html)」を参照してください。

### `signal-resource`
<a name="cloudformation_SignalResource_cli_2_topic"></a>

次のコード例は、`signal-resource` の使用方法を示しています。

**AWS CLI**  
**リソースにシグナルを送信する方法**  
次の `signal-resource` の例は、「`my-stack`」という名称のスタックで「`MyWaitCondition`」という名称の待機条件を満たすように `success` にシグナルを送信します。  

```
aws cloudformation signal-resource \
    --stack-name my-stack \
    --logical-resource-id MyWaitCondition \
    --unique-id 1234 \
    --status SUCCESS
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SignalResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/signal-resource.html)」を参照してください。

### `start-resource-scan`
<a name="cloudformation_StartResourceScan_cli_2_topic"></a>

次の例は、`start-resource-scan` を使用する方法を説明しています。

**AWS CLI**  
**リソーススキャンを開始するには**  
次の `start-resource-scan` の例では、現在のアカウントとリージョン内のすべての既存のリソースをスキャンするリソーススキャンを開始します。  

```
aws cloudformation start-resource-scan
```
出力:  

```
{
    "ResourceScanId":
      "arn:aws:cloudformation:us-east-1:123456789012:resourceScan/0a699f15-489c-43ca-a3ef-3e6ecfa5da60"
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[CloudFormation IaC ジェネレーターを使用してリソーススキャンを開始する](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/iac-generator-start-resource-scan.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartResourceScan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/start-resource-scan.html)」を参照してください。

### `stop-stack-set-operation`
<a name="cloudformation_StopStackSetOperation_cli_2_topic"></a>

次の例は、`stop-stack-set-operation` を使用する方法を説明しています。

**AWS CLI**  
**スタックセットオペレーションを停止する方法**  
次の `stop-stack-set-operation` の例は、指定されたスタックセットの進行中の更新オペレーションを停止します。  

```
aws cloudformation stop-stack-set-operation \
    --stack-set-name my-stack-set \
    --operation-id 1261cd27-490b-xmpl-ab42-793a896c69e6
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopStackSetOperation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/stop-stack-set-operation.html)」を参照してください。

### `test-type`
<a name="cloudformation_TestType_cli_2_topic"></a>

次のコード例は、`test-type` の使用方法を示しています。

**AWS CLI**  
**拡張機能をテストする方法**  
次の `test-type` の例は、CloudFormation レジストリ内での公開に必要なすべての要件を満たしていることを確認するため、登録済みの拡張機能をテストします。  

```
aws cloudformation test-type \
    --arn arn:aws:cloudformation:us-west-2:123456789012:type/resource/Sample-Test-Resource123/00000001
```
出力:  

```
{
    "TypeVersionArn": "arn:aws:cloudformation:us-west-2:123456789012:type/resource/Sample-Test-Resource123/00000001"
}
```
詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation レジストリ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/registry.html)の使用」を参照してください。 *AWS CloudFormation *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/test-type.html)」を参照してください。

### `update-stack-instances`
<a name="cloudformation_UpdateStackInstances_cli_2_topic"></a>

次のコード例は、`update-stack-instances` の使用方法を示しています。

**AWS CLI**  
**スタックインスタンスを更新する方法**  
次の `update-stack-instances` の例は、最新の設定で 2 つのリージョンの 2 つのアカウントのスタックインスタンスの更新を再試行します。指定された耐障害性の設定により、一部のスタックが更新できない場合でも、すべてのアカウントとリージョンで更新が試行されます。  

```
aws cloudformation update-stack-instances \
    --stack-set-name my-stack-set \
    --accounts 123456789012 567890123456 \
    --regions us-east-1 us-west-2 \
    --operation-preferences FailureToleranceCount=3
```
出力:  

```
{
    "OperationId": "103ebdf2-21ea-xmpl-8892-de5e30733132"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStackInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/update-stack-instances.html)」を参照してください。

### `update-stack-set`
<a name="cloudformation_UpdateStackSet_cli_2_topic"></a>

次のコード例は、`update-stack-set` の使用方法を示しています。

**AWS CLI**  
**テストセットを更新する方法**  
次の `update-stack-set` の例は、指定されたスタックセットで「`Owner`」のキー名と「`IT`」の値を持つタグをスタックインスタンスに追加します。  

```
aws cloudformation update-stack-set \
    --stack-set-name my-stack-set \
    --use-previous-template \
    --tags Key=Owner,Value=IT
```
出力:  

```
{
    "OperationId": "e2b60321-6cab-xmpl-bde7-530c6f47950e"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStackSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/update-stack-set.html)」を参照してください。

### `update-stack`
<a name="cloudformation_UpdateStack_cli_2_topic"></a>

次の例は、`update-stack` を使用する方法を説明しています。

**AWS CLI**  
** AWS CloudFormation スタックを更新するには**  
以下の `update-stack` コマンドは、`mystack` スタックのテンプレートと入力パラメータを更新します。  

```
aws cloudformation update-stack --stack-name mystack --template-url https://s3.amazonaws.com/sample/updated.template --parameters ParameterKey=KeyPairName,ParameterValue=SampleKeyPair ParameterKey=SubnetIDs,ParameterValue=SampleSubnetID1\\,SampleSubnetID2
```
以下の `update-stack` コマンドは、`mystack` スタックの `SubnetIDs` パラメータ値のみを更新します。パラメータ値を指定しない場合は、テンプレートで指定されているデフォルト値が使用されます。  

```
aws cloudformation update-stack --stack-name mystack --template-url https://s3.amazonaws.com/sample/updated.template --parameters ParameterKey=KeyPairName,UsePreviousValue=true ParameterKey=SubnetIDs,ParameterValue=SampleSubnetID1\\,UpdatedSampleSubnetID2
```
以下の `update-stack` コマンドは、`mystack` スタックに 2 つのスタック通知トピックを追加します。  

```
aws cloudformation update-stack --stack-name mystack --use-previous-template --notification-arns "arn:aws:sns:use-east-1:123456789012:mytopic1" "arn:aws:sns:us-east-1:123456789012:mytopic2"
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[AWS CloudFormation スタックの更新](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/update-stack.html)」を参照してください。

### `update-termination-protection`
<a name="cloudformation_UpdateTerminationProtection_cli_2_topic"></a>

次のコード例は、`update-termination-protection` の使用方法を示しています。

**AWS CLI**  
**削除保護を有効化する方法**  
次の `update-termination-protection` の例は、指定されたスタックで削除保護を有効にします。  

```
aws cloudformation update-termination-protection \
    --stack-name my-stack \
    --enable-termination-protection
```
出力:  

```
{
    "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTerminationProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/update-termination-protection.html)」を参照してください。

### `validate-template`
<a name="cloudformation_ValidateTemplate_cli_2_topic"></a>

次の例は、`validate-template` を使用する方法を説明しています。

**AWS CLI**  
** AWS CloudFormation テンプレートを検証するには**  
以下の `validate-template` コマンドは、`sampletemplate.json` テンプレートを検証します。  

```
aws cloudformation validate-template --template-body file://sampletemplate.json
```
出力:  

```
{
    "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
    "Parameters": [],
    "Capabilities": []
}
```
詳細については、 AWS CloudFormation *AWS ユーザーガイド」のCloudFormation *テンプレートの使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ValidateTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/validate-template.html)」を参照してください。

# を使用した CloudFront の例 AWS CLI
<a name="cli_2_cloudfront_code_examples"></a>

次のコード例は、CloudFront AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-distribution-tenant-web-acl`
<a name="cloudfront_AssociateDistributionTenantWebAcl_cli_2_topic"></a>

次のコード例は、`associate-distribution-tenant-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL と CloudFront ディストリビューションテナントを関連付けるには**  
次の `associate-distribution-tenant-web-acl` の例では、ウェブ ACL を ETag `E13V1IB3VIYABC` を持つ CloudFront ディストリビューションに関連付けます。  

```
aws cloudfront associate-distribution-tenant-web-acl \
    --id dt_2wjDZi3hD1ivOXf6rpZJO1AB \
    --if-match E13V1IB3VIYABC \
    --web-acl-arn arn:aws:wafv2:us-east-1:123456789012:global/webacl/web-global-example/626900da-5f64-418b-ba9b-743f37123ABC
```
出力:  

```
{
    "ETag": "E1VC38T7YXBABC",
    "Id": "dt_2wjDZi3hD1ivOXf6rpZJO1AB",
    "WebACLArn": "arn:aws:wafv2:us-east-1:123456789012:global/webacl/web-global-example/626900da-5f64-418b-ba9b-743f37123ABC"
}
```
詳細については、*Amazon CloudFront * [デベロッパーガイド」の AWS 「WAF 保護](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-awswaf.html)を使用する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateDistributionTenantWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/associate-distribution-tenant-web-acl.html)」を参照してください。

### `associate-distribution-web-acl`
<a name="cloudfront_AssociateDistributionWebAcl_cli_2_topic"></a>

次のコード例は、`associate-distribution-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL と CloudFront ディストリビューションを関連付けるには**  
次の `associate-distribution-web-acl` の例では、ウェブ ACL を CloudFront ディストリビューションに関連付けます。  

```
aws cloudfront associate-distribution-web-acl \
    --id E1XNX8R2GOAABC \
    --if-match E2YWS1C2J3OABC \
    --web-acl-arn arn:aws:wafv2:us-east-1:123456789012:global/webacl/web-global-example/626900da-5f64-418b-ba9b-743f3746cABC
```
出力:  

```
{
    "ETag": "E3QE7ED60U0ABC",
    "Id": "E1XNX8R2GOAABC",
    "WebACLArn": "arn:aws:wafv2:us-east-1:123456789012:global/webacl/web-global-example/626900da-5f64-418b-ba9b-743f3746cABC"
}
```
詳細については、*Amazon CloudFront * [デベロッパーガイド」の AWS 「WAF 保護](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-awswaf.html)を使用する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateDistributionWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/associate-distribution-web-acl.html)」を参照してください。

### `create-cloud-front-origin-access-identity`
<a name="cloudfront_CreateCloudFrontOriginAccessIdentity_cli_2_topic"></a>

次のコード例は、`create-cloud-front-origin-access-identity` を使用する方法を示しています。

**AWS CLI**  
**CloudFront オリジンアクセスアイデンティティを作成するには**  
次の例では、コマンドライン引数として OAI 設定を指定して、CloudFront オリジンアクセスアイデンティティ (OAI) を作成しています。  

```
aws cloudfront create-cloud-front-origin-access-identity \
    --cloud-front-origin-access-identity-config \
        CallerReference="cli-example",Comment="Example OAI"
```
次の例に示すように、同じことは、JSON ファイルで OAI 設定を指定することでも実現できます。  

```
aws cloudfront create-cloud-front-origin-access-identity \
    --cloud-front-origin-access-identity-config file://OAI-config.json
```
`OAI-config.json` ファイルは、以下を含む現在のディレクトリ内にある JSON ドキュメントです。  

```
{
    "CallerReference": "cli-example",
    "Comment": "Example OAI"
}
```
OAI 設定をコマンドライン引数で指定する場合も、JSON ファイルで指定する場合も、出力は変わりません。  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/origin-access-identity/cloudfront/E74FTE3AEXAMPLE",
    "ETag": "E2QWRUHEXAMPLE",
    "CloudFrontOriginAccessIdentity": {
        "Id": "E74FTE3AEXAMPLE",
        "S3CanonicalUserId": "cd13868f797c227fbea2830611a26fe0a21ba1b826ab4bed9b7771c9aEXAMPLE",
        "CloudFrontOriginAccessIdentityConfig": {
            "CallerReference": "cli-example",
            "Comment": "Example OAI"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCloudFrontOriginAccessIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-cloud-front-origin-access-identity.html)」を参照してください。

### `create-connection-group`
<a name="cloudfront_CreateConnectionGroup_cli_2_topic"></a>

次のコード例は、`create-connection-group` を使用する方法を示しています。

**AWS CLI**  
**CloudFront で接続グループを作成するには**  
次の `create-connection-group` の例では、有効な接続グループを作成し、エニーキャスト静的 IP リストを指定し、IPv6 を無効にします。  

```
aws cloudfront create-connection-group \
    --name cg-with-anycast-ip-list \
    --no-ipv6-enabled \
    --enabled \
    --anycast-ip-list-id aip_CCkW6gKrDiBD4n78123ABC \
    --tags "Items=[{Key=abc,Value=123}]"
```
出力:  

```
{
    "ETag": "E23ZP02F085ABC",
    "ConnectionGroup": {
        "Id": "cg_2yb6uj74B4PCbfhT31WFdiSABC",
        "Name": "cg-with-anycast-ip-list",
        "Arn": "arn:aws:cloudfront::123456789012:connection-group/cg_2yb6uj74B4PCbfhT31WFdiSABC",
        "CreatedTime": "2025-06-16T16:25:50.061000+00:00",
        "LastModifiedTime": "2025-06-16T16:25:50.061000+00:00",
        "Tags": {
            "Items": [
                {
                    "Key": "abc",
                    "Value": "123"
                }
            ]
        },
        "Ipv6Enabled": false,
        "RoutingEndpoint": "dj6xusxq65abc.cloudfront.net",
        "AnycastIpListId": "aip_CCkW6gKrDiBD4n78123ABC",
        "Status": "InProgress",
        "Enabled": true,
        "IsDefault": false
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[カスタム接続グループの作成 (オプション)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConnectionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-connection-group.html)」を参照してください。

### `create-distribution-tenant`
<a name="cloudfront_CreateDistributionTenant_cli_2_topic"></a>

次のコード例は、`create-distribution-tenant` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタム証明書を使用する CloudFront ディストリビューションテナントを作成するには**  
次の `create-distribution-tenant` の例では、WAF を無効にし、地域制限を追加し、別の TLS 証明書を使用するようにカスタマイズを指定する CloudFront ディストリビューションテナントを作成します。  

```
aws cloudfront create-distribution-tenant \
    --cli-input-json file://tenant.json
```
`tenant.json` の内容:  

```
{
    "DistributionId": "E1XNX8R2GOAABC",
    "Domains": [
        {
            "Domain": "example.com"
        }
    ],
    "Parameters": [
        {
            "Name": "testParam",
            "Value": "defaultValue"
        }
    ],
    "ConnectionGroupId": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
    "Enabled": false,
    "Tags": {
        "Items": [
            {
                "Key": "tag",
                "Value": "tagValue"
            }
        ]
    },
    "Name": "new-tenant-customizations",
    "Customizations": {
        "GeoRestrictions": {
            "Locations": ["DE"],
            "RestrictionType": "whitelist"
        },
        "WebAcl": {
            "Action": "disable"
        },
        "Certificate": {
            "Arn": "arn:aws:acm:us-east-1:123456789012:certificate/ec53f564-ea5a-4e4a-a0a2-e3c989449abc"
        }
    }
}
```
出力:  

```
{
    "ETag": "E23ZP02F085ABC",
    "DistributionTenant": {
        "Id": "dt_2yN5tYwVbPKr7m2IB69M1yp1AB",
        "DistributionId": "E1XNX8R2GOAABC",
        "Name": "new-tenant-customizations",
        "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2yN5tYwVbPKr7m2IB69M1yp1AB",
        "Domains": [
            {
                "Domain": "example.com",
                "Status": "active"
            }
        ],
        "Tags": {
            "Items": [
                {
                    "Key": "tag",
                    "Value": "tagValue"
                }
            ]
        },
        "Customizations": {
            "WebAcl": {
                "Action": "disable"
            },
            "Certificate": {
                "Arn": "arn:aws:acm:us-east-1:123456789012:certificate/ec53f564-ea5a-4e4a-a0a2-e3c989449abc"
            },
            "GeoRestrictions": {
                "RestrictionType": "whitelist",
                "Locations": [
                    "DE"
                ]
            }
        },
        "Parameters": [
            {
                "Name": "testParam",
                "Value": "defaultValue"
            }
        ],
        "ConnectionGroupId": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
        "CreatedTime": "2025-06-11T17:20:06.432000+00:00",
        "LastModifiedTime": "2025-06-11T17:20:06.432000+00:00",
        "Enabled": false,
        "Status": "InProgress"
    }
}
```
**例 2: 継承された証明書を使用するディストリビューションテナントを作成するには**  
次の `create-distribution-tenant` の例では、ディストリビューションテナントを作成し、マルチテナントディストリビューションから継承された TLS 証明書を指定します。  

```
aws cloudfront create-distribution-tenant \
    --cli-input-json file://tenant.json
```
`tenant.json` の内容:  

```
{
    "DistributionId": "E1HVIAU7U12ABC",
    "Domains": [
        {
            "Domain": "example.com"
        }
    ],
    "Parameters": [
        {
            "Name": "tenantName",
            "Value": "first-tenant"
        }
    ],
    "Enabled": true,
    "Name": "new-tenant-no-cert"
}
```
出力:  

```
{
    "ETag": "E23ZP02F0ABC",
    "DistributionTenant": {
        "Id": "dt_2zhRB0vBe0B72LZCVy1mgzI1AB",
        "DistributionId": "E1HVIAU7U12ABC",
        "Name": "new-tenant-no-cert",
        "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2zhRB0vBe0B72LZCVy1mgzI1AB",
        "Domains": [
            {
                "Domain": "example.com",
                "Status": "active"
            }
        ],
        "Parameters": [
            {
                "Name": "tenantName",
                "Value": "first-tenant"
            }
        ],
        "ConnectionGroupId": "cg_2yQEwpipGFN0hhA0ZemPabOABC",
        "CreatedTime": "2025-07-10T20:59:38.414000+00:00",
        "LastModifiedTime": "2025-07-10T20:59:38.414000+00:00",
        "Enabled": true,
        "Status": "InProgress"
    }
}
```
**例 3: CloudFront がホストする検証トークンを使用する CloudFront ディストリビューションテナントを作成するには**  
次の `create-distribution-tenant` の例では、ディストリビューションテナントを作成し、ドメイン名に CloudFront がホストする検証トークンを使用します。  

```
aws cloudfront create-distribution-tenant \
    --cli-input-json file://tenant.json
```
`tenant.json` の内容:  

```
{
    "DistributionId": "E2GJ5J9QN12ABC",
    "Domains": [
        {
            "Domain": "example.com"
        }
    ],
    "Parameters": [
        {
            "Name": "tenantName",
            "Value": "first-tenant"
        }
    ],
    "ConnectionGroupId": "cg_2yQEwpipGFN0hhA0ZemPabOABC",
    "Enabled": true,
    "Name": "new-tenant-cf-hosted",
    "ManagedCertificateRequest": {
        "ValidationTokenHost": "cloudfront"
    }
}
```
**重要:** このコマンドを正常に実行するには、新しいドメイン (example.com) がディストリビューションテナントに関連付けられている接続グループのルーティングエンドポイントを指すように CNAME DNS レコードを設定する必要があります。CloudFront がこのリクエストを正常に完了する前に、この CNAME レコードも伝播させる必要があります。  
出力:  

```
{
    "ETag": "E23ZP02F0ABC",
    "DistributionTenant": {
        "Id": "dt_2zhStKrA524GvvTWJX92Ozl1AB",
        "DistributionId": "E2GJ5J9QN12ABC",
        "Name": "new-tenant-cf-hosted",
        "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2zhStKrA524GvvTWJX92Ozl1AB",
        "Domains": [
            {
                "Domain": "example.com",
                "Status": "inactive"
            }
        ],
        "Parameters": [
            {
                "Name": "tenantName",
                "Value": "first-tenant"
            }
        ],
        "ConnectionGroupId": "cg_2zhSaGatwwXjTjE42nneZzqABC",
        "CreatedTime": "2025-07-10T21:13:46.416000+00:00",
        "LastModifiedTime": "2025-07-10T21:13:46.416000+00:00",
        "Enabled": true,
        "Status": "InProgress"
    }
}
```
**例 4: セルフホスト型の検証トークンを使用する CloudFront ディストリビューションテナントを作成するには**  
次の `create-distribution-tenant` の例では、CloudFront ディストリビューションテナントを作成し、セルフホスト型の検証トークンを使用します。  

```
aws cloudfront create-distribution-tenant \
    --cli-input-json file://tenant.json
```
`tenant.json` の内容:  

```
{
    "DistributionId": "E2GJ5J9QN12ABC",
    "Domains": [
        {
            "Domain": "example.com"
        }
    ],
    "Parameters": [
        {
            "Name": "tenantName",
            "Value": "first-tenant"
        }
    ],
    "Enabled": true,
    "Name": "new-tenant-self-hosted",
    "ManagedCertificateRequest": {
        "ValidationTokenHost": "self-hosted"
    }
}
```
出力:  

```
{
    "ETag": "E23ZP02F0ABC",
    "DistributionTenant": {
        "Id": "dt_2zhTFBV93OfFJJ3YMdNM5BC1AB",
        "DistributionId": "E2GJ5J9QN12ABC",
        "Name": "new-tenant-self-hosted",
        "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2zhTFBV93OfFJJ3YMdNM5BC1AB",
        "Domains": [
            {
                "Domain": "example.com",
                "Status": "inactive"
            }
        ],
        "Parameters": [
            {
                "Name": "tenantName",
                "Value": "first-tenant"
            }
        ],
        "ConnectionGroupId": "cg_2yQEwpipGFN0hhA0ZemPabOABC",
        "CreatedTime": "2025-07-10T21:16:39.828000+00:00",
        "LastModifiedTime": "2025-07-10T21:16:39.828000+00:00",
        "Enabled": true,
        "Status": "InProgress"
    }
}
```
**重要:** このコマンドの実行後、ディストリビューションテナントは検証なしで作成されます。トラフィックの受信を開始する準備ができたときにマネージド証明書のリクエストを検証し、DNS を設定するには、「*Amazon CloudFront デベロッパーガイド*」の「[ドメイン設定を完了する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/managed-cloudfront-certificates.html#complete-domain-ownership)」を参照してください。  
ディストリビューションテナントの作成の詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ディストリビューションを作成する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-console.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDistributionTenant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-distribution-tenant.html)」を参照してください。

### `create-distribution-with-tags`
<a name="cloudfront_CreateDistributionWithTags_cli_2_topic"></a>

次のコード例は、`create-distribution-with-tags` を使用する方法を示しています。

**AWS CLI**  
**タグ付きの CloudFront ディストリビューションを作成するには**  
次の `create-distribution-with-tags` の例では、`dist-config-with-tags.json` という名前の JSON ファイルにディストリビューション設定とタグを指定して、2 つのタグを持つディストリビューションを作成しています。  

```
aws cloudfront create-distribution-with-tags \
    --distribution-config-with-tags file://dist-config-with-tags.json
```
`dist-config-with-tags.json` ファイルは現在のフォルダ内の JSON ドキュメントです。ファイルの先頭にある `Tags` オブジェクトに、次の 2 つのタグが含まれていることに注目してください。  
`Name = ExampleDistribution``Project = ExampleProject`  
`dist-config-with-tags.json` の内容:  

```
{
    "Tags": {
        "Items": [
            {
                "Key": "Name",
                "Value": "ExampleDistribution"
            },
            {
                "Key": "Project",
                "Value": "ExampleProject"
            }
        ]
    },
    "DistributionConfig": {
        "CallerReference": "cli-example",
        "Aliases": {
            "Quantity": 0
        },
        "DefaultRootObject": "index.html",
        "Origins": {
            "Quantity": 1,
            "Items": [
                {
                    "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                    "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                    "OriginPath": "",
                    "CustomHeaders": {
                        "Quantity": 0
                    },
                    "S3OriginConfig": {
                        "OriginAccessIdentity": ""
                    }
                }
            ]
        },
        "OriginGroups": {
            "Quantity": 0
        },
        "DefaultCacheBehavior": {
            "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
            "ForwardedValues": {
                "QueryString": false,
                "Cookies": {
                    "Forward": "none"
                },
                "Headers": {
                    "Quantity": 0
                },
                "QueryStringCacheKeys": {
                    "Quantity": 0
                }
            },
            "TrustedSigners": {
                "Enabled": false,
                "Quantity": 0
            },
            "ViewerProtocolPolicy": "allow-all",
            "MinTTL": 0,
            "AllowedMethods": {
                "Quantity": 2,
                "Items": [
                    "HEAD",
                    "GET"
                ],
                "CachedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ]
                }
            },
            "SmoothStreaming": false,
            "DefaultTTL": 86400,
            "MaxTTL": 31536000,
            "Compress": false,
            "LambdaFunctionAssociations": {
                "Quantity": 0
            },
            "FieldLevelEncryptionId": ""
        },
        "CacheBehaviors": {
            "Quantity": 0
        },
        "CustomErrorResponses": {
            "Quantity": 0
        },
        "Comment": "",
        "Logging": {
            "Enabled": false,
            "IncludeCookies": false,
            "Bucket": "",
            "Prefix": ""
        },
        "PriceClass": "PriceClass_All",
        "Enabled": true,
        "ViewerCertificate": {
            "CloudFrontDefaultCertificate": true,
            "MinimumProtocolVersion": "TLSv1",
            "CertificateSource": "cloudfront"
        },
        "Restrictions": {
            "GeoRestriction": {
                "RestrictionType": "none",
                "Quantity": 0
            }
        },
        "WebACLId": "",
        "HttpVersion": "http2",
        "IsIPV6Enabled": true
    }
}
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/distribution/EDFDVBD6EXAMPLE",
    "ETag": "E2QWRUHEXAMPLE",
    "Distribution": {
        "Id": "EDFDVBD6EXAMPLE",
        "ARN": "arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE",
        "Status": "InProgress",
        "LastModifiedTime": "2019-12-04T23:35:41.433Z",
        "InProgressInvalidationBatches": 0,
        "DomainName": "d111111abcdef8.cloudfront.net",
        "ActiveTrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "DistributionConfig": {
            "CallerReference": "cli-example",
            "Aliases": {
                "Quantity": 0
            },
            "DefaultRootObject": "index.html",
            "Origins": {
                "Quantity": 1,
                "Items": [
                    {
                        "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                        "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                        "OriginPath": "",
                        "CustomHeaders": {
                            "Quantity": 0
                        },
                        "S3OriginConfig": {
                            "OriginAccessIdentity": ""
                        }
                    }
                ]
            },
            "OriginGroups": {
                "Quantity": 0
            },
            "DefaultCacheBehavior": {
                "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                "ForwardedValues": {
                    "QueryString": false,
                    "Cookies": {
                        "Forward": "none"
                    },
                    "Headers": {
                        "Quantity": 0
                    },
                    "QueryStringCacheKeys": {
                        "Quantity": 0
                    }
                },
                "TrustedSigners": {
                    "Enabled": false,
                    "Quantity": 0
                },
                "ViewerProtocolPolicy": "allow-all",
                "MinTTL": 0,
                "AllowedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ],
                    "CachedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ]
                    }
                },
                "SmoothStreaming": false,
                "DefaultTTL": 86400,
                "MaxTTL": 31536000,
                "Compress": false,
                "LambdaFunctionAssociations": {
                    "Quantity": 0
                },
                "FieldLevelEncryptionId": ""
            },
            "CacheBehaviors": {
                "Quantity": 0
            },
            "CustomErrorResponses": {
                "Quantity": 0
            },
            "Comment": "",
            "Logging": {
                "Enabled": false,
                "IncludeCookies": false,
                "Bucket": "",
                "Prefix": ""
            },
            "PriceClass": "PriceClass_All",
            "Enabled": true,
            "ViewerCertificate": {
                "CloudFrontDefaultCertificate": true,
                "MinimumProtocolVersion": "TLSv1",
                "CertificateSource": "cloudfront"
            },
            "Restrictions": {
                "GeoRestriction": {
                    "RestrictionType": "none",
                    "Quantity": 0
                }
            },
            "WebACLId": "",
            "HttpVersion": "http2",
            "IsIPV6Enabled": true
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDistributionWithTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-distribution-with-tags.html)」を参照してください。

### `create-distribution`
<a name="cloudfront_CreateDistribution_cli_2_topic"></a>

次のコード例は、`create-distribution` を使用する方法を示しています。

**AWS CLI**  
**例 1: CloudFront ディストリビューションを作成するには**  
次の `create-distribution` の例では、`amzn-s3-demo-bucket` という名前の S3 バケットのディストリビューションを作成し、コマンドライン引数を使用してデフォルトのルートオブジェクトとして `index.html` を指定しています。  

```
aws cloudfront create-distribution \
    --origin-domain-name amzn-s3-demo-bucket.s3.amazonaws.com \
    --default-root-object index.html
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/distribution/EMLARXS9EXAMPLE",
    "ETag": "E9LHASXEXAMPLE",
    "Distribution": {
        "Id": "EMLARXS9EXAMPLE",
        "ARN": "arn:aws:cloudfront::123456789012:distribution/EMLARXS9EXAMPLE",
        "Status": "InProgress",
        "LastModifiedTime": "2019-11-22T00:55:15.705Z",
        "InProgressInvalidationBatches": 0,
        "DomainName": "d111111abcdef8.cloudfront.net",
        "ActiveTrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "DistributionConfig": {
            "CallerReference": "cli-example",
            "Aliases": {
                "Quantity": 0
            },
            "DefaultRootObject": "index.html",
            "Origins": {
                "Quantity": 1,
                "Items": [
                    {
                        "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                        "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                        "OriginPath": "",
                        "CustomHeaders": {
                            "Quantity": 0
                        },
                        "S3OriginConfig": {
                            "OriginAccessIdentity": ""
                        }
                    }
                ]
            },
            "OriginGroups": {
                "Quantity": 0
            },
            "DefaultCacheBehavior": {
                "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                "ForwardedValues": {
                    "QueryString": false,
                    "Cookies": {
                        "Forward": "none"
                    },
                    "Headers": {
                        "Quantity": 0
                    },
                    "QueryStringCacheKeys": {
                        "Quantity": 0
                    }
                },
                "TrustedSigners": {
                    "Enabled": false,
                    "Quantity": 0
                },
                "ViewerProtocolPolicy": "allow-all",
                "MinTTL": 0,
                "AllowedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ],
                    "CachedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ]
                    }
                },
                "SmoothStreaming": false,
                "DefaultTTL": 86400,
                "MaxTTL": 31536000,
                "Compress": false,
                "LambdaFunctionAssociations": {
                    "Quantity": 0
                },
                "FieldLevelEncryptionId": ""
            },
            "CacheBehaviors": {
                "Quantity": 0
            },
            "CustomErrorResponses": {
                "Quantity": 0
            },
            "Comment": "",
            "Logging": {
                "Enabled": false,
                "IncludeCookies": false,
                "Bucket": "",
                "Prefix": ""
            },
            "PriceClass": "PriceClass_All",
            "Enabled": true,
            "ViewerCertificate": {
                "CloudFrontDefaultCertificate": true,
                "MinimumProtocolVersion": "TLSv1",
                "CertificateSource": "cloudfront"
            },
            "Restrictions": {
                "GeoRestriction": {
                    "RestrictionType": "none",
                    "Quantity": 0
                }
            },
            "WebACLId": "",
            "HttpVersion": "http2",
            "IsIPV6Enabled": true
        }
    }
}
```
**例 2: JSON ファイルを使用して CloudFront ディストリビューションを作成するには**  
次の `create-distribution` の例では、`amzn-s3-demo-bucket` という名前の S3 バケットのディストリビューションを作成し、JSON ファイルを使用してデフォルトのルートオブジェクトとして `index.html` を指定しています。  

```
aws cloudfront create-distribution \
    --distribution-config file://dist-config.json
```
`dist-config.json` の内容:  

```
{
    "CallerReference": "cli-example",
    "Aliases": {
        "Quantity": 0
    },
    "DefaultRootObject": "index.html",
    "Origins": {
        "Quantity": 1,
        "Items": [
            {
                "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                "OriginPath": "",
                "CustomHeaders": {
                    "Quantity": 0
                },
                "S3OriginConfig": {
                    "OriginAccessIdentity": ""
                }
            }
        ]
    },
    "OriginGroups": {
        "Quantity": 0
    },
    "DefaultCacheBehavior": {
        "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
        "ForwardedValues": {
            "QueryString": false,
            "Cookies": {
                "Forward": "none"
            },
            "Headers": {
                "Quantity": 0
            },
            "QueryStringCacheKeys": {
                "Quantity": 0
            }
        },
        "TrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "ViewerProtocolPolicy": "allow-all",
        "MinTTL": 0,
        "AllowedMethods": {
            "Quantity": 2,
            "Items": [
                "HEAD",
                "GET"
            ],
            "CachedMethods": {
                "Quantity": 2,
                "Items": [
                    "HEAD",
                    "GET"
                ]
            }
        },
        "SmoothStreaming": false,
        "DefaultTTL": 86400,
        "MaxTTL": 31536000,
        "Compress": false,
        "LambdaFunctionAssociations": {
            "Quantity": 0
        },
        "FieldLevelEncryptionId": ""
    },
    "CacheBehaviors": {
        "Quantity": 0
    },
    "CustomErrorResponses": {
        "Quantity": 0
    },
    "Comment": "",
    "Logging": {
        "Enabled": false,
        "IncludeCookies": false,
        "Bucket": "",
        "Prefix": ""
    },
    "PriceClass": "PriceClass_All",
    "Enabled": true,
    "ViewerCertificate": {
        "CloudFrontDefaultCertificate": true,
        "MinimumProtocolVersion": "TLSv1",
        "CertificateSource": "cloudfront"
    },
    "Restrictions": {
        "GeoRestriction": {
            "RestrictionType": "none",
            "Quantity": 0
        }
    },
    "WebACLId": "",
    "HttpVersion": "http2",
    "IsIPV6Enabled": true
}
```
出力例については、例 1 を参照してください。  
**例 3: 証明書を使用して CloudFront マルチテナントディストリビューションを作成するには**  
次の `create-distribution` の例では、マルチテナントをサポートする CloudFront ディストリビューションを作成し、TLS 証明書を指定します。  

```
aws cloudfront create-distribution \
    --distribution-config file://dist-config.json
```
`dist-config.json` の内容:  

```
{
    "CallerReference": "cli-example-with-cert",
    "Comment": "CLI example distribution",
    "DefaultRootObject": "index.html",
    "Origins": {
        "Quantity": 1,
        "Items": [
            {
                "Id": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                "DomainName": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                "OriginPath": "/{{tenantName}}",
                "CustomHeaders": {
                    "Quantity": 0
                },
                "S3OriginConfig": {
                    "OriginAccessIdentity": ""
                }
            }
        ]
    },
    "DefaultCacheBehavior": {
        "TargetOriginId": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
        "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e5ABC",
        "ViewerProtocolPolicy": "allow-all",
        "AllowedMethods": {
            "Quantity": 2,
            "Items": ["HEAD", "GET"],
            "CachedMethods": {
                "Quantity": 2,
                "Items": ["HEAD", "GET"]
            }
        }
    },
    "Enabled": true,
    "ViewerCertificate": {
        "ACMCertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/191306a1-db01-49ca-90ef-fc414ee5dabc",
        "SSLSupportMethod": "sni-only"
    },
    "HttpVersion": "http2",
    "ConnectionMode": "tenant-only",
    "TenantConfig": {
        "ParameterDefinitions": [
            {
                "Name": "tenantName",
                "Definition": {
                    "StringSchema": {
                        "Comment": "tenantName parameter",
                        "DefaultValue": "root",
                        "Required": false
                    }
                }
            }
        ]
    }
}
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2020-05-31/distribution/E1HVIAU7UABC",
    "ETag": "E20LT7R1BABC",
    "Distribution": {
        "Id": "E1HVIAU7U12ABC",
        "ARN": "arn:aws:cloudfront::123456789012:distribution/E1HVIAU7U12ABC",
        "Status": "InProgress",
        "LastModifiedTime": "2025-07-10T20:33:31.117000+00:00",
        "InProgressInvalidationBatches": 0,
        "DomainName": "example.com",
        "ActiveTrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "ActiveTrustedKeyGroups": {
            "Enabled": false,
            "Quantity": 0
        },
        "DistributionConfig": {
            "CallerReference": "cli-example-with-cert",
            "DefaultRootObject": "index.html",
            "Origins": {
                "Quantity": 1,
                "Items": [
                    {
                        "Id": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                        "DomainName": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                        "OriginPath": "/{{tenantName}}",
                        "CustomHeaders": {
                            "Quantity": 0
                        },
                        "S3OriginConfig": {
                            "OriginAccessIdentity": ""
                        },
                        "ConnectionAttempts": 3,
                        "ConnectionTimeout": 10,
                        "OriginShield": {
                            "Enabled": false
                        },
                        "OriginAccessControlId": ""
                    }
                ]
            },
            "OriginGroups": {
                "Quantity": 0
            },
            "DefaultCacheBehavior": {
                "TargetOriginId": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                "TrustedKeyGroups": {
                    "Enabled": false,
                    "Quantity": 0
                },
                "ViewerProtocolPolicy": "allow-all",
                "AllowedMethods": {
                    "Quantity": 2,
                    "Items": ["HEAD", "GET"],
                    "CachedMethods": {
                        "Quantity": 2,
                        "Items": ["HEAD", "GET"]
                    }
                },
                "Compress": false,
                "LambdaFunctionAssociations": {
                    "Quantity": 0
                },
                "FunctionAssociations": {
                    "Quantity": 0
                },
                "FieldLevelEncryptionId": "",
                "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e5ABC",
                "GrpcConfig": {
                    "Enabled": false
                }
            },
            "CacheBehaviors": {
                "Quantity": 0
            },
            "CustomErrorResponses": {
                "Quantity": 0
            },
            "Comment": "CLI example distribution",
            "Logging": {
                "Enabled": false,
                "IncludeCookies": false,
                "Bucket": "",
                "Prefix": ""
            },
            "Enabled": true,
            "ViewerCertificate": {
                "CloudFrontDefaultCertificate": false,
                "ACMCertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/1954f095-11b6-4daf-9952-0c308a00abc",
                "SSLSupportMethod": "sni-only",
                "MinimumProtocolVersion": "TLSv1.2_2021",
                "Certificate": "arn:aws:acm:us-east-1:123456789012:certificate/1954f095-11b6-4daf-9952-0c308a00abc",
                "CertificateSource": "acm"
            },
            "Restrictions": {
                "GeoRestriction": {
                    "RestrictionType": "none",
                    "Quantity": 0
                }
            },
            "WebACLId": "",
            "HttpVersion": "http2",
            "TenantConfig": {
                "ParameterDefinitions": [
                    {
                        "Name": "tenantName",
                        "Definition": {
                            "StringSchema": {
                                "Comment": "tenantName parameter",
                                "DefaultValue": "root",
                                "Required": false
                            }
                        }
                    }
                ]
            },
            "ConnectionMode": "tenant-only"
        }
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ディストリビューションの設定](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-working-with.html)」を参照してください。  
**例 4: 証明書を使用しないで CloudFront マルチテナントディストリビューションを作成するには**  
次の `create-distribution` の例では、マルチテナントをサポートしているが TLS 証明書はサポートしない CloudFront ディストリビューションを作成します。  

```
aws cloudfront create-distribution \
    --distribution-config file://dist-config.json
```
`dist-config.json` の内容:  

```
{
    "CallerReference": "cli-example",
    "Comment": "CLI example distribution",
    "DefaultRootObject": "index.html",
    "Origins": {
        "Quantity": 1,
        "Items": [
            {
                "Id": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                "DomainName": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                "OriginPath": "/{{tenantName}}",
                "CustomHeaders": {
                    "Quantity": 0
                },
                "S3OriginConfig": {
                    "OriginAccessIdentity": ""
                }
            }
        ]
    },
    "DefaultCacheBehavior": {
        "TargetOriginId": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
        "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e5ABC",
        "ViewerProtocolPolicy": "allow-all",
        "AllowedMethods": {
            "Quantity": 2,
            "Items": [
                "HEAD",
                "GET"
            ],
            "CachedMethods": {
                "Quantity": 2,
                "Items": [
                    "HEAD",
                    "GET"
                ]
            }
        }
    },
    "Enabled": true,
    "HttpVersion": "http2",
    "ConnectionMode": "tenant-only",
    "TenantConfig": {
        "ParameterDefinitions": [
            {
                "Name": "tenantName",
                "Definition": {
                    "StringSchema": {
                        "Comment": "tenantName parameter",
                        "DefaultValue": "root",
                        "Required": false
                    }
                }
            }
        ]
    }
}
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2020-05-31/distribution/E2GJ5J9QN12ABC",
    "ETag": "E37YLVVQIABC",
    "Distribution": {
        "Id": "E2GJ5J9QNABC",
        "ARN": "arn:aws:cloudfront::123456789012:distribution/E2GJ5J9QN12ABC",
        "Status": "InProgress",
        "LastModifiedTime": "2025-07-10T20:35:20.565000+00:00",
        "InProgressInvalidationBatches": 0,
        "DomainName": "example.com",
        "ActiveTrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "ActiveTrustedKeyGroups": {
            "Enabled": false,
            "Quantity": 0
        },
        "DistributionConfig": {
            "CallerReference": "cli-example-no-cert",
            "DefaultRootObject": "index.html",
            "Origins": {
                "Quantity": 1,
                "Items": [
                    {
                        "Id": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                        "DomainName": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                        "OriginPath": "/{{tenantName}}",
                        "CustomHeaders": {
                            "Quantity": 0
                        },
                        "S3OriginConfig": {
                            "OriginAccessIdentity": ""
                        },
                        "ConnectionAttempts": 3,
                        "ConnectionTimeout": 10,
                        "OriginShield": {
                            "Enabled": false
                        },
                        "OriginAccessControlId": ""
                    }
                ]
            },
            "OriginGroups": {
                "Quantity": 0
            },
            "DefaultCacheBehavior": {
                "TargetOriginId": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                "TrustedKeyGroups": {
                    "Enabled": false,
                    "Quantity": 0
                },
                "ViewerProtocolPolicy": "allow-all",
                "AllowedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ],
                    "CachedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ]
                    }
                },
                "Compress": false,
                "LambdaFunctionAssociations": {
                    "Quantity": 0
                },
                "FunctionAssociations": {
                    "Quantity": 0
                },
                "FieldLevelEncryptionId": "",
                "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e5ABC",
                "GrpcConfig": {
                    "Enabled": false
                }
            },
            "CacheBehaviors": {
                "Quantity": 0
            },
            "CustomErrorResponses": {
                "Quantity": 0
            },
            "Comment": "CLI example distribution",
            "Logging": {
                "Enabled": false,
                "IncludeCookies": false,
                "Bucket": "",
                "Prefix": ""
            },
            "Enabled": true,
            "ViewerCertificate": {
                "CloudFrontDefaultCertificate": true,
                "SSLSupportMethod": "sni-only",
                "MinimumProtocolVersion": "TLSv1",
                "CertificateSource": "cloudfront"
            },
            "Restrictions": {
                "GeoRestriction": {
                    "RestrictionType": "none",
                    "Quantity": 0
                }
            },
            "WebACLId": "",
            "HttpVersion": "http2",
            "TenantConfig": {
                "ParameterDefinitions": [
                    {
                        "Name": "tenantName",
                        "Definition": {
                            "StringSchema": {
                                "Comment": "tenantName parameter",
                                "DefaultValue": "root",
                                "Required": false
                            }
                        }
                    }
                ]
            },
            "ConnectionMode": "tenant-only"
        }
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ディストリビューションの設定](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-working-with.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateDistribution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-distribution.html)」を参照してください。**

### `create-field-level-encryption-config`
<a name="cloudfront_CreateFieldLevelEncryptionConfig_cli_2_topic"></a>

次のコード例は、`create-field-level-encryption-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化の設定を作成するには**  
次の例では、`fle-config.json` という名前の JSON ファイルに設定パラメータを指定して、フィールドレベル暗号化の設定を作成しています。フィールドレベル暗号化の設定を作成する前に、フィールドレベル暗号化のプロファイルが必要です。プロファイルを作成するには、create-field-level-encryption-profile コマンドを参照してください。  
CloudFront のフィールドレベル暗号化の詳細については、「*Amazon CloudFront 開発者ガイド*」の「[フィールドレベル暗号化を使用した機密データの保護](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/field-level-encryption.html)」を参照してください。  

```
aws cloudfront create-field-level-encryption-config \
    --field-level-encryption-config file://fle-config.json
```
`fle-config.json` ファイルは、以下を含む現在のフォルダ内にある JSON ドキュメントです。  

```
{
    "CallerReference": "cli-example",
    "Comment": "Example FLE configuration",
    "QueryArgProfileConfig": {
        "ForwardWhenQueryArgProfileIsUnknown": true,
        "QueryArgProfiles": {
            "Quantity": 0
        }
    },
    "ContentTypeProfileConfig": {
        "ForwardWhenContentTypeIsUnknown": true,
        "ContentTypeProfiles": {
            "Quantity": 1,
            "Items": [
                {
                    "Format": "URLEncoded",
                    "ProfileId": "P280MFCLSYOCVU",
                    "ContentType": "application/x-www-form-urlencoded"
                }
            ]
        }
    }
}
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/field-level-encryption/C3KM2WVD605UAY",
    "ETag": "E2P4Z4VU7TY5SG",
    "FieldLevelEncryption": {
        "Id": "C3KM2WVD605UAY",
        "LastModifiedTime": "2019-12-10T21:30:18.974Z",
        "FieldLevelEncryptionConfig": {
            "CallerReference": "cli-example",
            "Comment": "Example FLE configuration",
            "QueryArgProfileConfig": {
                "ForwardWhenQueryArgProfileIsUnknown": true,
                "QueryArgProfiles": {
                    "Quantity": 0,
                    "Items": []
                }
            },
            "ContentTypeProfileConfig": {
                "ForwardWhenContentTypeIsUnknown": true,
                "ContentTypeProfiles": {
                    "Quantity": 1,
                    "Items": [
                        {
                            "Format": "URLEncoded",
                            "ProfileId": "P280MFCLSYOCVU",
                            "ContentType": "application/x-www-form-urlencoded"
                        }
                    ]
                }
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFieldLevelEncryptionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-field-level-encryption-config.html)」を参照してください。

### `create-field-level-encryption-profile`
<a name="cloudfront_CreateFieldLevelEncryptionProfile_cli_2_topic"></a>

次のコード例は、`create-field-level-encryption-profile` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化のプロファイルを作成するには**  
次の例では、`fle-profile-config.json` という名前の JSON ファイルにパラメータを指定して、フィールドレベル暗号化のプロファイルを作成しています。フィールドレベル暗号化のプロファイルを作成する前に、CloudFront パブリックキーが必要です。CloudFront パブリックキーを作成するには、create-public-key コマンドを参照してください。  
CloudFront のフィールドレベル暗号化の詳細については、「*Amazon CloudFront 開発者ガイド*」の「[フィールドレベル暗号化を使用した機密データの保護](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/field-level-encryption.html)」を参照してください。  

```
aws cloudfront create-field-level-encryption-profile \
    --field-level-encryption-profile-config file://fle-profile-config.json
```
`fle-profile-config.json` ファイルは、以下を含む現在のフォルダ内にある JSON ドキュメントです。  

```
{
    "Name": "ExampleFLEProfile",
    "CallerReference": "cli-example",
    "Comment": "FLE profile for AWS CLI example",
    "EncryptionEntities": {
        "Quantity": 1,
        "Items": [
            {
                "PublicKeyId": "K2K8NC4HVFE3M0",
                "ProviderId": "ExampleFLEProvider",
                "FieldPatterns": {
                    "Quantity": 1,
                    "Items": [
                        "ExampleSensitiveField"
                    ]
                }
            }
        ]
    }
}
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/field-level-encryption-profile/PPK0UOSIF5WSV",
    "ETag": "E2QWRUHEXAMPLE",
    "FieldLevelEncryptionProfile": {
        "Id": "PPK0UOSIF5WSV",
        "LastModifiedTime": "2019-12-10T01:03:16.537Z",
        "FieldLevelEncryptionProfileConfig": {
            "Name": "ExampleFLEProfile",
            "CallerReference": "cli-example",
            "Comment": "FLE profile for AWS CLI example",
            "EncryptionEntities": {
                "Quantity": 1,
                "Items": [
                    {
                        "PublicKeyId": "K2K8NC4HVFE3M0",
                        "ProviderId": "ExampleFLEProvider",
                        "FieldPatterns": {
                            "Quantity": 1,
                            "Items": [
                                "ExampleSensitiveField"
                            ]
                        }
                    }
                ]
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFieldLevelEncryptionProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-field-level-encryption-profile.html)」を参照してください。

### `create-invalidation-for-distribution-tenant`
<a name="cloudfront_CreateInvalidationForDistributionTenant_cli_2_topic"></a>

次のコード例は、`create-invalidation-for-distribution-tenant` を使用する方法を示しています。

**AWS CLI**  
**ディストリビューションテナントの CloudFront の無効化を作成するには**  
次の `create-invalidation-for-distribution-tenant` の例では、CloudFront ディストリビューションテナント内ですべてのファイルの無効化を作成します。  

```
aws cloudfront create-invalidation-for-distribution-tenant \
    --id dt_2wjDZi3hD1ivOXf6rpZJO1AB \
    --invalidation-batch '{"Paths": {"Quantity": 1, "Items": ["/*"]}, "CallerReference": "invalidation-$(date +%s)"}'
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2020-05-31/distribution-tenant/dt_2wjDZi3hD1ivOXf6rpZJO1AB/invalidation/I2JGL2F1ZAA426PGG0YLLKABC",
    "Invalidation": {
        "Id": "I2JGL2F1ZAA426PGG0YLLKABC",
        "Status": "InProgress",
        "CreateTime": "2025-05-07T16:59:25.947000+00:00",
        "InvalidationBatch": {
            "Paths": {
                "Quantity": 1,
                "Items": [
                    "/*"
                ]
            },
            "CallerReference": "invalidation-$(date +%s)"
        }
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ファイルを無効化してコンテンツを削除する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInvalidationForDistributionTenant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-invalidation-for-distribution-tenant.html)」を参照してください。

### `create-invalidation`
<a name="cloudfront_CreateInvalidation_cli_2_topic"></a>

次のコード例は、`create-invalidation` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションでキャッシュ削除を作成するには**  
次の `create-invalidation` 例では、指定した CloudFront ディストリビューションで指定したファイルのキャッシュ削除を作成します。  

```
aws cloudfront create-invalidation \
    --distribution-id EDFDVBD6EXAMPLE \
    --paths "/example-path/example-file.jpg" "/example-path/example-file2.png"
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/distribution/EDFDVBD6EXAMPLE/invalidation/I1JLWSDAP8FU89",
    "Invalidation": {
        "Id": "I1JLWSDAP8FU89",
        "Status": "InProgress",
        "CreateTime": "2019-12-05T18:24:51.407Z",
        "InvalidationBatch": {
            "Paths": {
                "Quantity": 2,
                "Items": [
                    "/example-path/example-file2.png",
                    "/example-path/example-file.jpg"
                ]
            },
            "CallerReference": "cli-1575570291-670203"
        }
    }
}
```
前の例では、 CLI AWS はランダムな を自動的に生成しました`CallerReference`。独自の `CallerReference` を指定したり、キャッシュ削除パラメータをコマンドライン引数として渡さないようにしたりするには、JSON ファイルを使用できます。次の例では、`inv-batch.json` という名前の JSON ファイルでキャッシュ削除パラメータを指定して、2 つのファイルのキャッシュ削除を作成します。  

```
aws cloudfront create-invalidation \
    --distribution-id EDFDVBD6EXAMPLE \
    --invalidation-batch file://inv-batch.json
```
`inv-batch.json` の内容:  

```
{
    "Paths": {
        "Quantity": 2,
        "Items": [
            "/example-path/example-file.jpg",
            "/example-path/example-file2.png"
        ]
    },
    "CallerReference": "cli-example"
}
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/distribution/EDFDVBD6EXAMPLE/invalidation/I2J0I21PCUYOIK",
    "Invalidation": {
        "Id": "I2J0I21PCUYOIK",
        "Status": "InProgress",
        "CreateTime": "2019-12-05T18:40:49.413Z",
        "InvalidationBatch": {
            "Paths": {
                "Quantity": 2,
                "Items": [
                    "/example-path/example-file.jpg",
                    "/example-path/example-file2.png"
                ]
            },
            "CallerReference": "cli-example"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInvalidation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-invalidation.html)」を参照してください。

### `create-public-key`
<a name="cloudfront_CreatePublicKey_cli_2_topic"></a>

次のコード例は、`create-public-key` を使用する方法を示しています。

**AWS CLI**  
**CloudFront パブリックキーを作成するには**  
次の例では、`pub-key-config.json` という名前の JSON ファイルでパラメータを指定して、CloudFront パブリックキーを作成します。このコマンドを使用するには、事前に PEM でエンコードされたパブリックキーが必要です。詳細については、「Amazon CloudFront 開発者ガイド」の「[RSA キーペアを作成する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/field-level-encryption.html#field-level-encryption-setting-up-step1)」を参照してください。**  

```
aws cloudfront create-public-key \
    --public-key-config file://pub-key-config.json
```
`pub-key-config.json` ファイルは、以下を含む現在のフォルダ内にある JSON ドキュメントです。パブリックキーは PEM 形式でエンコードされていることに注意してください。  

```
{
    "CallerReference": "cli-example",
    "Name": "ExampleKey",
    "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPMbCA2Ks0lnd7IR+3pw\nwd3H/7jPGwj8bLUmore7bX+oeGpZ6QmLAe/1UOWcmZX2u70dYcSIzB1ofZtcn4cJ\nenHBAzO3ohBY/L1tQGJfS2A+omnN6H16VZE1JCK8XSJyfze7MDLcUyHZETdxuvRb\nA9X343/vMAuQPnhinFJ8Wdy8YBXSPpy7r95ylUQd9LfYTBzVZYG2tSesplcOkjM3\n2Uu+oMWxQAw1NINnSLPinMVsutJy6ZqlV3McWNWe4T+STGtWhrPNqJEn45sIcCx4\nq+kGZ2NQ0FyIyT2eiLKOX5Rgb/a36E/aMk4VoDsaenBQgG7WLTnstb9sr7MIhS6A\nrwIDAQAB\n-----END PUBLIC KEY-----\n",
    "Comment": "example public key"
}
```
出力:  

```
{
    "Location": "https://cloudfront.amazonaws.com/2019-03-26/public-key/KDFB19YGCR002",
    "ETag": "E2QWRUHEXAMPLE",
    "PublicKey": {
        "Id": "KDFB19YGCR002",
        "CreatedTime": "2019-12-05T18:51:43.781Z",
        "PublicKeyConfig": {
            "CallerReference": "cli-example",
            "Name": "ExampleKey",
            "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPMbCA2Ks0lnd7IR+3pw\nwd3H/7jPGwj8bLUmore7bX+oeGpZ6QmLAe/1UOWcmZX2u70dYcSIzB1ofZtcn4cJ\nenHBAzO3ohBY/L1tQGJfS2A+omnN6H16VZE1JCK8XSJyfze7MDLcUyHZETdxuvRb\nA9X343/vMAuQPnhinFJ8Wdy8YBXSPpy7r95ylUQd9LfYTBzVZYG2tSesplcOkjM3\n2Uu+oMWxQAw1NINnSLPinMVsutJy6ZqlV3McWNWe4T+STGtWhrPNqJEn45sIcCx4\nq+kGZ2NQ0FyIyT2eiLKOX5Rgb/a36E/aMk4VoDsaenBQgG7WLTnstb9sr7MIhS6A\nrwIDAQAB\n-----END PUBLIC KEY-----\n",
            "Comment": "example public key"
        }
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreatePublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/create-public-key.html)」を参照してください。**

### `delete-cloud-front-origin-access-identity`
<a name="cloudfront_DeleteCloudFrontOriginAccessIdentity_cli_2_topic"></a>

次のコード例は、`delete-cloud-front-origin-access-identity` を使用する方法を示しています。

**AWS CLI**  
**CloudFront オリジンアクセスアイデンティティを削除するには**  
次の例では、`E74FTE3AEXAMPLE` という ID のオリジンアクセスアイデンティティ (OAI) を削除しています。OAI を削除するには、OAI の ID と `ETag` が必要です。OAI ID は、create-cloud-front-origin-access-identity コマンドと list-cloud-front-origin-access-identities コマンドの出力で返されます。`ETag` を取得するには、get-cloud-front-origin-access-identity コマンドまたは get-cloud-front-origin-access-identity-config コマンドを使用します。`--if-match` オプションを使用して、OAI の `ETag` を指定します。  

```
aws cloudfront delete-cloud-front-origin-access-identity \
    --id E74FTE3AEXAMPLE \
    --if-match E2QWRUHEXAMPLE
```
成功した場合は、コマンドの出力はありません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCloudFrontOriginAccessIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/delete-cloud-front-origin-access-identity.html)」を参照してください。

### `delete-connection-group`
<a name="cloudfront_DeleteConnectionGroup_cli_2_topic"></a>

次のコード例は、`delete-connection-group` を使用する方法を示しています。

**AWS CLI**  
**接続グループを削除するには**  
次の `delete-connection-group` の例では、接続グループを削除します。接続グループは無効にする必要があり、どの CloudFront リソースにも関連付けることはできません。  

```
aws cloudfront delete-connection-group \
    --id cg_2wjLpjbHkLUdhWAjHllcOeABC \
    --if-match ETVPDKIKX0DABC
```
成功した場合は、コマンドの出力はありません。  
接続グループの管理の詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[カスタム接続グループを作成する (オプション)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConnectionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/delete-connection-group.html)」を参照してください。

### `delete-distribution-tenant`
<a name="cloudfront_DeleteDistributionTenant_cli_2_topic"></a>

次のコード例は、`delete-distribution-tenant` を使用する方法を示しています。

**AWS CLI**  
**ディストリビューションテナントを削除するには**  
次の `delete-distribution-tenant` の例では、ETag `ETVPDKIKX0DABC` を使用してディストリビューションテナントを削除します。ディストリビューションテナントは無効にする必要があり、どの CloudFront リソースにも関連付けることはできません。  

```
aws cloudfront delete-distribution-tenant \
    --id dt_2wjMUbg3NHZEQ7OfoalP5zi1AB \
    --if-match ETVPDKIKX0DABC
```
成功した場合は、コマンドの出力はありません。  
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ディストリビューションを削除する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/HowToDeleteDistribution.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDistributionTenant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/delete-distribution-tenant.html)」を参照してください。

### `delete-distribution`
<a name="cloudfront_DeleteDistribution_cli_2_topic"></a>

次のコード例は、`delete-distribution` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションを削除するには**  
次の例では、ID `EDFDVBD6EXAMPLE` の付いた CloudFront ディストリビューションを削除します。ディストリビューションを削除する前に、ディストリビューションを無効にする必要があります。ディストリビューションを無効にするには、update-distribution コマンドを使用します。詳細については、update-distribution の例を参照してください。  
ディストリビューションを無効にすると、ディストリビューションを削除できます。ディストリビューションを削除するには、`--if-match` オプションを使用してディストリビューション の`ETag` を指定する必要があります。`ETag` を取得するには、get-distribution コマンドまたは get-distribution-config コマンドを使用します。  

```
aws cloudfront delete-distribution \
    --id EDFDVBD6EXAMPLE \
    --if-match E2QWRUHEXAMPLE
```
成功した場合は、コマンドの出力はありません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteDistribution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/delete-distribution.html)」を参照してください。**

### `delete-field-level-encryption-config`
<a name="cloudfront_DeleteFieldLevelEncryptionConfig_cli_2_topic"></a>

次のコード例は、`delete-field-level-encryption-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化の設定を削除するには**  
次の例では、`C3KM2WVD605UAY` という ID を持つ CloudFront のフィールドレベル暗号化の設定を削除しています。フィールドレベル暗号化の設定を削除するには、その ID と `ETag` が必要です。ID は create-field-level-encryption-config コマンドと list-field-level-encryption-configs コマンドの出力で返されます。`ETag` を取得するには、get-field-level-encryption コマンドまたは get-field-level-encryption-config コマンドを使用します。`--if-match` オプションを使用して、設定の `ETag` を指定します。  

```
aws cloudfront delete-field-level-encryption-config \
    --id C3KM2WVD605UAY \
    --if-match E26M4BIAV81ZF6
```
成功した場合は、コマンドの出力はありません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFieldLevelEncryptionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/delete-field-level-encryption-config.html)」を参照してください。

### `delete-field-level-encryption-profile`
<a name="cloudfront_DeleteFieldLevelEncryptionProfile_cli_2_topic"></a>

次のコード例は、`delete-field-level-encryption-profile` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化のプロファイルを削除するには**  
次の例では、`PPK0UOSIF5WSV` という ID を持つ CloudFront のフィールドレベル暗号化のプロファイルを削除しています。フィールドレベル暗号化のプロファイルを削除するには、その ID と `ETag` が必要です。ID は create-field-level-encryption-profile コマンドと list-field-level-encryption-profiles コマンドの出力で返されます。`ETag` を取得するには、get-field-level-encryption-profile コマンドまたは get-field-level-encryption-profile-config コマンドを使用します。`--if-match` オプションを使用して、プロファイルの `ETag` を指定します。  

```
aws cloudfront delete-field-level-encryption-profile \
    --id PPK0UOSIF5WSV \
    --if-match EJETYFJ9CL66D
```
成功した場合は、コマンドの出力はありません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFieldLevelEncryptionProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/delete-field-level-encryption-profile.html)」を参照してください。

### `delete-public-key`
<a name="cloudfront_DeletePublicKey_cli_2_topic"></a>

次のコード例は、`delete-public-key` を使用する方法を示しています。

**AWS CLI**  
**CloudFront パブリックキーを削除するには**  
次の例では、`KDFB19YGCR002` という ID を持つ CloudFront パブリックキーを削除しています。パブリックキーを削除するには、その ID と `ETag` が必要です。ID は create-public-key コマンドと list-public-keys コマンドの出力で返されます。`ETag` を取得するには、get-public-key コマンドまたは get-public-key-config コマンドを使用します。`--if-match` オプションを使用して、パブリックキーの `ETag` を指定します。  

```
aws cloudfront delete-public-key \
    --id KDFB19YGCR002 \
    --if-match E2QWRUHEXAMPLE
```
成功した場合は、コマンドの出力はありません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/delete-public-key.html)」を参照してください。

### `disassociate-distribution-tenant-web-acl`
<a name="cloudfront_DisassociateDistributionTenantWebAcl_cli_2_topic"></a>

次のコード例は、`disassociate-distribution-tenant-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL とディストリビューションテナントの関連付けを解除するには**  
次の `disassociate-distribution-tenant-web-acl` の例では、ETag `E1PA6795UKMABC` を使用してディストリビューションテナントからウェブ ACL の関連付けを解除します。  

```
aws cloudfront disassociate-distribution-tenant-web-acl \
    --id dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB \
    --if-match E1PA6795UKMABC
```
出力:  

```
{
    "ETag": "E13V1IB3VIYABC",
    "Id": "dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB"
}
```
詳細については、*Amazon CloudFront デベロッパーガイド*」の[AWS 「WAF セキュリティ保護を無効にする](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/disable-waf.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateDistributionTenantWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/disassociate-distribution-tenant-web-acl.html)」を参照してください。

### `disassociate-distribution-web-acl`
<a name="cloudfront_DisassociateDistributionWebAcl_cli_2_topic"></a>

次のコード例は、`disassociate-distribution-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL と CloudFront ディストリビューションの関連付けを解除するには**  
次の `disassociate-distribution-web-acl` の例では、ETag `E13V1IB3VIYABC` を使用してウェブ ACL と CloudFront ディストリビューション間の関連付けを解除します。  

```
aws cloudfront disassociate-distribution-web-acl \
    --id E1XNX8R2GOAABC \
    --if-match EEZQ9Z24VM1ABC
```
出力:  

```
{
    "ETag": "E2YWS1C2J3OABC",
    "Id": "E1XNX8R2GOAABC"
}
```
詳細については、*Amazon CloudFront デベロッパーガイド*」の[AWS 「WAF セキュリティ保護を無効にする](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/disable-waf.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateDistributionWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/disassociate-distribution-web-acl.html)」を参照してください。

### `get-cloud-front-origin-access-identity-config`
<a name="cloudfront_GetCloudFrontOriginAccessIdentityConfig_cli_2_topic"></a>

次のコード例は、`get-cloud-front-origin-access-identity-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront オリジンアクセスアイデンティティ設定を取得するには**  
次の例では、ID が `E74FTE3AEXAMPLE` である CloudFront オリジンアクセスアイデンティティ (OAI) に関するメタデータ (`ETag` を含む) を取得します。OAI ID は、create-cloud-front-origin-access-identity コマンドと list-cloud-front-origin-access-identities コマンドの出力で返されます。  

```
aws cloudfront get-cloud-front-origin-access-identity-config --id E74FTE3AEXAMPLE
```
出力:  

```
{
    "ETag": "E2QWRUHEXAMPLE",
    "CloudFrontOriginAccessIdentityConfig": {
        "CallerReference": "cli-example",
        "Comment": "Example OAI"
    }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[GetCloudFrontOriginAccessIdentityConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-cloud-front-origin-access-identity-config.html)」を参照してください。**

### `get-cloud-front-origin-access-identity`
<a name="cloudfront_GetCloudFrontOriginAccessIdentity_cli_2_topic"></a>

次のコード例は、`get-cloud-front-origin-access-identity` を使用する方法を示しています。

**AWS CLI**  
**CloudFront オリジンアクセスアイデンティティを取得するには**  
次の例では、ID が `E74FTE3AEXAMPLE` である CloudFront オリジンアクセスアイデンティティ (OAI) を、`ETag` および関連する S3 正規 ID を含めて取得します。OAI ID は、create-cloud-front-origin-access-identity コマンドと list-cloud-front-origin-access-identities コマンドの出力で返されます。  

```
aws cloudfront get-cloud-front-origin-access-identity --id E74FTE3AEXAMPLE
```
出力:  

```
{
    "ETag": "E2QWRUHEXAMPLE",
    "CloudFrontOriginAccessIdentity": {
        "Id": "E74FTE3AEXAMPLE",
        "S3CanonicalUserId": "cd13868f797c227fbea2830611a26fe0a21ba1b826ab4bed9b7771c9aEXAMPLE",
        "CloudFrontOriginAccessIdentityConfig": {
            "CallerReference": "cli-example",
            "Comment": "Example OAI"
        }
    }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[GetCloudFrontOriginAccessIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-cloud-front-origin-access-identity.html)」を参照してください。**

### `get-connection-group-by-routing-endpoint`
<a name="cloudfront_GetConnectionGroupByRoutingEndpoint_cli_2_topic"></a>

次のコード例は、`get-connection-group-by-routing-endpoint` を使用する方法を示しています。

**AWS CLI**  
**ルーティングエンドポイントで接続グループを取得するには**  
次の `get-connection-group-by-routing-endpoint` の例では、ルーティングエンドポイントを使用して接続グループに関する情報を取得します。  

```
aws cloudfront get-connection-group-by-routing-endpoint \
    --routing-endpoint dvdg9gprgabc.cloudfront.net
```
出力:  

```
{
    "ETag": "E23ZP02F085ABC",
    "ConnectionGroup": {
        "Id": "cg_2wjDWTBKTlRB87cAaUQFaakABC",
        "Name": "connection-group-2",
        "Arn": "arn:aws:cloudfront::123456789012:connection-group/cg_2wjDWTBKTlRB87cAaUQFaakABC",
        "CreatedTime": "2025-05-06T15:42:00.790000+00:00",
        "LastModifiedTime": "2025-05-06T15:42:00.790000+00:00",
        "Ipv6Enabled": true,
        "RoutingEndpoint": "dvdg9gprgabc.cloudfront.net",
        "Status": "Deployed",
        "Enabled": true,
        "IsDefault": false
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[カスタム接続グループの作成 (オプション)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnectionGroupByRoutingEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-connection-group-by-routing-endpoint.html)」を参照してください。

### `get-connection-group`
<a name="cloudfront_GetConnectionGroup_cli_2_topic"></a>

次のコード例は、`get-connection-group` を使用する方法を示しています。

**AWS CLI**  
**CloudFront 接続グループを取得するには**  
次の `get-connection-group` の例では、CloudFront 接続グループに関する情報を取得します。  

```
aws cloudfront get-connection-group \
    --identifier cg_2wjDWTBKTlRB87cAaUQFaakABC
```
出力:  

```
{
    "ETag": "E23ZP02F085ABC",
    "ConnectionGroup": {
        "Id": "cg_2wjDWTBKTlRB87cAaUQFaakABC",
        "Name": "connection-group-2",
        "Arn": "arn:aws:cloudfront::123456789012:connection-group/cg_2wjDWTBKTlRB87cAaUQFaakABC",
        "CreatedTime": "2025-05-06T15:42:00.790000+00:00",
        "LastModifiedTime": "2025-05-06T15:42:00.790000+00:00",
        "Ipv6Enabled": true,
        "RoutingEndpoint": "dvdg9gprgabc.cloudfront.net",
        "Status": "Deployed",
        "Enabled": true,
        "IsDefault": false
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[カスタム接続グループの作成 (オプション)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnectionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-connection-group.html)」を参照してください。

### `get-distribution-config`
<a name="cloudfront_GetDistributionConfig_cli_2_topic"></a>

次のコード例は、`get-distribution-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューション設定を取得するには**  
次の例では、ID `EDFDVBD6EXAMPLE` の CloudFront ディストリビューションに関するメタデータ (`ETag` を含む) を取得します。ディストリビューション ID は create-distribution コマンドと list-distributions コマンドで返されます。  

```
aws cloudfront get-distribution-config \
    --id EDFDVBD6EXAMPLE
```
出力:  

```
{
    "ETag": "E2QWRUHEXAMPLE",
    "DistributionConfig": {
        "CallerReference": "cli-example",
        "Aliases": {
            "Quantity": 0
        },
        "DefaultRootObject": "index.html",
        "Origins": {
            "Quantity": 1,
            "Items": [
                {
                    "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                    "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                    "OriginPath": "",
                    "CustomHeaders": {
                        "Quantity": 0
                    },
                    "S3OriginConfig": {
                        "OriginAccessIdentity": ""
                    }
                }
            ]
        },
        "OriginGroups": {
            "Quantity": 0
        },
        "DefaultCacheBehavior": {
            "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
            "ForwardedValues": {
                "QueryString": false,
                "Cookies": {
                    "Forward": "none"
                },
                "Headers": {
                    "Quantity": 0
                },
                "QueryStringCacheKeys": {
                    "Quantity": 0
                }
            },
            "TrustedSigners": {
                "Enabled": false,
                "Quantity": 0
            },
            "ViewerProtocolPolicy": "allow-all",
            "MinTTL": 0,
            "AllowedMethods": {
                "Quantity": 2,
                "Items": [
                    "HEAD",
                    "GET"
                ],
                "CachedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ]
                }
            },
            "SmoothStreaming": false,
            "DefaultTTL": 86400,
            "MaxTTL": 31536000,
            "Compress": false,
            "LambdaFunctionAssociations": {
                "Quantity": 0
            },
            "FieldLevelEncryptionId": ""
        },
        "CacheBehaviors": {
            "Quantity": 0
        },
        "CustomErrorResponses": {
            "Quantity": 0
        },
        "Comment": "",
        "Logging": {
            "Enabled": false,
            "IncludeCookies": false,
            "Bucket": "",
            "Prefix": ""
        },
        "PriceClass": "PriceClass_All",
        "Enabled": true,
        "ViewerCertificate": {
            "CloudFrontDefaultCertificate": true,
            "MinimumProtocolVersion": "TLSv1",
            "CertificateSource": "cloudfront"
        },
        "Restrictions": {
            "GeoRestriction": {
                "RestrictionType": "none",
                "Quantity": 0
            }
        },
        "WebACLId": "",
        "HttpVersion": "http2",
        "IsIPV6Enabled": true
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetDistributionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-distribution-config.html)」を参照してください。**

### `get-distribution-tenant-by-domain`
<a name="cloudfront_GetDistributionTenantByDomain_cli_2_topic"></a>

次のコード例は、`get-distribution-tenant-by-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメイン別にディストリビューションテナント情報を取得するには**  
次の `get-distribution-tenant-by-domain` の例では、指定されたドメインを使用してディストリビューションテナントに関する情報を取得します。  

```
aws cloudfront get-distribution-tenant-by-domain \
    --domain example.com
```
出力:  

```
{
    "ETag": "E23ZP02F085ABC",
    "DistributionTenant": {
        "Id": "dt_2xVInRKCfUzQHgxosDs9hiLk1AB",
        "DistributionId": "E1XNX8R2GOAABC",
        "Name": "example-tenant-4",
        "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2xVInRKCfUzQHgxosDs9hiLk1AB",
        "Domains": [
            {
                "Domain": "example.com",
                "Status": "active"
            }
        ],
        "Parameters": [
            {
                "Name": "testParam",
                "Value": "defaultValue"
            }
        ],
        "ConnectionGroupId": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
        "CreatedTime": "2025-05-23T16:16:20.871000+00:00",
        "LastModifiedTime": "2025-05-23T16:16:20.871000+00:00",
        "Enabled": false,
        "Status": "Deployed"
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[Understand how multi-tenant distributions work](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-config-options.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDistributionTenantByDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-distribution-tenant-by-domain.html)」を参照してください。

### `get-distribution-tenant`
<a name="cloudfront_GetDistributionTenant_cli_2_topic"></a>

次のコード例は、`get-distribution-tenant` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションテナントに関する詳細を取得するには**  
次の `get-distribution-tenant` の例では、CloudFront ディストリビューションテナントに関する情報を取得します。  

```
aws cloudfront get-distribution-tenant \
    --id dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB
```
出力:  

```
{
    "ETag": "E23ZP02F085ABC",
    "DistributionTenant": {
        "Id": "dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB",
        "DistributionId": "E1XNX8R2GOAABC",
        "Name": "example-tenant-2",
        "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB",
        "Domains": [
            {
                "Domain": "example.com",
                "Status": "inactive"
            }
        ],
        "ConnectionGroupId": "cg_2wjDWTBKTlRB87cAaUQFaakABC",
        "CreatedTime": "2025-05-06T15:42:28.542000+00:00",
        "LastModifiedTime": "2025-05-06T15:42:37.724000+00:00",
        "Enabled": true,
        "Status": "InProgress"
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[Understand how multi-tenant distributions work](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-config-options.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDistributionTenant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-distribution-tenant.html)」を参照してください。

### `get-distribution`
<a name="cloudfront_GetDistribution_cli_2_topic"></a>

次のコード例は、`get-distribution` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションを取得するには**  
次の `get-distribution` の例では、ID が `EDFDVBD6EXAMPLE` である CloudFront ディストリビューション (`ETag` を含む) を取得します。ディストリビューション ID は create-distribution コマンドと list-distributions コマンドで返されます。  

```
aws cloudfront get-distribution \
    --id EDFDVBD6EXAMPLE
```
出力:  

```
{
    "ETag": "E2QWRUHEXAMPLE",
    "Distribution": {
        "Id": "EDFDVBD6EXAMPLE",
        "ARN": "arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE",
        "Status": "Deployed",
        "LastModifiedTime": "2019-12-04T23:35:41.433Z",
        "InProgressInvalidationBatches": 0,
        "DomainName": "d111111abcdef8.cloudfront.net",
        "ActiveTrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "DistributionConfig": {
            "CallerReference": "cli-example",
            "Aliases": {
                "Quantity": 0
            },
            "DefaultRootObject": "index.html",
            "Origins": {
                "Quantity": 1,
                "Items": [
                    {
                        "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                        "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                        "OriginPath": "",
                        "CustomHeaders": {
                            "Quantity": 0
                        },
                        "S3OriginConfig": {
                            "OriginAccessIdentity": ""
                        }
                    }
                ]
            },
            "OriginGroups": {
                "Quantity": 0
            },
            "DefaultCacheBehavior": {
                "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-cli-example",
                "ForwardedValues": {
                    "QueryString": false,
                    "Cookies": {
                        "Forward": "none"
                    },
                    "Headers": {
                        "Quantity": 0
                    },
                    "QueryStringCacheKeys": {
                        "Quantity": 0
                    }
                },
                "TrustedSigners": {
                    "Enabled": false,
                    "Quantity": 0
                },
                "ViewerProtocolPolicy": "allow-all",
                "MinTTL": 0,
                "AllowedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ],
                    "CachedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ]
                    }
                },
                "SmoothStreaming": false,
                "DefaultTTL": 86400,
                "MaxTTL": 31536000,
                "Compress": false,
                "LambdaFunctionAssociations": {
                    "Quantity": 0
                },
                "FieldLevelEncryptionId": ""
            },
            "CacheBehaviors": {
                "Quantity": 0
            },
            "CustomErrorResponses": {
                "Quantity": 0
            },
            "Comment": "",
            "Logging": {
                "Enabled": false,
                "IncludeCookies": false,
                "Bucket": "",
                "Prefix": ""
            },
            "PriceClass": "PriceClass_All",
            "Enabled": true,
            "ViewerCertificate": {
                "CloudFrontDefaultCertificate": true,
                "MinimumProtocolVersion": "TLSv1",
                "CertificateSource": "cloudfront"
            },
            "Restrictions": {
                "GeoRestriction": {
                    "RestrictionType": "none",
                    "Quantity": 0
                }
            },
            "WebACLId": "",
            "HttpVersion": "http2",
            "IsIPV6Enabled": true
        }
    }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[GetDistribution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-distribution.html)」を参照してください。**

### `get-field-level-encryption-config`
<a name="cloudfront_GetFieldLevelEncryptionConfig_cli_2_topic"></a>

次のコード例は、`get-field-level-encryption-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化の設定に関するメタデータを取得するには**  
次の例では、`C3KM2WVD605UAY` という ID を持つ CloudFront のフィールドレベル暗号化の設定に関するメタデータ (`ETag` を含む) を取得しています。  

```
aws cloudfront get-field-level-encryption-config --id C3KM2WVD605UAY
```
出力:  

```
{
    "ETag": "E2P4Z4VU7TY5SG",
    "FieldLevelEncryptionConfig": {
        "CallerReference": "cli-example",
        "Comment": "Example FLE configuration",
        "QueryArgProfileConfig": {
            "ForwardWhenQueryArgProfileIsUnknown": true,
            "QueryArgProfiles": {
                "Quantity": 0,
                "Items": []
            }
        },
        "ContentTypeProfileConfig": {
            "ForwardWhenContentTypeIsUnknown": true,
            "ContentTypeProfiles": {
                "Quantity": 1,
                "Items": [
                    {
                        "Format": "URLEncoded",
                        "ProfileId": "P280MFCLSYOCVU",
                        "ContentType": "application/x-www-form-urlencoded"
                    }
                ]
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFieldLevelEncryptionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-field-level-encryption-config.html)」を参照してください。

### `get-field-level-encryption-profile-config`
<a name="cloudfront_GetFieldLevelEncryptionProfileConfig_cli_2_topic"></a>

次のコード例は、`get-field-level-encryption-profile-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化のプロファイル設定を取得するには**  
次の例では、`PPK0UOSIF5WSV` という ID を持つ CloudFront のフィールドレベル暗号化のプロファイルに関するメタデータ (`ETag` を含む) を取得しています。  

```
aws cloudfront get-field-level-encryption-profile-config --id PPK0UOSIF5WSV
```
出力:  

```
{
    "ETag": "E1QQG65FS2L2GC",
    "FieldLevelEncryptionProfileConfig": {
        "Name": "ExampleFLEProfile",
        "CallerReference": "cli-example",
        "Comment": "FLE profile for AWS CLI example",
        "EncryptionEntities": {
            "Quantity": 1,
            "Items": [
                {
                    "PublicKeyId": "K2K8NC4HVFE3M0",
                    "ProviderId": "ExampleFLEProvider",
                    "FieldPatterns": {
                        "Quantity": 1,
                        "Items": [
                            "ExampleSensitiveField"
                        ]
                    }
                }
            ]
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFieldLevelEncryptionProfileConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-field-level-encryption-profile-config.html)」を参照してください。

### `get-field-level-encryption-profile`
<a name="cloudfront_GetFieldLevelEncryptionProfile_cli_2_topic"></a>

次のコード例は、`get-field-level-encryption-profile` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化のプロファイルを取得するには**  
次の例では、`PPK0UOSIF5WSV` という ID を持つ CloudFront のフィールドレベル暗号化のプロファイル (`ETag` を含む) を取得しています。  

```
aws cloudfront get-field-level-encryption-profile --id PPK0UOSIF5WSV
```
出力:  

```
{
    "ETag": "E1QQG65FS2L2GC",
    "FieldLevelEncryptionProfile": {
        "Id": "PPK0UOSIF5WSV",
        "LastModifiedTime": "2019-12-10T01:03:16.537Z",
        "FieldLevelEncryptionProfileConfig": {
            "Name": "ExampleFLEProfile",
            "CallerReference": "cli-example",
            "Comment": "FLE profile for AWS CLI example",
            "EncryptionEntities": {
                "Quantity": 1,
                "Items": [
                    {
                        "PublicKeyId": "K2K8NC4HVFE3M0",
                        "ProviderId": "ExampleFLEProvider",
                        "FieldPatterns": {
                            "Quantity": 1,
                            "Items": [
                                "ExampleSensitiveField"
                            ]
                        }
                    }
                ]
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFieldLevelEncryptionProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-field-level-encryption-profile.html)」を参照してください。

### `get-field-level-encryption`
<a name="cloudfront_GetFieldLevelEncryption_cli_2_topic"></a>

次のコード例は、`get-field-level-encryption` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化の設定を取得するには**  
次の例では、`C3KM2WVD605UAY` という ID を持つ CloudFront のフィールドレベル暗号化の設定 (`ETag` を含む) を取得しています。  

```
aws cloudfront get-field-level-encryption --id C3KM2WVD605UAY
```
出力:  

```
{
    "ETag": "E2P4Z4VU7TY5SG",
    "FieldLevelEncryption": {
        "Id": "C3KM2WVD605UAY",
        "LastModifiedTime": "2019-12-10T21:30:18.974Z",
        "FieldLevelEncryptionConfig": {
            "CallerReference": "cli-example",
            "Comment": "Example FLE configuration",
            "QueryArgProfileConfig": {
                "ForwardWhenQueryArgProfileIsUnknown": true,
                "QueryArgProfiles": {
                    "Quantity": 0,
                    "Items": []
                }
            },
            "ContentTypeProfileConfig": {
                "ForwardWhenContentTypeIsUnknown": true,
                "ContentTypeProfiles": {
                    "Quantity": 1,
                    "Items": [
                        {
                            "Format": "URLEncoded",
                            "ProfileId": "P280MFCLSYOCVU",
                            "ContentType": "application/x-www-form-urlencoded"
                        }
                    ]
                }
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFieldLevelEncryption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-field-level-encryption.html)」を参照してください。

### `get-invalidation-for-distribution-tenant`
<a name="cloudfront_GetInvalidationForDistributionTenant_cli_2_topic"></a>

次のコード例は、`get-invalidation-for-distribution-tenant` を使用する方法を示しています。

**AWS CLI**  
**ディストリビューションテナントの無効化を取得するには**  
次の `get-invalidation-for-distribution-tenant` の例では、ディストリビューションテナントの無効化に関する情報を取得します。  

```
aws cloudfront get-invalidation-for-distribution-tenant \
    --distribution-tenant-id dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB \
    --id I4CU23QAPKMUDUU06F9OFGFABC
```
出力:  

```
{
    "Invalidation": {
        "Id": "I4CU23QAPKMUDUU06F9OFGFABC",
        "Status": "Completed",
        "CreateTime": "2025-05-06T15:46:12.824000+00:00",
        "InvalidationBatch": {
            "Paths": {
                "Quantity": 2,
                "Items": [
                    "/example/invalidation",
                    "/more/invalidations"
                ]
            },
            "CallerReference": "007ee5a6-d0a0-42be-bb61-e7b915969b48"
        }
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ファイルを無効化してコンテンツを削除する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInvalidationForDistributionTenant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-invalidation-for-distribution-tenant.html)」を参照してください。

### `get-invalidation`
<a name="cloudfront_GetInvalidation_cli_2_topic"></a>

次のコード例は、`get-invalidation` を使用する方法を示しています。

**AWS CLI**  
**CloudFront の無効化を取得するには**  
次の例では、`EDFDVBD6EXAMPLE` という ID を持つ CloudFront ディストリビューションについて、`I2J0I21PCUYOIK` という ID の無効化を取得しています。  

```
aws cloudfront get-invalidation --id I2J0I21PCUYOIK --distribution-id EDFDVBD6EXAMPLE
```
出力:  

```
{
    "Invalidation": {
        "Status": "Completed",
        "InvalidationBatch": {
            "Paths": {
                "Items": [
                    "/example-path/example-file.jpg",
                    "/example-path/example-file-2.jpg"
                ],
                "Quantity": 2
            },
            "CallerReference": "cli-example"
        },
        "Id": "I2J0I21PCUYOIK",
        "CreateTime": "2019-12-05T18:40:49.413Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInvalidation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-invalidation.html)」を参照してください。

### `get-managed-certificate-details`
<a name="cloudfront_GetManagedCertificateDetails_cli_2_topic"></a>

次のコード例は、`get-managed-certificate-details` を使用する方法を示しています。

**AWS CLI**  
**マネージド証明書の詳細を取得するには**  
次の `get-managed-certificate-details` の例では、CloudFront マネージド ACM 証明書の詳細を取得します。  

```
aws cloudfront get-managed-certificate-details \
    --identifier dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB
```
出力:  

```
{
    "ManagedCertificateDetails": {
        "CertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/655dc1fe-6d37-451d-a013-c2db3a034abc",
        "CertificateStatus": "pending-validation",
        "ValidationTokenHost": "self-hosted",
        "ValidationTokenDetails": [
            {
                "Domain": "example.com",
                "RedirectTo": "validation.us-east-1.acm-validations.aws/123456789012/.well-known/pki-validation/b315c9ae21284e7918bb9f3f422ab1c7.txt",
                "RedirectFrom": "example.com/.well-known/pki-validation/b315c9ae21284e7918bb9f3f422ac3c7.txt"
            }
        ]
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[CloudFront ディストリビューションテナントの証明書をリクエストする](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/managed-cloudfront-certificates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetManagedCertificateDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-managed-certificate-details.html)」を参照してください。

### `get-public-key-config`
<a name="cloudfront_GetPublicKeyConfig_cli_2_topic"></a>

次のコード例は、`get-public-key-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront パブリックキーの設定を取得するには**  
次の例では、`KDFB19YGCR002` という ID を持つ CloudFront パブリックキーに関するメタデータ (`ETag` を含む) を取得します。パブリックキー ID は create-public-key コマンドと list-public-keys コマンドで返されます。  

```
aws cloudfront get-public-key-config --id KDFB19YGCR002
```
出力:  

```
{
    "ETag": "E2QWRUHEXAMPLE",
    "PublicKeyConfig": {
        "CallerReference": "cli-example",
        "Name": "ExampleKey",
        "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPMbCA2Ks0lnd7IR+3pw\nwd3H/7jPGwj8bLUmore7bX+oeGpZ6QmLAe/1UOWcmZX2u70dYcSIzB1ofZtcn4cJ\nenHBAzO3ohBY/L1tQGJfS2A+omnN6H16VZE1JCK8XSJyfze7MDLcUyHZETdxuvRb\nA9X343/vMAuQPnhinFJ8Wdy8YBXSPpy7r95ylUQd9LfYTBzVZYG2tSesplcOkjM3\n2Uu+oMWxQAw1NINnSLPinMVsutJy6ZqlV3McWNWe4T+STGtWhrPNqJEn45sIcCx4\nq+kGZ2NQ0FyIyT2eiLKOX5Rgb/a36E/aMk4VoDsaenBQgG7WLTnstb9sr7MIhS6A\nrwIDAQAB\n-----END PUBLIC KEY-----\n",
        "Comment": "example public key"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicKeyConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-public-key-config.html)」を参照してください。

### `get-public-key`
<a name="cloudfront_GetPublicKey_cli_2_topic"></a>

次のコード例は、`get-public-key` を使用する方法を示しています。

**AWS CLI**  
**CloudFront パブリックキーを取得するには**  
次の例では、`KDFB19YGCR002` という ID を持つ CloudFront パブリックキー (`ETag` を含む) を取得します。パブリックキー ID は create-public-key コマンドと list-public-keys コマンドで返されます。  

```
aws cloudfront get-public-key --id KDFB19YGCR002
```
出力:  

```
{
    "ETag": "E2QWRUHEXAMPLE",
    "PublicKey": {
        "Id": "KDFB19YGCR002",
        "CreatedTime": "2019-12-05T18:51:43.781Z",
        "PublicKeyConfig": {
            "CallerReference": "cli-example",
            "Name": "ExampleKey",
            "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPMbCA2Ks0lnd7IR+3pw\nwd3H/7jPGwj8bLUmore7bX+oeGpZ6QmLAe/1UOWcmZX2u70dYcSIzB1ofZtcn4cJ\nenHBAzO3ohBY/L1tQGJfS2A+omnN6H16VZE1JCK8XSJyfze7MDLcUyHZETdxuvRb\nA9X343/vMAuQPnhinFJ8Wdy8YBXSPpy7r95ylUQd9LfYTBzVZYG2tSesplcOkjM3\n2Uu+oMWxQAw1NINnSLPinMVsutJy6ZqlV3McWNWe4T+STGtWhrPNqJEn45sIcCx4\nq+kGZ2NQ0FyIyT2eiLKOX5Rgb/a36E/aMk4VoDsaenBQgG7WLTnstb9sr7MIhS6A\nrwIDAQAB\n-----END PUBLIC KEY-----\n",
            "Comment": "example public key"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/get-public-key.html)」を参照してください。

### `list-cloud-front-origin-access-identities`
<a name="cloudfront_ListCloudFrontOriginAccessIdentities_cli_2_topic"></a>

次のコード例は、`list-cloud-front-origin-access-identities` を使用する方法を示しています。

**AWS CLI**  
**CloudFront オリジンアクセスアイデンティティを一覧表示するには**  
次の の例では、 AWS アカウントの CloudFront オリジンアクセスアイデンティティ (OAIs) のリストを取得します。  

```
aws cloudfront list-cloud-front-origin-access-identities
```
出力:  

```
{
    "CloudFrontOriginAccessIdentityList": {
        "Items": [
            {
                "Id": "E74FTE3AEXAMPLE",
                "S3CanonicalUserId": "cd13868f797c227fbea2830611a26fe0a21ba1b826ab4bed9b7771c9aEXAMPLE",
                "Comment": "Example OAI"
            },
            {
                "Id": "EH1HDMBEXAMPLE",
                "S3CanonicalUserId": "1489f6f2e6faacaae7ff64c4c3e6956c24f78788abfc1718c3527c263bf7a17EXAMPLE",
                "Comment": "Test OAI"
            },
            {
                "Id": "E2X2C9TEXAMPLE",
                "S3CanonicalUserId": "cbfeebb915a64749f9be546a45b3fcfd3a31c779673c13c4dd460911ae402c2EXAMPLE",
                "Comment": "Example OAI #2"
            }
        ]
    }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListCloudFrontOriginAccessIdentities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-cloud-front-origin-access-identities.html)」を参照してください。**

### `list-connection-groups`
<a name="cloudfront_ListConnectionGroups_cli_2_topic"></a>

次のコード例は、`list-connection-groups` を使用する方法を示しています。

**AWS CLI**  
**接続グループを一覧表示するには**  
次の の`list-connection-groups`例では、 AWS アカウントで使用可能な接続グループを一覧表示します。  

```
aws cloudfront list-connection-groups
```
出力:  

```
{
    "ConnectionGroups": [
        {
            "Id": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
            "Name": "CreatedByCloudFront-cg_2whCJoXMYCjHcxaLGrkllvyABC",
            "Arn": "arn:aws:cloudfront::123456789012:connection-group/cg_2whCJoXMYCjHcxaLGrkllvyABC",
            "RoutingEndpoint": "d3sx0pso7m5abc.cloudfront.net",
            "CreatedTime": "2025-05-05T22:32:29.630000+00:00",
            "LastModifiedTime": "2025-05-05T22:32:29.630000+00:00",
            "ETag": "E23ZP02F085ABC",
            "Enabled": true,
            "Status": "Deployed",
            "IsDefault": true
        },
        {
            "Id": "cg_2wjDWTBKTlRB87cAaUQFaakABC",
            "Name": "connection-group-2",
            "Arn": "arn:aws:cloudfront::123456789012:connection-group/cg_2wjDWTBKTlRB87cAaUQFaakABC",
            "RoutingEndpoint": "dvdg9gprgabc.cloudfront.net",
            "CreatedTime": "2025-05-06T15:42:00.790000+00:00",
            "LastModifiedTime": "2025-05-06T15:42:00.790000+00:00",
            "ETag": "E23ZP02F085ABC",
            "Enabled": true,
            "Status": "Deployed",
            "IsDefault": false
        }
    ]
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[カスタム接続グループの作成 (オプション)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConnectionGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-connection-groups.html)」を参照してください。

### `list-distribution-tenants-by-customization`
<a name="cloudfront_ListDistributionTenantsByCustomization_cli_2_topic"></a>

次のコード例は、`list-distribution-tenants-by-customization` を使用する方法を示しています。

**AWS CLI**  
**カスタマイズ別にディストリビューションテナントを一覧表示するには**  
次の `list-distribution-tenants-by-customization` の例では、指定されたウェブ ACL を使用するディストリビューションテナントを一覧表示します。  

```
aws cloudfront list-distribution-tenants-by-customization \
    --web-acl-arn arn:aws:wafv2:us-east-1:123456789012:global/webacl/CreatedByCloudFront-0273cd2f/a3c19bce-42b5-48a1-a8d4-b2bb2f28eabc
```
出力:  

```
{
    "DistributionTenantList": [
        {
            "Id": "dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB",
            "DistributionId": "E1XNX8R2GOAABC",
            "Name": "example-tenant-2",
            "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB",
            "Domains": [
                {
                    "Domain": "example.com",
                    "Status": "inactive"
                }
            ],
            "ConnectionGroupId": "cg_2wjDWTBKTlRB87cAaUQFaakABC",
            "Customizations": {
                "WebAcl": {
                    "Action": "override",
                    "Arn": "arn:aws:wafv2:us-east-1:123456789012:global/webacl/CreatedByCloudFront-0273cd2f/a3c19bce-42b5-48a1-a8d4-b2bb2f28eabc"
                },
                "GeoRestrictions": {
                    "RestrictionType": "whitelist",
                    "Locations": [
                        "AL"
                    ]
                }
            },
            "CreatedTime": "2025-05-06T15:42:28.542000+00:00",
            "LastModifiedTime": "2025-05-06T16:14:08.710000+00:00",
            "ETag": "E1F83G8C2ARABC",
            "Enabled": true,
            "Status": "Deployed"
        }
    ]
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ディストリビューションテナントのカスタマイズ](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/tenant-customization.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDistributionTenantsByCustomization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-distribution-tenants-by-customization.html)」を参照してください。

### `list-distribution-tenants`
<a name="cloudfront_ListDistributionTenants_cli_2_topic"></a>

次のコード例は、`list-distribution-tenants` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションテナントを一覧表示するには**  
次の の`list-distribution-tenants`例では、 AWS アカウント内の 3 つの CloudFront ディストリビューションテナントを、関連付けられた接続グループ別に一覧表示します。  

```
aws cloudfront list-distribution-tenants \
    --association-filter ConnectionGroupId=cg_2whCJoXMYCjHcxaLGrkllvyABC \
    --max-items 3
```
出力:  

```
{
    "DistributionTenantList": [
        {
            "Id": "dt_2yMvQgam3QkJo2z54FDl91dk1AB",
            "DistributionId": "E1XNX8R2GOAABC",
            "Name": "new-tenant-customizations",
            "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2yMvQgam3QkJo2z54FDl91dk1AB",
            "Domains": [
                {
                    "Domain": "example.com",
                    "Status": "active"
                }
            ],
            "ConnectionGroupId": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
            "Customizations": {
                "WebAcl": {
                    "Action": "disable"
                },
                "GeoRestrictions": {
                    "RestrictionType": "whitelist",
                    "Locations": [
                        "DE"
                    ]
                }
            },
            "CreatedTime": "2025-06-11T15:54:02.142000+00:00",
            "LastModifiedTime": "2025-06-11T15:54:02.142000+00:00",
            "ETag": "E23ZP02F085ABC",
            "Enabled": false,
            "Status": "Deployed"
        },
        {
            "Id": "dt_2yMuV7NJuBcAB0cwwxMCBZQ1AB",
            "DistributionId": "E1XNX8R2GOAABC",
            "Name": "new-tenant",
            "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2yMuV7NJuBcAB0cwwxMCBZQ1AB",
            "Domains": [
                {
                    "Domain": "1.example.com",
                    "Status": "active"
                }
            ],
            "ConnectionGroupId": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
            "Customizations": {
                "GeoRestrictions": {
                    "RestrictionType": "whitelist",
                    "Locations": [
                        "DE"
                    ]
                }
            },
            "CreatedTime": "2025-06-11T15:46:23.466000+00:00",
            "LastModifiedTime": "2025-06-11T15:46:23.466000+00:00",
            "ETag": "E23ZP02F085ABC",
            "Enabled": false,
            "Status": "Deployed"
        },
        {
            "Id": "dt_2xVInRKCfUzQHgxosDs9hiLk1AB",
            "DistributionId": "E1XNX8R2GOAABC",
            "Name": "new-tenant-2",
            "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2xVInRKCfUzQHgxosDs9hiLk1AB",
            "Domains": [
                {
                    "Domain": "2.example.com",
                    "Status": "active"
                }
            ],
            "ConnectionGroupId": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
            "CreatedTime": "2025-05-23T16:16:20.871000+00:00",
            "LastModifiedTime": "2025-05-23T16:16:20.871000+00:00",
            "ETag": "E23ZP02F085ABC",
            "Enabled": false,
            "Status": "Deployed"
        }
    ],
    "NextToken": "eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAzfQ=="
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[Understand how multi-tenant distributions work](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-config-options.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDistributionTenants](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-distribution-tenants.html)」を参照してください。

### `list-distributions-by-connection-mode`
<a name="cloudfront_ListDistributionsByConnectionMode_cli_2_topic"></a>

次のコード例は、`list-distributions-by-connection-mode` を使用する方法を示しています。

**AWS CLI**  
**接続モードごとに CloudFront ディストリビューションを一覧表示するには**  
次の `list-distributions-by-connection-mode` の例では、指定された接続モードの CloudFront ディストリビューションを一覧表示します。  

```
aws cloudfront list-distributions-by-connection-mode \
    --connection-mode tenant-only
```
出力:  

```
{
    "DistributionList": {
        "Items": [
            {
                "Id": "E1XNX8R2GOAABC",
                "ARN": "arn:aws:cloudfront::123456789012:distribution/E1XNX8R2GOAABC",
                "ETag": "EPT4JPJQDY1ABC",
                "Status": "Deployed",
                "LastModifiedTime": "2025-05-23T16:16:15.691000+00:00",
                "DomainName": "-",
                "Aliases": {
                    "Quantity": 0
                },
                "Origins": {
                    "Quantity": 1,
                    "Items": [
                        {
                            "Id": "example-cfn-simple-distribution123",
                            "DomainName": "example.com",
                            "OriginPath": "",
                            "CustomHeaders": {
                                "Quantity": 0
                            },
                            "S3OriginConfig": {
                                "OriginAccessIdentity": ""
                            },
                            "ConnectionAttempts": 3,
                            "ConnectionTimeout": 10,
                            "OriginShield": {
                                "Enabled": false
                            },
                            "OriginAccessControlId": "E2CJRMB5LKEABC"
                        }
                    ]
                },
                "OriginGroups": {
                    "Quantity": 0
                },
                "DefaultCacheBehavior": {
                    "TargetOriginId": "example-cfn-simple-distribution123",
                    "TrustedKeyGroups": {
                        "Enabled": false,
                        "Quantity": 0
                    },
                    "ViewerProtocolPolicy": "allow-all",
                    "AllowedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ],
                        "CachedMethods": {
                            "Quantity": 2,
                            "Items": [
                                "HEAD",
                                "GET"
                            ]
                        }
                    },
                    "Compress": true,
                    "LambdaFunctionAssociations": {
                        "Quantity": 0
                    },
                    "FunctionAssociations": {
                        "Quantity": 0
                    },
                    "FieldLevelEncryptionId": "",
                    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e5abc",
                    "GrpcConfig": {
                        "Enabled": false
                    }
                },
                "CacheBehaviors": {
                    "Quantity": 0
                },
                "CustomErrorResponses": {
                    "Quantity": 0
                },
                "Comment": "",
                "PriceClass": "PriceClass_All",
                "Enabled": true,
                "ViewerCertificate": {
                    "CloudFrontDefaultCertificate": false,
                    "ACMCertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/ec53f564-ea5a-4e4a-a0a2-e3c989449abc",
                    "SSLSupportMethod": "sni-only",
                    "MinimumProtocolVersion": "TLSv1.2_2021",
                    "Certificate": "arn:aws:acm:us-east-1:123456789012:certificate/ec53f564-ea5a-4e4a-a0a2-e3c989449abc",
                    "CertificateSource": "acm"
                },
                "Restrictions": {
                    "GeoRestriction": {
                        "RestrictionType": "none",
                        "Quantity": 0
                    }
                },
                "WebACLId": "arn:aws:wafv2:us-east-1:123456789012:global/webacl/web-global-example/626900da-5f64-418b-ba9b-743f3746cabc",
                "HttpVersion": "http2",
                "IsIPV6Enabled": false,
                "Staging": false,
                "ConnectionMode": "tenant-only"
            }
        ]
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[カスタム接続グループの作成 (オプション)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDistributionsByConnectionMode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-distributions-by-connection-mode.html)」を参照してください。

### `list-distributions`
<a name="cloudfront_ListDistributions_cli_2_topic"></a>

次のコード例は、`list-distributions` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションを一覧表示するには**  
次の の例では、 AWS アカウントの CloudFront ディストリビューションのリストを取得します。  

```
aws cloudfront list-distributions
```
出力:  

```
{
    "DistributionList": {
        "Items": [
            {
                "Id": "E23YS8OEXAMPLE",
                "ARN": "arn:aws:cloudfront::123456789012:distribution/E23YS8OEXAMPLE",
                "Status": "Deployed",
                "LastModifiedTime": "2024-08-05T18:23:40.375000+00:00",
                "DomainName": "abcdefgh12ijk.cloudfront.net",
                "Aliases": {
                    "Quantity": 0
                },
                "Origins": {
                    "Quantity": 1,
                    "Items": [
                        {
                            "Id": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                            "DomainName": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                            "OriginPath": "",
                            "CustomHeaders": {
                                "Quantity": 0
                            },
                            "S3OriginConfig": {
                                "OriginAccessIdentity": ""
                            },
                            "ConnectionAttempts": 3,
                            "ConnectionTimeout": 10,
                            "OriginShield": {
                                "Enabled": false
                            },
                            "OriginAccessControlId": "EIAP8PEXAMPLE"
                        }
                    ]
                },
                "OriginGroups": {
                    "Quantity": 0
                },
                "DefaultCacheBehavior": {
                    "TargetOriginId": "amzn-s3-demo-bucket.s3.us-east-1.amazonaws.com",
                    "TrustedSigners": {
                        "Enabled": false,
                        "Quantity": 0
                    },
                    "TrustedKeyGroups": {
                        "Enabled": false,
                        "Quantity": 0
                    },
                    "ViewerProtocolPolicy": "allow-all",
                    "AllowedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ],
                        "CachedMethods": {
                            "Quantity": 2,
                            "Items": [
                                "HEAD",
                                "GET"
                            ]
                        }
                    },
                    "SmoothStreaming": false,
                    "Compress": true,
                    "LambdaFunctionAssociations": {
                        "Quantity": 0
                    },
                    "FunctionAssociations": {
                        "Quantity": 0
                    },
                    "FieldLevelEncryptionId": "",
                    "CachePolicyId": "658327ea-f89d-4fab-a63d-7e886EXAMPLE"
                },
                "CacheBehaviors": {
                    "Quantity": 0
                },
                "CustomErrorResponses": {
                    "Quantity": 0
                },
                "Comment": "",
                "PriceClass": "PriceClass_All",
                "Enabled": true,
                "ViewerCertificate": {
                    "CloudFrontDefaultCertificate": true,
                    "SSLSupportMethod": "vip",
                    "MinimumProtocolVersion": "TLSv1",
                    "CertificateSource": "cloudfront"
                },
                "Restrictions": {
                    "GeoRestriction": {
                        "RestrictionType": "none",
                        "Quantity": 0
                    }
                },
                "WebACLId": "",
                "HttpVersion": "HTTP2",
                "IsIPV6Enabled": true,
                "Staging": false
            }
        ]
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListDistributions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-distributions.html)」を参照してください。**

### `list-domain-conflicts`
<a name="cloudfront_ListDomainConflicts_cli_2_topic"></a>

次のコード例は、`list-domain-conflicts` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションのドメイン競合を一覧表示するには**  
次の `list-domain-conflicts` の例では、CloudFront ディストリビューションのドメイン競合を一覧表示します。  

```
aws cloudfront list-domain-conflicts \
    --domain example.com \
    --domain-control-validation-resource "DistributionTenantId=dt_2x9GhoK0TZRsohWzv1b9It8J1AB"
```
出力:  

```
{
    "DomainConflicts": [
        {
            "Domain": "example.com",
            "ResourceType": "distribution-tenant",
            "ResourceId": "***************ohWzv1b9It8J1AB",
            "AccountId": "123456789012"
        }
    ]
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[代替ドメイン名を別のディストリビューションに移動する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/alternate-domain-names-move.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDomainConflicts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-domain-conflicts.html)」を参照してください。

### `list-field-level-encryption-configs`
<a name="cloudfront_ListFieldLevelEncryptionConfigs_cli_2_topic"></a>

次のコード例は、`list-field-level-encryption-configs` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化の設定を一覧表示するには**  
次の の例では、 AWS アカウントの CloudFront フィールドレベルの暗号化設定のリストを取得します。  

```
aws cloudfront list-field-level-encryption-configs
```
出力:  

```
{
    "FieldLevelEncryptionList": {
        "MaxItems": 100,
        "Quantity": 1,
        "Items": [
            {
                "Id": "C3KM2WVD605UAY",
                "LastModifiedTime": "2019-12-10T21:30:18.974Z",
                "Comment": "Example FLE configuration",
                "QueryArgProfileConfig": {
                    "ForwardWhenQueryArgProfileIsUnknown": true,
                    "QueryArgProfiles": {
                        "Quantity": 0,
                        "Items": []
                    }
                },
                "ContentTypeProfileConfig": {
                    "ForwardWhenContentTypeIsUnknown": true,
                    "ContentTypeProfiles": {
                        "Quantity": 1,
                        "Items": [
                            {
                                "Format": "URLEncoded",
                                "ProfileId": "P280MFCLSYOCVU",
                                "ContentType": "application/x-www-form-urlencoded"
                            }
                        ]
                    }
                }
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFieldLevelEncryptionConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-field-level-encryption-configs.html)」を参照してください。

### `list-field-level-encryption-profiles`
<a name="cloudfront_ListFieldLevelEncryptionProfiles_cli_2_topic"></a>

次のコード例は、`list-field-level-encryption-profiles` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化のプロファイルを一覧表示するには**  
次の の例では、 AWS アカウントの CloudFront フィールドレベルの暗号化プロファイルのリストを取得します。  

```
aws cloudfront list-field-level-encryption-profiles
```
出力:  

```
{
    "FieldLevelEncryptionProfileList": {
        "MaxItems": 100,
        "Quantity": 2,
        "Items": [
            {
                "Id": "P280MFCLSYOCVU",
                "LastModifiedTime": "2019-12-05T01:05:39.896Z",
                "Name": "ExampleFLEProfile",
                "EncryptionEntities": {
                    "Quantity": 1,
                    "Items": [
                        {
                            "PublicKeyId": "K2K8NC4HVFE3M0",
                            "ProviderId": "ExampleFLEProvider",
                            "FieldPatterns": {
                                "Quantity": 1,
                                "Items": [
                                    "ExampleSensitiveField"
                                ]
                            }
                        }
                    ]
                },
                "Comment": "FLE profile for AWS CLI example"
            },
            {
                "Id": "PPK0UOSIF5WSV",
                "LastModifiedTime": "2019-12-10T01:03:16.537Z",
                "Name": "ExampleFLEProfile2",
                "EncryptionEntities": {
                    "Quantity": 1,
                    "Items": [
                        {
                            "PublicKeyId": "K2ABC10EXAMPLE",
                            "ProviderId": "ExampleFLEProvider2",
                            "FieldPatterns": {
                                "Quantity": 1,
                                "Items": [
                                    "ExampleSensitiveField2"
                                ]
                            }
                        }
                    ]
                },
                "Comment": "FLE profile #2 for AWS CLI example"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFieldLevelEncryptionProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-field-level-encryption-profiles.html)」を参照してください。

### `list-invalidations-for-distribution-tenant`
<a name="cloudfront_ListInvalidationsForDistributionTenant_cli_2_topic"></a>

次のコード例は、`list-invalidations-for-distribution-tenant` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションテナントの無効化を一覧表示するには**  
次の `list-invalidations-for-distribution-tenant` の例では、CloudFront ディストリビューションテナントの無効化を一覧表示します。  

```
aws cloudfront list-invalidations-for-distribution-tenant \
    --id dt_2wjDZi3hD1ivOXf6rpZJOSNE1AB
```
出力:  

```
{
    "InvalidationList": {
        "Items": [
            {
                "Id": "I4CU23QAPKMUDUU06F9OFGFABC",
                "CreateTime": "2025-05-06T15:46:12.824000+00:00",
                "Status": "Completed"
            }
        ]
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ファイルを無効化してコンテンツを削除する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInvalidationsForDistributionTenant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-invalidations-for-distribution-tenant.html)」を参照してください。

### `list-invalidations`
<a name="cloudfront_ListInvalidations_cli_2_topic"></a>

次のコード例は、`list-invalidations` を使用する方法を示しています。

**AWS CLI**  
**CloudFront の無効化を一覧表示するには**  
次の例では、`EDFDVBD6EXAMPLE` という ID を持つ CloudFront ディストリビューションの無効化のリストを取得しています。  

```
aws cloudfront list-invalidations --distribution-id EDFDVBD6EXAMPLE
```
出力:  

```
{
    "InvalidationList": {
        "Marker": "",
        "Items": [
            {
                "Status": "Completed",
                "Id": "YNY2LI2BVJ4NJU",
                "CreateTime": "2019-08-31T21:15:52.042Z"
            }
        ],
        "IsTruncated": false,
        "MaxItems": 100,
        "Quantity": 1
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInvalidations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-invalidations.html)」を参照してください。

### `list-public-keys`
<a name="cloudfront_ListPublicKeys_cli_2_topic"></a>

次のコード例は、`list-public-keys` を使用する方法を示しています。

**AWS CLI**  
**CloudFront パブリックキーを一覧表示するには**  
次の の例では、 AWS アカウントの CloudFront パブリックキーのリストを取得します。  

```
aws cloudfront list-public-keys
```
出力:  

```
{
    "PublicKeyList": {
        "MaxItems": 100,
        "Quantity": 2,
        "Items": [
            {
                "Id": "K2K8NC4HVFE3M0",
                "Name": "ExampleKey",
                "CreatedTime": "2019-12-05T01:04:28.818Z",
                "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxPMbCA2Ks0lnd7IR+3pw\nwd3H/7jPGwj8bLUmore7bX+oeGpZ6QmLAe/1UOWcmZX2u70dYcSIzB1ofZtcn4cJ\nenHBAzO3ohBY/L1tQGJfS2A+omnN6H16VZE1JCK8XSJyfze7MDLcUyHZETdxuvRb\nA9X343/vMAuQPnhinFJ8Wdy8YBXSPpy7r95ylUQd9LfYTBzVZYG2tSesplcOkjM3\n2Uu+oMWxQAw1NINnSLPinMVsutJy6ZqlV3McWNWe4T+STGtWhrPNqJEn45sIcCx4\nq+kGZ2NQ0FyIyT2eiLKOX5Rgb/a36E/aMk4VoDsaenBQgG7WLTnstb9sr7MIhS6A\nrwIDAQAB\n-----END PUBLIC KEY-----\n",
                "Comment": "example public key"
            },
            {
                "Id": "K1S0LWQ2L5HTBU",
                "Name": "ExampleKey2",
                "CreatedTime": "2019-12-09T23:28:11.110Z",
                "EncodedKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApOCAg88A8+f4dujn9Izt\n26LxtgAkn2opGgo/NKpMiaisyw5qlg3f1gol7FV6pYNl78iJg3EO8JBbwtlH+cR9\nLGSf60NDeVhm76Oc39Np/vWgOdsGQcRbi9WmKZeSODqjQGzVZWqPmito3FzWVk6b\nfVY5N36U/RdbVAJm95Km+qaMYlbIdF40t72bi3IkKYV5hlB2XoDjlQ9F6ajQKyTB\nMHa3SN8q+3ZjQ4sJJ7D1V6r4wR8jDcFVD5NckWJmmgIVnkOQM37NYeoDnkaOuTpu\nha/+3b8tOb2z3LBVHPkp85zJRAOXacSwf5rZtPYKBNFsixTa2n55k2r218mOkMC4\nUwIDAQAB\n-----END PUBLIC KEY-----",
                "Comment": "example public key #2"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPublicKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-public-keys.html)」を参照してください。

### `list-tags-for-resource`
<a name="cloudfront_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションのタグを一覧表示するには**  
次の例は、CloudFront ディストリビューションのタグのリストを取得しています。  

```
aws cloudfront list-tags-for-resource \
    --resource arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE
```
出力:  

```
{
    "Tags": {
        "Items": [
            {
                "Key": "DateCreated",
                "Value": "2019-12-04"
            },
            {
                "Key": "Name",
                "Value": "Example name"
            },
            {
                "Key": "Project",
                "Value": "Example project"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/list-tags-for-resource.html)」を参照してください。

### `sign`
<a name="cloudfront_Sign_cli_2_topic"></a>

次のコード例は、`sign` を使用する方法を示しています。

**AWS CLI**  
**CloudFront URL に署名するには**  
次の例では、CloudFront URL に署名しています。URL に署名するには、キーペア ID ( AWS マネジメントコンソールでは**アクセスキー ID** と呼ばれます) と、信頼された署名者の CloudFront キーペアのプライベートキーが必要です。署名付き URL の詳細については、「*Amazon CloudFront 開発者ガイド*」の「[署名付き URL と署名付き Cookie を使用してプライベートコンテンツを供給する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html)」を参照してください。  

```
aws cloudfront sign \
    --url https://d111111abcdef8.cloudfront.net/private-content/private-file.html \
    --key-pair-id APKAEIBAERJR2EXAMPLE \
    --private-key file://cf-signer-priv-key.pem \
    --date-less-than 2020-01-01
```
出力:  

```
https://d111111abcdef8.cloudfront.net/private-content/private-file.html?Expires=1577836800&Signature=nEXK7Kby47XKeZQKVc6pwkif6oZc-JWSpDkH0UH7EBGGqvgurkecCbgL5VfUAXyLQuJxFwRQWscz-owcq9KpmewCXrXQbPaJZNi9XSNwf4YKurPDQYaRQawKoeenH0GFteRf9ELK-Bs3nljTLjtbgzIUt7QJNKXcWr8AuUYikzGdJ4-qzx6WnxXfH~fxg4-GGl6l2kgCpXUB6Jx6K~Y3kpVOdzUPOIqFLHAnJojbhxqrVejomZZ2XrquDvNUCCIbePGnR3d24UPaLXG4FKOqNEaWDIBXu7jUUPwOyQCvpt-GNvjRJxqWf93uMobeMOiVYahb-e0KItiQewGcm0eLZQ__&Key-Pair-Id=APKAEIBAERJR2EXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Sign](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/sign.html)」を参照してください。

### `tag-resource`
<a name="cloudfront_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションにタグを追加するには**  
次の `tag-resource` の例では、指定された CloudFront ディストリビューションに 2 つのタグを追加しています。  

```
aws cloudfront tag-resource \
    --resource arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE \
    --tags 'Items=[{Key=Name,Value="Example name"},{Key=Project,Value="Example project"}]'
```
次の例に示すように、コマンドライン引数を使用する代わりに、JSON ファイルでタグを指定できます。  

```
aws cloudfront tag-resource \
    --resource arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE \
    --tags file://tags.json
```
`tags.json` の内容:  

```
{
    "Items": [
        {
            "Key": "Name",
            "Value": "Example name"
        },
        {
            "Key": "Project",
            "Value": "Example project"
        }
    ]
}
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="cloudfront_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションからタグを削除するには**  
次の例では、コマンドライン引数を使用して CloudFront ディストリビューションから 2 つのタグを削除しています。  

```
aws cloudfront untag-resource \
    --resource arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE \
    --tag-keys Items=Name,Project
```
次の例に示すように、コマンドライン引数を使用する代わりに、JSON ファイルでタグキーを指定できます。  

```
aws cloudfront untag-resource \
    --resource arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE \
    --tag-keys file://tag-keys.json
```
`tag-keys.json` ファイルは、以下を含む現在のフォルダ内にある JSON ドキュメントです。  

```
{
    "Items": [
        "Name",
        "Project"
    ]
}
```
成功した場合は、コマンドの出力はありません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/untag-resource.html)」を参照してください。

### `update-cloud-front-origin-access-identity`
<a name="cloudfront_UpdateCloudFrontOriginAccessIdentity_cli_2_topic"></a>

次のコード例は、`update-cloud-front-origin-access-identity` を使用する方法を示しています。

**AWS CLI**  
**CloudFront オリジンアクセスアイデンティティを更新するには**  
次のリクエスト例では、`E74FTE3AEXAMPLE` という ID のオリジンアクセスアイデンティティ (OAI) を更新しています。更新できるフィールドは、OAI の `Comment` のみです。  
OAI を更新するには、OAI の ID と `ETag` が必要です。OAI ID は、create-cloud-front-origin-access-identity コマンドと list-cloud-front-origin-access-identities コマンドの出力で返されます。`ETag` を取得するには、get-cloud-front-origin-access-identity コマンドまたは get-cloud-front-origin-access-identity-config コマンドを使用します。`--if-match` オプションを使用して、OAI の `ETag` を指定します。  

```
aws cloudfront update-cloud-front-origin-access-identity \
    --id E74FTE3AEXAMPLE \
    --if-match E2QWRUHEXAMPLE \
    --cloud-front-origin-access-identity-config \
        CallerReference=cli-example,Comment="Example OAI Updated"
```
次の例に示すように、同じことは、JSON ファイルで OAI 設定を指定することでも実現できます。  

```
aws cloudfront update-cloud-front-origin-access-identity \
    --id E74FTE3AEXAMPLE \
    --if-match E2QWRUHEXAMPLE \
    --cloud-front-origin-access-identity-config file://OAI-config.json
```
`OAI-config.json` ファイルは、以下を含む現在のディレクトリ内にある JSON ドキュメントです。  

```
{
    "CallerReference": "cli-example",
    "Comment": "Example OAI Updated"
}
```
OAI 設定をコマンドライン引数で指定する場合も、JSON ファイルで指定する場合も、出力は変わりません。  

```
{
    "ETag": "E9LHASXEXAMPLE",
    "CloudFrontOriginAccessIdentity": {
        "Id": "E74FTE3AEXAMPLE",
        "S3CanonicalUserId": "cd13868f797c227fbea2830611a26fe0a21ba1b826ab4bed9b7771c9aEXAMPLE",
        "CloudFrontOriginAccessIdentityConfig": {
            "CallerReference": "cli-example",
            "Comment": "Example OAI Updated"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCloudFrontOriginAccessIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/update-cloud-front-origin-access-identity.html)」を参照してください。

### `update-connection-group`
<a name="cloudfront_UpdateConnectionGroup_cli_2_topic"></a>

次のコード例は、`update-connection-group` を使用する方法を示しています。

**AWS CLI**  
**CloudFront 接続グループを更新するには**  
次の `update-connection-group` の例では、CloudFront 接続グループを無効にし、IPv6 を無効にします。  

```
aws cloudfront update-connection-group \
    --id cg_2yHsDkcPKeUlVkk3aEgLKcjABC \
    --no-ipv6-enabled \
    --no-enabled \
    --if-match E3UN6WX5RRO2ABC
```
出力:  

```
{
    "ETag": "E1F83G8C2ARABC",
    "ConnectionGroup": {
        "Id": "cg_2yHsDkcPKeUlVkk3aEgLKcjABC",
        "Name": "cg-example",
        "Arn": "arn:aws:cloudfront::123456789012:connection-group/cg_2yHsDkcPKeUlVkk3aEgLKcjABC",
        "CreatedTime": "2025-06-09T20:58:35.481000+00:00",
        "LastModifiedTime": "2025-06-11T16:25:54.280000+00:00",
        "Ipv6Enabled": false,
        "RoutingEndpoint": "du9xp1elo1abc.cloudfront.net",
        "Status": "InProgress",
        "Enabled": false,
        "IsDefault": false
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[カスタム接続グループの作成 (オプション)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/custom-connection-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateConnectionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/update-connection-group.html)」を参照してください。

### `update-distribution-tenant`
<a name="cloudfront_UpdateDistributionTenant_cli_2_topic"></a>

次のコード例は、`update-distribution-tenant` を使用する方法を示しています。

**AWS CLI**  
**CloudFront ディストリビューションテナントを更新するには**  
次の `update-distribution-tenant` の例では、新しいパラメータ値で CloudFront ディストリビューションテナントを更新し、地域制限に国を追加します。  

```
aws cloudfront update-distribution-tenant \
    --cli-input-json file://update-tenant.json
```
`update-tenant.json` の内容:  

```
{
    "Id": "dt_2yMvQgam3QkJo2z54FDl91dk1AB",
    "IfMatch": "E1F83G8C2ARABC",
    "Parameters": [
        {
            "Name": "testParam",
            "Value": "newParameterValue"
        }
    ],
    "Customizations": {
        "WebAcl": {
            "Action": "disable"
        },
        "GeoRestrictions": {
            "RestrictionType": "whitelist",
            "Locations": [
                "DE",
                "GB",
                "ES"
            ]
        }
    }
}
```
出力:  

```
{
    "ETag": "E1PA6795UKMABC",
    "DistributionTenant": {
        "Id": "dt_2yMvQgam3QkJo2z54FDl91dk1AB",
        "DistributionId": "E1XNX8R2GOAABC",
        "Name": "new-tenant-customizations",
        "Arn": "arn:aws:cloudfront::123456789012:distribution-tenant/dt_2yMvQgam3QkJo2z54FDl91dk1AB",
        "Domains": [
            {
                "Domain": "example.com",
                "Status": "active"
            }
        ],
        "Customizations": {
            "WebAcl": {
                "Action": "disable"
            },
            "GeoRestrictions": {
                "RestrictionType": "whitelist",
                "Locations": [
                    "DE",
                    "ES",
                    "GB"
                ]
            }
        },
        "Parameters": [
            {
                "Name": "testParam",
                "Value": "newParameterValue"
            }
        ],
        "ConnectionGroupId": "cg_2whCJoXMYCjHcxaLGrkllvyABC",
        "CreatedTime": "2025-06-11T15:54:02.142000+00:00",
        "LastModifiedTime": "2025-06-11T16:42:45.531000+00:00",
        "Enabled": false,
        "Status": "InProgress"
    }
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[ディストリビューションテナントのカスタマイズ](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/tenant-customization.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDistributionTenant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/update-distribution-tenant.html)」を参照してください。

### `update-distribution`
<a name="cloudfront_UpdateDistribution_cli_2_topic"></a>

次のコード例は、`update-distribution` を使用する方法を示しています。

**AWS CLI**  
**例 1: CloudFront ディストリビューションのデフォルトルートオブジェクトを更新するには**  
次の例では、ID が `EDFDVBD6EXAMPLE` の CloudFront ディストリビューションのデフォルトルートオブジェクトを `index.html` に更新します。  

```
aws cloudfront update-distribution \
    --id EDFDVBD6EXAMPLE \
    --default-root-object index.html
```
出力:  

```
{
    "ETag": "E2QWRUHEXAMPLE",
    "Distribution": {
        "Id": "EDFDVBD6EXAMPLE",
        "ARN": "arn:aws:cloudfront::123456789012:distribution/EDFDVBD6EXAMPLE",
        "Status": "InProgress",
        "LastModifiedTime": "2019-12-06T18:55:39.870Z",
        "InProgressInvalidationBatches": 0,
        "DomainName": "d111111abcdef8.cloudfront.net",
        "ActiveTrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "DistributionConfig": {
            "CallerReference": "6b10378d-49be-4c4b-a642-419ccaf8f3b5",
            "Aliases": {
                "Quantity": 0
            },
            "DefaultRootObject": "index.html",
            "Origins": {
                "Quantity": 1,
                "Items": [
                    {
                        "Id": "example-website",
                        "DomainName": "www.example.com",
                        "OriginPath": "",
                        "CustomHeaders": {
                            "Quantity": 0
                        },
                        "CustomOriginConfig": {
                            "HTTPPort": 80,
                            "HTTPSPort": 443,
                            "OriginProtocolPolicy": "match-viewer",
                            "OriginSslProtocols": {
                                "Quantity": 2,
                                "Items": [
                                    "SSLv3",
                                    "TLSv1"
                                ]
                            },
                            "OriginReadTimeout": 30,
                            "OriginKeepaliveTimeout": 5
                        }
                    }
                ]
            },
            "OriginGroups": {
                "Quantity": 0
            },
            "DefaultCacheBehavior": {
                "TargetOriginId": "example-website",
                "ForwardedValues": {
                    "QueryString": false,
                    "Cookies": {
                        "Forward": "none"
                    },
                    "Headers": {
                        "Quantity": 1,
                        "Items": [
                            "*"
                        ]
                    },
                    "QueryStringCacheKeys": {
                        "Quantity": 0
                    }
                },
                "TrustedSigners": {
                    "Enabled": false,
                    "Quantity": 0
                },
                "ViewerProtocolPolicy": "allow-all",
                "MinTTL": 0,
                "AllowedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ],
                    "CachedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ]
                    }
                },
                "SmoothStreaming": false,
                "DefaultTTL": 86400,
                "MaxTTL": 31536000,
                "Compress": false,
                "LambdaFunctionAssociations": {
                    "Quantity": 0
                },
                "FieldLevelEncryptionId": ""
            },
            "CacheBehaviors": {
                "Quantity": 0
            },
            "CustomErrorResponses": {
                "Quantity": 0
            },
            "Comment": "",
            "Logging": {
                "Enabled": false,
                "IncludeCookies": false,
                "Bucket": "",
                "Prefix": ""
            },
            "PriceClass": "PriceClass_All",
            "Enabled": true,
            "ViewerCertificate": {
                "CloudFrontDefaultCertificate": true,
                "MinimumProtocolVersion": "TLSv1",
                "CertificateSource": "cloudfront"
            },
            "Restrictions": {
                "GeoRestriction": {
                    "RestrictionType": "none",
                    "Quantity": 0
                }
            },
            "WebACLId": "",
            "HttpVersion": "http1.1",
            "IsIPV6Enabled": true
        }
    }
}
```
**例 2: CloudFront ディストリビューションを更新するには**  
次の例では、`dist-config-disable.json` という名前の JSON ファイルでディストリビューション設定を指定して、ID `EMLARXS9EXAMPLE` を持つ CloudFront ディストリビューションを無効にします。ディストリビューションを更新するには、`--if-match` オプションを使用してディストリビューションの `ETag` を指定する必要があります。`ETag` を取得するには、get-distribution コマンドまたは get-distribution-config コマンドを使用します。JSON ファイルでは `Enabled` フィールドが `false` に設定されていることに注意してください。  
次の例を使用してディストリビューションを無効にした後は、delete-distribution コマンドを使用してディストリビューションを削除できます。  

```
aws cloudfront update-distribution \
    --id EMLARXS9EXAMPLE \
    --if-match E2QWRUHEXAMPLE \
    --distribution-config file://dist-config-disable.json
```
`dist-config-disable.json` の内容:  

```
{
    "CallerReference": "cli-1574382155-496510",
    "Aliases": {
        "Quantity": 0
    },
    "DefaultRootObject": "index.html",
    "Origins": {
        "Quantity": 1,
        "Items": [
            {
                "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-1574382155-273939",
                "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                "OriginPath": "",
                "CustomHeaders": {
                    "Quantity": 0
                },
                "S3OriginConfig": {
                    "OriginAccessIdentity": ""
                }
            }
        ]
    },
    "OriginGroups": {
        "Quantity": 0
    },
    "DefaultCacheBehavior": {
        "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-1574382155-273939",
        "ForwardedValues": {
            "QueryString": false,
            "Cookies": {
                "Forward": "none"
            },
            "Headers": {
                "Quantity": 0
            },
            "QueryStringCacheKeys": {
                "Quantity": 0
            }
        },
        "TrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "ViewerProtocolPolicy": "allow-all",
        "MinTTL": 0,
        "AllowedMethods": {
            "Quantity": 2,
            "Items": [
                "HEAD",
                "GET"
            ],
            "CachedMethods": {
                "Quantity": 2,
                "Items": [
                    "HEAD",
                    "GET"
                ]
            }
        },
        "SmoothStreaming": false,
        "DefaultTTL": 86400,
        "MaxTTL": 31536000,
        "Compress": false,
        "LambdaFunctionAssociations": {
            "Quantity": 0
        },
        "FieldLevelEncryptionId": ""
    },
    "CacheBehaviors": {
        "Quantity": 0
    },
    "CustomErrorResponses": {
        "Quantity": 0
    },
    "Comment": "",
    "Logging": {
        "Enabled": false,
        "IncludeCookies": false,
        "Bucket": "",
        "Prefix": ""
    },
    "PriceClass": "PriceClass_All",
    "Enabled": false,
    "ViewerCertificate": {
        "CloudFrontDefaultCertificate": true,
        "MinimumProtocolVersion": "TLSv1",
        "CertificateSource": "cloudfront"
    },
    "Restrictions": {
        "GeoRestriction": {
            "RestrictionType": "none",
            "Quantity": 0
        }
    },
    "WebACLId": "",
    "HttpVersion": "http2",
    "IsIPV6Enabled": true
}
```
出力:  

```
{
    "ETag": "E9LHASXEXAMPLE",
    "Distribution": {
        "Id": "EMLARXS9EXAMPLE",
        "ARN": "arn:aws:cloudfront::123456789012:distribution/EMLARXS9EXAMPLE",
        "Status": "InProgress",
        "LastModifiedTime": "2019-12-06T18:32:35.553Z",
        "InProgressInvalidationBatches": 0,
        "DomainName": "d111111abcdef8.cloudfront.net",
        "ActiveTrustedSigners": {
            "Enabled": false,
            "Quantity": 0
        },
        "DistributionConfig": {
            "CallerReference": "cli-1574382155-496510",
            "Aliases": {
                "Quantity": 0
            },
            "DefaultRootObject": "index.html",
            "Origins": {
                "Quantity": 1,
                "Items": [
                    {
                        "Id": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-1574382155-273939",
                        "DomainName": "amzn-s3-demo-bucket.s3.amazonaws.com",
                        "OriginPath": "",
                        "CustomHeaders": {
                            "Quantity": 0
                        },
                        "S3OriginConfig": {
                            "OriginAccessIdentity": ""
                        }
                    }
                ]
            },
            "OriginGroups": {
                "Quantity": 0
            },
            "DefaultCacheBehavior": {
                "TargetOriginId": "amzn-s3-demo-bucket---s3.amazonaws.com.rproxy.goskope.com-1574382155-273939",
                "ForwardedValues": {
                    "QueryString": false,
                    "Cookies": {
                        "Forward": "none"
                    },
                    "Headers": {
                        "Quantity": 0
                    },
                    "QueryStringCacheKeys": {
                        "Quantity": 0
                    }
                },
                "TrustedSigners": {
                    "Enabled": false,
                    "Quantity": 0
                },
                "ViewerProtocolPolicy": "allow-all",
                "MinTTL": 0,
                "AllowedMethods": {
                    "Quantity": 2,
                    "Items": [
                        "HEAD",
                        "GET"
                    ],
                    "CachedMethods": {
                        "Quantity": 2,
                        "Items": [
                            "HEAD",
                            "GET"
                        ]
                    }
                },
                "SmoothStreaming": false,
                "DefaultTTL": 86400,
                "MaxTTL": 31536000,
                "Compress": false,
                "LambdaFunctionAssociations": {
                    "Quantity": 0
                },
                "FieldLevelEncryptionId": ""
            },
            "CacheBehaviors": {
                "Quantity": 0
            },
            "CustomErrorResponses": {
                "Quantity": 0
            },
            "Comment": "",
            "Logging": {
                "Enabled": false,
                "IncludeCookies": false,
                "Bucket": "",
                "Prefix": ""
            },
            "PriceClass": "PriceClass_All",
            "Enabled": false,
            "ViewerCertificate": {
                "CloudFrontDefaultCertificate": true,
                "MinimumProtocolVersion": "TLSv1",
                "CertificateSource": "cloudfront"
            },
            "Restrictions": {
                "GeoRestriction": {
                    "RestrictionType": "none",
                    "Quantity": 0
                }
            },
            "WebACLId": "",
            "HttpVersion": "http2",
            "IsIPV6Enabled": true
        }
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateDistribution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/update-distribution.html)」を参照してください。**

### `update-domain-association`
<a name="cloudfront_UpdateDomainAssociation_cli_2_topic"></a>

次のコード例は、`update-domain-association` を使用する方法を示しています。

**AWS CLI**  
**ドメインの関連付けを更新するには**  
次の `update-domain-association` の例では、ETag `E23ZP02F085ABC` を使用してディストリビューションテナントのドメインの関連付けを更新します。  

```
aws cloudfront update-domain-association \
    --domain example.com \
    --target-resource DistributionTenantId=dt_2x9GhoK0TZRsohWzv1b9It8J1AB \
    --if-match E23ZP02F085ABC
```
出力:  

```
{
    "ETag": "ETVPDKIKX0ABC",
    "Domain": "example.com",
    "ResourceId": "dt_2x9GhoK0TZRsohWzv1b9It8J1AB"
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[代替ドメイン名を別のディストリビューションに移動する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/alternate-domain-names-move.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDomainAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/update-domain-association.html)」を参照してください。

### `update-field-level-encryption-config`
<a name="cloudfront_UpdateFieldLevelEncryptionConfig_cli_2_topic"></a>

次のコード例は、`update-field-level-encryption-config` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化の設定を更新するには**  
次の例では、JSON ファイルにパラメータを指定することで、`C3KM2WVD605UAY` という ID を持つフィールドレベル暗号化の設定の `Comment` フィールドを更新しています。  
フィールドレベル暗号化の設定を更新するには、設定の ID と `ETag` が必要です。ID は create-field-level-encryption-config コマンドと list-field-level-encryption-configs コマンドの出力で返されます。`ETag` を取得するには、get-field-level-encryption コマンドまたは get-field-level-encryption-config コマンドを使用します。`--if-match` オプションを使用して、設定の `ETag` を指定します。  

```
aws cloudfront update-field-level-encryption-config \
    --id C3KM2WVD605UAY \
    --if-match E2P4Z4VU7TY5SG \
    --field-level-encryption-config file://fle-config.json
```
`fle-config.json` ファイルは、以下を含む現在のディレクトリ内にある JSON ドキュメントです。  

```
{
    "CallerReference": "cli-example",
    "Comment": "Updated example FLE configuration",
    "QueryArgProfileConfig": {
        "ForwardWhenQueryArgProfileIsUnknown": true,
        "QueryArgProfiles": {
            "Quantity": 0
        }
    },
    "ContentTypeProfileConfig": {
        "ForwardWhenContentTypeIsUnknown": true,
        "ContentTypeProfiles": {
            "Quantity": 1,
            "Items": [
                {
                    "Format": "URLEncoded",
                    "ProfileId": "P280MFCLSYOCVU",
                    "ContentType": "application/x-www-form-urlencoded"
                }
            ]
        }
    }
}
```
出力:  

```
{
    "ETag": "E26M4BIAV81ZF6",
    "FieldLevelEncryption": {
        "Id": "C3KM2WVD605UAY",
        "LastModifiedTime": "2019-12-10T22:26:26.170Z",
        "FieldLevelEncryptionConfig": {
            "CallerReference": "cli-example",
            "Comment": "Updated example FLE configuration",
            "QueryArgProfileConfig": {
                "ForwardWhenQueryArgProfileIsUnknown": true,
                "QueryArgProfiles": {
                    "Quantity": 0,
                    "Items": []
                }
            },
            "ContentTypeProfileConfig": {
                "ForwardWhenContentTypeIsUnknown": true,
                "ContentTypeProfiles": {
                    "Quantity": 1,
                    "Items": [
                        {
                            "Format": "URLEncoded",
                            "ProfileId": "P280MFCLSYOCVU",
                            "ContentType": "application/x-www-form-urlencoded"
                        }
                    ]
                }
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFieldLevelEncryptionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/update-field-level-encryption-config.html)」を参照してください。

### `update-field-level-encryption-profile`
<a name="cloudfront_UpdateFieldLevelEncryptionProfile_cli_2_topic"></a>

次のコード例は、`update-field-level-encryption-profile` を使用する方法を示しています。

**AWS CLI**  
**CloudFront のフィールドレベル暗号化のプロファイルを更新するには**  
次の例では、`PPK0UOSIF5WSV` という ID を持つフィールドレベル暗号化のプロファイルを更新しています。この例では、JSON ファイルにパラメータを指定して、プロファイルの `Name` と `Comment` を更新し、2 番目の `FieldPatterns` 項目を追加します。  
フィールドレベル暗号化のプロファイルを更新するには、プロファイルの ID と `ETag` が必要です。ID は create-field-level-encryption-profile コマンドと list-field-level-encryption-profiles コマンドの出力で返されます。`ETag` を取得するには、get-field-level-encryption-profile コマンドまたは get-field-level-encryption-profile-config コマンドを使用します。`--if-match` オプションを使用して、プロファイルの `ETag` を指定します。  

```
aws cloudfront update-field-level-encryption-profile \
    --id PPK0UOSIF5WSV \
    --if-match E1QQG65FS2L2GC \
    --field-level-encryption-profile-config file://fle-profile-config.json
```
`fle-profile-config.json` ファイルは、以下を含む現在のディレクトリ内にある JSON ドキュメントです。  

```
{
    "Name": "ExampleFLEProfileUpdated",
    "CallerReference": "cli-example",
    "Comment": "Updated FLE profile for AWS CLI example",
    "EncryptionEntities": {
        "Quantity": 1,
        "Items": [
            {
                "PublicKeyId": "K2K8NC4HVFE3M0",
                "ProviderId": "ExampleFLEProvider",
                "FieldPatterns": {
                    "Quantity": 2,
                    "Items": [
                        "ExampleSensitiveField",
                        "SecondExampleSensitiveField"
                    ]
                }
            }
        ]
    }
}
```
出力:  

```
{
    "ETag": "EJETYFJ9CL66D",
    "FieldLevelEncryptionProfile": {
        "Id": "PPK0UOSIF5WSV",
        "LastModifiedTime": "2019-12-10T19:05:58.296Z",
        "FieldLevelEncryptionProfileConfig": {
            "Name": "ExampleFLEProfileUpdated",
            "CallerReference": "cli-example",
            "Comment": "Updated FLE profile for AWS CLI example",
            "EncryptionEntities": {
                "Quantity": 1,
                "Items": [
                    {
                        "PublicKeyId": "K2K8NC4HVFE3M0",
                        "ProviderId": "ExampleFLEProvider",
                        "FieldPatterns": {
                            "Quantity": 2,
                            "Items": [
                                "ExampleSensitiveField",
                                "SecondExampleSensitiveField"
                            ]
                        }
                    }
                ]
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFieldLevelEncryptionProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/update-field-level-encryption-profile.html)」を参照してください。

### `verify-dns-configuration`
<a name="cloudfront_VerifyDnsConfiguration_cli_2_topic"></a>

次のコード例は、`verify-dns-configuration` を使用する方法を示しています。

**AWS CLI**  
**ドメインの DNS 設定を確認するには**  
次の `verify-dns-configuration` の例では、ドメインの DNS 設定を確認します。  

```
aws cloudfront verify-dns-configuration \
    --domain example.com \
    --identifier dt_2x9GhoK0TZRsohWzv1b9It8J1AB
```
出力:  

```
{
    "DnsConfigurationList": [
        {
            "Domain": "example.com",
            "Status": "valid-configuration"
        }
    ]
}
```
詳細については、「*Amazon CloudFront デベロッパーガイド*」の「[代替ドメイン名を別のディストリビューションに移動する](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/alternate-domain-names-move.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyDnsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudfront/verify-dns-configuration.html)」を参照してください。

# を使用した Amazon CloudSearch の例 AWS CLI
<a name="cli_2_cloudsearch-domain_code_examples"></a>

次のコード例は、Amazon CloudSearch AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `upload-documents`
<a name="cloudsearch-domain_UploadDocuments_cli_2_topic"></a>

次のコード例は、`upload-documents` を使用する方法を示しています。

**AWS CLI**  
次の `upload-documents` コマンドは、JSON ドキュメントのバッチを Amazon CloudSearch ドメインにアップロードします。  

```
aws cloudsearchdomain upload-documents --endpoint-url https://doc-my-domain.us-west-1.cloudsearch.amazonaws.com --content-type application/json --documents document-batch.json
```
出力:  

```
{
  "status": "success",
  "adds": 5000,
  "deletes": 0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadDocuments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudsearchdomain/upload-documents.html)」を参照してください。

# を使用した CloudTrail の例 AWS CLI
<a name="cli_2_cloudtrail_code_examples"></a>

次のコード例は、CloudTrail AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags`
<a name="cloudtrail_AddTags_cli_2_topic"></a>

次のコード例は、`add-tags` を使用する方法を示しています。

**AWS CLI**  
**証跡にタグを追加するには**  
次の `add-tags` コマンドは `Trail1` のタグを追加します。  

```
aws cloudtrail add-tags --resource-id arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 --tags-list Key=name,Value=Alice Key=location,Value=us
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/add-tags.html)」を参照してください。

### `create-subscription`
<a name="cloudtrail_CreateSubscription_cli_2_topic"></a>

次の例は、`create-subscription` を使用する方法を説明しています。

**AWS CLI**  
**証跡の AWS リソースを作成して設定するには**  
次の `create-subscription` コマンドは、`Trail1` の新しい S3 バケットと SNS トピックを作成します。  

```
aws cloudtrail create-subscription \
    --name Trail1 \
    --s3-new-bucket amzn-s3-demo-bucket \
    --sns-new-topic my-topic
```
出力:  

```
Setting up new S3 bucket amzn-s3-demo-bucket...
Setting up new SNS topic my-topic...
Creating/updating CloudTrail configuration...
CloudTrail configuration:
    {
        "trailList": [
            {
                "IncludeGlobalServiceEvents": true,
                "Name": "Trail1",
                "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1",
                "LogFileValidationEnabled": false,
                "IsMultiRegionTrail": false,
                "S3BucketName": "amzn-s3-demo-bucket",
                "SnsTopicName": "my-topic",
                "HomeRegion": "us-east-1"
            }
        ],
        "ResponseMetadata": {
        "HTTPStatusCode": 200,
        "RequestId": "f39e51f6-c615-11e5-85bd-d35ca21ee3e2"
        }
    }
Starting CloudTrail service...
Logs will be delivered to my-bucket
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/create-subscription.html)」を参照してください。

### `create-trail`
<a name="cloudtrail_CreateTrail_cli_2_topic"></a>

次のコード例は、`create-trail` を使用する方法を示しています。

**AWS CLI**  
**証跡を作成するには**  
次の `create-trail` の例では、`Trail1` という名前のマルチリージョン証跡を作成し、S3 バケットを指定します。  

```
aws cloudtrail create-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket \
    --is-multi-region-trail
```
出力:  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/create-trail.html)」を参照してください。

### `delete-trail`
<a name="cloudtrail_DeleteTrail_cli_2_topic"></a>

次のコード例は、`delete-trail` を使用する方法を示しています。

**AWS CLI**  
**証跡を削除するには**  
次の `delete-trail` コマンドは `Trail1` という名前の証跡を削除します。  

```
aws cloudtrail delete-trail --name Trail1
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/delete-trail.html)」を参照してください。

### `describe-trails`
<a name="cloudtrail_DescribeTrails_cli_2_topic"></a>

次のコード例は、`describe-trails` を使用する方法を示しています。

**AWS CLI**  
**証跡を記述するには**  
次の `describe-trails` の例では、`Trail1` と `Trail2` の設定を返します。  

```
aws cloudtrail describe-trails \
    --trail-name-list Trail1 Trail2
```
出力:  

```
{
    "trailList": [
        {
            "IncludeGlobalServiceEvents": true,
            "Name": "Trail1",
            "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1",
            "LogFileValidationEnabled": false,
            "IsMultiRegionTrail": false,
            "S3BucketName": "amzn-s3-demo-bucket",
            "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/CloudTrail_CloudWatchLogs_Role",
            "CloudWatchLogsLogGroupArn": "arn:aws:logs:us-east-1:123456789012:log-group:CloudTrail:*",
            "SnsTopicName": "my-topic",
            "HomeRegion": "us-east-1"
        },
        {
            "IncludeGlobalServiceEvents": true,
            "Name": "Trail2",
            "S3KeyPrefix": "my-prefix",
            "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail2",
            "LogFileValidationEnabled": false,
            "IsMultiRegionTrail": false,
            "S3BucketName": "amzn-s3-demo-bucket2",
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/4c5ae5ac-3c13-421e-8335-c7868ef6a769",
            "HomeRegion": "us-east-1"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/describe-trails.html)」を参照してください。

### `get-event-selectors`
<a name="cloudtrail_GetEventSelectors_cli_2_topic"></a>

次のコード例は、`get-event-selectors` を使用する方法を示しています。

**AWS CLI**  
**証跡のイベントセレクターの設定を表示するには**  
次の `get-event-selectors` コマンドは `Trail1` の設定を返します。  

```
aws cloudtrail get-event-selectors --trail-name Trail1
```
出力:  

```
{
  "EventSelectors": [
      {
          "IncludeManagementEvents": true,
          "DataResources": [],
          "ReadWriteType": "All"
      }
  ],
  "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEventSelectors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/get-event-selectors.html)」を参照してください。

### `get-trail-status`
<a name="cloudtrail_GetTrailStatus_cli_2_topic"></a>

次のコード例は、`get-trail-status` を使用する方法を示しています。

**AWS CLI**  
**証跡のステータスを取得するには**  
次の `get-trail-status` コマンドは `Trail1` の配信およびログの詳細を返します。  

```
aws cloudtrail get-trail-status --name Trail1
```
出力:  

```
{
  "LatestNotificationTime": 1454022144.869,
  "LatestNotificationAttemptSucceeded": "2016-01-28T23:02:24Z",
  "LatestDeliveryAttemptTime": "2016-01-28T23:02:24Z",
  "LatestDeliveryTime": 1454022144.869,
  "TimeLoggingStarted": "2015-11-06T18:36:38Z",
  "LatestDeliveryAttemptSucceeded": "2016-01-28T23:02:24Z",
  "IsLogging": true,
  "LatestCloudWatchLogsDeliveryTime": 1454022144.918,
  "StartLoggingTime": 1446834998.695,
  "StopLoggingTime": 1446834996.933,
  "LatestNotificationAttemptTime": "2016-01-28T23:02:24Z",
  "TimeLoggingStopped": "2015-11-06T18:36:36Z"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTrailStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/get-trail-status.html)」を参照してください。

### `list-public-keys`
<a name="cloudtrail_ListPublicKeys_cli_2_topic"></a>

次のコード例は、`list-public-keys` を使用する方法を示しています。

**AWS CLI**  
**証跡のすべてのパブリックキーを一覧表示するには**  
次の `list-public-keys` コマンドは、指定された時間範囲内に、対応するプライベートキーがダイジェストファイルの署名に使用されたすべてのパブリックキーを返します。  

```
aws cloudtrail list-public-keys --start-time 2016-01-01T20:30:00.000Z
```
出力:  

```
{
  "PublicKeyList": [
      {
         "ValidityStartTime": 1453076702.0,
         "ValidityEndTime": 1455668702.0,
         "Value": "MIIBCgKCAQEAlSS3cl92HDycr/MTj0moOhas8habjrraXw+KzlWF0axSI2tcF+3iJ9BKQAVSKxGwxwu3m0wG3J+kUl1xboEcEPHYoIYMbgfSw7KGnuDKwkLzsQWhUJ0cIbOHASox1vv/5fNXkrHhGbDCHeVXm804c83nvHUEFYThr1PfyP/8HwrCtR3FX5OANtQCP61C1nJtSSkC8JSQUOrIP4CuwJjc+4WGDk+BGH5m9iuiAKkipEHWmUl8/P7XpfpWQuk4h8g3pXZOrNXr08lbh4d39svj7UqdhvOXoBISp9t/EXYuePGEtBdrKD9Dz+VHwyUPtBQvYr9BnkF88qBnaPNhS44rzwIDAQAB",
         "Fingerprint": "7f3f401420072e50a65a141430817ab3"
     }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPublicKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/list-public-keys.html)」を参照してください。

### `list-tags`
<a name="cloudtrail_ListTags_cli_2_topic"></a>

次のコード例は、`list-tags` を使用する方法を示しています。

**AWS CLI**  
**証跡のタグを一覧表示するには**  
次の `list-tags` コマンドは、`Trail1` と `Trail2` のタグを一覧表示します。  

```
aws cloudtrail list-tags --resource-id-list arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail2
```
出力:  

```
{
 "ResourceTagList": [
     {
         "ResourceId": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1",
         "TagsList": [
             {
                 "Value": "Alice",
                 "Key": "name"
             },
             {
                 "Value": "us",
                 "Key": "location"
             }
         ]
     },
     {
         "ResourceId": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail2",
         "TagsList": [
             {
                 "Value": "Bob",
                 "Key": "name"
             }
         ]
     }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/list-tags.html)」を参照してください。

### `lookup-events`
<a name="cloudtrail_LookupEvents_cli_2_topic"></a>

次のコード例は、`lookup-events` を使用する方法を示しています。

**AWS CLI**  
**証跡のイベントを検索するには**  
次の `lookup-events` コマンドは、`EventName` 属性 で API アクティビティイベントを検索します。  

```
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=ConsoleLogin
```
出力:  

```
{
  "Events": [
     {
         "EventId": "654ccbc0-ba0d-486a-9076-dbf7274677a7",
         "Username": "my-session-name",
         "EventTime": "2021-11-18T09:41:02-08:00",
         "CloudTrailEvent": "{\"eventVersion\":\"1.02\",\"userIdentity\":{\"type\":\"AssumedRole\",\"principalId\":\"AROAJIKPFTA72SWU4L7T4:my-session-name\",\"arn\":\"arn:aws:sts::123456789012:assumed-role/my-role/my-session-name\",\"accountId\":\"123456789012\",\"sessionContext\":{\"attributes\":{\"mfaAuthenticated\":\"false\",\"creationDate\":\"2016-01-26T21:42:12Z\"},\"sessionIssuer\":{\"type\":\"Role\",\"principalId\":\"AROAJIKPFTA72SWU4L7T4\",\"arn\":\"arn:aws:iam::123456789012:role/my-role\",\"accountId\":\"123456789012\",\"userName\":\"my-role\"}}},\"eventTime\":\"2016-01-26T21:42:12Z\",\"eventSource\":\"signin.amazonaws.com\",\"eventName\":\"ConsoleLogin\",\"awsRegion\":\"us-east-1\",\"sourceIPAddress\":\"72.21.198.70\",\"userAgent\":\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36\",\"requestParameters\":null,\"responseElements\":{\"ConsoleLogin\":\"Success\"},\"additionalEventData\":{\"MobileVersion\":\"No\",\"MFAUsed\":\"No\"},\"eventID\":\"654ccbc0-ba0d-486a-9076-dbf7274677a7\",\"eventType\":\"AwsConsoleSignIn\",\"recipientAccountId\":\"123456789012\"}",
         "EventName": "ConsoleLogin",
         "Resources": []
     }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[LookupEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/lookup-events.html)」を参照してください。

### `put-event-selectors`
<a name="cloudtrail_PutEventSelectors_cli_2_topic"></a>

次のコード例は、`put-event-selectors` を使用する方法を示しています。

**AWS CLI**  
**例 1: 高度なイベントセレクターを使用して、管理イベントおよびデータイベントをログに記録する証跡を設定する**  
高度なイベントセレクターおよび高度なイベントセレクターの条件を追加できます。証跡のすべての条件とセレクターには、最大 500 個の値を設定できます。高度なイベントセレクターを使用すると、使用可能なすべてのデータイベントタイプをログに記録できます。高度なイベントセレクターまたは基本的なイベントセレクターのいずれかを使用できますが、両方を使用することはできません。高度なイベントセレクターを証跡に適用すると、既存の基本的なイベントセレクターは上書きされます。  
次の `put-event-selectors` の例では、`myTrail` という名前の証跡の高度なイベントセレクターを作成し、すべての管理イベント、1 つの S3 バケットを除くすべての S3 PutObject および DeleteObject API コール、`myFunction` という名前の Lambda 関数のデータ API コール、`myTopic` という名前の SNS トピックの Publish API コールをログに記録します。  

```
aws cloudtrail put-event-selectors \
    --trail-name myTrail \
    --advanced-event-selectors '[{"Name": "Log all management events", "FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Management"] }] },{"Name": "Log PutObject and DeleteObject events for all but one bucket","FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Data"] },{ "Field": "resources.type", "Equals": ["AWS::S3::Object"] },{ "Field": "eventName", "Equals": ["PutObject","DeleteObject"] },{ "Field": "resources.ARN", "NotStartsWith": ["arn:aws:s3:::amzn-s3-demo-bucket/"] }]},{"Name": "Log data events for a specific Lambda function","FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Data"] },{ "Field": "resources.type", "Equals": ["AWS::Lambda::Function"] },{ "Field": "resources.ARN", "Equals": ["arn:aws:lambda:us-east-1:123456789012:function:myFunction"] }]},{"Name": "Log all Publish API calls on a specific SNS topic","FieldSelectors": [{ "Field": "eventCategory", "Equals": ["Data"] },{ "Field": "resources.type", "Equals": ["AWS::SNS::Topic"] },{ "Field": "eventName", "Equals": ["Publish"] },{ "Field": "resources.ARN", "Equals": ["arn:aws:sns:us-east-1:123456789012:myTopic.fifo"] }]}]'
```
出力:  

```
{
    "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/myTrail",
    "AdvancedEventSelectors": [
        {
            "Name": "Log all management events",
            "FieldSelectors": [
                {
                    "Field": "eventCategory",
                    "Equals": [
                        "Management"
                    ]
                }
            ]
        },
        {
            "Name": "Log PutObject and DeleteObject events for all but one bucket",
            "FieldSelectors": [
                {
                    "Field": "eventCategory",
                    "Equals": [
                        "Data"
                    ]
                },
                {
                    "Field": "resources.type",
                    "Equals": [
                        "AWS::S3::Object"
                    ]
                },
                {
                    "Field": "eventName",
                    "Equals": [
                        "PutObject",
                        "DeleteObject"
                    ]
                },
                {
                    "Field": "resources.ARN",
                    "NotStartsWith": [
                        "arn:aws:s3:::amzn-s3-demo-bucket/"
                    ]
                }
            ]
        },
        {
            "Name": "Log data events for a specific Lambda function",
            "FieldSelectors": [
                {
                    "Field": "eventCategory",
                    "Equals": [
                        "Data"
                    ]
                },
                {
                    "Field": "resources.type",
                    "Equals": [
                        "AWS::Lambda::Function"
                    ]
                },
                {
                    "Field": "resources.ARN",
                    "Equals": [
                        "arn:aws:lambda:us-east-1:123456789012:function:myFunction"
                    ]
                }
            ]
        },
        {
            "Name": "Log all Publish API calls on a specific SNS topic",
            "FieldSelectors": [
                {
                    "Field": "eventCategory",
                    "Equals": [
                        "Data"
                    ]
                },
                {
                    "Field": "resources.type",
                    "Equals": [
                        "AWS::SNS::Topic"
                    ]
                },
                {
                    "Field": "eventName",
                    "Equals": [
                        "Publish"
                    ]
                },
                {
                    "Field": "resources.ARN",
                    "Equals": [
                        "arn:aws:sns:us-east-1:123456789012:myTopic.fifo"
                    ]
                }
            ]
        }
    ]
}
```
詳細については、「*AWS CloudTrail ユーザーガイド*」の「[アドバンストイベントセレクタを使用してイベントをログに記録する](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#creating-data-event-selectors-advanced)」を参照してください。  
**例 2: すべての管理イベントとデータイベントをログに記録する証跡のイベントセレクターを設定する**  
証跡あたり最大 5 つのイベントセレクタと、証跡あたり最大 250 の データリソースを設定できます。イベントセレクターは、基本的なイベントセレクターとも呼ばれます。イベントセレクターを使用して、S3 オブジェクト、Lambda 関数、および DynnamoDB テーブルの管理イベントとデータイベントをログに記録できます。その他のリソースタイプのデータイベントをログに記録するには、高度なイベントセレクターを使用する必要があります。  
次の`put-event-selectors`例では、 という名前の証跡のイベントセレクタを作成し、すべての管理イベント、2 つの Amazon S3 バケット/プレフィックスの組み合わせのデータイベント、および という名前の単一の AWS Lambda 関数のデータイベント`TrailName`を含めます`hello-world-python-function`。  

```
aws cloudtrail put-event-selectors \
    --trail-name TrailName \
    --event-selectors '[{"ReadWriteType": "All","IncludeManagementEvents": true,"DataResources": [{"Type":"AWS::S3::Object", "Values": ["arn:aws:s3:::amzn-s3-demo-bucket/prefix","arn:aws:s3:::amzn-s3-demo-bucket2/prefix2"]},{"Type": "AWS::Lambda::Function","Values": ["arn:aws:lambda:us-west-2:999999999999:function:hello-world-python-function"]}]}]'
```
出力:  

```
{
    "EventSelectors": [
        {
            "IncludeManagementEvents": true,
            "DataResources": [
                {
                    "Values": [
                        "arn:aws:s3:::amzn-s3-demo-bucket/prefix",
                        "arn:aws:s3:::amzn-s3-demo-bucket2/prefix2"
                    ],
                    "Type": "AWS::S3::Object"
                },
                {
                    "Values": [
                        "arn:aws:lambda:us-west-2:123456789012:function:hello-world-python-function"
                    ],
                    "Type": "AWS::Lambda::Function"
                },
            ],
            "ReadWriteType": "All"
        }
    ],
    "TrailARN": "arn:aws:cloudtrail:us-east-2:123456789012:trail/TrailName"
}
```
詳細については、「*AWS CloudTrail ユーザーガイド*」の「[基本的なイベントセレクターを使用してイベントをログに記録する](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#creating-data-event-selectors-basic)」を参照してください。  
**例 3: 管理イベント、S3 オブジェクト上のすべての S3 データイベント、およびアカウントの関数上のすべての Lambda データイベントをログに記録する証跡のイベントセレクターを設定する**  
次の`put-event-selectors`例では、アカウント内のすべての Amazon S3 バケットと AWS Lambda 関数のすべての管理イベントとすべてのデータイベント`TrailName2`を含む という名前の証跡のイベントセレクタを作成します AWS 。  

```
aws cloudtrail put-event-selectors \
    --trail-name TrailName2 \
    --event-selectors '[{"ReadWriteType": "All","IncludeManagementEvents": true,"DataResources": [{"Type":"AWS::S3::Object", "Values": ["arn:aws:s3"]},{"Type": "AWS::Lambda::Function","Values": ["arn:aws:lambda"]}]}]'
```
出力:  

```
{
    "EventSelectors": [
        {
            "IncludeManagementEvents": true,
            "DataResources": [
                {
                    "Values": [
                        "arn:aws:s3"
                    ],
                    "Type": "AWS::S3::Object"
                },
                {
                    "Values": [
                        "arn:aws:lambda"
                    ],
                    "Type": "AWS::Lambda::Function"
                },
            ],
            "ReadWriteType": "All"
        }
    ],
    "TrailARN": "arn:aws:cloudtrail:us-east-2:123456789012:trail/TrailName2"
}
```
詳細については、「*AWS CloudTrail ユーザーガイド*」の「[基本的なイベントセレクターを使用してイベントをログに記録する](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html#creating-data-event-selectors-basic)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutEventSelectors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/put-event-selectors.html)」を参照してください。

### `remove-tags`
<a name="cloudtrail_RemoveTags_cli_2_topic"></a>

次のコード例は、`remove-tags` を使用する方法を示しています。

**AWS CLI**  
**証跡のタグを削除するには**  
次の `remove-tags` コマンドは、`Trail1` の指定したタグを削除します。  

```
aws cloudtrail remove-tags --resource-id arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 --tags-list Key=name Key=location
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/remove-tags.html)」を参照してください。

### `start-logging`
<a name="cloudtrail_StartLogging_cli_2_topic"></a>

次のコード例は、`start-logging` を使用する方法を示しています。

**AWS CLI**  
**証跡のログ記録を開始するには**  
次の `start-logging` コマンドを実行して、`Trail1` のログ記録をオンにします。  

```
aws cloudtrail start-logging --name Trail1
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/start-logging.html)」を参照してください。

### `stop-logging`
<a name="cloudtrail_StopLogging_cli_2_topic"></a>

次のコード例は、`stop-logging` を使用する方法を示しています。

**AWS CLI**  
**証跡のログ記録を停止するには**  
次の `stop-logging` コマンドを実行して、`Trail1` のログ記録をオフにします。  

```
aws cloudtrail stop-logging --name Trail1
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/stop-logging.html)」を参照してください。

### `update-subscription`
<a name="cloudtrail_UpdateSubscription_cli_2_topic"></a>

次のコード例は、`update-subscription` を使用する方法を示しています。

**AWS CLI**  
**証跡の設定を更新するには**  
次の `update-subscription` の例では、証跡を更新して新しい S3 バケットと SNS トピックを指定します。  

```
aws cloudtrail update-subscription \
    --name Trail1 \
    --s3-new-bucket amzn-s3-demo-bucket \
    --sns-new-topic my-topic-new
```
出力:  

```
Setting up new S3 bucket amzn-s3-demo-bucket...
Setting up new SNS topic my-topic-new...
Creating/updating CloudTrail configuration...
CloudTrail configuration:
{
    "trailList": [
        {
            "IncludeGlobalServiceEvents": true,
            "Name": "Trail1",
            "TrailARN": "arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1",
            "LogFileValidationEnabled": false,
            "IsMultiRegionTrail": false,
            "S3BucketName": "amzn-s3-demo-bucket",
            "SnsTopicName": "my-topic-new",
            "HomeRegion": "us-east-1"
        }
    ],
    "ResponseMetadata": {
        "HTTPStatusCode": 200,
        "RequestId": "31126f8a-c616-11e5-9cc6-2fd637936879"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/update-subscription.html)」を参照してください。

### `update-trail`
<a name="cloudtrail_UpdateTrail_cli_2_topic"></a>

次のコード例は、`update-trail` を使用する方法を示しています。

**AWS CLI**  
**証跡を更新するには**  
次の `update-trail` の例では、ログ配信に既存のバケットを使用するように証跡を更新します。  

```
aws cloudtrail update-trail \
    --name Trail1 \
    --s3-bucket-name amzn-s3-demo-bucket
```
出力:  

```
{
    "IncludeGlobalServiceEvents": true,
    "Name": "Trail1",
    "TrailARN": "arn:aws:cloudtrail:us-west-2:123456789012:trail/Trail1",
    "LogFileValidationEnabled": false,
    "IsMultiRegionTrail": true,
    "S3BucketName": "amzn-s3-demo-bucket"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTrail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/update-trail.html)」を参照してください。

### `validate-logs`
<a name="cloudtrail_ValidateLogs_cli_2_topic"></a>

次のコード例は、`validate-logs` を使用する方法を示しています。

**AWS CLI**  
**ログファイルを検証するには**  
次の `validate-logs` コマンドは、`Trail1` のログを検証します。  

```
aws cloudtrail validate-logs --trail-arn arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 --start-time 20160129T19:00:00Z
```
出力:  

```
Validating log files for trail arn:aws:cloudtrail:us-east-1:123456789012:trail/Trail1 between 2016-01-29T19:00:00Z and 2016-01-29T22:15:43Z
Results requested for 2016-01-29T19:00:00Z to 2016-01-29T22:15:43Z
Results found for 2016-01-29T19:24:57Z to 2016-01-29T21:24:57Z:
3/3 digest files valid
15/15 log files valid
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ValidateLogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/validate-logs.html)」を参照してください。

# を使用した CloudWatch の例 AWS CLI
<a name="cli_2_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-alarms`
<a name="cloudwatch_DeleteAlarms_cli_2_topic"></a>

次のコード例は、`delete-alarms` を使用する方法を示しています。

**AWS CLI**  
**アラームを削除するには**  
次の例は、`delete-alarms` コマンドを使用して、「myalarm」という名前の Amazon CloudWatch アラームを削除します。  

```
aws cloudwatch delete-alarms --alarm-names myalarm
```
出力:  

```
This command returns to the prompt if successful.
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteAlarms](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-alarms.html)」を参照してください。**

### `delete-anomaly-detector`
<a name="cloudwatch_DeleteAnomalyDetector_cli_2_topic"></a>

次のコード例は、`delete-anomaly-detector` を使用する方法を示しています。

**AWS CLI**  
**指定された異常検出モデルを削除する方法**  
次の`delete-anomaly-detector` の例では、指定されたアカウントで異常検出モデルを削除します。  

```
aws cloudwatch delete-anomaly-detector \
    --namespace AWS/Logs \
    --metric-name IncomingBytes \
    --stat SampleCount
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[異常検出モデルの削除](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_Anomaly_Detection_Alarm.html#Delete_Anomaly_Detection_Model)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAnomalyDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-anomaly-detector.html)」を参照してください。

### `delete-dashboards`
<a name="cloudwatch_DeleteDashboards_cli_2_topic"></a>

次のコード例は、`delete-dashboards` を使用する方法を示しています。

**AWS CLI**  
**指定されたダッシュボードを削除する方法**  
次の `delete-dashboards` の例では、指定されたアカウントの `Dashboard-A` および `Dashboard-B` という名前の 2 つのダッシュボードを削除します。  

```
aws cloudwatch delete-dashboards \
    --dashboard-names Dashboard-A Dashboard-B
```
このコマンドでは何も出力されません。  
詳細については、「Amazon CloudWatch ユーザーガイド」の「[Amazon CloudWatch のダッシュボード](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDashboards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-dashboards.html)」を参照してください。

### `delete-insight-rules`
<a name="cloudwatch_DeleteInsightRules_cli_2_topic"></a>

次のコード例は、`delete-insight-rules` を使用する方法を示しています。

**AWS CLI**  
**指定した Contributor Insights のルールを削除するには**  
次の `delete-insight-rules` の例では、指定したアカウントから `Rule-A` および `Rule-B` という名前の 2 つの Contributor Insights ルールを削除します。  

```
aws cloudwatch delete-insight-rules \
    --rule-names Rule-A Rule-B
```
出力:  

```
{
    "Failures": []
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Contributor Insights を使用して高カーディナリティデータを分析する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-insight-rules.html)」を参照してください。

### `delete-metric-stream`
<a name="cloudwatch_DeleteMetricStream_cli_2_topic"></a>

次のコード例は、`delete-metric-stream` を使用する方法を示しています。

**AWS CLI**  
**指定したメトリクスストリームを削除するには**  
次の `delete-metric-stream` の例では、指定したアカウントから `QuickPartial-gSCKvO` という名前のメトリクスストリームを削除します。  

```
aws cloudwatch delete-metric-stream \
    --name QuickPartial-gSCKvO
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[メトリクスストリームを使用する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteMetricStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-metric-stream.html)」を参照してください。

### `describe-alarm-history`
<a name="cloudwatch_DescribeAlarmHistory_cli_2_topic"></a>

次のコード例は、`describe-alarm-history` を使用する方法を示しています。

**AWS CLI**  
**アラームの履歴を取得するには**  
次の例は、`describe-alarm-history` コマンドを使用して、「myalarm」という名前の Amazon CloudWatch アラームの履歴を取得します。  

```
aws cloudwatch describe-alarm-history --alarm-name "myalarm" --history-item-type StateUpdate
```
出力:  

```
{
    "AlarmHistoryItems": [
        {
            "Timestamp": "2014-04-09T18:59:06.442Z",
            "HistoryItemType": "StateUpdate",
            "AlarmName": "myalarm",
            "HistoryData": "{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"testing purposes\"},\"newState\":{\"stateValue\":\"OK\",\"stateReason\":\"Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].\",\"stateReasonData\":{\"version\":\"1.0\",\"queryDate\":\"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292],\"threshold\":70.0}}}",
            "HistorySummary": "Alarm updated from ALARM to OK"
        },
        {
            "Timestamp": "2014-04-09T18:59:05.805Z",
            "HistoryItemType": "StateUpdate",
            "AlarmName": "myalarm",
            "HistoryData": "{\"version\":\"1.0\",\"oldState\":{\"stateValue\":\"OK\",\"stateReason\":\"Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.839999999999996, 39.714].\",\"stateReasonData\":{\"version\":\"1.0\",\"queryDate\":\"2014-03-11T22:45:41.569+0000\",\"startDate\":\"2014-03-11T22:30:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.839999999999996,39.714],\"threshold\":70.0}},\"newState\":{\"stateValue\":\"ALARM\",\"stateReason\":\"testing purposes\"}}",
            "HistorySummary": "Alarm updated from OK to ALARM"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeAlarmHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-alarm-history.html)」を参照してください。**

### `describe-alarms-for-metric`
<a name="cloudwatch_DescribeAlarmsForMetric_cli_2_topic"></a>

次のコード例は、`describe-alarms-for-metric` を使用する方法を示しています。

**AWS CLI**  
**メトリクスに関連するアラームについての情報を表示するには**  
次の例は、`describe-alarms-for-metric` コマンドを使用して、Amazon EC2 CPUUtilization メトリクスと、ID i-0c986c72 のインスタンスに関連するすべてのアラームに関する情報を表示します。  

```
aws cloudwatch describe-alarms-for-metric --metric-name CPUUtilization --namespace AWS/EC2 --dimensions Name=InstanceId,Value=i-0c986c72
```
出力:  

```
{
    "MetricAlarms": [
        {
            "EvaluationPeriods": 10,
            "AlarmArn": "arn:aws:cloudwatch:us-east-1:111122223333:alarm:myHighCpuAlarm2",
            "StateUpdatedTimestamp": "2013-10-30T03:03:51.479Z",
            "AlarmConfigurationUpdatedTimestamp": "2013-10-30T03:03:50.865Z",
            "ComparisonOperator": "GreaterThanOrEqualToThreshold",
            "AlarmActions": [
                "arn:aws:sns:us-east-1:111122223333:NotifyMe"
            ],
            "Namespace": "AWS/EC2",
            "AlarmDescription": "CPU usage exceeds 70 percent",
            "StateReasonData": "{\"version\":\"1.0\",\"queryDate\":\"2013-10-30T03:03:51.479+0000\",\"startDate\":\"2013-10-30T02:08:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[40.698,39.612,42.432,39.796,38.816,42.28,42.854,40.088,40.760000000000005,41.316],\"threshold\":70.0}",
            "Period": 300,
            "StateValue": "OK",
            "Threshold": 70.0,
            "AlarmName": "myHighCpuAlarm2",
            "Dimensions": [
                {
                    "Name": "InstanceId",
                    "Value": "i-0c986c72"
                }
            ],
            "Statistic": "Average",
            "StateReason": "Threshold Crossed: 10 datapoints were not greater than or equal to the threshold (70.0). The most recent datapoints: [40.760000000000005, 41.316].",
            "InsufficientDataActions": [],
            "OKActions": [],
            "ActionsEnabled": true,
            "MetricName": "CPUUtilization"
        },
        {
            "EvaluationPeriods": 2,
            "AlarmArn": "arn:aws:cloudwatch:us-east-1:111122223333:alarm:myHighCpuAlarm",
            "StateUpdatedTimestamp": "2014-04-09T18:59:06.442Z",
            "AlarmConfigurationUpdatedTimestamp": "2014-04-09T22:26:05.958Z",
            "ComparisonOperator": "GreaterThanThreshold",
            "AlarmActions": [
                "arn:aws:sns:us-east-1:111122223333:HighCPUAlarm"
            ],
            "Namespace": "AWS/EC2",
            "AlarmDescription": "CPU usage exceeds 70 percent",
            "StateReasonData": "{\"version\":\"1.0\",\"queryDate\":\"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292],\"threshold\":70.0}",
            "Period": 300,
            "StateValue": "OK",
            "Threshold": 70.0,
            "AlarmName": "myHighCpuAlarm",
            "Dimensions": [
                {
                    "Name": "InstanceId",
                    "Value": "i-0c986c72"
                }
            ],
            "Statistic": "Average",
            "StateReason": "Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].",
            "InsufficientDataActions": [],
            "OKActions": [],
            "ActionsEnabled": false,
            "MetricName": "CPUUtilization"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeAlarmsForMetric](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-alarms-for-metric.html)」を参照してください。**

### `describe-alarms`
<a name="cloudwatch_DescribeAlarms_cli_2_topic"></a>

次のコード例は、`describe-alarms` を使用する方法を示しています。

**AWS CLI**  
**アラームに関する情報を一覧表示するには**  
次の例は、`describe-alarms` コマンドを使用して、「myalarm」という名前のアラームに関する情報を表示します。  

```
aws cloudwatch describe-alarms --alarm-names "myalarm"
```
出力:  

```
{
    "MetricAlarms": [
        {
            "EvaluationPeriods": 2,
            "AlarmArn": "arn:aws:cloudwatch:us-east-1:123456789012:alarm:myalarm",
            "StateUpdatedTimestamp": "2014-04-09T18:59:06.442Z",
            "AlarmConfigurationUpdatedTimestamp": "2012-12-27T00:49:54.032Z",
            "ComparisonOperator": "GreaterThanThreshold",
            "AlarmActions": [
                "arn:aws:sns:us-east-1:123456789012:myHighCpuAlarm"
            ],
            "Namespace": "AWS/EC2",
            "AlarmDescription": "CPU usage exceeds 70 percent",
            "StateReasonData": "{\"version\":\"1.0\",\"queryDate\":\"2014-04-09T18:59:06.419+0000\",\"startDate\":\"2014-04-09T18:44:00.000+0000\",\"statistic\":\"Average\",\"period\":300,\"recentDatapoints\":[38.958,40.292],\"threshold\":70.0}",
            "Period": 300,
            "StateValue": "OK",
            "Threshold": 70.0,
            "AlarmName": "myalarm",
            "Dimensions": [
                {
                    "Name": "InstanceId",
                    "Value": "i-0c986c72"
                }
            ],
            "Statistic": "Average",
            "StateReason": "Threshold Crossed: 2 datapoints were not greater than the threshold (70.0). The most recent datapoints: [38.958, 40.292].",
            "InsufficientDataActions": [],
            "OKActions": [],
            "ActionsEnabled": true,
            "MetricName": "CPUUtilization"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeAlarms](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-alarms.html)」を参照してください。**

### `describe-anomaly-detectors`
<a name="cloudwatch_DescribeAnomalyDetectors_cli_2_topic"></a>

次のコード例は、`describe-anomaly-detectors` を使用する方法を示しています。

**AWS CLI**  
**異常検出モデルのリストを取得する方法**  
次の `describe-anomaly-detectors` の例では、指定されたアカウントの `AWS/Logs` 名前空間に関連付けられた異常検出モデルに関する情報が表示されます。  

```
aws cloudwatch describe-anomaly-detectors \
    --namespace AWS/Logs
```
出力:  

```
{
    "AnomalyDetectors": [
        {
            "Namespace": "AWS/Logs",
            "MetricName": "IncomingBytes",
            "Dimensions": [],
            "Stat": "SampleCount",
            "Configuration": {
                "ExcludedTimeRanges": []
            },
            "StateValue": "TRAINED",
            "SingleMetricAnomalyDetector": {
                "AccountId": "123456789012",
                "Namespace": "AWS/Logs",
                "MetricName": "IncomingBytes",
                "Dimensions": [],
                "Stat": "SampleCount"
            }
        },
        {
            "Namespace": "AWS/Logs",
            "MetricName": "IncomingBytes",
            "Dimensions": [
                {
                    "Name": "LogGroupName",
                    "Value": "demo"
                }
            ],
            "Stat": "Average",
            "Configuration": {
                "ExcludedTimeRanges": []
            },
            "StateValue": "PENDING_TRAINING",
            "SingleMetricAnomalyDetector": {
                "AccountId": "123456789012",
                "Namespace": "AWS/Logs",
                "MetricName": "IncomingBytes",
                "Dimensions": [
                    {
                        "Name": "LogGroupName",
                        "Value": "demo"
                    }
                ],
                "Stat": "Average"
            }
        }
    ]
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[CloudWatch 異常検出の使用](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Anomaly_Detection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAnomalyDetectors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-anomaly-detectors.html)」を参照してください。

### `describe-insight-rules`
<a name="cloudwatch_DescribeInsightRules_cli_2_topic"></a>

次のコード例は、`describe-insight-rules` を使用する方法を示しています。

**AWS CLI**  
**Contributor Insights ルールのリストを取得するには**  
次の `describe-insight-rules` の例では、指定したアカウントのすべての Contributor Insights ルールを表示します。  

```
aws cloudwatch describe-insight-rules
```
出力:  

```
{
    "InsightRules": [
        {
            "Name": "Rule-A",
            "State": "ENABLED",
            "Schema": "CloudWatchLogRule/1",
            "Definition": "{\n\t\"AggregateOn\": \"Count\",\n\t\"Contribution\": {\n\t\t\"Filters\": [],\n\t\t\"Keys\": [\n\t\t\t\"$.requestId\"\n\t\t]\n\t},\n\t\"LogFormat\": \"JSON\",\n\t\"Schema\": {\n\t\t\"Name\": \"CloudWatchLogRule\",\n\t\t\"Version\": 1\n\t},\n\t\"LogGroupARNs\": [\n\t\t\"arn:aws:logs:us-east-1:123456789012:log-group:demo\"\n\t]\n}",
            "ManagedRule": false
        },
        {
            "Name": "Rule-B",
            "State": "ENABLED",
            "Schema": "CloudWatchLogRule/1",
            "Definition": "{\n\t\"AggregateOn\": \"Count\",\n\t\"Contribution\": {\n\t\t\"Filters\": [],\n\t\t\"Keys\": [\n\t\t\t\"$.requestId\"\n\t\t]\n\t},\n\t\"LogFormat\": \"JSON\",\n\t\"Schema\": {\n\t\t\"Name\": \"CloudWatchLogRule\",\n\t\t\"Version\": 1\n\t},\n\t\"LogGroupARNs\": [\n\t\t\"arn:aws:logs:us-east-1:123456789012:log-group:demo-1\"\n\t]\n}",
            "ManagedRule": false
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Contributor Insights を使用して高カーディナリティデータを分析する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/describe-insight-rules.html)」を参照してください。

### `disable-alarm-actions`
<a name="cloudwatch_DisableAlarmActions_cli_2_topic"></a>

次のコード例は、`disable-alarm-actions` を使用する方法を示しています。

**AWS CLI**  
**アラームのアクションを無効化するには**  
次の例は、`disable-alarm-actions` コマンドを使用して、「myalarm」という名前のアラームのアクションをすべて無効化します。  

```
aws cloudwatch disable-alarm-actions --alarm-names myalarm
```
正常に完了すると、このコマンドはプロンプトに戻ります。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DisableAlarmActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/disable-alarm-actions.html)」を参照してください。**

### `disable-insight-rules`
<a name="cloudwatch_DisableInsightRules_cli_2_topic"></a>

次のコード例は、`disable-insight-rules` を使用する方法を示しています。

**AWS CLI**  
**指定した Contributor Insights ルールを無効にするには**  
次の `disable-insight-rules` の例では、指定したアカウントの `Rule-A` および `Rule-B` という名前の 2 つの Contributor Insights ルールを無効にします。  

```
aws cloudwatch disable-insight-rules \
    --rule-names Rule-A Rule-B
```
出力:  

```
{
    "Failures": []
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Contributor Insights を使用して高カーディナリティデータを分析する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DisableInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/disable-insight-rules.html)」を参照してください。

### `enable-alarm-actions`
<a name="cloudwatch_EnableAlarmActions_cli_2_topic"></a>

次のコード例は、`enable-alarm-actions` を使用する方法を示しています。

**AWS CLI**  
**アラームのすべてのアクションを有効化するには**  
次の例は、`enable-alarm-actions` コマンドを使用して、「myalarm」という名前のアラームのアクションをすべて有効化します。  

```
aws cloudwatch enable-alarm-actions --alarm-names myalarm
```
正常に完了すると、このコマンドはプロンプトに戻ります。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[EnableAlarmActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/enable-alarm-actions.html)」を参照してください。**

### `enable-insight-rules`
<a name="cloudwatch_EnableInsightRules_cli_2_topic"></a>

次のコード例は、`enable-insight-rules` を使用する方法を示しています。

**AWS CLI**  
**指定した Contributor Insights ルールを有効にするには**  
次の `enable-insight-rules` の例では、指定したアカウントの `Rule-A` および `Rule-B` という名前の 2 つの Contributor Insights ルールを有効にします。  

```
aws cloudwatch enable-insight-rules \
    --rule-names Rule-A Rule-B
```
出力:  

```
{
    "Failures": []
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Contributor Insights を使用して高カーディナリティデータを分析する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[EnableInsightRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/enable-insight-rules.html)」を参照してください。

### `get-dashboard`
<a name="cloudwatch_GetDashboard_cli_2_topic"></a>

次のコード例は、`get-dashboard` を使用する方法を示しています。

**AWS CLI**  
**ダッシュボードに関する情報を取得する方法**  
次の `get-dashboard` の例では、指定されたアカウントで `Dashboard-A` という名前のダッシュボードに関する情報が表示されます。  

```
aws cloudwatch get-dashboard \
    --dashboard-name Dashboard-A
```
出力:  

```
{
    "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-A",
    "DashboardBody": "{\"widgets\":[{\"type\":\"metric\",\"x\":0,\"y\":0,\"width\":6,\"height\":6,\"properties\":{\"view\":\"timeSeries\",\"stacked\":false,\"metrics\":[[\"AWS/EC2\",\"NetworkIn\",\"InstanceId\",\"i-0131f062232ade043\"],[\".\",\"NetworkOut\",\".\",\".\"]],\"region\":\"us-east-1\"}}]}",
    "DashboardName": "Dashboard-A"
}
```
詳細については、「Amazon CloudWatch ユーザーガイド」の「[Amazon CloudWatch のダッシュボード](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-dashboard.html)」を参照してください。

### `get-insight-rule-report`
<a name="cloudwatch_GetInsightRuleReport_cli_2_topic"></a>

次のコード例は、`get-insight-rule-report` を使用する方法を示しています。

**AWS CLI**  
**Contributor Insights ルールによって収集された時系列データを取得するには**  
次の `get-insight-rule-report` の例では、Contributor Insights ルールによって収集された時系列データを返します。  

```
aws cloudwatch get-insight-rule-report \
    --rule-name Rule-A \
    --start-time 2024-10-13T20:15:00Z \
    --end-time 2024-10-13T20:30:00Z \
    --period 300
```
出力:  

```
{
    "KeyLabels": [
        "PartitionKey"
    ],
    "AggregationStatistic": "Sum",
    "AggregateValue": 0.5,
    "ApproximateUniqueCount": 1,
    "Contributors": [
        {
            "Keys": [
                "RequestID"
            ],
            "ApproximateAggregateValue": 0.5,
            "Datapoints": [
                {
                    "Timestamp": "2024-10-13T21:00:00+00:00",
                    "ApproximateValue": 0.5
                }
            ]
        }
    ],
    "RuleAttributes": []
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Contributor Insights を使用して高カーディナリティデータを分析する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetInsightRuleReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-insight-rule-report.html)」を参照してください。

### `get-metric-data`
<a name="cloudwatch_GetMetricData_cli_2_topic"></a>

次のコード例は、`get-metric-data` を使用する方法を示しています。

**AWS CLI**  
**例 1: 数式を使用して指定された EC2 の平均合計 IOPS を取得する方法**  
次の `get-metric-data` の例では、`EBSReadOps` と `EBSWriteOps` メトリクスを組み合わせた Metric Math 式を使用して、InstanceID `i-abcdef` を持つ EC2 インスタンスの CloudWatch メトリクス値を取得します。  

```
aws cloudwatch get-metric-data \
    --metric-data-queries file://file.json \
    --start-time 2024-09-29T22:10:00Z \
    --end-time 2024-09-29T22:15:00Z
```
`file.json` の内容:  

```
[
    {
        "Id": "m3",
        "Expression": "(m1+m2)/300",
        "Label": "Avg Total IOPS"
    },
    {
        "Id": "m1",
        "MetricStat": {
            "Metric": {
                "Namespace": "AWS/EC2",
                "MetricName": "EBSReadOps",
                "Dimensions": [
                    {
                        "Name": "InstanceId",
                        "Value": "i-abcdef"
                    }
                ]
            },
            "Period": 300,
            "Stat": "Sum",
            "Unit": "Count"
        },
        "ReturnData": false
    },
    {
        "Id": "m2",
        "MetricStat": {
            "Metric": {
                "Namespace": "AWS/EC2",
                "MetricName": "EBSWriteOps",
                "Dimensions": [
                    {
                        "Name": "InstanceId",
                        "Value": "i-abcdef"
                    }
                ]
            },
            "Period": 300,
            "Stat": "Sum",
            "Unit": "Count"
        },
        "ReturnData": false
    }
]
```
出力:  

```
{
    "MetricDataResults": [
        {
            "Id": "m3",
            "Label": "Avg Total IOPS",
            "Timestamps": [
                "2024-09-29T22:10:00+00:00"
            ],
            "Values": [
                96.85
            ],
            "StatusCode": "Complete"
        }
    ],
    "Messages": []
}
```
**例 2: CloudWatch 請求メトリクスを使用して推定 AWS 請求額をモニタリングするには**  
次の の`get-metric-data`例では、 AWS/Billing 名前空間から `EstimatedCharges` CloudWatch メトリクスを取得します。  

```
aws cloudwatch get-metric-data \
    --metric-data-queries '[{"Id":"m1","MetricStat":{"Metric":{"Namespace":"AWS/Billing","MetricName":"EstimatedCharges","Dimensions":[{"Name":"Currency","Value":"USD"}]},"Period":21600,"Stat":"Maximum"}}]' \
    --start-time 2024-09-26T12:00:00Z \
    --end-time 2024-09-26T18:00:00Z \
    --region us-east-1
```
出力:  

```
{
    "MetricDataResults": [
        {
            "Id": "m1",
            "Label": "EstimatedCharges",
            "Timestamps": [
                "2024-09-26T12:00:00+00:00"
            ],
            "Values": [
                542.38
            ],
            "StatusCode": "Complete"
        }
    ],
    "Messages": []
}
```
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[CloudWatch メトリクスで数式の使用](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-metric-math.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMetricData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-data.html)」を参照してください。

### `get-metric-statistics`
<a name="cloudwatch_GetMetricStatistics_cli_2_topic"></a>

次のコード例は、`get-metric-statistics` を使用する方法を示しています。

**AWS CLI**  
**EC2 インスタンスあたりの CPU 使用率を取得するには**  
次の例は、`get-metric-statistics` コマンドを使用して、ID i-abcdef の EC2 インスタンスの CPU 使用率を取得します。  

```
aws cloudwatch get-metric-statistics --metric-name CPUUtilization --start-time 2014-04-08T23:18:00Z --end-time 2014-04-09T23:18:00Z --period 3600 --namespace AWS/EC2 --statistics Maximum --dimensions Name=InstanceId,Value=i-abcdef
```
出力:  

```
{
    "Datapoints": [
        {
            "Timestamp": "2014-04-09T11:18:00Z",
            "Maximum": 44.79,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T20:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T19:18:00Z",
            "Maximum": 50.85,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T09:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T03:18:00Z",
            "Maximum": 76.84,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T21:18:00Z",
            "Maximum": 48.96,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T14:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T08:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T16:18:00Z",
            "Maximum": 45.55,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T06:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T13:18:00Z",
            "Maximum": 45.08,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T05:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T18:18:00Z",
            "Maximum": 46.88,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T17:18:00Z",
            "Maximum": 52.08,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T07:18:00Z",
            "Maximum": 47.92,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T02:18:00Z",
            "Maximum": 51.23,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T12:18:00Z",
            "Maximum": 47.67,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-08T23:18:00Z",
            "Maximum": 46.88,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T10:18:00Z",
            "Maximum": 51.91,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T04:18:00Z",
            "Maximum": 47.13,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T15:18:00Z",
            "Maximum": 48.96,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T00:18:00Z",
            "Maximum": 48.16,
            "Unit": "Percent"
        },
        {
            "Timestamp": "2014-04-09T01:18:00Z",
            "Maximum": 49.18,
            "Unit": "Percent"
        }
    ],
    "Label": "CPUUtilization"
}
```
**複数のディメンションを指定する**  
次の例は、複数のディメンションを指定する方法を示しています。各ディメンションは名前/値のペアとして指定され、名前と値の間にはカンマが入ります。複数のディメンションはスペースで区切ります。また、1 つのメトリクスに複数のディメンションを含む場合は、定義されているディメンションごとに値を指定する必要があります。  
`get-metric-statistics` コマンドのその他の使用例については、「Amazon CloudWatch ユーザーガイド」の「メトリクスの統計を取得する」を参照してください。**  

```
aws cloudwatch get-metric-statistics --metric-name Buffers --namespace MyNameSpace --dimensions Name=InstanceID,Value=i-abcdef Name=InstanceType,Value=m1.small --start-time 2016-10-15T04:00:00Z --end-time 2016-10-19T07:00:00Z --statistics Average --period 60
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetMetricStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-statistics.html)」を参照してください。**

### `get-metric-stream`
<a name="cloudwatch_GetMetricStream_cli_2_topic"></a>

次のコード例は、`get-metric-stream` を使用する方法を示しています。

**AWS CLI**  
**メトリクスストリームに関する情報を取得するには**  
次の `get-metric-stream` の例では、指定したアカウントの `QuickFull-GuaFbs` という名前のメトリクスストリームに関する情報が表示されます。  

```
aws cloudwatch get-metric-stream \
    --name QuickFull-GuaFbs
```
出力:  

```
{
    "Arn": "arn:aws:cloudwatch:us-east-1:123456789012:metric-stream/QuickFull-GuaFbs",
    "Name": "QuickFull-GuaFbs",
    "FirehoseArn": "arn:aws:firehose:us-east-1:123456789012:deliverystream/MetricStreams-QuickFull-GuaFbs-WnySbECG",
    "RoleArn": "arn:aws:iam::123456789012:role/service-role/MetricStreams-FirehosePutRecords-JN10W9B3",
    "State": "running",
    "CreationDate": "2024-10-11T18:48:59.187000+00:00",
    "LastUpdateDate": "2024-10-11T18:48:59.187000+00:00",
    "OutputFormat": "json",
    "IncludeLinkedAccountsMetrics": false
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[メトリクスストリームを使用する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetMetricStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-stream.html)」を参照してください。

### `get-metric-widget-image`
<a name="cloudwatch_GetMetricWidgetImage_cli_2_topic"></a>

次のコード例は、`get-metric-widget-image` を使用する方法を示しています。

**AWS CLI**  
**CPUUtilization のスナップショットグラフを取得する方法**  
次の `get-metric-widget-image` の例では、ID `i-abcde` を持つ EC2 インスタンスの `CPUUtilization` メトリクスのスナップショットグラフを取得し、取得したイメージを「image.png」という名前のファイルとしてローカルマシンに保存します。  

```
aws cloudwatch get-metric-widget-image \
    --metric-widget '{"metrics":[["AWS/EC2","CPUUtilization","InstanceId","i-abcde"]]}' \
    --output-format png \
    --output text | base64 --decode > image.png
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMetricWidgetImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/get-metric-widget-image.html)」を参照してください。

### `list-dashboards`
<a name="cloudwatch_ListDashboards_cli_2_topic"></a>

次のコード例は、`list-dashboards` を使用する方法を示しています。

**AWS CLI**  
**ダッシュボードのリストを取得する方法**  
次の `list-dashboards` の例では、指定されたアカウントですべてのダッシュボードを一覧表示します。  

```
aws cloudwatch list-dashboards
```
出力:  

```
{
    "DashboardEntries": [
        {
            "DashboardName": "Dashboard-A",
            "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-A",
            "LastModified": "2024-10-11T18:40:11+00:00",
            "Size": 271
        },
        {
            "DashboardName": "Dashboard-B",
            "DashboardArn": "arn:aws:cloudwatch::123456789012:dashboard/Dashboard-B",
            "LastModified": "2024-10-11T18:44:41+00:00",
            "Size": 522
        }
    ]
}
```
詳細については、「Amazon CloudWatch ユーザーガイド」の「[Amazon CloudWatch のダッシュボード](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Dashboards.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDashboards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-dashboards.html)」を参照してください。

### `list-metric-streams`
<a name="cloudwatch_ListMetricStreams_cli_2_topic"></a>

次のコード例は、`list-metric-streams` を使用する方法を示しています。

**AWS CLI**  
**メトリクスストリームのリストを取得するには**  
次の `list-metric-streams` の例では、指定したアカウントのすべてのメトリクスストリームを一覧表示します。  

```
aws cloudwatch list-metric-streams
```
出力:  

```
{
    "Entries": [
        {
            "Arn": "arn:aws:cloudwatch:us-east-1:123456789012:metric-stream/QuickFull-GuaFbs",
            "CreationDate": "2024-10-11T18:48:59.187000+00:00",
            "LastUpdateDate": "2024-10-11T18:48:59.187000+00:00",
            "Name": "QuickFull-GuaFbs",
            "FirehoseArn": "arn:aws:firehose:us-east-1:123456789012:deliverystream/MetricStreams-QuickFull-GuaFbs-WnySbECG",
            "State": "running",
            "OutputFormat": "json"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[メトリクスストリームを使用する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListMetricStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-metric-streams.html)」を参照してください。

### `list-metrics`
<a name="cloudwatch_ListMetrics_cli_2_topic"></a>

次のコード例は、`list-metrics` を使用する方法を示しています。

**AWS CLI**  
**Amazon SNS のメトリクスを一覧表示するには**  
次の `list-metrics` の例は、Amazon SNS のメトリクスを表示します。  

```
aws cloudwatch list-metrics \
    --namespace "AWS/SNS"
```
出力:  

```
{
    "Metrics": [
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "PublishSize"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "PublishSize"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "NumberOfNotificationsFailed"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "NumberOfNotificationsDelivered"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "NotifyMe"
                }
            ],
            "MetricName": "NumberOfMessagesPublished"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "NumberOfMessagesPublished"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "NumberOfNotificationsDelivered"
        },
        {
            "Namespace": "AWS/SNS",
            "Dimensions": [
                {
                    "Name": "TopicName",
                    "Value": "CFO"
                }
            ],
            "MetricName": "NumberOfNotificationsFailed"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListMetrics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-metrics.html)」を参照してください。**

### `list-tags-for-resource`
<a name="cloudwatch_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のアラームに関連付けられているタグを一覧表示するには\$1**  
次の `list-tags-for-resource` の例では、指定したアカウントの `demo` という名前のアラームに関連付けられているすべてのタグを一覧表示します。  

```
aws cloudwatch list-tags-for-resource \
    --resource-arn arn:aws:cloudwatch:us-east-1:123456789012:alarm:demo
```
出力:  

```
{
    "Tags": [
        {
            "Key": "stack",
            "Value": "Production"
        },
        {
            "Key": "team",
            "Value": "Devops"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[アラームとタグ付け](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_alarms_and_tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/list-tags-for-resource.html)」を参照してください。

### `put-anomaly-detector`
<a name="cloudwatch_PutAnomalyDetector_cli_2_topic"></a>

次のコード例は、`put-anomaly-detector` を使用する方法を示しています。

**AWS CLI**  
**異常検出モデルを作成する方法**  
次の `put-anomaly-detector` の例では、CloudWatch メトリクスの異常検出モデルを作成します。  

```
aws cloudwatch put-anomaly-detector \
    --namespace AWS/Logs \
    --metric-name IncomingBytes \
    --stat SampleCount
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[CloudWatch 異常検出の使用](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Anomaly_Detection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAnomalyDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-anomaly-detector.html)」を参照してください。

### `put-composite-alarm`
<a name="cloudwatch_PutCompositeAlarm_cli_2_topic"></a>

次のコード例は、`put-composite-alarm` を使用する方法を示しています。

**AWS CLI**  
**複合 CloudWatch アラームを作成するには**  
次の `put-composite-alarm` の例では、指定したアカウントに `ProdAlarm` という名前の複合アラームを作成します。  

```
aws cloudwatch put-composite-alarm \
    --alarm-name ProdAlarm \
    --alarm-rule "ALARM(CPUUtilizationTooHigh) AND ALARM(MemUsageTooHigh)" \
    --alarm-actions arn:aws:sns:us-east-1:123456789012:demo \
    --actions-enabled
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[複合アラームを作成する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Create_Composite_Alarm_How_To.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutCompositeAlarm](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-composite-alarm.html)」を参照してください。

### `put-dashboard`
<a name="cloudwatch_PutDashboard_cli_2_topic"></a>

次のコード例は、`put-dashboard` を使用する方法を示しています。

**AWS CLI**  
**ダッシュボードを作成するには**  
次の `put-dashboard` の例では、指定されたアカウントで `Dashboard-A` という名前のダッシュボードを作成します。  

```
aws cloudwatch put-dashboard \
    --dashboard-name Dashboard-A \
    --dashboard-body '{"widgets":[{"height":6,"width":6,"y":0,"x":0,"type":"metric","properties":{"view":"timeSeries","stacked":false,"metrics":[["Namespace","CPUUtilization","Environment","Prod","Type","App"]],"region":"us-east-1"}}]}'
```
出力:  

```
{
    "DashboardValidationMessages": []
}
```
詳細については、「*Amazon CloudWatchユーザーガイド*」の「[CloudWatch ダッシュボードの作成](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create_dashboard.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-dashboard.html)」を参照してください。

### `put-insight-rule`
<a name="cloudwatch_PutInsightRule_cli_2_topic"></a>

次のコード例は、`put-insight-rule` を使用する方法を示しています。

**AWS CLI**  
**Contributor Insights ルールを作成するには**  
次の `put-insight-rule` の例では、指定したアカウントに `VPCFlowLogsContributorInsights` という名前の Contributor Insights ルールを作成します。  

```
aws cloudwatch put-insight-rule \
    --rule-name VPCFlowLogsContributorInsights \
    --rule-definition file://insight-rule.json \
    --rule-state ENABLED
```
`insight-rule.json` の内容:  

```
{
    "Schema": {
        "Name": "CloudWatchLogRule",
        "Version": 1
    },
    "AggregateOn": "Count",
    "Contribution": {
        "Filters": [],
        "Keys": [
            "tcp-flag"
        ]
    },
    "LogFormat": "CLF",
    "LogGroupNames": [
        "/vpc/flowlogs/*"
    ],
    "Fields": {
        "23": "tcp-flag"
    }
}
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch で Contributor Insights ルールを作成する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContributorInsights-CreateRule.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutInsightRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-insight-rule.html)」を参照してください。

### `put-metric-alarm`
<a name="cloudwatch_PutMetricAlarm_cli_2_topic"></a>

次のコード例は、`put-metric-alarm` を使用する方法を示しています。

**AWS CLI**  
**CPU 使用率が 70% を超えたときに Amazon Simple Notification Service の E メールメッセージを送信するには**  
次の例では、`put-metric-alarm` コマンドを使用して、CPU 使用率が 70% を超えたときに、Amazon Simple Notification Service に E メールメッセージを送信します。  

```
aws cloudwatch put-metric-alarm --alarm-name cpu-mon --alarm-description "Alarm when CPU exceeds 70 percent" --metric-name CPUUtilization --namespace AWS/EC2 --statistic Average --period 300 --threshold 70 --comparison-operator GreaterThanThreshold  --dimensions "Name=InstanceId,Value=i-12345678" --evaluation-periods 2 --alarm-actions arn:aws:sns:us-east-1:111122223333:MyTopic --unit Percent
```
正常に完了すると、このコマンドはプロンプトに戻ります。同じ名前のアラームが既に存在する場合は、新しいアラームで上書きされます。  
**複数のディメンションを指定するには**  
次の例は、複数のディメンションを指定する方法を示しています。各ディメンションは名前/値のペアとして指定され、名前と値の間にはカンマが入ります。複数のディメンションはスペースで区切ります。  

```
aws cloudwatch put-metric-alarm --alarm-name "Default_Test_Alarm3" --alarm-description "The default example alarm" --namespace "CW EXAMPLE METRICS" --metric-name Default_Test --statistic Average --period 60 --evaluation-periods 3 --threshold 50 --comparison-operator GreaterThanOrEqualToThreshold --dimensions Name=key1,Value=value1 Name=key2,Value=value2
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutMetricAlarm](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-metric-alarm.html)」を参照してください。**

### `put-metric-data`
<a name="cloudwatch_PutMetricData_cli_2_topic"></a>

次のコード例は、`put-metric-data` を使用する方法を示しています。

**AWS CLI**  
**Amazon CloudWatch にカスタムメトリクスをパブリッシュするには**  
次の例は、`put-metric-data` コマンドを使用して、Amazon CloudWatch にカスタムメトリクスをパブリッシュします。  

```
aws cloudwatch put-metric-data --namespace "Usage Metrics" --metric-data file://metric.json
```
メトリクス自体の値は、JSON ファイル `metric.json` に保存されます。  
ファイルの内容は次のとおりです。  

```
[
  {
    "MetricName": "New Posts",
    "Timestamp": "Wednesday, June 12, 2013 8:28:20 PM",
    "Value": 0.50,
    "Unit": "Count"
  }
]
```
詳細については、「Amazon CloudWatch ユーザーガイド」の「カスタムメトリクスをパブリッシュする」を参照してください。**  
**複数のディメンションを指定するには**  
次の例は、複数のディメンションを指定する方法を示しています。各ディメンションは Name=Value ペアとして指定されます。複数のディメンションはコンマで区切ります。  

```
aws cloudwatch put-metric-data --metric-name Buffers --namespace MyNameSpace --unit Bytes --value 231434333 --dimensions InstanceID=1-23456789,InstanceType=m1.small
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutMetricData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-metric-data.html)」を参照してください。**

### `put-metric-stream`
<a name="cloudwatch_PutMetricStream_cli_2_topic"></a>

次のコード例は、`put-metric-stream` を使用する方法を示しています。

**AWS CLI**  
**メトリクスストリームを作成するには**  
次の `QuickFull-GuaFb` の例では、指定したアカウントに `put-metric-stream` という名前のメトリクスストリームを作成します。  

```
aws cloudwatch put-metric-stream \
    --name QuickFull-GuaFbs \
    --firehose-arn arn:aws:firehose:us-east-1:123456789012:deliverystream/MetricStreams-QuickFull-GuaFbs-WnySbECG \
    --role-arn arn:aws:iam::123456789012:role/service-role/MetricStreams-FirehosePutRecords-JN10W9B3 \
    --output-format json \
    --no-include-linked-accounts-metrics
```
出力:  

```
{
    "Arn": "arn:aws:cloudwatch:us-east-1:123456789012:metric-stream/QuickFull-GuaFbs"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[メトリクスストリームを設定する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-metric-streams-setup.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutMetricStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/put-metric-stream.html)」を参照してください。

### `set-alarm-state`
<a name="cloudwatch_SetAlarmState_cli_2_topic"></a>

次のコード例は、`set-alarm-state` を使用する方法を示しています。

**AWS CLI**  
**アラームの状態を一時的に変更するには**  
次の例では、`set-alarm-state` コマンドを使用して「myalarm」という名前の Amazon CloudWatch アラームの状態を一時的に変更し、テスト目的で ALARM 状態に設定します。  

```
aws cloudwatch set-alarm-state --alarm-name "myalarm" --state-value ALARM --state-reason "testing purposes"
```
正常に完了すると、このコマンドはプロンプトに戻ります。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetAlarmState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/set-alarm-state.html)」を参照してください。

### `start-metric-streams`
<a name="cloudwatch_StartMetricStreams_cli_2_topic"></a>

次のコード例は、`start-metric-streams` を使用する方法を示しています。

**AWS CLI**  
**指定したメトリクスストリームを開始するには**  
次の `start-metric-streams` の例では、指定したアカウントの `QuickFull-GuaFbs` という名前のメトリクスストリームを開始します。  

```
aws cloudwatch start-metric-streams \
    --names QuickFull-GuaFbs
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[メトリクスストリームを使用する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartMetricStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/start-metric-streams.html)」を参照してください。

### `stop-metric-streams`
<a name="cloudwatch_StopMetricStreams_cli_2_topic"></a>

次のコード例は、`stop-metric-streams` を使用する方法を示しています。

**AWS CLI**  
**指定したメトリクスストリームを停止するには**  
次の `stop-metric-streams` の例では、指定したアカウントの `QuickFull-GuaFbs` という名前のメトリクスストリームを停止します。  

```
aws cloudwatch stop-metric-streams \
    --names QuickFull-GuaFbs
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[メトリクスストリームを使用する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopMetricStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/stop-metric-streams.html)」を参照してください。

### `tag-resource`
<a name="cloudwatch_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定したリソースに 1 つ以上のタグを追加するには**  
次の `tag-resource` の例では、指定したアカウントの `demo` という名前の CloudWatch アラームに 2 つのタグを追加します。  

```
aws cloudwatch tag-resource \
    --resource-arn arn:aws:cloudwatch:us-east-1:123456789012:alarm:demo \
    --tags Key=stack,Value=Production Key=team,Value=Devops
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Amazon CloudWatch リソースのタグ付け](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="cloudwatch_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定したリソースから 1 つ以上のタグを削除するには**  
次の `untag-resource` の例では、指定したアカウントの `demo` という名前の CloudWatch アラームから 2 つのタグを削除します。  

```
aws cloudwatch untag-resource \
    --resource-arn arn:aws:cloudwatch:us-east-1:123456789012:alarm:demo \
    --tag-keys stack team
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Amazon CloudWatch リソースのタグ付け](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/untag-resource.html)」を参照してください。

# を使用した CloudWatch Logs の例 AWS CLI
<a name="cli_2_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-log-group`
<a name="cloudwatch-logs_CreateLogGroup_cli_2_topic"></a>

次のコード例は、`create-log-group` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-logs` という名前のロググループを作成します。  

```
aws logs create-log-group --log-group-name my-logs
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateLogGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/create-log-group.html)」を参照してください。**

### `create-log-stream`
<a name="cloudwatch-logs_CreateLogStream_cli_2_topic"></a>

次のコード例は、`create-log-stream` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ロググループ `my-logs` に `20150601` という名前のログストリームを作成します。  

```
aws logs create-log-stream --log-group-name my-logs --log-stream-name 20150601
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateLogStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/create-log-stream.html)」を参照してください。**

### `delete-log-group`
<a name="cloudwatch-logs_DeleteLogGroup_cli_2_topic"></a>

次のコード例は、`delete-log-group` を使用する方法を示しています。

**AWS CLI**  
以下のコマンドは、`my-logs` という名前のロググループを削除します。  

```
aws logs delete-log-group --log-group-name my-logs
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteLogGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-log-group.html)」を参照してください。**

### `delete-log-stream`
<a name="cloudwatch-logs_DeleteLogStream_cli_2_topic"></a>

次のコード例は、`delete-log-stream` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-logs` という名前のロググループから `20150531` という名前のログストリームを削除します。  

```
aws logs delete-log-stream --log-group-name my-logs --log-stream-name 20150531
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLogStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-log-stream.html)」を参照してください。

### `delete-retention-policy`
<a name="cloudwatch-logs_DeleteRetentionPolicy_cli_2_topic"></a>

次のコード例は、`delete-retention-policy` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-logs` という名前のロググループに以前に適用された保持ポリシーを削除します。  

```
aws logs delete-retention-policy --log-group-name my-logs
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRetentionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-retention-policy.html)」を参照してください。

### `describe-log-groups`
<a name="cloudwatch-logs_DescribeLogGroups_cli_2_topic"></a>

次のコード例は、`describe-log-groups` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-logs` という名前のロググループを記述します。  

```
aws logs describe-log-groups --log-group-name-prefix my-logs
```
出力:  

```
{
    "logGroups": [
        {
            "storedBytes": 0,
            "metricFilterCount": 0,
            "creationTime": 1433189500783,
            "logGroupName": "my-logs",
            "retentionInDays": 5,
            "arn": "arn:aws:logs:us-west-2:0123456789012:log-group:my-logs:*"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeLogGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/describe-log-groups.html)」を参照してください。**

### `describe-log-streams`
<a name="cloudwatch-logs_DescribeLogStreams_cli_2_topic"></a>

次のコード例は、`describe-log-streams` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ロググループ `my-logs` のプレフィックス `2015` で始まるすべてのログストリームを表示します。  

```
aws logs describe-log-streams --log-group-name my-logs --log-stream-name-prefix 2015
```
出力:  

```
{
    "logStreams": [
        {
            "creationTime": 1433189871774,
            "arn": "arn:aws:logs:us-west-2:0123456789012:log-group:my-logs:log-stream:20150531",
            "logStreamName": "20150531",
            "storedBytes": 0
        },
        {
            "creationTime": 1433189873898,
            "arn": "arn:aws:logs:us-west-2:0123456789012:log-group:my-logs:log-stream:20150601",
            "logStreamName": "20150601",
            "storedBytes": 0
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLogStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/describe-log-streams.html)」を参照してください。

### `get-log-events`
<a name="cloudwatch-logs_GetLogEvents_cli_2_topic"></a>

次のコード例は、`get-log-events` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ロググループ `my-logs` の `20150601` という名前のログストリームからログイベントを取得します。  

```
aws logs get-log-events --log-group-name my-logs --log-stream-name 20150601
```
出力:  

```
{
    "nextForwardToken": "f/31961209122447488583055879464742346735121166569214640130",
    "events": [
        {
            "ingestionTime": 1433190494190,
            "timestamp": 1433190184356,
            "message": "Example Event 1"
        },
        {
            "ingestionTime": 1433190516679,
            "timestamp": 1433190184356,
            "message": "Example Event 1"
        },
        {
            "ingestionTime": 1433190494190,
            "timestamp": 1433190184358,
            "message": "Example Event 2"
        }
    ],
    "nextBackwardToken": "b/31961209122358285602261756944988674324553373268216709120"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLogEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/get-log-events.html)」を参照してください。

### `put-log-events`
<a name="cloudwatch-logs_PutLogEvents_cli_2_topic"></a>

次のコード例は、`put-log-events` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ロググループ `my-logs` の `20150601` という名前のログストリームにログイベントを配置します。  

```
aws logs put-log-events --log-group-name my-logs --log-stream-name 20150601 --log-events file://events
```
出力:  

```
{
    "nextSequenceToken": "49542672486831074009579604567656788214806863282469607346"
}
```
上記の例では、現在のディレクトリにある `events` という名前のファイルからイベントの JSON 配列を読み取ります。  

```
[
  {
    "timestamp": 1433190184356,
    "message": "Example Event 1"
  },
  {
    "timestamp": 1433190184358,
    "message": "Example Event 2"
  },
  {
    "timestamp": 1433190184360,
    "message": "Example Event 3"
  }
]
```
以降の各呼び出しでは、前の呼び出しで提供された次のシーケンストークンをシーケンストークンオプションで指定する必要があります。  

```
aws logs put-log-events --log-group-name my-logs --log-stream-name 20150601 --log-events file://events2 --sequence-token "49542672486831074009579604567656788214806863282469607346"
```
出力:  

```
{
    "nextSequenceToken": "49542672486831074009579604567900991230369019956308219826"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLogEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/put-log-events.html)」を参照してください。

### `put-retention-policy`
<a name="cloudwatch-logs_PutRetentionPolicy_cli_2_topic"></a>

次のコード例は、`put-retention-policy` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-logs` という名前のロググループに 5 日間の保持ポリシーを追加します。  

```
aws logs put-retention-policy --log-group-name my-logs --retention-in-days 5
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRetentionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/put-retention-policy.html)」を参照してください。

# を使用した CloudWatch Network Monitoring の例 AWS CLI
<a name="cli_2_networkmonitor_code_examples"></a>

次のコード例は、CloudWatch Network Monitoring AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-monitor`
<a name="networkmonitor_CreateMonitor_cli_2_topic"></a>

次のコード例は、`create-monitor` を使用する方法を示しています。

**AWS CLI**  
**例 1: 集計期間付きのネットワークモニターを作成するには**  
次の `create-monitor` の例では、`aggregationPeriod` を `30` 秒に設定した `Example_NetworkMonitor` という名前のモニターを作成します。関連するプローブがないため、モニターのイニシャル `state` は `INACTIVE` となります。状態は、プローブが追加された場合にのみ `ACTIVE` に変わります。[update-monitor](https://docs.aws.amazon.com/cli/latest/reference/networkmonitor/update-monitor.html) コマンドまたは [create-probe](https://docs.aws.amazon.com/cli/latest/reference/networkmonitor/create-probe.html) コマンドを使用して、このモニターにプローブを追加できます。  

```
aws networkmonitor create-monitor \
     --monitor-name Example_NetworkMonitor \
     --aggregation-period 30
```
出力:  

```
{
    "monitorArn": "arn:aws:networkmonitor:region:111122223333:monitor/Example_NetworkMonitor",
    "monitorName": "Example_NetworkMonitor",
    "state": "INACTIVE",
    "aggregationPeriod": 30,
    "tags": {}
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
**例 2: TCP を使用してプローブ付きのネットワークモニターを作成し、タグを含めるには**  
次の `create-monitor` の例では、`Example_NetworkMonitor` という名前のモニターを作成します。コマンドは、`ICMP` プロトコルを使用して 1 つのプローブも作成し、タグを含めます。リクエストで `aggregationPeriod` が渡されないため、デフォルトとして `60` 秒が設定されます。プローブ付きのモニターの `state` は、モニターが `ACTIVE` になるまで `PENDING` になります。これには数分かかる場合があります。その時点で、`state` は `ACTIVE` に変わり、CloudWatch メトリクスの表示を開始できます。  

```
aws networkmonitor create-monitor \
    --monitor-name Example_NetworkMonitor \
    --probes sourceArn=arn:aws:ec2:region:111122223333:subnet/subnet-id,destination=10.0.0.100,destinationPort=80,protocol=TCP,packetSize=56,probeTags={Name=Probe1} \
    --tags Monitor=Monitor1
```
出力:  

```
{
    "monitorArn": "arn:aws:networkmonitor:region111122223333:monitor/Example_NetworkMonitor",
    "monitorName": "Example_NetworkMonitor",
    "state": "PENDING",
    "aggregationPeriod": 60,
    "tags": {
        "Monitor": "Monitor1"
    }
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
**例 3: ICMP を使用してプローブ付きのネットワークモニターを作成し、タグを含めるには**  
次の `create-monitor` の例では、`aggregationPeriod` が `30` 秒の `Example_NetworkMonitor` という名前のモニターを作成します。コマンドは、`ICMP` プロトコルを使用して 1 つのプローブも作成し、タグを含めます。リクエストで `aggregationPeriod` が渡されないため、デフォルトとして `60` 秒が設定されます。プローブ付きのモニターの `state` は、モニターが `ACTIVE` になるまで `PENDING` になります。これには数分かかる場合があります。その時点で、`state` は `ACTIVE` に変わり、CloudWatch メトリクスの表示を開始できます。  

```
aws networkmonitor create-monitor \
     --monitor-name Example_NetworkMonitor \
     --aggregation-period 30 \
     --probes sourceArn=arn:aws:ec2:region111122223333:subnet/subnet-id,destination=10.0.0.100,protocol=ICMP,packetSize=56,probeTags={Name=Probe1} \
     --tags Monitor=Monitor1
```
出力:  

```
{
    "monitorArn": "arn:aws:networkmonitor:region:111122223333:monitor/Example_NetworkMonitor",
    "monitorName": "Example_NetworkMonitor",
    "state": "PENDING",
    "aggregationPeriod": 30,
    "tags": {
        "Monitor": "Monitor1"
    }
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/create-monitor.html)」を参照してください。

### `create-probe`
<a name="networkmonitor_CreateProbe_cli_2_topic"></a>

次のコード例は、`create-probe` を使用する方法を示しています。

**AWS CLI**  
**例 1: TCP を使用するプローブを作成し、ネットワークモニターに追加するには**  
次の `create-probe` の例では、`TCP` `protocol` を使用するプローブを作成し、プローブを `Example_NetworkMonitor` という名前のモニターに追加します。作成されると、プローブ付きのモニターの `state` は、モニターが `ACTIVE` になるまで `PENDING` になります。これには数分かかる場合があります。その時点で state は `ACTIVE` に変わり、CloudWatch メトリクスの表示を開始できます。  

```
aws networkmonitor create-probe \
    --monitor-name Example_NetworkMonitor \
    --probe sourceArn=arn:aws:ec2:region:111122223333:subnet/subnet-id,destination=10.0.0.100,destinationPort=80,protocol=TCP,packetSize=56,tags={Name=Probe1}
```
出力:  

```
{
    "probeId": "probe-12345",
    "probeArn": "arn:aws:networkmonitor:region:111122223333:probe/probe-12345",
    "destination": "10.0.0.100",
    "destinationPort": 80,
    "packetSize": 56,
    "addressFamily": "IPV4",
    "vpcId": "vpc-12345",
    "state": "PENDING",
    "createdAt": "2024-03-29T12:41:57.314000-04:00",
    "modifiedAt": "2024-03-29T12:41:57.314000-04:00",
    "tags": {
        "Name": "Probe1"
    }
}
```
**例 2: ICMP を使用してプローブを使用するプローブ作成し、ネットワークモニターに追加するには**  
次の `create-probe` の例では、`ICMP` `protocol` を使用するプローブを作成し、プローブを `Example_NetworkMonitor` という名前のモニターに追加します。作成されると、プローブ付きのモニターの `state` は、モニターが `ACTIVE` になるまで `PENDING` になります。これには数分かかる場合があります。その時点で state は `ACTIVE` に変わり、CloudWatch メトリクスの表示を開始できます。  

```
aws networkmonitor create-probe \
    --monitor-name Example_NetworkMonitor \
    --probe sourceArn=arn:aws:ec2:region:012345678910:subnet/subnet-id,destination=10.0.0.100,protocol=ICMP,packetSize=56,tags={Name=Probe1}
```
出力:  

```
{
    "probeId": "probe-12345",
    "probeArn": "arn:aws:networkmonitor:region:111122223333:probe/probe-12345",
    "destination": "10.0.0.100",
    "packetSize": 56,
    "addressFamily": "IPV4",
    "vpcId": "vpc-12345",
    "state": "PENDING",
    "createdAt": "2024-03-29T12:44:02.452000-04:00",
    "modifiedAt": "2024-03-29T12:44:02.452000-04:00",
    "tags": {
        "Name": "Probe1"
    }
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProbe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/create-probe.html)」を参照してください。

### `delete-monitor`
<a name="networkmonitor_DeleteMonitor_cli_2_topic"></a>

次のコード例は、`delete-monitor` を使用する方法を示しています。

**AWS CLI**  
**モニターを削除するには**  
次の `delete-monitor` の例では、`Example_NetworkMonitor` という名前のモニターを削除します。  

```
aws networkmonitor delete-monitor \
    --monitor-name Example_NetworkMonitor
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/delete-monitor.html)」を参照してください。

### `delete-probe`
<a name="networkmonitor_DeleteProbe_cli_2_topic"></a>

次のコード例は、`delete-probe` を使用する方法を示しています。

**AWS CLI**  
**プローブを削除するには**  
次の `delete-probe` の例では、`Example_NetworkMonitor` という名前のネットワークモニターから ID が `probe-12345` のプローブを削除します。  

```
aws networkmonitor delete-probe \
    --monitor-name Example_NetworkMonitor \
    --probe-id probe-12345
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProbe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/delete-probe.html)」を参照してください。

### `get-monitor`
<a name="networkmonitor_GetMonitor_cli_2_topic"></a>

次のコード例は、`get-monitor` を使用する方法を示しています。

**AWS CLI**  
**モニター情報を取得するには**  
次の `get-monitor` の例では、`Example_NetworkMonitor` という名前のモニターに関する情報を取得します。  

```
aws networkmonitor get-monitor \
    --monitor-name Example_NetworkMonitor
```
出力:  

```
{
    "monitorArn": "arn:aws:networkmonitor:region:012345678910:monitor/Example_NetworkMonitor",
    "monitorName": "Example_NetworkMonitor",
    "state": "ACTIVE",
    "aggregationPeriod": 60,
    "tags": {},
    "probes": [],
    "createdAt": "2024-04-01T17:58:07.211000-04:00",
    "modifiedAt": "2024-04-01T17:58:07.211000-04:00"
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/get-monitor.html)」を参照してください。

### `get-probe`
<a name="networkmonitor_GetProbe_cli_2_topic"></a>

次のコード例は、`get-probe` を使用する方法を示しています。

**AWS CLI**  
**プローブの詳細を表示するには**  
次の `get-probe` の例では、`Example_NetworkMonitor` という名前のモニターに関連付けられた `probeID` `probe-12345` を持つプローブの詳細を返します。  

```
aws networkmonitor get-probe \
    --monitor-name Example_NetworkMonitor \
    --probe-id probe-12345
```
出力:  

```
{
    "probeId": "probe-12345",
    "probeArn": "arn:aws:networkmonitor:region:012345678910:probe/probe-12345",
    "sourceArn": "arn:aws:ec2:region:012345678910:subnet/subnet-12345",
    "destination": "10.0.0.100",
    "destinationPort": 80,
    "protocol": "TCP",
    "packetSize": 56,
    "addressFamily": "IPV4",
    "vpcId": "vpc-12345",
    "state": "ACTIVE",
    "createdAt": "2024-03-29T12:41:57.314000-04:00",
    "modifiedAt": "2024-03-29T12:42:28.610000-04:00",
    "tags": {
        "Name": "Probe1"
    }
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetProbe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/get-probe.html)」を参照してください。

### `list-monitors`
<a name="networkmonitor_ListMonitors_cli_2_topic"></a>

次のコード例は、`list-monitors` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのモニター (単一モニター) を一覧表示するには**  
次の `list-monitors` の例では、単一モニターのみのリストを返します。モニター `state` は `ACTIVE` で、`aggregationPeriod` は 60 秒です。  

```
aws networkmonitor list-monitors
```
出力:  

```
{
    "monitors": [{
            "monitorArn": "arn:aws:networkmonitor:region:012345678910:monitor/Example_NetworkMonitor",
            "monitorName": "Example_NetworkMonitor",
            "state": "ACTIVE",
            "aggregationPeriod": 60,
            "tags": {
                "Monitor": "Monitor1"
            }
        }
    ]
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
**例 2: すべてのモニターを一覧表示するには (複数のモニター)**  
次の `list-monitors` の例では、3 台のモニターのリストを返します。1 台のモニターの `state` は `ACTIVE` であり、CloudWatch メトリクスを生成します。他の 2 台のモニターの状態は `INACTIVE` であり、CloudWatch メトリクスを生成しません。3 台のモニターはすべて 60 秒の `aggregationPeriod` を使用します。  

```
aws networkmonitor list-monitors
```
出力:  

```
{
    "monitors": [
        {
            "monitorArn": "arn:aws:networkmonitor:us-east-1:111122223333:monitor/Example_NetworkMonitor",
            "monitorName": "Example_NetworkMonitor",
            "state": "INACTIVE",
            "aggregationPeriod": 60,
            "tags": {}
        },
        {
            "monitorArn": "arn:aws:networkmonitor:us-east-1:111122223333:monitor/Example_NetworkMonitor2",
            "monitorName": "Example_NetworkMonitor2",
            "state": "ACTIVE",
            "aggregationPeriod": 60,
            "tags": {
                "Monitor": "Monitor1"
            }
        },
        {
            "monitorArn": "arn:aws:networkmonitor:us-east-1:111122223333:monitor/TestNetworkMonitor_CLI",
            "monitorName": "TestNetworkMonitor_CLI",
            "state": "INACTIVE",
            "aggregationPeriod": 60,
            "tags": {}
        }
    ]
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMonitors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/list-monitors.html)」を参照してください。

### `list-tags-for-resource`
<a name="networkmonitor_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、`Example_NetworkMonitor` という名前のモニターのタグのリストを返します。  

```
aws networkmonitor list-tags-for-resource \
    --resource-arn arn:aws:networkmonitor:region:012345678910:monitor/Example_NetworkMonitor
```
出力:  

```
{
    "tags": {
        "Environment": "Dev",
        "Application": "PetStore"
    }
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/list-tags-for-resource.html)」を参照してください。

### `tag-resource`
<a name="networkmonitor_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、`Example_NetworkMonitor` という名前のモニターに `Environment=Dev` と `Application=PetStore` のタグを付けます。  

```
aws networkmonitor tag-resource \
    --resource-arn arn:aws:networkmonitor:region:012345678910:monitor/Example_NetworkMonitor \
    --tags Environment=Dev,Application=PetStore
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="networkmonitor_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを削除するには**  
次の `untag-resource` の例では、`Example_NetworkMonitor` という名前のモニターとの関連付けから、`Environment Application` のキーと値のペアを持つ `tag-keys` パラメータを削除します。  

```
aws networkmonitor untag-resource \
    --resource-arn arn:aws:networkmonitor:region:012345678910:monitor/Example_NetworkMonitor \
    --tag-keys Environment Application
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/untag-resource.html)」を参照してください。

### `update-monitor`
<a name="networkmonitor_UpdateMonitor_cli_2_topic"></a>

次のコード例は、`update-monitor` を使用する方法を示しています。

**AWS CLI**  
**モニターを更新するには**  
次の `update-monitor` の例では、モニターの `aggregationPeriod` を `60` 秒から `30` 秒に変更します。  

```
aws networkmonitor update-monitor \
    --monitor-name Example_NetworkMonitor \
    --aggregation-period 30
```
出力:  

```
{
    "monitorArn": "arn:aws:networkmonitor:region:012345678910:monitor/Example_NetworkMonitor",
    "monitorName": "Example_NetworkMonitor",
    "state": "PENDING",
    "aggregationPeriod": 30,
    "tags": {
        "Monitor": "Monitor1"
    }
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/update-monitor.html)」を参照してください。

### `update-probe`
<a name="networkmonitor_UpdateProbe_cli_2_topic"></a>

次のコード例は、`update-probe` を使用する方法を示しています。

**AWS CLI**  
**プローブを更新するには**  
次の `update-probe` の例では、プローブの元の `destination` IP アドレスを更新し、`packetSize` を `60` に更新します。  

```
aws networkmonitor update-probe \
    --monitor-name Example_NetworkMonitor \
    --probe-id probe-12345 \
    --destination 10.0.0.150 \
    --packet-size 60
```
出力:  

```
{
    "probeId": "probe-12345",
    "probeArn": "arn:aws:networkmonitor:region:012345678910:probe/probe-12345",
    "sourceArn": "arn:aws:ec2:region:012345678910:subnet/subnet-12345",
    "destination": "10.0.0.150",
    "destinationPort": 80,
    "protocol": "TCP",
    "packetSize": 60,
    "addressFamily": "IPV4",
    "vpcId": "vpc-12345",
    "state": "PENDING",
    "createdAt": "2024-03-29T12:41:57.314000-04:00",
    "modifiedAt": "2024-03-29T13:52:23.115000-04:00",
    "tags": {
        "Name": "Probe1"
    }
}
```
詳細については、「*Amazon CloudWatch User Guide*」の「[How Amazon CloudWatch Network Monitor Works](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/nw-monitor-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateProbe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmonitor/update-probe.html)」を参照してください。

# を使用した CloudWatch Observability Access Monitor の例 AWS CLI
<a name="cli_2_oam_code_examples"></a>

次のコード例は、CloudWatch Observability Access Monitor AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-link`
<a name="oam_CreateLink_cli_2_topic"></a>

次のコード例は、`create-link` を使用する方法を示しています。

**AWS CLI**  
**リンクを作成するには**  
次の `create-link` の例では、ソースアカウントと、モニタリングアカウントに作成したシンクとの間にリンクを作成します。  

```
aws oam create-link \
    --label-template sourceAccount \
    --resource-types AWS::CloudWatch::Metric \
    --sink-identifier arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345
```
出力:  

```
{
    "Arn": "arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111",
    "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
    "Label": "sourceAccount",
    "LabelTemplate": "sourceAccount",
    "ResourceTypes": [
        "AWS::CloudWatch::Metric"
    ],
    "SinkArn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
    "Tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/create-link.html)」を参照してください。

### `create-sink`
<a name="oam_CreateSink_cli_2_topic"></a>

次のコード例は、`create-sink` を使用する方法を示しています。

**AWS CLI**  
**シンクを作成するには**  
次の `create-sink` の例では、現在のアカウントにシンクを作成し、CloudWatch クロスアカウントオブザーバビリティでモニタリングアカウントとして使用できるようにします。  

```
aws oam create-sink \
    --name DemoSink
```
出力:  

```
{
    "Arn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
    "Id": "a1b2c3d4-5678-90ab-cdef-example12345",
    "Name": "DemoSink",
    "Tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateSink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/create-sink.html)」を参照してください。

### `delete-link`
<a name="oam_DeleteLink_cli_2_topic"></a>

次のコード例は、`delete-link` を使用する方法を示しています。

**AWS CLI**  
**リンクを削除するには**  
次の `delete-link` の例では、モニタリングアカウントシンクとソースアカウントとの間のリンクを削除します。  

```
aws oam delete-link \
    --identifier arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/delete-link.html)」を参照してください。

### `delete-sink`
<a name="oam_DeleteSink_cli_2_topic"></a>

次のコード例は、`delete-sink` を使用する方法を示しています。

**AWS CLI**  
**シンクを削除するには**  
次の `delete-sink` の例では、シンクを削除します。シンクを削除する前に、そのシンクへのすべてのリンクを削除する必要があります。  

```
aws oam delete-sink \
    --identifier arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteSink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/delete-sink.html)」を参照してください。

### `get-link`
<a name="oam_GetLink_cli_2_topic"></a>

次のコード例は、`get-link` を使用する方法を示しています。

**AWS CLI**  
**1 つのリンクに関する完全な情報を返すには**  
次の `get-link` の例では、リンクに関する完全な情報を返します。  

```
aws oam get-link \
    --identifier arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111
```
出力:  

```
{
    "Arn": "arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111",
    "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
    "Label": "sourceAccount",
    "LabelTemplate": "sourceAccount",
    "ResourceTypes": [
        "AWS::CloudWatch::Metric"
    ],
    "SinkArn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
    "Tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/get-link.html)」を参照してください。

### `get-sink-policy`
<a name="oam_GetSinkPolicy_cli_2_topic"></a>

次のコード例は、`get-sink-policy` を使用する方法を示しています。

**AWS CLI**  
**シンクにアタッチされている現在のポリシーを返すには**  
次の `get-sink-policy` の例では、シンクにアタッチされている現在のポリシーを返します。  

```
aws oam get-sink-policy \
    --sink-identifier arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345
```
出力:  

```
{
    "SinkArn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
    "SinkId": "a1b2c3d4-5678-90ab-cdef-example12345",
    "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::123456789111:root\"},\"Action\":[\"oam:CreateLink\",\"oam:UpdateLink\"],\"Resource\":\"*\",\"Condition\":{\"ForAllValues:StringEquals\":{\"oam:ResourceTypes\":[\"AWS::Logs::LogGroup\",\"AWS::CloudWatch::Metric\",\"AWS::XRay::Trace\",\"AWS::ApplicationInsights::Application\"]}}}]}"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetSinkPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/get-sink-policy.html)」を参照してください。

### `get-sink`
<a name="oam_GetSink_cli_2_topic"></a>

次のコード例は、`get-sink` を使用する方法を示しています。

**AWS CLI**  
**1 つのモニタリングアカウントシンクに関する完全な情報を返すには**  
次の `get-sink` の例では、モニタリングアカウントシンクに関する完全な情報を返します。  

```
aws oam get-sink \
    --identifier arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345
```
出力:  

```
{
    "Arn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
    "Id": "a1b2c3d4-5678-90ab-cdef-example12345",
    "Name": "DemoSink",
    "Tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetSink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/get-sink.html)」を参照してください。

### `list-attached-links`
<a name="oam_ListAttachedLinks_cli_2_topic"></a>

次のコード例は、`list-attached-links` を使用する方法を示しています。

**AWS CLI**  
**このモニタリングアカウントシンクにリンクされているソースアカウントリンクのリストを返すには**  
次の `list-attached-links` の例では、このモニタリングアカウントシンクにリンクされているソースアカウントリンクのリストを返します。  

```
aws oam list-attached-links \
    --sink-identifier arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345
```
出力:  

```
{
    "Items": [{
        "Label": "Monitoring account",
        "LinkArn": "arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111",
        "ResourceTypes": [
            "AWS::ApplicationInsights::Application",
            "AWS::Logs::LogGroup",
            "AWS::CloudWatch::Metric",
            "AWS::XRay::Trace"
        ]
    }]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListAttachedLinks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/list-attached-links.html)」を参照してください。

### `list-links`
<a name="oam_ListLinks_cli_2_topic"></a>

次のコード例は、`list-links` を使用する方法を示しています。

**AWS CLI**  
**1 つのモニタリングアカウントシンクのリンクのリストを返すには**  
次の `list-links` の例では、1 つのモニタリングアカウントシンクのリンクのリストを返します。このオペレーションをソースアカウントで実行すると、このソースアカウントのモニタリングアカウントシンクへのリンクのリストが返されます。  

```
aws oam list-links
```
出力:  

```
{
    "Items": [{
        "Arn": "arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111",
        "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
        "Label": "sourceAccount",
        "ResourceTypes": [
            "AWS::CloudWatch::Metric"
        ],
        "SinkArn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345"
    }]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListLinks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/list-links.html)」を参照してください。

### `list-sinks`
<a name="oam_ListSinks_cli_2_topic"></a>

次のコード例は、`list-sinks` を使用する方法を示しています。

**AWS CLI**  
**モニタリングアカウントに作成されたシンクのリストを返すには**  
次の `list-sinks` の例では、モニタリングアカウントに作成されたシンクのリストを返します。このオペレーションはモニタリングアカウントで実行します。  

```
aws oam list-sinks
```
出力:  

```
{
    "Items": [
        {
            "Arn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
            "Id": "a1b2c3d4-5678-90ab-cdef-example12345",
            "Name": "DemoSink"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListSinks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/list-sinks.html)」を参照してください。

### `list-tags-for-resource`
<a name="oam_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに関連付けられているタグを表示するには**  
次の `list-tags-for-resource` の例では、シンクに関連付けられているタグを表示します。  

```
aws oam list-tags-for-resource \
    --resource-arn arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345
```
出力:  

```
{
    "Tags": {
        "Team": "Devops"
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/list-tags-for-resource.html)」を参照してください。

### `put-sink-policy`
<a name="oam_PutSinkPolicy_cli_2_topic"></a>

次のコード例は、`put-sink-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースポリシーを作成または更新するには**  
次の `put-sink-policy` の例では、モニタリングアカウントシンクにリンクするためのアクセス許可をソースアカウントに付与するリソースポリシーを作成します。  

```
aws oam put-sink-policy \
    --policy '{"Version":"2012-10-17",		 	 	 "Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789111:root"},"Action":["oam:CreateLink","oam:UpdateLink"],"Resource":"*","Condition":{"ForAllValues:StringEquals":{"oam:ResourceTypes":["AWS::Logs::LogGroup","AWS::CloudWatch::Metric","AWS::XRay::Trace","AWS::ApplicationInsights::Application"]}}}]}' \
    --sink-identifier arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345
```
出力:  

```
{
    "SinkArn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
    "SinkId": "a1b2c3d4-5678-90ab-cdef-example12345",
    "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::123456789111:root\"},\"Action\":[\"oam:CreateLink\",\"oam:UpdateLink\"],\"Resource\":\"*\",\"Condition\":{\"ForAllValues:StringEquals\":{\"oam:ResourceTypes\":[\"AWS::Logs::LogGroup\",\"AWS::CloudWatch::Metric\",\"AWS::XRay::Trace\",\"AWS::ApplicationInsights::Application\"]}}}]}"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutSinkPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/put-sink-policy.html)」を参照してください。

### `tag-resource`
<a name="oam_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定したリソースに 1 つ以上のタグを割り当てるには**  
次の `tag-resource` の例では、シンク `arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345` にタグを付けます。  

```
aws oam tag-resource \
    --resource-arn arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345 \
    --tags team=Devops
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="oam_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定したリソースから 1 つ以上のタグを削除するには**  
次の `untag-resource` の例では、キーが `team` のタグをシンク `arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345` から削除します。  

```
aws oam untag-resource \
    --resource-arn arn:aws:oam:us-east-2:123456789012:sink/f3f42f60-f0f2-425c-1234-12347bdd821f \
    --tag-keys team
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/untag-resource.html)」を参照してください。

### `update-link`
<a name="oam_UpdateLink_cli_2_topic"></a>

次のコード例は、`update-link` を使用する方法を示しています。

**AWS CLI**  
**ソースアカウントからそのリンクされたモニタリングアカウントシンクに共有されるデータのタイプを変更するには**  
次の `update-link` の例では、リンク `arn:aws:oam:us-east-2:123456789111:link/0123e691-e7ef-43fa-1234-c57c837fced0` をリソースタイプ `AWS::CloudWatch::Metric` と `AWS::Logs::LogGroup` で更新します。  

```
aws oam update-link \
    --identifier arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111 \
    --resource-types "AWS::CloudWatch::Metric" "AWS::Logs::LogGroup"
```
出力:  

```
{
    "Arn": "arn:aws:oam:us-east-2:123456789111:link/a1b2c3d4-5678-90ab-cdef-example11111",
    "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
    "Label": "sourceAccount",
    "LabelTemplate": "sourceAccount",
    "ResourceTypes": [
        "AWS::CloudWatch::Metric",
        "AWS::Logs::LogGroup"
    ],
    "SinkArn": "arn:aws:oam:us-east-2:123456789012:sink/a1b2c3d4-5678-90ab-cdef-example12345",
    "Tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch のクロスアカウントオブザーバビリティ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/oam/update-link.html)」を参照してください。

# を使用した CloudWatch Observability Admin の例 AWS CLI
<a name="cli_2_observabilityadmin_code_examples"></a>

次のコード例は、CloudWatch Observability Admin AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-telemetry-evaluation-status-for-organization`
<a name="observabilityadmin_GetTelemetryEvaluationStatusForOrganization_cli_2_topic"></a>

次のコード例は、`get-telemetry-evaluation-status-for-organization` を使用する方法を示しています。

**AWS CLI**  
**組織のテレメトリオンボーディングステータスを取得するには**  
次の `get-telemetry-evaluation-status-for-organization` の例では、組織のテレメトリ設定機能の現在のオンボーディングステータスを返します。  

```
aws observabilityadmin get-telemetry-evaluation-status-for-organization
```
出力:  

```
{
    "Status": "RUNNING"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ設定の監査](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-cloudwatch.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetTelemetryEvaluationStatusForOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/get-telemetry-evaluation-status-for-organization.html)」を参照してください。

### `get-telemetry-evaluation-status`
<a name="observabilityadmin_GetTelemetryEvaluationStatus_cli_2_topic"></a>

次のコード例は、`get-telemetry-evaluation-status` を使用する方法を示しています。

**AWS CLI**  
**アカウントのテレメトリオンボーディングステータスを取得するには**  
次の `get-telemetry-evaluation-status` の例では、指定したアカウントのテレメトリ設定機能の現在のオンボーディングステータスを返します。  

```
aws observabilityadmin get-telemetry-evaluation-status
```
出力:  

```
{
    "Status": "RUNNING"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ設定の監査](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-cloudwatch.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetTelemetryEvaluationStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/get-telemetry-evaluation-status.html)」を参照してください。

### `list-resource-telemetry-for-organization`
<a name="observabilityadmin_ListResourceTelemetryForOrganization_cli_2_topic"></a>

次のコード例は、`list-resource-telemetry-for-organization` を使用する方法を示しています。

**AWS CLI**  
**組織のテレメトリ設定を取得するには**  
次の の`list-resource-telemetry-for-organization`例では、テレメトリ設定でサポートされている AWS リソースの組織内のテレメトリ設定のリストを返します。  

```
aws observabilityadmin list-resource-telemetry-for-organization \
    --resource-types  AWS::EC2::Instance
```
出力:  

```
{
    "TelemetryConfigurations": [
        {
            "AccountIdentifier": "111111111111",
            "TelemetryConfigurationState": {
                "Logs": "NotApplicable",
                "Metrics": "Disabled",
                "Traces": "NotApplicable"
            },
            "ResourceType": "AWS::EC2::Instance",
            "ResourceIdentifier": "i-a166400b",
            "ResourceTags": {
                "Name": "dev"
            },
            "LastUpdateTimeStamp": 1733168548521
        },
        {
            "AccountIdentifier": "222222222222",
            "TelemetryConfigurationState": {
                "Logs": "NotApplicable",
                "Metrics": "Disabled",
                "Traces": "NotApplicable"
            },
            "ResourceType": "AWS::EC2::Instance",
            "ResourceIdentifier": "i-b188560f",
            "ResourceTags": {
                "Name": "apache"
            },
            "LastUpdateTimeStamp": 1732744260182
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ設定の監査](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-cloudwatch.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListResourceTelemetryForOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/list-resource-telemetry-for-organization.html)」を参照してください。

### `list-resource-telemetry`
<a name="observabilityadmin_ListResourceTelemetry_cli_2_topic"></a>

次のコード例は、`list-resource-telemetry` を使用する方法を示しています。

**AWS CLI**  
**アカウントのテレメトリ設定を取得するには**  
次の の`list-resource-telemetry`例では、指定されたアカウントのテレメトリ設定でサポートされている AWS リソースのテレメトリ設定のリストを返します。  

```
aws observabilityadmin list-resource-telemetry \
    --resource-types  AWS::EC2::Instance
```
出力:  

```
{
    "TelemetryConfigurations": [
        {
            "AccountIdentifier": "111111111111",
            "TelemetryConfigurationState": {
                "Logs": "NotApplicable",
                "Metrics": "Disabled",
                "Traces": "NotApplicable"
            },
            "ResourceType": "AWS::EC2::Instance",
            "ResourceIdentifier": "i-0e979d278b040f856",
            "ResourceTags": {
                "Name": "apache"
            },
            "LastUpdateTimeStamp": 1732744260182
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ設定の監査](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-cloudwatch.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListResourceTelemetry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/list-resource-telemetry.html)」を参照してください。

### `start-telemetry-evaluation-for-organization`
<a name="observabilityadmin_StartTelemetryEvaluationForOrganization_cli_2_topic"></a>

次のコード例は、`start-telemetry-evaluation-for-organization` を使用する方法を示しています。

**AWS CLI**  
**テレメトリ設定機能を有効にするには**  
次の `start-telemetry-evaluation-for-organization` の例では、組織のテレメトリ設定機能を有効にします。  

```
aws observabilityadmin start-telemetry-evaluation-for-organization
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ監査を有効にする](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-turn-on.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartTelemetryEvaluationForOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/start-telemetry-evaluation-for-organization.html)」を参照してください。

### `start-telemetry-evaluation`
<a name="observabilityadmin_StartTelemetryEvaluation_cli_2_topic"></a>

次のコード例は、`start-telemetry-evaluation` を使用する方法を示しています。

**AWS CLI**  
**テレメトリ設定機能を有効にするには**  
次の `start-telemetry-evaluation` の例では、指定したアカウントのテレメトリ設定機能を有効にします。  

```
aws observabilityadmin start-telemetry-evaluation
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ監査を有効にする](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-turn-on.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartTelemetryEvaluation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/start-telemetry-evaluation.html)」を参照してください。

### `stop-telemetry-evaluation-for-organization`
<a name="observabilityadmin_StopTelemetryEvaluationForOrganization_cli_2_topic"></a>

次のコード例は、`stop-telemetry-evaluation-for-organization` を使用する方法を示しています。

**AWS CLI**  
**テレメトリ設定機能を無効にするには**  
次の `stop-telemetry-evaluation-for-organization` の例では、組織のテレメトリ設定機能を無効にします。  

```
aws observabilityadmin stop-telemetry-evaluation-for-organization
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ監査を無効にする](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-turn-off.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopTelemetryEvaluationForOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/stop-telemetry-evaluation-for-organization.html)」を参照してください。

### `stop-telemetry-evaluation`
<a name="observabilityadmin_StopTelemetryEvaluation_cli_2_topic"></a>

次のコード例は、`stop-telemetry-evaluation` を使用する方法を示しています。

**AWS CLI**  
**テレメトリ設定機能を無効にするには**  
次の `stop-telemetry-evaluation` の例では、指定したアカウントのテレメトリ設定機能を無効にします。  

```
aws observabilityadmin stop-telemetry-evaluation
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[CloudWatch テレメトリ監査を無効にする](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/telemetry-config-turn-off.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopTelemetryEvaluation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/observabilityadmin/stop-telemetry-evaluation.html)」を参照してください。

# を使用した CloudWatch Synthetics の例 AWS CLI
<a name="cli_2_synthetics_code_examples"></a>

次のコード例は、CloudWatch Synthetics AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-resource`
<a name="synthetics_AssociateResource_cli_2_topic"></a>

次のコード例は、`associate-resource` を使用する方法を示しています。

**AWS CLI**  
**Canary をグループに関連付けるには**  
次の `associate-resource` の例では、Canary を `demo_group` という名前のグループに関連付けます。  

```
aws synthetics associate-resource \
    --group-identifier demo_group \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:canary:demo_canary
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AssociateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/associate-resource.html)」を参照してください。

### `create-canary`
<a name="synthetics_CreateCanary_cli_2_topic"></a>

次のコード例は、`create-canary` を使用する方法を示しています。

**AWS CLI**  
**Canary を作成するには**  
次の `create-canary` の例では、`demo_canary` という名前の Canary を作成します。  

```
aws synthetics create-canary \
    --name demo_canary \
    --code '{"S3Bucket": "artifacts3bucket", "S3Key":"demo_canary.zip", "Handler": "index.lambda_handler"}' \
    --artifact-s3-location s3://amzn-s3-demo-bucket/demo_canary.zip \
    --execution-role-arn arn:aws:iam::123456789012:role/demo_canary_role \
    --schedule Expression="rate(10 minutes)" \
    --runtime-version syn-nodejs-puppeteer-9.1
```
出力:  

```
{
    "Canary": {
        "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
        "Name": "demo_canary",
        "Code": {
            "Handler": "index.lambda_handler"
        },
        "ExecutionRoleArn": "arn:aws:iam::123456789012:role/demo_canary_role",
        "Schedule": {
            "Expression": "rate(10 minutes)",
            "DurationInSeconds": 0
        },
        "RunConfig": {
            "TimeoutInSeconds": 600,
            "MemoryInMB": 1000,
            "ActiveTracing": false
        },
        "SuccessRetentionPeriodInDays": 31,
        "FailureRetentionPeriodInDays": 31,
        "Status": {
            "State": "CREATING",
            "StateReasonCode": "CREATE_PENDING"
        },
        "Timeline": {
            "Created": "2024-10-15T19:03:08.826000+05:30",
            "LastModified": "2024-10-15T19:03:08.826000+05:30"
        },
        "ArtifactS3Location": "amzn-s3-demo-bucket/demo_canary.zip",
        "RuntimeVersion": "syn-nodejs-puppeteer-9.1",
        "Tags": {}
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateCanary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/create-canary.html)」を参照してください。

### `create-group`
<a name="synthetics_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**グループを作成するには**  
次の `create-group` の例では、`demo_group` という名前のグループが作成されます。  

```
aws synthetics create-group \
    --name demo_group
```
出力:  

```
{
    "Group": {
        "Id": "example123",
        "Name": "demo_group",
        "Arn": "arn:aws:synthetics:us-east-1:123456789012:group:example123",
        "Tags": {},
        "CreatedTime": "2024-10-15T14:47:23.811000+05:30",
        "LastModifiedTime": "2024-10-15T14:47:23.811000+05:30"
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/create-group.html)」を参照してください。

### `delete-canary`
<a name="synthetics_DeleteCanary_cli_2_topic"></a>

次のコード例は、`delete-canary` を使用する方法を示しています。

**AWS CLI**  
**Canary を完全に削除するには**  
次の `delete-canary` の例では、`demo_canary` という名前の Canary を削除します。  

```
aws synthetics delete-canary \
    --name demo_canary
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteCanary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/delete-canary.html)」を参照してください。

### `delete-group`
<a name="synthetics_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**グループを削除するには**  
次の `delete-group` の例では、`demo_group` という名前のグループを削除します。  

```
aws synthetics delete-group \
    --group-identifier demo_group
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/delete-group.html)」を参照してください。

### `describe-canaries-last-run`
<a name="synthetics_DescribeCanariesLastRun_cli_2_topic"></a>

次のコード例は、`describe-canaries-last-run` を使用する方法を示しています。

**AWS CLI**  
**各 Canary の最新の実行からの情報を表示するには**  
次の `describe-canaries-last-run` の例では、作成した各 Canary の最新の実行を返します。  

```
aws synthetics describe-canaries-last-run
```
出力:  

```
{
    "CanariesLastRun": [
        {
            "CanaryName": "demo_canary",
            "LastRun": {
                "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
                "Name": "demo_canary",
                "Status": {
                    "State": "PASSED",
                    "StateReason": "",
                    "StateReasonCode": ""
                },
                "Timeline": {
                    "Started": "2024-10-15T19:20:39.691000+05:30",
                    "Completed": "2024-10-15T19:20:58.211000+05:30"
                },
                "ArtifactS3Location": "cw-syn-results-123456789012-us-east-1/canary/us-east-1/demo_canary-abc-example1234/2024/10/15/13/50-39-690"
            }
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeCanariesLastRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/describe-canaries-last-run.html)」を参照してください。

### `describe-canaries`
<a name="synthetics_DescribeCanaries_cli_2_topic"></a>

次のコード例は、`describe-canaries` を使用する方法を示しています。

**AWS CLI**  
**アカウントの Canary を一覧表示するには**  
次の `describe-canaries` の例では、アカウントの Canary の詳細を一覧表示します。  

```
aws synthetics describe-canaries
```
出力:  

```
{
    "Canaries": [
        {
            "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
            "Name": "demo_canary",
            "Code": {
                "SourceLocationArn": "arn:aws:lambda:us-east-1:123456789012:layer:cwsyn-demo_canary-a1b2c3d4-5678-90ab-cdef-example11111b8:1",
                "Handler": "pageLoadBlueprint.handler"
            },
            "ExecutionRoleArn": "arn:aws:iam::123456789012:role/service-role/CloudWatchSyntheticsRole-demo_canary-a12-a123bc456789",
            "Schedule": {
                "Expression": "rate(5 minutes)",
                "DurationInSeconds": 0
            },
            "RunConfig": {
                "TimeoutInSeconds": 300,
                "MemoryInMB": 1000,
                "ActiveTracing": false
            },
            "SuccessRetentionPeriodInDays": 31,
            "FailureRetentionPeriodInDays": 31,
            "Status": {
            "State": "RUNNING"
            },
            "Timeline": {
                "Created": "2024-10-15T18:55:15.168000+05:30",
                "LastModified": "2024-10-15T18:55:40.540000+05:30",
                "LastStarted": "2024-10-15T18:55:40.540000+05:30"
            },
            "ArtifactS3Location": "cw-syn-results-123456789012-us-east-1/canary/us-east-1/demo_canary-a12-a123bc456789",
            "EngineArn": "arn:aws:lambda:us-east-1:123456789012:function:cwsyn-demo_canary-a1b2c3d4-5678-90ab-cdef-example111118:1",
            "RuntimeVersion": "syn-nodejs-puppeteer-9.1",
            "Tags": {
                "blueprint": "heartbeat"
            }
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeCanaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/describe-canaries.html)」を参照してください。

### `describe-runtime-versions`
<a name="synthetics_DescribeRuntimeVersions_cli_2_topic"></a>

次のコード例は、`describe-runtime-versions` を使用する方法を示しています。

**AWS CLI**  
**Synthetics Canary ランタイムバージョンのリストを返すには**  
次の `describe-runtime-versions` の例では、Synthetics Canary ランタイムバージョンのリストを返します。  

```
aws synthetics describe-runtime-versions
```
出力:  

```
{
    "RuntimeVersions": [
        {
            "VersionName": "syn-nodejs-puppeteer-9.1",
            "Description": "Security fixes and bug fix for date range error in har. Dependencies: Node JS 20.x, Puppeteer-core 22.12.1, Chromium 126.0.6478.126",
            "ReleaseDate": "2024-10-02T05:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-9.0",
            "Description": "Upgraded Chromium and Puppeteer. Dependencies: Node JS 20.x, Puppeteer-core 22.12.1, Chromium 126.0.6478.126",
            "ReleaseDate": "2024-07-22T05:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-8.0",
            "Description": "Upgraded Chromium and Puppeteer. Dependencies: Node JS 20.x, Puppeteer-core 22.10.0, Chromium 125.0.6422.112",
            "ReleaseDate": "2024-06-21T05:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-7.0",
            "Description": "Upgraded Chromium and Puppeteer. Dependencies: Node JS 18.x, Puppeteer-core 21.9.0, Chromium 121.0.6167.139",
            "ReleaseDate": "2024-03-08T05:30:00+05:30"
            },
        {
            "VersionName": "syn-nodejs-puppeteer-6.2",
            "Description": "Updated shared libraries for Chromium and added ephemeral storage monitoring. Dependencies: Node JS 18.x, Puppeteer-core 19.7.0, Chromium 111.0.5563.146",
            "ReleaseDate": "2024-02-02T05:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-6.1",
            "Description": "Added puppeteer launch retry. Dependencies: Node JS 18.x, Puppeteer-core 19.7.0, Chromium 111.0.5563.146",
            "ReleaseDate": "2023-11-13T05:30:00+05:30",
            "DeprecationDate": "2024-03-08T13:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-6.0",
            "Description": "Reduced X-Ray traces of a canary run, improved duration metric and upgraded to NodeJS 18.x. Dependencies: Node JS 18.x, Puppeteer-core 19.7.0, Chromium 111.0.5563.146",
            "ReleaseDate": "2023-09-15T05:30:00+05:30",
            "DeprecationDate": "2024-03-08T13:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-5.2",
            "Description": "Updated shared libraries for Chromium. Dependencies: Node JS 16.x, Puppeteer-core 19.7.0, Chromium 111.0.5563.146",
            "ReleaseDate": "2024-02-01T05:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-5.1",
            "Description": "Fixes a bug about missing request headers in har. Dependencies: Node JS 16.x, Puppeteer-core 19.7.0, Chromium 111.0.5563.146",
            "ReleaseDate": "2023-08-09T05:30:00+05:30",
            "DeprecationDate": "2024-03-08T13:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-5.0",
            "Description": "Upgraded Puppeteer and Chromium. Dependencies: Node JS 16.x, Puppeteer-core 19.7.0, Chromium 111.0.5563.146",
            "ReleaseDate": "2023-07-21T05:30:00+05:30",
            "DeprecationDate": "2024-03-08T13:30:00+05:30"
        },
        {
            "VersionName": "syn-nodejs-puppeteer-4.0",
            "Description": "Upgraded to NodeJS 16.x. Dependencies: Node JS 16.x, Puppeteer-core 5.5.0, Chromium 92.0.4512.0",
            "ReleaseDate": "2023-05-01T05:30:00+05:30",
            "DeprecationDate": "2024-03-08T13:30:00+05:30"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeRuntimeVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/describe-runtime-versions.html)」を参照してください。

### `disassociate-resource`
<a name="synthetics_DisassociateResource_cli_2_topic"></a>

次のコード例は、`disassociate-resource` を使用する方法を示しています。

**AWS CLI**  
**グループから Canary を削除するには**  
次の `disassociate-resource` の例では、`demo_group` という名前のグループから Canary を削除します。  

```
aws synthetics disassociate-resource \
    --group-identifier demo_group \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:canary:demo_canary
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DisassociateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/disassociate-resource.html)」を参照してください。

### `get-canary-runs`
<a name="synthetics_GetCanaryRuns_cli_2_topic"></a>

次のコード例は、`get-canary-runs` を使用する方法を示しています。

**AWS CLI**  
**指定した Canary の実行リストを取得するには**  
次の `get-canary-runs` の例では、`demo_canary` という名前の Canary の実行リストを取得します。  

```
aws synthetics get-canary-runs \
    --name demo_canary
```
出力:  

```
{
    "CanaryRuns": [
        {
            "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
            "Name": "demo_canary",
            "Status": {
                "State": "PASSED",
                "StateReason": "",
                "StateReasonCode": ""
            },
            "Timeline": {
                "Started": "2024-10-16T10:38:57.013000+05:30",
                "Completed": "2024-10-16T10:39:25.793000+05:30"
            },
            "ArtifactS3Location": "cw-syn-results-123456789012-us-east-1/canary/us-east-1/demo_canary-abc-example1234/2024/10/15/13/50-39-690"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetCanaryRuns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/get-canary-runs.html)」を参照してください。

### `get-canary`
<a name="synthetics_GetCanary_cli_2_topic"></a>

次のコード例は、`get-canary` を使用する方法を示しています。

**AWS CLI**  
**1 つの Canary に関する完全な情報を取得するには**  
次の `get-canary` の例では、`demo_canary` という名前の Canary に関する完全な情報を取得します。  

```
aws synthetics get-canary \
    --name demo_canary
```
出力:  

```
{
    "Canary": {
        "Id": "a1b2c3d4-5678-90ab-cdef-example11111",
        "Name": "demo_canary",
        "Code": {
            "SourceLocationArn": "arn:aws:lambda:us-east-1:123456789012:layer:cwsyn-demo_canary-a1b2c3d4-5678-90ab-cdef-example111118:1",
            "Handler": "pageLoadBlueprint.handler"
        },
        "ExecutionRoleArn": "arn:aws:iam::123456789012:role/demo_canary_role",
        "Schedule": {
            "Expression": "rate(10 minutes)",
            "DurationInSeconds": 0
        },
        "RunConfig": {
            "TimeoutInSeconds": 300,
            "MemoryInMB": 1000,
            "ActiveTracing": false
        },
        "SuccessRetentionPeriodInDays": 31,
        "FailureRetentionPeriodInDays": 31,
        "Status": {
            "State": "RUNNING"
        },
        "Timeline": {
            "Created": "2024-10-15T18:55:15.168000+05:30",
            "LastModified": "2024-10-15T18:55:40.540000+05:30",
            "LastStarted": "2024-10-15T18:55:40.540000+05:30"
        },
        "ArtifactS3Location": "cw-syn-results-123456789012-us-east-1/canary/us-east-1/demo_canary-a12-a123bc456789",
        "EngineArn": "arn:aws:lambda:us-east-1:123456789012:function:cwsyn-demo_canary-a1b2c3d4-5678-90ab-cdef-example111118:1",
        "RuntimeVersion": "syn-nodejs-puppeteer-9.1",
        "Tags": {
            "blueprint": "heartbeat"
        }
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetCanary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/get-canary.html)」を参照してください。

### `get-group`
<a name="synthetics_GetGroup_cli_2_topic"></a>

次のコード例は、`get-group` を使用する方法を示しています。

**AWS CLI**  
**1 つのグループに関する情報を返すには**  
次の `get-group` の例では、`demo_group` という名前のグループに関する情報を返します。  

```
aws synthetics get-group \
    --group-identifier demo_group
```
出力:  

```
{
    "Group": {
        "Id": "example123",
        "Name": "demo_group",
        "Arn": "arn:aws:synthetics:us-east-1:123456789012:group:example123",
        "Tags": {},
        "CreatedTime": "2024-10-15T14:47:23.811000+05:30",
        "LastModifiedTime": "2024-10-15T14:47:23.811000+05:30"
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/get-group.html)」を参照してください。

### `list-associated-groups`
<a name="synthetics_ListAssociatedGroups_cli_2_topic"></a>

次のコード例は、`list-associated-groups` を使用する方法を示しています。

**AWS CLI**  
**グループのリストを返すには**  
次の `list-associated-groups` の例では、`demo_canary` という名前の Canary に関連付けられているグループのリストを返します。  

```
aws synthetics list-associated-groups \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:canary:demo_canary
```
出力:  

```
{
    "Groups": [
        {
            "Id": "example123",
            "Name": "demo_group",
            "Arn": "arn:aws:synthetics:us-east-1:123456789012:group:example123"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListAssociatedGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/list-associated-groups.html)」を参照してください。

### `list-group-resources`
<a name="synthetics_ListGroupResources_cli_2_topic"></a>

次のコード例は、`list-group-resources` を使用する方法を示しています。

**AWS CLI**  
**指定したグループに関連付けられている Canary の ARN のリストを返すには**  
次の `list-group-resources` の例では、`demo_group` という名前のグループに関連付けられている Canary の ARN のリストを返します。  

```
aws synthetics list-group-resources \
    --group-identifier demo_group
```
出力:  

```
{
    "Resources": [
        "arn:aws:synthetics:us-east-1:123456789012:canary:demo_canary"
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/list-group-resources.html)」を参照してください。

### `list-groups`
<a name="synthetics_ListGroups_cli_2_topic"></a>

次のコード例は、`list-groups` を使用する方法を示しています。

**AWS CLI**  
**アカウントのすべてのグループのリストを返すには**  
次の `list-groups` の例では、アカウントのすべてのグループのリストを返します。  

```
aws synthetics list-groups
```
出力:  

```
{
    "Groups": [
        {
            "Id": "example123",
            "Name": "demo_group",
            "Arn": "arn:aws:synthetics:us-east-1:123456789012:group:example123"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/list-groups.html)」を参照してください。

### `list-tags-for-resource`
<a name="synthetics_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: Canary に関連付けられているタグを表示するには**  
次の `list-tags-for-resource` の例では、`demo_canary` という名前の Canary に関連付けられているタグを返します。  

```
aws synthetics list-tags-for-resource \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:canary:demo_canary
```
出力:  

```
{
    "Tags": {
        "blueprint": "heartbeat"
    }
}
```
**例 2: グループに関連付けられているタグを表示するには**  
次の `list-tags-for-resource` の例では、`demo_group` という名前のグループに関連付けられているタグを返します。  

```
aws  synthetics list-tags-for-resource \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:group:example123
```
出力:  

```
{
    "Tags": {
        "team": "Devops"
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/list-tags-for-resource.html)」を参照してください。

### `start-canary`
<a name="synthetics_StartCanary_cli_2_topic"></a>

次のコード例は、`start-canary` を使用する方法を示しています。

**AWS CLI**  
**Canary を実行するには**  
次の `start-canary` の例では、`demo_canary` という名前の Canary を実行します。  

```
aws synthetics start-canary \
    --name demo_canary
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartCanary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/start-canary.html)」を参照してください。

### `stop-canary`
<a name="synthetics_StopCanary_cli_2_topic"></a>

次のコード例は、`stop-canary` を使用する方法を示しています。

**AWS CLI**  
**Canary を停止するには**  
次の `stop-canary` の例では、`demo_canary` という名前の Canary を停止します。  

```
aws synthetics stop-canary \
    --name demo_canary
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopCanary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/stop-canary.html)」を参照してください。

### `tag-resource`
<a name="synthetics_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: Canary にタグを割り当てるには**  
次の `tag-resource` の例では、`demo_canary` という名前の Canary にタグを割り当てます。  

```
aws synthetics tag-resource \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:canary:demo_canary \
    --tags blueprint=heartbeat
```
このコマンドでは何も出力されません。  
**例 2: グループにタグを割り当てるには**  
次の `tag-resource` の例では、`demo_group` という名前のグループにタグを割り当てます。  

```
aws synthetics tag-resource \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:group:example123 \
    --tags team=Devops
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="synthetics_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: Canary からタグを削除するには**  
次の `untag-resource` の例では、`demo_canary` という名前の Canary からタグを削除します。  

```
aws synthetics untag-resource \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:canary:demo_canary \
    --tag-keys blueprint
```
このコマンドでは何も出力されません。  
**例 2: グループからタグを削除するには**  
次の `untag-resource` の例では、`demo_group` という名前のグループからタグを削除します。  

```
aws synthetics untag-resource \
    --resource-arn arn:aws:synthetics:us-east-1:123456789012:group:example123 \
    --tag-keys team
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/untag-resource.html)」を参照してください。

### `update-canary`
<a name="synthetics_UpdateCanary_cli_2_topic"></a>

次のコード例は、`update-canary` を使用する方法を示しています。

**AWS CLI**  
**Canary を更新するには**  
次の `update-canary` の例では、`demo_canary` という名前の Canary の設定を更新します。  

```
aws synthetics update-canary \
    --name demo_canary \
    --schedule Expression="rate(15 minutes)"
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[合成モニタリング (Canary)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[UpdateCanary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/synthetics/update-canary.html)」を参照してください。

# を使用した CodeArtifact の例 AWS CLI
<a name="cli_2_codeartifact_code_examples"></a>

次のコード例は、CodeArtifact AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-external-connection`
<a name="codeartifact_AssociateExternalConnection_cli_2_topic"></a>

次のコード例は、`associate-external-connection` を使用する方法を示しています。

**AWS CLI**  
**リポジトリに外部接続を追加するには**  
次の `associate-external-connection` の例では、test-repo という名前のリポジトリに npmjs.com への外部接続を追加します。  

```
aws codeartifact associate-external-connection \
    --repository test-repo \
    --domain test-domain \
    --external-connection public:npmjs
```
出力:  

```
{
    "repository": {
        "name": "test-repo",
        "administratorAccount": "111122223333",
        "domainName": "test-domain",
        "domainOwner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo",
        "upstreams": [],
        "externalConnections": [
            {
                "externalConnectionName": "public:npmjs",
                "packageFormat": "npm",
                "status": "AVAILABLE"
            }
        ]
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Add an external connection](https://docs.aws.amazon.com/codeartifact/latest/ug/external-connection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateExternalConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/associate-external-connection.html)」を参照してください。

### `copy-package-versions`
<a name="codeartifact_CopyPackageVersions_cli_2_topic"></a>

次のコード例は、`copy-package-versions` を使用する方法を示しています。

**AWS CLI**  
**あるリポジトリから別のリポジトリにパッケージバージョンをコピーするには**  
次の `copy-package-versions` では、test-package という名前のパッケージのバージョン 4.0.0 および 5.0.0 を my-repo から test-repo に移動しています。  

```
aws codeartifact copy-package-versions \
    --domain test-domain \
    --source-repository my-repo \
    --destination-repository test-repo \
    --format npm \
    --package test-package \
    --versions '["4.0.0", "5.0.0"]'
```
出力:  

```
{
    "format": "npm",
    "package": "test-package",
    "versions": [
        {
        "version": "5.0.0",
        "revision": "REVISION-1-SAMPLE-6C81EFF7DA55CC",
        "status": "Published"
        },
        {
        "version": "4.0.0",
        "revision": "REVISION-2-SAMPLE-55C752BEE772FC",
        "status": "Published"
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Copy packages between repositories](https://docs.aws.amazon.com/codeartifact/latest/ug/copy-package.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyPackageVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/copy-package-versions.html)」を参照してください。

### `create-domain`
<a name="codeartifact_CreateDomain_cli_2_topic"></a>

次のコード例は、`create-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインを作成するには**  
次の `create-domain` の例では、test-domain という名前のドメインを作成します。  

```
aws codeartifact create-domain \
    --domain test-domain
```
出力:  

```
{
    "domain": {
        "name": "test-domain",
        "owner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:domain/test-domain",
        "status": "Active",
        "createdTime": "2020-10-20T13:16:48.559000-04:00",
        "encryptionKey": "arn:aws:kms:us-west-2:111122223333:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "repositoryCount": 0,
        "assetSizeBytes": 0
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Create a domain](https://docs.aws.amazon.com/codeartifact/latest/ug/domain-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/create-domain.html)」を参照してください。

### `create-repository`
<a name="codeartifact_CreateRepository_cli_2_topic"></a>

次のコード例は、`create-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリを作成するには**  
次の `create-repository` の例では、test-domain という名前のドメイン内に test-repo という名前のリポジトリを作成します。  

```
aws codeartifact create-repository \
    --domain test-domain \
    --domain-owner 111122223333 \
    --repository test-repo \
    --description "This is a test repository."
```
出力:  

```
{
    "repository": {
        "name": "test-repo",
        "administratorAccount": "111122223333",
        "domainName": "test-domain",
        "domainOwner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo",
        "description": "This is a test repository.",
        "upstreams": [],
        "externalConnections": []
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Create a domain](https://docs.aws.amazon.com/codeartifact/latest/ug/create-repo.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/create-repository.html)」を参照してください。

### `delete-domain-permissions-policy`
<a name="codeartifact_DeleteDomainPermissionsPolicy_cli_2_topic"></a>

次のコード例は、`delete-domain-permissions-policy` を使用する方法を示しています。

**AWS CLI**  
**ドメインからアクセス許可ポリシードキュメントを削除するには**  
次の `delete-domain-permissions-policy` の例では、test-domain という名前のドメインからアクセス許可ポリシーを削除します。  

```
aws codeartifact delete-domain-permissions-policy \
    --domain test-domain
```
出力:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "BasicDomainPolicy",
            "Action": [
                "codeartifact:GetDomainPermissionsPolicy",
                "codeartifact:ListRepositoriesInDomain",
                "codeartifact:GetAuthorizationToken",
                "codeartifact:CreateRepository"
            ],
            "Effect": "Allow",
            "Resource": "*",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            }
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Delete a domain policy](https://docs.aws.amazon.com/codeartifact/latest/ug/domain-policies.html#deleting-a-domain-policy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDomainPermissionsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/delete-domain-permissions-policy.html)」を参照してください。

### `delete-domain`
<a name="codeartifact_DeleteDomain_cli_2_topic"></a>

次のコード例は、`delete-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインを削除するには**  
次の `delete-domain` の例では、`test-domain` という名前のドメインを削除します。  

```
aws codeartifact delete-domain \
    --domain test-domain
```
出力:  

```
{
    "domain": {
        "name": "test-domain",
        "owner": "417498243647",
        "arn": "arn:aws:codeartifact:us-west-2:417498243647:domain/test-domain",
        "status": "Deleted",
        "createdTime": "2020-10-20T13:16:48.559000-04:00",
        "encryptionKey": "arn:aws:kms:us-west-2:417498243647:key/c9fe2447-0795-4fda-afbe-8464574ae162",
        "repositoryCount": 0,
        "assetSizeBytes": 0
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Delete a domain](https://docs.aws.amazon.com/codeartifact/latest/ug/delete-domain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/delete-domain.html)」を参照してください。

### `delete-package-versions`
<a name="codeartifact_DeletePackageVersions_cli_2_topic"></a>

次のコード例は、`delete-package-versions` を使用する方法を示しています。

**AWS CLI**  
**パッケージのバージョンを削除するには**  
次の `delete-package-versions` の例では、test-package という名前のパッケージのバージョン 4.0.0 を削除します。  

```
aws codeartifact delete-package-versions \
    --domain test-domain \
    --repo test-repo \
    --format npm \
    --package test-package \
    --versions 4.0.0
```
出力:  

```
{
    "successfulVersions": {
        "4.0.0": {
            "revision": "Ciqe5/9yicvkJT13b5/LdLpCyE6fqA7poa9qp+FilPs=",
            "status": "Deleted"
        }
    },
    "failedVersions": {}
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Delete a package version](https://docs.aws.amazon.com/codeartifact/latest/ug/delete-package.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePackageVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/delete-package-versions.html)」を参照してください。

### `delete-repository-permissions-policy`
<a name="codeartifact_DeleteRepositoryPermissionsPolicy_cli_2_topic"></a>

次のコード例は、`delete-repository-permissions-policy` を使用する方法を示しています。

**AWS CLI**  
**リポジトリからアクセス許可ポリシーを削除するには**  
次の `delete-repository-permissions-policy` の例では、test-repo という名前のリポジトリからアクセス許可ポリシーを削除します。  

```
aws codeartifact delete-repository-permissions-policy \
    --domain test-domain \
    --repository test-repo
```
出力:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            },
            "Action": [
                "codeartifact:DescribePackageVersion",
                "codeartifact:DescribeRepository",
                "codeartifact:GetPackageVersionReadme",
                "codeartifact:GetRepositoryEndpoint",
                "codeartifact:ListPackages",
                "codeartifact:ListPackageVersions",
                "codeartifact:ListPackageVersionAssets",
                "codeartifact:ListPackageVersionDependencies",
                "codeartifact:ReadFromRepository"
            ],
            "Resource": "*"
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Delete a policy](https://docs.aws.amazon.com/codeartifact/latest/ug/repo-policies.html#deleting-a-policy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRepositoryPermissionsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/delete-repository-permissions-policy.html)」を参照してください。

### `delete-repository`
<a name="codeartifact_DeleteRepository_cli_2_topic"></a>

次のコード例は、`delete-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリを削除するには**  
次の `delete-repository` の例では、`test-domain` という名前のドメイン内にある `test-repo` という名前のリポジトリを削除します。  

```
aws codeartifact delete-repository \
    --domain test-domain \
    --repository test-repo
```
出力:  

```
{
    "repository": {
        "name": "test-repo",
        "administratorAccount": "111122223333",
        "domainName": "test-domain",
        "domainOwner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo",
        "description": "This is a test repository",
        "upstreams": [],
        "externalConnections": []
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Delete a repository](https://docs.aws.amazon.com/codeartifact/latest/ug/delete-repo.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/delete-repository.html)」を参照してください。

### `describe-domain`
<a name="codeartifact_DescribeDomain_cli_2_topic"></a>

次のコード例は、`describe-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインに関する情報を取得するには**  
次の `describe-domain` の例では、test-domain という名前のドメインに対して DomainDescription オブジェクトを返します。  

```
aws codeartifact describe-domain \
    --domain test-domain
```
出力:  

```
{
    "domain": {
        "name": "test-domain",
        "owner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:domain/test-domain",
        "status": "Active",
        "createdTime": "2020-10-20T13:16:48.559000-04:00",
        "encryptionKey": "arn:aws:kms:us-west-2:111122223333:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "repositoryCount": 2,
        "assetSizeBytes": 0,
        "s3BucketArn": "arn:aws:s3:::assets-111122223333-us-west-2"
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Domain overview](https://docs.aws.amazon.com/codeartifact/latest/ug/domain-overview.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/describe-domain.html)」を参照してください。

### `describe-repository`
<a name="codeartifact_DescribeRepository_cli_2_topic"></a>

次のコード例は、`describe-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリに関する情報を取得するには**  
次の `describe-repository` の例では、test-repo という名前のリポジトリに対して RepositoryDescription オブジェクトを返します。  

```
aws codeartifact describe-repository \
    --domain test-domain \
    --repository test-repo
```
出力:  

```
{
    "repository": {
        "name": "test-repo",
        "administratorAccount": "111122223333",
        "domainName": "test-domain",
        "domainOwner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo",
        "description": "This is a test repository.",
        "upstreams": [],
        "externalConnections": []
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Create a domain](https://docs.aws.amazon.com/codeartifact/latest/ug/create-repo.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/describe-repository.html)」を参照してください。

### `disassociate-external-connection`
<a name="codeartifact_DisassociateExternalConnection_cli_2_topic"></a>

次のコード例は、`disassociate-external-connection` を使用する方法を示しています。

**AWS CLI**  
**リポジトリから外部接続を削除するには**  
次の `disassociate-external-connection` の例では、test-repo という名前のリポジトリから npmjs.com への外部接続を削除します。  

```
aws codeartifact disassociate-external-connection \
    --repository test-repo \
    --domain test-domain \
    --external-connection public:npmjs
```
出力:  

```
{
    "repository": {
        "name": "test-repo",
        "administratorAccount": "111122223333",
        "domainName": "test-domain",
        "domainOwner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo",
        "upstreams": [],
        "externalConnections": []
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Remove an external connection](https://docs.aws.amazon.com/codeartifact/latest/ug/external-connection.html#removing-an-external-connection)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateExternalConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/disassociate-external-connection.html)」を参照してください。

### `dispose-package-versions`
<a name="codeartifact_DisposePackageVersions_cli_2_topic"></a>

次のコード例は、`dispose-package-versions` を使用する方法を示しています。

**AWS CLI**  
**パッケージバージョンのアセットを削除し、そのステータスを [廃棄] に設定するには**  
次の `dispose-package-versions` の例では、test-package のバージョン 4.0.0 のアセットを削除し、そのステータスを [廃棄] に設定します。  

```
aws codeartifact dispose-package-versions \
    --domain test-domain \
    --repo test-repo \
    --format npm \
    --package test-package \
    --versions 4.0.0
```
出力:  

```
{
    "successfulVersions": {
        "4.0.0": {
            "revision": "Ciqe5/9yicvkJT13b5/LdLpCyE6fqA7poa9qp+FilPs=",
            "status": "Disposed"
        }
    },
    "failedVersions": {}
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Working with packages in CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/packages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisposePackageVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/dispose-package-versions.html)」を参照してください。

### `get-authorization-token`
<a name="codeartifact_GetAuthorizationToken_cli_2_topic"></a>

次のコード例は、`get-authorization-token` を使用する方法を示しています。

**AWS CLI**  
**認証トークンを取得するには**  
次の `get-authorization-token` の例では、CodeArtifact 認証トークンを取得します。  

```
aws codeartifact get-authorization-token \
    --domain test-domain \
    --query authorizationToken \
    --output text
```
出力:  

```
This command will return the authorization token. You can store the output in an environment variable when calling the command.
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Configure pip without the login command](https://docs.aws.amazon.com/codeartifact/latest/ug/python-configure-without-pip.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthorizationToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/get-authorization-token.html)」を参照してください。

### `get-domain-permissions-policy`
<a name="codeartifact_GetDomainPermissionsPolicy_cli_2_topic"></a>

次のコード例は、`get-domain-permissions-policy` を使用する方法を示しています。

**AWS CLI**  
**ドメインのアクセス許可ポリシードキュメントを取得するには**  
次の `get-domain-permissions-policy` の例では、test-domain という名前のドメインにアタッチされたアクセス許可ポリシーを取得します。  

```
aws codeartifact get-domain-permissions-policy \
    --domain test-domain
```
出力:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "BasicDomainPolicy",
            "Action": [
                "codeartifact:GetDomainPermissionsPolicy",
                "codeartifact:ListRepositoriesInDomain",
                "codeartifact:GetAuthorizationToken",
                "codeartifact:CreateRepository"
            ],
            "Effect": "Allow",
            "Resource": "*",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            }
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Read a domain policy](https://docs.aws.amazon.com/codeartifact/latest/ug/domain-policies.html#reading-a-domain-policy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomainPermissionsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/get-domain-permissions-policy.html)」を参照してください。

### `get-package-version-asset`
<a name="codeartifact_GetPackageVersionAsset_cli_2_topic"></a>

次のコード例は、`get-package-version-asset` を使用する方法を示しています。

**AWS CLI**  
**パッケージバージョンからアセットを取得するには**  
次の `get-package-version-asset` の例では、test-package という名前の npm パッケージのバージョン 4.0.0 の `package.tgz` アセットを取得します。  

```
aws codeartifact get-package-version-asset \
    --domain test-domain \
    --repository test-repo \
    --format npm \
    --package test-package \
    --package-version 4.0.0 \
    --asset 'package.tgz' \
    outfileName
```
出力:  

```
The output for this command will also store the raw asset in the file provided in place of outfileName.

{
    "assetName": "package.tgz",
    "packageVersion": "4.0.0",
    "packageVersionRevision": "Ciqe5/9yicvkJT13b5/LdLpCyE6fqA7poa9qp+FilPs="
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[List package version assets](https://docs.aws.amazon.com/codeartifact/latest/ug/list-assets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPackageVersionAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/get-package-version-asset.html)」を参照してください。

### `get-package-version-readme`
<a name="codeartifact_GetPackageVersionReadme_cli_2_topic"></a>

次のコード例は、`get-package-version-readme` を使用する方法を示しています。

**AWS CLI**  
**パッケージバージョンの readme ファイルを取得するには**  
次の `get-package-version-readme` の例では、test-package という名前の npm パッケージのバージョン 4.0.0 の readme ファイルを取得します。  

```
aws codeartifact get-package-version-readme \
    --domain test-domain \
    --repo test-repo \
    --format npm \
    --package test-package \
    --package-version 4.0.0
```
出力:  

```
{
    "format": "npm",
    "package": "test-package",
    "version": "4.0.0",
    "readme": "<div align=\"center\">\n   <a href=\https://github.com/test-package/testpack\"> ... more content ... \n",
    "versionRevision": "Ciqe5/9yicvkJT13b5/LdLpCyE6fqA7poa9qp+FilPs="
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[View package version readme file](https://docs.aws.amazon.com/codeartifact/latest/ug/describe-package-version.html#view-package-readme)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPackageVersionReadme](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/get-package-version-readme.html)」を参照してください。

### `get-repository-endpoint`
<a name="codeartifact_GetRepositoryEndpoint_cli_2_topic"></a>

次のコード例は、`get-repository-endpoint` を使用する方法を示しています。

**AWS CLI**  
**リポジトリの URL エンドポイントを取得するには**  
次の `get-repository-endpoint` の例では、test-repo リポジトリに対して npm エンドポイントを返します。  

```
aws codeartifact get-repository-endpoint \
    --domain test-domain \
    --repository test-repo \
    --format npm
```
出力:  

```
{
    "repositoryEndpoint": "https://test-domain-111122223333.d.codeartifact.us-west-2.amazonaws.com/npm/test-repo/"
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Connect to a repository](https://docs.aws.amazon.com/codeartifact/latest/ug/connect-repo.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRepositoryEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/get-repository-endpoint.html)」を参照してください。

### `get-repository-permissions-policy`
<a name="codeartifact_GetRepositoryPermissionsPolicy_cli_2_topic"></a>

次のコード例は、`get-repository-permissions-policy` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのアクセス許可ポリシードキュメントを取得するには**  
次の `get-repository-permissions-policy` の例では、test-repo という名前のリポジトリにアタッチされたアクセス許可ポリシーを取得します。  

```
aws codeartifact get-repository-permissions-policy \
    --domain test-domain \
    --repository test-repo
```
出力:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:root"
            },
            "Action": [
                "codeartifact:DescribePackageVersion",
                "codeartifact:DescribeRepository",
                "codeartifact:GetPackageVersionReadme",
                "codeartifact:GetRepositoryEndpoint",
                "codeartifact:ListPackages",
                "codeartifact:ListPackageVersions",
                "codeartifact:ListPackageVersionAssets",
                "codeartifact:ListPackageVersionDependencies",
                "codeartifact:ReadFromRepository"
            ],
            "Resource": "*"
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Read a policy](https://docs.aws.amazon.com/codeartifact/latest/ug/repo-policies.html#setting-a-policy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRepositoryPermissionsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/get-repository-permissions-policy.html)」を参照してください。

### `list-domains`
<a name="codeartifact_ListDomains_cli_2_topic"></a>

次のコード例は、`list-domains` を使用する方法を示しています。

**AWS CLI**  
**ドメインを一覧表示するには**  
次の の`list-domains`例では、呼び出しを行う AWS アカウントが所有するすべてのドメインの概要を返します。  

```
aws codeartifact list-domains
```
出力:  

```
{
    "domains": [
        {
            "name": "my-domain",
            "owner": "111122223333",
            "status": "Active",
            "encryptionKey": "arn:aws:kms:us-west-2:111122223333:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        },
        {
            "name": "test-domain",
            "owner": "111122223333",
            "status": "Active",
            "encryptionKey": "arn:aws:kms:us-west-2:111122223333:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Working with domains in CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/domains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/list-domains.html)」を参照してください。

### `list-package-version-assets`
<a name="codeartifact_ListPackageVersionAssets_cli_2_topic"></a>

次のコード例は、`list-package-version-assets` を使用する方法を示しています。

**AWS CLI**  
**パッケージバージョンのアセットを表示するには**  
次の `list-package-version-assets` の例では、test-package という名前の npm パッケージのバージョン 4.0.0 のアセットを取得します。  

```
aws codeartifact list-package-version-assets \
    --domain test-domain \
    --repo test-repo \
    --format npm \
    --package test-package \
    --package-version 4.0.0
```
出力:  

```
{
    "format": "npm",
    "package": "test-package",
    "version": "4.0.0",
    "versionRevision": "Ciqe5/9yicvkJT13b5/LdLpCyE6fqA7poa9qp+FilPs=",
    "assets": [
        {
            "name": "package.tgz",
            "size": 316680,
            "hashes": {
                "MD5": "60078ec6d9e76b89fb55c860832742b2",
                "SHA-1": "b44a9b6297bcb698f1c51a3545a2b3b368d59c52",
                "SHA-256": "d2aa8c6afc3c8591765785a37d1c5acae482a8eb3ab9729ed28922692454f2e2",
                "SHA-512": "3e585d15c8a594e20d7de57b362ea81754c011acb2641a19f1b72c8531ea39825896bab344ae616a0a5a824cb9a381df0b3cddd534645cf305aba70a93dac698"
            }
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[List package version assets](https://docs.aws.amazon.com/codeartifact/latest/ug/list-assets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPackageVersionAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/list-package-version-assets.html)」を参照してください。

### `list-package-version-dependencies`
<a name="codeartifact_ListPackageVersionDependencies_cli_2_topic"></a>

次のコード例は、`list-package-version-dependencies` を使用する方法を示しています。

**AWS CLI**  
**パッケージバージョンの依存関係を表示するには**  
次の `list-package-version-dependencies` 例では、test-package という名前の npm パッケージのバージョン 4.0.0 の依存関係を取得します。  

```
aws codeartifact list-package-version-dependencies \
    --domain test-domain \
    --repo test-repo \
    --format npm \
    --package test-package \
    --package-version 4.0.0
```
出力:  

```
{
    "format": "npm",
    "package": "test-package",
    "version": "4.0.0",
    "versionRevision": "Ciqe5/9yicvkJT13b5/LdLpCyE6fqA7poa9qp+FilPs=",
    "dependencies": [
        {
            "namespace": "testns",
            "package": "testdep1",
            "dependencyType": "regular",
            "versionRequirement": "1.8.5"
        },
        {
            "namespace": "testns",
            "package": "testdep2",
            "dependencyType": "regular",
            "versionRequirement": "1.8.5"
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[View and update package version details and dependencies](https://docs.aws.amazon.com/codeartifact/latest/ug/describe-package-version.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPackageVersionDependencies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/list-package-version-dependencies.html)」を参照してください。

### `list-package-versions`
<a name="codeartifact_ListPackageVersions_cli_2_topic"></a>

次のコード例は、`list-package-versions` を使用する方法を示しています。

**AWS CLI**  
**パッケージのパッケージバージョンを一覧表示するには**  
次の `list-package-versions` の例では、`kind-of` という名前のパッケージに対してパッケージバージョンのリストを返します。  

```
aws codeartifact list-package-versions \
    --package kind-of \
    --domain test-domain \
    --repository test-repo \
    --format npm
```
出力:  

```
{
    "defaultDisplayVersion": "1.0.1",
    "format": "npm",
    "package": "kind-of",
    "versions": [
        {
            "version": "1.0.1",
            "revision": "REVISION-SAMPLE-1-C7F4S5E9B772FC",
            "status": "Published"
        },
        {
            "version": "1.0.0",
            "revision": "REVISION-SAMPLE-2-C752BEEF6D2CFC",
            "status": "Published"
        },
        {
            "version": "0.1.2",
            "revision": "REVISION-SAMPLE-3-654S65A5C5E1FC",
            "status": "Published"
        },
        {
            "version": "0.1.1",
            "revision": "REVISION-SAMPLE-1-C7F4S5E9B772FC"",
            "status": "Published"
        },
        {
            "version": "0.1.0",
            "revision": "REVISION-SAMPLE-4-AF669139B772FC",
            "status": "Published"
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[List package versions](https://docs.aws.amazon.com/codeartifact/latest/ug/list-packages-versions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPackageVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/list-package-versions.html)」を参照してください。

### `list-packages`
<a name="codeartifact_ListPackages_cli_2_topic"></a>

次のコード例は、`list-packages` を使用する方法を示しています。

**AWS CLI**  
**リポジトリ内のパッケージを一覧表示するには**  
次の `list-packages` の例では、`test-domain` という名前のドメインにある `test-repo` という名前のリポジトリのパッケージを一覧表示します。  

```
aws codeartifact list-packages \
    --domain test-domain \
    --repository test-repo
```
出力:  

```
{
    "packages": [
        {
            "format": "npm",
            "package": "lodash"
        }
        {
            "format": "python",
            "package": "test-package"
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[List package names](https://docs.aws.amazon.com/codeartifact/latest/ug/list-packages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPackages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/list-packages.html)」を参照してください。

### `list-repositories-in-domain`
<a name="codeartifact_ListRepositoriesInDomain_cli_2_topic"></a>

次のコード例は、`list-repositories-in-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインのリポジトリを一覧表示するには**  
次の `list-repositories-in-domain` の例では、test-domain ドメイン内のすべてのリポジトリの概要を返します。  

```
aws codeartifact list-repositories-in-domain \
    --domain test-domain
```
出力:  

```
{
    "repositories": [
        {
            "name": "test-repo",
            "administratorAccount": "111122223333",
            "domainName": "test-domain",
            "domainOwner": "111122223333",
            "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo",
            "description": "This is a test repository."
        },
        {
            "name": "test-repo2",
            "administratorAccount": "111122223333",
            "domainName": "test-domain",
            "domainOwner": "111122223333",
            "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo2",
            "description": "This is a test repository."
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[List repositories](https://docs.aws.amazon.com/codeartifact/latest/ug/list-repos.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRepositoriesInDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/list-repositories-in-domain.html)」を参照してください。

### `list-repositories`
<a name="codeartifact_ListRepositories_cli_2_topic"></a>

次のコード例は、`list-repositories` を使用する方法を示しています。

**AWS CLI**  
**リポジトリを一覧表示するには**  
次の の`list-repositories`例では、呼び出しを行う AWS アカウントが所有するドメイン内のすべてのリポジトリの概要を返します。  

```
aws codeartifact list-repositories
```
出力:  

```
{
    "repositories": [
        {
            "name": "npm-store",
            "administratorAccount": "111122223333",
            "domainName": "my-domain",
            "domainOwner": "111122223333",
            "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/my-domain/npm-store",
            "description": "Provides npm artifacts from npm, Inc."
        },
        {
            "name": "target-repo",
            "administratorAccount": "111122223333",
            "domainName": "my-domain",
            "domainOwner": "111122223333",
            "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/my-domain/target-repo",
            "description": "test target repo"
        },
        {
            "name": "test-repo2",
            "administratorAccount": "111122223333",
            "domainName": "test-domain",
            "domainOwner": "111122223333",
            "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo2",
            "description": "This is a test repository."
        }
    ]
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[List repositories](https://docs.aws.amazon.com/codeartifact/latest/ug/list-repos.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRepositories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/list-repositories.html)」を参照してください。

### `login`
<a name="codeartifact_Login_cli_2_topic"></a>

次のコード例は、`login` を使用する方法を示しています。

**AWS CLI**  
**ログインコマンドを使用してリポジトリへの認証を設定するには**  
次の `login` の例では、test-domain という名前のドメインにある test-repo という名前のリポジトリを使用して npm パッケージマネージャーを設定します。  

```
aws codeartifact login \
    --domain test-domain \
    --repository test-repo \
    --tool npm
```
出力:  

```
Successfully configured npm to use AWS CodeArtifact repository https://test-domain-111122223333.d.codeartifact.us-west-2.amazonaws.com/npm/test-repo/
Login expires in 12 hours at 2020-11-12 01:53:16-05:00
```
詳細については、*AWS 「 CodeArtifact ユーザーガイド*[」の「 CLI AWS の開始方法](https://docs.aws.amazon.com/codeartifact/latest/ug/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Login](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/login.html)」を参照してください。

### `put-domain-permissions-policy`
<a name="codeartifact_PutDomainPermissionsPolicy_cli_2_topic"></a>

次のコード例は、`put-domain-permissions-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセス許可ポリシーをドメインにアタッチするには**  
次の `put-domain-permissions-policy` の例では、policy.json ファイルで定義されているアクセス許可ポリシーを test-domain という名前のドメインにアタッチします。  

```
aws codeartifact put-domain-permissions-policy \
    --domain test-domain \
    --policy-document file://PATH/TO/policy.json
```
出力:  

```
{
    "policy": {
        "resourceArn": "arn:aws:codeartifact:region-id:111122223333:domain/test-domain",
        "document": "{ ...policy document content...}",
        "revision": "MQlyyTQRASRU3HB58gBtSDHXG7Q3hvxxxxxxx="
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Set a domain policy](https://docs.aws.amazon.com/codeartifact/latest/ug/domain-policies.html#set-domain-policy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutDomainPermissionsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/put-domain-permissions-policy.html)」を参照してください。

### `put-repository-permissions-policy`
<a name="codeartifact_PutRepositoryPermissionsPolicy_cli_2_topic"></a>

次のコード例は、`put-repository-permissions-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセス許可ポリシーをリポジトリにアタッチするには**  
次の `put-repository-permissions-policy` の例では、policy.json ファイルで定義されているアクセス許可ポリシーを test-repo という名前のリポジトリにアタッチします。  

```
aws codeartifact put-repository-permissions-policy \
    --domain test-domain \
    --repository test-repo \
    --policy-document file://PATH/TO/policy.json
```
出力:  

```
{
    "policy": {
        "resourceArn": "arn:aws:codeartifact:region-id:111122223333:repository/test-domain/test-repo",
        "document": "{ ...policy document content...}",
        "revision": "MQlyyTQRASRU3HB58gBtSDHXG7Q3hvxxxxxxx="
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Set a policy](https://docs.aws.amazon.com/codeartifact/latest/ug/repo-policies.html#setting-a-policy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRepositoryPermissionsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/put-repository-permissions-policy.html)」を参照してください。

### `update-package-versions-status`
<a name="codeartifact_UpdatePackageVersionsStatus_cli_2_topic"></a>

次のコード例は、`update-package-versions-status` を使用する方法を示しています。

**AWS CLI**  
**パッケージバージョンのステータスを更新するには**  
次の `update-package-versions-status` の例では、test-package パッケージのバージョン 4.0.0 のステータスを [アーカイブ済み] に更新します。  

```
aws codeartifact update-package-versions-status \
    --domain test-domain \
    --repo test-repo \
    --format npm \
    --package test-package \
    --versions 4.0.0 \
    --target-status Archived
```
出力:  

```
{
    "successfulVersions": {
        "4.0.0": {
            "revision": "Ciqe5/9yicvkJT13b5/LdLpCyE6fqA7poa9qp+FilPs=",
            "status": "Archived"
        }
    },
    "failedVersions": {}
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[Update package version status](https://docs.aws.amazon.com/codeartifact/latest/ug/describe-package-version.html#update-package-version-status)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePackageVersionsStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/update-package-versions-status.html)」を参照してください。

### `update-repository`
<a name="codeartifact_UpdateRepository_cli_2_topic"></a>

次のコード例は、`update-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリを更新するには**  
次の `update-repository` の例では、test-domain という名前のドメインの test-repo という名前のリポジトリの説明を「これは更新された説明です」に更新します。  

```
aws codeartifact update-repository \
    --domain test-domain \
    --repository test-repo \
    --description "this is an updated description"
```
出力:  

```
{
    "repository": {
        "name": "test-repo",
        "administratorAccount": "111122223333",
        "domainName": "test-domain",
        "domainOwner": "111122223333",
        "arn": "arn:aws:codeartifact:us-west-2:111122223333:repository/test-domain/test-repo",
        "description": "this is an updated description",
        "upstreams": [],
        "externalConnections": []
    }
}
```
詳細については、「*AWS CodeArtifact ユーザーガイド*」の「[View or modify a repository configuration](https://docs.aws.amazon.com/codeartifact/latest/ug/config-repos.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeartifact/update-repository.html)」を参照してください。

# を使用した CodeBuild の例 AWS CLI
<a name="cli_2_codebuild_code_examples"></a>

次のコード例は、CodeBuild AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-delete-builds`
<a name="codebuild_BatchDeleteBuilds_cli_2_topic"></a>

次の例は、`batch-delete-builds` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でビルドを削除するには。**  
次の `batch-delete-builds` の例では、指定した ID を持つ CodeBuild のビルドを削除します。  

```
aws codebuild batch-delete-builds --ids my-build-project-one:a1b2c3d4-5678-9012-abcd-11111EXAMPLE my-build-project-two:a1b2c3d4-5678-9012-abcd-22222EXAMPLE
```
出力:  

```
{
    "buildsNotDeleted": [
        {
            "id": "arn:aws:codebuild:us-west-2:123456789012:build/my-build-project-one:a1b2c3d4-5678-9012-abcd-11111EXAMPLE",
            "statusCode": "BUILD_IN_PROGRESS"
        }
    ],
    "buildsDeleted": [
        "arn:aws:codebuild:us-west-2:123456789012:build/my-build-project-two:a1b2c3d4-5678-9012-abcd-22222EXAMPLE"
    ]
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*」の[「Delete Builds (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/delete-builds.html#delete-builds-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDeleteBuilds](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/batch-delete-builds.html)」を参照してください。

### `batch-get-build-batches`
<a name="codebuild_BatchGetBuildBatches_cli_2_topic"></a>

次の例は、`batch-get-build-batches` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild のビルドの詳細を表示するには。**  
次の `batch-get-build-batches` の例では、指定した ID を持つ CodeBuild のビルドバッチの情報を取得します。  

```
aws codebuild batch-get-build-batches \
    --ids codebuild-demo-project:e9c4f4df-3f43-41d2-ab3a-60fe2EXAMPLE
```
出力:  

```
{
    "buildBatches": [
        {
            "id": "codebuild-demo-project:e9c4f4df-3f43-41d2-ab3a-60fe2EXAMPLE",
            "arn": "arn:aws:codebuild:us-west-2:123456789012:build-batch/codebuild-demo-project:e9c4f4df-3f43-41d2-ab3a-60fe2EXAMPLE",
            "startTime": "2020-11-03T21:52:20.775000+00:00",
            "endTime": "2020-11-03T21:56:59.784000+00:00",
            "currentPhase": "SUCCEEDED",
            "buildBatchStatus": "SUCCEEDED",
            "resolvedSourceVersion": "0a6546f68309560d08a310daac92314c4d378f6b",
            "projectName": "codebuild-demo-project",
            "phases": [
                {
                    "phaseType": "SUBMITTED",
                    "phaseStatus": "SUCCEEDED",
                    "startTime": "2020-11-03T21:52:20.775000+00:00",
                    "endTime": "2020-11-03T21:52:20.976000+00:00",
                    "durationInSeconds": 0
                },
                {
                    "phaseType": "DOWNLOAD_BATCHSPEC",
                    "phaseStatus": "SUCCEEDED",
                    "startTime": "2020-11-03T21:52:20.976000+00:00",
                    "endTime": "2020-11-03T21:52:57.401000+00:00",
                    "durationInSeconds": 36
                },
                {
                    "phaseType": "IN_PROGRESS",
                    "phaseStatus": "SUCCEEDED",
                    "startTime": "2020-11-03T21:52:57.401000+00:00",
                    "endTime": "2020-11-03T21:56:59.751000+00:00",
                    "durationInSeconds": 242
                },
                {
                    "phaseType": "COMBINE_ARTIFACTS",
                    "phaseStatus": "SUCCEEDED",
                    "startTime": "2020-11-03T21:56:59.751000+00:00",
                    "endTime": "2020-11-03T21:56:59.784000+00:00",
                    "durationInSeconds": 0
                },
                {
                    "phaseType": "SUCCEEDED",
                    "startTime": "2020-11-03T21:56:59.784000+00:00"
                }
            ],
            "source": {
                "type": "GITHUB",
                "location": "https://github.com/my-repo/codebuild-demo-project.git",
                "gitCloneDepth": 1,
                "gitSubmodulesConfig": {
                    "fetchSubmodules": false
                },
                "reportBuildStatus": false,
                "insecureSsl": false
            },
            "secondarySources": [],
            "secondarySourceVersions": [],
            "artifacts": {
                "location": ""
            },
            "secondaryArtifacts": [],
            "cache": {
                "type": "NO_CACHE"
            },
            "environment": {
                "type": "LINUX_CONTAINER",
                "image": "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
                "computeType": "BUILD_GENERAL1_SMALL",
                "environmentVariables": [],
                "privilegedMode": false,
                "imagePullCredentialsType": "CODEBUILD"
            },
            "logConfig": {
                "cloudWatchLogs": {
                    "status": "ENABLED"
                },
                "s3Logs": {
                    "status": "DISABLED",
                    "encryptionDisabled": false
                }
            },
            "buildTimeoutInMinutes": 60,
            "queuedTimeoutInMinutes": 480,
            "complete": true,
            "initiator": "Strohm",
            "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
            "buildBatchNumber": 6,
            "buildBatchConfig": {
                "serviceRole": "arn:aws:iam::123456789012:role/service-role/codebuild-demo-project",
                "restrictions": {
                    "maximumBuildsAllowed": 100
                },
                "timeoutInMins": 480
            },
            "buildGroups": [
                {
                    "identifier": "DOWNLOAD_SOURCE",
                    "ignoreFailure": false,
                    "currentBuildSummary": {
                        "arn": "arn:aws:codebuild:us-west-2:123456789012:build/codebuild-demo-project:379737d8-bc35-48ec-97fd-776d27545315",
                        "requestedOn": "2020-11-03T21:52:21.394000+00:00",
                        "buildStatus": "SUCCEEDED",
                        "primaryArtifact": {
                            "type": "no_artifacts",
                            "identifier": "DOWNLOAD_SOURCE"
                        },
                        "secondaryArtifacts": []
                    }
                },
                {
                    "identifier": "linux_small",
                    "dependsOn": [],
                    "ignoreFailure": false,
                    "currentBuildSummary": {
                        "arn": "arn:aws:codebuild:us-west-2:123456789012:build/codebuild-demo-project:dd785171-ed84-4bb6-8ede-ceeb86e54bdb",
                        "requestedOn": "2020-11-03T21:52:57.604000+00:00",
                        "buildStatus": "SUCCEEDED",
                        "primaryArtifact": {
                            "type": "no_artifacts",
                            "identifier": "linux_small"
                        },
                        "secondaryArtifacts": []
                    }
                },
                {
                    "identifier": "linux_medium",
                    "dependsOn": [
                        "linux_small"
                    ],
                    "ignoreFailure": false,
                    "currentBuildSummary": {
                        "arn": "arn:aws:codebuild:us-west-2:123456789012:build/codebuild-demo-project:97cf7bd4-5313-4786-8243-4aef350a1267",
                        "requestedOn": "2020-11-03T21:54:18.474000+00:00",
                        "buildStatus": "SUCCEEDED",
                        "primaryArtifact": {
                            "type": "no_artifacts",
                            "identifier": "linux_medium"
                        },
                        "secondaryArtifacts": []
                    }
                },
                {
                    "identifier": "linux_large",
                    "dependsOn": [
                        "linux_medium"
                    ],
                    "ignoreFailure": false,
                    "currentBuildSummary": {
                        "arn": "arn:aws:codebuild:us-west-2:123456789012:build/codebuild-demo-project:60a194cd-0d03-4337-9db1-d41476a17d27",
                        "requestedOn": "2020-11-03T21:55:39.203000+00:00",
                        "buildStatus": "SUCCEEDED",
                        "primaryArtifact": {
                            "type": "no_artifacts",
                            "identifier": "linux_large"
                        },
                        "secondaryArtifacts": []
                    }
                }
            ]
        }
    ],
    "buildBatchesNotFound": []
}
```
詳細については、 AWS CodeBuild *AWS ユーザーガイドの「Batch builds inCodeBuild *<https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html>)\$1\$1」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetBuildBatches](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/batch-get-build-batches.html)」を参照してください。

### `batch-get-builds`
<a name="codebuild_BatchGetBuilds_cli_2_topic"></a>

次の例は、`batch-get-builds` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild のビルドの詳細を表示するには。**  
次の `batch-get-builds` の例では、指定した ID を持つ CodeBuild のビルドの情報を取得します。  

```
aws codebuild batch-get-builds --ids codebuild-demo-project:e9c4f4df-3f43-41d2-ab3a-60fe2EXAMPLE codebuild-demo-project:815e755f-bade-4a7e-80f0-efe51EXAMPLE
```
出力:  

```
{
    "buildsNotFound": [],
    "builds": [
        {
            "artifacts": {
                "md5sum": "0e95edf915048a0c22efe6d139fff837",
                "location": "arn:aws:s3:::codepipeline-us-west-2-820783811474/CodeBuild-Python-Pip/BuildArtif/6DJsqQa",
                "encryptionDisabled": false,
                "sha256sum": "cfa0df33a090966a737f64ae4fe498969fdc842a0c9aec540bf93c37ac0d05a2"
            },
            "logs": {
                "cloudWatchLogs": {
                    "status": "ENABLED"
                },
                "s3Logs": {
                    "status": "DISABLED"
                },
                "streamName": "46472baf-8f6b-43c2-9255-b3b963af2732",
                "groupName": "/aws/codebuild/codebuild-demo-project",
                "deepLink": "https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#logEvent:group=/aws/codebuild/codebuild-demo-project;stream=46472baf-8f6b-43c2-9255-b3b963af2732"
            },
            "timeoutInMinutes": 60,
            "environment": {
                "privilegedMode": false,
                "computeType": "BUILD_GENERAL1_MEDIUM",
                "image": "aws/codebuild/windows-base:1.0",
                "environmentVariables": [],
                "type": "WINDOWS_CONTAINER"
            },
            "projectName": "codebuild-demo-project",
            "buildComplete": true,
            "source": {
                "gitCloneDepth": 1,
                "insecureSsl": false,
                "type": "CODEPIPELINE"
            },
            "buildStatus": "SUCCEEDED",
            "secondaryArtifacts": [],
            "phases": [
                {
                    "durationInSeconds": 0,
                    "startTime": 1548717462.122,
                    "phaseType": "SUBMITTED",
                    "endTime": 1548717462.484,
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 0,
                    "startTime": 1548717462.484,
                    "phaseType": "QUEUED",
                    "endTime": 1548717462.775,
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 34,
                    "endTime": 1548717496.909,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717462.775,
                    "phaseType": "PROVISIONING",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 15,
                    "endTime": 1548717512.555,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717496.909,
                    "phaseType": "DOWNLOAD_SOURCE",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 0,
                    "endTime": 1548717512.734,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717512.555,
                    "phaseType": "INSTALL",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 0,
                    "endTime": 1548717512.924,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717512.734,
                    "phaseType": "PRE_BUILD",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 9,
                    "endTime": 1548717522.254,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717512.924,
                    "phaseType": "BUILD",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 3,
                    "endTime": 1548717525.498,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717522.254,
                    "phaseType": "POST_BUILD",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 9,
                    "endTime": 1548717534.646,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717525.498,
                    "phaseType": "UPLOAD_ARTIFACTS",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 2,
                    "endTime": 1548717536.846,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548717534.646,
                    "phaseType": "FINALIZING",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "startTime": 1548717536.846,
                    "phaseType": "COMPLETED"
                }
            ],
            "startTime": 1548717462.122,
            "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
            "initiator": "codepipeline/CodeBuild-Pipeline",
            "secondarySources": [],
            "serviceRole": "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role",
            "currentPhase": "COMPLETED",
            "id": "codebuild-demo-project:e9c4f4df-3f43-41d2-ab3a-60fe2EXAMPLE",
            "cache": {
                "type": "NO_CACHE"
            },
            "sourceVersion": "arn:aws:s3:::codepipeline-us-west-2-820783811474/CodeBuild-Python-Pip/SourceArti/1TspnN3.zip",
            "endTime": 1548717536.846,
            "arn": "arn:aws:codebuild:us-west-2:123456789012:build/codebuild-demo-project:e9c4f4df-3f43-41d2-ab3a-60fe2EXAMPLE",
            "queuedTimeoutInMinutes": 480,
            "resolvedSourceVersion": "f2194c1757bbdcb0f8f229254a4b3c8b27d43e0b"
        },
        {
            "artifacts": {
                "md5sum": "",
                "overrideArtifactName": false,
                "location": "arn:aws:s3:::my-artifacts/codebuild-demo-project",
                "encryptionDisabled": false,
                "sha256sum": ""
            },
            "logs": {
                "cloudWatchLogs": {
                    "status": "ENABLED"
                },
                "s3Logs": {
                    "status": "DISABLED"
                },
                "streamName": "4dea3ca4-20ec-4898-b22a-a9eb9292775d",
                "groupName": "/aws/codebuild/codebuild-demo-project",
                "deepLink": "https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#logEvent:group=/aws/codebuild/codebuild-demo-project;stream=4dea3ca4-20ec-4898-b22a-a9eb9292775d"
            },
            "timeoutInMinutes": 60,
            "environment": {
                "privilegedMode": false,
                "computeType": "BUILD_GENERAL1_MEDIUM",
                "image": "aws/codebuild/windows-base:1.0",
                "environmentVariables": [],
                "type": "WINDOWS_CONTAINER"
            },
            "projectName": "codebuild-demo-project",
            "buildComplete": true,
            "source": {
                "gitCloneDepth": 1,
                "location": "https://github.com/my-repo/codebuild-demo-project.git",
                "insecureSsl": false,
                "reportBuildStatus": false,
                "type": "GITHUB"
            },
            "buildStatus": "SUCCEEDED",
            "secondaryArtifacts": [],
            "phases": [
                {
                    "durationInSeconds": 0,
                    "startTime": 1548716241.89,
                    "phaseType": "SUBMITTED",
                    "endTime": 1548716242.241,
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 0,
                    "startTime": 1548716242.241,
                    "phaseType": "QUEUED",
                    "endTime": 1548716242.536,
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 33,
                    "endTime": 1548716276.171,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716242.536,
                    "phaseType": "PROVISIONING",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 15,
                    "endTime": 1548716291.809,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716276.171,
                    "phaseType": "DOWNLOAD_SOURCE",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 0,
                    "endTime": 1548716291.993,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716291.809,
                    "phaseType": "INSTALL",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 0,
                    "endTime": 1548716292.191,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716291.993,
                    "phaseType": "PRE_BUILD",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 9,
                    "endTime": 1548716301.622,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716292.191,
                    "phaseType": "BUILD",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 3,
                    "endTime": 1548716304.783,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716301.622,
                    "phaseType": "POST_BUILD",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 8,
                    "endTime": 1548716313.775,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716304.783,
                    "phaseType": "UPLOAD_ARTIFACTS",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "durationInSeconds": 2,
                    "endTime": 1548716315.935,
                    "contexts": [
                        {
                            "statusCode": "",
                            "message": ""
                        }
                    ],
                    "startTime": 1548716313.775,
                    "phaseType": "FINALIZING",
                    "phaseStatus": "SUCCEEDED"
                },
                {
                    "startTime": 1548716315.935,
                    "phaseType": "COMPLETED"
                }
            ],
            "startTime": 1548716241.89,
            "secondarySourceVersions": [],
            "initiator": "my-codebuild-project",
            "arn": "arn:aws:codebuild:us-west-2:123456789012:build/codebuild-demo-project:815e755f-bade-4a7e-80f0-efe51EXAMPLE",
            "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
            "serviceRole": "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role",
            "currentPhase": "COMPLETED",
            "id": "codebuild-demo-project:815e755f-bade-4a7e-80f0-efe51EXAMPLE",
            "cache": {
                "type": "NO_CACHE"
            },
            "endTime": 1548716315.935,
            "secondarySources": [],
            "queuedTimeoutInMinutes": 480,
            "resolvedSourceVersion": "f2194c1757bbdcb0f8f229254a4b3c8b27d43e0b"
        }
    ]
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*」の[「ビルドの詳細の表示 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/view-build-details.html#view-build-details-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetBuilds](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/batch-get-builds.html)」を参照してください。

### `batch-get-projects`
<a name="codebuild_BatchGetProjects_cli_2_topic"></a>

次の例は、`batch-get-projects` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクト名のリストを取得するには。**  
次の `batch-get-projects` の例では、名前で指定した CodeBuild ビルドプロジェクトのリストを取得します。  

```
aws codebuild batch-get-projects --names codebuild-demo-project codebuild-demo-project2 my-other-demo-project
```
次の出力では、指定されたビルドプロジェクト名のうち、見つからなかったものがすべて `projectsNotFound` 配列にリストされています。`projects` 配列は、情報が見つかった各ビルドプロジェクトの詳細を示しています。  

```
{
    "projectsNotFound": [],
    "projects": [
        {
            "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
            "name": "codebuild-demo-project2",
            "queuedTimeoutInMinutes": 480,
            "timeoutInMinutes": 60,
            "source": {
                "buildspec": "version: 0.2\n\n#env:\n  #variables:\n     # key: \"value\"\n     # key: \"value\"\n  #parameter-store:\n     # key: \"value\"\n     # key:\"value\"\n\nphases:\n  #install:\n    #commands:\n      # - command\n      # - command\n  #pre_build:\n    #commands:\n      # - command\n      # - command\n  build:\n    commands:\n      # - command\n      # - command\n  #post_build:\n    #commands:\n      # - command\n      # - command\n#artifacts:\n  #files:\n    # - location\n    # - location\n  #name: $(date +%Y-%m-%d)\n  #discard-paths: yes\n  #base-directory: location\n#cache:\n  #paths:\n    # - paths",
                "type": "NO_SOURCE",
                "insecureSsl": false,
                "gitCloneDepth": 1
            },
            "artifacts": {
                "type": "NO_ARTIFACTS"
            },
            "badge": {
                "badgeEnabled": false
            },
            "lastModified": 1540588091.108,
            "created": 1540588091.108,
            "arn": "arn:aws:codebuild:us-west-2:123456789012:project/test-for-sample",
            "secondarySources": [],
            "secondaryArtifacts": [],
            "cache": {
                "type": "NO_CACHE"
            },
            "serviceRole": "arn:aws:iam::123456789012:role/service-role/my-test-role",
            "environment": {
                "image": "aws/codebuild/java:openjdk-8",
                "privilegedMode": true,
                "type": "LINUX_CONTAINER",
                "computeType": "BUILD_GENERAL1_SMALL",
                "environmentVariables": []
            },
            "tags": []
        },
        {
            "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
            "name": "my-other-demo-project",
            "queuedTimeoutInMinutes": 480,
            "timeoutInMinutes": 60,
            "source": {
                "location": "https://github.com/iversonic/codedeploy-sample.git",
                "reportBuildStatus": false,
                "buildspec": "buildspec.yml",
                "insecureSsl": false,
                "gitCloneDepth": 1,
                "type": "GITHUB",
                "auth": {
                    "type": "OAUTH"
                }
            },
            "artifacts": {
                "type": "NO_ARTIFACTS"
            },
            "badge": {
                "badgeEnabled": false
            },
            "lastModified": 1523401711.73,
            "created": 1523401711.73,
            "arn": "arn:aws:codebuild:us-west-2:123456789012:project/Project2",
            "cache": {
                "type": "NO_CACHE"
            },
            "serviceRole": "arn:aws:iam::123456789012:role/service-role/codebuild-Project2-service-role",
            "environment": {
                "image": "aws/codebuild/nodejs:4.4.7",
                "privilegedMode": false,
                "type": "LINUX_CONTAINER",
                "computeType": "BUILD_GENERAL1_SMALL",
                "environmentVariables": []
            },
            "tags": []
        }
    ]
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドプロジェクトの詳細を表示する (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/view-project-details.html#view-project-details-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetProjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/batch-get-projects.html)」を参照してください。

### `batch-get-report-groups`
<a name="codebuild_BatchGetReportGroups_cli_2_topic"></a>

次の例は、`batch-get-report-groups` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild で 1 つ以上のレポートグループに関する情報を取得するには。**  
次の `batch-get-report-groups` の例では、指定した ARN を持つレポートグループの情報を取得します。  

```
aws codebuild batch-get-report-groups \
    --report-group-arns arn:aws:codebuild:<region-ID>:<user-ID>:report-group/<report-group-name>
```
出力:  

```
{
    "reportGroups": [
        {
            "arn": "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/<report-group-name>",
            "name": "report-group-name",
            "type": "TEST",
            "exportConfig": {
                "exportConfigType": "NO_EXPORT"
            },
            "created": "2020-10-01T18:04:08.466000+00:00",
            "lastModified": "2020-10-01T18:04:08.466000+00:00",
            "tags": []
        }
    ],
    "reportGroupsNotFound": []
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with report groups](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetReportGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/batch-get-report-groups.html)」を参照してください。

### `batch-get-reports`
<a name="codebuild_BatchGetReports_cli_2_topic"></a>

次の例は、`batch-get-reports` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild で 1 つ以上のレポートに関する情報を取得するには。**  
次の `batch-get-reports` の例では、指定した ARN を持つレポートの情報を取得します。  

```
aws codebuild batch-get-reports \
    --report-arns arn:aws:codebuild:<region-ID>:<user-ID>:report/<report-group-name>:<report 1 ID> arn:aws:codebuild:<region-ID>:<user-ID>:report/<report-group-name>:<report 2 ID>
```
出力:  

```
{
    "reports": [
        {
            "arn": "arn:aws:codebuild:<region-ID>:<user-ID>:report/<report-group-name>:<report 1 ID>",
            "type": "TEST",
            "name": "<report-group-name>",
            "reportGroupArn": "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/<report-group-name>",
            "executionId": "arn:aws:codebuild:<region-ID>:<user-ID>:build/test-reports:<ID>",
            "status": "FAILED",
            "created": "2020-10-01T11:25:22.531000-07:00",
            "expired": "2020-10-31T11:25:22-07:00",
            "exportConfig": {
                "exportConfigType": "NO_EXPORT"
            },
            "truncated": false,
            "testSummary": {
                "total": 28,
                "statusCounts": {
                    "ERROR": 5,
                    "FAILED": 1,
                    "SKIPPED": 4,
                    "SUCCEEDED": 18,
                    "UNKNOWN": 0
                },
                "durationInNanoSeconds": 94000000
            }
        },
        {
            "arn": "arn:aws:codebuild:<region-ID>:<user-ID>:report/<report-group-name>:<report 2 ID>",
            "type": "TEST",
            "name": "<report-group-name>",
            "reportGroupArn": "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/<report-group-name>",
            "executionId": "arn:aws:codebuild:<region-ID>:<user-ID>:build/test-reports:<ID>",
            "status": "FAILED",
            "created": "2020-10-01T11:13:05.816000-07:00",
            "expired": "2020-10-31T11:13:05-07:00",
            "exportConfig": {
                "exportConfigType": "NO_EXPORT"
            },
            "truncated": false,
            "testSummary": {
                "total": 28,
                "statusCounts": {
                    "ERROR": 5,
                    "FAILED": 1,
                    "SKIPPED": 4,
                    "SUCCEEDED": 18,
                    "UNKNOWN": 0
                },
                "durationInNanoSeconds": 94000000
            }
        }
    ],
    "reportsNotFound": []
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with reports](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetReports](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/batch-get-reports.html)」を参照してください。

### `create-project`
<a name="codebuild_CreateProject_cli_2_topic"></a>

次の例は、`create-project` を使用する方法を説明しています。

**AWS CLI**  
**例 1: AWS CodeBuild ビルドプロジェクトを作成するには**  
次の `create-project` 例は、S3 バケットのソースファイルを使用して CodeBuild ビルドプロジェクトを作成します。  

```
aws codebuild create-project \
    --name "my-demo-project" \
    --source "{\"type\": \"S3\",\"location\": \"codebuild-us-west-2-123456789012-input-bucket/my-source.zip\"}" \
    --artifacts {"\"type\": \"S3\",\"location\": \"codebuild-us-west-2-123456789012-output-bucket\""} \
    --environment "{\"type\": \"LINUX_CONTAINER\",\"image\": \"aws/codebuild/standard:1.0\",\"computeType\": \"BUILD_GENERAL1_SMALL\"}" \
    --service-role "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role"
```
出力:  

```
{
    "project": {
        "arn": "arn:aws:codebuild:us-west-2:123456789012:project/my-demo-project",
        "name": "my-cli-demo-project",
        "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
        "serviceRole": "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role",
        "lastModified": 1556839783.274,
        "badge": {
            "badgeEnabled": false
        },
        "queuedTimeoutInMinutes": 480,
        "environment": {
            "image": "aws/codebuild/standard:1.0",
            "computeType": "BUILD_GENERAL1_SMALL",
            "type": "LINUX_CONTAINER",
            "imagePullCredentialsType": "CODEBUILD",
            "privilegedMode": false,
            "environmentVariables": []
        },
        "artifacts": {
            "location": "codebuild-us-west-2-123456789012-output-bucket",
            "name": "my-cli-demo-project",
            "namespaceType": "NONE",
            "type": "S3",
            "packaging": "NONE",
            "encryptionDisabled": false
        },
        "source": {
            "type": "S3",
            "location": "codebuild-us-west-2-123456789012-input-bucket/my-source.zip",
            "insecureSsl": false
        },
        "timeoutInMinutes": 60,
        "cache": {
            "type": "NO_CACHE"
        },
        "created": 1556839783.274
    }
}
```
**例 2: パラメータの JSON 入力ファイルを使用して AWS CodeBuild ビルドプロジェクトを作成するには**  
次の `create-project` 例では、JSON 入力ファイルにすべての必須パラメータを渡して CodeBuild ビルドプロジェクトを作成します。`--generate-cli-skeleton parameter` のみを含むコマンドを実行して、入力ファイルテンプレートを作成します。  

```
aws codebuild create-project --cli-input-json file://create-project.json
```
入力 JSON ファイル `create-project.json` には、以下の内容が含まれます。  

```
{
    "name": "codebuild-demo-project",
    "source": {
        "type": "S3",
        "location": "codebuild-region-ID-account-ID-input-bucket/MessageUtil.zip"
    },
    "artifacts": {
        "type": "S3",
        "location": "codebuild-region-ID-account-ID-output-bucket"
    },
    "environment": {
        "type": "LINUX_CONTAINER",
        "image": "aws/codebuild/standard:1.0",
        "computeType": "BUILD_GENERAL1_SMALL"
    },
    "serviceRole": "serviceIAMRole"
}
```
出力:  

```
{
    "project": {
        "name": "codebuild-demo-project",
        "serviceRole": "serviceIAMRole",
        "tags": [],
        "artifacts": {
            "packaging": "NONE",
            "type": "S3",
            "location": "codebuild-region-ID-account-ID-output-bucket",
            "name": "message-util.zip"
        },
        "lastModified": 1472661575.244,
        "timeoutInMinutes": 60,
        "created": 1472661575.244,
        "environment": {
            "computeType": "BUILD_GENERAL1_SMALL",
            "image": "aws/codebuild/standard:1.0",
            "type": "LINUX_CONTAINER",
            "environmentVariables": []
        },
        "source": {
            "type": "S3",
            "location": "codebuild-region-ID-account-ID-input-bucket/MessageUtil.zip"
        },
        "encryptionKey": "arn:aws:kms:region-ID:account-ID:alias/aws/s3",
        "arn": "arn:aws:codebuild:region-ID:account-ID:project/codebuild-demo-project"
    }
}
```
詳細については、*AWS 「 CodeBuild * [ユーザーガイド」の「ビルドプロジェクトの作成 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/create-project.html#create-project-cli)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/create-project.html)」を参照してください。**

### `create-report-group`
<a name="codebuild_CreateReportGroup_cli_2_topic"></a>

次の例は、`create-report-group` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でレポートグループを作成するには。**  
次の `create-report-group` の例では、新しいレポートグループを作成します。  

```
aws codebuild create-report-group \
    --cli-input-json file://create-report-group-source.json
```
create-report-group-source.json の内容:  

```
{
    "name": "cli-created-report-group",
    "type": "TEST",
    "exportConfig": {
        "exportConfigType": "S3",
        "s3Destination": {
            "bucket": "amzn-s3-demo-bucket",
            "path": "",
            "packaging": "ZIP",
            "encryptionDisabled": true
        }
    }
}
```
出力:  

```
{
    "reportGroup": {
        "arn": "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/cli-created-report-group",
        "name": "cli-created-report-group",
        "type": "TEST",
        "exportConfig": {
            "exportConfigType": "S3",
            "s3Destination": {
                "bucket": "amzn-s3-demo-bucket",
                "path": "",
                "packaging": "ZIP",
                "encryptionDisabled": true
            }
        },
        "created": 1602020026.775,
        "lastModified": 1602020026.775
    }
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with report groups](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReportGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/create-report-group.html)」を参照してください。

### `create-webhook`
<a name="codebuild_CreateWebhook_cli_2_topic"></a>

次の例は、`create-webhook` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild プロジェクトのウェブフックフィルターを作成するには**  
次の `create-webhook` の例では、2 つのフィルタグループを持つ `my-project` という名前の CodeBuild プロジェクトのウェブフックを作成します。最初のフィルタグループでは、正規表現 `^refs/heads/master$` と一致する Git 参照名および `^refs/heads/myBranch$` と一致するヘッド参照を持つブランチに対してプルリクエストを作成、更新、または再開することを指定します。2 番目のフィルタグループでは、正規表現 `^refs/heads/myBranch$` と一致しない Git 参照名を持つブランチでプッシュリクエストを指定します。  

```
aws codebuild create-webhook \
    --project-name my-project \
    --filter-groups "[[{\"type\":\"EVENT\",\"pattern\":\"PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED\"},{\"type\":\"HEAD_REF\",\"pattern\":\"^refs/heads/myBranch$\",\"excludeMatchedPattern\":true},{\"type\":\"BASE_REF\",\"pattern\":\"^refs/heads/master$\",\"excludeMatchedPattern\":true}],[{\"type\":\"EVENT\",\"pattern\":\"PUSH\"},{\"type\":\"HEAD_REF\",\"pattern\":\"^refs/heads/myBranch$\",\"excludeMatchedPattern\":true}]]"
```
出力:  

```
{
    "webhook": {
        "payloadUrl": "https://codebuild.us-west-2.amazonaws.com/webhooks?t=eyJlbmNyeXB0ZWREYXRhIjoiVVl5MGtoeGRwSzZFRXl2Wnh4bld1Z0tKZ291TVpQNEtFamQ3RDlDYWpRaGIreVFrdm9EQktIVk1NeHJEWEpmUDUrVUNOMUIyRHJRc1VxcHJ6QlNDSnljPSIsIml2UGFyYW1ldGVyU3BlYyI6InN4Tm1SeUt5MUhaUVRWbGciLCJtYXRlcmlhbFNldFNlcmlhbCI6MX0%3D&v=1",
        "url": "https://api.github.com/repos/iversonic/codedeploy-sample/hooks/105190656",
        "lastModifiedSecret": 1556311319.069,
        "filterGroups": [
            [
                {
                    "type": "EVENT",
                    "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED",
                    "excludeMatchedPattern": false
                },
                {
                    "type": "HEAD_REF",
                    "pattern": "refs/heads/myBranch$",
                    "excludeMatchedPattern": true
                },
                {
                    "type": "BASE_REF",
                    "pattern": "refs/heads/master$",
                    "excludeMatchedPattern": true
                }
            ],
            [
                {
                    "type": "EVENT",
                    "pattern": "PUSH",
                    "excludeMatchedPattern": false
                },
                {
                    "type": "HEAD_REF",
                    "pattern": "refs/heads/myBranch$",
                    "excludeMatchedPattern": true
                }
            ]
        ]
    }
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Filter GitHub Webhook Events (SDK)](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-github-pull-request.html#sample-github-pull-request-filter-webhook-events-sdk)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWebhook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/create-webhook.html)」を参照してください。

### `delete-build-batch`
<a name="codebuild_DeleteBuildBatch_cli_2_topic"></a>

次の例は、`delete-build-batch` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でバッチビルドを削除するには。**  
次の `delete-build-batch` の例では、指定されたバッチビルドを削除します。  

```
aws codebuild delete-build-batch \
    --id <project-name>:<batch-ID>
```
出力:  

```
{
    "statusCode": "BATCH_DELETED",
    "buildsDeleted": [
        "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
        "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
        "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
        "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>"
    ],
    "buildsNotDeleted": []
}
```
詳細については、[「 AWS CodeBuild ユーザーガイド」の「Batch builds inCodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html)*AWS CodeBuild*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBuildBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/delete-build-batch.html)」を参照してください。

### `delete-project`
<a name="codebuild_DeleteProject_cli_2_topic"></a>

次の例は、`delete-project` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクトを削除するには**  
次の `delete-project` の例では、指定された CodeBuild ビルドプロジェクトを削除します。  

```
aws codebuild delete-project --name my-project
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドプロジェクトの削除 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/delete-project.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/delete-project.html)」を参照してください。

### `delete-report-group`
<a name="codebuild_DeleteReportGroup_cli_2_topic"></a>

次の例は、`delete-report-group` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でレポートグループを削除するには。**  
次の `delete-report-group` の例では、指定された ARN を持つレポートグループを削除します。  

```
aws codebuild delete-report-group \
    --arn arn:aws:codebuild:<region-ID>:<user-ID>:report-group/<report-group-name>
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with report groups](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReportGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/delete-report-group.html)」を参照してください。

### `delete-report`
<a name="codebuild_DeleteReport_cli_2_topic"></a>

次の例は、`delete-report` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でレポートを削除するには。**  
次の `delete-report` の例では、指定されたレポートを削除します。  

```
aws codebuild delete-report \
    --arn arn:aws:codebuild:<region-ID>:<account-ID>:report/<report-group-name>:<report-ID>
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with reports](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/delete-report.html)」を参照してください。

### `delete-source-credentials`
<a name="codebuild_DeleteSourceCredentials_cli_2_topic"></a>

次のコード例は、`delete-source-credentials` を使用する方法を示しています。

**AWS CLI**  
**ソースプロバイダーから切断し、そのアクセストークンを削除するには。**  
次の `delete-source-credentials` の例では、ソースプロバイダーから切断し、そのトークンを削除します。ソースプロバイダーへの接続に使用されるソース認証情報の ARN によって、どのソース認証情報が使用されるかが決定します。  

```
aws codebuild delete-source-credentials --arn arn-of-your-credentials
```
出力:  

```
{
    "arn": "arn:aws:codebuild:your-region:your-account-id:token/your-server-type"
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Connect Source Providers with Access Tokens (CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-access-tokens.html#sample-access-tokens-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSourceCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/delete-source-credentials.html)」を参照してください。

### `delete-webhook`
<a name="codebuild_DeleteWebhook_cli_2_topic"></a>

次の例は、`delete-webhook` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild プロジェクトからウェブフックフィルターを削除するには**  
次の `delete-webhook` の例では、指定された CodeBuild プロジェクトからウェブフックを削除します。  

```
aws codebuild delete-webhook --project-name my-project
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドの自動実行の停止 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/run-build.html#run-build-cli-auto-stop)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWebhook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/delete-webhook.html)」を参照してください。

### `describe-code-coverages`
<a name="codebuild_DescribeCodeCoverages_cli_2_topic"></a>

次の例は、`describe-code-coverages` を使用する方法を説明しています。

**AWS CLI**  
**コードカバレッジテスト結果に関する詳細情報を取得するには in AWS CodeBuild。**  
次の `describe-code-coverages` の例では、指定されたレポートのコードカバレッジテストの結果に関する情報を取得します。  

```
aws codebuild describe-code-coverages \
    --report-arn arn:aws:codebuild:<region-ID>:<account-ID>:report/<report-group-name>:<report-ID>
```
出力:  

```
{
    "codeCoverages": [
        {
            "id": "20a0adcc-db13-4b66-804b-ecaf9f852855",
            "reportARN": "arn:aws:codebuild:<region-ID>:972506530580:report/<report-group-name>:<report-ID>",
            "filePath": "<source-file-1-path>",
            "lineCoveragePercentage": 83.33,
            "linesCovered": 5,
            "linesMissed": 1,
            "branchCoveragePercentage": 50.0,
            "branchesCovered": 1,
            "branchesMissed": 1,
            "expired": "2020-11-20T21:22:45+00:00"
        },
        {
            "id": "0887162d-bf57-4cf1-a164-e432373d1a83",
            "reportARN": "arn:aws:codebuild:<region-ID>:972506530580:report/<report-group-name>:<report-ID>",
            "filePath": "<source-file-2-path>",
            "lineCoveragePercentage": 90.9,
            "linesCovered": 10,
            "linesMissed": 1,
            "branchCoveragePercentage": 50.0,
            "branchesCovered": 1,
            "branchesMissed": 1,
            "expired": "2020-11-20T21:22:45+00:00"
        }
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Code coverage reports](https://docs.aws.amazon.com/codebuild/latest/userguide/code-coverage-report.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCodeCoverages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/describe-code-coverages.html)」を参照してください。

### `describe-test-cases`
<a name="codebuild_DescribeTestCases_cli_2_topic"></a>

次の例は、`describe-test-cases` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild のテストケースに関する詳細情報を取得するには。**  
次の `describe-test-cases` の例では、指定されたレポートのテストケースに関する情報を取得します。  

```
aws codebuild describe-test-cases \
    --report-arn arn:aws:codebuild:<region-ID>:<account-ID>:report/<report-group-name>:<report-ID>
```
出力:  

```
{
    "testCases": [
        {
            "reportArn": "arn:aws:codebuild:<region-ID>:<account-ID>:report/<report-group-name>:<report-ID>",
            "testRawDataPath": "<test-report-path>",
            "prefix": "NUnit.Tests.Assemblies.MockTestFixture",
            "name": "NUnit.Tests.Assemblies.MockTestFixture.NotRunnableTest",
            "status": "ERROR",
            "durationInNanoSeconds": 0,
            "message": "No arguments were provided\n",
            "expired": "2020-11-20T17:52:10+00:00"
        },
        {
            "reportArn": "arn:aws:codebuild:<region-ID>:<account-ID>:report/<report-group-name>:<report-ID>",
            "testRawDataPath": "<test-report-path>",
            "prefix": "NUnit.Tests.Assemblies.MockTestFixture",
            "name": "NUnit.Tests.Assemblies.MockTestFixture.TestWithException",
            "status": "ERROR",
            "durationInNanoSeconds": 0,
            "message": "System.ApplicationException : Intentional Exception\nat NUnit.Tests.Assemblies.MockTestFixture.MethodThrowsException()\nat NUnit.Tests.Assemblies.MockTestFixture.TestWithException()\n\n",
            "expired": "2020-11-20T17:52:10+00:00"
        }
    ]
}
```
詳細については、[「 AWS CodeBuild ユーザーガイド」の「Working with test reporting inCodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/test-reporting.html)*AWS CodeBuild*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTestCases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/describe-test-cases.html)」を参照してください。

### `import-source-credentials`
<a name="codebuild_ImportSourceCredentials_cli_2_topic"></a>

次の例は、`import-source-credentials` を使用する方法を説明しています。

**AWS CLI**  
**ソースプロバイダーの認証情報をインポートして AWS CodeBuild ユーザーをソースプロバイダーに接続します。**  
次の `import-source-credentials` の例では、認証タイプに BASIC\$1AUTH を使用する Bitbucket リポジトリのトークンをインポートします。  

```
aws codebuild import-source-credentials --server-type BITBUCKET --auth-type BASIC_AUTH --token my-Bitbucket-password --username my-Bitbucket-username
```
出力:  

```
{
    "arn": "arn:aws:codebuild:us-west-2:123456789012:token/bitbucket"
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Connect Source Providers with Access Tokens (CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-access-tokens.html#sample-access-tokens-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportSourceCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/import-source-credentials.html)」を参照してください。

### `invalidate-project-cache`
<a name="codebuild_InvalidateProjectCache_cli_2_topic"></a>

次の例は、`invalidate-project-cache` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクトのキャッシュをリセットするには。**  
次の `invalidate-project-cache` の例では、指定された CodeBuild プロジェクトのキャッシュをリセットします。  

```
aws codebuild invalidate-project-cache --project-name my-project
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Build Caching in CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/build-caching.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InvalidateProjectCache](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/invalidate-project-cache.html)」を参照してください。

### `list-build-batches-for-project`
<a name="codebuild_ListBuildBatchesForProject_cli_2_topic"></a>

次の例は、`list-build-batches-for-project` を使用する方法を説明しています。

**AWS CLI**  
**特定のビルドプロジェクトのバッチビルドを AWS CodeBuild で一覧表示するには。**  
次の `list-build-batches-for-project` の例では、指定したプロジェクトの CodeBuild バッチビルドを一覧表示します。  

```
aws codebuild list-build-batches-for-project \
    --project-name "<project-name>"
```
出力:  

```
{
    "ids": [
        "<project-name>:<batch-ID>",
        "<project-name>:<batch-ID>"
    ]
}
```
詳細については、[「 AWS CodeBuild ユーザーガイド」の「Batch builds inCodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html)*AWS CodeBuild*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBuildBatchesForProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-build-batches-for-project.html)」を参照してください。

### `list-build-batches`
<a name="codebuild_ListBuildBatches_cli_2_topic"></a>

次の例は、`list-build-batches` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でバッチビルドを一覧表示するには。**  
次の `list-build-batches` の例では、現在のアカウントの CodeBuild バッチビルドを一覧表示します。  

```
aws codebuild list-build-batches
```
出力:  

```
{
    "ids": [
        "<project-name>:<batch-ID>",
        "<project-name>:<batch-ID>"
    ]
}
```
詳細については、 AWS CodeBuild *AWS ユーザーガイドの「Batch builds inCodeBuild *<https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html>)\$1\$1」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBuildBatches](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-build-batches.html)」を参照してください。

### `list-builds-for-project`
<a name="codebuild_ListBuildsForProject_cli_2_topic"></a>

次の例は、`list-builds-for-project` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクトのビルドのリストを表示するには。**  
次の `list-builds-for-project` の例では、指定された CodeBuild ビルドプロジェクトのビルド ID を降順で一覧表示します。  

```
aws codebuild list-builds-for-project --project-name codebuild-demo-project --sort-order DESCENDING
```
出力:  

```
{
    "ids": [
        "codebuild-demo-project:1a2b3c4d-5678-90ab-cdef-11111example",
        "codebuild-demo-project:1a2b3c4d-5678-90ab-cdef-22222example",
        "codebuild-demo-project:1a2b3c4d-5678-90ab-cdef-33333example",
        "codebuild-demo-project:1a2b3c4d-5678-90ab-cdef-44444example",
        "codebuild-demo-project:1a2b3c4d-5678-90ab-cdef-55555example"
    ]
}
```
詳細については、*AWS 「 CodeBuild * [ユーザーガイド」のIDs のリストAWS](https://docs.aws.amazon.com/codebuild/latest/userguide/view-builds-for-project.html#view-builds-for-project-cli)を表示する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBuildsForProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-builds-for-project.html)」を参照してください。

### `list-builds`
<a name="codebuild_ListBuilds_cli_2_topic"></a>

次の例は、`list-builds` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルド IDs。**  
次の `list-builds` の例では、昇順にソートされた CodeBuild ID のリストを取得します。  

```
aws codebuild list-builds --sort-order ASCENDING
```
出力には、より多くの出力が利用できることを示す `nextToken` 値が含まれます。  

```
{
    "nextToken": "4AEA6u7J...The full token has been omitted for brevity...MzY2OA==",
    "ids": [
        "codebuild-demo-project:815e755f-bade-4a7e-80f0-efe51EXAMPLE"
        "codebuild-demo-project:84a7f3d1-d40e-4956-b4cf-7a9d4EXAMPLE"
            ... The full list of build IDs has been omitted for brevity ...
        "codebuild-demo-project:931d0b72-bf6f-4040-a472-5c707EXAMPLE"
    ]
}
```
このコマンドを再度実行し、前のレスポンスの `nextToken` 値をパラメータとして指定して、出力の次の部分を取得します。レスポンスに `nextToken` 値が返されなくなるまで繰り返します。  

```
aws codebuild list-builds --sort-order ASCENDING --next-token 4AEA6u7J...The full token has been omitted for brevity...MzY2OA==
```
出力の次の部分:  

```
{
    "ids": [
        "codebuild-demo-project:49015049-21cf-4b50-9708-df115EXAMPLE",
        "codebuild-demo-project:543e7206-68a3-46d6-a4da-759abEXAMPLE",
            ... The full list of build IDs has been omitted for brevity ...
        "codebuild-demo-project:c282f198-4582-4b38-bdc0-26f96EXAMPLE"
    ]
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」のIDs のリストを表示する (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/view-build-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBuilds](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-builds.html)」を参照してください。

### `list-curated-environment-images`
<a name="codebuild_ListCuratedEnvironmentImages_cli_2_topic"></a>

次の例は、`list-curated-environment-images` を使用する方法を説明しています。

**AWS CLI**  
**ビルドに使用できる AWS CodeBuild によって管理される Docker イメージのリストを取得するには。**  
次の `list-curated-environment-images` の例では、CodeBuild によって管理され、ビルドに使用できる Docker イメージを一覧表示します。  

```
aws codebuild list-curated-environment-images
```
出力:  

```
{
    "platforms": [
        {
            "platform": "AMAZON_LINUX",
            "languages": [
                {
                    "language": "JAVA",
                    "images": [
                        {
                            "description": "AWS ElasticBeanstalk - Java 7 Running on Amazon Linux 64bit v2.1.3",
                            "name": "aws/codebuild/eb-java-7-amazonlinux-64:2.1.3",
                            "versions": [
                                "aws/codebuild/eb-java-7-amazonlinux-64:2.1.3-1.0.0"
                            ]
                        },
                        {
                            "description": "AWS ElasticBeanstalk - Java 8 Running on Amazon Linux 64bit v2.1.3",
                            "name": "aws/codebuild/eb-java-8-amazonlinux-64:2.1.3",
                            "versions": [
                                "aws/codebuild/eb-java-8-amazonlinux-64:2.1.3-1.0.0"
                            ]
                        },
                        ... LIST TRUNCATED FOR BREVITY ...
                    ]
                }
            ]
        }
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」で 「[Docker Images Provided by CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCuratedEnvironmentImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-curated-environment-images.html)」を参照してください。

### `list-projects`
<a name="codebuild_ListProjects_cli_2_topic"></a>

次の例は、`list-projects` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクト名のリストを取得するには。**  
次の `list-projects` の例では、CodeBuild ビルドプロジェクトを名前で昇順にソートしたリストを取得します。  

```
aws codebuild list-projects --sort-by NAME --sort-order ASCENDING
```
出力には、より多くの出力が利用できることを示す `nextToken` 値が含まれます。  

```
{
    "nextToken": "Ci33ACF6...The full token has been omitted for brevity...U+AkMx8=",
    "projects": [
        "codebuild-demo-project",
        "codebuild-demo-project2",
            ... The full list of build project names has been omitted for brevity ...
        "codebuild-demo-project99"
    ]
}
```
このコマンドを再度実行し、前のレスポンスの `nextToken` 値をパラメータとして指定して、出力の次の部分を取得します。レスポンスに `nextToken` 値が返されなくなるまで繰り返します。  

```
aws codebuild list-projects  --sort-by NAME --sort-order ASCENDING --next-token Ci33ACF6...The full token has been omitted for brevity...U+AkMx8=

{
    "projects": [
        "codebuild-demo-project100",
        "codebuild-demo-project101",
            ... The full list of build project names has been omitted for brevity ...
        "codebuild-demo-project122"
    ]
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドプロジェクト名のリストを表示する (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/view-project-list.html#view-project-list-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-projects.html)」を参照してください。

### `list-report-groups`
<a name="codebuild_ListReportGroups_cli_2_topic"></a>

次の例は、`list-report-groups` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でレポートグループ ARNs のリストを取得するには。**  
次の `list-report-groups` の例では、リージョン内のアカウントのレポートグループ ARN を取得します。  

```
aws codebuild list-report-groups
```
出力:  

```
{
    "reportGroups": [
        "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/report-group-1",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/report-group-2",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/report-group-3"
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with report groups](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReportGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-report-groups.html)」を参照してください。

### `list-reports-for-report-group`
<a name="codebuild_ListReportsForReportGroup_cli_2_topic"></a>

次の例は、`list-reports-for-report-group` を使用する方法を説明しています。

**AWS CLI**  
**レポートグループ in AWS CodeBuild 内のレポートのリストを取得するには。**  
次の `list-report-for-report-groups` の例では、リージョン内のアカウントの指定されたレポートグループのレポートを取得します。  

```
aws codebuild list-reports-for-report-group \
    --report-group-arn arn:aws:codebuild:<region-ID>:<user-ID>:report-group/<report-group-name>
```
出力:  

```
{
    "reports": [
        "arn:aws:codebuild:<region-ID>:<user-ID>:report/report-1",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report/report-2",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report/report-3"
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with report groups](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReportsForReportGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-reports-for-report-group.html)」を参照してください。

### `list-reports`
<a name="codebuild_ListReports_cli_2_topic"></a>

次の例は、`list-reports` を使用する方法を説明しています。

**AWS CLI**  
**現在のアカウント in AWS CodeBuild のレポートのリストを取得するには。**  
次の `list-reports` の例では、現在のアカウントのレポートの ARN を取得します。  

```
aws codebuild list-reports
```
出力:  

```
{
    "reports": [
        "arn:aws:codebuild:<region-ID>:<user-ID>:report/<report-group-name>:<report ID>",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report/<report-group-name>:<report ID>",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report/<report-group-name>:<report ID>"
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with reports](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReports](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-reports.html)」を参照してください。

### `list-shared-projects`
<a name="codebuild_ListSharedProjects_cli_2_topic"></a>

次の例は、`list-shared-projects` を使用する方法を説明しています。

**AWS CLI**  
**共有プロジェクト in AWS CodeBuild を一覧表示するには。**  
次の `list-shared-projects` の例では、現在のアカウントで利用可能な CodeBuild 共有プロジェクトを一覧表示します。  

```
aws codebuild list-shared-projects
```
出力:  

```
{
    "projects": [
        "arn:aws:codebuild:<region-ID>:<account-ID>:project/<shared-project-name-1>",
        "arn:aws:codebuild:<region-ID>:<account-ID>:project/<shared-project-name-2>"
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with shared projects](https://docs.aws.amazon.com/codebuild/latest/userguide/project-sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSharedProjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-shared-projects.html)」を参照してください。

### `list-shared-report-groups`
<a name="codebuild_ListSharedReportGroups_cli_2_topic"></a>

次の例は、`list-shared-report-groups` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild の共有レポートグループ ARNs のリストを取得するには。**  
次の `list-shared-report-groups` の例では、リージョン内のアカウントのレポートグループ ARN を取得します。  

```
aws codebuild list-shared-report-groups
```
出力:  

```
{
    "reportGroups": [
        "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/report-group-1",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/report-group-2",
        "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/report-group-3"
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with report groups](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSharedReportGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-shared-report-groups.html)」を参照してください。

### `list-source-credentials`
<a name="codebuild_ListSourceCredentials_cli_2_topic"></a>

次のコード例は、`list-source-credentials` を使用する方法を示しています。

**AWS CLI**  
**sourceCredentialsObjects のリストを表示するには**  
次の の`list-source-credentials`例では、1 つの Bitbucket AWS アカウントと 1 つの GitHub アカウントに接続されているアカウントのトークンを一覧表示します。レスポンス内の各 `sourceCredentialsInfos` オブジェクトには、接続されたソース認証情報が含まれています。  

```
aws codebuild list-source-credentials
```
出力:  

```
{
    "sourceCredentialsInfos": [
        {
            "serverType": "BITBUCKET",
            "arn": "arn:aws:codebuild:us-west-2:123456789012:token/bitbucket",
            "authType": "BASIC_AUTH"
        },
        {
            "serverType": "GITHUB",
            "arn": "arn:aws:codebuild:us-west-2:123456789012:token/github",
            "authType": "OAUTH"
        }
    ]
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Connect Source Providers with Access Tokens (CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-access-tokens.html#sample-access-tokens-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSourceCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/list-source-credentials.html)」を参照してください。

### `retry-build-batch`
<a name="codebuild_RetryBuildBatch_cli_2_topic"></a>

次の例は、`retry-build-batch` を使用する方法を説明しています。

**AWS CLI**  
**失敗したバッチビルド in AWS CodeBuild を再試行するには。**  
次の `retry-build-batch` の例では、指定されたバッチビルドを再起動します。  

```
aws codebuild retry-build-batch \
    --id <project-name>:<batch-ID>
```
出力:  

```
{
    "buildBatch": {
        "id": "<project-name>:<batch-ID>",
        "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build-batch/<project-name>:<batch-ID>",
        "startTime": "2020-10-21T17:26:23.099000+00:00",
        "currentPhase": "SUBMITTED",
        "buildBatchStatus": "IN_PROGRESS",
        "resolvedSourceVersion": "3a9e11cb419e8fff14b03883dc4e64f6155aaa7e",
        "projectName": "<project-name>",
        "phases": [
            {
                "phaseType": "SUBMITTED",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2020-10-21T17:26:23.099000+00:00",
                "endTime": "2020-10-21T17:26:23.457000+00:00",
                "durationInSeconds": 0
            },
            {
                "phaseType": "DOWNLOAD_BATCHSPEC",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2020-10-21T17:26:23.457000+00:00",
                "endTime": "2020-10-21T17:26:54.902000+00:00",
                "durationInSeconds": 31
            },
            {
                "phaseType": "IN_PROGRESS",
                "phaseStatus": "CLIENT_ERROR",
                "startTime": "2020-10-21T17:26:54.902000+00:00",
                "endTime": "2020-10-21T17:28:16.060000+00:00",
                "durationInSeconds": 81
            },
            {
                "phaseType": "FAILED",
                "phaseStatus": "RETRY",
                "startTime": "2020-10-21T17:28:16.060000+00:00",
                "endTime": "2020-10-21T17:29:39.709000+00:00",
                "durationInSeconds": 83
            },
            {
                "phaseType": "SUBMITTED",
                "startTime": "2020-10-21T17:29:39.709000+00:00"
            }
        ],
        "source": {
            "type": "GITHUB",
            "location": "https://github.com/strohm-a/<project-name>-graph.git",
            "gitCloneDepth": 1,
            "gitSubmodulesConfig": {
                "fetchSubmodules": false
            },
            "reportBuildStatus": false,
            "insecureSsl": false
        },
        "secondarySources": [],
        "secondarySourceVersions": [],
        "artifacts": {
            "location": ""
        },
        "secondaryArtifacts": [],
        "cache": {
            "type": "NO_CACHE"
        },
        "environment": {
            "type": "LINUX_CONTAINER",
            "image": "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
            "computeType": "BUILD_GENERAL1_SMALL",
            "environmentVariables": [],
            "privilegedMode": false,
            "imagePullCredentialsType": "CODEBUILD"
        },
        "logConfig": {
            "cloudWatchLogs": {
                "status": "ENABLED"
            },
            "s3Logs": {
                "status": "DISABLED",
                "encryptionDisabled": false
            }
        },
        "buildTimeoutInMinutes": 60,
        "queuedTimeoutInMinutes": 480,
        "complete": false,
        "initiator": "<username>",
        "encryptionKey": "arn:aws:kms:<region-ID>:<account-ID>:alias/aws/s3",
        "buildBatchNumber": 4,
        "buildBatchConfig": {
            "serviceRole": "arn:aws:iam::<account-ID>:role/service-role/<project-name>",
            "restrictions": {
                "maximumBuildsAllowed": 100
            },
            "timeoutInMins": 480
        },
        "buildGroups": [
            {
                "identifier": "DOWNLOAD_SOURCE",
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T17:26:23.889000+00:00",
                    "buildStatus": "SUCCEEDED",
                    "primaryArtifact": {
                        "type": "no_artifacts",
                        "identifier": "DOWNLOAD_SOURCE"
                    },
                    "secondaryArtifacts": []
                }
            },
            {
                "identifier": "linux_small",
                "dependsOn": [],
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T17:26:55.115000+00:00",
                    "buildStatus": "FAILED",
                    "primaryArtifact": {
                        "type": "no_artifacts",
                        "identifier": "linux_small"
                    },
                    "secondaryArtifacts": []
                }
            },
            {
                "identifier": "linux_medium",
                "dependsOn": [
                    "linux_small"
                ],
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T17:26:54.594000+00:00",
                    "buildStatus": "STOPPED"
                }
            },
            {
                "identifier": "linux_large",
                "dependsOn": [
                    "linux_medium"
                ],
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T17:26:54.701000+00:00",
                    "buildStatus": "STOPPED"
                }
            }
        ]
    }
}
```
詳細については、[「 AWS CodeBuild ユーザーガイド」の「Batch builds inCodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html)*AWS CodeBuild*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RetryBuildBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/retry-build-batch.html)」を参照してください。

### `retry-build`
<a name="codebuild_RetryBuild_cli_2_topic"></a>

次の例は、`retry-build` を使用する方法を説明しています。

**AWS CLI**  
**失敗したビルド in AWS CodeBuild を再試行するには。**  
次の `retry-build` の例では、指定されたビルドを再起動します。  

```
aws codebuild retry-build \
    --id <project-name>:<build-ID>
```
出力:  

```
{
    "build": {
        "id": "<project-name>:<build-ID>",
        "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
        "buildNumber": 9,
        "startTime": "2020-10-21T17:51:38.161000+00:00",
        "currentPhase": "QUEUED",
        "buildStatus": "IN_PROGRESS",
        "projectName": "<project-name>",
        "phases": [
            {
                "phaseType": "SUBMITTED",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2020-10-21T17:51:38.161000+00:00",
                "endTime": "2020-10-21T17:51:38.210000+00:00",
                "durationInSeconds": 0
            },
            {
                "phaseType": "QUEUED",
                "startTime": "2020-10-21T17:51:38.210000+00:00"
            }
        ],
        "source": {
            "type": "GITHUB",
            "location": "<GitHub-repo-URL>",
            "gitCloneDepth": 1,
            "gitSubmodulesConfig": {
                "fetchSubmodules": false
            },
            "reportBuildStatus": false,
            "insecureSsl": false
        },
        "secondarySources": [],
        "secondarySourceVersions": [],
        "artifacts": {
            "location": ""
        },
        "secondaryArtifacts": [],
        "cache": {
            "type": "NO_CACHE"
        },
        "environment": {
            "type": "LINUX_CONTAINER",
            "image": "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
            "computeType": "BUILD_GENERAL1_SMALL",
            "environmentVariables": [],
            "privilegedMode": false,
            "imagePullCredentialsType": "CODEBUILD"
        },
        "serviceRole": "arn:aws:iam::<account-ID>:role/service-role/<service-role-name>",
        "logs": {
            "deepLink": "https://console.aws.amazon.com/cloudwatch/home?region=<region-ID>#logEvent:group=null;stream=null",
            "cloudWatchLogsArn": "arn:aws:logs:<region-ID>:<account-ID>:log-group:null:log-stream:null",
            "cloudWatchLogs": {
                "status": "ENABLED"
            },
            "s3Logs": {
                "status": "DISABLED",
                "encryptionDisabled": false
            }
        },
        "timeoutInMinutes": 60,
        "queuedTimeoutInMinutes": 480,
        "buildComplete": false,
        "initiator": "<username>",
        "encryptionKey": "arn:aws:kms:<region-ID>:<account-ID>:alias/aws/s3"
    }
}
```
詳細については、[「 AWS CodeBuild ユーザーガイド」の「Batch builds inCodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html)*AWS CodeBuild*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RetryBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/retry-build.html)」を参照してください。

### `start-build-batch`
<a name="codebuild_StartBuildBatch_cli_2_topic"></a>

次の例は、`start-build-batch` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でバッチビルドを開始するには。**  
次の `start-build-batch` の例では、指定されたプロジェクトのバッチビルドを開始します。  

```
aws codebuild start-build-batch \
    --project-name <project-name>
```
出力:  

```
{
    "buildBatch": {
        "id": "<project-name>:<batch-ID>",
        "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build-batch/<project-name>:<batch-ID>",
        "startTime": "2020-10-21T16:54:24.740000+00:00",
        "currentPhase": "SUBMITTED",
        "buildBatchStatus": "IN_PROGRESS",
        "projectName": "<project-name>",
        "source": {
            "type": "GITHUB",
            "location": "<GitHub-repo-URL>",
            "gitCloneDepth": 1,
            "gitSubmodulesConfig": {
                "fetchSubmodules": false
            },
            "reportBuildStatus": false,
            "insecureSsl": false
        },
        "secondarySources": [],
        "secondarySourceVersions": [],
        "artifacts": {
            "location": ""
        },
        "secondaryArtifacts": [],
        "cache": {
            "type": "NO_CACHE"
        },
        "environment": {
            "type": "LINUX_CONTAINER",
            "image": "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
            "computeType": "BUILD_GENERAL1_SMALL",
            "environmentVariables": [],
            "privilegedMode": false,
            "imagePullCredentialsType": "CODEBUILD"
        },
        "logConfig": {
            "cloudWatchLogs": {
                "status": "ENABLED"
            },
            "s3Logs": {
                "status": "DISABLED",
                "encryptionDisabled": false
            }
        },
        "buildTimeoutInMinutes": 60,
        "queuedTimeoutInMinutes": 480,
        "complete": false,
        "initiator": "<username>",
        "encryptionKey": "arn:aws:kms:<region-ID>:<account-ID>:alias/aws/s3",
        "buildBatchNumber": 3,
        "buildBatchConfig": {
            "serviceRole": "arn:aws:iam::<account-ID>:role/service-role/<service-role-name>",
            "restrictions": {
                "maximumBuildsAllowed": 100
            },
            "timeoutInMins": 480
        }
    }
}
```
詳細については、[「 AWS CodeBuild ユーザーガイド」の「Batch builds inCodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html)*AWS CodeBuild*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartBuildBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/start-build-batch.html)」を参照してください。

### `start-build`
<a name="codebuild_StartBuild_cli_2_topic"></a>

次の例は、`start-build` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクトのビルドの実行を開始するには。**  
次の `start-build` の例では、指定した CodeBuild プロジェクトのビルドを開始します。ビルドは、タイムアウトするまでにビルドをキューに入れることができる分数に関するプロジェクト設定と、プロジェクトのアーティファクト設定の両方を上書きします。  

```
aws codebuild start-build \
    --project-name "my-demo-project" \
    --queued-timeout-in-minutes-override 5 \
    --artifacts-override {"\"type\": \"S3\",\"location\": \"arn:aws:s3:::artifacts-override\",\"overrideArtifactName\":true"}
```
出力:  

```
{
    "build": {
        "serviceRole": "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role",
        "buildStatus": "IN_PROGRESS",
        "buildComplete": false,
        "projectName": "my-demo-project",
        "timeoutInMinutes": 60,
        "source": {
            "insecureSsl": false,
            "type": "S3",
            "location": "codebuild-us-west-2-123456789012-input-bucket/my-source.zip"
        },
        "queuedTimeoutInMinutes": 5,
        "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
        "currentPhase": "QUEUED",
        "startTime": 1556905683.568,
        "environment": {
            "computeType": "BUILD_GENERAL1_MEDIUM",
            "environmentVariables": [],
            "type": "LINUX_CONTAINER",
            "privilegedMode": false,
            "image": "aws/codebuild/standard:1.0",
            "imagePullCredentialsType": "CODEBUILD"
        },
        "phases": [
            {
                "phaseStatus": "SUCCEEDED",
                "startTime": 1556905683.568,
                "phaseType": "SUBMITTED",
                "durationInSeconds": 0,
                "endTime": 1556905684.524
            },
            {
                "startTime": 1556905684.524,
                "phaseType": "QUEUED"
            }
        ],
        "logs": {
            "deepLink": "https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#logEvent:group=null;stream=null"
        },
        "artifacts": {
            "encryptionDisabled": false,
            "location": "arn:aws:s3:::artifacts-override/my-demo-project",
            "overrideArtifactName": true
        },
        "cache": {
            "type": "NO_CACHE"
        },
        "id": "my-demo-project::12345678-a1b2-c3d4-e5f6-11111EXAMPLE",
        "initiator": "my-aws-account-name",
        "arn": "arn:aws:codebuild:us-west-2:123456789012:build/my-demo-project::12345678-a1b2-c3d4-e5f6-11111EXAMPLE"
    }
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドの実行 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/run-build.html#run-build-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/start-build.html)」を参照してください。

### `stop-build-batch`
<a name="codebuild_StopBuildBatch_cli_2_topic"></a>

次の例は、`stop-build-batch` を使用する方法を説明しています。

**AWS CLI**  
**進行中のバッチビルド in AWS CodeBuild を停止するには。**  
次の `stop-build-batch` の例では、指定されたバッチビルドを停止します。  

```
aws codebuild stop-build-batch \
    --id <project-name>:<batch-ID>
```
出力:  

```
{
    "buildBatch": {
        "id": "<project-name>:<batch-ID>",
        "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build-batch/<project-name>:<batch-ID>",
        "startTime": "2020-10-21T16:54:24.740000+00:00",
        "endTime": "2020-10-21T16:56:05.152000+00:00",
        "currentPhase": "STOPPED",
        "buildBatchStatus": "STOPPED",
        "resolvedSourceVersion": "aef7744ed069c51098e15c360f4102cd2cd1ad64",
        "projectName": "<project-name>",
        "phases": [
            {
                "phaseType": "SUBMITTED",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2020-10-21T16:54:24.740000+00:00",
                "endTime": "2020-10-21T16:54:25.039000+00:00",
                "durationInSeconds": 0
            },
            {
                "phaseType": "DOWNLOAD_BATCHSPEC",
                "phaseStatus": "SUCCEEDED",
                "startTime": "2020-10-21T16:54:25.039000+00:00",
                "endTime": "2020-10-21T16:54:56.583000+00:00",
                "durationInSeconds": 31
            },
            {
                "phaseType": "IN_PROGRESS",
                "phaseStatus": "STOPPED",
                "startTime": "2020-10-21T16:54:56.583000+00:00",
                "endTime": "2020-10-21T16:56:05.152000+00:00",
                "durationInSeconds": 68
            },
            {
                "phaseType": "STOPPED",
                "startTime": "2020-10-21T16:56:05.152000+00:00"
            }
        ],
        "source": {
            "type": "GITHUB",
            "location": "<GitHub-repo-URL>",
            "gitCloneDepth": 1,
            "gitSubmodulesConfig": {
                "fetchSubmodules": false
            },
            "reportBuildStatus": false,
            "insecureSsl": false
        },
        "secondarySources": [],
        "secondarySourceVersions": [],
        "artifacts": {
            "location": ""
        },
        "secondaryArtifacts": [],
        "cache": {
            "type": "NO_CACHE"
        },
        "environment": {
            "type": "LINUX_CONTAINER",
            "image": "aws/codebuild/amazonlinux2-x86_64-standard:3.0",
            "computeType": "BUILD_GENERAL1_SMALL",
            "environmentVariables": [],
            "privilegedMode": false,
            "imagePullCredentialsType": "CODEBUILD"
        },
        "logConfig": {
            "cloudWatchLogs": {
                "status": "ENABLED"
            },
            "s3Logs": {
                "status": "DISABLED",
                "encryptionDisabled": false
            }
        },
        "buildTimeoutInMinutes": 60,
        "queuedTimeoutInMinutes": 480,
        "complete": true,
        "initiator": "Strohm",
        "encryptionKey": "arn:aws:kms:<region-ID>:<account-ID>:alias/aws/s3",
        "buildBatchNumber": 3,
        "buildBatchConfig": {
            "serviceRole": "arn:aws:iam::<account-ID>:role/service-role/<project-name>",
            "restrictions": {
                "maximumBuildsAllowed": 100
            },
            "timeoutInMins": 480
        },
        "buildGroups": [
            {
                "identifier": "DOWNLOAD_SOURCE",
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T16:54:25.468000+00:00",
                    "buildStatus": "SUCCEEDED",
                    "primaryArtifact": {
                        "type": "no_artifacts",
                        "identifier": "DOWNLOAD_SOURCE"
                    },
                    "secondaryArtifacts": []
                }
            },
            {
                "identifier": "linux_small",
                "dependsOn": [],
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T16:54:56.833000+00:00",
                    "buildStatus": "IN_PROGRESS"
                }
            },
            {
                "identifier": "linux_medium",
                "dependsOn": [
                    "linux_small"
                ],
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T16:54:56.211000+00:00",
                    "buildStatus": "PENDING"
                }
            },
            {
                "identifier": "linux_large",
                "dependsOn": [
                    "linux_medium"
                ],
                "ignoreFailure": false,
                "currentBuildSummary": {
                    "arn": "arn:aws:codebuild:<region-ID>:<account-ID>:build/<project-name>:<build-ID>",
                    "requestedOn": "2020-10-21T16:54:56.330000+00:00",
                    "buildStatus": "PENDING"
                }
            }
        ]
    }
}
```
詳細については、[「 AWS CodeBuild ユーザーガイド」の「Batch builds inCodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/batch-build.html)*AWS CodeBuild*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopBuildBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/stop-build-batch.html)」を参照してください。

### `stop-build`
<a name="codebuild_StopBuild_cli_2_topic"></a>

次の例は、`stop-build` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクトのビルドを停止するには。**  
次の `stop-build` の例では、指定された CodeBuild ビルドを停止します。  

```
aws codebuild stop-build --id my-demo-project:12345678-a1b2-c3d4-e5f6-11111EXAMPLE
```
出力:  

```
{
    "build": {
        "startTime": 1556906956.318,
        "initiator": "my-aws-account-name",
        "projectName": "my-demo-project",
        "currentPhase": "COMPLETED",
        "cache": {
            "type": "NO_CACHE"
        },
        "source": {
            "insecureSsl": false,
            "location": "codebuild-us-west-2-123456789012-input-bucket/my-source.zip",
            "type": "S3"
        },
        "id": "my-demo-project:1a2b3c4d-5678-90ab-cdef-11111EXAMPLE",
        "endTime": 1556906974.781,
        "phases": [
            {
                "durationInSeconds": 0,
                "phaseType": "SUBMITTED",
                "endTime": 1556906956.935,
                "phaseStatus": "SUCCEEDED",
                "startTime": 1556906956.318
            },
            {
                "durationInSeconds": 1,
                "phaseType": "QUEUED",
                "endTime": 1556906958.272,
                "phaseStatus": "SUCCEEDED",
                "startTime": 1556906956.935
            },
            {
                "phaseType": "PROVISIONING",
                "phaseStatus": "SUCCEEDED",
                "durationInSeconds": 14,
                "contexts": [
                    {
                        "message": "",
                        "statusCode": ""
                    }
                ],
                "endTime": 1556906972.847,
                "startTime": 1556906958.272
            },
            {
                "phaseType": "DOWNLOAD_SOURCE",
                "phaseStatus": "SUCCEEDED",
                "durationInSeconds": 0,
                "contexts": [
                        {
                        "message": "",
                        "statusCode": ""
                    }
                ],
                "endTime": 1556906973.552,
                "startTime": 1556906972.847
            },
            {
                "phaseType": "INSTALL",
                "phaseStatus": "SUCCEEDED",
                "durationInSeconds": 0,
                "contexts": [
                    {
                        "message": "",
                        "statusCode": ""
                    }
                ],
                "endTime": 1556906973.75,
                "startTime": 1556906973.552
            },
            {
                "phaseType": "PRE_BUILD",
                "phaseStatus": "SUCCEEDED",
                "durationInSeconds": 0,
                "contexts": [
                    {
                        "message": "",
                        "statusCode": ""
                    }
                ],
                "endTime": 1556906973.937,
                "startTime": 1556906973.75
            },
            {
                "durationInSeconds": 0,
                "phaseType": "BUILD",
                "endTime": 1556906974.781,
                "phaseStatus": "STOPPED",
                "startTime": 1556906973.937
            },
            {
                "phaseType": "COMPLETED",
                "startTime": 1556906974.781
            }
        ],
        "artifacts": {
            "location": "arn:aws:s3:::artifacts-override/my-demo-project",
            "encryptionDisabled": false,
            "overrideArtifactName": true
        },
        "buildComplete": true,
        "buildStatus": "STOPPED",
        "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
        "serviceRole": "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role",
        "queuedTimeoutInMinutes": 5,
        "timeoutInMinutes": 60,
        "environment": {
            "type": "LINUX_CONTAINER",
            "environmentVariables": [],
            "computeType": "BUILD_GENERAL1_MEDIUM",
            "privilegedMode": false,
            "image": "aws/codebuild/standard:1.0",
            "imagePullCredentialsType": "CODEBUILD"
        },
        "logs": {
            "streamName": "1a2b3c4d-5678-90ab-cdef-11111EXAMPLE",
            "deepLink": "https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#logEvent:group=/aws/codebuild/my-demo-project;stream=1a2b3c4d-5678-90ab-cdef-11111EXAMPLE",
            "groupName": "/aws/codebuild/my-demo-project"
        },
        "arn": "arn:aws:codebuild:us-west-2:123456789012:build/my-demo-project:1a2b3c4d-5678-90ab-cdef-11111EXAMPLE"
    }
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドの停止 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/stop-build.html#stop-build-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/stop-build.html)」を参照してください。

### `update-project`
<a name="codebuild_UpdateProject_cli_2_topic"></a>

次の例は、`update-project` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild ビルドプロジェクトの設定を変更するには。**  
次の `update-project`の例では、my-demo-project という名前の指定された CodeBuild ビルドプロジェクトの設定を変更します。  

```
aws codebuild update-project --name "my-demo-project" \
    --description "This project is updated" \
    --source "{\"type\": \"S3\",\"location\": \"codebuild-us-west-2-123456789012-input-bucket/my-source-2.zip\"}" \
    --artifacts {"\"type\": \"S3\",\"location\": \"codebuild-us-west-2-123456789012-output-bucket-2\""} \
    --environment "{\"type\": \"LINUX_CONTAINER\",\"image\": \"aws/codebuild/standard:1.0\",\"computeType\": \"BUILD_GENERAL1_MEDIUM\"}" \
    --service-role "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role"
```
出力には、更新された設定が表示されます。  

```
{
    "project": {
        "arn": "arn:aws:codebuild:us-west-2:123456789012:project/my-demo-project",
        "environment": {
            "privilegedMode": false,
            "environmentVariables": [],
            "type": "LINUX_CONTAINER",
            "image": "aws/codebuild/standard:1.0",
            "computeType": "BUILD_GENERAL1_MEDIUM",
            "imagePullCredentialsType": "CODEBUILD"
        },
        "queuedTimeoutInMinutes": 480,
        "description": "This project is updated",
        "artifacts": {
            "packaging": "NONE",
            "name": "my-demo-project",
            "type": "S3",
            "namespaceType": "NONE",
            "encryptionDisabled": false,
            "location": "codebuild-us-west-2-123456789012-output-bucket-2"
        },
        "encryptionKey": "arn:aws:kms:us-west-2:123456789012:alias/aws/s3",
        "badge": {
            "badgeEnabled": false
        },
        "serviceRole": "arn:aws:iam::123456789012:role/service-role/my-codebuild-service-role",
        "lastModified": 1556840545.967,
        "tags": [],
        "timeoutInMinutes": 60,
        "created": 1556839783.274,
        "name": "my-demo-project",
        "cache": {
            "type": "NO_CACHE"
        },
        "source": {
            "type": "S3",
            "insecureSsl": false,
            "location": "codebuild-us-west-2-123456789012-input-bucket/my-source-2.zip"
        }
    }
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドプロジェクトの設定の変更 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/change-project.html#change-project-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/update-project.html)」を参照してください。

### `update-report-group`
<a name="codebuild_UpdateReportGroup_cli_2_topic"></a>

次の例は、`update-report-group` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild でレポートグループを更新するには。**  
次の `update-report-group` の例では、レポートグループのエクスポートタイプを「NO\$1EXPORT」に変更します。  

```
aws codebuild update-report-group \
    --arn arn:aws:codebuild:<region-ID>:<user-ID>:report-group/cli-created-report-group \
    --export-config="exportConfigType=NO_EXPORT"
```
出力:  

```
{
    "reportGroup": {
        "arn": "arn:aws:codebuild:<region-ID>:<user-ID>:report-group/cli-created-report-group",
        "name": "cli-created-report-group",
        "type": "TEST",
        "exportConfig": {
            "exportConfigType": "NO_EXPORT"
        },
        "created": 1602020686.009,
        "lastModified": 1602021033.454,
        "tags": []
    }
}
```
詳細については、「*AWS CodeBuild ユーザーガイド*」の「[Working with report groups](https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateReportGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/update-report-group.html)」を参照してください。

### `update-webhook`
<a name="codebuild_UpdateWebhook_cli_2_topic"></a>

次の例は、`update-webhook` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeBuild プロジェクトのウェブフックを更新するには**  
次の `update-webhook` の例では、2 つのフィルタグループを使用して、指定された CodeBuild プロジェクトのウェブフックを更新します。`--rotate-secret` パラメータは、コード変更によってビルドがトリガーされるたびに GitHub がプロジェクトのシークレットキーをローテーションするように指定します。最初のフィルタグループでは、正規表現 `^refs/heads/master$` と一致する Git 参照名および `^refs/heads/myBranch$` と一致するヘッド参照を持つブランチに対してプルリクエストを作成、更新、または再開することを指定します。2 番目のフィルタグループでは、正規表現 `^refs/heads/myBranch$` と一致しない Git 参照名を持つブランチでプッシュリクエストを指定します。  

```
aws codebuild update-webhook \
    --project-name Project2 \
    --rotate-secret \
    --filter-groups "[[{\"type\":\"EVENT\",\"pattern\":\"PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED\"},{\"type\":\"HEAD_REF\",\"pattern\":\"^refs/heads/myBranch$\",\"excludeMatchedPattern\":true},{\"type\":\"BASE_REF\",\"pattern\":\"^refs/heads/master$\",\"excludeMatchedPattern\":true}],[{\"type\":\"EVENT\",\"pattern\":\"PUSH\"},{\"type\":\"HEAD_REF\",\"pattern\":\"^refs/heads/myBranch$\",\"excludeMatchedPattern\":true}]]"
```
出力:  

```
{
    "webhook": {
        "filterGroups": [
            [
                {
                    "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED",
                    "type": "EVENT"
                },
                {
                    "excludeMatchedPattern": true,
                    "pattern": "refs/heads/myBranch$",
                    "type": "HEAD_REF"
                },
                {
                    "excludeMatchedPattern": true,
                    "pattern": "refs/heads/master$",
                    "type": "BASE_REF"
                }
            ],
            [
                {
                    "pattern": "PUSH",
                    "type": "EVENT"
                },
                {
                    "excludeMatchedPattern": true,
                    "pattern": "refs/heads/myBranch$",
                    "type": "HEAD_REF"
                }
            ]
        ],
        "lastModifiedSecret": 1556312220.133
    }
}
```
詳細については、*AWS 「 CodeBuild ユーザーガイド*[」の「ビルドプロジェクトの設定の変更 (AWS CLI)](https://docs.aws.amazon.com/codebuild/latest/userguide/change-project.html#change-project-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWebhook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/update-webhook.html)」を参照してください。

# を使用した CodeCommit の例 AWS CLI
<a name="cli_2_codecommit_code_examples"></a>

次のコード例は、CodeCommit AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-approval-rule-template-with-repository`
<a name="codecommit_AssociateApprovalRuleTemplateWithRepository_cli_2_topic"></a>

次のコード例は、`associate-approval-rule-template-with-repository` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートをリポジトリに関連付けるには**  
次の `associate-approval-rule-template-with-repository` の例では、指定された承認ルールテンプレートを `MyDemoRepo` という名前のリポジトリに関連付けます。  

```
aws codecommit associate-approval-rule-template-with-repository \
    --repository-name MyDemoRepo  \
    --approval-rule-template-name 2-approver-rule-for-main
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Associate an Approval Rule Template with a Repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-associate-template.html#associate-template-repository)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateApprovalRuleTemplateWithRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/associate-approval-rule-template-with-repository.html)」を参照してください。

### `batch-associate-approval-rule-template-with-repositories`
<a name="codecommit_BatchAssociateApprovalRuleTemplateWithRepositories_cli_2_topic"></a>

次のコード例は、`batch-associate-approval-rule-template-with-repositories` を使用する方法を示しています。

**AWS CLI**  
**1 回のオペレーションで複数のリポジトリに承認ルールテンプレートを関連付けるには**  
次の `batch-associate-approval-rule-template-with-repositories` の例では、指定された承認ルールテンプレートを `MyDemoRepo` および `MyOtherDemoRepo` という名前のリポジトリに関連付けます。  
注: 承認ルールテンプレートは、作成された AWS リージョンに固有です。それらのリポジトリは、その AWS リージョンのリポジトリにのみ関連付けることができます。  

```
aws codecommit batch-associate-approval-rule-template-with-repositories \
    --repository-names MyDemoRepo, MyOtherDemoRepo  \
    --approval-rule-template-name 2-approver-rule-for-main
```
出力:  

```
{
    "associatedRepositoryNames": [
        "MyDemoRepo",
        "MyOtherDemoRepo"
    ],
    "errors": []
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Associate an Approval Rule Template with a Repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-associate-template.html#batch-associate-template-repositories)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchAssociateApprovalRuleTemplateWithRepositories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/batch-associate-approval-rule-template-with-repositories.html)」を参照してください。

### `batch-describe-merge-conflicts`
<a name="codecommit_BatchDescribeMergeConflicts_cli_2_topic"></a>

次のコード例は、`batch-describe-merge-conflicts` を使用する方法を示しています。

**AWS CLI**  
**2 つのコミット識別子間のマージにおいて、すべてのファイルまたはファイルのサブセットにあるマージ競合についての情報を取得するには**  
次の `batch-describe-merge-conflicts` の例では、`feature-randomizationfeature` という名前の送信元ブランチと `main` という名前の送信先ブランチを `MyDemoRepo` という名前のリポジトリで `THREE_WAY_MERGE` 戦略を使用してマージするときのマージ競合を判断します。  

```
aws codecommit batch-describe-merge-conflicts \
    --source-commit-specifier feature-randomizationfeature \
    --destination-commit-specifier main \
    --merge-option THREE_WAY_MERGE \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "conflicts": [
        {
            "conflictMetadata": {
                "filePath": "readme.md",
                "fileSizes": {
                    "source": 139,
                    "destination": 230,
                    "base": 85
                },
                "fileModes": {
                    "source": "NORMAL",
                    "destination": "NORMAL",
                    "base": "NORMAL"
                },
                "objectTypes": {
                    "source": "FILE",
                    "destination": "FILE",
                    "base": "FILE"
                },
                "numberOfConflicts": 1,
                "isBinaryFile": {
                    "source": false,
                    "destination": false,
                    "base": false
                },
                "contentConflict": true,
                "fileModeConflict": false,
                "objectTypeConflict": false,
                "mergeOperations": {
                    "source": "M",
                    "destination": "M"
                }
            },
            "mergeHunks": [
                {
                    "isConflict": true,
                    "source": {
                        "startLine": 0,
                        "endLine": 3,
                        "hunkContent": "VGhpcyBpEXAMPLE=="
                    },
                    "destination": {
                        "startLine": 0,
                        "endLine": 1,
                        "hunkContent": "VXNlIHRoEXAMPLE="
                    }
                }
            ]
        }
    ],
    "errors": [],
    "destinationCommitId": "86958e0aEXAMPLE",
    "sourceCommitId": "6ccd57fdEXAMPLE",
    "baseCommitId": "767b6958EXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Resolve Conflicts in a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-resolve-conflict-pull-request.html#batch-describe-merge-conflicts)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDescribeMergeConflicts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/batch-describe-merge-conflicts.html)」を参照してください。

### `batch-disassociate-approval-rule-template-from-repositories`
<a name="codecommit_BatchDisassociateApprovalRuleTemplateFromRepositories_cli_2_topic"></a>

次のコード例は、`batch-disassociate-approval-rule-template-from-repositories` を使用する方法を示しています。

**AWS CLI**  
**1 回のオペレーションで複数のリポジトリから承認ルールテンプレートの関連付けを解除するには**  
次の `batch-disassociate-approval-rule-template-from-repositories` の例では、指定された承認ルールテンプレートと `MyDemoRepo` および `MyOtherDemoRepo` という名前のリポジトリとの関連付けを解除します。  

```
aws codecommit batch-disassociate-approval-rule-template-from-repositories \
    --repository-names MyDemoRepo, MyOtherDemoRepo  \
    --approval-rule-template-name 1-approval-rule-for-all pull requests
```
出力:  

```
{
    "disassociatedRepositoryNames": [
        "MyDemoRepo",
        "MyOtherDemoRepo"
    ],
    "errors": []
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Disassociate an Approval Rule Template](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-disassociate-template.html#batch-disassociate-template)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDisassociateApprovalRuleTemplateFromRepositories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/batch-disassociate-approval-rule-template-from-repositories.html)」を参照してください。

### `batch-get-commits`
<a name="codecommit_BatchGetCommits_cli_2_topic"></a>

次のコード例は、`batch-get-commits` を使用する方法を示しています。

**AWS CLI**  
**複数のコミットに関する情報を表示するには**  
次の `batch-get-commits` の例では、指定されたコミットの詳細情報を表示します。  

```
aws codecommit batch-get-commits  \
    --repository-name MyDemoRepo  \
    --commit-ids 317f8570EXAMPLE 4c925148EXAMPLE
```
出力:  

```
{
    "commits": [
      {
        "additionalData": "",
        "committer": {
            "date": "1508280564 -0800",
            "name": "Mary Major",
            "email": "mary_major@example.com"
        },
        "author": {
            "date": "1508280564 -0800",
            "name": "Mary Major",
            "email": "mary_major@example.com"
        },
        "commitId": "317f8570EXAMPLE",
        "treeId": "1f330709EXAMPLE",
        "parents": [
            "6e147360EXAMPLE"
        ],
        "message": "Change variable name and add new response element"
    },
    {
        "additionalData": "",
        "committer": {
            "date": "1508280542 -0800",
            "name": "Li Juan",
            "email": "li_juan@example.com"
        },
        "author": {
            "date": "1508280542 -0800",
            "name": "Li Juan",
            "email": "li_juan@example.com"
        },
        "commitId": "4c925148EXAMPLE",
        "treeId": "1f330709EXAMPLE",
        "parents": [
            "317f8570EXAMPLE"
        ],
        "message": "Added new class"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[View Commit Details](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-view-commit-details.html#how-to-view-commit-details-cli-batch-get-commits)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetCommits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/batch-get-commits.html)」を参照してください。

### `batch-get-repositories`
<a name="codecommit_BatchGetRepositories_cli_2_topic"></a>

次のコード例は、`batch-get-repositories` を使用する方法を示しています。

**AWS CLI**  
**複数のリポジトリの詳細情報を表示するには**  
この例では、multiple AWS CodeCommit リポジトリの詳細を示しています。  

```
aws codecommit batch-get-repositories \
    --repository-names MyDemoRepo MyOtherDemoRepo
```
出力:  

```
{
    "repositoriesNotFound": [],
    "repositories": [
         {
            "creationDate": 1429203623.625,
            "defaultBranch": "main",
            "repositoryName": "MyDemoRepo",
            "cloneUrlSsh": "ssh://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyDemoRepo",
            "lastModifiedDate": 1430783812.0869999,
            "repositoryDescription": "My demonstration repository",
            "cloneUrlHttp": "https://codecommit.us-east-2.amazonaws.com/v1/repos/MyDemoRepo",
            "repositoryId": "f7579e13-b83e-4027-aaef-650c0EXAMPLE",
            "Arn": "arn:aws:codecommit:us-east-2:111111111111:MyDemoRepo"
            "accountId": "111111111111"
        },
        {
            "creationDate": 1429203623.627,
            "defaultBranch": "main",
            "repositoryName": "MyOtherDemoRepo",
            "cloneUrlSsh": "ssh://git-codecommit.us-east-2.amazonaws.com/v1/repos/MyOtherDemoRepo",
            "lastModifiedDate": 1430783812.0889999,
            "repositoryDescription": "My other demonstration repository",
            "cloneUrlHttp": "https://codecommit.us-east-2.amazonaws.com/v1/repos/MyOtherDemoRepo",
            "repositoryId": "cfc29ac4-b0cb-44dc-9990-f6f51EXAMPLE",
            "Arn": "arn:aws:codecommit:us-east-2:111111111111:MyOtherDemoRepo"
            "accountId": "111111111111"
        }
    ],
    "repositoriesNotFound": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetRepositories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/batch-get-repositories.html)」を参照してください。

### `create-approval-rule-template`
<a name="codecommit_CreateApprovalRuleTemplate_cli_2_topic"></a>

次のコード例は、`create-approval-rule-template` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートを作成するには**  
次の `create-approval-rule-template` の例では、`2-approver-rule-for-main ``. The template requires two users who assume the role of ``CodeCommitReview` という名前の承認ルールテンプレートを作成し、`main` ブランチにマージする前にプルリクエストを承認します。  

```
aws codecommit create-approval-rule-template \
    --approval-rule-template-name 2-approver-rule-for-main \
    --approval-rule-template-description  "Requires two developers from the team to approve the pull request if the destination branch is main" \
    --approval-rule-template-content "{\"Version\": \"2018-11-08\",\"DestinationReferences\": [\"refs/heads/main\"],\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}"
```
出力:  

```
{
    "approvalRuleTemplate": {
        "approvalRuleTemplateName": "2-approver-rule-for-main",
        "creationDate": 1571356106.936,
        "approvalRuleTemplateId": "dd8b17fe-EXAMPLE",
        "approvalRuleTemplateContent": "{\"Version\": \"2018-11-08\",\"DestinationReferences\": [\"refs/heads/main\"],\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
        "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
        "approvalRuleTemplateDescription": "Requires two developers from the team to approve the pull request if the destination branch is main",
        "lastModifiedDate": 1571356106.936,
        "ruleContentSha256": "4711b576EXAMPLE"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Create an Approval Rule Template](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-template.html#create-template-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApprovalRuleTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/create-approval-rule-template.html)」を参照してください。

### `create-branch`
<a name="codecommit_CreateBranch_cli_2_topic"></a>

次のコード例は、`create-branch` を使用する方法を示しています。

**AWS CLI**  
**ブランチを作成するには**  
この例では、 AWS CodeCommit リポジトリにブランチを作成します。このコマンドは、エラーがある場合にのみ出力を生成します。  
コマンド:  

```
aws codecommit create-branch --repository-name MyDemoRepo --branch-name MyNewBranch --commit-id 317f8570EXAMPLE
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBranch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/create-branch.html)」を参照してください。

### `create-commit`
<a name="codecommit_CreateCommit_cli_2_topic"></a>

次のコード例は、`create-commit` を使用する方法を示しています。

**AWS CLI**  
**コミットを作成するには**  
次の `create-commit` の例では、`main` ブランチの `MyDemoRepo` という名前のリポジトリに `readme.md` ファイルを追加する、リポジトリの初期コミットを作成する方法を示します。  

```
aws codecommit create-commit \
    --repository-name MyDemoRepo \
    --branch-name main \
    --put-files "filePath=readme.md,fileContent='Welcome to our team repository.'"
```
出力:  

```
{
    "filesAdded": [
        {
            "blobId": "5e1c309d-EXAMPLE",
            "absolutePath": "readme.md",
            "fileMode": "NORMAL"
        }
    ],
    "commitId": "4df8b524-EXAMPLE",
    "treeId": "55b57003-EXAMPLE",
    "filesDeleted": [],
    "filesUpdated": []
}
```
詳細については、[「 AWS CodeCommit ユーザーガイド」の「Create a Commit inCodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-commit.html#how-to-create-commit-cli)*AWS CodeCommit*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCommit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/create-commit.html)」を参照してください。

### `create-pull-request-approval-rule`
<a name="codecommit_CreatePullRequestApprovalRule_cli_2_topic"></a>

次のコード例は、`create-pull-request-approval-rule` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの承認ルールを作成するには**  
次の `create-pull-request-approval-rule` の例では、指定されたプルリクエストに `Require two approved approvers` という名前の承認ルールを作成します。このルールは、承認プールから 2 つの承認が必要であることを指定しています。プールには、`123456789012` AWS アカウント`CodeCommitReview`で のロールを引き受けて CodeCommit にアクセスするすべてのユーザーが含まれます。また、同じ AWS アカウント`Nikhil_Jayashankar`から という名前の IAM ユーザーまたはフェデレーティッドユーザーも含まれます。  

```
aws codecommit create-pull-request-approval-rule  \
    --approval-rule-name "Require two approved approvers"  \
    --approval-rule-content "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"CodeCommitApprovers:123456789012:Nikhil_Jayashankar\", \"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}"
```
出力:  

```
{
    "approvalRule": {
        "approvalRuleName": "Require two approved approvers",
        "lastModifiedDate": 1570752871.932,
        "ruleContentSha256": "7c44e6ebEXAMPLE",
        "creationDate": 1570752871.932,
        "approvalRuleId": "aac33506-EXAMPLE",
        "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"CodeCommitApprovers:123456789012:Nikhil_Jayashankar\", \"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
        "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Create an Approval Rule](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-pull-request-approval-rule.html#how-to-create-pull-request-approval-rule-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePullRequestApprovalRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/create-pull-request-approval-rule.html)」を参照してください。

### `create-pull-request`
<a name="codecommit_CreatePullRequest_cli_2_topic"></a>

次のコード例は、`create-pull-request` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストを作成するには**  
次の`create-pull-request`例では、「Jane-branch」ソースブランチをターゲットとし、MyDemoRepo」という名前の AWS CodeCommit リポジトリのデフォルトブランチ「main」にマージする「Pronunciation difficulty Analyzer」という名前のプルリクエストを作成します。  

```
aws codecommit create-pull-request \
    --title "My Pull Request" \
    --description "Please review these changes by Tuesday" \
    --client-request-token 123Example \
    --targets repositoryName=MyDemoRepo,sourceReference=MyNewBranch
```
出力:  

```
{
    "pullRequest": {
        "approvalRules": [
            {
                "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"DestinationReferences\": [\"refs/heads/main\"],\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
                "approvalRuleId": "dd8b17fe-EXAMPLE",
                "approvalRuleName": "2-approver-rule-for-main",
                "creationDate": 1571356106.936,
                "lastModifiedDate": 571356106.936,
                "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
                "originApprovalRuleTemplate": {
                    "approvalRuleTemplateId": "dd3d22fe-EXAMPLE",
                    "approvalRuleTemplateName": "2-approver-rule-for-main"
                },
                "ruleContentSha256": "4711b576EXAMPLE"
            }
        ],
        "authorArn": "arn:aws:iam::111111111111:user/Jane_Doe",
        "description": "Please review these changes by Tuesday",
        "title": "Pronunciation difficulty analyzer",
        "pullRequestTargets": [
            {
                "destinationCommit": "5d036259EXAMPLE",
                "destinationReference": "refs/heads/main",
                "repositoryName": "MyDemoRepo",
                "sourceCommit": "317f8570EXAMPLE",
                "sourceReference": "refs/heads/jane-branch",
                "mergeMetadata": {
                    "isMerged": false
                }
            }
        ],
        "lastActivityDate": 1508962823.285,
        "pullRequestId": "42",
        "clientRequestToken": "123Example",
        "pullRequestStatus": "OPEN",
        "creationDate": 1508962823.285
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePullRequest](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/create-pull-request.html)」を参照してください。

### `create-repository`
<a name="codecommit_CreateRepository_cli_2_topic"></a>

次のコード例は、`create-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリを作成するには**  
この例では、リポジトリを作成し、ユーザーの AWS アカウントに関連付けます。  
コマンド:  

```
aws codecommit create-repository --repository-name MyDemoRepo --repository-description "My demonstration repository"
```
出力:  

```
{
    "repositoryMetadata": {
        "repositoryName": "MyDemoRepo",
                "cloneUrlSsh": "ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo",
                "lastModifiedDate": 1444766838.027,
        "repositoryDescription": "My demonstration repository",
                "cloneUrlHttp": "https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo",
        "repositoryId": "f7579e13-b83e-4027-aaef-650c0EXAMPLE",
                "Arn": "arn:aws:codecommit:us-east-1:111111111111EXAMPLE:MyDemoRepo",
        "accountId": "111111111111"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/create-repository.html)」を参照してください。

### `create-unreferenced-merge-commit`
<a name="codecommit_CreateUnreferencedMergeCommit_cli_2_topic"></a>

次のコード例は、`create-unreferenced-merge-commit` を使用する方法を示しています。

**AWS CLI**  
**2 つのコミット指定子をマージした結果を表す非参照コミットを作成するには**  
次の `create-unreferenced-merge-commit` の例では、`MyDemoRepo` という名前のリポジトリで THREE\$1WAY\$1MERGE 戦略を使用して、`bugfix-1234` という名前の送信元ブランチと `main` という名前の送信先ブランチ間のマージ結果を表すコミットを作成します。  

```
aws codecommit create-unreferenced-merge-commit \
    --source-commit-specifier bugfix-1234 \
    --destination-commit-specifier main \
    --merge-option THREE_WAY_MERGE \
    --repository-name MyDemoRepo \
    --name "Maria Garcia" \
    --email "maria_garcia@example.com" \
    --commit-message "Testing the results of this merge."
```
出力:  

```
{
    "commitId": "4f178133EXAMPLE",
    "treeId": "389765daEXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Resolve Conflicts in a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-resolve-conflict-pull-request.html#batch-describe-merge-conflicts)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUnreferencedMergeCommit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/create-unreferenced-merge-commit.html)」を参照してください。

### `credential-helper`
<a name="codecommit_CredentialHelper_cli_2_topic"></a>

次の例は、`credential-helper` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeCommit を使用して CLI AWS に含まれる認証情報ヘルパーを設定するには**  
`credential-helper` ユーティリティは、 CLI AWS から直接呼び出されるように設計されていません。代わりに、ローカルコンピュータをセットアップするための `git config` コマンドでパラメータとして使用することを目的としています。これにより、Git が CodeCommit リポジトリとやり取り AWS するために を認証する必要があるたびに、Git は HTTPS と暗号化によって署名されたバージョンの IAM ユーザー認証情報または Amazon EC2 インスタンスロールを使用できます。  

```
git config --global credential.helper '!aws codecommit credential-helper $@'
git config --global credential.UseHttpPath true
```
出力:  

```
[credential]
    helper = !aws codecommit credential-helper $@
    UseHttpPath = true
```
詳細については、 AWS 「 CodeCommit *AWS ユーザーガイド」の「他の方法を使用した CodeCommit *のセットアップ」を参照してください。内容を注意深く読み、「*AWS CodeCommit ユーザーガイド*」の「For HTTPS Connections on Linux, macOS, or Unix」または「For HTTPS Connections on Windows」のいずれかのトピックに記載されている手順に従います。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CredentialHelper](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/credential-helper.html)」を参照してください。

### `delete-approval-rule-template`
<a name="codecommit_DeleteApprovalRuleTemplate_cli_2_topic"></a>

次のコード例は、`delete-approval-rule-template` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートを削除するには**  
次の `delete-approval-rule-template` の例では、指定された承認ルールテンプレートを削除します。  

```
aws codecommit delete-approval-rule-template  \
    --approval-rule-template-name 1-approver-for-all-pull-requests
```
出力:  

```
{
    "approvalRuleTemplateId": "41de97b7-EXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Delete an Approval Rule Template](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-delete-template.html#delete-template)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApprovalRuleTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/delete-approval-rule-template.html)」を参照してください。

### `delete-branch`
<a name="codecommit_DeleteBranch_cli_2_topic"></a>

次のコード例は、`delete-branch` を使用する方法を示しています。

**AWS CLI**  
**ブランチを削除するには**  
この例では、 AWS CodeCommit リポジトリでブランチを削除する方法を示します。  
コマンド:  

```
aws codecommit delete-branch --repository-name MyDemoRepo --branch-name MyNewBranch
```
出力:  

```
{
  "branch": {
      "commitId": "317f8570EXAMPLE",
      "branchName": "MyNewBranch"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBranch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/delete-branch.html)」を参照してください。

### `delete-comment-content`
<a name="codecommit_DeleteCommentContent_cli_2_topic"></a>

次のコード例は、`delete-comment-content` を使用する方法を示しています。

**AWS CLI**  
**コメントの内容を削除するには**  
コメントを自分で作成した場合のみコメントのコンテンツを削除できます。この例では、システム生成 ID が `ff30b348EXAMPLEb9aa670f` のコメントの内容を削除する方法を示しています。  

```
aws codecommit delete-comment-content \
    --comment-id ff30b348EXAMPLEb9aa670f
```
出力:  

```
{
    "comment": {
        "creationDate": 1508369768.142,
        "deleted": true,
        "lastModifiedDate": 1508369842.278,
        "clientRequestToken": "123Example",
        "commentId": "ff30b348EXAMPLEb9aa670f",
        "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
        "callerReactions": [],
        "reactionCounts":
        {
            "CLAP" : 1
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCommentContent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/delete-comment-content.html)」を参照してください。

### `delete-file`
<a name="codecommit_DeleteFile_cli_2_topic"></a>

次のコード例は、`delete-file` を使用する方法を示しています。

**AWS CLI**  
**ファイルを削除するには**  
次の `delete-file` の例は、`MyDemoRepo` という名前のリポジトリで、最新のコミット ID が `c5709475EXAMPLE` のブランチ `main` から `README.md` という名前のファイルを削除する方法を示します。  

```
aws codecommit delete-file \
    --repository-name MyDemoRepo \
    --branch-name main \
    --file-path README.md \
    --parent-commit-id c5709475EXAMPLE
```
出力:  

```
{
    "blobId":"559b44fEXAMPLE",
    "commitId":"353cf655EXAMPLE",
    "filePath":"README.md",
    "treeId":"6bc824cEXAMPLE"
}
```
詳細については、[AWS CodeCommit API リファレンスガイドの「Edit or Delete a File inCodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-edit-file.html?shortFooter=true#how-to-edit-file-cli)*AWS CodeCommit*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/delete-file.html)」を参照してください。

### `delete-pull-request-approval-rule`
<a name="codecommit_DeletePullRequestApprovalRule_cli_2_topic"></a>

次のコード例は、`delete-pull-request-approval-rule` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの承認ルールを削除するには**  
次の `delete-pull-request-approval-rule` の例では、指定されたプルリクエストの `My Approval Rule` という名前の承認ルールを削除しています。  

```
aws codecommit delete-pull-request-approval-rule  \
    --approval-rule-name "My Approval Rule"  \
    --pull-request-id 15
```
出力:  

```
{
    "approvalRuleId": "077d8e8a8-EXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Edit or Delete an Approval Rule](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-edit-delete-pull-request-approval-rule.html#delete-pull-request-approval-rule)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePullRequestApprovalRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/delete-pull-request-approval-rule.html)」を参照してください。

### `delete-repository`
<a name="codecommit_DeleteRepository_cli_2_topic"></a>

次のコード例は、`delete-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリを削除するには**  
この例では、 AWS CodeCommit リポジトリを削除する方法を示します。  
コマンド:  

```
aws codecommit delete-repository --repository-name MyDemoRepo
```
出力:  

```
{
  "repositoryId": "f7579e13-b83e-4027-aaef-650c0EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/delete-repository.html)」を参照してください。

### `describe-merge-conflicts`
<a name="codecommit_DescribeMergeConflicts_cli_2_topic"></a>

次のコード例は、`describe-merge-conflicts` を使用する方法を示しています。

**AWS CLI**  
**マージの競合に関する詳細情報を取得するには**  
次の `describe-merge-conflicts` の例では、THREE\$1WAY\$1MERGE 戦略を使用して、指定された送信元ブランチと送信先ブランチで `readme.md` という名前のファイルのマージの競合を判別します。  

```
aws codecommit describe-merge-conflicts \
    --source-commit-specifier feature-randomizationfeature \
    --destination-commit-specifier main \
    --merge-option THREE_WAY_MERGE \
    --file-path readme.md \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "conflictMetadata": {
        "filePath": "readme.md",
        "fileSizes": {
            "source": 139,
            "destination": 230,
            "base": 85
        },
        "fileModes": {
            "source": "NORMAL",
            "destination": "NORMAL",
            "base": "NORMAL"
        },
        "objectTypes": {
            "source": "FILE",
            "destination": "FILE",
            "base": "FILE"
        },
        "numberOfConflicts": 1,
        "isBinaryFile": {
            "source": false,
            "destination": false,
            "base": false
        },
        "contentConflict": true,
        "fileModeConflict": false,
        "objectTypeConflict": false,
        "mergeOperations": {
            "source": "M",
            "destination": "M"
        }
    },
    "mergeHunks": [
        {
            "isConflict": true,
            "source": {
                "startLine": 0,
                "endLine": 3,
                "hunkContent": "VGhpcyBpEXAMPLE="
            },
            "destination": {
                "startLine": 0,
                "endLine": 1,
                "hunkContent": "VXNlIHRoEXAMPLE="
            }
        }
    ],
    "destinationCommitId": "86958e0aEXAMPLE",
    "sourceCommitId": "6ccd57fdEXAMPLE",
    "baseCommitId": "767b69580EXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Resolve Conflicts in a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-resolve-conflict-pull-request.html#describe-merge-conflicts)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMergeConflicts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/describe-merge-conflicts.html)」を参照してください。

### `describe-pull-request-events`
<a name="codecommit_DescribePullRequestEvents_cli_2_topic"></a>

次のコード例は、`describe-pull-request-events` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストのイベントを表示するには**  
次の `describe-pull-request-events` の例では、ID が「8」のプルリクエストのイベントを取得しています。  

```
aws codecommit describe-pull-request-events --pull-request-id 8
```
出力:  

```
{
    "pullRequestEvents": [
        {
            "pullRequestId": "8",
            "pullRequestEventType": "PULL_REQUEST_CREATED",
            "eventDate": 1510341779.53,
            "actor": "arn:aws:iam::111111111111:user/Zhang_Wei"
        },
        {
            "pullRequestStatusChangedEventMetadata": {
                "pullRequestStatus": "CLOSED"
            },
            "pullRequestId": "8",
            "pullRequestEventType": "PULL_REQUEST_STATUS_CHANGED",
            "eventDate": 1510341930.72,
            "actor": "arn:aws:iam::111111111111:user/Jane_Doe"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePullRequestEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/describe-pull-request-events.html)」を参照してください。

### `disassociate-approval-rule-template-from-repository`
<a name="codecommit_DisassociateApprovalRuleTemplateFromRepository_cli_2_topic"></a>

次のコード例は、`disassociate-approval-rule-template-from-repository` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートをリポジトリから関連付け解除するには**  
次の `disassociate-approval-rule-template-from-repository` の例では、指定された承認ルールテンプレートを `MyDemoRepo` という名前のリポジトリから関連付け解除しています。  

```
aws codecommit disassociate-approval-rule-template-from-repository \
    --repository-name MyDemoRepo  \
    --approval-rule-template-name 1-approver-rule-for-all-pull-requests
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Disassociate an Approval Rule Template](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-disassociate-template.html#disassociate-template)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateApprovalRuleTemplateFromRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/disassociate-approval-rule-template-from-repository.html)」を参照してください。

### `evaluate-pull-request-approval-rules`
<a name="codecommit_EvaluatePullRequestApprovalRules_cli_2_topic"></a>

次のコード例は、`evaluate-pull-request-approval-rules` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの承認ルールがすべて満たされているかどうかを評価するには**  
次の `evaluate-pull-request-approval-rules` の例では、指定されたプルリクエストの承認ルールの状態を評価しています。この例では、プルリクエストの承認ルールが満たされていないため、コマンドの出力には `approved` の値として `false` が表示されます。  

```
aws codecommit evaluate-pull-request-approval-rules \
    --pull-request-id 27  \
    --revision-id 9f29d167EXAMPLE
```
出力:  

```
{
    "evaluation": {
        "approved": false,
        "approvalRulesNotSatisfied": [
            "Require two approved approvers"
        ],
        "overridden": false,
        "approvalRulesSatisfied": []
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Merge a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-merge-pull-request.html#evaluate-pull-request-approval-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EvaluatePullRequestApprovalRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/evaluate-pull-request-approval-rules.html)」を参照してください。

### `get-approval-rule-template`
<a name="codecommit_GetApprovalRuleTemplate_cli_2_topic"></a>

次のコード例は、`get-approval-rule-template` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートの内容を取得するには**  
次の `get-approval-rule-template` の例では、`1-approver-rule-for-all-pull-requests` という名前の承認ルールテンプレートの内容を取得しています。  

```
aws codecommit get-approval-rule-template \
    --approval-rule-template-name 1-approver-rule-for-all-pull-requests
```
出力:  

```
{
    "approvalRuleTemplate": {
        "approvalRuleTemplateContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 1,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
        "ruleContentSha256": "621181bbEXAMPLE",
        "lastModifiedDate": 1571356106.936,
        "creationDate": 1571356106.936,
        "approvalRuleTemplateName": "1-approver-rule-for-all-pull-requests",
        "lastModifiedUser": "arn:aws:iam::123456789012:user/Li_Juan",
        "approvalRuleTemplateId": "a29abb15-EXAMPLE",
        "approvalRuleTemplateDescription": "All pull requests must be approved by one developer on the team."
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Manage Approval Rule Templates](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-manage-templates.html#get-template)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApprovalRuleTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-approval-rule-template.html)」を参照してください。

### `get-blob`
<a name="codecommit_GetBlob_cli_2_topic"></a>

次のコード例は、`get-blob` を使用する方法を示しています。

**AWS CLI**  
**Git blob オブジェクトに関する情報を表示するには**  
次の の`get-blob`例では、MyDemoRepo」という名前の CodeCommit リポジトリの ID が「2eb4af3bEXAMPLE」の Git BLOB に関する情報を取得します。 AWS CodeCommit   

```
aws codecommit get-blob  --repository-name MyDemoRepo  --blob-id 2eb4af3bEXAMPLE
```
出力:  

```
{
    "content": "QSBCaW5hcnkgTGFyToEXAMPLE="
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBlob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-blob.html)」を参照してください。

### `get-branch`
<a name="codecommit_GetBranch_cli_2_topic"></a>

次のコード例は、`get-branch` を使用する方法を示しています。

**AWS CLI**  
**ブランチに関する情報を取得するには**  
この例では、 AWS CodeCommit リポジトリ内のブランチに関する情報を取得します。  
コマンド:  

```
aws codecommit get-branch --repository-name MyDemoRepo --branch-name MyNewBranch
```
出力:  

```
{
  "BranchInfo": {
        "commitID": "317f8570EXAMPLE",
                "branchName": "MyNewBranch"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBranch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-branch.html)」を参照してください。

### `get-comment-reactions`
<a name="codecommit_GetCommentReactions_cli_2_topic"></a>

次のコード例は、`get-comment-reactions` を使用する方法を示しています。

**AWS CLI**  
**コメントへの絵文字リアクションを表示するには**  
次の `get-comment-reactions` の例では、ID が `abcd1234EXAMPLEb5678efgh` のコメントに対するすべての絵文字リアクションを一覧表示しています。シェルのフォントが絵文字バージョン 1.0 の表示をサポートしている場合、`emoji` の出力に絵文字が表示されます。  

```
aws codecommit get-comment-reactions \
    --comment-id abcd1234EXAMPLEb5678efgh
```
出力:  

```
{
    "reactionsForComment": {
        [
           {
               "reaction": {
                    "emoji:"??",
                    "shortCode": "thumbsup",
                    "unicode": "U+1F44D"
                },
                "users": [
                    "arn:aws:iam::123456789012:user/Li_Juan",
                    "arn:aws:iam::123456789012:user/Mary_Major",
                    "arn:aws:iam::123456789012:user/Jorge_Souza"
                ]
            },
            {
                "reaction": {
                    "emoji": "??",
                    "shortCode": "thumbsdown",
                    "unicode": "U+1F44E"
                },
                "users": [
                    "arn:aws:iam::123456789012:user/Nikhil_Jayashankar"
                ]
            },
            {
                "reaction": {
                    "emoji": "??",
                    "shortCode": "confused",
                    "unicode": "U+1F615"
                },
                "users": [
                    "arn:aws:iam::123456789012:user/Saanvi_Sarkar"
                ]
            }
        ]
    }
}
```
詳細については、[「 AWS CodeCommit ユーザーガイド」の「コミットに関するコメント inCodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-commit-comment.html#how-to-commit-comment-cli-commit-emoji-view)*AWS CodeCommit*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCommentReactions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-comment-reactions.html)」を参照してください。

### `get-comment`
<a name="codecommit_GetComment_cli_2_topic"></a>

次のコード例は、`get-comment` を使用する方法を示しています。

**AWS CLI**  
**コメントの詳細を表示するには**  
この例では、システム生成コメント ID が `ff30b348EXAMPLEb9aa670f` のコメントの詳細を表示する方法を示しています。  

```
aws codecommit get-comment \
    --comment-id ff30b348EXAMPLEb9aa670f
```
出力:  

```
{
    "comment": {
        "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
        "clientRequestToken": "123Example",
        "commentId": "ff30b348EXAMPLEb9aa670f",
        "content": "Whoops - I meant to add this comment to the line, but I don't see how to delete it.",
        "creationDate": 1508369768.142,
        "deleted": false,
        "commentId": "",
        "lastModifiedDate": 1508369842.278,
        "callerReactions": [],
        "reactionCounts":
        {
            "SMILE" : 6,
            "THUMBSUP" : 1
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-comment.html)」を参照してください。

### `get-comments-for-compared-commit`
<a name="codecommit_GetCommentsForComparedCommit_cli_2_topic"></a>

次のコード例は、`get-comments-for-compared-commit` を使用する方法を示しています。

**AWS CLI**  
**コミットについてのコメントを表示するには**  
この例では、`MyDemoRepo` という名前のリポジトリで 2 つのコミット間の比較に対して作成されたコメントを表示する方法を示しています。  

```
aws codecommit get-comments-for-compared-commit \
    --repository-name MyDemoRepo \
    --before-commit-ID 6e147360EXAMPLE \
    --after-commit-id 317f8570EXAMPLE
```
出力:  

```
{
    "commentsForComparedCommitData": [
        {
            "afterBlobId": "1f330709EXAMPLE",
            "afterCommitId": "317f8570EXAMPLE",
            "beforeBlobId": "80906a4cEXAMPLE",
            "beforeCommitId": "6e147360EXAMPLE",
            "comments": [
                {
                    "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
                    "clientRequestToken": "123Example",
                    "commentId": "ff30b348EXAMPLEb9aa670f",
                    "content": "Whoops - I meant to add this comment to the line, not the file, but I don't see how to delete it.",
                    "creationDate": 1508369768.142,
                    "deleted": false,
                    "CommentId": "123abc-EXAMPLE",
                    "lastModifiedDate": 1508369842.278,
                    "callerReactions": [],
                    "reactionCounts":
                    {
                        "SMILE" : 6,
                        "THUMBSUP" : 1
                    }
                },
                {
                    "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
                    "clientRequestToken": "123Example",
                    "commentId": "553b509bEXAMPLE56198325",
                    "content": "Can you add a test case for this?",
                    "creationDate": 1508369612.240,
                    "deleted": false,
                    "commentId": "456def-EXAMPLE",
                    "lastModifiedDate": 1508369612.240,
                    "callerReactions": [],
                    "reactionCounts":
                    {
                        "THUMBSUP" : 2
                    }
                }
            ],
            "location": {
                "filePath": "cl_sample.js",
                "filePosition": 1232,
                "relativeFileVersion": "after"
            },
            "repositoryName": "MyDemoRepo"
        }
    ],
    "nextToken": "exampleToken"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCommentsForComparedCommit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-comments-for-compared-commit.html)」を参照してください。

### `get-comments-for-pull-request`
<a name="codecommit_GetCommentsForPullRequest_cli_2_topic"></a>

次のコード例は、`get-comments-for-pull-request` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストのコメントを表示するには**  
この例では、`MyDemoRepo` という名前のリポジトリにあるプルリクエストのコメントを表示する方法を示しています。  

```
aws codecommit get-comments-for-pull-request \
    --repository-name MyDemoRepo \
    --before-commit-ID 317f8570EXAMPLE \
    --after-commit-id 5d036259EXAMPLE
```
出力:  

```
{
    "commentsForPullRequestData": [
        {
            "afterBlobId": "1f330709EXAMPLE",
            "afterCommitId": "5d036259EXAMPLE",
            "beforeBlobId": "80906a4cEXAMPLE",
            "beforeCommitId": "317f8570EXAMPLE",
            "comments": [
                {
                    "authorArn": "arn:aws:iam::111111111111:user/Saanvi_Sarkar",
                    "clientRequestToken": "",
                    "commentId": "abcd1234EXAMPLEb5678efgh",
                    "content": "These don't appear to be used anywhere. Can we remove them?",
                    "creationDate": 1508369622.123,
                    "deleted": false,
                    "lastModifiedDate": 1508369622.123,
                    "callerReactions": [],
                    "reactionCounts":
                    {
                        "THUMBSUP" : 6,
                        "CONFUSED" : 1
                    }
                },
                {
                    "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
                    "clientRequestToken": "",
                    "commentId": "442b498bEXAMPLE5756813",
                    "content": "Good catch. I'll remove them.",
                    "creationDate": 1508369829.104,
                    "deleted": false,
                    "lastModifiedDate": 150836912.273,
                    "callerReactions": ["THUMBSUP"]
                    "reactionCounts":
                    {
                        "THUMBSUP" : 14
                    }
                }
            ],
            "location": {
                "filePath": "ahs_count.py",
                "filePosition": 367,
                "relativeFileVersion": "AFTER"
            },
            "repositoryName": "MyDemoRepo",
            "pullRequestId": "42"
        }
    ],
    "nextToken": "exampleToken"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCommentsForPullRequest](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-comments-for-pull-request.html)」を参照してください。

### `get-commit`
<a name="codecommit_GetCommit_cli_2_topic"></a>

次のコード例は、`get-commit` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのコミットに関する情報を表示するには**  
この例では、MyDemoRepo」という名前の AWS CodeCommit リポジトリのシステム生成 ID が「7e9fd3091thisisanexamplethisisanexample1」のコミットの詳細を示します。  
コマンド:  

```
aws codecommit get-commit --repository-name MyDemoRepo --commit-id 7e9fd3091thisisanexamplethisisanexample1
```
出力:  

```
{
  "commit": {
      "additionalData": "",
      "committer": {
          "date": "1484167798 -0800",
          "name": "Mary Major",
          "email": "mary_major@example.com"
      },
      "author": {
          "date": "1484167798 -0800",
          "name": "Mary Major",
          "email": "mary_major@example.com"
      },
      "treeId": "347a3408thisisanexampletreeidexample",
      "parents": [
          "7aa87a031thisisanexamplethisisanexample1"
      ],
      "message": "Fix incorrect variable name"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCommit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-commit.html)」を参照してください。

### `get-differences`
<a name="codecommit_GetDifferences_cli_2_topic"></a>

次のコード例は、`get-differences` を使用する方法を示しています。

**AWS CLI**  
**リポジトリ内のコミット指定子の違いに関する情報を取得するには**  
この例では、MyDemoRepo AWS CodeCommit という名前の新しいフォルダの 2 つのコミット指定子 (ブランチ、タグ、HEAD、またはコミット IDs などの他の完全修飾参照) 間の変更に関するメタデータ情報を表示します。この例では、これらのオプションを使用して結果を制限する方法をより詳細に説明するために、--before-commit-specifier、--before-path、--after-path などの必須ではないオプションがいくつか含まれています。レスポンスには、ファイルモードのアクセス許可が含まれます。  
コマンド:  

```
aws codecommit get-differences --repository-name MyDemoRepo --before-commit-specifier 955bba12thisisanexamplethisisanexample --after-commit-specifier 14a95463thisisanexamplethisisanexample --before-path tmp/example-folder --after-path tmp/renamed-folder
```
出力:  

```
{
  "differences": [
      {
          "afterBlob": {
              "path": "blob.txt",
              "blobId": "2eb4af3b1thisisanexamplethisisanexample1",
              "mode": "100644"
          },
          "changeType": "M",
          "beforeBlob": {
              "path": "blob.txt",
              "blobId": "bf7fcf281thisisanexamplethisisanexample1",
              "mode": "100644"
          }
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDifferences](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-differences.html)」を参照してください。

### `get-file`
<a name="codecommit_GetFile_cli_2_topic"></a>

次の例は、`get-file` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeCommit リポジトリ内のファイルの base-64 でエンコードされたコンテンツを取得するには**  
次の `get-file` の例では、`MyDemoRepo` という名前のリポジトリ内の `main` という名前のブランチから、`README.md` という名前のファイルの base-64 でエンコードされた内容を取得する方法を示しています。  

```
aws codecommit get-file \
    --repository-name MyDemoRepo \
    --commit-specifier main \
    --file-path README.md
```
出力:  

```
{
    "blobId":"559b44fEXAMPLE",
    "commitId":"c5709475EXAMPLE",
    "fileContent":"IyBQaHVzEXAMPLE",
    "filePath":"README.md",
    "fileMode":"NORMAL",
    "fileSize":1563
}
```
詳細については、「*AWS CodeCommit API リファレンス*」ガイドの「[GetFile](https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetFile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-file.html)」を参照してください。

### `get-folder`
<a name="codecommit_GetFolder_cli_2_topic"></a>

次の例は、`get-folder` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeCommit リポジトリ内のフォルダの内容を取得するには**  
次の `get-folder` の例では、`MyDemoRepo` という名前のリポジトリから最上位フォルダの内容を取得する方法を示しています。  

```
aws codecommit get-folder --repository-name MyDemoRepo --folder-path ""
```
出力:  

```
{
    "commitId":"c5709475EXAMPLE",
    "files":[
        {
            "absolutePath":".gitignore",
            "blobId":"74094e8bEXAMPLE",
            "fileMode":"NORMAL",
            "relativePath":".gitignore"
        },
        {
            "absolutePath":"Gemfile",
            "blobId":"9ceb72f6EXAMPLE",
            "fileMode":"NORMAL",
            "relativePath":"Gemfile"
        },
        {
            "absolutePath":"Gemfile.lock",
            "blobId":"795c4a2aEXAMPLE",
            "fileMode":"NORMAL",
            "relativePath":"Gemfile.lock"
        },
        {
            "absolutePath":"LICENSE.txt",
            "blobId":"0c7932c8EXAMPLE",
            "fileMode":"NORMAL",
            "relativePath":"LICENSE.txt"
        },
        {
            "absolutePath":"README.md",
            "blobId":"559b44feEXAMPLE",
            "fileMode":"NORMAL",
            "relativePath":"README.md"
        }
    ],
    "folderPath":"",
    "subFolders":[
        {
            "absolutePath":"public",
            "relativePath":"public",
            "treeId":"d5e92ae3aEXAMPLE"
        },
        {
            "absolutePath":"tmp",
            "relativePath":"tmp",
            "treeId":"d564d0bcEXAMPLE"
        }
    ],
    "subModules":[],
    "symbolicLinks":[],
    "treeId":"7b3c4dadEXAMPLE"
}
```
詳細については、「*AWS CodeCommit API リファレンス*」ガイドの「GetFolder」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFolder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-folder.html)」を参照してください。

### `get-merge-commit`
<a name="codecommit_GetMergeCommit_cli_2_topic"></a>

次のコード例は、`get-merge-commit` を使用する方法を示しています。

**AWS CLI**  
**マージコミットに関する詳細情報を取得するには**  
次の `get-merge-commit` の例では、`MyDemoRepo` という名前のリポジトリで `main` という名前の送信先ブランチと `bugfix-bug1234` という名前の送信元ブランチのマージコミットに関する詳細を表示しています。  

```
aws codecommit get-merge-commit \
    --source-commit-specifier bugfix-bug1234 \
    --destination-commit-specifier main \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "sourceCommitId": "c5709475EXAMPLE",
    "destinationCommitId": "317f8570EXAMPLE",
    "baseCommitId": "fb12a539EXAMPLE",
    "mergeCommitId": "ffc4d608eEXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[View Commit Details](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-view-commit-details.html#how-to-view-commit-details-cli-merge-commit)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMergeCommit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-merge-commit.html)」を参照してください。

### `get-merge-conflicts`
<a name="codecommit_GetMergeConflicts_cli_2_topic"></a>

次のコード例は、`get-merge-conflicts` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストにマージの競合があるかどうかを確認するには**  
次の `get-merge-conflicts` の例では、`feature-randomizationfeature` という名前の送信元ブランチの先端と、`MyDemoRepo` という名前のリポジトリ内の「main」という名前の送信先ブランチの間にマージの競合があるかどうかを示しています。  

```
aws codecommit get-merge-conflicts \
    --repository-name MyDemoRepo \
    --source-commit-specifier feature-randomizationfeature \
    --destination-commit-specifier main \
    --merge-option THREE_WAY_MERGE
```
出力:  

```
{
    "mergeable": false,
    "destinationCommitId": "86958e0aEXAMPLE",
    "sourceCommitId": "6ccd57fdEXAMPLE",
    "baseCommitId": "767b6958EXAMPLE",
    "conflictMetadataList": [
        {
            "filePath": "readme.md",
            "fileSizes": {
                "source": 139,
                "destination": 230,
                "base": 85
            },
            "fileModes": {
                "source": "NORMAL",
                "destination": "NORMAL",
                "base": "NORMAL"
            },
            "objectTypes": {
                "source": "FILE",
                "destination": "FILE",
                "base": "FILE"
            },
            "numberOfConflicts": 1,
            "isBinaryFile": {
                "source": false,
                "destination": false,
                "base": false
            },
            "contentConflict": true,
            "fileModeConflict": false,
            "objectTypeConflict": false,
            "mergeOperations": {
                "source": "M",
                "destination": "M"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMergeConflicts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-merge-conflicts.html)」を参照してください。

### `get-merge-options`
<a name="codecommit_GetMergeOptions_cli_2_topic"></a>

次のコード例は、`get-merge-options` を使用する方法を示しています。

**AWS CLI**  
**指定した 2 つのブランチのマージに使用できるマージオプションに関する情報を取得するには**  
次の `get-merge-options` の例では、`MyDemoRepo` という名前のリポジトリ内の `main` という名前の送信先ブランチに `bugfix-bug1234` という名前の送信元ブランチをマージするために使用できるマージオプションを決定しています。  

```
aws codecommit get-merge-options \
    --source-commit-specifier bugfix-bug1234 \
    --destination-commit-specifier main \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "mergeOptions": [
        "FAST_FORWARD_MERGE",
        "SQUASH_MERGE",
        "THREE_WAY_MERGE"
    ],
    "sourceCommitId": "18059494EXAMPLE",
    "destinationCommitId": "ffd3311dEXAMPLE",
    "baseCommitId": "ffd3311dEXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Resolve Conflicts in a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-resolve-conflict-pull-request.html#get-merge-options)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMergeOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-merge-options.html)」を参照してください。

### `get-pull-request-approval-states`
<a name="codecommit_GetPullRequestApprovalStates_cli_2_topic"></a>

次のコード例は、`get-pull-request-approval-states` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの承認を表示するには**  
次の `get-pull-request-approval-states` の例では、指定されたプルリクエストの承認を返しています。  

```
aws codecommit get-pull-request-approval-states \
    --pull-request-id 8 \
    --revision-id 9f29d167EXAMPLE
```
出力:  

```
{
    "approvals": [
        {
            "userArn": "arn:aws:iam::123456789012:user/Mary_Major",
            "approvalState": "APPROVE"
        }
    ]
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[View Pull Requests](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-view-pull-request.html#get-pull-request-approval-state)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPullRequestApprovalStates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-pull-request-approval-states.html)」を参照してください。

### `get-pull-request-override-state`
<a name="codecommit_GetPullRequestOverrideState_cli_2_topic"></a>

次のコード例は、`get-pull-request-override-state` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの上書きステータスに関する情報を取得するには**  
次の `get-pull-request-override-state` の例では、指定されたプルリクエストの上書きステータスを返しています。この例では、プルリクエストの承認ルールが Mary Major という名前のユーザーによって上書きされたため、出力は `true` の値を返します。  

```
aws codecommit get-pull-request-override-state \
    --pull-request-id 34  \
    --revision-id 9f29d167EXAMPLE
```
出力:  

```
{
    "overridden": true,
    "overrider": "arn:aws:iam::123456789012:user/Mary_Major"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Override Approval Rules on a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-override-approval-rules.html#get-override-status)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPullRequestOverrideState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-pull-request-override-state.html)」を参照してください。

### `get-pull-request`
<a name="codecommit_GetPullRequest_cli_2_topic"></a>

次のコード例は、`get-pull-request` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの詳細を表示するには**  
この例では、ID が `27` のプルリクエストに関する情報を表示する方法を示しています。  

```
aws codecommit get-pull-request \
    --pull-request-id 27
```
出力:  

```
{
    "pullRequest": {
        "approvalRules": [
            {
                "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
                "approvalRuleId": "dd8b17fe-EXAMPLE",
                "approvalRuleName": "2-approver-rule-for-main",
                "creationDate": 1571356106.936,
                "lastModifiedDate": 571356106.936,
                "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
                "ruleContentSha256": "4711b576EXAMPLE"
            }
        ],
        "lastActivityDate": 1562619583.565,
        "pullRequestTargets": [
            {
                "sourceCommit": "ca45e279EXAMPLE",
                "sourceReference": "refs/heads/bugfix-1234",
                "mergeBase": "a99f5ddbEXAMPLE",
                "destinationReference": "refs/heads/main",
                "mergeMetadata": {
                    "isMerged": false
                },
                "destinationCommit": "2abfc6beEXAMPLE",
                "repositoryName": "MyDemoRepo"
            }
        ],
        "revisionId": "e47def21EXAMPLE",
        "title": "Quick fix for bug 1234",
        "authorArn": "arn:aws:iam::123456789012:user/Nikhil_Jayashankar",
        "clientRequestToken": "d8d7612e-EXAMPLE",
        "creationDate": 1562619583.565,
        "pullRequestId": "27",
        "pullRequestStatus": "OPEN"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPullRequest](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-pull-request.html)」を参照してください。

### `get-repository-triggers`
<a name="codecommit_GetRepositoryTriggers_cli_2_topic"></a>

次のコード例は、`get-repository-triggers` を使用する方法を示しています。

**AWS CLI**  
**リポジトリ内のトリガーに関する情報を取得するには**  
この例では、 という名前の AWS CodeCommit リポジトリ用に設定されたトリガーの詳細を示します`MyDemoRepo`。  

```
aws codecommit get-repository-triggers \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "configurationId": "f7579e13-b83e-4027-aaef-650c0EXAMPLE",
    "triggers": [
        {
            "destinationArn": "arn:aws:sns:us-east-1:111111111111:MyCodeCommitTopic",
            "branches": [
                "main",
                "preprod"
            ],
            "name": "MyFirstTrigger",
            "customData": "",
            "events": [
                "all"
            ]
        },
        {
            "destinationArn": "arn:aws:lambda:us-east-1:111111111111:function:MyCodeCommitPythonFunction",
            "branches": [],
            "name": "MySecondTrigger",
            "customData": "EXAMPLE",
            "events": [
                "all"
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRepositoryTriggers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-repository-triggers.html)」を参照してください。

### `get-repository`
<a name="codecommit_GetRepository_cli_2_topic"></a>

次のコード例は、`get-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリに関する情報を取得するには**  
この例では、 AWS CodeCommit リポジトリの詳細を示します。  

```
aws codecommit get-repository \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "repositoryMetadata": {
        "creationDate": 1429203623.625,
        "defaultBranch": "main",
        "repositoryName": "MyDemoRepo",
        "cloneUrlSsh": "ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/v1/repos/MyDemoRepo",
        "lastModifiedDate": 1430783812.0869999,
        "repositoryDescription": "My demonstration repository",
        "cloneUrlHttp": "https://codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo",
        "repositoryId": "f7579e13-b83e-4027-aaef-650c0EXAMPLE",
        "Arn": "arn:aws:codecommit:us-east-1:80398EXAMPLE:MyDemoRepo
        "accountId": "111111111111"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/get-repository.html)」を参照してください。

### `list-approval-rule-templates`
<a name="codecommit_ListApprovalRuleTemplates_cli_2_topic"></a>

次の例は、`list-approval-rule-templates` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョン内のすべての承認ルールテンプレートを一覧表示するには**  
次の `list-approval-rule-templates` の例では、指定されたリージョン内のすべての承認ルールテンプレートを一覧表示しています。 AWS リージョンがパラメータとして指定されていない場合、コマンドはコマンドの実行に使用される CLI AWS プロファイルで指定されたリージョンの承認ルールテンプレートを返します。  

```
aws codecommit list-approval-rule-templates \
    --region us-east-2
```
出力:  

```
{
    "approvalRuleTemplateNames": [
        "2-approver-rule-for-main",
        "1-approver-rule-for-all-pull-requests"
    ]
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Manage Approval Rule Templates](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-manage-templates.html#list-templates)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListApprovalRuleTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/list-approval-rule-templates.html)」を参照してください。

### `list-associated-approval-rule-templates-for-repository`
<a name="codecommit_ListAssociatedApprovalRuleTemplatesForRepository_cli_2_topic"></a>

次のコード例は、`list-associated-approval-rule-templates-for-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリに関連付けられているすべてのテンプレートを一覧表示するには**  
次の `list-associated-approval-rule-templates-for-repository` の例では、`MyDemoRepo` という名前のリポジトリに関連付けられているすべての承認ルールテンプレートを一覧表示しています。  

```
aws codecommit list-associated-approval-rule-templates-for-repository \
    --repository-name MyDemoRepo
```
出力:  

```
{
  "approvalRuleTemplateNames": [
    "2-approver-rule-for-main",
    "1-approver-rule-for-all-pull-requests"
  ]
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Manage Approval Rule Templates](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-manage-templates.html#list-associated-templates)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssociatedApprovalRuleTemplatesForRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/list-associated-approval-rule-templates-for-repository.html)」を参照してください。

### `list-branches`
<a name="codecommit_ListBranches_cli_2_topic"></a>

次のコード例は、`list-branches` を使用する方法を示しています。

**AWS CLI**  
**ブランチ名のリストを表示するには**  
この例では、 AWS CodeCommit リポジトリ内のすべてのブランチ名を一覧表示します。  

```
aws codecommit list-branches \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "branches": [
        "MyNewBranch",
        "main"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBranches](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/list-branches.html)」を参照してください。

### `list-pull-requests`
<a name="codecommit_ListPullRequests_cli_2_topic"></a>

次のコード例は、`list-pull-requests` を使用する方法を示しています。

**AWS CLI**  
**リポジトリでプルリクエストのリストを表示するには**  
この例では、ARN 'arn:aws:iam::111111111111:user/Li\$1Juan' とステータスが 'CLOSED' の IAM ユーザーによって作成されたプルリクエストを、'MyDemoRepo' という名前の an AWS CodeCommit リポジトリに一覧表示する方法を示します。  

```
aws codecommit list-pull-requests --author-arn arn:aws:iam::111111111111:user/Li_Juan --pull-request-status CLOSED --repository-name MyDemoRepo
```
出力:  

```
{
 "nextToken": "",
 "pullRequestIds": ["2","12","16","22","23","35","30","39","47"]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPullRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/list-pull-requests.html)」を参照してください。

### `list-repositories-for-approval-rule-template`
<a name="codecommit_ListRepositoriesForApprovalRuleTemplate_cli_2_topic"></a>

次のコード例は、`list-repositories-for-approval-rule-template` を使用する方法を示しています。

**AWS CLI**  
**テンプレートに関連付けられているすべてのリポジトリを一覧表示するには**  
次の `list-repositories-for-approval-rule-template` の例では、指定された承認ルールテンプレートに関連付けられているすべてのリポジトリを一覧表示しています。  

```
aws codecommit list-repositories-for-approval-rule-template \
    --approval-rule-template-name 2-approver-rule-for-main
```
出力:  

```
{
    "repositoryNames": [
        "MyDemoRepo",
        "MyClonedRepo"
    ]
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Manage Approval Rule Templates](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-manage-templates.html#list-associated-repositories)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRepositoriesForApprovalRuleTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/list-repositories-for-approval-rule-template.html)」を参照してください。

### `list-repositories`
<a name="codecommit_ListRepositories_cli_2_topic"></a>

次のコード例は、`list-repositories` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのリストを表示するには**  
この例では、ユーザーの AWS アカウントに関連付けられているすべての AWS CodeCommit リポジトリを一覧表示します。  
コマンド:  

```
aws codecommit list-repositories
```
出力:  

```
{
  "repositories": [
      {
         "repositoryName": "MyDemoRepo"
         "repositoryId": "f7579e13-b83e-4027-aaef-650c0EXAMPLE",
      },
      {
         "repositoryName": "MyOtherDemoRepo"
         "repositoryId": "cfc29ac4-b0cb-44dc-9990-f6f51EXAMPLE"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRepositories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/list-repositories.html)」を参照してください。

### `list-tags-for-resource`
<a name="codecommit_ListTagsForResource_cli_2_topic"></a>

次の例は、`list-tags-for-resource` を使用する方法を説明しています。

**AWS CLI**  
**リポジトリの AWS タグを表示するには**  
次の `list-tags-for-resource` の例では、指定されたリポジトリのタグキーとタグ値を一覧表示しています。  

```
aws codecommit list-tags-for-resource \
    --resource-arn arn:aws:codecommit:us-west-2:111111111111:MyDemoRepo
```
出力:  

```
{
    "tags": {
        "Status": "Secret",
        "Team": "Saanvi"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[View Tags for a Repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-tag-repository-list.html#how-to-tag-repository-list-cli)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/list-tags-for-resource.html)」を参照してください。

### `merge-branches-by-fast-forward`
<a name="codecommit_MergeBranchesByFastForward_cli_2_topic"></a>

次のコード例は、`merge-branches-by-fast-forward` を使用する方法を示しています。

**AWS CLI**  
**早送りマージ戦略を使用して 2 つのブランチをマージするには**  
次の `merge-branches-by-fast-forward` の例では、指定された送信元ブランチを、`MyDemoRepo` という名前のリポジトリ内の指定された送信先ブランチとマージしています。  

```
aws codecommit merge-branches-by-fast-forward \
    --source-commit-specifier bugfix-bug1234 \
    --destination-commit-specifier bugfix-bug1233 \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "commitId": "4f178133EXAMPLE",
    "treeId": "389765daEXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Compare and Merge Branches](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-compare-branches.html#merge-branches-by-fast-forward)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MergeBranchesByFastForward](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/merge-branches-by-fast-forward.html)」を参照してください。

### `merge-branches-by-squash`
<a name="codecommit_MergeBranchesBySquash_cli_2_topic"></a>

次のコード例は、`merge-branches-by-squash` を使用する方法を示しています。

**AWS CLI**  
**スカッシュマージ戦略を使用して 2 つのブランチをマージするには**  
次の `merge-branches-by-squash` の例では、指定された送信元ブランチを、`MyDemoRepo` という名前のリポジトリ内の指定された送信先ブランチとマージしています。  

```
aws codecommit merge-branches-by-squash \
    --source-commit-specifier bugfix-bug1234 \
    --destination-commit-specifier bugfix-bug1233 \
    --author-name "Maria Garcia" \
    --email "maria_garcia@example.com" \
    --commit-message "Merging two fix branches to prepare for a general patch." \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "commitId": "4f178133EXAMPLE",
    "treeId": "389765daEXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Compare and Merge Branches](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-compare-branches.html#merge-branches-by-squash)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MergeBranchesBySquash](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/merge-branches-by-squash.html)」を参照してください。

### `merge-branches-by-three-way`
<a name="codecommit_MergeBranchesByThreeWay_cli_2_topic"></a>

次のコード例は、`merge-branches-by-three-way` を使用する方法を示しています。

**AWS CLI**  
**3 方向マージ戦略を使用して 2 つのブランチをマージするには**  
次の `merge-branches-by-three-way` の例では、指定された送信元ブランチを、`MyDemoRepo` という名前のリポジトリ内の指定された送信先ブランチとマージしています。  

```
aws codecommit merge-branches-by-three-way \
    --source-commit-specifier main \
    --destination-commit-specifier bugfix-bug1234 \
    --author-name "Jorge Souza" --email "jorge_souza@example.com" \
    --commit-message "Merging changes from main to bugfix branch before additional testing." \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "commitId": "4f178133EXAMPLE",
    "treeId": "389765daEXAMPLE"
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Compare and Merge Branches](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-compare-branches.html#merge-branches-by-three-way)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MergeBranchesByThreeWay](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/merge-branches-by-three-way.html)」を参照してください。

### `merge-pull-request-by-fast-forward`
<a name="codecommit_MergePullRequestByFastForward_cli_2_topic"></a>

次のコード例は、`merge-pull-request-by-fast-forward` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストをマージして閉じるには**  
この例では、`MyDemoRepo` という名前のリポジトリで、ID が「47」、ソースコミット ID が「99132ab0EXAMPLE」のプルリクエストをマージしてクローズする方法を示しています。  

```
aws codecommit merge-pull-request-by-fast-forward \
    --pull-request-id 47 \
    --source-commit-id 99132ab0EXAMPLE \
    --repository-name MyDemoRepo
```
出力:  

```
{
    "pullRequest": {
        "approvalRules": [
            {
                "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 1,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
                "approvalRuleId": "dd8b17fe-EXAMPLE",
                "approvalRuleName": "I want one approver for this pull request",
                "creationDate": 1571356106.936,
                "lastModifiedDate": 571356106.936,
                "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
                "ruleContentSha256": "4711b576EXAMPLE"
            }
        ],
        "authorArn": "arn:aws:iam::123456789012:user/Li_Juan",
        "clientRequestToken": "",
        "creationDate": 1508530823.142,
        "description": "Review the latest changes and updates to the global variables",
        "lastActivityDate": 1508887223.155,
        "pullRequestId": "47",
        "pullRequestStatus": "CLOSED",
        "pullRequestTargets": [
            {
                "destinationCommit": "9f31c968EXAMPLE",
                "destinationReference": "refs/heads/main",
                "mergeMetadata": {
                    "isMerged": true,
                    "mergedBy": "arn:aws:iam::123456789012:user/Mary_Major"
                },
                "repositoryName": "MyDemoRepo",
                "sourceCommit": "99132ab0EXAMPLE",
                "sourceReference": "refs/heads/variables-branch"
            }
        ],
        "title": "Consolidation of global variables"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Merge a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-merge-pull-request.html#merge-pull-request-by-fast-forward)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MergePullRequestByFastForward](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/merge-pull-request-by-fast-forward.html)」を参照してください。

### `merge-pull-request-by-squash`
<a name="codecommit_MergePullRequestBySquash_cli_2_topic"></a>

次のコード例は、`merge-pull-request-by-squash` を使用する方法を示しています。

**AWS CLI**  
**スカッシュマージ戦略を使用してプルリクエストをマージするには**  
次の `merge-pull-request-by-squash` の例では、`MyDemoRepo` という名前のリポジトリで ACCEPT\$1SOURCE の競合解決戦略を使用して、指定されたプルリクエストをマージして閉じています。  

```
aws codecommit merge-pull-request-by-squash \
    --pull-request-id 47 \
    --source-commit-id 99132ab0EXAMPLE \
    --repository-name MyDemoRepo \
    --conflict-detail-level LINE_LEVEL \
    --conflict-resolution-strategy ACCEPT_SOURCE \
    --name "Jorge Souza" --email "jorge_souza@example.com" \
    --commit-message "Merging pull request 47 by squash and accepting source in merge conflicts"
```
出力:  

```
{
    "pullRequest": {
        "approvalRules": [
            {
                "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"DestinationReferences\": [\"refs/heads/main\"],\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
                "approvalRuleId": "dd8b17fe-EXAMPLE",
                "approvalRuleName": "2-approver-rule-for-main",
                "creationDate": 1571356106.936,
                "lastModifiedDate": 571356106.936,
                "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
                "originApprovalRuleTemplate": {
                    "approvalRuleTemplateId": "dd8b17fe-EXAMPLE",
                    "approvalRuleTemplateName": "2-approver-rule-for-main"
                },
                "ruleContentSha256": "4711b576EXAMPLE"
            }
        ],
        "authorArn": "arn:aws:iam::123456789012:user/Li_Juan",
        "clientRequestToken": "",
        "creationDate": 1508530823.142,
        "description": "Review the latest changes and updates to the global variables",
        "lastActivityDate": 1508887223.155,
        "pullRequestId": "47",
        "pullRequestStatus": "CLOSED",
        "pullRequestTargets": [
            {
                "destinationCommit": "9f31c968EXAMPLE",
                "destinationReference": "refs/heads/main",
                "mergeMetadata": {
                    "isMerged": true,
                    "mergedBy": "arn:aws:iam::123456789012:user/Mary_Major"
                },
                "repositoryName": "MyDemoRepo",
                "sourceCommit": "99132ab0EXAMPLE",
                "sourceReference": "refs/heads/variables-branch"
            }
        ],
        "title": "Consolidation of global variables"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Merge a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-merge-pull-request.html#merge-pull-request-by-squash)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MergePullRequestBySquash](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/merge-pull-request-by-squash.html)」を参照してください。

### `merge-pull-request-by-three-way`
<a name="codecommit_MergePullRequestByThreeWay_cli_2_topic"></a>

次のコード例は、`merge-pull-request-by-three-way` を使用する方法を示しています。

**AWS CLI**  
**3 方向マージ戦略を使用してプルリクエストをマージするには**  
次の `merge-pull-request-by-three-way` の例では、`MyDemoRepo` という名前のリポジトリの競合の詳細と競合解決戦略のデフォルトオプションを使用して、指定されたプルリクエストをマージして閉じています。  

```
aws codecommit merge-pull-request-by-three-way \
    --pull-request-id 47 \
    --source-commit-id 99132ab0EXAMPLE \
    --repository-name MyDemoRepo \
    --name "Maria Garcia" \
    --email "maria_garcia@example.com" \
    --commit-message "Merging pull request 47 by three-way with default options"
```
出力:  

```
{
    "pullRequest": {
        "approvalRules": [
            {
                "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"DestinationReferences\": [\"refs/heads/main\"],\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
                "approvalRuleId": "dd8b17fe-EXAMPLE",
                "approvalRuleName": "2-approver-rule-for-main",
                "creationDate": 1571356106.936,
                "lastModifiedDate": 571356106.936,
                "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
                "originApprovalRuleTemplate": {
                    "approvalRuleTemplateId": "dd8b17fe-EXAMPLE",
                    "approvalRuleTemplateName": "2-approver-rule-for-main"
                },
                "ruleContentSha256": "4711b576EXAMPLE"
            }
        ],
        "authorArn": "arn:aws:iam::123456789012:user/Li_Juan",
        "clientRequestToken": "",
        "creationDate": 1508530823.142,
        "description": "Review the latest changes and updates to the global variables",
        "lastActivityDate": 1508887223.155,
        "pullRequestId": "47",
        "pullRequestStatus": "CLOSED",
        "pullRequestTargets": [
            {
                "destinationCommit": "9f31c968EXAMPLE",
                "destinationReference": "refs/heads/main",
                "mergeMetadata": {
                    "isMerged": true,
                    "mergedBy": "arn:aws:iam::123456789012:user/Mary_Major"
                },
                "repositoryName": "MyDemoRepo",
                "sourceCommit": "99132ab0EXAMPLE",
                "sourceReference": "refs/heads/variables-branch"
            }
        ],
        "title": "Consolidation of global variables"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Merge a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-merge-pull-request.html#merge-pull-request-by-three-way)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MergePullRequestByThreeWay](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/merge-pull-request-by-three-way.html)」を参照してください。

### `override-pull-request-approval-rules`
<a name="codecommit_OverridePullRequestApprovalRules_cli_2_topic"></a>

次のコード例は、`override-pull-request-approval-rules` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの承認ルール要件を上書きするには**  
次の `override-pull-request-approval-rules` の例では、指定されたプルリクエストの承認ルールを上書きしています。代わりに上書きを取り消すには、`--override-status` パラメータ値を `REVOKE` に設定します。  

```
aws codecommit override-pull-request-approval-rules \
    --pull-request-id 34  \
    --revision-id 927df8d8EXAMPLE \
    --override-status OVERRIDE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Override Approval Rules on a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-override-approval-rules.html#override-approval-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[OverridePullRequestApprovalRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/override-pull-request-approval-rules.html)」を参照してください。

### `post-comment-for-compared-commit`
<a name="codecommit_PostCommentForComparedCommit_cli_2_topic"></a>

次のコード例は、`post-comment-for-compared-commit` を使用する方法を示しています。

**AWS CLI**  
**コミットに対するコメントを作成するには**  
この例では、`MyDemoRepo` という名前のリポジトリ内の 2 つのコミットを比較して、変更に対するコメント `"Can you add a test case for this?"` を `cl_sample.js` ファイルに追加する方法を示しています。  

```
aws codecommit post-comment-for-compared-commit \
    --repository-name MyDemoRepo \
    --before-commit-id 317f8570EXAMPLE \
    --after-commit-id 5d036259EXAMPLE \
    --client-request-token 123Example \
    --content "Can you add a test case for this?" \
    --location filePath=cl_sample.js,filePosition=1232,relativeFileVersion=AFTER
```
出力:  

```
{
    "afterBlobId": "1f330709EXAMPLE",
    "afterCommitId": "317f8570EXAMPLE",
    "beforeBlobId": "80906a4cEXAMPLE",
    "beforeCommitId": "6e147360EXAMPLE",
    "comment": {
        "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
        "clientRequestToken": "",
        "commentId": "553b509bEXAMPLE56198325",
        "content": "Can you add a test case for this?",
        "creationDate": 1508369612.203,
        "deleted": false,
        "commentId": "abc123-EXAMPLE",
        "lastModifiedDate": 1508369612.203,
        "callerReactions": [],
        "reactionCounts": []
    },
    "location": {
        "filePath": "cl_sample.js",
        "filePosition": 1232,
        "relativeFileVersion": "AFTER"
    ,
    "repositoryName": "MyDemoRepo"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PostCommentForComparedCommit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/post-comment-for-compared-commit.html)」を参照してください。

### `post-comment-for-pull-request`
<a name="codecommit_PostCommentForPullRequest_cli_2_topic"></a>

次のコード例は、`post-comment-for-pull-request` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストにコメントを追加するには**  
次の `post-comment-for-pull-request` の例では、「これらは、どこでも使用されていないようです。削除できますか。」 というコメントを、`MyDemoRepo` という名前のリポジトリの ID が `47` のプルリクエストの `ahs_count.py` ファイルへの変更に追加しています。  

```
aws codecommit post-comment-for-pull-request \
    --pull-request-id "47" \
    --repository-name MyDemoRepo \
    --before-commit-id 317f8570EXAMPLE \
    --after-commit-id 5d036259EXAMPLE \
    --client-request-token 123Example \
    --content "These don't appear to be used anywhere. Can we remove them?" \
    --location filePath=ahs_count.py,filePosition=367,relativeFileVersion=AFTER
```
出力:  

```
{
     "afterBlobId": "1f330709EXAMPLE",
     "afterCommitId": "5d036259EXAMPLE",
     "beforeBlobId": "80906a4cEXAMPLE",
     "beforeCommitId": "317f8570EXAMPLE",
     "comment": {
            "authorArn": "arn:aws:iam::111111111111:user/Saanvi_Sarkar",
            "clientRequestToken": "123Example",
            "commentId": "abcd1234EXAMPLEb5678efgh",
            "content": "These don't appear to be used anywhere. Can we remove them?",
            "creationDate": 1508369622.123,
            "deleted": false,
            "CommentId": "",
            "lastModifiedDate": 1508369622.123,
            "callerReactions": [],
            "reactionCounts": []
        },
        "location": {
            "filePath": "ahs_count.py",
            "filePosition": 367,
            "relativeFileVersion": "AFTER"
         },
     "repositoryName": "MyDemoRepo",
     "pullRequestId": "47"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PostCommentForPullRequest](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/post-comment-for-pull-request.html)」を参照してください。

### `post-comment-reply`
<a name="codecommit_PostCommentReply_cli_2_topic"></a>

次のコード例は、`post-comment-reply` を使用する方法を示しています。

**AWS CLI**  
**コミットまたはプルリクエストのコメントに返信するには**  
この例では、システム生成 ID が `abcd1234EXAMPLEb5678efgh` のコメントに返信 `"Good catch. I'll remove them."` を追加する方法を示しています。  

```
aws codecommit post-comment-reply \
    --in-reply-to abcd1234EXAMPLEb5678efgh \
    --content "Good catch. I'll remove them." \
    --client-request-token 123Example
```
出力:  

```
{
    "comment": {
        "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
        "clientRequestToken": "123Example",
        "commentId": "442b498bEXAMPLE5756813",
        "content": "Good catch. I'll remove them.",
        "creationDate": 1508369829.136,
        "deleted": false,
        "CommentId": "abcd1234EXAMPLEb5678efgh",
        "lastModifiedDate": 150836912.221,
        "callerReactions": [],
        "reactionCounts": []
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PostCommentReply](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/post-comment-reply.html)」を参照してください。

### `put-comment-reaction`
<a name="codecommit_PutCommentReaction_cli_2_topic"></a>

次のコード例は、`put-comment-reaction` を使用する方法を示しています。

**AWS CLI**  
**絵文字を使用してコミットのコメントに返信するには**  
次の `put-comment-reaction` の例では、ID `abcd1234EXAMPLEb5678efgh` のコメントに絵文字リアクション値 `:thumbsup:` で返信しています。  

```
aws codecommit put-comment-reaction \
    --comment-id abcd1234EXAMPLEb5678efgh \
    --reaction-value :thumbsup:
```
このコマンドでは何も出力されません。  
詳細については、[「 AWS CodeCommit ユーザーガイド」の「コミットに関するコメント inCodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-commit-comment.html#how-to-commit-comment-cli-commit-reply-emoji)*AWS CodeCommit*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutCommentReaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/put-comment-reaction.html)」を参照してください。

### `put-file`
<a name="codecommit_PutFile_cli_2_topic"></a>

次のコード例は、`put-file` を使用する方法を示しています。

**AWS CLI**  
**リポジトリにファイルを追加するには**  
次の `put-file` の例では、「ExampleSolution.py」という名前のファイルを「MyDemoRepo」という名前のリポジトリの「feature-randomizationfeature」という名前のブランチに追加しています。最新のコミットの ID は「4c925148EXAMPLE」です。  

```
aws codecommit put-file \
    --repository-name MyDemoRepo \
    --branch-name feature-randomizationfeature \
    --file-content file://MyDirectory/ExampleSolution.py \
    --file-path /solutions/ExampleSolution.py \
    --parent-commit-id 4c925148EXAMPLE \
    --name "Maria Garcia" \
    --email "maria_garcia@example.com" \
    --commit-message "I added a third randomization routine."
```
出力:  

```
{
    "blobId": "2eb4af3bEXAMPLE",
    "commitId": "317f8570EXAMPLE",
    "treeId": "347a3408EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutFile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/put-file.html)」を参照してください。

### `put-repository-triggers`
<a name="codecommit_PutRepositoryTriggers_cli_2_topic"></a>

次のコード例は、`put-repository-triggers` を使用する方法を示しています。

**AWS CLI**  
**リポジトリでトリガーを追加または更新するには**  
この例では、MyDemoRepo という名前のリポジトリのすべてのトリガーの構造を含む、既に作成された JSON ファイル (ここでは MyTriggers.json) を使用して、「MyFirstTrigger」と「MySecondTrigger」という名前のトリガーを更新する方法を示しています。既存のトリガーの JSON を取得する方法については、get-repository-triggers コマンドを参照してください。  

```
aws codecommit put-repository-triggers \
    --repository-name MyDemoRepo file://MyTriggers.json
```
`MyTriggers.json` の内容:  

```
{
    "repositoryName": "MyDemoRepo",
    "triggers": [
        {
            "destinationArn": "arn:aws:sns:us-east-1:80398EXAMPLE:MyCodeCommitTopic",
            "branches": [
                "main",
                "preprod"
            ],
            "name": "MyFirstTrigger",
            "customData": "",
            "events": [
                "all"
            ]
        },
        {
            "destinationArn": "arn:aws:lambda:us-east-1:111111111111:function:MyCodeCommitPythonFunction",
            "branches": [],
            "name": "MySecondTrigger",
            "customData": "EXAMPLE",
            "events": [
                "all"
            ]
        }
    ]
}
```
出力:  

```
{
    "configurationId": "6fa51cd8-35c1-EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRepositoryTriggers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/put-repository-triggers.html)」を参照してください。

### `tag-resource`
<a name="codecommit_TagResource_cli_2_topic"></a>

次の例は、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
**既存のリポジトリに AWS タグを追加するには**  
次の `tag-resource` の例では、指定されたリポジトリに 2 つのタグを付けています。  

```
aws codecommit tag-resource \
    --resource-arn arn:aws:codecommit:us-west-2:111111111111:MyDemoRepo \
    --tags Status=Secret,Team=Saanvi
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Add a Tag to a Repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-tag-repository-add.html#how-to-tag-repository-add-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/tag-resource.html)」を参照してください。

### `test-repository-triggers`
<a name="codecommit_TestRepositoryTriggers_cli_2_topic"></a>

次のコード例は、`test-repository-triggers` を使用する方法を示しています。

**AWS CLI**  
**リポジトリ内のトリガーをテストするには**  
この例では、 MyDemoRepoMyFirstTrigger」という名前のトリガーをテストする方法を示します。 AWS CodeCommit この例では、リポジトリのイベントは Amazon Simple Notification Service (Amazon SNS) トピックから通知をトリガーします。  
コマンド:  

```
aws codecommit test-repository-triggers --repository-name MyDemoRepo --triggers name=MyFirstTrigger,destinationArn=arn:aws:sns:us-east-1:111111111111:MyCodeCommitTopic,branches=mainline,preprod,events=all
```
出力:  

```
{
  "successfulExecutions": [
      "MyFirstTrigger"
  ],
  "failedExecutions": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestRepositoryTriggers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/test-repository-triggers.html)」を参照してください。

### `untag-resource`
<a name="codecommit_UntagResource_cli_2_topic"></a>

次の例は、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リポジトリから AWS タグを削除するには**  
次の `untag-resource` の例では、`MyDemoRepo` という名前のリポジトリから指定されたキーのタグを削除しています。  

```
aws codecommit untag-resource \
    --resource-arn arn:aws:codecommit:us-west-2:111111111111:MyDemoRepo \
    --tag-keys Status
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Remove a Tag from a Repository](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-tag-repository-delete.html#how-to-tag-repository-delete-cli)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/untag-resource.html)」を参照してください。

### `update-approval-rule-template-content`
<a name="codecommit_UpdateApprovalRuleTemplateContent_cli_2_topic"></a>

次のコード例は、`update-approval-rule-template-content` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートの内容を更新するには**  
次の `update-approval-rule-template-content` の例では、指定された承認ルールテンプレートの内容を変更し、`CodeCommitReview` のロールを引き受けるユーザーに承認プールを再定義しています。  

```
aws codecommit update-approval-rule-template-content \
    --approval-rule-template-name 1-approver-rule  \
    --new-rule-content "{\"Version\": \"2018-11-08\",\"DestinationReferences\": [\"refs/heads/main\"],\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}"
```
出力:  

```
{
    "approvalRuleTemplate": {
        "creationDate": 1571352720.773,
        "approvalRuleTemplateDescription": "Requires 1 approval for all pull requests from the CodeCommitReview pool",
        "lastModifiedDate": 1571358728.41,
        "approvalRuleTemplateId": "41de97b7-EXAMPLE",
        "approvalRuleTemplateContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 1,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
        "approvalRuleTemplateName": "1-approver-rule-for-all-pull-requests",
        "ruleContentSha256": "2f6c21a5EXAMPLE",
        "lastModifiedUser": "arn:aws:iam::123456789012:user/Li_Juan"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Manage Approval Rule Templates](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-manage-templates.html#update-template-content)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApprovalRuleTemplateContent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-approval-rule-template-content.html)」を参照してください。

### `update-approval-rule-template-description`
<a name="codecommit_UpdateApprovalRuleTemplateDescription_cli_2_topic"></a>

次のコード例は、`update-approval-rule-template-description` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートの説明を更新するには**  
次の `update-approval-rule-template-description` の例では、指定された承認ルールテンプレートの説明を `Requires 1 approval for all pull requests from the CodeCommitReview pool` に変更しています。  

```
aws codecommit update-approval-rule-template-description \
    --approval-rule-template-name 1-approver-rule-for-all-pull-requests  \
    --approval-rule-template-description "Requires 1 approval for all pull requests from the CodeCommitReview pool"
```
出力:  

```
{
  "approvalRuleTemplate": {
    "creationDate": 1571352720.773,
    "approvalRuleTemplateDescription": "Requires 1 approval for all pull requests from the CodeCommitReview pool",
    "lastModifiedDate": 1571358728.41,
    "approvalRuleTemplateId": "41de97b7-EXAMPLE",
    "approvalRuleTemplateContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 1,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
    "approvalRuleTemplateName": "1-approver-rule-for-all-pull-requests",
    "ruleContentSha256": "2f6c21a5EXAMPLE",
    "lastModifiedUser": "arn:aws:iam::123456789012:user/Li_Juan"
  }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Manage Approval Rule Templates](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-manage-templates.html#update-template-description)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApprovalRuleTemplateDescription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-approval-rule-template-description.html)」を参照してください。

### `update-approval-rule-template-name`
<a name="codecommit_UpdateApprovalRuleTemplateName_cli_2_topic"></a>

次のコード例は、`update-approval-rule-template-name` を使用する方法を示しています。

**AWS CLI**  
**承認ルールテンプレートの名前を更新するには**  
次の `update-approval-rule-template-name` の例では、承認ルールテンプレートの名前を `1-approver-rule` から「1-approver-rule-for-all-pull-requests」に変更しています。  

```
aws codecommit update-approval-rule-template-name \
    --old-approval-rule-template-name 1-approver-rule  \
    --new-approval-rule-template-name 1-approver-rule-for-all-pull-requests
```
出力:  

```
{
  "approvalRuleTemplate": {
    "approvalRuleTemplateName": "1-approver-rule-for-all-pull-requests",
    "lastModifiedDate": 1571358241.619,
    "approvalRuleTemplateId": "41de97b7-EXAMPLE",
    "approvalRuleTemplateContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 1,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
    "creationDate": 1571352720.773,
    "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
    "approvalRuleTemplateDescription": "All pull requests must be approved by one developer on the team.",
    "ruleContentSha256": "2f6c21a5cEXAMPLE"
  }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Manage Approval Rule Templates](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-manage-templates.html#update-template-description)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApprovalRuleTemplateName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-approval-rule-template-name.html)」を参照してください。

### `update-comment`
<a name="codecommit_UpdateComment_cli_2_topic"></a>

次のコード例は、`update-comment` を使用する方法を示しています。

**AWS CLI**  
**コミットに対するコメントを更新するには**  
この例では、ID が `442b498bEXAMPLE5756813` のコメントに `"Fixed as requested. I'll update the pull request."` という内容を追加する方法を示しています。  

```
aws codecommit update-comment \
    --comment-id 442b498bEXAMPLE5756813 \
    --content "Fixed as requested. I'll update the pull request."
```
出力:  

```
{
    "comment": {
        "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
        "clientRequestToken": "",
        "commentId": "442b498bEXAMPLE5756813",
        "content": "Fixed as requested. I'll update the pull request.",
        "creationDate": 1508369929.783,
        "deleted": false,
        "lastModifiedDate": 1508369929.287,
        "callerReactions": [],
        "reactionCounts":
            {
                "THUMBSUP" : 2
            }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateComment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-comment.html)」を参照してください。

### `update-default-branch`
<a name="codecommit_UpdateDefaultBranch_cli_2_topic"></a>

次のコード例は、`update-default-branch` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのデフォルトブランチを変更するには**  
この例では、 AWS CodeCommit リポジトリのデフォルトブランチを変更します。このコマンドは、エラーがある場合にのみ出力を生成します。  
コマンド:  

```
aws codecommit update-default-branch --repository-name MyDemoRepo --default-branch-name MyNewBranch
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDefaultBranch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-default-branch.html)」を参照してください。

### `update-pull-request-approval-rule-content`
<a name="codecommit_UpdatePullRequestApprovalRuleContent_cli_2_topic"></a>

次のコード例は、`update-pull-request-approval-rule-content` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの承認ルールを編集するには**  
次の の`update-pull-request-approval-rule-content`例では、`123456789012` AWS アカウント内の任意の IAM ユーザーを含む承認プールから 1 人のユーザー承認を要求するように、指定した承認ルールを更新します。  

```
aws codecommit update-pull-request-approval-rule-content \
    --pull-request-id 27  \
    --approval-rule-name "Require two approved approvers" \
    --approval-rule-content "{Version: 2018-11-08, Statements: [{Type: \"Approvers\", NumberOfApprovalsNeeded: 1, ApprovalPoolMembers:[\"CodeCommitApprovers:123456789012:user/*\"]}]}}"
```
出力:  

```
{
    "approvalRule": {
        "approvalRuleContent": "{Version: 2018-11-08, Statements: [{Type: \"Approvers\", NumberOfApprovalsNeeded: 1, ApprovalPoolMembers:[\"CodeCommitApprovers:123456789012:user/*\"]}]}}",
        "approvalRuleId": "aac33506-EXAMPLE",
        "originApprovalRuleTemplate": {},
        "creationDate": 1570752871.932,
        "lastModifiedDate": 1570754058.333,
        "approvalRuleName": Require two approved approvers",
        "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
        "ruleContentSha256": "cd93921cEXAMPLE",
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Edit or Delete an Approval Rule](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-edit-delete-pull-request-approval-rule.html#update-pull-request-approval-rule-content)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePullRequestApprovalRuleContent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-pull-request-approval-rule-content.html)」を参照してください。

### `update-pull-request-approval-state`
<a name="codecommit_UpdatePullRequestApprovalState_cli_2_topic"></a>

次のコード例は、`update-pull-request-approval-state` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストを承認するか承認を取り消すには**  
次の `update-pull-request-approval-state` の例では、ID が `27` でリビジョン ID が `9f29d167EXAMPLE` のプルリクエストを承認しています。代わりに承認を取り消す場合は、`--approval-state` パラメータ値を `REVOKE` に設定します。  

```
aws codecommit update-pull-request-approval-state \
    --pull-request-id 27  \
    --revision-id 9f29d167EXAMPLE  \
    --approval-state "APPROVE"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[Review a Pull Request](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-review-pull-request.html#update-pull-request-approval-state)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePullRequestApprovalState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-pull-request-approval-state.html)」を参照してください。

### `update-pull-request-description`
<a name="codecommit_UpdatePullRequestDescription_cli_2_topic"></a>

次のコード例は、`update-pull-request-description` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストの説明を変更するには**  
この例では、ID が `47` のプルリクエストの説明を変更する方法を示しています。  

```
aws codecommit update-pull-request-description \
    --pull-request-id 47 \
    --description "Updated the pull request to remove unused global variable."
```
出力:  

```
{
    "pullRequest": {
        "authorArn": "arn:aws:iam::111111111111:user/Li_Juan",
        "clientRequestToken": "",
        "creationDate": 1508530823.155,
        "description": "Updated the pull request to remove unused global variable.",
        "lastActivityDate": 1508372423.204,
        "pullRequestId": "47",
        "pullRequestStatus": "OPEN",
        "pullRequestTargets": [
            {
                "destinationCommit": "9f31c968EXAMPLE",
                "destinationReference": "refs/heads/main",
                "mergeMetadata": {
                    "isMerged": false,
                },
                "repositoryName": "MyDemoRepo",
                "sourceCommit": "99132ab0EXAMPLE",
                "sourceReference": "refs/heads/variables-branch"
            }
        ],
        "title": "Consolidation of global variables"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePullRequestDescription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-pull-request-description.html)」を参照してください。

### `update-pull-request-status`
<a name="codecommit_UpdatePullRequestStatus_cli_2_topic"></a>

次のコード例は、`update-pull-request-status` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストのステータスを変更するには**  
この例では、ID が のプルリクエストのステータス`42`を、 という名前の AWS CodeCommit リポジトリ`CLOSED`の のステータスに変更する方法を示します`MyDemoRepo`。  

```
aws codecommit update-pull-request-status \
    --pull-request-id 42 \
    --pull-request-status CLOSED
```
出力:  

```
{
    "pullRequest": {
        "approvalRules": [
            {
                "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
                "approvalRuleId": "dd8b17fe-EXAMPLE",
                "approvalRuleName": "2-approvers-needed-for-this-change",
                "creationDate": 1571356106.936,
                "lastModifiedDate": 571356106.936,
                "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
                "ruleContentSha256": "4711b576EXAMPLE"
            }
        ],
        "authorArn": "arn:aws:iam::123456789012:user/Li_Juan",
        "clientRequestToken": "",
        "creationDate": 1508530823.165,
        "description": "Updated the pull request to remove unused global variable.",
        "lastActivityDate": 1508372423.12,
        "pullRequestId": "47",
        "pullRequestStatus": "CLOSED",
        "pullRequestTargets": [
            {
                "destinationCommit": "9f31c968EXAMPLE",
                "destinationReference": "refs/heads/main",
                "mergeMetadata": {
                    "isMerged": false,
                },
                "repositoryName": "MyDemoRepo",
                "sourceCommit": "99132ab0EXAMPLE",
                "sourceReference": "refs/heads/variables-branch"
            }
        ],
        "title": "Consolidation of global variables"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePullRequestStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-pull-request-status.html)」を参照してください。

### `update-pull-request-title`
<a name="codecommit_UpdatePullRequestTitle_cli_2_topic"></a>

次のコード例は、`update-pull-request-title` を使用する方法を示しています。

**AWS CLI**  
**プルリクエストのタイトルを変更するには**  
この例では、ID が `47` のプルリクエストのタイトルを変更する方法を示しています。  

```
aws codecommit update-pull-request-title \
    --pull-request-id 47 \
    --title "Consolidation of global variables - updated review"
```
出力:  

```
{
    "pullRequest": {
        "approvalRules": [
            {
                "approvalRuleContent": "{\"Version\": \"2018-11-08\",\"DestinationReferences\": [\"refs/heads/main\"],\"Statements\": [{\"Type\": \"Approvers\",\"NumberOfApprovalsNeeded\": 2,\"ApprovalPoolMembers\": [\"arn:aws:sts::123456789012:assumed-role/CodeCommitReview/*\"]}]}",
                "approvalRuleId": "dd8b17fe-EXAMPLE",
                "approvalRuleName": "2-approver-rule-for-main",
                "creationDate": 1571356106.936,
                "lastModifiedDate": 571356106.936,
                "lastModifiedUser": "arn:aws:iam::123456789012:user/Mary_Major",
                "originApprovalRuleTemplate": {
                    "approvalRuleTemplateId": "dd8b26gr-EXAMPLE",
                    "approvalRuleTemplateName": "2-approver-rule-for-main"
                },
                "ruleContentSha256": "4711b576EXAMPLE"
            }
        ],
        "authorArn": "arn:aws:iam::123456789012:user/Li_Juan",
        "clientRequestToken": "",
        "creationDate": 1508530823.12,
        "description": "Review the latest changes and updates to the global variables. I have updated this request with some changes, including removing some unused variables.",
        "lastActivityDate": 1508372657.188,
        "pullRequestId": "47",
        "pullRequestStatus": "OPEN",
        "pullRequestTargets": [
            {
                "destinationCommit": "9f31c968EXAMPLE",
                "destinationReference": "refs/heads/main",
                "mergeMetadata": {
                    "isMerged": false,
                },
                "repositoryName": "MyDemoRepo",
                "sourceCommit": "99132ab0EXAMPLE",
                "sourceReference": "refs/heads/variables-branch"
            }
        ],
        "title": "Consolidation of global variables - updated review"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePullRequestTitle](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-pull-request-title.html)」を参照してください。

### `update-repository-description`
<a name="codecommit_UpdateRepositoryDescription_cli_2_topic"></a>

次のコード例は、`update-repository-description` を使用する方法を示しています。

**AWS CLI**  
**リポジトリの説明を変更するには**  
この例では、 AWS CodeCommit リポジトリの説明を変更します。このコマンドは、エラーがある場合にのみ出力を生成します。  
コマンド:  

```
aws codecommit update-repository-description --repository-name MyDemoRepo --repository-description "This description was changed"
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRepositoryDescription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-repository-description.html)」を参照してください。

### `update-repository-name`
<a name="codecommit_UpdateRepositoryName_cli_2_topic"></a>

次のコード例は、`update-repository-name` を使用する方法を示しています。

**AWS CLI**  
**リポジトリの名前を変更するには**  
この例では、 AWS CodeCommit リポジトリの名前を変更します。このコマンドは、エラーがある場合にのみ出力を生成します。 AWS CodeCommit リポジトリの名前を変更すると、ユーザーがリポジトリに接続する必要がある SSH および HTTPS URLs が変更されます。ユーザーは、接続設定を更新するまでこのリポジトリに接続できなくなります。また、リポジトリの ARN が変更されるため、リポジトリ名を変更すると、このリポジトリの ARN に依存するすべての IAM ユーザーポリシーが無効になります。  
コマンド:  

```
aws codecommit update-repository-name --old-name MyDemoRepo --new-name MyRenamedDemoRepo
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRepositoryName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codecommit/update-repository-name.html)」を参照してください。

# を使用した CodeDeploy の例 AWS CLI
<a name="cli_2_codedeploy_code_examples"></a>

次のコード例は、CodeDeploy AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags-to-on-premises-instances`
<a name="codedeploy_AddTagsToOnPremisesInstances_cli_2_topic"></a>

次のコード例は、`add-tags-to-on-premises-instances` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスにタグを追加するには**  
次の`add-tags-to-on-premises-instances`例では、同じオンプレミスインスタンスタグを 2 つのオンプレミスインスタンスに in AWS CodeDeploy を関連付けます。オンプレミスインスタンスは AWS CodeDeploy に登録されません。  

```
aws deploy add-tags-to-on-premises-instances \
    --instance-names AssetTag12010298EX AssetTag23121309EX \
    --tags Key=Name,Value=CodeDeployDemo-OnPrem
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTagsToOnPremisesInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/add-tags-to-on-premises-instances.html)」を参照してください。

### `batch-get-application-revisions`
<a name="codedeploy_BatchGetApplicationRevisions_cli_2_topic"></a>

次のコード例は、`batch-get-application-revisions` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションリビジョンに関する情報を取得するには**  
次の `batch-get-application-revisions` の例では、GitHub リポジトリに保存されている指定されたリビジョンに関する情報を取得しています。  

```
aws deploy batch-get-application-revisions \
    --application-name my-codedeploy-application \
    --revisions "[{\"gitHubLocation\": {\"commitId\": \"fa85936EXAMPLEa31736c051f10d77297EXAMPLE\",\"repository\": \"my-github-token/my-repository\"},\"revisionType\": \"GitHub\"}]"
```
出力:  

```
{
    "revisions": [
        {
            "genericRevisionInfo": {
                "description": "Application revision registered by Deployment ID: d-A1B2C3111",
                "lastUsedTime": 1556912355.884,
                "registerTime": 1556912355.884,
                "firstUsedTime": 1556912355.884,
                "deploymentGroups": []
            },
            "revisionLocation": {
                "revisionType": "GitHub",
                "gitHubLocation": {
                    "commitId": "fa85936EXAMPLEa31736c051f10d77297EXAMPLE",
                    "repository": "my-github-token/my-repository"
                }
            }
        }
    ],
    "applicationName": "my-codedeploy-application",
    "errorMessage": ""
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[BatchGetApplicationRevisions](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetApplicationRevisions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetApplicationRevisions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/batch-get-application-revisions.html)」を参照してください。

### `batch-get-applications`
<a name="codedeploy_BatchGetApplications_cli_2_topic"></a>

次のコード例は、`batch-get-applications` を使用する方法を示しています。

**AWS CLI**  
**複数のアプリケーションに関する情報を取得するには**  
次の の`batch-get-applications`例では、ユーザーの AWS アカウントに関連付けられている複数のアプリケーションに関する情報を表示します。  

```
aws deploy batch-get-applications --application-names WordPress_App MyOther_App
```
出力:  

```
{
    "applicationsInfo": [
        {
            "applicationName": "WordPress_App",
            "applicationId": "d9dd6993-f171-44fa-a811-211e4EXAMPLE",
            "createTime": 1407878168.078,
            "linkedToGitHub": false
        },
        {
            "applicationName": "MyOther_App",
            "applicationId": "8ca57519-31da-42b2-9194-8bb16EXAMPLE",
            "createTime": 1407453571.63,
            "linkedToGitHub": false
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetApplications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/batch-get-applications.html)」を参照してください。

### `batch-get-deployment-groups`
<a name="codedeploy_BatchGetDeploymentGroups_cli_2_topic"></a>

次のコード例は、`batch-get-deployment-groups` を使用する方法を示しています。

**AWS CLI**  
**1 つまたは複数のデプロイグループに関する情報を取得するには**  
次の `batch-get-deployment-groups` の例では、指定された CodeDeploy アプリケーションに関連付けられている 2 つのデプロイグループに関する情報を取得しています。  

```
aws deploy batch-get-deployment-groups \
    --application-name my-codedeploy-application \
    --deployment-group-names "[\"my-deployment-group-1\",\"my-deployment-group-2\"]"
```
出力:  

```
{
    "deploymentGroupsInfo": [
        {
            "deploymentStyle": {
                "deploymentOption": "WITHOUT_TRAFFIC_CONTROL",
                "deploymentType": "IN_PLACE"
            },
            "autoRollbackConfiguration": {
                "enabled": false
            },
            "onPremisesTagSet": {
                "onPremisesTagSetList": []
            },
            "serviceRoleArn": "arn:aws:iam::123456789012:role/CodeDeployServiceRole",
            "lastAttemptedDeployment": {
                "endTime": 1556912366.415,
                "status": "Failed",
                "createTime": 1556912355.884,
                "deploymentId": "d-A1B2C3111"
            },
            "autoScalingGroups": [],
            "deploymentGroupName": "my-deployment-group-1",
            "ec2TagSet": {
                "ec2TagSetList": [
                    [
                        {
                            "Type": "KEY_AND_VALUE",
                            "Value": "my-EC2-instance",
                            "Key": "Name"
                        }
                    ]
                ]
            },
            "deploymentGroupId": "a1b2c3d4-5678-90ab-cdef-11111example",
            "triggerConfigurations": [],
            "applicationName": "my-codedeploy-application",
            "computePlatform": "Server",
            "deploymentConfigName": "CodeDeployDefault.AllAtOnce"
        },
        {
            "deploymentStyle": {
                "deploymentOption": "WITHOUT_TRAFFIC_CONTROL",
                "deploymentType": "IN_PLACE"
            },
            "autoRollbackConfiguration": {
                "enabled": false
            },
            "onPremisesTagSet": {
                "onPremisesTagSetList": []
            },
            "serviceRoleArn": "arn:aws:iam::123456789012:role/CodeDeployServiceRole",
            "autoScalingGroups": [],
            "deploymentGroupName": "my-deployment-group-2",
            "ec2TagSet": {
                "ec2TagSetList": [
                    [
                        {
                            "Type": "KEY_AND_VALUE",
                            "Value": "my-EC2-instance",
                            "Key": "Name"
                            }
                    ]
                ]
            },
            "deploymentGroupId": "a1b2c3d4-5678-90ab-cdef-22222example",
            "triggerConfigurations": [],
            "applicationName": "my-codedeploy-application",
            "computePlatform": "Server",
            "deploymentConfigName": "CodeDeployDefault.AllAtOnce"
        }
    ],
    "errorMessage": ""
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[BatchGetDeploymentGroups](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetDeploymentGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetDeploymentGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/batch-get-deployment-groups.html)」を参照してください。

### `batch-get-deployment-targets`
<a name="codedeploy_BatchGetDeploymentTargets_cli_2_topic"></a>

次のコード例は、`batch-get-deployment-targets` を使用する方法を示しています。

**AWS CLI**  
**デプロイに関連付けられているターゲットを取得するには**  
次の `batch-get-deployment-targets` の例では、指定されたデプロイに関連付けられたターゲットの 1 つに関する情報を返しています。  

```
aws deploy batch-get-deployment-targets \
    --deployment-id "d-1A2B3C4D5" \
    --target-ids "i-01a2b3c4d5e6f1111"
```
出力:  

```
{
    "deploymentTargets": [
        {
            "deploymentTargetType": "InstanceTarget",
            "instanceTarget": {
                "lifecycleEvents": [
                    {
                        "startTime": 1556918592.162,
                        "lifecycleEventName": "ApplicationStop",
                        "status": "Succeeded",
                        "endTime": 1556918592.247,
                        "diagnostics": {
                            "scriptName": "",
                            "errorCode": "Success",
                            "logTail": "",
                            "message": "Succeeded"
                        }
                    },
                    {
                        "startTime": 1556918593.193,
                        "lifecycleEventName": "DownloadBundle",
                        "status": "Succeeded",
                        "endTime": 1556918593.981,
                        "diagnostics": {
                            "scriptName": "",
                            "errorCode": "Success",
                            "logTail": "",
                            "message": "Succeeded"
                        }
                    },
                    {
                        "startTime": 1556918594.805,
                        "lifecycleEventName": "BeforeInstall",
                        "status": "Succeeded",
                        "endTime": 1556918681.807,
                        "diagnostics": {
                            "scriptName": "",
                            "errorCode": "Success",
                            "logTail": "",
                            "message": "Succeeded"
                        }
                    }
                ],
                "targetArn": "arn:aws:ec2:us-west-2:123456789012:instance/i-01a2b3c4d5e6f1111",
                "deploymentId": "d-1A2B3C4D5",
                "lastUpdatedAt": 1556918687.504,
                "targetId": "i-01a2b3c4d5e6f1111",
                "status": "Succeeded"
            }
        }
    ]
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[BatchGetDeploymentTargets](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_BatchGetDeploymentTargets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetDeploymentTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/batch-get-deployment-targets.html)」を参照してください。

### `batch-get-deployments`
<a name="codedeploy_BatchGetDeployments_cli_2_topic"></a>

次のコード例は、`batch-get-deployments` を使用する方法を示しています。

**AWS CLI**  
**複数のデプロイに関する情報を取得するには**  
次の の`batch-get-deployments`例では、ユーザーの AWS アカウントに関連付けられている複数のデプロイに関する情報を表示します。  

```
aws deploy batch-get-deployments --deployment-ids d-A1B2C3111 d-A1B2C3222
```
出力:  

```
{
    "deploymentsInfo": [
        {
            "applicationName": "WordPress_App",
            "status": "Failed",
            "deploymentOverview": {
                "Failed": 0,
                "InProgress": 0,
                "Skipped": 0,
                "Succeeded": 1,
                "Pending": 0
            },
            "deploymentConfigName": "CodeDeployDefault.OneAtATime",
            "creator": "user",
            "deploymentGroupName": "WordPress_DG",
            "revision": {
                "revisionType": "S3",
                "s3Location": {
                "bundleType": "zip",
                "version": "uTecLusEXAMPLEFXtfUcyfV8bEXAMPLE",
                "bucket": "amzn-s3-demo-bucket",
                "key": "WordPressApp.zip"
                }
            },
            "deploymentId": "d-A1B2C3111",
            "createTime": 1408480721.9,
            "completeTime": 1408480741.822
        },
        {
            "applicationName": "MyOther_App",
            "status": "Failed",
            "deploymentOverview": {
                "Failed": 1,
                "InProgress": 0,
                "Skipped": 0,
                "Succeeded": 0,
                "Pending": 0
            },
            "deploymentConfigName": "CodeDeployDefault.OneAtATime",
            "creator": "user",
            "errorInformation": {
                "message": "Deployment failed: Constraint default violated: No hosts succeeded.",
                "code": "HEALTH_CONSTRAINTS"
            },
            "deploymentGroupName": "MyOther_DG",
            "revision": {
                "revisionType": "S3",
                "s3Location": {
                "bundleType": "zip",
                "eTag": "\"dd56cfdEXAMPLE8e768f9d77fEXAMPLE\"",
                "bucket": "amzn-s3-demo-bucket",
                "key": "MyOtherApp.zip"
                }
            },
            "deploymentId": "d-A1B2C3222",
            "createTime": 1409764576.589,
            "completeTime": 1409764596.101
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/batch-get-deployments.html)」を参照してください。

### `batch-get-on-premises-instances`
<a name="codedeploy_BatchGetOnPremisesInstances_cli_2_topic"></a>

次のコード例は、`batch-get-on-premises-instances` を使用する方法を示しています。

**AWS CLI**  
**1 つまたは複数のオンプレミスインスタンスに関する情報を取得するには**  
次の `batch-get-on-premises-instances` の例では、2 つのオンプレミスインスタンスに関する情報を取得しています。  

```
aws deploy batch-get-on-premises-instances --instance-names AssetTag12010298EX AssetTag23121309EX
```
出力:  

```
{
    "instanceInfos": [
        {
            "iamUserArn": "arn:aws:iam::123456789012:user/AWS/CodeDeploy/AssetTag12010298EX",
            "tags": [
                {
                    "Value": "CodeDeployDemo-OnPrem",
                    "Key": "Name"
                }
            ],
            "instanceName": "AssetTag12010298EX",
            "registerTime": 1425579465.228,
            "instanceArn": "arn:aws:codedeploy:us-west-2:123456789012:instance/AssetTag12010298EX_4IwLNI2Alh"
        },
        {
            "iamUserArn": "arn:aws:iam::123456789012:user/AWS/CodeDeploy/AssetTag23121309EX",
            "tags": [
                {
                    "Value": "CodeDeployDemo-OnPrem",
                    "Key": "Name"
                }
            ],
            "instanceName": "AssetTag23121309EX",
            "registerTime": 1425595585.988,
            "instanceArn": "arn:aws:codedeploy:us-west-2:80398EXAMPLE:instance/AssetTag23121309EX_PomUy64Was"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetOnPremisesInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/batch-get-on-premises-instances.html)」を参照してください。

### `continue-deployment`
<a name="codedeploy_ContinueDeployment_cli_2_topic"></a>

次のコード例は、`continue-deployment` を使用する方法を示しています。

**AWS CLI**  
**指定された待機時間が経過するのを待たずにトラフィックの再ルーティングを開始するには。**  
次の `continue-deployment` の例では、置き換え先環境のインスタンスへトラフィックを移行する準備ができている元の環境のインスタンスからのトラフィックの再ルーティングを開始します。  

```
aws deploy continue-deployment \
    --deployment-id "d-A1B2C3111" \
    --deployment-wait-type "READY_WAIT"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeDeploy API リファレンス*」の「[ContinueDeployment](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ContinueDeployment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ContinueDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/continue-deployment.html)」を参照してください。

### `create-application`
<a name="codedeploy_CreateApplication_cli_2_topic"></a>

次のコード例は、`create-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを作成する方法**  
次の`create-application`例では、アプリケーションを作成し、ユーザーの AWS アカウントに関連付けます。  

```
aws deploy create-application --application-name MyOther_App
```
出力:  

```
{
    "applicationId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/create-application.html)」を参照してください。

### `create-deployment-config`
<a name="codedeploy_CreateDeploymentConfig_cli_2_topic"></a>

次のコード例は、`create-deployment-config` を使用する方法を示しています。

**AWS CLI**  
**カスタムデプロイ設定を作成するには**  
次の の`create-deployment-config`例では、カスタムデプロイ設定を作成し、ユーザーの AWS アカウントに関連付けます。  

```
aws deploy create-deployment-config \
    --deployment-config-name ThreeQuartersHealthy \
    --minimum-healthy-hosts type=FLEET_PERCENT,value=75
```
出力:  

```
{
    "deploymentConfigId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDeploymentConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/create-deployment-config.html)」を参照してください。

### `create-deployment-group`
<a name="codedeploy_CreateDeploymentGroup_cli_2_topic"></a>

次のコード例は、`create-deployment-group` を使用する方法を示しています。

**AWS CLI**  
**デプロイグループを作成するには**  
次の の`create-deployment-group`例では、デプロイグループを作成し、指定されたアプリケーションとユーザーの AWS アカウントに関連付けます。  

```
aws deploy create-deployment-group \
    --application-name WordPress_App \
    --auto-scaling-groups CodeDeployDemo-ASG \
    --deployment-config-name CodeDeployDefault.OneAtATime \
    --deployment-group-name WordPress_DG \
    --ec2-tag-filters Key=Name,Value=CodeDeployDemo,Type=KEY_AND_VALUE \
    --service-role-arn arn:aws:iam::123456789012:role/CodeDeployDemoRole
```
出力:  

```
{
    "deploymentGroupId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDeploymentGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/create-deployment-group.html)」を参照してください。

### `create-deployment`
<a name="codedeploy_CreateDeployment_cli_2_topic"></a>

次のコード例は、`create-deployment` を使用する方法を示しています。

**AWS CLI**  
**例 1: EC2/オンプレミスコンピューティングプラットフォームを使用して CodeDeploy デプロイを作成するには**  
次の の`create-deployment`例では、デプロイを作成し、ユーザーの AWS アカウントに関連付けます。  

```
aws deploy create-deployment \
    --application-name WordPress_App \
    --deployment-config-name CodeDeployDefault.OneAtATime \
    --deployment-group-name WordPress_DG \
    --description "My demo deployment" \
    --s3-location bucket=amzn-s3-demo-bucket,bundleType=zip,eTag=dd56cfdEXAMPLE8e768f9d77fEXAMPLE,key=WordPressApp.zip
```
出力:  

```
{
    "deploymentId": "d-A1B2C3111"
}
```
**例 2: Amazon ECS コンピューティングプラットフォームを使用して CodeDeploy デプロイを作成するには**  
次の `create-deployment` の例では、次の 2 つのファイルを使用して Amazon ECS サービスをデプロイしています。  
`create-deployment.json` ファイルの内容。  

```
{
    "applicationName": "ecs-deployment",
    "deploymentGroupName": "ecs-deployment-dg",
    "revision": {
        "revisionType": "S3",
        "s3Location": {
            "bucket": "ecs-deployment-bucket",
            "key": "appspec.yaml",
            "bundleType": "YAML"
        }
    }
}
```
このファイルは、次に `ecs-deployment-bucket` という S3 バケットから次のファイル `appspec.yaml` を取得しています。  

```
version: 0.0
Resources:
  - TargetService:
      Type: AWS::ECS::Service
      Properties:
        TaskDefinition: "arn:aws:ecs:region:123456789012:task-definition/ecs-task-def:2"
        LoadBalancerInfo:
          ContainerName: "sample-app"
          ContainerPort: 80
        PlatformVersion: "LATEST"
```
コマンド:  

```
aws deploy create-deployment \
    --cli-input-json file://create-deployment.json \
    --region us-east-1
```
出力:  

```
{
    "deploymentId": "d-1234ABCDE"
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[CreateDeployment](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_CreateDeployment.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/create-deployment.html)」を参照してください。**

### `delete-application`
<a name="codedeploy_DeleteApplication_cli_2_topic"></a>

次のコード例は、`delete-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを削除するには**  
次の の`delete-application`例では、ユーザーの AWS アカウントに関連付けられている指定されたアプリケーションを削除します。  

```
aws deploy delete-application --application-name WordPress_App
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/delete-application.html)」を参照してください。

### `delete-deployment-config`
<a name="codedeploy_DeleteDeploymentConfig_cli_2_topic"></a>

次のコード例は、`delete-deployment-config` を使用する方法を示しています。

**AWS CLI**  
**デプロイ設定を削除するには**  
次の の`delete-deployment-config`例では、ユーザーの AWS アカウントに関連付けられているカスタムデプロイ設定を削除します。  

```
aws deploy delete-deployment-config --deployment-config-name ThreeQuartersHealthy
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDeploymentConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/delete-deployment-config.html)」を参照してください。

### `delete-deployment-group`
<a name="codedeploy_DeleteDeploymentGroup_cli_2_topic"></a>

次のコード例は、`delete-deployment-group` を使用する方法を示しています。

**AWS CLI**  
**デプロイグループを削除するには**  
次の `delete-deployment-group` の例では、指定されたアプリケーションに関連付けられているデプロイグループを削除しています。  

```
aws deploy delete-deployment-group \
    --application-name WordPress_App \
    --deployment-group-name WordPress_DG
```
出力:  

```
{
    "hooksNotCleanedUp": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDeploymentGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/delete-deployment-group.html)」を参照してください。

### `delete-git-hub-account-token`
<a name="codedeploy_DeleteGitHubAccountToken_cli_2_topic"></a>

次のコード例は、`delete-git-hub-account-token` を使用する方法を示しています。

**AWS CLI**  
**GitHub アカウント接続を削除するには**  
次の `delete-git-hub-account-token` の例では、指定された GitHub アカウントの接続を削除しています。  

```
aws deploy delete-git-hub-account-token --token-name my-github-account
```
出力:  

```
{
    "tokenName": "my-github-account"
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[DeleteGitHubAccountToken](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeleteGitHubAccountToken.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGitHubAccountToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/delete-git-hub-account-token.html)」を参照してください。

### `deregister-on-premises-instance`
<a name="codedeploy_DeregisterOnPremisesInstance_cli_2_topic"></a>

次のコード例は、`deregister-on-premises-instance` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスの登録を解除するには**  
次の`deregister-on-premises-instance`例では、 AWS CodeDeploy を使用してオンプレミスインスタンスを登録解除しますが、インスタンスに関連付けられた IAM ユーザーを削除したり、インスタンスから in AWS CodeDeploy インスタンスタグの関連付けを解除したりすることはありません。また、 AWS CodeDeploy エージェントをインスタンスからアンインストールしたり、インスタンスからオンプレミス設定ファイルを削除したりしません。  

```
aws deploy deregister-on-premises-instance --instance-name AssetTag12010298EX
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterOnPremisesInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/deregister-on-premises-instance.html)」を参照してください。

### `deregister`
<a name="codedeploy_Deregister_cli_2_topic"></a>

次のコード例は、`deregister` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスの登録を解除するには**  
次の の`deregister`例では、 AWS CodeDeploy を使用してオンプレミスインスタンスの登録を解除します。インスタンスに関連付けられた IAM ユーザーは削除されません。インスタンスから in AWS CodeDeploy オンプレミスタグの関連付けを解除します。 AWS CodeDeploy エージェントをインスタンスからアンインストールしたり、インスタンスからオンプレミス設定ファイルを削除したりすることはありません。  

```
aws deploy deregister \
    --instance-name AssetTag12010298EX \
    --no-delete-iam-user \
    --region us-west-2
```
出力:  

```
Retrieving on-premises instance information... DONE
IamUserArn: arn:aws:iam::80398EXAMPLE:user/AWS/CodeDeploy/AssetTag12010298EX
Tags: Key=Name,Value=CodeDeployDemo-OnPrem
Removing tags from the on-premises instance... DONE
Deregistering the on-premises instance... DONE
Run the following command on the on-premises instance to uninstall the codedeploy-agent:
aws deploy uninstall
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Deregister](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/deregister.html)」を参照してください。

### `get-application-revision`
<a name="codedeploy_GetApplicationRevision_cli_2_topic"></a>

次のコード例は、`get-application-revision` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションリビジョンに関する情報を取得するには**  
次の `get-application-revision` の例では、指定されたアプリケーションに関連付けられているアプリケーションリビジョンに関する情報を表示しています。  

```
aws deploy get-application-revision \
    --application-name WordPress_App \
    --s3-location bucket=amzn-s3-demo-bucket,bundleType=zip,eTag=dd56cfdEXAMPLE8e768f9d77fEXAMPLE,key=WordPressApp.zip
```
出力:  

```
{
    "applicationName": "WordPress_App",
    "revisionInfo": {
        "description": "Application revision registered by Deployment ID: d-A1B2C3111",
        "registerTime": 1411076520.009,
        "deploymentGroups": "WordPress_DG",
        "lastUsedTime": 1411076520.009,
        "firstUsedTime": 1411076520.009
    },
    "revision": {
        "revisionType": "S3",
        "s3Location": {
            "bundleType": "zip",
            "eTag": "dd56cfdEXAMPLE8e768f9d77fEXAMPLE",
            "bucket": "amzn-s3-demo-bucket",
            "key": "WordPressApp.zip"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApplicationRevision](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-application-revision.html)」を参照してください。

### `get-application`
<a name="codedeploy_GetApplication_cli_2_topic"></a>

次のコード例は、`get-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションに関する情報を取得するには**  
次の の`get-application`例では、ユーザーの AWS アカウントに関連付けられているアプリケーションに関する情報を表示します。  

```
aws deploy get-application --application-name WordPress_App
```
出力:  

```
{
    "application": {
        "applicationName": "WordPress_App",
        "applicationId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "createTime": 1407878168.078,
        "linkedToGitHub": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-application.html)」を参照してください。

### `get-deployment-config`
<a name="codedeploy_GetDeploymentConfig_cli_2_topic"></a>

次のコード例は、`get-deployment-config` を使用する方法を示しています。

**AWS CLI**  
**デプロイ設定に関する情報を取得するには**  
次の の`get-deployment-config`例では、ユーザーの AWS アカウントに関連付けられているデプロイ設定に関する情報を表示します。  

```
aws deploy get-deployment-config --deployment-config-name ThreeQuartersHealthy
```
出力:  

```
{
    "deploymentConfigInfo": {
        "deploymentConfigId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "minimumHealthyHosts": {
            "type": "FLEET_PERCENT",
            "value": 75
        },
        "createTime": 1411081164.379,
        "deploymentConfigName": "ThreeQuartersHealthy"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeploymentConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-deployment-config.html)」を参照してください。

### `get-deployment-group`
<a name="codedeploy_GetDeploymentGroup_cli_2_topic"></a>

次のコード例は、`get-deployment-group` を使用する方法を示しています。

**AWS CLI**  
**デプロイグループに関する情報を表示するには**  
次の `get-deployment-group` の例では、指定されたアプリケーションに関連付けられているデプロイグループに関する情報を表示しています。  

```
aws deploy get-deployment-group \
    --application-name WordPress_App \
    --deployment-group-name WordPress_DG
```
出力:  

```
{
    "deploymentGroupInfo": {
        "applicationName": "WordPress_App",
        "autoScalingGroups": [
            "CodeDeployDemo-ASG"
        ],
        "deploymentConfigName": "CodeDeployDefault.OneAtATime",
        "ec2TagFilters": [
            {
                "Type": "KEY_AND_VALUE",
                "Value": "CodeDeployDemo",
                "Key": "Name"
            }
        ],
        "deploymentGroupId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "serviceRoleArn": "arn:aws:iam::123456789012:role/CodeDeployDemoRole",
        "deploymentGroupName": "WordPress_DG"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeploymentGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-deployment-group.html)」を参照してください。

### `get-deployment-instance`
<a name="codedeploy_GetDeploymentInstance_cli_2_topic"></a>

次のコード例は、`get-deployment-instance` を使用する方法を示しています。

**AWS CLI**  
**デプロイインスタンスに関する情報を取得するには**  
次の `get-deployment-instance` の例では、指定されたデプロイに関連付けられているデプロイインスタンスに関する情報を表示しています。  

```
aws deploy get-deployment-instance --deployment-id d-QA4G4F9EX --instance-id i-902e9fEX
```
出力:  

```
{
    "instanceSummary": {
        "instanceId": "arn:aws:ec2:us-east-1:80398EXAMPLE:instance/i-902e9fEX",
        "lifecycleEvents": [
            {
                "status": "Succeeded",
                "endTime": 1408480726.569,
                "startTime": 1408480726.437,
                "lifecycleEventName": "ApplicationStop"
            },
            {
                "status": "Succeeded",
                "endTime": 1408480728.016,
                "startTime": 1408480727.665,
                "lifecycleEventName": "DownloadBundle"
            },
            {
                "status": "Succeeded",
                "endTime": 1408480729.744,
                "startTime": 1408480729.125,
                "lifecycleEventName": "BeforeInstall"
            },
            {
                "status": "Succeeded",
                "endTime": 1408480730.979,
                "startTime": 1408480730.844,
                "lifecycleEventName": "Install"
            },
            {
                "status": "Failed",
                "endTime": 1408480732.603,
                "startTime": 1408480732.1,
                "lifecycleEventName": "AfterInstall"
            },
            {
                "status": "Skipped",
                "endTime": 1408480732.606,
                "lifecycleEventName": "ApplicationStart"
            },
            {
                "status": "Skipped",
                "endTime": 1408480732.606,
                "lifecycleEventName": "ValidateService"
            }
        ],
        "deploymentId": "d-QA4G4F9EX",
        "lastUpdatedAt": 1408480733.152,
        "status": "Failed"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeploymentInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-deployment-instance.html)」を参照してください。

### `get-deployment-target`
<a name="codedeploy_GetDeploymentTarget_cli_2_topic"></a>

次のコード例は、`get-deployment-target` を使用する方法を示しています。

**AWS CLI**  
**デプロイターゲットに関する情報を返すには**  
次の `get-deployment-target` の例では、指定されたデプロイに関連付けられているデプロイターゲットに関する情報を返しています。  

```
aws deploy get-deployment-target \
    --deployment-id "d-A1B2C3111" \
    --target-id "i-a1b2c3d4e5f611111"
```
出力:  

```
{
    "deploymentTarget": {
        "deploymentTargetType": "InstanceTarget",
        "instanceTarget": {
            "lastUpdatedAt": 1556918687.504,
            "targetId": "i-a1b2c3d4e5f611111",
            "targetArn": "arn:aws:ec2:us-west-2:123456789012:instance/i-a1b2c3d4e5f611111",
            "status": "Succeeded",
            "lifecycleEvents": [
                {
                    "status": "Succeeded",
                    "diagnostics": {
                        "errorCode": "Success",
                        "message": "Succeeded",
                        "logTail": "",
                        "scriptName": ""
                    },
                    "lifecycleEventName": "ApplicationStop",
                    "startTime": 1556918592.162,
                    "endTime": 1556918592.247
                },
                {
                    "status": "Succeeded",
                    "diagnostics": {
                        "errorCode": "Success",
                        "message": "Succeeded",
                        "logTail": "",
                        "scriptName": ""
                    },
                    "lifecycleEventName": "DownloadBundle",
                    "startTime": 1556918593.193,
                    "endTime": 1556918593.981
                },
                {
                    "status": "Succeeded",
                    "diagnostics": {
                        "errorCode": "Success",
                        "message": "Succeeded",
                        "logTail": "",
                        "scriptName": ""
                    },
                    "lifecycleEventName": "BeforeInstall",
                    "startTime": 1556918594.805,
                    "endTime": 1556918681.807
                },
                {
                    "status": "Succeeded",
                    "diagnostics": {
                        "errorCode": "Success",
                        "message": "Succeeded",
                        "logTail": "",
                        "scriptName": ""
                    },
                    "lifecycleEventName": "Install",
                    "startTime": 1556918682.696,
                    "endTime": 1556918683.005
                },
                {
                    "status": "Succeeded",
                    "diagnostics": {
                        "errorCode": "Success",
                        "message": "Succeeded",
                        "logTail": "",
                        "scriptName": ""
                    },
                    "lifecycleEventName": "AfterInstall",
                    "startTime": 1556918684.135,
                    "endTime": 1556918684.216
                },
                {
                    "status": "Succeeded",
                    "diagnostics": {
                        "errorCode": "Success",
                        "message": "Succeeded",
                        "logTail": "",
                        "scriptName": ""
                    },
                    "lifecycleEventName": "ApplicationStart",
                    "startTime": 1556918685.211,
                    "endTime": 1556918685.295
                },
                {
                    "status": "Succeeded",
                    "diagnostics": {
                        "errorCode": "Success",
                        "message": "Succeeded",
                        "logTail": "",
                        "scriptName": ""
                    },
                    "lifecycleEventName": "ValidateService",
                    "startTime": 1556918686.65,
                    "endTime": 1556918686.747
                }
            ],
            "deploymentId": "d-A1B2C3111"
        }
    }
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[GetDeploymentTarget](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_GetDeploymentTarget.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeploymentTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-deployment-target.html)」を参照してください。

### `get-deployment`
<a name="codedeploy_GetDeployment_cli_2_topic"></a>

次のコード例は、`get-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイの情報を取得する方法**  
次の の`get-deployment`例では、ユーザーの AWS アカウントに関連付けられているデプロイに関する情報を表示します。  

```
aws deploy get-deployment --deployment-id d-A1B2C3123
```
出力:  

```
{
    "deploymentInfo": {
        "applicationName": "WordPress_App",
        "status": "Succeeded",
        "deploymentOverview": {
            "Failed": 0,
            "InProgress": 0,
            "Skipped": 0,
            "Succeeded": 1,
            "Pending": 0
        },
        "deploymentConfigName": "CodeDeployDefault.OneAtATime",
        "creator": "user",
        "description": "My WordPress app deployment",
        "revision": {
            "revisionType": "S3",
            "s3Location":  {
            "bundleType": "zip",
            "eTag": "\"dd56cfdEXAMPLE8e768f9d77fEXAMPLE\"",
            "bucket": "amzn-s3-demo-bucket",
            "key": "WordPressApp.zip"
            }
        },
        "deploymentId": "d-A1B2C3123",
        "deploymentGroupName": "WordPress_DG",
        "createTime": 1409764576.589,
        "completeTime": 1409764596.101,
        "ignoreApplicationStopFailures": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-deployment.html)」を参照してください。

### `get-on-premises-instance`
<a name="codedeploy_GetOnPremisesInstance_cli_2_topic"></a>

次のコード例は、`get-on-premises-instance` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスに関する情報を取得するには**  
次の `get-on-premises-instance` の例では、指定されたオンプレミスインスタンスに関する情報を取得しています。  

```
aws deploy get-on-premises-instance --instance-name AssetTag12010298EX
```
出力:  

```
{
    "instanceInfo": {
    "iamUserArn": "arn:aws:iam::123456789012:user/AWS/CodeDeploy/AssetTag12010298EX",
        "tags": [
        {
            "Value": "CodeDeployDemo-OnPrem",
            "Key": "Name"
        }
        ],
        "instanceName": "AssetTag12010298EX",
        "registerTime": 1425579465.228,
        "instanceArn": "arn:aws:codedeploy:us-east-1:123456789012:instance/AssetTag12010298EX_4IwLNI2Alh"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOnPremisesInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/get-on-premises-instance.html)」を参照してください。

### `install`
<a name="codedeploy_Install_cli_2_topic"></a>

次のコード例は、`install` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスをインストールするには**  
次の の`install`例では、オンプレミス設定ファイルをインスタンス上の指定された場所から、 AWS CodeDeploy エージェントが見つけることを期待するインスタンス上の場所にコピーします。また、 AWS CodeDeploy エージェントをインスタンスにインストールします。IAM ユーザーを作成したり、オンプレミスインスタンスを AWS CodeDeploy に登録したり、インスタンスのオンプレミスインスタンスタグを AWS CodeDeploy に関連付けたりすることはありません。  

```
aws deploy install \
    --override-config \
    --config-file C:\temp\codedeploy.onpremises.yml \
    --region us-west-2 \
    --agent-installer s3://aws-codedeploy-us-west-2/latest/codedeploy-agent.msi
```
出力:  

```
Creating the on-premises instance configuration file... DONE
Installing the AWS CodeDeploy Agent... DONE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Install](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/install.html)」を参照してください。

### `list-application-revisions`
<a name="codedeploy_ListApplicationRevisions_cli_2_topic"></a>

次のコード例は、`list-application-revisions` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションリビジョンに関する情報を取得するには**  
次の `list-application-revisions` の例では、指定されたアプリケーションに関連付けられているすべてのアプリケーションリビジョンに関する情報を表示しています。  

```
aws deploy list-application-revisions \
    --application-name WordPress_App \
    --s-3-bucket amzn-s3-demo-bucket \
    --deployed exclude \
    --s-3-key-prefix WordPress_ \
    --sort-by lastUsedTime \
    --sort-order descending
```
出力:  

```
{
    "revisions": [
        {
            "revisionType": "S3",
            "s3Location": {
                "version": "uTecLusvCB_JqHFXtfUcyfV8bEXAMPLE",
                "bucket": "amzn-s3-demo-bucket",
                "key": "WordPress_App.zip",
                "bundleType": "zip"
            }
        },
        {
            "revisionType": "S3",
            "s3Location": {
                "version": "tMk.UxgDpMEVb7V187ZM6wVAWEXAMPLE",
                "bucket": "amzn-s3-demo-bucket",
                "key": "WordPress_App_2-0.zip",
                "bundleType": "zip"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListApplicationRevisions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-application-revisions.html)」を参照してください。

### `list-applications`
<a name="codedeploy_ListApplications_cli_2_topic"></a>

次のコード例は、`list-applications` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションに関する情報を取得するには**  
次の の`list-applications`例では、ユーザーの AWS アカウントに関連付けられているすべてのアプリケーションに関する情報を表示します。  

```
aws deploy list-applications
```
出力:  

```
{
    "applications": [
        "WordPress_App",
        "MyOther_App"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListApplications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-applications.html)」を参照してください。

### `list-deployment-configs`
<a name="codedeploy_ListDeploymentConfigs_cli_2_topic"></a>

次のコード例は、`list-deployment-configs` を使用する方法を示しています。

**AWS CLI**  
**デプロイ設定に関する情報を取得するには**  
次の の`list-deployment-configs`例では、ユーザーの AWS アカウントに関連付けられているすべてのデプロイ設定に関する情報を表示します。  

```
aws deploy list-deployment-configs
```
出力:  

```
{
    "deploymentConfigsList": [
        "ThreeQuartersHealthy",
        "CodeDeployDefault.AllAtOnce",
        "CodeDeployDefault.HalfAtATime",
        "CodeDeployDefault.OneAtATime"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeploymentConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-deployment-configs.html)」を参照してください。

### `list-deployment-groups`
<a name="codedeploy_ListDeploymentGroups_cli_2_topic"></a>

次のコード例は、`list-deployment-groups` を使用する方法を示しています。

**AWS CLI**  
**デプロイグループに関する情報を取得するには**  
次の `list-deployment-groups` の例では、指定されたアプリケーションに関連付けられているすべてのデプロイグループに関する情報を表示しています。  

```
aws deploy list-deployment-groups --application-name WordPress_App
```
出力:  

```
{
    "applicationName": "WordPress_App",
    "deploymentGroups": [
        "WordPress_DG",
        "WordPress_Beta_DG"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeploymentGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-deployment-groups.html)」を参照してください。

### `list-deployment-instances`
<a name="codedeploy_ListDeploymentInstances_cli_2_topic"></a>

次のコード例は、`list-deployment-instances` を使用する方法を示しています。

**AWS CLI**  
**デプロイインスタンスに関する情報を取得するには**  
次の `list-deployment-instances` の例では、指定されたデプロイに関連付けられているすべてのデプロイインスタンスに関する情報を表示しています。  

```
aws deploy list-deployment-instances \
    --deployment-id d-A1B2C3111 \
    --instance-status-filter Succeeded
```
出力:  

```
{
    "instancesList": [
        "i-EXAMPLE11",
        "i-EXAMPLE22"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeploymentInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-deployment-instances.html)」を参照してください。

### `list-deployment-targets`
<a name="codedeploy_ListDeploymentTargets_cli_2_topic"></a>

次のコード例は、`list-deployment-targets` を使用する方法を示しています。

**AWS CLI**  
**デプロイに関連付けられているターゲット ID のリストを取得するには**  
次の `list-deployment-targets` の例では、「Failed」または「InProgress」のステータスを持つデプロイに関連付けられたターゲット ID のリストを取得しています。  

```
aws deploy list-deployment-targets \
    --deployment-id "d-A1B2C3111" \
    --target-filters "{\"TargetStatus\":[\"Failed\",\"InProgress\"]}"
```
出力:  

```
{
    "targetIds": [
        "i-0f1558aaf90e5f1f9"
    ]
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[ListDeploymentTargets](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListDeploymentTargets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeploymentTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-deployment-targets.html)」を参照してください。

### `list-deployments`
<a name="codedeploy_ListDeployments_cli_2_topic"></a>

次のコード例は、`list-deployments` を使用する方法を示しています。

**AWS CLI**  
**デプロイに関する情報を取得するには**  
次の `list-deployments` の例では、指定されたアプリケーションとデプロイグループに関連付けられているすべてのデプロイに関する情報を表示しています。  

```
aws deploy list-deployments \
    --application-name WordPress_App \
    --create-time-range start=2014-08-19T00:00:00,end=2014-08-20T00:00:00 \
    --deployment-group-name WordPress_DG \
    --include-only-statuses Failed
```
出力:  

```
{
    "deployments": [
        "d-EXAMPLE11",
        "d-EXAMPLE22",
        "d-EXAMPLE33"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-deployments.html)」を参照してください。

### `list-git-hub-account-token-names`
<a name="codedeploy_ListGitHubAccountTokenNames_cli_2_topic"></a>

次のコード例は、`list-git-hub-account-token-names` を使用する方法を示しています。

**AWS CLI**  
**GitHub アカウントへの保存された接続の名前を一覧表示するには**  
次の の`list-git-hub-account-token-names`例では、現在の AWS ユーザーの GitHub アカウントへの保存済み接続の名前を一覧表示します。  

```
aws deploy list-git-hub-account-token-names
```
出力:  

```
{
    "tokenNameList": [
        "my-first-token",
        "my-second-token",
        "my-third-token"
    ]
}
```
詳細については、「*AWS CodeDeploy API リファレンス*」の「[ListGitHubAccountTokenNames](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_ListGitHubAccountTokenNames.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGitHubAccountTokenNames](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-git-hub-account-token-names.html)」を参照してください。

### `list-on-premises-instances`
<a name="codedeploy_ListOnPremisesInstances_cli_2_topic"></a>

次のコード例は、`list-on-premises-instances` を使用する方法を示しています。

**AWS CLI**  
**1 つまたは複数のオンプレミスインスタンスに関する情報を取得するには**  
次の の`list-on-premises-instances`例では、in AWS CodeDeploy に登録され、インスタンス AWS CodeDeploy に関連付けられた指定されたオンプレミスインスタンスタグを持つインスタンスで使用可能なオンプレミスインスタンス名のリストを取得します。  

```
aws deploy list-on-premises-instances \
    --registration-status Registered \
    --tag-filters Key=Name,Value=CodeDeployDemo-OnPrem,Type=KEY_AND_VALUE
```
出力:  

```
{
    "instanceNames": [
        "AssetTag12010298EX"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOnPremisesInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-on-premises-instances.html)」を参照してください。

### `list-tags-for-resource`
<a name="codedeploy_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには (アプリケーション)**  
次の `list-tags-for-resource` の例では、CodeDeploy の testApp という名前のアプリケーションに適用されるタグを一覧表示しています。  

```
aws deploy list-tags-for-resource \
    --resource-arn arn:aws:codedeploy:us-west-2:111122223333:application:testApp
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Type",
            "Value": "testType"
        },
        {
            "Key": "Name",
            "Value": "testName"
        }
    ]
}
```
詳細については、「*AWS CodeDeploy ユーザーガイド*」の「[Tagging instances for deployment groups in CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/instances-tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/list-tags-for-resource.html)」を参照してください。

### `push`
<a name="codedeploy_Push_cli_2_topic"></a>

次の例は、`push` を使用する方法を説明しています。

**AWS CLI**  
** AWS CodeDeploy 互換アプリケーションリビジョンをバンドルして Amazon S3 にデプロイするには**  
次の `push` の例では、アプリケーションリビジョンをバンドルして Amazon S3 にデプロイし、アプリケーションリビジョンを指定されたアプリケーションに関連付けています。  

```
aws deploy push \
    --application-name WordPress_App \
    --description "This is my deployment" \
    --ignore-hidden-files \
    --s3-location s3://amzn-s3-demo-bucket/WordPressApp.zip \
    --source /tmp/MyLocalDeploymentFolder/
```
出力では、`create-deployment` コマンドを使用して、アップロードされたアプリケーションリビジョンを使用するデプロイを作成する方法について説明しています。  

```
To deploy with this revision, run:
aws deploy create-deployment --application-name WordPress_App --deployment-config-name <deployment-config-name> --deployment-group-name <deployment-group-name> --s3-location bucket=amzn-s3-demo-bucket,key=WordPressApp.zip,bundleType=zip,eTag="cecc9b8EXAMPLE50a6e71fdb88EXAMPLE",version=LFsJAUdEXAMPLEfvKtvi79L8EXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Push](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/push.html)」を参照してください。

### `register-application-revision`
<a name="codedeploy_RegisterApplicationRevision_cli_2_topic"></a>

次のコード例は、`register-application-revision` を使用する方法を示しています。

**AWS CLI**  
**アップロード済みのアプリケーションリビジョンに関する情報を登録するには**  
次の の`register-application-revision`例では、Amazon S3 に保存されているアップロード済みのアプリケーションリビジョンに関する情報を AWS CodeDeploy に登録します。  

```
aws deploy register-application-revision \
    --application-name WordPress_App \
    --description "Revised WordPress application" \
    --s3-location bucket=amzn-s3-demo-bucket,key=RevisedWordPressApp.zip,bundleType=zip,eTag=cecc9b8a08eac650a6e71fdb88EXAMPLE
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterApplicationRevision](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/register-application-revision.html)」を参照してください。

### `register-on-premises-instance`
<a name="codedeploy_RegisterOnPremisesInstance_cli_2_topic"></a>

次のコード例は、`register-on-premises-instance` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスを登録するには**  
次の の`register-on-premises-instance`例では、 AWS CodeDeploy にオンプレミスインスタンスを登録します。指定された IAM ユーザーを作成したり、in AWS CodeDeploy のオンプレミスインスタンスタグを登録済みインスタンスに関連付けたりすることはありません。  

```
aws deploy register-on-premises-instance \
    --instance-name AssetTag12010298EX \
    --iam-user-arn arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser-OnPrem
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterOnPremisesInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/register-on-premises-instance.html)」を参照してください。

### `register`
<a name="codedeploy_Register_cli_2_topic"></a>

次のコード例は、`register` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスを登録するには**  
次の`register`例では、オンプレミスインスタンスを AWS CodeDeploy に登録し、in AWS CodeDeploy で指定されたオンプレミスインスタンスタグを登録済みインスタンスに関連付け、インスタンスにコピーできるオンプレミス設定ファイルを作成します。IAM ユーザーを作成したり、 AWS CodeDeploy エージェントをインスタンスにインストールしたりすることはありません。  

```
aws deploy register \
    --instance-name AssetTag12010298EX \
    --iam-user-arn arn:aws:iam::80398EXAMPLE:user/CodeDeployUser-OnPrem \
    --tags Key=Name,Value=CodeDeployDemo-OnPrem \
    --region us-west-2
```
出力:  

```
Registering the on-premises instance... DONE
Adding tags to the on-premises instance... DONE
Copy the on-premises configuration file named codedeploy.onpremises.yml to the on-premises instance, and run the following command on the on-premises instance to install and configure the AWS CodeDeploy Agent:
aws deploy install --config-file codedeploy.onpremises.yml
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Register](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/register.html)」を参照してください。

### `remove-tags-from-on-premises-instances`
<a name="codedeploy_RemoveTagsFromOnPremisesInstances_cli_2_topic"></a>

次のコード例は、`remove-tags-from-on-premises-instances` を使用する方法を示しています。

**AWS CLI**  
**1 つまたは複数のオンプレミスインスタンスからタグを削除するには**  
次の の`remove-tags-from-on-premises-instances`例では、指定されたオンプレミスタグ in AWS CodeDeploy とオンプレミスインスタンスの関連付けを解除します。 AWS CodeDeploy でオンプレミスインスタンスの登録を解除したり、インスタンスから AWS CodeDeploy エージェントをアンインストールしたり、インスタンスからオンプレミス設定ファイルを削除したり、インスタンスに関連付けられている IAM ユーザーを削除したりすることはありません。  

```
aws deploy remove-tags-from-on-premises-instances \
    --instance-names AssetTag12010298EX AssetTag23121309EX \
    --tags Key=Name,Value=CodeDeployDemo-OnPrem
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromOnPremisesInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/remove-tags-from-on-premises-instances.html)」を参照してください。

### `stop-deployment`
<a name="codedeploy_StopDeployment_cli_2_topic"></a>

次のコード例は、`stop-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイを停止するには**  
次の`stop-deployment`例では、ユーザーの AWS アカウントに関連付けられている進行中のデプロイを停止しようとします。  
aws deploy stop-deployment --deployment-id d-A1B2C3111  
出力:  

```
{
    "status": "Succeeded",
    "statusMessage": "No more commands will be scheduled for execution in the deployment instances"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/stop-deployment.html)」を参照してください。

### `tag-resource`
<a name="codedeploy_TagResource_cli_2_topic"></a>

次の例は、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースにタグを付けるには (アプリケーション)**  
次の `tag-resource` の例では、CodeDeploy の testApp という名前のアプリケーションに、キー Name と Type、値 testName と testType を持つ 2 つのタグを追加しています。  

```
aws deploy tag-resource \
    --resource-arn  arn:aws:codedeploy:us-west-2:111122223333:application:testApp \
    --tags Key=Name,Value=testName Key=Type,Value=testType
```
このコマンドが成功した場合、出力は生成されません。  
詳細については、「*AWS CodeDeploy ユーザーガイド*」の「[Tagging instances for deployment groups in CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/instances-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/tag-resource.html)」を参照してください。

### `uninstall`
<a name="codedeploy_Uninstall_cli_2_topic"></a>

次のコード例は、`uninstall` を使用する方法を示しています。

**AWS CLI**  
**オンプレミスインスタンスをアンインストールするには**  
次の`uninstall`例では、オンプレミスインスタンスから AWS CodeDeploy エージェントをアンインストールし、インスタンスからオンプレミス設定ファイルを削除します。 AWS CodeDeploy のインスタンスを登録解除したり、インスタンスから AWS CodeDeploy のオンプレミスインスタンスタグの関連付けを解除したり、インスタンスに関連付けられている IAM ユーザーを削除したりすることはありません。  

```
aws deploy uninstall
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Uninstall](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/uninstall.html)」を参照してください。

### `untag-resource`
<a name="codedeploy_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除するには (アプリケーション)**  
次の `untag-resource` の例では、CodeDeploy の testApp という名前のアプリケーションから、キー Name と Type を持つ 2 つのタグを削除しています。  

```
aws deploy untag-resource \
    --resource-arn  arn:aws:codedeploy:us-west-2:111122223333:application:testApp \
    --tag-keys Name Type
```
このコマンドが成功した場合、出力は生成されません。  
詳細については、「*AWS CodeDeploy ユーザーガイド*」の「[Tagging instances for deployment groups in CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/instances-tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/untag-resource.html)」を参照してください。

### `update-application`
<a name="codedeploy_UpdateApplication_cli_2_topic"></a>

次のコード例は、`update-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの詳細を変更するには**  
次の の`update-application`例では、ユーザーの AWS アカウントに関連付けられているアプリケーションの名前を変更します。  

```
aws deploy update-application \
    --application-name WordPress_App \
    --new-application-name My_WordPress_App
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/update-application.html)」を参照してください。

### `update-deployment-group`
<a name="codedeploy_UpdateDeploymentGroup_cli_2_topic"></a>

次のコード例は、`update-deployment-group` を使用する方法を示しています。

**AWS CLI**  
**デプロイグループに関する情報を変更するには**  
次の `update-deployment-group` の例では、指定されたアプリケーションに関連付けられているデプロイグループの設定を変更しています。  

```
aws deploy update-deployment-group \
    --application-name WordPress_App \
    --auto-scaling-groups My_CodeDeployDemo_ASG \
    --current-deployment-group-name WordPress_DG \
    --deployment-config-name CodeDeployDefault.AllAtOnce \
    --ec2-tag-filters Key=Name,Type=KEY_AND_VALUE,Value=My_CodeDeployDemo \
    --new-deployment-group-name My_WordPress_DepGroup \
    --service-role-arn arn:aws:iam::80398EXAMPLE:role/CodeDeployDemo-2
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDeploymentGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/deploy/update-deployment-group.html)」を参照してください。

# を使用した CodeGuru Reviewer の例 AWS CLI
<a name="cli_2_codeguru-reviewer_code_examples"></a>

次のコード例は、CodeGuru Reviewer AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-repository`
<a name="codeguru-reviewer_AssociateRepository_cli_2_topic"></a>

次のコード例は、`associate-repository` を使用する方法を示しています。

**AWS CLI**  
**例 1: Bitbucket リポジトリの関連付けを作成するには**  
次の `associate-repository` の例では、既存の Bitbucket リポジトリを使用してリポジトリの関連付けを作成しています。  

```
aws codeguru-reviewer associate-repository \
    --repository 'Bitbucket={Owner=sample-owner, Name=mySampleRepo, ConnectionArn=arn:aws:codestar-connections:us-west-2:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 }'
```
出力:  

```
{
    "RepositoryAssociation": {
        "ProviderType": "Bitbucket",
        "Name": "mySampleRepo",
        "LastUpdatedTimeStamp": 1596216896.979,
        "AssociationId": "association:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "CreatedTimeStamp": 1596216896.979,
        "ConnectionArn": "arn:aws:codestar-connections:us-west-2:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "State": "Associating",
        "StateReason": "Pending Repository Association",
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "Owner": "sample-owner"
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Create a Bitbucket repository association in Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/create-bitbucket-association.html)」を参照してください。  
**例 2: GitHub Enterprise リポジトリの関連付けを作成するには**  
次の `associate-repository` の例では、既存の GitHub Enterprise リポジトリを使用してリポジトリの関連付けを作成しています。  

```
aws codeguru-reviewer associate-repository \
    --repository 'GitHubEnterpriseServer={Owner=sample-owner, Name=mySampleRepo, ConnectionArn=arn:aws:codestar-connections:us-west-2:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 }'
```
出力:  

```
{
    "RepositoryAssociation": {
        "ProviderType": "GitHubEnterpriseServer",
        "Name": "mySampleRepo",
        "LastUpdatedTimeStamp": 1596216896.979,
        "AssociationId": "association:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "CreatedTimeStamp": 1596216896.979,
        "ConnectionArn": "arn:aws:codestar-connections:us-west-2:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "State": "Associating",
        "StateReason": "Pending Repository Association",
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "Owner": "sample-owner"
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Create a GitHub Enterprise Server repository association in Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/create-github-enterprise-association.html)」を参照してください。  
**例 3: AWS CodeCommit リポジトリの関連付けを作成するには**  
次の の`associate-repository`例では、既存の AWS CodeCommit リポジトリを使用してリポジトリの関連付けを作成します。  

```
aws codeguru-reviewer associate-repository \
    --repository CodeCommit={Name=mySampleRepo}
```
出力:  

```
{
    "RepositoryAssociation": {
        "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Name": "My-ecs-beta-repo",
        "LastUpdatedTimeStamp": 1595634764.029,
        "ProviderType": "CodeCommit",
        "CreatedTimeStamp": 1595634764.029,
        "Owner": "544120495673",
        "State": "Associating",
        "StateReason": "Pending Repository Association",
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:544120495673:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、[「Amazon CodeGuru Reviewer ユーザーガイド」の「Amazon CodeGuru Reviewer で AWS CodeCommit リポジトリの関連付け](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/create-codecommit-association.html)を作成する」を参照してください。 * CodeGuru *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/associate-repository.html)」を参照してください。

### `create-code-review`
<a name="codeguru-reviewer_CreateCodeReview_cli_2_topic"></a>

次のコード例は、`create-code-review` を使用する方法を示しています。

**AWS CLI**  
**コードレビューを作成するには。**  
以下は、 という名前の AWS CodeCommit リポジトリの`mainline`ブランチにコードのレビュー`create-code-review`を作成します`my-repository-name`。  

```
aws codeguru-reviewer create-code-review \
    --name my-code-review \
    --repository-association-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --type '{"RepositoryAnalysis": {"RepositoryHead": {"BranchName": "mainline"}}}'
```
出力:  

```
{
    "CodeReview": {
        "Name": "my-code-review",
        "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222:code-review:RepositoryAnalysis-my-code-review",
        "RepositoryName": "my-repository-name",
        "Owner": "123456789012",
        "ProviderType": "CodeCommit",
        "State": "Pending",
        "StateReason": "CodeGuru Reviewer has received the request, and a code review is scheduled.",
        "CreatedTimeStamp": 1618873489.195,
        "LastUpdatedTimeStamp": 1618873489.195,
        "Type": "RepositoryAnalysis",
        "SourceCodeType": {
            "RepositoryHead": {
                "BranchName": "mainline"
            }
        },
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Create code reviews in Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/create-code-reviews.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCodeReview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/create-code-review.html)」を参照してください。

### `describe-code-review`
<a name="codeguru-reviewer_DescribeCodeReview_cli_2_topic"></a>

次のコード例は、`describe-code-review` を使用する方法を示しています。

**AWS CLI**  
**コードレビューに関する詳細を一覧表示するには。**  
以下に、my-repo-name」という名前の AWS CodeCommit リポジトリの「mainline」ブランチ内のコードのレビューに関する情報`describe-code-review`を示します。  

```
aws codeguru-reviewer put-recommendation-feedback \
    --code-review-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:code-review:RepositoryAnalysis-my-repository-name-branch-abcdefgh12345678 \
    --recommendation-id 3be1b2e5d7ef6e298a06499379ee290c9c596cf688fdcadb08285ddb0dd390eb \
    --reactions ThumbsUp
```
Output  

```
{
        "CodeReview": {
            "Name": "My-ecs-beta-repo-master-xs6di4kfd4j269dz",
            "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222:code-review:RepositoryAnalysis-my-repo-name",
            "RepositoryName": "My-ecs-beta-repo",
            "Owner": "123456789012",
            "ProviderType": "CodeCommit",
            "State": "Pending",
            "StateReason": "CodeGuru Reviewer is reviewing the source code.",
            "CreatedTimeStamp": 1618874226.226,
            "LastUpdatedTimeStamp": 1618874233.689,
            "Type": "RepositoryAnalysis",
            "SourceCodeType": {
                "RepositoryHead": {
                    "BranchName": "mainline"
                }
            },
            "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        }
    }
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[View code review details](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/view-code-review-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCodeReview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/describe-code-review.html)」を参照してください。

### `describe-recommendation-feedback`
<a name="codeguru-reviewer_DescribeRecommendationFeedback_cli_2_topic"></a>

次のコード例は、`describe-recommendation-feedback` を使用する方法を示しています。

**AWS CLI**  
**推奨事項に対するフィードバックの情報を表示するには**  
次の `describe-recommendation-feedback` は、推奨事項に対するフィードバックの情報を示しています。この推奨事項には `ThumbsUp` リアクションが 1 つあります。  

```
aws codeguru-reviewer describe-recommendation-feedback \
    --code-review-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:code-review:RepositoryAnalysis-my-repository-name-branch-abcdefgh12345678 \
    --recommendation-id 3be1b2e5d7ef6e298a06499379ee290c9c596cf688fdcadb08285ddb0dd390eb
```
出力:  

```
{
    "RecommendationFeedback": {
        "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:code-review:RepositoryAnalysis-my-repository-name-branch-abcdefgh12345678",
        "RecommendationId": "3be1b2e5d7ef6e298a06499379ee290c9c596cf688fdcadb08285ddb0dd390eb",
        "Reactions": [
            "ThumbsUp"
        ],
        "UserId": "aws-user-id",
        "CreatedTimeStamp": 1618877070.313,
        "LastUpdatedTimeStamp": 1618877948.881
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[View recommendations and provide feedback](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/give-feedback-from-code-review-details.html)」および「[Step 4: Provide feedback](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/provide-feedback.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRecommendationFeedback](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/describe-recommendation-feedback.html)」を参照してください。

### `describe-repository-association`
<a name="codeguru-reviewer_DescribeRepositoryAssociation_cli_2_topic"></a>

次のコード例は、`describe-repository-association` を使用する方法を示しています。

**AWS CLI**  
**例 1: GitHub リポジトリの関連付けに関する情報を返すには**  
次の `describe-repository-association` の例では、GitHub Enterprise リポジトリを使用して `Associated` 状態にあるリポジトリの関連付けに関する情報を返しています。  

```
aws codeguru-reviewer describe-repository-association \
    --association-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RepositoryAssociation": {
        "AssociationId": "b822717e-0711-4e8a-bada-0e738289c75e",
        "Name": "mySampleRepo",
        "LastUpdatedTimeStamp": 1588102637.649,
        "ProviderType": "GitHub",
        "CreatedTimeStamp": 1588102615.636,
        "Owner": "sample-owner",
        "State": "Associated",
        "StateReason": "Pull Request Notification configuration successful",
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Create a GitHub Enterprise Server repository association in Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/create-github-enterprise-association.html)」を参照してください。  
**例 2: 失敗したリポジトリの関連付けに関する情報を返すには**  
次の `describe-repository-association` の例では、GitHub Enterprise リポジトリを使用して `Failed` 状態にあるリポジトリの関連付けに関する情報を返しています。  

```
aws codeguru-reviewer describe-repository-association \
    --association-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RepositoryAssociation": {
        "ProviderType": "GitHubEnterpriseServer",
        "Name": "mySampleRepo",
        "LastUpdatedTimeStamp": 1596217036.892,
        "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "CreatedTimeStamp": 1596216896.979,
        "ConnectionArn": "arn:aws:codestar-connections:us-west-2:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "State": "Failed",
        "StateReason": "Failed, Please retry.",
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
        "Owner": "sample-owner"
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Create a GitHub Enterprise Server repository association in Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/create-github-enterprise-association.html)」を参照してください。  
**例 3: リポジトリの関連付けの解除に関する情報を返すには**  
次の `describe-repository-association` の例では、GitHub Enterprise リポジトリを使用して `Disassociating` 状態にあるリポジトリの関連付けに関する情報を返しています。  

```
aws codeguru-reviewer describe-repository-association \
    --association-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RepositoryAssociation": {
        "ProviderType": "GitHubEnterpriseServer",
        "Name": "mySampleRepo",
        "LastUpdatedTimeStamp": 1596217036.892,
        "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "CreatedTimeStamp": 1596216896.979,
        "ConnectionArn": "arn:aws:codestar-connections:us-west-2:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "State": "Disassociating",
        "StateReason": "Source code access removal in progress",
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
        "Owner": "sample-owner"
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Create a GitHub Enterprise Server repository association in Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/create-github-enterprise-association.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRepositoryAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/describe-repository-association.html)」を参照してください。

### `disassociate-repository`
<a name="codeguru-reviewer_DisassociateRepository_cli_2_topic"></a>

次のコード例は、`disassociate-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリの関連付けを解除するには**  
次の は、 AWS CodeCommit リポジトリを使用しているリポジトリの関連付け`disassociate-repository`を解除します。  

```
aws codeguru-reviewer disassociate-repository \
    --association-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RepositoryAssociation": {
        "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Name": "my-repository",
        "Owner": "123456789012",
        "ProviderType": "CodeCommit",
        "State": "Disassociating",
        "LastUpdatedTimeStamp": 1618939174.759,
        "CreatedTimeStamp": 1595636947.096
    },
    "Tags": {
        "Status": "Secret",
        "Team": "Saanvi"
    }
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Disassociate a repository in CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/disassociate-repository-association.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/disassociate-repository.html)」を参照してください。

### `list-code-reviews`
<a name="codeguru-reviewer_ListCodeReviews_cli_2_topic"></a>

次の例は、`list-code-reviews` を使用する方法を説明しています。

**AWS CLI**  
**過去 90 日間に AWS アカウントで作成されたコードレビューを一覧表示するには。**  
次の `list-code-reviews` の例では、プルリクエストを使用して過去 90 日間に作成されたコードレビューを一覧表示しています。  

```
aws codeguru-reviewer list-code-reviews \
    --type PullRequest
```
出力:  

```
{
    "CodeReviewSummaries": [
        {
            "LastUpdatedTimeStamp": 1588897288.054,
            "Name": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ProviderType": "GitHub",
            "PullRequestId": "5",
            "MetricsSummary": {
                "MeteredLinesOfCodeCount": 24,
                "FindingsCount": 1
            },
            "CreatedTimeStamp": 1588897068.512,
            "State": "Completed",
            "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:code-review:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Owner": "sample-owner",
            "RepositoryName": "sample-repository-name",
            "Type": "PullRequest"
        },
        {
            "LastUpdatedTimeStamp": 1588869793.263,
            "Name": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "ProviderType": "GitHub",
            "PullRequestId": "4",
            "MetricsSummary": {
                "MeteredLinesOfCodeCount": 29,
                "FindingsCount": 0
            },
            "CreatedTimeStamp": 1588869575.949,
            "State": "Completed",
            "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:code-review:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "Owner": "sample-owner",
            "RepositoryName": "sample-repository-name",
            "Type": "PullRequest"
        },
        {
            "LastUpdatedTimeStamp": 1588870511.211,
            "Name": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "ProviderType": "GitHub",
            "PullRequestId": "4",
            "MetricsSummary": {
                "MeteredLinesOfCodeCount": 2,
                "FindingsCount": 0
            },
            "CreatedTimeStamp": 1588870292.425,
            "State": "Completed",
            "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:code-review:a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "Owner": "sample-owner",
            "RepositoryName": "sample-repository-name",
            "Type": "PullRequest"
        },
        {
            "LastUpdatedTimeStamp": 1588118522.452,
            "Name": "a1b2c3d4-5678-90ab-cdef-EXAMPLE44444",
            "ProviderType": "GitHub",
            "PullRequestId": "3",
            "MetricsSummary": {
                "MeteredLinesOfCodeCount": 29,
                "FindingsCount": 0
            },
            "CreatedTimeStamp": 1588118301.131,
            "State": "Completed",
            "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:code-review:a1b2c3d4-5678-90ab-cdef-EXAMPLE44444",
            "Owner": "sample-owner",
            "RepositoryName": "sample-repository-name",
            "Type": "PullRequest"
        },
        {
            "LastUpdatedTimeStamp": 1588112205.207,
            "Name": "a1b2c3d4-5678-90ab-cdef-EXAMPLE55555",
            "ProviderType": "GitHub",
            "PullRequestId": "2",
            "MetricsSummary": {
                "MeteredLinesOfCodeCount": 25,
                "FindingsCount": 0
            },
            "CreatedTimeStamp": 1588111987.443,
            "State": "Completed",
            "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:code-review:a1b2c3d4-5678-90ab-cdef-EXAMPLE55555",
            "Owner": "sample-owner",
            "RepositoryName": "sample-repository-name",
            "Type": "PullRequest"
        },
        {
            "LastUpdatedTimeStamp": 1588104489.981,
            "Name": "a1b2c3d4-5678-90ab-cdef-EXAMPLE66666",
            "ProviderType": "GitHub",
            "PullRequestId": "1",
            "MetricsSummary": {
                "MeteredLinesOfCodeCount": 25,
                "FindingsCount": 0
            },
            "CreatedTimeStamp": 1588104270.223,
            "State": "Completed",
            "CodeReviewArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:code-review:a1b2c3d4-5678-90ab-cdef-EXAMPLE66666",
            "Owner": "sample-owner",
            "RepositoryName": "sample-repository-name",
            "Type": "PullRequest"
        }
    ]
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[View all code reviews](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/view-all-code-reviews.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCodeReviews](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/list-code-reviews.html)」を参照してください。

### `list-recommendation-feedback`
<a name="codeguru-reviewer_ListRecommendationFeedback_cli_2_topic"></a>

次のコード例は、`list-recommendation-feedback` を使用する方法を示しています。

**AWS CLI**  
**関連付けられたリポジトリの推奨事項に対する顧客からの推奨事項のフィードバックを一覧表示するには**  
次の `list-recommendation-feedback` では、コードレビューに関するすべての推奨事項に対する顧客からのフィードバックを一覧表示しています。このコードレビューには、顧客から「ThumbsUp」のフィードバックが １ つあります。  

```
aws codeguru-reviewer list-recommendation-feedback \
    --code-review-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:code-review:RepositoryAnalysis-my-repository-name-branch-abcdefgh12345678
```
出力:  

```
{
    "RecommendationFeedbackSummaries": [
        {
            "RecommendationId": "3be1b2e5d7ef6e298a06499379ee290c9c596cf688fdcadb08285ddb0dd390eb",
            "Reactions": [
                "ThumbsUp"
            ],
            "UserId": "aws-user-id"
        }
    ]
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Step 4: Provide feedback](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/provide-feedback.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRecommendationFeedback](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/list-recommendation-feedback.html)」を参照してください。

### `list-recommendations`
<a name="codeguru-reviewer_ListRecommendations_cli_2_topic"></a>

次のコード例は、`list-recommendations` を使用する方法を示しています。

**AWS CLI**  
**完了したコードレビューの推奨事項を一覧表示するには**  
次の `list-recommendations` の例では、完了したコードレビューの推奨事項を一覧表示しています。このコードレビューには 1 つの推奨事項があります。  

```
aws codeguru-reviewer list-recommendations \
    --code-review-arn arn:aws:codeguru-reviewer:us-west-2:544120495673:code-review:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RecommendationSummaries": [
        {
            "Description": "\n\n**Problem**  \n You are using a `ConcurrentHashMap`, but your usage of `containsKey()` and `get()` may not be thread-safe at lines: **63 and 64**. In between the check and the `get()` another thread can remove the key and the `get()` will return `null`. The remove that can remove the key is at line: **59**.\n\n**Fix**  \n Consider calling `get()`, checking instead of your current check if the returned object is `null`, and then using that object only, without calling `get()` again.\n\n**More info**  \n [View an example on GitHub](https://github.com/apache/hadoop/blob/f16cf877e565084c66bc63605659b157c4394dc8/hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/s3guard/S3Guard.java#L302-L304) (external link).",
            "RecommendationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "StartLine": 63,
            "EndLine": 64,
            "FilePath": "src/main/java/com/company/sample/application/CreateOrderThread.java"
        }
    ]
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Step 4: Provide feedback](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/provide-feedback.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRecommendations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/list-recommendations.html)」を参照してください。

### `list-repository-associations`
<a name="codeguru-reviewer_ListRepositoryAssociations_cli_2_topic"></a>

次の例は、`list-repository-associations` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのリポジトリの関連付けを一覧表示するには**  
次の `list-repository-associations` の例では、アカウントのリポジトリ関連付けサマリーオブジェクトのリストを返しています。返されたリストは、`ProviderType`、`Name`、`State`、および `Owner` でフィルタリングできます。  

```
aws codeguru-reviewer list-repository-associations
```
出力:  

```
{
    "RepositoryAssociationSummaries": [
        {
            "LastUpdatedTimeStamp": 1595886609.616,
            "Name": "test",
            "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Owner": "sample-owner",
            "State": "Associated",
            "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ProviderType": "Bitbucket"
        },
        {
            "LastUpdatedTimeStamp": 1595636969.035,
            "Name": "CodeDeploy-CodePipeline-ECS-Tutorial",
            "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "Owner": "123456789012",
            "State": "Associated",
            "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "ProviderType": "CodeCommit"
        },
        {
            "LastUpdatedTimeStamp": 1595634785.983,
            "Name": "My-ecs-beta-repo",
            "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "Owner": "123456789012",
            "State": "Associated",
            "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "ProviderType": "CodeCommit"
        },
        {
            "LastUpdatedTimeStamp": 1590712811.77,
            "Name": "MyTestCodeCommit",
            "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE44444",
            "Owner": "123456789012",
            "State": "Associated",
            "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE44444",
            "ProviderType": "CodeCommit"
        },
        {
            "LastUpdatedTimeStamp": 1588102637.649,
            "Name": "aws-codeguru-profiler-sample-application",
            "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE55555",
            "Owner": "sample-owner",
            "State": "Associated",
            "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE55555",
            "ProviderType": "GitHub"
        },
        {
            "LastUpdatedTimeStamp": 1588028233.995,
            "Name": "codeguru-profiler-demo-app",
            "AssociationId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE66666",
            "Owner": "sample-owner",
            "State": "Associated",
            "AssociationArn": "arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE66666",
            "ProviderType": "GitHub"
        }
    ]
}
```
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[View all repository associations in CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/repository-association-view-all.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRepositoryAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/list-repository-associations.html)」を参照してください。

### `list-tags-for-resource`
<a name="codeguru-reviewer_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**関連付けられたリポジトリのタグを一覧表示するには**  
次の `list-tags-for-resource` では、関連付けられたリポジトリのタグを一覧表示しています。この関連付けられたリポジトリには 2 つのタグがあります。  

```
aws codeguru-reviewer list-tags-for-resource \
    --resource-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "Tags": {
        "Status": "Secret",
        "Team": "Saanvi"
    }
}
```
詳細については、「Amazon [ CodeGuru Reviewer ユーザーガイド」の「View tags for a CodeGuru Reviewer associated repository (AWS CLI)](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/how-to-tag-associated-repository-view-cli.html)」を参照してください。 * CodeGuru *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/list-tags-for-resource.html)」を参照してください。

### `put-recommendation-feedback`
<a name="codeguru-reviewer_PutRecommendationFeedback_cli_2_topic"></a>

次のコード例は、`put-recommendation-feedback` を使用する方法を示しています。

**AWS CLI**  
**コードレビューに推奨事項を追加するには**  
次の `put-recommendation-feedback` では、コードレビューに `ThumbsUp` の推奨事項を付けています。  

```
aws codeguru-reviewer put-recommendation-feedback \
    --code-review-arn \arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:code-review:RepositoryAnalysis-my-repository-name-branch-abcdefgh12345678 \
    --recommendation-id 3be1b2e5d7ef6e298a06499379ee290c9c596cf688fdcadb08285ddb0dd390eb \
    --reactions ThumbsUp
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon CodeGuru Reviewer ユーザーガイド*」の「[Step 4: Provide feedback](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/provide-feedback.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRecommendationFeedback](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/put-recommendation-feedback.html)」を参照してください。

### `tag-resource`
<a name="codeguru-reviewer_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**関連付けられたリポジトリにタグを追加するには**  
次の `tag-resource` では、関連付けられたリポジトリに 2 つのタグを追加しています。  

```
aws codeguru-reviewer tag-resource \
    --resource-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --tags Status=Secret,Team=Saanvi
```
このコマンドでは何も出力されません。  
詳細については、「Amazon [ CodeGuru Reviewer User Guide」の「Add a tag to a CodeGuru Reviewer associated repository (AWS CLI)](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/how-to-tag-associated-repository-add-cli.html)」および[「Add or update tags for a CodeGuru Reviewer associated repository (AWS CLI)](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/how-to-tag-associated-repository-update-cli.html)」を参照してください。 * CodeGuru *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="codeguru-reviewer_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**関連付けられたリポジトリのタグを解除するには**  
次の `untag-resource` では、キー「Secret」と「Team」を持つ 2 つのタグを関連するリポジトリから削除しています。  

```
aws codeguru-reviewer untag-resource \
    --resource-arn arn:aws:codeguru-reviewer:us-west-2:123456789012:association:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --tag-keys Status Team
```
このコマンドでは何も出力されません。  
詳細については、「Amazon [ CodeGuru Reviewer ユーザーガイド」の「Remove tags from a CodeGuru Reviewer associated repository (AWS CLI)](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/how-to-tag-associated-repository-remove-cli.html)」を参照してください。 * CodeGuru *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codeguru-reviewer/untag-resource.html)」を参照してください。

# を使用した CodePipeline の例 AWS CLI
<a name="cli_2_codepipeline_code_examples"></a>

次のコード例は、CodePipeline AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `acknowledge-job`
<a name="codepipeline_AcknowledgeJob_cli_2_topic"></a>

次のコード例は、`acknowledge-job` を使用する方法を示しています。

**AWS CLI**  
**指定したジョブに関する情報を取得するには**  
この例では、指定したジョブが存在する場合、そのジョブのステータスなどの情報を返します。これは、ジョブワーカーとカスタムアクションにのみ使用されます。nonce の値とジョブ ID を判別するには、aws codepipeline poll-for-jobs を使用します。  
コマンド:  

```
aws codepipeline acknowledge-job --job-id f4f4ff82-2d11-EXAMPLE --nonce 3
```
出力:  

```
{
  "status": "InProgress"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcknowledgeJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/acknowledge-job.html)」を参照してください。

### `create-custom-action-type`
<a name="codepipeline_CreateCustomActionType_cli_2_topic"></a>

次のコード例は、`create-custom-action-type` を使用する方法を示しています。

**AWS CLI**  
**カスタムアクションを作成するには**  
この例では、カスタムアクションの構造を含む作成済みの JSON ファイル (ここでは MyCustomAction.json) を使用して AWS CodePipeline のカスタムアクションを作成します。ファイルの構造など、カスタムアクションを作成するための要件の詳細については、 AWS CodePipeline ユーザーガイドを参照してください。  

```
aws codepipeline create-custom-action-type --cli-input-json file://MyCustomAction.json
```
JSON ファイル `MyCustomAction.json` の内容。  

```
{
    "category": "Build",
    "provider": "MyJenkinsProviderName",
    "version": "1",
    "settings": {
        "entityUrlTemplate": "https://192.0.2.4/job/{Config:ProjectName}/",
        "executionUrlTemplate": "https://192.0.2.4/job/{Config:ProjectName}/lastSuccessfulBuild/{ExternalExecutionId}/"
    },
    "configurationProperties": [
        {
            "name": "MyJenkinsExampleBuildProject",
            "required": true,
            "key": true,
            "secret": false,
            "queryable": false,
            "description": "The name of the build project must be provided when this action is added to the pipeline.",
            "type": "String"
        }
    ],
    "inputArtifactDetails": {
        "maximumCount": 1,
        "minimumCount": 0
    },
    "outputArtifactDetails": {
        "maximumCount": 1,
        "minimumCount": 0
    }
}
```
このコマンドは、カスタムアクションの構造を返します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomActionType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/create-custom-action-type.html)」を参照してください。

### `create-pipeline`
<a name="codepipeline_CreatePipeline_cli_2_topic"></a>

次のコード例は、`create-pipeline` を使用する方法を示しています。

**AWS CLI**  
**パイプラインを作成するには**  
この例では、パイプラインの構造を含む作成済みの JSON ファイル (ここでは AWS CodePipeline にパイプラインを作成します。 MySecondPipeline.json) ファイルの構造など、パイプラインを作成するための要件の詳細については、 AWS CodePipeline ユーザーガイド」を参照してください。  
コマンド:  

```
aws codepipeline create-pipeline --cli-input-json file://MySecondPipeline.json
```
JSON ファイルのサンプルの内容:  

```
{
 "pipeline": {
  "roleArn": "arn:aws:iam::111111111111:role/AWS-CodePipeline-Service",
  "stages": [
    {
      "name": "Source",
      "actions": [
        {
          "inputArtifacts": [],
          "name": "Source",
          "actionTypeId": {
            "category": "Source",
            "owner": "AWS",
            "version": "1",
            "provider": "S3"
          },
          "outputArtifacts": [
            {
              "name": "MyApp"
            }
          ],
          "configuration": {
            "S3Bucket": "awscodepipeline-demo-bucket",
            "S3ObjectKey": "aws-codepipeline-s3-aws-codedeploy_linux.zip"
          },
          "runOrder": 1
        }
      ]
    },
    {
      "name": "Beta",
      "actions": [
        {
          "inputArtifacts": [
            {
              "name": "MyApp"
            }
          ],
          "name": "CodePipelineDemoFleet",
          "actionTypeId": {
            "category": "Deploy",
            "owner": "AWS",
            "version": "1",
            "provider": "CodeDeploy"
          },
          "outputArtifacts": [],
          "configuration": {
            "ApplicationName": "CodePipelineDemoApplication",
            "DeploymentGroupName": "CodePipelineDemoFleet"
          },
          "runOrder": 1
        }
      ]
    }
  ],
  "artifactStore": {
    "type": "S3",
    "location": "codepipeline-us-east-1-11EXAMPLE11"
  },
  "name": "MySecondPipeline",
  "version": 1
 }
}
```
出力:  

```
This command returns the structure of the pipeline.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/create-pipeline.html)」を参照してください。

### `delete-custom-action-type`
<a name="codepipeline_DeleteCustomActionType_cli_2_topic"></a>

次のコード例は、`delete-custom-action-type` を使用する方法を示しています。

**AWS CLI**  
**カスタムアクションを削除するには**  
この例では、削除するアクションのタイプ、プロバイダー名、バージョン番号を含む作成済みの JSON ファイル (ここでは DeleteMyCustomAction.json) を使用して、 AWS CodePipeline のカスタムアクションを削除します。list-action-types コマンドを使用して、カテゴリ、バージョン、プロバイダーの正しい値を表示します。  
コマンド:  

```
aws codepipeline delete-custom-action-type --cli-input-json file://DeleteMyCustomAction.json
```
JSON ファイルのサンプルの内容:  

```
{
  "category": "Build",
  "version": "1",
  "provider": "MyJenkinsProviderName"
}
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCustomActionType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/delete-custom-action-type.html)」を参照してください。

### `delete-pipeline`
<a name="codepipeline_DeletePipeline_cli_2_topic"></a>

次のコード例は、`delete-pipeline` を使用する方法を示しています。

**AWS CLI**  
**パイプラインを削除するには**  
この例では、MySecondPipeline という名前のパイプラインを AWS CodePipeline から削除します。list-pipelines コマンドを使用して、 AWS アカウントに関連付けられたパイプラインのリストを表示します。  
コマンド:  

```
aws codepipeline delete-pipeline --name MySecondPipeline
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/delete-pipeline.html)」を参照してください。

### `delete-webhook`
<a name="codepipeline_DeleteWebhook_cli_2_topic"></a>

次のコード例は、`delete-webhook` を使用する方法を示しています。

**AWS CLI**  
**ウェブフックを削除するには**  
次の `delete-webhook` の例では、GitHub バージョン 1 ソースアクションのウェブフックを削除します。ウェブフックを削除する前に、`deregister-webhook-with-third-party` コマンドを使用してそのウェブフックの登録を解除する必要があります。  

```
aws codepipeline delete-webhook \
    --name my-webhook
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[Delete the webhook for your GitHub source](https://docs.aws.amazon.com/codepipeline/latest/userguide/appendix-github-oauth.html#pipelines-webhooks-delete)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWebhook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/delete-webhook.html)」を参照してください。

### `deregister-webhook-with-third-party`
<a name="codepipeline_DeregisterWebhookWithThirdParty_cli_2_topic"></a>

次のコード例は、`deregister-webhook-with-third-party` を使用する方法を示しています。

**AWS CLI**  
**ウェブフックの登録を解除するには**  
次の `deregister-webhook-with-third-party` の例では、GitHub バージョン 1 ソースアクションのウェブフックを削除します。ウェブフックを削除する前に、その登録を解除する必要があります。  

```
aws codepipeline deregister-webhook-with-third-party \
    --webhook-name my-webhook
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[Delete the webhook for your GitHub source](https://docs.aws.amazon.com/codepipeline/latest/userguide/appendix-github-oauth.html#pipelines-webhooks-delete)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterWebhookWithThirdParty](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/deregister-webhook-with-third-party.html)」を参照してください。

### `disable-stage-transition`
<a name="codepipeline_DisableStageTransition_cli_2_topic"></a>

次のコード例は、`disable-stage-transition` を使用する方法を示しています。

**AWS CLI**  
**パイプライン内のステージへの移行を無効にするには**  
この例では、CodePipeline の MyFirstPipeline パイプラインのベータステージへの移行を無効にします AWS CodePipeline 。  
コマンド:  

```
aws codepipeline disable-stage-transition --pipeline-name MyFirstPipeline --stage-name Beta  --transition-type Inbound
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableStageTransition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/disable-stage-transition.html)」を参照してください。

### `enable-stage-transition`
<a name="codepipeline_EnableStageTransition_cli_2_topic"></a>

次のコード例は、`enable-stage-transition` を使用する方法を示しています。

**AWS CLI**  
**パイプライン内のステージへの移行を有効にするには**  
この例では、CodePipeline の MyFirstPipeline パイプラインのベータステージへの移行を有効にします AWS CodePipeline 。  
コマンド:  

```
aws codepipeline enable-stage-transition --pipeline-name MyFirstPipeline --stage-name Beta  --transition-type Inbound
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableStageTransition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/enable-stage-transition.html)」を参照してください。

### `get-job-details`
<a name="codepipeline_GetJobDetails_cli_2_topic"></a>

次のコード例は、`get-job-details` を使用する方法を示しています。

**AWS CLI**  
**ジョブの詳細を取得するには**  
この例では、ID が f4f4ff82-2d11-EXAMPLE で表されるジョブに関する詳細を返しています。このコマンドはカスタムアクションにのみ使用されます。このコマンドが呼び出されると、 AWS CodePipeline は、カスタムアクションで必要な場合、パイプラインのアーティファクトを保存するために使用される Amazon S3 バケットの一時的な認証情報を返します。このコマンドは、アクションに定義されているシークレット値がある場合は、それも返します。  
コマンド:  

```
aws codepipeline get-job-details --job-id f4f4ff82-2d11-EXAMPLE
```
出力:  

```
{
 "jobDetails": {
  "accountId": "111111111111",
  "data": {
    "actionConfiguration": {
      "__type": "ActionConfiguration",
      "configuration": {
        "ProjectName": "MyJenkinsExampleTestProject"
      }
    },
    "actionTypeId": {
      "__type": "ActionTypeId",
      "category": "Test",
      "owner": "Custom",
      "provider": "MyJenkinsProviderName",
      "version": "1"
    },
    "artifactCredentials": {
      "__type": "AWSSessionCredentials",
      "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
      "secretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
      "sessionToken": "fICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcNMTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9TrDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpEIbb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0FkbFFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTbNYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE="
    },
    "inputArtifacts": [
      {
        "__type": "Artifact",
        "location": {
          "s3Location": {
            "bucketName": "codepipeline-us-east-1-11EXAMPLE11",
            "objectKey": "MySecondPipeline/MyAppBuild/EXAMPLE"
          },
          "type": "S3"
        },
        "name": "MyAppBuild"
      }
    ],
    "outputArtifacts": [],
    "pipelineContext": {
      "__type": "PipelineContext",
      "action": {
        "name": "MyJenkinsTest-Action"
      },
      "pipelineName": "MySecondPipeline",
      "stage": {
        "name": "Testing"
      }
    }
  },
  "id": "f4f4ff82-2d11-EXAMPLE"
 }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetJobDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/get-job-details.html)」を参照してください。

### `get-pipeline-state`
<a name="codepipeline_GetPipelineState_cli_2_topic"></a>

次のコード例は、`get-pipeline-state` を使用する方法を示しています。

**AWS CLI**  
**パイプラインの状態に関する情報を取得するには**  
この例では、MyFirstPipeline という名前のパイプラインの最新の状態を返しています。  
コマンド:  

```
aws codepipeline get-pipeline-state --name MyFirstPipeline
```
出力:  

```
{
 "created": 1446137312.204,
 "pipelineName": "MyFirstPipeline",
 "pipelineVersion": 1,
 "stageStates": [
  {
    "actionStates": [
      {
        "actionName": "Source",
        "entityUrl": "https://console.aws.amazon.com/s3/home?#",
        "latestExecution": {
          "lastStatusChange": 1446137358.328,
          "status": "Succeeded"
        }
      }
    ],
    "stageName": "Source"
  },
  {
    "actionStates": [
      {
        "actionName": "CodePipelineDemoFleet",
        "entityUrl": "https://console.aws.amazon.com/codedeploy/home?#/applications/CodePipelineDemoApplication/deployment-groups/CodePipelineDemoFleet",
        "latestExecution": {
          "externalExecutionId": "d-EXAMPLE",
          "externalExecutionUrl": "https://console.aws.amazon.com/codedeploy/home?#/deployments/d-EXAMPLE",
          "lastStatusChange": 1446137493.131,
          "status": "Succeeded",
          "summary": "Deployment Succeeded"
        }
      }
    ],
    "inboundTransitionState": {
      "enabled": true
    },
    "stageName": "Beta"
  }
 ],
 "updated": 1446137312.204
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPipelineState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/get-pipeline-state.html)」を参照してください。

### `get-pipeline`
<a name="codepipeline_GetPipeline_cli_2_topic"></a>

次のコード例は、`get-pipeline` を使用する方法を示しています。

**AWS CLI**  
**パイプラインの構造を表示するには**  
この例では、MyFirstPipeline という名前のパイプラインの構造を返しています。  
コマンド:  

```
aws codepipeline get-pipeline --name MyFirstPipeline
```
出力:  

```
{
  "pipeline": {
      "roleArn": "arn:aws:iam::111111111111:role/AWS-CodePipeline-Service",
      "stages": [
          {
              "name": "Source",
              "actions": [
                  {
                      "inputArtifacts": [],
                      "name": "Source",
                      "actionTypeId": {
                          "category": "Source",
                          "owner": "AWS",
                          "version": "1",
                          "provider": "S3"
                      },
                      "outputArtifacts": [
                          {
                              "name": "MyApp"
                          }
                      ],
                      "configuration": {
                          "S3Bucket": "awscodepipeline-demo-bucket",
                          "S3ObjectKey": "aws-codepipeline-s3-aws-codedeploy_linux.zip"
                      },
                      "runOrder": 1
                  }
              ]
          },
          {
              "name": "Beta",
              "actions": [
                  {
                      "inputArtifacts": [
                          {
                              "name": "MyApp"
                          }
                      ],
                      "name": "CodePipelineDemoFleet",
                      "actionTypeId": {
                          "category": "Deploy",
                          "owner": "AWS",
                          "version": "1",
                          "provider": "CodeDeploy"
                      },
                      "outputArtifacts": [],
                      "configuration": {
                          "ApplicationName": "CodePipelineDemoApplication",
                          "DeploymentGroupName": "CodePipelineDemoFleet"
                      },
                      "runOrder": 1
                  }
              ]
          }
      ],
      "artifactStore": {
          "type": "S3",
          "location": "codepipeline-us-east-1-11EXAMPLE11"
      },
      "name": "MyFirstPipeline",
      "version": 1
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/get-pipeline.html)」を参照してください。

### `list-action-executions`
<a name="codepipeline_ListActionExecutions_cli_2_topic"></a>

次のコード例は、`list-action-executions` を使用する方法を示しています。

**AWS CLI**  
**アクション実行を一覧表示するには**  
次の `list-action-executions` の例では、パイプラインのアクションの実行に関する詳細として、アクション実行 ID、入力アーティファクト、出力アーティファクト、実行結果、ステータスなどを表示しています。  

```
aws codepipeline list-action-executions \
    --pipeline-name myPipeline
```
出力:  

```
{
    "actionExecutionDetails": [
        {
            "pipelineExecutionId": "EXAMPLE0-adfc-488e-bf4c-1111111720d3",
            "actionExecutionId": "EXAMPLE4-2ee8-4853-bd6a-111111158148",
            "pipelineVersion": 12,
            "stageName": "Deploy",
            "actionName": "Deploy",
            "startTime": 1598572628.6,
            "lastUpdateTime": 1598572661.255,
            "status": "Succeeded",
            "input": {
                "actionTypeId": {
                    "category": "Deploy",
                    "owner": "AWS",
                    "provider": "CodeDeploy",
                    "version": "1"
                },
                "configuration": {
                    "ApplicationName": "my-application",
                    "DeploymentGroupName": "my-deployment-group"
                },
                "resolvedConfiguration": {
                    "ApplicationName": "my-application",
                    "DeploymentGroupName": "my-deployment-group"
                },
                "region": "us-east-1",
                "inputArtifacts": [
                    {
                        "name": "SourceArtifact",
                        "s3location": {
                            "bucket": "artifact-bucket",
                            "key": "myPipeline/SourceArti/key"
                        }
                    }
                ],
                "namespace": "DeployVariables"
            },
            "output": {
                "outputArtifacts": [],
                "executionResult": {
                    "externalExecutionId": "d-EXAMPLEE5",
                    "externalExecutionSummary": "Deployment Succeeded",
                    "externalExecutionUrl": "https://myaddress.com"
                },
                "outputVariables": {}
            }
        },
        {
            "pipelineExecutionId": "EXAMPLE0-adfc-488e-bf4c-1111111720d3",
            "actionExecutionId": "EXAMPLE5-abb4-4192-9031-11111113a7b0",
            "pipelineVersion": 12,
            "stageName": "Source",
            "actionName": "Source",
            "startTime": 1598572624.387,
            "lastUpdateTime": 1598572628.16,
            "status": "Succeeded",
            "input": {
                "actionTypeId": {
                    "category": "Source",
                    "owner": "AWS",
                    "provider": "CodeCommit",
                    "version": "1"
                },
                "configuration": {
                    "BranchName": "production",
                    "PollForSourceChanges": "false",
                    "RepositoryName": "my-repo"
                },
                "resolvedConfiguration": {
                    "BranchName": "production",
                    "PollForSourceChanges": "false",
                    "RepositoryName": "my-repo"
                },
                "region": "us-east-1",
                "inputArtifacts": [],
                "namespace": "SourceVariables"
            },
            "output": {
                "outputArtifacts": [
                    {
                        "name": "SourceArtifact",
                        "s3location": {
                            "bucket": "amzn-s3-demo-bucket",
                            "key": "myPipeline/SourceArti/key"
                        }
                    }
                ],
                "executionResult": {
                    "externalExecutionId": "1111111ad99dcd35914c00b7fbea13995EXAMPLE",
                    "externalExecutionSummary": "Edited template.yml",
                    "externalExecutionUrl": "https://myaddress.com"
                },
                "outputVariables": {
                    "AuthorDate": "2020-05-08T17:45:43Z",
                    "BranchName": "production",
                    "CommitId": "EXAMPLEad99dcd35914c00b7fbea139951111111",
                    "CommitMessage": "Edited template.yml",
                    "CommitterDate": "2020-05-08T17:45:43Z",
                    "RepositoryName": "my-repo"
                }
            }
        },
. . . .
```
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[View action executions (CLI)](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-view-cli.html#pipelines-action-executions-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListActionExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/list-action-executions.html)」を参照してください。

### `list-action-types`
<a name="codepipeline_ListActionTypes_cli_2_topic"></a>

次のコード例は、`list-action-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能なアクションタイプを表示するには**  
単独で使用する list-action-types コマンドは、 AWS アカウントで使用できるすべてのアクションの構造を返します。この例では、--action-owner-filter オプションを使用して、カスタムアクションのみを返しています。  
コマンド:  

```
aws codepipeline list-action-types --action-owner-filter Custom
```
出力:  

```
{
  "actionTypes": [
      {
          "inputArtifactDetails": {
              "maximumCount": 5,
              "minimumCount": 0
          },
          "actionConfigurationProperties": [
              {
                  "secret": false,
                  "required": true,
                  "name": "MyJenkinsExampleBuildProject",
                  "key": true,
                  "queryable": true
              }
          ],
          "outputArtifactDetails": {
              "maximumCount": 5,
              "minimumCount": 0
          },
          "id": {
              "category": "Build",
              "owner": "Custom",
              "version": "1",
              "provider": "MyJenkinsProviderName"
          },
          "settings": {
              "entityUrlTemplate": "http://192.0.2.4/job/{Config:ProjectName}",
              "executionUrlTemplate": "http://192.0.2.4/job/{Config:ProjectName}/{ExternalExecutionId}"
          }
      },
      {
          "inputArtifactDetails": {
              "maximumCount": 5,
              "minimumCount": 0
          },
          "actionConfigurationProperties": [
              {
                  "secret": false,
                  "required": true,
                  "name": "MyJenkinsExampleTestProject",
                  "key": true,
                  "queryable": true
              }
          ],
          "outputArtifactDetails": {
              "maximumCount": 5,
              "minimumCount": 0
          },
          "id": {
              "category": "Test",
              "owner": "Custom",
              "version": "1",
              "provider": "MyJenkinsProviderName"
          },
          "settings": {
              "entityUrlTemplate": "http://192.0.2.4/job/{Config:ProjectName}",
              "executionUrlTemplate": "http://192.0.2.4/job/{Config:ProjectName}/{ExternalExecutionId}"
          }
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListActionTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/list-action-types.html)」を参照してください。

### `list-pipeline-executions`
<a name="codepipeline_ListPipelineExecutions_cli_2_topic"></a>

次のコード例は、`list-pipeline-executions` を使用する方法を示しています。

**AWS CLI**  
**パイプラインの実行履歴を表示するには**  
次の`list-pipeline-executions`例は、 AWS アカウントのパイプラインのパイプライン実行履歴を示しています。  

```
aws codepipeline list-pipeline-executions \
    --pipeline-name MyPipeline
```
出力:  

```
{
    "pipelineExecutionSummaries": [
        {
            "lastUpdateTime": 1496380678.648,
            "pipelineExecutionId": "7cf7f7cb-3137-539g-j458-d7eu3EXAMPLE",
            "startTime": 1496380258.243,
            "status": "Succeeded"
        },
        {
            "lastUpdateTime": 1496591045.634,
            "pipelineExecutionId": "3137f7cb-8d494hj4-039j-d84l-d7eu3EXAMPLE",
            "startTime": 1496590401.222,
            "status": "Succeeded"
        },
        {
            "lastUpdateTime": 1496946071.6456,
            "pipelineExecutionId": "4992f7jf-7cf7-913k-k334-d7eu3EXAMPLE",
            "startTime": 1496945471.5645,
            "status": "Succeeded"
        }
    ]
}
```
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[View execution history](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-view-cli.html#pipelines-executions-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPipelineExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/list-pipeline-executions.html)」を参照してください。

### `list-pipelines`
<a name="codepipeline_ListPipelines_cli_2_topic"></a>

次のコード例は、`list-pipelines` を使用する方法を示しています。

**AWS CLI**  
**パイプラインのリストを表示するには**  
この例では、ユーザーの AWS アカウントに関連付けられているすべての AWS CodePipeline パイプラインを一覧表示します。  
コマンド:  

```
aws codepipeline list-pipelines
```
出力:  

```
{
  "pipelines": [
      {
          "updated": 1439504274.641,
          "version": 1,
          "name": "MyFirstPipeline",
          "created": 1439504274.641
      },
      {
          "updated": 1436461837.992,
          "version": 2,
          "name": "MySecondPipeline",
          "created": 1436460801.381
      }
      ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPipelines](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/list-pipelines.html)」を参照してください。

### `list-tags-for-resource`
<a name="codepipeline_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**タグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定されたパイプラインリソースにアタッチされたすべてのタグのリストを取得しています。  

```
aws codepipeline list-tags-for-resource \
    --resource-arn arn:aws:codepipeline:us-east-1:123456789012:MyPipeline
```
出力:  

```
{
    "tags": {
        "Project": "ProjectA",
        "IscontainerBased": "true"
    }
}
```
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[View tags for a pipeline (CLI)](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-tag.html#pipelines-tag-list-cli)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/list-tags-for-resource.html)」を参照してください。

### `list-webhooks`
<a name="codepipeline_ListWebhooks_cli_2_topic"></a>

次のコード例は、`list-webhooks` を使用する方法を示しています。

**AWS CLI**  
**ウェブフックを一覧表示するには**  
次の `list-webhooks` の例では、指定されたパイプラインリソースにアタッチされたすべてのタグのリストを取得しています。  

```
aws codepipeline list-webhooks \
    --endpoint-url "https://codepipeline.eu-central-1.amazonaws.com" \
    --region "eu-central-1"
```
出力:  

```
{
    "webhooks": [
        {
            "url": "https://webhooks.domain.com/trigger111111111EXAMPLE11111111111111111": {
                "authenticationConfiguration": {
                    "SecretToken": "Secret"
                },
                "name": "my-webhook",
                "authentication": "GITHUB_HMAC",
                "targetPipeline": "my-Pipeline",
                "targetAction": "Source",
                "filters": [
                    {
                        "jsonPath": "$.ref",
                        "matchEquals": "refs/heads/{Branch}"
                    }
                ]
            },
            "arn": "arn:aws:codepipeline:eu-central-1:123456789012:webhook:my-webhook"
        }
    ]
}
```
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[List webhooks in your account](https://docs.aws.amazon.com/codepipeline/latest/userguide/appendix-github-oauth.html#pipelines-webhooks-view)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWebhooks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/list-webhooks.html)」を参照してください。

### `poll-for-jobs`
<a name="codepipeline_PollForJobs_cli_2_topic"></a>

次のコード例は、`poll-for-jobs` を使用する方法を示しています。

**AWS CLI**  
**使用可能なジョブを表示するには**  
この例では、ジョブワーカーが実行するジョブに関する情報を返しています。この例では、事前定義済みの JSON ファイル (MyActionTypeInfo.json) を使用して、ジョブワーカーがジョブを処理するアクションタイプに関する情報を提供しています。このコマンドはカスタムアクションにのみ使用されます。このコマンドが呼び出されると、 AWS CodePipeline はパイプラインのアーティファクトの保存に使用される Amazon S3 バケットの一時的な認証情報を返します。このコマンドは、アクションに定義されているシークレット値がある場合は、それも返します。  
コマンド:  

```
aws codepipeline poll-for-jobs --cli-input-json file://MyActionTypeInfo.json
```
JSON ファイルのサンプルの内容:  

```
{
  "actionTypeId": {
    "category": "Test",
    "owner": "Custom",
    "provider": "MyJenkinsProviderName",
    "version": "1"
  },
  "maxBatchSize": 5,
  "queryParam": {
      "ProjectName": "MyJenkinsTestProject"
  }
}
```
出力:  

```
{
 "jobs": [
  {
    "accountId": "111111111111",
    "data": {
      "actionConfiguration": {
        "__type": "ActionConfiguration",
        "configuration": {
          "ProjectName": "MyJenkinsExampleTestProject"
        }
      },
      "actionTypeId": {
        "__type": "ActionTypeId",
        "category": "Test",
        "owner": "Custom",
        "provider": "MyJenkinsProviderName",
        "version": "1"
      },
      "artifactCredentials": {
        "__type": "AWSSessionCredentials",
        "accessKeyId": "AKIAIOSFODNN7EXAMPLE",
        "secretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "sessionToken": "fICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcNMTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9TrDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpEIbb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0FkbFFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTbNYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE="
      },
      "inputArtifacts": [
        {
          "__type": "Artifact",
          "location": {
            "s3Location": {
              "bucketName": "codepipeline-us-east-1-11EXAMPLE11",
              "objectKey": "MySecondPipeline/MyAppBuild/EXAMPLE"
            },
            "type": "S3"
          },
          "name": "MyAppBuild"
        }
      ],
      "outputArtifacts": [],
      "pipelineContext": {
        "__type": "PipelineContext",
        "action": {
          "name": "MyJenkinsTest-Action"
        },
        "pipelineName": "MySecondPipeline",
        "stage": {
          "name": "Testing"
        }
      }
    },
    "id": "ef66c259-64f9-EXAMPLE",
    "nonce": "3"
  }
 ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PollForJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/poll-for-jobs.html)」を参照してください。

### `put-webhook`
<a name="codepipeline_PutWebhook_cli_2_topic"></a>

次のコード例は、`put-webhook` を使用する方法を示しています。

**AWS CLI**  
**ウェブフックを作成するには**  
次の `put-webhook` の例では、GitHub バージョン 1 ソースアクションのウェブフックを作成しています。ウェブフックを作成したら、register-webhook-with-third-party コマンドを使用してウェブフックを登録する必要があります。  

```
aws codepipeline put-webhook \
    --cli-input-json file://webhook_json.json \
    --region "eu-central-1"
```
`webhook_json.json` の内容:  

```
{
    "webhook": {
        "name": "my-webhook",
        "targetPipeline": "pipeline_name",
        "targetAction": "source_action_name",
        "filters": [
            {
                "jsonPath": "$.ref",
                "matchEquals": "refs/heads/{Branch}"
            }
        ],
        "authentication": "GITHUB_HMAC",
        "authenticationConfiguration": {
            "SecretToken": "secret"
        }
    }
}
```
出力:  

```
{
    "webhook": {
        "url": "https://webhooks.domain.com/trigger111111111EXAMPLE11111111111111111",
        "definition": {
            "authenticationConfiguration": {
                "SecretToken": "secret"
            },
            "name": "my-webhook",
            "authentication": "GITHUB_HMAC",
            "targetPipeline": "pipeline_name",
            "targetAction": "Source",
            "filters": [
                {
                    "jsonPath": "$.ref",
                    "matchEquals": "refs/heads/{Branch}"
                }
            ]
        },
        "arn": "arn:aws:codepipeline:eu-central-1:123456789012:webhook:my-webhook"
    },
    "tags": [
        {
            "key": "Project",
            "value": "ProjectA"
        }
    ]
}
```
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[Create a webhook for a GitHub source](https://docs.aws.amazon.com/codepipeline/latest/userguide/appendix-github-oauth.html#pipelines-webhooks-create)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutWebhook](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/put-webhook.html)」を参照してください。

### `retry-stage-execution`
<a name="codepipeline_RetryStageExecution_cli_2_topic"></a>

次のコード例は、`retry-stage-execution` を使用する方法を示しています。

**AWS CLI**  
**失敗したアクションを再試行するには**  
次の `retry-stage-execution` の例では、失敗したアクションを持つステージを再試行しています。  

```
aws codepipeline retry-stage-execution \
    --pipeline-name MyPipeline \
    --stage-name Deploy \
    --pipeline-execution-id b59babff-5f34-EXAMPLE \
    --retry-mode FAILED_ACTIONS
```
出力:  

```
{
    "pipelineExecutionId": "b59babff-5f34-EXAMPLE"
}
```
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[Retry failed actions (CLI)](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-retry.html#actions-retry-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RetryStageExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/retry-stage-execution.html)」を参照してください。

### `start-pipeline-execution`
<a name="codepipeline_StartPipelineExecution_cli_2_topic"></a>

次のコード例は、`start-pipeline-execution` を使用する方法を示しています。

**AWS CLI**  
**パイプラインを介して最新のリビジョンを実行するには**  
この例では、「MyFirstPipeline」という名前のパイプラインを介して、パイプラインのソースステージに存在する最新のリビジョンを実行しています。  
コマンド:  

```
aws codepipeline start-pipeline-execution --name MyFirstPipeline
```
出力:  

```
{
  "pipelineExecutionId": "3137f7cb-7cf7-EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartPipelineExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/start-pipeline-execution.html)」を参照してください。

### `stop-pipeline-execution`
<a name="codepipeline_StopPipelineExecution_cli_2_topic"></a>

次のコード例は、`stop-pipeline-execution` を使用する方法を示しています。

**AWS CLI**  
**パイプライン実行を停止するには**  
次の `stop-pipeline-execution` の例では、デフォルトで進行中のアクションが完了するまで待機し、その後パイプラインを停止しています。実行がすでに [停止] 状態になっている場合、[Stop and wait (停止して待機)] を選択することはできません。実行がすでに [停止] 状態になっている場合、[Stop and abandon (停止して中止)] を選択することはできません。  

```
aws codepipeline stop-pipeline-execution \
    --pipeline-name MyFirstPipeline \
    --pipeline-execution-id d-EXAMPLE \
    --reason "Stopping pipeline after the build action is done"
```
このコマンドは出力なしを返します。  
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[Stop a pipeline execution (CLI)](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-stop.html#pipelines-stop-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopPipelineExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/stop-pipeline-execution.html)」を参照してください。

### `tag-resource`
<a name="codepipeline_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、提供されたタグのセットをパイプラインに関連付けています。このコマンドを使用して、タグを追加または編集します。  

```
aws codepipeline tag-resource \
    --resource-arn arn:aws:codepipeline:us-east-1:123456789012:MyPipeline \
    --tags key=Project,value=ProjectA key=IscontainerBased,value=true
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[Add tags to a pipeline (CLI)](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-tag.html#pipelines-tag-add-cli)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="codepipeline_UntagResource_cli_2_topic"></a>

次の例は、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**接続リソースから AWS タグを削除するには**  
次の `untag-resource` の例では、指定されたリソースからタグを削除しています。  

```
aws codepipeline untag-resource \
    --resource-arn arn:aws:codepipeline:us-east-1:123456789012:MyPipeline \
    --tag-keys Project IscontainerBased
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodePipeline ユーザーガイド*」の「[Remove tags from a pipeline (CLI)](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-tag.html#pipelines-tag-delete-cli)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/untag-resource.html)」を参照してください。

### `update-pipeline`
<a name="codepipeline_UpdatePipeline_cli_2_topic"></a>

次のコード例は、`update-pipeline` を使用する方法を示しています。

**AWS CLI**  
**パイプラインの構造を更新するには**  
この例では、update-pipeline コマンドで --cli-input-json 引数を使用しています。この例では、事前定義された JSON ファイル (MyFirstPipeline.json) を使用してパイプラインの構造を更新します。 AWS CodePipeline は JSON ファイルに含まれるパイプライン名を認識し、パイプライン構造内の変更されたフィールドからの変更を適用してパイプラインを更新します。  
事前定義された JSON ファイルを作成するときは、次のガイドラインを使用します。  
get-pipeline コマンドを使用して取得したパイプライン構造を使用する場合は、JSON ファイル内のパイプライン構造からメタデータセクション (「metadata」: \$1 \$1 行と、「created」、「pipelineARN」、「updated」フィールド) を削除する必要があります。パイプライン名は変更できません。  
コマンド:  

```
aws codepipeline update-pipeline --cli-input-json file://MyFirstPipeline.json
```
サンプル JSON ファイルの内容:  

```
{
 "pipeline": {
  "roleArn": "arn:aws:iam::111111111111:role/AWS-CodePipeline-Service",
  "stages": [
    {
      "name": "Source",
      "actions": [
        {
          "inputArtifacts": [],
          "name": "Source",
          "actionTypeId": {
            "category": "Source",
            "owner": "AWS",
            "version": "1",
            "provider": "S3"
          },
          "outputArtifacts": [
            {
              "name": "MyApp"
            }
          ],
          "configuration": {
            "S3Bucket": "awscodepipeline-demo-bucket2",
            "S3ObjectKey": "aws-codepipeline-s3-aws-codedeploy_linux.zip"
          },
          "runOrder": 1
        }
      ]
    },
    {
      "name": "Beta",
      "actions": [
        {
          "inputArtifacts": [
            {
              "name": "MyApp"
            }
          ],
          "name": "CodePipelineDemoFleet",
          "actionTypeId": {
            "category": "Deploy",
            "owner": "AWS",
            "version": "1",
            "provider": "CodeDeploy"
          },
          "outputArtifacts": [],
          "configuration": {
            "ApplicationName": "CodePipelineDemoApplication",
            "DeploymentGroupName": "CodePipelineDemoFleet"
          },
          "runOrder": 1
        }
      ]
    }
  ],
  "artifactStore": {
    "type": "S3",
    "location": "codepipeline-us-east-1-11EXAMPLE11"
  },
  "name": "MyFirstPipeline",
  "version": 1
 }
}
```
出力:  

```
{
 "pipeline": {
  "artifactStore": {
    "location": "codepipeline-us-east-1-11EXAMPLE11",
    "type": "S3"
  },
  "name": "MyFirstPipeline",
  "roleArn": "arn:aws:iam::111111111111:role/AWS-CodePipeline-Service",
  "stages": [
    {
      "actions": [
        {
          "actionTypeId": {
            "__type": "ActionTypeId",
            "category": "Source",
            "owner": "AWS",
            "provider": "S3",
            "version": "1"
          },
          "configuration": {
            "S3Bucket": "awscodepipeline-demo-bucket2",
            "S3ObjectKey": "aws-codepipeline-s3-aws-codedeploy_linux.zip"
          },
          "inputArtifacts": [],
          "name": "Source",
          "outputArtifacts": [
            {
              "name": "MyApp"
            }
          ],
          "runOrder": 1
        }
      ],
      "name": "Source"
    },
    {
      "actions": [
        {
          "actionTypeId": {
            "__type": "ActionTypeId",
            "category": "Deploy",
            "owner": "AWS",
            "provider": "CodeDeploy",
            "version": "1"
          },
          "configuration": {
            "ApplicationName": "CodePipelineDemoApplication",
            "DeploymentGroupName": "CodePipelineDemoFleet"
          },
          "inputArtifacts": [
            {
              "name": "MyApp"
            }
          ],
          "name": "CodePipelineDemoFleet",
          "outputArtifacts": [],
          "runOrder": 1
        }
      ],
      "name": "Beta"
    }
  ],
  "version": 3
 }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/update-pipeline.html)」を参照してください。

# AWS CodeStar を使用した通知の例 AWS CLI
<a name="cli_2_codestar-notifications_code_examples"></a>

次のコード例は、 AWS CodeStar 通知 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-notification-rule`
<a name="codestar-notifications_CreateNotificationRule_cli_2_topic"></a>

次のコード例は、`create-notification-rule` を使用する方法を示しています。

**AWS CLI**  
**通知ルールを作成するには**  
次の`create-notification-rule`例では、 という名前の JSON ファイルを使用して`rule.json`、`MyDemoRepo`指定された AWS アカウントの という名前のリポジトリ`MyNotificationRule`に という名前の通知ルールを作成します。ブランチとタグが作成されると、詳細タイプが `FULL` の通知が指定されたターゲットである Amazon SNS トピックに送信されます。  

```
aws codestar-notifications create-notification-rule \
    --cli-input-json file://rule.json
```
`rule.json` の内容:  

```
{
    "Name": "MyNotificationRule",
    "EventTypeIds": [
        "codecommit-repository-branches-and-tags-created"
    ],
    "Resource": "arn:aws:codecommit:us-east-1:123456789012:MyDemoRepo",
    "Targets": [
        {
            "TargetType": "SNS",
            "TargetAddress": "arn:aws:sns:us-east-1:123456789012:MyNotificationTopic"
        }
    ],
    "Status": "ENABLED",
    "DetailType": "FULL"
}
```
出力:  

```
{
    "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE"
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Create a Notification rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNotificationRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/create-notification-rule.html)」を参照してください。

### `delete-notification-rule`
<a name="codestar-notifications_DeleteNotificationRule_cli_2_topic"></a>

次のコード例は、`delete-notification-rule` を使用する方法を示しています。

**AWS CLI**  
**通知ルールを削除するには**  
次の `delete-notification-rule` の例では、指定された通知ルールを削除しています。  

```
aws codestar-notifications delete-notification-rule \
    --arn arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE
```
出力:  

```
{
    "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE"
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Delete a Notification Rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNotificationRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/delete-notification-rule.html)」を参照してください。

### `delete-target`
<a name="codestar-notifications_DeleteTarget_cli_2_topic"></a>

次のコード例は、`delete-target` を使用する方法を示しています。

**AWS CLI**  
**通知ルールのターゲットを削除するには**  
次の `delete-target` の例では、指定したターゲットを、ターゲットとして使用するように設定されているすべての通知ルールから削除し、次にそのターゲットも削除しています。  

```
aws codestar-notifications  delete-target \
    --target-address arn:aws:sns:us-east-1:123456789012:MyNotificationTopic \
    --force-unsubscribe-all
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Delete a Notification Rule Target](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-target-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/delete-target.html)」を参照してください。

### `describe-notification-rule`
<a name="codestar-notifications_DescribeNotificationRule_cli_2_topic"></a>

次のコード例は、`describe-notification-rule` を使用する方法を示しています。

**AWS CLI**  
**通知ルールの詳細を取得するには**  
次の `describe-notification-rule` の例では、指定された通知ルールの詳細を取得しています。  

```
aws codestar-notifications describe-notification-rule \
    --arn arn:aws:codestar-notifications:us-west-2:123456789012:notificationrule/dc82df7a-EXAMPLE
```
出力:  

```
{
    "LastModifiedTimestamp": 1569199844.857,
    "EventTypes": [
        {
            "ServiceName": "CodeCommit",
            "EventTypeName": "Branches and tags: Created",
            "ResourceType": "Repository",
            "EventTypeId": "codecommit-repository-branches-and-tags-created"
        }
    ],
    "Status": "ENABLED",
    "DetailType": "FULL",
    "Resource": "arn:aws:codecommit:us-west-2:123456789012:MyDemoRepo",
    "Arn": "arn:aws:codestar-notifications:us-west-w:123456789012:notificationrule/dc82df7a-EXAMPLE",
    "Targets": [
        {
            "TargetStatus": "ACTIVE",
            "TargetAddress": "arn:aws:sns:us-west-2:123456789012:MyNotificationTopic",
            "TargetType": "SNS"
        }
    ],
    "Name": "MyNotificationRule",
    "CreatedTimestamp": 1569199844.857,
    "CreatedBy": "arn:aws:iam::123456789012:user/Mary_Major"
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[View Notification Rules](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNotificationRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/describe-notification-rule.html)」を参照してください。

### `list-event-types`
<a name="codestar-notifications_ListEventTypes_cli_2_topic"></a>

次のコード例は、`list-event-types` を使用する方法を示しています。

**AWS CLI**  
**通知ルールのイベントタイプのリストを取得するには**  
次の `list-event-types` の例では、CodeDeploy アプリケーションで使用可能なすべての通知イベントタイプのフィルタリングされたリストを取得しています。フィルターを使用しない場合、コマンドはすべてのリソースタイプに対するすべての通知イベントタイプを返します。  

```
aws codestar-notifications list-event-types \
    --filters Name=SERVICE_NAME,Value=CodeDeploy
```
出力:  

```
{
    "EventTypes": [
        {
            "EventTypeId": "codedeploy-application-deployment-succeeded",
            "ServiceName": "CodeDeploy",
            "EventTypeName": "Deployment: Succeeded",
            "ResourceType": "Application"
        },
        {
            "EventTypeId": "codedeploy-application-deployment-failed",
            "ServiceName": "CodeDeploy",
            "EventTypeName": "Deployment: Failed",
            "ResourceType": "Application"
        },
        {
            "EventTypeId": "codedeploy-application-deployment-started",
            "ServiceName": "CodeDeploy",
            "EventTypeName": "Deployment: Started",
            "ResourceType": "Application"
        }
    ]
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Create a Notification Rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEventTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/list-event-types.html)」を参照してください。

### `list-notification-rules`
<a name="codestar-notifications_ListNotificationRules_cli_2_topic"></a>

次のコード例は、`list-notification-rules` を使用する方法を示しています。

**AWS CLI**  
**通知ルールのリストを取得するには**  
次の の`list-notification-rules`例では、指定された AWS リージョン内のすべての通知ルールのリストを取得します。  

```
aws codestar-notifications list-notification-rules --region us-east-1
```
出力:  

```
{
    "NotificationRules": [
        {
            "Id": "dc82df7a-EXAMPLE",
            "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE"
        },
        {
            "Id": "8d1f0983-EXAMPLE",
            "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/8d1f0983-EXAMPLE"
        }
    ]
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[View Notification Rules](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListNotificationRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/list-notification-rules.html)」を参照してください。

### `list-tags-for-resource`
<a name="codestar-notifications_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**通知ルールにアタッチされたタグのリストを取得するには**  
次の `list-tags-for-resource` の例では、指定された通知ルールにアタッチされたすべてのタグのリストを取得しています。この例では現在、通知ルールに関連付けられているタグがありません。  

```
aws codestar-notifications list-tags-for-resource \
    --arn arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/fe1efd35-EXAMPLE
```
出力:  

```
{
    "Tags": {}
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Create a Notification Rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-create.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/list-tags-for-resource.html)」を参照してください。

### `list-targets`
<a name="codestar-notifications_ListTargets_cli_2_topic"></a>

次のコード例は、`list-targets` を使用する方法を示しています。

**AWS CLI**  
**通知ルールのターゲットのリストを取得するには**  
次の の`list-targets`例では、指定された AWS リージョン内のすべての通知ルールターゲットのリストを取得します。  

```
aws codestar-notifications list-targets \
    --region us-east-1
```
出力:  

```
{
    "Targets": [
        {
            "TargetAddress": "arn:aws:sns:us-east-1:123456789012:MySNSTopicForNotificationRules",
            "TargetType": "SNS",
            "TargetStatus": "ACTIVE"
        },
        {
            "TargetAddress": "arn:aws:sns:us-east-1:123456789012:MySNSTopicForNotificationsAboutMyDemoRepo",
            "TargetType": "SNS",
            "TargetStatus": "ACTIVE"
        }
    ]
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[View Notification Rule Targets](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-target-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/list-targets.html)」を参照してください。

### `subscribe`
<a name="codestar-notifications_Subscribe_cli_2_topic"></a>

次のコード例は、`subscribe` を使用する方法を示しています。

**AWS CLI**  
**通知ルールにターゲットを追加するには**  
次の `subscribe` の例では、指定された通知ルールのターゲットとして Amazon SNS トピックを追加しています。  

```
aws codestar-notifications subscribe \
    --arn arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE \
    --target TargetType=SNS,TargetAddress=arn:aws:sns:us-east-1:123456789012:MyNotificationTopic
```
出力:  

```
{
    "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE"
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Add or Remove an Amazon SNS Topic as a Target for a Notification Rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-target-change-rule.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Subscribe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/subscribe.html)」を参照してください。

### `tag-resource`
<a name="codestar-notifications_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**通知ルールにタグを追加するには**  
次の `tag-resource` の例では、指定された通知ルールにキー名が `Team`、値が `Li_Juan` のタグを追加しています。  

```
aws codestar-notifications tag-resource \
    --arn arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/fe1efd35-EXAMPLE \
    --tags Team=Li_Juan
```
出力:  

```
{
    "Tags": {
        "Team": "Li_Juan"
    }
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Create a Notification Rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/tag-resource.html)」を参照してください。

### `unsubscribe`
<a name="codestar-notifications_Unsubscribe_cli_2_topic"></a>

次のコード例は、`unsubscribe` を使用する方法を示しています。

**AWS CLI**  
**通知ルールからターゲットを削除するには**  
次の `unsubscribe` の例では、指定された通知ルールのターゲットである Amazon SNS トピックを削除しています。  

```
aws codestar-notifications unsubscribe \
    --arn arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE \
    --target TargetType=SNS,TargetAddress=arn:aws:sns:us-east-1:123456789012:MyNotificationTopic
```
出力:  

```
{
    "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE"
    "TargetAddress": "arn:aws:sns:us-east-1:123456789012:MyNotificationTopic"
}
```
詳細については、「*AWS Developer Tools Console ユーザーガイド*」の「[Add or Remove an Amazon SNS Topic as a Target for a Notification Rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-target-change-rule.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Unsubscribe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/unsubscribe.html)」を参照してください。

### `untag-resource`
<a name="codestar-notifications_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**通知ルールからタグを削除するには**  
次の `untag-resource` の例では、指定された通知ルールからキー名が `Team` のタグを削除しています。  

```
aws codestar-notifications untag-resource \
    --arn arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/fe1efd35-EXAMPLE \
    --tag-keys Team
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Developer Tools console ユーザーガイド*」の「[Edit a Notification Rule](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notification-rule-edit.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/untag-resource.html)」を参照してください。

### `update-notification-rule`
<a name="codestar-notifications_UpdateNotificationRule_cli_2_topic"></a>

次のコード例は、`update-notification-rule` を使用する方法を示しています。

**AWS CLI**  
**通知ルールを更新するには**  
次の の`update-notification-rule`例では、 という名前の JSON ファイル`123456789012`を使用して、 AWS アカウント`MyNotificationRule`内の という名前の通知ルールを更新します`update.json`。  

```
aws codestar-notifications update-notification-rule \
    --cli-input-json file://update.json
```
`update.json` の内容:  

```
{
    "Name": "MyUpdatedNotificationRule",
    "EventTypeIds": [
        "codecommit-repository-branches-and-tags-created"
    ],
    "Resource": "arn:aws:codecommit:us-east-1:123456789012:MyDemoRepo",
    "Targets": [
        {
            "TargetType": "SNS",
            "TargetAddress": "arn:aws:sns:us-east-1:123456789012:MyNotificationTopic"
        }
    ],
    "Status": "ENABLED",
    "DetailType": "FULL"
}
```
出力:  

```
{
    "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE"
}
```
詳細については、「*AWS Developer Tools console ユーザーガイド*」の「[Edit a notification rule](https://docs.aws.amazon.com/dtconsole/latest/userguide/notification-rule-edit.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateNotificationRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-notifications/update-notification-rule.html)」を参照してください。

# を使用した CodeConnections の例 AWS CLI
<a name="cli_2_codestar-connections_code_examples"></a>

次のコード例は、CodeConnections AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-connection`
<a name="codestar-connections_CreateConnection_cli_2_topic"></a>

次のコード例は、`create-connection` を使用する方法を示しています。

**AWS CLI**  
**接続を作成するには**  
次の `create-connection` の例では、サードパーティーのリポジトリへの接続を作成する方法を示しています。この例では、サードパーティーのプロバイダーが Bitbucket である接続を作成しています。  
CLI または AWS CloudFormation AWS を介して作成された接続は、デフォルトで保留中のステータスになります。CLI または AWS CloudFormation との接続を作成したら、コンソールを使用して接続を編集し、ステータスを使用可能にします。  

```
aws codestar-connections create-connection \
    --provider-type Bitbucket \
    --connection-name MyConnection
```
出力:  

```
{
    "ConnectionArn": "arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f"
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[Create a connection](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/create-connection.html)」を参照してください。

### `create-host`
<a name="codestar-connections_CreateHost_cli_2_topic"></a>

次のコード例は、`create-host` を使用する方法を示しています。

**AWS CLI**  
**ホストを作成するには**  
次の `create-host` の例では、ホストを作成して、サードパーティーのプロバイダーがインストールされているインフラストラクチャのエンドポイントを表す方法を示しています。この例では、サードパーティーのインストールされたプロバイダーが GitHub Enterprise Server であるホストを作成しています。  
 AWS CLI を使用して作成されたホストは、デフォルトで保留中のステータスです。CLI でホストを作成した後、コンソールまたは CLI を使用してホストを設定し、ステータスを [使用可能] にします。  

```
aws codestar-connections create-host \
    --name MyHost \
    --provider-type GitHubEnterpriseServer \
    --provider-endpoint "https://my-instance.dev"
```
出力:  

```
{
    "HostArn": "arn:aws:codestar-connections:us-east-1:123456789012:host/My-Host-28aef605"
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[Create a host (CLI)](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-host-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateHost](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/create-host.html)」を参照してください。

### `delete-connection`
<a name="codestar-connections_DeleteConnection_cli_2_topic"></a>

次のコード例は、`delete-connection` を使用する方法を示しています。

**AWS CLI**  
**接続を削除するには**  
次の `delete-connection` の例では、接続を削除する方法を示しています。  

```
aws codestar-connections delete-connection \
    --connection-arn arn:aws:codestar-connections:us-west-2:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f
```
このコマンドでは何も出力されません。  
詳細については、「*Developer Tools console ユーザーガイド*」の「[Delete a connection (CLI)](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-delete.html#connections-delete-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/delete-connection.html)」を参照してください。

### `delete-host`
<a name="codestar-connections_DeleteHost_cli_2_topic"></a>

次のコード例は、`delete-host` を使用する方法を示しています。

**AWS CLI**  
**ホストを削除するには**  
次の `delete-host` の例では、ホストを削除する方法を示しています。ホストを削除する前に、ホストに関連付けられたすべての接続を削除する必要があります。  

```
aws codestar-connections delete-host \
    --host-arn "arn:aws:codestar-connections:us-east-1 :123456789012:host/My-Host-28aef605"
```
このコマンドでは何も出力されません。  
詳細については、「*Developer Tools console ユーザーガイド*」の「[Delete a host (CLI)](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-host-delete.html#connections-host-delete-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteHost](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/delete-host.html)」を参照してください。

### `get-connection`
<a name="codestar-connections_GetConnection_cli_2_topic"></a>

次のコード例は、`get-connection` を使用する方法を示しています。

**AWS CLI**  
**接続に関する情報を取得するには**  
次の `get-connection` の例では、接続の詳細を示します。  

```
aws codestar-connections get-connection \
    --connection-arn arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f
```
出力:  

```
{
    "Connection": {
        "ConnectionName": "MyConnection",
        "ConnectionArn": "arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f",
        "ProviderType": "Bitbucket",
        "OwnerAccountId": "123456789012",
        "ConnectionStatus": "AVAILABLE"
    }
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[View connection details](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-view-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/get-connection.html)」を参照してください。

### `get-host`
<a name="codestar-connections_GetHost_cli_2_topic"></a>

次のコード例は、`get-host` を使用する方法を示しています。

**AWS CLI**  
**ホストに関する情報を取得するには**  
次の `get-host` の例では、ホストの詳細を示します。  

```
aws codestar-connections get-host \
    --host-arn arn:aws:codestar-connections:us-east-1:123456789012:host/MyHost-28aef605
```
出力:  

```
{
    "Name": "MyHost",
    "Status": "AVAILABLE",
    "ProviderType": "GitHubEnterpriseServer",
    "ProviderEndpoint": "https://test-instance-1.dev/"
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[View host details (CLI)](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-host-view.html#connections-host-view-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetHost](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/get-host.html)」を参照してください。

### `list-connections`
<a name="codestar-connections_ListConnections_cli_2_topic"></a>

次のコード例は、`list-connections` を使用する方法を示しています。

**AWS CLI**  
**接続を一覧表示するには**  
次の `list-connections` の例では、Bitbucket プロバイダタイプのアカウント内のすべての接続のリストを取得しています。  

```
aws codestar-connections list-connections \
--provider-type Bitbucket \
--max-results 5 \
--next-token: next-token
```
出力:  

```
{
    "Connections": [
        {
            "ConnectionName": "my-connection",
            "ProviderType": "Bitbucket",
            "Status": "PENDING",
            "ARN": "arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f",
            "OwnerAccountId": "123456789012"
        },
        {
            "ConnectionName": "my-other-connection",
            "ProviderType": "Bitbucket",
            "Status": "AVAILABLE",
            "ARN": "arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f",
            "OwnerAccountId": "123456789012"
        },
    ],
    "NextToken": "next-token"
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[List connections (CLI)](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-list.html#connections-list-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/list-connections.html)」を参照してください。

### `list-hosts`
<a name="codestar-connections_ListHosts_cli_2_topic"></a>

次のコード例は、`list-hosts` を使用する方法を示しています。

**AWS CLI**  
**ホストを一覧表示するには**  
次の `list-hosts` の例では、アカウント内のすべてのホストのリストを取得しています。  

```
aws codestar-connections list-hosts
```
出力:  

```
{
    "Hosts": [
        {
            "Name": "My-Host",
            "HostArn": "arn:aws:codestar-connections:us-east-1:123456789012:host/My-Host-28aef605",
            "ProviderType": "GitHubEnterpriseServer",
            "ProviderEndpoint": "https://my-instance.test.dev",
            "Status": "AVAILABLE"
        }
    ]
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[List hosts (CLI)](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-host-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/list-hosts.html)」を参照してください。

### `list-tags-for-resource`
<a name="codestar-connections_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**タグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された接続リソースにアタッチされたすべてのタグのリストを取得しています。  

```
aws codestar-connections list-tags-for-resource \
    --resource-arn arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Project",
            "Value": "ProjectA"
        },
        {
            "Key": "ReadOnly",
            "Value": "true"
        }
    ]
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[View tags for a connections resource](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-tag.html#connections-tag-view)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/list-tags-for-resource.html)」を参照してください。

### `tag-resource`
<a name="codestar-connections_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、提供されたタグのセットを接続に関連付けています。このコマンドを使用して、タグを追加または編集します。  

```
aws codestar-connections tag-resource \
    --resource-arn arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f \
    --tags Key=Project,Value=ProjectA Key=IscontainerBased,Value=true
```
このコマンドでは何も出力されません。  
詳細については、「*Developer Tools console ユーザーガイド*」の「[Add tags to a connections resource](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-tag.html#connections-tag-add)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="codestar-connections_UntagResource_cli_2_topic"></a>

次の例は、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**接続リソースから AWS タグを削除するには**  
次の `untag-resource` では、指定されたリソースからタグを削除しています。  

```
aws codestar-connections untag-resource \
    --resource-arn arn:aws:codestar-connections:us-east-1:123456789012:connection/aEXAMPLE-8aad-4d5d-8878-dfcab0bc441f \
    --tag-keys Project ReadOnly
```
出力:  

```
{
    "Tags": []
}
```
詳細については、「*Developer Tools console ユーザーガイド*」の「[Remove tags from a connections resource](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-tag.html#connections-tag-delete)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codestar-connections/untag-resource.html)」を参照してください。

# を使用した Amazon Cognito ID の例 AWS CLI
<a name="cli_2_cognito-identity_code_examples"></a>

次のコード例は、Amazon Cognito Identity AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-identity-pool`
<a name="cognito-identity_CreateIdentityPool_cli_2_topic"></a>

次のコード例は、`create-identity-pool` を使用する方法を示しています。

**AWS CLI**  
**Cognito アイデンティティプールプロバイダーを含むアイデンティティプールを作成するには**  
この例では MyIdentityPool という名前のアイデンティティプールを作成します。これには Cognito アイデンティティプールプロバイダーが含まれます。認証されていないアイデンティティは許可されません。  
コマンド:  

```
aws cognito-identity create-identity-pool --identity-pool-name MyIdentityPool --no-allow-unauthenticated-identities --cognito-identity-providers ProviderName="cognito-idp.us-west-2.amazonaws.com/us-west-2_aaaaaaaaa",ClientId="3n4b5urk1ft4fl3mg5e62d9ado",ServerSideTokenCheck=false
```
出力:  

```
{
  "IdentityPoolId": "us-west-2:11111111-1111-1111-1111-111111111111",
  "IdentityPoolName": "MyIdentityPool",
  "AllowUnauthenticatedIdentities": false,
  "CognitoIdentityProviders": [
      {
          "ProviderName": "cognito-idp.us-west-2.amazonaws.com/us-west-2_111111111",
          "ClientId": "3n4b5urk1ft4fl3mg5e62d9ado",
          "ServerSideTokenCheck": false
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIdentityPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/create-identity-pool.html)」を参照してください。

### `delete-identities`
<a name="cognito-identity_DeleteIdentities_cli_2_topic"></a>

次のコード例は、`delete-identities` を使用する方法を示しています。

**AWS CLI**  
**アイデンティティプールを削除するには**  
この例ではアイデンティティプールを削除しています。  
コマンド:  

```
aws cognito-identity delete-identity-pool --identity-ids-to-delete "us-west-2:11111111-1111-1111-1111-111111111111"
```
出力:  

```
{
  "UnprocessedIdentityIds": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIdentities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/delete-identities.html)」を参照してください。

### `delete-identity-pool`
<a name="cognito-identity_DeleteIdentityPool_cli_2_topic"></a>

次のコード例は、`delete-identity-pool` を使用する方法を示しています。

**AWS CLI**  
**アイデンティティプールを削除するには**  
次の `delete-identity-pool` 例では、指定したアイデンティティプールを削除します。  
コマンド:  

```
aws cognito-identity delete-identity-pool \
    --identity-pool-id "us-west-2:11111111-1111-1111-1111-111111111111"
```
このコマンドでは何も出力されません。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteIdentityPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/delete-identity-pool.html)」を参照してください。**

### `describe-identity-pool`
<a name="cognito-identity_DescribeIdentityPool_cli_2_topic"></a>

次のコード例は、`describe-identity-pool` を使用する方法を示しています。

**AWS CLI**  
**アイデンティティプールを記述するには**  
この例では、アイデンティティプールをを記述します。  
コマンド:  

```
aws cognito-identity describe-identity-pool --identity-pool-id "us-west-2:11111111-1111-1111-1111-111111111111"
```
出力:  

```
{
  "IdentityPoolId": "us-west-2:11111111-1111-1111-1111-111111111111",
  "IdentityPoolName": "MyIdentityPool",
  "AllowUnauthenticatedIdentities": false,
  "CognitoIdentityProviders": [
      {
          "ProviderName": "cognito-idp.us-west-2.amazonaws.com/us-west-2_111111111",
          "ClientId": "3n4b5urk1ft4fl3mg5e62d9ado",
          "ServerSideTokenCheck": false
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIdentityPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/describe-identity-pool.html)」を参照してください。

### `get-identity-pool-roles`
<a name="cognito-identity_GetIdentityPoolRoles_cli_2_topic"></a>

次のコード例は、`get-identity-pool-roles` を使用する方法を示しています。

**AWS CLI**  
**アイデンティティプールのロールを取得するには**  
この例ではアイデンティティプールのロールを取得しています。  
コマンド:  

```
aws cognito-identity get-identity-pool-roles --identity-pool-id "us-west-2:11111111-1111-1111-1111-111111111111"
```
出力:  

```
{
  "IdentityPoolId": "us-west-2:11111111-1111-1111-1111-111111111111",
  "Roles": {
      "authenticated": "arn:aws:iam::111111111111:role/Cognito_MyIdentityPoolAuth_Role",
      "unauthenticated": "arn:aws:iam::111111111111:role/Cognito_MyIdentityPoolUnauth_Role"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIdentityPoolRoles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/get-identity-pool-roles.html)」を参照してください。

### `list-identity-pools`
<a name="cognito-identity_ListIdentityPools_cli_2_topic"></a>

次のコード例は、`list-identity-pools` を使用する方法を示しています。

**AWS CLI**  
**アイデンティティプールを一覧表示するには**  
この例ではアイデンティティプールを一覧表示します。最大 20 個のアイデンティティが一覧表示されます。  
コマンド:  

```
aws cognito-identity list-identity-pools --max-results 20
```
出力:  

```
{
  "IdentityPools": [
      {
          "IdentityPoolId": "us-west-2:11111111-1111-1111-1111-111111111111",
          "IdentityPoolName": "MyIdentityPool"
      },
      {
          "IdentityPoolId": "us-west-2:11111111-1111-1111-1111-111111111111",
          "IdentityPoolName": "AnotherIdentityPool"
      },
      {
          "IdentityPoolId": "us-west-2:11111111-1111-1111-1111-111111111111",
          "IdentityPoolName": "IdentityPoolRegionA"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIdentityPools](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/list-identity-pools.html)」を参照してください。

### `set-identity-pool-roles`
<a name="cognito-identity_SetIdentityPoolRoles_cli_2_topic"></a>

次のコード例は、`set-identity-pool-roles` を使用する方法を示しています。

**AWS CLI**  
**アイデンティティプールのロールを設定するには**  
次の `set-identity-pool-roles` の例では、アイデンティティプールのロールを設定しています。  

```
aws cognito-identity set-identity-pool-roles \
    --identity-pool-id "us-west-2:11111111-1111-1111-1111-111111111111" \
    --roles authenticated="arn:aws:iam::111111111111:role/Cognito_MyIdentityPoolAuth_Role"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetIdentityPoolRoles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/set-identity-pool-roles.html)」を参照してください。

### `update-identity-pool`
<a name="cognito-identity_UpdateIdentityPool_cli_2_topic"></a>

次のコード例は、`update-identity-pool` を使用する方法を示しています。

**AWS CLI**  
**アイデンティティプールを更新するには**  
この例では、アイデンティティプールを更新しています。名前を「MyIdentityPool」に設定します。Cognito をアイデンティティプロバイダとして追加します。認証されていないアイデンティティは許可されません。  
コマンド:  

```
aws cognito-identity update-identity-pool --identity-pool-id "us-west-2:11111111-1111-1111-1111-111111111111" --identity-pool-name "MyIdentityPool" --no-allow-unauthenticated-identities --cognito-identity-providers ProviderName="cognito-idp.us-west-2.amazonaws.com/us-west-2_111111111",ClientId="3n4b5urk1ft4fl3mg5e62d9ado",ServerSideTokenCheck=false
```
出力:  

```
{
  "IdentityPoolId": "us-west-2:11111111-1111-1111-1111-111111111111",
  "IdentityPoolName": "MyIdentityPool",
  "AllowUnauthenticatedIdentities": false,
  "CognitoIdentityProviders": [
      {
          "ProviderName": "cognito-idp.us-west-2.amazonaws.com/us-west-2_111111111",
          "ClientId": "3n4b5urk1ft4fl3mg5e62d9ado",
          "ServerSideTokenCheck": false
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIdentityPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-identity/update-identity-pool.html)」を参照してください。

# を使用した Amazon Cognito ID プロバイダーの例 AWS CLI
<a name="cli_2_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダー AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-custom-attributes`
<a name="cognito-identity-provider_AddCustomAttributes_cli_2_topic"></a>

次のコード例は、`add-custom-attributes` を使用する方法を示しています。

**AWS CLI**  
**カスタム属性を追加するには**  
この例では、カスタム属性 CustomAttr1 をユーザープールに追加しています。これは文字列型のため、1 文字以上 15 文字以下にする必要があります。この値は必須ではありません。  
コマンド:  

```
aws cognito-idp add-custom-attributes --user-pool-id us-west-2_aaaaaaaaa --custom-attributes Name="CustomAttr1",AttributeDataType="String",DeveloperOnlyAttribute=false,Required=false,StringAttributeConstraints="{MinLength=1,MaxLength=15}"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddCustomAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/add-custom-attributes.html)」を参照してください。

### `admin-add-user-to-group`
<a name="cognito-identity-provider_AdminAddUserToGroup_cli_2_topic"></a>

次のコード例は、`admin-add-user-to-group` を使用する方法を示しています。

**AWS CLI**  
**ユーザーをグループに追加するには**  
この例では、MyGroup にユーザー Jane を追加しています。  
コマンド:  

```
aws cognito-idp admin-add-user-to-group --user-pool-id us-west-2_aaaaaaaaa --username Jane --group-name MyGroup
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminAddUserToGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-add-user-to-group.html)」を参照してください。

### `admin-confirm-sign-up`
<a name="cognito-identity-provider_AdminConfirmSignUp_cli_2_topic"></a>

次のコード例は、`admin-confirm-sign-up` を使用する方法を示しています。

**AWS CLI**  
**ユーザー登録を確認するには**  
この例では、ユーザー jane@example.com を確認しています。  
コマンド:  

```
aws cognito-idp admin-confirm-sign-up --user-pool-id us-west-2_aaaaaaaaa --username jane@example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminConfirmSignUp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-confirm-sign-up.html)」を参照してください。

### `admin-create-user`
<a name="cognito-identity-provider_AdminCreateUser_cli_2_topic"></a>

次のコード例は、`admin-create-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを作成するには**  
次の `admin-create-user` の例では、指定された設定の E メールアドレスと電話番号のユーザーを作成しています。  

```
aws cognito-idp admin-create-user \
    --user-pool-id us-west-2_aaaaaaaaa \
    --username diego \
    --user-attributes Name=email,Value=diego@example.com Name=phone_number,Value="+15555551212" \
    --message-action SUPPRESS
```
出力:  

```
{
    "User": {
        "Username": "diego",
        "Attributes": [
            {
                "Name": "sub",
                "Value": "7325c1de-b05b-4f84-b321-9adc6e61f4a2"
            },
            {
                "Name": "phone_number",
                "Value": "+15555551212"
            },
            {
                "Name": "email",
                "Value": "diego@example.com"
            }
        ],
        "UserCreateDate": 1548099495.428,
        "UserLastModifiedDate": 1548099495.428,
        "Enabled": true,
        "UserStatus": "FORCE_CHANGE_PASSWORD"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminCreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-create-user.html)」を参照してください。

### `admin-delete-user-attributes`
<a name="cognito-identity-provider_AdminDeleteUserAttributes_cli_2_topic"></a>

次のコード例は、`admin-delete-user-attributes` を使用する方法を示しています。

**AWS CLI**  
**ユーザー属性を削除するには**  
この例では、ユーザー diego@example.com のカスタム属性 CustomAttr1 を削除しています。  
コマンド:  

```
aws cognito-idp admin-delete-user-attributes --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com --user-attribute-names "custom:CustomAttr1"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminDeleteUserAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-delete-user-attributes.html)」を参照してください。

### `admin-delete-user`
<a name="cognito-identity-provider_AdminDeleteUser_cli_2_topic"></a>

次のコード例は、`admin-delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
この例では、ユーザーを削除します。  
コマンド:  

```
aws cognito-idp admin-delete-user --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminDeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-delete-user.html)」を参照してください。

### `admin-disable-provider-for-user`
<a name="cognito-identity-provider_AdminDisableProviderForUser_cli_2_topic"></a>

次のコード例は、`admin-disable-provider-for-user` を使用する方法を示しています。

**AWS CLI**  
**フェデレーションユーザーをローカルユーザープロファイルからリンク解除するには**  
次の `admin-disable-provider-for-user` の例では、Google ユーザーをローカルプロファイルからリンク解除します。  

```
aws cognito-idp admin-disable-provider-for-user \
    --user-pool-id us-west-2_EXAMPLE \
    --user ProviderAttributeName=Cognito_Subject,ProviderAttributeValue=0000000000000000,ProviderName=Google
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[フェデレーションユーザーを既存のユーザープロファイルにリンクする](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation-consolidate-users.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AdminDisableProviderForUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-disable-provider-for-user.html)」を参照してください。

### `admin-disable-user`
<a name="cognito-identity-provider_AdminDisableUser_cli_2_topic"></a>

次のコード例は、`admin-disable-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーによるサインインを禁止するには**  
次の `admin-disable-user` の例では、ユーザー `diego@example.com` によるサインインを禁止します。  

```
aws cognito-idp admin-disable-user \
    --user-pool-id us-west-2_EXAMPLE \
    --username diego@example.com
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザーの管理](https://docs.aws.amazon.com/cognito/latest/developerguide/managing-users.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AdminDisableUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-disable-user.html)」を参照してください。

### `admin-enable-user`
<a name="cognito-identity-provider_AdminEnableUser_cli_2_topic"></a>

次のコード例は、`admin-enable-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーによるサインインを有効にするには**  
次の `admin-enable-user` の例では、ユーザー diego@example.com によるサインインを有効にします。  

```
aws cognito-idp admin-enable-user \
    --user-pool-id us-west-2_EXAMPLE \
    --username diego@example.com
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザーの管理](https://docs.aws.amazon.com/cognito/latest/developerguide/managing-users.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AdminEnableUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-enable-user.html)」を参照してください。

### `admin-forget-device`
<a name="cognito-identity-provider_AdminForgetDevice_cli_2_topic"></a>

次のコード例は、`admin-forget-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスの「記憶済み」状態を解除するには**  
この例では、ユーザー名 jane@example.com のデバイスの「記憶済み」状態を解除しています  
コマンド:  

```
aws cognito-idp admin-forget-device --user-pool-id us-west-2_aaaaaaaaa --username jane@example.com --device-key us-west-2_abcd_1234-5678
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminForgetDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-forget-device.html)」を参照してください。

### `admin-get-device`
<a name="cognito-identity-provider_AdminGetDevice_cli_2_topic"></a>

次のコード例は、`admin-get-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスを取得するには**  
次の `admin-get-device` の例では、ユーザー `diego` の 1 つのデバイスを表示します。  

```
aws cognito-idp admin-get-device \
    --user-pool-id us-west-2_EXAMPLE \
    --username diego \
    --device-key us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "Device": {
        "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "DeviceAttributes": [
            {
                "Name": "device_status",
                "Value": "valid"
            },
            {
                "Name": "device_name",
                "Value": "MyDevice"
            },
            {
                "Name": "dev:device_arn",
                "Value": "arn:aws:cognito-idp:us-west-2:123456789012:owner/diego.us-west-2_EXAMPLE/device/us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
            },
            {
                "Name": "dev:device_owner",
                "Value": "diego.us-west-2_EXAMPLE"
            },
            {
                "Name": "last_ip_used",
                "Value": "192.0.2.1"
            },
            {
                "Name": "dev:device_remembered_status",
                "Value": "remembered"
            },
            {
                "Name": "dev:device_sdk",
                "Value": "aws-sdk"
            }
        ],
        "DeviceCreateDate": 1715100742.022,
        "DeviceLastModifiedDate": 1723233651.167,
        "DeviceLastAuthenticatedDate": 1715100742.0
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープール内のユーザーデバイスの使用](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminGetDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-get-device.html)」を参照してください。

### `admin-get-user`
<a name="cognito-identity-provider_AdminGetUser_cli_2_topic"></a>

次のコード例は、`admin-get-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを取得するには**  
この例では、ユーザー名 jane@example.com に関する情報を取得します。  
コマンド:  

```
aws cognito-idp admin-get-user --user-pool-id us-west-2_aaaaaaaaa --username jane@example.com
```
出力:  

```
{
  "Username": "4320de44-2322-4620-999b-5e2e1c8df013",
  "Enabled": true,
  "UserStatus": "FORCE_CHANGE_PASSWORD",
  "UserCreateDate": 1548108509.537,
  "UserAttributes": [
      {
          "Name": "sub",
          "Value": "4320de44-2322-4620-999b-5e2e1c8df013"
      },
      {
          "Name": "email_verified",
          "Value": "true"
      },
      {
          "Name": "phone_number_verified",
          "Value": "true"
      },
      {
          "Name": "phone_number",
          "Value": "+01115551212"
      },
      {
          "Name": "email",
          "Value": "jane@example.com"
      }
  ],
  "UserLastModifiedDate": 1548108509.537
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AdminGetUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-get-user.html)」を参照してください。**

### `admin-initiate-auth`
<a name="cognito-identity-provider_AdminInitiateAuth_cli_2_topic"></a>

次のコード例は、`admin-initiate-auth` を使用する方法を示しています。

**AWS CLI**  
**管理者としてユーザーのサインインを許可するには**  
次の `admin-initiate-auth` の例では、ユーザー diego@example.com のサインインを許可します。この例には、脅威保護のためのメタデータと Lambda トリガーのための ClientMetadata も含まれています。ユーザーは TOTP MFA 用に設定されており、認証を完了する前に、認証アプリケーションからコードの入力を求めるチャレンジを受け取ります。  

```
aws cognito-idp admin-initiate-auth \
    --user-pool-id us-west-2_EXAMPLE \
    --client-id 1example23456789 \
    --auth-flow ADMIN_USER_PASSWORD_AUTH \
    --auth-parameters USERNAME=diego@example.com,PASSWORD="My@Example$Password3!",SECRET_HASH=ExampleEncodedClientIdSecretAndUsername= \
    --context-data="{\"EncodedData\":\"abc123example\",\"HttpHeaders\":[{\"headerName\":\"UserAgent\",\"headerValue\":\"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\"}],\"IpAddress\":\"192.0.2.1\",\"ServerName\":\"example.com\",\"ServerPath\":\"/login\"}" \
    --client-metadata="{\"MyExampleKey\": \"MyExampleValue\"}"
```
出力:  

```
{
    "ChallengeName": "SOFTWARE_TOKEN_MFA",
    "Session": "AYABeExample...",
    "ChallengeParameters": {
        "FRIENDLY_DEVICE_NAME": "MyAuthenticatorApp",
        "USER_ID_FOR_SRP": "diego@example.com"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[管理認証フロー](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-admin-authentication-flow)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AdminInitiateAuth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-initiate-auth.html)」を参照してください。**

### `admin-link-provider-for-user`
<a name="cognito-identity-provider_AdminLinkProviderForUser_cli_2_topic"></a>

次のコード例は、`admin-link-provider-for-user` を使用する方法を示しています。

**AWS CLI**  
**ローカルユーザーをフェデレーションユーザーにリンクするには**  
次の `admin-link-provider-for-user` の例では、ローカルユーザー diego を、Google でフェデレーションサインインを行うユーザーにリンクします。  

```
aws cognito-idp admin-link-provider-for-user \
    --user-pool-id us-west-2_EXAMPLE \
    --destination-user ProviderName=Cognito,ProviderAttributeValue=diego \
    --source-user ProviderAttributeName=Cognito_Subject,ProviderAttributeValue=0000000000000000,ProviderName=Google
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[フェデレーションユーザーを既存のユーザープロファイルにリンクする](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation-consolidate-users.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AdminLinkProviderForUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-link-provider-for-user.html)」を参照してください。

### `admin-list-devices`
<a name="cognito-identity-provider_AdminListDevices_cli_2_topic"></a>

次のコード例は、`admin-list-devices` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのデバイスを一覧表示するには**  
次の `admin-list-devices` の例では、ユーザー diego のデバイスを一覧表示します。  

```
aws cognito-idp admin-list-devices \
    --user-pool-id us-west-2_EXAMPLE \
    --username diego \
    --limit 1
```
出力:  

```
{
    "Devices": [
        {
            "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "DeviceAttributes": [
                {
                    "Name": "device_status",
                    "Value": "valid"
                },
                {
                    "Name": "device_name",
                    "Value": "MyDevice"
                },
                {
                    "Name": "dev:device_arn",
                    "Value": "arn:aws:cognito-idp:us-west-2:123456789012:owner/diego.us-west-2_EXAMPLE/device/us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
                },
                {
                    "Name": "dev:device_owner",
                    "Value": "diego.us-west-2_EXAMPLE"
                },
                {
                    "Name": "last_ip_used",
                    "Value": "192.0.2.1"
                },
                {
                    "Name": "dev:device_remembered_status",
                    "Value": "remembered"
                },
                {
                    "Name": "dev:device_sdk",
                    "Value": "aws-sdk"
                }
            ],
            "DeviceCreateDate": 1715100742.022,
            "DeviceLastModifiedDate": 1723233651.167,
            "DeviceLastAuthenticatedDate": 1715100742.0
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープール内のユーザーデバイスの使用](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminListDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-list-devices.html)」を参照してください。

### `admin-list-groups-for-user`
<a name="cognito-identity-provider_AdminListGroupsForUser_cli_2_topic"></a>

次のコード例は、`admin-list-groups-for-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのグループを一覧表示するには**  
この例では、ユーザー名 jane@example.com のグループを一覧表示しています。  
コマンド:  

```
aws cognito-idp admin-list-groups-for-user --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com
```
出力:  

```
{
  "Groups": [
      {
          "Description": "Sample group",
          "Precedence": 1,
          "LastModifiedDate": 1548097827.125,
          "RoleArn": "arn:aws:iam::111111111111:role/SampleRole",
          "GroupName": "SampleGroup",
          "UserPoolId": "us-west-2_aaaaaaaaa",
          "CreationDate": 1548097827.125
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminListGroupsForUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-list-groups-for-user.html)」を参照してください。

### `admin-list-user-auth-events`
<a name="cognito-identity-provider_AdminListUserAuthEvents_cli_2_topic"></a>

次のコード例は、`admin-list-user-auth-events` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの承認イベントを一覧表示するには**  
次の `admin-list-user-auth-events` の例では、ユーザー diego の最新のユーザーアクティビティログイベントを一覧表示します。  

```
aws cognito-idp admin-list-user-auth-events \
    --user-pool-id us-west-2_ywDJHlIfU \
    --username brcotter+050123 \
    --max-results 1
```
出力:  

```
{
    "AuthEvents": [
        {
            "EventId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "EventType": "SignIn",
            "CreationDate": 1726694203.495,
            "EventResponse": "InProgress",
            "EventRisk": {
                "RiskDecision": "AccountTakeover",
                "RiskLevel": "Medium",
                "CompromisedCredentialsDetected": false
            },
            "ChallengeResponses": [
                {
                    "ChallengeName": "Password",
                    "ChallengeResponse": "Success"
                }
            ],
            "EventContextData": {
                "IpAddress": "192.0.2.1",
                "City": "Seattle",
                "Country": "United States"
            }
        }
    ],
    "NextToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222#2024-09-18T21:16:43.495Z"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザーイベント履歴の表示とエクスポート](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-adaptive-authentication.html#user-pool-settings-adaptive-authentication-event-user-history)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminListUserAuthEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-list-user-auth-events.html)」を参照してください。

### `admin-remove-user-from-group`
<a name="cognito-identity-provider_AdminRemoveUserFromGroup_cli_2_topic"></a>

次のコード例は、`admin-remove-user-from-group` を使用する方法を示しています。

**AWS CLI**  
**グループからユーザーを削除するには**  
この例では、SampleGroup から jane@example.com を削除しています。  
コマンド:  

```
aws cognito-idp admin-remove-user-from-group --user-pool-id us-west-2_aaaaaaaaa --username jane@example.com --group-name SampleGroup
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminRemoveUserFromGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-remove-user-from-group.html)」を参照してください。

### `admin-reset-user-password`
<a name="cognito-identity-provider_AdminResetUserPassword_cli_2_topic"></a>

次のコード例は、`admin-reset-user-password` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのパスワードをリセットするには**  
この例では、diego@example.com のパスワードをリセットしています。  
コマンド:  

```
aws cognito-idp admin-reset-user-password --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminResetUserPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-reset-user-password.html)」を参照してください。

### `admin-respond-to-auth-challenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_cli_2_topic"></a>

次のコード例は、`admin-respond-to-auth-challenge` を使用する方法を示しています。

**AWS CLI**  
**認証チャレンジに応答するには**  
認証チャレンジに応答する方法は、認証フロー、ユーザープールの設定、ユーザーの設定によって異なります。次の `admin-respond-to-auth-challenge` の例では、diego@example.com の TOTP MFA コードを提供し、サインインを完了する方法を示します。このユーザープールではデバイスの記憶がオンになっているため、認証結果として新しいデバイスキーも返されます。  

```
aws cognito-idp admin-respond-to-auth-challenge \
    --user-pool-id us-west-2_EXAMPLE \
    --client-id 1example23456789 \
    --challenge-name SOFTWARE_TOKEN_MFA \
    --challenge-responses USERNAME=diego@example.com,SOFTWARE_TOKEN_MFA_CODE=000000 \
    --session AYABeExample...
```
出力:  

```
{
    "ChallengeParameters": {},
    "AuthenticationResult": {
        "AccessToken": "eyJra456defEXAMPLE",
        "ExpiresIn": 3600,
        "TokenType": "Bearer",
        "RefreshToken": "eyJra123abcEXAMPLE",
        "IdToken": "eyJra789ghiEXAMPLE",
        "NewDeviceMetadata": {
            "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "DeviceGroupKey": "-ExAmPlE1"
        }
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[管理認証フロー](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#amazon-cognito-user-pools-admin-authentication-flow)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AdminRespondToAuthChallenge](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-respond-to-auth-challenge.html)」を参照してください。

### `admin-set-user-mfa-preference`
<a name="cognito-identity-provider_AdminSetUserMfaPreference_cli_2_topic"></a>

次のコード例は、`admin-set-user-mfa-preference` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの MFA を設定するには**  
この例では、ユーザー名 diego@example.com の SMS MFA 設定を行っています。  
コマンド:  

```
aws cognito-idp admin-set-user-mfa-preference --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com --sms-mfa-settings Enabled=false,PreferredMfa=false
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminSetUserMfaPreference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-set-user-mfa-preference.html)」を参照してください。

### `admin-set-user-password`
<a name="cognito-identity-provider_AdminSetUserPassword_cli_2_topic"></a>

次のコード例は、`admin-set-user-password` を使用する方法を示しています。

**AWS CLI**  
**管理者としてユーザーのパスワードを設定するには**  
次の `admin-set-user-password` の例では、diego@example.com のパスワードを永続的に設定します。  

```
aws cognito-idp admin-set-user-password \
    --user-pool-id us-west-2_EXAMPLE \
    --username diego@example.com \
    --password MyExamplePassword1! \
    --permanent
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[パスワード、パスワード復旧、パスワードポリシー](https://docs.aws.amazon.com/cognito/latest/developerguide/managing-users-passwords.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AdminSetUserPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-set-user-password.html)」を参照してください。

### `admin-set-user-settings`
<a name="cognito-identity-provider_AdminSetUserSettings_cli_2_topic"></a>

次のコード例は、`admin-set-user-settings` を使用する方法を示しています。

**AWS CLI**  
**ユーザー設定を行うには**  
この例では、ユーザー名 diego@example.com の MFA 配信設定を EMAIL に設定しています。  
コマンド:  

```
aws cognito-idp admin-set-user-settings --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com --mfa-options DeliveryMedium=EMAIL
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminSetUserSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-set-user-settings.html)」を参照してください。

### `admin-update-auth-event-feedback`
<a name="cognito-identity-provider_AdminUpdateAuthEventFeedback_cli_2_topic"></a>

次のコード例は、`admin-update-auth-event-feedback` を使用する方法を示しています。

**AWS CLI**  
**認証イベントにフィードバックを提供するには**  
この例では、event-id で識別される承認イベントのフィードバック値を Valid に設定します。  
コマンド:  

```
aws cognito-idp admin-update-auth-event-feedback --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com --event-id c2c2cf89-c0d3-482d-aba6-99d78a5b0bfe --feedback-value Valid
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminUpdateAuthEventFeedback](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-update-auth-event-feedback.html)」を参照してください。

### `admin-update-device-status`
<a name="cognito-identity-provider_AdminUpdateDeviceStatus_cli_2_topic"></a>

次のコード例は、`admin-update-device-status` を使用する方法を示しています。

**AWS CLI**  
**デバイスステータスを更新するには**  
この例では、device-key によって識別されるデバイスの記憶状態を not\$1remembered に設定しています。  
コマンド:  

```
aws cognito-idp admin-update-device-status --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com --device-key xxxx  --device-remembered-status not_remembered
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminUpdateDeviceStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-update-device-status.html)」を参照してください。

### `admin-update-user-attributes`
<a name="cognito-identity-provider_AdminUpdateUserAttributes_cli_2_topic"></a>

次のコード例は、`admin-update-user-attributes` を使用する方法を示しています。

**AWS CLI**  
**ユーザー属性を更新するには**  
この例では、ユーザー diego@example.com のカスタムユーザー属性 CustomAttr1 を更新しています。  
コマンド:  

```
aws cognito-idp admin-update-user-attributes --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com --user-attributes Name="custom:CustomAttr1",Value="Purple"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdminUpdateUserAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-update-user-attributes.html)」を参照してください。

### `admin-user-global-sign-out`
<a name="cognito-identity-provider_AdminUserGlobalSignOut_cli_2_topic"></a>

次のコード例は、`admin-user-global-sign-out` を使用する方法を示しています。

**AWS CLI**  
**管理者としてユーザーのサインアウトを許可するには**  
次の `admin-user-global-sign-out` の例では、ユーザー diego@example.com のサインアウトを許可します。  

```
aws cognito-idp admin-user-global-sign-out \
    --user-pool-id us-west-2_EXAMPLE \
    --username diego@example.com
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープールによる認証](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AdminUserGlobalSignOut](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/admin-user-global-sign-out.html)」を参照してください。

### `associate-software-token`
<a name="cognito-identity-provider_AssociateSoftwareToken_cli_2_topic"></a>

次のコード例は、`associate-software-token` を使用する方法を示しています。

**AWS CLI**  
**MFA 認証アプリケーション用のシークレットキーを生成するには**  
次の `associate-software-token` の例では、サインインしてアクセストークンを受け取ったユーザーの TOTP シークレットキーを生成します。生成されたシークレットキーは、認証アプリケーションに手動で入力することも、ユーザーがスキャン可能な QR コードとしてアプリケーションでレンダリングすることもできます。  

```
aws cognito-idp associate-software-token \
    --access-token eyJra456defEXAMPLE
```
出力:  

```
{
    "SecretCode": "QWERTYUIOP123456EXAMPLE"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[TOTP ソフトウェアトークン MFA](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa-totp.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AssociateSoftwareToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/associate-software-token.html)」を参照してください。

### `change-password`
<a name="cognito-identity-provider_ChangePassword_cli_2_topic"></a>

次のコード例は、`change-password` を使用する方法を示しています。

**AWS CLI**  
**パスワードを変更するには**  
この例では、パスワードを変更しています。  
コマンド:  

```
aws cognito-idp change-password --previous-password OldPassword --proposed-password NewPassword --access-token ACCESS_TOKEN
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ChangePassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/change-password.html)」を参照してください。

### `confirm-device`
<a name="cognito-identity-provider_ConfirmDevice_cli_2_topic"></a>

次のコード例は、`confirm-device` を使用する方法を示しています。

**AWS CLI**  
**ユーザーデバイスを確認するには**  
次の `confirm-device` の例では、現在のユーザー用に新しく記憶されたデバイスを追加します。  

```
aws cognito-idp confirm-device \
   --access-token eyJra456defEXAMPLE \
   --device-key us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
   --device-secret-verifier-config PasswordVerifier=TXlWZXJpZmllclN0cmluZw,Salt=TXlTUlBTYWx0
```
出力:  

```
{
     "UserConfirmationNecessary": false
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープール内のユーザーデバイスの使用](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ConfirmDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/confirm-device.html)」を参照してください。

### `confirm-forgot-password`
<a name="cognito-identity-provider_ConfirmForgotPassword_cli_2_topic"></a>

次のコード例は、`confirm-forgot-password` を使用する方法を示しています。

**AWS CLI**  
**忘れたパスワードを確認するには**  
この例では、ユーザー名 diego@example.com が忘れたパスワードを確認しています。  
コマンド:  

```
aws cognito-idp confirm-forgot-password --client-id 3n4b5urk1ft4fl3mg5e62d9ado --username=diego@example.com --password PASSWORD --confirmation-code CONF_CODE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmForgotPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/confirm-forgot-password.html)」を参照してください。

### `confirm-sign-up`
<a name="cognito-identity-provider_ConfirmSignUp_cli_2_topic"></a>

次のコード例は、`confirm-sign-up` を使用する方法を示しています。

**AWS CLI**  
**サインアップを確認するには**  
この例では、ユーザー名 diego@example.com のサインアップを確認します。  
コマンド:  

```
aws cognito-idp confirm-sign-up --client-id 3n4b5urk1ft4fl3mg5e62d9ado --username=diego@example.com --confirmation-code CONF_CODE
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ConfirmSignUp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/confirm-sign-up.html)」を参照してください。**

### `create-group`
<a name="cognito-identity-provider_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**グループを作成するには**  
この例では、説明付きのグループを作成しています。  
コマンド:  

```
aws cognito-idp create-group --user-pool-id us-west-2_aaaaaaaaa --group-name MyNewGroup --description "New group."
```
出力:  

```
{
  "Group": {
      "GroupName": "MyNewGroup",
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "Description": "New group.",
      "LastModifiedDate": 1548270073.795,
      "CreationDate": 1548270073.795
  }
}
```
**ロールと優先順位を持つグループを作成するには**  
この例では、説明付きのグループを作成しています。また、ロールと優先順位も含まれます。  
コマンド:  

```
aws cognito-idp create-group --user-pool-id us-west-2_aaaaaaaaa --group-name MyNewGroupWithRole --description "New group with a role." --role-arn arn:aws:iam::111111111111:role/MyNewGroupRole --precedence 2
```
出力:  

```
{
  "Group": {
      "GroupName": "MyNewGroupWithRole",
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "Description": "New group with a role.",
      "RoleArn": "arn:aws:iam::111111111111:role/MyNewGroupRole",
      "Precedence": 2,
      "LastModifiedDate": 1548270211.761,
      "CreationDate": 1548270211.761
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/create-group.html)」を参照してください。

### `create-identity-provider`
<a name="cognito-identity-provider_CreateIdentityProvider_cli_2_topic"></a>

次のコード例は、`create-identity-provider` を使用する方法を示しています。

**AWS CLI**  
**例 1: メタデータ URL を使用してユーザープール SAML ID プロバイダー (IdP) を作成するには**  
次の `create-identity-provider` の例では、パブリック URL からのメタデータ、属性マッピング、2 つの識別子を使用して、新しい SAML IdP を作成します。  

```
aws cognito-idp create-identity-provider \
    --user-pool-id us-west-2_EXAMPLE \
    --provider-name MySAML \
    --provider-type SAML \
    --provider-details IDPInit=true,IDPSignout=true,EncryptedResponses=true,MetadataURL=https://auth.example.com/sso/saml/metadata,RequestSigningAlgorithm=rsa-sha256 \
    --attribute-mapping email=emailaddress,phone_number=phone,custom:111=department \
    --idp-identifiers CorpSAML WestSAML
```
出力:  

```
{
    "IdentityProvider": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "ProviderName": "MySAML",
        "ProviderType": "SAML",
        "ProviderDetails": {
            "ActiveEncryptionCertificate": "MIICvTCCAaEXAMPLE",
            "EncryptedResponses": "true",
            "IDPInit": "true",
            "IDPSignout": "true",
            "MetadataURL": "https://auth.example.com/sso/saml/metadata",
            "RequestSigningAlgorithm": "rsa-sha256",
            "SLORedirectBindingURI": "https://auth.example.com/slo/saml",
            "SSORedirectBindingURI": "https://auth.example.com/sso/saml"
        },
        "AttributeMapping": {
            "custom:111": "department",
            "emailaddress": "email",
            "phone": "phone_number"
        },
        "IdpIdentifiers": [
            "CorpSAML",
            "WestSAML"
        ],
        "LastModifiedDate": 1726853833.977,
        "CreationDate": 1726853833.977
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[サードパーティー経由のユーザープールへのサインインの追加](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html)」を参照してください。  
**例 2: メタデータファイルを使用してユーザープール SAML ID プロバイダー (IdP) を作成するには**  
次の `create-identity-provider` の例では、ファイルからのメタデータ、属性マッピング、2 つの識別子を使用して、新しい SAML IdP を作成します。`--provider-details` パラメータのファイル構文はオペレーティングシステムによって異なる場合があります。このオペレーションでは JSON 入力ファイルを作成するのが最も簡単です。  

```
aws cognito-idp create-identity-provider \
    --cli-input-json file://.\SAML-identity-provider.json
```
`SAML-identity-provider.json` の内容:  

```
{
    "AttributeMapping": {
        "email" : "idp_email",
        "email_verified" : "idp_email_verified"
    },
    "IdpIdentifiers": [ "platform" ],
    "ProviderDetails": {
        "MetadataFile": "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\"http://www.example.com/sso\"><md:IDPSSODescriptor WantAuthnRequestsSigned=\"false\" protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\"><md:KeyDescriptor use=\"signing\"><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data><ds:X509Certificate>[IDP_CERTIFICATE_DATA]</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor><md:SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"https://www.example.com/slo/saml\"/><md:SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" Location=\"https://www.example.com/slo/saml\"/><md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat><md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat><md:SingleSignOnService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"https://www.example.com/sso/saml\"/><md:SingleSignOnService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" Location=\"https://www.example.com/sso/saml\"/></md:IDPSSODescriptor></md:EntityDescriptor>",
        "IDPSignout" : "true",
        "RequestSigningAlgorithm" : "rsa-sha256",
        "EncryptedResponses" : "true",
        "IDPInit" : "true"
    },
    "ProviderName": "MySAML2",
    "ProviderType": "SAML",
    "UserPoolId": "us-west-2_EXAMPLE"
}
```
出力:  

```
{
    "IdentityProvider": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "ProviderName": "MySAML2",
        "ProviderType": "SAML",
        "ProviderDetails": {
            "ActiveEncryptionCertificate": "[USER_POOL_ENCRYPTION_CERTIFICATE_DATA]",
            "EncryptedResponses": "true",
            "IDPInit": "true",
            "IDPSignout": "true",
            "MetadataFile": "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" entityID=\"http://www.example.com/sso\"><md:IDPSSODescriptor WantAuthnRequestsSigned=\"false\" protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\"><md:KeyDescriptor use=\"signing\"><ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ds:X509Data><ds:X509Certificate>[IDP_CERTIFICATE_DATA]</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor><md:SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"https://www.example.com/slo/saml\"/><md:SingleLogoutService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" Location=\"https://www.example.com/slo/saml\"/><md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified</md:NameIDFormat><md:NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</md:NameIDFormat><md:SingleSignOnService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" Location=\"https://www.example.com/sso/saml\"/><md:SingleSignOnService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" Location=\"https://www.example.com/sso/saml\"/></md:IDPSSODescriptor></md:EntityDescriptor>",
            "RequestSigningAlgorithm": "rsa-sha256",
            "SLORedirectBindingURI": "https://www.example.com/slo/saml",
            "SSORedirectBindingURI": "https://www.example.com/sso/saml"
        },
        "AttributeMapping": {
            "email": "idp_email",
            "email_verified": "idp_email_verified"
        },
        "IdpIdentifiers": [
            "platform"
        ],
        "LastModifiedDate": 1726855290.731,
        "CreationDate": 1726855290.731
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[サードパーティー経由のユーザープールへのサインインの追加](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateIdentityProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/create-identity-provider.html)」を参照してください。

### `create-resource-server`
<a name="cognito-identity-provider_CreateResourceServer_cli_2_topic"></a>

次のコード例は、`create-resource-server` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールのクライアントを作成するには**  
次の `create-resource-server` の例では、カスタムスコープを設定した新しいリソースサーバーを作成します。  

```
aws cognito-idp create-resource-server \
    --user-pool-id us-west-2_EXAMPLE \
    --identifier solar-system-data \
    --name "Solar system object tracker" \
    --scopes ScopeName=sunproximity.read,ScopeDescription="Distance in AU from Sol" ScopeName=asteroids.add,ScopeDescription="Enter a new asteroid"
```
出力:  

```
{
    "ResourceServer": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "Identifier": "solar-system-data",
        "Name": "Solar system object tracker",
        "Scopes": [
            {
                "ScopeName": "sunproximity.read",
                "ScopeDescription": "Distance in AU from Sol"
            },
            {
                "ScopeName": "asteroids.add",
                "ScopeDescription": "Enter a new asteroid"
            }
        ]
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[スコープ、M2M、リソースサーバーを使用した API](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateResourceServer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/create-resource-server.html)」を参照してください。

### `create-user-import-job`
<a name="cognito-identity-provider_CreateUserImportJob_cli_2_topic"></a>

次のコード例は、`create-user-import-job` を使用する方法を示しています。

**AWS CLI**  
**ユーザーインポートジョブを作成するには**  
この例では、MyImportJob という名前のユーザーインポートジョブを作成しています。  
ユーザーをインポートする方法の詳細については、「Importing Users into User Pools From a CSV File」を参照してください。  
コマンド:  

```
aws cognito-idp create-user-import-job --user-pool-id us-west-2_aaaaaaaaa --job-name MyImportJob --cloud-watch-logs-role-arn arn:aws:iam::111111111111:role/CognitoCloudWatchLogsRole
```
出力:  

```
{
  "UserImportJob": {
      "JobName": "MyImportJob",
      "JobId": "import-qQ0DCt2fRh",
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "PreSignedUrl": "PRE_SIGNED_URL",
      "CreationDate": 1548271795.471,
      "Status": "Created",
      "CloudWatchLogsRoleArn": "arn:aws:iam::111111111111:role/CognitoCloudWatchLogsRole",
      "ImportedUsers": 0,
      "SkippedUsers": 0,
      "FailedUsers": 0
  }
}
```
署名付き URL を使用して、.csv ファイルを curl でアップロードします。  
コマンド:  

```
curl -v -T "PATH_TO_CSV_FILE" -H "x-amz-server-side-encryption:aws:kms" "PRE_SIGNED_URL"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUserImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/create-user-import-job.html)」を参照してください。

### `create-user-pool-client`
<a name="cognito-identity-provider_CreateUserPoolClient_cli_2_topic"></a>

次のコード例は、`create-user-pool-client` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールのクライアントを作成するには**  
次の `create-user-pool-client` の例では、クライアントシークレット、明示的な読み取りおよび書き込み属性、ユーザー名とパスワードおよび SRP フローでのサインイン、3 つの IdP でのサインイン、OAuth スコープのサブセットへのアクセス、PinPoint 分析、拡張認証セッション有効期間を設定した新しいユーザープールクライアントを作成します。  

```
aws cognito-idp create-user-pool-client \
    --user-pool-id us-west-2_EXAMPLE \
    --client-name MyTestClient \
    --generate-secret \
    --refresh-token-validity 10 \
    --access-token-validity 60 \
    --id-token-validity 60 \
    --token-validity-units AccessToken=minutes,IdToken=minutes,RefreshToken=days \
    --read-attributes email phone_number email_verified phone_number_verified \
    --write-attributes email phone_number \
    --explicit-auth-flows ALLOW_USER_PASSWORD_AUTH ALLOW_USER_SRP_AUTH ALLOW_REFRESH_TOKEN_AUTH \
    --supported-identity-providers Google Facebook MyOIDC \
    --callback-urls https://www.amazon.com https://example.com http://localhost:8001 myapp://example \
    --allowed-o-auth-flows code implicit \
    --allowed-o-auth-scopes openid profile aws.cognito.signin.user.admin solar-system-data/asteroids.add \
    --allowed-o-auth-flows-user-pool-client \
    --analytics-configuration ApplicationArn=arn:aws:mobiletargeting:us-west-2:767671399759:apps/thisisanexamplepinpointapplicationid,UserDataShared=TRUE \
    --prevent-user-existence-errors ENABLED \
    --enable-token-revocation \
    --enable-propagate-additional-user-context-data \
    --auth-session-validity 4
```
出力:  

```
{
    "UserPoolClient": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "ClientName": "MyTestClient",
        "ClientId": "123abc456defEXAMPLE",
        "ClientSecret": "this1234is5678my91011example1213client1415secret",
        "LastModifiedDate": 1726788459.464,
        "CreationDate": 1726788459.464,
        "RefreshTokenValidity": 10,
        "AccessTokenValidity": 60,
        "IdTokenValidity": 60,
        "TokenValidityUnits": {
            "AccessToken": "minutes",
            "IdToken": "minutes",
            "RefreshToken": "days"
        },
        "ReadAttributes": [
            "email_verified",
            "phone_number_verified",
            "phone_number",
            "email"
        ],
        "WriteAttributes": [
            "phone_number",
            "email"
        ],
        "ExplicitAuthFlows": [
            "ALLOW_USER_PASSWORD_AUTH",
            "ALLOW_USER_SRP_AUTH",
            "ALLOW_REFRESH_TOKEN_AUTH"
        ],
        "SupportedIdentityProviders": [
            "Google",
            "MyOIDC",
            "Facebook"
        ],
        "CallbackURLs": [
            "https://example.com",
            "https://www.amazon.com",
            "myapp://example",
            "http://localhost:8001"
        ],
        "AllowedOAuthFlows": [
            "implicit",
            "code"
        ],
        "AllowedOAuthScopes": [
            "aws.cognito.signin.user.admin",
            "openid",
            "profile",
            "solar-system-data/asteroids.add"
        ],
        "AllowedOAuthFlowsUserPoolClient": true,
        "AnalyticsConfiguration": {
            "ApplicationArn": "arn:aws:mobiletargeting:us-west-2:123456789012:apps/thisisanexamplepinpointapplicationid",
            "RoleArn": "arn:aws:iam::123456789012:role/aws-service-role/cognito-idp.amazonaws.com/AWSServiceRoleForAmazonCognitoIdp",
            "UserDataShared": true
        },
        "PreventUserExistenceErrors": "ENABLED",
        "EnableTokenRevocation": true,
        "EnablePropagateAdditionalUserContextData": true,
        "AuthSessionValidity": 4
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[アプリケーションクライアントによるアプリケーション固有の設定](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUserPoolClient](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/create-user-pool-client.html)」を参照してください。

### `create-user-pool-domain`
<a name="cognito-identity-provider_CreateUserPoolDomain_cli_2_topic"></a>

次のコード例は、`create-user-pool-domain` を使用する方法を示しています。

**AWS CLI**  
**例 1: ユーザープールドメインを作成するには**  
次の `create-user-pool-domain` の例では、新しいカスタムドメインを作成します。  

```
aws cognito-idp create-user-pool-domain \
    --user-pool-id us-west-2_EXAMPLE \
    --domain auth.example.com \
    --custom-domain-config CertificateArn=arn:aws:acm:us-east-1:123456789012:certificate/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222
```
出力:  

```
{
    "CloudFrontDomain": "example1domain.cloudfront.net"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープールドメインの設定](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain.html)」を参照してください。  
**例 2: ユーザープールドメインを作成するには**  
次の `create-user-pool-domain` の例では、サービス所有プレフィックスを付加した新しいドメインを作成します。  

```
aws cognito-idp create-user-pool-domain \
    --user-pool-id us-west-2_EXAMPLE2 \
    --domain mydomainprefix
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープールドメインの設定](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUserPoolDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/create-user-pool-domain.html)」を参照してください。

### `create-user-pool`
<a name="cognito-identity-provider_CreateUserPool_cli_2_topic"></a>

次のコード例は、`create-user-pool` を使用する方法を示しています。

**AWS CLI**  
**最小構成のユーザープールを作成するには**  
この例では、デフォルト値を使用して MyUserPool という名前のユーザープールを作成します。必要な属性やアプリケーションクライアントはありません。MFA およびアドバンストセキュリティは無効化されています。  
コマンド:  

```
aws cognito-idp create-user-pool --pool-name MyUserPool
```
出力:  

```
{
  "UserPool": {
      "SchemaAttributes": [
          {
              "Name": "sub",
              "StringAttributeConstraints": {
                  "MinLength": "1",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": true,
              "AttributeDataType": "String",
              "Mutable": false
          },
          {
              "Name": "name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "given_name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "family_name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "middle_name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "nickname",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "preferred_username",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "profile",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "picture",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "website",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "email",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "AttributeDataType": "Boolean",
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "Name": "email_verified",
              "Mutable": true
          },
          {
              "Name": "gender",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "birthdate",
              "StringAttributeConstraints": {
                  "MinLength": "10",
                  "MaxLength": "10"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "zoneinfo",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "locale",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "phone_number",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "AttributeDataType": "Boolean",
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "Name": "phone_number_verified",
              "Mutable": true
          },
          {
              "Name": "address",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "updated_at",
              "NumberAttributeConstraints": {
                  "MinValue": "0"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "Number",
              "Mutable": true
          }
      ],
      "MfaConfiguration": "OFF",
      "Name": "MyUserPool",
      "LastModifiedDate": 1547833345.777,
      "AdminCreateUserConfig": {
          "UnusedAccountValidityDays": 7,
          "AllowAdminCreateUserOnly": false
      },
      "EmailConfiguration": {},
      "Policies": {
          "PasswordPolicy": {
              "RequireLowercase": true,
              "RequireSymbols": true,
              "RequireNumbers": true,
              "MinimumLength": 8,
              "RequireUppercase": true
          }
      },
      "CreationDate": 1547833345.777,
      "EstimatedNumberOfUsers": 0,
      "Id": "us-west-2_aaaaaaaaa",
      "LambdaConfig": {}
  }
}
```
**2 つの必須属性でユーザープールを作成するには**  
この例では、ユーザープール MyUserPool を作成します。プールは、E メールをユーザー名属性として受け入れるように設定されています。また、Amazon Simple Email Service を使用して、E メールの送信元アドレスを検証済みのアドレスに設定します。  
コマンド:  

```
aws cognito-idp create-user-pool --pool-name MyUserPool --username-attributes "email" --email-configuration=SourceArn="arn:aws:ses:us-east-1:111111111111:identity/jane@example.com",ReplyToEmailAddress="jane@example.com"
```
出力:  

```
{
  "UserPool": {
      "SchemaAttributes": [
          {
              "Name": "sub",
              "StringAttributeConstraints": {
                  "MinLength": "1",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": true,
              "AttributeDataType": "String",
              "Mutable": false
          },
          {
              "Name": "name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "given_name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "family_name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "middle_name",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "nickname",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "preferred_username",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "profile",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "picture",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "website",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "email",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "AttributeDataType": "Boolean",
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "Name": "email_verified",
              "Mutable": true
          },
          {
              "Name": "gender",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "birthdate",
              "StringAttributeConstraints": {
                  "MinLength": "10",
                  "MaxLength": "10"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "zoneinfo",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "locale",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "phone_number",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "AttributeDataType": "Boolean",
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "Name": "phone_number_verified",
              "Mutable": true
          },
          {
              "Name": "address",
              "StringAttributeConstraints": {
                  "MinLength": "0",
                  "MaxLength": "2048"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "String",
              "Mutable": true
          },
          {
              "Name": "updated_at",
              "NumberAttributeConstraints": {
                  "MinValue": "0"
              },
              "DeveloperOnlyAttribute": false,
              "Required": false,
              "AttributeDataType": "Number",
              "Mutable": true
          }
      ],
      "MfaConfiguration": "OFF",
      "Name": "MyUserPool",
      "LastModifiedDate": 1547837788.189,
      "AdminCreateUserConfig": {
          "UnusedAccountValidityDays": 7,
          "AllowAdminCreateUserOnly": false
      },
      "EmailConfiguration": {
          "ReplyToEmailAddress": "jane@example.com",
          "SourceArn": "arn:aws:ses:us-east-1:111111111111:identity/jane@example.com"
      },
      "Policies": {
          "PasswordPolicy": {
              "RequireLowercase": true,
              "RequireSymbols": true,
              "RequireNumbers": true,
              "MinimumLength": 8,
              "RequireUppercase": true
          }
      },
      "UsernameAttributes": [
          "email"
      ],
      "CreationDate": 1547837788.189,
      "EstimatedNumberOfUsers": 0,
      "Id": "us-west-2_aaaaaaaaa",
      "LambdaConfig": {}
  }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateUserPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/create-user-pool.html)」を参照してください。**

### `delete-group`
<a name="cognito-identity-provider_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**グループを削除するには**  
この例では、グループを削除しています。  
コマンド:  

```
aws cognito-idp delete-group --user-pool-id us-west-2_aaaaaaaaa  --group-name MyGroupName
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-group.html)」を参照してください。

### `delete-identity-provider`
<a name="cognito-identity-provider_DeleteIdentityProvider_cli_2_topic"></a>

次のコード例は、`delete-identity-provider` を使用する方法を示しています。

**AWS CLI**  
**ID プロバイダーを削除するには**  
この例では、ID プロバイダーを削除しています。  
コマンド:  

```
aws cognito-idp delete-identity-provider --user-pool-id us-west-2_aaaaaaaaa --provider-name Facebook
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIdentityProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-identity-provider.html)」を参照してください。

### `delete-resource-server`
<a name="cognito-identity-provider_DeleteResourceServer_cli_2_topic"></a>

次のコード例は、`delete-resource-server` を使用する方法を示しています。

**AWS CLI**  
**リソースサーバーを削除するには**  
この例では、weather.example.com という名前のリソースサーバーを削除しています。  
コマンド:  

```
aws cognito-idp delete-resource-server --user-pool-id us-west-2_aaaaaaaaa --identifier weather.example.com
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourceServer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-resource-server.html)」を参照してください。

### `delete-user-attributes`
<a name="cognito-identity-provider_DeleteUserAttributes_cli_2_topic"></a>

次のコード例は、`delete-user-attributes` を使用する方法を示しています。

**AWS CLI**  
**ユーザー属性を削除するには**  
次の `delete-user-attributes` の例では、現在サインインしているユーザーからカスタム属性「custom:attribute」を削除します。  

```
aws cognito-idp delete-user-attributes \
    --access-token ACCESS_TOKEN \
    --user-attribute-names "custom:department"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザー属性の使用](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUserAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-user-attributes.html)」を参照してください。

### `delete-user-pool-client`
<a name="cognito-identity-provider_DeleteUserPoolClient_cli_2_topic"></a>

次のコード例は、`delete-user-pool-client` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールクライアントを削除するには**  
この例では、ユーザープールクライアントを削除しています。  
コマンド:  

```
aws cognito-idp delete-user-pool-client --user-pool-id us-west-2_aaaaaaaaa --client-id 38fjsnc484p94kpqsnet7mpld0
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUserPoolClient](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-user-pool-client.html)」を参照してください。

### `delete-user-pool-domain`
<a name="cognito-identity-provider_DeleteUserPoolDomain_cli_2_topic"></a>

次のコード例は、`delete-user-pool-domain` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールのドメインを削除するには**  
次の `delete-user-pool-domain` の例では、`my-domain` という名前のユーザープールのドメインを削除しています。  

```
aws cognito-idp delete-user-pool-domain \
    --user-pool-id us-west-2_aaaaaaaaa \
    --domain my-domain
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUserPoolDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-user-pool-domain.html)」を参照してください。

### `delete-user-pool`
<a name="cognito-identity-provider_DeleteUserPool_cli_2_topic"></a>

次のコード例は、`delete-user-pool` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールを削除するには**  
この例では、ユーザープール ID、us-west-2\$1aaaaaaaaa を使用してユーザープールを削除しています。  
コマンド:  

```
aws cognito-idp delete-user-pool --user-pool-id us-west-2_aaaaaaaaa
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUserPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-user-pool.html)」を参照してください。

### `delete-user`
<a name="cognito-identity-provider_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
この例では、ユーザーを削除します。  
コマンド:  

```
aws cognito-idp delete-user --access-token ACCESS_TOKEN
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/delete-user.html)」を参照してください。

### `describe-identity-provider`
<a name="cognito-identity-provider_DescribeIdentityProvider_cli_2_topic"></a>

次のコード例は、`describe-identity-provider` を使用する方法を示しています。

**AWS CLI**  
**ID プロバイダーを記述するには**  
この例では、Facebook という名前の ID プロバイダーを記述します。  
コマンド:  

```
aws cognito-idp describe-identity-provider --user-pool-id us-west-2_aaaaaaaaa --provider-name Facebook
```
出力:  

```
{
  "IdentityProvider": {
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "ProviderName": "Facebook",
      "ProviderType": "Facebook",
      "ProviderDetails": {
          "attributes_url": "https://graph.facebook.com/me?fields=",
          "attributes_url_add_attributes": "true",
          "authorize_scopes": myscope",
          "authorize_url": "https://www.facebook.com/v2.9/dialog/oauth",
          "client_id": "11111",
          "client_secret": "11111",
          "token_request_method": "GET",
          "token_url": "https://graph.facebook.com/v2.9/oauth/access_token"
      },
      "AttributeMapping": {
          "username": "id"
      },
      "IdpIdentifiers": [],
      "LastModifiedDate": 1548105901.736,
      "CreationDate": 1548105901.736
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIdentityProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/describe-identity-provider.html)」を参照してください。

### `describe-resource-server`
<a name="cognito-identity-provider_DescribeResourceServer_cli_2_topic"></a>

次のコード例は、`describe-resource-server` を使用する方法を示しています。

**AWS CLI**  
**リソースサーバーを記述するには**  
この例では、リソースサーバー weather.example.com を記述します。  
コマンド:  

```
aws cognito-idp describe-resource-server --user-pool-id us-west-2_aaaaaaaaa --identifier weather.example.com
```
出力:  

```
{
  "ResourceServer": {
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "Identifier": "weather.example.com",
      "Name": "Weather",
      "Scopes": [
          {
              "ScopeName": "weather.update",
              "ScopeDescription": "Update weather forecast"
          },
          {
              "ScopeName": "weather.read",
              "ScopeDescription": "Read weather forecasts"
          },
          {
              "ScopeName": "weather.delete",
              "ScopeDescription": "Delete a weather forecast"
          }
      ]
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeResourceServer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/describe-resource-server.html)」を参照してください。

### `describe-risk-configuration`
<a name="cognito-identity-provider_DescribeRiskConfiguration_cli_2_topic"></a>

次のコード例は、`describe-risk-configuration` を使用する方法を示しています。

**AWS CLI**  
**リスク設定を記述するには**  
この例では、プール us-west-2\$1aaaaaaaa に関連するリスク設定を記述します。  
コマンド:  

```
aws cognito-idp describe-risk-configuration --user-pool-id us-west-2_aaaaaaaaa
```
出力:  

```
{
  "RiskConfiguration": {
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "CompromisedCredentialsRiskConfiguration": {
          "EventFilter": [
              "SIGN_IN",
              "SIGN_UP",
              "PASSWORD_CHANGE"
          ],
          "Actions": {
              "EventAction": "BLOCK"
          }
      },
      "AccountTakeoverRiskConfiguration": {
          "NotifyConfiguration": {
              "From": "diego@example.com",
              "ReplyTo": "diego@example.com",
              "SourceArn": "arn:aws:ses:us-east-1:111111111111:identity/diego@example.com",
              "BlockEmail": {
                  "Subject": "Blocked sign-in attempt",
                  "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We blocked an unrecognized sign-in to your account with this information:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                  "TextBody": "We blocked an unrecognized sign-in to your account with this information:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
              },
              "NoActionEmail": {
                  "Subject": "New sign-in attempt",
                  "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We observed an unrecognized sign-in to your account with this information:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                  "TextBody": "We observed an unrecognized sign-in to your account with this information:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
              },
              "MfaEmail": {
                  "Subject": "New sign-in attempt",
                  "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We required you to use multi-factor authentication for the following sign-in attempt:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                  "TextBody": "We required you to use multi-factor authentication for the following sign-in attempt:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
              }
          },
          "Actions": {
              "LowAction": {
                  "Notify": true,
                  "EventAction": "NO_ACTION"
              },
              "MediumAction": {
                  "Notify": true,
                  "EventAction": "MFA_IF_CONFIGURED"
              },
              "HighAction": {
                  "Notify": true,
                  "EventAction": "MFA_IF_CONFIGURED"
              }
          }
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRiskConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/describe-risk-configuration.html)」を参照してください。

### `describe-user-import-job`
<a name="cognito-identity-provider_DescribeUserImportJob_cli_2_topic"></a>

次のコード例は、`describe-user-import-job` を使用する方法を示しています。

**AWS CLI**  
**ユーザーインポートジョブを記述するには**  
この例では、ユーザー入力ジョブを記述します。  
ユーザーをインポートする方法の詳細については、「Importing Users into User Pools From a CSV File」を参照してください。  
コマンド:  

```
aws cognito-idp describe-user-import-job --user-pool-id us-west-2_aaaaaaaaa --job-id import-TZqNQvDRnW
```
出力:  

```
{
  "UserImportJob": {
      "JobName": "import-Test1",
      "JobId": "import-TZqNQvDRnW",
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "PreSignedUrl": "PRE_SIGNED URL",
      "CreationDate": 1548271708.512,
      "Status": "Created",
      "CloudWatchLogsRoleArn": "arn:aws:iam::111111111111:role/CognitoCloudWatchLogsRole",
      "ImportedUsers": 0,
      "SkippedUsers": 0,
      "FailedUsers": 0
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUserImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/describe-user-import-job.html)」を参照してください。

### `describe-user-pool-client`
<a name="cognito-identity-provider_DescribeUserPoolClient_cli_2_topic"></a>

次のコード例は、`describe-user-pool-client` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールクライアントを記述するには**  
この例では、ユーザープールクライアントを記述します。  
コマンド:  

```
aws cognito-idp describe-user-pool-client --user-pool-id us-west-2_aaaaaaaaa --client-id 38fjsnc484p94kpqsnet7mpld0
```
出力:  

```
{
  "UserPoolClient": {
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "ClientName": "MyApp",
      "ClientId": "38fjsnc484p94kpqsnet7mpld0",
      "ClientSecret": "CLIENT_SECRET",
      "LastModifiedDate": 1548108676.163,
      "CreationDate": 1548108676.163,
      "RefreshTokenValidity": 30,
      "ReadAttributes": [
          "address",
          "birthdate",
          "custom:CustomAttr1",
          "custom:CustomAttr2",
          "email",
          "email_verified",
          "family_name",
          "gender",
          "given_name",
          "locale",
          "middle_name",
          "name",
          "nickname",
          "phone_number",
          "phone_number_verified",
          "picture",
          "preferred_username",
          "profile",
          "updated_at",
          "website",
          "zoneinfo"
      ],
      "WriteAttributes": [
          "address",
          "birthdate",
          "custom:CustomAttr1",
          "custom:CustomAttr2",
          "email",
          "family_name",
          "gender",
          "given_name",
          "locale",
          "middle_name",
          "name",
          "nickname",
          "phone_number",
          "picture",
          "preferred_username",
          "profile",
          "updated_at",
          "website",
          "zoneinfo"
      ],
      "ExplicitAuthFlows": [
          "ADMIN_NO_SRP_AUTH",
          "USER_PASSWORD_AUTH"
      ],
      "AllowedOAuthFlowsUserPoolClient": false
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUserPoolClient](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/describe-user-pool-client.html)」を参照してください。

### `describe-user-pool-domain`
<a name="cognito-identity-provider_DescribeUserPoolDomain_cli_2_topic"></a>

次のコード例は、`describe-user-pool-domain` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールクライアントを記述するには**  
この例では、my-domain という名前のユーザープールドメインを記述します。  
コマンド:  

```
aws cognito-idp describe-user-pool-domain --domain my-domain
```
出力:  

```
{
  "DomainDescription": {
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "AWSAccountId": "111111111111",
      "Domain": "my-domain",
      "S3Bucket": "aws-cognito-prod-pdx-assets",
      "CloudFrontDistribution": "aaaaaaaaaaaaa.cloudfront.net",
      "Version": "20190128175402",
      "Status": "ACTIVE",
      "CustomDomainConfig": {}
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUserPoolDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/describe-user-pool-domain.html)」を参照してください。

### `describe-user-pool`
<a name="cognito-identity-provider_DescribeUserPool_cli_2_topic"></a>

次のコード例は、`describe-user-pool` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールを記述するには**  
次の例では、ユーザープール ID が us-west-2\$1EXAMPLE のユーザープールについて説明します。  

```
aws cognito-idp describe-user-pool \
    --user-pool-id us-west-2_EXAMPLE
```
出力:  

```
{
    "UserPool": {
        "Id": "us-west-2_EXAMPLE",
        "Name": "MyUserPool",
        "Policies": {
            "PasswordPolicy": {
                "MinimumLength": 8,
                "RequireUppercase": true,
                "RequireLowercase": true,
                "RequireNumbers": true,
                "RequireSymbols": true,
                "TemporaryPasswordValidityDays": 1
            }
        },
        "DeletionProtection": "ACTIVE",
        "LambdaConfig": {
            "PreSignUp": "arn:aws:lambda:us-west-2:123456789012:function:MyPreSignUpFunction",
            "CustomMessage": "arn:aws:lambda:us-west-2:123456789012:function:MyCustomMessageFunction",
            "PostConfirmation": "arn:aws:lambda:us-west-2:123456789012:function:MyPostConfirmationFunction",
            "PreAuthentication": "arn:aws:lambda:us-west-2:123456789012:function:MyPreAuthenticationFunction",
            "PostAuthentication": "arn:aws:lambda:us-west-2:123456789012:function:MyPostAuthenticationFunction",
            "DefineAuthChallenge": "arn:aws:lambda:us-west-2:123456789012:function:MyDefineAuthChallengeFunction",
            "CreateAuthChallenge": "arn:aws:lambda:us-west-2:123456789012:function:MyCreateAuthChallengeFunction",
            "VerifyAuthChallengeResponse": "arn:aws:lambda:us-west-2:123456789012:function:MyVerifyAuthChallengeFunction",
            "PreTokenGeneration": "arn:aws:lambda:us-west-2:123456789012:function:MyPreTokenGenerationFunction",
            "UserMigration": "arn:aws:lambda:us-west-2:123456789012:function:MyMigrateUserFunction",
            "PreTokenGenerationConfig": {
                "LambdaVersion": "V2_0",
                "LambdaArn": "arn:aws:lambda:us-west-2:123456789012:function:MyPreTokenGenerationFunction"
            },
            "CustomSMSSender": {
                "LambdaVersion": "V1_0",
                "LambdaArn": "arn:aws:lambda:us-west-2:123456789012:function:MyCustomSMSSenderFunction"
            },
            "CustomEmailSender": {
                "LambdaVersion": "V1_0",
                "LambdaArn": "arn:aws:lambda:us-west-2:123456789012:function:MyCustomEmailSenderFunction"
            },
            "KMSKeyID": "arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
        },
        "LastModifiedDate": 1726784814.598,
        "CreationDate": 1602103465.273,
        "SchemaAttributes": [
            {
                "Name": "sub",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": false,
                "Required": true,
                "StringAttributeConstraints": {
                    "MinLength": "1",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "given_name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "family_name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "middle_name",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "nickname",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "preferred_username",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "profile",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "picture",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "website",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "email",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": true,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "email_verified",
                "AttributeDataType": "Boolean",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false
            },
            {
                "Name": "gender",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "birthdate",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "10",
                    "MaxLength": "10"
                }
            },
            {
                "Name": "zoneinfo",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "locale",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "phone_number",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "phone_number_verified",
                "AttributeDataType": "Boolean",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false
            },
            {
                "Name": "address",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "0",
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "updated_at",
                "AttributeDataType": "Number",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "NumberAttributeConstraints": {
                    "MinValue": "0"
                }
            },
            {
                "Name": "identities",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {}
            },
            {
                "Name": "custom:111",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "1",
                    "MaxLength": "256"
                }
            },
            {
                "Name": "dev:custom:222",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": true,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MinLength": "1",
                    "MaxLength": "421"
                }
            },
            {
                "Name": "custom:accesstoken",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MaxLength": "2048"
                }
            },
            {
                "Name": "custom:idtoken",
                "AttributeDataType": "String",
                "DeveloperOnlyAttribute": false,
                "Mutable": true,
                "Required": false,
                "StringAttributeConstraints": {
                    "MaxLength": "2048"
                }
            }
        ],
        "AutoVerifiedAttributes": [
            "email"
        ],
        "SmsVerificationMessage": "Your verification code is {####}. ",
        "EmailVerificationMessage": "Your verification code is {####}. ",
        "EmailVerificationSubject": "Your verification code",
        "VerificationMessageTemplate": {
            "SmsMessage": "Your verification code is {####}. ",
            "EmailMessage": "Your verification code is {####}. ",
            "EmailSubject": "Your verification code",
            "EmailMessageByLink": "Please click the link below to verify your email address. <b>{##Verify Your Email##}</b>\n this is from us-west-2_ywDJHlIfU",
            "EmailSubjectByLink": "Your verification link",
            "DefaultEmailOption": "CONFIRM_WITH_LINK"
        },
        "SmsAuthenticationMessage": "Your verification code is {####}. ",
        "UserAttributeUpdateSettings": {
            "AttributesRequireVerificationBeforeUpdate": []
        },
        "MfaConfiguration": "OPTIONAL",
        "DeviceConfiguration": {
            "ChallengeRequiredOnNewDevice": true,
            "DeviceOnlyRememberedOnUserPrompt": false
        },
        "EstimatedNumberOfUsers": 166,
        "EmailConfiguration": {
            "SourceArn": "arn:aws:ses:us-west-2:123456789012:identity/admin@example.com",
            "EmailSendingAccount": "DEVELOPER"
        },
        "SmsConfiguration": {
            "SnsCallerArn": "arn:aws:iam::123456789012:role/service-role/userpool-SMS-Role",
            "ExternalId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "SnsRegion": "us-west-2"
        },
        "UserPoolTags": {},
        "Domain": "myCustomDomain",
        "CustomDomain": "auth.example.com",
        "AdminCreateUserConfig": {
            "AllowAdminCreateUserOnly": false,
            "UnusedAccountValidityDays": 1,
            "InviteMessageTemplate": {
                "SMSMessage": "Your username is {username} and temporary password is {####}. ",
                "EmailMessage": "Your username is {username} and temporary password is {####}. ",
                "EmailSubject": "Your temporary password"
            }
        },
        "UserPoolAddOns": {
            "AdvancedSecurityMode": "ENFORCED",
            "AdvancedSecurityAdditionalFlows": {}
        },
        "Arn": "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_EXAMPLE",
        "AccountRecoverySetting": {
            "RecoveryMechanisms": [
                {
                    "Priority": 1,
                    "Name": "verified_email"
                }
            ]
        }
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Amazon Cognito user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUserPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/describe-user-pool.html)」を参照してください。

### `forget-device`
<a name="cognito-identity-provider_ForgetDevice_cli_2_topic"></a>

次のコード例は、`forget-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスの「記憶済み」状態を解除するには**  
この例では、デバイスの「記憶済み」状態を解除します。  
コマンド:  

```
aws cognito-idp forget-device --device-key us-west-2_abcd_1234-5678
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ForgetDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/forget-device.html)」を参照してください。

### `forgot-password`
<a name="cognito-identity-provider_ForgotPassword_cli_2_topic"></a>

次のコード例は、`forgot-password` を使用する方法を示しています。

**AWS CLI**  
**強制的にパスワードを変更するには**  
次の `forgot-password` の例では、パスワードを変更するようにメッセージを jane@example.com に送信しています。  

```
aws cognito-idp forgot-password --client-id 38fjsnc484p94kpqsnet7mpld0 --username jane@example.com
```
出力:  

```
{
    "CodeDeliveryDetails": {
        "Destination": "j***@e***.com",
        "DeliveryMedium": "EMAIL",
        "AttributeName": "email"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ForgotPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/forgot-password.html)」を参照してください。

### `get-csv-header`
<a name="cognito-identity-provider_GetCsvHeader_cli_2_topic"></a>

次のコード例は、`get-csv-header` を使用する方法を示しています。

**AWS CLI**  
**csv ヘッダーを作成するには**  
この例では、csv ヘッダーを作成しています。  
ユーザーをインポートする方法の詳細については、「Importing Users into User Pools From a CSV File」を参照してください。  
コマンド:  

```
aws cognito-idp get-csv-header --user-pool-id us-west-2_aaaaaaaaa
```
出力:  

```
{
  "UserPoolId": "us-west-2_aaaaaaaaa",
  "CSVHeader": [
      "name",
      "given_name",
      "family_name",
      "middle_name",
      "nickname",
      "preferred_username",
      "profile",
      "picture",
      "website",
      "email",
      "email_verified",
      "gender",
      "birthdate",
      "zoneinfo",
      "locale",
      "phone_number",
      "phone_number_verified",
      "address",
      "updated_at",
      "cognito:mfa_enabled",
      "cognito:username"
  ]
}
```
... Importing Users into User Pools From a CSV File: https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCsvHeader](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-csv-header.html)」を参照してください。

### `get-device`
<a name="cognito-identity-provider_GetDevice_cli_2_topic"></a>

次のコード例は、`get-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスを取得するには**  
次の `get-device` の例では、現在サインインしているユーザーの 1 つのデバイスを表示します。  

```
aws cognito-idp get-device \
    --access-token eyJra456defEXAMPLE \
    --device-key us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "Device": {
        "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "DeviceAttributes": [
            {
                "Name": "device_status",
                "Value": "valid"
            },
            {
                "Name": "device_name",
                "Value": "MyDevice"
            },
            {
                "Name": "dev:device_arn",
                "Value": "arn:aws:cognito-idp:us-west-2:123456789012:owner/diego.us-west-2_EXAMPLE/device/us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
            },
            {
                "Name": "dev:device_owner",
                "Value": "diego.us-west-2_EXAMPLE"
            },
            {
                "Name": "last_ip_used",
                "Value": "192.0.2.1"
            },
            {
                "Name": "dev:device_remembered_status",
                "Value": "remembered"
            },
            {
                "Name": "dev:device_sdk",
                "Value": "aws-sdk"
            }
        ],
        "DeviceCreateDate": 1715100742.022,
        "DeviceLastModifiedDate": 1723233651.167,
        "DeviceLastAuthenticatedDate": 1715100742.0
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープール内のユーザーデバイスの使用](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-device.html)」を参照してください。

### `get-group`
<a name="cognito-identity-provider_GetGroup_cli_2_topic"></a>

次のコード例は、`get-group` を使用する方法を示しています。

**AWS CLI**  
**グループに関する情報を取得するには**  
次の `get-group` の例では、`MyGroup` という名前のユーザーグループのプロパティを一覧表示します。このグループには、優先順位とそれに関連付けられた IAM ロールがあります。  

```
aws cognito-idp get-group \
    --user-pool-id us-west-2_EXAMPLE \
    --group-name MyGroup
```
出力:  

```
{
    "Group": {
        "GroupName": "MyGroup",
        "UserPoolId": "us-west-2_EXAMPLE",
        "RoleArn": "arn:aws:iam::123456789012:role/example-cognito-role",
        "Precedence": 7,
        "LastModifiedDate": 1697211218.305,
        "CreationDate": 1611685503.954
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープールへのグループの追加](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-group.html)」を参照してください。

### `get-identity-provider-by-identifier`
<a name="cognito-identity-provider_GetIdentityProviderByIdentifier_cli_2_topic"></a>

次のコード例は、`get-identity-provider-by-identifier` を使用する方法を示しています。

**AWS CLI**  
**IdP 識別子から ID プロバイダーの設定を取得するには**  
次の `get-identity-provider-by-identifier` の例では、識別子 `mysso` を持つ ID プロバイダーの設定が返されます。  

```
aws cognito-idp get-identity-provider-by-identifier \
    --user-pool-id us-west-2_EXAMPLE \
    --idp-identifier mysso
```
出力:  

```
{
    "IdentityProvider": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "ProviderName": "MYSAML",
        "ProviderType": "SAML",
        "ProviderDetails": {
            "ActiveEncryptionCertificate": "[Certificate contents]",
            "IDPSignout": "false",
            "MetadataURL": "https://auth.example.com/saml/metadata/",
            "SLORedirectBindingURI": "https://auth.example.com/saml/logout/",
            "SSORedirectBindingURI": "https://auth.example.com/saml/assertion/"
        },
        "AttributeMapping": {
            "email": "email"
        },
        "IdpIdentifiers": [
            "mysso",
            "mysamlsso"
        ],
        "LastModifiedDate": 1705616729.188,
        "CreationDate": 1643734622.919
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Third-party IdP sign-in](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIdentityProviderByIdentifier](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-identity-provider-by-identifier.html)」を参照してください。

### `get-log-delivery-configuration`
<a name="cognito-identity-provider_GetLogDeliveryConfiguration_cli_2_topic"></a>

次のコード例は、`get-log-delivery-configuration` を使用する方法を示しています。

**AWS CLI**  
**ログ配信設定を表示するには**  
次の `get-log-delivery-configuration` の例では、リクエストされたユーザープールのログエクスポート設定を表示します。  

```
aws cognito-idp get-log-delivery-configuration \
    --user-pool-id us-west-2_EXAMPLE
```
出力:  

```
{
    "LogDeliveryConfiguration": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "LogConfigurations": [
            {
                "LogLevel": "INFO",
                "EventSource": "userAuthEvents",
                "FirehoseConfiguration": {
                    "StreamArn": "arn:aws:firehose:us-west-2:123456789012:deliverystream/my-test-deliverystream"
                }
            },
            {
                "LogLevel": "ERROR",
                "EventSource": "userNotification",
                "CloudWatchLogsConfiguration": {
                    "LogGroupArn": "arn:aws:logs:us-west-2:123456789012:log-group:my-message-delivery-logs"
                }
            }
        ]
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Exporting user pool logs](https://docs.aws.amazon.com/cognito/latest/developerguide/exporting-quotas-and-usage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLogDeliveryConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-log-delivery-configuration.html)」を参照してください。

### `get-signing-certificate`
<a name="cognito-identity-provider_GetSigningCertificate_cli_2_topic"></a>

次のコード例は、`get-signing-certificate` を使用する方法を示しています。

**AWS CLI**  
**SAML 署名証明書を表示するには**  
次の `get-signing-certificate` の例では、リクエストユーザープールの SAML 2.0 署名証明書を表示します。  

```
aws cognito-idp get-signing-certificate \
    --user-pool-id us-west-2_EXAMPLE
```
出力:  

```
{
    "Certificate": "[Certificate content]"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[SAML signing and encryption](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-SAML-signing-encryption.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSigningCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-signing-certificate.html)」を参照してください。

### `get-ui-customization`
<a name="cognito-identity-provider_GetUiCustomization_cli_2_topic"></a>

次のコード例は、`get-ui-customization` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションクライアントのホストされた UI カスタマイズの従来の設定を表示するには**  
次の `get-ui-customization` の例では、ユーザープールから設定を継承しないアプリケーションクライアントのホスト UI カスタマイズの従来の設定を表示します。  

```
aws cognito-idp get-ui-customization \
    --user-pool-id us-west-2_EXAMPLE \
    --client-id 1example23456789
```
出力:  

```
{
    "UICustomization": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "ClientId": "1example23456789",
        "ImageUrl": "https://example.cloudfront.net/us-west-2_EXAMPLE/1example23456789/20250115191928/assets/images/image.jpg",
        "CSS": "\n.logo-customizable {\n  max-width: 80%;\n  max-height: 30%;\n}\n\n.banner-customizable {\n  padding: 25px 0px 25px 0px;\n  background-color: lightgray;\n}\n\n.label-customizable {\n  font-weight: 400;\n}\n\n.textDescription-customizable {\n  padding-top: 100px;\n  padding-bottom: 10px;\n  display: block;\n  font-size: 12px;\n}\n\n.idpDescription-customizable {\n  padding-top: 10px;\n  padding-bottom: 10px;\n  display: block;\n  font-size: 16px;\n}\n\n.legalText-customizable {\n  color: #747474;\n  font-size: 11px;\n}\n\n.submitButton-customizable {\n  font-size: 14px;\n  font-weight: bold;\n  margin: 20px 0px 10px 0px;\n  height: 50px;\n  width: 100%;\n  color: #fff;\n  background-color: #337ab7;\n}\n\n.submitButton-customizable:hover {\n  color: #fff;\n  background-color: #286090;\n}\n\n.errorMessage-customizable {\n  padding: 5px;\n  font-size: 12px;\n  width: 100%;\n  background: #F5F5F5;\n  border: 2px solid #D64958;\n  color: #D64958;\n}\n\n.inputField-customizable {\n  width: 100%;\n  height: 34px;\n  color: #555;\n  background-color: #fff;\n  border: 1px solid #ccc;\n}\n\n.inputField-customizable:focus {\n  border-color: #66afe9;\n  outline: 0;\n}\n\n.idpButton-customizable {\n  height: 40px;\n  width: 100%;\n  width: 100%;\n  text-align: center;\n  margin-bottom: 15px;\n  color: #fff;\n  background-color: #5bc0de;\n  border-color: #46b8da;\n}\n\n.idpButton-customizable:hover {\n  color: #fff;\n  background-color: #31b0d5;\n}\n\n.socialButton-customizable {\n  border-radius: 2px;\n  height: 60px;\n  margin-bottom: 15px;\n  padding: 1px;\n  text-align: left;\n  width: 100%;\n}\n\n.redirect-customizable {\n  text-align: center;\n}\n\n.passwordCheck-notValid-customizable {\n  color: #DF3312;\n}\n\n.passwordCheck-valid-customizable {\n  color: #19BF00;\n}\n\n.background-customizable {\n  background-color: #fff;\n}\n",
        "CSSVersion": "20250115191928"
    }
}
```
詳細については、*Amazon Cognito デベロッパーガイド*」の「[Hosted UI (classic) branding](https://docs.aws.amazon.com/cognito/latest/developerguide/hosted-ui-classic-branding.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUiCustomization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-ui-customization.html)」を参照してください。

### `get-user-attribute-verification-code`
<a name="cognito-identity-provider_GetUserAttributeVerificationCode_cli_2_topic"></a>

次のコード例は、`get-user-attribute-verification-code` を使用する方法を示しています。

**AWS CLI**  
**属性検証コードを現在のユーザーに送信するには**  
次の `get-user-attribute-verification-code` の例では、現在サインインしているユーザーの E メールアドレスに属性検証コードを送信します。  

```
aws cognito-idp get-user-attribute-verification-code \
    --access-token eyJra456defEXAMPLE \
    --attribute-name email
```
出力:  

```
{
    "CodeDeliveryDetails": {
        "Destination": "a***@e***",
        "DeliveryMedium": "EMAIL",
        "AttributeName": "email"
    }
}
```
詳細については、「Amazon Cognito デベロッパーガイド」の「[ユーザーアカウントのサインアップと確認](https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUserAttributeVerificationCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-user-attribute-verification-code.html)」を参照してください。

### `get-user-auth-factors`
<a name="cognito-identity-provider_GetUserAuthFactors_cli_2_topic"></a>

次のコード例は、`get-user-auth-factors` を使用する方法を示しています。

**AWS CLI**  
**現在のユーザーが使用できる認証要素を一覧表示するには**  
次の `get-user-auth-factors` の例では、現在サインインしているユーザーが使用できる認証要素を一覧表示します。  

```
aws cognito-idp get-user-auth-factors \
    --access-token eyJra456defEXAMPLE
```
出力:  

```
{
    "Username": "testuser",
    "ConfiguredUserAuthFactors": [
        "PASSWORD",
        "EMAIL_OTP",
        "SMS_OTP",
        "WEB_AUTHN"
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Authentication](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUserAuthFactors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-user-auth-factors.html)」を参照してください。

### `get-user-pool-mfa-config`
<a name="cognito-identity-provider_GetUserPoolMfaConfig_cli_2_topic"></a>

次のコード例は、`get-user-pool-mfa-config` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールの多要素認証と WebAuthn 設定を表示するには**  
次の `get-user-pool-mfa-config` の例では、リクエストされたユーザープールの MFA および WebAuthn 設定を表示します。  

```
aws cognito-idp get-user-pool-mfa-config \
    --user-pool-id us-west-2_EXAMPLE
```
出力:  

```
{
    "SmsMfaConfiguration": {
        "SmsAuthenticationMessage": "Your OTP for MFA or sign-in: use {####}.",
        "SmsConfiguration": {
            "SnsCallerArn": "arn:aws:iam::123456789012:role/service-role/my-SMS-Role",
            "ExternalId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "SnsRegion": "us-west-2"
        }
    },
    "SoftwareTokenMfaConfiguration": {
        "Enabled": true
    },
    "EmailMfaConfiguration": {
        "Message": "Your OTP for MFA or sign-in: use {####}",
        "Subject": "OTP test"
    },
    "MfaConfiguration": "OPTIONAL",
    "WebAuthnConfiguration": {
        "RelyingPartyId": "auth.example.com",
        "UserVerification": "preferred"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Adding MFA](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUserPoolMfaConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-user-pool-mfa-config.html)」を参照してください。

### `get-user`
<a name="cognito-identity-provider_GetUser_cli_2_topic"></a>

次のコード例は、`get-user` を使用する方法を示しています。

**AWS CLI**  
**現在のユーザーの詳細を取得するには**  
次の `get-user` の例では、現在サインインしているユーザーのプロファイルを表示します。  

```
aws cognito-idp get-user \
    --access-token eyJra456defEXAMPLE
```
出力:  

```
{
    "Username": "johndoe",
    "UserAttributes": [
        {
            "Name": "sub",
            "Value": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        },
        {
            "Name": "identities",
            "Value": "[{\"userId\":\"a1b2c3d4-5678-90ab-cdef-EXAMPLE22222\",\"providerName\":\"SignInWithApple\",\"providerType\":\"SignInWithApple\",\"issuer\":null,\"primary\":false,\"dateCreated\":1701125599632}]"
        },
        {
            "Name": "email_verified",
            "Value": "true"
        },
        {
            "Name": "custom:state",
            "Value": "Maine"
        },
        {
            "Name": "name",
            "Value": "John Doe"
        },
        {
            "Name": "phone_number_verified",
            "Value": "true"
        },
        {
            "Name": "phone_number",
            "Value": "+12065551212"
        },
        {
            "Name": "preferred_username",
            "Value": "jamesdoe"
        },
        {
            "Name": "locale",
            "Value": "EMEA"
        },
        {
            "Name": "email",
            "Value": "jamesdoe@example.com"
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザーの管理](https://docs.aws.amazon.com/cognito/latest/developerguide/managing-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/get-user.html)」を参照してください。

### `global-sign-out`
<a name="cognito-identity-provider_GlobalSignOut_cli_2_topic"></a>

次のコード例は、`global-sign-out` を使用する方法を示しています。

**AWS CLI**  
**現在のユーザーをサインアウトするには**  
次の `global-sign-out` の例では、現在のユーザーをサインアウトします。  

```
aws cognito-idp global-sign-out \
    --access-token eyJra456defEXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザーの管理](https://docs.aws.amazon.com/cognito/latest/developerguide/managing-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GlobalSignOut](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/global-sign-out.html)」を参照してください。

### `initiate-auth`
<a name="cognito-identity-provider_InitiateAuth_cli_2_topic"></a>

次のコード例は、`initiate-auth` を使用する方法を示しています。

**AWS CLI**  
**ユーザーをサインインするには**  
次の `initiate-auth` の例では、基本的なユーザー名-パスワードフローを使用してユーザーにサインインし、追加のチャレンジはありません。  

```
aws cognito-idp initiate-auth \
    --auth-flow USER_PASSWORD_AUTH \
    --client-id 1example23456789 \
    --analytics-metadata AnalyticsEndpointId=d70b2ba36a8c4dc5a04a0451aEXAMPLE \
    --auth-parameters USERNAME=testuser,PASSWORD=[Password] --user-context-data EncodedData=mycontextdata --client-metadata MyTestKey=MyTestValue
```
出力:  

```
{
    "AuthenticationResult": {
        "AccessToken": "eyJra456defEXAMPLE",
        "ExpiresIn": 3600,
        "TokenType": "Bearer",
        "RefreshToken": "eyJra123abcEXAMPLE",
        "IdToken": "eyJra789ghiEXAMPLE",
        "NewDeviceMetadata": {
            "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "DeviceGroupKey": "-v7w9UcY6"
        }
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Authentication](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InitiateAuth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/initiate-auth.html)」を参照してください。

### `list-devices`
<a name="cognito-identity-provider_ListDevices_cli_2_topic"></a>

次のコード例は、`list-devices` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのデバイスを一覧表示するには**  
次の `list-devices` の例では、現在のユーザーが登録したデバイスを一覧表示します。  

```
aws cognito-idp list-devices \
    --access-token eyJra456defEXAMPLE
```
出力:  

```
{
    "Devices": [
        {
            "DeviceAttributes": [
                {
                    "Name": "device_status",
                    "Value": "valid"
                },
                {
                    "Name": "device_name",
                    "Value": "Dart-device"
                },
                {
                    "Name": "last_ip_used",
                    "Value": "192.0.2.1"
                }
            ],
            "DeviceCreateDate": 1715100742.022,
            "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "DeviceLastAuthenticatedDate": 1715100742.0,
            "DeviceLastModifiedDate": 1723233651.167
        },
        {
            "DeviceAttributes": [
                {
                    "Name": "device_status",
                    "Value": "valid"
                },
                {
                    "Name": "last_ip_used",
                    "Value": "192.0.2.2"
                }
            ],
            "DeviceCreateDate": 1726856147.993,
            "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "DeviceLastAuthenticatedDate": 1726856147.0,
            "DeviceLastModifiedDate": 1726856147.993
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Working with devices](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-device-tracking.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-devices.html)」を参照してください。

### `list-groups`
<a name="cognito-identity-provider_ListGroups_cli_2_topic"></a>

次のコード例は、`list-groups` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールのグループを一覧表示するには**  
次の `list-groups` の例では、リクエストされたユーザープールの最初の 2 つのグループを一覧表示します。  

```
aws cognito-idp list-groups \
    --user-pool-id us-west-2_EXAMPLE \
    --max-items 2
```
出力:  

```
{
    "Groups": [
        {
            "CreationDate": 1681760899.633,
            "Description": "My test group",
            "GroupName": "testgroup",
            "LastModifiedDate": 1681760899.633,
            "Precedence": 1,
            "UserPoolId": "us-west-2_EXAMPLE"
        },
        {
            "CreationDate": 1642632749.051,
            "Description": "Autogenerated group for users who sign in using Facebook",
            "GroupName": "us-west-2_EXAMPLE_Facebook",
            "LastModifiedDate": 1642632749.051,
            "UserPoolId": "us-west-2_EXAMPLE"
        }
    ],
    "NextToken": "[Pagination token]"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[ユーザープールへのグループの追加](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-user-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-groups.html)」を参照してください。

### `list-identity-providers`
<a name="cognito-identity-provider_ListIdentityProviders_cli_2_topic"></a>

次のコード例は、`list-identity-providers` を使用する方法を示しています。

**AWS CLI**  
**ID プロバイダーを一覧表示するには**  
次の `list-identity-providers` の例では、リクエストされたユーザープールの最初の 2 つの ID プロバイダーを一覧表示します。  

```
aws cognito-idp list-identity-providers \
    --user-pool-id us-west-2_EXAMPLE \
    --max-items 2
```
出力:  

```
{
    "Providers": [
        {
            "CreationDate": 1619477386.504,
            "LastModifiedDate": 1703798328.142,
            "ProviderName": "Azure",
            "ProviderType": "SAML"
        },
        {
            "CreationDate": 1642698776.175,
            "LastModifiedDate": 1642699086.453,
            "ProviderName": "LoginWithAmazon",
            "ProviderType": "LoginWithAmazon"
        }
    ],
    "NextToken": "[Pagination token]"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Third-party IdP sign-in](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-identity-federation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIdentityProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-identity-providers.html)」を参照してください。

### `list-resource-servers`
<a name="cognito-identity-provider_ListResourceServers_cli_2_topic"></a>

次のコード例は、`list-resource-servers` を使用する方法を示しています。

**AWS CLI**  
**リソースサーバーを一覧表示するには**  
次の `list-resource-servers` の例では、リクエストされたユーザープールの最初の 2 つのリソースサーバーを一覧表示します。  

```
aws cognito-idp list-resource-servers \
    --user-pool-id us-west-2_EXAMPLE \
    --max-results 2
```
出力:  

```
{
    "ResourceServers": [
        {
            "Identifier": "myapi.example.com",
            "Name": "Example API with custom access control scopes",
            "Scopes": [
                {
                    "ScopeDescription": "International customers",
                    "ScopeName": "international.read"
                },
                {
                    "ScopeDescription": "Domestic customers",
                    "ScopeName": "domestic.read"
                }
            ],
            "UserPoolId": "us-west-2_EXAMPLE"
        },
        {
            "Identifier": "myapi2.example.com",
            "Name": "Another example API for access control",
            "Scopes": [
                {
                    "ScopeDescription": "B2B customers",
                    "ScopeName": "b2b.read"
                }
            ],
            "UserPoolId": "us-west-2_EXAMPLE"
        }
    ],
    "NextToken": "[Pagination token]"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Access control with resource servers](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-define-resource-servers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceServers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-resource-servers.html)」を参照してください。

### `list-tags-for-resource`
<a name="cognito-identity-provider_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、リクエストされた ARN を使用してユーザープールに割り当てられたタグを一覧表示します。  

```
aws cognito-idp list-tags-for-resource \
    --resource-arn arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_EXAMPLE
```
出力:  

```
{
    "Tags": {
        "administrator": "Jie",
        "tenant": "ExampleCorp"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Tagging Amazon Cognito resources](https://docs.aws.amazon.com/cognito/latest/developerguide/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-tags-for-resource.html)」を参照してください。

### `list-user-import-jobs`
<a name="cognito-identity-provider_ListUserImportJobs_cli_2_topic"></a>

次のコード例は、`list-user-import-jobs` を使用する方法を示しています。

**AWS CLI**  
**ユーザーインポートジョブとステータスを一覧表示するには**  
次の `list-user-import-jobs` の例では、リクエストされたユーザープールの最初の 3 つのユーザーインポートジョブとその詳細を一覧表示します。  

```
aws cognito-idp list-user-import-jobs \
    --user-pool-id us-west-2_EXAMPLE \
    --max-results 3
```
出力:  

```
{
    "PaginationToken": "us-west-2_EXAMPLE#import-example3#1667948397084",
    "UserImportJobs": [
        {
            "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/service-role/Cognito-UserImport-Role",
            "CompletionDate": 1735329786.142,
            "CompletionMessage": "The user import job has expired.",
            "CreationDate": 1735241621.022,
            "FailedUsers": 0,
            "ImportedUsers": 0,
            "JobId": "import-example1",
            "JobName": "Test-import-job-1",
            "PreSignedUrl": "https://aws-cognito-idp-user-import-pdx.s3.us-west-2.amazonaws.com/123456789012/us-west-2_EXAMPLE/import-mAgUtd8PMm?X-Amz-Security-Token=[token]&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20241226T193341Z&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption&X-Amz-Expires=899&X-Amz-Credential=[credential]&X-Amz-Signature=[signature]",
            "SkippedUsers": 0,
            "Status": "Expired",
            "UserPoolId": "us-west-2_EXAMPLE"
        },
        {
            "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/service-role/Cognito-UserImport-Role",
            "CompletionDate": 1681509058.408,
            "CompletionMessage": "Too many users have failed or been skipped during the import.",
            "CreationDate": 1681509001.477,
            "FailedUsers": 1,
            "ImportedUsers": 0,
            "JobId": "import-example2",
            "JobName": "Test-import-job-2",
            "PreSignedUrl": "https://aws-cognito-idp-user-import-pdx.s3.us-west-2.amazonaws.com/123456789012/us-west-2_EXAMPLE/import-mAgUtd8PMm?X-Amz-Security-Token=[token]&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20241226T193341Z&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption&X-Amz-Expires=899&X-Amz-Credential=[credential]&X-Amz-Signature=[signature]",
            "SkippedUsers": 0,
            "StartDate": 1681509057.965,
            "Status": "Failed",
            "UserPoolId": "us-west-2_EXAMPLE"
        },
        {
            "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/service-role/Cognito-UserImport-Role",
            "CompletionDate": 1.667864578676E9,
            "CompletionMessage": "Import Job Completed Successfully.",
            "CreationDate": 1.667864480281E9,
            "FailedUsers": 0,
            "ImportedUsers": 6,
            "JobId": "import-example3",
            "JobName": "Test-import-job-3",
            "PreSignedUrl": "https://aws-cognito-idp-user-import-pdx.s3.us-west-2.amazonaws.com/123456789012/us-west-2_EXAMPLE/import-mAgUtd8PMm?X-Amz-Security-Token=[token]&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20241226T193341Z&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption&X-Amz-Expires=899&X-Amz-Credential=[credential]&X-Amz-Signature=[signature]",
            "SkippedUsers": 0,
            "StartDate": 1.667864578167E9,
            "Status": "Succeeded",
            "UserPoolId": "us-west-2_EXAMPLE"
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Importing users from a CSV file](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUserImportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-user-import-jobs.html)」を参照してください。

### `list-user-pool-clients`
<a name="cognito-identity-provider_ListUserPoolClients_cli_2_topic"></a>

次のコード例は、`list-user-pool-clients` を使用する方法を示しています。

**AWS CLI**  
**アプリクライアントを一覧表示するには**  
次の `list-user-pool-clients` の例では、リクエストされたユーザープールの最初の 3 つのアプリクライアントを一覧表示します。  

```
aws cognito-idp list-user-pool-clients \
    --user-pool-id us-west-2_EXAMPLE \
    --max-results 3
```
出力:  

```
{
    "NextToken": "[Pagination token]",
    "UserPoolClients": [
        {
            "ClientId": "1example23456789",
            "ClientName": "app-client-1",
            "UserPoolId": "us-west-2_EXAMPLE"
        },
        {
            "ClientId": "2example34567890",
            "ClientName": "app-client-2",
            "UserPoolId": "us-west-2_EXAMPLE"
        },
        {
            "ClientId": "3example45678901",
            "ClientName": "app-client-3",
            "UserPoolId": "us-west-2_EXAMPLE"
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[App clients](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUserPoolClients](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-user-pool-clients.html)」を参照してください。

### `list-user-pools`
<a name="cognito-identity-provider_ListUserPools_cli_2_topic"></a>

次のコード例は、`list-user-pools` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールを一覧表示するには**  
次の の`list-user-pools`例では、現在の CLI 認証情報の AWS アカウントで使用可能なユーザープールの 3 つを一覧表示します。  

```
aws cognito-idp list-user-pools \
    --max-results 3
```
出力:  

```
{
    "NextToken": "[Pagination token]",
    "UserPools": [
        {
            "CreationDate": 1681502497.741,
            "Id": "us-west-2_EXAMPLE1",
            "LambdaConfig": {
                "CustomMessage": "arn:aws:lambda:us-east-1:123456789012:function:MyFunction",
                "PreSignUp": "arn:aws:lambda:us-east-1:123456789012:function:MyFunction",
                "PreTokenGeneration": "arn:aws:lambda:us-east-1:123456789012:function:MyFunction",
                "PreTokenGenerationConfig": {
                    "LambdaArn": "arn:aws:lambda:us-east-1:123456789012:function:MyFunction",
                    "LambdaVersion": "V1_0"
                }
            },
            "LastModifiedDate": 1681502497.741,
            "Name": "user pool 1"
        },
        {
            "CreationDate": 1686064178.717,
            "Id": "us-west-2_EXAMPLE2",
            "LambdaConfig": {
            },
            "LastModifiedDate": 1686064178.873,
            "Name": "user pool 2"
        },
        {
            "CreationDate": 1627681712.237,
            "Id": "us-west-2_EXAMPLE3",
            "LambdaConfig": {
                "UserMigration": "arn:aws:lambda:us-east-1:123456789012:function:MyFunction"
            },
            "LastModifiedDate": 1678486942.479,
            "Name": "user pool 3"
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Amazon Cognito user pools](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListUserPools](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-user-pools.html)」を参照してください。**

### `list-users-in-group`
<a name="cognito-identity-provider_ListUsersInGroup_cli_2_topic"></a>

次のコード例は、`list-users-in-group` を使用する方法を示しています。

**AWS CLI**  
**グループ内のユーザーを一覧表示するには**  
この例では、MyGroup グループのユーザーを一覧表示しています。  
コマンド:  

```
aws cognito-idp list-users-in-group --user-pool-id us-west-2_aaaaaaaaa --group-name MyGroup
```
出力:  

```
{
  "Users": [
      {
          "Username": "acf10624-80bb-401a-ac61-607bee2110ec",
          "Attributes": [
              {
                  "Name": "sub",
                  "Value": "acf10624-80bb-401a-ac61-607bee2110ec"
              },
              {
                  "Name": "custom:CustomAttr1",
                  "Value": "New Value!"
              },
              {
                  "Name": "email",
                  "Value": "jane@example.com"
              }
          ],
          "UserCreateDate": 1548102770.284,
          "UserLastModifiedDate": 1548103204.893,
          "Enabled": true,
          "UserStatus": "CONFIRMED"
      },
      {
          "Username": "22704aa3-fc10-479a-97eb-2af5806bd327",
          "Attributes": [
              {
                  "Name": "sub",
                  "Value": "22704aa3-fc10-479a-97eb-2af5806bd327"
              },
              {
                  "Name": "email_verified",
                  "Value": "true"
              },
              {
                  "Name": "email",
                  "Value": "diego@example.com"
              }
          ],
          "UserCreateDate": 1548089817.683,
          "UserLastModifiedDate": 1548089817.683,
          "Enabled": true,
          "UserStatus": "FORCE_CHANGE_PASSWORD"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsersInGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-users-in-group.html)」を参照してください。

### `list-users`
<a name="cognito-identity-provider_ListUsers_cli_2_topic"></a>

次のコード例は、`list-users` を使用する方法を示しています。

**AWS CLI**  
**例 1: サーバー側のフィルターを使用してユーザーを一覧表示するには**  
次の `list-users` の例では、リクエストされたユーザープールの E メールアドレスが `testuser` で始まる 3 人のユーザーを一覧表示します。  

```
aws cognito-idp list-users \
    --user-pool-id us-west-2_EXAMPLE \
    --filter email^=\"testuser\" \
    --max-items 3
```
出力:  

```
{
    "PaginationToken": "efgh5678EXAMPLE",
    "Users": [
        {
            "Attributes": [
                {
                    "Name": "sub",
                    "Value": "eaad0219-2117-439f-8d46-4db20e59268f"
                },
                {
                    "Name": "email",
                    "Value": "testuser@example.com"
                }
            ],
            "Enabled": true,
            "UserCreateDate": 1682955829.578,
            "UserLastModifiedDate": 1689030181.63,
            "UserStatus": "CONFIRMED",
            "Username": "testuser"
        },
        {
            "Attributes": [
                {
                    "Name": "sub",
                    "Value": "3b994cfd-0b07-4581-be46-3c82f9a70c90"
                },
                {
                    "Name": "email",
                    "Value": "testuser2@example.com"
                }
            ],
            "Enabled": true,
            "UserCreateDate": 1684427979.201,
            "UserLastModifiedDate": 1684427979.201,
            "UserStatus": "UNCONFIRMED",
            "Username": "testuser2"
        },
        {
            "Attributes": [
                {
                    "Name": "sub",
                    "Value": "5929e0d1-4c34-42d1-9b79-a5ecacfe66f7"
                },
                {
                    "Name": "email",
                    "Value": "testuser3@example.com"
                }
            ],
            "Enabled": true,
            "UserCreateDate": 1684427823.641,
            "UserLastModifiedDate": 1684427823.641,
            "UserStatus": "UNCONFIRMED",
            "Username": "testuser3@example.com"
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Managing and searching for users](https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-manage-user-accounts.html)」を参照してください。  
**例 2: クライアント側のフィルターを使用してユーザーを一覧表示するには**  
次の `list-users` の例では、属性を持つ 3 人のユーザーの属性を一覧表示します。この場合は、E メールアドレスに、E メールドメイン「@example.com」が含まれています。他の属性がこの文字列を含んでいる場合、その属性も表示されます。2 番目のユーザーは、クエリに一致する属性を持たず、表示される出力から除外されますが、サーバーのレスポンスからは除外されません。  

```
aws cognito-idp list-users \
    --user-pool-id us-west-2_EXAMPLE \
    --max-items 3
    --query Users\[\*\].Attributes\[\?Value\.contains\(\@\,\'@example.com\'\)\]
```
出力:  

```
[
    [
        {
            "Name": "email",
            "Value": "admin@example.com"
        }
    ],
    [],
    [
        {
            "Name": "email",
            "Value": "operator@example.com"
        }
    ]
]
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Managing and searching for users](https://docs.aws.amazon.com/cognito/latest/developerguide/how-to-manage-user-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-users.html)」を参照してください。

### `list-web-authn-credentials`
<a name="cognito-identity-provider_ListWebAuthnCredentials_cli_2_topic"></a>

次のコード例は、`list-web-authn-credentials` を使用する方法を示しています。

**AWS CLI**  
**パスキーの認証情報を一覧表示するには**  
次の `list-web-authn-credentials` の例では、現在のユーザーのパスキー、WebAuthn、または認証情報を一覧表示します。登録されているデバイスは 1 つです。  

```
aws cognito-idp list-web-authn-credentials \
    --access-token eyJra456defEXAMPLE
```
出力:  

```
{
    "Credentials": [
        {
            "AuthenticatorAttachment": "cross-platform",
            "CreatedAt": 1736293876.115,
            "CredentialId": "8LApgk4-lNUFHbhm2w6Und7-uxcc8coJGsPxiogvHoItc64xWQc3r4CEXAMPLE",
            "FriendlyCredentialName": "Roaming passkey",
            "RelyingPartyId": "auth.example.com"
        }
    ]
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Passkey sign-in](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html#amazon-cognito-user-pools-authentication-flow-methods-passkey)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWebAuthnCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/list-web-authn-credentials.html)」を参照してください。

### `resend-confirmation-code`
<a name="cognito-identity-provider_ResendConfirmationCode_cli_2_topic"></a>

次のコード例は、`resend-confirmation-code` を使用する方法を示しています。

**AWS CLI**  
**確認コードを再送信するには**  
次の `resend-confirmation-code` 例では、ユーザー `jane` に確認コードを送信します。  

```
aws cognito-idp resend-confirmation-code \
    --client-id 12a3b456c7de890f11g123hijk \
    --username jane
```
出力:  

```
{
    "CodeDeliveryDetails": {
        "Destination": "j***@e***.com",
        "DeliveryMedium": "EMAIL",
        "AttributeName": "email"
    }
}
```
詳細については、「Amazon Cognito デベロッパーガイド」の「[ユーザーアカウントのサインアップと確認](https://docs.aws.amazon.com/cognito/latest/developerguide/signing-up-users-in-your-app.html)」を参照してください。**  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ResendConfirmationCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/resend-confirmation-code.html)」を参照してください。**

### `respond-to-auth-challenge`
<a name="cognito-identity-provider_RespondToAuthChallenge_cli_2_topic"></a>

次のコード例は、`respond-to-auth-challenge` を使用する方法を示しています。

**AWS CLI**  
**例 1: NEW\$1PASSWORD\$1REQUIRED チャレンジに応答するには**  
次の `respond-to-auth-challenge` の例では、initiate-auth によって返された NEW\$1PASSWORD\$1REQUIRED チャレンジに応答します。ユーザー `jane@example.com` のパスワードを設定します。  

```
aws cognito-idp respond-to-auth-challenge \
    --client-id 1example23456789 \
    --challenge-name NEW_PASSWORD_REQUIRED \
    --challenge-responses USERNAME=jane@example.com,NEW_PASSWORD=[Password] \
    --session AYABeEv5HklEXAMPLE
```
出力:  

```
{
    "ChallengeParameters": {},
    "AuthenticationResult": {
        "AccessToken": "ACCESS_TOKEN",
        "ExpiresIn": 3600,
        "TokenType": "Bearer",
        "RefreshToken": "REFRESH_TOKEN",
        "IdToken": "ID_TOKEN",
        "NewDeviceMetadata": {
            "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "DeviceGroupKey": "-wt2ha1Zd"
        }
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Authentication](https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html)」を参照してください。  
**例 2: SELECT\$1MFA\$1TYPE チャレンジに応答するには**  
次の `respond-to-auth-challenge` の例では、現在のユーザーの MFA オプションとして TOTP MFA を選択します。ユーザーは、MFA タイプを選択して MFA コードを入力するように求められます。  

```
aws cognito-idp respond-to-auth-challenge \
    --client-id 1example23456789
    --session AYABeEv5HklEXAMPLE
    --challenge-name SELECT_MFA_TYPE
    --challenge-responses USERNAME=testuser,ANSWER=SOFTWARE_TOKEN_MFA
```
出力:  

```
{
    "ChallengeName": "SOFTWARE_TOKEN_MFA",
    "Session": "AYABeEv5HklEXAMPLE",
    "ChallengeParameters": {
        "FRIENDLY_DEVICE_NAME": "transparent"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Adding MFA](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html)」を参照してください。  
**例 3: SOFTWARE\$1TOKEN\$1MFA チャレンジに応答するには**  
次の `respond-to-auth-challenge` の例では、TOTP MFA コードを提供し、サインインを完了する方法を示します。  

```
aws cognito-idp respond-to-auth-challenge \
    --client-id 1example23456789 \
    --session AYABeEv5HklEXAMPLE \
    --challenge-name SOFTWARE_TOKEN_MFA \
    --challenge-responses USERNAME=testuser,SOFTWARE_TOKEN_MFA_CODE=123456
```
出力:  

```
{
    "AuthenticationResult": {
        "AccessToken": "eyJra456defEXAMPLE",
        "ExpiresIn": 3600,
        "TokenType": "Bearer",
        "RefreshToken": "eyJra123abcEXAMPLE",
        "IdToken": "eyJra789ghiEXAMPLE",
        "NewDeviceMetadata": {
            "DeviceKey": "us-west-2_a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "DeviceGroupKey": "-v7w9UcY6"
        }
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Adding MFA](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[RespondToAuthChallenge](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/respond-to-auth-challenge.html)」を参照してください。**

### `revoke-token`
<a name="cognito-identity-provider_RevokeToken_cli_2_topic"></a>

次のコード例は、`revoke-token` を使用する方法を示しています。

**AWS CLI**  
**更新トークンを取り消すには**  
次の `revoke-token` では、リクエストされた更新トークンと、関連するアクセストークンを取り消します。  

```
aws cognito-idp revoke-token \
    --token eyJjd123abcEXAMPLE \
    --client-id 1example23456789
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Revoking tokens](https://docs.aws.amazon.com/cognito/latest/developerguide/token-revocation.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[RevokeToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/revoke-token.html)」を参照してください。**

### `set-log-delivery-configuration`
<a name="cognito-identity-provider_SetLogDeliveryConfiguration_cli_2_topic"></a>

次のコード例は、`set-log-delivery-configuration` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールからのログのエクスポートを設定するには**  
次の `set-log-delivery-configuration` の例では、ロググループへのユーザー通知エラーのログ記録と S3 バケットへのユーザー認証情報のログ記録を使用して、リクエストされたユーザープールを設定します。  

```
aws cognito-idp set-log-delivery-configuration \
    --user-pool-id us-west-2_EXAMPLE \
    --log-configurations LogLevel=ERROR,EventSource=userNotification,CloudWatchLogsConfiguration={LogGroupArn=arn:aws:logs:us-west-2:123456789012:log-group:cognito-exported} LogLevel=INFO,EventSource=userAuthEvents,S3Configuration={BucketArn=arn:aws:s3:::amzn-s3-demo-bucket1}
```
出力:  

```
{
   "LogDeliveryConfiguration": {
        "LogConfigurations": [
            {
                "CloudWatchLogsConfiguration": {
                    "LogGroupArn": "arn:aws:logs:us-west-2:123456789012:log-group:cognito-exported"
                },
                "EventSource": "userNotification",
                "LogLevel": "ERROR"
            },
            {
                "EventSource": "userAuthEvents",
                "LogLevel": "INFO",
                "S3Configuration": {
                    "BucketArn": "arn:aws:s3:::amzn-s3-demo-bucket1"
                }
            }
        ],
        "UserPoolId": "us-west-2_EXAMPLE"
   }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Exporting user pool logs](https://docs.aws.amazon.com/cognito/latest/developerguide/exporting-quotas-and-usage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetLogDeliveryConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/set-log-delivery-configuration.html)」を参照してください。

### `set-risk-configuration`
<a name="cognito-identity-provider_SetRiskConfiguration_cli_2_topic"></a>

次のコード例は、`set-risk-configuration` を使用する方法を示しています。

**AWS CLI**  
**脅威保護のリスク設定を行うには**  
次の `set-risk-configuration` の例では、リクエストされたアプリクライアントで脅威保護のメッセージとアクション、侵害された認証情報、および IP アドレス例外を設定します。NotifyConfiguration オブジェクトは複雑であるため、JSON 入力がこのコマンドのベストプラクティスです。  

```
aws cognito-idp set-risk-configuration \
    --cli-input-json file://set-risk-configuration.json
```
`set-risk-configuration.json` の内容:  

```
{
    "AccountTakeoverRiskConfiguration": {
        "Actions": {
            "HighAction": {
                "EventAction": "MFA_REQUIRED",
                "Notify": true
            },
            "LowAction": {
                "EventAction": "NO_ACTION",
                "Notify": true
            },
            "MediumAction": {
                "EventAction": "MFA_IF_CONFIGURED",
                "Notify": true
            }
        },
        "NotifyConfiguration": {
            "BlockEmail": {
                "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We blocked an unrecognized sign-in to your account with this information:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                "Subject": "Blocked sign-in attempt",
                "TextBody": "We blocked an unrecognized sign-in to your account with this information:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
            },
            "From": "admin@example.com",
            "MfaEmail": {
                "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We required you to use multi-factor authentication for the following sign-in attempt:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                "Subject": "New sign-in attempt",
                "TextBody": "We required you to use multi-factor authentication for the following sign-in attempt:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
            },
            "NoActionEmail": {
                "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We observed an unrecognized sign-in to your account with this information:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                "Subject": "New sign-in attempt",
                "TextBody": "We observed an unrecognized sign-in to your account with this information:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
            },
            "ReplyTo": "admin@example.com",
            "SourceArn": "arn:aws:ses:us-west-2:123456789012:identity/admin@example.com"
        }
    },
    "ClientId": "1example23456789",
    "CompromisedCredentialsRiskConfiguration": {
        "Actions": {
            "EventAction": "BLOCK"
        },
        "EventFilter": [
            "PASSWORD_CHANGE",
            "SIGN_UP",
            "SIGN_IN"
        ]
    },
    "RiskExceptionConfiguration": {
        "BlockedIPRangeList": [
            "192.0.2.1/32",
            "192.0.2.2/32"
        ],
        "SkippedIPRangeList": [
            "203.0.113.1/32",
            "203.0.113.2/32"
        ]
    },
    "UserPoolId": "us-west-2_EXAMPLE"
}
```
出力:  

```
{
    "RiskConfiguration": {
        "AccountTakeoverRiskConfiguration": {
            "Actions": {
                "HighAction": {
                    "EventAction": "MFA_REQUIRED",
                    "Notify": true
                },
                "LowAction": {
                    "EventAction": "NO_ACTION",
                    "Notify": true
                },
                "MediumAction": {
                    "EventAction": "MFA_IF_CONFIGURED",
                    "Notify": true
                }
            },
            "NotifyConfiguration": {
                "BlockEmail": {
                    "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We blocked an unrecognized sign-in to your account with this information:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                    "Subject": "Blocked sign-in attempt",
                    "TextBody": "We blocked an unrecognized sign-in to your account with this information:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
                },
                "From": "admin@example.com",
                "MfaEmail": {
                    "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We required you to use multi-factor authentication for the following sign-in attempt:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                    "Subject": "New sign-in attempt",
                    "TextBody": "We required you to use multi-factor authentication for the following sign-in attempt:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
                },
                "NoActionEmail": {
                    "HtmlBody": "<!DOCTYPE html>\n<html>\n<head>\n\t<title>HTML email context</title>\n\t<meta charset=\"utf-8\">\n</head>\n<body>\n<pre>We observed an unrecognized sign-in to your account with this information:\n<ul>\n<li>Time: {login-time}</li>\n<li>Device: {device-name}</li>\n<li>Location: {city}, {country}</li>\n</ul>\nIf this sign-in was not by you, you should change your password and notify us by clicking on <a href={one-click-link-invalid}>this link</a>\nIf this sign-in was by you, you can follow <a href={one-click-link-valid}>this link</a> to let us know</pre>\n</body>\n</html>",
                    "Subject": "New sign-in attempt",
                    "TextBody": "We observed an unrecognized sign-in to your account with this information:\nTime: {login-time}\nDevice: {device-name}\nLocation: {city}, {country}\nIf this sign-in was not by you, you should change your password and notify us by clicking on {one-click-link-invalid}\nIf this sign-in was by you, you can follow {one-click-link-valid} to let us know"
                },
                "ReplyTo": "admin@example.com",
                "SourceArn": "arn:aws:ses:us-west-2:123456789012:identity/admin@example.com"
            }
        },
        "ClientId": "1example23456789",
        "CompromisedCredentialsRiskConfiguration": {
            "Actions": {
                "EventAction": "BLOCK"
            },
            "EventFilter": [
                "PASSWORD_CHANGE",
                "SIGN_UP",
                "SIGN_IN"
            ]
        },
        "RiskExceptionConfiguration": {
            "BlockedIPRangeList": [
                "192.0.2.1/32",
                "192.0.2.2/32"
            ],
            "SkippedIPRangeList": [
                "203.0.113.1/32",
                "203.0.113.2/32"
            ]
        },
        "UserPoolId": "us-west-2_EXAMPLE"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Threat protection](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-settings-threat-protection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetRiskConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/set-risk-configuration.html)」を参照してください。

### `set-ui-customization`
<a name="cognito-identity-provider_SetUiCustomization_cli_2_topic"></a>

次のコード例は、`set-ui-customization` を使用する方法を示しています。

**AWS CLI**  
**例 1: アプリクライアントのクラシックホスト UI をカスタマイズするには**  
次の `set-ui-customization` の例では、リクエストされたアプリクライアントをいくつかのカスタム CSS で設定し、Amazon Cognito ロゴをアプリケーションロゴとして使用します。  

```
aws cognito-idp set-ui-customization \
    --user-pool-id us-west-2_ywDJHlIfU \
    --client-id 14pq32c5q2uq2q7keorloqvb23 \
    --css ".logo-customizable {\n\tmax-width: 60%;\n\tmax-height: 30%;\n}\n.banner-customizable {\n\tpadding: 25px 0px 25px 0px;\n\tbackground-color: lightgray;\n}\n.label-customizable {\n\tfont-weight: 400;\n}\n.textDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.idpDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.legalText-customizable {\n\tcolor: #747474;\n\tfont-size: 11px;\n}\n.submitButton-customizable {\n\tfont-size: 11px;\n\tfont-weight: normal;\n\tmargin: 20px -15px 10px -13px;\n\theight: 40px;\n\twidth: 108%;\n\tcolor: #fff;\n\tbackground-color: #337ab7;\n\ttext-align: center;\n}\n.submitButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #286090;\n}\n.errorMessage-customizable {\n\tpadding: 5px;\n\tfont-size: 14px;\n\twidth: 100%;\n\tbackground: #F5F5F5;\n\tborder: 2px solid #D64958;\n\tcolor: #D64958;\n}\n.inputField-customizable {\n\twidth: 100%;\n\theight: 34px;\n\tcolor: #555;\n\tbackground-color: #fff;\n\tborder: 1px solid #ccc;\n\tborder-radius: 0px;\n}\n.inputField-customizable:focus {\n\tborder-color: #66afe9;\n\toutline: 0;\n}\n.idpButton-customizable {\n\theight: 40px;\n\twidth: 100%;\n\twidth: 100%;\n\ttext-align: center;\n\tmargin-bottom: 15px;\n\tcolor: #fff;\n\tbackground-color: #5bc0de;\n\tborder-color: #46b8da;\n}\n.idpButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #31b0d5;\n}\n.socialButton-customizable {\n\tborder-radius: 2px;\n\theight: 40px;\n\tmargin-bottom: 15px;\n\tpadding: 1px;\n\ttext-align: left;\n\twidth: 100%;\n}\n.redirect-customizable {\n\ttext-align: center;\n}\n.passwordCheck-notValid-customizable {\n\tcolor: #DF3312;\n}\n.passwordCheck-valid-customizable {\n\tcolor: #19BF00;\n}\n.background-customizable {\n\tbackground-color: #fff;\n}\n" \
    --image-file iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAA2UExURd00TN9BV/Cmsfvm6f3y9P////fM0uqAj+yNmu6ZpvnZ3eNabuFNYuZneehzhPKzvPTAxwAAAOiMMlkAAAASdFJOU///////////////////////AOK/vxIAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAKDSURBVFhH7ZfpkoMgEISDHKuEw/d/2u2BQWMiBrG29o+fVsKatdPMAeZxc3Nz8w+ISekzmB++sYIw/I/tjHzrPpO2Tx62EbR2PNxFac+jVuKxRaV50IzXkUe76NOCoUuwlvnQKei02gNF0ykotOLRBq/nboeWRxAISx2EbsHFoRhK6Igk2JJlwScfQjgt06dOaWWiTbEDAe/iq8N9kqCw2uCbHkHlYkaXEF8EYeL9RDqT4FhC6XMIIEifdcUwCc4leNyhabadWU6OlKYJE1Oac3NSPhB5rlaXlSgmr/1lww4nPaU/1ylfLGxX1r6Y66ZZkCqvnOlqKWws59ELj7fULc2CubwySYkdDuuiY0/F0L6Q5pZiSG0SfZTSTCOUhxOCH1AdIoCpTTIjtd+VpEjUDDytQH/0Fpc661Aisas/4qmyUItD557pSCOSQQzlx27J+meyDGc5zZgfhWuXE1lGgmVOMwmWdeGdzhjqZV14x5vSj7vsC5JDz/Cl0Vhp56n2NQt1wQIpury1EPbwyaYm+IhmAQKoajkH51wg4cMZ1wQ3QG9efKWWOaDhYWnU6jXjCMdRmm21PArI+Pb5DYoH93hq0ZCPlxeGJho/DI15C6sQc/L2sTC47UFBKZGHT6k+zlXg7WebA0Nr0HTcLMfk/Y4Rc65D3iG6WDd7YLSlVqk87bVhUwhnClrx11RsVQwlAA818Mn+QEs71BhSFU6orsUfKhHp72XMGYXi4q9c64RXRvzkWurRfG2vI2be/VaNcNgpX0Evb/vio7nPMmj5qujkpQgSaPd1UcVqciHFDNZpOcGlcOPyi+AamCbIL9fitxAGeFN2Dl+3vZubm5u/4fH4Bd14HhIPdwZPAAAAAElFTkSuQmCC
```
出力:  

```
{
    "UICustomization": {
        "UserPoolId": "us-west-2_ywDJHlIfU",
        "ClientId": "14pq32c5q2uq2q7keorloqvb23",
        "ImageUrl": "https://cf.thewrong.club/14pq32c5q2uq2q7keorloqvb23/20250117005911/assets/images/image.jpg",
        "CSS": ".logo-customizable {\n\tmax-width: 60%;\n\tmax-height: 30%;\n}\n.banner-customizable {\n\tpadding: 25px 0px 25px 0px;\n\tbackground-color: lightgray;\n}\n.label-customizable {\n\tfont-weight: 400;\n}\n.textDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.idpDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.legalText-customizable {\n\tcolor: #747474;\n\tfont-size: 11px;\n}\n.submitButton-customizable {\n\tfont-size: 11px;\n\tfont-weight: normal;\n\tmargin: 20px -15px 10px -13px;\n\theight: 40px;\n\twidth: 108%;\n\tcolor: #fff;\n\tbackground-color: #337ab7;\n\ttext-align: center;\n}\n.submitButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #286090;\n}\n.errorMessage-customizable {\n\tpadding: 5px;\n\tfont-size: 14px;\n\twidth: 100%;\n\tbackground: #F5F5F5;\n\tborder: 2px solid #D64958;\n\tcolor: #D64958;\n}\n.inputField-customizable {\n\twidth: 100%;\n\theight: 34px;\n\tcolor: #555;\n\tbackground-color: #fff;\n\tborder: 1px solid #ccc;\n\tborder-radius: 0px;\n}\n.inputField-customizable:focus {\n\tborder-color: #66afe9;\n\toutline: 0;\n}\n.idpButton-customizable {\n\theight: 40px;\n\twidth: 100%;\n\twidth: 100%;\n\ttext-align: center;\n\tmargin-bottom: 15px;\n\tcolor: #fff;\n\tbackground-color: #5bc0de;\n\tborder-color: #46b8da;\n}\n.idpButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #31b0d5;\n}\n.socialButton-customizable {\n\tborder-radius: 2px;\n\theight: 40px;\n\tmargin-bottom: 15px;\n\tpadding: 1px;\n\ttext-align: left;\n\twidth: 100%;\n}\n.redirect-customizable {\n\ttext-align: center;\n}\n.passwordCheck-notValid-customizable {\n\tcolor: #DF3312;\n}\n.passwordCheck-valid-customizable {\n\tcolor: #19BF00;\n}\n.background-customizable {\n\tbackground-color: #fff;\n}\n",
        "CSSVersion": "20250117005911"
    }
}
```
**例 2: すべてのアプリクライアントのデフォルトの UI カスタマイズを設定するには**  
次の `set-ui-customization` の例では、クライアント固有の設定を持たないすべてのアプリクライアントに対して、リクエストされたユーザープールを設定します。このコマンドは、いくつかのカスタム CSS を適用し、Amazon Cognito ロゴをアプリケーションロゴとして使用します。  

```
aws cognito-idp set-ui-customization \
--user-pool-id us-west-2_ywDJHlIfU \
--client-id ALL \
--css ".logo-customizable {\n\tmax-width: 60%;\n\tmax-height: 30%;\n}\n.banner-customizable {\n\tpadding: 25px 0px 25px 0px;\n\tbackground-color: lightgray;\n}\n.label-customizable {\n\tfont-weight: 400;\n}\n.textDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.idpDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.legalText-customizable {\n\tcolor: #747474;\n\tfont-size: 11px;\n}\n.submitButton-customizable {\n\tfont-size: 11px;\n\tfont-weight: normal;\n\tmargin: 20px -15px 10px -13px;\n\theight: 40px;\n\twidth: 108%;\n\tcolor: #fff;\n\tbackground-color: #337ab7;\n\ttext-align: center;\n}\n.submitButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #286090;\n}\n.errorMessage-customizable {\n\tpadding: 5px;\n\tfont-size: 14px;\n\twidth: 100%;\n\tbackground: #F5F5F5;\n\tborder: 2px solid #D64958;\n\tcolor: #D64958;\n}\n.inputField-customizable {\n\twidth: 100%;\n\theight: 34px;\n\tcolor: #555;\n\tbackground-color: #fff;\n\tborder: 1px solid #ccc;\n\tborder-radius: 0px;\n}\n.inputField-customizable:focus {\n\tborder-color: #66afe9;\n\toutline: 0;\n}\n.idpButton-customizable {\n\theight: 40px;\n\twidth: 100%;\n\twidth: 100%;\n\ttext-align: center;\n\tmargin-bottom: 15px;\n\tcolor: #fff;\n\tbackground-color: #5bc0de;\n\tborder-color: #46b8da;\n}\n.idpButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #31b0d5;\n}\n.socialButton-customizable {\n\tborder-radius: 2px;\n\theight: 40px;\n\tmargin-bottom: 15px;\n\tpadding: 1px;\n\ttext-align: left;\n\twidth: 100%;\n}\n.redirect-customizable {\n\ttext-align: center;\n}\n.passwordCheck-notValid-customizable {\n\tcolor: #DF3312;\n}\n.passwordCheck-valid-customizable {\n\tcolor: #19BF00;\n}\n.background-customizable {\n\tbackground-color: #fff;\n}\n" \
--image-file iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAMAAAC5zwKfAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAA2UExURd00TN9BV/Cmsfvm6f3y9P////fM0uqAj+yNmu6ZpvnZ3eNabuFNYuZneehzhPKzvPTAxwAAAOiMMlkAAAASdFJOU///////////////////////AOK/vxIAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAKDSURBVFhH7ZfpkoMgEISDHKuEw/d/2u2BQWMiBrG29o+fVsKatdPMAeZxc3Nz8w+ISekzmB++sYIw/I/tjHzrPpO2Tx62EbR2PNxFac+jVuKxRaV50IzXkUe76NOCoUuwlvnQKei02gNF0ykotOLRBq/nboeWRxAISx2EbsHFoRhK6Igk2JJlwScfQjgt06dOaWWiTbEDAe/iq8N9kqCw2uCbHkHlYkaXEF8EYeL9RDqT4FhC6XMIIEifdcUwCc4leNyhabadWU6OlKYJE1Oac3NSPhB5rlaXlSgmr/1lww4nPaU/1ylfLGxX1r6Y66ZZkCqvnOlqKWws59ELj7fULc2CubwySYkdDuuiY0/F0L6Q5pZiSG0SfZTSTCOUhxOCH1AdIoCpTTIjtd+VpEjUDDytQH/0Fpc661Aisas/4qmyUItD557pSCOSQQzlx27J+meyDGc5zZgfhWuXE1lGgmVOMwmWdeGdzhjqZV14x5vSj7vsC5JDz/Cl0Vhp56n2NQt1wQIpury1EPbwyaYm+IhmAQKoajkH51wg4cMZ1wQ3QG9efKWWOaDhYWnU6jXjCMdRmm21PArI+Pb5DYoH93hq0ZCPlxeGJho/DI15C6sQc/L2sTC47UFBKZGHT6k+zlXg7WebA0Nr0HTcLMfk/Y4Rc65D3iG6WDd7YLSlVqk87bVhUwhnClrx11RsVQwlAA818Mn+QEs71BhSFU6orsUfKhHp72XMGYXi4q9c64RXRvzkWurRfG2vI2be/VaNcNgpX0Evb/vio7nPMmj5qujkpQgSaPd1UcVqciHFDNZpOcGlcOPyi+AamCbIL9fitxAGeFN2Dl+3vZubm5u/4fH4Bd14HhIPdwZPAAAAAElFTkSuQmCC
```
出力:  

```
{
    "UICustomization": {
        "UserPoolId": "us-west-2_ywDJHlIfU",
        "ClientId": "14pq32c5q2uq2q7keorloqvb23",
        "ImageUrl": "https://cf.thewrong.club/14pq32c5q2uq2q7keorloqvb23/20250117005911/assets/images/image.jpg",
        "CSS": ".logo-customizable {\n\tmax-width: 60%;\n\tmax-height: 30%;\n}\n.banner-customizable {\n\tpadding: 25px 0px 25px 0px;\n\tbackground-color: lightgray;\n}\n.label-customizable {\n\tfont-weight: 400;\n}\n.textDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.idpDescription-customizable {\n\tpadding-top: 10px;\n\tpadding-bottom: 10px;\n\tdisplay: block;\n\tfont-size: 16px;\n}\n.legalText-customizable {\n\tcolor: #747474;\n\tfont-size: 11px;\n}\n.submitButton-customizable {\n\tfont-size: 11px;\n\tfont-weight: normal;\n\tmargin: 20px -15px 10px -13px;\n\theight: 40px;\n\twidth: 108%;\n\tcolor: #fff;\n\tbackground-color: #337ab7;\n\ttext-align: center;\n}\n.submitButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #286090;\n}\n.errorMessage-customizable {\n\tpadding: 5px;\n\tfont-size: 14px;\n\twidth: 100%;\n\tbackground: #F5F5F5;\n\tborder: 2px solid #D64958;\n\tcolor: #D64958;\n}\n.inputField-customizable {\n\twidth: 100%;\n\theight: 34px;\n\tcolor: #555;\n\tbackground-color: #fff;\n\tborder: 1px solid #ccc;\n\tborder-radius: 0px;\n}\n.inputField-customizable:focus {\n\tborder-color: #66afe9;\n\toutline: 0;\n}\n.idpButton-customizable {\n\theight: 40px;\n\twidth: 100%;\n\twidth: 100%;\n\ttext-align: center;\n\tmargin-bottom: 15px;\n\tcolor: #fff;\n\tbackground-color: #5bc0de;\n\tborder-color: #46b8da;\n}\n.idpButton-customizable:hover {\n\tcolor: #fff;\n\tbackground-color: #31b0d5;\n}\n.socialButton-customizable {\n\tborder-radius: 2px;\n\theight: 40px;\n\tmargin-bottom: 15px;\n\tpadding: 1px;\n\ttext-align: left;\n\twidth: 100%;\n}\n.redirect-customizable {\n\ttext-align: center;\n}\n.passwordCheck-notValid-customizable {\n\tcolor: #DF3312;\n}\n.passwordCheck-valid-customizable {\n\tcolor: #19BF00;\n}\n.background-customizable {\n\tbackground-color: #fff;\n}\n",
        "CSSVersion": "20250117005911"
    }
}
```
詳細については、*Amazon Cognito デベロッパーガイド*」の「[Hosted UI (classic) branding](https://docs.aws.amazon.com/cognito/latest/developerguide/hosted-ui-classic-branding.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetUiCustomization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/set-ui-customization.html)」を参照してください。

### `set-user-mfa-preference`
<a name="cognito-identity-provider_SetUserMfaPreference_cli_2_topic"></a>

次のコード例は、`set-user-mfa-preference` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの MFA を設定するには**  
次の `set-user-mfa-preference` の例では、TOTP MFA を使用するように現在のユーザーを設定し、他のすべての MFA 要因を無効にします。  

```
aws cognito-idp set-user-mfa-preference \
    --access-token eyJra456defEXAMPLE \
    --software-token-mfa-settings Enabled=true,PreferredMfa=true \
    --sms-mfa-settings Enabled=false,PreferredMfa=false \
    --email-mfa-settings Enabled=false,PreferredMfa=false
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Adding MFA](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetUserMfaPreference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/set-user-mfa-preference.html)」を参照してください。

### `set-user-pool-mfa-config`
<a name="cognito-identity-provider_SetUserPoolMfaConfig_cli_2_topic"></a>

次のコード例は、`set-user-pool-mfa-config` を使用する方法を示しています。

**AWS CLI**  
**ユーザープール MFA と WebAuthn を設定するには**  
次の `set-user-pool-mfa-config` の例では、使用可能なすべての MFA メソッドでオプションの MFA を使用して、リクエストされたユーザープールを設定し、WebAuthn の構成を設定します。  

```
aws cognito-idp set-user-pool-mfa-config \
    --user-pool-id us-west-2_EXAMPLE \
    --sms-mfa-configuration "SmsAuthenticationMessage=\"Your OTP for MFA or sign-in: use {####}.\",SmsConfiguration={SnsCallerArn=arn:aws:iam::123456789012:role/service-role/test-SMS-Role,ExternalId=a1b2c3d4-5678-90ab-cdef-EXAMPLE11111,SnsRegion=us-west-2}" \
    --software-token-mfa-configuration Enabled=true \
    --email-mfa-configuration "Message=\"Your OTP for MFA or sign-in: use {####}\",Subject=\"OTP test\"" \
    --mfa-configuration OPTIONAL \
    --web-authn-configuration RelyingPartyId=auth.example.com,UserVerification=preferred
```
出力:  

```
{
    "EmailMfaConfiguration": {
        "Message": "Your OTP for MFA or sign-in: use {####}",
        "Subject": "OTP test"
    },
    "MfaConfiguration": "OPTIONAL",
    "SmsMfaConfiguration": {
        "SmsAuthenticationMessage": "Your OTP for MFA or sign-in: use {####}.",
        "SmsConfiguration": {
            "ExternalId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "SnsCallerArn": "arn:aws:iam::123456789012:role/service-role/test-SMS-Role",
            "SnsRegion": "us-west-2"
        }
    },
    "SoftwareTokenMfaConfiguration": {
        "Enabled": true
    },
    "WebAuthnConfiguration": {
        "RelyingPartyId": "auth.example.com",
        "UserVerification": "preferred"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Adding MFA](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html)」と「[Passkey sign-in](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html#amazon-cognito-user-pools-authentication-flow-methods-passkey)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetUserPoolMfaConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/set-user-pool-mfa-config.html)」を参照してください。

### `set-user-settings`
<a name="cognito-identity-provider_SetUserSettings_cli_2_topic"></a>

次のコード例は、`set-user-settings` を使用する方法を示しています。

**AWS CLI**  
**ユーザー設定を行うには**  
この例では、MFA 配信設定を EMAIL に設定しています。  
コマンド:  

```
aws cognito-idp set-user-settings --access-token ACCESS_TOKEN --mfa-options DeliveryMedium=EMAIL
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetUserSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/set-user-settings.html)」を参照してください。

### `sign-up`
<a name="cognito-identity-provider_SignUp_cli_2_topic"></a>

次のコード例は、`sign-up` を使用する方法を示しています。

**AWS CLI**  
**ユーザーをサインアップするには**  
この例では jane@example.com をサインアップします。  
コマンド:  

```
aws cognito-idp sign-up --client-id 3n4b5urk1ft4fl3mg5e62d9ado --username jane@example.com --password PASSWORD --user-attributes Name="email",Value="jane@example.com" Name="name",Value="Jane"
```
出力:  

```
{
  "UserConfirmed": false,
  "UserSub": "e04d60a6-45dc-441c-a40b-e25a787d4862"
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[SignUp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/sign-up.html)」を参照してください。**

### `start-user-import-job`
<a name="cognito-identity-provider_StartUserImportJob_cli_2_topic"></a>

次のコード例は、`start-user-import-job` を使用する方法を示しています。

**AWS CLI**  
**インポートジョブを開始するには**  
次の `start-user-import-job` の例では、リクエストされたユーザープールで、リクエストされたインポートジョブを開始します。  

```
aws cognito-idp start-user-import-job \
    --user-pool-id us-west-2_EXAMPLE \
    --job-id import-mAgUtd8PMm
```
出力:  

```
{
    "UserImportJob": {
        "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/example-cloudwatch-logs-role",
        "CreationDate": 1736442975.904,
        "FailedUsers": 0,
        "ImportedUsers": 0,
        "JobId": "import-mAgUtd8PMm",
        "JobName": "Customer import",
        "PreSignedUrl": "https://aws-cognito-idp-user-import-pdx.s3.us-west-2.amazonaws.com/123456789012/us-west-2_EXAMPLE/import-mAgUtd8PMm?X-Amz-Security-Token=[token]&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20241226T193341Z&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption&X-Amz-Expires=899&X-Amz-Credential=[credential]&X-Amz-Signature=[signature]",
        "SkippedUsers": 0,
        "StartDate": 1736443020.081,
        "Status": "Pending",
        "UserPoolId": "us-west-2_EXAMPLE"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Importing users into a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartUserImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/start-user-import-job.html)」を参照してください。

### `start-web-authn-registration`
<a name="cognito-identity-provider_StartWebAuthnRegistration_cli_2_topic"></a>

次のコード例は、`start-web-authn-registration` を使用する方法を示しています。

**AWS CLI**  
**サインインしたユーザーのパスキー登録情報を取得するには**  
次の `start-web-authn-registration` の例では、現在のユーザーの WebAuthn 登録オプションを生成します。  

```
aws cognito-idp start-web-authn-registration \
    --access-token eyJra456defEXAMPLE
```
出力:  

```
{
    "CredentialCreationOptions": {
        "authenticatorSelection": {
            "requireResidentKey": true,
            "residentKey": "required",
            "userVerification": "preferred"
        },
        "challenge": "wxvbDicyqQqvF2EXAMPLE",
        "excludeCredentials": [
            {
                "id": "8LApgk4-lNUFHbhm2w6Und7-uxcc8coJGsPxiogvHoItc64xWQc3r4CEXAMPLE",
                "type": "public-key"
            }
        ],
        "pubKeyCredParams": [
            {
                "alg": -7,
                "type": "public-key"
            },
            {
                "alg": -257,
                "type": "public-key"
            }
        ],
        "rp": {
            "id": "auth.example.com",
            "name": "auth.example.com"
        },
        "timeout": 60000,
        "user": {
            "displayName": "testuser",
            "id": "ZWFhZDAyMTktMjExNy00MzlmLThkNDYtNGRiMjBlNEXAMPLE",
            "name": "testuser"
        }
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Passkey sign-in](https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow-methods.html#amazon-cognito-user-pools-authentication-flow-methods-passkey)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartWebAuthnRegistration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/start-web-authn-registration.html)」を参照してください。

### `stop-user-import-job`
<a name="cognito-identity-provider_StopUserImportJob_cli_2_topic"></a>

次のコード例は、`stop-user-import-job` を使用する方法を示しています。

**AWS CLI**  
**インポートジョブを停止するには**  
次の `stop-user-import-job` の例では、リクエストされたユーザープールで、リクエストされた実行中のユーザーインポートジョブを停止します。  

```
aws cognito-idp stop-user-import-job \
    --user-pool-id us-west-2_EXAMPLE \
    --job-id import-mAgUtd8PMm
```
出力:  

```
{
    "UserImportJob": {
        "CloudWatchLogsRoleArn": "arn:aws:iam::123456789012:role/example-cloudwatch-logs-role",
        "CompletionDate": 1736443496.379,
        "CompletionMessage": "The Import Job was stopped by the developer.",
        "CreationDate": 1736443471.781,
        "FailedUsers": 0,
        "ImportedUsers": 0,
        "JobId": "import-mAgUtd8PMm",
        "JobName": "Customer import",
        "PreSignedUrl": "https://aws-cognito-idp-user-import-pdx.s3.us-west-2.amazonaws.com/123456789012/us-west-2_EXAMPLE/import-mAgUtd8PMm?X-Amz-Security-Token=[token]&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20241226T193341Z&X-Amz-SignedHeaders=host%3Bx-amz-server-side-encryption&X-Amz-Expires=899&X-Amz-Credential=[credential]&X-Amz-Signature=[signature]",
        "SkippedUsers": 0,
        "StartDate": 1736443494.154,
        "Status": "Stopped",
        "UserPoolId": "us-west-2_EXAMPLE"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Importing users into a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-using-import-tool.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopUserImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/stop-user-import-job.html)」を参照してください。

### `tag-resource`
<a name="cognito-identity-provider_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールにタグ付けするには**  
次の `tag-resource` の例では、リクエストされたユーザープールに `administrator` および `department` タグを適用します。  

```
aws cognito-idp tag-resource \
    --resource-arn arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_EXAMPLE \
    --tags administrator=Jie,tenant=ExampleCorp
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Tagging Amazon Cognito resources](https://docs.aws.amazon.com/cognito/latest/developerguide/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="cognito-identity-provider_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールからタグを削除するには**  
次の `untag-resource` の例では、リクエストされたユーザープールから `administrator` および `department` タグを削除します。  

```
aws cognito-idp untag-resource \
    --resource-arn arn:aws:cognito-idp:us-west-2:767671399759:userpool/us-west-2_l5cxwdm2K \
    --tag-keys administrator tenant
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Tagging Amazon Cognito resources](https://docs.aws.amazon.com/cognito/latest/developerguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/untag-resource.html)」を参照してください。

### `update-auth-event-feedback`
<a name="cognito-identity-provider_UpdateAuthEventFeedback_cli_2_topic"></a>

次のコード例は、`update-auth-event-feedback` を使用する方法を示しています。

**AWS CLI**  
**認証イベントフィードバックを更新するには**  
この例では、認証イベントフィードバックを更新しています。イベント「Valid」をマークします。  
コマンド:  

```
aws cognito-idp update-auth-event-feedback --user-pool-id us-west-2_aaaaaaaaa --username diego@example.com --event-id EVENT_ID --feedback-token FEEDBACK_TOKEN --feedback-value "Valid"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAuthEventFeedback](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-auth-event-feedback.html)」を参照してください。

### `update-device-status`
<a name="cognito-identity-provider_UpdateDeviceStatus_cli_2_topic"></a>

次のコード例は、`update-device-status` を使用する方法を示しています。

**AWS CLI**  
**デバイスステータスを更新するには**  
この例では、デバイスのステータスを「not\$1remembered」に更新しています。  
コマンド:  

```
aws cognito-idp update-device-status --access-token ACCESS_TOKEN --device-key DEVICE_KEY --device-remembered-status "not_remembered"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDeviceStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-device-status.html)」を参照してください。

### `update-group`
<a name="cognito-identity-provider_UpdateGroup_cli_2_topic"></a>

次のコード例は、`update-group` を使用する方法を示しています。

**AWS CLI**  
**グループを更新するには**  
この例では、MyGroup の説明と優先順位を更新しています。  
コマンド:  

```
aws cognito-idp update-group --user-pool-id us-west-2_aaaaaaaaa --group-name MyGroup --description "New description" --precedence 2
```
出力:  

```
{
  "Group": {
      "GroupName": "MyGroup",
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "Description": "New description",
      "RoleArn": "arn:aws:iam::111111111111:role/MyRole",
      "Precedence": 2,
      "LastModifiedDate": 1548800862.812,
      "CreationDate": 1548097827.125
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-group.html)」を参照してください。

### `update-identity-provider`
<a name="cognito-identity-provider_UpdateIdentityProvider_cli_2_topic"></a>

次のコード例は、`update-identity-provider` を使用する方法を示しています。

**AWS CLI**  
**ユーザープール ID プロバイダーを更新するには**  
次の `update-identity-provider` の例では、リクエストされたユーザープールの OIDC プロバイダー「MyOIDCIdP」を更新します。  

```
aws cognito-idp update-identity-provider \
    --cli-input-json file://update-identity-provider.json
```
`update-identity-provider.json` の内容:  

```
{
   "AttributeMapping": {
            "email": "idp_email",
            "email_verified": "idp_email_verified",
            "username": "sub"
    },
    "CreationDate": 1.701129701653E9,
    "IdpIdentifiers": [
        "corp",
        "dev"
    ],
    "LastModifiedDate": 1.701129701653E9,
    "ProviderDetails": {
        "attributes_request_method": "GET",
        "attributes_url": "https://example.com/userInfo",
        "attributes_url_add_attributes": "false",
        "authorize_scopes": "openid profile",
        "authorize_url": "https://example.com/authorize",
        "client_id": "idpexampleclient123",
        "client_secret": "idpexamplesecret456",
        "jwks_uri": "https://example.com/.well-known/jwks.json",
        "oidc_issuer": "https://example.com",
        "token_url": "https://example.com/token"
    },
    "ProviderName": "MyOIDCIdP",
    "UserPoolId": "us-west-2_EXAMPLE"
}
```
出力:  

```
{
    "IdentityProvider": {
        "AttributeMapping": {
            "email": "idp_email",
            "email_verified": "idp_email_verified",
            "username": "sub"
        },
        "CreationDate": 1701129701.653,
        "IdpIdentifiers": [
            "corp",
            "dev"
        ],
        "LastModifiedDate": 1736444278.211,
        "ProviderDetails": {
            "attributes_request_method": "GET",
            "attributes_url": "https://example.com/userInfo",
            "attributes_url_add_attributes": "false",
            "authorize_scopes": "openid profile",
            "authorize_url": "https://example.com/authorize",
            "client_id": "idpexampleclient123",
            "client_secret": "idpexamplesecret456",
            "jwks_uri": "https://example.com/.well-known/jwks.json",
            "oidc_issuer": "https://example.com",
            "token_url": "https://example.com/token"
        },
        "ProviderName": "MyOIDCIdP",
        "ProviderType": "OIDC",
        "UserPoolId": "us-west-2_EXAMPLE"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Configuring a domain](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIdentityProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-identity-provider.html)」を参照してください。

### `update-managed-login-branding`
<a name="cognito-identity-provider_UpdateManagedLoginBranding_cli_2_topic"></a>

次のコード例は、`update-managed-login-branding` を使用する方法を示しています。

**AWS CLI**  
**マネージドログインブランディングのスタイルを更新するには**  
次の `update-managed-login-branding` の例では、リクエストされたアプリケーションクライアントブランドディングのスタイルを更新します。  

```
aws cognito-idp update-managed-login-branding \
    --cli-input-json file://update-managed-login-branding.json
```
`update-managed-login-branding.json` の内容:  

```
{
    "Assets": [
        {
            "Bytes": "PHN2ZyB3aWR0aD0iMjAwMDAiIGhlaWdodD0iNDAwIiB2aWV3Qm94PSIwIDAgMjAwMDAgNDAwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8ZyBjbGlwLXBhdGg9InVybCgjY2xpcDBfMTcyNTlfMjM2Njc0KSI+CjxyZWN0IHdpZHRoPSIyMDAwMCIgaGVpZ2h0PSI0MDAiIGZpbGw9InVybCgjcGFpbnQwX2xpbmVhcl8xNzI1OV8yMzY2NzQpIi8+CjxwYXRoIGQ9Ik0wIDBIMjAwMDBWNDAwSDBWMFoiIGZpbGw9IiMxMjIwMzciIGZpbGwtb3BhY2l0eT0iMC41Ii8+CjwvZz4KPGRlZnM+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQwX2xpbmVhcl8xNzI1OV8yMzY2NzQiIHgxPSItODk0LjI0OSIgeTE9IjE5OS45MzEiIHgyPSIxODAzNC41IiB5Mj0iLTU4OTkuNTciIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0JGODBGRiIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGRjhGQUIiLz4KPC9saW5lYXJHcmFkaWVudD4KPGNsaXBQYXRoIGlkPSJjbGlwMF8xNzI1OV8yMzY2NzQiPgo8cmVjdCB3aWR0aD0iMjAwMDAiIGhlaWdodD0iNDAwIiBmaWxsPSJ3aGl0ZSIvPgo8L2NsaXBQYXRoPgo8L2RlZnM+Cjwvc3ZnPgo=",
            "Category": "PAGE_FOOTER_BACKGROUND",
            "ColorMode": "DARK",
            "Extension": "SVG"
        }
    ],
    "ManagedLoginBrandingId": "63f30090-6b1f-4278-b885-2bbb81f8e545",
    "Settings": {
        "categories": {
            "auth": {
                "authMethodOrder": [
                    [
                        {
                            "display": "BUTTON",
                            "type": "FEDERATED"
                        },
                        {
                            "display": "INPUT",
                            "type": "USERNAME_PASSWORD"
                        }
                    ]
                ],
                "federation": {
                    "interfaceStyle": "BUTTON_LIST",
                    "order": [
                    ]
                }
            },
            "form": {
                "displayGraphics": true,
                "instructions": {
                    "enabled": false
                },
                "languageSelector": {
                    "enabled": false
                },
                "location": {
                    "horizontal": "CENTER",
                    "vertical": "CENTER"
                },
                "sessionTimerDisplay": "NONE"
            },
            "global": {
                "colorSchemeMode": "LIGHT",
                "pageFooter": {
                    "enabled": false
                },
                "pageHeader": {
                    "enabled": false
                },
                "spacingDensity": "REGULAR"
            },
            "signUp": {
                "acceptanceElements": [
                    {
                        "enforcement": "NONE",
                        "textKey": "en"
                    }
                ]
            }
        },
        "componentClasses": {
            "buttons": {
                "borderRadius": 8.0
            },
            "divider": {
                "darkMode": {
                    "borderColor": "232b37ff"
                },
                "lightMode": {
                    "borderColor": "ebebf0ff"
                }
            },
            "dropDown": {
                "borderRadius": 8.0,
                "darkMode": {
                    "defaults": {
                        "itemBackgroundColor": "192534ff"
                    },
                    "hover": {
                        "itemBackgroundColor": "081120ff",
                        "itemBorderColor": "5f6b7aff",
                        "itemTextColor": "e9ebedff"
                    },
                    "match": {
                        "itemBackgroundColor": "d1d5dbff",
                        "itemTextColor": "89bdeeff"
                    }
                },
                "lightMode": {
                    "defaults": {
                        "itemBackgroundColor": "ffffffff"
                    },
                    "hover": {
                        "itemBackgroundColor": "f4f4f4ff",
                        "itemBorderColor": "7d8998ff",
                        "itemTextColor": "000716ff"
                    },
                    "match": {
                        "itemBackgroundColor": "414d5cff",
                        "itemTextColor": "0972d3ff"
                    }
                }
            },
            "focusState": {
                "darkMode": {
                    "borderColor": "539fe5ff"
                },
                "lightMode": {
                    "borderColor": "0972d3ff"
                }
            },
            "idpButtons": {
                "icons": {
                    "enabled": true
                }
            },
            "input": {
                "borderRadius": 8.0,
                "darkMode": {
                    "defaults": {
                        "backgroundColor": "0f1b2aff",
                        "borderColor": "5f6b7aff"
                    },
                    "placeholderColor": "8d99a8ff"
                },
                "lightMode": {
                    "defaults": {
                        "backgroundColor": "ffffffff",
                        "borderColor": "7d8998ff"
                    },
                    "placeholderColor": "5f6b7aff"
                }
            },
            "inputDescription": {
                "darkMode": {
                    "textColor": "8d99a8ff"
                },
                "lightMode": {
                    "textColor": "5f6b7aff"
                }
            },
            "inputLabel": {
                "darkMode": {
                    "textColor": "d1d5dbff"
                },
                "lightMode": {
                    "textColor": "000716ff"
                }
            },
            "link": {
                "darkMode": {
                    "defaults": {
                        "textColor": "539fe5ff"
                    },
                    "hover": {
                        "textColor": "89bdeeff"
                    }
                },
                "lightMode": {
                    "defaults": {
                        "textColor": "0972d3ff"
                    },
                    "hover": {
                        "textColor": "033160ff"
                    }
                }
            },
            "optionControls": {
                "darkMode": {
                    "defaults": {
                        "backgroundColor": "0f1b2aff",
                        "borderColor": "7d8998ff"
                    },
                    "selected": {
                        "backgroundColor": "539fe5ff",
                        "foregroundColor": "000716ff"
                    }
                },
                "lightMode": {
                    "defaults": {
                        "backgroundColor": "ffffffff",
                        "borderColor": "7d8998ff"
                    },
                    "selected": {
                        "backgroundColor": "0972d3ff",
                        "foregroundColor": "ffffffff"
                    }
                }
            },
            "statusIndicator": {
                "darkMode": {
                    "error": {
                        "backgroundColor": "1a0000ff",
                        "borderColor": "eb6f6fff",
                        "indicatorColor": "eb6f6fff"
                    },
                    "pending": {
                        "indicatorColor": "AAAAAAAA"
                    },
                    "success": {
                        "backgroundColor": "001a02ff",
                        "borderColor": "29ad32ff",
                        "indicatorColor": "29ad32ff"
                    },
                    "warning": {
                        "backgroundColor": "1d1906ff",
                        "borderColor": "e0ca57ff",
                        "indicatorColor": "e0ca57ff"
                    }
                },
                "lightMode": {
                    "error": {
                        "backgroundColor": "fff7f7ff",
                        "borderColor": "d91515ff",
                        "indicatorColor": "d91515ff"
                    },
                    "pending": {
                        "indicatorColor": "AAAAAAAA"
                    },
                    "success": {
                        "backgroundColor": "f2fcf3ff",
                        "borderColor": "037f0cff",
                        "indicatorColor": "037f0cff"
                    },
                    "warning": {
                        "backgroundColor": "fffce9ff",
                        "borderColor": "8d6605ff",
                        "indicatorColor": "8d6605ff"
                    }
                }
            }
        },
        "components": {
            "alert": {
                "borderRadius": 12.0,
                "darkMode": {
                    "error": {
                        "backgroundColor": "1a0000ff",
                        "borderColor": "eb6f6fff"
                    }
                },
                "lightMode": {
                    "error": {
                        "backgroundColor": "fff7f7ff",
                        "borderColor": "d91515ff"
                    }
                }
            },
            "favicon": {
                "enabledTypes": [
                    "ICO",
                    "SVG"
                ]
            },
            "form": {
                "backgroundImage": {
                    "enabled": false
                },
                "borderRadius": 8.0,
                "darkMode": {
                    "backgroundColor": "0f1b2aff",
                    "borderColor": "424650ff"
                },
                "lightMode": {
                    "backgroundColor": "ffffffff",
                    "borderColor": "c6c6cdff"
                },
                "logo": {
                    "enabled": false,
                    "formInclusion": "IN",
                    "location": "CENTER",
                    "position": "TOP"
                }
            },
            "idpButton": {
                "custom": {
                },
                "standard": {
                    "darkMode": {
                        "active": {
                            "backgroundColor": "354150ff",
                            "borderColor": "89bdeeff",
                            "textColor": "89bdeeff"
                        },
                        "defaults": {
                            "backgroundColor": "0f1b2aff",
                            "borderColor": "c6c6cdff",
                            "textColor": "c6c6cdff"
                        },
                        "hover": {
                            "backgroundColor": "192534ff",
                            "borderColor": "89bdeeff",
                            "textColor": "89bdeeff"
                        }
                    },
                    "lightMode": {
                        "active": {
                            "backgroundColor": "d3e7f9ff",
                            "borderColor": "033160ff",
                            "textColor": "033160ff"
                        },
                        "defaults": {
                            "backgroundColor": "ffffffff",
                            "borderColor": "424650ff",
                            "textColor": "424650ff"
                        },
                        "hover": {
                            "backgroundColor": "f2f8fdff",
                            "borderColor": "033160ff",
                            "textColor": "033160ff"
                        }
                    }
                }
            },
            "pageBackground": {
                "darkMode": {
                    "color": "0f1b2aff"
                },
                "image": {
                    "enabled": true
                },
                "lightMode": {
                    "color": "ffffffff"
                }
            },
            "pageFooter": {
                "backgroundImage": {
                    "enabled": false
                },
                "darkMode": {
                    "background": {
                        "color": "0f141aff"
                    },
                    "borderColor": "424650ff"
                },
                "lightMode": {
                    "background": {
                        "color": "fafafaff"
                    },
                    "borderColor": "d5dbdbff"
                },
                "logo": {
                    "enabled": false,
                    "location": "START"
                }
            },
            "pageHeader": {
                "backgroundImage": {
                    "enabled": false
                },
                "darkMode": {
                    "background": {
                        "color": "0f141aff"
                    },
                    "borderColor": "424650ff"
                },
                "lightMode": {
                    "background": {
                        "color": "fafafaff"
                    },
                    "borderColor": "d5dbdbff"
                },
                "logo": {
                    "enabled": false,
                    "location": "START"
                }
            },
            "pageText": {
                "darkMode": {
                    "bodyColor": "b6bec9ff",
                    "descriptionColor": "b6bec9ff",
                    "headingColor": "d1d5dbff"
                },
                "lightMode": {
                    "bodyColor": "414d5cff",
                    "descriptionColor": "414d5cff",
                    "headingColor": "000716ff"
                }
            },
            "phoneNumberSelector": {
                "displayType": "TEXT"
            },
            "primaryButton": {
                "darkMode": {
                    "active": {
                        "backgroundColor": "539fe5ff",
                        "textColor": "000716ff"
                    },
                    "defaults": {
                        "backgroundColor": "539fe5ff",
                        "textColor": "000716ff"
                    },
                    "disabled": {
                        "backgroundColor": "ffffffff",
                        "borderColor": "ffffffff"
                    },
                    "hover": {
                        "backgroundColor": "89bdeeff",
                        "textColor": "000716ff"
                    }
                },
                "lightMode": {
                    "active": {
                        "backgroundColor": "033160ff",
                        "textColor": "ffffffff"
                    },
                    "defaults": {
                        "backgroundColor": "0972d3ff",
                        "textColor": "ffffffff"
                    },
                    "disabled": {
                        "backgroundColor": "ffffffff",
                        "borderColor": "ffffffff"
                    },
                    "hover": {
                        "backgroundColor": "033160ff",
                        "textColor": "ffffffff"
                    }
                }
            },
            "secondaryButton": {
                "darkMode": {
                    "active": {
                        "backgroundColor": "354150ff",
                        "borderColor": "89bdeeff",
                        "textColor": "89bdeeff"
                    },
                    "defaults": {
                        "backgroundColor": "0f1b2aff",
                        "borderColor": "539fe5ff",
                        "textColor": "539fe5ff"
                    },
                    "hover": {
                        "backgroundColor": "192534ff",
                        "borderColor": "89bdeeff",
                        "textColor": "89bdeeff"
                    }
                },
                "lightMode": {
                    "active": {
                        "backgroundColor": "d3e7f9ff",
                        "borderColor": "033160ff",
                        "textColor": "033160ff"
                    },
                    "defaults": {
                        "backgroundColor": "ffffffff",
                        "borderColor": "0972d3ff",
                        "textColor": "0972d3ff"
                    },
                    "hover": {
                        "backgroundColor": "f2f8fdff",
                        "borderColor": "033160ff",
                        "textColor": "033160ff"
                    }
                }
            }
        }
    },
    "UseCognitoProvidedValues": false,
    "UserPoolId": "ca-central-1_EXAMPLE"
}
```
出力:  

```
{
    "ManagedLoginBranding": {
        "Assets": [
            {
                "Bytes": "PHN2ZyB3aWR0aD0iMjAwMDAiIGhlaWdodD0iNDAwIiB2aWV3Qm94PSIwIDAgMjAwMDAgNDAwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8ZyBjbGlwLXBhdGg9InVybCgjY2xpcDBfMTcyNTlfMjM2Njc0KSI+CjxyZWN0IHdpZHRoPSIyMDAwMCIgaGVpZ2h0PSI0MDAiIGZpbGw9InVybCgjcGFpbnQwX2xpbmVhcl8xNzI1OV8yMzY2NzQpIi8+CjxwYXRoIGQ9Ik0wIDBIMjAwMDBWNDAwSDBWMFoiIGZpbGw9IiMxMjIwMzciIGZpbGwtb3BhY2l0eT0iMC41Ii8+CjwvZz4KPGRlZnM+CjxsaW5lYXJHcmFkaWVudCBpZD0icGFpbnQwX2xpbmVhcl8xNzI1OV8yMzY2NzQiIHgxPSItODk0LjI0OSIgeTE9IjE5OS45MzEiIHgyPSIxODAzNC41IiB5Mj0iLTU4OTkuNTciIGdyYWRpZW50VW5pdHM9InVzZXJTcGFjZU9uVXNlIj4KPHN0b3Agc3RvcC1jb2xvcj0iI0JGODBGRiIvPgo8c3RvcCBvZmZzZXQ9IjEiIHN0b3AtY29sb3I9IiNGRjhGQUIiLz4KPC9saW5lYXJHcmFkaWVudD4KPGNsaXBQYXRoIGlkPSJjbGlwMF8xNzI1OV8yMzY2NzQiPgo8cmVjdCB3aWR0aD0iMjAwMDAiIGhlaWdodD0iNDAwIiBmaWxsPSJ3aGl0ZSIvPgo8L2NsaXBQYXRoPgo8L2RlZnM+Cjwvc3ZnPgo=",
                "Category": "PAGE_FOOTER_BACKGROUND",
                "ColorMode": "DARK",
                "Extension": "SVG"
            }
        ],
        "CreationDate": 1732138490.642,
        "LastModifiedDate": 1732140420.301,
        "ManagedLoginBrandingId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Settings": {
            "categories": {
                "auth": {
                    "authMethodOrder": [
                        [
                            {
                                "display": "BUTTON",
                                "type": "FEDERATED"
                            },
                            {
                                "display": "INPUT",
                                "type": "USERNAME_PASSWORD"
                            }
                        ]
                    ],
                    "federation": {
                        "interfaceStyle": "BUTTON_LIST",
                        "order": [
                        ]
                    }
                },
                "form": {
                    "displayGraphics": true,
                    "instructions": {
                        "enabled": false
                    },
                    "languageSelector": {
                        "enabled": false
                    },
                    "location": {
                        "horizontal": "CENTER",
                        "vertical": "CENTER"
                    },
                    "sessionTimerDisplay": "NONE"
                },
                "global": {
                    "colorSchemeMode": "LIGHT",
                    "pageFooter": {
                        "enabled": false
                    },
                    "pageHeader": {
                        "enabled": false
                    },
                    "spacingDensity": "REGULAR"
                },
                "signUp": {
                    "acceptanceElements": [
                        {
                            "enforcement": "NONE",
                            "textKey": "en"
                        }
                    ]
                }
            },
            "componentClasses": {
                "buttons": {
                    "borderRadius": 8.0
                },
                "divider": {
                    "darkMode": {
                        "borderColor": "232b37ff"
                    },
                    "lightMode": {
                        "borderColor": "ebebf0ff"
                    }
                },
                "dropDown": {
                    "borderRadius": 8.0,
                    "darkMode": {
                        "defaults": {
                            "itemBackgroundColor": "192534ff"
                        },
                        "hover": {
                            "itemBackgroundColor": "081120ff",
                            "itemBorderColor": "5f6b7aff",
                            "itemTextColor": "e9ebedff"
                        },
                        "match": {
                            "itemBackgroundColor": "d1d5dbff",
                            "itemTextColor": "89bdeeff"
                        }
                    },
                    "lightMode": {
                        "defaults": {
                            "itemBackgroundColor": "ffffffff"
                        },
                        "hover": {
                            "itemBackgroundColor": "f4f4f4ff",
                            "itemBorderColor": "7d8998ff",
                            "itemTextColor": "000716ff"
                        },
                        "match": {
                            "itemBackgroundColor": "414d5cff",
                            "itemTextColor": "0972d3ff"
                        }
                    }
                },
                "focusState": {
                    "darkMode": {
                        "borderColor": "539fe5ff"
                    },
                    "lightMode": {
                        "borderColor": "0972d3ff"
                    }
                },
                "idpButtons": {
                    "icons": {
                        "enabled": true
                    }
                },
                "input": {
                    "borderRadius": 8.0,
                    "darkMode": {
                        "defaults": {
                            "backgroundColor": "0f1b2aff",
                            "borderColor": "5f6b7aff"
                        },
                        "placeholderColor": "8d99a8ff"
                    },
                    "lightMode": {
                        "defaults": {
                            "backgroundColor": "ffffffff",
                            "borderColor": "7d8998ff"
                        },
                        "placeholderColor": "5f6b7aff"
                    }
                },
                "inputDescription": {
                    "darkMode": {
                        "textColor": "8d99a8ff"
                    },
                    "lightMode": {
                        "textColor": "5f6b7aff"
                    }
                },
                "inputLabel": {
                    "darkMode": {
                        "textColor": "d1d5dbff"
                    },
                    "lightMode": {
                        "textColor": "000716ff"
                    }
                },
                "link": {
                    "darkMode": {
                        "defaults": {
                            "textColor": "539fe5ff"
                        },
                        "hover": {
                            "textColor": "89bdeeff"
                        }
                    },
                    "lightMode": {
                        "defaults": {
                            "textColor": "0972d3ff"
                        },
                        "hover": {
                            "textColor": "033160ff"
                        }
                    }
                },
                "optionControls": {
                    "darkMode": {
                        "defaults": {
                            "backgroundColor": "0f1b2aff",
                            "borderColor": "7d8998ff"
                        },
                        "selected": {
                            "backgroundColor": "539fe5ff",
                            "foregroundColor": "000716ff"
                        }
                    },
                    "lightMode": {
                        "defaults": {
                            "backgroundColor": "ffffffff",
                            "borderColor": "7d8998ff"
                        },
                        "selected": {
                            "backgroundColor": "0972d3ff",
                            "foregroundColor": "ffffffff"
                        }
                    }
                },
                "statusIndicator": {
                    "darkMode": {
                        "error": {
                            "backgroundColor": "1a0000ff",
                            "borderColor": "eb6f6fff",
                            "indicatorColor": "eb6f6fff"
                        },
                        "pending": {
                            "indicatorColor": "AAAAAAAA"
                        },
                        "success": {
                            "backgroundColor": "001a02ff",
                            "borderColor": "29ad32ff",
                            "indicatorColor": "29ad32ff"
                        },
                        "warning": {
                            "backgroundColor": "1d1906ff",
                            "borderColor": "e0ca57ff",
                            "indicatorColor": "e0ca57ff"
                        }
                    },
                    "lightMode": {
                        "error": {
                            "backgroundColor": "fff7f7ff",
                            "borderColor": "d91515ff",
                            "indicatorColor": "d91515ff"
                        },
                        "pending": {
                            "indicatorColor": "AAAAAAAA"
                        },
                        "success": {
                            "backgroundColor": "f2fcf3ff",
                            "borderColor": "037f0cff",
                            "indicatorColor": "037f0cff"
                        },
                        "warning": {
                            "backgroundColor": "fffce9ff",
                            "borderColor": "8d6605ff",
                            "indicatorColor": "8d6605ff"
                        }
                    }
                }
            },
            "components": {
                "alert": {
                    "borderRadius": 12.0,
                    "darkMode": {
                        "error": {
                            "backgroundColor": "1a0000ff",
                            "borderColor": "eb6f6fff"
                        }
                    },
                    "lightMode": {
                        "error": {
                            "backgroundColor": "fff7f7ff",
                            "borderColor": "d91515ff"
                        }
                    }
                },
                "favicon": {
                    "enabledTypes": [
                        "ICO",
                        "SVG"
                    ]
                },
                "form": {
                    "backgroundImage": {
                        "enabled": false
                    },
                    "borderRadius": 8.0,
                    "darkMode": {
                        "backgroundColor": "0f1b2aff",
                        "borderColor": "424650ff"
                    },
                    "lightMode": {
                        "backgroundColor": "ffffffff",
                        "borderColor": "c6c6cdff"
                    },
                    "logo": {
                        "enabled": false,
                        "formInclusion": "IN",
                        "location": "CENTER",
                        "position": "TOP"
                    }
                },
                "idpButton": {
                    "custom": {
                    },
                    "standard": {
                        "darkMode": {
                            "active": {
                                "backgroundColor": "354150ff",
                                "borderColor": "89bdeeff",
                                "textColor": "89bdeeff"
                            },
                            "defaults": {
                                "backgroundColor": "0f1b2aff",
                                "borderColor": "c6c6cdff",
                                "textColor": "c6c6cdff"
                            },
                            "hover": {
                                "backgroundColor": "192534ff",
                                "borderColor": "89bdeeff",
                                "textColor": "89bdeeff"
                            }
                        },
                        "lightMode": {
                            "active": {
                                "backgroundColor": "d3e7f9ff",
                                "borderColor": "033160ff",
                                "textColor": "033160ff"
                            },
                            "defaults": {
                                "backgroundColor": "ffffffff",
                                "borderColor": "424650ff",
                                "textColor": "424650ff"
                            },
                            "hover": {
                                "backgroundColor": "f2f8fdff",
                                "borderColor": "033160ff",
                                "textColor": "033160ff"
                            }
                        }
                    }
                },
                "pageBackground": {
                    "darkMode": {
                        "color": "0f1b2aff"
                    },
                    "image": {
                        "enabled": true
                    },
                    "lightMode": {
                        "color": "ffffffff"
                    }
                },
                "pageFooter": {
                    "backgroundImage": {
                        "enabled": false
                    },
                    "darkMode": {
                        "background": {
                            "color": "0f141aff"
                        },
                        "borderColor": "424650ff"
                    },
                    "lightMode": {
                        "background": {
                            "color": "fafafaff"
                        },
                        "borderColor": "d5dbdbff"
                    },
                    "logo": {
                        "enabled": false,
                        "location": "START"
                    }
                },
                "pageHeader": {
                    "backgroundImage": {
                        "enabled": false
                    },
                    "darkMode": {
                        "background": {
                            "color": "0f141aff"
                        },
                        "borderColor": "424650ff"
                    },
                    "lightMode": {
                        "background": {
                            "color": "fafafaff"
                        },
                        "borderColor": "d5dbdbff"
                    },
                    "logo": {
                        "enabled": false,
                        "location": "START"
                    }
                },
                "pageText": {
                    "darkMode": {
                        "bodyColor": "b6bec9ff",
                        "descriptionColor": "b6bec9ff",
                        "headingColor": "d1d5dbff"
                    },
                    "lightMode": {
                        "bodyColor": "414d5cff",
                        "descriptionColor": "414d5cff",
                        "headingColor": "000716ff"
                    }
                },
                "phoneNumberSelector": {
                    "displayType": "TEXT"
                },
                "primaryButton": {
                    "darkMode": {
                        "active": {
                            "backgroundColor": "539fe5ff",
                            "textColor": "000716ff"
                        },
                        "defaults": {
                            "backgroundColor": "539fe5ff",
                            "textColor": "000716ff"
                        },
                        "disabled": {
                            "backgroundColor": "ffffffff",
                            "borderColor": "ffffffff"
                        },
                        "hover": {
                            "backgroundColor": "89bdeeff",
                            "textColor": "000716ff"
                        }
                    },
                    "lightMode": {
                        "active": {
                            "backgroundColor": "033160ff",
                            "textColor": "ffffffff"
                        },
                        "defaults": {
                            "backgroundColor": "0972d3ff",
                            "textColor": "ffffffff"
                        },
                        "disabled": {
                            "backgroundColor": "ffffffff",
                            "borderColor": "ffffffff"
                        },
                        "hover": {
                            "backgroundColor": "033160ff",
                            "textColor": "ffffffff"
                        }
                    }
                },
                "secondaryButton": {
                    "darkMode": {
                        "active": {
                            "backgroundColor": "354150ff",
                            "borderColor": "89bdeeff",
                            "textColor": "89bdeeff"
                        },
                        "defaults": {
                            "backgroundColor": "0f1b2aff",
                            "borderColor": "539fe5ff",
                            "textColor": "539fe5ff"
                        },
                        "hover": {
                            "backgroundColor": "192534ff",
                            "borderColor": "89bdeeff",
                            "textColor": "89bdeeff"
                        }
                    },
                    "lightMode": {
                        "active": {
                            "backgroundColor": "d3e7f9ff",
                            "borderColor": "033160ff",
                            "textColor": "033160ff"
                        },
                        "defaults": {
                            "backgroundColor": "ffffffff",
                            "borderColor": "0972d3ff",
                            "textColor": "0972d3ff"
                        },
                        "hover": {
                            "backgroundColor": "f2f8fdff",
                            "borderColor": "033160ff",
                            "textColor": "033160ff"
                        }
                    }
                }
            }
        },
        "UseCognitoProvidedValues": false,
        "UserPoolId": "ca-central-1_EXAMPLE"
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Apply branding to managed login pages](https://docs.aws.amazon.com/cognito/latest/developerguide/managed-login-branding.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateManagedLoginBranding](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-managed-login-branding.html)」を参照してください。

### `update-resource-server`
<a name="cognito-identity-provider_UpdateResourceServer_cli_2_topic"></a>

次のコード例は、`update-resource-server` を使用する方法を示しています。

**AWS CLI**  
**リソースサーバーを更新するには**  
この例では、リソースサーバー Weather を更新しています。新しいスコープが追加されます。  
コマンド:  

```
aws cognito-idp update-resource-server --user-pool-id us-west-2_aaaaaaaaa --identifier weather.example.com --name Weather --scopes ScopeName=NewScope,ScopeDescription="New scope description"
```
出力:  

```
{
  "ResourceServer": {
      "UserPoolId": "us-west-2_aaaaaaaaa",
      "Identifier": "weather.example.com",
      "Name": "Happy",
      "Scopes": [
          {
              "ScopeName": "NewScope",
              "ScopeDescription": "New scope description"
          }
      ]
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResourceServer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-resource-server.html)」を参照してください。

### `update-user-attributes`
<a name="cognito-identity-provider_UpdateUserAttributes_cli_2_topic"></a>

次のコード例は、`update-user-attributes` を使用する方法を示しています。

**AWS CLI**  
**ユーザー属性を更新するには**  
この例では、ユーザー属性「nickname」を更新しています。  
コマンド:  

```
aws cognito-idp update-user-attributes --access-token ACCESS_TOKEN --user-attributes Name="nickname",Value="Dan"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-user-attributes.html)」を参照してください。

### `update-user-pool-client`
<a name="cognito-identity-provider_UpdateUserPoolClient_cli_2_topic"></a>

次のコード例は、`update-user-pool-client` を使用する方法を示しています。

**AWS CLI**  
**アプリクライアントを更新するには**  
次の `update-user-pool-client` の例では、リクエストされたアプリクライアントの設定を更新します。  

```
aws cognito-idp update-user-pool-client \
    --user-pool-id us-west-2_EXAMPLE \
    --client-id 1example23456789 \
    --client-name my-test-app \
    --refresh-token-validity 30 \
    --access-token-validity 60 \
    --id-token-validity 60 \
    --token-validity-units AccessToken=minutes,IdToken=minutes,RefreshToken=days \
    --read-attributes "address" "birthdate" "email" "email_verified" "family_name" "gender" "locale" "middle_name" "name" "nickname" "phone_number" "phone_number_verified" "picture" "preferred_username" "profile" "updated_at" "website" "zoneinfo" \
    --write-attributes "address" "birthdate" "email" "family_name" "gender" "locale" "middle_name" "name" "nickname" "phone_number" "picture" "preferred_username" "profile" "updated_at" "website" "zoneinfo" \
    --explicit-auth-flows "ALLOW_ADMIN_USER_PASSWORD_AUTH" "ALLOW_CUSTOM_AUTH" "ALLOW_REFRESH_TOKEN_AUTH" "ALLOW_USER_PASSWORD_AUTH" "ALLOW_USER_SRP_AUTH" \
    --supported-identity-providers "MySAML" "COGNITO" "Google" \
    --callback-urls "https://www.example.com" "https://app2.example.com" \
    --logout-urls "https://auth.example.com/login?client_id=1example23456789&response_type=code&redirect_uri=https%3A%2F%2Fwww.example.com" "https://example.com/logout" \
    --default-redirect-uri "https://www.example.com" \
    --allowed-o-auth-flows "code" "implicit" \
    --allowed-o-auth-scopes "openid" "profile" "aws.cognito.signin.user.admin" \
    --allowed-o-auth-flows-user-pool-client \
    --prevent-user-existence-errors ENABLED \
    --enable-token-revocation \
    --no-enable-propagate-additional-user-context-data \
    --auth-session-validity 3
```
出力:  

```
{
    "UserPoolClient": {
        "UserPoolId": "us-west-2_EXAMPLE",
        "ClientName": "my-test-app",
        "ClientId": "1example23456789",
        "LastModifiedDate": "2025-01-31T14:40:12.498000-08:00",
        "CreationDate": "2023-09-13T16:26:34.408000-07:00",
        "RefreshTokenValidity": 30,
        "AccessTokenValidity": 60,
        "IdTokenValidity": 60,
        "TokenValidityUnits": {
            "AccessToken": "minutes",
            "IdToken": "minutes",
            "RefreshToken": "days"
        },
        "ReadAttributes": [
            "website",
            "zoneinfo",
            "address",
            "birthdate",
            "email_verified",
            "gender",
            "profile",
            "phone_number_verified",
            "preferred_username",
            "locale",
            "middle_name",
            "picture",
            "updated_at",
            "name",
            "nickname",
            "phone_number",
            "family_name",
            "email"
        ],
        "WriteAttributes": [
            "website",
            "zoneinfo",
            "address",
            "birthdate",
            "gender",
            "profile",
            "preferred_username",
            "locale",
            "middle_name",
            "picture",
            "updated_at",
            "name",
            "nickname",
            "phone_number",
            "family_name",
            "email"
        ],
        "ExplicitAuthFlows": [
            "ALLOW_CUSTOM_AUTH",
            "ALLOW_USER_PASSWORD_AUTH",
            "ALLOW_ADMIN_USER_PASSWORD_AUTH",
            "ALLOW_USER_SRP_AUTH",
            "ALLOW_REFRESH_TOKEN_AUTH"
        ],
        "SupportedIdentityProviders": [
            "Google",
            "COGNITO",
            "MySAML"
        ],
        "CallbackURLs": [
            "https://www.example.com",
            "https://app2.example.com"
        ],
        "LogoutURLs": [
            "https://example.com/logout",
            "https://auth.example.com/login?client_id=1example23456789&response_type=code&redirect_uri=https%3A%2F%2Fwww.example.com"
        ],
        "DefaultRedirectURI": "https://www.example.com",
        "AllowedOAuthFlows": [
            "implicit",
            "code"
        ],
        "AllowedOAuthScopes": [
            "aws.cognito.signin.user.admin",
            "openid",
            "profile"
        ],
        "AllowedOAuthFlowsUserPoolClient": true,
        "PreventUserExistenceErrors": "ENABLED",
        "EnableTokenRevocation": true,
        "EnablePropagateAdditionalUserContextData": false,
        "AuthSessionValidity": 3
    }
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[アプリケーションクライアントによるアプリケーション固有の設定](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserPoolClient](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-user-pool-client.html)」を参照してください。

### `update-user-pool-domain`
<a name="cognito-identity-provider_UpdateUserPoolDomain_cli_2_topic"></a>

次のコード例は、`update-user-pool-domain` を使用する方法を示しています。

**AWS CLI**  
**カスタムドメイン名を更新するには**  
次の `update-user-pool-domain` の例では、リクエストされたユーザープールのカスタムドメインのブランディングバージョンと証明書を設定します。  

```
aws cognito-idp update-user-pool-domain \
    --user-pool-id ca-central-1_EXAMPLE \
    --domain auth.example.com \
    --managed-login-version 2 \
    --custom-domain-config CertificateArn=arn:aws:acm:us-east-1:123456789012:certificate/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "CloudFrontDomain": "example.cloudfront.net",
    "ManagedLoginVersion": 2
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Managed login](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-managed-login.html)」と「[Configuring a domain](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-assign-domain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserPoolDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-user-pool-domain.html)」を参照してください。

### `update-user-pool`
<a name="cognito-identity-provider_UpdateUserPool_cli_2_topic"></a>

次のコード例は、`update-user-pool` を使用する方法を示しています。

**AWS CLI**  
**ユーザープールを更新するには**  
次の `update-user-pool` の例では、使用可能な各設定オプションの構文例を使用して、ユーザープールを変更しています。ユーザープールを更新するには、以前に設定されたすべてのオプションを指定する必要があります。指定しない場合は、デフォルト値にリセットされます。  

```
aws cognito-idp update-user-pool --user-pool-id us-west-2_EXAMPLE \
    --policies PasswordPolicy=\{MinimumLength=6,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true,RequireSymbols=true,TemporaryPasswordValidityDays=7\} \
    --deletion-protection ACTIVE \
    --lambda-config PreSignUp="arn:aws:lambda:us-west-2:123456789012:function:cognito-test-presignup-function",PreTokenGeneration="arn:aws:lambda:us-west-2:123456789012:function:cognito-test-pretoken-function" \
    --auto-verified-attributes "phone_number" "email" \
    --verification-message-template \{\"SmsMessage\":\""Your code is {####}"\",\"EmailMessage\":\""Your code is {####}"\",\"EmailSubject\":\""Your verification code"\",\"EmailMessageByLink\":\""Click {##here##} to verify your email address."\",\"EmailSubjectByLink\":\""Your verification link"\",\"DefaultEmailOption\":\"CONFIRM_WITH_LINK\"\} \
    --sms-authentication-message "Your code is {####}" \
    --user-attribute-update-settings AttributesRequireVerificationBeforeUpdate="email","phone_number" \
    --mfa-configuration "OPTIONAL" \
    --device-configuration ChallengeRequiredOnNewDevice=true,DeviceOnlyRememberedOnUserPrompt=true \
    --email-configuration SourceArn="arn:aws:ses:us-west-2:123456789012:identity/admin@example.com",ReplyToEmailAddress="amdin+noreply@example.com",EmailSendingAccount=DEVELOPER,From="admin@amazon.com",ConfigurationSet="test-configuration-set" \
    --sms-configuration SnsCallerArn="arn:aws:iam::123456789012:role/service-role/SNS-SMS-Role",ExternalId="12345",SnsRegion="us-west-2" \
    --admin-create-user-config AllowAdminCreateUserOnly=false,InviteMessageTemplate=\{SMSMessage=\""Welcome {username}. Your confirmation code is {####}"\",EmailMessage=\""Welcome {username}. Your confirmation code is {####}"\",EmailSubject=\""Welcome to MyMobileGame"\"\} \
    --user-pool-tags "Function"="MyMobileGame","Developers"="Berlin" \
    --admin-create-user-config AllowAdminCreateUserOnly=false,InviteMessageTemplate=\{SMSMessage=\""Welcome {username}. Your confirmation code is {####}"\",EmailMessage=\""Welcome {username}. Your confirmation code is {####}"\",EmailSubject=\""Welcome to MyMobileGame"\"\} \
    --user-pool-add-ons AdvancedSecurityMode="AUDIT" \
    --account-recovery-setting RecoveryMechanisms=\[\{Priority=1,Name="verified_email"\},\{Priority=2,Name="verified_phone_number"\}\]
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Cognito Developer Guide*」の「[Updating user pool configuration](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pool-updating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/update-user-pool.html)」を参照してください。

### `verify-software-token`
<a name="cognito-identity-provider_VerifySoftwareToken_cli_2_topic"></a>

次のコード例は、`verify-software-token` を使用する方法を示しています。

**AWS CLI**  
**TOTP 認証システムの登録を確認するには**  
次の `verify-software-token` の例では、現在のユーザーの TOTP 登録を完了します。  

```
aws cognito-idp verify-software-token \
    --access-token eyJra456defEXAMPLE \
    --user-code 123456
```
出力:  

```
{
    "Status": "SUCCESS"
}
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Adding MFA to a user pool](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifySoftwareToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/verify-software-token.html)」を参照してください。

### `verify-user-attribute`
<a name="cognito-identity-provider_VerifyUserAttribute_cli_2_topic"></a>

次のコード例は、`verify-user-attribute` を使用する方法を示しています。

**AWS CLI**  
**属性の変更を確認するには**  
次の `verify-user-attribute` の例では、現在のユーザーの E メール属性の変更を検証します。  

```
aws cognito-idp verify-user-attribute \
    --access-token eyJra456defEXAMPLE \
    --attribute-name email \
    --code 123456
```
詳細については、「*Amazon Cognito デベロッパーガイド*」の「[Configuring email or phone verification](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyUserAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cognito-idp/verify-user-attribute.html)」を参照してください。

# を使用した Amazon Comprehend の例 AWS CLI
<a name="cli_2_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-detect-dominant-language`
<a name="comprehend_BatchDetectDominantLanguage_cli_2_topic"></a>

次のコード例は、`batch-detect-dominant-language` を使用する方法を示しています。

**AWS CLI**  
**複数の入力テキストの主要言語を検出するには**  
次の `batch-detect-dominant-language` の例では、複数の入力テキストを分析し、それぞれの主要言語を返しています。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend batch-detect-dominant-language \
    --text-list "Physics is the natural science that involves the study of matter and its motion and behavior through space and time, along with related concepts such as energy and force."
```
出力:  

```
{
    "ResultList": [
        {
            "Index": 0,
            "Languages": [
                {
                    "LanguageCode": "en",
                    "Score": 0.9986501932144165
                }
            ]
        }
    ],
    "ErrorList": []
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[主要言語](https://docs.aws.amazon.com/comprehend/latest/dg/how-languages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDetectDominantLanguage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/batch-detect-dominant-language.html)」を参照してください。

### `batch-detect-entities`
<a name="comprehend_BatchDetectEntities_cli_2_topic"></a>

次のコード例は、`batch-detect-entities` を使用する方法を示しています。

**AWS CLI**  
**複数の入力テキストからエンティティを検出するには**  
次の `batch-detect-entities` の例では、複数の入力テキストを分析し、それぞれの名前付きエンティティを返しています。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend batch-detect-entities \
    --language-code en \
    --text-list "Dear Jane, Your AnyCompany Financial Services LLC credit card account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st." "Please send customer feedback to Sunshine Spa, 123 Main St, Anywhere or to Alice at AnySpa@example.com."
```
出力:  

```
{
    "ResultList": [
        {
            "Index": 0,
            "Entities": [
                {
                    "Score": 0.9985517859458923,
                    "Type": "PERSON",
                    "Text": "Jane",
                    "BeginOffset": 5,
                    "EndOffset": 9
                },
                {
                    "Score": 0.9767839312553406,
                    "Type": "ORGANIZATION",
                    "Text": "AnyCompany Financial Services, LLC",
                    "BeginOffset": 16,
                    "EndOffset": 50
                },
                {
                    "Score": 0.9856694936752319,
                    "Type": "OTHER",
                    "Text": "1111-XXXX-1111-XXXX",
                    "BeginOffset": 71,
                    "EndOffset": 90
                },
                {
                    "Score": 0.9652159810066223,
                    "Type": "QUANTITY",
                    "Text": ".53",
                    "BeginOffset": 116,
                    "EndOffset": 119
                },
                {
                    "Score": 0.9986667037010193,
                    "Type": "DATE",
                    "Text": "July 31st",
                    "BeginOffset": 135,
                    "EndOffset": 144
                }
            ]
        },
        {
            "Index": 1,
            "Entities": [
                {
                    "Score": 0.720084547996521,
                    "Type": "ORGANIZATION",
                    "Text": "Sunshine Spa",
                    "BeginOffset": 33,
                    "EndOffset": 45
                },
                {
                    "Score": 0.9865870475769043,
                    "Type": "LOCATION",
                    "Text": "123 Main St",
                    "BeginOffset": 47,
                    "EndOffset": 58
                },
                {
                    "Score": 0.5895616412162781,
                    "Type": "LOCATION",
                    "Text": "Anywhere",
                    "BeginOffset": 60,
                    "EndOffset": 68
                },
                {
                    "Score": 0.6809214353561401,
                    "Type": "PERSON",
                    "Text": "Alice",
                    "BeginOffset": 75,
                    "EndOffset": 80
                },
                {
                    "Score": 0.9979087114334106,
                    "Type": "OTHER",
                    "Text": "AnySpa@example.com",
                    "BeginOffset": 84,
                    "EndOffset": 99
                }
            ]
        }
    ],
    "ErrorList": []
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[エンティティ](https://docs.aws.amazon.com/comprehend/latest/dg/how-entities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDetectEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/batch-detect-entities.html)」を参照してください。

### `batch-detect-key-phrases`
<a name="comprehend_BatchDetectKeyPhrases_cli_2_topic"></a>

次のコード例は、`batch-detect-key-phrases` を使用する方法を示しています。

**AWS CLI**  
**複数のテキスト入力のキーフレーズを検出するには**  
次の `batch-detect-key-phrases` の例では、複数の入力テキストを分析し、それぞれの主要な名詞フレーズを返しています。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend batch-detect-key-phrases \
    --language-code en \
    --text-list "Hello Zhang Wei, I am John, writing to you about the trip for next Saturday." "Dear Jane, Your AnyCompany Financial Services LLC credit card account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st." "Please send customer feedback to Sunshine Spa, 123 Main St, Anywhere or to Alice at AnySpa@example.com."
```
出力:  

```
{
    "ResultList": [
        {
            "Index": 0,
            "KeyPhrases": [
                {
                    "Score": 0.99700927734375,
                    "Text": "Zhang Wei",
                    "BeginOffset": 6,
                    "EndOffset": 15
                },
                {
                    "Score": 0.9929308891296387,
                    "Text": "John",
                    "BeginOffset": 22,
                    "EndOffset": 26
                },
                {
                    "Score": 0.9997230172157288,
                    "Text": "the trip",
                    "BeginOffset": 49,
                    "EndOffset": 57
                },
                {
                    "Score": 0.9999470114707947,
                    "Text": "next Saturday",
                    "BeginOffset": 62,
                    "EndOffset": 75
                }
            ]
        },
        {
            "Index": 1,
            "KeyPhrases": [
                {
                    "Score": 0.8358274102210999,
                    "Text": "Dear Jane",
                    "BeginOffset": 0,
                    "EndOffset": 9
                },
                {
                    "Score": 0.989359974861145,
                    "Text": "Your AnyCompany Financial Services",
                    "BeginOffset": 11,
                    "EndOffset": 45
                },
                {
                    "Score": 0.8812323808670044,
                    "Text": "LLC credit card account 1111-XXXX-1111-XXXX",
                    "BeginOffset": 47,
                    "EndOffset": 90
                },
                {
                    "Score": 0.9999381899833679,
                    "Text": "a minimum payment",
                    "BeginOffset": 95,
                    "EndOffset": 112
                },
                {
                    "Score": 0.9997439980506897,
                    "Text": ".53",
                    "BeginOffset": 116,
                    "EndOffset": 119
                },
                {
                    "Score": 0.996875524520874,
                    "Text": "July 31st",
                    "BeginOffset": 135,
                    "EndOffset": 144
                }
            ]
        },
        {
            "Index": 2,
            "KeyPhrases": [
                {
                    "Score": 0.9990295767784119,
                    "Text": "customer feedback",
                    "BeginOffset": 12,
                    "EndOffset": 29
                },
                {
                    "Score": 0.9994127750396729,
                    "Text": "Sunshine Spa",
                    "BeginOffset": 33,
                    "EndOffset": 45
                },
                {
                    "Score": 0.9892991185188293,
                    "Text": "123 Main St",
                    "BeginOffset": 47,
                    "EndOffset": 58
                },
                {
                    "Score": 0.9969810843467712,
                    "Text": "Alice",
                    "BeginOffset": 75,
                    "EndOffset": 80
                },
                {
                    "Score": 0.9703696370124817,
                    "Text": "AnySpa@example.com",
                    "BeginOffset": 84,
                    "EndOffset": 99
                }
            ]
        }
    ],
    "ErrorList": []
}
```
詳細については、「Amazon Comprehend 開発者ガイド」の「[キーフレーズ](https://docs.aws.amazon.com/comprehend/latest/dg/how-key-phrases.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDetectKeyPhrases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/batch-detect-key-phrases.html)」を参照してください。

### `batch-detect-sentiment`
<a name="comprehend_BatchDetectSentiment_cli_2_topic"></a>

次のコード例は、`batch-detect-sentiment` を使用する方法を示しています。

**AWS CLI**  
**複数の入力テキストの一般的な感情を検出するには**  
次の `batch-detect-sentiment` の例では、入力テキストを分析し、一般的な感情 (それぞれの `POSITIVE`、`NEUTRAL`、`MIXED`、または `NEGATIVE`) を返しています。  

```
aws comprehend batch-detect-sentiment \
    --text-list "That movie was very boring, I can't believe it was over four hours long." "It is a beautiful day for hiking today." "My meal was okay, I'm excited to try other restaurants." \
    --language-code en
```
出力:  

```
{
    "ResultList": [
        {
            "Index": 0,
            "Sentiment": "NEGATIVE",
            "SentimentScore": {
                "Positive": 0.00011316669406369328,
                "Negative": 0.9995445609092712,
                "Neutral": 0.00014722718333359808,
                "Mixed": 0.00019498742767609656
            }
        },
        {
            "Index": 1,
            "Sentiment": "POSITIVE",
            "SentimentScore": {
                "Positive": 0.9981263279914856,
                "Negative": 0.00015240783977787942,
                "Neutral": 0.0013876151060685515,
                "Mixed": 0.00033366199932061136
            }
        },
        {
            "Index": 2,
            "Sentiment": "MIXED",
            "SentimentScore": {
                "Positive": 0.15930435061454773,
                "Negative": 0.11471917480230331,
                "Neutral": 0.26897063851356506,
                "Mixed": 0.45700588822364807
            }
        }
    ],
    "ErrorList": []
}
```
詳細については、「Amazon Comprehend デベロッパーガイド」の「[感情](https://docs.aws.amazon.com/comprehend/latest/dg/how-sentiment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDetectSentiment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/batch-detect-sentiment.html)」を参照してください。

### `batch-detect-syntax`
<a name="comprehend_BatchDetectSyntax_cli_2_topic"></a>

次のコード例は、`batch-detect-syntax` を使用する方法を示しています。

**AWS CLI**  
**複数の入力テキスト内の単語の構文と品詞を調べるには**  
次の `batch-detect-syntax` の例では、複数の入力テキストの構文を分析し、さまざまな品詞を返しています。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend batch-detect-syntax \
    --text-list "It is a beautiful day." "Can you please pass the salt?" "Please pay the bill before the 31st." \
    --language-code en
```
出力:  

```
{
    "ResultList": [
        {
            "Index": 0,
            "SyntaxTokens": [
                {
                    "TokenId": 1,
                    "Text": "It",
                    "BeginOffset": 0,
                    "EndOffset": 2,
                    "PartOfSpeech": {
                        "Tag": "PRON",
                        "Score": 0.9999740719795227
                    }
                },
                {
                    "TokenId": 2,
                    "Text": "is",
                    "BeginOffset": 3,
                    "EndOffset": 5,
                    "PartOfSpeech": {
                        "Tag": "VERB",
                        "Score": 0.999937117099762
                    }
                },
                {
                    "TokenId": 3,
                    "Text": "a",
                    "BeginOffset": 6,
                    "EndOffset": 7,
                    "PartOfSpeech": {
                        "Tag": "DET",
                        "Score": 0.9999926686286926
                    }
                },
                {
                    "TokenId": 4,
                    "Text": "beautiful",
                    "BeginOffset": 8,
                    "EndOffset": 17,
                    "PartOfSpeech": {
                        "Tag": "ADJ",
                        "Score": 0.9987891912460327
                    }
                },
                {
                    "TokenId": 5,
                    "Text": "day",
                    "BeginOffset": 18,
                    "EndOffset": 21,
                    "PartOfSpeech": {
                        "Tag": "NOUN",
                        "Score": 0.9999778866767883
                    }
                },
                {
                    "TokenId": 6,
                    "Text": ".",
                    "BeginOffset": 21,
                    "EndOffset": 22,
                    "PartOfSpeech": {
                        "Tag": "PUNCT",
                        "Score": 0.9999974966049194
                    }
                }
            ]
        },
        {
            "Index": 1,
            "SyntaxTokens": [
                {
                    "TokenId": 1,
                    "Text": "Can",
                    "BeginOffset": 0,
                    "EndOffset": 3,
                    "PartOfSpeech": {
                        "Tag": "AUX",
                        "Score": 0.9999770522117615
                    }
                },
                {
                    "TokenId": 2,
                    "Text": "you",
                    "BeginOffset": 4,
                    "EndOffset": 7,
                    "PartOfSpeech": {
                        "Tag": "PRON",
                        "Score": 0.9999986886978149
                    }
                },
                {
                    "TokenId": 3,
                    "Text": "please",
                    "BeginOffset": 8,
                    "EndOffset": 14,
                    "PartOfSpeech": {
                        "Tag": "INTJ",
                        "Score": 0.9681622385978699
                    }
                },
                {
                    "TokenId": 4,
                    "Text": "pass",
                    "BeginOffset": 15,
                    "EndOffset": 19,
                    "PartOfSpeech": {
                        "Tag": "VERB",
                        "Score": 0.9999874830245972
                    }
                },
                {
                    "TokenId": 5,
                    "Text": "the",
                    "BeginOffset": 20,
                    "EndOffset": 23,
                    "PartOfSpeech": {
                        "Tag": "DET",
                        "Score": 0.9999827146530151
                    }
                },
                {
                    "TokenId": 6,
                    "Text": "salt",
                    "BeginOffset": 24,
                    "EndOffset": 28,
                    "PartOfSpeech": {
                        "Tag": "NOUN",
                        "Score": 0.9995040893554688
                    }
                },
                {
                    "TokenId": 7,
                    "Text": "?",
                    "BeginOffset": 28,
                    "EndOffset": 29,
                    "PartOfSpeech": {
                        "Tag": "PUNCT",
                        "Score": 0.999998152256012
                    }
                }
            ]
        },
        {
            "Index": 2,
            "SyntaxTokens": [
                {
                    "TokenId": 1,
                    "Text": "Please",
                    "BeginOffset": 0,
                    "EndOffset": 6,
                    "PartOfSpeech": {
                        "Tag": "INTJ",
                        "Score": 0.9997857809066772
                    }
                },
                {
                    "TokenId": 2,
                    "Text": "pay",
                    "BeginOffset": 7,
                    "EndOffset": 10,
                    "PartOfSpeech": {
                        "Tag": "VERB",
                        "Score": 0.9999252557754517
                    }
                },
                {
                    "TokenId": 3,
                    "Text": "the",
                    "BeginOffset": 11,
                    "EndOffset": 14,
                    "PartOfSpeech": {
                        "Tag": "DET",
                        "Score": 0.9999842643737793
                    }
                },
                {
                    "TokenId": 4,
                    "Text": "bill",
                    "BeginOffset": 15,
                    "EndOffset": 19,
                    "PartOfSpeech": {
                        "Tag": "NOUN",
                        "Score": 0.9999588131904602
                    }
                },
                {
                    "TokenId": 5,
                    "Text": "before",
                    "BeginOffset": 20,
                    "EndOffset": 26,
                    "PartOfSpeech": {
                        "Tag": "ADP",
                        "Score": 0.9958304762840271
                    }
                },
                {
                    "TokenId": 6,
                    "Text": "the",
                    "BeginOffset": 27,
                    "EndOffset": 30,
                    "PartOfSpeech": {
                        "Tag": "DET",
                        "Score": 0.9999947547912598
                    }
                },
                {
                    "TokenId": 7,
                    "Text": "31st",
                    "BeginOffset": 31,
                    "EndOffset": 35,
                    "PartOfSpeech": {
                        "Tag": "NOUN",
                        "Score": 0.9924124479293823
                    }
                },
                {
                    "TokenId": 8,
                    "Text": ".",
                    "BeginOffset": 35,
                    "EndOffset": 36,
                    "PartOfSpeech": {
                        "Tag": "PUNCT",
                        "Score": 0.9999955892562866
                    }
                }
            ]
        }
    ],
    "ErrorList": []
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[構文分析](https://docs.aws.amazon.com/comprehend/latest/dg/how-syntax.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDetectSyntax](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/batch-detect-syntax.html)」を参照してください。

### `batch-detect-targeted-sentiment`
<a name="comprehend_BatchDetectTargetedSentiment_cli_2_topic"></a>

次のコード例は、`batch-detect-targeted-sentiment` を使用する方法を示しています。

**AWS CLI**  
**複数の入力テキストの感情とそれぞれの名前付きエンティティを検出するには**  
次の `batch-detect-targeted-sentiment` の例では、複数の入力テキストを分析し、名前付きエンティティとそれぞれのエンティティにアタッチされた一般的な感情を返しています。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend batch-detect-targeted-sentiment \
    --language-code en \
    --text-list "That movie was really boring, the original was way more entertaining" "The trail is extra beautiful today." "My meal was just okay."
```
出力:  

```
{
    "ResultList": [
        {
            "Index": 0,
            "Entities": [
                {
                    "DescriptiveMentionIndex": [
                        0
                    ],
                    "Mentions": [
                        {
                            "Score": 0.9999009966850281,
                            "GroupScore": 1.0,
                            "Text": "movie",
                            "Type": "MOVIE",
                            "MentionSentiment": {
                                "Sentiment": "NEGATIVE",
                                "SentimentScore": {
                                    "Positive": 0.13887299597263336,
                                    "Negative": 0.8057460188865662,
                                    "Neutral": 0.05525200068950653,
                                    "Mixed": 0.00012799999967683107
                                }
                            },
                            "BeginOffset": 5,
                            "EndOffset": 10
                        }
                    ]
                },
                {
                    "DescriptiveMentionIndex": [
                        0
                    ],
                    "Mentions": [
                        {
                            "Score": 0.9921110272407532,
                            "GroupScore": 1.0,
                            "Text": "original",
                            "Type": "MOVIE",
                            "MentionSentiment": {
                                "Sentiment": "POSITIVE",
                                "SentimentScore": {
                                    "Positive": 0.9999989867210388,
                                    "Negative": 9.999999974752427e-07,
                                    "Neutral": 0.0,
                                    "Mixed": 0.0
                                }
                            },
                            "BeginOffset": 34,
                            "EndOffset": 42
                        }
                    ]
                }
            ]
        },
        {
            "Index": 1,
            "Entities": [
                {
                    "DescriptiveMentionIndex": [
                        0
                    ],
                    "Mentions": [
                        {
                            "Score": 0.7545599937438965,
                            "GroupScore": 1.0,
                            "Text": "trail",
                            "Type": "OTHER",
                            "MentionSentiment": {
                                "Sentiment": "POSITIVE",
                                "SentimentScore": {
                                    "Positive": 1.0,
                                    "Negative": 0.0,
                                    "Neutral": 0.0,
                                    "Mixed": 0.0
                                }
                            },
                            "BeginOffset": 4,
                            "EndOffset": 9
                        }
                    ]
                },
                {
                    "DescriptiveMentionIndex": [
                        0
                    ],
                    "Mentions": [
                        {
                            "Score": 0.9999960064888,
                            "GroupScore": 1.0,
                            "Text": "today",
                            "Type": "DATE",
                            "MentionSentiment": {
                                "Sentiment": "NEUTRAL",
                                "SentimentScore": {
                                    "Positive": 9.000000318337698e-06,
                                    "Negative": 1.9999999949504854e-06,
                                    "Neutral": 0.9999859929084778,
                                    "Mixed": 3.999999989900971e-06
                                }
                            },
                            "BeginOffset": 29,
                            "EndOffset": 34
                        }
                    ]
                }
            ]
        },
        {
            "Index": 2,
            "Entities": [
                {
                    "DescriptiveMentionIndex": [
                        0
                    ],
                    "Mentions": [
                        {
                            "Score": 0.9999880194664001,
                            "GroupScore": 1.0,
                            "Text": "My",
                            "Type": "PERSON",
                            "MentionSentiment": {
                                "Sentiment": "NEUTRAL",
                                "SentimentScore": {
                                    "Positive": 0.0,
                                    "Negative": 0.0,
                                    "Neutral": 1.0,
                                    "Mixed": 0.0
                                }
                            },
                            "BeginOffset": 0,
                            "EndOffset": 2
                        }
                    ]
                },
                {
                    "DescriptiveMentionIndex": [
                        0
                    ],
                    "Mentions": [
                        {
                            "Score": 0.9995260238647461,
                            "GroupScore": 1.0,
                            "Text": "meal",
                            "Type": "OTHER",
                            "MentionSentiment": {
                                "Sentiment": "NEUTRAL",
                                "SentimentScore": {
                                    "Positive": 0.04695599898695946,
                                    "Negative": 0.003226999891921878,
                                    "Neutral": 0.6091709733009338,
                                    "Mixed": 0.34064599871635437
                                }
                            },
                            "BeginOffset": 3,
                            "EndOffset": 7
                        }
                    ]
                }
            ]
        }
    ],
    "ErrorList": []
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Targeted Sentiment](https://docs.aws.amazon.com/comprehend/latest/dg/how-targeted-sentiment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDetectTargetedSentiment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/batch-detect-targeted-sentiment.html)」を参照してください。

### `classify-document`
<a name="comprehend_ClassifyDocument_cli_2_topic"></a>

次のコード例は、`classify-document` を使用する方法を示しています。

**AWS CLI**  
**モデル固有のエンドポイントを使用してドキュメントを分類するには**  
次の `classify-document` の例では、カスタムモデルのエンドポイントを使用してドキュメントを分類しています。この例のモデルは、スパムまたは非スパム (「ハム」) としてラベル付けされた SMS メッセージを含むデータセットでトレーニングされました。  

```
aws comprehend classify-document \
    --endpoint-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/example-classifier-endpoint \
    --text "CONGRATULATIONS! TXT 1235550100 to win $5000"
```
出力:  

```
{
    "Classes": [
        {
            "Name": "spam",
            "Score": 0.9998599290847778
        },
        {
            "Name": "ham",
            "Score": 0.00014001205272506922
        }
    ]
}
```
詳細については、「Amazon Comprehend 開発者ガイド」の「[カスタム分類](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ClassifyDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/classify-document.html)」を参照してください。

### `contains-pii-entities`
<a name="comprehend_ContainsPiiEntities_cli_2_topic"></a>

次のコード例は、`contains-pii-entities` を使用する方法を示しています。

**AWS CLI**  
**PII 情報の有無について入力テキストを分析するには**  
次の `contains-pii-entities` の例では、入力テキストを分析して個人を特定できる情報 (PII) の有無を確認し、名前、住所、銀行口座番号、電話番号などの識別された PII エンティティタイプのラベルを返しています。  

```
aws comprehend contains-pii-entities \
    --language-code en \
    --text "Hello Zhang Wei, I am John. Your AnyCompany Financial Services, LLC credit card
        account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st. Based on your autopay settings,
        we will withdraw your payment on the due date from your bank account number XXXXXX1111 with the routing number XXXXX0000.
        Customer feedback for Sunshine Spa, 100 Main St, Anywhere. Send comments to Alice at AnySpa@example.com."
```
出力:  

```
{
    "Labels": [
        {
            "Name": "NAME",
            "Score": 1.0
        },
        {
            "Name": "EMAIL",
            "Score": 1.0
        },
        {
            "Name": "BANK_ACCOUNT_NUMBER",
            "Score": 0.9995794296264648
        },
        {
            "Name": "BANK_ROUTING",
            "Score": 0.9173126816749573
        },
        {
            "Name": "CREDIT_DEBIT_NUMBER",
            "Score": 1.0
        }
}
```
サポートされる PII エンティティタイプの一覧の詳細については、「Amazon Comprehend 開発者ガイド」の「[個人を特定できる情報 (PII)](https://docs.aws.amazon.com/comprehend/latest/dg/pii.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ContainsPiiEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/contains-pii-entities.html)」を参照してください。

### `create-dataset`
<a name="comprehend_CreateDataset_cli_2_topic"></a>

次のコード例は、`create-dataset` を使用する方法を示しています。

**AWS CLI**  
**フライホイールデータセットを作成するには**  
次の `create-dataset` の例では、フライホイールのデータセットを作成しています。このデータセットは、`--dataset-type` タグで指定された追加のトレーニングデータとして使用されます。  

```
aws comprehend create-dataset \
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity \
    --dataset-name example-dataset \
    --dataset-type "TRAIN" \
    --input-data-config file://inputConfig.json
```
`file://inputConfig.json` の内容:  

```
{
    "DataFormat": "COMPREHEND_CSV",
    "DocumentClassifierInputDataConfig": {
        "S3Uri": "s3://amzn-s3-demo-bucket/training-data.csv"
    }
}
```
出力:  

```
{
    "DatasetArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity/dataset/example-dataset"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDataset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/create-dataset.html)」を参照してください。

### `create-document-classifier`
<a name="comprehend_CreateDocumentClassifier_cli_2_topic"></a>

次のコード例は、`create-document-classifier` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントを分類するドキュメント分類子を作成するには**  
次の `create-document-classifier` の例では、ドキュメント分類子モデルのトレーニングプロセスを開始します。トレーニングデータファイル「`training.csv`」は、`--input-data-config` タグにあります。`training.csv` は 2 列のドキュメントで、1 番目の列にはラベルまたは分類が、2 番目の列にはドキュメントが表示されます。  

```
aws comprehend create-document-classifier \
    --document-classifier-name example-classifier \
    --data-access-arn arn:aws:comprehend:us-west-2:111122223333:pii-entities-detection-job/123456abcdeb0e11022f22a11EXAMPLE \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/" \
    --language-code en
```
出力:  

```
{
    "DocumentClassifierArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier"
}
```
詳細については、「Amazon Comprehend 開発者ガイド」の「[カスタム分類](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateDocumentClassifier](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/create-document-classifier.html)」を参照してください。**

### `create-endpoint`
<a name="comprehend_CreateEndpoint_cli_2_topic"></a>

次のコード例は、`create-endpoint` を使用する方法を示しています。

**AWS CLI**  
**カスタムモデルのエンドポイントを作成するには**  
次の `create-endpoint` の例では、以前にトレーニングしたカスタムモデルの同期推論用のエンドポイントを作成しています。  

```
aws comprehend create-endpoint \
    --endpoint-name example-classifier-endpoint-1 \
    --model-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier \
    --desired-inference-units 1
```
出力:  

```
{
    "EndpointArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/example-classifier-endpoint-1"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/create-endpoint.html)」を参照してください。

### `create-entity-recognizer`
<a name="comprehend_CreateEntityRecognizer_cli_2_topic"></a>

次のコード例は、`create-entity-recognizer` を使用する方法を示しています。

**AWS CLI**  
**カスタムエンティティレコグナイザーを作成するには**  
次の `create-entity-recognizer` の例では、カスタムエンティティレコグナイザーモデルのトレーニングプロセスを開始しています。この例では、トレーニングドキュメントを含む CSV ファイル (`raw_text.csv`)、および CSV エンティティリスト (`entity_list.csv`) を使用してモデルをトレーニングします。`entity-list.csv` には、テキスト列とタイプ列が含まれています。  

```
aws comprehend create-entity-recognizer \
    --recognizer-name example-entity-recognizer
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role \
    --input-data-config "EntityTypes=[{Type=DEVICE}],Documents={S3Uri=s3://amzn-s3-demo-bucket/trainingdata/raw_text.csv},EntityList={S3Uri=s3://amzn-s3-demo-bucket/trainingdata/entity_list.csv}"
    --language-code en
```
出力:  

```
{
    "EntityRecognizerArn": "arn:aws:comprehend:us-west-2:111122223333:example-entity-recognizer/entityrecognizer1"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Custom entity recognition](https://docs.aws.amazon.com/comprehend/latest/dg/custom-entity-recognition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEntityRecognizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/create-entity-recognizer.html)」を参照してください。

### `create-flywheel`
<a name="comprehend_CreateFlywheel_cli_2_topic"></a>

次のコード例は、`create-flywheel` を使用する方法を示しています。

**AWS CLI**  
**フライホイールを作成するには**  
次の `create-flywheel` の例では、ドキュメント分類またはエンティティ認識モデルの継続的なトレーニングを調整するためのフライホイールを作成しています。この例でのフライホイールは、`--active-model-arn` タグで指定された既存のトレーニング済みモデルを管理するために作成されています。フライホイールが作成されると、`--input-data-lake` タグにデータレイクが作成されます。  

```
aws comprehend create-flywheel \
    --flywheel-name example-flywheel \
    --active-model-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-model/version/1 \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role \
    --data-lake-s3-uri "s3://amzn-s3-demo-bucket"
```
出力:  

```
{
    "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFlywheel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/create-flywheel.html)」を参照してください。

### `delete-document-classifier`
<a name="comprehend_DeleteDocumentClassifier_cli_2_topic"></a>

次のコード例は、`delete-document-classifier` を使用する方法を示しています。

**AWS CLI**  
**カスタムドキュメント分類子を削除するには**  
次の `delete-document-classifier` の例では、カスタムドキュメント分類子モデルを削除します。  

```
aws comprehend delete-document-classifier \
    --document-classifier-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier-1
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteDocumentClassifier](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/delete-document-classifier.html)」を参照してください。**

### `delete-endpoint`
<a name="comprehend_DeleteEndpoint_cli_2_topic"></a>

次のコード例は、`delete-endpoint` を使用する方法を示しています。

**AWS CLI**  
**カスタムモデルのエンドポイントを削除するには**  
次の `delete-endpoint` の例では、モデル固有のエンドポイントを削除しています。モデルを削除するには、すべてのエンドポイントを削除する必要があります。  

```
aws comprehend delete-endpoint \
    --endpoint-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/example-classifier-endpoint-1
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/delete-endpoint.html)」を参照してください。

### `delete-entity-recognizer`
<a name="comprehend_DeleteEntityRecognizer_cli_2_topic"></a>

次のコード例は、`delete-entity-recognizer` を使用する方法を示しています。

**AWS CLI**  
**カスタムエンティティレコグナイザーモデルを削除するには**  
次の `delete-entity-recognizer` の例では、カスタムエンティティレコグナイザーモデルを削除しています。  

```
aws comprehend delete-entity-recognizer \
    --entity-recognizer-arn arn:aws:comprehend:us-west-2:111122223333:entity-recognizer/example-entity-recognizer-1
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEntityRecognizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/delete-entity-recognizer.html)」を参照してください。

### `delete-flywheel`
<a name="comprehend_DeleteFlywheel_cli_2_topic"></a>

次のコード例は、`delete-flywheel` を使用する方法を示しています。

**AWS CLI**  
**フライホイールを削除するには**  
次の `delete-flywheel` の例では、フライホイールを削除しています。フライホイールに関連付けられたデータレイクまたはモデルは削除されません。  

```
aws comprehend delete-flywheel \
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel-1
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFlywheel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/delete-flywheel.html)」を参照してください。

### `delete-resource-policy`
<a name="comprehend_DeleteResourcePolicy_cli_2_topic"></a>

次のコード例は、`delete-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースベースのポリシーを削除するには**  
次の `delete-resource-policy` の例では、Amazon Comprehend リソースからリソースベースのポリシーを削除しています。  

```
aws comprehend delete-resource-policy \
    --resource-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier-1/version/1
```
このコマンドでは何も出力されません。  
詳細については、[「Amazon Comprehend デベロッパーガイド」の AWS 「アカウント間のカスタムモデルのコピー](https://docs.aws.amazon.com/comprehend/latest/dg/custom-copy.html)」を参照してください。 *Amazon Comprehend *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/delete-resource-policy.html)」を参照してください。

### `describe-dataset`
<a name="comprehend_DescribeDataset_cli_2_topic"></a>

次のコード例は、`describe-dataset` を使用する方法を示しています。

**AWS CLI**  
**フライホイールデータセットを記述するには**  
次の `describe-dataset` の例では、フライホイールのデータセットのプロパティを取得しています。  

```
aws comprehend describe-dataset \
    --dataset-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity/dataset/example-dataset
```
出力:  

```
{
    "DatasetProperties": {
        "DatasetArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity/dataset/example-dataset",
        "DatasetName": "example-dataset",
        "DatasetType": "TRAIN",
        "DatasetS3Uri": "s3://amzn-s3-demo-bucket/flywheel-entity/schemaVersion=1/12345678A123456Z/datasets/example-dataset/20230616T203710Z/",
        "Status": "CREATING",
        "CreationTime": "2023-06-16T20:37:10.400000+00:00"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDataset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-dataset.html)」を参照してください。

### `describe-document-classification-job`
<a name="comprehend_DescribeDocumentClassificationJob_cli_2_topic"></a>

次のコード例は、`describe-document-classification-job` を使用する方法を示しています。

**AWS CLI**  
**ドキュメント分類ジョブを記述するには**  
次の `describe-document-classification-job` の例では、非同期ドキュメント分類ジョブのプロパティを取得します。  

```
aws comprehend describe-document-classification-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "DocumentClassificationJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:document-classification-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "exampleclassificationjob",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2023-06-14T17:09:51.788000+00:00",
        "EndTime": "2023-06-14T17:15:58.582000+00:00",
        "DocumentClassifierArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/mymodel/version/1",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/jobdata/",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-CLN-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
        },
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-servicerole"
    }
}
```
詳細については、「Amazon Comprehend デベロッパーガイド」の「[カスタム分類](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeDocumentClassificationJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-document-classification-job.html)」を参照してください。**

### `describe-document-classifier`
<a name="comprehend_DescribeDocumentClassifier_cli_2_topic"></a>

次のコード例は、`describe-document-classifier` を使用する方法を示しています。

**AWS CLI**  
**ドキュメント分類子を記述するには**  
次の `describe-document-classifier` の例では、カスタムドキュメント分類子モデルのプロパティを取得します。  

```
aws comprehend describe-document-classifier \
    --document-classifier-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier-1
```
出力:  

```
{
    "DocumentClassifierProperties": {
        "DocumentClassifierArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier-1",
        "LanguageCode": "en",
        "Status": "TRAINED",
        "SubmitTime": "2023-06-13T19:04:15.735000+00:00",
        "EndTime": "2023-06-13T19:42:31.752000+00:00",
        "TrainingStartTime": "2023-06-13T19:08:20.114000+00:00",
        "TrainingEndTime": "2023-06-13T19:41:35.080000+00:00",
        "InputDataConfig": {
            "DataFormat": "COMPREHEND_CSV",
            "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata"
        },
        "OutputDataConfig": {},
        "ClassifierMetadata": {
            "NumberOfLabels": 3,
            "NumberOfTrainedDocuments": 5016,
            "NumberOfTestDocuments": 557,
            "EvaluationMetrics": {
                "Accuracy": 0.9856,
                "Precision": 0.9919,
                "Recall": 0.9459,
                "F1Score": 0.9673,
                "MicroPrecision": 0.9856,
                "MicroRecall": 0.9856,
                "MicroF1Score": 0.9856,
                "HammingLoss": 0.0144
            }
        },
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role",
        "Mode": "MULTI_CLASS"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[カスタムモデルの作成と管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-models.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDocumentClassifier](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-document-classifier.html)」を参照してください。

### `describe-dominant-language-detection-job`
<a name="comprehend_DescribeDominantLanguageDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-dominant-language-detection-job` を使用する方法を示しています。

**AWS CLI**  
**主要言語の検出ジョブを記述するには。**  
次の `describe-dominant-language-detection-job` の例では、非同期主要言語検出ジョブのプロパティを取得しています。  

```
aws comprehend describe-dominant-language-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "DominantLanguageDetectionJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:dominant-language-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "languageanalysis1",
        "JobStatus": "IN_PROGRESS",
        "SubmitTime": "2023-06-09T18:10:38.037000+00:00",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-LANGUAGE-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
        },
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDominantLanguageDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-dominant-language-detection-job.html)」を参照してください。

### `describe-endpoint`
<a name="comprehend_DescribeEndpoint_cli_2_topic"></a>

次のコード例は、`describe-endpoint` を使用する方法を示しています。

**AWS CLI**  
**特定のエンドポイントを記述するには**  
次の `describe-endpoint` の例では、モデル固有のエンドポイントのプロパティを取得しています。  

```
aws comprehend describe-endpoint \
    --endpoint-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/example-classifier-endpoint
```
出力:  

```
{
    "EndpointProperties": {
        "EndpointArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/example-classifier-endpoint,
        "Status": "IN_SERVICE",
        "ModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier1",
        "DesiredModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier1",
        "DesiredInferenceUnits": 1,
        "CurrentInferenceUnits": 1,
        "CreationTime": "2023-06-13T20:32:54.526000+00:00",
        "LastModifiedTime": "2023-06-13T20:32:54.526000+00:00"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-endpoint.html)」を参照してください。**

### `describe-entities-detection-job`
<a name="comprehend_DescribeEntitiesDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-entities-detection-job` を使用する方法を示しています。

**AWS CLI**  
**エンティティ検出ジョブを記述するには**  
次の `describe-entities-detection-job` の例では、非同期エンティティ検出ジョブのプロパティを取得しています。  

```
aws comprehend describe-entities-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "EntitiesDetectionJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:entities-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "example-entity-detector",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2023-06-08T21:30:15.323000+00:00",
        "EndTime": "2023-06-08T21:40:23.509000+00:00",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/thefolder/111122223333-NER-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::12345678012:role/service-role/AmazonComprehendServiceRole-example-role"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEntitiesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-entities-detection-job.html)」を参照してください。

### `describe-entity-recognizer`
<a name="comprehend_DescribeEntityRecognizer_cli_2_topic"></a>

次のコード例は、`describe-entity-recognizer` を使用する方法を示しています。

**AWS CLI**  
**エンティティレコグナイザーを記述するには**  
次の `describe-entity-recognizer` の例では、カスタムエンティティレコグナイザーモデルのプロパティを取得しています。  

```
aws comprehend describe-entity-recognizer \
    entity-recognizer-arn arn:aws:comprehend:us-west-2:111122223333:entity-recognizer/business-recongizer-1/version/1
```
出力:  

```
{
    "EntityRecognizerProperties": {
        "EntityRecognizerArn": "arn:aws:comprehend:us-west-2:111122223333:entity-recognizer/business-recongizer-1/version/1",
        "LanguageCode": "en",
        "Status": "TRAINED",
        "SubmitTime": "2023-06-14T20:44:59.631000+00:00",
        "EndTime": "2023-06-14T20:59:19.532000+00:00",
        "TrainingStartTime": "2023-06-14T20:48:52.811000+00:00",
        "TrainingEndTime": "2023-06-14T20:58:11.473000+00:00",
        "InputDataConfig": {
            "DataFormat": "COMPREHEND_CSV",
            "EntityTypes": [
                {
                    "Type": "BUSINESS"
                }
            ],
            "Documents": {
                "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata/dataset/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "EntityList": {
                "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata/entity.csv"
            }
        },
        "RecognizerMetadata": {
            "NumberOfTrainedDocuments": 1814,
            "NumberOfTestDocuments": 486,
            "EvaluationMetrics": {
                "Precision": 100.0,
                "Recall": 100.0,
                "F1Score": 100.0
            },
            "EntityTypes": [
                {
                    "Type": "BUSINESS",
                    "EvaluationMetrics": {
                        "Precision": 100.0,
                        "Recall": 100.0,
                        "F1Score": 100.0
                    },
                    "NumberOfTrainMentions": 1520
                }
            ]
        },
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role",
        "VersionName": "1"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Custom entity recognition](https://docs.aws.amazon.com/comprehend/latest/dg/custom-entity-recognition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEntityRecognizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-entity-recognizer.html)」を参照してください。

### `describe-events-detection-job`
<a name="comprehend_DescribeEventsDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-events-detection-job` を使用する方法を示しています。

**AWS CLI**  
**イベント検出ジョブを記述するには。**  
次の `describe-events-detection-job` の例では、非同期イベント検出ジョブのプロパティを取得しています。  

```
aws comprehend describe-events-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "EventsDetectionJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:events-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "events_job_1",
        "JobStatus": "IN_PROGRESS",
        "SubmitTime": "2023-06-12T18:45:56.054000+00:00",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/EventsData",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-EVENTS-123456abcdeb0e11022f22a11EXAMPLE/output/"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role",
        "TargetEventTypes": [
            "BANKRUPTCY",
            "EMPLOYMENT",
            "CORPORATE_ACQUISITION",
            "CORPORATE_MERGER",
            "INVESTMENT_GENERAL"
        ]
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventsDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-events-detection-job.html)」を参照してください。

### `describe-flywheel-iteration`
<a name="comprehend_DescribeFlywheelIteration_cli_2_topic"></a>

次のコード例は、`describe-flywheel-iteration` を使用する方法を示しています。

**AWS CLI**  
**フライホイールイテレーションを記述するには**  
次の `describe-flywheel-iteration` の例では、フライホイールイテレーションのプロパティを取得しています。  

```
aws comprehend describe-flywheel-iteration \
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel \
    --flywheel-iteration-id 20232222AEXAMPLE
```
出力:  

```
{
    "FlywheelIterationProperties": {
        "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity",
        "FlywheelIterationId": "20232222AEXAMPLE",
        "CreationTime": "2023-06-16T21:10:26.385000+00:00",
        "EndTime": "2023-06-16T23:33:16.827000+00:00",
        "Status": "COMPLETED",
        "Message": "FULL_ITERATION: Flywheel iteration performed all functions successfully.",
        "EvaluatedModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1",
        "EvaluatedModelMetrics": {
            "AverageF1Score": 0.7742663922375772,
            "AveragePrecision": 0.8287636394041166,
            "AverageRecall": 0.7427084833645399,
            "AverageAccuracy": 0.8795394154118689
        },
        "TrainedModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/Comprehend-Generated-v1-bb52d585",
        "TrainedModelMetrics": {
            "AverageF1Score": 0.9767700253081214,
            "AveragePrecision": 0.9767700253081214,
            "AverageRecall": 0.9767700253081214,
            "AverageAccuracy": 0.9858281665190434
        },
        "EvaluationManifestS3Prefix": "s3://amzn-s3-demo-destination-bucket/flywheel-entity/schemaVersion=1/20230616T200543Z/evaluation/20230616T211026Z/"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFlywheelIteration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-flywheel-iteration.html)」を参照してください。

### `describe-flywheel`
<a name="comprehend_DescribeFlywheel_cli_2_topic"></a>

次のコード例は、`describe-flywheel` を使用する方法を示しています。

**AWS CLI**  
**フライホイールを記述するには**  
次の `describe-flywheel` の例では、フライホイールのプロパティを取得しています。この例では、フライホイールに関連付けられたモデルは、ドキュメントをスパムまたは非スパム (「ハム」) として分類するようにトレーニングされたカスタム分類子モデルです。  

```
aws comprehend describe-flywheel \
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel
```
出力:  

```
{
    "FlywheelProperties": {
        "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel",
        "ActiveModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-model/version/1",
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role",
        "TaskConfig": {
            "LanguageCode": "en",
            "DocumentClassificationConfig": {
                "Mode": "MULTI_CLASS",
                "Labels": [
                    "ham",
                    "spam"
                ]
            }
        },
        "DataLakeS3Uri": "s3://amzn-s3-demo-bucket/example-flywheel/schemaVersion=1/20230616T200543Z/",
        "DataSecurityConfig": {},
        "Status": "ACTIVE",
        "ModelType": "DOCUMENT_CLASSIFIER",
        "CreationTime": "2023-06-16T20:05:43.242000+00:00",
        "LastModifiedTime": "2023-06-16T20:21:43.567000+00:00"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFlywheel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-flywheel.html)」を参照してください。

### `describe-key-phrases-detection-job`
<a name="comprehend_DescribeKeyPhrasesDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-key-phrases-detection-job` を使用する方法を示しています。

**AWS CLI**  
**キーフレーズ検出ジョブを記述するには**  
次の `describe-key-phrases-detection-job` の例では、非同期キーフレーズ検出ジョブのプロパティを取得しています。  

```
aws comprehend describe-key-phrases-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "KeyPhrasesDetectionJobProperties": {
        "JobId": "69aa080c00fc68934a6a98f10EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:key-phrases-detection-job/69aa080c00fc68934a6a98f10EXAMPLE",
        "JobName": "example-key-phrases-detection-job",
        "JobStatus": "COMPLETED",
        "SubmitTime": 1686606439.177,
        "EndTime": 1686606806.157,
        "InputDataConfig": {
            "S3Uri": "s3://dereksbucket1001/EventsData/",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://dereksbucket1002/testfolder/111122223333-KP-69aa080c00fc68934a6a98f10EXAMPLE/output/output.tar.gz"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-testrole"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeKeyPhrasesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-key-phrases-detection-job.html)」を参照してください。

### `describe-pii-entities-detection-job`
<a name="comprehend_DescribePiiEntitiesDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-pii-entities-detection-job` を使用する方法を示しています。

**AWS CLI**  
**PII エンティティ検出ジョブを記述するには**  
次の `describe-pii-entities-detection-job` の例では、非同期 PII エンティティ検出ジョブのプロパティを取得しています。  

```
aws comprehend describe-pii-entities-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "PiiEntitiesDetectionJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:pii-entities-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "example-pii-entities-job",
        "JobStatus": "IN_PROGRESS",
        "SubmitTime": "2023-06-08T21:30:15.323000+00:00",
        "EndTime": "2023-06-08T21:40:23.509000+00:00",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/thefolder/111122223333-NER-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::12345678012:role/service-role/AmazonComprehendServiceRole-example-role"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePiiEntitiesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-pii-entities-detection-job.html)」を参照してください。

### `describe-resource-policy`
<a name="comprehend_DescribeResourcePolicy_cli_2_topic"></a>

次のコード例は、`describe-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**モデルにアタッチされたリソースポリシーを記述するには**  
次の `describe-resource-policy` の例では、モデルにアタッチされたリソースベースのポリシーのプロパティを取得しています。  

```
aws comprehend describe-resource-policy \
    --resource-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1
```
出力:  

```
{
    "ResourcePolicy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::444455556666:root\"},\"Action\":\"comprehend:ImportModel\",\"Resource\":\"*\"}]}",
    "CreationTime": "2023-06-19T18:44:26.028000+00:00",
    "LastModifiedTime": "2023-06-19T18:53:02.002000+00:00",
    "PolicyRevisionId": "baa675d069d07afaa2aa3106ae280f61"
}
```
詳細については、[「Amazon Comprehend デベロッパーガイド」の AWS 「アカウント間のカスタムモデルのコピー](https://docs.aws.amazon.com/comprehend/latest/dg/custom-copy.html)」を参照してください。 *Amazon Comprehend *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-resource-policy.html)」を参照してください。

### `describe-sentiment-detection-job`
<a name="comprehend_DescribeSentimentDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-sentiment-detection-job` を使用する方法を示しています。

**AWS CLI**  
**感情検出ジョブを記述するには**  
次の `describe-sentiment-detection-job` の例では、非同期感情検出ジョブのプロパティを取得しています。  

```
aws comprehend describe-sentiment-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "SentimentDetectionJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:sentiment-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "movie_review_analysis",
        "JobStatus": "IN_PROGRESS",
        "SubmitTime": "2023-06-09T23:16:15.956000+00:00",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/MovieData",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-TS-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-servicerole"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSentimentDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-sentiment-detection-job.html)」を参照してください。

### `describe-targeted-sentiment-detection-job`
<a name="comprehend_DescribeTargetedSentimentDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-targeted-sentiment-detection-job` を使用する方法を示しています。

**AWS CLI**  
**ターゲット感情検出ジョブを記述するには**  
次の `describe-targeted-sentiment-detection-job` の例では、非同期ターゲット感情検出ジョブのプロパティを取得しています。  

```
aws comprehend describe-targeted-sentiment-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "TargetedSentimentDetectionJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:targeted-sentiment-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "movie_review_analysis",
        "JobStatus": "IN_PROGRESS",
        "SubmitTime": "2023-06-09T23:16:15.956000+00:00",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/MovieData",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-TS-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-servicerole"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTargetedSentimentDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-targeted-sentiment-detection-job.html)」を参照してください。

### `describe-topics-detection-job`
<a name="comprehend_DescribeTopicsDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-topics-detection-job` を使用する方法を示しています。

**AWS CLI**  
**トピック検出ジョブを説明するには**  
次の `describe-topics-detection-job` の例では、非同期トピック検出ジョブのプロパティを取得します。  

```
aws comprehend describe-topics-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "TopicsDetectionJobProperties": {
        "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
        "JobArn": "arn:aws:comprehend:us-west-2:111122223333:topics-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
        "JobName": "example_topics_detection",
        "JobStatus": "IN_PROGRESS",
        "SubmitTime": "2023-06-09T18:44:43.414000+00:00",
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket",
            "InputFormat": "ONE_DOC_PER_LINE"
        },
        "OutputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-TOPICS-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
        },
        "NumberOfTopics": 10,
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-examplerole"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeTopicsDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/describe-topics-detection-job.html)」を参照してください。**

### `detect-dominant-language`
<a name="comprehend_DetectDominantLanguage_cli_2_topic"></a>

次のコード例は、`detect-dominant-language` を使用する方法を示しています。

**AWS CLI**  
**入力テキストの主要言語を検出するには**  
以下の `detect-dominant-language` は、入力テキストを分析し、主要言語を特定します。事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend detect-dominant-language \
    --text "It is a beautiful day in Seattle."
```
出力:  

```
{
    "Languages": [
        {
            "LanguageCode": "en",
            "Score": 0.9877256155014038
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[主要言語](https://docs.aws.amazon.com/comprehend/latest/dg/how-languages.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectDominantLanguage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/detect-dominant-language.html)」を参照してください。

### `detect-entities`
<a name="comprehend_DetectEntities_cli_2_topic"></a>

次のコード例は、`detect-entities` を使用する方法を示しています。

**AWS CLI**  
**入力テキストの名前付きエンティティを検出するには**  
次の `detect-entities` の例では、入力テキストを分析し、名前付きエンティティを返します。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend detect-entities \
    --language-code en \
    --text "Hello Zhang Wei, I am John. Your AnyCompany Financial Services, LLC credit card \
    account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st. Based on your autopay settings, \
    we will withdraw your payment on the due date from your bank account number XXXXXX1111 with the routing number XXXXX0000. \
    Customer feedback for Sunshine Spa, 123 Main St, Anywhere. Send comments to Alice at AnySpa@example.com."
```
出力:  

```
{
    "Entities": [
        {
            "Score": 0.9994556307792664,
            "Type": "PERSON",
            "Text": "Zhang Wei",
            "BeginOffset": 6,
            "EndOffset": 15
        },
        {
            "Score": 0.9981022477149963,
            "Type": "PERSON",
            "Text": "John",
            "BeginOffset": 22,
            "EndOffset": 26
        },
        {
            "Score": 0.9986887574195862,
            "Type": "ORGANIZATION",
            "Text": "AnyCompany Financial Services, LLC",
            "BeginOffset": 33,
            "EndOffset": 67
        },
        {
            "Score": 0.9959119558334351,
            "Type": "OTHER",
            "Text": "1111-XXXX-1111-XXXX",
            "BeginOffset": 88,
            "EndOffset": 107
        },
        {
            "Score": 0.9708039164543152,
            "Type": "QUANTITY",
            "Text": ".53",
            "BeginOffset": 133,
            "EndOffset": 136
        },
        {
            "Score": 0.9987268447875977,
            "Type": "DATE",
            "Text": "July 31st",
            "BeginOffset": 152,
            "EndOffset": 161
        },
        {
            "Score": 0.9858865737915039,
            "Type": "OTHER",
            "Text": "XXXXXX1111",
            "BeginOffset": 271,
            "EndOffset": 281
        },
        {
            "Score": 0.9700471758842468,
            "Type": "OTHER",
            "Text": "XXXXX0000",
            "BeginOffset": 306,
            "EndOffset": 315
        },
        {
            "Score": 0.9591118693351746,
            "Type": "ORGANIZATION",
            "Text": "Sunshine Spa",
            "BeginOffset": 340,
            "EndOffset": 352
        },
        {
            "Score": 0.9797496795654297,
            "Type": "LOCATION",
            "Text": "123 Main St",
            "BeginOffset": 354,
            "EndOffset": 365
        },
        {
            "Score": 0.994929313659668,
            "Type": "PERSON",
            "Text": "Alice",
            "BeginOffset": 394,
            "EndOffset": 399
        },
        {
            "Score": 0.9949769377708435,
            "Type": "OTHER",
            "Text": "AnySpa@example.com",
            "BeginOffset": 403,
            "EndOffset": 418
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[エンティティ](https://docs.aws.amazon.com/comprehend/latest/dg/how-entities.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/detect-entities.html)」を参照してください。**

### `detect-key-phrases`
<a name="comprehend_DetectKeyPhrases_cli_2_topic"></a>

次のコード例は、`detect-key-phrases` を使用する方法を示しています。

**AWS CLI**  
**入力テキスト内のキーフレーズを検出するには**  
次の `detect-key-phrases` の例では、入力テキストを分析し、主要な名詞フレーズを特定します。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend detect-key-phrases \
    --language-code en \
    --text "Hello Zhang Wei, I am John. Your AnyCompany Financial Services, LLC credit card \
        account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st. Based on your autopay settings, \
        we will withdraw your payment on the due date from your bank account number XXXXXX1111 with the routing number XXXXX0000. \
        Customer feedback for Sunshine Spa, 123 Main St, Anywhere. Send comments to Alice at AnySpa@example.com."
```
出力:  

```
{
    "KeyPhrases": [
        {
            "Score": 0.8996376395225525,
            "Text": "Zhang Wei",
            "BeginOffset": 6,
            "EndOffset": 15
        },
        {
            "Score": 0.9992469549179077,
            "Text": "John",
            "BeginOffset": 22,
            "EndOffset": 26
        },
        {
            "Score": 0.988385021686554,
            "Text": "Your AnyCompany Financial Services",
            "BeginOffset": 28,
            "EndOffset": 62
        },
        {
            "Score": 0.8740853071212769,
            "Text": "LLC credit card account 1111-XXXX-1111-XXXX",
            "BeginOffset": 64,
            "EndOffset": 107
        },
        {
            "Score": 0.9999437928199768,
            "Text": "a minimum payment",
            "BeginOffset": 112,
            "EndOffset": 129
        },
        {
            "Score": 0.9998900890350342,
            "Text": ".53",
            "BeginOffset": 133,
            "EndOffset": 136
        },
        {
            "Score": 0.9979453086853027,
            "Text": "July 31st",
            "BeginOffset": 152,
            "EndOffset": 161
        },
        {
            "Score": 0.9983011484146118,
            "Text": "your autopay settings",
            "BeginOffset": 172,
            "EndOffset": 193
        },
        {
            "Score": 0.9996572136878967,
            "Text": "your payment",
            "BeginOffset": 211,
            "EndOffset": 223
        },
        {
            "Score": 0.9995037317276001,
            "Text": "the due date",
            "BeginOffset": 227,
            "EndOffset": 239
        },
        {
            "Score": 0.9702621698379517,
            "Text": "your bank account number XXXXXX1111",
            "BeginOffset": 245,
            "EndOffset": 280
        },
        {
            "Score": 0.9179925918579102,
            "Text": "the routing number XXXXX0000.Customer feedback",
            "BeginOffset": 286,
            "EndOffset": 332
        },
        {
            "Score": 0.9978160858154297,
            "Text": "Sunshine Spa",
            "BeginOffset": 337,
            "EndOffset": 349
        },
        {
            "Score": 0.9706913232803345,
            "Text": "123 Main St",
            "BeginOffset": 351,
            "EndOffset": 362
        },
        {
            "Score": 0.9941995143890381,
            "Text": "comments",
            "BeginOffset": 379,
            "EndOffset": 387
        },
        {
            "Score": 0.9759287238121033,
            "Text": "Alice",
            "BeginOffset": 391,
            "EndOffset": 396
        },
        {
            "Score": 0.8376792669296265,
            "Text": "AnySpa@example.com",
            "BeginOffset": 400,
            "EndOffset": 415
        }
    ]
}
```
詳細については、「Amazon Comprehend 開発者ガイド」の「[キーフレーズ](https://docs.aws.amazon.com/comprehend/latest/dg/how-key-phrases.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectKeyPhrases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/detect-key-phrases.html)」を参照してください。**

### `detect-pii-entities`
<a name="comprehend_DetectPiiEntities_cli_2_topic"></a>

次のコード例は、`detect-pii-entities` を使用する方法を示しています。

**AWS CLI**  
**入力テキストの PII エンティティを検出するには**  
次の `detect-pii-entities` の例では、入力テキストを分析し、個人を特定できる情報 (PII) を含むエンティティを特定します。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend detect-pii-entities \
    --language-code en \
    --text "Hello Zhang Wei, I am John. Your AnyCompany Financial Services, LLC credit card \
        account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st. Based on your autopay settings, \
        we will withdraw your payment on the due date from your bank account number XXXXXX1111 with the routing number XXXXX0000. \
        Customer feedback for Sunshine Spa, 123 Main St, Anywhere. Send comments to Alice at AnySpa@example.com."
```
出力:  

```
{
    "Entities": [
        {
            "Score": 0.9998322129249573,
            "Type": "NAME",
            "BeginOffset": 6,
            "EndOffset": 15
        },
        {
            "Score": 0.9998878240585327,
            "Type": "NAME",
            "BeginOffset": 22,
            "EndOffset": 26
        },
        {
            "Score": 0.9994089603424072,
            "Type": "CREDIT_DEBIT_NUMBER",
            "BeginOffset": 88,
            "EndOffset": 107
        },
        {
            "Score": 0.9999760985374451,
            "Type": "DATE_TIME",
            "BeginOffset": 152,
            "EndOffset": 161
        },
        {
            "Score": 0.9999449253082275,
            "Type": "BANK_ACCOUNT_NUMBER",
            "BeginOffset": 271,
            "EndOffset": 281
        },
        {
            "Score": 0.9999847412109375,
            "Type": "BANK_ROUTING",
            "BeginOffset": 306,
            "EndOffset": 315
        },
        {
            "Score": 0.999925434589386,
            "Type": "ADDRESS",
            "BeginOffset": 354,
            "EndOffset": 365
        },
        {
            "Score": 0.9989161491394043,
            "Type": "NAME",
            "BeginOffset": 394,
            "EndOffset": 399
        },
        {
            "Score": 0.9994171857833862,
            "Type": "EMAIL",
            "BeginOffset": 403,
            "EndOffset": 418
        }
    ]
}
```
サポートされる PII エンティティタイプの一覧の詳細については、「Amazon Comprehend 開発者ガイド」の「[個人を特定できる情報 (PII)](https://docs.aws.amazon.com/comprehend/latest/dg/pii.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectPiiEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/detect-pii-entities.html)」を参照してください。**

### `detect-sentiment`
<a name="comprehend_DetectSentiment_cli_2_topic"></a>

次のコード例は、`detect-sentiment` を使用する方法を示しています。

**AWS CLI**  
**入力テキストの感情を検出するには**  
次の `detect-sentiment` の例では、入力テキストを分析し、一般的な感情 (`POSITIVE`、`NEUTRAL`、`MIXED`、または `NEGATIVE`) の推論を返します。  

```
aws comprehend detect-sentiment \
    --language-code en \
    --text "It is a beautiful day in Seattle"
```
出力:  

```
{
    "Sentiment": "POSITIVE",
    "SentimentScore": {
        "Positive": 0.9976957440376282,
        "Negative": 9.653854067437351e-05,
        "Neutral": 0.002169104292988777,
        "Mixed": 3.857641786453314e-05
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[感情](https://docs.aws.amazon.com/comprehend/latest/dg/how-sentiment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectSentiment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/detect-sentiment.html)」を参照してください。

### `detect-syntax`
<a name="comprehend_DetectSyntax_cli_2_topic"></a>

次のコード例は、`detect-syntax` を使用する方法を示しています。

**AWS CLI**  
**入力テキスト内の品詞を検出するには**  
次の `detect-syntax` の例では、入力テキストの構文を分析し、さまざまな品詞を返します。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend detect-syntax \
    --language-code en \
    --text "It is a beautiful day in Seattle."
```
出力:  

```
{
    "SyntaxTokens": [
        {
            "TokenId": 1,
            "Text": "It",
            "BeginOffset": 0,
            "EndOffset": 2,
            "PartOfSpeech": {
                "Tag": "PRON",
                "Score": 0.9999740719795227
            }
        },
        {
            "TokenId": 2,
            "Text": "is",
            "BeginOffset": 3,
            "EndOffset": 5,
            "PartOfSpeech": {
                "Tag": "VERB",
                "Score": 0.999901294708252
            }
        },
        {
            "TokenId": 3,
            "Text": "a",
            "BeginOffset": 6,
            "EndOffset": 7,
            "PartOfSpeech": {
                "Tag": "DET",
                "Score": 0.9999938607215881
            }
        },
        {
            "TokenId": 4,
            "Text": "beautiful",
            "BeginOffset": 8,
            "EndOffset": 17,
            "PartOfSpeech": {
                "Tag": "ADJ",
                "Score": 0.9987351894378662
            }
        },
        {
            "TokenId": 5,
            "Text": "day",
            "BeginOffset": 18,
            "EndOffset": 21,
            "PartOfSpeech": {
                "Tag": "NOUN",
                "Score": 0.9999796748161316
            }
        },
        {
            "TokenId": 6,
            "Text": "in",
            "BeginOffset": 22,
            "EndOffset": 24,
            "PartOfSpeech": {
                "Tag": "ADP",
                "Score": 0.9998047947883606
            }
        },
        {
            "TokenId": 7,
            "Text": "Seattle",
            "BeginOffset": 25,
            "EndOffset": 32,
            "PartOfSpeech": {
                "Tag": "PROPN",
                "Score": 0.9940530061721802
            }
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[構文分析](https://docs.aws.amazon.com/comprehend/latest/dg/how-syntax.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectSyntax](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/detect-syntax.html)」を参照してください。

### `detect-targeted-sentiment`
<a name="comprehend_DetectTargetedSentiment_cli_2_topic"></a>

次のコード例は、`detect-targeted-sentiment` を使用する方法を示しています。

**AWS CLI**  
**入力テキスト内の名前付きエンティティのターゲット感情を検出するには**  
次の `detect-targeted-sentiment` の例では、入力テキストを分析し、名前付きエンティティと、各エンティティに関連付けられたターゲット感情を返します。予測ごとに、事前トレーニング済みモデルの信頼スコアも出力されます。  

```
aws comprehend detect-targeted-sentiment \
    --language-code en \
    --text "I do not enjoy January because it is too cold but August is the perfect temperature"
```
出力:  

```
{
    "Entities": [
        {
            "DescriptiveMentionIndex": [
                0
            ],
            "Mentions": [
                {
                    "Score": 0.9999979734420776,
                    "GroupScore": 1.0,
                    "Text": "I",
                    "Type": "PERSON",
                    "MentionSentiment": {
                        "Sentiment": "NEUTRAL",
                        "SentimentScore": {
                            "Positive": 0.0,
                            "Negative": 0.0,
                            "Neutral": 1.0,
                            "Mixed": 0.0
                        }
                    },
                    "BeginOffset": 0,
                    "EndOffset": 1
                }
            ]
        },
        {
            "DescriptiveMentionIndex": [
                0
            ],
            "Mentions": [
                {
                    "Score": 0.9638869762420654,
                    "GroupScore": 1.0,
                    "Text": "January",
                    "Type": "DATE",
                    "MentionSentiment": {
                        "Sentiment": "NEGATIVE",
                        "SentimentScore": {
                            "Positive": 0.0031610000878572464,
                            "Negative": 0.9967250227928162,
                            "Neutral": 0.00011100000119768083,
                            "Mixed": 1.9999999949504854e-06
                        }
                    },
                    "BeginOffset": 15,
                    "EndOffset": 22
                }
            ]
        },
        {
            "DescriptiveMentionIndex": [
                0
            ],
            "Mentions": [
                {
                {
                    "Score": 0.9664419889450073,
                    "GroupScore": 1.0,
                    "Text": "August",
                    "Type": "DATE",
                    "MentionSentiment": {
                        "Sentiment": "POSITIVE",
                        "SentimentScore": {
                            "Positive": 0.9999549984931946,
                            "Negative": 3.999999989900971e-06,
                            "Neutral": 4.099999932805076e-05,
                            "Mixed": 0.0
                        }
                    },
                    "BeginOffset": 50,
                    "EndOffset": 56
                }
            ]
        },
        {
            "DescriptiveMentionIndex": [
                0
            ],
            "Mentions": [
                {
                    "Score": 0.9803199768066406,
                    "GroupScore": 1.0,
                    "Text": "temperature",
                    "Type": "ATTRIBUTE",
                    "MentionSentiment": {
                        "Sentiment": "POSITIVE",
                        "SentimentScore": {
                            "Positive": 1.0,
                            "Negative": 0.0,
                            "Neutral": 0.0,
                            "Mixed": 0.0
                        }
                    },
                    "BeginOffset": 77,
                    "EndOffset": 88
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Targeted Sentiment](https://docs.aws.amazon.com/comprehend/latest/dg/how-targeted-sentiment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectTargetedSentiment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/detect-targeted-sentiment.html)」を参照してください。

### `import-model`
<a name="comprehend_ImportModel_cli_2_topic"></a>

次のコード例は、`import-model` を使用する方法を示しています。

**AWS CLI**  
**モデルをインポートするには**  
次の の`import-model`例では、別の AWS アカウントからモデルをインポートします。アカウント `444455556666` のドキュメント分類子モデルには、アカウント `111122223333` がモデルをインポートできるようにするリソースベースのポリシーがあります。  

```
aws comprehend import-model \
    --source-model-arn arn:aws:comprehend:us-west-2:444455556666:document-classifier/example-classifier
```
出力:  

```
{
    "ModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier"
}
```
詳細については、[「Amazon Comprehend デベロッパーガイド」の AWS 「アカウント間のカスタムモデルのコピー](https://docs.aws.amazon.com/comprehend/latest/dg/custom-copy.html)」を参照してください。 *Amazon Comprehend *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/import-model.html)」を参照してください。

### `list-datasets`
<a name="comprehend_ListDatasets_cli_2_topic"></a>

次のコード例は、`list-datasets` を使用する方法を示しています。

**AWS CLI**  
**すべてのフライホイールデータセットを一覧表示するには**  
次の `list-datasets` の例では、フライホイールに関連付けられているすべてのデータセットを一覧表示しています。  

```
aws comprehend list-datasets \
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity
```
出力:  

```
{
    "DatasetPropertiesList": [
        {
            "DatasetArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity/dataset/example-dataset-1",
            "DatasetName": "example-dataset-1",
            "DatasetType": "TRAIN",
            "DatasetS3Uri": "s3://amzn-s3-demo-bucket/flywheel-entity/schemaVersion=1/20230616T200543Z/datasets/example-dataset-1/20230616T203710Z/",
            "Status": "CREATING",
            "CreationTime": "2023-06-16T20:37:10.400000+00:00"
        },
        {
            "DatasetArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity/dataset/example-dataset-2",
            "DatasetName": "example-dataset-2",
            "DatasetType": "TRAIN",
            "DatasetS3Uri": "s3://amzn-s3-demo-bucket/flywheel-entity/schemaVersion=1/20230616T200543Z/datasets/example-dataset-2/20230616T200607Z/",
            "Description": "TRAIN Dataset created by Flywheel creation.",
            "Status": "COMPLETED",
            "NumberOfDocuments": 5572,
            "CreationTime": "2023-06-16T20:06:07.722000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDatasets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-datasets.html)」を参照してください。

### `list-document-classification-jobs`
<a name="comprehend_ListDocumentClassificationJobs_cli_2_topic"></a>

次のコード例は、`list-document-classification-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべてのドキュメント分類ジョブを一覧表示するには**  
次の `list-document-classification-jobs` の例では、すべてのドキュメント分類ジョブを一覧表示しています。  

```
aws comprehend list-document-classification-jobs
```
出力:  

```
{
    "DocumentClassificationJobPropertiesList": [
        {
            "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:1234567890101:document-classification-job/123456abcdeb0e11022f22a11EXAMPLE",
            "JobName": "exampleclassificationjob",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-14T17:09:51.788000+00:00",
            "EndTime": "2023-06-14T17:15:58.582000+00:00",
            "DocumentClassifierArn": "arn:aws:comprehend:us-west-2:1234567890101:document-classifier/mymodel/version/12",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/jobdata/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/1234567890101-CLN-e758dd56b824aa717ceab551f11749fb/output/output.tar.gz"
            },
            "DataAccessRoleArn": "arn:aws:iam::1234567890101:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "123456abcdeb0e11022f22a1EXAMPLE2",
            "JobArn": "arn:aws:comprehend:us-west-2:1234567890101:document-classification-job/123456abcdeb0e11022f22a1EXAMPLE2",
            "JobName": "exampleclassificationjob2",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-14T17:22:39.829000+00:00",
            "EndTime": "2023-06-14T17:28:46.107000+00:00",
            "DocumentClassifierArn": "arn:aws:comprehend:us-west-2:1234567890101:document-classifier/mymodel/version/12",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/jobdata/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/1234567890101-CLN-123456abcdeb0e11022f22a1EXAMPLE2/output/output.tar.gz"
            },
            "DataAccessRoleArn": "arn:aws:iam::1234567890101:role/service-role/AmazonComprehendServiceRole-example-role"
        }
    ]
}
```
詳細については、「Amazon Comprehend 開発者ガイド」の「[カスタム分類](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDocumentClassificationJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-document-classification-jobs.html)」を参照してください。

### `list-document-classifier-summaries`
<a name="comprehend_ListDocumentClassifierSummaries_cli_2_topic"></a>

次のコード例は、`list-document-classifier-summaries` を使用する方法を示しています。

**AWS CLI**  
**作成されたすべてのドキュメント分類子の概要を一覧表示するには**  
次の `list-document-classifier-summaries` の例では、作成されたすべてのドキュメント分類子の概要を一覧表示しています。  

```
aws comprehend list-document-classifier-summaries
```
出力:  

```
{
    "DocumentClassifierSummariesList": [
        {
            "DocumentClassifierName": "example-classifier-1",
            "NumberOfVersions": 1,
            "LatestVersionCreatedAt": "2023-06-13T22:07:59.825000+00:00",
            "LatestVersionName": "1",
            "LatestVersionStatus": "TRAINED"
        },
        {
            "DocumentClassifierName": "example-classifier-2",
            "NumberOfVersions": 2,
            "LatestVersionCreatedAt": "2023-06-13T21:54:59.589000+00:00",
            "LatestVersionName": "2",
            "LatestVersionStatus": "TRAINED"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[カスタムモデルの作成と管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-models.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDocumentClassifierSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-document-classifier-summaries.html)」を参照してください。

### `list-document-classifiers`
<a name="comprehend_ListDocumentClassifiers_cli_2_topic"></a>

次のコード例は、`list-document-classifiers` を使用する方法を示しています。

**AWS CLI**  
**すべてのドキュメント分類子を一覧表示するには**  
次の `list-document-classifiers` の例は、トレーニング済みおよびトレーニング中のすべてのドキュメント分類子モデルを一覧表示します。  

```
aws comprehend list-document-classifiers
```
出力:  

```
{
    "DocumentClassifierPropertiesList": [
        {
            "DocumentClassifierArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier1",
            "LanguageCode": "en",
            "Status": "TRAINED",
            "SubmitTime": "2023-06-13T19:04:15.735000+00:00",
            "EndTime": "2023-06-13T19:42:31.752000+00:00",
            "TrainingStartTime": "2023-06-13T19:08:20.114000+00:00",
            "TrainingEndTime": "2023-06-13T19:41:35.080000+00:00",
            "InputDataConfig": {
                "DataFormat": "COMPREHEND_CSV",
                "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata"
            },
            "OutputDataConfig": {},
            "ClassifierMetadata": {
                "NumberOfLabels": 3,
                "NumberOfTrainedDocuments": 5016,
                "NumberOfTestDocuments": 557,
                "EvaluationMetrics": {
                    "Accuracy": 0.9856,
                    "Precision": 0.9919,
                    "Recall": 0.9459,
                    "F1Score": 0.9673,
                    "MicroPrecision": 0.9856,
                    "MicroRecall": 0.9856,
                    "MicroF1Score": 0.9856,
                    "HammingLoss": 0.0144
                }
            },
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-testorle",
            "Mode": "MULTI_CLASS"
        },
        {
            "DocumentClassifierArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier2",
            "LanguageCode": "en",
            "Status": "TRAINING",
            "SubmitTime": "2023-06-13T21:20:28.690000+00:00",
            "InputDataConfig": {
                "DataFormat": "COMPREHEND_CSV",
                "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata"
            },
            "OutputDataConfig": {},
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-testorle",
            "Mode": "MULTI_CLASS"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[カスタムモデルの作成と管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-models.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDocumentClassifiers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-document-classifiers.html)」を参照してください。

### `list-dominant-language-detection-jobs`
<a name="comprehend_ListDominantLanguageDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-dominant-language-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべての主要言語検出ジョブを一覧表示するには**  
次の `list-dominant-language-detection-jobs` の例では、進行中および完了したすべての非同期主要言語検出ジョブを一覧表示しています。  

```
aws comprehend list-dominant-language-detection-jobs
```
出力:  

```
{
    "DominantLanguageDetectionJobPropertiesList": [
        {
            "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:dominant-language-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
            "JobName": "languageanalysis1",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-09T18:10:38.037000+00:00",
            "EndTime": "2023-06-09T18:18:45.498000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-LANGUAGE-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
            },
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:dominant-language-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
            "JobName": "languageanalysis2",
            "JobStatus": "STOPPED",
            "SubmitTime": "2023-06-09T18:16:33.690000+00:00",
            "EndTime": "2023-06-09T18:24:40.608000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-LANGUAGE-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
            },
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDominantLanguageDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-dominant-language-detection-jobs.html)」を参照してください。

### `list-endpoints`
<a name="comprehend_ListEndpoints_cli_2_topic"></a>

次のコード例は、`list-endpoints` を使用する方法を示しています。

**AWS CLI**  
**すべてのエンドポイントを一覧表示するには**  
次の `list-endpoints` の例では、すべてのアクティブなモデル固有のエンドポイントを一覧表示しています。  

```
aws comprehend list-endpoints
```
出力:  

```
{
    "EndpointPropertiesList": [
        {
            "EndpointArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/ExampleClassifierEndpoint",
            "Status": "IN_SERVICE",
            "ModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier1",
            "DesiredModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier1",
            "DesiredInferenceUnits": 1,
            "CurrentInferenceUnits": 1,
            "CreationTime": "2023-06-13T20:32:54.526000+00:00",
            "LastModifiedTime": "2023-06-13T20:32:54.526000+00:00"
        },
        {
            "EndpointArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/ExampleClassifierEndpoint2",
            "Status": "IN_SERVICE",
            "ModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier2",
            "DesiredModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier2",
            "DesiredInferenceUnits": 1,
            "CurrentInferenceUnits": 1,
            "CreationTime": "2023-06-13T20:32:54.526000+00:00",
            "LastModifiedTime": "2023-06-13T20:32:54.526000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-endpoints.html)」を参照してください。

### `list-entities-detection-jobs`
<a name="comprehend_ListEntitiesDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-entities-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべてのエンティティ検出ジョブを一覧表示するには**  
次の `list-entities-detection-jobs` の例では、すべての非同期エンティティ検出ジョブを一覧表示しています。  

```
aws comprehend list-entities-detection-jobs
```
出力:  

```
{
    "EntitiesDetectionJobPropertiesList": [
        {
            "JobId": "468af39c28ab45b83eb0c4ab9EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:entities-detection-job/468af39c28ab45b83eb0c4ab9EXAMPLE",
            "JobName": "example-entities-detection",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-08T20:57:46.476000+00:00",
            "EndTime": "2023-06-08T21:05:53.718000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/111122223333-NER-468af39c28ab45b83eb0c4ab9EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "809691caeaab0e71406f80a28EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:entities-detection-job/809691caeaab0e71406f80a28EXAMPLE",
            "JobName": "example-entities-detection-2",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-08T21:30:15.323000+00:00",
            "EndTime": "2023-06-08T21:40:23.509000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/111122223333-NER-809691caeaab0e71406f80a28EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "e00597c36b448b91d70dea165EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:entities-detection-job/e00597c36b448b91d70dea165EXAMPLE",
            "JobName": "example-entities-detection-3",
            "JobStatus": "STOPPED",
            "SubmitTime": "2023-06-08T22:19:28.528000+00:00",
            "EndTime": "2023-06-08T22:27:33.991000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/111122223333-NER-e00597c36b448b91d70dea165EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[エンティティ](https://docs.aws.amazon.com/comprehend/latest/dg/how-entities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEntitiesDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-entities-detection-jobs.html)」を参照してください。

### `list-entity-recognizer-summaries`
<a name="comprehend_ListEntityRecognizerSummaries_cli_2_topic"></a>

次のコード例は、`list-entity-recognizer-summaries` を使用する方法を示しています。

**AWS CLI**  
**作成されたすべてのエンティティレコグナイザーの概要を一覧表示するには**  
次の `list-entity-recognizer-summaries` の例では、すべてのエンティティレコグナイザーの概要を一覧表示しています。  

```
aws comprehend list-entity-recognizer-summaries
```
出力:  

```
{
    "EntityRecognizerSummariesList": [
        {
            "RecognizerName": "entity-recognizer-3",
            "NumberOfVersions": 2,
            "LatestVersionCreatedAt": "2023-06-15T23:15:07.621000+00:00",
            "LatestVersionName": "2",
            "LatestVersionStatus": "STOP_REQUESTED"
        },
        {
            "RecognizerName": "entity-recognizer-2",
            "NumberOfVersions": 1,
            "LatestVersionCreatedAt": "2023-06-14T22:55:27.805000+00:00",
            "LatestVersionName": "2"
            "LatestVersionStatus": "TRAINED"
        },
        {
            "RecognizerName": "entity-recognizer-1",
            "NumberOfVersions": 1,
            "LatestVersionCreatedAt": "2023-06-14T20:44:59.631000+00:00",
            "LatestVersionName": "1",
            "LatestVersionStatus": "TRAINED"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Custom entity recognition](https://docs.aws.amazon.com/comprehend/latest/dg/custom-entity-recognition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEntityRecognizerSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-entity-recognizer-summaries.html)」を参照してください。

### `list-entity-recognizers`
<a name="comprehend_ListEntityRecognizers_cli_2_topic"></a>

次のコード例は、`list-entity-recognizers` を使用する方法を示しています。

**AWS CLI**  
**すべてのカスタムエンティティレコグナイザーを一覧表示するには**  
次の `list-entity-recognizers` の例では、作成されたすべてのカスタムエンティティレコグナイザーを一覧表示しています。  

```
aws comprehend list-entity-recognizers
```
出力:  

```
{
    "EntityRecognizerPropertiesList": [
        {
            "EntityRecognizerArn": "arn:aws:comprehend:us-west-2:111122223333:entity-recognizer/EntityRecognizer/version/1",
            "LanguageCode": "en",
            "Status": "TRAINED",
            "SubmitTime": "2023-06-14T20:44:59.631000+00:00",
            "EndTime": "2023-06-14T20:59:19.532000+00:00",
            "TrainingStartTime": "2023-06-14T20:48:52.811000+00:00",
            "TrainingEndTime": "2023-06-14T20:58:11.473000+00:00",
            "InputDataConfig": {
                "DataFormat": "COMPREHEND_CSV",
                "EntityTypes": [
                    {
                        "Type": "BUSINESS"
                    }
                ],
                "Documents": {
                    "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata/dataset/",
                    "InputFormat": "ONE_DOC_PER_LINE"
                },
                "EntityList": {
                    "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata/entity.csv"
                }
            },
            "RecognizerMetadata": {
                "NumberOfTrainedDocuments": 1814,
                "NumberOfTestDocuments": 486,
                "EvaluationMetrics": {
                    "Precision": 100.0,
                    "Recall": 100.0,
                    "F1Score": 100.0
                },
                "EntityTypes": [
                    {
                        "Type": "BUSINESS",
                        "EvaluationMetrics": {
                            "Precision": 100.0,
                            "Recall": 100.0,
                            "F1Score": 100.0
                        },
                        "NumberOfTrainMentions": 1520
                    }
                ]
            },
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-servicerole",
            "VersionName": "1"
        },
        {
            "EntityRecognizerArn": "arn:aws:comprehend:us-west-2:111122223333:entity-recognizer/entityrecognizer3",
            "LanguageCode": "en",
            "Status": "TRAINED",
            "SubmitTime": "2023-06-14T22:57:51.056000+00:00",
            "EndTime": "2023-06-14T23:14:13.894000+00:00",
            "TrainingStartTime": "2023-06-14T23:01:33.984000+00:00",
            "TrainingEndTime": "2023-06-14T23:13:02.984000+00:00",
            "InputDataConfig": {
                "DataFormat": "COMPREHEND_CSV",
                "EntityTypes": [
                    {
                        "Type": "DEVICE"
                    }
                ],
                "Documents": {
                    "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata/raw_txt.csv",
                    "InputFormat": "ONE_DOC_PER_LINE"
                },
                "EntityList": {
                    "S3Uri": "s3://amzn-s3-demo-bucket/trainingdata/entity_list.csv"
                }
            },
            "RecognizerMetadata": {
                "NumberOfTrainedDocuments": 4616,
                "NumberOfTestDocuments": 3489,
                "EvaluationMetrics": {
                    "Precision": 98.54227405247813,
                    "Recall": 100.0,
                    "F1Score": 99.26578560939794
                },
                "EntityTypes": [
                    {
                        "Type": "DEVICE",
                        "EvaluationMetrics": {
                            "Precision": 98.54227405247813,
                            "Recall": 100.0,
                            "F1Score": 99.26578560939794
                        },
                        "NumberOfTrainMentions": 2764
                    }
                ]
            },
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-servicerole"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Custom entity recognition](https://docs.aws.amazon.com/comprehend/latest/dg/custom-entity-recognition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEntityRecognizers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-entity-recognizers.html)」を参照してください。

### `list-events-detection-jobs`
<a name="comprehend_ListEventsDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-events-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべてのイベント検出ジョブを一覧表示するには**  
次の `list-events-detection-jobs` の例では、すべての非同期イベント検出ジョブを一覧表示しています。  

```
aws comprehend list-events-detection-jobs
```
出力:  

```
{
    "EventsDetectionJobPropertiesList": [
        {
            "JobId": "aa9593f9203e84f3ef032ce18EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:1111222233333:events-detection-job/aa9593f9203e84f3ef032ce18EXAMPLE",
            "JobName": "events_job_1",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-12T19:14:57.751000+00:00",
            "EndTime": "2023-06-12T19:21:04.962000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-source-bucket/EventsData/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/1111222233333-EVENTS-aa9593f9203e84f3ef032ce18EXAMPLE/output/"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::1111222233333:role/service-role/AmazonComprehendServiceRole-example-role",
            "TargetEventTypes": [
                "BANKRUPTCY",
                "EMPLOYMENT",
                "CORPORATE_ACQUISITION",
                "CORPORATE_MERGER",
                "INVESTMENT_GENERAL"
            ]
        },
        {
            "JobId": "4a990a2f7e82adfca6e171135EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:1111222233333:events-detection-job/4a990a2f7e82adfca6e171135EXAMPLE",
            "JobName": "events_job_2",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-12T19:55:43.702000+00:00",
            "EndTime": "2023-06-12T20:03:49.893000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-source-bucket/EventsData/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/1111222233333-EVENTS-4a990a2f7e82adfca6e171135EXAMPLE/output/"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::1111222233333:role/service-role/AmazonComprehendServiceRole-example-role",
            "TargetEventTypes": [
                "BANKRUPTCY",
                "EMPLOYMENT",
                "CORPORATE_ACQUISITION",
                "CORPORATE_MERGER",
                "INVESTMENT_GENERAL"
            ]
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEventsDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-events-detection-jobs.html)」を参照してください。

### `list-flywheel-iteration-history`
<a name="comprehend_ListFlywheelIterationHistory_cli_2_topic"></a>

次のコード例は、`list-flywheel-iteration-history` を使用する方法を示しています。

**AWS CLI**  
**すべてのフライホイールイテレーション履歴を一覧表示するには**  
次の `list-flywheel-iteration-history` の例では、すべてのフライホイールイテレーションを一覧表示しています。  

```
aws comprehend list-flywheel-iteration-history
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel
```
出力:  

```
{
    "FlywheelIterationPropertiesList": [
        {
            "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel",
            "FlywheelIterationId": "20230619TEXAMPLE",
            "CreationTime": "2023-06-19T04:00:32.594000+00:00",
            "EndTime": "2023-06-19T04:00:49.248000+00:00",
            "Status": "COMPLETED",
            "Message": "FULL_ITERATION: Flywheel iteration performed all functions successfully.",
            "EvaluatedModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1",
            "EvaluatedModelMetrics": {
                "AverageF1Score": 0.7742663922375772,
                "AverageF1Score": 0.9876464664646313,
                "AveragePrecision": 0.9800000253081214,
                "AverageRecall": 0.9445600253081214,
                "AverageAccuracy": 0.9997281665190434
            },
            "EvaluationManifestS3Prefix": "s3://amzn-s3-demo-bucket/example-flywheel/schemaVersion=1/20230619TEXAMPLE/evaluation/20230619TEXAMPLE/"
        },
        {
            "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel-2",
            "FlywheelIterationId": "20230616TEXAMPLE",
            "CreationTime": "2023-06-16T21:10:26.385000+00:00",
            "EndTime": "2023-06-16T23:33:16.827000+00:00",
            "Status": "COMPLETED",
            "Message": "FULL_ITERATION: Flywheel iteration performed all functions successfully.",
            "EvaluatedModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/spamvshamclassify/version/1",
            "EvaluatedModelMetrics": {
                "AverageF1Score": 0.7742663922375772,
                "AverageF1Score": 0.9767700253081214,
                "AveragePrecision": 0.9767700253081214,
                "AverageRecall": 0.9767700253081214,
                "AverageAccuracy": 0.9858281665190434
            },
            "EvaluationManifestS3Prefix": "s3://amzn-s3-demo-bucket/example-flywheel-2/schemaVersion=1/20230616TEXAMPLE/evaluation/20230616TEXAMPLE/"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFlywheelIterationHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-flywheel-iteration-history.html)」を参照してください。

### `list-flywheels`
<a name="comprehend_ListFlywheels_cli_2_topic"></a>

次のコード例は、`list-flywheels` を使用する方法を示しています。

**AWS CLI**  
**すべてのフライホイールを一覧表示するには**  
次の `list-flywheels` の例では、作成されたすべてのフライホイールを一覧表示しています。  

```
aws comprehend list-flywheels
```
出力:  

```
{
    "FlywheelSummaryList": [
        {
            "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel-1",
            "ActiveModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier/version/1",
            "DataLakeS3Uri": "s3://amzn-s3-demo-bucket/example-flywheel-1/schemaVersion=1/20230616T200543Z/",
            "Status": "ACTIVE",
            "ModelType": "DOCUMENT_CLASSIFIER",
            "CreationTime": "2023-06-16T20:05:43.242000+00:00",
            "LastModifiedTime": "2023-06-19T04:00:43.027000+00:00",
            "LatestFlywheelIteration": "20230619T040032Z"
        },
        {
            "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel-2",
            "ActiveModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/exampleclassifier2/version/1",
            "DataLakeS3Uri": "s3://amzn-s3-demo-bucket/example-flywheel-2/schemaVersion=1/20220616T200543Z/",
            "Status": "ACTIVE",
            "ModelType": "DOCUMENT_CLASSIFIER",
            "CreationTime": "2022-06-16T20:05:43.242000+00:00",
            "LastModifiedTime": "2022-06-19T04:00:43.027000+00:00",
            "LatestFlywheelIteration": "20220619T040032Z"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFlywheels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-flywheels.html)」を参照してください。

### `list-key-phrases-detection-jobs`
<a name="comprehend_ListKeyPhrasesDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-key-phrases-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべてのキーフレーズ検出ジョブを一覧表示するには**  
次の `list-key-phrases-detection-jobs` の例では、進行中および完了したすべての非同期キーフレーズ検出ジョブを一覧表示しています。  

```
aws comprehend list-key-phrases-detection-jobs
```
出力:  

```
{
    "KeyPhrasesDetectionJobPropertiesList": [
        {
            "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:key-phrases-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
            "JobName": "keyphrasesanalysis1",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-08T22:31:43.767000+00:00",
            "EndTime": "2023-06-08T22:39:52.565000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-source-bucket/AsyncBatchJobs/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-KP-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "123456abcdeb0e11022f22a33EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:key-phrases-detection-job/123456abcdeb0e11022f22a33EXAMPLE",
            "JobName": "keyphrasesanalysis2",
            "JobStatus": "STOPPED",
            "SubmitTime": "2023-06-08T22:57:52.154000+00:00",
            "EndTime": "2023-06-08T23:05:48.385000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-KP-123456abcdeb0e11022f22a33EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "123456abcdeb0e11022f22a44EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:key-phrases-detection-job/123456abcdeb0e11022f22a44EXAMPLE",
            "JobName": "keyphrasesanalysis3",
            "JobStatus": "FAILED",
            "Message": "NO_READ_ACCESS_TO_INPUT: The provided data access role does not have proper access to the input data.",
            "SubmitTime": "2023-06-09T16:47:04.029000+00:00",
            "EndTime": "2023-06-09T16:47:18.413000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-KP-123456abcdeb0e11022f22a44EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListKeyPhrasesDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-key-phrases-detection-jobs.html)」を参照してください。

### `list-pii-entities-detection-jobs`
<a name="comprehend_ListPiiEntitiesDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-pii-entities-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべての PII エンティティ検出ジョブを一覧表示するには**  
次の `list-pii-entities-detection-jobs` の例では、進行中および完了したすべての非同期 PII 検出ジョブを一覧表示しています。  

```
aws comprehend list-pii-entities-detection-jobs
```
出力:  

```
{
    "PiiEntitiesDetectionJobPropertiesList": [
        {
            "JobId": "6f9db0c42d0c810e814670ee4EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:pii-entities-detection-job/6f9db0c42d0c810e814670ee4EXAMPLE",
            "JobName": "example-pii-detection-job",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-09T21:02:46.241000+00:00",
            "EndTime": "2023-06-09T21:12:52.602000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-source-bucket/111122223333-PII-6f9db0c42d0c810e814670ee4EXAMPLE/output/"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role",
            "Mode": "ONLY_OFFSETS"
        },
        {
            "JobId": "d927562638cfa739331a99b3cEXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:pii-entities-detection-job/d927562638cfa739331a99b3cEXAMPLE",
            "JobName": "example-pii-detection-job-2",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-09T21:20:58.211000+00:00",
            "EndTime": "2023-06-09T21:31:06.027000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/AsyncBatchJobs/",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/111122223333-PII-d927562638cfa739331a99b3cEXAMPLE/output/"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role",
            "Mode": "ONLY_OFFSETS"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPiiEntitiesDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-pii-entities-detection-jobs.html)」を参照してください。

### `list-sentiment-detection-jobs`
<a name="comprehend_ListSentimentDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-sentiment-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべての感情検出ジョブを一覧表示するには**  
次の `list-sentiment-detection-jobs` の例では、進行中および完了したすべての非同期感情検出ジョブを一覧表示しています。  

```
aws comprehend list-sentiment-detection-jobs
```
出力:  

```
{
    "SentimentDetectionJobPropertiesList": [
        {
            "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:sentiment-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
            "JobName": "example-sentiment-detection-job",
            "JobStatus": "IN_PROGRESS",
            "SubmitTime": "2023-06-09T22:42:20.545000+00:00",
            "EndTime": "2023-06-09T22:52:27.416000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/MovieData",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-TS-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "123456abcdeb0e11022f22a1EXAMPLE2",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:sentiment-detection-job/123456abcdeb0e11022f22a1EXAMPLE2",
            "JobName": "example-sentiment-detection-job-2",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-09T23:16:15.956000+00:00",
            "EndTime": "2023-06-09T23:26:00.168000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/MovieData2",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-TS-123456abcdeb0e11022f22a1EXAMPLE2/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSentimentDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-sentiment-detection-jobs.html)」を参照してください。

### `list-tags-for-resource`
<a name="comprehend_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Amazon Comprehend リソースのタグを一覧表示しています。  

```
aws comprehend list-tags-for-resource \
    --resource-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1
```
出力:  

```
{
    "ResourceArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1",
    "Tags": [
        {
            "Key": "Department",
            "Value": "Finance"
        },
        {
            "Key": "location",
            "Value": "Seattle"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Tagging your resources](https://docs.aws.amazon.com/comprehend/latest/dg/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-tags-for-resource.html)」を参照してください。

### `list-targeted-sentiment-detection-jobs`
<a name="comprehend_ListTargetedSentimentDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-targeted-sentiment-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべてのターゲット感情検出ジョブを一覧表示するには**  
次の `list-targeted-sentiment-detection-jobs` の例では、進行中および完了したすべての非同期ターゲット感情検出ジョブを一覧表示しています。  

```
aws comprehend list-targeted-sentiment-detection-jobs
```
出力:  

```
{
    "TargetedSentimentDetectionJobPropertiesList": [
        {
            "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:targeted-sentiment-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
            "JobName": "example-targeted-sentiment-detection-job",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-09T22:42:20.545000+00:00",
            "EndTime": "2023-06-09T22:52:27.416000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/MovieData",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-TS-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-IOrole"
        },
        {
            "JobId": "123456abcdeb0e11022f22a1EXAMPLE2",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:targeted-sentiment-detection-job/123456abcdeb0e11022f22a1EXAMPLE2",
            "JobName": "example-targeted-sentiment-detection-job-2",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-09T23:16:15.956000+00:00",
            "EndTime": "2023-06-09T23:26:00.168000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/MovieData2",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/testfolder/111122223333-TS-123456abcdeb0e11022f22a1EXAMPLE2/output/output.tar.gz"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTargetedSentimentDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-targeted-sentiment-detection-jobs.html)」を参照してください。

### `list-topics-detection-jobs`
<a name="comprehend_ListTopicsDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-topics-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**トピック検出ジョブをすべて一覧表示するには**  
次の `list-topics-detection-jobs` の例では、進行中および完了した非同期トピック検出ジョブをすべて一覧表示します。  

```
aws comprehend list-topics-detection-jobs
```
出力:  

```
{
    "TopicsDetectionJobPropertiesList": [
        {
            "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:topics-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
            "JobName" "topic-analysis-1"
            "JobStatus": "IN_PROGRESS",
            "SubmitTime": "2023-06-09T18:40:35.384000+00:00",
            "EndTime": "2023-06-09T18:46:41.936000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/111122223333-TOPICS-123456abcdeb0e11022f22a11EXAMPLE/output/output.tar.gz"
            },
            "NumberOfTopics": 10,
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "123456abcdeb0e11022f22a1EXAMPLE2",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:topics-detection-job/123456abcdeb0e11022f22a1EXAMPLE2",
            "JobName": "topic-analysis-2",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2023-06-09T18:44:43.414000+00:00",
            "EndTime": "2023-06-09T18:50:50.872000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/111122223333-TOPICS-123456abcdeb0e11022f22a1EXAMPLE2/output/output.tar.gz"
            },
            "NumberOfTopics": 10,
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        },
        {
            "JobId": "123456abcdeb0e11022f22a1EXAMPLE3",
            "JobArn": "arn:aws:comprehend:us-west-2:111122223333:topics-detection-job/123456abcdeb0e11022f22a1EXAMPLE3",
            "JobName": "topic-analysis-2",
            "JobStatus": "IN_PROGRESS",
            "SubmitTime": "2023-06-09T18:50:56.737000+00:00",
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket",
                "InputFormat": "ONE_DOC_PER_LINE"
            },
            "OutputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-destination-bucket/thefolder/111122223333-TOPICS-123456abcdeb0e11022f22a1EXAMPLE3/output/output.tar.gz"
            },
            "NumberOfTopics": 10,
            "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role"
        }
    ]
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTopicsDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/list-topics-detection-jobs.html)」を参照してください。

### `put-resource-policy`
<a name="comprehend_PutResourcePolicy_cli_2_topic"></a>

次のコード例は、`put-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースベースのポリシーをアタッチするには**  
次の`put-resource-policy`例では、リソースベースのポリシーをモデルにアタッチして、 を別の AWS アカウントでインポートできるようにします。ポリシーがアカウント `111122223333` のモデルにアタッチされ、アカウント `444455556666` がモデルをインポートできます。  

```
aws comprehend put-resource-policy \
    --resource-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1 \
    --resource-policy '{"Version":"2012-10-17",		 	 	 "Statement":[{"Effect":"Allow","Action":"comprehend:ImportModel","Resource":"*","Principal":{"AWS":["arn:aws:iam::444455556666:root"]}}]}'
```
出力:  

```
{
    "PolicyRevisionId": "aaa111d069d07afaa2aa3106aEXAMPLE"
}
```
詳細については、[「Amazon Comprehend デベロッパーガイド」の AWS 「アカウント間のカスタムモデルのコピー](https://docs.aws.amazon.com/comprehend/latest/dg/custom-copy.html)」を参照してください。 *Amazon Comprehend *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/put-resource-policy.html)」を参照してください。

### `start-document-classification-job`
<a name="comprehend_StartDocumentClassificationJob_cli_2_topic"></a>

次のコード例は、`start-document-classification-job` を使用する方法を示しています。

**AWS CLI**  
**ドキュメント分類ジョブを開始するには**  
次の `start-document-classification-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して、カスタムモデルを使用してドキュメント分類ジョブを開始します。この例では、入力 S3 バケットには、`SampleSMStext1.txt`、`SampleSMStext2.txt`、`SampleSMStext3.txt` が含まれています。このモデルは以前、迷惑メールと迷惑メールでない正規のメール、または SMS メッセージにドキュメントを分類するトレーニングを受けていました。ジョブが完了すると、`output.tar.gz` は `--output-data-config` タグで指定された場所に配置されます。`output.tar.gz` には各ドキュメントの分類を一覧表示する `predictions.jsonl` が含まれています。Json の出力は、1 ファイルに 1 行で出力されますが、ここでは読みやすい形式で表示されています。  

```
aws comprehend start-document-classification-job \
    --job-name exampleclassificationjob \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket-INPUT/jobdata/" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role \
    --document-classifier-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/mymodel/version/12
```
`SampleSMStext1.txt` の内容:  

```
"CONGRATULATIONS! TXT 2155550100 to win $5000"
```
`SampleSMStext2.txt` の内容:  

```
"Hi, when do you want me to pick you up from practice?"
```
`SampleSMStext3.txt` の内容:  

```
"Plz send bank account # to 2155550100 to claim prize!!"
```
出力:  

```
{
    "JobId": "e758dd56b824aa717ceab551fEXAMPLE",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:document-classification-job/e758dd56b824aa717ceab551fEXAMPLE",
    "JobStatus": "SUBMITTED"
}
```
`predictions.jsonl` の内容:  

```
{"File": "SampleSMSText1.txt", "Line": "0", "Classes": [{"Name": "spam", "Score": 0.9999}, {"Name": "ham", "Score": 0.0001}]}
{"File": "SampleSMStext2.txt", "Line": "0", "Classes": [{"Name": "ham", "Score": 0.9994}, {"Name": "spam", "Score": 0.0006}]}
{"File": "SampleSMSText3.txt", "Line": "0", "Classes": [{"Name": "spam", "Score": 0.9999}, {"Name": "ham", "Score": 0.0001}]}
```
詳細については、「Amazon Comprehend 開発者ガイド」の「[カスタム分類](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDocumentClassificationJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-document-classification-job.html)」を参照してください。

### `start-dominant-language-detection-job`
<a name="comprehend_StartDominantLanguageDetectionJob_cli_2_topic"></a>

次のコード例は、`start-dominant-language-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期言語検出ジョブを開始するには**  
次の `start-dominant-language-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期言語検出ジョブを開始します。この例の S3 バケットには `Sampletext1.txt` が含まれています。ジョブが完了すると、`output` フォルダが `--output-data-config` タグで指定された場所に配置されます。フォルダには `output.txt` が含まれており、これには各テキストファイルの主要言語と、予測ごとの事前トレーニング済みモデルの信頼スコアが含まれています。  

```
aws comprehend start-dominant-language-detection-job \
    --job-name example_language_analysis_job \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role \
    --language-code en
```
Sampletext1.txt の内容:  

```
"Physics is the natural science that involves the study of matter and its motion and behavior through space and time, along with related concepts such as energy and force."
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:dominant-language-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
    "JobStatus": "SUBMITTED"
}
```
`output.txt` の内容:  

```
{"File": "Sampletext1.txt", "Languages": [{"LanguageCode": "en", "Score": 0.9913753867149353}], "Line": 0}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDominantLanguageDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-dominant-language-detection-job.html)」を参照してください。

### `start-entities-detection-job`
<a name="comprehend_StartEntitiesDetectionJob_cli_2_topic"></a>

次のコード例は、`start-entities-detection-job` を使用する方法を示しています。

**AWS CLI**  
**例 1: 事前トレーニング済みモデルを使用して標準エンティティ検出ジョブを開始するには**  
次の `start-entities-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期エンティティ検出ジョブを開始します。この例の S3 バケットには `Sampletext1.txt`、`Sampletext2.txt`、`Sampletext3.txt` が含まれています。ジョブが完了すると、`output` フォルダが `--output-data-config` タグで指定された場所に配置されます。フォルダには `output.txt` が含まれており、これには各テキストファイル内で検出されたすべての名前付きエンティティと、予測ごとの事前トレーニング済みモデルの信頼スコアが一覧表示されています。Json の出力は、入力ファイルごとに 1 行に出力されますが、ここでは読みやすい形式で表示されています。  

```
aws comprehend start-entities-detection-job \
    --job-name entitiestest \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role \
    --language-code en
```
`Sampletext1.txt` の内容:  

```
"Hello Zhang Wei, I am John. Your AnyCompany Financial Services, LLC credit card account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st."
```
`Sampletext2.txt` の内容:  

```
"Dear Max, based on your autopay settings for your account example1.org account, we will withdraw your payment on the due date from your bank account number XXXXXX1111 with the routing number XXXXX0000. "
```
`Sampletext3.txt` の内容:  

```
"Jane, please submit any customer feedback from this weekend to AnySpa, 123 Main St, Anywhere and send comments to Alice at AnySpa@example.com."
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:entities-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
    "JobStatus": "SUBMITTED"
}
```
読みやすいように行にインデントを加えた `output.txt` の内容:  

```
{
"Entities": [
    {
    "BeginOffset": 6,
    "EndOffset": 15,
    "Score": 0.9994006636420306,
    "Text": "Zhang Wei",
    "Type": "PERSON"
    },
    {
    "BeginOffset": 22,
    "EndOffset": 26,
    "Score": 0.9976647915128143,
    "Text": "John",
    "Type": "PERSON"
    },
    {
    "BeginOffset": 33,
    "EndOffset": 67,
    "Score": 0.9984608700836206,
    "Text": "AnyCompany Financial Services, LLC",
    "Type": "ORGANIZATION"
    },
    {
    "BeginOffset": 88,
    "EndOffset": 107,
    "Score": 0.9868521019555556,
    "Text": "1111-XXXX-1111-XXXX",
    "Type": "OTHER"
    },
    {
    "BeginOffset": 133,
    "EndOffset": 139,
    "Score": 0.998242565709204,
    "Text": "$24.53",
    "Type": "QUANTITY"
    },
    {
    "BeginOffset": 155,
    "EndOffset": 164,
    "Score": 0.9993039263159287,
    "Text": "July 31st",
    "Type": "DATE"
    }
],
"File": "SampleText1.txt",
"Line": 0
}
{
"Entities": [
    {
    "BeginOffset": 5,
    "EndOffset": 8,
    "Score": 0.9866232147545232,
    "Text": "Max",
    "Type": "PERSON"
    },
    {
    "BeginOffset": 156,
    "EndOffset": 166,
    "Score": 0.9797723450933329,
    "Text": "XXXXXX1111",
    "Type": "OTHER"
    },
    {
    "BeginOffset": 191,
    "EndOffset": 200,
    "Score": 0.9247838572396843,
    "Text": "XXXXX0000",
    "Type": "OTHER"
    }
],
"File": "SampleText2.txt",
"Line": 0
}
{
 "Entities": [
    {
    "Score": 0.9990532994270325,
    "Type": "PERSON",
    "Text": "Jane",
    "BeginOffset": 0,
    "EndOffset": 4
    },
    {
    "Score": 0.9519651532173157,
    "Type": "DATE",
    "Text": "this weekend",
    "BeginOffset": 47,
    "EndOffset": 59
    },
    {
    "Score": 0.5566426515579224,
    "Type": "ORGANIZATION",
    "Text": "AnySpa",
    "BeginOffset": 63,
    "EndOffset": 69
    },
    {
    "Score": 0.8059805631637573,
    "Type": "LOCATION",
    "Text": "123 Main St, Anywhere",
    "BeginOffset": 71,
    "EndOffset": 92
    },
    {
    "Score": 0.998830258846283,
    "Type": "PERSON",
    "Text": "Alice",
    "BeginOffset": 114,
    "EndOffset": 119
    },
    {
    "Score": 0.997818112373352,
    "Type": "OTHER",
    "Text": "AnySpa@example.com",
    "BeginOffset": 123,
    "EndOffset": 138
    }
    ],
    "File": "SampleText3.txt",
    "Line": 0
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
**例 2: カスタムエンティティ検出ジョブを開始するには**  
次の `start-entities-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期カスタムエンティティ検出ジョブを開始します。この例では、S3 バケットに `SampleFeedback1.txt`、`SampleFeedback2.txt`、`SampleFeedback3.txt` が含まれています。エンティティレコグナイザーモデルは、デバイス名を認識するためにカスタマーサポートフィードバックでトレーニングされました。ジョブが完了すると、`output` フォルダが `--output-data-config` タグで指定された場所に配置されます。フォルダには `output.txt` が含まれており、これには各テキストファイル内で検出されたすべての名前付きエンティティと、予測ごとの事前トレーニング済みモデルの信頼スコアが一覧表示されています。Json の出力は、1 ファイルに 1 行で出力されますが、ここでは読みやすい形式で表示されています。  

```
aws comprehend start-entities-detection-job \
    --job-name customentitiestest \
    --entity-recognizer-arn "arn:aws:comprehend:us-west-2:111122223333:entity-recognizer/entityrecognizer" \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/jobdata/" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-IOrole"
```
`SampleFeedback1.txt` の内容:  

```
"I've been on the AnyPhone app have had issues for 24 hours when trying to pay bill. Cannot make payment. Sigh. | Oh man! Lets get that app up and running. DM me, and we can get to work!"
```
`SampleFeedback2.txt` の内容:  

```
"Hi, I have a discrepancy with my new bill. Could we get it sorted out? A rep added stuff I didn't sign up for when I did my AnyPhone 10 upgrade. | We can absolutely get this sorted!"
```
`SampleFeedback3.txt` の内容:  

```
"Is the by 1 get 1 free AnySmartPhone promo still going on? | Hi Christian! It ended yesterday, send us a DM if you have any questions and we can take a look at your options!"
```
出力:  

```
{
    "JobId": "019ea9edac758806850fa8a79ff83021",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:entities-detection-job/019ea9edac758806850fa8a79ff83021",
    "JobStatus": "SUBMITTED"
}
```
読みやすいように行にインデントを加えた `output.txt` の内容:  

```
{
"Entities": [
    {
    "BeginOffset": 17,
    "EndOffset": 25,
    "Score": 0.9999728210205924,
    "Text": "AnyPhone",
    "Type": "DEVICE"
    }
],
"File": "SampleFeedback1.txt",
"Line": 0
}
{
"Entities": [
    {
    "BeginOffset": 123,
    "EndOffset": 133,
    "Score": 0.9999892116761524,
    "Text": "AnyPhone 10",
    "Type": "DEVICE"
    }
],
"File": "SampleFeedback2.txt",
"Line": 0
}
{
"Entities": [
    {
    "BeginOffset": 23,
    "EndOffset": 35,
    "Score": 0.9999971389852362,
    "Text": "AnySmartPhone",
    "Type": "DEVICE"
    }
],
"File": "SampleFeedback3.txt",
"Line": 0
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Custom entity recognition](https://docs.aws.amazon.com/comprehend/latest/dg/custom-entity-recognition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartEntitiesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-entities-detection-job.html)」を参照してください。

### `start-events-detection-job`
<a name="comprehend_StartEventsDetectionJob_cli_2_topic"></a>

次のコード例は、`start-events-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期イベント検出ジョブを開始するには**  
次の `start-events-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期イベント検出ジョブを開始します。考えられるターゲットイベントタイプには、`BANKRUPCTY`、`EMPLOYMENT`、`CORPORATE_ACQUISITION`、`INVESTMENT_GENERAL`、`CORPORATE_MERGER`、`IPO`、`RIGHTS_ISSUE`、`SECONDARY_OFFERING`、`SHELF_OFFERING`、`TENDER_OFFERING`、`STOCK_SPLIT` があります。この例の S3 バケットには `SampleText1.txt`、`SampleText2.txt`、`SampleText3.txt` が含まれています。ジョブが完了すると、`output` フォルダが `--output-data-config` タグで指定された場所に配置されます。フォルダには `SampleText1.txt.out`、`SampleText2.txt.out`、`SampleText3.txt.out` が含まれています。Json の出力は、1 ファイルに 1 行で出力されますが、ここでは読みやすい形式で表示されています。  

```
aws comprehend start-events-detection-job \
    --job-name events-detection-1 \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/EventsData" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-servicerole \
    --language-code en \
    --target-event-types "BANKRUPTCY" "EMPLOYMENT" "CORPORATE_ACQUISITION" "CORPORATE_MERGER" "INVESTMENT_GENERAL"
```
`SampleText1.txt` の内容:  

```
"Company AnyCompany grew by increasing sales and through acquisitions. After purchasing competing firms in 2020, AnyBusiness, a part of the AnyBusinessGroup, gave Jane Does firm a going rate of one cent a gallon or forty-two cents a barrel."
```
`SampleText2.txt` の内容:  

```
"In 2021, AnyCompany officially purchased AnyBusiness for 100 billion dollars, surprising and exciting the shareholders."
```
`SampleText3.txt` の内容:  

```
"In 2022, AnyCompany stock crashed 50. Eventually later that year they filed for bankruptcy."
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:events-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
    "JobStatus": "SUBMITTED"
}
```
読みやすいように行にインデントを加えた `SampleText1.txt.out` の内容:  

```
{
    "Entities": [
        {
        "Mentions": [
            {
            "BeginOffset": 8,
            "EndOffset": 18,
            "Score": 0.99977,
            "Text": "AnyCompany",
            "Type": "ORGANIZATION",
            "GroupScore": 1
            },
            {
            "BeginOffset": 112,
            "EndOffset": 123,
            "Score": 0.999747,
            "Text": "AnyBusiness",
            "Type": "ORGANIZATION",
            "GroupScore": 0.979826
            },
            {
            "BeginOffset": 171,
            "EndOffset": 175,
            "Score": 0.999615,
            "Text": "firm",
            "Type": "ORGANIZATION",
            "GroupScore": 0.871647
            }
        ]
        },
        {
        "Mentions": [
            {
            "BeginOffset": 97,
            "EndOffset": 102,
            "Score": 0.987687,
            "Text": "firms",
            "Type": "ORGANIZATION",
            "GroupScore": 1
            }
        ]
        },
        {
        "Mentions": [
            {
            "BeginOffset": 103,
            "EndOffset": 110,
            "Score": 0.999458,
            "Text": "in 2020",
            "Type": "DATE",
            "GroupScore": 1
            }
        ]
        },
        {
        "Mentions": [
            {
            "BeginOffset": 160,
            "EndOffset": 168,
            "Score": 0.999649,
            "Text": "John Doe",
            "Type": "PERSON",
            "GroupScore": 1
            }
        ]
        }
    ],
    "Events": [
        {
        "Type": "CORPORATE_ACQUISITION",
        "Arguments": [
            {
            "EntityIndex": 0,
            "Role": "INVESTOR",
            "Score": 0.99977
            }
        ],
        "Triggers": [
            {
            "BeginOffset": 56,
            "EndOffset": 68,
            "Score": 0.999967,
            "Text": "acquisitions",
            "Type": "CORPORATE_ACQUISITION",
            "GroupScore": 1
            }
        ]
        },
        {
        "Type": "CORPORATE_ACQUISITION",
        "Arguments": [
            {
            "EntityIndex": 1,
            "Role": "INVESTEE",
            "Score": 0.987687
            },
            {
            "EntityIndex": 2,
            "Role": "DATE",
            "Score": 0.999458
            },
            {
            "EntityIndex": 3,
            "Role": "INVESTOR",
            "Score": 0.999649
            }
        ],
        "Triggers": [
            {
            "BeginOffset": 76,
            "EndOffset": 86,
            "Score": 0.999973,
            "Text": "purchasing",
            "Type": "CORPORATE_ACQUISITION",
            "GroupScore": 1
            }
        ]
        }
    ],
    "File": "SampleText1.txt",
    "Line": 0
}
```
`SampleText2.txt.out` の内容:  

```
{
    "Entities": [
        {
        "Mentions": [
            {
            "BeginOffset": 0,
            "EndOffset": 7,
            "Score": 0.999473,
            "Text": "In 2021",
            "Type": "DATE",
            "GroupScore": 1
            }
        ]
        },
        {
        "Mentions": [
            {
            "BeginOffset": 9,
            "EndOffset": 19,
            "Score": 0.999636,
            "Text": "AnyCompany",
            "Type": "ORGANIZATION",
            "GroupScore": 1
            }
        ]
        },
        {
        "Mentions": [
            {
            "BeginOffset": 45,
            "EndOffset": 56,
            "Score": 0.999712,
            "Text": "AnyBusiness",
            "Type": "ORGANIZATION",
            "GroupScore": 1
            }
        ]
        },
        {
        "Mentions": [
            {
            "BeginOffset": 61,
            "EndOffset": 80,
            "Score": 0.998886,
            "Text": "100 billion dollars",
            "Type": "MONETARY_VALUE",
            "GroupScore": 1
            }
        ]
        }
    ],
    "Events": [
        {
        "Type": "CORPORATE_ACQUISITION",
        "Arguments": [
            {
            "EntityIndex": 3,
            "Role": "AMOUNT",
            "Score": 0.998886
            },
            {
            "EntityIndex": 2,
            "Role": "INVESTEE",
            "Score": 0.999712
            },
            {
            "EntityIndex": 0,
            "Role": "DATE",
            "Score": 0.999473
            },
            {
            "EntityIndex": 1,
            "Role": "INVESTOR",
            "Score": 0.999636
            }
        ],
        "Triggers": [
            {
            "BeginOffset": 31,
            "EndOffset": 40,
            "Score": 0.99995,
            "Text": "purchased",
            "Type": "CORPORATE_ACQUISITION",
            "GroupScore": 1
            }
        ]
        }
    ],
    "File": "SampleText2.txt",
    "Line": 0
}
```
`SampleText3.txt.out` の内容:  

```
{
    "Entities": [
        {
        "Mentions": [
            {
            "BeginOffset": 9,
            "EndOffset": 19,
            "Score": 0.999774,
            "Text": "AnyCompany",
            "Type": "ORGANIZATION",
            "GroupScore": 1
            },
            {
            "BeginOffset": 66,
            "EndOffset": 70,
            "Score": 0.995717,
            "Text": "they",
            "Type": "ORGANIZATION",
            "GroupScore": 0.997626
            }
        ]
        },
        {
        "Mentions": [
            {
            "BeginOffset": 50,
            "EndOffset": 65,
            "Score": 0.999656,
            "Text": "later that year",
            "Type": "DATE",
            "GroupScore": 1
            }
        ]
        }
    ],
    "Events": [
        {
        "Type": "BANKRUPTCY",
        "Arguments": [
            {
            "EntityIndex": 1,
            "Role": "DATE",
            "Score": 0.999656
            },
            {
            "EntityIndex": 0,
            "Role": "FILER",
            "Score": 0.995717
            }
        ],
        "Triggers": [
            {
            "BeginOffset": 81,
            "EndOffset": 91,
            "Score": 0.999936,
            "Text": "bankruptcy",
            "Type": "BANKRUPTCY",
            "GroupScore": 1
            }
        ]
        }
    ],
    "File": "SampleText3.txt",
    "Line": 0
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartEventsDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-events-detection-job.html)」を参照してください。

### `start-flywheel-iteration`
<a name="comprehend_StartFlywheelIteration_cli_2_topic"></a>

次のコード例は、`start-flywheel-iteration` を使用する方法を示しています。

**AWS CLI**  
**フライホイールイテレーションを開始するには**  
次の `start-flywheel-iteration` の例では、フライホイールイテレーションを開始しています。このオペレーションでは、フライホイール内の新しいデータセットを使用して、新しいモデルバージョンをトレーニングしています。  

```
aws comprehend start-flywheel-iteration \
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel
```
出力:  

```
{
    "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel",
    "FlywheelIterationId": "12345123TEXAMPLE"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartFlywheelIteration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-flywheel-iteration.html)」を参照してください。

### `start-key-phrases-detection-job`
<a name="comprehend_StartKeyPhrasesDetectionJob_cli_2_topic"></a>

次のコード例は、`start-key-phrases-detection-job` を使用する方法を示しています。

**AWS CLI**  
**キーフレーズ検出ジョブを開始するには**  
次の `start-key-phrases-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期キーフレーズ検出ジョブを開始しています。この例の S3 バケットには `Sampletext1.txt`、`Sampletext2.txt`、`Sampletext3.txt` が含まれています。ジョブが完了すると、`output` フォルダが `--output-data-config` タグで指定された場所に配置されます。フォルダには `output.txt` ファイルが含まれており、これには各テキストファイル内で検出されたすべてのキーフレーズと、予測ごとの事前トレーニング済みモデルの信頼スコアが含まれています。Json の出力は、1 ファイルに 1 行で出力されますが、ここでは読みやすい形式で表示されています。  

```
aws comprehend start-key-phrases-detection-job \
    --job-name keyphrasesanalysistest1 \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role" \
    --language-code en
```
`Sampletext1.txt` の内容:  

```
"Hello Zhang Wei, I am John. Your AnyCompany Financial Services, LLC credit card account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st."
```
`Sampletext2.txt` の内容:  

```
"Dear Max, based on your autopay settings for your account Internet.org account, we will withdraw your payment on the due date from your bank account number XXXXXX1111 with the routing number XXXXX0000. "
```
`Sampletext3.txt` の内容:  

```
"Jane, please submit any customer feedback from this weekend to Sunshine Spa, 123 Main St, Anywhere and send comments to Alice at AnySpa@example.com."
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:key-phrases-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
    "JobStatus": "SUBMITTED"
}
```
読みやすいように行にインデントを加えた `output.txt` の内容:  

```
{
    "File": "SampleText1.txt",
    "KeyPhrases": [
        {
        "BeginOffset": 6,
        "EndOffset": 15,
        "Score": 0.9748965572679326,
        "Text": "Zhang Wei"
        },
        {
        "BeginOffset": 22,
        "EndOffset": 26,
        "Score": 0.9997344722354619,
        "Text": "John"
        },
        {
        "BeginOffset": 28,
        "EndOffset": 62,
        "Score": 0.9843791074032948,
        "Text": "Your AnyCompany Financial Services"
        },
        {
        "BeginOffset": 64,
        "EndOffset": 107,
        "Score": 0.8976122401721824,
        "Text": "LLC credit card account 1111-XXXX-1111-XXXX"
        },
        {
        "BeginOffset": 112,
        "EndOffset": 129,
        "Score": 0.9999612982629748,
        "Text": "a minimum payment"
        },
        {
        "BeginOffset": 133,
        "EndOffset": 139,
        "Score": 0.99975728947036,
        "Text": "$24.53"
        },
        {
        "BeginOffset": 155,
        "EndOffset": 164,
        "Score": 0.9940866241449973,
        "Text": "July 31st"
        }
    ],
    "Line": 0
    }
    {
    "File": "SampleText2.txt",
    "KeyPhrases": [
        {
        "BeginOffset": 0,
        "EndOffset": 8,
        "Score": 0.9974021100118472,
        "Text": "Dear Max"
        },
        {
        "BeginOffset": 19,
        "EndOffset": 40,
        "Score": 0.9961120519515884,
        "Text": "your autopay settings"
        },
        {
        "BeginOffset": 45,
        "EndOffset": 78,
        "Score": 0.9980620070116009,
        "Text": "your account Internet.org account"
        },
        {
        "BeginOffset": 97,
        "EndOffset": 109,
        "Score": 0.999919660140754,
        "Text": "your payment"
        },
        {
        "BeginOffset": 113,
        "EndOffset": 125,
        "Score": 0.9998370719754205,
        "Text": "the due date"
        },
        {
        "BeginOffset": 131,
        "EndOffset": 166,
        "Score": 0.9955068678502509,
        "Text": "your bank account number XXXXXX1111"
        },
        {
        "BeginOffset": 172,
        "EndOffset": 200,
        "Score": 0.8653433315829526,
        "Text": "the routing number XXXXX0000"
        }
    ],
    "Line": 0
    }
    {
    "File": "SampleText3.txt",
    "KeyPhrases": [
        {
        "BeginOffset": 0,
        "EndOffset": 4,
        "Score": 0.9142947833681668,
        "Text": "Jane"
        },
        {
        "BeginOffset": 20,
        "EndOffset": 41,
        "Score": 0.9984325676596763,
        "Text": "any customer feedback"
        },
        {
        "BeginOffset": 47,
        "EndOffset": 59,
        "Score": 0.9998782448150636,
        "Text": "this weekend"
        },
        {
        "BeginOffset": 63,
        "EndOffset": 75,
        "Score": 0.99866741830757,
        "Text": "Sunshine Spa"
        },
        {
        "BeginOffset": 77,
        "EndOffset": 88,
        "Score": 0.9695803485466054,
        "Text": "123 Main St"
        },
        {
        "BeginOffset": 108,
        "EndOffset": 116,
        "Score": 0.9997065928550928,
        "Text": "comments"
        },
        {
        "BeginOffset": 120,
        "EndOffset": 125,
        "Score": 0.9993466833825161,
        "Text": "Alice"
        },
        {
        "BeginOffset": 129,
        "EndOffset": 144,
        "Score": 0.9654563612885667,
        "Text": "AnySpa@example.com"
        }
    ],
    "Line": 0
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartKeyPhrasesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-key-phrases-detection-job.html)」を参照してください。

### `start-pii-entities-detection-job`
<a name="comprehend_StartPiiEntitiesDetectionJob_cli_2_topic"></a>

次のコード例は、`start-pii-entities-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期 PII 検出ジョブを開始するには**  
次の `start-pii-entities-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期の個人を特定できる情報 (PII) エンティティ検出ジョブを開始します。この例の S3 バケットには `Sampletext1.txt`、`Sampletext2.txt`、`Sampletext3.txt` が含まれています。ジョブが完了すると、`output` フォルダが `--output-data-config` タグで指定された場所に配置されます。フォルダには、各テキストファイル内の名前付きエンティティを一覧表示している `SampleText1.txt.out`、`SampleText2.txt.out`、`SampleText3.txt.out` が含まれています。Json の出力は、1 ファイルに 1 行で出力されますが、ここでは読みやすい形式で表示されています。  

```
aws comprehend start-pii-entities-detection-job \
    --job-name entities_test \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role \
    --language-code en \
    --mode ONLY_OFFSETS
```
`Sampletext1.txt` の内容:  

```
"Hello Zhang Wei, I am John. Your AnyCompany Financial Services, LLC credit card account 1111-XXXX-1111-XXXX has a minimum payment of $24.53 that is due by July 31st."
```
`Sampletext2.txt` の内容:  

```
"Dear Max, based on your autopay settings for your account Internet.org account, we will withdraw your payment on the due date from your bank account number XXXXXX1111 with the routing number XXXXX0000. "
```
`Sampletext3.txt` の内容:  

```
"Jane, please submit any customer feedback from this weekend to Sunshine Spa, 123 Main St, Anywhere and send comments to Alice at AnySpa@example.com."
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:pii-entities-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
    "JobStatus": "SUBMITTED"
}
```
読みやすいように行にインデントを加えた `SampleText1.txt.out` の内容:  

```
{
    "Entities": [
        {
        "BeginOffset": 6,
        "EndOffset": 15,
        "Type": "NAME",
        "Score": 0.9998490510222595
        },
        {
        "BeginOffset": 22,
        "EndOffset": 26,
        "Type": "NAME",
        "Score": 0.9998937958019426
        },
        {
        "BeginOffset": 88,
        "EndOffset": 107,
        "Type": "CREDIT_DEBIT_NUMBER",
        "Score": 0.9554297245278491
        },
        {
        "BeginOffset": 155,
        "EndOffset": 164,
        "Type": "DATE_TIME",
        "Score": 0.9999720462925257
        }
    ],
    "File": "SampleText1.txt",
    "Line": 0
}
```
読みやすいように行にインデントを加えた `SampleText2.txt.out` の内容:  

```
{
    "Entities": [
        {
        "BeginOffset": 5,
        "EndOffset": 8,
        "Type": "NAME",
        "Score": 0.9994390774924007
        },
        {
        "BeginOffset": 58,
        "EndOffset": 70,
        "Type": "URL",
        "Score": 0.9999958276922101
        },
        {
        "BeginOffset": 156,
        "EndOffset": 166,
        "Type": "BANK_ACCOUNT_NUMBER",
        "Score": 0.9999721058045592
        },
        {
        "BeginOffset": 191,
        "EndOffset": 200,
        "Type": "BANK_ROUTING",
        "Score": 0.9998968945989909
        }
    ],
    "File": "SampleText2.txt",
    "Line": 0
}
```
読みやすいように行にインデントを加えた `SampleText3.txt.out` の内容:  

```
{
    "Entities": [
        {
        "BeginOffset": 0,
        "EndOffset": 4,
        "Type": "NAME",
        "Score": 0.999949934606805
        },
        {
        "BeginOffset": 77,
        "EndOffset": 88,
        "Type": "ADDRESS",
        "Score": 0.9999035300466904
        },
        {
        "BeginOffset": 120,
        "EndOffset": 125,
        "Type": "NAME",
        "Score": 0.9998203838716296
        },
        {
        "BeginOffset": 129,
        "EndOffset": 144,
        "Type": "EMAIL",
        "Score": 0.9998313473105228
        }
    ],
    "File": "SampleText3.txt",
    "Line": 0
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartPiiEntitiesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-pii-entities-detection-job.html)」を参照してください。

### `start-sentiment-detection-job`
<a name="comprehend_StartSentimentDetectionJob_cli_2_topic"></a>

次のコード例は、`start-sentiment-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期感情分析ジョブを開始するには**  
次の `start-sentiment-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期感情分析検出ジョブを開始します。この例の S3 バケットフォルダには `SampleMovieReview1.txt`、`SampleMovieReview2.txt`、`SampleMovieReview3.txt` が含まれています。ジョブが完了すると、`output` フォルダが `--output-data-config` タグで指定された場所に配置されます。フォルダには `output.txt` ファイルが含まれており、これには各テキストファイルの一般的な感情と、予測ごとの事前トレーニング済みモデルの信頼スコアが含まれています。Json の出力は、1 ファイルに 1 行で出力されますが、ここでは読みやすい形式で表示されています。  

```
aws comprehend start-sentiment-detection-job \
    --job-name example-sentiment-detection-job \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/MovieData" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role
```
`SampleMovieReview1.txt` の内容:  

```
"The film, AnyMovie2, is fairly predictable and just okay."
```
`SampleMovieReview2.txt` の内容:  

```
"AnyMovie2 is the essential sci-fi film that I grew up watching when I was a kid. I highly recommend this movie."
```
`SampleMovieReview3.txt` の内容:  

```
"Don't get fooled by the 'awards' for AnyMovie2. All parts of the film were poorly stolen from other modern directors."
```
出力:  

```
{
    "JobId": "0b5001e25f62ebb40631a9a1a7fde7b3",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:sentiment-detection-job/0b5001e25f62ebb40631a9a1a7fde7b3",
    "JobStatus": "SUBMITTED"
}
```
読みやすいように行にインデントを加えた `output.txt` の内容:  

```
{
    "File": "SampleMovieReview1.txt",
        "Line": 0,
        "Sentiment": "MIXED",
        "SentimentScore": {
            "Mixed": 0.6591159105300903,
            "Negative": 0.26492202281951904,
            "Neutral": 0.035430654883384705,
            "Positive": 0.04053137078881264
            }
        }
    {
    "File": "SampleMovieReview2.txt",
        "Line": 0,
        "Sentiment": "POSITIVE",
        "SentimentScore": {
            "Mixed": 0.000008718466233403888,
            "Negative": 0.00006134175055194646,
            "Neutral": 0.0002941041602753103,
            "Positive": 0.9996358156204224
            }
        }
    {
    "File": "SampleMovieReview3.txt",
        "Line": 0,
        "Sentiment": "NEGATIVE",
        "SentimentScore": {
            "Mixed": 0.004146667663007975,
            "Negative": 0.9645107984542847,
            "Neutral": 0.016559595242142677,
            "Positive": 0.014782938174903393
        }
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartSentimentDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-sentiment-detection-job.html)」を参照してください。

### `start-targeted-sentiment-detection-job`
<a name="comprehend_StartTargetedSentimentDetectionJob_cli_2_topic"></a>

次のコード例は、`start-targeted-sentiment-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期ターゲット感情分析ジョブを開始するには**  
次の `start-targeted-sentiment-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルに対して非同期ターゲット感情分析検出ジョブを開始しています。この例の S3 バケットフォルダには `SampleMovieReview1.txt`、`SampleMovieReview2.txt`、`SampleMovieReview3.txt` が含まれています。ジョブが完了すると、`output.tar.gz` が `--output-data-config` タグで指定された場所に配置されます。`output.tar.gz` には、ファイル `SampleMovieReview1.txt.out`、`SampleMovieReview2.txt.out`、`SampleMovieReview3.txt.out` が含まれており、それぞれには 1 つの入力テキストファイルの名前付きエンティティと関連する感情がすべて含まれています。  

```
aws comprehend start-targeted-sentiment-detection-job \
    --job-name targeted_movie_review_analysis1 \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/MovieData" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role
```
`SampleMovieReview1.txt` の内容:  

```
"The film, AnyMovie, is fairly predictable and just okay."
```
`SampleMovieReview2.txt` の内容:  

```
"AnyMovie is the essential sci-fi film that I grew up watching when I was a kid. I highly recommend this movie."
```
`SampleMovieReview3.txt` の内容:  

```
"Don't get fooled by the 'awards' for AnyMovie. All parts of the film were poorly stolen from other modern directors."
```
出力:  

```
{
    "JobId": "0b5001e25f62ebb40631a9a1a7fde7b3",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:targeted-sentiment-detection-job/0b5001e25f62ebb40631a9a1a7fde7b3",
    "JobStatus": "SUBMITTED"
}
```
読みやすいように行にインデントを加えた `SampleMovieReview1.txt.out` の内容:  

```
{
    "Entities": [
        {
        "DescriptiveMentionIndex": [
            0
        ],
        "Mentions": [
            {
            "BeginOffset": 4,
            "EndOffset": 8,
            "Score": 0.994972,
            "GroupScore": 1,
            "Text": "film",
            "Type": "MOVIE",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 1,
                "Positive": 0
                }
            }
            }
        ]
        },
        {
        "DescriptiveMentionIndex": [
            0
        ],
        "Mentions": [
            {
            "BeginOffset": 10,
            "EndOffset": 18,
            "Score": 0.631368,
            "GroupScore": 1,
            "Text": "AnyMovie",
            "Type": "ORGANIZATION",
            "MentionSentiment": {
                "Sentiment": "POSITIVE",
                "SentimentScore": {
                "Mixed": 0.001729,
                "Negative": 0.000001,
                "Neutral": 0.000318,
                "Positive": 0.997952
                }
            }
            }
        ]
        }
    ],
    "File": "SampleMovieReview1.txt",
    "Line": 0
}
```
読みやすいように行にインデントを加えた `SampleMovieReview2.txt.out` の内容:  

```
{
    "Entities": [
        {
        "DescriptiveMentionIndex": [
            0
        ],
        "Mentions": [
            {
            "BeginOffset": 0,
            "EndOffset": 8,
            "Score": 0.854024,
            "GroupScore": 1,
            "Text": "AnyMovie",
            "Type": "MOVIE",
            "MentionSentiment": {
                "Sentiment": "POSITIVE",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 0.000007,
                "Positive": 0.999993
                }
            }
            },
            {
            "BeginOffset": 104,
            "EndOffset": 109,
            "Score": 0.999129,
            "GroupScore": 0.502937,
            "Text": "movie",
            "Type": "MOVIE",
            "MentionSentiment": {
                "Sentiment": "POSITIVE",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 0,
                "Positive": 1
                }
            }
            },
            {
            "BeginOffset": 33,
            "EndOffset": 37,
            "Score": 0.999823,
            "GroupScore": 0.999252,
            "Text": "film",
            "Type": "MOVIE",
            "MentionSentiment": {
                "Sentiment": "POSITIVE",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 0.000001,
                "Positive": 0.999999
                }
            }
            }
        ]
        },
        {
        "DescriptiveMentionIndex": [
            0,
            1,
            2
        ],
        "Mentions": [
            {
            "BeginOffset": 43,
            "EndOffset": 44,
            "Score": 0.999997,
            "GroupScore": 1,
            "Text": "I",
            "Type": "PERSON",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 1,
                "Positive": 0
                }
            }
            },
            {
            "BeginOffset": 80,
            "EndOffset": 81,
            "Score": 0.999996,
            "GroupScore": 0.52523,
            "Text": "I",
            "Type": "PERSON",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 1,
                "Positive": 0
                }
            }
            },
            {
            "BeginOffset": 67,
            "EndOffset": 68,
            "Score": 0.999994,
            "GroupScore": 0.999499,
            "Text": "I",
            "Type": "PERSON",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 1,
                "Positive": 0
                }
            }
            }
        ]
        },
        {
        "DescriptiveMentionIndex": [
            0
        ],
        "Mentions": [
            {
            "BeginOffset": 75,
            "EndOffset": 78,
            "Score": 0.999978,
            "GroupScore": 1,
            "Text": "kid",
            "Type": "PERSON",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 1,
                "Positive": 0
                }
            }
            }
        ]
        }
    ],
    "File": "SampleMovieReview2.txt",
    "Line": 0
}
```
読みやすいように行にインデントを加えた `SampleMovieReview3.txt.out` の内容:  

```
{
    "Entities": [
        {
        "DescriptiveMentionIndex": [
            1
        ],
        "Mentions": [
            {
            "BeginOffset": 64,
            "EndOffset": 68,
            "Score": 0.992953,
            "GroupScore": 0.999814,
            "Text": "film",
            "Type": "MOVIE",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0.000004,
                "Negative": 0.010425,
                "Neutral": 0.989543,
                "Positive": 0.000027
                }
            }
            },
            {
            "BeginOffset": 37,
            "EndOffset": 45,
            "Score": 0.999782,
            "GroupScore": 1,
            "Text": "AnyMovie",
            "Type": "ORGANIZATION",
            "MentionSentiment": {
                "Sentiment": "POSITIVE",
                "SentimentScore": {
                "Mixed": 0.000095,
                "Negative": 0.039847,
                "Neutral": 0.000673,
                "Positive": 0.959384
                }
            }
            }
        ]
        },
        {
        "DescriptiveMentionIndex": [
            0
        ],
        "Mentions": [
            {
            "BeginOffset": 47,
            "EndOffset": 50,
            "Score": 0.999991,
            "GroupScore": 1,
            "Text": "All",
            "Type": "QUANTITY",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0.000001,
                "Negative": 0.000001,
                "Neutral": 0.999998,
                "Positive": 0
                }
            }
            }
        ]
        },
        {
        "DescriptiveMentionIndex": [
            0
        ],
        "Mentions": [
            {
            "BeginOffset": 106,
            "EndOffset": 115,
            "Score": 0.542083,
            "GroupScore": 1,
            "Text": "directors",
            "Type": "PERSON",
            "MentionSentiment": {
                "Sentiment": "NEUTRAL",
                "SentimentScore": {
                "Mixed": 0,
                "Negative": 0,
                "Neutral": 1,
                "Positive": 0
                }
            }
            }
        ]
        }
    ],
    "File": "SampleMovieReview3.txt",
    "Line": 0
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartTargetedSentimentDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-targeted-sentiment-detection-job.html)」を参照してください。

### `start-topics-detection-job`
<a name="comprehend_StartTopicsDetectionJob_cli_2_topic"></a>

次のコード例は、`start-topics-detection-job` を使用する方法を示しています。

**AWS CLI**  
**トピック検出分析ジョブを開始するには**  
次の `start-topics-detection-job` の例では、`--input-data-config` タグで指定されたアドレスにあるすべてのファイルの非同期トピック検出ジョブを開始します。ジョブが完了すると、フォルダ、`output` は `--ouput-data-config` タグで指定された場所に配置されます。`output` には topic-terms.csv と doc-topics.csv が含まれています。最初の出力ファイル topic-terms.csv は、コレクション内のトピックのリストです。デフォルトでは、リストには、各トピックの上位の言葉が重みに応じてトピック別に含まれています。2 つ目のファイル `doc-topics.csv` には、トピックに関連するドキュメントと、そのトピックに関係するドキュメントの割合が一覧表示されます。  

```
aws comprehend start-topics-detection-job \
    --job-name example_topics_detection_job \
    --language-code en \
    --input-data-config "S3Uri=s3://amzn-s3-demo-bucket/" \
    --output-data-config "S3Uri=s3://amzn-s3-demo-destination-bucket/testfolder/" \
    --data-access-role-arn arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role \
    --language-code en
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE",
    "JobArn": "arn:aws:comprehend:us-west-2:111122223333:key-phrases-detection-job/123456abcdeb0e11022f22a11EXAMPLE",
    "JobStatus": "SUBMITTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[トピックのモデリング](https://docs.aws.amazon.com/comprehend/latest/dg/topic-modeling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartTopicsDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/start-topics-detection-job.html)」を参照してください。

### `stop-dominant-language-detection-job`
<a name="comprehend_StopDominantLanguageDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-dominant-language-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期主要言語検出ジョブを停止するには**  
次の `stop-dominant-language-detection-job` の例では、進行中の非同期主要言語検出ジョブを停止しています。ジョブの現在の状態が `IN_PROGRESS` の場合、そのジョブは終了としてマークされ、状態が `STOP_REQUESTED` になります。ジョブを停止する前にジョブが完了した場合、そのジョブの状態は `COMPLETED` になります。  

```
aws comprehend stop-dominant-language-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE,
    "JobStatus": "STOP_REQUESTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopDominantLanguageDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-dominant-language-detection-job.html)」を参照してください。

### `stop-entities-detection-job`
<a name="comprehend_StopEntitiesDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-entities-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期エンティティ検出ジョブを停止するには**  
次の `stop-entities-detection-job` の例では、進行中の非同期エンティティ検出ジョブを停止しています。ジョブの現在の状態が `IN_PROGRESS` の場合、そのジョブは終了としてマークされ、状態が `STOP_REQUESTED` になります。ジョブを停止する前にジョブが完了した場合、そのジョブの状態は `COMPLETED` になります。  

```
aws comprehend stop-entities-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE,
    "JobStatus": "STOP_REQUESTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopEntitiesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-entities-detection-job.html)」を参照してください。

### `stop-events-detection-job`
<a name="comprehend_StopEventsDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-events-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期イベント検出ジョブを停止するには**  
次の `stop-events-detection-job` の例では、進行中の非同期イベント検出ジョブを停止しています。ジョブの現在の状態が `IN_PROGRESS` の場合、そのジョブは終了としてマークされ、状態が `STOP_REQUESTED` になります。ジョブを停止する前にジョブが完了した場合、そのジョブの状態は `COMPLETED` になります。  

```
aws comprehend stop-events-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE,
    "JobStatus": "STOP_REQUESTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopEventsDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-events-detection-job.html)」を参照してください。

### `stop-key-phrases-detection-job`
<a name="comprehend_StopKeyPhrasesDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-key-phrases-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期キーフレーズ検出ジョブを停止するには**  
次の `stop-key-phrases-detection-job` の例では、進行中の非同期キーフレーズ検出ジョブを停止しています。ジョブの現在の状態が `IN_PROGRESS` の場合、そのジョブは終了としてマークされ、状態が `STOP_REQUESTED` になります。ジョブを停止する前にジョブが完了した場合、そのジョブの状態は `COMPLETED` になります。  

```
aws comprehend stop-key-phrases-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE,
    "JobStatus": "STOP_REQUESTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopKeyPhrasesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-key-phrases-detection-job.html)」を参照してください。

### `stop-pii-entities-detection-job`
<a name="comprehend_StopPiiEntitiesDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-pii-entities-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期 PII エンティティ検出ジョブを停止するには**  
次の `stop-pii-entities-detection-job` の例では、進行中の非同期 PII エンティティ検出ジョブを停止しています。ジョブの現在の状態が `IN_PROGRESS` の場合、そのジョブは終了としてマークされ、状態が `STOP_REQUESTED` になります。ジョブを停止する前にジョブが完了した場合、そのジョブの状態は `COMPLETED` になります。  

```
aws comprehend stop-pii-entities-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE,
    "JobStatus": "STOP_REQUESTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopPiiEntitiesDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-pii-entities-detection-job.html)」を参照してください。

### `stop-sentiment-detection-job`
<a name="comprehend_StopSentimentDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-sentiment-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期感情検出ジョブを停止するには**  
次の `stop-sentiment-detection-job` の例では、進行中の非同期感情検出ジョブを停止しています。ジョブの現在の状態が `IN_PROGRESS` の場合、そのジョブは終了としてマークされ、状態が `STOP_REQUESTED` になります。ジョブを停止する前にジョブが完了した場合、そのジョブの状態は `COMPLETED` になります。  

```
aws comprehend stop-sentiment-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE,
    "JobStatus": "STOP_REQUESTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopSentimentDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-sentiment-detection-job.html)」を参照してください。

### `stop-targeted-sentiment-detection-job`
<a name="comprehend_StopTargetedSentimentDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-targeted-sentiment-detection-job` を使用する方法を示しています。

**AWS CLI**  
**非同期ターゲット感情検出ジョブを停止するには**  
次の `stop-targeted-sentiment-detection-job` の例では、進行中の非同期ターゲット感情検出ジョブを停止しています。ジョブの現在の状態が `IN_PROGRESS` の場合、そのジョブは終了としてマークされ、状態が `STOP_REQUESTED` になります。ジョブを停止する前にジョブが完了した場合、そのジョブの状態は `COMPLETED` になります。  

```
aws comprehend stop-targeted-sentiment-detection-job \
    --job-id 123456abcdeb0e11022f22a11EXAMPLE
```
出力:  

```
{
    "JobId": "123456abcdeb0e11022f22a11EXAMPLE,
    "JobStatus": "STOP_REQUESTED"
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のインサイトのための非同期分析](https://docs.aws.amazon.com/comprehend/latest/dg/api-async-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopTargetedSentimentDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-targeted-sentiment-detection-job.html)」を参照してください。

### `stop-training-document-classifier`
<a name="comprehend_StopTrainingDocumentClassifier_cli_2_topic"></a>

次のコード例は、`stop-training-document-classifier` を使用する方法を示しています。

**AWS CLI**  
**ドキュメント分類子モデルのトレーニングを停止するには**  
次の `stop-training-document-classifier` の例では、進行中のドキュメント分類子モデルのトレーニングを停止しています。  

```
aws comprehend stop-training-document-classifier
    --document-classifier-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[カスタムモデルの作成と管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-models.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopTrainingDocumentClassifier](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-training-document-classifier.html)」を参照してください。

### `stop-training-entity-recognizer`
<a name="comprehend_StopTrainingEntityRecognizer_cli_2_topic"></a>

次のコード例は、`stop-training-entity-recognizer` を使用する方法を示しています。

**AWS CLI**  
**エンティティレコグナイザーモデルのトレーニングを停止するには**  
次の `stop-training-entity-recognizer` の例では、進行中のエンティティレコグナイザーモデルのトレーニングを停止しています。  

```
aws comprehend stop-training-entity-recognizer
    --entity-recognizer-arn "arn:aws:comprehend:us-west-2:111122223333:entity-recognizer/examplerecognizer1"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[カスタムモデルの作成と管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-models.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopTrainingEntityRecognizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/stop-training-entity-recognizer.html)」を参照してください。

### `tag-resource`
<a name="comprehend_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースにタグを付けるには**  
次の `tag-resource` の例では、Amazon Comprehend リソースにタグを 1 つ追加しています。  

```
aws comprehend tag-resource \
    --resource-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1 \
    --tags Key=Location,Value=Seattle
```
このコマンドには出力がありません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Tagging your resources](https://docs.aws.amazon.com/comprehend/latest/dg/tagging.html)」を参照してください。  
**例 2: 複数のタグをリソースに追加する**  
次の `tag-resource` の例では、Amazon Comprehend リソースに複数のタグを追加しています。  

```
aws comprehend tag-resource \
    --resource-arn "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1" \
    --tags Key=location,Value=Seattle Key=Department,Value=Finance
```
このコマンドには出力がありません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Tagging your resources](https://docs.aws.amazon.com/comprehend/latest/dg/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="comprehend_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースから 1 つのタグを削除するには**  
次の `untag-resource` の例では、Amazon Comprehend リソースからタグを 1 つ削除しています。  

```
aws comprehend untag-resource \
    --resource-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1
    --tag-keys Location
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Tagging your resources](https://docs.aws.amazon.com/comprehend/latest/dg/tagging.html)」を参照してください。  
**例 2: リソースから複数のタグを削除するには**  
次の `untag-resource` の例では、Amazon Comprehend リソースから複数のタグを削除しています。  

```
aws comprehend untag-resource \
    --resource-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/1
    --tag-keys Location Department
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Tagging your resources](https://docs.aws.amazon.com/comprehend/latest/dg/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/untag-resource.html)」を参照してください。

### `update-endpoint`
<a name="comprehend_UpdateEndpoint_cli_2_topic"></a>

次のコード例は、`update-endpoint` を使用する方法を示しています。

**AWS CLI**  
**例 1: エンドポイントの推論ユニットを更新するには**  
次の `update-endpoint` の例では、エンドポイントに関する情報を更新しています。この例では、推論ユニットの数が増加します。  

```
aws comprehend update-endpoint \
    --endpoint-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/example-classifier-endpoint
    --desired-inference-units 2
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
**例 2: エンドポイントのアクティブモデルを更新するには**  
次の `update-endpoint` の例では、エンドポイントに関する情報を更新しています。この例では、アクティブモデルが変更されます。  

```
aws comprehend update-endpoint \
    --endpoint-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier-endpoint/example-classifier-endpoint
    --active-model-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier-new
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Amazon Comprehend のエンドポイントの管理](https://docs.aws.amazon.com/comprehend/latest/dg/manage-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/update-endpoint.html)」を参照してください。

### `update-flywheel`
<a name="comprehend_UpdateFlywheel_cli_2_topic"></a>

次のコード例は、`update-flywheel` を使用する方法を示しています。

**AWS CLI**  
**フライホイールの設定を更新するには**  
次の `update-flywheel` の例では、フライホイールの設定を更新しています。この例では、フライホイールのアクティブモデルが更新されます。  

```
aws comprehend update-flywheel \
    --flywheel-arn arn:aws:comprehend:us-west-2:111122223333:flywheel/example-flywheel-1 \
    --active-model-arn arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/new-example-classifier-model
```
出力:  

```
{
    "FlywheelProperties": {
        "FlywheelArn": "arn:aws:comprehend:us-west-2:111122223333:flywheel/flywheel-entity",
        "ActiveModelArn": "arn:aws:comprehend:us-west-2:111122223333:document-classifier/example-classifier/version/new-example-classifier-model",
        "DataAccessRoleArn": "arn:aws:iam::111122223333:role/service-role/AmazonComprehendServiceRole-example-role",
        "TaskConfig": {
            "LanguageCode": "en",
            "DocumentClassificationConfig": {
                "Mode": "MULTI_CLASS"
            }
        },
        "DataLakeS3Uri": "s3://amzn-s3-demo-bucket/flywheel-entity/schemaVersion=1/20230616T200543Z/",
        "DataSecurityConfig": {},
        "Status": "ACTIVE",
        "ModelType": "DOCUMENT_CLASSIFIER",
        "CreationTime": "2023-06-16T20:05:43.242000+00:00",
        "LastModifiedTime": "2023-06-19T04:00:43.027000+00:00",
        "LatestFlywheelIteration": "20230619T040032Z"
    }
}
```
詳細については、「*Amazon Comprehend デベロッパーガイド*」の「[Flywheel Overview](https://docs.aws.amazon.com/comprehend/latest/dg/flywheels-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFlywheel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehend/update-flywheel.html)」を参照してください。

# を使用した Amazon Comprehend Medical の例 AWS CLI
<a name="cli_2_comprehendmedical_code_examples"></a>

次のコード例は、Amazon Comprehend Medical AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-entities-detection-v2-job`
<a name="comprehendmedical_DescribeEntitiesDetectionV2Job_cli_2_topic"></a>

次のコード例は、`describe-entities-detection-v2-job` を使用する方法を示しています。

**AWS CLI**  
**エンティティ検出ジョブを記述するには**  
次の `describe-entities-detection-v2-job` の例では、非同期エンティティ検出ジョブに関連付けられたプロパティを表示しています。  

```
aws comprehendmedical describe-entities-detection-v2-job \
    --job-id "ab9887877365fe70299089371c043b96"
```
出力:  

```
{
    "ComprehendMedicalAsyncJobProperties": {
        "JobId": "ab9887877365fe70299089371c043b96",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2020-03-18T21:20:15.614000+00:00",
        "EndTime": "2020-03-18T21:27:07.350000+00:00",
        "ExpirationTime": "2020-07-16T21:20:15+00:00",
        "InputDataConfig": {
            "S3Bucket": "comp-med-input",
            "S3Key": ""
        },
        "OutputDataConfig": {
            "S3Bucket": "comp-med-output",
            "S3Key": "867139942017-EntitiesDetection-ab9887877365fe70299089371c043b96/"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
        "ModelVersion": "DetectEntitiesModelV20190930"
    }
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEntitiesDetectionV2Job](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/describe-entities-detection-v2-job.html)」を参照してください。

### `describe-icd10-cm-inference-job`
<a name="comprehendmedical_DescribeIcd10CmInferenceJob_cli_2_topic"></a>

次のコード例は、`describe-icd10-cm-inference-job` を使用する方法を示しています。

**AWS CLI**  
**ICD-10-CM 推論ジョブを記述するには**  
次の `describe-icd10-cm-inference-job` の例では、指定された job-id を持つリクエストされた推論ジョブのプロパティを表示しています。  

```
aws comprehendmedical describe-icd10-cm-inference-job \
    --job-id "5780034166536cdb52ffa3295a1b00a7"
```
出力:  

```
{
    "ComprehendMedicalAsyncJobProperties": {
        "JobId": "5780034166536cdb52ffa3295a1b00a7",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2020-05-18T21:20:15.614000+00:00",
        "EndTime": "2020-05-18T21:27:07.350000+00:00",
        "ExpirationTime": "2020-09-16T21:20:15+00:00",
        "InputDataConfig": {
            "S3Bucket": "comp-med-input",
            "S3Key": "AKIAIOSFODNN7EXAMPLE"
        },
        "OutputDataConfig": {
            "S3Bucket": "comp-med-output",
            "S3Key": "AKIAIOSFODNN7EXAMPLE"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
        "ModelVersion":  "0.1.0"
    }
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIcd10CmInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/describe-icd10-cm-inference-job.html)」を参照してください。

### `describe-phi-detection-job`
<a name="comprehendmedical_DescribePhiDetectionJob_cli_2_topic"></a>

次のコード例は、`describe-phi-detection-job` を使用する方法を示しています。

**AWS CLI**  
**PHI 検出ジョブを記述するには**  
次の `describe-phi-detection-job` の例では、非同期の保護対象の医療情報 (PHI) 検出ジョブに関連付けられたプロパティを表示しています。  

```
aws comprehendmedical describe-phi-detection-job \
    --job-id "4750034166536cdb52ffa3295a1b00a3"
```
出力:  

```
{
    "ComprehendMedicalAsyncJobProperties": {
        "JobId": "4750034166536cdb52ffa3295a1b00a3",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2020-03-19T20:38:37.594000+00:00",
        "EndTime": "2020-03-19T20:45:07.894000+00:00",
        "ExpirationTime": "2020-07-17T20:38:37+00:00",
        "InputDataConfig": {
            "S3Bucket": "comp-med-input",
            "S3Key": ""
        },
        "OutputDataConfig": {
            "S3Bucket": "comp-med-output",
            "S3Key": "867139942017-PHIDetection-4750034166536cdb52ffa3295a1b00a3/"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
        "ModelVersion": "PHIModelV20190903"
    }
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePhiDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/describe-phi-detection-job.html)」を参照してください。

### `describe-rx-norm-inference-job`
<a name="comprehendmedical_DescribeRxNormInferenceJob_cli_2_topic"></a>

次のコード例は、`describe-rx-norm-inference-job` を使用する方法を示しています。

**AWS CLI**  
**RxNorm 推論ジョブを記述するには**  
次の `describe-rx-norm-inference-job` の例では、指定された job-id を持つリクエストされた推論ジョブのプロパティを表示しています。  

```
aws comprehendmedical describe-rx-norm-inference-job \
    --job-id "eg8199877365fc70299089371c043b96"
```
出力:  

```
{
    "ComprehendMedicalAsyncJobProperties": {
        "JobId": "g8199877365fc70299089371c043b96",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2020-05-18T21:20:15.614000+00:00",
        "EndTime": "2020-05-18T21:27:07.350000+00:00",
        "ExpirationTime": "2020-09-16T21:20:15+00:00",
        "InputDataConfig": {
            "S3Bucket": "comp-med-input",
            "S3Key": "AKIAIOSFODNN7EXAMPLE"
        },
        "OutputDataConfig": {
            "S3Bucket": "comp-med-output",
            "S3Key": "AKIAIOSFODNN7EXAMPLE"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
        "ModelVersion": "0.0.0"
    }
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRxNormInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/describe-rx-norm-inference-job.html)」を参照してください。

### `describe-snomedct-inference-job`
<a name="comprehendmedical_DescribeSnomedctInferenceJob_cli_2_topic"></a>

次のコード例は、`describe-snomedct-inference-job` を使用する方法を示しています。

**AWS CLI**  
**SNOMED CT 推論ジョブを記述するには**  
次の `describe-snomedct-inference-job` の例では、指定された job-id を持つリクエストされた推論ジョブのプロパティを表示しています。  

```
aws comprehendmedical describe-snomedct-inference-job \
    --job-id "2630034166536cdb52ffa3295a1b00a7"
```
出力:  

```
{
    "ComprehendMedicalAsyncJobProperties": {
        "JobId": "2630034166536cdb52ffa3295a1b00a7",
        "JobStatus": "COMPLETED",
        "SubmitTime": "2021-12-18T21:20:15.614000+00:00",
        "EndTime": "2021-12-18T21:27:07.350000+00:00",
        "ExpirationTime": "2022-05-16T21:20:15+00:00",
        "InputDataConfig": {
            "S3Bucket": "comp-med-input",
            "S3Key": "AKIAIOSFODNN7EXAMPLE"
        },
        "OutputDataConfig": {
            "S3Bucket": "comp-med-output",
            "S3Key": "AKIAIOSFODNN7EXAMPLE"
        },
        "LanguageCode": "en",
        "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
        "ModelVersion":  "0.1.0"
    }
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSnomedctInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/describe-snomedct-inference-job.html)」を参照してください。

### `detect-entities-v2`
<a name="comprehendmedical_DetectEntitiesV2_cli_2_topic"></a>

次のコード例は、`detect-entities-v2` を使用する方法を示しています。

**AWS CLI**  
**例 1: テキストから直接エンティティを検出するには**  
次の `detect-entities-v2` の例では、検出されたエンティティを表示し、入力テキストから直接タイプに従ってラベル付けしています。  

```
aws comprehendmedical detect-entities-v2 \
    --text "Sleeping trouble on present dosage of Clonidine. Severe rash on face and leg, slightly itchy."
```
出力:  

```
{
    "Id": 0,
    "BeginOffset": 38,
    "EndOffset": 47,
    "Score": 0.9942955374717712,
    "Text": "Clonidine",
    "Category": "MEDICATION",
    "Type": "GENERIC_NAME",
    "Traits": []
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Detect Entities Version 2](https://docs.aws.amazon.com/comprehend/latest/dg/extracted-med-info-V2.html)」を参照してください。  
**例 2: ファイルパスからエンティティを検出するには**  
次の `detect-entities-v2` の例では、検出されたエンティティを表示し、ファイルパスのタイプに従ってラベル付けしています。  

```
aws comprehendmedical detect-entities-v2 \
    --text file://medical_entities.txt
```
`medical_entities.txt` の内容:  

```
{
    "Sleeping trouble on present dosage of Clonidine. Severe rash on face and leg, slightly itchy."
}
```
出力:  

```
{
    "Id": 0,
    "BeginOffset": 38,
    "EndOffset": 47,
    "Score": 0.9942955374717712,
    "Text": "Clonidine",
    "Category": "MEDICATION",
    "Type": "GENERIC_NAME",
    "Traits": []
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Detect Entities Version 2](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-entitiesv2.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectEntitiesV2](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/detect-entities-v2.html)」を参照してください。

### `detect-phi`
<a name="comprehendmedical_DetectPhi_cli_2_topic"></a>

次のコード例は、`detect-phi` を使用する方法を示しています。

**AWS CLI**  
**例 1: 保護対象の医療情報 (PHI) をテキストから直接検出するには**  
次の `detect-phi` の例では、検出された保護対象の医療情報 (PHI) エンティティを入力テキストから直接表示しています。  

```
aws comprehendmedical detect-phi \
    --text "Patient Carlos Salazar presented with rash on his upper extremities and dry cough. He lives at 100 Main Street, Anytown, USA where he works from his home as a carpenter."
```
出力:  

```
{
    "Entities": [
        {
            "Id": 0,
            "BeginOffset": 8,
            "EndOffset": 21,
            "Score": 0.9914507269859314,
            "Text": "Carlos Salazar",
            "Category": "PROTECTED_HEALTH_INFORMATION",
            "Type": "NAME",
            "Traits": []
        },
        {
            "Id": 1,
            "BeginOffset": 94,
            "EndOffset": 109,
            "Score": 0.871849775314331,
            "Text": "100 Main Street, Anytown, USA",
            "Category": "PROTECTED_HEALTH_INFORMATION",
            "Type": "ADDRESS",
            "Traits": []
        },
        {
            "Id": 2,
            "BeginOffset": 145,
            "EndOffset": 154,
            "Score": 0.8302185535430908,
            "Text": "carpenter",
            "Category": "PROTECTED_HEALTH_INFORMATION",
            "Type": "PROFESSION",
            "Traits": []
        }
    ],
    "ModelVersion": "0.0.0"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Detect PHI](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-phi.html)」を参照してください。  
**例 2: ファイルパスから直接、保護対象の医療情報 (PHI) を検出するには**  
次の `detect-phi` の例では、ファイルパスから検出された保護対象の医療情報 (PHI) エンティティを表示しています。  

```
aws comprehendmedical detect-phi \
    --text file://phi.txt
```
`phi.txt` の内容:  

```
"Patient Carlos Salazar presented with a rash on his upper extremities and a dry cough. He lives at 100 Main Street, Anytown, USA, where he works from his home as a carpenter."
```
出力:  

```
{
    "Entities": [
        {
            "Id": 0,
            "BeginOffset": 8,
            "EndOffset": 21,
            "Score": 0.9914507269859314,
            "Text": "Carlos Salazar",
            "Category": "PROTECTED_HEALTH_INFORMATION",
            "Type": "NAME",
            "Traits": []
        },
        {
            "Id": 1,
            "BeginOffset": 94,
            "EndOffset": 109,
            "Score": 0.871849775314331,
            "Text": "100 Main Street, Anytown, USA",
            "Category": "PROTECTED_HEALTH_INFORMATION",
            "Type": "ADDRESS",
            "Traits": []
        },
        {
            "Id": 2,
            "BeginOffset": 145,
            "EndOffset": 154,
            "Score": 0.8302185535430908,
            "Text": "carpenter",
            "Category": "PROTECTED_HEALTH_INFORMATION",
            "Type": "PROFESSION",
            "Traits": []
        }
    ],
    "ModelVersion": "0.0.0"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Detect PHI](https://docs.aws.amazon.com/comprehend/latest/dg/how-medical-phi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetectPhi](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/detect-phi.html)」を参照してください。

### `infer-icd10-cm`
<a name="comprehendmedical_InferIcd10Cm_cli_2_topic"></a>

次のコード例は、`infer-icd10-cm` を使用する方法を示しています。

**AWS CLI**  
**例 1: 病状エンティティを検出し、テキストから直接 ICD-10-CM オントロジーにリンクするには**  
次の `infer-icd10-cm` の例では、検出された病状エンティティにラベルを付け、それらのエンティティを国際疾病分類の 2019 年改訂版 (ICD-10-CM) のコードにリンクしています。  

```
aws comprehendmedical infer-icd10-cm \
    --text "The patient complains of abdominal pain, has a long-standing history of diabetes treated with Micronase daily."
```
出力:  

```
{
    "Entities": [
        {
            "Id": 0,
            "Text": "abdominal pain",
            "Category": "MEDICAL_CONDITION",
            "Type": "DX_NAME",
            "Score": 0.9475538730621338,
            "BeginOffset": 28,
            "EndOffset": 42,
            "Attributes": [],
            "Traits": [
                {
                    "Name": "SYMPTOM",
                    "Score": 0.6724207401275635
                }
            ],
            "ICD10CMConcepts": [
                {
                    "Description": "Unspecified abdominal pain",
                    "Code": "R10.9",
                    "Score": 0.6904221177101135
                },
                {
                    "Description": "Epigastric pain",
                    "Code": "R10.13",
                    "Score": 0.1364113688468933
                },
                {
                    "Description": "Generalized abdominal pain",
                    "Code": "R10.84",
                    "Score": 0.12508003413677216
                },
                {
                    "Description": "Left lower quadrant pain",
                    "Code": "R10.32",
                    "Score": 0.10063883662223816
                },
                {
                    "Description": "Lower abdominal pain, unspecified",
                    "Code": "R10.30",
                    "Score": 0.09933677315711975
                }
            ]
        },
        {
            "Id": 1,
            "Text": "diabetes",
            "Category": "MEDICAL_CONDITION",
            "Type": "DX_NAME",
            "Score": 0.9899052977561951,
            "BeginOffset": 75,
            "EndOffset": 83,
            "Attributes": [],
            "Traits": [
                {
                    "Name": "DIAGNOSIS",
                    "Score": 0.9258432388305664
                }
            ],
            "ICD10CMConcepts": [
                {
                    "Description": "Type 2 diabetes mellitus without complications",
                    "Code": "E11.9",
                    "Score": 0.7158446311950684
                },
                {
                    "Description": "Family history of diabetes mellitus",
                    "Code": "Z83.3",
                    "Score": 0.5704703330993652
                },
                {
                    "Description": "Family history of other endocrine, nutritional and metabolic diseases",
                    "Code": "Z83.49",
                    "Score": 0.19856023788452148
                },
                {
                    "Description": "Type 1 diabetes mellitus with ketoacidosis without coma",
                    "Code": "E10.10",
                    "Score": 0.13285516202449799
                },
                {
                    "Description": "Type 2 diabetes mellitus with hyperglycemia",
                    "Code": "E11.65",
                    "Score": 0.0993388369679451
                }
            ]
        }
    ],
    "ModelVersion": "0.1.0"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Infer ICD10-CM](https://docs.aws.amazon.com/comprehend/latest/dg/ontology-linking-icd10.html)」を参照してください。  
**例 2: ファイルパスウェイから病状エンティティを検出し、ICD-10-CM オントロジーにリンクするには**  
次の `infer-icd-10-cm` の例では、検出された病状エンティティにラベルを付け、それらのエンティティを国際疾病分類の 2019 年改訂版 (ICD-10-CM) のコードにリンクしています。  

```
aws comprehendmedical infer-icd10-cm \
    --text file://icd10cm.txt
```
`icd10cm.txt` の内容:  

```
{
    "The patient complains of abdominal pain, has a long-standing history of diabetes treated with Micronase daily."
}
```
出力:  

```
{
    "Entities": [
        {
            "Id": 0,
            "Text": "abdominal pain",
            "Category": "MEDICAL_CONDITION",
            "Type": "DX_NAME",
            "Score": 0.9475538730621338,
            "BeginOffset": 28,
            "EndOffset": 42,
            "Attributes": [],
            "Traits": [
                {
                    "Name": "SYMPTOM",
                    "Score": 0.6724207401275635
                }
            ],
            "ICD10CMConcepts": [
                {
                    "Description": "Unspecified abdominal pain",
                    "Code": "R10.9",
                    "Score": 0.6904221177101135
                },
                {
                    "Description": "Epigastric pain",
                    "Code": "R10.13",
                    "Score": 0.1364113688468933
                },
                {
                    "Description": "Generalized abdominal pain",
                    "Code": "R10.84",
                    "Score": 0.12508003413677216
                },
                {
                    "Description": "Left lower quadrant pain",
                    "Code": "R10.32",
                    "Score": 0.10063883662223816
                },
                {
                    "Description": "Lower abdominal pain, unspecified",
                    "Code": "R10.30",
                    "Score": 0.09933677315711975
                }
            ]
        },
        {
            "Id": 1,
            "Text": "diabetes",
            "Category": "MEDICAL_CONDITION",
            "Type": "DX_NAME",
            "Score": 0.9899052977561951,
            "BeginOffset": 75,
            "EndOffset": 83,
            "Attributes": [],
            "Traits": [
                {
                    "Name": "DIAGNOSIS",
                    "Score": 0.9258432388305664
                }
            ],
            "ICD10CMConcepts": [
                {
                    "Description": "Type 2 diabetes mellitus without complications",
                    "Code": "E11.9",
                    "Score": 0.7158446311950684
                },
                {
                    "Description": "Family history of diabetes mellitus",
                    "Code": "Z83.3",
                    "Score": 0.5704703330993652
                },
                {
                    "Description": "Family history of other endocrine, nutritional and metabolic diseases",
                    "Code": "Z83.49",
                    "Score": 0.19856023788452148
                },
                {
                    "Description": "Type 1 diabetes mellitus with ketoacidosis without coma",
                    "Code": "E10.10",
                    "Score": 0.13285516202449799
                },
                {
                    "Description": "Type 2 diabetes mellitus with hyperglycemia",
                    "Code": "E11.65",
                    "Score": 0.0993388369679451
                }
            ]
        }
    ],
    "ModelVersion": "0.1.0"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Infer-ICD10-CM](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontology-icd10.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InferIcd10Cm](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/infer-icd10-cm.html)」を参照してください。

### `infer-rx-norm`
<a name="comprehendmedical_InferRxNorm_cli_2_topic"></a>

次のコード例は、`infer-rx-norm` を使用する方法を示しています。

**AWS CLI**  
**例 1: 薬剤エンティティを検出し、テキストから直接 RxNorm にリンクするには**  
次の `infer-rx-norm` の例では、検出された薬剤エンティティを表示してラベル付けし、それらのエンティティを米国国立医学図書館の RxNorm データベースの概念識別子 (RxCUI) にリンクしています。  

```
aws comprehendmedical infer-rx-norm \
    --text "Patient reports taking Levothyroxine 125 micrograms p.o. once daily, but denies taking Synthroid."
```
出力:  

```
{
    "Entities": [
        {
            "Id": 0,
            "Text": "Levothyroxine",
            "Category": "MEDICATION",
            "Type": "GENERIC_NAME",
            "Score": 0.9996285438537598,
            "BeginOffset": 23,
            "EndOffset": 36,
            "Attributes": [
                {
                    "Type": "DOSAGE",
                    "Score": 0.9892290830612183,
                    "RelationshipScore": 0.9997978806495667,
                    "Id": 1,
                    "BeginOffset": 37,
                    "EndOffset": 51,
                    "Text": "125 micrograms",
                    "Traits": []
                },
                {
                    "Type": "ROUTE_OR_MODE",
                    "Score": 0.9988924860954285,
                    "RelationshipScore": 0.998291552066803,
                    "Id": 2,
                    "BeginOffset": 52,
                    "EndOffset": 56,
                    "Text": "p.o.",
                    "Traits": []
                },
                {
                    "Type": "FREQUENCY",
                    "Score": 0.9953463673591614,
                    "RelationshipScore": 0.9999889135360718,
                    "Id": 3,
                    "BeginOffset": 57,
                    "EndOffset": 67,
                    "Text": "once daily",
                    "Traits": []
                }
            ],
            "Traits": [],
            "RxNormConcepts": [
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet",
                    "Code": "966224",
                    "Score": 0.9912070631980896
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Capsule",
                    "Code": "966405",
                    "Score": 0.8698278665542603
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet [Synthroid]",
                    "Code": "966191",
                    "Score": 0.7448257803916931
                },
                {
                    "Description": "levothyroxine",
                    "Code": "10582",
                    "Score": 0.7050482630729675
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet [Levoxyl]",
                    "Code": "966190",
                    "Score": 0.6921631693840027
                }
            ]
        },
        {
            "Id": 4,
            "Text": "Synthroid",
            "Category": "MEDICATION",
            "Type": "BRAND_NAME",
            "Score": 0.9946461319923401,
            "BeginOffset": 86,
            "EndOffset": 95,
            "Attributes": [],
            "Traits": [
                {
                    "Name": "NEGATION",
                    "Score": 0.5167351961135864
                }
            ],
            "RxNormConcepts": [
                {
                    "Description": "Synthroid",
                    "Code": "224920",
                    "Score": 0.9462039470672607
                },
                {
                    "Description": "Levothyroxine Sodium 0.088 MG Oral Tablet [Synthroid]",
                    "Code": "966282",
                    "Score": 0.8309829235076904
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet [Synthroid]",
                    "Code": "966191",
                    "Score": 0.4945160448551178
                },
                {
                    "Description": "Levothyroxine Sodium 0.05 MG Oral Tablet [Synthroid]",
                    "Code": "966247",
                    "Score": 0.3674522042274475
                },
                {
                    "Description": "Levothyroxine Sodium 0.025 MG Oral Tablet [Synthroid]",
                    "Code": "966158",
                    "Score": 0.2588822841644287
                }
            ]
        }
    ],
    "ModelVersion": "0.0.0"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Infer RxNorm](https://docs.aws.amazon.com/comprehend/latest/dg/ontology-linking-rxnorm.html)」を参照してください。  
**例 2: 薬剤エンティティを検出し、ファイルパスから RxNorm にリンクするには。**  
次の `infer-rx-norm` の例では、検出された薬剤エンティティを表示してラベル付けし、それらのエンティティを米国国立医学図書館の RxNorm データベースの概念識別子 (RxCUI) にリンクしています。  

```
aws comprehendmedical infer-rx-norm \
    --text file://rxnorm.txt
```
`rxnorm.txt` の内容:  

```
{
    "Patient reports taking Levothyroxine 125 micrograms p.o. once daily, but denies taking Synthroid."
}
```
出力:  

```
{
    "Entities": [
        {
            "Id": 0,
            "Text": "Levothyroxine",
            "Category": "MEDICATION",
            "Type": "GENERIC_NAME",
            "Score": 0.9996285438537598,
            "BeginOffset": 23,
            "EndOffset": 36,
            "Attributes": [
                {
                    "Type": "DOSAGE",
                    "Score": 0.9892290830612183,
                    "RelationshipScore": 0.9997978806495667,
                    "Id": 1,
                    "BeginOffset": 37,
                    "EndOffset": 51,
                    "Text": "125 micrograms",
                    "Traits": []
                },
                {
                    "Type": "ROUTE_OR_MODE",
                    "Score": 0.9988924860954285,
                    "RelationshipScore": 0.998291552066803,
                    "Id": 2,
                    "BeginOffset": 52,
                    "EndOffset": 56,
                    "Text": "p.o.",
                    "Traits": []
                },
                {
                    "Type": "FREQUENCY",
                    "Score": 0.9953463673591614,
                    "RelationshipScore": 0.9999889135360718,
                    "Id": 3,
                    "BeginOffset": 57,
                    "EndOffset": 67,
                    "Text": "once daily",
                    "Traits": []
                }
            ],
            "Traits": [],
            "RxNormConcepts": [
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet",
                    "Code": "966224",
                    "Score": 0.9912070631980896
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Capsule",
                    "Code": "966405",
                    "Score": 0.8698278665542603
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet [Synthroid]",
                    "Code": "966191",
                    "Score": 0.7448257803916931
                },
                {
                    "Description": "levothyroxine",
                    "Code": "10582",
                    "Score": 0.7050482630729675
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet [Levoxyl]",
                    "Code": "966190",
                    "Score": 0.6921631693840027
                }
            ]
        },
        {
            "Id": 4,
            "Text": "Synthroid",
            "Category": "MEDICATION",
            "Type": "BRAND_NAME",
            "Score": 0.9946461319923401,
            "BeginOffset": 86,
            "EndOffset": 95,
            "Attributes": [],
            "Traits": [
                {
                    "Name": "NEGATION",
                    "Score": 0.5167351961135864
                }
            ],
            "RxNormConcepts": [
                {
                    "Description": "Synthroid",
                    "Code": "224920",
                    "Score": 0.9462039470672607
                },
                {
                    "Description": "Levothyroxine Sodium 0.088 MG Oral Tablet [Synthroid]",
                    "Code": "966282",
                    "Score": 0.8309829235076904
                },
                {
                    "Description": "Levothyroxine Sodium 0.125 MG Oral Tablet [Synthroid]",
                    "Code": "966191",
                    "Score": 0.4945160448551178
                },
                {
                    "Description": "Levothyroxine Sodium 0.05 MG Oral Tablet [Synthroid]",
                    "Code": "966247",
                    "Score": 0.3674522042274475
                },
                {
                    "Description": "Levothyroxine Sodium 0.025 MG Oral Tablet [Synthroid]",
                    "Code": "966158",
                    "Score": 0.2588822841644287
                }
            ]
        }
    ],
    "ModelVersion": "0.0.0"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Infer RxNorm](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontology-RxNorm.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InferRxNorm](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/infer-rx-norm.html)」を参照してください。

### `infer-snomedct`
<a name="comprehendmedical_InferSnomedct_cli_2_topic"></a>

次のコード例は、`infer-snomedct` を使用する方法を示しています。

**AWS CLI**  
**例: エンティティを検出し、テキストから直接 SNOMED CT オントロジーにリンクする**  
次の `infer-snomedct` の例では、薬剤エンティティを検出し、それらを 2021-03 バージョンの国際医療用語集 (Systematized Nomenclature of Medicine, Clinical Terms: SNOMED CT) の概念にリンクする方法を示しています。  

```
aws comprehendmedical infer-snomedct \
    --text "The patient complains of abdominal pain, has a long-standing history of diabetes treated with Micronase daily."
```
出力:  

```
{
    "Entities": [
        {
            "Id": 3,
            "BeginOffset": 26,
            "EndOffset": 40,
            "Score": 0.9598260521888733,
            "Text": "abdominal pain",
            "Category": "MEDICAL_CONDITION",
            "Type": "DX_NAME",
            "Traits": [
                {
                    "Name": "SYMPTOM",
                    "Score": 0.6819021701812744
                }
            ]
        },
        {
            "Id": 4,
            "BeginOffset": 73,
            "EndOffset": 81,
            "Score": 0.9905840158462524,
            "Text": "diabetes",
            "Category": "MEDICAL_CONDITION",
            "Type": "DX_NAME",
            "Traits": [
                {
                    "Name": "DIAGNOSIS",
                    "Score": 0.9255214333534241
                }
            ]
        },
        {
            "Id": 1,
            "BeginOffset": 95,
            "EndOffset": 104,
            "Score": 0.6371926665306091,
            "Text": "Micronase",
            "Category": "MEDICATION",
            "Type": "BRAND_NAME",
            "Traits": [],
            "Attributes": [
                {
                    "Type": "FREQUENCY",
                    "Score": 0.9761165380477905,
                    "RelationshipScore": 0.9984188079833984,
                    "RelationshipType": "FREQUENCY",
                    "Id": 2,
                    "BeginOffset": 105,
                    "EndOffset": 110,
                    "Text": "daily",
                    "Category": "MEDICATION",
                    "Traits": []
                }
            ]
        }
    ],
    "UnmappedAttributes": [],
    "ModelVersion": "1.0.0"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[InferSNOMEDCT](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontology-linking-snomed.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InferSnomedct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/infer-snomedct.html)」を参照してください。

### `list-entities-detection-v2-jobs`
<a name="comprehendmedical_ListEntitiesDetectionV2Jobs_cli_2_topic"></a>

次のコード例は、`list-entities-detection-v2-jobs` を使用する方法を示しています。

**AWS CLI**  
**エンティティ検出ジョブを一覧表示するには**  
次の `list-entities-detection-v2-jobs` の例では、現在の非同期検出ジョブを一覧表示しています。  

```
aws comprehendmedical list-entities-detection-v2-jobs
```
出力:  

```
{
    "ComprehendMedicalAsyncJobPropertiesList": [
        {
            "JobId": "ab9887877365fe70299089371c043b96",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2020-03-19T20:38:37.594000+00:00",
            "EndTime": "2020-03-19T20:45:07.894000+00:00",
            "ExpirationTime": "2020-07-17T20:38:37+00:00",
            "InputDataConfig": {
                "S3Bucket": "comp-med-input",
                "S3Key": ""
            },
            "OutputDataConfig": {
                "S3Bucket": "comp-med-output",
                "S3Key": "867139942017-EntitiesDetection-ab9887877365fe70299089371c043b96/"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
            "ModelVersion": "DetectEntitiesModelV20190930"
        }
    ]
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEntitiesDetectionV2Jobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/list-entities-detection-v2-jobs.html)」を参照してください。

### `list-icd10-cm-inference-jobs`
<a name="comprehendmedical_ListIcd10CmInferenceJobs_cli_2_topic"></a>

次のコード例は、`list-icd10-cm-inference-jobs` を使用する方法を示しています。

**AWS CLI**  
**現在のすべての ICD-10-CM 推論ジョブを一覧表示するには**  
次の例では、`list-icd10-cm-inference-jobs` オペレーションが現在の非同期 ICD-10-CM バッチ推論ジョブのリストを返す方法を示します。  

```
aws comprehendmedical list-icd10-cm-inference-jobs
```
出力:  

```
{
    "ComprehendMedicalAsyncJobPropertiesList": [
        {
            "JobId": "5780034166536cdb52ffa3295a1b00a7",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2020-05-19T20:38:37.594000+00:00",
            "EndTime": "2020-05-19T20:45:07.894000+00:00",
            "ExpirationTime": "2020-09-17T20:38:37+00:00",
            "InputDataConfig": {
                "S3Bucket": "comp-med-input",
                "S3Key": "AKIAIOSFODNN7EXAMPLE"
            },
            "OutputDataConfig": {
                "S3Bucket": "comp-med-output",
                "S3Key": "AKIAIOSFODNN7EXAMPLE"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
            "ModelVersion":  "0.1.0"
        }
    ]
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIcd10CmInferenceJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/list-icd10-cm-inference-jobs.html)」を参照してください。

### `list-phi-detection-jobs`
<a name="comprehendmedical_ListPhiDetectionJobs_cli_2_topic"></a>

次のコード例は、`list-phi-detection-jobs` を使用する方法を示しています。

**AWS CLI**  
**保護対象の医療情報 (PHI) 検出ジョブを一覧表示するには**  
次の `list-phi-detection-jobs` の例では、現在の保護対象の医療情報 (PHI) 検出ジョブを一覧表示しています。  

```
aws comprehendmedical list-phi-detection-jobs
```
出力:  

```
{
    "ComprehendMedicalAsyncJobPropertiesList": [
        {
            "JobId": "4750034166536cdb52ffa3295a1b00a3",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2020-03-19T20:38:37.594000+00:00",
            "EndTime": "2020-03-19T20:45:07.894000+00:00",
            "ExpirationTime": "2020-07-17T20:38:37+00:00",
            "InputDataConfig": {
                "S3Bucket": "comp-med-input",
                "S3Key": ""
            },
            "OutputDataConfig": {
                "S3Bucket": "comp-med-output",
                "S3Key": "867139942017-PHIDetection-4750034166536cdb52ffa3295a1b00a3/"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
            "ModelVersion": "PHIModelV20190903"
        }
    ]
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPhiDetectionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/list-phi-detection-jobs.html)」を参照してください。

### `list-rx-norm-inference-jobs`
<a name="comprehendmedical_ListRxNormInferenceJobs_cli_2_topic"></a>

次のコード例は、`list-rx-norm-inference-jobs` を使用する方法を示しています。

**AWS CLI**  
**現在のすべての Rx-Norm 推論ジョブを一覧表示するには**  
次の例では、`list-rx-norm-inference-jobs` が現在の非同期 Rx-Norm バッチ推論ジョブのリストを返す方法を示します。  

```
aws comprehendmedical list-rx-norm-inference-jobs
```
出力:  

```
{
    "ComprehendMedicalAsyncJobPropertiesList": [
        {
            "JobId": "4980034166536cfb52gga3295a1b00a3",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2020-05-19T20:38:37.594000+00:00",
            "EndTime": "2020-05-19T20:45:07.894000+00:00",
            "ExpirationTime": "2020-09-17T20:38:37+00:00",
            "InputDataConfig": {
                "S3Bucket": "comp-med-input",
                "S3Key": "AKIAIOSFODNN7EXAMPLE"
            },
            "OutputDataConfig": {
                "S3Bucket": "comp-med-output",
                "S3Key": "AKIAIOSFODNN7EXAMPLE"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
            "ModelVersion": "0.0.0"
        }
    ]
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRxNormInferenceJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/list-rx-norm-inference-jobs.html)」を参照してください。

### `list-snomedct-inference-jobs`
<a name="comprehendmedical_ListSnomedctInferenceJobs_cli_2_topic"></a>

次のコード例は、`list-snomedct-inference-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべての SNOMED CT 推論ジョブを一覧表示するには**  
次の例では、`list-snomedct-inference-jobs` オペレーションが現在の非同期 SNOMED CT バッチ推論ジョブのリストを返す方法を示します。  

```
aws comprehendmedical list-snomedct-inference-jobs
```
出力:  

```
{
    "ComprehendMedicalAsyncJobPropertiesList": [
        {
            "JobId": "5780034166536cdb52ffa3295a1b00a7",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2020-05-19T20:38:37.594000+00:00",
            "EndTime": "2020-05-19T20:45:07.894000+00:00",
            "ExpirationTime": "2020-09-17T20:38:37+00:00",
            "InputDataConfig": {
                "S3Bucket": "comp-med-input",
                "S3Key": "AKIAIOSFODNN7EXAMPLE"
            },
            "OutputDataConfig": {
                "S3Bucket": "comp-med-output",
                "S3Key": "AKIAIOSFODNN7EXAMPLE"
            },
            "LanguageCode": "en",
            "DataAccessRoleArn": "arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole",
            "ModelVersion":  "0.1.0"
        }
    ]
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSnomedctInferenceJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/list-snomedct-inference-jobs.html)」を参照してください。

### `start-entities-detection-v2-job`
<a name="comprehendmedical_StartEntitiesDetectionV2Job_cli_2_topic"></a>

次のコード例は、`start-entities-detection-v2-job` を使用する方法を示しています。

**AWS CLI**  
**エンティティ検出ジョブを開始するには**  
次の `start-entities-detection-v2-job` の例では、非同期エンティティ検出ジョブを開始しています。  

```
aws comprehendmedical start-entities-detection-v2-job \
    --input-data-config "S3Bucket=comp-med-input" \
    --output-data-config "S3Bucket=comp-med-output" \
    --data-access-role-arn arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole \
    --language-code en
```
出力:  

```
{
    "JobId": "ab9887877365fe70299089371c043b96"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartEntitiesDetectionV2Job](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/start-entities-detection-v2-job.html)」を参照してください。

### `start-icd10-cm-inference-job`
<a name="comprehendmedical_StartIcd10CmInferenceJob_cli_2_topic"></a>

次のコード例は、`start-icd10-cm-inference-job` を使用する方法を示しています。

**AWS CLI**  
**ICD-10-CM 推論ジョブを開始するには**  
次の `start-icd10-cm-inference-job` の例では、ICD-10-CM 推論バッチ分析ジョブを開始しています。  

```
aws comprehendmedical start-icd10-cm-inference-job \
    --input-data-config "S3Bucket=comp-med-input" \
    --output-data-config "S3Bucket=comp-med-output" \
    --data-access-role-arn arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole \
    --language-code en
```
出力:  

```
{
    "JobId": "ef7289877365fc70299089371c043b96"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartIcd10CmInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/start-icd10-cm-inference-job.html)」を参照してください。

### `start-phi-detection-job`
<a name="comprehendmedical_StartPhiDetectionJob_cli_2_topic"></a>

次のコード例は、`start-phi-detection-job` を使用する方法を示しています。

**AWS CLI**  
**PHI 検出ジョブを開始するには**  
次の `start-phi-detection-job` の例では、非同期 PHI エンティティ検出ジョブを開始しています。  

```
aws comprehendmedical start-phi-detection-job \
    --input-data-config "S3Bucket=comp-med-input" \
    --output-data-config "S3Bucket=comp-med-output" \
    --data-access-role-arn arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole \
    --language-code en
```
出力:  

```
{
    "JobId": "ab9887877365fe70299089371c043b96"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartPhiDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/start-phi-detection-job.html)」を参照してください。

### `start-rx-norm-inference-job`
<a name="comprehendmedical_StartRxNormInferenceJob_cli_2_topic"></a>

次のコード例は、`start-rx-norm-inference-job` を使用する方法を示しています。

**AWS CLI**  
**RxNorm 推論ジョブを開始するには**  
次の `start-rx-norm-inference-job` の例では、RxNorm 推論バッチ分析ジョブを開始しています。  

```
aws comprehendmedical start-rx-norm-inference-job \
    --input-data-config "S3Bucket=comp-med-input" \
    --output-data-config "S3Bucket=comp-med-output" \
    --data-access-role-arn arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole \
    --language-code en
```
出力:  

```
{
    "JobId": "eg8199877365fc70299089371c043b96"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartRxNormInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/start-rx-norm-inference-job.html)」を参照してください。

### `start-snomedct-inference-job`
<a name="comprehendmedical_StartSnomedctInferenceJob_cli_2_topic"></a>

次のコード例は、`start-snomedct-inference-job` を使用する方法を示しています。

**AWS CLI**  
**SNOMED CT 推論ジョブを開始するには**  
次の `start-snomedct-inference-job` の例では、SNOMED CT 推論バッチ分析ジョブを開始しています。  

```
aws comprehendmedical start-snomedct-inference-job \
    --input-data-config "S3Bucket=comp-med-input" \
    --output-data-config "S3Bucket=comp-med-output" \
    --data-access-role-arn arn:aws:iam::867139942017:role/ComprehendMedicalBatchProcessingRole \
    --language-code en
```
出力:  

```
{
    "JobId": "dg7289877365fc70299089371c043b96"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartSnomedctInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/start-snomedct-inference-job.html)」を参照してください。

### `stop-entities-detection-v2-job`
<a name="comprehendmedical_StopEntitiesDetectionV2Job_cli_2_topic"></a>

次のコード例は、`stop-entities-detection-v2-job` を使用する方法を示しています。

**AWS CLI**  
**エンティティ検出ジョブを停止するには**  
次の `stop-entities-detection-v2-job` の例では、非同期エンティティ検出ジョブを停止しています。  

```
aws comprehendmedical stop-entities-detection-v2-job \
    --job-id "ab9887877365fe70299089371c043b96"
```
出力:  

```
{
    "JobId": "ab9887877365fe70299089371c043b96"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopEntitiesDetectionV2Job](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/stop-entities-detection-v2-job.html)」を参照してください。

### `stop-icd10-cm-inference-job`
<a name="comprehendmedical_StopIcd10CmInferenceJob_cli_2_topic"></a>

次のコード例は、`stop-icd10-cm-inference-job` を使用する方法を示しています。

**AWS CLI**  
**ICD-10-CM 推論ジョブを停止するには**  
次の `stop-icd10-cm-inference-job` の例では、ICD-10-CM 推論バッチ分析ジョブを停止しています。  

```
aws comprehendmedical stop-icd10-cm-inference-job \
    --job-id "4750034166536cdb52ffa3295a1b00a3"
```
出力:  

```
{
    "JobId": "ef7289877365fc70299089371c043b96",
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopIcd10CmInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/stop-icd10-cm-inference-job.html)」を参照してください。

### `stop-phi-detection-job`
<a name="comprehendmedical_StopPhiDetectionJob_cli_2_topic"></a>

次のコード例は、`stop-phi-detection-job` を使用する方法を示しています。

**AWS CLI**  
**保護対象の医療情報 (PHI) 検出ジョブを停止するには**  
次の `stop-phi-detection-job` の例では、非同期保護対象の医療情報 (PHI) 検出ジョブを停止しています。  

```
aws comprehendmedical stop-phi-detection-job \
    --job-id "4750034166536cdb52ffa3295a1b00a3"
```
出力:  

```
{
    "JobId": "ab9887877365fe70299089371c043b96"
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Batch APIs](https://docs.aws.amazon.com/comprehend-medical/latest/dev/textanalysis-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopPhiDetectionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/stop-phi-detection-job.html)」を参照してください。

### `stop-rx-norm-inference-job`
<a name="comprehendmedical_StopRxNormInferenceJob_cli_2_topic"></a>

次のコード例は、`stop-rx-norm-inference-job` を使用する方法を示しています。

**AWS CLI**  
**RxNorm 推論ジョブを停止するには**  
次の `stop-rx-norm-inference-job` の例では、ICD-10-CM 推論バッチ分析ジョブを停止しています。  

```
aws comprehendmedical stop-rx-norm-inference-job \
    --job-id "eg8199877365fc70299089371c043b96"
```
出力:  

```
{
    "JobId": "eg8199877365fc70299089371c043b96",
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopRxNormInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/stop-rx-norm-inference-job.html)」を参照してください。

### `stop-snomedct-inference-job`
<a name="comprehendmedical_StopSnomedctInferenceJob_cli_2_topic"></a>

次のコード例は、`stop-snomedct-inference-job` を使用する方法を示しています。

**AWS CLI**  
**SNOMED CT 推論ジョブを停止するには**  
次の `stop-snomedct-inference-job` の例では、SNOMED CT 推論バッチ分析ジョブを停止しています。  

```
aws comprehendmedical stop-snomedct-inference-job \
    --job-id "8750034166436cdb52ffa3295a1b00a1"
```
出力:  

```
{
    "JobId": "8750034166436cdb52ffa3295a1b00a1",
}
```
詳細については、「*Amazon Comprehend Medical デベロッパーガイド*」の「[Ontology linking batch analysis](https://docs.aws.amazon.com/comprehend-medical/latest/dev/ontologies-batchapi.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopSnomedctInferenceJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/comprehendmedical/stop-snomedct-inference-job.html)」を参照してください。

# AWS Config を使用した の例 AWS CLI
<a name="cli_2_config-service_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Config。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-config-rule`
<a name="config-service_DeleteConfigRule_cli_2_topic"></a>

次の例は、`delete-config-rule` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS ルールを削除するには**  
次のコマンドは、 という名前 AWS の Config ルールを削除します`MyConfigRule`。  

```
aws configservice delete-config-rule --config-rule-name MyConfigRule
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteConfigRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/delete-config-rule.html)」を参照してください。**

### `delete-delivery-channel`
<a name="config-service_DeleteDeliveryChannel_cli_2_topic"></a>

次のコード例は、`delete-delivery-channel` を使用する方法を示しています。

**AWS CLI**  
**配信チャネルを削除するには**  
次のコマンドでは、デフォルトの配信チャネルを削除しています。  

```
aws configservice delete-delivery-channel --delivery-channel-name default
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDeliveryChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/delete-delivery-channel.html)」を参照してください。

### `delete-evaluation-results`
<a name="config-service_DeleteEvaluationResults_cli_2_topic"></a>

次のコード例は、`delete-evaluation-results` を使用する方法を示しています。

**AWS CLI**  
**手動で評価結果を削除するには**  
次のコマンドは、 AWS マネージドルール s3-bucket-versioning-enabled の現在の評価結果を削除します。  

```
aws configservice delete-evaluation-results --config-rule-name s3-bucket-versioning-enabled
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEvaluationResults](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/delete-evaluation-results.html)」を参照してください。

### `deliver-config-snapshot`
<a name="config-service_DeliverConfigSnapshot_cli_2_topic"></a>

次のコード例は、`deliver-config-snapshot` を使用する方法を示しています。

**AWS CLI**  
**設定スナップショットを配信するには**  
次のコマンドは、デフォルトの配信チャネルに属する Amazon S3 バケットに設定スナップショットを配信します。  

```
aws configservice deliver-config-snapshot --delivery-channel-name default
```
出力:  

```
{
    "configSnapshotId": "d0333b00-a683-44af-921e-examplefb794"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeliverConfigSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/deliver-config-snapshot.html)」を参照してください。

### `describe-compliance-by-config-rule`
<a name="config-service_DescribeComplianceByConfigRule_cli_2_topic"></a>

次の例は、`describe-compliance-by-config-rule` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS ルールのコンプライアンス情報を取得するには**  
次のコマンドは、1 つ以上の AWS リソースによって違反された各 AWS Config ルールのコンプライアンス情報を返します。  

```
aws configservice describe-compliance-by-config-rule --compliance-types NON_COMPLIANT
```
出力では、各 `CappedCount` 属性の値は、関連するルールに準拠していないリソースの数を示します。例えば、次の出力は、3 つのリソースが `InstanceTypesAreT2micro` という名前のルールに準拠していないことを示しています。  
出力:  

```
{
    "ComplianceByConfigRules": [
        {
            "Compliance": {
                "ComplianceContributorCount": {
                    "CappedCount": 3,
                    "CapExceeded": false
                },
                "ComplianceType": "NON_COMPLIANT"
            },
            "ConfigRuleName": "InstanceTypesAreT2micro"
        },
        {
            "Compliance": {
                "ComplianceContributorCount": {
                    "CappedCount": 10,
                    "CapExceeded": false
                },
                "ComplianceType": "NON_COMPLIANT"
            },
            "ConfigRuleName": "RequiredTagsForVolumes"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeComplianceByConfigRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-compliance-by-config-rule.html)」を参照してください。

### `describe-compliance-by-resource`
<a name="config-service_DescribeComplianceByResource_cli_2_topic"></a>

次の例は、`describe-compliance-by-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースのコンプライアンス情報を取得するには**  
次のコマンドは、Config によって記録され、1 つ以上のルールに違反する各 EC2 AWS インスタンスのコンプライアンス情報を返します。  

```
aws configservice describe-compliance-by-resource --resource-type AWS::EC2::Instance --compliance-types NON_COMPLIANT
```
出力では、各 `CappedCount` 属性の値は、リソースが違反するルールの数を示します。例えば、次の出力は、インスタンス `i-1a2b3c4d` が 2 つのルールに違反していることを示しています。  
出力:  

```
{
    "ComplianceByResources": [
        {
            "ResourceType": "AWS::EC2::Instance",
            "ResourceId": "i-1a2b3c4d",
            "Compliance": {
                "ComplianceContributorCount": {
                    "CappedCount": 2,
                    "CapExceeded": false
                },
                "ComplianceType": "NON_COMPLIANT"
            }
        },
        {
            "ResourceType": "AWS::EC2::Instance",
            "ResourceId": "i-2a2b3c4d ",
            "Compliance": {
                "ComplianceContributorCount": {
                    "CappedCount": 3,
                    "CapExceeded": false
                },
                "ComplianceType": "NON_COMPLIANT"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeComplianceByResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-compliance-by-resource.html)」を参照してください。

### `describe-config-rule-evaluation-status`
<a name="config-service_DescribeConfigRuleEvaluationStatus_cli_2_topic"></a>

次の例は、`describe-config-rule-evaluation-status` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS ルールのステータス情報を取得するには**  
次のコマンドは、 という名前の AWS Config ルールのステータス情報を返します`MyConfigRule`。  

```
aws configservice describe-config-rule-evaluation-status --config-rule-names MyConfigRule
```
出力:  

```
{
    "ConfigRulesEvaluationStatus": [
        {
            "ConfigRuleArn": "arn:aws:config:us-east-1:123456789012:config-rule/config-rule-abcdef",
            "FirstActivatedTime": 1450311703.844,
            "ConfigRuleId": "config-rule-abcdef",
            "LastSuccessfulInvocationTime": 1450314643.156,
            "ConfigRuleName": "MyConfigRule"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConfigRuleEvaluationStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-config-rule-evaluation-status.html)」を参照してください。

### `describe-config-rules`
<a name="config-service_DescribeConfigRules_cli_2_topic"></a>

次の例は、`describe-config-rules` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS ルールの詳細を取得するには**  
次のコマンドは、 という名前 AWS の Config ルールの詳細を返します`InstanceTypesAreT2micro`。  

```
aws configservice describe-config-rules --config-rule-names InstanceTypesAreT2micro
```
出力:  

```
{
    "ConfigRules": [
        {
            "ConfigRuleState": "ACTIVE",
            "Description": "Evaluates whether EC2 instances are the t2.micro type.",
            "ConfigRuleName": "InstanceTypesAreT2micro",
            "ConfigRuleArn": "arn:aws:config:us-east-1:123456789012:config-rule/config-rule-abcdef",
            "Source": {
                "Owner": "CUSTOM_LAMBDA",
                "SourceIdentifier": "arn:aws:lambda:us-east-1:123456789012:function:InstanceTypeCheck",
                "SourceDetails": [
                    {
                        "EventSource": "aws.config",
                        "MessageType": "ConfigurationItemChangeNotification"
                    }
                ]
            },
            "InputParameters": "{\"desiredInstanceType\":\"t2.micro\"}",
            "Scope": {
                "ComplianceResourceTypes": [
                    "AWS::EC2::Instance"
                ]
            },
            "ConfigRuleId": "config-rule-abcdef"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConfigRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-config-rules.html)」を参照してください。

### `describe-configuration-recorder-status`
<a name="config-service_DescribeConfigurationRecorderStatus_cli_2_topic"></a>

次のコード例は、`describe-configuration-recorder-status` を使用する方法を示しています。

**AWS CLI**  
**設定レコーダーのステータス情報を取得するには**  
次のコマンドは、デフォルトの設定レコーダーのステータスを返します。  

```
aws configservice describe-configuration-recorder-status
```
出力:  

```
{
    "ConfigurationRecordersStatus": [
        {
            "name": "default",
            "lastStatus": "SUCCESS",
            "recording": true,
            "lastStatusChangeTime": 1452193834.344,
            "lastStartTime": 1441039997.819,
            "lastStopTime": 1441039992.835
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConfigurationRecorderStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-configuration-recorder-status.html)」を参照してください。

### `describe-configuration-recorders`
<a name="config-service_DescribeConfigurationRecorders_cli_2_topic"></a>

次のコード例は、`describe-configuration-recorders` を使用する方法を示しています。

**AWS CLI**  
**設定レコーダーの詳細を取得するには**  
次のコマンドは、デフォルト設定レコーダーの詳細を返します。  

```
aws configservice describe-configuration-recorders
```
出力:  

```
{
    "ConfigurationRecorders": [
        {
            "recordingGroup": {
                "allSupported": true,
                "resourceTypes": [],
                "includeGlobalResourceTypes": true
            },
            "roleARN": "arn:aws:iam::123456789012:role/config-ConfigRole-A1B2C3D4E5F6",
            "name": "default"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConfigurationRecorders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-configuration-recorders.html)」を参照してください。

### `describe-delivery-channel-status`
<a name="config-service_DescribeDeliveryChannelStatus_cli_2_topic"></a>

次のコード例は、`describe-delivery-channel-status` を使用する方法を示しています。

**AWS CLI**  
**配信チャネルのステータス情報を取得するには**  
次のコマンドは、配信チャネルのステータスを返します。  

```
aws configservice describe-delivery-channel-status
```
出力:  

```
{
    "DeliveryChannelsStatus": [
        {
            "configStreamDeliveryInfo": {
                "lastStatusChangeTime": 1452193834.381,
                "lastStatus": "SUCCESS"
            },
            "configHistoryDeliveryInfo": {
                "lastSuccessfulTime": 1450317838.412,
                "lastStatus": "SUCCESS",
                "lastAttemptTime": 1450317838.412
            },
            "configSnapshotDeliveryInfo": {
                "lastSuccessfulTime": 1452185597.094,
                "lastStatus": "SUCCESS",
                "lastAttemptTime": 1452185597.094
            },
            "name": "default"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDeliveryChannelStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-delivery-channel-status.html)」を参照してください。

### `describe-delivery-channels`
<a name="config-service_DescribeDeliveryChannels_cli_2_topic"></a>

次のコード例は、`describe-delivery-channels` を使用する方法を示しています。

**AWS CLI**  
**配信チャネルの詳細を取得するには**  
次のコマンドは、配信チャネルに関する詳細を返します。  

```
aws configservice describe-delivery-channels
```
出力:  

```
{
    "DeliveryChannels": [
        {
            "snsTopicARN": "arn:aws:sns:us-east-1:123456789012:config-topic",
            "name": "default",
            "s3BucketName": "config-bucket-123456789012"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDeliveryChannels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/describe-delivery-channels.html)」を参照してください。

### `get-compliance-details-by-config-rule`
<a name="config-service_GetComplianceDetailsByConfigRule_cli_2_topic"></a>

次の例は、`get-compliance-details-by-config-rule` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS ルールの評価結果を取得するには**  
次のコマンドは、 という名前の Config AWS ルールに準拠していないすべてのリソースの評価結果を返します`InstanceTypesAreT2micro`。  

```
aws configservice get-compliance-details-by-config-rule --config-rule-name InstanceTypesAreT2micro --compliance-types NON_COMPLIANT
```
出力:  

```
{
    "EvaluationResults": [
        {
            "EvaluationResultIdentifier": {
                "OrderingTimestamp": 1450314635.065,
                "EvaluationResultQualifier": {
                    "ResourceType": "AWS::EC2::Instance",
                    "ResourceId": "i-1a2b3c4d",
                    "ConfigRuleName": "InstanceTypesAreT2micro"
                }
            },
            "ResultRecordedTime": 1450314645.261,
            "ConfigRuleInvokedTime": 1450314642.948,
            "ComplianceType": "NON_COMPLIANT"
        },
        {
            "EvaluationResultIdentifier": {
                "OrderingTimestamp": 1450314635.065,
                "EvaluationResultQualifier": {
                    "ResourceType": "AWS::EC2::Instance",
                    "ResourceId": "i-2a2b3c4d",
                    "ConfigRuleName": "InstanceTypesAreT2micro"
                }
            },
            "ResultRecordedTime": 1450314645.18,
            "ConfigRuleInvokedTime": 1450314642.902,
            "ComplianceType": "NON_COMPLIANT"
        },
        {
            "EvaluationResultIdentifier": {
                "OrderingTimestamp": 1450314635.065,
                "EvaluationResultQualifier": {
                    "ResourceType": "AWS::EC2::Instance",
                    "ResourceId": "i-3a2b3c4d",
                    "ConfigRuleName": "InstanceTypesAreT2micro"
                }
            },
            "ResultRecordedTime": 1450314643.346,
            "ConfigRuleInvokedTime": 1450314643.124,
            "ComplianceType": "NON_COMPLIANT"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComplianceDetailsByConfigRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/get-compliance-details-by-config-rule.html)」を参照してください。

### `get-compliance-details-by-resource`
<a name="config-service_GetComplianceDetailsByResource_cli_2_topic"></a>

次の例は、`get-compliance-details-by-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースの評価結果を取得するには**  
次のコマンドは、EC2 インスタンス `i-1a2b3c4d` が準拠していない各ルールの評価結果を返します。  

```
aws configservice get-compliance-details-by-resource --resource-type AWS::EC2::Instance --resource-id i-1a2b3c4d --compliance-types NON_COMPLIANT
```
出力:  

```
{
    "EvaluationResults": [
        {
            "EvaluationResultIdentifier": {
                "OrderingTimestamp": 1450314635.065,
                "EvaluationResultQualifier": {
                    "ResourceType": "AWS::EC2::Instance",
                    "ResourceId": "i-1a2b3c4d",
                    "ConfigRuleName": "InstanceTypesAreT2micro"
                }
            },
            "ResultRecordedTime": 1450314643.288,
            "ConfigRuleInvokedTime": 1450314643.034,
            "ComplianceType": "NON_COMPLIANT"
        },
        {
            "EvaluationResultIdentifier": {
                "OrderingTimestamp": 1450314635.065,
                "EvaluationResultQualifier": {
                    "ResourceType": "AWS::EC2::Instance",
                    "ResourceId": "i-1a2b3c4d",
                    "ConfigRuleName": "RequiredTagForEC2Instances"
                }
            },
            "ResultRecordedTime": 1450314645.261,
            "ConfigRuleInvokedTime": 1450314642.948,
            "ComplianceType": "NON_COMPLIANT"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComplianceDetailsByResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/get-compliance-details-by-resource.html)」を参照してください。

### `get-compliance-summary-by-config-rule`
<a name="config-service_GetComplianceSummaryByConfigRule_cli_2_topic"></a>

次の例は、`get-compliance-summary-by-config-rule` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS ルールのコンプライアンス概要を取得するには**  
次のコマンドは、準拠しているルールの数と準拠していないルールの数を返します。  

```
aws configservice get-compliance-summary-by-config-rule
```
出力では、各 `CappedCount` 属性の値は、準拠または非準拠のルールの数を示します。  
出力:  

```
{
    "ComplianceSummary": {
        "NonCompliantResourceCount": {
            "CappedCount": 3,
            "CapExceeded": false
        },
        "ComplianceSummaryTimestamp": 1452204131.493,
        "CompliantResourceCount": {
            "CappedCount": 2,
            "CapExceeded": false
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComplianceSummaryByConfigRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/get-compliance-summary-by-config-rule.html)」を参照してください。

### `get-compliance-summary-by-resource-type`
<a name="config-service_GetComplianceSummaryByResourceType_cli_2_topic"></a>

次のコード例は、`get-compliance-summary-by-resource-type` を使用する方法を示しています。

**AWS CLI**  
**すべてのリソースタイプのコンプライアンス概要を取得するには**  
次のコマンドは、非準拠の AWS リソースの数と準拠しているリソースの数を返します。  

```
aws configservice get-compliance-summary-by-resource-type
```
出力では、各 `CappedCount` 属性の値は、準拠または非準拠のリソースの数を示します。  
出力:  

```
{
    "ComplianceSummariesByResourceType": [
        {
            "ComplianceSummary": {
                "NonCompliantResourceCount": {
                    "CappedCount": 16,
                    "CapExceeded": false
                },
                "ComplianceSummaryTimestamp": 1453237464.543,
                "CompliantResourceCount": {
                    "CappedCount": 10,
                    "CapExceeded": false
                }
            }
        }
    ]
}
```
**特定のリソースタイプのコンプライアンス概要を取得するには**  
次のコマンドは、準拠していない EC2 インスタンスの数と準拠しているインスタンスの数を返します。  

```
aws configservice get-compliance-summary-by-resource-type --resource-types AWS::EC2::Instance
```
出力では、各 `CappedCount` 属性の値は、準拠または非準拠のリソースの数を示します。  
出力:  

```
{
    "ComplianceSummariesByResourceType": [
        {
            "ResourceType": "AWS::EC2::Instance",
            "ComplianceSummary": {
                "NonCompliantResourceCount": {
                    "CappedCount": 3,
                    "CapExceeded": false
                },
                "ComplianceSummaryTimestamp": 1452204923.518,
                "CompliantResourceCount": {
                    "CappedCount": 7,
                    "CapExceeded": false
                }
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComplianceSummaryByResourceType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/get-compliance-summary-by-resource-type.html)」を参照してください。

### `get-resource-config-history`
<a name="config-service_GetResourceConfigHistory_cli_2_topic"></a>

次の例は、`get-resource-config-history` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースの設定履歴を取得するには**  
次のコマンドは、ID が `i-1a2b3c4d` の EC2 インスタンスの設定項目のリストを返します。  

```
aws configservice get-resource-config-history --resource-type AWS::EC2::Instance --resource-id i-1a2b3c4d
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceConfigHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/get-resource-config-history.html)」を参照してください。

### `get-status`
<a name="config-service_GetStatus_cli_2_topic"></a>

次の例は、`get-status` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS のステータスを取得するには**  
次のコマンドは、配信チャネルと設定レコーダーのステータスを返します。  

```
aws configservice get-status
```
出力:  

```
Configuration Recorders:

name: default
recorder: ON
last status: SUCCESS

Delivery Channels:

name: default
last stream delivery status: SUCCESS
last history delivery status: SUCCESS
last snapshot delivery status: SUCCESS
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/get-status.html)」を参照してください。

### `list-discovered-resources`
<a name="config-service_ListDiscoveredResources_cli_2_topic"></a>

次の例は、`list-discovered-resources` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS が検出したリソースを一覧表示するには**  
次のコマンドは、Config が検出した EC2 AWS インスタンスを一覧表示します。  

```
aws configservice list-discovered-resources --resource-type AWS::EC2::Instance
```
出力:  

```
{
    "resourceIdentifiers": [
        {
            "resourceType": "AWS::EC2::Instance",
            "resourceId": "i-1a2b3c4d"
        },
        {
            "resourceType": "AWS::EC2::Instance",
            "resourceId": "i-2a2b3c4d"
        },
        {
            "resourceType": "AWS::EC2::Instance",
            "resourceId": "i-3a2b3c4d"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDiscoveredResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/list-discovered-resources.html)」を参照してください。

### `put-config-rule`
<a name="config-service_PutConfigRule_cli_2_topic"></a>

次の例は、`put-config-rule` を使用する方法を説明しています。

**AWS CLI**  
** AWS マネージド Config ルールを追加するには**  
次のコマンドは、 AWS マネージド Config ルールを追加するための JSON コードを提供します。  

```
aws configservice put-config-rule --config-rule file://RequiredTagsForEC2Instances.json
```
`RequiredTagsForEC2Instances.json` は、ルール設定を含む JSON ファイルです。  

```
{
  "ConfigRuleName": "RequiredTagsForEC2Instances",
  "Description": "Checks whether the CostCenter and Owner tags are applied to EC2 instances.",
  "Scope": {
    "ComplianceResourceTypes": [
      "AWS::EC2::Instance"
    ]
  },
  "Source": {
    "Owner": "AWS",
    "SourceIdentifier": "REQUIRED_TAGS"
  },
  "InputParameters": "{\"tag1Key\":\"CostCenter\",\"tag2Key\":\"Owner\"}"
}
```
`ComplianceResourceTypes` 属性の場合、この JSON コードはスコープを `AWS::EC2::Instance`タイプのリソースに制限するため、Config AWS は EC2 インスタンスのみをルールに対して評価します。このルールはマネージドルールであるため、`Owner` 属性は `AWS` に設定され、`SourceIdentifier` 属性はルール識別子 `REQUIRED_TAGS` に設定されます。`InputParameters` 属性には、ルールに必要なタグキー、および `CostCenter` と `Owner` が指定されます。  
コマンドが成功すると、 AWS Config は出力を返しません。ルール設定を確認するには、describe-config-rules コマンドを実行してルール名を指定します。  
**カスタマーマネージド Config ルールを追加するには**  
次のコマンドは、カスタマーマネージド Config ルールを追加するための JSON コードを提供します。  

```
aws configservice put-config-rule --config-rule file://InstanceTypesAreT2micro.json
```
`InstanceTypesAreT2micro.json` は、ルール設定を含む JSON ファイルです。  

```
{
  "ConfigRuleName": "InstanceTypesAreT2micro",
  "Description": "Evaluates whether EC2 instances are the t2.micro type.",
  "Scope": {
    "ComplianceResourceTypes": [
      "AWS::EC2::Instance"
    ]
  },
  "Source": {
    "Owner": "CUSTOM_LAMBDA",
    "SourceIdentifier": "arn:aws:lambda:us-east-1:123456789012:function:InstanceTypeCheck",
    "SourceDetails": [
      {
        "EventSource": "aws.config",
        "MessageType": "ConfigurationItemChangeNotification"
      }
    ]
  },
  "InputParameters": "{\"desiredInstanceType\":\"t2.micro\"}"
}
```
`ComplianceResourceTypes` 属性の場合、この JSON コードはスコープを `AWS::EC2::Instance`タイプのリソースに制限するため、Config AWS は EC2 インスタンスのみをルールに対して評価します。このルールはカスタマーマネージドルールであるため、 `Owner` 属性は に設定され`CUSTOM_LAMBDA`、 `SourceIdentifier` 属性は AWS Lambda 関数の ARN に設定されます。`SourceDetails` オブジェクトは必須です。`InputParameters` 属性に指定されたパラメータは、Config が呼び出してルールに対してリソースを評価するときに AWS Lambda AWS 関数に渡されます。  
コマンドが成功すると、 AWS Config は出力を返しません。ルール設定を確認するには、describe-config-rules コマンドを実行してルール名を指定します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutConfigRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/put-config-rule.html)」を参照してください。

### `put-configuration-recorder`
<a name="config-service_PutConfigurationRecorder_cli_2_topic"></a>

次のコード例は、`put-configuration-recorder` を使用する方法を示しています。

**AWS CLI**  
**例 1: サポートされているすべてのリソースを記録するには**  
次のコマンドは、グローバルリソースタイプを含む、サポートされているすべてのリソースタイプに対する変更を追跡する設定レコーダーを作成します。  

```
aws configservice put-configuration-recorder \
    --configuration-recorder name=default,roleARN=arn:aws:iam::123456789012:role/config-role \
    --recording-group allSupported=true,includeGlobalResourceTypes=true
```
コマンドが成功すると、 AWS Config は出力を返しません。設定レコーダーの設定を確認するには、describe-configuration-recorders コマンドを実行します。  
**例 2: 特定のタイプのリソースを記録するには**  
次のコマンドは、JSON ファイルで --recording-group オプションに指定されているリソースタイプに対する変更のみを追跡する設定レコーダーを作成します。  

```
aws configservice put-configuration-recorder \
    --configuration-recorder name=default,roleARN=arn:aws:iam::123456789012:role/config-role \
    --recording-group file://recordingGroup.json
```
recordingGroup.json は、Config AWS が記録するリソースのタイプを指定する JSON ファイルです。  

```
{
    "allSupported": false,
    "includeGlobalResourceTypes": false,
    "resourceTypes": [
        "AWS::EC2::EIP",
        "AWS::EC2::Instance",
        "AWS::EC2::NetworkAcl",
        "AWS::EC2::SecurityGroup",
        "AWS::CloudTrail::Trail",
        "AWS::EC2::Volume",
        "AWS::EC2::VPC",
        "AWS::IAM::User",
        "AWS::IAM::Policy"
    ]
}
```
resourceTypes キーのリソースタイプを指定する前に、allSupported オプションおよび includeGlobalResourceTypes オプションを false に設定するか、オプション自体を省略する必要があります。  
コマンドが成功すると、 AWS Config は出力を返しません。設定レコーダーの設定を確認するには、describe-configuration-recorders コマンドを実行します。  
**例 3: 特定のリソースタイプ以外の、すべてのサポートされているリソースを選択するには**  
次のコマンドは、JSON ファイルで --recording-group オプションに指定されているリソースタイプを除き、現在および将来サポートされるすべてのリソースタイプに対する変更を追跡する設定レコーダーを作成します。  

```
aws configservice put-configuration-recorder \
    --configuration-recorder name=default,roleARN=arn:aws:iam::123456789012:role/config-role \
    --recording-group file://recordingGroup.json
```
recordingGroup.json は、Config AWS が記録するリソースのタイプを指定する JSON ファイルです。  

```
{
    "allSupported": false,
    "exclusionByResourceTypes": {
        "resourceTypes": [
        "AWS::Redshift::ClusterSnapshot",
        "AWS::RDS::DBClusterSnapshot",
        "AWS::CloudFront::StreamingDistribution"
    ]
    },
        "includeGlobalResourceTypes": false,
        "recordingStrategy": {
        "useOnly": "EXCLUSION_BY_RESOURCE_TYPES"
    },
}
```
記録から除外するリソースタイプを指定する前に、1) allSupported オプションおよび includeGlobalResourceTypes オプションを false に設定するか、オプション自体を省略する必要があります。2) RecordingStrategy の useOnly フィールドを EXCLUSION\$1BY\$1RESOURCE\$1TYPES に設定する必要があります。  
コマンドが成功すると、 AWS Config は出力を返しません。設定レコーダーの設定を確認するには、describe-configuration-recorders コマンドを実行します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutConfigurationRecorder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/put-configuration-recorder.html)」を参照してください。

### `put-delivery-channel`
<a name="config-service_PutDeliveryChannel_cli_2_topic"></a>

次のコード例は、`put-delivery-channel` を使用する方法を示しています。

**AWS CLI**  
**配信チャネルを作成するには**  
次のコマンドは、配信チャネルの設定を JSON コードとして提供します。  

```
aws configservice put-delivery-channel --delivery-channel file://deliveryChannel.json
```
`deliveryChannel.json` ファイルは、配信チャネルの属性を指定します。  

```
{
    "name": "default",
    "s3BucketName": "config-bucket-123456789012",
    "snsTopicARN": "arn:aws:sns:us-east-1:123456789012:config-topic",
    "configSnapshotDeliveryProperties": {
        "deliveryFrequency": "Twelve_Hours"
    }
}
```
この例では以下の属性を設定します。  
`name` - 配信チャネルの名前です。デフォルトでは、 AWS Config は新しい配信チャネル`default`に名前を割り当てます。 `put-delivery-channel` コマンドを使用して配信チャネル名を更新することはできません。名前を変更する手順については、「配信チャネルの名前変更」を参照してください。`s3BucketName`- Config が設定スナップショットと設定履歴ファイルを配信する Amazon S3 AWS バケットの名前。別の AWS アカウントに属するバケットを指定する場合、そのバケットには Config AWS にアクセス許可を付与するポリシーが必要です。詳細については、Amazon S3 バケットのアクセス許可を参照してください。  
`snsTopicARN` - Config が設定変更に関する通知を送信する Amazon SNS トピックの Amazon リソースネーム (ARN)。別のアカウントからトピックを選択した場合、トピックには Config AWS にアクセス許可を付与するポリシーが必要です。 AWS 詳細については、「Permissions for the Amazon SNS Topic」を参照してください。  
`configSnapshotDeliveryProperties` - Config が設定スナップショットを配信する頻度と、定期的な AWS Config ルールの評価を呼び出す頻度を設定する `deliveryFrequency` 属性が含まれます。  
コマンドが成功すると、 AWS Config は出力を返しません。配信チャネルの設定を確認するには、describe-delivery-channels コマンドを実行します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutDeliveryChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/put-delivery-channel.html)」を参照してください。

### `start-config-rules-evaluation`
<a name="config-service_StartConfigRulesEvaluation_cli_2_topic"></a>

次の例は、`start-config-rules-evaluation` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS ルールのオンデマンド評価を実行するには**  
次のコマンドは、2 つの AWS マネージドルールの評価を開始します。  

```
aws configservice start-config-rules-evaluation --config-rule-names s3-bucket-versioning-enabled cloudtrail-enabled
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartConfigRulesEvaluation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/start-config-rules-evaluation.html)」を参照してください。

### `start-configuration-recorder`
<a name="config-service_StartConfigurationRecorder_cli_2_topic"></a>

次のコード例は、`start-configuration-recorder` を使用する方法を示しています。

**AWS CLI**  
**設定レコーダーを起動するには**  
次のコマンドは、デフォルトの設定レコーダーを起動します。  

```
aws configservice start-configuration-recorder --configuration-recorder-name default
```
コマンドが成功すると、 AWS Config は出力を返しません。 AWS Config がリソースを記録していることを確認するには、get-status コマンドを実行します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartConfigurationRecorder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/start-configuration-recorder.html)」を参照してください。

### `stop-configuration-recorder`
<a name="config-service_StopConfigurationRecorder_cli_2_topic"></a>

次のコード例は、`stop-configuration-recorder` を使用する方法を示しています。

**AWS CLI**  
**設定レコーダーを停止するには**  
次のコマンドは、デフォルトの設定レコーダーを停止します。  

```
aws configservice stop-configuration-recorder --configuration-recorder-name default
```
コマンドが成功すると、 AWS Config は出力を返しません。Config AWS がリソースを記録していないことを確認するには、get-status コマンドを実行します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopConfigurationRecorder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/stop-configuration-recorder.html)」を参照してください。

### `subscribe`
<a name="config-service_Subscribe_cli_2_topic"></a>

次の例は、`subscribe` を使用する方法を説明しています。

**AWS CLI**  
**Config AWS にサブスクライブするには**  
次のコマンドは、デフォルトの配信チャネルと設定レコーダーを作成します。コマンドは、Config が設定情報を配信する Amazon S3 バケットと Amazon SNS AWS トピックも指定します。  

```
aws configservice subscribe --s3-bucket config-bucket-123456789012 --sns-topic arn:aws:sns:us-east-1:123456789012:config-topic --iam-role arn:aws:iam::123456789012:role/ConfigRole-A1B2C3D4E5F6
```
出力:  

```
Using existing S3 bucket: config-bucket-123456789012
Using existing SNS topic: arn:aws:sns:us-east-1:123456789012:config-topic
Subscribe succeeded:

Configuration Recorders: [
    {
        "recordingGroup": {
            "allSupported": true,
            "resourceTypes": [],
            "includeGlobalResourceTypes": false
        },
        "roleARN": "arn:aws:iam::123456789012:role/ConfigRole-A1B2C3D4E5F6",
        "name": "default"
    }
]

Delivery Channels: [
    {
        "snsTopicARN": "arn:aws:sns:us-east-1:123456789012:config-topic",
        "name": "default",
        "s3BucketName": "config-bucket-123456789012"
    }
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Subscribe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/subscribe.html)」を参照してください。

# を使用した Amazon Connect の例 AWS CLI
<a name="cli_2_connect_code_examples"></a>

次のコード例は、Amazon Connect AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-user`
<a name="connect_CreateUser_cli_2_topic"></a>

次のコード例は、`create-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを作成するには**  
次の `create-user` の例では、指定された属性を持つユーザーを指定された Amazon Connect インスタンスに追加しています。  

```
aws connect create-user \
    --username Mary \
    --password Pass@Word1 \
    --identity-info FirstName=Mary,LastName=Major \
    --phone-config PhoneType=DESK_PHONE,AutoAccept=true,AfterContactWorkTimeLimit=60,DeskPhoneNumber=+15555551212 \
    --security-profile-id 12345678-1111-2222-aaaa-a1b2c3d4f5g7 \
    --routing-profile-id 87654321-9999-3434-abcd-x1y2z3a1b2c3 \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "UserId": "87654321-2222-1234-1234-111234567891",
    "UserArn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/agent/87654321-2222-1234-1234-111234567891"
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Add Users](https://docs.aws.amazon.com/connect/latest/adminguide/user-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/create-user.html)」を参照してください。

### `delete-user`
<a name="connect_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
次の `delete-user` の例では、指定された Amazon Connect インスタンスから指定されたユーザーを削除しています。  

```
aws connect delete-user \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --user-id 87654321-2222-1234-1234-111234567891
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Connect 管理者ガイド*」の「[Manage Users](https://docs.aws.amazon.com/connect/latest/adminguide/manage-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/delete-user.html)」を参照してください。

### `describe-user-hierarchy-group`
<a name="connect_DescribeUserHierarchyGroup_cli_2_topic"></a>

次のコード例は、`describe-user-hierarchy-group` を使用する方法を示しています。

**AWS CLI**  
**階層グループの詳細を表示するには**  
次の `describe-user-hierarchy-group` の例では、指定された Amazon Connect 階層グループの詳細を表示しています。  

```
aws connect describe-user-hierarchy-group \
    --hierarchy-group-id 12345678-1111-2222-800e-aaabbb555gg \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
     "HierarchyGroup": {
         "Id": "12345678-1111-2222-800e-a2b3c4d5f6g7",
         "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/agent-group/12345678-1111-2222-800e-a2b3c4d5f6g7",
         "Name": "Example Corporation",
         "LevelId": "1",
         "HierarchyPath": {
             "LevelOne": {
                 "Id": "abcdefgh-3333-4444-8af3-201123456789",
                 "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/agent-group/abcdefgh-3333-4444-8af3-201123456789",
                 "Name": "Example Corporation"
             }
         }
     }
 }
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Set Up Agent Hierarchies](https://docs.aws.amazon.com/connect/latest/adminguide/agent-hierarchy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUserHierarchyGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/describe-user-hierarchy-group.html)」を参照してください。

### `describe-user-hierarchy-structure`
<a name="connect_DescribeUserHierarchyStructure_cli_2_topic"></a>

次のコード例は、`describe-user-hierarchy-structure` を使用する方法を示しています。

**AWS CLI**  
**階層構造の詳細を表示するには**  
次の `describe-user-hierarchy-structure` の例では、指定された Amazon Connect インスタンスの階層構造の詳細を表示しています。  

```
aws connect describe-user-hierarchy-group \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
     "HierarchyStructure": {
         "LevelOne": {
             "Id": "12345678-1111-2222-800e-aaabbb555gg",
             "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/agent-group-level/1",
             "Name": "Corporation"
         },
         "LevelTwo": {
             "Id": "87654321-2222-3333-ac99-123456789102",
             "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/agent-group-level/2",
             "Name": "Services Division"
         },
         "LevelThree": {
             "Id": "abcdefgh-3333-4444-8af3-201123456789",
             "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/agent-group-level/3",
             "Name": "EU Site"
         }
     }
 }
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Set Up Agent Hierarchies](https://docs.aws.amazon.com/connect/latest/adminguide/agent-hierarchy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUserHierarchyStructure](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/describe-user-hierarchy-structure.html)」を参照してください。

### `describe-user`
<a name="connect_DescribeUser_cli_2_topic"></a>

次のコード例は、`describe-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの詳細を表示するには**  
次の `describe-user` の例では、指定された Amazon Connect ユーザーの詳細を表示しています。  

```
aws connect describe-user \
    --user-id 0c245dc0-0cf5-4e37-800e-2a7481cc8a60
    --instance-id 40c83b68-ea62-414c-97bb-d018e39e158e
```
出力:  

```
{
    "User": {
        "Id": "0c245dc0-0cf5-4e37-800e-2a7481cc8a60",
        "Arn": "arn:aws:connect:us-west-2:123456789012:instance/40c83b68-ea62-414c-97bb-d018e39e158e/agent/0c245dc0-0cf5-4e37-800e-2a7481cc8a60",
        "Username": "Jane",
        "IdentityInfo": {
            "FirstName": "Jane",
            "LastName": "Doe",
            "Email": "example.com"
        },
        "PhoneConfig": {
            "PhoneType": "SOFT_PHONE",
            "AutoAccept": false,
            "AfterContactWorkTimeLimit": 0,
            "DeskPhoneNumber": ""
        },
        "DirectoryUserId": "8b444cf6-b368-4f29-ba18-07af27405658",
        "SecurityProfileIds": [
            "b6f85a42-1dc5-443b-b621-de0abf70c9cf"
        ],
        "RoutingProfileId": "0be36ee9-2b5f-4ef4-bcf7-87738e5be0e5",
        "Tags": {}
    }
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Manage Users](https://docs.aws.amazon.com/connect/latest/adminguide/manage-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*の「[DescribeUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/describe-user.html)」を参照してください。

### `get-contact-attributes`
<a name="connect_GetContactAttributes_cli_2_topic"></a>

次のコード例は、`get-contact-attributes` を使用する方法を示しています。

**AWS CLI**  
**連絡先の属性を取得するには**  
次の `get-contact-attributes` の例では、指定された Amazon Connect の連絡先に設定された属性を取得しています。  

```
aws connect get-contact-attributes \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --initial-contact-id 12345678-1111-2222-800e-a2b3c4d5f6g7
```
出力:  

```
{
    "Attributes": {
        "greetingPlayed": "true"
    }
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Use Amazon Connect Contact Attributes](https://docs.aws.amazon.com/connect/latest/adminguide/connect-contact-attributes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContactAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/get-contact-attributes.html)」を参照してください。

### `list-contact-flows`
<a name="connect_ListContactFlows_cli_2_topic"></a>

次のコード例は、`list-contact-flows` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの問い合わせフローを一覧表示するには**  
次の `list-contact-flows` の例では、指定された Amazon Connect インスタンスの問い合わせフローを一覧表示しています。  

```
aws connect list-contact-flows \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
     "ContactFlowSummaryList": [
         {
             "Id": "12345678-1111-2222-800e-a2b3c4d5f6g7",
             "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/contact-flow/12345678-1111-2222-800e-a2b3c4d5f6g7",
             "Name": "Default queue transfer",
             "ContactFlowType": "QUEUE_TRANSFER"
         },
         {
             "Id": "87654321-2222-3333-ac99-123456789102",
             "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/contact-flow/87654321-2222-3333-ac99-123456789102",
             "Name": "Default agent hold",
             "ContactFlowType": "AGENT_HOLD"
         },
         {
             "Id": "abcdefgh-3333-4444-8af3-201123456789",
                 "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/contact-flow/abcdefgh-3333-4444-8af3-201123456789",
             "Name": "Default customer hold",
             "ContactFlowType": "CUSTOMER_HOLD"
         },
     ]
 }
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Create Amazon Connect Contact Flows](https://docs.aws.amazon.com/connect/latest/adminguide/connect-contact-flows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListContactFlows](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-contact-flows.html)」を参照してください。

### `list-hours-of-operations`
<a name="connect_ListHoursOfOperations_cli_2_topic"></a>

次のコード例は、`list-hours-of-operations` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのオペレーション時間を一覧表示するには**  
次の `list-hours-of-operations` の例では、指定された Amazon Connect インスタンスのオペレーション時間を一覧表示しています。  

```
aws connect list-hours-of-operations \
    --instance-id 40c83b68-ea62-414c-97bb-d018e39e158e
```
出力:  

```
{
    "HoursOfOperationSummaryList": [
        {
            "Id": "d69f1f84-7457-4924-8fbe-e64875546259",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/40c83b68-ea62-414c-97bb-d018e39e158e/operating-hours/d69f1f84-7457-4924-8fbe-e64875546259",
            "Name": "Basic Hours"
        }
    ]
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Set the Hours of Operation for a Queue](https://docs.aws.amazon.com/connect/latest/adminguide/set-hours-operation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHoursOfOperations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-hours-of-operations.html)」を参照してください。

### `list-phone-numbers`
<a name="connect_ListPhoneNumbers_cli_2_topic"></a>

次のコード例は、`list-phone-numbers` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの電話番号を一覧表示するには**  
次の `list-phone-numbers` の例では、指定された Amazon Connect インスタンスの電話番号を一覧表示しています。  

```
aws connect list-phone-numbers \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "PhoneNumberSummaryList": [
        {
            "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/phone-number/xyz80zxy-xyz1-80zx-zx80-11111EXAMPLE",
            "PhoneNumber": "+17065551212",
            "PhoneNumberType": "DID",
            "PhoneNumberCountryCode": "US"
        },
        {
            "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/phone-number/ccc0ccc-xyz1-80zx-zx80-22222EXAMPLE",
            "PhoneNumber": "+18555551212",
            "PhoneNumberType": "TOLL_FREE",
            "PhoneNumberCountryCode": "US"
        }
    ]
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Set Up Phone Numbers for Your Contact Center](https://docs.aws.amazon.com/connect/latest/adminguide/contact-center-phone-number.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPhoneNumbers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-phone-numbers.html)」を参照してください。

### `list-queues`
<a name="connect_ListQueues_cli_2_topic"></a>

次のコード例は、`list-queues` を使用する方法を示しています。

**AWS CLI**  
**インスタンス内のキューを一覧表示するには**  
次の `list-queues` の例では、指定された Amazon Connect インスタンスのキューを一覧表示しています。  

```
aws connect list-queues \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "QueueSummaryList": [
        {
            "Id": "12345678-1111-2222-800e-a2b3c4d5f6g7",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/queue/agent/12345678-1111-2222-800e-a2b3c4d5f6g7",
            "QueueType": "AGENT"
        },
        {
            "Id": "87654321-2222-3333-ac99-123456789102",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/queue/agent/87654321-2222-3333-ac99-123456789102",
            "QueueType": "AGENT"
        },
        {
            "Id": "abcdefgh-3333-4444-8af3-201123456789",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/queue/agent/abcdefgh-3333-4444-8af3-201123456789",
            "QueueType": "AGENT"
        },
        {
            "Id": "hgfedcba-4444-5555-a31f-123456789102",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/queue/hgfedcba-4444-5555-a31f-123456789102",
            "Name": "BasicQueue",
            "QueueType": "STANDARD"
        },
    ]
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Create a Queue](https://docs.aws.amazon.com/connect/latest/adminguide/create-queue.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListQueues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-queues.html)」を参照してください。**

### `list-routing-profiles`
<a name="connect_ListRoutingProfiles_cli_2_topic"></a>

次のコード例は、`list-routing-profiles` を使用する方法を示しています。

**AWS CLI**  
**インスタンス内のルーティングプロファイルを一覧表示するには**  
次の `list-routing-profiles` の例では、指定された Amazon Connect インスタンス内のルーティングプロファイルを一覧表示しています。  

```
aws connect list-routing-profiles \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RoutingProfileSummaryList": [
        {
            "Id": "12345678-1111-2222-800e-a2b3c4d5f6g7",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/routing-profile/12345678-1111-2222-800e-a2b3c4d5f6g7",
            "Name": "Basic Routing Profile"
        },
    ]
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Create a Routing Profile](https://docs.aws.amazon.com/connect/latest/adminguide/routing-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoutingProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-routing-profiles.html)」を参照してください。

### `list-security-profiles`
<a name="connect_ListSecurityProfiles_cli_2_topic"></a>

次のコード例は、`list-security-profiles` を使用する方法を示しています。

**AWS CLI**  
**インスタンス内のセキュリティプロファイルを一覧表示するには**  
次の `list-security-profiles` の例では、指定された Amazon Connect インスタンス内のセキュリティプロファイルを一覧表示しています。  

```
aws connect list-security-profiles \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "SecurityProfileSummaryList": [
        {
            "Id": "12345678-1111-2222-800e-a2b3c4d5f6g7",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/security-profile/12345678-1111-2222-800e-a2b3c4d5f6g7",
            "Name": "CallCenterManager"
        },
        {
            "Id": "87654321-2222-3333-ac99-123456789102",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/security-profile/87654321-2222-3333-ac99-123456789102",
            "Name": "QualityAnalyst"
        },
        {
            "Id": "abcdefgh-3333-4444-8af3-201123456789",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/security-profile/abcdefgh-3333-4444-8af3-201123456789",
            "Name": "Agent"
        },
        {
            "Id": "12345678-1111-2222-800e-x2y3c4d5fzzzz",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111/security-profile/12345678-1111-2222-800e-x2y3c4d5fzzzz",
            "Name": "Admin"
        }
    ]
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Assign Permissions: Security Profiles](https://docs.aws.amazon.com/connect/latest/adminguide/connect-security-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSecurityProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-security-profiles.html)」を参照してください。

### `list-user-hierarchy-groups`
<a name="connect_ListUserHierarchyGroups_cli_2_topic"></a>

次のコード例は、`list-user-hierarchy-groups` を使用する方法を示しています。

**AWS CLI**  
**インスタンス内のユーザー階層グループを一覧表示するには**  
次の `list-user-hierarchy-groups` の例では、指定された Amazon Connect インスタンス内のユーザー階層グループを一覧表示しています。  

```
aws connect list-user-hierarchy-groups \
    --instance-id 40c83b68-ea62-414c-97bb-d018e39e158e
```
出力:  

```
{
    "UserHierarchyGroupSummaryList": [
        {
            "Id": "0e2f6d1d-b3ca-494b-8dbc-ba81d9f8182a",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/40c83b68-ea62-414c-97bb-d018e39e158e/agent-group/0e2f6d1d-b3ca-494b-8dbc-ba81d9f8182a",
            "Name": "Example Corporation"
        },
    ]
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Set Up Agent Hierarchies](https://docs.aws.amazon.com/connect/latest/adminguide/agent-hierarchy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUserHierarchyGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-user-hierarchy-groups.html)」を参照してください。

### `list-users`
<a name="connect_ListUsers_cli_2_topic"></a>

次のコード例は、`list-users` を使用する方法を示しています。

**AWS CLI**  
**インスタンス内のユーザー階層グループを一覧表示するには**  
次の `list-users` の例では、指定された Amazon Connect インスタンス内のユーザーを一覧表示しています。  

```
aws connect list-users \
    --instance-id 40c83b68-ea62-414c-97bb-d018e39e158e
```
出力:  

```
{
    "UserSummaryList": [
        {
            "Id": "0c245dc0-0cf5-4e37-800e-2a7481cc8a60",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/40c83b68-ea62-414c-97bb-d018e39e158e/agent/0c245dc0-0cf5-4e37-800e-2a7481cc8a60",
            "Username": "Jane"
        },
        {
            "Id": "46f0c67c-3fc7-4806-ac99-403798788c14",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/40c83b68-ea62-414c-97bb-d018e39e158e/agent/46f0c67c-3fc7-4806-ac99-403798788c14",
            "Username": "Paulo"
        },
        {
            "Id": "55a83578-95e1-4710-8af3-2b7afe310e48",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/40c83b68-ea62-414c-97bb-d018e39e158e/agent/55a83578-95e1-4710-8af3-2b7afe310e48",
            "Username": "JohnD"
        },
        {
            "Id": "703e27b5-c9f0-4f1f-a239-64ccbb160125",
            "Arn": "arn:aws:connect:us-west-2:123456789012:instance/40c83b68-ea62-414c-97bb-d018e39e158e/agent/703e27b5-c9f0-4f1f-a239-64ccbb160125",
            "Username": "JohnS"
        }
    ]
}
```
詳細については、「*Amazon Connect 管理者ガイド*」の「[Add Users](https://docs.aws.amazon.com/connect/latest/adminguide/user-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/list-users.html)」を参照してください。

### `update-contact-attributes`
<a name="connect_UpdateContactAttributes_cli_2_topic"></a>

次のコード例は、`update-contact-attributes` を使用する方法を示しています。

**AWS CLI**  
**連絡先の属性を更新するには**  
次の `update-contact-attributes` の例では、指定された Amazon Connect ユーザーの `greetingPlayed` 属性を更新しています。  

```
aws connect update-contact-attributes \
    --initial-contact-id 11111111-2222-3333-4444-12345678910 \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --attributes greetingPlayed=false
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Connect 管理者ガイド*」の「[Use Amazon Connect Contact Attributes](https://docs.aws.amazon.com/connect/latest/adminguide/connect-contact-attributes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateContactAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/update-contact-attributes.html)」を参照してください。

### `update-user-hierarchy`
<a name="connect_UpdateUserHierarchy_cli_2_topic"></a>

次のコード例は、`update-user-hierarchy` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの階層を更新するには**  
次の `update-user-hierarchy` の例では、指定された Amazon Connect ユーザーのエージェント階層を更新しています。  

```
aws connect update-user-hierarchy \
    --hierarchy-group-id 12345678-a1b2-c3d4-e5f6-123456789abc \
    --user-id 87654321-2222-1234-1234-111234567891 \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Connect 管理者ガイド*」の「[Configure Agent Settings](https://docs.aws.amazon.com/connect/latest/adminguide/configure-agents.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserHierarchy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/update-user-hierarchy.html)」を参照してください。

### `update-user-identity-info`
<a name="connect_UpdateUserIdentityInfo_cli_2_topic"></a>

次のコード例は、`update-user-identity-info` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの ID 情報を更新するには**  
次の `update-user-identity-info` の例では、指定された Amazon Connect ユーザーの ID 情報を更新しています。  

```
aws connect update-user-identity-info \
    --identity-info FirstName=Mary,LastName=Major,Email=marym@example.com \
    --user-id 87654321-2222-1234-1234-111234567891 \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Connect 管理者ガイド*」の「[Configure Agent Settings](https://docs.aws.amazon.com/connect/latest/adminguide/configure-agents.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserIdentityInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/update-user-identity-info.html)」を参照してください。

### `update-user-phone-config`
<a name="connect_UpdateUserPhoneConfig_cli_2_topic"></a>

次のコード例は、`update-user-phone-config` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの電話設定を更新するには**  
次の `update-user-phone-config` の例では、指定されたユーザーの電話設定を更新しています。  

```
aws connect update-user-phone-config \
    --phone-config PhoneType=SOFT_PHONE,AutoAccept=false,AfterContactWorkTimeLimit=60,DeskPhoneNumber=+18005551212 \
    --user-id 12345678-4444-3333-2222-111122223333 \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Connect 管理者ガイド*」の「[Configure Agent Settings](https://docs.aws.amazon.com/connect/latest/adminguide/configure-agents.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserPhoneConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/update-user-phone-config.html)」を参照してください。

### `update-user-routing-profile`
<a name="connect_UpdateUserRoutingProfile_cli_2_topic"></a>

次のコード例は、`update-user-routing-profile` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのルーティングプロファイルを更新するには**  
次の `update-user-routing-profile` の例では、指定された Amazon Connect ユーザーのルーティングプロファイルを更新しています。  

```
aws connect update-user-routing-profile \
    --routing-profile-id 12345678-1111-3333-2222-4444EXAMPLE \
    --user-id 87654321-2222-1234-1234-111234567891 \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Connect 管理者ガイド*」の「[Configure Agent Settings](https://docs.aws.amazon.com/connect/latest/adminguide/configure-agents.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserRoutingProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/update-user-routing-profile.html)」を参照してください。

### `update-user-security-profiles`
<a name="connect_UpdateUserSecurityProfiles_cli_2_topic"></a>

次のコード例は、`update-user-security-profiles` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのセキュリティプロファイルを更新するには**  
次の `update-user-security-profiles` の例では、指定された Amazon Connect ユーザーのセキュリティプロファイルを更新しています。  

```
aws connect update-user-security-profiles \
    --security-profile-ids 12345678-1234-1234-1234-1234567892111 \
    --user-id 87654321-2222-1234-1234-111234567891 \
    --instance-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Connect 管理者ガイド*」の「[Assign Permissions: Security Profiles](https://docs.aws.amazon.com/connect/latest/adminguide/connect-security-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUserSecurityProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/connect/update-user-security-profiles.html)」を参照してください。

# AWS Cost and Usage Report を使用した の例 AWS CLI
<a name="cli_2_cost-and-usage-report-service_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Cost and Usage Report。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-report-definition`
<a name="cost-and-usage-report-service_DeleteReportDefinition_cli_2_topic"></a>

次の例は、`delete-report-definition` を使用する方法を説明しています。

**AWS CLI**  
** AWS コストと使用状況レポートを削除するには**  
この例では、 AWS コストと使用状況レポートを削除します。  
コマンド:  

```
aws cur --region us-east-1 delete-report-definition --report-name "ExampleReport"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReportDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cur/delete-report-definition.html)」を参照してください。

### `describe-report-definitions`
<a name="cost-and-usage-report-service_DescribeReportDefinitions_cli_2_topic"></a>

次の例は、`describe-report-definitions` を使用する方法を説明しています。

**AWS CLI**  
** AWS コストと使用状況レポートのリストを取得するには**  
この例では、アカウントが所有する AWS コストと使用状況レポートのリストについて説明します。  
コマンド:  

```
aws cur --region us-east-1 describe-report-definitions --max-items 5
```
出力:  

```
  {
"ReportDefinitions": [
  {
      "ReportName": "ExampleReport",
      "Compression": "ZIP",
      "S3Region": "us-east-1",
      "Format": "textORcsv",
      "S3Prefix": "exampleprefix",
      "S3Bucket": "example-s3-bucket",
      "TimeUnit": "DAILY",
      "AdditionalArtifacts": [
          "REDSHIFT",
          "QUICKSIGHT"
      ],
      "AdditionalSchemaElements": [
          "RESOURCES"
      ]
  }
]
  }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReportDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cur/describe-report-definitions.html)」を参照してください。

### `put-report-definition`
<a name="cost-and-usage-report-service_PutReportDefinition_cli_2_topic"></a>

次の例は、`put-report-definition` を使用する方法を説明しています。

**AWS CLI**  
** AWS コストと使用状況レポートを作成するには**  
次の`put-report-definition`例では、Amazon Redshift または Amazon QuickSight にアップロードできる毎日の AWS コストと使用状況レポートを作成します。  

```
aws cur put-report-definition --report-definition file://report-definition.json
```
`report-definition.json` の内容:  

```
{
    "ReportName": "ExampleReport",
    "TimeUnit": "DAILY",
    "Format": "textORcsv",
    "Compression": "ZIP",
    "AdditionalSchemaElements": [
        "RESOURCES"
    ],
    "S3Bucket": "example-s3-bucket",
    "S3Prefix": "exampleprefix",
    "S3Region": "us-east-1",
    "AdditionalArtifacts": [
        "REDSHIFT",
        "QUICKSIGHT"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutReportDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cur/put-report-definition.html)」を参照してください。

# を使用した Cost Explorer Service の例 AWS CLI
<a name="cli_2_cost-explorer_code_examples"></a>

次のコード例は、Cost Explorer Service AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-cost-and-usage`
<a name="cost-explorer_GetCostAndUsage_cli_2_topic"></a>

次のコード例は、`get-cost-and-usage` を使用する方法を示しています。

**AWS CLI**  
**2017 年 9 月に関するアカウントの S3 の使用状況を取得するには**  
次の `get-cost-and-usage` の例では、2017 年 9 月のアカウントの S3 の使用状況を取得しています。  

```
aws ce get-cost-and-usage \
    --time-period Start=2017-09-01,End=2017-10-01 \
    --granularity MONTHLY \
    --metrics "BlendedCost" "UnblendedCost" "UsageQuantity" \
    --group-by Type=DIMENSION,Key=SERVICE Type=TAG,Key=Environment \
    --filter file://filters.json
```
`filters.json` の内容:  

```
{
    "Dimensions": {
        "Key": "SERVICE",
        "Values": [
            "Amazon Simple Storage Service"
        ]
    }
}
```
出力:  

```
{
    "GroupDefinitions": [
        {
            "Type": "DIMENSION",
            "Key": "SERVICE"
        },
        {
            "Type": "TAG",
            "Key": "Environment"
        }
    ],
    "ResultsByTime": [
        {
            "Estimated": false,
            "TimePeriod": {
                "Start": "2017-09-01",
                "End": "2017-10-01"
            },
            "Total": {},
            "Groups": [
                {
                    "Keys": [
                        "Amazon Simple Storage Service",
                        "Environment$"
                    ],
                    "Metrics": {
                        "BlendedCost": {
                            "Amount": "40.3527508453",
                            "Unit": "USD"
                        },
                        "UnblendedCost": {
                            "Amount": "40.3543773134",
                            "Unit": "USD"
                        },
                        "UsageQuantity": {
                            "Amount": "9312771.098461578",
                            "Unit": "N/A"
                        }
                    }
                },
                {
                    "Keys": [
                        "Amazon Simple Storage Service",
                        "Environment$Dev"
                    ],
                    "Metrics": {
                        "BlendedCost": {
                            "Amount": "0.2682364644",
                            "Unit": "USD"
                        },
                        "UnblendedCost": {
                            "Amount": "0.2682364644",
                            "Unit": "USD"
                        },
                        "UsageQuantity": {
                            "Amount": "22403.4395271182",
                            "Unit": "N/A"
                        }
                    }
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCostAndUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ce/get-cost-and-usage.html)」を参照してください。

### `get-dimension-values`
<a name="cost-explorer_GetDimensionValues_cli_2_topic"></a>

次のコード例は、`get-dimension-values` を使用する方法を示しています。

**AWS CLI**  
**「Elastic」という値を使用してディメンション SERVICE のタグを取得するには**  
この例では、2017 年 1 月 1 日から 2017 年 5 月 18 日までの値「Elastic」を持つディメンション SERVICE のタグを取得しています。  
コマンド:  

```
aws ce get-dimension-values --search-string Elastic --time-period Start=2017-01-01,End=2017-05-18 --dimension SERVICE
```
出力:  

```
{
   "TotalSize": 6,
   "DimensionValues": [
       {
           "Attributes": {},
           "Value": "Amazon ElastiCache"
       },
       {
           "Attributes": {},
           "Value": "EC2 - Other"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elastic Compute Cloud - Compute"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elastic Load Balancing"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elastic MapReduce"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elasticsearch Service"
       }
   ],
   "ReturnSize": 6
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDimensionValues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ce/get-dimension-values.html)」を参照してください。

### `get-reservation-coverage`
<a name="cost-explorer_GetReservationCoverage_cli_2_topic"></a>

次のコード例は、`get-reservation-coverage` を使用する方法を示しています。

**AWS CLI**  
**us-east-1 リージョンの EC2 t2.nano インスタンスの予約カバレッジを取得するには**  
この例では、2017 年 7 月から 9 月の us-east-1 リージョンの EC2 t2.nano インスタンスの予約カバレッジを取得しています。  
コマンド:  

```
aws ce get-reservation-coverage --time-period Start=2017-07-01,End=2017-10-01 --group-by Type=Dimension,Key=REGION --filter file://filters.json
```
filters.json:  

```
{
   "And": [
     {
       "Dimensions": {
         "Key": "INSTANCE_TYPE",
         "Values": [
           "t2.nano"
         ]
       },
       "Dimensions": {
         "Key": "REGION",
         "Values": [
           "us-east-1"
         ]
       }
     }
   ]
 }
```
出力:  

```
{
   "TotalSize": 6,
   "DimensionValues": [
       {
           "Attributes": {},
           "Value": "Amazon ElastiCache"
       },
       {
           "Attributes": {},
           "Value": "EC2 - Other"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elastic Compute Cloud - Compute"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elastic Load Balancing"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elastic MapReduce"
       },
       {
           "Attributes": {},
           "Value": "Amazon Elasticsearch Service"
       }
   ],
   "ReturnSize": 6
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReservationCoverage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ce/get-reservation-coverage.html)」を参照してください。

### `get-reservation-purchase-recommendation`
<a name="cost-explorer_GetReservationPurchaseRecommendation_cli_2_topic"></a>

次のコード例は、`get-reservation-purchase-recommendation` を使用する方法を示しています。

**AWS CLI**  
**3 年契約の一部前払い EC2 RI の予約の推奨事項を取得するには**  
次の `get-reservation-purchase-recommendation` の例では、過去 60 日間の EC2 の使用状況に基づいて、3 年契約の一部前払い EC2 インスタンスの推奨事項を取得しています。  

```
aws ce get-reservation-purchase-recommendation \
    --service "Amazon Redshift" \
    --lookback-period-in-days SIXTY_DAYS \
    --term-in-years THREE_YEARS \
    --payment-option PARTIAL_UPFRONT
```
出力:  

```
{
    "Recommendations": [],
    "Metadata": {
        "GenerationTimestamp": "2018-08-08T15:20:57Z",
        "RecommendationId": "00d59dde-a1ad-473f-8ff2-iexample3330b"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReservationPurchaseRecommendation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ce/get-reservation-purchase-recommendation.html)」を参照してください。

### `get-reservation-utilization`
<a name="cost-explorer_GetReservationUtilization_cli_2_topic"></a>

次のコード例は、`get-reservation-utilization` を使用する方法を示しています。

**AWS CLI**  
**アカウントの予約率を取得するには**  
次の `get-reservation-utilization` の例では、アカウントの 2018-03-01 から 2018-08-01 までのすべての t2.nano インスタンスタイプの RI 使用率を取得しています。  

```
aws ce get-reservation-utilization \
    --time-period Start=2018-03-01,End=2018-08-01 \
    --filter file://filters.json
```
`filters.json` の内容:  

```
{
    "Dimensions": {
        "Key": "INSTANCE_TYPE",
        "Values": [
            "t2.nano"
        ]
    }
}
```
出力:  

```
{
    "Total": {
        "TotalAmortizedFee": "0",
        "UtilizationPercentage": "0",
        "PurchasedHours": "0",
        "NetRISavings": "0",
        "TotalActualHours": "0",
        "AmortizedRecurringFee": "0",
        "UnusedHours": "0",
        "TotalPotentialRISavings": "0",
        "OnDemandCostOfRIHoursUsed": "0",
        "AmortizedUpfrontFee": "0"
    },
    "UtilizationsByTime": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReservationUtilization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ce/get-reservation-utilization.html)」を参照してください。

### `get-tags`
<a name="cost-explorer_GetTags_cli_2_topic"></a>

次のコード例は、`get-tags` を使用する方法を示しています。

**AWS CLI**  
**コスト配分タグのキーと値を取得するには**  
この例では、「プロジェクト」のキーと「secretProject」を含む値を持つすべてのコスト配分タグを取得しています。  
コマンド:  

```
aws ce get-tags --search-string secretProject --time-period Start=2017-01-01,End=2017-05-18 --tag-key Project
```
出力:  

```
{
  "ReturnSize": 2,
  "Tags": [
    "secretProject1",
    "secretProject2"
  ],
  "TotalSize": 2
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ce/get-tags.html)」を参照してください。

# を使用した Firehose の例 AWS CLI
<a name="cli_2_firehose_code_examples"></a>

次のコード例は、Firehose AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `list-delivery-streams`
<a name="firehose_ListDeliveryStreams_cli_2_topic"></a>

次のコード例は、`list-delivery-streams` を使用する方法を示しています。

**AWS CLI**  
**使用可能な配信ストリームを一覧表示するには**  
次の の`list-delivery-streams`例では、 AWS アカウントで使用可能な配信ストリームを一覧表示します。  

```
aws firehose list-delivery-streams
```
出力:  

```
{
    "DeliveryStreamNames": [
        "my-stream"
    ],
    "HasMoreDeliveryStreams": false
}
```
詳細については、*Amazon Kinesis Data Firehose デベロッパーガイド*の「[Amazon Kinesis Data Firehose 配信ストリームの作成](https://docs.aws.amazon.com/firehose/latest/dev/basic-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeliveryStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/firehose/list-delivery-streams.html)」を参照してください。

### `put-record-batch`
<a name="firehose_PutRecordBatch_cli_2_topic"></a>

次のコード例は、`put-record-batch` を使用する方法を示しています。

**AWS CLI**  
**複数のレコードをストリームに書き込むには**  
この `put-record-batch` の例は、3 つのレコードをストリームに書き込みます。データは Base64 形式でエンコードされます。  

```
aws firehose put-record-batch \
    --delivery-stream-name my-stream \
    --records file://records.json
```
`myfile.json` の内容:  

```
[
    {"Data": "Rmlyc3QgdGhpbmc="},
    {"Data": "U2Vjb25kIHRoaW5n"},
    {"Data": "VGhpcmQgdGhpbmc="}
]
```
出力:  

```
{
    "FailedPutCount": 0,
    "Encrypted": false,
    "RequestResponses": [
        {
            "RecordId": "9D2OJ6t2EqCTZTXwGzeSv/EVHxRoRCw89xd+o3+sXg8DhYOaWKPSmZy/CGlRVEys1u1xbeKh6VofEYKkoeiDrcjrxhQp9iF7sUW7pujiMEQ5LzlrzCkGosxQn+3boDnURDEaD42V7GiixpOyLJkYZcae1i7HzlCEoy9LJhMr8EjDSi4Om/9Vc2uhwwuAtGE0XKpxJ2WD7ZRWtAnYlKAnvgSPRgg7zOWL"
        },
        {
            "RecordId": "jFirejqxCLlK5xjH/UNmlMVcjktEN76I7916X9PaZ+PVaOSXDfU1WGOqEZhxq2js7xcZ552eoeDxsuTU1MSq9nZTbVfb6cQTIXnm/GsuF37Uhg67GKmR5z90l6XKJ+/+pDloFv7Hh9a3oUS6wYm3DcNRLTHHAimANp1PhkQvWpvLRfzbuCUkBphR2QVzhP9OiHLbzGwy8/DfH8sqWEUYASNJKS8GXP5s"
        },
        {
            "RecordId": "oy0amQ40o5Y2YV4vxzufdcMOOw6n3EPr3tpPJGoYVNKH4APPVqNcbUgefo1stEFRg4hTLrf2k6eliHu/9+YJ5R3iiedHkdsfkIqX0XTySSutvgFYTjNY1TSrK0pM2sWxpjqqnk3+2UX1MV5z88xGro3cQm/DTBt3qBlmTj7Xq8SKVbO1S7YvMTpWkMKA86f8JfmT8BMKoMb4XZS/sOkQLe+qh0sYKXWl"
        }
    ]
}
```
詳細については、「Amazon Kinesis Data Firehose ディベロッパーガイド」の「[Amazon Kinesis Data Firehose 配信ストリームへのデータの送信](https://docs.aws.amazon.com/firehose/latest/dev/basic-write.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutRecordBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/firehose/put-record-batch.html)」を参照してください。**

### `put-record`
<a name="firehose_PutRecord_cli_2_topic"></a>

次のコード例は、`put-record` を使用する方法を示しています。

**AWS CLI**  
**ストリームにレコードを書き込むには**  
次の `put-record` の例では、データをストリームに書き込みます。データは Base64 形式でエンコードされます。  

```
aws firehose put-record \
    --delivery-stream-name my-stream \
    --record '{"Data":"SGVsbG8gd29ybGQ="}'
```
出力:  

```
{
    "RecordId": "RjB5K/nnoGFHqwTsZlNd/TTqvjE8V5dsyXZTQn2JXrdpMTOwssyEb6nfC8fwf1whhwnItt4mvrn+gsqeK5jB7QjuLg283+Ps4Sz/j1Xujv31iDhnPdaLw4BOyM9Amv7PcCuB2079RuM0NhoakbyUymlwY8yt20G8X2420wu1jlFafhci4erAt7QhDEvpwuK8N1uOQ1EuaKZWxQHDzcG6tk1E49IPeD9k",
    "Encrypted": false
}
```
詳細については、「Amazon Kinesis Data Firehose ディベロッパーガイド」の「[Amazon Kinesis Data Firehose 配信ストリームへのデータの送信](https://docs.aws.amazon.com/firehose/latest/dev/basic-write.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutRecord](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/firehose/put-record.html)」を参照してください。**

# を使用した Amazon Data Lifecycle Manager の例 AWS CLI
<a name="cli_2_dlm_code_examples"></a>

次のコード例は、Amazon Data Lifecycle Manager AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-default-role`
<a name="dlm_CreateDefaultRole_cli_2_topic"></a>

次のコード例は、`create-default-role` を使用する方法を示しています。

**AWS CLI**  
**Amazon DLM 用にひつような IAM ロールを作成するには**  
次の`dlm create-default-role`例では、スナップショットを管理するための AWS DataLifecycleManagerDefaultRole デフォルトロールを作成します。  

```
aws dlm create-default-role \
    --resource-type snapshot
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[Default service roles for Amazon Data Lifecycle Manager](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/service-role.html#default-service-roles)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDefaultRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dlm/create-default-role.html)」を参照してください。

### `create-lifecycle-policy`
<a name="dlm_CreateLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`create-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシーを作成するには**  
次の `create-lifecycle-policy` の例では、指定した時間にボリュームのスナップショットを毎日作成するライフサイクルポリシーを作成します。指定されたタグはスナップショットに追加され、タグもボリュームからコピーされてスナップショットに追加されます。新しいスナップショットの作成が指定された最大数を超える場合は、最も古いスナップショットが削除されます。  

```
aws dlm create-lifecycle-policy \
    --description "My first policy" \
    --state ENABLED \
    --execution-role-arn arn:aws:iam::12345678910:role/AWSDataLifecycleManagerDefaultRole \
    --policy-details file://policyDetails.json
```
`policyDetails.json` の内容:  

```
{
    "ResourceTypes": [
        "VOLUME"
    ],
    "TargetTags": [
        {
            "Key": "costCenter",
            "Value": "115"
        }
    ],
    "Schedules":[
        {
            "Name": "DailySnapshots",
            "CopyTags": true,
            "TagsToAdd": [
                {
                    "Key": "type",
                     "Value": "myDailySnapshot"
                }
            ],
            "CreateRule": {
                "Interval": 24,
                "IntervalUnit": "HOURS",
                "Times": [
                    "03:00"
                ]
            },
            "RetainRule": {
                "Count":5
            }
        }
    ]
}
```
出力:  

```
{
    "PolicyId": "policy-0123456789abcdef0"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dlm/create-lifecycle-policy.html)」を参照してください。

### `delete-lifecycle-policy`
<a name="dlm_DeleteLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`delete-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシーを削除するには**  
次の例では、指定されたライフサイクルポリシーを削除します。  

```
aws dlm delete-lifecycle-policy --policy-id policy-0123456789abcdef0
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dlm/delete-lifecycle-policy.html)」を参照してください。

### `get-lifecycle-policies`
<a name="dlm_GetLifecyclePolicies_cli_2_topic"></a>

次のコード例は、`get-lifecycle-policies` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシーの概要を取得するには**  
次の `get-lifecycle-policies` の例では、すべてのライフサイクルポリシーを一覧表示します。  

```
aws dlm get-lifecycle-policies
```
出力:  

```
{
    "Policies": [
        {
            "PolicyId": "policy-0123456789abcdef0",
            "Description": "My first policy",
            "State": "ENABLED"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLifecyclePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dlm/get-lifecycle-policies.html)」を参照してください。

### `get-lifecycle-policy`
<a name="dlm_GetLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`get-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシーを記述するには**  
次の `get-lifecycle-policy` の例では、指定されたライフサイクルポリシーの詳細を表示します。  

```
aws dlm get-lifecycle-policy \
    --policy-id policy-0123456789abcdef0
```
出力:  

```
{
    "Policy": {
        "PolicyId": "policy-0123456789abcdef0",
        "Description": "My policy",
        "State": "ENABLED",
        "ExecutionRoleArn": "arn:aws:iam::123456789012:role/AWSDataLifecycleManagerDefaultRole",
        "DateCreated": "2019-08-08T17:45:42Z",
        "DateModified": "2019-08-08T17:45:42Z",
        "PolicyDetails": {
            "PolicyType": "EBS_SNAPSHOT_MANAGEMENT",
            "ResourceTypes": [
                "VOLUME"
            ],
            "TargetTags": [
              {
                  "Key": "costCenter",
                  "Value": "115"
              }
            ],
            "Schedules": [
              {
                  "Name": "DailySnapshots",
                  "CopyTags": true,
                  "TagsToAdd": [
                    {
                        "Key": "type",
                        "Value": "myDailySnapshot"
                    }
                  ],
                  "CreateRule": {
                    "Interval": 24,
                    "IntervalUnit": "HOURS",
                    "Times": [
                        "03:00"
                    ]
                  },
                  "RetainRule": {
                    "Count": 5
                  }
              }
            ]
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dlm/get-lifecycle-policy.html)」を参照してください。

### `update-lifecycle-policy`
<a name="dlm_UpdateLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`update-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: ライフサイクルポリシーを有効にするには**  
次の `update-lifecycle-policy` の例では、指定されたライフサイクルポリシーを有効にします。  

```
aws dlm update-lifecycle-policy \
    --policy-id policy-0123456789abcdef0 \
    --state ENABLED
```
**例 2: ライフサイクルポリシーを無効にするには**  
次の `update-lifecycle-policy` の例では、指定されたライフサイクルポリシーを無効にします。  

```
aws dlm update-lifecycle-policy \
    --policy-id policy-0123456789abcdef0 \
    --state DISABLED
```
**例 3: ライフサイクルポリシーの詳細を更新するには**  
次の `update-lifecycle-policy` の例では、指定されたライフサイクルポリシーのターゲットタグを更新します。  

```
aws dlm update-lifecycle-policy \
    --policy-id policy-0123456789abcdef0
    --policy-details file://policyDetails.json
```
`policyDetails.json` の内容。このファイルで参照されていないその他の詳細は、コマンドでは変更されません。  

```
{
    "TargetTags": [
        {
            "Key": "costCenter",
            "Value": "120"
        },
        {
            "Key": "project",
            "Value": "lima"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dlm/update-lifecycle-policy.html)」を参照してください。

# AWS Data Pipeline を使用した の例 AWS CLI
<a name="cli_2_data-pipeline_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Data Pipeline。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `activate-pipeline`
<a name="data-pipeline_ActivatePipeline_cli_2_topic"></a>

次のコード例は、`activate-pipeline` を使用する方法を示しています。

**AWS CLI**  
**パイプラインをアクティブ化するには**  
この例では、指定されたパイプラインをアクティブ化しています。  

```
aws datapipeline activate-pipeline --pipeline-id df-00627471SOVYZEXAMPLE
```
特定の日時でパイプラインをアクティブ化するには、次のコマンドを使用します。  

```
aws datapipeline activate-pipeline --pipeline-id df-00627471SOVYZEXAMPLE --start-timestamp 2015-04-07T00:00:00Z
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ActivatePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/activate-pipeline.html)」を参照してください。

### `add-tags`
<a name="data-pipeline_AddTags_cli_2_topic"></a>

次のコード例は、`add-tags` を使用する方法を示しています。

**AWS CLI**  
**パイプラインにタグを追加するには**  
この例では、指定されたタグを指定されたパイプラインに追加しています。  

```
aws datapipeline add-tags --pipeline-id df-00627471SOVYZEXAMPLE --tags key=environment,value=production key=owner,value=sales
```
タグを表示するには、describe-pipelines コマンドを使用します。たとえば、サンプルコマンドで追加されたタグは、describe-pipelines の出力に次のように表示されます。  

```
{
    ...
        "tags": [
            {
                "value": "production",
                "key": "environment"
            },
            {
                "value": "sales",
                "key": "owner"
            }
        ]
    ...
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/add-tags.html)」を参照してください。

### `create-pipeline`
<a name="data-pipeline_CreatePipeline_cli_2_topic"></a>

次のコード例は、`create-pipeline` を使用する方法を示しています。

**AWS CLI**  
**パイプラインを作成するには**  
この例では、パイプラインを作成しています。  

```
aws datapipeline create-pipeline --name my-pipeline --unique-id my-pipeline-token
```
出力例を次に示します。  

```
{
    "pipelineId": "df-00627471SOVYZEXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/create-pipeline.html)」を参照してください。

### `deactivate-pipeline`
<a name="data-pipeline_DeactivatePipeline_cli_2_topic"></a>

次のコード例は、`deactivate-pipeline` を使用する方法を示しています。

**AWS CLI**  
パイプラインを非アクティブ化するには  
この例では、指定されたパイプラインを非アクティブ化しています。  

```
aws datapipeline deactivate-pipeline --pipeline-id df-00627471SOVYZEXAMPLE
```
すべての実行中のアクティビティが終了した後にのみ、パイプラインを非アクティブ化するには、次のコマンドを使用します。  

```
aws datapipeline deactivate-pipeline --pipeline-id df-00627471SOVYZEXAMPLE --no-cancel-active
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeactivatePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/deactivate-pipeline.html)」を参照してください。

### `delete-pipeline`
<a name="data-pipeline_DeletePipeline_cli_2_topic"></a>

次のコード例は、`delete-pipeline` を使用する方法を示しています。

**AWS CLI**  
**パイプラインを削除するには**  
この例では、指定されたパイプラインを削除しています。  

```
aws datapipeline delete-pipeline --pipeline-id df-00627471SOVYZEXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/delete-pipeline.html)」を参照してください。

### `describe-pipelines`
<a name="data-pipeline_DescribePipelines_cli_2_topic"></a>

次のコード例は、`describe-pipelines` を使用する方法を示しています。

**AWS CLI**  
**パイプラインを記述するには**  
この例では、指定されたパイプラインを記述します。  

```
aws datapipeline describe-pipelines --pipeline-ids df-00627471SOVYZEXAMPLE
```
出力例を次に示します。  

```
{
  "pipelineDescriptionList": [
      {
          "fields": [
              {
                  "stringValue": "PENDING",
                  "key": "@pipelineState"
              },
              {
                  "stringValue": "my-pipeline",
                  "key": "name"
              },
              {
                  "stringValue": "2015-04-07T16:05:58",
                  "key": "@creationTime"
              },
              {
                  "stringValue": "df-00627471SOVYZEXAMPLE",
                  "key": "@id"
              },
              {
                  "stringValue": "123456789012",
                  "key": "pipelineCreator"
              },
              {
                  "stringValue": "PIPELINE",
                  "key": "@sphere"
              },
              {
                  "stringValue": "123456789012",
                  "key": "@userId"
              },
              {
                  "stringValue": "123456789012",
                  "key": "@accountId"
              },
              {
                  "stringValue": "my-pipeline-token",
                  "key": "uniqueId"
              }
          ],
          "pipelineId": "df-00627471SOVYZEXAMPLE",
          "name": "my-pipeline",
          "tags": []
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePipelines](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/describe-pipelines.html)」を参照してください。

### `get-pipeline-definition`
<a name="data-pipeline_GetPipelineDefinition_cli_2_topic"></a>

次のコード例は、`get-pipeline-definition` を使用する方法を示しています。

**AWS CLI**  
**パイプライン定義を取得するには**  
次の例では、指定したパイプラインのパイプライン定義を取得しています。  

```
aws datapipeline get-pipeline-definition --pipeline-id df-00627471SOVYZEXAMPLE
```
出力例を次に示します。  

```
{
  "parameters": [
      {
          "type": "AWS::S3::ObjectKey",
          "id": "myS3OutputLoc",
          "description": "S3 output folder"
      },
      {
          "default": "s3://us-east-1.elasticmapreduce.samples/pig-apache-logs/data",
          "type": "AWS::S3::ObjectKey",
          "id": "myS3InputLoc",
          "description": "S3 input folder"
      },
      {
          "default": "grep -rc \"GET\" ${INPUT1_STAGING_DIR}/* > ${OUTPUT1_STAGING_DIR}/output.txt",
          "type": "String",
          "id": "myShellCmd",
          "description": "Shell command to run"
      }
  ],
  "objects": [
      {
          "type": "Ec2Resource",
          "terminateAfter": "20 Minutes",
          "instanceType": "t1.micro",
          "id": "EC2ResourceObj",
          "name": "EC2ResourceObj"
      },
      {
          "name": "Default",
          "failureAndRerunMode": "CASCADE",
          "resourceRole": "DataPipelineDefaultResourceRole",
          "schedule": {
              "ref": "DefaultSchedule"
          },
          "role": "DataPipelineDefaultRole",
          "scheduleType": "cron",
          "id": "Default"
      },
      {
          "directoryPath": "#{myS3OutputLoc}/#{format(@scheduledStartTime, 'YYYY-MM-dd-HH-mm-ss')}",
          "type": "S3DataNode",
          "id": "S3OutputLocation",
          "name": "S3OutputLocation"
      },
      {
          "directoryPath": "#{myS3InputLoc}",
          "type": "S3DataNode",
          "id": "S3InputLocation",
          "name": "S3InputLocation"
      },
      {
          "startAt": "FIRST_ACTIVATION_DATE_TIME",
          "name": "Every 15 minutes",
          "period": "15 minutes",
          "occurrences": "4",
          "type": "Schedule",
          "id": "DefaultSchedule"
      },
      {
          "name": "ShellCommandActivityObj",
          "command": "#{myShellCmd}",
          "output": {
              "ref": "S3OutputLocation"
          },
          "input": {
              "ref": "S3InputLocation"
          },
          "stage": "true",
          "type": "ShellCommandActivity",
          "id": "ShellCommandActivityObj",
          "runsOn": {
              "ref": "EC2ResourceObj"
          }
      }
  ],
  "values": {
      "myS3OutputLoc": "s3://amzn-s3-demo-bucket/",
      "myS3InputLoc": "s3://us-east-1.elasticmapreduce.samples/pig-apache-logs/data",
      "myShellCmd": "grep -rc \"GET\" ${INPUT1_STAGING_DIR}/* > ${OUTPUT1_STAGING_DIR}/output.txt"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPipelineDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/get-pipeline-definition.html)」を参照してください。

### `list-pipelines`
<a name="data-pipeline_ListPipelines_cli_2_topic"></a>

次のコード例は、`list-pipelines` を使用する方法を示しています。

**AWS CLI**  
**パイプラインを一覧表示するには**  
この例では、パイプラインを一覧表示しています。  

```
aws datapipeline list-pipelines
```
出力例を次に示します。  

```
{
  "pipelineIdList": [
      {
          "id": "df-00627471SOVYZEXAMPLE",
          "name": "my-pipeline"
      },
      {
          "id": "df-09028963KNVMREXAMPLE",
          "name": "ImportDDB"
      },
      {
          "id": "df-0870198233ZYVEXAMPLE",
          "name": "CrossRegionDDB"
      },
      {
          "id": "df-00189603TB4MZEXAMPLE",
          "name": "CopyRedshift"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPipelines](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/list-pipelines.html)」を参照してください。

### `list-runs`
<a name="data-pipeline_ListRuns_cli_2_topic"></a>

次のコード例は、`list-runs` を使用する方法を示しています。

**AWS CLI**  
**例 1: パイプラインの実行を一覧表示するには**  
次の `list-runs` の例では、指定されたパイプラインの実行を一覧表示しています。  

```
aws datapipeline list-runs --pipeline-id df-00627471SOVYZEXAMPLE
```
出力:  

```
    Name                       Scheduled Start        Status                     ID                                              Started                Ended
    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1.  EC2ResourceObj             2015-04-12T17:33:02    CREATING                   @EC2ResourceObj_2015-04-12T17:33:02             2015-04-12T17:33:10
2.  S3InputLocation            2015-04-12T17:33:02    FINISHED                   @S3InputLocation_2015-04-12T17:33:02            2015-04-12T17:33:09    2015-04-12T17:33:09
3.  S3OutputLocation           2015-04-12T17:33:02    WAITING_ON_DEPENDENCIES    @S3OutputLocation_2015-04-12T17:33:02           2015-04-12T17:33:09
4.  ShellCommandActivityObj    2015-04-12T17:33:02    WAITING_FOR_RUNNER         @ShellCommandActivityObj_2015-04-12T17:33:02    2015-04-12T17:33:09
```
**例 2: 指定された日付の間のパイプライン実行を一覧表示するには**  
次の `list-runs` の例では、`--start-interval` を使用して、出力に含める日付を指定しています。  

```
aws datapipeline list-runs --pipeline-id df-01434553B58A2SHZUKO5 --start-interval 2017-10-07T00:00:00,2017-10-08T00:00:00
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRuns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/list-runs.html)」を参照してください。

### `put-pipeline-definition`
<a name="data-pipeline_PutPipelineDefinition_cli_2_topic"></a>

次のコード例は、`put-pipeline-definition` を使用する方法を示しています。

**AWS CLI**  
**パイプライン定義をアップロードするには**  
この例では、指定されたパイプライン定義を指定されたパイプラインにアップロードしています。  

```
aws datapipeline put-pipeline-definition --pipeline-id df-00627471SOVYZEXAMPLE --pipeline-definition file://my-pipeline-definition.json
```
出力例を次に示します。  

```
{
  "validationErrors": [],
  "errored": false,
  "validationWarnings": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutPipelineDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/put-pipeline-definition.html)」を参照してください。

### `remove-tags`
<a name="data-pipeline_RemoveTags_cli_2_topic"></a>

次のコード例は、`remove-tags` を使用する方法を示しています。

**AWS CLI**  
**パイプラインからタグを削除するには**  
この例では、指定されたタグを指定されたパイプラインから削除しています。  

```
aws datapipeline remove-tags --pipeline-id df-00627471SOVYZEXAMPLE --tag-keys environment
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datapipeline/remove-tags.html)」を参照してください。

# を使用した DataSync の例 AWS CLI
<a name="cli_2_datasync_code_examples"></a>

次のコード例は、DataSync AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `update-location-azure-blob`
<a name="datasync_UpdateLocationAzureBlob_cli_2_topic"></a>

次のコード例は、`update-location-azure-blob` を使用する方法を示しています。

**AWS CLI**  
**新しいエージェントを使用して転送場所を更新するには**  
次の `update-location-object-storage` の例では、新しいエージェントを使用して Microsoft Azure Blob Storage の DataSync のロケーションを更新しています。  

```
aws datasync update-location-azure-blob \
    --location-arn arn:aws:datasync:us-west-2:123456789012:location/loc-abcdef01234567890 \
    --agent-arns arn:aws:datasync:us-west-2:123456789012:agent/agent-1234567890abcdef0 \
    --sas-configuration '{ \
        "Token": "sas-token-for-azure-blob-storage-access" \
    }'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS DataSync ユーザーガイド*」の「[Replacing your agent](https://docs.aws.amazon.com/datasync/latest/userguide/replacing-agent.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLocationAzureBlob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datasync/update-location-azure-blob.html)」を参照してください。

### `update-location-hdfs`
<a name="datasync_UpdateLocationHdfs_cli_2_topic"></a>

次のコード例は、`update-location-hdfs` を使用する方法を示しています。

**AWS CLI**  
**新しいエージェントを使用して転送場所を更新するには**  
次の `update-location-hdfs` の例では、新しいエージェントを使用して DataSync HDFS のロケーションを更新しています。HDFS クラスターが Kerberos 認証を使用している場合にのみ、`--kerberos-keytab` オプションおよび `--kerberos-krb5-conf` オプションが必要です。  

```
aws datasync update-location-hdfs \
    --location-arn arn:aws:datasync:us-west-2:123456789012:location/loc-abcdef01234567890 \
    --agent-arns arn:aws:datasync:us-west-2:123456789012:agent/agent-1234567890abcdef0 \
    --kerberos-keytab file://hdfs.keytab
    --kerberos-krb5-conf file://krb5.conf
```
`hdfs.keytab` の内容:  

```
N/A. The content of this file is encrypted and not human readable.
```
`krb5.conf` の内容:  

```
[libdefaults]
    default_realm = EXAMPLE.COM
    dns_lookup_realm = false
    dns_lookup_kdc = false
    rdns = true
    ticket_lifetime = 24h
    forwardable = true
    udp_preference_limit = 1000000
    default_tkt_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1
    default_tgs_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1
    permitted_enctypes = aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96 des3-cbc-sha1

[realms]
    EXAMPLE.COM = {
      kdc = kdc1.example.com
      admin_server = krbadmin.example.com
      default_domain = example.com
    }

[domain_realm]
    .example.com = EXAMPLE.COM
    example.com = EXAMPLE.COM

[logging]
    kdc = FILE:/var/log/krb5kdc.log
    admin_server = FILE:/var/log/kerberos/kadmin.log
    default = FILE:/var/log/krb5libs.log
```
このコマンドでは何も出力されません。  
詳細については、「*AWS DataSync ユーザーガイド*」の「[Replacing your agent](https://docs.aws.amazon.com/datasync/latest/userguide/replacing-agent.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLocationHdfs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datasync/update-location-hdfs.html)」を参照してください。

### `update-location-nfs`
<a name="datasync_UpdateLocationNfs_cli_2_topic"></a>

次のコード例は、`update-location-nfs` を使用する方法を示しています。

**AWS CLI**  
**新しいエージェントを使用して転送場所を更新するには**  
次の `update-location-nfs` の例では、新しいエージェントを使用して DataSync NFS のロケーションを更新しています。  

```
aws datasync update-location-nfs \
    --location-arn arn:aws:datasync:us-west-2:123456789012:location/loc-abcdef01234567890 \
    --on-prem-config AgentArns=arn:aws:datasync:us-west-2:123456789012:agent/agent-1234567890abcdef0
```
このコマンドでは何も出力されません。  
詳細については、「*AWS DataSync ユーザーガイド*」の「[Replacing your agent](https://docs.aws.amazon.com/datasync/latest/userguide/replacing-agent.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLocationNfs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datasync/update-location-nfs.html)」を参照してください。

### `update-location-object-storage`
<a name="datasync_UpdateLocationObjectStorage_cli_2_topic"></a>

次のコード例は、`update-location-object-storage` を使用する方法を示しています。

**AWS CLI**  
**新しいエージェントを使用して転送場所を更新するには**  
次の `update-location-object-storage` の例では、新しいエージェントを使用して DataSync オブジェクトストレージのロケーションを更新しています。  

```
aws datasync update-location-object-storage \
    --location-arn arn:aws:datasync:us-west-2:123456789012:location/loc-abcdef01234567890 \
    --agent-arns arn:aws:datasync:us-west-2:123456789012:agent/agent-1234567890abcdef0 \
    --secret-key secret-key-for-object-storage
```
このコマンドでは何も出力されません。  
詳細については、「*AWS DataSync ユーザーガイド*」の「[Replacing your agent](https://docs.aws.amazon.com/datasync/latest/userguide/replacing-agent.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLocationObjectStorage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datasync/update-location-object-storage.html)」を参照してください。

### `update-location-smb`
<a name="datasync_UpdateLocationSmb_cli_2_topic"></a>

次のコード例は、`update-location-smb` を使用する方法を示しています。

**AWS CLI**  
**新しいエージェントを使用して転送場所を更新するには**  
次の `update-location-smb` の例では、新しいエージェントを使用して DataSync SMB のロケーションを更新しています。  

```
aws datasync update-location-smb \
    --location-arn arn:aws:datasync:us-west-2:123456789012:location/loc-abcdef01234567890 \
    --agent-arns arn:aws:datasync:us-west-2:123456789012:agent/agent-1234567890abcdef0 \
    --password smb-file-server-password
```
このコマンドでは何も出力されません。  
詳細については、「*AWS DataSync ユーザーガイド*」の「[Replacing your agent](https://docs.aws.amazon.com/datasync/latest/userguide/replacing-agent.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLocationSmb](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/datasync/update-location-smb.html)」を参照してください。

# を使用した DAX の例 AWS CLI
<a name="cli_2_dax_code_examples"></a>

次のコード例は、DAX AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-cluster`
<a name="dax_CreateCluster_cli_2_topic"></a>

次のコード例は、`create-cluster` を使用する方法を示しています。

**AWS CLI**  
**DAX クラスターを作成するには**  
次の `create-cluster` の例では、指定された設定で DAX クラスターを作成します。  

```
aws dax create-cluster \
    --cluster-name daxcluster \
    --node-type dax.r4.large \
    --replication-factor 3 \
    --iam-role-arn roleARN  \
    --sse-specification Enabled=true
```
出力:  

```
{
    "Cluster": {
        "ClusterName": "daxcluster",
        "ClusterArn": "arn:aws:dax:us-west-2:123456789012:cache/daxcluster",
        "TotalNodes": 3,
        "ActiveNodes": 0,
        "NodeType": "dax.r4.large",
        "Status": "creating",
        "ClusterDiscoveryEndpoint": {
            "Port": 8111
        },
        "PreferredMaintenanceWindow": "thu:13:00-thu:14:00",
        "SubnetGroup": "default",
        "SecurityGroups": [
            {
                "SecurityGroupIdentifier": "sg-1af6e36e",
                "Status": "active"
            }
        ],
        "IamRoleArn": "arn:aws:iam::123456789012:role/DAXServiceRoleForDynamoDBAccess",
        "ParameterGroup": {
            "ParameterGroupName": "default.dax1.0",
            "ParameterApplyStatus": "in-sync",
            "NodeIdsToReboot": []
        },
        "SSEDescription": {
            "Status": "ENABLED"
        }
    }
}
```
詳細については、「Amazon DynamoDB デベロッパーガイド」の「[Step 3: Create a DAX Cluster](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.create-cluster.cli.create-cluster.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/create-cluster.html)」を参照してください。

### `create-parameter-group`
<a name="dax_CreateParameterGroup_cli_2_topic"></a>

次のコード例は、`create-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループを作成するには**  
次の「create-parameter-group」の例では、指定された設定でパラメータグループを作成します。  

```
aws dax create-parameter-group \
    --parameter-group-name daxparametergroup \
    --description "A new parameter group"
```
出力:  

```
{
    "ParameterGroup": {
        "ParameterGroupName": "daxparametergroup",
        "Description": "A new parameter group"
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html#DAX.cluster-management.custom-settings.ttl)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/create-parameter-group.html)」を参照してください。

### `create-subnet-group`
<a name="dax_CreateSubnetGroup_cli_2_topic"></a>

次のコード例は、`create-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**DAX サブネットグループを作成するには**  
次の `create-subnet-group` の例では、指定された設定でサブネットグループを作成します。  

```
aws dax create-subnet-group \
    --subnet-group-name daxSubnetGroup \
    --subnet-ids subnet-11111111 subnet-22222222
```
出力:  

```
{
    "SubnetGroup": {
        "SubnetGroupName": "daxSubnetGroup",
        "VpcId": "vpc-05a1fa8e00c325226",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-11111111",
                "SubnetAvailabilityZone": "us-west-2b"
            },
            {
                "SubnetIdentifier": "subnet-22222222",
                "SubnetAvailabilityZone": "us-west-2c"
            }
        ]
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Step 2: Create a Subnet Group](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.create-cluster.cli.create-subnet-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/create-subnet-group.html)」を参照してください。

### `decrease-replication-factor`
<a name="dax_DecreaseReplicationFactor_cli_2_topic"></a>

次のコード例は、`decrease-replication-factor` を使用する方法を示しています。

**AWS CLI**  
**クラスターから 1 つ以上のノードを削除するには**  
次の `decrease-replication-factor` の例では、指定された ‭DAX クラスター‬内のノード数を 1 に減らします。‬‬‬‬‬  

```
aws dax decrease-replication-factor \
    --cluster-name daxcluster \
    --new-replication-factor 1
```
出力:  

```
{
    "Cluster": {
        "ClusterName": "daxcluster",
        "ClusterArn": "arn:aws:dax:us-west-2:123456789012:cache/daxcluster",
        "TotalNodes": 3,
        "ActiveNodes": 3,
        "NodeType": "dax.r4.large",
        "Status": "modifying",
        "ClusterDiscoveryEndpoint": {
            "Address": "daxcluster.ey3o9d.clustercfg.dax.usw2.cache.amazonaws.com",
            "Port": 8111
        },
        "Nodes": [
            {
                "NodeId": "daxcluster-a",
                "Endpoint": {
                    "Address": "daxcluster-a.ey3o9d.0001.dax.usw2.cache.amazonaws.com",
                    "Port": 8111
                },
                "NodeCreateTime": 1576625059.509,
                "AvailabilityZone": "us-west-2c",
                "NodeStatus": "available",
                "ParameterGroupStatus": "in-sync"
            },
            {
                "NodeId": "daxcluster-b",
                "Endpoint": {
                    "Address": "daxcluster-b.ey3o9d.0001.dax.usw2.cache.amazonaws.com",
                    "Port": 8111
                },
                "NodeCreateTime": 1576625059.509,
                "AvailabilityZone": "us-west-2a",
                "NodeStatus": "available",
                "ParameterGroupStatus": "in-sync"
            },
            {
                "NodeId": "daxcluster-c",
                "Endpoint": {
                    "Address": "daxcluster-c.ey3o9d.0001.dax.usw2.cache.amazonaws.com",
                    "Port": 8111
                },
                "NodeCreateTime": 1576625059.509,
                "AvailabilityZone": "us-west-2b",
                "NodeStatus": "available",
                "ParameterGroupStatus": "in-sync"
            }
        ],
        "PreferredMaintenanceWindow": "thu:13:00-thu:14:00",
        "SubnetGroup": "default",
        "SecurityGroups": [
            {
                "SecurityGroupIdentifier": "sg-1af6e36e",
                "Status": "active"
            }
        ],
        "IamRoleArn": "arn:aws:iam::123456789012:role/DAXServiceRoleForDynamoDBAccess",
        "ParameterGroup": {
            "ParameterGroupName": "default.dax1.0",
            "ParameterApplyStatus": "in-sync",
            "NodeIdsToReboot": []
        },
        "SSEDescription": {
            "Status": "ENABLED"
        }
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html#DAX.cluster-management.custom-settings)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecreaseReplicationFactor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/decrease-replication-factor.html)」を参照してください。

### `delete-cluster`
<a name="dax_DeleteCluster_cli_2_topic"></a>

次のコード例は、`delete-cluster` を使用する方法を示しています。

**AWS CLI**  
**DAX クラスターを削除するには**  
次の `delete-cluster` の例では、指定された DAX クラスターを削除します。  

```
aws dax delete-cluster \
    --cluster-name daxcluster
```
出力:  

```
{
    "Cluster": {
        "ClusterName": "daxcluster",
        "ClusterArn": "arn:aws:dax:us-west-2:123456789012:cache/daxcluster",
        "TotalNodes": 3,
        "ActiveNodes": 0,
        "NodeType": "dax.r4.large",
        "Status": "deleting",
        "ClusterDiscoveryEndpoint": {
            "Address": "dd.ey3o9d.clustercfg.dax.usw2.cache.amazonaws.com",
            "Port": 8111
        },
        "PreferredMaintenanceWindow": "fri:06:00-fri:07:00",
        "SubnetGroup": "default",
        "SecurityGroups": [
            {
                "SecurityGroupIdentifier": "sg-1af6e36e",
                "Status": "active"
            }
        ],
        "IamRoleArn": "arn:aws:iam::123456789012:role/DAXServiceRoleForDynamoDBAccess",
        "ParameterGroup": {
            "ParameterGroupName": "default.dax1.0",
            "ParameterApplyStatus": "in-sync",
            "NodeIdsToReboot": []
        },
        "SSEDescription": {
            "Status": "ENABLED"
        }
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html#DAX.cluster-management.deleting)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/delete-cluster.html)」を参照してください。

### `delete-parameter-group`
<a name="dax_DeleteParameterGroup_cli_2_topic"></a>

次のコード例は、`delete-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループを削除するには**  
次の `delete-parameter-group` の例では、指定された DAX パラメータグループを削除します。  

```
aws dax  delete-parameter-group \
    --parameter-group-name daxparametergroup
```
出力:  

```
{
    "DeletionMessage": "Parameter group daxparametergroup has been deleted."
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/delete-parameter-group.html)」を参照してください。

### `delete-subnet-group`
<a name="dax_DeleteSubnetGroup_cli_2_topic"></a>

次のコード例は、`delete-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループを削除するには**  
次の `delete-subnet-group` の例は、指定された DAX サブネットグループを削除します。  

```
aws dax delete-subnet-group \
    --subnet-group-name daxSubnetGroup
```
出力:  

```
{
    "DeletionMessage": "Subnet group daxSubnetGroup has been deleted."
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/delete-subnet-group.html)」を参照してください。

### `describe-clusters`
<a name="dax_DescribeClusters_cli_2_topic"></a>

次のコード例は、`describe-clusters` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされた DAX クラスターに関する情報を返すには**  
次の `describe-clusters` の例では、プロビジョニングされたすべての DAX クラスターに関する詳細を表示します。  

```
aws dax describe-clusters
```
出力:  

```
{
    "Clusters": [
        {
            "ClusterName": "daxcluster",
            "ClusterArn": "arn:aws:dax:us-west-2:123456789012:cache/daxcluster",
            "TotalNodes": 1,
            "ActiveNodes": 1,
            "NodeType": "dax.r4.large",
            "Status": "available",
            "ClusterDiscoveryEndpoint": {
                "Address": "daxcluster.ey3o9d.clustercfg.dax.usw2.cache.amazonaws.com",
                "Port": 8111
            },
            "Nodes": [
                {
                    "NodeId": "daxcluster-a",
                    "Endpoint": {
                        "Address": "daxcluster-a.ey3o9d.0001.dax.usw2.cache.amazonaws.com",
                        "Port": 8111
                    },
                    "NodeCreateTime": 1576625059.509,
                    "AvailabilityZone": "us-west-2c",
                    "NodeStatus": "available",
                    "ParameterGroupStatus": "in-sync"
                }
            ],
            "PreferredMaintenanceWindow": "thu:13:00-thu:14:00",
            "SubnetGroup": "default",
            "SecurityGroups": [
                {
                    "SecurityGroupIdentifier": "sg-1af6e36e",
                    "Status": "active"
                }
            ],
            "IamRoleArn": "arn:aws:iam::123456789012:role/DAXServiceRoleForDynamoDBAccess",
            "ParameterGroup": {
                "ParameterGroupName": "default.dax1.0",
                "ParameterApplyStatus": "in-sync",
                "NodeIdsToReboot": []
            },
            "SSEDescription": {
                "Status": "ENABLED"
            }
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/describe-clusters.html)」を参照してください。

### `describe-default-parameters`
<a name="dax_DescribeDefaultParameters_cli_2_topic"></a>

次のコード例は、`describe-default-parameters` を使用する方法を示しています。

**AWS CLI**  
**DAX のデフォルトのシステムパラメータ情報を返すには**  
次の `describe-default-parameters` の例では、DAX のデフォルトのシステムパラメータ情報を表示します。  

```
aws dax describe-default-parameters
```
出力:  

```
{
    "Parameters": [
        {
            "ParameterName": "query-ttl-millis",
            "ParameterType": "DEFAULT",
            "ParameterValue": "300000",
            "NodeTypeSpecificValues": [],
            "Description": "Duration in milliseconds for queries to remain cached",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": "TRUE",
            "ChangeType": "IMMEDIATE"
        },
        {
            "ParameterName": "record-ttl-millis",
            "ParameterType": "DEFAULT",
            "ParameterValue": "300000",
            "NodeTypeSpecificValues": [],
            "Description": "Duration in milliseconds for records to remain valid in cache (Default: 0 = infinite)",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": "TRUE",
            "ChangeType": "IMMEDIATE"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDefaultParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/describe-default-parameters.html)」を参照してください。

### `describe-events`
<a name="dax_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
**DAX クラスターとパラメータグループに関連するイベントを返すには**  
次の `describe-events` の例では、DAX クラスターとパラメータグループに関連するイベントの詳細を表示します。  

```
aws dax describe-events
```
出力:  

```
{
    "Events": [
        {
            "SourceName": "daxcluster",
            "SourceType": "CLUSTER",
            "Message": "Cluster deleted.",
            "Date": 1576702736.706
        },
        {
            "SourceName": "daxcluster",
            "SourceType": "CLUSTER",
            "Message": "Removed node daxcluster-b.",
            "Date": 1576702691.738
        },
        {
            "SourceName": "daxcluster",
            "SourceType": "CLUSTER",
            "Message": "Removed node daxcluster-a.",
            "Date": 1576702633.498
        },
        {
            "SourceName": "daxcluster",
            "SourceType": "CLUSTER",
            "Message": "Removed node daxcluster-c.",
            "Date": 1576702631.329
        },
        {
            "SourceName": "daxcluster",
            "SourceType": "CLUSTER",
            "Message": "Cluster created.",
            "Date": 1576626560.057
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/describe-events.html)」を参照してください。

### `describe-parameter-groups`
<a name="dax_DescribeParameterGroups_cli_2_topic"></a>

次のコード例は、`describe-parameter-groups` を使用する方法を示しています。

**AWS CLI**  
**DAX で定義されたパラメータグループを記述するには**  
次の `describe-parameter-groups` の例では、DAX で定義されたパラメータグループに関する詳細を取得します。  

```
aws dax describe-parameter-groups
```
出力:  

```
{
    "ParameterGroups": [
        {
            "ParameterGroupName": "default.dax1.0",
            "Description": "Default parameter group for dax1.0"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeParameterGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/describe-parameter-groups.html)」を参照してください。

### `describe-parameters`
<a name="dax_DescribeParameters_cli_2_topic"></a>

次のコード例は、`describe-parameters` を使用する方法を示しています。

**AWS CLI**  
**DAX パラメータグループで定義されたパラメータを記述するには**  
次の `describe-parameters` の例では、指定された DAX パラメータグループで定義されているパラメータの詳細を取得します。  

```
aws dax describe-parameters \
    --parameter-group-name default.dax1.0
```
出力:  

```
{
    "Parameters": [
        {
            "ParameterName": "query-ttl-millis",
            "ParameterType": "DEFAULT",
            "ParameterValue": "300000",
            "NodeTypeSpecificValues": [],
            "Description": "Duration in milliseconds for queries to remain cached",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": "TRUE",
            "ChangeType": "IMMEDIATE"
        },
        {
            "ParameterName": "record-ttl-millis",
            "ParameterType": "DEFAULT",
            "ParameterValue": "300000",
            "NodeTypeSpecificValues": [],
            "Description": "Duration in milliseconds for records to remain valid in cache (Default: 0 = infinite)",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": "TRUE",
            "ChangeType": "IMMEDIATE"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/describe-parameters.html)」を参照してください。

### `describe-subnet-groups`
<a name="dax_DescribeSubnetGroups_cli_2_topic"></a>

次のコード例は、`describe-subnet-groups` を使用する方法を示しています。

**AWS CLI**  
**DAX で定義されたサブネットグループを記述するには**  
次の `describe-subnet-groups` の例では、DAX で定義されたサブネットグループの詳細を取得します。  

```
aws dax describe-subnet-groups
```
出力:  

```
{
    "SubnetGroups": [
        {
            "SubnetGroupName": "default",
            "Description": "Default CacheSubnetGroup",
            "VpcId": "vpc-ee70a196",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-874953af",
                    "SubnetAvailabilityZone": "us-west-2d"
                },
                {
                    "SubnetIdentifier": "subnet-bd3d1fc4",
                    "SubnetAvailabilityZone": "us-west-2a"
                },
                {
                    "SubnetIdentifier": "subnet-72c2ff28",
                    "SubnetAvailabilityZone": "us-west-2c"
                },
                {
                    "SubnetIdentifier": "subnet-09e6aa42",
                    "SubnetAvailabilityZone": "us-west-2b"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.concepts.cluster.html#DAX.concepts.cluster.security)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSubnetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/describe-subnet-groups.html)」を参照してください。

### `increase-replication-factor`
<a name="dax_IncreaseReplicationFactor_cli_2_topic"></a>

次のコード例は、`increase-replication-factor` を使用する方法を示しています。

**AWS CLI**  
**DAX クラスターのレプリケーション係数を増やすには**  
次の `increase-replication-factor` の例では、指定された DAX クラスターのレプリケーション係数を 3 に増やします。  

```
aws dax increase-replication-factor \
    --cluster-name daxcluster \
    --new-replication-factor 3
```
出力:  

```
{
    "Cluster": {
        "ClusterName": "daxcluster",
        "ClusterArn": "arn:aws:dax:us-west-2:123456789012:cache/daxcluster",
        "TotalNodes": 3,
        "ActiveNodes": 1,
        "NodeType": "dax.r4.large",
        "Status": "modifying",
        "ClusterDiscoveryEndpoint": {
            "Address": "daxcluster.ey3o9d.clustercfg.dax.usw2.cache.amazonaws.com",
            "Port": 8111
        },
        "Nodes": [
            {
                "NodeId": "daxcluster-a",
                "Endpoint": {
                    "Address": "daxcluster-a.ey3o9d.0001.dax.usw2.cache.amazonaws.com",
                    "Port": 8111
                },
                "NodeCreateTime": 1576625059.509,
                "AvailabilityZone": "us-west-2c",
                "NodeStatus": "available",
                "ParameterGroupStatus": "in-sync"
            },
            {
                "NodeId": "daxcluster-b",
                "NodeStatus": "creating"
            },
            {
                "NodeId": "daxcluster-c",
                "NodeStatus": "creating"
            }
        ],
        "PreferredMaintenanceWindow": "thu:13:00-thu:14:00",
        "SubnetGroup": "default",
        "SecurityGroups": [
            {
                "SecurityGroupIdentifier": "sg-1af6e36e",
                "Status": "active"
            }
        ],
        "IamRoleArn": "arn:aws:iam::123456789012:role/DAXServiceRoleForDynamoDBAccess",
        "ParameterGroup": {
            "ParameterGroupName": "default.dax1.0",
            "ParameterApplyStatus": "in-sync",
            "NodeIdsToReboot": []
        },
        "SSEDescription": {
            "Status": "ENABLED"
        }
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html#DAX.cluster-management.custom-settings)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IncreaseReplicationFactor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/increase-replication-factor.html)」を参照してください。

### `list-tags`
<a name="dax_ListTags_cli_2_topic"></a>

次のコード例は、`list-tags` を使用する方法を示しています。

**AWS CLI**  
**DAX リソースのタグを一覧表示するには**  
次の `list-tags` の例では、指定された DAX クラスターにアタッチされているタグキーと値を一覧表示します。  

```
aws dax list-tags \
    --resource-name arn:aws:dax:us-west-2:123456789012:cache/daxcluster
```
出力:  

```
{
    "Tags": [
        {
            "Key": "ClusterUsage",
            "Value": "prod"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html#DAX.management.tagging)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/list-tags.html)」を参照してください。

### `tag-resource`
<a name="dax_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**DAX リソースにタグを付けるには**  
次の `tag-resource` の例では、指定されたタグキー名と関連する値を、指定された DAX クラスターにアタッチして、クラスターの使用状況を記述します。  

```
aws dax tag-resource \
    --resource-name arn:aws:dax:us-west-2:123456789012:cache/daxcluster \
    --tags="Key=ClusterUsage,Value=prod"
```
出力:  

```
{
    "Tags": [
        {
            "Key": "ClusterUsage",
            "Value": "prod"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html#DAX.management.tagging)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="dax_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**DAX リソースからタグを削除するには**  
次の `untag-resource` の例では、指定されたキー名を持つタグを DAX クラスターから削除します。  

```
aws dax untag-resource  \
    --resource-name arn:aws:dax:us-west-2:123456789012:cache/daxcluster \
    --tag-keys="ClusterUsage"
```
出力:  

```
{
    "Tags": []
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DAX クラスターの管理](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.cluster-management.html#DAX.management.tagging)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dax/untag-resource.html)」を参照してください。

# を使用した検出の例 AWS CLI
<a name="cli_2_detective_code_examples"></a>

次のコード例は、Detective AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-invitation`
<a name="detective_AcceptInvitation_cli_2_topic"></a>

次のコード例は、`accept-invitation` を使用する方法を示しています。

**AWS CLI**  
**動作グラフのメンバーアカウントになるための招待を受け入れるには**  
次の `accept-invitation` の例では、動作グラフ arn:aws:detective:us-east-1:111122223333:graph:123412341234 のメンバーアカウントになるための招待を受け入れます。  

```
aws detective accept-invitation \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Detective Administration Guide*」の[「Responding to a behavior graph invitation](https://docs.aws.amazon.com/detective/latest/adminguide/member-invitation-response.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptInvitation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/accept-invitation.html)」を参照してください。

### `create-graph`
<a name="detective_CreateGraph_cli_2_topic"></a>

次のコード例は、`create-graph` を使用する方法を示しています。

**AWS CLI**  
**Amazon Detective を有効にして新しい動作グラフを作成するには**  
次の`create-graph`例では、コマンドが実行されるリージョンでコマンドを実行する AWS アカウントに対して Detective を有効にします。そのアカウントを管理者アカウントとする新しい動作グラフが作成されます。このコマンドは、部門タグに「財務」という値を割り当てます。  

```
aws detective create-graph \
    --tags '{"Department": "Finance"}'
```
出力:  

```
{
    "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:027c7c4610ea4aacaf0b883093cab899"
}
```
詳細については、「*Amazon Detective Administration Guide*」の「[Enabling Amazon Detective](https://docs.aws.amazon.com/detective/latest/adminguide/detective-enabling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGraph](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/create-graph.html)」を参照してください。

### `create-members`
<a name="detective_CreateMembers_cli_2_topic"></a>

次のコード例は、`create-members` を使用する方法を示しています。

**AWS CLI**  
**動作グラフにメンバーアカウントを招待するには**  
次の`create-members`例では、動作グラフ arn:aws:detective:us-east-1:111122223333:graph:123412341234 のメンバーアカウントに 2 つの AWS アカウントを招待します。アカウントごとに、リクエストは AWS アカウント ID とアカウントのルートユーザーの E メールアドレスを提供します。リクエストには、招待メールに挿入するカスタムメッセージが含まれています。  

```
aws detective create-members \
    --accounts AccountId=444455556666,EmailAddress=mmajor@example.com AccountId=123456789012,EmailAddress=jstiles@example.com \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234 \
    --message "This is Paul Santos. I need to add your account to the data we use for security investigation in Amazon Detective. If you have any questions, contact me at psantos@example.com."
```
出力:  

```
{
    "Members": [
    {
        "AccountId": "444455556666",
        "AdministratorId": "111122223333",
        "EmailAddress": "mmajor@example.com",
        "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
        "InvitedTime": 1579826107000,
        "MasterId": "111122223333",
        "Status": "INVITED",
        "UpdatedTime": 1579826107000
   },
   {
        "AccountId": "123456789012",
        "AdministratorId": "111122223333",
        "EmailAddress": "jstiles@example.com",
        "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
        "InvitedTime": 1579826107000,
        "MasterId": "111122223333",
        "Status": "VERIFICATION_IN_PROGRESS",
        "UpdatedTime": 1579826107000
     }
    ],
    "UnprocessedAccounts": [ ]
}
```
詳細については、「*Amazon Detective Administration Guide*」の「Inviting member accounts to a behavior graph<https://docs.aws.amazon.com/detective/latest/adminguide/graph-admin-add-member-accounts.html>」を参照してください。  
**招待メールを送信せずにメンバーアカウントを招待するには**  
次の`create-members`例では、動作グラフ arn:aws:detective:us-east-1:111122223333:graph:123412341234 のメンバーアカウントに 2 つの AWS アカウントを招待します。アカウントごとに、リクエストは AWS アカウント ID とアカウントのルートユーザーの E メールアドレスを提供します。メンバーアカウントには招待メールは届きません。  

```
aws detective create-members \
    --accounts AccountId=444455556666,EmailAddress=mmajor@example.com AccountId=123456789012,EmailAddress=jstiles@example.com \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234 \
    --disable-email-notification
```
出力:  

```
{
    "Members": [
    {
        "AccountId": "444455556666",
        "AdministratorId": "111122223333",
        "EmailAddress": "mmajor@example.com",
        "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
        "InvitedTime": 1579826107000,
        "MasterId": "111122223333",
        "Status": "INVITED",
        "UpdatedTime": 1579826107000
   },
   {
        "AccountId": "123456789012",
        "AdministratorId": "111122223333",
        "EmailAddress": "jstiles@example.com",
        "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
        "InvitedTime": 1579826107000,
        "MasterId": "111122223333",
        "Status": "VERIFICATION_IN_PROGRESS",
        "UpdatedTime": 1579826107000
     }
    ],
    "UnprocessedAccounts": [ ]
}
```
詳細については、「*Amazon Detective Administration Guide*」の「Inviting member accounts to a behavior graph<https://docs.aws.amazon.com/detective/latest/adminguide/graph-admin-add-member-accounts.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/create-members.html)」を参照してください。

### `delete-graph`
<a name="detective_DeleteGraph_cli_2_topic"></a>

次のコード例は、`delete-graph` を使用する方法を示しています。

**AWS CLI**  
**Detective を無効にして動作グラフを削除するには**  
次の `delete-graph` の例では、Detective を無効にし、指定された動作グラフを削除します。  

```
aws detective delete-graph \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Detective Administration Guide*」の「[Disabling Amazon Detective](https://docs.aws.amazon.com/detective/latest/adminguide/detective-disabling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGraph](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/delete-graph.html)」を参照してください。

### `delete-members`
<a name="detective_DeleteMembers_cli_2_topic"></a>

次のコード例は、`delete-members` を使用する方法を示しています。

**AWS CLI**  
**動作グラフからメンバーアカウントを削除するには**  
次の `delete-members` の例では、動作グラフ arn:aws:detective:us-east-1:111122223333:graph:123412341234 から 2 つのメンバーアカウントを削除します。アカウントを識別するために、リクエストは AWS アカウント IDsを提供します。  

```
aws detective delete-members \
    --account-ids 444455556666 123456789012 \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
出力:  

```
 {
    "AccountIds": [ "444455556666", "123456789012" ],
    "UnprocessedAccounts": [ ]
}
```
詳細については、「*Amazon Detective Administration Guide*」の「Removing member accounts from a behavior graph<https://docs.aws.amazon.com/detective/latest/adminguide/graph-admin-remove-member-accounts.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/delete-members.html)」を参照してください。

### `disassociate-membership`
<a name="detective_DisassociateMembership_cli_2_topic"></a>

次のコード例は、`disassociate-membership` を使用する方法を示しています。

**AWS CLI**  
**動作グラフのメンバーシップを辞退するには**  
次の関連付け解除メンバーの例では、動作グラフ arn:aws:detective:us-east-1:111122223333:graph:123412341234 からコマンドを実行する AWS アカウントを削除します。  

```
aws detective disassociate-membership \
     --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
詳細については、「*Amazon Detective Administration Guide*」の「Removing your account from a behavior graph<https://docs.aws.amazon.com/detective/latest/adminguide/member-remove-self-from-graph.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateMembership](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/disassociate-membership.html)」を参照してください。

### `get-members`
<a name="detective_GetMembers_cli_2_topic"></a>

次のコード例は、`get-members` を使用する方法を示しています。

**AWS CLI**  
**選択した動作グラフメンバーアカウントに関する情報を取得するには**  
次の `get-members` の例では、動作グラフ arn:aws:detective:us-east-1:111122223333:graph:123412341234 の 2 つのメンバーアカウントに関する情報を取得します。2 つのアカウントの場合、リクエストは AWS アカウント IDsを提供します。  

```
aws detective get-members \
    --account-ids 444455556666 123456789012 \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
出力:  

```
{
    "MemberDetails": [
    {
        "AccountId": "444455556666",
        "AdministratorId": "111122223333",
        "EmailAddress": "mmajor@example.com",
        "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
        "InvitedTime": 1579826107000,
        "MasterId": "111122223333",
        "Status": "INVITED",
        "UpdatedTime": 1579826107000
    }
    {
        "AccountId": "123456789012",
        "AdministratorId": "111122223333",
        "EmailAddress": "jstiles@example.com",
        "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
        "InvitedTime": 1579826107000,
        "MasterId": "111122223333",
        "Status": "INVITED",
        "UpdatedTime": 1579826107000
    }
],
    "UnprocessedAccounts": [ ]
}
```
詳細については、「*Amazon Detective Administration Guide*」の「Viewing the list of accounts in a behavior graph<https://docs.aws.amazon.com/detective/latest/adminguide/graph-admin-view-accounts.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/get-members.html)」を参照してください。

### `list-graphs`
<a name="detective_ListGraphs_cli_2_topic"></a>

次のコード例は、`list-graphs` を使用する方法を示しています。

**AWS CLI**  
**自身のアカウントが管理者になっている動作グラフのリストを表示するには**  
次の `list-graphs` の例は、呼び出し元アカウントが現在のリージョン内で管理者となっている動作グラフを取得します。  

```
aws detective list-graphs
```
出力:  

```
{
    "GraphList": [
        {
            "Arn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
            "CreatedTime": 1579736111000
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGraphs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/list-graphs.html)」を参照してください。

### `list-invitations`
<a name="detective_ListInvitations_cli_2_topic"></a>

次のコード例は、`list-invitations` を使用する方法を示しています。

**AWS CLI**  
**アカウントがメンバーであるか招待されている動作グラフのリストを表示するには**  
次の `list-invitations` の例では、呼び出し元アカウントが招待されている動作グラフを取得しています。結果には、未対応の招待と承諾済みの招待のみが表示されます。拒否した招待や削除されたメンバーシップは含まれません。  

```
aws detective list-invitations
```
出力:  

```
{
    "Invitations": [
    {
        "AccountId": "444455556666",
        "AdministratorId": "111122223333",
        "EmailAddress": "mmajor@example.com",
        "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
        "InvitedTime": 1579826107000,
        "MasterId": "111122223333",
        "Status": "INVITED",
        "UpdatedTime": 1579826107000
    }
]
}
```
詳細については、「*Amazon Detective Administration Guide*」の「Viewing your list of behavior graph invitations<https://docs.aws.amazon.com/detective/latest/adminguide/member-view-graph-invitations.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInvitations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/list-invitations.html)」を参照してください。

### `list-members`
<a name="detective_ListMembers_cli_2_topic"></a>

次のコード例は、`list-members` を使用する方法を示しています。

**AWS CLI**  
**動作グラフのメンバーアカウントを一覧表示するには**  
次の `list-members` の例では、動作グラフ `arn:aws:detective:us-east-1:111122223333:graph:123412341234` の招待された有効なメンバーアカウントを取得します。結果には、削除されたメンバーアカウントは含まれません。  

```
aws detective list-members \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
出力:  

```
{
    "MemberDetails": [
        {
            "AccountId": "444455556666",
            "AdministratorId": "111122223333",
            "EmailAddress": "mmajor@example.com",
            "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
            "InvitedTime": 1579826107000,
            "MasterId": "111122223333",
            "Status": "INVITED",
            "UpdatedTime": 1579826107000
        },
        {
            "AccountId": "123456789012",
            "AdministratorId": "111122223333",
            "EmailAddress": "jstiles@example.com",
            "GraphArn": "arn:aws:detective:us-east-1:111122223333:graph:123412341234",
            "InvitedTime": 1579826107000,
            "MasterId": "111122223333",
            "PercentOfGraphUtilization": 2,
            "PercentOfGraphUtilizationUpdatedTime": 1586287843,
            "Status": "ENABLED",
            "UpdatedTime": 1579973711000,
            "VolumeUsageInBytes": 200,
            "VolumeUsageUpdatedTime": 1586287843
        }
    ]
}
```
詳細については、「*Amazon Detective Administration Guide*」の「[Viewing the list of accounts in a behavior graph](https://docs.aws.amazon.com/detective/latest/adminguide/graph-admin-view-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/list-members.html)」を参照してください。

### `list-tags-for-resource`
<a name="detective_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**動作グラフに割り当てられたタグを取得するには**  
次の `list-tags-for-resource` の例では、指定された動作グラフに割り当てられたタグを返します。  

```
aws detective list-tags-for-resource \
    --resource-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
出力:  

```
{
    "Tags": {
        "Department" : "Finance"
    }
}
```
詳細については、「*Amazon Detective Administration Guide*」の「[Managing tags for a behavior graph](https://docs.aws.amazon.com/detective/latest/adminguide/graph-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/list-tags-for-resource.html)」を参照してください。

### `reject-invitation`
<a name="detective_RejectInvitation_cli_2_topic"></a>

次のコード例は、`reject-invitation` を使用する方法を示しています。

**AWS CLI**  
**動作グラフのメンバーアカウントになるための招待を拒否するには**  
次の `reject-invitation` の例では、動作グラフ arn:aws:detective:us-east-1:111122223333:graph:123412341234 のメンバーアカウントになるための招待を拒否します。  

```
aws detective reject-invitation \
    --graph-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Detective Administration Guide*」の「Responding to a behavior graph invitation<https://docs.aws.amazon.com/detective/latest/adminguide/member-invitation-response.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectInvitation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/reject-invitation.html)」を参照してください。

### `tag-resource`
<a name="detective_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを割り当てるには**  
次の `tag-resource` の例では、Department タグの値を指定された動作グラフに割り当てます。  

```
aws detective tag-resource \
    --resource-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234 \
    --tags '{"Department":"Finance"}'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Detective Administration Guide*」の「[Managing tags for a behavior graph](https://docs.aws.amazon.com/detective/latest/adminguide/graph-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="detective_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグ値を削除するには**  
次の `untag-resource` の例では、指定された動作グラフから Department タグを削除します。  

```
aws detective untag-resource \
    --resource-arn arn:aws:detective:us-east-1:111122223333:graph:123412341234 \
    --tag-keys "Department"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Detective Administration Guide*」の「[Managing tags for a behavior graph](https://docs.aws.amazon.com/detective/latest/adminguide/graph-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/detective/untag-resource.html)」を参照してください。

# を使用した Device Farm の例 AWS CLI
<a name="cli_2_device-farm_code_examples"></a>

次のコード例は、Device Farm AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-device-pool`
<a name="device-farm_CreateDevicePool_cli_2_topic"></a>

次のコード例は、`create-device-pool` を使用する方法を示しています。

**AWS CLI**  
**デバイスプールを作成するには**  
次のコマンドは、プロジェクトの Android デバイスプールを作成します。  

```
aws devicefarm create-device-pool --name pool1 --rules file://device-pool-rules.json --project-arn "arn:aws:devicefarm:us-west-2:123456789012:project:070fc3ca-7ec1-4741-9c1f-d3e044efc506"
```
プロジェクト ARN は、`create-project` または `list-projects` の出力から取得できます。この `device-pool-rules.json` ファイルは、デバイスのプラットフォームを指定する現在のフォルダ内の JSON ドキュメントです。  

```
[
    {
        "attribute": "PLATFORM",
        "operator": "EQUALS",
        "value": "\"ANDROID\""
    }
]
```
出力:  

```
{
    "devicePool": {
        "rules": [
            {
                "operator": "EQUALS",
                "attribute": "PLATFORM",
                "value": "\"ANDROID\""
            }
        ],
        "type": "PRIVATE",
        "name": "pool1",
        "arn": "arn:aws:devicefarm:us-west-2:123456789012:devicepool:070fc3ca-7ec1-4741-9c1f-d3e044efc506/2aa8d2a9-5e73-47ca-b929-659cb34b7dcd"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDevicePool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/devicefarm/create-device-pool.html)」を参照してください。

### `create-project`
<a name="device-farm_CreateProject_cli_2_topic"></a>

次のコード例は、`create-project` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトを作成するには**  
次のコマンドは、`my-project` という名前の新しいプロジェクトを作成します。  

```
aws devicefarm create-project --name my-project
```
出力:  

```
{
    "project": {
        "name": "myproject",
        "arn": "arn:aws:devicefarm:us-west-2:123456789012:project:070fc3ca-7ec1-4741-9c1f-d3e044efc506",
        "created": 1503612890.057
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/devicefarm/create-project.html)」を参照してください。**

### `create-upload`
<a name="device-farm_CreateUpload_cli_2_topic"></a>

次のコード例は、`create-upload` を使用する方法を示しています。

**AWS CLI**  
**アップロードを作成するには**  
次のコマンドは、Android アプリのアップロードを作成します。  

```
aws devicefarm create-upload --project-arn "arn:aws:devicefarm:us-west-2:123456789012:project:070fc3ca-7ec1-4741-9c1f-d3e044efc506" --name app.apk --type ANDROID_APP
```
プロジェクト ARN は、create-project または list-projects の出力から取得できます。  
出力:  

```
{
    "upload": {
        "status": "INITIALIZED",
        "name": "app.apk",
        "created": 1503614408.769,
        "url": "https://prod-us-west-2-uploads.s3-us-west-2.amazonaws.com/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A123456789012%3Aproject%3A070fc3ca-c7e1-4471-91cf-d3e4efc50604/uploads/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A123456789012%3Aupload%3A070fc3ca-7ec1-4741-9c1f-d3e044efc506/dd72723a-ae9e-4087-09e6-f4cea3599514/app.apk?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20170824T224008Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAEXAMPLEPBUMBC3GA%2F20170824%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=05050370c38894ef5bd09f5d009f36fc8f96fa4bb04e1bba9aca71b8dbe49a0f",
        "type": "ANDROID_APP",
        "arn": "arn:aws:devicefarm:us-west-2:123456789012:upload:070fc3ca-7ec1-4741-9c1f-d3e044efc506/dd72723a-ae9e-4087-09e6-f4cea3599514"
    }
}
```
出力内の署名付き URL を使用して、ファイルを Device Farm にアップロードします。  

```
curl -T app.apk "https://prod-us-west-2-uploads.s3-us-west-2.amazonaws.com/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A123456789012%3Aproject%3A070fc3ca-c7e1-4471-91cf-d3e4efc50604/uploads/arn%3Aaws%3Adevicefarm%3Aus-west-2%3A123456789012%3Aupload%3A070fc3ca-7ec1-4741-9c1f-d3e044efc506/dd72723a-ae9e-4087-09e6-f4cea3599514/app.apk?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20170824T224008Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAEXAMPLEPBUMBC3GA%2F20170824%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=05050370c38894ef5bd09f5d009f36fc8f96fa4bb04e1bba9aca71b8dbe49a0f"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*の「[CreateUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/devicefarm/create-upload.html)」を参照してください。

### `get-upload`
<a name="device-farm_GetUpload_cli_2_topic"></a>

次のコード例は、`get-upload` を使用する方法を示しています。

**AWS CLI**  
**アップロードを表示するには**  
次のコマンドは、アップロードに関する情報を取得します。  

```
aws devicefarm get-upload --arn "arn:aws:devicefarm:us-west-2:123456789012:upload:070fc3ca-7ec1-4741-9c1f-d3e044efc506/dd72723a-ae9e-4087-09e6-f4cea3599514"
```
アップロード ARN は、`create-upload` の出力から取得できます。  
出力:  

```
{
    "upload": {
        "status": "SUCCEEDED",
        "name": "app.apk",
        "created": 1505262773.186,
        "type": "ANDROID_APP",
        "arn": "arn:aws:devicefarm:us-west-2:123456789012:upload:070fc3ca-7ec1-4741-9c1f-d3e044efc506/dd72723a-ae9e-4087-09e6-f4cea3599514",
        "metadata": "{\"device_admin\":false,\"activity_name\":\"ccom.example.client.LauncherActivity\",\"version_name\":\"1.0.2.94\",\"screens\":[\"small\",\"normal\",\"large\",\"xlarge\"],\"error_type\":null,\"sdk_version\":\"16\",\"package_name\":\"com.example.client\",\"version_code\":\"20994\",\"native_code\":[\"armeabi-v7a\"],\"target_sdk_version\":\"25\"}"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/devicefarm/get-upload.html)」を参照してください。

### `list-projects`
<a name="device-farm_ListProjects_cli_2_topic"></a>

次のコード例は、`list-projects` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトを一覧表示するには**  
次のコマンドは、プロジェクトのリストを取得します。  

```
aws devicefarm list-projects
```
出力:  

```
{
    "projects": [
        {
            "name": "myproject",
            "arn": "arn:aws:devicefarm:us-west-2:123456789012:project:070fc3ca-7ec1-4741-9c1f-d3e044efc506",
            "created": 1503612890.057
        },
        {
            "name": "otherproject",
            "arn": "arn:aws:devicefarm:us-west-2:123456789012:project:a5f5b752-8098-49d1-86bf-5f7682c1c77e",
            "created": 1505257519.337
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/devicefarm/list-projects.html)」を参照してください。

# Direct Connect を使用した の例 AWS CLI
<a name="cli_2_direct-connect_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています Direct Connect。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-direct-connect-gateway-association-proposal`
<a name="direct-connect_AcceptDirectConnectGatewayAssociationProposal_cli_2_topic"></a>

次のコード例は、`accept-direct-connect-gateway-association-proposal` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイの関連付けの提案を承諾するには**  
以下の `accept-direct-connect-gateway-association-proposal` は指定された提案を承諾します。  

```
aws directconnect  accept-direct-connect-gateway-association-proposal \
    --direct-connect-gateway-id 11460968-4ac1-4fd3-bdb2-00599EXAMPLE \
    --proposal-id cb7f41cb-8128-43a5-93b1-dcaedEXAMPLE \
    --associated-gateway-owner-account 111122223333

{
    "directConnectGatewayAssociation": {
        "directConnectGatewayId": "11460968-4ac1-4fd3-bdb2-00599EXAMPLE",
        "directConnectGatewayOwnerAccount": "111122223333",
        "associationState": "associating",
        "associatedGateway": {
            "id": "tgw-02f776b1a7EXAMPLE",
            "type": "transitGateway",
            "ownerAccount": "111122223333",
            "region": "us-east-1"
        },
        "associationId": "6441f8bf-5917-4279-ade1-9708bEXAMPLE",
        "allowedPrefixesToDirectConnectGateway": [
            {
                "cidr": "192.168.1.0/30"
            }
        ]
    }
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Accepting or Rejecting a Transit Gateway Association Proposal](https://docs.aws.amazon.com/directconnect/latest/UserGuide/multi-account-associate-tgw.html#multi-account-tgw-accept-reject-proposal)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptDirectConnectGatewayAssociationProposal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/accept-direct-connect-gateway-association-proposal.html)」を参照してください。

### `allocate-connection-on-interconnect`
<a name="direct-connect_AllocateConnectionOnInterconnect_cli_2_topic"></a>

次のコード例は、`allocate-connection-on-interconnect` を使用する方法を示しています。

**AWS CLI**  
**相互接続上にホスト接続を作成するには**  
次の `allocate-connection-on-interconnect` コマンドは、相互接続上にホスト接続を作成します。  

```
aws directconnect allocate-connection-on-interconnect --bandwidth 500Mbps --connection-name mydcinterconnect --owner-account 123456789012 --interconnect-id dxcon-fgktov66 --vlan 101
```
出力:  

```
{
    "partnerName": "TIVIT",
    "vlan": 101,
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-ffzc51m1",
    "connectionState": "ordering",
    "bandwidth": "500Mbps",
    "location": "TIVIT",
    "connectionName": "mydcinterconnect",
    "region": "sa-east-1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateConnectionOnInterconnect](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/allocate-connection-on-interconnect.html)」を参照してください。

### `allocate-hosted-connection`
<a name="direct-connect_AllocateHostedConnection_cli_2_topic"></a>

次のコード例は、`allocate-hosted-connection` を使用する方法を示しています。

**AWS CLI**  
**相互接続上にホスト接続を作成するには**  
次の `allocate-hosted-connection` の例では、指定された相互接続上にホスト接続を作成します。  

```
aws directconnect allocate-hosted-connection \
    --bandwidth 500Mbps \
    --connection-name mydcinterconnect \
    --owner-account 123456789012
    -connection-id dxcon-fgktov66
    -vlan 101
```
出力:  

```
{
    "partnerName": "TIVIT",
    "vlan": 101,
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-ffzc51m1",
    "connectionState": "ordering",
    "bandwidth": "500Mbps",
    "location": "TIVIT",
    "connectionName": "mydcinterconnect",
    "region": "sa-east-1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateHostedConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/allocate-hosted-connection.html)」を参照してください。

### `allocate-private-virtual-interface`
<a name="direct-connect_AllocatePrivateVirtualInterface_cli_2_topic"></a>

次のコード例は、`allocate-private-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**プライベート仮想インターフェイスをプロビジョニングするには**  
次の `allocate-private-virtual-interface` コマンドは、別の顧客が所有できるようにプライベート仮想インターフェイスをプロビジョニングします。  

```
aws directconnect allocate-private-virtual-interface --connection-id dxcon-ffjrkx17 --owner-account 123456789012 --new-private-virtual-interface-allocation virtualInterfaceName=PrivateVirtualInterface,vlan=1000,asn=65000,authKey=asdf34example,amazonAddress=192.168.1.1/30,customerAddress=192.168.1.2/30
```
出力:  

```
{
    "virtualInterfaceState": "confirming",
    "asn": 65000,
    "vlan": 1000,
    "customerAddress": "192.168.1.2/30",
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-ffjrkx17",
    "virtualInterfaceId": "dxvif-fgy8orxu",
    "authKey": "asdf34example",
    "routeFilterPrefixes": [],
    "location": "TIVIT",
    "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n  <logical_connection id=\"dxvif-fgy8orxu\">\n  <vlan>1000</vlan>\n  <customer_address>192.168.1.2/30</customer_address>\n  <amazon_address>192.168.1.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>asdf34example</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>private</connection_type>\n</logical_connection>\n",
    "amazonAddress": "192.168.1.1/30",
    "virtualInterfaceType": "private",
    "virtualInterfaceName": "PrivateVirtualInterface"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocatePrivateVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/allocate-private-virtual-interface.html)」を参照してください。

### `allocate-public-virtual-interface`
<a name="direct-connect_AllocatePublicVirtualInterface_cli_2_topic"></a>

次のコード例は、`allocate-public-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**パブリック仮想インターフェイスをプロビジョニングするには**  
次の `allocate-public-virtual-interface` コマンドは、別の顧客が所有できるようにパブリック仮想インターフェイスをプロビジョニングします。  

```
aws directconnect allocate-public-virtual-interface --connection-id dxcon-ffjrkx17 --owner-account 123456789012 --new-public-virtual-interface-allocation virtualInterfaceName=PublicVirtualInterface,vlan=2000,asn=65000,authKey=asdf34example,amazonAddress=203.0.113.1/30,customerAddress=203.0.113.2/30,routeFilterPrefixes=[{cidr=203.0.113.0/30},{cidr=203.0.113.4/30}]
```
出力:  

```
{
    "virtualInterfaceState": "confirming",
    "asn": 65000,
    "vlan": 2000,
    "customerAddress": "203.0.113.2/30",
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-ffjrkx17",
    "virtualInterfaceId": "dxvif-fg9xo9vp",
    "authKey": "asdf34example",
    "routeFilterPrefixes": [
        {
            "cidr": "203.0.113.0/30"
        },
        {
            "cidr": "203.0.113.4/30"
        }
    ],
    "location": "TIVIT",
    "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fg9xo9vp\">\n  <vlan>2000</vlan>\n  <customer_address>203.0.113.2/30</customer_address>\n  <amazon_address>203.0.113.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>asdf34example</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>public</connection_type>\n</logical_connection>\n",
    "amazonAddress": "203.0.113.1/30",
    "virtualInterfaceType": "public",
    "virtualInterfaceName": "PublicVirtualInterface"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocatePublicVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/allocate-public-virtual-interface.html)」を参照してください。

### `allocate-transit-virtual-interface`
<a name="direct-connect_AllocateTransitVirtualInterface_cli_2_topic"></a>

次の例は、`allocate-transit-virtual-interface` を使用する方法を説明しています。

**AWS CLI**  
**指定された AWS アカウントが所有するトランジット仮想インターフェイスをプロビジョニングするには**  
次の `allocate-transit-virtual-interface` の例では、指定されたアカウントのトランジット仮想インターフェイスをプロビジョニングします。  

```
aws directconnect allocate-transit-virtual-interface \
    --connection-id dxlag-fEXAMPLE \
    --owner-account 123456789012 \
    --new-transit-virtual-interface-allocation "virtualInterfaceName=Example Transit Virtual Interface,vlan=126,asn=65110,mtu=1500,authKey=0xzxgA9YoW9h58u8SEXAMPLE,amazonAddress=192.168.1.1/30,customerAddress=192.168.1.2/30,addressFamily=ipv4,tags=[{key=Tag,value=Example}]"
```
出力:  

```
{
    "virtualInterface": {
        "ownerAccount": "123456789012",
        "virtualInterfaceId": "dxvif-fEXAMPLE",
        "location": "loc1",
        "connectionId": "dxlag-fEXAMPLE",
        "virtualInterfaceType": "transit",
        "virtualInterfaceName": "Example Transit Virtual Interface",
        "vlan": 126,
        "asn": 65110,
        "amazonSideAsn": 7224,
        "authKey": "0xzxgA9YoW9h58u8SEXAMPLE",
        "amazonAddress": "192.168.1.1/30",
        "customerAddress": "192.168.1.2/30",
        "addressFamily": "ipv4",
        "virtualInterfaceState": "confirming",
        "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fEXAMPLE\">\n  <vlan>126</vlan>\n  <customer_address>192.168.1.2/30</customer_address>\n  <amazon_address>192.168.1.1/30</amazon_address>\n  <bgp_asn>65110</bgp_asn>\n  <bgp_auth_key>0xzxgA9YoW9h58u8SEXAMPLE</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>transit</connection_type>\n</logical_connection>\n",
        "mtu": 1500,
        "jumboFrameCapable": true,
        "virtualGatewayId": "",
        "directConnectGatewayId": "",
        "routeFilterPrefixes": [],
        "bgpPeers": [
            {
                "bgpPeerId": "dxpeer-fEXAMPLE",
                "asn": 65110,
                "authKey": "0xzxgA9YoW9h58u8EXAMPLE",
                "addressFamily": "ipv4",
                "amazonAddress": "192.168.1.1/30",
                "customerAddress": "192.168.1.2/30",
                "bgpPeerState": "pending",
                "bgpStatus": "down",
                "awsDeviceV2": "loc1-26wz6vEXAMPLE"
            }
        ],
        "region": "sa-east-1",
        "awsDeviceV2": "loc1-26wz6vEXAMPLE",
        "tags": [
            {
                "key": "Tag",
                "value": "Example"
            }
        ]
    }
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Creating a Hosted Transit Virtual Interface](https://docs.aws.amazon.com/directconnect/latest/UserGuide/createhostedvirtualinterface.html#create-hosted-transit-vif)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateTransitVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/allocate-transit-virtual-interface.html)」を参照してください。

### `associate-connection-with-lag`
<a name="direct-connect_AssociateConnectionWithLag_cli_2_topic"></a>

次のコード例は、`associate-connection-with-lag` を使用する方法を示しています。

**AWS CLI**  
**接続を LAG と関連付けるには**  
次の例では、指定した接続を指定した LAG と関連付けます。  
コマンド:  

```
aws directconnect associate-connection-with-lag --lag-id dxlag-fhccu14t --connection-id dxcon-fg9607vm
```
出力:  

```
{
  "ownerAccount": "123456789012",
  "connectionId": "dxcon-fg9607vm",
  "lagId": "dxlag-fhccu14t",
  "connectionState": "requested",
  "bandwidth": "1Gbps",
  "location": "EqDC2",
  "connectionName": "Con2ForLag",
  "region": "us-east-1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateConnectionWithLag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/associate-connection-with-lag.html)」を参照してください。

### `associate-hosted-connection`
<a name="direct-connect_AssociateHostedConnection_cli_2_topic"></a>

次のコード例は、`associate-hosted-connection` を使用する方法を示しています。

**AWS CLI**  
**ホスト接続を LAG と関連付けるには**  
次の例では、指定したホスト接続を指定した LAG と関連付けます。  
コマンド:  

```
aws directconnect associate-hosted-connection --parent-connection-id dxlag-fhccu14t --connection-id dxcon-fg9607vm
```
出力:  

```
{
  "partnerName": "TIVIT",
  "vlan": 101,
  "ownerAccount": "123456789012",
  "connectionId": "dxcon-fg9607vm",
  "lagId": "dxlag-fhccu14t",
  "connectionState": "ordering",
  "bandwidth": "500Mbps",
  "location": "TIVIT",
  "connectionName": "mydcinterconnect",
  "region": "sa-east-1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateHostedConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/associate-hosted-connection.html)」を参照してください。

### `associate-virtual-interface`
<a name="direct-connect_AssociateVirtualInterface_cli_2_topic"></a>

次のコード例は、`associate-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**仮想インターフェイスを接続と関連付けるには**  
次の例では、指定した仮想インターフェイスを指定した LAG と関連付けます。または、仮想インターフェイスを接続に関連付けるには、 の AWS Direct Connect 接続の ID を指定します`--connection-id`。たとえば、 です`dxcon-ffnikghc`。  
コマンド:  

```
aws directconnect associate-virtual-interface --connection-id dxlag-ffjhj9lx --virtual-interface-id dxvif-fgputw0j
```
出力:  

```
{
  "virtualInterfaceState": "pending",
  "asn": 65000,
  "vlan": 123,
  "customerAddress": "169.254.255.2/30",
  "ownerAccount": "123456789012",
  "connectionId": "dxlag-ffjhj9lx",
  "addressFamily": "ipv4",
  "virtualGatewayId": "vgw-38e90b51",
  "virtualInterfaceId": "dxvif-fgputw0j",
  "authKey": "0x123pK5_VBqv.UQ3kJ4123_",
  "routeFilterPrefixes": [],
  "location": "CSVA1",
  "bgpPeers": [
      {
          "bgpStatus": "down",
          "customerAddress": "169.254.255.2/30",
          "addressFamily": "ipv4",
          "authKey": "0x123pK5_VBqv.UQ3kJ4123_",
          "bgpPeerState": "deleting",
          "amazonAddress": "169.254.255.1/30",
          "asn": 65000
      },
      {
          "bgpStatus": "down",
          "customerAddress": "169.254.255.2/30",
          "addressFamily": "ipv4",
          "authKey": "0x123pK5_VBqv.UQ3kJ4123_",
          "bgpPeerState": "pending",
          "amazonAddress": "169.254.255.1/30",
          "asn": 65000
      }
  ],
  "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fgputw0j\">\n  <vlan>123</vlan>\n  <customer_address>169.254.255.2/30</customer_address>\n  <amazon_address>169.254.255.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>0x123pK5_VBqv.UQ3kJ4123_</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>private</connection_type>\n</logical_connection>\n",
  "amazonAddress": "169.254.255.1/30",
  "virtualInterfaceType": "private",
  "virtualInterfaceName": "VIF1A"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/associate-virtual-interface.html)」を参照してください。

### `confirm-connection`
<a name="direct-connect_ConfirmConnection_cli_2_topic"></a>

次のコード例は、`confirm-connection` を使用する方法を示しています。

**AWS CLI**  
**相互接続上にホスト接続が作成されていることを確認するには**  
次の `confirm-connection` コマンドは、相互接続上にホスト接続が作成されていることを確認します。  

```
aws directconnect confirm-connection --connection-id dxcon-fg2wi7hy
```
出力:  

```
{
    "connectionState": "pending"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/confirm-connection.html)」を参照してください。

### `confirm-private-virtual-interface`
<a name="direct-connect_ConfirmPrivateVirtualInterface_cli_2_topic"></a>

次のコード例は、`confirm-private-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**プライベート仮想インターフェイスの所有権を承諾するには**  
次の `confirm-private-virtual-interface` コマンドは、別の顧客が作成したプライベート仮想インターフェイスの所有権を承諾します。  

```
aws directconnect confirm-private-virtual-interface --virtual-interface-id dxvif-fgy8orxu --virtual-gateway-id vgw-e4a47df9
```
出力:  

```
{
    "virtualInterfaceState": "pending"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmPrivateVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/confirm-private-virtual-interface.html)」を参照してください。

### `confirm-public-virtual-interface`
<a name="direct-connect_ConfirmPublicVirtualInterface_cli_2_topic"></a>

次のコード例は、`confirm-public-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**パブリック仮想インターフェイスの所有権を承諾するには**  
次の `confirm-public-virtual-interface` コマンドは、別の顧客が作成したパブリック仮想インターフェイスの所有権を承諾します。  

```
aws directconnect confirm-public-virtual-interface --virtual-interface-id dxvif-fg9xo9vp
```
出力:  

```
{
    "virtualInterfaceState": "verifying"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmPublicVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/confirm-public-virtual-interface.html)」を参照してください。

### `confirm-transit-virtual-interface`
<a name="direct-connect_ConfirmTransitVirtualInterface_cli_2_topic"></a>

次のコード例は、`confirm-transit-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**トランジット仮想インターフェイスの所有権を承諾するには**  
次の `confirm-transit-virtual-interface` コマンドは、別の顧客が作成したトランジット仮想インターフェイスの所有権を承諾します。  

```
aws directconnect confirm-transit-virtual-interface \
    --virtual-interface-id dxvif-fEXAMPLE \
    --direct-connect-gateway-id 4112ccf9-25e9-4111-8237-b6c5dEXAMPLE
```
出力:  

```
{
    "virtualInterfaceState": "pending"
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Accepting a Hosted Virtual Interface](https://docs.aws.amazon.com/directconnect/latest/UserGuide/accepthostedvirtualinterface.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmTransitVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/confirm-transit-virtual-interface.html)」を参照してください。

### `create-bgp-peer`
<a name="direct-connect_CreateBgpPeer_cli_2_topic"></a>

次のコード例は、`create-bgp-peer` を使用する方法を示しています。

**AWS CLI**  
**IPv6 BGP ピアリングセッションを作成するには**  
次の例では、プライベート仮想インターフェイス `dxvif-fg1vuj3d` に IPv6 BGP ピアリングセッションを作成します。ピア IPv6 アドレスは Amazon によって自動的に割り当てられます。  
コマンド:  

```
aws directconnect create-bgp-peer --virtual-interface-id dxvif-fg1vuj3d --new-bgp-peer asn=64600,addressFamily=ipv6
```
出力:  

```
{
  "virtualInterface": {
      "virtualInterfaceState": "available",
      "asn": 65000,
      "vlan": 125,
      "customerAddress": "169.254.255.2/30",
      "ownerAccount": "123456789012",
      "connectionId": "dxcon-fguhmqlc",
      "addressFamily": "ipv4",
      "virtualGatewayId": "vgw-f9eb0c90",
      "virtualInterfaceId": "dxvif-fg1vuj3d",
      "authKey": "0xC_ukbCerl6EYA0example",
      "routeFilterPrefixes": [],
      "location": "EqDC2",
      "bgpPeers": [
          {
              "bgpStatus": "down",
              "customerAddress": "169.254.255.2/30",
              "addressFamily": "ipv4",
              "authKey": "0xC_ukbCerl6EYA0uexample",
              "bgpPeerState": "available",
              "amazonAddress": "169.254.255.1/30",
              "asn": 65000
          },
          {
              "bgpStatus": "down",
              "customerAddress": "2001:db8:1100:2f0:0:1:9cb4:4216/125",
              "addressFamily": "ipv6",
              "authKey": "0xS27kAIU_VHPjjAexample",
              "bgpPeerState": "pending",
              "amazonAddress": "2001:db8:1100:2f0:0:1:9cb4:4211/125",
              "asn": 64600
          }
      ],
      "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fg1vuj3d\">\n  <vlan>125</vlan>\n  <customer_address>169.254.255.2/30</customer_address>\n  <amazon_address>169.254.255.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>0xC_ukbCerl6EYA0uexample</bgp_auth_key>\n  <ipv6_customer_address>2001:db8:1100:2f0:0:1:9cb4:4216/125</ipv6_customer_address>\n  <ipv6_amazon_address>2001:db8:1100:2f0:0:1:9cb4:4211/125</ipv6_amazon_address>\n  <ipv6_bgp_asn>64600</ipv6_bgp_asn>\n  <ipv6_bgp_auth_key>0xS27kAIU_VHPjjAexample</ipv6_bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>private</connection_type>\n</logical_connection>\n",
      "amazonAddress": "169.254.255.1/30",
      "virtualInterfaceType": "private",
      "virtualInterfaceName": "Test"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBgpPeer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-bgp-peer.html)」を参照してください。

### `create-connection`
<a name="direct-connect_CreateConnection_cli_2_topic"></a>

次の例は、`create-connection` を使用する方法を説明しています。

**AWS CLI**  
**ネットワークから AWS Direct Connect ロケーションへの接続を作成するには**  
次の`create-connection`コマンドは、ネットワークから AWS Direct Connect ロケーションへの接続を作成します。  

```
aws directconnect create-connection --location TIVIT --bandwidth 1Gbps --connection-name "Connection to AWS"
```
出力:  

```
{
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-fg31dyv6",
    "connectionState": "requested",
    "bandwidth": "1Gbps",
    "location": "TIVIT",
    "connectionName": "Connection to AWS",
    "region": "sa-east-1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-connection.html)」を参照してください。

### `create-direct-connect-gateway-association-proposal`
<a name="direct-connect_CreateDirectConnectGatewayAssociationProposal_cli_2_topic"></a>

次のコード例は、`create-direct-connect-gateway-association-proposal` を使用する方法を示しています。

**AWS CLI**  
**指定した Transit Gateway を、指定した Direct Connect ゲートウェイと関連付けるための提案を作成するには**  
次の `create-direct-connect-gateway-association-proposal` では、指定した Transit Gateway を、指定した Direct Connect ゲートウェイと関連付けるための提案を作成します。  

```
aws directconnect create-direct-connect-gateway-association-proposal \
    --direct-connect-gateway-id 11460968-4ac1-4fd3-bdb2-00599EXAMPLE \
    --direct-connect-gateway-owner-account 111122223333 \
    --gateway-id tgw-02f776b1a7EXAMPLE \
    --add-allowed-prefixes-to-direct-connect-gateway cidr=192.168.1.0/30
```
出力:  

```
{
    "directConnectGatewayAssociationProposal": {
        "proposalId": "cb7f41cb-8128-43a5-93b1-dcaedEXAMPLE",
        "directConnectGatewayId": "11460968-4ac1-4fd3-bdb2-00599EXAMPLE",
        "directConnectGatewayOwnerAccount": "111122223333",
        "proposalState": "requested",
        "associatedGateway": {
            "id": "tgw-02f776b1a7EXAMPLE",
            "type": "transitGateway",
            "ownerAccount": "111122223333",
            "region": "us-east-1"
        },
        "requestedAllowedPrefixesToDirectConnectGateway": [
            {
                "cidr": "192.168.1.0/30"
            }
        ]
    }
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Creating a Transit Gateway Association Proposal](https://docs.aws.amazon.com/directconnect/latest/UserGuide/multi-account-associate-tgw.html#multi-account-tgw-create-proposal)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDirectConnectGatewayAssociationProposal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-direct-connect-gateway-association-proposal.html)」を参照してください。

### `create-direct-connect-gateway-association`
<a name="direct-connect_CreateDirectConnectGatewayAssociation_cli_2_topic"></a>

次のコード例は、`create-direct-connect-gateway-association` を使用する方法を示しています。

**AWS CLI**  
**仮想プライベートインターフェイスを Direct Connect ゲートウェイと関連付けるには**  
次の例では、仮想プライベートゲートウェイ `vgw-6efe725e` を Direct Connect ゲートウェイ `5f294f92-bafb-4011-916d-9b0bexample` と関連付けます。仮想プライベートゲートウェイがあるリージョンで、コマンドを実行する必要があります。  
コマンド:  

```
aws directconnect create-direct-connect-gateway-association --direct-connect-gateway-id 5f294f92-bafb-4011-916d-9b0bexample --virtual-gateway-id vgw-6efe725e
```
出力:  

```
{
  "directConnectGatewayAssociation": {
      "associationState": "associating",
      "virtualGatewayOwnerAccount": "123456789012",
      "directConnectGatewayId": "5f294f92-bafb-4011-916d-9b0bexample",
      "virtualGatewayId": "vgw-6efe725e",
      "virtualGatewayRegion": "us-east-2"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDirectConnectGatewayAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-direct-connect-gateway-association.html)」を参照してください。

### `create-direct-connect-gateway`
<a name="direct-connect_CreateDirectConnectGateway_cli_2_topic"></a>

次のコード例は、`create-direct-connect-gateway` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイを作成するには**  
次の例では、`DxGateway1` という名前の Direct Connect ゲートウェイを作成します。  
コマンド:  

```
aws directconnect create-direct-connect-gateway --direct-connect-gateway-name "DxGateway1"
```
出力:  

```
{
  "directConnectGateway": {
      "amazonSideAsn": 64512,
      "directConnectGatewayId": "5f294f92-bafb-4011-916d-9b0bdexample",
      "ownerAccount": "123456789012",
      "directConnectGatewayName": "DxGateway1",
      "directConnectGatewayState": "available"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDirectConnectGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-direct-connect-gateway.html)」を参照してください。

### `create-interconnect`
<a name="direct-connect_CreateInterconnect_cli_2_topic"></a>

次の例は、`create-interconnect` を使用する方法を説明しています。

**AWS CLI**  
**パートナーのネットワークと の間に相互接続を作成するには AWS**  
次の`create-interconnect`コマンドは、 AWS Direct Connect パートナーのネットワークと特定の AWS Direct Connect ロケーションの間に相互接続を作成します。  

```
aws directconnect create-interconnect --interconnect-name "1G Interconnect to AWS" --bandwidth 1Gbps --location TIVIT
```
出力:  

```
{
    "region": "sa-east-1",
    "bandwidth": "1Gbps",
    "location": "TIVIT",
    "interconnectName": "1G Interconnect to AWS",
    "interconnectId": "dxcon-fgktov66",
    "interconnectState": "requested"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInterconnect](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-interconnect.html)」を参照してください。

### `create-lag`
<a name="direct-connect_CreateLag_cli_2_topic"></a>

次のコード例は、`create-lag` を使用する方法を示しています。

**AWS CLI**  
**新しい接続で LAG を作成するには**  
次の例では、LAG を作成し、1 Gbps の帯域幅で LAG に 2 つの新しい AWS Direct Connect 接続をリクエストします。  
コマンド:  

```
aws directconnect create-lag --location CSVA1 --number-of-connections 2 --connections-bandwidth 1Gbps --lag-name 1GBLag
```
出力:  

```
{
  "awsDevice": "CSVA1-23u8tlpaz8iks",
  "numberOfConnections": 2,
  "lagState": "pending",
  "ownerAccount": "123456789012",
  "lagName": "1GBLag",
  "connections": [
      {
          "ownerAccount": "123456789012",
          "connectionId": "dxcon-ffqr6x5q",
          "lagId": "dxlag-ffjhj9lx",
          "connectionState": "requested",
          "bandwidth": "1Gbps",
          "location": "CSVA1",
          "connectionName": "Requested Connection 1 for Lag dxlag-ffjhj9lx",
          "region": "us-east-1"
      },
      {
          "ownerAccount": "123456789012",
          "connectionId": "dxcon-fflqyj95",
          "lagId": "dxlag-ffjhj9lx",
          "connectionState": "requested",
          "bandwidth": "1Gbps",
          "location": "CSVA1",
          "connectionName": "Requested Connection 2 for Lag dxlag-ffjhj9lx",
          "region": "us-east-1"
      }
  ],
  "lagId": "dxlag-ffjhj9lx",
  "minimumLinks": 0,
  "connectionsBandwidth": "1Gbps",
  "region": "us-east-1",
  "location": "CSVA1"
}
```
**既存の接続を使用して LAG を作成するには**  
次の例では、アカウント内の既存の接続から LAG を作成し、既存の接続と同じ帯域幅とロケーションを持つ 2 番目の新しい接続を LAG 用にリクエストします。  
コマンド:  

```
aws directconnect create-lag --location EqDC2 --number-of-connections 2 --connections-bandwidth 1Gbps --lag-name 2ConnLAG --connection-id dxcon-fgk145dr
```
出力:  

```
{
  "awsDevice": "EqDC2-4h6ce2r1bes6",
  "numberOfConnections": 2,
  "lagState": "pending",
  "ownerAccount": "123456789012",
  "lagName": "2ConnLAG",
  "connections": [
      {
          "ownerAccount": "123456789012",
          "connectionId": "dxcon-fh6ljcvo",
          "lagId": "dxlag-fhccu14t",
          "connectionState": "requested",
          "bandwidth": "1Gbps",
          "location": "EqDC2",
          "connectionName": "Requested Connection 1 for Lag dxlag-fhccu14t",
          "region": "us-east-1"
      },
      {
          "ownerAccount": "123456789012",
          "connectionId": "dxcon-fgk145dr",
          "lagId": "dxlag-fhccu14t",
          "connectionState": "down",
          "bandwidth": "1Gbps",
          "location": "EqDC2",
          "connectionName": "VAConn1",
          "region": "us-east-1"
      }
  ],
  "lagId": "dxlag-fhccu14t",
  "minimumLinks": 0,
  "connectionsBandwidth": "1Gbps",
  "region": "us-east-1",
  "location": "EqDC2"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-lag.html)」を参照してください。

### `create-private-virtual-interface`
<a name="direct-connect_CreatePrivateVirtualInterface_cli_2_topic"></a>

次のコード例は、`create-private-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**プライベート仮想インターフェイスを作成するには**  
次の `create-private-virtual-interface` コマンドは、プライベート仮想インターフェイスを作成します。  

```
aws directconnect create-private-virtual-interface --connection-id dxcon-ffjrkx17 --new-private-virtual-interface virtualInterfaceName=PrivateVirtualInterface,vlan=101,asn=65000,authKey=asdf34example,amazonAddress=192.168.1.1/30,customerAddress=192.168.1.2/30,virtualGatewayId=vgw-aba37db6
```
出力:  

```
{
    "virtualInterfaceState": "pending",
    "asn": 65000,
    "vlan": 101,
    "customerAddress": "192.168.1.2/30",
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-ffjrkx17",
    "virtualGatewayId": "vgw-aba37db6",
    "virtualInterfaceId": "dxvif-ffhhk74f",
    "authKey": "asdf34example",
    "routeFilterPrefixes": [],
    "location": "TIVIT",
    "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-ffhhk74f\">\n  <vlan>101</vlan>\n  <customer_address>192.168.1.2/30</customer_address>\n  <amazon_address>192.168.1.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>asdf34example</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>private</connection_type>\n</logical_connection>\n",
    "amazonAddress": "192.168.1.1/30",
    "virtualInterfaceType": "private",
    "virtualInterfaceName": "PrivateVirtualInterface"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePrivateVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-private-virtual-interface.html)」を参照してください。

### `create-public-virtual-interface`
<a name="direct-connect_CreatePublicVirtualInterface_cli_2_topic"></a>

次のコード例は、`create-public-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**パブリック仮想インターフェイスを作成するには**  
次の `create-public-virtual-interface` コマンドは、パブリック仮想インターフェイスを作成します。  

```
aws directconnect create-public-virtual-interface --connection-id dxcon-ffjrkx17 --new-public-virtual-interface virtualInterfaceName=PublicVirtualInterface,vlan=2000,asn=65000,authKey=asdf34example,amazonAddress=203.0.113.1/30,customerAddress=203.0.113.2/30,routeFilterPrefixes=[{cidr=203.0.113.0/30},{cidr=203.0.113.4/30}]
```
出力:  

```
{
    "virtualInterfaceState": "verifying",
    "asn": 65000,
    "vlan": 2000,
    "customerAddress": "203.0.113.2/30",
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-ffjrkx17",
    "virtualInterfaceId": "dxvif-fgh0hcrk",
    "authKey": "asdf34example",
    "routeFilterPrefixes": [
        {
            "cidr": "203.0.113.0/30"
        },
        {
            "cidr": "203.0.113.4/30"
        }
    ],
    "location": "TIVIT",
    "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fgh0hcrk\">\n  <vlan>2000</vlan>\n  <customer_address>203.0.113.2/30</customer_address>\n  <amazon_address>203.0.113.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>asdf34example</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>public</connection_type>\n</logical_connection>\n",
    "amazonAddress": "203.0.113.1/30",
    "virtualInterfaceType": "public",
    "virtualInterfaceName": "PublicVirtualInterface"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePublicVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-public-virtual-interface.html)」を参照してください。

### `create-transit-virtual-interface`
<a name="direct-connect_CreateTransitVirtualInterface_cli_2_topic"></a>

次のコード例は、`create-transit-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**トランジット仮想インターフェイスを作成するには**  
次の `create-transit-virtual-interface` の例では、指定した接続用にトランジット仮想インターフェイスを作成します。  

```
aws directconnect create-transit-virtual-interface \
    --connection-id dxlag-fEXAMPLE \
    --new-transit-virtual-interface "virtualInterfaceName=Example Transit Virtual Interface,vlan=126,asn=65110,mtu=1500,authKey=0xzxgA9YoW9h58u8SvEXAMPLE,amazonAddress=192.168.1.1/30,customerAddress=192.168.1.2/30,addressFamily=ipv4,directConnectGatewayId=8384da05-13ce-4a91-aada-5a1baEXAMPLE,tags=[{key=Tag,value=Example}]"
```
出力:  

```
{
    "virtualInterface": {
        "ownerAccount": "1111222233333",
        "virtualInterfaceId": "dxvif-fEXAMPLE",
        "location": "loc1",
        "connectionId": "dxlag-fEXAMPLE",
        "virtualInterfaceType": "transit",
        "virtualInterfaceName": "Example Transit Virtual Interface",
        "vlan": 126,
        "asn": 65110,
        "amazonSideAsn": 4200000000,
        "authKey": "0xzxgA9YoW9h58u8SEXAMPLE",
        "amazonAddress": "192.168.1.1/30",
        "customerAddress": "192.168.1.2/30",
        "addressFamily": "ipv4",
        "virtualInterfaceState": "pending",
        "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fEXAMPLE\">\n  <vlan>126</vlan>\n  <customer_address>192.168.1.2/30</customer_address>\n  <amazon_address>192.168.1.1/30</amazon_address>\n  <bgp_asn>65110</bgp_asn>\n  <bgp_auth_key>0xzxgA9YoW9h58u8SvOmXRTw</bgp_auth_key>\n  <amazon_bgp_asn>4200000000</amazon_bgp_asn>\n  <connection_type>transit</connection_type>\n</logical_connection>\n",
        "mtu": 1500,
        "jumboFrameCapable": true,
        "virtualGatewayId": "",
        "directConnectGatewayId": "8384da05-13ce-4a91-aada-5a1baEXAMPLE",
        "routeFilterPrefixes": [],
        "bgpPeers": [
            {
                "bgpPeerId": "dxpeer-EXAMPLE",
                "asn": 65110,
                "authKey": "0xzxgA9YoW9h58u8SEXAMPLE",
                "addressFamily": "ipv4",
                "amazonAddress": "192.168.1.1/30",
                "customerAddress": "192.168.1.2/30",
                "bgpPeerState": "pending",
                "bgpStatus": "down",
                "awsDeviceV2": "loc1-26wz6vEXAMPLE"
            }
        ],
        "region": "sa-east-1",
        "awsDeviceV2": "loc1-26wz6vEXAMPLE",
        "tags": [
            {
                "key": "Tag",
                "value": "Example"
            }
        ]
    }
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Creating a Transit Virtual Interface to the Direct Connect Gateway](https://docs.aws.amazon.com/directconnect/latest/UserGuide/create-vif.html#create-transit-vif)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/create-transit-virtual-interface.html)」を参照してください。

### `delete-bgp-peer`
<a name="direct-connect_DeleteBgpPeer_cli_2_topic"></a>

次のコード例は、`delete-bgp-peer` を使用する方法を示しています。

**AWS CLI**  
**仮想インターフェイスから BGP ピアを削除するには**  
次の例では、仮想インターフェイス `dxvif-fg1vuj3d` から IPv6 BGP ピアを削除します。  
コマンド:  

```
aws directconnect delete-bgp-peer --virtual-interface-id dxvif-fg1vuj3d --asn 64600 --customer-address 2001:db8:1100:2f0:0:1:9cb4:4216/125
```
出力:  

```
{
  "virtualInterface": {
      "virtualInterfaceState": "available",
      "asn": 65000,
      "vlan": 125,
      "customerAddress": "169.254.255.2/30",
      "ownerAccount": "123456789012",
      "connectionId": "dxcon-fguhmqlc",
      "addressFamily": "ipv4",
      "virtualGatewayId": "vgw-f9eb0c90",
      "virtualInterfaceId": "dxvif-fg1vuj3d",
      "authKey": "0xC_ukbCerl6EYA0example",
      "routeFilterPrefixes": [],
      "location": "EqDC2",
      "bgpPeers": [
          {
              "bgpStatus": "down",
              "customerAddress": "169.254.255.2/30",
              "addressFamily": "ipv4",
              "authKey": "0xC_ukbCerl6EYA0uexample",
              "bgpPeerState": "available",
              "amazonAddress": "169.254.255.1/30",
              "asn": 65000
          },
          {
              "bgpStatus": "down",
              "customerAddress": "2001:db8:1100:2f0:0:1:9cb4:4216/125",
              "addressFamily": "ipv6",
              "authKey": "0xS27kAIU_VHPjjAexample",
              "bgpPeerState": "deleting",
              "amazonAddress": "2001:db8:1100:2f0:0:1:9cb4:4211/125",
              "asn": 64600
          }
      ],
      "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fg1vuj3d\">\n  <vlan>125</vlan>\n  <customer_address>169.254.255.2/30</customer_address>\n  <amazon_address>169.254.255.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>0xC_ukbCerl6EYA0example</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>private</connection_type>\n</logical_connection>\n",
      "amazonAddress": "169.254.255.1/30",
      "virtualInterfaceType": "private",
      "virtualInterfaceName": "Test"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBgpPeer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/delete-bgp-peer.html)」を参照してください。

### `delete-connection`
<a name="direct-connect_DeleteConnection_cli_2_topic"></a>

次のコード例は、`delete-connection` を使用する方法を示しています。

**AWS CLI**  
**接続を削除するには**  
次の `delete-connection` コマンドは、指定した接続を削除します。  

```
aws directconnect delete-connection --connection-id dxcon-fg31dyv6
```
出力:  

```
{
    "ownerAccount": "123456789012",
    "connectionId": "dxcon-fg31dyv6",
    "connectionState": "deleted",
    "bandwidth": "1Gbps",
    "location": "TIVIT",
    "connectionName": "Connection to AWS",
    "region": "sa-east-1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/delete-connection.html)」を参照してください。

### `delete-direct-connect-gateway-association`
<a name="direct-connect_DeleteDirectConnectGatewayAssociation_cli_2_topic"></a>

次のコード例は、`delete-direct-connect-gateway-association` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイの関連付けを削除するには**  
次の `delete-direct-connect-gateway-association` の例では、指定された関連付け ID を持つ Transit Gateway との Direct Connect ゲートウェイの関連付けを削除します。  

```
aws directconnect delete-direct-connect-gateway-association --association-id  be85116d-46eb-4b43-a27a-da0c2ad648de
```
出力:  

```
{
    "directConnectGatewayAssociation": {
        "directConnectGatewayId": "11460968-4ac1-4fd3-bdb2-00599EXAMPlE",
        "directConnectGatewayOwnerAccount": "123456789012",
        "associationState": "disassociating",
        "associatedGateway": {
            "id": "tgw-095b3b0b54EXAMPLE",
            "type": "transitGateway",
            "ownerAccount": "123456789012",
            "region": "us-east-1"
       },
        "associationId": " be85116d-46eb-4b43-a27a-da0c2ad648deEXAMPLE ",
        "allowedPrefixesToDirectConnectGateway": [
            {
                "cidr": "192.0.1.0/28"
            }
        ]
    }
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Associating and Disassociating Transit Gateways](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-transit-gateways.html#associate-tgw-with-direct-connect-gateway)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDirectConnectGatewayAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/delete-direct-connect-gateway-association.html)」を参照してください。

### `delete-direct-connect-gateway`
<a name="direct-connect_DeleteDirectConnectGateway_cli_2_topic"></a>

次のコード例は、`delete-direct-connect-gateway` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイを削除するには**  
次の例では、Direct Connect ゲートウェイ `5f294f92-bafb-4011-916d-9b0bexample` を削除します。  
コマンド:  

```
aws directconnect delete-direct-connect-gateway --direct-connect-gateway-id 5f294f92-bafb-4011-916d-9b0bexample
```
出力:  

```
{
  "directConnectGateway": {
      "amazonSideAsn": 64512,
      "directConnectGatewayId": "5f294f92-bafb-4011-916d-9b0bexample",
      "ownerAccount": "123456789012",
      "directConnectGatewayName": "DxGateway1",
      "directConnectGatewayState": "deleting"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDirectConnectGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/delete-direct-connect-gateway.html)」を参照してください。

### `delete-interconnect`
<a name="direct-connect_DeleteInterconnect_cli_2_topic"></a>

次のコード例は、`delete-interconnect` を使用する方法を示しています。

**AWS CLI**  
**相互接続を削除するには**  
次の `delete-interconnect` コマンドは、指定した相互接続を削除します。  

```
aws directconnect delete-interconnect --interconnect-id dxcon-fgktov66
```
出力:  

```
{
    "interconnectState": "deleted"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInterconnect](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/delete-interconnect.html)」を参照してください。

### `delete-lag`
<a name="direct-connect_DeleteLag_cli_2_topic"></a>

次のコード例は、`delete-lag` を使用する方法を示しています。

**AWS CLI**  
**LAG を削除するには**  
次の例では、指定した LAG を削除します。  
コマンド:  

```
aws directconnect delete-lag --lag-id dxlag-ffrhowd9
```
出力:  

```
{
  "awsDevice": "EqDC2-4h6ce2r1bes6",
  "numberOfConnections": 0,
  "lagState": "deleted",
  "ownerAccount": "123456789012",
  "lagName": "TestLAG",
  "connections": [],
  "lagId": "dxlag-ffrhowd9",
  "minimumLinks": 0,
  "connectionsBandwidth": "1Gbps",
  "region": "us-east-1",
  "location": "EqDC2"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/delete-lag.html)」を参照してください。

### `delete-virtual-interface`
<a name="direct-connect_DeleteVirtualInterface_cli_2_topic"></a>

次のコード例は、`delete-virtual-interface` を使用する方法を示しています。

**AWS CLI**  
**仮想インターフェイスを削除するには**  
次の `delete-virtual-interface` コマンドは、指定した仮想インターフェイスを削除します。  

```
aws directconnect delete-virtual-interface --virtual-interface-id dxvif-ffhhk74f
```
出力:  

```
{
    "virtualInterfaceState": "deleting"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVirtualInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/delete-virtual-interface.html)」を参照してください。

### `describe-connection-loa`
<a name="direct-connect_DescribeConnectionLoa_cli_2_topic"></a>

次のコード例は、`describe-connection-loa` を使用する方法を示しています。

**AWS CLI**  
**Linux または Mac OS X を使用して接続用の LOA-CFA を記述するには**  
次の例では、接続 `dxcon-fh6ayh1d` 用の LOA-CFA を記述します。LOA-CFA の内容は base64 でエンコードされています。このコマンドは、`--output` パラメータおよび `--query` パラメータを使用して出力を制御し、`loaContent` 構造の内容を抽出します。コマンドの最後の部分で `base64` ユーティリティを使用してコンテンツをデコードし、出力を PDF ファイルに送信します。  

```
aws directconnect describe-connection-loa --connection-id dxcon-fh6ayh1d --output text --query loa.loaContent|base64 --decode > myLoaCfa.pdf
```
**Windows を使用して接続用の LOA-CFA を記述するには**  
前の例では、`base64` ユーティリティを使用して出力をデコードする必要がありました。Windows コンピュータでは、代わりに `certutil` を使用できます。次の例では、最初のコマンドで接続 `dxcon-fh6ayh1d` 用の LOA-CFA を記述し、`--output` パラメータと `--query` パラメータを使用して出力を制御し、`loaContent` 構造の内容を `myLoaCfa.base64` というファイルに抽出します。2 番目のコマンドでは、`certutil` ユーティリティを使用してファイルをデコードし、PDF ファイルに出力を送信します。  

```
aws directconnect describe-connection-loa --connection-id dxcon-fh6ayh1d --output text --query loa.loaContent > myLoaCfa.base64
```

```
certutil -decode myLoaCfa.base64 myLoaCfa.pdf
```
 AWS CLI 出力の制御の詳細については、[「 コマンドラインインターフェイスユーザーガイド」の AWS 「 コマンドラインインターフェイスからのコマンド出力の制御](https://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConnectionLoa](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-connection-loa.html)」を参照してください。

### `describe-connections-on-interconnect`
<a name="direct-connect_DescribeConnectionsOnInterconnect_cli_2_topic"></a>

次のコード例は、`describe-connections-on-interconnect` を使用する方法を示しています。

**AWS CLI**  
**相互接続上の接続を一覧表示するには**  
次の `describe-connections-on-interconnect` コマンドは、指定された相互接続上にプロビジョニングされた接続を一覧表示します。  

```
aws directconnect describe-connections-on-interconnect --interconnect-id dxcon-fgktov66
```
出力:  

```
{
    "connections": [
        {
            "partnerName": "TIVIT",
            "vlan": 101,
            "ownerAccount": "123456789012",
            "connectionId": "dxcon-ffzc51m1",
            "connectionState": "ordering",
            "bandwidth": "500Mbps",
            "location": "TIVIT",
            "connectionName": "mydcinterconnect",
            "region": "sa-east-1"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConnectionsOnInterconnect](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-connections-on-interconnect.html)」を参照してください。

### `describe-connections`
<a name="direct-connect_DescribeConnections_cli_2_topic"></a>

次のコード例は、`describe-connections` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンのすべての接続を一覧表示するには**  
次の `describe-connections` コマンドは、現在のリージョン内にあるすべての接続を一覧表示します。  

```
aws directconnect describe-connections
```
出力:  

```
{
  "connections": [
      {
          "awsDevice": "EqDC2-123h49s71dabc",
          "ownerAccount": "123456789012",
          "connectionId": "dxcon-fguhmqlc",
          "lagId": "dxlag-ffrz71kw",
          "connectionState": "down",
          "bandwidth": "1Gbps",
          "location": "EqDC2",
          "connectionName": "My_Connection",
          "loaIssueTime": 1491568964.0,
          "region": "us-east-1"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-connections.html)」を参照してください。

### `describe-direct-connect-gateway-association-proposals`
<a name="direct-connect_DescribeDirectConnectGatewayAssociationProposals_cli_2_topic"></a>

次のコード例は、`describe-direct-connect-gateway-association-proposals` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイの関連付けの提案を記述するには**  
次の `describe-direct-connect-gateway-association-proposals` の例では、Direct Connect ゲートウェイの関連付けの提案に関する詳細を表示します。  

```
aws directconnect describe-direct-connect-gateway-association-proposals
```
出力:  

```
{
    "directConnectGatewayAssociationProposals": [
        {
            "proposalId": "c2ede9b4-bbc6-4d33-923c-bc4feEXAMPLE",
            "directConnectGatewayId": "11460968-4ac1-4fd3-bdb2-00599EXAMPLE",
            "directConnectGatewayOwnerAccount": "111122223333",
            "proposalState": "requested",
            "associatedGateway": {
                "id": "tgw-02f776b1a7EXAMPLE",
                "type": "transitGateway",
                "ownerAccount": "111122223333",
                "region": "us-east-1"
            },
            "existingAllowedPrefixesToDirectConnectGateway": [
                {
                    "cidr": "192.168.2.0/30"
                },
                {
                    "cidr": "192.168.1.0/30"
                }
            ],
            "requestedAllowedPrefixesToDirectConnectGateway": [
                {
                    "cidr": "192.168.1.0/30"
                }
            ]
        },
        {
            "proposalId": "cb7f41cb-8128-43a5-93b1-dcaedEXAMPLE",
            "directConnectGatewayId": "11560968-4ac1-4fd3-bcb2-00599EXAMPLE",
            "directConnectGatewayOwnerAccount": "111122223333",
            "proposalState": "accepted",
            "associatedGateway": {
                "id": "tgw-045776b1a7EXAMPLE",
                "type": "transitGateway",
                "ownerAccount": "111122223333",
                "region": "us-east-1"
            },
            "existingAllowedPrefixesToDirectConnectGateway": [
                {
                    "cidr": "192.168.4.0/30"
                },
                {
                    "cidr": "192.168.5.0/30"
                }
            ],
            "requestedAllowedPrefixesToDirectConnectGateway": [
                {
                    "cidr": "192.168.5.0/30"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Associating and Disassociating Transit Gateways](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-transit-gateways.html#associate-tgw-with-direct-connect-gateway)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDirectConnectGatewayAssociationProposals](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-direct-connect-gateway-association-proposals.html)」を参照してください。

### `describe-direct-connect-gateway-associations`
<a name="direct-connect_DescribeDirectConnectGatewayAssociations_cli_2_topic"></a>

次のコード例は、`describe-direct-connect-gateway-associations` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイの関連付けを記述するには**  
次の例では、Direct Connect ゲートウェイ `5f294f92-bafb-4011-916d-9b0bexample` とのすべての関連付けについて説明します。  
コマンド:  

```
aws directconnect describe-direct-connect-gateway-associations --direct-connect-gateway-id 5f294f92-bafb-4011-916d-9b0bexample
```
出力:  

```
{
  "nextToken": "eyJ2IjoxLCJzIjoxLCJpIjoiOU83OTFodzdycnZCbkN4MExHeHVwQT09IiwiYyI6InIxTEN0UEVHV0I1UFlkaWFnNlUxanJkRWF6eW1iOElHM0FRVW1MdHRJK0dxcnN1RWtvcFBKWFE2ZjRNRGdGTkhCa0tDZmVINEtZOEYwZ0dEYWZpbmU0ZnZMYVhKRjdXRVdENmdQZ1Y4d2w0PSJ9",
  "directConnectGatewayAssociations": [
      {
          "associationState": "associating",
          "virtualGatewayOwnerAccount": "123456789012",
          "directConnectGatewayId": "5f294f92-bafb-4011-916d-9b0bexample",
          "virtualGatewayId": "vgw-6efe725e",
          "virtualGatewayRegion": "us-east-2"
      },
      {
          "associationState": "disassociating",
          "virtualGatewayOwnerAccount": "123456789012",
          "directConnectGatewayId": "5f294f92-bafb-4011-916d-9b0bexample",
          "virtualGatewayId": "vgw-ebaa27db",
          "virtualGatewayRegion": "us-east-2"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDirectConnectGatewayAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-direct-connect-gateway-associations.html)」を参照してください。

### `describe-direct-connect-gateway-attachments`
<a name="direct-connect_DescribeDirectConnectGatewayAttachments_cli_2_topic"></a>

次のコード例は、`describe-direct-connect-gateway-attachments` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイのアタッチメントを記述するには**  
次の例では、Direct Connect ゲートウェイ `5f294f92-bafb-4011-916d-9b0bexample` にアタッチされている仮想インターフェイスについて説明します。  
コマンド:  

```
aws directconnect describe-direct-connect-gateway-attachments --direct-connect-gateway-id 5f294f92-bafb-4011-916d-9b0bexample
```
出力:  

```
{
  "directConnectGatewayAttachments": [
      {
          "virtualInterfaceOwnerAccount": "123456789012",
          "directConnectGatewayId": "5f294f92-bafb-4011-916d-9b0bexample",
          "virtualInterfaceRegion": "us-east-2",
          "attachmentState": "attaching",
          "virtualInterfaceId": "dxvif-fg9zyabc"
      }
  ],
  "nextToken": "eyJ2IjoxLCJzIjoxLCJpIjoibEhXdlNpUXF5RzhoL1JyUW52SlV2QT09IiwiYyI6Im5wQjFHQ0RyQUdRS3puNnNXcUlINCtkTTA4dTk3KzBiU0xtb05JQmlaczZ6NXRIYmk3c3VESUxFTTd6a2FzVHM0VTFwaGJkZGNxTytqWmQ3QzMzOGRQaTVrTThrOG1zelRsV3gyMWV3VTNFPSJ9"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDirectConnectGatewayAttachments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-direct-connect-gateway-attachments.html)」を参照してください。

### `describe-direct-connect-gateways`
<a name="direct-connect_DescribeDirectConnectGateways_cli_2_topic"></a>

次のコード例は、`describe-direct-connect-gateways` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイを記述するには**  
次の例では、すべての Direct Connect ゲートウェイについて説明します。  
コマンド:  

```
aws directconnect describe-direct-connect-gateways
```
出力:  

```
{
  "directConnectGateways": [
      {
          "amazonSideAsn": 64512,
          "directConnectGatewayId": "cf68415c-f4ae-48f2-87a7-3b52cexample",
          "ownerAccount": "123456789012",
          "directConnectGatewayName": "DxGateway2",
          "directConnectGatewayState": "available"
      },
      {
          "amazonSideAsn": 64512,
          "directConnectGatewayId": "5f294f92-bafb-4011-916d-9b0bdexample",
          "ownerAccount": "123456789012",
          "directConnectGatewayName": "DxGateway1",
          "directConnectGatewayState": "available"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDirectConnectGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-direct-connect-gateways.html)」を参照してください。

### `describe-hosted-connections`
<a name="direct-connect_DescribeHostedConnections_cli_2_topic"></a>

次のコード例は、`describe-hosted-connections` を使用する方法を示しています。

**AWS CLI**  
**相互接続上の接続を一覧表示するには**  
次の例では、指定された相互接続上にプロビジョニングされている接続を一覧表示します。  
コマンド:  

```
aws directconnect describe-hosted-connections --connection-id dxcon-fgktov66
```
出力:  

```
{
    "connections": [
        {
            "partnerName": "TIVIT",
            "vlan": 101,
            "ownerAccount": "123456789012",
            "connectionId": "dxcon-ffzc51m1",
            "connectionState": "ordering",
            "bandwidth": "500Mbps",
            "location": "TIVIT",
            "connectionName": "mydcinterconnect",
            "region": "sa-east-1"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHostedConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-hosted-connections.html)」を参照してください。

### `describe-interconnect-loa`
<a name="direct-connect_DescribeInterconnectLoa_cli_2_topic"></a>

次のコード例は、`describe-interconnect-loa` を使用する方法を示しています。

**AWS CLI**  
**Linux または Mac OS X を使用して相互接続用の LOA-CFA を記述するには**  
次の例では、相互接続 `dxcon-fh6ayh1d` 用の LOA-CFA を記述します。LOA-CFA の内容は base64 でエンコードされています。このコマンドは、`--output` パラメータおよび `--query` パラメータを使用して出力を制御し、`loaContent` 構造の内容を抽出します。コマンドの最後の部分で `base64` ユーティリティを使用してコンテンツをデコードし、出力を PDF ファイルに送信します。  

```
aws directconnect describe-interconnect-loa --interconnect-id dxcon-fh6ayh1d --output text --query loa.loaContent|base64 --decode > myLoaCfa.pdf
```
**Windows を使用して相互接続用の LOA-CFA を記述するには**  
前の例では、`base64` ユーティリティを使用して出力をデコードする必要がありました。Windows コンピュータでは、代わりに `certutil` を使用できます。次の例では、最初のコマンドで相互接続 `dxcon-fh6ayh1d` 用の LOA-CFA を記述し、`--output` パラメータと `--query` パラメータを使用して出力を制御し、`loaContent` 構造の内容を `myLoaCfa.base64` というファイルに抽出します。2 番目のコマンドでは、`certutil` ユーティリティを使用してファイルをデコードし、PDF ファイルに出力を送信します。  

```
aws directconnect describe-interconnect-loa --interconnect-id dxcon-fh6ayh1d --output text --query loa.loaContent > myLoaCfa.base64
```

```
certutil -decode myLoaCfa.base64 myLoaCfa.pdf
```
 AWS CLI 出力の制御の詳細については、[「 コマンドラインインターフェイスユーザーガイド」の AWS 「 コマンドラインインターフェイスからのコマンド出力の制御](https://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInterconnectLoa](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-interconnect-loa.html)」を参照してください。

### `describe-interconnects`
<a name="direct-connect_DescribeInterconnects_cli_2_topic"></a>

次のコード例は、`describe-interconnects` を使用する方法を示しています。

**AWS CLI**  
**相互接続を一覧表示するには**  
次の`describe-interconnects`コマンドは、 AWS アカウントが所有する相互接続を一覧表示します。  

```
aws directconnect describe-interconnects
```
出力:  

```
{
    "interconnects": [
        {
            "region": "sa-east-1",
            "bandwidth": "1Gbps",
            "location": "TIVIT",
            "interconnectName": "1G Interconnect to AWS",
            "interconnectId": "dxcon-fgktov66",
            "interconnectState": "down"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInterconnects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-interconnects.html)」を参照してください。

### `describe-lags`
<a name="direct-connect_DescribeLags_cli_2_topic"></a>

次のコード例は、`describe-lags` を使用する方法を示しています。

**AWS CLI**  
**LAG を記述するには**  
次のコマンドは、現在のリージョンのすべての LAG について表示します。  
コマンド:  

```
aws directconnect describe-lags
```
出力:  

```
{
  "lags": [
      {
          "awsDevice": "EqDC2-19y7z3m17xpuz",
          "numberOfConnections": 2,
          "lagState": "down",
          "ownerAccount": "123456789012",
          "lagName": "DA-LAG",
          "connections": [
              {
                  "ownerAccount": "123456789012",
                  "connectionId": "dxcon-ffnikghc",
                  "lagId": "dxlag-fgsu9erb",
                  "connectionState": "requested",
                  "bandwidth": "10Gbps",
                  "location": "EqDC2",
                  "connectionName": "Requested Connection 1 for Lag dxlag-fgsu9erb",
                  "region": "us-east-1"
              },
              {
                  "ownerAccount": "123456789012",
                  "connectionId": "dxcon-fglgbdea",
                  "lagId": "dxlag-fgsu9erb",
                  "connectionState": "requested",
                  "bandwidth": "10Gbps",
                  "location": "EqDC2",
                  "connectionName": "Requested Connection 2 for Lag dxlag-fgsu9erb",
                  "region": "us-east-1"
              }
          ],
          "lagId": "dxlag-fgsu9erb",
          "minimumLinks": 0,
          "connectionsBandwidth": "10Gbps",
          "region": "us-east-1",
          "location": "EqDC2"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-lags.html)」を参照してください。

### `describe-loa`
<a name="direct-connect_DescribeLoa_cli_2_topic"></a>

次のコード例は、`describe-loa` を使用する方法を示しています。

**AWS CLI**  
**Linux または Mac OS X を使用して接続用の LOA-CFA を記述するには**  
次の例では、接続 `dxcon-fh6ayh1d` 用の LOA-CFA を記述します。LOA-CFA の内容は base64 でエンコードされています。このコマンドは、`--output` パラメータおよび `--query` パラメータを使用して出力を制御し、`loaContent` 構造の内容を抽出します。コマンドの最後の部分で `base64` ユーティリティを使用してコンテンツをデコードし、出力を PDF ファイルに送信します。  

```
aws directconnect describe-loa --connection-id dxcon-fh6ayh1d --output text --query loa.loaContent|base64 --decode > myLoaCfa.pdf
```
**Windows を使用して接続用の LOA-CFA を記述するには**  
前の例では、`base64` ユーティリティを使用して出力をデコードする必要がありました。Windows コンピュータでは、代わりに `certutil` を使用できます。次の例では、最初のコマンドで接続 `dxcon-fh6ayh1d` 用の LOA-CFA を記述し、`--output` パラメータと `--query` パラメータを使用して出力を制御し、`loaContent` 構造の内容を `myLoaCfa.base64` というファイルに抽出します。2 番目のコマンドでは、`certutil` ユーティリティを使用してファイルをデコードし、PDF ファイルに出力を送信します。  

```
aws directconnect describe-loa --connection-id dxcon-fh6ayh1d --output text --query loa.loaContent > myLoaCfa.base64
```

```
certutil -decode myLoaCfa.base64 myLoaCfa.pdf
```
 AWS CLI 出力の制御の詳細については、[「 コマンドラインインターフェイスユーザーガイド」の AWS 「 コマンドラインインターフェイスからのコマンド出力の制御](https://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoa](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-loa.html)」を参照してください。

### `describe-locations`
<a name="direct-connect_DescribeLocations_cli_2_topic"></a>

次の例は、`describe-locations` を使用する方法を説明しています。

**AWS CLI**  
** AWS Direct Connect パートナーとロケーションを一覧表示するには**  
次の`describe-locations`コマンドは、現在のリージョンの AWS Direct Connect パートナーとロケーションを一覧表示します。  

```
aws directconnect describe-locations
```
出力:  

```
{
    "locations": [
        {
            "locationName": "NAP do Brasil, Barueri, Sao Paulo",
            "locationCode": "TNDB"
        },
        {
            "locationName": "Tivit - Site Transamerica (Sao Paulo)",
            "locationCode": "TIVIT"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLocations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-locations.html)」を参照してください。

### `describe-tags`
<a name="direct-connect_DescribeTags_cli_2_topic"></a>

次の例は、`describe-tags` を使用する方法を説明しています。

**AWS CLI**  
** AWS Direct Connect リソースのタグを記述するには**  
次のコマンドは、接続 `dxcon-abcabc12` のタグについて表示します。  
コマンド:  

```
aws directconnect describe-tags --resource-arns arn:aws:directconnect:us-east-1:123456789012:dxcon/dxcon-abcabc12
```
出力:  

```
{
  "resourceTags": [
      {
          "resourceArn": "arn:aws:directconnect:us-east-1:123456789012:dxcon/dxcon-abcabc12",
          "tags": [
              {
                  "value": "VAConnection",
                  "key": "Name"
              }
          ]
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-tags.html)」を参照してください。

### `describe-virtual-gateways`
<a name="direct-connect_DescribeVirtualGateways_cli_2_topic"></a>

次のコード例は、`describe-virtual-gateways` を使用する方法を示しています。

**AWS CLI**  
**仮想プライベートゲートウェイを一覧表示するには**  
次の`describe-virtual-gateways`コマンドは、 AWS アカウントが所有する仮想プライベートゲートウェイを一覧表示します。  

```
aws directconnect describe-virtual-gateways
```
出力:  

```
{
    "virtualGateways": [
        {
            "virtualGatewayId": "vgw-aba37db6",
            "virtualGatewayState": "available"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVirtualGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-virtual-gateways.html)」を参照してください。

### `describe-virtual-interfaces`
<a name="direct-connect_DescribeVirtualInterfaces_cli_2_topic"></a>

次のコード例は、`describe-virtual-interfaces` を使用する方法を示しています。

**AWS CLI**  
**すべての仮想インターフェイスを一覧表示するには**  
次の`describe-virtual-interfaces`コマンドは、 AWS アカウントに関連付けられているすべての仮想インターフェイスに関する情報を一覧表示します。  

```
aws directconnect describe-virtual-interfaces --connection-id dxcon-ffjrkx17
```
出力:  

```
{
    "virtualInterfaces": [
        {
            "virtualInterfaceState": "down",
            "asn": 65000,
            "vlan": 101,
            "customerAddress": "192.168.1.2/30",
            "ownerAccount": "123456789012",
            "connectionId": "dxcon-ffjrkx17",
            "virtualGatewayId": "vgw-aba37db6",
            "virtualInterfaceId": "dxvif-ffhhk74f",
            "authKey": "asdf34example",
            "routeFilterPrefixes": [],
            "location": "TIVIT",
            "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-ffhhk74f\">\n  <vlan>101</vlan>\n  <customer_address>192.168.1.2/30</customer_address>\n  <amazon_address>192.168.1.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>asdf34example</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>private</connection_type>\n</logical_connection>\n",
            "amazonAddress": "192.168.1.1/30",
            "virtualInterfaceType": "private",
            "virtualInterfaceName": "PrivateVirtualInterface"
        },
        {
            "virtualInterfaceState": "verifying",
            "asn": 65000,
            "vlan": 2000,
            "customerAddress": "203.0.113.2/30",
            "ownerAccount": "123456789012",
            "connectionId": "dxcon-ffjrkx17",
            "virtualGatewayId": "",
            "virtualInterfaceId": "dxvif-fgh0hcrk",
            "authKey": "asdf34example",
            "routeFilterPrefixes": [
                {
                    "cidr": "203.0.113.4/30"
                },
                {
                    "cidr": "203.0.113.0/30"
                }
            ],
            "location": "TIVIT",
            "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fgh0hcrk\">\n  <vlan>2000</vlan>\n  <customer_address>203.0.113.2/30</customer_address>\n  <amazon_address>203.0.113.1/30</amazon_address>\n  <bgp_asn>65000</bgp_asn>\n  <bgp_auth_key>asdf34example</bgp_auth_key>\n  <amazon_bgp_asn>7224</amazon_bgp_asn>\n  <connection_type>public</connection_type>\n</logical_connection>\n",
            "amazonAddress": "203.0.113.1/30",
            "virtualInterfaceType": "public",
            "virtualInterfaceName": "PublicVirtualInterface"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVirtualInterfaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/describe-virtual-interfaces.html)」を参照してください。

### `disassociate-connection-from-lag`
<a name="direct-connect_DisassociateConnectionFromLag_cli_2_topic"></a>

次のコード例は、`disassociate-connection-from-lag` を使用する方法を示しています。

**AWS CLI**  
**LAG から接続の関連付けを解除するには**  
次の例では、指定された接続の関連付けを指定された LAG から解除します。  
コマンド:  

```
aws directconnect disassociate-connection-from-lag --lag-id dxlag-fhccu14t --connection-id  dxcon-fg9607vm
```
出力:  

```
{
  "ownerAccount": "123456789012",
  "connectionId": "dxcon-fg9607vm",
  "connectionState": "requested",
  "bandwidth": "1Gbps",
  "location": "EqDC2",
  "connectionName": "Con2ForLag",
  "region": "us-east-1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateConnectionFromLag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/disassociate-connection-from-lag.html)」を参照してください。

### `tag-resource`
<a name="direct-connect_TagResource_cli_2_topic"></a>

次の例は、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS Direct Connect リソースにタグを追加するには**  
次のコマンドは、キー `Name` と値 `VAConnection` を持つタグを接続 `dxcon-abcabc12` に追加します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws directconnect tag-resource --resource-arn arn:aws:directconnect:us-east-1:123456789012:dxcon/dxcon-abcabc12 --tags "key=Name,value=VAConnection"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="direct-connect_UntagResource_cli_2_topic"></a>

次の例は、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS Direct Connect リソースからタグを削除するには**  
次のコマンドは、キー `Name` を持つタグを接続 `dxcon-abcabc12` から削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws directconnect untag-resource --resource-arn arn:aws:directconnect:us-east-1:123456789012:dxcon/dxcon-abcabc12 --tag-keys Name
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/untag-resource.html)」を参照してください。

### `update-direct-connect-gateway-association`
<a name="direct-connect_UpdateDirectConnectGatewayAssociation_cli_2_topic"></a>

次のコード例は、`update-direct-connect-gateway-association` を使用する方法を示しています。

**AWS CLI**  
**Direct Connect ゲートウェイの関連付けの指定された属性を更新するには**  
次の `update-direct-connect-gateway-association` の例では、指定された CIDR ブロックを Direct Connect ゲートウェイの関連付けに追加します。  

```
aws directconnect update-direct-connect-gateway-association \
    --association-id 820a6e4f-5374-4004-8317-3f64bEXAMPLE \
    --add-allowed-prefixes-to-direct-connect-gateway cidr=192.168.2.0/30
```
出力:  

```
{
    "directConnectGatewayAssociation": {
        "directConnectGatewayId": "11460968-4ac1-4fd3-bdb2-00599EXAMPLE",
        "directConnectGatewayOwnerAccount": "111122223333",
        "associationState": "updating",
        "associatedGateway": {
            "id": "tgw-02f776b1a7EXAMPLE",
            "type": "transitGateway",
            "ownerAccount": "111122223333",
            "region": "us-east-1"
        },
        "associationId": "820a6e4f-5374-4004-8317-3f64bEXAMPLE",
        "allowedPrefixesToDirectConnectGateway": [
            {
                "cidr": "192.168.2.0/30"
            },
            {
                "cidr": "192.168.1.0/30"
            }
        ]
    }
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Working with Direct Connect Gateways](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDirectConnectGatewayAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/update-direct-connect-gateway-association.html)」を参照してください。

### `update-lag`
<a name="direct-connect_UpdateLag_cli_2_topic"></a>

次のコード例は、`update-lag` を使用する方法を示しています。

**AWS CLI**  
**LAG を更新するには**  
次の例では、指定された LAG の名前を変更します。  
コマンド:  

```
aws directconnect update-lag --lag-id dxlag-ffjhj9lx --lag-name 2ConnLag
```
出力:  

```
{
  "awsDevice": "CSVA1-23u8tlpaz8iks",
  "numberOfConnections": 2,
  "lagState": "down",
  "ownerAccount": "123456789012",
  "lagName": "2ConnLag",
  "connections": [
      {
          "ownerAccount": "123456789012",
          "connectionId": "dxcon-fflqyj95",
          "lagId": "dxlag-ffjhj9lx",
          "connectionState": "requested",
          "bandwidth": "1Gbps",
          "location": "CSVA1",
          "connectionName": "Requested Connection 2 for Lag dxlag-ffjhj9lx",
          "region": "us-east-1"
      },
      {
          "ownerAccount": "123456789012",
          "connectionId": "dxcon-ffqr6x5q",
          "lagId": "dxlag-ffjhj9lx",
          "connectionState": "requested",
          "bandwidth": "1Gbps",
          "location": "CSVA1",
          "connectionName": "Requested Connection 1 for Lag dxlag-ffjhj9lx",
          "region": "us-east-1"
      }
  ],
  "lagId": "dxlag-ffjhj9lx",
  "minimumLinks": 0,
  "connectionsBandwidth": "1Gbps",
  "region": "us-east-1",
  "location": "CSVA1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/update-lag.html)」を参照してください。

### `update-virtual-interface-attributes`
<a name="direct-connect_UpdateVirtualInterfaceAttributes_cli_2_topic"></a>

次のコード例は、`update-virtual-interface-attributes` を使用する方法を示しています。

**AWS CLI**  
**仮想インターフェイスの MTU を更新するには**  
次の `update-virtual-interface-attributes` の例では、指定された仮想インターフェイスの MTU を更新しています。  

```
aws directconnect update-virtual-interface-attributes \
    --virtual-interface-id dxvif-fEXAMPLE \
    --mtu 1500
```
出力:  

```
{
    "ownerAccount": "1111222233333",
    "virtualInterfaceId": "dxvif-fEXAMPLE",
    "location": "loc1",
    "connectionId": "dxlag-fEXAMPLE",
    "virtualInterfaceType": "transit",
    "virtualInterfaceName": "example transit virtual interface",
    "vlan": 125,
    "asn": 650001,
    "amazonSideAsn": 64512,
    "authKey": "0xzxgA9YoW9h58u8SEXAMPLE",
    "amazonAddress": "169.254.248.1/30",
    "customerAddress": "169.254.248.2/30",
    "addressFamily": "ipv4",
    "virtualInterfaceState": "down",
    "customerRouterConfig": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<logical_connection id=\"dxvif-fEXAMPLE\">\n  <vlan>125</vlan>\n  <customer_address>169.254.248.2/30</customer_address>\n  <amazon_address>169.254.248.1/30</amazon_address>\n  <bgp_asn>650001</bgp_asn>\n  <bgp_auth_key>0xzxgA9YoW9h58u8SEXAMPLE</bgp_auth_key>\n  <amazon_bgp_asn>64512</amazon_bgp_asn>\n  <connection_type>transit</connection_type>\n</logical_connection>\n",
    "mtu": 1500,
    "jumboFrameCapable": true,
    "virtualGatewayId": "",
    "directConnectGatewayId": "879b76a1-403d-4700-8b53-4a56ed85436e",
    "routeFilterPrefixes": [],
    "bgpPeers": [
        {
            "bgpPeerId": "dxpeer-fEXAMPLE",
            "asn": 650001,
            "authKey": "0xzxgA9YoW9h58u8SEXAMPLE",
            "addressFamily": "ipv4",
            "amazonAddress": "169.254.248.1/30",
            "customerAddress": "169.254.248.2/30",
            "bgpPeerState": "available",
            "bgpStatus": "down",
            "awsDeviceV2": "loc1-26wz6vEXAMPLE"
        }
    ],
    "region": "sa-east-1",
    "awsDeviceV2": "loc1-26wz6vEXAMPLE",
    "tags": []
}
```
詳細については、「*AWS Direct Connect ユーザーガイド*」の「[Setting Network MTU for Private Virtual Interfaces or Transit Virtual Interfaces](https://docs.aws.amazon.com/directconnect/latest/UserGuide/set-jumbo-frames-vif.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVirtualInterfaceAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directconnect/update-virtual-interface-attributes.html)」を参照してください。

# Directory Service を使用した の例 AWS CLI
<a name="cli_2_directory-service_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています Directory Service。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-directories`
<a name="directory-service_DescribeDirectories_cli_2_topic"></a>

次のコード例は、`describe-directories` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリに関する詳細を取得するには**  
次の `describe-directories` の例では、指定されたディレクトリに関する詳細情報を表示しています。  

```
aws ds describe-directories \
   --directory-id d-a1b2c3d4e5
```
出力:  

```
{
    "DirectoryDescriptions": [
        {
            "DirectoryId": "d-a1b2c3d4e5",
            "Name": "mydirectory.example.com",
            "ShortName": "mydirectory",
            "Size": "Small",
            "Edition": "Standard",
            "Alias": "d-a1b2c3d4e5",
            "AccessUrl": "d-a1b2c3d4e5.awsapps.com",
            "Stage": "Active",
            "ShareStatus": "Shared",
            "ShareMethod": "HANDSHAKE",
            "ShareNotes": "These are my share notes",
            "LaunchTime": "2019-07-08T15:33:46.327000-07:00",
            "StageLastUpdatedDateTime": "2019-07-08T15:59:12.307000-07:00",
            "Type": "SharedMicrosoftAD",
            "SsoEnabled": false,
            "DesiredNumberOfDomainControllers": 0,
            "OwnerDirectoryDescription": {
                "DirectoryId": "d-b2c3d4e5f6",
                "AccountId": "123456789111",
                "DnsIpAddrs": [
                    "203.113.0.248",
                    "203.113.0.253"
                ],
                "VpcSettings": {
                    "VpcId": "vpc-a1b2c3d4",
                    "SubnetIds": [
                        "subnet-a1b2c3d4",
                        "subnet-d4c3b2a1"
                    ],
                    "AvailabilityZones": [
                        "us-west-2a",
                        "us-west-2c"
                    ]
                }
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDirectories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/describe-directories.html)」を参照してください。

### `describe-trusts`
<a name="directory-service_DescribeTrusts_cli_2_topic"></a>

次のコード例は、`describe-trusts` を使用する方法を示しています。

**AWS CLI**  
**信頼関係に関する詳細を取得するには**  
次の `describe-trusts` の例では、指定されたディレクトリの信頼関係に関する詳細情報を表示しています。  

```
aws ds describe-trusts \
   --directory-id d-a1b2c3d4e5
```
出力:  

```
{
    "Trusts": [
        {
            "DirectoryId": "d-a1b2c3d4e5",
            "TrustId": "t-9a8b7c6d5e",
            "RemoteDomainName": "other.example.com",
            "TrustType": "Forest",
            "TrustDirection": "Two-Way",
            "TrustState": "Verified",
            "CreatedDateTime": "2017-06-20T18:08:45.614000-07:00",
            "LastUpdatedDateTime": "2019-06-04T10:52:12.410000-07:00",
            "StateLastUpdatedDateTime": "2019-06-04T10:52:12.410000-07:00",
            "SelectiveAuth": "Disabled"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrusts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ds/describe-trusts.html)」を参照してください。

# Directory Service を使用したデータ例 AWS CLI
<a name="cli_2_directory-service-data_code_examples"></a>

次のコード例は、 Directory Service データ AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-group-member`
<a name="directory-service-data_AddGroupMember_cli_2_topic"></a>

次のコード例は、`add-group-member` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリにグループメンバーを追加するには**  
次の `add-group-member` の例では、指定したディレクトリ内の指定したグループに、指定したユーザーを追加します。  

```
aws ds-data add-group-member \
    --directory-id d-1234567890 \
    --group-name 'sales' \
    --member-name 'john.doe'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 Directory Service 管理ガイド*」の[「グループへの AWS Managed Microsoft AD メンバーの追加または削除」および「グループへのグループ](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_add_remove_user_group.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AddGroupMember](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/add-group-member.html)」を参照してください。

### `create-group`
<a name="directory-service-data_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**使用可能なウィジェットを一覧表示するには**  
次の `create-group` の例では、指定したディレクトリにグループを作成します。  

```
aws ds-data create-group \
    --directory-id d-1234567890 \
    --sam-account-name "sales"
```
出力:  

```
{
    "DirectoryId": "d-1234567890",
    "SAMAccountName": "sales",
    "SID": "S-1-2-34-5567891234-5678912345-67891234567-8912"
}
```
詳細については、*AWS 「 Directory Service* [管理ガイド」の AWS 「 Managed Microsoft AD グループ](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_create_group.html)の作成」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/create-group.html)」を参照してください。

### `create-user`
<a name="directory-service-data_CreateUser_cli_2_topic"></a>

次のコード例は、`create-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを作成するには**  
次の `create-user` の例では、指定したディレクトリにユーザーを作成します。  

```
aws ds-data create-user \
    --directory-id d-1234567890 \
    --sam-account-name 'john.doe'
```
出力:  

```
{
    "DirectoryId": "d-1234567890",
    "SAMAccountName": "john.doe",
    "SID": "S-1-2-34-5567891234-5678912345-67891234567-8912"
}
```
詳細については、*AWS 「 Directory Service* [管理ガイド」の AWS 「 Managed Microsoft AD ユーザー](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_create_user.html)の作成」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/create-user.html)」を参照してください。

### `delete-group`
<a name="directory-service-data_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**グループを削除するには**  
次の `delete-group` の例では、指定したディレクトリから指定したグループを削除します。  

```
aws ds-data delete-group \
    --directory-id d-1234567890 \
    --sam-account-name 'sales'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 Directory Service 管理ガイド*[」の AWS 「Managed Microsoft AD グループの削除](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_delete_group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/delete-group.html)」を参照してください。

### `delete-user`
<a name="directory-service-data_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
次の `delete-user` の例では、指定したディレクトリから指定したユーザーを削除します。  

```
aws ds-data delete-user \
    --directory-id d-1234567890 \
    --sam-account-name 'john.doe'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 Directory Service 管理ガイド*[」の AWS 「 Managed Microsoft AD ユーザーの削除](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_delete_user.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/delete-user.html)」を参照してください。

### `describe-group`
<a name="directory-service-data_DescribeGroup_cli_2_topic"></a>

次のコード例は、`describe-group` を使用する方法を示しています。

**AWS CLI**  
**グループの詳細を一覧表示するには**  
次の `describe-group` の例では、指定したディレクトリ内の指定したグループの情報を取得します。  

```
aws ds-data describe-group \
    --directory-id d-1234567890 \
    --sam-account-name 'sales'
```
出力:  

```
{
    "DirectoryId": "d-1234567890",
    "DistinguishedName": "CN=sales,OU=Users,OU=CORP,DC=corp,DC=example,DC=com",
    "GroupScope": "Global",
    "GroupType": "Security",
    "Realm": "corp.example.com",
    "SAMAccountName": "sales",
    "SID": "S-1-2-34-5567891234-5678912345-67891234567-8912"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD グループの詳細の表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_group.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/describe-group.html)」を参照してください。

### `describe-user`
<a name="directory-service-data_DescribeUser_cli_2_topic"></a>

次のコード例は、`describe-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーの情報を一覧表示するには**  
次の `describe-user` の例では、指定したディレクトリ内の指定したユーザーの情報を取得します。  

```
aws ds-data describe-user command-name \
    --directory-id d-1234567890 \
    --sam-account-name 'john.doe'
```
出力:  

```
{
    "DirectoryId": "d-1234567890",
    "DistinguishedName": "CN=john.doe,OU=Users,OU=CORP,DC=corp,DC=example,DC=com",
    "Enabled": false,
    "Realm": "corp.example.com",
    "SAMAccountName": "john.doe",
    "SID": "S-1-2-34-5678901234-5678901234-5678910123-4567",
    "UserPrincipalName": "john.doe@CORP.EXAMPLE.COM"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD ユーザーの表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_user.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*の「[DescribeUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/describe-user.html)」を参照してください。

### `disable-directory-data-access`
<a name="directory-service-data_DisableDirectoryDataAccess_cli_2_topic"></a>

次のコード例は、`disable-directory-data-access` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリの Directory Service Data API を無効にするには**  
次の `disable-directory-data-access` の例では、指定したディレクトリの Directory Service Data API を無効にします。  

```
aws ds disable-directory-data-access \
    --directory-id d-1234567890
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Directory Service 管理ガイド」の「ユーザーとグループの管理の有効化または無効化」または「 Directory Service データ](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_users_groups_mgmt_enable_disable.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DisableDirectoryDataAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/disable-directory-data-access.html)」を参照してください。

### `disable-user`
<a name="directory-service-data_DisableUser_cli_2_topic"></a>

次のコード例は、`disable-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを無効にするには**  
次の `disable-user` の例では、指定したディレクトリ内の指定したユーザーを無効にします。  

```
aws ds-data disable-user \
    --directory-id d-1234567890 \
    --sam-account-name 'john.doe'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 Directory Service 管理ガイド*[」の AWS 「 Managed Microsoft AD ユーザーの無効化](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_disable_user.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DisableUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/disable-user.html)」を参照してください。

### `enable-directory-data-access`
<a name="directory-service-data_EnableDirectoryDataAccess_cli_2_topic"></a>

次のコード例は、`enable-directory-data-access` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリの Directory Service Data API を有効にするには**  
次の `enable-directory-data-access` の例では、指定されたディレクトリの Directory Service Data API を有効にします。  

```
aws ds enable-directory-data-access \
    --directory-id d-1234567890
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Directory Service 管理ガイド」の「ユーザーとグループの管理の有効化または無効化」または「 Directory Service データ](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_users_groups_mgmt_enable_disable.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[EnableDirectoryDataAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/enable-directory-data-access.html)」を参照してください。

### `list-group-members`
<a name="directory-service-data_ListGroupMembers_cli_2_topic"></a>

次のコード例は、`list-group-members` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリのグループメンバーを一覧表示するには**  
次の `list-group-members` の例では、指定したディレクトリ内の指定したグループのグループメンバーを一覧表示します。  

```
aws ds-data list-group-members \
    --directory-id d-1234567890 \
    --sam-account-name 'sales'
```
出力:  

```
{
    "Members": [
        {
            "MemberType": "USER",
            "SAMAccountName": "Jane Doe",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4568"
        },
        {
            "MemberType": "USER",
            "SAMAccountName": "John Doe",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4569"
        }
    ],
    "DirectoryId": "d-1234567890",
    "MemberRealm": "corp.example.com",
    "Realm": "corp.example.com"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD グループの詳細の表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_group.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/list-group-members.html)」を参照してください。

### `list-groups-for-member`
<a name="directory-service-data_ListGroupsForMember_cli_2_topic"></a>

次のコード例は、`list-groups-for-member` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリのグループメンバーシップを一覧表示するには**  
次の `list-groups-for-member` の例では、指定したディレクトリ内の指定したユーザーのグループメンバーシップを一覧表示します。  

```
aws ds-data list-groups-for-member \
    --directory-id d-1234567890 \
    --sam-account-name 'john.doe'
```
出力:  

```
{
    "Groups": [
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Domain Users",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4567"
        }
    ],
    "DirectoryId": "d-1234567890",
    "MemberRealm": "corp.example.com",
    "Realm": "corp.example.com"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD ユーザーの表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_user.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListGroupsForMember](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/list-groups-for-member.html)」を参照してください。

### `list-groups`
<a name="directory-service-data_ListGroups_cli_2_topic"></a>

次のコード例は、`list-groups` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリのグループを一覧表示するには**  
次の `list-groups` の例では、指定したディレクトリ内のグループを一覧表示します。  

```
aws ds-data list-groups \
    --directory-id d-1234567890
```
出力:  

```
{
    "Groups": [
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Administrators",
            "SID": "S-1-2-33-441"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Users",
            "SID": "S-1-2-33-442"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Guests",
            "SID": "S-1-2-33-443"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Print Operators",
            "SID": "S-1-2-33-444"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Backup Operators",
            "SID": "S-1-2-33-445"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Replicator",
            "SID": "S-1-2-33-446"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Remote Desktop Users",
            "SID": "S-1-2-33-447"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Network Configuration Operators",
            "SID": "S-1-2-33-448"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Performance Monitor Users",
            "SID": "S-1-2-33-449"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Performance Log Users",
            "SID": "S-1-2-33-450"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Distributed COM Users",
            "SID": "S-1-2-33-451"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "IIS_IUSRS",
            "SID": "S-1-2-33-452"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Cryptographic Operators",
            "SID": "S-1-2-33-453"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Event Log Readers",
            "SID": "S-1-2-33-454"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Certificate Service DCOM Access",
            "SID": "S-1-2-33-456"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "RDS Remote Access Servers",
            "SID": "S-1-2-33-457"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "RDS Endpoint Servers",
            "SID": "S-1-2-33-458"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "RDS Management Servers",
            "SID": "S-1-2-33-459"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Hyper-V Administrators",
            "SID": "S-1-2-33-460"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Access Control Assistance Operators",
            "SID": "S-1-2-33-461"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Remote Management Users",
            "SID": "S-1-2-33-462"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Storage Replica Administrators",
            "SID": "S-1-2-33-463"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Domain Computers",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-789"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Domain Controllers",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-790"
        },
        {
            "GroupScope": "Universal",
            "GroupType": "Security",
            "SAMAccountName": "Schema Admins",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-791"
        },
        {
            "GroupScope": "Universal",
            "GroupType": "Security",
            "SAMAccountName": "Enterprise Admins",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-792"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "Cert Publishers",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-793"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Domain Admins",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-794"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Domain Users",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-795"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Domain Guests",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-796"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Group Policy Creator Owners",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-797"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "RAS and IAS Servers",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-798"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Server Operators",
            "SID": "S-1-2-33-464"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Account Operators",
            "SID": "S-1-2-33-465"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Pre-Windows 2000 Compatible Access",
            "SID": "S-1-2-33-466"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Incoming Forest Trust Builders",
            "SID": "S-1-2-33-467"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Windows Authorization Access Group",
            "SID": "S-1-2-33-468"
        },
        {
            "GroupScope": "BuiltinLocal",
            "GroupType": "Security",
            "SAMAccountName": "Terminal Server License Servers",
            "SID": "S-1-2-33-469"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "Allowed RODC Password Replication Group",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-798"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "Denied RODC Password Replication Group",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-799"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Read-only Domain Controllers",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-800"
        },
        {
            "GroupScope": "Universal",
            "GroupType": "Security",
            "SAMAccountName": "Enterprise Read-only Domain Controllers",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-801"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Cloneable Domain Controllers",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-802"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Protected Users",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-803"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Key Admins",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-804"
        },
        {
            "GroupScope": "Universal",
            "GroupType": "Security",
            "SAMAccountName": "Enterprise Key Admins",
            "SID": "S-1-2-34-56789123456-7891012345-6789123486-805"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "DnsAdmins",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4567"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "DnsUpdateProxy",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4568"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "Admins",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4569"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWSAdministrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4570"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Object Management Service Accounts",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4571"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Private CA Connector for AD Delegated Group",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4572"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Application and Service Delegated Group",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4573"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4574"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated FSx Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4575"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Account Operators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4576"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Active Directory Based Activation Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4577"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Allowed to Authenticate Objects",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4578"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Allowed to Authenticate to Domain Controllers",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4579"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Deleted Object Lifetime Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4580"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Distributed File System Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4581"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Dynamic Host Configuration Protocol Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4582"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Enterprise Certificate Authority Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4583"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Fine Grained Password Policy Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4584"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Group Policy Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4585"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Managed Service Account Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4586"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Read Foreign Security Principals",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4587"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Remote Access Service Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4588"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Replicate Directory Changes Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4588"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Sites and Services Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4589"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated System Management Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4590"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Terminal Server Licensing Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4591"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated User Principal Name Suffix Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4592"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Add Workstations To Domain Users",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4593"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Domain Name System Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4594"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Kerberos Delegation Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4595"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated Server Administrators",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4596"
        },
        {
            "GroupScope": "DomainLocal",
            "GroupType": "Security",
            "SAMAccountName": "AWS Delegated MS-NPRC Non-Compliant Devices",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4597"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Remote Access",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4598"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Security",
            "SAMAccountName": "Accounting",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4599"
        },
        {
            "GroupScope": "Global",
            "GroupType": "Distribution",
            "SAMAccountName": "sales",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4567"
        }
    ],
    "DirectoryId": "d-1234567890",
    "Realm": "corp.example.com"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD グループの詳細の表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_group.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/list-groups.html)」を参照してください。

### `list-users`
<a name="directory-service-data_ListUsers_cli_2_topic"></a>

次のコード例は、`list-users` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリのユーザーを一覧表示するには**  
次の `list-users` の例では、指定したディレクトリ内のユーザーを一覧表示します。  

```
aws ds-data list-users \
    --directory-id d-1234567890
```
出力:  

```
{
    "Users": [
        {
            "Enabled": true,
            "SAMAccountName": "Administrator",
            "SID": "S-1-2-34-5678910123-4567895012-3456789012-345"
        },
        {
            "Enabled": false,
            "SAMAccountName": "Guest",
            "SID": "S-1-2-34-5678910123-4567895012-3456789012-345"
        },
        {
            "Enabled": false,
            "SAMAccountName": "krbtgt",
            "SID": "S-1-2-34-5678910123-4567895012-3456789012-346"
        },
        {
            "Enabled": true,
            "SAMAccountName": "Admin",
            "SID": "S-1-2-34-5678910123-4567895012-3456789012-347"
        },
        {
            "Enabled": true,
            "SAMAccountName": "Richard Roe",
            "SID": "S-1-2-34-5678910123-4567895012-3456789012-348"
        },
        {
            "Enabled": true,
            "SAMAccountName": "Jane Doe",
            "SID": "S-1-2-34-5678910123-4567895012-3456789012-349"
        },
        {
            "Enabled": true,
            "SAMAccountName": "AWS_WGnzYlN6YyY",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4567"
        },
        {
            "Enabled": true,
            "SAMAccountName": "john.doe",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4568"
        }
    ],
    "DirectoryId": "d-1234567890",
    "Realm": "corp.example.com"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD ユーザーの表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_user.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/list-users.html)」を参照してください。

### `remove-group-member`
<a name="directory-service-data_RemoveGroupMember_cli_2_topic"></a>

次のコード例は、`remove-group-member` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリからグループメンバーを削除するには**  
次の `remove-group-member` の例では、指定したディレクトリ内の指定したグループから、指定したグループメンバーを削除します。  

```
aws ds-data remove-group-member \
    --directory-id d-1234567890 \
    --group-name 'sales' \
    --member-name 'john.doe'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 Directory Service 管理ガイド*」の「グループ[への AWS Managed Microsoft AD メンバーの追加と削除」および「グループへのグループ](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_add_remove_user_group.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[RemoveGroupMember](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/remove-group-member.html)」を参照してください。

### `reset-user-password`
<a name="directory-service-data_ResetUserPassword_cli_2_topic"></a>

次のコード例は、`reset-user-password` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリ内のユーザーパスワードをリセットするには**  
次の `reset-user-password` の例では、指定したディレクトリ内の指定したユーザーをリセットして有効にします。  

```
aws ds reset-user-password \
    --directory-id d-1234567890 \
    --user-name 'john.doe' \
    --new-password 'password'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 Directory Service 管理ガイド*[」の AWS 「 Managed Microsoft AD ユーザーのパスワードのリセットと有効化](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_reset_user_pswd.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ResetUserPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/reset-user-password.html)」を参照してください。

### `search-groups`
<a name="directory-service-data_SearchGroups_cli_2_topic"></a>

次のコード例は、`search-groups` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリ内のグループを検索するには**  
次の `search-groups` の例では、指定したディレクトリ内の指定したグループを検索します。  

```
aws ds-data search-groups \
    --directory-id d-1234567890 \
    --search-attributes 'SamAccountName' \
    --search-string 'sales'
```
出力:  

```
{
    "Groups": [
        {
            "GroupScope": "Global",
            "GroupType": "Distribution",
            "SAMAccountName": "sales",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4567"
        }
    ],
    "DirectoryId": "d-1234567890",
    "Realm": "corp.example.com"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD グループの詳細の表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_group.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[SearchGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/search-groups.html)」を参照してください。

### `search-users`
<a name="directory-service-data_SearchUsers_cli_2_topic"></a>

次のコード例は、`search-users` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリ内のユーザーを検索するには**  
次の `search-users` の例では、指定したディレクトリ内の指定したユーザーを検索します。  

```
aws ds-data search-users \
    --directory-id d-1234567890 \
    --search-attributes 'SamAccountName' \
    --Search-string 'john.doe'
```
出力:  

```
{
    "Users": [
        {
            "Enabled": true,
            "SAMAccountName": "john.doe",
            "SID": "S-1-2-34-5678901234-5678901234-5678910123-4567"
        }
    ],
    "DirectoryId": "d-1234567890",
    "Realm": "corp.example.com"
}
```
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD ユーザーの表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_user.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[SearchUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/search-users.html)」を参照してください。

### `update-group`
<a name="directory-service-data_UpdateGroup_cli_2_topic"></a>

次のコード例は、`update-group` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリ内のグループの属性を更新するには**  
次の `update-group` の例では、指定したディレクトリ内の指定したグループの指定した属性を更新します。  

```
aws ds-data update-group \
    --directory-id d-1234567890 \
    --sam-account-name 'sales' \
    --update-type 'REPLACE' \
    --group-type 'Distribution'
```
このコマンドでは何も出力されません。  
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD グループの詳細の表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_group.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/update-group.html)」を参照してください。

### `update-user`
<a name="directory-service-data_UpdateUser_cli_2_topic"></a>

次のコード例は、`update-user` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリ内のユーザーの属性を更新するには**  
次の `update-user` の例では、指定したディレクトリ内の指定したユーザーの指定した属性を更新します。  

```
aws ds-data update-user \
    --directory-id d-1234567890 \
    --sam-account-name 'john.doe' \
    --update-type 'ADD' \
    --email-address 'example.corp.com'
```
このコマンドでは何も出力されません。  
詳細については、[「 Directory Service 管理ガイド」の AWS 「 Managed Microsoft AD ユーザーの表示と更新](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_view_update_user.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/directory-service-data/update-user.html)」を参照してください。

# AWS DMS を使用した の例 AWS CLI
<a name="cli_2_database-migration-service_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS DMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags-to-resource`
<a name="database-migration-service_AddTagsToResource_cli_2_topic"></a>

次のコード例は、`add-tags-to-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加するには**  
次の `add-tags-to-resource` の例では、タグをレプリケーション インスタンスに追加しています。  

```
aws dms add-tags-to-resource \
    --resource-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE \
    --tags Key=Environment,Value=PROD Key=Project,Value=dbMigration
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Tagging Resources](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AddTagsToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/add-tags-to-resource.html)」を参照してください。

### `create-endpoint`
<a name="database-migration-service_CreateEndpoint_cli_2_topic"></a>

次のコード例は、`create-endpoint` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントを作成するには**  
次の `create-endpoint` の例では、Amazon S3 ソースのエンドポイントを作成しています。  

```
aws dms create-endpoint \
    --endpoint-type source \
    --engine-name s3 \
    --endpoint-identifier src-endpoint \
    --s3-settings file://s3-settings.json
```
`s3-settings.json` の内容:  

```
{
    "BucketName":"my-corp-data",
    "BucketFolder":"sourcedata",
    "ServiceAccessRoleArn":"arn:aws:iam::123456789012:role/my-s3-access-role"
}
```
出力:  

```
{
    "Endpoint": {
        "EndpointIdentifier": "src-endpoint",
        "EndpointType": "SOURCE",
        "EngineName": "s3",
        "EngineDisplayName": "Amazon S3",
        "ExtraConnectionAttributes": "bucketFolder=sourcedata;bucketName=my-corp-data;compressionType=NONE;csvDelimiter=,;csvRowDelimiter=\\n;",
        "Status": "active",
        "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:GUVAFG34EECUOJ6QVZ56DAHT3U",
        "SslMode": "none",
        "ServiceAccessRoleArn": "arn:aws:iam::123456789012:role/my-s3-access-role",
        "S3Settings": {
            "ServiceAccessRoleArn": "arn:aws:iam::123456789012:role/my-s3-access-role",
            "CsvRowDelimiter": "\\n",
            "CsvDelimiter": ",",
            "BucketFolder": "sourcedata",
            "BucketName": "my-corp-data",
            "CompressionType": "NONE",
            "EnableStatistics": true
        }
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*」の[「DMS AWS エンドポイントの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/create-endpoint.html)」を参照してください。

### `create-event-subscription`
<a name="database-migration-service_CreateEventSubscription_cli_2_topic"></a>

次のコード例は、`create-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを一覧表示するには**  
次の `create-event-subscription` の例では、Amazon SNS トピック (my-sns-topic) へのイベントサブスクリプションを作成しています。  

```
aws dms create-event-subscription \
    --subscription-name my-dms-events \
    --sns-topic-arn arn:aws:sns:us-east-1:123456789012:my-sns-topic
```
出力:  

```
{
    "EventSubscription": {
        "CustomerAwsId": "123456789012",
        "CustSubscriptionId": "my-dms-events",
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:my-sns-topic",
        "Status": "creating",
        "SubscriptionCreationTime": "2020-05-21 21:58:38.598",
        "Enabled": true
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Working with Events and Notifications](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/create-event-subscription.html)」を参照してください。

### `create-replication-instance`
<a name="database-migration-service_CreateReplicationInstance_cli_2_topic"></a>

次のコード例は、`create-replication-instance` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションインスタンスを作成するには**  
次の `create-replication-instance` の例では、レプリケーションインスタンスを作成しています。  

```
aws dms create-replication-instance \
    --replication-instance-identifier my-repl-instance \
    --replication-instance-class dms.t2.micro \
    --allocated-storage 5
```
出力:  

```
{
    "ReplicationInstance": {
        "ReplicationInstanceIdentifier": "my-repl-instance",
        "ReplicationInstanceClass": "dms.t2.micro",
        "ReplicationInstanceStatus": "creating",
        "AllocatedStorage": 5,
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-f839b688",
                "Status": "active"
            }
        ],
        "ReplicationSubnetGroup": {
            "ReplicationSubnetGroupIdentifier": "default",
            "ReplicationSubnetGroupDescription": "default",
            "VpcId": "vpc-136a4c6a",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-da327bf6",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-42599426",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1d"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-bac383e0",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1c"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-6746046b",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1f"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-d7c825e8",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1e"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-cbfff283",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1b"
                    },
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "sat:12:35-sat:13:05",
        "PendingModifiedValues": {},
        "MultiAZ": false,
        "EngineVersion": "3.3.2",
        "AutoMinorVersionUpgrade": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/f7bc0f8e-1a3a-4ace-9faa-e8494fa3921a",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:ZK2VQBUWFDBAWHIXHAYG5G2PKY",
        "PubliclyAccessible": true
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS レプリケーションインスタンスの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReplicationInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/create-replication-instance.html)」を参照してください。

### `create-replication-subnet-group`
<a name="database-migration-service_CreateReplicationSubnetGroup_cli_2_topic"></a>

次のコード例は、`create-replication-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループを作成するには**  
次の `create-replication-subnet-group` の例では、3 つのサブネットで構成されるグループを作成しています。  

```
aws dms create-replication-subnet-group \
    --replication-subnet-group-identifier my-subnet-group \
    --replication-subnet-group-description "my subnet group" \
    --subnet-ids subnet-da327bf6 subnet-bac383e0 subnet-d7c825e8
```
出力:  

```
{
    "ReplicationSubnetGroup": {
        "ReplicationSubnetGroupIdentifier": "my-subnet-group",
        "ReplicationSubnetGroupDescription": "my subnet group",
        "VpcId": "vpc-136a4c6a",
        "SubnetGroupStatus": "Complete",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-da327bf6",
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1a"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-bac383e0",
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1c"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-d7c825e8",
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1e"
                },
                "SubnetStatus": "Active"
            }
        ]
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Setting Up a Network for a Replication Instance](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.VPC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReplicationSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/create-replication-subnet-group.html)」を参照してください。

### `create-replication-task`
<a name="database-migration-service_CreateReplicationTask_cli_2_topic"></a>

次のコード例は、`create-replication-task` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションタスクを作成するには**  
次の `create-replication-task` の例では、レプリケーションタスクを作成しています。  

```
aws dms create-replication-task \
    --replication-task-identifier movedata \
    --source-endpoint-arn arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA \
    --target-endpoint-arn arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U \
    --replication-instance-arn $RI_ARN \
    --migration-type full-load \
    --table-mappings file://table-mappings.json
```
`table-mappings.json` の内容:  

```
{
    "rules": [
        {
            "rule-type": "selection",
            "rule-id": "1",
            "rule-name": "1",
            "object-locator": {
                "schema-name": "prodrep",
                "table-name": "%"
            },
            "rule-action": "include",
            "filters": []
        }
    ]
}
```
出力:  

```
{
    "ReplicationTask": {
        "ReplicationTaskIdentifier": "moveit2",
        "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "MigrationType": "full-load",
        "TableMappings": ...output omitted... ,
        "ReplicationTaskSettings": ...output omitted... ,
        "Status": "creating",
        "ReplicationTaskCreationDate": 1590524772.505,
        "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII"
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS タスクの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReplicationTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/create-replication-task.html)」を参照してください。

### `delete-connection`
<a name="database-migration-service_DeleteConnection_cli_2_topic"></a>

次のコード例は、`delete-connection` を使用する方法を示しています。

**AWS CLI**  
**接続を削除するには**  
次の `delete-connection` の例では、レプリケーションインスタンスからエンドポイントの関連付けを解除しています。  

```
aws dms delete-connection \
    --endpoint-arn arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA \
    --replication-instance-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE
```
出力:  

```
{
    "Connection": {
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "Status": "deleting",
        "EndpointIdentifier": "src-database-1",
        "ReplicationInstanceIdentifier": "my-repl-instance"
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の [https://docs.aws.amazon.com/dms/latest/userguide/CHAP\$1Endpoints.Creating.html](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Endpoints.Creating.html) を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/delete-connection.html)」を参照してください。

### `delete-endpoint`
<a name="database-migration-service_DeleteEndpoint_cli_2_topic"></a>

次のコード例は、`delete-endpoint` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントを削除するには**  
次の `delete-endpoint` の例では、エンドポイントを削除しています。  

```
aws dms delete-endpoint \
    --endpoint-arn arn:aws:dms:us-east-1:123456789012:endpoint:OUJJVXO4XZ4CYTSEG5XGMN2R3Y
```
出力:  

```
{
    "Endpoint": {
        "EndpointIdentifier": "src-endpoint",
        "EndpointType": "SOURCE",
        "EngineName": "s3",
        "EngineDisplayName": "Amazon S3",
        "ExtraConnectionAttributes": "bucketFolder=sourcedata;bucketName=my-corp-data;compressionType=NONE;csvDelimiter=,;csvRowDelimiter=\\n;",
        "Status": "deleting",
        "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:OUJJVXO4XZ4CYTSEG5XGMN2R3Y",
        "SslMode": "none",
        "ServiceAccessRoleArn": "arn:aws:iam::123456789012:role/my-s3-access-role",
        "S3Settings": {
            "ServiceAccessRoleArn": "arn:aws:iam::123456789012:role/my-s3-access-role",
            "CsvRowDelimiter": "\\n",
            "CsvDelimiter": ",",
            "BucketFolder": "sourcedata",
            "BucketName": "my-corp-data",
            "CompressionType": "NONE",
            "EnableStatistics": true
        }
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*」の[「DMS AWS エンドポイントの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/delete-endpoint.html)」を参照してください。

### `delete-event-subscription`
<a name="database-migration-service_DeleteEventSubscription_cli_2_topic"></a>

次のコード例は、`delete-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを削除するには**  
次の `delete-event-subscription` の例では、Amazon SNS トピックへのサブスクリプションを削除しています。  

```
aws dms delete-event-subscription \
    --subscription-name "my-dms-events"
```
出力:  

```
{
    "EventSubscription": {
        "CustomerAwsId": "123456789012",
        "CustSubscriptionId": "my-dms-events",
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:my-sns-topic",
        "Status": "deleting",
        "SubscriptionCreationTime": "2020-05-21 21:58:38.598",
        "Enabled": true
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Working with Events and Notifications](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/delete-event-subscription.html)」を参照してください。

### `delete-replication-instance`
<a name="database-migration-service_DeleteReplicationInstance_cli_2_topic"></a>

次のコード例は、`delete-replication-instance` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションインスタンスを削除するには**  
次の `delete-replication-instance` の例では、レプリケーション インスタンスを削除します。  

```
aws dms delete-replication-instance \
    --replication-instance-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE
```
出力:  

```
{
    "ReplicationInstance": {
        "ReplicationInstanceIdentifier": "my-repl-instance",
        "ReplicationInstanceClass": "dms.t2.micro",
        "ReplicationInstanceStatus": "deleting",
        "AllocatedStorage": 5,
        "InstanceCreateTime": 1590011235.952,
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-f839b688",
                "Status": "active"
            }
        ],
        "AvailabilityZone": "us-east-1e",
        "ReplicationSubnetGroup": {
            "ReplicationSubnetGroupIdentifier": "default",
            "ReplicationSubnetGroupDescription": "default",
            "VpcId": "vpc-136a4c6a",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-da327bf6",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-42599426",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1d"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-bac383e0",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1c"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-6746046b",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1f"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-d7c825e8",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1e"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-cbfff283",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1b"
                    },
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "wed:11:42-wed:12:12",
        "PendingModifiedValues": {},
        "MultiAZ": true,
        "EngineVersion": "3.3.2",
        "AutoMinorVersionUpgrade": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/f7bc0f8e-1a3a-4ace-9faa-e8494fa3921a",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "ReplicationInstancePublicIpAddress": "54.225.120.92",
        "ReplicationInstancePrivateIpAddress": "172.31.30.121",
        "ReplicationInstancePublicIpAddresses": [
            "54.225.120.92",
            "3.230.18.248"
        ],
        "ReplicationInstancePrivateIpAddresses": [
            "172.31.30.121",
            "172.31.75.90"
        ],
        "PubliclyAccessible": true,
        "SecondaryAvailabilityZone": "us-east-1b"
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS レプリケーションインスタンスの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReplicationInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/delete-replication-instance.html)」を参照してください。

### `delete-replication-subnet-group`
<a name="database-migration-service_DeleteReplicationSubnetGroup_cli_2_topic"></a>

次のコード例は、`delete-replication-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループを削除するには**  
次の `delete-replication-subnet-group` の例では、サブネットグループを削除しています。  

```
aws dms delete-replication-subnet-group \
--replication-subnet-group-identifier my-subnet-group
```
出力:  

```
(none)
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Setting Up a Network for a Replication Instance](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.VPC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReplicationSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/delete-replication-subnet-group.html)」を参照してください。

### `delete-replication-task`
<a name="database-migration-service_DeleteReplicationTask_cli_2_topic"></a>

次のコード例は、`delete-replication-task` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションタスクを削除するには**  
次の `delete-replication-task` の例では、レプリケーションタスクを削除しています。  

```
aws dms delete-replication-task \
    --replication-task-arn arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII
```
出力:  

```
{
    "ReplicationTask": {
        "ReplicationTaskIdentifier": "moveit2",
        "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "MigrationType": "full-load",
        "TableMappings": ...output omitted...,
        "ReplicationTaskSettings": ...output omitted...,
        "Status": "deleting",
        "StopReason": "Stop Reason FULL_LOAD_ONLY_FINISHED",
        "ReplicationTaskCreationDate": 1590524772.505,
        "ReplicationTaskStartDate": 1590789988.677,
        "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII"
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS タスクの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReplicationTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/delete-replication-task.html)」を参照してください。

### `describe-account-attributes`
<a name="database-migration-service_DescribeAccountAttributes_cli_2_topic"></a>

次のコード例は、`describe-account-attributes` を使用する方法を示しています。

**AWS CLI**  
**アカウントの属性を記述するには**  
次の の`describe-account-attributes`例では、 AWS アカウントの属性を一覧表示します。  

```
aws dms describe-account-attributes
```
出力:  

```
{
    "AccountQuotas": [
        {
            "AccountQuotaName": "ReplicationInstances",
            "Used": 1,
            "Max": 20
        },
        {
            "AccountQuotaName": "AllocatedStorage",
            "Used": 5,
            "Max": 10000
        },

        ...remaining output omitted...

    ],
    "UniqueAccountIdentifier": "cqahfbfy5xee"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-account-attributes.html)」を参照してください。

### `describe-certificates`
<a name="database-migration-service_DescribeCertificates_cli_2_topic"></a>

次のコード例は、`describe-certificates` を使用する方法を示しています。

**AWS CLI**  
**使用可能な証明書を一覧表示するには**  
次の の`describe-certificates`例では、 AWS アカウントで使用可能な証明書を一覧表示します。  

```
aws dms describe-certificates
```
出力:  

```
{
    "Certificates": [
        {
            "CertificateIdentifier": "my-cert",
            "CertificateCreationDate": 1543259542.506,
            "CertificatePem": "-----BEGIN CERTIFICATE-----\nMIID9DCCAtygAwIBAgIBQjANBgkqhkiG9w0BAQ ...U"

            ... remaining output omittted ...

        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Using SSL](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Security.html#CHAP_Security.SSL)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-certificates.html)」を参照してください。

### `describe-connections`
<a name="database-migration-service_DescribeConnections_cli_2_topic"></a>

次のコード例は、`describe-connections` を使用する方法を示しています。

**AWS CLI**  
**接続を記述するには**  
次の `describe-connections` の例では、レプリケーションインスタンスとエンドポイント間でテストした接続を一覧表示しています。  

```
aws dms describe-connections
```
出力:  

```
{
    "Connections": [
        {
            "Status": "successful",
            "ReplicationInstanceIdentifier": "test",
            "EndpointArn": "arn:aws:dms:us-east-arn:aws:dms:us-east-1:123456789012:endpoint:ZW5UAN6P4E77EC7YWHK4RZZ3BE",
            "EndpointIdentifier": "testsrc1",
            "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:6UTDJGBOUS3VI3SUWA66XFJCJQ"
        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Creating Source and Target Endpoints](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Endpoints.Creating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-connections.html)」を参照してください。

### `describe-endpoint-types`
<a name="database-migration-service_DescribeEndpointTypes_cli_2_topic"></a>

次のコード例は、`describe-endpoint-types` を使用する方法を示しています。

**AWS CLI**  
**使用可能なエンドポイントタイプを一覧表示するには**  
次の `describe-endpoint-types` の例では、使用可能な MySQL エンドポイントタイプを一覧表示しています。  

```
aws dms describe-endpoint-types \
    --filters "Name=engine-name,Values=mysql"
```
出力:  

```
{
    "SupportedEndpointTypes": [
        {
            "EngineName": "mysql",
            "SupportsCDC": true,
            "EndpointType": "source",
            "EngineDisplayName": "MySQL"
        },
        {
            "EngineName": "mysql",
            "SupportsCDC": true,
            "EndpointType": "target",
            "EngineDisplayName": "MySQL"
        }
    ]
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*」の「Working with AWS DMS Endpoints <https://docs.aws.amazon.com/dms/latest/userguide/CHAP\$1Endpoints.html>`\$1\$1」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEndpointTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-endpoint-types.html)」を参照してください。

### `describe-endpoints`
<a name="database-migration-service_DescribeEndpoints_cli_2_topic"></a>

次のコード例は、`describe-endpoints` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントを記述するには**  
次の の`describe-endpoints`例では、 AWS アカウントのエンドポイントを一覧表示します。  

```
aws dms describe-endpoints
```
出力:  

```
{
    "Endpoints": [
        {
            "Username": "dms",
            "Status": "active",
            "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:SF2WOFLWYWKVEOHID2EKLP3SJI",
            "ServerName": "ec2-52-32-48-61.us-west-2.compute.amazonaws.com",
            "EndpointType": "SOURCE",
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/94d5c4e7-4e4c-44be-b58a-c8da7adf57cd",
            "DatabaseName": "test",
            "EngineName": "mysql",
            "EndpointIdentifier": "pri100",
            "Port": 8193
        },
        {
            "Username": "admin",
            "Status": "active",
            "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:TJJZCIH3CJ24TJRU4VC32WEWFR",
            "ServerName": "test.example.com",
            "EndpointType": "SOURCE",
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/2431021b-1cf2-a2d4-77b2-59a9e4bce323",
            "DatabaseName": "EMPL",
            "EngineName": "oracle",
            "EndpointIdentifier": "test",
            "Port": 1521
        }
    ]
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*」の[「DMS AWS エンドポイントの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-endpoints.html)」を参照してください。

### `describe-event-categories`
<a name="database-migration-service_DescribeEventCategories_cli_2_topic"></a>

次のコード例は、`describe-event-categories` を使用する方法を示しています。

**AWS CLI**  
**イベントカテゴリを記述するには**  
次の `describe-event-categories` の例では、使用可能なイベントカテゴリを一覧表示しています。  

```
aws dms describe-event-categories
```
出力:  

```
{
    "EventCategoryGroupList": [
        {
            "SourceType": "replication-instance",
            "EventCategories": [
                "low storage",
                "configuration change",
                "maintenance",
                "deletion",
                "creation",
                "failover",
                "failure"
            ]
        },
        {
            "SourceType": "replication-task",
            "EventCategories": [
                "configuration change",
                "state change",
                "deletion",
                "creation",
                "failure"
            ]
        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Working with Events and Notifications](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventCategories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-event-categories.html)」を参照してください。

### `describe-event-subscriptions`
<a name="database-migration-service_DescribeEventSubscriptions_cli_2_topic"></a>

次のコード例は、`describe-event-subscriptions` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを記述するには**  
次の `describe-event-subscriptions` の例では、Amazon SNS トピックへのイベントサブスクリプションを一覧表示しています。  

```
aws dms describe-event-subscriptions
```
出力:  

```
{
    "EventSubscriptionsList": [
        {
            "CustomerAwsId": "123456789012",
            "CustSubscriptionId": "my-dms-events",
            "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:my-sns-topic",
            "Status": "deleting",
            "SubscriptionCreationTime": "2020-05-21 22:28:51.924",
            "Enabled": true
        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Working with Events and Notifications](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventSubscriptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-event-subscriptions.html)」を参照してください。

### `describe-events`
<a name="database-migration-service_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
**DMS イベントを一覧表示するには**  
次の `describe-events` の例では、レプリケーションインスタンスから発生したイベントを一覧表示しています。  

```
aws dms describe-events \
    --source-type "replication-instance"
```
出力:  

```
{
    "Events": [
        {
            "SourceIdentifier": "my-repl-instance",
            "SourceType": "replication-instance",
            "Message": "Replication application shutdown",
            "EventCategories": [],
            "Date": 1590771645.776
        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Working with Events and Notifications](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-events.html)」を参照してください。

### `describe-orderable-replication-instances`
<a name="database-migration-service_DescribeOrderableReplicationInstances_cli_2_topic"></a>

次のコード例は、`describe-orderable-replication-instances` を使用する方法を示しています。

**AWS CLI**  
**指示設定が可能なレプリケーションインスタンスを記述するには**  
次の `describe-orderable-replication-instances` の例では、指示設定が可能なレプリケーションインスタンスタイプを一覧表示しています。  

```
aws dms describe-orderable-replication-instances
```
出力:  

```
{
    "OrderableReplicationInstances": [
        {
            "EngineVersion": "3.3.2",
            "ReplicationInstanceClass": "dms.c4.2xlarge",
            "StorageType": "gp2",
            "MinAllocatedStorage": 5,
            "MaxAllocatedStorage": 6144,
            "DefaultAllocatedStorage": 100,
            "IncludedAllocatedStorage": 100,
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
                "us-east-1f"
            ]
        },
        {
            "EngineVersion": "3.3.2",
            "ReplicationInstanceClass": "dms.c4.4xlarge",
            "StorageType": "gp2",
            "MinAllocatedStorage": 5,
            "MaxAllocatedStorage": 6144,
            "DefaultAllocatedStorage": 100,
            "IncludedAllocatedStorage": 100,
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
                "us-east-1f"
            ]
        },

        ...remaining output omitted...

    }
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS レプリケーションインスタンスの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOrderableReplicationInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-orderable-replication-instances.html)」を参照してください。

### `describe-refresh-schemas-status`
<a name="database-migration-service_DescribeRefreshSchemasStatus_cli_2_topic"></a>

次のコード例は、`describe-refresh-schemas-status` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントの更新ステータスを一覧表示するには**  
次の `describe-refresh-schemas-status` の例では、以前の更新リクエストのステータスを返しています。  

```
aws dms describe-refresh-schemas-status \
    --endpoint-arn arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA
```
出力:  

```
{
    "RefreshSchemasStatus": {
        "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "Status": "successful",
        "LastRefreshDate": 1590786544.605
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRefreshSchemasStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-refresh-schemas-status.html)」を参照してください。

### `describe-replication-instances`
<a name="database-migration-service_DescribeReplicationInstances_cli_2_topic"></a>

次のコード例は、`describe-replication-instances` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションインスタンスを記述するには**  
次の の`describe-replication-instances`例では、 AWS アカウントのレプリケーションインスタンスを一覧表示します。  

```
aws dms describe-replication-instances
```
出力:  

```
{
    "ReplicationInstances": [
        {
            "ReplicationInstanceIdentifier": "my-repl-instance",
            "ReplicationInstanceClass": "dms.t2.micro",
            "ReplicationInstanceStatus": "available",
            "AllocatedStorage": 5,
            "InstanceCreateTime": 1590011235.952,
            "VpcSecurityGroups": [
                {
                    "VpcSecurityGroupId": "sg-f839b688",
                    "Status": "active"
                }
            ],
            "AvailabilityZone": "us-east-1e",
            "ReplicationSubnetGroup": {
                "ReplicationSubnetGroupIdentifier": "default",
                "ReplicationSubnetGroupDescription": "default",
                "VpcId": "vpc-136a4c6a",
                "SubnetGroupStatus": "Complete",
                "Subnets": [
                    {
                        "SubnetIdentifier": "subnet-da327bf6",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1a"
                        },
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-42599426",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1d"
                        },
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-bac383e0",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1c"
                        },
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-6746046b",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1f"
                        },
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-d7c825e8",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1e"
                        },
                        "SubnetStatus": "Active"
                    },
                    {
                        "SubnetIdentifier": "subnet-cbfff283",
                        "SubnetAvailabilityZone": {
                            "Name": "us-east-1b"
                        },
                        "SubnetStatus": "Active"
                    }
                ]
            },
            "PreferredMaintenanceWindow": "wed:11:42-wed:12:12",
            "PendingModifiedValues": {
                "MultiAZ": true
            },
            "MultiAZ": false,
            "EngineVersion": "3.3.2",
            "AutoMinorVersionUpgrade": true,
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/f7bc0f8e-1a3a-4ace-9faa-e8494fa3921a",
            "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
            "ReplicationInstancePublicIpAddress": "3.230.18.248",
            "ReplicationInstancePrivateIpAddress": "172.31.75.90",
            "ReplicationInstancePublicIpAddresses": [
                "3.230.18.248"
            ],
            "ReplicationInstancePrivateIpAddresses": [
                "172.31.75.90"
            ],
            "PubliclyAccessible": true,
            "FreeUntil": 1590194829.267
        }
    ]
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS レプリケーションインスタンスの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReplicationInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-replication-instances.html)」を参照してください。

### `describe-replication-subnet-groups`
<a name="database-migration-service_DescribeReplicationSubnetGroups_cli_2_topic"></a>

次のコード例は、`describe-replication-subnet-groups` を使用する方法を示しています。

**AWS CLI**  
**使用可能なサブネットグループを表示するには**  
次の `describe-replication-subnet-groups` の例では、使用可能なサブネットグループを一覧表示しています。  

```
aws dms describe-replication-subnet-groups \
    --filter "Name=replication-subnet-group-id,Values=my-subnet-group"
```
出力:  

```
{
    "ReplicationSubnetGroups": [
        {
            "ReplicationSubnetGroupIdentifier": "my-subnet-group",
            "ReplicationSubnetGroupDescription": "my subnet group",
            "VpcId": "vpc-136a4c6a",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-da327bf6",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-bac383e0",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1c"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-d7c825e8",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1e"
                    },
                    "SubnetStatus": "Active"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Setting Up a Network for a Replication Instance](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.VPC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReplicationSubnetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-replication-subnet-groups.html)」を参照してください。

### `describe-replication-task-assessment-results`
<a name="database-migration-service_DescribeReplicationTaskAssessmentResults_cli_2_topic"></a>

次のコード例は、`describe-replication-task-assessment-results` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションタスク評価の結果を一覧表示するには**  
次の `describe-replication-task-assessment-results` の例では、以前のタスク評価の結果を一覧表示しています。  

```
aws dms describe-replication-task-assessment-results
```
出力:  

```
{
    "ReplicationTaskAssessmentResults": [
        {
            "ReplicationTaskIdentifier": "moveit2",
            "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII",
            "ReplicationTaskLastAssessmentDate": 1590790230.0,
            "AssessmentStatus": "No issues found",
            "AssessmentResultsFile": "moveit2/2020-05-29-22-10"
        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Creating a Task Assessment Report](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.AssessmentReport.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReplicationTaskAssessmentResults](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-replication-task-assessment-results.html)」を参照してください。

### `describe-replication-tasks`
<a name="database-migration-service_DescribeReplicationTasks_cli_2_topic"></a>

次のコード例は、`describe-replication-tasks` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションタスクを記述するには**  
次の `describe-replication-tasks` の例では、現在のレプリケーションタスクについて表示しています。  

```
aws dms describe-replication-tasks
```
出力:  

```
{
    "ReplicationTasks": [
        {
            "ReplicationTaskIdentifier": "moveit2",
            "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
            "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U",
            "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
            "MigrationType": "full-load",
            "TableMappings": ...output omitted... ,
            "ReplicationTaskSettings": ...output omitted... ,
            "Status": "stopped",
            "StopReason": "Stop Reason FULL_LOAD_ONLY_FINISHED",
            "ReplicationTaskCreationDate": 1590524772.505,
            "ReplicationTaskStartDate": 1590619805.212,
            "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII",
            "ReplicationTaskStats": {
                "FullLoadProgressPercent": 100,
                "ElapsedTimeMillis": 0,
                "TablesLoaded": 0,
                "TablesLoading": 0,
                "TablesQueued": 0,
                "TablesErrored": 0,
                "FreshStartDate": 1590619811.528,
                "StartDate": 1590619811.528,
                "StopDate": 1590619842.068
            }
        }
    ]
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS タスクの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReplicationTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-replication-tasks.html)」を参照してください。

### `describe-schemas`
<a name="database-migration-service_DescribeSchemas_cli_2_topic"></a>

次の例は、`describe-schemas` を使用する方法を説明しています。

**AWS CLI**  
**データベーススキーマについて表示するには**  
次の `describe-schemas` の例では、エンドポイントで使用可能なテーブルを一覧表示しています。  

```
aws dms describe-schemas \
    --endpoint-arn "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA"
```
出力:  

```
{
    "Schemas": [
        "prodrep"
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[This is the topic title](https://link.to.the/topic/page)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSchemas](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/describe-schemas.html)」を参照してください。

### `list-tags-for-resource`
<a name="database-migration-service_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、レプリケーションインスタンスのタグを一覧表示しています。  

```
aws dms list-tags-for-resource \
    --resource-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE
```
出力:  

```
{
    "TagList": [
        {
            "Key": "Project",
            "Value": "dbMigration"
        },
        {
            "Key": "Environment",
            "Value": "PROD"
        }
    ]
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Tagging Resources](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/list-tags-for-resource.html)」を参照してください。

### `modify-endpoint`
<a name="database-migration-service_ModifyEndpoint_cli_2_topic"></a>

次のコード例は、`modify-endpoint` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントを変更するには**  
次の `modify-endpoint` の例では、エンドポイントに追加の接続属性を設定しています。  

```
aws dms modify-endpoint \
    --endpoint-arn "arn:aws:dms:us-east-1:123456789012:endpoint:GUVAFG34EECUOJ6QVZ56DAHT3U" \
    --extra-connection-attributes "compressionType=GZIP"
```
出力:  

```
{
    "Endpoint": {
        "EndpointIdentifier": "src-endpoint",
        "EndpointType": "SOURCE",
        "EngineName": "s3",
        "EngineDisplayName": "Amazon S3",
        "ExtraConnectionAttributes": "compressionType=GZIP;csvDelimiter=,;csvRowDelimiter=\\n;",
        "Status": "active",
        "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:GUVAFG34EECUOJ6QVZ56DAHT3U",
        "SslMode": "none",
        "ServiceAccessRoleArn": "arn:aws:iam::123456789012:role/my-s3-access-role",
        "S3Settings": {
            "ServiceAccessRoleArn": "arn:aws:iam::123456789012:role/my-s3-access-role",
            "CsvRowDelimiter": "\\n",
            "CsvDelimiter": ",",
            "BucketFolder": "",
            "BucketName": "",
            "CompressionType": "GZIP",
            "EnableStatistics": true
        }
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*」の「Working with AWS DMS Endpoints <https://docs.aws.amazon.com/dms/latest/userguide/CHAP\$1Endpoints.html>`\$1\$1」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/modify-endpoint.html)」を参照してください。

### `modify-event-subscription`
<a name="database-migration-service_ModifyEventSubscription_cli_2_topic"></a>

次のコード例は、`modify-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを変更するには**  
次の `modify-event-subscription` の例では、イベントサブスクリプションのソースタイプを変更しています。  

```
aws dms modify-event-subscription \
    --subscription-name "my-dms-events" \
    --source-type replication-task
```
出力:  

```
{
    "EventSubscription": {
        "CustomerAwsId": "123456789012",
        "CustSubscriptionId": "my-dms-events",
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:my-sns-topic",
        "Status": "modifying",
        "SubscriptionCreationTime": "2020-05-29 17:04:40.262",
        "SourceType": "replication-task",
        "Enabled": true
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Working with Events and Notifications](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/modify-event-subscription.html)」を参照してください。

### `modify-replication-instance`
<a name="database-migration-service_ModifyReplicationInstance_cli_2_topic"></a>

次のコード例は、`modify-replication-instance` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションインスタンスを変更するには**  
次の `modify-replication-instance` の例では、マルチ AZ 配置を使用するようにレプリケーションインスタンスを変更しています。  

```
aws dms modify-replication-instance \
     --replication-instance-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE \
     --multi-az
```
出力:  

```
{
    "ReplicationInstance": {
        "ReplicationInstanceIdentifier": "my-repl-instance",
        "ReplicationInstanceClass": "dms.t2.micro",
        "ReplicationInstanceStatus": "available",
        "AllocatedStorage": 5,
        "InstanceCreateTime": 1590011235.952,

        ...output omitted...

        "PendingModifiedValues": {
            "MultiAZ": true
        },
        "MultiAZ": false,
        "EngineVersion": "3.3.2",
        "AutoMinorVersionUpgrade": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/f7bc0f8e-1a3a-4ace-9faa-e8494fa3921a",

        ...output omitted...

    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS レプリケーションインスタンスの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyReplicationInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/modify-replication-instance.html)」を参照してください。

### `modify-replication-subnet-group`
<a name="database-migration-service_ModifyReplicationSubnetGroup_cli_2_topic"></a>

次のコード例は、`modify-replication-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループを変更するには**  
次の `modify-replication-subnet-group` の例では、サブネットグループに関連付けられているサブネットのリストを変更しています。  

```
aws dms modify-replication-subnet-group \
    --replication-subnet-group-identifier my-subnet-group \
    --subnet-id subnet-da327bf6 subnet-bac383e0
```
出力:  

```
{
    "ReplicationSubnetGroup": {
        "ReplicationSubnetGroupIdentifier": "my-subnet-group",
        "ReplicationSubnetGroupDescription": "my subnet group",
        "VpcId": "vpc-136a4c6a",
        "SubnetGroupStatus": "Complete",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-da327bf6",
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1a"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-bac383e0",
                "SubnetAvailabilityZone": {
                    "Name": "us-east-1c"
                },
                "SubnetStatus": "Active"
            }
        ]
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Setting Up a Network for a Replication Instance](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.VPC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyReplicationSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/modify-replication-subnet-group.html)」を参照してください。

### `modify-replication-task`
<a name="database-migration-service_ModifyReplicationTask_cli_2_topic"></a>

次のコード例は、`modify-replication-task` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションタスクを変更するには**  
次の `modify-replication-task` の例では、タスクのテーブルマッピングを変更します。  

```
aws dms modify-replication-task \
    --replication-task-arn "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII" \
    --table-mappings file://table-mappings.json
```
`table-mappings.json` の内容:  

```
{
    "rules": [
        {
            "rule-type": "selection",
            "rule-id": "1",
            "rule-name": "1",
            "object-locator": {
                "schema-name": "prodrep",
                "table-name": "ACCT_%"
            },
            "rule-action": "include",
            "filters": []
        }
    ]
}
```
出力:  

```
{
    "ReplicationTask": {
        "ReplicationTaskIdentifier": "moveit2",
        "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "MigrationType": "full-load",
        "TableMappings": ...output omitted...,
        "ReplicationTaskSettings": ...output omitted...,
        "Status": "modifying",
        "StopReason": "Stop Reason FULL_LOAD_ONLY_FINISHED",
        "ReplicationTaskCreationDate": 1590524772.505,
        "ReplicationTaskStartDate": 1590789424.653,
        "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII"
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS タスクの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyReplicationTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/modify-replication-task.html)」を参照してください。

### `reboot-replication-instance`
<a name="database-migration-service_RebootReplicationInstance_cli_2_topic"></a>

次のコード例は、`reboot-replication-instance` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションインスタンスを再起動するには**  
次の `reboot-replication-instance` の例では、レプリケーション インスタンスを再起動します。  

```
aws dms reboot-replication-instance \
    --replication-instance-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE
```
出力:  

```
{
    "ReplicationInstance": {
        "ReplicationInstanceIdentifier": "my-repl-instance",
        "ReplicationInstanceClass": "dms.t2.micro",
        "ReplicationInstanceStatus": "rebooting",
        "AllocatedStorage": 5,
        "InstanceCreateTime": 1590011235.952,
    ... output omitted ...
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS レプリケーションインスタンスの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_ReplicationInstance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootReplicationInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/reboot-replication-instance.html)」を参照してください。

### `refresh-schemas`
<a name="database-migration-service_RefreshSchemas_cli_2_topic"></a>

次のコード例は、`refresh-schemas` を使用する方法を示しています。

**AWS CLI**  
**データベーススキーマを更新するには**  
次の`refresh-schemas`例では、DMS AWS がエンドポイントのスキーマのリストを更新するようにリクエストします。  

```
aws dms refresh-schemas \
    --replication-instance-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE \
    --endpoint-arn "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA"
```
出力:  

```
{
    "RefreshSchemasStatus": {
        "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "Status": "refreshing",
        "LastRefreshDate": 1590019949.103
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RefreshSchemas](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/refresh-schemas.html)」を参照してください。

### `reload-tables`
<a name="database-migration-service_ReloadTables_cli_2_topic"></a>

次のコード例は、`reload-tables` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントで使用可能なテーブルのリストを更新するには**  
次の `reload-tables` の例では、エンドポイントで使用可能なテーブルのリストを再ロードしています。  

```
aws dms reload-tables \
    --replication-task-arn "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII" \
    --tables-to-reload "SchemaName=prodrep,TableName=ACCT_BAL"
```
出力:  

```
{
    "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReloadTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/reload-tables.html)」を参照してください。

### `remove-tags-from-resource`
<a name="database-migration-service_RemoveTagsFromResource_cli_2_topic"></a>

次のコード例は、`remove-tags-from-resource` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションインスタンスからタグを削除するには**  
次の `remove-tags-from-resource` の例では、レプリケーションインスタンスからタグを削除しています。  

```
aws dms remove-tags-from-resource \
    --resource-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE \
    --tag-keys Environment Project
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Tagging Resources](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/remove-tags-from-resource.html)」を参照してください。

### `start-replication-task-assessment`
<a name="database-migration-service_StartReplicationTaskAssessment_cli_2_topic"></a>

次のコード例は、`start-replication-task-assessment` を使用する方法を示しています。

**AWS CLI**  
**タスク評価を開始するには**  
次の `start-replication-task-assessment` の例では、レプリケーションタスクの評価を開始しています。  

```
aws dms start-replication-task-assessment \
    --replication-task-arn arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII
```
出力:  

```
{
    "ReplicationTask": {
        "ReplicationTaskIdentifier": "moveit2",
        "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "MigrationType": "full-load",
        "TableMappings": ...output omitted...,
        "ReplicationTaskSettings": ...output omitted...,
        "Status": "testing",
        "StopReason": "Stop Reason FULL_LOAD_ONLY_FINISHED",
        "ReplicationTaskCreationDate": 1590524772.505,
        "ReplicationTaskStartDate": 1590789988.677,
        "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII"
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Creating a Task Assessment Report](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.AssessmentReport.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartReplicationTaskAssessment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/start-replication-task-assessment.html)」を参照してください。

### `start-replication-task`
<a name="database-migration-service_StartReplicationTask_cli_2_topic"></a>

次のコード例は、`start-replication-task` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションタスクを開始するには**  
次の の`command-name`例では、 AWS アカウントで使用可能なウィジェットを一覧表示します。  

```
aws dms start-replication-task \
    --replication-task-arn arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII \
    --start-replication-task-type reload-target
```
出力:  

```
{
    "ReplicationTask": {
        "ReplicationTaskIdentifier": "moveit2",
        "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "MigrationType": "full-load",
        "TableMappings": ...output omitted... ,
        "ReplicationTaskSettings": ...output omitted... ,
        "Status": "starting",
        "ReplicationTaskCreationDate": 1590524772.505,
        "ReplicationTaskStartDate": 1590619805.212,
        "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII"
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS タスクの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartReplicationTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/start-replication-task.html)」を参照してください。

### `stop-replication-task`
<a name="database-migration-service_StopReplicationTask_cli_2_topic"></a>

次のコード例は、`stop-replication-task` を使用する方法を示しています。

**AWS CLI**  
**タスクを停止するには**  
次の `stop-replication-task` の例ではタスクを停止しています。  

```
aws dms stop-replication-task \
    --replication-task-arn arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII
```
出力:  

```
{
    "ReplicationTask": {
        "ReplicationTaskIdentifier": "moveit2",
        "SourceEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "TargetEndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:EOM4SFKCZEYHZBFGAGZT3QEC5U",
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "MigrationType": "full-load",
        "TableMappings": ...output omitted...,
        "ReplicationTaskSettings": ...output omitted...,
        "Status": "stopping",
        "ReplicationTaskCreationDate": 1590524772.505,
        "ReplicationTaskStartDate": 1590789424.653,
        "ReplicationTaskArn": "arn:aws:dms:us-east-1:123456789012:task:K55IUCGBASJS5VHZJIINA45FII"
    }
}
```
詳細については、*AWS 「 Database Migration Service ユーザーガイド*[AWS 」の「DMS タスクの使用](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopReplicationTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/stop-replication-task.html)」を参照してください。

### `test-connection`
<a name="database-migration-service_TestConnection_cli_2_topic"></a>

次のコード例は、`test-connection` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントへの接続をテストするには**  
次の `test-connection` の例では、レプリケーションインスタンスからエンドポイントにアクセスできるかどうかをテストしています。  

```
aws dms test-connection \
    --replication-instance-arn arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE \
    --endpoint-arn arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA
```
出力:  

```
{
    "Connection": {
        "ReplicationInstanceArn": "arn:aws:dms:us-east-1:123456789012:rep:T3OM7OUB5NM2LCVZF7JPGJRNUE",
        "EndpointArn": "arn:aws:dms:us-east-1:123456789012:endpoint:6GGI6YPWWGAYUVLKIB732KEVWA",
        "Status": "testing",
        "EndpointIdentifier": "src-database-1",
        "ReplicationInstanceIdentifier": "my-repl-instance"
    }
}
```
詳細については、「*AWS Database Migration Service ユーザーガイド*」の「[Creating source and target endpoints](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Endpoints.Creating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dms/test-connection.html)」を参照してください。

# を使用した Amazon DocumentDB の例 AWS CLI
<a name="cli_2_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags-to-resource`
<a name="docdb_AddTagsToResource_cli_2_topic"></a>

次のコード例は、`add-tags-to-resource` を使用する方法を示しています。

**AWS CLI**  
**指定されたリソースに 1 つまたは複数のタグを追加するには**  
次の `add-tags-to-resource` の例では、`sample-cluster` に 3 つのタグを追加します。1 つのタグ (`CropB`) にはキー名がありますが、値はありません。  

```
aws docdb add-tags-to-resource \
    --resource-name arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster \
    --tags Key="CropA",Value="Apple" Key="CropB" Key="CropC",Value="Corn"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Tagging Amazon DocumentDB Resources](https://docs.aws.amazon.com/documentdb/latest/developerguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AddTagsToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/add-tags-to-resource.html)」を参照してください。

### `apply-pending-maintenance-action`
<a name="docdb_ApplyPendingMaintenanceAction_cli_2_topic"></a>

次のコード例は、`apply-pending-maintenance-action` を使用する方法を示しています。

**AWS CLI**  
**次のメンテナンス期間に保留中のメンテナンスアクションを実行するには**  
次の `apply-pending-maintenance-action` の例では、次のスケジュールされたメンテナンス期間中にすべてのシステム更新アクションが実行されます。  

```
aws docdb apply-pending-maintenance-action \
--resource-identifier arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster \
--apply-action system-update \
--opt-in-type next-maintenance
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Applying Amazon DocumentDB Updates](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-maintain.html#db-instance-updates-apply)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ApplyPendingMaintenanceAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/apply-pending-maintenance-action.html)」を参照してください。

### `copy-db-cluster-parameter-group`
<a name="docdb_CopyDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`copy-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**既存の DB クラスターパラメータグループを複製するには**  
次の `copy-db-cluster-parameter-group` の例では、パラメータグループ `custom-docdb3-6` のコピーを `custom-docdb3-6-copy` という名前で作成します。コピーを作成すると、新しいパラメータグループにタグが追加されます。  

```
aws docdb copy-db-cluster-parameter-group \
    --source-db-cluster-parameter-group-identifier custom-docdb3-6 \
    --target-db-cluster-parameter-group-identifier custom-docdb3-6-copy \
    --target-db-cluster-parameter-group-description "Copy of custom-docdb3-6" \
    --tags Key="CopyNumber",Value="1" Key="Modifiable",Value="Yes"
```
出力:  

```
{
    "DBClusterParameterGroup": {
        "DBParameterGroupFamily": "docdb3.6",
        "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:12345678901:cluster-pg:custom-docdb3-6-copy",
        "DBClusterParameterGroupName": "custom-docdb3-6-copy",
        "Description": "Copy of custom-docdb3-6"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Copying an Amazon DocumentDB Cluster Parameter Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameter-group-copy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/copy-db-cluster-parameter-group.html)」を参照してください。

### `copy-db-cluster-snapshot`
<a name="docdb_CopyDbClusterSnapshot_cli_2_topic"></a>

次のコード例は、`copy-db-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのコピーを作成するには**  
次の `copy-db-cluster-snapshot` の例では、`sample-cluster-snapshot-copy` という名前の `sample-cluster-snapshot` のコピーを作成します。コピーには、元のすべてのタグに加えて、キー名 `CopyNumber` の新しいタグも含まれます。  

```
aws docdb copy-db-cluster-snapshot \
    --source-db-cluster-snapshot-identifier sample-cluster-snapshot \
    --target-db-cluster-snapshot-identifier sample-cluster-snapshot-copy \
    --copy-tags \
    --tags Key="CopyNumber",Value="1"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Copying a Cluster Snapshot](https://docs.aws.amazon.com/documentdb/latest/developerguide/backup-restore.db-cluster-snapshot-copy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyDbClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/copy-db-cluster-snapshot.html)」を参照してください。

### `create-db-cluster-parameter-group`
<a name="docdb_CreateDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`create-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターパラメータグループを作成するには**  
次の `create-db-cluster-parameter-group` の例では、`docdb3.6` ファミリーを使用して DB クラスターパラメータグループ `sample-parameter-group` を作成します。  

```
aws docdb create-db-cluster-parameter-group \
    --db-cluster-parameter-group-name sample-parameter-group \
    --db-parameter-group-family docdb3.6 \
    --description "Sample parameter group based on docdb3.6"
```
出力:  

```
{
    "DBClusterParameterGroup": {
        "Description": "Sample parameter group based on docdb3.6",
        "DBParameterGroupFamily": "docdb3.6",
        "DBClusterParameterGroupArn": "arn:aws:rds:us-west-2:123456789012:cluster-pg:sample-parameter-group",
        "DBClusterParameterGroupName": "sample-parameter-group"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Creating an Amazon DocumentDB Cluster Parameter Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameter-group-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/create-db-cluster-parameter-group.html)」を参照してください。

### `create-db-cluster-snapshot`
<a name="docdb_CreateDbClusterSnapshot_cli_2_topic"></a>

次のコード例は、`create-db-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB の手動クラスタースナップショットを作成するには**  
次の `create-db-cluster-snapshot` の例では、sample-cluster-snapshot という名前の Amazon DB クラスタースナップショットを作成します。  

```
aws docdb create-db-cluster-snapshot \
   --db-cluster-identifier sample-cluster \
   --db-cluster-snapshot-identifier sample-cluster-snapshot
```
出力:  

```
{
    "DBClusterSnapshot": {
        "MasterUsername": "master-user",
        "SnapshotCreateTime": "2019-03-18T18:27:14.794Z",
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2b",
            "us-west-2c",
            "us-west-2d",
            "us-west-2e",
            "us-west-2f"
        ],
        "SnapshotType": "manual",
        "DBClusterSnapshotArn": "arn:aws:rds:us-west-2:123456789012:cluster-snapshot:sample-cluster-snapshot",
        "EngineVersion": "3.6.0",
        "PercentProgress": 0,
        "DBClusterSnapshotIdentifier": "sample-cluster-snapshot",
        "Engine": "docdb",
        "DBClusterIdentifier": "sample-cluster",
        "Status": "creating",
        "ClusterCreateTime": "2019-03-15T20:29:58.836Z",
        "Port": 0,
        "StorageEncrypted": false,
        "VpcId": "vpc-91280df6"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Creating a Manual Cluster Snapshot](https://docs.aws.amazon.com/documentdb/latest/developerguide/backup-restore.db-cluster-snapshot-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/create-db-cluster-snapshot.html)」を参照してください。

### `create-db-cluster`
<a name="docdb_CreateDbCluster_cli_2_topic"></a>

次のコード例は、`create-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターを作成するには**  
次の `create-db-cluster` の例では、日曜日の 20:30 から 11:00 までの優先メンテナンス期間で、`sample-cluster` という名前の Amazon DocumentDB クラスターを作成しています。  

```
aws docdb create-db-cluster \
    --db-cluster-identifier sample-cluster \
    --engine docdb \
    --master-username master-user \
    --master-user-password password \
    --preferred-maintenance-window Sun:20:30-Sun:21:00
```
出力:  

```
{
    "DBCluster": {
        "DBClusterParameterGroup": "default.docdb3.6",
        "AssociatedRoles": [],
        "DBSubnetGroup": "default",
        "ClusterCreateTime": "2019-03-18T18:06:34.616Z",
        "Status": "creating",
        "Port": 27017,
        "PreferredMaintenanceWindow": "sun:20:30-sun:21:00",
        "HostedZoneId": "ZNKXH85TT8WVW",
        "DBClusterMembers": [],
        "Engine": "docdb",
        "DBClusterIdentifier": "sample-cluster",
        "PreferredBackupWindow": "10:12-10:42",
        "AvailabilityZones": [
            "us-west-2d",
            "us-west-2f",
            "us-west-2e"
        ],
        "MasterUsername": "master-user",
        "BackupRetentionPeriod": 1,
        "ReaderEndpoint": "sample-cluster.cluster-ro-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-77186e0d",
                "Status": "active"
            }
        ],
        "StorageEncrypted": false,
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster",
        "DbClusterResourceId": "cluster-L3R4YRSBUYDP4GLMTJ2WF5GH5Q",
        "MultiAZ": false,
        "Endpoint": "sample-cluster.cluster-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "EngineVersion": "3.6.0"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Creating an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/create-db-cluster.html)」を参照してください。

### `create-db-instance`
<a name="docdb_CreateDbInstance_cli_2_topic"></a>

次のコード例は、`create-db-instance` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターインスタンスを作成するには**  
次の `create-db-instance` のサンプルコードは、Amazon DocumentDB クラスター `sample-cluster` にインスタンス `sample-cluster-instance-2` を作成します。  

```
aws docdb create-db-instance \
    --db-cluster-identifier sample-cluster \
    --db-instance-class db.r4.xlarge \
    --db-instance-identifier sample-cluster-instance-2 \
    --engine docdb
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceStatus": "creating",
        "PendingModifiedValues": {
            "PendingCloudwatchLogsExports": {
                "LogTypesToEnable": [
                    "audit"
                ]
            }
        },
        "PubliclyAccessible": false,
        "PreferredBackupWindow": "00:00-00:30",
        "PromotionTier": 1,
        "EngineVersion": "3.6.0",
        "BackupRetentionPeriod": 3,
        "DBInstanceIdentifier": "sample-cluster-instance-2",
        "PreferredMaintenanceWindow": "tue:10:28-tue:10:58",
        "StorageEncrypted": false,
        "Engine": "docdb",
        "DBClusterIdentifier": "sample-cluster",
        "DBSubnetGroup": {
            "Subnets": [
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-4e26d263"
                },
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2c"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-afc329f4"
                },
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2d"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-53ab3636"
                },
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2b"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-991cb8d0"
                }
            ],
            "DBSubnetGroupDescription": "default",
            "SubnetGroupStatus": "Complete",
            "VpcId": "vpc-91280df6",
            "DBSubnetGroupName": "default"
        },
        "DBInstanceClass": "db.r4.xlarge",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ],
        "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster-instance-2",
        "DbiResourceId": "db-XEKJLEMGRV5ZKCARUVA4HO3ITE"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Adding an Amazon DocumentDB Instance to a Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-add.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/create-db-instance.html)」を参照してください。

### `create-db-subnet-group`
<a name="docdb_CreateDbSubnetGroup_cli_2_topic"></a>

次のコード例は、`create-db-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB サブネットグループを作成するには**  
次の `create-db-subnet-group` の例では、`sample-subnet-group` という名前の Amazon DocumentDB サブネットグループを作成します。  

```
aws docdb create-db-subnet-group \
    --db-subnet-group-description "a sample subnet group" \
    --db-subnet-group-name sample-subnet-group \
    --subnet-ids "subnet-29ab1025" "subnet-991cb8d0" "subnet-53ab3636"
```
出力:  

```
{
    "DBSubnetGroup": {
        "SubnetGroupStatus": "Complete",
        "DBSubnetGroupName": "sample-subnet-group",
        "DBSubnetGroupDescription": "a sample subnet group",
        "VpcId": "vpc-91280df6",
        "DBSubnetGroupArn": "arn:aws:rds:us-west-2:123456789012:subgrp:sample-subnet-group",
        "Subnets": [
            {
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-53ab3636",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2d"
                }
            },
            {
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-991cb8d0",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2b"
                }
            },
            {
                "SubnetStatus": "Active",
                "SubnetIdentifier": "subnet-29ab1025",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2c"
                }
            }
        ]
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Creating an Amazon DocumentDB Subnet Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/document-db-subnet-groups.html#document-db-subnet-group-create)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/create-db-subnet-group.html)」を参照してください。

### `delete-db-cluster-parameter-group`
<a name="docdb_DeleteDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`delete-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターパラメータグループを削除するには**  
次の `delete-db-cluster-parameter-group` の例では、Amazon DocumentDB パラメータグループ `sample-parameter-group` を削除しています。  

```
aws docdb delete-db-cluster-parameter-group \
    --db-cluster-parameter-group-name sample-parameter-group
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Deleting an Amazon DocumentDB Cluster Parameter Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameter-group-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/delete-db-cluster-parameter-group.html)」を参照してください。

### `delete-db-cluster-snapshot`
<a name="docdb_DeleteDbClusterSnapshot_cli_2_topic"></a>

次のコード例は、`delete-db-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスタースナップショットを削除するには**  
次の `delete-db-cluster-snapshot` の例では、Amazon DocumentDB クラスタースナップショット `sample-cluster-snapshot` を削除します。  

```
aws docdb delete-db-cluster-snapshot \
    --db-cluster-snapshot-identifier sample-cluster-snapshot
```
出力:  

```
{
    "DBClusterSnapshot": {
        "DBClusterIdentifier": "sample-cluster",
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2b",
            "us-west-2c",
            "us-west-2d"
        ],
        "DBClusterSnapshotIdentifier": "sample-cluster-snapshot",
        "VpcId": "vpc-91280df6",
        "DBClusterSnapshotArn": "arn:aws:rds:us-west-2:123456789012:cluster-snapshot:sample-cluster-snapshot",
        "EngineVersion": "3.6.0",
        "Engine": "docdb",
        "SnapshotCreateTime": "2019-03-18T18:27:14.794Z",
        "Status": "available",
        "MasterUsername": "master-user",
        "ClusterCreateTime": "2019-03-15T20:29:58.836Z",
        "PercentProgress": 100,
        "StorageEncrypted": false,
        "SnapshotType": "manual",
        "Port": 0
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Deleting a Cluster Snapshot](https://docs.aws.amazon.com/documentdb/latest/developerguide/backup-restore.db-cluster-snapshot-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/delete-db-cluster-snapshot.html)」を参照してください。

### `delete-db-cluster`
<a name="docdb_DeleteDbCluster_cli_2_topic"></a>

次のコード例は、`delete-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターを削除するには**  
次の `delete-db-cluster` の例では、Amazon DocumentDB クラスター `sample-cluster` を削除します。削除する前にクラスターのバックアップは行われません。注: クラスターを削除する前に、クラスターに関連付けられているすべてのインスタンスを削除する必要があります。  

```
aws docdb delete-db-cluster \
    --db-cluster-identifier sample-cluster \
    --skip-final-snapshot
```
出力:  

```
{
    "DBCluster": {
        "DBClusterIdentifier": "sample-cluster",
        "DBSubnetGroup": "default",
        "EngineVersion": "3.6.0",
        "Engine": "docdb",
        "LatestRestorableTime": "2019-03-18T18:07:24.610Z",
        "PreferredMaintenanceWindow": "sun:20:30-sun:21:00",
        "StorageEncrypted": false,
        "EarliestRestorableTime": "2019-03-18T18:07:24.610Z",
        "Port": 27017,
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ],
        "MultiAZ": false,
        "MasterUsername": "master-user",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster",
        "Status": "available",
        "PreferredBackupWindow": "10:12-10:42",
        "ReaderEndpoint": "sample-cluster.cluster-ro-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "AvailabilityZones": [
            "us-west-2c",
            "us-west-2b",
            "us-west-2a"
        ],
        "Endpoint": "sample-cluster.cluster-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "DbClusterResourceId": "cluster-L3R4YRSBUYDP4GLMTJ2WF5GH5Q",
        "ClusterCreateTime": "2019-03-18T18:06:34.616Z",
        "AssociatedRoles": [],
        "DBClusterParameterGroup": "default.docdb3.6",
        "HostedZoneId": "ZNKXH85TT8WVW",
        "BackupRetentionPeriod": 1,
        "DBClusterMembers": []
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Deleting an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/delete-db-cluster.html)」を参照してください。

### `delete-db-instance`
<a name="docdb_DeleteDbInstance_cli_2_topic"></a>

次のコード例は、`delete-db-instance` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB インスタンスを削除するには**  
次の `delete-db-instance` の例では、Amazon DocumentDB インスタンス `sample-cluster-instance-2` を削除しています。  

```
aws docdb delete-db-instance \
    --db-instance-identifier sample-cluster-instance-2
```
出力:  

```
{
    "DBInstance": {
        "DBSubnetGroup": {
            "Subnets": [
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-4e26d263"
                },
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2c"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-afc329f4"
                },
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2d"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-53ab3636"
                },
                {
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2b"
                    },
                    "SubnetStatus": "Active",
                    "SubnetIdentifier": "subnet-991cb8d0"
                }
            ],
            "DBSubnetGroupName": "default",
            "DBSubnetGroupDescription": "default",
            "VpcId": "vpc-91280df6",
            "SubnetGroupStatus": "Complete"
        },
        "PreferredBackupWindow": "00:00-00:30",
        "InstanceCreateTime": "2019-03-18T18:37:33.709Z",
        "DBInstanceClass": "db.r4.xlarge",
        "DbiResourceId": "db-XEKJLEMGRV5ZKCARUVA4HO3ITE",
        "BackupRetentionPeriod": 3,
        "Engine": "docdb",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ],
        "AutoMinorVersionUpgrade": true,
        "PromotionTier": 1,
        "EngineVersion": "3.6.0",
        "Endpoint": {
            "Address": "sample-cluster-instance-2.corcjozrlsfc.us-west-2.docdb.amazonaws.com",
            "HostedZoneId": "ZNKXH85TT8WVW",
            "Port": 27017
        },
        "DBInstanceIdentifier": "sample-cluster-instance-2",
        "PreferredMaintenanceWindow": "tue:10:28-tue:10:58",
        "EnabledCloudwatchLogsExports": [
            "audit"
        ],
        "PendingModifiedValues": {},
        "DBInstanceStatus": "deleting",
        "PubliclyAccessible": false,
        "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster-instance-2",
        "DBClusterIdentifier": "sample-cluster",
        "AvailabilityZone": "us-west-2c",
        "StorageEncrypted": false
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Deleting an Amazon DocumentDB Instance](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/delete-db-instance.html)」を参照してください。

### `delete-db-subnet-group`
<a name="docdb_DeleteDbSubnetGroup_cli_2_topic"></a>

次のコード例は、`delete-db-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB サブネットグループを削除するには**  
次の `delete-db-subnet-group` の例では、Amazon DocumentDB サブネットグループ `sample-subnet-group` を削除します。  

```
aws docdb delete-db-subnet-group \
    --db-subnet-group-name sample-subnet-group
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Deleting an Amazon DocumentDB Subnet Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/document-db-subnet-groups.html#document-db-subnet-group-delete)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/delete-db-subnet-group.html)」を参照してください。

### `describe-db-cluster-parameter-groups`
<a name="docdb_DescribeDbClusterParameterGroups_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-parameter-groups` を使用する方法を示しています。

**AWS CLI**  
**1 つまたは複数の Amazon DocumentDB クラスターパラメータグループの詳細を表示するには**  
次の `describe-db-cluster-parameter-groups` の例では、Amazon DocumentDB クラスターパラメータグループ `custom3-6-param-grp` の詳細を表示します。  

```
aws docdb describe-db-cluster-parameter-groups \
    --db-cluster-parameter-group-name custom3-6-param-grp
```
出力:  

```
{
    "DBClusterParameterGroups": [
        {
            "DBParameterGroupFamily": "docdb3.6",
            "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:custom3-6-param-grp",
            "Description": "Custom docdb3.6 parameter group",
            "DBClusterParameterGroupName": "custom3-6-param-grp"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Viewing Amazon DocumentDB Cluster Parameter Groups](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameter-group-describe.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterParameterGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-cluster-parameter-groups.html)」を参照してください。

### `describe-db-cluster-parameters`
<a name="docdb_DescribeDbClusterParameters_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-parameters` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターパラメータグループの詳細なパラメータリストを表示するには。**  
次の `describe-db-cluster-parameters` の例では、Amazon DocumentDB パラメータグループ custom3-6-param-grp のパラメータを一覧表示します。  

```
aws docdb describe-db-cluster-parameters \
     --db-cluster-parameter-group-name custom3-6-param-grp
```
出力:  

```
{
    "Parameters": [
        {
            "DataType": "string",
            "ParameterName": "audit_logs",
            "IsModifiable": true,
            "ApplyMethod": "pending-reboot",
            "Source": "system",
            "ApplyType": "dynamic",
            "AllowedValues": "enabled,disabled",
            "Description": "Enables auditing on cluster.",
            "ParameterValue": "disabled"
        },
        {
            "DataType": "string",
            "ParameterName": "tls",
            "IsModifiable": true,
            "ApplyMethod": "pending-reboot",
            "Source": "system",
            "ApplyType": "static",
            "AllowedValues": "disabled,enabled",
            "Description": "Config to enable/disable TLS",
            "ParameterValue": "enabled"
        },
        {
            "DataType": "string",
            "ParameterName": "ttl_monitor",
            "IsModifiable": true,
            "ApplyMethod": "pending-reboot",
            "Source": "user",
            "ApplyType": "dynamic",
            "AllowedValues": "disabled,enabled",
            "Description": "Enables TTL Monitoring",
            "ParameterValue": "enabled"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Viewing Amazon DocumentDB Cluster Parameters](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameters-describe.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-cluster-parameters.html)」を参照してください。

### `describe-db-cluster-snapshot-attributes`
<a name="docdb_DescribeDbClusterSnapshotAttributes_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-snapshot-attributes` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB スナップショットの属性名と値を一覧表示するには**  
次の `describe-db-cluster-snapshot-attributes` の例では、Amazon DocumentDB スナップショット `sample-cluster-snapshot` の属性名と値を一覧表示します。  

```
aws docdb describe-db-cluster-snapshot-attributes \
    --db-cluster-snapshot-identifier sample-cluster-snapshot
```
出力:  

```
{
    "DBClusterSnapshotAttributesResult": {
        "DBClusterSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": []
            }
        ],
        "DBClusterSnapshotIdentifier": "sample-cluster-snapshot"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[DescribeDBClusterSnapshotAttributes](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeDBClusterSnapshotAttributes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterSnapshotAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-cluster-snapshot-attributes.html)」を参照してください。

### `describe-db-cluster-snapshots`
<a name="docdb_DescribeDbClusterSnapshots_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-snapshots` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB スナップショットを記述するには**  
次の `describe-db-cluster-snapshots` の例では、Amazon DocumentDB スナップショット `sample-cluster-snapshot` の詳細を表示します。  

```
aws docdb describe-db-cluster-snapshots \
    --db-cluster-snapshot-identifier sample-cluster-snapshot
```
出力:  

```
{
    "DBClusterSnapshots": [
        {
            "AvailabilityZones": [
                "us-west-2a",
                "us-west-2b",
                "us-west-2c",
                "us-west-2d"
            ],
            "Status": "available",
            "DBClusterSnapshotArn": "arn:aws:rds:us-west-2:123456789012:cluster-snapshot:sample-cluster-snapshot",
            "SnapshotCreateTime": "2019-03-15T20:41:26.515Z",
            "SnapshotType": "manual",
            "DBClusterSnapshotIdentifier": "sample-cluster-snapshot",
            "DBClusterIdentifier": "sample-cluster",
            "MasterUsername": "master-user",
            "StorageEncrypted": false,
            "VpcId": "vpc-91280df6",
            "EngineVersion": "3.6.0",
            "PercentProgress": 100,
            "Port": 0,
            "Engine": "docdb",
            "ClusterCreateTime": "2019-03-15T20:29:58.836Z"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[DescribeDBClusterSnapshots](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeDBClusterSnapshots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-cluster-snapshots.html)」を参照してください。

### `describe-db-clusters`
<a name="docdb_DescribeDbClusters_cli_2_topic"></a>

次のコード例は、`describe-db-clusters` を使用する方法を示しています。

**AWS CLI**  
**1 つ以上の Amazon DocumentDB クラスターに関する詳細情報を取得するには。**  
次の `describe-db-clusters` の例では、Amazon DocumentDB クラスター `sample-cluster` の詳細を表示します。`--db-cluster-identifier` パラメータを省略すると、最大 100 個のクラスターの情報を取得できます。  

```
aws docdb describe-db-clusters
    --db-cluster-identifier sample-cluster
```
出力:  

```
{
    "DBClusters": [
        {
            "DBClusterParameterGroup": "default.docdb3.6",
            "Endpoint": "sample-cluster.cluster-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
            "PreferredBackupWindow": "00:00-00:30",
            "DBClusterIdentifier": "sample-cluster",
            "ClusterCreateTime": "2019-03-15T20:29:58.836Z",
            "LatestRestorableTime": "2019-03-18T20:28:03.239Z",
            "MasterUsername": "master-user",
            "DBClusterMembers": [
                {
                    "PromotionTier": 1,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "IsClusterWriter": false,
                    "DBInstanceIdentifier": "sample-cluster"
                },
                {
                    "PromotionTier": 1,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "IsClusterWriter": true,
                    "DBInstanceIdentifier": "sample-cluster2"
                }
            ],
            "PreferredMaintenanceWindow": "sat:04:30-sat:05:00",
            "VpcSecurityGroups": [
                {
                    "VpcSecurityGroupId": "sg-77186e0d",
                    "Status": "active"
                }
            ],
            "Engine": "docdb",
            "ReaderEndpoint": "sample-cluster.cluster-ro-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
            "DBSubnetGroup": "default",
            "MultiAZ": true,
            "AvailabilityZones": [
                "us-west-2a",
                "us-west-2c",
                "us-west-2b"
            ],
            "EarliestRestorableTime": "2019-03-15T20:30:47.020Z",
            "DbClusterResourceId": "cluster-UP4EF2PVDDFVHHDJQTYDAIGHLE",
            "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster",
            "BackupRetentionPeriod": 3,
            "HostedZoneId": "ZNKXH85TT8WVW",
            "StorageEncrypted": false,
            "EnabledCloudwatchLogsExports": [
                "audit"
            ],
            "AssociatedRoles": [],
            "EngineVersion": "3.6.0",
            "Port": 27017,
            "Status": "available"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Describing Amazon DocumentDB Clusters](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-view-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-clusters.html)」を参照してください。

### `describe-db-engine-versions`
<a name="docdb_DescribeDbEngineVersions_cli_2_topic"></a>

次のコード例は、`describe-db-engine-versions` を使用する方法を示しています。

**AWS CLI**  
**使用可能な Amazon DocumentDB エンジンのバージョンを一覧表示するには**  
次の `describe-db-engine-versions` の例では、使用可能な Amazon DocumentDB エンジンのバージョンをすべて一覧表示します。  

```
aws docdb describe-db-engine-versions \
    --engine docdb
```
出力:  

```
{
    "DBEngineVersions": [
        {
            "DBEngineVersionDescription": "DocDB version 1.0.200837",
            "DBParameterGroupFamily": "docdb3.6",
            "EngineVersion": "3.6.0",
            "ValidUpgradeTarget": [],
            "DBEngineDescription": "Amazon DocumentDB (with MongoDB compatibility)",
            "SupportsLogExportsToCloudwatchLogs": true,
            "Engine": "docdb",
            "ExportableLogTypes": [
                "audit"
            ]
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeDBEngineVersions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbEngineVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-engine-versions.html)」を参照してください。

### `describe-db-instances`
<a name="docdb_DescribeDbInstances_cli_2_topic"></a>

次のコード例は、`describe-db-instances` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされた Amazon DocumentDB インスタンスに関する情報を見つけるには**  
次の `describe-db-instances` の例では、Amazon DocumentDB インスタンス `sample-cluster-instance` の詳細を表示します。`--db-instance-identifier` パラメータを省略すると、最大 100 個のインスタンスの情報を取得できます。  

```
aws docdb describe-db-instances \
    --db-instance-identifier sample-cluster-instance
```
出力:  

```
{
    "DBInstances": [
        {
            "Endpoint": {
                "HostedZoneId": "ZNKXH85TT8WVW",
                "Address": "sample-cluster-instance.corcjozrlsfc.us-west-2.docdb.amazonaws.com",
                "Port": 27017
            },
            "PreferredBackupWindow": "00:00-00:30",
            "DBInstanceStatus": "available",
            "DBInstanceClass": "db.r4.large",
            "EnabledCloudwatchLogsExports": [
                "audit"
            ],
            "DBInstanceIdentifier": "sample-cluster-instance",
            "DBSubnetGroup": {
                "Subnets": [
                    {
                        "SubnetStatus": "Active",
                        "SubnetIdentifier": "subnet-4e26d263",
                        "SubnetAvailabilityZone": {
                            "Name": "us-west-2a"
                        }
                    },
                    {
                        "SubnetStatus": "Active",
                        "SubnetIdentifier": "subnet-afc329f4",
                        "SubnetAvailabilityZone": {
                            "Name": "us-west-2c"
                        }
                    },
                    {
                        "SubnetStatus": "Active",
                        "SubnetIdentifier": "subnet-53ab3636",
                        "SubnetAvailabilityZone": {
                            "Name": "us-west-2d"
                        }
                    },
                    {
                        "SubnetStatus": "Active",
                        "SubnetIdentifier": "subnet-991cb8d0",
                        "SubnetAvailabilityZone": {
                            "Name": "us-west-2b"
                        }
                    }
                ],
                "DBSubnetGroupName": "default",
                "SubnetGroupStatus": "Complete",
                "DBSubnetGroupDescription": "default",
                "VpcId": "vpc-91280df6"
            },
            "InstanceCreateTime": "2019-03-15T20:36:06.338Z",
            "Engine": "docdb",
            "StorageEncrypted": false,
            "AutoMinorVersionUpgrade": true,
            "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster-instance",
            "PreferredMaintenanceWindow": "tue:08:39-tue:09:09",
            "VpcSecurityGroups": [
                {
                    "Status": "active",
                    "VpcSecurityGroupId": "sg-77186e0d"
                }
            ],
            "DBClusterIdentifier": "sample-cluster",
            "PendingModifiedValues": {},
            "BackupRetentionPeriod": 3,
            "PubliclyAccessible": false,
            "EngineVersion": "3.6.0",
            "PromotionTier": 1,
            "AvailabilityZone": "us-west-2c",
            "DbiResourceId": "db-A2GIKUV6KPOHITGGKI2NHVISZA"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Describing Amazon DocumentDB Instances](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-view-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-instances.html)」を参照してください。

### `describe-db-subnet-groups`
<a name="docdb_DescribeDbSubnetGroups_cli_2_topic"></a>

次のコード例は、`describe-db-subnet-groups` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB サブネットの説明のリストを取得するには**  
次の `describe-db-subnet-groups` の例では、`default` という名前の Amazon DocumentDB サブネットの詳細を記述します。  

```
aws docdb describe-db-subnet-groups \
    --db-subnet-group-name default
```
出力:  

```
{
    "DBSubnetGroups": [
        {
            "VpcId": "vpc-91280df6",
            "DBSubnetGroupArn": "arn:aws:rds:us-west-2:123456789012:subgrp:default",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-4e26d263",
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    }
                },
                {
                    "SubnetIdentifier": "subnet-afc329f4",
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2c"
                    }
                },
                {
                    "SubnetIdentifier": "subnet-53ab3636",
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2d"
                    }
                },
                {
                    "SubnetIdentifier": "subnet-991cb8d0",
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2b"
                    }
                }
            ],
            "DBSubnetGroupName": "default",
            "SubnetGroupStatus": "Complete",
            "DBSubnetGroupDescription": "default"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Describing Subnet Groups](https://docs.aws.amazon.com/documentdb/latest/developerguide/document-db-subnet-groups.html#document-db-subnet-groups-describe)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbSubnetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-db-subnet-groups.html)」を参照してください。

### `describe-engine-default-cluster-parameters`
<a name="docdb_DescribeEngineDefaultClusterParameters_cli_2_topic"></a>

次のコード例は、`describe-engine-default-cluster-parameters` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB のデフォルトのエンジンおよびシステムパラメータ情報を記述するには**  
次の `describe-engine-default-cluster-parameters` の例では、Amazon DocumentDB パラメータグループ `docdb3.6` のデフォルトのエンジンの詳細およびシステムパラメータ情報を表示します。  

```
aws docdb describe-engine-default-cluster-parameters \
    --db-parameter-group-family docdb3.6
```
出力:  

```
{
    "EngineDefaults": {
        "DBParameterGroupFamily": "docdb3.6",
        "Parameters": [
            {
                "ApplyType": "dynamic",
                "ParameterValue": "disabled",
                "Description": "Enables auditing on cluster.",
                "Source": "system",
                "DataType": "string",
                "MinimumEngineVersion": "3.6.0",
                "AllowedValues": "enabled,disabled",
                "ParameterName": "audit_logs",
                "IsModifiable": true
            },
            {
                "ApplyType": "static",
                "ParameterValue": "enabled",
                "Description": "Config to enable/disable TLS",
                "Source": "system",
                "DataType": "string",
                "MinimumEngineVersion": "3.6.0",
                "AllowedValues": "disabled,enabled",
                "ParameterName": "tls",
                "IsModifiable": true
            },
            {
                "ApplyType": "dynamic",
                "ParameterValue": "enabled",
                "Description": "Enables TTL Monitoring",
                "Source": "system",
                "DataType": "string",
                "MinimumEngineVersion": "3.6.0",
                "AllowedValues": "disabled,enabled",
                "ParameterName": "ttl_monitor",
                "IsModifiable": true
            }
        ]
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[DescribeEngineDefaultClusterParameters](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_DescribeEngineDefaultClusterParameters.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEngineDefaultClusterParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-engine-default-cluster-parameters.html)」を参照してください。

### `describe-event-categories`
<a name="docdb_DescribeEventCategories_cli_2_topic"></a>

次のコード例は、`describe-event-categories` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB イベントカテゴリをすべて記述するには**  
次の `describe-event-categories` の例では、Amazon DocumentDB イベントソースタイプ `db-instance` のすべてのカテゴリを一覧表示します。  

```
aws docdb describe-event-categories \
    --source-type db-cluster
```
出力:  

```
{
    "EventCategoriesMapList": [
        {
            "SourceType": "db-cluster",
            "EventCategories": [
                "failover",
                "maintenance",
                "notification",
                "failure"
            ]
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Viewing Event Categories](https://docs.aws.amazon.com/documentdb/latest/developerguide/managing-events.html#viewing-event-categories)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventCategories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-event-categories.html)」を参照してください。

### `describe-events`
<a name="docdb_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB イベントを一覧表示するには**  
次の `describe-events` の例では、過去 24 時間 (1,440 分) のすべての Amazon DocumentDB イベントを一覧表示します。  

```
aws docdb describe-events \
    --duration 1440
```
このコマンドでは何も出力されません。出力:  

```
{
    "Events": [
        {
            "EventCategories": [
                "failover"
            ],
            "Message": "Started cross AZ failover to DB instance: sample-cluster",
            "Date": "2019-03-18T21:36:29.807Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster",
            "SourceIdentifier": "sample-cluster",
            "SourceType": "db-cluster"
        },
        {
            "EventCategories": [
                "availability"
            ],
            "Message": "DB instance restarted",
            "Date": "2019-03-18T21:36:40.793Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster",
            "SourceIdentifier": "sample-cluster",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [],
            "Message": "A new writer was promoted. Restarting database as a reader.",
            "Date": "2019-03-18T21:36:43.873Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [
                "availability"
            ],
            "Message": "DB instance restarted",
            "Date": "2019-03-18T21:36:51.257Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [
                "failover"
            ],
            "Message": "Completed failover to DB instance: sample-cluster",
            "Date": "2019-03-18T21:36:53.462Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster",
            "SourceIdentifier": "sample-cluster",
            "SourceType": "db-cluster"
        },
        {
            "Date": "2019-03-19T16:51:48.847Z",
            "EventCategories": [
                "configuration change"
            ],
            "Message": "Updated parameter audit_logs to enabled with apply method pending-reboot",
            "SourceIdentifier": "custom3-6-param-grp",
            "SourceType": "db-parameter-group"
        },
        {
            "EventCategories": [
                "configuration change"
            ],
            "Message": "Applying modification to database instance class",
            "Date": "2019-03-19T17:55:20.095Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [
                "availability"
            ],
            "Message": "DB instance shutdown",
            "Date": "2019-03-19T17:56:31.127Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [
                "configuration change"
            ],
            "Message": "Finished applying modification to DB instance class",
            "Date": "2019-03-19T18:00:45.822Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [
                "availability"
            ],
            "Message": "DB instance restarted",
            "Date": "2019-03-19T18:00:53.397Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [
                "availability"
            ],
            "Message": "DB instance shutdown",
            "Date": "2019-03-19T18:23:36.045Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "EventCategories": [
                "availability"
            ],
            "Message": "DB instance restarted",
            "Date": "2019-03-19T18:23:46.209Z",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
            "SourceIdentifier": "sample-cluster2",
            "SourceType": "db-instance"
        },
        {
            "Date": "2019-03-19T18:39:05.822Z",
            "EventCategories": [
                "configuration change"
            ],
            "Message": "Updated parameter ttl_monitor to enabled with apply method immediate",
            "SourceIdentifier": "custom3-6-param-grp",
            "SourceType": "db-parameter-group"
        },
        {
            "Date": "2019-03-19T18:39:48.067Z",
            "EventCategories": [
                "configuration change"
            ],
            "Message": "Updated parameter audit_logs to disabled with apply method immediate",
            "SourceIdentifier": "custom3-6-param-grp",
            "SourceType": "db-parameter-group"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Viewing Amazon DocumentDB Events](https://docs.aws.amazon.com/documentdb/latest/developerguide/managing-events.html#viewing-events)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-events.html)」を参照してください。

### `describe-orderable-db-instance-options`
<a name="docdb_DescribeOrderableDbInstanceOptions_cli_2_topic"></a>

次のコード例は、`describe-orderable-db-instance-options` を使用する方法を示しています。

**AWS CLI**  
**注文できる Amazon DocumentDB インスタンスオプションを見つけるには**  
次の `describe-orderable-db-instance-options` の例では、リージョンの Amazon DocumentDB 用インスタンスオプションをすべて一覧表示します。  

```
aws docdb describe-orderable-db-instance-options \
    --engine docdb \
    --region us-east-1
```
出力:  

```
{
    "OrderableDBInstanceOptions": [
        {
            "Vpc": true,
            "AvailabilityZones": [
                {
                    "Name": "us-east-1a"
                },
                {
                    "Name": "us-east-1b"
                },
                {
                    "Name": "us-east-1c"
                },
                {
                    "Name": "us-east-1d"
                }
            ],
            "EngineVersion": "3.6.0",
            "DBInstanceClass": "db.r4.16xlarge",
            "LicenseModel": "na",
            "Engine": "docdb"
        },
        {
            "Vpc": true,
            "AvailabilityZones": [
                {
                    "Name": "us-east-1a"
                },
                {
                    "Name": "us-east-1b"
                },
                {
                    "Name": "us-east-1c"
                },
                {
                    "Name": "us-east-1d"
                }
                }
            ],
            "EngineVersion": "3.6.0",
            "DBInstanceClass": "db.r4.2xlarge",
            "LicenseModel": "na",
            "Engine": "docdb"
        },
        {
            "Vpc": true,
            "AvailabilityZones": [
                {
                    "Name": "us-east-1a"
                },
                {
                    "Name": "us-east-1b"
                },
                {
                    "Name": "us-east-1c"
                },
                {
                    "Name": "us-east-1d"
                }
            ],
            "EngineVersion": "3.6.0",
            "DBInstanceClass": "db.r4.4xlarge",
            "LicenseModel": "na",
            "Engine": "docdb"
        },
        {
            "Vpc": true,
            "AvailabilityZones": [
                {
                    "Name": "us-east-1a"
                },
                {
                    "Name": "us-east-1b"
                },
                {
                    "Name": "us-east-1c"
                },
                {
                    "Name": "us-east-1d"
                }
            ],
            "EngineVersion": "3.6.0",
            "DBInstanceClass": "db.r4.8xlarge",
            "LicenseModel": "na",
            "Engine": "docdb"
        },
        {
            "Vpc": true,
            "AvailabilityZones": [
                {
                    "Name": "us-east-1a"
                },
                {
                    "Name": "us-east-1b"
                },
                {
                    "Name": "us-east-1c"
                },
                {
                    "Name": "us-east-1d"
                }
            ],
            "EngineVersion": "3.6.0",
            "DBInstanceClass": "db.r4.large",
            "LicenseModel": "na",
            "Engine": "docdb"
        },
        {
            "Vpc": true,
            "AvailabilityZones": [
                {
                    "Name": "us-east-1a"
                },
                {
                    "Name": "us-east-1b"
                },
                {
                    "Name": "us-east-1c"
                },
                {
                    "Name": "us-east-1d"
                }
            ],
            "EngineVersion": "3.6.0",
            "DBInstanceClass": "db.r4.xlarge",
            "LicenseModel": "na",
            "Engine": "docdb"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Adding an Amazon DocumentDB Instance to a Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-add.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOrderableDbInstanceOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-orderable-db-instance-options.html)」を参照してください。

### `describe-pending-maintenance-actions`
<a name="docdb_DescribePendingMaintenanceActions_cli_2_topic"></a>

次のコード例は、`describe-pending-maintenance-actions` を使用する方法を示しています。

**AWS CLI**  
**保留中の Amazon DocumentDB メンテナンスアクションを一覧表示するには**  
次の `describe-pending-maintenance-actions` の例では、保留中の Amazon DocumentDB メンテナンスアクションをすべて一覧表示します。  

```
aws docdb describe-pending-maintenance-actions
```
出力:  

```
{
    "PendingMaintenanceActions": []
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Maintaining Amazon DocumentDB](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-maintain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePendingMaintenanceActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/describe-pending-maintenance-actions.html)」を参照してください。

### `failover-db-cluster`
<a name="docdb_FailoverDbCluster_cli_2_topic"></a>

次のコード例は、`failover-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターを強制的にレプリカにフェイルオーバーするには**  
次の `failover-db-cluster` の例では、Amazon DocumentDB クラスターのサンプルクラスターのプライマリインスタンスをレプリカにフェイルオーバーします。  

```
aws docdb failover-db-cluster \
    --db-cluster-identifier sample-cluster
```
出力:  

```
{
    "DBCluster": {
        "AssociatedRoles": [],
        "DBClusterIdentifier": "sample-cluster",
        "EngineVersion": "3.6.0",
        "DBSubnetGroup": "default",
        "MasterUsername": "master-user",
        "EarliestRestorableTime": "2019-03-15T20:30:47.020Z",
        "Endpoint": "sample-cluster.cluster-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2c",
            "us-west-2b"
        ],
        "LatestRestorableTime": "2019-03-18T21:35:23.548Z",
        "PreferredMaintenanceWindow": "sat:04:30-sat:05:00",
        "PreferredBackupWindow": "00:00-00:30",
        "Port": 27017,
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-77186e0d",
                "Status": "active"
            }
        ],
        "StorageEncrypted": false,
        "ClusterCreateTime": "2019-03-15T20:29:58.836Z",
        "MultiAZ": true,
        "Status": "available",
        "DBClusterMembers": [
            {
                "DBClusterParameterGroupStatus": "in-sync",
                "IsClusterWriter": false,
                "DBInstanceIdentifier": "sample-cluster",
                "PromotionTier": 1
            },
            {
                "DBClusterParameterGroupStatus": "in-sync",
                "IsClusterWriter": true,
                "DBInstanceIdentifier": "sample-cluster2",
                "PromotionTier": 2
            }
        ],
        "EnabledCloudwatchLogsExports": [
            "audit"
        ],
        "DBClusterParameterGroup": "default.docdb3.6",
        "HostedZoneId": "ZNKXH85TT8WVW",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster",
        "BackupRetentionPeriod": 3,
        "DbClusterResourceId": "cluster-UP4EF2PVDDFVHHDJQTYDAIGHLE",
        "ReaderEndpoint": "sample-cluster.cluster-ro-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "Engine": "docdb"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Amazon DocumentDB Failover](https://docs.aws.amazon.com/documentdb/latest/developerguide/failover.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[FailoverDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/failover-db-cluster.html)」を参照してください。

### `list-tags-for-resource`
<a name="docdb_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB リソースのすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Amazon DocumentDB クラスター `sample-cluster` のすべてのタグを一覧表示します。  

```
aws docdb list-tags-for-resource \
    --resource-name arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster
```
出力:  

```
{
    "TagList": [
        {
            "Key": "A",
            "Value": "ALPHA"
        },
        {
            "Key": "B",
            "Value": ""
        },
        {
            "Key": "C",
            "Value": "CHARLIE"
        }
    ]
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Listing Tags on an Amazon DocumentDB Resource](https://docs.aws.amazon.com/documentdb/latest/developerguide/tagging.html#tagging-list)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/list-tags-for-resource.html)」を参照してください。

### `modify-db-cluster-parameter-group`
<a name="docdb_ModifyDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`modify-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターパラメータグループを変更するには**  
次の `modify-db-cluster-parameter-group` の例では、2 つのパラメータ `audit_logs` と `ttl_monitor` を有効に設定して、Amazon DocumentDB クラスターパラメータグループ `custom3-6-param-grp` を変更します。変更は次回の再起動時に適用されます。  

```
aws docdb modify-db-cluster-parameter-group \
    --db-cluster-parameter-group-name custom3-6-param-grp \
    --parameters ParameterName=audit_logs,ParameterValue=enabled,ApplyMethod=pending-reboot \
                 ParameterName=ttl_monitor,ParameterValue=enabled,ApplyMethod=pending-reboot
```
出力:  

```
{
    "DBClusterParameterGroupName": "custom3-6-param-grp"
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Modifying an Amazon DocumentDB Cluster Parameter Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameter-group-modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/modify-db-cluster-parameter-group.html)」を参照してください。

### `modify-db-cluster-snapshot-attribute`
<a name="docdb_ModifyDbClusterSnapshotAttribute_cli_2_topic"></a>

次のコード例は、`modify-db-cluster-snapshot-attribute` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon DocumentDB スナップショットに属性を追加するには**  
次の `modify-db-cluster-snapshot-attribute` の例では、Amazon DocumentDB クラスタースナップショットに 4 つの属性値を追加します。  

```
aws docdb modify-db-cluster-snapshot-attribute \
    --db-cluster-snapshot-identifier sample-cluster-snapshot \
    --attribute-name restore \
    --values-to-add 123456789011 123456789012 123456789013
```
出力:  

```
{
    "DBClusterSnapshotAttributesResult": {
        "DBClusterSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "123456789011",
                    "123456789012",
                    "123456789013"
                ]
            }
        ],
        "DBClusterSnapshotIdentifier": "sample-cluster-snapshot"
    }
}
```
**例 2: Amazon DocumentDB スナップショットから属性を削除するには**  
次の `modify-db-cluster-snapshot-attribute` の例では、Amazon DocumentDB クラスタースナップショットから 2 つの属性値を削除します。  

```
aws docdb modify-db-cluster-snapshot-attribute \
    --db-cluster-snapshot-identifier sample-cluster-snapshot \
    --attribute-name restore \
    --values-to-remove 123456789012
```
出力:  

```
{
    "DBClusterSnapshotAttributesResult": {
        "DBClusterSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "123456789011",
                    "123456789013"
                ]
            }
        ],
        "DBClusterSnapshotIdentifier": "sample-cluster-snapshot"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[ModifyDBClusterSnapshotAttribute](https://docs.aws.amazon.com/documentdb/latest/developerguide/API_ModifyDBClusterSnapshotAttribute.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbClusterSnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/modify-db-cluster-snapshot-attribute.html)」を参照してください。

### `modify-db-cluster`
<a name="docdb_ModifyDbCluster_cli_2_topic"></a>

次のコード例は、`modify-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターを変更するには**  
次の `modify-db-cluster` の例では、自動バックアップの保持期間を 7 日間に設定し、バックアップとメンテナンスの両方の優先期間を変更して、Amazon DocumentDB クラスター `sample-cluster` を変更します。変更はすべて、次のメンテナンス時に適用されます。  

```
aws docdb modify-db-cluster \
    --db-cluster-identifier sample-cluster \
    --no-apply-immediately \
    --backup-retention-period 7 \
    --preferred-backup-window 18:00-18:30 \
    --preferred-maintenance-window sun:20:00-sun:20:30
```
出力:  

```
{
    "DBCluster": {
        "Endpoint": "sample-cluster.cluster-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "DBClusterMembers": [
            {
                "DBClusterParameterGroupStatus": "in-sync",
                "DBInstanceIdentifier": "sample-cluster",
                "IsClusterWriter": true,
                "PromotionTier": 1
            },
            {
                "DBClusterParameterGroupStatus": "in-sync",
                "DBInstanceIdentifier": "sample-cluster2",
                "IsClusterWriter": false,
                "PromotionTier": 2
            }
        ],
        "HostedZoneId": "ZNKXH85TT8WVW",
        "StorageEncrypted": false,
        "PreferredBackupWindow": "18:00-18:30",
        "MultiAZ": true,
        "EngineVersion": "3.6.0",
        "MasterUsername": "master-user",
        "ReaderEndpoint": "sample-cluster.cluster-ro-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "DBSubnetGroup": "default",
        "LatestRestorableTime": "2019-03-18T22:08:13.408Z",
        "EarliestRestorableTime": "2019-03-15T20:30:47.020Z",
        "PreferredMaintenanceWindow": "sun:20:00-sun:20:30",
        "AssociatedRoles": [],
        "EnabledCloudwatchLogsExports": [
            "audit"
        ],
        "Engine": "docdb",
        "DBClusterParameterGroup": "default.docdb3.6",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster",
        "BackupRetentionPeriod": 7,
        "DBClusterIdentifier": "sample-cluster",
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2c",
            "us-west-2b"
        ],
        "Status": "available",
        "DbClusterResourceId": "cluster-UP4EF2PVDDFVHHDJQTYDAIGHLE",
        "ClusterCreateTime": "2019-03-15T20:29:58.836Z",
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-77186e0d",
                "Status": "active"
            }
        ],
        "Port": 27017
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Modifying an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/modify-db-cluster.html)」を参照してください。

### `modify-db-instance`
<a name="docdb_ModifyDbInstance_cli_2_topic"></a>

次のコード例は、`modify-db-instance` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB インスタンスを変更するには**  
次の `modify-db-instance` の例では、インスタンスクラスを `db.r4.4xlarge` に変更し、昇格階層を `5` に変更して、Amazon DocumentDB インスタンス `sample-cluster2` を変更します。変更はすぐに適用されますが、インスタンスステータスが使用可能になった後にのみ表示されます。  

```
aws docdb modify-db-instance \
    --db-instance-identifier sample-cluster2 \
    --apply-immediately \
    --db-instance-class db.r4.4xlarge \
    --promotion-tier 5
```
出力:  

```
{
    "DBInstance": {
        "EngineVersion": "3.6.0",
        "StorageEncrypted": false,
        "DBInstanceClass": "db.r4.large",
        "PreferredMaintenanceWindow": "mon:08:39-mon:09:09",
        "AutoMinorVersionUpgrade": true,
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-77186e0d",
                "Status": "active"
            }
        ],
        "PreferredBackupWindow": "18:00-18:30",
        "EnabledCloudwatchLogsExports": [
            "audit"
        ],
        "AvailabilityZone": "us-west-2f",
        "DBInstanceIdentifier": "sample-cluster2",
        "InstanceCreateTime": "2019-03-15T20:36:06.338Z",
        "Engine": "docdb",
        "BackupRetentionPeriod": 7,
        "DBSubnetGroup": {
            "DBSubnetGroupName": "default",
            "DBSubnetGroupDescription": "default",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-4e26d263",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-afc329f4",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2c"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-53ab3636",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2d"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-991cb8d0",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2b"
                    },
                    "SubnetStatus": "Active"
                }
            ],
            "VpcId": "vpc-91280df6"
        },
        "PromotionTier": 2,
        "Endpoint": {
            "Address": "sample-cluster2.corcjozrlsfc.us-west-2.docdb.amazonaws.com",
            "HostedZoneId": "ZNKXH85TT8WVW",
            "Port": 27017
        },
        "DbiResourceId": "db-A2GIKUV6KPOHITGGKI2NHVISZA",
        "DBClusterIdentifier": "sample-cluster",
        "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
        "PendingModifiedValues": {
            "DBInstanceClass": "db.r4.4xlarge"
        },
        "PubliclyAccessible": false,
        "DBInstanceStatus": "available"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Modifying an Amazon DocumentDB Instance](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/modify-db-instance.html)」を参照してください。

### `modify-db-subnet-group`
<a name="docdb_ModifyDbSubnetGroup_cli_2_topic"></a>

次のコード例は、`modify-db-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB サブネットグループを変更するには**  
次の `modify-db-subnet-group` の例では、指定したサブネットと新しい説明を追加して、サブネットグループ `sample-subnet-group` を変更します。  

```
aws docdb modify-db-subnet-group \
    --db-subnet-group-name sample-subnet-group \
    --subnet-ids subnet-b3806e8f subnet-53ab3636 subnet-991cb8d0 \
    --db-subnet-group-description "New subnet description"
```
出力:  

```
{
    "DBSubnetGroup": {
        "DBSubnetGroupName": "sample-subnet-group",
        "SubnetGroupStatus": "Complete",
        "DBSubnetGroupArn": "arn:aws:rds:us-west-2:123456789012:subgrp:sample-subnet-group",
        "VpcId": "vpc-91280df6",
        "DBSubnetGroupDescription": "New subnet description",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-b3806e8f",
                "SubnetStatus": "Active",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2a"
                }
            },
            {
                "SubnetIdentifier": "subnet-53ab3636",
                "SubnetStatus": "Active",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2c"
                }
            },
            {
                "SubnetIdentifier": "subnet-991cb8d0",
                "SubnetStatus": "Active",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2b"
                }
            }
        ]
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Modifying an Amazon DocumentDB Subnet Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/document-db-subnet-groups.html#document-db-subnet-group-modify)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/modify-db-subnet-group.html)」を参照してください。

### `reboot-db-instance`
<a name="docdb_RebootDbInstance_cli_2_topic"></a>

次のコード例は、`reboot-db-instance` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB インスタンスを再起動するには**  
次の `reboot-db-instance` の例では、Amazon DocumentDB インスタンス `sample-cluster2` を再起動します。  

```
aws docdb reboot-db-instance \
    --db-instance-identifier sample-cluster2
```
このコマンドでは何も出力されません。出力:  

```
{
    "DBInstance": {
        "PreferredBackupWindow": "18:00-18:30",
        "DBInstanceIdentifier": "sample-cluster2",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ],
        "DBSubnetGroup": {
            "VpcId": "vpc-91280df6",
            "Subnets": [
                {
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    },
                    "SubnetIdentifier": "subnet-4e26d263"
                },
                {
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2c"
                    },
                    "SubnetIdentifier": "subnet-afc329f4"
                },
                {
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2d"
                    },
                    "SubnetIdentifier": "subnet-53ab3636"
                },
                {
                    "SubnetStatus": "Active",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2b"
                    },
                    "SubnetIdentifier": "subnet-991cb8d0"
                }
            ],
            "SubnetGroupStatus": "Complete",
            "DBSubnetGroupName": "default",
            "DBSubnetGroupDescription": "default"
        },
        "PendingModifiedValues": {},
        "Endpoint": {
            "Address": "sample-cluster2.corcjozrlsfc.us-west-2.docdb.amazonaws.com",
            "HostedZoneId": "ZNKXH85TT8WVW",
            "Port": 27017
        },
        "EnabledCloudwatchLogsExports": [
            "audit"
        ],
        "StorageEncrypted": false,
        "DbiResourceId": "db-A2GIKUV6KPOHITGGKI2NHVISZA",
        "AutoMinorVersionUpgrade": true,
        "Engine": "docdb",
        "InstanceCreateTime": "2019-03-15T20:36:06.338Z",
        "EngineVersion": "3.6.0",
        "PromotionTier": 5,
        "BackupRetentionPeriod": 7,
        "DBClusterIdentifier": "sample-cluster",
        "PreferredMaintenanceWindow": "mon:08:39-mon:09:09",
        "PubliclyAccessible": false,
        "DBInstanceClass": "db.r4.4xlarge",
        "AvailabilityZone": "us-west-2d",
        "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:sample-cluster2",
        "DBInstanceStatus": "rebooting"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Rebooting an Amazon DocumentDB ILnstance](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-instance-reboot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/reboot-db-instance.html)」を参照してください。

### `remove-tags-from-resource`
<a name="docdb_RemoveTagsFromResource_cli_2_topic"></a>

次のコード例は、`remove-tags-from-resource` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB リソースからタグを削除するには**  
次の `remove-tags-from-resource` の例では、Amazon DocumentDB クラスター `sample-cluster` から `B` という名前のキーを持つタグを削除します。  

```
aws docdb remove-tags-from-resource \
    --resource-name arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster \
    --tag-keys B
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Removing Tags from an Amazon DocumentDBResource](https://docs.aws.amazon.com/documentdb/latest/developerguide/tagging.html#tagging-remove)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/remove-tags-from-resource.html)」を参照してください。

### `reset-db-cluster-parameter-group`
<a name="docdb_ResetDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`reset-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**指定したパラメータ値を Amazon DocumentDB パラメータグループのデフォルトにリセットするには**  
次の `reset-db-cluster-parameter-group` の例では、Amazon DocumentDB パラメータグループ `custom3-6-param-grp` のパラメータ `ttl_monitor` をデフォルト値にリセットします。  

```
aws docdb reset-db-cluster-parameter-group \
    --db-cluster-parameter-group-name custom3-6-param-grp \
    --parameters ParameterName=ttl_monitor,ApplyMethod=immediate
```
出力:  

```
{
    "DBClusterParameterGroupName": "custom3-6-param-grp"
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」を参照してください。  
**指定したパラメータ値またはすべてのパラメータ値を Amazon DocumentDB パラメータグループのデフォルトにリセットするには**  
次の `reset-db-cluster-parameter-group` の例では、Amazon DocumentDB パラメータグループ `custom3-6-param-grp` のすべてのパラメータをデフォルト値にリセットします。  

```
aws docdb reset-db-cluster-parameter-group \
    --db-cluster-parameter-group-name custom3-6-param-grp \
    --reset-all-parameters
```
出力:  

```
{
    "DBClusterParameterGroupName": "custom3-6-param-grp"
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Resetting an Amazon DocumentDB Cluster Parameter Group](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-parameter-group-reset.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/reset-db-cluster-parameter-group.html)」を参照してください。

### `restore-db-cluster-from-snapshot`
<a name="docdb_RestoreDbClusterFromSnapshot_cli_2_topic"></a>

次のコード例は、`restore-db-cluster-from-snapshot` を使用する方法を示しています。

**AWS CLI**  
**自動または手動スナップショットから Amazon DocumentDB クラスターを復元するには**  
次の `restore-db-cluster-from-snapshot` の例では、スナップショット `rds:sample-cluster-2019-03-16-00-01` から `sample-cluster-2019-03-16-00-01-restored` という名前の新しい Amazon DocumentDB クラスターを作成します。  

```
aws docdb restore-db-cluster-from-snapshot \
    --db-cluster-identifier sample-cluster-2019-03-16-00-01-restored \
    --engine docdb \
    --snapshot-identifier rds:sample-cluster-2019-03-16-00-01
```
出力:  

```
{
    "DBCluster": {
        "ClusterCreateTime": "2019-03-19T18:45:01.857Z",
        "HostedZoneId": "ZNKXH85TT8WVW",
        "Engine": "docdb",
        "DBClusterMembers": [],
        "MultiAZ": false,
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2c",
            "us-west-2b"
        ],
        "StorageEncrypted": false,
        "ReaderEndpoint": "sample-cluster-2019-03-16-00-01-restored.cluster-ro-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "Endpoint": "sample-cluster-2019-03-16-00-01-restored.cluster-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "Port": 27017,
        "PreferredBackupWindow": "00:00-00:30",
        "DBSubnetGroup": "default",
        "DBClusterIdentifier": "sample-cluster-2019-03-16-00-01-restored",
        "PreferredMaintenanceWindow": "sat:04:30-sat:05:00",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster-2019-03-16-00-01-restored",
        "DBClusterParameterGroup": "default.docdb3.6",
        "DbClusterResourceId": "cluster-XOO46Q3RH4LWSYNH3NMZKXPISU",
        "MasterUsername": "master-user",
        "EngineVersion": "3.6.0",
        "BackupRetentionPeriod": 3,
        "AssociatedRoles": [],
        "Status": "creating",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ]
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Restoring from a Cluster Snapshot](https://docs.aws.amazon.com/documentdb/latest/developerguide/backup-restore.restore-from-snapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbClusterFromSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/restore-db-cluster-from-snapshot.html)」を参照してください。

### `restore-db-cluster-to-point-in-time`
<a name="docdb_RestoreDbClusterToPointInTime_cli_2_topic"></a>

次のコード例は、`restore-db-cluster-to-point-in-time` を使用する方法を示しています。

**AWS CLI**  
**手動スナップショットから Amazon DocumentDB クラスターを特定時点に復元するには**  
次の `restore-db-cluster-to-point-in-time` の例では、`sample-cluster-snapshot` を使用し、復元可能な最後の時刻を使用して新しい Amazon DocumentDB クラスター `sample-cluster-pit` を作成します。  

```
aws docdb restore-db-cluster-to-point-in-time \
    --db-cluster-identifier sample-cluster-pit \
    --source-db-cluster-identifier arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster \
    --use-latest-restorable-time
```
出力:  

```
{
    "DBCluster": {
        "StorageEncrypted": false,
        "BackupRetentionPeriod": 3,
        "MasterUsername": "master-user",
        "HostedZoneId": "ZNKXH85TT8WVW",
        "PreferredBackupWindow": "00:00-00:30",
        "MultiAZ": false,
        "DBClusterIdentifier": "sample-cluster-pit",
        "DBSubnetGroup": "default",
        "ClusterCreateTime": "2019-04-03T15:55:21.320Z",
        "AssociatedRoles": [],
        "DBClusterParameterGroup": "default.docdb3.6",
        "DBClusterMembers": [],
        "Status": "creating",
        "AvailabilityZones": [
            "us-west-2a",
            "us-west-2d",
            "us-west-2b"
        ],
        "ReaderEndpoint": "sample-cluster-pit.cluster-ro-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "Port": 27017,
        "Engine": "docdb",
        "EngineVersion": "3.6.0",
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-77186e0d",
                "Status": "active"
            }
        ],
        "PreferredMaintenanceWindow": "sat:04:30-sat:05:00",
        "Endpoint": "sample-cluster-pit.cluster-corcjozrlsfc.us-west-2.docdb.amazonaws.com",
        "DbClusterResourceId": "cluster-NLCABBXOSE2QPQ4GOLZIFWEPLM",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster-pit"
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Restoring a Snapshot to a Point in Time](https://docs.aws.amazon.com/documentdb/latest/developerguide/backup-restore.point-in-time-recovery.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbClusterToPointInTime](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/restore-db-cluster-to-point-in-time.html)」を参照してください。

### `start-db-cluster`
<a name="docdb_StartDbCluster_cli_2_topic"></a>

次のコード例は、`start-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**停止した Amazon DocumentDB クラスターを開始するには**  
次の `start-db-cluster` の例では、指定した Amazon DocumentDB クラスターを起動します。  

```
aws docdb start-db-cluster \
    --db-cluster-identifier sample-cluster
```
出力:  

```
{
    "DBCluster": {
        "ClusterCreateTime": "2019-03-19T18:45:01.857Z",
        "HostedZoneId": "ZNKXH85TT8WVW",
        "Engine": "docdb",
        "DBClusterMembers": [],
        "MultiAZ": false,
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1c",
            "us-east-1f"
        ],
        "StorageEncrypted": false,
        "ReaderEndpoint": "sample-cluster-2019-03-16-00-01-restored.cluster-ro-corcjozrlsfc.us-east-1.docdb.amazonaws.com",
        "Endpoint": "sample-cluster-2019-03-16-00-01-restored.cluster-corcjozrlsfc.us-east-1.docdb.amazonaws.com",
        "Port": 27017,
        "PreferredBackupWindow": "00:00-00:30",
        "DBSubnetGroup": "default",
        "DBClusterIdentifier": "sample-cluster-2019-03-16-00-01-restored",
        "PreferredMaintenanceWindow": "sat:04:30-sat:05:00",
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster-2019-03-16-00-01-restored",
        "DBClusterParameterGroup": "default.docdb3.6",
        "DbClusterResourceId": "cluster-XOO46Q3RH4LWSYNH3NMZKXPISU",
        "MasterUsername": "master-user",
        "EngineVersion": "3.6.0",
        "BackupRetentionPeriod": 3,
        "AssociatedRoles": [],
        "Status": "creating",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ]
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Stopping and Starting an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/start-db-cluster.html)」を参照してください。

### `stop-db-cluster`
<a name="docdb_StopDbCluster_cli_2_topic"></a>

次のコード例は、`stop-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon DocumentDB クラスターの実行を停止するには**  
次の `stop-db-cluster` の例では、指定した Amazon DocumentDB クラスターを停止します。  

```
aws docdb stop-db-cluster \
    --db-cluster-identifier sample-cluster
```
出力:  

```
{
    "DBCluster": {
        "ClusterCreateTime": "2019-03-19T18:45:01.857Z",
        "HostedZoneId": "ZNKXH85TT8WVW",
        "Engine": "docdb",
        "DBClusterMembers": [],
        "MultiAZ": false,
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1c",
            "us-east-1f"
        ],
        "StorageEncrypted": false,
        "ReaderEndpoint": "sample-cluster-2019-03-16-00-01-restored.cluster-ro-corcjozrlsfc.us-east-1.docdb.amazonaws.com",
        "Endpoint": "sample-cluster-2019-03-16-00-01-restored.cluster-corcjozrlsfc.us-east-1.docdb.amazonaws.com",
        "Port": 27017,
        "PreferredBackupWindow": "00:00-00:30",
        "DBSubnetGroup": "default",
        "DBClusterIdentifier": "sample-cluster-2019-03-16-00-01-restored",
        "PreferredMaintenanceWindow": "sat:04:30-sat:05:00",
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster-2019-03-16-00-01-restored",
        "DBClusterParameterGroup": "default.docdb3.6",
        "DbClusterResourceId": "cluster-XOO46Q3RH4LWSYNH3NMZKXPISU",
        "MasterUsername": "master-user",
        "EngineVersion": "3.6.0",
        "BackupRetentionPeriod": 3,
        "AssociatedRoles": [],
        "Status": "creating",
        "VpcSecurityGroups": [
            {
                "Status": "active",
                "VpcSecurityGroupId": "sg-77186e0d"
            }
        ]
    }
}
```
詳細については、「*Amazon DocumentDB デベロッパーガイド*」の「[Stopping and Starting an Amazon DocumentDB Cluster](https://docs.aws.amazon.com/documentdb/latest/developerguide/db-cluster-stop-start.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/docdb/stop-db-cluster.html)」を参照してください。

# を使用した DynamoDB の例 AWS CLI
<a name="cli_2_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-get-item`
<a name="dynamodb_BatchGetItem_cli_2_topic"></a>

次のコード例は、`batch-get-item` を使用する方法を示しています。

**AWS CLI**  
**テーブルから複数の項目を取得するには**  
次の `batch-get-items` の例では、3 つの `GetItem` リクエストのバッチを使用して `MusicCollection` テーブルから複数の項目を読み込み、この操作で使用された読み込み容量ユニットの数を取得します。このコマンドは `AlbumTitle` 属性のみを返します。  

```
aws dynamodb batch-get-item \
    --request-items file://request-items.json \
    --return-consumed-capacity TOTAL
```
`request-items.json` の内容:  

```
{
    "MusicCollection": {
        "Keys": [
            {
                "Artist": {"S": "No One You Know"},
                "SongTitle": {"S": "Call Me Today"}
            },
            {
                "Artist": {"S": "Acme Band"},
                "SongTitle": {"S": "Happy Day"}
            },
            {
                "Artist": {"S": "No One You Know"},
                "SongTitle": {"S": "Scared of My Shadow"}
            }
        ],
        "ProjectionExpression":"AlbumTitle"
    }
}
```
出力:  

```
{
    "Responses": {
        "MusicCollection": [
            {
                "AlbumTitle": {
                    "S": "Somewhat Famous"
                }
            },
            {
                "AlbumTitle": {
                    "S": "Blue Sky Blues"
                }
            },
            {
                "AlbumTitle": {
                    "S": "Louder Than Ever"
                }
            }
        ]
    },
    "UnprocessedKeys": {},
    "ConsumedCapacity": [
        {
            "TableName": "MusicCollection",
            "CapacityUnits": 1.5
        }
    ]
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[バッチオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.BatchOperations)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/batch-get-item.html)」を参照してください。

### `batch-write-item`
<a name="dynamodb_BatchWriteItem_cli_2_topic"></a>

次のコード例は、`batch-write-item` を使用する方法を示しています。

**AWS CLI**  
**テーブルに複数の項目を追加するには**  
次の `batch-write-item` の例は、3 つの `PutItem` リクエストのバッチを使用して、`MusicCollection` テーブルに 3 つの新しい項目を追加します。また、このオペレーションによって消費される書き込み容量ユニットの数、およびオペレーションによって変更されるアイテムコレクションに関する情報も要求します。  

```
aws dynamodb batch-write-item \
    --request-items file://request-items.json \
    --return-consumed-capacity INDEXES \
    --return-item-collection-metrics SIZE
```
`request-items.json` の内容:  

```
{
    "MusicCollection": [
        {
            "PutRequest": {
                "Item": {
                    "Artist": {"S": "No One You Know"},
                    "SongTitle": {"S": "Call Me Today"},
                    "AlbumTitle": {"S": "Somewhat Famous"}
                }
            }
        },
        {
            "PutRequest": {
                "Item": {
                    "Artist": {"S": "Acme Band"},
                    "SongTitle": {"S": "Happy Day"},
                    "AlbumTitle": {"S": "Songs About Life"}
                }
            }
        },
        {
            "PutRequest": {
                "Item": {
                    "Artist": {"S": "No One You Know"},
                    "SongTitle": {"S": "Scared of My Shadow"},
                    "AlbumTitle": {"S": "Blue Sky Blues"}
                }
            }
        }
    ]
}
```
出力:  

```
{
    "UnprocessedItems": {},
    "ItemCollectionMetrics": {
        "MusicCollection": [
            {
                "ItemCollectionKey": {
                    "Artist": {
                        "S": "No One You Know"
                    }
                },
                "SizeEstimateRangeGB": [
                    0.0,
                    1.0
                ]
            },
            {
                "ItemCollectionKey": {
                    "Artist": {
                        "S": "Acme Band"
                    }
                },
                "SizeEstimateRangeGB": [
                    0.0,
                    1.0
                ]
            }
        ]
    },
    "ConsumedCapacity": [
        {
            "TableName": "MusicCollection",
            "CapacityUnits": 6.0,
            "Table": {
                "CapacityUnits": 3.0
            },
            "LocalSecondaryIndexes": {
                "AlbumTitleIndex": {
                    "CapacityUnits": 3.0
                }
            }
        }
    ]
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[バッチオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.BatchOperations)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchWriteItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/batch-write-item.html)」を参照してください。

### `create-backup`
<a name="dynamodb_CreateBackup_cli_2_topic"></a>

次のコード例は、`create-backup` を使用する方法を示しています。

**AWS CLI**  
**既存の DynamoDB テーブルのバックアップを作成するには**  
次の `create-backup` の例では、`MusicCollection` テーブルのバックアップを作成します。  

```
aws dynamodb create-backup \
    --table-name MusicCollection \
    --backup-name MusicCollectionBackup
```
出力:  

```
{
    "BackupDetails": {
        "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01576616366715-b4e58d3a",
        "BackupName": "MusicCollectionBackup",
        "BackupSizeBytes": 0,
        "BackupStatus": "CREATING",
        "BackupType": "USER",
        "BackupCreationDateTime": 1576616366.715
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBackup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-backup.html)」を参照してください。

### `create-global-table`
<a name="dynamodb_CreateGlobalTable_cli_2_topic"></a>

次のコード例は、`create-global-table` を使用する方法を示しています。

**AWS CLI**  
**グローバルテーブルを作成するには**  
次の の`create-global-table`例では、指定された別々の AWS リージョンにある 2 つの同じテーブルからグローバルテーブルを作成します。  

```
aws dynamodb create-global-table \
    --global-table-name MusicCollection \
    --replication-group RegionName=us-east-2 RegionName=us-east-1 \
    --region us-east-2
```
出力:  

```
{
    "GlobalTableDescription": {
        "ReplicationGroup": [
            {
                "RegionName": "us-east-2"
            },
            {
                "RegionName": "us-east-1"
            }
        ],
        "GlobalTableArn": "arn:aws:dynamodb::123456789012:global-table/MusicCollection",
        "CreationDateTime": 1576625818.532,
        "GlobalTableStatus": "CREATING",
        "GlobalTableName": "MusicCollection"
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGlobalTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-global-table.html)」を参照してください。

### `create-table`
<a name="dynamodb_CreateTable_cli_2_topic"></a>

次のコード例は、`create-table` を使用する方法を示しています。

**AWS CLI**  
**例 1: タグ付きのテーブルを作成するには**  
次の `create-table` の例では、指定された属性とキースキーマを使用して、`MusicCollection` という名前のテーブルを作成します。このテーブルはプロビジョニングされたスループットを使用し、保管時にはデフォルトの AWS 所有 CMK を使用して暗号化されます。またこのコマンドは、`Owner` キーと `blueTeam` 値を使用して、テーブルにタグを適用します。  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --tags Key=Owner,Value=blueTeam
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "TableName": "MusicCollection",
        "TableStatus": "CREATING",
        "KeySchema": [
            {
                "KeyType": "HASH",
                "AttributeName": "Artist"
            },
            {
                "KeyType": "RANGE",
                "AttributeName": "SongTitle"
            }
        ],
        "ItemCount": 0,
        "CreationDateTime": "2020-05-26T16:04:41.627000-07:00",
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 2: オンデマンドモードでテーブルを作成するには**  
次の例は、プロビジョニングされたスループットモードではなく、オンデマンドモードを使用して `MusicCollection` というテーブルを作成します。これは、ワークロードが予測できないテーブルに役立ちます。  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --billing-mode PAY_PER_REQUEST
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-27T11:44:10.807000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 0,
            "WriteCapacityUnits": 0
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "BillingModeSummary": {
            "BillingMode": "PAY_PER_REQUEST"
        }
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 3: テーブルを作成してカスタマーマネージド CMK で暗号化するには**  
次の例では、`MusicCollection` という名前のテーブルを作成し、カスタマーマネージド CMK を使用して暗号化します。  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --sse-specification Enabled=true,SSEType=KMS,KMSMasterKeyId=abcd1234-abcd-1234-a123-ab1234a1b234
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-27T11:12:16.431000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "SSEDescription": {
            "Status": "ENABLED",
            "SSEType": "KMS",
            "KMSMasterKeyArn": "arn:aws:kms:us-west-2:123456789012:key/abcd1234-abcd-1234-a123-ab1234a1b234"
        }
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 4: ローカルセカンダリインデックスを持つテーブルを作成するには**  
次の例では、指定された属性とキースキーマを使用して、`AlbumTitleIndex` という名前のローカルセカンダリインデックスを持つ `MusicCollection` という名前のテーブルを作成します。  

```
aws dynamodb create-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=Artist,AttributeType=S AttributeName=SongTitle,AttributeType=S AttributeName=AlbumTitle,AttributeType=S \
    --key-schema AttributeName=Artist,KeyType=HASH AttributeName=SongTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --local-secondary-indexes \
        "[
            {
                \"IndexName\": \"AlbumTitleIndex\",
                \"KeySchema\": [
                    {\"AttributeName\": \"Artist\",\"KeyType\":\"HASH\"},
                    {\"AttributeName\": \"AlbumTitle\",\"KeyType\":\"RANGE\"}
                ],
                \"Projection\": {
                    \"ProjectionType\": \"INCLUDE\",
                    \"NonKeyAttributes\": [\"Genre\", \"Year\"]
                }
            }
        ]"
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "AlbumTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-26T15:59:49.473000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "LocalSecondaryIndexes": [
            {
                "IndexName": "AlbumTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "Artist",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "AlbumTitle",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "INCLUDE",
                    "NonKeyAttributes": [
                        "Genre",
                        "Year"
                    ]
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitleIndex"
            }
        ]
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 5: グローバルセカンダリインデックスを持つテーブルを作成するには**  
次の例では、`GameTitleIndex` という名前のグローバルセカンダリインデックスを持つ `GameScores` という名前のテーブルを作成します。ベーステーブルには、パーティションキー `UserId` とソートキー `GameTitle` があり、特定のゲームの個々のユーザーのベストスコアを効率的に見つけることができます。一方、GSI にはパーティションキー `GameTitle` とソートキー `TopScore` があり、特定のゲームの全体的な最高スコアをすばやく見つけることができます。  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S AttributeName=TopScore,AttributeType=N \
    --key-schema AttributeName=UserId,KeyType=HASH \
                AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --global-secondary-indexes \
        "[
            {
                \"IndexName\": \"GameTitleIndex\",
                \"KeySchema\": [
                    {\"AttributeName\":\"GameTitle\",\"KeyType\":\"HASH\"},
                    {\"AttributeName\":\"TopScore\",\"KeyType\":\"RANGE\"}
                ],
                \"Projection\": {
                    \"ProjectionType\":\"INCLUDE\",
                    \"NonKeyAttributes\":[\"UserId\"]
                },
                \"ProvisionedThroughput\": {
                    \"ReadCapacityUnits\": 10,
                    \"WriteCapacityUnits\": 5
                }
            }
        ]"
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "TopScore",
                "AttributeType": "N"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-26T17:28:15.602000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "GlobalSecondaryIndexes": [
            {
                "IndexName": "GameTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "GameTitle",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "TopScore",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "INCLUDE",
                    "NonKeyAttributes": [
                        "UserId"
                    ]
                },
                "IndexStatus": "CREATING",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 10,
                    "WriteCapacityUnits": 5
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameTitleIndex"
            }
        ]
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 6: 複数のグローバルセカンダリインデックスを持つテーブルを一度に作成するには**  
次の例では、2 つのグローバルセカンダリインデックスを持つ `GameScores` という名前のテーブルを作成します。GSI スキーマはコマンドラインではなくファイルを介して渡されます。  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S AttributeName=TopScore,AttributeType=N AttributeName=Date,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --global-secondary-indexes file://gsi.json
```
`gsi.json` の内容:  

```
[
    {
        "IndexName": "GameTitleIndex",
        "KeySchema": [
            {
                "AttributeName": "GameTitle",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "TopScore",
                "KeyType": "RANGE"
            }
        ],
        "Projection": {
            "ProjectionType": "ALL"
        },
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        }
    },
    {
        "IndexName": "GameDateIndex",
        "KeySchema": [
            {
                "AttributeName": "GameTitle",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "Date",
                "KeyType": "RANGE"
            }
        ],
        "Projection": {
            "ProjectionType": "ALL"
        },
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        }
    }
]
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Date",
                "AttributeType": "S"
            },
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "TopScore",
                "AttributeType": "N"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-08-04T16:40:55.524000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "GlobalSecondaryIndexes": [
            {
                "IndexName": "GameTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "GameTitle",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "TopScore",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "ALL"
                },
                "IndexStatus": "CREATING",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 10,
                    "WriteCapacityUnits": 5
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameTitleIndex"
            },
            {
                "IndexName": "GameDateIndex",
                "KeySchema": [
                    {
                        "AttributeName": "GameTitle",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "Date",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "ALL"
                },
                "IndexStatus": "CREATING",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 5,
                    "WriteCapacityUnits": 5
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/index/GameDateIndex"
            }
        ]
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 7: ストリームが有効なテーブルを作成するには**  
次の例では、DynamoDB ストリームを有効にした状態の `GameScores` という名前のテーブルを作成します。各アイテムの新しいイメージと古いイメージの両方がストリームに書き込まれます。  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --stream-specification StreamEnabled=TRUE,StreamViewType=NEW_AND_OLD_IMAGES
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2020-05-27T10:49:34.056000-07:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "StreamSpecification": {
            "StreamEnabled": true,
            "StreamViewType": "NEW_AND_OLD_IMAGES"
        },
        "LatestStreamLabel": "2020-05-27T17:49:34.056",
        "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/stream/2020-05-27T17:49:34.056"
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB テーブルの基本的なオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html)」を参照してください。**  
**例 8: Keys-Only ストリームが有効なテーブルを作成するには**  
次の例では、DynamoDB ストリームを有効にした状態の `GameScores` という名前のテーブルを作成します。変更された項目のキー属性のみがストリームに書き込まれます。  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --stream-specification StreamEnabled=TRUE,StreamViewType=KEYS_ONLY
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2023-05-25T18:45:34.140000+00:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "StreamSpecification": {
            "StreamEnabled": true,
            "StreamViewType": "KEYS_ONLY"
        },
        "LatestStreamLabel": "2023-05-25T18:45:34.140",
        "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores/stream/2023-05-25T18:45:34.140",
        "DeletionProtectionEnabled": false
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB Streams の変更データキャプチャ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)」を参照してください。**  
**例 9: Standard Infrequent Access クラスでテーブルを作成するには**  
次の例は、`GameScores` という名前のテーブルを作成し、Standard-Infrequent Access (DynamoDB Standard-IA) テーブルクラスを割り当てます。このテーブルクラスは、ストレージが主なコストとなるように最適化されています。  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --table-class STANDARD_INFREQUENT_ACCESS
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2023-05-25T18:33:07.581000+00:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "TableClassSummary": {
            "TableClass": "STANDARD_INFREQUENT_ACCESS"
        },
        "DeletionProtectionEnabled": false
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[テーブルクラス](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.TableClasses.html)」を参照してください。**  
**例 10: 削除保護を有効にしたテーブルを作成するには**  
次の例では、`GameScores` というテーブルを作成し、削除保護を有効にします。  

```
aws dynamodb create-table \
    --table-name GameScores \
    --attribute-definitions AttributeName=UserId,AttributeType=S AttributeName=GameTitle,AttributeType=S \
    --key-schema AttributeName=UserId,KeyType=HASH AttributeName=GameTitle,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=10,WriteCapacityUnits=5 \
    --deletion-protection-enabled
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "GameTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "UserId",
                "AttributeType": "S"
            }
        ],
        "TableName": "GameScores",
        "KeySchema": [
            {
                "AttributeName": "UserId",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "GameTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": "2023-05-25T23:02:17.093000+00:00",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 10,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/GameScores",
        "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "DeletionProtectionEnabled": true
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[削除保護の使用](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeletionProtection)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/create-table.html)」を参照してください。

### `delete-backup`
<a name="dynamodb_DeleteBackup_cli_2_topic"></a>

次のコード例は、`delete-backup` を使用する方法を示しています。

**AWS CLI**  
**既存の DynamoDB バックアップを削除するには**  
次の `delete-backup` の例は、指定した既存のバックアップを削除します。  

```
aws dynamodb delete-backup \
    --backup-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01576616366715-b4e58d3a
```
出力:  

```
{
    "BackupDescription": {
        "BackupDetails": {
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01576616366715-b4e58d3a",
            "BackupName": "MusicCollectionBackup",
            "BackupSizeBytes": 0,
            "BackupStatus": "DELETED",
            "BackupType": "USER",
            "BackupCreationDateTime": 1576616366.715
        },
        "SourceTableDetails": {
            "TableName": "MusicCollection",
            "TableId": "b0c04bcc-309b-4352-b2ae-9088af169fe2",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "TableSizeBytes": 0,
            "KeySchema": [
                {
                    "AttributeName": "Artist",
                    "KeyType": "HASH"
                },
                {
                    "AttributeName": "SongTitle",
                    "KeyType": "RANGE"
                }
            ],
            "TableCreationDateTime": 1576615228.571,
            "ProvisionedThroughput": {
                "ReadCapacityUnits": 5,
                "WriteCapacityUnits": 5
            },
            "ItemCount": 0,
            "BillingMode": "PROVISIONED"
        },
        "SourceTableFeatureDetails": {}
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBackup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-backup.html)」を参照してください。

### `delete-item`
<a name="dynamodb_DeleteItem_cli_2_topic"></a>

次のコード例は、`delete-item` を使用する方法を示しています。

**AWS CLI**  
**例 1: 項目を削除するには**  
次の `delete-item` の例は、`MusicCollection` テーブルから項目を削除し、削除した項目とそのリクエストで使用された容量に関する詳細を取得します。  

```
aws dynamodb delete-item \
    --table-name MusicCollection \
    --key file://key.json \
    --return-values ALL_OLD \
    --return-consumed-capacity TOTAL \
    --return-item-collection-metrics SIZE
```
`key.json` の内容:  

```
{
    "Artist": {"S": "No One You Know"},
    "SongTitle": {"S": "Scared of My Shadow"}
}
```
出力:  

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Blue Sky Blues"
        },
        "Artist": {
            "S": "No One You Know"
        },
        "SongTitle": {
            "S": "Scared of My Shadow"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 2.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "No One You Know"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目を書き込みます](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
**例 2: 条件付きで項目を削除するには**  
次の例では、`ProductCategory` が `Sporting Goods` または `Gardening Supplies` で、その価格が 500 および 600 の場合のみ、`ProductCatalog` テーブルから項目を削除します。削除された項目に関する詳細が返されます。  

```
aws dynamodb delete-item \
    --table-name ProductCatalog \
    --key '{"Id":{"N":"456"}}' \
    --condition-expression "(ProductCategory IN (:cat1, :cat2)) and (#P between :lo and :hi)" \
    --expression-attribute-names file://names.json \
    --expression-attribute-values file://values.json \
    --return-values ALL_OLD
```
`names.json` の内容:  

```
{
    "#P": "Price"
}
```
`values.json` の内容:  

```
{
    ":cat1": {"S": "Sporting Goods"},
    ":cat2": {"S": "Gardening Supplies"},
    ":lo": {"N": "500"},
    ":hi": {"N": "600"}
}
```
出力:  

```
{
    "Attributes": {
        "Id": {
            "N": "456"
        },
        "Price": {
            "N": "550"
        },
        "ProductCategory": {
            "S": "Sporting Goods"
        }
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目を書き込みます](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-item.html)」を参照してください。

### `delete-table`
<a name="dynamodb_DeleteTable_cli_2_topic"></a>

次のコード例は、`delete-table` を使用する方法を示しています。

**AWS CLI**  
**テーブルを削除するには**  
以下の `delete-table` の例は `MusicCollection` テーブルを削除します。  

```
aws dynamodb delete-table \
    --table-name MusicCollection
```
出力:  

```
{
    "TableDescription": {
        "TableStatus": "DELETING",
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableName": "MusicCollection",
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        }
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[テーブルの削除](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DeleteTable)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/delete-table.html)」を参照してください。

### `describe-backup`
<a name="dynamodb_DescribeBackup_cli_2_topic"></a>

次のコード例は、`describe-backup` を使用する方法を示しています。

**AWS CLI**  
**テーブルの既存のバックアップに関する情報を取得するには**  
次の `describe-backup` の例では、指定し既存のバックアップの情報を表示します。  

```
aws dynamodb describe-backup \
    --backup-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01576616366715-b4e58d3a
```
出力:  

```
{
    "BackupDescription": {
        "BackupDetails": {
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01576616366715-b4e58d3a",
            "BackupName": "MusicCollectionBackup",
            "BackupSizeBytes": 0,
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupCreationDateTime": 1576616366.715
        },
        "SourceTableDetails": {
            "TableName": "MusicCollection",
            "TableId": "b0c04bcc-309b-4352-b2ae-9088af169fe2",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "TableSizeBytes": 0,
            "KeySchema": [
                {
                    "AttributeName": "Artist",
                    "KeyType": "HASH"
                },
                {
                    "AttributeName": "SongTitle",
                    "KeyType": "RANGE"
                }
            ],
            "TableCreationDateTime": 1576615228.571,
            "ProvisionedThroughput": {
                "ReadCapacityUnits": 5,
                "WriteCapacityUnits": 5
            },
            "ItemCount": 0,
            "BillingMode": "PROVISIONED"
        },
        "SourceTableFeatureDetails": {}
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBackup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-backup.html)」を参照してください。

### `describe-continuous-backups`
<a name="dynamodb_DescribeContinuousBackups_cli_2_topic"></a>

次のコード例は、`describe-continuous-backups` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB テーブルの継続的バックアップに関する情報を取得するには**  
次の `describe-continuous-backups` の例では、`MusicCollection` テーブルの継続的バックアップ設定の詳細を表示します。  

```
aws dynamodb describe-continuous-backups \
    --table-name MusicCollection
```
出力:  

```
{
    "ContinuousBackupsDescription": {
        "ContinuousBackupsStatus": "ENABLED",
        "PointInTimeRecoveryDescription": {
            "PointInTimeRecoveryStatus": "DISABLED"
        }
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Point-in-Time Recovery for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeContinuousBackups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-continuous-backups.html)」を参照してください。

### `describe-contributor-insights`
<a name="dynamodb_DescribeContributorInsights_cli_2_topic"></a>

次のコード例は、`describe-contributor-insights` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB テーブルの Contributor Insights 設定を表示するには**  
次の `describe-contributor-insights` の例では、`MusicCollection` テーブルと `AlbumTitle-index` グローバルセカンダリインデックスの Contributor Insights 設定を表示します。  

```
aws dynamodb describe-contributor-insights \
    --table-name MusicCollection \
    --index-name AlbumTitle-index
```
出力:  

```
{
    "TableName": "MusicCollection",
    "IndexName": "AlbumTitle-index",
    "ContributorInsightsRuleList": [
        "DynamoDBContributorInsights-PKC-MusicCollection-1576629651520",
        "DynamoDBContributorInsights-SKC-MusicCollection-1576629651520",
        "DynamoDBContributorInsights-PKT-MusicCollection-1576629651520",
        "DynamoDBContributorInsights-SKT-MusicCollection-1576629651520"
    ],
    "ContributorInsightsStatus": "ENABLED",
    "LastUpdateDateTime": 1576629654.78
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Analyzing Data Access Using CloudWatch Contributor Insights for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/contributorinsights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeContributorInsights](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-contributor-insights.html)」を参照してください。

### `describe-endpoints`
<a name="dynamodb_DescribeEndpoints_cli_2_topic"></a>

次のコード例は、`describe-endpoints` を使用する方法を示しています。

**AWS CLI**  
**リージョンエンドポイント情報を表示するには**  
次の の`describe-endpoints`例では、現在の AWS リージョンのエンドポイントに関する詳細を表示します。  

```
aws dynamodb describe-endpoints
```
出力:  

```
{
    "Endpoints": [
        {
            "Address": "dynamodb.us-west-2.amazonaws.com",
            "CachePeriodInMinutes": 1440
        }
    ]
}
```
詳細については、「*AWS 全般リファレンス*」の「[Amazon DynamoDB Endpoints and Quotas](https://docs.aws.amazon.com/general/latest/gr/ddb.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-endpoints.html)」を参照してください。

### `describe-global-table-settings`
<a name="dynamodb_DescribeGlobalTableSettings_cli_2_topic"></a>

次のコード例は、`describe-global-table-settings` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB グローバルテーブルの設定に関する情報を取得するには**  
次の `describe-global-table-settings` の例では、`MusicCollection` グローバルテーブルの設定を表示します。  

```
aws dynamodb describe-global-table-settings \
    --global-table-name MusicCollection
```
出力:  

```
{
    "GlobalTableName": "MusicCollection",
    "ReplicaSettings": [
        {
            "RegionName": "us-east-1",
            "ReplicaStatus": "ACTIVE",
            "ReplicaProvisionedReadCapacityUnits": 10,
            "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            },
            "ReplicaProvisionedWriteCapacityUnits": 5,
            "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            }
        },
        {
            "RegionName": "us-east-2",
            "ReplicaStatus": "ACTIVE",
            "ReplicaProvisionedReadCapacityUnits": 10,
            "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            },
            "ReplicaProvisionedWriteCapacityUnits": 5,
            "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            }
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGlobalTableSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-global-table-settings.html)」を参照してください。

### `describe-global-table`
<a name="dynamodb_DescribeGlobalTable_cli_2_topic"></a>

次のコード例は、`describe-global-table` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB グローバルテーブルに関する情報を表示するには**  
次の `describe-global-table` の例では、`MusicCollection` グローバルテーブルの詳細を表示します。  

```
aws dynamodb describe-global-table \
    --global-table-name MusicCollection
```
出力:  

```
{
    "GlobalTableDescription": {
        "ReplicationGroup": [
            {
                "RegionName": "us-east-2"
            },
            {
                "RegionName": "us-east-1"
            }
        ],
        "GlobalTableArn": "arn:aws:dynamodb::123456789012:global-table/MusicCollection",
        "CreationDateTime": 1576625818.532,
        "GlobalTableStatus": "ACTIVE",
        "GlobalTableName": "MusicCollection"
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGlobalTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-global-table.html)」を参照してください。

### `describe-limits`
<a name="dynamodb_DescribeLimits_cli_2_topic"></a>

次のコード例は、`describe-limits` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされたキャパシティの制限を表示するには**  
次の の`describe-limits`例では、現在の AWS リージョンのアカウントのプロビジョンドキャパシティ制限を表示します。  

```
aws dynamodb describe-limits
```
出力:  

```
{
    "AccountMaxReadCapacityUnits": 80000,
    "AccountMaxWriteCapacityUnits": 80000,
    "TableMaxReadCapacityUnits": 40000,
    "TableMaxWriteCapacityUnits": 40000
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Limits in DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-limits.html)」を参照してください。

### `describe-table-replica-auto-scaling`
<a name="dynamodb_DescribeTableReplicaAutoScaling_cli_2_topic"></a>

次のコード例は、`describe-table-replica-auto-scaling` を使用する方法を示しています。

**AWS CLI**  
**グローバルテーブルのレプリカ間で自動スケーリング設定を表示するには**  
次の `describe-table-replica-auto-scaling` の例では、`MusicCollection` グローバルテーブルのレプリカ間の自動スケーリング設定を表示します。  

```
aws dynamodb describe-table-replica-auto-scaling \
    --table-name MusicCollection
```
出力:  

```
{
    "TableAutoScalingDescription": {
        "TableName": "MusicCollection",
        "TableStatus": "ACTIVE",
        "Replicas": [
            {
                "RegionName": "us-east-1",
                "GlobalSecondaryIndexes": [],
                "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                    "MinimumUnits": 5,
                    "MaximumUnits": 40000,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBReadCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 70.0
                            }
                        }
                    ]
                },
                "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                    "MinimumUnits": 5,
                    "MaximumUnits": 40000,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBWriteCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 70.0
                            }
                        }
                    ]
                },
                "ReplicaStatus": "ACTIVE"
            },
            {
                "RegionName": "us-east-2",
                "GlobalSecondaryIndexes": [],
                "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                    "MinimumUnits": 5,
                    "MaximumUnits": 40000,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBReadCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 70.0
                            }
                        }
                    ]
                },
                "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                    "MinimumUnits": 5,
                    "MaximumUnits": 40000,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBWriteCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 70.0
                            }
                        }
                    ]
                },
                "ReplicaStatus": "ACTIVE"
            }
        ]
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTableReplicaAutoScaling](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-table-replica-auto-scaling.html)」を参照してください。

### `describe-table`
<a name="dynamodb_DescribeTable_cli_2_topic"></a>

次のコード例は、`describe-table` を使用する方法を示しています。

**AWS CLI**  
**テーブルを記述するには**  
次の `describe-table` の例は、`MusicCollection` テーブルを記述します。  

```
aws dynamodb describe-table \
    --table-name MusicCollection
```
出力:  

```
{
    "Table": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "WriteCapacityUnits": 5,
            "ReadCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "TableName": "MusicCollection",
        "TableStatus": "ACTIVE",
        "KeySchema": [
            {
                "KeyType": "HASH",
                "AttributeName": "Artist"
            },
            {
                "KeyType": "RANGE",
                "AttributeName": "SongTitle"
            }
        ],
        "ItemCount": 0,
        "CreationDateTime": 1421866952.062
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[表の説明](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.DescribeTable)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-table.html)」を参照してください。

### `describe-time-to-live`
<a name="dynamodb_DescribeTimeToLive_cli_2_topic"></a>

次のコード例は、`describe-time-to-live` を使用する方法を示しています。

**AWS CLI**  
**テーブルの Time to Live 設定を表示するには**  
次の `describe-time-to-live` の例は、`MusicCollection` テーブルの Time to Live 設定を表示します。  

```
aws dynamodb describe-time-to-live \
    --table-name MusicCollection
```
出力:  

```
{
    "TimeToLiveDescription": {
        "TimeToLiveStatus": "ENABLED",
        "AttributeName": "ttl"
    }
}
```
詳細については、「**Amazon DynamoDB デベロッパーガイド」の「[Time to Live (TTL)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html)」を参照してください。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DescribeTimeToLive](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/describe-time-to-live.html)」を参照してください。

### `get-item`
<a name="dynamodb_GetItem_cli_2_topic"></a>

次のコード例は、`get-item` を使用する方法を示しています。

**AWS CLI**  
**例 1: テーブル内の項目を読み込むには**  
次の `get-item` の例は、`MusicCollection` テーブルから項目を取得します。テーブルにはハッシュおよび範囲プライマリキー (`Artist`および`SongTitle`) があるため、これらの属性の両方を指定する必要があります。このコマンドは、オペレーションによって消費される読み込み容量に関する情報も要求します。  

```
aws dynamodb get-item \
    --table-name MusicCollection \
    --key file://key.json \
    --return-consumed-capacity TOTAL
```
`key.json` の内容:  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
出力:  

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目の読み込み](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)」を参照してください。**  
**例 2: 整合性のある読み込みを使用して項目を読み込むには**  
次の例では、強力な整合性のある読み込みを使用して `MusicCollection` テーブルから項目を読み込みます。  

```
aws dynamodb get-item \
    --table-name MusicCollection \
    --key file://key.json \
    --consistent-read \
    --return-consumed-capacity TOTAL
```
`key.json` の内容:  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
出力:  

```
{
    "Item": {
        "AlbumTitle": {
            "S": "Songs About Life"
        },
        "SongTitle": {
            "S": "Happy Day"
        },
        "Artist": {
            "S": "Acme Band"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目の読み込み](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)」を参照してください。**  
**例 3: 項目の特定の属性を取得するには**  
次の例は、射影式を使用して目的のアイテムの 3 つの属性のみを取得します。  

```
aws dynamodb get-item \
    --table-name ProductCatalog \
    --key '{"Id": {"N": "102"}}' \
    --projection-expression "#T, #C, #P" \
    --expression-attribute-names file://names.json
```
`names.json` の内容:  

```
{
    "#T": "Title",
    "#C": "ProductCategory",
    "#P": "Price"
}
```
出力:  

```
{
    "Item": {
        "Price": {
            "N": "20"
        },
        "Title": {
            "S": "Book 102 Title"
        },
        "ProductCategory": {
            "S": "Book"
        }
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目の読み込み](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.ReadingData)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/get-item.html)」を参照してください。

### `list-backups`
<a name="dynamodb_ListBackups_cli_2_topic"></a>

次のコード例は、`list-backups` を使用する方法を示しています。

**AWS CLI**  
**例 1: 既存の DynamoDB バックアップをすべて一覧表示するには**  
次の `list-backups` の例では、既存のバックアップをすべて一覧表示します。  

```
aws dynamodb list-backups
```
出力:  

```
{
    "BackupSummaries": [
        {
            "TableName": "MusicCollection",
            "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01234567890123-a1bcd234",
            "BackupName": "MusicCollectionBackup1",
            "BackupCreationDateTime": "2020-02-12T14:41:51.617000-08:00",
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupSizeBytes": 170
        },
        {
            "TableName": "MusicCollection",
            "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01234567890123-b2abc345",
            "BackupName": "MusicCollectionBackup2",
            "BackupCreationDateTime": "2020-06-26T11:08:35.431000-07:00",
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupSizeBytes": 400
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
**例 2: 特定の時間範囲内にユーザーが作成したバックアップを一覧表示するには**  
次の例では、作成日が 2020 年 1 月 1 日から 2020 年 3 月 1 日までの期間内にある、(DynamoDB によって自動的に作成されたバックアップではなく) ユーザーによって作成された `MusicCollection` テーブルのバックアップのみを一覧表示します。  

```
aws dynamodb list-backups \
    --table-name MusicCollection \
    --time-range-lower-bound 1577836800 \
    --time-range-upper-bound 1583020800 \
    --backup-type USER
```
出力:  

```
{
    "BackupSummaries": [
        {
            "TableName": "MusicCollection",
            "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01234567890123-a1bcd234",
            "BackupName": "MusicCollectionBackup1",
            "BackupCreationDateTime": "2020-02-12T14:41:51.617000-08:00",
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupSizeBytes": 170
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
**例 3: ページサイズを制限するには**  
次の例では、既存のすべてのバックアップのリストを返しますが、1 回の呼び出しで 1 つの項目のみを取得し、必要な場合は複数の呼び出しを実行してリスト全体を取得します。デフォルトのページサイズ (1000) を使用して大量のリソースに対してリストコマンドを実行する際に「タイムアウト」が発生する場合、ページサイズを制限してください。  

```
aws dynamodb list-backups \
    --page-size 1
```
出力:  

```
{
    "BackupSummaries": [
        {
            "TableName": "MusicCollection",
            "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01234567890123-a1bcd234",
            "BackupName": "MusicCollectionBackup1",
            "BackupCreationDateTime": "2020-02-12T14:41:51.617000-08:00",
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupSizeBytes": 170
        },
        {
            "TableName": "MusicCollection",
            "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01234567890123-b2abc345",
            "BackupName": "MusicCollectionBackup2",
            "BackupCreationDateTime": "2020-06-26T11:08:35.431000-07:00",
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupSizeBytes": 400
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
**例 4: 返される項目の数を制限するには**  
次の例では、返される項目の数を 1 に制限します。レスポンスには、次の結果ページの取得に使用する `NextToken` 値が含まれます。  

```
aws dynamodb list-backups \
    --max-items 1
```
出力:  

```
{
    "BackupSummaries": [
        {
            "TableName": "MusicCollection",
            "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01234567890123-a1bcd234",
            "BackupName": "MusicCollectionBackup1",
            "BackupCreationDateTime": "2020-02-12T14:41:51.617000-08:00",
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupSizeBytes": 170
        }
    ],
    "NextToken": "abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9"
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
**例 5: 次の結果ページを取得するには**  
次のコマンドは、`list-backups` コマンドへの前の呼び出しの `NextToken` 値を使用して、次の結果ページを取得します。この場合のレスポンスには `NextToken` 値が含まれていないため、結果の最後のページに達したことがわかります。  

```
aws dynamodb list-backups \
    --starting-token abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9
```
Output  

```
{
    "BackupSummaries": [
        {
            "TableName": "MusicCollection",
            "TableId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "BackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01234567890123-b2abc345",
            "BackupName": "MusicCollectionBackup2",
            "BackupCreationDateTime": "2020-06-26T11:08:35.431000-07:00",
            "BackupStatus": "AVAILABLE",
            "BackupType": "USER",
            "BackupSizeBytes": 400
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBackups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/list-backups.html)」を参照してください。

### `list-contributor-insights`
<a name="dynamodb_ListContributorInsights_cli_2_topic"></a>

次のコード例は、`list-contributor-insights` を使用する方法を示しています。

**AWS CLI**  
**例 1: Contributor Insights の概要のリストを表示するには**  
次の `list-contributor-insights` の例では、Contributor Insights の概要のリストを示します。  

```
aws dynamodb list-contributor-insights
```
出力:  

```
{
    "ContributorInsightsSummaries": [
        {
            "TableName": "MusicCollection",
            "IndexName": "AlbumTitle-index",
            "ContributorInsightsStatus": "ENABLED"
        },
        {
            "TableName": "ProductCatalog",
            "ContributorInsightsStatus": "ENABLED"
        },
        {
            "TableName": "Forum",
            "ContributorInsightsStatus": "ENABLED"
        },
        {
            "TableName": "Reply",
            "ContributorInsightsStatus": "ENABLED"
        },
        {
            "TableName": "Thread",
            "ContributorInsightsStatus": "ENABLED"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Analyzing Data Access Using CloudWatch Contributor Insights for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/contributorinsights.html)」を参照してください。  
**例 2: 返される項目の数を制限するには**  
次の例では、返される項目の数を 4 に制限します。レスポンスには、次の結果ページの取得に使用する `NextToken` 値が含まれます。  

```
aws dynamodb list-contributor-insights \
    --max-results 4
```
出力:  

```
{
    "ContributorInsightsSummaries": [
        {
            "TableName": "MusicCollection",
            "IndexName": "AlbumTitle-index",
            "ContributorInsightsStatus": "ENABLED"
        },
        {
            "TableName": "ProductCatalog",
            "ContributorInsightsStatus": "ENABLED"
        },
        {
            "TableName": "Forum",
            "ContributorInsightsStatus": "ENABLED"
        }
    ],
    "NextToken": "abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9"
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Analyzing Data Access Using CloudWatch Contributor Insights for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/contributorinsights.html)」を参照してください。  
**例 3: 次の結果ページを取得するには**  
次のコマンドは、`list-contributor-insights` コマンドへの前の呼び出しの `NextToken` 値を使用して、次の結果ページを取得します。この場合のレスポンスには `NextToken` 値が含まれていないため、結果の最後のページに達したことがわかります。  

```
aws dynamodb list-contributor-insights \
    --max-results 4 \
    --next-token abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9
```
出力:  

```
{
    "ContributorInsightsSummaries": [
        {
            "TableName": "Reply",
            "ContributorInsightsStatus": "ENABLED"
        },
        {
            "TableName": "Thread",
            "ContributorInsightsStatus": "ENABLED"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Analyzing Data Access Using CloudWatch Contributor Insights for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/contributorinsights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListContributorInsights](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/list-contributor-insights.html)」を参照してください。

### `list-global-tables`
<a name="dynamodb_ListGlobalTables_cli_2_topic"></a>

次のコード例は、`list-global-tables` を使用する方法を示しています。

**AWS CLI**  
**既存の DynamoDB グローバルテーブルを一覧表示するには**  
次の `list-global-tables` の例では、既存のグローバルテーブルをすべて一覧表示します。  

```
aws dynamodb list-global-tables
```
出力:  

```
{
    "GlobalTables": [
        {
            "GlobalTableName": "MusicCollection",
            "ReplicationGroup": [
                {
                    "RegionName": "us-east-2"
                },
                {
                    "RegionName": "us-east-1"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGlobalTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/list-global-tables.html)」を参照してください。

### `list-tables`
<a name="dynamodb_ListTables_cli_2_topic"></a>

次のコード例は、`list-tables` を使用する方法を示しています。

**AWS CLI**  
**例 1: テーブルを一覧表示するには**  
次の の`list-tables`例では、現在の AWS アカウントとリージョンに関連付けられているすべてのテーブルを一覧表示します。  

```
aws dynamodb list-tables
```
出力:  

```
{
    "TableNames": [
        "Forum",
        "ProductCatalog",
        "Reply",
        "Thread"
    ]
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[テーブル名のリスト化](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.ListTables)」を参照してください。**  
**例 2: ページサイズを制限するには**  
次の例は、既存のすべてのテーブルのリストを返しますが、1 回の呼び出しで 1 つの項目のみを取得し、必要な場合は複数の呼び出しを実行してリスト全体を取得します。デフォルトのページサイズ (1000) を使用して大量のリソースに対してリストコマンドを実行する際に「タイムアウト」が発生する場合、ページサイズを制限してください。  

```
aws dynamodb list-tables \
    --page-size 1
```
出力:  

```
{
    "TableNames": [
        "Forum",
        "ProductCatalog",
        "Reply",
        "Thread"
    ]
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[テーブル名のリスト化](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.ListTables)」を参照してください。**  
**例 3: 返される項目の数を制限するには**  
次の例は、返される項目の数を 2 に制限します。レスポンスには、次の結果ページの取得に使用する `NextToken` 値が含まれます。  

```
aws dynamodb list-tables \
    --max-items 2
```
出力:  

```
{
    "TableNames": [
        "Forum",
        "ProductCatalog"
    ],
    "NextToken": "abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9"
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[テーブル名のリスト化](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.ListTables)」を参照してください。**  
**例 4: 次の結果ページを取得するには**  
次のコマンドは、`list-tables` コマンドへの前の呼び出しの `NextToken` 値を使用して、次の結果ページを取得します。この場合のレスポンスには `NextToken` 値が含まれていないため、結果の最後のページに達したことがわかります。  

```
aws dynamodb list-tables \
    --starting-token abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9
```
出力:  

```
{
    "TableNames": [
        "Reply",
        "Thread"
    ]
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[テーブル名のリスト化](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.ListTables)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/list-tables.html)」を参照してください。

### `list-tags-of-resource`
<a name="dynamodb_ListTagsOfResource_cli_2_topic"></a>

次のコード例は、`list-tags-of-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: DynamoDB リソースのタグを一覧表示するには**  
次の `list-tags-of-resource` の例では、`MusicCollection` テーブルのタグを表示します。  

```
aws dynamodb list-tags-of-resource \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Owner",
            "Value": "blueTeam"
        },
        {
            "Key": "Environment",
            "Value": "Production"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Tagging for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html)」を参照してください。  
**例 2: 返されるタグの数を制限するには**  
次の例では、返されるタグの数を 1 に制限します。レスポンスには、次の結果ページの取得に使用する `NextToken` 値が含まれます。  

```
aws dynamodb list-tags-of-resource \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \
    --max-items 1
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Owner",
            "Value": "blueTeam"
        }
    ],
    "NextToken": "abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9"
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Tagging for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html)」を参照してください。  
**例 3: 次の結果ページを取得するには**  
次のコマンドは、`list-tags-of-resource` コマンドへの前の呼び出しの `NextToken` 値を使用して、次の結果ページを取得します。この場合のレスポンスには `NextToken` 値が含まれていないため、結果の最後のページに達したことがわかります。  

```
aws dynamodb list-tags-of-resource \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \
    --starting-token abCDeFGhiJKlmnOPqrSTuvwxYZ1aBCdEFghijK7LM51nOpqRSTuv3WxY3ZabC5dEFGhI2Jk3LmnoPQ6RST9
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Environment",
            "Value": "Production"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Tagging for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsOfResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/list-tags-of-resource.html)」を参照してください。

### `put-item`
<a name="dynamodb_PutItem_cli_2_topic"></a>

次のコード例は、`put-item` を使用する方法を示しています。

**AWS CLI**  
**例 1: テーブルに項目を追加するには**  
次の `put-item` の例は、*MusicCollection* テーブルに新しい項目を追加します。  

```
aws dynamodb put-item \
    --table-name MusicCollection \
    --item file://item.json \
    --return-consumed-capacity TOTAL \
    --return-item-collection-metrics SIZE
```
`item.json` の内容:  

```
{
    "Artist": {"S": "No One You Know"},
    "SongTitle": {"S": "Call Me Today"},
    "AlbumTitle": {"S": "Greatest Hits"}
}
```
出力:  

```
{
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "No One You Know"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目を書き込みます](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
**例 2: テーブル内の項目を条件付きで上書きするには**  
次の `put-item` の例は、`MusicCollection` テーブル内の既存の項目に `Greatest Hits` の値を持つ `AlbumTitle` 属性がある場合にのみ、その項目を上書きします。このコマンドは、その項目の以前の値を返します。  

```
aws dynamodb put-item \
    --table-name MusicCollection \
    --item file://item.json \
    --condition-expression "#A = :A" \
    --expression-attribute-names file://names.json \
    --expression-attribute-values file://values.json \
    --return-values ALL_OLD
```
`item.json` の内容:  

```
{
    "Artist": {"S": "No One You Know"},
    "SongTitle": {"S": "Call Me Today"},
    "AlbumTitle": {"S": "Somewhat Famous"}
}
```
`names.json` の内容:  

```
{
    "#A": "AlbumTitle"
}
```
`values.json` の内容:  

```
{
    ":A": {"S": "Greatest Hits"}
}
```
出力:  

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Greatest Hits"
        },
        "Artist": {
            "S": "No One You Know"
        },
        "SongTitle": {
            "S": "Call Me Today"
        }
    }
}
```
キーが存在する場合は、次のような出力が表示されます。  

```
A client error (ConditionalCheckFailedException) occurred when calling the PutItem operation: The conditional request failed.
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目を書き込みます](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/put-item.html)」を参照してください。

### `query`
<a name="dynamodb_Query_cli_2_topic"></a>

次のコード例は、`query` を使用する方法を示しています。

**AWS CLI**  
**例 1: テーブルにクエリを実行するには**  
次の `query` の例では、`MusicCollection` テーブルの項目にクエリを実行します。テーブルにはハッシュおよび範囲プライマリキー (`Artist`および`SongTitle`) がありますが、このクエリではハッシュキー値のみを指定します。「No One You Know」という名前のアーティストの曲タイトルが返されます。  

```
aws dynamodb query \
    --table-name MusicCollection \
    --projection-expression "SongTitle" \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json \
    --return-consumed-capacity TOTAL
```
`expression-attributes.json` の内容:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
出力:  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Call Me Today"
            },
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB のクエリオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html)」を参照してください。**  
**例 2: 強力な整合性のある読み込みを使用してテーブルにクエリを実行し、インデックスを降順で走査するには**  
次の例では、最初の例と同じクエリを実行しますが、結果は逆の順序で返され、強力な整合性のある読み込みが使用されます。  

```
aws dynamodb query \
    --table-name MusicCollection \
    --projection-expression "SongTitle" \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json \
    --consistent-read \
    --no-scan-index-forward \
    --return-consumed-capacity TOTAL
```
`expression-attributes.json` の内容:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
出力:  

```
{
    "Items": [
        {
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        },
        {
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 1.0
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB のクエリオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html)」を参照してください。**  
**例 3: 特定の結果を除外するには**  
次の例は、`MusicCollection` をクエリしますが、`AlbumTitle` 属性に特定の値を含む結果を除外します。このフィルターは項目が読み込まれた後に適用されるため、`ScannedCount` または `ConsumedCapacity` には影響しないことに注意してください。  

```
aws dynamodb query \
    --table-name MusicCollection \
    --key-condition-expression "#n1 = :v1" \
    --filter-expression "NOT (#n2 IN (:v2, :v3))" \
    --expression-attribute-names file://names.json \
    --expression-attribute-values file://values.json \
    --return-consumed-capacity TOTAL
```
`values.json` の内容:  

```
{
    ":v1": {"S": "No One You Know"},
    ":v2": {"S": "Blue Sky Blues"},
    ":v3": {"S": "Greatest Hits"}
}
```
`names.json` の内容:  

```
{
    "#n1": "Artist",
    "#n2": "AlbumTitle"
}
```
出力:  

```
{
    "Items": [
        {
            "AlbumTitle": {
                "S": "Somewhat Famous"
            },
            "Artist": {
                "S": "No One You Know"
            },
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 1,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB のクエリオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html)」を参照してください。**  
**例 4: 項目数だけを取得するには**  
次の例は、クエリに一致する項目数を取得しますが、項目自体は取得しません。  

```
aws dynamodb query \
    --table-name MusicCollection \
    --select COUNT \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json
```
`expression-attributes.json` の内容:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
出力:  

```
{
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": null
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB のクエリオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html)」を参照してください。**  
**例 5: インデックスをクエリするには**  
次の例は、ローカルセカンダリインデックス `AlbumTitleIndex` をクエリします。クエリは、ローカルセカンダリインデックスに射影されたベーステーブルのすべての属性を返します。ローカルセカンダリインデックスまたはグローバルセカンダリインデックスをクエリする場合は、`table-name` パラメータを使用してベーステーブルの名前も指定する必要があることに注意してください。  

```
aws dynamodb query \
    --table-name MusicCollection \
    --index-name AlbumTitleIndex \
    --key-condition-expression "Artist = :v1" \
    --expression-attribute-values file://expression-attributes.json \
    --select ALL_PROJECTED_ATTRIBUTES \
    --return-consumed-capacity INDEXES
```
`expression-attributes.json` の内容:  

```
{
    ":v1": {"S": "No One You Know"}
}
```
出力:  

```
{
    "Items": [
        {
            "AlbumTitle": {
                "S": "Blue Sky Blues"
            },
            "Artist": {
                "S": "No One You Know"
            },
            "SongTitle": {
                "S": "Scared of My Shadow"
            }
        },
        {
            "AlbumTitle": {
                "S": "Somewhat Famous"
            },
            "Artist": {
                "S": "No One You Know"
            },
            "SongTitle": {
                "S": "Call Me Today"
            }
        }
    ],
    "Count": 2,
    "ScannedCount": 2,
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 0.5,
        "Table": {
            "CapacityUnits": 0.0
        },
        "LocalSecondaryIndexes": {
            "AlbumTitleIndex": {
                "CapacityUnits": 0.5
            }
        }
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB のクエリオペレーション](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Query](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/query.html)」を参照してください。

### `restore-table-from-backup`
<a name="dynamodb_RestoreTableFromBackup_cli_2_topic"></a>

次のコード例は、`restore-table-from-backup` を使用する方法を示しています。

**AWS CLI**  
**既存のバックアップから DynamoDB テーブルを復元するには**  
次の `restore-table-from-backup` の例では、指定したテーブルを既存のバックアップから削除します。  

```
aws dynamodb restore-table-from-backup \
    --target-table-name MusicCollection \
    --backup-arnarn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01576616366715-b4e58d3a
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection2",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": 1576618274.326,
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection2",
        "TableId": "114865c9-5ef3-496c-b4d1-c4cbdd2d44fb",
        "BillingModeSummary": {
            "BillingMode": "PROVISIONED"
        },
        "RestoreSummary": {
            "SourceBackupArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/backup/01576616366715-b4e58d3a",
            "SourceTableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "RestoreDateTime": 1576616366.715,
            "RestoreInProgress": true
        }
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[On-Demand Backup and Restore for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreTableFromBackup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/restore-table-from-backup.html)」を参照してください。

### `restore-table-to-point-in-time`
<a name="dynamodb_RestoreTableToPointInTime_cli_2_topic"></a>

次のコード例は、`restore-table-to-point-in-time` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB テーブルを特定時点に復元するには**  
次の `restore-table-to-point-in-time` の例では、`MusicCollection` テーブルを指定した時点に復元します。  

```
aws dynamodb restore-table-to-point-in-time \
    --source-table-name MusicCollection \
    --target-table-name MusicCollectionRestore \
    --restore-date-time 1576622404.0
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollectionRestore",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "CREATING",
        "CreationDateTime": 1576623311.86,
        "ProvisionedThroughput": {
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 5,
            "WriteCapacityUnits": 5
        },
        "TableSizeBytes": 0,
        "ItemCount": 0,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollectionRestore",
        "TableId": "befd9e0e-1843-4dc6-a147-d6d00e85cb1f",
        "BillingModeSummary": {
            "BillingMode": "PROVISIONED"
        },
        "RestoreSummary": {
            "SourceTableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
            "RestoreDateTime": 1576622404.0,
            "RestoreInProgress": true
        }
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Point-in-Time Recovery for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreTableToPointInTime](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/restore-table-to-point-in-time.html)」を参照してください。

### `scan`
<a name="dynamodb_Scan_cli_2_topic"></a>

次のコード例は、`scan` を使用する方法を示しています。

**AWS CLI**  
**テーブルをスキャンするには**  
次の `scan` の例は、`MusicCollection` テーブル全体をスキャンし、その結果をアーティスト「No One You Know」の曲に絞り込みます。各項目について、アルバムタイトルと曲タイトルのみが返されます。  

```
aws dynamodb scan \
    --table-name MusicCollection \
    --filter-expression "Artist = :a" \
    --projection-expression "#ST, #AT" \
    --expression-attribute-names file://expression-attribute-names.json \
    --expression-attribute-values file://expression-attribute-values.json
```
`expression-attribute-names.json` の内容:  

```
{
    "#ST": "SongTitle",
    "#AT":"AlbumTitle"
}
```
`expression-attribute-values.json` の内容:  

```
{
    ":a": {"S": "No One You Know"}
}
```
出力:  

```
{
    "Count": 2,
    "Items": [
        {
            "SongTitle": {
                "S": "Call Me Today"
            },
            "AlbumTitle": {
                "S": "Somewhat Famous"
            }
        },
        {
            "SongTitle": {
                "S": "Scared of My Shadow"
            },
            "AlbumTitle": {
                "S": "Blue Sky Blues"
            }
        }
    ],
    "ScannedCount": 3,
    "ConsumedCapacity": null
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[DynamoDB でのスキャンの使用](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Scan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/scan.html)」を参照してください。

### `tag-resource`
<a name="dynamodb_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB リソースにタグを追加するには**  
次の `tag-resource` の例では、タグのキー/値ペアを `MusicCollection` に追加します。  

```
aws dynamodb tag-resource \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \
    --tags Key=Owner,Value=blueTeam
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Tagging for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/tag-resource.html)」を参照してください。

### `transact-get-items`
<a name="dynamodb_TransactGetItems_cli_2_topic"></a>

次のコード例は、`transact-get-items` を使用する方法を示しています。

**AWS CLI**  
**1 つ以上のテーブルから複数の項目をアトミックに取得するには**  
次の `transact-get-items` の例では、複数の項目をアトミックに取得します。  

```
aws dynamodb transact-get-items \
    --transact-items file://transact-items.json \
    --return-consumed-capacity TOTAL
```
`transact-items.json` の内容:  

```
[
    {
        "Get": {
            "Key": {
                "Artist": {"S": "Acme Band"},
                "SongTitle": {"S": "Happy Day"}
            },
            "TableName": "MusicCollection"
        }
    },
    {
        "Get": {
            "Key": {
                "Artist": {"S": "No One You Know"},
                "SongTitle": {"S": "Call Me Today"}
            },
            "TableName": "MusicCollection"
        }
    }
]
```
出力:  

```
{
    "ConsumedCapacity": [
        {
            "TableName": "MusicCollection",
            "CapacityUnits": 4.0,
            "ReadCapacityUnits": 4.0
        }
    ],
    "Responses": [
        {
            "Item": {
                "AlbumTitle": {
                    "S": "Songs About Life"
                },
                "Artist": {
                    "S": "Acme Band"
                },
                "SongTitle": {
                    "S": "Happy Day"
                }
            }
        },
        {
            "Item": {
                "AlbumTitle": {
                    "S": "Somewhat Famous"
                },
                "Artist": {
                    "S": "No One You Know"
                },
                "SongTitle": {
                    "S": "Call Me Today"
                }
            }
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Managing Complex Workflows with DynamoDB Transactions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transactions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TransactGetItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/transact-get-items.html)」を参照してください。

### `transact-write-items`
<a name="dynamodb_TransactWriteItems_cli_2_topic"></a>

次のコード例は、`transact-write-items` を使用する方法を示しています。

**AWS CLI**  
**例 1: 1 つ以上のテーブルに項目をアトミックに書き込むには**  
次の `transact-write-items` の例では、1 つの項目を更新し、別の項目を削除します。いずれかのオペレーションが失敗した場合、または、いずれかのアイテムに `Rating` 属性が含まれている場合、オペレーションは失敗します。  

```
aws dynamodb transact-write-items \
    --transact-items file://transact-items.json \
    --return-consumed-capacity TOTAL \
    --return-item-collection-metrics SIZE
```
`transact-items.json` ファイルの内容:  

```
[
    {
        "Update": {
            "Key": {
                "Artist": {"S": "Acme Band"},
                "SongTitle": {"S": "Happy Day"}
            },
            "UpdateExpression": "SET AlbumTitle = :newval",
            "ExpressionAttributeValues": {
                ":newval": {"S": "Updated Album Title"}
            },
            "TableName": "MusicCollection",
            "ConditionExpression": "attribute_not_exists(Rating)"
        }
    },
    {
        "Delete": {
            "Key": {
                "Artist": {"S": "No One You Know"},
                "SongTitle": {"S": "Call Me Today"}
            },
            "TableName": "MusicCollection",
            "ConditionExpression": "attribute_not_exists(Rating)"
        }
    }
]
```
出力:  

```
{
    "ConsumedCapacity": [
        {
            "TableName": "MusicCollection",
            "CapacityUnits": 10.0,
            "WriteCapacityUnits": 10.0
        }
    ],
    "ItemCollectionMetrics": {
        "MusicCollection": [
            {
                "ItemCollectionKey": {
                    "Artist": {
                        "S": "No One You Know"
                    }
                },
                "SizeEstimateRangeGB": [
                    0.0,
                    1.0
                ]
            },
            {
                "ItemCollectionKey": {
                    "Artist": {
                        "S": "Acme Band"
                    }
                },
                "SizeEstimateRangeGB": [
                    0.0,
                    1.0
                ]
            }
        ]
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Managing Complex Workflows with DynamoDB Transactions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transactions.html)」を参照してください。  
**例 2: クライアントリクエストトークンを使用して項目をアトミックに書き込むには**  
次のコマンドは、クライアントリクエストトークンを使用して `transact-write-items` 呼び出しをべき等なもの、つまり、複数回の呼び出しが 1 回の呼び出しと同じ効果を持つようにします。  

```
aws dynamodb transact-write-items \
    --transact-items file://transact-items.json \
    --client-request-token abc123
```
`transact-items.json` ファイルの内容:  

```
[
    {
        "Update": {
            "Key": {
                "Artist": {"S": "Acme Band"},
                "SongTitle": {"S": "Happy Day"}
            },
            "UpdateExpression": "SET AlbumTitle = :newval",
            "ExpressionAttributeValues": {
                ":newval": {"S": "Updated Album Title"}
            },
            "TableName": "MusicCollection",
            "ConditionExpression": "attribute_not_exists(Rating)"
        }
    },
    {
        "Delete": {
            "Key": {
                "Artist": {"S": "No One You Know"},
                "SongTitle": {"S": "Call Me Today"}
            },
            "TableName": "MusicCollection",
            "ConditionExpression": "attribute_not_exists(Rating)"
        }
    }
]
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Managing Complex Workflows with DynamoDB Transactions](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/transactions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TransactWriteItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/transact-write-items.html)」を参照してください。

### `untag-resource`
<a name="dynamodb_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB リソースからタグを削除するには**  
次の `untag-resource` の例では、キー `Owner` を持つタグを `MusicCollection` テーブルから削除します。  

```
aws dynamodb untag-resource \
    --resource-arn arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection \
    --tag-keys Owner
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Tagging for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/untag-resource.html)」を参照してください。

### `update-continuous-backups`
<a name="dynamodb_UpdateContinuousBackups_cli_2_topic"></a>

次のコード例は、`update-continuous-backups` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB テーブルの継続的バックアップ設定を更新するには**  
次の `update-continuous-backups` の例では、`MusicCollection` テーブルのポイントインタイムリカバリを有効にします。  

```
aws dynamodb update-continuous-backups \
    --table-name MusicCollection \
    --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
```
出力:  

```
{
    "ContinuousBackupsDescription": {
        "ContinuousBackupsStatus": "ENABLED",
        "PointInTimeRecoveryDescription": {
            "PointInTimeRecoveryStatus": "ENABLED",
            "EarliestRestorableDateTime": 1576622404.0,
            "LatestRestorableDateTime": 1576622404.0
        }
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Point-in-Time Recovery for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/PointInTimeRecovery.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateContinuousBackups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-continuous-backups.html)」を参照してください。

### `update-contributor-insights`
<a name="dynamodb_UpdateContributorInsights_cli_2_topic"></a>

次のコード例は、`update-contributor-insights` を使用する方法を示しています。

**AWS CLI**  
**テーブルで Contributor Insights を有効にするには**  
次の `update-contributor-insights` の例では、`MusicCollection` テーブルと `AlbumTitle-index` グローバルセカンダリインデックスで Contributor Insights を有効にします。  

```
aws dynamodb update-contributor-insights \
    --table-name MusicCollection \
    --index-name AlbumTitle-index \
    --contributor-insights-action ENABLE
```
出力:  

```
{
    "TableName": "MusicCollection",
    "IndexName": "AlbumTitle-index",
    "ContributorInsightsStatus": "ENABLING"
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Analyzing Data Access Using CloudWatch Contributor Insights for DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/contributorinsights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateContributorInsights](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-contributor-insights.html)」を参照してください。

### `update-global-table-settings`
<a name="dynamodb_UpdateGlobalTableSettings_cli_2_topic"></a>

次のコード例は、`update-global-table-settings` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB グローバルテーブルのプロビジョニングされた書き込みキャパシティ設定を更新するには**  
次の `update-global-table-settings` の例では、`MusicCollection` グローバルテーブルのプロビジョニングされた書き込みキャパシティを 15 に設定します。  

```
aws dynamodb update-global-table-settings \
    --global-table-name MusicCollection \
    --global-table-provisioned-write-capacity-units 15
```
出力:  

```
{
    "GlobalTableName": "MusicCollection",
    "ReplicaSettings": [
        {
            "RegionName": "eu-west-1",
            "ReplicaStatus": "UPDATING",
            "ReplicaProvisionedReadCapacityUnits": 10,
            "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            },
            "ReplicaProvisionedWriteCapacityUnits": 10,
            "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            }
        },
        {
            "RegionName": "us-east-1",
            "ReplicaStatus": "UPDATING",
            "ReplicaProvisionedReadCapacityUnits": 10,
            "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            },
            "ReplicaProvisionedWriteCapacityUnits": 10,
            "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            }
        },
        {
            "RegionName": "us-east-2",
            "ReplicaStatus": "UPDATING",
            "ReplicaProvisionedReadCapacityUnits": 10,
            "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            },
            "ReplicaProvisionedWriteCapacityUnits": 10,
            "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                "AutoScalingDisabled": true
            }
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGlobalTableSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-global-table-settings.html)」を参照してください。

### `update-global-table`
<a name="dynamodb_UpdateGlobalTable_cli_2_topic"></a>

次のコード例は、`update-global-table` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB グローバルテーブルを更新するには**  
次の `update-global-table` の例では、指定したリージョンのレプリカを `MusicCollection` グローバルテーブルに追加します。  

```
aws dynamodb update-global-table \
    --global-table-name MusicCollection \
    --replica-updates Create={RegionName=eu-west-1}
```
出力:  

```
{
    "GlobalTableDescription": {
        "ReplicationGroup": [
            {
                "RegionName": "eu-west-1"
            },
            {
                "RegionName": "us-east-2"
            },
            {
                "RegionName": "us-east-1"
            }
        ],
        "GlobalTableArn": "arn:aws:dynamodb::123456789012:global-table/MusicCollection",
        "CreationDateTime": 1576625818.532,
        "GlobalTableStatus": "ACTIVE",
        "GlobalTableName": "MusicCollection"
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGlobalTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-global-table.html)」を参照してください。

### `update-item`
<a name="dynamodb_UpdateItem_cli_2_topic"></a>

次のコード例は、`update-item` を使用する方法を示しています。

**AWS CLI**  
**例 1: テーブル内の項目を更新するには**  
次の `update-item` の例では、`MusicCollection` テーブルの項目を更新します。新しい属性 (`Year`) を追加して、`AlbumTitle` 属性を更新します。更新後に表示される項目内の属性はすべて、レスポンスで返されます。  

```
aws dynamodb update-item \
    --table-name MusicCollection \
    --key file://key.json \
    --update-expression "SET #Y = :y, #AT = :t" \
    --expression-attribute-names file://expression-attribute-names.json \
    --expression-attribute-values file://expression-attribute-values.json  \
    --return-values ALL_NEW \
    --return-consumed-capacity TOTAL \
    --return-item-collection-metrics SIZE
```
`key.json` の内容:  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
`expression-attribute-names.json` の内容:  

```
{
    "#Y":"Year", "#AT":"AlbumTitle"
}
```
`expression-attribute-values.json` の内容:  

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
出力:  

```
{
    "Attributes": {
        "AlbumTitle": {
            "S": "Louder Than Ever"
        },
        "Awards": {
            "N": "10"
        },
        "Artist": {
            "S": "Acme Band"
        },
        "Year": {
            "N": "2015"
        },
        "SongTitle": {
            "S": "Happy Day"
        }
    },
    "ConsumedCapacity": {
        "TableName": "MusicCollection",
        "CapacityUnits": 3.0
    },
    "ItemCollectionMetrics": {
        "ItemCollectionKey": {
            "Artist": {
                "S": "Acme Band"
            }
        },
        "SizeEstimateRangeGB": [
            0.0,
            1.0
        ]
    }
}
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目を書き込みます](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
**例 2: 項目を条件付きで更新するには**  
次の例は、既存の項目に `Year` 属性がない場合にのみ、`MusicCollection` テーブル内の項目を更新します。  

```
aws dynamodb update-item \
    --table-name MusicCollection \
    --key file://key.json \
    --update-expression "SET #Y = :y, #AT = :t" \
    --expression-attribute-names file://expression-attribute-names.json \
    --expression-attribute-values file://expression-attribute-values.json  \
    --condition-expression "attribute_not_exists(#Y)"
```
`key.json` の内容:  

```
{
    "Artist": {"S": "Acme Band"},
    "SongTitle": {"S": "Happy Day"}
}
```
`expression-attribute-names.json` の内容:  

```
{
    "#Y":"Year",
    "#AT":"AlbumTitle"
}
```
`expression-attribute-values.json` の内容:  

```
{
    ":y":{"N": "2015"},
    ":t":{"S": "Louder Than Ever"}
}
```
項目にすでに `Year` 属性がある場合、DynamoDB は次の出力を返します。  

```
An error occurred (ConditionalCheckFailedException) when calling the UpdateItem operation: The conditional request failed
```
詳細については、「Amazon DynamoDB ディベロッパーガイド」の「[項目を書き込みます](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html#WorkingWithItems.WritingData)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-item.html)」を参照してください。

### `update-table-replica-auto-scaling`
<a name="dynamodb_UpdateTableReplicaAutoScaling_cli_2_topic"></a>

次のコード例は、`update-table-replica-auto-scaling` を使用する方法を示しています。

**AWS CLI**  
**グローバルテーブルのレプリカ間で自動スケーリング設定を更新するには**  
次の `update-table-replica-auto-scaling` の例では、指定したグローバルテーブルのレプリカ間の書き込みキャパシティ自動スケーリング設定を更新します。  

```
aws dynamodb update-table-replica-auto-scaling \
    --table-name MusicCollection \
    --provisioned-write-capacity-auto-scaling-update file://auto-scaling-policy.json
```
`auto-scaling-policy.json` の内容:  

```
{
    "MinimumUnits": 10,
    "MaximumUnits": 100,
    "AutoScalingDisabled": false,
    "ScalingPolicyUpdate": {
        "PolicyName": "DynamoDBWriteCapacityUtilization:table/MusicCollection",
        "TargetTrackingScalingPolicyConfiguration": {
            "TargetValue": 80
        }
    }
}
```
出力:  

```
{
    "TableAutoScalingDescription": {
        "TableName": "MusicCollection",
        "TableStatus": "ACTIVE",
        "Replicas": [
            {
                "RegionName": "eu-central-1",
                "GlobalSecondaryIndexes": [],
                "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                    "MinimumUnits": 5,
                    "MaximumUnits": 40000,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBReadCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 70.0
                            }
                        }
                    ]
                },
                "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                    "MinimumUnits": 10,
                    "MaximumUnits": 100,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBWriteCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 80.0
                            }
                        }
                    ]
                },
                "ReplicaStatus": "ACTIVE"
            },
            {
                "RegionName": "us-east-1",
                "GlobalSecondaryIndexes": [],
                "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                    "MinimumUnits": 5,
                    "MaximumUnits": 40000,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBReadCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 70.0
                            }
                        }
                    ]
                },
                "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                    "MinimumUnits": 10,
                    "MaximumUnits": 100,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBWriteCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 80.0
                            }
                        }
                    ]
                },
                "ReplicaStatus": "ACTIVE"
            },
            {
                "RegionName": "us-east-2",
                "GlobalSecondaryIndexes": [],
                "ReplicaProvisionedReadCapacityAutoScalingSettings": {
                    "MinimumUnits": 5,
                    "MaximumUnits": 40000,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBReadCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 70.0
                            }
                        }
                    ]
                },
                "ReplicaProvisionedWriteCapacityAutoScalingSettings": {
                    "MinimumUnits": 10,
                    "MaximumUnits": 100,
                    "AutoScalingRoleArn": "arn:aws:iam::123456789012:role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable",
                    "ScalingPolicies": [
                        {
                            "PolicyName": "DynamoDBWriteCapacityUtilization:table/MusicCollection",
                            "TargetTrackingScalingPolicyConfiguration": {
                                "TargetValue": 80.0
                            }
                        }
                    ]
                },
                "ReplicaStatus": "ACTIVE"
            }
        ]
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[DynamoDB Global Tables](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GlobalTables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTableReplicaAutoScaling](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-table-replica-auto-scaling.html)」を参照してください。

### `update-table`
<a name="dynamodb_UpdateTable_cli_2_topic"></a>

次のコード例は、`update-table` を使用する方法を示しています。

**AWS CLI**  
**例 1: テーブルの請求モードを変更するには**  
次の `update-table` 例は、`MusicCollection` テーブルにプロビジョニングされた読み取り/書き込みキャパシティを増やします。  

```
aws dynamodb update-table \
    --table-name MusicCollection \
    --billing-mode PROVISIONED \
    --provisioned-throughput ReadCapacityUnits=15,WriteCapacityUnits=10
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "AlbumTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "UPDATING",
        "CreationDateTime": "2020-05-26T15:59:49.473000-07:00",
        "ProvisionedThroughput": {
            "LastIncreaseDateTime": "2020-07-28T13:18:18.921000-07:00",
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 15,
            "WriteCapacityUnits": 10
        },
        "TableSizeBytes": 182,
        "ItemCount": 2,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "abcd0123-01ab-23cd-0123-abcdef123456",
        "BillingModeSummary": {
            "BillingMode": "PROVISIONED",
            "LastUpdateToPayPerRequestDateTime": "2020-07-28T13:14:48.366000-07:00"
        }
    }
}
```
詳細については、「Amazon DynamoDB デベロッパーガイド」の「[テーブルの更新](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.UpdateTable)」を参照してください。**  
**例 2: グローバルセカンダリインデックスを作成するには**  
次の例は、`MusicCollection` テーブルにグローバルセカンダリインデックスを追加します。  

```
aws dynamodb update-table \
    --table-name MusicCollection \
    --attribute-definitions AttributeName=AlbumTitle,AttributeType=S \
    --global-secondary-index-updates file://gsi-updates.json
```
`gsi-updates.json` の内容:  

```
[
    {
        "Create": {
            "IndexName": "AlbumTitle-index",
            "KeySchema": [
                {
                    "AttributeName": "AlbumTitle",
                    "KeyType": "HASH"
                }
            ],
            "ProvisionedThroughput": {
                "ReadCapacityUnits": 10,
                "WriteCapacityUnits": 10
            },
            "Projection": {
                "ProjectionType": "ALL"
            }
        }
    }
]
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "AlbumTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "UPDATING",
        "CreationDateTime": "2020-05-26T15:59:49.473000-07:00",
        "ProvisionedThroughput": {
            "LastIncreaseDateTime": "2020-07-28T12:59:17.537000-07:00",
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 15,
            "WriteCapacityUnits": 10
        },
        "TableSizeBytes": 182,
        "ItemCount": 2,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "abcd0123-01ab-23cd-0123-abcdef123456",
        "BillingModeSummary": {
            "BillingMode": "PROVISIONED",
            "LastUpdateToPayPerRequestDateTime": "2020-07-28T13:14:48.366000-07:00"
        },
        "GlobalSecondaryIndexes": [
            {
                "IndexName": "AlbumTitle-index",
                "KeySchema": [
                    {
                        "AttributeName": "AlbumTitle",
                        "KeyType": "HASH"
                    }
                ],
                "Projection": {
                    "ProjectionType": "ALL"
                },
                "IndexStatus": "CREATING",
                "Backfilling": false,
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 10,
                    "WriteCapacityUnits": 10
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitle-index"
            }
        ]
    }
}
```
詳細については、「Amazon DynamoDB デベロッパーガイド」の「[テーブルの更新](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.UpdateTable)」を参照してください。**  
**例 3: テーブルで DynamoDB Streams を有効化するには**  
次のコマンドは、`MusicCollection` テーブルで DynamoDB Streams を有効化します。  

```
aws dynamodb update-table \
    --table-name MusicCollection \
    --stream-specification StreamEnabled=true,StreamViewType=NEW_IMAGE
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "AlbumTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "UPDATING",
        "CreationDateTime": "2020-05-26T15:59:49.473000-07:00",
        "ProvisionedThroughput": {
            "LastIncreaseDateTime": "2020-07-28T12:59:17.537000-07:00",
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 15,
            "WriteCapacityUnits": 10
        },
        "TableSizeBytes": 182,
        "ItemCount": 2,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "abcd0123-01ab-23cd-0123-abcdef123456",
        "BillingModeSummary": {
            "BillingMode": "PROVISIONED",
            "LastUpdateToPayPerRequestDateTime": "2020-07-28T13:14:48.366000-07:00"
        },
        "LocalSecondaryIndexes": [
            {
                "IndexName": "AlbumTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "Artist",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "AlbumTitle",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "INCLUDE",
                    "NonKeyAttributes": [
                        "Year",
                        "Genre"
                    ]
                },
                "IndexSizeBytes": 139,
                "ItemCount": 2,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitleIndex"
            }
        ],
        "GlobalSecondaryIndexes": [
            {
                "IndexName": "AlbumTitle-index",
                "KeySchema": [
                    {
                        "AttributeName": "AlbumTitle",
                        "KeyType": "HASH"
                    }
                ],
                "Projection": {
                    "ProjectionType": "ALL"
                },
                "IndexStatus": "ACTIVE",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 10,
                    "WriteCapacityUnits": 10
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitle-index"
            }
        ],
        "StreamSpecification": {
            "StreamEnabled": true,
            "StreamViewType": "NEW_IMAGE"
        },
        "LatestStreamLabel": "2020-07-28T21:53:39.112",
        "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/stream/2020-07-28T21:53:39.112"
    }
}
```
詳細については、「Amazon DynamoDB デベロッパーガイド」の「[テーブルの更新](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.UpdateTable)」を参照してください。**  
**例 4: サーバー側の暗号化を有効化するには**  
次の例は、`MusicCollection` テーブルでサーバー側の暗号化を有効します。  

```
aws dynamodb update-table \
    --table-name MusicCollection \
    --sse-specification Enabled=true,SSEType=KMS
```
出力:  

```
{
    "TableDescription": {
        "AttributeDefinitions": [
            {
                "AttributeName": "AlbumTitle",
                "AttributeType": "S"
            },
            {
                "AttributeName": "Artist",
                "AttributeType": "S"
            },
            {
                "AttributeName": "SongTitle",
                "AttributeType": "S"
            }
        ],
        "TableName": "MusicCollection",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "TableStatus": "ACTIVE",
        "CreationDateTime": "2020-05-26T15:59:49.473000-07:00",
        "ProvisionedThroughput": {
            "LastIncreaseDateTime": "2020-07-28T12:59:17.537000-07:00",
            "NumberOfDecreasesToday": 0,
            "ReadCapacityUnits": 15,
            "WriteCapacityUnits": 10
        },
        "TableSizeBytes": 182,
        "ItemCount": 2,
        "TableArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection",
        "TableId": "abcd0123-01ab-23cd-0123-abcdef123456",
        "BillingModeSummary": {
            "BillingMode": "PROVISIONED",
            "LastUpdateToPayPerRequestDateTime": "2020-07-28T13:14:48.366000-07:00"
        },
        "LocalSecondaryIndexes": [
            {
                "IndexName": "AlbumTitleIndex",
                "KeySchema": [
                    {
                        "AttributeName": "Artist",
                        "KeyType": "HASH"
                    },
                    {
                        "AttributeName": "AlbumTitle",
                        "KeyType": "RANGE"
                    }
                ],
                "Projection": {
                    "ProjectionType": "INCLUDE",
                    "NonKeyAttributes": [
                        "Year",
                        "Genre"
                    ]
                },
                "IndexSizeBytes": 139,
                "ItemCount": 2,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitleIndex"
            }
        ],
        "GlobalSecondaryIndexes": [
            {
                "IndexName": "AlbumTitle-index",
                "KeySchema": [
                    {
                        "AttributeName": "AlbumTitle",
                        "KeyType": "HASH"
                    }
                ],
                "Projection": {
                    "ProjectionType": "ALL"
                },
                "IndexStatus": "ACTIVE",
                "ProvisionedThroughput": {
                    "NumberOfDecreasesToday": 0,
                    "ReadCapacityUnits": 10,
                    "WriteCapacityUnits": 10
                },
                "IndexSizeBytes": 0,
                "ItemCount": 0,
                "IndexArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/index/AlbumTitle-index"
            }
        ],
        "StreamSpecification": {
            "StreamEnabled": true,
            "StreamViewType": "NEW_IMAGE"
        },
        "LatestStreamLabel": "2020-07-28T21:53:39.112",
        "LatestStreamArn": "arn:aws:dynamodb:us-west-2:123456789012:table/MusicCollection/stream/2020-07-28T21:53:39.112",
        "SSEDescription": {
            "Status": "UPDATING"
        }
    }
}
```
詳細については、「Amazon DynamoDB デベロッパーガイド」の「[テーブルの更新](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.Basics.html#WorkingWithTables.Basics.UpdateTable)」を参照してください。**  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UpdateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-table.html)」を参照してください。**

### `update-time-to-live`
<a name="dynamodb_UpdateTimeToLive_cli_2_topic"></a>

次のコード例は、`update-time-to-live` を使用する方法を示しています。

**AWS CLI**  
**テーブルの Time to Live 設定を更新するには**  
次の `update-time-to-live` 例は、指定したテーブルの Time to Live を有効にします。  

```
aws dynamodb update-time-to-live \
    --table-name MusicCollection \
    --time-to-live-specification Enabled=true,AttributeName=ttl
```
出力:  

```
{
    "TimeToLiveSpecification": {
        "Enabled": true,
        "AttributeName": "ttl"
    }
}
```
詳細については、「**Amazon DynamoDB デベロッパーガイド」の「[Time to Live (TTL)](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html)」を参照してください。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[UpdateTimeToLive](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodb/update-time-to-live.html)」を参照してください。

# を使用した DynamoDB Streams の例 AWS CLI
<a name="cli_2_dynamodb-streams_code_examples"></a>

次のコード例は、DynamoDB Streams AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-stream`
<a name="dynamodb-streams_DescribeStream_cli_2_topic"></a>

次のコード例は、`describe-stream` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB ストリームに関する情報を取得するには**  
次の `describe-stream` コマンドは、特定の DynamoDB ストリームに関する情報を表示します。  

```
aws dynamodbstreams describe-stream \
    --stream-arn arn:aws:dynamodb:us-west-1:123456789012:table/Music/stream/2019-10-22T18:02:01.576
```
出力:  

```
{
    "StreamDescription": {
        "StreamArn": "arn:aws:dynamodb:us-west-1:123456789012:table/Music/stream/2019-10-22T18:02:01.576",
        "StreamLabel": "2019-10-22T18:02:01.576",
        "StreamStatus": "ENABLED",
        "StreamViewType": "NEW_AND_OLD_IMAGES",
        "CreationRequestDateTime": 1571767321.571,
        "TableName": "Music",
        "KeySchema": [
            {
                "AttributeName": "Artist",
                "KeyType": "HASH"
            },
            {
                "AttributeName": "SongTitle",
                "KeyType": "RANGE"
            }
        ],
        "Shards": [
            {
                "ShardId": "shardId-00000001571767321804-697ce3d2",
                "SequenceNumberRange": {
                    "StartingSequenceNumber": "4000000000000642977831",
                    "EndingSequenceNumber": "4000000000000642977831"
                }
            },
            {
                "ShardId": "shardId-00000001571780995058-40810d86",
                "SequenceNumberRange": {
                    "StartingSequenceNumber": "757400000000005655171150"
                },
                "ParentShardId": "shardId-00000001571767321804-697ce3d2"
            }
        ]
    }
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Capturing Table Activity with DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodbstreams/describe-stream.html)」を参照してください。**

### `get-records`
<a name="dynamodb-streams_GetRecords_cli_2_topic"></a>

次のコード例は、`get-records` を使用する方法を示しています。

**AWS CLI**  
**Dynamodb ストリームからレコードを取得するには**  
次の `get-records` コマンドは、指定した Amazon DynamoDB シャードイテレーターを使用してレコードを取得します。  

```
aws dynamodbstreams get-records \
    --shard-iterator "arn:aws:dynamodb:us-west-1:123456789012:table/Music/stream/2019-10-22T18:02:01.576|1|AAAAAAAAAAGgM3YZ89vLZZxjmoQeo33r9M4x3+zmmTLsiL86MfrF4+B4EbsByi52InVmiONmy6xVW4IRcIIbs1zO7MNIlqZfx8WQzMwVDyINtGG2hCLg78JKbYxFasXeePGlApTyf3rJxR765uyOVaBvBHAJuwF2TXIuxhaAlOupNGHr52qAC3a49ZOmf+CjNPlqQjnyRSAnfOwWmKhL1/KNParWSfz2odf780oOObIDIWRRMkt7+Hyzh9SD+hFxFAWR5C7QIlOXPc8mRBfNIazfrVCjJK8/jsjCzsqNyXKzJbhh+GXCoxYN+Kpmg4nyj1EAsYhbGL35muvHFoHjcyuynbsczbWaXNfThDwRAyvoTmc8XhHKtAWUbJiaVd8ZPtQwDsThCrmDRPIdmTRGWllGfUr5ezN5LscvkQezzgpaU5p8BgCqRzjv5Vl8LB6wHgQWNG+w/lEGS05ha1qNP+Vl4+tuhz2TRnhnJo/pny9GI/yGpce97mWvSPr5KPwy+Dtcm5BHayBs+PVYHITaTliInFlT+LCwvaz1QH3MY3b8A05Z800wjpktm60iQqtMeDwN4NX6FrcxR34JoFKGsgR8XkHVJzz2xr1xqSJ12ycpNTyHnndusw=="
```
出力:  

```
{
    "Records": [
        {
            "eventID": "c3b5d798eef6215d42f8137b19a88e50",
            "eventName": "INSERT",
            "eventVersion": "1.1",
            "eventSource": "aws:dynamodb",
            "awsRegion": "us-west-1",
            "dynamodb": {
                "ApproximateCreationDateTime": 1571849028.0,
                "Keys": {
                    "Artist": {
                        "S": "No One You Know"
                    },
                    "SongTitle": {
                        "S": "Call Me Today"
                    }
                },
                "NewImage": {
                    "AlbumTitle": {
                        "S": "Somewhat Famous"
                    },
                    "Artist": {
                        "S": "No One You Know"
                    },
                    "Awards": {
                        "N": "1"
                    },
                    "SongTitle": {
                        "S": "Call Me Today"
                    }
                },
                "SequenceNumber": "700000000013256296913",
                "SizeBytes": 119,
                "StreamViewType": "NEW_AND_OLD_IMAGES"
            }
        },
        {
            "eventID": "878960a6967867e2da16b27380a27328",
            "eventName": "INSERT",
            "eventVersion": "1.1",
            "eventSource": "aws:dynamodb",
            "awsRegion": "us-west-1",
            "dynamodb": {
                "ApproximateCreationDateTime": 1571849029.0,
                "Keys": {
                    "Artist": {
                        "S": "Acme Band"
                    },
                    "SongTitle": {
                        "S": "Happy Day"
                    }
                },
                "NewImage": {
                    "AlbumTitle": {
                        "S": "Songs About Life"
                    },
                    "Artist": {
                        "S": "Acme Band"
                    },
                    "Awards": {
                        "N": "10"
                    },
                    "SongTitle": {
                        "S": "Happy Day"
                    }
                },
                "SequenceNumber": "800000000013256297217",
                "SizeBytes": 100,
                "StreamViewType": "NEW_AND_OLD_IMAGES"
            }
        },
        {
            "eventID": "520fabde080e159fc3710b15ee1d4daa",
            "eventName": "MODIFY",
            "eventVersion": "1.1",
            "eventSource": "aws:dynamodb",
            "awsRegion": "us-west-1",
            "dynamodb": {
                "ApproximateCreationDateTime": 1571849734.0,
                "Keys": {
                    "Artist": {
                        "S": "Acme Band"
                    },
                    "SongTitle": {
                        "S": "Happy Day"
                    }
                },
                "NewImage": {
                    "AlbumTitle": {
                        "S": "Updated Album Title"
                    },
                    "Artist": {
                        "S": "Acme Band"
                    },
                    "Awards": {
                        "N": "10"
                    },
                    "SongTitle": {
                        "S": "Happy Day"
                    }
                },
                "OldImage": {
                    "AlbumTitle": {
                        "S": "Songs About Life"
                    },
                    "Artist": {
                        "S": "Acme Band"
                    },
                    "Awards": {
                        "N": "10"
                    },
                    "SongTitle": {
                        "S": "Happy Day"
                    }
                },
                "SequenceNumber": "900000000013256687845",
                "SizeBytes": 170,
                "StreamViewType": "NEW_AND_OLD_IMAGES"
            }
        }
    ],
    "NextShardIterator": "arn:aws:dynamodb:us-west-1:123456789012:table/Music/stream/2019-10-23T16:41:08.740|1|AAAAAAAAAAEhEI04jkFLW+LKOwivjT8d/IHEh3iExV2xK00aTxEzVy1C1C7Kbb5+ZOW6bT9VQ2n1/mrs7+PRiaOZCHJu7JHJVW7zlsqOi/ges3fw8GYEymyL+piEk35cx67rQqwKKyq+Q6w9JyjreIOj4F2lWLV26lBwRTrIYC4IB7C3BZZK4715QwYdDxNdVHiSBRZX8UqoS6WOt0F87xZLNB9F/NhYBLXi/wcGvAcBcC0TNIOH+N0NqwtoB/FGCkNrf8YZ0xRoNN6RgGuVWHF3pxOhxEJeFZoSoJTIKeG9YcYxzi5Ci/mhdtm7tBXnbw5c6xmsGsBqTirNjlDyJLcWl8Cl0UOLX63Ufo/5QliztcjEbKsQe28x8LM8o7VH1Is0fF/ITt8awSA4igyJS0P87GN8Qri8kj8iaE35805jBHWF2wvwT6Iy2xGrR2r2HzYps9dwGOarVdEITaJfWzNoL4HajMhmREZLYfM7Pb0PvRMO7JkENyPIU6e2w16W1CvJO2EGFIxtNk+V04i1YIeHMXJfcwetNRuIbdQXfJht2NQZa4PVV6iknY6d19MrdbSTMKoqAuvp6g3Q2jH4t7GKCLWgodcPAn8g5+43DaNkh4Z5zKOfNw=="
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Capturing Table Activity with DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRecords](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodbstreams/get-records.html)」を参照してください。

### `get-shard-iterator`
<a name="dynamodb-streams_GetShardIterator_cli_2_topic"></a>

次のコード例は、`get-shard-iterator` を使用する方法を示しています。

**AWS CLI**  
**シャードイテレーターを取得するには**  
次の `get-shard-iterator` コマンドは、指定したシャードのシャードイテレーターを取得します。  

```
aws dynamodbstreams get-shard-iterator \
    --stream-arn arn:aws:dynamodb:us-west-1:12356789012:table/Music/stream/2019-10-22T18:02:01.576 \
    --shard-id shardId-00000001571780995058-40810d86 \
    --shard-iterator-type LATEST
```
出力:  

```
{
    "ShardIterator": "arn:aws:dynamodb:us-west-1:123456789012:table/Music/stream/2019-10-22T18:02:01.576|1|AAAAAAAAAAGgM3YZ89vLZZxjmoQeo33r9M4x3+zmmTLsiL86MfrF4+B4EbsByi52InVmiONmy6xVW4IRcIIbs1zO7MNIlqZfx8WQzMwVDyINtGG2hCLg78JKbYxFasXeePGlApTyf3rJxR765uyOVaBvBHAJuwF2TXIuxhaAlOupNGHr52qAC3a49ZOmf+CjNPlqQjnyRSAnfOwWmKhL1/KNParWSfz2odf780oOObIDIWRRMkt7+Hyzh9SD+hFxFAWR5C7QIlOXPc8mRBfNIazfrVCjJK8/jsjCzsqNyXKzJbhh+GXCoxYN+Kpmg4nyj1EAsYhbGL35muvHFoHjcyuynbsczbWaXNfThDwRAyvoTmc8XhHKtAWUbJiaVd8ZPtQwDsThCrmDRPIdmTRGWllGfUr5ezN5LscvkQezzgpaU5p8BgCqRzjv5Vl8LB6wHgQWNG+w/lEGS05ha1qNP+Vl4+tuhz2TRnhnJo/pny9GI/yGpce97mWvSPr5KPwy+Dtcm5BHayBs+PVYHITaTliInFlT+LCwvaz1QH3MY3b8A05Z800wjpktm60iQqtMeDwN4NX6FrcxR34JoFKGsgR8XkHVJzz2xr1xqSJ12ycpNTyHnndusw=="
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Capturing Table Activity with DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetShardIterator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodbstreams/get-shard-iterator.html)」を参照してください。

### `list-streams`
<a name="dynamodb-streams_ListStreams_cli_2_topic"></a>

次のコード例は、`list-streams` を使用する方法を示しています。

**AWS CLI**  
**DynamoDB ストリームを一覧表示するには**  
次の `list-streams` コマンドは、デフォルト AWS リージョン内のすべての既存の Amazon DynamoDB ストリームを一覧表示します。  

```
aws dynamodbstreams list-streams
```
出力:  

```
{
    "Streams": [
        {
            "StreamArn": "arn:aws:dynamodb:us-west-1:123456789012:table/Music/stream/2019-10-22T18:02:01.576",
            "TableName": "Music",
            "StreamLabel": "2019-10-22T18:02:01.576"
        }
    ]
}
```
詳細については、「*Amazon DynamoDB デベロッパーガイド*」の「[Capturing Table Activity with DynamoDB Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/dynamodbstreams/list-streams.html)」を参照してください。**

# を使用した Amazon EC2 の例 AWS CLI
<a name="cli_2_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-address-transfer`
<a name="ec2_AcceptAddressTransfer_cli_2_topic"></a>

次のコード例は、`accept-address-transfer` を使用する方法を示しています。

**AWS CLI**  
**アカウントに移行された Elastic IP アドレスを承諾するには**  
次の `accept-address-transfer` の例では、指定した Elastic IP アドレスのアカウントへの転送を承諾します。  

```
aws ec2 accept-address-transfer \
    --address 100.21.184.216
```
出力:  

```
{
    "AddressTransfer": {
        "PublicIp": "100.21.184.216",
        "AllocationId": "eipalloc-09ad461b0d03f6aaf",
        "TransferAccountId": "123456789012",
        "TransferOfferExpirationTimestamp": "2023-02-22T20:51:10.000Z",
        "TransferOfferAcceptedTimestamp": "2023-02-22T22:52:54.000Z",
        "AddressTransferStatus": "accepted"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Transfer Elastic IP addresses](https://docs.aws.amazon.com/vpc/latest/userguide/WorkWithEIPs.html#transfer-EIPs-intro)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptAddressTransfer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/accept-address-transfer.html)」を参照してください。

### `accept-reserved-instances-exchange-quote`
<a name="ec2_AcceptReservedInstancesExchangeQuote_cli_2_topic"></a>

次のコード例は、`accept-reserved-instances-exchange-quote` を使用する方法を示しています。

**AWS CLI**  
**コンバーティブルリザーブドインスタンス交換を実行するには**  
この例では、指定されたコンバーティブルリザーブドインスタンスの交換を実行します。  
コマンド:  

```
aws ec2 accept-reserved-instances-exchange-quote --reserved-instance-ids 7b8750c3-397e-4da4-bbcb-a45ebexample --target-configurations OfferingId=b747b472-423c-48f3-8cee-679bcexample
```
出力:  

```
{
  "ExchangeId": "riex-e68ed3c1-8bc8-4c17-af77-811afexample"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptReservedInstancesExchangeQuote](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/accept-reserved-instances-exchange-quote.html)」を参照してください。

### `accept-transit-gateway-peering-attachment`
<a name="ec2_AcceptTransitGatewayPeeringAttachment_cli_2_topic"></a>

次のコード例は、`accept-transit-gateway-peering-attachment` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ピアリングアタッチメントを承諾するには**  
次の `accept-transit-gateway-peering-attachment` の例では、指定した Transit Gateway ピアリングアタッチメントを承諾します。`--region` パラメータは、アクセプタ Transit Gateway があるリージョンを指定します。  

```
aws ec2 accept-transit-gateway-peering-attachment \
    --transit-gateway-attachment-id tgw-attach-4455667788aabbccd \
    --region us-east-2
```
出力:  

```
{
    "TransitGatewayPeeringAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-4455667788aabbccd",
        "RequesterTgwInfo": {
            "TransitGatewayId": "tgw-123abc05e04123abc",
            "OwnerId": "123456789012",
            "Region": "us-west-2"
        },
        "AccepterTgwInfo": {
            "TransitGatewayId": "tgw-11223344aabbcc112",
            "OwnerId": "123456789012",
            "Region": "us-east-2"
        },
        "State": "pending",
        "CreationTime": "2019-12-09T11:38:31.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit Gateway Peering Attachments](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptTransitGatewayPeeringAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/accept-transit-gateway-peering-attachment.html)」を参照してください。

### `accept-transit-gateway-vpc-attachment`
<a name="ec2_AcceptTransitGatewayVpcAttachment_cli_2_topic"></a>

次のコード例は、`accept-transit-gateway-vpc-attachment` を使用する方法を示しています。

**AWS CLI**  
**VPC を Transit Gateway にアタッチするためのリクエストを承諾するには。**  
次の `accept-transit-gateway-vpc-attachment` の例では、リクエスト forte で指定した添付ファイルを承諾します。  

```
aws ec2 accept-transit-gateway-vpc-attachment \
    --transit-gateway-attachment-id tgw-attach-0a34fe6b4fEXAMPLE
```
出力:  

```
{
    "TransitGatewayVpcAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-0a34fe6b4fEXAMPLE",
        "TransitGatewayId": "tgw-0262a0e521EXAMPLE",
        "VpcId": "vpc-07e8ffd50fEXAMPLE",
        "VpcOwnerId": "123456789012",
        "State": "pending",
        "SubnetIds": [
            "subnet-0752213d59EXAMPLE"
        ],
        "CreationTime": "2019-07-10T17:33:46.000Z",
        "Options": {
            "DnsSupport": "enable",
            "Ipv6Support": "disable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit Gateway Attachments to a VPC](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptTransitGatewayVpcAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/accept-transit-gateway-vpc-attachment.html)」を参照してください。

### `accept-vpc-endpoint-connections`
<a name="ec2_AcceptVpcEndpointConnections_cli_2_topic"></a>

次のコード例は、`accept-vpc-endpoint-connections` を使用する方法を示しています。

**AWS CLI**  
**インターフェイスエンドポイント接続リクエストを承諾するには**  
この例では、指定されたエンドポイントサービスに対して指定されたエンドポイント接続リクエストを承諾します。  
コマンド:  

```
aws ec2 accept-vpc-endpoint-connections --service-id vpce-svc-03d5ebb7d9579a2b3 --vpc-endpoint-ids vpce-0c1308d7312217abc
```
出力:  

```
{
  "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptVpcEndpointConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/accept-vpc-endpoint-connections.html)」を参照してください。

### `accept-vpc-peering-connection`
<a name="ec2_AcceptVpcPeeringConnection_cli_2_topic"></a>

次のコード例は、`accept-vpc-peering-connection` を使用する方法を示しています。

**AWS CLI**  
**VPC ピアリング接続を承諾するには**  
この例では、指定された VPC ピアリング接続リクエストを承諾します。  
コマンド:  

```
aws ec2 accept-vpc-peering-connection --vpc-peering-connection-id pcx-1a2b3c4d
```
出力:  

```
{
  "VpcPeeringConnection": {
    "Status": {
      "Message": "Provisioning",
      "Code": "provisioning"
    },
    "Tags": [],
    "AccepterVpcInfo": {
      "OwnerId": "444455556666",
      "VpcId": "vpc-44455566",
      "CidrBlock": "10.0.1.0/28"
    },
    "VpcPeeringConnectionId": "pcx-1a2b3c4d",
    "RequesterVpcInfo": {
      "OwnerId": "444455556666",
      "VpcId": "vpc-111abc45",
      "CidrBlock": "10.0.0.0/28"
    }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptVpcPeeringConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/accept-vpc-peering-connection.html)」を参照してください。

### `advertise-byoip-cidr`
<a name="ec2_AdvertiseByoipCidr_cli_2_topic"></a>

次のコード例は、`advertise-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲をアドバタイズするには**  
次の `advertise-byoip-cidr` の例では、指定したパブリック IPv4 アドレス範囲をアドバタイズします。  

```
aws ec2 advertise-byoip-cidr \
    --cidr 203.0.113.25/24
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "203.0.113.25/24",
        "StatusMessage": "ipv4pool-ec2-1234567890abcdef0",
        "State": "provisioned"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdvertiseByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/advertise-byoip-cidr.html)」を参照してください。

### `allocate-address`
<a name="ec2_AllocateAddress_cli_2_topic"></a>

次のコード例は、`allocate-address` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon のアドレスプールから Elastic IP アドレスを割り当てるには**  
次の `allocate-address` の例では、Elastic IP アドレスを割り当てています。Amazon EC2 は、Amazon のアドレスプールからアドレスを選択します。  

```
aws ec2 allocate-address
```
出力:  

```
{
    "PublicIp": "70.224.234.241",
    "AllocationId": "eipalloc-01435ba59eEXAMPLE",
    "PublicIpv4Pool": "amazon",
    "NetworkBorderGroup": "us-west-2",
    "Domain": "vpc"
}
```
詳細については、「Amazon EC2 ユーザーガイド」の「[Elastic IP アドレス](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)」を参照してください。  
**例 2: Elastic IP アドレスを割り当て、インスタンスまたはネットワークボーダーグループと関連付けるには**  
次の `allocate-address` の例では、Elastic IP アドレスを割り当て、指定されたネットワークボーダーグループに関連付けます。  

```
aws ec2 allocate-address \
    --network-border-group us-west-2-lax-1
```
出力:  

```
{
    "PublicIp": "70.224.234.241",
    "AllocationId": "eipalloc-e03dd489ceEXAMPLE",
    "PublicIpv4Pool": "amazon",
    "NetworkBorderGroup": "us-west-2-lax-1",
    "Domain": "vpc"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Elastic IP アドレス](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)」を参照してください。  
**例 3: 所有するアドレスプールから Elastic IP アドレスを割り当てるには**  
次の `allocate-address` の例では、Amazon Web Services アカウントに入れたアドレスプールから Elastic IP アドレスを割り当てています。Amazon EC2 は、アドレスプールからアドレスを選択します。  

```
aws ec2 allocate-address \
    --public-ipv4-pool ipv4pool-ec2-1234567890abcdef0
```
出力:  

```
{
    "AllocationId": "eipalloc-02463d08ceEXAMPLE",
    "NetworkBorderGroup": "us-west-2",
    "CustomerOwnedIp": "18.218.95.81",
    "CustomerOwnedIpv4Pool": "ipv4pool-ec2-1234567890abcdef0",
    "Domain": "vpc"
    "NetworkBorderGroup": "us-west-2",
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Elastic IP アドレス](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)」を参照してください。  
**例 4: IPAM プールから Elastic IP アドレスを割り当てるには**  
次の `allocate-address` の例では、Amazon VPC IP Address Manager (IPAM) プールから特定の /32 Elastic IP アドレスを割り当てます。  

```
aws ec2 allocate-address \
    --region us-east-1 \
    --ipam-pool-id ipam-pool-1234567890abcdef0 \
    --address 192.0.2.0
```
出力:  

```
{
    "PublicIp": "192.0.2.0",
    "AllocationId": "eipalloc-abcdef01234567890",
    "PublicIpv4Pool": "ipam-pool-1234567890abcdef0",
    "NetworkBorderGroup": "us-east-1",
    "Domain": "vpc"
}
```
詳細については「Amazon VPC IPAM ユーザーガイド」の「[Allocate sequential Elastic IP addresses from an IPAM pool](https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-eip-pool.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/allocate-address.html)」を参照してください。

### `allocate-hosts`
<a name="ec2_AllocateHosts_cli_2_topic"></a>

次のコード例は、`allocate-hosts` を使用する方法を示しています。

**AWS CLI**  
**例 1: 専有ホストを割り当てるには**  
次の `allocate-hosts` の例では、`eu-west-1a` アベイラビリティーゾーンに 1 つの専有ホストを割り当てます。このゾーンでは `m5.large` インスタンスを起動できます。デフォルトでは、専有ホストはターゲットインスタンスの起動のみを承諾し、ホストリカバリはサポートしていません。  

```
aws ec2 allocate-hosts \
    --instance-type m5.large \
    --availability-zone eu-west-1a \
    --quantity 1
```
出力:  

```
{
    "HostIds": [
        "h-07879acf49EXAMPLE"
    ]
}
```
**例 2: 自動配置とホストリカバリが有効になっている専有ホストを割り当てるには**  
次の `allocate-hosts` の例では、自動配置とホストリカバリが有効になっている `eu-west-1a` アベイラビリティーゾーンに 1 つの専有ホストを割り当てます。  

```
aws ec2 allocate-hosts \
    --instance-type m5.large \
    --availability-zone eu-west-1a \
    --auto-placement on \
    --host-recovery on \
    --quantity 1
```
出力:  

```
{
     "HostIds": [
         "h-07879acf49EXAMPLE"
     ]
}
```
**例 3: タグのある専有ホストを割り当てるには**  
次の `allocate-hosts` の例では、1 つの専有ホストを割り当てて、`purpose` という名前のキーと `production` の値を持つタグを適用します。  

```
aws ec2 allocate-hosts \
    --instance-type m5.large \
    --availability-zone eu-west-1a \
    --quantity 1 \
    --tag-specifications 'ResourceType=dedicated-host,Tags={Key=purpose,Value=production}'
```
出力:  

```
{
    "HostIds": [
        "h-07879acf49EXAMPLE"
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[専有ホストを割り当てる](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/dedicated-hosts-allocating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/allocate-hosts.html)」を参照してください。

### `allocate-ipam-pool-cidr`
<a name="ec2_AllocateIpamPoolCidr_cli_2_topic"></a>

次のコード例は、`allocate-ipam-pool-cidr` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールから CIDR を割り当てるには**  
次の `allocate-ipam-pool-cidr` の例では、IPAM プールから CIDR を割り当てます。  
(Linux):  

```
aws ec2 allocate-ipam-pool-cidr \
    --ipam-pool-id ipam-pool-0533048da7d823723 \
    --netmask-length 24
```
(Windows):  

```
aws ec2 allocate-ipam-pool-cidr ^
   --ipam-pool-id ipam-pool-0533048da7d823723 ^
   --netmask-length 24
```
出力:  

```
{
    "IpamPoolAllocation": {
        "Cidr": "10.0.0.0/24",
        "IpamPoolAllocationId": "ipam-pool-alloc-018ecc28043b54ba38e2cd99943cebfbd",
        "ResourceType": "custom",
        "ResourceOwner": "123456789012"
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Manually allocate a CIDR to a pool to reserve IP address space](https://docs.aws.amazon.com/vpc/latest/ipam/manually-allocate-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateIpamPoolCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/allocate-ipam-pool-cidr.html)」を参照してください。

### `apply-security-groups-to-client-vpn-target-network`
<a name="ec2_ApplySecurityGroupsToClientVpnTargetNetwork_cli_2_topic"></a>

次のコード例は、`apply-security-groups-to-client-vpn-target-network` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントのターゲットネットワークにセキュリティグループを適用するには**  
次の `apply-security-groups-to-client-vpn-target-network` の例では、セキュリティグループ `sg-01f6e627a89f4db32` を指定したターゲットネットワークとクライアント VPN エンドポイント間の関連付けに適用します。  

```
aws ec2 apply-security-groups-to-client-vpn-target-network \
    --security-group-ids sg-01f6e627a89f4db32 \
    --vpc-id vpc-0e2110c2f324332e0 \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "SecurityGroupIds": [
        "sg-01f6e627a89f4db32"
    ]
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Target Networks](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-target.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ApplySecurityGroupsToClientVpnTargetNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/apply-security-groups-to-client-vpn-target-network.html)」を参照してください。

### `assign-ipv6-addresses`
<a name="ec2_AssignIpv6Addresses_cli_2_topic"></a>

次のコード例は、`assign-ipv6-addresses` を使用する方法を示しています。

**AWS CLI**  
**特定の IPv6 アドレスをネットワークインターフェイスに割り当てるには**  
この例では、指定された IPv6 アドレスを指定されたネットワークインターフェイスに割り当てます。  
コマンド:  

```
aws ec2 assign-ipv6-addresses --network-interface-id eni-38664473 --ipv6-addresses 2001:db8:1234:1a00:3304:8879:34cf:4071 2001:db8:1234:1a00:9691:9503:25ad:1761
```
出力:  

```
{
  "AssignedIpv6Addresses": [
      "2001:db8:1234:1a00:3304:8879:34cf:4071",
      "2001:db8:1234:1a00:9691:9503:25ad:1761"
  ],
  "NetworkInterfaceId": "eni-38664473"
}
```
**Amazon が選択した IPv6 アドレスをネットワークインターフェイスに割り当てるには**  
この例では、2 つの IPv6 アドレスを指定されたネットワークインターフェイスに割り当てます。Amazon は、サブネットの IPv6 CIDR ブロック範囲内で使用可能な IPv6 アドレスからこれらの IPv6 アドレスを自動的に割り当てます。  
コマンド:  

```
aws ec2 assign-ipv6-addresses --network-interface-id eni-38664473 --ipv6-address-count 2
```
出力:  

```
{
  "AssignedIpv6Addresses": [
      "2001:db8:1234:1a00:3304:8879:34cf:4071",
      "2001:db8:1234:1a00:9691:9503:25ad:1761"
  ],
  "NetworkInterfaceId": "eni-38664473"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssignIpv6Addresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/assign-ipv6-addresses.html)」を参照してください。

### `assign-private-ip-addresses`
<a name="ec2_AssignPrivateIpAddresses_cli_2_topic"></a>

次のコード例は、`assign-private-ip-addresses` を使用する方法を示しています。

**AWS CLI**  
**セカンダリプライベート IP アドレスをネットワークインターフェイスに割り当てるには**  
この例では、指定されたセカンダリプライベート IP アドレスを指定されたネットワークインターフェイスに割り当てます。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 assign-private-ip-addresses --network-interface-id eni-e5aa89a3 --private-ip-addresses 10.0.0.82
```
**Amazon EC2 が選択したセカンダリプライベート IP アドレスをネットワークインターフェイスに割り当てるには**  
この例では、2 つのセカンダリプライベート IP アドレスを指定されたネットワークインターフェイスに割り当てます。Amazon EC2 は、ネットワークインターフェイスが関連付けられているサブネットの CIDR ブロック範囲内にある使用可能な IP アドレスから、これらの IP アドレスを自動的に割り当てます。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 assign-private-ip-addresses --network-interface-id eni-e5aa89a3 --secondary-private-ip-address-count 2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssignPrivateIpAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/assign-private-ip-addresses.html)」を参照してください。

### `assign-private-nat-gateway-address`
<a name="ec2_AssignPrivateNatGatewayAddress_cli_2_topic"></a>

次のコード例は、`assign-private-nat-gateway-address` を使用する方法を示しています。

**AWS CLI**  
**プライベート IP アドレスをプライベート NAT ゲートウェイに割り当てるには**  
次の `assign-private-nat-gateway-address` の例では、指定したプライベート NAT ゲートウェイに 2 つのプライベート IP アドレスを割り当てます。  

```
aws ec2 assign-private-nat-gateway-address \
    --nat-gateway-id nat-1234567890abcdef0 \
    --private-ip-address-count 2
```
出力:  

```
{
    "NatGatewayId": "nat-1234567890abcdef0",
    "NatGatewayAddresses": [
        {
            "NetworkInterfaceId": "eni-0065a61b324d1897a",
            "IsPrimary": false,
            "Status": "assigning"
        },
        {
            "NetworkInterfaceId": "eni-0065a61b324d1897a",
            "IsPrimary": false,
            "Status": "assigning"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[NAT ゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssignPrivateNatGatewayAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/assign-private-nat-gateway-address.html)」を参照してください。

### `associate-address`
<a name="ec2_AssociateAddress_cli_2_topic"></a>

次のコード例は、`associate-address` を使用する方法を示しています。

**AWS CLI**  
**例 1: Elastic IP アドレスをインスタンスに関連付けるには**  
次の `associate-address` の例では、Elastic IP アドレスを、指定した EC2 インスタンスに関連付けます。  

```
aws ec2 associate-address \
    --instance-id i-0b263919b6498b123 \
    --allocation-id eipalloc-64d5890a
```
出力:  

```
{
    "AssociationId": "eipassoc-2bebb745"
}
```
**例 2: Elastic IP アドレスをネットワークインターフェイスに関連付けるには**  
次の `associate-address` の例では、指定した Elastic IP アドレスを、指定したネットワークインターフェイスに関連付けます。  

```
aws ec2 associate-address
    --allocation-id eipalloc-64d5890a \
    --network-interface-id eni-1a2b3c4d
```
出力:  

```
{
    "AssociationId": "eipassoc-2bebb745"
}
```
**例 3: Elastic IP アドレスをプライベート IP アドレスに関連付けるには**  
次の `associate-address` の例では、指定した Elastic IP アドレスを、指定したネットワークインターフェイス内の指定したプライベート IP アドレスに関連付けます。  

```
aws ec2 associate-address \
    --allocation-id eipalloc-64d5890a \
    --network-interface-id eni-1a2b3c4d \
    --private-ip-address 10.0.0.85
```
出力:  

```
{
    "AssociationId": "eipassoc-2bebb745"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Elastic IP アドレス](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-address.html)」を参照してください。

### `associate-client-vpn-target-network`
<a name="ec2_AssociateClientVpnTargetNetwork_cli_2_topic"></a>

次のコード例は、`associate-client-vpn-target-network` を使用する方法を示しています。

**AWS CLI**  
**ターゲットネットワークをクライアント VPN エンドポイントに関連付けるには**  
次の `associate-client-vpn-target-network` の例では、指定したクライアント VPN エンドポイントにサブネットを関連付けます。  

```
aws ec2 associate-client-vpn-target-network \
    --subnet-id subnet-0123456789abcabca \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "AssociationId": "cvpn-assoc-12312312312312312",
    "Status": {
        "Code": "associating"
    }
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Target Networks](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-target.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateClientVpnTargetNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-client-vpn-target-network.html)」を参照してください。

### `associate-dhcp-options`
<a name="ec2_AssociateDhcpOptions_cli_2_topic"></a>

次のコード例は、`associate-dhcp-options` を使用する方法を示しています。

**AWS CLI**  
**DHCP オプションセットを VPC に関連付けるには**  
この例では、指定された DHCP オプションセットを指定された VPC に関連付けます。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 associate-dhcp-options --dhcp-options-id dopt-d9070ebb --vpc-id vpc-a01106c2
```
**デフォルトの DHCP オプションセットを VPC に関連付けるには**  
この例では、デフォルトの DHCP オプションセットを指定された VPC に関連付けます。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 associate-dhcp-options --dhcp-options-id default --vpc-id vpc-a01106c2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-dhcp-options.html)」を参照してください。

### `associate-iam-instance-profile`
<a name="ec2_AssociateIamInstanceProfile_cli_2_topic"></a>

次のコード例は、`associate-iam-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**IAM インスタンスプロファイルをインスタンスに関連付けるには**  
この例では、`admin-role` という名前の IAM インスタンスプロファイルをインスタンス `i-123456789abcde123` に関連付けます。  
コマンド:  

```
aws ec2 associate-iam-instance-profile --instance-id i-123456789abcde123 --iam-instance-profile Name=admin-role
```
出力:  

```
{
  "IamInstanceProfileAssociation": {
      "InstanceId": "i-123456789abcde123",
      "State": "associating",
      "AssociationId": "iip-assoc-0e7736511a163c209",
      "IamInstanceProfile": {
          "Id": "AIPAJBLK7RKJKWDXVHIEC",
          "Arn": "arn:aws:iam::123456789012:instance-profile/admin-role"
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateIamInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-iam-instance-profile.html)」を参照してください。

### `associate-instance-event-window`
<a name="ec2_AssociateInstanceEventWindow_cli_2_topic"></a>

次のコード例は、`associate-instance-event-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: イベントウィンドウに 1 つ以上のインスタンスを関連付けるには**  
次の `associate-instance-event-window` の例では、1 つ以上のインスタンスをイベントウィンドウに関連付けます。  

```
aws ec2 associate-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --association-target "InstanceIds=i-1234567890abcdef0,i-0598c7d356eba48d7"
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "AssociationTarget": {
            "InstanceIds": [
                "i-1234567890abcdef0",
                "i-0598c7d356eba48d7"
            ],
            "Tags": [],
            "DedicatedHostIds": []
        },
        "State": "creating"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 2: インスタンスタグをイベントウィンドウに関連付けるには**  
次の `associate-instance-event-window` の例では、インスタンスタグをイベントウィンドウに関連付けます。`instance-event-window-id` パラメータを入力して、イベントウィンドウを指定します。インスタンスタグを関連付けるには、`association-target` パラメータを指定し、そのパラメータ値に 1 つ以上のタグを指定します。  

```
aws ec2 associate-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --association-target "InstanceTags=[{Key=k2,Value=v2},{Key=k1,Value=v1}]"
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "AssociationTarget": {
            "InstanceIds": [],
            "Tags": [
                {
                    "Key": "k2",
                    "Value": "v2"
                },
                {
                    "Key": "k1",
                    "Value": "v1"
                }
            ],
            "DedicatedHostIds": []
        },
        "State": "creating"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 3: 専有ホストをイベントウィンドウに関連付けるには**  
次の `associate-instance-event-window` の例では、専有ホストをイベントウィンドウに関連付けます。`instance-event-window-id` パラメータを入力して、イベントウィンドウを指定します。専有ホストを関連付けるには、`--association-target` パラメータを指定し、そのパラメータ値に 1 つ以上の専有ホスト ID を指定します。  

```
aws ec2 associate-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --association-target "DedicatedHostIds=h-029fa35a02b99801d"
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "AssociationTarget": {
            "InstanceIds": [],
            "Tags": [],
            "DedicatedHostIds": [
                "h-029fa35a02b99801d"
            ]
        },
        "State": "creating"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateInstanceEventWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-instance-event-window.html)」を参照してください。

### `associate-ipam-resource-discovery`
<a name="ec2_AssociateIpamResourceDiscovery_cli_2_topic"></a>

次のコード例は、`associate-ipam-resource-discovery` を使用する方法を示しています。

**AWS CLI**  
**リソース検出を IPAM に関連付けるには**  
この例では、あなたは IPAM 委任管理者であり、リソース検出が別の AWS アカウントによって作成および共有されているため、IPAM を使用して他のアカウントが所有するリソース CIDRsを管理およびモニタリングできます。  
メモ  
このリクエストを完了するには、[describe-ipam-resource-discoveries](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-ipam-resource-discoveries.html) で取得できるリソース検出 ID と [describe-ipams](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-ipams.html) で取得できる IPAM ID が必要です。関連付けるリソース検出は、まず AWS RAM を使用してアカウントと共有されている必要があります。`--region`入力する は、関連付ける IPAM のホームリージョンと一致する必要があります。  
次の `associate-ipam-resource-discovery` の例では、リソース検出を IPAM に関連付けます。  

```
aws ec2 associate-ipam-resource-discovery \
    --ipam-id ipam-005f921c17ebd5107 \
    --ipam-resource-discovery-id ipam-res-disco-03e0406de76a044ee \
    --tag-specifications 'ResourceType=ipam-resource-discovery,Tags=[{Key=cost-center,Value=cc123}]' \
    --region us-east-1
```
出力:  

```
{
    {
        "IpamResourceDiscoveryAssociation": {
            "OwnerId": "320805250157",
            "IpamResourceDiscoveryAssociationId": "ipam-res-disco-assoc-04382a6346357cf82",
            "IpamResourceDiscoveryAssociationArn": "arn:aws:ec2::320805250157:ipam-resource-discovery-association/ipam-res-disco-assoc-04382a6346357cf82",
            "IpamResourceDiscoveryId": "ipam-res-disco-0365d2977fc1672fe",
            "IpamId": "ipam-005f921c17ebd5107",
            "IpamArn": "arn:aws:ec2::320805250157:ipam/ipam-005f921c17ebd5107",
            "IpamRegion": "us-east-1",
            "IsDefault": false,
            "ResourceDiscoveryStatus": "active",
            "State": "associate-in-progress",
            "Tags": []
        }
    }
}
```
リソース検出を関連付けると、他のアカウントで作成されたリソースの IP アドレスをモニタリングしたり管理したりできます。詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Integrate IPAM with accounts outside of your organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateIpamResourceDiscovery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-ipam-resource-discovery.html)」を参照してください。

### `associate-nat-gateway-address`
<a name="ec2_AssociateNatGatewayAddress_cli_2_topic"></a>

次のコード例は、`associate-nat-gateway-address` を使用する方法を示しています。

**AWS CLI**  
**Elastic IP アドレスをパブリック NAT ゲートウェイに関連付けるには**  
次の の`associate-nat-gateway-address`例では、指定された Elastic IP アドレスを指定されたパブリック NAT ゲートウェイに関連付けます。 はセカンダリプライベート IPv4 アドレス AWS を自動的に割り当てます。  

```
aws ec2 associate-nat-gateway-address \
    --nat-gateway-id nat-1234567890abcdef0 \
    --allocation-ids eipalloc-0be6ecac95EXAMPLE
```
出力:  

```
{
    "NatGatewayId": "nat-1234567890abcdef0",
    "NatGatewayAddresses": [
        {
            "AllocationId": "eipalloc-0be6ecac95EXAMPLE",
            "NetworkInterfaceId": "eni-09cc4b2558794f7f9",
            "IsPrimary": false,
            "Status": "associating"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[NAT ゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateNatGatewayAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-nat-gateway-address.html)」を参照してください。

### `associate-route-table`
<a name="ec2_AssociateRouteTable_cli_2_topic"></a>

次のコード例は、`associate-route-table` を使用する方法を示しています。

**AWS CLI**  
**ルートテーブルをサブネットに関連付けるには**  
この例では、指定されたルートテーブルを指定されたサブネットに関連付けます。  
コマンド:  

```
aws ec2 associate-route-table --route-table-id rtb-22574640 --subnet-id subnet-9d4a7b6c
```
出力:  

```
{
    "AssociationId": "rtbassoc-781d0d1a"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-route-table.html)」を参照してください。

### `associate-security-group-vpc`
<a name="ec2_AssociateSecurityGroupVpc_cli_2_topic"></a>

次のコード例は、`associate-security-group-vpc` を使用する方法を示しています。

**AWS CLI**  
**セキュリティグループを別の VPC と関連付けるには**  
次の `associate-security-group-vpc` の例では、指定されたセキュリティグループを指定された VPC に関連付けます。  

```
aws ec2 associate-security-group-vpc \
    --group-id sg-04dbb43907d3f8a78 \
    --vpc-id vpc-0bf4c2739bc05a694
```
出力:  

```
{
    "State": "associating"
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[セキュリティグループを複数の VPC に関連付ける](https://docs.aws.amazon.com/vpc/latest/userguide/security-group-assoc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateSecurityGroupVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-security-group-vpc.html)」を参照してください。

### `associate-subnet-cidr-block`
<a name="ec2_AssociateSubnetCidrBlock_cli_2_topic"></a>

次のコード例は、`associate-subnet-cidr-block` を使用する方法を示しています。

**AWS CLI**  
**IPv6 CIDR ブロックをサブネットに関連付けるには**  
この例では、IPv6 CIDR ブロックを指定されたサブネットに関連付けます。  
コマンド:  

```
aws ec2 associate-subnet-cidr-block --subnet-id subnet-5f46ec3b --ipv6-cidr-block 2001:db8:1234:1a00::/64
```
出力:  

```
{
  "SubnetId": "subnet-5f46ec3b",
  "Ipv6CidrBlockAssociation": {
      "Ipv6CidrBlock": "2001:db8:1234:1a00::/64",
      "AssociationId": "subnet-cidr-assoc-3aa54053",
      "Ipv6CidrBlockState": {
          "State": "associating"
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateSubnetCidrBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-subnet-cidr-block.html)」を参照してください。

### `associate-transit-gateway-multicast-domain`
<a name="ec2_AssociateTransitGatewayMulticastDomain_cli_2_topic"></a>

次のコード例は、`associate-transit-gateway-multicast-domain` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway をマルチキャストドメインに関連付けるには**  
次の `associate-transit-gateway-multicast-domain` の例では、指定したサブネットとアタッチメントを指定したマルチキャストドメインに関連付けます。  

```
aws ec2 associate-transit-gateway-multicast-domain \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef79d6e597 \
    --transit-gateway-attachment-id tgw-attach-028c1dd0f8f5cbe8e \
    --subnet-ids subnet-000de86e3b49c932a \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef7EXAMPLE
```
出力:  

```
{
    "Associations": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c4905cef79d6e597",
        "TransitGatewayAttachmentId": "tgw-attach-028c1dd0f8f5cbe8e",
        "ResourceId": "vpc-01128d2c240c09bd5",
        "ResourceType": "vpc",
        "Subnets": [
            {
                "SubnetId": "subnet-000de86e3b49c932a",
                "State": "associating"
            }
        ]
    }
}
```
詳細については、*Transit Gateways ガイド*の「[マルチキャストドメイン](https://docs.aws.amazon.com/vpc/latest/tgw/multicast-domains-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateTransitGatewayMulticastDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-transit-gateway-multicast-domain.html)」を参照してください。

### `associate-transit-gateway-route-table`
<a name="ec2_AssociateTransitGatewayRouteTable_cli_2_topic"></a>

次のコード例は、`associate-transit-gateway-route-table` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ルートテーブルを Transit Gateway アタッチメントに関連付けるには**  
次の例では、指定した Transit Gateway ルートテーブルを指定した VPC アタッチメントと関連付けます。  

```
aws ec2 associate-transit-gateway-route-table \
    --transit-gateway-route-table-id tgw-rtb-002573ed1eEXAMPLE \
    --transit-gateway-attachment-id tgw-attach-0b5968d3b6EXAMPLE
```
出力:  

```
{
    "Association": {
        "TransitGatewayRouteTableId": "tgw-rtb-002573ed1eEXAMPLE",
        "TransitGatewayAttachmentId": "tgw-attach-0b5968d3b6EXAMPLE",
        "ResourceId": "vpc-0065acced4EXAMPLE",
        "ResourceType": "vpc",
        "State": "associating"
    }
}
```
詳細については、「*AWS Transit Gateways ガイド*」の「[Associate a Transit Gateway Route Table](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#associate-tgw-route-table)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateTransitGatewayRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-transit-gateway-route-table.html)」を参照してください。

### `associate-vpc-cidr-block`
<a name="ec2_AssociateVpcCidrBlock_cli_2_topic"></a>

次のコード例は、`associate-vpc-cidr-block` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon が提供する IPv6 CIDR ブロックを VPC に関連付けるには**  
次の `associate-vpc-cidr-block` の例では、IPv6 CIDR ブロックを指定した VPC に関連付けます。  

```
aws ec2 associate-vpc-cidr-block \
    --amazon-provided-ipv6-cidr-block \
    --ipv6-cidr-block-network-border-group us-west-2-lax-1  \
    --vpc-id vpc-8EXAMPLE
```
出力:  

```
{
    "Ipv6CidrBlockAssociation": {
        "AssociationId": "vpc-cidr-assoc-0838ce7d9dEXAMPLE",
        "Ipv6CidrBlockState": {
            "State": "associating"
        },
        "NetworkBorderGroup": "us-west-2-lax-1"
    },
    "VpcId": "vpc-8EXAMPLE"
}
```
**例 2: 追加の IPv4 CIDR ブロックを VPC に関連付けるには**  
次の `associate-vpc-cidr-block` の例では、IPv4 CIDR ブロック `10.2.0.0/16` を指定した VPC に関連付けます。  

```
aws ec2 associate-vpc-cidr-block \
    --vpc-id vpc-1EXAMPLE \
    --cidr-block 10.2.0.0/16
```
出力:  

```
{
    "CidrBlockAssociation": {
        "AssociationId": "vpc-cidr-assoc-2EXAMPLE",
        "CidrBlock": "10.2.0.0/16",
        "CidrBlockState": {
            "State": "associating"
        }
    },
    "VpcId": "vpc-1EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateVpcCidrBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/associate-vpc-cidr-block.html)」を参照してください。

### `attach-classic-link-vpc`
<a name="ec2_AttachClassicLinkVpc_cli_2_topic"></a>

次のコード例は、`attach-classic-link-vpc` を使用する方法を示しています。

**AWS CLI**  
**EC2-Classic インスタンスを VPC にリンク (アタッチ) するには**  
この例では、VPC セキュリティグループ sg-12312312 を介してインスタンス i-1234567890abcdef0 を VPC vpc-88888888 にリンクします。  
コマンド:  

```
aws ec2 attach-classic-link-vpc --instance-id  i-1234567890abcdef0 --vpc-id vpc-88888888 --groups sg-12312312
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachClassicLinkVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-classic-link-vpc.html)」を参照してください。

### `attach-internet-gateway`
<a name="ec2_AttachInternetGateway_cli_2_topic"></a>

次のコード例は、`attach-internet-gateway` を使用する方法を示しています。

**AWS CLI**  
**VPC にインターネットゲートウェイをアタッチするには**  
次の `attach-internet-gateway` の例では、指定したインターネットゲートウェイを特定の VPC にアタッチします。  

```
aws ec2 attach-internet-gateway \
    --internet-gateway-id igw-0d0fb496b3EXAMPLE \
    --vpc-id vpc-0a60eb65b4EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、*Amazon VPC ユーザーガイド*の「[インターネットゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-internet-gateway.html)」を参照してください。

### `attach-network-interface`
<a name="ec2_AttachNetworkInterface_cli_2_topic"></a>

次のコード例は、`attach-network-interface` を使用する方法を示しています。

**AWS CLI**  
**例 1: ネットワークインターフェイスをインスタンスにアタッチするには**  
次の `attach-network-interface` の例では、指定したネットワークインターフェイスを指定したインスタンスにアタッチします。  

```
aws ec2 attach-network-interface \
    --network-interface-id eni-0dc56a8d4640ad10a \
    --instance-id i-1234567890abcdef0 \
    --device-index 1
```
出力:  

```
{
    "AttachmentId": "eni-attach-01a8fc87363f07cf9"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Elastic Network Interface](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html)」を参照してください。  
**例 2: ネットワークインターフェイスを複数のネットワークを持つインスタンスにアタッチするには**  
次の `attach-network-interface` の例では、指定したネットワークインターフェイスを指定したインスタンスとネットワークカードにアタッチします。  

```
aws ec2 attach-network-interface \
    --network-interface-id eni-07483b1897541ad83 \
    --instance-id i-01234567890abcdef \
    --network-card-index 1 \
    --device-index 1
```
出力:  

```
{
    "AttachmentId": "eni-attach-0fbd7ee87a88cd06c"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Elastic Network Interface](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-network-interface.html)」を参照してください。

### `attach-verified-access-trust-provider`
<a name="ec2_AttachVerifiedAccessTrustProvider_cli_2_topic"></a>

次のコード例は、`attach-verified-access-trust-provider` を使用する方法を示しています。

**AWS CLI**  
**信頼プロバイダーをインスタンスにアタッチするには**  
次の `attach-verified-access-trust-provider` の例では、指定した Verified Access 信頼プロバイダーを指定した Verified Access インスタンスにアタッチします。  

```
aws ec2 attach-verified-access-trust-provider \
    --verified-access-instance-id vai-0ce000c0b7643abea \
    --verified-access-trust-provider-id vatp-0bb32de759a3e19e7
```
出力:  

```
{
    "VerifiedAccessTrustProvider": {
        "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
        "Description": "",
        "TrustProviderType": "user",
        "UserTrustProviderType": "iam-identity-center",
        "PolicyReferenceName": "idc",
        "CreationTime": "2023-08-25T19:00:38",
        "LastUpdatedTime": "2023-08-25T19:00:38"
    },
    "VerifiedAccessInstance": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "",
        "VerifiedAccessTrustProviders": [
            {
                "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
                "TrustProviderType": "user",
                "UserTrustProviderType": "iam-identity-center"
            }
        ],
        "CreationTime": "2023-08-25T18:27:56",
        "LastUpdatedTime": "2023-08-25T18:27:56"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Access インスタンス](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachVerifiedAccessTrustProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-verified-access-trust-provider.html)」を参照してください。

### `attach-volume`
<a name="ec2_AttachVolume_cli_2_topic"></a>

次のコード例は、`attach-volume` を使用する方法を示しています。

**AWS CLI**  
**ボリュームをインスタンスにアタッチするには**  
この例では、ボリューム (`vol-1234567890abcdef0`) を `/dev/sdf` としてインスタンス (`i-01474ef662b89480`) にアタッチします。  
コマンド:  

```
aws ec2 attach-volume --volume-id vol-1234567890abcdef0 --instance-id i-01474ef662b89480 --device /dev/sdf
```
出力:  

```
{
    "AttachTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "InstanceId": "i-01474ef662b89480",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "attaching",
    "Device": "/dev/sdf"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-volume.html)」を参照してください。

### `attach-vpn-gateway`
<a name="ec2_AttachVpnGateway_cli_2_topic"></a>

次のコード例は、`attach-vpn-gateway` を使用する方法を示しています。

**AWS CLI**  
**仮想プライベートゲートウェイを VPC にアタッチするには**  
次の `attach-vpn-gateway` の例では、指定した仮想ゲートウェイを指定した VPC にアタッチします。  

```
aws ec2 attach-vpn-gateway \
    --vpn-gateway-id vgw-9a4cacf3 \
    --vpc-id vpc-a01106c2
```
出力:  

```
{
    "VpcAttachment": {
        "State": "attaching",
        "VpcId": "vpc-a01106c2"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/attach-vpn-gateway.html)」を参照してください。

### `authorize-client-vpn-ingress`
<a name="ec2_AuthorizeClientVpnIngress_cli_2_topic"></a>

次のコード例は、`authorize-client-vpn-ingress` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントに承認ルールを追加するには**  
次の `authorize-client-vpn-ingress` の例では、すべてのユーザーにインターネット (`0.0.0.0/0`) へのアクセスを許可するイングレス承認ルールを追加します。  

```
aws ec2 authorize-client-vpn-ingress \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --target-network-cidr 0.0.0.0/0 \
    --authorize-all-groups
```
出力:  

```
{
    "Status": {
        "Code": "authorizing"
    }
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Authorization Rules](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AuthorizeClientVpnIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/authorize-client-vpn-ingress.html)」を参照してください。

### `authorize-security-group-egress`
<a name="ec2_AuthorizeSecurityGroupEgress_cli_2_topic"></a>

次のコード例は、`authorize-security-group-egress` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定のアドレス範囲へのアウトバウンドトラフィックを許可するルールを追加するには**  
次の `authorize-security-group-egress` の例では、TCP ポート 80 で、指定したアドレス範囲へのアクセスを許可するルールを追加します。  

```
aws ec2 authorize-security-group-egress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges=[{CidrIp=10.0.0.0/16}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0b15794cdb17bf29c",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": true,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "CidrIpv4": "10.0.0.0/16"
        }
    ]
}
```
**例 2: 特定のセキュリティグループへのアウトバウンドトラフィックを許可するルールを追加するには**  
次の `authorize-security-group-egress` の例では、TCP ポート 80 で、指定したセキュリティグループへのアクセスを許可するルールを追加します。  

```
aws ec2 authorize-security-group-egress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=80,ToPort=80,UserIdGroupPairs=[{GroupId=sg-0aad1c26bbeec5c22}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0b5dd815afcea9cc3",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": true,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "ReferencedGroupInfo": {
                "GroupId": "sg-0aad1c26bbeec5c22",
                "UserId": "123456789012"
            }
        }
    ]
}
```
詳細については、Amazon VPC ユーザーガイドの「[セキュリティグループ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AuthorizeSecurityGroupEgress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/authorize-security-group-egress.html)」を参照してください。

### `authorize-security-group-ingress`
<a name="ec2_AuthorizeSecurityGroupIngress_cli_2_topic"></a>

次のコード例は、`authorize-security-group-ingress` を使用する方法を示しています。

**AWS CLI**  
**例 1: インバウンド SSH トラフィックを許可するルールを追加するには**  
次の `authorize-security-group-ingress` の例では、TCP ポート 22 (SSH) にインバウンドトラフィックを許可するルールを追加します。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --protocol tcp \
    --port 22 \
    --cidr 203.0.113.0/24
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-01afa97ef3e1bedfc",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIpv4": "203.0.113.0/24"
        }
    ]
}
```
**例 2: セキュリティグループからの HTTP トラフィックを許可するルールを追加するには**  
次の `authorize-security-group-ingress` の例では、ソースセキュリティグループ `sg-1a2b3c4d` からの TCP ポート 80 へのインバウンドアクセスを許可するルールを追加します。ソースグループは、同じ VPC にあるか、ピア VPC (VPC ピアリング接続が必要) に存在している必要があります。着信トラフィックは、ソースセキュリティグループに関連付けられたインスタンスのプライベート IP アドレスに基づいて許可されます (パブリック IP アドレスまたは Elastic IP アドレスは考慮されません)。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --protocol tcp \
    --port 80 \
    --source-group sg-1a2b3c4d
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-01f4be99110f638a7",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 80,
            "ToPort": 80,
            "ReferencedGroupInfo": {
                "GroupId": "sg-1a2b3c4d",
                "UserId": "123456789012"
            }
        }
    ]
}
```
**例 3: 同じ呼び出しに複数のルールを追加するには**  
次の `authorize-security-group-ingress` の例では、`ip-permissions` パラメータを使用して 2 つのインバウンドルールを追加します。一方は TCP ポート 3389 (RDP) でのインバウンドアクセスを有効にするルールであり、もう一方は ping/ICMP を有効にするルールです。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=3389,ToPort=3389,IpRanges=[{CidrIp=172.31.0.0/16}]' 'IpProtocol=icmp,FromPort=-1,ToPort=-1,IpRanges=[{CidrIp=172.31.0.0/16}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-00e06e5d3690f29f3",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 3389,
            "ToPort": 3389,
            "CidrIpv4": "172.31.0.0/16"
        },
        {
            "SecurityGroupRuleId": "sgr-0a133dd4493944b87",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv4": "172.31.0.0/16"
        }
    ]
}
```
**例 4: ICMP トラフィックのルールを追加するには**  
次の `authorize-security-group-ingress` の例では、`ip-permissions` パラメータを使用して、どこからでも ICMP メッセージ `Destination Unreachable: Fragmentation Needed and Don't Fragment was Set` (タイプ 3、コード 4) を許可するインバウンドルールを追加します。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=icmp,FromPort=3,ToPort=4,IpRanges=[{CidrIp=0.0.0.0/0}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0de3811019069b787",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "icmp",
            "FromPort": 3,
            "ToPort": 4,
            "CidrIpv4": "0.0.0.0/0"
        }
    ]
}
```
**例 5: IPv6 トラフィックのルールを追加するには**  
次の `authorize-security-group-ingress` の例では、`ip-permissions` パラメータを使用して、IPv6 範囲 `2001:db8:1234:1a00::/64` からの SSH アクセス (ポート 22) を許可するインバウンドルールを追加します。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=22,ToPort=22,Ipv6Ranges=[{CidrIpv6=2001:db8:1234:1a00::/64}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0455bc68b60805563",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 22,
            "ToPort": 22,
            "CidrIpv6": "2001:db8:1234:1a00::/64"
        }
    ]
}
```
**例 6: ICMPv6 トラフィックのルールを追加するには**  
次の `authorize-security-group-ingress` の例では、`ip-permissions` パラメータを使用して、どこからでも ICMPv6 トラフィックを許可するインバウンドルールを追加します。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=icmpv6,Ipv6Ranges=[{CidrIpv6=::/0}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-04b612d9363ab6327",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "icmpv6",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv6": "::/0"
        }
    ]
}
```
**例 7: 説明付きのルールを追加する**  
次の `authorize-security-group-ingress` の例では、`ip-permissions` パラメータを使用して、指定した IPv4 アドレス範囲からの RDP トラフィックを許可するインバウンドルールを追加します。ルールには、後で特定できるように説明が含まれます。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-1234567890abcdef0 \
    --ip-permissions 'IpProtocol=tcp,FromPort=3389,ToPort=3389,IpRanges=[{CidrIp=203.0.113.0/24,Description='RDP access from NY office'}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-0397bbcc01e974db3",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "tcp",
            "FromPort": 3389,
            "ToPort": 3389,
            "CidrIpv4": "203.0.113.0/24",
            "Description": "RDP access from NY office"
        }
    ]
}
```
**例 8: プレフィックスリストを使用するインバウンドルールを追加するには**  
次の `authorize-security-group-ingress` の例では、`ip-permissions` パラメータを使用して、指定されたプレフィックスリスト内の CIDR 範囲のトラフィックすべてを許可するインバウンドルールを追加します。  

```
aws ec2 authorize-security-group-ingress \
    --group-id sg-04a351bfe432d4e71 \
    --ip-permissions 'IpProtocol=all,PrefixListIds=[{PrefixListId=pl-002dc3ec097de1514}]'
```
出力:  

```
{
    "Return": true,
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-09c74b32f677c6c7c",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "123456789012",
            "IsEgress": false,
            "IpProtocol": "-1",
            "FromPort": -1,
            "ToPort": -1,
            "PrefixListId": "pl-0721453c7ac4ec009"
        }
    ]
}
```
詳細については、Amazon VPC ユーザーガイドの「[セキュリティグループ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AuthorizeSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/authorize-security-group-ingress.html)」を参照してください。

### `bundle-instance`
<a name="ec2_BundleInstance_cli_2_topic"></a>

次のコード例は、`bundle-instance` を使用する方法を示しています。

**AWS CLI**  
**インスタンスをバンドルするには**  
この例では、`bundletasks` という名前のバケットにインスタンス `i-1234567890abcdef0` をバンドルします。アクセスキー IDs AWS 「アクセスキーを管理するためのベストプラクティス」のガイダンスを確認して従ってください。  
コマンド:  

```
aws ec2 bundle-instance --instance-id i-1234567890abcdef0 --bucket bundletasks --prefix winami --owner-akid AK12AJEXAMPLE --owner-sak example123example
```
出力:  

```
{
  "BundleTask": {
    "UpdateTime": "2015-09-15T13:30:35.000Z",
    "InstanceId": "i-1234567890abcdef0",
    "Storage": {
      "S3": {
        "Prefix": "winami",
        "Bucket": "bundletasks"
      }
    },
    "State": "pending",
    "StartTime": "2015-09-15T13:30:35.000Z",
    "BundleId": "bun-294e041f"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BundleInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/bundle-instance.html)」を参照してください。

### `cancel-bundle-task`
<a name="ec2_CancelBundleTask_cli_2_topic"></a>

次のコード例は、`cancel-bundle-task` を使用する方法を示しています。

**AWS CLI**  
**バンドルタスクをキャンセルするには**  
この例では、バンドルタスク `bun-2a4e041c` をキャンセルします。  
コマンド:  

```
aws ec2 cancel-bundle-task --bundle-id bun-2a4e041c
```
出力:  

```
{
  "BundleTask": {
    "UpdateTime": "2015-09-15T13:27:40.000Z",
    "InstanceId": "i-1234567890abcdef0",
    "Storage": {
      "S3": {
        "Prefix": "winami",
        "Bucket": "bundletasks"
      }
    },
    "State": "cancelling",
    "StartTime": "2015-09-15T13:24:35.000Z",
    "BundleId": "bun-2a4e041c"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelBundleTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-bundle-task.html)」を参照してください。

### `cancel-capacity-reservation-fleets`
<a name="ec2_CancelCapacityReservationFleets_cli_2_topic"></a>

次のコード例は、`cancel-capacity-reservation-fleets` を使用する方法を示しています。

**AWS CLI**  
**キャパシティ予約フリートをキャンセルするには**  
次の `cancel-capacity-reservation-fleets` の例では、指定したキャパシティ予約フリートとそれが予約するキャパシティをキャンセルします。フリートをキャンセルすると、そのステータスが `cancelled` に変わり、キャパシティ予約を新たに作成することはできなくなります。さらに、フリート内の個々のキャパシティ予約はすべてキャンセルされます。また、以前にリザーブドキャパシティで実行されていたインスタンスは、共有キャパシティを使用して正常に実行が継続されます。  

```
aws ec2 cancel-capacity-reservation-fleets \
    --capacity-reservation-fleet-ids crf-abcdef01234567890
```
出力:  

```
{
    "SuccessfulFleetCancellations": [
        {
            "CurrentFleetState": "cancelling",
            "PreviousFleetState": "active",
            "CapacityReservationFleetId": "crf-abcdef01234567890"
        }
    ],
    "FailedFleetCancellations": []
}
```
キャパシティ予約フリートの詳細については、「*Amazon EC2 ユーザーガイド*」の「[キャパシティ予約フリート](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/cr-fleets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelCapacityReservationFleets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-capacity-reservation-fleets.html)」を参照してください。

### `cancel-capacity-reservation`
<a name="ec2_CancelCapacityReservation_cli_2_topic"></a>

次のコード例は、`cancel-capacity-reservation` を使用する方法を示しています。

**AWS CLI**  
**キャパシティ予約をキャンセルするには**  
次の `cancel-capacity-reservation` の例では、指定したキャパシティ予約をキャンセルします。  

```
aws ec2 cancel-capacity-reservation \
    --capacity-reservation-id cr-1234abcd56EXAMPLE
```
出力:  

```
{
    "Return": true
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[キャパシティ予約のキャンセル](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-release.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelCapacityReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-capacity-reservation.html)」を参照してください。

### `cancel-conversion-task`
<a name="ec2_CancelConversionTask_cli_2_topic"></a>

次のコード例は、`cancel-conversion-task` を使用する方法を示しています。

**AWS CLI**  
**インスタンスまたはボリュームのアクティブな変換をキャンセルするには**  
この例では、タスク ID import-i-fh95npoc に関連付けられたアップロードをキャンセルします。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 cancel-conversion-task --conversion-task-id import-i-fh95npoc
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelConversionTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-conversion-task.html)」を参照してください。

### `cancel-export-task`
<a name="ec2_CancelExportTask_cli_2_topic"></a>

次のコード例は、`cancel-export-task` を使用する方法を示しています。

**AWS CLI**  
**アクティブなエクスポートタスクをキャンセルするには**  
この例では、タスク ID export-i-fgelt0i7 を使用してアクティブなエクスポートタスクをキャンセルします。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 cancel-export-task --export-task-id export-i-fgelt0i7
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelExportTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-export-task.html)」を参照してください。

### `cancel-image-launch-permission`
<a name="ec2_CancelImageLaunchPermission_cli_2_topic"></a>

次のコード例は、`cancel-image-launch-permission` を使用する方法を示しています。

**AWS CLI**  
** Amazon Web Services アカウントとの AMI の共有をキャンセルするには**  
次の `cancel-image-launch-permission` の例では、指定した AMI 起動許可からアカウントが削除されます。  

```
aws ec2 cancel-image-launch-permission \
    --image-id ami-0123456789example \
    --region us-east-1
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Cancel having an AMI shared with your Amazon Web Services account](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/cancel-sharing-an-AMI.html#cancel-image-launch-permission)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelImageLaunchPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-image-launch-permission.html)」を参照してください。

### `cancel-import-task`
<a name="ec2_CancelImportTask_cli_2_topic"></a>

次のコード例は、`cancel-import-task` を使用する方法を示しています。

**AWS CLI**  
**インポートタスクをキャンセルするには**  
次の `cancel-import-task` の例では、指定したイメージのインポートタスクをキャンセルします。  

```
aws ec2 cancel-import-task \
    --import-task-id import-ami-1234567890abcdef0
```
出力:  

```
{
    "ImportTaskId": "import-ami-1234567890abcdef0",
    "PreviousState": "active",
    "State": "deleting"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelImportTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-import-task.html)」を参照してください。

### `cancel-reserved-instances-listing`
<a name="ec2_CancelReservedInstancesListing_cli_2_topic"></a>

次のコード例は、`cancel-reserved-instances-listing` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスのリストをキャンセルするには**  
次の `cancel-reserved-instances-listing` の例では、指定したリザーブドインスタンスのリストをキャンセルします。  

```
aws ec2 cancel-reserved-instances-listing \
    --reserved-instances-listing-id 5ec28771-05ff-4b9b-aa31-9e57dexample
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelReservedInstancesListing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-reserved-instances-listing.html)」を参照してください。

### `cancel-spot-fleet-requests`
<a name="ec2_CancelSpotFleetRequests_cli_2_topic"></a>

次のコード例は、`cancel-spot-fleet-requests` を使用する方法を示しています。

**AWS CLI**  
**例 1: スポットフリートリクエストをキャンセルし、関連付けられたインスタンスを終了するには**  
次の `cancel-spot-fleet-requests` の例では、スポットフリートリクエストをキャンセルし、関連付けられたオンデマンドインスタンスとスポットインスタンスを終了します。  

```
aws ec2 cancel-spot-fleet-requests \
    --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE \
    --terminate-instances
```
出力:  

```
{
    "SuccessfulFleetRequests": [
        {
            "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
            "CurrentSpotFleetRequestState": "cancelled_terminating",
            "PreviousSpotFleetRequestState": "active"
        }
    ],
    "UnsuccessfulFleetRequests": []
}
```
**例 2: 関連付けられたインスタンスを終了せずに、スポットフリートリクエストをキャンセルするには**  
次の `cancel-spot-fleet-requests` の例では、関連付けられたオンデマンドインスタンスとスポットインスタンスを終了しないで、スポットフリートリクエストをキャンセルします。  

```
aws ec2 cancel-spot-fleet-requests \
    --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE \
    --no-terminate-instances
```
出力:  

```
{
    "SuccessfulFleetRequests": [
        {
            "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
            "CurrentSpotFleetRequestState": "cancelled_running",
            "PreviousSpotFleetRequestState": "active"
        }
    ],
    "UnsuccessfulFleetRequests": []
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[スポットフリートリクエストのキャンセル](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/cancel-spot-fleet.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelSpotFleetRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-spot-fleet-requests.html)」を参照してください。

### `cancel-spot-instance-requests`
<a name="ec2_CancelSpotInstanceRequests_cli_2_topic"></a>

次のコード例は、`cancel-spot-instance-requests` を使用する方法を示しています。

**AWS CLI**  
**スポットインスタンスリクエストをキャンセルするには**  
このコマンド例では、スポットインスタンスリクエストをキャンセルします。  
コマンド:  

```
aws ec2 cancel-spot-instance-requests --spot-instance-request-ids sir-08b93456
```
出力:  

```
{
    "CancelledSpotInstanceRequests": [
        {
            "State": "cancelled",
            "SpotInstanceRequestId": "sir-08b93456"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelSpotInstanceRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/cancel-spot-instance-requests.html)」を参照してください。

### `confirm-product-instance`
<a name="ec2_ConfirmProductInstance_cli_2_topic"></a>

次のコード例は、`confirm-product-instance` を使用する方法を示しています。

**AWS CLI**  
**製品インスタンスを確認するには**  
この例では、指定された製品コードが指定されたインスタンスに関連付けられているかどうかを判断します。  
コマンド:  

```
aws ec2 confirm-product-instance --product-code 774F4FF8 --instance-id i-1234567890abcdef0
```
出力:  

```
{
  "OwnerId": "123456789012"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmProductInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/confirm-product-instance.html)」を参照してください。

### `copy-fpga-image`
<a name="ec2_CopyFpgaImage_cli_2_topic"></a>

次のコード例は、`copy-fpga-image` を使用する方法を示しています。

**AWS CLI**  
**Amazon FPGA イメージをコピーするには**  
この例では、指定された AFI を `us-east-1` リージョンから現在のリージョン (`eu-west-1`) にコピーします。  
コマンド:  

```
aws ec2 copy-fpga-image --name copy-afi --source-fpga-image-id afi-0d123e123bfc85abc --source-region us-east-1 --region eu-west-1
```
出力:  

```
{
  "FpgaImageId": "afi-06b12350a123fbabc"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyFpgaImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/copy-fpga-image.html)」を参照してください。

### `copy-image`
<a name="ec2_CopyImage_cli_2_topic"></a>

次のコード例は、`copy-image` を使用する方法を示しています。

**AWS CLI**  
**例 1: AMI を別のリージョンにコピーするには**  
次の `copy-image` の例では、指定した AMI を `us-west-2` リージョンから `us-east-1` リージョンにコピーし、簡単な説明を追加します。  

```
aws ec2 copy-image \
    --region us-east-1 \
    --name ami-name \
    --source-region us-west-2 \
    --source-image-id ami-066877671789bd71b \
    --description "This is my copied image."
```
出力:  

```
{
    "ImageId": "ami-0123456789abcdefg"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[AMI のコピー](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html)」を参照してください。  
**例 2: AMI を別のリージョンにコピーし、バッキングスナップショットを暗号化するには**  
次の `copy-image` コマンドは、指定した AMI を `us-west-2` リージョンから現在のリージョンにコピーし、指定した KMS キーを使用してバックアップするスナップショットを暗号化します。  

```
aws ec2 copy-image \
    --source-region us-west-2 \
    --name ami-name \
    --source-image-id ami-066877671789bd71b \
    --encrypted \
    --kms-key-id alias/my-kms-key
```
出力:  

```
{
    "ImageId": "ami-0123456789abcdefg"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[AMI のコピー](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html)」を参照してください。  
**例 3: AMI のコピー時にユーザー定義の AMI タグを含めるには**  
次の `copy-image` コマンドは、`--copy-image-tags` パラメータを使用して、AMI のコピー時にユーザー定義の AMI タグをコピーします。  

```
aws ec2 copy-image \
    --region us-east-1 \
    --name ami-name \
    --source-region us-west-2 \
    --source-image-id ami-066877671789bd71b \
    --description "This is my copied image."
    --copy-image-tags
```
出力:  

```
{
    "ImageId": "ami-0123456789abcdefg"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[AMI のコピー](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/CopyingAMIs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/copy-image.html)」を参照してください。

### `copy-snapshot`
<a name="ec2_CopySnapshot_cli_2_topic"></a>

次のコード例は、`copy-snapshot` を使用する方法を示しています。

**AWS CLI**  
**例 1: スナップショットを別のリージョンにコピーするには**  
次の `copy-snapshot` の例では、指定したスナップショットを `us-west-2` リージョンから `us-east-1` リージョンにコピーし、簡単な説明を追加します。  

```
aws ec2 copy-snapshot \
    --region us-east-1 \
    --source-region us-west-2 \
    --source-snapshot-id snap-066877671789bd71b \
    --description 'This is my copied snapshot.'
```
出力:  

```
{
    "SnapshotId": "snap-066877671789bd71b"
}
```
**例 2: 暗号化されていないスナップショットをコピーし、新しいスナップショットを暗号化するには**  
次の `copy-snapshot` コマンドは、指定した暗号化されていないスナップショットを `us-west-2` リージョンから現在のリージョンにコピーし、指定した KMS キーを使用してバックアップするスナップショットを暗号化します。  

```
aws ec2 copy-snapshot \
    --source-region us-west-2 \
    --source-snapshot-id snap-066877671789bd71b \
    --encrypted \
    --kms-key-id alias/my-kms-key
```
出力:  

```
{
    "SnapshotId": "snap-066877671789bd71b"
}
```
詳細については、*Amazon EBS ユーザーガイド*の「[Amazon EBS スナップショットのコピー](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-copy-snapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopySnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/copy-snapshot.html)」を参照してください。

### `create-capacity-reservation-fleet`
<a name="ec2_CreateCapacityReservationFleet_cli_2_topic"></a>

次のコード例は、`create-capacity-reservation-fleet` を使用する方法を示しています。

**AWS CLI**  
**キャパシティ予約フリートを作成するには**  
次の `create-capacity-reservation-fleet` の例では、リクエストで指定したインスタンスタイプのキャパシティ予約フリートを、指定した合計ターゲット容量を上限として作成します。キャパシティ予約フリートがキャパシティを予約するインスタンスの数は、リクエストで指定する合計ターゲット容量とインスタンスタイプの重みによって異なります。使用するインスタンスタイプと、指定された各インスタンスタイプの優先度を指定します。  

```
aws ec2 create-capacity-reservation-fleet \
--total-target-capacity 24 \
--allocation-strategy prioritized \
--instance-match-criteria open \
--tenancy default \
--end-date 2022-12-31T23:59:59.000Z \
--instance-type-specifications file://instanceTypeSpecification.json
```
`instanceTypeSpecification.json` の内容:  

```
[
    {
        "InstanceType": "m5.xlarge",
        "InstancePlatform": "Linux/UNIX",
        "Weight": 3.0,
        "AvailabilityZone":"us-east-1a",
        "EbsOptimized": true,
        "Priority" : 1
    }
]
```
出力:  

```
{
    "Status": "submitted",
    "TotalFulfilledCapacity": 0.0,
    "CapacityReservationFleetId": "crf-abcdef01234567890",
    "TotalTargetCapacity": 24
}
```
キャパシティ予約フリートの詳細については、「*Amazon EC2 ユーザーガイド*」の「[キャパシティ予約フリート](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/cr-fleets.html)」を参照してください。  
インスタンスタイプの重みと合計ターゲット容量の詳細については、「*Amazon EC2 ユーザーガイド*」の「[インスタンスタイプの重み](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/crfleet-concepts.html#instance-weight)」と「[総ターゲット容量](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/crfleet-concepts.html#target-capacity)」を参照してください。  
指定されたインスタンスタイプの優先順位の指定の詳細については、「*Amazon EC2 ユーザーガイド*」の「[配分戦略](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/crfleet-concepts.html#allocation-strategy)」と「[インスタンスタイプ優先順位](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/crfleet-concepts.html#instance-priority)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCapacityReservationFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-capacity-reservation-fleet.html)」を参照してください。

### `create-capacity-reservation`
<a name="ec2_CreateCapacityReservation_cli_2_topic"></a>

次のコード例は、`create-capacity-reservation` を使用する方法を示しています。

**AWS CLI**  
**例 1: キャパシティ予約を作成するには**  
次の `create-capacity-reservation` の例では、`eu-west-1a` アベイラビリティーゾーンにキャパシティ予約を作成します。そこでは、Linux/Unix オペレーティングシステムを実行している 3 つの `t2.medium` インスタンスを起動できます。デフォルトでは、キャパシティ予約はオープンインスタンス一致基準で作成され、エフェメラルストレージはサポートされません。手動でキャンセルされるまでアクティブな状態を維持します。  

```
aws ec2 create-capacity-reservation \
    --availability-zone eu-west-1a \
    --instance-type t2.medium \
    --instance-platform Linux/UNIX \
    --instance-count 3
```
出力:  

```
{
    "CapacityReservation": {
        "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
        "EndDateType": "unlimited",
        "AvailabilityZone": "eu-west-1a",
        "InstanceMatchCriteria": "open",
        "EphemeralStorage": false,
        "CreateDate": "2019-08-16T09:27:35.000Z",
        "AvailableInstanceCount": 3,
        "InstancePlatform": "Linux/UNIX",
        "TotalInstanceCount": 3,
        "State": "active",
        "Tenancy": "default",
        "EbsOptimized": false,
        "InstanceType": "t2.medium"
    }
}
```
**例 2: 指定した日付/時刻に自動的に終了するキャパシティ予約を作成するには**  
次の `create-capacity-reservation` の例では、`eu-west-1a` アベイラビリティーゾーンにキャパシティ予約を作成します。そこでは、Linux/Unix オペレーティングシステムを実行している 3 つの `m5.large` インスタンスを起動できます。このキャパシティ予約は、2019/8/31 の 23:59:59 に自動的に終了します。  

```
aws ec2 create-capacity-reservation \
    --availability-zone eu-west-1a \
    --instance-type m5.large \
    --instance-platform Linux/UNIX \
    --instance-count 3 \
    --end-date-type limited \
    --end-date 2019-08-31T23:59:59Z
```
出力:  

```
{
    "CapacityReservation": {
        "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
        "EndDateType": "limited",
        "AvailabilityZone": "eu-west-1a",
        "EndDate": "2019-08-31T23:59:59.000Z",
        "InstanceMatchCriteria": "open",
        "EphemeralStorage": false,
        "CreateDate": "2019-08-16T10:15:53.000Z",
        "AvailableInstanceCount": 3,
        "InstancePlatform": "Linux/UNIX",
        "TotalInstanceCount": 3,
        "State": "active",
        "Tenancy": "default",
        "EbsOptimized": false,
        "InstanceType": "m5.large"
    }
}
```
**例 3: 対象インスタンスの起動のみを受け入れるキャパシティ予約を作成するには**  
次の `create-capacity-reservation` の例では、対象インスタンスの起動のみを承諾するキャパシティ予約を作成します。  

```
aws ec2 create-capacity-reservation \
    --availability-zone eu-west-1a \
    --instance-type m5.large \
    --instance-platform Linux/UNIX \
    --instance-count 3 \
    --instance-match-criteria targeted
```
出力:  

```
{
    "CapacityReservation": {
        "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
        "EndDateType": "unlimited",
        "AvailabilityZone": "eu-west-1a",
        "InstanceMatchCriteria": "targeted",
        "EphemeralStorage": false,
        "CreateDate": "2019-08-16T10:21:57.000Z",
        "AvailableInstanceCount": 3,
        "InstancePlatform": "Linux/UNIX",
        "TotalInstanceCount": 3,
        "State": "active",
        "Tenancy": "default",
        "EbsOptimized": false,
        "InstanceType": "m5.large"
    }
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[ キャパシティ予約の作成](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCapacityReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-capacity-reservation.html)」を参照してください。

### `create-carrier-gateway`
<a name="ec2_CreateCarrierGateway_cli_2_topic"></a>

次のコード例は、`create-carrier-gateway` を使用する方法を示しています。

**AWS CLI**  
**キャリアゲートウェイを作成するには**  
次の `create-carrier-gateway` の例では、指定した VPC のキャリアゲートウェイを作成します。  

```
aws ec2 create-carrier-gateway \
    --vpc-id vpc-0c529aEXAMPLE1111
```
出力:  

```
{
    "CarrierGateway": {
        "CarrierGatewayId": "cagw-0465cdEXAMPLE1111",
        "VpcId": "vpc-0c529aEXAMPLE1111",
        "State": "pending",
        "OwnerId": "123456789012"
    }
}
```
詳細については、「*AWS Wavelength ユーザーガイド*」の「[Carrier gateways](https://docs.aws.amazon.com/wavelength/latest/developerguide/carrier-gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCarrierGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-carrier-gateway.html)」を参照してください。

### `create-client-vpn-endpoint`
<a name="ec2_CreateClientVpnEndpoint_cli_2_topic"></a>

次のコード例は、`create-client-vpn-endpoint` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントを作成するには**  
次の `create-client-vpn-endpoint` の例では、相互認証を使用するクライアント VPN エンドポイントを作成し、クライアント CIDR ブロックの値を指定します。  

```
aws ec2 create-client-vpn-endpoint \
    --client-cidr-block "172.31.0.0/16" \
    --server-certificate-arn arn:aws:acm:ap-south-1:123456789012:certificate/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --authentication-options Type=certificate-authentication,MutualAuthentication={ClientRootCertificateChainArn=arn:aws:acm:ap-south-1:123456789012:certificate/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE} \
    --connection-log-options Enabled=false
```
出力:  

```
{
    "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
    "Status": {
        "Code": "pending-associate"
    },
    "DnsName": "cvpn-endpoint-123456789123abcde.prod.clientvpn.ap-south-1.amazonaws.com"
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client VPN Endpoints](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateClientVpnEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-client-vpn-endpoint.html)」を参照してください。

### `create-client-vpn-route`
<a name="ec2_CreateClientVpnRoute_cli_2_topic"></a>

次のコード例は、`create-client-vpn-route` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントのルートを作成するには**  
次の `create-client-vpn-route` の例では、クライアント VPN エンドポイントの指定されたサブネット用にインターネット (`0.0.0.0/0`) へのルートを追加します。  

```
aws ec2 create-client-vpn-route \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --destination-cidr-block 0.0.0.0/0  \
    --target-vpc-subnet-id subnet-0123456789abcabca
```
出力:  

```
{
    "Status": {
        "Code": "creating"
    }
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Routes](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateClientVpnRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-client-vpn-route.html)」を参照してください。

### `create-coip-cidr`
<a name="ec2_CreateCoipCidr_cli_2_topic"></a>

次のコード例は、`create-coip-cidr` を使用する方法を示しています。

**AWS CLI**  
**顧客所有の IP (CoIP) アドレスの範囲を作成するには**  
次の `create-coip-cidr` の例では、指定した CoIP プールに指定した CoIP アドレスの範囲を作成します。  

```
aws ec2 create-coip-cidr \
    --cidr 15.0.0.0/24 \
    --coip-pool-id ipv4pool-coip-1234567890abcdefg
```
出力:  

```
{
    "CoipCidr": {
        "Cidr": "15.0.0.0/24",
        "CoipPoolId": "ipv4pool-coip-1234567890abcdefg",
        "LocalGatewayRouteTableId": "lgw-rtb-abcdefg1234567890"
    }
}
```
CoIP の詳細については、「*AWS Outposts ユーザーガイド*」の「[カスタマー所有の IP アドレス](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#ip-addressing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-coip-cidr.html)」を参照してください。

### `create-coip-pool`
<a name="ec2_CreateCoipPool_cli_2_topic"></a>

次のコード例は、`create-coip-pool` を使用する方法を示しています。

**AWS CLI**  
**顧客所有の IP (CoIP) アドレスのプールを作成するには**  
次の `create-coip-pool` の例では、指定したローカルゲートウェイのルートテーブルに CoIP アドレスの CoIP プールを作成します。  

```
aws ec2 create-coip-pool \
    --local-gateway-route-table-id lgw-rtb-abcdefg1234567890
```
出力:  

```
{
    "CoipPool": {
        "PoolId": "ipv4pool-coip-1234567890abcdefg",
        "LocalGatewayRouteTableId": "lgw-rtb-abcdefg1234567890",
        "PoolArn": "arn:aws:ec2:us-west-2:123456789012:coip-pool/ipv4pool-coip-1234567890abcdefg"
    }
}
```
CoIP の詳細については、「*AWS Outposts ユーザーガイド*」の「[カスタマー所有の IP アドレス](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#ip-addressing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCoipPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-coip-pool.html)」を参照してください。

### `create-customer-gateway`
<a name="ec2_CreateCustomerGateway_cli_2_topic"></a>

次のコード例は、`create-customer-gateway` を使用する方法を示しています。

**AWS CLI**  
**カスタマーゲートウェイを作成するには**  
この例では、外部インターフェイスに指定された IP アドレスを持つカスタマーゲートウェイを作成します。  
コマンド:  

```
aws ec2 create-customer-gateway --type ipsec.1 --public-ip 12.1.2.3 --bgp-asn 65534
```
出力:  

```
{
    "CustomerGateway": {
        "CustomerGatewayId": "cgw-0e11f167",
        "IpAddress": "12.1.2.3",
        "State": "available",
        "Type": "ipsec.1",
        "BgpAsn": "65534"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomerGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-customer-gateway.html)」を参照してください。

### `create-default-subnet`
<a name="ec2_CreateDefaultSubnet_cli_2_topic"></a>

次のコード例は、`create-default-subnet` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのサブネットを作成するには**  
この例では、アベイラビリティーゾーン `us-east-2a` にデフォルトのサブネットを作成します。  
コマンド:  

```
 aws ec2 create-default-subnet --availability-zone us-east-2a

{
   "Subnet": {
       "AvailabilityZone": "us-east-2a",
       "Tags": [],
       "AvailableIpAddressCount": 4091,
       "DefaultForAz": true,
       "Ipv6CidrBlockAssociationSet": [],
       "VpcId": "vpc-1a2b3c4d",
       "State": "available",
       "MapPublicIpOnLaunch": true,
       "SubnetId": "subnet-1122aabb",
       "CidrBlock": "172.31.32.0/20",
       "AssignIpv6AddressOnCreation": false
   }
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDefaultSubnet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-default-subnet.html)」を参照してください。

### `create-default-vpc`
<a name="ec2_CreateDefaultVpc_cli_2_topic"></a>

次のコード例は、`create-default-vpc` を使用する方法を示しています。

**AWS CLI**  
**デフォルトの VPC を作成するには**  
この例では、デフォルトの VPC を作成します。  
コマンド:  

```
aws ec2 create-default-vpc
```
出力:  

```
{
   "Vpc": {
       "VpcId": "vpc-8eaae5ea",
       "InstanceTenancy": "default",
       "Tags": [],
       "Ipv6CidrBlockAssociationSet": [],
       "State": "pending",
       "DhcpOptionsId": "dopt-af0c32c6",
       "CidrBlock": "172.31.0.0/16",
       "IsDefault": true
   }
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDefaultVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-default-vpc.html)」を参照してください。

### `create-dhcp-options`
<a name="ec2_CreateDhcpOptions_cli_2_topic"></a>

次のコード例は、`create-dhcp-options` を使用する方法を示しています。

**AWS CLI**  
**DHCP オプションセットを作成するには**  
次の `create-dhcp-options` の例では、ドメイン名、ドメインネームサーバー、NetBIOS ノードタイプを指定する DHCP オプションセットを作成します。  

```
aws ec2 create-dhcp-options \
    --dhcp-configuration \
        "Key=domain-name-servers,Values=10.2.5.1,10.2.5.2" \
        "Key=domain-name,Values=example.com" \
        "Key=netbios-node-type,Values=2"
```
出力:  

```
{
    "DhcpOptions": {
        "DhcpConfigurations": [
            {
                "Key": "domain-name",
                "Values": [
                    {
                        "Value": "example.com"
                    }
                ]
            },
            {
                "Key": "domain-name-servers",
                "Values": [
                    {
                        "Value": "10.2.5.1"
                    },
                    {
                        "Value": "10.2.5.2"
                    }
                ]
            },
            {
                "Key": "netbios-node-type",
                "Values": [
                    {
                        "Value": "2"
                    }
                ]
            }
        ],
        "DhcpOptionsId": "dopt-06d52773eff4c55f3"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-dhcp-options.html)」を参照してください。

### `create-egress-only-internet-gateway`
<a name="ec2_CreateEgressOnlyInternetGateway_cli_2_topic"></a>

次のコード例は、`create-egress-only-internet-gateway` を使用する方法を示しています。

**AWS CLI**  
**Egress-Only インターネットゲートウェイを作成するには**  
この例では、指定した VPC の Egress-only インターネットゲートウェイを作成します。  
コマンド:  

```
aws ec2 create-egress-only-internet-gateway --vpc-id vpc-0c62a468
```
出力:  

```
{
  "EgressOnlyInternetGateway": {
      "EgressOnlyInternetGatewayId": "eigw-015e0e244e24dfe8a",
      "Attachments": [
          {
              "State": "attached",
              "VpcId": "vpc-0c62a468"
          }
      ]
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEgressOnlyInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-egress-only-internet-gateway.html)」を参照してください。

### `create-fleet`
<a name="ec2_CreateFleet_cli_2_topic"></a>

次のコード例は、`create-fleet` を使用する方法を示しています。

**AWS CLI**  
**例 1: スポットインスタンスをデフォルトの購入モデルとして起動する EC2 フリートを作成するには**  
次の `create-fleet` の例では、フリートを起動するのに必要な最小限のパラメータ (起動テンプレート、ターゲット容量、デフォルト購入モデル) を使用して EC2 フリートを作成します。起動テンプレートは、起動テンプレート ID とバージョン番号によって識別されます。フリートのターゲット容量は 2 個のインスタンスであり、デフォルト購入モデルは `spot` です。この結果、フリートは 2 個のスポットインスタンスを起動します。  
EC2 フリート を作成するときは、JSON ファイルを使用して起動するインスタンスについての情報を指定します。  

```
aws ec2 create-fleet \
    --cli-input-json file://file_name.json
```
file\$1name.json の内容:  

```
{
    "LaunchTemplateConfigs": [
    {
        "LaunchTemplateSpecification": {
        "LaunchTemplateId": "lt-0e8c754449b27161c",
        "Version": "1"
        }
    }
    ],
    "TargetCapacitySpecification": {
        "TotalTargetCapacity": 2,
        "DefaultTargetCapacityType": "spot"
    }
}
```
出力:  

```
{
    "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE"
}
```
**例 2: オンデマンドインスタンスをデフォルトの購入モデルとして起動する EC2 フリートを作成するには**  
次の `create-fleet` の例では、フリートを起動するのに必要な最小限のパラメータ (起動テンプレート、ターゲット容量、デフォルト購入モデル) を使用して EC2 フリートを作成します。起動テンプレートは、起動テンプレート ID とバージョン番号によって識別されます。フリートのターゲット容量は 2 個のインスタンスであり、デフォルト購入モデルは `on-demand` です。この結果、フリートは 2 個のオンデマンドインスタンス を起動します。  
EC2 フリート を作成するときは、JSON ファイルを使用して起動するインスタンスについての情報を指定します。  

```
aws ec2 create-fleet \
    --cli-input-json file://file_name.json
```
file\$1name.json の内容:  

```
{
    "LaunchTemplateConfigs": [
    {
        "LaunchTemplateSpecification": {
        "LaunchTemplateId": "lt-0e8c754449b27161c",
        "Version": "1"
        }
    }
    ],
    "TargetCapacitySpecification": {
    "TotalTargetCapacity": 2,
    "DefaultTargetCapacityType": "on-demand"
    }
}
```
出力:  

```
{
    "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE"
}
```
**例 3: オンデマンドインスタンスをプライマリキャパシティとして起動する EC2 フリートを作成するには**  
次の `create-fleet` の例では、フリートの合計ターゲット容量を 2 つのインスタンス、ターゲット容量を 1 つのオンデマンドインスタンスとして指定する EC2 フリートを作成します。デフォルトの購入モデルは `spot` です。フリートは指定されたとおり 1 個のオンデマンドインスタンス を起動しますが、合計ターゲット容量を満たすために、さらに 1 個以上のインスタンスを起動する必要があります。差額の購入モデルは、`TotalTargetCapacity` - `OnDemandTargetCapacity` = `DefaultTargetCapacityType` で計算されます。この結果、フリートは 1 個のスポットインスタンスを起動します。  
EC2 フリート を作成するときは、JSON ファイルを使用して起動するインスタンスについての情報を指定します。  

```
aws ec2 create-fleet \
    --cli-input-json file://file_name.json
```
file\$1name.json の内容:  

```
{
    "LaunchTemplateConfigs": [
    {
        "LaunchTemplateSpecification": {
        "LaunchTemplateId": "lt-0e8c754449b27161c",
        "Version": "1"
        }
    }
    ],
    "TargetCapacitySpecification": {
        "TotalTargetCapacity": 2,
        "OnDemandTargetCapacity":1,
        "DefaultTargetCapacityType": "spot"
    }
}
```
出力:  

```
{
    "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE"
}
```
**例 4: 最低料金割り当て戦略を使用してスポットインスタンスを起動する EC2 フリートを作成するには**  
スポットインスタンスの配分戦略を指定しない場合、デフォルト配分戦略である `lowest-price` が使用されます。次の `create-fleet` の例では、`lowest-price` 割り当て戦略を使用して EC2 フリートを作成します。起動テンプレートをオーバーライドする 3 つの起動条件は、インスタンスタイプが異なりますが、加重容量とサブネットは同じです。合計ターゲット容量は 2 個のインスタンスで、デフォルト購入モデルは `spot` です。EC2 フリートは、最低価格の起動条件のインスタンスタイプを使用して 2 つのスポットインスタンスを起動します。  
EC2 フリート を作成するときは、JSON ファイルを使用して起動するインスタンスについての情報を指定します。  

```
aws ec2 create-fleet \
    --cli-input-json file://file_name.jsonContents of file_name.json::

{
    "LaunchTemplateConfigs": [
    {
        "LaunchTemplateSpecification": {
        "LaunchTemplateId": "lt-0e8c754449b27161c",
        "Version": "1"
        },
        "Overrides": [
            {
                "InstanceType": "c4.large",
                "WeightedCapacity": 1,
                "SubnetId": "subnet-a4f6c5d3"
            },
            {
                "InstanceType": "c3.large",
                "WeightedCapacity": 1,
                "SubnetId": "subnet-a4f6c5d3"
            },
            {
                "InstanceType": "c5.large",
                "WeightedCapacity": 1,
                "SubnetId": "subnet-a4f6c5d3"
            }
        ]
    }
    ],
    "TargetCapacitySpecification": {
        "TotalTargetCapacity": 2,
        "DefaultTargetCapacityType": "spot"
    }
}
```
出力:  

```
{
    "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-fleet.html)」を参照してください。

### `create-flow-logs`
<a name="ec2_CreateFlowLogs_cli_2_topic"></a>

次のコード例は、`create-flow-logs` を使用する方法を示しています。

**AWS CLI**  
**例 1: フローログを作成するには**  
次の `create-flow-logs` の例では、指定したネットワークインターフェイスについて拒否されたすべてのトラフィックをキャプチャするフローログを作成します。フローログは、指定された IAM ロールのアクセス許可を使用して CloudWatch Logs のロググループに配信されます。  

```
aws ec2 create-flow-logs \
    --resource-type NetworkInterface \
    --resource-ids eni-11223344556677889 \
    --traffic-type REJECT \
    --log-group-name my-flow-logs \
    --deliver-logs-permission-arn arn:aws:iam::123456789101:role/publishFlowLogs
```
出力:  

```
{
    "ClientToken": "so0eNA2uSHUNlHI0S2cJ305GuIX1CezaRdGtexample",
    "FlowLogIds": [
        "fl-12345678901234567"
    ],
    "Unsuccessful": []
}
```
詳細については、「Amazon VPC ユーザーガイド」の「[VPC フローログを使用した IP トラフィックのログ記録](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)」を参照してください。  
**例 2: カスタム形式でフローログを作成するには**  
次の `create-flow-logs` の例では、指定した VPC のすべてのトラフィックをキャプチャするフローログを作成し、そのフローログを Amazon S3 バケットに配信します。`--log-format` パラメータにより、フローログレコードのカスタム形式が指定されます。Windows でこのコマンドを実行するには、一重引用符 (') を二重引用符 (") に変更します。  

```
aws ec2 create-flow-logs \
    --resource-type VPC \
    --resource-ids vpc-00112233344556677 \
    --traffic-type ALL \
    --log-destination-type s3 \
    --log-destination arn:aws:s3:::flow-log-bucket/my-custom-flow-logs/ \
    --log-format '${version} ${vpc-id} ${subnet-id} ${instance-id} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${protocol} ${tcp-flags} ${type} ${pkt-srcaddr} ${pkt-dstaddr}'
```
詳細については、「Amazon VPC ユーザーガイド」の「[VPC フローログを使用した IP トラフィックのログ記録](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)」を参照してください。  
**例 3: 1 分間の最大集計間隔でフローログを作成するには**  
次の `create-flow-logs` の例では、指定した VPC のすべてのトラフィックをキャプチャするフローログを作成し、そのフローログを Amazon S3 バケットに配信します。`--max-aggregation-interval` パラメータは、最大集約間隔を 60 秒 (1 分) に指定します。  

```
aws ec2 create-flow-logs \
    --resource-type VPC \
    --resource-ids vpc-00112233344556677 \
    --traffic-type ALL \
    --log-destination-type s3 \
    --log-destination arn:aws:s3:::flow-log-bucket/my-custom-flow-logs/ \
    --max-aggregation-interval 60
```
詳細については、「Amazon VPC ユーザーガイド」の「[VPC フローログを使用した IP トラフィックのログ記録](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFlowLogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-flow-logs.html)」を参照してください。

### `create-fpga-image`
<a name="ec2_CreateFpgaImage_cli_2_topic"></a>

次のコード例は、`create-fpga-image` を使用する方法を示しています。

**AWS CLI**  
**Amazon FPGA イメージを作成するには**  
この例では、指定したバケット内の指定した tarball から AFI を作成します。  
コマンド:  

```
aws ec2 create-fpga-image --name my-afi --description test-afi --input-storage-location Bucket=my-fpga-bucket,Key=dcp/17_12_22-103226.Developer_CL.tar --logs-storage-location Bucket=my-fpga-bucket,Key=logs
```
出力:  

```
{
  "FpgaImageId": "afi-0d123e123bfc85abc",
  "FpgaImageGlobalId": "agfi-123cb27b5e84a0abc"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFpgaImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-fpga-image.html)」を参照してください。

### `create-image`
<a name="ec2_CreateImage_cli_2_topic"></a>

次のコード例は、`create-image` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EBS-backed インスタンスから AMI を作成するには**  
次の `create-image` の例では、指定したインスタンスから AMI を作成します。  

```
aws ec2 create-image \
    --instance-id i-1234567890abcdef0 \
    --name "My server" \
    --description "An AMI for my server"
```
出力:  

```
{
    "ImageId": "ami-abcdef01234567890"
}
```
AMI のブロックデバイスマッピングの指定の詳細については、「*Amazon EC2 ユーザーガイド*」の「[Specifying a block device mapping for an AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#create-ami-bdm)」を参照してください。  
**例 2: 再起動せずに Amazon EBS-backed インスタンスから AMI を作成するには**  
次の `create-image` の例では、AMI を作成し、--no-reboot パラメータを設定して、イメージの作成前にインスタンスが再起動されないようにします。  

```
aws ec2 create-image \
    --instance-id i-1234567890abcdef0 \
    --name "My server" \
    --no-reboot
```
出力:  

```
{
    "ImageId": "ami-abcdef01234567890"
}
```
AMI のブロックデバイスマッピングの指定の詳細については、「*Amazon EC2 ユーザーガイド*」の「[Specifying a block device mapping for an AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html#create-ami-bdm)」を参照してください。  
**例 3: 作成時に AMI とスナップショットにタグを付けるには**  
次の `create-image` の例では、AMI を作成し、AMI とスナップショットに同じタグ `cost-center=cc123` を付けます。  

```
aws ec2 create-image \
    --instance-id i-1234567890abcdef0 \
    --name "My server" \
    --tag-specifications "ResourceType=image,Tags=[{Key=cost-center,Value=cc123}]" "ResourceType=snapshot,Tags=[{Key=cost-center,Value=cc123}]"
```
出力:  

```
{
    "ImageId": "ami-abcdef01234567890"
}
```
作成時のリソースのタグ付けの詳細については、「*Amazon EC2 ユーザーガイド*」の「[Add tags on resource creation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#tag-on-create-examples)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-image.html)」を参照してください。

### `create-instance-connect-endpoint`
<a name="ec2_CreateInstanceConnectEndpoint_cli_2_topic"></a>

次のコード例は、`create-instance-connect-endpoint` を使用する方法を示しています。

**AWS CLI**  
**EC2 Instance Connect Endpoint を作成するには**  
次の `create-instance-connect-endpoint` の例では、指定したサブネットに EC2 Instance Connect エンドポイントを作成します。  

```
aws ec2 create-instance-connect-endpoint \
    --region us-east-1 \
    --subnet-id subnet-0123456789example
```
出力:  

```
{
    "VpcId": "vpc-0123abcd",
    "InstanceConnectEndpointArn": "arn:aws:ec2:us-east-1:111111111111:instance-connect-endpoint/eice-0123456789example",
    "AvailabilityZone": "us-east-1a",
    "NetworkInterfaceIds": [
        "eni-0123abcd"
    ],
    "PreserveClientIp": true,
    "Tags": [],
    "FipsDnsName": "eice-0123456789example.0123abcd.fips.ec2-instance-connect-endpoint.us-east-1.amazonaws.com",
    "StateMessage": "",
    "State": "create-complete",
    "DnsName": "eice-0123456789example.0123abcd.ec2-instance-connect-endpoint.us-east-1.amazonaws.com",
    "SubnetId": "subnet-0123abcd",
    "OwnerId": "111111111111",
    "SecurityGroupIds": [
        "sg-0123abcd"
    ],
    "InstanceConnectEndpointId": "eice-0123456789example",
    "CreatedAt": "2023-04-07T15:43:53.000Z"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[EC2 Instance Connect Endpoint の作成](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-ec2-instance-connect-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInstanceConnectEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-instance-connect-endpoint.html)」を参照してください。

### `create-instance-event-window`
<a name="ec2_CreateInstanceEventWindow_cli_2_topic"></a>

次のコード例は、`create-instance-event-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: 時間範囲を設定したイベントウィンドウを作成するには**  
次の `create-instance-event-window` の例では、時間範囲を持つイベントウィンドウを作成します。また、`cron-expression` パラメータを指定することはできません。  

```
aws ec2 create-instance-event-window \
    --region us-east-1 \
    --time-range StartWeekDay=monday,StartHour=2,EndWeekDay=wednesday,EndHour=8 \
    --tag-specifications "ResourceType=instance-event-window,Tags=[{Key=K1,Value=V1}]" \
    --name myEventWindowName
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "TimeRanges": [
            {
                "StartWeekDay": "monday",
                "StartHour": 2,
                "EndWeekDay": "wednesday",
                "EndHour": 8
            }
        ],
        "Name": "myEventWindowName",
        "State": "creating",
        "Tags": [
            {
                "Key": "K1",
                "Value": "V1"
            }
        ]
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 2: cron 式を指定したイベントウィンドウを作成するには**  
次の `create-instance-event-window` の例では、cron 式を持つイベントウィンドウを作成します。また、`time-range` パラメータを指定することはできません。  

```
aws ec2 create-instance-event-window \
    --region us-east-1 \
    --cron-expression "* 21-23 * * 2,3" \
    --tag-specifications "ResourceType=instance-event-window,Tags=[{Key=K1,Value=V1}]" \
    --name myEventWindowName
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "State": "creating",
        "Tags": [
            {
                "Key": "K1",
                "Value": "V1"
            }
        ]
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInstanceEventWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-instance-event-window.html)」を参照してください。

### `create-instance-export-task`
<a name="ec2_CreateInstanceExportTask_cli_2_topic"></a>

次のコード例は、`create-instance-export-task` を使用する方法を示しています。

**AWS CLI**  
**インスタンスをエクスポートするには**  
このコマンド例では、インスタンス i-1234567890abcdef0 を Amazon S3 バケット myexportbucket にエクスポートするタスクを作成します。  
コマンド:  

```
aws ec2 create-instance-export-task --description "RHEL5 instance" --instance-id i-1234567890abcdef0 --target-environment vmware --export-to-s3-task DiskImageFormat=vmdk,ContainerFormat=ova,S3Bucket=myexportbucket,S3Prefix=RHEL5
```
出力:  

```
{
    "ExportTask": {
        "State": "active",
        "InstanceExportDetails": {
            "InstanceId": "i-1234567890abcdef0",
            "TargetEnvironment": "vmware"
        },
        "ExportToS3Task": {
            "S3Bucket": "myexportbucket",
            "S3Key": "RHEL5export-i-fh8sjjsq.ova",
            "DiskImageFormat": "vmdk",
            "ContainerFormat": "ova"
        },
        "Description": "RHEL5 instance",
        "ExportTaskId": "export-i-fh8sjjsq"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInstanceExportTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-instance-export-task.html)」を参照してください。

### `create-internet-gateway`
<a name="ec2_CreateInternetGateway_cli_2_topic"></a>

次のコード例は、`create-internet-gateway` を使用する方法を示しています。

**AWS CLI**  
**インターネットゲートウェイを作成するには**  
次の `create-internet-gateway` の例では、タグ `Name=my-igw` を持つインターネットゲートウェイを作成します。  

```
aws ec2 create-internet-gateway \
    --tag-specifications ResourceType=internet-gateway,Tags=[{Key=Name,Value=my-igw}]
```
出力:  

```
{
    "InternetGateway": {
        "Attachments": [],
        "InternetGatewayId": "igw-0d0fb496b3994d755",
        "OwnerId": "123456789012",
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-igw"
            }
        ]
    }
}
```
詳細については、*Amazon VPC ユーザーガイド*の「[インターネットゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-internet-gateway.html)」を参照してください。

### `create-ipam-pool`
<a name="ec2_CreateIpamPool_cli_2_topic"></a>

次のコード例は、`create-ipam-pool` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールを作成するには**  
次の `create-ipam-pool` の例では、IPAM プールを作成します。  
(Linux):  

```
aws ec2 create-ipam-pool \
    --ipam-scope-id ipam-scope-02fc38cd4c48e7d38 \
    --address-family ipv4 \
    --auto-import \
    --allocation-min-netmask-length 16 \
    --allocation-max-netmask-length 26 \
    --allocation-default-netmask-length 24 \
    --allocation-resource-tags "Key=Environment,Value=Preprod" \
    --tag-specifications 'ResourceType=ipam-pool,Tags=[{Key=Name,Value="Preprod pool"}]'
```
(Windows):  

```
aws ec2 create-ipam-pool ^
    --ipam-scope-id ipam-scope-02fc38cd4c48e7d38 ^
    --address-family ipv4 ^
    --auto-import ^
    --allocation-min-netmask-length 16 ^
    --allocation-max-netmask-length 26 ^
    --allocation-default-netmask-length 24 ^
    --allocation-resource-tags "Key=Environment,Value=Preprod" ^
    --tag-specifications ResourceType=ipam-pool,Tags=[{Key=Name,Value="Preprod pool"}]
```
出力:  

```
{
    "IpamPool": {
        "OwnerId": "123456789012",
        "IpamPoolId": "ipam-pool-0533048da7d823723",
        "IpamPoolArn": "arn:aws:ec2::123456789012:ipam-pool/ipam-pool-0533048da7d823723",
        "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-02fc38cd4c48e7d38",
        "IpamScopeType": "private",
        "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
        "IpamRegion": "us-east-1",
        "Locale": "None",
        "PoolDepth": 1,
        "State": "create-in-progress",
        "AutoImport": true,
        "AddressFamily": "ipv4",
        "AllocationMinNetmaskLength": 16,
        "AllocationMaxNetmaskLength": 26,
        "AllocationDefaultNetmaskLength": 24,
        "AllocationResourceTags": [
            {
                "Key": "Environment",
                "Value": "Preprod"
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "Preprod pool"
            }
        ]
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Plan for IP address provisioning](https://docs.aws.amazon.com/vpc/latest/ipam/planning-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIpamPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-ipam-pool.html)」を参照してください。

### `create-ipam-resource-discovery`
<a name="ec2_CreateIpamResourceDiscovery_cli_2_topic"></a>

次のコード例は、`create-ipam-resource-discovery` を使用する方法を示しています。

**AWS CLI**  
**リソース検出を作成するには**  
この例では、委任された IPAM 管理者として、リソース検出を作成して別の AWS 組織の IPAM 管理者と共有し、他の組織の管理者が組織内のリソースの IP アドレスを管理およびモニタリングできるようにします。  
[重要]  
リソース検出を IPAM と正常に統合するためには特定の方法で設定する必要があるため、この例には `--region` と `--operating-regions` の両方のオプションが含まれています。どちらもオプションです。\$1 `--operating-regions` は、IPAM で検出するリソースがある地域と一致する必要があります。(コンプライアンス上の理由などで) IPAM で IP アドレスを管理したくないリージョンがある場合は、そのリージョンを含めないでください。\$1 `--region` は、関連付ける IPAM のホームリージョンと一致する必要があります。IPAM が作成されたのと同じリージョンでリソース検出を作成する必要があります。例えば、関連付ける IPAM が us-east-1 で作成された場合は、リクエストに `--region us-east-1` を含めます。`--region` と `--operating-regions` オプションは両方とも、指定しない場合はコマンドを実行しているリージョンにデフォルト設定されます。  
この例では、統合対象の IPAM の運用リージョンには、`us-west-1`、`us-west-2`、および `ap-south-1` が含まれます。リソース検出を作成する場合、IPAM では、`ap-south-1` ではなく、`us-west-2` と `us-west-1` にあるリソース IP アドレスを検出する必要があります。そのため、リクエストには `--operating-regions RegionName='us-west-1' RegionName='us-west-2'` のみを含めます。  
次の `create-ipam-resource-discovery` の例では、IPAM リソース検出を作成します。  

```
aws ec2 create-ipam-resource-discovery \
    --description 'Example-resource-discovery' \
    --tag-specifications 'ResourceType=ipam-resource-discovery,Tags=[{Key=cost-center,Value=cc123}]' \
    --operating-regions RegionName='us-west-1' RegionName='us-west-2' \
    --region us-east-1
```
出力:  

```
{
    "IpamResourceDiscovery":{
        "OwnerId": "149977607591",
        "IpamResourceDiscoveryId": "ipam-res-disco-0257046d8aa78b8bc",
        "IpamResourceDiscoveryArn": "arn:aws:ec2::149977607591:ipam-resource-discovery/ipam-res-disco-0257046d8aa78b8bc",
        "IpamResourceDiscoveryRegion": "us-east-1",
        "Description": "'Example-resource-discovery'",
        "OperatingRegions":[
            {"RegionName": "us-west-1"},
            {"RegionName": "us-west-2"},
            {"RegionName": "us-east-1"}
        ],
        "IsDefault": false,
        "State": "create-in-progress",
        "Tags": [
            {
                "Key": "cost-center",
                "Value": "cc123"
            }
        ]
}
```
リソース検出を作成後、それを別の IPAM の委任された管理者と共有する必要が出てくる場合があります。[create-resource-share](https://docs.aws.amazon.com/cli/latest/reference/ram/create-resource-share.html) を使用すればそれに対応できます。詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Integrate IPAM with accounts outside of your organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIpamResourceDiscovery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-ipam-resource-discovery.html)」を参照してください。

### `create-ipam-scope`
<a name="ec2_CreateIpamScope_cli_2_topic"></a>

次のコード例は、`create-ipam-scope` を使用する方法を示しています。

**AWS CLI**  
**IPAM スコープを作成するには**  
次の `create-ipam-scope` の例では、IPAM スコープを作成します。  
(Linux):  

```
aws ec2 create-ipam-scope \
    --ipam-id ipam-08440e7a3acde3908 \
    --description "Example description" \
    --tag-specifications 'ResourceType=ipam-scope,Tags=[{Key=Name,Value="Example name value"}]'
```
(Windows):  

```
aws ec2 create-ipam-scope ^
    --ipam-id ipam-08440e7a3acde3908 ^
    --description "Example description" ^
    --tag-specifications ResourceType=ipam-scope,Tags=[{Key=Name,Value="Example name value"}]
```
出力:  

```
{
    "IpamScope": {
        "OwnerId": "123456789012",
        "IpamScopeId": "ipam-scope-01c1ebab2b63bd7e4",
        "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-01c1ebab2b63bd7e4",
        "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
        "IpamRegion": "us-east-1",
        "IpamScopeType": "private",
        "IsDefault": false,
        "Description": "Example description",
        "PoolCount": 0,
        "State": "create-in-progress",
        "Tags": [
            {
                "Key": "Name",
                "Value": "Example name value"
            }
        ]
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Create additional scopes](https://docs.aws.amazon.com/vpc/latest/ipam/add-scope-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIpamScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-ipam-scope.html)」を参照してください。

### `create-ipam`
<a name="ec2_CreateIpam_cli_2_topic"></a>

次のコード例は、`create-ipam` を使用する方法を示しています。

**AWS CLI**  
**IPAM を作成するには**  
次の `create-ipam` の例では、IPAM を作成します。  
(Linux):  

```
aws ec2 create-ipam \
    --description "Example description" \
    --operating-regions "RegionName=us-east-2" "RegionName=us-west-1" \
    --tag-specifications 'ResourceType=ipam,Tags=[{Key=Name,Value=ExampleIPAM}]'
```
(Windows):  

```
aws ec2 create-ipam ^
    --description "Example description" ^
    --operating-regions "RegionName=us-east-2" "RegionName=us-west-1" ^
    --tag-specifications ResourceType=ipam,Tags=[{Key=Name,Value=ExampleIPAM}]
```
出力:  

```
{
    "Ipam": {
        "OwnerId": "123456789012",
        "IpamId": "ipam-036486dfa6af58ee0",
        "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-036486dfa6af58ee0",
        "IpamRegion": "us-east-1",
        "PublicDefaultScopeId": "ipam-scope-071b8042b0195c183",
        "PrivateDefaultScopeId": "ipam-scope-0807405dece705a30",
        "ScopeCount": 2,
        "OperatingRegions": [
            {
                "RegionName": "us-east-2"
            },
            {
                "RegionName": "us-west-1"
            },
            {
                "RegionName": "us-east-1"
            }
        ],
        "State": "create-in-progress",
        "Tags": [
            {
                "Key": "Name",
                "Value": "ExampleIPAM"
            }
        ]
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Create an IPAM](https://docs.aws.amazon.com/vpc/latest/ipam/create-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIpam](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-ipam.html)」を参照してください。

### `create-key-pair`
<a name="ec2_CreateKeyPair_cli_2_topic"></a>

次のコード例は、`create-key-pair` を使用する方法を示しています。

**AWS CLI**  
**キーペアを作成するには**  
この例では、`MyKeyPair` という名前のキーペアが作成されます。  
コマンド:  

```
aws ec2 create-key-pair --key-name MyKeyPair
```
出力は ASCII バージョンのプライベートキーとキーフィンガープリントです。キーはファイルに保存する必要があります。  
詳細については、「*AWS コマンドラインインターフェイスユーザーガイド*」でキーペアの使用方法を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-key-pair.html)」を参照してください。

### `create-launch-template-version`
<a name="ec2_CreateLaunchTemplateVersion_cli_2_topic"></a>

次のコード例は、`create-launch-template-version` を使用する方法を示しています。

**AWS CLI**  
**起動テンプレートのバージョンを作成するには**  
この例では、起動テンプレートのバージョン 1 に基づいて新しいバージョンを作成し、異なる AMI ID を指定します。  
コマンド:  

```
aws ec2 create-launch-template-version --launch-template-id lt-0abcd290751193123 --version-description WebVersion2 --source-version 1 --launch-template-data '{"ImageId":"ami-c998b6b2"}'
```
出力:  

```
{
  "LaunchTemplateVersion": {
      "VersionDescription": "WebVersion2",
      "LaunchTemplateId": "lt-0abcd290751193123",
      "LaunchTemplateName": "WebServers",
      "VersionNumber": 2,
      "CreatedBy": "arn:aws:iam::123456789012:root",
      "LaunchTemplateData": {
          "ImageId": "ami-c998b6b2",
          "InstanceType": "t2.micro",
          "NetworkInterfaces": [
              {
                  "Ipv6Addresses": [
                      {
                          "Ipv6Address": "2001:db8:1234:1a00::123"
                      }
                  ],
                  "DeviceIndex": 0,
                  "SubnetId": "subnet-7b16de0c",
                  "AssociatePublicIpAddress": true
              }
          ]
      },
      "DefaultVersion": false,
      "CreateTime": "2017-12-01T13:35:46.000Z"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLaunchTemplateVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template-version.html)」を参照してください。

### `create-launch-template`
<a name="ec2_CreateLaunchTemplate_cli_2_topic"></a>

次のコード例は、`create-launch-template` を使用する方法を示しています。

**AWS CLI**  
**例 1: 起動テンプレートを作成するには**  
次の `create-launch-template` の例では、インスタンスを起動し、インスタンスにパブリック IP アドレスと IPv6 アドレスを割り当て、インスタンスのタグを作成するサブネットを指定する起動テンプレートを作成しています。  

```
aws ec2 create-launch-template \
    --launch-template-name TemplateForWebServer \
    --version-description WebVersion1 \
    --launch-template-data '{"NetworkInterfaces":[{"AssociatePublicIpAddress":true,"DeviceIndex":0,"Ipv6AddressCount":1,"SubnetId":"subnet-7b16de0c"}],"ImageId":"ami-8c1be5f6","InstanceType":"t2.small","TagSpecifications":[{"ResourceType":"instance","Tags":[{"Key":"purpose","Value":"webserver"}]}]}'
```
出力:  

```
{
    "LaunchTemplate": {
        "LatestVersionNumber": 1,
        "LaunchTemplateId": "lt-01238c059e3466abc",
        "LaunchTemplateName": "TemplateForWebServer",
        "DefaultVersionNumber": 1,
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "CreateTime": "2019-01-27T09:13:24.000Z"
    }
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「起動テンプレートからのインスタンスの起動」を参照してください。JSON 形式のパラメータで引用する方法については、「*AWS コマンドラインインターフェイスユーザーガイド*」の「文字列の引用」を参照してください。  
**例 2: Amazon EC2 Auto Scaling の起動テンプレートを作成するには**  
次の `create-launch-template` の例では、複数のタグとブロックデバイスマッピングを使ってインスタンス起動時に追加の EBS ボリュームを指定する起動テンプレートを作成しています。Auto Scaling グループがインスタンスを起動する VPC のセキュリティグループに対応する `Groups` の値を指定します。Auto Scaling グループのプロパティとして VPC とサブネットを指定します。  

```
aws ec2 create-launch-template \
    --launch-template-name TemplateForAutoScaling \
    --version-description AutoScalingVersion1 \
    --launch-template-data '{"NetworkInterfaces":[{"DeviceIndex":0,"AssociatePublicIpAddress":true,"Groups":["sg-7c227019,sg-903004f8"],"DeleteOnTermination":true}],"ImageId":"ami-b42209de","InstanceType":"m4.large","TagSpecifications":[{"ResourceType":"instance","Tags":[{"Key":"environment","Value":"production"},{"Key":"purpose","Value":"webserver"}]},{"ResourceType":"volume","Tags":[{"Key":"environment","Value":"production"},{"Key":"cost-center","Value":"cc123"}]}],"BlockDeviceMappings":[{"DeviceName":"/dev/sda1","Ebs":{"VolumeSize":100}}]}' --region us-east-1
```
出力:  

```
{
    "LaunchTemplate": {
        "LatestVersionNumber": 1,
        "LaunchTemplateId": "lt-0123c79c33a54e0abc",
        "LaunchTemplateName": "TemplateForAutoScaling",
        "DefaultVersionNumber": 1,
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "CreateTime": "2019-04-30T18:16:06.000Z"
    }
}
```
詳細については、「*Amazon EC2 Auto Scaling ユーザーガイド*」の「Auto Scaling グループの起動テンプレートを作成する」を参照してください。JSON 形式のパラメータで引用する方法については、「*AWS コマンドラインインターフェイスユーザーガイド*」の「文字列の引用」を参照してください。  
**例 3: EBS ボリュームの暗号化を指定する起動テンプレートを作成するには**  
次の `create-launch-template` の例では、暗号化されていないスナップショットから作成された暗号化された EBS ボリュームを含む起動テンプレートを作成しています。また、作成時にボリュームにタグ付けしています。暗号化がデフォルトで無効になっている場合、次の例のように `"Encrypted"` オプションを指定する必要があります。`"KmsKeyId"` オプションを使用してカスタマー管理の CMK を指定する場合は、デフォルトで暗号化が有効になっていても `"Encrypted"` オプションを指定する必要があります。  

```
aws ec2 create-launch-template \
  --launch-template-name TemplateForEncryption \
  --launch-template-data file://config.json
```
`config.json` の内容:  

```
{
    "BlockDeviceMappings":[
        {
            "DeviceName":"/dev/sda1",
            "Ebs":{
                "VolumeType":"gp2",
                "DeleteOnTermination":true,
                "SnapshotId":"snap-066877671789bd71b",
                "Encrypted":true,
                "KmsKeyId":"arn:aws:kms:us-east-1:012345678910:key/abcd1234-a123-456a-a12b-a123b4cd56ef"
            }
        }
    ],
    "ImageId":"ami-00068cd7555f543d5",
    "InstanceType":"c5.large",
    "TagSpecifications":[
        {
            "ResourceType":"volume",
            "Tags":[
                {
                    "Key":"encrypted",
                    "Value":"yes"
                }
            ]
        }
    ]
}
```
出力:  

```
{
    "LaunchTemplate": {
        "LatestVersionNumber": 1,
        "LaunchTemplateId": "lt-0d5bd51bcf8530abc",
        "LaunchTemplateName": "TemplateForEncryption",
        "DefaultVersionNumber": 1,
        "CreatedBy": "arn:aws:iam::123456789012:user/Bob",
        "CreateTime": "2020-01-07T19:08:36.000Z"
    }
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「スナップショットからの Amazon EBS ボリュームの復元」と「デフォルトでの暗号化」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateLaunchTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-launch-template.html)」を参照してください。

### `create-local-gateway-route-table-virtual-interface-group-association`
<a name="ec2_CreateLocalGatewayRouteTableVirtualInterfaceGroupAssociation_cli_2_topic"></a>

次のコード例は、`create-local-gateway-route-table-virtual-interface-group-association` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイのルートテーブルを仮想インターフェイス (VIF) グループに関連付けるには**  
次の `create-local-gateway-route-table-virtual-interface-group-association` の例では、指定したローカルゲートウェイのルートテーブルと VIF グループ間の関連付けを作成します。  

```
aws ec2 create-local-gateway-route-table-virtual-interface-group-association \
    --local-gateway-route-table-id lgw-rtb-exampleidabcd1234 \
    --local-gateway-virtual-interface-group-id lgw-vif-grp-exampleid0123abcd
```
出力:  

```
{
    "LocalGatewayRouteTableVirtualInterfaceGroupAssociation": {
        "LocalGatewayRouteTableVirtualInterfaceGroupAssociationId": "lgw-vif-grp-assoc-exampleid12345678",
        "LocalGatewayVirtualInterfaceGroupId": "lgw-vif-grp-exampleid0123abcd",
        "LocalGatewayId": "lgw-exampleid11223344",
        "LocalGatewayRouteTableId": "lgw-rtb-exampleidabcd1234",
        "LocalGatewayRouteTableArn": "arn:aws:ec2:us-west-2:111122223333:local-gateway-route-table/lgw-rtb-exampleidabcd1234",
        "OwnerId": "111122223333",
        "State": "pending",
        "Tags": []
    }
}
```
詳細については、「*AWS Outposts ユーザーガイド*」の「[VIF group associations](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#vif-group-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLocalGatewayRouteTableVirtualInterfaceGroupAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-local-gateway-route-table-virtual-interface-group-association.html)」を参照してください。

### `create-local-gateway-route-table-vpc-association`
<a name="ec2_CreateLocalGatewayRouteTableVpcAssociation_cli_2_topic"></a>

次のコード例は、`create-local-gateway-route-table-vpc-association` を使用する方法を示しています。

**AWS CLI**  
**VPC をルートテーブルに関連付けるには**  
次の `create-local-gateway-route-table-vpc-association` の例では、指定した VPC を指定したローカルゲートウェイのルートテーブルに関連付けます。  

```
aws ec2 create-local-gateway-route-table-vpc-association \
    --local-gateway-route-table-id lgw-rtb-059615ef7dEXAMPLE \
    --vpc-id vpc-07ef66ac71EXAMPLE
```
出力:  

```
{
    "LocalGatewayRouteTableVpcAssociation": {
        "LocalGatewayRouteTableVpcAssociationId": "lgw-vpc-assoc-0ee765bcc8EXAMPLE",
        "LocalGatewayRouteTableId": "lgw-rtb-059615ef7dEXAMPLE",
        "LocalGatewayId": "lgw-09b493aa7cEXAMPLE",
        "VpcId": "vpc-07ef66ac71EXAMPLE",
        "State": "associated"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLocalGatewayRouteTableVpcAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-local-gateway-route-table-vpc-association.html)」を参照してください。

### `create-local-gateway-route-table`
<a name="ec2_CreateLocalGatewayRouteTable_cli_2_topic"></a>

次のコード例は、`create-local-gateway-route-table` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイのルートテーブルのルートを作成するには**  
次の `create-local-gateway-route-table` の例では、直接 VPC ルーティングモードでローカルゲートウェイのルートテーブルを作成します。  

```
aws ec2 create-local-gateway-route-table \
    --local-gateway-id lgw-1a2b3c4d5e6f7g8h9 \
    --mode direct-vpc-routing
```
出力:  

```
{
    "LocalGatewayRouteTable": {
        "LocalGatewayRouteTableId": "lgw-rtb-abcdefg1234567890",
        "LocalGatewayRouteTableArn": "arn:aws:ec2:us-west-2:111122223333:local-gateway-route-table/lgw-rtb-abcdefg1234567890",
        "LocalGatewayId": "lgw-1a2b3c4d5e6f7g8h9",
        "OutpostArn": "arn:aws:outposts:us-west-2:111122223333:outpost/op-021345abcdef67890",
        "OwnerId": "111122223333",
        "State": "pending",
        "Tags": [],
        "Mode": "direct-vpc-routing"
    }
}
```
詳細については、「AWS Outposts ユーザーガイド」の「[ローカルゲートウェイルートテーブル](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLocalGatewayRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-local-gateway-route-table.html)」を参照してください。

### `create-local-gateway-route`
<a name="ec2_CreateLocalGatewayRoute_cli_2_topic"></a>

次のコード例は、`create-local-gateway-route` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイのルートテーブルの静的ルートを作成するには**  
次の `create-local-gateway-route` の例では、指定したローカルゲートウェイのルートテーブルに指定したルートを作成します。  

```
aws ec2 create-local-gateway-route \
    --destination-cidr-block 0.0.0.0/0 \
    --local-gateway-route-table-id lgw-rtb-059615ef7dEXAMPLE
```
出力:  

```
{
    "Route": {
        "DestinationCidrBlock": "0.0.0.0/0",
        "LocalGatewayVirtualInterfaceGroupId": "lgw-vif-grp-07145b276bEXAMPLE",
        "Type": "static",
        "State": "deleted",
        "LocalGatewayRouteTableId": "lgw-rtb-059615ef7dEXAMPLE"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLocalGatewayRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-local-gateway-route.html)」を参照してください。

### `create-managed-prefix-list`
<a name="ec2_CreateManagedPrefixList_cli_2_topic"></a>

次のコード例は、`create-managed-prefix-list` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストを作成する**  
次の `create-managed-prefix-list` の例では、最大エントリ数が 10 個の IPv4 プレフィックスリストを作成し、そのプレフィックスリストに 2 つのエントリを作成します。  

```
aws ec2 create-managed-prefix-list \
    --address-family IPv4 \
    --max-entries 10 \
    --entries Cidr=10.0.0.0/16,Description=vpc-a Cidr=10.2.0.0/16,Description=vpc-b \
    --prefix-list-name vpc-cidrs
```
出力:  

```
{
    "PrefixList": {
        "PrefixListId": "pl-0123456abcabcabc1",
        "AddressFamily": "IPv4",
        "State": "create-in-progress",
        "PrefixListArn": "arn:aws:ec2:us-west-2:123456789012:prefix-list/pl-0123456abcabcabc1",
        "PrefixListName": "vpc-cidrs",
        "MaxEntries": 10,
        "Version": 1,
        "Tags": [],
        "OwnerId": "123456789012"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Managed prefix lists](https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateManagedPrefixList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-managed-prefix-list.html)」を参照してください。

### `create-nat-gateway`
<a name="ec2_CreateNatGateway_cli_2_topic"></a>

次のコード例は、`create-nat-gateway` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリック NAT ゲートウェイを作成するには**  
次の `create-nat-gateway` の例では、指定したサブネットにパブリック NAT ゲートウェイを作成し、Elastic IP アドレスを指定した割り当て ID に関連付けます。パブリック NAT ゲートウェイを作成する場合、Elastic IP アドレスを関連付ける必要があります。  

```
aws ec2 create-nat-gateway \
    --subnet-id subnet-0250c25a1fEXAMPLE \
    --allocation-id eipalloc-09ad461b0dEXAMPLE
```
出力:  

```
{
    "NatGateway": {
        "CreateTime": "2021-12-01T22:22:38.000Z",
        "NatGatewayAddresses": [
            {
                "AllocationId": "eipalloc-09ad461b0dEXAMPLE"
            }
        ],
        "NatGatewayId": "nat-0c61bf8a12EXAMPLE",
        "State": "pending",
        "SubnetId": "subnet-0250c25a1fEXAMPLE",
        "VpcId": "vpc-0a60eb65b4EXAMPLE",
        "ConnectivityType": "public"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[NAT ゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)」を参照してください。  
**例 2: プライベート NAT ゲートウェイを作成するには**  
次の `create-nat-gateway` の例では、指定したサブネットにプライベート NAT ゲートウェイを作成します。プライベート NAT ゲートウェイには、関連付けられた Elastic IP アドレスがありません。  

```
aws ec2 create-nat-gateway \
    --subnet-id subnet-0250c25a1fEXAMPLE \
    --connectivity-type private
```
出力:  

```
{
    "NatGateway": {
        "CreateTime": "2021-12-01T22:26:00.000Z",
        "NatGatewayAddresses": [
            {}
        ],
        "NatGatewayId": "nat-011b568379EXAMPLE",
        "State": "pending",
        "SubnetId": "subnet-0250c25a1fEXAMPLE",
        "VpcId": "vpc-0a60eb65b4EXAMPLE",
        "ConnectivityType": "private"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[NAT ゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNatGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-nat-gateway.html)」を参照してください。

### `create-network-acl-entry`
<a name="ec2_CreateNetworkAclEntry_cli_2_topic"></a>

次のコード例は、`create-network-acl-entry` を使用する方法を示しています。

**AWS CLI**  
**ネットワーク ACL エントリを作成するには**  
この例では、指定したネットワーク ACL のエントリを作成します。このルールは、UDP ポート 53 (DNS) 上の任意の IPv4 アドレス (0.0.0.0/0) から任意の関連付けられたサブネットへの受信トラフィックを許可します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 create-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 100 --protocol udp --port-range From=53,To=53 --cidr-block 0.0.0.0/0 --rule-action allow
```
この例では、TCP ポート 80 (HTTP) 上の任意の IPv6 アドレス (::/0) からの受信トラフィックを許可する、指定したネットワーク ACL のルールを作成します。  
コマンド:  

```
aws ec2 create-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 120 --protocol tcp --port-range From=80,To=80 --ipv6-cidr-block ::/0 --rule-action allow
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNetworkAclEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-acl-entry.html)」を参照してください。

### `create-network-acl`
<a name="ec2_CreateNetworkAcl_cli_2_topic"></a>

次のコード例は、`create-network-acl` を使用する方法を示しています。

**AWS CLI**  
**ネットワーク ACL を作成するには**  
この例では、指定した VPC に対してネットワーク ACL を作成します。  
コマンド:  

```
aws ec2 create-network-acl --vpc-id vpc-a01106c2
```
出力:  

```
{
    "NetworkAcl": {
        "Associations": [],
        "NetworkAclId": "acl-5fb85d36",
        "VpcId": "vpc-a01106c2",
        "Tags": [],
        "Entries": [
            {
                "CidrBlock": "0.0.0.0/0",
                "RuleNumber": 32767,
                "Protocol": "-1",
                "Egress": true,
                "RuleAction": "deny"
            },
            {
                "CidrBlock": "0.0.0.0/0",
                "RuleNumber": 32767,
                "Protocol": "-1",
                "Egress": false,
                "RuleAction": "deny"
            }
        ],
        "IsDefault": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNetworkAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-acl.html)」を参照してください。

### `create-network-insights-access-scope`
<a name="ec2_CreateNetworkInsightsAccessScope_cli_2_topic"></a>

次のコード例は、`create-network-insights-access-scope` を使用する方法を示しています。

**AWS CLI**  
**Network Access Scope を作成するには**  
次の `create-network-insights-access-scope` の例では、Network Access Scope を作成します。  

```
aws ec2 create-network-insights-access-scope \
    --cli-input-json file://access-scope-file.json
```
`access-scope-file.json` の内容:  

```
{
    "MatchPaths": [
        {
            "Source": {
                "ResourceStatement": {
                    "Resources": [
                        "vpc-abcd12e3"
                    ]
                }
            }
         }
    ],
    "ExcludePaths": [
        {
            "Source": {
                "ResourceStatement": {
                    "ResourceTypes": [
                        "AWS::EC2::InternetGateway"
                    ]
                }
            }
        }
    ]
}
```
出力:  

```
{
    "NetworkInsightsAccessScope": {
        "NetworkInsightsAccessScopeId": "nis-123456789abc01234",
        "NetworkInsightsAccessScopeArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-access-scope/nis-123456789abc01234",
        "CreatedDate": "2022-01-25T19:20:28.796000+00:00",
        "UpdatedDate": "2022-01-25T19:20:28.797000+00:00"
    },
    "NetworkInsightsAccessScopeContent": {
        "NetworkInsightsAccessScopeId": "nis-123456789abc01234",
        "MatchPaths": [
            {
                "Source": {
                    "ResourceStatement": {
                        "Resources": [
                            "vpc-abcd12e3"
                        ]
                    }
                }
            }
        ],
        "ExcludePaths": [
            {
                "Source": {
                    "ResourceStatement": {
                        "ResourceTypes": [
                            "AWS::EC2::InternetGateway"
                        ]
                    }
                }
            }
        ]
    }
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNetworkInsightsAccessScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-insights-access-scope.html)」を参照してください。

### `create-network-insights-path`
<a name="ec2_CreateNetworkInsightsPath_cli_2_topic"></a>

次のコード例は、`create-network-insights-path` を使用する方法を示しています。

**AWS CLI**  
**パスを作成するには**  
次の `create-network-insights-path` の例では、パスを作成します。送信元は指定されたインターネットゲートウェイで、送信先は指定された EC2 インスタンスです。指定されたプロトコルとポートを使用して送信先に到達できるかどうかを確認するには、`start-network-insights-analysis` コマンドを使用してパスを分析します。  

```
aws ec2 create-network-insights-path \
    --source igw-0797cccdc9d73b0e5 \
    --destination i-0495d385ad28331c7 \
    --destination-port 22 \
    --protocol TCP
```
出力:  

```
{
    "NetworkInsightsPaths": {
        "NetworkInsightsPathId": "nip-0b26f224f1d131fa8",
        "NetworkInsightsPathArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-path/nip-0b26f224f1d131fa8",
        "CreatedDate": "2021-01-20T22:43:46.933Z",
        "Source": "igw-0797cccdc9d73b0e5",
        "Destination": "i-0495d385ad28331c7",
        "Protocol": "tcp"
    }
}
```
詳細については、*「Reachability Analyzer* [Guide」の「Getting started using the AWS CLI](https://docs.aws.amazon.com/vpc/latest/reachability/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNetworkInsightsPath](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-insights-path.html)」を参照してください。

### `create-network-interface-permission`
<a name="ec2_CreateNetworkInterfacePermission_cli_2_topic"></a>

次のコード例は、`create-network-interface-permission` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイス権限を作成するには**  
この例では、インスタンスにネットワークインターフェイス `eni-1a2b3c4d` をアタッチするためにアカウント `123456789012` へのアクセス許可を付与します。  
コマンド:  

```
aws ec2 create-network-interface-permission --network-interface-id eni-1a2b3c4d --aws-account-id 123456789012 --permission INSTANCE-ATTACH
```
出力:  

```
{
  "InterfacePermission": {
      "PermissionState": {
          "State": "GRANTED"
      },
      "NetworkInterfacePermissionId": "eni-perm-06fd19020ede149ea",
      "NetworkInterfaceId": "eni-1a2b3c4d",
      "Permission": "INSTANCE-ATTACH",
      "AwsAccountId": "123456789012"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNetworkInterfacePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-interface-permission.html)」を参照してください。

### `create-network-interface`
<a name="ec2_CreateNetworkInterface_cli_2_topic"></a>

次のコード例は、`create-network-interface` を使用する方法を示しています。

**AWS CLI**  
**例 1: ネットワークインターフェイスの IPv4 アドレスを指定するには**  
次の `create-network-interface` の例では、指定したプライマリ IPv4 アドレスを持つ指定したサブネット用にネットワークインターフェイスを作成します。  

```
aws ec2 create-network-interface \
    --subnet-id subnet-00a24d0d67acf6333 \
    --description "my network interface" \
    --groups sg-09dfba7ed20cda78b \
    --private-ip-address 10.0.8.17
```
出力:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "Description": "my network interface",
        "Groups": [
            {
                "GroupName": "my-security-group",
                "GroupId": "sg-09dfba7ed20cda78b"
            }
        ],
        "InterfaceType": "interface",
        "Ipv6Addresses": [],
        "MacAddress": "06:6a:0f:9a:49:37",
        "NetworkInterfaceId": "eni-0492b355f0cf3b3f8",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-18.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.17",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-17.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.17"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b"
    }
}
```
**例 2: IPv4 アドレスと IPv6 アドレスを持つネットワークインターフェイスを作成するには**  
次の `create-network-interface` の例では、Amazon EC2 で選択されている IPv4 アドレスと IPv6 アドレスを使用して、指定したサブネット用にネットワークインターフェイスを作成します。  

```
aws ec2 create-network-interface \
    --subnet-id subnet-00a24d0d67acf6333 \
    --description "my dual stack network interface" \
    --ipv6-address-count 1 \
    --groups sg-09dfba7ed20cda78b
```
出力:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "Description": "my dual stack network interface",
        "Groups": [
            {
                "GroupName": "my-security-group",
                "GroupId": "sg-09dfba7ed20cda78b"
            }
        ],
        "InterfaceType": "interface",
        "Ipv6Addresses": [
            {
                "Ipv6Address": "2600:1f13:cfe:3650:a1dc:237c:393a:4ba7",
                "IsPrimaryIpv6": false
            }
        ],
        "MacAddress": "06:b8:68:d2:b2:2d",
        "NetworkInterfaceId": "eni-05da417453f9a84bf",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-18.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.18",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-18.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.18"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b",
        "Ipv6Address": "2600:1f13:cfe:3650:a1dc:237c:393a:4ba7"
    }
}
```
**例 3: 接続追跡設定オプションを使用してネットワークインターフェイスを作成するには**  
次の `create-network-interface` の例では、ネットワークインターフェイスを作成し、アイドル接続追跡タイムアウトを設定します。  

```
aws ec2 create-network-interface \
    --subnet-id subnet-00a24d0d67acf6333 \
    --groups sg-02e57dbcfe0331c1b \
    --connection-tracking-specification TcpEstablishedTimeout=86400,UdpTimeout=60
```
出力:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "ConnectionTrackingConfiguration": {
            "TcpEstablishedTimeout": 86400,
            "UdpTimeout": 60
        },
        "Description": "",
        "Groups": [
            {
                "GroupName": "my-security-group",
                "GroupId": "sg-02e57dbcfe0331c1b"
            }
        ],
        "InterfaceType": "interface",
        "Ipv6Addresses": [],
        "MacAddress": "06:4c:53:de:6d:91",
        "NetworkInterfaceId": "eni-0c133586e08903d0b",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-94.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.94",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-94.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.94"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b"
    }
}
```
**例 4: Elastic Fabric Adapter を作成するには**  
次の `create-network-interface` の例では、EFA を作成します。  

```
aws ec2 create-network-interface \
    --interface-type efa \
    --subnet-id subnet-00a24d0d67acf6333 \
    --description "my efa" \
    --groups sg-02e57dbcfe0331c1b
```
出力:  

```
{
    "NetworkInterface": {
        "AvailabilityZone": "us-west-2a",
        "Description": "my efa",
        "Groups": [
            {
                "GroupName": "my-efa-sg",
                "GroupId": "sg-02e57dbcfe0331c1b"
            }
        ],
        "InterfaceType": "efa",
        "Ipv6Addresses": [],
        "MacAddress": "06:d7:a4:f7:4d:57",
        "NetworkInterfaceId": "eni-034acc2885e862b65",
        "OwnerId": "123456789012",
        "PrivateDnsName": "ip-10-0-8-180.us-west-2.compute.internal",
        "PrivateIpAddress": "10.0.8.180",
        "PrivateIpAddresses": [
            {
                "Primary": true,
                "PrivateDnsName": "ip-10-0-8-180.us-west-2.compute.internal",
                "PrivateIpAddress": "10.0.8.180"
            }
        ],
        "RequesterId": "AIDA4Z3Y7GSXTMEXAMPLE",
        "RequesterManaged": false,
        "SourceDestCheck": true,
        "Status": "pending",
        "SubnetId": "subnet-00a24d0d67acf6333",
        "TagSet": [],
        "VpcId": "vpc-02723a0feeeb9d57b"
    }
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Elastic Network Interface](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-interface.html)」を参照してください。

### `create-placement-group`
<a name="ec2_CreatePlacementGroup_cli_2_topic"></a>

次のコード例は、`create-placement-group` を使用する方法を示しています。

**AWS CLI**  
**プレイスメントグループを作成するには**  
このコマンド例では、指定された名前のプレイスメントグループを作成します。  
コマンド:  

```
aws ec2 create-placement-group --group-name my-cluster --strategy cluster
```
**パーティションプレイスメントグループを作成するには**  
このコマンド例では、`HDFS-Group-A` という名前のパーティションプレイスメントグループと 5 つのパーティションを作成します。  
コマンド:  

```
aws ec2 create-placement-group --group-name HDFS-Group-A --strategy partition --partition-count 5
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePlacementGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-placement-group.html)」を参照してください。

### `create-replace-root-volume-task`
<a name="ec2_CreateReplaceRootVolumeTask_cli_2_topic"></a>

次のコード例は、`create-replace-root-volume-task` を使用する方法を示しています。

**AWS CLI**  
**例 1: ルートボリュームを初期起動状態に復元するには**  
次の `create-replace-root-volume-task` の例では、インスタンス i-0123456789abcdefa のルートボリュームを初期起動状態に復元します。  

```
aws ec2 create-replace-root-volume-task \
    --instance-id i-0123456789abcdefa
```
出力:  

```
{
    "ReplaceRootVolumeTask":
    {
        "InstanceId": "i-0123456789abcdefa",
            "ReplaceRootVolumeTaskId": "replacevol-0111122223333abcd",
            "TaskState": "pending",
            "StartTime": "2022-03-14T15:06:38Z",
            "Tags": []
    }
}
```
**例 2: ルートボリュームを特定のスナップショットに復元するには**  
次の `create-replace-root-volume-task` の例では、インスタンス i-0123456789abcdefa のルートボリュームをスナップショット snap-0abcdef1234567890 に復元します。  

```
aws ec2 create-replace-root-volume-task \
    --instance-id i-0123456789abcdefa \
    --snapshot-id  snap-0abcdef1234567890
```
出力:  

```
{
    "ReplaceRootVolumeTask":
    {
        "InstanceId": "i-0123456789abcdefa",
        "ReplaceRootVolumeTaskId": "replacevol-0555566667777abcd",
        "TaskState": "pending",
        "StartTime": "2022-03-14T15:16:28Z",
        "Tags": []
    }
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[ルートボリュームを置き換える](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/replace-root.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReplaceRootVolumeTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-replace-root-volume-task.html)」を参照してください。

### `create-reserved-instances-listing`
<a name="ec2_CreateReservedInstancesListing_cli_2_topic"></a>

次のコード例は、`create-reserved-instances-listing` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスマーケットプレイス内のリザーブドインスタンスを一覧表示するには**  
次の `create-reserved-instances-listing` の例では、指定したリザーブドインスタンスのリストをリザーブドインスタンスマーケットプレイスに作成します。  

```
aws ec2 create-reserved-instances-listing \
    --reserved-instances-id 5ec28771-05ff-4b9b-aa31-9e57dexample \
    --instance-count 3 \
    --price-schedules CurrencyCode=USD,Price=25.50 \
    --client-token 550e8400-e29b-41d4-a716-446655440000
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReservedInstancesListing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-reserved-instances-listing.html)」を参照してください。

### `create-restore-image-task`
<a name="ec2_CreateRestoreImageTask_cli_2_topic"></a>

次のコード例は、`create-restore-image-task` を使用する方法を示しています。

**AWS CLI**  
**S3 バケットから AMI を復元するには**  
次の `create-restore-image-task` の例では、S3 バケットから AMI を復元します。`describe-store-image-tasks` 出力からの `S3ObjectKey `` and ``Bucket` の値を使用し、AMI のオブジェクトキーと AMI のコピー先である S3 バケットの名前を指定して、復元された AMI の名前を指定します。このアカウントの名前は、リージョン内の AMI に対して一意である必要があります。復元された AMI は新しい AMI ID を受け取ります。  

```
aws ec2 create-restore-image-task \
    --object-key ami-1234567890abcdef0.bin \
    --bucket my-ami-bucket \
    --name 'New AMI Name'
```
出力:  

```
{
    "ImageId": "ami-0eab20fe36f83e1a8"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[S3 を使用して AMI を保存および復元する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-store-restore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRestoreImageTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-restore-image-task.html)」を参照してください。

### `create-route-table`
<a name="ec2_CreateRouteTable_cli_2_topic"></a>

次のコード例は、`create-route-table` を使用する方法を示しています。

**AWS CLI**  
**ルートテーブルを作成するには**  
この例では、指定された VPC に対してルートテーブルを作成しています。  
コマンド:  

```
aws ec2 create-route-table --vpc-id vpc-a01106c2
```
出力:  

```
{
    "RouteTable": {
        "Associations": [],
        "RouteTableId": "rtb-22574640",
        "VpcId": "vpc-a01106c2",
        "PropagatingVgws": [],
        "Tags": [],
        "Routes": [
            {
                "GatewayId": "local",
                "DestinationCidrBlock": "10.0.0.0/16",
                "State": "active"
            }
        ]
    }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-route-table.html)」を参照してください。

### `create-route`
<a name="ec2_CreateRoute_cli_2_topic"></a>

次のコード例は、`create-route` を使用する方法を示しています。

**AWS CLI**  
**ルートを作成するには**  
この例では、指定したルートテーブルに対してルートを作成します。ルートはすべての IPv4 トラフィック (`0.0.0.0/0`) と一致し、指定されたインターネットゲートウェイにルーティングされます。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 create-route --route-table-id rtb-22574640 --destination-cidr-block 0.0.0.0/0 --gateway-id igw-c0a643a9
```
このコマンド例では、ルートテーブル rtb-g8ff4ea2 にルートを作成します。ルートは IPv4 CIDR ブロック 10.0.0.0/16 のトラフィックに一致し、VPC ピアリング接続 pcx-111aaa22 にルーティングされます。このルートにより、トラフィックを VPC ピアリング接続のピア VPC にルーティングできます。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 create-route --route-table-id rtb-g8ff4ea2 --destination-cidr-block 10.0.0.0/16 --vpc-peering-connection-id pcx-1a2b3c4d
```
この例では、すべての IPv6 トラフィック (`::/0`) に一致するルートを指定されたルートテーブルに作成し、指定された Egress 専用インターネットゲートウェイにルーティングします。  
コマンド:  

```
aws ec2 create-route --route-table-id rtb-dce620b8 --destination-ipv6-cidr-block ::/0 --egress-only-internet-gateway-id eigw-01eadbd45ecd7943f
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-route.html)」を参照してください。

### `create-security-group`
<a name="ec2_CreateSecurityGroup_cli_2_topic"></a>

次のコード例は、`create-security-group` を使用する方法を示しています。

**AWS CLI**  
**EC2-Classic 用セキュリティグループを作成するには**  
この例では、`MySecurityGroup` という名前のセキュリティグループが作成されます。  
コマンド:  

```
aws ec2 create-security-group --group-name MySecurityGroup --description "My security group"
```
出力:  

```
{
    "GroupId": "sg-903004f8"
}
```
**EC2-VPC 用セキュリティグループを作成するには**  
この例では、指定された VPC 用に `MySecurityGroup` という名前のセキュリティグループが作成されます。  
コマンド:  

```
aws ec2 create-security-group --group-name MySecurityGroup --description "My security group" --vpc-id vpc-1a2b3c4d
```
出力:  

```
{
    "GroupId": "sg-903004f8"
}
```
詳細については、「*AWS コマンドラインインターフェイスユーザーガイド*」でセキュリティグループの使用方法を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-security-group.html)」を参照してください。

### `create-snapshot`
<a name="ec2_CreateSnapshot_cli_2_topic"></a>

次のコード例は、`create-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットを作成するには**  
このコマンド例では、`vol-1234567890abcdef0` というボリューム ID を持つスナップショットと、そのスナップショットを識別するための短い説明を作成します。  
コマンド:  

```
aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description "This is my root volume snapshot"
```
出力:  

```
{
    "Description": "This is my root volume snapshot",
    "Tags": [],
    "Encrypted": false,
    "VolumeId": "vol-1234567890abcdef0",
    "State": "pending",
    "VolumeSize": 8,
    "StartTime": "2018-02-28T21:06:01.000Z",
    "Progress": "",
    "OwnerId": "012345678910",
    "SnapshotId": "snap-066877671789bd71b"
}
```
**タグ付きのスナップショットを作成するには**  
このコマンド例では、スナップショットを作成し、purpose=prod と costcenter=123 という 2 つのタグを適用します。  
コマンド:  

```
aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description 'Prod backup' --tag-specifications 'ResourceType=snapshot,Tags=[{Key=purpose,Value=prod},{Key=costcenter,Value=123}]'
```
出力:  

```
{
    "Description": "Prod backup",
    "Tags": [
        {
            "Value": "prod",
            "Key": "purpose"
        },
        {
            "Value": "123",
            "Key": "costcenter"
        }
     ],
     "Encrypted": false,
     "VolumeId": "vol-1234567890abcdef0",
     "State": "pending",
     "VolumeSize": 8,
     "StartTime": "2018-02-28T21:06:06.000Z",
     "Progress": "",
     "OwnerId": "012345678910",
     "SnapshotId": "snap-09ed24a70bc19bbe4"
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-snapshot.html)」を参照してください。

### `create-snapshots`
<a name="ec2_CreateSnapshots_cli_2_topic"></a>

次のコード例は、`create-snapshots` を使用する方法を示しています。

**AWS CLI**  
**例 1: マルチボリュームスナップショットを作成するには**  
次の `create-snapshots` の例では、指定したインスタンスにアタッチされたすべてのボリュームのスナップショットを作成します。  

```
aws ec2 create-snapshots \
    --instance-specification InstanceId=i-1234567890abcdef0 \
    --description "This is snapshot of a volume from my-instance"
```
出力:  

```
{
    "Snapshots": [
        {
            "Description": "This is a snapshot of a volume from my-instance",
            "Tags": [],
            "Encrypted": false,
            "VolumeId": "vol-0a01d2d5a34697479",
            "State": "pending",
            "VolumeSize": 16,
            "StartTime": "2019-08-05T16:58:19.000Z",
            "Progress": "",
            "OwnerId": "123456789012",
            "SnapshotId": "snap-07f30e3909aa0045e"
        },
        {
            "Description": "This is a snapshot of a volume from my-instance",
            "Tags": [],
            "Encrypted": false,
            "VolumeId": "vol-02d0d4947008cb1a2",
            "State": "pending",
            "VolumeSize": 20,
            "StartTime": "2019-08-05T16:58:19.000Z",
            "Progress": "",
            "OwnerId": "123456789012",
            "SnapshotId": "snap-0ec20b602264aad48"
        },
        ...
    ]
}
```
**例 2: ソースボリュームからタグ付きのマルチボリュームスナップショットを作成するには**  
次の `create-snapshots` の例では、指定したインスタンスにアタッチされたすべてのボリュームのスナップショットを作成し、各ボリュームから対応するスナップショットにタグをコピーします。  

```
aws ec2 create-snapshots \
    --instance-specification InstanceId=i-1234567890abcdef0 \
    --copy-tags-from-source volume \
    --description "This is snapshot of a volume from my-instance"
```
出力:  

```
{
    "Snapshots": [
        {
            "Description": "This is a snapshot of a volume from my-instance",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-volume"
                }
            ],
            "Encrypted": false,
            "VolumeId": "vol-02d0d4947008cb1a2",
            "State": "pending",
            "VolumeSize": 20,
            "StartTime": "2019-08-05T16:53:04.000Z",
            "Progress": "",
            "OwnerId": "123456789012",
            "SnapshotId": "snap-053bfaeb821a458dd"
        }
        ...
    ]
}
```
**例 3: ルートボリュームを含まないマルチボリュームスナップショットを作成するには**  
次の `create-snapshots` の例では、指定したインスタンスにアタッチされたすべてのボリュームのスナップショットを作成します。ただし、ルートボリュームは除きます。  

```
aws ec2 create-snapshots \
    --instance-specification InstanceId=i-1234567890abcdef0,ExcludeBootVolume=true
```
出力例については、例 1 を参照してください。  
**例 4: マルチボリュームスナップショットを作成してタグを追加するには**  
次の `create-snapshots` の例では、指定したインスタンスにアタッチされたすべてのボリュームのスナップショットを作成し、各スナップショットに 2 つのタグを追加します。  

```
aws ec2 create-snapshots \
    --instance-specification InstanceId=i-1234567890abcdef0 \
    --tag-specifications 'ResourceType=snapshot,Tags=[{Key=Name,Value=backup},{Key=costcenter,Value=123}]'
```
出力例については、例 1 を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-snapshots.html)」を参照してください。

### `create-spot-datafeed-subscription`
<a name="ec2_CreateSpotDatafeedSubscription_cli_2_topic"></a>

次のコード例は、`create-spot-datafeed-subscription` を使用する方法を示しています。

**AWS CLI**  
**スポットインスタンスのデータフィードを作成するには**  
次の `create-spot-datafeed-subscription` の例では、スポットインスタンスのデータフィードを作成します。  

```
aws ec2 create-spot-datafeed-subscription \
    --bucket amzn-s3-demo-bucket \
    --prefix spot-data-feed
```
出力:  

```
{
    "SpotDatafeedSubscription": {
        "Bucket": "amzn-s3-demo-bucket",
        "OwnerId": "123456789012",
        "Prefix": "spot-data-feed",
        "State": "Active"
    }
}
```
データフィードは、指定した Amazon S3 バケットに保存されます。このデータフィードのファイル名の形式は次のとおりです。  

```
amzn-s3-demo-bucket.s3.amazonaws.com/spot-data-feed/123456789012.YYYY-MM-DD-HH.n.abcd1234.gz
```
詳細については、*Amazon EC2 ユーザーガイド*の「[ スポットインスタンスのデータフィード](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-data-feeds.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSpotDatafeedSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-spot-datafeed-subscription.html)」を参照してください。

### `create-store-image-task`
<a name="ec2_CreateStoreImageTask_cli_2_topic"></a>

次のコード例は、`create-store-image-task` を使用する方法を示しています。

**AWS CLI**  
**S3 バケットに AMI を保存するには**  
次の `create-store-image-task` の例では、S3 バケットに AMI を保存します。AMI の ID と、AMI を保存する S3 バケットの名前を指定します。  

```
aws ec2 create-store-image-task \
  --image-id ami-1234567890abcdef0 \
  --bucket my-ami-bucket
```
出力:  

```
{
    "ObjectKey": "ami-1234567890abcdef0.bin"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[S3 を使用して AMI を保存および復元する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-store-restore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStoreImageTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-store-image-task.html)」を参照してください。

### `create-subnet-cidr-reservation`
<a name="ec2_CreateSubnetCidrReservation_cli_2_topic"></a>

次のコード例は、`create-subnet-cidr-reservation` を使用する方法を示しています。

**AWS CLI**  
**サブネット CIDR 予約を作成するには**  
次の `create-subnet-cidr-reservation` の例では、指定したサブネットと CIDR 範囲に対してサブネット CIDR 予約を作成します。  

```
aws ec2 create-subnet-cidr-reservation \
    --subnet-id subnet-03c51e2eEXAMPLE \
    --reservation-type prefix \
    --cidr 10.1.0.20/26
```
出力:  

```
{
    "SubnetCidrReservation": {
        "SubnetCidrReservationId": "scr-044f977c4eEXAMPLE",
        "SubnetId": "subnet-03c51e2e6cEXAMPLE",
        "Cidr": "10.1.0.16/28",
        "ReservationType": "prefix",
        "OwnerId": "123456789012"
    }
}
```
詳細については、*Amazon VPC ユーザーガイド*の[サブネット CIDR の予約](https://docs.aws.amazon.com/vpc/latest/userguide/subnet-cidr-reservation.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubnetCidrReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-subnet-cidr-reservation.html)」を参照してください。

### `create-subnet`
<a name="ec2_CreateSubnet_cli_2_topic"></a>

次のコード例は、`create-subnet` を使用する方法を示しています。

**AWS CLI**  
**例 1: IPv4 CIDR ブロックのみを使用してサブネットを作成するには**  
次の `create-subnet` の例では、指定された IPv4 CIDR ブロックで指定された VPC にサブネットを作成しています。  

```
aws ec2 create-subnet \
    --vpc-id vpc-081ec835f3EXAMPLE \
    --cidr-block 10.0.0.0/24 \
    --tag-specifications ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv4-only-subnet}]
```
出力:  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.0.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0e99b93155EXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv4-only-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0e99b93155EXAMPLE"
    }
}
```
**例 2: IPv4 と IPv6 CIDR ブロックの両方を使用してサブネットを作成するには**  
次の `create-subnet` の例では、指定された IPv4 および IPv6 CIDR ブロックで指定された VPC にサブネットを作成しています。  

```
aws ec2 create-subnet \
    --vpc-id vpc-081ec835f3EXAMPLE \
    --cidr-block 10.0.0.0/24 \
    --ipv6-cidr-block 2600:1f16:cfe:3660::/64 \
    --tag-specifications ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv4-ipv6-subnet}]
```
出力:  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 251,
        "CidrBlock": "10.0.0.0/24",
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-0736441d38EXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": false,
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "subnet-cidr-assoc-06c5f904499fcc623",
                "Ipv6CidrBlock": "2600:1f13:cfe:3660::/64",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                }
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv4-ipv6-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0736441d38EXAMPLE"
    }
}
```
**例 3: IPv6 CIDR ブロックのみを使用してサブネットを作成するには**  
次の `create-subnet` の例では、指定された IPv6 CIDR ブロックで指定された VPC にサブネットを作成しています。  

```
aws ec2 create-subnet \
    --vpc-id vpc-081ec835f3EXAMPLE \
    --ipv6-native \
    --ipv6-cidr-block 2600:1f16:115:200::/64 \
    --tag-specifications ResourceType=subnet,Tags=[{Key=Name,Value=my-ipv6-only-subnet}]
```
出力:  

```
{
    "Subnet": {
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az2",
        "AvailableIpAddressCount": 0,
        "DefaultForAz": false,
        "MapPublicIpOnLaunch": false,
        "State": "available",
        "SubnetId": "subnet-03f720e7deEXAMPLE",
        "VpcId": "vpc-081ec835f3EXAMPLE",
        "OwnerId": "123456789012",
        "AssignIpv6AddressOnCreation": true,
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "subnet-cidr-assoc-01ef639edde556709",
                "Ipv6CidrBlock": "2600:1f13:cfe:3660::/64",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                }
            }
        ],
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-ipv6-only-subnet"
            }
        ],
        "SubnetArn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-03f720e7deEXAMPLE"
    }
}
```
詳細については、「Amazon VPC ユーザーガイド」の「[VPC とサブネット](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateSubnet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-subnet.html)」を参照してください。

### `create-tags`
<a name="ec2_CreateTags_cli_2_topic"></a>

次のコード例は、`create-tags` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースにタグを追加するには**  
次の `create-tags` の例では、タグ `Stack=production` を指定されたイメージに追加するか、タグキーが `Stack` の AMI 用に既存のタグを上書きします。  

```
aws ec2 create-tags \
    --resources ami-1234567890abcdef0 \
    --tags Key=Stack,Value=production
```
このコマンドでは何も出力されません。  
**例 2: 複数のリソースにタグを追加するには**  
次の `create-tags` の例では、2 つのタグを AMI とインスタンス用に追加 (または上書き) します。一方のタグでは、キー (`webserver`) はありますが値はありません (値は空文字列に設定されています)。もう一方のタグにはキー (`stack`) と値 (`Production`) があります。  

```
aws ec2 create-tags \
    --resources ami-1a2b3c4d i-1234567890abcdef0 \
    --tags Key=webserver,Value=   Key=stack,Value=Production
```
このコマンドでは何も出力されません。  
**例 3: 特殊文字を含むタグを追加するには**  
次の `create-tags` の例では、インスタンスにタグ `[Group]=test` を追加します。角括弧 ([、]) は特殊文字であり、エスケープする必要があります。以下の例でも、各環境に適した行継続文字を使用しています。  
Windows を使用している場合、特殊文字を含む要素を二重引用符 (") で囲み、各二重引用符の前にバックスラッシュ (\$1) を付けます。  

```
aws ec2 create-tags ^
    --resources i-1234567890abcdef0 ^
    --tags Key=\"[Group]\",Value=test
```
Windows PowerShell を使用している場合、次のように特殊文字を含む値を二重引用符 (") で囲み、各二重引用符の前にバックスラッシュ (\$1) を付けてから、キーと値の構造全体を一重引用符 (') で囲みます。  

```
aws ec2 create-tags `
    --resources i-1234567890abcdef0 `
    --tags 'Key=\"[Group]\",Value=test'
```
Linux または OS X を使用している場合は、次のように特殊文字を含む要素を二重引用符 (") で囲んだ後、キーと値の構造全体を一重引用符 (') で囲みます。  

```
aws ec2 create-tags \
    --resources i-1234567890abcdef0 \
    --tags 'Key="[Group]",Value=test'
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Amazon EC2 リソースのタグ付け](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-tags.html)」を参照してください。

### `create-traffic-mirror-filter-rule`
<a name="ec2_CreateTrafficMirrorFilterRule_cli_2_topic"></a>

次のコード例は、`create-traffic-mirror-filter-rule` を使用する方法を示しています。

**AWS CLI**  
**受信 TCP トラフィックのフィルタールールを作成するには**  
次の `create-traffic-mirror-filter-rule` の例では、すべての受信 TCP トラフィックをミラーリングするために使用できるルールを作成します。このコマンドを実行する前に、`create-traffic-mirror-filter` を使用してトラフィックミラーフィルタを作成します。  

```
aws ec2 create-traffic-mirror-filter-rule \
    --description 'TCP Rule' \
    --destination-cidr-block 0.0.0.0/0  \
    --protocol 6 \
    --rule-action accept \
    --rule-number 1 \
    --source-cidr-block 0.0.0.0/0 \
    --traffic-direction ingress \
    --traffic-mirror-filter-id tmf-04812ff784b25ae67
```
出力:  

```
{
    "TrafficMirrorFilterRule": {
        "DestinationCidrBlock": "0.0.0.0/0",
        "TrafficMirrorFilterId": "tmf-04812ff784b25ae67",
        "TrafficMirrorFilterRuleId": "tmfr-02d20d996673f3732",
        "SourceCidrBlock": "0.0.0.0/0",
        "TrafficDirection": "ingress",
        "Description": "TCP Rule",
        "RuleNumber": 1,
        "RuleAction": "accept",
        "Protocol": 6
    },
    "ClientToken": "4752b573-40a6-4eac-a8a4-a72058761219"
}
```
詳細については、*トラフィックミラーリングガイド*の「[トラフィックミラーフィルタを作成する](https://docs.aws.amazon.com/vpc/latest/mirroring/create-traffic-mirroring-filter.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTrafficMirrorFilterRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-traffic-mirror-filter-rule.html)」を参照してください。

### `create-traffic-mirror-filter`
<a name="ec2_CreateTrafficMirrorFilter_cli_2_topic"></a>

次のコード例は、`create-traffic-mirror-filter` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーフィルタを作成するには**  
次の `create-traffic-mirror-filter` の例では、トラフィックミラーフィルタを作成します。フィルタを作成したら、`create-traffic-mirror-filter-rule` を使用してルールを追加します。  

```
aws ec2 create-traffic-mirror-filter \
    --description 'TCP Filter'
```
出力:  

```
{
    "ClientToken": "28908518-100b-4987-8233-8c744EXAMPLE",
    "TrafficMirrorFilter": {
        "TrafficMirrorFilterId": "tmf-04812ff784EXAMPLE",
        "Description": "TCP Filter",
        "EgressFilterRules": [],
        "IngressFilterRules": [],
        "Tags": [],
        "NetworkServices": []
    }
}
```
詳細については、*トラフィックミラーリングガイド*の「[トラフィックミラーフィルタを作成する](https://docs.aws.amazon.com/vpc/latest/mirroring/create-traffic-mirroring-filter.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTrafficMirrorFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-traffic-mirror-filter.html)」を参照してください。

### `create-traffic-mirror-session`
<a name="ec2_CreateTrafficMirrorSession_cli_2_topic"></a>

次のコード例は、`create-traffic-mirror-session` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーセッションを作成するには**  
次の `create-traffic-mirror-session` コマンドは、指定したソースとターゲットのトラフィックミラーセッションを 25 バイトのパケットに対して作成します。  

```
aws ec2 create-traffic-mirror-session \
    --description 'example session' \
    --traffic-mirror-target-id tmt-07f75d8feeEXAMPLE \
    --network-interface-id eni-070203f901EXAMPLE \
    --session-number 1  \
    --packet-length 25 \
    --traffic-mirror-filter-id tmf-04812ff784EXAMPLE
```
出力:  

```
{
    "TrafficMirrorSession": {
        "TrafficMirrorSessionId": "tms-08a33b1214EXAMPLE",
        "TrafficMirrorTargetId": "tmt-07f75d8feeEXAMPLE",
        "TrafficMirrorFilterId": "tmf-04812ff784EXAMPLE",
        "NetworkInterfaceId": "eni-070203f901EXAMPLE",
        "OwnerId": "111122223333",
        "PacketLength": 25,
        "SessionNumber": 1,
        "VirtualNetworkId": 7159709,
        "Description": "example session",
        "Tags": []
    },
    "ClientToken": "5236cffc-ee13-4a32-bb5b-388d9da09d96"
}
```
詳細については、*トラフィックミラーリングガイド*の「[トラフィックミラーセッションを作成する](https://docs.aws.amazon.com/vpc/latest/mirroring/create-traffic-mirroring-session.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTrafficMirrorSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-traffic-mirror-session.html)」を参照してください。

### `create-traffic-mirror-target`
<a name="ec2_CreateTrafficMirrorTarget_cli_2_topic"></a>

次のコード例は、`create-traffic-mirror-target` を使用する方法を示しています。

**AWS CLI**  
**Network Load Balancer トラフィックミラーターゲットを作成するには**  
次の `create-traffic-mirror-target` の例では、Network Load Balancer トラフィックミラーターゲットを作成します。  

```
aws ec2 create-traffic-mirror-target \
    --description 'Example Network Load Balancer Target' \
    --network-load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/net/NLB/7cdec873EXAMPLE
```
出力:  

```
{
    "TrafficMirrorTarget": {
        "Type": "network-load-balancer",
        "Tags": [],
        "Description": "Example Network Load Balancer Target",
        "OwnerId": "111122223333",
        "NetworkLoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:724145273726:loadbalancer/net/NLB/7cdec873EXAMPLE",
        "TrafficMirrorTargetId": "tmt-0dabe9b0a6EXAMPLE"
    },
    "ClientToken": "d5c090f5-8a0f-49c7-8281-72c796a21f72"
}
```
**ネットワークのトラフィックミラーターゲットを作成するには**  
次の `create-traffic-mirror-target` の例では、ネットワークインターフェイスのトラフィックミラーターゲットを作成します。  

```
aws ec2 create-traffic-mirror-target \
    --description 'Network interface target' \
    --network-interface-id eni-eni-01f6f631eEXAMPLE
```
出力:  

```
{
    "ClientToken": "5289a345-0358-4e62-93d5-47ef3061d65e",
    "TrafficMirrorTarget": {
        "Description": "Network interface target",
        "NetworkInterfaceId": "eni-01f6f631eEXAMPLE",
        "TrafficMirrorTargetId": "tmt-02dcdbe2abEXAMPLE",
        "OwnerId": "111122223333",
        "Type": "network-interface",
        "Tags": []
    }
}
```
詳細については、*トラフィックミラーリングガイド*の「[トラフィックミラーターゲットを作成する](https://docs.aws.amazon.com/vpc/latest/mirroring/create-traffic-mirroring-target.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTrafficMirrorTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-traffic-mirror-target.html)」を参照してください。

### `create-transit-gateway-connect-peer`
<a name="ec2_CreateTransitGatewayConnectPeer_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-connect-peer` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway Connect ピアを作成するには**  
次の `create-transit-gateway-connect-peer` の例では、Connect ピアを作成します。  

```
aws ec2 create-transit-gateway-connect-peer \
    --transit-gateway-attachment-id tgw-attach-0f0927767cEXAMPLE \
    --peer-address 172.31.1.11 \
    --inside-cidr-blocks 169.254.6.0/29
```
出力:  

```
{
    "TransitGatewayConnectPeer": {
        "TransitGatewayAttachmentId": "tgw-attach-0f0927767cEXAMPLE",
        "TransitGatewayConnectPeerId": "tgw-connect-peer-0666adbac4EXAMPLE",
        "State": "pending",
        "CreationTime": "2021-10-13T03:35:17.000Z",
        "ConnectPeerConfiguration": {
            "TransitGatewayAddress": "10.0.0.234",
            "PeerAddress": "172.31.1.11",
            "InsideCidrBlocks": [
                "169.254.6.0/29"
            ],
            "Protocol": "gre",
            "BgpConfigurations": [
                {
                    "TransitGatewayAsn": 64512,
                    "PeerAsn": 64512,
                    "TransitGatewayAddress": "169.254.6.2",
                    "PeerAddress": "169.254.6.1",
                    "BgpStatus": "down"
                },
                {
                    "TransitGatewayAsn": 64512,
                    "PeerAsn": 64512,
                    "TransitGatewayAddress": "169.254.6.3",
                    "PeerAddress": "169.254.6.1",
                    "BgpStatus": "down"
                }
            ]
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway Connect attachments and Transit Gateway Connect peers](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayConnectPeer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-connect-peer.html)」を参照してください。

### `create-transit-gateway-connect`
<a name="ec2_CreateTransitGatewayConnect_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-connect` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway Connect アタッチメントを作成するには**  
次の `create-transit-gateway-connect` の例では、指定したアタッチメント用に、「gre」プロトコルを使用して、Connect アタッチメントを作成します。  

```
aws ec2 create-transit-gateway-connect \
    --transport-transit-gateway-attachment-id tgw-attach-0a89069f57EXAMPLE \
    --options "Protocol=gre"
```
出力:  

```
{
    "TransitGatewayConnect": {
        "TransitGatewayAttachmentId": "tgw-attach-037012e5dcEXAMPLE",
        "TransportTransitGatewayAttachmentId": "tgw-attach-0a89069f57EXAMPLE",
        "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
        "State": "pending",
        "CreationTime": "2021-03-09T19:59:17+00:00",
        "Options": {
            "Protocol": "gre"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway Connect attachments and Transit Gateway Connect peers](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayConnect](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-connect.html)」を参照してください。

### `create-transit-gateway-multicast-domain`
<a name="ec2_CreateTransitGatewayMulticastDomain_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-multicast-domain` を使用する方法を示しています。

**AWS CLI**  
**例 1: IGMP マルチキャストドメインを作成するには**  
次の `create-transit-gateway-multicast-domain` の例では、指定した Transit Gateway 用にマルチキャストドメインを作成します。静的ソースを無効にすると、マルチキャストドメインに関連付けられたサブネット内のすべてのインスタンスがマルチキャストトラフィックを送信できるようになります。メンバーの少なくとも 1 人が IGMP プロトコルを使用している場合は、IGMPv2 サポートを有効にする必要があります。  

```
aws ec2 create-transit-gateway-multicast-domain \
    --transit-gateway-id tgw-0bf0bffefaEXAMPLE \
    --options StaticSourcesSupport=disable,Igmpv2Support=enable
```
出力:  

```
{
    "TransitGatewayMulticastDomain": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c9e29e2a7EXAMPLE",
        "TransitGatewayId": "tgw-0bf0bffefaEXAMPLE",
        "TransitGatewayMulticastDomainArn": "arn:aws:ec2:us-west-2:123456789012:transit-gateway-multicast-domain/tgw-mcast-domain-0c9e29e2a7EXAMPLE",
        "OwnerId": "123456789012",
        "Options": {
            "Igmpv2Support": "enable",
            "StaticSourcesSupport": "disable",
            "AutoAcceptSharedAssociations": "disable"
        },
        "State": "pending",
        "CreationTime": "2021-09-29T22:17:13.000Z"
    }
}
```
**例 2: 静的マルチキャストドメインを作成するには**  
次の `create-transit-gateway-multicast-domain` の例では、指定した Transit Gateway 用にマルチキャストドメインを作成します。静的ソースが有効になっている場合は、ソースを静的に追加する必要があります。  

```
aws ec2 create-transit-gateway-multicast-domain \
    --transit-gateway-id tgw-0bf0bffefaEXAMPLE \
    --options StaticSourcesSupport=enable,Igmpv2Support=disable
```
出力:  

```
{
    "TransitGatewayMulticastDomain": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-000fb24d04EXAMPLE",
        "TransitGatewayId": "tgw-0bf0bffefaEXAMPLE",
        "TransitGatewayMulticastDomainArn": "arn:aws:ec2:us-west-2:123456789012:transit-gateway-multicast-domain/tgw-mcast-domain-000fb24d04EXAMPLE",
        "OwnerId": "123456789012",
        "Options": {
            "Igmpv2Support": "disable",
            "StaticSourcesSupport": "enable",
            "AutoAcceptSharedAssociations": "disable"
        },
        "State": "pending",
        "CreationTime": "2021-09-29T22:20:19.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Managing multicast domains](https://docs.aws.amazon.com/vpc/latest/tgw/manage-domain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayMulticastDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-multicast-domain.html)」を参照してください。

### `create-transit-gateway-peering-attachment`
<a name="ec2_CreateTransitGatewayPeeringAttachment_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-peering-attachment` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ピアリングアタッチメントを作成するには**  
次の `create-transit-gateway-peering-attachment` の例では、指定した 2 つのゲートウェイ間のピアリングアタッチメントリクエストを作成します。  

```
aws ec2 create-transit-gateway-peering-attachment \
    --transit-gateway-id tgw-123abc05e04123abc \
    --peer-transit-gateway-id tgw-11223344aabbcc112 \
    --peer-account-id 123456789012 \
    --peer-region us-east-2
```
出力:  

```
{
    "TransitGatewayPeeringAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-4455667788aabbccd",
        "RequesterTgwInfo": {
            "TransitGatewayId": "tgw-123abc05e04123abc",
            "OwnerId": "123456789012",
            "Region": "us-west-2"
        },
        "AccepterTgwInfo": {
            "TransitGatewayId": "tgw-11223344aabbcc112",
            "OwnerId": "123456789012",
            "Region": "us-east-2"
        },
        "State": "initiatingRequest",
        "CreationTime": "2019-12-09T11:38:05.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit Gateway Peering Attachments](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayPeeringAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-peering-attachment.html)」を参照してください。

### `create-transit-gateway-policy-table`
<a name="ec2_CreateTransitGatewayPolicyTable_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-policy-table` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ポリシーテーブルを作成するには**  
次の `create-transit-gateway-policy-table` の例では、指定した Transit Gateway 用に Transit Gateway ポリシーテーブルを作成します。  

```
aws ec2 create-transit-gateway-policy-table \
    --transit-gateway-id tgw-067f8505c18f0bd6e
```
出力:  

```
{
    "TransitGatewayPolicyTable": {
        "TransitGatewayPolicyTableId": "tgw-ptb-0a16f134b78668a81",
        "TransitGatewayId": "tgw-067f8505c18f0bd6e",
        "State": "pending",
        "CreationTime": "2023-11-28T16:36:43+00:00"
    }
}
```
詳細については、「*Transit Gateway ユーザーガイド*」の「[Transit gateway policy tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-policy-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayPolicyTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-policy-table.html)」を参照してください。

### `create-transit-gateway-prefix-list-reference`
<a name="ec2_CreateTransitGatewayPrefixListReference_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-prefix-list-reference` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストのリファレンスを作成するには**  
次の `create-transit-gateway-prefix-list-reference` の例では、指定した Transit Gateway ルートテーブルに指定したプレフィックスリストへの参照を作成します。  

```
aws ec2 create-transit-gateway-prefix-list-reference \
    --transit-gateway-route-table-id tgw-rtb-0123456789abcd123 \
    --prefix-list-id pl-11111122222222333 \
    --transit-gateway-attachment-id tgw-attach-aaaaaabbbbbb11111
```
出力:  

```
{
    "TransitGatewayPrefixListReference": {
        "TransitGatewayRouteTableId": "tgw-rtb-0123456789abcd123",
        "PrefixListId": "pl-11111122222222333",
        "PrefixListOwnerId": "123456789012",
        "State": "pending",
        "Blackhole": false,
        "TransitGatewayAttachment": {
            "TransitGatewayAttachmentId": "tgw-attach-aaaaaabbbbbb11111",
            "ResourceType": "vpc",
            "ResourceId": "vpc-112233445566aabbc"
        }
    }
}
```
詳細については、*Transit Gateways ガイド*の「[プレフィックスリスト参照の作成](https://docs.aws.amazon.com/vpc/latest/tgw/create-prefix-list-reference.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayPrefixListReference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-prefix-list-reference.html)」を参照してください。

### `create-transit-gateway-route-table`
<a name="ec2_CreateTransitGatewayRouteTable_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-route-table` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ルートテーブルを作成するには**  
次の `create-transit-gateway-route-table` の例では、指定した Transit Gateway 用にルートテーブルを作成します。  

```
aws ec2 create-transit-gateway-route-table \
    --transit-gateway-id tgw-0262a0e521EXAMPLE
```
出力:  

```
{
    "TransitGatewayRouteTable": {
        "TransitGatewayRouteTableId": "tgw-rtb-0960981be7EXAMPLE",
        "TransitGatewayId": "tgw-0262a0e521EXAMPLE",
        "State": "pending",
        "DefaultAssociationRouteTable": false,
        "DefaultPropagationRouteTable": false,
        "CreationTime": "2019-07-10T19:01:46.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Create a transit gateway route table](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#create-tgw-route-table)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-route-table.html)」を参照してください。

### `create-transit-gateway-route`
<a name="ec2_CreateTransitGatewayRoute_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-route` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ルートを作成するには**  
次の `create-transit-gateway-route` の例では、指定したルートテーブル用に、指定した場所を使用して、ルートを作成します。  

```
aws ec2 create-transit-gateway-route \
    --destination-cidr-block 10.0.2.0/24 \
    --transit-gateway-route-table-id tgw-rtb-0b6f6aaa01EXAMPLE \
    --transit-gateway-attachment-id tgw-attach-0b5968d3b6EXAMPLE
```
出力:  

```
{
    "Route": {
        "DestinationCidrBlock": "10.0.2.0/24",
        "TransitGatewayAttachments": [
            {
                "ResourceId": "vpc-0065acced4EXAMPLE",
                "TransitGatewayAttachmentId": "tgw-attach-0b5968d3b6EXAMPLE",
                "ResourceType": "vpc"
            }
        ],
        "Type": "static",
        "State": "active"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-route.html)」を参照してください。

### `create-transit-gateway-vpc-attachment`
<a name="ec2_CreateTransitGatewayVpcAttachment_cli_2_topic"></a>

次のコード例は、`create-transit-gateway-vpc-attachment` を使用する方法を示しています。

**AWS CLI**  
**例 1: Transit Gateway を VPC に関連付けるには**  
次の `create-transit-gateway-vpc-attachment` の例では、指定した VPC への Transit Gateway アタッチメントを作成します。  

```
aws ec2 create-transit-gateway-vpc-attachment \
    --transit-gateway-id tgw-0262a0e521EXAMPLE \
    --vpc-id vpc-07e8ffd50f49335df \
    --subnet-id subnet-0752213d59EXAMPLE
```
出力:  

```
{
    "TransitGatewayVpcAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-0a34fe6b4fEXAMPLE",
        "TransitGatewayId": "tgw-0262a0e521EXAMPLE",
        "VpcId": "vpc-07e8ffd50fEXAMPLE",
        "VpcOwnerId": "111122223333",
        "State": "pending",
        "SubnetIds": [
            "subnet-0752213d59EXAMPLE"
        ],
        "CreationTime": "2019-07-10T17:33:46.000Z",
        "Options": {
            "DnsSupport": "enable",
            "Ipv6Support": "disable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Create a transit gateway attachment to a VPC](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#create-vpc-attachment)」を参照してください。  
**例 2: Transit Gateway を VPC 内の複数のサブネットに関連付けるには**  
次の `create-transit-gateway-vpc-attachment` の例では、指定した VPC とサブネットへの Transit Gateway アタッチメントを作成します。  

```
aws ec2 create-transit-gateway-vpc-attachment \
    --transit-gateway-id tgw-02f776b1a7EXAMPLE  \
    --vpc-id vpc-3EXAMPLE \
    --subnet-ids "subnet-dEXAMPLE" "subnet-6EXAMPLE"
```
出力:  

```
{
    "TransitGatewayVpcAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-0e141e0bebEXAMPLE",
        "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
        "VpcId": "vpc-3EXAMPLE",
        "VpcOwnerId": "111122223333",
        "State": "pending",
        "SubnetIds": [
            "subnet-6EXAMPLE",
            "subnet-dEXAMPLE"
        ],
        "CreationTime": "2019-12-17T20:07:52.000Z",
        "Options": {
            "DnsSupport": "enable",
            "Ipv6Support": "disable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Create a transit gateway attachment to a VPC](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#create-vpc-attachment)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGatewayVpcAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway-vpc-attachment.html)」を参照してください。

### `create-transit-gateway`
<a name="ec2_CreateTransitGateway_cli_2_topic"></a>

次のコード例は、`create-transit-gateway` を使用する方法を示しています。

**AWS CLI**  
** Transit Gateway を作成するには**  
次の `create-transit-gateway` の例では、Transit Gateway を作成します。  

```
aws ec2 create-transit-gateway \
    --description MyTGW \
    --options AmazonSideAsn=64516,AutoAcceptSharedAttachments=enable,DefaultRouteTableAssociation=enable,DefaultRouteTablePropagation=enable,VpnEcmpSupport=enable,DnsSupport=enable
```
出力:  

```
{
    "TransitGateway": {
        "TransitGatewayId": "tgw-0262a0e521EXAMPLE",
        "TransitGatewayArn": "arn:aws:ec2:us-east-2:111122223333:transit-gateway/tgw-0262a0e521EXAMPLE",
        "State": "pending",
        "OwnerId": "111122223333",
        "Description": "MyTGW",
        "CreationTime": "2019-07-10T14:02:12.000Z",
        "Options": {
            "AmazonSideAsn": 64516,
            "AutoAcceptSharedAttachments": "enable",
            "DefaultRouteTableAssociation": "enable",
            "AssociationDefaultRouteTableId": "tgw-rtb-018774adf3EXAMPLE",
            "DefaultRouteTablePropagation": "enable",
            "PropagationDefaultRouteTableId": "tgw-rtb-018774adf3EXAMPLE",
            "VpnEcmpSupport": "enable",
            "DnsSupport": "enable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Create a transit gateway](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#create-tgw)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTransitGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-transit-gateway.html)」を参照してください。

### `create-verified-access-endpoint`
<a name="ec2_CreateVerifiedAccessEndpoint_cli_2_topic"></a>

次のコード例は、`create-verified-access-endpoint` を使用する方法を示しています。

**AWS CLI**  
**Verified Access エンドポイントを作成するには**  
次の `create-verified-access-endpoint` の例では、指定した Verified Access グループの Verified Access エンドポイントを作成します。指定されたネットワークインターフェイスとセキュリティグループは、同じ VPC に属している必要があります。  

```
aws ec2 create-verified-access-endpoint \
    --verified-access-group-id vagr-0dbe967baf14b7235 \
    --endpoint-type network-interface \
    --attachment-type vpc \
    --domain-certificate-arn arn:aws:acm:us-east-2:123456789012:certificate/eb065ea0-26f9-4e75-a6ce-0a1a7EXAMPLE \
    --application-domain example.com \
    --endpoint-domain-prefix my-ava-app \
    --security-group-ids sg-004915970c4c8f13a \
    --network-interface-options NetworkInterfaceId=eni-0aec70418c8d87a0f,Protocol=https,Port=443 \
    --tag-specifications ResourceType=verified-access-endpoint,Tags=[{Key=Name,Value=my-va-endpoint}]
```
出力:  

```
{
    "VerifiedAccessEndpoint": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
        "VerifiedAccessEndpointId": "vae-066fac616d4d546f2",
        "ApplicationDomain": "example.com",
        "EndpointType": "network-interface",
        "AttachmentType": "vpc",
        "DomainCertificateArn": "arn:aws:acm:us-east-2:123456789012:certificate/eb065ea0-26f9-4e75-a6ce-0a1a7EXAMPLE",
        "EndpointDomain": "my-ava-app.edge-00c3372d53b1540bb.vai-0ce000c0b7643abea.prod.verified-access.us-east-2.amazonaws.com",
        "SecurityGroupIds": [
            "sg-004915970c4c8f13a"
        ],
        "NetworkInterfaceOptions": {
            "NetworkInterfaceId": "eni-0aec70418c8d87a0f",
            "Protocol": "https",
            "Port": 443
        },
        "Status": {
            "Code": "pending"
        },
        "Description": "",
        "CreationTime": "2023-08-25T20:54:43",
        "LastUpdatedTime": "2023-08-25T20:54:43",
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-va-endpoint"
            }
        ]
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access endpoints](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVerifiedAccessEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-verified-access-endpoint.html)」を参照してください。

### `create-verified-access-group`
<a name="ec2_CreateVerifiedAccessGroup_cli_2_topic"></a>

次のコード例は、`create-verified-access-group` を使用する方法を示しています。

**AWS CLI**  
**Verified Access グループを作成するには**  
次の `create-verified-access-group` の例では、指定した Verified Access インスタンスの Verified Access グループを作成します。  

```
aws ec2 create-verified-access-group \
    --verified-access-instance-id vai-0ce000c0b7643abea \
    --tag-specifications ResourceType=verified-access-group,Tags=[{Key=Name,Value=my-va-group}]
```
出力:  

```
{
    "VerifiedAccessGroup": {
        "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "",
        "Owner": "123456789012",
        "VerifiedAccessGroupArn": "arn:aws:ec2:us-east-2:123456789012:verified-access-group/vagr-0dbe967baf14b7235",
        "CreationTime": "2023-08-25T19:55:19",
        "LastUpdatedTime": "2023-08-25T19:55:19",
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-va-group"
            }
        ]
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access groups](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVerifiedAccessGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-verified-access-group.html)」を参照してください。

### `create-verified-access-instance`
<a name="ec2_CreateVerifiedAccessInstance_cli_2_topic"></a>

次のコード例は、`create-verified-access-instance` を使用する方法を示しています。

**AWS CLI**  
**Verified Access インスタンスを作成するには**  
次の `create-verified-access-instance` の例では、名前タグを使用して Verified Access インスタンスを作成します。  

```
aws ec2 create-verified-access-instance \
    --tag-specifications ResourceType=verified-access-instance,Tags=[{Key=Name,Value=my-va-instance}]
```
出力:  

```
{
    "VerifiedAccessInstance": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "",
        "VerifiedAccessTrustProviders": [],
        "CreationTime": "2023-08-25T18:27:56",
        "LastUpdatedTime": "2023-08-25T18:27:56",
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-va-instance"
            }
        ]
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Access インスタンス](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVerifiedAccessInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-verified-access-instance.html)」を参照してください。

### `create-verified-access-trust-provider`
<a name="ec2_CreateVerifiedAccessTrustProvider_cli_2_topic"></a>

次のコード例は、`create-verified-access-trust-provider` を使用する方法を示しています。

**AWS CLI**  
**Verified Access 信頼プロバイダーを作成するには**  
次の の`create-verified-access-trust-provider`例では、 AWS Identity Center を使用して Verified Access 信頼プロバイダーを設定します。  

```
aws ec2 create-verified-access-trust-provider \
    --trust-provider-type user \
    --user-trust-provider-type iam-identity-center \
    --policy-reference-name idc \
    --tag-specifications ResourceType=verified-access-trust-provider,Tags=[{Key=Name,Value=my-va-trust-provider}]
```
出力:  

```
{
    "VerifiedAccessTrustProvider": {
        "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
        "Description": "",
        "TrustProviderType": "user",
        "UserTrustProviderType": "iam-identity-center",
        "PolicyReferenceName": "idc",
        "CreationTime": "2023-08-25T18:40:36",
        "LastUpdatedTime": "2023-08-25T18:40:36",
        "Tags": [
            {
                "Key": "Name",
                "Value": "my-va-trust-provider"
            }
        ]
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Trust providers for Verified Access](https://docs.aws.amazon.com/verified-access/latest/ug/trust-providers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVerifiedAccessTrustProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-verified-access-trust-provider.html)」を参照してください。

### `create-volume`
<a name="ec2_CreateVolume_cli_2_topic"></a>

次のコード例は、`create-volume` を使用する方法を示しています。

**AWS CLI**  
**空の汎用 SSD (gp2) ボリュームを作成するには**  
次の `create-volume` の例では、指定したアベイラビリティーゾーンに 80 GiB 汎用 SSD (gp2) ボリュームを作成します。現在のリージョンは `us-east-1` である必要があります。または、`--region` パラメータを追加してコマンドのリージョンを指定できます。  

```
aws ec2 create-volume \
    --volume-type gp2 \
    --size 80 \
    --availability-zone us-east-1a
```
出力:  

```
{
    "AvailabilityZone": "us-east-1a",
    "Tags": [],
    "Encrypted": false,
    "VolumeType": "gp2",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "creating",
    "Iops": 240,
    "SnapshotId": "",
    "CreateTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "Size": 80
}
```
ボリュームタイプを指定しない場合、デフォルトのボリュームタイプは `gp2` です。  

```
aws ec2 create-volume \
    --size 80 \
    --availability-zone us-east-1a
```
**例 2: スナップショットからプロビジョンド IOPS SSD (io1) ボリュームを作成するには**  
次の `create-volume` の例では、指定したスナップショットを使用して、指定したアベイラビリティーゾーンに 1,000 個のプロビジョニングされた IOPS を持つプロビジョンド IOPS SSD (io1) ボリュームを作成します。  

```
aws ec2 create-volume \
    --volume-type io1 \
    --iops 1000 \
    --snapshot-id snap-066877671789bd71b \
    --availability-zone us-east-1a
```
出力:  

```
{
    "AvailabilityZone": "us-east-1a",
    "Tags": [],
    "Encrypted": false,
    "VolumeType": "io1",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "creating",
    "Iops": 1000,
    "SnapshotId": "snap-066877671789bd71b",
    "CreateTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "Size": 500
}
```
**例 3: 暗号化されたボリュームを作成するには**  
次の `create-volume` の例では、EBS 暗号化用のデフォルトの CMK を使用して暗号化されたボリュームを作成します。デフォルトで暗号化が無効になっている場合、次のように `--encrypted` パラメータを指定する必要があります。  

```
aws ec2 create-volume \
    --size 80 \
    --encrypted \
    --availability-zone us-east-1a
```
出力:  

```
{
    "AvailabilityZone": "us-east-1a",
    "Tags": [],
    "Encrypted": true,
    "VolumeType": "gp2",
    "VolumeId": "vol-1234567890abcdef0",
    "State": "creating",
    "Iops": 240,
    "SnapshotId": "",
    "CreateTime": "YYYY-MM-DDTHH:MM:SS.000Z",
    "Size": 80
}
```
暗号化がデフォルトで有効になっている場合、次の例のコマンドは、`--encrypted` パラメータがなくても暗号化されたボリュームを作成します。  

```
aws ec2 create-volume \
    --size 80 \
    --availability-zone us-east-1a
```
`--kms-key-id` パラメータを使用してカスタマー管理の CMK を指定する場合は、デフォルトで暗号化が有効になっていても `--encrypted` パラメータを指定する必要があります。  

```
aws ec2 create-volume \
    --volume-type gp2 \
    --size 80 \
    --encrypted \
    --kms-key-id 0ea3fef3-80a7-4778-9d8c-1c0c6EXAMPLE \
    --availability-zone us-east-1a
```
**例 4: タグ付きのボリュームを作成するには**  
次の `create-volume` の例では、ボリュームを作成して 2 つのタグを追加します。  

```
aws ec2 create-volume \
    --availability-zone us-east-1a \
    --volume-type gp2 \
    --size 80 \
    --tag-specifications 'ResourceType=volume,Tags=[{Key=purpose,Value=production},{Key=cost-center,Value=cc123}]'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-volume.html)」を参照してください。

### `create-vpc-endpoint-connection-notification`
<a name="ec2_CreateVpcEndpointConnectionNotification_cli_2_topic"></a>

次のコード例は、`create-vpc-endpoint-connection-notification` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントの接続通知を作成するには**  
この例では、インターフェイスエンドポイントがサービスに接続されているとき、およびエンドポイントがサービスに対して承諾されたときに警告する、特定のエンドポイントサービスの通知を作成します。  
コマンド:  

```
aws ec2 create-vpc-endpoint-connection-notification --connection-notification-arn arn:aws:sns:us-east-2:123456789012:VpceNotification --connection-events Connect Accept --service-id vpce-svc-1237881c0d25a3abc
```
出力:  

```
{
   "ConnectionNotification": {
       "ConnectionNotificationState": "Enabled",
       "ConnectionNotificationType": "Topic",
       "ServiceId": "vpce-svc-1237881c0d25a3abc",
       "ConnectionEvents": [
           "Accept",
           "Connect"
       ],
       "ConnectionNotificationId": "vpce-nfn-008776de7e03f5abc",
       "ConnectionNotificationArn": "arn:aws:sns:us-east-2:123456789012:VpceNotification"
   }
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpcEndpointConnectionNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpc-endpoint-connection-notification.html)」を参照してください。

### `create-vpc-endpoint-service-configuration`
<a name="ec2_CreateVpcEndpointServiceConfiguration_cli_2_topic"></a>

次のコード例は、`create-vpc-endpoint-service-configuration` を使用する方法を示しています。

**AWS CLI**  
**例 1: インターフェイスエンドポイントのエンドポイントサービス設定を作成するには**  
次の `create-vpc-endpoint-service-configuration` の例では、Network Load Balancer `nlb-vpce` を使用して VPC エンドポイントサービス設定を作成します。この例では、インターフェイスエンドポイントを通じてサービスに接続するリクエストを承諾する必要があることも指定します。  

```
aws ec2 create-vpc-endpoint-service-configuration \
    --network-load-balancer-arns arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/nlb-vpce/e94221227f1ba532 \
    --acceptance-required
```
出力:  

```
{
   "ServiceConfiguration": {
       "ServiceType": [
           {
               "ServiceType": "Interface"
           }
       ],
       "NetworkLoadBalancerArns": [
           "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/nlb-vpce/e94221227f1ba532"
       ],
       "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-03d5ebb7d9579a2b3",
       "ServiceState": "Available",
       "ServiceId": "vpce-svc-03d5ebb7d9579a2b3",
       "AcceptanceRequired": true,
       "AvailabilityZones": [
           "us-east-1d"
       ],
       "BaseEndpointDnsNames": [
           "vpce-svc-03d5ebb7d9579a2b3.us-east-1.vpce.amazonaws.com"
       ]
   }
}
```
詳細については、*AWS PrivateLink ユーザーガイド*の「[エンドポイントサービスの作成](https://docs.aws.amazon.com/vpc/latest/privatelink/create-endpoint-service.html)」を参照してください。  
**例 2: Gateway Load Balancer エンドポイントのエンドポイントサービス設定を作成するには**  
次の `create-vpc-endpoint-service-configuration` の例では、Gateway Load Balancer `GWLBService` を使用して VPC エンドポイントサービス設定を作成します。Gateway Load Balancer エンドポイントを介してサービスに接続するリクエストは自動的に承諾されます。  

```
aws ec2 create-vpc-endpoint-service-configuration \
    --gateway-load-balancer-arns arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/gwy/GWLBService/123123123123abcc \
    --no-acceptance-required
```
出力:  

```
{
    "ServiceConfiguration": {
        "ServiceType": [
            {
                "ServiceType": "GatewayLoadBalancer"
            }
        ],
        "ServiceId": "vpce-svc-123123a1c43abc123",
        "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-123123a1c43abc123",
        "ServiceState": "Available",
        "AvailabilityZones": [
            "us-east-1d"
        ],
        "AcceptanceRequired": false,
        "ManagesVpcEndpoints": false,
        "GatewayLoadBalancerArns": [
            "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/gwy/GWLBService/123123123123abcc"
        ]
    }
}
```
詳細については、*AWS PrivateLink ユーザーガイド*の「[Gateway Load Balancer エンドポイントサービスの作成](https://docs.aws.amazon.com/vpc/latest/privatelink/create-gateway-load-balancer-endpoint-service.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpcEndpointServiceConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpc-endpoint-service-configuration.html)」を参照してください。

### `create-vpc-endpoint`
<a name="ec2_CreateVpcEndpoint_cli_2_topic"></a>

次のコード例は、`create-vpc-endpoint` を使用する方法を示しています。

**AWS CLI**  
**例 1: ゲートウェイエンドポイントを作成するには**  
次の `create-vpc-endpoint` の例では、`us-east-1` リージョン内の VPC `vpc-1a2b3c4d` と Amazon S3 の間にゲートウェイ VPC エンドポイントを作成し、ルートテーブル `rtb-11aa22bb` をそのエンドポイントに関連付けます。  

```
aws ec2 create-vpc-endpoint \
    --vpc-id vpc-1a2b3c4d \
    --service-name com.amazonaws.us-east-1.s3 \
    --route-table-ids rtb-11aa22bb
```
出力:  

```
{
    "VpcEndpoint": {
        "PolicyDocument": "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":\"\*\",\"Action\":\"\*\",\"Resource\":\"\*\"}]}",
        "VpcId": "vpc-1a2b3c4d",
        "State": "available",
        "ServiceName": "com.amazonaws.us-east-1.s3",
        "RouteTableIds": [
            "rtb-11aa22bb"
        ],
        "VpcEndpointId": "vpc-1a2b3c4d",
        "CreationTimestamp": "2015-05-15T09:40:50Z"
    }
}
```
詳細については、*AWS PrivateLink ユーザーガイド*の「[ゲートウェイエンドポイントを作成する](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html#create-gateway-endpoint-s3)」を参照してください。  
**例 2: インターフェイスエンドポイントを作成するには**  
次の `create-vpc-endpoint` の例では、`us-east-1` リージョン内の VPC `vpc-1a2b3c4d` と Amazon S3 の間にインターフェイス VPC エンドポイントを作成します。コマンドにより、サブネット `subnet-1a2b3c4d` にエンドポイントが作成され、セキュリティグループ `sg-1a2b3c4d` に関連付けられ、「サービス」というキーと「S3」という値を持つタグが追加されます。  

```
aws ec2 create-vpc-endpoint \
    --vpc-id vpc-1a2b3c4d \
    --vpc-endpoint-type Interface \
    --service-name com.amazonaws.us-east-1.s3 \
    --subnet-ids subnet-7b16de0c \
    --security-group-id sg-1a2b3c4d \
    --tag-specifications ResourceType=vpc-endpoint,Tags=[{Key=service,Value=S3}]
```
出力:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-1a2b3c4d5e6f1a2b3",
        "VpcEndpointType": "Interface",
        "VpcId": "vpc-1a2b3c4d",
        "ServiceName": "com.amazonaws.us-east-1.s3",
        "State": "pending",
        "RouteTableIds": [],
        "SubnetIds": [
            "subnet-1a2b3c4d"
        ],
        "Groups": [
            {
                "GroupId": "sg-1a2b3c4d",
                "GroupName": "default"
            }
        ],
        "PrivateDnsEnabled": false,
        "RequesterManaged": false,
        "NetworkInterfaceIds": [
            "eni-0b16f0581c8ac6877"
        ],
        "DnsEntries": [
            {
                "DnsName": "*.vpce-1a2b3c4d5e6f1a2b3-9hnenorg.s3.us-east-1.vpce.amazonaws.com",
                "HostedZoneId": "Z7HUB22UULQXV"
            },
            {
                "DnsName": "*.vpce-1a2b3c4d5e6f1a2b3-9hnenorg-us-east-1c.s3.us-east-1.vpce.amazonaws.com",
                "HostedZoneId": "Z7HUB22UULQXV"
            }
        ],
        "CreationTimestamp": "2021-03-05T14:46:16.030000+00:00",
        "Tags": [
            {
                "Key": "service",
                "Value": "S3"
            }
        ],
        "OwnerId": "123456789012"
    }
}
```
詳細については、*AWS PrivateLink ユーザーガイド*の「[インターフェイス VPC エンドポイントを作成する](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)」を参照してください。  
**例 3: Gateway Load Balancer エンドポイントを作成するには**  
次の `create-vpc-endpoint` の例では、VPC `vpc-111122223333aabbc` と、Gateway Load Balancer を使用して設定されたサービスの間に Gateway Load Balancer エンドポイントを作成します。  

```
aws ec2 create-vpc-endpoint \
    --service-name com.amazonaws.vpce.us-east-1.vpce-svc-123123a1c43abc123 \
    --vpc-endpoint-type GatewayLoadBalancer \
    --vpc-id vpc-111122223333aabbc \
    --subnet-ids subnet-0011aabbcc2233445
```
出力:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-aabbaabbaabbaabba",
        "VpcEndpointType": "GatewayLoadBalancer",
        "VpcId": "vpc-111122223333aabbc",
        "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-123123a1c43abc123",
        "State": "pending",
        "SubnetIds": [
            "subnet-0011aabbcc2233445"
        ],
        "RequesterManaged": false,
        "NetworkInterfaceIds": [
            "eni-01010120203030405"
        ],
        "CreationTimestamp": "2020-11-11T08:06:03.522Z",
        "OwnerId": "123456789012"
    }
}
```
詳細については、*AWS PrivateLink ユーザーガイド*の「[Gateway Load Balancer エンドポイント](https://docs.aws.amazon.com/vpc/latest/privatelink/gateway-load-balancer-endpoints.html)」を参照してください。  
**例 4: リソースエンドポイントを作成するには**  
次の `create-vpc-endpoint` の例では、リソースエンドポイントを作成します。  

```
aws ec2 create-vpc-endpoint \
    --vpc-endpoint-type Resource \
    --vpc-id vpc-111122223333aabbc \
    --subnet-ids subnet-0011aabbcc2233445 \
    --resource-configuration-arn arn:aws:vpc-lattice-us-east-1:123456789012:resourceconfiguration/rcfg-0123abcde98765432
```
出力:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-00939a7ed9EXAMPLE",
        "VpcEndpointType": "Resource",
        "VpcId": "vpc-111122223333aabbc",
        "State": "Pending",
        "SubnetIds": [
            "subnet-0011aabbcc2233445"
        ],
        "Groups": [
            {
                "GroupId": "sg-03e2f15fbfc09b000",
                "GroupName": "default"
            }
        ],
        "IpAddressType": "IPV4",
        "PrivateDnsEnabled": false,
        "CreationTimestamp": "2025-02-06T23:38:49.525000+00:00",
        "Tags": [],
        "OwnerId": "123456789012",
        "ResourceConfigurationArn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-0123abcde98765432"
    }
}
```
詳細については、「*AWS PrivateLink ユーザーガイド*」の「[Resource endpoints](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-access-resources.html)」を参照してください。  
**例 5: サービスネットワークエンドポイントを作成するには**  
次の `create-vpc-endpoint` の例では、サービスネットワークエンドポイントを作成します。  

```
aws ec2 create-vpc-endpoint \
    --vpc-endpoint-type ServiceNetwork \
    --vpc-id vpc-111122223333aabbc \
    --subnet-ids subnet-0011aabbcc2233445 \
    --service-network-arn arn:aws:vpc-lattice:us-east-1:123456789012:servicenetwork/sn-0101abcd5432abcd0 \
    --security-group-ids sg-0123456789012abcd
```
出力:  

```
{
    "VpcEndpoint": {
        "VpcEndpointId": "vpce-0f00567fa8EXAMPLE",
        "VpcEndpointType": "ServiceNetwork",
        "VpcId": "vpc-111122223333aabbc",
        "State": "Pending",
        "SubnetIds": [
            "subnet-0011aabbcc2233445"
        ],
        "Groups": [
            {
                "GroupId": "sg-0123456789012abcd",
                "GroupName": "my-security-group"
            }
        ],
        "IpAddressType": "IPV4",
        "PrivateDnsEnabled": false,
        "CreationTimestamp": "2025-02-06T23:44:20.449000+00:00",
        "Tags": [],
        "OwnerId": "123456789012",
        "ServiceNetworkArn": "arn:aws:vpc-lattice:us-east-1:123456789012:servicenetwork/sn-0101abcd5432abcd0"
    }
}
```
詳細については、「*AWS PrivateLink ユーザーガイド*」の「[Service network endpoints](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-access-service-networks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpcEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpc-endpoint.html)」を参照してください。

### `create-vpc-peering-connection`
<a name="ec2_CreateVpcPeeringConnection_cli_2_topic"></a>

次のコード例は、`create-vpc-peering-connection` を使用する方法を示しています。

**AWS CLI**  
**VPC 間の VPC ピアリング接続を作成するには**  
この例では、vpc-1a2b3c4d と vpc-11122233 という VPC 間のピアリング接続をリクエストします。  
コマンド:  

```
aws ec2 create-vpc-peering-connection --vpc-id vpc-1a2b3c4d --peer-vpc-id vpc-11122233
```
出力:  

```
{
    "VpcPeeringConnection": {
        "Status": {
            "Message": "Initiating Request to 444455556666",
            "Code": "initiating-request"
        },
        "Tags": [],
        "RequesterVpcInfo": {
            "OwnerId": "444455556666",
            "VpcId": "vpc-1a2b3c4d",
            "CidrBlock": "10.0.0.0/28"
        },
        "VpcPeeringConnectionId": "pcx-111aaa111",
        "ExpirationTime": "2014-04-02T16:13:36.000Z",
        "AccepterVpcInfo": {
            "OwnerId": "444455556666",
            "VpcId": "vpc-11122233"
        }
    }
}
```
**別のアカウントの VPC との VPC ピアリング接続を作成するには**  
この例では、VPC (vpc-1a2b3c4d) と AWS アカウント に属する VPC (vpc-11122233) 間のピアリング接続をリクエストします123456789012。  
コマンド:  

```
aws ec2 create-vpc-peering-connection --vpc-id vpc-1a2b3c4d --peer-vpc-id vpc-11122233 --peer-owner-id 123456789012
```
**異なるリージョンの VPC との VPC ピアリング接続を作成するには**  
この例では、現在のリージョンの VPC (vpc-1a2b3c4d) と、`us-west-2` リージョンのアカウント内にある VPC (vpc-11122233) 間のピアリング接続をリクエストします。  
コマンド:  

```
aws ec2 create-vpc-peering-connection --vpc-id vpc-1a2b3c4d --peer-vpc-id vpc-11122233 --peer-region us-west-2
```
この例では、現在のリージョン (vpc-1a2b3c4d) の VPC と、`us-west-2`リージョンにある AWS アカウント 123456789012 に属する VPC (vpc-11122233) 間のピアリング接続をリクエストします。  
コマンド:  

```
aws ec2 create-vpc-peering-connection --vpc-id vpc-1a2b3c4d --peer-vpc-id vpc-11122233 --peer-owner-id 123456789012 --peer-region us-west-2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpcPeeringConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpc-peering-connection.html)」を参照してください。

### `create-vpc`
<a name="ec2_CreateVpc_cli_2_topic"></a>

次のコード例は、`create-vpc` を使用する方法を示しています。

**AWS CLI**  
**例 1: VPC を作成するには**  
次の `create-vpc` の例では、指定された IPv4 CIDR ブロックと Name タグを持つ VPC を作成しています。  

```
aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --tag-specifications ResourceType=vpc,Tags=[{Key=Name,Value=MyVpc}]
```
出力:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-5EXAMPLE",
        "State": "pending",
        "VpcId": "vpc-0a60eb65b4EXAMPLE",
        "OwnerId": "123456789012",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-07501b79ecEXAMPLE",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false,
        "Tags": [
            {
                "Key": "Name",
                "Value": MyVpc"
            }
        ]
    }
}
```
**例 2: 専用テナンシーを持つ VPC を作成するには**  
次の `create-vpc` の例では、指定された IPv4 CIDR ブロックと専用テナンシーを持つ VPC を作成しています。  

```
aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --instance-tenancy dedicated
```
出力:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-19edf471",
        "State": "pending",
        "VpcId": "vpc-0a53287fa4EXAMPLE",
        "OwnerId": "111122223333",
        "InstanceTenancy": "dedicated",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-00b24cc1c2EXAMPLE",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false
    }
}
```
**例 3: IPv6 CIDR ブロックで VPC を作成するには**  
次の `create-vpc` の例では、Amazon が提供する IPv6 CIDR ブロックを使用して、VPC を作成しています。  

```
aws ec2 create-vpc \
    --cidr-block 10.0.0.0/16 \
    --amazon-provided-ipv6-cidr-block
```
出力:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.0.0/16",
        "DhcpOptionsId": "dopt-dEXAMPLE",
        "State": "pending",
        "VpcId": "vpc-0fc5e3406bEXAMPLE",
        "OwnerId": "123456789012",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-068432c60bEXAMPLE",
                "Ipv6CidrBlock": "",
                "Ipv6CidrBlockState": {
                    "State": "associating"
                },
                "Ipv6Pool": "Amazon",
                "NetworkBorderGroup": "us-west-2"
            }
        ],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-0669f8f9f5EXAMPLE",
                "CidrBlock": "10.0.0.0/16",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false
    }
}
```
**例 4: IPAM プールの CIDR を使って VPC を作成するには**  
次の `create-vpc` の例では、Amazon VPC IP Address Manager (IPAM) プールの CIDR を使用して VPC を作成しています。  
Linux および macOS:  

```
aws ec2 create-vpc \
    --ipv4-ipam-pool-id ipam-pool-0533048da7d823723 \
    --tag-specifications ResourceType=vpc,Tags='[{Key=Environment,Value="Preprod"},{Key=Owner,Value="Build Team"}]'
```
Windows:  

```
aws ec2 create-vpc ^
    --ipv4-ipam-pool-id ipam-pool-0533048da7d823723 ^
    --tag-specifications ResourceType=vpc,Tags=[{Key=Environment,Value="Preprod"},{Key=Owner,Value="Build Team"}]
```
出力:  

```
{
    "Vpc": {
        "CidrBlock": "10.0.1.0/24",
        "DhcpOptionsId": "dopt-2afccf50",
        "State": "pending",
        "VpcId": "vpc-010e1791024eb0af9",
        "OwnerId": "123456789012",
        "InstanceTenancy": "default",
        "Ipv6CidrBlockAssociationSet": [],
        "CidrBlockAssociationSet": [
            {
                "AssociationId": "vpc-cidr-assoc-0a77de1d803226d4b",
                "CidrBlock": "10.0.1.0/24",
                "CidrBlockState": {
                    "State": "associated"
                }
            }
        ],
        "IsDefault": false,
        "Tags": [
            {
                "Key": "Environment",
                "Value": "Preprod"
            },
            {
                "Key": "Owner",
                "Value": "Build Team"
            }
        ]
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[IPAM プール CIDR を使用する VPC を作成する](https://docs.aws.amazon.com/vpc/latest/ipam/create-vpc-ipam.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpc.html)」を参照してください。

### `create-vpn-connection-route`
<a name="ec2_CreateVpnConnectionRoute_cli_2_topic"></a>

次のコード例は、`create-vpn-connection-route` を使用する方法を示しています。

**AWS CLI**  
**VPN 接続の静的ルートを作成するには**  
この例では、指定された VPN 接続に対して静的ルートを作成しています。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 create-vpn-connection-route --vpn-connection-id vpn-40f41529 --destination-cidr-block 11.12.0.0/16
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpnConnectionRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpn-connection-route.html)」を参照してください。

### `create-vpn-connection`
<a name="ec2_CreateVpnConnection_cli_2_topic"></a>

次のコード例は、`create-vpn-connection` を使用する方法を示しています。

**AWS CLI**  
**例 1: 動的ルーティングを使用して VPN 接続を作成するには**  
次の `create-vpn-connection` の例では、指定した仮想プライベートゲートウェイと指定したカスタマーゲートウェイの間に VPN 接続を作成し、VPN 接続にタグを適用します。出力には、カスタマーゲートウェイデバイスの設定情報が XML 形式で含まれます。  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --customer-gateway-id cgw-001122334455aabbc \
    --vpn-gateway-id vgw-1a1a1a1a1a1a2b2b2 \
    --tag-specification 'ResourceType=vpn-connection,Tags=[{Key=Name,Value=BGP-VPN}]'
```
出力:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "...configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-123123123123abcab",
        "VpnGatewayId": "vgw-1a1a1a1a1a1a2b2b2",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": false,
            "LocalIpv4NetworkCidr": "0.0.0.0/0",
            "RemoteIpv4NetworkCidr": "0.0.0.0/0",
            "TunnelInsideIpVersion": "ipv4",
            "TunnelOptions": [
                {},
                {}
            ]
        },
        "Routes": [],
        "Tags": [
             {
                "Key": "Name",
                "Value": "BGP-VPN"
            }
        ]
    }
}
```
詳細については、[AWS 「 Site-to-Site VPN ユーザーガイド](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html)*AWS 」のSite-to-Site VPN* works」を参照してください。  
**例 2: 静的ルーティングを使用して VPN 接続を作成するには**  
次の `create-vpn-connection` の例では、指定した仮想プライベートゲートウェイと指定したカスタマーゲートウェイの間に VPN 接続を作成します。オプションで静的ルーティングを指定します。出力には、カスタマーゲートウェイデバイスの設定情報が XML 形式で含まれます。  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --customer-gateway-id cgw-001122334455aabbc \
    --vpn-gateway-id vgw-1a1a1a1a1a1a2b2b2 \
    --options "{\"StaticRoutesOnly\":true}"
```
出力:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "..configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-123123123123abcab",
        "VpnGatewayId": "vgw-1a1a1a1a1a1a2b2b2",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": true,
            "LocalIpv4NetworkCidr": "0.0.0.0/0",
            "RemoteIpv4NetworkCidr": "0.0.0.0/0",
            "TunnelInsideIpVersion": "ipv4",
            "TunnelOptions": [
                {},
                {}
            ]
        },
        "Routes": [],
        "Tags": []
    }
}
```
詳細については、[AWS 「 Site-to-Site VPN ユーザーガイド](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html)*AWS 」のSite-to-Site VPN* works」を参照してください。  
**例 3: VPN 接続を作成し、CIDR 内で独自のキーと事前共有キーを指定するには**  
次の `create-vpn-connection` の例では、VPN 接続を作成し、内部 IP アドレス CIDR ブロック、および各トンネルのカスタム事前共有キーを指定します。指定された値は `CustomerGatewayConfiguration` 情報に返されます。  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --customer-gateway-id cgw-001122334455aabbc \
    --vpn-gateway-id vgw-1a1a1a1a1a1a2b2b2 \
    --options TunnelOptions='[{TunnelInsideCidr=169.254.12.0/30,PreSharedKey=ExamplePreSharedKey1},{TunnelInsideCidr=169.254.13.0/30,PreSharedKey=ExamplePreSharedKey2}]'
```
出力:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "..configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-123123123123abcab",
        "VpnGatewayId": "vgw-1a1a1a1a1a1a2b2b2",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": false,
            "LocalIpv4NetworkCidr": "0.0.0.0/0",
            "RemoteIpv4NetworkCidr": "0.0.0.0/0",
            "TunnelInsideIpVersion": "ipv4",
            "TunnelOptions": [
                {
                    "OutsideIpAddress": "203.0.113.3",
                    "TunnelInsideCidr": "169.254.12.0/30",
                    "PreSharedKey": "ExamplePreSharedKey1"
                },
                {
                    "OutsideIpAddress": "203.0.113.5",
                    "TunnelInsideCidr": "169.254.13.0/30",
                    "PreSharedKey": "ExamplePreSharedKey2"
                }
            ]
        },
        "Routes": [],
        "Tags": []
    }
}
```
詳細については、[AWS 「 Site-to-Site VPN ユーザーガイド](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html)*AWS 」のSite-to-Site VPN* works」を参照してください。  
**例 4: IPv6 トラフィックをサポートする VPN 接続を作成するには**  
次の `create-vpn-connection` の例では、指定した Transit Gateway と指定したカスタマーゲートウェイの間に IPv6 トラフィックをサポートする VPN 接続を作成します。両方のトンネルのトンネルオプションは、 が IKE ネゴシエーションを開始 AWS する必要があることを指定します。  

```
aws ec2 create-vpn-connection \
    --type ipsec.1 \
    --transit-gateway-id tgw-12312312312312312 \
    --customer-gateway-id cgw-001122334455aabbc \
    --options TunnelInsideIpVersion=ipv6,TunnelOptions=[{StartupAction=start},{StartupAction=start}]
```
出力:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "..configuration information...",
        "CustomerGatewayId": "cgw-001122334455aabbc",
        "Category": "VPN",
        "State": "pending",
        "VpnConnectionId": "vpn-11111111122222222",
        "TransitGatewayId": "tgw-12312312312312312",
        "Options": {
            "EnableAcceleration": false,
            "StaticRoutesOnly": false,
            "LocalIpv6NetworkCidr": "::/0",
            "RemoteIpv6NetworkCidr": "::/0",
            "TunnelInsideIpVersion": "ipv6",
            "TunnelOptions": [
                {
                    "OutsideIpAddress": "203.0.113.3",
                    "StartupAction": "start"
                },
                {
                    "OutsideIpAddress": "203.0.113.5",
                    "StartupAction": "start"
                }
            ]
        },
        "Routes": [],
        "Tags": []
    }
}
```
詳細については、[AWS 「 Site-to-Site VPN ユーザーガイド](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html)*AWS 」のSite-to-Site VPN* works」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpnConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpn-connection.html)」を参照してください。

### `create-vpn-gateway`
<a name="ec2_CreateVpnGateway_cli_2_topic"></a>

次のコード例は、`create-vpn-gateway` を使用する方法を示しています。

**AWS CLI**  
**仮想プライベートゲートウェイを作成するには**  
この例では、仮想プライベートゲートウェイを作成します。  
コマンド:  

```
aws ec2 create-vpn-gateway --type ipsec.1
```
出力:  

```
{
    "VpnGateway": {
        "AmazonSideAsn": 64512,
        "State": "available",
        "Type": "ipsec.1",
        "VpnGatewayId": "vgw-9a4cacf3",
        "VpcAttachments": []
    }
}
```
**特定の Amazon 側の ASN を使用して仮想プライベートゲートウェイを作成するには**  
この例では、仮想プライベートゲートウェイを作成し、BGP セッションの Amazon 側に AS 番号 (ASN) を指定します。  
コマンド:  

```
aws ec2 create-vpn-gateway --type ipsec.1 --amazon-side-asn 65001
```
出力:  

```
{
    "VpnGateway": {
        "AmazonSideAsn": 65001,
        "State": "available",
        "Type": "ipsec.1",
        "VpnGatewayId": "vgw-9a4cacf3",
        "VpcAttachments": []
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-vpn-gateway.html)」を参照してください。

### `delete-carrier-gateway`
<a name="ec2_DeleteCarrierGateway_cli_2_topic"></a>

次のコード例は、`delete-carrier-gateway` を使用する方法を示しています。

**AWS CLI**  
**キャリアゲートウェイを削除するには**  
次の `delete-carrier-gateway` の例では、指定したキャリアゲートウェイを削除します。  

```
aws ec2 delete-carrier-gateway \
    --carrier-gateway-id cagw-0465cdEXAMPLE1111
```
出力:  

```
{
    "CarrierGateway": {
        "CarrierGatewayId": "cagw-0465cdEXAMPLE1111",
        "VpcId": "vpc-0c529aEXAMPLE1111",
        "State": "deleting",
        "OwnerId": "123456789012"
    }
}
```
詳細については、「*Amazon Virtual Private Cloud ユーザーガイド*」の「[Carrier gateways](https://docs.aws.amazon.com/vpc/latest/userguide/Carrier_Gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCarrierGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-carrier-gateway.html)」を参照してください。

### `delete-client-vpn-endpoint`
<a name="ec2_DeleteClientVpnEndpoint_cli_2_topic"></a>

次のコード例は、`delete-client-vpn-endpoint` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントを削除するには**  
次の `delete-client-vpn-endpoint` の例では、指定したクライアント VPN エンドポイントを削除します。  

```
aws ec2 delete-client-vpn-endpoint \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "Status": {
        "Code": "deleting"
    }
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client VPN Endpoints](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteClientVpnEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-client-vpn-endpoint.html)」を参照してください。

### `delete-client-vpn-route`
<a name="ec2_DeleteClientVpnRoute_cli_2_topic"></a>

次のコード例は、`delete-client-vpn-route` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントのルートを削除するには**  
次の `delete-client-vpn-route` の例では、クライアント VPN エンドポイントの指定されたサブネット用の `0.0.0.0/0` ルートを削除します。  

```
aws ec2 delete-client-vpn-route \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --destination-cidr-block 0.0.0.0/0 \
    --target-vpc-subnet-id subnet-0123456789abcabca
```
出力:  

```
{
    "Status": {
        "Code": "deleting"
    }
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Routes](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteClientVpnRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-client-vpn-route.html)」を参照してください。

### `delete-coip-cidr`
<a name="ec2_DeleteCoipCidr_cli_2_topic"></a>

次のコード例は、`delete-coip-cidr` を使用する方法を示しています。

**AWS CLI**  
**顧客所有の IP (CoIP) アドレスの範囲を削除するには**  
次の `delete-coip-cidr` の例では、指定した CoIP プールに指定した CoIP アドレスの範囲を削除します。  

```
aws ec2 delete-coip-cidr \
    --cidr 14.0.0.0/24 \
    --coip-pool-id ipv4pool-coip-1234567890abcdefg
```
出力:  

```
{
    "CoipCidr": {
        "Cidr": "14.0.0.0/24",
        "CoipPoolId": "ipv4pool-coip-1234567890abcdefg",
        "LocalGatewayRouteTableId": "lgw-rtb-abcdefg1234567890"
    }
}
```
CoIP の詳細については、「*AWS Outposts ユーザーガイド*」の「[カスタマー所有の IP アドレス](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#ip-addressing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-coip-cidr.html)」を参照してください。

### `delete-coip-pool`
<a name="ec2_DeleteCoipPool_cli_2_topic"></a>

次のコード例は、`delete-coip-pool` を使用する方法を示しています。

**AWS CLI**  
**顧客所有の IP (CoIP) アドレスのプールを削除するには**  
次の `delete-coip-pool` の例では、CoIP アドレスの CoIP プールを削除します。  

```
aws ec2 delete-coip-pool \
    --coip-pool-id ipv4pool-coip-1234567890abcdefg
```
出力:  

```
{
    "CoipPool": {
        "PoolId": "ipv4pool-coip-1234567890abcdefg",
        "LocalGatewayRouteTableId": "lgw-rtb-abcdefg1234567890",
        "PoolArn": "arn:aws:ec2:us-west-2:123456789012:coip-pool/ipv4pool-coip-1234567890abcdefg"
    }
}
```
CoIP の詳細については、「*AWS Outposts ユーザーガイド*」の「[カスタマー所有の IP アドレス](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#ip-addressing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCoipPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-coip-pool.html)」を参照してください。

### `delete-customer-gateway`
<a name="ec2_DeleteCustomerGateway_cli_2_topic"></a>

次のコード例は、`delete-customer-gateway` を使用する方法を示しています。

**AWS CLI**  
**カスタマーゲートウェイを削除するには**  
この例では、指定されたカスタマーゲートウェイを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-customer-gateway --customer-gateway-id cgw-0e11f167
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCustomerGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-customer-gateway.html)」を参照してください。

### `delete-dhcp-options`
<a name="ec2_DeleteDhcpOptions_cli_2_topic"></a>

次のコード例は、`delete-dhcp-options` を使用する方法を示しています。

**AWS CLI**  
**DHCP オプションセットを削除するには**  
この例では、指定された DHCP オプションのセットを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-dhcp-options --dhcp-options-id dopt-d9070ebb
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-dhcp-options.html)」を参照してください。

### `delete-egress-only-internet-gateway`
<a name="ec2_DeleteEgressOnlyInternetGateway_cli_2_topic"></a>

次のコード例は、`delete-egress-only-internet-gateway` を使用する方法を示しています。

**AWS CLI**  
**Egress-Only インターネットゲートウェイを削除するには**  
この例では、指定された Egress-Only インターネットゲートウェイを削除します。  
コマンド:  

```
aws ec2 delete-egress-only-internet-gateway --egress-only-internet-gateway-id eigw-01eadbd45ecd7943f
```
出力:  

```
{
  "ReturnCode": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEgressOnlyInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-egress-only-internet-gateway.html)」を参照してください。

### `delete-fleets`
<a name="ec2_DeleteFleets_cli_2_topic"></a>

次のコード例は、`delete-fleets` を使用する方法を示しています。

**AWS CLI**  
**例 1: EC2 フリートを削除し、関連付けられたインスタンスを終了するには**  
次の `delete-fleets` の例では、EC2 フリートを削除し、関連付けられたオンデマンドインスタンスとスポットインスタンスを終了します。  

```
aws ec2 delete-fleets \
    --fleet-ids fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE \
    --terminate-instances
```
出力:  

```
{
    "SuccessfulFleetDeletions": [
        {
            "CurrentFleetState": "deleted_terminating",
            "PreviousFleetState": "active",
            "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE"
        }
    ],
    "UnsuccessfulFleetDeletions": []
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Delete an EC2 Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-ec2-fleet.html#delete-fleet)」を参照してください。  
**例 2: 関連付けられたインスタンスを終了せずに EC2 フリートを削除するには**  
次の `delete-fleets` の例では、関連付けられたオンデマンドインスタンスとスポットインスタンスを終了しないで、EC2 フリートを削除します。  

```
aws ec2 delete-fleets \
    --fleet-ids fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE \
    --no-terminate-instances
```
出力:  

```
{
    "SuccessfulFleetDeletions": [
        {
            "CurrentFleetState": "deleted_running",
            "PreviousFleetState": "active",
            "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE"
        }
    ],
    "UnsuccessfulFleetDeletions": []
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Delete an EC2 Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-ec2-fleet.html#delete-fleet)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFleets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-fleets.html)」を参照してください。

### `delete-flow-logs`
<a name="ec2_DeleteFlowLogs_cli_2_topic"></a>

次のコード例は、`delete-flow-logs` を使用する方法を示しています。

**AWS CLI**  
**フローログを削除するには**  
次の `delete-flow-logs` の例では、指定したフローログを削除します。  

```
aws ec2 delete-flow-logs --flow-log-id fl-11223344556677889
```
出力:  

```
{
    "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFlowLogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-flow-logs.html)」を参照してください。

### `delete-fpga-image`
<a name="ec2_DeleteFpgaImage_cli_2_topic"></a>

次のコード例は、`delete-fpga-image` を使用する方法を示しています。

**AWS CLI**  
**Amazon FPGA イメージを削除するには**  
この例では、指定されたキューを削除します。  
コマンド:  

```
aws ec2 delete-fpga-image --fpga-image-id afi-06b12350a123fbabc
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFpgaImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-fpga-image.html)」を参照してください。

### `delete-instance-connect-endpoint`
<a name="ec2_DeleteInstanceConnectEndpoint_cli_2_topic"></a>

次のコード例は、`delete-instance-connect-endpoint` を使用する方法を示しています。

**AWS CLI**  
**EC2 Instance Connect エンドポイントを削除するには**  
次の `delete-instance-connect-endpoint` の例では、指定した EC2 Instance Connect エンドポイントを削除します。  

```
aws ec2 delete-instance-connect-endpoint \
    --instance-connect-endpoint-id eice-03f5e49b83924bbc7
```
出力:  

```
{
    "InstanceConnectEndpoint": {
        "OwnerId": "111111111111",
        "InstanceConnectEndpointId": "eice-0123456789example",
        "InstanceConnectEndpointArn": "arn:aws:ec2:us-east-1:111111111111:instance-connect-endpoint/eice-0123456789example",
        "State": "delete-in-progress",
        "StateMessage": "",
        "NetworkInterfaceIds": [],
        "VpcId": "vpc-0123abcd",
        "AvailabilityZone": "us-east-1d",
        "CreatedAt": "2023-02-07T12:05:37+00:00",
        "SubnetId": "subnet-0123abcd"
    }
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[EC2 Instance Connect エンドポイントを削除する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/delete-ec2-instance-connect-endpoint.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInstanceConnectEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-instance-connect-endpoint.html)」を参照してください。

### `delete-instance-event-window`
<a name="ec2_DeleteInstanceEventWindow_cli_2_topic"></a>

次のコード例は、`delete-instance-event-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: イベントウィンドウを削除するには**  
次の `delete-instance-event-window` の例では、イベントウィンドウを削除します。  

```
aws ec2 delete-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890
```
出力:  

```
{
    "InstanceEventWindowState": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "State": "deleting"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 2: イベントウィンドウを強制的に削除するには**  
次の `delete-instance-event-window` の例では、イベントウィンドウが現在ターゲットに関連付けられている場合、イベントウィンドウを強制的に削除します。  

```
aws ec2 delete-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --force-delete
```
出力:  

```
{
    "InstanceEventWindowState": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "State": "deleting"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInstanceEventWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-instance-event-window.html)」を参照してください。

### `delete-internet-gateway`
<a name="ec2_DeleteInternetGateway_cli_2_topic"></a>

次のコード例は、`delete-internet-gateway` を使用する方法を示しています。

**AWS CLI**  
**インターネットゲートウェイを削除するには**  
次の `delete-internet-gateway` の例では、指定したインターネットゲートウェイを削除します。  

```
aws ec2 delete-internet-gateway \
    --internet-gateway-id igw-0d0fb496b3EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、*Amazon VPC ユーザーガイド*の「[インターネットゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-internet-gateway.html)」を参照してください。

### `delete-ipam-pool`
<a name="ec2_DeleteIpamPool_cli_2_topic"></a>

次のコード例は、`delete-ipam-pool` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールを削除するには**  
この例では、あなたは IPAM の委任された管理者として、不要になった IPAM プールを削除したいと考えていますが、そのプールには CIDR がプロビジョニングされています。`--cascade` オプションを使用しない限り、CIDR がプロビジョニングされているプールを削除することはできないため、`--cascade` を使用します。  
このリクエストを完了するには:  
[describe-ipam-pools](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-ipam-pools.html) で取得できる IPAM プール ID が必要です。`--region` は IPAM ホームリージョンである必要があります。  
次の の`delete-ipam-pool`例では、 AWS アカウントの IPAM プールを削除します。  

```
aws ec2 delete-ipam-pool \
    --ipam-pool-id ipam-pool-050c886a3ca41cd5b \
    --cascade \
    --region us-east-1
```
出力:  

```
{
    "IpamPool": {
        "OwnerId": "320805250157",
        "IpamPoolId": "ipam-pool-050c886a3ca41cd5b",
        "IpamPoolArn": "arn:aws:ec2::320805250157:ipam-pool/ipam-pool-050c886a3ca41cd5b",
        "IpamScopeArn": "arn:aws:ec2::320805250157:ipam-scope/ipam-scope-0a158dde35c51107b",
        "IpamScopeType": "private",
        "IpamArn": "arn:aws:ec2::320805250157:ipam/ipam-005f921c17ebd5107",
        "IpamRegion": "us-east-1",
        "Locale": "None",
        "PoolDepth": 1,
        "State": "delete-in-progress",
        "Description": "example",
        "AutoImport": false,
        "AddressFamily": "ipv4",
        "AllocationMinNetmaskLength": 0,
        "AllocationMaxNetmaskLength": 32
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Delete a pool](https://docs.aws.amazon.com/vpc/latest/ipam/delete-pool-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIpamPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-ipam-pool.html)」を参照してください。

### `delete-ipam-resource-discovery`
<a name="ec2_DeleteIpamResourceDiscovery_cli_2_topic"></a>

次のコード例は、`delete-ipam-resource-discovery` を使用する方法を示しています。

**AWS CLI**  
**リソース検出を削除するには**  
この例では、あなたは IPAM の委任された管理者として、組織外のアカウントと IPAM を統合するプロセス中に別の IPAM 管理者と共有するために作成した、デフォルト以外のリソース検出を削除したいと考えています。  
このリクエストを完了するには:  
`--region` は、リソース検出を作成したリージョンである必要があります。`"IsDefault": true` の場合、デフォルトのリソース検出を削除することはできません。デフォルトのリソース検出は、IPAM の作成時に自動的に作成されるリソース検出です。デフォルトのリソース検出を削除するには、IPAM を削除する必要があります。  
次の `delete-ipam-resource-discovery` の例では、リソース検出を削除します。  

```
aws ec2 delete-ipam-resource-discovery \
    --ipam-resource-discovery-id ipam-res-disco-0e39761475298ee0f \
    --region us-east-1
```
出力:  

```
{
    "IpamResourceDiscovery": {
        "OwnerId": "149977607591",
        "IpamResourceDiscoveryId": "ipam-res-disco-0e39761475298ee0f",
        "IpamResourceDiscoveryArn": "arn:aws:ec2::149977607591:ipam-resource-discovery/ipam-res-disco-0e39761475298ee0f",
        "IpamResourceDiscoveryRegion": "us-east-1",
        "OperatingRegions": [
            {
                "RegionName": "us-east-1"
            }
        ],
        "IsDefault": false,
        "State": "delete-in-progress"
    }
}
```
リソース検出の詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Work with resource discoveries](https://docs.aws.amazon.com/vpc/latest/ipam/res-disc-work-with.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIpamResourceDiscovery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-ipam-resource-discovery.html)」を参照してください。

### `delete-ipam-scope`
<a name="ec2_DeleteIpamScope_cli_2_topic"></a>

次のコード例は、`delete-ipam-scope` を使用する方法を示しています。

**AWS CLI**  
**IPAM スコープを削除するには**  
次の `delete-ipam-scope` の例では、IPAM を削除します。  

```
aws ec2 delete-ipam-scope \
    --ipam-scope-id ipam-scope-01c1ebab2b63bd7e4
```
出力:  

```
{
    "IpamScope": {
        "OwnerId": "123456789012",
        "IpamScopeId": "ipam-scope-01c1ebab2b63bd7e4",
        "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-01c1ebab2b63bd7e4",
        "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
        "IpamRegion": "us-east-1",
        "IpamScopeType": "private",
        "IsDefault": false,
        "Description": "Example description",
        "PoolCount": 0,
        "State": "delete-in-progress"
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Delete a scope](https://docs.aws.amazon.com/vpc/latest/ipam/delete-scope-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIpamScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-ipam-scope.html)」を参照してください。

### `delete-ipam`
<a name="ec2_DeleteIpam_cli_2_topic"></a>

次のコード例は、`delete-ipam` を使用する方法を示しています。

**AWS CLI**  
**IPAM を削除するには**  
次の `delete-ipam` の例では、IPAM を削除します。  

```
aws ec2 delete-ipam \
    --ipam-id ipam-036486dfa6af58ee0
```
出力:  

```
{
    "Ipam": {
        "OwnerId": "123456789012",
        "IpamId": "ipam-036486dfa6af58ee0",
        "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-036486dfa6af58ee0",
        "IpamRegion": "us-east-1",
        "PublicDefaultScopeId": "ipam-scope-071b8042b0195c183",
        "PrivateDefaultScopeId": "ipam-scope-0807405dece705a30",
        "ScopeCount": 2,
        "OperatingRegions": [
            {
                "RegionName": "us-east-1"
            },
            {
                "RegionName": "us-east-2"
            },
            {
                "RegionName": "us-west-1"
            }
        ],
        "State": "delete-in-progress"
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Delete an IPAM](https://docs.aws.amazon.com/vpc/latest/ipam/delete-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIpam](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-ipam.html)」を参照してください。

### `delete-key-pair`
<a name="ec2_DeleteKeyPair_cli_2_topic"></a>

次のコード例は、`delete-key-pair` を使用する方法を示しています。

**AWS CLI**  
**キーペアを削除するには**  
次の `delete-key-pair` の例では、指定されたキーペアを削除します。  

```
aws ec2 delete-key-pair \
    --key-name my-key-pair
```
出力:  

```
{
    "Return": true,
    "KeyPairId": "key-03c8d3aceb53b507"
}
```
詳細については、「*AWS コマンドラインインターフェイス*」の「[Create and delete key pairs](https://docs.aws.amazon.com/cli/latest/userguide/cli-ec2-keypairs.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-key-pair.html)」を参照してください。

### `delete-launch-template-versions`
<a name="ec2_DeleteLaunchTemplateVersions_cli_2_topic"></a>

次のコード例は、`delete-launch-template-versions` を使用する方法を示しています。

**AWS CLI**  
**起動テンプレートのバージョンを削除するには**  
この例では、指定した起動テンプレートを削除しています。  
コマンド:  

```
aws ec2 delete-launch-template-versions --launch-template-id lt-0abcd290751193123 --versions 1
```
出力:  

```
{
  "UnsuccessfullyDeletedLaunchTemplateVersions": [],
  "SuccessfullyDeletedLaunchTemplateVersions": [
      {
          "LaunchTemplateName": "TestVersion",
          "VersionNumber": 1,
          "LaunchTemplateId": "lt-0abcd290751193123"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLaunchTemplateVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-launch-template-versions.html)」を参照してください。

### `delete-launch-template`
<a name="ec2_DeleteLaunchTemplate_cli_2_topic"></a>

次のコード例は、`delete-launch-template` を使用する方法を示しています。

**AWS CLI**  
**起動テンプレートを削除するには**  
次の例では、指定した起動テンプレートを削除しています。  
コマンド:  

```
aws ec2 delete-launch-template --launch-template-id lt-0abcd290751193123
```
出力:  

```
{
  "LaunchTemplate": {
      "LatestVersionNumber": 2,
      "LaunchTemplateId": "lt-0abcd290751193123",
      "LaunchTemplateName": "TestTemplate",
      "DefaultVersionNumber": 2,
      "CreatedBy": "arn:aws:iam::123456789012:root",
      "CreateTime": "2017-11-23T16:46:25.000Z"
  }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteLaunchTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-launch-template.html)」を参照してください。

### `delete-local-gateway-route-table-virtual-interface-group-association`
<a name="ec2_DeleteLocalGatewayRouteTableVirtualInterfaceGroupAssociation_cli_2_topic"></a>

次のコード例は、`delete-local-gateway-route-table-virtual-interface-group-association` を使用する方法を示しています。

**AWS CLI**  
**仮想インターフェイス (VIF) グループからローカルゲートウェイのルートテーブルの関連付けを解除するには**  
次の `delete-local-gateway-route-table-virtual-interface-group-association` の例では、指定したローカルゲートウェイのルートテーブルと VIF グループ間の関連付けを削除します。  

```
aws ec2 delete-local-gateway-route-table-virtual-interface-group-association \
    --local-gateway-route-table-virtual-interface-group-association-id lgw-vif-grp-assoc-exampleid12345678
```
出力:  

```
{
    "LocalGatewayRouteTableVirtualInterfaceGroupAssociation": {
        "LocalGatewayRouteTableVirtualInterfaceGroupAssociationId": "lgw-vif-grp-assoc-exampleid12345678",
        "LocalGatewayVirtualInterfaceGroupId": "lgw-vif-grp-exampleid0123abcd",
        "LocalGatewayId": "lgw-exampleid11223344",
        "LocalGatewayRouteTableId": "lgw-rtb-exampleidabcd1234",
        "LocalGatewayRouteTableArn": "arn:aws:ec2:us-west-2:111122223333:local-gateway-route-table/lgw-rtb-exampleidabcd1234",
        "OwnerId": "111122223333",
        "State": "disassociating",
        "Tags": []
    }
}
```
詳細については、「*AWS Outposts ユーザーガイド*」の「[VIF group associations](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#vif-group-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLocalGatewayRouteTableVirtualInterfaceGroupAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-local-gateway-route-table-virtual-interface-group-association.html)」を参照してください。

### `delete-local-gateway-route-table-vpc-association`
<a name="ec2_DeleteLocalGatewayRouteTableVpcAssociation_cli_2_topic"></a>

次のコード例は、`delete-local-gateway-route-table-vpc-association` を使用する方法を示しています。

**AWS CLI**  
**VPC からローカルゲートウェイのルートテーブルの関連付けを解除するには**  
次の `delete-local-gateway-route-table-vpc-association` の例では、指定したローカルゲートウェイのルートテーブルと VPC 間の関連付けを削除します。  

```
aws ec2 delete-local-gateway-route-table-vpc-association \
    --local-gateway-route-table-vpc-association-id vpc-example0123456789
```
出力:  

```
{
    "LocalGatewayRouteTableVpcAssociation": {
        "LocalGatewayRouteTableVpcAssociationId": "lgw-vpc-assoc-abcd1234wxyz56789",
        "LocalGatewayRouteTableId": "lgw-rtb-abcdefg1234567890",
        "LocalGatewayRouteTableArn": "arn:aws:ec2:us-west-2:555555555555:local-gateway-route-table/lgw-rtb-abcdefg1234567890",
        "LocalGatewayId": "lgw-exampleid01234567",
        "VpcId": "vpc-example0123456789",
        "OwnerId": "555555555555",
        "State": "disassociating"
    }
}
```
詳細については、「*AWS Outposts ユーザーガイド*」の「[VPC associations](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#vpc-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLocalGatewayRouteTableVpcAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-local-gateway-route-table-vpc-association.html)」を参照してください。

### `delete-local-gateway-route-table`
<a name="ec2_DeleteLocalGatewayRouteTable_cli_2_topic"></a>

次のコード例は、`delete-local-gateway-route-table` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイのルートテーブルを作成するには**  
次の `delete-local-gateway-route-table` の例では、直接 VPC ルーティングモードでローカルゲートウェイのルートテーブルを作成します。  

```
aws ec2 delete-local-gateway-route-table \
    --local-gateway-route-table-id lgw-rtb-abcdefg1234567890
```
出力:  

```
{
    "LocalGatewayRouteTable": {
        "LocalGatewayRouteTableId": "lgw-rtb-abcdefg1234567890",
        "LocalGatewayRouteTableArn": "arn:aws:ec2:us-west-2:111122223333:local-gateway-route-table/lgw-rtb-abcdefg1234567890",
        "LocalGatewayId": "lgw-1a2b3c4d5e6f7g8h9",
        "OutpostArn": "arn:aws:outposts:us-west-2:111122223333:outpost/op-021345abcdef67890",
        "OwnerId": "111122223333",
        "State": "deleting",
        "Tags": [],
        "Mode": "direct-vpc-routing"
    }
}
```
詳細については、「*AWS Outposts ユーザーガイド*」の「[ローカルゲートウェイルートテーブル](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLocalGatewayRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-local-gateway-route-table.html)」を参照してください。

### `delete-local-gateway-route`
<a name="ec2_DeleteLocalGatewayRoute_cli_2_topic"></a>

次のコード例は、`delete-local-gateway-route` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイのルートテーブルからルートを削除するには**  
次の `delete-local-gateway-route` の例では、指定したローカルゲートウェイのルートテーブルから指定したルートを削除します。  

```
aws ec2 delete-local-gateway-route \
    --destination-cidr-block 0.0.0.0/0 \
    --local-gateway-route-table-id lgw-rtb-059615ef7dEXAMPLE
```
出力:  

```
{
    "Route": {
        "DestinationCidrBlock": "0.0.0.0/0",
        "LocalGatewayVirtualInterfaceGroupId": "lgw-vif-grp-07145b276bEXAMPLE",
        "Type": "static",
        "State": "deleted",
        "LocalGatewayRouteTableId": "lgw-rtb-059615ef7EXAMPLE"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLocalGatewayRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-local-gateway-route.html)」を参照してください。

### `delete-managed-prefix-list`
<a name="ec2_DeleteManagedPrefixList_cli_2_topic"></a>

次のコード例は、`delete-managed-prefix-list` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストを削除するには**  
次の `delete-managed-prefix-list` の例では、指定したプレフィックスリストを削除します。  

```
aws ec2 delete-managed-prefix-list \
    --prefix-list-id pl-0123456abcabcabc1
```
出力:  

```
{
    "PrefixList": {
        "PrefixListId": "pl-0123456abcabcabc1",
        "AddressFamily": "IPv4",
        "State": "delete-in-progress",
        "PrefixListArn": "arn:aws:ec2:us-west-2:123456789012:prefix-list/pl-0123456abcabcabc1",
        "PrefixListName": "test",
        "MaxEntries": 10,
        "Version": 1,
        "OwnerId": "123456789012"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Managed prefix lists](https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteManagedPrefixList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-managed-prefix-list.html)」を参照してください。

### `delete-nat-gateway`
<a name="ec2_DeleteNatGateway_cli_2_topic"></a>

次のコード例は、`delete-nat-gateway` を使用する方法を示しています。

**AWS CLI**  
**NAT ゲートウェイを削除するには**  
この例では、NAT ゲートウェイ `nat-04ae55e711cec5680` を削除します。  
コマンド:  

```
aws ec2 delete-nat-gateway --nat-gateway-id nat-04ae55e711cec5680
```
出力:  

```
{
   "NatGatewayId": "nat-04ae55e711cec5680"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNatGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-nat-gateway.html)」を参照してください。

### `delete-network-acl-entry`
<a name="ec2_DeleteNetworkAclEntry_cli_2_topic"></a>

次のコード例は、`delete-network-acl-entry` を使用する方法を示しています。

**AWS CLI**  
**ネットワーク ACL エントリを削除するには**  
この例では、指定されたネットワーク ACL から受信ルール番号 100 を削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 100
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkAclEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-acl-entry.html)」を参照してください。

### `delete-network-acl`
<a name="ec2_DeleteNetworkAcl_cli_2_topic"></a>

次のコード例は、`delete-network-acl` を使用する方法を示しています。

**AWS CLI**  
**ネットワーク ACL を削除するには**  
この例では、指定されたネットワーク ACL を削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-network-acl --network-acl-id acl-5fb85d36
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-acl.html)」を参照してください。

### `delete-network-insights-access-scope-analysis`
<a name="ec2_DeleteNetworkInsightsAccessScopeAnalysis_cli_2_topic"></a>

次のコード例は、`delete-network-insights-access-scope-analysis` を使用する方法を示しています。

**AWS CLI**  
**Network Access Scope の分析を削除するには**  
次の `delete-network-insights-access-scope-analysis` の例では、指定した Network Access Scope の分析を削除します。  

```
aws ec2 delete-network-insights-access-scope-analysis \
    --network-insights-access-scope-analysis-id nisa-01234567891abcdef
```
出力:  

```
{
    "NetworkInsightsAccessScopeAnalysisId": "nisa-01234567891abcdef
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkInsightsAccessScopeAnalysis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-insights-access-scope-analysis.html)」を参照してください。

### `delete-network-insights-access-scope`
<a name="ec2_DeleteNetworkInsightsAccessScope_cli_2_topic"></a>

次のコード例は、`delete-network-insights-access-scope` を使用する方法を示しています。

**AWS CLI**  
**Network Access Scope を削除するには**  
次の `delete-network-insights-access-scope` の例では、指定した Network Access Scope を削除します。  

```
aws ec2 delete-network-insights-access-scope \
    --network-insights-access-scope-id nis-123456789abc01234
```
出力:  

```
{
    "NetworkInsightsAccessScopeId": "nis-123456789abc01234"
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkInsightsAccessScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-insights-access-scope.html)」を参照してください。

### `delete-network-insights-analysis`
<a name="ec2_DeleteNetworkInsightsAnalysis_cli_2_topic"></a>

次のコード例は、`delete-network-insights-analysis` を使用する方法を示しています。

**AWS CLI**  
**パス分析を削除するには**  
次の `delete-network-insights-analysis` の例では、指定した分析を削除します。  

```
aws ec2 delete-network-insights-analysis \
    --network-insights-analysis-id nia-02207aa13eb480c7a
```
出力:  

```
{
    "NetworkInsightsAnalysisId": "nia-02207aa13eb480c7a"
}
```
詳細については、*「Reachability Analyzer* [Guide」の「Getting started using the AWS CLI](https://docs.aws.amazon.com/vpc/latest/reachability/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkInsightsAnalysis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-insights-analysis.html)」を参照してください。

### `delete-network-insights-path`
<a name="ec2_DeleteNetworkInsightsPath_cli_2_topic"></a>

次のコード例は、`delete-network-insights-path` を使用する方法を示しています。

**AWS CLI**  
**パスを削除するには**  
次の `delete-network-insights-path` の例では、指定したパスを削除します。パスを削除する前に、`delete-network-insights-analysis` コマンドを使用してすべての分析を削除する必要があります。  

```
aws ec2 delete-network-insights-path \
    --network-insights-path-id nip-0b26f224f1d131fa8
```
出力:  

```
{
    "NetworkInsightsPathId": "nip-0b26f224f1d131fa8"
}
```
詳細については、*「Reachability Analyzer* [Guide」の「Getting started using the AWS CLI](https://docs.aws.amazon.com/vpc/latest/reachability/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkInsightsPath](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-insights-path.html)」を参照してください。

### `delete-network-interface-permission`
<a name="ec2_DeleteNetworkInterfacePermission_cli_2_topic"></a>

次のコード例は、`delete-network-interface-permission` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイス権限を削除するには**  
この例では、指定されたネットワークインターフェイスのアクセス許可を削除します。  
コマンド:  

```
aws ec2 delete-network-interface-permission --network-interface-permission-id eni-perm-06fd19020ede149ea
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkInterfacePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-interface-permission.html)」を参照してください。

### `delete-network-interface`
<a name="ec2_DeleteNetworkInterface_cli_2_topic"></a>

次のコード例は、`delete-network-interface` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイスを削除するには**  
この例では、指定されたネットワークインターフェイスを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-network-interface --network-interface-id eni-e5aa89a3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-interface.html)」を参照してください。

### `delete-placement-group`
<a name="ec2_DeletePlacementGroup_cli_2_topic"></a>

次のコード例は、`delete-placement-group` を使用する方法を示しています。

**AWS CLI**  
**プレイスメントグループを削除するには**  
このコマンド例では、指定されたプレイスメントグループを削除します。  
コマンド:  

```
aws ec2 delete-placement-group --group-name my-cluster
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePlacementGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-placement-group.html)」を参照してください。

### `delete-queued-reserved-instances`
<a name="ec2_DeleteQueuedReservedInstances_cli_2_topic"></a>

次のコード例は、`delete-queued-reserved-instances` を使用する方法を示しています。

**AWS CLI**  
**キューに入っている購入をキャンセルするには**  
次の `delete-queued-reserved-instances` の例では、指定したリザーブドインスタンス (購入のためにキューに入れられていたもの) を削除します。  

```
aws ec2 delete-queued-reserved-instances \
    --reserved-instances-ids af9f760e-6f91-4559-85f7-4980eexample
```
出力:  

```
{
    "SuccessfulQueuedPurchaseDeletions": [
        {
            "ReservedInstancesId": "af9f760e-6f91-4559-85f7-4980eexample"
        }
    ],
    "FailedQueuedPurchaseDeletions": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteQueuedReservedInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-queued-reserved-instances.html)」を参照してください。

### `delete-route-table`
<a name="ec2_DeleteRouteTable_cli_2_topic"></a>

次のコード例は、`delete-route-table` を使用する方法を示しています。

**AWS CLI**  
**ルートテーブルを削除するには**  
この例では、指定されたルートテーブルを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-route-table --route-table-id rtb-22574640
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-route-table.html)」を参照してください。

### `delete-route`
<a name="ec2_DeleteRoute_cli_2_topic"></a>

次のコード例は、`delete-route` を使用する方法を示しています。

**AWS CLI**  
**ルートを削除するには**  
この例では、指定したルートテーブルから指定したルートを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-route --route-table-id rtb-22574640 --destination-cidr-block 0.0.0.0/0
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-route.html)」を参照してください。

### `delete-security-group`
<a name="ec2_DeleteSecurityGroup_cli_2_topic"></a>

次のコード例は、`delete-security-group` を使用する方法を示しています。

**AWS CLI**  
**[EC2-Classic] セキュリティグループを削除するには**  
この例では、`MySecurityGroup` という名前のセキュリティグループを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-security-group --group-name MySecurityGroup
```
**[EC2-VPC] セキュリティグループを削除するには**  
この例では、`sg-903004f8` という ID のセキュリティグループを削除します。EC2-VPC 用セキュリティグループは名前では参照できないことに注意してください。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-security-group --group-id sg-903004f8
```
詳細については、「*AWS コマンドラインインターフェイスユーザーガイド*」でセキュリティグループの使用方法を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-security-group.html)」を参照してください。

### `delete-snapshot`
<a name="ec2_DeleteSnapshot_cli_2_topic"></a>

次のコード例は、`delete-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットを削除するには**  
このコマンド例は、スナップショット ID が `snap-1234567890abcdef0` のスナップショットを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-snapshot --snapshot-id snap-1234567890abcdef0
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-snapshot.html)」を参照してください。

### `delete-spot-datafeed-subscription`
<a name="ec2_DeleteSpotDatafeedSubscription_cli_2_topic"></a>

次のコード例は、`delete-spot-datafeed-subscription` を使用する方法を示しています。

**AWS CLI**  
**スポットインスタンスデータフィードサブスクリプションをキャンセルするには**  
このコマンド例では、アカウントのスポットデータフィードサブスクリプションを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-spot-datafeed-subscription
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSpotDatafeedSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-spot-datafeed-subscription.html)」を参照してください。

### `delete-subnet-cidr-reservation`
<a name="ec2_DeleteSubnetCidrReservation_cli_2_topic"></a>

次のコード例は、`delete-subnet-cidr-reservation` を使用する方法を示しています。

**AWS CLI**  
**サブネット CIDR 予約を削除するには**  
次の `delete-subnet-cidr-reservation` の例では、指定したサブネット CIDR 予約を削除します。  

```
aws ec2 delete-subnet-cidr-reservation \
    --subnet-cidr-reservation-id scr-044f977c4eEXAMPLE
```
出力:  

```
{
    "DeletedSubnetCidrReservation": {
        "SubnetCidrReservationId": "scr-044f977c4eEXAMPLE",
        "SubnetId": "subnet-03c51e2e6cEXAMPLE",
        "Cidr": "10.1.0.16/28",
        "ReservationType": "prefix",
        "OwnerId": "123456789012"
    }
}
```
詳細については、*Amazon VPC ユーザーガイド*の[サブネット CIDR の予約](https://docs.aws.amazon.com/vpc/latest/userguide/subnet-cidr-reservation.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubnetCidrReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-subnet-cidr-reservation.html)」を参照してください。

### `delete-subnet`
<a name="ec2_DeleteSubnet_cli_2_topic"></a>

次のコード例は、`delete-subnet` を使用する方法を示しています。

**AWS CLI**  
**サブネットを削除するには**  
この例では、指定されたサブネットを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-subnet --subnet-id subnet-9d4a7b6c
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubnet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-subnet.html)」を参照してください。

### `delete-tags`
<a name="ec2_DeleteTags_cli_2_topic"></a>

次のコード例は、`delete-tags` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースからタグを削除するには**  
次の `delete-tags` の例では、指定したイメージからタグ `Stack=Test` を削除します。値とキー名の両方を指定すると、タグの値が指定された値と一致する場合にのみ、タグは削除されます。  

```
aws ec2 delete-tags \
    --resources ami-1234567890abcdef0 \
    --tags Key=Stack,Value=Test
```
タグの値を指定することはオプションです。次の `delete-tags` の例では、タグのタグ値に関係なく、指定したインスタンスからキー名 `purpose` を持つタグを削除します。  

```
aws ec2 delete-tags \
    --resources i-1234567890abcdef0 \
    --tags Key=purpose
```
空の文字列をタグ値として指定すると、タグの値が空の文字列である場合にのみタグが削除されます。次の `delete-tags` の例では、空の文字列を、削除するタグのタグ値として指定します。  

```
aws ec2 delete-tags \
    --resources i-1234567890abcdef0 \
    --tags Key=Name,Value=
```
**例 2: 複数のリソースからタグを削除するには**  
次の `delete-tags` の例では、インスタンスと AMI の両方からタグ「Purpose=Test」を削除します。前の例に示されているように、コマンドのタグ値を省略できます。  

```
aws ec2 delete-tags \
    --resources i-1234567890abcdef0 ami-1234567890abcdef0 \
    --tags Key=Purpose
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-tags.html)」を参照してください。

### `delete-traffic-mirror-filter-rule`
<a name="ec2_DeleteTrafficMirrorFilterRule_cli_2_topic"></a>

次のコード例は、`delete-traffic-mirror-filter-rule` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーフィルタールールを削除するには**  
次の `delete-traffic-mirror-filter-rule` の例では、指定したトラフィックミラーフィルタールールを削除します。  

```
aws ec2 delete-traffic-mirror-filter-rule \
    --traffic-mirror-filter-rule-id tmfr-081f71283bEXAMPLE
```
出力:  

```
{
    "TrafficMirrorFilterRuleId": "tmfr-081f71283bEXAMPLE"
}
```
詳細については、「*AWS トラフィックミラーリングガイド*」の「[Modify Your Traffic Mirror Filter Rules](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-filter.html#modify-traffic-mirroring-filter-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTrafficMirrorFilterRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-traffic-mirror-filter-rule.html)」を参照してください。

### `delete-traffic-mirror-filter`
<a name="ec2_DeleteTrafficMirrorFilter_cli_2_topic"></a>

次のコード例は、`delete-traffic-mirror-filter` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーフィルターを削除するには**  
次の `delete-traffic-mirror-filter` の例では、指定したトラフィックミラーフィルターを削除します。  

```
aws ec2 delete-traffic-mirror-filter \
    --traffic-mirror-filter-id tmf-0be0b25fcdEXAMPLE
```
出力:  

```
{
    "TrafficMirrorFilterId": "tmf-0be0b25fcdEXAMPLE"
}
```
詳細については、「*AWS トラフィックミラーリングガイド*」の「[Delete a Traffic Mirror Filter](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-filter.html#delete-traffic-mirroring-filter)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTrafficMirrorFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-traffic-mirror-filter.html)」を参照してください。

### `delete-traffic-mirror-session`
<a name="ec2_DeleteTrafficMirrorSession_cli_2_topic"></a>

次のコード例は、`delete-traffic-mirror-session` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーセッションを削除するには**  
次の `delete-traffic-mirror-session` の例では、指定したトラフィックミラーセッションを削除します。  

```
aws ec2 delete-traffic-mirror-session \
    --traffic-mirror-session-id tms-0af3141ce5EXAMPLE
```
出力:  

```
{
    "TrafficMirrorSessionId": "tms-0af3141ce5EXAMPLE"
}
```
詳細については、「*AWS トラフィックミラーリングガイド*」の「[Delete a Traffic Mirror Session](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-session.html#delete-traffic-mirroring-session)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTrafficMirrorSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-traffic-mirror-session.html)」を参照してください。

### `delete-traffic-mirror-target`
<a name="ec2_DeleteTrafficMirrorTarget_cli_2_topic"></a>

次のコード例は、`delete-traffic-mirror-target` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーターゲットを削除するには**  
次の `delete-traffic-mirror-target` の例では、指定したトラフィックミラーターゲットを削除します。  

```
aws ec2 delete-traffic-mirror-target \
    --traffic-mirror-target-id tmt-060f48ce9EXAMPLE
```
出力:  

```
{
    "TrafficMirrorTargetId": "tmt-060f48ce9EXAMPLE"
}
```
詳細については、「*AWS トラフィックミラーリングガイド*」の「[Delete a Traffic Mirror Target](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-target.html#delete-traffic-mirroring-target)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTrafficMirrorTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-traffic-mirror-target.html)」を参照してください。

### `delete-transit-gateway-connect-peer`
<a name="ec2_DeleteTransitGatewayConnectPeer_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-connect-peer` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway Connect ピアを削除するには**  
次の `delete-transit-gateway-connect-peer` の例では、指定した Connect ピアを削除します。  

```
aws ec2 delete-transit-gateway-connect-peer \
    --transit-gateway-connect-peer-id tgw-connect-peer-0666adbac4EXAMPLE
```
出力:  

```
{
    "TransitGatewayConnectPeer": {
        "TransitGatewayAttachmentId": "tgw-attach-0f0927767cEXAMPLE",
        "TransitGatewayConnectPeerId": "tgw-connect-peer-0666adbac4EXAMPLE",
        "State": "deleting",
        "CreationTime": "2021-10-13T03:35:17.000Z",
        "ConnectPeerConfiguration": {
            "TransitGatewayAddress": "10.0.0.234",
            "PeerAddress": "172.31.1.11",
            "InsideCidrBlocks": [
                "169.254.6.0/29"
            ],
            "Protocol": "gre",
            "BgpConfigurations": [
                {
                    "TransitGatewayAsn": 64512,
                    "PeerAsn": 64512,
                    "TransitGatewayAddress": "169.254.6.2",
                    "PeerAddress": "169.254.6.1",
                    "BgpStatus": "down"
                },
                {
                    "TransitGatewayAsn": 64512,
                    "PeerAsn": 64512,
                    "TransitGatewayAddress": "169.254.6.3",
                    "PeerAddress": "169.254.6.1",
                    "BgpStatus": "down"
                }
            ]
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway Connect attachments and Transit Gateway Connect peers](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayConnectPeer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-connect-peer.html)」を参照してください。

### `delete-transit-gateway-connect`
<a name="ec2_DeleteTransitGatewayConnect_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-connect` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway Connect アタッチメントを削除するには**  
次の `delete-transit-gateway-connect` の例では、指定した Connect アタッチメントを削除します。  

```
aws ec2 delete-transit-gateway-connect \
    --transit-gateway-attachment-id tgw-attach-037012e5dcEXAMPLE
```
出力:  

```
{
    "TransitGatewayConnect": {
        "TransitGatewayAttachmentId": "tgw-attach-037012e5dcEXAMPLE",
        "TransportTransitGatewayAttachmentId": "tgw-attach-0a89069f57EXAMPLE",
        "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
        "State": "deleting",
        "CreationTime": "2021-03-09T19:59:17+00:00",
        "Options": {
            "Protocol": "gre"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway Connect attachments and Transit Gateway Connect peers](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayConnect](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-connect.html)」を参照してください。

### `delete-transit-gateway-multicast-domain`
<a name="ec2_DeleteTransitGatewayMulticastDomain_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-multicast-domain` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway マルチキャストドメインを削除するには**  
次の `delete-transit-gateway-multicast-domain` の例では、指定したマルチキャストドメインを削除します。  

```
aws ec2 delete-transit-gateway-multicast-domain \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef7EXAMPLE
```
出力:  

```
{
    "TransitGatewayMulticastDomain": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-02bb79002bEXAMPLE",
        "TransitGatewayId": "tgw-0d88d2d0d5EXAMPLE",
        "State": "deleting",
        "CreationTime": "2019-11-20T22:02:03.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Managing multicast domains](https://docs.aws.amazon.com/vpc/latest/tgw/manage-domain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayMulticastDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-multicast-domain.html)」を参照してください。

### `delete-transit-gateway-peering-attachment`
<a name="ec2_DeleteTransitGatewayPeeringAttachment_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-peering-attachment` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ピアリングアタッチメントを削除するには**  
次の `delete-transit-gateway-peering-attachment` の例では、指定した Transit Gateway ピアリングアタッチメントを削除します。  

```
aws ec2 delete-transit-gateway-peering-attachment \
    --transit-gateway-attachment-id tgw-attach-4455667788aabbccd
```
出力:  

```
{
    "TransitGatewayPeeringAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-4455667788aabbccd",
        "RequesterTgwInfo": {
            "TransitGatewayId": "tgw-123abc05e04123abc",
            "OwnerId": "123456789012",
            "Region": "us-west-2"
        },
        "AccepterTgwInfo": {
            "TransitGatewayId": "tgw-11223344aabbcc112",
            "OwnerId": "123456789012",
            "Region": "us-east-2"
        },
        "State": "deleting",
        "CreationTime": "2019-12-09T11:38:31.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit Gateway Peering Attachments](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayPeeringAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-peering-attachment.html)」を参照してください。

### `delete-transit-gateway-policy-table`
<a name="ec2_DeleteTransitGatewayPolicyTable_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-policy-table` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ポリシーテーブルを削除するには**  
次の `delete-transit-gateway-policy-table` の例では、指定した Transit Gateway ポリシーテーブルを削除します。  

```
aws ec2 delete-transit-gateway-policy-table \
    --transit-gateway-policy-table-id tgw-ptb-0a16f134b78668a81
```
出力:  

```
{
    "TransitGatewayPolicyTables": [
        {
            "TransitGatewayPolicyTableId": "tgw-ptb-0a16f134b78668a81",
            "TransitGatewayId": "tgw-067f8505c18f0bd6e",
            "State": "deleting",
            "CreationTime": "2023-11-28T16:36:43+00:00",
            "Tags": []
        }
    ]
}
```
詳細については、「*Transit Gateway ユーザーガイド*」の「[Transit gateway policy tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-policy-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayPolicyTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-policy-table.html)」を参照してください。

### `delete-transit-gateway-prefix-list-reference`
<a name="ec2_DeleteTransitGatewayPrefixListReference_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-prefix-list-reference` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストのリファレンスを削除するには**  
次の `delete-transit-gateway-prefix-list-reference` の例では、指定したプレフィックスリストのリファレンスを削除します。  

```
aws ec2 delete-transit-gateway-prefix-list-reference \
    --transit-gateway-route-table-id tgw-rtb-0123456789abcd123 \
    --prefix-list-id pl-11111122222222333
```
出力:  

```
{
    "TransitGatewayPrefixListReference": {
        "TransitGatewayRouteTableId": "tgw-rtb-0123456789abcd123",
        "PrefixListId": "pl-11111122222222333",
        "PrefixListOwnerId": "123456789012",
        "State": "deleting",
        "Blackhole": false,
        "TransitGatewayAttachment": {
            "TransitGatewayAttachmentId": "tgw-attach-aabbccddaabbccaab",
            "ResourceType": "vpc",
            "ResourceId": "vpc-112233445566aabbc"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Prefix list references](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayPrefixListReference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-prefix-list-reference.html)」を参照してください。

### `delete-transit-gateway-route-table`
<a name="ec2_DeleteTransitGatewayRouteTable_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-route-table` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ルートテーブルを削除するには**  
次の `delete-transit-gateway-route-table` の例では、指定した Transit Gateway ルートテーブルを削除します。  

```
aws ec2  delete-transit-gateway-route-table \
    --transit-gateway-route-table-id tgw-rtb-0b6f6aaa01EXAMPLE
```
出力:  

```
{
    "TransitGatewayRouteTable": {
        "TransitGatewayRouteTableId": "tgw-rtb-0b6f6aaa01EXAMPLE",
        "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
        "State": "deleting",
        "DefaultAssociationRouteTable": false,
        "DefaultPropagationRouteTable": false,
        "CreationTime": "2019-07-17T20:27:26.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Delete a transit gateway route table](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#delete-tgw-route-table)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-route-table.html)」を参照してください。

### `delete-transit-gateway-route`
<a name="ec2_DeleteTransitGatewayRoute_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-route` を使用する方法を示しています。

**AWS CLI**  
**ルートテーブルから CIDR ブロックを削除するには**  
次の `delete-transit-gateway-route` の例では、指定した Transit Gateway ルートテーブルから CIDR ブロックを削除します。  

```
aws ec2 delete-transit-gateway-route \
    --transit-gateway-route-table-id tgw-rtb-0b6f6aaa01EXAMPLE \
    --destination-cidr-block 10.0.2.0/24
```
出力:  

```
{
    "Route": {
        "DestinationCidrBlock": "10.0.2.0/24",
        "TransitGatewayAttachments": [
            {
                "ResourceId": "vpc-0065acced4EXAMPLE",
                "TransitGatewayAttachmentId": "tgw-attach-0b5968d3b6EXAMPLE",
                "ResourceType": "vpc"
            }
        ],
        "Type": "static",
        "State": "deleted"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Delete a static route](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#tgw-delete-static-route)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-route.html)」を参照してください。

### `delete-transit-gateway-vpc-attachment`
<a name="ec2_DeleteTransitGatewayVpcAttachment_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway-vpc-attachment` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway VPC アタッチメントを削除するには**  
次の `delete-transit-gateway-vpc-attachment` の例では、指定した VPC アタッチメントを削除します。  

```
aws ec2 delete-transit-gateway-vpc-attachment \
    --transit-gateway-attachment-id tgw-attach-0d2c54bdbEXAMPLE
```
出力:  

```
{
    "TransitGatewayVpcAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-0d2c54bdb3EXAMPLE",
        "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
        "VpcId": "vpc-0065acced4f61c651",
        "VpcOwnerId": "111122223333",
        "State": "deleting",
        "CreationTime": "2019-07-17T16:04:27.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Delete a VPC attachment](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#delete-vpc-attachment)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGatewayVpcAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway-vpc-attachment.html)」を参照してください。

### `delete-transit-gateway`
<a name="ec2_DeleteTransitGateway_cli_2_topic"></a>

次のコード例は、`delete-transit-gateway` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway を削除するには**  
次の `delete-transit-gateway` の例では、指定した Transit Gateway を削除します。  

```
aws ec2  delete-transit-gateway \
    --transit-gateway-id tgw-01f04542b2EXAMPLE
```
出力:  

```
{
    "TransitGateway": {
        "TransitGatewayId": "tgw-01f04542b2EXAMPLE",
        "State": "deleting",
        "OwnerId": "123456789012",
        "Description": "Example Transit Gateway",
        "CreationTime": "2019-08-27T15:04:35.000Z",
        "Options": {
            "AmazonSideAsn": 64515,
            "AutoAcceptSharedAttachments": "disable",
            "DefaultRouteTableAssociation": "enable",
            "AssociationDefaultRouteTableId": "tgw-rtb-0ce7a6948fEXAMPLE",
            "DefaultRouteTablePropagation": "enable",
            "PropagationDefaultRouteTableId": "tgw-rtb-0ce7a6948fEXAMPLE",
            "VpnEcmpSupport": "enable",
            "DnsSupport": "enable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Delete a transit gateway](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#delete-tgw)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTransitGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-transit-gateway.html)」を参照してください。

### `delete-verified-access-endpoint`
<a name="ec2_DeleteVerifiedAccessEndpoint_cli_2_topic"></a>

次のコード例は、`delete-verified-access-endpoint` を使用する方法を示しています。

**AWS CLI**  
**Verified Access エンドポイントを削除するには**  
次の `delete-verified-access-endpoint` の例では、指定した Verified Access エンドポイントを削除します。  

```
aws ec2 delete-verified-access-endpoint \
    --verified-access-endpoint-id vae-066fac616d4d546f2
```
出力:  

```
{
    "VerifiedAccessEndpoint": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
        "VerifiedAccessEndpointId": "vae-066fac616d4d546f2",
        "ApplicationDomain": "example.com",
        "EndpointType": "network-interface",
        "AttachmentType": "vpc",
        "DomainCertificateArn": "arn:aws:acm:us-east-2:123456789012:certificate/eb065ea0-26f9-4e75-a6ce-0a1a7EXAMPLE",
        "EndpointDomain": "my-ava-app.edge-00c3372d53b1540bb.vai-0ce000c0b7643abea.prod.verified-access.us-east-2.amazonaws.com",
        "SecurityGroupIds": [
            "sg-004915970c4c8f13a"
        ],
        "NetworkInterfaceOptions": {
            "NetworkInterfaceId": "eni-0aec70418c8d87a0f",
            "Protocol": "https",
            "Port": 443
        },
        "Status": {
            "Code": "deleting"
        },
        "Description": "Testing Verified Access",
        "CreationTime": "2023-08-25T20:54:43",
        "LastUpdatedTime": "2023-08-25T22:46:32"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access endpoints](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVerifiedAccessEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-verified-access-endpoint.html)」を参照してください。

### `delete-verified-access-group`
<a name="ec2_DeleteVerifiedAccessGroup_cli_2_topic"></a>

次のコード例は、`delete-verified-access-group` を使用する方法を示しています。

**AWS CLI**  
**Verified Access グループを削除するには**  
次の `delete-verified-access-group` の例では、指定した Verified Access グループを削除します。  

```
aws ec2 delete-verified-access-group \
    --verified-access-group-id vagr-0dbe967baf14b7235
```
出力:  

```
{
    "VerifiedAccessGroup": {
        "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "Testing Verified Access",
        "Owner": "123456789012",
        "VerifiedAccessGroupArn": "arn:aws:ec2:us-east-2:123456789012:verified-access-group/vagr-0dbe967baf14b7235",
        "CreationTime": "2023-08-25T19:55:19",
        "LastUpdatedTime": "2023-08-25T22:49:03",
        "DeletionTime": "2023-08-26T00:58:31"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access groups](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVerifiedAccessGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-verified-access-group.html)」を参照してください。

### `delete-verified-access-instance`
<a name="ec2_DeleteVerifiedAccessInstance_cli_2_topic"></a>

次のコード例は、`delete-verified-access-instance` を使用する方法を示しています。

**AWS CLI**  
**Verified Access インスタンスを削除するには**  
次の `delete-verified-access-instance` の例では、指定した Verified Access インスタンスを削除します。  

```
aws ec2 delete-verified-access-instance \
    --verified-access-instance-id vai-0ce000c0b7643abea
```
出力:  

```
{
    "VerifiedAccessInstance": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "Testing Verified Access",
        "VerifiedAccessTrustProviders": [],
        "CreationTime": "2023-08-25T18:27:56",
        "LastUpdatedTime": "2023-08-26T01:00:18"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Access インスタンス](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVerifiedAccessInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-verified-access-instance.html)」を参照してください。

### `delete-verified-access-trust-provider`
<a name="ec2_DeleteVerifiedAccessTrustProvider_cli_2_topic"></a>

次のコード例は、`delete-verified-access-trust-provider` を使用する方法を示しています。

**AWS CLI**  
**Verified Access デバイスの信頼プロバイダーを削除するには**  
次の `delete-verified-access-trust-provider` の例では、指定した Verified Access 信頼プロバイダーを削除します。  

```
aws ec2 delete-verified-access-trust-provider \
    --verified-access-trust-provider-id vatp-0bb32de759a3e19e7
```
出力:  

```
{
    "VerifiedAccessTrustProvider": {
        "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
        "Description": "Testing Verified Access",
        "TrustProviderType": "user",
        "UserTrustProviderType": "iam-identity-center",
        "PolicyReferenceName": "idc",
        "CreationTime": "2023-08-25T18:40:36",
        "LastUpdatedTime": "2023-08-25T18:40:36"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Trust providers for Verified Access](https://docs.aws.amazon.com/verified-access/latest/ug/trust-providers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVerifiedAccessTrustProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-verified-access-trust-provider.html)」を参照してください。

### `delete-volume`
<a name="ec2_DeleteVolume_cli_2_topic"></a>

次のコード例は、`delete-volume` を使用する方法を示しています。

**AWS CLI**  
**ボリュームを削除するには**  
このコマンド例では、`vol-049df61146c4d7901` というボリューム ID を持つ使用可能なボリュームを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-volume --volume-id vol-049df61146c4d7901
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-volume.html)」を参照してください。

### `delete-vpc-endpoint-connection-notifications`
<a name="ec2_DeleteVpcEndpointConnectionNotifications_cli_2_topic"></a>

次のコード例は、`delete-vpc-endpoint-connection-notifications` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントの接続通知を削除するには**  
この例では、指定されたエンドポイント接続通知を削除します。  
コマンド:  

```
aws ec2 delete-vpc-endpoint-connection-notifications --connection-notification-ids vpce-nfn-008776de7e03f5abc
```
出力:  

```
{
  "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpcEndpointConnectionNotifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpc-endpoint-connection-notifications.html)」を参照してください。

### `delete-vpc-endpoint-service-configurations`
<a name="ec2_DeleteVpcEndpointServiceConfigurations_cli_2_topic"></a>

次のコード例は、`delete-vpc-endpoint-service-configurations` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントサービス設定を削除するには**  
この例では、指定されたエンドポイントサービス設定を削除します。  
コマンド:  

```
aws ec2 delete-vpc-endpoint-service-configurations --service-ids vpce-svc-03d5ebb7d9579a2b3
```
出力:  

```
{
   "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpcEndpointServiceConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpc-endpoint-service-configurations.html)」を参照してください。

### `delete-vpc-endpoints`
<a name="ec2_DeleteVpcEndpoints_cli_2_topic"></a>

次のコード例は、`delete-vpc-endpoints` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントを削除するには**  
この例では、エンドポイント vpce-aa22bb33 と vpce-1a2b3c4d を削除します。コマンドが部分的に成功または失敗した場合は、失敗した項目のリストが返されます。コマンドが成功した場合、返されたリストは空になります。  
コマンド:  

```
aws ec2 delete-vpc-endpoints --vpc-endpoint-ids vpce-aa22bb33 vpce-1a2b3c4d
```
出力:  

```
{
  "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpcEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpc-endpoints.html)」を参照してください。

### `delete-vpc-peering-connection`
<a name="ec2_DeleteVpcPeeringConnection_cli_2_topic"></a>

次のコード例は、`delete-vpc-peering-connection` を使用する方法を示しています。

**AWS CLI**  
**VPC ピアリング接続を削除するには**  
この例では、指定された VPC ピアリング接続を削除します。  
コマンド:  

```
aws ec2 delete-vpc-peering-connection --vpc-peering-connection-id pcx-1a2b3c4d
```
出力:  

```
{
    "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpcPeeringConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpc-peering-connection.html)」を参照してください。

### `delete-vpc`
<a name="ec2_DeleteVpc_cli_2_topic"></a>

次のコード例は、`delete-vpc` を使用する方法を示しています。

**AWS CLI**  
**VPC を削除するには**  
この例では、指定された VPC を削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-vpc --vpc-id vpc-a01106c2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpc.html)」を参照してください。

### `delete-vpn-connection-route`
<a name="ec2_DeleteVpnConnectionRoute_cli_2_topic"></a>

次のコード例は、`delete-vpn-connection-route` を使用する方法を示しています。

**AWS CLI**  
**VPN 接続から静的ルートを削除するには**  
この例では、指定された VPN 接続から指定された静的ルートを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-vpn-connection-route --vpn-connection-id vpn-40f41529 --destination-cidr-block 11.12.0.0/16
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpnConnectionRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpn-connection-route.html)」を参照してください。

### `delete-vpn-connection`
<a name="ec2_DeleteVpnConnection_cli_2_topic"></a>

次のコード例は、`delete-vpn-connection` を使用する方法を示しています。

**AWS CLI**  
**VPN 接続を削除するには**  
この例では、指定された VPN 接続を削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-vpn-connection --vpn-connection-id vpn-40f41529
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpnConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpn-connection.html)」を参照してください。

### `delete-vpn-gateway`
<a name="ec2_DeleteVpnGateway_cli_2_topic"></a>

次のコード例は、`delete-vpn-gateway` を使用する方法を示しています。

**AWS CLI**  
**仮想プライベートゲートウェイを削除するには**  
この例では、指定された仮想プライベートゲートウェイを削除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 delete-vpn-gateway --vpn-gateway-id vgw-9a4cacf3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-vpn-gateway.html)」を参照してください。

### `deprovision-byoip-cidr`
<a name="ec2_DeprovisionByoipCidr_cli_2_topic"></a>

次のコード例は、`deprovision-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**使用から IP アドレス範囲を削除するには**  
次の の例では、指定されたアドレス範囲を での使用から削除します AWS。  

```
aws ec2 deprovision-byoip-cidr \
    --cidr 203.0.113.25/24
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "203.0.113.25/24",
        "State": "pending-deprovision"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeprovisionByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/deprovision-byoip-cidr.html)」を参照してください。

### `deprovision-ipam-pool-cidr`
<a name="ec2_DeprovisionIpamPoolCidr_cli_2_topic"></a>

次のコード例は、`deprovision-ipam-pool-cidr` を使用する方法を示しています。

**AWS CLI**  
**IPAM プール CIDR のプロビジョニングを解除するには**  
次の `deprovision-ipam-pool-cidr` の例では、IPAM プールにプロビジョニングされた CIDR のプロビジョニングを解除します。  
(Linux):  

```
aws ec2 deprovision-ipam-pool-cidr \
    --ipam-pool-id ipam-pool-02ec043a19bbe5d08 \
    --cidr 11.0.0.0/16
```
(Windows):  

```
aws ec2 deprovision-ipam-pool-cidr ^
    --ipam-pool-id ipam-pool-02ec043a19bbe5d08 ^
    --cidr 11.0.0.0/16
```
出力:  

```
{
    "IpamPoolCidr": {
        "Cidr": "11.0.0.0/16",
        "State": "pending-deprovision"
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Deprovision pool CIDRs](https://docs.aws.amazon.com/vpc/latest/ipam/depro-pool-cidr-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeprovisionIpamPoolCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/deprovision-ipam-pool-cidr.html)」を参照してください。

### `deregister-image`
<a name="ec2_DeregisterImage_cli_2_topic"></a>

次のコード例は、`deregister-image` を使用する方法を示しています。

**AWS CLI**  
**AMI の登録を解除するには**  
この例では、指定された AMI の登録を解除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 deregister-image --image-id ami-4fa54026
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/deregister-image.html)」を参照してください。

### `deregister-instance-event-notification-attributes`
<a name="ec2_DeregisterInstanceEventNotificationAttributes_cli_2_topic"></a>

次のコード例は、`deregister-instance-event-notification-attributes` を使用する方法を示しています。

**AWS CLI**  
**例 1: イベント通知からすべてのタグを削除するには**  
次の `deregister-instance-event-notification-attributes` の例では、`IncludeAllTagsOfInstance=true` を削除します。これにより、`IncludeAllTagsOfInstance` は `false` に設定されます。  

```
aws ec2 deregister-instance-event-notification-attributes \
    --instance-tag-attribute IncludeAllTagsOfInstance=true
```
出力:  

```
{
    "InstanceTagAttribute": {
        "InstanceTagKeys": [],
        "IncludeAllTagsOfInstance": true
    }
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Scheduled events for your instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html)」を参照してください。  
**例 2: イベント通知から特定のタグを削除するには**  
次の `deregister-instance-event-notification-attributes` の例では、イベント通知に含まれるタグから指定したタグを削除します。イベント通知に含まれる残りのタグを記述するには、`describe-instance-event-notification-attributes` を使用します。  

```
aws ec2 deregister-instance-event-notification-attributes \
    --instance-tag-attribute InstanceTagKeys="tag-key2"
```
出力:  

```
{
    "InstanceTagAttribute": {
        "InstanceTagKeys": [
            "tag-key2"
        ],
        "IncludeAllTagsOfInstance": false
    }
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Scheduled events for your instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterInstanceEventNotificationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/deregister-instance-event-notification-attributes.html)」を参照してください。

### `deregister-transit-gateway-multicast-group-members`
<a name="ec2_DeregisterTransitGatewayMulticastGroupMembers_cli_2_topic"></a>

次のコード例は、`deregister-transit-gateway-multicast-group-members` を使用する方法を示しています。

**AWS CLI**  
**マルチキャストグループからグループメンバーの登録を解除するには**  
この例では、Transit Gateway マルチキャストグループから指定されたネットワークインターフェイスグループメンバーの登録を解除します。  

```
aws ec2 deregister-transit-gateway-multicast-group-members \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef7EXAMPLE \
    --group-ip-address 224.0.1.0 \
    --network-interface-ids eni-0e246d3269EXAMPLE
```
出力:  

```
{
    "DeregisteredMulticastGroupMembers": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c4905cef7EXAMPLE",
        "RegisteredNetworkInterfaceIds": [
            "eni-0e246d3269EXAMPLE"
        ],
        "GroupIpAddress": "224.0.1.0"
    }
}
```
詳細については、「*AWS Transit Gateway ユーザーガイド*」の「[Deregister Members from a Multicast Group](https://docs.aws.amazon.com/vpc/latest/tgw/working-with-multicast.html#remove-members-multicast-group)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTransitGatewayMulticastGroupMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/deregister-transit-gateway-multicast-group-members.html)」を参照してください。

### `deregister-transit-gateway-multicast-group-source`
<a name="ec2_DeregisterTransitGatewayMulticastGroupSource_cli_2_topic"></a>

次のコード例は、`deregister-transit-gateway-multicast-group-source` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway マルチキャストグループからソースの登録を解除するには**  
この例では、マルチキャストグループから指定されたネットワークインターフェイスグループソースの登録を解除します。  

```
aws ec2 register-transit-gateway-multicast-group-sources \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef79d6e597 \
    --group-ip-address 224.0.1.0 \
    --network-interface-ids eni-07f290fc3c090cbae
```
出力:  

```
{
    "DeregisteredMulticastGroupSources": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c4905cef79d6e597",
        "DeregisteredNetworkInterfaceIds": [
            "eni-07f290fc3c090cbae"
        ],
        "GroupIpAddress": "224.0.1.0"
    }
}
```
詳細については、「*AWS Transit Gateway ユーザーガイド*」の「[Deregister Sources from a Multicast Group](https://docs.aws.amazon.com/vpc/latest/tgw/working-with-multicast.html#remove-source-multicast-group)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTransitGatewayMulticastGroupSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/deregister-transit-gateway-multicast-group-source.html)」を参照してください。

### `describe-account-attributes`
<a name="ec2_DescribeAccountAttributes_cli_2_topic"></a>

次の例は、`describe-account-attributes` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのすべての属性を記述するには**  
この例では、 AWS アカウントの属性について説明します。  
コマンド:  

```
aws ec2 describe-account-attributes
```
出力:  

```
{
    "AccountAttributes": [
        {
            "AttributeName": "vpc-max-security-groups-per-interface",
            "AttributeValues": [
                {
                    "AttributeValue": "5"
                }
            ]
        },
        {
            "AttributeName": "max-instances",
            "AttributeValues": [
                {
                    "AttributeValue": "20"
                }
            ]
        },
        {
            "AttributeName": "supported-platforms",
            "AttributeValues": [
                {
                    "AttributeValue": "EC2"
                },
                {
                    "AttributeValue": "VPC"
                }
            ]
        },
        {
            "AttributeName": "default-vpc",
            "AttributeValues": [
                {
                    "AttributeValue": "none"
                }
            ]
        },
        {
            "AttributeName": "max-elastic-ips",
            "AttributeValues": [
                {
                    "AttributeValue": "5"
                }
            ]
        },
        {
            "AttributeName": "vpc-max-elastic-ips",
            "AttributeValues": [
                {
                    "AttributeValue": "5"
                }
            ]
        }
    ]
}
```
** AWS アカウントの単一の属性を記述するには**  
この例では、 AWS アカウントの `supported-platforms` 属性について説明します。  
コマンド:  

```
aws ec2 describe-account-attributes --attribute-names supported-platforms
```
出力:  

```
{
    "AccountAttributes": [
        {
            "AttributeName": "supported-platforms",
            "AttributeValues": [
                {
                    "AttributeValue": "EC2"
                },
                {
                    "AttributeValue": "VPC"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-account-attributes.html)」を参照してください。

### `describe-address-transfers`
<a name="ec2_DescribeAddressTransfers_cli_2_topic"></a>

次のコード例は、`describe-address-transfers` を使用する方法を示しています。

**AWS CLI**  
**Elastic IP アドレスの移管を記述するには**  
次の `describe-address-transfers` の例では、指定した Elastic IP アドレスの Elastic IP アドレス転送を記述します。  

```
aws ec2 describe-address-transfers \
    --allocation-ids eipalloc-09ad461b0d03f6aaf
```
出力:  

```
{
    "AddressTransfers": [
        {
            "PublicIp": "100.21.184.216",
            "AllocationId": "eipalloc-09ad461b0d03f6aaf",
            "TransferAccountId": "123456789012",
            "TransferOfferExpirationTimestamp": "2023-02-22T22:51:01.000Z",
            "AddressTransferStatus": "pending"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Transfer Elastic IP addresses](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-eips.html#transfer-EIPs-intro)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAddressTransfers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-address-transfers.html)」を参照してください。

### `describe-addresses-attribute`
<a name="ec2_DescribeAddressesAttribute_cli_2_topic"></a>

次のコード例は、`describe-addresses-attribute` を使用する方法を示しています。

**AWS CLI**  
**Elastic IP アドレスに関連付けられたドメイン名の属性を表示するには**  
次の `describe-addresses-attribute` の例では、Elastic IP アドレスに関連付けられたドメイン名の属性を返します。  
Linux ：  

```
aws ec2 describe-addresses-attribute \
    --allocation-ids eipalloc-abcdef01234567890 \
    --attribute domain-name
```
Windows ：  

```
aws ec2 describe-addresses-attribute ^
    --allocation-ids eipalloc-abcdef01234567890 ^
    --attribute domain-name
```
出力:  

```
{
    "Addresses": [
        {
            "PublicIp": "192.0.2.0",
            "AllocationId": "eipalloc-abcdef01234567890",
            "PtrRecord": "example.com."
        }
    ]
}
```
Elastic IP アドレスの属性を表示するには、まずドメイン名を Elastic IP アドレスに関連付ける必要があります。詳細については、「*Amazon EC2 ユーザーガイド*」の「[Use reverse DNS for email applications](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html#Using_Elastic_Addressing_Reverse_DNS)」または「*AWS CLI コマンドリファレンス*」の「[modify-address-attribute](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-address-attribute.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAddressesAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-addresses-attribute.html)」を参照してください。

### `describe-addresses`
<a name="ec2_DescribeAddresses_cli_2_topic"></a>

次のコード例は、`describe-addresses` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべての Elastic IP アドレスに関する詳細を取得するには**  
次の `describe addresses` の例では、Elastic IP アドレスに関する詳細が表示されます。  

```
aws ec2 describe-addresses
```
出力:  

```
{
    "Addresses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PublicIp": "198.51.100.0",
            "PublicIpv4Pool": "amazon",
            "Domain": "standard"
        },
        {
            "Domain": "vpc",
            "PublicIpv4Pool": "amazon",
            "InstanceId": "i-1234567890abcdef0",
            "NetworkInterfaceId": "eni-12345678",
            "AssociationId": "eipassoc-12345678",
            "NetworkInterfaceOwnerId": "123456789012",
            "PublicIp": "203.0.113.0",
            "AllocationId": "eipalloc-12345678",
            "PrivateIpAddress": "10.0.1.241"
        }
    ]
}
```
**例 2: EC2-VPC の Elastic IP アドレスに関する詳細を取得するには**  
次の `describe-addresses` の例では、VPC 内のインスタンスで使用する Elastic IP アドレスの詳細が表示されます。  

```
aws ec2 describe-addresses \
    --filters "Name=domain,Values=vpc"
```
出力:  

```
{
    "Addresses": [
        {
            "Domain": "vpc",
            "PublicIpv4Pool": "amazon",
            "InstanceId": "i-1234567890abcdef0",
            "NetworkInterfaceId": "eni-12345678",
            "AssociationId": "eipassoc-12345678",
            "NetworkInterfaceOwnerId": "123456789012",
            "PublicIp": "203.0.113.0",
            "AllocationId": "eipalloc-12345678",
            "PrivateIpAddress": "10.0.1.241"
        }
    ]
}
```
**例 3: 割り当て ID で指定された Elastic IP アドレスに関する詳細を取得するには**  
次の `describe-addresses` の例では、EC2-VPC 内のインスタンスに関連付けられている、指定された割り当て ID を持つ Elastic IP アドレスの詳細を表示します。  

```
aws ec2 describe-addresses \
    --allocation-ids eipalloc-282d9641
```
出力:  

```
{
    "Addresses": [
        {
            "Domain": "vpc",
            "PublicIpv4Pool": "amazon",
            "InstanceId": "i-1234567890abcdef0",
            "NetworkInterfaceId": "eni-1a2b3c4d",
            "AssociationId": "eipassoc-123abc12",
            "NetworkInterfaceOwnerId": "1234567891012",
            "PublicIp": "203.0.113.25",
            "AllocationId": "eipalloc-282d9641",
            "PrivateIpAddress": "10.251.50.12"
        }
    ]
}
```
**例 4: VPC プライベート IP アドレスで指定された Elastic IP アドレスに関する詳細を取得するには**  
次の `describe-addresses` の例では、EC2-VPC の特定のプライベート IP アドレスに関連付けられている Elastic IP アドレスの詳細が表示されます。  

```
aws ec2 describe-addresses \
    --filters "Name=private-ip-address,Values=10.251.50.12"
```
**例 5: EC2-Classic の Elastic IP アドレスに関する詳細を取得するには**  
次の `describe-addresses` の例では、EC2-Classic で使用する Elastic IP アドレスを表示します。  

```
aws ec2 describe-addresses \
    --filters "Name=domain,Values=standard"
```
出力:  

```
{
    "Addresses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PublicIp": "203.0.110.25",
            "PublicIpv4Pool": "amazon",
            "Domain": "standard"
        }
    ]
}
```
**例 6: パブリック IP アドレスで指定された Elastic IP アドレスに関する詳細を取得するには**  
次の `describe-addresses` の例では、EC2-Classic のインスタンスに関連付けられている、値 `203.0.110.25` を持つ Elastic IP アドレスの詳細を表示します。  

```
aws ec2 describe-addresses \
    --public-ips 203.0.110.25
```
出力:  

```
{
    "Addresses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PublicIp": "203.0.110.25",
            "PublicIpv4Pool": "amazon",
            "Domain": "standard"
        }
    ]
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-addresses.html)」を参照してください。

### `describe-aggregate-id-format`
<a name="ec2_DescribeAggregateIdFormat_cli_2_topic"></a>

次のコード例は、`describe-aggregate-id-format` を使用する方法を示しています。

**AWS CLI**  
**任意のリージョンのすべてのリソースタイプに対する長い ID 形式の設定を記述するには**  
次の `describe-aggregate-id-format` の例では、現在のリージョンに対する全体的な長い ID 形式ステータスを記述します。`Deadline` 値は、これらのリソースが短い ID 形式から長い ID 形式に完全に切り替わる期限が切れたことを示します。`UseLongIdsAggregated` 値は、すべての IAM ユーザーと IAM ロールが、すべてのリソースタイプに長い ID 形式を使用するように設定されていることを示します。  

```
aws ec2 describe-aggregate-id-format
```
出力:  

```
{
    "UseLongIdsAggregated": true,
    "Statuses": [
        {
            "Deadline": "2018-08-13T02:00:00.000Z",
            "Resource": "network-interface-attachment",
            "UseLongIds": true
        },
        {
            "Deadline": "2016-12-13T02:00:00.000Z",
            "Resource": "instance",
            "UseLongIds": true
        },
        {
            "Deadline": "2018-08-13T02:00:00.000Z",
            "Resource": "elastic-ip-association",
            "UseLongIds": true
        },
        ...
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAggregateIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-aggregate-id-format.html)」を参照してください。

### `describe-availability-zones`
<a name="ec2_DescribeAvailabilityZones_cli_2_topic"></a>

次のコード例は、`describe-availability-zones` を使用する方法を示しています。

**AWS CLI**  
**アベイラビリティーゾーンを説明するには**  
次の `describe-availability-zones` の例では、利用可能なアベイラビリティーゾーンの詳細が表示されます。レスポンスには、現在のリージョンのアベイラビリティーゾーンのみが含まれます。この例では、デフォルトの `us-west-2` (オレゴン) リージョンのプロファイルを使用しています。  

```
aws ec2 describe-availability-zones
```
出力:  

```
{
    "AvailabilityZones": [
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2a",
            "ZoneId": "usw2-az1",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2b",
            "ZoneId": "usw2-az2",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2c",
            "ZoneId": "usw2-az3",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opt-in-not-required",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2d",
            "ZoneId": "usw2-az4",
            "GroupName": "us-west-2",
            "NetworkBorderGroup": "us-west-2"
        },
        {
            "State": "available",
            "OptInStatus": "opted-in",
            "Messages": [],
            "RegionName": "us-west-2",
            "ZoneName": "us-west-2-lax-1a",
            "ZoneId": "usw2-lax1-az1",
            "GroupName": "us-west-2-lax-1",
            "NetworkBorderGroup": "us-west-2-lax-1"
        }
    ]
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeAvailabilityZones](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-availability-zones.html)」を参照してください。

### `describe-aws-network-performance-metric-subscription`
<a name="ec2_DescribeAwsNetworkPerformanceMetricSubscription_cli_2_topic"></a>

次のコード例は、`describe-aws-network-performance-metric-subscription` を使用する方法を示しています。

**AWS CLI**  
**メトリクスサブスクリプションを記述するには**  
次の `describe-aws-network-performance-metric-subscriptions` の例では、メトリクスサブスクリプションを記述します。  

```
aws ec2 describe-aws-network-performance-metric-subscriptions
```
出力:  

```
{
    "Subscriptions": [
        {
            "Source": "us-east-1",
            "Destination": "eu-west-1",
            "Metric": "aggregate-latency",
            "Statistic": "p50",
            "Period": "five-minutes"
        }
    ]
}
```
詳細については、「*インフラストラクチャのパフォーマンスのユーザーガイド*」の「[Manage subscriptions](https://docs.aws.amazon.com/network-manager/latest/infrastructure-performance/nmip-subscriptions-cw.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAwsNetworkPerformanceMetricSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-aws-network-performance-metric-subscription.html)」を参照してください。

### `describe-aws-network-performance-metric-subscriptions`
<a name="ec2_DescribeAwsNetworkPerformanceMetricSubscriptions_cli_2_topic"></a>

次のコード例は、`describe-aws-network-performance-metric-subscriptions` を使用する方法を示しています。

**AWS CLI**  
**メトリクスサブスクリプションを記述するには**  
次の `describe-aws-network-performance-metric-subscriptions` の例では、メトリクスサブスクリプションを記述します。  

```
aws ec2 describe-aws-network-performance-metric-subscriptions
```
出力:  

```
{
    "Subscriptions": [
        {
            "Source": "us-east-1",
            "Destination": "eu-west-1",
            "Metric": "aggregate-latency",
            "Statistic": "p50",
            "Period": "five-minutes"
        }
    ]
}
```
詳細については、「*インフラストラクチャのパフォーマンスのユーザーガイド*」の「[Manage subscriptions](https://docs.aws.amazon.com/network-manager/latest/infrastructure-performance/nmip-subscriptions-cw.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAwsNetworkPerformanceMetricSubscriptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-aws-network-performance-metric-subscriptions.html)」を参照してください。

### `describe-bundle-tasks`
<a name="ec2_DescribeBundleTasks_cli_2_topic"></a>

次のコード例は、`describe-bundle-tasks` を使用する方法を示しています。

**AWS CLI**  
**バンドルタスクを記述するには**  
この例では、すべてのバンドルタスクを記述します。  
コマンド:  

```
aws ec2 describe-bundle-tasks
```
出力:  

```
{
  "BundleTasks": [
    {
      "UpdateTime": "2015-09-15T13:26:54.000Z",
      "InstanceId": "i-1234567890abcdef0",
      "Storage": {
        "S3": {
            "Prefix": "winami",
            "Bucket": "bundletasks"
        }
      },
      "State": "bundling",
      "StartTime": "2015-09-15T13:24:35.000Z",
      "Progress": "3%",
      "BundleId": "bun-2a4e041c"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBundleTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-bundle-tasks.html)」を参照してください。

### `describe-byoip-cidrs`
<a name="ec2_DescribeByoipCidrs_cli_2_topic"></a>

次のコード例は、`describe-byoip-cidrs` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされたアドレス範囲を記述するには**  
次の の`describe-byoip-cidrs`例では、 で使用するためにプロビジョニングしたパブリック IPv4 アドレス範囲の詳細を表示します AWS。  

```
aws ec2 describe-byoip-cidrs
```
出力:  

```
{
    "ByoipCidrs": [
        {
            "Cidr": "203.0.113.25/24",
            "StatusMessage": "ipv4pool-ec2-1234567890abcdef0",
            "State": "provisioned"
        }
    ]
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DescribeByoipCidrs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-byoip-cidrs.html)」を参照してください。

### `describe-capacity-reservation-fleets`
<a name="ec2_DescribeCapacityReservationFleets_cli_2_topic"></a>

次のコード例は、`describe-capacity-reservation-fleets` を使用する方法を示しています。

**AWS CLI**  
**キャパシティ予約フリートを表示するには**  
次の `describe-capacity-reservation-fleets` の例では、指定したキャパシティ予約フリートの設定とキャパシティ情報を一覧表示します。フリート内の個々のキャパシティ予約に関する詳細も一覧表示されます。  

```
aws ec2 describe-capacity-reservation-fleets \
    --capacity-reservation-fleet-ids crf-abcdef01234567890
```
出力:  

```
{
    "CapacityReservationFleets": [
        {
            "State": "active",
            "EndDate": "2022-12-31T23:59:59.000Z",
            "InstanceMatchCriteria": "open",
            "Tags": [],
            "CapacityReservationFleetId": "crf-abcdef01234567890",
            "Tenancy": "default",
            "InstanceTypeSpecifications": [
                {
                    "CapacityReservationId": "cr-1234567890abcdef0",
                    "AvailabilityZone": "us-east-1a",
                    "FulfilledCapacity": 5.0,
                    "Weight": 1.0,
                    "CreateDate": "2022-07-02T08:34:33.398Z",
                    "InstancePlatform": "Linux/UNIX",
                    "TotalInstanceCount": 5,
                    "Priority": 1,
                    "EbsOptimized": true,
                    "InstanceType": "m5.xlarge"
                }
            ],
            "TotalTargetCapacity": 5,
            "TotalFulfilledCapacity": 5.0,
            "CreateTime": "2022-07-02T08:34:33.397Z",
            "AllocationStrategy": "prioritized"
        }
    ]
}
```
キャパシティ予約フリートの詳細については、「*Amazon EC2 ユーザーガイド*」の「[キャパシティ予約フリート](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/cr-fleets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCapacityReservationFleets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-capacity-reservation-fleets.html)」を参照してください。

### `describe-capacity-reservations`
<a name="ec2_DescribeCapacityReservations_cli_2_topic"></a>

次のコード例は、`describe-capacity-reservations` を使用する方法を示しています。

**AWS CLI**  
**例 1: 1 つ以上のキャパシティ予約を記述するには**  
次の の`describe-capacity-reservations`例では、現在の AWS リージョンのすべてのキャパシティ予約の詳細を表示します。  

```
aws ec2 describe-capacity-reservations
```
出力:  

```
{
    "CapacityReservations": [
        {
            "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
            "OwnerId": "123456789111",
            "CapacityReservationArn": "arn:aws:ec2:us-east-1:123456789111:capacity-reservation/cr-1234abcd56EXAMPLE",
            "AvailabilityZoneId": "use1-az2",
            "InstanceType": "c5.large",
            "InstancePlatform": "Linux/UNIX",
            "AvailabilityZone": "us-east-1a",
            "Tenancy": "default",
            "TotalInstanceCount": 1,
            "AvailableInstanceCount": 1,
            "EbsOptimized": true,
            "EphemeralStorage": false,
            "State": "active",
            "StartDate": "2024-10-23T15:00:24+00:00",
            "EndDateType": "unlimited",
            "InstanceMatchCriteria": "open",
            "CreateDate": "2024-10-23T15:00:24+00:00",
            "Tags": [],
            "CapacityAllocations": []
        },
        {
            "CapacityReservationId": "cr-abcdEXAMPLE9876ef ",
            "OwnerId": "123456789111",
            "CapacityReservationArn": "arn:aws:ec2:us-east-1:123456789111:capacity-reservation/cr-abcdEXAMPLE9876ef",
            "AvailabilityZoneId": "use1-az2",
            "InstanceType": "c4.large",
            "InstancePlatform": "Linux/UNIX",
            "AvailabilityZone": "us-east-1a",
            "Tenancy": "default",
            "TotalInstanceCount": 1,
            "AvailableInstanceCount": 1,
            "EbsOptimized": true,
            "EphemeralStorage": false,
            "State": "cancelled",
            "StartDate": "2024-10-23T15:01:03+00:00",
            "EndDateType": "unlimited",
            "InstanceMatchCriteria": "open",
            "CreateDate": "2024-10-23T15:01:02+00:00",
            "Tags": [],
            "CapacityAllocations": []
        }
    ]
}
```
**例 2: 1 つ以上のキャパシティ予約を記述するには**  
次の `describe-capacity-reservations` の例では、指定したキャパシティ予約の詳細を表示します。  

```
aws ec2 describe-capacity-reservations \
    --capacity-reservation-ids cr-1234abcd56EXAMPLE
```
出力:  

```
{
    "CapacityReservations": [
        {
            "CapacityReservationId": "cr-abcdEXAMPLE9876ef ",
            "OwnerId": "123456789111",
            "CapacityReservationArn": "arn:aws:ec2:us-east-1:123456789111:capacity-reservation/cr-abcdEXAMPLE9876ef",
            "AvailabilityZoneId": "use1-az2",
            "InstanceType": "c4.large",
            "InstancePlatform": "Linux/UNIX",
            "AvailabilityZone": "us-east-1a",
            "Tenancy": "default",
            "TotalInstanceCount": 1,
            "AvailableInstanceCount": 1,
            "EbsOptimized": true,
            "EphemeralStorage": false,
            "State": "active",
            "StartDate": "2024-10-23T15:01:03+00:00",
            "EndDateType": "unlimited",
            "InstanceMatchCriteria": "open",
            "CreateDate": "2024-10-23T15:01:02+00:00",
            "Tags": [],
            "CapacityAllocations": []
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Viewing a Capacity Reservation](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-using.html#capacity-reservations-view)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCapacityReservations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-capacity-reservations.html)」を参照してください。

### `describe-carrier-gateways`
<a name="ec2_DescribeCarrierGateways_cli_2_topic"></a>

次のコード例は、`describe-carrier-gateways` を使用する方法を示しています。

**AWS CLI**  
**すべてのキャリアゲートウェイを記述するには**  
次の `describe-carrier-gateways` の例では、すべてのキャリアゲートウェイを一覧表示します。  

```
aws ec2 describe-carrier-gateways
```
出力:  

```
{
    "CarrierGateways": [
        {
            "CarrierGatewayId": "cagw-0465cdEXAMPLE1111",
            "VpcId": "vpc-0c529aEXAMPLE",
            "State": "available",
            "OwnerId": "123456789012",
            "Tags": [
                {

                    "Key": "example",
                    "Value": "tag"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon Virtual Private Cloud ユーザーガイド*」の「Carrier gateways」<https://docs.aws.amazon.com/vpc/latest/userguide/Carrier\$1Gateway.html> を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCarrierGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-carrier-gateways.html)」を参照してください。

### `describe-classic-link-instances`
<a name="ec2_DescribeClassicLinkInstances_cli_2_topic"></a>

次のコード例は、`describe-classic-link-instances` を使用する方法を示しています。

**AWS CLI**  
**リンクされた EC2-Classic インスタンスを記述するには**  
この例では、リンクされたすべての EC2-Classic インスタンスを一覧表示します。  
コマンド:  

```
aws ec2 describe-classic-link-instances
```
出力:  

```
{
        "Instances": [
                {
                        "InstanceId": "i-1234567890abcdef0",
                        "VpcId": "vpc-88888888",
                        "Groups": [
                                {
                                        "GroupId": "sg-11122233"
                                }
                        ],
                        "Tags": [
                                {
                                        "Value": "ClassicInstance",
                                        "Key": "Name"
                                }
                        ]
                },
                {
                        "InstanceId": "i-0598c7d356eba48d7",
                        "VpcId": "vpc-12312312",
                        "Groups": [
                                {
                                        "GroupId": "sg-aabbccdd"
                                }
                        ],
                        "Tags": [
                                {
                                        "Value": "ClassicInstance2",
                                        "Key": "Name"
                                }
                        ]
                }
        ]
}
```
この例では、リンクされたすべての EC2-Classic インスタンスを一覧表示し、VPC vpc-88888888 にリンクされているインスタンスのみを含むようにレスポンスをフィルタリングします。  
コマンド:  

```
aws ec2 describe-classic-link-instances --filter "Name=vpc-id,Values=vpc-88888888"
```
出力:  

```
{
        "Instances": [
                {
                        "InstanceId": "i-1234567890abcdef0",
                        "VpcId": "vpc-88888888",
                        "Groups": [
                                {
                                        "GroupId": "sg-11122233"
                                }
                        ],
                        "Tags": [
                                {
                                        "Value": "ClassicInstance",
                                        "Key": "Name"
                                }
                        ]
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClassicLinkInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-classic-link-instances.html)」を参照してください。

### `describe-client-vpn-authorization-rules`
<a name="ec2_DescribeClientVpnAuthorizationRules_cli_2_topic"></a>

次のコード例は、`describe-client-vpn-authorization-rules` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントの承認ルールを記述するには**  
次の `describe-client-vpn-authorization-rules` の例では、指定したクライアント VPN エンドポイントの承認ルールに関する詳細を表示します。  

```
aws ec2 describe-client-vpn-authorization-rules \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "AuthorizationRules": [
        {
            "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
            "GroupId": "",
            "AccessAll": true,
            "DestinationCidr": "0.0.0.0/0",
            "Status": {
                "Code": "active"
            }
        }
    ]
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Authorization Rules](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClientVpnAuthorizationRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-client-vpn-authorization-rules.html)」を参照してください。

### `describe-client-vpn-connections`
<a name="ec2_DescribeClientVpnConnections_cli_2_topic"></a>

次のコード例は、`describe-client-vpn-connections` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントへの接続を記述するには**  
次の `describe-client-vpn-connections` の例では、指定したクライアント VPN エンドポイントへクライアント接続の詳細を表示します。  

```
aws ec2 describe-client-vpn-connections \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "Connections": [
        {
            "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
            "Timestamp": "2019-08-12 07:58:34",
            "ConnectionId": "cvpn-connection-0e03eb24267165acd",
            "ConnectionEstablishedTime": "2019-08-12 07:57:14",
            "IngressBytes": "32302",
            "EgressBytes": "5696",
            "IngressPackets": "332",
            "EgressPackets": "67",
            "ClientIp": "172.31.0.225",
            "CommonName": "client1.domain.tld",
            "Status": {
                "Code": "terminated"
            },
            "ConnectionEndTime": "2019-08-12 07:58:34"
        },
        {
            "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
            "Timestamp": "2019-08-12 08:02:54",
            "ConnectionId": "cvpn-connection-00668867a40f18253",
            "ConnectionEstablishedTime": "2019-08-12 08:02:53",
            "IngressBytes": "2951",
            "EgressBytes": "2611",
            "IngressPackets": "9",
            "EgressPackets": "6",
            "ClientIp": "172.31.0.226",
            "CommonName": "client1.domain.tld",
            "Status": {
                "Code": "active"
            },
            "ConnectionEndTime": "-"
        }
    ]
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client Connections](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-connections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClientVpnConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-client-vpn-connections.html)」を参照してください。

### `describe-client-vpn-endpoints`
<a name="ec2_DescribeClientVpnEndpoints_cli_2_topic"></a>

次のコード例は、`describe-client-vpn-endpoints` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントを記述するには**  
次の `describe-client-vpn-endpoints` の例では、すべてのクライアント VPN エンドポイントの詳細を表示します。  

```
aws ec2 describe-client-vpn-endpoints
```
出力:  

```
{
    "ClientVpnEndpoints": [
        {
            "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
            "Description": "Endpoint for Admin access",
            "Status": {
                "Code": "available"
            },
            "CreationTime": "2020-11-13T11:37:27",
            "DnsName": "*.cvpn-endpoint-123456789123abcde.prod.clientvpn.ap-south-1.amazonaws.com",
            "ClientCidrBlock": "172.31.0.0/16",
            "DnsServers": [
                "8.8.8.8"
            ],
            "SplitTunnel": false,
            "VpnProtocol": "openvpn",
            "TransportProtocol": "udp",
            "VpnPort": 443,
            "ServerCertificateArn": "arn:aws:acm:ap-south-1:123456789012:certificate/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "AuthenticationOptions": [
                {
                    "Type": "certificate-authentication",
                    "MutualAuthentication": {
                        "ClientRootCertificateChain": "arn:aws:acm:ap-south-1:123456789012:certificate/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE"
                    }
                }
            ],
            "ConnectionLogOptions": {
                "Enabled": true,
                "CloudwatchLogGroup": "Client-vpn-connection-logs",
                "CloudwatchLogStream": "cvpn-endpoint-123456789123abcde-ap-south-1-2020/11/13-FCD8HEMVaCcw"
            },
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Client VPN"
                }
            ],
            "SecurityGroupIds": [
                "sg-aabbcc11223344567"
            ],
            "VpcId": "vpc-a87f92c1",
            "SelfServicePortalUrl": "https://self-service.clientvpn.amazonaws.com/endpoints/cvpn-endpoint-123456789123abcde",
            "ClientConnectOptions": {
                 "Enabled": false
            }
        }
    ]
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client VPN Endpoints](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClientVpnEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-client-vpn-endpoints.html)」を参照してください。

### `describe-client-vpn-routes`
<a name="ec2_DescribeClientVpnRoutes_cli_2_topic"></a>

次のコード例は、`describe-client-vpn-routes` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントのルートを記述するには**  
次の `describe-client-vpn-routes` の例では、指定したクライアント VPN エンドポイントのルートの詳細を表示します。  

```
aws ec2 describe-client-vpn-routes \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "Routes": [
        {
            "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
            "DestinationCidr": "10.0.0.0/16",
            "TargetSubnet": "subnet-0123456789abcabca",
            "Type": "Nat",
            "Origin": "associate",
            "Status": {
                "Code": "active"
            },
            "Description": "Default Route"
        },
        {
            "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
            "DestinationCidr": "0.0.0.0/0",
            "TargetSubnet": "subnet-0123456789abcabca",
            "Type": "Nat",
            "Origin": "add-route",
            "Status": {
                "Code": "active"
            }
        }
    ]
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Routes](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-routes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClientVpnRoutes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-client-vpn-routes.html)」を参照してください。

### `describe-client-vpn-target-networks`
<a name="ec2_DescribeClientVpnTargetNetworks_cli_2_topic"></a>

次のコード例は、`describe-client-vpn-target-networks` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントのターゲットネットワークを記述するには**  
次の `describe-client-vpn-target-networks` の例では、指定したクライアント VPN エンドポイントのターゲットネットワークの詳細を表示します。  

```
aws ec2 describe-client-vpn-target-networks \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "ClientVpnTargetNetworks": [
        {
            "AssociationId": "cvpn-assoc-012e837060753dc3d",
            "VpcId": "vpc-11111222222333333",
            "TargetNetworkId": "subnet-0123456789abcabca",
            "ClientVpnEndpointId": "cvpn-endpoint-123456789123abcde",
            "Status": {
                "Code": "associating"
            },
            "SecurityGroups": [
                "sg-012345678910abcab"
            ]
        }
    ]
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Target Networks](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-target.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClientVpnTargetNetworks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-client-vpn-target-networks.html)」を参照してください。

### `describe-coip-pools`
<a name="ec2_DescribeCoipPools_cli_2_topic"></a>

次のコード例は、`describe-coip-pools` を使用する方法を示しています。

**AWS CLI**  
**顧客所有の IP アドレスプールを記述するには**  
次の の`describe-coip-pools`例では、 AWS アカウントの顧客所有の IP アドレスプールについて説明します。  

```
aws ec2 describe-coip-pools
```
出力:  

```
{
    "CoipPools": [
        {
            "PoolId": "ipv4pool-coip-123a45678bEXAMPLE",
            "PoolCidrs": [
                "0.0.0.0/0"
            ],
            "LocalGatewayRouteTableId": "lgw-rtb-059615ef7dEXAMPLE",
            "PoolArn": "arn:aws:ec2:us-west-2:123456789012:coip-pool/ipv4pool-coip-123a45678bEXAMPLE"
        }
    ]
}
```
CoIP の詳細については、「*AWS Outposts ユーザーガイド*」の「[カスタマー所有の IP アドレス](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-networking-components.html#ip-addressing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCoipPools](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-coip-pools.html)」を参照してください。

### `describe-conversion-tasks`
<a name="ec2_DescribeConversionTasks_cli_2_topic"></a>

次のコード例は、`describe-conversion-tasks` を使用する方法を示しています。

**AWS CLI**  
**変換タスクのステータスを表示するには**  
この例では、ID import-i-ffvko9js を持つ変換タスクのステータスを返します。  
コマンド:  

```
aws ec2 describe-conversion-tasks --conversion-task-ids import-i-ffvko9js
```
出力:  

```
{
    "ConversionTasks": [
        {
            "ConversionTaskId": "import-i-ffvko9js",
            "ImportInstance": {
                "InstanceId": "i-1234567890abcdef0",
                "Volumes": [
                    {
                        "Volume": {
                            "Id": "vol-049df61146c4d7901",
                            "Size": 16
                        },
                        "Status": "completed",
                        "Image": {
                            "Size": 1300687360,
                            "ImportManifestUrl": "https://s3.amazonaws.com/myimportbucket/411443cd-d620-4f1c-9d66-13144EXAMPLE/RHEL5.vmdkmanifest.xml?AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&Expires=140EXAMPLE&Signature=XYNhznHNgCqsjDxL9wRL%2FJvEXAMPLE",
                            "Format": "VMDK"
                        },
                        "BytesConverted": 1300682960,
                        "AvailabilityZone": "us-east-1d"
                    }
                ]
            },
            "ExpirationTime": "2014-05-14T22:06:23Z",
            "State": "completed"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConversionTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-conversion-tasks.html)」を参照してください。

### `describe-customer-gateways`
<a name="ec2_DescribeCustomerGateways_cli_2_topic"></a>

次のコード例は、`describe-customer-gateways` を使用する方法を示しています。

**AWS CLI**  
**カスタマーゲートウェイを記述するには**  
この例では、カスタマーゲートウェイを記述します。  
コマンド:  

```
aws ec2 describe-customer-gateways
```
出力:  

```
{
    "CustomerGateways": [
        {
            "CustomerGatewayId": "cgw-b4dc3961",
            "IpAddress": "203.0.113.12",
            "State": "available",
            "Type": "ipsec.1",
            "BgpAsn": "65000"
        },
        {
            "CustomerGatewayId": "cgw-0e11f167",
            "IpAddress": "12.1.2.3",
            "State": "available",
            "Type": "ipsec.1",
            "BgpAsn": "65534"
        }
    ]
}
```
**特定のカスタマーゲートウェイを記述するには**  
この例では、指定されたカスタマーゲートウェイを記述します。  
コマンド:  

```
aws ec2 describe-customer-gateways --customer-gateway-ids cgw-0e11f167
```
出力:  

```
{
    "CustomerGateways": [
        {
            "CustomerGatewayId": "cgw-0e11f167",
            "IpAddress": "12.1.2.3",
            "State": "available",
            "Type": "ipsec.1",
            "BgpAsn": "65534"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomerGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-customer-gateways.html)」を参照してください。

### `describe-dhcp-options`
<a name="ec2_DescribeDhcpOptions_cli_2_topic"></a>

次のコード例は、`describe-dhcp-options` を使用する方法を示しています。

**AWS CLI**  
**例 1: DHCP オプションを記述するには**  
次の `describe-dhcp-options` の例では、DHCP の詳細を取得します。  

```
aws ec2 describe-dhcp-options
```
出力:  

```
{
    "DhcpOptions": [
        {
            "DhcpConfigurations": [
                {
                    "Key": "domain-name",
                    "Values": [
                        {
                            "Value": "us-east-2.compute.internal"
                        }
                    ]
                },
                {
                    "Key": "domain-name-servers",
                    "Values": [
                        {
                            "Value": "AmazonProvidedDNS"
                        }
                    ]
                }
            ],
            "DhcpOptionsId": "dopt-19edf471",
            "OwnerId": "111122223333"
        },
        {
            "DhcpConfigurations": [
                {
                    "Key": "domain-name",
                    "Values": [
                        {
                            "Value": "us-east-2.compute.internal"
                        }
                    ]
                },
                {
                    "Key": "domain-name-servers",
                    "Values": [
                        {
                            "Value": "AmazonProvidedDNS"
                        }
                    ]
                }
            ],
            "DhcpOptionsId": "dopt-fEXAMPLE",
            "OwnerId": "111122223333"
        }
    ]
}
```
詳細については、「*AWS VPC ユーザーガイド*」の「[Working with DHCP Option Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html#DHCPOptionSet)」を参照してください。  
**例 2: DHCP オプションを記述し、出力をフィルタリングするには**  
次の `describe-dhcp-options` の例では、DHCP オプションを記述し、フィルターを使用して、ドメインネームサーバーに `example.com` を持つ DHCP オプションのみを返します。この例では、`--query` パラメータを使用して、出力に設定情報と ID のみを表示します。  

```
aws ec2 describe-dhcp-options \
    --filters Name=key,Values=domain-name-servers Name=value,Values=example.com \
    --query "DhcpOptions[*].[DhcpConfigurations,DhcpOptionsId]"
```
出力:  

```
[
    [
        [
            {
                "Key": "domain-name",
                "Values": [
                    {
                        "Value": "example.com"
                    }
                ]
            },
            {
                "Key": "domain-name-servers",
                "Values": [
                    {
                        "Value": "172.16.16.16"
                    }
                ]
            }
        ],
        "dopt-001122334455667ab"
    ]
]
```
詳細については、「*AWS VPC ユーザーガイド*」の「[Working with DHCP Option Sets](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html#DHCPOptionSet)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDhcpOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-dhcp-options.html)」を参照してください。

### `describe-egress-only-internet-gateways`
<a name="ec2_DescribeEgressOnlyInternetGateways_cli_2_topic"></a>

次のコード例は、`describe-egress-only-internet-gateways` を使用する方法を示しています。

**AWS CLI**  
**Egress-Only インターネットゲートウェイを記述するには**  
この例では、Egress-Only インターネットゲートウェイを記述します。  
コマンド:  

```
aws ec2 describe-egress-only-internet-gateways
```
出力:  

```
{
  "EgressOnlyInternetGateways": [
      {
          "EgressOnlyInternetGatewayId": "eigw-015e0e244e24dfe8a",
          "Attachments": [
              {
                  "State": "attached",
                  "VpcId": "vpc-0c62a468"
              }
          ]
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEgressOnlyInternetGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-egress-only-internet-gateways.html)」を参照してください。

### `describe-elastic-gpus`
<a name="ec2_DescribeElasticGpus_cli_2_topic"></a>

次のコード例は、`describe-elastic-gpus` を使用する方法を示しています。

**AWS CLI**  
**Elastic GPU を記述するには**  
コマンド:  

```
aws ec2 describe-elastic-gpus --elastic-gpu-ids egpu-12345678901234567890abcdefghijkl
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeElasticGpus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-elastic-gpus.html)」を参照してください。

### `describe-export-image-tasks`
<a name="ec2_DescribeExportImageTasks_cli_2_topic"></a>

次のコード例は、`describe-export-image-tasks` を使用する方法を示しています。

**AWS CLI**  
**イメージのエクスポートタスクをモニタリングするには**  
次の `describe-export-image-tasks` の例では、指定したイメージのエクスポートタスクのステータスをチェックします。Amazon S3 の結果のイメージファイルは `my-export-bucket/exports/export-ami-1234567890abcdef0.vmdk` です。  

```
aws ec2 describe-export-image-tasks \
    --export-image-task-ids export-ami-1234567890abcdef0
```
進行中のイメージのエクスポートタスクの出力。  

```
{
    "ExportImageTasks": [
        {
            "ExportImageTaskId": "export-ami-1234567890abcdef0"
            "Progress": "21",
            "S3ExportLocation": {
                "S3Bucket": "my-export-bucket",
                "S3Prefix": "exports/"
            },
            "Status": "active",
            "StatusMessage": "updating"
        }
    ]
}
```
完了したイメージのエクスポートタスクの出力。  

```
{
    "ExportImageTasks": [
        {
            "ExportImageTaskId": "export-ami-1234567890abcdef0"
            "S3ExportLocation": {
                "S3Bucket": "my-export-bucket",
                "S3Prefix": "exports/"
            },
            "Status": "completed"
        }
    ]
}
```
詳細については、「*VM Import/Export ユーザーガイド*」の「[Export a VM from an AMI](https://docs.aws.amazon.com/vm-import/latest/userguide/vmexport_image.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeExportImageTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-export-image-tasks.html)」を参照してください。

### `describe-export-tasks`
<a name="ec2_DescribeExportTasks_cli_2_topic"></a>

次のコード例は、`describe-export-tasks` を使用する方法を示しています。

**AWS CLI**  
**インスタンスエクスポートタスクの詳細を一覧表示するには**  
この例では、ID export-i-fh8sjjsq を使用したエクスポートタスクを記述します。  
コマンド:  

```
aws ec2 describe-export-tasks --export-task-ids export-i-fh8sjjsq
```
出力:  

```
{
    "ExportTasks": [
        {
            "State": "active",
            "InstanceExportDetails": {
                "InstanceId": "i-1234567890abcdef0",
                "TargetEnvironment": "vmware"
            },
            "ExportToS3Task": {
                "S3Bucket": "myexportbucket",
                "S3Key": "RHEL5export-i-fh8sjjsq.ova",
                "DiskImageFormat": "vmdk",
                "ContainerFormat": "ova"
            },
            "Description": "RHEL5 instance",
            "ExportTaskId": "export-i-fh8sjjsq"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeExportTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-export-tasks.html)」を参照してください。

### `describe-fast-launch-images`
<a name="ec2_DescribeFastLaunchImages_cli_2_topic"></a>

次のコード例は、`describe-fast-launch-images` を使用する方法を示しています。

**AWS CLI**  
**高速起動用に設定された Windows AMI の詳細を記述するには**  
次の `describe-fast-launch-images` の例では、高速起動用に設定されたアカウント内にある各 AMI の詳細を説明しています。この詳細には、リソースタイプ、スナップショット設定、起動テンプレートの詳細、並列起動の最大数、AMI 所有者 ID、高速起動設定の状態、状態が変更された理由、および状態変更が発生した時間などがあります。  

```
aws ec2 describe-fast-launch-images
```
出力:  

```
{
    "FastLaunchImages": [
        {
            "ImageId": "ami-01234567890abcedf",
            "ResourceType": "snapshot",
            "SnapshotConfiguration": {},
            "LaunchTemplate": {
                "LaunchTemplateId": "lt-01234567890abcedf",
                "LaunchTemplateName": "EC2FastLaunchDefaultResourceCreation-a8c6215d-94e6-441b-9272-dbd1f87b07e2",
                "Version": "1"
            },
            "MaxParallelLaunches": 6,
            "OwnerId": "0123456789123",
            "State": "enabled",
            "StateTransitionReason": "Client.UserInitiated",
            "StateTransitionTime": "2022-01-27T22:20:06.552000+00:00"
        }
    ]
}
```
起動を高速化するための Windows AMI の設定の詳細については、「*Amazon EC2 ユーザーガイド*」の「[Configure your AMI for faster launching](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/windows-ami-version-history.html#win-ami-config-fast-launch)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFastLaunchImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-fast-launch-images.html)」を参照してください。

### `describe-fast-snapshot-restores`
<a name="ec2_DescribeFastSnapshotRestores_cli_2_topic"></a>

次のコード例は、`describe-fast-snapshot-restores` を使用する方法を示しています。

**AWS CLI**  
**高速スナップショットを記述するには**  
次の `describe-fast-snapshot-restores` の例では、`disabled` の状態のすべての高速スナップショット復元に関する詳細を表示します。  

```
aws ec2 describe-fast-snapshot-restores \
    --filters Name=state,Values=disabled
```
出力:  

```
{
    "FastSnapshotRestores": [
        {
            "SnapshotId": "snap-1234567890abcdef0",
            "AvailabilityZone": "us-west-2c",
            "State": "disabled",
            "StateTransitionReason": "Client.UserInitiated - Lifecycle state transition",
            "OwnerId": "123456789012",
            "EnablingTime": "2020-01-25T23:57:49.596Z",
            "OptimizingTime": "2020-01-25T23:58:25.573Z",
            "EnabledTime": "2020-01-25T23:59:29.852Z",
            "DisablingTime": "2020-01-26T00:40:56.069Z",
            "DisabledTime": "2020-01-26T00:41:27.390Z"
        }
    ]
}
```
次の `describe-fast-snapshot-restores` の例では、すべての高速スナップショット復元について説明します。  

```
aws ec2 describe-fast-snapshot-restores
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFastSnapshotRestores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-fast-snapshot-restores.html)」を参照してください。

### `describe-fleet-history`
<a name="ec2_DescribeFleetHistory_cli_2_topic"></a>

次のコード例は、`describe-fleet-history` を使用する方法を示しています。

**AWS CLI**  
**EC2 フリートの履歴を記述するには**  
次の `describe-fleet-history` の例では、指定した時刻から始まる、指定した EC2 フリートの履歴を返します。出力は、2 つの実行中のインスタンスを持つ EC2 フリート用です。  

```
aws ec2 describe-fleet-history \
    --fleet-id fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE \
    --start-time 2020-09-01T00:00:00Z
```
出力:  

```
{
    "HistoryRecords": [
        {
            "EventInformation": {
                "EventSubType": "submitted"
            },
            "EventType": "fleetRequestChange",
            "Timestamp": "2020-09-01T18:26:05.000Z"
        },
        {
            "EventInformation": {
                "EventSubType": "active"
            },
            "EventType": "fleetRequestChange",
            "Timestamp": "2020-09-01T18:26:15.000Z"
        },
        {
            "EventInformation": {
                "EventDescription": "t2.small, ami-07c8bc5c1ce9598c3, ...",
                "EventSubType": "progress"
            },
            "EventType": "fleetRequestChange",
            "Timestamp": "2020-09-01T18:26:17.000Z"
        },
        {
            "EventInformation": {
                "EventDescription": "{\"instanceType\":\"t2.small\", ...}",
                "EventSubType": "launched",
                "InstanceId": "i-083a1c446e66085d2"
            },
            "EventType": "instanceChange",
            "Timestamp": "2020-09-01T18:26:17.000Z"
        },
        {
            "EventInformation": {
                "EventDescription": "{\"instanceType\":\"t2.small\", ...}",
                "EventSubType": "launched",
                "InstanceId": "i-090db02406cc3c2d6"
            },
            "EventType": "instanceChange",
            "Timestamp": "2020-09-01T18:26:17.000Z"
        }
    ],
    "LastEvaluatedTime": "2020-09-01T19:10:19.000Z",
    "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE",
    "StartTime": "2020-08-31T23:53:20.000Z"
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Managing an EC2 Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-ec2-fleet.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleetHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-fleet-history.html)」を参照してください。

### `describe-fleet-instances`
<a name="ec2_DescribeFleetInstances_cli_2_topic"></a>

次のコード例は、`describe-fleet-instances` を使用する方法を示しています。

**AWS CLI**  
**EC2 フリートの実行中のインスタンスを記述するには**  
次の `describe-fleet-instances` の例では、指定した EC2 フリートの実行中のインスタンスについて説明します。  

```
aws ec2 describe-fleet-instances \
    --fleet-id 12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE
```
出力:  

```
{
    "ActiveInstances": [
        {
            "InstanceId": "i-090db02406cc3c2d6",
            "InstanceType": "t2.small",
            "SpotInstanceRequestId": "sir-a43gtpfk",
            "InstanceHealth": "healthy"
        },
        {
            "InstanceId": "i-083a1c446e66085d2",
            "InstanceType": "t2.small",
            "SpotInstanceRequestId": "sir-iwcit2nj",
            "InstanceHealth": "healthy"
        }
    ],
    "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE"
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Managing an EC2 Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-ec2-fleet.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleetInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-fleet-instances.html)」を参照してください。

### `describe-fleets`
<a name="ec2_DescribeFleets_cli_2_topic"></a>

次のコード例は、`describe-fleets` を使用する方法を示しています。

**AWS CLI**  
**EC2 フリートを記述するには**  
次の `describe-fleets` の例では、指定した EC2 フリートについて説明します。  

```
aws ec2 describe-fleets \
    --fleet-ids fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE
```
出力:  

```
{
    "Fleets": [
        {
            "ActivityStatus": "pending_fulfillment",
            "CreateTime": "2020-09-01T18:26:05.000Z",
            "FleetId": "fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE",
            "FleetState": "active",
            "ExcessCapacityTerminationPolicy": "termination",
            "FulfilledCapacity": 0.0,
            "FulfilledOnDemandCapacity": 0.0,
            "LaunchTemplateConfigs": [
                {
                    "LaunchTemplateSpecification": {
                        "LaunchTemplateId": "lt-0e632f2855a979cd5",
                        "Version": "1"
                    }
                }
            ],
            "TargetCapacitySpecification": {
                "TotalTargetCapacity": 2,
                "OnDemandTargetCapacity": 0,
                "SpotTargetCapacity": 2,
                "DefaultTargetCapacityType": "spot"
            },
            "TerminateInstancesWithExpiration": false,
            "Type": "maintain",
            "ReplaceUnhealthyInstances": false,
            "SpotOptions": {
                "AllocationStrategy": "lowestPrice",
                "InstanceInterruptionBehavior": "terminate",
                "InstancePoolsToUseCount": 1
            },
            "OnDemandOptions": {
                "AllocationStrategy": "lowestPrice"
            }
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Managing an EC2 Fleet](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-ec2-fleet.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-fleets.html)」を参照してください。

### `describe-flow-logs`
<a name="ec2_DescribeFlowLogs_cli_2_topic"></a>

次のコード例は、`describe-flow-logs` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのフローログを記述するには**  
次の `describe-flow-logs` の例では、すべてのフローログの詳細を表示します。  

```
aws ec2 describe-flow-logs
```
出力:  

```
{
    "FlowLogs": [
        {
            "CreationTime": "2018-02-21T13:22:12.644Z",
            "DeliverLogsPermissionArn": "arn:aws:iam::123456789012:role/flow-logs-role",
            "DeliverLogsStatus": "SUCCESS",
            "FlowLogId": "fl-aabbccdd112233445",
            "MaxAggregationInterval": 600,
            "FlowLogStatus": "ACTIVE",
            "LogGroupName": "FlowLogGroup",
            "ResourceId": "subnet-12345678901234567",
            "TrafficType": "ALL",
            "LogDestinationType": "cloud-watch-logs",
            "LogFormat": "${version} ${account-id} ${interface-id} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${protocol} ${packets} ${bytes} ${start} ${end} ${action} ${log-status}"
        },
        {
            "CreationTime": "2020-02-04T15:22:29.986Z",
            "DeliverLogsStatus": "SUCCESS",
            "FlowLogId": "fl-01234567890123456",
            "MaxAggregationInterval": 60,
            "FlowLogStatus": "ACTIVE",
            "ResourceId": "vpc-00112233445566778",
            "TrafficType": "ACCEPT",
            "LogDestinationType": "s3",
            "LogDestination": "arn:aws:s3:::my-flow-log-bucket/custom",
            "LogFormat": "${version} ${vpc-id} ${subnet-id} ${instance-id} ${interface-id} ${account-id} ${type} ${srcaddr} ${dstaddr} ${srcport} ${dstport} ${pkt-srcaddr} ${pkt-dstaddr} ${protocol} ${bytes} ${packets} ${start} ${end} ${action} ${tcp-flags} ${log-status}"
        }
    ]
}
```
**例 2: フローログのサブセットを記述するには**  
次の `describe-flow-logs` の例では、フィルターを使用して、Amazon CloudWatch Logs の指定されたロググループに含まれるフローログの詳細のみを表示します。  

```
aws ec2 describe-flow-logs \
    --filter "Name=log-group-name,Values=MyFlowLogs"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFlowLogs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-flow-logs.html)」を参照してください。

### `describe-fpga-image-attribute`
<a name="ec2_DescribeFpgaImageAttribute_cli_2_topic"></a>

次のコード例は、`describe-fpga-image-attribute` を使用する方法を示しています。

**AWS CLI**  
**Amazon FPGA イメージの属性を記述するには**  
この例では、指定された AFI のロードアクセス許可を記述します。  
コマンド:  

```
aws ec2 describe-fpga-image-attribute --fpga-image-id afi-0d123e123bfc85abc --attribute loadPermission
```
出力:  

```
{
  "FpgaImageAttribute": {
      "FpgaImageId": "afi-0d123e123bfc85abc",
      "LoadPermissions": [
          {
              "UserId": "123456789012"
          }
      ]
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFpgaImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-fpga-image-attribute.html)」を参照してください。

### `describe-fpga-images`
<a name="ec2_DescribeFpgaImages_cli_2_topic"></a>

次のコード例は、`describe-fpga-images` を使用する方法を示しています。

**AWS CLI**  
**Amazon FPGA イメージを記述するには**  
この例では、アカウント `123456789012` が所有する AFI を記述します。  
コマンド:  

```
aws ec2 describe-fpga-images --filters Name=owner-id,Values=123456789012
```
出力:  

```
{
  "FpgaImages": [
      {
          "UpdateTime": "2017-12-22T12:09:14.000Z",
          "Name": "my-afi",
          "PciId": {
              "SubsystemVendorId": "0xfedd",
              "VendorId": "0x1d0f",
              "DeviceId": "0xf000",
              "SubsystemId": "0x1d51"
          },
          "FpgaImageGlobalId": "agfi-123cb27b5e84a0abc",
          "Public": false,
          "State": {
              "Code": "available"
          },
          "ShellVersion": "0x071417d3",
          "OwnerId": "123456789012",
          "FpgaImageId": "afi-0d123e123bfc85abc",
          "CreateTime": "2017-12-22T11:43:33.000Z",
          "Description": "my-afi"
      }
  ]
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DescribeFpgaImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-fpga-images.html)」を参照してください。

### `describe-host-reservation-offerings`
<a name="ec2_DescribeHostReservationOfferings_cli_2_topic"></a>

次のコード例は、`describe-host-reservation-offerings` を使用する方法を示しています。

**AWS CLI**  
**専有ホスト予約サービスを記述するには**  
この例では、購入可能な M4 インスタンスファミリー専有ホストの予約を記述します。  
コマンド:  

```
aws ec2 describe-host-reservation-offerings --filter Name=instance-family,Values=m4
```
出力:  

```
{
  "OfferingSet": [
      {
          "HourlyPrice": "1.499",
          "OfferingId": "hro-03f707bf363b6b324",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "UpfrontPrice": "0.000",
          "Duration": 31536000
      },
      {
          "HourlyPrice": "1.045",
          "OfferingId": "hro-0ef9181cabdef7a02",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "UpfrontPrice": "0.000",
          "Duration": 94608000
      },
      {
          "HourlyPrice": "0.714",
          "OfferingId": "hro-04567a15500b92a51",
          "InstanceFamily": "m4",
          "PaymentOption": "PartialUpfront",
          "UpfrontPrice": "6254.000",
          "Duration": 31536000
      },
      {
          "HourlyPrice": "0.484",
          "OfferingId": "hro-0d5d7a9d23ed7fbfe",
          "InstanceFamily": "m4",
          "PaymentOption": "PartialUpfront",
          "UpfrontPrice": "12720.000",
          "Duration": 94608000
      },
      {
          "HourlyPrice": "0.000",
          "OfferingId": "hro-05da4108ca998c2e5",
          "InstanceFamily": "m4",
          "PaymentOption": "AllUpfront",
          "UpfrontPrice": "23913.000",
          "Duration": 94608000
      },
      {
          "HourlyPrice": "0.000",
          "OfferingId": "hro-0a9f9be3b95a3dc8f",
          "InstanceFamily": "m4",
          "PaymentOption": "AllUpfront",
          "UpfrontPrice": "12257.000",
          "Duration": 31536000
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHostReservationOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-host-reservation-offerings.html)」を参照してください。

### `describe-host-reservations`
<a name="ec2_DescribeHostReservations_cli_2_topic"></a>

次のコード例は、`describe-host-reservations` を使用する方法を示しています。

**AWS CLI**  
**アカウントの専有ホスト予約を記述するには**  
この例では、アカウントの専有ホストの予約を記述します。  
コマンド:  

```
aws ec2 describe-host-reservations
```
出力:  

```
{
  "HostReservationSet": [
      {
          "Count": 1,
          "End": "2019-01-10T12:14:09Z",
          "HourlyPrice": "1.499",
          "InstanceFamily": "m4",
          "OfferingId": "hro-03f707bf363b6b324",
          "PaymentOption": "NoUpfront",
          "State": "active",
          "HostIdSet": [
              "h-013abcd2a00cbd123"
          ],
          "Start": "2018-01-10T12:14:09Z",
          "HostReservationId": "hr-0d418a3a4ffc669ae",
          "UpfrontPrice": "0.000",
          "Duration": 31536000
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHostReservations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-host-reservations.html)」を参照してください。

### `describe-hosts`
<a name="ec2_DescribeHosts_cli_2_topic"></a>

次のコード例は、`describe-hosts` を使用する方法を示しています。

**AWS CLI**  
**専有ホストの詳細を表示するには**  
次の の`describe-hosts`例では、 AWS アカウント内の `available` Dedicated Hosts の詳細を表示します。  

```
aws ec2 describe-hosts --filter "Name=state,Values=available"
```
出力:  

```
{
    "Hosts": [
        {
            "HostId": "h-07879acf49EXAMPLE",
            "Tags": [
                {
                    "Value": "production",
                    "Key": "purpose"
                }
            ],
            "HostProperties": {
                "Cores": 48,
                "TotalVCpus": 96,
                "InstanceType": "m5.large",
                "Sockets": 2
            },
            "Instances": [],
            "State": "available",
            "AvailabilityZone": "eu-west-1a",
            "AvailableCapacity": {
                "AvailableInstanceCapacity": [
                    {
                        "AvailableCapacity": 48,
                        "InstanceType": "m5.large",
                        "TotalCapacity": 48
                    }
                ],
                "AvailableVCpus": 96
            },
            "HostRecovery": "on",
            "AllocationTime": "2019-08-19T08:57:44.000Z",
            "AutoPlacement": "off"
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Viewing Dedicated Hosts](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/how-dedicated-hosts-work.html#dedicated-hosts-managing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-hosts.html)」を参照してください。

### `describe-iam-instance-profile-associations`
<a name="ec2_DescribeIamInstanceProfileAssociations_cli_2_topic"></a>

次のコード例は、`describe-iam-instance-profile-associations` を使用する方法を示しています。

**AWS CLI**  
**IAM インスタンスプロファイルの関連付けについて説明するには**  
この例では、IAM インスタンスプロファイルのすべての関連付けについて説明しています。  
コマンド:  

```
aws ec2 describe-iam-instance-profile-associations
```
出力:  

```
{
  "IamInstanceProfileAssociations": [
      {
          "InstanceId": "i-09eb09efa73ec1dee",
          "State": "associated",
          "AssociationId": "iip-assoc-0db249b1f25fa24b8",
          "IamInstanceProfile": {
              "Id": "AIPAJVQN4F5WVLGCJDRGM",
              "Arn": "arn:aws:iam::123456789012:instance-profile/admin-role"
          }
      },
      {
          "InstanceId": "i-0402909a2f4dffd14",
          "State": "associating",
          "AssociationId": "iip-assoc-0d1ec06278d29f44a",
          "IamInstanceProfile": {
              "Id": "AGJAJVQN4F5WVLGCJABCM",
              "Arn": "arn:aws:iam::123456789012:instance-profile/user1-role"
          }
      }
   ]
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeIamInstanceProfileAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-iam-instance-profile-associations.html)」を参照してください。

### `describe-id-format`
<a name="ec2_DescribeIdFormat_cli_2_topic"></a>

次のコード例は、`describe-id-format` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースの ID 形式を記述するには**  
次の `describe-id-format` の例では、セキュリティグループの ID 形式について説明します。  

```
aws ec2 describe-id-format \
    --resource security-group
```
次の出力例では、`Deadline` 値は、このリソースタイプが短い ID 形式から長い ID 形式に完全に切り替わる期限が、2018 年 8 月 15 日の 00:00 UTC に終了したことを示します。  

```
{
    "Statuses": [
        {
            "Deadline": "2018-08-15T00:00:00.000Z",
            "Resource": "security-group",
            "UseLongIds": true
        }
    ]
}
```
**例 2: すべてのリソースの ID 形式を記述するには**  
次の `describe-id-format` の例では、すべてのリソースタイプの ID 形式について説明します。短い ID 形式をサポートしたすべてのリソースタイプは、長い ID 形式を使用するように切り替えられました。  

```
aws ec2 describe-id-format
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-id-format.html)」を参照してください。

### `describe-identity-id-format`
<a name="ec2_DescribeIdentityIdFormat_cli_2_topic"></a>

次のコード例は、`describe-identity-id-format` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールの ID 形式を記述するには**  
次の`describe-identity-id-format`例では、 AWS アカウントの IAM ロールによって作成されたインスタンス`EC2Role`によって受信される ID 形式について説明します。  

```
aws ec2 describe-identity-id-format \
    --principal-arn arn:aws:iam::123456789012:role/my-iam-role \
    --resource instance
```
次の出力は、このロールによって作成されたインスタンスが長い ID 形式で ID を受け取ることを示します。  

```
{
    "Statuses": [
        {
            "Deadline": "2016-12-15T00:00:00Z",
            "Resource": "instance",
            "UseLongIds": true
        }
    ]
}
```
**IAM ユーザーの ID 形式を記述するには**  
次の`describe-identity-id-format`例では、`AdminUser` AWS アカウントの IAM ユーザーが作成したスナップショットによって受信される ID 形式について説明します。  

```
aws ec2 describe-identity-id-format \
    --principal-arn arn:aws:iam::123456789012:user/AdminUser \
    --resource snapshot
```
出力は、このユーザーによって作成されたスナップショットが長い ID 形式で ID を受け取ることを示します。  

```
{
    "Statuses": [
        {
            "Deadline": "2016-12-15T00:00:00Z",
            "Resource": "snapshot",
            "UseLongIds": true
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIdentityIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-identity-id-format.html)」を参照してください。

### `describe-image-attribute`
<a name="ec2_DescribeImageAttribute_cli_2_topic"></a>

次のコード例は、`describe-image-attribute` を使用する方法を示しています。

**AWS CLI**  
**AMI の起動許可を記述するには**  
この例では、指定された AMI の起動許可を記述します。  
コマンド:  

```
aws ec2 describe-image-attribute --image-id ami-5731123e --attribute launchPermission
```
出力:  

```
{
    "LaunchPermissions": [
        {
            "UserId": "123456789012"
        }
    ],
    "ImageId": "ami-5731123e",
}
```
**AMI の製品コードを記述するには**  
この例では、指定された AMI の製品コードを記述します。この AMI には製品コードはありません。  
コマンド:  

```
aws ec2 describe-image-attribute --image-id ami-5731123e --attribute productCodes
```
出力:  

```
{
    "ProductCodes": [],
    "ImageId": "ami-5731123e",
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-image-attribute.html)」を参照してください。

### `describe-images`
<a name="ec2_DescribeImages_cli_2_topic"></a>

次のコード例は、`describe-images` を使用する方法を示しています。

**AWS CLI**  
**例 1: AMI を説明するには**  
次の `describe-images` の例では、指定された AMI 内のインターフェイスについて説明します。  

```
aws ec2 describe-images \
    --region us-east-1 \
    --image-ids ami-1234567890EXAMPLE
```
出力:  

```
{
    "Images": [
        {
            "VirtualizationType": "hvm",
            "Description": "Provided by Red Hat, Inc.",
            "PlatformDetails": "Red Hat Enterprise Linux",
            "EnaSupport": true,
            "Hypervisor": "xen",
            "State": "available",
            "SriovNetSupport": "simple",
            "ImageId": "ami-1234567890EXAMPLE",
            "UsageOperation": "RunInstances:0010",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/sda1",
                    "Ebs": {
                        "SnapshotId": "snap-111222333444aaabb",
                        "DeleteOnTermination": true,
                        "VolumeType": "gp2",
                        "VolumeSize": 10,
                        "Encrypted": false
                    }
                }
            ],
            "Architecture": "x86_64",
            "ImageLocation": "123456789012/RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2",
            "RootDeviceType": "ebs",
            "OwnerId": "123456789012",
            "RootDeviceName": "/dev/sda1",
            "CreationDate": "2019-05-10T13:17:12.000Z",
            "Public": true,
            "ImageType": "machine",
            "Name": "RHEL-8.0.0_HVM-20190618-x86_64-1-Hourly2-GP2"
        }
    ]
}
```
詳細については「*アマゾン EC2 ユーザーガイド*」の「[アマゾン マシンイメージ (AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)」を参照してください。  
**例 2: フィルターに基づいて AMI を説明するには**  
次の `describe-images` の例では、Amazon が提供する、Amazon EBS を基にした Windows AMI を説明しています。  

```
aws ec2 describe-images \
    --owners amazon \
    --filters "Name=platform,Values=windows" "Name=root-device-type,Values=ebs"
```
`describe-images` の出力例については、例 1 を参照してください。  
フィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[リソースの一覧表示とフィルタリングの方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)」を参照してください。  
**例 3: タグに基づいて AMI を説明するには**  
次の `describe-images` の例では、タグ `Type=Custom` が付いたすべての AMI について説明しています。この例では、`--query` パラメータを使用して AMI ID のみを表示します。  

```
aws ec2 describe-images \
    --filters "Name=tag:Type,Values=Custom" \
    --query 'Images[*].[ImageId]' \
    --output text
```
出力:  

```
ami-1234567890EXAMPLE
ami-0abcdef1234567890
```
タグフィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[タグの使用方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-images.html)」を参照してください。

### `describe-import-image-tasks`
<a name="ec2_DescribeImportImageTasks_cli_2_topic"></a>

次のコード例は、`describe-import-image-tasks` を使用する方法を示しています。

**AWS CLI**  
**イメージのインポートタスクをモニタリングするには**  
次の `describe-import-image-tasks` の例では、指定したイメージのインポートタスクをチェックします。  

```
aws ec2 describe-import-image-tasks \
    --import-task-ids import-ami-1234567890abcdef0
```
進行中のイメージのインポートタスクの出力。  

```
{
    "ImportImageTasks": [
        {
            "ImportTaskId": "import-ami-1234567890abcdef0",
            "Progress": "28",
            "SnapshotDetails": [
                {
                    "DiskImageSize": 705638400.0,
                    "Format": "ova",
                    "Status": "completed",
                    "UserBucket": {
                        "S3Bucket": "my-import-bucket",
                        "S3Key": "vms/my-server-vm.ova"
                    }
                }
            ],
            "Status": "active",
            "StatusMessage": "converting"
        }
    ]
}
```
完了したイメージのインポートタスクの出力。結果の AMI の ID は `ImageId` によって指定されます。  

```
{
    "ImportImageTasks": [
        {
            "ImportTaskId": "import-ami-1234567890abcdef0",
            "ImageId": "ami-1234567890abcdef0",
            "SnapshotDetails": [
                {
                    "DiskImageSize": 705638400.0,
                    "Format": "ova",
                    "SnapshotId": "snap-1234567890abcdef0"
                    "Status": "completed",
                    "UserBucket": {
                        "S3Bucket": "my-import-bucket",
                        "S3Key": "vms/my-server-vm.ova"
                    }
                }
            ],
            "Status": "completed"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeImportImageTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-import-image-tasks.html)」を参照してください。

### `describe-import-snapshot-tasks`
<a name="ec2_DescribeImportSnapshotTasks_cli_2_topic"></a>

次のコード例は、`describe-import-snapshot-tasks` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのインポートタスクをモニタリングするには**  
次の `describe-import-snapshot-tasks` の例では、指定したインポートスナップショットタスクをチェックします。  

```
aws ec2 describe-import-snapshot-tasks \
    --import-task-ids import-snap-1234567890abcdef0
```
進行中のスナップショットのインポートタスクの出力:  

```
{
    "ImportSnapshotTasks": [
        {
            "Description": "My server VMDK",
            "ImportTaskId": "import-snap-1234567890abcdef0",
            "SnapshotTaskDetail": {
                "Description": "My server VMDK",
                "DiskImageSize": "705638400.0",
                "Format": "VMDK",
                "Progress": "42",
                "Status": "active",
                "StatusMessage": "downloading/converting",
                "UserBucket": {
                    "S3Bucket": "my-import-bucket",
                    "S3Key": "vms/my-server-vm.vmdk"
                }
            }
        }
    ]
}
```
完了したスナップショットのインポートタスクの出力。結果のスナップショットの ID は `SnapshotId` によって指定されます。  

```
{
    "ImportSnapshotTasks": [
        {
            "Description": "My server VMDK",
            "ImportTaskId": "import-snap-1234567890abcdef0",
            "SnapshotTaskDetail": {
                "Description": "My server VMDK",
                "DiskImageSize": "705638400.0",
                "Format": "VMDK",
                "SnapshotId": "snap-1234567890abcdef0"
                "Status": "completed",
                "UserBucket": {
                    "S3Bucket": "my-import-bucket",
                    "S3Key": "vms/my-server-vm.vmdk"
                }
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeImportSnapshotTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-import-snapshot-tasks.html)」を参照してください。

### `describe-instance-attribute`
<a name="ec2_DescribeInstanceAttribute_cli_2_topic"></a>

次のコード例は、`describe-instance-attribute` を使用する方法を示しています。

**AWS CLI**  
**インスタンスタイプを記述するには**  
この例では、指定されたインスタンスのインスタンスタイプを記述します。  
コマンド:  

```
aws ec2 describe-instance-attribute --instance-id i-1234567890abcdef0 --attribute instanceType
```
出力:  

```
{
    "InstanceId": "i-1234567890abcdef0"
    "InstanceType": {
        "Value": "t1.micro"
    }
}
```
**disableApiTermination 属性を記述するには**  
この例では、指定されたインスタンスの `disableApiTermination` 属性を記述します。  
コマンド:  

```
aws ec2 describe-instance-attribute --instance-id i-1234567890abcdef0 --attribute disableApiTermination
```
出力:  

```
{
"InstanceId": "i-1234567890abcdef0"
    "DisableApiTermination": {
        "Value": "false"
    }
}
```
**インスタンスのブロックデバイスマッピングを記述するには**  
この例では、指定されたインスタンスの `blockDeviceMapping` 属性を記述します。  
コマンド:  

```
aws ec2 describe-instance-attribute --instance-id i-1234567890abcdef0 --attribute blockDeviceMapping
```
出力:  

```
{
    "InstanceId": "i-1234567890abcdef0"
    "BlockDeviceMappings": [
        {
            "DeviceName": "/dev/sda1",
            "Ebs": {
                "Status": "attached",
                "DeleteOnTermination": true,
                "VolumeId": "vol-049df61146c4d7901",
                "AttachTime": "2013-05-17T22:42:34.000Z"
            }
        },
        {
            "DeviceName": "/dev/sdf",
            "Ebs": {
                "Status": "attached",
                "DeleteOnTermination": false,
                "VolumeId": "vol-049df61146c4d7901",
                "AttachTime": "2013-09-10T23:07:00.000Z"
            }
        }
    ],
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-attribute.html)」を参照してください。

### `describe-instance-connect-endpoints`
<a name="ec2_DescribeInstanceConnectEndpoints_cli_2_topic"></a>

次のコード例は、`describe-instance-connect-endpoints` を使用する方法を示しています。

**AWS CLI**  
**EC2 Instance Connect エンドポイントを記述するには**  
次の `describe-instance-connect-endpoints` の例では、指定した EC2 Instance Connect エンドポイントについて説明します。  

```
aws ec2 describe-instance-connect-endpoints \
    --region us-east-1 \
    --instance-connect-endpoint-ids eice-0123456789example
```
出力:  

```
{
    "InstanceConnectEndpoints": [
        {
            "OwnerId": "111111111111",
            "InstanceConnectEndpointId": "eice-0123456789example",
            "InstanceConnectEndpointArn": "arn:aws:ec2:us-east-1:111111111111:instance-connect-endpoint/eice-0123456789example",
            "State": "create-complete",
            "StateMessage": "",
            "DnsName": "eice-0123456789example.b67b86ba.ec2-instance-connect-endpoint.us-east-1.amazonaws.com",
            "NetworkInterfaceIds": [
                "eni-0123456789example"
            ],
            "VpcId": "vpc-0123abcd",
            "AvailabilityZone": "us-east-1d",
            "CreatedAt": "2023-02-07T12:05:37+00:00",
            "SubnetId": "subnet-0123abcd",
            "Tags": []
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[EC2 Instance Connect Endpoint の作成](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-ec2-instance-connect-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceConnectEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-connect-endpoints.html)」を参照してください。

### `describe-instance-credit-specifications`
<a name="ec2_DescribeInstanceCreditSpecifications_cli_2_topic"></a>

次のコード例は、`describe-instance-credit-specifications` を使用する方法を示しています。

**AWS CLI**  
**1 つ以上のインスタンスの CPU 使用率に関するクレジットオプションを記述するには**  
次の `describe-instance-credit-specifications` の例では、指定したインスタンスの CPU クレジットについて説明します。  

```
aws ec2 describe-instance-credit-specifications \
    --instance-ids i-1234567890abcdef0
```
出力:  

```
{
    "InstanceCreditSpecifications": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "CpuCredits": "unlimited"
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[バーストパフォーマンスインスタンスの使用](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances-how-to.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceCreditSpecifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-credit-specifications.html)」を参照してください。

### `describe-instance-event-notification-attributes`
<a name="ec2_DescribeInstanceEventNotificationAttributes_cli_2_topic"></a>

次のコード例は、`describe-instance-event-notification-attributes` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされたイベント通知のタグを記述するには**  
次の `describe-instance-event-notification-attributes` の例では、スケジュールされたイベント通知に表示されるタグについて説明します。  

```
aws ec2 describe-instance-event-notification-attributes
```
出力:  

```
{
    "InstanceTagAttribute": {
        "InstanceTagKeys": [],
        "IncludeAllTagsOfInstance": true
    }
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Scheduled events for your instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceEventNotificationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-event-notification-attributes.html)」を参照してください。

### `describe-instance-event-windows`
<a name="ec2_DescribeInstanceEventWindows_cli_2_topic"></a>

次のコード例は、`describe-instance-event-windows` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのイベントウィンドウを記述するには**  
次の `describe-instance-event-windows` の例では、指定されたリージョン内のすべてのイベントウィンドウについて説明します。  

```
aws ec2 describe-instance-event-windows \
    --region us-east-1
```
出力:  

```
{
    "InstanceEventWindows": [
        {
            "InstanceEventWindowId": "iew-0abcdef1234567890",
            "Name": "myEventWindowName",
            "CronExpression": "* 21-23 * * 2,3",
            "AssociationTarget": {
                "InstanceIds": [
                    "i-1234567890abcdef0",
                    "i-0598c7d356eba48d7"
                ],
                "Tags": [],
                "DedicatedHostIds": []
            },
            "State": "active",
            "Tags": []
        }

        ...

    ],
    "NextToken": "9d624e0c-388b-4862-a31e-a85c64fc1d4a"
}
```
**例 2: 特定のイベントウィンドウを記述するには**  
次の `describe-instance-event-windows` の例では、`instance-event-window` パラメータを使用して特定のイベントウィンドウを記述し、特定のイベントについて説明します。  

```
aws ec2 describe-instance-event-windows \
    --region us-east-1 \
    --instance-event-window-ids iew-0abcdef1234567890
```
出力:  

```
{
    "InstanceEventWindows": [
        {
            "InstanceEventWindowId": "iew-0abcdef1234567890",
            "Name": "myEventWindowName",
            "CronExpression": "* 21-23 * * 2,3",
            "AssociationTarget": {
                "InstanceIds": [
                    "i-1234567890abcdef0",
                    "i-0598c7d356eba48d7"
                ],
                "Tags": [],
                "DedicatedHostIds": []
            },
            "State": "active",
            "Tags": []
        }
}
```
**例 3: 1 つ以上のフィルターに一致するイベントウィンドウを表示するには**  
次の `describe-instance-event-windows` の例では、`filter` パラメータを使用して 1 つ以上のフィルターに一致するイベントウィンドウについて説明します。`instance-id` フィルターは、指定されたインスタンスに関連付けられているすべてのイベントウィンドウを記述するために使用されます。フィルタを使用すると、直接的な一致が評価されます。ただし、`instance-id` フィルターの場合は異なります。直接一致するインスタンス ID が見つからない場合は、インスタンスのタグや専有ホスト ID (インスタンスが専有ホストの場合) など、イベントウィンドウとの間接的な関連付けにフォールバックされます。  

```
aws ec2 describe-instance-event-windows \
    --region us-east-1 \
    --filters Name=instance-id,Values=i-1234567890abcdef0 \
    --max-results 100 \
    --next-token <next-token-value>
```
出力:  

```
{
    "InstanceEventWindows": [
        {
            "InstanceEventWindowId": "iew-0dbc0adb66f235982",
            "TimeRanges": [
                {
                    "StartWeekDay": "sunday",
                    "StartHour": 2,
                    "EndWeekDay": "sunday",
                    "EndHour": 8
                }
            ],
            "Name": "myEventWindowName",
            "AssociationTarget": {
                "InstanceIds": [],
                "Tags": [],
                "DedicatedHostIds": [
                    "h-0140d9a7ecbd102dd"
                ]
            },
            "State": "active",
            "Tags": []
        }
    ]
}
```
出力例では、インスタンスはイベントウィンドウに関連付けられた専有ホスト上にあります。  
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceEventWindows](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-event-windows.html)」を参照してください。

### `describe-instance-image-metadata`
<a name="ec2_DescribeInstanceImageMetadata_cli_2_topic"></a>

次のコード例は、`describe-instance-image-metadata` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのインスタンスの AMI メタデータの詳細を取得するには**  
次の の`describe-instance-image-metadata`例では、指定されたリージョンの AWS アカウント内のすべてのインスタンスの AMI メタデータについて説明します。  

```
aws ec2 describe-instance-image-metadata \
    --region us-east-1
```
出力:  

```
{
    "InstanceImageMetadata": [
        {
            "InstanceId": "i-1234567890EXAMPLE",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-28T11:25:45+00:00",
            "AvailabilityZone": "us-east-1a",
            "State": {
                "Code": 16,
                "Name": "running"
            },
            "OwnerId": "123412341234",
            "Tags": [
                {
                    "Key": "MyTagName",
                    "Value": "my-tag-value"
                }
            ],
            "ImageMetadata": {
                "ImageId": "ami-0b752bf1df193a6c4",
                "Name": "al2023-ami-2023.5.20240819.0-kernel-6.1-x86_64",
                "OwnerId": "137112412989",
                "State": "available",
                "ImageOwnerAlias": "amazon",
                "CreationDate": "2023-01-25T17:20:40Z",
                "DeprecationTime": "2025-01-25T17:20:40Z",
                "IsPublic": true
            }
        }
    ],
    "NextToken": "...EXAMPLEwIAABAA2JHaFxLnEXAMPLE..."
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[Amazon EC2 の Amazon マシンイメージ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)」を参照してください。  
**例 2: 指定したインスタンスの AMI メタデータの詳細を取得するには**  
次の `describe-instance-image-metadata` の例では、指定したインスタンスの AMI メタデータの詳細を取得します。  

```
aws ec2 describe-instance-image-metadata \
    --region us-east-1 \
    --instance-ids i-1234567890EXAMPLE i-0987654321EXAMPLE
```
出力:  

```
{
    "InstanceImageMetadata": [
        {
            "InstanceId": "i-1234567890EXAMPLE",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-28T11:25:45+00:00",
            "AvailabilityZone": "us-east-1a",
            "State": {
                "Code": 16,
                "Name": "running"
            },
            "OwnerId": "123412341234",
            "Tags": [
                {
                    "Key": "MyTagName",
                    "Value": "my-tag-value"
                }
            ],
            "ImageMetadata": {
                "ImageId": "ami-0b752bf1df193a6c4",
                "Name": "al2023-ami-2023.5.20240819.0-kernel-6.1-x86_64",
                "OwnerId": "137112412989",
                "State": "available",
                "ImageOwnerAlias": "amazon",
                "CreationDate": "2023-01-25T17:20:40Z",
                "DeprecationTime": "2025-01-25T17:20:40Z",
                "IsPublic": true
            }
        },
        {
            "InstanceId": "i-0987654321EXAMPLE",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-28T11:25:45+00:00",
            "AvailabilityZone": "us-east-1a",
            "State": {
                "Code": 16,
                "Name": "running"
            },
            "OwnerId": "123412341234",
            "Tags": [
                {
                    "Key": "MyTagName",
                    "Value": "my-tag-value"
                }
            ],
            "ImageMetadata": {
                "ImageId": "ami-0b752bf1df193a6c4",
                "Name": "al2023-ami-2023.5.20240819.0-kernel-6.1-x86_64",
                "OwnerId": "137112412989",
                "State": "available",
                "ImageOwnerAlias": "amazon",
                "CreationDate": "2023-01-25T17:20:40Z",
                "DeprecationTime": "2025-01-25T17:20:40Z",
                "IsPublic": true
            }
        }
    ]
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[Amazon EC2 の Amazon マシンイメージ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)」を参照してください。  
**例 3: フィルタに基づいてインスタンスの AMI メタデータの詳細を取得するには**  
次の `describe-instance-image-metadata` の例では、`us-east-1a` アベイラビリティーゾーン内の `t2.nano` および `t2.micro` インスタンスの AMI メタデータの詳細を取得します。  

```
aws ec2 describe-instance-image-metadata \
    --region us-east-1 \
    --filters Name=availability-zone,Values=us-east-1a Name=instance-type,Values=t2.nano,t2.micro
```
出力:  

```
{
    "InstanceImageMetadata": [
        {
            "InstanceId": "i-1234567890EXAMPLE",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-28T11:25:45+00:00",
            "AvailabilityZone": "us-east-1a",
            "State": {
                "Code": 16,
                "Name": "running"
            },
            "OwnerId": "123412341234",
            "Tags": [
                {
                    "Key": "MyTagName",
                    "Value": "my-tag-value"
                }
            ],
            "ImageMetadata": {
                "ImageId": "ami-0b752bf1df193a6c4",
                "Name": "al2023-ami-2023.5.20240819.0-kernel-6.1-x86_64",
                "OwnerId": "137112412989",
                "State": "available",
                "ImageOwnerAlias": "amazon",
                "CreationDate": "2023-01-25T17:20:40Z",
                "DeprecationTime": "2025-01-25T17:20:40Z",
                "IsPublic": true
            }
        },
        {
            "InstanceId": "i-0987654321EXAMPLE",
            "InstanceType": "t2.micro",
            "LaunchTime": "2024-08-28T11:25:45+00:00",
            "AvailabilityZone": "us-east-1a",
            "State": {
                "Code": 16,
                "Name": "running"
            },
            "OwnerId": "123412341234",
            "Tags": [
                {
                    "Key": "MyTagName",
                    "Value": "my-tag-value"
                }
            ],
            "ImageMetadata": {
                "ImageId": "ami-0b752bf1df193a6c4",
                "Name": "al2023-ami-2023.5.20240819.0-kernel-6.1-x86_64",
                "OwnerId": "137112412989",
                "State": "available",
                "ImageOwnerAlias": "amazon",
                "CreationDate": "2023-01-25T17:20:40Z",
                "DeprecationTime": "2025-01-25T17:20:40Z",
                "IsPublic": true
            }
        }
    ],
    "NextToken": "...EXAMPLEV7ixRYHwIAABAA2JHaFxLnDAzpatfEXAMPLE..."
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[Amazon EC2 の Amazon マシンイメージ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeInstanceImageMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-image-metadata.html)」を参照してください。

### `describe-instance-status`
<a name="ec2_DescribeInstanceStatus_cli_2_topic"></a>

次のコード例は、`describe-instance-status` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのステータスを表示するには**  
次の `describe-instance-status` の例では、指定したインスタンスの現在のステータスを示しています。  

```
aws ec2 describe-instance-status \
    --instance-ids i-1234567890abcdef0
```
出力:  

```
{
    "InstanceStatuses": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "InstanceState": {
                "Code": 16,
                "Name": "running"
            },
            "AvailabilityZone": "us-east-1d",
            "SystemStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Status": "passed",
                        "Name": "reachability"
                    }
                ]
            },
            "InstanceStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Status": "passed",
                        "Name": "reachability"
                    }
                ]
            }
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[インスタンスのステータスのモニタリング](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeInstanceStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-status.html)」を参照してください。

### `describe-instance-topology`
<a name="ec2_DescribeInstanceTopology_cli_2_topic"></a>

次のコード例は、`describe-instance-topology` を使用する方法を示しています。

**AWS CLI**  
**すべてのインスタンスのインスタンストポロジーを記述するには**  
次の `describe-instance-topology` の例では、このコマンドでサポートされているインスタンスタイプに一致するすべてのインスタンスのトポロジについて説明します。  

```
aws ec2 describe-instance-topology \
    --region us-west-2
```
出力:  

```
{
    "Instances": [
        {
            "InstanceId": "i-1111111111example",
            "InstanceType": "p4d.24xlarge",
            "GroupName": "my-ml-cpg",
            "NetworkNodes": [
                "nn-1111111111example",
                "nn-2222222222example",
                "nn-3333333333example"
            ],
            "ZoneId": "usw2-az2",
            "AvailabilityZone": "us-west-2a"
        },
        {
            "InstanceId": "i-2222222222example",
            "InstanceType": "p4d.24xlarge",
            "NetworkNodes": [
                "nn-1111111111example",
                "nn-2222222222example",
                "nn-3333333333example"
            ],
            "ZoneId": "usw2-az2",
            "AvailabilityZone": "us-west-2a"
        },
        {
            "InstanceId": "i-3333333333example",
            "InstanceType": "trn1.32xlarge",
            "NetworkNodes": [
                "nn-1212121212example",
                "nn-1211122211example",
                "nn-1311133311example"
            ],
            "ZoneId": "usw2-az4",
            "AvailabilityZone": "us-west-2d"
        },
        {
            "InstanceId": "i-444444444example",
            "InstanceType": "trn1.2xlarge",
            "NetworkNodes": [
                "nn-1111111111example",
                "nn-5434334334example",
                "nn-1235301234example"
            ],
            "ZoneId": "usw2-az2",
            "AvailabilityZone": "us-west-2a"
        }
    ],
    "NextToken": "SomeEncryptedToken"
}
```
その他の例を含む詳細については、「*Amazon EC2 ユーザーガイド*」の「[Amazon EC2 インスタンストポロジー](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-topology.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceTopology](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-topology.html)」を参照してください。

### `describe-instance-type-offerings`
<a name="ec2_DescribeInstanceTypeOfferings_cli_2_topic"></a>

次のコード例は、`describe-instance-type-offerings` を使用する方法を示しています。

**AWS CLI**  
**例 1: リージョンで提供されるインスタンスタイプを一覧表示するには**  
次の の`describe-instance-type-offerings`例では、 AWS CLI のデフォルトリージョンとして設定された リージョンで提供されているインスタンスタイプを一覧表示します。  

```
aws ec2 describe-instance-type-offerings
```
別のリージョンで提供されるインスタンスタイプを一覧表示するには、`--region` パラメータを使用してリージョンを指定します。  

```
aws ec2 describe-instance-type-offerings \
    --region us-east-2
```
出力:  

```
{
  "InstanceTypeOfferings": [
      {
          "InstanceType": "m5.2xlarge",
          "LocationType": "region",
          "Location": "us-east-2"
      },
      {
          "InstanceType": "t3.micro",
          "LocationType": "region",
          "Location": "us-east-2"
      },
      ...
  ]
}
```
**例 2: アベイラビリティーゾーンで提供されるインスタンスタイプを一覧表示するには**  
次の `describe-instance-type-offerings` の例では、指定したアベイラビリティーゾーンで提供されるインスタンスタイプを一覧表示します。アベイラビリティーゾーンは、指定されたリージョンにある必要があります。  

```
aws ec2 describe-instance-type-offerings \
    --location-type availability-zone \
    --filters Name=location,Values=us-east-2a \
    --region us-east-2
```
**例 3: インスタンスタイプがサポートされているかどうかを確認するには**  
次の `describe-instance-type-offerings` コマンドは、指定されたリージョンで `c5.xlarge` インスタンスタイプがサポートされているかどうかを示します。  

```
aws ec2 describe-instance-type-offerings \
    --filters Name=instance-type,Values=c5.xlarge \
    --region us-east-2
```
次の `describe-instance-type-offerings` の例では、指定したリージョン内でサポートされている C5 インスタンスタイプをすべて一覧表示します。  

```
aws ec2 describe-instance-type-offerings \
    --filters Name=instance-type,Values=c5* \
    --query "InstanceTypeOfferings[].InstanceType" \
    --region us-east-2
```
出力:  

```
[
    "c5d.12xlarge",
    "c5d.9xlarge",
    "c5n.xlarge",
    "c5.xlarge",
    "c5d.metal",
    "c5n.metal",
    "c5.large",
    "c5d.2xlarge",
    "c5n.4xlarge",
    "c5.2xlarge",
    "c5n.large",
    "c5n.9xlarge",
    "c5d.large",
    "c5.18xlarge",
    "c5d.18xlarge",
    "c5.12xlarge",
    "c5n.18xlarge",
    "c5.metal",
    "c5d.4xlarge",
    "c5.24xlarge",
    "c5d.xlarge",
    "c5n.2xlarge",
    "c5d.24xlarge",
    "c5.9xlarge",
    "c5.4xlarge"
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceTypeOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-type-offerings.html)」を参照してください。

### `describe-instance-types`
<a name="ec2_DescribeInstanceTypes_cli_2_topic"></a>

次のコード例は、`describe-instance-types` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスタイプを説明するには**  
次の `describe-instance-types` の例では、指定されたインスタンスタイプの詳細を表示します。  

```
aws ec2 describe-instance-types \
    --instance-types t2.micro
```
出力:  

```
{
    "InstanceTypes": [
        {
            "InstanceType": "t2.micro",
            "CurrentGeneration": true,
            "FreeTierEligible": true,
            "SupportedUsageClasses": [
                "on-demand",
                "spot"
            ],
            "SupportedRootDeviceTypes": [
                "ebs"
            ],
            "BareMetal": false,
            "Hypervisor": "xen",
            "ProcessorInfo": {
                "SupportedArchitectures": [
                    "i386",
                    "x86_64"
                ],
                "SustainedClockSpeedInGhz": 2.5
            },
            "VCpuInfo": {
                "DefaultVCpus": 1,
                "DefaultCores": 1,
                "DefaultThreadsPerCore": 1,
                "ValidCores": [
                    1
                ],
                "ValidThreadsPerCore": [
                    1
                ]
            },
            "MemoryInfo": {
                "SizeInMiB": 1024
            },
            "InstanceStorageSupported": false,
            "EbsInfo": {
                "EbsOptimizedSupport": "unsupported",
                "EncryptionSupport": "supported"
            },
            "NetworkInfo": {
                "NetworkPerformance": "Low to Moderate",
                "MaximumNetworkInterfaces": 2,
                "Ipv4AddressesPerInterface": 2,
                "Ipv6AddressesPerInterface": 2,
                "Ipv6Supported": true,
                "EnaSupport": "unsupported"
            },
            "PlacementGroupInfo": {
                "SupportedStrategies": [
                    "partition",
                    "spread"
                ]
            },
            "HibernationSupported": false,
            "BurstablePerformanceSupported": true,
            "DedicatedHostsSupported": false,
            "AutoRecoverySupported": true
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)」を参照してください。  
**例 2: 使用可能なインスタンスタイプをフィルタリングするには**  
フィルターを指定して、特定の特性を持つインスタンスタイプに結果を絞り込めます。次の `describe-instance-types` の例では、休止状態をサポートするインスタンスタイプを一覧表示しています。  

```
aws ec2 describe-instance-types \
    --filters Name=hibernation-supported,Values=true --query 'InstanceTypes[*].InstanceType'
```
出力:  

```
[
    "m5.8xlarge",
    "r3.large",
    "c3.8xlarge",
    "r5.large",
    "m4.4xlarge",
    "c4.large",
    "m5.xlarge",
    "m4.xlarge",
    "c3.large",
    "c4.8xlarge",
    "c4.4xlarge",
    "c5.xlarge",
    "c5.12xlarge",
    "r5.4xlarge",
    "c5.4xlarge"
]
```
詳細については、「*Amazon Elastic Compute Cloud User Guide for Linux Instances*」の「[Instance Types](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeInstanceTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instance-types.html)」を参照してください。

### `describe-instances`
<a name="ec2_DescribeInstances_cli_2_topic"></a>

次のコード例は、`describe-instances` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスを説明するには**  
次の `describe-instances` の例では、指定したインスタンスを示しています。  

```
aws ec2 describe-instances \
    --instance-ids i-1234567890abcdef0
```
出力:  

```
{
    "Reservations": [
        {
            "Groups": [],
            "Instances": [
                {
                    "AmiLaunchIndex": 0,
                    "ImageId": "ami-0abcdef1234567890",
                    "InstanceId": "i-1234567890abcdef0",
                    "InstanceType": "t3.nano",
                    "KeyName": "my-key-pair",
                    "LaunchTime": "2022-11-15T10:48:59+00:00",
                    "Monitoring": {
                        "State": "disabled"
                    },
                    "Placement": {
                        "AvailabilityZone": "us-east-2a",
                        "GroupName": "",
                        "Tenancy": "default"
                    },
                    "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                    "PrivateIpAddress": "10-0-0-157",
                    "ProductCodes": [],
                    "PublicDnsName": "ec2-34-253-223-13.us-east-2.compute.amazonaws.com",
                    "PublicIpAddress": "34.253.223.13",
                    "State": {
                        "Code": 16,
                        "Name": "running"
                    },
                    "StateTransitionReason": "",
                    "SubnetId": "subnet-04a636d18e83cfacb",
                    "VpcId": "vpc-1234567890abcdef0",
                    "Architecture": "x86_64",
                    "BlockDeviceMappings": [
                        {
                            "DeviceName": "/dev/xvda",
                            "Ebs": {
                                "AttachTime": "2022-11-15T10:49:00+00:00",
                                "DeleteOnTermination": true,
                                "Status": "attached",
                                "VolumeId": "vol-02e6ccdca7de29cf2"
                            }
                        }
                    ],
                    "ClientToken": "1234abcd-1234-abcd-1234-d46a8903e9bc",
                    "EbsOptimized": true,
                    "EnaSupport": true,
                    "Hypervisor": "xen",
                    "IamInstanceProfile": {
                        "Arn": "arn:aws:iam::111111111111:instance-profile/AmazonSSMRoleForInstancesQuickSetup",
                        "Id": "111111111111111111111"
                    },
                    "NetworkInterfaces": [
                        {
                            "Association": {
                                "IpOwnerId": "amazon",
                                "PublicDnsName": "ec2-34-253-223-13.us-east-2.compute.amazonaws.com",
                                "PublicIp": "34.253.223.13"
                            },
                            "Attachment": {
                                "AttachTime": "2022-11-15T10:48:59+00:00",
                                "AttachmentId": "eni-attach-1234567890abcdefg",
                                "DeleteOnTermination": true,
                                "DeviceIndex": 0,
                                "Status": "attached",
                                "NetworkCardIndex": 0
                            },
                            "Description": "",
                            "Groups": [
                                {
                                    "GroupName": "launch-wizard-146",
                                    "GroupId": "sg-1234567890abcdefg"
                                }
                            ],
                            "Ipv6Addresses": [],
                            "MacAddress": "00:11:22:33:44:55",
                            "NetworkInterfaceId": "eni-1234567890abcdefg",
                            "OwnerId": "104024344472",
                            "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                            "PrivateIpAddress": "10-0-0-157",
                            "PrivateIpAddresses": [
                                {
                                    "Association": {
                                        "IpOwnerId": "amazon",
                                        "PublicDnsName": "ec2-34-253-223-13.us-east-2.compute.amazonaws.com",
                                        "PublicIp": "34.253.223.13"
                                    },
                                    "Primary": true,
                                    "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                                    "PrivateIpAddress": "10-0-0-157"
                                }
                            ],
                            "SourceDestCheck": true,
                            "Status": "in-use",
                            "SubnetId": "subnet-1234567890abcdefg",
                            "VpcId": "vpc-1234567890abcdefg",
                            "InterfaceType": "interface"
                        }
                    ],
                    "RootDeviceName": "/dev/xvda",
                    "RootDeviceType": "ebs",
                    "SecurityGroups": [
                        {
                            "GroupName": "launch-wizard-146",
                            "GroupId": "sg-1234567890abcdefg"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": "my-instance"
                        }
                    ],
                    "VirtualizationType": "hvm",
                    "CpuOptions": {
                        "CoreCount": 1,
                        "ThreadsPerCore": 2
                    },
                    "CapacityReservationSpecification": {
                        "CapacityReservationPreference": "open"
                    },
                    "HibernationOptions": {
                        "Configured": false
                    },
                    "MetadataOptions": {
                        "State": "applied",
                        "HttpTokens": "optional",
                        "HttpPutResponseHopLimit": 1,
                        "HttpEndpoint": "enabled",
                        "HttpProtocolIpv6": "disabled",
                        "InstanceMetadataTags": "enabled"
                    },
                    "EnclaveOptions": {
                        "Enabled": false
                    },
                    "PlatformDetails": "Linux/UNIX",
                    "UsageOperation": "RunInstances",
                    "UsageOperationUpdateTime": "2022-11-15T10:48:59+00:00",
                    "PrivateDnsNameOptions": {
                        "HostnameType": "ip-name",
                        "EnableResourceNameDnsARecord": true,
                        "EnableResourceNameDnsAAAARecord": false
                    },
                    "MaintenanceOptions": {
                        "AutoRecovery": "default"
                    }
                }
            ],
            "OwnerId": "111111111111",
            "ReservationId": "r-1234567890abcdefg"
        }
    ]
}
```
**例 2: 指定したタイプのインスタンスをフィルタリングするには**  
次の `describe-instances` の例では、フィルターを使用して、指定されたタイプのインスタンスに結果の範囲を限定しています。  

```
aws ec2 describe-instances \
    --filters Name=instance-type,Values=m5.large
```
出力例については、例 1 を参照してください。  
詳細については、「*Amazon EC2 ユーザーガイド*」の「[CLI を使用した一覧表示およびフィルタリング](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)」を参照してください。  
**例 3: 指定したタイプとアベイラビリティーゾーンでインスタンスをフィルタリングするには**  
次の `describe-instances` の例では、複数のフィルターを使用して、指定されたアベイラビリティーゾーンにある、指定されたタイプのインスタンスに結果を絞り込みます。  

```
aws ec2 describe-instances \
    --filters Name=instance-type,Values=t2.micro,t3.micro Name=availability-zone,Values=us-east-2c
```
出力例については、例 1 を参照してください。  
**例 4: JSON ファイルを使用して、指定したタイプとアベイラビリティーゾーンでインスタンスをフィルタリングするには**  
次の `describe-instances` の例では、JSON 入力ファイルを使用して、前の例と同じフィルタリングを実行します。フィルターが複雑になるほど、JSON ファイル内での指定が簡単になります。  

```
aws ec2 describe-instances \
    --filters file://filters.json
```
`filters.json` の内容:  

```
[
    {
        "Name": "instance-type",
        "Values": ["t2.micro", "t3.micro"]
    },
    {
        "Name": "availability-zone",
        "Values": ["us-east-2c"]
    }
]
```
出力例については、例 1 を参照してください。  
**例 5: 指定した Owner タグを持つインスタンスをフィルタリングするには**  
次の `describe-instances` の例では、タグフィルターを使用して、タグ値に関係なく、指定されたタグキー (Owner) のタグを持つインスタンスに結果を絞り込みます。  

```
aws ec2 describe-instances \
    --filters "Name=tag-key,Values=Owner"
```
出力例については、例 1 を参照してください。  
**例 6: 指定した my-team タグ値を持つインスタンスをフィルタリングするには**  
次の `describe-instances` の例では、タグフィルターを使用して、タグキーに関係なく、指定されたタグ値 (my-team) のタグを持つインスタンスに結果を絞り込みます。  

```
aws ec2 describe-instances \
    --filters "Name=tag-value,Values=my-team"
```
出力例については、例 1 を参照してください。  
**例 7: 指定した Owner タグと my-team 値を持つインスタンスをフィルタリングするには**  
次の `describe-instances` の例では、タグフィルターを使用して、指定したタグ (Owner=my-team) を持つインスタンスに結果を絞り込みます。  

```
aws ec2 describe-instances \
    --filters "Name=tag:Owner,Values=my-team"
```
出力例については、例 1 を参照してください。  
**例 8: すべてのインスタンスのインスタンス ID とサブネット ID のみを表示するには**  
次の `describe-instances` の例では、`--query` パラメータを使用して、すべてのインスタンスのインスタンス ID とサブネット ID のみを JSON 形式で表示します。  
Linux および macOS:  

```
aws ec2 describe-instances \
    --query 'Reservations[*].Instances[*].{Instance:InstanceId,Subnet:SubnetId}' \
    --output json
```
Windows:  

```
aws ec2 describe-instances ^
    --query "Reservations[*].Instances[*].{Instance:InstanceId,Subnet:SubnetId}" ^
    --output json
```
出力:  

```
[
    {
        "Instance": "i-057750d42936e468a",
        "Subnet": "subnet-069beee9b12030077"
    },
    {
        "Instance": "i-001efd250faaa6ffa",
        "Subnet": "subnet-0b715c6b7db68927a"
    },
    {
        "Instance": "i-027552a73f021f3bd",
        "Subnet": "subnet-0250c25a1f4e15235"
    }
    ...
]
```
**例 9: 指定したタイプのインスタンスをフィルタリングし、そのインスタンス ID のみを表示するには**  
次の `describe-instances` の例では、フィルターを使用して、指定されたタイプのインスタンスに結果を絞り込み、`--query` パラメータを使用してインスタンス ID のみを表示します。  

```
aws ec2 describe-instances \
    --filters "Name=instance-type,Values=t2.micro" \
    --query "Reservations[*].Instances[*].[InstanceId]" \
    --output text
```
出力:  

```
i-031c0dc19de2fb70c
i-00d8bff789a736b75
i-0b715c6b7db68927a
i-0626d4edd54f1286d
i-00b8ae04f9f99908e
i-0fc71c25d2374130c
```
**例 10: 指定したタイプのインスタンスをフィルタリングし、インスタンス ID、アベイラビリティーゾーン、指定したタグ値のみを表示するには**  
次の `describe-instances` の例では、`tag-key` という名前のタグを持つインスタンスのインスタンス ID、アベイラビリティーゾーン、および `Name` タグの値を表形式で表示します。  
Linux および macOS:  

```
aws ec2 describe-instances \
    --filters Name=tag-key,Values=Name \
    --query 'Reservations[*].Instances[*].{Instance:InstanceId,AZ:Placement.AvailabilityZone,Name:Tags[?Key==`Name`]|[0].Value}' \
    --output table
```
Windows:  

```
aws ec2 describe-instances ^
    --filters Name=tag-key,Values=Name ^
    --query "Reservations[*].Instances[*].{Instance:InstanceId,AZ:Placement.AvailabilityZone,Name:Tags[?Key=='Name']|[0].Value}" ^
    --output table
```
出力:  

```
-------------------------------------------------------------
|                     DescribeInstances                     |
+--------------+-----------------------+--------------------+
|      AZ      |       Instance        |        Name        |
+--------------+-----------------------+--------------------+
|  us-east-2b  |  i-057750d42936e468a  |  my-prod-server    |
|  us-east-2a  |  i-001efd250faaa6ffa  |  test-server-1     |
|  us-east-2a  |  i-027552a73f021f3bd  |  test-server-2     |
+--------------+-----------------------+--------------------+
```
**例 11: パーティションプレイスメントグループ内のインスタンスを説明するには**  
次の `describe-instances` の例では、指定したインスタンスを示しています。出力にはインスタンスのプレイスメント情報が含まれています。この情報にはインスタンスのプレイスメントグループ名とパーティション番号が含まれます。  

```
aws ec2 describe-instances \
    --instance-ids i-0123a456700123456 \
    --query "Reservations[*].Instances[*].Placement"
```
出力:  

```
[
    [
        {
            "AvailabilityZone": "us-east-1c",
            "GroupName": "HDFS-Group-A",
            "PartitionNumber": 3,
            "Tenancy": "default"
        }

    ]
]
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[プレイスメントグループのインスタンスの説明](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html#describe-instance-placement)」を参照してください。  
**例 12: 指定したプレイスメントグループとパーティション番号を持つインスタンスでフィルタリングするには**  
次の `describe-instances` の例では、指定したプレイスメントグループとパーティション番号のインスタンスのみに結果をフィルタリングします。  

```
aws ec2 describe-instances \
    --filters "Name=placement-group-name,Values=HDFS-Group-A" "Name=placement-partition-number,Values=7"
```
次の例では、出力の関連情報のみが表示されます。  

```
"Instances": [
    {
        "InstanceId": "i-0123a456700123456",
        "InstanceType": "r4.large",
        "Placement": {
            "AvailabilityZone": "us-east-1c",
            "GroupName": "HDFS-Group-A",
            "PartitionNumber": 7,
            "Tenancy": "default"
        }
    },
    {
        "InstanceId": "i-9876a543210987654",
        "InstanceType": "r4.large",
        "Placement": {
            "AvailabilityZone": "us-east-1c",
            "GroupName": "HDFS-Group-A",
            "PartitionNumber": 7,
            "Tenancy": "default"
        }
    ],
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[プレイスメントグループのインスタンスの説明](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html#describe-instance-placement)」を参照してください。  
**例 13: インスタンスメタデータのタグへのアクセスを許可するように設定されているインスタンスに絞り込むには**  
次の `describe-instances` の例では、インスタンスメタデータからインスタンスタグへのアクセスを許可するように設定されているインスタンスのみに結果をフィルタリングします。  

```
aws ec2 describe-instances \
    --filters "Name=metadata-options.instance-metadata-tags,Values=enabled" \
    --query "Reservations[*].Instances[*].InstanceId" \
    --output text
```
次のような出力が予想されます。  

```
i-1234567890abcdefg
i-abcdefg1234567890
i-11111111aaaaaaaaa
i-aaaaaaaa111111111
```
詳細については、「*Amazon EC2 ユーザーガイド*」で[インスタンスメタデータ内のインスタンスタグの使用方法](https://docs.aws.amazon.com/en_us/AWSEC2/latest/UserGuide/Using_Tags.html#view-access-to-tags-in-IMDS)を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-instances.html)」を参照してください。

### `describe-internet-gateways`
<a name="ec2_DescribeInternetGateways_cli_2_topic"></a>

次のコード例は、`describe-internet-gateways` を使用する方法を示しています。

**AWS CLI**  
**インターネットゲートウェイを記述するには**  
次の `describe-internet-gateways` の例では、指定したインターネットゲートウェイについて説明します。  

```
aws ec2 describe-internet-gateways \
    --internet-gateway-ids igw-0d0fb496b3EXAMPLE
```
出力:  

```
{
    "InternetGateways": [
        {
            "Attachments": [
                {
                    "State": "available",
                    "VpcId": "vpc-0a60eb65b4EXAMPLE"
                }
            ],
            "InternetGatewayId": "igw-0d0fb496b3EXAMPLE",
            "OwnerId": "123456789012",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-igw"
                }
            ]
        }
    ]
}
```
詳細については、*Amazon VPC ユーザーガイド*の「[インターネットゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInternetGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-internet-gateways.html)」を参照してください。

### `describe-ipam-pools`
<a name="ec2_DescribeIpamPools_cli_2_topic"></a>

次のコード例は、`describe-ipam-pools` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールの詳細を表示するには**  
次の `describe-ipam-pools` の例では、プールの詳細を表示します。  
(Linux):  

```
aws ec2 describe-ipam-pools \
    --filters Name=owner-id,Values=123456789012 Name=ipam-scope-id,Values=ipam-scope-02fc38cd4c48e7d38
```
(Windows):  

```
aws ec2 describe-ipam-pools ^
    --filters Name=owner-id,Values=123456789012 Name=ipam-scope-id,Values=ipam-scope-02fc38cd4c48e7d38
```
出力:  

```
{
    "IpamPools": [
        {
            "OwnerId": "123456789012",
            "IpamPoolId": "ipam-pool-02ec043a19bbe5d08",
            "IpamPoolArn": "arn:aws:ec2::123456789012:ipam-pool/ipam-pool-02ec043a19bbe5d08",
            "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-02fc38cd4c48e7d38",
            "IpamScopeType": "private",
            "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
            "IpamRegion": "us-east-1",
            "Locale": "None",
            "PoolDepth": 1,
            "State": "create-complete",
            "AutoImport": true,
            "AddressFamily": "ipv4",
            "AllocationMinNetmaskLength": 16,
            "AllocationMaxNetmaskLength": 26,
            "AllocationDefaultNetmaskLength": 24,
            "AllocationResourceTags": [
                {
                    "Key": "Environment",
                    "Value": "Preprod"
                }
            ],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Preprod pool"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIpamPools](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-ipam-pools.html)」を参照してください。

### `describe-ipam-resource-discoveries`
<a name="ec2_DescribeIpamResourceDiscoveries_cli_2_topic"></a>

次のコード例は、`describe-ipam-resource-discoveries` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソース検出の詳細を表示する**  
この例では、管理者が組織内のリソースの IP アドレスを管理およびモニタリングできるように、リソース検出を作成して別の AWS 組織の IPAM 管理者と共有したい委任 IPAM 管理者です。  
この例は、次の場合に便利です。  
リソース検出を作成しようとしましたが、上限の 1 に達したというエラーが表示されました。リソース検出を既に作成している可能性があることに気づき、アカウントで確認したいと考えます。IPAM で検出されていないリージョン内にリソースがあります。リソースに対して定義されている `--operating-regions` を表示し、そこにあるリソースを検出できるように、適切なリージョンを運用リージョンとして追加したことを確認します。  
次の の`describe-ipam-resource-discoveries`例では、 AWS アカウントのリソース検出の詳細を一覧表示します。 AWS リージョンごとに 1 つのリソース検出を持つことができます。  

```
aws ec2 describe-ipam-resource-discoveries \
    --region us-east-1
```
出力:  

```
{
    "IpamResourceDiscoveries": [
        {
            "OwnerId": "149977607591",
            "IpamResourceDiscoveryId": "ipam-res-disco-0f8bdee9067137c0d",
            "IpamResourceDiscoveryArn": "arn:aws:ec2::149977607591:ipam-resource-discovery/ipam-res-disco-0f8bdee9067137c0d",
            "IpamResourceDiscoveryRegion": "us-east-1",
            "OperatingRegions": [
                {
                    "RegionName": "us-east-1"
                }
            ],
            "IsDefault": false,
            "State": "create-complete",
            "Tags": []
    }
]
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Integrate IPAM with accounts outside of your organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org.html)」を参照してください。  
**例 2: リソース検出 ID のみを表示する**  
次の の`describe-ipam-resource-discoveries`例では、 AWS アカウントのリソース検出の ID を一覧表示します。 AWS リージョンごとに 1 つのリソース検出を持つことができます。  

```
aws ec2 describe-ipam-resource-discoveries \
    --query "IpamResourceDiscoveries[*].IpamResourceDiscoveryId" \
    --output text
```
出力:  

```
ipam-res-disco-0481e39b242860333
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Integrate IPAM with accounts outside of your organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIpamResourceDiscoveries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-ipam-resource-discoveries.html)」を参照してください。

### `describe-ipam-resource-discovery-associations`
<a name="ec2_DescribeIpamResourceDiscoveryAssociations_cli_2_topic"></a>

次のコード例は、`describe-ipam-resource-discovery-associations` を使用する方法を示しています。

**AWS CLI**  
**IPAM とのすべてのリソース検出の関連付けを表示するには**  
この例では、あなたは IPAM の委任された管理者として、他のアカウントを自身の IPAM と統合するためにリソース検出を自身の IPAM に関連付けています。IPAM がリソース検出の運用リージョン内にあるリソースを期待どおりに検出していないことに気付きました。リソース検出のステータスと状態をチェックして、それを作成したアカウントがまだアクティブであり、リソース検出がまだ共有されていることを確認します。  
`--region` は IPAM のホームリージョンである必要があります。  
次の の`describe-ipam-resource-discovery-associations`例では、 AWS アカウントのリソース検出の関連付けを一覧表示します。  

```
aws ec2 describe-ipam-resource-discovery-associations \
    --region us-east-1
```
出力:  

```
{
    "IpamResourceDiscoveryAssociations": [
        {
            "OwnerId": "320805250157",
            "IpamResourceDiscoveryAssociationId": "ipam-res-disco-assoc-05e6b45eca5bf5cf7",
            "IpamResourceDiscoveryAssociationArn": "arn:aws:ec2::320805250157:ipam-resource-discovery-association/ipam-res-disco-assoc-05e6b45eca5bf5cf7",
            "IpamResourceDiscoveryId": "ipam-res-disco-0f4ef577a9f37a162",
            "IpamId": "ipam-005f921c17ebd5107",
            "IpamArn": "arn:aws:ec2::320805250157:ipam/ipam-005f921c17ebd5107",
            "IpamRegion": "us-east-1",
            "IsDefault": true,
            "ResourceDiscoveryStatus": "active",
            "State": "associate-complete",
            "Tags": []
        },
        {
            "OwnerId": "149977607591",
            "IpamResourceDiscoveryAssociationId": "ipam-res-disco-assoc-0dfd21ae189ab5f62",
            "IpamResourceDiscoveryAssociationArn": "arn:aws:ec2::149977607591:ipam-resource-discovery-association/ipam-res-disco-assoc-0dfd21ae189ab5f62",
            "IpamResourceDiscoveryId": "ipam-res-disco-0365d2977fc1672fe",
            "IpamId": "ipam-005f921c17ebd5107",
            "IpamArn": "arn:aws:ec2::149977607591:ipam/ipam-005f921c17ebd5107",
            "IpamRegion": "us-east-1",
            "IsDefault": false,
            "ResourceDiscoveryStatus": "active",
            "State": "create-complete",
            "Tags": []
        }
    ]
}
```
この例では、このコマンドを実行した後、あなたはデフォルト以外のリソース検出が 1 つあることに気づきます (`"IsDefault": false ``) that is ``"ResourceDiscoveryStatus": "not-found"` と`"State": "create-complete"`。リソース検出の所有者のアカウントは解約されています。別のケースで、`"ResourceDiscoveryStatus": "not-found"` および `"State": "associate-complete"` であることに気付いた場合は、これは次のいずれかが発生したことを示します。  
リソース検出がリソース検出の所有者によって削除された。リソース検出の所有者がリソース検出の共有を解除した。  
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Integrate IPAM with accounts outside of your organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIpamResourceDiscoveryAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-ipam-resource-discovery-associations.html)」を参照してください。

### `describe-ipam-scopes`
<a name="ec2_DescribeIpamScopes_cli_2_topic"></a>

次のコード例は、`describe-ipam-scopes` を使用する方法を示しています。

**AWS CLI**  
**IPAM スコープの詳細を表示するには**  
次の `describe-ipam-scopes` の例では、スコープの詳細を表示します。  

```
aws ec2 describe-ipam-scopes \
    --filters Name=owner-id,Values=123456789012 Name=ipam-id,Values=ipam-08440e7a3acde3908
```
出力:  

```
{
    "IpamScopes": [
        {
            "OwnerId": "123456789012",
            "IpamScopeId": "ipam-scope-02fc38cd4c48e7d38",
            "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-02fc38cd4c48e7d38",
            "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
            "IpamRegion": "us-east-1",
            "IpamScopeType": "private",
            "IsDefault": true,
            "PoolCount": 2,
            "State": "create-complete",
            "Tags": []
        },
        {
            "OwnerId": "123456789012",
            "IpamScopeId": "ipam-scope-0b9eed026396dbc16",
            "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-0b9eed026396dbc16",
            "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
            "IpamRegion": "us-east-1",
            "IpamScopeType": "public",
            "IsDefault": true,
            "PoolCount": 0,
            "State": "create-complete",
            "Tags": []
        },
        {
            "OwnerId": "123456789012",
            "IpamScopeId": "ipam-scope-0f1aff29486355c22",
            "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-0f1aff29486355c22",
            "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
            "IpamRegion": "us-east-1",
            "IpamScopeType": "private",
            "IsDefault": false,
            "Description": "Example description",
            "PoolCount": 0,
            "State": "create-complete",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Example name value"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DescribeIpamScopes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-ipam-scopes.html)」を参照してください。

### `describe-ipams`
<a name="ec2_DescribeIpams_cli_2_topic"></a>

次のコード例は、`describe-ipams` を使用する方法を示しています。

**AWS CLI**  
**IPAM の詳細を表示するには**  
次の `describe-ipams` の例では、IPAM の詳細を表示します。  

```
aws ec2 describe-ipams \
    --filters Name=owner-id,Values=123456789012
```
出力:  

```
{
    "Ipams": [
        {
            "OwnerId": "123456789012",
            "IpamId": "ipam-08440e7a3acde3908",
            "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
            "IpamRegion": "us-east-1",
            "PublicDefaultScopeId": "ipam-scope-0b9eed026396dbc16",
            "PrivateDefaultScopeId": "ipam-scope-02fc38cd4c48e7d38",
            "ScopeCount": 3,
            "OperatingRegions": [
                {
                    "RegionName": "us-east-1"
                },
                {
                    "RegionName": "us-east-2"
                },
                {
                    "RegionName": "us-west-1"
                }
            ],
            "State": "create-complete",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "ExampleIPAM"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIpams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-ipams.html)」を参照してください。

### `describe-ipv6-pools`
<a name="ec2_DescribeIpv6Pools_cli_2_topic"></a>

次のコード例は、`describe-ipv6-pools` を使用する方法を示しています。

**AWS CLI**  
**IPv6 アドレスプールを記述するには**  
次の `describe-ipv6-pools` の例では、すべての IPv6 アドレスプールの詳細を表示します。  

```
aws ec2 describe-ipv6-pools
```
出力:  

```
{
    "Ipv6Pools": [
        {
            "PoolId": "ipv6pool-ec2-012345abc12345abc",
            "PoolCidrBlocks": [
                {
                    "Cidr": "2001:db8:123::/48"
                }
            ],
            "Tags": [
                {
                    "Key": "pool-1",
                    "Value": "public"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIpv6Pools](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-ipv6-pools.html)」を参照してください。

### `describe-key-pairs`
<a name="ec2_DescribeKeyPairs_cli_2_topic"></a>

次のコード例は、`describe-key-pairs` を使用する方法を示しています。

**AWS CLI**  
**キーペアを表示するには**  
次の `describe-key-pairs` の例では、指定されたキーペアの情報が表示されます。  

```
aws ec2 describe-key-pairs \
    --key-names my-key-pair
```
出力:  

```
{
    "KeyPairs": [
        {
            "KeyPairId": "key-0b94643da6EXAMPLE",
            "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f",
            "KeyName": "my-key-pair",
            "KeyType": "rsa",
            "Tags": [],
            "CreateTime": "2022-05-27T21:51:16.000Z"
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[パブリックキーの説明](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/describe-keys.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeKeyPairs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-key-pairs.html)」を参照してください。

### `describe-launch-template-versions`
<a name="ec2_DescribeLaunchTemplateVersions_cli_2_topic"></a>

次のコード例は、`describe-launch-template-versions` を使用する方法を示しています。

**AWS CLI**  
**起動テンプレートのバージョンを記述するには**  
この例では、指定された起動テンプレートのバージョンを記述します。  
コマンド:  

```
aws ec2 describe-launch-template-versions --launch-template-id lt-068f72b72934aff71
```
出力:  

```
{
  "LaunchTemplateVersions": [
      {
          "LaunchTemplateId": "lt-068f72b72934aff71",
          "LaunchTemplateName": "Webservers",
          "VersionNumber": 3,
          "CreatedBy": "arn:aws:iam::123456789102:root",
          "LaunchTemplateData": {
              "KeyName": "kp-us-east",
              "ImageId": "ami-6057e21a",
              "InstanceType": "t2.small",
              "NetworkInterfaces": [
                  {
                      "SubnetId": "subnet-7b16de0c",
                      "DeviceIndex": 0,
                      "Groups": [
                          "sg-7c227019"
                      ]
                  }
              ]
          },
          "DefaultVersion": false,
          "CreateTime": "2017-11-20T13:19:54.000Z"
      },
      {
          "LaunchTemplateId": "lt-068f72b72934aff71",
          "LaunchTemplateName": "Webservers",
          "VersionNumber": 2,
          "CreatedBy": "arn:aws:iam::123456789102:root",
          "LaunchTemplateData": {
              "KeyName": "kp-us-east",
              "ImageId": "ami-6057e21a",
              "InstanceType": "t2.medium",
              "NetworkInterfaces": [
                  {
                      "SubnetId": "subnet-1a2b3c4d",
                      "DeviceIndex": 0,
                      "Groups": [
                          "sg-7c227019"
                      ]
                  }
              ]
          },
          "DefaultVersion": false,
          "CreateTime": "2017-11-20T13:12:32.000Z"
      },
      {
          "LaunchTemplateId": "lt-068f72b72934aff71",
          "LaunchTemplateName": "Webservers",
          "VersionNumber": 1,
          "CreatedBy": "arn:aws:iam::123456789102:root",
          "LaunchTemplateData": {
              "UserData": "",
              "KeyName": "kp-us-east",
              "ImageId": "ami-aabbcc11",
              "InstanceType": "t2.medium",
              "NetworkInterfaces": [
                  {
                      "SubnetId": "subnet-7b16de0c",
                      "DeviceIndex": 0,
                      "DeleteOnTermination": false,
                      "Groups": [
                          "sg-7c227019"
                      ],
                      "AssociatePublicIpAddress": true
                  }
              ]
          },
          "DefaultVersion": true,
          "CreateTime": "2017-11-20T12:52:33.000Z"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLaunchTemplateVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-template-versions.html)」を参照してください。

### `describe-launch-templates`
<a name="ec2_DescribeLaunchTemplates_cli_2_topic"></a>

次のコード例は、`describe-launch-templates` を使用する方法を示しています。

**AWS CLI**  
**起動テンプレートを記述するには**  
この例では、起動テンプレートを記述します。  
コマンド:  

```
aws ec2 describe-launch-templates
```
出力:  

```
{
  "LaunchTemplates": [
      {
          "LatestVersionNumber": 2,
          "LaunchTemplateId": "lt-0e06d290751193123",
          "LaunchTemplateName": "TemplateForWebServer",
          "DefaultVersionNumber": 2,
          "CreatedBy": "arn:aws:iam::123456789012:root",
          "CreateTime": "2017-11-27T09:30:23.000Z"
      },
      {
          "LatestVersionNumber": 6,
          "LaunchTemplateId": "lt-0c45b5e061ec98456",
          "LaunchTemplateName": "DBServersTemplate",
          "DefaultVersionNumber": 1,
          "CreatedBy": "arn:aws:iam::123456789012:root",
          "CreateTime": "2017-11-20T09:25:22.000Z"
      },
      {
          "LatestVersionNumber": 1,
          "LaunchTemplateId": "lt-0d47d774e8e52dabc",
          "LaunchTemplateName": "MyLaunchTemplate2",
          "DefaultVersionNumber": 1,
          "CreatedBy": "arn:aws:iam::123456789012:root",
          "CreateTime": "2017-11-02T12:06:21.000Z"
      },
      {
          "LatestVersionNumber": 3,
          "LaunchTemplateId": "lt-01e5f948eb4f589d6",
          "LaunchTemplateName": "testingtemplate2",
          "DefaultVersionNumber": 1,
          "CreatedBy": "arn:aws:sts::123456789012:assumed-role/AdminRole/i-03ee35176e2e5aabc",
          "CreateTime": "2017-12-01T08:19:48.000Z"
      },
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLaunchTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-launch-templates.html)」を参照してください。

### `describe-local-gateway-route-table-virtual-interface-group-associations`
<a name="ec2_DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations_cli_2_topic"></a>

次のコード例は、`describe-local-gateway-route-table-virtual-interface-group-associations` を使用する方法を示しています。

**AWS CLI**  
**仮想インターフェイスグループとローカルゲートウェイのルートテーブル間の関連付けを記述するには**  
次の`describe-local-gateway-route-table-virtual-interface-group-associations`例では、 AWS アカウントの仮想インターフェイスグループとローカルゲートウェイルートテーブル間の関連付けについて説明します。  

```
aws ec2 describe-local-gateway-route-table-virtual-interface-group-associations
```
出力:  

```
{
    "LocalGatewayRouteTableVirtualInterfaceGroupAssociations": [
        {
            "LocalGatewayRouteTableVirtualInterfaceGroupAssociationId": "lgw-vif-grp-assoc-07145b276bEXAMPLE",
            "LocalGatewayVirtualInterfaceGroupId": "lgw-vif-grp-07145b276bEXAMPLE",
            "LocalGatewayId": "lgw-0ab1c23d4eEXAMPLE",
            "LocalGatewayRouteTableId": "lgw-rtb-059615ef7dEXAMPLE",
            "LocalGatewayRouteTableArn": "arn:aws:ec2:us-west-2:123456789012:local-gateway-route-table/lgw-rtb-059615ef7dEXAMPLE",
            "OwnerId": "123456789012",
            "State": "associated",
            "Tags": []
        }
    ]
}
```
詳細については、「*AWS Outposts ユーザーガイド*」の「[Working with local gateways](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-local-gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLocalGatewayRouteTableVirtualInterfaceGroupAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-local-gateway-route-table-virtual-interface-group-associations.html)」を参照してください。

### `describe-local-gateway-route-table-vpc-associations`
<a name="ec2_DescribeLocalGatewayRouteTableVpcAssociations_cli_2_topic"></a>

次のコード例は、`describe-local-gateway-route-table-vpc-associations` を使用する方法を示しています。

**AWS CLI**  
**VPC とローカルゲートウェイのルートテーブル間の関連付けを記述するには**  
次の `describe-local-gateway-route-table-vpc-associations` の例では、VPC とローカルゲートウェイのルートテーブル間の指定した関連付けの情報を表示します。  

```
aws ec2 describe-local-gateway-route-table-vpc-associations \
    --local-gateway-route-table-vpc-association-ids lgw-vpc-assoc-0e0f27af15EXAMPLE
```
出力:  

```
{
    "LocalGatewayRouteTableVpcAssociation": {
        "LocalGatewayRouteTableVpcAssociationId": "lgw-vpc-assoc-0e0f27af1EXAMPLE",
        "LocalGatewayRouteTableId": "lgw-rtb-059615ef7dEXAMPLE",
        "LocalGatewayId": "lgw-09b493aa7cEXAMPLE",
        "VpcId": "vpc-0efe9bde08EXAMPLE",
        "State": "associated"
    }
}
```
詳細については、「* Outposts ユーザーガイド*」の「[ローカルゲートウェイルートテーブル](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLocalGatewayRouteTableVpcAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-local-gateway-route-table-vpc-associations.html)」を参照してください。

### `describe-local-gateway-route-tables`
<a name="ec2_DescribeLocalGatewayRouteTables_cli_2_topic"></a>

次のコード例は、`describe-local-gateway-route-tables` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイのルートテーブルを記述するには**  
次の `describe-local-gateway-route-tables` の例では、ローカルゲートウェイのルートテーブルの詳細を表示します。  

```
aws ec2 describe-local-gateway-route-tables
```
出力:  

```
{
    "LocalGatewayRouteTables": [
        {
            "LocalGatewayRouteTableId": "lgw-rtb-059615ef7deEXAMPLE",
            "LocalGatewayId": "lgw-09b493aa7cEXAMPLE",
            "OutpostArn": "arn:aws:outposts:us-west-2:111122223333:outpost/op-0dc11b66edEXAMPLE",
            "State": "available"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLocalGatewayRouteTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-local-gateway-route-tables.html)」を参照してください。

### `describe-local-gateway-virtual-interface-groups`
<a name="ec2_DescribeLocalGatewayVirtualInterfaceGroups_cli_2_topic"></a>

次のコード例は、`describe-local-gateway-virtual-interface-groups` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイ仮想インターフェイスグループを記述するには**  
次の`describe-local-gateway-virtual-interface-groups`例では、 AWS アカウントのローカルゲートウェイ仮想インターフェイスグループについて説明します。  

```
aws ec2 describe-local-gateway-virtual-interface-groups
```
出力:  

```
{
    "LocalGatewayVirtualInterfaceGroups": [
        {
            "LocalGatewayVirtualInterfaceGroupId": "lgw-vif-grp-07145b276bEXAMPLE",
            "LocalGatewayVirtualInterfaceIds": [
                "lgw-vif-01a23bc4d5EXAMPLE",
                "lgw-vif-543ab21012EXAMPLE"
            ],
            "LocalGatewayId": "lgw-0ab1c23d4eEXAMPLE",
            "OwnerId": "123456789012",
            "Tags": []
        }
    ]
}
```
詳細については、「*AWS Outposts ユーザーガイド*」の「[Working with local gateways](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-local-gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLocalGatewayVirtualInterfaceGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-local-gateway-virtual-interface-groups.html)」を参照してください。

### `describe-local-gateway-virtual-interfaces`
<a name="ec2_DescribeLocalGatewayVirtualInterfaces_cli_2_topic"></a>

次のコード例は、`describe-local-gateway-virtual-interfaces` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイ仮想インターフェイスを記述するには**  
次の`describe-local-gateway-virtual-interfaces`例では、 AWS アカウントのローカルゲートウェイ仮想インターフェイスについて説明します。  

```
aws ec2 describe-local-gateway-virtual-interfaces
```
出力:  

```
{
    "LocalGatewayVirtualInterfaces": [
        {
            "LocalGatewayVirtualInterfaceId": "lgw-vif-01a23bc4d5EXAMPLE",
            "LocalGatewayId": "lgw-0ab1c23d4eEXAMPLE",
            "Vlan": 2410,
            "LocalAddress": "0.0.0.0/0",
            "PeerAddress": "0.0.0.0/0",
            "LocalBgpAsn": 65010,
            "PeerBgpAsn": 65000,
            "OwnerId": "123456789012",
            "Tags": []
        },
        {
            "LocalGatewayVirtualInterfaceId": "lgw-vif-543ab21012EXAMPLE",
            "LocalGatewayId": "lgw-0ab1c23d4eEXAMPLE",
            "Vlan": 2410,
            "LocalAddress": "0.0.0.0/0",
            "PeerAddress": "0.0.0.0/0",
            "LocalBgpAsn": 65010,
            "PeerBgpAsn": 65000,
            "OwnerId": "123456789012",
            "Tags": []
        }
    ]
}
```
詳細については、「*AWS Outposts ユーザーガイド*」の「[Working with local gateways](https://docs.aws.amazon.com/outposts/latest/userguide/outposts-local-gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLocalGatewayVirtualInterfaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-local-gateway-virtual-interfaces.html)」を参照してください。

### `describe-local-gateways`
<a name="ec2_DescribeLocalGateways_cli_2_topic"></a>

次のコード例は、`describe-local-gateways` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイを記述するには**  
次の `describe-local-gateways` の例では、使用可能なローカルゲートウェイの詳細を表示します。  

```
aws ec2 describe-local-gateways
```
出力:  

```
{
    "LocalGateways": [
        {
            "LocalGatewayId": "lgw-09b493aa7cEXAMPLE",
            "OutpostArn": "arn:aws:outposts:us-west-2:123456789012:outpost/op-0dc11b66ed59f995a",
            "OwnerId": "123456789012",
            "State": "available"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLocalGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-local-gateways.html)」を参照してください。

### `describe-locked-snapshots`
<a name="ec2_DescribeLockedSnapshots_cli_2_topic"></a>

次のコード例は、`describe-locked-snapshots` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのロックのステータスを記述するには**  
次の `describe-locked-snapshots` の例では、指定したスナップショットのロックのステータスについて説明します。  

```
aws ec2 describe-locked-snapshots \
    --snapshot-ids snap-0b5e733b4a8df6e0d
```
出力:  

```
{
    "Snapshots": [
        {
            "OwnerId": "123456789012",
            "SnapshotId": "snap-0b5e733b4a8df6e0d",
            "LockState": "governance",
            "LockDuration": 365,
            "LockCreatedOn": "2024-05-05T00:56:06.208000+00:00",
            "LockDurationStartTime": "2024-05-05T00:56:06.208000+00:00",
            "LockExpiresOn": "2025-05-05T00:56:06.208000+00:00"
        }
    ]
}
```
詳細については、「*Amazon EBS ユーザーガイド*」の「[Snapshot lock](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-snapshot-lock.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLockedSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-locked-snapshots.html)」を参照してください。

### `describe-managed-prefix-lists`
<a name="ec2_DescribeManagedPrefixLists_cli_2_topic"></a>

次のコード例は、`describe-managed-prefix-lists` を使用する方法を示しています。

**AWS CLI**  
**マネージドプレフィックスリストを記述するには**  
次の`describe-managed-prefix-lists`例では、 AWS アカウント が所有するプレフィックスリストについて説明します`123456789012`。  

```
aws ec2 describe-managed-prefix-lists \
    --filters Name=owner-id,Values=123456789012
```
出力:  

```
{
    "PrefixLists": [
        {
            "PrefixListId": "pl-11223344556677aab",
            "AddressFamily": "IPv6",
            "State": "create-complete",
            "PrefixListArn": "arn:aws:ec2:us-west-2:123456789012:prefix-list/pl-11223344556677aab",
            "PrefixListName": "vpc-ipv6-cidrs",
            "MaxEntries": 25,
            "Version": 1,
            "Tags": [],
            "OwnerId": "123456789012"
        },
        {
            "PrefixListId": "pl-0123456abcabcabc1",
            "AddressFamily": "IPv4",
            "State": "active",
            "PrefixListArn": "arn:aws:ec2:us-west-2:123456789012:prefix-list/pl-0123456abcabcabc1",
            "PrefixListName": "vpc-cidrs",
            "MaxEntries": 10,
            "Version": 1,
            "Tags": [],
            "OwnerId": "123456789012"
      }
  ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Managed prefix lists](https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeManagedPrefixLists](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-managed-prefix-lists.html)」を参照してください。

### `describe-moving-addresses`
<a name="ec2_DescribeMovingAddresses_cli_2_topic"></a>

次のコード例は、`describe-moving-addresses` を使用する方法を示しています。

**AWS CLI**  
**移動アドレスを記述するには**  
この例では、移動するすべての Elastic IP アドレスを記述します。  
コマンド:  

```
aws ec2 describe-moving-addresses
```
出力:  

```
{
  "MovingAddressStatuses": [
    {
      "PublicIp": "198.51.100.0",
      "MoveStatus": "MovingToVpc"
    }
  ]
}
```
この例では、EC2-VPC プラットフォームに移動するすべてのアドレスを記述します。  
コマンド:  

```
aws ec2 describe-moving-addresses --filters Name=moving-status,Values=MovingToVpc
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMovingAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-moving-addresses.html)」を参照してください。

### `describe-nat-gateways`
<a name="ec2_DescribeNatGateways_cli_2_topic"></a>

次のコード例は、`describe-nat-gateways` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリック NAT ゲートウェイを記述するには**  
次の `describe-nat-gateways` の例では、指定したパブリック NAT ゲートウェイについて説明します。  

```
aws ec2 describe-nat-gateways \
    --nat-gateway-id nat-01234567890abcdef
```
出力:  

```
{
    "NatGateways": [
        {
            "CreateTime": "2023-08-25T01:56:51.000Z",
            "NatGatewayAddresses": [
                {
                    "AllocationId": "eipalloc-0790180cd2EXAMPLE",
                    "NetworkInterfaceId": "eni-09cc4b2558794f7f9",
                    "PrivateIp": "10.0.0.211",
                    "PublicIp": "54.85.121.213",
                    "AssociationId": "eipassoc-04d295cc9b8815b24",
                    "IsPrimary": true,
                    "Status": "succeeded"
                },
                {
                    "AllocationId": "eipalloc-0be6ecac95EXAMPLE",
                    "NetworkInterfaceId": "eni-09cc4b2558794f7f9",
                    "PrivateIp": "10.0.0.74",
                    "PublicIp": "3.211.231.218",
                    "AssociationId": "eipassoc-0f96bdca17EXAMPLE",
                    "IsPrimary": false,
                    "Status": "succeeded"
                }
            ],
            "NatGatewayId": "nat-01234567890abcdef",
            "State": "available",
            "SubnetId": "subnet-655eab5f08EXAMPLE",
            "VpcId": "vpc-098eb5ef58EXAMPLE",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "public-nat"
                }
            ],
            "ConnectivityType": "public"
        }
    ]
}
```
**例 2: プライベート NAT ゲートウェイを記述するには**  
次の `describe-nat-gateways` の例では、指定したプライベート NAT ゲートウェイについて説明します。  

```
aws ec2 describe-nat-gateways \
    --nat-gateway-id nat-1234567890abcdef0
```
出力:  

```
{
    "NatGateways": [
        {
            "CreateTime": "2023-08-25T00:50:05.000Z",
            "NatGatewayAddresses": [
                {
                    "NetworkInterfaceId": "eni-0065a61b324d1897a",
                    "PrivateIp": "10.0.20.240",
                    "IsPrimary": true,
                    "Status": "succeeded"
                },
                {
                    "NetworkInterfaceId": "eni-0065a61b324d1897a",
                    "PrivateIp": "10.0.20.33",
                    "IsPrimary": false,
                    "Status": "succeeded"
                },
                {
                    "NetworkInterfaceId": "eni-0065a61b324d1897a",
                    "PrivateIp": "10.0.20.197",
                    "IsPrimary": false,
                    "Status": "succeeded"
                }
            ],
            "NatGatewayId": "nat-1234567890abcdef0",
            "State": "available",
            "SubnetId": "subnet-08fc749671EXAMPLE",
            "VpcId": "vpc-098eb5ef58EXAMPLE",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "private-nat"
                }
            ],
            "ConnectivityType": "private"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[NAT ゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNatGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-nat-gateways.html)」を参照してください。

### `describe-network-acls`
<a name="ec2_DescribeNetworkAcls_cli_2_topic"></a>

次のコード例は、`describe-network-acls` を使用する方法を示しています。

**AWS CLI**  
**ネットワーク ACL を記述するには**  
次の `describe-network-acls` の例では、ネットワーク ACL の詳細を取得します。  

```
aws ec2 describe-network-acls
```
出力:  

```
{
    "NetworkAcls": [
        {
            "Associations": [
                {
                    "NetworkAclAssociationId": "aclassoc-0c1679dc41EXAMPLE",
                    "NetworkAclId": "acl-0ea1f54ca7EXAMPLE",
                    "SubnetId": "subnet-0931fc2fa5EXAMPLE"
                }
            ],
            "Entries": [
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                }
            ],
            "IsDefault": true,
            "NetworkAclId": "acl-0ea1f54ca7EXAMPLE",
            "Tags": [],
            "VpcId": "vpc-06e4ab6c6cEXAMPLE",
            "OwnerId": "111122223333"
        },
        {
            "Associations": [],
            "Entries": [
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "Egress": true,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 101
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": true,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                },
                {
                    "Egress": true,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32768
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 100
                },
                {
                    "Egress": false,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "allow",
                    "RuleNumber": 101
                },
                {
                    "CidrBlock": "0.0.0.0/0",
                    "Egress": false,
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32767
                },
                {
                    "Egress": false,
                    "Ipv6CidrBlock": "::/0",
                    "Protocol": "-1",
                    "RuleAction": "deny",
                    "RuleNumber": 32768
                }
            ],
            "IsDefault": true,
            "NetworkAclId": "acl-0e2a78e4e2EXAMPLE",
            "Tags": [],
            "VpcId": "vpc-03914afb3eEXAMPLE",
            "OwnerId": "111122223333"
        }
    ]
}
```
詳細については、「*AWS VPC ユーザーガイド*」の「[Network ACLs](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkAcls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-acls.html)」を参照してください。

### `describe-network-insights-access-scope-analyses`
<a name="ec2_DescribeNetworkInsightsAccessScopeAnalyses_cli_2_topic"></a>

次のコード例は、`describe-network-insights-access-scope-analyses` を使用する方法を示しています。

**AWS CLI**  
**Network Insights アクセススコープ分析を記述するには**  
次の の`describe-network-insights-access-scope-analyses`例では、 AWS アカウントのアクセススコープ分析について説明します。  

```
aws ec2 describe-network-insights-access-scope-analyses \
    --region us-east-1
```
出力:  

```
{
    "NetworkInsightsAccessScopeAnalyses": [
        {
            "NetworkInsightsAccessScopeAnalysisId": "nisa-123456789111",
            "NetworkInsightsAccessScopeAnalysisArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-access-scope-analysis/nisa-123456789111",
            "NetworkInsightsAccessScopeId": "nis-123456789222",
            "Status": "succeeded",
            "StartDate": "2022-01-25T19:45:36.842000+00:00",
            "FindingsFound": "true",
            "Tags": []
        }
    ]
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli-naa.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkInsightsAccessScopeAnalyses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-insights-access-scope-analyses.html)」を参照してください。

### `describe-network-insights-access-scopes`
<a name="ec2_DescribeNetworkInsightsAccessScopes_cli_2_topic"></a>

次のコード例は、`describe-network-insights-access-scopes` を使用する方法を示しています。

**AWS CLI**  
**Network Insights アクセススコープを記述するには**  
次の`describe-network-insights-access-scopes`例では、 AWS アカウントのアクセススコープ分析について説明します。  

```
aws ec2 describe-network-insights-access-scopes \
    --region us-east-1
```
出力:  

```
{
    "NetworkInsightsAccessScopes": [
        {
            "NetworkInsightsAccessScopeId": "nis-123456789111",
            "NetworkInsightsAccessScopeArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-access-scope/nis-123456789111",
            "CreatedDate": "2021-11-29T21:12:41.416000+00:00",
            "UpdatedDate": "2021-11-29T21:12:41.416000+00:00",
            "Tags": []
        }
    ]
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli-naa.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkInsightsAccessScopes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-insights-access-scopes.html)」を参照してください。

### `describe-network-insights-analyses`
<a name="ec2_DescribeNetworkInsightsAnalyses_cli_2_topic"></a>

次のコード例は、`describe-network-insights-analyses` を使用する方法を示しています。

**AWS CLI**  
**パス分析の結果を表示するには**  
次の `describe-network-insights-analyses` の例では、指定した分析について説明します。この例では、送信元はインターネットゲートウェイ、送信先は EC2 インスタンス、プロトコルは TCP です。分析は成功し (`Status` は `succeeded`)、パスに到達できません (`NetworkPathFound` は `false`)。説明コード `ENI_SG_RULES_MISMATCH` は、インスタンスのセキュリティグループに、送信先ポートでトラフィックを許可するルールが含まれていないことを示します。  

```
aws ec2 describe-network-insights-analyses \
    --network-insights-analysis-ids nia-02207aa13eb480c7a
```
出力:  

```
{
    "NetworkInsightsAnalyses": [
        {
            "NetworkInsightsAnalysisId": "nia-02207aa13eb480c7a",
            "NetworkInsightsAnalysisArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-analysis/nia-02207aa13eb480c7a",
            "NetworkInsightsPathId": "nip-0b26f224f1d131fa8",
            "StartDate": "2021-01-20T22:58:37.495Z",
            "Status": "succeeded",
            "NetworkPathFound": false,
            "Explanations": [
                {
                    "Direction": "ingress",
                    "ExplanationCode": "ENI_SG_RULES_MISMATCH",
                    "NetworkInterface": {
                        "Id": "eni-0a25edef15a6cc08c",
                        "Arn": "arn:aws:ec2:us-east-1:123456789012:network-interface/eni-0a25edef15a6cc08c"
                    },
                    "SecurityGroups": [
                        {
                            "Id": "sg-02f0d35a850ba727f",
                            "Arn": "arn:aws:ec2:us-east-1:123456789012:security-group/sg-02f0d35a850ba727f"
                        }
                    ],
                    "Subnet": {
                        "Id": "subnet-004ff41eccb4d1194",
                        "Arn": "arn:aws:ec2:us-east-1:123456789012:subnet/subnet-004ff41eccb4d1194"
                    },
                    "Vpc": {
                        "Id": "vpc-f1663d98ad28331c7",
                        "Arn": "arn:aws:ec2:us-east-1:123456789012:vpc/vpc-f1663d98ad28331c7"
                    }
                }
            ],
            "Tags": []
        }
    ]
}
```
詳細については、*「Reachability Analyzer* [Guide」の「Getting started using the AWS CLI](https://docs.aws.amazon.com/vpc/latest/reachability/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkInsightsAnalyses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-insights-analyses.html)」を参照してください。

### `describe-network-insights-paths`
<a name="ec2_DescribeNetworkInsightsPaths_cli_2_topic"></a>

次のコード例は、`describe-network-insights-paths` を使用する方法を示しています。

**AWS CLI**  
**パスを記述するには**  
次の `describe-network-insights-paths` の例では、指定したパスについて説明します。  

```
aws ec2 describe-network-insights-paths \
    --network-insights-path-ids nip-0b26f224f1d131fa8
```
出力:  

```
{
    "NetworkInsightsPaths": [
        {
            "NetworkInsightsPathId": "nip-0b26f224f1d131fa8",
            "NetworkInsightsPathArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-path/nip-0b26f224f1d131fa8",
            "CreatedDate": "2021-01-20T22:43:46.933Z",
            "Source": "igw-0797cccdc9d73b0e5",
            "Destination": "i-0495d385ad28331c7",
            "Protocol": "tcp"
        }
    ]
}
```
詳細については、*「Reachability Analyzer* [Guide」の「Getting started using the AWS CLI](https://docs.aws.amazon.com/vpc/latest/reachability/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkInsightsPaths](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-insights-paths.html)」を参照してください。

### `describe-network-interface-attribute`
<a name="ec2_DescribeNetworkInterfaceAttribute_cli_2_topic"></a>

次のコード例は、`describe-network-interface-attribute` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイスのアタッチメント属性を記述するには**  
このコマンド例では、指定されたネットワークインターフェイスの `attachment` 属性を記述します。  
コマンド:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute attachment
```
出力:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "Attachment": {
      "Status": "attached",
      "DeviceIndex": 0,
      "AttachTime": "2015-05-21T20:02:20.000Z",
      "InstanceId": "i-1234567890abcdef0",
      "DeleteOnTermination": true,
      "AttachmentId": "eni-attach-43348162",
      "InstanceOwnerId": "123456789012"
  }
}
```
**ネットワークインターフェイスの説明属性を記述するには**  
このコマンド例では、指定されたネットワークインターフェイスの `description` 属性を記述します。  
コマンド:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute description
```
出力:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "Description": {
      "Value": "My description"
  }
}
```
**ネットワークインターフェイスの groupSet 属性を記述するには**  
このコマンド例では、指定されたネットワークインターフェイスの `groupSet` 属性を記述します。  
コマンド:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute groupSet
```
出力:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "Groups": [
      {
          "GroupName": "my-security-group",
          "GroupId": "sg-903004f8"
      }
  ]
}
```
**ネットワークインターフェイスの sourceDestCheck 属性を記述するには**  
このコマンド例では、指定されたネットワークインターフェイスの `sourceDestCheck` 属性を記述します。  
コマンド:  

```
aws ec2 describe-network-interface-attribute --network-interface-id eni-686ea200 --attribute sourceDestCheck
```
出力:  

```
{
  "NetworkInterfaceId": "eni-686ea200",
  "SourceDestCheck": {
      "Value": true
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkInterfaceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-interface-attribute.html)」を参照してください。

### `describe-network-interface-permissions`
<a name="ec2_DescribeNetworkInterfacePermissions_cli_2_topic"></a>

次のコード例は、`describe-network-interface-permissions` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイス権限を記述するには**  
この例では、すべてのネットワークインターフェイスのアクセス許可を記述します。  
コマンド:  

```
aws ec2 describe-network-interface-permissions
```
出力:  

```
{
  "NetworkInterfacePermissions": [
      {
          "PermissionState": {
              "State": "GRANTED"
          },
          "NetworkInterfacePermissionId": "eni-perm-06fd19020ede149ea",
          "NetworkInterfaceId": "eni-b909511a",
          "Permission": "INSTANCE-ATTACH",
          "AwsAccountId": "123456789012"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkInterfacePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-interface-permissions.html)」を参照してください。

### `describe-network-interfaces`
<a name="ec2_DescribeNetworkInterfaces_cli_2_topic"></a>

次のコード例は、`describe-network-interfaces` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイスを記述するには**  
この例では、すべてのネットワークインターフェイスを記述します。  
コマンド:  

```
aws ec2 describe-network-interfaces
```
出力:  

```
{
  "NetworkInterfaces": [
      {
          "Status": "in-use",
          "MacAddress": "02:2f:8f:b0:cf:75",
          "SourceDestCheck": true,
          "VpcId": "vpc-a01106c2",
          "Description": "my network interface",
          "Association": {
              "PublicIp": "203.0.113.12",
              "AssociationId": "eipassoc-0fbb766a",
              "PublicDnsName": "ec2-203-0-113-12.compute-1.amazonaws.com",
              "IpOwnerId": "123456789012"
          },
          "NetworkInterfaceId": "eni-e5aa89a3",
          "PrivateIpAddresses": [
              {
                  "PrivateDnsName": "ip-10-0-1-17.ec2.internal",
                  "Association": {
                      "PublicIp": "203.0.113.12",
                      "AssociationId": "eipassoc-0fbb766a",
                      "PublicDnsName": "ec2-203-0-113-12.compute-1.amazonaws.com",
                      "IpOwnerId": "123456789012"
                  },
                  "Primary": true,
                  "PrivateIpAddress": "10.0.1.17"
              }
          ],
          "RequesterManaged": false,
          "Ipv6Addresses": [],
          "PrivateDnsName": "ip-10-0-1-17.ec2.internal",
          "AvailabilityZone": "us-east-1d",
          "Attachment": {
              "Status": "attached",
              "DeviceIndex": 1,
              "AttachTime": "2013-11-30T23:36:42.000Z",
              "InstanceId": "i-1234567890abcdef0",
              "DeleteOnTermination": false,
              "AttachmentId": "eni-attach-66c4350a",
              "InstanceOwnerId": "123456789012"
          },
          "Groups": [
              {
                  "GroupName": "default",
                  "GroupId": "sg-8637d3e3"
              }
          ],
          "SubnetId": "subnet-b61f49f0",
          "OwnerId": "123456789012",
          "TagSet": [],
          "PrivateIpAddress": "10.0.1.17"
      },
      {
          "Status": "in-use",
          "MacAddress": "02:58:f5:ef:4b:06",
          "SourceDestCheck": true,
          "VpcId": "vpc-a01106c2",
          "Description": "Primary network interface",
          "Association": {
              "PublicIp": "198.51.100.0",
              "IpOwnerId": "amazon"
          },
          "NetworkInterfaceId": "eni-f9ba99bf",
          "PrivateIpAddresses": [
              {
                  "Association": {
                      "PublicIp": "198.51.100.0",
                      "IpOwnerId": "amazon"
                  },
                  "Primary": true,
                  "PrivateIpAddress": "10.0.1.149"
              }
          ],
          "RequesterManaged": false,
          "Ipv6Addresses": [],
          "AvailabilityZone": "us-east-1d",
          "Attachment": {
              "Status": "attached",
              "DeviceIndex": 0,
              "AttachTime": "2013-11-30T23:35:33.000Z",
              "InstanceId": "i-0598c7d356eba48d7",
              "DeleteOnTermination": true,
              "AttachmentId": "eni-attach-1b9db777",
              "InstanceOwnerId": "123456789012"
          },
          "Groups": [
              {
                  "GroupName": "default",
                  "GroupId": "sg-8637d3e3"
              }
          ],
          "SubnetId": "subnet-b61f49f0",
          "OwnerId": "123456789012",
          "TagSet": [],
          "PrivateIpAddress": "10.0.1.149"
      }
  ]
}
```
この例では、キー `Purpose` と値 `Prod` を含むタグを持つネットワークインターフェイスを記述します。  
コマンド:  

```
aws ec2 describe-network-interfaces --filters Name=tag:Purpose,Values=Prod
```
出力:  

```
{
  "NetworkInterfaces": [
      {
          "Status": "available",
          "MacAddress": "12:2c:bd:f9:bf:17",
          "SourceDestCheck": true,
          "VpcId": "vpc-8941ebec",
          "Description": "ProdENI",
          "NetworkInterfaceId": "eni-b9a5ac93",
          "PrivateIpAddresses": [
              {
                  "PrivateDnsName": "ip-10-0-1-55.ec2.internal",
                  "Primary": true,
                  "PrivateIpAddress": "10.0.1.55"
              },
              {
                  "PrivateDnsName": "ip-10-0-1-117.ec2.internal",
                  "Primary": false,
                  "PrivateIpAddress": "10.0.1.117"
              }
          ],
          "RequesterManaged": false,
          "PrivateDnsName": "ip-10-0-1-55.ec2.internal",
          "AvailabilityZone": "us-east-1d",
          "Ipv6Addresses": [],
          "Groups": [
              {
                  "GroupName": "MySG",
                  "GroupId": "sg-905002f5"
              }
          ],
          "SubnetId": "subnet-31d6c219",
          "OwnerId": "123456789012",
          "TagSet": [
              {
                  "Value": "Prod",
                  "Key": "Purpose"
              }
          ],
          "PrivateIpAddress": "10.0.1.55"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNetworkInterfaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-interfaces.html)」を参照してください。

### `describe-placement-groups`
<a name="ec2_DescribePlacementGroups_cli_2_topic"></a>

次のコード例は、`describe-placement-groups` を使用する方法を示しています。

**AWS CLI**  
**プレイスメントグループを記述するには**  
このコマンド例では、すべてのプレイスメントグループを記述します。  
コマンド:  

```
aws ec2 describe-placement-groups
```
出力:  

```
{
    "PlacementGroups": [
        {
            "GroupName": "my-cluster",
            "State": "available",
            "Strategy": "cluster"
        },
        ...
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePlacementGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-placement-groups.html)」を参照してください。

### `describe-prefix-lists`
<a name="ec2_DescribePrefixLists_cli_2_topic"></a>

次のコード例は、`describe-prefix-lists` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストを記述するには**  
この例では、リージョンで使用可能なすべてのプレフィックスリストを一覧表示します。  
コマンド:  

```
aws ec2 describe-prefix-lists
```
出力:  

```
{
  "PrefixLists": [
    {
      "PrefixListName": "com.amazonaws.us-east-1.s3",
      "Cidrs": [
        "54.231.0.0/17"
      ],
      "PrefixListId": "pl-63a5400a"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePrefixLists](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-prefix-lists.html)」を参照してください。

### `describe-principal-id-format`
<a name="ec2_DescribePrincipalIdFormat_cli_2_topic"></a>

次のコード例は、`describe-principal-id-format` を使用する方法を示しています。

**AWS CLI**  
**長い ID 形式が有効になっている IAM ユーザーとロールの ID 形式を記述するには**  
次の `describe-principal-id-format` の例では、ルートユーザーの ID 形式、すべての IAM ロール、および長い ID 形式が有効になっているすべての IAM ユーザーについて説明します。  

```
aws ec2 describe-principal-id-format \
    --resource instance
```
出力:  

```
{
    "Principals": [
        {
            "Arn": "arn:aws:iam::123456789012:root",
            "Statuses": [
                {
                    "Deadline": "2016-12-15T00:00:00.000Z",
                    "Resource": "reservation",
                    "UseLongIds": true
                },
                {
                    "Deadline": "2016-12-15T00:00:00.000Z",
                    "Resource": "instance",
                    "UseLongIds": true
                },
                {
                    "Deadline": "2016-12-15T00:00:00.000Z",
                    "Resource": "volume",
                    "UseLongIds": true
                },
            ]
        },
        ...
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePrincipalIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-principal-id-format.html)」を参照してください。

### `describe-public-ipv4-pools`
<a name="ec2_DescribePublicIpv4Pools_cli_2_topic"></a>

次のコード例は、`describe-public-ipv4-pools` を使用する方法を示しています。

**AWS CLI**  
**パブリック IPv4 アドレスプールを記述するには**  
次の `describe-public-ipv4-pools` の例では、BYOIP (Bring Your Own IP Addresses) を使用してパブリック IPv4 アドレス範囲をプロビジョニングしたときに作成されたアドレスプールの詳細を表示します。  

```
aws ec2 describe-public-ipv4-pools
```
出力:  

```
{
    "PublicIpv4Pools": [
        {
            "PoolId": "ipv4pool-ec2-1234567890abcdef0",
            "PoolAddressRanges": [
                {
                    "FirstAddress": "203.0.113.0",
                    "LastAddress": "203.0.113.255",
                    "AddressCount": 256,
                    "AvailableAddressCount": 256
                }
            ],
            "TotalAddressCount": 256,
            "TotalAvailableAddressCount": 256
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePublicIpv4Pools](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-public-ipv4-pools.html)」を参照してください。

### `describe-regions`
<a name="ec2_DescribeRegions_cli_2_topic"></a>

次のコード例は、`describe-regions` を使用する方法を示しています。

**AWS CLI**  
**例 1: 有効になっているすべてのリージョンを説明するには**  
次の `describe-regions` の例は、アカウントで有効なすべてのリージョンを説明しています。  

```
aws ec2 describe-regions
```
出力:  

```
{
    "Regions": [
        {
            "Endpoint": "ec2.eu-north-1.amazonaws.com",
            "RegionName": "eu-north-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-south-1.amazonaws.com",
            "RegionName": "ap-south-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-3.amazonaws.com",
            "RegionName": "eu-west-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-2.amazonaws.com",
            "RegionName": "eu-west-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-1.amazonaws.com",
            "RegionName": "eu-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-3.amazonaws.com",
            "RegionName": "ap-northeast-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-2.amazonaws.com",
            "RegionName": "ap-northeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-1.amazonaws.com",
            "RegionName": "ap-northeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.sa-east-1.amazonaws.com",
            "RegionName": "sa-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ca-central-1.amazonaws.com",
            "RegionName": "ca-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-southeast-1.amazonaws.com",
            "RegionName": "ap-southeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-southeast-2.amazonaws.com",
            "RegionName": "ap-southeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-central-1.amazonaws.com",
            "RegionName": "eu-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-1.amazonaws.com",
            "RegionName": "us-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-2.amazonaws.com",
            "RegionName": "us-east-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-1.amazonaws.com",
            "RegionName": "us-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-2.amazonaws.com",
            "RegionName": "us-west-2",
            "OptInStatus": "opt-in-not-required"
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[リージョンとゾーン](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)」を参照してください。  
**例 2: エンドポイント名に特定の文字列が含まれる有効なリージョンを説明するには**  
次の `describe-regions` の例では、エンドポイントに「us」という文字列が含まれる、有効にしたすべてのリージョンを説明しています。  

```
aws ec2 describe-regions \
    --filters "Name=endpoint,Values=*us*"
```
出力:  

```
{
    "Regions": [
        {
            "Endpoint": "ec2.us-east-1.amazonaws.com",
            "RegionName": "us-east-1"
        },
        {
            "Endpoint": "ec2.us-east-2.amazonaws.com",
            "RegionName": "us-east-2"
        },
        {
            "Endpoint": "ec2.us-west-1.amazonaws.com",
            "RegionName": "us-west-1"
        },
        {
            "Endpoint": "ec2.us-west-2.amazonaws.com",
            "RegionName": "us-west-2"
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[リージョンとゾーン](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)」を参照してください。  
**例 3: すべてのリージョンを説明するには**  
次の `describe-regions` の例では、無効になっているリージョンを含め、使用可能なすべてのリージョンについて説明しています。  

```
aws ec2 describe-regions \
    --all-regions
```
出力:  

```
{
    "Regions": [
        {
            "Endpoint": "ec2.eu-north-1.amazonaws.com",
            "RegionName": "eu-north-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-south-1.amazonaws.com",
            "RegionName": "ap-south-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-3.amazonaws.com",
            "RegionName": "eu-west-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-2.amazonaws.com",
            "RegionName": "eu-west-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-west-1.amazonaws.com",
            "RegionName": "eu-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-3.amazonaws.com",
            "RegionName": "ap-northeast-3",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.me-south-1.amazonaws.com",
            "RegionName": "me-south-1",
            "OptInStatus": "not-opted-in"
        },
        {
            "Endpoint": "ec2.ap-northeast-2.amazonaws.com",
            "RegionName": "ap-northeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-northeast-1.amazonaws.com",
            "RegionName": "ap-northeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.sa-east-1.amazonaws.com",
            "RegionName": "sa-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ca-central-1.amazonaws.com",
            "RegionName": "ca-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-east-1.amazonaws.com",
            "RegionName": "ap-east-1",
            "OptInStatus": "not-opted-in"
        },
        {
            "Endpoint": "ec2.ap-southeast-1.amazonaws.com",
            "RegionName": "ap-southeast-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.ap-southeast-2.amazonaws.com",
            "RegionName": "ap-southeast-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.eu-central-1.amazonaws.com",
            "RegionName": "eu-central-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-1.amazonaws.com",
            "RegionName": "us-east-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-east-2.amazonaws.com",
            "RegionName": "us-east-2",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-1.amazonaws.com",
            "RegionName": "us-west-1",
            "OptInStatus": "opt-in-not-required"
        },
        {
            "Endpoint": "ec2.us-west-2.amazonaws.com",
            "RegionName": "us-west-2",
            "OptInStatus": "opt-in-not-required"
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[リージョンとゾーン](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)」を参照してください。  
**例 4: リージョン名だけを一覧表示するには**  
次の `describe-regions` の例では、`--query` パラメータを使用して出力をフィルタリングし、リージョンの名前のみをテキストとして返します。  

```
aws ec2 describe-regions \
    --all-regions \
    --query "Regions[].{Name:RegionName}" \
    --output text
```
出力:  

```
eu-north-1
ap-south-1
eu-west-3
eu-west-2
eu-west-1
ap-northeast-3
ap-northeast-2
me-south-1
ap-northeast-1
sa-east-1
ca-central-1
ap-east-1
ap-southeast-1
ap-southeast-2
eu-central-1
us-east-1
us-east-2
us-west-1
us-west-2
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[リージョンとゾーン](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeRegions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-regions.html)」を参照してください。

### `describe-replace-root-volume-tasks`
<a name="ec2_DescribeReplaceRootVolumeTasks_cli_2_topic"></a>

次のコード例は、`describe-replace-root-volume-tasks` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定のルートボリューム置き換えタスクに関する情報を表示するには**  
次の `describe-replace-root-volume-tasks` の例では、ルートボリュームの置き換えタスク replacevol-0111122223333abcd について説明します。  

```
aws ec2 describe-replace-root-volume-tasks \
    --replace-root-volume-task-ids replacevol-0111122223333abcd
```
出力:  

```
{
    "ReplaceRootVolumeTasks": [
        {
            "ReplaceRootVolumeTaskId": "replacevol-0111122223333abcd",
            "Tags": [],
            "InstanceId": "i-0123456789abcdefa",
            "TaskState": "succeeded",
            "StartTime": "2022-03-14T15:16:28Z",
            "CompleteTime": "2022-03-14T15:16:52Z"
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[Replace a root volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-restoring-volume.html#replace-root)」を参照してください。  
**例 2: 特定のインスタンスのすべてのルートボリューム置き換えタスクに関する情報を表示するには**  
次の `describe-replace-root-volume-tasks` の例では、インスタンス i-0123456789abcdefa のすべてのルートボリュームの置き換えタスクについて説明します。  

```
aws ec2 describe-replace-root-volume-tasks \
    --filters Name=instance-id,Values=i-0123456789abcdefa
```
出力:  

```
{
    "ReplaceRootVolumeTasks": [
        {
            "ReplaceRootVolumeTaskId": "replacevol-0111122223333abcd",
            "Tags": [],
            "InstanceId": "i-0123456789abcdefa",
            "TaskState": "succeeded",
            "StartTime": "2022-03-14T15:06:38Z",
            "CompleteTime": "2022-03-14T15:07:03Z"
        },
        {
            "ReplaceRootVolumeTaskId": "replacevol-0444455555555abcd",
            "Tags": [],
            "InstanceId": "i-0123456789abcdefa",
            "TaskState": "succeeded",
            "StartTime": "2022-03-14T15:16:28Z",
            "CompleteTime": "2022-03-14T15:16:52Z"
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[Replace a root volume](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-restoring-volume.html#replace-root)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReplaceRootVolumeTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-replace-root-volume-tasks.html)」を参照してください。

### `describe-reserved-instances-listings`
<a name="ec2_DescribeReservedInstancesListings_cli_2_topic"></a>

次のコード例は、`describe-reserved-instances-listings` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスのリストを記述するには**  
次の `describe-reserved-instances-listings` の例では、指定したリザーブドインスタンスのリスト関する情報を取得します。  

```
aws ec2 describe-reserved-instances-listings \
    --reserved-instances-listing-id 5ec28771-05ff-4b9b-aa31-9e57dexample
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedInstancesListings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-reserved-instances-listings.html)」を参照してください。

### `describe-reserved-instances-modifications`
<a name="ec2_DescribeReservedInstancesModifications_cli_2_topic"></a>

次のコード例は、`describe-reserved-instances-modifications` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスの変更を記述するには**  
このコマンド例では、 アカウントに対して送信されたすべてのリザーブドインスタンスの変更リクエストを記述します。  
コマンド:  

```
aws ec2 describe-reserved-instances-modifications
```
出力:  

```
{
    "ReservedInstancesModifications": [
        {
            "Status": "fulfilled",
            "ModificationResults": [
                {
                    "ReservedInstancesId": "93bbbca2-62f1-4d9d-b225-16bada29e6c7",
                    "TargetConfiguration": {
                        "AvailabilityZone": "us-east-1b",
                        "InstanceType": "m1.large",
                        "InstanceCount": 3
                    }
                },
                {
                     "ReservedInstancesId": "1ba8e2e3-aabb-46c3-bcf5-3fe2fda922e6",
                     "TargetConfiguration": {
                         "AvailabilityZone": "us-east-1d",
                         "InstanceType": "m1.xlarge",
                         "InstanceCount": 1
                     }
                 }
            ],
            "EffectiveDate": "2015-08-12T17:00:00.000Z",
            "CreateDate": "2015-08-12T17:52:52.630Z",
            "UpdateDate": "2015-08-12T18:08:06.698Z",
            "ClientToken": "c9adb218-3222-4889-8216-0cf0e52dc37e:
            "ReservedInstancesModificationId": "rimod-d3ed4335-b1d3-4de6-ab31-0f13aaf46687",
            "ReservedInstancesIds": [
                {
                    "ReservedInstancesId": "b847fa93-e282-4f55-b59a-1342f5bd7c02"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedInstancesModifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-reserved-instances-modifications.html)」を参照してください。

### `describe-reserved-instances-offerings`
<a name="ec2_DescribeReservedInstancesOfferings_cli_2_topic"></a>

次のコード例は、`describe-reserved-instances-offerings` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスサービスを記述するには**  
このコマンド例では、リージョンで購入できるすべてのリザーブドインスタンスを記述します。  
コマンド:  

```
aws ec2 describe-reserved-instances-offerings
```
出力:  

```
{
  "ReservedInstancesOfferings": [
      {
          "OfferingType": "Partial Upfront",
          "AvailabilityZone": "us-east-1b",
          "InstanceTenancy": "default",
          "PricingDetails": [],
          "ProductDescription": "Red Hat Enterprise Linux",
          "UsagePrice": 0.0,
          "RecurringCharges": [
              {
                  "Amount": 0.088,
                  "Frequency": "Hourly"
              }
          ],
          "Marketplace": false,
          "CurrencyCode": "USD",
          "FixedPrice": 631.0,
          "Duration": 94608000,
          "ReservedInstancesOfferingId": "9a06095a-bdc6-47fe-a94a-2a382f016040",
          "InstanceType": "c1.medium"
      },
      {
          "OfferingType": "PartialUpfront",
          "AvailabilityZone": "us-east-1b",
          "InstanceTenancy": "default",
          "PricingDetails": [],
          "ProductDescription": "Linux/UNIX",
          "UsagePrice": 0.0,
          "RecurringCharges": [
              {
                  "Amount": 0.028,
                  "Frequency": "Hourly"
              }
          ],
          "Marketplace": false,
          "CurrencyCode": "USD",
          "FixedPrice": 631.0,
          "Duration": 94608000,
          "ReservedInstancesOfferingId": "bfbefc6c-0d10-418d-b144-7258578d329d",
          "InstanceType": "c1.medium"
      },
  ...
}
```
**オプションを使用してリザーブドインスタンスサービスを記述するには**  
この例では、t1.micro インスタンスタイプ、Windows (Amazon VPC) 製品、Heavy Utilization オファリングの仕様 AWS で が提供するリザーブドインスタンスを一覧表示します。  
コマンド:  

```
aws ec2 describe-reserved-instances-offerings --no-include-marketplace --instance-type "t1.micro" --product-description "Windows (Amazon VPC)" --offering-type "no upfront"
```
出力:  

```
{
    "ReservedInstancesOfferings": [
      {
          "OfferingType": "No Upfront",
          "AvailabilityZone": "us-east-1b",
          "InstanceTenancy": "default",
          "PricingDetails": [],
          "ProductDescription": "Windows",
          "UsagePrice": 0.0,
          "RecurringCharges": [
              {
                  "Amount": 0.015,
                  "Frequency": "Hourly"
              }
          ],
          "Marketplace": false,
          "CurrencyCode": "USD",
          "FixedPrice": 0.0,
          "Duration": 31536000,
          "ReservedInstancesOfferingId": "c48ab04c-fe69-4f94-8e39-a23842292823",
          "InstanceType": "t1.micro"
      },

              ...
      {
          "OfferingType": "No Upfront",
          "AvailabilityZone": "us-east-1d",
          "InstanceTenancy": "default",
          "PricingDetails": [],
          "ProductDescription": "Windows (Amazon VPC)",
          "UsagePrice": 0.0,
          "RecurringCharges": [
              {
                  "Amount": 0.015,
                  "Frequency": "Hourly"
              }
          ],
          "Marketplace": false,
          "CurrencyCode": "USD",
          "FixedPrice": 0.0,
          "Duration": 31536000,
          "ReservedInstancesOfferingId": "3a98bf7d-2123-42d4-b4f5-8dbec4b06dc6",
          "InstanceType": "t1.micro"
      }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedInstancesOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-reserved-instances-offerings.html)」を参照してください。

### `describe-reserved-instances`
<a name="ec2_DescribeReservedInstances_cli_2_topic"></a>

次のコード例は、`describe-reserved-instances` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスを記述するには**  
このコマンド例では、所有しているリザーブドインスタンスを記述します。  
コマンド:  

```
aws ec2 describe-reserved-instances
```
出力:  

```
{
  "ReservedInstances": [
      {
          "ReservedInstancesId": "b847fa93-e282-4f55-b59a-1342fexample",
          "OfferingType": "No Upfront",
          "AvailabilityZone": "us-west-1c",
          "End": "2016-08-14T21:34:34.000Z",
          "ProductDescription": "Linux/UNIX",
          "UsagePrice": 0.00,
          "RecurringCharges": [
              {
                  "Amount": 0.104,
                  "Frequency": "Hourly"
              }
          ],
          "Start": "2015-08-15T21:34:35.086Z",
          "State": "active",
          "FixedPrice": 0.0,
          "CurrencyCode": "USD",
          "Duration": 31536000,
          "InstanceTenancy": "default",
          "InstanceType": "m3.medium",
          "InstanceCount": 2
      },
      ...
  ]
}
```
**フィルターを使用してリザーブドインスタンスを記述するには**  
この例では、us-west-1c に 3 年間の t2.micro Linux/UNIX リザーブドインスタンスのみを含めるようにレスポンスをフィルタリングします。  
コマンド:  

```
aws ec2 describe-reserved-instances --filters Name=duration,Values=94608000 Name=instance-type,Values=t2.micro Name=product-description,Values=Linux/UNIX Name=availability-zone,Values=us-east-1e
```
出力:  

```
{
    "ReservedInstances": [
        {
            "ReservedInstancesId": "f127bd27-edb7-44c9-a0eb-0d7e09259af0",
            "OfferingType": "All Upfront",
            "AvailabilityZone": "us-east-1e",
            "End": "2018-03-26T21:34:34.000Z",
            "ProductDescription": "Linux/UNIX",
            "UsagePrice": 0.00,
            "RecurringCharges": [],
            "Start": "2015-03-27T21:34:35.848Z",
            "State": "active",
            "FixedPrice": 151.0,
            "CurrencyCode": "USD",
            "Duration": 94608000,
            "InstanceTenancy": "default",
            "InstanceType": "t2.micro",
            "InstanceCount": 1
        }
    ]
}
```
詳細については、「*AWS コマンドラインインターフェイスユーザーガイド*」で Amazon EC2 インスタンスの使用方法を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-reserved-instances.html)」を参照してください。

### `describe-route-tables`
<a name="ec2_DescribeRouteTables_cli_2_topic"></a>

次のコード例は、`describe-route-tables` を使用する方法を示しています。

**AWS CLI**  
**ルートテーブルを記述するには**  
次の `describe-route-tables` の例では、ルートテーブルの詳細を取得します。  

```
aws ec2 describe-route-tables
```
出力:  

```
{
    "RouteTables": [
        {
            "Associations": [
                {
                    "Main": true,
                    "RouteTableAssociationId": "rtbassoc-0df3f54e06EXAMPLE",
                    "RouteTableId": "rtb-09ba434c1bEXAMPLE"
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-09ba434c1bEXAMPLE",
            "Routes": [
                {
                    "DestinationCidrBlock": "10.0.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "NatGatewayId": "nat-06c018cbd8EXAMPLE",
                    "Origin": "CreateRoute",
                    "State": "blackhole"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-0065acced4EXAMPLE",
            "OwnerId": "111122223333"
        },
        {
            "Associations": [
                {
                    "Main": true,
                    "RouteTableAssociationId": "rtbassoc-9EXAMPLE",
                    "RouteTableId": "rtb-a1eec7de"
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-a1eec7de",
            "Routes": [
                {
                    "DestinationCidrBlock": "172.31.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "GatewayId": "igw-fEXAMPLE",
                    "Origin": "CreateRoute",
                    "State": "active"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-3EXAMPLE",
            "OwnerId": "111122223333"
        },
        {
            "Associations": [
                {
                    "Main": false,
                    "RouteTableAssociationId": "rtbassoc-0b100c28b2EXAMPLE",
                    "RouteTableId": "rtb-07a98f76e5EXAMPLE",
                    "SubnetId": "subnet-0d3d002af8EXAMPLE"
                }
            ],
            "PropagatingVgws": [],
            "RouteTableId": "rtb-07a98f76e5EXAMPLE",
            "Routes": [
                {
                    "DestinationCidrBlock": "10.0.0.0/16",
                    "GatewayId": "local",
                    "Origin": "CreateRouteTable",
                    "State": "active"
                },
                {
                    "DestinationCidrBlock": "0.0.0.0/0",
                    "GatewayId": "igw-06cf664d80EXAMPLE",
                    "Origin": "CreateRoute",
                    "State": "active"
                }
            ],
            "Tags": [],
            "VpcId": "vpc-0065acced4EXAMPLE",
            "OwnerId": "111122223333"
        }
    ]
}
```
詳細については、「*AWS VPC ユーザーガイド*」の「[Working with Route Tables](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#WorkWithRouteTables)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRouteTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-route-tables.html)」を参照してください。

### `describe-scheduled-instance-availability`
<a name="ec2_DescribeScheduledInstanceAvailability_cli_2_topic"></a>

次のコード例は、`describe-scheduled-instance-availability` を使用する方法を示しています。

**AWS CLI**  
**使用可能なスケジュールを記述するには**  
この例では、指定した日付から毎週日曜日に発生するスケジュールを記述します。  
コマンド:  

```
aws ec2 describe-scheduled-instance-availability --recurrence Frequency=Weekly,Interval=1,OccurrenceDays=[1] --first-slot-start-time-range EarliestTime=2016-01-31T00:00:00Z,LatestTime=2016-01-31T04:00:00Z
```
出力:  

```
{
  "ScheduledInstanceAvailabilitySet": [
    {
        "AvailabilityZone": "us-west-2b",
        "TotalScheduledInstanceHours": 1219,
        "PurchaseToken": "eyJ2IjoiMSIsInMiOjEsImMiOi...",
        "MinTermDurationInDays": 366,
        "AvailableInstanceCount": 20,
        "Recurrence": {
            "OccurrenceDaySet": [
                1
            ],
            "Interval": 1,
            "Frequency": "Weekly",
            "OccurrenceRelativeToEnd": false
        },
        "Platform": "Linux/UNIX",
        "FirstSlotStartTime": "2016-01-31T00:00:00Z",
        "MaxTermDurationInDays": 366,
        "SlotDurationInHours": 23,
        "NetworkPlatform": "EC2-VPC",
        "InstanceType": "c4.large",
        "HourlyPrice": "0.095"
    },
    ...
  ]
}
```
結果を絞り込むために、オペレーティングシステム、ネットワーク、インスタンスタイプを指定するフィルターを追加できます。  
コマンド:  
--filters Name=platform,Values=Linux/UNIX Name=network-platform,Values=EC2-VPC Name=instance-type,Values=c4.large  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScheduledInstanceAvailability](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-scheduled-instance-availability.html)」を参照してください。

### `describe-scheduled-instances`
<a name="ec2_DescribeScheduledInstances_cli_2_topic"></a>

次のコード例は、`describe-scheduled-instances` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされたインスタンスを記述するには**  
この例では、指定のスケジュールされたインスタンスを記述します。  
コマンド:  

```
aws ec2 describe-scheduled-instances --scheduled-instance-ids sci-1234-1234-1234-1234-123456789012
```
出力:  

```
{
  "ScheduledInstanceSet": [
      {
          "AvailabilityZone": "us-west-2b",
          "ScheduledInstanceId": "sci-1234-1234-1234-1234-123456789012",
          "HourlyPrice": "0.095",
          "CreateDate": "2016-01-25T21:43:38.612Z",
          "Recurrence": {
              "OccurrenceDaySet": [
                  1
              ],
              "Interval": 1,
              "Frequency": "Weekly",
              "OccurrenceRelativeToEnd": false,
              "OccurrenceUnit": ""
          },
          "Platform": "Linux/UNIX",
          "TermEndDate": "2017-01-31T09:00:00Z",
          "InstanceCount": 1,
          "SlotDurationInHours": 32,
          "TermStartDate": "2016-01-31T09:00:00Z",
          "NetworkPlatform": "EC2-VPC",
          "TotalScheduledInstanceHours": 1696,
          "NextSlotStartTime": "2016-01-31T09:00:00Z",
          "InstanceType": "c4.large"
      }
  ]
}
```
この例では、すべてのスケジュールされたインスタンスを記述します。  
コマンド:  

```
aws ec2 describe-scheduled-instances
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScheduledInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-scheduled-instances.html)」を参照してください。

### `describe-security-group-references`
<a name="ec2_DescribeSecurityGroupReferences_cli_2_topic"></a>

次のコード例は、`describe-security-group-references` を使用する方法を示しています。

**AWS CLI**  
**セキュリティグループの参照を記述するには**  
この例では、`sg-bbbb2222` のセキュリティグループの参照を記述します。応答は、セキュリティグループ `sg-bbbb2222` が VPC `vpc-aaaaaaaa` のセキュリティグループで参照されていることを示します。  
コマンド:  

```
aws ec2 describe-security-group-references --group-id sg-bbbbb22222
```
出力:  

```
{
  "SecurityGroupsReferenceSet": [
    {
      "ReferencingVpcId": "vpc-aaaaaaaa ",
      "GroupId": "sg-bbbbb22222",
      "VpcPeeringConnectionId": "pcx-b04deed9"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSecurityGroupReferences](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-security-group-references.html)」を参照してください。

### `describe-security-group-rules`
<a name="ec2_DescribeSecurityGroupRules_cli_2_topic"></a>

次のコード例は、`describe-security-group-rules` を使用する方法を示しています。

**AWS CLI**  
**例 1: セキュリティグループのセキュリティグループルールを記述するには**  
次の `describe-security-group-rules` の例では、指定したセキュリティグループのセキュリティグループルールについて説明します。`filters` オプションを使用して、結果を特定のセキュリティグループにスコープします。  

```
aws ec2 describe-security-group-rules \
    --filters Name="group-id",Values="sg-1234567890abcdef0"
```
出力:  

```
{
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-abcdef01234567890",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "111122223333",
            "IsEgress": false,
            "IpProtocol": "-1",
            "FromPort": -1,
            "ToPort": -1,
            "ReferencedGroupInfo": {
                "GroupId": "sg-1234567890abcdef0",
                "UserId": "111122223333"
            },
            "Tags": []
        },
        {
            "SecurityGroupRuleId": "sgr-bcdef01234567890a",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "111122223333",
            "IsEgress": true,
            "IpProtocol": "-1",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv6": "::/0",
            "Tags": []
        },
        {
            "SecurityGroupRuleId": "sgr-cdef01234567890ab",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "111122223333",
            "IsEgress": true,
            "IpProtocol": "-1",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv4": "0.0.0.0/0",
            "Tags": []
        }
    ]
}
```
**例 2: セキュリティグループルールを記述するには**  
次の `describe-security-group-rules` の例では、指定したセキュリティグループルールについて説明します。  

```
aws ec2 describe-security-group-rules \
    --security-group-rule-ids sgr-cdef01234567890ab
```
出力:  

```
{
    "SecurityGroupRules": [
        {
            "SecurityGroupRuleId": "sgr-cdef01234567890ab",
            "GroupId": "sg-1234567890abcdef0",
            "GroupOwnerId": "111122223333",
            "IsEgress": true,
            "IpProtocol": "-1",
            "FromPort": -1,
            "ToPort": -1,
            "CidrIpv4": "0.0.0.0/0",
            "Tags": []
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[セキュリティグループルール](https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSecurityGroupRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-security-group-rules.html)」を参照してください。

### `describe-security-group-vpc-associations`
<a name="ec2_DescribeSecurityGroupVpcAssociations_cli_2_topic"></a>

次のコード例は、`describe-security-group-vpc-associations` を使用する方法を示しています。

**AWS CLI**  
**VPC の関連付けを記述するには**  
次の `describe-security-group-vpc-associations` の例では、指定したセキュリティグループの VPC 関連付けを記述します。  

```
aws ec2 describe-security-group-vpc-associations \
    --filters Name=group-id,Values=sg-04dbb43907d3f8a78
```
出力:  

```
{
    "SecurityGroupVpcAssociations": [
        {
            "GroupId": "sg-04dbb43907d3f8a78",
            "VpcId": "vpc-0bf4c2739bc05a694",
            "VpcOwnerId": "123456789012",
            "State": "associated"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[セキュリティグループを複数の VPC に関連付ける](https://docs.aws.amazon.com/vpc/latest/userguide/security-group-assoc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSecurityGroupVpcAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-security-group-vpc-associations.html)」を参照してください。

### `describe-security-groups`
<a name="ec2_DescribeSecurityGroups_cli_2_topic"></a>

次のコード例は、`describe-security-groups` を使用する方法を示しています。

**AWS CLI**  
**例 1: セキュリティグループを説明するには**  
次の `describe-security-groups` の例では、指定したセキュリティグループを示しています。  

```
aws ec2 describe-security-groups \
    --group-ids sg-903004f8
```
出力:  

```
{
    "SecurityGroups": [
        {
            "IpPermissionsEgress": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [
                        {
                            "CidrIp": "0.0.0.0/0"
                        }
                    ],
                    "UserIdGroupPairs": [],
                    "PrefixListIds": []
                }
            ],
            "Description": "My security group",
            "Tags": [
                {
                    "Value": "SG1",
                    "Key": "Name"
                }
            ],
            "IpPermissions": [
                {
                    "IpProtocol": "-1",
                    "IpRanges": [],
                    "UserIdGroupPairs": [
                        {
                            "UserId": "123456789012",
                            "GroupId": "sg-903004f8"
                        }
                    ],
                    "PrefixListIds": []
                },
                {
                    "PrefixListIds": [],
                    "FromPort": 22,
                    "IpRanges": [
                        {
                            "Description": "Access from NY office",
                            "CidrIp": "203.0.113.0/24"
                        }
                    ],
                    "ToPort": 22,
                    "IpProtocol": "tcp",
                    "UserIdGroupPairs": []
                    }
            ],
            "GroupName": "MySecurityGroup",
            "VpcId": "vpc-1a2b3c4d",
            "OwnerId": "123456789012",
            "GroupId": "sg-903004f8",
        }
    ]
}
```
**例 2: 特定のルールを持つセキュリティグループを説明するには**  
次の `describe-security-groups` の例では、フィルターを使用して、SSH トラフィック (ポート 22) を許可するルールと、すべてのアドレス (`0.0.0.0/0`) からのトラフィックを許可するルールを持つセキュリティグループに結果の範囲を絞り込みます。例では、`--query` パラメータを使用してセキュリティグループの名前のみを表示しています。セキュリティグループが結果で返されるようにするには、すべてのフィルターに一致する必要があります。ただし、1 つのルールがすべてのフィルターに一致する必要はありません。例えば、出力は、特定の IP アドレスからの SSH トラフィックを許可するルールと、すべてのアドレスからの HTTP トラフィックを許可する別のルールを含むセキュリティグループを返します。  

```
aws ec2 describe-security-groups \
    --filters Name=ip-permission.from-port,Values=22 Name=ip-permission.to-port,Values=22 Name=ip-permission.cidr,Values='0.0.0.0/0' \
    --query "SecurityGroups[*].[GroupName]" \
    --output text
```
出力:  

```
default
my-security-group
web-servers
launch-wizard-1
```
**例 3: タグに基づいてセキュリティグループを説明するには**  
次の `describe-security-groups` の例では、フィルターを使用して、セキュリティグループ名に `test` が含まれ、タグ `Test=To-delete` が付けられているセキュリティグループに結果を絞り込みます。例では、`--query` パラメータを使用してセキュリティグループの名前と ID のみを表示しています。  

```
aws ec2 describe-security-groups \
    --filters Name=group-name,Values=*test* Name=tag:Test,Values=To-delete \
    --query "SecurityGroups[*].{Name:GroupName,ID:GroupId}"
```
出力:  

```
[
    {
        "Name": "testfornewinstance",
        "ID": "sg-33bb22aa"
    },
    {
        "Name": "newgrouptest",
        "ID": "sg-1a2b3c4d"
    }
]
```
タグフィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[タグの使用方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeSecurityGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-security-groups.html)」を参照してください。

### `describe-snapshot-attribute`
<a name="ec2_DescribeSnapshotAttribute_cli_2_topic"></a>

次のコード例は、`describe-snapshot-attribute` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのスナップショット属性を記述するには**  
次の `describe-snapshot-attribute` の例では、スナップショットを共有するアカウントを一覧表示します。  

```
aws ec2 describe-snapshot-attribute \
    --snapshot-id snap-01234567890abcedf \
    --attribute createVolumePermission
```
出力:  

```
{
    "SnapshotId": "snap-01234567890abcedf",
    "CreateVolumePermissions": [
        {
            "UserId": "123456789012"
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[Share an Amazon EBS snapshot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-modifying-snapshot-permissions.html#share-unencrypted-snapshot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-snapshot-attribute.html)」を参照してください。

### `describe-snapshot-tier-status`
<a name="ec2_DescribeSnapshotTierStatus_cli_2_topic"></a>

次のコード例は、`describe-snapshot-tier-status` を使用する方法を示しています。

**AWS CLI**  
**アーカイブされたスナップショットに関するアーカイブ情報を表示するには**  
次の `describe-snapshot-tier-status` の例では、アーカイブされたスナップショットに関するアーカイブ情報を提供します。  

```
aws ec2 describe-snapshot-tier-status \
    --filters "Name=snapshot-id, Values=snap-01234567890abcedf"
```
出力:  

```
{
    "SnapshotTierStatuses": [
        {
            "Status": "completed",
            "ArchivalCompleteTime": "2021-09-15T17:33:16.147Z",
            "LastTieringProgress": 100,
            "Tags": [],
            "VolumeId": "vol-01234567890abcedf",
            "LastTieringOperationState": "archival-completed",
            "StorageTier": "archive",
            "OwnerId": "123456789012",
            "SnapshotId": "snap-01234567890abcedf",
            "LastTieringStartTime": "2021-09-15T16:44:37.574Z"
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[アーカイブされたスナップショットを表示する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-snapshot-archiving.html#view-archived-snapshot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSnapshotTierStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-snapshot-tier-status.html)」を参照してください。

### `describe-snapshots`
<a name="ec2_DescribeSnapshots_cli_2_topic"></a>

次のコード例は、`describe-snapshots` を使用する方法を示しています。

**AWS CLI**  
**例 1: スナップショットを説明するには**  
次の `describe-snapshots` の例では、指定したスナップショットを示しています。  

```
aws ec2 describe-snapshots \
    --snapshot-ids snap-1234567890abcdef0
```
出力:  

```
{
    "Snapshots": [
        {
            "Description": "This is my snapshot",
            "Encrypted": false,
            "VolumeId": "vol-049df61146c4d7901",
            "State": "completed",
            "VolumeSize": 8,
            "StartTime": "2019-02-28T21:28:32.000Z",
            "Progress": "100%",
            "OwnerId": "012345678910",
            "SnapshotId": "snap-01234567890abcdef",
            "Tags": [
                {
                    "Key": "Stack",
                    "Value": "test"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Amazon EBS スナップショット](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSSnapshots.html)」を参照してください。  
**例 2: フィルターに基づいてスナップショットを説明するには**  
次の`describe-snapshots`例では、フィルターを使用して、 `pending`状態にある AWS アカウントが所有するスナップショットに結果をスコープします。この例では、`--query` パラメータを使用して、スナップショット ID とスナップショットが開始された時間のみを表示します。  

```
aws ec2 describe-snapshots \
    --owner-ids self \
    --filters Name=status,Values=pending \
    --query "Snapshots[*].{ID:SnapshotId,Time:StartTime}"
```
出力:  

```
[
    {
        "ID": "snap-1234567890abcdef0",
        "Time": "2019-08-04T12:48:18.000Z"
    },
    {
        "ID": "snap-066877671789bd71b",
        "Time": "2019-08-04T02:45:16.000Z
    },
    ...
]
```
次の `describe-snapshots` の例では、フィルターを使用して、指定したボリュームから作成されたスナップショットに結果を絞っています。この例では、`--query` パラメータを使用してスナップショット ID のみを表示します。  

```
aws ec2 describe-snapshots \
    --filters Name=volume-id,Values=049df61146c4d7901 \
    --query "Snapshots[*].[SnapshotId]" \
    --output text
```
出力:  

```
snap-1234567890abcdef0
snap-08637175a712c3fb9
...
```
フィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[リソースの一覧表示とフィルタリングの方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)」を参照してください。  
**例 3: タグに基づいてスナップショットを説明するには**  
次の `describe-snapshots` の例では、タグフィルターを使用して、結果の範囲をタグ `Stack=Prod` を含むスナップショットに限定しています。  

```
aws ec2 describe-snapshots \
    --filters Name=tag:Stack,Values=prod
```
`describe-snapshots` の出力例については、例 1 を参照してください。  
タグフィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[タグの使用方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)」を参照してください。  
**例 4: 日付に基づいてスナップショットを説明するには**  
次の`describe-snapshots`例では、JMESPath 式を使用して、指定した日付より前に AWS アカウントによって作成されたすべてのスナップショットを記述します。スナップショット ID のみが表示されます。  

```
aws ec2 describe-snapshots \
    --owner-ids 012345678910 \
    --query "Snapshots[?(StartTime<='2020-03-31')].[SnapshotId]"
```
フィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[リソースの一覧表示とフィルタリングの方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)」を参照してください。  
**例 5: アーカイブされたスナップショットのみを表示するには**  
次の `describe-snapshots` の例では、アーカイブ階層に保存されたスナップショットのみを説明しています。  

```
aws ec2 describe-snapshots \
    --filters "Name=storage-tier,Values=archive"
```
出力:  

```
{
    "Snapshots": [
        {
            "Description": "Snap A",
            "Encrypted": false,
            "VolumeId": "vol-01234567890aaaaaa",
            "State": "completed",
            "VolumeSize": 8,
            "StartTime": "2021-09-07T21:00:00.000Z",
            "Progress": "100%",
            "OwnerId": "123456789012",
            "SnapshotId": "snap-01234567890aaaaaa",
            "StorageTier": "archive",
            "Tags": []
        },
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[アーカイブされたスナップショットを表示する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/working-with-snapshot-archiving.html#view-archived-snapshot)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-snapshots.html)」を参照してください。

### `describe-spot-datafeed-subscription`
<a name="ec2_DescribeSpotDatafeedSubscription_cli_2_topic"></a>

次のコード例は、`describe-spot-datafeed-subscription` を使用する方法を示しています。

**AWS CLI**  
**アカウントのスポットインスタンスデータフィードサブスクリプションを記述するには**  
このコマンド例では、アカウントのデータフィードを記述します。  
コマンド:  

```
aws ec2 describe-spot-datafeed-subscription
```
出力:  

```
{
    "SpotDatafeedSubscription": {
        "OwnerId": "123456789012",
        "Prefix": "spotdata",
        "Bucket": "amzn-s3-demo-bucket",
        "State": "Active"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSpotDatafeedSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-datafeed-subscription.html)」を参照してください。

### `describe-spot-fleet-instances`
<a name="ec2_DescribeSpotFleetInstances_cli_2_topic"></a>

次のコード例は、`describe-spot-fleet-instances` を使用する方法を示しています。

**AWS CLI**  
**スポットフリートに関連付けられたスポットインスタンスを記述するには**  
このコマンド例では、指定されたスポットフリートに関連付けられたスポットインスタンスを一覧表示します。  
コマンド:  

```
aws ec2 describe-spot-fleet-instances --spot-fleet-request-id sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
出力:  

```
{
  "ActiveInstances": [
      {
          "InstanceId": "i-1234567890abcdef0",
          "InstanceType": "m3.medium",
          "SpotInstanceRequestId": "sir-08b93456"
      },
      ...
  ],
  "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSpotFleetInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-fleet-instances.html)」を参照してください。

### `describe-spot-fleet-request-history`
<a name="ec2_DescribeSpotFleetRequestHistory_cli_2_topic"></a>

次のコード例は、`describe-spot-fleet-request-history` を使用する方法を示しています。

**AWS CLI**  
**スポットフリートの履歴を記述するには**  
このコマンド例では、指定された時刻から始まる、指定されたスポットフリートの履歴を返します。  
コマンド:  

```
aws ec2 describe-spot-fleet-request-history --spot-fleet-request-id sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE --start-time 2015-05-26T00:00:00Z
```
次の出力例は、スポットフリートの 2 つのスポットインスタンスの正常な起動を示しています。  
出力:  

```
{
  "HistoryRecords": [
      {
          "Timestamp": "2015-05-26T23:17:20.697Z",
          "EventInformation": {
              "EventSubType": "submitted"
          },
          "EventType": "fleetRequestChange"
      },
      {
          "Timestamp": "2015-05-26T23:17:20.873Z",
          "EventInformation": {
              "EventSubType": "active"
          },
          "EventType": "fleetRequestChange"
      },
      {
          "Timestamp": "2015-05-26T23:21:21.712Z",
          "EventInformation": {
              "InstanceId": "i-1234567890abcdef0",
              "EventSubType": "launched"
          },
          "EventType": "instanceChange"
      },
      {
          "Timestamp": "2015-05-26T23:21:21.816Z",
          "EventInformation": {
              "InstanceId": "i-1234567890abcdef1",
              "EventSubType": "launched"
          },
          "EventType": "instanceChange"
      }
  ],
  "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
  "NextToken": "CpHNsscimcV5oH7bSbub03CI2Qms5+ypNpNm+53MNlR0YcXAkp0xFlfKf91yVxSExmbtma3awYxMFzNA663ZskT0AHtJ6TCb2Z8bQC2EnZgyELbymtWPfpZ1ZbauVg+P+TfGlWxWWB/Vr5dk5d4LfdgA/DRAHUrYgxzrEXAMPLE=",
  "StartTime": "2015-05-26T00:00:00Z"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSpotFleetRequestHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-fleet-request-history.html)」を参照してください。

### `describe-spot-fleet-requests`
<a name="ec2_DescribeSpotFleetRequests_cli_2_topic"></a>

次のコード例は、`describe-spot-fleet-requests` を使用する方法を示しています。

**AWS CLI**  
**スポットフリートリクエストを記述するには**  
この例では、すべてのスポットフリートリクエストを記述します。  
コマンド:  

```
aws ec2 describe-spot-fleet-requests
```
出力:  

```
{
  "SpotFleetRequestConfigs": [
      {
          "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
          "SpotFleetRequestConfig": {
              "TargetCapacity": 20,
              "LaunchSpecifications": [
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "cc2.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  },
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "r3.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  }
              ],
              "SpotPrice": "0.05",
              "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role"
          },
          "SpotFleetRequestState": "active"
      },
      {
          "SpotFleetRequestId": "sfr-306341ed-9739-402e-881b-ce47bEXAMPLE",
          "SpotFleetRequestConfig": {
              "TargetCapacity": 20,
              "LaunchSpecifications": [
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-6e7f829e",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "m3.medium",
                      "ImageId": "ami-1a2b3c4d"
                  }
              ],
              "SpotPrice": "0.05",
              "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role"
          },
          "SpotFleetRequestState": "active"
      }
  ]
}
```
**スポットフリートリクエストを記述するには**  
この例では、指定されたスポットフリートリクエストを記述します。  
コマンド:  

```
aws ec2 describe-spot-fleet-requests --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
出力:  

```
{
  "SpotFleetRequestConfigs": [
      {
          "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE",
          "SpotFleetRequestConfig": {
              "TargetCapacity": 20,
              "LaunchSpecifications": [
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "cc2.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  },
                  {
                      "EbsOptimized": false,
                      "NetworkInterfaces": [
                          {
                              "SubnetId": "subnet-a61dafcf",
                              "DeviceIndex": 0,
                              "DeleteOnTermination": false,
                              "AssociatePublicIpAddress": true,
                              "SecondaryPrivateIpAddressCount": 0
                          }
                      ],
                      "InstanceType": "r3.8xlarge",
                      "ImageId": "ami-1a2b3c4d"
                  }
              ],
              "SpotPrice": "0.05",
              "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role"
          },
          "SpotFleetRequestState": "active"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSpotFleetRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-fleet-requests.html)」を参照してください。

### `describe-spot-instance-requests`
<a name="ec2_DescribeSpotInstanceRequests_cli_2_topic"></a>

次のコード例は、`describe-spot-instance-requests` を使用する方法を示しています。

**AWS CLI**  
**例 1: スポットインスタンスリクエストを記述するには**  
次の `describe-spot-instance-requests` の例では、指定したスポットインスタンスについて説明します。  

```
aws ec2 describe-spot-instance-requests \
    --spot-instance-request-ids sir-08b93456
```
出力:  

```
{
    "SpotInstanceRequests": [
        {
            "CreateTime": "2018-04-30T18:14:55.000Z",
            "InstanceId": "i-1234567890abcdef1",
            "LaunchSpecification": {
                "InstanceType": "t2.micro",
                "ImageId": "ami-003634241a8fcdec0",
                "KeyName": "my-key-pair",
                "SecurityGroups": [
                    {
                        "GroupName": "default",
                        "GroupId": "sg-e38f24a7"
                    }
                ],
                "BlockDeviceMappings": [
                    {
                        "DeviceName": "/dev/sda1",
                        "Ebs": {
                            "DeleteOnTermination": true,
                            "SnapshotId": "snap-0e54a519c999adbbd",
                            "VolumeSize": 8,
                            "VolumeType": "standard",
                            "Encrypted": false
                        }
                    }
                ],
                "NetworkInterfaces": [
                    {
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "SubnetId": "subnet-049df61146c4d7901"
                    }
                ],
                "Placement": {
                    "AvailabilityZone": "us-east-2b",
                    "Tenancy": "default"
                },
                "Monitoring": {
                    "Enabled": false
                }
            },
            "LaunchedAvailabilityZone": "us-east-2b",
            "ProductDescription": "Linux/UNIX",
            "SpotInstanceRequestId": "sir-08b93456",
            "SpotPrice": "0.010000"
            "State": "active",
            "Status": {
                "Code": "fulfilled",
                "Message": "Your Spot request is fulfilled.",
                "UpdateTime": "2018-04-30T18:16:21.000Z"
            },
            "Tags": [],
            "Type": "one-time",
            "InstanceInterruptionBehavior": "terminate"
        }
    ]
}
```
**例 2: フィルターに基づいてスポットインスタンスリクエストを記述するには**  
次の `describe-spot-instance-requests` の例では、フィルターを使用して、指定したアベイラビリティーゾーンにある指定したインスタントタイプを持つスポットインスタンスリクエストに結果の範囲を絞り込みます。この例では、`--query` パラメータを使用してインスタンス ID のみを表示します。  

```
aws ec2 describe-spot-instance-requests \
    --filters Name=launch.instance-type,Values=m3.medium Name=launched-availability-zone,Values=us-east-2a \
    --query "SpotInstanceRequests[*].[InstanceId]" \
    --output text
```
出力:  

```
i-057750d42936e468a
i-001efd250faaa6ffa
i-027552a73f021f3bd
...
```
フィルターの使用の詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[Listing and filtering your resources](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Filtering.html#Filtering_Resources_CLI)」を参照してください。  
**例 3: タグに基づいてスポットインスタンスリクエストを記述するには**  
次の `describe-spot-instance-requests` の例では、タグフィルターを使用して、タグ `cost-center=cc123` を含むスポットインスタンスリクエストに結果の範囲を絞り込みます。  

```
aws ec2 describe-spot-instance-requests \
    --filters Name=tag:cost-center,Values=cc123
```
`describe-spot-instance-requests` の出力例については、例 1 を参照してください。  
タグフィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[タグの使用方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSpotInstanceRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-instance-requests.html)」を参照してください。

### `describe-spot-price-history`
<a name="ec2_DescribeSpotPriceHistory_cli_2_topic"></a>

次のコード例は、`describe-spot-price-history` を使用する方法を示しています。

**AWS CLI**  
**スポット料金履歴を記述するには**  
このコマンド例では、1 月の特定の日について m1.xlarge インスタンスのスポット料金履歴を返します。  
コマンド:  

```
aws ec2 describe-spot-price-history --instance-types m1.xlarge --start-time 2014-01-06T07:08:09 --end-time 2014-01-06T08:09:10
```
出力:  

```
{
  "SpotPriceHistory": [
          {
              "Timestamp": "2014-01-06T07:10:55.000Z",
              "ProductDescription": "SUSE Linux",
              "InstanceType": "m1.xlarge",
              "SpotPrice": "0.087000",
              "AvailabilityZone": "us-west-1b"
          },
          {
              "Timestamp": "2014-01-06T07:10:55.000Z",
              "ProductDescription": "SUSE Linux",
              "InstanceType": "m1.xlarge",
              "SpotPrice": "0.087000",
              "AvailabilityZone": "us-west-1c"
          },
          {
              "Timestamp": "2014-01-06T05:42:36.000Z",
              "ProductDescription": "SUSE Linux (Amazon VPC)",
              "InstanceType": "m1.xlarge",
              "SpotPrice": "0.087000",
              "AvailabilityZone": "us-west-1a"
      },
      ...
}
```
**Linux/UNIX Amazon VPC のスポット料金履歴を記述するには**  
このコマンド例では、1 月の特定の日について m1.xlarge Linux/UNIX Amazon VPC インスタンスのスポット料金履歴を返します。  
コマンド:  

```
aws ec2 describe-spot-price-history --instance-types m1.xlarge --product-description "Linux/UNIX (Amazon VPC)" --start-time 2014-01-06T07:08:09 --end-time 2014-01-06T08:09:10
```
出力:  

```
{
  "SpotPriceHistory": [
      {
          "Timestamp": "2014-01-06T04:32:53.000Z",
          "ProductDescription": "Linux/UNIX (Amazon VPC)",
          "InstanceType": "m1.xlarge",
          "SpotPrice": "0.080000",
          "AvailabilityZone": "us-west-1a"
      },
      {
          "Timestamp": "2014-01-05T11:28:26.000Z",
          "ProductDescription": "Linux/UNIX (Amazon VPC)",
          "InstanceType": "m1.xlarge",
          "SpotPrice": "0.080000",
          "AvailabilityZone": "us-west-1c"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSpotPriceHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-spot-price-history.html)」を参照してください。

### `describe-stale-security-groups`
<a name="ec2_DescribeStaleSecurityGroups_cli_2_topic"></a>

次のコード例は、`describe-stale-security-groups` を使用する方法を示しています。

**AWS CLI**  
**古いセキュリティグループを記述するには**  
この例では、`vpc-11223344` の古いセキュリティグループのルールを記述します。応答は、アカウントの sg-5fa68d3a にピア VPC の `sg-279ab042` を参照する古い入力 SSH ルールがあること、ならびにアカウントの `sg-fe6fba9a` にピア VPC の `sg-ef6fba8b` を参照する古い出力 SSH ルールがあることを示します。  
コマンド:  

```
aws ec2 describe-stale-security-groups --vpc-id vpc-11223344
```
出力:  

```
{
  "StaleSecurityGroupSet": [
      {
          "VpcId": "vpc-11223344",
          "StaleIpPermissionsEgress": [
              {
                  "ToPort": 22,
                  "FromPort": 22,
                  "UserIdGroupPairs": [
                      {
                          "VpcId": "vpc-7a20e51f",
                          "GroupId": "sg-ef6fba8b",
                          "VpcPeeringConnectionId": "pcx-b04deed9",
                          "PeeringStatus": "active"
                      }
                  ],
                  "IpProtocol": "tcp"
              }
          ],
          "GroupName": "MySG1",
          "StaleIpPermissions": [],
          "GroupId": "sg-fe6fba9a",
          "Description": MySG1"
      },
      {
          "VpcId": "vpc-11223344",
          "StaleIpPermissionsEgress": [],
          "GroupName": "MySG2",
          "StaleIpPermissions": [
              {
                  "ToPort": 22,
                  "FromPort": 22,
                  "UserIdGroupPairs": [
                      {
                          "VpcId": "vpc-7a20e51f",
                          "GroupId": "sg-279ab042",
                          "Description": "Access from pcx-b04deed9",
                          "VpcPeeringConnectionId": "pcx-b04deed9",
                          "PeeringStatus": "active"
                      }
                  ],
                  "IpProtocol": "tcp"
              }
          ],
          "GroupId": "sg-5fa68d3a",
          "Description": "MySG2"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStaleSecurityGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-stale-security-groups.html)」を参照してください。

### `describe-store-image-tasks`
<a name="ec2_DescribeStoreImageTasks_cli_2_topic"></a>

次のコード例は、`describe-store-image-tasks` を使用する方法を示しています。

**AWS CLI**  
**AMI 保存タスクの進行状況を記述するには**  
次の `describe-store-image-tasks` の例では、AMI ストアタスクの進行状況について説明します。  

```
aws ec2 describe-store-image-tasks
```
出力:  

```
{
    "StoreImageTaskResults": [
        {
            "AmiId": "ami-1234567890abcdef0",
            "Bucket": "my-ami-bucket",
            "ProgressPercentage": 17,
            "S3objectKey": "ami-1234567890abcdef0.bin",
            "StoreTaskState": "InProgress",
            "StoreTaskFailureReason": null,
            "TaskStartTime": "2022-01-01T01:01:01.001Z"
        }
    ]
}
```
S3 を使用した AMI の保存と復元の詳細については、「*Amazon EC2 ユーザーガイド*」の「S3 を使用して AMI を保存および復元する <https://docs.aws.amazon.com/AWS EC2/latest/UserGuide /ami-store-restore.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStoreImageTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-store-image-tasks.html)」を参照してください。

### `describe-subnets`
<a name="ec2_DescribeSubnets_cli_2_topic"></a>

次のコード例は、`describe-subnets` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのサブネットを説明するには**  
次の `describe-subnets` の例では、サブネットの詳細を示します。  

```
aws ec2 describe-subnets
```
出力:  

```
{
    "Subnets": [
        {
            "AvailabilityZone": "us-east-1d",
            "AvailabilityZoneId": "use1-az2",
            "AvailableIpAddressCount": 4089,
            "CidrBlock": "172.31.80.0/20",
            "DefaultForAz": true,
            "MapPublicIpOnLaunch": false,
            "MapCustomerOwnedIpOnLaunch": true,
            "State": "available",
            "SubnetId": "subnet-0bb1c79de3EXAMPLE",
            "VpcId": "vpc-0ee975135dEXAMPLE",
            "OwnerId": "111122223333",
            "AssignIpv6AddressOnCreation": false,
            "Ipv6CidrBlockAssociationSet": [],
            "CustomerOwnedIpv4Pool:": 'pool-2EXAMPLE',
            "SubnetArn": "arn:aws:ec2:us-east-2:111122223333:subnet/subnet-0bb1c79de3EXAMPLE",
            "EnableDns64": false,
            "Ipv6Native": false,
            "PrivateDnsNameOptionsOnLaunch": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            }
        },
        {
            "AvailabilityZone": "us-east-1d",
            "AvailabilityZoneId": "use1-az2",
            "AvailableIpAddressCount": 4089,
            "CidrBlock": "172.31.80.0/20",
            "DefaultForAz": true,
            "MapPublicIpOnLaunch": true,
            "MapCustomerOwnedIpOnLaunch": false,
            "State": "available",
            "SubnetId": "subnet-8EXAMPLE",
            "VpcId": "vpc-3EXAMPLE",
            "OwnerId": "1111222233333",
            "AssignIpv6AddressOnCreation": false,
            "Ipv6CidrBlockAssociationSet": [],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "MySubnet"
                }
            ],
            "SubnetArn": "arn:aws:ec2:us-east-1:111122223333:subnet/subnet-8EXAMPLE",
            "EnableDns64": false,
            "Ipv6Native": false,
            "PrivateDnsNameOptionsOnLaunch": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            }
        }
    ]
}
```
詳細については、「*AWS VPC ユーザーガイド*」で [VPC とサブネットの使用方法](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html)を参照してください。  
**例 2: 特定の VPC のサブネットを説明するには**  
次の `describe-subnets` 例では、フィルターを使用して、指定した VPC のサブネットに関する詳細を取得します。  

```
aws ec2 describe-subnets \
    --filters "Name=vpc-id,Values=vpc-3EXAMPLE"
```
出力:  

```
{
    "Subnets": [
        {
            "AvailabilityZone": "us-east-1d",
            "AvailabilityZoneId": "use1-az2",
            "AvailableIpAddressCount": 4089,
            "CidrBlock": "172.31.80.0/20",
            "DefaultForAz": true,
            "MapPublicIpOnLaunch": true,
            "MapCustomerOwnedIpOnLaunch": false,
            "State": "available",
            "SubnetId": "subnet-8EXAMPLE",
            "VpcId": "vpc-3EXAMPLE",
            "OwnerId": "1111222233333",
            "AssignIpv6AddressOnCreation": false,
            "Ipv6CidrBlockAssociationSet": [],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "MySubnet"
                }
            ],
            "SubnetArn": "arn:aws:ec2:us-east-1:111122223333:subnet/subnet-8EXAMPLE",
            "EnableDns64": false,
            "Ipv6Native": false,
            "PrivateDnsNameOptionsOnLaunch": {
                "HostnameType": "ip-name",
                "EnableResourceNameDnsARecord": false,
                "EnableResourceNameDnsAAAARecord": false
            }
        }
    ]
}
```
詳細については、「*AWS VPC ユーザーガイド*」で [VPC とサブネットの使用方法](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html)を参照してください。  
**例 3: 特定のタグを持つサブネットを説明するには**  
次の `describe-subnets` の例では、フィルターを使用してタグ `CostCenter=123` 付きのサブネットの詳細を取得し、`--query` パラメータを使用してこのタグが付いたサブネットのサブネット ID を表示します。  

```
aws ec2 describe-subnets \
    --filters "Name=tag:CostCenter,Values=123" \
    --query "Subnets[*].SubnetId" \
    --output text
```
出力:  

```
subnet-0987a87c8b37348ef
subnet-02a95061c45f372ee
subnet-03f720e7de2788d73
```
詳細については、「*Amazon VPC ユーザーガイド*」で [VPC とサブネットの使用方法](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html)を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeSubnets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-subnets.html)」を参照してください。

### `describe-tags`
<a name="ec2_DescribeTags_cli_2_topic"></a>

次のコード例は、`describe-tags` を使用する方法を示しています。

**AWS CLI**  
**例 1: 1 つのリソースのタグをすべて記述するには**  
次の `describe-tags` の例では、指定したインスタンスのタグについて説明します。  

```
aws ec2 describe-tags \
    --filters "Name=resource-id,Values=i-1234567890abcdef8"
```
出力:  

```
{
    "Tags": [
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Test",
            "Key": "Stack"
        },
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Beta Server",
            "Key": "Name"
        }
    ]
}
```
**例 2: リソースタイプのタグをすべて記述するには**  
次の `describe-tags` の例では、ボリュームのタグについて説明します。  

```
aws ec2 describe-tags \
    --filters "Name=resource-type,Values=volume"
```
出力:  

```
{
    "Tags": [
        {
            "ResourceType": "volume",
            "ResourceId": "vol-1234567890abcdef0",
            "Value": "Project1",
            "Key": "Purpose"
        },
        {
            "ResourceType": "volume",
            "ResourceId": "vol-049df61146c4d7901",
            "Value": "Logs",
            "Key": "Purpose"
        }
    ]
}
```
**例 3: タグをすべて記述するには**  
次の `describe-tags` の例では、リソースのタグについて説明します。  

```
aws ec2 describe-tags
```
**例 4: タグキーに基づいてリソースのタグを記述するには**  
次の `describe-tags` の例では、キー `Stack` を持つタグのあるリソースのタグについて説明します。  

```
aws ec2 describe-tags \
    --filters Name=key,Values=Stack
```
出力:  

```
{
    "Tags": [
        {
            "ResourceType": "volume",
            "ResourceId": "vol-027552a73f021f3b",
            "Value": "Production",
            "Key": "Stack"
        },
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Test",
            "Key": "Stack"
        }
    ]
}
```
**例 5: タグキーとタグ値に基づいてリソースのタグを記述するには**  
次の `describe-tags` の例では、タグ `Stack=Test` のあるリソースのタグについて説明します。  

```
aws ec2 describe-tags \
    --filters Name=key,Values=Stack Name=value,Values=Test
```
出力:  

```
{
    "Tags": [
        {
            "ResourceType": "image",
            "ResourceId": "ami-3ac336533f021f3bd",
            "Value": "Test",
            "Key": "Stack"
        },
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef8",
            "Value": "Test",
            "Key": "Stack"
        }
    ]
}
```
次の `describe-tags` の例では、代替構文を使用して、タグ `Stack=Test` を持つリソースについて説明します。  

```
aws ec2 describe-tags \
    --filters "Name=tag:Stack,Values=Test"
```
次の `describe-tags` の例では、キー `Purpose` を持つものの値を持っていないタグのある、すべてのインスタンスのタグについて説明します。  

```
aws ec2 describe-tags \
    --filters "Name=resource-type,Values=instance" "Name=key,Values=Purpose" "Name=value,Values="
```
出力:  

```
{
    "Tags": [
        {
            "ResourceType": "instance",
            "ResourceId": "i-1234567890abcdef5",
            "Value": null,
            "Key": "Purpose"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-tags.html)」を参照してください。

### `describe-traffic-mirror-filters`
<a name="ec2_DescribeTrafficMirrorFilters_cli_2_topic"></a>

次のコード例は、`describe-traffic-mirror-filters` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーフィルターを表示するには**  
次の `describe-traffic-mirror-filters` の例では、すべてのトラフィックミラーフィルターについて説明します。  

```
aws ec2 describe-traffic-mirror-filters
```
出力:  

```
{
    "TrafficMirrorFilters": [
        {
            "TrafficMirrorFilterId": "tmf-0293f26e86EXAMPLE",
            "IngressFilterRules": [
                {
                    "TrafficMirrorFilterRuleId": "tmfr-0ca76e0e08EXAMPLE",
                    "TrafficMirrorFilterId": "tmf-0293f26e86EXAMPLE",
                    "TrafficDirection": "ingress",
                    "RuleNumber": 100,
                    "RuleAction": "accept",
                    "Protocol": 6,
                    "DestinationCidrBlock": "10.0.0.0/24",
                    "SourceCidrBlock": "10.0.0.0/24",
                    "Description": "TCP Rule"
                }
            ],
            "EgressFilterRules": [],
            "NetworkServices": [],
            "Description": "Example filter",
            "Tags": []
        }
    ]
}
```
詳細については、「* トラフィックミラーリングガイド*」の「[View your traffic mirror filters](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-filter.html#view-traffic-mirroring-filter)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrafficMirrorFilters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-traffic-mirror-filters.html)」を参照してください。

### `describe-traffic-mirror-sessions`
<a name="ec2_DescribeTrafficMirrorSessions_cli_2_topic"></a>

次のコード例は、`describe-traffic-mirror-sessions` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーセッションを記述するには**  
次の `describe-traffic-mirror-sessions` の例では、トラフィックミラーセッションの詳細について説明します。  

```
aws ec2 describe-traffic-mirror-sessions
```
出力:  

```
{
    "TrafficMirrorSessions": [
        {
            "Tags": [],
            "VirtualNetworkId": 42,
            "OwnerId": "111122223333",
            "Description": "TCP Session",
            "NetworkInterfaceId": "eni-0a471a5cf3EXAMPLE",
            "TrafficMirrorTargetId": "tmt-0dabe9b0a6EXAMPLE",
            "TrafficMirrorFilterId": "tmf-083e18f985EXAMPLE",
            "PacketLength": 20,
            "SessionNumber": 1,
            "TrafficMirrorSessionId": "tms-0567a4c684EXAMPLE"
        },
        {
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "tag test"
                }
            ],
            "VirtualNetworkId": 13314501,
            "OwnerId": "111122223333",
            "Description": "TCP Session",
            "NetworkInterfaceId": "eni-0a471a5cf3EXAMPLE",
            "TrafficMirrorTargetId": "tmt-03665551cbEXAMPLE",
            "TrafficMirrorFilterId": "tmf-06c787846cEXAMPLE",
            "SessionNumber": 2,
            "TrafficMirrorSessionId": "tms-0060101cf8EXAMPLE"
        }
    ]
}
```
詳細については、「*AWS トラフィックミラーリングガイド*」の「[View Traffic Mirror Session Details](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-session.html#view-traffic-mirroring-session)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrafficMirrorSessions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-traffic-mirror-sessions.html)」を参照してください。

### `describe-traffic-mirror-targets`
<a name="ec2_DescribeTrafficMirrorTargets_cli_2_topic"></a>

次のコード例は、`describe-traffic-mirror-targets` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーターゲットを記述するには**  
次の `describe-traffic-mirror-targets` の例では、指定したトラフィックミラーターゲットの情報を表示します。  

```
aws ec2 describe-traffic-mirror-targets \
    --traffic-mirror-target-ids tmt-0dabe9b0a6EXAMPLE
```
出力:  

```
{
    "TrafficMirrorTargets": [
        {
            "TrafficMirrorTargetId": "tmt-0dabe9b0a6EXAMPLE",
            "NetworkLoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:111122223333:loadbalancer/net/NLB/7cdec873fEXAMPLE",
            "Type": "network-load-balancer",
            "Description": "Example Network Load Balancer target",
            "OwnerId": "111122223333",
            "Tags": []
        }
    ]
}
```
詳細については、「*Amazon VPC トラフィックミラーリングガイド*」の「[Traffic mirror targets](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-target.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrafficMirrorTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-traffic-mirror-targets.html)」を参照してください。

### `describe-transit-gateway-attachments`
<a name="ec2_DescribeTransitGatewayAttachments_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-attachments` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway アタッチメントを表示するには**  
次の `describe-transit-gateway-attachments` の例では、Transit Gateway アタッチメントの詳細を表示します。  

```
aws ec2 describe-transit-gateway-attachments
```
出力:  

```
{
    "TransitGatewayAttachments": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-01f8100bc7EXAMPLE",
            "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
            "TransitGatewayOwnerId": "123456789012",
            "ResourceOwnerId": "123456789012",
            "ResourceType": "vpc",
            "ResourceId": "vpc-3EXAMPLE",
            "State": "available",
            "Association": {
                "TransitGatewayRouteTableId": "tgw-rtb-002573ed1eEXAMPLE",
                "State": "associated"
            },
            "CreationTime": "2019-08-26T14:59:25.000Z",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Example"
                }
            ]
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-0b5968d3b6EXAMPLE",
            "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
            "TransitGatewayOwnerId": "123456789012",
            "ResourceOwnerId": "123456789012",
            "ResourceType": "vpc",
            "ResourceId": "vpc-0065acced4EXAMPLE",
            "State": "available",
            "Association": {
                "TransitGatewayRouteTableId": "tgw-rtb-002573ed1eEXAMPLE",
                "State": "associated"
            },
            "CreationTime": "2019-08-07T17:03:07.000Z",
            "Tags": []
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-08e0bc912cEXAMPLE",
            "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
            "TransitGatewayOwnerId": "123456789012",
            "ResourceOwnerId": "123456789012",
            "ResourceType": "direct-connect-gateway",
            "ResourceId": "11460968-4ac1-4fd3-bdb2-00599EXAMPLE",
            "State": "available",
            "Association": {
                "TransitGatewayRouteTableId": "tgw-rtb-002573ed1eEXAMPLE",
                "State": "associated"
            },
            "CreationTime": "2019-08-14T20:27:44.000Z",
            "Tags": []
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-0a89069f57EXAMPLE",
            "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
            "TransitGatewayOwnerId": "123456789012",
            "ResourceOwnerId": "123456789012",
            "ResourceType": "direct-connect-gateway",
            "ResourceId": "8384da05-13ce-4a91-aada-5a1baEXAMPLE",
            "State": "available",
            "Association": {
                "TransitGatewayRouteTableId": "tgw-rtb-002573ed1eEXAMPLE",
                "State": "associated"
            },
            "CreationTime": "2019-08-14T20:33:02.000Z",
            "Tags": []
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Work with transit gateways](https://docs.aws.amazon.com/vpc/latest/tgw/working-with-transit-gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayAttachments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-attachments.html)」を参照してください。

### `describe-transit-gateway-connect-peers`
<a name="ec2_DescribeTransitGatewayConnectPeers_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-connect-peers` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway Connect ピアを記述するには**  
次の `describe-transit-gateway-connect-peers` の例では、指定した Connect ピアについて説明します。  

```
aws ec2 describe-transit-gateway-connect-peers \
    --transit-gateway-connect-peer-ids tgw-connect-peer-0666adbac4EXAMPLE
```
出力:  

```
{
    "TransitGatewayConnectPeers": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-0f0927767cEXAMPLE",
            "TransitGatewayConnectPeerId": "tgw-connect-peer-0666adbac4EXAMPLE",
            "State": "available",
            "CreationTime": "2021-10-13T03:35:17.000Z",
            "ConnectPeerConfiguration": {
                "TransitGatewayAddress": "10.0.0.234",
                "PeerAddress": "172.31.1.11",
                "InsideCidrBlocks": [
                    "169.254.6.0/29"
                ],
                "Protocol": "gre",
                "BgpConfigurations": [
                    {
                        "TransitGatewayAsn": 64512,
                        "PeerAsn": 64512,
                        "TransitGatewayAddress": "169.254.6.2",
                        "PeerAddress": "169.254.6.1",
                        "BgpStatus": "down"
                    },
                    {
                        "TransitGatewayAsn": 64512,
                        "PeerAsn": 64512,
                        "TransitGatewayAddress": "169.254.6.3",
                        "PeerAddress": "169.254.6.1",
                        "BgpStatus": "down"
                    }
                ]
            },
            "Tags": []
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway Connect attachments and Transit Gateway Connect peers](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayConnectPeers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-connect-peers.html)」を参照してください。

### `describe-transit-gateway-connects`
<a name="ec2_DescribeTransitGatewayConnects_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-connects` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway Connect アタッチメントを記述するには**  
次の `describe-transit-gateway-connects` の例では、指定した Connect アタッチメントについて説明します。  

```
aws ec2 describe-transit-gateway-connects \
    --transit-gateway-attachment-ids tgw-attach-037012e5dcEXAMPLE
```
出力:  

```
{
    "TransitGatewayConnects": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-037012e5dcEXAMPLE",
            "TransportTransitGatewayAttachmentId": "tgw-attach-0a89069f57EXAMPLE",
            "TransitGatewayId": "tgw-02f776b1a7EXAMPLE",
            "State": "available",
            "CreationTime": "2021-03-09T19:59:17+00:00",
            "Options": {
                "Protocol": "gre"
            },
            "Tags": []
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway Connect attachments and Transit Gateway Connect peers](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayConnects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-connects.html)」を参照してください。

### `describe-transit-gateway-multicast-domains`
<a name="ec2_DescribeTransitGatewayMulticastDomains_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-multicast-domains` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway マルチキャストドメインを記述するには**  
次の `describe-transit-gateway-multicast-domains` の例では、すべての Transit Gateway マルチキャストドメインの詳細を表示します。  

```
aws ec2 describe-transit-gateway-multicast-domains
```
出力:  

```
{

    "TransitGatewayMulticastDomains": [
        {
            "TransitGatewayMulticastDomainId": "tgw-mcast-domain-000fb24d04EXAMPLE",
            "TransitGatewayId": "tgw-0bf0bffefaEXAMPLE",
            "TransitGatewayMulticastDomainArn": "arn:aws:ec2:us-east-1:123456789012:transit-gateway-multicast-domain/tgw-mcast-domain-000fb24d04EXAMPLE",
            "OwnerId": "123456789012",
            "Options": {
                "Igmpv2Support": "disable",
                "StaticSourcesSupport": "enable",
                "AutoAcceptSharedAssociations": "disable"
            },
            "State": "available",
            "CreationTime": "2019-12-10T18:32:50+00:00",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "mc1"
                }
            ]
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Managing multicast domains](https://docs.aws.amazon.com/vpc/latest/tgw/manage-domain.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayMulticastDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-multicast-domains.html)」を参照してください。

### `describe-transit-gateway-peering-attachments`
<a name="ec2_DescribeTransitGatewayPeeringAttachments_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-peering-attachments` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ピアリングアタッチメントを記述するには**  
次の `describe-transit-gateway-peering-attachments` の例では、すべての Transit Gateway ピアリングアタッチメントの詳細を表示します。  

```
aws ec2 describe-transit-gateway-peering-attachments
```
出力:  

```
{
    "TransitGatewayPeeringAttachments": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-4455667788aabbccd",
            "RequesterTgwInfo": {
                "TransitGatewayId": "tgw-123abc05e04123abc",
                "OwnerId": "123456789012",
                "Region": "us-west-2"
            },
            "AccepterTgwInfo": {
                "TransitGatewayId": "tgw-11223344aabbcc112",
                "OwnerId": "123456789012",
                "Region": "us-east-2"
            },
            "State": "pendingAcceptance",
            "CreationTime": "2019-12-09T11:38:05.000Z",
            "Tags": []
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit Gateway Peering Attachments](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayPeeringAttachments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-peering-attachments.html)」を参照してください。

### `describe-transit-gateway-policy-tables`
<a name="ec2_DescribeTransitGatewayPolicyTables_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-policy-tables` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ポリシーテーブルを記述するには**  
次の `describe-transit-gateway-policy-tables` の例では、指定した Transit Gateway ポリシーテーブルについて説明します。  

```
aws ec2 describe-transit-gateway-policy-tables \
    --transit-gateway-policy-table-ids tgw-ptb-0a16f134b78668a81
```
出力:  

```
{
    "TransitGatewayPolicyTables": [
        {
            "TransitGatewayPolicyTableId": "tgw-ptb-0a16f134b78668a81",
            "TransitGatewayId": "tgw-067f8505c18f0bd6e",
            "State": "available",
            "CreationTime": "2023-11-28T16:36:43+00:00",
            "Tags": []
        }
    ]
}
```
詳細については、「*Transit Gateway ユーザーガイド*」の「[Transit gateway policy tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-policy-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayPolicyTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-policy-tables.html)」を参照してください。

### `describe-transit-gateway-route-tables`
<a name="ec2_DescribeTransitGatewayRouteTables_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-route-tables` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ルートテーブルを記述するには**  
次の `describe-transit-gateway-route-tables` の例では、Transit Gateway ルートテーブルの詳細を表示します。  

```
aws ec2 describe-transit-gateway-route-tables
```
出力:  

```
{
    "TransitGatewayRouteTables": [
        {
            "TransitGatewayRouteTableId": "tgw-rtb-0ca78a549EXAMPLE",
            "TransitGatewayId": "tgw-0bc994abffEXAMPLE",
            "State": "available",
            "DefaultAssociationRouteTable": true,
            "DefaultPropagationRouteTable": true,
            "CreationTime": "2018-11-28T14:24:49.000Z",
            "Tags": []
        },
        {
            "TransitGatewayRouteTableId": "tgw-rtb-0e8f48f148EXAMPLE",
            "TransitGatewayId": "tgw-0043d72bb4EXAMPLE",
            "State": "available",
            "DefaultAssociationRouteTable": true,
            "DefaultPropagationRouteTable": true,
            "CreationTime": "2018-11-28T14:24:00.000Z",
            "Tags": []
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[View transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#view-tgw-route-tables)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayRouteTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-route-tables.html)」を参照してください。

### `describe-transit-gateway-vpc-attachments`
<a name="ec2_DescribeTransitGatewayVpcAttachments_cli_2_topic"></a>

次のコード例は、`describe-transit-gateway-vpc-attachments` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway VPC アタッチメントを記述するには**  
次の `describe-transit-gateway-vpc-attachments` の例では、Transit Gateway VPC アタッチメントの詳細を表示します。  

```
aws ec2 describe-transit-gateway-vpc-attachments
```
出力:  

```
{
    "TransitGatewayVpcAttachments": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-0a08e88308EXAMPLE",
            "TransitGatewayId": "tgw-0043d72bb4EXAMPLE",
            "VpcId": "vpc-0f501f7ee8EXAMPLE",
            "VpcOwnerId": "111122223333",
            "State": "available",
            "SubnetIds": [
                "subnet-045d586432EXAMPLE",
                "subnet-0a0ad478a6EXAMPLE"
            ],
            "CreationTime": "2019-02-13T11:04:02.000Z",
            "Options": {
                "DnsSupport": "enable",
                "Ipv6Support": "disable"
            },
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "attachment name"
                }
            ]
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[View your VPC attachments](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#view-vpc-attachment)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGatewayVpcAttachments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateway-vpc-attachments.html)」を参照してください。

### `describe-transit-gateways`
<a name="ec2_DescribeTransitGateways_cli_2_topic"></a>

次のコード例は、`describe-transit-gateways` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway を記述するには**  
次の `describe-transit-gateways` の例では、Transit Gateway の詳細を取得します。  

```
aws ec2 describe-transit-gateways
```
出力:  

```
{
    "TransitGateways": [
        {
            "TransitGatewayId": "tgw-0262a0e521EXAMPLE",
            "TransitGatewayArn": "arn:aws:ec2:us-east-2:111122223333:transit-gateway/tgw-0262a0e521EXAMPLE",
            "State": "available",
            "OwnerId": "111122223333",
            "Description": "MyTGW",
            "CreationTime": "2019-07-10T14:02:12.000Z",
            "Options": {
                "AmazonSideAsn": 64516,
                "AutoAcceptSharedAttachments": "enable",
                "DefaultRouteTableAssociation": "enable",
                "AssociationDefaultRouteTableId": "tgw-rtb-018774adf3EXAMPLE",
                "DefaultRouteTablePropagation": "enable",
                "PropagationDefaultRouteTableId": "tgw-rtb-018774adf3EXAMPLE",
                "VpnEcmpSupport": "enable",
                "DnsSupport": "enable"
            },
            "Tags": []
        },
        {
            "TransitGatewayId": "tgw-0fb8421e2dEXAMPLE",
            "TransitGatewayArn": "arn:aws:ec2:us-east-2:111122223333:transit-gateway/tgw-0fb8421e2da853bf3",
            "State": "available",
            "OwnerId": "111122223333",
            "CreationTime": "2019-03-15T22:57:33.000Z",
            "Options": {
                "AmazonSideAsn": 65412,
                "AutoAcceptSharedAttachments": "disable",
                "DefaultRouteTableAssociation": "enable",
                "AssociationDefaultRouteTableId": "tgw-rtb-06a241a3d8EXAMPLE",
                "DefaultRouteTablePropagation": "enable",
                "PropagationDefaultRouteTableId": "tgw-rtb-06a241a3d8EXAMPLE",
                "VpnEcmpSupport": "enable",
                "DnsSupport": "enable"
            },
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "TGW1"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransitGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-transit-gateways.html)」を参照してください。

### `describe-verified-access-endpoints`
<a name="ec2_DescribeVerifiedAccessEndpoints_cli_2_topic"></a>

次のコード例は、`describe-verified-access-endpoints` を使用する方法を示しています。

**AWS CLI**  
**Verified Access エンドポイントを記述するには**  
次の `describe-verified-access-endpoints` の例では、指定した Verified Access エンドポイントについて説明します。  

```
aws ec2 describe-verified-access-endpoints \
    --verified-access-endpoint-ids vae-066fac616d4d546f2
```
出力:  

```
{
    "VerifiedAccessEndpoints": [
        {
            "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
            "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
            "VerifiedAccessEndpointId": "vae-066fac616d4d546f2",
            "ApplicationDomain": "example.com",
            "EndpointType": "network-interface",
            "AttachmentType": "vpc",
            "DomainCertificateArn": "arn:aws:acm:us-east-2:123456789012:certificate/eb065ea0-26f9-4e75-a6ce-0a1a7EXAMPLE",
            "EndpointDomain": "my-ava-app.edge-00c3372d53b1540bb.vai-0ce000c0b7643abea.prod.verified-access.us-east-2.amazonaws.com",
            "SecurityGroupIds": [
                "sg-004915970c4c8f13a"
            ],
            "NetworkInterfaceOptions": {
                "NetworkInterfaceId": "eni-0aec70418c8d87a0f",
                "Protocol": "https",
                "Port": 443
            },
            "Status": {
                "Code": "active"
            },
            "Description": "",
            "CreationTime": "2023-08-25T20:54:43",
            "LastUpdatedTime": "2023-08-25T22:17:26",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-va-endpoint"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access endpoints](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVerifiedAccessEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-verified-access-endpoints.html)」を参照してください。

### `describe-verified-access-groups`
<a name="ec2_DescribeVerifiedAccessGroups_cli_2_topic"></a>

次のコード例は、`describe-verified-access-groups` を使用する方法を示しています。

**AWS CLI**  
**Verified Access グループを記述するには**  
次の `describe-verified-access-groups` の例では、指定した Verified Access グループについて説明します。  

```
aws ec2 describe-verified-access-groups \
    --verified-access-group-ids vagr-0dbe967baf14b7235
```
出力:  

```
{
    "VerifiedAccessGroups": [
        {
            "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
            "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
            "Description": "Testing Verified Access",
            "Owner": "123456789012",
            "VerifiedAccessGroupArn": "arn:aws:ec2:us-east-2:123456789012:verified-access-group/vagr-0dbe967baf14b7235",
            "CreationTime": "2023-08-25T19:55:19",
            "LastUpdatedTime": "2023-08-25T22:17:25",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-va-group"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access groups](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVerifiedAccessGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-verified-access-groups.html)」を参照してください。

### `describe-verified-access-instance-logging-configurations`
<a name="ec2_DescribeVerifiedAccessInstanceLoggingConfigurations_cli_2_topic"></a>

次のコード例は、`describe-verified-access-instance-logging-configurations` を使用する方法を示しています。

**AWS CLI**  
**Verified Access インスタンスに関するログ設定を記述するには**  
次の `describe-verified-access-instance-logging-configurations` の例では、指定した Verified Access インスタンスのログ記録設定について説明します。  

```
aws ec2 describe-verified-access-instance-logging-configurations \
    --verified-access-instance-ids vai-0ce000c0b7643abea
```
出力:  

```
{
    "LoggingConfigurations": [
        {
            "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
            "AccessLogs": {
                "S3": {
                    "Enabled": false
                },
                "CloudWatchLogs": {
                    "Enabled": true,
                    "DeliveryStatus": {
                        "Code": "success"
                    },
                    "LogGroup": "my-log-group"
                },
                "KinesisDataFirehose": {
                    "Enabled": false
                },
                "LogVersion": "ocsf-1.0.0-rc.2",
                "IncludeTrustContext": false
            }
        }
    ]
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access logs](https://docs.aws.amazon.com/verified-access/latest/ug/access-logs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVerifiedAccessInstanceLoggingConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-verified-access-instance-logging-configurations.html)」を参照してください。

### `describe-verified-access-instances`
<a name="ec2_DescribeVerifiedAccessInstances_cli_2_topic"></a>

次のコード例は、`describe-verified-access-instances` を使用する方法を示しています。

**AWS CLI**  
**Verified Access インスタンスを記述するには**  
次の `describe-verified-access-instances` の例では、指定した Verified Access インスタンスについて説明します。  

```
aws ec2 describe-verified-access-instances \
    --verified-access-instance-ids vai-0ce000c0b7643abea
```
出力:  

```
{
    "VerifiedAccessInstances": [
        {
            "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
            "Description": "Testing Verified Access",
            "VerifiedAccessTrustProviders": [
                {
                    "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
                    "TrustProviderType": "user",
                    "UserTrustProviderType": "iam-identity-center"
                }
            ],
            "CreationTime": "2023-08-25T18:27:56",
            "LastUpdatedTime": "2023-08-25T19:03:32",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-ava-instance"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Access インスタンス](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVerifiedAccessInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-verified-access-instances.html)」を参照してください。

### `describe-verified-access-trust-providers`
<a name="ec2_DescribeVerifiedAccessTrustProviders_cli_2_topic"></a>

次のコード例は、`describe-verified-access-trust-providers` を使用する方法を示しています。

**AWS CLI**  
**Verified Access 信頼プロバイダーを記述するには**  
次の `describe-verified-access-trust-providers` の例では、指定した Verified Access 信頼プロバイダーについて説明します。  

```
aws ec2 describe-verified-access-trust-providers \
    --verified-access-trust-provider-ids vatp-0bb32de759a3e19e7
```
出力:  

```
{
    "VerifiedAccessTrustProviders": [
        {
            "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
            "Description": "Testing Verified Access",
            "TrustProviderType": "user",
            "UserTrustProviderType": "iam-identity-center",
            "PolicyReferenceName": "idc",
            "CreationTime": "2023-08-25T19:00:38",
            "LastUpdatedTime": "2023-08-25T19:03:32",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-va-trust-provider"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Trust providers for Verified Access](https://docs.aws.amazon.com/verified-access/latest/ug/trust-providers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVerifiedAccessTrustProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-verified-access-trust-providers.html)」を参照してください。

### `describe-volume-attribute`
<a name="ec2_DescribeVolumeAttribute_cli_2_topic"></a>

次のコード例は、`describe-volume-attribute` を使用する方法を示しています。

**AWS CLI**  
**ボリューム属性を記述するには**  
このコマンド例では、ID `vol-049df61146c4d7901` を持つボリュームの `autoEnableIo` 属性を記述します。  
コマンド:  

```
aws ec2 describe-volume-attribute --volume-id vol-049df61146c4d7901 --attribute autoEnableIO
```
出力:  

```
{
    "AutoEnableIO": {
        "Value": false
    },
    "VolumeId": "vol-049df61146c4d7901"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVolumeAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-volume-attribute.html)」を参照してください。

### `describe-volume-status`
<a name="ec2_DescribeVolumeStatus_cli_2_topic"></a>

次のコード例は、`describe-volume-status` を使用する方法を示しています。

**AWS CLI**  
**単一ボリュームのステータスを記述するには**  
このコマンド例では、ボリューム `vol-1234567890abcdef0` のステータスを記述します。  
コマンド:  

```
aws ec2 describe-volume-status --volume-ids vol-1234567890abcdef0
```
出力:  

```
{
    "VolumeStatuses": [
        {
            "VolumeStatus": {
                "Status": "ok",
                "Details": [
                    {
                        "Status": "passed",
                        "Name": "io-enabled"
                    },
                    {
                        "Status": "not-applicable",
                        "Name": "io-performance"
                    }
                ]
            },
            "AvailabilityZone": "us-east-1a",
            "VolumeId": "vol-1234567890abcdef0",
            "Actions": [],
            "Events": []
        }
    ]
}
```
**障害のあるボリュームのステータスを記述するには**  
このコマンド例では、障害のあるすべてのボリュームのステータスを記述します。この例では、障害のあるボリュームはありません。  
コマンド:  

```
aws ec2 describe-volume-status --filters Name=volume-status.status,Values=impaired
```
出力:  

```
{
    "VolumeStatuses": []
}
```
ステータスチェックに失敗したボリュームがある場合 (ステータスに障害がある場合)、「*Amazon EC2 ユーザーガイド*」の「Working with an Impaired Volume」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVolumeStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-volume-status.html)」を参照してください。

### `describe-volumes-modifications`
<a name="ec2_DescribeVolumesModifications_cli_2_topic"></a>

次のコード例は、`describe-volumes-modifications` を使用する方法を示しています。

**AWS CLI**  
**ボリュームの変更ステータスを記述するには**  
次の `describe-volumes-modifications` の例では、指定したボリュームのボリューム変更ステータスについて説明します。  

```
aws ec2 describe-volumes-modifications \
    --volume-ids vol-1234567890abcdef0
```
出力:  

```
{
    "VolumeModification": {
        "TargetSize": 150,
        "TargetVolumeType": "io1",
        "ModificationState": "optimizing",
        "VolumeId": " vol-1234567890abcdef0",
        "TargetIops": 100,
        "StartTime": "2019-05-17T11:27:19.000Z",
        "Progress": 70,
        "OriginalVolumeType": "io1",
        "OriginalIops": 100,
        "OriginalSize": 100
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVolumesModifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-volumes-modifications.html)」を参照してください。

### `describe-volumes`
<a name="ec2_DescribeVolumes_cli_2_topic"></a>

次のコード例は、`describe-volumes` を使用する方法を示しています。

**AWS CLI**  
**例 1: ボリュームを記述するには**  
次の `describe-volumes` の例では、現在のリージョンで指定したボリュームについて説明します。  

```
aws ec2 describe-volumes \
    --volume-ids vol-049df61146c4d7901 vol-1234567890abcdef0
```
出力:  

```
{
    "Volumes": [
        {
            "AvailabilityZone": "us-east-1a",
            "Attachments": [
                {
                    "AttachTime": "2013-12-18T22:35:00.000Z",
                    "InstanceId": "i-1234567890abcdef0",
                    "VolumeId": "vol-049df61146c4d7901",
                    "State": "attached",
                    "DeleteOnTermination": true,
                    "Device": "/dev/sda1"
                }
            ],
            "Encrypted": true,
            "KmsKeyId": "arn:aws:kms:us-east-2a:123456789012:key/8c5b2c63-b9bc-45a3-a87a-5513eEXAMPLE,
            "VolumeType": "gp2",
            "VolumeId": "vol-049df61146c4d7901",
            "State": "in-use",
            "Iops": 100,
            "SnapshotId": "snap-1234567890abcdef0",
            "CreateTime": "2019-12-18T22:35:00.084Z",
            "Size": 8
        },
        {
            "AvailabilityZone": "us-east-1a",
            "Attachments": [],
            "Encrypted": false,
            "VolumeType": "gp2",
            "VolumeId": "vol-1234567890abcdef0",
            "State": "available",
            "Iops": 300,
            "SnapshotId": "",
            "CreateTime": "2020-02-27T00:02:41.791Z",
            "Size": 100
        }
    ]
}
```
**例 2: 特定のインスタンスにアタッチされているボリュームを記述するには**  
次の `describe-volumes` の例では、指定したインスタンスにアタッチされているものと、インスタンスの終了時に削除するように設定されているものの両方に該当するすべてのボリュームについて説明します。  

```
aws ec2 describe-volumes \
    --region us-east-1 \
    --filters Name=attachment.instance-id,Values=i-1234567890abcdef0 Name=attachment.delete-on-termination,Values=true
```
`describe-volumes` の出力例については、例 1 を参照してください。  
**例 3: 特定のアベイラビリティーゾーンで使用可能なボリュームを記述するには**  
次の `describe-volumes` の例では、ステータスが `available` であり、指定したアベイラビリティーゾーンにあるすべてのボリュームについて説明します。  

```
aws ec2 describe-volumes \
    --filters Name=status,Values=available Name=availability-zone,Values=us-east-1a
```
`describe-volumes` の出力例については、例 1 を参照してください。  
**例 4: タグに基づいてボリュームを記述するには**  
次の `describe-volumes` の例では、タグキー `Name` を持ち、`Test` で始まる値を持つすべてのボリュームについて説明します。その後、出力は、ボリュームのタグと ID のみを表示するクエリでフィルタリングされます。  

```
aws ec2 describe-volumes \
    --filters Name=tag:Name,Values=Test* \
    --query "Volumes[*].{ID:VolumeId,Tag:Tags}"
```
出力:  

```
[
    {
       "Tag": [
           {
               "Value": "Test2",
               "Key": "Name"
           }
       ],
       "ID": "vol-1234567890abcdef0"
   },
   {
       "Tag": [
           {
               "Value": "Test1",
               "Key": "Name"
           }
       ],
       "ID": "vol-049df61146c4d7901"
    }
]
```
タグフィルターを使用するその他の例については、「*Amazon EC2 ユーザーガイド*」の「[タグの使用方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html#Using_Tags_CLI)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVolumes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-volumes.html)」を参照してください。

### `describe-vpc-attribute`
<a name="ec2_DescribeVpcAttribute_cli_2_topic"></a>

次のコード例は、`describe-vpc-attribute` を使用する方法を示しています。

**AWS CLI**  
**enableDnsSupport 属性を記述するには**  
この例では、`enableDnsSupport` 属性を記述します。この属性は、VPC に対して DNS 解決が有効になっているかどうかを示します。この属性が `true` の場合、Amazon DNS サーバーはインスタンスの DNS ホスト名を対応する IP アドレスに解決します。それ以外の場合は解決しません。  
コマンド:  

```
aws ec2 describe-vpc-attribute --vpc-id vpc-a01106c2 --attribute enableDnsSupport
```
出力:  

```
{
    "VpcId": "vpc-a01106c2",
    "EnableDnsSupport": {
        "Value": true
    }
}
```
**enableDnsHostnames 属性を記述するには**  
この例では、`enableDnsHostnames` 属性を記述します。この属性は、VPC 内に起動されるインスタンスが DNS ホスト名を取得するかどうかを示します。この属性が `true` の場合、VPC 内のインスタンスは DNS ホスト名を取得します。それ以外の場合は取得しません。  
コマンド:  

```
aws ec2 describe-vpc-attribute --vpc-id vpc-a01106c2 --attribute enableDnsHostnames
```
出力:  

```
{
    "VpcId": "vpc-a01106c2",
    "EnableDnsHostnames": {
        "Value": true
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-attribute.html)」を参照してください。

### `describe-vpc-classic-link-dns-support`
<a name="ec2_DescribeVpcClassicLinkDnsSupport_cli_2_topic"></a>

次のコード例は、`describe-vpc-classic-link-dns-support` を使用する方法を示しています。

**AWS CLI**  
**VPC の ClassicLink DNS サポートを記述するには**  
この例では、すべての VPC の ClassicLink DNS サポートステータスを記述します。  
コマンド:  

```
aws ec2 describe-vpc-classic-link-dns-support
```
出力:  

```
{
  "Vpcs": [
    {
      "VpcId": "vpc-88888888",
      "ClassicLinkDnsSupported": true
    },
    {
      "VpcId": "vpc-1a2b3c4d",
      "ClassicLinkDnsSupported": false
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcClassicLinkDnsSupport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-classic-link-dns-support.html)」を参照してください。

### `describe-vpc-classic-link`
<a name="ec2_DescribeVpcClassicLink_cli_2_topic"></a>

次のコード例は、`describe-vpc-classic-link` を使用する方法を示しています。

**AWS CLI**  
**VPC の ClassicLink ステータスを記述するには**  
この例では、vpc-88888888 の ClassicLink ステータスを一覧表示します。  
コマンド:  

```
aws ec2 describe-vpc-classic-link --vpc-id vpc-88888888
```
出力:  

```
{
  "Vpcs": [
    {
      "ClassicLinkEnabled": true,
      "VpcId": "vpc-88888888",
      "Tags": [
        {
          "Value": "classiclinkvpc",
          "Key": "Name"
        }
      ]
    }
  ]
}
```
この例では、Classiclink で有効になっている VPCs のみを一覧表示します (`is-classic-link-enabled` のフィルター値は `true` に設定されています)。  
コマンド:  

```
aws ec2 describe-vpc-classic-link --filter "Name=is-classic-link-enabled,Values=true"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcClassicLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-classic-link.html)」を参照してください。

### `describe-vpc-endpoint-associations`
<a name="ec2_DescribeVpcEndpointAssociations_cli_2_topic"></a>

次のコード例は、`describe-vpc-endpoint-associations` を使用する方法を示しています。

**AWS CLI**  
**VPC エンドポイントの関連付けを記述するには**  
次の `describe-vpc-endpoint-associations` の例では、VPC エンドポイントの関連付けを記述します。  

```
aws ec2 describe-vpc-endpoint-associations
```
出力:  

```
{
    "VpcEndpointAssociations": [
        {
            "Id": "vpce-rsc-asc-0a810ca6ac8866bf9",
            "VpcEndpointId": "vpce-019b90d6f16d4f958",
            "AssociatedResourceAccessibility": "Accessible",
            "DnsEntry": {
                "DnsName": "vpce-019b90d6f16d4f958.rcfg-07129f3acded87625.4232ccc.vpc-lattice-rsc.us-east-2.on.aws",
                "HostedZoneId": "Z03265862FOUNWMZOKUF4"
            },
            "AssociatedResourceArn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-07129f3acded87625"
        }
    ]
}
```
詳細については、「*AWS PrivateLink ユーザーガイド*」の「[VPC エンドポイントの関連付けを管理する](https://docs.aws.amazon.com/vpc/latest/privatelink/resource-configuration-associations.html#resource-config-manage-ep-association)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcEndpointAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoint-associations.html)」を参照してください。

### `describe-vpc-endpoint-connection-notifications`
<a name="ec2_DescribeVpcEndpointConnectionNotifications_cli_2_topic"></a>

次のコード例は、`describe-vpc-endpoint-connection-notifications` を使用する方法を示しています。

**AWS CLI**  
**エンドポイント接続通知を記述するには**  
次の `describe-vpc-endpoint-connection-notifications` の例では、すべてのエンドポイント接続通知について説明します。  

```
aws ec2 describe-vpc-endpoint-connection-notifications
```
出力:  

```
{
   "ConnectionNotificationSet": [
       {
           "ConnectionNotificationState": "Enabled",
           "ConnectionNotificationType": "Topic",
           "ConnectionEvents": [
               "Accept",
               "Reject",
               "Delete",
               "Connect"
           ],
           "ConnectionNotificationId": "vpce-nfn-04bcb952bc8af7abc",
           "ConnectionNotificationArn": "arn:aws:sns:us-east-1:123456789012:VpceNotification",
           "VpcEndpointId": "vpce-0324151a02f327123"
       }
   ]
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcEndpointConnectionNotifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoint-connection-notifications.html)」を参照してください。

### `describe-vpc-endpoint-connections`
<a name="ec2_DescribeVpcEndpointConnections_cli_2_topic"></a>

次のコード例は、`describe-vpc-endpoint-connections` を使用する方法を示しています。

**AWS CLI**  
**VPC エンドポイント接続を記述するには**  
この例では、エンドポイントサービスへのインターフェイスエンドポイント接続を記述し、結果をフィルタリングして `PendingAcceptance` であるエンドポイントを表示します。  
コマンド:  

```
aws ec2 describe-vpc-endpoint-connections --filters Name=vpc-endpoint-state,Values=pendingAcceptance
```
出力:  

```
{
  "VpcEndpointConnections": [
      {
          "VpcEndpointId": "vpce-0abed31004e618123",
          "ServiceId": "vpce-svc-0abced088d20def56",
          "CreationTimestamp": "2017-11-30T10:00:24.350Z",
          "VpcEndpointState": "pendingAcceptance",
          "VpcEndpointOwner": "123456789012"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcEndpointConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoint-connections.html)」を参照してください。

### `describe-vpc-endpoint-service-configurations`
<a name="ec2_DescribeVpcEndpointServiceConfigurations_cli_2_topic"></a>

次のコード例は、`describe-vpc-endpoint-service-configurations` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントサービス設定を記述するには**  
次の `describe-vpc-endpoint-service-configurations` の例では、エンドポイントサービスの設定について説明します。  

```
aws ec2 describe-vpc-endpoint-service-configurations
```
出力:  

```
{
    "ServiceConfigurations": [
        {
            "ServiceType": [
                {
                    "ServiceType": "GatewayLoadBalancer"
                }
            ],
            "ServiceId": "vpce-svc-012d33a1c4321cabc",
            "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-012d33a1c4321cabc",
            "ServiceState": "Available",
            "AvailabilityZones": [
                "us-east-1d"
            ],
            "AcceptanceRequired": false,
            "ManagesVpcEndpoints": false,
            "GatewayLoadBalancerArns": [
                "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/gwy/GWLBService/123210844e429123"
            ],
            "Tags": []
        },
        {
            "ServiceType": [
                {
                    "ServiceType": "Interface"
                }
            ],
            "ServiceId": "vpce-svc-123cabc125efa123",
            "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-123cabc125efa123",
            "ServiceState": "Available",
            "AvailabilityZones": [
                "us-east-1a"
            ],
            "AcceptanceRequired": true,
            "ManagesVpcEndpoints": false,
            "NetworkLoadBalancerArns": [
                "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/NLBforService/1238753950b25123"
            ],
            "BaseEndpointDnsNames": [
                "vpce-svc-123cabc125efa123.us-east-1.vpce.amazonaws.com"
            ],
            "PrivateDnsName": "example.com",
            "PrivateDnsNameConfiguration": {
                "State": "failed",
                "Type": "TXT",
                "Value": "vpce:qUAth3FdeABCApUiXabc",
                "Name": "_1d367jvbg34znqvyefrj"
            },
            "Tags": []
        }
    ]
}
```
詳細については、*AWS PrivateLink ユーザーガイド*の「[概念](https://docs.aws.amazon.com/vpc/latest/privatelink/concepts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcEndpointServiceConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoint-service-configurations.html)」を参照してください。

### `describe-vpc-endpoint-service-permissions`
<a name="ec2_DescribeVpcEndpointServicePermissions_cli_2_topic"></a>

次のコード例は、`describe-vpc-endpoint-service-permissions` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントサービスのアクセス許可を記述するには**  
この例では、指定されたエンドポイントサービスのアクセス許可を記述します。  
コマンド:  

```
aws ec2 describe-vpc-endpoint-service-permissions --service-id vpce-svc-03d5ebb7d9579a2b3
```
出力:  

```
{
   "AllowedPrincipals": [
       {
           "PrincipalType": "Account",
           "Principal": "arn:aws:iam::123456789012:root"
       }
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcEndpointServicePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoint-service-permissions.html)」を参照してください。

### `describe-vpc-endpoint-services`
<a name="ec2_DescribeVpcEndpointServices_cli_2_topic"></a>

次のコード例は、`describe-vpc-endpoint-services` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべての VPC エンドポイントサービスを記述するには**  
次の の`describe-vpc-endpoint-services`例では、 AWS リージョンのすべての VPC エンドポイントサービスを一覧表示します。  

```
aws ec2 describe-vpc-endpoint-services
```
出力:  

```
{
    "ServiceDetails": [
        {
            "ServiceType": [
                {
                    "ServiceType": "Gateway"
                }
            ],
            "AcceptanceRequired": false,
            "ServiceName": "com.amazonaws.us-east-1.dynamodb",
            "VpcEndpointPolicySupported": true,
            "Owner": "amazon",
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
                "us-east-1f"
            ],
            "BaseEndpointDnsNames": [
                "dynamodb.us-east-1.amazonaws.com"
            ]
        },
        {
            "ServiceType": [
                {
                    "ServiceType": "Interface"
                }
            ],
            "PrivateDnsName": "ec2.us-east-1.amazonaws.com",
            "ServiceName": "com.amazonaws.us-east-1.ec2",
            "VpcEndpointPolicySupported": false,
            "Owner": "amazon",
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
                "us-east-1f"
            ],
            "AcceptanceRequired": false,
            "BaseEndpointDnsNames": [
                "ec2.us-east-1.vpce.amazonaws.com"
            ]
        },
        {
            "ServiceType": [
                {
                    "ServiceType": "Interface"
                }
            ],
            "PrivateDnsName": "ssm.us-east-1.amazonaws.com",
            "ServiceName": "com.amazonaws.us-east-1.ssm",
            "VpcEndpointPolicySupported": true,
            "Owner": "amazon",
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e"
            ],
            "AcceptanceRequired": false,
            "BaseEndpointDnsNames": [
                "ssm.us-east-1.vpce.amazonaws.com"
            ]
        }
    ],
    "ServiceNames": [
        "com.amazonaws.us-east-1.dynamodb",
        "com.amazonaws.us-east-1.ec2",
        "com.amazonaws.us-east-1.ec2messages",
        "com.amazonaws.us-east-1.elasticloadbalancing",
        "com.amazonaws.us-east-1.kinesis-streams",
        "com.amazonaws.us-east-1.s3",
        "com.amazonaws.us-east-1.ssm"
    ]
}
```
**例 2: エンドポイントサービスの詳細を記述するには**  
次の `describe-vpc-endpoint-services` の例では、Amazon S3 インターフェイスエンドポイントサービスの詳細を一覧表示します。  

```
aws ec2 describe-vpc-endpoint-services \
    --filter 'Name=service-type,Values=Interface' Name=service-name,Values=com.amazonaws.us-east-1.s3
```
出力:  

```
{
    "ServiceDetails": [
        {
            "ServiceName": "com.amazonaws.us-east-1.s3",
            "ServiceId": "vpce-svc-081d84efcdEXAMPLE",
            "ServiceType": [
                {
                    "ServiceType": "Interface"
                }
            ],
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1c",
                "us-east-1d",
                "us-east-1e",
            "us-east-1f"
            ],
            "Owner": "amazon",
            "BaseEndpointDnsNames": [
                "s3.us-east-1.vpce.amazonaws.com"
            ],
            "VpcEndpointPolicySupported": true,
            "AcceptanceRequired": false,
            "ManagesVpcEndpoints": false,
            "Tags": []
        }
    ],
    "ServiceNames": [
        "com.amazonaws.us-east-1.s3"
    ]
}
```
詳細については、*AWS 「 PrivateLink ユーザーガイド*」の[「使用可能な AWS サービス名](https://docs.aws.amazon.com/vpc/latest/privatelink/aws-services-privatelink-support.html#vpce-view-available-services)を表示する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcEndpointServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoint-services.html)」を参照してください。

### `describe-vpc-endpoints`
<a name="ec2_DescribeVpcEndpoints_cli_2_topic"></a>

次のコード例は、`describe-vpc-endpoints` を使用する方法を示しています。

**AWS CLI**  
**VPC エンドポイントを記述するには**  
次の `describe-vpc-endpoints` の例では、すべての VPC エンドポイントの詳細を表示します。  

```
aws ec2 describe-vpc-endpoints
```
出力:  

```
{
    "VpcEndpoints": [
        {
            "PolicyDocument": "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"*\",\"Resource\":\"*\"}]}",
            "VpcId": "vpc-aabb1122",
            "NetworkInterfaceIds": [],
            "SubnetIds": [],
            "PrivateDnsEnabled": true,
            "State": "available",
            "ServiceName": "com.amazonaws.us-east-1.dynamodb",
            "RouteTableIds": [
                "rtb-3d560345"
            ],
            "Groups": [],
            "VpcEndpointId": "vpce-032a826a",
            "VpcEndpointType": "Gateway",
            "CreationTimestamp": "2017-09-05T20:41:28Z",
            "DnsEntries": [],
            "OwnerId": "123456789012"
        },
        {
            "PolicyDocument": "{\n  \"Statement\": [\n    {\n      \"Action\": \"*\", \n      \"Effect\": \"Allow\", \n      \"Principal\": \"*\", \n      \"Resource\": \"*\"\n    }\n  ]\n}",
            "VpcId": "vpc-1a2b3c4d",
            "NetworkInterfaceIds": [
                "eni-2ec2b084",
                "eni-1b4a65cf"
            ],
            "SubnetIds": [
                "subnet-d6fcaa8d",
                "subnet-7b16de0c"
            ],
            "PrivateDnsEnabled": false,
            "State": "available",
            "ServiceName": "com.amazonaws.us-east-1.elasticloadbalancing",
            "RouteTableIds": [],
            "Groups": [
                {
                    "GroupName": "default",
                    "GroupId": "sg-54e8bf31"
                }
            ],
            "VpcEndpointId": "vpce-0f89a33420c1931d7",
            "VpcEndpointType": "Interface",
            "CreationTimestamp": "2017-09-05T17:55:27.583Z",
            "DnsEntries": [
                {
                    "HostedZoneId": "Z7HUB22UULQXV",
                    "DnsName": "vpce-0f89a33420c1931d7-bluzidnv.elasticloadbalancing.us-east-1.vpce.amazonaws.com"
                },
                {
                    "HostedZoneId": "Z7HUB22UULQXV",
                    "DnsName": "vpce-0f89a33420c1931d7-bluzidnv-us-east-1b.elasticloadbalancing.us-east-1.vpce.amazonaws.com"
                },
                {
                    "HostedZoneId": "Z7HUB22UULQXV",
                    "DnsName": "vpce-0f89a33420c1931d7-bluzidnv-us-east-1a.elasticloadbalancing.us-east-1.vpce.amazonaws.com"
                }
            ],
            "OwnerId": "123456789012"
        },
        {
            "VpcEndpointId": "vpce-aabbaabbaabbaabba",
            "VpcEndpointType": "GatewayLoadBalancer",
            "VpcId": "vpc-111122223333aabbc",
            "ServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-123123a1c43abc123",
            "State": "available",
            "SubnetIds": [
                "subnet-0011aabbcc2233445"
            ],
            "RequesterManaged": false,
            "NetworkInterfaceIds": [
                "eni-01010120203030405"
            ],
            "CreationTimestamp": "2020-11-11T08:06:03.522Z",
            "Tags": [],
            "OwnerId": "123456789012"
        }
    ]
}
```
詳細については、*AWS PrivateLink ユーザーガイド*の「[概念](https://docs.aws.amazon.com/vpc/latest/privatelink/concepts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoints.html)」を参照してください。

### `describe-vpc-peering-connections`
<a name="ec2_DescribeVpcPeeringConnections_cli_2_topic"></a>

次のコード例は、`describe-vpc-peering-connections` を使用する方法を示しています。

**AWS CLI**  
**VPC ピアリング接続を記述するには**  
この例では、すべての VPC ピアリング接続を記述します。  
コマンド:  

```
aws ec2 describe-vpc-peering-connections
```
出力:  

```
{
    "VpcPeeringConnections": [
        {
            "Status": {
                "Message": "Active",
                "Code": "active"
            },
            "Tags": [
                {
                    "Value": "Peering-1",
                    "Key": "Name"
                }
            ],
            "AccepterVpcInfo": {
                "OwnerId": "111122223333",
                "VpcId": "vpc-1a2b3c4d",
                "CidrBlock": "10.0.1.0/28"
            },
            "VpcPeeringConnectionId": "pcx-11122233",
            "RequesterVpcInfo": {
                "PeeringOptions": {
                    "AllowEgressFromLocalVpcToRemoteClassicLink": false,
                    "AllowEgressFromLocalClassicLinkToRemoteVpc": false
                },
                "OwnerId": "444455556666",
                "VpcId": "vpc-123abc45",
                "CidrBlock": "192.168.0.0/16"
            }
        },
        {
            "Status": {
                "Message": "Pending Acceptance by 444455556666",
                "Code": "pending-acceptance"
            },
            "Tags": [],
            "RequesterVpcInfo": {
                "PeeringOptions": {
                    "AllowEgressFromLocalVpcToRemoteClassicLink": false,
                    "AllowEgressFromLocalClassicLinkToRemoteVpc": false
                },
                "OwnerId": "444455556666",
                "VpcId": "vpc-11aa22bb",
                "CidrBlock": "10.0.0.0/28"
            },
            "VpcPeeringConnectionId": "pcx-abababab",
            "ExpirationTime": "2014-04-03T09:12:43.000Z",
            "AccepterVpcInfo": {
                "OwnerId": "444455556666",
                "VpcId": "vpc-33cc44dd"
            }
        }
    ]
}
```
**特定の VPC ピアリング接続を記述するには**  
この例では、保留中の承諾の状態にあるすべての VPC ピアリング接続を記述します。  
コマンド:  

```
aws ec2 describe-vpc-peering-connections --filters Name=status-code,Values=pending-acceptance
```
この例では、「Owner=Finance」というタグを持つすべての VPC ピアリング接続を記述します。  
コマンド:  

```
aws ec2 describe-vpc-peering-connections --filters Name=tag:Owner,Values=Finance
```
この例では、指定された VPC、vpc-1a2b3c4d に対してリクエストしたすべての VPC ピアリング接続を記述します。  
コマンド:  

```
aws ec2 describe-vpc-peering-connections --filters Name=requester-vpc-info.vpc-id,Values=vpc-1a2b3c4d
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpcPeeringConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-peering-connections.html)」を参照してください。

### `describe-vpcs`
<a name="ec2_DescribeVpcs_cli_2_topic"></a>

次のコード例は、`describe-vpcs` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべての VPC を説明するには**  
次の `describe-vpcs` の例では、VPC に関する詳細を取得します。  

```
aws ec2 describe-vpcs
```
出力:  

```
{
    "Vpcs": [
        {
            "CidrBlock": "30.1.0.0/16",
            "DhcpOptionsId": "dopt-19edf471",
            "State": "available",
            "VpcId": "vpc-0e9801d129EXAMPLE",
            "OwnerId": "111122223333",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-062c64cfafEXAMPLE",
                    "CidrBlock": "30.1.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Not Shared"
                }
            ]
        },
        {
            "CidrBlock": "10.0.0.0/16",
            "DhcpOptionsId": "dopt-19edf471",
            "State": "available",
            "VpcId": "vpc-06e4ab6c6cEXAMPLE",
            "OwnerId": "222222222222",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-00b17b4eddEXAMPLE",
                    "CidrBlock": "10.0.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Shared VPC"
                }
            ]
        }
    ]
}
```
**例 2: 指定した VPC を説明するには**  
次の `describe-vpcs` 例では、指定した VPC に関する詳細を取得します。  

```
aws ec2 describe-vpcs \
    --vpc-ids vpc-06e4ab6c6cEXAMPLE
```
出力:  

```
{
    "Vpcs": [
        {
            "CidrBlock": "10.0.0.0/16",
            "DhcpOptionsId": "dopt-19edf471",
            "State": "available",
            "VpcId": "vpc-06e4ab6c6cEXAMPLE",
            "OwnerId": "111122223333",
            "InstanceTenancy": "default",
            "CidrBlockAssociationSet": [
                {
                    "AssociationId": "vpc-cidr-assoc-00b17b4eddEXAMPLE",
                    "CidrBlock": "10.0.0.0/16",
                    "CidrBlockState": {
                        "State": "associated"
                    }
                }
            ],
            "IsDefault": false,
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "Shared VPC"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeVpcs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpcs.html)」を参照してください。

### `describe-vpn-connections`
<a name="ec2_DescribeVpnConnections_cli_2_topic"></a>

次のコード例は、`describe-vpn-connections` を使用する方法を示しています。

**AWS CLI**  
**例 1: VPN 接続を記述するには**  
次の `describe-vpn-connections` の例では、すべての Site-to-Site VPN 接続について説明します。  

```
aws ec2 describe-vpn-connections
```
出力:  

```
{
    "VpnConnections": [
        {
            "CustomerGatewayConfiguration": "...configuration information...",
            "CustomerGatewayId": "cgw-01234567abcde1234",
            "Category": "VPN",
            "State": "available",
            "Type": "ipsec.1",
            "VpnConnectionId": "vpn-1122334455aabbccd",
            "TransitGatewayId": "tgw-00112233445566aab",
            "Options": {
                "EnableAcceleration": false,
                "StaticRoutesOnly": true,
                "LocalIpv4NetworkCidr": "0.0.0.0/0",
                "RemoteIpv4NetworkCidr": "0.0.0.0/0",
                "TunnelInsideIpVersion": "ipv4"
            },
            "Routes": [],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "CanadaVPN"
                }
            ],
            "VgwTelemetry": [
                {
                    "AcceptedRouteCount": 0,
                    "LastStatusChange": "2020-07-29T10:35:11.000Z",
                    "OutsideIpAddress": "203.0.113.3",
                    "Status": "DOWN",
                    "StatusMessage": ""
                },
                {
                    "AcceptedRouteCount": 0,
                    "LastStatusChange": "2020-09-02T09:09:33.000Z",
                    "OutsideIpAddress": "203.0.113.5",
                    "Status": "UP",
                    "StatusMessage": ""
                }
            ]
        }
    ]
}
```
詳細については、[AWS 「 Site-to-Site VPN ユーザーガイド](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html)*AWS 」のSite-to-Site VPN* works」を参照してください。  
**例 2: 使用可能な VPN 接続を記述するには**  
次の `describe-vpn-connections` の例では、状態が `available` である Site-to-Site VPN 接続について説明します。  

```
aws ec2 describe-vpn-connections \
    --filters "Name=state,Values=available"
```
詳細については、[AWS 「 Site-to-Site VPN ユーザーガイド](https://docs.aws.amazon.com/vpn/latest/s2svpn/how_it_works.html)*AWS 」のSite-to-Site VPN* works」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeVpnConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpn-connections.html)」を参照してください。

### `describe-vpn-gateways`
<a name="ec2_DescribeVpnGateways_cli_2_topic"></a>

次のコード例は、`describe-vpn-gateways` を使用する方法を示しています。

**AWS CLI**  
**仮想プライベートゲートウェイを記述するには**  
この例では、仮想プライベートゲートウェイを記述します。  
コマンド:  

```
aws ec2 describe-vpn-gateways
```
出力:  

```
{
    "VpnGateways": [
        {
            "State": "available",
            "Type": "ipsec.1",
            "VpnGatewayId": "vgw-f211f09b",
            "VpcAttachments": [
                {
                    "State": "attached",
                    "VpcId": "vpc-98eb5ef5"
                }
            ]
        },
        {
            "State": "available",
            "Type": "ipsec.1",
            "VpnGatewayId": "vgw-9a4cacf3",
            "VpcAttachments": [
                {
                    "State": "attaching",
                    "VpcId": "vpc-a01106c2"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVpnGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpn-gateways.html)」を参照してください。

### `detach-classic-link-vpc`
<a name="ec2_DetachClassicLinkVpc_cli_2_topic"></a>

次のコード例は、`detach-classic-link-vpc` を使用する方法を示しています。

**AWS CLI**  
**VPC から EC2-Classic インスタンスのリンクを解除 (デタッチ) するには**  
この例では、VPC vpc-88888888 からインスタンス i-0598c7d356eba48d7 のリンクを解除します。  
コマンド:  

```
aws ec2 detach-classic-link-vpc --instance-id i-0598c7d356eba48d7 --vpc-id vpc-88888888
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachClassicLinkVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-classic-link-vpc.html)」を参照してください。

### `detach-internet-gateway`
<a name="ec2_DetachInternetGateway_cli_2_topic"></a>

次のコード例は、`detach-internet-gateway` を使用する方法を示しています。

**AWS CLI**  
**VPC からインターネットゲートウェイをデタッチするには**  
次の `detach-internet-gateway` の例では、特定の VPC から指定したインターネットゲートウェイをデタッチします。  

```
aws ec2 detach-internet-gateway \
    --internet-gateway-id igw-0d0fb496b3EXAMPLE \
    --vpc-id vpc-0a60eb65b4EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、*Amazon VPC ユーザーガイド*の「[インターネットゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachInternetGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-internet-gateway.html)」を参照してください。

### `detach-network-interface`
<a name="ec2_DetachNetworkInterface_cli_2_topic"></a>

次のコード例は、`detach-network-interface` を使用する方法を示しています。

**AWS CLI**  
**インスタンスからネットワークインターフェイスをデタッチするには**  
この例では、指定されたインスタンスから指定されたネットワークインターフェイスをデタッチします。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 detach-network-interface --attachment-id eni-attach-66c4350a
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachNetworkInterface](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-network-interface.html)」を参照してください。

### `detach-verified-access-trust-provider`
<a name="ec2_DetachVerifiedAccessTrustProvider_cli_2_topic"></a>

次のコード例は、`detach-verified-access-trust-provider` を使用する方法を示しています。

**AWS CLI**  
**インスタンスから信頼プロバイダーをデタッチするには**  
次の `detach-verified-access-trust-provider` の例では、指定した Verified Access 信頼プロバイダーを指定した Verified Access インスタンスからデタッチします。  

```
aws ec2 detach-verified-access-trust-provider \
    --verified-access-instance-id vai-0ce000c0b7643abea \
    --verified-access-trust-provider-id vatp-0bb32de759a3e19e7
```
出力:  

```
{
    "VerifiedAccessTrustProvider": {
        "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
        "Description": "Testing Verified Access",
        "TrustProviderType": "user",
        "UserTrustProviderType": "iam-identity-center",
        "PolicyReferenceName": "idc",
        "CreationTime": "2023-08-25T19:00:38",
        "LastUpdatedTime": "2023-08-25T19:00:38"
    },
    "VerifiedAccessInstance": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "Testing Verified Access",
        "VerifiedAccessTrustProviders": [],
        "CreationTime": "2023-08-25T18:27:56",
        "LastUpdatedTime": "2023-08-25T18:27:56"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Access インスタンス](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachVerifiedAccessTrustProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-verified-access-trust-provider.html)」を参照してください。

### `detach-volume`
<a name="ec2_DetachVolume_cli_2_topic"></a>

次のコード例は、`detach-volume` を使用する方法を示しています。

**AWS CLI**  
**インスタンスからボリュームをデタッチするには**  
このコマンド例では、ボリューム (`vol-049df61146c4d7901`) をアタッチされているインスタンスからデタッチします。  
コマンド:  

```
aws ec2 detach-volume --volume-id vol-1234567890abcdef0
```
出力:  

```
{
    "AttachTime": "2014-02-27T19:23:06.000Z",
    "InstanceId": "i-1234567890abcdef0",
    "VolumeId": "vol-049df61146c4d7901",
    "State": "detaching",
    "Device": "/dev/sdb"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-volume.html)」を参照してください。

### `detach-vpn-gateway`
<a name="ec2_DetachVpnGateway_cli_2_topic"></a>

次のコード例は、`detach-vpn-gateway` を使用する方法を示しています。

**AWS CLI**  
**VPC から仮想プライベートゲートウェイをデタッチするには**  
この例では、指定された VPC から指定された仮想プライベートゲートウェイをデタッチします。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 detach-vpn-gateway --vpn-gateway-id vgw-9a4cacf3 --vpc-id vpc-a01106c2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachVpnGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/detach-vpn-gateway.html)」を参照してください。

### `disable-address-transfer`
<a name="ec2_DisableAddressTransfer_cli_2_topic"></a>

次のコード例は、`disable-address-transfer` を使用する方法を示しています。

**AWS CLI**  
**Elastic IP アドレスの移行を無効にするには**  
次の `disable-address-transfer` の例では、指定した Elastic IP アドレスの Elastic IP アドレス転送を無効にします。  

```
aws ec2 disable-address-transfer \
    --allocation-id eipalloc-09ad461b0d03f6aaf
```
出力:  

```
{
    "AddressTransfer": {
        "PublicIp": "100.21.184.216",
        "AllocationId": "eipalloc-09ad461b0d03f6aaf",
        "AddressTransferStatus": "disabled"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Transfer Elastic IP addresses](https://docs.aws.amazon.com/vpc/latest/userguide/WorkWithEIPs.html#transfer-EIPs-intro)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableAddressTransfer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-address-transfer.html)」を参照してください。

### `disable-aws-network-performance-metric-subscription`
<a name="ec2_DisableAwsNetworkPerformanceMetricSubscription_cli_2_topic"></a>

次のコード例は、`disable-aws-network-performance-metric-subscription` を使用する方法を示しています。

**AWS CLI**  
**メトリクスサブスクリプションを無効にするには**  
次の `disable-aws-network-performance-metric-subscription` の例では、指定した転送元リージョンと転送先リージョン間のネットワークレイテンシーの集計のモニタリングを無効にします。  

```
aws ec2 disable-aws-network-performance-metric-subscription \
    --source us-east-1 \
    --destination eu-west-1 \
    --metric aggregate-latency \
    --statistic p50
```
出力:  

```
{
    "Output": true
}
```
詳細については、*インフラストラクチャパフォーマンスユーザーガイド*の「[CLI を使用して CloudWatch サブスクリプションを管理する](https://docs.aws.amazon.com/network-manager/latest/infrastructure-performance/getting-started-nmip-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableAwsNetworkPerformanceMetricSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-aws-network-performance-metric-subscription.html)」を参照してください。

### `disable-ebs-encryption-by-default`
<a name="ec2_DisableEbsEncryptionByDefault_cli_2_topic"></a>

次のコード例は、`disable-ebs-encryption-by-default` を使用する方法を示しています。

**AWS CLI**  
**デフォルトで EBS 暗号化を無効にするには**  
次の の`disable-ebs-encryption-by-default`例では、現在のリージョンの AWS アカウントの EBS 暗号化をデフォルトで無効にします。  

```
aws ec2 disable-ebs-encryption-by-default
```
出力:  

```
{
    "EbsEncryptionByDefault": false
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableEbsEncryptionByDefault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-ebs-encryption-by-default.html)」を参照してください。

### `disable-fast-launch`
<a name="ec2_DisableFastLaunch_cli_2_topic"></a>

次のコード例は、`disable-fast-launch` を使用する方法を示しています。

**AWS CLI**  
**イメージの高速起動を中止するには**  
次の `disable-fast-launch` の例では、指定した AMI での高速起動を中止し、事前プロビジョニングされたスナップショットをクリーンアップします。  

```
aws ec2 disable-fast-launch \
    --image-id ami-01234567890abcedf
```
出力:  

```
{
    "ImageId": "ami-01234567890abcedf",
    "ResourceType": "snapshot",
    "SnapshotConfiguration": {},
    "LaunchTemplate": {
        "LaunchTemplateId": "lt-01234567890abcedf",
        "LaunchTemplateName": "EC2FastLaunchDefaultResourceCreation-a8c6215d-94e6-441b-9272-dbd1f87b07e2",
        "Version": "1"
    },
    "MaxParallelLaunches": 6,
    "OwnerId": "0123456789123",
    "State": "disabling",
    "StateTransitionReason": "Client.UserInitiated",
    "StateTransitionTime": "2022-01-27T22:47:29.265000+00:00"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[Windows AMI に EC2 Fast Launch 設定を構成する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/win-fast-launch-configure.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableFastLaunch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-fast-launch.html)」を参照してください。

### `disable-fast-snapshot-restores`
<a name="ec2_DisableFastSnapshotRestores_cli_2_topic"></a>

次のコード例は、`disable-fast-snapshot-restores` を使用する方法を示しています。

**AWS CLI**  
**高速スナップショット復元を無効にするには**  
次の `disable-fast-snapshot-restores` の例では、指定したアベイラビリティーゾーン内の指定したスナップショットの高速スナップショット復元を無効にします。  

```
aws ec2 disable-fast-snapshot-restores \
    --availability-zones us-east-2a \
    --source-snapshot-ids snap-1234567890abcdef0
```
出力:  

```
{
    "Successful": [
        {
            "SnapshotId": "snap-1234567890abcdef0"
            "AvailabilityZone": "us-east-2a",
            "State": "disabling",
            "StateTransitionReason": "Client.UserInitiated",
            "OwnerId": "123456789012",
            "EnablingTime": "2020-01-25T23:57:49.602Z"
        }
    ],
    "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableFastSnapshotRestores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-fast-snapshot-restores.html)」を参照してください。

### `disable-image-block-public-access`
<a name="ec2_DisableImageBlockPublicAccess_cli_2_topic"></a>

次のコード例は、`disable-image-block-public-access` を使用する方法を示しています。

**AWS CLI**  
**指定したリージョンで AMI のパブリックアクセスのブロックを無効にするには**  
次の `disable-image-block-public-access` の例では、指定したリージョンからアカウントレベルの AMI のブロックパブリックアクセスを無効にします。  

```
aws ec2 disable-image-block-public-access \
    --region us-east-1
```
出力:  

```
{
    "ImageBlockPublicAccessState": "unblocked"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Block public access to your AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-public-access-to-amis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableImageBlockPublicAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-image-block-public-access.html)」を参照してください。

### `disable-image-deprecation`
<a name="ec2_DisableImageDeprecation_cli_2_topic"></a>

次のコード例は、`disable-image-deprecation` を使用する方法を示しています。

**AWS CLI**  
**AMI の非推奨をキャンセルするには**  
次の `disable-image-deprecation` の例では、AMI の非推奨化をキャンセルします。これにより、`describe-images` 出力から `DeprecationTime` フィールドが削除されます。この手順を実行するには、AMI の所有者である必要があります。  

```
aws ec2 disable-image-deprecation \
    --image-id ami-1234567890abcdef0
```
出力:  

```
{
    "RequestID": "11aabb229-4eac-35bd-99ed-be587EXAMPLE",
    "Return": "true"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[AMI を非推奨にする](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-deprecate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableImageDeprecation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-image-deprecation.html)」を参照してください。

### `disable-image-deregistration-protection`
<a name="ec2_DisableImageDeregistrationProtection_cli_2_topic"></a>

次のコード例は、`disable-image-deregistration-protection` を使用する方法を示しています。

**AWS CLI**  
**登録解除保護を無効にするには**  
次の `disable-image-deregistration-protection` の例では、指定されたイメージの登録解除保護を無効にします。  

```
aws ec2 disable-image-deregistration-protection \
    --image-id ami-0b1a928a144a74ec9
```
出力:  

```
{
    "Return": "disabled"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Amazon EC2 AMI を登録解除から保護する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-deregistration-protection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableImageDeregistrationProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-image-deregistration-protection.html)」を参照してください。

### `disable-image`
<a name="ec2_DisableImage_cli_2_topic"></a>

次のコード例は、`disable-image` を使用する方法を示しています。

**AWS CLI**  
**AMI を無効化するには**  
次の `disable-image` の例では、指定した AMI を無効にします。  

```
aws ec2 disable-image \
    --image-id ami-1234567890abcdef0
```
出力:  

```
{
    "Return": "true"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[AMI を無効にする](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/disable-an-ami.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-image.html)」を参照してください。

### `disable-ipam-organization-admin-account`
<a name="ec2_DisableIpamOrganizationAdminAccount_cli_2_topic"></a>

次のコード例は、`disable-ipam-organization-admin-account` を使用する方法を示しています。

**AWS CLI**  
**委任された IPAM 管理者を無効にするには**  
特定のシナリオでは、IPAM を AWS Organizations と統合します。これを行うと、 AWS Organizations 管理アカウントは AWS Organizations メンバーアカウントを IPAM 管理者として委任します。  
この例では、IPAM 管理者アカウントを委任した AWS Organizations 管理アカウントであり、そのアカウントを IPAM 管理者として無効にします。  
このリクエストを行う`--region`ときは、 の任意の AWS リージョンを使用できます。最初に管理者を委任したリージョン、IPAM が作成されたリージョン、または IPAM 運用リージョンを使用する必要はありません。委任された管理者アカウントを無効にすると、いつでも再び有効にしたり、新しいアカウントを IPAM 管理者として委任したりすることができます。  
次の の`disable-ipam-organization-admin-account`例では、 AWS アカウントの委任 IPAM 管理者を無効にします。  

```
aws ec2 disable-ipam-organization-admin-account \
    --delegated-admin-account-id 320805250157 \
    --region ap-south-1
```
出力:  

```
{
    "Success": true
}
```
詳細については、*「Amazon VPC* [IPAM ユーザーガイド」の「Integrate IPAM with accounts in an AWS Organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableIpamOrganizationAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-ipam-organization-admin-account.html)」を参照してください。

### `disable-serial-console-access`
<a name="ec2_DisableSerialConsoleAccess_cli_2_topic"></a>

次のコード例は、`disable-serial-console-access` を使用する方法を示しています。

**AWS CLI**  
**アカウントの EC2 シリアルコンソールへのアクセスを無効にするには**  
次の `disable-serial-console-access` の例では、シリアルコンソールへのアカウントアクセスを無効にします。  

```
aws ec2 disable-serial-console-access
```
出力:  

```
{
    "SerialConsoleAccessEnabled": false
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[EC2 Serial Console](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-serial-console.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableSerialConsoleAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-serial-console-access.html)」を参照してください。

### `disable-snapshot-block-public-access`
<a name="ec2_DisableSnapshotBlockPublicAccess_cli_2_topic"></a>

次のコード例は、`disable-snapshot-block-public-access` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのブロックパブリックアクセスを無効にするには**  
次の `disable-snapshot-block-public-access` の例では、スナップショットのブロックパブリックアクセスを無効にして、スナップショットのパブリック共有を許可します。  

```
aws ec2 disable-snapshot-block-public-access
```
出力:  

```
{
    "State": "unblocked"
}
```
詳細については、「*Amazon EBS ユーザーガイド*」の「[Block public access for snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/block-public-access-snapshots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableSnapshotBlockPublicAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-snapshot-block-public-access.html)」を参照してください。

### `disable-transit-gateway-route-table-propagation`
<a name="ec2_DisableTransitGatewayRouteTablePropagation_cli_2_topic"></a>

次のコード例は、`disable-transit-gateway-route-table-propagation` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway アタッチメントを無効にして、指定された伝播ルートテーブルにルートを伝播するには**  
次の `disable-transit-gateway-route-table-propagation` の例では、指定したアタッチメントが、指定した伝播ルートテーブルにルートを伝播することを無効にします。  

```
aws ec2 disable-transit-gateway-route-table-propagation \
    --transit-gateway-route-table-id tgw-rtb-0a823edbdeEXAMPLE \
    --transit-gateway-attachment-id tgw-attach-09b52ccdb5EXAMPLE
```
出力:  

```
{
    "Propagation": {
        "TransitGatewayAttachmentId": "tgw-attach-09b52ccdb5EXAMPLE",
        "ResourceId": "vpc-4d7de228",
        "ResourceType": "vpc",
        "TransitGatewayRouteTableId": "tgw-rtb-0a823edbdeEXAMPLE",
        "State": "disabled"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableTransitGatewayRouteTablePropagation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-transit-gateway-route-table-propagation.html)」を参照してください。

### `disable-vgw-route-propagation`
<a name="ec2_DisableVgwRoutePropagation_cli_2_topic"></a>

次のコード例は、`disable-vgw-route-propagation` を使用する方法を示しています。

**AWS CLI**  
**ルート伝播を無効にするには**  
この例では、指定された仮想プライベートゲートウェイが指定されたルートテーブルに静的ルートを伝播しないようにします。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 disable-vgw-route-propagation --route-table-id rtb-22574640 --gateway-id vgw-9a4cacf3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableVgwRoutePropagation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-vgw-route-propagation.html)」を参照してください。

### `disable-vpc-classic-link-dns-support`
<a name="ec2_DisableVpcClassicLinkDnsSupport_cli_2_topic"></a>

次のコード例は、`disable-vpc-classic-link-dns-support` を使用する方法を示しています。

**AWS CLI**  
**VPC の ClassicLink DNS サポートを無効にするには**  
`vpc-88888888` の ClassicLink DNS サポートを無効にします。  
コマンド:  

```
aws ec2 disable-vpc-classic-link-dns-support --vpc-id vpc-88888888
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableVpcClassicLinkDnsSupport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-vpc-classic-link-dns-support.html)」を参照してください。

### `disable-vpc-classic-link`
<a name="ec2_DisableVpcClassicLink_cli_2_topic"></a>

次のコード例は、`disable-vpc-classic-link` を使用する方法を示しています。

**AWS CLI**  
**VPC の ClassicLink を無効にするには**  
この例では、vpc-8888888 の ClassicLink を無効にします。  
コマンド:  

```
aws ec2 disable-vpc-classic-link --vpc-id vpc-88888888
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableVpcClassicLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-vpc-classic-link.html)」を参照してください。

### `disassociate-address`
<a name="ec2_DisassociateAddress_cli_2_topic"></a>

次のコード例は、`disassociate-address` を使用する方法を示しています。

**AWS CLI**  
**EC2-Classic で Elastic IP アドレスの関連付けを解除するには**  
この例では、EC2-Classic のインスタンスから Elastic IP アドレスの関連付けを解除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 disassociate-address --public-ip 198.51.100.0
```
**EC2-VPC で Elastic IP アドレスの関連付けを解除するには**  
この例では、VPC のインスタンスから Elastic IP アドレスの関連付けを解除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 disassociate-address --association-id eipassoc-2bebb745
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DisassociateAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-address.html)」を参照してください。

### `disassociate-client-vpn-target-network`
<a name="ec2_DisassociateClientVpnTargetNetwork_cli_2_topic"></a>

次のコード例は、`disassociate-client-vpn-target-network` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントからネットワークの関連付けを解除するには**  
次の `disassociate-client-vpn-target-network` の例では、指定したクライアント VPN エンドポイントの `cvpn-assoc-12312312312312312` 関連付け ID に関連付けられているターゲットネットワークの関連付けを解除します。  

```
aws ec2 disassociate-client-vpn-target-network \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --association-id cvpn-assoc-12312312312312312
```
出力:  

```
{
    "AssociationId": "cvpn-assoc-12312312312312312",
    "Status": {
        "Code": "disassociating"
    }
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Target Networks](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-target.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateClientVpnTargetNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-client-vpn-target-network.html)」を参照してください。

### `disassociate-iam-instance-profile`
<a name="ec2_DisassociateIamInstanceProfile_cli_2_topic"></a>

次のコード例は、`disassociate-iam-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**IAM インスタンスプロファイルの関連付けを解除するには**  
この例では、IAM インスタンスプロファイルと関連付け ID `iip-assoc-05020b59952902f5f` の関連付けを解除します。  
コマンド:  

```
aws ec2 disassociate-iam-instance-profile --association-id iip-assoc-05020b59952902f5f
```
出力:  

```
{
  "IamInstanceProfileAssociation": {
      "InstanceId": "i-123456789abcde123",
      "State": "disassociating",
      "AssociationId": "iip-assoc-05020b59952902f5f",
      "IamInstanceProfile": {
          "Id": "AIPAI5IVIHMFFYY2DKV5Y",
          "Arn": "arn:aws:iam::123456789012:instance-profile/admin-role"
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateIamInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-iam-instance-profile.html)」を参照してください。

### `disassociate-instance-event-window`
<a name="ec2_DisassociateInstanceEventWindow_cli_2_topic"></a>

次のコード例は、`disassociate-instance-event-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: イベントウィンドウから 1 つ以上のインスタンスの関連付けを解除するには**  
次の `disassociate-instance-event-window` の例では、1 つ以上のインスタンスの関連付けをイベントウィンドウから解除します。`instance-event-window-id` パラメータを指定して、イベントウィンドウを指定します。インスタンスの関連付けを解除するには、`association-target` パラメータを使用し、その値に 1 つまたは複数のインスタンス ID を指定します。  

```
aws ec2 disassociate-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --association-target "InstanceIds=i-1234567890abcdef0,i-0598c7d356eba48d7"
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "AssociationTarget": {
            "InstanceIds": [],
            "Tags": [],
            "DedicatedHostIds": []
        },
        "State": "creating"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 2: イベントウィンドウからインスタンスタグの関連付けを解除するには**  
次の `disassociate-instance-event-window` の例では、インスタンスタグの関連付けをイベントウィンドウから解除します。`instance-event-window-id` パラメータを指定して、イベントウィンドウを指定します。インスタンスタグの関連付けを解除するには`association-target` パラメータを使用し、その値に 1 つ以上のタグを指定します。  

```
aws ec2 disassociate-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --association-target "InstanceTags=[{Key=k2,Value=v2},{Key=k1,Value=v1}]"
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "AssociationTarget": {
            "InstanceIds": [],
            "Tags": [],
            "DedicatedHostIds": []
        },
        "State": "creating"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 3: イベントウィンドウから専有ホストの関連付けを解除するには**  
次の `disassociate-instance-event-window` の例では、専有ホストの関連付けをイベントウィンドウから解除します。`instance-event-window-id` パラメータを指定して、イベントウィンドウを指定します。Dedicated Host の関連付けを解除するには`association-target` パラメータを使用し、その値に 1 つ以上の Dedicated Host ID を指定します。  

```
aws ec2 disassociate-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --association-target DedicatedHostIds=h-029fa35a02b99801d
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "AssociationTarget": {
            "InstanceIds": [],
            "Tags": [],
            "DedicatedHostIds": []
        },
        "State": "creating"
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateInstanceEventWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-instance-event-window.html)」を参照してください。

### `disassociate-ipam-resource-discovery`
<a name="ec2_DisassociateIpamResourceDiscovery_cli_2_topic"></a>

次のコード例は、`disassociate-ipam-resource-discovery` を使用する方法を示しています。

**AWS CLI**  
**IPAM からリソース検出の関連付けを解除するには**  
この例では、あなたは IPAM の委任された管理者アカウントとして、IPAM から IPAM リソース検出の関連付けを解除したいと考えています。あなたは describe コマンドを実行し、`"ResourceDiscoveryStatus": "not-found"` に気付いたため、自身の IPAM からその関連付けを解除して、他の関連付けのためのスペースを確保したいと考えています。  
次の の`disassociate-ipam-resource-discovery`例では、 AWS アカウントの IPAM リソース検出の関連付けを解除します。  

```
aws ec2 disassociate-ipam-resource-discovery \
    --ipam-resource-discovery-association-id ipam-res-disco-assoc-04382a6346357cf82 \
    --region us-east-1
```
出力:  

```
{
    "IpamResourceDiscoveryAssociation": {
        "OwnerId": "320805250157",
        "IpamResourceDiscoveryAssociationId": "ipam-res-disco-assoc-04382a6346357cf82",
        "IpamResourceDiscoveryAssociationArn":             "arn:aws:ec2::320805250157:ipam-resource-discovery-association/ipam-res-disco-assoc-04382a6346357cf82",
        "IpamResourceDiscoveryId": "ipam-res-disco-0365d2977fc1672fe",
        "IpamId": "ipam-005f921c17ebd5107",
        "IpamArn": "arn:aws:ec2::320805250157:ipam/ipam-005f921c17ebd5107",
        "IpamRegion": "us-east-1",
        "IsDefault": false,
        "ResourceDiscoveryStatus": "not-found",
        "State": "disassociate-in-progress"
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Integrate IPAM with accounts outside of your organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateIpamResourceDiscovery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-ipam-resource-discovery.html)」を参照してください。

### `disassociate-nat-gateway-address`
<a name="ec2_DisassociateNatGatewayAddress_cli_2_topic"></a>

次のコード例は、`disassociate-nat-gateway-address` を使用する方法を示しています。

**AWS CLI**  
**パブリック NAT ゲートウェイから Elastic IP アドレスの関連付けを解除するには**  
次の `disassociate-nat-gateway-address` の例では、指定した Elastic IP アドレスの関連付けを指定したパブリック NAT ゲートウェイから解除します。  

```
aws ec2 disassociate-nat-gateway-address \
    --nat-gateway-id nat-1234567890abcdef0 \
    --association-ids eipassoc-0f96bdca17EXAMPLE
```
出力:  

```
{
    "NatGatewayId": "nat-1234567890abcdef0",
    "NatGatewayAddresses": [
        {
            "AllocationId": "eipalloc-0be6ecac95EXAMPLE",
            "NetworkInterfaceId": "eni-09cc4b2558794f7f9",
            "PrivateIp": "10.0.0.74",
            "PublicIp": "3.211.231.218",
            "AssociationId": "eipassoc-0f96bdca17EXAMPLE",
            "IsPrimary": false,
            "Status": "disassociating"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[NAT ゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateNatGatewayAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-nat-gateway-address.html)」を参照してください。

### `disassociate-route-table`
<a name="ec2_DisassociateRouteTable_cli_2_topic"></a>

次のコード例は、`disassociate-route-table` を使用する方法を示しています。

**AWS CLI**  
** ルートテーブルの関連付けを解除するには**  
この例では、指定されたサブネットから指定されたルートテーブルの関連付けを解除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 disassociate-route-table --association-id rtbassoc-781d0d1a
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-route-table.html)」を参照してください。

### `disassociate-security-group-vpc`
<a name="ec2_DisassociateSecurityGroupVpc_cli_2_topic"></a>

次のコード例は、`disassociate-security-group-vpc` を使用する方法を示しています。

**AWS CLI**  
**VPC からセキュリティグループの関連付けを解除するには**  
次の `disassociate-security-group-vpc` の例では、指定されたセキュリティグループの関連付けを指定された VPC から解除します。  

```
aws ec2 disassociate-security-group-vpc \
    --group-id sg-04dbb43907d3f8a78 \
    --vpc-id vpc-0bf4c2739bc05a694
```
出力:  

```
{
    "State": "disassociating"
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[セキュリティグループを複数の VPC に関連付ける](https://docs.aws.amazon.com/vpc/latest/userguide/security-group-assoc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateSecurityGroupVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-security-group-vpc.html)」を参照してください。

### `disassociate-subnet-cidr-block`
<a name="ec2_DisassociateSubnetCidrBlock_cli_2_topic"></a>

次のコード例は、`disassociate-subnet-cidr-block` を使用する方法を示しています。

**AWS CLI**  
**サブネットから IPv6 CIDR ブロックの関連付けを解除するには**  
この例では、CIDR ブロックの関連付け ID を使用して、サブネットから IPv6 CIDR ブロックの関連付けを解除します。  
コマンド:  

```
aws ec2 disassociate-subnet-cidr-block --association-id subnet-cidr-assoc-3aa54053
```
出力:  

```
{
  "SubnetId": "subnet-5f46ec3b",
  "Ipv6CidrBlockAssociation": {
      "Ipv6CidrBlock": "2001:db8:1234:1a00::/64",
      "AssociationId": "subnet-cidr-assoc-3aa54053",
      "Ipv6CidrBlockState": {
          "State": "disassociating"
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateSubnetCidrBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-subnet-cidr-block.html)」を参照してください。

### `disassociate-transit-gateway-multicast-domain`
<a name="ec2_DisassociateTransitGatewayMulticastDomain_cli_2_topic"></a>

次のコード例は、`disassociate-transit-gateway-multicast-domain` を使用する方法を示しています。

**AWS CLI**  
**マルチキャストドメインからサブネットの関連付けを解除するには**  
次の `disassociate-transit-gateway-multicast-domain` の例では、指定したマルチキャストドメインからサブネットの関連付けを解除します。  

```
aws ec2 disassociate-transit-gateway-multicast-domain \
    --transit-gateway-attachment-id tgw-attach-070e571cd1EXAMPLE \
    --subnet-id subnet-000de86e3bEXAMPLE \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef7EXAMPLE
```
出力:  

```
{
    "Associations": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c4905cef7EXAMPLE",
        "TransitGatewayAttachmentId": "tgw-attach-070e571cd1EXAMPLE",
        "ResourceId": "vpc-7EXAMPLE",
        "ResourceType": "vpc",
        "Subnets": [
            {
                "SubnetId": "subnet-000de86e3bEXAMPLE",
                "State": "disassociating"
            }
        ]
    }
}
```
詳細については、*Transit Gateways ガイド*の「[マルチキャストドメイン](https://docs.aws.amazon.com/vpc/latest/tgw/multicast-domains-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateTransitGatewayMulticastDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-transit-gateway-multicast-domain.html)」を参照してください。

### `disassociate-transit-gateway-route-table`
<a name="ec2_DisassociateTransitGatewayRouteTable_cli_2_topic"></a>

次のコード例は、`disassociate-transit-gateway-route-table` を使用する方法を示しています。

**AWS CLI**  
**リソースアタッチメントから Transit Gateway ルートテーブルの関連付けを解除するには**  
次の `disassociate-transit-gateway-route-table` の例では、指定したアタッチメントの関連付けを Transit Gateway ルートテーブルから解除します。  

```
aws ec2 disassociate-transit-gateway-route-table \
    --transit-gateway-route-table-id tgw-rtb-002573ed1eEXAMPLE \
    --transit-gateway-attachment-id tgw-attach-08e0bc912cEXAMPLE
```
出力:  

```
{
    "Association": {
        "TransitGatewayRouteTableId": "tgw-rtb-002573ed1eEXAMPLE",
        "TransitGatewayAttachmentId": "tgw-attach-08e0bc912cEXAMPLE",
        "ResourceId": "11460968-4ac1-4fd3-bdb2-00599EXAMPLE",
        "ResourceType": "direct-connect-gateway",
        "State": "disassociating"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateTransitGatewayRouteTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-transit-gateway-route-table.html)」を参照してください。

### `disassociate-vpc-cidr-block`
<a name="ec2_DisassociateVpcCidrBlock_cli_2_topic"></a>

次のコード例は、`disassociate-vpc-cidr-block` を使用する方法を示しています。

**AWS CLI**  
**VPC から IPv6 CIDR ブロックの関連付けを解除するには**  
この例では、CIDR ブロックの関連付け ID を使用して、VPC から IPv6 CIDR ブロックの関連付けを解除します。  
コマンド:  

```
aws ec2 disassociate-vpc-cidr-block --association-id vpc-cidr-assoc-eca54085
```
出力:  

```
{
  "Ipv6CidrBlockAssociation": {
      "Ipv6CidrBlock": "2001:db8:1234:1a00::/56",
      "AssociationId": "vpc-cidr-assoc-eca54085",
      "Ipv6CidrBlockState": {
          "State": "disassociating"
      }
  },
  "VpcId": "vpc-a034d6c4"
}
```
**VPC から IPv4 CIDR ブロックの関連付けを解除するには**  
この例では、VPC から IPv4 CIDR ブロックの関連付けを解除します。  
コマンド:  

```
aws ec2 disassociate-vpc-cidr-block --association-id vpc-cidr-assoc-0287ac6b
```
出力:  

```
{
  "CidrBlockAssociation": {
      "AssociationId": "vpc-cidr-assoc-0287ac6b",
      "CidrBlock": "172.18.0.0/16",
      "CidrBlockState": {
          "State": "disassociating"
      }
  },
  "VpcId": "vpc-27621243"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateVpcCidrBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disassociate-vpc-cidr-block.html)」を参照してください。

### `enable-address-transfer`
<a name="ec2_EnableAddressTransfer_cli_2_topic"></a>

次のコード例は、`enable-address-transfer` を使用する方法を示しています。

**AWS CLI**  
**Elastic IP アドレスの転送を有効にするには**  
次の `enable-address-transfer` の例では、指定した Elastic IP アドレスの Elastic IP アドレス転送を指定したアカウントに対して有効にします。  

```
aws ec2 enable-address-transfer \
    --allocation-id eipalloc-09ad461b0d03f6aaf \
    --transfer-account-id 123456789012
```
出力:  

```
{
     "AddressTransfer": {
        "PublicIp": "100.21.184.216",
        "AllocationId": "eipalloc-09ad461b0d03f6aaf",
        "TransferAccountId": "123456789012",
        "TransferOfferExpirationTimestamp": "2023-02-22T20:51:01.000Z",
        "AddressTransferStatus": "pending"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Transfer Elastic IP addresses](https://docs.aws.amazon.com/vpc/latest/userguide/WorkWithEIPs.html#transfer-EIPs-intro)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableAddressTransfer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-address-transfer.html)」を参照してください。

### `enable-aws-network-performance-metric-subscription`
<a name="ec2_EnableAwsNetworkPerformanceMetricSubscription_cli_2_topic"></a>

次のコード例は、`enable-aws-network-performance-metric-subscription` を使用する方法を示しています。

**AWS CLI**  
**メトリクスサブスクリプションを有効にするには**  
次の `enable-aws-network-performance-metric-subscription` の例では、指定した転送元リージョンと転送先リージョン間のネットワークレイテンシーの集計のモニタリングを有効にします。  

```
aws ec2 enable-aws-network-performance-metric-subscription \
    --source us-east-1 \
    --destination eu-west-1 \
    --metric aggregate-latency \
    --statistic p50
```
出力:  

```
{
    "Output": true
}
```
詳細については、「*インフラストラクチャのパフォーマンスのユーザーガイド*」の「[Manage subscriptions](https://docs.aws.amazon.com/network-manager/latest/infrastructure-performance/nmip-subscriptions-cw.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableAwsNetworkPerformanceMetricSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-aws-network-performance-metric-subscription.html)」を参照してください。

### `enable-ebs-encryption-by-default`
<a name="ec2_EnableEbsEncryptionByDefault_cli_2_topic"></a>

次のコード例は、`enable-ebs-encryption-by-default` を使用する方法を示しています。

**AWS CLI**  
**デフォルトで EBS 暗号化を有効にするには**  
次の`enable-ebs-encryption-by-default`例では、現在のリージョンの AWS アカウントで EBS 暗号化をデフォルトで有効にします。  

```
aws ec2 enable-ebs-encryption-by-default
```
出力:  

```
{
    "EbsEncryptionByDefault": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableEbsEncryptionByDefault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-ebs-encryption-by-default.html)」を参照してください。

### `enable-fast-launch`
<a name="ec2_EnableFastLaunch_cli_2_topic"></a>

次のコード例は、`enable-fast-launch` を使用する方法を示しています。

**AWS CLI**  
**イメージの高速起動を開始するには**  
次の `enable-fast-launch` の例では、指定した AMI を高速起動用に設定し、起動する並列インスタンスの最大数を 6 に設定します。AMI の事前プロビジョニングに使用するリソースのタイプは `snapshot` に設定され、これはデフォルト値でもあります。  

```
aws ec2 enable-fast-launch \
    --image-id ami-01234567890abcedf \
    --max-parallel-launches 6 \
    --resource-type snapshot
```
出力:  

```
{
    "ImageId": "ami-01234567890abcedf",
    "ResourceType": "snapshot",
    "SnapshotConfiguration": {
        "TargetResourceCount": 10
    },
    "LaunchTemplate": {},
    "MaxParallelLaunches": 6,
    "OwnerId": "0123456789123",
    "State": "enabling",
    "StateTransitionReason": "Client.UserInitiated",
    "StateTransitionTime": "2022-01-27T22:16:03.199000+00:00"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[Windows AMI に EC2 Fast Launch 設定を構成する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/win-fast-launch-configure.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableFastLaunch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-fast-launch.html)」を参照してください。

### `enable-fast-snapshot-restores`
<a name="ec2_EnableFastSnapshotRestores_cli_2_topic"></a>

次のコード例は、`enable-fast-snapshot-restores` を使用する方法を示しています。

**AWS CLI**  
**高速スナップショット復元を有効にするには**  
次の `enable-fast-snapshot-restores` の例では、指定したアベイラビリティーゾーン内の指定したスナップショットの高速スナップショット復元を有効にします。  

```
aws ec2 enable-fast-snapshot-restores \
    --availability-zones us-east-2a us-east-2b \
    --source-snapshot-ids snap-1234567890abcdef0
```
出力:  

```
{
    "Successful": [
        {
            "SnapshotId": "snap-1234567890abcdef0"
            "AvailabilityZone": "us-east-2a",
            "State": "enabling",
            "StateTransitionReason": "Client.UserInitiated",
            "OwnerId": "123456789012",
            "EnablingTime": "2020-01-25T23:57:49.602Z"
        },
        {
            "SnapshotId": "snap-1234567890abcdef0"
            "AvailabilityZone": "us-east-2b",
            "State": "enabling",
            "StateTransitionReason": "Client.UserInitiated",
            "OwnerId": "123456789012",
            "EnablingTime": "2020-01-25T23:57:49.596Z"
        }
    ],
    "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableFastSnapshotRestores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-fast-snapshot-restores.html)」を参照してください。

### `enable-image-block-public-access`
<a name="ec2_EnableImageBlockPublicAccess_cli_2_topic"></a>

次のコード例は、`enable-image-block-public-access` を使用する方法を示しています。

**AWS CLI**  
**指定したリージョンで AMI のパブリックアクセスのブロックを有効にするには**  
次の `enable-image-block-public-access` の例では、指定したリージョンからアカウントレベルの AMI のブロックパブリックアクセスを有効にします。  

```
aws ec2 enable-image-block-public-access \
    --region us-east-1 \
    --image-block-public-access-state block-new-sharing
```
出力:  

```
{
    "ImageBlockPublicAccessState": "block-new-sharing"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Block public access to your AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharingamis-intro.html#block-public-access-to-amis)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableImageBlockPublicAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-image-block-public-access.html)」を参照してください。

### `enable-image-deprecation`
<a name="ec2_EnableImageDeprecation_cli_2_topic"></a>

次のコード例は、`enable-image-deprecation` を使用する方法を示しています。

**AWS CLI**  
**AMI を非推奨にするには**  
次の `enable-image-deprecation` の例では、特定の日時の AMI を非推奨化します。秒の値を指定した場合は、Amazon EC2 により最も近い分に丸められます。この手順を実行するには、AMI の所有者である必要があります。  

```
aws ec2 enable-image-deprecation \
    --image-id ami-1234567890abcdef0 \
    --deprecate-at '2022-10-15T13:17:12.000Z'
```
出力:  

```
{
    "RequestID": "59dbff89-35bd-4eac-99ed-be587EXAMPLE",
    "Return": "true"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[AMI を非推奨にする](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-deprecate.html#deprecate-ami)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableImageDeprecation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-image-deprecation.html)」を参照してください。

### `enable-image-deregistration-protection`
<a name="ec2_EnableImageDeregistrationProtection_cli_2_topic"></a>

次のコード例は、`enable-image-deregistration-protection` を使用する方法を示しています。

**AWS CLI**  
**登録解除保護を有効にするには**  
次の `enable-image-deregistration-protection` の例では、指定されたイメージの登録解除保護を有効にします。  

```
aws ec2 enable-image-deregistration-protection \
    --image-id ami-0b1a928a144a74ec9
```
出力:  

```
{
    "Return": "enabled-without-cooldown"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Amazon EC2 AMI を登録解除から保護する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ami-deregistration-protection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI Command Reference*」の「[EnableImageDeregistrationProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-image-deregistration-protection.html)」を参照してください。

### `enable-image`
<a name="ec2_EnableImage_cli_2_topic"></a>

次のコード例は、`enable-image` を使用する方法を示しています。

**AWS CLI**  
**AMI を有効にするには**  
次の `enable-image` の例では、指定した AMI を有効にします。  

```
aws ec2 enable-image \
    --image-id ami-1234567890abcdef0
```
出力:  

```
{
    "Return": "true"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[AMI を無効にする](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/disable-an-ami.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-image.html)」を参照してください。

### `enable-ipam-organization-admin-account`
<a name="ec2_EnableIpamOrganizationAdminAccount_cli_2_topic"></a>

次の例は、`enable-ipam-organization-admin-account` を使用する方法を説明しています。

**AWS CLI**  
** AWS Organizations と統合し、メンバーアカウントを IPAM アカウントとして委任するには**  
次の`enable-ipam-organization-admin-account`例では、IPAM を AWS Organizations と統合し、メンバーアカウントを IPAM アカウントとして委任します。  

```
aws ec2 enable-ipam-organization-admin-account \
    --delegated-admin-account-id 320805250157
```
出力:  

```
{
    "Success": true
}
```
詳細については、*「Amazon VPC* [IPAM ユーザーガイド」の「IPAM と AWS Organizations の統合](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableIpamOrganizationAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-ipam-organization-admin-account.html)」を参照してください。

### `enable-reachability-analyzer-organization-sharing`
<a name="ec2_EnableReachabilityAnalyzerOrganizationSharing_cli_2_topic"></a>

次のコード例は、`enable-reachability-analyzer-organization-sharing` を使用する方法を示しています。

**AWS CLI**  
**Reachability Analyzer で信頼されたアクセスを有効にするには**  
次の `enable-reachability-analyzer-organization-sharing` の例では、Reachability Analyzer の信頼されたアクセスを有効にします。  

```
aws ec2 enable-reachability-analyzer-organization-sharing
```
このコマンドでは何も出力されません。  
詳細については、「*Reachability Analyzer ユーザーガイド*」の「[Cross-account analyses](https://docs.aws.amazon.com/vpc/latest/reachability/multi-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableReachabilityAnalyzerOrganizationSharing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-reachability-analyzer-organization-sharing.html)」を参照してください。

### `enable-serial-console-access`
<a name="ec2_EnableSerialConsoleAccess_cli_2_topic"></a>

次のコード例は、`enable-serial-console-access` を使用する方法を示しています。

**AWS CLI**  
**アカウントのシリアルコンソールへのアクセスを有効にするには**  
次の `enable-serial-console-access` の例では、シリアルコンソールへのアカウントアクセスを有効にします。  

```
aws ec2 enable-serial-console-access
```
出力:  

```
{
    "SerialConsoleAccessEnabled": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[EC2 Serial Console](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-serial-console.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableSerialConsoleAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-serial-console-access.html)」を参照してください。

### `enable-snapshot-block-public-access`
<a name="ec2_EnableSnapshotBlockPublicAccess_cli_2_topic"></a>

次のコード例は、`enable-snapshot-block-public-access` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのパブリックアクセスのブロックを有効にするには**  
次の `enable-snapshot-block-public-access` の例では、スナップショットのすべてのパブリック共有をブロックします。  

```
aws ec2 enable-snapshot-block-public-access \
    --state block-all-sharing
```
出力:  

```
{
    "State": "block-all-sharing"
}
```
詳細については、「*Amazon EBS ユーザーガイド*」の「[Block public access for snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/block-public-access-snapshots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableSnapshotBlockPublicAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-snapshot-block-public-access.html)」を参照してください。

### `enable-transit-gateway-route-table-propagation`
<a name="ec2_EnableTransitGatewayRouteTablePropagation_cli_2_topic"></a>

次のコード例は、`enable-transit-gateway-route-table-propagation` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway アタッチメントを有効にして、指定した伝播ルートテーブルにルートを伝播するには**  
次の `enable-transit-gateway-route-table-propagation` の例では、指定したアタッチメントが、指定した伝播ルートテーブルにルートを伝播することを有効にします。  

```
aws ec2 enable-transit-gateway-route-table-propagation \
    --transit-gateway-route-table-id tgw-rtb-0a823edbdeEXAMPLE \
    --transit-gateway-attachment-id tgw-attach-09b52ccdb5EXAMPLE
```
出力:  

```
{
    "Propagation": {
        "TransitGatewayAttachmentId": "tgw-attach-09b52ccdb5EXAMPLE",
        "ResourceId": "vpc-4d7de228",
        "ResourceType": "vpc",
        "TransitGatewayRouteTableId": "tgw-rtb-0a823edbdeEXAMPLE",
        "State": "disabled"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableTransitGatewayRouteTablePropagation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-transit-gateway-route-table-propagation.html)」を参照してください。

### `enable-vgw-route-propagation`
<a name="ec2_EnableVgwRoutePropagation_cli_2_topic"></a>

次のコード例は、`enable-vgw-route-propagation` を使用する方法を示しています。

**AWS CLI**  
**ルート伝播を有効にするには**  
この例では、指定された仮想プライベートゲートウェイが指定されたルートテーブルに静的ルートを伝播できるようにします。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 enable-vgw-route-propagation --route-table-id rtb-22574640 --gateway-id vgw-9a4cacf3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableVgwRoutePropagation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-vgw-route-propagation.html)」を参照してください。

### `enable-volume-io`
<a name="ec2_EnableVolumeIo_cli_2_topic"></a>

次のコード例は、`enable-volume-io` を使用する方法を示しています。

**AWS CLI**  
**ボリュームの I/O を有効にするには**  
この例では、ボリューム `vol-1234567890abcdef0` の I/O を有効にします。  
コマンド:  

```
aws ec2 enable-volume-io --volume-id vol-1234567890abcdef0
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableVolumeIo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-volume-io.html)」を参照してください。

### `enable-vpc-classic-link-dns-support`
<a name="ec2_EnableVpcClassicLinkDnsSupport_cli_2_topic"></a>

次のコード例は、`enable-vpc-classic-link-dns-support` を使用する方法を示しています。

**AWS CLI**  
**VPC の ClassicLink DNS サポートを有効にするには**  
この例では、`vpc-88888888` の ClassicLink DNS サポートを有効にします。  
コマンド:  

```
aws ec2 enable-vpc-classic-link-dns-support --vpc-id vpc-88888888
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableVpcClassicLinkDnsSupport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-vpc-classic-link-dns-support.html)」を参照してください。

### `enable-vpc-classic-link`
<a name="ec2_EnableVpcClassicLink_cli_2_topic"></a>

次のコード例は、`enable-vpc-classic-link` を使用する方法を示しています。

**AWS CLI**  
**ClassicLink 用に VPC を有効にするには**  
この例では、ClassicLink の vpc-8888888 を有効にします。  
コマンド:  

```
aws ec2 enable-vpc-classic-link --vpc-id vpc-88888888
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableVpcClassicLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/enable-vpc-classic-link.html)」を参照してください。

### `export-client-vpn-client-certificate-revocation-list`
<a name="ec2_ExportClientVpnClientCertificateRevocationList_cli_2_topic"></a>

次のコード例は、`export-client-vpn-client-certificate-revocation-list` を使用する方法を示しています。

**AWS CLI**  
**クライアント証明書失効リストをエクスポートするには**  
次の `export-client-vpn-client-certificate-revocation-list` の例では、指定したクライアント VPN エンドポイントのクライアント証明書失効リストをエクスポートします。この例では、読みやすくするために出力はテキスト形式で返されます。  

```
aws ec2 export-client-vpn-client-certificate-revocation-list \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --output text
```
出力:  

```
-----BEGIN X509 CRL-----
MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END X509 CRL-----
STATUS      pending
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client Certificate Revocation Lists](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-certificates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExportClientVpnClientCertificateRevocationList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/export-client-vpn-client-certificate-revocation-list.html)」を参照してください。

### `export-client-vpn-client-configuration`
<a name="ec2_ExportClientVpnClientConfiguration_cli_2_topic"></a>

次のコード例は、`export-client-vpn-client-configuration` を使用する方法を示しています。

**AWS CLI**  
**クライアント設定をエクスポートするには**  
次の `export-client-vpn-client-configuration` の例では、指定したクライアント VPN エンドポイントのクライアント設定をエクスポートします。この例では、読みやすくするために出力はテキスト形式で返されます。  

```
aws ec2 export-client-vpn-client-configuration \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --output text
```
出力:  

```
client
dev tun
proto udp
remote cvpn-endpoint-123456789123abcde.prod.clientvpn.ap-south-1.amazonaws.com 443
remote-random-hostname
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
cipher AES-256-GCM
verb 3
<ca>
-----BEGIN CERTIFICATE-----
MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----
</ca>
reneg-sec 0
```
詳細については、*AWS Client VPN 管理者ガイド*の「[クライアント VPN エンドポイント設定ファイルのエクスポート](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-endpoint-export.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExportClientVpnClientConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/export-client-vpn-client-configuration.html)」を参照してください。

### `export-image`
<a name="ec2_ExportImage_cli_2_topic"></a>

次のコード例は、`export-image` を使用する方法を示しています。

**AWS CLI**  
**AMI から VM をエクスポートするには**  
次の `export-image` の例では、指定した AMI を指定した形式で指定したバケットにエクスポートします。  

```
aws ec2 export-image \
    --image-id ami-1234567890abcdef0 \
    --disk-image-format VMDK \
    --s3-export-location S3Bucket=my-export-bucket,S3Prefix=exports/
```
出力:  

```
{
    "DiskImageFormat": "vmdk",
    "ExportImageTaskId": "export-ami-1234567890abcdef0"
    "ImageId": "ami-1234567890abcdef0",
    "RoleName": "vmimport",
    "Progress": "0",
    "S3ExportLocation": {
        "S3Bucket": "my-export-bucket",
        "S3Prefix": "exports/"
    },
    "Status": "active",
    "StatusMessage": "validating"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExportImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/export-image.html)」を参照してください。

### `get-associated-ipv6-pool-cidrs`
<a name="ec2_GetAssociatedIpv6PoolCidrs_cli_2_topic"></a>

次のコード例は、`get-associated-ipv6-pool-cidrs` を使用する方法を示しています。

**AWS CLI**  
**IPv6 アドレスプールの関連付けを取得するには**  
次の `get-associated-ipv6-pool-cidrs` の例では、指定した IPv6 アドレスプールの関連付けを取得します。  

```
aws ec2 get-associated-ipv6-pool-cidrs \
    --pool-id ipv6pool-ec2-012345abc12345abc
```
出力:  

```
{
    "Ipv6CidrAssociations": [
        {
            "Ipv6Cidr": "2001:db8:1234:1a00::/56",
            "AssociatedResource": "vpc-111111222222333ab"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAssociatedIpv6PoolCidrs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-associated-ipv6-pool-cidrs.html)」を参照してください。

### `get-aws-network-performance-data`
<a name="ec2_GetAwsNetworkPerformanceData_cli_2_topic"></a>

次のコード例は、`get-aws-network-performance-data` を使用する方法を示しています。

**AWS CLI**  
**ネットワークパフォーマンスデータを取得するには**  
次の `get-aws-network-performance-data` の例では、指定した期間内の指定したリージョン間のネットワークパフォーマンスに関するデータを取得します。  

```
aws ec2 get-aws-network-performance-data \
    --start-time 2022-10-26T12:00:00.000Z \
    --end-time 2022-10-26T12:30:00.000Z \
    --data-queries Id=my-query,Source=us-east-1,Destination=eu-west-1,Metric=aggregate-latency,Statistic=p50,Period=five-minutes
```
出力:  

```
{
    "DataResponses": [
        {
            "Id": "my-query",
            "Source": "us-east-1",
            "Destination": "eu-west-1",
            "Metric": "aggregate-latency",
            "Statistic": "p50",
            "Period": "five-minutes",
            "MetricPoints": [
                {
                    "StartDate": "2022-10-26T12:00:00+00:00",
                    "EndDate": "2022-10-26T12:05:00+00:00",
                    "Value": 62.44349,
                    "Status": "OK"
                },
                {
                    "StartDate": "2022-10-26T12:05:00+00:00",
                    "EndDate": "2022-10-26T12:10:00+00:00",
                    "Value": 62.483498,
                    "Status": "OK"
                },
                {
                    "StartDate": "2022-10-26T12:10:00+00:00",
                    "EndDate": "2022-10-26T12:15:00+00:00",
                    "Value": 62.51248,
                    "Status": "OK"
                },
                {
                    "StartDate": "2022-10-26T12:15:00+00:00",
                    "EndDate": "2022-10-26T12:20:00+00:00",
                    "Value": 62.635475,
                    "Status": "OK"
                },
                {
                    "StartDate": "2022-10-26T12:20:00+00:00",
                    "EndDate": "2022-10-26T12:25:00+00:00",
                    "Value": 62.733974,
                    "Status": "OK"
                },
                {
                    "StartDate": "2022-10-26T12:25:00+00:00",
                    "EndDate": "2022-10-26T12:30:00+00:00",
                    "Value": 62.773975,
                    "Status": "OK"
                },
                {
                    "StartDate": "2022-10-26T12:30:00+00:00",
                    "EndDate": "2022-10-26T12:35:00+00:00",
                    "Value": 62.75349,
                    "Status": "OK"
                }
            ]
        }
    ]
}
```
詳細については、「*インフラストラクチャのパフォーマンスのユーザーガイド*」の「[Monitor network performance](https://docs.aws.amazon.com/network-manager/latest/infrastructure-performance/nmip-performance-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAwsNetworkPerformanceData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-aws-network-performance-data.html)」を参照してください。

### `get-capacity-reservation-usage`
<a name="ec2_GetCapacityReservationUsage_cli_2_topic"></a>

次の例は、`get-capacity-reservation-usage` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウント間でキャパシティ予約の使用状況を表示するには**  
次の `get-capacity-reservation-usage` の例では、指定したキャパシティ予約の使用情報を表示します。  

```
aws ec2 get-capacity-reservation-usage \
    --capacity-reservation-id cr-1234abcd56EXAMPLE
```
出力:  

```
{
    "CapacityReservationId": "cr-1234abcd56EXAMPLE ",
    "InstanceUsages": [
        {
            "UsedInstanceCount": 1,
            "AccountId": "123456789012"
        }
    ],
    "AvailableInstanceCount": 4,
    "TotalInstanceCount": 5,
    "State": "active",
    "InstanceType": "t2.medium"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[共有キャパシティ予約](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservation-sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCapacityReservationUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-capacity-reservation-usage.html)」を参照してください。

### `get-coip-pool-usage`
<a name="ec2_GetCoipPoolUsage_cli_2_topic"></a>

次のコード例は、`get-coip-pool-usage` を使用する方法を示しています。

**AWS CLI**  
**顧客所有の IP アドレスプールの使用状況を取得するには**  
次の `get-coip-pool-usage` の例では、指定したカスタマー所有 IP アドレスプールの使用状況の詳細を取得します。  

```
aws ec2 get-coip-pool-usage \
    --pool-id ipv4pool-coip-123a45678bEXAMPLE
```
出力:  

```
{
    "CoipPoolId": "ipv4pool-coip-123a45678bEXAMPLE",
    "CoipAddressUsages": [
        {
            "CoIp": "0.0.0.0"
        },
        {
            "AllocationId": "eipalloc-123ab45c6dEXAMPLE",
            "AwsAccountId": "123456789012",
            "CoIp": "0.0.0.0"
        },
        {
            "AllocationId": "eipalloc-123ab45c6dEXAMPLE",
            "AwsAccountId": "123456789111",
            "CoIp": "0.0.0.0"
        }
    ],
    "LocalGatewayRouteTableId": "lgw-rtb-059615ef7dEXAMPLE"
}
```
詳細については、*AWS Outposts ラックユーザーガイド*の「[カスタマー所有の IP アドレス](https://docs.aws.amazon.com/outposts/latest/userguide/routing.html#ip-addressing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCoipPoolUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-coip-pool-usage.html)」を参照してください。

### `get-console-output`
<a name="ec2_GetConsoleOutput_cli_2_topic"></a>

次のコード例は、`get-console-output` を使用する方法を示しています。

**AWS CLI**  
**例 1: コンソール出力を取得するには**  
次の `get-console-output` の例では、指定した Linux インスタンスのコンソール出力を取得します。  

```
aws ec2 get-console-output \
    --instance-id i-1234567890abcdef0
```
出力:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "Timestamp": "2013-07-25T21:23:53.000Z",
    "Output": "..."
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[インスタンスコンソール出力](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output)」を参照してください。  
**例 2: 最新のコンソール出力を取得するには**  
次の `get-console-output` の例では、指定した Linux インスタンスの最新のコンソール出力を取得します。  

```
aws ec2 get-console-output \
    --instance-id i-1234567890abcdef0 \
    --latest \
    --output text
```
出力:  

```
i-1234567890abcdef0 [    0.000000] Command line: root=LABEL=/ console=tty1 console=ttyS0 selinux=0 nvme_core.io_timeout=4294967295
[    0.000000] x86/fpu: Supporting XSAVE feature 0x001: 'x87 floating point registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x002: 'SSE registers'
[    0.000000] x86/fpu: Supporting XSAVE feature 0x004: 'AVX registers'
...
Cloud-init v. 0.7.6 finished at Wed, 09 May 2018 19:01:13 +0000. Datasource DataSourceEc2.  Up 21.50 seconds
Amazon Linux AMI release 2018.03
Kernel 4.14.26-46.32.amzn1.x
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[インスタンスコンソール出力](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-console.html#instance-console-console-output)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConsoleOutput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-console-output.html)」を参照してください。

### `get-console-screenshot`
<a name="ec2_GetConsoleScreenshot_cli_2_topic"></a>

次のコード例は、`get-console-screenshot` を使用する方法を示しています。

**AWS CLI**  
**実行中のインスタンスのスクリーンショットを取得するには**  
次の `get-console-screenshot` の例では、指定したインスタンスのスクリーンショットを取得します。スクリーンショットは Base64 エンコード文字列として返されます。  

```
aws ec2 get-console-screenshot \
    --instance-id i-1234567890abcdef0
```
出力:  

```
{
    "ImageData": "997987/8kgj49ikjhewkwwe0008084EXAMPLE",
    "InstanceId": "i-1234567890abcdef0"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConsoleScreenshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-console-screenshot.html)」を参照してください。

### `get-default-credit-specification`
<a name="ec2_GetDefaultCreditSpecification_cli_2_topic"></a>

次のコード例は、`get-default-credit-specification` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのクレジットオプションを記述するには**  
次の `get-default-credit-specification` の例では、T2 インスタンスのデフォルトのクレジットオプションについて説明します。  

```
aws ec2 get-default-credit-specification \
    --instance-family t2
```
出力:  

```
{
    "InstanceFamilyCreditSpecification": {
        "InstanceFamily": "t2",
        "CpuCredits": "standard"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDefaultCreditSpecification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-default-credit-specification.html)」を参照してください。

### `get-ebs-default-kms-key-id`
<a name="ec2_GetEbsDefaultKmsKeyId_cli_2_topic"></a>

次のコード例は、`get-ebs-default-kms-key-id` を使用する方法を示しています。

**AWS CLI**  
**EBS 暗号化用のデフォルトの CMK を記述するには**  
次の`get-ebs-default-kms-key-id`例では、 AWS アカウントの EBS 暗号化用のデフォルトの CMK について説明します。  

```
aws ec2 get-ebs-default-kms-key-id
```
出力には、EBS 暗号化用のデフォルトの CMK が表示されます。これは、エイリアス を持つ AWS マネージド CMK です`alias/aws/ebs`。  

```
{
    "KmsKeyId": "alias/aws/ebs"
}
```
次の出力は、EBS 暗号化用のカスタム CMK を示します。  

```
{
    "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/0ea3fef3-80a7-4778-9d8c-1c0c6EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEbsDefaultKmsKeyId](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ebs-default-kms-key-id.html)」を参照してください。

### `get-ebs-encryption-by-default`
<a name="ec2_GetEbsEncryptionByDefault_cli_2_topic"></a>

次のコード例は、`get-ebs-encryption-by-default` を使用する方法を示しています。

**AWS CLI**  
**EBS 暗号化がデフォルトで有効になっているかどうかを記述するには**  
次の`get-ebs-encryption-by-default`例は、現在のリージョンの AWS アカウントで EBS 暗号化がデフォルトで有効になっているかどうかを示します。  

```
aws ec2 get-ebs-encryption-by-default
```
次の出力は、EBS 暗号化がデフォルトで無効になっていることを示します。  

```
{
    "EbsEncryptionByDefault": false
}
```
次の出力は、EBS 暗号化がデフォルトで有効になっていることを示します。  

```
{
    "EbsEncryptionByDefault": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEbsEncryptionByDefault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ebs-encryption-by-default.html)」を参照してください。

### `get-flow-logs-integration-template`
<a name="ec2_GetFlowLogsIntegrationTemplate_cli_2_topic"></a>

次のコード例は、`get-flow-logs-integration-template` を使用する方法を示しています。

**AWS CLI**  
**VPC フローログと Amazon Athena の統合を自動化する CloudFormation テンプレートを作成するには**  
次の `get-flow-logs-integration-template` の例では、VPC フローログと Amazon Athena の統合を自動化する CloudFormation テンプレートを作成します。  
Linux ：  

```
aws ec2 get-flow-logs-integration-template \
    --flow-log-id fl-1234567890abcdef0 \
    --config-delivery-s3-destination-arn arn:aws:s3:::amzn-s3-demo-bucket \
    --integrate-services AthenaIntegrations='[{IntegrationResultS3DestinationArn=arn:aws:s3:::amzn-s3-demo-bucket,PartitionLoadFrequency=none,PartitionStartDate=2021-07-21T00:40:00,PartitionEndDate=2021-07-21T00:42:00},{IntegrationResultS3DestinationArn=arn:aws:s3:::amzn-s3-demo-bucket,PartitionLoadFrequency=none,PartitionStartDate=2021-07-21T00:40:00,PartitionEndDate=2021-07-21T00:42:00}]'
```
Windows ：  

```
aws ec2 get-flow-logs-integration-template ^
    --flow-log-id fl-1234567890abcdef0 ^
    --config-delivery-s3-destination-arn arn:aws:s3:::amzn-s3-demo-bucket ^
    --integrate-services AthenaIntegrations=[{IntegrationResultS3DestinationArn=arn:aws:s3:::amzn-s3-demo-bucket,PartitionLoadFrequency=none,PartitionStartDate=2021-07-21T00:40:00,PartitionEndDate=2021-07-21T00:42:00},{IntegrationResultS3DestinationArn=arn:aws:s3:::amzn-s3-demo-bucket,PartitionLoadFrequency=none,PartitionStartDate=2021-07-21T00:40:00,PartitionEndDate=2021-07-21T00:42:00}]
```
出力:  

```
{
    "Result": "https://amzn-s3-demo-bucket.s3.us-east-2.amazonaws.com/VPCFlowLogsIntegrationTemplate_fl-1234567890abcdef0_Wed%20Jul%2021%2000%3A57%3A56%20UTC%202021.yml"
}
```
CloudFormation テンプレートの使用の詳細については、[AWS CloudFormation ユーザーガイド」の「CloudFormation テンプレートの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)」を参照してください。 *AWS CloudFormation *  
Amazon Athena とフローログの使用に関する詳細については、「*Amazon Virtual Private Cloud ユーザーガイド*」の「[Amazon Athena を使用したフローログのクエリ](https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs-athena.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFlowLogsIntegrationTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-flow-logs-integration-template.html)」を参照してください。

### `get-groups-for-capacity-reservation`
<a name="ec2_GetGroupsForCapacityReservation_cli_2_topic"></a>

次のコード例は、`get-groups-for-capacity-reservation` を使用する方法を示しています。

**AWS CLI**  
**キャパシティ予約のあるリソースグループを一覧表示するには**  
次の `get-groups-for-capacity-reservation` の例では、指定したキャパシティ予約が追加されたリソースグループを一覧表示します。  

```
aws ec2 get-groups-for-capacity-reservation \
    --capacity-reservation-id cr-1234abcd56EXAMPLE
```
出力:  

```
{
    "CapacityReservationsGroup": [
        {
            "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/my-resource-group",
            "OwnerId": "123456789012"
        }
    ]
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[キャパシティ予約グループ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-cr-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroupsForCapacityReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-groups-for-capacity-reservation.html)」を参照してください。

### `get-host-reservation-purchase-preview`
<a name="ec2_GetHostReservationPurchasePreview_cli_2_topic"></a>

次のコード例は、`get-host-reservation-purchase-preview` を使用する方法を示しています。

**AWS CLI**  
**専有ホストの予約の購入プレビューを取得するには**  
この例では、アカウント内の指定された専有ホストに対して指定された専有ホスト予約のコストをプレビューします。  
コマンド:  

```
aws ec2 get-host-reservation-purchase-preview --offering-id hro-03f707bf363b6b324 --host-id-set h-013abcd2a00cbd123
```
出力:  

```
{
  "TotalHourlyPrice": "1.499",
  "Purchase": [
      {
          "HourlyPrice": "1.499",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "HostIdSet": [
              "h-013abcd2a00cbd123"
          ],
          "UpfrontPrice": "0.000",
          "Duration": 31536000
      }
  ],
  "TotalUpfrontPrice": "0.000"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetHostReservationPurchasePreview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-host-reservation-purchase-preview.html)」を参照してください。

### `get-image-block-public-access-state`
<a name="ec2_GetImageBlockPublicAccessState_cli_2_topic"></a>

次のコード例は、`get-image-block-public-access-state` を使用する方法を示しています。

**AWS CLI**  
**指定したリージョンで AMI のパブリックアクセスのブロック状態を取得するには**  
次の `get-image-block-public-access-state` の例では、指定したリージョン内のアカウントレベルの AMI についてブロックパブリックアクセスを取得します。  

```
aws ec2 get-image-block-public-access-state \
    --region us-east-1
```
出力:  

```
{
    "ImageBlockPublicAccessState": "block-new-sharing"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Block public access to your AMIs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/sharingamis-intro.html#block-public-access-to-amis)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImageBlockPublicAccessState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-image-block-public-access-state.html)」を参照してください。

### `get-instance-types-from-instance-requirements`
<a name="ec2_GetInstanceTypesFromInstanceRequirements_cli_2_topic"></a>

次のコード例は、`get-instance-types-from-instance-requirements` を使用する方法を示しています。

**AWS CLI**  
**指定された属性に一致するインスタンスタイプをプレビューするには**  
次の `get-instance-types-from-instance-requirements` の例では、`--generate-cli-skeleton` パラメータを使用して指定できるすべての属性のリストを先に生成してから、そのリストを JSON ファイルに保存します。次に、JSON ファイルを使用して、一致するインスタンスタイプをプレビューする属性をカスタマイズします。  
指定できる属性をすべて生成し、出力を JSON ファイルに直接保存するには、次のコマンドを使用します。  

```
aws ec2 get-instance-types-from-instance-requirements \
    --region us-east-1 \
    --generate-cli-skeleton input > attributes.json
```
出力:  

```
{
    "DryRun": true,
    "ArchitectureTypes": [
        "x86_64_mac"
    ],
    "VirtualizationTypes": [
        "paravirtual"
    ],
    "InstanceRequirements": {
        "VCpuCount": {
            "Min": 0,
            "Max": 0
        },
        "MemoryMiB": {
            "Min": 0,
            "Max": 0
        },
        "CpuManufacturers": [
            "intel"
        ],
        "MemoryGiBPerVCpu": {
            "Min": 0.0,
            "Max": 0.0
        },
        "ExcludedInstanceTypes": [
            ""
        ],
        "InstanceGenerations": [
            "current"
        ],
        "SpotMaxPricePercentageOverLowestPrice": 0,
        "OnDemandMaxPricePercentageOverLowestPrice": 0,
        "BareMetal": "included",
        "BurstablePerformance": "excluded",
        "RequireHibernateSupport": true,
        "NetworkInterfaceCount": {
            "Min": 0,
            "Max": 0
        },
        "LocalStorage": "required",
        "LocalStorageTypes": [
            "hdd"
        ],
        "TotalLocalStorageGB": {
            "Min": 0.0,
            "Max": 0.0
        },
        "BaselineEbsBandwidthMbps": {
            "Min": 0,
            "Max": 0
        },
        "AcceleratorTypes": [
            "inference"
        ],
        "AcceleratorCount": {
            "Min": 0,
            "Max": 0
        },
        "AcceleratorManufacturers": [
            "xilinx"
        ],
        "AcceleratorNames": [
            "t4"
        ],
        "AcceleratorTotalMemoryMiB": {
            "Min": 0,
            "Max": 0
        }
    },
    "MaxResults": 0,
    "NextToken": ""
}
```
JSON ファイルを設定します。`ArchitectureTypes`、`VirtualizationTypes`、`VCpuCount`、および `MemoryMiB` の値を指定する必要があります。他の属性は省略できます。省略すると、デフォルト値が使用されます。各属性とそのデフォルト値の説明については、「get-instance-types-from-instance-requirements <https://docs.aws.amazon.com/cli/latest/reference/ec2/get-instance-types-from-instance-requirements.html>」を参照してください。  
`attributes.json` で指定された属性を持つインスタンスタイプをプレビューします。`--cli-input-json` パラメータを使用して、JSON ファイルの名前とパスを指定します。次のリクエストでは、出力はテーブル形式で提供されます。  

```
aws ec2 get-instance-types-from-instance-requirements \
    --cli-input-json file://attributes.json \
    --output table
```
`attributes.json` ファイルの内容。  

```
{

    "ArchitectureTypes": [
        "x86_64"
    ],
    "VirtualizationTypes": [
        "hvm"
    ],
    "InstanceRequirements": {
        "VCpuCount": {
            "Min": 4,
            "Max": 6
        },
        "MemoryMiB": {
            "Min": 2048
        },
        "InstanceGenerations": [
            "current"
        ]
    }
}
```
出力:  

```
------------------------------------------
|GetInstanceTypesFromInstanceRequirements|
+----------------------------------------+
||             InstanceTypes            ||
|+--------------------------------------+|
||             InstanceType             ||
|+--------------------------------------+|
||  c4.xlarge                           ||
||  c5.xlarge                           ||
||  c5a.xlarge                          ||
||  c5ad.xlarge                         ||
||  c5d.xlarge                          ||
||  c5n.xlarge                          ||
||  d2.xlarge                           ||
...
```
属性ベースのインスタンスタイプの選択の詳細については、「*Amazon EC2 ユーザーガイド*」の「[属性ベースのインスタンスタイプ選択の仕組み](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-fleet-attribute-based-instance-type-selection.html#ec2fleet-abs-how-it-works)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceTypesFromInstanceRequirements](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-instance-types-from-instance-requirements.html)」を参照してください。

### `get-instance-uefi-data`
<a name="ec2_GetInstanceUefiData_cli_2_topic"></a>

次のコード例は、`get-instance-uefi-data` を使用する方法を示しています。

**AWS CLI**  
**インスタンスから UEFI データを取得するには**  
次の `get-instance-uefi-data` の例では、インスタンスから UEFI データを取得します。出力が空の場合、インスタンスには UEFI データが含まれません。  

```
aws ec2 get-instance-uefi-data \
    --instance-id i-0123456789example
```
出力:  

```
{
    "InstanceId": "i-0123456789example",
    "UefiData": "QU1aTlVFRkkf+uLXAAAAAHj5a7fZ9+3dBzxXb/.
    <snipped>
    AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4L/J/AODshho="
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Amazon EC2 インスタンスの UEFI Secure Boot](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/uefi-secure-boot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceUefiData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-instance-uefi-data.html)」を参照してください。

### `get-ipam-address-history`
<a name="ec2_GetIpamAddressHistory_cli_2_topic"></a>

次のコード例は、`get-ipam-address-history` を使用する方法を示しています。

**AWS CLI**  
**CIDR の履歴を取得するには**  
次の `get-ipam-address-history` の例では、CIDR の履歴を取得します。  
(Linux):  

```
aws ec2 get-ipam-address-history \
   --cidr 10.0.0.0/16 \
   --ipam-scope-id ipam-scope-02fc38cd4c48e7d38 \
   --start-time 2021-12-08T01:00:00.000Z \
   --end-time 2021-12-10T01:00:00.000Z
```
(Windows):  

```
aws ec2 get-ipam-address-history ^
   --cidr 10.0.0.0/16 ^
   --ipam-scope-id ipam-scope-02fc38cd4c48e7d38 ^
   --start-time 2021-12-08T01:00:00.000Z ^
   --end-time 2021-12-10T01:00:00.000Z
```
出力:  

```
{
    "HistoryRecords": [
        {
            "ResourceOwnerId": "123456789012",
            "ResourceRegion": "us-west-1",
            "ResourceType": "vpc",
            "ResourceId": "vpc-06cbefa9ee907e1c0",
            "ResourceCidr": "10.0.0.0/16",
            "ResourceName": "Demo",
            "ResourceComplianceStatus": "unmanaged",
            "ResourceOverlapStatus": "overlapping",
            "VpcId": "vpc-06cbefa9ee907e1c0",
            "SampledStartTime": "2021-12-08T19:54:57.675000+00:00"
        },
        {
            "ResourceOwnerId": "123456789012",
            "ResourceRegion": "us-east-2",
            "ResourceType": "vpc",
            "ResourceId": "vpc-042702f474812c9ad",
            "ResourceCidr": "10.0.0.0/16",
            "ResourceName": "test",
            "ResourceComplianceStatus": "unmanaged",
            "ResourceOverlapStatus": "overlapping",
            "VpcId": "vpc-042702f474812c9ad",
            "SampledStartTime": "2021-12-08T19:54:59.019000+00:00"
        },
        {
            "ResourceOwnerId": "123456789012",
            "ResourceRegion": "us-east-2",
            "ResourceType": "vpc",
            "ResourceId": "vpc-042b8a44f64267d67",
            "ResourceCidr": "10.0.0.0/16",
            "ResourceName": "tester",
            "ResourceComplianceStatus": "unmanaged",
            "ResourceOverlapStatus": "overlapping",
            "VpcId": "vpc-042b8a44f64267d67",
            "SampledStartTime": "2021-12-08T19:54:59.019000+00:00"
        }
    ]
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[View the history of IP addresses](https://docs.aws.amazon.com/vpc/latest/ipam/view-history-cidr-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpamAddressHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ipam-address-history.html)」を参照してください。

### `get-ipam-discovered-accounts`
<a name="ec2_GetIpamDiscoveredAccounts_cli_2_topic"></a>

次のコード例は、`get-ipam-discovered-accounts` を使用する方法を示しています。

**AWS CLI**  
**IPAM によって検出されたアカウントを表示するには**  
このシナリオでは、IPAM が検出するリソースを所有する AWS アカウントを表示したい IPAM 委任管理者です。  
`--discovery-region` は、モニタリング対象のアカウントステータスを表示する IPAM 運用リージョンです。例えば、3 つの IPAM 運用リージョンがある場合、このリクエストを 3 回実行して、それらの各リージョンで検出に固有のタイムスタンプを表示することができます。  
次の の`get-ipam-discovered-accounts`例では、IPAM が検出するリソースを所有する AWS アカウントを一覧表示します。  

```
aws ec2 get-ipam-discovered-accounts \
   --ipam-resource-discovery-id ipam-res-disco-0365d2977fc1672fe \
   --discovery-region us-east-1
```
出力:  

```
{
    "IpamDiscoveredAccounts": [
        {
            "AccountId": "149977607591",
            "DiscoveryRegion": "us-east-1",
            "LastAttemptedDiscoveryTime": "2024-02-09T19:04:31.379000+00:00",
            "LastSuccessfulDiscoveryTime": "2024-02-09T19:04:31.379000+00:00"
        }
    ]
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Integrate IPAM with accounts outside of your organization](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpamDiscoveredAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ipam-discovered-accounts.html)」を参照してください。

### `get-ipam-discovered-public-addresses`
<a name="ec2_GetIpamDiscoveredPublicAddresses_cli_2_topic"></a>

次のコード例は、`get-ipam-discovered-public-addresses` を使用する方法を示しています。

**AWS CLI**  
**検出されたパブリック IP アドレスを表示するには**  
この例では、あなたは IPAM の委任された管理者として、IPAM が検出したリソースの IP アドレスを表示したいと考えています。[describe-ipam-resource-discoveries](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-ipam-resource-discoveries.html) を使用してリソース検出 ID を取得できます。  
次の `get-ipam-discovered-public-addresses` の例では、リソース検出で検出されたパブリック IP アドレスを表示します。  

```
aws ec2 get-ipam-discovered-public-addresses \
    --ipam-resource-discovery-id ipam-res-disco-0f4ef577a9f37a162 \
    --address-region us-east-1 \
    --region us-east-1
```
出力:  

```
{
    "IpamDiscoveredPublicAddresses": [
        {
           "IpamResourceDiscoveryId": "ipam-res-disco-0f4ef577a9f37a162",
            "AddressRegion": "us-east-1",
            "Address": "54.208.155.7",
            "AddressOwnerId": "320805250157",
            "AssociationStatus": "associated",
            "AddressType": "ec2-public-ip",
            "VpcId": "vpc-073b294916198ce49",
            "SubnetId": "subnet-0b6c8a8839e9a4f15",
            "NetworkInterfaceId": "eni-081c446b5284a5e06",
            "NetworkInterfaceDescription": "",
            "InstanceId": "i-07459a6fca5b35823",
            "Tags": {},
            "NetworkBorderGroup": "us-east-1c",
            "SecurityGroups": [
                {
                    "GroupName": "launch-wizard-2",
                    "GroupId": "sg-0a489dd6a65c244ce"
                }
            ],
            "SampleTime": "2024-04-05T15:13:59.228000+00:00"
        },
        {
            "IpamResourceDiscoveryId": "ipam-res-disco-0f4ef577a9f37a162",
            "AddressRegion": "us-east-1",
            "Address": "44.201.251.218",
            "AddressOwnerId": "470889052923",
            "AssociationStatus": "associated",
            "AddressType": "ec2-public-ip",
            "VpcId": "vpc-6c31a611",
            "SubnetId": "subnet-062f47608b99834b1",
            "NetworkInterfaceId": "eni-024845359c2c3ae9b",
            "NetworkInterfaceDescription": "",
            "InstanceId": "i-04ef786d9c4e03f41",
            "Tags": {},
            "NetworkBorderGroup": "us-east-1a",
            "SecurityGroups": [
                {
                    "GroupName": "launch-wizard-32",
                    "GroupId": "sg-0ed1a426e96a68374"
                }
            ],
            "SampleTime": "2024-04-05T15:13:59.145000+00:00"
        }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[View public IP insights](https://docs.aws.amazon.com/vpc/latest/ipam/view-public-ip-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpamDiscoveredPublicAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ipam-discovered-public-addresses.html)」を参照してください。

### `get-ipam-discovered-resource-cidrs`
<a name="ec2_GetIpamDiscoveredResourceCidrs_cli_2_topic"></a>

次のコード例は、`get-ipam-discovered-resource-cidrs` を使用する方法を示しています。

**AWS CLI**  
**IPAM によって検出された IP アドレス CIDR を表示するには**  
この例では、あなたは IPAM の委任された管理者として、IPAM が検出するリソースの IP アドレス CIDR に関連する詳細を表示したいと考えています。  
このリクエストを完了するには:  
選択したリソース検出は IPAM に関連付ける必要があります。 `--resource-region`はリソースが作成された AWS リージョンです。  
次の `get-ipam-discovered-resource-cidrs` の例では、IPAM が検出するリソースの IP アドレスを一覧表示します。  

```
aws ec2 get-ipam-discovered-resource-cidrs \
   --ipam-resource-discovery-id ipam-res-disco-0365d2977fc1672fe \
   --resource-region us-east-1
```
出力:  

```
{
    {
        "IpamDiscoveredResourceCidrs": [
        {
            "IpamResourceDiscoveryId": "ipam-res-disco-0365d2977fc1672fe",
            "ResourceRegion": "us-east-1",
            "ResourceId": "vpc-0c974c95ca7ceef4a",
            "ResourceOwnerId": "149977607591",
            "ResourceCidr": "172.31.0.0/16",
            "ResourceType": "vpc",
            "ResourceTags": [],
            "IpUsage": 0.375,
            "VpcId": "vpc-0c974c95ca7ceef4a",
            "SampleTime": "2024-02-09T19:15:16.529000+00:00"
        },
        {
            "IpamResourceDiscoveryId": "ipam-res-disco-0365d2977fc1672fe",
            "ResourceRegion": "us-east-1",
            "ResourceId": "subnet-07fe028119082a8c1",
            "ResourceOwnerId": "149977607591",
            "ResourceCidr": "172.31.0.0/20",
            "ResourceType": "subnet",
            "ResourceTags": [],
            "IpUsage": 0.0012,
            "VpcId": "vpc-0c974c95ca7ceef4a",
            "SampleTime": "2024-02-09T19:15:16.529000+00:00"
        },
        {
            "IpamResourceDiscoveryId": "ipam-res-disco-0365d2977fc1672fe",
            "ResourceRegion": "us-east-1",
            "ResourceId": "subnet-0a96893763984cc4e",
            "ResourceOwnerId": "149977607591",
            "ResourceCidr": "172.31.64.0/20",
            "ResourceType": "subnet",
            "ResourceTags": [],
            "IpUsage": 0.0012,
            "VpcId": "vpc-0c974c95ca7ceef4a",
            "SampleTime": "2024-02-09T19:15:16.529000+00:00"
        }
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Monitor CIDR usage by resource](https://docs.aws.amazon.com/vpc/latest/ipam/monitor-cidr-compliance-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpamDiscoveredResourceCidrs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ipam-discovered-resource-cidrs.html)」を参照してください。

### `get-ipam-pool-allocations`
<a name="ec2_GetIpamPoolAllocations_cli_2_topic"></a>

次のコード例は、`get-ipam-pool-allocations` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールから割り当てられた CIDR を取得するには**  
次の `get-ipam-pool-allocations` の例では、IPAM プールから割り当てられた CIDR を一覧表示します。  
(Linux):  

```
aws ec2 get-ipam-pool-allocations \
    --ipam-pool-id ipam-pool-0533048da7d823723 \
    --filters Name=ipam-pool-allocation-id,Values=ipam-pool-alloc-0e6186d73999e47389266a5d6991e6220
```
(Windows):  

```
aws ec2 get-ipam-pool-allocations ^
    --ipam-pool-id ipam-pool-0533048da7d823723 ^
    --filters Name=ipam-pool-allocation-id,Values=ipam-pool-alloc-0e6186d73999e47389266a5d6991e6220
```
出力:  

```
{
    "IpamPoolAllocations": [
        {
            "Cidr": "10.0.0.0/16",
            "IpamPoolAllocationId": "ipam-pool-alloc-0e6186d73999e47389266a5d6991e6220",
            "ResourceType": "custom",
            "ResourceOwner": "123456789012"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpamPoolAllocations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ipam-pool-allocations.html)」を参照してください。

### `get-ipam-pool-cidrs`
<a name="ec2_GetIpamPoolCidrs_cli_2_topic"></a>

次のコード例は、`get-ipam-pool-cidrs` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールにプロビジョニングされた CIDR を取得するには**  
次の `get-ipam-pool-cidrs` の例では、IPAM プールにプロビジョニングされた CIDR を取得します。  
(Linux):  

```
aws ec2 get-ipam-pool-cidrs \
    --ipam-pool-id ipam-pool-0533048da7d823723 \
    --filters 'Name=cidr,Values=10.*'
```
(Windows):  

```
aws ec2 get-ipam-pool-cidrs ^
    --ipam-pool-id ipam-pool-0533048da7d823723 ^
    --filters Name=cidr,Values=10.*
```
出力:  

```
{
    "IpamPoolCidr": {
        "Cidr": "10.0.0.0/24",
        "State": "provisioned"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpamPoolCidrs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ipam-pool-cidrs.html)」を参照してください。

### `get-ipam-resource-cidrs`
<a name="ec2_GetIpamResourceCidrs_cli_2_topic"></a>

次のコード例は、`get-ipam-resource-cidrs` を使用する方法を示しています。

**AWS CLI**  
**リソースに割り当てられた CIDR を取得するには**  
次の `get-ipam-resource-cidrs` の例では、リソースに割り当てられた CIDR を取得します。  
(Linux):  

```
aws ec2 get-ipam-resource-cidrs \
    --ipam-scope-id ipam-scope-02fc38cd4c48e7d38 \
    --filters Name=management-state,Values=unmanaged
```
(Windows):  

```
aws ec2 get-ipam-resource-cidrs ^
    --ipam-scope-id ipam-scope-02fc38cd4c48e7d38 ^
    --filters Name=management-state,Values=unmanaged
```
出力:  

```
{
    "IpamResourceCidrs": [
        {
            "IpamId": "ipam-08440e7a3acde3908",
            "IpamScopeId": "ipam-scope-02fc38cd4c48e7d38",
            "ResourceRegion": "us-east-2",
            "ResourceOwnerId": "123456789012",
            "ResourceId": "vpc-621b8709",
            "ResourceName": "Default AWS VPC",
            "ResourceCidr": "172.33.0.0/16",
            "ResourceType": "vpc",
            "ResourceTags": [
                {
                    "Key": "Environment",
                    "Value": "Test"
                },
                {
                    "Key": "Name",
                    "Value": "Default AWS VPC"
                }
            ],
            "IpUsage": 0.0039,
            "ComplianceStatus": "unmanaged",
            "ManagementState": "unmanaged",
            "OverlapStatus": "nonoverlapping",
            "VpcId": "vpc-621b8709"
        }
    ]
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Monitor CIDR usage by resource](https://docs.aws.amazon.com/vpc/latest/ipam/monitor-cidr-compliance-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpamResourceCidrs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-ipam-resource-cidrs.html)」を参照してください。

### `get-launch-template-data`
<a name="ec2_GetLaunchTemplateData_cli_2_topic"></a>

次のコード例は、`get-launch-template-data` を使用する方法を示しています。

**AWS CLI**  
**起動テンプレートのインスタンスデータを取得するには**  
この例では、指定されたインスタンスに関するデータを取得し、`--query` オプションを使用して `LaunchTemplateData` 内の内容を返します。出力をベースとして使用して、新しい起動テンプレートや起動テンプレートのバージョンを作成できます。  
コマンド:  

```
aws ec2 get-launch-template-data --instance-id i-0123d646e8048babc --query 'LaunchTemplateData'
```
出力:  

```
{
      "Monitoring": {},
      "ImageId": "ami-8c1be5f6",
      "BlockDeviceMappings": [
          {
              "DeviceName": "/dev/xvda",
              "Ebs": {
                  "DeleteOnTermination": true
              }
          }
      ],
      "EbsOptimized": false,
      "Placement": {
          "Tenancy": "default",
          "GroupName": "",
          "AvailabilityZone": "us-east-1a"
      },
      "InstanceType": "t2.micro",
      "NetworkInterfaces": [
          {
              "Description": "",
              "NetworkInterfaceId": "eni-35306abc",
              "PrivateIpAddresses": [
                  {
                      "Primary": true,
                      "PrivateIpAddress": "10.0.0.72"
                  }
              ],
              "SubnetId": "subnet-7b16de0c",
              "Groups": [
                  "sg-7c227019"
              ],
              "Ipv6Addresses": [
                  {
                      "Ipv6Address": "2001:db8:1234:1a00::123"
                  }
              ],
              "PrivateIpAddress": "10.0.0.72"
          }
      ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLaunchTemplateData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-launch-template-data.html)」を参照してください。

### `get-managed-prefix-list-associations`
<a name="ec2_GetManagedPrefixListAssociations_cli_2_topic"></a>

次のコード例は、`get-managed-prefix-list-associations` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストの関連付けを取得するには**  
次の `get-managed-prefix-list-associations` の例では、指定したプレフィックスリストに関連付けられたリソースを取得します。  

```
aws ec2 get-managed-prefix-list-associations \
    --prefix-list-id pl-0123456abcabcabc1
```
出力:  

```
{
    "PrefixListAssociations": [
        {
            "ResourceId": "sg-0abc123456abc12345",
            "ResourceOwner": "123456789012"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Managed prefix lists](https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetManagedPrefixListAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-managed-prefix-list-associations.html)」を参照してください。

### `get-managed-prefix-list-entries`
<a name="ec2_GetManagedPrefixListEntries_cli_2_topic"></a>

次のコード例は、`get-managed-prefix-list-entries` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストのエントリを取得するには**  
次の `get-managed-prefix-list-entries` では、指定されたプレフィックスリストのエントリを取得します。  

```
aws ec2 get-managed-prefix-list-entries \
    --prefix-list-id pl-0123456abcabcabc1
```
出力:  

```
{
    "Entries": [
        {
            "Cidr": "10.0.0.0/16",
            "Description": "vpc-a"
        },
        {
            "Cidr": "10.2.0.0/16",
            "Description": "vpc-b"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Managed prefix lists](https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetManagedPrefixListEntries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-managed-prefix-list-entries.html)」を参照してください。

### `get-network-insights-access-scope-analysis-findings`
<a name="ec2_GetNetworkInsightsAccessScopeAnalysisFindings_cli_2_topic"></a>

次のコード例は、`get-network-insights-access-scope-analysis-findings` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインサイトのアクセス範囲析の結果を取得するには**  
次の の`get-network-insights-access-scope-analysis-findings`例では、 AWS アカウントで選択したスコープ分析結果を取得します。  

```
aws ec2 get-network-insights-access-scope-analysis-findings \
    --region us-east-1 \
    --network-insights-access-scope-analysis-id nis \
    --nis-123456789111
```
出力:  

```
{
    "NetworkInsightsAccessScopeAnalysisId": "nisa-123456789222",
    "AnalysisFindings": [
        {
            "NetworkInsightsAccessScopeAnalysisId": "nisa-123456789222",
            "NetworkInsightsAccessScopeId": "nis-123456789111",
            "FindingComponents": [
                {
                    "SequenceNumber": 1,
                    "Component": {
                        "Id": "eni-02e3d42d5cceca67d",
                        "Arn": "arn:aws:ec2:us-east-1:936459623503:network-interface/eni-02e3d32d9cceca17d"
                    },
                    "OutboundHeader": {
                        "DestinationAddresses": [
                            "0.0.0.0/5",
                            "11.0.0.0/8",
                            "12.0.0.0/6",
                            "128.0.0.0/3",
                            "16.0.0.0/4",
                            "160.0.0.0/5",
                            "168.0.0.0/6",
                            "172.0.0.0/12"
                            "8.0.0.0/7"
                        ],
                        "DestinationPortRanges": [
                            {
                                "From": 0,
                                "To": 65535
                            }
                        ],
                        "Protocol": "6",
                        "SourceAddresses": [
                            "10.0.2.253/32"
                        ],
                        "SourcePortRanges": [
                            {
                                "From": 0,
                                "To": 65535
                            }
                        ]
                    }, [etc]
                ]
            }
        }
    ]
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetNetworkInsightsAccessScopeAnalysisFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-network-insights-access-scope-analysis-findings.html)」を参照してください。

### `get-network-insights-access-scope-content`
<a name="ec2_GetNetworkInsightsAccessScopeContent_cli_2_topic"></a>

次のコード例は、`get-network-insights-access-scope-content` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインサイトのアクセス範囲の内容を取得するには**  
次の の`get-network-insights-access-scope-content`例では、 AWS アカウントで選択したスコープ分析 ID のコンテンツを取得します。  

```
aws ec2 get-network-insights-access-scope-content \
    --region us-east-1 \
    --network-insights-access-scope-id nis-123456789222
```
出力:  

```
{
    "NetworkInsightsAccessScopeContent": {
        "NetworkInsightsAccessScopeId": "nis-123456789222",
        "MatchPaths": [
            {
                "Source": {
                    "ResourceStatement": {
                        "ResourceTypes": [
                            "AWS::EC2::NetworkInterface"
                        ]
                    }
                },
                "Destination": {
                    "ResourceStatement": {
                        "ResourceTypes": [
                            "AWS::EC2::InternetGateway"
                        ]
                    }
                }
            }
        ]
    }
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetNetworkInsightsAccessScopeContent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-network-insights-access-scope-content.html)」を参照してください。

### `get-password-data`
<a name="ec2_GetPasswordData_cli_2_topic"></a>

次のコード例は、`get-password-data` を使用する方法を示しています。

**AWS CLI**  
**暗号化されたパスワードを取得するには**  
この例では、暗号化されたパスワードを取得します。  
コマンド:  

```
aws ec2 get-password-data --instance-id i-1234567890abcdef0
```
出力:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "Timestamp": "2013-08-07T22:18:38.000Z",
    "PasswordData": "gSlJFq+VpcZXqy+iktxMF6NyxQ4qCrT4+gaOuNOenX1MmgXPTj7XEXAMPLE
UQ+YeFfb+L1U4C4AKv652Ux1iRB3CPTYP7WmU3TUnhsuBd+p6LVk7T2lKUml6OXbk6WPW1VYYm/TRPB1
e1DQ7PY4an/DgZT4mwcpRFigzhniQgDDeO1InvSDcwoUTwNs0Y1S8ouri2W4n5GNlriM3Q0AnNVelVz/
53TkDtxbNoU606M1gK9zUWSxqEgwvbV2j8c5rP0WCuaMWSFl4ziDu4bd7q+4RSyi8NUsVWnKZ4aEZffu
DPGzKrF5yLlf3etP2L4ZR6CvG7K1hx7VKOQVN32Dajw=="
}
```
**復号されたパスワードを取得するには**  
この例では、復号されたパスワードを取得します。  
コマンド:  

```
aws ec2 get-password-data --instance-id  i-1234567890abcdef0 --priv-launch-key C:\Keys\MyKeyPair.pem
```
出力:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "Timestamp": "2013-08-30T23:18:05.000Z",
    "PasswordData": "&ViJ652e*u"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPasswordData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-password-data.html)」を参照してください。

### `get-reserved-instances-exchange-quote`
<a name="ec2_GetReservedInstancesExchangeQuote_cli_2_topic"></a>

次のコード例は、`get-reserved-instances-exchange-quote` を使用する方法を示しています。

**AWS CLI**  
**コンバーティブルリザーブドインスタンスの交換の見積りを取得するには**  
この例では、指定されたコンバーティブルリザーブドインスタンスの交換情報を取得します。  
コマンド:  

```
aws ec2 get-reserved-instances-exchange-quote --reserved-instance-ids 7b8750c3-397e-4da4-bbcb-a45ebexample --target-configurations OfferingId=6fea5434-b379-434c-b07b-a7abexample
```
出力:  

```
{
  "CurrencyCode": "USD",
  "ReservedInstanceValueSet": [
      {
          "ReservedInstanceId": "7b8750c3-397e-4da4-bbcb-a45ebexample",
          "ReservationValue": {
              "RemainingUpfrontValue": "0.000000",
              "HourlyPrice": "0.027800",
              "RemainingTotalValue": "730.556200"
          }
      }
  ],
  "PaymentDue": "424.983828",
  "TargetConfigurationValueSet": [
      {
          "TargetConfiguration": {
              "InstanceCount": 5,
              "OfferingId": "6fea5434-b379-434c-b07b-a7abexample"
          },
          "ReservationValue": {
              "RemainingUpfrontValue": "424.983828",
              "HourlyPrice": "0.016000",
              "RemainingTotalValue": "845.447828"
          }
      }
  ],
  "IsValidExchange": true,
  "OutputReservedInstancesWillExpireAt": "2020-10-01T13:03:39Z",
  "ReservedInstanceValueRollup": {
      "RemainingUpfrontValue": "0.000000",
      "HourlyPrice": "0.027800",
      "RemainingTotalValue": "730.556200"
  },
  "TargetConfigurationValueRollup": {
      "RemainingUpfrontValue": "424.983828",
      "HourlyPrice": "0.016000",
      "RemainingTotalValue": "845.447828"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReservedInstancesExchangeQuote](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-reserved-instances-exchange-quote.html)」を参照してください。

### `get-security-groups-for-vpc`
<a name="ec2_GetSecurityGroupsForVpc_cli_2_topic"></a>

次のコード例は、`get-security-groups-for-vpc` を使用する方法を示しています。

**AWS CLI**  
**指定した VPC のネットワークインターフェイスに関連付けることができるセキュリティグループを表示するには。**  
次の `get-security-groups-for-vpc` の例では、VPC 内のネットワークインターフェイスに関連付けることができるセキュリティグループを表示します。  

```
aws ec2 get-security-groups-for-vpc \
    --vpc-id vpc-6c31a611 \
    --region us-east-1
```
出力:  

```
{
    "SecurityGroupForVpcs": [
        {
            "Description": "launch-wizard-36 created 2022-08-29T15:59:35.338Z",
            "GroupName": "launch-wizard-36",
            "OwnerId": "470889052923",
            "GroupId": "sg-007e0c3027ee885f5",
            "Tags": [],
            "PrimaryVpcId": "vpc-6c31a611"
        },
        {
            "Description": "launch-wizard-18 created 2024-01-19T20:22:27.527Z",
            "GroupName": "launch-wizard-18",
            "OwnerId": "470889052923",
            "GroupId": "sg-0147193bef51c9eef",
            "Tags": [],
            "PrimaryVpcId": "vpc-6c31a611"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSecurityGroupsForVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-security-groups-for-vpc.html)」を参照してください。

### `get-serial-console-access-status`
<a name="ec2_GetSerialConsoleAccessStatus_cli_2_topic"></a>

次のコード例は、`get-serial-console-access-status` を使用する方法を示しています。

**AWS CLI**  
**シリアルコンソールへのアカウントアクセスのステータスを表示するには**  
次の `get-serial-console-access-status` の例では、アカウントでシリアルコンソールアクセスが有効になっているかどうかを判断します。  

```
aws ec2 get-serial-console-access-status
```
出力:  

```
{
    "SerialConsoleAccessEnabled": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[EC2 Serial Console](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-serial-console.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSerialConsoleAccessStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-serial-console-access-status.html)」を参照してください。

### `get-snapshot-block-public-access-state`
<a name="ec2_GetSnapshotBlockPublicAccessState_cli_2_topic"></a>

次のコード例は、`get-snapshot-block-public-access-state` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのパブリックアクセスブロックの現在の状態を取得するには**  
次の `get-snapshot-block-public-access-state` の例では、スナップショットのパブリックアクセスブロックの現在の状態を取得します。  

```
aws ec2 get-snapshot-block-public-access-state
```
出力:  

```
{
    "State": "block-all-sharing"
}
```
詳細については、「*Amazon EBS ユーザーガイド*」の「[Block public access for snapshots](https://docs.aws.amazon.com/ebs/latest/userguide/block-public-access-snapshots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSnapshotBlockPublicAccessState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-snapshot-block-public-access-state.html)」を参照してください。

### `get-spot-placement-scores`
<a name="ec2_GetSpotPlacementScores_cli_2_topic"></a>

次のコード例は、`get-spot-placement-scores` を使用する方法を示しています。

**AWS CLI**  
**指定された要件のスポットプレイスメントスコアを計算するには**  
次の `get-spot-placement-scores` の例では、`--generate-cli-skeleton` パラメータを使用してスポットプレイスメントスコア設定に指定できるすべてのパラメータのリストを先に生成してから、そのリストを JSON ファイルに保存します。次に、JSON ファイルを使用して、スポットプレイスメントスコアの計算に使用する要件を設定します。  
スポットプレイスメントスコア設定に指定できるすべてのパラメータを生成し、出力を JSON ファイルに直接保存します。  

```
aws ec2 get-spot-placement-scores \
    --region us-east-1 \
    --generate-cli-skeleton input > attributes.json
```
出力:  

```
{
    "InstanceTypes": [
        ""
    ],
    "TargetCapacity": 0,
    "TargetCapacityUnitType": "vcpu",
    "SingleAvailabilityZone": true,
    "RegionNames": [
        ""
    ],
    "InstanceRequirementsWithMetadata": {
        "ArchitectureTypes": [
            "x86_64_mac"
        ],
        "VirtualizationTypes": [
            "hvm"
        ],
        "InstanceRequirements": {
            "VCpuCount": {
                "Min": 0,
                "Max": 0
            },
            "MemoryMiB": {
                "Min": 0,
                "Max": 0
            },
            "CpuManufacturers": [
                "amd"
            ],
            "MemoryGiBPerVCpu": {
                "Min": 0.0,
                "Max": 0.0
            },
            "ExcludedInstanceTypes": [
                ""
            ],
            "InstanceGenerations": [
                "previous"
            ],
            "SpotMaxPricePercentageOverLowestPrice": 0,
            "OnDemandMaxPricePercentageOverLowestPrice": 0,
            "BareMetal": "excluded",
            "BurstablePerformance": "excluded",
            "RequireHibernateSupport": true,
            "NetworkInterfaceCount": {
                "Min": 0,
                "Max": 0
            },
            "LocalStorage": "included",
            "LocalStorageTypes": [
                "hdd"
            ],
            "TotalLocalStorageGB": {
                "Min": 0.0,
                "Max": 0.0
            },
            "BaselineEbsBandwidthMbps": {
                "Min": 0,
                "Max": 0
            },
            "AcceleratorTypes": [
                "fpga"
            ],
            "AcceleratorCount": {
                "Min": 0,
                "Max": 0
            },
            "AcceleratorManufacturers": [
                "amd"
            ],
            "AcceleratorNames": [
                "vu9p"
            ],
            "AcceleratorTotalMemoryMiB": {
                "Min": 0,
                "Max": 0
            }
        }
    },
    "DryRun": true,
    "MaxResults": 0,
    "NextToken": ""
}
```
JSON ファイルを設定します。`TargetCapacity` の値を指定する必要があります。各パラメータとそのデフォルト値の説明については、「スポットプレイスメントスコアの計算 (AWS CLI) <https://docs.aws.amazon.com/AWS EC2/latest/UserGuide/spot-placement-score.html\$1calculate-sps-cli>」を参照してください。  
`attributes.json` で指定された要件のスポットプレイスメントスコアを計算します。`--cli-input-json` パラメータを使用して、JSON ファイルの名前とパスを指定します。  

```
aws ec2 get-spot-placement-scores \
    --region us-east-1 \
    --cli-input-json file://attributes.json
```
`SingleAvailabilityZone` が `false` に設定されているか、省略されている場合は出力します (省略されている場合、デフォルトで `false` になります)。リージョンのスコアリストが返されます。  

```
"Recommendation": [
    {
        "Region": "us-east-1",
        "Score": 7
    },
    {
        "Region": "us-west-1",
        "Score": 5
    },
   ...
```
`SingleAvailabilityZone` が `true` に設定されている場合は出力します。SingleAvailability Zones のスコアリストが返されます。  

```
"Recommendation": [
    {
        "Region": "us-east-1",
        "AvailabilityZoneId": "use1-az1"
        "Score": 8
    },
    {
        "Region": "us-east-1",
        "AvailabilityZoneId": "usw2-az3"
        "Score": 6
    },
   ...
```
スポットプレイスメントスコアの計算の詳細について、および設定例については、「*Amazon EC2 ユーザーガイド*」の「[Calculate a Spot placement score](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-placement-score.html#work-with-spot-placement-score)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSpotPlacementScores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-spot-placement-scores.html)」を参照してください。

### `get-subnet-cidr-reservations`
<a name="ec2_GetSubnetCidrReservations_cli_2_topic"></a>

次のコード例は、`get-subnet-cidr-reservations` を使用する方法を示しています。

**AWS CLI**  
**サブネット CIDR 予約に関する情報を取得するには**  
次の `get-subnet-cidr-reservations` の例では、指定したサブネット CIDR 予約の情報を表示します。  

```
aws ec2 get-subnet-cidr-reservations \
    --subnet-id subnet-03c51e2e6cEXAMPLE
```
出力:  

```
{
    "SubnetIpv4CidrReservations": [
        {
            "SubnetCidrReservationId": "scr-044f977c4eEXAMPLE",
            "SubnetId": "subnet-03c51e2e6cEXAMPLE",
            "Cidr": "10.1.0.16/28",
            "ReservationType": "prefix",
            "OwnerId": "123456789012"
        }
    ],
    "SubnetIpv6CidrReservations": []
}
```
詳細については、*Amazon VPC ユーザーガイド*の[サブネット CIDR の予約](https://docs.aws.amazon.com/vpc/latest/userguide/subnet-cidr-reservation.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSubnetCidrReservations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-subnet-cidr-reservations.html)」を参照してください。

### `get-transit-gateway-attachment-propagations`
<a name="ec2_GetTransitGatewayAttachmentPropagations_cli_2_topic"></a>

次のコード例は、`get-transit-gateway-attachment-propagations` を使用する方法を示しています。

**AWS CLI**  
**指定したリソースアタッチメントがルートを伝播する対象ルートテーブルを一覧表示します。**  
次の `get-transit-gateway-attachment-propagations` の例では、指定したリソースアタッチメントがルートを伝播するルートテーブルを一覧表示します。  

```
aws ec2 get-transit-gateway-attachment-propagations \
    --transit-gateway-attachment-id tgw-attach-09fbd47ddfEXAMPLE
```
出力:  

```
{
    "TransitGatewayAttachmentPropagations": [
        {
            "TransitGatewayRouteTableId": "tgw-rtb-0882c61b97EXAMPLE",
            "State": "enabled"
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTransitGatewayAttachmentPropagations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-transit-gateway-attachment-propagations.html)」を参照してください。

### `get-transit-gateway-multicast-domain-associations`
<a name="ec2_GetTransitGatewayMulticastDomainAssociations_cli_2_topic"></a>

次のコード例は、`get-transit-gateway-multicast-domain-associations` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway マルチキャストドメインの関連付けに関する情報を表示するには**  
次の `get-transit-gateway-multicast-domain-associations` の例では、指定したマルチキャストドメインの関連付けを返します。  

```
aws ec2 get-transit-gateway-multicast-domain-associations \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef7EXAMPLE
```
出力:  

```
{
    "MulticastDomainAssociations": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-028c1dd0f8EXAMPLE",
            "ResourceId": "vpc-01128d2c24EXAMPLE",
            "ResourceType": "vpc",
            "Subnet": {
                "SubnetId": "subnet-000de86e3bEXAMPLE",
                "State": "associated"
            }
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-070e571cd1EXAMPLE",
            "ResourceId": "vpc-7EXAMPLE",
            "ResourceType": "vpc",
            "Subnet": {
                "SubnetId": "subnet-4EXAMPLE",
                "State": "associated"
            }
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-070e571cd1EXAMPLE",
            "ResourceId": "vpc-7EXAMPLE",
            "ResourceType": "vpc",
            "Subnet": {
                "SubnetId": "subnet-5EXAMPLE",
                "State": "associated"
            }
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-070e571cd1EXAMPLE",
            "ResourceId": "vpc-7EXAMPLE",
            "ResourceType": "vpc",
            "Subnet": {
                "SubnetId": "subnet-aEXAMPLE",
                "State": "associated"
            }
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-070e571cd1EXAMPLE",
            "ResourceId": "vpc-7EXAMPLE",
            "ResourceType": "vpc",
            "Subnet": {
                "SubnetId": "subnet-fEXAMPLE",
                "State": "associated"
            }
        }
    ]
}
```
詳細については、*Transit Gateways ガイド*の「[マルチキャストドメイン](https://docs.aws.amazon.com/vpc/latest/tgw/multicast-domains-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTransitGatewayMulticastDomainAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-transit-gateway-multicast-domain-associations.html)」を参照してください。

### `get-transit-gateway-prefix-list-references`
<a name="ec2_GetTransitGatewayPrefixListReferences_cli_2_topic"></a>

次のコード例は、`get-transit-gateway-prefix-list-references` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ルートテーブルでプレフィックスリストのリファレンスを取得するには**  
次の `get-transit-gateway-prefix-list-references` の例では、指定した Transit Gateway ルートテーブルのプレフィックスリストのリファレンスを取得し、特定のプレフィックスリストの ID でフィルタリングします。  

```
aws ec2 get-transit-gateway-prefix-list-references \
    --transit-gateway-route-table-id tgw-rtb-0123456789abcd123 \
    --filters Name=prefix-list-id,Values=pl-11111122222222333
```
出力:  

```
{
    "TransitGatewayPrefixListReferences": [
        {
            "TransitGatewayRouteTableId": "tgw-rtb-0123456789abcd123",
            "PrefixListId": "pl-11111122222222333",
            "PrefixListOwnerId": "123456789012",
            "State": "available",
            "Blackhole": false,
            "TransitGatewayAttachment": {
                "TransitGatewayAttachmentId": "tgw-attach-aabbccddaabbccaab",
                "ResourceType": "vpc",
                "ResourceId": "vpc-112233445566aabbc"
            }
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Prefix list references](https://docs.aws.amazon.com/vpc/latest/tgw/create-prefix-list-reference.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTransitGatewayPrefixListReferences](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-transit-gateway-prefix-list-references.html)」を参照してください。

### `get-transit-gateway-route-table-associations`
<a name="ec2_GetTransitGatewayRouteTableAssociations_cli_2_topic"></a>

次のコード例は、`get-transit-gateway-route-table-associations` を使用する方法を示しています。

**AWS CLI**  
**指定した Transit Gateway ルートテーブルの関連付けに関する情報を取得するには**  
次の `get-transit-gateway-route-table-associations` の例では、指定した Transit Gateway ルートテーブルの関連付けに関する情報を表示します。  

```
aws ec2 get-transit-gateway-route-table-associations \
    --transit-gateway-route-table-id tgw-rtb-0a823edbdeEXAMPLE
```
出力:  

```
{
    "Associations": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-09b52ccdb5EXAMPLE",
            "ResourceId": "vpc-4d7de228",
            "ResourceType": "vpc",
            "State": "associating"
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#associate-tgw-route-table)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTransitGatewayRouteTableAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-transit-gateway-route-table-associations.html)」を参照してください。

### `get-transit-gateway-route-table-propagations`
<a name="ec2_GetTransitGatewayRouteTablePropagations_cli_2_topic"></a>

次のコード例は、`get-transit-gateway-route-table-propagations` を使用する方法を示しています。

**AWS CLI**  
**指定した Transit Gateway ルートテーブルのルートテーブル伝播に関する情報を取得するには**  
次の `get-transit-gateway-route-table-propagations` の例では、指定したルートテーブルのルートテーブル伝播を返します。  

```
aws ec2 get-transit-gateway-route-table-propagations \
    --transit-gateway-route-table-id tgw-rtb-002573ed1eEXAMPLE
```
出力:  

```
{
    "TransitGatewayRouteTablePropagations": [
        {
            "TransitGatewayAttachmentId": "tgw-attach-01f8100bc7EXAMPLE",
            "ResourceId": "vpc-3EXAMPLE",
            "ResourceType": "vpc",
            "State": "enabled"
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-08e0bc912cEXAMPLE",
            "ResourceId": "11460968-4ac1-4fd3-bdb2-00599EXAMPLE",
            "ResourceType": "direct-connect-gateway",
            "State": "enabled"
        },
        {
            "TransitGatewayAttachmentId": "tgw-attach-0a89069f57EXAMPLE",
            "ResourceId": "8384da05-13ce-4a91-aada-5a1baEXAMPLE",
            "ResourceType": "direct-connect-gateway",
            "State": "enabled"
        }
    ]
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTransitGatewayRouteTablePropagations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-transit-gateway-route-table-propagations.html)」を参照してください。

### `get-verified-access-endpoint-policy`
<a name="ec2_GetVerifiedAccessEndpointPolicy_cli_2_topic"></a>

次のコード例は、`get-verified-access-endpoint-policy` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントの Verified Access ポリシーを取得するには**  
次の `get-verified-access-endpoint-policy` の例では、指定したエンドポイントの Verified Access ポリシーを取得します。  

```
aws ec2 get-verified-access-endpoint-policy \
    --verified-access-endpoint-id vae-066fac616d4d546f2
```
出力:  

```
{
    "PolicyEnabled": true,
    "PolicyDocument": "permit(principal,action,resource)\nwhen {\n    context.identity.groups.contains(\"finance\") &&\n    context.identity.email_verified == true\n};"
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access policies](https://docs.aws.amazon.com/verified-access/latest/ug/auth-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVerifiedAccessEndpointPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-verified-access-endpoint-policy.html)」を参照してください。

### `get-verified-access-group-policy`
<a name="ec2_GetVerifiedAccessGroupPolicy_cli_2_topic"></a>

次のコード例は、`get-verified-access-group-policy` を使用する方法を示しています。

**AWS CLI**  
**グループの Verified Access ポリシーを取得するには**  
次の `get-verified-access-group-policy` の例では、指定したグループの Verified Access ポリシーを取得します。  

```
aws ec2 get-verified-access-group-policy \
    --verified-access-group-id vagr-0dbe967baf14b7235
```
出力:  

```
{
    "PolicyEnabled": true,
    "PolicyDocument": "permit(principal,action,resource)\nwhen {\n    context.identity.groups.contains(\"finance\") &&\n    context.identity.email_verified == true\n};"
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access groups](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVerifiedAccessGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-verified-access-group-policy.html)」を参照してください。

### `get-vpn-connection-device-sample-configuration`
<a name="ec2_GetVpnConnectionDeviceSampleConfiguration_cli_2_topic"></a>

次のコード例は、`get-vpn-connection-device-sample-configuration` を使用する方法を示しています。

**AWS CLI**  
**サンプル設定ファイルをダウンロードするには**  
次の `get-vpn-connection-device-sample-configuration` の例では、指定したサンプル設定ファイルをダウンロードします。サンプル設定ファイルを使用してゲートウェイデバイスを一覧表示するには、`get-vpn-connection-device-types` コマンドを呼び出します。  

```
aws ec2 get-vpn-connection-device-sample-configuration \
    --vpn-connection-id vpn-123456789abc01234 \
    --vpn-connection-device-type-id 5fb390ba
```
出力:  

```
{
    "VpnConnectionDeviceSampleConfiguration": "contents-of-the-sample-configuration-file"
}
```
詳細については、「*AWS Site-to-Site VPN ユーザーガイド*」の「[Download the configuration file](https://docs.aws.amazon.com/vpn/latest/s2svpn/SetUpVPNConnections.html#vpn-download-config)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVpnConnectionDeviceSampleConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-vpn-connection-device-sample-configuration.html)」を参照してください。

### `get-vpn-connection-device-types`
<a name="ec2_GetVpnConnectionDeviceTypes_cli_2_topic"></a>

次のコード例は、`get-vpn-connection-device-types` を使用する方法を示しています。

**AWS CLI**  
**サンプル設定ファイルを使用してゲートウェイデバイスを一覧表示するには**  
次の `get-vpn-connection-device-types` の例では、サンプル設定ファイルを持つ Palo Alto Networks からのゲートウェイデバイスを一覧表示します。  

```
aws ec2 get-vpn-connection-device-types \
    --query "VpnConnectionDeviceTypes[?Vendor==`Palo Alto Networks`]"
```
出力:  

```
[
    {
        "VpnConnectionDeviceTypeId": "754a6372",
        "Vendor": "Palo Alto Networks",
        "Platform": "PA Series",
        "Software": "PANOS 4.1.2+"
    },
    {
        "VpnConnectionDeviceTypeId": "9612cbed",
        "Vendor": "Palo Alto Networks",
        "Platform": "PA Series",
        "Software": "PANOS 4.1.2+ (GUI)"
    },
    {
        "VpnConnectionDeviceTypeId": "5fb390ba",
        "Vendor": "Palo Alto Networks",
        "Platform": "PA Series",
        "Software": "PANOS 7.0+"
    }
]
```
詳細については、「*AWS Site-to-Site VPN ユーザーガイド*」の「[Download the configuration file](https://docs.aws.amazon.com/vpn/latest/s2svpn/SetUpVPNConnections.html#vpn-download-config)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVpnConnectionDeviceTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/get-vpn-connection-device-types.html)」を参照してください。

### `import-client-vpn-client-certificate-revocation-list`
<a name="ec2_ImportClientVpnClientCertificateRevocationList_cli_2_topic"></a>

次のコード例は、`import-client-vpn-client-certificate-revocation-list` を使用する方法を示しています。

**AWS CLI**  
**クライアント証明書失効リストをインポートするには**  
次の `import-client-vpn-client-certificate-revocation-list` の例では、ローカルコンピュータ上のファイルの場所を指定して、クライアント証明書失効リストをクライアント VPN エンドポイントにインポートします。  

```
aws ec2 import-client-vpn-client-certificate-revocation-list \
    --certificate-revocation-list file:///path/to/crl.pem \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client Certificate Revocation Lists](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-certificates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportClientVpnClientCertificateRevocationList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-client-vpn-client-certificate-revocation-list.html)」を参照してください。

### `import-image`
<a name="ec2_ImportImage_cli_2_topic"></a>

次のコード例は、`import-image` を使用する方法を示しています。

**AWS CLI**  
**VM イメージファイルを AMI としてインポートするには**  
次の `import-image` の例では、指定した OVA をインポートします。  

```
aws ec2 import-image \
  --disk-containers Format=ova,UserBucket="{S3Bucket=my-import-bucket,S3Key=vms/my-server-vm.ova}"
```
出力:  

```
{
    "ImportTaskId": "import-ami-1234567890abcdef0",
    "Progress": "2",
    "SnapshotDetails": [
        {
            "DiskImageSize": 0.0,
            "Format": "ova",
            "UserBucket": {
                "S3Bucket": "my-import-bucket",
                "S3Key": "vms/my-server-vm.ova"
            }
        }
    ],
    "Status": "active",
    "StatusMessage": "pending"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-image.html)」を参照してください。

### `import-key-pair`
<a name="ec2_ImportKeyPair_cli_2_topic"></a>

次のコード例は、`import-key-pair` を使用する方法を示しています。

**AWS CLI**  
**パブリックキーをインポートするには**  
最初に、選択したツールを使用してキーペアを生成します。例えば、次の ssh-keygen コマンドを使用します。  
コマンド:  

```
ssh-keygen -t rsa -C "my-key" -f ~/.ssh/my-key
```
出力:  

```
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ec2-user/.ssh/my-key.
Your public key has been saved in /home/ec2-user/.ssh/my-key.pub.
...
```
このコマンド例では、指定されたパブリックキーをインポートします。  
コマンド:  

```
aws ec2 import-key-pair --key-name "my-key" --public-key-material fileb://~/.ssh/my-key.pub
```
出力:  

```
{
  "KeyName": "my-key",
  "KeyFingerprint": "1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-key-pair.html)」を参照してください。

### `import-snapshot`
<a name="ec2_ImportSnapshot_cli_2_topic"></a>

次のコード例は、`import-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットをインポートするには**  
次の `import-snapshot` の例では、指定したディスクをスナップショットとしてインポートします。  

```
aws ec2 import-snapshot \
    --description "My server VMDK" \
    --disk-container Format=VMDK,UserBucket={'S3Bucket=my-import-bucket,S3Key=vms/my-server-vm.vmdk'}
```
出力:  

```
{
    "Description": "My server VMDK",
    "ImportTaskId": "import-snap-1234567890abcdef0",
    "SnapshotTaskDetail": {
        "Description": "My server VMDK",
        "DiskImageSize": "0.0",
        "Format": "VMDK",
        "Progress": "3",
        "Status": "active",
        "StatusMessage": "pending"
        "UserBucket": {
            "S3Bucket": "my-import-bucket",
            "S3Key": "vms/my-server-vm.vmdk"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/import-snapshot.html)」を参照してください。

### `list-images-in-recycle-bin`
<a name="ec2_ListImagesInRecycleBin_cli_2_topic"></a>

次のコード例は、`list-images-in-recycle-bin` を使用する方法を示しています。

**AWS CLI**  
**ごみ箱内のイメージを一覧表示するには**  
次の `list-images-in-recycle-bin` の例では、ごみ箱に現在保持されているすべてのイメージを一覧表示します。  

```
aws ec2 list-images-in-recycle-bin
```
出力:  

```
{
    "Images": [
        {
            "RecycleBinEnterTime": "2022-03-14T15:35:08.000Z",
            "Description": "Monthly AMI One",
            "RecycleBinExitTime": "2022-03-15T15:35:08.000Z",
            "Name": "AMI_01",
            "ImageId": "ami-0111222333444abcd"
        }
    ]
}
```
詳細については、*Amazon EBS ユーザーガイド*の「[削除された AMI をごみ箱から復元する](https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin-working-with-amis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListImagesInRecycleBin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/list-images-in-recycle-bin.html)」を参照してください。

### `list-snapshots-in-recycle-bin`
<a name="ec2_ListSnapshotsInRecycleBin_cli_2_topic"></a>

次のコード例は、`list-snapshots-in-recycle-bin` を使用する方法を示しています。

**AWS CLI**  
**ごみ箱のスナップショットを表示するには**  
次の `list-snapshots-in-recycle-bin` の例では、ごみ箱にあるスナップショットの情報を一覧表示します。この詳細には、スナップショット ID、スナップショットの説明、スナップショットが作成されたボリュームの ID、スナップショットが削除されてごみ箱に入った日時、保持期間が終了する日時などがあります。  

```
aws ec2 list-snapshots-in-recycle-bin \
    --snapshot-id snap-01234567890abcdef
```
出力:  

```
{
    "SnapshotRecycleBinInfo": [
        {
            "Description": "Monthly data backup snapshot",
            "RecycleBinEnterTime": "2022-12-01T13:00:00.000Z",
            "RecycleBinExitTime": "2022-12-15T13:00:00.000Z",
            "VolumeId": "vol-abcdef09876543210",
            "SnapshotId": "snap-01234567890abcdef"
        }
    ]
}
```
ごみ箱の詳細については、*Amazon EBS ユーザーガイド*の「[削除されたスナップショットをごみ箱から復元する](https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin-working-with-snaps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSnapshotsInRecycleBin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/list-snapshots-in-recycle-bin.html)」を参照してください。

### `lock-snapshot`
<a name="ec2_LockSnapshot_cli_2_topic"></a>

次のコード例は、`lock-snapshot` を使用する方法を示しています。

**AWS CLI**  
**例 1: ガバナンスモードでスナップショットをロックするには**  
次の `lock-snapshot` の例では、指定したスナップショットをガバナンスモードでロックします。  

```
aws ec2 lock-snapshot \
    --snapshot-id snap-0b5e733b4a8df6e0d \
    --lock-mode governance \
    --lock-duration 365
```
出力:  

```
{
    "SnapshotId": "snap-0b5e733b4a8df6e0d",
    "LockState": "governance",
    "LockDuration": 365,
    "LockCreatedOn": "2024-05-05T00:56:06.208000+00:00",
    "LockExpiresOn": "2025-05-05T00:56:06.208000+00:00",
    "LockDurationStartTime": "2024-05-05T00:56:06.208000+00:00"
}
```
詳細については、「*Amazon EBS ユーザーガイド*」の「[Snapshot lock](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-snapshot-lock.html)」を参照してください。  
**例 2: スナップショットをコンプライアンスモードでロックするには**  
次の `lock-snapshot` の例では、指定したスナップショットをコンプライアンスモードでロックします。  

```
aws ec2 lock-snapshot \
    --snapshot-id snap-0163a8524c5b9901f \
    --lock-mode compliance \
    --cool-off-period 24 \
    --lock-duration 365
```
出力:  

```
{
    "SnapshotId": "snap-0b5e733b4a8df6e0d",
    "LockState": "compliance-cooloff",
    "LockDuration": 365,
    "CoolOffPeriod": 24,
    "CoolOffPeriodExpiresOn": "2024-05-06T01:02:20.527000+00:00",
    "LockCreatedOn": "2024-05-05T01:02:20.527000+00:00",
    "LockExpiresOn": "2025-05-05T01:02:20.527000+00:00",
    "LockDurationStartTime": "2024-05-05T01:02:20.527000+00:00"
}
```
詳細については、「*Amazon EBS ユーザーガイド*」の「[Snapshot lock](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-snapshot-lock.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[LockSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/lock-snapshot.html)」を参照してください。

### `modify-address-attribute`
<a name="ec2_ModifyAddressAttribute_cli_2_topic"></a>

次のコード例は、`modify-address-attribute` を使用する方法を示しています。

**AWS CLI**  
**Elastic IP アドレスに関連付けられたドメイン名属性を変更するには**  
次の `modify-address-attribute` の例では、Elastic IP アドレスのドメイン名の属性を変更します。  
Linux ：  

```
aws ec2 modify-address-attribute \
    --allocation-id eipalloc-abcdef01234567890 \
    --domain-name example.com
```
Windows ：  

```
aws ec2 modify-address-attribute ^
    --allocation-id eipalloc-abcdef01234567890 ^
    --domain-name example.com
```
出力:  

```
{
    "Addresses": [
        {
            "PublicIp": "192.0.2.0",
            "AllocationId": "eipalloc-abcdef01234567890",
            "PtrRecord": "example.net."
            "PtrRecordUpdate": {
                "Value": "example.com.",
                "Status": "PENDING"
        }
    ]
}
```
保留中の変更をモニタリングし、Elastic IP アドレスの変更された属性を表示するには、「*AWS CLI コマンドリファレンス*」の「[describe-addresses-attribute](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-addresses-attribute.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyAddressAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-address-attribute.html)」を参照してください。

### `modify-availability-zone-group`
<a name="ec2_ModifyAvailabilityZoneGroup_cli_2_topic"></a>

次のコード例は、`modify-availability-zone-group` を使用する方法を示しています。

**AWS CLI**  
**ゾーングループを有効にするには**  
次の `modify-availability-zone-group` の例では、指定したゾーングループを有効にします。  

```
aws ec2 modify-availability-zone-group \
    --group-name us-west-2-lax-1 \
    --opt-in-status opted-in
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[リージョンとゾーン](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyAvailabilityZoneGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-availability-zone-group.html)」を参照してください。

### `modify-capacity-reservation-fleet`
<a name="ec2_ModifyCapacityReservationFleet_cli_2_topic"></a>

次のコード例は、`modify-capacity-reservation-fleet` を使用する方法を示しています。

**AWS CLI**  
**例 1: キャパシティ予約フリートの合計ターゲット容量を変更するには**  
次の `modify-capacity-reservation-fleet` の例では、指定したキャパシティ予約フリートの合計ターゲット容量を変更します。キャパシティ予約フリートの総ターゲット容量を変更すると、フリートは、新しい総ターゲット容量を満たすように、自動的に新しいキャパシティ予約を作成したり、フリート内の既存のキャパシティ予約を変更またはキャンセルしたりします。フリートのステータスが `modifying` の間は、他の変更を試みることはできません。  

```
aws ec2 modify-capacity-reservation-fleet \
    --capacity-reservation-fleet-id crf-01234567890abcedf \
    --total-target-capacity 160
```
出力:  

```
{
    "Return": true
}
```
**例 2: キャパシティ予約フリートの終了日を変更するには**  
次の `modify-capacity-reservation-fleet` の例では、指定したキャパシティ予約フリートの終了日を変更します。フリートの終了日を変更すると、個々のキャパシティ予約の終了日もそれに応じて更新されます。フリートのステータスが `modifying` の間は、他の変更を試みることはできません。  

```
aws ec2 modify-capacity-reservation-fleet \
    --capacity-reservation-fleet-id crf-01234567890abcedf \
    --end-date 2022-07-04T23:59:59.000Z
```
出力:  

```
{
    "Return": true
}
```
キャパシティ予約フリートの詳細については、「*Amazon EC2 ユーザーガイド*」の「[キャパシティ予約フリート](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/cr-fleets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyCapacityReservationFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-capacity-reservation-fleet.html)」を参照してください。

### `modify-capacity-reservation`
<a name="ec2_ModifyCapacityReservation_cli_2_topic"></a>

次のコード例は、`modify-capacity-reservation` を使用する方法を示しています。

**AWS CLI**  
**例 1: 既存のキャパシティ予約で予約されたインスタンスの数を変更するには**  
次の `modify-capacity-reservation` の例では、キャパシティ予約でキャパシティを予約するインスタンスの合計数を変更します。  

```
aws ec2 modify-capacity-reservation \
    --capacity-reservation-id cr-1234abcd56EXAMPLE \
    --instance-count 5
```
出力:  

```
{
    "Return": true
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[キャパシティ予約の変更](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-modify.html)」を参照してください。  
**例 2: 既存のキャパシティ予約の終了日時を変更するには**  
次の `modify-capacity-reservation` の例では、指定した日時に既存のキャパシティ予約が終了するように変更します。  

```
aws ec2 modify-capacity-reservation \
    --capacity-reservation-id cr-1234abcd56EXAMPLE \
    --end-date-type limited \
    --end-date 2019-08-31T23:59:59Z
```
詳細については、*Amazon EC2 ユーザーガイド*の「[キャパシティ予約の変更](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyCapacityReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-capacity-reservation.html)」を参照してください。

### `modify-client-vpn-endpoint`
<a name="ec2_ModifyClientVpnEndpoint_cli_2_topic"></a>

次のコード例は、`modify-client-vpn-endpoint` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントを変更するには**  
次の `modify-client-vpn-endpoint` の例では、指定したクライアント VPN エンドポイントのクライアント接続を有効にします。  

```
aws ec2 modify-client-vpn-endpoint \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --connection-log-options Enabled=true,CloudwatchLogGroup=ClientVPNLogs
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client VPN Endpoints](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClientVpnEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-client-vpn-endpoint.html)」を参照してください。

### `modify-default-credit-specification`
<a name="ec2_ModifyDefaultCreditSpecification_cli_2_topic"></a>

次のコード例は、`modify-default-credit-specification` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのクレジットオプションを変更するには**  
次の `modify-default-credit-specification` の例では、T2 インスタンスのデフォルトのクレジットオプションを変更します。  

```
aws ec2 modify-default-credit-specification \
    --instance-family t2 \
    --cpu-credits unlimited
```
出力:  

```
{
    "InstanceFamilyCreditSpecification": {
        "InstanceFamily": "t2",
        "CpuCredits": "unlimited"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDefaultCreditSpecification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-default-credit-specification.html)」を参照してください。

### `modify-ebs-default-kms-key-id`
<a name="ec2_ModifyEbsDefaultKmsKeyId_cli_2_topic"></a>

次のコード例は、`modify-ebs-default-kms-key-id` を使用する方法を示しています。

**AWS CLI**  
**EBS 暗号化用のデフォルトの CMK を設定するには**  
次の の`modify-ebs-default-kms-key-id`例では、指定された CMK を現在のリージョンの AWS アカウントの EBS 暗号化のデフォルト CMK として設定します。  

```
aws ec2 modify-ebs-default-kms-key-id \
    --kms-key-id alias/my-cmk
```
出力:  

```
{
    "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/0ea3fef3-80a7-4778-9d8c-1c0c6EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyEbsDefaultKmsKeyId](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-ebs-default-kms-key-id.html)」を参照してください。

### `modify-fleet`
<a name="ec2_ModifyFleet_cli_2_topic"></a>

次のコード例は、`modify-fleet` を使用する方法を示しています。

**AWS CLI**  
**EC2 フリートをスケールするには**  
次の `modify-fleet` の例では、指定した EC2 フリートのターゲット容量を変更します。指定された値が現在の容量より大きい場合、EC2 フリートは追加のインスタンスを起動します。指定された値が現在の容量よりも小さい場合、EC2 フリートは未完了のリクエストをキャンセルし、終了ポリシーが `terminate` の場合、EC2 フリートは新しいターゲット容量を超えるインスタンスをすべて終了します。  

```
aws ec2 modify-fleet \
    --fleet-ids fleet-12a34b55-67cd-8ef9-ba9b-9208dEXAMPLE \
    --target-capacity-specification TotalTargetCapacity=5
```
出力:  

```
{
    "Return": true
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[EC2 フリートの管理](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/manage-ec2-fleet.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-fleet.html)」を参照してください。

### `modify-fpga-image-attribute`
<a name="ec2_ModifyFpgaImageAttribute_cli_2_topic"></a>

次のコード例は、`modify-fpga-image-attribute` を使用する方法を示しています。

**AWS CLI**  
**Amazon FPGA イメージの属性を変更するには**  
この例では、指定された AFI のアカウント ID `123456789012` にロード許可を追加します。  
コマンド:  

```
aws ec2 modify-fpga-image-attribute --attribute loadPermission --fpga-image-id afi-0d123e123bfc85abc --load-permission Add=[{UserId=123456789012}]
```
出力:  

```
{
  "FpgaImageAttribute": {
      "FpgaImageId": "afi-0d123e123bfc85abc",
      "LoadPermissions": [
          {
              "UserId": "123456789012"
          }
      ]
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyFpgaImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-fpga-image-attribute.html)」を参照してください。

### `modify-hosts`
<a name="ec2_ModifyHosts_cli_2_topic"></a>

次のコード例は、`modify-hosts` を使用する方法を示しています。

**AWS CLI**  
**例 1: 専有ホストの自動配置を有効にするには**  
次の `modify-hosts` の例では、インスタンスタイプ設定が一致するすべてのターゲット未指定のインスタンス起動を受け入れるため、専有ホストの自動配置を有効にします。  

```
aws ec2 modify-hosts \
    --host-id h-06c2f189b4EXAMPLE \
    --auto-placement on
```
出力:  

```
{
    "Successful": [
        "h-06c2f189b4EXAMPLE"
    ],
    "Unsuccessful": []
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[専有ホストの自動配置設定の変更](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/modify-host-auto-placement.html)」を参照してください。  
**例 2: 専有ホストのホストリカバリを有効にするには**  
次の `modify-hosts` の例では、指定した専有ホストのホストの復旧を有効にします。  

```
aws ec2 modify-hosts \
    --host-id h-06c2f189b4EXAMPLE \
    --host-recovery on
```
出力:  

```
{
    "Successful": [
        "h-06c2f189b4EXAMPLE"
    ],
    "Unsuccessful": []
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[専有ホストの自動配置設定の変更](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/modify-host-auto-placement.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-hosts.html)」を参照してください。

### `modify-id-format`
<a name="ec2_ModifyIdFormat_cli_2_topic"></a>

次のコード例は、`modify-id-format` を使用する方法を示しています。

**AWS CLI**  
**リソースの長い ID 形式を有効にするには**  
次の `modify-id-format` の例では、`instance` リソースタイプの長い ID 形式を有効にします。  

```
aws ec2 modify-id-format \
    --resource instance \
    --use-long-ids
```
**リソースの長い ID 形式を無効にするには**  
次の `modify-id-format` の例では、`instance` リソースタイプの長い ID 形式を無効にします。  

```
aws ec2 modify-id-format \
    --resource instance \
    --no-use-long-ids
```
次の `modify-id-format` の例では、オプトイン期間内にあるすべてのサポート対象リソースタイプの長い ID 形式を有効にします。  

```
aws ec2 modify-id-format \
    --resource all-current \
    --use-long-ids
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-id-format.html)」を参照してください。

### `modify-identity-id-format`
<a name="ec2_ModifyIdentityIdFormat_cli_2_topic"></a>

次のコード例は、`modify-identity-id-format` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールを有効にして、リソースの長い ID を使用するには**  
次の`modify-identity-id-format`例では、 AWS アカウントの IAM ロール`EC2Role`が`instance`リソースタイプに長い ID 形式を使用できるようにします。  

```
aws ec2 modify-identity-id-format \
    --principal-arn arn:aws:iam::123456789012:role/EC2Role \
    --resource instance \
    --use-long-ids
```
**IAM ユーザーを有効にして、リソースの長い ID を使用するには**  
次の`modify-identity-id-format`例では、`AdminUser` AWS アカウントの IAM ユーザーが`volume`リソースタイプに長い ID 形式を使用できるようにします。  

```
aws ec2 modify-identity-id-format \
    --principal-arn arn:aws:iam::123456789012:user/AdminUser \
    --resource volume \
    --use-long-ids
```
次の`modify-identity-id-format`例では、`AdminUser` AWS アカウントの IAM ユーザーが、オプトイン期間内にサポートされているすべてのリソースタイプで長い ID 形式を使用できるようにします。  

```
aws ec2 modify-identity-id-format \
    --principal-arn arn:aws:iam::123456789012:user/AdminUser \
    --resource all-current \
    --use-long-ids
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyIdentityIdFormat](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-identity-id-format.html)」を参照してください。

### `modify-image-attribute`
<a name="ec2_ModifyImageAttribute_cli_2_topic"></a>

次のコード例は、`modify-image-attribute` を使用する方法を示しています。

**AWS CLI**  
**例 1: AMI をパブリックにするには**  
次の `modify-instance-attribute` の例では、指定した AMI を公開します。  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Add=[{Group=all}]"
```
このコマンドでは何も出力されません。  
**例 2: AMI をプライベートにするには**  
次の `modify-instance-attribute` の例では、指定した AMI を非公開にします。  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Remove=[{Group=all}]"
```
このコマンドでは何も出力されません。  
**例 3: AWS アカウントに起動許可を付与するには**  
次の の`modify-instance-attribute`例では、指定された AWS アカウントに起動アクセス許可を付与します。  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Add=[{UserId=123456789012}]"
```
このコマンドでは何も出力されません。  
**例 4: AWS アカウントから起動許可を削除するには**  
次の の`modify-instance-attribute`例では、指定された AWS アカウントから起動許可を削除します。  

```
aws ec2 modify-image-attribute \
    --image-id ami-5731123e \
    --launch-permission "Remove=[{UserId=123456789012}]"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-image-attribute.html)」を参照してください。

### `modify-instance-attribute`
<a name="ec2_ModifyInstanceAttribute_cli_2_topic"></a>

次のコード例は、`modify-instance-attribute` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスタイプを変更するには**  
次の `modify-instance-attribute` の例では、指定したインスタンスのインスタンスタイプを変更します。インスタンスは `stopped` の状態である必要があります。  

```
aws ec2 modify-instance-attribute \
    --instance-id i-1234567890abcdef0 \
    --instance-type "{\"Value\": \"m1.small\"}"
```
このコマンドでは何も出力されません。  
**例 2: インスタンスで拡張ネットワーキングを有効にするには**  
次の `modify-instance-attribute` の例では、指定されたインスタンスの拡張ネットワーキングを有効にします。インスタンスは `stopped` の状態である必要があります。  

```
aws ec2 modify-instance-attribute \
    --instance-id i-1234567890abcdef0 \
    --sriov-net-support simple
```
このコマンドでは何も出力されません。  
**例 3: sourceDestCheck 属性を変更するには**  
次の `modify-instance-attribute` の例では、指定したインスタンスの `sourceDestCheck` 属性を `true` に設定します。インスタンスは VPC にある必要があります。  

```
aws ec2 modify-instance-attribute --instance-id i-1234567890abcdef0 --source-dest-check "{\"Value\": true}"
```
このコマンドでは何も出力されません。  
**例 4: ルートボリュームの deleteOnTermination 属性を変更するには**  
次の `modify-instance-attribute` の例では、指定した Amazon EBS-backed インスタンスのルートボリュームに対する `deleteOnTermination` 属性を `false` に設定します。デフォルトでは、この属性はルートボリュームに対して `true` です。  
コマンド:  

```
aws ec2 modify-instance-attribute \
  --instance-id i-1234567890abcdef0 \
  --block-device-mappings "[{\"DeviceName\": \"/dev/sda1\",\"Ebs\":{\"DeleteOnTermination\":false}}]"
```
このコマンドでは何も出力されません。  
**例 5: インスタンスにアタッチされたユーザーデータを変更するには**  
次の `modify-instance-attribute` の例では、指定したインスタンスの UserData としてファイル `UserData.txt` の内容を追加します。  
元のファイル `UserData.txt` の内容:  

```
#!/bin/bash
yum update -y
service httpd start
chkconfig httpd on
```
ファイルの内容は、base64 でエンコードされている必要があります。最初のコマンドはテキストファイルを base64 に変換し、新しいファイルとして保存します。  
コマンドの Linux/macOS バージョン:  

```
base64 UserData.txt > UserData.base64.txt
```
このコマンドでは何も出力されません。  
コマンドの Windows バージョン:  

```
certutil -encode UserData.txt tmp.b64 && findstr /v /c:- tmp.b64 > UserData.base64.txt
```
出力:  

```
Input Length = 67
Output Length = 152
CertUtil: -encode command completed successfully.
```
これで、次の CLI コマンドでそのファイルを参照できるようになりました。  

```
aws ec2 modify-instance-attribute \
    --instance-id=i-09b5a14dbca622e76 \
    --attribute userData --value file://UserData.base64.txt
```
このコマンドでは何も出力されません。  
詳細については、*EC2 ユーザーガイド*[の「ユーザーデータと AWS CLI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-api-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-attribute.html)」を参照してください。

### `modify-instance-capacity-reservation-attributes`
<a name="ec2_ModifyInstanceCapacityReservationAttributes_cli_2_topic"></a>

次のコード例は、`modify-instance-capacity-reservation-attributes` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスのキャパシティ予約のターゲット設定を変更するには**  
次の `modify-instance-capacity-reservation-attributes` の例では、特定のキャパシティ予約をターゲットにするようにインスタンスを変更します。  

```
aws ec2 modify-instance-capacity-reservation-attributes \
    --instance-id i-EXAMPLE8765abcd4e \
    --capacity-reservation-specification 'CapacityReservationTarget={CapacityReservationId= cr-1234abcd56EXAMPLE }'
```
出力:  

```
{
    "Return": true
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[インスタンスのキャパシティ予約設定を変更する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-modify-instance.html)」を参照してください。  
**例 2: インスタンスのキャパシティ予約のターゲット設定を変更するには**  
次の `modify-instance-capacity-reservation-attributes` の例では、指定したキャパシティ予約をターゲットとする停止されたインスタンスを変更して、一致する属性 (インスタンスタイプ、プラットフォーム、アベイラビリティーゾーン) を持つキャパシティ予約、およびオープンインスタンスの一致基準を持つキャパシティ予約で起動するようにします。  

```
aws ec2 modify-instance-capacity-reservation-attributes \
    --instance-id i-EXAMPLE8765abcd4e \
    --capacity-reservation-specification 'CapacityReservationPreference=open'
```
出力:  

```
{
    "Return": true
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[インスタンスのキャパシティ予約設定を変更する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/capacity-reservations-modify-instance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceCapacityReservationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-capacity-reservation-attributes.html)」を参照してください。

### `modify-instance-credit-specification`
<a name="ec2_ModifyInstanceCreditSpecification_cli_2_topic"></a>

次のコード例は、`modify-instance-credit-specification` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの CPU 使用率に対するクレジットオプションを変更するには**  
この例では、指定されたリージョン内にある指定されたインスタンスの CPU 使用率のクレジットオプションを「無制限」に変更します。有効なクレジットオプションは、「標準」と「無制限」です。  
コマンド:  

```
aws ec2 modify-instance-credit-specification --instance-credit-specification "InstanceId=i-1234567890abcdef0,CpuCredits=unlimited"
```
出力:  

```
{
  "SuccessfulInstanceCreditSpecifications": [
    {
      "InstanceId": "i-1234567890abcdef0"
    }
  ],
  "UnsuccessfulInstanceCreditSpecifications": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceCreditSpecification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-credit-specification.html)」を参照してください。

### `modify-instance-event-start-time`
<a name="ec2_ModifyInstanceEventStartTime_cli_2_topic"></a>

次のコード例は、`modify-instance-event-start-time` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのイベント開始時刻を変更するには**  
次の `modify-instance-event-start-time` コマンドは、指定したインスタンスのイベント開始時刻を変更する方法を示します。`--instance-event-id` パラメータを使用してイベント ID を指定します。`--not-before` パラメータを使用して新しい日時を指定します。  

```
aws ec2 modify-instance-event-start-time --instance-id i-1234567890abcdef0 --instance-event-id instance-event-0abcdef1234567890 --not-before 2019-03-25T10:00:00.000
```
出力:  

```
"Event": {
    "InstanceEventId": "instance-event-0abcdef1234567890",
    "Code": "system-reboot",
    "Description": "scheduled reboot",
    "NotAfter": "2019-03-25T12:00:00.000Z",
    "NotBefore": "2019-03-25T10:00:00.000Z",
    "NotBeforeDeadline": "2019-04-22T21:00:00.000Z"
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「Working with Instances Scheduled for Reboot」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceEventStartTime](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-event-start-time.html)」を参照してください。

### `modify-instance-event-window`
<a name="ec2_ModifyInstanceEventWindow_cli_2_topic"></a>

次のコード例は、`modify-instance-event-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: イベントウィンドウの時間範囲を変更するには**  
次の `modify-instance-event-window` の例では、イベントウィンドウの時間範囲を変更します。`time-range` パラメータにより時間範囲を変更します。また、`cron-expression` パラメータを指定することはできません。  

```
aws ec2 modify-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890
    --time-range StartWeekDay=monday,StartHour=2,EndWeekDay=wednesday,EndHour=8
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "TimeRanges": [
            {
                "StartWeekDay": "monday",
                "StartHour": 2,
                "EndWeekDay": "wednesday",
                "EndHour": 8
            }
        ],
        "Name": "myEventWindowName",
        "AssociationTarget": {
            "InstanceIds": [
                "i-0abcdef1234567890",
                "i-0be35f9acb8ba01f0"
            ],
            "Tags": [],
            "DedicatedHostIds": []
        },
        "State": "creating",
        "Tags": [
            {
                "Key": "K1",
                "Value": "V1"
            }
        ]
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 2: イベントウィンドウの時間範囲セットを変更するには**  
次の `modify-instance-event-window` の例では、イベントウィンドウの時間範囲を変更します。`time-range` パラメータにより時間範囲を変更します。また、`cron-expression` パラメータを指定することはできません。  

```
aws ec2 modify-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --time-range '[{"StartWeekDay": "monday", "StartHour": 2, "EndWeekDay": "wednesday", "EndHour": 8},
        {"StartWeekDay": "thursday", "StartHour": 2, "EndWeekDay": "friday", "EndHour": 8}]'
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "TimeRanges": [
            {
                "StartWeekDay": "monday",
                "StartHour": 2,
                "EndWeekDay": "wednesday",
                "EndHour": 8
            },
            {
                "StartWeekDay": "thursday",
                "StartHour": 2,
                "EndWeekDay": "friday",
                "EndHour": 8
            }
        ],
        "Name": "myEventWindowName",
        "AssociationTarget": {
            "InstanceIds": [
                "i-0abcdef1234567890",
                "i-0be35f9acb8ba01f0"
            ],
            "Tags": [],
            "DedicatedHostIds": []
        },
        "State": "creating",
        "Tags": [
            {
                "Key": "K1",
                "Value": "V1"
            }
        ]
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
**例 3: イベントウィンドウの cron 式を変更するには**  
次の `modify-instance-event-window` の例では、イベントウィンドウの cron 式を変更します。`cron-expression` パラメータにより cron 式を変更します。また、`time-range` パラメータを指定することはできません。  

```
aws ec2 modify-instance-event-window \
    --region us-east-1 \
    --instance-event-window-id iew-0abcdef1234567890 \
    --cron-expression "* 21-23 * * 2,3"
```
出力:  

```
{
    "InstanceEventWindow": {
        "InstanceEventWindowId": "iew-0abcdef1234567890",
        "Name": "myEventWindowName",
        "CronExpression": "* 21-23 * * 2,3",
        "AssociationTarget": {
            "InstanceIds": [
                "i-0abcdef1234567890",
                "i-0be35f9acb8ba01f0"
            ],
            "Tags": [],
            "DedicatedHostIds": []
        },
        "State": "creating",
        "Tags": [
            {
                "Key": "K1",
                "Value": "V1"
            }
        ]
    }
}
```
イベントウィンドウの制約については、「*Amazon EC2 ユーザーガイド*」の予定されているイベントに関するセクションの「[考慮事項](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/event-windows.html#event-windows-considerations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceEventWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-event-window.html)」を参照してください。

### `modify-instance-maintenance-options`
<a name="ec2_ModifyInstanceMaintenanceOptions_cli_2_topic"></a>

次のコード例は、`modify-instance-maintenance-options` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスの復旧動作を無効にするには**  
次の `modify-instance-maintenance-options` の例では、実行中または停止中のインスタンスの簡素化された自動復旧を無効にします。  

```
aws ec2 modify-instance-maintenance-options \
    --instance-id i-0abcdef1234567890 \
    --auto-recovery disabled
```
出力:  

```
{
    "InstanceId": "i-0abcdef1234567890",
    "AutoRecovery": "disabled"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[簡易自動復旧を設定する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-configuration-recovery.html)」を参照してください。  
**例 2: インスタンスの復旧動作をデフォルトに設定するには**  
次の `modify-instance-maintenance-options` の例では、自動復旧動作をデフォルトに設定し、サポートされているインスタンスタイプの簡素化された自動復旧を有効にします。  

```
aws ec2 modify-instance-maintenance-options \
    --instance-id i-0abcdef1234567890 \
    --auto-recovery default
```
出力:  

```
{
    "InstanceId": "i-0abcdef1234567890",
    "AutoRecovery": "default"
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[簡易自動復旧を設定する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-configuration-recovery.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceMaintenanceOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-maintenance-options.html)」を参照してください。

### `modify-instance-metadata-options`
<a name="ec2_ModifyInstanceMetadataOptions_cli_2_topic"></a>

次のコード例は、`modify-instance-metadata-options` を使用する方法を示しています。

**AWS CLI**  
**例 1: IMDSv2 を有効にするには**  
次の `modify-instance-metadata-options` の例では、指定したインスタンスでの IMDSv2 の使用を設定します。  

```
aws ec2 modify-instance-metadata-options \
    --instance-id i-1234567898abcdef0 \
    --http-tokens required \
    --http-endpoint enabled
```
出力:  

```
{
    "InstanceId": "i-1234567898abcdef0",
    "InstanceMetadataOptions": {
        "State": "pending",
        "HttpTokens": "required",
        "HttpPutResponseHopLimit": 1,
        "HttpEndpoint": "enabled"
    }
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[インスタンスメタデータ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)」を参照してください。  
**例 2: インスタンスメタデータを無効にするには**  
次の `modify-instance-metadata-options` の例では、指定したインスタンスですべてのバージョンのインスタンスメタデータの使用を無効にします。  

```
aws ec2 modify-instance-metadata-options \
    --instance-id i-1234567898abcdef0 \
    --http-endpoint disabled
```
出力:  

```
{
    "InstanceId": "i-1234567898abcdef0",
    "InstanceMetadataOptions": {
        "State": "pending",
        "HttpTokens": "required",
        "HttpPutResponseHopLimit": 1,
        "HttpEndpoint": "disabled"
    }
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[インスタンスメタデータ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)」を参照してください。  
**例 3: インスタンスのインスタンスメタデータ IPv6 エンドポイントを有効にするには**  
次の `modify-instance-metadata-options` の例では、インスタンスメタデータサービスの IPv6 エンドポイントを有効にする方法を示します。デフォルトでは、IPv6 エンドポイントは無効です。これは、インスタンスを IPv6 専用サブネットで起動した場合にも当てはまります。IMDS の IPv6 エンドポイントは、Nitro System 上に構築されたインスタンスでのみアクセス可能です。  

```
aws ec2 modify-instance-metadata-options \
    --instance-id i-1234567898abcdef0 \
    --http-protocol-ipv6 enabled \
    --http-endpoint enabled
```
出力:  

```
{
    "InstanceId": "i-1234567898abcdef0",
    "InstanceMetadataOptions": {
        "State": "pending",
        "HttpTokens": "required",
        "HttpPutResponseHopLimit": 1,
        "HttpEndpoint": "enabled",
        HttpProtocolIpv6": "enabled"
    }
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[インスタンスメタデータ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceMetadataOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-metadata-options.html)」を参照してください。

### `modify-instance-placement`
<a name="ec2_ModifyInstancePlacement_cli_2_topic"></a>

次のコード例は、`modify-instance-placement` を使用する方法を示しています。

**AWS CLI**  
**例 1: 専有ホストとのインスタンスのアフィニティを削除するには**  
次の `modify-instance-placement` の例では、専有ホストとのインスタンスのアフィニティを削除し、そのインスタンスタイプをサポートするアカウントで使用可能な専有ホストで起動できるようにします。  

```
aws ec2 modify-instance-placement \
    --instance-id i-0e6ddf6187EXAMPLE \
    --affinity default
```
出力:  

```
{
    "Return": true
}
```
**例 2: インスタンスと指定された専有ホスト間のアフィニティを確立するには**  
次の `modify-instance-placement` の例では、インスタンスと専有ホストの間に起動関係を確立します。インスタンスは、指定された専有ホストでのみ実行できます。  

```
aws ec2 modify-instance-placement \
    --instance-id i-0e6ddf6187EXAMPLE \
    --affinity host \
    --host-id i-0e6ddf6187EXAMPLE
```
出力:  

```
{
    "Return": true
}
```
**例 3: プレイスメントグループにインスタンスを移動するには**  
次の `modify-instance-placement` の例では、インスタンスをプレイスメントグループに移動してインスタンスを停止し、インスタンスの配置を変更してからインスタンスを再起動します。  

```
aws ec2 stop-instances \
    --instance-ids i-0123a456700123456

aws ec2 modify-instance-placement \
    --instance-id i-0123a456700123456 \
    --group-name MySpreadGroup

aws ec2 start-instances \
    --instance-ids i-0123a456700123456
```
**例 4: プレイスメントグループからインスタンスを削除するには**  
次の `modify-instance-placement` の例では、インスタンスを停止し、インスタンスの配置を変更してからインスタンスを再起動して、インスタンスをプレイスメントグループから削除します。次の例では、プレイスメントグループ名に空の文字列 ("") を指定すると、インスタンスがプレイスメントグループに配置されないことを示しています。  
インスタンスを停止する  

```
aws ec2 stop-instances \
    --instance-ids i-0123a456700123456
```
配置を変更する (Windows コマンドプロンプト):  

```
aws ec2 modify-instance-placement \
    --instance-id i-0123a456700123456 \
    --group-name ""
```
配置を変更する (Windows PowerShell、Linux、macOS):  

```
aws ec2 modify-instance-placement `
    --instance-id i-0123a456700123456 `
    --group-name ''
```
インスタンスを再起動します:  

```
aws ec2 start-instances \
    --instance-ids i-0123a456700123456
```
出力:  

```
{
    "Return": true
}
```
詳細については、*Amazon EC2 ユーザーガイド*の「[専有ホストのテナンシーとアフィニティを変更する](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/moving-instances-dedicated-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstancePlacement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-instance-placement.html)」を参照してください。

### `modify-ipam-pool`
<a name="ec2_ModifyIpamPool_cli_2_topic"></a>

次のコード例は、`modify-ipam-pool` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールを変更するには**  
次の `modify-ipam-pool` の例では、IPAM プールを変更します。  
(Linux):  

```
aws ec2 modify-ipam-pool \
    --ipam-pool-id ipam-pool-0533048da7d823723 \
    --add-allocation-resource-tags "Key=Owner,Value=Build Team" \
    --clear-allocation-default-netmask-length \
    --allocation-min-netmask-length 14
```
(Windows):  

```
aws ec2 modify-ipam-pool ^
    --ipam-pool-id ipam-pool-0533048da7d823723 ^
    --add-allocation-resource-tags "Key=Owner,Value=Build Team" ^
    --clear-allocation-default-netmask-length ^
    --allocation-min-netmask-length 14
```
出力:  

```
{
    "IpamPool": {
        "OwnerId": "123456789012",
        "IpamPoolId": "ipam-pool-0533048da7d823723",
        "IpamPoolArn": "arn:aws:ec2::123456789012:ipam-pool/ipam-pool-0533048da7d823723",
        "IpamScopeArn": "arn:aws:ec2::123456789012:ipam-scope/ipam-scope-02fc38cd4c48e7d38",
        "IpamScopeType": "private",
        "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
        "IpamRegion": "us-east-1",
        "Locale": "None",
        "PoolDepth": 1,
        "State": "modify-complete",
        "AutoImport": true,
        "AddressFamily": "ipv4",
        "AllocationMinNetmaskLength": 14,
        "AllocationMaxNetmaskLength": 26,
        "AllocationResourceTags": [
            {
                "Key": "Environment",
                "Value": "Preprod"
            },
            {
                "Key": "Owner",
                "Value": "Build Team"
            }
        ]
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Edit a pool](https://docs.aws.amazon.com/vpc/latest/ipam/mod-pool-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyIpamPool](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-ipam-pool.html)」を参照してください。

### `modify-ipam-resource-cidr`
<a name="ec2_ModifyIpamResourceCidr_cli_2_topic"></a>

次のコード例は、`modify-ipam-resource-cidr` を使用する方法を示しています。

**AWS CLI**  
**リソースに割り当てられた CIDR を変更するには**  
次の `modify-ipam-resource-cidr` の例では、リソース CIDR を変更します。  
(Linux):  

```
aws ec2 modify-ipam-resource-cidr \
    --current-ipam-scope-id ipam-scope-02fc38cd4c48e7d38 \
    --destination-ipam-scope-id ipam-scope-0da34c61fd189a141 \
    --resource-id vpc-010e1791024eb0af9 \
    --resource-cidr 10.0.1.0/24 \
    --resource-region us-east-1 \
    --monitored
```
(Windows):  

```
aws ec2 modify-ipam-resource-cidr ^
    --current-ipam-scope-id ipam-scope-02fc38cd4c48e7d38 ^
    --destination-ipam-scope-id ipam-scope-0da34c61fd189a141 ^
    --resource-id vpc-010e1791024eb0af9 ^
    --resource-cidr 10.0.1.0/24 ^
    --resource-region us-east-1 ^
    --monitored
```
出力:  

```
{
    "IpamResourceCidr": {
        "IpamId": "ipam-08440e7a3acde3908",
        "IpamScopeId": "ipam-scope-0da34c61fd189a141",
        "IpamPoolId": "ipam-pool-0533048da7d823723",
        "ResourceRegion": "us-east-1",
        "ResourceOwnerId": "123456789012",
        "ResourceId": "vpc-010e1791024eb0af9",
        "ResourceCidr": "10.0.1.0/24",
        "ResourceType": "vpc",
        "ResourceTags": [
            {
                "Key": "Environment",
                "Value": "Preprod"
            },
            {
                "Key": "Owner",
                "Value": "Build Team"
            }
        ],
        "IpUsage": 0.0,
        "ComplianceStatus": "noncompliant",
        "ManagementState": "managed",
        "OverlapStatus": "overlapping",
        "VpcId": "vpc-010e1791024eb0af9"
    }
}
```
リソースの移動の詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Move resource CIDRs between scopes](https://docs.aws.amazon.com/vpc/latest/ipam/move-resource-ipam.html)」を参照してください。  
モニタリング状態の変更の詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Change the monitoring state of resource CIDRs](https://docs.aws.amazon.com/vpc/latest/ipam/change-monitoring-state-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyIpamResourceCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-ipam-resource-cidr.html)」を参照してください。

### `modify-ipam-resource-discovery`
<a name="ec2_ModifyIpamResourceDiscovery_cli_2_topic"></a>

次のコード例は、`modify-ipam-resource-discovery` を使用する方法を示しています。

**AWS CLI**  
**リソース検出の運用リージョンを変更するには**  
この例では、あなたは IPAM の委任された管理者として、リソース検出の運用リージョンを変更したいと考えています。  
このリクエストを完了するには:  
デフォルトのリソース検出を変更することはできません。また、リソース検出の所有者である必要があります。[describe-ipam-resource-discoveries](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-ipam-resource-discoveries.html) で取得できるリソース検出 ID が必要です。  
次の の`modify-ipam-resource-discovery`例では、 AWS アカウントのデフォルト以外のリソース検出を変更します。  

```
aws ec2 modify-ipam-resource-discovery \
    --ipam-resource-discovery-id ipam-res-disco-0f4ef577a9f37a162 \
    --add-operating-regions RegionName='us-west-1' \
    --remove-operating-regions RegionName='us-east-2' \
    --region us-east-1
```
出力:  

```
{
    "IpamResourceDiscovery": {
        "OwnerId": "149977607591",
        "IpamResourceDiscoveryId": "ipam-res-disco-0365d2977fc1672fe",
        "IpamResourceDiscoveryArn": "arn:aws:ec2::149977607591:ipam-resource-discovery/ipam-res-disco-0365d2977fc1672fe",
        "IpamResourceDiscoveryRegion": "us-east-1",
        "Description": "Example",
        "OperatingRegions": [
            {
                "RegionName": "us-east-1"
            },
            {
                "RegionName": "us-west-1"
            }
        ],
        "IsDefault": false,
        "State": "modify-in-progress"
    }
}
```
詳細については、「**Amazon VPC IPAM ユーザーズガイド」の「[リソース検出を使用する](https://docs.aws.amazon.com/vpc/latest/ipam/res-disc-work-with.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyIpamResourceDiscovery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-ipam-resource-discovery.html)」を参照してください。

### `modify-ipam-scope`
<a name="ec2_ModifyIpamScope_cli_2_topic"></a>

次のコード例は、`modify-ipam-scope` を使用する方法を示しています。

**AWS CLI**  
**範囲の説明を変更するには**  
このシナリオでは、あなたは IPAM の委任された管理者として、IPAM スコープの説明を変更したいと考えています。  
このリクエストを完了するには、[describe-ipam-scopes](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-ipam-scopes.html) で取得できるスコープ ID が必要です。  
次の `modify-ipam-scope` の例では、範囲の説明を更新します。  

```
aws ec2 modify-ipam-scope \
    --ipam-scope-id ipam-scope-0d3539a30b57dcdd1 \
    --description example \
    --region us-east-1
```
出力:  

```
{
"IpamScope": {
        "OwnerId": "320805250157",
        "IpamScopeId": "ipam-scope-0d3539a30b57dcdd1",
        "IpamScopeArn": "arn:aws:ec2::320805250157:ipam-scope/ipam-scope-0d3539a30b57dcdd1",
        "IpamArn": "arn:aws:ec2::320805250157:ipam/ipam-005f921c17ebd5107",
        "IpamRegion": "us-east-1",
        "IpamScopeType": "public",
        "IsDefault": true,
        "Description": "example",
        "PoolCount": 1,
        "State": "modify-in-progress"
    }
}
```
スコープの詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[How IPAM works](https://docs.aws.amazon.com/vpc/latest/ipam/how-it-works-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyIpamScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-ipam-scope.html)」を参照してください。

### `modify-ipam`
<a name="ec2_ModifyIpam_cli_2_topic"></a>

次のコード例は、`modify-ipam` を使用する方法を示しています。

**AWS CLI**  
**IPAM を変更するには**  
次の `modify-ipam` の例では、運用リージョンを追加して IPAM を変更します。  
(Linux):  

```
aws ec2 modify-ipam \
    --ipam-id ipam-08440e7a3acde3908 \
    --add-operating-regions RegionName=us-west-2
```
(Windows):  

```
aws ec2 modify-ipam ^
    --ipam-id ipam-08440e7a3acde3908 ^
    --add-operating-regions RegionName=us-west-2
```
出力:  

```
{
    "Ipam": {
        "OwnerId": "123456789012",
        "IpamId": "ipam-08440e7a3acde3908",
        "IpamArn": "arn:aws:ec2::123456789012:ipam/ipam-08440e7a3acde3908",
        "IpamRegion": "us-east-1",
        "PublicDefaultScopeId": "ipam-scope-0b9eed026396dbc16",
        "PrivateDefaultScopeId": "ipam-scope-02fc38cd4c48e7d38",
        "ScopeCount": 3,
        "OperatingRegions": [
            {
                "RegionName": "us-east-1"
            },
            {
                "RegionName": "us-east-2"
            },
            {
                "RegionName": "us-west-1"
            },
            {
                "RegionName": "us-west-2"
            }
        ],
        "State": "modify-in-progress"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyIpam](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-ipam.html)」を参照してください。

### `modify-launch-template`
<a name="ec2_ModifyLaunchTemplate_cli_2_topic"></a>

次のコード例は、`modify-launch-template` を使用する方法を示しています。

**AWS CLI**  
**デフォルトの起動テンプレートのバージョンを変更するには**  
この例では、指定された起動テンプレートのバージョン 2 をデフォルトバージョンとして指定します。  
コマンド:  

```
aws ec2 modify-launch-template --launch-template-id lt-0abcd290751193123 --default-version 2
```
出力:  

```
{
  "LaunchTemplate": {
      "LatestVersionNumber": 2,
      "LaunchTemplateId": "lt-0abcd290751193123",
      "LaunchTemplateName": "WebServers",
      "DefaultVersionNumber": 2,
      "CreatedBy": "arn:aws:iam::123456789012:root",
      "CreateTime": "2017-12-01T13:35:46.000Z"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyLaunchTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-launch-template.html)」を参照してください。

### `modify-managed-prefix-list`
<a name="ec2_ModifyManagedPrefixList_cli_2_topic"></a>

次のコード例は、`modify-managed-prefix-list` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストを変更するには**  
次の `modify-managed-prefix-list` の例では、指定したプレフィックスリストにエントリを追加します。  

```
aws ec2 modify-managed-prefix-list \
    --prefix-list-id pl-0123456abcabcabc1 \
    --add-entries Cidr=10.1.0.0/16,Description=vpc-c \
    --current-version 1
```
出力:  

```
{
    "PrefixList": {
        "PrefixListId": "pl-0123456abcabcabc1",
        "AddressFamily": "IPv4",
        "State": "modify-in-progress",
        "PrefixListArn": "arn:aws:ec2:us-west-2:123456789012:prefix-list/pl-0123456abcabcabc1",
        "PrefixListName": "vpc-cidrs",
        "MaxEntries": 10,
        "Version": 1,
        "OwnerId": "123456789012"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Managed prefix lists](https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyManagedPrefixList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-managed-prefix-list.html)」を参照してください。

### `modify-network-interface-attribute`
<a name="ec2_ModifyNetworkInterfaceAttribute_cli_2_topic"></a>

次のコード例は、`modify-network-interface-attribute` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイスのアタッチメント属性を変更するには**  
このコマンド例では、指定されたネットワークインターフェイスの `attachment` 属性を変更します。  
コマンド:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --attachment AttachmentId=eni-attach-43348162,DeleteOnTermination=false
```
**ネットワークインターフェイスの説明属性を変更するには**  
このコマンド例では、指定されたネットワークインターフェイスの `description` 属性を変更します。  
コマンド:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --description "My description"
```
**ネットワークインターフェイスの groupSet 属性を変更するには**  
このコマンド例では、指定されたネットワークインターフェイスの `groupSet` 属性を変更します。  
コマンド:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --groups sg-903004f8 sg-1a2b3c4d
```
**ネットワークインターフェイスの sourceDestCheck 属性を変更するには**  
このコマンド例では、指定されたネットワークインターフェイスの `sourceDestCheck` 属性を変更します。  
コマンド:  

```
aws ec2 modify-network-interface-attribute --network-interface-id eni-686ea200 --no-source-dest-check
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyNetworkInterfaceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-network-interface-attribute.html)」を参照してください。

### `modify-private-dns-name-options`
<a name="ec2_ModifyPrivateDnsNameOptions_cli_2_topic"></a>

次のコード例は、`modify-private-dns-name-options` を使用する方法を示しています。

**AWS CLI**  
**インスタンスホスト名に対するオプションを変更するには**  
次の `modify-private-dns-name-options` の例では、DNS A レコードを持つインスタンスホスト名の DNS クエリに応答するオプションを無効にします。  

```
aws ec2 modify-private-dns-name-options \
    --instance-id i-1234567890abcdef0 \
    --no-enable-resource-name-dns-a-record
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Amazon EC2 インスタンスホスト名のタイプ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-naming.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyPrivateDnsNameOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-private-dns-name-options.html)」を参照してください。

### `modify-reserved-instances`
<a name="ec2_ModifyReservedInstances_cli_2_topic"></a>

次のコード例は、`modify-reserved-instances` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスを変更するには**  
このコマンド例では、リザーブドインスタンスを同じリージョンにある別のアベイラビリティーゾーンに移動します。  
コマンド:  

```
aws ec2 modify-reserved-instances --reserved-instances-ids b847fa93-e282-4f55-b59a-1342f5bd7c02 --target-configurations AvailabilityZone=us-west-1c,Platform=EC2-Classic,InstanceCount=10
```
出力:  

```
{
  "ReservedInstancesModificationId": "rimod-d3ed4335-b1d3-4de6-ab31-0f13aaf46687"
}
```
**リザーブドインスタンスのネットワークプラットフォームを変更するには**  
このコマンド例では、EC2-Classic リザーブドインスタンスを EC2-VPC に変換します。  
コマンド:  

```
aws ec2 modify-reserved-instances --reserved-instances-ids f127bd27-edb7-44c9-a0eb-0d7e09259af0 --target-configurations AvailabilityZone=us-west-1c,Platform=EC2-VPC,InstanceCount=5
```
出力:  

```
{
  "ReservedInstancesModificationId": "rimod-82fa9020-668f-4fb6-945d-61537009d291"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「リザーブドインスタンス の変更」を参照してください。  
**リザーブドインスタンスのインスタンスサイズを変更するには**  
このコマンド例では、us-west-1c に 10 個の m1.small Linux/UNIX インスタンスを持つリザーブドインスタンスを変更して、8 個の m1.small インスタンスを 2 個の m1.large インスタンスにし、残りの 2 個の m1.small を同じアベイラビリティーゾーンの 1 個の m1.medium インスタンスにします。コマンド:  

```
aws ec2 modify-reserved-instances --reserved-instances-ids 1ba8e2e3-3556-4264-949e-63ee671405a9 --target-configurations AvailabilityZone=us-west-1c,Platform=EC2-Classic,InstanceCount=2,InstanceType=m1.large AvailabilityZone=us-west-1c,Platform=EC2-Classic,InstanceCount=1,InstanceType=m1.medium
```
出力:  

```
{
    "ReservedInstancesModificationId": "rimod-acc5f240-080d-4717-b3e3-1c6b11fa00b6"
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「Modifying the Instance Size of Your Reservations」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyReservedInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-reserved-instances.html)」を参照してください。

### `modify-security-group-rules`
<a name="ec2_ModifySecurityGroupRules_cli_2_topic"></a>

次のコード例は、`modify-security-group-rules` を使用する方法を示しています。

**AWS CLI**  
**セキュリティグループルールを変更して、ルールの説明、IP プロトコル、および CidrIpv4 アドレス範囲を更新するには**  
次の `modify-security-group-rules` の例では、指定したセキュリティグループルールの説明、IP プロトコル、IPV4 CIDR 範囲を更新します。`security-group-rules` パラメータを使用して、指定されたセキュリティグループルールの更新を入力します。`-1` はすべてのプロトコルを指定します。  

```
aws ec2 modify-security-group-rules \
    --group-id sg-1234567890abcdef0 \
    --security-group-rules SecurityGroupRuleId=sgr-abcdef01234567890,SecurityGroupRule='{Description=test,IpProtocol=-1,CidrIpv4=0.0.0.0/0}'
```
出力:  

```
{
    "Return": true
}
```
セキュリティグループのルールの詳細については、「*Amazon EC2 ユーザーガイド*」の「[セキュリティグループのルール](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifySecurityGroupRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-security-group-rules.html)」を参照してください。

### `modify-snapshot-attribute`
<a name="ec2_ModifySnapshotAttribute_cli_2_topic"></a>

次のコード例は、`modify-snapshot-attribute` を使用する方法を示しています。

**AWS CLI**  
**例 1: スナップショット属性を変更するには**  
次の `modify-snapshot-attribute` の例では、指定したスナップショットの `createVolumePermission` 属性を更新し、指定したユーザーのボリュームアクセス許可を削除します。  

```
aws ec2 modify-snapshot-attribute \
    --snapshot-id snap-1234567890abcdef0 \
    --attribute createVolumePermission \
    --operation-type remove \
    --user-ids 123456789012
```
**例 2: スナップショットをパブリックにするには**  
次の `modify-snapshot-attribute` の例では、指定したスナップショットを公開します。  

```
aws ec2 modify-snapshot-attribute \
    --snapshot-id snap-1234567890abcdef0 \
    --attribute createVolumePermission \
    --operation-type add \
    --group-names all
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifySnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-snapshot-attribute.html)」を参照してください。

### `modify-snapshot-tier`
<a name="ec2_ModifySnapshotTier_cli_2_topic"></a>

次のコード例は、`modify-snapshot-tier` を使用する方法を示しています。

**AWS CLI**  
**スナップショットをアーカイブするには**  
次の `modify-snapshot-tier` の例では、指定したスナップショットをアーカイブします。`TieringStartTime` レスポンスパラメータは、アーカイブプロセスが開始された日付と時刻を、UTC 時間形式 (YYYY-MM-DDTHH:MM:SSZ) で示します。  

```
aws ec2 modify-snapshot-tier \
    --snapshot-id snap-01234567890abcedf \
    --storage-tier archive
```
出力:  

```
{
    "SnapshotId": "snap-01234567890abcedf",
    "TieringStartTime": "2021-09-15T16:44:37.574Z"
}
```
スナップショットのアーカイブの詳細については、*Amazon EBS ユーザーガイド*の「[Amazon EBS スナップショットのアーカイブ](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifySnapshotTier](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-snapshot-tier.html)」を参照してください。

### `modify-spot-fleet-request`
<a name="ec2_ModifySpotFleetRequest_cli_2_topic"></a>

次のコード例は、`modify-spot-fleet-request` を使用する方法を示しています。

**AWS CLI**  
**スポットフリートリクエストを変更するには**  
このコマンド例では、指定されたスポットフリートリクエストのターゲット容量を更新します。  
コマンド:  

```
aws ec2 modify-spot-fleet-request --target-capacity 20 --spot-fleet-request-id sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
出力:  

```
{
    "Return": true
}
```
このコマンド例では、結果的にいずれのスポットインスタンスも終了せずに、指定したスポットフリートのターゲット容量を減らします。  
コマンド:  

```
aws ec2 modify-spot-fleet-request --target-capacity 10 --excess-capacity-termination-policy NoTermination --spot-fleet-request-ids sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
出力:  

```
{
    "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifySpotFleetRequest](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-spot-fleet-request.html)」を参照してください。

### `modify-subnet-attribute`
<a name="ec2_ModifySubnetAttribute_cli_2_topic"></a>

次のコード例は、`modify-subnet-attribute` を使用する方法を示しています。

**AWS CLI**  
**サブネットのパブリック IPv4 アドレス指定の動作を変更するには**  
この例では、subnet-1a2b3c4d を変更して、このサブネットで起動されたすべてのインスタンスにパブリック IPv4 アドレスが割り当てられるように指定します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 modify-subnet-attribute --subnet-id subnet-1a2b3c4d --map-public-ip-on-launch
```
**サブネットの IPv6 アドレス指定の動作を変更するには**  
この例では、subnet-1a2b3c4d を変更して、このサブネットで起動されたすべてのインスタンスに、そのサブネットの範囲から IPv6 アドレスが割り当てられるように指定します。  
コマンド:  

```
aws ec2 modify-subnet-attribute --subnet-id subnet-1a2b3c4d --assign-ipv6-address-on-creation
```
詳細については、「*AWS Virtual Private Cloud ユーザーガイド*」の「VPC とサブネットの IP アドレス指定」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifySubnetAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-subnet-attribute.html)」を参照してください。

### `modify-traffic-mirror-filter-network-services`
<a name="ec2_ModifyTrafficMirrorFilterNetworkServices_cli_2_topic"></a>

次のコード例は、`modify-traffic-mirror-filter-network-services` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーフィルターにネットワークサービスを追加するには**  
次の `modify-traffic-mirror-filter-network-services` の例では、Amazon DNS ネットワークサービスを指定されたフィルターに追加します。  

```
aws ec2 modify-traffic-mirror-filter-network-services \
    --traffic-mirror-filter-id tmf-04812ff784EXAMPLE \
    --add-network-service amazon-dns
```
出力:  

```
{
    "TrafficMirrorFilter": {
        "Tags": [
            {
                "Key": "Name",
                "Value": "Production"
            }
        ],
        "EgressFilterRules": [],
        "NetworkServices": [
            "amazon-dns"
        ],
        "TrafficMirrorFilterId": "tmf-04812ff784EXAMPLE",
        "IngressFilterRules": [
            {
                "SourceCidrBlock": "0.0.0.0/0",
                "RuleNumber": 1,
                "DestinationCidrBlock": "0.0.0.0/0",
                "Description": "TCP Rule",
                "Protocol": 6,
                "TrafficDirection": "ingress",
                "TrafficMirrorFilterId": "tmf-04812ff784EXAMPLE",
                "RuleAction": "accept",
                "TrafficMirrorFilterRuleId": "tmf-04812ff784EXAMPLE"
            }
        ]
    }
}
```
詳細については、「*AWS トラフィックミラーリングガイド*」の「[Modify Traffic Mirror Filter Network Services](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-filter.html#modify-traffic-mirroring-filter-network-services)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTrafficMirrorFilterNetworkServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-traffic-mirror-filter-network-services.html)」を参照してください。

### `modify-traffic-mirror-filter-rule`
<a name="ec2_ModifyTrafficMirrorFilterRule_cli_2_topic"></a>

次のコード例は、`modify-traffic-mirror-filter-rule` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーフィルタールールを変更するには**  
次の `modify-traffic-mirror-filter-rule` の例では、指定したトラフィックミラーフィルタールールを変更します。  

```
aws ec2 modify-traffic-mirror-filter-rule \
    --traffic-mirror-filter-rule-id tmfr-0ca76e0e08EXAMPLE \
    --description "TCP Rule"
```
出力:  

```
{
    "TrafficMirrorFilterRule": {
        "TrafficMirrorFilterRuleId": "tmfr-0ca76e0e08EXAMPLE",
        "TrafficMirrorFilterId": "tmf-0293f26e86EXAMPLE",
        "TrafficDirection": "ingress",
        "RuleNumber": 100,
        "RuleAction": "accept",
        "Protocol": 6,
        "DestinationCidrBlock": "10.0.0.0/24",
        "SourceCidrBlock": "10.0.0.0/24",
        "Description": "TCP Rule"
    }
}
```
詳細については、「*AWS トラフィックミラーリングガイド*」の「[Modify Your Traffic Mirror Filter Rules](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-filter.html#modify-traffic-mirroring-filter-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTrafficMirrorFilterRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-traffic-mirror-filter-rule.html)」を参照してください。

### `modify-traffic-mirror-session`
<a name="ec2_ModifyTrafficMirrorSession_cli_2_topic"></a>

次のコード例は、`modify-traffic-mirror-session` を使用する方法を示しています。

**AWS CLI**  
**トラフィックミラーセッションを変更するには**  
次の `modify-traffic-mirror-session` の例では、トラフィックミラーセッションの説明とミラーリングするパケットの数を変更します。  

```
aws ec2 modify-traffic-mirror-session \
    --description "Change packet length" \
    --traffic-mirror-session-id tms-08a33b1214EXAMPLE \
    --remove-fields "packet-length"
```
出力:  

```
{
    "TrafficMirrorSession": {
        "TrafficMirrorSessionId": "tms-08a33b1214EXAMPLE",
        "TrafficMirrorTargetId": "tmt-07f75d8feeEXAMPLE",
        "TrafficMirrorFilterId": "tmf-04812ff784EXAMPLE",
        "NetworkInterfaceId": "eni-070203f901EXAMPLE",
        "OwnerId": "111122223333",
        "SessionNumber": 1,
        "VirtualNetworkId": 7159709,
        "Description": "Change packet length",
        "Tags": []
    }
}
```
詳細については、「* トラフィックミラーリングガイド*」の「[Modify your traffic mirror session](https://docs.aws.amazon.com/vpc/latest/mirroring/traffic-mirroring-session.html#modify-traffic-mirroring-session)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTrafficMirrorSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-traffic-mirror-session.html)」を参照してください。

### `modify-transit-gateway-prefix-list-reference`
<a name="ec2_ModifyTransitGatewayPrefixListReference_cli_2_topic"></a>

次のコード例は、`modify-transit-gateway-prefix-list-reference` を使用する方法を示しています。

**AWS CLI**  
**プレフィックスリストのリファレンスを変更するには**  
次の `modify-transit-gateway-prefix-list-reference` の例では、トラフィックがルーティングされるアタッチメントを変更して、指定されたルートテーブルのプレフィックスリストのリファレンスを変更します。  

```
aws ec2 modify-transit-gateway-prefix-list-reference \
    --transit-gateway-route-table-id tgw-rtb-0123456789abcd123 \
    --prefix-list-id pl-11111122222222333 \
    --transit-gateway-attachment-id tgw-attach-aabbccddaabbccaab
```
出力:  

```
{
    "TransitGatewayPrefixListReference": {
        "TransitGatewayRouteTableId": "tgw-rtb-0123456789abcd123",
        "PrefixListId": "pl-11111122222222333",
        "PrefixListOwnerId": "123456789012",
        "State": "modifying",
        "Blackhole": false,
        "TransitGatewayAttachment": {
            "TransitGatewayAttachmentId": "tgw-attach-aabbccddaabbccaab",
            "ResourceType": "vpc",
            "ResourceId": "vpc-112233445566aabbc"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Prefix list references](https://docs.aws.amazon.com/vpc/latest/tgw/create-prefix-list-reference.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTransitGatewayPrefixListReference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-transit-gateway-prefix-list-reference.html)」を参照してください。

### `modify-transit-gateway-vpc-attachment`
<a name="ec2_ModifyTransitGatewayVpcAttachment_cli_2_topic"></a>

次のコード例は、`modify-transit-gateway-vpc-attachment` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway VPC アタッチメントを変更するには**  
次の `modify-transit-gateway-vpc-attachment` の例では、指定された Transit Gateway VPC アタッチメントにサブネットを追加します。  

```
aws ec2 modify-transit-gateway-vpc-attachment \
    --transit-gateway-attachment-id tgw-attach-09fbd47ddfEXAMPLE \
    --add-subnet-ids subnet-0e51f45802EXAMPLE
```
出力:  

```
{
    "TransitGatewayVpcAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-09fbd47ddfEXAMPLE",
        "TransitGatewayId": "tgw-0560315ccfEXAMPLE",
        "VpcId": "vpc-5eccc927",
        "VpcOwnerId": "111122223333",
        "State": "modifying",
        "SubnetIds": [
            "subnet-0e51f45802EXAMPLE",
            "subnet-1EXAMPLE"
        ],
        "CreationTime": "2019-08-08T16:47:38.000Z",
        "Options": {
            "DnsSupport": "enable",
            "Ipv6Support": "disable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway attachments to a VPC](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTransitGatewayVpcAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-transit-gateway-vpc-attachment.html)」を参照してください。

### `modify-transit-gateway`
<a name="ec2_ModifyTransitGateway_cli_2_topic"></a>

次のコード例は、`modify-transit-gateway` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway を変更するには**  
次の `modify-transit-gateway` の例では、VPN アタッチメントの ECMP サポートを有効にして、指定された Transit Gateway を変更します。  

```
aws ec2 modify-transit-gateway \
    --transit-gateway-id tgw-111111222222aaaaa \
    --options VpnEcmpSupport=enable
```
出力:  

```
{
    "TransitGateway": {
        "TransitGatewayId": "tgw-111111222222aaaaa",
        "TransitGatewayArn": "64512",
        "State": "modifying",
        "OwnerId": "123456789012",
        "CreationTime": "2020-04-30T08:41:37.000Z",
        "Options": {
            "AmazonSideAsn": 64512,
            "AutoAcceptSharedAttachments": "disable",
            "DefaultRouteTableAssociation": "enable",
            "AssociationDefaultRouteTableId": "tgw-rtb-0123456789abcd123",
            "DefaultRouteTablePropagation": "enable",
            "PropagationDefaultRouteTableId": "tgw-rtb-0123456789abcd123",
            "VpnEcmpSupport": "enable",
            "DnsSupport": "enable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateways](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTransitGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-transit-gateway.html)」を参照してください。

### `modify-verified-access-endpoint-policy`
<a name="ec2_ModifyVerifiedAccessEndpointPolicy_cli_2_topic"></a>

次のコード例は、`modify-verified-access-endpoint-policy` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントの Verified Access ポリシーを設定するには**  
次の `modify-verified-access-endpoint-policy` の例では、指定した Verified Access ポリシーを指定した Verified Access エンドポイントに追加します。  

```
aws ec2 modify-verified-access-endpoint-policy \
    --verified-access-endpoint-id vae-066fac616d4d546f2 \
    --policy-enabled \
    --policy-document file://policy.txt
```
`policy.txt` の内容:  

```
permit(principal,action,resource)
when {
    context.identity.groups.contains("finance") &&
    context.identity.email.verified == true
};
```
出力:  

```
{
    "PolicyEnabled": true,
    "PolicyDocument": "permit(principal,action,resource)\nwhen {\n    context.identity.groups.contains(\"finance\") &&\n    context.identity.email_verified == true\n};"
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access policies](https://docs.aws.amazon.com/verified-access/latest/ug/auth-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVerifiedAccessEndpointPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-verified-access-endpoint-policy.html)」を参照してください。

### `modify-verified-access-endpoint`
<a name="ec2_ModifyVerifiedAccessEndpoint_cli_2_topic"></a>

次のコード例は、`modify-verified-access-endpoint` を使用する方法を示しています。

**AWS CLI**  
**Verified Access エンドポイントの設定を変更するには**  
次の `modify-verified-access-endpoint` の例では、指定した説明を指定した Verified Access エンドポイントに追加します。  

```
aws ec2 modify-verified-access-endpoint \
    --verified-access-endpoint-id vae-066fac616d4d546f2 \
    --description 'Testing Verified Access'
```
出力:  

```
{
    "VerifiedAccessEndpoint": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
        "VerifiedAccessEndpointId": "vae-066fac616d4d546f2",
        "ApplicationDomain": "example.com",
        "EndpointType": "network-interface",
        "AttachmentType": "vpc",
        "DomainCertificateArn": "arn:aws:acm:us-east-2:123456789012:certificate/eb065ea0-26f9-4e75-a6ce-0a1a7EXAMPLE",
        "EndpointDomain": "my-ava-app.edge-00c3372d53b1540bb.vai-0ce000c0b7643abea.prod.verified-access.us-east-2.amazonaws.com",
        "SecurityGroupIds": [
            "sg-004915970c4c8f13a"
        ],
        "NetworkInterfaceOptions": {
            "NetworkInterfaceId": "eni-0aec70418c8d87a0f",
            "Protocol": "https",
            "Port": 443
        },
        "Status": {
            "Code": "updating"
        },
        "Description": "Testing Verified Access",
        "CreationTime": "2023-08-25T20:54:43",
        "LastUpdatedTime": "2023-08-25T22:46:32"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access endpoints](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVerifiedAccessEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-verified-access-endpoint.html)」を参照してください。

### `modify-verified-access-group-policy`
<a name="ec2_ModifyVerifiedAccessGroupPolicy_cli_2_topic"></a>

次のコード例は、`modify-verified-access-group-policy` を使用する方法を示しています。

**AWS CLI**  
**グループに Verified Access ポリシーを設定するには**  
次の `modify-verified-access-group-policy` の例では、指定した Verified Access ポリシーを指定した Verified Access グループに追加します。  

```
aws ec2 modify-verified-access-group-policy \
    --verified-access-group-id vagr-0dbe967baf14b7235 \
    --policy-enabled \
    --policy-document file://policy.txt
```
`policy.txt` の内容:  

```
permit(principal,action,resource)
when {
    context.identity.groups.contains("finance") &&
    context.identity.email.verified == true
};
```
出力:  

```
{
    "PolicyEnabled": true,
    "PolicyDocument": "permit(principal,action,resource)\nwhen {\n    context.identity.groups.contains(\"finance\") &&\n    context.identity.email_verified == true\n};"
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access groups](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVerifiedAccessGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-verified-access-group-policy.html)」を参照してください。

### `modify-verified-access-group`
<a name="ec2_ModifyVerifiedAccessGroup_cli_2_topic"></a>

次のコード例は、`modify-verified-access-group` を使用する方法を示しています。

**AWS CLI**  
**Verified Access グループの設定を変更するには**  
次の `modify-verified-access-group` の例では、指定した説明を指定した Verified Access グループに追加します。  

```
aws ec2 modify-verified-access-group \
    --verified-access-group-id vagr-0dbe967baf14b7235 \
    --description "Testing Verified Access"
```
出力:  

```
{
    "VerifiedAccessGroup": {
        "VerifiedAccessGroupId": "vagr-0dbe967baf14b7235",
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "Testing Verified Access",
        "Owner": "123456789012",
        "VerifiedAccessGroupArn": "arn:aws:ec2:us-east-2:123456789012:verified-access-group/vagr-0dbe967baf14b7235",
        "CreationTime": "2023-08-25T19:55:19",
        "LastUpdatedTime": "2023-08-25T22:17:25"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access groups](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVerifiedAccessGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-verified-access-group.html)」を参照してください。

### `modify-verified-access-instance-logging-configuration`
<a name="ec2_ModifyVerifiedAccessInstanceLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`modify-verified-access-instance-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**Verified Access インスタンスのログ記録を有効にするには**  
次の `modify-verified-access-instance-logging-configuration` の例では、指定した Verified Access インスタンスのアクセスロギングを有効にします。ログは、指定された CloudWatch Logs ロググループに配信されます。  

```
aws ec2 modify-verified-access-instance-logging-configuration \
    --verified-access-instance-id vai-0ce000c0b7643abea \
    --access-logs CloudWatchLogs={Enabled=true,LogGroup=my-log-group}
```
出力:  

```
{
    "LoggingConfiguration": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "AccessLogs": {
            "S3": {
                "Enabled": false
            },
            "CloudWatchLogs": {
                "Enabled": true,
                "DeliveryStatus": {
                    "Code": "success"
                },
                "LogGroup": "my-log-group"
            },
            "KinesisDataFirehose": {
                "Enabled": false
            },
            "LogVersion": "ocsf-1.0.0-rc.2",
            "IncludeTrustContext": false
        }
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Verified Access logs](https://docs.aws.amazon.com/verified-access/latest/ug/access-logs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVerifiedAccessInstanceLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-verified-access-instance-logging-configuration.html)」を参照してください。

### `modify-verified-access-instance`
<a name="ec2_ModifyVerifiedAccessInstance_cli_2_topic"></a>

次のコード例は、`modify-verified-access-instance` を使用する方法を示しています。

**AWS CLI**  
**Verified Access インスタンスの設定を変更するには**  
次の `modify-verified-access-instance` の例では、指定した説明を指定した Verified Access インスタンスに追加します。  

```
aws ec2 modify-verified-access-instance \
    --verified-access-instance-id vai-0ce000c0b7643abea \
    --description "Testing Verified Access"
```
出力:  

```
{
    "VerifiedAccessInstance": {
        "VerifiedAccessInstanceId": "vai-0ce000c0b7643abea",
        "Description": "Testing Verified Access",
        "VerifiedAccessTrustProviders": [
            {
                "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
                "TrustProviderType": "user",
                "UserTrustProviderType": "iam-identity-center"
            }
        ],
        "CreationTime": "2023-08-25T18:27:56",
        "LastUpdatedTime": "2023-08-25T22:41:04"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Access インスタンス](https://docs.aws.amazon.com/verified-access/latest/ug/verified-access-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVerifiedAccessInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-verified-access-instance.html)」を参照してください。

### `modify-verified-access-trust-provider`
<a name="ec2_ModifyVerifiedAccessTrustProvider_cli_2_topic"></a>

次のコード例は、`modify-verified-access-trust-provider` を使用する方法を示しています。

**AWS CLI**  
**Verified Access 信頼プロバイダーの設定を変更するには**  
次の `modify-verified-access-trust-provider` の例では、指定した説明を指定した Verified Access 信頼プロバイダーに追加します。  

```
aws ec2 modify-verified-access-trust-provider \
    --verified-access-trust-provider-id vatp-0bb32de759a3e19e7 \
    --description "Testing Verified Access"
```
出力:  

```
{
    "VerifiedAccessTrustProvider": {
        "VerifiedAccessTrustProviderId": "vatp-0bb32de759a3e19e7",
        "Description": "Testing Verified Access",
        "TrustProviderType": "user",
        "UserTrustProviderType": "iam-identity-center",
        "PolicyReferenceName": "idc",
        "CreationTime": "2023-08-25T19:00:38",
        "LastUpdatedTime": "2023-08-25T19:18:21"
    }
}
```
詳細については、「*AWS Verified Access ユーザーガイド*」の「[Trust providers for Verified Access](https://docs.aws.amazon.com/verified-access/latest/ug/trust-providers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVerifiedAccessTrustProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-verified-access-trust-provider.html)」を参照してください。

### `modify-volume-attribute`
<a name="ec2_ModifyVolumeAttribute_cli_2_topic"></a>

次のコード例は、`modify-volume-attribute` を使用する方法を示しています。

**AWS CLI**  
**ボリューム属性を変更するには**  
この例では、ID `vol-1234567890abcdef0` を持つボリュームの `autoEnableIo` 属性を `true` に設定します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 modify-volume-attribute --volume-id vol-1234567890abcdef0 --auto-enable-io
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVolumeAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-volume-attribute.html)」を参照してください。

### `modify-volume`
<a name="ec2_ModifyVolume_cli_2_topic"></a>

次のコード例は、`modify-volume` を使用する方法を示しています。

**AWS CLI**  
**例 1: ボリュームのサイズを変更してボリュームを変更するには**  
次の `modify-volume` の例では、指定されたボリュームのサイズを 150 GB に変更します。  
コマンド:  

```
aws ec2 modify-volume --size 150 --volume-id vol-1234567890abcdef0
```
出力:  

```
{
    "VolumeModification": {
        "TargetSize": 150,
        "TargetVolumeType": "io1",
        "ModificationState": "modifying",
        "VolumeId": " vol-1234567890abcdef0",
        "TargetIops": 100,
        "StartTime": "2019-05-17T11:27:19.000Z",
        "Progress": 0,
        "OriginalVolumeType": "io1",
        "OriginalIops": 100,
        "OriginalSize": 100
    }
}
```
**例 2: ボリュームのタイプ、サイズ、IOPS 値を変更してボリュームを変更するには**  
次の `modify-volume` の例では、ボリュームタイプをプロビジョンド IOPS SSD に変更して、ターゲット IOPS レートを 10,000 に設定し、ボリュームサイズを 350 GB に設定します。  

```
aws ec2 modify-volume \
    --volume-type io1 \
    --iops 10000 \
    --size 350 \
    --volume-id vol-1234567890abcdef0
```
出力:  

```
{
    "VolumeModification": {
        "TargetSize": 350,
        "TargetVolumeType": "io1",
        "ModificationState": "modifying",
        "VolumeId": "vol-0721c1a9d08c93bf6",
        "TargetIops": 10000,
        "StartTime": "2019-05-17T11:38:57.000Z",
        "Progress": 0,
        "OriginalVolumeType": "gp2",
        "OriginalIops": 150,
        "OriginalSize": 50
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVolume](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-volume.html)」を参照してください。

### `modify-vpc-attribute`
<a name="ec2_ModifyVpcAttribute_cli_2_topic"></a>

次のコード例は、`modify-vpc-attribute` を使用する方法を示しています。

**AWS CLI**  
**enableDnsSupport 属性を変更するには**  
この例では、`enableDnsSupport` 属性を変更します。この属性は、VPC に対して DNS 解決が有効になっているかどうかを示します。この属性が `true` の場合、Amazon DNS サーバーはインスタンスの DNS ホスト名を対応する IP アドレスに解決します。それ以外の場合は解決しません。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 modify-vpc-attribute --vpc-id vpc-a01106c2 --enable-dns-support "{\"Value\":false}"
```
**enableDnsHostnames 属性を変更するには**  
この例では、`enableDnsHostnames` 属性を変更します。この属性は、VPC 内に起動されるインスタンスが DNS ホスト名を取得するかどうかを示します。この属性が `true` の場合、VPC 内のインスタンスは DNS ホスト名を取得します。それ以外の場合は取得しません。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 modify-vpc-attribute --vpc-id vpc-a01106c2 --enable-dns-hostnames "{\"Value\":false}"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-attribute.html)」を参照してください。

### `modify-vpc-endpoint-connection-notification`
<a name="ec2_ModifyVpcEndpointConnectionNotification_cli_2_topic"></a>

次のコード例は、`modify-vpc-endpoint-connection-notification` を使用する方法を示しています。

**AWS CLI**  
**エンドポイント接続通知を変更するには**  
この例では、指定されたエンドポイント接続通知の SNS トピックを変更します。  
コマンド:  

```
aws ec2 modify-vpc-endpoint-connection-notification --connection-notification-id vpce-nfn-008776de7e03f5abc --connection-events Accept Reject --connection-notification-arn arn:aws:sns:us-east-2:123456789012:mytopic
```
出力:  

```
{
   "ReturnValue": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcEndpointConnectionNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-endpoint-connection-notification.html)」を参照してください。

### `modify-vpc-endpoint-service-configuration`
<a name="ec2_ModifyVpcEndpointServiceConfiguration_cli_2_topic"></a>

次のコード例は、`modify-vpc-endpoint-service-configuration` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントサービス設定を削除するには**  
この例では、指定されたエンドポイントサービスの承諾要件を変更します。  
コマンド:  

```
aws ec2 modify-vpc-endpoint-service-configuration --service-id vpce-svc-09222513e6e77dc86 --no-acceptance-required
```
出力:  

```
{
   "ReturnValue": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcEndpointServiceConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-endpoint-service-configuration.html)」を参照してください。

### `modify-vpc-endpoint-service-payer-responsibility`
<a name="ec2_ModifyVpcEndpointServicePayerResponsibility_cli_2_topic"></a>

次のコード例は、`modify-vpc-endpoint-service-payer-responsibility` を使用する方法を示しています。

**AWS CLI**  
**支払者の責任を変更するには**  
次の `modify-vpc-endpoint-service-payer-responsibility` の例では、指定されたエンドポイントサービスの支払者の責任を変更します。  

```
aws ec2 modify-vpc-endpoint-service-payer-responsibility \
    --service-id vpce-svc-071afff70666e61e0 \
    --payer-responsibility ServiceOwner
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcEndpointServicePayerResponsibility](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-endpoint-service-payer-responsibility.html)」を参照してください。

### `modify-vpc-endpoint-service-permissions`
<a name="ec2_ModifyVpcEndpointServicePermissions_cli_2_topic"></a>

次のコード例は、`modify-vpc-endpoint-service-permissions` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントサービスのアクセス許可を変更するには**  
この例では、 AWS アカウントが指定されたエンドポイントサービスに接続するためのアクセス許可を追加します。  
コマンド:  

```
aws ec2 modify-vpc-endpoint-service-permissions --service-id vpce-svc-03d5ebb7d9579a2b3 --add-allowed-principals '["arn:aws:iam::123456789012:root"]'
```
出力:  

```
{
   "ReturnValue": true
}
```
この例では、特定の IAM ユーザー (`admin`) が指定されたエンドポイントサービスに接続するためのアクセス許可を追加します。  
コマンド:  

```
aws ec2 modify-vpc-endpoint-service-permissions --service-id vpce-svc-03d5ebb7d9579a2b3 --add-allowed-principals '["arn:aws:iam::123456789012:user/admin"]'
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcEndpointServicePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-endpoint-service-permissions.html)」を参照してください。

### `modify-vpc-endpoint`
<a name="ec2_ModifyVpcEndpoint_cli_2_topic"></a>

次のコード例は、`modify-vpc-endpoint` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイエンドポイントを変更するには**  
この例では、ルートテーブル `rtb-aaa222bb` をエンドポイントに関連付け、ポリシードキュメントをリセットすることで、ゲートウェイエンドポイント `vpce-1a2b3c4d` を変更します。  
コマンド:  

```
aws ec2 modify-vpc-endpoint --vpc-endpoint-id vpce-1a2b3c4d --add-route-table-ids rtb-aaa222bb --reset-policy
```
出力:  

```
{
  "Return": true
}
```
**インターフェイスエンドポイントを変更するには**  
この例では、エンドポイントにサブネット `subnet-d6fcaa8d` を追加してインターフェイスエンドポイント `vpce-0fe5b17a0707d6fa5` を変更します。  
コマンド:  

```
aws ec2 modify-vpc-endpoint --vpc-endpoint-id vpce-0fe5b17a0707d6fa5 --add-subnet-id subnet-d6fcaa8d
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-endpoint.html)」を参照してください。

### `modify-vpc-peering-connection-options`
<a name="ec2_ModifyVpcPeeringConnectionOptions_cli_2_topic"></a>

次のコード例は、`modify-vpc-peering-connection-options` を使用する方法を示しています。

**AWS CLI**  
**ローカル ClassicLink 接続から VPC ピアリング接続を介した通信を有効にするには**  
この例では、ピアリング接続 `pcx-aaaabbb` の場合、リクエスタ VPC の所有者は VPC ピアリング接続オプションを変更して、ローカル ClassicLink 接続がピア VPC と通信できるようにします。  
コマンド:  

```
aws ec2 modify-vpc-peering-connection-options --vpc-peering-connection-id pcx-aaaabbbb --requester-peering-connection-options AllowEgressFromLocalClassicLinkToRemoteVpc=true
```
出力:  

```
{
  "RequesterPeeringConnectionOptions": {
      "AllowEgressFromLocalClassicLinkToRemoteVpc": true
  }
}
```
**ローカル VPC からリモート ClassicLink 接続への VPC ピアリング接続を介した通信を有効にするには**  
この例では、アクセプタ VPC の所有者は VPC ピアリング接続オプションを変更して、ローカル VPC がピア VPC の ClassicLink 接続と通信できるようにします。  
コマンド:  

```
aws ec2 modify-vpc-peering-connection-options --vpc-peering-connection-id pcx-aaaabbbb --accepter-peering-connection-options AllowEgressFromLocalVpcToRemoteClassicLink=true
```
出力:  

```
{
  "AccepterPeeringConnectionOptions": {
    "AllowEgressFromLocalVpcToRemoteClassicLink": true
  }
}
```
**VPC ピアリング接続の DNS 解決サポートを有効にするには**  
この例では、リクエスタ VPC の所有者は、`pcx-aaaabbbb` の VPC ピアリング接続オプションを変更して、ピア VPC のインスタンスからクエリされたときに、ローカル VPC がパブリック DNS ホスト名をプライベート IP アドレスに解決できるようにします。  
コマンド:  

```
aws ec2 modify-vpc-peering-connection-options --vpc-peering-connection-id pcx-aaaabbbb --requester-peering-connection-options AllowDnsResolutionFromRemoteVpc=true
```
出力:  

```
{
  "RequesterPeeringConnectionOptions": {
      "AllowDnsResolutionFromRemoteVpc": true
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcPeeringConnectionOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-peering-connection-options.html)」を参照してください。

### `modify-vpc-tenancy`
<a name="ec2_ModifyVpcTenancy_cli_2_topic"></a>

次のコード例は、`modify-vpc-tenancy` を使用する方法を示しています。

**AWS CLI**  
**VPC のテナンシーを変更するには**  
この例では、VPC `default` のテナンシーを `vpc-1a2b3c4d` に変更します。  
コマンド:  

```
aws ec2 modify-vpc-tenancy --vpc-id vpc-1a2b3c4d --instance-tenancy default
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpcTenancy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpc-tenancy.html)」を参照してください。

### `modify-vpn-connection-options`
<a name="ec2_ModifyVpnConnectionOptions_cli_2_topic"></a>

次のコード例は、`modify-vpn-connection-options` を使用する方法を示しています。

**AWS CLI**  
**VPN 接続オプションを変更する**  
次の `modify-vpn-connection-options` の例では、指定された VPN 接続のカスタマーゲートウェイ側のローカル IPv4 CIDR を変更します。  

```
aws ec2 modify-vpn-connection-options \
    --vpn-connection-id vpn-1122334455aabbccd \
    --local-ipv4-network-cidr 10.0.0.0/16
```
出力:  

```
{
    "VpnConnections": [
        {
            "CustomerGatewayConfiguration": "...configuration information...",
            "CustomerGatewayId": "cgw-01234567abcde1234",
            "Category": "VPN",
            "State": "modifying",
            "Type": "ipsec.1",
            "VpnConnectionId": "vpn-1122334455aabbccd",
            "TransitGatewayId": "tgw-00112233445566aab",
            "Options": {
                "EnableAcceleration": false,
                "StaticRoutesOnly": true,
                "LocalIpv4NetworkCidr": "10.0.0.0/16",
                "RemoteIpv4NetworkCidr": "0.0.0.0/0",
                "TunnelInsideIpVersion": "ipv4"
            },
            "Routes": [],
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "CanadaVPN"
                }
            ],
            "VgwTelemetry": [
                {
                    "AcceptedRouteCount": 0,
                    "LastStatusChange": "2020-07-29T10:35:11.000Z",
                    "OutsideIpAddress": "203.0.113.3",
                    "Status": "DOWN",
                    "StatusMessage": ""
                },
                {
                    "AcceptedRouteCount": 0,
                    "LastStatusChange": "2020-09-02T09:09:33.000Z",
                    "OutsideIpAddress": "203.0.113.5",
                    "Status": "UP",
                    "StatusMessage": ""
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Site-to-Site VPN ユーザーガイド*」の「[Modifying Site-to-Site VPN connection options](https://docs.aws.amazon.com/vpn/latest/s2svpn/modify-vpn-connection-options.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpnConnectionOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpn-connection-options.html)」を参照してください。

### `modify-vpn-connection`
<a name="ec2_ModifyVpnConnection_cli_2_topic"></a>

次のコード例は、`modify-vpn-connection` を使用する方法を示しています。

**AWS CLI**  
**VPN 接続を変更するには**  
次の `modify-vpn-connection` の例では、VPN 接続 `vpn-12345678901234567` のターゲットゲートウェイを仮想プライベートゲートウェイ `vgw-11223344556677889` に変更します。  

```
aws ec2 modify-vpn-connection \
    --vpn-connection-id vpn-12345678901234567 \
    --vpn-gateway-id vgw-11223344556677889
```
出力:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "...configuration information...",
        "CustomerGatewayId": "cgw-aabbccddee1122334",
        "Category": "VPN",
        "State": "modifying",
        "Type": "ipsec.1",
        "VpnConnectionId": "vpn-12345678901234567",
        "VpnGatewayId": "vgw-11223344556677889",
        "Options": {
            "StaticRoutesOnly": false
        },
        "VgwTelemetry": [
            {
                "AcceptedRouteCount": 0,
                "LastStatusChange": "2019-07-17T07:34:00.000Z",
                "OutsideIpAddress": "18.210.3.222",
                "Status": "DOWN",
                "StatusMessage": "IPSEC IS DOWN"
            },
            {
                "AcceptedRouteCount": 0,
                "LastStatusChange": "2019-07-20T21:20:16.000Z",
                "OutsideIpAddress": "34.193.129.33",
                "Status": "DOWN",
                "StatusMessage": "IPSEC IS DOWN"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpnConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpn-connection.html)」を参照してください。

### `modify-vpn-tunnel-certificate`
<a name="ec2_ModifyVpnTunnelCertificate_cli_2_topic"></a>

次のコード例は、`modify-vpn-tunnel-certificate` を使用する方法を示しています。

**AWS CLI**  
**VPN トンネル証明書をローテーションするには**  
次の `modify-vpn-tunnel-certificate` の例では、VPN 接続の指定されたトンネルの証明書をローテーションします。  

```
aws ec2 modify-vpn-tunnel-certificate \
    --vpn-tunnel-outside-ip-address 203.0.113.17 \
    --vpn-connection-id vpn-12345678901234567
```
出力:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": ...configuration information...,
        "CustomerGatewayId": "cgw-aabbccddee1122334",
        "Category": "VPN",
        "State": "modifying",
        "Type": "ipsec.1",
        "VpnConnectionId": "vpn-12345678901234567",
        "VpnGatewayId": "vgw-11223344556677889",
        "Options": {
            "StaticRoutesOnly": false
        },
        "VgwTelemetry": [
            {
                "AcceptedRouteCount": 0,
                "LastStatusChange": "2019-09-11T17:27:14.000Z",
                "OutsideIpAddress": "203.0.113.17",
                "Status": "DOWN",
                "StatusMessage": "IPSEC IS DOWN",
                "CertificateArn": "arn:aws:acm:us-east-1:123456789101:certificate/c544d8ce-20b8-4fff-98b0-example"
            },
            {
                "AcceptedRouteCount": 0,
                "LastStatusChange": "2019-09-11T17:26:47.000Z",
                "OutsideIpAddress": "203.0.114.18",
                "Status": "DOWN",
                "StatusMessage": "IPSEC IS DOWN",
                "CertificateArn": "arn:aws:acm:us-east-1:123456789101:certificate/5ab64566-761b-4ad3-b259-example"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpnTunnelCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpn-tunnel-certificate.html)」を参照してください。

### `modify-vpn-tunnel-options`
<a name="ec2_ModifyVpnTunnelOptions_cli_2_topic"></a>

次のコード例は、`modify-vpn-tunnel-options` を使用する方法を示しています。

**AWS CLI**  
**VPN 接続のトンネルオプションを変更するには**  
次の `modify-vpn-tunnel-options` の例では、指定されたトンネルと VPN 接続で許可されている Diffie-Hellman グループを更新します。  

```
aws ec2 modify-vpn-tunnel-options \
    --vpn-connection-id vpn-12345678901234567 \
    --vpn-tunnel-outside-ip-address 203.0.113.17 \
    --tunnel-options Phase1DHGroupNumbers=[{Value=14},{Value=15},{Value=16},{Value=17},{Value=18}],Phase2DHGroupNumbers=[{Value=14},{Value=15},{Value=16},{Value=17},{Value=18}]
```
出力:  

```
{
    "VpnConnection": {
        "CustomerGatewayConfiguration": "...configuration information...",
        "CustomerGatewayId": "cgw-aabbccddee1122334",
        "Category": "VPN",
        "State": "available",
        "Type": "ipsec.1",
        "VpnConnectionId": "vpn-12345678901234567",
        "VpnGatewayId": "vgw-11223344556677889",
        "Options": {
            "StaticRoutesOnly": false,
            "TunnelOptions": [
                {
                    "OutsideIpAddress": "203.0.113.17",
                    "Phase1DHGroupNumbers": [
                        {
                            "Value": 14
                        },
                        {
                            "Value": 15
                        },
                        {
                            "Value": 16
                        },
                        {
                            "Value": 17
                        },
                        {
                            "Value": 18
                        }
                    ],
                    "Phase2DHGroupNumbers": [
                        {
                            "Value": 14
                        },
                        {
                            "Value": 15
                        },
                        {
                            "Value": 16
                        },
                        {
                            "Value": 17
                        },
                        {
                            "Value": 18
                        }
                    ]
                },
                {
                    "OutsideIpAddress": "203.0.114.19"
                }
            ]
        },
        "VgwTelemetry": [
            {
                "AcceptedRouteCount": 0,
                "LastStatusChange": "2019-09-10T21:56:54.000Z",
                "OutsideIpAddress": "203.0.113.17",
                "Status": "DOWN",
                "StatusMessage": "IPSEC IS DOWN"
            },
            {
                "AcceptedRouteCount": 0,
                "LastStatusChange": "2019-09-10T21:56:43.000Z",
                "OutsideIpAddress": "203.0.114.19",
                "Status": "DOWN",
                "StatusMessage": "IPSEC IS DOWN"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyVpnTunnelOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-vpn-tunnel-options.html)」を参照してください。

### `monitor-instances`
<a name="ec2_MonitorInstances_cli_2_topic"></a>

次のコード例は、`monitor-instances` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの詳細モニタリングを有効にするには**  
このコマンド例は、指定されたインスタンスの詳細モニタリングを有効にします。  
コマンド:  

```
aws ec2 monitor-instances --instance-ids i-1234567890abcdef0
```
出力:  

```
{
  "InstanceMonitorings": [
      {
          "InstanceId": "i-1234567890abcdef0",
          "Monitoring": {
              "State": "pending"
          }
      }
  ]
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[MonitorInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/monitor-instances.html)」を参照してください。

### `move-address-to-vpc`
<a name="ec2_MoveAddressToVpc_cli_2_topic"></a>

次のコード例は、`move-address-to-vpc` を使用する方法を示しています。

**AWS CLI**  
**アドレスを EC2-VPC に移動するには**  
この例では、Elastic IP アドレス 54.123.4.56 を EC2-VPC プラットフォームに移動します。  
コマンド:  

```
aws ec2 move-address-to-vpc --public-ip 54.123.4.56
```
出力:  

```
{
  "Status": "MoveInProgress"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MoveAddressToVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/move-address-to-vpc.html)」を参照してください。

### `move-byoip-cidr-to-ipam`
<a name="ec2_MoveByoipCidrToIpam_cli_2_topic"></a>

次のコード例は、`move-byoip-cidr-to-ipam` を使用する方法を示しています。

**AWS CLI**  
**BYOIP CIDR を IPAM に転送するには**  
次の `move-byoip-cidr-to-ipam` の例では、BYOIP CIDR を IPAM に転送します。  
(Linux):  

```
aws ec2 move-byoip-cidr-to-ipam \
    --region us-west-2 \
    --ipam-pool-id ipam-pool-0a03d430ca3f5c035 \
    --ipam-pool-owner 111111111111 \
    --cidr 130.137.249.0/24
```
(Windows):  

```
aws ec2 move-byoip-cidr-to-ipam ^
    --region us-west-2 ^
    --ipam-pool-id ipam-pool-0a03d430ca3f5c035 ^
    --ipam-pool-owner 111111111111 ^
    --cidr 130.137.249.0/24
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "130.137.249.0/24",
        "State": "pending-transfer"
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Tutorial: Transfer an existing BYOIP IPv4 CIDR to IPAM](https://docs.aws.amazon.com/vpc/latest/ipam/tutorials-byoip-ipam-transfer-ipv4.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MoveByoipCidrToIpam](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/move-byoip-cidr-to-ipam.html)」を参照してください。

### `network-insights-access-scope`
<a name="ec2_NetworkInsightsAccessScope_cli_2_topic"></a>

次のコード例は、`network-insights-access-scope` を使用する方法を示しています。

**AWS CLI**  
**Network Insights アクセススコープを作成するには**  
次の の`create-network-insights-access-scope`例では、 AWS アカウントにネットワークインサイトアクセススコープを作成します。  

```
aws ec2 create-network-insights-access-scope \
    --cli-input-json file://access-scope-file.json
```
`access-scope-file.json` の内容:  

```
{
    {
        "MatchPaths": [
            {
                "Source": {
                    "ResourceStatement": {
                         "Resources": [
                            "vpc-abcd12e3"
                        ]
                    }
                }
            }
        ],
        "ExcludePaths": [
            {
                "Source": {
                    "ResourceStatement": {
                        "ResourceTypes": [
                            "AWS::EC2::InternetGateway"
                        ]
                    }
                }
            }
        ]
    }
}
```
出力:  

```
{
    "NetworkInsightsAccessScopeAnalysisId": "nisa-123456789111"
    }{
    "NetworkInsightsAccessScope": {
        "NetworkInsightsAccessScopeId": "nis-123456789222",
        "NetworkInsightsAccessScopeArn": "arn:aws:ec2:us-east-1:123456789222:network-insights-access-scope/nis-123456789222",
        "CreatedDate": "2022-01-25T19:20:28.796000+00:00",
        "UpdatedDate": "2022-01-25T19:20:28.797000+00:00"
    },
    "NetworkInsightsAccessScopeContent": {
        "NetworkInsightsAccessScopeId": "nis-04c0c0fbca737c404",
        "MatchPaths": [
            {
                "Source": {
                    "ResourceStatement": {
                        "Resources": [
                            "vpc-abcd12e3"
                        ]
                    }
                }
            }
        ],
        "ExcludePaths": [
            {
                "Source": {
                    "ResourceStatement": {
                        "ResourceTypes": [
                            "AWS::EC2::InternetGateway"
                        ]
                    }
                }
            }
        ]
    }
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli-naa.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[NetworkInsightsAccessScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/network-insights-access-scope.html)」を参照してください。

### `provision-byoip-cidr`
<a name="ec2_ProvisionByoipCidr_cli_2_topic"></a>

次のコード例は、`provision-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲をプロビジョニングするには**  
次の の`provision-byoip-cidr`例では、 で使用するパブリック IP アドレス範囲をプロビジョニングします AWS。  

```
aws ec2 provision-byoip-cidr \
    --cidr 203.0.113.25/24 \
    --cidr-authorization-context Message="$text_message",Signature="$signed_message"
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "203.0.113.25/24",
        "State": "pending-provision"
    }
}
```
認証コンテキストのメッセージ文字列の作成の詳細については、「*Amazon EC2 ユーザーガイド*」の「[Bring Your Own IP Addresses](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-byoip.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ProvisionByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/provision-byoip-cidr.html)」を参照してください。

### `provision-ipam-pool-cidr`
<a name="ec2_ProvisionIpamPoolCidr_cli_2_topic"></a>

次のコード例は、`provision-ipam-pool-cidr` を使用する方法を示しています。

**AWS CLI**  
**CIDR を IPAM プールにプロビジョニングするには**  
次の `provision-ipam-pool-cidr` の例では、IPAM プールに CIDR をプロビジョニングします。  
(Linux):  

```
aws ec2 provision-ipam-pool-cidr \
    --ipam-pool-id ipam-pool-0533048da7d823723 \
    --cidr 10.0.0.0/24
```
(Windows):  

```
aws ec2 provision-ipam-pool-cidr ^
    --ipam-pool-id ipam-pool-0533048da7d823723 ^
    --cidr 10.0.0.0/24
```
出力:  

```
{
    "IpamPoolCidr": {
        "Cidr": "10.0.0.0/24",
        "State": "pending-provision"
    }
}
```
詳細については、「*Amazon VPC IPAM ユーザーガイド*」の「[Provision CIDRs to a pool](https://docs.aws.amazon.com/vpc/latest/ipam/prov-cidr-ipam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ProvisionIpamPoolCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/provision-ipam-pool-cidr.html)」を参照してください。

### `purchase-host-reservation`
<a name="ec2_PurchaseHostReservation_cli_2_topic"></a>

次のコード例は、`purchase-host-reservation` を使用する方法を示しています。

**AWS CLI**  
**専有ホストの予約を購入するには**  
この例では、アカウント内の指定された専有ホストに対して指定された専有ホスト予約サービスを購入します。  
コマンド:  

```
aws ec2 purchase-host-reservation --offering-id hro-03f707bf363b6b324 --host-id-set h-013abcd2a00cbd123
```
出力:  

```
{
  "TotalHourlyPrice": "1.499",
  "Purchase": [
      {
          "HourlyPrice": "1.499",
          "InstanceFamily": "m4",
          "PaymentOption": "NoUpfront",
          "HostIdSet": [
              "h-013abcd2a00cbd123"
          ],
          "HostReservationId": "hr-0d418a3a4ffc669ae",
          "UpfrontPrice": "0.000",
          "Duration": 31536000
      }
  ],
  "TotalUpfrontPrice": "0.000"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseHostReservation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/purchase-host-reservation.html)」を参照してください。

### `purchase-reserved-instances-offering`
<a name="ec2_PurchaseReservedInstancesOffering_cli_2_topic"></a>

次のコード例は、`purchase-reserved-instances-offering` を使用する方法を示しています。

**AWS CLI**  
**リザーブドインスタンスサービスを購入するには**  
このコマンド例では、オファリング ID とインスタンス数を指定して、リザーブドインスタンス提供の購入を示します。  
コマンド:  

```
aws ec2 purchase-reserved-instances-offering --reserved-instances-offering-id ec06327e-dd07-46ee-9398-75b5fexample --instance-count 3
```
出力:  

```
{
  "ReservedInstancesId": "af9f760e-6f91-4559-85f7-4980eexample"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseReservedInstancesOffering](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/purchase-reserved-instances-offering.html)」を参照してください。

### `purchase-scheduled-instances`
<a name="ec2_PurchaseScheduledInstances_cli_2_topic"></a>

次のコード例は、`purchase-scheduled-instances` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされたインスタンスを購入するには**  
この例では、スケジュールされたインスタンスを購入します。  
コマンド:  

```
aws ec2 purchase-scheduled-instances --purchase-requests file://purchase-request.json
```
Purchase-request.json:  

```
[
    {
        "PurchaseToken": "eyJ2IjoiMSIsInMiOjEsImMiOi...",
        "InstanceCount": 1
    }
]
```
出力:  

```
{
  "ScheduledInstanceSet": [
      {
          "AvailabilityZone": "us-west-2b",
          "ScheduledInstanceId": "sci-1234-1234-1234-1234-123456789012",
          "HourlyPrice": "0.095",
          "CreateDate": "2016-01-25T21:43:38.612Z",
          "Recurrence": {
              "OccurrenceDaySet": [
                  1
              ],
              "Interval": 1,
              "Frequency": "Weekly",
              "OccurrenceRelativeToEnd": false,
              "OccurrenceUnit": ""
          },
          "Platform": "Linux/UNIX",
          "TermEndDate": "2017-01-31T09:00:00Z",
          "InstanceCount": 1,
          "SlotDurationInHours": 32,
          "TermStartDate": "2016-01-31T09:00:00Z",
          "NetworkPlatform": "EC2-VPC",
          "TotalScheduledInstanceHours": 1696,
          "NextSlotStartTime": "2016-01-31T09:00:00Z",
          "InstanceType": "c4.large"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseScheduledInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/purchase-scheduled-instances.html)」を参照してください。

### `reboot-instances`
<a name="ec2_RebootInstances_cli_2_topic"></a>

次のコード例は、`reboot-instances` を使用する方法を示しています。

**AWS CLI**  
**Amazon EC2 インスタンスを再起動するには**  
この例では、指定のインスタンスを再起動します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 reboot-instances --instance-ids i-1234567890abcdef5
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「インスタンスの再起動方法」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[RebootInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reboot-instances.html)」を参照してください。

### `register-image`
<a name="ec2_RegisterImage_cli_2_topic"></a>

次のコード例は、`register-image` を使用する方法を示しています。

**AWS CLI**  
**例 1: マニフェストファイルを使用して AMI を登録するには**  
次の `register-image` の例では、Amazon S3 で指定されたマニフェストファイルを使用して AMI を登録します。  

```
aws ec2 register-image \
    --name my-image \
    --image-location amzn-s3-demo-bucket/myimage/image.manifest.xml
```
出力:  

```
{
    "ImageId": "ami-1234567890EXAMPLE"
}
```
詳細については「*アマゾン EC2 ユーザーガイド*」の「[アマゾン マシンイメージ (AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)」を参照してください。  
**例 2: ルートデバイスのスナップショットを使用して AMI を登録するには**  
次の `register-image` の例では、EBS ルートボリュームの指定されたスナップショットをデバイス `/dev/xvda` として使用して、AMI を登録します。ブロックデバイスマッピングには、デバイス `/dev/xvdf` として空の 100 GiB EBS ボリュームも含まれます。  

```
aws ec2 register-image \
    --name my-image \
    --root-device-name /dev/xvda \
    --block-device-mappings DeviceName=/dev/xvda,Ebs={SnapshotId=snap-0db2cf683925d191f} DeviceName=/dev/xvdf,Ebs={VolumeSize=100}
```
出力:  

```
{
    "ImageId": "ami-1a2b3c4d5eEXAMPLE"
}
```
詳細については「*アマゾン EC2 ユーザーガイド*」の「[アマゾン マシンイメージ (AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/register-image.html)」を参照してください。

### `register-instance-event-notification-attributes`
<a name="ec2_RegisterInstanceEventNotificationAttributes_cli_2_topic"></a>

次のコード例は、`register-instance-event-notification-attributes` を使用する方法を示しています。

**AWS CLI**  
**例 1: イベント通知にすべてのタグを含めるには**  
次の `register-instance-event-notification-attributes` の例では、イベント通知にすべてのタグを含めます。  

```
aws ec2 register-instance-event-notification-attributes \
    --instance-tag-attribute IncludeAllTagsOfInstance=true
```
出力:  

```
{
    "InstanceTagAttribute": {
        "InstanceTagKeys": [],
        "IncludeAllTagsOfInstance": true
    }
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[インスタンスの予定されているイベント](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html)」を参照してください。  
**例 2: イベント通知に特定のタグを含めるには**  
次の `register-instance-event-notification-attributes` の例では、イベント通知に指定したタグを含めます。`IncludeAllTagsOfInstance` が `true` の場合、タグは指定できません。  

```
aws ec2 register-instance-event-notification-attributes \
    --instance-tag-attribute InstanceTagKeys="tag-key1","tag-key2"
```
出力:  

```
{
    "InstanceTagAttribute": {
        "InstanceTagKeys": [
            "tag-key1",
            "tag-key2"
        ],
        "IncludeAllTagsOfInstance": false
    }
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[インスタンスの予定されているイベント](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterInstanceEventNotificationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/register-instance-event-notification-attributes.html)」を参照してください。

### `register-transit-gateway-multicase-group-sources`
<a name="ec2_RegisterTransitGatewayMulticaseGroupSources_cli_2_topic"></a>

次のコード例は、`register-transit-gateway-multicase-group-sources` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway マルチキャストグループにソースを登録するには。**  
次の `register-transit-gateway-multicast-group-sources` の例では、指定されたネットワークインターフェイスグループソースをマルチキャストグループに登録します。  

```
aws ec2 register-transit-gateway-multicast-group-sources \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef79d6e597 \
    --group-ip-address 224.0.1.0 \
    --network-interface-ids eni-07f290fc3c090cbae
```
出力:  

```
{
    "RegisteredMulticastGroupSources": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c4905cef79d6e597",
        "RegisteredNetworkInterfaceIds": [
            "eni-07f290fc3c090cbae"
        ],
        "GroupIpAddress": "224.0.1.0"
    }
}
```
詳細については、「*AWS Transit Gateway ユーザーガイド*」の「[Register Sources with a Multicast Group](https://docs.aws.amazon.com/vpc/latest/tgw/working-with-multicast.html#add-source-multicast-group)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTransitGatewayMulticaseGroupSources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/register-transit-gateway-multicase-group-sources.html)」を参照してください。

### `register-transit-gateway-multicast-group-members`
<a name="ec2_RegisterTransitGatewayMulticastGroupMembers_cli_2_topic"></a>

次のコード例は、`register-transit-gateway-multicast-group-members` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway マルチキャストドメインの関連付けに関する情報を表示するには**  
次の `register-transit-gateway-multicast-group-members` の例では、指定したマルチキャストドメインの関連付けを返します。  

```
aws ec2 register-transit-gateway-multicast-group-members \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef79d6e597 \
    --group-ip-address 224.0.1.0 \
    --network-interface-ids eni-0e246d32695012e81
```
出力:  

```
{
    "RegisteredMulticastGroupMembers": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c4905cef79d6e597",
        "RegisteredNetworkInterfaceIds": [
            "eni-0e246d32695012e81"
        ],
        "GroupIpAddress": "224.0.1.0"
    }
}
```
詳細については、*Transit Gateways ユーザーガイド*の「[マルチキャストドメイン](https://docs.aws.amazon.com/vpc/latest/tgw/multicast-domains-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTransitGatewayMulticastGroupMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/register-transit-gateway-multicast-group-members.html)」を参照してください。

### `register-transit-gateway-multicast-group-sources`
<a name="ec2_RegisterTransitGatewayMulticastGroupSources_cli_2_topic"></a>

次のコード例は、`register-transit-gateway-multicast-group-sources` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway マルチキャストグループにソースを登録するには。**  
次の `register-transit-gateway-multicast-group-sources` の例では、指定されたネットワークインターフェイスグループソースをマルチキャストグループに登録します。  

```
aws ec2 register-transit-gateway-multicast-group-sources \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-0c4905cef79d6e597 \
    --group-ip-address 224.0.1.0 \
    --network-interface-ids eni-07f290fc3c090cbae
```
出力:  

```
{
    "RegisteredMulticastGroupSources": {
        "TransitGatewayMulticastDomainId": "tgw-mcast-domain-0c4905cef79d6e597",
        "RegisteredNetworkInterfaceIds": [
            "eni-07f290fc3c090cbae"
        ],
        "GroupIpAddress": "224.0.1.0"
    }
}
```
詳細については、*Transit Gateways ガイド*の「[マルチキャストドメイン](https://docs.aws.amazon.com/vpc/latest/tgw/multicast-domains-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTransitGatewayMulticastGroupSources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/register-transit-gateway-multicast-group-sources.html)」を参照してください。

### `reject-transit-gateway-peering-attachment`
<a name="ec2_RejectTransitGatewayPeeringAttachment_cli_2_topic"></a>

次のコード例は、`reject-transit-gateway-peering-attachment` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway ピアリングアタッチメントを拒否するには**  
次の `reject-transit-gateway-peering-attachment` の例では、指定した Transit Gateway ピアリングアタッチメントリクエストを拒否します。`--region` パラメータは、アクセプタ Transit Gateway があるリージョンを指定します。  

```
aws ec2 reject-transit-gateway-peering-attachment \
    --transit-gateway-attachment-id tgw-attach-4455667788aabbccd \
    --region us-east-2
```
出力:  

```
{
    "TransitGatewayPeeringAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-4455667788aabbccd",
        "RequesterTgwInfo": {
            "TransitGatewayId": "tgw-123abc05e04123abc",
            "OwnerId": "123456789012",
            "Region": "us-west-2"
        },
        "AccepterTgwInfo": {
            "TransitGatewayId": "tgw-11223344aabbcc112",
            "OwnerId": "123456789012",
            "Region": "us-east-2"
        },
        "State": "rejecting",
        "CreationTime": "2019-12-09T11:50:31.000Z"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit Gateway Peering Attachments](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectTransitGatewayPeeringAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reject-transit-gateway-peering-attachment.html)」を参照してください。

### `reject-transit-gateway-vpc-attachment`
<a name="ec2_RejectTransitGatewayVpcAttachment_cli_2_topic"></a>

次のコード例は、`reject-transit-gateway-vpc-attachment` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway VPC アタッチメントを拒否するには**  
次の `reject-transit-gateway-vpc-attachment` の例では、指定した Transit Gateway VPC アタッチメントを拒否します。  

```
aws ec2 reject-transit-gateway-vpc-attachment \
    --transit-gateway-attachment-id tgw-attach-0a34fe6b4fEXAMPLE
```
出力:  

```
{
    "TransitGatewayVpcAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-0a34fe6b4fEXAMPLE",
        "TransitGatewayId": "tgw-0262a0e521EXAMPLE",
        "VpcId": "vpc-07e8ffd50fEXAMPLE",
        "VpcOwnerId": "111122223333",
        "State": "pending",
        "SubnetIds": [
            "subnet-0752213d59EXAMPLE"
        ],
        "CreationTime": "2019-07-10T17:33:46.000Z",
        "Options": {
            "DnsSupport": "enable",
            "Ipv6Support": "disable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway attachments to a VPC](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectTransitGatewayVpcAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reject-transit-gateway-vpc-attachment.html)」を参照してください。

### `reject-transit-gateway-vpc-attachments`
<a name="ec2_RejectTransitGatewayVpcAttachments_cli_2_topic"></a>

次のコード例は、`reject-transit-gateway-vpc-attachments` を使用する方法を示しています。

**AWS CLI**  
**Transit Gateway VPC アタッチメントを拒否するには**  
次の `reject-transit-gateway-vpc-attachment` の例では、指定した Transit Gateway VPC アタッチメントを拒否します。  

```
aws ec2 reject-transit-gateway-vpc-attachment \
    --transit-gateway-attachment-id tgw-attach-0a34fe6b4fEXAMPLE
```
出力:  

```
{
    "TransitGatewayVpcAttachment": {
        "TransitGatewayAttachmentId": "tgw-attach-0a34fe6b4fEXAMPLE",
        "TransitGatewayId": "tgw-0262a0e521EXAMPLE",
        "VpcId": "vpc-07e8ffd50fEXAMPLE",
        "VpcOwnerId": "111122223333",
        "State": "pending",
        "SubnetIds": [
            "subnet-0752213d59EXAMPLE"
        ],
        "CreationTime": "2019-07-10T17:33:46.000Z",
        "Options": {
            "DnsSupport": "enable",
            "Ipv6Support": "disable"
        }
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway attachments to a VPC](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectTransitGatewayVpcAttachments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reject-transit-gateway-vpc-attachments.html)」を参照してください。

### `reject-vpc-endpoint-connections`
<a name="ec2_RejectVpcEndpointConnections_cli_2_topic"></a>

次のコード例は、`reject-vpc-endpoint-connections` を使用する方法を示しています。

**AWS CLI**  
**インターフェイスエンドポイント接続リクエストを拒否するには**  
この例では、指定されたエンドポイントサービスに対して指定されたエンドポイント接続リクエストを拒否します。  
コマンド:  

```
aws ec2 reject-vpc-endpoint-connections --service-id vpce-svc-03d5ebb7d9579a2b3 --vpc-endpoint-ids vpce-0c1308d7312217abc
```
出力:  

```
{
  "Unsuccessful": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectVpcEndpointConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reject-vpc-endpoint-connections.html)」を参照してください。

### `reject-vpc-peering-connection`
<a name="ec2_RejectVpcPeeringConnection_cli_2_topic"></a>

次のコード例は、`reject-vpc-peering-connection` を使用する方法を示しています。

**AWS CLI**  
VPC ピアリング接続を拒否するには  
この例では、指定された VPC ピアリング接続リクエストを拒否します。  
コマンド:  

```
aws ec2 reject-vpc-peering-connection --vpc-peering-connection-id pcx-1a2b3c4d
```
出力:  

```
{
    "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectVpcPeeringConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reject-vpc-peering-connection.html)」を参照してください。

### `release-address`
<a name="ec2_ReleaseAddress_cli_2_topic"></a>

次のコード例は、`release-address` を使用する方法を示しています。

**AWS CLI**  
**EC2-Classic 用 Elastic IP アドレスをリリースするには**  
この例では、EC2-Classic のインスタンスに使用する Elastic IP アドレスをリリースしています。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 release-address --public-ip 198.51.100.0
```
**EC2-VPC 用 Elastic IP アドレスをリリースするには**  
この例では、VPC のインスタンスに使用する Elastic IP アドレスをリリースしています。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 release-address --allocation-id eipalloc-64d5890a
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ReleaseAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/release-address.html)」を参照してください。

### `release-hosts`
<a name="ec2_ReleaseHosts_cli_2_topic"></a>

次のコード例は、`release-hosts` を使用する方法を示しています。

**AWS CLI**  
**アカウントから専有ホストを解除するには**  
アカウントから専有ホストを解除するには。ホストを解除する前に、ホスト上にあるインスタンスを停止または終了する必要があります。  
コマンド:  

```
aws ec2 release-hosts --host-id=h-0029d6e3cacf1b3da
```
出力:  

```
{
    "Successful":  [
        "h-0029d6e3cacf1b3da"
         ],
  "Unsuccessful": []

 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReleaseHosts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/release-hosts.html)」を参照してください。

### `release-ipam-pool-allocation`
<a name="ec2_ReleaseIpamPoolAllocation_cli_2_topic"></a>

次のコード例は、`release-ipam-pool-allocation` を使用する方法を示しています。

**AWS CLI**  
**IPAM プールの割り当てを解除するには**  
この例では、あなたは IPAM の委任された管理者として IPAM プールを削除しようとしましたが、プールに割り当てがある間はプールを削除できないというエラーを受け取りました。このコマンドを使用して、プール割り当てを解除します。  
次の点に注意してください。  
このコマンドは、カスタム割り当てにのみ使用できます。リソースを削除せずにリソースの割り当てを削除するには、[modify-ipam-resource-cidr](https://docs.aws.amazon.com/cli/latest/reference/ec2/modify-ipam-resource-cidr.html) を使用してモニタリング状態を false に設定します。このリクエストを完了するには、[describe-ipam-pools](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-ipam-pools.html) で取得できる IPAM プール ID が必要です。また、[get-ipam-pool-allocations](https://docs.aws.amazon.com/cli/latest/reference/ec2/get-ipam-pool-allocations.html) で取得できる割り当て ID も必要です。割り当てを 1 つずつ削除したくない場合は、IPAM プールを削除するときに `--cascade option` を使用して、削除する前にプール内の割り当てをすべて自動的に解除できます。このコマンドを実行する前に、いくつかの前提条件があります。詳細については「*Amazon VPC IPAM ユーザーガイド*」の「[Release an allocation](https://docs.aws.amazon.com/vpc/latest/ipam/release-alloc-ipam.html)」を参照してください。このコマンドを実行する `--region` は、割り当てのある IPAM プールのロケールである必要があります。  
次の `release-ipam-pool-allocation` の例では、IPAM プールの割り振りをリリースします。  

```
aws ec2 release-ipam-pool-allocation \
    --ipam-pool-id ipam-pool-07bdd12d7c94e4693 \
    --cidr 10.0.0.0/23 \
    --ipam-pool-allocation-id ipam-pool-alloc-0e66a1f730da54791b99465b79e7d1e89 \
    --region us-west-1
```
出力:  

```
{
    "Success": true
}
```
割り当てをリリースしたら、[delete-ipam-pool](https://docs.aws.amazon.com/cli/latest/reference/ec2/delete-ipam-pool.html) を実行することができます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReleaseIpamPoolAllocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/release-ipam-pool-allocation.html)」を参照してください。

### `replace-iam-instance-profile-association`
<a name="ec2_ReplaceIamInstanceProfileAssociation_cli_2_topic"></a>

次のコード例は、`replace-iam-instance-profile-association` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの IAM インスタンスプロファイルを置き換えるには**  
この例では、関連付け `iip-assoc-060bae234aac2e7fa` によって表される IAM インスタンスプロファイルを、`AdminRole` という名前の IAM インスタンスプロファイルに置き換えています。  

```
aws ec2 replace-iam-instance-profile-association \
    --iam-instance-profile Name=AdminRole \
    --association-id iip-assoc-060bae234aac2e7fa
```
出力:  

```
{
    "IamInstanceProfileAssociation": {
        "InstanceId": "i-087711ddaf98f9489",
        "State": "associating",
        "AssociationId": "iip-assoc-0b215292fab192820",
        "IamInstanceProfile": {
            "Id": "AIPAJLNLDX3AMYZNWYYAY",
            "Arn": "arn:aws:iam::123456789012:instance-profile/AdminRole"
        }
    }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ReplaceIamInstanceProfileAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-iam-instance-profile-association.html)」を参照してください。

### `replace-network-acl-association`
<a name="ec2_ReplaceNetworkAclAssociation_cli_2_topic"></a>

次のコード例は、`replace-network-acl-association` を使用する方法を示しています。

**AWS CLI**  
**ネットワーク ACL をサブネットと置き換えるには**  
この例では、指定されたネットワーク ACL を、指定されたネットワーク ACL 関連付けのサブネットに関連付けます。  
コマンド:  

```
aws ec2 replace-network-acl-association --association-id aclassoc-e5b95c8c --network-acl-id acl-5fb85d36
```
出力:  

```
{
    "NewAssociationId": "aclassoc-3999875b"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReplaceNetworkAclAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-network-acl-association.html)」を参照してください。

### `replace-network-acl-entry`
<a name="ec2_ReplaceNetworkAclEntry_cli_2_topic"></a>

次のコード例は、`replace-network-acl-entry` を使用する方法を示しています。

**AWS CLI**  
**ネットワーク ACL エントリを置き換えるには**  
この例では、指定されたネットワーク ACL のエントリを置き換えます。新しいルール 100 は、UDP ポート 53 (DNS) の 203.0.113.12/24 から任意の関連付けられたサブネットへの入力トラフィックを許可します。  
コマンド:  

```
aws ec2 replace-network-acl-entry --network-acl-id acl-5fb85d36 --ingress --rule-number 100 --protocol udp --port-range From=53,To=53 --cidr-block 203.0.113.12/24 --rule-action allow
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReplaceNetworkAclEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-network-acl-entry.html)」を参照してください。

### `replace-route-table-association`
<a name="ec2_ReplaceRouteTableAssociation_cli_2_topic"></a>

次のコード例は、`replace-route-table-association` を使用する方法を示しています。

**AWS CLI**  
**サブネットに関連付けられたルートテーブルを置き換えるには**  
この例では、指定されたルートテーブルを、指定されたルートテーブルの関連付け用のサブネットに関連付けます。  
コマンド:  

```
aws ec2 replace-route-table-association --association-id rtbassoc-781d0d1a --route-table-id rtb-22574640
```
出力:  

```
{
    "NewAssociationId": "rtbassoc-3a1f0f58"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReplaceRouteTableAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-route-table-association.html)」を参照してください。

### `replace-route`
<a name="ec2_ReplaceRoute_cli_2_topic"></a>

次のコード例は、`replace-route` を使用する方法を示しています。

**AWS CLI**  
**ルートを置き換えるには**  
この例では、指定したルートテーブルの指定したルートを置き換えます。新しいルートは、指定された CIDR に一致し、トラフィックを指定された仮想プライベートゲートウェイに送信します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 replace-route --route-table-id rtb-22574640 --destination-cidr-block 10.0.0.0/16 --gateway-id vgw-9a4cacf3
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReplaceRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-route.html)」を参照してください。

### `replace-transit-gateway-route`
<a name="ec2_ReplaceTransitGatewayRoute_cli_2_topic"></a>

次のコード例は、`replace-transit-gateway-route` を使用する方法を示しています。

**AWS CLI**  
**指定された Transit Gateway ルートテーブルの指定されたルートを置き換えるには**  
次の `replace-transit-gateway-route` の例では、指定した Transit Gateway ルートテーブルのルートを置き換えます。  

```
aws ec2 replace-transit-gateway-route \
    --destination-cidr-block 10.0.2.0/24 \
    --transit-gateway-attachment-id tgw-attach-09b52ccdb5EXAMPLE \
    --transit-gateway-route-table-id tgw-rtb-0a823edbdeEXAMPLE
```
出力:  

```
{
    "Route": {
        "DestinationCidrBlock": "10.0.2.0/24",
        "TransitGatewayAttachments": [
            {
                "ResourceId": "vpc-4EXAMPLE",
                "TransitGatewayAttachmentId": "tgw-attach-09b52ccdb5EXAMPLE",
                "ResourceType": "vpc"
            }
        ],
        "Type": "static",
        "State": "active"
    }
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReplaceTransitGatewayRoute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/replace-transit-gateway-route.html)」を参照してください。

### `report-instance-status`
<a name="ec2_ReportInstanceStatus_cli_2_topic"></a>

次のコード例は、`report-instance-status` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのステータスフィードバックを報告するには**  
このコマンド例では、指定されたインスタンスのステータスフィードバックを報告します。  
コマンド:  

```
aws ec2 report-instance-status --instances i-1234567890abcdef0 --status impaired --reason-codes unresponsive
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReportInstanceStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/report-instance-status.html)」を参照してください。

### `request-spot-fleet`
<a name="ec2_RequestSpotFleet_cli_2_topic"></a>

次のコード例は、`request-spot-fleet` を使用する方法を示しています。

**AWS CLI**  
**最低料金でサブネット内のスポットフリートをリクエストするには**  
このコマンド例では、サブネットによってのみ異なる 2 つの起動仕様を持つスポットフリートリクエストを作成します。スポットフリートは、指定された最低料金のサブネットでインスタンスを起動します。インスタンスがデフォルトの VPC で起動される場合は、デフォルトでパブリック IP アドレスが割り当てられます。インスタンスがデフォルト以外の VPC で起動される場合は、デフォルトでパブリック IP アドレスは割り当てられません。  
スポットフリートリクエストで、同じアベイラビリティーゾーンから異なるサブネットを指定することはできません。  
コマンド:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
config.json:  

```
{
  "SpotPrice": "0.04",
  "TargetCapacity": 2,
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "KeyName": "my-key-pair",
          "SecurityGroups": [
              {
                  "GroupId": "sg-1a2b3c4d"
              }
          ],
          "InstanceType": "m3.medium",
          "SubnetId": "subnet-1a2b3c4d, subnet-3c4d5e6f",
          "IamInstanceProfile": {
              "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
          }
      }
  ]
}
```
出力:  

```
{
  "SpotFleetRequestId": "sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE"
}
```
**最低料金でアベイラビリティーゾーンのスポットフリートをリクエストするには**  
このコマンド例では、アベイラビリティーゾーンによってのみ異なる 2 つの起動仕様を持つスポットフリートリクエストを作成します。スポットフリートは、指定された最低料金のアベイラビリティーゾーンでインスタンスを起動します。アカウントが EC2-VPC のみをサポートしている場合、Amazon EC2 はアベイラビリティーゾーンのデフォルトサブネットでスポットインスタンスを起動します。アカウントが EC2-Classic をサポートしている場合、Amazon EC2 はアベイラビリティーゾーンの EC2-Classic でインスタンスを起動します。  
コマンド:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
config.json:  

```
{
  "SpotPrice": "0.04",
  "TargetCapacity": 2,
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "KeyName": "my-key-pair",
          "SecurityGroups": [
              {
                  "GroupId": "sg-1a2b3c4d"
              }
          ],
          "InstanceType": "m3.medium",
          "Placement": {
              "AvailabilityZone": "us-west-2a, us-west-2b"
          },
          "IamInstanceProfile": {
              "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
          }
      }
  ]
}
```
**サブネットでスポットインスタンスを起動し、パブリック IP アドレスを割り当てるには**  
このコマンド例では、デフォルト以外の VPC で起動されたインスタンスにパブリックアドレスを割り当てます。ネットワークインターフェイスを指定する際、ネットワークインターフェイスを使用してサブネット ID とセキュリティグループ ID を含める必要があります。  
コマンド:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
config.json:  

```
{
  "SpotPrice": "0.04",
  "TargetCapacity": 2,
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "KeyName": "my-key-pair",
          "InstanceType": "m3.medium",
          "NetworkInterfaces": [
              {
                  "DeviceIndex": 0,
                  "SubnetId": "subnet-1a2b3c4d",
                  "Groups": [ "sg-1a2b3c4d" ],
                  "AssociatePublicIpAddress": true
              }
          ],
          "IamInstanceProfile": {
              "Arn": "arn:aws:iam::880185128111:instance-profile/my-iam-role"
          }
      }
  ]
}
```
**分散配分戦略を使用してスポットフリートをリクエストするには**  
このコマンド例では、分散配分戦略を使用して 30 個のインスタンスを起動するスポットフリートリクエストを作成します。起動仕様はインスタンスタイプによって異なります。スポットフリートは、各タイプのインスタンスが 10 個になるように、起動仕様全体にインスタンスを分散します。  
コマンド:  

```
aws ec2 request-spot-fleet --spot-fleet-request-config file://config.json
```
config.json:  

```
{
  "SpotPrice": "0.70",
  "TargetCapacity": 30,
  "AllocationStrategy": "diversified",
  "IamFleetRole": "arn:aws:iam::123456789012:role/my-spot-fleet-role",
  "LaunchSpecifications": [
      {
          "ImageId": "ami-1a2b3c4d",
          "InstanceType": "c4.2xlarge",
          "SubnetId": "subnet-1a2b3c4d"
      },
      {
          "ImageId": "ami-1a2b3c4d",
          "InstanceType": "m3.2xlarge",
          "SubnetId": "subnet-1a2b3c4d"
      },
      {
          "ImageId": "ami-1a2b3c4d",
          "InstanceType": "r3.2xlarge",
          "SubnetId": "subnet-1a2b3c4d"
      }
  ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「Spot Fleet Requests」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RequestSpotFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/request-spot-fleet.html)」を参照してください。

### `request-spot-instances`
<a name="ec2_RequestSpotInstances_cli_2_topic"></a>

次のコード例は、`request-spot-instances` を使用する方法を示しています。

**AWS CLI**  
**スポットインスタンスをリクエストするには**  
このコマンド例では、指定されたアベイラビリティーゾーン内の 5 個のインスタンスに対して 1 回限りのスポットインスタンスリクエストを作成します。アカウントが EC2-VPC のみをサポートしている場合、Amazon EC2 は指定されたアベイラビリティーゾーンのデフォルトサブネットでインスタンスを起動します。アカウントが EC2-Classic をサポートしている場合、Amazon EC2 は指定されたアベイラビリティーゾーンの EC2-Classic でインスタンスを起動します。  
コマンド:  

```
aws ec2 request-spot-instances --spot-price "0.03" --instance-count 5 --type "one-time" --launch-specification file://specification.json
```
Specification.json:  

```
{
  "ImageId": "ami-1a2b3c4d",
  "KeyName": "my-key-pair",
  "SecurityGroupIds": [ "sg-1a2b3c4d" ],
  "InstanceType": "m3.medium",
  "Placement": {
    "AvailabilityZone": "us-west-2a"
  },
  "IamInstanceProfile": {
      "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
  }
}
```
出力:  

```
{
  "SpotInstanceRequests": [
      {
          "Status": {
              "UpdateTime": "2014-03-25T20:54:21.000Z",
              "Code": "pending-evaluation",
              "Message": "Your Spot request has been submitted for review, and is pending evaluation."
          },
          "ProductDescription": "Linux/UNIX",
          "SpotInstanceRequestId": "sir-df6f405d",
          "State": "open",
          "LaunchSpecification": {
              "Placement": {
                  "AvailabilityZone": "us-west-2a"
              },
              "ImageId": "ami-1a2b3c4d",
              "KeyName": "my-key-pair",
              "SecurityGroups": [
                  {
                      "GroupName": "my-security-group",
                      "GroupId": "sg-1a2b3c4d"
                  }
              ],
              "Monitoring": {
                  "Enabled": false
              },
              "IamInstanceProfile": {
                  "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
              },
              "InstanceType": "m3.medium"
          },
          "Type": "one-time",
          "CreateTime": "2014-03-25T20:54:20.000Z",
          "SpotPrice": "0.050000"
      },
      ...
  ]
}
```
このコマンド例では、指定されたサブネット内の 5 個のインスタンスに対して 1 回限りのスポットインスタンスリクエストを作成します。Amazon EC2 は指定されたサブネットでインスタンスを起動します。VPC がデフォルト以外の VPC である場合、インスタンスにはデフォルトでパブリック IP アドレスが割り当てられません。  
コマンド:  

```
aws ec2 request-spot-instances --spot-price "0.050" --instance-count 5 --type "one-time" --launch-specification file://specification.json
```
Specification.json:  

```
{
  "ImageId": "ami-1a2b3c4d",
  "SecurityGroupIds": [ "sg-1a2b3c4d" ],
  "InstanceType": "m3.medium",
  "SubnetId": "subnet-1a2b3c4d",
  "IamInstanceProfile": {
      "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
  }
}
```
出力:  

```
{
  "SpotInstanceRequests": [
      {
          "Status": {
             "UpdateTime": "2014-03-25T22:21:58.000Z",
             "Code": "pending-evaluation",
             "Message": "Your Spot request has been submitted for review, and is pending evaluation."
          },
          "ProductDescription": "Linux/UNIX",
          "SpotInstanceRequestId": "sir-df6f405d",
          "State": "open",
          "LaunchSpecification": {
             "Placement": {
                 "AvailabilityZone": "us-west-2a"
             }
             "ImageId": "ami-1a2b3c4d"
             "SecurityGroups": [
                 {
                     "GroupName": "my-security-group",
                     "GroupID": "sg-1a2b3c4d"
                 }
             ]
             "SubnetId": "subnet-1a2b3c4d",
             "Monitoring": {
                 "Enabled": false
             },
             "IamInstanceProfile": {
                 "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
             },
             "InstanceType": "m3.medium",
         },
         "Type": "one-time",
         "CreateTime": "2014-03-25T22:21:58.000Z",
         "SpotPrice": "0.050000"
      },
      ...
  ]
}
```
この例では、デフォルト以外の VPC で起動するスポットインスタンスにパブリック IP アドレスを割り当てます。ネットワークインターフェイスを指定する際、ネットワークインターフェイスを使用してサブネット ID とセキュリティグループ ID を含める必要があります。  
コマンド:  

```
aws ec2 request-spot-instances --spot-price "0.050" --instance-count 1 --type "one-time" --launch-specification file://specification.json
```
Specification.json:  

```
{
  "ImageId": "ami-1a2b3c4d",
  "KeyName": "my-key-pair",
  "InstanceType": "m3.medium",
  "NetworkInterfaces": [
    {
      "DeviceIndex": 0,
      "SubnetId": "subnet-1a2b3c4d",
      "Groups": [ "sg-1a2b3c4d" ],
      "AssociatePublicIpAddress": true
    }
  ],
  "IamInstanceProfile": {
      "Arn": "arn:aws:iam::123456789012:instance-profile/my-iam-role"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RequestSpotInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/request-spot-instances.html)」を参照してください。

### `reset-address-attribute`
<a name="ec2_ResetAddressAttribute_cli_2_topic"></a>

次のコード例は、`reset-address-attribute` を使用する方法を示しています。

**AWS CLI**  
**Elastic IP アドレスに関連付けられたドメイン名属性をリセットするには**  
次の `reset-address-attribute` の例では、Elastic IP アドレスのドメイン名の属性をリセットします。  
Linux ：  

```
aws ec2 reset-address-attribute \
    --allocation-id eipalloc-abcdef01234567890 \
    --attribute domain-name
```
Windows ：  

```
aws ec2 reset-address-attribute ^
    --allocation-id eipalloc-abcdef01234567890 ^
    --attribute domain-name
```
出力:  

```
{
    "Addresses": [
        {
            "PublicIp": "192.0.2.0",
            "AllocationId": "eipalloc-abcdef01234567890",
            "PtrRecord": "example.com."
            "PtrRecordUpdate": {
                "Value": "example.net.",
                "Status": "PENDING"
        }
    ]
}
```
保留中の変更をモニタリングするには、「*AWS CLI コマンドリファレンス*」の「[describe-addresses-attribute](https://docs.aws.amazon.com/cli/latest/reference/ec2/describe-addresses-attribute.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetAddressAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-address-attribute.html)」を参照してください。

### `reset-ebs-default-kms-key-id`
<a name="ec2_ResetEbsDefaultKmsKeyId_cli_2_topic"></a>

次のコード例は、`reset-ebs-default-kms-key-id` を使用する方法を示しています。

**AWS CLI**  
**EBS 暗号化用のデフォルトの CMK をリセットするには**  
次の の`reset-ebs-default-kms-key-id`例では、現在のリージョンの AWS アカウントの EBS 暗号化のデフォルトの CMK をリセットします。  

```
aws ec2 reset-ebs-default-kms-key-id
```
出力:  

```
{
   "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/8c5b2c63-b9bc-45a3-a87a-5513eEXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetEbsDefaultKmsKeyId](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-ebs-default-kms-key-id.html)」を参照してください。

### `reset-fpga-image-attribute`
<a name="ec2_ResetFpgaImageAttribute_cli_2_topic"></a>

次のコード例は、`reset-fpga-image-attribute` を使用する方法を示しています。

**AWS CLI**  
**Amazon FPGA イメージの属性をリセットするには**  
この例では、指定された AFI のロードアクセス許可をリセットします。  
コマンド:  

```
aws ec2 reset-fpga-image-attribute --fpga-image-id afi-0d123e123bfc85abc --attribute loadPermission
```
出力:  

```
{
  "Return": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetFpgaImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-fpga-image-attribute.html)」を参照してください。

### `reset-image-attribute`
<a name="ec2_ResetImageAttribute_cli_2_topic"></a>

次のコード例は、`reset-image-attribute` を使用する方法を示しています。

**AWS CLI**  
**launchPermission 属性をリセットするには**  
この例では、指定された AMI の `launchPermission` 属性をデフォルト値にリセットします。デフォルトでは、AMI はプライベートです。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 reset-image-attribute --image-id ami-5731123e --attribute launchPermission
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetImageAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-image-attribute.html)」を参照してください。

### `reset-instance-attribute`
<a name="ec2_ResetInstanceAttribute_cli_2_topic"></a>

次のコード例は、`reset-instance-attribute` を使用する方法を示しています。

**AWS CLI**  
**sourceDestCheck 属性をリセットするには**  
この例では、指定されたインスタンスの `sourceDestCheck` 属性をリセットします。インスタンスは VPC にある必要があります。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 reset-instance-attribute --instance-id i-1234567890abcdef0 --attribute sourceDestCheck
```
**カーネル属性をリセットするには**  
この例では、指定されたインスタンスの `kernel` 属性をリセットします。インスタンスは `stopped` の状態である必要があります。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 reset-instance-attribute --instance-id i-1234567890abcdef0 --attribute kernel
```
**ramdisk 属性をリセットするには**  
この例では、指定されたインスタンスの `ramdisk` 属性をリセットします。インスタンスは `stopped` の状態である必要があります。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 reset-instance-attribute --instance-id i-1234567890abcdef0 --attribute ramdisk
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetInstanceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-instance-attribute.html)」を参照してください。

### `reset-network-interface-attribute`
<a name="ec2_ResetNetworkInterfaceAttribute_cli_2_topic"></a>

次のコード例は、`reset-network-interface-attribute` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイス属性をリセットするには**  
次の `reset-network-interface-attribute` の例では、送信元/送信先チェック属性の値を `true` にリセットします。  

```
aws ec2 reset-network-interface-attribute \
    --network-interface-id eni-686ea200 \
    --source-dest-check
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetNetworkInterfaceAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-network-interface-attribute.html)」を参照してください。

### `reset-snapshot-attribute`
<a name="ec2_ResetSnapshotAttribute_cli_2_topic"></a>

次のコード例は、`reset-snapshot-attribute` を使用する方法を示しています。

**AWS CLI**  
**スナップショット属性をリセットするには**  
この例では、スナップショット `snap-1234567890abcdef0` のボリューム作成のアクセス許可をリセットします。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 reset-snapshot-attribute --snapshot-id snap-1234567890abcdef0 --attribute createVolumePermission
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetSnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/reset-snapshot-attribute.html)」を参照してください。

### `restore-address-to-classic`
<a name="ec2_RestoreAddressToClassic_cli_2_topic"></a>

次のコード例は、`restore-address-to-classic` を使用する方法を示しています。

**AWS CLI**  
**アドレスを EC2-Classic に復元するには**  
この例では、Elastic IP アドレス 198.51.100.0 を EC2-Classic プラットフォームに復元します。  
コマンド:  

```
aws ec2 restore-address-to-classic --public-ip 198.51.100.0
```
出力:  

```
{
  "Status": "MoveInProgress",
  "PublicIp": "198.51.100.0"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreAddressToClassic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/restore-address-to-classic.html)」を参照してください。

### `restore-image-from-recycle-bin`
<a name="ec2_RestoreImageFromRecycleBin_cli_2_topic"></a>

次のコード例は、`restore-image-from-recycle-bin` を使用する方法を示しています。

**AWS CLI**  
**ごみ箱からイメージを復元するには**  
次の `restore-image-from-recycle-bin` の例では、AMI ami-0111222333444abcd をごみ箱から復元します。  

```
aws ec2 restore-image-from-recycle-bin \
    --image-id ami-0111222333444abcd
```
出力:  

```
{
    "Return": true
}
```
詳細については、*Amazon EBS ユーザーガイド*の「[削除された AMI をごみ箱から復元する](https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin-working-with-amis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreImageFromRecycleBin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/restore-image-from-recycle-bin.html)」を参照してください。

### `restore-managed-prefix-list-version`
<a name="ec2_RestoreManagedPrefixListVersion_cli_2_topic"></a>

次のコード例は、`restore-managed-prefix-list-version` を使用する方法を示しています。

**AWS CLI**  
us-west-2\$1\$1プレフィックスリストバージョンを復元するには\$1\$1  
次の `restore-managed-prefix-list-version` では、指定されたプレフィックスリストのバージョン 1 からのエントリを復元します。  

```
aws ec2 restore-managed-prefix-list-version \
    --prefix-list-id pl-0123456abcabcabc1 \
    --current-version 2 \
    --previous-version 1
```
出力:  

```
{
    "PrefixList": {
        "PrefixListId": "pl-0123456abcabcabc1",
        "AddressFamily": "IPv4",
        "State": "restore-in-progress",
        "PrefixListArn": "arn:aws:ec2:us-west-2:123456789012:prefix-list/pl-0123456abcabcabc1",
        "PrefixListName": "vpc-cidrs",
        "MaxEntries": 10,
        "Version": 2,
        "OwnerId": "123456789012"
    }
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[Managed prefix lists](https://docs.aws.amazon.com/vpc/latest/userguide/managed-prefix-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreManagedPrefixListVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/restore-managed-prefix-list-version.html)」を参照してください。

### `restore-snapshot-from-recycle-bin`
<a name="ec2_RestoreSnapshotFromRecycleBin_cli_2_topic"></a>

次のコード例は、`restore-snapshot-from-recycle-bin` を使用する方法を示しています。

**AWS CLI**  
**ごみ箱からスナップショットを復元するには**  
次の `restore-snapshot-from-recycle-bin` の例では、スナップショットをごみ箱から復元します。ごみ箱からスナップショットを復元すると、そのスナップショットはすぐに使用でき、ごみ箱から削除されます。復元されたスナップショットは、アカウント内の他のスナップショットと同じ方法で使用できます。  

```
aws ec2 restore-snapshot-from-recycle-bin \
    --snapshot-id snap-01234567890abcdef
```
このコマンドでは何も出力されません。  
ごみ箱の詳細については、*Amazon EBS ユーザーガイド*の「[削除されたスナップショットをごみ箱から復元する](https://docs.aws.amazon.com/ebs/latest/userguide/recycle-bin-working-with-snaps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreSnapshotFromRecycleBin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/restore-snapshot-from-recycle-bin.html)」を参照してください。

### `restore-snapshot-tier`
<a name="ec2_RestoreSnapshotTier_cli_2_topic"></a>

次のコード例は、`restore-snapshot-tier` を使用する方法を示しています。

**AWS CLI**  
**例 1: アーカイブされたスナップショットを永続的に復元するには**  
次の `restore-snapshot-tier` の例では、指定したスナップショットを完全に復元します。`--snapshot-id` を指定し、`permanent-restore` オプションを含めます。  

```
aws ec2 restore-snapshot-tier \
    --snapshot-id snap-01234567890abcedf \
    --permanent-restore
```
出力:  

```
{
    "SnapshotId": "snap-01234567890abcedf",
    "IsPermanentRestore": true
}
```
スナップショットのアーカイブの詳細については、*Amazon EBS ユーザーガイド*の「[Amazon EBS スナップショットのアーカイブ](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html)」を参照してください。  
**例 2: アーカイブされたスナップショットを一時的に復元するには**  
次の `restore-snapshot-tier` の例では、指定したスナップショットを一時的に復元します。`--permanent-restore` オプションを省略します。`--snapshot-id` を指定し、`temporary-restore-days` にスナップショットを復元する日数を指定します。`temporary-restore-days` は日数で指定する必要があります。許容範囲は `1`～`180` です。値を指定しないと、デフォルトで `1` に設定されます。  

```
aws ec2 restore-snapshot-tier \
    --snapshot-id snap-01234567890abcedf \
    --temporary-restore-days 5
```
出力:  

```
{
    "SnapshotId": "snap-01234567890abcedf",
    "RestoreDuration": 5,
    "IsPermanentRestore": false
}
```
スナップショットのアーカイブの詳細については、*Amazon EBS ユーザーガイド*の「[Amazon EBS スナップショットのアーカイブ](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html)」を参照してください。  
**例 3: 復元期間を変更するには**  
次の `restore-snapshot-tier` の例では、指定したスナップショットの復元期間を `10` 日間に変更します。  

```
aws ec2 restore-snapshot-tier \
    --snapshot-id snap-01234567890abcedf
    --temporary-restore-days 10
```
出力:  

```
{
    "SnapshotId": "snap-01234567890abcedf",
    "RestoreDuration": 10,
    "IsPermanentRestore": false
}
```
スナップショットのアーカイブの詳細については、*Amazon EBS ユーザーガイド*の「[Amazon EBS スナップショットのアーカイブ](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html)」を参照してください。  
**例 4: 復元タイプを変更するには**  
次の `restore-snapshot-tier` の例では、指定したスナップショットの復元タイプを一時的から完全に変更します。  

```
aws ec2 restore-snapshot-tier \
    --snapshot-id snap-01234567890abcedf
    --permanent-restore
```
出力:  

```
{
    "SnapshotId": "snap-01234567890abcedf",
    "IsPermanentRestore": true
}
```
スナップショットのアーカイブの詳細については、*Amazon EBS ユーザーガイド*の「[Amazon EBS スナップショットのアーカイブ](https://docs.aws.amazon.com/ebs/latest/userguide/snapshot-archive.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreSnapshotTier](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/restore-snapshot-tier.html)」を参照してください。

### `revoke-client-vpn-ingress`
<a name="ec2_RevokeClientVpnIngress_cli_2_topic"></a>

次のコード例は、`revoke-client-vpn-ingress` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントの承認ルールを取り消すには**  
次の `revoke-client-vpn-ingress` の例では、すべてのグループのインターネットアクセス (`0.0.0.0/0`) のルールを取り消します。  

```
aws ec2 revoke-client-vpn-ingress \
    --client-vpn-endpoint-id cvpn-endpoint-123456789123abcde \
    --target-network-cidr 0.0.0.0/0 --revoke-all-groups
```
出力:  

```
{
    "Status": {
        "Code": "revoking"
    }
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Authorization Rules](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokeClientVpnIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-client-vpn-ingress.html)」を参照してください。

### `revoke-security-group-egress`
<a name="ec2_RevokeSecurityGroupEgress_cli_2_topic"></a>

次のコード例は、`revoke-security-group-egress` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定のアドレス範囲へのアウトバウンドトラフィックを許可するルールを削除するには**  
次の `revoke-security-group-egress` の例では、TCP ポート 80 で指定されたアドレス範囲へのアクセスを付与するルールを削除します。  

```
aws ec2 revoke-security-group-egress \
    --group-id sg-026c12253ce15eff7 \
    --ip-permissions [{IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges=[{CidrIp=10.0.0.0/16}]
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)」を参照してください。  
**例 2: 特定のセキュリティグループへのアウトバウンドトラフィックを許可するルールを削除するには**  
次の `revoke-security-group-egress` の例では、TCP ポート 80 で指定されたセキュリティグループへのアクセスを付与するルールを削除します。  

```
aws ec2 revoke-security-group-egress \
    --group-id sg-026c12253ce15eff7 \
    --ip-permissions '[{"IpProtocol": "tcp", "FromPort": 443, "ToPort": 443,"UserIdGroupPairs": [{"GroupId": "sg-06df23a01ff2df86d"}]}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokeSecurityGroupEgress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-security-group-egress.html)」を参照してください。

### `revoke-security-group-ingress`
<a name="ec2_RevokeSecurityGroupIngress_cli_2_topic"></a>

次のコード例は、`revoke-security-group-ingress` を使用する方法を示しています。

**AWS CLI**  
**例 1: セキュリティグループからルールを削除するには**  
次の `revoke-security-group-ingress` の例では、デフォルトの VPC に指定されたセキュリティグループから、`203.0.113.0/24` アドレス範囲の TCP ポート 22 アクセスを削除します。  

```
aws ec2 revoke-security-group-ingress \
    --group-name mySecurityGroup
    --protocol tcp \
    --port 22 \
    --cidr 203.0.113.0/24
```
このコマンドが成功した場合、出力は生成されません。  
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)」を参照してください。  
**例 2: IP アクセス許可セットを使用してルールを削除するには**  
次の `revoke-security-group-ingress` の例では、`ip-permissions` パラメータを使用して、ICMP メッセージ `Destination Unreachable: Fragmentation Needed and Don't Fragment was Set` (タイプ 3、コード 4) を許可するインバウンドルールを削除します。  

```
aws ec2 revoke-security-group-ingress \
    --group-id sg-026c12253ce15eff7 \
    --ip-permissions IpProtocol=icmp,FromPort=3,ToPort=4,IpRanges=[{CidrIp=0.0.0.0/0}]
```
このコマンドが成功した場合、出力は生成されません。  
詳細については、「*Amazon EC2 ユーザーガイド*」の「[Security groups](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokeSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/revoke-security-group-ingress.html)」を参照してください。

### `run-instances`
<a name="ec2_RunInstances_cli_2_topic"></a>

次のコード例は、`run-instances` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスをデフォルトサブネット内で起動するには**  
次の `run-instances` の例では、現在のリージョンのデフォルトサブネットにタイプ `t2.micro` の単一のインスタンスを起動し、それをリージョンのデフォルト VPC のデフォルトサブネットに関連付けます。SSH (Linux) または RDP (Windows) を使用してインスタンスに接続する予定がない場合、キーペアはオプションです。  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --key-name MyKeyPair
```
出力:  

```
{
    "Instances": [
        {
            "AmiLaunchIndex": 0,
            "ImageId": "ami-0abcdef1234567890",
            "InstanceId": "i-1231231230abcdef0",
            "InstanceType": "t2.micro",
            "KeyName": "MyKeyPair",
            "LaunchTime": "2018-05-10T08:05:20.000Z",
            "Monitoring": {
                "State": "disabled"
            },
            "Placement": {
                "AvailabilityZone": "us-east-2a",
                "GroupName": "",
                "Tenancy": "default"
            },
            "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
            "PrivateIpAddress": "10.0.0.157",
            "ProductCodes": [],
            "PublicDnsName": "",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "StateTransitionReason": "",
            "SubnetId": "subnet-04a636d18e83cfacb",
            "VpcId": "vpc-1234567890abcdef0",
            "Architecture": "x86_64",
            "BlockDeviceMappings": [],
            "ClientToken": "",
            "EbsOptimized": false,
            "Hypervisor": "xen",
            "NetworkInterfaces": [
                {
                    "Attachment": {
                        "AttachTime": "2018-05-10T08:05:20.000Z",
                        "AttachmentId": "eni-attach-0e325c07e928a0405",
                        "DeleteOnTermination": true,
                        "DeviceIndex": 0,
                        "Status": "attaching"
                    },
                    "Description": "",
                    "Groups": [
                        {
                            "GroupName": "MySecurityGroup",
                            "GroupId": "sg-0598c7d356eba48d7"
                        }
                    ],
                    "Ipv6Addresses": [],
                    "MacAddress": "0a:ab:58:e0:67:e2",
                    "NetworkInterfaceId": "eni-0c0a29997760baee7",
                    "OwnerId": "123456789012",
                    "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                    "PrivateIpAddress": "10.0.0.157",
                    "PrivateIpAddresses": [
                        {
                            "Primary": true,
                            "PrivateDnsName": "ip-10-0-0-157.us-east-2.compute.internal",
                            "PrivateIpAddress": "10.0.0.157"
                        }
                    ],
                    "SourceDestCheck": true,
                    "Status": "in-use",
                    "SubnetId": "subnet-04a636d18e83cfacb",
                    "VpcId": "vpc-1234567890abcdef0",
                    "InterfaceType": "interface"
                }
            ],
            "RootDeviceName": "/dev/xvda",
            "RootDeviceType": "ebs",
            "SecurityGroups": [
                {
                    "GroupName": "MySecurityGroup",
                    "GroupId": "sg-0598c7d356eba48d7"
                }
            ],
            "SourceDestCheck": true,
            "StateReason": {
                "Code": "pending",
                "Message": "pending"
            },
            "Tags": [],
            "VirtualizationType": "hvm",
            "CpuOptions": {
                "CoreCount": 1,
                "ThreadsPerCore": 1
            },
            "CapacityReservationSpecification": {
                "CapacityReservationPreference": "open"
            },
            "MetadataOptions": {
                "State": "pending",
                "HttpTokens": "optional",
                "HttpPutResponseHopLimit": 1,
                "HttpEndpoint": "enabled"
            }
        }
    ],
    "OwnerId": "123456789012",
    "ReservationId": "r-02a3f596d91211712"
}
```
**例 2: デフォルトではないサブネットでインスタンスを起動し、パブリック IP アドレスを追加するには**  
次の `run-instances` の例では、デフォルト以外のサブネットで起動するインスタンスのパブリック IP アドレスをリクエストします。インスタンスは指定されたセキュリティグループに関連付けられます。  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --subnet-id subnet-08fc749671b2d077c \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --associate-public-ip-address \
    --key-name MyKeyPair
```
`run-instances` の出力例については、例 1 を参照してください。  
**例 3: ボリュームを追加してインスタンスを起動するには**  
次の `run-instances` の例では、mapping.json で指定されたブロックデバイスマッピングを使用して、起動時に追加のボリュームをアタッチします。ブロックデバイスマッピングは、EBS ボリューム、インスタンスストアボリューム、あるいは EBS ボリュームとインスタンスストアボリュームの両方を指定できます。  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --subnet-id subnet-08fc749671b2d077c \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --key-name MyKeyPair \
    --block-device-mappings file://mapping.json
```
`mapping.json` の内容。この例では、サイズが 100 GiB である空の EBS ボリュームの `/dev/sdh` を追加します。  

```
[
    {
        "DeviceName": "/dev/sdh",
        "Ebs": {
            "VolumeSize": 100
        }
    }
]
```
`mapping.json` の内容。この例は、`ephemeral1` をインスタンスストアボリュームとして追加しています。  

```
[
    {
        "DeviceName": "/dev/sdc",
        "VirtualName": "ephemeral1"
    }
]
```
`run-instances` の出力例については、例 1 を参照してください。  
ブロックデバイスマッピングの詳細については、「*Amazon EC2 ユーザーガイド*」の「[ブロックデバイスマッピング](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html)」を参照してください。  
**例 4: インスタンスを起動し、作成時にタグを追加するには**  
次の `run-instances` の例では、キー `webserver` と値 `production` のタグをインスタンスに追加しています。さらに、`cost-center` キーと `cc123` の値を持つタグを、作成された EBS ボリューム (この場合はルートボリューム) に適用します。  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --count 1 \
    --subnet-id subnet-08fc749671b2d077c \
    --key-name MyKeyPair \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --tag-specifications 'ResourceType=instance,Tags=[{Key=webserver,Value=production}]' 'ResourceType=volume,Tags=[{Key=cost-center,Value=cc123}]'
```
`run-instances` の出力例については、例 1 を参照してください。  
**例 5: ユーザーデータを使用してインスタンスを起動するには**  
次の `run-instances` の例では、インスタンスの設定スクリプトを含む `my_script.txt` というファイルにユーザーデータを渡します。このスクリプトは起動時に実行されます。  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --count 1 \
    --subnet-id subnet-08fc749671b2d077c \
    --key-name MyKeyPair \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --user-data file://my_script.txt
```
`run-instances` の出力例については、例 1 を参照してください。  
インスタンスユーザーデータの詳細については、「*Amazon EC2 ユーザーガイド*」の「[インスタンスユーザーデータの使用](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-add-user-data.html)」を参照してください。  
**例 6: バーストパフォーマンスインスタンスを起動するには**  
次の `run-instances` の例では、`unlimited` クレジットオプションを使用して t2.micro インスタンスを起動しています。T2 インスタンスを起動する際に `--credit-specification` を指定しない場合、デフォルトは `standard` クレジットオプションです。T3 インスタンスを起動する際、デフォルトは `unlimited` クレジットオプションです。  

```
aws ec2 run-instances \
    --image-id ami-0abcdef1234567890 \
    --instance-type t2.micro \
    --count 1 \
    --subnet-id subnet-08fc749671b2d077c \
    --key-name MyKeyPair \
    --security-group-ids sg-0b0384b66d7d692f9 \
    --credit-specification CpuCredits=unlimited
```
`run-instances` の出力例については、例 1 を参照してください。  
バーストパフォーマンスインスタンスの詳細については、「*Amazon EC2 ユーザーガイド*」の「[バーストパフォーマンスインスタンス](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/burstable-performance-instances.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[RunInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/run-instances.html)」を参照してください。

### `run-scheduled-instances`
<a name="ec2_RunScheduledInstances_cli_2_topic"></a>

次のコード例は、`run-scheduled-instances` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされたインスタンスを起動するには**  
この例では、VPC で指定されたスケジュールされたインスタンスを起動します。  
コマンド:  

```
aws ec2 run-scheduled-instances --scheduled-instance-id sci-1234-1234-1234-1234-123456789012 --instance-count 1 --launch-specification file://launch-specification.json
```
Launch-specification.json:  

```
{
  "ImageId": "ami-12345678",
  "KeyName": "my-key-pair",
  "InstanceType": "c4.large",
  "NetworkInterfaces": [
    {
        "DeviceIndex": 0,
        "SubnetId": "subnet-12345678",
        "AssociatePublicIpAddress": true,
        "Groups": ["sg-12345678"]
    }
  ],
  "IamInstanceProfile": {
      "Name": "my-iam-role"
  }
}
```
出力:  

```
{
  "InstanceIdSet": [
      "i-1234567890abcdef0"
  ]
}
```
この例では、EC2-Classic で指定されたスケジュールされたインスタンスを起動します。  
コマンド:  

```
aws ec2 run-scheduled-instances --scheduled-instance-id sci-1234-1234-1234-1234-123456789012 --instance-count 1 --launch-specification file://launch-specification.json
```
Launch-specification.json:  

```
{
  "ImageId": "ami-12345678",
  "KeyName": "my-key-pair",
  "SecurityGroupIds": ["sg-12345678"],
  "InstanceType": "c4.large",
  "Placement": {
    "AvailabilityZone": "us-west-2b"
  }
  "IamInstanceProfile": {
      "Name": "my-iam-role"
  }
}
```
出力:  

```
{
  "InstanceIdSet": [
      "i-1234567890abcdef0"
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RunScheduledInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/run-scheduled-instances.html)」を参照してください。

### `search-local-gateway-routes`
<a name="ec2_SearchLocalGatewayRoutes_cli_2_topic"></a>

次のコード例は、`search-local-gateway-routes` を使用する方法を示しています。

**AWS CLI**  
**ローカルゲートウェイのルートテーブル内のルートを検索するには**  
次の `search-local-gateway-routes` の例では、指定されたローカルゲートウェイのルートテーブルで静的ルートを検索します。  

```
aws ec2 search-local-gateway-routes \
    --local-gateway-route-table-id lgw-rtb-059615ef7dEXAMPLE \
    --filters "Name=type,Values=static"
```
出力:  

```
{
    "Route": {
        "DestinationCidrBlock": "0.0.0.0/0",
        "LocalGatewayVirtualInterfaceGroupId": "lgw-vif-grp-07145b276bEXAMPLE",
        "Type": "static",
        "State": "deleted",
        "LocalGatewayRouteTableId": "lgw-rtb-059615ef7EXAMPLE"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchLocalGatewayRoutes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/search-local-gateway-routes.html)」を参照してください。

### `search-transit-gateway-multicast-groups`
<a name="ec2_SearchTransitGatewayMulticastGroups_cli_2_topic"></a>

次のコード例は、`search-transit-gateway-multicast-groups` を使用する方法を示しています。

**AWS CLI**  
**1 つまたは複数の Transit Gateway マルチキャストグループを検索し、グループメンバーシップ情報を返すには**  
次の `search-transit-gateway-multicast-groups` の例では、指定されたマルチキャストグループのグループメンバーシップを返します。  

```
aws ec2 search-transit-gateway-multicast-groups \
    --transit-gateway-multicast-domain-id tgw-mcast-domain-000fb24d04EXAMPLE
```
出力:  

```
{
    "MulticastGroups": [
        {
            "GroupIpAddress": "224.0.1.0",
            "TransitGatewayAttachmentId": "tgw-attach-0372e72386EXAMPLE",
            "SubnetId": "subnet-0187aff814EXAMPLE",
            "ResourceId": "vpc-0065acced4EXAMPLE",
            "ResourceType": "vpc",
            "NetworkInterfaceId": "eni-03847706f6EXAMPLE",
            "GroupMember": false,
            "GroupSource": true,
            "SourceType": "static"
        }
    ]
}
```
詳細については、*Transit Gateways ガイド*の「[Transit Gateways でのマルチキャスト](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-multicast-overview.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchTransitGatewayMulticastGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/search-transit-gateway-multicast-groups.html)」を参照してください。

### `search-transit-gateway-routes`
<a name="ec2_SearchTransitGatewayRoutes_cli_2_topic"></a>

次のコード例は、`search-transit-gateway-routes` を使用する方法を示しています。

**AWS CLI**  
**指定された Transit Gateway のルートテーブルでルートを検索するには**  
次の `search-transit-gateway-routes` の例では、指定されたルートテーブルでタイプ `static` であるすべてのルートを返します。  

```
aws ec2 search-transit-gateway-routes \
    --transit-gateway-route-table-id tgw-rtb-0a823edbdeEXAMPLE \
    --filters "Name=type,Values=static"
```
出力:  

```
{
    "Routes": [
        {
            "DestinationCidrBlock": "10.0.2.0/24",
            "TransitGatewayAttachments": [
                {
                    "ResourceId": "vpc-4EXAMPLE",
                    "TransitGatewayAttachmentId": "tgw-attach-09b52ccdb5EXAMPLE",
                    "ResourceType": "vpc"
                }
            ],
            "Type": "static",
            "State": "active"
        },
        {
            "DestinationCidrBlock": "10.1.0.0/24",
            "TransitGatewayAttachments": [
                {
                    "ResourceId": "vpc-4EXAMPLE",
                    "TransitGatewayAttachmentId": "tgw-attach-09b52ccdb5EXAMPLE",
                    "ResourceType": "vpc"
                }
            ],
            "Type": "static",
            "State": "active"
        }
    ],
    "AdditionalRoutesAvailable": false
}
```
詳細については、「*Transit Gateways ガイド*」の「[Transit gateway route tables](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchTransitGatewayRoutes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/search-transit-gateway-routes.html)」を参照してください。

### `send-diagnostic-interrupt`
<a name="ec2_SendDiagnosticInterrupt_cli_2_topic"></a>

次のコード例は、`send-diagnostic-interrupt` を使用する方法を示しています。

**AWS CLI**  
**診断割り込みを送信送信するには**  
次の `send-diagnostic-interrupt` の例では、指定されたインスタンスに診断割り込みを送信します。  

```
aws ec2 send-diagnostic-interrupt \
    --instance-id i-1234567890abcdef0
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendDiagnosticInterrupt](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/send-diagnostic-interrupt.html)」を参照してください。

### `start-instances`
<a name="ec2_StartInstances_cli_2_topic"></a>

次のコード例は、`start-instances` を使用する方法を示しています。

**AWS CLI**  
**Amazon EC2 インスタンスを開始するには**  
この例では、指定された Amazon EBS-backed インスタンスを開始します。  
コマンド:  

```
aws ec2 start-instances --instance-ids i-1234567890abcdef0
```
出力:  

```
{
    "StartingInstances": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "CurrentState": {
                "Code": 0,
                "Name": "pending"
            },
            "PreviousState": {
                "Code": 80,
                "Name": "stopped"
            }
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「インスタンスの停止と起動」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[StartInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/start-instances.html)」を参照してください。

### `start-network-insights-access-scope-analysis`
<a name="ec2_StartNetworkInsightsAccessScopeAnalysis_cli_2_topic"></a>

次のコード例は、`start-network-insights-access-scope-analysis` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインサイトのアクセス範囲分析を開始するには**  
次の の`start-network-insights-access-scope-analysis`例では、 AWS アカウントでスコープ分析を開始します。  

```
aws ec2 start-network-insights-access-scope-analysis \
    --region us-east-1 \
    --network-insights-access-scope-id nis-123456789111
```
出力:  

```
{
    "NetworkInsightsAccessScopeAnalysis": {
        "NetworkInsightsAccessScopeAnalysisId": "nisa-123456789222",
        "NetworkInsightsAccessScopeAnalysisArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-access-scope-analysis/nisa-123456789222",
        "NetworkInsightsAccessScopeId": "nis-123456789111",
        "Status": "running",
        "StartDate": "2022-01-26T00:47:06.814000+00:00"
    }
}
```
詳細については、[「Network Access Analyzer ガイド」の「 CLI AWS を使用した Network Access Analyzer の開始方法](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartNetworkInsightsAccessScopeAnalysis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/start-network-insights-access-scope-analysis.html)」を参照してください。

### `start-network-insights-analysis`
<a name="ec2_StartNetworkInsightsAnalysis_cli_2_topic"></a>

次のコード例は、`start-network-insights-analysis` を使用する方法を示しています。

**AWS CLI**  
**パスを分析するには**  
次の `start-network-insights-analysis` の例では、送信元と送信先の間のパスを分析します。パス分析の結果を表示するには、`describe-network-insights-analyses` コマンドを使用します。  

```
aws ec2 start-network-insights-analysis \
    --network-insights-path-id nip-0b26f224f1d131fa8
```
出力:  

```
{
    "NetworkInsightsAnalysis": {
        "NetworkInsightsAnalysisId": "nia-02207aa13eb480c7a",
        "NetworkInsightsAnalysisArn": "arn:aws:ec2:us-east-1:123456789012:network-insights-analysis/nia-02207aa13eb480c7a",
        "NetworkInsightsPathId": "nip-0b26f224f1d131fa8",
        "StartDate": "2021-01-20T22:58:37.495Z",
        "Status": "running"
    }
}
```
詳細については、*「Reachability Analyzer* [Guide」の「Getting started using the AWS CLI](https://docs.aws.amazon.com/vpc/latest/reachability/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartNetworkInsightsAnalysis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/start-network-insights-analysis.html)」を参照してください。

### `start-vpc-endpoint-service-private-dns-verification`
<a name="ec2_StartVpcEndpointServicePrivateDnsVerification_cli_2_topic"></a>

次のコード例は、`start-vpc-endpoint-service-private-dns-verification` を使用する方法を示しています。

**AWS CLI**  
**DNS 検証プロセスを開始するには**  
次の `start-vpc-endpoint-service-private-dns-verification` 例では、指定されたエンドポイントサービスの DNS 検証プロセスを開始します。  

```
aws ec2 start-vpc-endpoint-service-private-dns-verification \
    --service-id vpce-svc-071afff70666e61e0
```
このコマンドでは何も出力されません。  
詳細については、「*AWS PrivateLink ユーザーガイド*」の「[Manage DNS names](https://docs.aws.amazon.com/vpc/latest/privatelink/manage-dns-names.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartVpcEndpointServicePrivateDnsVerification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/start-vpc-endpoint-service-private-dns-verification.html)」を参照してください。

### `stop-instances`
<a name="ec2_StopInstances_cli_2_topic"></a>

次のコード例は、`stop-instances` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EC2 インスタンスを停止するには**  
次の `stop-instances` の例では、Amazon EBS-backed インスタンスを停止します。  

```
aws ec2 stop-instances \
    --instance-ids i-1234567890abcdef0
```
出力:  

```
{
    "StoppingInstances": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "CurrentState": {
                "Code": 64,
                "Name": "stopping"
            },
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[インスタンスの停止と起動](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html)」を参照してください。  
**例 2: Amazon EC2 インスタンスを休止するには**  
次の `stop-instances` の例では、休止が有効で、休止の前提条件を満たしている場合に Amazon EBS-backed インスタンスを休止します。インスタンスが休止状態になると、インスタンスは停止されます。  

```
aws ec2 stop-instances \
    --instance-ids i-1234567890abcdef0 \
    --hibernate
```
出力:  

```
{
    "StoppingInstances": [
        {
            "CurrentState": {
                "Code": 64,
                "Name": "stopping"
            },
            "InstanceId": "i-1234567890abcdef0",
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
詳細については、「*Amazon Elastic Compute Cloud ユーザーガイド*」の「[オンデマンド Linux インスタンスの休止方法](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Hibernate.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[StopInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/stop-instances.html)」を参照してください。

### `terminate-client-vpn-connections`
<a name="ec2_TerminateClientVpnConnections_cli_2_topic"></a>

次のコード例は、`terminate-client-vpn-connections` を使用する方法を示しています。

**AWS CLI**  
**クライアント VPN エンドポイントへの接続を終了するには**  
次の `terminate-client-vpn-connections` の例では、クライアント VPN エンドポイントへの指定された接続を終了します。  

```
aws ec2 terminate-client-vpn-connections \
    --client-vpn-endpoint-id vpn-endpoint-123456789123abcde \
    --connection-id cvpn-connection-04edd76f5201e0cb8
```
出力:  

```
{
    "ClientVpnEndpointId": "vpn-endpoint-123456789123abcde",
    "ConnectionStatuses": [
        {
            "ConnectionId": "cvpn-connection-04edd76f5201e0cb8",
            "PreviousStatus": {
                "Code": "active"
            },
            "CurrentStatus": {
                "Code": "terminating"
            }
        }
    ]
}
```
詳細については、「*AWS Client VPN 管理者ガイド*」の「[Client Connections](https://docs.aws.amazon.com/vpn/latest/clientvpn-admin/cvpn-working-connections.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TerminateClientVpnConnections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/terminate-client-vpn-connections.html)」を参照してください。

### `terminate-instances`
<a name="ec2_TerminateInstances_cli_2_topic"></a>

次のコード例は、`terminate-instances` を使用する方法を示しています。

**AWS CLI**  
**Amazon EC2 インスタンスを終了するには**  
この例では、指定されたインスタンスを終了します。  
コマンド:  

```
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0
```
出力:  

```
{
    "TerminatingInstances": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "CurrentState": {
                "Code": 32,
                "Name": "shutting-down"
            },
            "PreviousState": {
                "Code": 16,
                "Name": "running"
            }
        }
    ]
}
```
詳細については、「*AWS コマンドラインインターフェイスユーザーガイド*」で Amazon EC2 インスタンスの使用方法を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[TerminateInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/terminate-instances.html)」を参照してください。

### `unassign-ipv6-addresses`
<a name="ec2_UnassignIpv6Addresses_cli_2_topic"></a>

次のコード例は、`unassign-ipv6-addresses` を使用する方法を示しています。

**AWS CLI**  
ネットワークインターフェイスから IPv6 アドレスを割り当て解除するには  
この例では、指定されたネットワークインターフェイスから指定された IPv6 アドレスの割り当てを解除します。  
コマンド:  

```
aws ec2 unassign-ipv6-addresses --ipv6-addresses 2001:db8:1234:1a00:3304:8879:34cf:4071 --network-interface-id eni-23c49b68
```
出力:  

```
{
  "NetworkInterfaceId": "eni-23c49b68",
  "UnassignedIpv6Addresses": [
      "2001:db8:1234:1a00:3304:8879:34cf:4071"
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UnassignIpv6Addresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/unassign-ipv6-addresses.html)」を参照してください。

### `unassign-private-ip-addresses`
<a name="ec2_UnassignPrivateIpAddresses_cli_2_topic"></a>

次のコード例は、`unassign-private-ip-addresses` を使用する方法を示しています。

**AWS CLI**  
**ネットワークインターフェイスからセカンダリプライベート IP アドレスの割り当てを解除するには**  
この例では、指定されたネットワークインターフェイスから指定されたプライベート IP アドレスの割り当てを解除します。コマンドが成功した場合、出力は返りません。  
コマンド:  

```
aws ec2 unassign-private-ip-addresses --network-interface-id eni-e5aa89a3 --private-ip-addresses 10.0.0.82
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UnassignPrivateIpAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/unassign-private-ip-addresses.html)」を参照してください。

### `unassign-private-nat-gateway-address`
<a name="ec2_UnassignPrivateNatGatewayAddress_cli_2_topic"></a>

次のコード例は、`unassign-private-nat-gateway-address` を使用する方法を示しています。

**AWS CLI**  
**プライベート NAT ゲートウェイからプライベート IP アドレスの割り当てを解除するには**  
次の `unassign-private-nat-gateway-address` の例では、指定されたプライベート NAT ゲートウェイから指定された IP アドレスの割り当てを解除します。  

```
aws ec2 unassign-private-nat-gateway-address \
    --nat-gateway-id nat-1234567890abcdef0 \
    --private-ip-addresses 10.0.20.197
```
出力:  

```
{
    "NatGatewayId": "nat-0ee3edd182361f662",
    "NatGatewayAddresses": [
        {
            "NetworkInterfaceId": "eni-0065a61b324d1897a",
            "PrivateIp": "10.0.20.197",
            "IsPrimary": false,
            "Status": "unassigning"
        }
    ]
}
```
詳細については、「*Amazon VPC ユーザーガイド*」の「[NAT ゲートウェイ](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UnassignPrivateNatGatewayAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/unassign-private-nat-gateway-address.html)」を参照してください。

### `unlock-snapshot`
<a name="ec2_UnlockSnapshot_cli_2_topic"></a>

次のコード例は、`unlock-snapshot` を使用する方法を示しています。

**AWS CLI**  
スナップショットをロック解除するには  
次の `unlock-snapshot` の例では、指定したスナップショットのロックを解除します。  

```
aws ec2 unlock-snapshot \
    --snapshot-id snap-0b5e733b4a8df6e0d
```
出力:  

```
{
    "SnapshotId": "snap-0b5e733b4a8df6e0d"
}
```
詳細については、「*Amazon EBS ユーザーガイド*」の「[Snapshot lock](https://docs.aws.amazon.com/ebs/latest/userguide/ebs-snapshot-lock.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UnlockSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/unlock-snapshot.html)」を参照してください。

### `unmonitor-instances`
<a name="ec2_UnmonitorInstances_cli_2_topic"></a>

次のコード例は、`unmonitor-instances` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの詳細モニタリングを無効にするには**  
このコマンド例は、指定されたインスタンスの詳細モニタリングを無効にします。  
コマンド:  

```
aws ec2 unmonitor-instances --instance-ids i-1234567890abcdef0
```
出力:  

```
{
  "InstanceMonitorings": [
      {
          "InstanceId": "i-1234567890abcdef0",
          "Monitoring": {
              "State": "disabling"
          }
      }
  ]
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UnmonitorInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/unmonitor-instances.html)」を参照してください。

### `update-security-group-rule-descriptions-egress`
<a name="ec2_UpdateSecurityGroupRuleDescriptionsEgress_cli_2_topic"></a>

次のコード例は、`update-security-group-rule-descriptions-egress` を使用する方法を示しています。

**AWS CLI**  
**アウトバウンドセキュリティグループのルールの説明を更新するには**  
次の `update-security-group-rule-descriptions-egress` の例では、指定したポートと IPv4 アドレス範囲のセキュリティグループルールの説明を更新します。説明 '`Outbound HTTP access to server 2`' は、ルールの既存の説明を置き換えます。  

```
aws ec2 update-security-group-rule-descriptions-egress \
    --group-id sg-02f0d35a850ba727f \
    --ip-permissions IpProtocol=tcp,FromPort=80,ToPort=80,IpRanges=[{CidrIp=203.0.113.0/24,Description="Outbound HTTP access to server 2"}]
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[セキュリティグループのルール](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html#security-group-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSecurityGroupRuleDescriptionsEgress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/update-security-group-rule-descriptions-egress.html)」を参照してください。

### `update-security-group-rule-descriptions-ingress`
<a name="ec2_UpdateSecurityGroupRuleDescriptionsIngress_cli_2_topic"></a>

次のコード例は、`update-security-group-rule-descriptions-ingress` を使用する方法を示しています。

**AWS CLI**  
**例 1: CIDR ソースを使用してインバウンドセキュリティグループのルールの説明を更新するには**  
次の `update-security-group-rule-descriptions-ingress` の例では、指定したポートと IPv4 アドレス範囲のセキュリティグループルールの説明を更新します。説明 '`SSH access from ABC office`' は、ルールの既存の説明を置き換えます。  

```
aws ec2 update-security-group-rule-descriptions-ingress \
    --group-id sg-02f0d35a850ba727f \
    --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,IpRanges='[{CidrIp=203.0.113.0/16,Description="SSH access from corpnet"}]'
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[セキュリティグループのルール](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html#security-group-rules)」を参照してください。  
**例 2: プレフィックスリストソースを使用してインバウンドセキュリティグループのルールの説明を更新するには**  
次の `update-security-group-rule-descriptions-ingress` の例では、指定したポートとプレフィックスリストのセキュリティグループルールの説明を更新します。説明 '`SSH access from ABC office`' は、ルールの既存の説明を置き換えます。  

```
aws ec2 update-security-group-rule-descriptions-ingress \
    --group-id sg-02f0d35a850ba727f \
    --ip-permissions IpProtocol=tcp,FromPort=22,ToPort=22,PrefixListIds='[{PrefixListId=pl-12345678,Description="SSH access from corpnet"}]'
```
出力:  

```
{
    "Return": true
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[セキュリティグループのルール](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html#security-group-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSecurityGroupRuleDescriptionsIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/update-security-group-rule-descriptions-ingress.html)」を参照してください。

### `withdraw-byoip-cidr`
<a name="ec2_WithdrawByoipCidr_cli_2_topic"></a>

次のコード例は、`withdraw-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲のアドバタイズを停止するには**  
次の `withdraw-byoip-cidr` の例では、指定したアドレス範囲のアドバタイズを中止します。  

```
aws ec2 withdraw-byoip-cidr
    --cidr 203.0.113.25/24
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "203.0.113.25/24",
        "StatusMessage": "ipv4pool-ec2-1234567890abcdef0",
        "State": "advertised"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[WithdrawByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/withdraw-byoip-cidr.html)」を参照してください。

# を使用した Amazon EC2 Instance Connect の例 AWS CLI
<a name="cli_2_ec2-instance-connect_code_examples"></a>

次のコード例は、Amazon EC2 Instance Connect AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `send-ssh-public-key`
<a name="ec2-instance-connect_SendSshPublicKey_cli_2_topic"></a>

次のコード例は、`send-ssh-public-key` を使用する方法を示しています。

**AWS CLI**  
**SSH パブリックキーをインスタンスに送信するには**  
次の `send-ssh-public-key` 例では、指定された SSH パブリックキーを指定されたインスタンスに送信します。このキーは、指定されたユーザーを認証するために使用されます。  

```
aws ec2-instance-connect send-ssh-public-key \
    --instance-id i-1234567890abcdef0 \
    --instance-os-user ec2-user \
    --availability-zone us-east-2b \
    --ssh-public-key file://path/my-rsa-key.pub
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendSshPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2-instance-connect/send-ssh-public-key.html)」を参照してください。

# を使用した Amazon ECR の例 AWS CLI
<a name="cli_2_ecr_code_examples"></a>

次のコード例は、Amazon ECR AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-check-layer-availability`
<a name="ecr_BatchCheckLayerAvailability_cli_2_topic"></a>

次のコード例は、`batch-check-layer-availability` を使用する方法を示しています。

**AWS CLI**  
**レイヤーの可用性を確認するには**  
次の `batch-check-layer-availability` の例では、`cluster-autoscaler` リポジトリ内のダイジェスト `sha256:6171c7451a50945f8ddd72f7732cc04d7a0d1f48138a426b2e64387fdeb834ed` を持つレイヤーの可用性をチェックします。  

```
aws ecr batch-check-layer-availability \
    --repository-name cluster-autoscaler \
    --layer-digests sha256:6171c7451a50945f8ddd72f7732cc04d7a0d1f48138a426b2e64387fdeb834ed
```
出力:  

```
{
    "layers": [
        {
            "layerDigest": "sha256:6171c7451a50945f8ddd72f7732cc04d7a0d1f48138a426b2e64387fdeb834ed",
            "layerAvailability": "AVAILABLE",
            "layerSize": 2777,
            "mediaType": "application/vnd.docker.container.image.v1+json"
        }
    ],
    "failures": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchCheckLayerAvailability](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/batch-check-layer-availability.html)」を参照してください。

### `batch-delete-image`
<a name="ecr_BatchDeleteImage_cli_2_topic"></a>

次のコード例は、`batch-delete-image` を使用する方法を示しています。

**AWS CLI**  
**例 1: イメージを削除するには**  
次の `batch-delete-image` の例では、アカウントのデフォルトレジストリの指定されたリポジトリに `precise` タグが付いたイメージを削除します。  

```
aws ecr batch-delete-image \
    --repository-name ubuntu \
    --image-ids imageTag=precise
```
出力:  

```
{
    "failures": [],
    "imageIds": [
        {
            "imageTag": "precise",
            "imageDigest": "sha256:19665f1e6d1e504117a1743c0a3d3753086354a38375961f2e665416ef4b1b2f"
        }
    ]
}
```
**例 2: 複数のイメージを削除するには**  
次の `batch-delete-image` の例では、指定されたリポジトリ内の `prod` と `team1` でタグ付けされたすべてのイメージを削除します。  

```
aws ecr batch-delete-image \
    --repository-name MyRepository \
    --image-ids imageTag=prod imageTag=team1
```
出力:  

```
{
    "imageIds": [
        {
            "imageDigest": "sha256:123456789012",
            "imageTag": "prod"
        },
        {
            "imageDigest": "sha256:567890121234",
            "imageTag": "team1"
        }
    ],
    "failures": []
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージの削除](https://docs.aws.amazon.com/AmazonECR/latest/userguide/delete_image.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDeleteImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/batch-delete-image.html)」を参照してください。

### `batch-get-image`
<a name="ecr_BatchGetImage_cli_2_topic"></a>

次のコード例は、`batch-get-image` を使用する方法を示しています。

**AWS CLI**  
**例 1: イメージを取得するには**  
次の `batch-get-image` の例では、アカウントのデフォルトレジストリで `cluster-autoscaler` と呼ばれるリポジトリ内の `v1.13.6` タグを持つイメージを取得します。  

```
aws ecr batch-get-image \
    --repository-name cluster-autoscaler \
    --image-ids imageTag=v1.13.6
```
出力:  

```
{
    "images": [
        {
            "registryId": "012345678910",
            "repositoryName": "cluster-autoscaler",
            "imageId": {
                "imageDigest": "sha256:4a1c6567c38904384ebc64e35b7eeddd8451110c299e3368d2210066487d97e5",
                "imageTag": "v1.13.6"
            },
            "imageManifest": "{\n   \"schemaVersion\": 2,\n   \"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\",\n   \"config\": {\n      \"mediaType\": \"application/vnd.docker.container.image.v1+json\",\n      \"size\": 2777,\n      \"digest\": \"sha256:6171c7451a50945f8ddd72f7732cc04d7a0d1f48138a426b2e64387fdeb834ed\"\n   },\n   \"layers\": [\n      {\n         \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n         \"size\": 17743696,\n         \"digest\": \"sha256:39fafc05754f195f134ca11ecdb1c9a691ab0848c697fffeb5a85f900caaf6e1\"\n      },\n      {\n         \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n         \"size\": 2565026,\n         \"digest\": \"sha256:8c8a779d3a537b767ae1091fe6e00c2590afd16767aa6096d1b318d75494819f\"\n      },\n      {\n         \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n         \"size\": 28005981,\n         \"digest\": \"sha256:c44ba47496991c9982ee493b47fd25c252caabf2b4ae7dd679c9a27b6a3c8fb7\"\n      },\n      {\n         \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n         \"size\": 775,\n         \"digest\": \"sha256:e2c388b44226544363ca007be7b896bcce1baebea04da23cbd165eac30be650f\"\n      }\n   ]\n}"
        }
    ],
    "failures": []
}
```
**例 2: 複数のイメージを取得するには**  
次の `batch-get-image` の例では、指定されたリポジトリ内の `prod` と `team1` でタグ付けされたすべてのイメージの詳細を表示します。  

```
aws ecr batch-get-image \
    --repository-name MyRepository \
    --image-ids imageTag=prod imageTag=team1
```
出力:  

```
{
    "images": [
        {
            "registryId": "123456789012",
            "repositoryName": "MyRepository",
            "imageId": {
                "imageDigest": "sha256:123456789012",
                "imageTag": "prod"
            },
            "imageManifest": "manifestExample1"
        },
        {
            "registryId": "567890121234",
            "repositoryName": "MyRepository",
            "imageId": {
                "imageDigest": "sha256:123456789012",
                "imageTag": "team1"
            },
            "imageManifest": "manifestExample2"
        }
    ],
    "failures": []
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージ](https://docs.aws.amazon.com/AmazonECR/latest/userguide/images.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/batch-get-image.html)」を参照してください。

### `complete-layer-upload`
<a name="ecr_CompleteLayerUpload_cli_2_topic"></a>

次のコード例は、`complete-layer-upload` を使用する方法を示しています。

**AWS CLI**  
**イメージレイヤーのアップロードを完了するには**  
次の `complete-layer-upload` の例では、`layer-test` リポジトリへのイメージレイヤーのアップロードを完了します。  

```
aws ecr complete-layer-upload \
    --repository-name layer-test \
    --upload-id 6cb64b8a-9378-0e33-2ab1-b780fab8a9e9 \
    --layer-digests 6cb64b8a-9378-0e33-2ab1-b780fab8a9e9:48074e6d3a68b39aad8ccc002cdad912d4148c0f92b3729323e
```
出力:  

```
{
    "uploadId": "6cb64b8a-9378-0e33-2ab1-b780fab8a9e9",
    "layerDigest": "sha256:9a77f85878aa1906f2020a0ecdf7a7e962d57e882250acd773383224b3fe9a02",
    "repositoryName": "layer-test",
    "registryId": "130757420319"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CompleteLayerUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/complete-layer-upload.html)」を参照してください。

### `create-repository`
<a name="ecr_CreateRepository_cli_2_topic"></a>

次のコード例は、`create-repository` を使用する方法を示しています。

**AWS CLI**  
**例 1: リポジトリを作成するには**  
次の `create-repository` の例では、アカウントのデフォルトレジストリ内の指定された名前空間にリポジトリを作成します。  

```
aws ecr create-repository \
    --repository-name project-a/sample-repo
```
出力:  

```
{
    "repository": {
        "registryId": "123456789012",
        "repositoryName": "project-a/sample-repo",
        "repositoryArn": "arn:aws:ecr:us-west-2:123456789012:repository/project-a/sample-repo"
    }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[リポジトリの作成](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)」を参照してください。  
**例 2: イメージタグのイミュータビリティが設定されたリポジトリを作成する場合**  
次の `create-repository` の例では、アカウントのデフォルトレジストリ内にタグのイミュータビリティが設定されたリポジトリを作成します。  

```
aws ecr create-repository \
    --repository-name project-a/sample-repo \
    --image-tag-mutability IMMUTABLE
```
出力:  

```
{
    "repository": {
        "registryId": "123456789012",
        "repositoryName": "project-a/sample-repo",
        "repositoryArn": "arn:aws:ecr:us-west-2:123456789012:repository/project-a/sample-repo",
        "imageTagMutability": "IMMUTABLE"
    }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージタグの変更可能性](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-tag-mutability.html)」を参照してください。  
**例 3: スキャン設定が設定されたリポジトリを作成する場合**  
次の `create-repository` の例では、アカウントのデフォルトレジストリ内でイメージプッシュに対して脆弱性スキャンを実行するように設定されたリポジトリを作成します。  

```
aws ecr create-repository \
    --repository-name project-a/sample-repo \
    --image-scanning-configuration scanOnPush=true
```
出力:  

```
{
    "repository": {
        "registryId": "123456789012",
        "repositoryName": "project-a/sample-repo",
        "repositoryArn": "arn:aws:ecr:us-west-2:123456789012:repository/project-a/sample-repo",
        "imageScanningConfiguration": {
            "scanOnPush": true
        }
    }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージスキャン](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/create-repository.html)」を参照してください。

### `delete-lifecycle-policy`
<a name="ecr_DeleteLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`delete-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのライフサイクルポリシーを削除するには**  
次の `delete-lifecycle-policy` の例では、`hello-world` リポジトリのライフサイクルポリシーを削除します。  

```
aws ecr delete-lifecycle-policy \
    --repository-name hello-world
```
出力:  

```
{
    "registryId": "012345678910",
    "repositoryName": "hello-world",
    "lifecyclePolicyText": "{\"rules\":[{\"rulePriority\":1,\"description\":\"Remove untagged images.\",\"selection\":{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":10},\"action\":{\"type\":\"expire\"}}]}",
    "lastEvaluatedAt": 0.0
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/delete-lifecycle-policy.html)」を参照してください。

### `delete-repository-policy`
<a name="ecr_DeleteRepositoryPolicy_cli_2_topic"></a>

次のコード例は、`delete-repository-policy` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのリポジトリポリシーを削除するには**  
次の `delete-repository-policy` の例では、`cluster-autoscaler` リポジトリのリポジトリポリシーを削除します。  

```
aws ecr delete-repository-policy \
    --repository-name cluster-autoscaler
```
出力:  

```
{
    "registryId": "012345678910",
    "repositoryName": "cluster-autoscaler",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"allow public pull\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : \"*\",\n    \"Action\" : [ \"ecr:BatchCheckLayerAvailability\", \"ecr:BatchGetImage\", \"ecr:GetDownloadUrlForLayer\" ]\n  } ]\n}"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRepositoryPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/delete-repository-policy.html)」を参照してください。

### `delete-repository`
<a name="ecr_DeleteRepository_cli_2_topic"></a>

次のコード例は、`delete-repository` を使用する方法を示しています。

**AWS CLI**  
**リポジトリを削除するには**  
次のコマンドフォース `delete-repository` の例では、アカウントのデフォルトレジストリ内の指定されたリポジトリを削除します。リポジトリにイメージが含まれている場合は、`--force` フラグが必要です。  

```
aws ecr delete-repository \
    --repository-name ubuntu \
    --force
```
出力:  

```
{
    "repository": {
        "registryId": "123456789012",
        "repositoryName": "ubuntu",
        "repositoryArn": "arn:aws:ecr:us-west-2:123456789012:repository/ubuntu"
    }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[リポジトリの削除](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/delete-repository.html)」を参照してください。

### `describe-image-scan-findings`
<a name="ecr_DescribeImageScanFindings_cli_2_topic"></a>

次のコード例は、`describe-image-scan-findings` を使用する方法を示しています。

**AWS CLI**  
**イメージのスキャンの検出結果を記述するには**  
次の `describe-image-scan-findings` の例では、アカウントのデフォルトレジストリの指定されたリポジトリでイメージダイジェストを使用して、イメージのイメージスキャン結果を返します。  

```
aws ecr describe-image-scan-findings \
    --repository-name sample-repo \
    --image-id imageDigest=sha256:74b2c688c700ec95a93e478cdb959737c148df3fbf5ea706abe0318726e885e6
```
出力:  

```
{
    "imageScanFindings": {
      "findings": [
          {
              "name": "CVE-2019-5188",
              "description": "A code execution vulnerability exists in the directory rehashing functionality of E2fsprogs e2fsck 1.45.4. A specially crafted ext4 directory can cause an out-of-bounds write on the stack, resulting in code execution. An attacker can corrupt a partition to trigger this vulnerability.",
              "uri": "http://people.ubuntu.com/~ubuntu-security/cve/CVE-2019-5188",
              "severity": "MEDIUM",
              "attributes": [
                  {
                      "key": "package_version",
                      "value": "1.44.1-1ubuntu1.1"
                  },
                  {
                      "key": "package_name",
                      "value": "e2fsprogs"
                  },
                  {
                      "key": "CVSS2_VECTOR",
                      "value": "AV:L/AC:L/Au:N/C:P/I:P/A:P"
                  },
                  {
                      "key": "CVSS2_SCORE",
                      "value": "4.6"
                  }
              ]
          }
      ],
      "imageScanCompletedAt": 1579839105.0,
      "vulnerabilitySourceUpdatedAt": 1579811117.0,
      "findingSeverityCounts": {
          "MEDIUM": 1
      }
  },
  "registryId": "123456789012",
  "repositoryName": "sample-repo",
  "imageId": {
      "imageDigest": "sha256:74b2c688c700ec95a93e478cdb959737c148df3fbf5ea706abe0318726e885e6"
  },
  "imageScanStatus": {
      "status": "COMPLETE",
      "description": "The scan was completed successfully."
  }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージスキャン](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeImageScanFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/describe-image-scan-findings.html)」を参照してください。

### `describe-images`
<a name="ecr_DescribeImages_cli_2_topic"></a>

次のコード例は、`describe-images` を使用する方法を示しています。

**AWS CLI**  
**リポジトリ内のイメージを記述する場合**  
次の `describe-images` の例では、`cluster-autoscaler` リポジトリ内でタグ `v1.13.6` が付いているイメージに関する詳細を表示します。  

```
aws ecr describe-images \
    --repository-name cluster-autoscaler \
    --image-ids imageTag=v1.13.6
```
出力:  

```
{
    "imageDetails": [
        {
            "registryId": "012345678910",
            "repositoryName": "cluster-autoscaler",
            "imageDigest": "sha256:4a1c6567c38904384ebc64e35b7eeddd8451110c299e3368d2210066487d97e5",
            "imageTags": [
                "v1.13.6"
            ],
            "imageSizeInBytes": 48318255,
            "imagePushedAt": 1565128275.0
        }
    ]
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/describe-images.html)」を参照してください。

### `describe-repositories`
<a name="ecr_DescribeRepositories_cli_2_topic"></a>

次のコード例は、`describe-repositories` を使用する方法を示しています。

**AWS CLI**  
**レジストリ内のリポジトリを記述するには**  
この例は、アカウントのデフォルトレジストリ内のリポジトリを記述します。  
コマンド:  

```
aws ecr describe-repositories
```
出力:  

```
{
    "repositories": [
        {
            "registryId": "012345678910",
            "repositoryName": "ubuntu",
            "repositoryArn": "arn:aws:ecr:us-west-2:012345678910:repository/ubuntu"
        },
        {
            "registryId": "012345678910",
            "repositoryName": "test",
            "repositoryArn": "arn:aws:ecr:us-west-2:012345678910:repository/test"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeRepositories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/describe-repositories.html)」を参照してください。**

### `get-authorization-token`
<a name="ecr_GetAuthorizationToken_cli_2_topic"></a>

次のコード例は、`get-authorization-token` を使用する方法を示しています。

**AWS CLI**  
**デフォルトレジストリ用の認可トークンを取得する場合**  
次のコマンド `get-authorization-token` の例では、デフォルトレジストリ用の認可トークンを取得します。  

```
aws ecr get-authorization-token
```
出力:  

```
{
    "authorizationData": [
        {
            "authorizationToken": "QVdTOkN...",
            "expiresAt": 1448875853.241,
            "proxyEndpoint": "https://123456789012.dkr.ecr.us-west-2.amazonaws.com"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthorizationToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/get-authorization-token.html)」を参照してください。

### `get-download-url-for-layer`
<a name="ecr_GetDownloadUrlForLayer_cli_2_topic"></a>

次のコード例は、`get-download-url-for-layer` を使用する方法を示しています。

**AWS CLI**  
**レイヤーのダウンロード URL を取得するには**  
次の `get-download-url-for-layer` の例は、`cluster-autoscaler` リポジトリ内のダイジェスト `sha256:6171c7451a50945f8ddd72f7732cc04d7a0d1f48138a426b2e64387fdeb834ed` を含むレイヤーのダウンロード URL を示しています。  

```
aws ecr get-download-url-for-layer \
    --repository-name cluster-autoscaler  \
    --layer-digest sha256:6171c7451a50945f8ddd72f7732cc04d7a0d1f48138a426b2e64387fdeb834ed
```
出力:  

```
{
    "downloadUrl": "https://prod-us-west-2-starport-layer-bucket.s3.us-west-2.amazonaws.com/e501-012345678910-9cb60dc0-7284-5643-3987-da6dac0465f0/04620aac-66a5-4167-8232-55ee7ef6d565?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190814T220617Z&X-Amz-SignedHeaders=host&X-Amz-Expires=3600&X-Amz-Credential=AKIA32P3D2JDNMVAJLGF%2F20190814%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=9161345894947a1672467a0da7a1550f2f7157318312fe4941b59976239c3337",
    "layerDigest": "sha256:6171c7451a50945f8ddd72f7732cc04d7a0d1f48138a426b2e64387fdeb834ed"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDownloadUrlForLayer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/get-download-url-for-layer.html)」を参照してください。

### `get-lifecycle-policy-preview`
<a name="ecr_GetLifecyclePolicyPreview_cli_2_topic"></a>

次のコード例は、`get-lifecycle-policy-preview` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシープレビューの詳細を取得するには**  
次の `get-lifecycle-policy-preview` 例では、アカウントのデフォルトレジストリで指定されたリポジトリのライフサイクルポリシープレビューの結果を取得します。  
コマンド:  

```
aws ecr get-lifecycle-policy-preview \
    --repository-name "project-a/amazon-ecs-sample"
```
出力:  

```
{
    "registryId": "012345678910",
    "repositoryName": "project-a/amazon-ecs-sample",
    "lifecyclePolicyText": "{\n    \"rules\": [\n        {\n            \"rulePriority\": 1,\n            \"description\": \"Expire images older than 14 days\",\n            \"selection\": {\n                \"tagStatus\": \"untagged\",\n                \"countType\": \"sinceImagePushed\",\n                \"countUnit\": \"days\",\n                \"countNumber\": 14\n            },\n            \"action\": {\n                \"type\": \"expire\"\n            }\n        }\n    ]\n}\n",
    "status": "COMPLETE",
    "previewResults": [],
    "summary": {
        "expiringImageTotalCount": 0
    }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[ライフサイクルポリシー](https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLifecyclePolicyPreview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/get-lifecycle-policy-preview.html)」を参照してください。

### `get-lifecycle-policy`
<a name="ecr_GetLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`get-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシーを取得するには**  
次の `get-lifecycle-policy` 例では、アカウントのデフォルトレジストリで、指定されたリポジトリのライフサイクルポリシーの詳細を表示します。  

```
aws ecr get-lifecycle-policy \
    --repository-name "project-a/amazon-ecs-sample"
```
出力:  

```
{
     "registryId": "123456789012",
     "repositoryName": "project-a/amazon-ecs-sample",
     "lifecyclePolicyText": "{\"rules\":[{\"rulePriority\":1,\"description\":\"Expire images older than 14 days\",\"selection\":{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":14},\"action\":{\"type\":\"expire\"}}]}",
     "lastEvaluatedAt": 1504295007.0
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[ライフサイクルポリシー](https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/get-lifecycle-policy.html)」を参照してください。

### `get-login-password`
<a name="ecr_GetLoginPassword_cli_2_topic"></a>

次のコード例は、`get-login-password` を使用する方法を示しています。

**AWS CLI**  
**レジストリに認証するパスワードを取得するには**  
次の `get-login-password` は、IAM プリンシパルがアクセスできる Amazon ECR レジストリに対して認証するために、選択したコンテナクライアントで使用できるパスワードを示しています。  

```
aws ecr get-login-password
```
出力:  

```
<password>
```
Docker CLI で使用するには、`get-login-password` コマンドの出力を `docker login` コマンドにパイプします。パスワードを取得するときは、Amazon ECR レジストリが存在するのと同じリージョンを指定する必要があります。  

```
aws ecr get-login-password \
    --region <region> \
| docker login \
    --username AWS \
    --password-stdin <aws_account_id>.dkr.ecr.<region>.amazonaws.com
```
詳細については、「[Amazon ECR ユーザーガイド](https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries#registry_auth)」の「*レジストリの認証*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoginPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/get-login-password.html)」を参照してください。

### `get-login`
<a name="ecr_GetLogin_cli_2_topic"></a>

次のコード例は、`get-login` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのレジストリに Docker ログインコマンドを取得するには**  
この例では、デフォルトの Amazon ECR レジストリにログインするために使用できるコマンドをプリントします。  
コマンド:  

```
aws ecr get-login
```
出力:  

```
docker login -u AWS -p <password> -e none https://<aws_account_id>.dkr.ecr.<region>.amazonaws.com
```
**別のアカウントのレジストリにログインするには**  
この例では、他のアカウントに関連付けられた Amazon ECR レジストリにログインするために使用できる 1 つ以上のコマンドをプリントします。  
コマンド:  

```
aws ecr get-login --registry-ids 012345678910 023456789012
```
出力:  

```
docker login -u <username> -p <token-1> -e none <endpoint-1>
docker login -u <username> -p <token-2> -e none <endpoint-2>
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLogin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/get-login.html)」を参照してください。

### `get-repository-policy`
<a name="ecr_GetRepositoryPolicy_cli_2_topic"></a>

次のコード例は、`get-repository-policy` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのリポジトリポリシーを取得するには**  
次の `get-repository-policy` の例では、`cluster-autoscaler` リポジトリのリポジトリポリシーの詳細を表示します。  

```
aws ecr get-repository-policy \
    --repository-name cluster-autoscaler
```
出力:  

```
{
    "registryId": "012345678910",
    "repositoryName": "cluster-autoscaler",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"allow public pull\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : \"*\",\n    \"Action\" : [ \"ecr:BatchCheckLayerAvailability\", \"ecr:BatchGetImage\", \"ecr:GetDownloadUrlForLayer\" ]\n  } ]\n}"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRepositoryPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/get-repository-policy.html)」を参照してください。

### `initiate-layer-upload`
<a name="ecr_InitiateLayerUpload_cli_2_topic"></a>

次のコード例は、`initiate-layer-upload` を使用する方法を示しています。

**AWS CLI**  
**イメージレイヤーのアップロードを開始するには**  
次の `initiate-layer-upload` 例では、`layer-test` リポジトリへのイメージレイヤーのアップロードを開始します。  

```
aws ecr initiate-layer-upload \
    --repository-name layer-test
```
出力:  

```
{
    "partSize": 10485760,
    "uploadId": "6cb64b8a-9378-0e33-2ab1-b780fab8a9e9"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InitiateLayerUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/initiate-layer-upload.html)」を参照してください。

### `list-images`
<a name="ecr_ListImages_cli_2_topic"></a>

次のコード例は、`list-images` を使用する方法を示しています。

**AWS CLI**  
**リポジトリ内のイメージを一覧表示するには**  
次の `list-images` の例は、`cluster-autoscaler` リポジトリ内のイメージのリストを表示します。  

```
aws ecr list-images \
    --repository-name cluster-autoscaler
```
出力:  

```
{
    "imageIds": [
        {
            "imageDigest": "sha256:99c6fb4377e9a420a1eb3b410a951c9f464eff3b7dbc76c65e434e39b94b6570",
            "imageTag": "v1.13.8"
        },
        {
            "imageDigest": "sha256:99c6fb4377e9a420a1eb3b410a951c9f464eff3b7dbc76c65e434e39b94b6570",
            "imageTag": "v1.13.7"
        },
        {
            "imageDigest": "sha256:4a1c6567c38904384ebc64e35b7eeddd8451110c299e3368d2210066487d97e5",
            "imageTag": "v1.13.6"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/list-images.html)」を参照してください。**

### `list-tags-for-resource`
<a name="ecr_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのタグを一覧表示するには**  
次の `list-tags-for-resource` の例は、`hello-world` リポジトリに関連するタグのリストを表示します。  

```
aws ecr list-tags-for-resource \
    --resource-arn arn:aws:ecr:us-west-2:012345678910:repository/hello-world
```
出力:  

```
{
    "tags": [
        {
            "Key": "Stage",
            "Value": "Integ"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/list-tags-for-resource.html)」を参照してください。

### `put-image-scanning-configuration`
<a name="ecr_PutImageScanningConfiguration_cli_2_topic"></a>

次のコード例は、`put-image-scanning-configuration` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのイメージスキャン設定を更新するには**  
次の `put-image-scanning-configuration` 例では、指定されたリポジトリのイメージスキャン設定を更新します。  

```
aws ecr put-image-scanning-configuration \
    --repository-name sample-repo \
    --image-scanning-configuration scanOnPush=true
```
出力:  

```
{
   "registryId": "012345678910",
   "repositoryName": "sample-repo",
   "imageScanningConfiguration": {
     "scanOnPush": true
   }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージスキャン](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutImageScanningConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/put-image-scanning-configuration.html)」を参照してください。

### `put-image-tag-mutability`
<a name="ecr_PutImageTagMutability_cli_2_topic"></a>

次のコード例は、`put-image-tag-mutability` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのイメージタグの変更可能性の設定を更新するには**  
次の `put-image-tag-mutability` の例では、タグのイミュータビリティを確保するため指定されたリポジトリを設定します。これにより、リポジトリ内のすべてのイメージタグが上書きされるのを防ぎます。  

```
aws ecr put-image-tag-mutability \
    --repository-name hello-repository \
    --image-tag-mutability IMMUTABLE
```
出力:  

```
{
   "registryId": "012345678910",
   "repositoryName": "sample-repo",
   "imageTagMutability": "IMMUTABLE"
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージタグの変更可能性](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-tag-mutability.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutImageTagMutability](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/put-image-tag-mutability.html)」を参照してください。

### `put-image`
<a name="ecr_PutImage_cli_2_topic"></a>

次のコード例は、`put-image` を使用する方法を示しています。

**AWS CLI**  
**マニフェストを使用してイメージにタグを付け直すには**  
次の `put-image` 例では、既存のイメージマニフェストを使用して `hello-world` リポジトリに新しいタグを作成します。  

```
aws ecr put-image \
    --repository-name hello-world \
    --image-tag 2019.08 \
    --image-manifest file://hello-world.manifest.json
```
`hello-world.manifest.json` の内容:  

```
{
    "schemaVersion": 2,
    "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
    "config": {
        "mediaType": "application/vnd.docker.container.image.v1+json",
        "size": 5695,
        "digest": "sha256:cea5fe7701b7db3dd1c372f3cea6f43cdda444fcc488f530829145e426d8b980"
    },
    "layers": [
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 39096921,
            "digest": "sha256:d8868e50ac4c7104d2200d42f432b661b2da8c1e417ccfae217e6a1e04bb9295"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 57938,
            "digest": "sha256:83251ac64627fc331584f6c498b3aba5badc01574e2c70b2499af3af16630eed"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 423,
            "digest": "sha256:589bba2f1b36ae56f0152c246e2541c5aa604b058febfcf2be32e9a304fec610"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 680,
            "digest": "sha256:d62ecaceda3964b735cdd2af613d6bb136a52c1da0838b2ff4b4dab4212bcb1c"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 162,
            "digest": "sha256:6d93b41cfc6bf0d2522b7cf61588de4cd045065b36c52bd3aec2ba0622b2b22b"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 28268840,
            "digest": "sha256:6986b4d4c07932c680b3587f2eac8b0e013568c003cc23b04044628a5c5e599f"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 35369152,
            "digest": "sha256:8c5ec60f10102dc8da0649d866c7c2f706e459d0bdc25c83ad2de86f4996c276"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 155,
            "digest": "sha256:cde50b1c594539c5f67cbede9aef95c9ae321ccfb857f7b251b45b84198adc85"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 28737,
            "digest": "sha256:2e102807ab72a73fc9abf53e8c50e421bdc337a0a8afcb242176edeec65977e4"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 190,
            "digest": "sha256:fc379bbd5ed37808772bef016553a297356c59b8f134659e6ee4ecb563c2f5a7"
        },
        {
            "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
            "size": 28748,
            "digest": "sha256:021db240dfccf5a1aff19507d17c0177e5888e518acf295b52204b1825e8b7ee"
        }
    ]
}
```
出力:  

```
{
    "image": {
        "registryId": "130757420319",
        "repositoryName": "hello-world",
        "imageId": {
            "imageDigest": "sha256:8ece96b74f87652876199d83bd107d0435a196133af383ac54cb82b6cc5283ae",
            "imageTag": "2019.08"
        },
        "imageManifest": "{\n  \"schemaVersion\": 2,\n  \"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\",\n  \"config\": {\n    \"mediaType\": \"application/vnd.docker.container.image.v1+json\",\n    \"size\": 5695,\n    \"digest\": \"sha256:cea5fe7701b7db3dd1c372f3cea6f43cdda444fcc488f530829145e426d8b980\"\n  },\n  \"layers\": [\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 39096921,\n      \"digest\": \"sha256:d8868e50ac4c7104d2200d42f432b661b2da8c1e417ccfae217e6a1e04bb9295\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 57938,\n      \"digest\": \"sha256:83251ac64627fc331584f6c498b3aba5badc01574e2c70b2499af3af16630eed\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 423,\n      \"digest\": \"sha256:589bba2f1b36ae56f0152c246e2541c5aa604b058febfcf2be32e9a304fec610\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 680,\n      \"digest\": \"sha256:d62ecaceda3964b735cdd2af613d6bb136a52c1da0838b2ff4b4dab4212bcb1c\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 162,\n      \"digest\": \"sha256:6d93b41cfc6bf0d2522b7cf61588de4cd045065b36c52bd3aec2ba0622b2b22b\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 28268840,\n      \"digest\": \"sha256:6986b4d4c07932c680b3587f2eac8b0e013568c003cc23b04044628a5c5e599f\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 35369152,\n      \"digest\": \"sha256:8c5ec60f10102dc8da0649d866c7c2f706e459d0bdc25c83ad2de86f4996c276\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 155,\n      \"digest\": \"sha256:cde50b1c594539c5f67cbede9aef95c9ae321ccfb857f7b251b45b84198adc85\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 28737,\n      \"digest\": \"sha256:2e102807ab72a73fc9abf53e8c50e421bdc337a0a8afcb242176edeec65977e4\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 190,\n      \"digest\": \"sha256:fc379bbd5ed37808772bef016553a297356c59b8f134659e6ee4ecb563c2f5a7\"\n    },\n    {\n      \"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\",\n      \"size\": 28748,\n      \"digest\": \"sha256:021db240dfccf5a1aff19507d17c0177e5888e518acf295b52204b1825e8b7ee\"\n    }\n  ]\n}\n"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/put-image.html)」を参照してください。

### `put-lifecycle-policy`
<a name="ecr_PutLifeCyclePolicy_cli_2_topic"></a>

次のコード例は、`put-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシーを作成するには**  
次の `put-lifecycle-policy` 例では、アカウントのデフォルトレジストリに指定されたリポジトリのライフサイクルポリシーを作成します。  

```
aws ecr put-lifecycle-policy \
    --repository-name "project-a/amazon-ecs-sample" \
    --lifecycle-policy-text "file://policy.json"
```
`policy.json` の内容:  

```
{
   "rules": [
       {
           "rulePriority": 1,
           "description": "Expire images older than 14 days",
           "selection": {
               "tagStatus": "untagged",
               "countType": "sinceImagePushed",
               "countUnit": "days",
               "countNumber": 14
           },
           "action": {
               "type": "expire"
           }
       }
   ]
}
```
出力:  

```
{
   "registryId": "<aws_account_id>",
   "repositoryName": "project-a/amazon-ecs-sample",
   "lifecyclePolicyText": "{\"rules\":[{\"rulePriority\":1,\"description\":\"Expire images older than 14 days\",\"selection\":{\"tagStatus\":\"untagged\",\"countType\":\"sinceImagePushed\",\"countUnit\":\"days\",\"countNumber\":14},\"action\":{\"type\":\"expire\"}}]}"
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[ライフサイクルポリシー](https://docs.aws.amazon.com/AmazonECR/latest/userguide/LifecyclePolicies.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutLifeCyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/put-life-cycle-policy.html)」を参照してください。

### `set-repository-policy`
<a name="ecr_SetRepositoryPolicy_cli_2_topic"></a>

次のコード例は、`set-repository-policy` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのリポジトリポリシーを設定するには**  
次の `set-repository-policy` の例では、ファイルに含まれるリポジトリポリシーを `cluster-autoscaler` リポジトリにアタッチします。  

```
aws ecr set-repository-policy \
    --repository-name cluster-autoscaler \
    --policy-text file://my-policy.json
```
`my-policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement" : [
        {
            "Sid" : "allow public pull",
            "Effect" : "Allow",
            "Principal" : "*",
            "Action" : [
                "ecr:BatchCheckLayerAvailability",
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer"
            ]
        }
    ]
}
```
出力:  

```
{
    "registryId": "012345678910",
    "repositoryName": "cluster-autoscaler",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"allow public pull\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : \"*\",\n    \"Action\" : [ \"ecr:BatchCheckLayerAvailability\", \"ecr:BatchGetImage\", \"ecr:GetDownloadUrlForLayer\" ]\n  } ]\n}"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetRepositoryPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/set-repository-policy.html)」を参照してください。

### `start-image-scan`
<a name="ecr_StartImageScan_cli_2_topic"></a>

次のコード例は、`start-image-scan` を使用する方法を示しています。

**AWS CLI**  
**イメージ脆弱性スキャンを開始するには**  
次の `start-image-scan` 例では、イメージスキャンを開始し、指定されたリポジトリのイメージダイジェストで指定します。  

```
aws ecr start-image-scan \
    --repository-name sample-repo \
    --image-id imageDigest=sha256:74b2c688c700ec95a93e478cdb959737c148df3fbf5ea706abe0318726e885e6
```
出力:  

```
{
   "registryId": "012345678910",
   "repositoryName": "sample-repo",
   "imageId": {
       "imageDigest": "sha256:74b2c688c700ec95a93e478cdb959737c148df3fbf5ea706abe0318726e885e6"
   },
   "imageScanStatus": {
       "status": "IN_PROGRESS"
   }
}
```
詳細については、「*Amazon ECR ユーザーガイド*」の「[イメージスキャン](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartImageScan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/start-image-scan.html)」を参照してください。

### `start-lifecycle-policy-preview`
<a name="ecr_StartLifecyclePolicyPreview_cli_2_topic"></a>

次のコード例は、`start-lifecycle-policy-preview` を使用する方法を示しています。

**AWS CLI**  
**ライフサイクルポリシーのプレビューを作成するには**  
次の `start-lifecycle-policy-preview` の例では、指定されたリポジトリに対して JSON ファイルで定義されたライフサイクルポリシーのプレビューを作成します。  

```
aws ecr start-lifecycle-policy-preview \
    --repository-name "project-a/amazon-ecs-sample" \
    --lifecycle-policy-text "file://policy.json"
```
`policy.json` の内容:  

```
{
   "rules": [
       {
           "rulePriority": 1,
           "description": "Expire images older than 14 days",
           "selection": {
               "tagStatus": "untagged",
               "countType": "sinceImagePushed",
               "countUnit": "days",
               "countNumber": 14
           },
           "action": {
               "type": "expire"
           }
       }
   ]
}
```
出力:  

```
{
   "registryId": "012345678910",
   "repositoryName": "project-a/amazon-ecs-sample",
   "lifecyclePolicyText": "{\n    \"rules\": [\n        {\n            \"rulePriority\": 1,\n            \"description\": \"Expire images older than 14 days\",\n            \"selection\": {\n                \"tagStatus\": \"untagged\",\n                \"countType\": \"sinceImagePushed\",\n                \"countUnit\": \"days\",\n                \"countNumber\": 14\n            },\n            \"action\": {\n                \"type\": \"expire\"\n            }\n        }\n    ]\n}\n",
   "status": "IN_PROGRESS"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartLifecyclePolicyPreview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/start-lifecycle-policy-preview.html)」を参照してください。

### `tag-resource`
<a name="ecr_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リポジトリにタグを付けるには**  
次の `tag-resource` の例では、`hello-world` レポジトリのキー `Stage` と値 `Integ` でタグを設定します。  

```
aws ecr tag-resource \
    --resource-arn arn:aws:ecr:us-west-2:012345678910:repository/hello-world \
    --tags Key=Stage,Value=Integ
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ecr_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リポジトリのタグを解除するには**  
次の `untag-resource` の例では、`Stage` というキーのタグを `hello-world` リポジトリから削除します。  

```
aws ecr untag-resource \
    --resource-arn arn:aws:ecr:us-west-2:012345678910:repository/hello-world \
    --tag-keys Stage
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/untag-resource.html)」を参照してください。

### `upload-layer-part`
<a name="ecr_UploadLayerPart_cli_2_topic"></a>

次のコード例は、`upload-layer-part` を使用する方法を示しています。

**AWS CLI**  
**レイヤーパートをアップロードするには**  
以下の `upload-layer-part` は、イメージレイヤーパートを `layer-test` リポジトリにアップロードします。  

```
aws ecr upload-layer-part \
    --repository-name layer-test \
    --upload-id 6cb64b8a-9378-0e33-2ab1-b780fab8a9e9 \
    --part-first-byte 0 \
    --part-last-byte 8323314 \
    --layer-part-blob file:///var/lib/docker/image/overlay2/layerdb/sha256/ff986b10a018b48074e6d3a68b39aad8ccc002cdad912d4148c0f92b3729323e/layer.b64
```
出力:  

```
{
    "uploadId": "6cb64b8a-9378-0e33-2ab1-b780fab8a9e9",
    "registryId": "012345678910",
    "lastByteReceived": 8323314,
    "repositoryName": "layer-test"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadLayerPart](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr/upload-layer-part.html)」を参照してください。

# を使用した Amazon ECR Public の例 AWS CLI
<a name="cli_2_ecr-public_code_examples"></a>

次のコード例は、Amazon ECR Public AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-delete-image`
<a name="ecr-public_BatchDeleteImage_cli_2_topic"></a>

次のコード例は、`batch-delete-image` を使用する方法を示しています。

**AWS CLI**  
**例 1: イメージダイジェスト ID を使用してイメージを削除するために、パブリックレジストリ内のリポジトリからイメージとそのすべてのタグが削除される**  
次の `batch-delete-image` の例では、イメージダイジェストを指定してイメージを削除します。  

```
aws ecr-public batch-delete-image \
    --repository-name project-a/nginx-web-app \
    --image-ids imageDigest=sha256:b1f9deb5fe3711a3278379ebbcaefbc5d70a2263135db86bd27a0dae150546c2
```
出力:  

```
{
"imageIds": [
    {
        "imageDigest": "sha256:b1f9deb5fe3711a3278379ebbcaefbc5d70a2263135db86bd27a0dae150546c2",
        "imageTag": "latest"
    }
],
"failures": []
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリからのイメージの削除](https://docs.aws.amazon.com/AmazonECR/latest/public/public-image-delete.html)」を参照してください。  
**例 2: リポジトリから削除するイメージに関連付けられているタグを指定してイメージを削除するには**  
次の `batch-delete-image` の例では、パブリックレジストリ内の `project-a/nginx-web-app` という名前のイメージリポジトリに関連付けられているタグを指定してイメージを削除します。タグが 1 つしかない場合、このコマンドを実行すると、イメージが削除されます。同じイメージに複数のタグがある場合は、1 つのタグを指定すると、そのタグのみがリポジトリから削除され、イメージ自体は削除されません。  

```
aws ecr-public batch-delete-image \
    --repository-name project-a/nginx-web-app \
    --image-ids imageTag=_temp
```
出力:  

```
{
    "imageIds": [
        {
            "imageDigest": "sha256:f7a86a0760e2f8d7eff07e515fc87bf4bac45c35376c06f9a280f15ecad6d7e0",
            "imageTag": "_temp"
        }
    ],
    "failures": []
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリからのイメージの削除](https://docs.aws.amazon.com/AmazonECR/latest/public/public-image-delete.html)」を参照してください。  
**例 3: パブリックレジストリ内のリポジトリに対するリクエストで複数のイメージタグまたはイメージダイジェストを指定して、複数のイメージを削除するには**  
次の `batch-delete-image` の例では、リクエストで複数のイメージタグまたはイメージダイジェストを指定することで、project-a/nginx-web-app という名前のリポジトリから複数のイメージを削除します。  

```
aws ecr-public batch-delete-image \
    --repository-name project-a/nginx-web-app \
    --image-ids imageTag=temp2.0  imageDigest=sha256:47ba980bc055353d9c0af89b1894f68faa43ca93856917b8406316be86f01278
```
出力:  

```
{
     "imageIds": [
         {
             "imageDigest": "sha256:47ba980bc055353d9c0af89b1894f68faa43ca93856917b8406316be86f01278"
         },
         {
             "imageDigest": "sha256:f7a86a0760e2f8d7eff07e515fc87bf4bac45c35376c06f9a280f15ecad6d7e0",
             "imageTag": "temp2.0"
         }
     ],
     "failures": []
 }
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリからのイメージの削除](https://docs.aws.amazon.com/AmazonECR/latest/public/public-image-delete.html)」を参照してください。  
**例 4: registry-id と imagedigest ID を使用してクロス AWS アカウントのイメージを削除するには、イメージとそのすべてのタグがパブリックレジストリのリポジトリ内で削除されます。**  
次の`batch-delete-image`例では、クロス AWS アカウントでイメージダイジェストを指定してイメージを削除します。  

```
aws ecr-public batch-delete-image \
    --registry-id 123456789098 \
    --repository-name project-a/nginx-web-app \
    --image-ids imageDigest=sha256:b1f9deb5fe3711a3278379ebbcaefbc5d70a2263135db86bd27a0dae150546c2 \
    --region us-east-1
```
出力:  

```
{
    "imageIds": [
        {
            "imageDigest": "sha256:b1f9deb5fe3711a3278379ebbcaefbc5d70a2263135db86bd27a0dae150546c2",
            "imageTag": "temp2.0"
        }
    ],
    "failures": []
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリからのイメージの削除](https://docs.aws.amazon.com/AmazonECR/latest/public/public-image-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDeleteImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/batch-delete-image.html)」を参照してください。

### `create-repository`
<a name="ecr-public_CreateRepository_cli_2_topic"></a>

次のコード例は、`create-repository` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックレジストリにリポジトリを作成するには**  
次の `create-repository` の例では、パブリックレジストリに project-a/nginx-web-app という名前のリポジトリを作成します。  

```
aws ecr-public create-repository \
    --repository-name project-a/nginx-web-app
```
出力:  

```
{
    "repository": {
        "repositoryArn": "arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app",
        "registryId": "123456789012",
        "repositoryName": "project-a/nginx-web-app",
        "repositoryUri": "public.ecr.aws/public-registry-custom-alias/project-a/nginx-web-app",
        "createdAt": "2024-07-01T21:08:55.131000+00:00"
    },
    "catalogData": {}
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリの作成](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-create.html)」を参照してください。  
**例 2: リポジトリ内のイメージと互換性があるリポジトリ、システム、およびオペレーションアーキテクチャの内容を簡単に記述して、パブリックレジストリにリポジトリを作成するには**  
次の `create-repository` の例では、パブリックレジストリに project-a/nginx-web-app という名前のリポジトリを作成し、そのリポジトリの内容について、さらに、そのリポジトリ内のイメージと互換性のあるシステムとオペレーティングアーキテクチャについて、簡単な説明を追加します。  

```
aws ecr-public create-repository \
    --repository-name project-a/nginx-web-app \
    --catalog-data 'description=My project-a ECR Public Repository,architectures=ARM,ARM 64,x86,x86-64,operatingSystems=Linux'
```
出力:  

```
{
    "repository": {
        "repositoryArn": "arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app",
        "registryId": "123456789012",
        "repositoryName": "project-a/nginx-web-app",
        "repositoryUri": "public.ecr.aws/public-registry-custom-alias/project-a/nginx-web-app",
        "createdAt": "2024-07-01T21:23:20.455000+00:00"
    },
    "catalogData": {
        "description": "My project-a ECR Public Repository",
        "architectures": [
            "ARM",
            "ARM 64",
            "x86",
            "x86-64"
        ],
        "operatingSystems": [
            "Linux"
        ]
    }
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリの作成](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-create.html)」を参照してください。  
**例 3: logoImageBlob、aboutText、usageText、タグ情報と一緒にパブリックレジストリにリポジトリを作成するには**  
次の `create-repository` の例では、project-a/nginx-web-app という名前のリポジトリを、logoImageBlob、aboutText、usageText、タグ情報と一緒にパブリックレジストリに作成します。  

```
aws ecr-public create-repository \
    --cli-input-json file://myfile.json
```
`myfile.json` の内容:  

```
{
    "repositoryName": "project-a/nginx-web-app",
    "catalogData": {
        "description": "My project-a ECR Public Repository",
        "architectures": [
            "ARM",
            "ARM 64",
            "x86",
            "x86-64"
        ],
        "operatingSystems": [
            "Linux"
        ],
        "logoImageBlob": "iVBORw0KGgoA<<truncated-for-better-reading>>ErkJggg==",
        "aboutText": "## Quick reference\n\nMaintained by: [the Amazon Linux Team](https://github.com/aws/amazon-linux-docker-images)\n\nWhere to get help: [the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://dockr.ly/slack), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)\n\n## Supported tags and respective `dockerfile` links\n\n* [`2.0.20200722.0`, `2`, `latest`](https://github.com/amazonlinux/container-images/blob/03d54f8c4d522bf712cffd6c8f9aafba0a875e78/Dockerfile)\n* [`2.0.20200722.0-with-sources`, `2-with-sources`, `with-sources`](https://github.com/amazonlinux/container-images/blob/1e7349845e029a2e6afe6dc473ef17d052e3546f/Dockerfile)\n* [`2018.03.0.20200602.1`, `2018.03`, `1`](https://github.com/amazonlinux/container-images/blob/f10932e08c75457eeb372bf1cc47ea2a4b8e98c8/Dockerfile)\n* [`2018.03.0.20200602.1-with-sources`, `2018.03-with-sources`, `1-with-sources`](https://github.com/amazonlinux/container-images/blob/8c9ee491689d901aa72719be0ec12087a5fa8faf/Dockerfile)\n\n## What is Amazon Linux?\n\nAmazon Linux is provided by Amazon Web Services (AWS). It is designed to provide a stable, secure, and high-performance execution environment for applications running on Amazon EC2. The full distribution includes packages that enable easy integration with AWS, including launch configuration tools and many popular AWS libraries and tools. AWS provides ongoing security and maintenance updates to all instances running Amazon Linux.\n\nThe Amazon Linux container image contains a minimal set of packages. To install additional packages, [use `yum`](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/managing-software.html).\n\nAWS provides two versions of Amazon Linux: [Amazon Linux 2](https://aws.amazon.com/amazon-linux-2/) and [Amazon Linux AMI](https://aws.amazon.com/amazon-linux-ami/).\n\nFor information on security updates for Amazon Linux, please refer to [Amazon Linux 2 Security Advisories](https://alas.aws.amazon.com/alas2.html) and [Amazon Linux AMI Security Advisories](https://alas.aws.amazon.com/). Note that Docker Hub's vulnerability scanning for Amazon Linux is currently based on RPM versions, which does not reflect the state of backported patches for vulnerabilities.\n\n## Where can I run Amazon Linux container images?\n\nYou can run Amazon Linux container images in any Docker based environment. Examples include, your laptop, in Amazon EC2 instances, and Amazon ECS clusters.\n\n## License\n\nAmazon Linux is available under the [GNU General Public License, version 2.0](https://github.com/aws/amazon-linux-docker-images/blob/master/LICENSE). Individual software packages are available under their own licenses; run `rpm -qi [package name]` or check `/usr/share/doc/[package name]-*` and `/usr/share/licenses/[package name]-*` for details.\n\nAs with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).\n\nSome additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `amazonlinux/` directory](https://github.com/docker-library/repo-info/tree/master/repos/amazonlinux).\n\n## Security\n\nFor information on security updates for Amazon Linux, please refer to [Amazon Linux 2 Security Advisories](https://alas.aws.amazon.com/alas2.html) and [Amazon Linux AMI Security Advisories](https://alas.aws.amazon.com/). Note that Docker Hub's vulnerability scanning for Amazon Linux is currently based on RPM versions, which does not reflect the state of backported patches for vulnerabilities.",
        "usageText": "## Supported architectures\n\namd64, arm64v8\n\n## Where can I run Amazon Linux container images?\n\nYou can run Amazon Linux container images in any Docker based environment. Examples include, your laptop, in Amazon EC2 instances, and ECS clusters.\n\n## How do I install a software package from Extras repository in Amazon Linux 2?\n\nAvailable packages can be listed with the `amazon-linux-extras` command. Packages can be installed with the `amazon-linux-extras install <package>` command. Example: `amazon-linux-extras install rust1`\n\n## Will updates be available for Amazon Linux containers?\n\nSimilar to the Amazon Linux images for Amazon EC2 and on-premises use, Amazon Linux container images will get ongoing updates from Amazon in the form of security updates, bug fix updates, and other enhancements. Security bulletins for Amazon Linux are available at https://alas.aws.amazon.com/\n\n## Will AWS Support the current version of Amazon Linux going forward?\n\nYes; in order to avoid any disruption to your existing applications and to facilitate migration to Amazon Linux 2, AWS will provide regular security updates for Amazon Linux 2018.03 AMI and container image for 2 years after the final LTS build is announced. You can also use all your existing support channels such as AWS Support and Amazon Linux Discussion Forum to continue to submit support requests."
    },
    "tags": [
        {
            "Key": "Name",
            "Value": "project-a/nginx-web-app"
        },
        {
            "Key": "Environment",
            "Value": "Prod"
        }
    ]
}
```
出力:  

```
{
    "repository": {
        "repositoryArn": "arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app",
        "registryId": "123456789012",
        "repositoryName": "project-a/nginx-web-app",
        "repositoryUri": "public.ecr.aws/public-registry-custom-alias/project-a/nginx-web-app",
        "createdAt": "2024-07-01T21:53:05.749000+00:00"
    },
    "catalogData": {
        "description": "My project-a ECR Public Repository",
        "architectures": [
            "ARM",
            "ARM 64",
            "x86",
            "x86-64"
        ],
        "operatingSystems": [
            "Linux"
        ],
        "logoUrl": "https://d3g9o9u8re44ak.cloudfront.net/logo/23861450-4b9b-403c-9a4c-7aa0ef140bb8/2f9bf5a7-a32f-45b4-b5cd-c5770a35e6d7.png",
        "aboutText": "## Quick reference\n\nMaintained by: [the Amazon Linux Team](https://github.com/aws/amazon-linux-docker-images)\n\nWhere to get help: [the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://dockr.ly/slack), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)\n\n## Supported tags and respective `dockerfile` links\n\n* [`2.0.20200722.0`, `2`, `latest`](https://github.com/amazonlinux/container-images/blob/03d54f8c4d522bf712cffd6c8f9aafba0a875e78/Dockerfile)\n* [`2.0.20200722.0-with-sources`, `2-with-sources`, `with-sources`](https://github.com/amazonlinux/container-images/blob/1e7349845e029a2e6afe6dc473ef17d052e3546f/Dockerfile)\n* [`2018.03.0.20200602.1`, `2018.03`, `1`](https://github.com/amazonlinux/container-images/blob/f10932e08c75457eeb372bf1cc47ea2a4b8e98c8/Dockerfile)\n* [`2018.03.0.20200602.1-with-sources`, `2018.03-with-sources`, `1-with-sources`](https://github.com/amazonlinux/container-images/blob/8c9ee491689d901aa72719be0ec12087a5fa8faf/Dockerfile)\n\n## What is Amazon Linux?\n\nAmazon Linux is provided by Amazon Web Services (AWS). It is designed to provide a stable, secure, and high-performance execution environment for applications running on Amazon EC2. The full distribution includes packages that enable easy integration with AWS, including launch configuration tools and many popular AWS libraries and tools. AWS provides ongoing security and maintenance updates to all instances running Amazon Linux.\n\nThe Amazon Linux container image contains a minimal set of packages. To install additional packages, [use `yum`](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/managing-software.html).\n\nAWS provides two versions of Amazon Linux: [Amazon Linux 2](https://aws.amazon.com/amazon-linux-2/) and [Amazon Linux AMI](https://aws.amazon.com/amazon-linux-ami/).\n\nFor information on security updates for Amazon Linux, please refer to [Amazon Linux 2 Security Advisories](https://alas.aws.amazon.com/alas2.html) and [Amazon Linux AMI Security Advisories](https://alas.aws.amazon.com/). Note that Docker Hub's vulnerability scanning for Amazon Linux is currently based on RPM versions, which does not reflect the state of backported patches for vulnerabilities.\n\n## Where can I run Amazon Linux container images?\n\nYou can run Amazon Linux container images in any Docker based environment. Examples include, your laptop, in Amazon EC2 instances, and Amazon ECS clusters.\n\n## License\n\nAmazon Linux is available under the [GNU General Public License, version 2.0](https://github.com/aws/amazon-linux-docker-images/blob/master/LICENSE). Individual software packages are available under their own licenses; run `rpm -qi [package name]` or check `/usr/share/doc/[package name]-*` and `/usr/share/licenses/[package name]-*` for details.\n\nAs with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).\n\nSome additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `amazonlinux/` directory](https://github.com/docker-library/repo-info/tree/master/repos/amazonlinux).\n\n## Security\n\nFor information on security updates for Amazon Linux, please refer to [Amazon Linux 2 Security Advisories](https://alas.aws.amazon.com/alas2.html) and [Amazon Linux AMI Security Advisories](https://alas.aws.amazon.com/). Note that Docker Hub's vulnerability scanning for Amazon Linux is currently based on RPM versions, which does not reflect the state of backported patches for vulnerabilities.",
        "usageText": "## Supported architectures\n\namd64, arm64v8\n\n## Where can I run Amazon Linux container images?\n\nYou can run Amazon Linux container images in any Docker based environment. Examples include, your laptop, in Amazon EC2 instances, and ECS clusters.\n\n## How do I install a software package from Extras repository in Amazon Linux 2?\n\nAvailable packages can be listed with the `amazon-linux-extras` command. Packages can be installed with the `amazon-linux-extras install <package>` command. Example: `amazon-linux-extras install rust1`\n\n## Will updates be available for Amazon Linux containers?\n\nSimilar to the Amazon Linux images for Amazon EC2 and on-premises use, Amazon Linux container images will get ongoing updates from Amazon in the form of security updates, bug fix updates, and other enhancements. Security bulletins for Amazon Linux are available at https://alas.aws.amazon.com/\n\n## Will AWS Support the current version of Amazon Linux going forward?\n\nYes; in order to avoid any disruption to your existing applications and to facilitate migration to Amazon Linux 2, AWS will provide regular security updates for Amazon Linux 2018.03 AMI and container image for 2 years after the final LTS build is announced. You can also use all your existing support channels such as AWS Support and Amazon Linux Discussion Forum to continue to submit support requests."
    }
}
```
詳細については、「*Amazon ECR Public ユーザーガイド*」の「[パブリックリポジトリの作成](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-create.html)」および「*Amazon ECR Public ユーザーガイド*」の「[リポジトリカタログデータ](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-catalog-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/create-repository.html)」を参照してください。

### `delete-repository-policy`
<a name="ecr-public_DeleteRepositoryPolicy_cli_2_topic"></a>

次のコード例は、`delete-repository-policy` を使用する方法を示しています。

**AWS CLI**  
**パブリックレジストリのリポジトリに関するポリシーを削除するには**  
次の の`delete-repository-policy`例では、 AWS アカウントの ECR Public リポジトリのリポジトリポリシーを削除します。  

```
aws ecr-public delete-repository-policy \
     --repository-name project-a/nginx-web-app \
     --region us-east-1
```
出力:  

```
{
    "registryId": "123456789012",
    "repositoryName": "project-a/nginx-web-app",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"AllowPush\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : {\n      \"AWS\" : [ \"arn:aws:iam:"123456789012":user/eksuser1\", \"arn:aws:iam:"123456789012":user/admin\" ]\n    },\n    \"Action\" : [ \"ecr-public:BatchCheckLayerAvailability\", \"ecr-public:PutImage\", \"ecr-public:InitiateLayerUpload\", \"ecr-public:UploadLayerPart\", \"ecr-public:CompleteLayerUpload\" ]\n  } ]\n}"
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリのポリシーステートメントの削除](https://docs.aws.amazon.com/AmazonECR/latest/public/delete-public-repository-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRepositoryPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/delete-repository-policy.html)」を参照してください。

### `delete-repository`
<a name="ecr-public_DeleteRepository_cli_2_topic"></a>

次のコード例は、`delete-repository` を使用する方法を示しています。

**AWS CLI**  
**パブリックレジストリのリポジトリを削除するには**  
次の `delete-repository` の例では、パブリックレジストリから `project-a/nginx-web-app` という名前のリポジトリを削除します。  

```
aws ecr-public delete-repository \
    --repository-name project-a/nginx-web-app
```
出力:  

```
{
    "repository": {
        "repositoryArn": "arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app",
        "registryId": "123456789012",
        "repositoryName": "project-a/nginx-web-app",
        "repositoryUri": "public.ecr.aws/public-registry-custom-alias/project-a/nginx-web-app",
        "createdAt": "2024-07-01T22:14:50.103000+00:00"
    }
}
```
詳細については、[Amazon ECR Public](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-delete.html) の「*パブリックリポジトリの削除*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/delete-repository.html)」を参照してください。

### `describe-image-tags`
<a name="ecr-public_DescribeImageTags_cli_2_topic"></a>

次のコード例は、`describe-image-tags` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックリポジトリのイメージタグの詳細を取得するには**  
次の `describe-image-tags` の例では、`project-a/nginx-web-app` サンプルリポジトリ内のイメージタグについて説明します。  

```
aws ecr-public describe-image-tags \
    --repository-name project-a/nginx-web-app \
    --region us-east-1
```
出力:  

```
{
    "imageTagDetails": [
        {
            "imageTag": "latest",
            "createdAt": "2024-07-10T22:29:00-05:00",
            "imageDetail": {
                "imageDigest": "sha256:b1f9deb5fe3711a3278379ebbcaefbc5d70a2263135db86bd27a0dae150546c2",
                "imageSizeInBytes": 121956548,
                "imagePushedAt": "2024-07-10T22:29:00-05:00",
                "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
                "artifactMediaType": "application/vnd.docker.container.image.v1+json"
            }
        }
    ]
}
```
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeImageTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/describe-image-tags.html)」を参照してください。

### `describe-images`
<a name="ecr-public_DescribeImages_cli_2_topic"></a>

次のコード例は、`describe-images` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックレジストリリポジトリ内のイメージの詳細を取得するには**  
次の `describe-images` の例では、パブリックレジストリ内の `project-a/nginx-web-app` という名前のリポジトリ内の imagesDetails の詳細を取得します。  

```
aws ecr-public describe-images \
    --repository-name project-a/nginx-web-app \
    --region us-east-1
```
出力:  

```
{
    "imageDetails": [
        {
            "registryId": "123456789012",
            "repositoryName": "project-a/nginx-web-app",
            "imageDigest": "sha256:0d8c93e72e82fa070d49565c00af32abbe8ddfd7f75e39f4306771ae0628c7e8",
            "imageTags": [
                "temp1.0"
            ],
            "imageSizeInBytes": 123184716,
            "imagePushedAt": "2024-07-23T11:32:49-05:00",
            "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
            "artifactMediaType": "application/vnd.docker.container.image.v1+json"
        },
        {
            "registryId": "123456789012",
            "repositoryName": "project-a/nginx-web-app",
            "imageDigest": "sha256:b1f9deb5fe3711a3278379ebbcaefbc5d70a2263135db86bd27a0dae150546c2",
            "imageTags": [
                "temp2.0"
            ],
            "imageSizeInBytes": 121956548,
            "imagePushedAt": "2024-07-23T11:39:38-05:00",
            "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
            "artifactMediaType": "application/vnd.docker.container.image.v1+json"
        },
        {
            "registryId": "123456789012",
            "repositoryName": "project-a/nginx-web-app",
            "imageDigest": "sha256:f7a86a0760e2f8d7eff07e515fc87bf4bac45c35376c06f9a280f15ecad6d7e0",
            "imageTags": [
                "temp3.0",
                "latest"
            ],
            "imageSizeInBytes": 232108879,
            "imagePushedAt": "2024-07-22T00:54:34-05:00",
            "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
            "artifactMediaType": "application/vnd.docker.container.image.v1+json"
        }
    ]
}
```
詳細については、*Amazon ECR Public* の「[パブリックリポジトリのイメージの詳細を取得する](https://docs.aws.amazon.com/AmazonECR/latest/public/docker-push-multi-architecture-image.html)」を参照してください。  
**例 2: リポジトリからイメージを imageTags と imagePushedAt でソートして詳細を取得するには**  
次の `describe-images` の例では、パブリックレジストリ内の project-a/nginx-web-app という名前のリポジトリ内のイメージの詳細を取得します。  

```
aws ecr-public describe-images \
    --repository-name project-a/nginx-web-app \
    --query 'sort_by(imageDetails,& imagePushedAt)[*].imageTags[*]' \
    --output text
```
出力:  

```
temp3.0 latest
temp1.0
temp2.0
```
**例 3: リポジトリにプッシュされた最後の 2 つのイメージタグを生成するためにリポジトリからイメージの詳細を取得するには**  
次の `describe-images` の例では、パブリックレジストリ内の `project-a/nginx-web-app` という名前のリポジトリからイメージタグの詳細を取得し、結果に対してクエリを実行して最初の 2 つのレコードのみを表示します。  

```
aws ecr-public describe-images \
    --repository-name project-a/nginx-web-app  \
    --query 'sort_by(imageDetails,& imagePushedAt)[*].imageTags[*] | [0:2]' \
    --output text
```
出力:  

```
temp3.0 latest
temp1.0
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/describe-images.html)」を参照してください。

### `describe-registries`
<a name="ecr-public_DescribeRegistries_cli_2_topic"></a>

次のコード例は、`describe-registries` を使用する方法を示しています。

**AWS CLI**  
**パブリックレジストリ内のすべてのレジストリの詳細を取得するには**  
次の `describe-registries` の例では、アカウントのすべてのレジストリの詳細を取得します。  

```
aws ecr-public describe-registries
```
出力:  

```
{
 "registries": [
     {
         "registryId": "123456789012",
         "registryArn": "arn:aws:ecr-public::123456789012:registry/123456789012",
         "registryUri": "public.ecr.aws/publicregistrycustomalias",
         "verified": false,
         "aliases": [
             {
                 "name": "publicregistrycustomalias",
                 "status": "ACTIVE",
                 "primaryRegistryAlias": true,
                 "defaultRegistryAlias": true
             }
         ]
     }
     ]
 }
```
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeRegistries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/describe-registries.html)」を参照してください。

### `describe-repository`
<a name="ecr-public_DescribeRepository_cli_2_topic"></a>

次のコード例は、`describe-repository` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックレジストリ内のリポジトリの詳細を取得するには**  
次の `describe-repositories` の例では、パブリックレジストリ内の `project-a/nginx-web-app` という名前のリポジトリの詳細を取得します。  

```
aws ecr-public describe-repositories \
    --repository-name project-a/nginx-web-app
```
出力:  

```
{
    "repositories": [
        {
            "repositoryArn": "arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app",
            "registryId": "123456789012",
            "repositoryName": "project-a/nginx-web-app",
            "repositoryUri": "public.ecr.aws/public-registry-custom-alias/project-a/nginx-web-app",
            "createdAt": "2024-07-07T00:07:56.526000-05:00"
        }
    ]
}
```
**例 2: パブリックレジストリ内のすべてのリポジトリの詳細を表形式で表示するには**  
次の `describe-repositories` の例では、パブリックレジストリ内のすべてのリポジトリの詳細を取得し、リポジトリ名を表形式で出力します。  

```
aws ecr-public describe-repositories \
    --region us-east-1 \
    --output table \
    --query "repositories[*].repositoryName"
```
出力:  

```
-----------------------------
|   DescribeRepositories    |
+---------------------------+
|  project-a/nginx-web-app  |
|  nginx                    |
|  myfirstrepo1             |
|  helm-test-chart          |
|  test-ecr-public          |
|  nginx-web-app            |
|  sample-repo              |
+---------------------------+
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRepository](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/describe-repository.html)」を参照してください。

### `get-authorization-token`
<a name="ecr-public_GetAuthorizationToken_cli_2_topic"></a>

次のコード例は、`get-authorization-token` を使用する方法を示しています。

**AWS CLI**  
**例 1: IAM プリンシパルがアクセスできる Amazon ECR パブリックレジストリの認可トークンを取得するには**  
次の の`get-authorization-token`例では、 CLI AWS を使用して認可トークンを取得し、環境変数に設定します。  

```
aws ecr-public get-authorization-token \
    --region us-east-1
```
出力:  

```
{
    "authorizationData": {
        "authorizationToken": "QVdTOmV5SndZWGxzYjJKJFHDSFKJHERWUY65IOU36TRYEGFNSDLRIUOTUYTHJKLDFGOcmFUQk9OSFV2UVV4a0x6Sm1ZV0Z6TDFndlZtUjJSVmgxVEVObU9IZEdTWEZxU210c1JUQm5RWGxOUVV4NlNFUnROWG92ZWtGbWJFUjRkbWMyV0U5amFpczRNWGxTVkM5Tk5qWkVUM2RDYm05TVJqSkxjV3BsUVZvMmFYSm5iV1ZvVFdGSVRqVlFMMHN4VnpsTGVXbDFRWGRoTmpsbWFuQllhbVl6TkdGaGMwUjJha2xsYUhscWRscHZTRUpFVkVnNVQwNUdOVFpPY2xZclVFNVFVWGRSVFZvd04xUkhjVGxZZFVkQ1ZFZHBPRUptUzBVclYxQldMMjVMVkRsd2VFVlNSa1EzTWpWSlIxRkVWakJGZFZOVWEzaFBSVk5FWWpSc1lWZHZWMHBSYmxaMlJYWmhZekpaWVVOeFppdFlUa2xKU1RCdFUwdElVbXRJYlhGRk1WaFhNVTVRTkdwc1FYRlVNVWxZZUhkV05Xa3ZXWGd3ZUVZMWIyeE5VRU5QZEdSaWRHOU9lakZOZVdwTVZEUkNRVzlvYzNKSlpsRXhhR2cwWjJwRVJFVjNWalEzYjNCUmRIcEZUR1pYU1Rsc1kxSlNNbU5hUW5wRE1tOUpRMHR5Y1hkeGNXNDVMMmx4Um5GUlVGQnhjMVpQZG5WYUswOW9SQ3RPY0hwSlRsUk5lVXQyY0c1b1FsQjVZVEprVmtSdmJsQklOM05RU3pkNmQydERhMkZ5VmxSRmFVUndWVlE1ZGtsVWFXUkJWMFZEWVhoSFdXTk5VMXBTYTFreVRHZEVlVVZ0ZFRWRk4xTTVjRXBDUjBRMlYyTkdPVWhGWkVweVVGcEVaRFJxZUVablkwNXFaamh5YkVKWmJGSTNOVzFXSzFjdllXSTVTMWx2YUZacksxSnJWSFJ0Wml0T1NFSnpWVFZvV204eVFYbzFWRU5SYjNaR01Va3hPR3h2TWxkNVJsSmpUbTVSTjNjemJsUkdVRlZKVDBjeE9VeHlXVEpGVFRSS2NWbFdkVEJrV0VreFVsSktXbkpCVGtsMFdVZEJOMjltWjFFNGVHRktNbGRuWlVoUlNXNXdZV3A0VjI5M2FYZGljbE5tZGpkQ1ZYTmhOVFUyTDBzeVpteDBka0pUTVdkNGJ6TkxkSEJDYml0cE0waGhTbVpEZEZkQ00yOU1TM1pXTDNSVFlWaFpWelZXVWxjNFRXNXdhR3BhUmpoU1FuWnFkRlJMVW5abGRYRlNjVVJKZDBaSFpXUTRabEZUTUdOTVQwcFFkVXAyYjA5Tk9UaFlZMjEwVnpFMlpXdE9hMnBWV0hST1owUkpVV3R1VFU1dGJXWjNNVGc0VTAxUlNHZE9TbXRMY2tWYWJVeFljVVk0ZWpsTFdWWlRNbEZMVDJkMk1FaFBTMDl5YzJSM1NqTlplRGhUWVVOQlJGWnRlbkU1WTBKVFdqTktSR05WTkd0RGNEVjZNalJHVXpkVk9HTnVSa2xLUVd4SVJDODJXbGcyYldGemJVczJPRVp6TDBoNFMwWkRUMmdyYldGa1QwWjVhMlZQTm5SQ1l6QkpNbFpyVUhSaGVIbFVOR296VjFGVlQyMHpNeTlPWVVoSk1FdDBWalZFU2pneU5rcHNLemQxZDNwcVp6RlNja3AwVm10VU0yRnRWWGMzZDJnMFduSnFjVXczWTBjclNXeHFUVlUyVkZwWGNWY3ZSV0V6WW1oT2JIRklZVlJHU1RrMGEyOVJiMHBPVUhORk9FdERjbFJZY0daS2VVdHRZa2x5YjFORE4zSkJaWEJPZUU5eGR6WnhZMlY1WXprM1JtSkZhVFZFYkVFck5EUk9ZMWRyVEVNd1dqa2lMQ0prWVhSaGEyVjVJam9pWlhsS1VWSkdaMmxQYVVwV1ZXeENhVk5YVm14WFdFWk5VMjFrV21SRE9YaGFhWFF4VkhwS1MyTkljSHBVUms0MFlWaHNTbUpIYUhsWFZHdDZZVWhqZDFKRmFETldNbFYyWTJ0cmVVMUlTbHBWUjJONFRURlJNMDlHYUd4U01uaHVWRVJzUWxaV1pGZFJibkJLV1RCYU5HTXpUakpXTUhoWFRrWndhRTVyTVVwVFZFSkdWV3RzTUZaVVpEQlRSVGxyVkVkb2FGUlVVWHBaTVhCSFQxWmFOVlJxU20xaVZXUnVTM3BaTlZaV2NIcFdWMlJGVkcwMVRHSXdSakpXUnpoNlVsUm5kbUpzUmpGT2FUazFWVzFTY0dWR1FtOVdiVEZoVmpKc1NWRllhRmRTUkZwc1V6SkdSbUpWYkhCVlNFbDJWVzB4Ym1OVk1IWmFhelZ3WkZoa1FtVnFUa3BpTTJoTVRWVk9jMVo2V2t4aWJFWnJWRVUxVW1ONlp6QldWVFZPWW14c01sZFlZekprUjFwVFkxaE9kRnBXWkhaVFZWcGhWa2MxU2xWRlVtdFRiWE16WWpOVmVrNXFSa2RVTTJSd1QwaGtXbVJIVVhsbGJYQkRaRlp2ZGxvd1ZqWmlNbEl4Vkc1T2FtSldjRU5VU0ZVd1kwZDRjbU14WkhaVVYwNTRaRzV2TWxSVlVsQmpiSEJPVkc1VmVsZEZPVzVYYkVwWlUyNWtVbGRZWkZWaVdFWlNUVzF3VFZSSVFraE9XRnBwWVZoak0xUnJXak5OYm04eFpEQk9XbEZzYkhSTmEyaHpaRmRTUTJORVFUQlpWMk01VUZOSmMwbHJiRUpTUTBrMlNXNUZlbHA2U1RGVVZXeFVZekIwYVU5RWFEVmtiRVpzVVZWc2QxbHJWbmxOYW13MVZWaG9UazVzVWpWbFJHaDZZMjFHVkZVeFFubFZXRTVLVGpCMGFXSlZNWGhpUjBwTVlUSTVNRTVVYXpCTE0wVnlWakF4VG1WSE5VcGtSa0pRVld4V1UwOVdVWGhqTVc4eVZraFdlVnA2VGsxV01tUnhVV3Q0ZEdGcVRsUk5hMnN5V2tSV2FtUkdVakZqVm5CUFVrUlNjR0pHUm1GbGFscDRXV2x6Y2xFd1VYcGhSRnBZVmtaU2FVNXVSVFZYYlVaVFpXdHdkVmRZVGpaVGEyaDBWMnhDVlU0elZrWlRSRUpIVlVWa2MwNVlhRFZsUkVwelQwWkNSbE5WY0ZGWFNFWXhaVmMxVEZsVE9VeFdhMGt4V1ROS1Rrd3pXazFpYkhCdFVrUldWRlJHVlhaTmJVazBZbFZzUkV3d2N6UldSV2MxVDBWa05tSXpiM2hXVms1V1ZtMDFiRkZUT1hoUFJVcHpUMGRzU2xaSVJrTkxNVTVFWWtaa05WWnViRmRYVjJRd1RXcG5kMVJWUmpCa1JYQkdZVlYwZFZNeU1VVlpWVTVQV25wa1ExZHFVbE5sUjBaRVlWVTFXbVZwY3pSTE1HTTFVbFZGTlZwRll6UlRSMVoxVFcxb05XTnJkRUpWZWxsM1RETmplbUV4WkdGU1JsWm9ZVVpzZEdWR2JFTlVNblJYVkRCNE5HUXlkRXhaTWxKTlYxZDBWRTB5YUZwaFJsazFVMGR3Y0ZGVk9YaGxhekV6VVZRd09VbHVNRDBpTENKMlpYSnphVzl1SWpvaU15SXNJblI1Y0dVaU9pSkVRVlJCWDB0RldTSXNJbVY0Y0dseVlYUnBiMjRpT2pFM01qRTVOVGMzTmpKOQ==",
        "expiresAt": "2024-07-25T21:37:26.301000-04:00"
    }
}
```
詳細については、*Amazon ECR Public* の「[Amazon ECR パブリックレジストリ](https://docs.aws.amazon.com/AmazonECR/latest/public/public-registries.html#registry_auth_http)」を参照してください。  
**例 2: IAM プリンシパルがアクセスできる Amazon ECR パブリックレジストリの認可トークンを取得するには**  
次の の`get-authorization-token`例では、 CLI AWS を使用して認可トークンを取得し、環境変数に設定します。  

```
aws ecr-public get-authorization-token \
    --region us-east-1 \
    --output=text \
    --query 'authorizationData.authorizationToken'
```
出力:  

```
QVdTOmV5SndZWGxzYjJKJFHDSFKJHERWUY65IOU36TRYEGFNSDLRIUOTUYTHJKLDFGOcmFUQk9OSFV2UVV4a0x6Sm1ZV0Z6TDFndlZtUjJSVmgxVEVObU9IZEdTWEZxU210c1JUQm5RWGxOUVV4NlNFUnROWG92ZWtGbWJFUjRkbWMyV0U5amFpczRNWGxTVkM5Tk5qWkVUM2RDYm05TVJqSkxjV3BsUVZvMmFYSm5iV1ZvVFdGSVRqVlFMMHN4VnpsTGVXbDFRWGRoTmpsbWFuQllhbVl6TkdGaGMwUjJha2xsYUhscWRscHZTRUpFVkVnNVQwNUdOVFpPY2xZclVFNVFVWGRSVFZvd04xUkhjVGxZZFVkQ1ZFZHBPRUptUzBVclYxQldMMjVMVkRsd2VFVlNSa1EzTWpWSlIxRkVWakJGZFZOVWEzaFBSVk5FWWpSc1lWZHZWMHBSYmxaMlJYWmhZekpaWVVOeFppdFlUa2xKU1RCdFUwdElVbXRJYlhGRk1WaFhNVTVRTkdwc1FYRlVNVWxZZUhkV05Xa3ZXWGd3ZUVZMWIyeE5VRU5QZEdSaWRHOU9lakZOZVdwTVZEUkNRVzlvYzNKSlpsRXhhR2cwWjJwRVJFVjNWalEzYjNCUmRIcEZUR1pYU1Rsc1kxSlNNbU5hUW5wRE1tOUpRMHR5Y1hkeGNXNDVMMmx4Um5GUlVGQnhjMVpQZG5WYUswOW9SQ3RPY0hwSlRsUk5lVXQyY0c1b1FsQjVZVEprVmtSdmJsQklOM05RU3pkNmQydERhMkZ5VmxSRmFVUndWVlE1ZGtsVWFXUkJWMFZEWVhoSFdXTk5VMXBTYTFreVRHZEVlVVZ0ZFRWRk4xTTVjRXBDUjBRMlYyTkdPVWhGWkVweVVGcEVaRFJxZUVablkwNXFaamh5YkVKWmJGSTNOVzFXSzFjdllXSTVTMWx2YUZacksxSnJWSFJ0Wml0T1NFSnpWVFZvV204eVFYbzFWRU5SYjNaR01Va3hPR3h2TWxkNVJsSmpUbTVSTjNjemJsUkdVRlZKVDBjeE9VeHlXVEpGVFRSS2NWbFdkVEJrV0VreFVsSktXbkpCVGtsMFdVZEJOMjltWjFFNGVHRktNbGRuWlVoUlNXNXdZV3A0VjI5M2FYZGljbE5tZGpkQ1ZYTmhOVFUyTDBzeVpteDBka0pUTVdkNGJ6TkxkSEJDYml0cE0waGhTbVpEZEZkQ00yOU1TM1pXTDNSVFlWaFpWelZXVWxjNFRXNXdhR3BhUmpoU1FuWnFkRlJMVW5abGRYRlNjVVJKZDBaSFpXUTRabEZUTUdOTVQwcFFkVXAyYjA5Tk9UaFlZMjEwVnpFMlpXdE9hMnBWV0hST1owUkpVV3R1VFU1dGJXWjNNVGc0VTAxUlNHZE9TbXRMY2tWYWJVeFljVVk0ZWpsTFdWWlRNbEZMVDJkMk1FaFBTMDl5YzJSM1NqTlplRGhUWVVOQlJGWnRlbkU1WTBKVFdqTktSR05WTkd0RGNEVjZNalJHVXpkVk9HTnVSa2xLUVd4SVJDODJXbGcyYldGemJVczJPRVp6TDBoNFMwWkRUMmdyYldGa1QwWjVhMlZQTm5SQ1l6QkpNbFpyVUhSaGVIbFVOR296VjFGVlQyMHpNeTlPWVVoSk1FdDBWalZFU2pneU5rcHNLemQxZDNwcVp6RlNja3AwVm10VU0yRnRWWGMzZDJnMFduSnFjVXczWTBjclNXeHFUVlUyVkZwWGNWY3ZSV0V6WW1oT2JIRklZVlJHU1RrMGEyOVJiMHBPVUhORk9FdERjbFJZY0daS2VVdHRZa2x5YjFORE4zSkJaWEJPZUU5eGR6WnhZMlY1WXprM1JtSkZhVFZFYkVFck5EUk9ZMWRyVEVNd1dqa2lMQ0prWVhSaGEyVjVJam9pWlhsS1VWSkdaMmxQYVVwV1ZXeENhVk5YVm14WFdFWk5VMjFrV21SRE9YaGFhWFF4VkhwS1MyTkljSHBVUms0MFlWaHNTbUpIYUhsWFZHdDZZVWhqZDFKRmFETldNbFYyWTJ0cmVVMUlTbHBWUjJONFRURlJNMDlHYUd4U01uaHVWRVJzUWxaV1pGZFJibkJLV1RCYU5HTXpUakpXTUhoWFRrWndhRTVyTVVwVFZFSkdWV3RzTUZaVVpEQlRSVGxyVkVkb2FGUlVVWHBaTVhCSFQxWmFOVlJxU20xaVZXUnVTM3BaTlZaV2NIcFdWMlJGVkcwMVRHSXdSakpXUnpoNlVsUm5kbUpzUmpGT2FUazFWVzFTY0dWR1FtOVdiVEZoVmpKc1NWRllhRmRTUkZwc1V6SkdSbUpWYkhCVlNFbDJWVzB4Ym1OVk1IWmFhelZ3WkZoa1FtVnFUa3BpTTJoTVRWVk9jMVo2V2t4aWJFWnJWRVUxVW1ONlp6QldWVFZPWW14c01sZFlZekprUjFwVFkxaE9kRnBXWkhaVFZWcGhWa2MxU2xWRlVtdFRiWE16WWpOVmVrNXFSa2RVTTJSd1QwaGtXbVJIVVhsbGJYQkRaRlp2ZGxvd1ZqWmlNbEl4Vkc1T2FtSldjRU5VU0ZVd1kwZDRjbU14WkhaVVYwNTRaRzV2TWxSVlVsQmpiSEJPVkc1VmVsZEZPVzVYYkVwWlUyNWtVbGRZWkZWaVdFWlNUVzF3VFZSSVFraE9XRnBwWVZoak0xUnJXak5OYm04eFpEQk9XbEZzYkhSTmEyaHpaRmRTUTJORVFUQlpWMk01VUZOSmMwbHJiRUpTUTBrMlNXNUZlbHA2U1RGVVZXeFVZekIwYVU5RWFEVmtiRVpzVVZWc2QxbHJWbmxOYW13MVZWaG9UazVzVWpWbFJHaDZZMjFHVkZVeFFubFZXRTVLVGpCMGFXSlZNWGhpUjBwTVlUSTVNRTVVYXpCTE0wVnlWakF4VG1WSE5VcGtSa0pRVld4V1UwOVdVWGhqTVc4eVZraFdlVnA2VGsxV01tUnhVV3Q0ZEdGcVRsUk5hMnN5V2tSV2FtUkdVakZqVm5CUFVrUlNjR0pHUm1GbGFscDRXV2x6Y2xFd1VYcGhSRnBZVmtaU2FVNXVSVFZYYlVaVFpXdHdkVmRZVGpaVGEyaDBWMnhDVlU0elZrWlRSRUpIVlVWa2MwNVlhRFZsUkVwelQwWkNSbE5WY0ZGWFNFWXhaVmMxVEZsVE9VeFdhMGt4V1ROS1Rrd3pXazFpYkhCdFVrUldWRlJHVlhaTmJVazBZbFZzUkV3d2N6UldSV2MxVDBWa05tSXpiM2hXVms1V1ZtMDFiRkZUT1hoUFJVcHpUMGRzU2xaSVJrTkxNVTVFWWtaa05WWnViRmRYVjJRd1RXcG5kMVJWUmpCa1JYQkdZVlYwZFZNeU1VVlpWVTVQV25wa1ExZHFVbE5sUjBaRVlWVTFXbVZwY3pSTE1HTTFVbFZGTlZwRll6UlRSMVoxVFcxb05XTnJkRUpWZWxsM1RETmplbUV4WkdGU1JsWm9ZVVpzZEdWR2JFTlVNblJYVkRCNE5HUXlkRXhaTWxKTlYxZDBWRTB5YUZwaFJsazFVMGR3Y0ZGVk9YaGxhekV6VVZRd09VbHVNRDBpTENKMlpYSnphVzl1SWpvaU15SXNJblI1Y0dVaU9pSkVRVlJCWDB0RldTSXNJbVY0Y0dseVlYUnBiMjRpT2pFM01qRTVOVGMzTmpKOQ
```
詳細については、*Amazon ECR Public* の「[Amazon ECR パブリックレジストリ](https://docs.aws.amazon.com/AmazonECR/latest/public/public-registries.html#registry_auth_http)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthorizationToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/get-authorization-token.html)」を参照してください。

### `get-login-password`
<a name="ecr-public_GetLoginPassword_cli_2_topic"></a>

次のコード例は、`get-login-password` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon ECR パブリックレジストリに docker を認証するには**  
次の `get-login-password` の例では、GetAuthorizationToken API を使用して認証トークンを取得して表示します。このトークンを使用して、Amazon ECR パブリックレジストリに認証できます。  

```
aws ecr-public get-login-password \
    --region us-east-1
| docker login \
    --username AWS \
    --password-stdin public.ecr.aws
```
このコマンドはターミナルに出力を表示せず、代わりに Docker に出力をパイプします。  
詳細については、*Amazon ECR Public* の「[パブリックレジストリへの認証](https://docs.aws.amazon.com/AmazonECR/latest/public/public-registries.html#public-registry-auth)」を参照してください。  
**例 2: 独自のカスタム AmazonECR パブリックレジストリに docker を認証するには**  
次の `get-login-password` の例では、GetAuthorizationToken API を使用して認証トークンを取得して表示します。このトークンを使用して、独自のカスタム Amazon ECR パブリックレジストリに認証できます。  

```
 aws ecr-public get-login-password \
    --region us-east-1 \
| docker login \
    --username AWS \
    --password-stdin public.ecr.aws/<your-public-registry-custom-alias>
```
このコマンドはターミナルに出力を表示せず、代わりに Docker に出力をパイプします。  
詳細については、*Amazon ECR Public* の「[独自の Amazon ECR Public への認証](https://docs.aws.amazon.com/AmazonECR/latest/public/public-registries.html#public-registry-auth)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoginPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/get-login-password.html)」を参照してください。

### `get-registry-catalog-data`
<a name="ecr-public_GetRegistryCatalogData_cli_2_topic"></a>

次のコード例は、`get-registry-catalog-data` を使用する方法を示しています。

**AWS CLI**  
**パブリック ECR レジストリのカタログメタデータを取得するには**  
次の `get-registry-catalog-data` は、ECR パブリックレジストリのカタログメタデータを取得します。  

```
aws ecr-public get-registry-catalog-data \
    --region us-east-1
```
出力:  

```
{
    "registryCatalogData": {
        "displayName": "YourCustomPublicRepositoryalias"
    }
}
```
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetRegistryCatalogData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/get-registry-catalog-data.html)」を参照してください。

### `get-repository-catalog-data`
<a name="ecr-public_GetRepositoryCatalogData_cli_2_topic"></a>

次のコード例は、`get-repository-catalog-data` を使用する方法を示しています。

**AWS CLI**  
**パブリックレジストリ内のリポジトリのカタログメタデータを取得するには**  
次の `get-repository-catalog-data` の例では、パブリックレジストリ内のリポジトリ `project-a/nginx-web-app` のカタログメタデータを一覧表示します。  

```
aws ecr-public get-repository-catalog-data \
    --repository-name project-a/nginx-web-app \
    --region us-east-1
```
出力:  

```
{
    "catalogData": {
        "description": "My project-a ECR Public Repository",
        "architectures": [
            "ARM",
            "ARM 64",
            "x86",
            "x86-64"
        ],
        "operatingSystems": [
            "Linux"
        ],
        "logoUrl": "https://d3g9o9u8re44ak.cloudfront.net/logo/491d3846-8f33-4d8b-a10c-c2ce271e6c0d/4f09d87c-2569-4916-a932-5c296bf6f88a.png",
        "aboutText": "## Quick reference\n\nMaintained <truncated>",
        "usageText": "## Supported architectures\n\namd64, arm64v8\n\n## <truncated>"
    }
}
```
詳細については、*Amazon ECR Public* の「[リポジトリカタログデータ](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-catalog-data.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetRepositoryCatalogData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/get-repository-catalog-data.html)」を参照してください。

### `get-repository-policy`
<a name="ecr-public_GetRepositoryPolicy_cli_2_topic"></a>

次のコード例は、`get-repository-policy` を使用する方法を示しています。

**AWS CLI**  
**リポジトリに関連付けられているポリシーを取得するには**  
次の `get-repository-policy` の例では、リポジトリに関連付けられているポリシーを取得します。  

```
aws ecr-public get-repository-policy \
    --repository-name project-a/nginx-web-app \
    --region us-east-1
```
出力:  

```
{
    "registryId": "123456789012",
    "repositoryName": "project-a/nginx-web-app",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"AllowPush\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : {\n      \"AWS\" : [ \"arn:aws:iam::123456789012:user/eksuser1\", \"arn:aws:iam::123456789012:user/admin\" ]\n    },\n    \"Action\" : [ \"ecr-public:BatchCheckLayerAvailability\", \"ecr-public:PutImage\", \"ecr-public:InitiateLayerUpload\", \"ecr-public:UploadLayerPart\", \"ecr-public:CompleteLayerUpload\" ]\n  } ]\n}"
}
```
詳細については、*「Amazon ECR* [Public User Guide」の「Use GetRepositoryPolicy with an AWS SDK or CLI](https://docs.aws.amazon.com/AmazonECR/latest/userguide/example_ecr_GetRepositoryPolicy_section.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRepositoryPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/get-repository-policy.html)」を参照してください。

### `list-tags-for-resource`
<a name="ecr-public_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**パブリックレジストリ内のパブリックリポジトリのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、パブリックレジストリ内の `project-a/nginx-web-app` という名前のリソースのタグを一覧表示します。  

```
aws ecr-public list-tags-for-resource \
    --resource-arn arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app \
    --region us-east-1
```
出力:  

```
{
    "tags": [
        {
            "Key": "Environment",
            "Value": "Prod"
        },
        {
            "Key": "stack",
            "Value": "dev1"
        },
        {
            "Key": "Name",
            "Value": "project-a/nginx-web-app"
        }
    ]
}
```
詳細については、*Amazon ECR Public* の「[パブリックリポジトリのタグを一覧表示する](https://docs.aws.amazon.com/AmazonECR/latest/public/ecr-public-using-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/list-tags-for-resource.html)」を参照してください。

### `put-registry-catalog-data`
<a name="ecr-public_PutRegistryCatalogData_cli_2_topic"></a>

次のコード例は、`put-registry-catalog-data` を使用する方法を示しています。

**AWS CLI**  
**パブリック ECR レジストリのカタログメタデータを作成または更新するには**  
次の `put-registry-catalog-data` は、ECR パブリックレジストリのカタログメタデータを作成または更新します。検証済みアカウントバッジを取得したアカウントのみがレジストリ表示名を設定できます。  

```
aws ecr-public put-registry-catalog-data \
    --region us-east-1 \
    --display-name <YourCustomPublicRepositoryalias>
```
出力:  

```
{
    "registryCatalogData": {
        "displayName": "YourCustomPublicRepositoryalias"
    }
}
```
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutRegistryCatalogData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/put-registry-catalog-data.html)」を参照してください。

### `put-repository-catalog-data`
<a name="ecr-public_PutRepositoryCatalogData_cli_2_topic"></a>

次のコード例は、`put-repository-catalog-data` を使用する方法を示しています。

**AWS CLI**  
**パブリックレジストリ内のリポジトリのカタログデータを作成または更新するには**  
次の `put-repository-catalog-data` の例では、パブリックレジストリ内の project-a/nginx-web-app という名前のリポジトリのカタログデータを作成または更新し、logoImageBlob、aboutText、usageText、およびタグ情報を追加します。  

```
aws ecr-public put-repository-catalog-data \
    --repository-name project-a/nginx-web-app \
    --cli-input-json file://repository-catalog-data.json \
    --region us-east-1
```
`repository-catalog-data.json` の内容:  

```
{
    "repositoryName": "project-a/nginx-web-app",
    "catalogData": {
        "description": "My project-a ECR Public Repository",
        "architectures": [
            "ARM",
            "ARM 64",
            "x86",
            "x86-64"
        ],
        "operatingSystems": [
            "Linux"
        ],
        "logoImageBlob": "iVBORw0KGgoA<<truncated-for-better-reading>>ErkJggg==",
        "aboutText": "## Quick reference.",
        "usageText": "## Supported architectures are as follows."
    }
}
```
出力:  

```
{
    "catalogData": {
        "description": "My project-a ECR Public Repository",
        "architectures": [
            "ARM",
            "ARM 64",
            "x86",
            "x86-64"
        ],
        "operatingSystems": [
            "Linux"
        ],
        "logoUrl": "https://d3g9o9u8re44ak.cloudfront.net/logo/df86cf58-ee60-4061-b804-0be24d97ccb1/4a9ed9b2-69e4-4ede-b924-461462d20ef0.png",
        "aboutText": "## Quick reference.",
        "usageText": "## Supported architectures are as follows."
    }
}
```
詳細については、*Amazon ECR Public* の「[リポジトリカタログデータ](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-catalog-data.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[PutRepositoryCatalogData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/put-repository-catalog-data.html)」を参照してください。

### `set-repository-policy`
<a name="ecr-public_SetRepositoryPolicy_cli_2_topic"></a>

次のコード例は、`set-repository-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: リポジトリへのプルを許可するリポジトリポリシーを設定するには**  
次の `set-repository-policy` の例では、指定したリポジトリに ECR パブリックリポジトリポリシーを適用して、アクセス許可を制御します。  

```
aws ecr-public set-repository-policy \
    --repository-name project-a/nginx-web-app \
    --policy-text file://my-repository-policy.json
```
`my-repository-policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement" : [
        {
            "Sid" : "allow public pull",
            "Effect" : "Allow",
            "Principal" : "*",
            "Action" : [
                "ecr:BatchCheckLayerAvailability",
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer"
            ]
        }
    ]
}
```
出力:  

```
{
    "registryId": "12345678901",
    "repositoryName": "project-a/nginx-web-app",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"allow public pull\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : \"*\",\n    \"Action\" : [ \"ecr:BatchCheckLayerAvailability\", \"ecr:BatchGetImage\", \"ecr:GetDownloadUrlForLayer\" ]\n  } ]\n}"
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[リポジトリポリシーステートメントの設定](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-policy-examples.html)」を参照してください。  
**例 2: アカウント内の IAM ユーザーがイメージをプッシュできるようにリポジトリポリシーを設定するには**  
次の`set-repository-policy`例では、アカウント内の IAM ユーザーが、ポリシーテキスト`file://my-repository-policy.json`として という名前の入力ファイルを使用して、 を使用して AWS アカウントの ECR リポジトリにイメージをプッシュできるようにします。  

```
aws ecr-public set-repository-policy \
    --repository-name project-a/nginx-web-app \
    --policy-text file://my-repository-policy.json
```
`my-repository-policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowPush",
            "Effect": "Allow",
            "Principal": {
                "AWS": [
                    "arn:aws:iam::account-id:user/push-pull-user-1",
                    "arn:aws:iam::account-id:user/push-pull-user-2"
                ]
            },
            "Action": [
                "ecr-public:BatchCheckLayerAvailability",
                "ecr-public:PutImage",
                "ecr-public:InitiateLayerUpload",
                "ecr-public:UploadLayerPart",
                "ecr-public:CompleteLayerUpload"
            ]
        }
    ]
}
```
出力:  

```
{
    "registryId": "12345678901",
    "repositoryName": "project-a/nginx-web-app",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"AllowPush\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : {\n      \"AWS\" : [ \"arn:aws:iam::12345678901:user/admin\", \"arn:aws:iam::12345678901:user/eksuser1\" ]\n    },\n    \"Action\" : [ \"ecr-public:BatchCheckLayerAvailability\", \"ecr-public:PutImage\", \"ecr-public:InitiateLayerUpload\", \"ecr-public:UploadLayerPart\", \"ecr-public:CompleteLayerUpload\" ]\n  } ]\n}"
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[リポジトリポリシーステートメントの設定](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-policy-examples.html)」を参照してください。  
**例 3: 異なるアカウントの IAM ユーザーにイメージのプッシュを許可するリポジトリポリシーを設定するには**  
次の`set-repository-policy`例では、特定のアカウントが cli 入力ファイル://my-repository-policy.json を使用して AWS イメージをプッシュできるようにします。  

```
aws ecr-public set-repository-policy \
    --repository-name project-a/nginx-web-app \
    --policy-text file://my-repository-policy.json
```
`my-repository-policy.json` の内容:  

```
 {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
         {
             "Sid": "AllowCrossAccountPush",
             "Effect": "Allow",
             "Principal": {
                 "AWS": "arn:aws:iam::other-or-same-account-id:role/RoleName"
             },
             "Action": [
                 "ecr-public:BatchCheckLayerAvailability",
                 "ecr-public:PutImage",
                 "ecr-public:InitiateLayerUpload",
                 "ecr-public:UploadLayerPart",
                 "ecr-public:CompleteLayerUpload"
             ]
         }
     ]
}
```
出力:  

```
{
    "registryId": "12345678901",
    "repositoryName": "project-a/nginx-web-app",
    "policyText": "{\n  \"Version\" : \"2008-10-17\",\n  \"Statement\" : [ {\n    \"Sid\" : \"AllowCrossAccountPush\",\n    \"Effect\" : \"Allow\",\n    \"Principal\" : {\n      \"AWS\" : \"arn:aws:iam::12345678901:role/RoleName\"\n    },\n    \"Action\" : [ \"ecr-public:BatchCheckLayerAvailability\", \"ecr-public:PutImage\", \"ecr-public:InitiateLayerUpload\", \"ecr-public:UploadLayerPart\", \"ecr-public:CompleteLayerUpload\" ]\n  } ]\n}"
}
```
詳細については、*Amazon ECR Public ユーザーガイド*の「[パブリックリポジトリポリシーの例](https://docs.aws.amazon.com/AmazonECR/latest/public/public-repository-policy-examples.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetRepositoryPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/set-repository-policy.html)」を参照してください。

### `tag-resource`
<a name="ecr-public_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックレジストリ内の既存のパブリックリポジトリにタグを付けるには**  
次の `tag-resource` の例では、パブリックレジストリ内の `project-a/nginx-web-app` という名前のリポジトリにタグを付けます。  

```
aws ecr-public tag-resource \
    --resource-arn arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app \
    --tags Key=stack,Value=dev \
    --region us-east-1
```
詳細については、*Amazon ECR Public* の「[パブリックリポジトリのタグの使用](https://docs.aws.amazon.com/AmazonECR/latest/public/ecr-public-using-tags.html)」を参照してください。  
**例 2: パブリックレジストリ内の既存のパブリックリポジトリに複数のタグを付けるには**  
次の `tag-resource` の例では、既存のリポジトリに複数のタグを付けます。  

```
aws ecr-public tag-resource \
    --resource-arn arn:aws:ecr-public::890517186334:repository/project-a/nginx-web-app  \
    --tags Key=key1,Value=value1 Key=key2,Value=value2 Key=key3,Value=value3 \
    --region us-east-1
```
詳細については、*Amazon ECR Public* の「[パブリックリポジトリのタグの使用](https://docs.aws.amazon.com/AmazonECR/latest/public/ecr-public-using-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ecr-public_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: パブリックレジストリ内の既存のパブリックリポジトリのタグを削除するには**  
次の `untag-resource` の例では、パブリックレジストリ内の `project-a/nginx-web-app` という名前のリポジトリにタグを付けます。  

```
aws ecr-public untag-resource \
    --resource-arn arn:aws:ecr-public::123456789012:repository/project-a/nginx-web-app \
    --tag-keys stack \
    --region us-east-1
```
このコマンドでは何も出力されません。  
詳細については、*Amazon ECR Public* の「[パブリックリポジトリのタグの使用](https://docs.aws.amazon.com/AmazonECR/latest/public/ecr-public-using-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecr-public/untag-resource.html)」を参照してください。

# を使用した Amazon ECS の例 AWS CLI
<a name="cli_2_ecs_code_examples"></a>

次のコード例は、Amazon ECS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `capacity-provider-update`
<a name="ecs_CapacityProviderUpdate_cli_2_topic"></a>

次のコード例は、`capacity-provider-update` を使用する方法を示しています。

**AWS CLI**  
**ECS クラスターのキャパシティプロバイダーを更新する**  
次の `update-capacity-provider` の例では、ECS クラスターのキャパシティプロバイダーのパラメータを変更する方法を示します。  

```
aws ecs update-capacity-provider \
    --name Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt \
    --auto-scaling-group-provider "managedScaling={status=DISABLED,targetCapacity=50,minimumScalingStepSize=2,maximumScalingStepSize=30,instanceWarmupPeriod=200},managedTerminationProtection=DISABLED,managedDraining=DISABLED"
```
出力:  

```
{
    "capacityProvider": {
        "capacityProviderArn": "arn:aws:ecs:us-west-2:123456789012:capacity-provider/Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt",
        "name": "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt",
        "status": "ACTIVE",
        "autoScalingGroupProvider": {
            "autoScalingGroupArn": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:424941d1-b43f-4a17-adbb-08b6a6e397e1:autoScalingGroupName/Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-ECSAutoScalingGroup-f44jrQHS2nRB",
            "managedScaling": {
                "status": "ENABLED",
                "targetCapacity": 100,
                "minimumScalingStepSize": 1,
                "maximumScalingStepSize": 10000,
                "instanceWarmupPeriod": 300
            },
            "managedTerminationProtection": "DISABLED",
            "managedDraining": "ENABLED"
        },
        "updateStatus": "UPDATE_IN_PROGRESS",
        "tags": []
    }
}
```
キャパシティプロバイダーの詳細については、*Amazon ECS デベロッパーガイド*の「[EC2 起動タイプ用の Amazon ECS キャパシティプロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/asg-capacity-providers.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CapacityProviderUpdate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/capacity-provider-update.html)」を参照してください。

### `create-capacity-provider`
<a name="ecs_CreateCapacityProvider_cli_2_topic"></a>

次のコード例は、`create-capacity-provider` を使用する方法を示しています。

**AWS CLI**  
**キャパシティープロバイダーを作成するには**  
次の create-capacity-provider の例では、MyASG という名前の Auto Scaling グループを使用し、マネージドスケーリングおよびマネージド終了保護を有効にしたキャパシティープロバイダーを作成します。この構成は、Amazon ECS クラスターの自動スケーリングに使用されます。  

```
aws ecs create-capacity-provider \
    --name "MyCapacityProvider" \
    --auto-scaling-group-provider "autoScalingGroupArn=arn:aws:autoscaling:us-east-1:123456789012:autoScalingGroup:57ffcb94-11f0-4d6d-bf60-3bac5EXAMPLE:autoScalingGroupName/MyASG,managedScaling={status=ENABLED,targetCapacity=100},managedTerminationProtection=ENABLED"
```
出力:  

```
{
    "capacityProvider": {
    "capacityProviderArn": "arn:aws:ecs:us-east-1:123456789012:capacity-provider/MyCapacityProvider",
    "name": "MyCapacityProvider",
    "status": "ACTIVE",
    "autoScalingGroupProvider": {
        "autoScalingGroupArn": "arn:aws:autoscaling:us-east-1:132456789012:autoScalingGroup:57ffcb94-11f0-4d6d-bf60-3bac5EXAMPLE:autoScalingGroupName/MyASG",
        "managedScaling": {
            "status": "ENABLED",
            "targetCapacity": 100,
            "minimumScalingStepSize": 1,
            "maximumScalingStepSize": 10000,
            "instanceWarmupPeriod": 300
        },
        "managedTerminationProtection": "ENABLED"
    },
    "tags": []
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS クラスター自動スケーリング](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-auto-scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCapacityProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/create-capacity-provider.html)」を参照してください。

### `create-cluster`
<a name="ecs_CreateCluster_cli_2_topic"></a>

次のコード例は、`create-cluster` を使用する方法を示しています。

**AWS CLI**  
**例 1: 新しいクラスターを作成するには**  
次の `create-cluster`の例では、`MyCluster` という名前のクラスターを作成し、オブザーバビリティが強化された CloudWatch Container Insights を有効にします。  

```
aws ecs create-cluster \
    --cluster-name MyCluster \
    --settings name=containerInsights,value=enhanced
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "clusterName": "MyCluster",
        "status": "ACTIVE",
        "registeredContainerInstancesCount": 0,
        "pendingTasksCount": 0,
        "runningTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "enhanced"
            }
        ],
        "tags": []
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[従来のコンソールを使用したクラスターの作成](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)」を参照してください。**  
**例 2: キャパシティプロバイダーを使用して新しいクラスターを作成するには**  
次の `create-cluster` の例は、クラスターを作成し、2 つの既存のキャパシティプロバイダーをそのクラスターに関連付けます。キャパシティープロバイダーを作成するには、`create-capacity-provider` コマンドを使用します。デフォルトのキャパシティープロバイダー戦略を指定することは任意ですが、指定することをお勧めします。この例では、`MyCluster` という名前のクラスターを作成し、`MyCapacityProvider1` と `MyCapacityProvider2` をキャパシティプロバイダーに関連付けます。デフォルトのキャパシティープロバイダー戦略は、タスクを両方のキャパシティープロバイダーに均等に分散するように指定されています。  

```
aws ecs create-cluster \
    --cluster-name MyCluster \
    --capacity-providers MyCapacityProvider1 MyCapacityProvider2 \
    --default-capacity-provider-strategy capacityProvider=MyCapacityProvider1,weight=1 capacityProvider=MyCapacityProvider2,weight=1
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "clusterName": "MyCluster",
        "status": "PROVISIONING",
        "registeredContainerInstancesCount": 0,
        "pendingTasksCount": 0,
        "runningTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "enabled"
            }
        ],
        "capacityProviders": [
            "MyCapacityProvider1",
            "MyCapacityProvider2"
        ],
        "defaultCapacityProviderStrategy": [
            {
                "capacityProvider": "MyCapacityProvider1",
                "weight": 1,
                "base": 0
            },
            {
                "capacityProvider": "MyCapacityProvider2",
                "weight": 1,
                "base": 0
            }
        ],
        "attachments": [
           {
               "id": "0fb0c8f4-6edd-4de1-9b09-17e470ee1918",
               "type": "asp",
               "status": "PRECREATED",
               "details": [
                   {
                       "name": "capacityProviderName",
                       "value": "MyCapacityProvider1"
                   },
                   {
                       "name": "scalingPlanName",
                       "value": "ECSManagedAutoScalingPlan-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
                   }
                ]
            },
            {
                "id": "ae592060-2382-4663-9476-b015c685593c",
                "type": "asp",
                "status": "PRECREATED",
                "details": [
                    {
                        "name": "capacityProviderName",
                        "value": "MyCapacityProvider2"
                    },
                    {
                        "name": "scalingPlanName",
                        "value": "ECSManagedAutoScalingPlan-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
                    }
                ]
            }
        ],
        "attachmentsStatus": "UPDATE_IN_PROGRESS"
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
**例 3: 複数のタグを含む新しいクラスターを作成するには**  
次の `create-cluster` の例は、複数のタグを含むクラスターを作成します。短縮構文を使用したタグの追加の詳細については、「 *AWS CLI ユーザーガイド*[」の AWS 「 コマンドラインインターフェイスでの短縮構文](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-shorthand.html)の使用」を参照してください。  

```
aws ecs create-cluster \
    --cluster-name MyCluster \
    --tags key=key1,value=value1 key=key2,value=value2
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "clusterName": "MyCluster",
        "status": "ACTIVE",
        "registeredContainerInstancesCount": 0,
        "pendingTasksCount": 0,
        "runningTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "tags": [
            {
                "key": "key1",
                "value": "value1"
            },
            {
                "key": "key2",
                "value": "value2"
            }
        ]
     }
 }
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[従来のコンソールを使用したクラスターの作成](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/create-cluster.html)」を参照してください。

### `create-service`
<a name="ecs_CreateService_cli_2_topic"></a>

次のコード例は、`create-service` を使用する方法を示しています。

**AWS CLI**  
**例 1: Fargate タスクを使用してサービスを作成するには**  
次の `create-service` の例は、Fargate タスクを使用してサービスを作成する方法を示しています。  

```
aws ecs create-service \
    --cluster MyCluster \
    --service-name MyService \
    --task-definition sample-fargate:1 \
    --desired-count 2 \
    --launch-type FARGATE \
    --platform-version LATEST \
    --network-configuration 'awsvpcConfiguration={subnets=[subnet-12344321],securityGroups=[sg-12344321],assignPublicIp=ENABLED}' \
    --tags key=key1,value=value1 key=key2,value=value2 key=key3,value=value3
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/MyCluster/MyService",
        "serviceName": "MyService",
          "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 0,
        "pendingCount": 0,
        "launchType": "FARGATE",
        "platformVersion": "LATEST",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sample-fargate:1",
        "deploymentConfiguration": {
            "maximumPercent": 200,
            "minimumHealthyPercent": 100
        },
        "deployments": [
            {
                "id": "ecs-svc/1234567890123456789",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sample-fargate:1",
                "desiredCount": 2,
                "pendingCount": 0,
                "runningCount": 0,
                "createdAt": 1557119253.821,
                "updatedAt": 1557119253.821,
                "launchType": "FARGATE",
                "platformVersion": "1.3.0",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321"
                        ],
                        "securityGroups": [
                            "sg-12344321"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                }
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [],
        "createdAt": 1557119253.821,
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321"
                ],
                "securityGroups": [
                    "sg-12344321"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "schedulingStrategy": "REPLICA",
        "tags": [
            {
                "key": "key1",
                "value": "value1"
            },
            {
                "key": "key2",
                "value": "value2"
            },
            {
                "key": "key3",
                "value": "value3"
            }
        ],
        "enableECSManagedTags": false,
        "propagateTags": "NONE"
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[クラシックコンソール内の Amazon ECS サービスの作成](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-service-console-v2.html)」を参照してください。**  
**例 2: EC2 起動タイプを使用してサービスを作成するには**  
次の `create-service` の例は、EC2 起動タイプを使用して、`ecs-simple-service` と呼ばれるサービスを作成する方法を示しています。このサービスは `sleep360` タスク定義を使用し、タスクのインスタンスを 1 つ保持します。  

```
aws ecs create-service \
    --cluster MyCluster \
    --service-name ecs-simple-service \
    --task-definition sleep360:2 \
    --desired-count 1
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/MyCluster/ecs-simple-service",
        "serviceName": "ecs-simple-service",
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 1,
        "runningCount": 0,
        "pendingCount": 0,
        "launchType": "EC2",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sleep360:2",
        "deploymentConfiguration": {
            "maximumPercent": 200,
            "minimumHealthyPercent": 100
        },
        "deployments": [
            {
                "id": "ecs-svc/1234567890123456789",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sleep360:2",
                "desiredCount": 1,
                "pendingCount": 0,
                "runningCount": 0,
                "createdAt": 1557206498.798,
                "updatedAt": 1557206498.798,
                "launchType": "EC2"
            }
        ],
        "events": [],
        "createdAt": 1557206498.798,
        "placementConstraints": [],
        "placementStrategy": [],
        "schedulingStrategy": "REPLICA",
        "enableECSManagedTags": false,
        "propagateTags": "NONE"
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[クラシックコンソール内の Amazon ECS サービスの作成](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-service-console-v2.html)」を参照してください。**  
**例 3: 外部のデプロイコントローラーを使用するサービスを作成するには**  
次の `create-service` の例は、外部のデプロイコントローラーを使用するサービスを作成します。  

```
aws ecs create-service \
    --cluster MyCluster \
    --service-name MyService \
    --deployment-controller type=EXTERNAL \
    --desired-count 1
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/MyCluster/MyService",
        "serviceName": "MyService",
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 1,
        "runningCount": 0,
        "pendingCount": 0,
        "launchType": "EC2",
        "deploymentConfiguration": {
            "maximumPercent": 200,
            "minimumHealthyPercent": 100
        },
        "taskSets": [],
        "deployments": [],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [],
        "createdAt": 1557128207.101,
        "placementConstraints": [],
        "placementStrategy": [],
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "EXTERNAL"
        },
        "enableECSManagedTags": false,
        "propagateTags": "NONE"
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[クラシックコンソール内の Amazon ECS サービスの作成](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-service-console-v2.html)」を参照してください。**  
**例 4: ロードバランサーの背後に新しいサービスを作成するには**  
次の `create-service` の例は、ロードバランサーの背後にサービスを作成する方法を示しています。コンテナインスタンスと同じリージョンに、ロードバランサーを設定する必要があります。この例では、`--cli-input-json` オプションと、以下の内容を含む JSON 入力ファイル (`ecs-simple-service-elb.json`) を使用します。  

```
aws ecs create-service \
    --cluster MyCluster \
    --service-name ecs-simple-service-elb \
    --cli-input-json file://ecs-simple-service-elb.json
```
`ecs-simple-service-elb.json` の内容:  

```
 {
    "serviceName": "ecs-simple-service-elb",
    "taskDefinition": "ecs-demo",
    "loadBalancers": [
        {
            "loadBalancerName": "EC2Contai-EcsElast-123456789012",
            "containerName": "simple-demo",
            "containerPort": 80
        }
    ],
    "desiredCount": 10,
    "role": "ecsServiceRole"
}
```
出力:  

```
{
    "service": {
        "status": "ACTIVE",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/ecs-demo:1",
        "pendingCount": 0,
        "loadBalancers": [
            {
                "containerName": "ecs-demo",
                "containerPort": 80,
                "loadBalancerName": "EC2Contai-EcsElast-123456789012"
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/ecsServiceRole",
        "desiredCount": 10,
        "serviceName": "ecs-simple-service-elb",
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/ecs-simple-service-elb",
        "deployments": [
            {
                "status": "PRIMARY",
                "pendingCount": 0,
                "createdAt": 1428100239.123,
                "desiredCount": 10,
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/ecs-demo:1",
                "updatedAt": 1428100239.123,
                "id": "ecs-svc/1234567890123456789",
                "runningCount": 0
            }
        ],
        "events": [],
        "runningCount": 0
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[ロードバランサーを使用して Amazon ECS サービストラフィックを分散する](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-load-balancing.html)」を参照してください。  
**例 5: サービスの作成時に Amazon EBS ボリュームを設定するには**  
次の `create-service` の例では、サービスで管理するタスクごとに Amazon EBS ボリュームを設定する方法を示します。`AmazonECSInfrastructureRolePolicyForVolumes` マネージドポリシーがアタッチされた Amazon ECS インフラストラクチャロールを設定する必要があります。`create-service` リクエストと同じボリューム名でタスク定義を指定する必要があります。この例では、`--cli-input-json` オプションと、以下の内容を含む JSON 入力ファイル (`ecs-simple-service-ebs.json`) を使用します。  

```
aws ecs create-service \
    --cli-input-json file://ecs-simple-service-ebs.json
```
`ecs-simple-service-ebs.json` の内容:  

```
{
    "cluster": "mycluster",
    "taskDefinition": "mytaskdef",
    "serviceName": "ecs-simple-service-ebs",
    "desiredCount": 2,
    "launchType": "FARGATE",
    "networkConfiguration":{
        "awsvpcConfiguration":{
            "assignPublicIp": "ENABLED",
            "securityGroups": ["sg-12344321"],
            "subnets":["subnet-12344321"]
        }
    },
    "volumeConfigurations": [
        {
            "name": "myEbsVolume",
            "managedEBSVolume": {
                "roleArn":"arn:aws:iam::123456789012:role/ecsInfrastructureRole",
                "volumeType": "gp3",
                "sizeInGiB": 100,
                "iops": 3000,
                "throughput": 125,
                "filesystemType": "ext4"
            }
        }
   ]
}
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/mycluster/ecs-simple-service-ebs",
        "serviceName": "ecs-simple-service-ebs",
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/mycluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 0,
        "pendingCount": 0,
        "launchType": "EC2",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:3",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": false,
                "rollback": false
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100
        },
        "deployments": [
            {
                "id": "ecs-svc/7851020056849183687",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:3",
                "desiredCount": 0,
                "pendingCount": 0,
                "runningCount": 0,
                "failedTasks": 0,
                "createdAt": "2025-01-21T11:32:38.034000-06:00",
                "updatedAt": "2025-01-21T11:32:38.034000-06:00",
                "launchType": "EC2",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321"
                        ],
                        "securityGroups": [
                            "sg-12344321"
                        ],
                        "assignPublicIp": "DISABLED"
                    }
                },
                "rolloutState": "IN_PROGRESS",
                "rolloutStateReason": "ECS deployment ecs-svc/7851020056849183687 in progress.",
                "volumeConfigurations": [
                    {
                        "name": "myEBSVolume",
                        "managedEBSVolume": {
                            "volumeType": "gp3",
                            "sizeInGiB": 100,
                            "iops": 3000,
                            "throughput": 125,
                            "roleArn": "arn:aws:iam::123456789012:role/ecsInfrastructureRole",
                            "filesystemType": "ext4"
                        }
                    }
                ]
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [],
        "createdAt": "2025-01-21T11:32:38.034000-06:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321"
                ],
                "securityGroups": [
                    "sg-12344321"
                ],
                "assignPublicIp": "DISABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::123456789012:user/AIDACKCEVSQ6C2EXAMPLE",
        "enableECSManagedTags": false,
        "propagateTags": "NONE",
        "enableExecuteCommand": false,
        "availabilityZoneRebalancing": "DISABLED"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS での Amazon EBS ボリュームの使用](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-volumes.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/create-service.html)」を参照してください。**

### `create-task-set`
<a name="ecs_CreateTaskSet_cli_2_topic"></a>

次のコード例は、`create-task-set` を使用する方法を示しています。

**AWS CLI**  
**タスクセットを作成するには**  
次の `create-task-set` の例は、外部のデプロイコントローラーを使用するサービスのタスクセットを作成します。  

```
aws ecs create-task-set \
    --cluster MyCluster \
    --service MyService \
    --task-definition MyTaskDefinition:2 \
    --network-configuration "awsvpcConfiguration={subnets=[subnet-12344321],securityGroups=[sg-12344321]}"
```
出力:  

```
{
    "taskSet": {
        "id": "ecs-svc/1234567890123456789",
        "taskSetArn": "arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789",
        "status": "ACTIVE",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/MyTaskDefinition:2",
        "computedDesiredCount": 0,
        "pendingCount": 0,
        "runningCount": 0,
        "createdAt": 1557128360.711,
        "updatedAt": 1557128360.711,
        "launchType": "EC2",
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321"
                ],
                "securityGroups": [
                    "sg-12344321"
                ],
                "assignPublicIp": "DISABLED"
            }
        },
        "loadBalancers": [],
        "serviceRegistries": [],
        "scale": {
            "value": 0.0,
            "unit": "PERCENT"
        },
        "stabilityStatus": "STABILIZING",
        "stabilityStatusAt": 1557128360.711
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTaskSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/create-task-set.html)」を参照してください。

### `delete-account-setting`
<a name="ecs_DeleteAccountSetting_cli_2_topic"></a>

次のコード例は、`delete-account-setting` を使用する方法を示しています。

**AWS CLI**  
**特定の IAM ユーザーまたは IAM ロールのアカウント設定を削除するには**  
次の例では、`delete-account-setting` により、特定の IAM ユーザーまたは IAM ロールのアカウント設定が削除されます。  

```
aws ecs delete-account-setting \
    --name serviceLongArnFormat \
    --principal-arn arn:aws:iam::123456789012:user/MyUser
```
出力:  

```
{
    "setting": {
        "name": "serviceLongArnFormat",
        "value": "enabled",
        "principalArn": "arn:aws:iam::123456789012:user/MyUser"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon リソースネーム (ARN) と ID](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-resource-ids.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccountSetting](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/delete-account-setting.html)」を参照してください。

### `delete-attributes`
<a name="ecs_DeleteAttributes_cli_2_topic"></a>

次のコード例は、`delete-attributes` を使用する方法を示しています。

**AWS CLI**  
**Amazon ECS リソースから 1 つ以上のカスタム属性を削除するには**  
次の `delete-attributes` では、コンテナインスタンスから `stack` という名前の属性を削除します。  

```
aws ecs delete-attributes \
    --attributes name=stack,targetId=arn:aws:ecs:us-west-2:130757420319:container-instance/1c3be8ed-df30-47b4-8f1e-6e68ebd01f34
```
出力:  

```
{
    "attributes": [
        {
            "name": "stack",
            "targetId": "arn:aws:ecs:us-west-2:130757420319:container-instance/1c3be8ed-df30-47b4-8f1e-6e68ebd01f34",
            "value": "production"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/delete-attributes.html)」を参照してください。

### `delete-capacity-provider`
<a name="ecs_DeleteCapacityProvider_cli_2_topic"></a>

次のコード例は、`delete-capacity-provider` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon リソースネーム (ARN) を使用してキャパシティプロバイダーを削除するには**  
次の `delete-capacity-provider` の例では、キャパシティープロバイダーの Amazon リソースネーム (ARN) を指定して、キャパシティープロバイダーを削除します。ARN とキャパシティープロバイダーの削除のステータスは、`describe-capacity-providers` コマンドを使用して取得できます。  

```
aws ecs delete-capacity-provider \
    --capacity-provider arn:aws:ecs:us-west-2:123456789012:capacity-provider/ExampleCapacityProvider
```
出力:  

```
{
    "capacityProvider": {
        "capacityProviderArn": "arn:aws:ecs:us-west-2:123456789012:capacity-provider/ExampleCapacityProvider",
        "name": "ExampleCapacityProvider",
        "status": "ACTIVE",
        "autoScalingGroupProvider": {
            "autoScalingGroupArn": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:autoScalingGroupName/MyAutoScalingGroup",
            "managedScaling": {
                "status": "ENABLED",
                "targetCapacity": 100,
                "minimumScalingStepSize": 1,
                "maximumScalingStepSize": 10000
            },
            "managedTerminationProtection": "DISABLED"
        },
        "updateStatus": "DELETE_IN_PROGRESS",
        "tags": []
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
**例 2: 名前を使用してキャパシティープロバイダーを削除するには**  
次の `delete-capacity-provider` の例では、キャパシティープロバイダーの短縮名を指定して、キャパシティープロバイダーを削除します。短縮名とキャパシティープロバイダーの削除のステータスは、`describe-capacity-providers` コマンドを使用して取得できます。  

```
aws ecs delete-capacity-provider \
    --capacity-provider ExampleCapacityProvider
```
出力:  

```
{
    "capacityProvider": {
        "capacityProviderArn": "arn:aws:ecs:us-west-2:123456789012:capacity-provider/ExampleCapacityProvider",
        "name": "ExampleCapacityProvider",
        "status": "ACTIVE",
        "autoScalingGroupProvider": {
            "autoScalingGroupArn": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:autoScalingGroupName/MyAutoScalingGroup",
            "managedScaling": {
                "status": "ENABLED",
                "targetCapacity": 100,
                "minimumScalingStepSize": 1,
                "maximumScalingStepSize": 10000
            },
            "managedTerminationProtection": "DISABLED"
        },
        "updateStatus": "DELETE_IN_PROGRESS",
        "tags": []
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCapacityProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/delete-capacity-provider.html)」を参照してください。

### `delete-cluster`
<a name="ecs_DeleteCluster_cli_2_topic"></a>

次のコード例は、`delete-cluster` を使用する方法を示しています。

**AWS CLI**  
**空のクラスターを削除するには**  
次の `delete-cluster` の例は、指定された空のクラスターを削除します。  

```
aws ecs delete-cluster --cluster MyCluster
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "status": "INACTIVE",
        "clusterName": "MyCluster",
        "registeredContainerInstancesCount": 0,
        "pendingTasksCount": 0,
        "runningTasksCount": 0,
        "activeServicesCount": 0
        "statistics": [],
        "tags": []
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[クラシックコンソールを使用してクラスターを削除するには](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/delete_cluster.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/delete-cluster.html)」を参照してください。

### `delete-service`
<a name="ecs_DeleteService_cli_2_topic"></a>

次のコード例は、`delete-service` を使用する方法を示しています。

**AWS CLI**  
**サービスを削除する方法**  
次の `ecs delete-service` の例は、指定されたサービスをクラスターから削除します。`--force` パラメータを含めると、タスクがゼロになっていない場合でも、サービスを削除することができます。  

```
aws ecs delete-service --cluster MyCluster --service MyService1 --force
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[クラシックコンソールを使用してサービスを削除するには](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/delete-service.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/delete-service.html)」を参照してください。

### `delete-task-definitions`
<a name="ecs_DeleteTaskDefinitions_cli_2_topic"></a>

次のコード例は、`delete-task-definitions` を使用する方法を示しています。

**AWS CLI**  
**タスク定義を削除するには**  
次の `delete-task-definitions` の例では、INACTIVE タスク定義を削除します。  

```
aws ecs delete-task-definitions \
    --task-definition curltest:1
```
出力:  

```
{
"taskDefinitions": [
    {
        "taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/curltest:1",
        "containerDefinitions": [
            {
                "name": "ctest",
                "image": "mreferre/eksutils",
                "cpu": 0,
                "portMappings": [],
                "essential": true,
                "entryPoint": [
                    "sh",
                    "-c"
                ],
                "command": [
                    "curl ${ECS_CONTAINER_METADATA_URI_V4}/task"
                ],
                "environment": [],
                "mountPoints": [],
                "volumesFrom": [],
                "logConfiguration": {
                    "logDriver": "awslogs",
                    "options": {
                        "awslogs-create-group": "true",
                        "awslogs-group": "/ecs/curltest",
                        "awslogs-region": "us-east-1",
                        "awslogs-stream-prefix": "ecs"
                    }
                }
            }
        ],
        "family": "curltest",
        "taskRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
        "executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
        "networkMode": "awsvpc",
        "revision": 1,
        "volumes": [],
        "status": "DELETE_IN_PROGRESS",
        "compatibilities": [
            "EC2",
            "FARGATE"
        ],
        "requiresCompatibilities": [
            "FARGATE"
        ],
        "cpu": "256",
        "memory": "512",
        "registeredAt": "2021-09-10T12:56:24.704000+00:00",
        "deregisteredAt": "2023-03-14T15:20:59.419000+00:00",
        "registeredBy": "arn:aws:sts::123456789012:assumed-role/Admin/jdoe"
        }
    ],
    "failures": []
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS のタスク定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTaskDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/delete-task-definitions.html)」を参照してください。

### `delete-task-set`
<a name="ecs_DeleteTaskSet_cli_2_topic"></a>

次のコード例は、`delete-task-set` を使用する方法を示しています。

**AWS CLI**  
**タスクセットを削除するには**  
次の `delete-task-set` の例で、タスクセットを削除する方法について説明します。`--force` パラメータを含めると、タスクセットがゼロになっていない場合でも、タスクセットを削除することができます。  

```
aws ecs delete-task-set \
    --cluster MyCluster \
    --service MyService \
    --task-set arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789 \
    --force
```
出力:  

```
{
    "taskSet": {
        "id": "ecs-svc/1234567890123456789",
        "taskSetArn": "arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789",
        "status": "DRAINING",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sample-fargate:2",
        "computedDesiredCount": 0,
        "pendingCount": 0,
        "runningCount": 0,
        "createdAt": 1557130260.276,
        "updatedAt": 1557130290.707,
        "launchType": "EC2",
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12345678"
                ],
                "securityGroups": [
                    "sg-12345678"
                ],
                "assignPublicIp": "DISABLED"
            }
        },
        "loadBalancers": [],
        "serviceRegistries": [],
        "scale": {
            "value": 0.0,
            "unit": "PERCENT"
        },
        "stabilityStatus": "STABILIZING",
        "stabilityStatusAt": 1557130290.707
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTaskSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/delete-task-set.html)」を参照してください。

### `deregister-container-instance`
<a name="ecs_DeregisterContainerInstance_cli_2_topic"></a>

次のコード例は、`deregister-container-instance` を使用する方法を示しています。

**AWS CLI**  
**クラスターからコンテナインスタンスの登録を解除するには**  
次の `deregister-container-instance` の例では、指定されたクラスターからコンテナインスタンスを登録解除します。コンテナインスタンスでまだ実行中のタスクがある場合は、登録解除する前にそれらのタスクを停止するか、`--force` オプションを使用する必要があります。  

```
aws ecs deregister-container-instance \
    --cluster arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster \
    --container-instance arn:aws:ecs:us-west-2:123456789012:container-instance/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --force
```
出力:  

```
{
    "containerInstance": {
        "remainingResources": [
            {
                "integerValue": 1024,
                "doubleValue": 0.0,
                "type": "INTEGER",
                "longValue": 0,
                "name": "CPU"
            },
            {
                "integerValue": 985,
                "doubleValue": 0.0,
                "type": "INTEGER",
                "longValue": 0,
                "name": "MEMORY"
            },
            {
                "type": "STRINGSET",
                "integerValue": 0,
                "name": "PORTS",
                "stringSetValue": [
                    "22",
                    "2376",
                    "2375",
                    "51678",
                    "51679"
                ],
                "longValue": 0,
                "doubleValue": 0.0
            },
            {
                "type": "STRINGSET",
                "integerValue": 0,
                "name": "PORTS_UDP",
                "stringSetValue": [],
                "longValue": 0,
                "doubleValue": 0.0
            }
        ],
        "agentConnected": true,
        "attributes": [
            {
                "name": "ecs.capability.secrets.asm.environment-variables"
            },
            {
                "name": "com.amazonaws.ecs.capability.logging-driver.syslog"
            },
            {
                "value": "ami-01a82c3fce2c3ba58",
                "name": "ecs.ami-id"
            },
            {
                "name": "ecs.capability.secrets.asm.bootstrap.log-driver"
            },
            {
                "name": "com.amazonaws.ecs.capability.logging-driver.none"
            },
            {
                "name": "ecs.capability.ecr-endpoint"
            },
            {
                "name": "com.amazonaws.ecs.capability.logging-driver.json-file"
            },
            {
                "value": "vpc-1234567890123467",
                "name": "ecs.vpc-id"
            },
            {
                "name": "ecs.capability.execution-role-awslogs"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.17"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
            },
            {
                "name": "ecs.capability.docker-plugin.local"
            },
            {
                "name": "ecs.capability.task-eni"
            },
            {
                "name": "ecs.capability.task-cpu-mem-limit"
            },
            {
                "name": "ecs.capability.secrets.ssm.bootstrap.log-driver"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.30"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.31"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.32"
            },
            {
                "name": "ecs.capability.execution-role-ecr-pull"
            },
            {
                "name": "ecs.capability.container-health-check"
            },
            {
                "value": "subnet-1234567890123467",
                "name": "ecs.subnet-id"
            },
            {
                "value": "us-west-2a",
                "name": "ecs.availability-zone"
            },
            {
                "value": "t2.micro",
                "name": "ecs.instance-type"
            },
            {
                "name": "com.amazonaws.ecs.capability.task-iam-role-network-host"
            },
            {
                "name": "ecs.capability.aws-appmesh"
            },
            {
                "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.24"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.25"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.26"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.27"
            },
            {
                "name": "com.amazonaws.ecs.capability.privileged-container"
            },
            {
                "name": "ecs.capability.container-ordering"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
            },
            {
                "value": "x86_64",
                "name": "ecs.cpu-architecture"
            },
            {
                "value": "93f43776-2018.10.0",
                "name": "ecs.capability.cni-plugin-version"
            },
            {
                "name": "ecs.capability.secrets.ssm.environment-variables"
            },
            {
                "name": "ecs.capability.pid-ipc-namespace-sharing"
            },
            {
                "name": "com.amazonaws.ecs.capability.ecr-auth"
            },
            {
                "value": "linux",
                "name": "ecs.os-type"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.20"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.21"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.22"
            },
            {
                "name": "ecs.capability.task-eia"
            },
            {
                "name": "ecs.capability.private-registry-authentication.secretsmanager"
            },
            {
                "name": "com.amazonaws.ecs.capability.task-iam-role"
            },
            {
                "name": "com.amazonaws.ecs.capability.docker-remote-api.1.23"
            }
        ],
        "pendingTasksCount": 0,
        "tags": [],
        "containerInstanceArn": "arn:aws:ecs:us-west-2:123456789012:container-instance/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "registeredResources": [
            {
                "integerValue": 1024,
                "doubleValue": 0.0,
                "type": "INTEGER",
                "longValue": 0,
                "name": "CPU"
            },
            {
                "integerValue": 985,
                "doubleValue": 0.0,
                "type": "INTEGER",
                "longValue": 0,
                "name": "MEMORY"
            },
            {
                "type": "STRINGSET",
                "integerValue": 0,
                "name": "PORTS",
                "stringSetValue": [
                    "22",
                    "2376",
                    "2375",
                    "51678",
                    "51679"
                ],
                "longValue": 0,
                "doubleValue": 0.0
            },
            {
                "type": "STRINGSET",
                "integerValue": 0,
                "name": "PORTS_UDP",
                "stringSetValue": [],
                "longValue": 0,
                "doubleValue": 0.0
            }
        ],
        "status": "INACTIVE",
        "registeredAt": 1557768075.681,
        "version": 4,
        "versionInfo": {
            "agentVersion": "1.27.0",
            "agentHash": "aabe65ee",
            "dockerVersion": "DockerVersion: 18.06.1-ce"
        },
        "attachments": [],
        "runningTasksCount": 0,
        "ec2InstanceId": "i-12345678901234678"
    }
}
```
詳細については、「*ECS デベロッパーガイド*」の[「コンテナインスタンスの登録解除](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deregister_container_instance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterContainerInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/deregister-container-instance.html)」を参照してください。

### `deregister-task-definition`
<a name="ecs_DeregisterTaskDefinition_cli_2_topic"></a>

次のコード例は、`deregister-task-definition` を使用する方法を示しています。

**AWS CLI**  
**タスク定義の登録を解除するには**  
次の `deregister-task-definition` の例では、デフォルトのリージョンで `curler` タスク定義の最初のリビジョンを登録解除します。  

```
aws ecs deregister-task-definition --task-definition curler:1
```
結果の出力では、タスク定義ステータスに `INACTIVE` が表示されることに注意してください。  

```
{
    "taskDefinition": {
        "status": "INACTIVE",
        "family": "curler",
        "volumes": [],
        "taskDefinitionArn": "arn:aws:ecs:us-west-2:123456789012:task-definition/curler:1",
        "containerDefinitions": [
            {
                "environment": [],
                "name": "curler",
                "mountPoints": [],
                "image": "curl:latest",
                "cpu": 100,
                "portMappings": [],
                "entryPoint": [],
                "memory": 256,
                "command": [
                    "curl -v http://example.com/"
                ],
                "essential": true,
                "volumesFrom": []
            }
        ],
        "revision": 1
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS のタスク定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTaskDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/deregister-task-definition.html)」を参照してください。

### `describe-capacity-providers`
<a name="ecs_DescribeCapacityProviders_cli_2_topic"></a>

次のコード例は、`describe-capacity-providers` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのキャパシティプロバイダーを記述するには**  
次の `describe-capacity-providers` の例では、すべてのキャパシティプロバイダーの詳細を取得します。  

```
aws ecs describe-capacity-providers
```
出力:  

```
{
    "capacityProviders": [
        {
            "capacityProviderArn": "arn:aws:ecs:us-west-2:123456789012:capacity-provider/MyCapacityProvider",
            "name": "MyCapacityProvider",
            "status": "ACTIVE",
            "autoScalingGroupProvider": {
                "autoScalingGroupArn": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:autoScalingGroupName/MyAutoScalingGroup",
                "managedScaling": {
                    "status": "ENABLED",
                    "targetCapacity": 100,
                    "minimumScalingStepSize": 1,
                    "maximumScalingStepSize": 1000
                },
                "managedTerminationProtection": "ENABLED"
            },
            "tags": []
        },
        {
            "capacityProviderArn": "arn:aws:ecs:us-west-2:123456789012:capacity-provider/FARGATE",
            "name": "FARGATE",
            "status": "ACTIVE",
            "tags": []
        },
        {
            "capacityProviderArn": "arn:aws:ecs:us-west-2:123456789012:capacity-provider/FARGATE_SPOT",
            "name": "FARGATE_SPOT",
            "status": "ACTIVE",
            "tags": []
        }
    ]
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
**例 2: 特定のキャパシティプロバイダーを記述するには**  
次の `describe-capacity-providers` の例では、特定のキャパシティープロバイダーの詳細を取得します。`--include TAGS` パラメータを使用すると、キャパシティープロバイダーに関連付けられたタグが出力に追加されます。  

```
aws ecs describe-capacity-providers \
    --capacity-providers MyCapacityProvider \
    --include TAGS
```
出力:  

```
{
    "capacityProviders": [
        {
            "capacityProviderArn": "arn:aws:ecs:us-west-2:123456789012:capacity-provider/MyCapacityProvider",
            "name": "MyCapacityProvider",
            "status": "ACTIVE",
            "autoScalingGroupProvider": {
                "autoScalingGroupArn": "arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111:autoScalingGroupName/MyAutoScalingGroup",
                "managedScaling": {
                    "status": "ENABLED",
                    "targetCapacity": 100,
                    "minimumScalingStepSize": 1,
                    "maximumScalingStepSize": 1000
                },
                "managedTerminationProtection": "ENABLED"
            },
            "tags": [
                {
                    "key": "environment",
                    "value": "production"
                }
            ]
        }
    ]
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCapacityProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-capacity-providers.html)」を参照してください。

### `describe-clusters`
<a name="ecs_DescribeClusters_cli_2_topic"></a>

次のコード例は、`describe-clusters` を使用する方法を示しています。

**AWS CLI**  
**例 1: クラスターを記述するには**  
次の `describe-clusters` の例は、指定されたクラスターの詳細情報を取得します。  

```
aws ecs describe-clusters \
    --cluster default
```
出力:  

```
{
    "clusters": [
        {
            "status": "ACTIVE",
            "clusterName": "default",
            "registeredContainerInstancesCount": 0,
            "pendingTasksCount": 0,
            "runningTasksCount": 0,
            "activeServicesCount": 1,
            "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/default"
        }
    ],
    "failures": []
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS Clusters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html)」を参照してください。**  
**例 2: 添付ファイルオプションを使用してクラスターを記述するには**  
次の `describe-clusters` の例は、添付ファイルオプションを指定します。指定されたクラスターの詳細情報と、クラスターにアタッチされているリソースのリストを添付ファイルの形式で取得します。キャパシティプロバイダーをクラスターで使用する場合、AutoScaling プランまたはスケーリングポリシーのリソースは asp または as\$1policy ATTACHMENTS として表示されます。  

```
aws ecs describe-clusters \
    --include ATTACHMENTS \
    --clusters sampleCluster
```
出力:  

```
{
    "clusters": [
        {
            "clusterArn": "arn:aws:ecs:af-south-1:123456789222:cluster/sampleCluster",
            "clusterName": "sampleCluster",
            "status": "ACTIVE",
            "registeredContainerInstancesCount": 0,
            "runningTasksCount": 0,
            "pendingTasksCount": 0,
            "activeServicesCount": 0,
            "statistics": [],
            "tags": [],
            "settings": [],
            "capacityProviders": [
                "sampleCapacityProvider"
            ],
            "defaultCapacityProviderStrategy": [],
            "attachments": [
                {
                    "id": "a1b2c3d4-5678-901b-cdef-EXAMPLE22222",
                    "type": "as_policy",
                    "status": "CREATED",
                    "details": [
                        {
                            "name": "capacityProviderName",
                            "value": "sampleCapacityProvider"
                        },
                        {
                            "name": "scalingPolicyName",
                            "value": "ECSManagedAutoScalingPolicy-3048e262-fe39-4eaf-826d-6f975d303188"
                        }
                    ]
                }
            ],
            "attachmentsStatus": "UPDATE_COMPLETE"
        }
    ],
    "failures": []
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS Clusters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-clusters.html)」を参照してください。

### `describe-container-instances`
<a name="ecs_DescribeContainerInstances_cli_2_topic"></a>

次のコード例は、`describe-container-instances` を使用する方法を示しています。

**AWS CLI**  
**コンテナインスタンスを記述するには**  
次の `describe-container-instances` の例では、コンテナインスタンス UUID を識別子として使用して、`update` クラスター内のコンテナインスタンスの詳細を取得します。  

```
aws ecs describe-container-instances \
    --cluster update \
    --container-instances a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "failures": [],
    "containerInstances": [
        {
            "status": "ACTIVE",
            "registeredResources": [
                {
                    "integerValue": 2048,
                    "longValue": 0,
                    "type": "INTEGER",
                    "name": "CPU",
                    "doubleValue": 0.0
                },
                {
                    "integerValue": 3955,
                    "longValue": 0,
                    "type": "INTEGER",
                    "name": "MEMORY",
                    "doubleValue": 0.0
                },
                {
                    "name": "PORTS",
                    "longValue": 0,
                    "doubleValue": 0.0,
                    "stringSetValue": [
                        "22",
                        "2376",
                        "2375",
                        "51678"
                    ],
                    "type": "STRINGSET",
                    "integerValue": 0
                }
            ],
            "ec2InstanceId": "i-A1B2C3D4",
            "agentConnected": true,
            "containerInstanceArn": "arn:aws:ecs:us-west-2:123456789012:container-instance/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "pendingTasksCount": 0,
            "remainingResources": [
                {
                    "integerValue": 2048,
                    "longValue": 0,
                    "type": "INTEGER",
                    "name": "CPU",
                    "doubleValue": 0.0
                },
                {
                    "integerValue": 3955,
                    "longValue": 0,
                    "type": "INTEGER",
                    "name": "MEMORY",
                    "doubleValue": 0.0
                },
                {
                    "name": "PORTS",
                    "longValue": 0,
                    "doubleValue": 0.0,
                    "stringSetValue": [
                        "22",
                        "2376",
                        "2375",
                        "51678"
                    ],
                    "type": "STRINGSET",
                    "integerValue": 0
                }
            ],
            "runningTasksCount": 0,
            "versionInfo": {
                "agentVersion": "1.0.0",
                "agentHash": "4023248",
                "dockerVersion": "DockerVersion: 1.5.0"
            }
        }
    ]
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS コンテナインスタンス](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeContainerInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-container-instances.html)」を参照してください。

### `describe-service-deployments`
<a name="ecs_DescribeServiceDeployments_cli_2_topic"></a>

次のコード例は、`describe-service-deployments` を使用する方法を示しています。

**AWS CLI**  
**サービスデプロイの詳細を取得するには**  
次の `describe-service-deployments` の例では、ARN が `arn:aws:ecs:us-east-1:123456789012:service-deployment/example-cluster/example-service/ejGvqq2ilnbKT9qj0vLJe` のサービスデプロイの詳細を取得します。  

```
aws ecs describe-service-deployments \
    --service-deployment-arn arn:aws:ecs:us-east-1:123456789012:service-deployment/example-cluster/example-service/ejGvqq2ilnbKT9qj0vLJe
```
出力:  

```
{
    "serviceDeployments": [
        {
            "serviceDeploymentArn": "arn:aws:ecs:us-east-1:123456789012:service-deployment/example-cluster/example-service/ejGvqq2ilnbKT9qj0vLJe",
            "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/example-cluster/example-service",
            "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/example-cluster",
            "createdAt": "2024-10-31T08:03:30.917000-04:00",
            "startedAt": "2024-10-31T08:03:32.510000-04:00",
            "finishedAt": "2024-10-31T08:05:04.527000-04:00",
            "updatedAt": "2024-10-31T08:05:04.527000-04:00",
            "sourceServiceRevisions": [],
            "targetServiceRevision": {
                "arn": "arn:aws:ecs:us-east-1:123456789012:service-revision/example-cluster/example-service/1485800978477494678",
                "requestedTaskCount": 1,
                "runningTaskCount": 1,
                "pendingTaskCount": 0
            },
            "status": "SUCCESSFUL",
            "deploymentConfiguration": {
                "deploymentCircuitBreaker": {
                    "enable": true,
                    "rollback": true
                },
                "maximumPercent": 200,
                "minimumHealthyPercent": 100,
                "alarms": {
                    "alarmNames": [],
                    "rollback": false,
                    "enable": false
                }
            },
            "deploymentCircuitBreaker": {
                "status": "MONITORING_COMPLETE",
                "failureCount": 0,
                "threshold": 3
            },
            "alarms": {
                "status": "DISABLED"
            }
        }
    ],
    "failures": []
}
```
詳細については、*Amazon ECS デベロッパーガイド*の「[Amazon ECS サービスデプロイを使用してサービス履歴を表示する](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-deployment.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeServiceDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-service-deployments.html)」を参照してください。

### `describe-service-revisions`
<a name="ecs_DescribeServiceRevisions_cli_2_topic"></a>

次のコード例は、`describe-service-revisions` を使用する方法を示しています。

**AWS CLI**  
**サービスリビジョンの詳細を取得するには**  
次の `describe-service-revisions` の例では、ARN が `arn:aws:ecs:us-east-1:123456789012:service-revision/example-cluster/example-service/1485800978477494678` のサービスリビジョンの詳細を取得します。  

```
aws ecs describe-service-revisions \
    --service-revision-arns arn:aws:ecs:us-east-1:123456789012:service-revision/example-cluster/example-service/1485800978477494678
```
出力:  

```
{
    "serviceRevisions": [
        {
            "serviceRevisionArn": "arn:aws:ecs:us-east-1:123456789012:service-revision/example-cluster/example-service/1485800978477494678",
            "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/example-cluster/example-service",
            "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/example-cluster",
            "taskDefinition": "arn:aws:ecs:us-east-1:123456789012:task-definition/webserver:5",
            "capacityProviderStrategy": [
                {
                    "capacityProvider": "FARGATE",
                    "weight": 1,
                    "base": 0
                }
            ],
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-0d0eab1bb38d5ca64",
                        "subnet-0db5010045995c2d5"
                    ],
                    "securityGroups": [
                        "sg-02556bf85a191f59a"
                    ],
                    "assignPublicIp": "ENABLED"
                }
            },
            "containerImages": [
                {
                    "containerName": "aws-otel-collector",
                    "imageDigest": "sha256:7a1b3560655071bcacd66902c20ebe9a69470d5691fe3bd36baace7c2f3c4640",
                    "image": "public.ecr.aws/aws-observability/aws-otel-collector:v0.32.0"
                },
                {
                    "containerName": "web",
                    "imageDigest": "sha256:28402db69fec7c17e179ea87882667f1e054391138f77ffaf0c3eb388efc3ffb",
                    "image": "nginx"
                }
            ],
            "guardDutyEnabled": false,
            "serviceConnectConfiguration": {
                "enabled": false
            },
            "createdAt": "2024-10-31T08:03:29.302000-04:00"
        }
    ],
    "failures": []
}
```
詳細については、*Amazon ECS デベロッパーガイド*の「[Amazon ECS サービスリビジョン](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-revision.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeServiceRevisions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-service-revisions.html)」を参照してください。

### `describe-services`
<a name="ecs_DescribeServices_cli_2_topic"></a>

次のコード例は、`describe-services` を使用する方法を示しています。

**AWS CLI**  
**サービスを記述するには**  
次の `describe-services` の例では、デフォルトのクラスター内の `my-http-service` サービスの詳細を取得します。  

```
aws ecs describe-services --services my-http-service
```
出力:  

```
{
    "services": [
        {
            "status": "ACTIVE",
            "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/amazon-ecs-sample:1",
            "pendingCount": 0,
            "loadBalancers": [],
            "desiredCount": 10,
            "createdAt": 1466801808.595,
            "serviceName": "my-http-service",
            "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/default",
            "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/my-http-service",
            "deployments": [
                {
                    "status": "PRIMARY",
                    "pendingCount": 0,
                    "createdAt": 1466801808.595,
                    "desiredCount": 10,
                    "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/amazon-ecs-sample:1",
                    "updatedAt": 1428326312.703,
                    "id": "ecs-svc/1234567890123456789",
                    "runningCount": 10
                }
            ],
            "events": [
                {
                    "message": "(service my-http-service) has reached a steady state.",
                    "id": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
                    "createdAt": 1466801812.435
                }
            ],
            "runningCount": 10
        }
    ],
    "failures": []
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS サービス](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-services.html)」を参照してください。

### `describe-task-definition`
<a name="ecs_DescribeTaskDefinition_cli_2_topic"></a>

次のコード例は、`describe-task-definition` を使用する方法を示しています。

**AWS CLI**  
**タスク定義を記述するには**  
次の `describe-task-definition` の例は、タスク定義の詳細情報を取得します。  

```
aws ecs describe-task-definition \
    --task-definition hello_world:8
```
出力:  

```
{
    "taskDefinition": {
        "taskDefinitionArn": "arn:aws:ecs:us-east-1:012345678910:task-definition/hello_world:8",
        "containerDefinitions": [
            {
                "cpu": 10,
                "environment": [],
                "essential": true,
                "image": "wordpress",
                "links": [
                    "mysql"
                ] ,
                "memory": 500,
                "mountPoints": [],
                "name": "wordpress",
                "portMappings": [
                    {
                        "containerPort": 80,
                        "hostPort": 80
                    }
                ],
                "volumesFrom": []
            },
            {
                "cpu": 10,
                "environment": [
                    {
                        "name": "MYSQL_ROOT_PASSWORD",
                        "value": "password"
                    }
                ],
                "essential": true,
                "image": "mysql",
                "memory": 500,
                "mountPoints": [],
                "name": "mysql",
                "portMappings": [],
                "volumesFrom": []
            }
        ],
    "family": "hello_world",
    "revision": 8,
    "volumes": [],
    "status": "ACTIVE",
    "placementConstraints": [],
    "compatibilities": [
        "EXTERNAL",
        "EC2"
    ],
    "registeredAt": "2024-06-21T11:15:12.669000-05:00",
    "registeredBy": "arn:aws:sts::012345678910:assumed-role/demo-role/jane-doe"
    },
    "tags": []
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS のタスク定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTaskDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-task-definition.html)」を参照してください。

### `describe-task-sets`
<a name="ecs_DescribeTaskSets_cli_2_topic"></a>

次のコード例は、`describe-task-sets` を使用する方法を示しています。

**AWS CLI**  
**タスクセットを記述するには**  
次の `describe-task-sets` の例では、外部デプロイを使用するサービス内のタスクセットについて説明します。  

```
aws ecs describe-task-sets \
    --cluster MyCluster \
    --service MyService \
    --task-sets arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789
```
出力:  

```
{
    "taskSets": [
        {
            "id": "ecs-svc/1234567890123456789",
            "taskSetArn": "arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789",
            "status": "ACTIVE",
            "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sample-fargate:2",
            "computedDesiredCount": 0,
            "pendingCount": 0,
            "runningCount": 0,
            "createdAt": 1557207715.195,
            "updatedAt": 1557207740.014,
            "launchType": "EC2",
            "networkConfiguration": {
                "awsvpcConfiguration": {
                    "subnets": [
                        "subnet-12344321"
                    ],
                    "securityGroups": [
                        "sg-1234431"
                    ],
                    "assignPublicIp": "DISABLED"
                }
            },
            "loadBalancers": [],
            "serviceRegistries": [],
            "scale": {
                "value": 0.0,
                "unit": "PERCENT"
            },
            "stabilityStatus": "STEADY_STATE",
            "stabilityStatusAt": 1557207740.014
        }
    ],
    "failures": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTaskSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-task-sets.html)」を参照してください。

### `describe-tasks`
<a name="ecs_DescribeTasks_cli_2_topic"></a>

次の例は、`describe-tasks` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 単一のタスクを記述するには**  
次の `describe-tasks` の例は、クラスター内の単一のタスクの詳細情報を取得します。タスクの ID または完全な ARN を使用して、タスクを指定できます。この例では、タスクの完全な ARN を使用します。  

```
aws ecs describe-tasks \
    --cluster MyCluster \
    --tasks arn:aws:ecs:us-east-1:123456789012:task/MyCluster/4d590253bb114126b7afa7b58EXAMPLE
```
出力:  

```
{
    "tasks": [
        {
            "attachments": [],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "us-east-1b",
            "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/MyCluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2021-08-11T12:21:26.681000-04:00",
            "containerInstanceArn": "arn:aws:ecs:us-east-1:123456789012:container-instance/test/025c7e2c5e054a6790a29fc1fEXAMPLE",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:us-east-1:123456789012:container/MyCluster/4d590253bb114126b7afa7b58eea9221/a992d1cc-ea46-474a-b6e8-24688EXAMPLE",
                    "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/MyCluster/4d590253bb114126b7afa7b58EXAMPLE",
                    "name": "simple-app",
                    "image": "httpd:2.4",
                    "runtimeId": "91251eed27db90006ad67b1a08187290869f216557717dd5c39b37c94EXAMPLE",
                    "lastStatus": "RUNNING",
                    "networkBindings": [
                        {
                            "bindIP": "0.0.0.0",
                            "containerPort": 80,
                            "hostPort": 80,
                            "protocol": "tcp"
                        }
                    ],
                    "networkInterfaces": [],
                    "healthStatus": "UNKNOWN",
                    "cpu": "10",
                    "memory": "300"
                }
            ],
            "cpu": "10",
            "createdAt": "2021-08-11T12:21:26.681000-04:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:testupdate",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "EC2",
            "memory": "300",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "simple-app"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "pullStartedAt": "2021-08-11T12:21:28.234000-04:00",
            "pullStoppedAt": "2021-08-11T12:21:33.793000-04:00",
            "startedAt": "2021-08-11T12:21:34.945000-04:00",
            "startedBy": "ecs-svc/968695068243EXAMPLE",
            "tags": [],
            "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/MyCluster/4d590253bb114126b7afa7b58eea9221",
            "taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/console-sample-app-static2:1",
            "version": 2
        }
    ],
    "failures": []
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS のタスク定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)」を参照してください。**  
**例 2: 複数のタスクを記述するには**  
次の `describe-tasks` の例は、クラスター内の複数のタスクの詳細情報を取得します。タスクの ID または完全な ARN を使用して、タスクを指定できます。この例では、タスクの完全な ID を使用します。  

```
aws ecs describe-tasks \
    --cluster MyCluster \
    --tasks "74de0355a10a4f979ac495c14EXAMPLE" "d789e94343414c25b9f6bd59eEXAMPLE"
```
出力:  

```
{
    "tasks": [
        {
            "attachments": [
                {
                    "id": "d9e7735a-16aa-4128-bc7a-b2d51EXAMPLE",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-0d0eab1bb3EXAMPLE"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-0fa40520aeEXAMPLE"
                        },
                        {
                            "name": "macAddress",
                            "value": "0e:89:76:28:07:b3"
                        },
                        {
                            "name": "privateDnsName",
                            "value": "ip-10-0-1-184.ec2.internal"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.1.184"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "us-east-1b",
            "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/MyCluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2021-12-20T12:13:37.875000-05:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:us-east-1:123456789012:container/MyCluster/74de0355a10a4f979ac495c14EXAMPLE/aad3ba00-83b3-4dac-84d4-11f8cEXAMPLE",
                    "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/MyCluster/74de0355a10a4f979ac495c14EXAMPLE",
                    "name": "web",
                    "image": "nginx",
                    "runtimeId": "74de0355a10a4f979ac495c14EXAMPLE-265927825",
                    "lastStatus": "RUNNING",
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "d9e7735a-16aa-4128-bc7a-b2d51EXAMPLE",
                            "privateIpv4Address": "10.0.1.184"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "99",
                    "memory": "100"
                }
            ],
            "cpu": "256",
            "createdAt": "2021-12-20T12:13:20.226000-05:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:tdsevicetag",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "FARGATE",
            "memory": "512",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "web"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2021-12-20T12:13:42.665000-05:00",
            "pullStoppedAt": "2021-12-20T12:13:46.543000-05:00",
            "startedAt": "2021-12-20T12:13:48.086000-05:00",
            "startedBy": "ecs-svc/988401040018EXAMPLE",
            "tags": [],
            "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/MyCluster/74de0355a10a4f979ac495c14EXAMPLE",
            "taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/webserver:2",
            "version": 3,
            "ephemeralStorage": {
            "sizeInGiB": 20
            }
        },
        {
            "attachments": [
                {
                    "id": "214eb5a9-45cd-4bf8-87bc-57fefEXAMPLE",
                    "type": "ElasticNetworkInterface",
                    "status": "ATTACHED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-0d0eab1bb3EXAMPLE"
                        },
                        {
                            "name": "networkInterfaceId",
                            "value": "eni-064c7766daEXAMPLE"
                        },
                        {
                            "name": "macAddress",
                            "value": "0e:76:83:01:17:a9"
                        },
                        {
                            "name": "privateDnsName",
                            "value": "ip-10-0-1-41.ec2.internal"
                        },
                        {
                            "name": "privateIPv4Address",
                            "value": "10.0.1.41"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "us-east-1b",
            "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/MyCluster",
            "connectivity": "CONNECTED",
            "connectivityAt": "2021-12-20T12:13:35.243000-05:00",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:us-east-1:123456789012:container/MyCluster/d789e94343414c25b9f6bd59eEXAMPLE/9afef792-609b-43a5-bb6a-3efdbEXAMPLE",
                    "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/MyCluster/d789e94343414c25b9f6bd59eEXAMPLE",
                    "name": "web",
                    "image": "nginx",
                    "runtimeId": "d789e94343414c25b9f6bd59eEXAMPLE-265927825",
                    "lastStatus": "RUNNING",
                    "networkBindings": [],
                    "networkInterfaces": [
                        {
                            "attachmentId": "214eb5a9-45cd-4bf8-87bc-57fefEXAMPLE",
                            "privateIpv4Address": "10.0.1.41"
                        }
                    ],
                    "healthStatus": "UNKNOWN",
                    "cpu": "99",
                    "memory": "100"
                }
            ],
            "cpu": "256",
            "createdAt": "2021-12-20T12:13:20.226000-05:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "service:tdsevicetag",
            "healthStatus": "UNKNOWN",
            "lastStatus": "RUNNING",
            "launchType": "FARGATE",
            "memory": "512",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "web"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "pullStartedAt": "2021-12-20T12:13:44.611000-05:00",
            "pullStoppedAt": "2021-12-20T12:13:48.251000-05:00",
            "startedAt": "2021-12-20T12:13:49.326000-05:00",
            "startedBy": "ecs-svc/988401040018EXAMPLE",
            "tags": [],
            "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/MyCluster/d789e94343414c25b9f6bd59eEXAMPLE",
            "taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/webserver:2",
            "version": 3,
            "ephemeralStorage": {
                "sizeInGiB": 20
            }
        }
    ],
    "failures": []
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS のタスク定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/describe-tasks.html)」を参照してください。**

### `execute-command`
<a name="ecs_ExecuteCommand_cli_2_topic"></a>

次のコード例は、`execute-command` を使用する方法を示しています。

**AWS CLI**  
**インタラクティブ /bin/sh コマンドを実行するには**  
次の `execute-command` の例では、ID が `arn:aws:ecs:us-east-1:123456789012:task/MyCluster/d789e94343414c25b9f6bd59eEXAMPLE` のタスクで、MyContainer という名前のコンテナに対してインタラクティブな /bin/sh コマンドを実行します。  

```
aws ecs execute-command \
    --cluster MyCluster \
    --task arn:aws:ecs:us-east-1:123456789012:task/MyCluster/d789e94343414c25b9f6bd59eEXAMPLE \
    --container MyContainer \
    --interactive \
    --command "/bin/sh"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS Exec を使用してデバッグする](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExecuteCommand](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/execute-command.html)」を参照してください。

### `get-task-protection`
<a name="ecs_GetTaskProtection_cli_2_topic"></a>

次のコード例は、`get-task-protection` を使用する方法を示しています。

**AWS CLI**  
**ECS サービスでタスクの保護ステータスを取得する**  
次の `get-task-protection` は、Amazon ECS サービスに属する ECS タスクの保護ステータスを返します。  

```
aws ecs get-task-protection \
    --cluster ECS-project-update-cluster \
    --tasks c43ed3b1331041f289316f958adb6a24
```
出力:  

```
{
    "protectedTasks": [
        {
            "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/c43ed3b1331041f289316f958adb6a24",
            "protectionEnabled": false
        }
    ],
    "failures": []
}
```
タスク保護の詳細については、*Amazon ECS デベロッパーガイド*の「[Amazon ECS タスクがスケールインイベントによって終了するのを防ぐ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-scale-in-protection.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetTaskProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/get-task-protection.html)」を参照してください。

### `list-account-settings`
<a name="ecs_ListAccountSettings_cli_2_topic"></a>

次のコード例は、`list-account-settings` を使用する方法を示しています。

**AWS CLI**  
**例 1: アカウントのアカウント設定を表示するには**  
次の `list-account-settings` の例は、アカウントの有効なアカウント設定を示しています。  

```
aws ecs list-account-settings --effective-settings
```
出力:  

```
{
    "settings": [
        {
            "name": "containerInstanceLongArnFormat",
            "value": "enabled",
            "principalArn": "arn:aws:iam::123456789012:root"
        },
        {
            "name": "serviceLongArnFormat",
            "value": "enabled",
            "principalArn": "arn:aws:iam::123456789012:root"
        },
        {
            "name": "taskLongArnFormat",
            "value": "enabled",
            "principalArn": "arn:aws:iam::123456789012:root"
        }
    ]
}
```
**例 2: 特定の IAM ユーザーまたは IAM ロールのアカウント設定を表示するには**  
次の `list-account-settings` の例では、指定された IAM ユーザーまたは IAM ロールのアカウント設定を表示します。  

```
aws ecs list-account-settings --principal-arn arn:aws:iam::123456789012:user/MyUser
```
出力:  

```
{
    "settings": [
        {
            "name": "serviceLongArnFormat",
            "value": "enabled",
            "principalArn": "arn:aws:iam::123456789012:user/MyUser"
        }
    ]
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon リソースネーム (ARN) と ID](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-resource-ids.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccountSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-account-settings.html)」を参照してください。

### `list-attributes`
<a name="ecs_ListAttributes_cli_2_topic"></a>

次のコード例は、`list-attributes` を使用する方法を示しています。

**AWS CLI**  
**特定の属性を含むコンテナインスタンスを一覧表示するには**  
次の例では、デフォルトクラスターに `stack=production` 属性を持つコンテナインスタンスの属性を一覧表示します。  

```
aws ecs list-attributes \
    --target-type container-instance \
    --attribute-name stack \
    --attribute-value production \
    --cluster default
```
出力:  

```
{
    "attributes": [
        {
            "name": "stack",
            "targetId": "arn:aws:ecs:us-west-2:130757420319:container-instance/1c3be8ed-df30-47b4-8f1e-6e68ebd01f34",
            "value": "production"
        }
    ]
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS コンテナエージェントの設定](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-config.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-attributes.html)」を参照してください。

### `list-clusters`
<a name="ecs_ListClusters_cli_2_topic"></a>

次のコード例は、`list-clusters` を使用する方法を示しています。

**AWS CLI**  
**使用可能なクラスターを一覧表示するには**  
次の `list-clusters` の例は、使用可能なすべてのクラスターを一覧表示します。  

```
aws ecs list-clusters
```
出力:  

```
{
    "clusterArns": [
        "arn:aws:ecs:us-west-2:123456789012:cluster/MyECSCluster1",
        "arn:aws:ecs:us-west-2:123456789012:cluster/AnotherECSCluster"
    ]
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS Clusters](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_clusters.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-clusters.html)」を参照してください。**

### `list-container-instances`
<a name="ecs_ListContainerInstances_cli_2_topic"></a>

次のコード例は、`list-container-instances` を使用する方法を示しています。

**AWS CLI**  
**クラスター内のコンテナインスタンスを一覧表示するには**  
次の `list-container-instances` の例は、クラスターで使用可能なすべてのコンテナインスタンスを一覧表示します。  

```
aws ecs list-container-instances --cluster MyCluster
```
出力:  

```
{
    "containerInstanceArns": [
        "arn:aws:ecs:us-west-2:123456789012:container-instance/MyCluster/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "arn:aws:ecs:us-west-2:123456789012:container-instance/MyCluster/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE"
    ]
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS コンテナインスタンス](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListContainerInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-container-instances.html)」を参照してください。

### `list-service-deployments`
<a name="ecs_ListServiceDeployments_cli_2_topic"></a>

次のコード例は、`list-service-deployments` を使用する方法を示しています。

**AWS CLI**  
**サービスデプロイを一覧表示するには**  
次の `list-service-deployments` の例では、`example-service` という名前のサービスのサービスデプロイを取得します。  

```
aws ecs list-service-deployments \
    --service arn:aws:ecs:us-east-1:123456789012:service/example-cluster/example-service
```
出力:  

```
{
    "serviceDeployments": [
        {
            "serviceDeploymentArn": "arn:aws:ecs:us-east-1:123456789012:service-deployment/example-cluster/example-service/ejGvqq2ilnbKT9qj0vLJe",
            "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/example-cluster/example-service",
            "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/example-cluster",
            "startedAt": "2024-10-31T08:03:32.510000-04:00",
            "createdAt": "2024-10-31T08:03:30.917000-04:00",
            "finishedAt": "2024-10-31T08:05:04.527000-04:00",
            "targetServiceRevisionArn": "arn:aws:ecs:us-east-1:123456789012:service-revision/example-cluster/example-service/1485800978477494678",
            "status": "SUCCESSFUL"
        }
    ]
}
```
詳細については、*Amazon ECS デベロッパーガイド*の「[Amazon ECS サービスデプロイを使用してサービス履歴を表示する](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-deployment.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListServiceDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-service-deployments.html)」を参照してください。

### `list-services-by-namespace`
<a name="ecs_ListServicesByNamespace_cli_2_topic"></a>

次のコード例は、`list-services-by-namespace` を使用する方法を示しています。

**AWS CLI**  
**名前空間内のサービスを一覧表示するには**  
次の `list-services-by-namespace` の例では、デフォルトのリージョンで指定された名前空間に対して設定されたすべてのサービスを一覧表示します。  

```
aws ecs list-services-by-namespace \
    --namespace service-connect
```
出力:  

```
{
    "serviceArns": [
        "arn:aws:ecs:us-west-2:123456789012:service/MyCluster/MyService",
        "arn:aws:ecs:us-west-2:123456789012:service/tutorial/service-connect-nginx-service"
    ]
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Service Connect](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServicesByNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-services-by-namespace.html)」を参照してください。

### `list-services`
<a name="ecs_ListServices_cli_2_topic"></a>

次のコード例は、`list-services` を使用する方法を示しています。

**AWS CLI**  
**クラスター内のサービスを一覧表示するには**  
次の `list-services` の例は、クラスターで実行中のサービスを一覧表示する方法を示しています。  

```
aws ecs list-services --cluster MyCluster
```
出力:  

```
 {
     "serviceArns": [
         "arn:aws:ecs:us-west-2:123456789012:service/MyCluster/MyService"
     ]
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS サービス](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_services.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-services.html)」を参照してください。**

### `list-tags-for-resource`
<a name="ecs_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、特定のクラスターのタグを一覧表示します。  

```
aws ecs list-tags-for-resource \
    --resource-arn arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster
```
出力:  

```
{
    "tags": [
        {
            "key": "key1",
            "value": "value1"
        },
        {
            "key": "key2",
            "value": "value2"
        },
        {
            "key": "key3",
            "value": "value3"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-tags-for-resource.html)」を参照してください。

### `list-task-definition-families`
<a name="ecs_ListTaskDefinitionFamilies_cli_2_topic"></a>

次のコード例は、`list-task-definition-families` を使用する方法を示しています。

**AWS CLI**  
**例 1: 登録されたタスク定義ファミリーを一覧表示するには**  
次の `list-task-definition-families` の例では、登録されたすべてのタスク定義ファミリーを一覧表示します。  

```
aws ecs list-task-definition-families
```
出力:  

```
{
    "families": [
        "node-js-app",
        "web-timer",
        "hpcc",
        "hpcc-c4-8xlarge"
    ]
}
```
**例 2: 登録されたタスク定義ファミリーをフィルタリングするには**  
次の `list-task-definition-families` の例では、「hpcc」で始まるタスク定義のリビジョンを一覧表示します。  

```
aws ecs list-task-definition-families --family-prefix hpcc
```
出力:  

```
{
    "families": [
        "hpcc",
        "hpcc-c4-8xlarge"
    ]
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[タスク定義のパラメータ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#family)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTaskDefinitionFamilies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-task-definition-families.html)」を参照してください。

### `list-task-definitions`
<a name="ecs_ListTaskDefinitions_cli_2_topic"></a>

次のコード例は、`list-task-definitions` を使用する方法を示しています。

**AWS CLI**  
**例 1: 登録されたタスク定義を一覧表示するには**  
次の `list-task-definitions` の例では、登録されたすべてのタスク定義を一覧表示します。  

```
aws ecs list-task-definitions
```
出力:  

```
{
    "taskDefinitionArns": [
        "arn:aws:ecs:us-west-2:123456789012:task-definition/sleep300:2",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/sleep360:1",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:3",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:4",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:5",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:6"
    ]
}
```
**例 2: ファミリーに登録されたタスク定義を一覧表示するには**  
次の list-task-definitions の例では、指定されたファミリーのタスク定義リビジョンを一覧表示します。  

```
aws ecs list-task-definitions --family-prefix wordpress
```
出力:  

```
{
    "taskDefinitionArns": [
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:3",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:4",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:5",
        "arn:aws:ecs:us-west-2:123456789012:task-definition/wordpress:6"
    ]
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS のタスク定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTaskDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-task-definitions.html)」を参照してください。

### `list-tasks`
<a name="ecs_ListTasks_cli_2_topic"></a>

次のコード例は、`list-tasks` を使用する方法を示しています。

**AWS CLI**  
**例 1: クラスター内のタスクを一覧表示するには**  
次の `list-tasks` の例は、クラスター内のすべてのタスクを一覧表示します。  

```
aws ecs list-tasks --cluster default
```
出力:  

```
{
    "taskArns": [
        "arn:aws:ecs:us-west-2:123456789012:task/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "arn:aws:ecs:us-west-2:123456789012:task/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE"
    ]
}
```
**例 2: 特定のコンテナインスタンスのタスクを一覧表示するには**  
次の `list-tasks` の例は、コンテナインスタンスの UUID をフィルタとして使用して、コンテナインスタンスのタスクを一覧表示します。  

```
aws ecs list-tasks --cluster default --container-instance a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
```
出力:  

```
{
    "taskArns": [
        "arn:aws:ecs:us-west-2:123456789012:task/a1b2c3d4-5678-90ab-cdef-44444EXAMPLE"
    ]
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS のタスク定義](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/list-tasks.html)」を参照してください。**

### `put-account-setting-default`
<a name="ecs_PutAccountSettingDefault_cli_2_topic"></a>

次のコード例は、`put-account-setting-default` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのアカウント設定を変更するには**  
次の `put-account-setting-default` の例では、アカウントのすべての IAM ユーザーまたはロールのデフォルトアカウント設定を変更します。これらの変更は、IAM ユーザーまたはロールがこれらの設定を明示的に上書きしない限り、 AWS アカウント全体に適用されます。  

```
aws ecs put-account-setting-default --name serviceLongArnFormat --value enabled
```
出力:  

```
{
    "setting": {
        "name": "serviceLongArnFormat",
        "value": "enabled",
        "principalArn": "arn:aws:iam::123456789012:root"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon リソースネーム (ARN) と ID](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-resource-ids.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAccountSettingDefault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/put-account-setting-default.html)」を参照してください。

### `put-account-setting`
<a name="ecs_PutAccountSetting_cli_2_topic"></a>

次のコード例は、`put-account-setting` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーアカウントのアカウント設定を変更するには**  
次の `put-account-setting` の例では、IAM ユーザーアカウントの `containerInsights` アカウント設定を `enhanced` に設定します。これにより、オブザーバビリティが強化された Container Insights が有効になります。  

```
aws ecs put-account-setting \
    --name containerInsights \
    --value enhanced
```
出力:  

```
{
    "setting": {
        "name": "containerInsights",
        "value": "enhanced",
        "principalArn": "arn:aws:iam::123456789012:user/johndoe",
        "type": "user"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[アカウント設定の変更](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-modifying-longer-id-settings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAccountSetting](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/put-account-setting.html)」を参照してください。

### `put-account-settings`
<a name="ecs_PutAccountSettings_cli_2_topic"></a>

次のコード例は、`put-account-settings` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーまたは IAM ロールのアカウント設定を変更するには**  
次の `put-account-setting` の例では、指定された IAM ユーザーまたは IAM ロールのアカウント設定を変更します。  

```
aws ecs put-account-setting \
    --name serviceLongArnFormat \
    --value enabled \
    --principal-arn arn:aws:iam::123456789012:user/MyUser
```
出力:  

```
{
    "setting": {
        "name": "serviceLongArnFormat",
        "value": "enabled",
        "principalArn": "arn:aws:iam::123456789012:user/MyUser"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAccountSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/put-account-settings.html)」を参照してください。

### `put-attributes`
<a name="ecs_PutAttributes_cli_2_topic"></a>

次のコード例は、`put-attributes` を使用する方法を示しています。

**AWS CLI**  
**属性を作成して Amazon ECS リソースに関連付けるには**  
次の `put-attributes` では、名前 stack と値 production を含む属性をコンテナインスタンスに適用します。  

```
aws ecs put-attributes \
    --attributes name=stack,value=production,targetId=arn:aws:ecs:us-west-2:130757420319:container-instance/1c3be8ed-df30-47b4-8f1e-6e68ebd01f34
```
出力:  

```
{
    "attributes": [
        {
            "name": "stack",
            "targetId": "arn:aws:ecs:us-west-2:130757420319:container-instance/1c3be8ed-df30-47b4-8f1e-6e68ebd01f34",
            "value": "production"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/put-attributes.html)」を参照してください。

### `put-cluster-capacity-providers`
<a name="ecs_PutClusterCapacityProviders_cli_2_topic"></a>

次のコード例は、`put-cluster-capacity-providers` を使用する方法を示しています。

**AWS CLI**  
**例 1: 既存のキャパシティプロバイダーをクラスターに追加するには**  
次の `put-cluster-capacity-providers` の例では、既存のキャパシティープロバイダーをクラスターに追加します。キャパシティープロバイダーを作成するには、`create-capacity-provider` コマンドを使用します。`describe-clusters` コマンドは、現在のキャパシティープロバイダーとクラスターに関連付けられたデフォルトのキャパシティープロバイダー戦略を記述するために使用されます。新しいキャパシティープロバイダーをクラスターに追加するときは、クラスターに関連付ける新しいキャパシティープロバイダーに加えて、既存のすべてのキャパシティープロバイダーを指定する必要があります。また、クラスターに関連付けるデフォルトのキャパシティープロバイダー戦略も指定する必要があります。この例では、`MyCluster` クラスターは関連付けられた `MyCapacityProvider1` キャパシティープロバイダーがあり、`MyCapacityProvider2` キャパシティープロバイダーを追加して、それをデフォルトのキャパシティープロバイダー戦略に含めることで、タスクが両方のキャパシティープロバイダーに均等に分散されるようにしようとしています。  

```
aws ecs put-cluster-capacity-providers \
    --cluster MyCluster \
    --capacity-providers MyCapacityProvider1 MyCapacityProvider2 \
    --default-capacity-provider-strategy capacityProvider=MyCapacityProvider1,weight=1 capacityProvider=MyCapacityProvider2,weight=1
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "clusterName": "MyCluster",
        "status": "ACTIVE",
        "registeredContainerInstancesCount": 0,
        "runningTasksCount": 0,
        "pendingTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "tags": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "enabled"
            }
        ],
        "capacityProviders": [
            "MyCapacityProvider1",
            "MyCapacityProvider2"
        ],
        "defaultCapacityProviderStrategy": [
            {
                "capacityProvider": "MyCapacityProvider1",
                "weight": 1,
                "base": 0
            },
            {
                "capacityProvider": "MyCapacityProvider2",
                "weight": 1,
                "base": 0
            }
        ],
        "attachments": [
           {
                "id": "0fb0c8f4-6edd-4de1-9b09-17e470ee1918",
                "type": "as_policy",
                "status": "ACTIVE",
                "details": [
                    {
                        "name": "capacityProviderName",
                        "value": "MyCapacityProvider1"
                    },
                    {
                        "name": "scalingPolicyName",
                        "value": "ECSManagedAutoScalingPolicy-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
                    }
                ]
            },
            {
                "id": "ae592060-2382-4663-9476-b015c685593c",
                "type": "as_policy",
                "status": "ACTIVE",
                "details": [
                    {
                        "name": "capacityProviderName",
                        "value": "MyCapacityProvider2"
                    },
                    {
                        "name": "scalingPolicyName",
                        "value": "ECSManagedAutoScalingPolicy-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
                    }
                ]
            }
        ],
        "attachmentsStatus": "UPDATE_IN_PROGRESS"
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
**例 2: クラスターからキャパシティプロバイダーを削除するには**  
次の `put-cluster-capacity-providers` の例では、クラスターからキャパシティプロバイダーを削除します。`describe-clusters` コマンドは、クラスターに関連付けられている現在のキャパシティプロバイダーを記述するために使用されます。クラスターからキャパシティープロバイダーを削除するときは、クラスターに関連付けられたままにするキャパシティープロバイダーと、クラスターに関連付けるデフォルトのキャパシティープロバイダー戦略を指定する必要があります。この例では、クラスターに `MyCapacityProvider1` と `MyCapacityProvider2` キャパシティープロバイダーが関連付けられており、`MyCapacityProvider2` キャパシティープロバイダーを削除しようと思っています。そのため、更新されたデフォルトのキャパシティープロバイダー戦略とともにコマンドで `MyCapacityProvider1` のみを指定します。  

```
aws ecs put-cluster-capacity-providers \
    --cluster MyCluster \
    --capacity-providers MyCapacityProvider1 \
    --default-capacity-provider-strategy capacityProvider=MyCapacityProvider1,weight=1,base=0
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "clusterName": "MyCluster",
        "status": "ACTIVE",
        "registeredContainerInstancesCount": 0,
        "runningTasksCount": 0,
        "pendingTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "tags": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "enabled"
            }
        ],
        "capacityProviders": [
            "MyCapacityProvider1"
        ],
        "defaultCapacityProviderStrategy": [
            "capacityProvider": "MyCapacityProvider1",
            "weight": 1,
            "base": 0
        ],
        "attachments": [
           {
                "id": "0fb0c8f4-6edd-4de1-9b09-17e470ee1918",
                "type": "as_policy",
                "status": "ACTIVE",
                "details": [
                    {
                        "name": "capacityProviderName",
                        "value": "MyCapacityProvider1"
                    },
                    {
                        "name": "scalingPolicyName",
                        "value": "ECSManagedAutoScalingPolicy-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
                    }
                ]
            },
            {
                "id": "ae592060-2382-4663-9476-b015c685593c",
                "type": "as_policy",
                "status": "DELETING",
                "details": [
                    {
                        "name": "capacityProviderName",
                        "value": "MyCapacityProvider2"
                    },
                    {
                        "name": "scalingPolicyName",
                        "value": "ECSManagedAutoScalingPolicy-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
                    }
                ]
            }
        ],
        "attachmentsStatus": "UPDATE_IN_PROGRESS"
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
**例 3: クラスターからすべてのキャパシティプロバイダーを削除するには**  
次の `put-cluster-capacity-providers` の例では、クラスターからすべての既存のキャパシティプロバイダーを削除します。  

```
aws ecs put-cluster-capacity-providers \
    --cluster MyCluster \
    --capacity-providers [] \
    --default-capacity-provider-strategy []
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster",
        "clusterName": "MyCluster",
        "status": "ACTIVE",
        "registeredContainerInstancesCount": 0,
        "runningTasksCount": 0,
        "pendingTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "tags": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "enabled"
            }
        ],
        "capacityProviders": [],
        "defaultCapacityProviderStrategy": [],
        "attachments": [
           {
                "id": "0fb0c8f4-6edd-4de1-9b09-17e470ee1918",
                "type": "as_policy",
                "status": "DELETING",
                "details": [
                    {
                        "name": "capacityProviderName",
                        "value": "MyCapacityProvider1"
                    },
                    {
                        "name": "scalingPolicyName",
                        "value": "ECSManagedAutoScalingPolicy-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
                    }
                ]
            },
            {
                "id": "ae592060-2382-4663-9476-b015c685593c",
                "type": "as_policy",
                "status": "DELETING",
                "details": [
                    {
                        "name": "capacityProviderName",
                        "value": "MyCapacityProvider2"
                    },
                    {
                        "name": "scalingPolicyName",
                        "value": "ECSManagedAutoScalingPolicy-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
                    }
                ]
            }
        ],
        "attachmentsStatus": "UPDATE_IN_PROGRESS"
    }
}
```
詳細については、「Amazon ECS ディベロッパーガイド」の「[Amazon ECS キャパシティープロバイダー](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutClusterCapacityProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/put-cluster-capacity-providers.html)」を参照してください。

### `register-task-definition`
<a name="ecs_RegisterTaskDefinition_cli_2_topic"></a>

次のコード例は、`register-task-definition` を使用する方法を示しています。

**AWS CLI**  
**例 1: タスク定義を JSON ファイルに登録するには**  
次の `register-task-definition` の例では、タスク定義を指定されたファミリーに登録します。コンテナ定義は、指定されたファイルの場所に JSON 形式で保存されます。  

```
aws ecs register-task-definition \
    --cli-input-json file://<path_to_json_file>/sleep360.json
```
`sleep360.json` の内容:  

```
{
    "containerDefinitions": [
        {
            "name": "sleep",
            "image": "busybox",
            "cpu": 10,
            "command": [
                "sleep",
                "360"
            ],
            "memory": 10,
            "essential": true
        }
    ],
    "family": "sleep360"
}
```
出力:  

```
{
    "taskDefinition": {
        "status": "ACTIVE",
        "family": "sleep360",
        "placementConstraints": [],
        "compatibilities": [
                "EXTERNAL",
                "EC2"
        ],
        "volumes": [],
        "taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/sleep360:1",
        "containerDefinitions": [
            {
                "environment": [],
                "name": "sleep",
                "mountPoints": [],
                "image": "busybox",
                "cpu": 10,
                "portMappings": [],
                "command": [
                    "sleep",
                    "360"
                ],
        "memory": 10,
        "essential": true,
        "volumesFrom": []
        }
    ],
        "revision": 1
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[タスク定義の例](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/example_task_definitions.html)」を参照してください。  
**例 2: タスク定義を JSON 文字列パラメータに登録するには**  
次の `register-task-definition` の例では、エスケープされた二重引用符を持つ JSON 文字列パラメータとして提供されるコンテナ定義を使用してタスク定義を登録します。  

```
aws ecs register-task-definition \
    --family sleep360 \
    --container-definitions "[{\"name\":\"sleep\",\"image\":\"busybox\",\"cpu\":10,\"command\":[\"sleep\",\"360\"],\"memory\":10,\"essential\":true}]"
```
出力は前の例と同じです。  
詳細については、「*Amazon ECS デベロッパーガイド*」の「[タスク定義の作成](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTaskDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/register-task-definition.html)」を参照してください。

### `run-task`
<a name="ecs_RunTask_cli_2_topic"></a>

次のコード例は、`run-task` を使用する方法を示しています。

**AWS CLI**  
**例 1: デフォルトのクラスターでタスクを実行するには**  
次の `run-task` の例では、デフォルトのクラスターでタスクを実行し、クライアントトークンを使用します。  

```
aws ecs run-task \
    --cluster default \
    --task-definition sleep360:1 \
    --client-token 550e8400-e29b-41d4-a716-446655440000
```
出力:  

```
{
    "tasks": [
        {
            "attachments": [],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "us-east-1b",
            "capacityProviderName": "example-capacity-provider",
            "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/default",
            "containerInstanceArn": "arn:aws:ecs:us-east-1:123456789012:container-instance/default/bc4d2ec611d04bb7bb97e83ceEXAMPLE",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:us-east-1:123456789012:container/default/d6f51cc5bbc94a47969c92035e9f66f8/75853d2d-711e-458a-8362-0f0aEXAMPLE",
                    "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/default/d6f51cc5bbc94a47969c9203EXAMPLE",
                    "name": "sleep",
                    "image": "busybox",
                    "lastStatus": "PENDING",
                    "networkInterfaces": [],
                    "cpu": "10",
                    "memory": "10"
                }
            ],
            "cpu": "10",
            "createdAt": "2023-11-21T16:59:34.403000-05:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "family:sleep360",
            "lastStatus": "PENDING",
            "launchType": "EC2",
            "memory": "10",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "sleep"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "tags": [],
            "taskArn": "arn:aws:ecs:us-east-1:123456789012:task/default/d6f51cc5bbc94a47969c9203EXAMPLE",
            "taskDefinitionArn": "arn:aws:ecs:us-east-1:123456789012:task-definition/sleep360:1",
            "version": 1
        }
    ],
    "failures": []
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[スタンドアロンタスクとしてのアプリケーションの実行](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/standalone-task-create.html)」を参照してください。  
**例 2: スタンドアロンタスクの Amazon EBS ボリュームを設定するには**  
次の `run-task` の例では、デフォルトのクラスターで Fargate タスク用に暗号化された Amazon EBS ボリュームを設定します。`AmazonECSInfrastructureRolePolicyForVolumes` マネージドポリシーがアタッチされた Amazon ECS インフラストラクチャロールを設定する必要があります。`run-task` リクエストと同じボリューム名でタスク定義を指定する必要があります。この例では、`--cli-input-json` オプションと JSON 入力ファイル (`ebs.json`) を使用します。  

```
aws ecs run-task \
    --cli-input-json file://ebs.json
```
`ebs.json` の内容:  

```
{
   "cluster": "default",
   "taskDefinition": "mytaskdef",
   "launchType": "FARGATE",
   "networkConfiguration":{
        "awsvpcConfiguration":{
            "assignPublicIp": "ENABLED",
            "securityGroups": ["sg-12344321"],
            "subnets":["subnet-12344321"]
        }
    },
   "volumeConfigurations": [
        {
            "name": "myEBSVolume",
            "managedEBSVolume": {
                "volumeType": "gp3",
                "sizeInGiB": 100,
                "roleArn":"arn:aws:iam::1111222333:role/ecsInfrastructureRole",
                "encrypted": true,
                "kmsKeyId": "arn:aws:kms:region:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"
            }
        }
    ]
}
```
出力:  

```
{
    "tasks": [
        {
            "attachments": [
                {
                    "id": "ce868693-15ca-4083-91ac-f782f64000c9",
                    "type": "ElasticNetworkInterface",
                    "status": "PRECREATED",
                    "details": [
                        {
                        "name": "subnetId",
                        "value": "subnet-070982705451dad82"
                        }
                    ]
                },
                {
                    "id": "a17ed863-786c-4372-b5b3-b23e53f37877",
                    "type": "AmazonElasticBlockStorage",
                    "status": "CREATED",
                    "details": [
                        {
                            "name": "roleArn",
                            "value": "arn:aws:iam::123456789012:role/ecsInfrastructureRole"
                        },
                        {
                            "name": "volumeName",
                            "value": "myEBSVolume"
                        },
                        {
                            "name": "deleteOnTermination",
                            "value": "true"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                }
            ],
            "availabilityZone": "us-west-2b",
            "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/default",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:us-west-2:123456789012:container/default/7f1fbd3629434cc4b82d72d2f09b67c9/e21962a2-f328-4699-98a3-5161ac2c186a",
                    "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/default/7f1fbd3629434cc4b82d72d2f09b67c9",
                    "name": "container-using-ebs",
                    "image": "amazonlinux:2",
                    "lastStatus": "PENDING",
                    "networkInterfaces": [],
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2025-01-23T10:29:46.650000-06:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "family:mytaskdef",
            "lastStatus": "PROVISIONING",
            "launchType": "FARGATE",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "container-using-ebs"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
            "platformVersion": "1.4.0",
            "platformFamily": "Linux",
            "tags": [],
            "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/default/7f1fbd3629434cc4b82d72d2f09b67c9",
            "taskDefinitionArn": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:4",
            "version": 1,
            "ephemeralStorage": {
                "sizeInGiB": 20
            },
            "fargateEphemeralStorage": {
                "sizeInGiB": 20
            }
        }
    ],
    "failures": []
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS での Amazon EBS ボリュームの使用](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-volumes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RunTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/run-task.html)」を参照してください。

### `start-task`
<a name="ecs_StartTask_cli_2_topic"></a>

次のコード例は、`start-task` を使用する方法を示しています。

**AWS CLI**  
**例 1: 新しいタスクを開始するには**  
次の `start-task` の例では、デフォルトクラスター内の指定されたコンテナインスタンスで、最新リビジョンの `sleep360` タスク定義を使用してタスクを開始します。  

```
aws ecs start-task \
    --task-definition sleep360 \
    --container-instances 765936fadbdd46b5991a4bd70c2a43d4
```
出力:  

```
{
    "tasks": [
        {
            "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/default/666fdccc2e2d4b6894dd422f4eeee8f8",
            "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/default",
            "taskDefinitionArn": "arn:aws:ecs:us-west-2:123456789012:task-definition/sleep360:3",
            "containerInstanceArn": "arn:aws:ecs:us-west-2:123456789012:container-instance/default/765936fadbdd46b5991a4bd70c2a43d4",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "sleep"
                    }
                ]
            },
            "lastStatus": "PENDING",
            "desiredStatus": "RUNNING",
            "cpu": "128",
            "memory": "128",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:us-west-2:123456789012:container/75f11ed4-8a3d-4f26-a33b-ad1db9e02d41",
                    "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/default/666fdccc2e2d4b6894dd422f4eeee8f8",
                    "name": "sleep",
                    "lastStatus": "PENDING",
                    "networkInterfaces": [],
                    "cpu": "10",
                    "memory": "10"
                }
            ],
            "version": 1,
            "createdAt": 1563421494.186,
            "group": "family:sleep360",
            "launchType": "EC2",
            "attachments": [],
            "tags": []
        }
    ],
    "failures": []
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS でコンテナをスケジュールする](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/scheduling_tasks.html)」を参照してください。  
**例 2: タスク開始時に Amazon EBS ボリュームを設定するには**  
次の `start-task` の例では、指定されたコンテナインスタンスのタスク用に暗号化された Amazon EBS ボリュームを設定します。`AmazonECSInfrastructureRolePolicyForVolumes` マネージドポリシーがアタッチされた Amazon ECS インフラストラクチャロールを設定する必要があります。`start-task` リクエストと同じボリューム名でタスク定義を指定する必要があります。この例では、`--cli-input-json` オプションと、以下の内容を含む JSON 入力ファイル (`ebs.json`) を使用します。  

```
aws ecs start-task \
    --cli-input-json file://ebs.json \
    --container-instances 765936fadbdd46b5991a4bd70c2a43d4
```
`ebs.json` の内容:  

```
{
   "cluster": "default",
   "taskDefinition": "mytaskdef",
   "networkConfiguration":{
        "awsvpcConfiguration":{
            "assignPublicIp": "ENABLED",
            "securityGroups": ["sg-12344321"],
            "subnets":["subnet-12344321"]
        }
    },
   "volumeConfigurations": [
        {
            "name": "myEBSVolume",
            "managedEBSVolume": {
                "volumeType": "gp3",
                "sizeInGiB": 100,
                "roleArn":"arn:aws:iam::123456789012:role/ecsInfrastructureRole",
                "encrypted": true,
                "kmsKeyId": "arn:aws:kms:region:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
            }
        }
    ]
}
```
出力:  

```
{
    "tasks": [
        {
            "attachments": [
                {
                    "id": "aea29489-9dcd-49f1-8164-4d91566e1113",
                    "type": "ElasticNetworkInterface",
                    "status": "PRECREATED",
                    "details": [
                        {
                            "name": "subnetId",
                            "value": "subnet-12344321"
                        }
                    ]
                },
                {
                    "id": "f29e1222-9a1e-410f-b499-a12a7cd6d42e",
                    "type": "AmazonElasticBlockStorage",
                    "status": "CREATED",
                    "details": [
                        {
                            "name": "roleArn",
                            "value": "arn:aws:iam::123456789012:role/ecsInfrastructureRole"
                        },
                        {
                            "name": "volumeName",
                            "value": "myEBSVolume"
                        },
                        {
                            "name": "deleteOnTermination",
                            "value": "true"
                        }
                    ]
                }
            ],
            "attributes": [
                {
                    "name": "ecs.cpu-architecture",
                    "value": "arm64"
                }
            ],
            "availabilityZone": "us-west-2c",
            "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/default",
            "containerInstanceArn": "arn:aws:ecs:us-west-2:123456789012:container-instance/default/765936fadbdd46b5991a4bd70c2a43d4",
            "containers": [
                {
                    "containerArn": "arn:aws:ecs:us-west-2:123456789012:container/default/bb122ace3ed84add92c00a351a03c69e/a4a9ed10-51c7-4567-9653-50e71b94f867",
                    "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/default/bb122ace3ed84add92c00a351a03c69e",
                    "name": "container-using-ebs",
                    "image": "amazonlinux:2",
                    "lastStatus": "PENDING",
                    "networkInterfaces": [],
                    "cpu": "0"
                }
            ],
            "cpu": "1024",
            "createdAt": "2025-01-23T14:51:05.191000-06:00",
            "desiredStatus": "RUNNING",
            "enableExecuteCommand": false,
            "group": "family:mytaskdef",
            "lastStatus": "PROVISIONING",
            "launchType": "EC2",
            "memory": "3072",
            "overrides": {
                "containerOverrides": [
                    {
                        "name": "container-using-ebs"
                    }
                ],
                "inferenceAcceleratorOverrides": []
            },
             "tags": [],
            "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/default/bb122ace3ed84add92c00a351a03c69e",
            "taskDefinitionArn": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:4",
            "version": 1
        }
    ],
    "failures": []
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS での Amazon EBS ボリュームの使用](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-volumes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/start-task.html)」を参照してください。

### `stop-task`
<a name="ecs_StopTask_cli_2_topic"></a>

次のコード例は、`stop-task` を使用する方法を示しています。

**AWS CLI**  
**タスクを停止するには**  
次の `stop-task` は、指定されたタスクがデフォルトのクラスターで実行されないようにします。  

```
aws ecs stop-task \
    --task 666fdccc2e2d4b6894dd422f4eeee8f8
```
出力:  

```
{
    "task": {
        "taskArn": "arn:aws:ecs:us-west-2:130757420319:task/default/666fdccc2e2d4b6894dd422f4eeee8f8",
        "clusterArn": "arn:aws:ecs:us-west-2:130757420319:cluster/default",
        "taskDefinitionArn": "arn:aws:ecs:us-west-2:130757420319:task-definition/sleep360:3",
        "containerInstanceArn": "arn:aws:ecs:us-west-2:130757420319:container-instance/default/765936fadbdd46b5991a4bd70c2a43d4",
        "overrides": {
            "containerOverrides": []
        },
        "lastStatus": "STOPPED",
        "desiredStatus": "STOPPED",
        "cpu": "128",
        "memory": "128",
        "containers": [],
        "version": 2,
        "stoppedReason": "Taskfailedtostart",
        "stopCode": "TaskFailedToStart",
        "connectivity": "CONNECTED",
        "connectivityAt": 1563421494.186,
        "pullStartedAt": 1563421494.252,
        "pullStoppedAt": 1563421496.252,
        "executionStoppedAt": 1563421497,
        "createdAt": 1563421494.186,
        "stoppingAt": 1563421497.252,
        "stoppedAt": 1563421497.252,
        "group": "family:sleep360",
        "launchType": "EC2",
        "attachments": [],
        "tags": []
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/stop-task.html)」を参照してください。

### `tag-resource`
<a name="ecs_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、指定されたリソースに単一のタグを追加します。  

```
aws ecs tag-resource \
    --resource-arn arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster
    --tags key=key1,value=value1
```
このコマンドでは何も出力されません。  
**リソースに複数のタグを追加するには**  
次の `tag-resource` の例では、指定されたリソースに複数のタグを追加します。  

```
aws ecs tag-resource \
--resource-arn arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster \
--tags key=key1,value=value1 key=key2,value=value2 key=key3,value=value3
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ecs_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `untag-resource` の例では、指定されたリソース共有から一覧表示されたタグを削除します。  

```
aws ecs untag-resource \
    --resource-arn arn:aws:ecs:us-west-2:123456789012:cluster/MyCluster \
    --tag-keys key1,key2
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/untag-resource.html)」を参照してください。

### `update-cluster-settings`
<a name="ecs_UpdateClusterSettings_cli_2_topic"></a>

次のコード例は、`update-cluster-settings` を使用する方法を示しています。

**AWS CLI**  
**クラスターの設定を変更するには**  
次の `update-cluster-settings`の例では、`MyCluster` クラスターに対して、オブザーバビリティが強化された CloudWatch Container Insights を有効にします。  

```
aws ecs update-cluster-settings \
    --cluster MyCluster \
    --settings name=containerInsights,value=enhanced
```
出力:  

```
{
    "cluster": {
        "clusterArn": "arn:aws:ecs:us-esat-1:123456789012:cluster/MyCluster",
        "clusterName": "default",
        "status": "ACTIVE",
        "registeredContainerInstancesCount": 0,
        "runningTasksCount": 0,
        "pendingTasksCount": 0,
        "activeServicesCount": 0,
        "statistics": [],
        "tags": [],
        "settings": [
            {
                "name": "containerInsights",
                "value": "enhanced"
            }
        ]
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[アカウント設定の変更](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-modifying-longer-id-settings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateClusterSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-cluster-settings.html)」を参照してください。

### `update-cluster`
<a name="ecs_UpdateCluster_cli_2_topic"></a>

次のコード例は、`update-cluster` を使用する方法を示しています。

**AWS CLI**  
**例 1: containerInsights を有効にして ECS クラスターを更新する**  
次の `update-cluster` では、作成済みのクラスターで containerInsights の値を `enabled` に更新します。デフォルトでは、これは無効になっています。  

```
aws ecs update-cluster \
    --cluster ECS-project-update-cluster \
    --settings name=containerInsights,value=enabled
```
出力:  

```
"cluster": {
    "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/ECS-project-update-cluster",
    "clusterName": "ECS-project-update-cluster",
    "status": "ACTIVE",
    "registeredContainerInstancesCount": 0,
    "runningTasksCount": 0,
    "pendingTasksCount": 0,
    "activeServicesCount": 0,
    "statistics": [],
    "tags": [],
    "settings": [
        {
            "name": "containerInsights",
            "value": "enabled"
        }
    ],
    "capacityProviders": [
        "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt"
    ],
    "defaultCapacityProviderStrategy": [
        {
            "capacityProvider": "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt",
            "weight": 1,
            "base": 0
        }
    ],
    "attachments": [
        {
            "id": "069d002b-7634-42e4-b1d4-544f4c8f6380",
            "type": "as_policy",
            "status": "CREATED",
            "details": [
                {
                    "name": "capacityProviderName",
                    "value": "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt"
                },
                {
                    "name": "scalingPolicyName",
                    "value": "ECSManagedAutoScalingPolicy-152363a6-8c65-484c-b721-42c3e070ae93"
                }
            ]
        },
        {
            "id": "08b5b6ca-45e9-4209-a65d-e962a27c490a",
            "type": "managed_draining",
            "status": "CREATED",
            "details": [
                {
                    "name": "capacityProviderName",
                    "value": "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt"
                },
                {
                    "name": "autoScalingLifecycleHookName",
                    "value": "ecs-managed-draining-termination-hook"
                }
            ]
        },
        {
            "id": "45d0b36f-8cff-46b6-9380-1288744802ab",
            "type": "sc",
            "status": "ATTACHED",
            "details": []
        }
    ],
    "attachmentsStatus": "UPDATE_COMPLETE",
    "serviceConnectDefaults": {
        "namespace": "arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-igwrsylmy3kwvcdx"
    }
}
```
**例 2: デフォルトの Service Connect 名前空間を設定して ECS クラスターを更新する**  
次の `update-cluster` は、デフォルトの Service Connect 名前空間を設定して ECS クラスターを更新します。  

```
aws ecs update-cluster \
    --cluster ECS-project-update-cluster \
    --service-connect-defaults namespace=test
```
出力:  

```
 {
     "cluster": {
         "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/ECS-project-update-cluster",
         "clusterName": "ECS-project-update-cluster",
         "status": "ACTIVE",
         "registeredContainerInstancesCount": 0,
         "runningTasksCount": 0,
         "pendingTasksCount": 0,
         "activeServicesCount": 0,
         "statistics": [],
         "tags": [],
         "settings": [
             {
                 "name": "containerInsights",
                 "value": "enabled"
             }
         ],
         "capacityProviders": [
             "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt"
         ],
         "defaultCapacityProviderStrategy": [
             {
                 "capacityProvider": "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt",
                 "weight": 1,
                 "base": 0
             }
         ],
         "attachments": [
             {
                 "id": "069d002b-7634-42e4-b1d4-544f4c8f6380",
                 "type": "as_policy",
                 "status": "CREATED",
                 "details": [
                     {
                         "name": "capacityProviderName",
                         "value": "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt"
                     },
                     {
                         "name": "scalingPolicyName",
                         "value": "ECSManagedAutoScalingPolicy-152363a6-8c65-484c-b721-42c3e070ae93"
                     }
                 ]
             },
             {
                 "id": "08b5b6ca-45e9-4209-a65d-e962a27c490a",
                 "type": "managed_draining",
                 "status": "CREATED",
                 "details": [
                     {
                         "name": "capacityProviderName",
                         "value": "Infra-ECS-Cluster-ECS-project-update-cluster-d6bb6d5b-EC2CapacityProvider-3fIpdkLywwFt"
                     },
                     {
                         "name": "autoScalingLifecycleHookName",
                         "value": "ecs-managed-draining-termination-hook"
                     }
                 ]
             },
             {
                 "id": "45d0b36f-8cff-46b6-9380-1288744802ab",
                 "type": "sc",
                 "status": "DELETED",
                 "details": []
             },
             {
                 "id": "3e6890c3-609c-4832-91de-d6ca891b3ef1",
                 "type": "sc",
                 "status": "ATTACHED",
                 "details": []
             },
             {
                 "id": "961b8ec1-c2f1-4070-8495-e669b7668e90",
                 "type": "sc",
                 "status": "DELETED",
                 "details": []
             }
         ],
         "attachmentsStatus": "UPDATE_COMPLETE",
         "serviceConnectDefaults": {
             "namespace": "arn:aws:servicediscovery:us-west-2:123456789012:namespace/ns-dtjmxqpfi46ht7dr"
         }
     }
}
```
Service Connect の詳細については、*Amazon ECS デベロッパーガイド*の「[Service Connect を使用して Amazon ECS サービスを短縮名で接続する](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-connect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-cluster.html)」を参照してください。

### `update-container-agent`
<a name="ecs_UpdateContainerAgent_cli_2_topic"></a>

次のコード例は、`update-container-agent` を使用する方法を示しています。

**AWS CLI**  
**Amazon ECS コンテナインスタンスのコンテナエージェントを更新するには**  
次の `update-container-agent` の例では、デフォルトのクラスターで指定されたコンテナインスタンスのコンテナエージェントを更新します。  

```
aws ecs update-container-agent --cluster default --container-instance a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "containerInstance": {
        "status": "ACTIVE",
...
        "agentUpdateStatus": "PENDING",
        "versionInfo": {
            "agentVersion": "1.0.0",
            "agentHash": "4023248",
            "dockerVersion": "DockerVersion: 1.5.0"
        }
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS コンテナエージェントの更新](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateContainerAgent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-container-agent.html)」を参照してください。

### `update-container-instances-state`
<a name="ecs_UpdateContainerInstancesState_cli_2_topic"></a>

次のコード例は、`update-container-instances-state` を使用する方法を示しています。

**AWS CLI**  
**コンテナインスタンスの状態を更新するには**  
次の `update-container-instances-state` は、指定されたコンテナインスタンスを `DRAINING` の状態を更新し、登録されているクラスターから削除します。  

```
aws ecs update-container-instances-state \
    --container-instances 765936fadbdd46b5991a4bd70c2a43d4 \
    --status DRAINING
```
出力:  

```
{
    "containerInstances": [
        {
            "containerInstanceArn": "arn:aws:ecs:us-west-2:130757420319:container-instance/default/765936fadbdd46b5991a4bd70c2a43d4",
            "ec2InstanceId": "i-013d87ffbb4d513bf",
            "version": 4390,
            "versionInfo": {
                "agentVersion": "1.29.0",
                "agentHash": "a190a73f",
                "dockerVersion": "DockerVersion:18.06.1-ce"
            },
            "remainingResources": [
                {
                    "name": "CPU",
                    "type": "INTEGER",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 1536
                },
                {
                    "name": "MEMORY",
                    "type": "INTEGER",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 2681
                },
                {
                    "name": "PORTS",
                    "type": "STRINGSET",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 0,
                    "stringSetValue": [
                        "22",
                        "2376",
                        "2375",
                        "51678",
                        "51679"
                    ]
                },
                {
                    "name": "PORTS_UDP",
                    "type": "STRINGSET",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 0,
                    "stringSetValue": []
                }
            ],
            "registeredResources": [
                {
                    "name": "CPU",
                    "type": "INTEGER",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 2048
                },
                {
                    "name": "MEMORY",
                    "type": "INTEGER",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 3705
                },
                {
                    "name": "PORTS",
                    "type": "STRINGSET",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 0,
                    "stringSetValue": [
                        "22",
                        "2376",
                        "2375",
                        "51678",
                        "51679"
                    ]
                },
                {
                    "name": "PORTS_UDP",
                    "type": "STRINGSET",
                    "doubleValue": 0,
                    "longValue": 0,
                    "integerValue": 0,
                    "stringSetValue": []
                }
            ],
            "status": "DRAINING",
            "agentConnected": true,
            "runningTasksCount": 2,
            "pendingTasksCount": 0,
            "attributes": [
                {
                    "name": "ecs.capability.secrets.asm.environment-variables"
                },
                {
                    "name": "ecs.capability.branch-cni-plugin-version",
                    "value": "e0703516-"
                },
                {
                    "name": "ecs.ami-id",
                    "value": "ami-00e0090ac21971297"
                },
                {
                    "name": "ecs.capability.secrets.asm.bootstrap.log-driver"
                },
                {
                    "name": "com.amazonaws.ecs.capability.logging-driver.none"
                },
                {
                    "name": "ecs.capability.ecr-endpoint"
                },
                {
                    "name": "ecs.capability.docker-plugin.local"
                },
                {
                    "name": "ecs.capability.task-cpu-mem-limit"
                },
                {
                    "name": "ecs.capability.secrets.ssm.bootstrap.log-driver"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.30"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.31"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.32"
                },
                {
                    "name": "ecs.availability-zone",
                    "value": "us-west-2c"
                },
                {
                    "name": "ecs.capability.aws-appmesh"
                },
                {
                    "name": "com.amazonaws.ecs.capability.logging-driver.awslogs"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.24"
                },
                {
                    "name": "ecs.capability.task-eni-trunking"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.25"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.26"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.27"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.28"
                },
                {
                    "name": "com.amazonaws.ecs.capability.privileged-container"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.29"
                },
                {
                    "name": "ecs.cpu-architecture",
                    "value": "x86_64"
                },
                {
                    "name": "com.amazonaws.ecs.capability.ecr-auth"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.20"
                },
                {
                    "name": "ecs.os-type",
                    "value": "linux"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.21"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.22"
                },
                {
                    "name": "ecs.capability.task-eia"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.23"
                },
                {
                    "name": "ecs.capability.private-registry-authentication.secretsmanager"
                },
                {
                    "name": "com.amazonaws.ecs.capability.logging-driver.syslog"
                },
                {
                    "name": "com.amazonaws.ecs.capability.logging-driver.json-file"
                },
                {
                    "name": "ecs.capability.execution-role-awslogs"
                },
                {
                    "name": "ecs.vpc-id",
                    "value": "vpc-1234"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.17"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.18"
                },
                {
                    "name": "com.amazonaws.ecs.capability.docker-remote-api.1.19"
                },
                {
                    "name": "ecs.capability.task-eni"
                },
                {
                    "name": "ecs.capability.execution-role-ecr-pull"
                },
                {
                    "name": "ecs.capability.container-health-check"
                },
                {
                    "name": "ecs.subnet-id",
                    "value": "subnet-1234"
                },
                {
                    "name": "ecs.instance-type",
                    "value": "c5.large"
                },
                {
                    "name": "com.amazonaws.ecs.capability.task-iam-role-network-host"
                },
                {
                    "name": "ecs.capability.container-ordering"
                },
                {
                    "name": "ecs.capability.cni-plugin-version",
                    "value": "91ccefc8-2019.06.0"
                },
                {
                    "name": "ecs.capability.pid-ipc-namespace-sharing"
                },
                {
                    "name": "ecs.capability.secrets.ssm.environment-variables"
                },
                {
                    "name": "com.amazonaws.ecs.capability.task-iam-role"
                }
            ],
            "registeredAt": 1560788724.507,
            "attachments": [],
            "tags": []
        }
    ],
    "failures": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateContainerInstancesState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-container-instances-state.html)」を参照してください。

### `update-service-primary-task-set`
<a name="ecs_UpdateServicePrimaryTaskSet_cli_2_topic"></a>

次のコード例は、`update-service-primary-task-set` を使用する方法を示しています。

**AWS CLI**  
**サービスのプライマリタスクセットを更新するには**  
次の `update-service-primary-task-set` の例では、指定されたサービスのプライマリタスクセットを更新します。  

```
aws ecs update-service-primary-task-set \
    --cluster MyCluster \
    --service MyService \
    --primary-task-set arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789
```
出力:  

```
{
    "taskSet": {
        "id": "ecs-svc/1234567890123456789",
        "taskSetArn": "arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789",
        "status": "PRIMARY",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sample-fargate:2",
        "computedDesiredCount": 1,
        "pendingCount": 0,
        "runningCount": 0,
        "createdAt": 1557128360.711,
        "updatedAt": 1557129412.653,
        "launchType": "EC2",
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321"
                ],
                "securityGroups": [
                    "sg-12344312"
                ],
                "assignPublicIp": "DISABLED"
            }
        },
        "loadBalancers": [],
        "serviceRegistries": [],
        "scale": {
            "value": 50.0,
            "unit": "PERCENT"
        },
        "stabilityStatus": "STABILIZING",
        "stabilityStatusAt": 1557129279.914
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServicePrimaryTaskSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-service-primary-task-set.html)」を参照してください。

### `update-service`
<a name="ecs_UpdateService_cli_2_topic"></a>

次のコード例は、`update-service` を使用する方法を示しています。

**AWS CLI**  
**例 1: サービスで使用されるタスク定義を変更するには**  
次の `update-service` の例は、`amazon-ecs-sample` タスク定義を使用するように `my-http-service` サービスを更新します。  

```
aws ecs update-service \
    --cluster test \
    --service my-http-service \
    --task-definition amazon-ecs-sample
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/test/my-http-service",
        "serviceName": "my-http-service",
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/test",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 2,
        "pendingCount": 0,
        "launchType": "FARGATE",
        "platformVersion": "1.4.0",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/amazon-ecs-sample:2",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": true,
                "rollback": true
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100,
            "alarms": {
                "alarmNames": [],
                "rollback": false,
                "enable": false
            }
        },
        "deployments": [
            {
                "id": "ecs-svc/7419115625193919142",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/amazon-ecs-sample:2",
                "desiredCount": 0,
                "pendingCount": 0,
                "runningCount": 0,
                "failedTasks": 0,
                "createdAt": "2025-02-21T13:26:02.734000-06:00",
                "updatedAt": "2025-02-21T13:26:02.734000-06:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321"
                        ],
                        "securityGroups": [
                            "sg-12344321"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "IN_PROGRESS",
                "rolloutStateReason": "ECS deployment ecs-svc/7419115625193919142 in progress."
            },
            {
                "id": "ecs-svc/1709597507655421668",
                "status": "ACTIVE",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/old-amazon-ecs-sample:4",
                "desiredCount": 2,
                "pendingCount": 0,
                "runningCount": 2,
                "failedTasks": 0,
                "createdAt": "2025-01-24T11:13:07.621000-06:00",
                "updatedAt": "2025-02-02T16:11:30.838000-06:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321"
                        ],
                        "securityGroups": [
                             "sg-12344321"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "COMPLETED",
                "rolloutStateReason": "ECS deployment ecs-svc/1709597507655421668 completed."
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [
            {
                "id": "e40b4d1c-80d9-4834-aaf3-6a268e530e17",
                "createdAt": "2025-02-21T10:31:26.037000-06:00",
                "message": "(my-http-service) has reached a steady state."
            },
            {
                "id": "6ac069ad-fc8b-4e49-a35d-b5574a964c8e",
                "createdAt": "2025-02-21T04:31:22.703000-06:00",
                "message": "(my-http-service) has reached a steady state."
            },
            {
                "id": "265f7d37-dfd1-4880-a846-ec486f341919",
                "createdAt": "2025-02-20T22:31:22.514000-06:00",
                "message": "(my-http-service) has reached a steady state."
            }
        ],
        "createdAt": "2024-10-30T17:12:43.218000-05:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321",
                ],
                "securityGroups": [
                    "sg-12344321"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::123456789012:role/AIDACKCEVSQ6C2EXAMPLE",
        "enableECSManagedTags": true,
        "propagateTags": "NONE",
        "enableExecuteCommand": false,
        "availabilityZoneRebalancing": "DISABLED"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[コンソールを使用した Amazon ECS サービスの更新](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-service-console-v2.html)」を参照してください。  
**例 2: サービス内のタスク数を変更するには**  
次の `update-service` の例では、`my-http-service` サービスの必要なタスク数を 2 に更新します。  

```
aws ecs update-service \
    --cluster MyCluster \
    --service my-http-service \
    --desired-count 2
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/MyCluster/my-http-service",
        "serviceName": "my-http-service",
        "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/MyCluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 1,
        "pendingCount": 0,
        "capacityProviderStrategy": [
            {
                "capacityProvider": "FARGATE",
                "weight": 1,
                "base": 0
            }
        ],
        "platformVersion": "LATEST",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:us-east-1:123456789012:task-definition/MyTaskDefinition",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": true,
                "rollback": true
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100,
            "alarms": {
                "alarmNames": [],
                "rollback": false,
                "enable": false
            }
        },
        "deployments": [
            {
                "id": "ecs-svc/1976744184940610707",
                "status": "PRIMARY",
                "taskkDefinition": "arn:aws:ecs:us-east-1:123456789012:task-definition/MyTaskDefinition",
                "desiredCount": 1,
                "pendingCount": 0,
                "runningCount": 1,
                "failedTasks": 0,
                "createdAt": "2024-12-03T16:24:25.225000-05:00",
                "updatedAt": "2024-12-03T16:25:15.837000-05:00",
                "capacityProviderStrategy": [
                    {
                        "capacityProvider": "FARGATE",
                        "weight": 1,
                        "base": 0
                    }
                ],
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-0d0eab1bb38d5ca64",
                            "subnet-0db5010045995c2d5"
                        ],
                        "securityGroups": [
                            "sg-02556bf85a191f59a"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "COMPLETED",
                "rolloutStateReason": "ECS deployment ecs-svc/1976744184940610707 completed."
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [
            {
                "id": "f27350b9-4b2a-4e2e-b72e-a4b68380de45",
                "createdAt": "2024-12-30T13:24:07.345000-05:00",
                "message": "(service my-http-service) has reached a steady state."
            },
            {
                "id": "e764ec63-f53f-45e3-9af2-d99f922d2957",
                "createdAt": "2024-12-30T12:32:21.600000-05:00",
                "message": "(service my-http-service) has reached a steady state."
            },
            {
                "id": "28444756-c2fa-47f8-bd60-93a8e05f3991",
                "createdAt": "2024-12-08T19:26:10.367000-05:00",
                "message": "(service my-http-service) has reached a steady state."
            }
        ],
        "createdAt": "2024-12-03T16:24:25.225000-05:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-0d0eab1bb38d5ca64",
                    "subnet-0db5010045995c2d5"
                ],
                "securityGroups": [
                    "sg-02556bf85a191f59a"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::123456789012:role/Admin",
        "enableECSManagedTags": true,
        "propagateTags": "NONE",
        "enableExecuteCommand": false,
        "availabilityZoneRebalancing": "ENABLED"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[コンソールを使用した Amazon ECS サービスの更新](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-service-console-v2.html)」を参照してください。  
**例 3: サービスの更新時にアタッチメント用に Amazon EBS ボリュームを設定するには**  
次の `update-service` の例では、Amazon EBS ボリュームを使用するように `my-http-service` サービスを更新します。`AmazonECSInfrastructureRolePolicyForVolumes` マネージドポリシーがアタッチされた Amazon ECS インフラストラクチャロールを設定する必要があります。また、`update-service` リクエストと同じボリューム名で、`configuredAtLaunch` を `true` に設定してタスク定義を指定する必要があります。この例では、`--cli-input-json` オプションと JSON 入力ファイル (`ebs.json`) を使用します。  

```
aws ecs update-service \
    --cli-input-json file://ebs.json
```
`ebs.json` の内容:  

```
{
   "cluster": "mycluster",
   "taskDefinition": "mytaskdef",
   "service": "my-http-service",
   "desiredCount": 2,
   "volumeConfigurations": [
        {
            "name": "myEbsVolume",
            "managedEBSVolume": {
                "roleArn":"arn:aws:iam::123456789012:role/ecsInfrastructureRole",
                "volumeType": "gp3",
                "sizeInGiB": 100,
                "iops": 3000,
                "throughput": 125,
                "filesystemType": "ext4"
            }
        }
   ]
}
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/mycluster/my-http-service",
        "serviceName": "my-http-service",
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/mycluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 2,
        "pendingCount": 0,
        "launchType": "FARGATE",
        "platformVersion": "LATEST",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:1",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": true,
                "rollback": true
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100,
            "alarms": {
                "alarmNames": [],
                "rollback": false,
                "enable": false
            }
        },
        "deployments": [
            {
                "id": "ecs-svc/2420458347226626275",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:1",
                "desiredCount": 0,
                "pendingCount": 0,
                "runningCount": 0,
                "failedTasks": 0,
                "createdAt": "2025-02-21T15:07:20.519000-06:00",
                "updatedAt": "2025-02-21T15:07:20.519000-06:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321",
                        ],
                        "securityGroups": [
                            "sg-12344321"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "IN_PROGRESS",
                "rolloutStateReason": "ECS deployment ecs-svc/2420458347226626275 in progress.",
                "volumeConfigurations": [
                    {
                        "name": "ebs-volume",
                        "managedEBSVolume": {
                            "volumeType": "gp3",
                            "sizeInGiB": 100,
                            "iops": 3000,
                            "throughput": 125,
                            "roleArn": "arn:aws:iam::123456789012:role/ecsInfrastructureRole",
                            "filesystemType": "ext4"
                        }
                    }
                ]
            },
            {
                "id": "ecs-svc/5191625155316533644",
                "status": "ACTIVE",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:2",
                "desiredCount": 2,
                "pendingCount": 0,
                "runningCount": 2,
                "failedTasks": 0,
                "createdAt": "2025-02-21T14:54:48.862000-06:00",
                "updatedAt": "2025-02-21T14:57:22.502000-06:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321"
                        ],
                        "securityGroups": [
                            "sg-12344321"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "COMPLETED",
                "rolloutStateReason": "ECS deployment ecs-svc/5191625155316533644 completed."
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [
            {
                "id": "b5823113-c2c5-458e-9649-8c2ed38f23a5",
                "createdAt": "2025-02-21T14:57:22.508000-06:00",
                "message": "(service my-http-service) has reached a steady state."
            },
            {
                "id": "b05a48e8-da35-4074-80aa-37ceb3167357",
                "createdAt": "2025-02-21T14:57:22.507000-06:00",
                "message": "(service my-http-service) (deployment ecs-svc/5191625155316533644) deployment completed."
            },
            {
                "id": "a10cd55d-4ba6-4cea-a655-5a5d32ada8a0",
                "createdAt": "2025-02-21T14:55:32.833000-06:00",
                "message": "(service my-http-service) has started 1 tasks: (task fb9c8df512684aec92f3c57dc3f22361)."
            },
        ],
        "createdAt": "2025-02-21T14:54:48.862000-06:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321"
                ],
                "securityGroups": [
                    "sg-12344321"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::123456789012:role/AIDACKCEVSQ6C2EXAMPLE",
        "enableECSManagedTags": true,
        "propagateTags": "NONE",
        "enableExecuteCommand": false,
        "availabilityZoneRebalancing": "ENABLED"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS での Amazon EBS ボリュームの使用](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-volumes.html)」を参照してください。  
**例 4: Amazon EBS ボリュームを今後使用しないようにサービスを更新するには**  
次の `update-service` の例では、Amazon EBS ボリュームを今後使用しないように `my-http-service` サービスを更新します。`configuredAtLaunch` を `false` に設定したタスク定義リビジョンを指定する必要があります。  

```
aws ecs update-service \
    --cluster mycluster \
    --task-definition mytaskdef \
    --service my-http-service \
    --desired-count 2 \
    --volume-configurations "[]"
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-west-2:123456789012:service/mycluster/my-http-service",
        "serviceName": "my-http-service",
        "clusterArn": "arn:aws:ecs:us-west-2:123456789012:cluster/mycluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 2,
        "pendingCount": 0,
        "launchType": "FARGATE",
        "platformVersion": "LATEST",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:3",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": true,
                "rollback": true
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100,
            "alarms": {
                "alarmNames": [],
                "rollback": false,
                "enable": false
            }
        },
        "deployments": [
            {
                "id": "ecs-svc/7522791612543716777",
                "status": "PRIMARY",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/mytaskdef:3",
                "desiredCount": 0,
                "pendingCount": 0,
                "runningCount": 0,
                "failedTasks": 0,
                "createdAt": "2025-02-21T15:25:38.598000-06:00",
                "updatedAt": "2025-02-21T15:25:38.598000-06:00",
                    "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321"
                        ],
                        "securityGroups": [
                            "sg-12344321"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "IN_PROGRESS",
                "rolloutStateReason": "ECS deployment ecs-svc/7522791612543716777 in progress."
            },
            {
                "id": "ecs-svc/2420458347226626275",
                "status": "ACTIVE",
                "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/myoldtaskdef:1",
                "desiredCount": 2,
                "pendingCount": 0,
                "runningCount": 2,
                "failedTasks": 0,
                "createdAt": "2025-02-21T15:07:20.519000-06:00",
                "updatedAt": "2025-02-21T15:10:59.955000-06:00",
                "launchType": "FARGATE",
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-12344321"
                        ],
                        "securityGroups": [
                            "sg-12344321"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "COMPLETED",
                "rolloutStateReason": "ECS deployment ecs-svc/2420458347226626275 completed.",
                "volumeConfigurations": [
                    {
                        "name": "ebs-volume",
                        "managedEBSVolume": {
                            "volumeType": "gp3",
                            "sizeInGiB": 100,
                            "iops": 3000,
                            "throughput": 125,
                            "roleArn": "arn:aws:iam::123456789012:role/ecsInfrastructureRole",
                            "filesystemType": "ext4"
                        }
                    }
                ]
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [
            {
                "id": "4f2c3ca1-7800-4048-ba57-bba210ada2ad",
                "createdAt": "2025-02-21T15:10:59.959000-06:00",
                "message": "(service my-http-service) has reached a steady state."
            },
            {
                "id": "4b36a593-2d40-4ed6-8be8-b9b699eb6198",
                "createdAt": "2025-02-21T15:10:59.958000-06:00",
                "message": "(service my-http-service) (deployment ecs-svc/2420458347226626275) deployment completed."
            },
            {
                "id": "88380089-14e2-4ef0-8dbb-a33991683371",
                "createdAt": "2025-02-21T15:09:39.055000-06:00",
                "message": "(service my-http-service) has stopped 1 running tasks: (task fb9c8df512684aec92f3c57dc3f22361)."
            },
            {
                "id": "97d84243-d52f-4255-89bb-9311391c61f6",
                "createdAt": "2025-02-21T15:08:57.653000-06:00",
                "message": "(service my-http-service) has stopped 1 running tasks: (task 33eff090ad2c40539daa837e6503a9bc)."
            },
            {
                "id": "672ece6c-e2d0-4021-b5da-eefb14001687",
                "createdAt": "2025-02-21T15:08:15.631000-06:00",
                "message": "(service my-http-service) has started 1 tasks: (task 996c02a66ff24f3190a4a8e0c841740f)."
            },
            {
                "id": "a3cf9bea-9be6-4175-ac28-4c68360986eb",
                "createdAt": "2025-02-21T15:07:36.931000-06:00",
                "message": "(service my-http-service) has started 1 tasks: (task d5d23c39f89e46cf9a647b9cc6572feb)."
            },
            {
                "id": "b5823113-c2c5-458e-9649-8c2ed38f23a5",
                "createdAt": "2025-02-21T14:57:22.508000-06:00",
                "message": "(service my-http-service) has reached a steady state."
            },
            {
                "id": "b05a48e8-da35-4074-80aa-37ceb3167357",
                "createdAt": "2025-02-21T14:57:22.507000-06:00",
                "message": "(service my-http-service) (deployment ecs-svc/5191625155316533644) deployment completed."
            },
            {
                "id": "a10cd55d-4ba6-4cea-a655-5a5d32ada8a0",
                "createdAt": "2025-02-21T14:55:32.833000-06:00",
                "message": "(service my-http-service) has started 1 tasks: (task fb9c8df512684aec92f3c57dc3f22361)."
            },
            {
                "id": "42da91fa-e26d-42ef-88c3-bb5965c56b2f",
                "createdAt": "2025-02-21T14:55:02.703000-06:00",
                "message": "(service my-http-service) has started 1 tasks: (task 33eff090ad2c40539daa837e6503a9bc)."
            }
        ],
        "createdAt": "2025-02-21T14:54:48.862000-06:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321"
                ],
                "securityGroups": [
                    "sg-12344321"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::123456789012:role/AIDACKCEVSQ6C2EXAMPLE",
        "enableECSManagedTags": true,
        "propagateTags": "NONE",
        "enableExecuteCommand": false,
        "availabilityZoneRebalancing": "ENABLED"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[Amazon ECS での Amazon EBS ボリュームの使用](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ebs-volumes.html)」を参照してください。  
**例 5: サービスのアベイラビリティーゾーンのリバランスを有効にするには**  
次の `update-service` の例では、サービス `my-http-service` のアベイラビリティーゾーンのリバランスを有効にします。  

```
aws ecs update-service \
    --cluster MyCluster \
    --service my-http-service \
    --availability-zone-rebalancing ENABLED
```
出力:  

```
{
    "service": {
        "serviceArn": "arn:aws:ecs:us-east-1:123456789012:service/MyCluster/my-http-service",
        "serviceName": "my-http-service",
        "clusterArn": "arn:aws:ecs:us-east-1:123456789012:cluster/MyCluster",
        "loadBalancers": [],
        "serviceRegistries": [],
        "status": "ACTIVE",
        "desiredCount": 2,
        "runningCount": 1,
        "pendingCount": 0,
        "capacityProviderStrategy": [
            {
                "capacityProvider": "FARGATE",
                "weight": 1,
                "base": 0
            }
        ],
        "platformVersion": "LATEST",
        "platformFamily": "Linux",
        "taskDefinition": "arn:aws:ecs:us-east-1:123456789012:task-definition/MyTaskDefinition",
        "deploymentConfiguration": {
            "deploymentCircuitBreaker": {
                "enable": true,
                "rollback": true
            },
            "maximumPercent": 200,
            "minimumHealthyPercent": 100,
            "alarms": {
                "alarmNames": [],
                "rollback": false,
                "enable": false
            }
        },
        "deployments": [
            {
                "id": "ecs-svc/1976744184940610707",
                "status": "PRIMARY",
                "taskkDefinition": "arn:aws:ecs:us-east-1:123456789012:task-definition/MyTaskDefinition",
                "desiredCount": 1,
                "pendingCount": 0,
                "runningCount": 1,
                "failedTasks": 0,
                "createdAt": "2024-12-03T16:24:25.225000-05:00",
                "updatedAt": "2024-12-03T16:25:15.837000-05:00",
                "capacityProviderStrategy": [
                    {
                        "capacityProvider": "FARGATE",
                        "weight": 1,
                        "base": 0
                    }
                ],
                "platformVersion": "1.4.0",
                "platformFamily": "Linux",
                "networkConfiguration": {
                    "awsvpcConfiguration": {
                        "subnets": [
                            "subnet-0d0eab1bb38d5ca64",
                            "subnet-0db5010045995c2d5"
                        ],
                        "securityGroups": [
                            "sg-02556bf85a191f59a"
                        ],
                        "assignPublicIp": "ENABLED"
                    }
                },
                "rolloutState": "COMPLETED",
                "rolloutStateReason": "ECS deployment ecs-svc/1976744184940610707 completed."
            }
        ],
        "roleArn": "arn:aws:iam::123456789012:role/aws-service-role/ecs.amazonaws.com/AWSServiceRoleForECS",
        "events": [],
        "createdAt": "2024-12-03T16:24:25.225000-05:00",
        "placementConstraints": [],
        "placementStrategy": [],
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-0d0eab1bb38d5ca64",
                    "subnet-0db5010045995c2d5"
                ],
                "securityGroups": [
                    "sg-02556bf85a191f59a"
                ],
                "assignPublicIp": "ENABLED"
            }
        },
        "healthCheckGracePeriodSeconds": 0,
        "schedulingStrategy": "REPLICA",
        "deploymentController": {
            "type": "ECS"
        },
        "createdBy": "arn:aws:iam::123456789012:role/Admin",
        "enableECSManagedTags": true,
        "propagateTags": "NONE",
        "enableExecuteCommand": false,
        "availabilityZoneRebalancing": "ENABLED"
    }
}
```
詳細については、「*Amazon ECS デベロッパーガイド*」の「[コンソールを使用した Amazon ECS サービスの更新](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-service-console-v2.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-service.html)」を参照してください。**

### `update-task-protection`
<a name="ecs_UpdateTaskProtection_cli_2_topic"></a>

次のコード例は、`update-task-protection` を使用する方法を示しています。

**AWS CLI**  
**例 1: ECS タスクのタスク保護を有効にする**  
次の `update-task-protection` は、デプロイまたは AutoScaling サービスによるスケールイン中の終了から ECS タスクを保護します。タスク保護のカスタム有効期限は 1 分から 2,880 分 (48 時間) の範囲で指定できます。有効期間を指定しない場合、タスク保護のデフォルトの有効期間は 2 時間になります。  

```
aws ecs update-task-protection \
    --cluster ECS-project-update-cluster \
    --tasks c43ed3b1331041f289316f958adb6a24 \
    --protection-enabled \
    --expires-in-minutes 300
```
出力:  

```
{
"protectedTasks": [
    {
        "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/c43ed3b1331041f289316f958adb6a24",
        "protectionEnabled": true,
        "expirationDate": "2024-09-14T19:53:36.687000-05:00"
    }
],
"failures": []
}
```
**例 2: ECS タスクのタスク保護を無効にする**  
次の `update-task-protection` は、デプロイまたは Auto Scaling サービスによるスケールインから保護されているタスクの保護を無効にします。  

```
aws ecs update-task-protection \
    --cluster ECS-project-update-cluster \
    --tasks c43ed3b1331041f289316f958adb6a24 \
    --no-protection-enabled
```
出力:  

```
{
    "protectedTasks": [
        {
            "taskArn": "arn:aws:ecs:us-west-2:123456789012:task/c43ed3b1331041f289316f958adb6a24",
            "protectionEnabled": false
        }
    ],
    "failures": []
}
```
タスク保護の詳細については、*Amazon ECS デベロッパーガイド*の「[Amazon ECS タスクがスケールインイベントによって終了するのを防ぐ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-scale-in-protection.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[UpdateTaskProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-task-protection.html)」を参照してください。

### `update-task-set`
<a name="ecs_UpdateTaskSet_cli_2_topic"></a>

次のコード例は、`update-task-set` を使用する方法を示しています。

**AWS CLI**  
**テストセットを更新するには**  
次の `update-task-set` の例では、タスクセットを更新してスケールを調整します。  

```
aws ecs update-task-set \
    --cluster MyCluster \
    --service MyService \
    --task-set arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789 \
    --scale value=50,unit=PERCENT
```
出力:  

```
{
    "taskSet": {
        "id": "ecs-svc/1234567890123456789",
        "taskSetArn": "arn:aws:ecs:us-west-2:123456789012:task-set/MyCluster/MyService/ecs-svc/1234567890123456789",
        "status": "ACTIVE",
        "taskDefinition": "arn:aws:ecs:us-west-2:123456789012:task-definition/sample-fargate:2",
        "computedDesiredCount": 0,
        "pendingCount": 0,
        "runningCount": 0,
        "createdAt": 1557128360.711,
        "updatedAt": 1557129279.914,
        "launchType": "EC2",
        "networkConfiguration": {
            "awsvpcConfiguration": {
                "subnets": [
                    "subnet-12344321"
                ],
                "securityGroups": [
                    "sg-12344321"
                ],
                "assignPublicIp": "DISABLED"
            }
        },
        "loadBalancers": [],
        "serviceRegistries": [],
        "scale": {
            "value": 50.0,
            "unit": "PERCENT"
        },
        "stabilityStatus": "STABILIZING",
        "stabilityStatusAt": 1557129279.914
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTaskSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ecs/update-task-set.html)」を参照してください。

# を使用した Amazon EFS の例 AWS CLI
<a name="cli_2_efs_code_examples"></a>

次のコード例は、Amazon EFS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-file-system`
<a name="efs_CreateFileSystem_cli_2_topic"></a>

次のコード例は、`create-file-system` を使用する方法を示しています。

**AWS CLI**  
**暗号化されたファイルシステムのを作成するには**  
次の `create-file-system` の例では、デフォルトの CMK を使用して暗号化されたファイルシステムを作成します。タグ `Name=my-file-system` も追加されます。  

```
aws efs create-file-system \
    --performance-mode generalPurpose \
    --throughput-mode bursting \
    --encrypted \
    --tags Key=Name,Value=my-file-system
```
出力:  

```
{
    "OwnerId": "123456789012",
    "CreationToken": "console-d7f56c5f-e433-41ca-8307-9d9c0example",
    "FileSystemId": "fs-c7a0456e",
    "FileSystemArn": "arn:aws:elasticfilesystem:us-west-2:123456789012:file-system/fs-48499b4d",
    "CreationTime": 1595286880.0,
    "LifeCycleState": "creating",
    "Name": "my-file-system",
    "NumberOfMountTargets": 0,
    "SizeInBytes": {
        "Value": 0,
        "ValueInIA": 0,
        "ValueInStandard": 0
    },
    "PerformanceMode": "generalPurpose",
    "Encrypted": true,
    "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/a59b3472-e62c-42e4-adcf-30d92example",
    "ThroughputMode": "bursting",
    "Tags": [
        {
            "Key": "Name",
            "Value": "my-file-system"
        }
    ]
}
```
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[Amazon EFS ファイルシステムの作成](https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFileSystem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/create-file-system.html)」を参照してください。

### `create-mount-target`
<a name="efs_CreateMountTarget_cli_2_topic"></a>

次のコード例は、`create-mount-target` を使用する方法を示しています。

**AWS CLI**  
**マウントターゲットを作成するには**  
次の `create-mount-target` の例では、指定されたファイルシステムのマウントターゲットを作成します。  

```
aws efs create-mount-target \
    --file-system-id fs-c7a0456e \
    --subnet-id subnet-02bf4c428bexample \
    --security-groups sg-068f739363example
```
出力:  

```
{
    "OwnerId": "123456789012",
    "MountTargetId": "fsmt-f9a14450",
    "FileSystemId": "fs-c7a0456e",
    "SubnetId": "subnet-02bf4c428bexample",
    "LifeCycleState": "creating",
    "IpAddress": "10.0.1.24",
    "NetworkInterfaceId": "eni-02d542216aexample",
    "AvailabilityZoneId": "use2-az2",
    "AvailabilityZoneName": "us-east-2b",
    "VpcId": "vpc-0123456789abcdef0"
}
```
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[マウントターゲットの作成](https://docs.aws.amazon.com/efs/latest/ug/accessing-fs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMountTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/create-mount-target.html)」を参照してください。

### `delete-file-system`
<a name="efs_DeleteFileSystem_cli_2_topic"></a>

次のコード例は、`delete-file-system` を使用する方法を示しています。

**AWS CLI**  
**ファイルシステムを削除するには**  
次の `delete-file-system` の例は、指定されたファイルシステムを削除します。  

```
aws efs delete-file-system \
    --file-system-id fs-c7a0456e
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[Amazon EFS ファイルシステムの削除](https://docs.aws.amazon.com/efs/latest/ug/delete-efs-fs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFileSystem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/delete-file-system.html)」を参照してください。

### `delete-mount-target`
<a name="efs_DeleteMountTarget_cli_2_topic"></a>

次のコード例は、`delete-mount-target` を使用する方法を示しています。

**AWS CLI**  
**マウントターゲットを削除するには**  
次の `delete-mount-target` の例は、指定されたマウントターゲットを削除します。  

```
aws efs delete-mount-target \
    --mount-target-id fsmt-f9a14450
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[マウントターゲットの作成](https://docs.aws.amazon.com/efs/latest/ug/accessing-fs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMountTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/delete-mount-target.html)」を参照してください。

### `describe-file-systems`
<a name="efs_DescribeFileSystems_cli_2_topic"></a>

次のコード例は、`describe-file-systems` を使用する方法を示しています。

**AWS CLI**  
**ファイルシステムを記述するには**  
次の `describe-file-systems` の例では、指定したファイルシステムを記述しています。  

```
aws efs describe-file-systems \
    --file-system-id fs-c7a0456e
```
出力:  

```
{
    "FileSystems": [
        {
            "OwnerId": "123456789012",
            "CreationToken": "console-d7f56c5f-e433-41ca-8307-9d9c0example",
            "FileSystemId": "fs-c7a0456e",
            "FileSystemArn": "arn:aws:elasticfilesystem:us-west-2:123456789012:file-system/fs-48499b4d",
            "CreationTime": 1595286880.0,
            "LifeCycleState": "available",
            "Name": "my-file-system",
            "NumberOfMountTargets": 3,
            "SizeInBytes": {
                "Value": 6144,
                "Timestamp": 1600991437.0,
                "ValueInIA": 0,
                "ValueInStandard": 6144
            },
            "PerformanceMode": "generalPurpose",
            "Encrypted": true,
            "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/a59b3472-e62c-42e4-adcf-30d92example",
            "ThroughputMode": "bursting",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "my-file-system"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[Amazon EFS ファイルシステムの管理](https://docs.aws.amazon.com/efs/latest/ug/managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFileSystems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/describe-file-systems.html)」を参照してください。

### `describe-mount-targets`
<a name="efs_DescribeMountTargets_cli_2_topic"></a>

次のコード例は、`describe-mount-targets` を使用する方法を示しています。

**AWS CLI**  
**マウントターゲットを記述するには**  
次の `describe-mount-targets` の例では、指定したマウントターゲットを記述しています。  

```
aws efs describe-mount-targets \
    --mount-target-id fsmt-f9a14450
```
出力:  

```
{
    "MountTargets": [
        {
            "OwnerId": "123456789012",
            "MountTargetId": "fsmt-f9a14450",
            "FileSystemId": "fs-c7a0456e",
            "SubnetId": "subnet-02bf4c428bexample",
            "LifeCycleState": "creating",
            "IpAddress": "10.0.1.24",
            "NetworkInterfaceId": "eni-02d542216aexample",
            "AvailabilityZoneId": "use2-az2",
            "AvailabilityZoneName": "us-east-2b",
            "VpcId": "vpc-0123456789abcdef0"
        }
    ]
}
```
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[マウントターゲットの作成](https://docs.aws.amazon.com/efs/latest/ug/accessing-fs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMountTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/describe-mount-targets.html)」を参照してください。

### `describe-tags`
<a name="efs_DescribeTags_cli_2_topic"></a>

次のコード例は、`describe-tags` を使用する方法を示しています。

**AWS CLI**  
**ファイルシステムのタグを記述するには**  
次の `describe-tags` の例では、指定したファイルシステムのタグを記述しています。  

```
aws efs describe-tags \
    --file-system-id fs-c7a0456e
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Name",
            "Value": "my-file-system"
        },
        {
            "Key": "Department",
            "Value": "Business Intelligence"
        }
    ]
}
```
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[ファイルシステムタグの管理](https://docs.aws.amazon.com/efs/latest/ug/manage-fs-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/describe-tags.html)」を参照してください。

### `list-tags-for-resource`
<a name="efs_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを取得するには**  
次の `list-tags-for-resource` の例では、指定されたファイルシステムに関連付けられたタグを取得します。  

```
aws efs list-tags-for-resource \
    --resource-id fs-c7a0456e
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Name",
            "Value": "my-file-system"
        },
        {
            "Key": "Department",
            "Value": "Business Intelligence"
        }
    ]
}
```
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[ファイルシステムタグの管理](https://docs.aws.amazon.com/efs/latest/ug/manage-fs-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/list-tags-for-resource.html)」を参照してください。

### `tag-resource`
<a name="efs_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、ファイルシステムにタグ `Department=Business Intelligence` を追加します。  

```
aws efs tag-resource \
    --resource-id fs-c7a0456e \
    --tags Key=Department,Value="Business Intelligence"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[ファイルシステムタグの管理](https://docs.aws.amazon.com/efs/latest/ug/manage-fs-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="efs_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `untag-resource` の例は、タグキーが `Department` のタグを指定したファイルシステムから削除します。  

```
aws efs untag-resource \
    --resource-id fs-c7a0456e \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Elastic File System ユーザーガイド*」の「[ファイルシステムタグの管理](https://docs.aws.amazon.com/efs/latest/ug/manage-fs-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/efs/untag-resource.html)」を参照してください。

# を使用した Amazon EKS の例 AWS CLI
<a name="cli_2_eks_code_examples"></a>

次のコード例は、Amazon EKS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-access-policy`
<a name="eks_AssociateAccessPolicy_cli_2_topic"></a>

次のコード例は、`associate-access-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセスポリシーとその範囲をクラスターのアクセスエントリに関連付けるには**  
次の `associate-access-policy` は、アクセスポリシーとその範囲を、指定されたクラスターのアクセスエントリに関連付けます。  

```
aws eks associate-access-policy \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:role/Admin \
    --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy \
    --access-scope type=namespace,namespaces=default
```
出力:  

```
{
    "clusterName": "eks-customer",
    "principalArn": "arn:aws:iam::111122223333:role/Admin",
    "associatedAccessPolicy": {
        "policyArn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy",
        "accessScope": {
            "type": "namespace",
            "namespaces": [
                "default"
            ]
        },
        "associatedAt": "2025-05-24T15:59:51.981000-05:00",
        "modifiedAt": "2025-05-24T15:59:51.981000-05:00"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[アクセスポリシーをアクセスエントリに関連付ける](https://docs.aws.amazon.com/eks/latest/userguide/access-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/associate-access-policy.html)」を参照してください。

### `associate-encryption-config`
<a name="eks_AssociateEncryptionConfig_cli_2_topic"></a>

次のコード例は、`associate-encryption-config` を使用する方法を示しています。

**AWS CLI**  
**暗号化設定を既存のクラスターに関連付けるには**  
次の `associate-encryption-config` の例では、暗号化が有効になっていない既存の EKS クラスターで暗号化を有効にします。  

```
aws eks associate-encryption-config \
    --cluster-name my-eks-cluster \
    --encryption-config '[{"resources":["secrets"],"provider":{"keyArn":"arn:aws:kms:region-code:account:key/key"}}]'
```
出力:  

```
{
    "update": {
        "id": "3141b835-8103-423a-8e68-12c2521ffa4d",
        "status": "InProgress",
        "type": "AssociateEncryptionConfig",
        "params": [
            {
                "type": "EncryptionConfig",
                "value": "[{\"resources\":[\"secrets\"],\"provider\":{\"keyArn\":\"arn:aws:kms:region-code:account:key/key\"}}]"
            }
        ],
        "createdAt": "2024-03-14T11:01:26.297000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[既存のクラスターでのシークレット暗号化の有効化](https://docs.aws.amazon.com/eks/latest/userguide/enable-kms.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateEncryptionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/associate-encryption-config.html)」を参照してください。

### `associate-identity-provider-config`
<a name="eks_AssociateIdentityProviderConfig_cli_2_topic"></a>

次のコード例は、`associate-identity-provider-config` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスターに ID プロバイダーを関連付ける**  
次の `associate-identity-provider-config` の例では、ID プロバイダーを Amazon EKS クラスターに関連付けます。  

```
aws eks associate-identity-provider-config \
    --cluster-name my-eks-cluster \
    --oidc 'identityProviderConfigName=my-identity-provider,issuerUrl=https://oidc.eks.us-east-2.amazonaws.com/id/38D6A4619A0A69E342B113ED7F1A7652,clientId=kubernetes,usernameClaim=email,usernamePrefix=my-username-prefix,groupsClaim=my-claim,groupsPrefix=my-groups-prefix,requiredClaims={Claim1=value1,Claim2=value2}' \
    --tags env=dev
```
出力:  

```
{
    "update": {
        "id": "8c6c1bef-61fe-42ac-a242-89412387b8e7",
        "status": "InProgress",
        "type": "AssociateIdentityProviderConfig",
        "params": [
            {
                "type": "IdentityProviderConfig",
                "value": "[{\"type\":\"oidc\",\"name\":\"my-identity-provider\"}]"
            }
        ],
        "createdAt": "2024-04-11T13:46:49.648000-04:00",
        "errors": []
    },
    "tags": {
        "env": "dev"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[OpenID Connect ID プロバイダーからクラスターのユーザーを認証する - OIDC ID プロバイダーを関連付ける](https://docs.aws.amazon.com/eks/latest/userguide/authenticate-oidc-identity-provider.html#associate-oidc-identity-provider)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateIdentityProviderConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/associate-identity-provider-config.html)」を参照してください。

### `create-access-entry`
<a name="eks_CreateAccessEntry_cli_2_topic"></a>

次のコード例は、`create-access-entry` を使用する方法を示しています。

**AWS CLI**  
**例 1: EKS クラスターのアクセスエントリを作成するには**  
次の `create-access-entry` の例では、IAM プリンシパルが EKS クラスターにアクセスできるようにするアクセスエントリを作成します。  

```
aws eks create-access-entry \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:user/eks-user
```
出力:  

```
{
    "accessEntry": {
        "clusterName": "eks-customer",
        "principalArn": "arn:aws:iam::111122223333:user/eks-user",
        "kubernetesGroups": [],
        "accessEntryArn": "arn:aws:eks:us-west-2:111122223333:access-entry/eks-customer/user/111122223333/eks-user/a1b2c3d4-5678-90ab-cdef-a6506e3d36p0",
        "createdAt": "2025-04-14T22:45:48.097000-05:00",
        "modifiedAt": "2025-04-14T22:45:48.097000-05:00",
        "tags": {},
        "username": "arn:aws:iam::111122223333:user/eks-user",
        "type": "STANDARD"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[アクセスエントリを作成する](https://docs.aws.amazon.com/eks/latest/userguide/creating-access-entries.html)」を参照してください。  
**例 2: アクセスエントリのタイプを指定して EKS クラスターのアクセスエントリを作成するには**  
次の `create-access-entry` の例では、EKS クラスターにタイプ `EC2_LINUX` のアクセスエントリを作成します。デフォルトでは、タイプ `STANDARD` のアクセスエントリが作成されます。デフォルト以外に、他のアクセスエントリタイプを指定する場合は、CLI で IAM ロール ARN を渡す必要があります。  

```
aws eks create-access-entry \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:role/admin-test-ip \
    --type EC2_LINUX
```
出力:  

```
{
    "accessEntry": {
        "clusterName": "eks-customer",
        "principalArn": "arn:aws:iam::111122223333:role/admin-test-ip",
        "kubernetesGroups": [
            "system:nodes"
        ],
        "accessEntryArn": "arn:aws:eks:us-west-2:111122223333:access-entry/eks-customer/role/111122223333/admin-test-ip/accb5418-f493-f390-3e6e-c3f19f725fcp",
        "createdAt": "2025-05-06T19:42:45.453000-05:00",
        "modifiedAt": "2025-05-06T19:42:45.453000-05:00",
        "tags": {},
        "username": "system:node:{{EC2PrivateDNSName}}",
        "type": "EC2_LINUX"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[アクセスエントリを作成する](https://docs.aws.amazon.com/eks/latest/userguide/creating-access-entries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAccessEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/create-access-entry.html)」を参照してください。

### `create-addon`
<a name="eks_CreateAddon_cli_2_topic"></a>

次の例は、`create-addon` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 各 EKS クラスターバージョンのデフォルトの互換性バージョンで Amazon EKS アドオンを作成するには**  
次の `create-addon` の例では、それぞれの EKS クラスターバージョンのデフォルトの互換性バージョンを持つ Amazon EKS アドオンを作成します。  

```
aws eks create-addon \
    --cluster-name my-eks-cluster \
    --addon-name my-eks-addon \
    --service-account-role-arn arn:aws:iam::111122223333:role/role-name
```
出力:  

```
{
    "addon": {
        "addonName": "my-eks-addon",
        "clusterName": "my-eks-cluster",
        "status": "CREATING",
        "addonVersion": "v1.15.1-eksbuild.1",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/my-eks-addon/1ec71ee1-b9c2-8915-4e17-e8be0a55a149",
        "createdAt": "2024-03-14T12:20:03.264000-04:00",
        "modifiedAt": "2024-03-14T12:20:03.283000-04:00",
        "serviceAccountRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
**例 2: 特定のアドオンバージョンで Amazon EKS アドオンを作成するには**  
次の `create-addon` の例では、特定のアドオンバージョンを使用して Amazon EKS アドオンを作成します。  

```
aws eks create-addon \
    --cluster-name my-eks-cluster \
    --addon-name my-eks-addon \
    --service-account-role-arn arn:aws:iam::111122223333:role/role-name \
    --addon-version v1.16.4-eksbuild.2
```
出力:  

```
{
    "addon": {
        "addonName": "my-eks-addon",
        "clusterName": "my-eks-cluster",
        "status": "CREATING",
        "addonVersion": "v1.16.4-eksbuild.2",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/my-eks-addon/34c71ee6-7738-6c8b-c6bd-3921a176b5ff",
        "createdAt": "2024-03-14T12:30:24.507000-04:00",
        "modifiedAt": "2024-03-14T12:30:24.521000-04:00",
        "serviceAccountRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
**例 3: カスタム設定値を使用して Amazon EKS アドオンを作成し、競合の詳細を解決するには**  
次の `create-addon` の例では、カスタム設定値を使用して Amazon EKS アドオンを作成し、競合の詳細を解決します。  

```
aws eks create-addon \
    --cluster-name my-eks-cluster \
    --addon-name my-eks-addon \
    --service-account-role-arn arn:aws:iam::111122223333:role/role-name \
    --addon-version v1.16.4-eksbuild.2 \
    --configuration-values '{"resources":{"limits":{"cpu":"100m"}}}' \
    --resolve-conflicts OVERWRITE
```
出力:  

```
{
    "addon": {
        "addonName": "my-eks-addon",
        "clusterName": "my-eks-cluster",
        "status": "CREATING",
        "addonVersion": "v1.16.4-eksbuild.2",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/my-eks-addon/a6c71ee9-0304-9237-1be8-25af1b0f1ffb",
        "createdAt": "2024-03-14T12:35:58.313000-04:00",
        "modifiedAt": "2024-03-14T12:35:58.327000-04:00",
        "serviceAccountRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "tags": {},
        "configurationValues": "{\"resources\":{\"limits\":{\"cpu\":\"100m\"}}}"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
**例 4: カスタム JSON 設定値ファイルを使用して Amazon EKS アドオンを作成するには**  
次の `create-addon` の例では、カスタム設定値を使用して Amazon EKS アドオンを作成し、競合の詳細を解決します。  

```
aws eks create-addon \
    --cluster-name my-eks-cluster \
    --addon-name my-eks-addon \
    --service-account-role-arn arn:aws:iam::111122223333:role/role-name \
    --addon-version v1.16.4-eksbuild.2 \
    --configuration-values 'file://configuration-values.json' \
    --resolve-conflicts OVERWRITE \
    --tags '{"eks-addon-key-1": "value-1" , "eks-addon-key-2": "value-2"}'
```
`configuration-values.json` の内容:  

```
{
    "resources": {
        "limits": {
            "cpu": "150m"
        }
    },
    "env": {
        "AWS_VPC_K8S_CNI_LOGLEVEL": "ERROR"
    }
}
```
出力:  

```
{
    "addon": {
        "addonName": "my-eks-addon",
        "clusterName": "my-eks-cluster",
        "status": "CREATING",
        "addonVersion": "v1.16.4-eksbuild.2",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/my-eks-addon/d8c71ef8-fbd8-07d0-fb32-6a7be19ececd",
        "createdAt": "2024-03-14T13:10:51.763000-04:00",
        "modifiedAt": "2024-03-14T13:10:51.777000-04:00",
        "serviceAccountRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "tags": {
            "eks-addon-key-1": "value-1",
            "eks-addon-key-2": "value-2"
        },
        "configurationValues": "{\n    \"resources\": {\n        \"limits\": {\n            \"cpu\": \"150m\"\n        }\n    },\n    \"env\": {\n        \"AWS_VPC_K8S_CNI_LOGLEVEL\": \"ERROR\"\n    }\n}"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
**例 5: カスタム YAML 設定値ファイルを使用して Amazon EKS アドオンを作成するには**  
次の `create-addon` の例では、カスタム設定値を使用して Amazon EKS アドオンを作成し、競合の詳細を解決します。  

```
aws eks create-addon \
    --cluster-name my-eks-cluster \
    --addon-name my-eks-addon \
    --service-account-role-arn arn:aws:iam::111122223333:role/role-name \
    --addon-version v1.16.4-eksbuild.2 \
    --configuration-values 'file://configuration-values.yaml' \
    --resolve-conflicts OVERWRITE \
    --tags '{"eks-addon-key-1": "value-1" , "eks-addon-key-2": "value-2"}'
```
`configuration-values.yaml` の内容:  

```
resources:
    limits:
        cpu: '100m'
env:
    AWS_VPC_K8S_CNI_LOGLEVEL: 'DEBUG'
```
出力:  

```
{
    "addon": {
        "addonName": "my-eks-addon",
        "clusterName": "my-eks-cluster",
        "status": "CREATING",
        "addonVersion": "v1.16.4-eksbuild.2",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/my-eks-addon/d4c71efb-3909-6f36-a548-402cd4b5d59e",
        "createdAt": "2024-03-14T13:15:45.220000-04:00",
        "modifiedAt": "2024-03-14T13:15:45.237000-04:00",
        "serviceAccountRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "tags": {
            "eks-addon-key-3": "value-3",
            "eks-addon-key-4": "value-4"
        },
        "configurationValues": "resources:\n    limits:\n        cpu: '100m'\nenv:\n    AWS_VPC_K8S_CNI_LOGLEVEL: 'INFO'"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAddon](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/create-addon.html)」を参照してください。

### `create-cluster`
<a name="eks_CreateCluster_cli_2_topic"></a>

次のコード例は、`create-cluster` を使用する方法を示しています。

**AWS CLI**  
**新しいクラスターを作成するには**  
このコマンド例は、デフォルトリージョンに `prod` という名前のクラスターを作成します。  
コマンド:  

```
aws eks create-cluster --name prod \
--role-arn arn:aws:iam::012345678910:role/eks-service-role-AWSServiceRoleForAmazonEKS-J7ONKE3BQ4PI \
--resources-vpc-config subnetIds=subnet-6782e71e,subnet-e7e761ac,securityGroupIds=sg-6979fe18
```
出力:  

```
{
    "cluster": {
        "name": "prod",
        "arn": "arn:aws:eks:us-west-2:012345678910:cluster/prod",
        "createdAt": 1527808069.147,
        "version": "1.10",
        "roleArn": "arn:aws:iam::012345678910:role/eks-service-role-AWSServiceRoleForAmazonEKS-J7ONKE3BQ4PI",
        "resourcesVpcConfig": {
            "subnetIds": [
                "subnet-6782e71e",
                "subnet-e7e761ac"
            ],
            "securityGroupIds": [
                "sg-6979fe18"
            ],
            "vpcId": "vpc-950809ec"
        },
        "status": "CREATING",
        "certificateAuthority": {}
    }
}
```
**プライベートエンドポイントアクセスを含むクラスターを作成してロギングを埋め込むには**  
このコマンド例は、パブリックエンドポイントアクセスを無効にし、プライベートエンドポイントアクセスを有効にして、すべてのロギングタイプが有効な、`example` という名前のクラスターをデフォルトのリージョンに作成します。  
コマンド:  

```
aws eks create-cluster --name example --kubernetes-version 1.12 \
--role-arn arn:aws:iam::012345678910:role/example-cluster-ServiceRole-1XWBQWYSFRE2Q \
--resources-vpc-config subnetIds=subnet-0a188dccd2f9a632f,subnet-09290d93da4278664,subnet-0f21dd86e0e91134a,subnet-0173dead68481a583,subnet-051f70a57ed6fcab6,subnet-01322339c5c7de9b4,securityGroupIds=sg-0c5b580845a031c10,endpointPublicAccess=false,endpointPrivateAccess=true \
--logging '{"clusterLogging":[{"types":["api","audit","authenticator","controllerManager","scheduler"],"enabled":true}]}'
```
出力:  

```
{
    "cluster": {
        "name": "example",
        "arn": "arn:aws:eks:us-west-2:012345678910:cluster/example",
        "createdAt": 1565804921.901,
        "version": "1.12",
        "roleArn": "arn:aws:iam::012345678910:role/example-cluster-ServiceRole-1XWBQWYSFRE2Q",
        "resourcesVpcConfig": {
            "subnetIds": [
                "subnet-0a188dccd2f9a632f",
                "subnet-09290d93da4278664",
                "subnet-0f21dd86e0e91134a",
                "subnet-0173dead68481a583",
                "subnet-051f70a57ed6fcab6",
                "subnet-01322339c5c7de9b4"
            ],
            "securityGroupIds": [
                "sg-0c5b580845a031c10"
            ],
            "vpcId": "vpc-0f622c01f68d4afec",
            "endpointPublicAccess": false,
            "endpointPrivateAccess": true
        },
        "logging": {
            "clusterLogging": [
                {
                    "types": [
                        "api",
                        "audit",
                        "authenticator",
                        "controllerManager",
                        "scheduler"
                    ],
                    "enabled": true
                }
            ]
        },
        "status": "CREATING",
        "certificateAuthority": {},
        "platformVersion": "eks.3"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/create-cluster.html)」を参照してください。

### `create-fargate-profile`
<a name="eks_CreateFargateProfile_cli_2_topic"></a>

次のコード例は、`create-fargate-profile` を使用する方法を示しています。

**AWS CLI**  
**例 1: 名前空間を持つセレクターの EKS Fargate プロファイルを作成する**  
次の `create-fargate-profile` の例では、名前空間を持つセレクターの EKS Fargate Profile を作成します。  

```
aws eks create-fargate-profile \
    --cluster-name my-eks-cluster \
    --pod-execution-role-arn arn:aws:iam::111122223333:role/role-name \
    --fargate-profile-name my-fargate-profile \
    --selectors '[{"namespace": "default"}]'
```
出力:  

```
{
    "fargateProfile": {
        "fargateProfileName": "my-fargate-profile",
        "fargateProfileArn": "arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/a2c72bca-318e-abe8-8ed1-27c6d4892e9e",
        "clusterName": "my-eks-cluster",
        "createdAt": "2024-03-19T12:38:47.368000-04:00",
        "podExecutionRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "subnets": [
            "subnet-09d912bb63ef21b9a",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-0e2907431c9988b72"
        ],
        "selectors": [
            {
                "namespace": "default"
            }
        ],
        "status": "CREATING",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[AWS Fargate プロファイル - Fargate プロファイルの作成](https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html#create-fargate-profile)」を参照してください。  
**例 2: 名前空間とラベルを持つセレクターの EKS Fargate プロファイルを作成する**  
次の `create-fargate-profile` の例では、名前空間とラベルを持つセレクターの EKS Fargate プロファイルを作成します。  

```
aws eks create-fargate-profile \
    --cluster-name my-eks-cluster \
    --pod-execution-role-arn arn:aws:iam::111122223333:role/role-name \
    --fargate-profile-name my-fargate-profile \
    --selectors '[{"namespace": "default", "labels": {"labelname1": "labelvalue1"}}]'
```
出力:  

```
{
    "fargateProfile": {
        "fargateProfileName": "my-fargate-profile",
        "fargateProfileArn": "arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/88c72bc7-e8a4-fa34-44e4-2f1397224bb3",
        "clusterName": "my-eks-cluster",
        "createdAt": "2024-03-19T12:33:48.125000-04:00",
        "podExecutionRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "subnets": [
            "subnet-09d912bb63ef21b9a",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-0e2907431c9988b72"
        ],
        "selectors": [
            {
                "namespace": "default",
                "labels": {
                    "labelname1": "labelvalue1"
                }
            }
        ],
        "status": "CREATING",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[AWS Fargate プロファイル - Fargate プロファイルの作成](https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html#create-fargate-profile)」を参照してください。  
**例 3: 名前空間とラベル、およびポッドを起動するサブネットの ID を持つセレクターの EKS Fargate Profile を作成する。**  
次の `create-fargate-profile` の例では、名前空間とラベル、およびポッドを起動するサブネットの ID を持つセレクターの EKS Fargate Profile を作成します。  

```
aws eks create-fargate-profile \
    --cluster-name my-eks-cluster \
    --pod-execution-role-arn arn:aws:iam::111122223333:role/role-name \
    --fargate-profile-name my-fargate-profile \
    --selectors '[{"namespace": "default", "labels": {"labelname1": "labelvalue1"}}]' \
    --subnets '["subnet-09d912bb63ef21b9a", "subnet-04ad87f71c6e5ab4d", "subnet-0e2907431c9988b72"]'
```
出力:  

```
{
    "fargateProfile": {
        "fargateProfileName": "my-fargate-profile",
        "fargateProfileArn": "arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/e8c72bc8-e87b-5eb6-57cb-ed4fe57577e3",
        "clusterName": "my-eks-cluster",
        "createdAt": "2024-03-19T12:35:58.640000-04:00",
        "podExecutionRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "subnets": [
            "subnet-09d912bb63ef21b9a",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-0e2907431c9988b72"
        ],
        "selectors": [
            {
                "namespace": "default",
                "labels": {
                    "labelname1": "labelvalue1"
                }
            }
        ],
        "status": "CREATING",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[AWS Fargate プロファイル - Fargate プロファイルの作成](https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html#create-fargate-profile)」を参照してください。  
**例 4: 複数の名前空間とラベル、およびポッドを起動するサブネットの ID を持つセレクターの EKS Fargate プロファイルを作成する**  
次の `create-fargate-profile` の例では、複数の名前空間とラベル、およびポッドを起動するサブネットの ID を持つセレクターの EKS Fargate プロファイルを作成します。  

```
aws eks create-fargate-profile \
    --cluster-name my-eks-cluster \
    --pod-execution-role-arn arn:aws:iam::111122223333:role/role-name \
    --fargate-profile-name my-fargate-profile \
    --selectors '[{"namespace": "default1", "labels": {"labelname1": "labelvalue1", "labelname2": "labelvalue2"}}, {"namespace": "default2", "labels": {"labelname1": "labelvalue1", "labelname2": "labelvalue2"}}]' \
    --subnets '["subnet-09d912bb63ef21b9a", "subnet-04ad87f71c6e5ab4d", "subnet-0e2907431c9988b72"]' \
    --tags '{"eks-fargate-profile-key-1": "value-1" , "eks-fargate-profile-key-2": "value-2"}'
```
出力:  

```
{
    "fargateProfile": {
        "fargateProfileName": "my-fargate-profile",
        "fargateProfileArn": "arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/4cc72bbf-b766-8ee6-8d29-e62748feb3cd",
        "clusterName": "my-eks-cluster",
        "createdAt": "2024-03-19T12:15:55.271000-04:00",
        "podExecutionRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "subnets": [
            "subnet-09d912bb63ef21b9a",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-0e2907431c9988b72"
        ],
        "selectors": [
            {
                "namespace": "default1",
                "labels": {
                    "labelname2": "labelvalue2",
                    "labelname1": "labelvalue1"
                }
            },
            {
                "namespace": "default2",
                "labels": {
                    "labelname2": "labelvalue2",
                    "labelname1": "labelvalue1"
                }
            }
        ],
        "status": "CREATING",
        "tags": {
            "eks-fargate-profile-key-2": "value-2",
            "eks-fargate-profile-key-1": "value-1"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[AWS Fargate プロファイル - Fargate プロファイルの作成](https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html#create-fargate-profile)」を参照してください。  
**例 5: 名前空間とラベル用のワイルドカードセレクタと、ポッドを起動するサブネットの IDs を使用して EKS Fargate Profile を作成する**  
次の `create-fargate-profile` の例では、複数の名前空間とラベル、およびポッドを起動するサブネットの ID を持つセレクターの EKS Fargate プロファイルを作成します。  

```
aws eks create-fargate-profile \
    --cluster-name my-eks-cluster \
    --pod-execution-role-arn arn:aws:iam::111122223333:role/role-name \
    --fargate-profile-name my-fargate-profile \
    --selectors '[{"namespace": "prod*", "labels": {"labelname*?": "*value1"}}, {"namespace": "*dev*", "labels": {"labelname*?": "*value*"}}]' \
    --subnets '["subnet-09d912bb63ef21b9a", "subnet-04ad87f71c6e5ab4d", "subnet-0e2907431c9988b72"]' \
    --tags '{"eks-fargate-profile-key-1": "value-1" , "eks-fargate-profile-key-2": "value-2"}'
```
出力:  

```
{
    "fargateProfile": {
        "fargateProfileName": "my-fargate-profile",
        "fargateProfileArn": "arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/e8c72bd6-5966-0bfe-b77b-1802893e5a6f",
        "clusterName": "my-eks-cluster",
        "createdAt": "2024-03-19T13:05:20.550000-04:00",
        "podExecutionRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "subnets": [
            "subnet-09d912bb63ef21b9a",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-0e2907431c9988b72"
        ],
        "selectors": [
            {
                "namespace": "prod*",
                "labels": {
                    "labelname*?": "*value1"
                }
            },
            {
                "namespace": "*dev*",
                "labels": {
                    "labelname*?": "*value*"
                }
            }
        ],
        "status": "CREATING",
        "tags": {
            "eks-fargate-profile-key-2": "value-2",
            "eks-fargate-profile-key-1": "value-1"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[AWS Fargate プロファイル - Fargate プロファイルの作成](https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html#create-fargate-profile)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFargateProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/create-fargate-profile.html)」を参照してください。

### `create-nodegroup`
<a name="eks_CreateNodegroup_cli_2_topic"></a>

次のコード例は、`create-nodegroup` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EKS クラスターのマネージド型ノードグループを作成する**  
次の `create-nodegroup` の例では、Amazon EKS クラスターにマネージド型ノードグループを作成します。  

```
aws eks create-nodegroup \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --node-role arn:aws:iam::111122223333:role/role-name \
    --subnets "subnet-0e2907431c9988b72" "subnet-04ad87f71c6e5ab4d" "subnet-09d912bb63ef21b9a" \
    --scaling-config minSize=1,maxSize=3,desiredSize=1 \
    --region us-east-2
```
出力:  

```
{
    "nodegroup": {
        "nodegroupName": "my-eks-nodegroup",
        "nodegroupArn": "arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-nodegroup/bac7550f-b8b8-5fbb-4f3e-7502a931119e",
        "clusterName": "my-eks-cluster",
        "version": "1.26",
        "releaseVersion": "1.26.12-20240329",
        "createdAt": "2024-04-04T13:19:32.260000-04:00",
        "modifiedAt": "2024-04-04T13:19:32.260000-04:00",
        "status": "CREATING",
        "capacityType": "ON_DEMAND",
        "scalingConfig": {
            "minSize": 1,
            "maxSize": 3,
            "desiredSize": 1
        },
        "instanceTypes": [
            "t3.medium"
        ],
        "subnets": [
            "subnet-0e2907431c9988b72, subnet-04ad87f71c6e5ab4d, subnet-09d912bb63ef21b9a"
        ],
        "amiType": "AL2_x86_64",
        "nodeRole": "arn:aws:iam::111122223333:role/role-name",
        "diskSize": 20,
        "health": {
            "issues": []
        },
        "updateConfig": {
            "maxUnavailable": 1
        },
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの作成](https://docs.aws.amazon.com/eks/latest/userguide/create-managed-node-group.html)」を参照してください。  
**例 2: カスタムの instance-types と disk-size のある Amazon EKS クラスターのマネージド型ノードグループを作成する**  
次の `create-nodegroup` の例では、カスタムの instance-types と disk-size のある Amazon EKS クラスターのマネージド型ノードグループを作成します。  

```
aws eks create-nodegroup \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --node-role arn:aws:iam::111122223333:role/role-name \
    --subnets "subnet-0e2907431c9988b72" "subnet-04ad87f71c6e5ab4d" "subnet-09d912bb63ef21b9a" \
    --scaling-config minSize=1,maxSize=3,desiredSize=1 \
    --capacity-type ON_DEMAND \
    --instance-types 'm5.large' \
    --disk-size 50 \
    --region us-east-2
```
出力:  

```
{
    "nodegroup": {
        "nodegroupName": "my-eks-nodegroup",
        "nodegroupArn": "arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-nodegroup/c0c7551b-e4f9-73d9-992c-a450fdb82322",
        "clusterName": "my-eks-cluster",
        "version": "1.26",
        "releaseVersion": "1.26.12-20240329",
        "createdAt": "2024-04-04T13:46:07.595000-04:00",
        "modifiedAt": "2024-04-04T13:46:07.595000-04:00",
        "status": "CREATING",
        "capacityType": "ON_DEMAND",
        "scalingConfig": {
            "minSize": 1,
            "maxSize": 3,
            "desiredSize": 1
        },
        "instanceTypes": [
            "m5.large"
        ],
        "subnets": [
            "subnet-0e2907431c9988b72",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-09d912bb63ef21b9a"
        ],
        "amiType": "AL2_x86_64",
        "nodeRole": "arn:aws:iam::111122223333:role/role-name",
        "diskSize": 50,
        "health": {
            "issues": []
        },
        "updateConfig": {
            "maxUnavailable": 1
        },
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの作成](https://docs.aws.amazon.com/eks/latest/userguide/create-managed-node-group.html)」を参照してください。  
**例 3: カスタムの instance-types、disk-size、ami-type、capacity-type、update-config、ラベル、テイント、タグを持つ Amazon EKS クラスターのマネージド型ノードグループを作成する。**  
次の `create-nodegroup` の例では、カスタムの instance-types、disk-size、ami-type、capacity-type、update-config、ラベル、テイント、タグを持つ Amazon EKS クラスターのマネージド型ノードグループを作成します。  

```
aws eks create-nodegroup  \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --node-role arn:aws:iam::111122223333:role/role-name \
    --subnets "subnet-0e2907431c9988b72" "subnet-04ad87f71c6e5ab4d" "subnet-09d912bb63ef21b9a" \
    --scaling-config minSize=1,maxSize=5,desiredSize=4 \
    --instance-types 't3.large' \
    --disk-size 50 \
    --ami-type AL2_x86_64 \
    --capacity-type SPOT \
    --update-config maxUnavailable=2 \
    --labels '{"my-eks-nodegroup-label-1": "value-1" , "my-eks-nodegroup-label-2": "value-2"}' \
    --taints '{"key": "taint-key-1" , "value": "taint-value-1", "effect": "NO_EXECUTE"}' \
    --tags '{"my-eks-nodegroup-key-1": "value-1" , "my-eks-nodegroup-key-2": "value-2"}'
```
出力:  

```
{
    "nodegroup": {
        "nodegroupName": "my-eks-nodegroup",
        "nodegroupArn": "arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-nodegroup/88c75524-97af-0cb9-a9c5-7c0423ab5314",
        "clusterName": "my-eks-cluster",
        "version": "1.26",
        "releaseVersion": "1.26.12-20240329",
        "createdAt": "2024-04-04T14:05:07.940000-04:00",
        "modifiedAt": "2024-04-04T14:05:07.940000-04:00",
        "status": "CREATING",
        "capacityType": "SPOT",
        "scalingConfig": {
            "minSize": 1,
            "maxSize": 5,
            "desiredSize": 4
        },
        "instanceTypes": [
            "t3.large"
        ],
        "subnets": [
            "subnet-0e2907431c9988b72",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-09d912bb63ef21b9a"
        ],
        "amiType": "AL2_x86_64",
        "nodeRole": "arn:aws:iam::111122223333:role/role-name",
        "labels": {
            "my-eks-nodegroup-label-2": "value-2",
            "my-eks-nodegroup-label-1": "value-1"
        },
        "taints": [
            {
                "key": "taint-key-1",
                "value": "taint-value-1",
                "effect": "NO_EXECUTE"
            }
        ],
        "diskSize": 50,
        "health": {
            "issues": []
        },
        "updateConfig": {
            "maxUnavailable": 2
        },
        "tags": {
            "my-eks-nodegroup-key-1": "value-1",
            "my-eks-nodegroup-key-2": "value-2"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの作成](https://docs.aws.amazon.com/eks/latest/userguide/create-managed-node-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNodegroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/create-nodegroup.html)」を参照してください。

### `create-pod-identity-association`
<a name="eks_CreatePodIdentityAssociation_cli_2_topic"></a>

次のコード例は、`create-pod-identity-association` を使用する方法を示しています。

**AWS CLI**  
**例 1: EKS クラスターで EKS Pod Identity の関連付けを作成するには**  
次の `create-pod-identity-association` の例では、EKS クラスター内のサービスアカウントと IAM ロールの間に EKS Pod Identity の関連付けを作成します。  

```
aws eks create-pod-identity-association \
    --cluster-name eks-customer \
    --namespace default \
    --service-account default \
    --role-arn arn:aws:iam::111122223333:role/my-role
```
出力:  

```
{
    "association": {
        "clusterName": "eks-customer",
        "namespace": "default",
        "serviceAccount": "default",
        "roleArn": "arn:aws:iam::111122223333:role/my-role",
        "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-8mvwvh57cu74mgcst",
        "associationId": "a-8mvwvh57cu74mgcst",
        "tags": {},
        "createdAt": "2025-05-24T19:40:13.961000-05:00",
        "modifiedAt": "2025-05-24T19:40:13.961000-05:00"
    }
}
```
詳細については、*「Amazon* [EKS ユーザーガイド」の「EKS Pod Identity がポッドに AWS サービスへのアクセスを許可する方法](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)」を参照してください。  
**例 2: タグを使用する EKS クラスターに EKS Pod Identity の関連付けを作成するには**  
次の `create-pod-identity-association` では、サービスアカウントとタグを使用する EKS クラスター内の IAM ロールとの間に EKS Pod Identity の関連付けを作成します。  

```
aws eks create-pod-identity-association \
    --cluster-name eks-customer \
    --namespace default \
    --service-account default \
    --role-arn arn:aws:iam::111122223333:role/my-role \
    --tags Key1=value1,Key2=value2
```
出力:  

```
{
    "association": {
        "clusterName": "eks-customer",
        "namespace": "default",
        "serviceAccount": "default",
        "roleArn": "arn:aws:iam::111122223333:role/my-role",
        "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-9njjin9gfghecgoda",
        "associationId": "a-9njjin9gfghecgoda",
        "tags": {
            "Key2": "value2",
            "Key1": "value1"
        },
        "createdAt": "2025-05-24T19:52:14.135000-05:00",
        "modifiedAt": "2025-05-24T19:52:14.135000-05:00"
    }
}
```
詳細については、*「Amazon* [EKS ユーザーガイド」の「EKS Pod Identity がポッドに AWS サービスへのアクセスを許可する方法](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePodIdentityAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/create-pod-identity-association.html)」を参照してください。

### `delete-access-entry`
<a name="eks_DeleteAccessEntry_cli_2_topic"></a>

次のコード例は、`delete-access-entry` を使用する方法を示しています。

**AWS CLI**  
**クラスターに関連付けられたアクセスエントリを削除するには**  
次の `delete-access-entry` は、`eks-customer` という名前の EKS クラスターに関連付けられたアクセスエントリを削除します。  

```
aws eks delete-access-entry \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:role/Admin
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EKS ユーザーガイド*」の「[アクセスエントリを削除する](https://docs.aws.amazon.com/eks/latest/userguide/deleting-access-entries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/delete-access-entry.html)」を参照してください。

### `delete-addon`
<a name="eks_DeleteAddon_cli_2_topic"></a>

次のコード例は、`delete-addon` を使用する方法を示しています。

**AWS CLI**  
**例 1。Amazon EKS アドオンを削除し、アドオンソフトウェアを EKS クラスターに保存するには**  
次の `delete-addon` コマンド例では、Amazon EKS アドオンを削除しますが、アドオンソフトウェアは EKS クラスターに保持されます。  

```
aws eks delete-addon \
    --cluster-name my-eks-cluster \
    --addon-name my-eks-addon \
    --preserve
```
出力:  

```
{
    "addon": {
        "addonName": "my-eks-addon",
        "clusterName": "my-eks-cluster",
        "status": "DELETING",
        "addonVersion": "v1.9.3-eksbuild.7",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/my-eks-addon/a8c71ed3-944e-898b-9167-c763856af4b8",
        "createdAt": "2024-03-14T11:49:09.009000-04:00",
        "modifiedAt": "2024-03-14T12:03:49.776000-04:00",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS*」の「[Amazon EKS アドオンの管理 - アドオンの削除](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#removing-an-add-on)」を参照してください。  
**例 2。Amazon EKS アドオンを削除し、EKS クラスターからアドオンソフトウェアも削除するには**  
次の `delete-addon` のコマンド例では、Amazon EKS アドオンを削除し、EKS クラスターからアドオンソフトウェアも削除します。  

```
aws eks delete-addon \
    --cluster-name my-eks-cluster \
    --addon-name my-eks-addon
```
出力:  

```
{
    "addon": {
        "addonName": "my-eks-addon",
        "clusterName": "my-eks-cluster",
        "status": "DELETING",
        "addonVersion": "v1.15.1-eksbuild.1",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/my-eks-addon/bac71ed1-ec43-3bb6-88ea-f243cdb58954",
        "createdAt": "2024-03-14T11:45:31.983000-04:00",
        "modifiedAt": "2024-03-14T11:58:40.136000-04:00",
        "serviceAccountRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS*」の「[Amazon EKS アドオンの管理 - アドオンの削除](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#removing-an-add-on)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAddon](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/delete-addon.html)」を参照してください。

### `delete-cluster`
<a name="eks_DeleteCluster_cli_2_topic"></a>

次のコード例は、`delete-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスターコントロールプレーンを削除する**  
次の `delete-cluster` の例では、Amazon EKS クラスターコントロールプレーンを削除します。  

```
aws eks delete-cluster \
    --name my-eks-cluster
```
出力:  

```
{
    "cluster": {
        "name": "my-eks-cluster",
        "arn": "arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster",
        "createdAt": "2024-03-14T11:31:44.348000-04:00",
        "version": "1.27",
        "endpoint": "https://DALSJ343KE23J3RN45653DSKJTT647TYD.yl4.us-east-2.eks.amazonaws.com",
        "roleArn": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-cluster-ServiceRole-zMF6CBakwwbW",
        "resourcesVpcConfig": {
            "subnetIds": [
                "subnet-0fb75d2d8401716e7",
                "subnet-02184492f67a3d0f9",
                "subnet-04098063527aab776",
                "subnet-0e2907431c9988b72",
                "subnet-04ad87f71c6e5ab4d",
                "subnet-09d912bb63ef21b9a"
            ],
            "securityGroupIds": [
                "sg-0c1327f6270afbb36"
            ],
            "clusterSecurityGroupId": "sg-01c84d09d70f39a7f",
            "vpcId": "vpc-0012b8e1cc0abb17d",
            "endpointPublicAccess": true,
            "endpointPrivateAccess": true,
            "publicAccessCidrs": [
                "0.0.0.0/0"
            ]
        },
        "kubernetesNetworkConfig": {
            "serviceIpv4Cidr": "10.100.0.0/16",
            "ipFamily": "ipv4"
        },
        "logging": {
            "clusterLogging": [
                {
                    "types": [
                        "api",
                        "audit",
                        "authenticator",
                        "controllerManager",
                        "scheduler"
                    ],
                    "enabled": true
                }
            ]
        },
        "identity": {
            "oidc": {
                "issuer": "https://oidc.eks.us-east-2.amazonaws.com/id/DALSJ343KE23J3RN45653DSKJTT647TYD"
            }
        },
        "status": "DELETING",
        "certificateAuthority": {
            "data": "XXX_CA_DATA_XXX"
        },
        "platformVersion": "eks.16",
        "tags": {
            "aws:cloudformation:stack-name": "eksctl-my-eks-cluster-cluster",
            "alpha.eksctl.io/cluster-name": "my-eks-cluster",
            "karpenter.sh/discovery": "my-eks-cluster",
            "aws:cloudformation:stack-id": "arn:aws:cloudformation:us-east-2:111122223333:stack/eksctl-my-eks-cluster-cluster/e752ea00-e217-11ee-beae-0a9599c8c7ed",
            "auto-delete": "no",
            "eksctl.cluster.k8s.io/v1alpha1/cluster-name": "my-eks-cluster",
            "EKS-Cluster-Name": "my-eks-cluster",
            "alpha.eksctl.io/cluster-oidc-enabled": "true",
            "aws:cloudformation:logical-id": "ControlPlane",
            "alpha.eksctl.io/eksctl-version": "0.173.0-dev+a7ee89342.2024-03-01T03:40:57Z",
            "Name": "eksctl-my-eks-cluster-cluster/ControlPlane"
        },
        "accessConfig": {
            "authenticationMode": "API_AND_CONFIG_MAP"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS クラスターの削除](https://docs.aws.amazon.com/eks/latest/userguide/delete-cluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/delete-cluster.html)」を参照してください。

### `delete-fargate-profile`
<a name="eks_DeleteFargateProfile_cli_2_topic"></a>

次のコード例は、`delete-fargate-profile` を使用する方法を示しています。

**AWS CLI**  
**例 1: 名前空間を持つセレクターの EKS Fargate プロファイルを作成する**  
次の `delete-fargate-profile` の例では、名前空間を持つセレクターの EKS Fargate Profile を作成します。  

```
aws eks delete-fargate-profile \
    --cluster-name my-eks-cluster \
    --fargate-profile-name my-fargate-profile
```
出力:  

```
{
    "fargateProfile": {
        "fargateProfileName": "my-fargate-profile",
        "fargateProfileArn": "arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/1ac72bb3-3fc6-2631-f1e1-98bff53bed62",
        "clusterName": "my-eks-cluster",
        "createdAt": "2024-03-19T11:48:39.975000-04:00",
        "podExecutionRoleArn": "arn:aws:iam::111122223333:role/role-name",
        "subnets": [
            "subnet-09d912bb63ef21b9a",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-0e2907431c9988b72"
        ],
        "selectors": [
            {
                "namespace": "default",
                "labels": {
                    "foo": "bar"
                }
            }
        ],
        "status": "DELETING",
        "tags": {}
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[AWS Fargate プロファイル - Fargate の削除](https://docs.aws.amazon.com/eks/latest/userguide/fargate-profile.html#delete-fargate-profile)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFargateProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/delete-fargate-profile.html)」を参照してください。

### `delete-nodegroup`
<a name="eks_DeleteNodegroup_cli_2_topic"></a>

次のコード例は、`delete-nodegroup` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EKS クラスターのマネージドノードグループを削除する**  
次の `delete-nodegroup` の例では、Amazon EKS クラスターのマネージド型ノードグループを削除します。  

```
aws eks delete-nodegroup \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup
```
出力:  

```
{
    "nodegroup": {
        "nodegroupName": "my-eks-nodegroup",
        "nodegroupArn": "arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-nodegroup/1ec75f5f-0e21-dcc0-b46e-f9c442685cd8",
        "clusterName": "my-eks-cluster",
        "version": "1.26",
        "releaseVersion": "1.26.12-20240329",
        "createdAt": "2024-04-08T13:25:15.033000-04:00",
        "modifiedAt": "2024-04-08T13:25:31.252000-04:00",
        "status": "DELETING",
        "capacityType": "SPOT",
        "scalingConfig": {
            "minSize": 1,
            "maxSize": 5,
            "desiredSize": 4
        },
        "instanceTypes": [
            "t3.large"
        ],
        "subnets": [
            "subnet-0e2907431c9988b72",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-09d912bb63ef21b9a"
        ],
        "amiType": "AL2_x86_64",
        "nodeRole": "arn:aws:iam::111122223333:role/role-name",
        "labels": {
            "my-eks-nodegroup-label-2": "value-2",
            "my-eks-nodegroup-label-1": "value-1"
        },
        "taints": [
            {
                "key": "taint-key-1",
                "value": "taint-value-1",
                "effect": "NO_EXECUTE"
            }
        ],
        "diskSize": 50,
        "health": {
            "issues": []
        },
        "updateConfig": {
            "maxUnavailable": 2
        },
        "tags": {
            "my-eks-nodegroup-key-1": "value-1",
            "my-eks-nodegroup-key-2": "value-2"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNodegroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/delete-nodegroup.html)」を参照してください。

### `delete-pod-identity-association`
<a name="eks_DeletePodIdentityAssociation_cli_2_topic"></a>

次のコード例は、`delete-pod-identity-association` を使用する方法を示しています。

**AWS CLI**  
**EKS Pod Identity の関連付けを削除するには**  
次の `delete-pod-identity-association` の例では、`eks-customer` という名前の EKS クラスターから、関連付け ID `a-9njjin9gfghecgocd` との EKS Pod Identity の関連付けを削除します。  

```
aws eks delete-pod-identity-association \
    --cluster-name eks-customer \
    --association-id a-9njjin9gfghecgocd
```
出力:  

```
{
    "association": {
        "clusterName": "eks-customer",
        "namespace": "default",
        "serviceAccount": "default",
        "roleArn": "arn:aws:iam::111122223333:role/s3-role",
        "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-9njjin9gfghecgocd",
        "associationId": "a-9njjin9gfghecgocd",
        "tags": {
            "Key2": "value2",
            "Key1": "value1"
        },
        "createdAt": "2025-05-24T19:52:14.135000-05:00",
        "modifiedAt": "2025-05-25T21:10:56.923000-05:00"
    }
}
```
詳細については、*「Amazon* [EKS ユーザーガイド」の「EKS Pod Identity がポッドに AWS サービスへのアクセスを許可する方法](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePodIdentityAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/delete-pod-identity-association.html)」を参照してください。

### `deregister-cluster`
<a name="eks_DeregisterCluster_cli_2_topic"></a>

次のコード例は、`deregister-cluster` を使用する方法を示しています。

**AWS CLI**  
**接続されたクラスターの登録を解除して Amazon EKS コントロールプレーンから削除するには**  
次の `deregister-cluster` の例では、接続されたクラスターを登録解除して、Amazon EKS コントロールプレーンから削除します。  

```
aws eks deregister-cluster \
    --name my-eks-anywhere-cluster
```
出力:  

```
{
    "cluster": {
        "name": "my-eks-anywhere-cluster",
        "arn": "arn:aws:eks:us-east-2:111122223333:cluster/my-eks-anywhere-cluster",
        "createdAt": "2024-04-12T12:38:37.561000-04:00",
        "status": "DELETING",
        "tags": {},
        "connectorConfig": {
            "activationId": "dfb5ad28-13c3-4e26-8a19-5b2457638c74",
            "activationExpiry": "2024-04-15T12:38:37.082000-04:00",
            "provider": "EKS_ANYWHERE",
            "roleArn": "arn:aws:iam::111122223333:role/AmazonEKSConnectorAgentRole"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Deregistering a cluster](https://docs.aws.amazon.com/eks/latest/userguide/deregister-connected-cluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/deregister-cluster.html)」を参照してください。

### `describe-access-entry`
<a name="eks_DescribeAccessEntry_cli_2_topic"></a>

次のコード例は、`describe-access-entry` を使用する方法を示しています。

**AWS CLI**  
**EKS クラスターのアクセスエントリを記述するには**  
次の `describe-access-entry` の例では、EKS クラスターのアクセスエントリについて説明します。  

```
aws eks describe-access-entry \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:user/eks-admin-user
```
出力:  

```
{
    "accessEntry": {
        "clusterName": "eks-customer",
        "principalArn": "arn:aws:iam::111122223333:user/eks-admin-user",
        "kubernetesGroups": [],
        "accessEntryArn": "arn:aws:eks:us-west-2:111122223333:access-entry/eks-customer/user/111122223333/eks-admin-user/0acb1bc6-cb0a-ede6-11ae-a6506e3d36p0",
        "createdAt": "2025-04-14T22:45:48.097000-05:00",
        "modifiedAt": "2025-04-14T22:45:48.097000-05:00",
        "tags": {},
        "username": "arn:aws:iam::111122223333:user/eks-admin-user",
        "type": "STANDARD"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[EKS アクセスエントリを使用して Kubernetes へのアクセス権を IAM ユーザーに付与する](https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccessEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-access-entry.html)」を参照してください。

### `describe-addon-configuration`
<a name="eks_DescribeAddonConfiguration_cli_2_topic"></a>

次のコード例は、`describe-addon-configuration` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon vpc-cni AddOns を作成または更新するときに使用できる設定オプション**  
次の `describe-addon-configuration` の例では、vpc-cni アドオンのアドオンが各バージョンで作成または更新されたときに使用するすべての使用可能な設定スキーマを返します。  

```
aws eks describe-addon-configuration \
    --addon-name vpc-cni \
    --addon-version v1.15.1-eksbuild.1
```
出力:  

```
{
    "addonName": "vpc-cni",
    "addonVersion": "v1.15.1-eksbuild.1",
    "configurationSchema": "{\"$ref\":\"#/definitions/VpcCni\",\"$schema\":\"http://json-schema.org/draft-06/schema#\",\"definitions\":{\"Affinity\":{\"type\":[\"object\",\"null\"]},\"EniConfig\":{\"additionalProperties\":false,\"properties\":{\"create\":{\"type\":\"boolean\"},\"region\":{\"type\":\"string\"},\"subnets\":{\"additionalProperties\":{\"additionalProperties\":false,\"properties\":{\"id\":{\"type\":\"string\"},\"securityGroups\":{\"items\":{\"type\":\"string\"},\"type\":\"array\"}},\"required\":[\"id\"],\"type\":\"object\"},\"minProperties\":1,\"type\":\"object\"}},\"required\":[\"create\",\"region\",\"subnets\"],\"type\":\"object\"},\"Env\":{\"additionalProperties\":false,\"properties\":{\"ADDITIONAL_ENI_TAGS\":{\"type\":\"string\"},\"ANNOTATE_POD_IP\":{\"format\":\"boolean\",\"type\":\"string\"},\"AWS_EC2_ENDPOINT\":{\"type\":\"string\"},\"AWS_EXTERNAL_SERVICE_CIDRS\":{\"type\":\"string\"},\"AWS_MANAGE_ENIS_NON_SCHEDULABLE\":{\"format\":\"boolean\",\"type\":\"string\"},\"AWS_VPC_CNI_NODE_PORT_SUPPORT\":{\"format\":\"boolean\",\"type\":\"string\"},\"AWS_VPC_ENI_MTU\":{\"format\":\"integer\",\"type\":\"string\"},\"AWS_VPC_K8S_CNI_CUSTOM_NETWORK_CFG\":{\"format\":\"boolean\",\"type\":\"string\"},\"AWS_VPC_K8S_CNI_EXCLUDE_SNAT_CIDRS\":{\"type\":\"string\"},\"AWS_VPC_K8S_CNI_EXTERNALSNAT\":{\"format\":\"boolean\",\"type\":\"string\"},\"AWS_VPC_K8S_CNI_LOGLEVEL\":{\"type\":\"string\"},\"AWS_VPC_K8S_CNI_LOG_FILE\":{\"type\":\"string\"},\"AWS_VPC_K8S_CNI_RANDOMIZESNAT\":{\"type\":\"string\"},\"AWS_VPC_K8S_CNI_VETHPREFIX\":{\"type\":\"string\"},\"AWS_VPC_K8S_PLUGIN_LOG_FILE\":{\"type\":\"string\"},\"AWS_VPC_K8S_PLUGIN_LOG_LEVEL\":{\"type\":\"string\"},\"CLUSTER_ENDPOINT\":{\"type\":\"string\"},\"DISABLE_INTROSPECTION\":{\"format\":\"boolean\",\"type\":\"string\"},\"DISABLE_LEAKED_ENI_CLEANUP\":{\"format\":\"boolean\",\"type\":\"string\"},\"DISABLE_METRICS\":{\"format\":\"boolean\",\"type\":\"string\"},\"DISABLE_NETWORK_RESOURCE_PROVISIONING\":{\"format\":\"boolean\",\"type\":\"string\"},\"DISABLE_POD_V6\":{\"format\":\"boolean\",\"type\":\"string\"},\"ENABLE_BANDWIDTH_PLUGIN\":{\"format\":\"boolean\",\"type\":\"string\"},\"ENABLE_POD_ENI\":{\"format\":\"boolean\",\"type\":\"string\"},\"ENABLE_PREFIX_DELEGATION\":{\"format\":\"boolean\",\"type\":\"string\"},\"ENABLE_V4_EGRESS\":{\"format\":\"boolean\",\"type\":\"string\"},\"ENABLE_V6_EGRESS\":{\"format\":\"boolean\",\"type\":\"string\"},\"ENI_CONFIG_ANNOTATION_DEF\":{\"type\":\"string\"},\"ENI_CONFIG_LABEL_DEF\":{\"type\":\"string\"},\"INTROSPECTION_BIND_ADDRESS\":{\"type\":\"string\"},\"IP_COOLDOWN_PERIOD\":{\"format\":\"integer\",\"type\":\"string\"},\"MAX_ENI\":{\"format\":\"integer\",\"type\":\"string\"},\"MINIMUM_IP_TARGET\":{\"format\":\"integer\",\"type\":\"string\"},\"POD_SECURITY_GROUP_ENFORCING_MODE\":{\"type\":\"string\"},\"WARM_ENI_TARGET\":{\"format\":\"integer\",\"type\":\"string\"},\"WARM_IP_TARGET\":{\"format\":\"integer\",\"type\":\"string\"},\"WARM_PREFIX_TARGET\":{\"format\":\"integer\",\"type\":\"string\"}},\"title\":\"Env\",\"type\":\"object\"},\"Init\":{\"additionalProperties\":false,\"properties\":{\"env\":{\"$ref\":\"#/definitions/InitEnv\"}},\"title\":\"Init\",\"type\":\"object\"},\"InitEnv\":{\"additionalProperties\":false,\"properties\":{\"DISABLE_TCP_EARLY_DEMUX\":{\"format\":\"boolean\",\"type\":\"string\"},\"ENABLE_V6_EGRESS\":{\"format\":\"boolean\",\"type\":\"string\"}},\"title\":\"InitEnv\",\"type\":\"object\"},\"Limits\":{\"additionalProperties\":false,\"properties\":{\"cpu\":{\"type\":\"string\"},\"memory\":{\"type\":\"string\"}},\"title\":\"Limits\",\"type\":\"object\"},\"NodeAgent\":{\"additionalProperties\":false,\"properties\":{\"enableCloudWatchLogs\":{\"format\":\"boolean\",\"type\":\"string\"},\"enablePolicyEventLogs\":{\"format\":\"boolean\",\"type\":\"string\"},\"healthProbeBindAddr\":{\"format\":\"integer\",\"type\":\"string\"},\"metricsBindAddr\":{\"format\":\"integer\",\"type\":\"string\"}},\"title\":\"NodeAgent\",\"type\":\"object\"},\"Resources\":{\"additionalProperties\":false,\"properties\":{\"limits\":{\"$ref\":\"#/definitions/Limits\"},\"requests\":{\"$ref\":\"#/definitions/Limits\"}},\"title\":\"Resources\",\"type\":\"object\"},\"Tolerations\":{\"additionalProperties\":false,\"items\":{\"type\":\"object\"},\"type\":\"array\"},\"VpcCni\":{\"additionalProperties\":false,\"properties\":{\"affinity\":{\"$ref\":\"#/definitions/Affinity\"},\"enableNetworkPolicy\":{\"format\":\"boolean\",\"type\":\"string\"},\"enableWindowsIpam\":{\"format\":\"boolean\",\"type\":\"string\"},\"eniConfig\":{\"$ref\":\"#/definitions/EniConfig\"},\"env\":{\"$ref\":\"#/definitions/Env\"},\"init\":{\"$ref\":\"#/definitions/Init\"},\"livenessProbeTimeoutSeconds\":{\"type\":\"integer\"},\"nodeAgent\":{\"$ref\":\"#/definitions/NodeAgent\"},\"readinessProbeTimeoutSeconds\":{\"type\":\"integer\"},\"resources\":{\"$ref\":\"#/definitions/Resources\"},\"tolerations\":{\"$ref\":\"#/definitions/Tolerations\"}},\"title\":\"VpcCni\",\"type\":\"object\"}},\"description\":\"vpc-cni\"}"
}
```
**例 2: Amazon coredns AddOns を作成または更新するときに使用できる設定オプション**  
次の `describe-addon-configuration` の例では、それぞれのバージョンで coredns アドオンのアドオンを作成または更新するときに使用するすべての使用可能な設定スキーマを返します。  

```
aws eks describe-addon-configuration \
    --addon-name coredns \
    --addon-version v1.8.7-eksbuild.4
```
出力:  

```
{
    "addonName": "coredns",
    "addonVersion": "v1.8.7-eksbuild.4",
    "configurationSchema": "{\"$ref\":\"#/definitions/Coredns\",\"$schema\":\"http://json-schema.org/draft-06/schema#\",\"definitions\":{\"Coredns\":{\"additionalProperties\":false,\"properties\":{\"computeType\":{\"type\":\"string\"},\"corefile\":{\"description\":\"Entire corefile contents to use with installation\",\"type\":\"string\"},\"nodeSelector\":{\"additionalProperties\":{\"type\":\"string\"},\"type\":\"object\"},\"replicaCount\":{\"type\":\"integer\"},\"resources\":{\"$ref\":\"#/definitions/Resources\"}},\"title\":\"Coredns\",\"type\":\"object\"},\"Limits\":{\"additionalProperties\":false,\"properties\":{\"cpu\":{\"type\":\"string\"},\"memory\":{\"type\":\"string\"}},\"title\":\"Limits\",\"type\":\"object\"},\"Resources\":{\"additionalProperties\":false,\"properties\":{\"limits\":{\"$ref\":\"#/definitions/Limits\"},\"requests\":{\"$ref\":\"#/definitions/Limits\"}},\"title\":\"Resources\",\"type\":\"object\"}}}"
}
```
詳細については、「*Amazon EKS*」の「[Amazon EKS クラスターの kubeconfig ファイルの作成または更新](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAddonConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-addon-configuration.html)」を参照してください。

### `describe-addon-versions`
<a name="eks_DescribeAddonVersions_cli_2_topic"></a>

次のコード例は、`describe-addon-versions` を使用する方法を示しています。

**AWS CLI**  
**例 1: EKS クラスターで使用できるすべてのアドオンを一覧表示する**  
次の の`describe-addon-versions`例では、使用可能なすべての AWS アドオンを一覧表示します。  

```
aws eks describe-addon-versions  \
    --query 'sort_by(addons  &owner)[].{publisher: publisher, owner: owner, addonName: addonName, type: type}' \
    --output table
```
出力:  

```
--------------------------------------------------------------------------------------------------------------------
|                                               DescribeAddonVersions                                              |
+---------------------------------------------+------------------+-----------------------+-------------------------+
|                  addonName                  |      owner       |       publisher       |          type           |
+---------------------------------------------+------------------+-----------------------+-------------------------+
|  vpc-cni                                    |  aws             |  eks                  |  networking             |
|  snapshot-controller                        |  aws             |  eks                  |  storage                |
|  kube-proxy                                 |  aws             |  eks                  |  networking             |
|  eks-pod-identity-agent                     |  aws             |  eks                  |  security               |
|  coredns                                    |  aws             |  eks                  |  networking             |
|  aws-mountpoint-s3-csi-driver               |  aws             |  s3                   |  storage                |
|  aws-guardduty-agent                        |  aws             |  eks                  |  security               |
|  aws-efs-csi-driver                         |  aws             |  eks                  |  storage                |
|  aws-ebs-csi-driver                         |  aws             |  eks                  |  storage                |
|  amazon-cloudwatch-observability            |  aws             |  eks                  |  observability          |
|  adot                                       |  aws             |  eks                  |  observability          |
|  upwind-security_upwind-operator            |  aws-marketplace |  Upwind Security      |  security               |
|  upbound_universal-crossplane               |  aws-marketplace |  upbound              |  infra-management       |
|  tetrate-io_istio-distro                    |  aws-marketplace |  tetrate-io           |  policy-management      |
|  teleport_teleport                          |  aws-marketplace |  teleport             |  policy-management      |
|  stormforge_optimize-live                   |  aws-marketplace |  StormForge           |  cost-management        |
|  splunk_splunk-otel-collector-chart         |  aws-marketplace |  Splunk               |  monitoring             |
|  solo-io_istio-distro                       |  aws-marketplace |  Solo.io              |  service-mesh           |
|  rafay-systems_rafay-operator               |  aws-marketplace |  rafay-systems        |  kubernetes-management  |
|  new-relic_kubernetes-operator              |  aws-marketplace |  New Relic            |  observability          |
|  netapp_trident-operator                    |  aws-marketplace |  NetApp Inc.          |  storage                |
|  leaksignal_leakagent                       |  aws-marketplace |  leaksignal           |  monitoring             |
|  kubecost_kubecost                          |  aws-marketplace |  kubecost             |  cost-management        |
|  kong_konnect-ri                            |  aws-marketplace |  kong                 |  ingress-service-type   |
|  kasten_k10                                 |  aws-marketplace |  Kasten by Veeam      |  data-protection        |
|  haproxy-technologies_kubernetes-ingress-ee |  aws-marketplace |  HAProxy Technologies |  ingress-controller     |
|  groundcover_agent                          |  aws-marketplace |  groundcover          |  monitoring             |
|  grafana-labs_kubernetes-monitoring         |  aws-marketplace |  Grafana Labs         |  monitoring             |
|  factorhouse_kpow                           |  aws-marketplace |  factorhouse          |  monitoring             |
|  dynatrace_dynatrace-operator               |  aws-marketplace |  dynatrace            |  monitoring             |
|  datree_engine-pro                          |  aws-marketplace |  datree               |  policy-management      |
|  datadog_operator                           |  aws-marketplace |  Datadog              |  monitoring             |
|  cribl_cribledge                            |  aws-marketplace |  Cribl                |  observability          |
|  calyptia_fluent-bit                        |  aws-marketplace |  Calyptia Inc         |  observability          |
|  accuknox_kubearmor                         |  aws-marketplace |  AccuKnox             |  security               |
+---------------------------------------------+------------------+-----------------------+-------------------------+
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
**例 2: EKS 用にサポートされる指定された Kubernetes バージョンで使用可能なすべてのアドオンを一覧表示する**  
次の `describe-addon-versions` の例では、EKS 用にサポートされる指定された Kubernetes バージョンで使用可能なアドオンを一覧表示します。  

```
aws eks describe-addon-versions  \
    --kubernetes-version=1.26 \
    --query 'sort_by(addons  &owner)[].{publisher: publisher, owner: owner, addonName: addonName, type: type}' \
    --output table
```
出力:  

```
--------------------------------------------------------------------------------------------------------------------
|                                               DescribeAddonVersions                                              |
+---------------------------------------------+------------------+-----------------------+-------------------------+
|                  addonName                  |      owner       |       publisher       |          type           |
+---------------------------------------------+------------------+-----------------------+-------------------------+
|  vpc-cni                                    |  aws             |  eks                  |  networking             |
|  snapshot-controller                        |  aws             |  eks                  |  storage                |
|  kube-proxy                                 |  aws             |  eks                  |  networking             |
|  eks-pod-identity-agent                     |  aws             |  eks                  |  security               |
|  coredns                                    |  aws             |  eks                  |  networking             |
|  aws-mountpoint-s3-csi-driver               |  aws             |  s3                   |  storage                |
|  aws-guardduty-agent                        |  aws             |  eks                  |  security               |
|  aws-efs-csi-driver                         |  aws             |  eks                  |  storage                |
|  aws-ebs-csi-driver                         |  aws             |  eks                  |  storage                |
|  amazon-cloudwatch-observability            |  aws             |  eks                  |  observability          |
|  adot                                       |  aws             |  eks                  |  observability          |
|  upwind-security_upwind-operator            |  aws-marketplace |  Upwind Security      |  security               |
|  tetrate-io_istio-distro                    |  aws-marketplace |  tetrate-io           |  policy-management      |
|  stormforge_optimize-live                   |  aws-marketplace |  StormForge           |  cost-management        |
|  splunk_splunk-otel-collector-chart         |  aws-marketplace |  Splunk               |  monitoring             |
|  solo-io_istio-distro                       |  aws-marketplace |  Solo.io              |  service-mesh           |
|  rafay-systems_rafay-operator               |  aws-marketplace |  rafay-systems        |  kubernetes-management  |
|  new-relic_kubernetes-operator              |  aws-marketplace |  New Relic            |  observability          |
|  netapp_trident-operator                    |  aws-marketplace |  NetApp Inc.          |  storage                |
|  leaksignal_leakagent                       |  aws-marketplace |  leaksignal           |  monitoring             |
|  kubecost_kubecost                          |  aws-marketplace |  kubecost             |  cost-management        |
|  kong_konnect-ri                            |  aws-marketplace |  kong                 |  ingress-service-type   |
|  haproxy-technologies_kubernetes-ingress-ee |  aws-marketplace |  HAProxy Technologies |  ingress-controller     |
|  groundcover_agent                          |  aws-marketplace |  groundcover          |  monitoring             |
|  grafana-labs_kubernetes-monitoring         |  aws-marketplace |  Grafana Labs         |  monitoring             |
|  dynatrace_dynatrace-operator               |  aws-marketplace |  dynatrace            |  monitoring             |
|  datadog_operator                           |  aws-marketplace |  Datadog              |  monitoring             |
|  cribl_cribledge                            |  aws-marketplace |  Cribl                |  observability          |
|  calyptia_fluent-bit                        |  aws-marketplace |  Calyptia Inc         |  observability          |
|  accuknox_kubearmor                         |  aws-marketplace |  AccuKnox             |  security               |
+---------------------------------------------+------------------+-----------------------+-------------------------+
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
**例 3: EKS 用にサポートされる指定された Kubernetes バージョンで使用可能なすべての vpc-cni アドオンバージョンを一覧表示する**  
次の `describe-addon-versions` の例では、EKS 用にサポートされる指定された Kubernetes バージョンで使用可能なすべての vpc-cni アドオンバージョンを一覧表示します。  

```
aws eks describe-addon-versions \
    --kubernetes-version=1.26 \
    --addon-name=vpc-cni \
    --query='addons[].addonVersions[].addonVersion'
```
出力:  

```
[
    "v1.18.0-eksbuild.1",
    "v1.17.1-eksbuild.1",
    "v1.16.4-eksbuild.2",
    "v1.16.3-eksbuild.2",
    "v1.16.2-eksbuild.1",
    "v1.16.0-eksbuild.1",
    "v1.15.5-eksbuild.1",
    "v1.15.4-eksbuild.1",
    "v1.15.3-eksbuild.1",
    "v1.15.1-eksbuild.1",
    "v1.15.0-eksbuild.2",
    "v1.14.1-eksbuild.1",
    "v1.14.0-eksbuild.3",
    "v1.13.4-eksbuild.1",
    "v1.13.3-eksbuild.1",
    "v1.13.2-eksbuild.1",
    "v1.13.0-eksbuild.1",
    "v1.12.6-eksbuild.2",
    "v1.12.6-eksbuild.1",
    "v1.12.5-eksbuild.2",
    "v1.12.0-eksbuild.2"
]
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの作成](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#creating-an-add-on)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAddonVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-addon-versions.html)」を参照してください。

### `describe-addon`
<a name="eks_DescribeAddon_cli_2_topic"></a>

次のコード例は、`describe-addon` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスターでアクティブに実行されている EKS アドオンを記述する**  
次の `describe-addon` の例では、Amazon EKS クラスターで EKS アドオンをアクティブに実行しています。  

```
aws eks describe-addon \
    --cluster-name my-eks-cluster \
    --addon-name vpc-cni
```
出力:  

```
{
    "addon": {
        "addonName": "vpc-cni",
        "clusterName": "my-eks-cluster",
        "status": "ACTIVE",
        "addonVersion": "v1.16.4-eksbuild.2",
        "health": {
            "issues": []
        },
        "addonArn": "arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/vpc-cni/0ec71efc-98dd-3203-60b0-4b939b2a5e5f",
        "createdAt": "2024-03-14T13:18:45.417000-04:00",
        "modifiedAt": "2024-03-14T13:18:49.557000-04:00",
        "serviceAccountRoleArn": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm",
        "tags": {
            "eks-addon-key-3": "value-3",
            "eks-addon-key-4": "value-4"
        },
        "configurationValues": "resources:\n    limits:\n        cpu: '100m'\nenv:\n    AWS_VPC_K8S_CNI_LOGLEVEL: 'DEBUG'"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAddon](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-addon.html)」を参照してください。

### `describe-cluster`
<a name="eks_DescribeCluster_cli_2_topic"></a>

次のコード例は、`describe-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスターでアクティブに実行されている EKS アドオンを記述する**  
次の `describe-cluster` の例では、Amazon EKS クラスターで EKS アドオンをアクティブに実行しています。  

```
aws eks describe-cluster \
    --name my-eks-cluster
```
出力:  

```
{
    "cluster": {
        "name": "my-eks-cluster",
        "arn": "arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster",
        "createdAt": "2024-03-14T11:31:44.348000-04:00",
        "version": "1.26",
        "endpoint": "https://JSA79429HJDASKJDJ8223829MNDNASW.yl4.us-east-2.eks.amazonaws.com",
        "roleArn": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-cluster-ServiceRole-zMF6CBakwwbW",
        "resourcesVpcConfig": {
            "subnetIds": [
                "subnet-0fb75d2d8401716e7",
                "subnet-02184492f67a3d0f9",
                "subnet-04098063527aab776",
                "subnet-0e2907431c9988b72",
                "subnet-04ad87f71c6e5ab4d",
                "subnet-09d912bb63ef21b9a"
            ],
            "securityGroupIds": [
                "sg-0c1327f6270afbb36"
            ],
            "clusterSecurityGroupId": "sg-01c84d09d70f39a7f",
            "vpcId": "vpc-0012b8e1cc0abb17d",
            "endpointPublicAccess": true,
            "endpointPrivateAccess": true,
            "publicAccessCidrs": [
                "22.19.18.2/32"
            ]
        },
        "kubernetesNetworkConfig": {
            "serviceIpv4Cidr": "10.100.0.0/16",
            "ipFamily": "ipv4"
        },
        "logging": {
            "clusterLogging": [
                {
                    "types": [
                        "api",
                        "audit",
                        "authenticator",
                        "controllerManager",
                        "scheduler"
                    ],
                    "enabled": true
                }
            ]
        },
        "identity": {
            "oidc": {
                "issuer": "https://oidc.eks.us-east-2.amazonaws.com/id/JSA79429HJDASKJDJ8223829MNDNASW"
            }
        },
        "status": "ACTIVE",
        "certificateAuthority": {
            "data": "CA_DATA_STRING..."
        },
        "platformVersion": "eks.14",
        "tags": {
            "aws:cloudformation:stack-name": "eksctl-my-eks-cluster-cluster",
            "alpha.eksctl.io/cluster-name": "my-eks-cluster",
            "karpenter.sh/discovery": "my-eks-cluster",
            "aws:cloudformation:stack-id": "arn:aws:cloudformation:us-east-2:111122223333:stack/eksctl-my-eks-cluster-cluster/e752ea00-e217-11ee-beae-0a9599c8c7ed",
            "auto-delete": "no",
            "eksctl.cluster.k8s.io/v1alpha1/cluster-name": "my-eks-cluster",
            "EKS-Cluster-Name": "my-eks-cluster",
            "alpha.eksctl.io/cluster-oidc-enabled": "true",
            "aws:cloudformation:logical-id": "ControlPlane",
            "alpha.eksctl.io/eksctl-version": "0.173.0-dev+a7ee89342.2024-03-01T03:40:57Z",
            "Name": "eksctl-my-eks-cluster-cluster/ControlPlane"
        },
        "health": {
            "issues": []
        },
        "accessConfig": {
            "authenticationMode": "API_AND_CONFIG_MAP"
        }
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-cluster.html)」を参照してください。**

### `describe-fargate-profile`
<a name="eks_DescribeFargateProfile_cli_2_topic"></a>

次のコード例は、`describe-fargate-profile` を使用する方法を示しています。

**AWS CLI**  
**Fargate プロファイルを記述する**  
次の `describe-fargate-profile` の例では、Fargate プロファイルについて記述します。  

```
aws eks describe-fargate-profile \
    --cluster-name my-eks-cluster \
    --fargate-profile-name my-fargate-profile
```
出力:  

```
{
    "fargateProfile": {
        "fargateProfileName": "my-fargate-profile",
        "fargateProfileArn": "arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/96c766ce-43d2-f9c9-954c-647334391198",
        "clusterName": "my-eks-cluster",
        "createdAt": "2024-04-11T10:42:52.486000-04:00",
        "podExecutionRoleArn": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-farga-FargatePodExecutionRole-1htfAaJdJUEO",
        "subnets": [
            "subnet-09d912bb63ef21b9a",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-0e2907431c9988b72"
        ],
        "selectors": [
            {
                "namespace": "prod*",
                "labels": {
                    "labelname*?": "*value1"
                }
            },
            {
                "namespace": "*dev*",
                "labels": {
                    "labelname*?": "*value*"
                }
            }
        ],
        "status": "ACTIVE",
        "tags": {
            "eks-fargate-profile-key-2": "value-2",
            "eks-fargate-profile-key-1": "value-1"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFargateProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-fargate-profile.html)」を参照してください。

### `describe-identity-provider-config`
<a name="eks_DescribeIdentityProviderConfig_cli_2_topic"></a>

次のコード例は、`describe-identity-provider-config` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスターに関連付けられた ID プロバイダー設定を記述する**  
次の `describe-identity-provider-config` の例では、Amazon EKS クラスターに関連付けられた ID プロバイダー設定について記述します。  

```
aws eks describe-identity-provider-config \
    --cluster-name my-eks-cluster \
    --identity-provider-config type=oidc,name=my-identity-provider
```
出力:  

```
{
    "identityProviderConfig": {
        "oidc": {
            "identityProviderConfigName": "my-identity-provider",
            "identityProviderConfigArn": "arn:aws:eks:us-east-2:111122223333:identityproviderconfig/my-eks-cluster/oidc/my-identity-provider/8ac76722-78e4-cec1-ed76-d49eea058622",
            "clusterName": "my-eks-cluster",
            "issuerUrl": "https://oidc.eks.us-east-2.amazonaws.com/id/38D6A4619A0A69E342B113ED7F1A7652",
            "clientId": "kubernetes",
            "usernameClaim": "email",
            "usernamePrefix": "my-username-prefix",
            "groupsClaim": "my-claim",
            "groupsPrefix": "my-groups-prefix",
            "requiredClaims": {
                "Claim1": "value1",
                "Claim2": "value2"
            },
            "tags": {
                "env": "dev"
            },
            "status": "ACTIVE"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Authenticate users for your cluster from an OpenID Connect identity provider](https://docs.aws.amazon.com/eks/latest/userguide/authenticate-oidc-identity-provider.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIdentityProviderConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-identity-provider-config.html)」を参照してください。

### `describe-insight`
<a name="eks_DescribeInsight_cli_2_topic"></a>

次のコード例は、`describe-insight` を使用する方法を示しています。

**AWS CLI**  
**ID を使用して EKS クラスターのインサイトの詳細を取得するには**  
次の `describe-insight` の例では、クラスター名とインサイト ID を使用して指定されたインサイトの詳細を返します。  

```
aws eks describe-insight \
    --cluster-name eks-customer \
    --id 38ea7a64-a14f-4e0e-95c7-8dbcab3c3623
```
出力:  

```
{
    "insight": {
        "id": "38ea7a64-a14f-4e0e-95c7-8dbcab3c3623",
        "name": "Kubelet version skew",
        "category": "UPGRADE_READINESS",
        "kubernetesVersion": "1.33",
        "lastRefreshTime": "2025-05-24T11:22:50-05:00",
        "lastTransitionTime": "2025-05-24T11:22:50-05:00",
        "description": "Checks for kubelet versions of worker nodes in the cluster to see if upgrade would cause noncompliance with supported Kubernetes kubelet version skew policy.",
        "insightStatus": {
            "status": "PASSING",
            "reason": "Node kubelet versions match the cluster control plane version."
        },
        "recommendation": "Upgrade your worker nodes to match the Kubernetes version of your cluster control plane.",
        "additionalInfo": {
            "Kubelet version skew policy": "https://kubernetes.io/releases/version-skew-policy/#kubelet",
            "Updating a managed node group": "https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html"
        },
        "resources": [],
        "categorySpecificSummary": {
            "deprecationDetails": []
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[クラスターインサイトを表示する](https://docs.aws.amazon.com/eks/latest/userguide/view-cluster-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInsight](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-insight.html)」を参照してください。

### `describe-nodegroup`
<a name="eks_DescribeNodegroup_cli_2_topic"></a>

次のコード例は、`describe-nodegroup` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスターのマネージド型ノードグループを記述する**  
次の `describe-nodegroup` の例では、Amazon EKS クラスターのマネージド型ノードグループについて説明します。  

```
aws eks describe-nodegroup \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup
```
出力:  

```
{
    "nodegroup": {
        "nodegroupName": "my-eks-nodegroup",
        "nodegroupArn": "arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-nodegroup/a8c75f2f-df78-a72f-4063-4b69af3de5b1",
        "clusterName": "my-eks-cluster",
        "version": "1.26",
        "releaseVersion": "1.26.12-20240329",
        "createdAt": "2024-04-08T11:42:10.555000-04:00",
        "modifiedAt": "2024-04-08T11:44:12.402000-04:00",
        "status": "ACTIVE",
        "capacityType": "ON_DEMAND",
        "scalingConfig": {
            "minSize": 1,
            "maxSize": 3,
            "desiredSize": 1
        },
        "instanceTypes": [
            "t3.medium"
        ],
        "subnets": [
            "subnet-0e2907431c9988b72",
            "subnet-04ad87f71c6e5ab4d",
            "subnet-09d912bb63ef21b9a"
        ],
        "amiType": "AL2_x86_64",
        "nodeRole": "arn:aws:iam::111122223333:role/role-name",
        "labels": {},
        "resources": {
            "autoScalingGroups": [
                {
                    "name": "eks-my-eks-nodegroup-a8c75f2f-df78-a72f-4063-4b69af3de5b1"
                }
            ]
        },
        "diskSize": 20,
        "health": {
            "issues": []
        },
        "updateConfig": {
            "maxUnavailable": 1
        },
        "tags": {}
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNodegroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-nodegroup.html)」を参照してください。

### `describe-pod-identity-association`
<a name="eks_DescribePodIdentityAssociation_cli_2_topic"></a>

次のコード例は、`describe-pod-identity-association` を使用する方法を示しています。

**AWS CLI**  
**Pod Identity の関連付けの詳細を指定するには**  
次の `describe-pod-identity-association` の例では、EKS クラスター内の Pod Identity の関連付けについて説明します。  

```
aws eks describe-pod-identity-association \
    --cluster-name eks-customer \
    --association-id a-9njjin9gfghecgocd
```
出力:  

```
{
    "association": {
        "clusterName": "eks-customer",
        "namespace": "default",
        "serviceAccount": "default",
        "roleArn": "arn:aws:iam::111122223333:role/my-role",
        "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-9njjin9gfghecgocd",
        "associationId": "a-9njjin9gfghecgocd",
        "tags": {
            "Key2": "value2",
            "Key1": "value1"
        },
        "createdAt": "2025-05-24T19:52:14.135000-05:00",
        "modifiedAt": "2025-05-24T19:52:14.135000-05:00"
    }
}
```
詳細については、*「Amazon* [EKS ユーザーガイド」の「EKS Pod Identity がポッドに AWS サービスへのアクセスを許可する方法](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePodIdentityAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-pod-identity-association.html)」を参照してください。

### `describe-update`
<a name="eks_DescribeUpdate_cli_2_topic"></a>

次のコード例は、`describe-update` を使用する方法を示しています。

**AWS CLI**  
**例 1: クラスターの更新を記述するには**  
次の `describe-update` の例では、名前の付いたクラスターの更新について記述しています。  

```
aws eks describe-update \
    --name my-eks-cluster \
    --update-id 10bddb13-a71b-425a-b0a6-71cd03e59161
```
出力:  

```
{
    "update": {
        "id": "10bddb13-a71b-425a-b0a6-71cd03e59161",
        "status": "Successful",
        "type": "EndpointAccessUpdate",
        "params": [
            {
                "type": "EndpointPublicAccess",
                "value": "false"
            },
            {
                "type": "EndpointPrivateAccess",
                "value": "true"
            }
        ],
        "createdAt": "2024-03-14T10:01:26.297000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Updating an Amazon EKS cluster Kubernetes version](https://docs.aws.amazon.com/eks/latest/userguide/update-cluster.html)」を参照してください。  
**例 2: クラスターの更新を記述するには**  
次の `describe-update` の例では、名前の付いたクラスターの更新について記述しています。  

```
aws eks describe-update \
    --name my-eks-cluster \
    --update-id e4994991-4c0f-475a-a040-427e6da52966
```
出力:  

```
{
    "update": {
        "id": "e4994991-4c0f-475a-a040-427e6da52966",
        "status": "Successful",
        "type": "AssociateEncryptionConfig",
        "params": [
            {
                "type": "EncryptionConfig",
                "value": "[{\"resources\":[\"secrets\"],\"provider\":{\"keyArn\":\"arn:aws:kms:region-code:account:key/key\"}}]"
            }
        ],
        "createdAt": "2024-03-14T11:01:26.297000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Updating an Amazon EKS cluster Kubernetes version](https://docs.aws.amazon.com/eks/latest/userguide/update-cluster.html)」を参照してください。  
**例 3: クラスターの更新を記述するには**  
次の `describe-update` の例では、名前の付いたクラスターの更新について記述しています。  

```
aws eks describe-update \
    --name my-eks-cluster \
    --update-id b5f0ba18-9a87-4450-b5a0-825e6e84496f
```
出力:  

```
{
    "update": {
        "id": "b5f0ba18-9a87-4450-b5a0-825e6e84496f",
        "status": "Successful",
        "type": "VersionUpdate",
        "params": [
            {
                "type": "Version",
                "value": "1.29"
            },
            {
                "type": "PlatformVersion",
                "value": "eks.1"
            }
        ],
        "createdAt": "2024-03-14T12:05:26.297000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Updating an Amazon EKS cluster Kubernetes version](https://docs.aws.amazon.com/eks/latest/userguide/update-cluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUpdate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-update.html)」を参照してください。

### `disassociate-access-policy`
<a name="eks_DisassociateAccessPolicy_cli_2_topic"></a>

次のコード例は、`disassociate-access-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセスポリシーとアクセスエントリの関連付けを解除するには**  
次の `disassociate-access-policy` では、アクセスエントリに関連付けられたアクセスポリシーを削除します。  

```
aws eks disassociate-access-policy \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:role/Admin \
    --policy-arn arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon EKS ユーザーガイド*」の「[アクセスポリシーをアクセスエントリに関連付ける](https://docs.aws.amazon.com/eks/latest/userguide/access-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/disassociate-access-policy.html)」を参照してください。

### `disassociate-identity-provider-config`
<a name="eks_DisassociateIdentityProviderConfig_cli_2_topic"></a>

次のコード例は、`disassociate-identity-provider-config` を使用する方法を示しています。

**AWS CLI**  
**ID プロバイダーと Amazon EKS クラスターの関連付けを解除するには**  
次の `disassociate-identity-provider-config` の例では、Amazon EKS クラスターへの ID プロバイダーの関連付けを解除します。  

```
aws eks disassociate-identity-provider-config \
    --cluster-name my-eks-cluster \
    --identity-provider-config 'type=oidc,name=my-identity-provider'
```
出力:  

```
{
    "update": {
        "id": "5f78d14e-c57b-4857-a3e4-cf664ae20949",
        "status": "InProgress",
        "type": "DisassociateIdentityProviderConfig",
        "params": [
            {
                "type": "IdentityProviderConfig",
                "value": "[]"
            }
        ],
        "createdAt": "2024-04-11T13:53:43.314000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Authenticate users for your cluster from an OpenID Connect identity provider - Disassociate an OIDC identity provider from your cluster](https://docs.aws.amazon.com/eks/latest/userguide/authenticate-oidc-identity-provider.html#disassociate-oidc-identity-provider)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateIdentityProviderConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/disassociate-identity-provider-config.html)」を参照してください。

### `get-token`
<a name="eks_GetToken_cli_2_topic"></a>

次のコード例は、`get-token` を使用する方法を示しています。

**AWS CLI**  
**例 1:「my-eks-cluster」という名前の Amazon EKS クラスターの認証トークンを取得する**  
次の `get-token` の例では、my-eks-cluster という名前の Amazon EKS クラスターの認証トークンを取得します。  

```
aws eks get-token \
    --cluster-name my-eks-cluster
```
出力:  

```
{
    "kind": "ExecCredential",
    "apiVersion": "client.authentication.k8s.io/v1beta1",
    "spec": {},
    "status": {
        "expirationTimestamp": "2024-04-11T20:59:56Z",
        "token": "k8s-aws-v1.EXAMPLE_TOKEN_DATA_STRING..."
    }
}
```
**例 2: トークンの署名時に認証情報としてこの roleARN を引き受けることで、「my-eks-cluster」という名前の Amazon EKS クラスターの認証トークンを取得する**  
次の `get-token` の例では、トークンの署名時に認証情報としてこの roleARN を引き受けることで、my-eks-cluster という名前の Amazon EKS クラスターの認証トークンを取得します。  

```
aws eks get-token \
    --cluster-name my-eks-cluster \
    --role-arn arn:aws:iam::111122223333:role/eksctl-EKS-Linux-Cluster-v1-24-cluster-ServiceRole-j1k7AfTIQtnM
```
出力:  

```
{
    "kind": "ExecCredential",
    "apiVersion": "client.authentication.k8s.io/v1beta1",
    "spec": {},
    "status": {
        "expirationTimestamp": "2024-04-11T21:05:26Z",
        "token": "k8s-aws-v1.EXAMPLE_TOKEN_DATA_STRING..."
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/get-token.html)」を参照してください。

### `list-access-entries`
<a name="eks_ListAccessEntries_cli_2_topic"></a>

次のコード例は、`list-access-entries` を使用する方法を示しています。

**AWS CLI**  
**EKS クラスターのアクセスエントリを一覧表示するには**  
次の `list-access-entries` は、EKS クラスター `eks-customer` に関連付けられたアクセスエントリのリストを返します。  

```
aws eks list-access-entries \
    --cluster-name eks-customer
```
出力:  

```
{
    "accessEntries": [
        "arn:aws:iam::111122223333:role/Admin",
        "arn:aws:iam::111122223333:role/admin-test-ip",
        "arn:aws:iam::111122223333:role/assume-worker-node-role",
        "arn:aws:iam::111122223333:user/eks-admin-user"
    ]
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[EKS アクセスエントリを使用して Kubernetes へのアクセスを IAM ユーザーに許可する](https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessEntries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-access-entries.html)」を参照してください。

### `list-access-policies`
<a name="eks_ListAccessPolicies_cli_2_topic"></a>

次のコード例は、`list-access-policies` を使用する方法を示しています。

**AWS CLI**  
**利用可能なすべてのアクセスポリシーを一覧表示するには**  
この `list-access-policies` の例では、利用可能なすべてのアクセスポリシーのリストを返します。  

```
aws eks list-access-policies
```
出力:  

```
{
    "accessPolicies": [
        {
            "name": "AmazonEKSAdminPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSAdminPolicy"
        },
        {
            "name": "AmazonEKSAdminViewPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSAdminViewPolicy"
        },
        {
            "name": "AmazonEKSAutoNodePolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSAutoNodePolicy"
        },
        {
            "name": "AmazonEKSBlockStorageClusterPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSBlockStorageClusterPolicy"
        },
        {
            "name": "AmazonEKSBlockStoragePolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSBlockStoragePolicy"
        },
        {
            "name": "AmazonEKSClusterAdminPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy"
        },
        {
            "name": "AmazonEKSComputeClusterPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSComputeClusterPolicy"
        },
        {
            "name": "AmazonEKSComputePolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSComputePolicy"
        },
        {
            "name": "AmazonEKSEditPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSEditPolicy"
        },
        {
            "name": "AmazonEKSHybridPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSHybridPolicy"
        },
        {
            "name": "AmazonEKSLoadBalancingClusterPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSLoadBalancingClusterPolicy"
        },
        {
            "name": "AmazonEKSLoadBalancingPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSLoadBalancingPolicy"
        },
        {
            "name": "AmazonEKSNetworkingClusterPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSNetworkingClusterPolicy"
        },
        {
            "name": "AmazonEKSNetworkingPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSNetworkingPolicy"
        },
        {
            "name": "AmazonEKSViewPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSViewPolicy"
        },
        {
            "name": "AmazonEMRJobPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonEMRJobPolicy"
        },
        {
            "name": "AmazonSagemakerHyperpodClusterPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonSagemakerHyperpodClusterPolicy"
        },
        {
            "name": "AmazonSagemakerHyperpodControllerPolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonSagemakerHyperpodControllerPolicy"
        },
        {
            "name": "AmazonSagemakerHyperpodSystemNamespacePolicy",
            "arn": "arn:aws:eks::aws:cluster-access-policy/AmazonSagemakerHyperpodSystemNamespacePolicy"
        }
    ]
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[アクセスポリシーをアクセスエントリに関連付ける](https://docs.aws.amazon.com/eks/latest/userguide/access-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-access-policies.html)」を参照してください。

### `list-addons`
<a name="eks_ListAddons_cli_2_topic"></a>

次のコード例は、`list-addons` を使用する方法を示しています。

**AWS CLI**  
**「my-eks-cluster」という名前の Amazon EKS クラスターにインストールされているすべてのアドオンを一覧表示する**  
次の `list-addons` の例では、my-eks-cluster という名前の Amazon EKS クラスターにインストールされているすべてのアドオンを一覧表示します。  

```
aws eks list-addons \
    --cluster-name my-eks-cluster
```
出力:  

```
{
    "addons": [
        "kube-proxy",
        "vpc-cni"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAddons](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-addons.html)」を参照してください。

### `list-associated-access-policies`
<a name="eks_ListAssociatedAccessPolicies_cli_2_topic"></a>

次のコード例は、`list-associated-access-policies` を使用する方法を示しています。

**AWS CLI**  
**アクセスエントリに関連付けられたアクセスポリシーを一覧表示するには**  
次の `list-associated-access-policies` の例では、EKS クラスターのアクセスエントリに関連付けられたアクセスポリシーのリストを返します。  

```
aws eks list-associated-access-policies \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:role/Admin
```
出力:  

```
{
    "associatedAccessPolicies": [
        {
            "policyArn": "arn:aws:eks::aws:cluster-access-policy/AmazonEKSAdminPolicy",
            "accessScope": {
                "type": "cluster",
                "namespaces": []
            },
            "associatedAt": "2025-05-24T17:26:22.935000-05:00",
            "modifiedAt": "2025-05-24T17:26:22.935000-05:00"
        }
    ],
    "clusterName": "eks-customer",
    "principalArn": "arn:aws:iam::111122223333:role/Admin"
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[EKS アクセスエントリを使用して Kubernetes へのアクセスを IAM ユーザーに許可する](https://docs.aws.amazon.com/eks/latest/userguide/access-entries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssociatedAccessPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-associated-access-policies.html)」を参照してください。

### `list-clusters`
<a name="eks_ListClusters_cli_2_topic"></a>

次のコード例は、`list-clusters` を使用する方法を示しています。

**AWS CLI**  
**「my-eks-cluster」という名前の Amazon EKS クラスターにインストールされているすべてのアドオンを一覧表示するには**  
次の `list-clusters` の例では、my-eks-cluster という名前の Amazon EKS クラスターにインストールされているすべてのアドオンを一覧表示します。  

```
aws eks list-clusters
```
出力:  

```
{
    "clusters": [
        "prod",
        "qa",
        "stage",
        "my-eks-cluster"
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-clusters.html)」を参照してください。**

### `list-fargate-profiles`
<a name="eks_ListFargateProfiles_cli_2_topic"></a>

次のコード例は、`list-fargate-profiles` を使用する方法を示しています。

**AWS CLI**  
**「my-eks-cluster」という名前の Amazon EKS クラスター内のすべての Fargate プロファイルを一覧表示するには**  
次の `list-fargate-profiles` の例では、my-eks-cluster という名前の Amazon EKS クラスター内のすべての Fargate プロファイルを一覧表示します。  

```
aws eks list-fargate-profiles \
    --cluster-name my-eks-cluster
```
出力:  

```
{
    "fargateProfileNames": [
        "my-fargate-profile"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFargateProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-fargate-profiles.html)」を参照してください。

### `list-identity-provider-configs`
<a name="eks_ListIdentityProviderConfigs_cli_2_topic"></a>

次のコード例は、`list-identity-provider-configs` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスターに関連付けられている ID プロバイダーを一覧表示する**  
次の `list-identity-provider-configs` の例では、Amazon EKS クラスターに関連付けられている ID プロバイダーを一覧表示します。  

```
aws eks list-identity-provider-configs \
    --cluster-name my-eks-cluster
```
出力:  

```
{
    "identityProviderConfigs": [
        {
            "type": "oidc",
            "name": "my-identity-provider"
        }
    ]
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Authenticate users for your cluster from an OpenID Connect identity provider](https://docs.aws.amazon.com/eks/latest/userguide/authenticate-oidc-identity-provider.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIdentityProviderConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-identity-provider-configs.html)」を参照してください。

### `list-insights`
<a name="eks_ListInsights_cli_2_topic"></a>

次のコード例は、`list-insights` を使用する方法を示しています。

**AWS CLI**  
**指定されたクラスターのすべてのインサイトを一覧表示するには**  
次の `list-insights` の例では、指定されたクラスターに対してチェックされたすべてのインサイトのリストを返します。  

```
aws eks list-insights \
--cluster-name eks-customer
```
出力:  

```
{
    "insights": [
        {
            "id": "38ea7a64-a14f-4e0e-95c7-8dbcab3c3616",
            "name": "Kubelet version skew",
            "category": "UPGRADE_READINESS",
            "kubernetesVersion": "1.33",
            "lastRefreshTime": "2025-05-24T11:22:50-05:00",
            "lastTransitionTime": "2025-05-24T11:22:50-05:00",
            "description": "Checks for kubelet versions of worker nodes in the cluster to see if upgrade would cause noncompliance with supported Kubernetes kubelet version skew policy.",
            "insightStatus": {
                "status": "PASSING",
                "reason": "Node kubelet versions match the cluster control plane version."
            }
        },
        {
            "id": "9cd91472-f99c-45a9-b7d7-54d4900dee23",
            "name": "EKS add-on version compatibility",
            "category": "UPGRADE_READINESS",
            "kubernetesVersion": "1.33",
            "lastRefreshTime": "2025-05-24T11:22:59-05:00",
            "lastTransitionTime": "2025-05-24T11:22:50-05:00",
            "description": "Checks version of installed EKS add-ons to ensure they are compatible with the next version of Kubernetes. ",
            "insightStatus": {
                "status": "PASSING",
                "reason": "All installed EKS add-on versions are compatible with next Kubernetes version."
            }
        },
        {
            "id": "0deb269d-b1e1-458c-a2b4-7a57f940c875",
            "name": "Cluster health issues",
            "category": "UPGRADE_READINESS",
            "kubernetesVersion": "1.33",
            "lastRefreshTime": "2025-05-24T11:22:59-05:00",
            "lastTransitionTime": "2025-05-24T11:22:50-05:00",
            "description": "Checks for any cluster health issues that prevent successful upgrade to the next Kubernetes version on EKS.",
            "insightStatus": {
                "status": "PASSING",
                "reason": "No cluster health issues detected."
            }
        },
        {
            "id": "214fa274-344f-420b-812a-5049ce72c9ww",
            "name": "kube-proxy version skew",
            "category": "UPGRADE_READINESS",
            "kubernetesVersion": "1.33",
            "lastRefreshTime": "2025-05-24T11:22:50-05:00",
            "lastTransitionTime": "2025-05-24T11:22:50-05:00",
            "description": "Checks version of kube-proxy in cluster to see if upgrade would cause noncompliance with supported Kubernetes kube-proxy version skew policy.",
            "insightStatus": {
                "status": "PASSING",
                "reason": "kube-proxy versions match the cluster control plane version."
            }
        }
    ]
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[クラスターインサイトを表示する](https://docs.aws.amazon.com/eks/latest/userguide/view-cluster-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInsights](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-insights.html)」を参照してください。

### `list-nodegroups`
<a name="eks_ListNodegroups_cli_2_topic"></a>

次のコード例は、`list-nodegroups` を使用する方法を示しています。

**AWS CLI**  
**Amazon EKS クラスター内のすべてのノードグループを一覧表示する**  
次の `list-nodegroups` の例では、 Amazon EKS クラスターにすべてのノードグループを一覧表示します。  

```
aws eks list-nodegroups \
    --cluster-name my-eks-cluster
```
出力:  

```
{
    "nodegroups": [
        "my-eks-managed-node-group",
        "my-eks-nodegroup"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListNodegroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-nodegroups.html)」を参照してください。

### `list-pod-identity-associations`
<a name="eks_ListPodIdentityAssociations_cli_2_topic"></a>

次のコード例は、`list-pod-identity-associations` を使用する方法を示しています。

**AWS CLI**  
**例 1: EKS クラスター内の Pod Identity の関連付けを一覧表示するには**  
次の `list-pod-identity-associations` は、すべての名前空間とサービスアカウントで `eks-customer` という名前の EKS クラスターに関連付けられた Pod Identity の関連付けのリストを返します。  

```
aws eks list-pod-identity-associations \
    --cluster-name eks-customer
```
出力:  

```
{
    "associations": [
        {
            "clusterName": "eks-customer",
            "namespace": "default",
            "serviceAccount": "default",
            "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-9njjin9gfghecgocd",
            "associationId": "a-9njjin9gfghecgocd"
        },
        {
            "clusterName": "eks-customer",
            "namespace": "kube-system",
            "serviceAccount": "eks-customer",
            "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-dvtacahdvjn01ffbc",
            "associationId": "a-dvtacahdvjn01ffbc"
        },
        {
            "clusterName": "eks-customer",
            "namespace": "kube-system",
            "serviceAccount": "coredns",
            "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-yrpsdroc4ei7k6xps",
            "associationId": "a-yrpsdroc4ei7k6xps"
        }
    ]
}
```
詳細については、*「Amazon* [EKS ユーザーガイド」の「EKS Pod Identity がポッドに AWS サービスへのアクセスを許可する方法](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)」を参照してください。  
**例 2: 名前空間とサービスアカウントに基づいて EKS クラスター内の Pod Identity の関連付けを一覧表示するには**  
次の `list-pod-identity-associations` は、名前空間とサービスアカウントに基づいて EKS クラスター内の Pod Identity の関連付けのリストを返します。  

```
aws eks list-pod-identity-associations \
    --cluster-name eks-customer \
    --namespace kube-system \
    --service-account eks-customer
```
出力:  

```
{
    "associations": [
        {
            "clusterName": "eks-customer",
            "namespace": "kube-system",
            "serviceAccount": "eks-customer",
            "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-dvtacahdvjn01ffbc",
            "associationId": "a-dvtacahdvjn01ffbc"
        }
    ]
}
```
詳細については、*「Amazon* [EKS ユーザーガイド」の「EKS Pod Identity がポッドに AWS サービスへのアクセスを許可する方法](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPodIdentityAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-pod-identity-associations.html)」を参照してください。

### `list-tags-for-resource`
<a name="eks_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EKS クラスター ARN のすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Amazon EKS クラスター ARN のすべてのタグを一覧表示します。  

```
aws eks list-tags-for-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster
```
出力:  

```
{
    "tags": {
        "aws:cloudformation:stack-name": "eksctl-my-eks-cluster-cluster",
        "alpha.eksctl.io/cluster-name": "my-eks-cluster",
        "karpenter.sh/discovery": "my-eks-cluster",
        "aws:cloudformation:stack-id": "arn:aws:cloudformation:us-east-2:111122223333:stack/eksctl-my-eks-cluster-cluster/e752ea00-e217-11ee-beae-0a9599c8c7ed",
        "auto-delete": "no",
        "eksctl.cluster.k8s.io/v1alpha1/cluster-name": "my-eks-cluster",
        "EKS-Cluster-Name": "my-eks-cluster",
        "alpha.eksctl.io/cluster-oidc-enabled": "true",
        "aws:cloudformation:logical-id": "ControlPlane",
        "alpha.eksctl.io/eksctl-version": "0.173.0-dev+a7ee89342.2024-03-01T03:40:57Z",
        "Name": "eksctl-my-eks-cluster-cluster/ControlPlane"
    }
}
```
**例 2: Amazon EKS ノードグループ ARN のすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Amazon EKS ノードグループ ARN のすべてのタグを一覧表示します。  

```
aws eks list-tags-for-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-managed-node-group/60c71ed2-2cfb-020f-a5f4-ad32477f198c
```
出力:  

```
{
    "tags": {
        "aws:cloudformation:stack-name": "eksctl-my-eks-cluster-nodegroup-my-eks-managed-node-group",
        "aws:cloudformation:stack-id": "arn:aws:cloudformation:us-east-2:111122223333:stack/eksctl-my-eks-cluster-nodegroup-my-eks-managed-node-group/eaa20310-e219-11ee-b851-0ab9ad8228ff",
        "eksctl.cluster.k8s.io/v1alpha1/cluster-name": "my-eks-cluster",
        "EKS-Cluster-Name": "my-eks-cluster",
        "alpha.eksctl.io/nodegroup-type": "managed",
        "NodeGroup Name 1": "my-eks-managed-node-group",
        "k8s.io/cluster-autoscaler/enabled": "true",
        "nodegroup-role": "worker",
        "alpha.eksctl.io/cluster-name": "my-eks-cluster",
        "alpha.eksctl.io/nodegroup-name": "my-eks-managed-node-group",
        "karpenter.sh/discovery": "my-eks-cluster",
        "NodeGroup Name 2": "AmazonLinux-Linux-Managed-NG-v1-26-v1",
        "auto-delete": "no",
        "k8s.io/cluster-autoscaler/my-eks-cluster": "owned",
        "aws:cloudformation:logical-id": "ManagedNodeGroup",
        "alpha.eksctl.io/eksctl-version": "0.173.0-dev+a7ee89342.2024-03-01T03:40:57Z"
    }
}
```
**例 3: Amazon EKS Fargate プロフィル ARNe のすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Amazon EKS Fargate プロファイル ARN のすべてのタグを一覧表示します。  

```
aws eks list-tags-for-resource  \
    --resource-arn arn:aws:eks:us-east-2:111122223333:fargateprofile/my-eks-cluster/my-fargate-profile/d6c76780-e541-0725-c816-36754cab734b
```
出力:  

```
{
    "tags": {
        "eks-fargate-profile-key-2": "value-2",
        "eks-fargate-profile-key-1": "value-1"
    }
}
```
**例 4: Amazon EKS アドオン ARN のすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Amazon EKS アドオン ARN のすべてのタグを一覧表示します。  

```
aws eks list-tags-for-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:addon/my-eks-cluster/vpc-cni/0ec71efc-98dd-3203-60b0-4b939b2a5e5f
```
出力:  

```
{
    "tags": {
        "eks-addon-key-2": "value-2",
        "eks-addon-key-1": "value-1"
    }
}
```
**例 5: Amazon EKS OIDC ID プロバイダー ARN のすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Amazon EKS OIDC ID プロバイダー ARN のすべてのタグを一覧表示します。  

```
aws eks list-tags-for-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:identityproviderconfig/my-eks-cluster/oidc/my-identity-provider/8ac76722-78e4-cec1-ed76-d49eea058622
```
出力:  

```
{
    "tags": {
        "my-identity-provider": "test"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-tags-for-resource.html)」を参照してください。

### `list-update`
<a name="eks_ListUpdate_cli_2_topic"></a>

次のコード例は、`list-update` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EKS クラスター名に関連付けられた更新を一覧表示するには**  
次の `list-updates` の例では、Amazon EKS クラスター名のすべての更新 ID を一覧表示します。  

```
aws eks list-updates \
    --name my-eks-cluster
```
出力:  

```
{
    "updateIds": [
        "5f78d14e-c57b-4857-a3e4-cf664ae20949",
        "760e5a3f-adad-48c7-88d3-7ac283c09c26",
        "cd4ec863-bc55-47d5-a377-3971502f529b",
        "f12657ce-e869-4f17-b158-a82ab8b7d937"
    ]
}
```
**例 2: Amazon EKS ノードグループのすべての更新 ID を一覧表示するには**  
次の `list-updates` の例では、Amazon EKS ノードグループのすべての更新 ID を一覧表示します。  

```
aws eks list-updates \
    --name my-eks-cluster \
    --nodegroup-name my-eks-managed-node-group
```
出力:  

```
{
    "updateIds": [
        "8c6c1bef-61fe-42ac-a242-89412387b8e7"
    ]
}
```
**例 3: Amazon EKS アドオンのすべての更新 ID を一覧表示するには**  
次の `list-updates` の例では、Amazon EKS アドオンのすべての更新 ID を一覧表示します。  

```
aws eks list-updates \
    --name my-eks-cluster \
    --addon-name vpc-cni
```
出力:  

```
{
    "updateIds": [
        "9cdba8d4-79fb-3c83-afe8-00b508d33268"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUpdate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-update.html)」を参照してください。

### `list-updates`
<a name="eks_ListUpdates_cli_2_topic"></a>

次のコード例は、`list-updates` を使用する方法を示しています。

**AWS CLI**  
**クラスターの更新を一覧表示するには**  
このコマンド例では、デフォルトのリージョンで `example` という名前のクラスターの現在の更新を一覧表示します。  
コマンド:  

```
aws eks list-updates --name example
```
出力:  

```
{
    "updateIds": [
        "10bddb13-a71b-425a-b0a6-71cd03e59161"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUpdates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/list-updates.html)」を参照してください。

### `register-cluster`
<a name="eks_RegisterCluster_cli_2_topic"></a>

次のコード例は、`register-cluster` を使用する方法を示しています。

**AWS CLI**  
**例 1: 外部 EKS\$1ANYWHERE Kubernetes クラスターを Amazon EKS に登録する**  
次の `register-cluster` の例では、外部 EKS\$1ANYWHERE Kubernetes クラスターを Amazon EKS に登録します。  

```
aws eks register-cluster \
    --name my-eks-anywhere-cluster \
    --connector-config 'roleArn=arn:aws:iam::111122223333:role/AmazonEKSConnectorAgentRole,provider=EKS_ANYWHERE'
```
出力:  

```
{
    "cluster": {
        "name": "my-eks-anywhere-cluster",
        "arn": "arn:aws:eks:us-east-2:111122223333:cluster/my-eks-anywhere-cluster",
        "createdAt": "2024-04-12T12:38:37.561000-04:00",
        "status": "PENDING",
        "tags": {},
        "connectorConfig": {
            "activationId": "xxxxxxxxACTIVATION_IDxxxxxxxx",
            "activationCode": "xxxxxxxxACTIVATION_CODExxxxxxxx",
            "activationExpiry": "2024-04-15T12:38:37.082000-04:00",
            "provider": "EKS_ANYWHERE",
            "roleArn": "arn:aws:iam::111122223333:role/AmazonEKSConnectorAgentRole"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[外部のクラスターの接続](https://docs.aws.amazon.com/eks/latest/userguide/connecting-cluster.html)」を参照してください。  
**例 2: 外部 Kubernetes クラスターを Amazon EKS に登録する**  
次の `register-cluster` の例では、外部 EKS\$1ANYWHERE Kubernetes クラスターを Amazon EKS に登録します。  

```
aws eks register-cluster \
    --name my-eks-anywhere-cluster \
    --connector-config 'roleArn=arn:aws:iam::111122223333:role/AmazonEKSConnectorAgentRole,provider=OTHER'
```
出力:  

```
{
    "cluster": {
        "name": "my-onprem-k8s-cluster",
        "arn": "arn:aws:eks:us-east-2:111122223333:cluster/my-onprem-k8s-cluster",
        "createdAt": "2024-04-12T12:42:10.861000-04:00",
        "status": "PENDING",
        "tags": {},
        "connectorConfig": {
            "activationId": "xxxxxxxxACTIVATION_IDxxxxxxxx",
            "activationCode": "xxxxxxxxACTIVATION_CODExxxxxxxx",
            "activationExpiry": "2024-04-15T12:42:10.339000-04:00",
            "provider": "OTHER",
            "roleArn": "arn:aws:iam::111122223333:role/AmazonEKSConnectorAgentRole"
        }
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[外部のクラスターの接続](https://docs.aws.amazon.com/eks/latest/userguide/connecting-cluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/register-cluster.html)」を参照してください。

### `tag-resource`
<a name="eks_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定されたタグを Amazon EKS クラスターに追加するには**  
次の `tag-resource` の例では、指定されたタグを Amazon EKS クラスターに追加します。  

```
aws eks tag-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster \
    --tag 'my-eks-cluster-test-1=test-value-1,my-eks-cluster-dev-1=dev-value-2'
```
このコマンドでは何も出力されません。  
**例 2: 指定されたタグを Amazon EKS ノードグループに追加するには**  
次の `tag-resource` の例では、Amazon EKS ノードグループに指定されたタグを追加します。  

```
aws eks tag-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-managed-node-group/60c71ed2-2cfb-020f-a5f4-ad32477f198c \
    --tag 'my-eks-nodegroup-test-1=test-value-1,my-eks-nodegroup-dev-1=dev-value-2'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="eks_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EKS クラスターから指定されたタグを削除するには**  
次の `untag-resource` の例は、指定されたタグを Amazon EKS クラスターから削除します。  

```
aws eks untag-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster \
    --tag-keys "my-eks-cluster-test-1" "my-eks-cluster-dev-1"
```
このコマンドでは何も出力されません。  
**例 2: Amazon EKS ノードグループから指定されたタグを削除するには**  
次の `untag-resource` の例では、Amazon EKS ノードグループから指定されたタグを削除します。  

```
aws eks untag-resource \
    --resource-arn arn:aws:eks:us-east-2:111122223333:nodegroup/my-eks-cluster/my-eks-managed-node-group/60c71ed2-2cfb-020f-a5f4-ad32477f198c \
    --tag-keys "my-eks-nodegroup-test-1" "my-eks-nodegroup-dev-1"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/untag-resource.html)」を参照してください。

### `update-access-entry`
<a name="eks_UpdateAccessEntry_cli_2_topic"></a>

次のコード例は、`update-access-entry` を使用する方法を示しています。

**AWS CLI**  
**EKS クラスターのアクセスエントリを更新するには**  
次の `update-access-entry` は、Kubernetes グループ `tester` を追加して、EKS クラスターのアクセスエントリを更新します。  

```
aws eks update-access-entry \
    --cluster-name eks-customer \
    --principal-arn arn:aws:iam::111122223333:role/Admin \
    --kubernetes-groups tester
```
出力:  

```
{
    "accessEntry": {
        "clusterName": "eks-customer",
        "principalArn": "arn:aws:iam::111122223333:role/Admin",
        "kubernetesGroups": [
            "tester"
        ],
        "accessEntryArn": "arn:aws:eks:us-west-2:111122223333:access-entry/eks-customer/role/111122223333/Admin/d2cb8183-d6ec-b82a-d967-eca21902a4b4",
        "createdAt": "2025-05-24T11:02:04.432000-05:00",
        "modifiedAt": "2025-05-24T17:08:01.608000-05:00",
        "tags": {},
        "username": "arn:aws:sts::111122223333:assumed-role/Admin/{{SessionName}}",
        "type": "STANDARD"
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[アクセスエントリを更新する](https://docs.aws.amazon.com/eks/latest/userguide/updating-access-entries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccessEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-access-entry.html)」を参照してください。

### `update-addon`
<a name="eks_UpdateAddon_cli_2_topic"></a>

次のコード例は、`update-addon` を使用する方法を示しています。

**AWS CLI**  
**例 1。サービスアカウントロール ARN を使用して Amazon EKS アドオンを更新するには**  
次の `update-addon` の例では、サービスアカウントロール ARN を使用して Amazon EKS アドオンを更新します。  

```
aws eks update-addon \
    --cluster-name my-eks-cluster \
    --addon-name vpc-cni \
    --service-account-role-arn arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm
```
出力:  

```
{
    "update": {
        "id": "c00d2de2-c2e4-3d30-929e-46b8edec2ce4",
        "status": "InProgress",
        "type": "AddonUpdate",
        "params": [
            {
                "type": "ServiceAccountRoleArn",
                "value": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm"
            }
        ],
        "updatedAt": "2024-04-12T16:04:55.614000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの更新](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#updating-an-add-on)」を参照してください。  
**例 2。特定のアドオンバージョンで Amazon EKS アドオンを更新するには**  
次の `update-addon` のコマンド例では、Amazon EKS アドオンを特定のアドオンバージョンで更新します。  

```
aws eks update-addon \
    --cluster-name my-eks-cluster \
    --addon-name vpc-cni \
    --service-account-role-arn arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm \
    --addon-version v1.16.4-eksbuild.2
```
出力:  

```
{
    "update": {
        "id": "f58dc0b0-2b18-34bd-bc6a-e4abc0011f36",
        "status": "InProgress",
        "type": "AddonUpdate",
        "params": [
            {
                "type": "AddonVersion",
                "value": "v1.16.4-eksbuild.2"
            },
            {
                "type": "ServiceAccountRoleArn",
                "value": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm"
            }
        ],
        "createdAt": "2024-04-12T16:07:16.550000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの更新](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#updating-an-add-on)」を参照してください。  
**例 3。Amazon EKS アドオンをカスタム設定値で更新し、競合の詳細を解決するには**  
次の `update-addon` のコマンド例では、Amazon EKS アドオンをカスタム設定値で更新し、競合の詳細を解決します。  

```
aws eks update-addon \
    --cluster-name my-eks-cluster \
    --addon-name vpc-cni \
    --service-account-role-arn arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm \
    --addon-version v1.16.4-eksbuild.2 \
    --configuration-values '{"resources": {"limits":{"cpu":"100m"}, "requests":{"cpu":"50m"}}}' \
    --resolve-conflicts PRESERVE
```
出力:  

```
{
    "update": {
        "id": "cd9f2173-a8d8-3004-a90f-032f14326520",
        "status": "InProgress",
        "type": "AddonUpdate",
        "params": [
            {
                "type": "AddonVersion",
                "value": "v1.16.4-eksbuild.2"
            },
            {
                "type": "ServiceAccountRoleArn",
                "value": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm"
            },
            {
                "type": "ResolveConflicts",
                "value": "PRESERVE"
            },
            {
                "type": "ConfigurationValues",
                "value": "{\"resources\": {\"limits\":{\"cpu\":\"100m\"}, \"requests\":{\"cpu\":\"50m\"}}}"
            }
        ],
        "createdAt": "2024-04-12T16:16:27.363000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの更新](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#updating-an-add-on)」を参照してください。  
**例 4。Amazon EKS アドオンをカスタム JSON 設定値ファイルで更新するには**  
次の `update-addon` の例では、カスタム JSON 設定値を使用して Amazon EKS アドオンを更新し、競合の詳細を解決します。  

```
aws eks update-addon \
    --cluster-name my-eks-cluster \
    --addon-name vpc-cni \
    --service-account-role-arn arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm \
    --addon-version v1.17.1-eksbuild.1 \
    --configuration-values 'file://configuration-values.json' \
    --resolve-conflicts PRESERVE
```
`configuration-values.json` の内容:  

```
{
    "resources": {
        "limits": {
            "cpu": "100m"
        },
        "requests": {
            "cpu": "50m"
        }
    },
    "env": {
        "AWS_VPC_K8S_CNI_LOGLEVEL": "ERROR"
    }
}
```
出力:  

```
{
    "update": {
        "id": "6881a437-174f-346b-9a63-6e91763507cc",
        "status": "InProgress",
        "type": "AddonUpdate",
        "params": [
            {
                "type": "AddonVersion",
                "value": "v1.17.1-eksbuild.1"
            },
            {
                "type": "ServiceAccountRoleArn",
                "value": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm"
            },
            {
                "type": "ResolveConflicts",
                "value": "PRESERVE"
            },
            {
                "type": "ConfigurationValues",
                "value": "{\n    \"resources\": {\n        \"limits\": {\n            \"cpu\": \"100m\"\n        },\n        \"requests\": {\n            \"cpu\": \"50m\"\n        }\n    },\n    \"env\": {\n        \"AWS_VPC_K8S_CNI_LOGLEVEL\": \"ERROR\"\n    }\n}"
            }
        ],
        "createdAt": "2024-04-12T16:22:55.519000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの更新](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#updating-an-add-on)」を参照してください。  
**例 5。Amazon EKS アドオンをカスタム YAML 設定値ファイルで更新するには**  
次の `update-addon` の例では、カスタム YAML 設定値を使用して Amazon EKS アドオンを更新し、競合の詳細を解決します。  

```
aws eks update-addon \
    --cluster-name my-eks-cluster \
    --addon-name vpc-cni \
    --service-account-role-arn arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm \
    --addon-version v1.18.0-eksbuild.1 \
    --configuration-values 'file://configuration-values.yaml' \
    --resolve-conflicts PRESERVE
```
`configuration-values.yaml` の内容:  

```
resources:
    limits:
        cpu: '100m'
    requests:
        cpu: '50m'
env:
    AWS_VPC_K8S_CNI_LOGLEVEL: 'DEBUG'
```
出力:  

```
{
    "update": {
        "id": "a067a4c9-69d0-3769-ace9-d235c5b16701",
        "status": "InProgress",
        "type": "AddonUpdate",
        "params": [
            {
                "type": "AddonVersion",
                "value": "v1.18.0-eksbuild.1"
            },
            {
                "type": "ServiceAccountRoleArn",
                "value": "arn:aws:iam::111122223333:role/eksctl-my-eks-cluster-addon-vpc-cni-Role1-YfakrqOC1UTm"
            },
            {
                "type": "ResolveConflicts",
                "value": "PRESERVE"
            },
            {
                "type": "ConfigurationValues",
                "value": "resources:\n    limits:\n        cpu: '100m'\n    requests:\n        cpu: '50m'\nenv:\n    AWS_VPC_K8S_CNI_LOGLEVEL: 'DEBUG'"
            }
        ],
        "createdAt": "2024-04-12T16:25:07.212000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Amazon EKS アドオンの管理 - アドオンの更新](https://docs.aws.amazon.com/eks/latest/userguide/managing-add-ons.html#updating-an-add-on)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAddon](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-addon.html)」を参照してください。

### `update-cluster-config`
<a name="eks_UpdateClusterConfig_cli_2_topic"></a>

次のコード例は、`update-cluster-config` を使用する方法を示しています。

**AWS CLI**  
**クラスターエンドポイントアクセスを更新するには**  
このコマンド例では、クラスターを更新してエンドポイントのパブリックアクセスを無効にし、プライベートエンドポイントアクセスを有効にします。  
コマンド:  

```
aws eks update-cluster-config --name example \
--resources-vpc-config endpointPublicAccess=false,endpointPrivateAccess=true
```
出力:  

```
{
    "update": {
        "id": "ec883c93-2e9e-407c-a22f-8f6fa6e67d4f",
        "status": "InProgress",
        "type": "EndpointAccessUpdate",
        "params": [
            {
                "type": "EndpointPublicAccess",
                "value": "false"
            },
            {
                "type": "EndpointPrivateAccess",
                "value": "true"
            }
        ],
        "createdAt": 1565806986.506,
        "errors": []
    }
}
```
**クラスターのログ記録を有効にするには**  
このコマンド例では、`example` という名前のクラスターのすべてのクラスターコントロールプレーンのログ記録タイプを有効にします。  
コマンド:  

```
aws eks update-cluster-config --name example \
--logging '{"clusterLogging":[{"types":["api","audit","authenticator","controllerManager","scheduler"],"enabled":true}]}'
```
出力:  

```
{
    "update": {
        "id": "7551c64b-1d27-4b1e-9f8e-c45f056eb6fd",
        "status": "InProgress",
        "type": "LoggingUpdate",
        "params": [
            {
                "type": "ClusterLogging",
                "value": "{\"clusterLogging\":[{\"types\":[\"api\",\"audit\",\"authenticator\",\"controllerManager\",\"scheduler\"],\"enabled\":true}]}"
            }
        ],
        "createdAt": 1565807210.37,
        "errors": []
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateClusterConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-cluster-config.html)」を参照してください。

### `update-cluster-version`
<a name="eks_UpdateClusterVersion_cli_2_topic"></a>

次のコード例は、`update-cluster-version` を使用する方法を示しています。

**AWS CLI**  
**「my-eks-cluster」という名前の Amazon EKS クラスターを指定された Kubernetes バージョンに更新するには**  
次の `update-cluster-version` の例では、Amazon EKS クラスターを指定された Kubernetes バージョンに更新します。  

```
aws eks update-cluster-version \
    --name my-eks-cluster \
    --kubernetes-version 1.27
```
出力:  

```
{
    "update": {
        "id": "e4091a28-ea14-48fd-a8c7-975aeb469e8a",
        "status": "InProgress",
        "type": "VersionUpdate",
        "params": [
            {
                "type": "Version",
                "value": "1.27"
            },
            {
                "type": "PlatformVersion",
                "value": "eks.16"
            }
        ],
        "createdAt": "2024-04-12T16:56:01.082000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[Updating an Amazon EKS cluster Kubernetes version](https://docs.aws.amazon.com/eks/latest/userguide/update-cluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateClusterVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-cluster-version.html)」を参照してください。

### `update-kubeconfig`
<a name="eks_UpdateKubeconfig_cli_2_topic"></a>

次のコード例は、`update-kubeconfig` を使用する方法を示しています。

**AWS CLI**  
**例 1: 「my-eks-cluster」という名前の Amazon EKS クラスターに接続できるように、kubeconfig を作成または更新して kubectl を設定する**  
次の `update-kubeconfig` の例では、my-eks-cluster という名前の Amazon EKS クラスターに接続できるように、kubeconfig を作成または更新して kubectl を設定します。  

```
aws eks update-kubeconfig \
    --name my-eks-cluster
```
出力:  

```
Updated context arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster in /Users/xxx/.kube/config
```
詳細については、*Amazon EKS ユーザーガイド*の「[Amazon EKS クラスター用の kubeconfig ファイルの作成または更新](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html)」を参照してください。  
**例 2: kubeconfig (クラスター認証のロールを引き受ける role-arn オプションを使用) を作成または更新して kubectl を設定し、「my-eks-cluster」という名前の Amazon EKS クラスターに接続できるようにする**  
次の `update-kubeconfig` の例では、my-eks-cluster という名前の Amazon EKS クラスターに接続できるように、kubeconfig (クラスター認証のロールを引き受ける role-arn オプションを使用) を作成または更新して kubectl を設定します。  

```
aws eks update-kubeconfig \
    --name my-eks-cluster \
    --role-arn arn:aws:iam::111122223333:role/eksctl-EKS-Linux-Cluster-v1-24-cluster-ServiceRole-j1k7AfTIQtnM
```
出力:  

```
Updated context arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster in /Users/xxx/.kube/config
```
詳細については、*Amazon EKS ユーザーガイド*の「[Amazon EKS クラスター用の kubeconfig ファイルの作成または更新](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html)」を参照してください。  
**例 3: kubeconfig (カスタムクラスターエイリアスとユーザーエイリアスとともにクラスター認証のロールを引き受ける role-arn オプションを使用) を作成または更新して kubectl を設定し、「my-eks-cluster」という名前の Amazon EKS クラスターに接続できるようにする**  
次の `update-kubeconfig` の例では、my-eks-cluster という名前の Amazon EKS クラスターに接続できるように、kubeconfig (カスタムクラスターエイリアスとユーザーエイリアスとともにクラスター認証のロールを引き受ける role-arn オプションを使用) を作成または更新して kubectl を設定します。  

```
aws eks update-kubeconfig \
    --name my-eks-cluster \
    --role-arn arn:aws:iam::111122223333:role/eksctl-EKS-Linux-Cluster-v1-24-cluster-ServiceRole-j1k7AfTIQtnM \
    --alias stage-eks-cluster \
    --user-alias john
```
出力:  

```
Updated context stage-eks-cluster in /Users/dubaria/.kube/config
```
詳細については、*Amazon EKS ユーザーガイド*の「[Amazon EKS クラスター用の kubeconfig ファイルの作成または更新](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html)」を参照してください。  
**例 4: レビュー用に kubeconfig ファイルエントリを印刷し、「my-eks-cluster」という名前の Amazon EKS クラスターに接続できるように kubectl を設定する**  
次の `update-kubeconfig` の例では、my-eks-cluster という名前の Amazon EKS クラスターに接続できるように、kubeconfig (カスタムクラスターエイリアスとユーザーエイリアスとともにクラスター認証のロールを引き受ける role-arn オプションを使用) を作成または更新して kubectl を設定します。  

```
aws eks update-kubeconfig \
    --name my-eks-cluster \
    --role-arn arn:aws:iam::111122223333:role/eksctl-EKS-Linux-Cluster-v1-24-cluster-ServiceRole-j1k7AfTIQtnM \
    --alias stage-eks-cluster \
    --user-alias john \
    --verbose
```
出力:  

```
Updated context stage-eks-cluster in /Users/dubaria/.kube/config
Entries:

context:
cluster: arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster
user: john
name: stage-eks-cluster

name: john
user:
exec:
    apiVersion: client.authentication.k8s.io/v1beta1
    args:
    - --region
    - us-east-2
    - eks
    - get-token
    - --cluster-name
    - my-eks-cluster
    - --output
    - json
    - --role
    - arn:aws:iam::111122223333:role/eksctl-EKS-Linux-Cluster-v1-24-cluster-ServiceRole-j1k7AfTIQtnM
    command: aws

cluster:
certificate-authority-data: xxx_CA_DATA_xxx
server: https://DALSJ343KE23J3RN45653DSKJTT647TYD.yl4.us-east-2.eks.amazonaws.com
name: arn:aws:eks:us-east-2:111122223333:cluster/my-eks-cluster
```
詳細については、*Amazon EKS ユーザーガイド*の「[Amazon EKS クラスター用の kubeconfig ファイルの作成または更新](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateKubeconfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-kubeconfig.html)」を参照してください。

### `update-nodegroup-config`
<a name="eks_UpdateNodegroupConfig_cli_2_topic"></a>

次のコード例は、`update-nodegroup-config` を使用する方法を示しています。

**AWS CLI**  
**例 1: マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードに新しいラベルとテイントを追加する**  
次の `update-nodegroup-config` の例では、マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードに新しいラベルとテイントを追加します。  

```
aws eks update-nodegroup-config \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --labels 'addOrUpdateLabels={my-eks-nodegroup-label-1=value-1,my-eks-nodegroup-label-2=value-2}' \
    --taints 'addOrUpdateTaints=[{key=taint-key-1,value=taint-value-1,effect=NO_EXECUTE}]'
```
出力:  

```
{
    "update": {
        "id": "e66d21d3-bd8b-3ad1-a5aa-b196dc08c7c1",
        "status": "InProgress",
        "type": "ConfigUpdate",
        "params": [
            {
                "type": "LabelsToAdd",
                "value": "{\"my-eks-nodegroup-label-2\":\"value-2\",\"my-eks-nodegroup-label-1\":\"value-1\"}"
            },
            {
                "type": "TaintsToAdd",
                "value": "[{\"effect\":\"NO_EXECUTE\",\"value\":\"taint-value-1\",\"key\":\"taint-key-1\"}]"
            }
        ],
        "createdAt": "2024-04-08T12:05:19.161000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの更新](https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html)」を参照してください。  
**例 2: マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードのラベルとテイントを削除する**  
次の `update-nodegroup-config` の例では、マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードのラベルとテイントを削除します。  

```
aws eks update-nodegroup-config \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --labels 'removeLabels=my-eks-nodegroup-label-1, my-eks-nodegroup-label-2' \
    --taints 'removeTaints=[{key=taint-key-1,value=taint-value-1,effect=NO_EXECUTE}]'
```
出力:  

```
{
    "update": {
        "id": "67a08692-9e59-3ace-a916-13929f44cec3",
        "status": "InProgress",
        "type": "ConfigUpdate",
        "params": [
            {
                "type": "LabelsToRemove",
                "value": "[\"my-eks-nodegroup-label-1\",\"my-eks-nodegroup-label-2\"]"
            },
            {
                "type": "TaintsToRemove",
                "value": "[{\"effect\":\"NO_EXECUTE\",\"value\":\"taint-value-1\",\"key\":\"taint-key-1\"}]"
            }
        ],
        "createdAt": "2024-04-08T12:17:31.817000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの更新](https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html)」を参照してください。  
**例 3: マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードのラベルとテイントを削除および追加する**  
次の `update-nodegroup-config` の例では、マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードのラベルとテイントを削除および追加します。  

```
aws eks update-nodegroup-config \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --labels 'addOrUpdateLabels={my-eks-nodegroup-new-label-1=new-value-1,my-eks-nodegroup-new-label-2=new-value-2},removeLabels=my-eks-nodegroup-label-1, my-eks-nodegroup-label-2' \
    --taints 'addOrUpdateTaints=[{key=taint-new-key-1,value=taint-new-value-1,effect=PREFER_NO_SCHEDULE}],removeTaints=[{key=taint-key-1,value=taint-value-1,effect=NO_EXECUTE}]'
```
出力:  

```
{
    "update": {
        "id": "4a9c8c45-6ac7-3115-be71-d6412a2339b7",
        "status": "InProgress",
        "type": "ConfigUpdate",
        "params": [
            {
                "type": "LabelsToAdd",
                "value": "{\"my-eks-nodegroup-new-label-1\":\"new-value-1\",\"my-eks-nodegroup-new-label-2\":\"new-value-2\"}"
            },
            {
                "type": "LabelsToRemove",
                "value": "[\"my-eks-nodegroup-label-1\",\"my-eks-nodegroup-label-2\"]"
            },
            {
                "type": "TaintsToAdd",
                "value": "[{\"effect\":\"PREFER_NO_SCHEDULE\",\"value\":\"taint-new-value-1\",\"key\":\"taint-new-key-1\"}]"
            },
            {
                "type": "TaintsToRemove",
                "value": "[{\"effect\":\"NO_EXECUTE\",\"value\":\"taint-value-1\",\"key\":\"taint-key-1\"}]"
            }
        ],
        "createdAt": "2024-04-08T12:30:55.486000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの更新](https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html)」を参照してください。  
**例 4: マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードの scaling-config と update-config を更新する**  
次の `update-nodegroup-config` の例では、マネージド型ノードグループを更新して、Amazon EKS クラスターの EKS ワーカーノードの scaling-config と update-config を更新します。  

```
aws eks update-nodegroup-config \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --scaling-config minSize=1,maxSize=5,desiredSize=2 \
    --update-config maxUnavailable=2
```
出力:  

```
{
    "update": {
        "id": "a977160f-59bf-3023-805d-c9826e460aea",
        "status": "InProgress",
        "type": "ConfigUpdate",
        "params": [
            {
                "type": "MinSize",
                "value": "1"
            },
            {
                "type": "MaxSize",
                "value": "5"
            },
            {
                "type": "DesiredSize",
                "value": "2"
            },
            {
                "type": "MaxUnavailable",
                "value": "2"
            }
        ],
        "createdAt": "2024-04-08T12:35:17.036000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの更新](https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateNodegroupConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-nodegroup-config.html)」を参照してください。

### `update-nodegroup-version`
<a name="eks_UpdateNodegroupVersion_cli_2_topic"></a>

次のコード例は、`update-nodegroup-version` を使用する方法を示しています。

**AWS CLI**  
**例 1: Amazon EKS マネージド型ノードグループの Kubernetes バージョンまたは AMI バージョンを更新する**  
次の `update-nodegroup-version` の例では、Amazon EKS マネージド型ノードグループの Kubernetes バージョンまたは AMI バージョンを、Kubernetes クラスターで利用可能な最新バージョンに更新します。  

```
aws eks update-nodegroup-version \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --no-force
```
出力:  

```
{
    "update": {
        "id": "a94ebfc3-6bf8-307a-89e6-7dbaa36421f7",
        "status": "InProgress",
        "type": "VersionUpdate",
        "params": [
            {
                "type": "Version",
                "value": "1.26"
            },
            {
                "type": "ReleaseVersion",
                "value": "1.26.12-20240329"
            }
        ],
        "createdAt": "2024-04-08T13:16:00.724000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「[マネージド型ノードグループの更新](https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html)」を参照してください。  
**例 2: Amazon EKS マネージド型ノードグループの Kubernetes バージョンまたは AMI バージョンを更新する**  
次の `update-nodegroup-version` の例では、Amazon EKS マネージド型ノードグループの Kubernetes バージョンまたは AMI バージョンを指定された AMI リリースバージョンに更新します。  

```
aws eks update-nodegroup-version \
    --cluster-name my-eks-cluster \
    --nodegroup-name my-eks-nodegroup \
    --kubernetes-version '1.26' \
    --release-version '1.26.12-20240307' \
    --no-force
```
出力:  

```
{
    "update": {
        "id": "4db06fe1-088d-336b-bdcd-3fdb94995fb7",
        "status": "InProgress",
        "type": "VersionUpdate",
        "params": [
            {
                "type": "Version",
                "value": "1.26"
            },
            {
                "type": "ReleaseVersion",
                "value": "1.26.12-20240307"
            }
        ],
        "createdAt": "2024-04-08T13:13:58.595000-04:00",
        "errors": []
    }
}
```
詳細については、「*Amazon EKS ユーザーガイド*」の「マネージド型ノードグループの更新 - <https://docs.aws.amazon.com/eks/latest/userguide/update-managed-node-group.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateNodegroupVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-nodegroup-version.html)」を参照してください。

### `update-pod-identity-association`
<a name="eks_UpdatePodIdentityAssociation_cli_2_topic"></a>

次のコード例は、`update-pod-identity-association` を使用する方法を示しています。

**AWS CLI**  
**EKS Pod Identity の関連付けを更新するには**  
次の `update-pod-identity-association` の例では、関連付け ID `a-9njjin9gfghecgocd` の関連付けられた IAM ロールを `arn:aws:iam::111122223333:role/my-role` から `arn:aws:iam::111122223333:role/s3-role` に変更することで、EKS Pod Identity の関連付けを更新します。この API は、関連付けられた IAM ロールの更新のみを許可します。  

```
aws eks update-pod-identity-association \
    --cluster-name eks-customer \
    --association-id a-9njjin9gfghecgocd \
    --role-arn arn:aws:iam::111122223333:role/s3-role
```
出力:  

```
{
    "association": {
        "clusterName": "eks-customer",
        "namespace": "default",
        "serviceAccount": "default",
        "roleArn": "arn:aws:iam::111122223333:role/s3-role",
        "associationArn": "arn:aws:eks:us-west-2:111122223333:podidentityassociation/eks-customer/a-9njjin9gfghecgocd",
        "associationId": "a-9njjin9gfghecgocd",
        "tags": {
            "Key2": "value2",
            "Key1": "value1"
        },
        "createdAt": "2025-05-24T19:52:14.135000-05:00",
        "modifiedAt": "2025-05-25T21:01:53.120000-05:00"
    }
}
```
詳細については、*「Amazon* [EKS ユーザーガイド」の「EKS Pod Identity がポッドに AWS サービスへのアクセスを許可する方法](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePodIdentityAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/update-pod-identity-association.html)」を参照してください。

# を使用した Elastic Beanstalk の例 AWS CLI
<a name="cli_2_elastic-beanstalk_code_examples"></a>

次のコード例は、Elastic Beanstalk AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `abort-environment-update`
<a name="elastic-beanstalk_AbortEnvironmentUpdate_cli_2_topic"></a>

次のコード例は、`abort-environment-update` を使用する方法を示しています。

**AWS CLI**  
**デプロイを中止するには**  
次のコマンドは、`my-env` という名前の環境に対して実行中のアプリケーションバージョンデプロイを中止します。  

```
aws elasticbeanstalk abort-environment-update --environment-name my-env
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AbortEnvironmentUpdate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/abort-environment-update.html)」を参照してください。

### `check-dns-availability`
<a name="elastic-beanstalk_CheckDnsAvailability_cli_2_topic"></a>

次のコード例は、`check-dns-availability` を使用する方法を示しています。

**AWS CLI**  
**CNAME を可用性を確認するには**  
次のコマンドは、サブドメイン `my-cname.elasticbeanstalk.com` の可用性をチェックします。  

```
aws elasticbeanstalk check-dns-availability --cname-prefix my-cname
```
出力:  

```
{
    "Available": true,
    "FullyQualifiedCNAME": "my-cname.elasticbeanstalk.com"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CheckDnsAvailability](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/check-dns-availability.html)」を参照してください。

### `create-application-version`
<a name="elastic-beanstalk_CreateApplicationVersion_cli_2_topic"></a>

次のコード例は、`create-application-version` を使用する方法を示しています。

**AWS CLI**  
**新しいアプリケーションバージョンを作成するには**  
次のコマンドは、「MyApp」という名前のアプリケーションの新しいバージョン「v1」を作成します。  

```
aws elasticbeanstalk create-application-version --application-name MyApp --version-label v1 --description MyAppv1 --source-bundle S3Bucket="amzn-s3-demo-bucket",S3Key="sample.war" --auto-create-application
```
auto-create-application オプションにより、アプリケーションがまだ存在しない場合は自動的に作成されます。ソースバンドルは、「amzn-s3-demo-bucket」という名前の s3 バケットに保存されている .war ファイルであり、Apache Tomcat サンプルアプリケーションが含まれています。  
出力:  

```
{
  "ApplicationVersion": {
      "ApplicationName": "MyApp",
      "VersionLabel": "v1",
      "Description": "MyAppv1",
      "DateCreated": "2015-02-03T23:01:25.412Z",
      "DateUpdated": "2015-02-03T23:01:25.412Z",
      "SourceBundle": {
          "S3Bucket": "amzn-s3-demo-bucket",
          "S3Key": "sample.war"
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApplicationVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/create-application-version.html)」を参照してください。

### `create-application`
<a name="elastic-beanstalk_CreateApplication_cli_2_topic"></a>

次のコード例は、`create-application` を使用する方法を示しています。

**AWS CLI**  
**新しいアプリケーションを作成するには**  
次のコマンドは、「MyApp」という名前の新しいアプリケーションを作成します。  

```
aws elasticbeanstalk create-application --application-name MyApp --description "my application"
```
`create-application` コマンドは、アプリケーションの名前と説明のみを設定します。アプリケーションのソースコードをアップロードするには、`create-application-version` を使用してアプリケーションの初期バージョンを作成します。`create-application-version` には、アプリケーションとアプリケーションバージョンを 1 ステップで作成できる `auto-create-application` オプションもあります。  
出力:  

```
{
  "Application": {
      "ApplicationName": "MyApp",
      "ConfigurationTemplates": [],
      "DateUpdated": "2015-02-12T18:32:21.181Z",
      "Description": "my application",
      "DateCreated": "2015-02-12T18:32:21.181Z"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/create-application.html)」を参照してください。

### `create-configuration-template`
<a name="elastic-beanstalk_CreateConfigurationTemplate_cli_2_topic"></a>

次のコード例は、`create-configuration-template` を使用する方法を示しています。

**AWS CLI**  
**設定テンプレートを作成するには**  
次のコマンドは、ID が `e-rpqsewtp2j` の環境に適用される設定から `my-app-v1` という名前の設定テンプレートを作成します。  

```
aws elasticbeanstalk create-configuration-template --application-name my-app --template-name my-app-v1 --environment-id e-rpqsewtp2j
```
出力:  

```
{
    "ApplicationName": "my-app",
    "TemplateName": "my-app-v1",
    "DateCreated": "2015-08-12T18:40:39Z",
    "DateUpdated": "2015-08-12T18:40:39Z",
    "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConfigurationTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/create-configuration-template.html)」を参照してください。

### `create-environment`
<a name="elastic-beanstalk_CreateEnvironment_cli_2_topic"></a>

次のコード例は、`create-environment` を使用する方法を示しています。

**AWS CLI**  
**アプリケーション用の新しい環境を作成するには**  
次のコマンドは、「my-app」という名前の Java アプリケーションのバージョン「v1」用の新しい環境を作成します。  

```
aws elasticbeanstalk create-environment --application-name my-app --environment-name my-env --cname-prefix my-app --version-label v1 --solution-stack-name "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8"
```
出力:  

```
{
  "ApplicationName": "my-app",
  "EnvironmentName": "my-env",
  "VersionLabel": "v1",
  "Status": "Launching",
  "EnvironmentId": "e-izqpassy4h",
  "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
  "CNAME": "my-app.elasticbeanstalk.com",
  "Health": "Grey",
  "Tier": {
      "Type": "Standard",
      "Name": "WebServer",
      "Version": " "
  },
  "DateUpdated": "2015-02-03T23:04:54.479Z",
  "DateCreated": "2015-02-03T23:04:54.479Z"
}
```
`v1` は、以前に create-application-version でアップロードされたアプリケーションバージョンのラベルです。  
**環境設定オプションを定義する JSON ファイルを指定するには**  
次の `create-environment` コマンドは、`myoptions.json` という名前の JSON ファイルを使用して、ソリューションスタックまたは設定テンプレートから取得した値を上書きするように指定します。  

```
aws elasticbeanstalk create-environment --environment-name sample-env --application-name sampleapp --option-settings file://myoptions.json
```
`myoptions.json` は、いくつかの設定を定義する JSON オブジェクトです。  

```
[
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "Interval",
    "Value": "15"
  },
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "Timeout",
    "Value": "8"
  },
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "HealthyThreshold",
    "Value": "2"
  },
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "UnhealthyThreshold",
    "Value": "3"
  }
]
```
詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「オプション値」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/create-environment.html)」を参照してください。

### `create-storage-location`
<a name="elastic-beanstalk_CreateStorageLocation_cli_2_topic"></a>

次のコード例は、`create-storage-location` を使用する方法を示しています。

**AWS CLI**  
**ストレージの場所を作成するには**  
次のコマンドは、Amazon S3 のストレージロケーションを作成します。  

```
aws elasticbeanstalk create-storage-location
```
出力:  

```
{
    "S3Bucket": "elasticbeanstalk-us-west-2-0123456789012"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStorageLocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/create-storage-location.html)」を参照してください。

### `delete-application-version`
<a name="elastic-beanstalk_DeleteApplicationVersion_cli_2_topic"></a>

次のコード例は、`delete-application-version` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションバージョンを削除するには**  
次のコマンドは、`my-app` という名前のアプリケーションで `22a0-stage-150819_182129` という名前のアプリケーションバージョンを削除します。  

```
aws elasticbeanstalk delete-application-version --version-label 22a0-stage-150819_182129 --application-name my-app
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApplicationVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/delete-application-version.html)」を参照してください。

### `delete-application`
<a name="elastic-beanstalk_DeleteApplication_cli_2_topic"></a>

次のコード例は、`delete-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを削除するには**  
次のコマンドは、`my-app` という名前のアプリケーションが削除します。  

```
aws elasticbeanstalk delete-application --application-name my-app
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/delete-application.html)」を参照してください。

### `delete-configuration-template`
<a name="elastic-beanstalk_DeleteConfigurationTemplate_cli_2_topic"></a>

次のコード例は、`delete-configuration-template` を使用する方法を示しています。

**AWS CLI**  
**設定テンプレートを削除するには**  
次のコマンドは、`my-app` という名前のアプリケーションの `my-template` という名前の設定テンプレートを削除します。  

```
aws elasticbeanstalk delete-configuration-template --template-name my-template --application-name my-app
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConfigurationTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/delete-configuration-template.html)」を参照してください。

### `delete-environment-configuration`
<a name="elastic-beanstalk_DeleteEnvironmentConfiguration_cli_2_topic"></a>

次のコード例は、`delete-environment-configuration` を使用する方法を示しています。

**AWS CLI**  
**ドラフト設定を削除するには**  
次のコマンドは、`my-env` という名前の環境のドラフト設定を削除します。  

```
aws elasticbeanstalk delete-environment-configuration --environment-name my-env --application-name my-app
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEnvironmentConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/delete-environment-configuration.html)」を参照してください。

### `describe-application-versions`
<a name="elastic-beanstalk_DescribeApplicationVersions_cli_2_topic"></a>

次のコード例は、`describe-application-versions` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションバージョンの情報を表示するには**  
次のコマンドは、`v2` というラベルのアプリケーションバージョンに関する情報を取得します。  

```
aws elasticbeanstalk describe-application-versions --application-name my-app --version-label "v2"
```
出力:  

```
{
    "ApplicationVersions": [
        {
            "ApplicationName": "my-app",
            "VersionLabel": "v2",
            "Description": "update cover page",
            "DateCreated": "2015-07-23T01:32:26.079Z",
            "DateUpdated": "2015-07-23T01:32:26.079Z",
            "SourceBundle": {
                "S3Bucket": "elasticbeanstalk-us-west-2-015321684451",
                "S3Key": "my-app/5026-stage-150723_224258.war"
            }
        },
      {
          "ApplicationName": "my-app",
          "VersionLabel": "v1",
          "Description": "initial version",
          "DateCreated": "2015-07-23T22:26:10.816Z",
          "DateUpdated": "2015-07-23T22:26:10.816Z",
          "SourceBundle": {
              "S3Bucket": "elasticbeanstalk-us-west-2-015321684451",
              "S3Key": "my-app/5026-stage-150723_222618.war"
          }
      }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeApplicationVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-application-versions.html)」を参照してください。

### `describe-applications`
<a name="elastic-beanstalk_DescribeApplications_cli_2_topic"></a>

次のコード例は、`describe-applications` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションのリストを表示するには**  
次のコマンドは、現在のリージョンのアプリケーションに関する情報を取得します。  

```
aws elasticbeanstalk describe-applications
```
出力:  

```
{
    "Applications": [
        {
            "ApplicationName": "ruby",
            "ConfigurationTemplates": [],
            "DateUpdated": "2015-08-13T21:05:44.376Z",
            "Versions": [
                "Sample Application"
            ],
            "DateCreated": "2015-08-13T21:05:44.376Z"
        },
        {
            "ApplicationName": "pythonsample",
            "Description": "Application created from the EB CLI using \"eb init\"",
            "Versions": [
                "Sample Application"
            ],
            "DateCreated": "2015-08-13T19:05:43.637Z",
            "ConfigurationTemplates": [],
            "DateUpdated": "2015-08-13T19:05:43.637Z"
        },
        {
            "ApplicationName": "nodejs-example",
            "ConfigurationTemplates": [],
            "DateUpdated": "2015-08-06T17:50:02.486Z",
            "Versions": [
                "add elasticache",
                "First Release"
            ],
            "DateCreated": "2015-08-06T17:50:02.486Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeApplications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-applications.html)」を参照してください。

### `describe-configuration-options`
<a name="elastic-beanstalk_DescribeConfigurationOptions_cli_2_topic"></a>

次のコード例は、`describe-configuration-options` を使用する方法を示しています。

**AWS CLI**  
**環境の設定オプションを表示するには**  
次のコマンドは、`my-env` という名前の環境で使用できるすべての設定オプションの記述を取得します。  

```
aws elasticbeanstalk describe-configuration-options --environment-name my-env --application-name my-app
```
出力 (省略):  

```
{
    "Options": [
        {
            "Name": "JVMOptions",
            "UserDefined": false,
            "DefaultValue": "Xms=256m,Xmx=256m,XX:MaxPermSize=64m,JVM Options=",
            "ChangeSeverity": "RestartApplicationServer",
            "Namespace": "aws:cloudformation:template:parameter",
            "ValueType": "KeyValueList"
        },
        {
            "Name": "Interval",
            "UserDefined": false,
            "DefaultValue": "30",
            "ChangeSeverity": "NoInterruption",
            "Namespace": "aws:elb:healthcheck",
            "MaxValue": 300,
            "MinValue": 5,
            "ValueType": "Scalar"
        },
        ...
        {
            "Name": "LowerThreshold",
            "UserDefined": false,
            "DefaultValue": "2000000",
            "ChangeSeverity": "NoInterruption",
            "Namespace": "aws:autoscaling:trigger",
            "MinValue": 0,
            "ValueType": "Scalar"
        },
        {
            "Name": "ListenerEnabled",
            "UserDefined": false,
            "DefaultValue": "true",
            "ChangeSeverity": "Unknown",
            "Namespace": "aws:elb:listener",
            "ValueType": "Boolean"
        }
    ]
}
```
使用可能な設定オプションは、プラットフォームと設定バージョンによって異なります。名前空間とサポートされているオプションの詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「Option Values」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConfigurationOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-configuration-options.html)」を参照してください。

### `describe-configuration-settings`
<a name="elastic-beanstalk_DescribeConfigurationSettings_cli_2_topic"></a>

次のコード例は、`describe-configuration-settings` を使用する方法を示しています。

**AWS CLI**  
**環境の設定を表示するには**  
次のコマンドは、`my-env` という名前の環境の設定を取得します。  

```
aws elasticbeanstalk describe-configuration-settings --environment-name my-env --application-name my-app
```
出力 (省略):  

```
{
    "ConfigurationSettings": [
        {
            "ApplicationName": "my-app",
            "EnvironmentName": "my-env",
            "Description": "Environment created from the EB CLI using \"eb create\"",
            "DeploymentStatus": "deployed",
            "DateCreated": "2015-08-13T19:16:25Z",
            "OptionSettings": [
                {
                    "OptionName": "Availability Zones",
                    "ResourceName": "AWSEBAutoScalingGroup",
                    "Namespace": "aws:autoscaling:asg",
                    "Value": "Any"
                },
                {
                    "OptionName": "Cooldown",
                    "ResourceName": "AWSEBAutoScalingGroup",
                    "Namespace": "aws:autoscaling:asg",
                    "Value": "360"
                },
                ...
                {
                    "OptionName": "ConnectionDrainingTimeout",
                    "ResourceName": "AWSEBLoadBalancer",
                    "Namespace": "aws:elb:policies",
                    "Value": "20"
                },
                {
                    "OptionName": "ConnectionSettingIdleTimeout",
                    "ResourceName": "AWSEBLoadBalancer",
                    "Namespace": "aws:elb:policies",
                    "Value": "60"
                }
            ],
            "DateUpdated": "2015-08-13T23:30:07Z",
            "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8"
        }
    ]
}
```
名前空間とサポートされているオプションの詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「Option Values」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeConfigurationSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-configuration-settings.html)」を参照してください。

### `describe-environment-health`
<a name="elastic-beanstalk_DescribeEnvironmentHealth_cli_2_topic"></a>

次のコード例は、`describe-environment-health` を使用する方法を示しています。

**AWS CLI**  
**環境ヘルスを表示するには**  
次のコマンドは、`my-env` という名前の全体的な環境ヘルス情報を取得します。  

```
aws elasticbeanstalk describe-environment-health --environment-name my-env --attribute-names All
```
出力:  

```
{
    "Status": "Ready",
    "EnvironmentName": "my-env",
    "Color": "Green",
    "ApplicationMetrics": {
        "Duration": 10,
        "Latency": {
            "P99": 0.004,
            "P75": 0.002,
            "P90": 0.003,
            "P95": 0.004,
            "P85": 0.003,
            "P10": 0.001,
            "P999": 0.004,
            "P50": 0.001
        },
        "RequestCount": 45,
        "StatusCodes": {
            "Status3xx": 0,
            "Status2xx": 45,
            "Status5xx": 0,
            "Status4xx": 0
        }
    },
    "RefreshedAt": "2015-08-20T21:09:18Z",
    "HealthStatus": "Ok",
    "InstancesHealth": {
        "Info": 0,
        "Ok": 1,
        "Unknown": 0,
        "Severe": 0,
        "Warning": 0,
        "Degraded": 0,
        "NoData": 0,
        "Pending": 0
    },
    "Causes": []
}
```
ヘルス情報は、拡張ヘルスレポートが有効になっている環境でのみ使用できます。詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「拡張ヘルスレポートおよびモニタリング」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEnvironmentHealth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-environment-health.html)」を参照してください。

### `describe-environment-resources`
<a name="elastic-beanstalk_DescribeEnvironmentResources_cli_2_topic"></a>

次の例は、`describe-environment-resources` を使用する方法を説明しています。

**AWS CLI**  
**環境内の AWS リソースに関する情報を表示するには**  
次のコマンドは、`my-env` という名前の環境内のリソースに関する情報を取得します。  

```
aws elasticbeanstalk describe-environment-resources --environment-name my-env
```
出力:  

```
{
    "EnvironmentResources": {
        "EnvironmentName": "my-env",
        "AutoScalingGroups": [
            {
                "Name": "awseb-e-qu3fyyjyjs-stack-AWSEBAutoScalingGroup-QSB2ZO88SXZT"
            }
        ],
        "Triggers": [],
        "LoadBalancers": [
            {
                "Name": "awseb-e-q-AWSEBLoa-1EEPZ0K98BIF0"
            }
        ],
        "Queues": [],
        "Instances": [
            {
                "Id": "i-0c91c786"
            }
        ],
        "LaunchConfigurations": [
            {
                "Name": "awseb-e-qu3fyyjyjs-stack-AWSEBAutoScalingLaunchConfiguration-1UUVQIBC96TQ2"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEnvironmentResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-environment-resources.html)」を参照してください。

### `describe-environments`
<a name="elastic-beanstalk_DescribeEnvironments_cli_2_topic"></a>

次のコード例は、`describe-environments` を使用する方法を示しています。

**AWS CLI**  
**環境に関する情報を表示するには**  
次のコマンドは、`my-env` という名前の環境に関する情報を取得します。  

```
aws elasticbeanstalk describe-environments --environment-names my-env
```
出力:  

```
{
    "Environments": [
        {
            "ApplicationName": "my-app",
            "EnvironmentName": "my-env",
            "VersionLabel": "7f58-stage-150812_025409",
            "Status": "Ready",
            "EnvironmentId": "e-rpqsewtp2j",
            "EndpointURL": "awseb-e-w-AWSEBLoa-1483140XB0Q4L-109QXY8121.us-west-2.elb.amazonaws.com",
            "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
            "CNAME": "my-env.elasticbeanstalk.com",
            "Health": "Green",
            "AbortableOperationInProgress": false,
            "Tier": {
                "Version": " ",
                "Type": "Standard",
                "Name": "WebServer"
            },
            "DateUpdated": "2015-08-12T18:16:55.019Z",
            "DateCreated": "2015-08-07T20:48:49.599Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEnvironments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-environments.html)」を参照してください。

### `describe-events`
<a name="elastic-beanstalk_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
**環境のイベントを表示するには**  
次のコマンドは、`my-env` という名前の環境のイベントを取得します。  

```
aws elasticbeanstalk describe-events --environment-name my-env
```
出力 (省略):  

```
{
    "Events": [
        {
            "ApplicationName": "my-app",
            "EnvironmentName": "my-env",
            "Message": "Environment health has transitioned from Info to Ok.",
            "EventDate": "2015-08-20T07:06:53.535Z",
            "Severity": "INFO"
        },
        {
            "ApplicationName": "my-app",
            "EnvironmentName": "my-env",
            "Severity": "INFO",
            "RequestId": "b7f3960b-4709-11e5-ba1e-07e16200da41",
            "Message": "Environment update completed successfully.",
            "EventDate": "2015-08-20T07:06:02.049Z"
        },
        ...
        {
            "ApplicationName": "my-app",
            "EnvironmentName": "my-env",
            "Severity": "INFO",
            "RequestId": "ca8dfbf6-41ef-11e5-988b-651aa638f46b",
            "Message": "Using elasticbeanstalk-us-west-2-012445113685 as Amazon S3 storage bucket for environment data.",
            "EventDate": "2015-08-13T19:16:27.561Z"
        },
        {
            "ApplicationName": "my-app",
            "EnvironmentName": "my-env",
            "Severity": "INFO",
            "RequestId": "cdfba8f6-41ef-11e5-988b-65638f41aa6b",
            "Message": "createEnvironment is starting.",
            "EventDate": "2015-08-13T19:16:26.581Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-events.html)」を参照してください。

### `describe-instances-health`
<a name="elastic-beanstalk_DescribeInstancesHealth_cli_2_topic"></a>

次のコード例は、`describe-instances-health` を使用する方法を示しています。

**AWS CLI**  
**環境ヘルスを表示するには**  
次のコマンドでは、`my-env` という名前の環境内のインスタンスのヘルス情報を取得できるようにします。  

```
aws elasticbeanstalk describe-instances-health --environment-name my-env --attribute-names All
```
出力:  

```
{
    "InstanceHealthList": [
        {
            "InstanceId": "i-08691cc7",
            "ApplicationMetrics": {
                "Duration": 10,
                "Latency": {
                    "P99": 0.006,
                    "P75": 0.002,
                    "P90": 0.004,
                    "P95": 0.005,
                    "P85": 0.003,
                    "P10": 0.0,
                    "P999": 0.006,
                    "P50": 0.001
                },
                "RequestCount": 48,
                "StatusCodes": {
                    "Status3xx": 0,
                    "Status2xx": 47,
                    "Status5xx": 0,
                    "Status4xx": 1
                }
            },
            "System": {
                "LoadAverage": [
                    0.0,
                    0.02,
                    0.05
                ],
                "CPUUtilization": {
                    "SoftIRQ": 0.1,
                    "IOWait": 0.2,
                    "System": 0.3,
                    "Idle": 97.8,
                    "User": 1.5,
                    "IRQ": 0.0,
                    "Nice": 0.1
                }
            },
            "Color": "Green",
            "HealthStatus": "Ok",
            "LaunchedAt": "2015-08-13T19:17:09Z",
            "Causes": []
        }
    ],
    "RefreshedAt": "2015-08-20T21:09:08Z"
}
```
ヘルス情報は、拡張ヘルスレポートが有効になっている環境でのみ使用できます。詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「拡張ヘルスレポートおよびモニタリング」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstancesHealth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-instances-health.html)」を参照してください。

### `list-available-solution-stacks`
<a name="elastic-beanstalk_ListAvailableSolutionStacks_cli_2_topic"></a>

次のコード例は、`list-available-solution-stacks` を使用する方法を示しています。

**AWS CLI**  
**ソリューションスタックを表示するには**  
次のコマンドは、現在利用可能なすべてのプラットフォーム設定と、過去に使用したことがあるすべてのソリューションスタックを一覧表示します。  

```
aws elasticbeanstalk list-available-solution-stacks
```
出力 (省略):  

```
{
    "SolutionStacks": [
        "64bit Amazon Linux 2015.03 v2.0.0 running Node.js",
        "64bit Amazon Linux 2015.03 v2.0.0 running PHP 5.6",
        "64bit Amazon Linux 2015.03 v2.0.0 running PHP 5.5",
        "64bit Amazon Linux 2015.03 v2.0.0 running PHP 5.4",
        "64bit Amazon Linux 2015.03 v2.0.0 running Python 3.4",
        "64bit Amazon Linux 2015.03 v2.0.0 running Python 2.7",
        "64bit Amazon Linux 2015.03 v2.0.0 running Python",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.2 (Puma)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.2 (Passenger Standalone)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.1 (Puma)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.1 (Passenger Standalone)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.0 (Puma)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.0 (Passenger Standalone)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 1.9.3",
        "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
        "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 7 Java 7",
        "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 7 Java 6",
        "64bit Windows Server Core 2012 R2 running IIS 8.5",
        "64bit Windows Server 2012 R2 running IIS 8.5",
        "64bit Windows Server 2012 running IIS 8",
        "64bit Windows Server 2008 R2 running IIS 7.5",
        "64bit Amazon Linux 2015.03 v2.0.0 running Docker 1.6.2",
        "64bit Amazon Linux 2015.03 v2.0.0 running Multi-container Docker 1.6.2 (Generic)",
        "64bit Debian jessie v2.0.0 running GlassFish 4.1 Java 8 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running GlassFish 4.0 Java 7 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running Go 1.4 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running Go 1.3 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running Python 3.4 (Preconfigured - Docker)",
    ],
    "SolutionStackDetails": [
        {
            "PermittedFileTypes": [
                "zip"
            ],
            "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Node.js"
        },
        ...
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAvailableSolutionStacks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/list-available-solution-stacks.html)」を参照してください。

### `rebuild-environment`
<a name="elastic-beanstalk_RebuildEnvironment_cli_2_topic"></a>

次のコード例は、`rebuild-environment` を使用する方法を示しています。

**AWS CLI**  
**環境のを再構築するには**  
次のコマンドは、`my-env` という名前の環境でリソースを終了して再作成します。  

```
aws elasticbeanstalk rebuild-environment --environment-name my-env
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebuildEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/rebuild-environment.html)」を参照してください。

### `request-environment-info`
<a name="elastic-beanstalk_RequestEnvironmentInfo_cli_2_topic"></a>

次のコード例は、`request-environment-info` を使用する方法を示しています。

**AWS CLI**  
**追跡ログをリクエストするには**  
次のコマンドは、`my-env` という名前の環境からログをリクエストします。  

```
aws elasticbeanstalk request-environment-info --environment-name my-env --info-type tail
```
ログをリクエストしたら、retrieve-environment-info を使用してその場所を取得します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RequestEnvironmentInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/request-environment-info.html)」を参照してください。

### `restart-app-server`
<a name="elastic-beanstalk_RestartAppServer_cli_2_topic"></a>

次のコード例は、`restart-app-server` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションサーバーを再起動するには**  
次のコマンドは、`my-env` という環境内のすべてのインスタンスでアプリケーションサーバーを再起動します。  

```
aws elasticbeanstalk restart-app-server --environment-name my-env
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestartAppServer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/restart-app-server.html)」を参照してください。

### `retrieve-environment-info`
<a name="elastic-beanstalk_RetrieveEnvironmentInfo_cli_2_topic"></a>

次のコード例は、`retrieve-environment-info` を使用する方法を示しています。

**AWS CLI**  
**追跡ログを取得するには**  
次のコマンドは、`my-env` という名前の環境からログへのリンクを取得します。  

```
aws elasticbeanstalk retrieve-environment-info --environment-name my-env --info-type tail
```
出力:  

```
{
    "EnvironmentInfo": [
        {
            "SampleTimestamp": "2015-08-20T22:23:17.703Z",
            "Message": "https://elasticbeanstalk-us-west-2-0123456789012.s3.amazonaws.com/resources/environments/logs/tail/e-fyqyju3yjs/i-09c1c867/TailLogs-1440109397703.out?AWSAccessKeyId=AKGPT4J56IAJ2EUBL5CQ&Expires=1440195891&Signature=n%2BEalOV6A2HIOx4Rcfb7LT16bBM%3D",
            "InfoType": "tail",
            "Ec2InstanceId": "i-09c1c867"
        }
    ]
}
```
ブラウザでリンクを表示します。取得前に、request-environment-info を使用してログをリクエストする必要があります。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RetrieveEnvironmentInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/retrieve-environment-info.html)」を参照してください。

### `swap-environment-cnames`
<a name="elastic-beanstalk_SwapEnvironmentCnames_cli_2_topic"></a>

次のコード例は、`swap-environment-cnames` を使用する方法を示しています。

**AWS CLI**  
**環境の CNAME を交換するには**  
次のコマンドは、2 つの環境に割り当てられたサブドメインをスワップします。  

```
aws elasticbeanstalk swap-environment-cnames --source-environment-name my-env-blue --destination-environment-name my-env-green
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SwapEnvironmentCnames](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/swap-environment-cnames.html)」を参照してください。

### `terminate-environment`
<a name="elastic-beanstalk_TerminateEnvironment_cli_2_topic"></a>

次のコード例は、`terminate-environment` を使用する方法を示しています。

**AWS CLI**  
環境を終了するには  
次のコマンドは、`my-env` という名前の Elastic Beanstalk 環境を終了します。  

```
aws elasticbeanstalk terminate-environment --environment-name my-env
```
出力:  

```
{
    "ApplicationName": "my-app",
    "EnvironmentName": "my-env",
    "Status": "Terminating",
    "EnvironmentId": "e-fh2eravpns",
    "EndpointURL": "awseb-e-f-AWSEBLoa-1I9XUMP4-8492WNUP202574.us-west-2.elb.amazonaws.com",
    "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
    "CNAME": "my-env.elasticbeanstalk.com",
    "Health": "Grey",
    "AbortableOperationInProgress": false,
    "Tier": {
        "Version": " ",
        "Type": "Standard",
        "Name": "WebServer"
    },
    "DateUpdated": "2015-08-12T19:05:54.744Z",
    "DateCreated": "2015-08-12T18:52:53.622Z"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TerminateEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/terminate-environment.html)」を参照してください。

### `update-application-version`
<a name="elastic-beanstalk_UpdateApplicationVersion_cli_2_topic"></a>

次のコード例は、`update-application-version` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションバージョンの説明を変更するには**  
次のコマンドは、`22a0-stage-150819_185942` という名前のアプリケーションバージョンの記述を更新します。  

```
aws elasticbeanstalk update-application-version --version-label 22a0-stage-150819_185942 --application-name my-app --description "new description"
```
出力:  

```
{
    "ApplicationVersion": {
        "ApplicationName": "my-app",
        "VersionLabel": "22a0-stage-150819_185942",
        "Description": "new description",
        "DateCreated": "2015-08-19T18:59:17.646Z",
        "DateUpdated": "2015-08-20T22:53:28.871Z",
        "SourceBundle": {
            "S3Bucket": "elasticbeanstalk-us-west-2-0123456789012",
            "S3Key": "my-app/22a0-stage-150819_185942.war"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApplicationVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/update-application-version.html)」を参照してください。

### `update-application`
<a name="elastic-beanstalk_UpdateApplication_cli_2_topic"></a>

次のコード例は、`update-application` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの説明を変更するには**  
次のコマンドは、`my-app` という名前のアプリケーションの記述を更新します。  

```
aws elasticbeanstalk update-application --application-name my-app --description "my Elastic Beanstalk application"
```
出力:  

```
{
    "Application": {
        "ApplicationName": "my-app",
        "Description": "my Elastic Beanstalk application",
        "Versions": [
            "2fba-stage-150819_234450",
            "bf07-stage-150820_214945",
            "93f8",
            "fd7c-stage-150820_000431",
            "22a0-stage-150819_185942"
        ],
        "DateCreated": "2015-08-13T19:15:50.449Z",
        "ConfigurationTemplates": [],
        "DateUpdated": "2015-08-20T22:34:56.195Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/update-application.html)」を参照してください。

### `update-configuration-template`
<a name="elastic-beanstalk_UpdateConfigurationTemplate_cli_2_topic"></a>

次のコード例は、`update-configuration-template` を使用する方法を示しています。

**AWS CLI**  
**設定テンプレートを更新するには**  
次のコマンドは、`my-template` という名前の保存済み設定テンプレートから、設定済みの CloudWatch カスタムヘルスメトリクス設定 `ConfigDocument` を削除します。  

```
aws elasticbeanstalk update-configuration-template --template-name my-template --application-name my-app --options-to-remove Namespace=aws:elasticbeanstalk:healthreporting:system,OptionName=ConfigDocument
```
出力:  

```
{
    "ApplicationName": "my-app",
    "TemplateName": "my-template",
    "DateCreated": "2015-08-20T22:39:31Z",
    "DateUpdated": "2015-08-20T22:43:11Z",
    "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8"
}
```
名前空間とサポートされているオプションの詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「Option Values」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateConfigurationTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/update-configuration-template.html)」を参照してください。

### `update-environment`
<a name="elastic-beanstalk_UpdateEnvironment_cli_2_topic"></a>

次のコード例は、`update-environment` を使用する方法を示しています。

**AWS CLI**  
**環境を新しいバージョンに更新するには**  
次のコマンドは、「my-env」という名前の環境を、それが属するアプリケーションのバージョン「v2」に更新します。  

```
aws elasticbeanstalk update-environment --environment-name my-env --version-label v2
```
このコマンドでは、「my-env」環境が既に存在し、「v2」というラベルが付いた有効なアプリケーションバージョンを持つアプリケーションに属している必要があります。  
出力:  

```
{
  "ApplicationName": "my-app",
  "EnvironmentName": "my-env",
  "VersionLabel": "v2",
  "Status": "Updating",
  "EnvironmentId": "e-szqipays4h",
  "EndpointURL": "awseb-e-i-AWSEBLoa-1RDLX6TC9VUAO-0123456789.us-west-2.elb.amazonaws.com",
  "SolutionStackName": "64bit Amazon Linux running Tomcat 7",
  "CNAME": "my-env.elasticbeanstalk.com",
  "Health": "Grey",
  "Tier": {
      "Version": " ",
      "Type": "Standard",
      "Name": "WebServer"
  },
  "DateUpdated": "2015-02-03T23:12:29.119Z",
  "DateCreated": "2015-02-03T23:04:54.453Z"
}
```
**環境変数を設定するには**  
次のコマンドは、「my-env」環境の「PARAM1」変数の値を「ParamValue」に設定します。  

```
aws elasticbeanstalk update-environment --environment-name my-env --option-settings Namespace=aws:elasticbeanstalk:application:environment,OptionName=PARAM1,Value=ParamValue
```
`option-settings` パラメータは、変数の名前と値に加えて名前空間を取得します。Elastic Beanstalk は、環境変数に加えて、オプション用のいくつかの名前空間をサポートしています。  
**ファイルからオプション設定を設定するには**  
次のコマンドは、ファイルから `aws:elb:loadbalancer` 名前空間内のいくつかのオプションを設定します。  

```
aws elasticbeanstalk update-environment --environment-name my-env --option-settings file://options.json
```
`options.json` は、いくつかの設定を定義する JSON オブジェクトです。  

```
[
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "Interval",
    "Value": "15"
  },
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "Timeout",
    "Value": "8"
  },
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "HealthyThreshold",
    "Value": "2"
  },
  {
    "Namespace": "aws:elb:healthcheck",
    "OptionName": "UnhealthyThreshold",
    "Value": "3"
  }
]
```
出力:  

```
{
    "ApplicationName": "my-app",
    "EnvironmentName": "my-env",
    "VersionLabel": "7f58-stage-150812_025409",
    "Status": "Updating",
    "EnvironmentId": "e-wtp2rpqsej",
    "EndpointURL": "awseb-e-w-AWSEBLoa-14XB83101Q4L-104QXY80921.sa-east-1.elb.amazonaws.com",
    "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
    "CNAME": "my-env.elasticbeanstalk.com",
    "Health": "Grey",
    "AbortableOperationInProgress": true,
    "Tier": {
        "Version": " ",
        "Type": "Standard",
        "Name": "WebServer"
    },
    "DateUpdated": "2015-08-12T18:15:23.804Z",
    "DateCreated": "2015-08-07T20:48:49.599Z"
}
```
名前空間とサポートされているオプションの詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「Option Values」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEnvironment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/update-environment.html)」を参照してください。

### `validate-configuration-settings`
<a name="elastic-beanstalk_ValidateConfigurationSettings_cli_2_topic"></a>

次のコード例は、`validate-configuration-settings` を使用する方法を示しています。

**AWS CLI**  
**設定を検証するには**  
次のコマンドは、CloudWatch カスタムメトリクス設定ドキュメントを検証します。  

```
aws elasticbeanstalk validate-configuration-settings --application-name my-app --environment-name my-env --option-settings file://options.json
```
`options.json` は、検証する 1 つ以上の設定を含む JSON ドキュメントです。  

```
[
    {
        "Namespace": "aws:elasticbeanstalk:healthreporting:system",
        "OptionName": "ConfigDocument",
        "Value": "{\"CloudWatchMetrics\": {\"Environment\": {\"ApplicationLatencyP99.9\": null,\"InstancesSevere\": 60,\"ApplicationLatencyP90\": 60,\"ApplicationLatencyP99\": null,\"ApplicationLatencyP95\": 60,\"InstancesUnknown\": 60,\"ApplicationLatencyP85\": 60,\"InstancesInfo\": null,\"ApplicationRequests2xx\": null,\"InstancesDegraded\": null,\"InstancesWarning\": 60,\"ApplicationLatencyP50\": 60,\"ApplicationRequestsTotal\": null,\"InstancesNoData\": null,\"InstancesPending\": 60,\"ApplicationLatencyP10\": null,\"ApplicationRequests5xx\": null,\"ApplicationLatencyP75\": null,\"InstancesOk\": 60,\"ApplicationRequests3xx\": null,\"ApplicationRequests4xx\": null},\"Instance\": {\"ApplicationLatencyP99.9\": null,\"ApplicationLatencyP90\": 60,\"ApplicationLatencyP99\": null,\"ApplicationLatencyP95\": null,\"ApplicationLatencyP85\": null,\"CPUUser\": 60,\"ApplicationRequests2xx\": null,\"CPUIdle\": null,\"ApplicationLatencyP50\": null,\"ApplicationRequestsTotal\": 60,\"RootFilesystemUtil\": null,\"LoadAverage1min\": null,\"CPUIrq\": null,\"CPUNice\": 60,\"CPUIowait\": 60,\"ApplicationLatencyP10\": null,\"LoadAverage5min\": null,\"ApplicationRequests5xx\": null,\"ApplicationLatencyP75\": 60,\"CPUSystem\": 60,\"ApplicationRequests3xx\": 60,\"ApplicationRequests4xx\": null,\"InstanceHealth\": null,\"CPUSoftirq\": 60}},\"Version\": 1}"
    }
]
```
指定したオプションが指定された環境に対して有効な場合、Elastic Beanstalk は空の Messages 配列を返します。  

```
{
    "Messages": []
}
```
検証に失敗すると、レスポンスにはエラーに関する情報が含まれます。  

```
{
    "Messages": [
        {
            "OptionName": "ConfigDocumet",
            "Message": "Invalid option specification (Namespace: 'aws:elasticbeanstalk:healthreporting:system', OptionName: 'ConfigDocumet'): Unknown configuration setting.",
            "Namespace": "aws:elasticbeanstalk:healthreporting:system",
            "Severity": "error"
        }
    ]
}
```
名前空間とサポートされているオプションの詳細については、「*AWS Elastic Beanstalk デベロッパーガイド*」の「Option Values」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ValidateConfigurationSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/validate-configuration-settings.html)」を参照してください。

# を使用した Elastic Load Balancing - バージョン 1 の例 AWS CLI
<a name="cli_2_elastic-load-balancing_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 1 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags`
<a name="elastic-load-balancing_AddTags_cli_2_topic"></a>

次のコード例は、`add-tags` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーにタグを追加するには**  
この例は、指定されたロードバランサーにタグを追加します。  
コマンド:  

```
aws elb add-tags --load-balancer-name my-load-balancer --tags "Key=project,Value=lima" "Key=department,Value=digital-media"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/add-tags.html)」を参照してください。

### `apply-security-groups-to-load-balancer`
<a name="elastic-load-balancing_ApplySecurityGroupsToLoadBalancer_cli_2_topic"></a>

次のコード例は、`apply-security-groups-to-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**セキュリティグループを VPC 内のロードバランサーに関連付けるには**  
この例では、VPC 内の指定されたロードバランサーにセキュリティグループを関連付けます。  
コマンド:  

```
aws elb apply-security-groups-to-load-balancer --load-balancer-name my-load-balancer --security-groups sg-fc448899
```
出力:  

```
{
  "SecurityGroups": [
      "sg-fc448899"
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ApplySecurityGroupsToLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/apply-security-groups-to-load-balancer.html)」を参照してください。

### `attach-load-balancer-to-subnets`
<a name="elastic-load-balancing_AttachLoadBalancerToSubnets_cli_2_topic"></a>

次のコード例は、`attach-load-balancer-to-subnets` を使用する方法を示しています。

**AWS CLI**  
**サブネットをロードバランサーにアタッチするには**  
この例では、指定されたロードバランサーの一連の設定済みサブネットのセットに指定されたサブネットを追加します。  
コマンド:  

```
aws elb attach-load-balancer-to-subnets --load-balancer-name my-load-balancer --subnets subnet-0ecac448
```
出力:  

```
{
   "Subnets": [
       "subnet-15aaab61",
       "subnet-0ecac448"
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachLoadBalancerToSubnets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/attach-load-balancer-to-subnets.html)」を参照してください。

### `configure-health-check`
<a name="elastic-load-balancing_ConfigureHealthCheck_cli_2_topic"></a>

次のコード例は、`configure-health-check` を使用する方法を示しています。

**AWS CLI**  
**バックエンド EC2 インスタンスのヘルスチェック設定を指定するには**  
この例では、バックエンド EC2 インスタンスのヘルスを評価するために使用されるヘルスチェック設定を指定します。  
コマンド:  

```
aws elb configure-health-check --load-balancer-name my-load-balancer --health-check Target=HTTP:80/png,Interval=30,UnhealthyThreshold=2,HealthyThreshold=2,Timeout=3
```
出力:  

```
{
   "HealthCheck": {
       "HealthyThreshold": 2,
       "Interval": 30,
       "Target": "HTTP:80/png",
       "Timeout": 3,
       "UnhealthyThreshold": 2
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfigureHealthCheck](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/configure-health-check.html)」を参照してください。

### `create-app-cookie-stickiness-policy`
<a name="elastic-load-balancing_CreateAppCookieStickinessPolicy_cli_2_topic"></a>

次のコード例は、`create-app-cookie-stickiness-policy` を使用する方法を示しています。

**AWS CLI**  
**HTTPS ロードバランサーのスティッキーポリシーを生成するには**  
次の例では、アプリケーションによって生成された Cookie のスティッキーセッション存続期間に従う維持ポリシーを生成します。  
コマンド:  

```
aws elb create-app-cookie-stickiness-policy --load-balancer-name my-load-balancer --policy-name my-app-cookie-policy --cookie-name my-app-cookie
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAppCookieStickinessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/create-app-cookie-stickiness-policy.html)」を参照してください。

### `create-lb-cookie-stickiness-policy`
<a name="elastic-load-balancing_CreateLbCookieStickinessPolicy_cli_2_topic"></a>

次のコード例は、`create-lb-cookie-stickiness-policy` を使用する方法を示しています。

**AWS CLI**  
**HTTPS ロードバランサーの期間ベースの維持ポリシーを生成するには**  
この例では、指定された有効期限によって制御されたスティッキーセッションの存続期間を持つスティッキーポリシーを生成します。  
コマンド:  

```
aws elb create-lb-cookie-stickiness-policy --load-balancer-name my-load-balancer --policy-name my-duration-cookie-policy --cookie-expiration-period 60
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLbCookieStickinessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/create-lb-cookie-stickiness-policy.html)」を参照してください。

### `create-load-balancer-listeners`
<a name="elastic-load-balancing_CreateLoadBalancerListeners_cli_2_topic"></a>

次のコード例は、`create-load-balancer-listeners` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーの HTTP リスナーを作成するには**  
この例では、HTTP プロトコルを使用してポート 80 でロードバランサーのリスナーを作成します。  
コマンド:  

```
aws elb create-load-balancer-listeners --load-balancer-name my-load-balancer --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=80"
```
**ロードバランサーの HTTPS リスナーを作成するには**  
この例では、HTTP プロトコルを使用してポート 443 でロードバランサーのリスナーを作成します。  
コマンド:  

```
aws elb create-load-balancer-listeners --load-balancer-name my-load-balancer --listeners "Protocol=HTTPS,LoadBalancerPort=443,InstanceProtocol=HTTP,InstancePort=80"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLoadBalancerListeners](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/create-load-balancer-listeners.html)」を参照してください。

### `create-load-balancer-policy`
<a name="elastic-load-balancing_CreateLoadBalancerPolicy_cli_2_topic"></a>

次のコード例は、`create-load-balancer-policy` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーで Proxy Protocol を有効にするポリシーを作成するには**  
この例では、指定されたロードバランサーでプロキシプロトコルを有効にするポリシーを作成します。  
コマンド:  

```
aws elb create-load-balancer-policy --load-balancer-name my-load-balancer --policy-name my-ProxyProtocol-policy --policy-type-name ProxyProtocolPolicyType --policy-attributes AttributeName=ProxyProtocol,AttributeValue=true
```
**推奨されるセキュリティポリシーを使用して SSL ネゴシエーションポリシーを作成するには**  
この例では、推奨されるセキュリティポリシーを使用して、指定された HTTPS ロードバランサーの SSL ネゴシエーションポリシーを作成します。  
コマンド:  

```
aws elb create-load-balancer-policy --load-balancer-name my-load-balancer --policy-name my-SSLNegotiation-policy --policy-type-name SSLNegotiationPolicyType --policy-attributes AttributeName=Reference-Security-Policy,AttributeValue=ELBSecurityPolicy-2015-03
```
**カスタムセキュリティポリシーを使用して SSL ネゴシエーションポリシーを作成するには**  
この例では、プロトコルと暗号を有効にして、カスタムセキュリティポリシーを使用して HTTPS ロードバランサーの SSL ネゴシエーションポリシーを作成します。  
コマンド:  

```
aws elb create-load-balancer-policy --load-balancer-name my-load-balancer --policy-name my-SSLNegotiation-policy --policy-type-name SSLNegotiationPolicyType --policy-attributes AttributeName=Protocol-SSLv3,AttributeValue=true AttributeName=Protocol-TLSv1.1,AttributeValue=true AttributeName=DHE-RSA-AES256-SHA256,AttributeValue=true AttributeName=Server-Defined-Cipher-Order,AttributeValue=true
```
**パブリックキーポリシーを作成するには**  
この例では、パブリックキーポリシーを作成します。  
コマンド:  

```
aws elb create-load-balancer-policy --load-balancer-name my-load-balancer --policy-name my-PublicKey-policy --policy-type-name PublicKeyPolicyType --policy-attributes AttributeName=PublicKey,AttributeValue=MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwAYUjnfyEyXr1pxjhFWBpMlggUcqoi3kl+dS74kj//c6x7ROtusUaeQCTgIUkayttRDWchuqo1pHC1u+n5xxXnBBe2ejbb2WRsKIQ5rXEeixsjFpFsojpSQKkzhVGI6mJVZBJDVKSHmswnwLBdofLhzvllpovBPTHe+o4haAWvDBALJU0pkSI1FecPHcs2hwxf14zHoXy1e2k36A64nXW43wtfx5qcVSIxtCEOjnYRg7RPvybaGfQ+v6Iaxb/+7J5kEvZhTFQId+bSiJImF1FSUT1W1xwzBZPUbcUkkXDj45vC2s3Z8E+Lk7a3uZhvsQHLZnrfuWjBWGWvZ/MhZYgEXAMPLE
```
**バックエンドサーバー認証ポリシーを作成するには**  
この例では、パブリックキーポリシーを使用してバックエンドインスタンスで認証を有効にするバックエンドサーバー認証ポリシーを作成します。  
コマンド:  

```
aws elb create-load-balancer-policy --load-balancer-name my-load-balancer --policy-name my-authentication-policy --policy-type-name BackendServerAuthenticationPolicyType --policy-attributes AttributeName=PublicKeyPolicyName,AttributeValue=my-PublicKey-policy
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLoadBalancerPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/create-load-balancer-policy.html)」を参照してください。

### `create-load-balancer`
<a name="elastic-load-balancing_CreateLoadBalancer_cli_2_topic"></a>

次のコード例は、`create-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**HTTP ロードバランサーを作成するには**  
この例では、VPC に HTTP リスナーを持つロードバランサーを作成します。  
コマンド:  

```
aws elb create-load-balancer --load-balancer-name my-load-balancer --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=80" --subnets subnet-15aaab61 --security-groups sg-a61988c3
```
出力:  

```
{
    "DNSName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com"
}
```
この例では、EC2-Classic に HTTP リスナーを持つロードバランサーを作成します。  
コマンド:  

```
aws elb create-load-balancer --load-balancer-name my-load-balancer --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=80" --availability-zones us-west-2a us-west-2b
```
出力:  

```
{
    "DNSName": "my-load-balancer-123456789.us-west-2.elb.amazonaws.com"
}
```
**HTTPS ロードバランサーを作成するには**  
この例では、VPC に HTTPS リスナーを持つロードバランサーを作成します。  
コマンド:  

```
aws elb create-load-balancer --load-balancer-name my-load-balancer --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=80" "Protocol=HTTPS,LoadBalancerPort=443,InstanceProtocol=HTTP,InstancePort=80,SSLCertificateId=arn:aws:iam::123456789012:server-certificate/my-server-cert" --subnets subnet-15aaab61 --security-groups sg-a61988c3
```
出力:  

```
{
    "DNSName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com"
}
```
この例では、EC2-Classic に HTTPS リスナーを使用してロードバランサーを作成します。  
コマンド:  

```
aws elb create-load-balancer --load-balancer-name my-load-balancer --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=80" "Protocol=HTTPS,LoadBalancerPort=443,InstanceProtocol=HTTP,InstancePort=80,SSLCertificateId=arn:aws:iam::123456789012:server-certificate/my-server-cert" --availability-zones us-west-2a us-west-2b
```
出力:  

```
{
    "DNSName": "my-load-balancer-123456789.us-west-2.elb.amazonaws.com"
}
```
**内部向けロードバランサーを作成するには**  
この例では、VPC に HTTP リスナーを持つ内部ロードバランサーを作成します。  
コマンド:  

```
aws elb create-load-balancer --load-balancer-name my-load-balancer --listeners "Protocol=HTTP,LoadBalancerPort=80,InstanceProtocol=HTTP,InstancePort=80" --scheme internal --subnets subnet-a85db0df --security-groups sg-a61988c3
```
出力:  

```
{
    "DNSName": "internal-my-load-balancer-123456789.us-west-2.elb.amazonaws.com"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/create-load-balancer.html)」を参照してください。**

### `delete-load-balancer-listeners`
<a name="elastic-load-balancing_DeleteLoadBalancerListeners_cli_2_topic"></a>

次のコード例は、`delete-load-balancer-listeners` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーからリスナーを削除するには**  
この例では、指定されたロードバランサーから指定されたポートのリスナーを削除します。  
コマンド:  

```
aws elb delete-load-balancer-listeners --load-balancer-name my-load-balancer --load-balancer-ports 80
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLoadBalancerListeners](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/delete-load-balancer-listeners.html)」を参照してください。

### `delete-load-balancer-policy`
<a name="elastic-load-balancing_DeleteLoadBalancerPolicy_cli_2_topic"></a>

次のコード例は、`delete-load-balancer-policy` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーからポリシーを削除するには**  
この例では、指定されたロードバランサーから指定されたポリシーを削除します。このポリシーでは、どのリスナーでも有効にできません。  
コマンド:  

```
aws elb delete-load-balancer-policy --load-balancer-name my-load-balancer --policy-name my-duration-cookie-policy
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLoadBalancerPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/delete-load-balancer-policy.html)」を参照してください。

### `delete-load-balancer`
<a name="elastic-load-balancing_DeleteLoadBalancer_cli_2_topic"></a>

次のコード例は、`delete-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーを削除するには**  
この例は、指定されたロードバランサーを削除します。  
コマンド:  

```
aws elb delete-load-balancer --load-balancer-name my-load-balancer
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/delete-load-balancer.html)」を参照してください。**

### `deregister-instances-from-load-balancer`
<a name="elastic-load-balancing_DeregisterInstancesFromLoadBalancer_cli_2_topic"></a>

次のコード例は、`deregister-instances-from-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーからインスタンスの登録を解除するには**  
この例では、指定されたロードバランサーから指定されたインスタンスを登録解除します。  
コマンド:  

```
aws elb deregister-instances-from-load-balancer --load-balancer-name my-load-balancer --instances i-d6f6fae3
```
出力:  

```
{
    "Instances": [
        {
            "InstanceId": "i-207d9717"
        },
        {
            "InstanceId": "i-afefb49b"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterInstancesFromLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/deregister-instances-from-load-balancer.html)」を参照してください。

### `describe-account-limits`
<a name="elastic-load-balancing_DescribeAccountLimits_cli_2_topic"></a>

次のコード例は、`describe-account-limits` を使用する方法を示しています。

**AWS CLI**  
**Classic Load Balancer の制限を記述するには**  
次の の`describe-account-limits`例では、 AWS アカウントの Classic Load Balancer の制限に関する詳細を表示します。  

```
aws elb describe-account-limits
```
出力:  

```
{
    "Limits": [
        {
            "Name": "classic-load-balancers",
            "Max": "20"
        },
        {
            "Name": "classic-listeners",
            "Max": "100"
        },
        {
            "Name": "classic-registered-instances",
            "Max": "1000"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/describe-account-limits.html)」を参照してください。

### `describe-instance-health`
<a name="elastic-load-balancing_DescribeInstanceHealth_cli_2_topic"></a>

次のコード例は、`describe-instance-health` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーのインスタンスのヘルスを記述するには**  
この例では、指定されたロードバランサーのインスタンスのヘルスを記述します。  
コマンド:  

```
aws elb describe-instance-health --load-balancer-name my-load-balancer
```
出力:  

```
{
  "InstanceStates": [
      {
          "InstanceId": "i-207d9717",
          "ReasonCode": "N/A",
          "State": "InService",
          "Description": "N/A"
      },
      {
          "InstanceId": "i-afefb49b",
          "ReasonCode": "N/A",
          "State": "InService",
          "Description": "N/A"
      }
  ]
}
```
**ロードバランサーのインスタンスのヘルスを記述するには**  
この例では、指定されたロードバランサーの指定されたインスタンスのヘルスを記述します。  
コマンド:  

```
aws elb describe-instance-health --load-balancer-name my-load-balancer --instances i-7299c809
```
次は、登録しているインスタンスのレスポンスの例を次に示します。  
出力:  

```
{
  "InstanceStates": [
      {
          "InstanceId": "i-7299c809",
          "ReasonCode": "ELB",
          "State": "OutOfService",
          "Description": "Instance registration is still in progress."
    }
  ]
}
```
次は、異常なインスタンスのレスポンスの例です。  
出力:  

```
{
  "InstanceStates": [
      {
          "InstanceId": "i-7299c809",
          "ReasonCode": "Instance",
          "State": "OutOfService",
          "Description": "Instance has failed at least the UnhealthyThreshold number of health checks consecutively."
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceHealth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/describe-instance-health.html)」を参照してください。

### `describe-load-balancer-attributes`
<a name="elastic-load-balancing_DescribeLoadBalancerAttributes_cli_2_topic"></a>

次のコード例は、`describe-load-balancer-attributes` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーの属性を記述するには**  
この例では、指定されたロードバランサーの属性を記述します。  
コマンド:  

```
aws elb describe-load-balancer-attributes --load-balancer-name my-load-balancer
```
出力:  

```
{
  "LoadBalancerAttributes": {
      "ConnectionDraining": {
          "Enabled": false,
          "Timeout": 300
      },
      "CrossZoneLoadBalancing": {
          "Enabled": true
      },
      "ConnectionSettings": {
          "IdleTimeout": 30
      },
      "AccessLog": {
          "Enabled": false
    }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoadBalancerAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/describe-load-balancer-attributes.html)」を参照してください。

### `describe-load-balancer-policies`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicies_cli_2_topic"></a>

次のコード例は、`describe-load-balancer-policies` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーに関連付けられたすべてのポリシーを記述するには**  
この例では、指定されたロードバランサーに関連付けられたすべてのポリシーを記述します。  
コマンド:  

```
aws elb describe-load-balancer-policies --load-balancer-name my-load-balancer
```
出力:  

```
{
  "PolicyDescriptions": [
    {
      "PolicyAttributeDescriptions": [
        {
          "AttributeName": "ProxyProtocol",
          "AttributeValue": "true"
        }
      ],
      "PolicyName": "my-ProxyProtocol-policy",
      "PolicyTypeName": "ProxyProtocolPolicyType"
    },
    {
        "PolicyAttributeDescriptions": [
            {
                "AttributeName": "CookieName",
                "AttributeValue": "my-app-cookie"
            }
        ],
        "PolicyName": "my-app-cookie-policy",
        "PolicyTypeName": "AppCookieStickinessPolicyType"
    },
    {
      "PolicyAttributeDescriptions": [
        {
          "AttributeName": "CookieExpirationPeriod",
          "AttributeValue": "60"
        }
      ],
      "PolicyName": "my-duration-cookie-policy",
      "PolicyTypeName": "LBCookieStickinessPolicyType"
    },
    .
    .
    .
  ]
}
```
**ロードバランサーに関連付けられた特定のポリシーを記述するには**  
この例では、指定されたロードバランサーに関連付けられた指定されたポリシーを記述します。  
コマンド:  

```
aws elb describe-load-balancer-policies --load-balancer-name my-load-balancer --policy-name my-authentication-policy
```
出力:  

```
{
  "PolicyDescriptions": [
      {
          "PolicyAttributeDescriptions": [
              {
                  "AttributeName": "PublicKeyPolicyName",
                  "AttributeValue": "my-PublicKey-policy"
              }
          ],
          "PolicyName": "my-authentication-policy",
          "PolicyTypeName": "BackendServerAuthenticationPolicyType"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoadBalancerPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/describe-load-balancer-policies.html)」を参照してください。

### `describe-load-balancer-policy-types`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicyTypes_cli_2_topic"></a>

次のコード例は、`describe-load-balancer-policy-types` を使用する方法を示しています。

**AWS CLI**  
**Elastic Load Balancing で定義されるロードバランサーポリシータイプを記述するには**  
この例では、ロードバランサーのポリシー設定を作成するために使用できるロードバランサーのポリシータイプを記述します。  
コマンド:  

```
aws elb describe-load-balancer-policy-types
```
出力:  

```
{
  "PolicyTypeDescriptions": [
      {
          "PolicyAttributeTypeDescriptions": [
              {
                  "Cardinality": "ONE",
                  "AttributeName": "ProxyProtocol",
                  "AttributeType": "Boolean"
              }
          ],
          "PolicyTypeName": "ProxyProtocolPolicyType",
          "Description": "Policy that controls whether to include the IP address and port of the originating request for TCP messages. This policy operates on TCP/SSL listeners only"
      },
      {
          "PolicyAttributeTypeDescriptions": [
              {
                  "Cardinality": "ONE",
                  "AttributeName": "PublicKey",
                  "AttributeType": "String"
              }
          ],
          "PolicyTypeName": "PublicKeyPolicyType",
          "Description": "Policy containing a list of public keys to accept when authenticating the back-end server(s). This policy cannot be applied directly to back-end servers or listeners but must be part of a BackendServerAuthenticationPolicyType."
      },
      {
          "PolicyAttributeTypeDescriptions": [
              {
                  "Cardinality": "ONE",
                  "AttributeName": "CookieName",
                  "AttributeType": "String"
              }
          ],
          "PolicyTypeName": "AppCookieStickinessPolicyType",
          "Description": "Stickiness policy with session lifetimes controlled by the lifetime of the application-generated cookie. This policy can be associated only with HTTP/HTTPS listeners."
      },
      {
          "PolicyAttributeTypeDescriptions": [
              {
                  "Cardinality": "ZERO_OR_ONE",
                  "AttributeName": "CookieExpirationPeriod",
                  "AttributeType": "Long"
              }
          ],
          "PolicyTypeName": "LBCookieStickinessPolicyType",
          "Description": "Stickiness policy with session lifetimes controlled by the browser (user-agent) or a specified expiration period. This policy can be associated only with HTTP/HTTPS listeners."
      },
      {
          "PolicyAttributeTypeDescriptions": [
              .
              .
              .
          ],
          "PolicyTypeName": "SSLNegotiationPolicyType",
          "Description": "Listener policy that defines the ciphers and protocols that will be accepted by the load balancer. This policy can be associated only with HTTPS/SSL listeners."
      },
      {
          "PolicyAttributeTypeDescriptions": [
              {
                  "Cardinality": "ONE_OR_MORE",
                  "AttributeName": "PublicKeyPolicyName",
                  "AttributeType": "PolicyName"
              }
          ],
          "PolicyTypeName": "BackendServerAuthenticationPolicyType",
          "Description": "Policy that controls authentication to back-end server(s) and contains one or more policies, such as an instance of a PublicKeyPolicyType. This policy can be associated only with back-end servers that are using HTTPS/SSL."
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoadBalancerPolicyTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/describe-load-balancer-policy-types.html)」を参照してください。

### `describe-load-balancers`
<a name="elastic-load-balancing_DescribeLoadBalancers_cli_2_topic"></a>

次のコード例は、`describe-load-balancers` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーを記述するには**  
この例は、すべてのロードバランサーを記述します。  
コマンド:  

```
aws elb describe-load-balancers
```
**ロードバランサーの 1 つを記述するには**  
この例は、指定されたロードバランサーを記述します。  
コマンド:  

```
aws elb describe-load-balancers --load-balancer-name my-load-balancer
```
次の応答例は、VPC 内に HTTPS ロードバランサー用です。  
出力:  

```
{
  "LoadBalancerDescriptions": [
    {
      "Subnets": [
          "subnet-15aaab61"
      ],
      "CanonicalHostedZoneNameID": "Z3DZXE0EXAMPLE",
      "CanonicalHostedZoneName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com",
      "ListenerDescriptions": [
          {
              "Listener": {
                  "InstancePort": 80,
                  "LoadBalancerPort": 80,
                  "Protocol": "HTTP",
                  "InstanceProtocol": "HTTP"
              },
              "PolicyNames": []
          },
          {
              "Listener": {
                  "InstancePort": 443,
                  "SSLCertificateId": "arn:aws:iam::123456789012:server-certificate/my-server-cert",
                  "LoadBalancerPort": 443,
                  "Protocol": "HTTPS",
                  "InstanceProtocol": "HTTPS"
              },
              "PolicyNames": [
                  "ELBSecurityPolicy-2015-03"
              ]
          }
      ],
      "HealthCheck": {
          "HealthyThreshold": 2,
          "Interval": 30,
          "Target": "HTTP:80/png",
          "Timeout": 3,
          "UnhealthyThreshold": 2
      },
      "VPCId": "vpc-a01106c2",
      "BackendServerDescriptions": [
          {
              "InstancePort": 80,
              "PolicyNames": [
                  "my-ProxyProtocol-policy"
              ]
          }
      ],
      "Instances": [
          {
              "InstanceId": "i-207d9717"
          },
          {
              "InstanceId": "i-afefb49b"
          }
      ],
      "DNSName": "my-load-balancer-1234567890.us-west-2.elb.amazonaws.com",
      "SecurityGroups": [
          "sg-a61988c3"
      ],
      "Policies": {
          "LBCookieStickinessPolicies": [
              {
                  "PolicyName": "my-duration-cookie-policy",
                  "CookieExpirationPeriod": 60
              }
          ],
          "AppCookieStickinessPolicies": [],
          "OtherPolicies": [
              "my-PublicKey-policy",
              "my-authentication-policy",
              "my-SSLNegotiation-policy",
              "my-ProxyProtocol-policy",
              "ELBSecurityPolicy-2015-03"
          ]
      },
      "LoadBalancerName": "my-load-balancer",
      "CreatedTime": "2015-03-19T03:24:02.650Z",
      "AvailabilityZones": [
          "us-west-2a"
      ],
      "Scheme": "internet-facing",
      "SourceSecurityGroup": {
          "OwnerAlias": "123456789012",
          "GroupName": "my-elb-sg"
      }
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/describe-load-balancers.html)」を参照してください。

### `describe-tags`
<a name="elastic-load-balancing_DescribeTags_cli_2_topic"></a>

次のコード例は、`describe-tags` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーに割り当てられたタグを記述するには**  
この例では、指定されたロードバランサーに割り当てられたタグを記述します。  
コマンド:  

```
aws elb describe-tags --load-balancer-name my-load-balancer
```
出力:  

```
{
  "TagDescriptions": [
      {
          "Tags": [
              {
                  "Value": "lima",
                  "Key": "project"
              },
              {
                  "Value": "digital-media",
                  "Key": "department"
              }
          ],
          "LoadBalancerName": "my-load-balancer"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/describe-tags.html)」を参照してください。

### `detach-load-balancer-from-subnets`
<a name="elastic-load-balancing_DetachLoadBalancerFromSubnets_cli_2_topic"></a>

次のコード例は、`detach-load-balancer-from-subnets` を使用する方法を示しています。

**AWS CLI**  
**サブネットからロードバランサーをデタッチするには**  
この例では、指定されたロードバランサーを指定されたサブネットからデタッチします。  
コマンド:  

```
aws elb detach-load-balancer-from-subnets --load-balancer-name my-load-balancer --subnets subnet-0ecac448
```
出力:  

```
{
   "Subnets": [
       "subnet-15aaab61"
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachLoadBalancerFromSubnets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/detach-load-balancer-from-subnets.html)」を参照してください。

### `disable-availability-zones-for-load-balancer`
<a name="elastic-load-balancing_DisableAvailabilityZonesForLoadBalancer_cli_2_topic"></a>

次のコード例は、`disable-availability-zones-for-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーのアベイラビリティーゾーンを無効にするには**  
この例では、指定されたアベイラビリティーゾーンを、指定されたロードバランサーの一連のアベイラビリティーゾーンから削除します。  
コマンド:  

```
aws elb disable-availability-zones-for-load-balancer --load-balancer-name my-load-balancer --availability-zones us-west-2a
```
出力:  

```
{
    "AvailabilityZones": [
        "us-west-2b"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableAvailabilityZonesForLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/disable-availability-zones-for-load-balancer.html)」を参照してください。

### `enable-availability-zones-for-load-balancer`
<a name="elastic-load-balancing_EnableAvailabilityZonesForLoadBalancer_cli_2_topic"></a>

次のコード例は、`enable-availability-zones-for-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーのアベイラビリティーゾーンを有効にするには**  
この例では、指定されたアベイラビリティーゾーンを指定されたロードバランサーに追加します。  
コマンド:  

```
aws elb enable-availability-zones-for-load-balancer --load-balancer-name my-load-balancer --availability-zones us-west-2b
```
出力:  

```
{
    "AvailabilityZones": [
        "us-west-2a",
        "us-west-2b"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableAvailabilityZonesForLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/enable-availability-zones-for-load-balancer.html)」を参照してください。

### `modify-load-balancer-attributes`
<a name="elastic-load-balancing_ModifyLoadBalancerAttributes_cli_2_topic"></a>

次のコード例は、`modify-load-balancer-attributes` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーの属性を変更するには**  
次の例は、指定されたロードバランサーの `CrossZoneLoadBalancing` 属性を変更します。  
コマンド:  

```
aws elb modify-load-balancer-attributes --load-balancer-name my-load-balancer --load-balancer-attributes "{\"CrossZoneLoadBalancing\":{\"Enabled\":true}}"
```
出力:  

```
{
    "LoadBalancerAttributes": {
        "CrossZoneLoadBalancing": {
            "Enabled": true
        }
    },
    "LoadBalancerName": "my-load-balancer"
}
```
次の例は、指定されたロードバランサーの `ConnectionDraining` 属性を変更します。  
コマンド:  

```
aws elb modify-load-balancer-attributes --load-balancer-name my-load-balancer --load-balancer-attributes "{\"ConnectionDraining\":{\"Enabled\":true,\"Timeout\":300}}"
```
出力:  

```
{
    "LoadBalancerAttributes": {
        "ConnectionDraining": {
            "Enabled": true,
            "Timeout": 300
        }
    },
    "LoadBalancerName": "my-load-balancer"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyLoadBalancerAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/modify-load-balancer-attributes.html)」を参照してください。

### `register-instances-with-load-balancer`
<a name="elastic-load-balancing_RegisterInstancesWithLoadBalancer_cli_2_topic"></a>

次のコード例は、`register-instances-with-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーにインスタンスを登録するには**  
この例では、指定されたインスタンスを指定されたロードバランサーに登録します。  
コマンド:  

```
aws elb register-instances-with-load-balancer --load-balancer-name my-load-balancer --instances i-d6f6fae3
```
出力:  

```
{
   "Instances": [
       {
           "InstanceId": "i-d6f6fae3"
       },
       {
           "InstanceId": "i-207d9717"
       },
       {
           "InstanceId": "i-afefb49b"
       }
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterInstancesWithLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/register-instances-with-load-balancer.html)」を参照してください。

### `remove-tags`
<a name="elastic-load-balancing_RemoveTags_cli_2_topic"></a>

次のコード例は、`remove-tags` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーからタグを削除するには**  
この例では、指定されたロードバランサーからタグを削除します。  
コマンド:  

```
aws elb remove-tags --load-balancer-name my-load-balancer --tags project
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/remove-tags.html)」を参照してください。

### `set-load-balancer-listener-ssl-certificate`
<a name="elastic-load-balancing_SetLoadBalancerListenerSslCertificate_cli_2_topic"></a>

次のコード例は、`set-load-balancer-listener-ssl-certificate` を使用する方法を示しています。

**AWS CLI**  
**HTTPS ロードバランサーの SSL 証明書を更新するには**  
この例では、指定された HTTPS ロードバランサーの既存の SSL 証明書を置き換えます。  
コマンド:  

```
aws elb set-load-balancer-listener-ssl-certificate --load-balancer-name my-load-balancer --load-balancer-port 443 --ssl-certificate-id arn:aws:iam::123456789012:server-certificate/new-server-cert
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetLoadBalancerListenerSslCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/set-load-balancer-listener-ssl-certificate.html)」を参照してください。

### `set-load-balancer-policies-for-backend-server`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesForBackendServer_cli_2_topic"></a>

次のコード例は、`set-load-balancer-policies-for-backend-server` を使用する方法を示しています。

**AWS CLI**  
**バックエンドインスタンスのポートに関連付けられたポリシーを置き換えるには**  
この例では、指定されたポートに現在関連付けられているポリシーを置き換えます。  
コマンド:  

```
aws elb set-load-balancer-policies-for-backend-server --load-balancer-name my-load-balancer --instance-port 80 --policy-names my-ProxyProtocol-policy
```
**バックエンドインスタンスのポートに現在関連付けられているすべてのポリシーを削除するには**  
この例では、指定されたポートに関連付けられているすべてのポリシーを削除します。  
コマンド:  

```
aws elb set-load-balancer-policies-for-backend-server --load-balancer-name my-load-balancer --instance-port 80 --policy-names []
```
ポリシーが削除されていることを確認するには、`describe-load-balancer-policies` コマンドを使用します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetLoadBalancerPoliciesForBackendServer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/set-load-balancer-policies-for-backend-server.html)」を参照してください。

### `set-load-balancer-policies-of-listener`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesOfListener_cli_2_topic"></a>

次のコード例は、`set-load-balancer-policies-of-listener` を使用する方法を示しています。

**AWS CLI**  
**リスナーに関連付けられたポリシーを置き換えるには**  
この例では、指定されたリスナーに現在関連付けられているポリシーを置き換えます。  
コマンド:  

```
aws elb set-load-balancer-policies-of-listener --load-balancer-name my-load-balancer --load-balancer-port 443 --policy-names my-SSLNegotiation-policy
```
**リスナーに関連付けられているすべてのポリシーを削除するには**  
この例では、指定したリスナーに現在関連付けられているすべてのポリシーを削除します。  
コマンド:  

```
aws elb set-load-balancer-policies-of-listener --load-balancer-name my-load-balancer --load-balancer-port 443 --policy-names []
```
ポリシーがロードバランサーから削除されていることを確認するには、`describe-load-balancer-policies` コマンドを使用します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetLoadBalancerPoliciesOfListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elb/set-load-balancer-policies-of-listener.html)」を参照してください。

# を使用した Elastic Load Balancing - バージョン 2 の例 AWS CLI
<a name="cli_2_elastic-load-balancing-v2_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 2 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-listener-certificates`
<a name="elastic-load-balancing-v2_AddListenerCertificates_cli_2_topic"></a>

次のコード例は、`add-listener-certificates` を使用する方法を示しています。

**AWS CLI**  
**セキュアリスナーに証明書を追加するには**  
この例では、指定された証明書を指定されたセキュアリスナーに追加します。  
コマンド:  

```
aws elbv2 add-listener-certificates --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 --certificates CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/5cc54884-f4a3-4072-80be-05b9ba72f705
```
出力:  

```
{
  "Certificates": [
      {
          "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/5cc54884-f4a3-4072-80be-05b9ba72f705",
          "IsDefault": false
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddListenerCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/add-listener-certificates.html)」を参照してください。

### `add-tags`
<a name="elastic-load-balancing-v2_AddTags_cli_2_topic"></a>

次のコード例は、`add-tags` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーにタグを追加するには**  
次の `add-tags` の例では、指定されたロードバランサーに `project` と `department` タグを追加します。  

```
aws elbv2 add-tags \
    --resource-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 \
    --tags "Key=project,Value=lima" "Key=department,Value=digital-media"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/add-tags.html)」を参照してください。

### `create-listener`
<a name="elastic-load-balancing-v2_CreateListener_cli_2_topic"></a>

次のコード例は、`create-listener` を使用する方法を示しています。

**AWS CLI**  
**例 1: HTTP リスナーを作成するには**  
次の `create-listener` の例は、指定されたターゲットグループにリクエストを転送する、指定された Application Load Balancer の HTTP リスナーを作成します。  

```
aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 \
    --protocol HTTP \
    --port 80 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
詳細については、[Application Load Balancer ユーザーガイド」の「チュートリアル: CLI AWS を使用して](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/tutorial-application-load-balancer-cli.html#create-load-balancer-aws-cli) *Application Load Balancer* を作成する」を参照してください。  
**例 2: HTTPS リスナーを作成するには**  
次の `create-listener` の例は、指定されたターゲットグループにリクエストを転送する、指定された Application Load Balancer の HTTPS リスナーを作成します。HTTPS リスナーの SSL 証明書を指定する必要があります。Certificate AWS Manager (ACM) を使用して証明書を作成および管理できます。または、SSL/TLS ツールを使用して証明書を作成し、認証機関 (CA) によって署名された証明書を取得し、その証明書を AWS Identity and Access Management (IAM) にアップロードすることもできます。  

```
aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 \
    --protocol HTTPS \
    --port 443 \
    --certificates CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/3dcb0a41-bd72-4774-9ad9-756919c40557 \
    --ssl-policy ELBSecurityPolicy-2016-08 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
詳細については、「Application Load Balancers のユーザーガイド」の「[HTTPS リスナーの追加](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/tutorial-application-load-balancer-cli.html#https-listener-aws-cli)」を参照してください。**  
**例 3: TCP リスナーを作成するには**  
次の `create-listener` の例は、指定されたターゲットグループにリクエストを転送する、指定された Network Load Balancer の TCP リスナーを作成します。  

```
aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/net/my-network-load-balancer/5d1b75f4f1cee11e \
    --protocol TCP \
    --port 80 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-tcp-targets/b6bba954d1361c78
```
詳細については、[「Network Load Balancer ユーザーガイド」の「チュートリアル: CLI AWS を使用して](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/network-load-balancer-cli.html#create-load-balancer-aws-cli) *Network Load Balancer* を作成する」を参照してください。  
**例 4: TLS リスナーを作成するには**  
次の `create-listener` の例は、指定されたターゲットグループにリクエストを転送する、指定された Network Load Balancer の TLS リスナーを作成します。TLS リスナーの SSL 証明書を指定する必要があります。  

```
aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 \
    --protocol TLS \
    --port 443 \
    --certificates CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/3dcb0a41-bd72-4774-9ad9-756919c40557 \
    --ssl-policy ELBSecurityPolicy-2016-08 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
詳細については、「Network Load Balancers のユーザーガイド」の「[Network Load Balancer の TLS リスナー](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-tls-listener.html)」を参照してください。**  
**例 5: UDP リスナーを作成するには**  
次の `create-listener` の例は、指定されたターゲットグループにリクエストを転送する、指定された Network Load Balancer の UDP リスナーを作成します。  

```
aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/net/my-network-load-balancer/5d1b75f4f1cee11e \
    --protocol UDP \
    --port 53 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-tcp-targets/b6bba954d1361c78
```
詳細については、[「Network Load Balancer ユーザーガイド」の「チュートリアル: CLI AWS を使用して](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/network-load-balancer-cli.html#create-load-balancer-aws-cli) *Network Load Balancer* を作成する」を参照してください。  
**例 6: 指定されたゲートウェイのリスナーを作成して転送するには**  
次の `create-listener` の例は、指定されたターゲットグループにリクエストを転送する、指定された Gateway Load Balancer のリスナーを作成します。  

```
aws elbv2 create-listener \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-east-1:850631746142:loadbalancer/gwy/my-gateway-load-balancer/e0f9b3d5c7f7d3d6 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-east-1:850631746142:targetgroup/my-glb-targets/007ca469fae3bb1615
```
出力:  

```
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:elasticloadbalancing:us-east-1:850631746142:listener/gwy/my-agw-lb-example2/e0f9b3d5c7f7d3d6/afc127db15f925de",
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:850631746142:loadbalancer/gwy/my-agw-lb-example2/e0f9b3d5c7f7d3d6",
            "DefaultActions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:850631746142:targetgroup/test-tg-agw-2/007ca469fae3bb1615",
                    "ForwardConfig": {
                        "TargetGroups": [
                            {
                                "TargetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:850631746142:targetgroup/test-tg-agw-2/007ca469fae3bb1615"
                            }
                        ]
                    }
                }
            ]
        }
    ]
}
```
詳細については、[Gateway Load Balancer ユーザーガイドの「 CLI AWS を使用した Gateway Load Balancer の開始方法](https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/create-listener.html)」を参照してください。**

### `create-load-balancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_cli_2_topic"></a>

次のコード例は、`create-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**例 1: インターネット向けロードバランサーを作成するには**  
次の `create-load-balancer` の例は、インターネット向けの Application Load Balancer を作成し、指定されたサブネットのアベイラビリティーゾーンを有効化します。  

```
aws elbv2 create-load-balancer \
    --name my-load-balancer \
    --subnets subnet-b7d581c0 subnet-8360a9e7
```
出力:  

```
{
    "LoadBalancers": [
        {
            "Type": "application",
            "Scheme": "internet-facing",
            "IpAddressType": "ipv4",
            "VpcId": "vpc-3ac0fb5f",
            "AvailabilityZones": [
                {
                    "ZoneName": "us-west-2a",
                    "SubnetId": "subnet-8360a9e7"
                },
                {
                    "ZoneName": "us-west-2b",
                    "SubnetId": "subnet-b7d581c0"
                }
            ],
            "CreatedTime": "2017-08-25T21:26:12.920Z",
            "CanonicalHostedZoneId": "Z2P70J7EXAMPLE",
            "DNSName": "my-load-balancer-424835706.us-west-2.elb.amazonaws.com",
            "SecurityGroups": [
                "sg-5943793c"
            ],
            "LoadBalancerName": "my-load-balancer",
            "State": {
                "Code": "provisioning"
            },
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188"
        }
    ]
}
```
詳細については、[Application Load Balancer ユーザーガイド」の「チュートリアル: CLI AWS を使用して](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/tutorial-application-load-balancer-cli.html) *Application Load Balancer* を作成する」を参照してください。  
**例 2: 内部向けロードバランサーを作成するには**  
次の `create-load-balancer` の例は、内部向けの Application Load Balancer を作成し、指定されたサブネットのアベイラビリティーゾーンを有効化します。  

```
aws elbv2 create-load-balancer \
    --name my-internal-load-balancer \
    --scheme internal \
    --subnets subnet-b7d581c0 subnet-8360a9e7
```
出力:  

```
{
    "LoadBalancers": [
        {
            "Type": "application",
            "Scheme": "internal",
            "IpAddressType": "ipv4",
            "VpcId": "vpc-3ac0fb5f",
            "AvailabilityZones": [
                {
                    "ZoneName": "us-west-2a",
                    "SubnetId": "subnet-8360a9e7"
                },
                {
                    "ZoneName": "us-west-2b",
                    "SubnetId": "subnet-b7d581c0"
                }
            ],
            "CreatedTime": "2016-03-25T21:29:48.850Z",
            "CanonicalHostedZoneId": "Z2P70J7EXAMPLE",
            "DNSName": "internal-my-internal-load-balancer-1529930873.us-west-2.elb.amazonaws.com",
            "SecurityGroups": [
                "sg-5943793c"
            ],
            "LoadBalancerName": "my-internal-load-balancer",
            "State": {
                "Code": "provisioning"
            },
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-internal-load-balancer/5b49b8d4303115c2"
        }
    ]
}
```
詳細については、[Application Load Balancer ユーザーガイド」の「チュートリアル: CLI AWS を使用して](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/tutorial-application-load-balancer-cli.html) *Application Load Balancer* を作成する」を参照してください。  
**例 3: Network Load Balancer を作成するには**  
次の `create-load-balancer` の例は、インターネット向けの Network Load Balancer を作成し、指定されたサブネットのアベイラビリティーゾーンを有効化します。サブネットマッピングを使用して、指定された Elastic IP アドレスを、アベイラビリティーゾーンのロードバランサーノードが使用するネットワークインターフェイスに関連付けます。  

```
aws elbv2 create-load-balancer \
    --name my-network-load-balancer \
    --type network \
    --subnet-mappings SubnetId=subnet-b7d581c0,AllocationId=eipalloc-64d5890a
```
出力:  

```
{
    "LoadBalancers": [
        {
            "Type": "network",
            "Scheme": "internet-facing",
            "IpAddressType": "ipv4",
            "VpcId": "vpc-3ac0fb5f",
            "AvailabilityZones": [
                {
                    "LoadBalancerAddresses": [
                        {
                            "IpAddress": "35.161.207.171",
                            "AllocationId": "eipalloc-64d5890a"
                        }
                    ],
                    "ZoneName": "us-west-2b",
                    "SubnetId": "subnet-5264e837"
                }
            ],
            "CreatedTime": "2017-10-15T22:41:25.657Z",
            "CanonicalHostedZoneId": "Z2P70J7EXAMPLE",
            "DNSName": "my-network-load-balancer-5d1b75f4f1cee11e.elb.us-west-2.amazonaws.com",
            "LoadBalancerName": "my-network-load-balancer",
            "State": {
                "Code": "provisioning"
            },
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/net/my-network-load-balancer/5d1b75f4f1cee11e"
        }
    ]
}
```
詳細については、[「Network Load Balancer ユーザーガイド」の「チュートリアル: CLI AWS を使用して](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/network-load-balancer-cli.html) *Network Load Balancer* を作成する」を参照してください。  
**例 4: Gateway Load Balancer を作成するには**  
次の `create-load-balancer` の例は、Gateway Load Balancer を作成し、指定されたサブネットのアベイラビリティーゾーンを有効化します。  

```
aws elbv2 create-load-balancer \
    --name my-gateway-load-balancer \
    --type gateway \
    --subnets subnet-dc83f691 subnet-a62583f9
```
出力:  

```
{
    "LoadBalancers": [
        {
            "Type": "gateway",
            "VpcId": "vpc-838475fe",
            "AvailabilityZones": [
                {
                    "ZoneName": "us-east-1b",
                    "SubnetId": "subnet-a62583f9"
                },
            {
                    "ZoneName": "us-east-1a",
                    "SubnetId": "subnet-dc83f691"
                }
            ],
            "CreatedTime": "2021-07-14T19:33:43.324000+00:00",
            "LoadBalancerName": "my-gateway-load-balancer",
            "State": {
                "Code": "provisioning"
            },
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:850631746142:loadbalancer/gwy/my-gateway-load-balancer/dfbb5a7d32cdee79"
        }
    ]
}
```
詳細については、[Gateway Load Balancer ユーザーガイドの「 CLI AWS を使用した Gateway Load Balancer の開始方法](https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/getting-started-cli.html)」を参照してください。 **  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/create-load-balancer.html)」を参照してください。**

### `create-rule`
<a name="elastic-load-balancing-v2_CreateRule_cli_2_topic"></a>

次のコード例は、`create-rule` を使用する方法を示しています。

**AWS CLI**  
**例 1: パス条件とフォワードアクションを使用してルールを作成するには**  
次の `create-rule` の例では、リクエストの URL に指定されたパターンが含まれる場合、指定されたターゲットグループへのリクエスト送信ルールを作成します。  

```
aws elbv2 create-rule \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 \
    --priority 5 \
    --conditions file://conditions-pattern.json
    --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
`conditions-pattern.json` の内容:  

```
[
    {
        "Field": "path-pattern",
        "PathPatternConfig": {
            "Values": ["/images/*"]
        }
    }
]
```
**例 2: ホスト条件と固定レスポンスを使用してルールを作成するには**  
次の `create-rule` の例では、ホストヘッダーのホスト名が指定されたホスト名と一致する場合に、固定されたレスポンスを提供するルールを作成します。  

```
aws elbv2 create-rule \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 \
    --priority 10 \
    --conditions file://conditions-host.json \
    --actions file://actions-fixed-response.json
```
`conditions-host.json` の内容  

```
[
  {
      "Field": "host-header",
      "HostHeaderConfig": {
          "Values": ["*.example.com"]
      }
  }
]
```
`actions-fixed-response.json` の内容  

```
[
    {
        "Type": "fixed-response",
        "FixedResponseConfig": {
            "MessageBody": "Hello world",
            "StatusCode": "200",
            "ContentType": "text/plain"
        }
    }
]
```
**例 3: ソース IP アドレス条件、認証アクション、転送アクションを使用してルールを作成するには**  
次の `create-rule` の例では、送信元 IP アドレスが指定された IP アドレスと一致する場合にユーザーを認証するルールを作成し、認証が成功した場合にリクエストを指定されたターゲットグループに転送します。  

```
aws elbv2 create-rule \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 \
    --priority 20 \
    --conditions file://conditions-source-ip.json \
    --actions file://actions-authenticate.json
```
`conditions-source-ip.json` の内容  

```
[
    {
        "Field": "source-ip",
        "SourceIpConfig": {
            "Values": ["192.0.2.0/24", "198.51.100.10/32"]
        }
    }
]
```
`actions-authenticate.json` の内容  

```
[
    {
        "Type": "authenticate-oidc",
        "AuthenticateOidcConfig": {
            "Issuer": "https://idp-issuer.com",
            "AuthorizationEndpoint": "https://authorization-endpoint.com",
            "TokenEndpoint": "https://token-endpoint.com",
            "UserInfoEndpoint": "https://user-info-endpoint.com",
            "ClientId": "abcdefghijklmnopqrstuvwxyz123456789",
            "ClientSecret": "123456789012345678901234567890",
            "SessionCookieName": "my-cookie",
            "SessionTimeout": 3600,
            "Scope": "email",
            "AuthenticationRequestExtraParams": {
                "display": "page",
                "prompt": "login"
            },
            "OnUnauthenticatedRequest": "deny"
        },
        "Order": 1
    },
    {
        "Type": "forward",
        "TargetGroupArn": "arn:aws:elasticloadbalancing:us-east-1:880185128111:targetgroup/cli-test/642a97ecb0e0f26b",
        "Order": 2
    }
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/create-rule.html)」を参照してください。

### `create-target-group`
<a name="elastic-load-balancing-v2_CreateTargetGroup_cli_2_topic"></a>

次のコード例は、`create-target-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: Application Load Balancer のターゲットグループを作成するには**  
次の `create-target-group` の例は、Application Load Balancer のターゲットグループを作成し、インスタンス ID (ターゲットタイプは `instance`) でターゲットを登録します。このターゲットグループは HTTP プロトコル、ポート 80、および HTTP ターゲットグループのデフォルトのヘルスチェック設定を使用します。  

```
aws elbv2 create-target-group \
    --name my-targets \
    --protocol HTTP \
    --port 80 \
    --target-type instance \
    --vpc-id vpc-3ac0fb5f
```
出力:  

```
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
            "TargetGroupName": "my-targets",
            "Protocol": "HTTP",
            "Port": 80,
            "VpcId": "vpc-3ac0fb5f",
            "HealthCheckProtocol": "HTTP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/",
            "Matcher": {
                "HttpCode": "200"
            },
            "TargetType": "instance",
            "ProtocolVersion": "HTTP1",
            "IpAddressType": "ipv4"
        }
    ]
}
```
詳細については、「Application Load Balancers のユーザーガイド」の「[ターゲットグループの作成](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-target-group.html)」を参照してください。**  
**例 2: Application Load Balancer から Lambda 関数にトラフィックをルーティングするターゲットグループを作成するには**  
次の `create-target-group` の例は、Application Load Balancer のターゲットグループを作成します。ターゲットは Lambda 関数 (ターゲットタイプは `lambda`) です。このターゲットグループのヘルスチェックは、デフォルトでは無効化されています。  

```
aws elbv2 create-target-group \
    --name my-lambda-target \
    --target-type lambda
```
出力:  

```
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-lambda-target/a3003e085dbb8ddc",
            "TargetGroupName": "my-lambda-target",
            "HealthCheckEnabled": false,
            "HealthCheckIntervalSeconds": 35,
            "HealthCheckTimeoutSeconds": 30,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/",
            "Matcher": {
                "HttpCode": "200"
            },
            "TargetType": "lambda",
            "IpAddressType": "ipv4"
        }
    ]
}
```
詳細については、「*Application Load Balancer ユーザーガイド*」の「[ターゲットとしての Lambda 関数](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html)」を参照してください。  
**例 3: Network Load Balancer のターゲットグループを作成するには**  
次の `create-target-group` の例は、Network Load Balancer のターゲットグループを作成し、IP アドレス (ターゲットタイプは `ip`) でターゲットを登録します。このターゲットグループは TCP プロトコル、ポート 80、および TCP ターゲットグループのデフォルトのヘルスチェック設定を使用します。  

```
aws elbv2 create-target-group \
    --name my-ip-targets \
    --protocol TCP \
    --port 80 \
    --target-type ip \
    --vpc-id vpc-3ac0fb5f
```
出力:  

```
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-ip-targets/b6bba954d1361c78",
            "TargetGroupName": "my-ip-targets",
            "Protocol": "TCP",
            "Port": 80,
            "VpcId": "vpc-3ac0fb5f",
            "HealthCheckEnabled": true,
            "HealthCheckProtocol": "TCP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 10,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "TargetType": "ip",
            "IpAddressType": "ipv4"
        }
    ]
}
```
詳細については、「*Network Load Balancer のユーザーガイド*」の「[Create a target group](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-target-group.html)」を参照してください。  
**例 4: Network Load Balancer から Application Load Balancer にトラフィックをルーティングするターゲットグループを作成するには**  
次の `create-target-group` の例は、Network Load Balancer のターゲットグループを作成し、そこにターゲットとして (ターゲットタイプは `alb`) Application Load Balancer をを登録します。  
aws elbv2 create-target-group --name my-alb-target --protocol TCP --port 80 --target-type alb --vpc-id vpc-3ac0fb5f  
出力:  

```
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-alb-target/a3003e085dbb8ddc",
            "TargetGroupName": "my-alb-target",
            "Protocol": "TCP",
            "Port": 80,
            "VpcId": "vpc-838475fe",
            "HealthCheckProtocol": "HTTP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 6,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/",
            "Matcher": {
                "HttpCode": "200-399"
            },
            "TargetType": "alb",
            "IpAddressType": "ipv4"
        }
    ]
}
```
詳細については、「*Network Load Balancer のユーザーガイド*」の「[Create a target group with an Application Load Balancer as the target](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/application-load-balancer-target.html)」を参照してください。  
**例 5: Gateway Load Balancer のターゲットグループを作成するには**  
次の `create-target-group` の例は、Gateway Load Balancer のターゲットグループを作成します。ターゲットはインスタンスで、ターゲットグループのプロトコルは `GENEVE` です。  

```
aws elbv2 create-target-group \
    --name my-glb-targetgroup \
    --protocol GENEVE \
    --port 6081 \
    --target-type instance \
    --vpc-id vpc-838475fe
```
出力:  

```
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-glb-targetgroup/00c3d57eacd6f40b6f",
            "TargetGroupName": "my-glb-targetgroup",
            "Protocol": "GENEVE",
            "Port": 6081,
            "VpcId": "vpc-838475fe",
            "HealthCheckProtocol": "TCP",
            "HealthCheckPort": "80",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 10,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "TargetType": "instance"
        }
    ]
}
```
詳細については、「*Gateway Load Balancer ユーザーガイド*」の「ターゲットグループの作成 <https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/create-target-group.html>`\$1\$1」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateTargetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/create-target-group.html)」を参照してください。**

### `delete-listener`
<a name="elastic-load-balancing-v2_DeleteListener_cli_2_topic"></a>

次のコード例は、`delete-listener` を使用する方法を示しています。

**AWS CLI**  
**リスナーを削除するには**  
以下の `delete-listener` 例は、指定されたリスナーを削除します。  

```
aws elbv2 delete-listener \
    --listener-arn arn:aws:elasticloadbalancing:ua-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/delete-listener.html)」を参照してください。

### `delete-load-balancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_cli_2_topic"></a>

次のコード例は、`delete-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーを削除するには**  
次の `delete-load-balancer` の例は、指定されたロードバランサーを削除します。  

```
aws elbv2 delete-load-balancer \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/delete-load-balancer.html)」を参照してください。**

### `delete-rule`
<a name="elastic-load-balancing-v2_DeleteRule_cli_2_topic"></a>

次のコード例は、`delete-rule` を使用する方法を示しています。

**AWS CLI**  
**ルールを削除するには**  
次の `delete-rule` の例は、指定されたルールを削除します。  

```
aws elbv2 delete-rule \
    --rule-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/1291d13826f405c3
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/delete-rule.html)」を参照してください。**

### `delete-target-group`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_cli_2_topic"></a>

次のコード例は、`delete-target-group` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループを削除するには**  
次の `delete-target-group` の例は、指定されたターゲットグループを削除します。  

```
aws elbv2 delete-target-group \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
このコマンドでは何も出力されません。  
詳細については、「*Application Load Balancer ユーザーガイド*」の「[Delete a load balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-delete.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteTargetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/delete-target-group.html)」を参照してください。**

### `deregister-targets`
<a name="elastic-load-balancing-v2_DeregisterTargets_cli_2_topic"></a>

次のコード例は、`deregister-targets` を使用する方法を示しています。

**AWS CLI**  
**例 1: ターゲットグループからターゲットの登録を解除するには**  
次の `deregister-targets` の例では、指定されたインスタンスを指定されたターゲットグループから削除します。  

```
aws elbv2 deregister-targets \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 \
    --targets Id=i-1234567890abcdef0
```
**例 2: ポートオーバーライドを使用して登録されたターゲットの登録を解除するには**  
次の `deregister-targets` の例では、ポートオーバーライドを使用して登録されたターゲットグループからインスタンスを削除します。  

```
aws elbv2 deregister-targets \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-internal-targets/3bb63f11dfb0faf9 \
    --targets Id=i-1234567890abcdef0,Port=80 Id=i-1234567890abcdef0,Port=766
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/deregister-targets.html)」を参照してください。

### `describe-account-limits`
<a name="elastic-load-balancing-v2_DescribeAccountLimits_cli_2_topic"></a>

次のコード例は、`describe-account-limits` を使用する方法を示しています。

**AWS CLI**  
**Elastic Load Balancing の制限を記述するには**  
次の の`describe-account-limits`例では、現在のリージョンの AWS アカウントの Elastic Load Balancing の制限を表示します。  

```
aws elbv2 describe-account-limits
```
出力:  

```
{
    "Limits": [
        {
            "Name": "target-groups",
            "Max": "3000"
        },
        {
            "Name": "targets-per-application-load-balancer",
            "Max": "1000"
        },
        {
            "Name": "listeners-per-application-load-balancer",
            "Max": "50"
        },
        {
            "Name": "rules-per-application-load-balancer",
            "Max": "100"
        },
        {
            "Name": "network-load-balancers",
            "Max": "50"
        },
        {
            "Name": "targets-per-network-load-balancer",
            "Max": "3000"
        },
        {
            "Name": "targets-per-availability-zone-per-network-load-balancer",
            "Max": "500"
        },
        {
            "Name": "listeners-per-network-load-balancer",
            "Max": "50"
        },
        {
            "Name": "condition-values-per-alb-rule",
            "Max": "5"
        },
        {
            "Name": "condition-wildcards-per-alb-rule",
            "Max": "5"
        },
        {
            "Name": "target-groups-per-application-load-balancer",
            "Max": "100"
        },
        {
            "Name": "target-groups-per-action-on-application-load-balancer",
            "Max": "5"
        },
        {
            "Name": "target-groups-per-action-on-network-load-balancer",
            "Max": "1"
        },
        {
            "Name": "certificates-per-application-load-balancer",
            "Max": "25"
        },
        {
            "Name": "certificates-per-network-load-balancer",
            "Max": "25"
        },
        {
            "Name": "targets-per-target-group",
            "Max": "1000"
        },
        {
            "Name": "target-id-registrations-per-application-load-balancer",
            "Max": "1000"
        },
        {
            "Name": "network-load-balancer-enis-per-vpc",
            "Max": "1200"
        },
        {
            "Name": "application-load-balancers",
            "Max": "50"
        },
        {
            "Name": "gateway-load-balancers",
            "Max": "100"
        },
        {
            "Name": "gateway-load-balancers-per-vpc",
            "Max": "100"
        },
        {
            "Name": "geneve-target-groups",
            "Max": "100"
        },
        {
            "Name": "targets-per-availability-zone-per-gateway-load-balancer",
            "Max": "300"
        }
    ]
}
```
詳細については、「*AWS 全般リファレンス*」の「[Quotas](https://docs.aws.amazon.com/general/latest/gr/elb.html#limits_elastic_load_balancer)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-account-limits.html)」を参照してください。

### `describe-listener-certificates`
<a name="elastic-load-balancing-v2_DescribeListenerCertificates_cli_2_topic"></a>

次のコード例は、`describe-listener-certificates` を使用する方法を示しています。

**AWS CLI**  
**セキュアリスナーの証明書を記述するには**  
この例では、指定されたセキュアリスナーの証明書を記述します。  
コマンド:  

```
aws elbv2 describe-listener-certificates --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2
```
出力:  

```
{
  "Certificates": [
      {
          "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/5cc54884-f4a3-4072-80be-05b9ba72f705",
          "IsDefault": false
      },
      {
          "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/3dcb0a41-bd72-4774-9ad9-756919c40557",
          "IsDefault": false
      },
      {
          "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/fe59da96-6f58-4a22-8eed-6d0d50477e1d",
          "IsDefault": true
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeListenerCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-listener-certificates.html)」を参照してください。

### `describe-listeners`
<a name="elastic-load-balancing-v2_DescribeListeners_cli_2_topic"></a>

次のコード例は、`describe-listeners` を使用する方法を示しています。

**AWS CLI**  
**リスナーを記述するには**  
この例では、指定されたリスナーを記述します。  
コマンド:  

```
aws elbv2 describe-listeners --listener-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2
```
出力:  

```
{
  "Listeners": [
      {
          "Port": 80,
          "Protocol": "HTTP",
          "DefaultActions": [
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
                  "Type": "forward"
              }
          ],
          "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188",
          "ListenerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2"
      }
  ]
}
```
**ロードバランサーのリスナーを記述するには**  
この例は、指定されたロードバランサーのリスナーを記述します。  
コマンド:  

```
aws elbv2 describe-listeners --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188
```
出力:  

```
{
  "Listeners": [
      {
          "Port": 443,
          "Protocol": "HTTPS",
          "DefaultActions": [
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
                  "Type": "forward"
              }
          ],
          "SslPolicy": "ELBSecurityPolicy-2015-05",
          "Certificates": [
              {
                  "CertificateArn": "arn:aws:iam::123456789012:server-certificate/my-server-cert"
              }
          ],
          "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188",
          "ListenerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/0467ef3c8400ae65"
      },
      {
          "Port": 80,
          "Protocol": "HTTP",
          "DefaultActions": [
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
                  "Type": "forward"
              }
          ],
          "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188",
          "ListenerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeListeners](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-listeners.html)」を参照してください。

### `describe-load-balancer-attributes`
<a name="elastic-load-balancing-v2_DescribeLoadBalancerAttributes_cli_2_topic"></a>

次のコード例は、`describe-load-balancer-attributes` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサー属性を記述するには**  
次の `describe-load-balancer-attributes` の例では、指定されたロードバランサーの属性を表示します。  

```
aws elbv2 describe-load-balancer-attributes \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188
```
次の出力例は、Application Load Balancer の属性を示しています。  

```
{
    "Attributes": [
        {
            "Value": "false",
            "Key": "access_logs.s3.enabled"
        },
        {
            "Value": "",
            "Key": "access_logs.s3.bucket"
        },
        {
            "Value": "",
            "Key": "access_logs.s3.prefix"
        },
        {
            "Value": "60",
            "Key": "idle_timeout.timeout_seconds"
        },
        {
            "Value": "false",
            "Key": "deletion_protection.enabled"
        },
        {
            "Value": "true",
            "Key": "routing.http2.enabled"
        }
    ]
}
```
次の出力例には、Network Load Balancer の属性が含まれています。  

```
{
    "Attributes": [
        {
            "Value": "false",
            "Key": "access_logs.s3.enabled"
        },
        {
            "Value": "",
            "Key": "access_logs.s3.bucket"
        },
        {
            "Value": "",
            "Key": "access_logs.s3.prefix"
        },
        {
            "Value": "false",
            "Key": "deletion_protection.enabled"
        },
        {
            "Value": "false",
            "Key": "load_balancing.cross_zone.enabled"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoadBalancerAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-load-balancer-attributes.html)」を参照してください。

### `describe-load-balancers`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_cli_2_topic"></a>

次のコード例は、`describe-load-balancers` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーを記述するには**  
この例は、指定されたロードバランサーを記述します。  
コマンド:  

```
aws elbv2 describe-load-balancers --load-balancer-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188
```
出力:  

```
{
  "LoadBalancers": [
      {
          "Type": "application",
          "Scheme": "internet-facing",
          "IpAddressType": "ipv4",
          "VpcId": "vpc-3ac0fb5f",
          "AvailabilityZones": [
              {
                  "ZoneName": "us-west-2a",
                  "SubnetId": "subnet-8360a9e7"
              },
              {
                  "ZoneName": "us-west-2b",
                  "SubnetId": "subnet-b7d581c0"
              }
          ],
          "CreatedTime": "2016-03-25T21:26:12.920Z",
          "CanonicalHostedZoneId": "Z2P70J7EXAMPLE",
          "DNSName": "my-load-balancer-424835706.us-west-2.elb.amazonaws.com",
          "SecurityGroups": [
              "sg-5943793c"
          ],
          "LoadBalancerName": "my-load-balancer",
          "State": {
              "Code": "active"
          },
          "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188"
      }
  ]
}
```
**すべてのロードバランサーを記述するには**  
この例は、すべてのロードバランサーを記述します。  
コマンド:  

```
aws elbv2 describe-load-balancers
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-load-balancers.html)」を参照してください。**

### `describe-rules`
<a name="elastic-load-balancing-v2_DescribeRules_cli_2_topic"></a>

次のコード例は、`describe-rules` を使用する方法を示しています。

**AWS CLI**  
**例 1: ルールを記述するには**  
次の `describe-rules` の例は、指定されたルールの詳細情報を表示します。  

```
aws elbv2 describe-rules \
    --rule-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/9683b2d02a6cabee
```
**例 2: リスナーのルールを記述するには**  
次の `describe-rules` の例は、指定されたリスナーのルールの詳細を表示します。出力には、デフォルトのルールと、追加したその他のルールが含まれます。  

```
aws elbv2 describe-rules \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-rules.html)」を参照してください。

### `describe-ssl-policies`
<a name="elastic-load-balancing-v2_DescribeSslPolicies_cli_2_topic"></a>

次のコード例は、`describe-ssl-policies` を使用する方法を示しています。

**AWS CLI**  
**例 1: ロードバランサータイプ別に SSL ネゴシエーションに使用されるポリシーを一覧表示するには**  
次の `describe-ssl-policies` の例は、Application Load Balancer との SSL ネゴシエーションに使用できるポリシーの名前を示しています。例では、`--query` パラメータを使用してポリシーの名前のみを表示しています。  

```
aws elbv2 describe-ssl-policies \
    --load-balancer-type application \
    --query SslPolicies[*].Name
```
出力:  

```
[
    "ELBSecurityPolicy-2016-08",
    "ELBSecurityPolicy-TLS13-1-2-2021-06",
    "ELBSecurityPolicy-TLS13-1-2-Res-2021-06",
    "ELBSecurityPolicy-TLS13-1-2-Ext1-2021-06",
    "ELBSecurityPolicy-TLS13-1-2-Ext2-2021-06",
    "ELBSecurityPolicy-TLS13-1-1-2021-06",
    "ELBSecurityPolicy-TLS13-1-0-2021-06",
    "ELBSecurityPolicy-TLS13-1-3-2021-06",
    "ELBSecurityPolicy-TLS-1-2-2017-01",
    "ELBSecurityPolicy-TLS-1-1-2017-01",
    "ELBSecurityPolicy-TLS-1-2-Ext-2018-06",
    "ELBSecurityPolicy-FS-2018-06",
    "ELBSecurityPolicy-2015-05",
    "ELBSecurityPolicy-TLS-1-0-2015-04",
    "ELBSecurityPolicy-FS-1-2-Res-2019-08",
    "ELBSecurityPolicy-FS-1-1-2019-08",
    "ELBSecurityPolicy-FS-1-2-2019-08",
    "ELBSecurityPolicy-FS-1-2-Res-2020-10"
]
```
**例 2: 特定のプロトコルをサポートするポリシーを一覧表示するには**  
次の `describe-ssl-policies` の例は、TLS 1.3 プロトコルをサポートするポリシーの名前を示しています。例では、`--query` パラメータを使用してポリシーの名前のみを表示しています。  

```
aws elbv2 describe-ssl-policies \
    --load-balancer-type application \
    --query SslPolicies[?contains(SslProtocols,'TLSv1.3')].Name
```
出力:  

```
[
    "ELBSecurityPolicy-TLS13-1-2-2021-06",
    "ELBSecurityPolicy-TLS13-1-2-Res-2021-06",
    "ELBSecurityPolicy-TLS13-1-2-Ext1-2021-06",
    "ELBSecurityPolicy-TLS13-1-2-Ext2-2021-06",
    "ELBSecurityPolicy-TLS13-1-1-2021-06",
    "ELBSecurityPolicy-TLS13-1-0-2021-06",
    "ELBSecurityPolicy-TLS13-1-3-2021-06"
]
```
**例 3: ポリシーの暗号を表示するには**  
次の `describe-ssl-policies` の例では、指定されたポリシーの暗号の名前を表示します。例では、`--query` パラメータを使用して暗号の名前のみを表示しています。リスト内の最初の暗号の優先度は 1 で、残りの暗号は優先順位が付けられています。  

```
aws elbv2 describe-ssl-policies \
    --names ELBSecurityPolicy-TLS13-1-2-2021-06 \
    --query SslPolicies[*].Ciphers[*].Name
```
出力:  

```
[
    "TLS_AES_128_GCM_SHA256",
    "TLS_AES_256_GCM_SHA384",
    "TLS_CHACHA20_POLY1305_SHA256",
    "ECDHE-ECDSA-AES128-GCM-SHA256",
    "ECDHE-RSA-AES128-GCM-SHA256",
    "ECDHE-ECDSA-AES128-SHA256",
    "ECDHE-RSA-AES128-SHA256",
    "ECDHE-ECDSA-AES256-GCM-SHA384",
    "ECDHE-RSA-AES256-GCM-SHA384",
    "ECDHE-ECDSA-AES256-SHA384",
    "ECDHE-RSA-AES256-SHA384"
]
```
詳細については、「*Application Load Balancer のユーザーガイド*」の「[セキュリティポリシー](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-https-listener.html#describe-ssl-policies)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSslPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-ssl-policies.html)」を参照してください。

### `describe-tags`
<a name="elastic-load-balancing-v2_DescribeTags_cli_2_topic"></a>

次のコード例は、`describe-tags` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーに割り当てられたタグを記述するには**  
この例では、指定されたロードバランサーに割り当てられたタグを記述します。  
コマンド:  

```
aws elbv2 describe-tags --resource-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188
```
出力:  

```
{
  "TagDescriptions": [
      {
          "ResourceArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188",
          "Tags": [
              {
                  "Value": "lima",
                  "Key": "project"
              },
              {
                  "Value": "digital-media",
                  "Key": "department"
              }
          ]
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-tags.html)」を参照してください。

### `describe-target-group-attributes`
<a name="elastic-load-balancing-v2_DescribeTargetGroupAttributes_cli_2_topic"></a>

次のコード例は、`describe-target-group-attributes` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループ属性を記述するには**  
次の `describe-target-group-attributes` の例では、指定したターゲットグループの属性を表示します。  

```
aws elbv2 describe-target-group-attributes \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
プロトコルが HTTP または HTTPS で、ターゲットタイプが `instance` または `ip` の場合、出力には属性が含まれます。  

```
{
    "Attributes": [
        {
            "Value": "false",
            "Key": "stickiness.enabled"
        },
        {
            "Value": "300",
            "Key": "deregistration_delay.timeout_seconds"
        },
        {
            "Value": "lb_cookie",
            "Key": "stickiness.type"
        },
        {
            "Value": "86400",
            "Key": "stickiness.lb_cookie.duration_seconds"
        },
        {
            "Value": "0",
            "Key": "slow_start.duration_seconds"
        }
    ]
}
```
プロトコルが HTTP または HTTPS で、ターゲットタイプが `lambda` の場合、次の出力には属性が含まれます。  

```
{
    "Attributes": [
        {
            "Value": "false",
            "Key": "lambda.multi_value_headers.enabled"
        }
    ]
}
```
次の出力には、プロトコルが TCP、TLS、UDP、または TCP\$1UDP の場合の属性が含まれます。  

```
{
    "Attributes": [
        {
            "Value": "false",
            "Key": "proxy_protocol_v2.enabled"
        },
        {
            "Value": "300",
            "Key": "deregistration_delay.timeout_seconds"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTargetGroupAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-target-group-attributes.html)」を参照してください。

### `describe-target-groups`
<a name="elastic-load-balancing-v2_DescribeTargetGroups_cli_2_topic"></a>

次のコード例は、`describe-target-groups` を使用する方法を示しています。

**AWS CLI**  
**例 1: ターゲットグループを記述するには**  
次の `describe-target-groups` の例は、指定されたターゲットグループの詳細情報を表示します。  

```
aws elbv2 describe-target-groups \
    --target-group-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
出力:  

```
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
            "TargetGroupName": "my-targets",
            "Protocol": "HTTP",
            "Port": 80,
            "VpcId": "vpc-3ac0fb5f",
            "HealthCheckProtocol": "HTTP",
            "HealthCheckPort": "traffic-port",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "HealthCheckPath": "/",
            "Matcher": {
                "HttpCode": "200"
            },
            "LoadBalancerArns": [
                "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188"
            ],
            "TargetType": "instance",
            "ProtocolVersion": "HTTP1",
            "IpAddressType": "ipv4"
        }
    ]
}
```
**例 2: ロードバランサーのすべてのターゲットグループを記述するには**  
次の `describe-target-groups` の例は、指定されたロードバランサーのすべてのターゲットグループの詳細情報を表示します。例では、`--query` パラメータを使用してターゲットグループの名前のみを表示しています。  

```
aws elbv2 describe-target-groups \
    --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 \
    --query TargetGroups[*].TargetGroupName
```
出力:  

```
[
    "my-instance-targets",
    "my-ip-targets",
    "my-lambda-target"
]
```
詳細については、「*Application Load Balancer ガイド*」の「[ターゲットグループ](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeTargetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-target-groups.html)」を参照してください。**

### `describe-target-health`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_cli_2_topic"></a>

次のコード例は、`describe-target-health` を使用する方法を示しています。

**AWS CLI**  
**例 1: ターゲットグループのターゲットのヘルスを記述するには**  
次の `describe-target-health` の例は、指定されたターゲットグループのターゲットのヘルスの詳細情報を表示します。これらのターゲットは正常です。  

```
aws elbv2 describe-target-health \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
出力:  

```
{
    "TargetHealthDescriptions": [
        {
            "HealthCheckPort": "80",
            "Target": {
                "Id": "i-ceddcd4d",
                "Port": 80
            },
            "TargetHealth": {
                "State": "healthy"
            }
        },
        {
            "HealthCheckPort": "80",
            "Target": {
                "Id": "i-0f76fade",
                "Port": 80
            },
            "TargetHealth": {
                "State": "healthy"
            }
        }
    ]
}
```
**例 2: ターゲットのヘルスを記述するには**  
次の `describe-target-health` の例は、指定されたターゲットのヘルスの詳細情報を表示します。このターゲットは正常です。  

```
aws elbv2 describe-target-health \
    --targets Id=i-0f76fade,Port=80 \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067
```
出力:  

```
{
    "TargetHealthDescriptions": [
        {
            "HealthCheckPort": "80",
            "Target": {
                "Id": "i-0f76fade",
                "Port": 80
            },
            "TargetHealth": {
                "State": "healthy"
            }
        }
    ]
}
```
次の出力例は、リスナーのアクションでターゲットグループが指定されていないターゲットの出力です。このターゲットはロードバランサーからのトラフィックを受信できません。  

```
{
    "TargetHealthDescriptions": [
    {
        "HealthCheckPort": "80",
        "Target": {
            "Id": "i-0f76fade",
            "Port": 80
        },
            "TargetHealth": {
                "State": "unused",
                "Reason": "Target.NotInUse",
                "Description": "Target group is not configured to receive traffic from the load balancer"
            }
        }
    ]
}
```
次の例は、リスナーのアクションでターゲットグループが指定されたばかりのターゲットの出力です。このターゲットは現在登録中です。  

```
{
    "TargetHealthDescriptions": [
        {
            "HealthCheckPort": "80",
            "Target": {
                "Id": "i-0f76fade",
                "Port": 80
            },
            "TargetHealth": {
                "State": "initial",
                "Reason": "Elb.RegistrationInProgress",
                "Description": "Target registration is in progress"
            }
        }
    ]
}
```
次の例は、正常でないターゲットの出力です。  

```
{
    "TargetHealthDescriptions": [
        {
            "HealthCheckPort": "80",
            "Target": {
                "Id": "i-0f76fade",
                "Port": 80
            },
            "TargetHealth": {
                "State": "unhealthy",
                "Reason": "Target.Timeout",
                "Description": "Connection to target timed out"
            }
        }
    ]
}
```
以下は、ターゲットが Lambda 関数で、ヘルスチェックが無効化されている出力の例です。  

```
{
    "TargetHealthDescriptions": [
        {
            "Target": {
                "Id": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
                "AvailabilityZone": "all",
            },
            "TargetHealth": {
                "State": "unavailable",
                "Reason": "Target.HealthCheckDisabled",
                "Description": "Health checks are not enabled for this target"
            }
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeTargetHealth](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/describe-target-health.html)」を参照してください。**

### `modify-listener`
<a name="elastic-load-balancing-v2_ModifyListener_cli_2_topic"></a>

次のコード例は、`modify-listener` を使用する方法を示しています。

**AWS CLI**  
**例 1: デフォルトのアクションを転送アクションに変更するには**  
次の `modify-listener` の例では、デフォルトのアクションを指定されたリスナーの `forward` アクションに変更します。  

```
aws elbv2 modify-listener \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 \
    --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-new-targets/2453ed029918f21f
```
出力:  

```
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2",
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188",
            "Protocol": "HTTP",
            "Port": 80,
            "DefaultActions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-new-targets/2453ed029918f21f"
                }
            ]
        }
    ]
}
```
**例 2: デフォルトのアクションをリダイレクトアクションに変更するには**  
次の `modify-listener` の例では、デフォルトのアクションを指定されたリスナーの `redirect` アクションに変更します。  

```
aws elbv2 modify-listener \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 \
    --default-actions Type=redirect, RedirectConfig='{Protocol=HTTPS,StatusCode=HTTP_302}'
```
出力:  

```
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2",
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188",
            "Protocol": "HTTP",
            "Port": 80,
            "DefaultActions": [
                {
                    "Type": "redirect",
                    "RedirectConfig": {
                        "Protocol": "HTTPS",
                        "Port": "#{port}",
                        "Host": "#{host}",
                        "Path": "/#{path}",
                        "Query": "#{query}",
                        "StatusCode": "HTTP_302",
                    }
                }
            ]
        }
    ]
}
```
**例 3: サーバー証明書を変更するには**  
次の `modify-listener` の例では、指定された HTTPS リスナーのサーバー証明書を変更します。  

```
aws elbv2 modify-listener \
    --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/0467ef3c8400ae65 \
    --certificates CertificateArn=arn:aws:iam::123456789012:server-certificate/my-new-server-cert
```
出力:  

```
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/0467ef3c8400ae65",
            "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188",
            "Protocol": "HTTPS",
            "Port": 443,
            "DefaultActions": [
                {
                    "Type": "forward",
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067"
                }
            ],
            "SslPolicy": "ELBSecurityPolicy-2015-05",
            "Certificates": [
                {
                    "CertificateArn": "arn:aws:iam::123456789012:server-certificate/my-new-server-cert"
                }
            ],
        }
    ]
}
```
詳細については、「*Application Load Balancer のユーザーガイド*」の「[リスナールール](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#listener-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/modify-listener.html)」を参照してください。

### `modify-load-balancer-attributes`
<a name="elastic-load-balancing-v2_ModifyLoadBalancerAttributes_cli_2_topic"></a>

次のコード例は、`modify-load-balancer-attributes` を使用する方法を示しています。

**AWS CLI**  
**削除保護を有効にするには**  
この例では、指定されたロードバランサーの削除保護を有効にします。  
コマンド:  

```
aws elbv2 modify-load-balancer-attributes --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 --attributes Key=deletion_protection.enabled,Value=true
```
出力:  

```
{
  "Attributes": [
      {
          "Value": "true",
          "Key": "deletion_protection.enabled"
      },
      {
          "Value": "false",
          "Key": "access_logs.s3.enabled"
      },
      {
          "Value": "60",
          "Key": "idle_timeout.timeout_seconds"
      },
      {
          "Value": "",
          "Key": "access_logs.s3.prefix"
      },
      {
          "Value": "",
          "Key": "access_logs.s3.bucket"
      }
  ]
}
```
**アイドルタイムアウトを変更するには**  
この例では、指定されたロードバランサーのアイドルタイムアウト値を変更します。  
コマンド:  

```
aws elbv2 modify-load-balancer-attributes --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 --attributes Key=idle_timeout.timeout_seconds,Value=30
```
出力:  

```
{
  "Attributes": [
      {
          "Value": "30",
          "Key": "idle_timeout.timeout_seconds"
      },
      {
          "Value": "false",
          "Key": "access_logs.s3.enabled"
      },
      {
          "Value": "",
          "Key": "access_logs.s3.prefix"
      },
      {
          "Value": "true",
          "Key": "deletion_protection.enabled"
      },
      {
          "Value": "",
          "Key": "access_logs.s3.bucket"
      }
  ]
}
```
**アクセスログを有効にするには**  
この例では、指定されたロードバランサーのアクセスログを有効にします。S3 バケットはロードバランサーと同じリージョンに存在し、Elastic Load Balancing サービスへのアクセスを許可するポリシーがアタッチされている必要があることに注意してください。  
コマンド:  

```
aws elbv2 modify-load-balancer-attributes --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 --attributes Key=access_logs.s3.enabled,Value=true Key=access_logs.s3.bucket,Value=my-loadbalancer-logs Key=access_logs.s3.prefix,Value=myapp
```
出力:  

```
{
  "Attributes": [
      {
          "Value": "true",
          "Key": "access_logs.s3.enabled"
      },
      {
          "Value": "my-load-balancer-logs",
          "Key": "access_logs.s3.bucket"
      },
      {
          "Value": "myapp",
          "Key": "access_logs.s3.prefix"
      },
      {
          "Value": "60",
          "Key": "idle_timeout.timeout_seconds"
      },
      {
          "Value": "false",
          "Key": "deletion_protection.enabled"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyLoadBalancerAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/modify-load-balancer-attributes.html)」を参照してください。

### `modify-rule`
<a name="elastic-load-balancing-v2_ModifyRule_cli_2_topic"></a>

次のコード例は、`modify-rule` を使用する方法を示しています。

**AWS CLI**  
**ルールを変更するには**  
次の `modify-rule` の例では、指定されたルールのアクションと条件を更新します。  

```
aws elbv2 modify-rule \
  --actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 \
  --conditions Field=path-pattern,Values='/images/*'
  --rule-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/9683b2d02a6cabee
```
出力:  

```
{
    "Rules": [
        {
            "Priority": "10",
            "Conditions": [
                {
                    "Field": "path-pattern",
                    "Values": [
                        "/images/*"
                    ]
                }
            ],
            "RuleArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/9683b2d02a6cabee",
            "IsDefault": false,
            "Actions": [
                {
                    "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
                    "Type": "forward"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/modify-rule.html)」を参照してください。

### `modify-target-group-attributes`
<a name="elastic-load-balancing-v2_ModifyTargetGroupAttributes_cli_2_topic"></a>

次のコード例は、`modify-target-group-attributes` を使用する方法を示しています。

**AWS CLI**  
**登録解除遅延タイムアウトを変更するには**  
この例では、登録解除遅延タイムアウトを指定されたターゲットグループの指定された値に設定します。  
コマンド:  

```
aws elbv2 modify-target-group-attributes --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 --attributes Key=deregistration_delay.timeout_seconds,Value=600
```
出力:  

```
{
  "Attributes": [
      {
          "Value": "false",
          "Key": "stickiness.enabled"
      },
      {
          "Value": "600",
          "Key": "deregistration_delay.timeout_seconds"
      },
      {
          "Value": "lb_cookie",
          "Key": "stickiness.type"
      },
      {
          "Value": "86400",
          "Key": "stickiness.lb_cookie.duration_seconds"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTargetGroupAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/modify-target-group-attributes.html)」を参照してください。

### `modify-target-group`
<a name="elastic-load-balancing-v2_ModifyTargetGroup_cli_2_topic"></a>

次のコード例は、`modify-target-group` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループのヘルスチェック設定を変更するには**  
次の `modify-target-group` の例では、指定されたターゲットグループのターゲットのヘルスを評価するために使用されるヘルスチェックの設定を変更します。CLI がカンマを解析する方法により、二重引用符ではなく一重引用符で `--matcher` オプションの範囲を囲む必要があることに注意してください。  

```
aws elbv2 modify-target-group \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-https-targets/2453ed029918f21f \
    --health-check-protocol HTTPS \
    --health-check-port 443 \
    --matcher HttpCode='200,299'
```
出力:  

```
{
    "TargetGroups": [
        {
            "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-https-targets/2453ed029918f21f",
            "TargetGroupName": "my-https-targets",
            "Protocol": "HTTPS",
            "Port": 443,
            "VpcId": "vpc-3ac0fb5f",
            "HealthCheckProtocol": "HTTPS",
            "HealthCheckPort": "443",
            "HealthCheckEnabled": true,
            "HealthCheckIntervalSeconds": 30,
            "HealthCheckTimeoutSeconds": 5,
            "HealthyThresholdCount": 5,
            "UnhealthyThresholdCount": 2,
            "Matcher": {
                "HttpCode": "200,299"
            },
            "LoadBalancerArns": [
                "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188"
            ],
            "TargetType": "instance",
            "ProtocolVersion": "HTTP1",
            "IpAddressType": "ipv4"
        }
    ]
}
```
詳細については、「*Application Load Balancer ガイド*」の「[ターゲットグループ](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyTargetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/modify-target-group.html)」を参照してください。

### `register-targets`
<a name="elastic-load-balancing-v2_RegisterTargets_cli_2_topic"></a>

次のコード例は、`register-targets` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンス ID でターゲットグループにターゲットを登録するには**  
次の `register-targets` の例では、指定されたインスタンスをターゲットグループに登録します。ターゲットグループは、`instance` のターゲットタイプを持つ必要があります。  

```
aws elbv2 register-targets \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067 \
    --targets Id=i-1234567890abcdef0 Id=i-0abcdef1234567890
```
**例 2: ポートオーバーライドを使用してターゲットをターゲットグループに登録するには**  
次の `register-targets` の例では、複数のポートを使用して、指定されたインスタンスをターゲットグループに登録します。これにより、ターゲットグループのターゲットと同じインスタンスにコンテナを登録できます。  

```
aws elbv2 register-targets \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-internal-targets/3bb63f11dfb0faf9 \
    --targets Id=i-0598c7d356eba48d7,Port=80 Id=i-0598c7d356eba48d7,Port=766
```
**例 3: IP アドレスでターゲットグループにターゲットを登録するには**  
次の `register-targets` の例では、指定された IP アドレスをターゲットグループに登録します。ターゲットグループは、`ip` のターゲットタイプを持つ必要があります。  

```
aws elbv2 register-targets \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-tcp-ip-targets/8518e899d173178f \
    --targets Id=10.0.1.15 Id=10.0.1.23
```
**例 4: Lambda 関数をターゲットとして登録するには**  
次の `register-targets` の例では、指定された IP アドレスをターゲットグループに登録します。ターゲットグループは、`lambda` のターゲットタイプを持つ必要があります。Lambda 関数を呼び出すには、Elastic Load Balancing のアクセス許可が必要です。  

```
aws elbv2 register-targets \
    --target-group-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-tcp-ip-targets/8518e899d173178f \
    --targets Id=arn:aws:lambda:us-west-2:123456789012:function:my-function
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/register-targets.html)」を参照してください。

### `remove-listener-certificates`
<a name="elastic-load-balancing-v2_RemoveListenerCertificates_cli_2_topic"></a>

次のコード例は、`remove-listener-certificates` を使用する方法を示しています。

**AWS CLI**  
**セキュアリスナーから証明書を削除するには**  
この例では、指定された証明書を指定されたセキュアリスナーから削除します。  
コマンド:  

```
aws elbv2 remove-listener-certificates --listener-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 --certificates CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/5cc54884-f4a3-4072-80be-05b9ba72f705
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveListenerCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/remove-listener-certificates.html)」を参照してください。

### `remove-tags`
<a name="elastic-load-balancing-v2_RemoveTags_cli_2_topic"></a>

次のコード例は、`remove-tags` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーからタグを削除するには**  
次の `remove-tags` の例では、指定されたロードバランサーから `project` と `department` タグを削除します。  

```
aws elbv2 remove-tags \
    --resource-arns arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 \
    --tag-keys project department
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/remove-tags.html)」を参照してください。

### `set-ip-address-type`
<a name="elastic-load-balancing-v2_SetIpAddressType_cli_2_topic"></a>

次のコード例は、`set-ip-address-type` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーのアドレスタイプを設定するには**  
この例では、指定されたロードバランサーのアドレスタイプを `dualstack` に設定します。ロードバランサーサブネットには IPv6 CIDR ブロックが関連付けられている必要があります。  
コマンド:  

```
aws elbv2 set-ip-address-type --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 --ip-address-type dualstack
```
出力:  

```
{
    "IpAddressType": "dualstack"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetIpAddressType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/set-ip-address-type.html)」を参照してください。

### `set-rule-priorities`
<a name="elastic-load-balancing-v2_SetRulePriorities_cli_2_topic"></a>

次のコード例は、`set-rule-priorities` を使用する方法を示しています。

**AWS CLI**  
**ルールの優先度を設定するには**  
この例では、指定されたルールの優先度を設定します。  
コマンド:  

```
aws elbv2 set-rule-priorities --rule-priorities RuleArn=arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/1291d13826f405c3,Priority=5
```
出力:  

```
{
  "Rules": [
      {
          "Priority": "5",
          "Conditions": [
              {
                  "Field": "path-pattern",
                  "Values": [
                      "/img/*"
                  ]
              }
          ],
          "RuleArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:listener-rule/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2/1291d13826f405c3",
          "IsDefault": false,
          "Actions": [
              {
                  "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067",
                  "Type": "forward"
              }
          ]
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetRulePriorities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/set-rule-priorities.html)」を参照してください。

### `set-security-groups`
<a name="elastic-load-balancing-v2_SetSecurityGroups_cli_2_topic"></a>

次のコード例は、`set-security-groups` を使用する方法を示しています。

**AWS CLI**  
**セキュリティグループをロードバランサーに関連付けるには**  
この例では、指定されたセキュリティグループを指定されたロードバランサーに関連付けます。  
コマンド:  

```
aws elbv2 set-security-groups --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 --security-groups sg-5943793c
```
出力:  

```
{
  "SecurityGroupIds": [
      "sg-5943793c"
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetSecurityGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/set-security-groups.html)」を参照してください。

### `set-subnets`
<a name="elastic-load-balancing-v2_SetSubnets_cli_2_topic"></a>

次のコード例は、`set-subnets` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーのアベイラビリティーゾーンを有効にするには**  
この例では、指定されたロードバランサーの指定されたサブネットのアベイラビリティーゾーンを有効にします。  
コマンド:  

```
aws elbv2 set-subnets --load-balancer-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188 --subnets subnet-8360a9e7 subnet-b7d581c0
```
出力:  

```
{
  "AvailabilityZones": [
      {
          "SubnetId": "subnet-8360a9e7",
          "ZoneName": "us-west-2a"
      },
      {
          "SubnetId": "subnet-b7d581c0",
          "ZoneName": "us-west-2b"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetSubnets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elbv2/set-subnets.html)」を参照してください。

# を使用した ElastiCache の例 AWS CLI
<a name="cli_2_elasticache_code_examples"></a>

次のコード例は、ElastiCache AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags-to-resource`
<a name="elasticache_AddTagsToResource_cli_2_topic"></a>

次のコード例は、`add-tags-to-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加するには**  
次の `add-tags-to-resource` の例では、クラスターまたはスナップショットリソースに最大 10 個のタグ、キーと値のペアを追加します。  

```
aws elasticache add-tags-to-resource \
    --resource-name "arn:aws:elasticache:us-east-1:1234567890:cluster:my-mem-cluster" \
    --tags '{"20150202":15, "ElastiCache":"Service"}'
```
出力:  

```
{
    "TagList": [
        {
            "Value": "20150202",
            "Key": "APIVersion"
        },
        {
            "Value": "ElastiCache",
            "Key": "Service"
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Monitoring Costs with Cost Allocation Tags](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AddTagsToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/add-tags-to-resource.html)」を参照してください。

### `authorize-cache-security-group-ingress`
<a name="elasticache_AuthorizeCacheSecurityGroupIngress_cli_2_topic"></a>

次のコード例は、`authorize-cache-security-group-ingress` を使用する方法を示しています。

**AWS CLI**  
**キャッシュセキュリティグループの進入を承認するには**  
次の `authorize-cache-security-group-ingress` の例では、キャッシュセキュリティグループへのネットワーク進入を許可します。  

```
aws elasticache authorize-cache-security-group-ingress \
     --cache-security-group-name  "my-sec-grp" \
     --ec2-security-group-name "my-ec2-sec-grp" \
     --ec2-security-group-owner-id "1234567890"
```
このコマンドでは何も出力されません。  
詳細については、「*ElastiCache ユーザーガイド*」の「[Self-Service Updates in Amazon ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Self-Service-Updates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AuthorizeCacheSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/authorize-cache-security-group-ingress.html)」を参照してください。

### `batch-apply-update-action`
<a name="elasticache_BatchApplyUpdateAction_cli_2_topic"></a>

次のコード例は、`batch-apply-update-action` を使用する方法を示しています。

**AWS CLI**  
**サービスの更新を適用するには**  
次の `batch-apply-update-action` の例では、Redis クラスターにサービス更新を適用します。  

```
aws elasticache batch-apply-update-action \
    --service-update-name elc-xxxxx406-xxx \
    --replication-group-ids test-cluster
```
出力:  

```
{
    "ProcessedUpdateActions": [
        {
            "ReplicationGroupId": "pat-cluster",
            "ServiceUpdateName": "elc-xxxxx406-xxx",
            "UpdateActionStatus": "waiting-to-start"
        }
    ],
    "UnprocessedUpdateActions": []
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Self-Service Updates in Amazon ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Self-Service-Updates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchApplyUpdateAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/batch-apply-update-action.html)」を参照してください。

### `batch-stop-update-action`
<a name="elasticache_BatchStopUpdateAction_cli_2_topic"></a>

次のコード例は、`batch-stop-update-action` を使用する方法を示しています。

**AWS CLI**  
**サービスの更新を停止するには**  
次の `batch-stop-update-action` の例では、Redis クラスターにサービス更新を適用します。  

```
aws elasticache batch-stop-update-action \
    --service-update-name elc-xxxxx406-xxx \
    --replication-group-ids test-cluster
```
出力:  

```
{
    "ProcessedUpdateActions": [
        {
            "ReplicationGroupId": "pat-cluster",
            "ServiceUpdateName": "elc-xxxxx406-xxx",
            "UpdateActionStatus": "stopping"
        }
    ],
    "UnprocessedUpdateActions": []
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Self-Service Updates in Amazon ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Self-Service-Updates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchStopUpdateAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/batch-stop-update-action.html)」を参照してください。

### `copy-snapshot`
<a name="elasticache_CopySnapshot_cli_2_topic"></a>

次のコード例は、`copy-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットをコピーするには**  
次の `copy-snapshot` の例では、既存のスナップショットのコピーを作成します。  

```
aws elasticache copy-snapshot \
    --source-snapshot-name "my-snapshot" \
    --target-snapshot-name "my-snapshot-copy"
```
出力:  

```
{
    "Snapshot":{
        "Engine": "redis",
        "CacheParameterGroupName": "default.redis3.2",
        "VpcId": "vpc-3820329f3",
        "CacheClusterId": "my-redis4",
        "SnapshotRetentionLimit": 7,
        "NumCacheNodes": 1,
        "SnapshotName": "my-snapshot-copy",
        "CacheClusterCreateTime": "2016-12-21T22:24:04.955Z",
        "AutoMinorVersionUpgrade": true,
        "PreferredAvailabilityZone": "us-east-1c",
        "SnapshotStatus": "creating",
        "SnapshotSource": "manual",
        "SnapshotWindow": "07:00-08:00",
        "EngineVersion": "3.2.4",
        "NodeSnapshots": [
            {
                "CacheSize": "3 MB",
                "SnapshotCreateTime": "2016-12-28T07:00:52Z",
                "CacheNodeId": "0001",
                "CacheNodeCreateTime": "2016-12-21T22:24:04.955Z"
            }
        ],
        "CacheSubnetGroupName": "default",
        "Port": 6379,
        "PreferredMaintenanceWindow": "tue:09:30-tue:10:30",
        "CacheNodeType": "cache.m3.large"
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[バックアップのエクスポート](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/backups-exporting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopySnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/copy-snapshot.html)」を参照してください。

### `create-cache-cluster`
<a name="elasticache_CreateCacheCluster_cli_2_topic"></a>

次のコード例は、`create-cache-cluster` を使用する方法を示しています。

**AWS CLI**  
**キャッシュクラスターを作成するには**  
次の `create-cache-cluster` の例では、Redis エンジンを使用してキャッシュクラスターを作成します。  

```
aws elasticache create-cache-cluster \
    --cache-cluster-id "cluster-test" \
    --engine redis \
    --cache-node-type cache.m5.large \
    --num-cache-nodes 1
```
出力:  

```
{
    "CacheCluster": {
        "CacheClusterId": "cluster-test",
        "ClientDownloadLandingPage": "https://console.aws.amazon.com/elasticache/home#client-download:",
        "CacheNodeType": "cache.m5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.5",
        "CacheClusterStatus": "creating",
        "NumCacheNodes": 1,
        "PreferredMaintenanceWindow": "sat:13:00-sat:14:00",
        "PendingModifiedValues": {},
        "CacheSecurityGroups": [],
        "CacheParameterGroup": {
            "CacheParameterGroupName": "default.redis5.0",
            "ParameterApplyStatus": "in-sync",
            "CacheNodeIdsToReboot": []
        },
        "CacheSubnetGroupName": "default",
        "AutoMinorVersionUpgrade": true,
        "SnapshotRetentionLimit": 0,
        "SnapshotWindow": "06:30-07:30",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[クラスターの作成](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.Create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCacheCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-cache-cluster.html)」を参照してください。

### `create-cache-parameter-group`
<a name="elasticache_CreateCacheParameterGroup_cli_2_topic"></a>

次のコード例は、`create-cache-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**キャッシュパラメータグループを作成するには**  
次の `create-cache-parameter-group` の例では、新しい Amazon ElastiCache キャッシュパラメータグループを作成します。  

```
aws elasticache create-cache-parameter-group \
    --cache-parameter-group-family "redis5.0" \
    --cache-parameter-group-name "mygroup" \
    --description "mygroup"
```
出力:  

```
{
    "CacheParameterGroup": {
        "CacheParameterGroupName": "mygroup",
        "CacheParameterGroupFamily": "redis5.0",
        "Description": "my group"
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[パラメータグループの作成](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/ParameterGroups.Creating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCacheParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-cache-parameter-group.html)」を参照してください。

### `create-cache-subnet-group`
<a name="elasticache_CreateCacheSubnetGroup_cli_2_topic"></a>

次のコード例は、`create-cache-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**キャッシュサブネットグループを作成するには**  
次の `create-cache-subnet-group` の例では、新しいキャッシュサブネットグループを作成します。  

```
aws elasticache create-cache-subnet-group \
    --cache-subnet-group-name "mygroup" \
    --cache-subnet-group-description "my subnet group" \
    --subnet-ids "subnet-xxxxec4f"
```
出力:  

```
{
    "CacheSubnetGroup": {
        "CacheSubnetGroupName": "mygroup",
        "CacheSubnetGroupDescription": "my subnet group",
        "VpcId": "vpc-a3e97cdb",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-xxxxec4f",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2d"
                }
            }
        ]
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[キャッシュサブネットグループの作成](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/VPCs.CreatingSubnetGroup.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCacheSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-cache-subnet-group.html)」を参照してください。

### `create-global-replication-group`
<a name="elasticache_CreateGlobalReplicationGroup_cli_2_topic"></a>

次のコード例は、`create-global-replication-group` を使用する方法を示しています。

**AWS CLI**  
**グローバルレプリケーショングループを作成するには**  
次の `create-global-replication-group` の例では、新しいグローバルレプリケーショングループを作成します。  

```
aws elasticache create-global-replication-group \
    --global-replication-group-id-suffix my-global-replication-group \
    --primary-replication-group-id my-primary-cluster
```
出力:  

```
{
    "GlobalReplicationGroup": {
        "GlobalReplicationGroupId": "sgaui-my-global-replication-group",
        "GlobalReplicationGroupDescription": " ",
        "Status": "creating",
        "CacheNodeType": "cache.r5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.6",
        "Members": [
            {
                "ReplicationGroupId": "my-primary-cluster",
                "ReplicationGroupRegion": "us-west-2",
                "Role": "PRIMARY",
                "AutomaticFailover": "enabled",
                "Status": "associating"
            }
        ],
        "ClusterEnabled": true,
        "GlobalNodeGroups": [
            {
                "GlobalNodeGroupId": "sgaui-my-global-replication-group-0001",
                "Slots": "0-16383"
            }
        ],
        "AuthTokenEnabled": false,
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、*Elasticache ユーザーガイド*の[「グローバルデータストアを使用した AWS リージョン間のレプリケーション](https://docs.amazonaws.cn/en_us/AmazonElastiCache/latest/red-ug/Redis-Global-Datastore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGlobalReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-global-replication-group.html)」を参照してください。

### `create-replication-group`
<a name="elasticache_CreateReplicationGroup_cli_2_topic"></a>

次のコード例は、`create-replication-group` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションサブネットグループを作成するには**  
次の `create-replication-group` の例では、Redis (クラスターモードが無効) または Redis (クラスターモードが有効) レプリケーショングループを作成します。このオペレーションは Redis でのみ有効です。  

```
aws elasticache create-replication-group \
    --replication-group-id "mygroup" \
    --replication-group-description "my group" \
    --engine "redis" \
    --cache-node-type "cache.m5.large"
```
出力:  

```
{
    "ReplicationGroup": {
        "ReplicationGroupId": "mygroup",
        "Description": "my group",
        "Status": "creating",
        "PendingModifiedValues": {},
        "MemberClusters": [
            "mygroup-001"
        ],
        "AutomaticFailover": "disabled",
        "SnapshotRetentionLimit": 0,
        "SnapshotWindow": "06:00-07:00",
        "ClusterEnabled": false,
        "CacheNodeType": "cache.m5.large",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Creating a Redis Replication Group](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Replication.CreatingRepGroup.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-replication-group.html)」を参照してください。

### `create-snapshot`
<a name="elasticache_CreateSnapshot_cli_2_topic"></a>

次のコード例は、`create-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットを作成するには**  
次の `create-snapshot` の例では、Redis エンジンを使用してスナップショットを作成します。  

```
aws elasticache create-snapshot \
    --snapshot-name mysnapshot \
    --cache-cluster-id cluster-test
```
出力:  

```
{
    "Snapshot": {
        "SnapshotName": "mysnapshot",
        "CacheClusterId": "cluster-test",
        "SnapshotStatus": "creating",
        "SnapshotSource": "manual",
        "CacheNodeType": "cache.m5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.5",
        "NumCacheNodes": 1,
        "PreferredAvailabilityZone": "us-west-2b",
        "CacheClusterCreateTime": "2020-03-19T03:12:01.483Z",
        "PreferredMaintenanceWindow": "sat:13:00-sat:14:00",
        "Port": 6379,
        "CacheParameterGroupName": "default.redis5.0",
        "CacheSubnetGroupName": "default",
        "VpcId": "vpc-a3e97cdb",
        "AutoMinorVersionUpgrade": true,
        "SnapshotRetentionLimit": 0,
        "SnapshotWindow": "06:30-07:30",
        "NodeSnapshots": [
            {
                "CacheNodeId": "0001",
                "CacheSize": "",
                "CacheNodeCreateTime": "2020-03-19T03:12:01.483Z"
            }
        ]
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Backup and Restore for ElastiCache for Redis](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/backups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-snapshot.html)」を参照してください。

### `create-user-group`
<a name="elasticache_CreateUserGroup_cli_2_topic"></a>

次のコード例は、`create-user-group` を使用する方法を示しています。

**AWS CLI**  
**ユーザーグループを作成するには**  
次の `create-user-group` の例では、新しいユーザーグループを作成します。  

```
aws elasticache create-user-group \
    --user-group-id myusergroup \
    --engine redis \
    --user-ids default
```
出力:  

```
{
    "UserGroupId": "myusergroup",
    "Status": "creating",
    "Engine": "redis",
    "UserIds": [
        "default"
    ],
    "ReplicationGroups": [],
    "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:usergroup:myusergroup"
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUserGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-user-group.html)」を参照してください。

### `create-user`
<a name="elasticache_CreateUser_cli_2_topic"></a>

次のコード例は、`create-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを作成するには**  
次の `create-user` の例では、新しいユーザーを作成します。  

```
aws elasticache create-user \
    --user-id user1 \
    --user-name myUser \
    --passwords mYnuUzrpAxXw2rdzx \
    --engine redis \
    --access-string "on ~app::* -@all +@read"
```
出力:  

```
{
    "UserId": "user2",
    "UserName": "myUser",
    "Status": "active",
    "Engine": "redis",
    "AccessString": "on ~app::* -@all +@read +@hash +@bitmap +@geo -setbit -bitfield -hset -hsetnx -hmset -hincrby -hincrbyfloat -hdel -bitop -geoadd -georadius -georadiusbymember",
    "UserGroupIds": [],
    "Authentication": {
        "Type": "password",
        "PasswordCount": 1
    },
    "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:user:user2"
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/create-user.html)」を参照してください。

### `decrease-node-groups-in-global-replication-group`
<a name="elasticache_DecreaseNodeGroupsInGlobalReplicationGroup_cli_2_topic"></a>

次のコード例は、`decrease-node-groups-in-global-replication-group` を使用する方法を示しています。

**AWS CLI**  
**グローバルレプリケーショングループ内のノードグループの数を減らすには**  
次の `decrease-node-groups-in-global-replication-group` は、Redis エンジンを使用してノードグループの数を減らします。  

```
aws elasticache decrease-node-groups-in-global-replication-group \
    --global-replication-group-id sgaui-test \
    --node-group-count 1 \
    --apply-immediately \
    --global-node-groups-to-retain sgaui-test-0003
```
出力:  

```
{
    "GlobalReplicationGroup":
    {
        "GlobalReplicationGroupId": "sgaui-test",
        "GlobalReplicationGroupDescription": "test",
        "Status": "modifying",
        "CacheNodeType": "cache.r5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.6",
        "Members": [
            {
                "ReplicationGroupId": "test-2",
                "ReplicationGroupRegion": "us-east-1",
                "Role": "SECONDARY",
                "AutomaticFailover": "enabled",
                "Status": "associated"
            },
            {
                "ReplicationGroupId": "test-1",
                "ReplicationGroupRegion": "us-west-2",
                "Role": "PRIMARY",
                "AutomaticFailover": "enabled",
                "Status": "associated"
            }
        ],
        "ClusterEnabled": true,
        "GlobalNodeGroups": [
            {
                "GlobalNodeGroupId": "sgaui-test-0001",
                "Slots": "0-449,1816-5461"
            },
            {
                "GlobalNodeGroupId": "sgaui-test-0002",
                "Slots": "6827-10922"
            },
            {
                "GlobalNodeGroupId": "sgaui-test-0003",
                "Slots": "10923-14052,15418-16383"
            },
            {
                "GlobalNodeGroupId": "sgaui-test-0004",
                "Slots": "450-1815,5462-6826,14053-15417"
            }
        ],
        "AuthTokenEnabled": false,
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、*Elasticache ユーザーガイド*の[「グローバルデータストアを使用した AWS リージョン間のレプリケーション](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Datastore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecreaseNodeGroupsInGlobalReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/decrease-node-groups-in-global-replication-group.html)」を参照してください。

### `decrease-replica-count`
<a name="elasticache_DecreaseReplicaCount_cli_2_topic"></a>

次のコード例は、`decrease-replica-count` を使用する方法を示しています。

**AWS CLI**  
**レプリカ数を減らすには**  
次の `decrease-replica-count` の例では、Redis (クラスターモード無効化) レプリケーショングループのレプリカ数、または Redis (クラスターモード有効化) レプリケーショングループの 1 つ以上のノードグループ (シャード) のレプリカノードの数を動的に減らします。このオペレーションは、クラスターのダウンタイムなしで実行されます。  

```
aws elasticache decrease-replica-count \
    --replication-group-id my-cluster \
    --apply-immediately  \
    --new-replica-count 2
```
出力:  

```
{
    "ReplicationGroup": {
        "ReplicationGroupId": "my-cluster",
        "Description": " ",
        "Status": "modifying",
        "PendingModifiedValues": {},
        "MemberClusters": [
            "myrepliace",
            "my-cluster-001",
            "my-cluster-002",
            "my-cluster-003"
        ],
        "NodeGroups": [
            {
                "NodeGroupId": "0001",
                "Status": "modifying",
                "PrimaryEndpoint": {
                    "Address": "my-cluster.xxxxx.ng.0001.usw2.cache.amazonaws.com",
                    "Port": 6379
                },
                "ReaderEndpoint": {
                    "Address": "my-cluster-ro.xxxxx.ng.0001.usw2.cache.amazonaws.com",
                    "Port": 6379
                },
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "myrepliace",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "myrepliace.xxxxx.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2a",
                        "CurrentRole": "replica"
                    },
                    {
                        "CacheClusterId": "my-cluster-001",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "my-cluster-001.xxxxx.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2a",
                        "CurrentRole": "primary"
                    },
                    {
                        "CacheClusterId": "my-cluster-002",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "my-cluster-002.xxxxx.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2a",
                        "CurrentRole": "replica"
                    },
                    {
                        "CacheClusterId": "my-cluster-003",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "my-cluster-003.xxxxx.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2a",
                        "CurrentRole": "replica"
                    }
                ]
            }
        ],
        "AutomaticFailover": "disabled",
        "SnapshotRetentionLimit": 0,
        "SnapshotWindow": "07:30-08:30",
        "ClusterEnabled": false,
        "CacheNodeType": "cache.r5.xlarge",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Changing the Number of Replicas](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/increase-decrease-replica-count.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecreaseReplicaCount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/decrease-replica-count.html)」を参照してください。

### `delete-cache-cluster`
<a name="elasticache_DeleteCacheCluster_cli_2_topic"></a>

次のコード例は、`delete-cache-cluster` を使用する方法を示しています。

**AWS CLI**  
**キャッシュクラスターを削除するには**  
次の `delete-cache-cluster` の例は、指定された以前にプロビジョニングされたクラスターを削除します。コマンドは、関連付けられたすべてのキャッシュノード、ノードエンドポイント、およびクラスター自体を削除します。このオペレーションから正常まレスポンスを受信すると、Amazon ElastiCache はただちにクラスターの削除を開始します。このオペレーションをキャンセルしたり、元に戻したりすることはできません。  
このオペレーションは、次には無効です。  
Redis (クラスターモードが有効) クラスター。レプリケーショングループの最後のリードレプリカであるクラスター。マルチ AZ モードが有効になっているノードグループ (シャード)。Redis (クラスターモードが有効) レプリケーショングループのクラスター。使用可能な状態ではないクラスター  

```
aws elasticache delete-cache-cluster \
    --cache-cluster-id "my-cluster-002"
```
出力:  

```
{
    "CacheCluster": {
        "CacheClusterId": "my-cluster-002",
        "ClientDownloadLandingPage": "https://console.aws.amazon.com/elasticache/home#client-download:",
        "CacheNodeType": "cache.r5.xlarge",
        "Engine": "redis",
        "EngineVersion": "5.0.5",
        "CacheClusterStatus": "deleting",
        "NumCacheNodes": 1,
        "PreferredAvailabilityZone": "us-west-2a",
        "CacheClusterCreateTime": "2019-11-26T03:35:04.546Z",
        "PreferredMaintenanceWindow": "mon:04:05-mon:05:05",
        "PendingModifiedValues": {},
        "NotificationConfiguration": {
            "TopicArn": "arn:aws:sns:us-west-x:xxxxxxx4152:My_Topic",
            "TopicStatus": "active"
        },
        "CacheSecurityGroups": [],
        "CacheParameterGroup": {
            "CacheParameterGroupName": "mygroup",
            "ParameterApplyStatus": "in-sync",
            "CacheNodeIdsToReboot": []
        },
        "CacheSubnetGroupName": "kxkxk",
        "AutoMinorVersionUpgrade": true,
        "SecurityGroups": [
            {
                "SecurityGroupId": "sg-xxxxxxxxxx9836",
                "Status": "active"
            },
            {
                "SecurityGroupId": "sg-xxxxxxxxxxxx7b",
                "Status": "active"
            }
        ],
        "ReplicationGroupId": "my-cluster",
        "SnapshotRetentionLimit": 0,
        "SnapshotWindow": "07:30-08:30",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Deleting a Cluster](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.Delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCacheCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-cache-cluster.html)」を参照してください。

### `delete-cache-parameter-group`
<a name="elasticache_DeleteCacheParameterGroup_cli_2_topic"></a>

次のコード例は、`delete-cache-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**キャッシュパラメータグループを削除するには**  
次の `delete-cache-parameter-group` の例では、指定されたキャッシュパラメータグループを削除します。キャッシュパラメータグループがキャッシュクラスターに関連付けられている場合は、そのキャッシュパラメータグループを削除できません。  

```
aws elasticache delete-cache-parameter-group \
    --cache-parameter-group-name myparamgroup
```
このコマンドでは何も出力されません。  
詳細については、「*ElastiCache ユーザーガイド*」の「[パラメータグループの削除](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/ParameterGroups.Deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCacheParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-cache-parameter-group.html)」を参照してください。

### `delete-cache-subnet-group`
<a name="elasticache_DeleteCacheSubnetGroup_cli_2_topic"></a>

次のコード例は、`delete-cache-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**キャッシュサブネットグループを削除するには**  
次の `delete-cache-subnet-group` の例では、指定されたキャッシュサブネットグループを削除します。キャッシュサブネットグループが何らかのクラスターに関連付けられている場合は、そのキャッシュサブネットグループを削除できません。  

```
aws elasticache delete-cache-subnet-group \
    --cache-subnet-group-name "mygroup"
```
このコマンドでは何も出力されません。  
詳細については、「*ElastiCache ユーザーガイド*」の「[Deleting a Subnet Group](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/SubnetGroups.Deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCacheSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-cache-subnet-group.html)」を参照してください。

### `delete-global-replication-group`
<a name="elasticache_DeleteGlobalReplicationGroup_cli_2_topic"></a>

次のコード例は、`delete-global-replication-group` を使用する方法を示しています。

**AWS CLI**  
**グローバルレプリケーショングループを削除するには**  
次の `delete-global-replication-group` の例では、新しいグローバルレプリケーショングループを削除します。  

```
aws elasticache delete-global-replication-group \
    --global-replication-group-id my-global-replication-group \
    --retain-primary-replication-group
```
出力:  

```
{
    "GlobalReplicationGroup": {
        "GlobalReplicationGroupId": "sgaui-my-grg",
        "GlobalReplicationGroupDescription": "my-grg",
        "Status": "deleting",
        "CacheNodeType": "cache.r5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.6",
        "Members": [
            {
                "ReplicationGroupId": "my-cluster-grg",
                "ReplicationGroupRegion": "us-west-2",
                "Role": "PRIMARY",
                "AutomaticFailover": "enabled",
                "Status": "associated"
            }
        ],
        "ClusterEnabled": false,
        "AuthTokenEnabled": false,
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、*Elasticache ユーザーガイド*の[「グローバルデータストアを使用した AWS リージョン間のレプリケーション](https://docs.amazonaws.cn/en_us/AmazonElastiCache/latest/red-ug/Redis-Global-Datastore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGlobalReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-global-replication-group.html)」を参照してください。

### `delete-replication-group`
<a name="elasticache_DeleteReplicationGroup_cli_2_topic"></a>

次のコード例は、`delete-replication-group` を使用する方法を示しています。

**AWS CLI**  
**レプリケーショングループを削除するには**  
次の `delete-replication-group` の例では、既存のレプリケーショングループを削除します。デフォルトでは、このオペレーションはプライマリ/プライマリとすべてのリードレプリカを含むレプリケーショングループ全体を削除します。レプリケーショングループにプライマリが 1 つしかない場合は、オプションでリードレプリカのみを削除し、RetainPrimaryCluster=true を設定してプライマリを保持できます。  
このオペレーションから正常まレスポンスを受信すると、Amazon ElastiCache はただちに選択したリソースの削除を開始します。このオペレーションをキャンセルしたり、元に戻したりすることはできません。Redis にのみ有効です。  

```
aws elasticache delete-replication-group \
    --replication-group-id "mygroup"
```
出力:  

```
{
     "ReplicationGroup": {
         "ReplicationGroupId": "mygroup",
         "Description": "my group",
         "Status": "deleting",
         "PendingModifiedValues": {},
         "AutomaticFailover": "disabled",
         "SnapshotRetentionLimit": 0,
         "SnapshotWindow": "06:00-07:00",
         "TransitEncryptionEnabled": false,
         "AtRestEncryptionEnabled": false
     }
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-replication-group.html)」を参照してください。

### `delete-snapshot`
<a name="elasticache_DeleteSnapshot_cli_2_topic"></a>

次のコード例は、`delete-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットを削除するには**  
次の `delete-snapshot` の例では、Redis エンジンを使用してスナップショットを削除しました。  

```
aws elasticache delete-snapshot \
    --snapshot-name mysnapshot
```
出力:  

```
{
    "Snapshot": {
        "SnapshotName": "my-cluster-snapshot",
        "ReplicationGroupId": "mycluster",
        "ReplicationGroupDescription": "mycluster",
        "SnapshotStatus": "deleting",
        "SnapshotSource": "manual",
        "CacheNodeType": "cache.r5.xlarge",
        "Engine": "redis",
        "EngineVersion": "5.0.5",
        "PreferredMaintenanceWindow": "thu:12:00-thu:13:00",
        "TopicArn": "arn:aws:sns:us-west-2:xxxxxxxxxxxxx152:My_Topic",
        "Port": 6379,
        "CacheParameterGroupName": "default.redis5.0.cluster.on",
        "CacheSubnetGroupName": "default",
        "VpcId": "vpc-a3e97cdb",
        "AutoMinorVersionUpgrade": true,
        "SnapshotRetentionLimit": 1,
        "SnapshotWindow": "13:00-14:00",
        "NumNodeGroups": 4,
        "AutomaticFailover": "enabled",
        "NodeSnapshots": [
            {
                "CacheClusterId": "mycluster-0002-003",
                "NodeGroupId": "0002",
                "CacheNodeId": "0001",
                "CacheSize": "6 MB",
                "CacheNodeCreateTime": "2020-06-18T00:05:44.719000+00:00",
                "SnapshotCreateTime": "2020-06-25T20:34:30+00:00"
            },
            {
                "CacheClusterId": "mycluster-0003-003",
                "NodeGroupId": "0003",
                "CacheNodeId": "0001",
                "CacheSize": "6 MB",
                "CacheNodeCreateTime": "2019-12-05T19:13:15.912000+00:00",
                "SnapshotCreateTime": "2020-06-25T20:34:30+00:00"
            },
            {
                "CacheClusterId": "mycluster-0004-002",
                "NodeGroupId": "0004",
                "CacheNodeId": "0001",
                "CacheSize": "6 MB",
                "CacheNodeCreateTime": "2019-12-09T19:44:34.324000+00:00",
                "SnapshotCreateTime": "2020-06-25T20:34:30+00:00"
            },
            {
                "CacheClusterId": "mycluster-0005-003",
                "NodeGroupId": "0005",
                "CacheNodeId": "0001",
                "CacheSize": "6 MB",
                "CacheNodeCreateTime": "2020-06-18T00:05:44.775000+00:00",
                "SnapshotCreateTime": "2020-06-25T20:34:30+00:00"
            }
        ]
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Backup and Restore for ElastiCache for Redis](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/backups.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-snapshot.html)」を参照してください。

### `delete-user-group`
<a name="elasticache_DeleteUserGroup_cli_2_topic"></a>

次のコード例は、`delete-user-group` を使用する方法を示しています。

**AWS CLI**  
**ユーザーグループを削除するには**  
次の `delete-user-group` の例では、ユーザーグループを削除します。  

```
aws elasticache delete-user-group \
    --user-group-id myusergroup
```
出力:  

```
{
    "UserGroupId": "myusergroup",
    "Status": "deleting",
    "Engine": "redis",
    "UserIds": [
        "default"
    ],
    "ReplicationGroups": [],
    "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:usergroup:myusergroup"
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUserGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-user-group.html)」を参照してください。

### `delete-user`
<a name="elasticache_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
次の `delete-user` の例では、ユーザーを削除します。  

```
aws elasticache delete-user \
    --user-id user2
```
出力:  

```
{
    "UserId": "user1",
    "UserName": "myUser",
    "Status": "deleting",
    "Engine": "redis",
    "AccessString": "on ~* +@all",
    "UserGroupIds": [
        "myusergroup"
    ],
    "Authentication": {
        "Type": "password",
        "PasswordCount": 1
    },
    "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:user:user1"
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/delete-user.html)」を参照してください。

### `describe-cache-clusters`
<a name="elasticache_DescribeCacheClusters_cli_2_topic"></a>

次のコード例は、`describe-cache-clusters` を使用する方法を示しています。

**AWS CLI**  
**キャッシュクラスターを記述するには**  
次の `describe-cache-clusters` の例は、キャッシュクラスターを表しています。  

```
aws elasticache describe-cache-clusters
```
出力:  

```
{
    "CacheClusters": [
    {
            "CacheClusterId": "my-cluster-003",
            "ClientDownloadLandingPage": "https://console.aws.amazon.com/elasticache/home#client-download:",
            "CacheNodeType": "cache.r5.large",
            "Engine": "redis",
            "EngineVersion": "5.0.5",
            "CacheClusterStatus": "available",
            "NumCacheNodes": 1,
            "PreferredAvailabilityZone": "us-west-2a",
            "CacheClusterCreateTime": "2019-11-26T01:22:52.396Z",
            "PreferredMaintenanceWindow": "mon:17:30-mon:18:30",
            "PendingModifiedValues": {},
            "NotificationConfiguration": {
                "TopicArn": "arn:aws:sns:us-west-2:xxxxxxxxxxx152:My_Topic",
                "TopicStatus": "active"
            },
            "CacheSecurityGroups": [],
            "CacheParameterGroup": {
                "CacheParameterGroupName": "default.redis5.0",
                "ParameterApplyStatus": "in-sync",
                "CacheNodeIdsToReboot": []
            },
            "CacheSubnetGroupName": "kxkxk",
            "AutoMinorVersionUpgrade": true,
            "SecurityGroups": [
                {
                    "SecurityGroupId": "sg-xxxxxd7b",
                    "Status": "active"
                }
            ],
            "ReplicationGroupId": "my-cluster",
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "06:30-07:30",
            "AuthTokenEnabled": false,
            "TransitEncryptionEnabled": false,
            "AtRestEncryptionEnabled": false,
            "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxxx152:cluster:my-cache-cluster",
            "ReplicationGroupLogDeliveryEnabled": false,
            "LogDeliveryConfigurations": [
                {
                    "LogType": "slow-log",
                    "DestinationType": "cloudwatch-logs",
                    "DestinationDetails": {
                        "CloudWatchLogsDetails": {
                            "LogGroup": "test-log"
                        }
                    },
                    "LogFormat": "text",
                    "Status": "active"
                }
            ]
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Managing Clusters](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCacheClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-cache-clusters.html)」を参照してください。

### `describe-cache-engine-versions`
<a name="elasticache_DescribeCacheEngineVersions_cli_2_topic"></a>

次のコード例は、`describe-cache-engine-versions` を使用する方法を示しています。

**AWS CLI**  
**キャッシュエンジンのバージョンを記述するには**  
次の `describe-cache-engine-versions` の例では、使用可能なキャッシュエンジンとそのバージョンのリストを返します。  

```
aws elasticache describe-cache-engine-versions \
    --engine "Redis"
```
出力:  

```
{
    "CacheEngineVersions": [
        {
            "Engine": "redis",
            "EngineVersion": "2.6.13",
            "CacheParameterGroupFamily": "redis2.6",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 2.6.13"
        },
        {
            "Engine": "redis",
            "EngineVersion": "2.8.19",
            "CacheParameterGroupFamily": "redis2.8",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 2.8.19"
        },
        {
            "Engine": "redis",
            "EngineVersion": "2.8.21",
            "CacheParameterGroupFamily": "redis2.8",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 2.8.21"
        },
        {
            "Engine": "redis",
            "EngineVersion": "2.8.22",
            "CacheParameterGroupFamily": "redis2.8",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 2.8.22"
        },
        {
            "Engine": "redis",
            "EngineVersion": "2.8.23",
            "CacheParameterGroupFamily": "redis2.8",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 2.8.23"
        },
        {
            "Engine": "redis",
            "EngineVersion": "2.8.24",
            "CacheParameterGroupFamily": "redis2.8",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 2.8.24"
        },
        {
            "Engine": "redis",
            "EngineVersion": "2.8.6",
            "CacheParameterGroupFamily": "redis2.8",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 2.8.6"
        },
        {
            "Engine": "redis",
            "EngineVersion": "3.2.10",
            "CacheParameterGroupFamily": "redis3.2",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 3.2.10"
        },
        {
            "Engine": "redis",
            "EngineVersion": "3.2.4",
            "CacheParameterGroupFamily": "redis3.2",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 3.2.4"
        },
        {
            "Engine": "redis",
            "EngineVersion": "3.2.6",
            "CacheParameterGroupFamily": "redis3.2",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 3.2.6"
        },
        {
            "Engine": "redis",
            "EngineVersion": "4.0.10",
            "CacheParameterGroupFamily": "redis4.0",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 4.0.10"
        },
        {
            "Engine": "redis",
            "EngineVersion": "5.0.0",
            "CacheParameterGroupFamily": "redis5.0",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 5.0.0"
        },
        {
            "Engine": "redis",
            "EngineVersion": "5.0.3",
            "CacheParameterGroupFamily": "redis5.0",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 5.0.3"
        },
        {
            "Engine": "redis",
            "EngineVersion": "5.0.4",
            "CacheParameterGroupFamily": "redis5.0",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 5.0.4"
        },
        {
            "Engine": "redis",
            "EngineVersion": "5.0.5",
            "CacheParameterGroupFamily": "redis5.0",
            "CacheEngineDescription": "Redis",
            "CacheEngineVersionDescription": "redis version 5.0.5"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCacheEngineVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-cache-engine-versions.html)」を参照してください。

### `describe-cache-parameter-groups`
<a name="elasticache_DescribeCacheParameterGroups_cli_2_topic"></a>

次のコード例は、`describe-cache-parameter-groups` を使用する方法を示しています。

**AWS CLI**  
**キャッシュパラメータグループを記述するには**  
次の `describe-cache-parameter-groups` の例では、キャッシュパラメータグループの記述のリストを返します。  

```
aws elasticache describe-cache-parameter-groups \
    --cache-parameter-group-name "mygroup"
```
出力:  

```
{
    "CacheParameterGroups": [
        {
            "CacheParameterGroupName": "mygroup",
            "CacheParameterGroupFamily": "redis5.0",
            "Description": " "
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Configuring Engine Parameters Using Parameter Groups](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/ParameterGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCacheParameterGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-cache-parameter-groups.html)」を参照してください。

### `describe-cache-parameters`
<a name="elasticache_DescribeCacheParameters_cli_2_topic"></a>

次のコード例は、`describe-cache-parameters` を使用する方法を示しています。

**AWS CLI**  
**キャッシュパラメータを記述するには**  
次の「describe-cache-parameters」の例は、特定のキャッシュパラメータグループの詳細なパラメータリストを返します。  

```
aws elasticache describe-cache-parameters \
    --cache-parameter-group-name "myparamgroup"
```
出力:  

```
{
    "Parameters": [
        {
            "ParameterName": "activedefrag",
            "ParameterValue": "yes",
            "Description": "Enabled active memory defragmentation",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "active-defrag-cycle-max",
            "ParameterValue": "75",
            "Description": "Maximal effort for defrag in CPU percentage",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-75",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "active-defrag-cycle-min",
            "ParameterValue": "5",
            "Description": "Minimal effort for defrag in CPU percentage",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-75",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "active-defrag-ignore-bytes",
            "ParameterValue": "104857600",
            "Description": "Minimum amount of fragmentation waste to start active defrag",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1048576-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "active-defrag-max-scan-fields",
            "ParameterValue": "1000",
            "Description": "Maximum number of set/hash/zset/list fields that will be processed from the main dictionary scan",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-1000000",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "active-defrag-threshold-lower",
            "ParameterValue": "10",
            "Description": "Minimum percentage of fragmentation to start active defrag",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-100",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "active-defrag-threshold-upper",
            "ParameterValue": "100",
            "Description": "Maximum percentage of fragmentation at which we use maximum effort",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-100",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "activerehashing",
            "ParameterValue": "yes",
            "Description": "Apply rehashing or not.",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "requires-reboot"
        },
        {
            "ParameterName": "appendfsync",
            "ParameterValue": "everysec",
            "Description": "fsync policy for AOF persistence",
            "Source": "system",
            "DataType": "string",
            "AllowedValues": "always,everysec,no",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "appendonly",
            "ParameterValue": "no",
            "Description": "Enable Redis persistence.",
            "Source": "system",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-output-buffer-limit-normal-hard-limit",
            "ParameterValue": "0",
            "Description": "Normal client output buffer hard limit in bytes.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-output-buffer-limit-normal-soft-limit",
            "ParameterValue": "0",
            "Description": "Normal client output buffer soft limit in bytes.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-output-buffer-limit-normal-soft-seconds",
            "ParameterValue": "0",
            "Description": "Normal client output buffer soft limit in seconds.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-output-buffer-limit-pubsub-hard-limit",
            "ParameterValue": "33554432",
            "Description": "Pubsub client output buffer hard limit in bytes.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-output-buffer-limit-pubsub-soft-limit",
            "ParameterValue": "8388608",
            "Description": "Pubsub client output buffer soft limit in bytes.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-output-buffer-limit-pubsub-soft-seconds",
            "ParameterValue": "60",
            "Description": "Pubsub client output buffer soft limit in seconds.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-output-buffer-limit-replica-soft-seconds",
            "ParameterValue": "60",
            "Description": "Replica client output buffer soft limit in seconds.",
            "Source": "system",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "client-query-buffer-limit",
            "ParameterValue": "1073741824",
            "Description": "Max size of a single client query buffer",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1048576-1073741824",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "close-on-replica-write",
            "ParameterValue": "yes",
            "Description": "If enabled, clients who attempt to write to a read-only replica will be disconnected. Applicable to 2.8.23 and higher.",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "cluster-enabled",
            "ParameterValue": "no",
            "Description": "Enable cluster mode",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "requires-reboot"
        },
        {
            "ParameterName": "cluster-require-full-coverage",
            "ParameterValue": "no",
            "Description": "Whether cluster becomes unavailable if one or more slots are not covered",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "databases",
            "ParameterValue": "16",
            "Description": "Set the number of databases.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-1200000",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "requires-reboot"
        },
        {
            "ParameterName": "hash-max-ziplist-entries",
            "ParameterValue": "512",
            "Description": "The maximum number of hash entries in order for the dataset to be compressed.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "hash-max-ziplist-value",
            "ParameterValue": "64",
            "Description": "The threshold of biggest hash entries in order for the dataset to be compressed.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "hll-sparse-max-bytes",
            "ParameterValue": "3000",
            "Description": "HyperLogLog sparse representation bytes limit",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-16000",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "lazyfree-lazy-eviction",
            "ParameterValue": "no",
            "Description": "Perform an asynchronous delete on evictions",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "lazyfree-lazy-expire",
            "ParameterValue": "no",
            "Description": "Perform an asynchronous delete on expired keys",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "lazyfree-lazy-server-del",
            "ParameterValue": "no",
            "Description": "Perform an asynchronous delete on key updates",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "lfu-decay-time",
            "ParameterValue": "1",
            "Description": "The amount of time in minutes to decrement the key counter for LFU eviction policy",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "lfu-log-factor",
            "ParameterValue": "10",
            "Description": "The log factor for incrementing key counter for LFU eviction policy",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "list-compress-depth",
            "ParameterValue": "0",
            "Description": "Number of quicklist ziplist nodes from each side of the list to exclude from compression. The head and tail of the list are always uncompressed for fast push/pop operations",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "list-max-ziplist-size",
            "ParameterValue": "-2",
            "Description": "The number of entries allowed per internal list node can be specified as a fixed maximum size or a maximum number of elements",
            "Source": "system",
            "DataType": "integer",
            "AllowedValues": "-5,-4,-3,-2,-1,1-",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "lua-replicate-commands",
            "ParameterValue": "yes",
            "Description": "Always enable Lua effect replication or not",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "lua-time-limit",
            "ParameterValue": "5000",
            "Description": "Max execution time of a Lua script in milliseconds. 0 for unlimited execution without warnings.",
            "Source": "system",
            "DataType": "integer",
            "AllowedValues": "5000",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "maxclients",
            "ParameterValue": "65000",
            "Description": "The maximum number of Redis clients.",
            "Source": "system",
            "DataType": "integer",
            "AllowedValues": "1-65000",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "requires-reboot"
        },
        {
            "ParameterName": "maxmemory-policy",
            "ParameterValue": "volatile-lru",
            "Description": "Max memory policy.",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "volatile-lru,allkeys-lru,volatile-lfu,allkeys-lfu,volatile-random,allkeys-random,volatile-ttl,noeviction",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "maxmemory-samples",
            "ParameterValue": "3",
            "Description": "Max memory samples.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "min-replicas-max-lag",
            "ParameterValue": "10",
            "Description": "The maximum amount of replica lag in seconds beyond which the master would stop taking writes. A value of 0 means the master always takes writes.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "min-replicas-to-write",
            "ParameterValue": "0",
            "Description": "The minimum number of replicas that must be present with lag no greater than min-replicas-max-lag for master to take writes. Setting this to 0 means the master always takes writes.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "notify-keyspace-events",
            "Description": "The keyspace events for Redis to notify Pub/Sub clients about. By default all notifications are disabled",
            "Source": "user",
            "DataType": "string",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "proto-max-bulk-len",
            "ParameterValue": "536870912",
            "Description": "Max size of a single element request",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "1048576-536870912",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "rename-commands",
            "ParameterValue": "",
            "Description": "Redis commands that can be dynamically renamed by the customer",
            "Source": "user",
            "DataType": "string",
            "AllowedValues": "APPEND,BITCOUNT,BITFIELD,BITOP,BITPOS,BLPOP,BRPOP,BRPOPLPUSH,BZPOPMIN,BZPOPMAX,CLIENT,COMMAND,DBSIZE,DECR,DECRBY,DEL,DISCARD,DUMP,ECHO,EVAL,EVALSHA,EXEC,EXISTS,EXPIRE,EXPIREAT,FLUSHALL,FLUSHDB,GEOADD,GEOHASH,GEOPOS,GEODIST,GEORADIUS,GEORADIUSBYMEMBER,GET,GETBIT,GETRANGE,GETSET,HDEL,HEXISTS,HGET,HGETALL,HINCRBY,HINCRBYFLOAT,HKEYS,HLEN,HMGET,HMSET,HSET,HSETNX,HSTRLEN,HVALS,INCR,INCRBY,INCRBYFLOAT,INFO,KEYS,LASTSAVE,LINDEX,LINSERT,LLEN,LPOP,LPUSH,LPUSHX,LRANGE,LREM,LSET,LTRIM,MEMORY,MGET,MONITOR,MOVE,MSET,MSETNX,MULTI,OBJECT,PERSIST,PEXPIRE,PEXPIREAT,PFADD,PFCOUNT,PFMERGE,PING,PSETEX,PSUBSCRIBE,PUBSUB,PTTL,PUBLISH,PUNSUBSCRIBE,RANDOMKEY,READONLY,READWRITE,RENAME,RENAMENX,RESTORE,ROLE,RPOP,RPOPLPUSH,RPUSH,RPUSHX,SADD,SCARD,SCRIPT,SDIFF,SDIFFSTORE,SELECT,SET,SETBIT,SETEX,SETNX,SETRANGE,SINTER,SINTERSTORE,SISMEMBER,SLOWLOG,SMEMBERS,SMOVE,SORT,SPOP,SRANDMEMBER,SREM,STRLEN,SUBSCRIBE,SUNION,SUNIONSTORE,SWAPDB,TIME,TOUCH,TTL,TYPE,UNSUBSCRIBE,UNLINK,UNWATCH,WAIT,WATCH,ZADD,ZCARD,ZCOUNT,ZINCRBY,ZINTERSTORE,ZLEXCOUNT,ZPOPMAX,ZPOPMIN,ZRANGE,ZRANGEBYLEX,ZREVRANGEBYLEX,ZRANGEBYSCORE,ZRANK,ZREM,ZREMRANGEBYLEX,ZREMRANGEBYRANK,ZREMRANGEBYSCORE,ZREVRANGE,ZREVRANGEBYSCORE,ZREVRANK,ZSCORE,ZUNIONSTORE,SCAN,SSCAN,HSCAN,ZSCAN,XINFO,XADD,XTRIM,XDEL,XRANGE,XREVRANGE,XLEN,XREAD,XGROUP,XREADGROUP,XACK,XCLAIM,XPENDING,GEORADIUS_RO,GEORADIUSBYMEMBER_RO,LOLWUT,XSETID,SUBSTR",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.3",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "repl-backlog-size",
            "ParameterValue": "1048576",
            "Description": "The replication backlog size in bytes for PSYNC. This is the size of the buffer which accumulates slave data when slave is disconnected for some time, so that when slave reconnects again, only transfer the portion of data which the slave missed. Minimum value is 16K.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "16384-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "repl-backlog-ttl",
            "ParameterValue": "3600",
            "Description": "The amount of time in seconds after the master no longer have any slaves connected for the master to free the replication backlog. A value of 0 means to never release the backlog.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "replica-allow-chaining",
            "ParameterValue": "no",
            "Description": "Configures if chaining of replicas is allowed",
            "Source": "system",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "replica-ignore-maxmemory",
            "ParameterValue": "yes",
            "Description": "Determines if replica ignores maxmemory setting by not evicting items independent from the master",
            "Source": "system",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "replica-lazy-flush",
            "ParameterValue": "no",
            "Description": "Perform an asynchronous flushDB during replica sync",
            "Source": "system",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "IsModifiable": false,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "reserved-memory-percent",
            "ParameterValue": "25",
            "Description": "The percent of memory reserved for non-cache memory usage. You may want to increase this parameter for nodes with read replicas, AOF enabled, etc, to reduce swap usage.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-100",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "set-max-intset-entries",
            "ParameterValue": "512",
            "Description": "The limit in the size of the set in order for the dataset to be compressed.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "slowlog-log-slower-than",
            "ParameterValue": "10000",
            "Description": "The execution time, in microseconds, to exceed in order for the command to get logged. Note that a negative number disables the slow log, while a value of zero forces the logging of every command.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "slowlog-max-len",
            "ParameterValue": "128",
            "Description": "The length of the slow log. There is no limit to this length. Just be aware that it will consume memory. You can reclaim memory used by the slow log with SLOWLOG RESET.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "stream-node-max-bytes",
            "ParameterValue": "4096",
            "Description": "The maximum size of a single node in a stream in bytes",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "stream-node-max-entries",
            "ParameterValue": "100",
            "Description": "The maximum number of items a single node in a stream can contain",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "tcp-keepalive",
            "ParameterValue": "300",
            "Description": "If non-zero, send ACKs every given number of seconds.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "timeout",
            "ParameterValue": "0",
            "Description": "Close connection if client is idle for a given number of seconds, or never if 0.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0,20-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "zset-max-ziplist-entries",
            "ParameterValue": "128",
            "Description": "The maximum number of sorted set entries in order for the dataset to be compressed.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        },
        {
            "ParameterName": "zset-max-ziplist-value",
            "ParameterValue": "64",
            "Description": "The threshold of biggest sorted set entries in order for the dataset to be compressed.",
            "Source": "user",
            "DataType": "integer",
            "AllowedValues": "0-",
            "IsModifiable": true,
            "MinimumEngineVersion": "5.0.0",
            "ChangeType": "immediate"
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Parameter Management](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/ParameterGroups.Management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCacheParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-cache-parameters.html)」を参照してください。

### `describe-cache-subnet-groups`
<a name="elasticache_DescribeCacheSubnetGroups_cli_2_topic"></a>

次のコード例は、`describe-cache-subnet-groups` を使用する方法を示しています。

**AWS CLI**  
**キャッシュサブネットグループを記述するには**  
次の `describe-cache-subnet-groups` の例では、サブネットグループのリストを返します。  

```
aws elasticache describe-cache-subnet-groups
```
出力:  

```
{
    "CacheSubnetGroups": [
        {
            "CacheSubnetGroupName": "default",
            "CacheSubnetGroupDescription": "Default CacheSubnetGroup",
            "VpcId": "vpc-a3e97cdb",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-8d4bacf5",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2b"
                    }
                },
                {
                    "SubnetIdentifier": "subnet-dde21380",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2c"
                    }
                },
                {
                    "SubnetIdentifier": "subnet-6485ec4f",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2d"
                    }
                },
                {
                    "SubnetIdentifier": "subnet-b4ebebff",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    }
                }
            ]
        },
        {
            "CacheSubnetGroupName": "kxkxk",
            "CacheSubnetGroupDescription": "mygroup",
            "VpcId": "vpc-a3e97cdb",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-b4ebebff",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    }
                }
            ]
        },
        {
            "CacheSubnetGroupName": "test",
            "CacheSubnetGroupDescription": "test",
            "VpcId": "vpc-a3e97cdb",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-b4ebebff",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    }
                }
            ]
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Subnets and Subnet Groups](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/SubnetGroups.html)」または「*ElastiCache for Memcached ユーザーガイド*」の「[Subnets and Subnet Groups](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/SubnetGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCacheSubnetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-cache-subnet-groups.html)」を参照してください。

### `describe-engine-default-parameters`
<a name="elasticache_DescribeEngineDefaultParameters_cli_2_topic"></a>

次のコード例は、`describe-engine-default-parameters` を使用する方法を示しています。

**AWS CLI**  
**エンジンのデフォルトパラメータを記述するには**  
次の `describe-engine-default-parameters` の例では、指定されたキャッシュエンジンのデフォルトのエンジンおよびシステムパラメータ情報を返します。  

```
aws elasticache describe-engine-default-parameters \
    --cache-parameter-group-family "redis5.0"
```
出力:  

```
{
    "EngineDefaults": {
        "Parameters": [
            {
                "ParameterName": "activedefrag",
                "ParameterValue": "no",
                "Description": "Enabled active memory defragmentation",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "active-defrag-cycle-max",
                "ParameterValue": "75",
                "Description": "Maximal effort for defrag in CPU percentage",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-75",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "active-defrag-cycle-min",
                "ParameterValue": "5",
                "Description": "Minimal effort for defrag in CPU percentage",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-75",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "active-defrag-ignore-bytes",
                "ParameterValue": "104857600",
                "Description": "Minimum amount of fragmentation waste to start active defrag",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1048576-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "active-defrag-max-scan-fields",
                "ParameterValue": "1000",
                "Description": "Maximum number of set/hash/zset/list fields that will be processed from the main dictionary scan",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-1000000",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "active-defrag-threshold-lower",
                "ParameterValue": "10",
                "Description": "Minimum percentage of fragmentation to start active defrag",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-100",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "active-defrag-threshold-upper",
                "ParameterValue": "100",
                "Description": "Maximum percentage of fragmentation at which we use maximum effort",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-100",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "activerehashing",
                "ParameterValue": "yes",
                "Description": "Apply rehashing or not.",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "requires-reboot"
            },
            {
                "ParameterName": "appendfsync",
                "ParameterValue": "everysec",
                "Description": "fsync policy for AOF persistence",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "always,everysec,no",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "appendonly",
                "ParameterValue": "no",
                "Description": "Enable Redis persistence.",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-output-buffer-limit-normal-hard-limit",
                "ParameterValue": "0",
                "Description": "Normal client output buffer hard limit in bytes.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-output-buffer-limit-normal-soft-limit",
                "ParameterValue": "0",
                "Description": "Normal client output buffer soft limit in bytes.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-output-buffer-limit-normal-soft-seconds",
                "ParameterValue": "0",
                "Description": "Normal client output buffer soft limit in seconds.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-output-buffer-limit-pubsub-hard-limit",
                "ParameterValue": "33554432",
                "Description": "Pubsub client output buffer hard limit in bytes.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-output-buffer-limit-pubsub-soft-limit",
                "ParameterValue": "8388608",
                "Description": "Pubsub client output buffer soft limit in bytes.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-output-buffer-limit-pubsub-soft-seconds",
                "ParameterValue": "60",
                "Description": "Pubsub client output buffer soft limit in seconds.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-output-buffer-limit-replica-soft-seconds",
                "ParameterValue": "60",
                "Description": "Replica client output buffer soft limit in seconds.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "client-query-buffer-limit",
                "ParameterValue": "1073741824",
                "Description": "Max size of a single client query buffer",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1048576-1073741824",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "close-on-replica-write",
                "ParameterValue": "yes",
                "Description": "If enabled, clients who attempt to write to a read-only replica will be disconnected. Applicable to 2.8.23 and higher.",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "cluster-enabled",
                "ParameterValue": "no",
                "Description": "Enable cluster mode",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "requires-reboot"
            },
            {
                "ParameterName": "cluster-require-full-coverage",
                "ParameterValue": "no",
                "Description": "Whether cluster becomes unavailable if one or more slots are not covered",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "databases",
                "ParameterValue": "16",
                "Description": "Set the number of databases.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-1200000",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "requires-reboot"
            },
            {
                "ParameterName": "hash-max-ziplist-entries",
                "ParameterValue": "512",
                "Description": "The maximum number of hash entries in order for the dataset to be compressed.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "hash-max-ziplist-value",
                "ParameterValue": "64",
                "Description": "The threshold of biggest hash entries in order for the dataset to be compressed.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "hll-sparse-max-bytes",
                "ParameterValue": "3000",
                "Description": "HyperLogLog sparse representation bytes limit",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-16000",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "lazyfree-lazy-eviction",
                "ParameterValue": "no",
                "Description": "Perform an asynchronous delete on evictions",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "lazyfree-lazy-expire",
                "ParameterValue": "no",
                "Description": "Perform an asynchronous delete on expired keys",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "lazyfree-lazy-server-del",
                "ParameterValue": "no",
                "Description": "Perform an asynchronous delete on key updates",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "lfu-decay-time",
                "ParameterValue": "1",
                "Description": "The amount of time in minutes to decrement the key counter for LFU eviction policy",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "lfu-log-factor",
                "ParameterValue": "10",
                "Description": "The log factor for incrementing key counter for LFU eviction policy",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "list-compress-depth",
                "ParameterValue": "0",
                "Description": "Number of quicklist ziplist nodes from each side of the list to exclude from compression. The head and tail of the list are always uncompressed for fast push/pop operations",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "list-max-ziplist-size",
                "ParameterValue": "-2",
                "Description": "The number of entries allowed per internal list node can be specified as a fixed maximum size or a maximum number of elements",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "-5,-4,-3,-2,-1,1-",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "lua-replicate-commands",
                "ParameterValue": "yes",
                "Description": "Always enable Lua effect replication or not",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "lua-time-limit",
                "ParameterValue": "5000",
                "Description": "Max execution time of a Lua script in milliseconds. 0 for unlimited execution without warnings.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "5000",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "maxclients",
                "ParameterValue": "65000",
                "Description": "The maximum number of Redis clients.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-65000",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "requires-reboot"
            },
            {
                "ParameterName": "maxmemory-policy",
                "ParameterValue": "volatile-lru",
                "Description": "Max memory policy.",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "volatile-lru,allkeys-lru,volatile-lfu,allkeys-lfu,volatile-random,allkeys-random,volatile-ttl,noeviction",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "maxmemory-samples",
                "ParameterValue": "3",
                "Description": "Max memory samples.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "min-replicas-max-lag",
                "ParameterValue": "10",
                "Description": "The maximum amount of replica lag in seconds beyond which the master would stop taking writes. A value of 0 means the master always takes writes.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "min-replicas-to-write",
                "ParameterValue": "0",
                "Description": "The minimum number of replicas that must be present with lag no greater than min-replicas-max-lag for master to take writes. Setting this to 0 means the master always takes writes.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "notify-keyspace-events",
                "Description": "The keyspace events for Redis to notify Pub/Sub clients about. By default all notifications are disabled",
                "Source": "system",
                "DataType": "string",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "proto-max-bulk-len",
                "ParameterValue": "536870912",
                "Description": "Max size of a single element request",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "1048576-536870912",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "rename-commands",
                "ParameterValue": "",
                "Description": "Redis commands that can be dynamically renamed by the customer",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "APPEND,BITCOUNT,BITFIELD,BITOP,BITPOS,BLPOP,BRPOP,BRPOPLPUSH,BZPOPMIN,BZPOPMAX,CLIENT,COMMAND,DBSIZE,DECR,DECRBY,DEL,DISCARD,DUMP,ECHO,EVAL,EVALSHA,EXEC,EXISTS,EXPIRE,EXPIREAT,FLUSHALL,FLUSHDB,GEOADD,GEOHASH,GEOPOS,GEODIST,GEORADIUS,GEORADIUSBYMEMBER,GET,GETBIT,GETRANGE,GETSET,HDEL,HEXISTS,HGET,HGETALL,HINCRBY,HINCRBYFLOAT,HKEYS,HLEN,HMGET,HMSET,HSET,HSETNX,HSTRLEN,HVALS,INCR,INCRBY,INCRBYFLOAT,INFO,KEYS,LASTSAVE,LINDEX,LINSERT,LLEN,LPOP,LPUSH,LPUSHX,LRANGE,LREM,LSET,LTRIM,MEMORY,MGET,MONITOR,MOVE,MSET,MSETNX,MULTI,OBJECT,PERSIST,PEXPIRE,PEXPIREAT,PFADD,PFCOUNT,PFMERGE,PING,PSETEX,PSUBSCRIBE,PUBSUB,PTTL,PUBLISH,PUNSUBSCRIBE,RANDOMKEY,READONLY,READWRITE,RENAME,RENAMENX,RESTORE,ROLE,RPOP,RPOPLPUSH,RPUSH,RPUSHX,SADD,SCARD,SCRIPT,SDIFF,SDIFFSTORE,SELECT,SET,SETBIT,SETEX,SETNX,SETRANGE,SINTER,SINTERSTORE,SISMEMBER,SLOWLOG,SMEMBERS,SMOVE,SORT,SPOP,SRANDMEMBER,SREM,STRLEN,SUBSCRIBE,SUNION,SUNIONSTORE,SWAPDB,TIME,TOUCH,TTL,TYPE,UNSUBSCRIBE,UNLINK,UNWATCH,WAIT,WATCH,ZADD,ZCARD,ZCOUNT,ZINCRBY,ZINTERSTORE,ZLEXCOUNT,ZPOPMAX,ZPOPMIN,ZRANGE,ZRANGEBYLEX,ZREVRANGEBYLEX,ZRANGEBYSCORE,ZRANK,ZREM,ZREMRANGEBYLEX,ZREMRANGEBYRANK,ZREMRANGEBYSCORE,ZREVRANGE,ZREVRANGEBYSCORE,ZREVRANK,ZSCORE,ZUNIONSTORE,SCAN,SSCAN,HSCAN,ZSCAN,XINFO,XADD,XTRIM,XDEL,XRANGE,XREVRANGE,XLEN,XREAD,XGROUP,XREADGROUP,XACK,XCLAIM,XPENDING,GEORADIUS_RO,GEORADIUSBYMEMBER_RO,LOLWUT,XSETID,SUBSTR",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.3",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "repl-backlog-size",
                "ParameterValue": "1048576",
                "Description": "The replication backlog size in bytes for PSYNC. This is the size of the buffer which accumulates slave data when slave is disconnected for some time, so that when slave reconnects again, only transfer the portion of data which the slave missed. Minimum value is 16K.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "16384-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "repl-backlog-ttl",
                "ParameterValue": "3600",
                "Description": "The amount of time in seconds after the master no longer have any slaves connected for the master to free the replication backlog. A value of 0 means to never release the backlog.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "replica-allow-chaining",
                "ParameterValue": "no",
                "Description": "Configures if chaining of replicas is allowed",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "replica-ignore-maxmemory",
                "ParameterValue": "yes",
                "Description": "Determines if replica ignores maxmemory setting by not evicting items independent from the master",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "replica-lazy-flush",
                "ParameterValue": "no",
                "Description": "Perform an asynchronous flushDB during replica sync",
                "Source": "system",
                "DataType": "string",
                "AllowedValues": "yes,no",
                "IsModifiable": false,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "reserved-memory-percent",
                "ParameterValue": "25",
                "Description": "The percent of memory reserved for non-cache memory usage. You may want to increase this parameter for nodes with read replicas, AOF enabled, etc, to reduce swap usage.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-100",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "set-max-intset-entries",
                "ParameterValue": "512",
                "Description": "The limit in the size of the set in order for the dataset to be compressed.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "slowlog-log-slower-than",
                "ParameterValue": "10000",
                "Description": "The execution time, in microseconds, to exceed in order for the command to get logged. Note that a negative number disables the slow log, while a value of zero forces the logging of every command.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "slowlog-max-len",
                "ParameterValue": "128",
                "Description": "The length of the slow log. There is no limit to this length. Just be aware that it will consume memory. You can reclaim memory used by the slow log with SLOWLOG RESET.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "stream-node-max-bytes",
                "ParameterValue": "4096",
                "Description": "The maximum size of a single node in a stream in bytes",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "stream-node-max-entries",
                "ParameterValue": "100",
                "Description": "The maximum number of items a single node in a stream can contain",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "tcp-keepalive",
                "ParameterValue": "300",
                "Description": "If non-zero, send ACKs every given number of seconds.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "timeout",
                "ParameterValue": "0",
                "Description": "Close connection if client is idle for a given number of seconds, or never if 0.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0,20-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "zset-max-ziplist-entries",
                "ParameterValue": "128",
                "Description": "The maximum number of sorted set entries in order for the dataset to be compressed.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            },
            {
                "ParameterName": "zset-max-ziplist-value",
                "ParameterValue": "64",
                "Description": "The threshold of biggest sorted set entries in order for the dataset to be compressed.",
                "Source": "system",
                "DataType": "integer",
                "AllowedValues": "0-",
                "IsModifiable": true,
                "MinimumEngineVersion": "5.0.0",
                "ChangeType": "immediate"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEngineDefaultParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-engine-default-parameters.html)」を参照してください。

### `describe-events`
<a name="elasticache_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
**レプリケーショングループのイベントを記述するには**  
次の `describe-events` の例では、レプリケーショングループのイベントのリストを返します。  

```
aws elasticache describe-events \
    --source-identifier test-cluster \
    --source-type replication-group
```
出力:  

```
{
    "Events": [
        {
            "SourceIdentifier": "test-cluster",
            "SourceType": "replication-group",
            "Message": "Automatic failover has been turned on for replication group test-cluster",
            "Date": "2020-03-18T23:51:34.457Z"
        },
        {
            "SourceIdentifier": "test-cluster",
            "SourceType": "replication-group",
            "Message": "Replication group test-cluster created",
            "Date": "2020-03-18T23:50:31.378Z"
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Monitoring Events](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/ECEvents.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-events.html)」を参照してください。

### `describe-global-replication-groups`
<a name="elasticache_DescribeGlobalReplicationGroups_cli_2_topic"></a>

次のコード例は、`describe-global-replication-groups` を使用する方法を示しています。

**AWS CLI**  
**グローバルレプリケーショングループを記述するには**  
次の `describe-global-replication-groups` の例では、グローバルデータストアの詳細を返します。  

```
aws elasticache describe-global-replication-groups \
    --global-replication-group-id my-grg
```
出力:  

```
{
    "GlobalReplicationGroups": [
        {
            "GlobalReplicationGroupId": "my-grg",
            "GlobalReplicationGroupDescription": "my-grg",
            "Status": "creating",
            "CacheNodeType": "cache.r5.large",
            "Engine": "redis",
            "EngineVersion": "5.0.6",
            "ClusterEnabled": false,
            "AuthTokenEnabled": false,
            "TransitEncryptionEnabled": false,
            "AtRestEncryptionEnabled": false
        }
    ]
}
```
詳細については、*Elasticache ユーザーガイド*の[「グローバルデータストアを使用した AWS リージョン間のレプリケーション](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Datastore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGlobalReplicationGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-global-replication-groups.html)」を参照してください。

### `describe-replication-groups`
<a name="elasticache_DescribeReplicationGroups_cli_2_topic"></a>

次のコード例は、`describe-replication-groups` を使用する方法を示しています。

**AWS CLI**  
**レプリケーショングループの詳細のリストを返すには**  
次の `describe-replication-groups` の例では、レプリケーショングループを返します。  

```
aws elasticache describe-replication-groups
```
出力:  

```
{
    "ReplicationGroups": [
        {
            "ReplicationGroupId": "my-cluster",
            "Description": "mycluster",
            "Status": "available",
            "PendingModifiedValues": {},
            "MemberClusters": [
                "pat-cluster-001",
                "pat-cluster-002",
                "pat-cluster-003",
                "pat-cluster-004"
            ],
            "NodeGroups": [
                {
                    "NodeGroupId": "0001",
                    "Status": "available",
                    "PrimaryEndpoint": {
                        "Address": "my-cluster.xxxxih.ng.0001.usw2.cache.amazonaws.com",
                        "Port": 6379
                    },
                    "ReaderEndpoint": {
                        "Address": "my-cluster-ro.xxxxih.ng.0001.usw2.cache.amazonaws.com",
                        "Port": 6379
                    },
                    "NodeGroupMembers": [
                        {
                            "CacheClusterId": "my-cluster-001",
                            "CacheNodeId": "0001",
                            "ReadEndpoint": {
                                "Address": "pat-cluster-001.xxxih.0001.usw2.cache.amazonaws.com",
                                "Port": 6379
                            },
                            "PreferredAvailabilityZone": "us-west-2a",
                            "CurrentRole": "primary"
                        },
                        {
                            "CacheClusterId": "my-cluster-002",
                            "CacheNodeId": "0001",
                            "ReadEndpoint": {
                                "Address": "pat-cluster-002.xxxxih.0001.usw2.cache.amazonaws.com",
                                "Port": 6379
                            },
                            "PreferredAvailabilityZone": "us-west-2a",
                            "CurrentRole": "replica"
                        },
                        {
                            "CacheClusterId": "my-cluster-003",
                            "CacheNodeId": "0001",
                            "ReadEndpoint": {
                                "Address": "pat-cluster-003.xxxxih.0001.usw2.cache.amazonaws.com",
                                "Port": 6379
                            },
                            "PreferredAvailabilityZone": "us-west-2a",
                            "CurrentRole": "replica"
                        },
                        {
                            "CacheClusterId": "my-cluster-004",
                            "CacheNodeId": "0001",
                            "ReadEndpoint": {
                                "Address": "pat-cluster-004.xxxih.0001.usw2.cache.amazonaws.com",
                                "Port": 6379
                            },
                            "PreferredAvailabilityZone": "us-west-2a",
                            "CurrentRole": "replica"
                        }
                    ]
                }
            ],
            "AutomaticFailover": "disabled",
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "07:30-08:30",
            "ClusterEnabled": false,
            "CacheNodeType": "cache.r5.xlarge",
            "AuthTokenEnabled": false,
            "TransitEncryptionEnabled": false,
            "AtRestEncryptionEnabled": false,
            "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxxx152:replicationgroup:my-cluster",
            "LogDeliveryConfigurations": [
                {
                    "LogType": "slow-log",
                    "DestinationType": "cloudwatch-logs",
                    "DestinationDetails": {
                        "CloudWatchLogsDetails": {
                            "LogGroup": "test-log"
                        }
                    },
                    "LogFormat": "json",
                    "Status": "active"
                }
            ]
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Managing Clusters](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReplicationGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-replication-groups.html)」を参照してください。

### `describe-reserved-cache-nodes-offerings`
<a name="elasticache_DescribeReservedCacheNodesOfferings_cli_2_topic"></a>

次のコード例は、`describe-reserved-cache-nodes-offerings` を使用する方法を示しています。

**AWS CLI**  
**reserved-cache-nodes-offerings を記述するには**  
次の `describe-reserved-cache-nodes-offerings` の例では、予約済みキャッシュノードオプションの詳細を返します。  

```
aws elasticache describe-reserved-cache-nodes-offerings
```
出力:  

```
{
    "ReservedCacheNodesOfferings": [
        {
            "ReservedCacheNodesOfferingId": "01ce0a19-a476-41cb-8aee-48eacbcdc8e5",
            "CacheNodeType": "cache.t3.small",
            "Duration": 31536000,
            "FixedPrice": 97.0,
            "UsagePrice": 0.0,
            "ProductDescription": "memcached",
            "OfferingType": "Partial Upfront",
            "RecurringCharges": [
                {
                    "RecurringChargeAmount": 0.011,
                    "RecurringChargeFrequency": "Hourly"
                }
            ]
        },
        {
            "ReservedCacheNodesOfferingId": "0443a27b-4da5-4b90-b92d-929fbd7abed2",
            "CacheNodeType": "cache.m3.2xlarge",
            "Duration": 31536000,
            "FixedPrice": 1772.0,
            "UsagePrice": 0.0,
            "ProductDescription": "redis",
            "OfferingType": "Heavy Utilization",
            "RecurringCharges": [
                {
                    "RecurringChargeAmount": 0.25,
                    "RecurringChargeFrequency": "Hourly"
                }
            ]
        },

        ...

    ]
}
```
詳細については、「*ElastiCache Redis ユーザーガイド*」の「[Getting Info About Reserved Node Offerings](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/reserved-nodes-offerings.html)」または「*ElastiCache Memcached ユーザーガイド*」の「[Getting Info About Reserved Node Offerings](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/reserved-nodes-offerings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedCacheNodesOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-reserved-cache-nodes-offerings.html)」を参照してください。

### `describe-reserved-cache-nodes`
<a name="elasticache_DescribeReservedCacheNodes_cli_2_topic"></a>

次のコード例は、`describe-reserved-cache-nodes` を使用する方法を示しています。

**AWS CLI**  
**予約済みキャッシュノードを記述するには**  
次の `describe-reserved-cache-nodes` の例は、このアカウントの予約済みキャッシュノード、または指定した予約済みキャッシュノードに関する情報を返します。  
aws elasticache describe-reserved-cache-nodes  
出力:  

```
{
    "ReservedCacheNodes": [
        {
            "ReservedCacheNodeId": "mynode",
            "ReservedCacheNodesOfferingId": "xxxxxxxxx-xxxxx-xxxxx-xxxx-xxxxxxxx71",
            "CacheNodeType": "cache.t3.small",
            "StartTime": "2019-12-06T02:50:44.003Z",
            "Duration": 31536000,
            "FixedPrice": 0.0,
            "UsagePrice": 0.0,
            "CacheNodeCount": 1,
            "ProductDescription": "redis",
            "OfferingType": "No Upfront",
            "State": "payment-pending",
            "RecurringCharges": [
                {
                    "RecurringChargeAmount": 0.023,
                    "RecurringChargeFrequency": "Hourly"
                }
            ],
            "ReservationARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxxxx52:reserved-instance:mynode"
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の[「Managing Costs with Reserved Nodes](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/reserved-nodes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedCacheNodes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-reserved-cache-nodes.html)」を参照してください。

### `describe-service-updates`
<a name="elasticache_DescribeServiceUpdates_cli_2_topic"></a>

次のコード例は、`describe-service-updates` を使用する方法を示しています。

**AWS CLI**  
**サービス更新を記述するには**  
次の `describe-service-updates` の例では、サービスの更新に関する詳細を返します。  

```
aws elasticache describe-service-updates
```
出力:  

```
{
     "ServiceUpdates": [
         {
             "ServiceUpdateName": "elc-xxxxxxxx7-001",
             "ServiceUpdateReleaseDate": "2019-10-09T16:00:00Z",
             "ServiceUpdateEndDate": "2020-02-09T15:59:59Z",
             "ServiceUpdateSeverity": "important",
             "ServiceUpdateRecommendedApplyByDate": "2019-11-08T15:59:59Z",
             "ServiceUpdateStatus": "available",
             "ServiceUpdateDescription": "Upgrades to improve the security, reliability, and operational performance of your ElastiCache nodes",
             "ServiceUpdateType": "security-update",
             "Engine": "redis, memcached",
             "EngineVersion": "redis 2.6.13 and onwards, memcached 1.4.5 and onwards",
             "AutoUpdateAfterRecommendedApplyByDate": false,
             "EstimatedUpdateTime": "30 minutes per node"
         },
         {
             "ServiceUpdateName": "elc-xxxxxxxx4-001",
             "ServiceUpdateReleaseDate": "2019-06-11T15:00:00Z",
             "ServiceUpdateEndDate": "2019-10-01T09:24:00Z",
             "ServiceUpdateSeverity": "important",
             "ServiceUpdateRecommendedApplyByDate": "2019-07-11T14:59:59Z",
             "ServiceUpdateStatus": "expired",
             "ServiceUpdateDescription": "Upgrades to improve the security, reliability, and operational performance of your ElastiCache nodes",
             "ServiceUpdateType": "security-update",
             "Engine": "redis",
             "EngineVersion": "redis 3.2.6, redis 4.0 and onwards",
             "AutoUpdateAfterRecommendedApplyByDate": false,
             "EstimatedUpdateTime": "30 minutes per node"
         }
     ]
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeServiceUpdates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-service-updates.html)」を参照してください。

### `describe-snapshots`
<a name="elasticache_DescribeSnapshots_cli_2_topic"></a>

次のコード例は、`describe-snapshots` を使用する方法を示しています。

**AWS CLI**  
**スナップショットを記述するには**  
次の「describe-snapshots」の例は、クラスターまたはレプリケーショングループのスナップショットに関する情報を返します。  

```
aws elasticache describe-snapshots
```
出力:  

```
{
    "Snapshots": [
        {
            "SnapshotName": "automatic.my-cluster2-002-2019-12-05-06-38",
            "CacheClusterId": "my-cluster2-002",
            "SnapshotStatus": "available",
            "SnapshotSource": "automated",
            "CacheNodeType": "cache.r5.large",
            "Engine": "redis",
            "EngineVersion": "5.0.5",
            "NumCacheNodes": 1,
            "PreferredAvailabilityZone": "us-west-2a",
            "CacheClusterCreateTime": "2019-11-26T01:22:52.396Z",
            "PreferredMaintenanceWindow": "mon:17:30-mon:18:30",
            "TopicArn": "arn:aws:sns:us-west-2:xxxxxxxxx52:My_Topic",
            "Port": 6379,
            "CacheParameterGroupName": "default.redis5.0",
            "CacheSubnetGroupName": "kxkxk",
            "VpcId": "vpc-a3e97cdb",
            "AutoMinorVersionUpgrade": true,
            "SnapshotRetentionLimit": 1,
            "SnapshotWindow": "06:30-07:30",
            "NodeSnapshots": [
                {
                    "CacheNodeId": "0001",
                    "CacheSize": "5 MB",
                    "CacheNodeCreateTime": "2019-11-26T01:22:52.396Z",
                    "SnapshotCreateTime": "2019-12-05T06:38:23Z"
                }
            ]
        },
        {
            "SnapshotName": "myreplica-backup",
            "CacheClusterId": "myreplica",
            "SnapshotStatus": "available",
            "SnapshotSource": "manual",
            "CacheNodeType": "cache.r5.large",
            "Engine": "redis",
            "EngineVersion": "5.0.5",
            "NumCacheNodes": 1,
            "PreferredAvailabilityZone": "us-west-2a",
            "CacheClusterCreateTime": "2019-11-26T00:14:52.439Z",
            "PreferredMaintenanceWindow": "sat:10:00-sat:11:00",
            "TopicArn": "arn:aws:sns:us-west-2:xxxxxxxxxx152:My_Topic",
            "Port": 6379,
            "CacheParameterGroupName": "default.redis5.0",
            "CacheSubnetGroupName": "kxkxk",
            "VpcId": "vpc-a3e97cdb",
            "AutoMinorVersionUpgrade": true,
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "09:00-10:00",
            "NodeSnapshots": [
                {
                    "CacheNodeId": "0001",
                    "CacheSize": "5 MB",
                    "CacheNodeCreateTime": "2019-11-26T00:14:52.439Z",
                    "SnapshotCreateTime": "2019-11-26T00:25:01Z"
                }
            ]
        },
        {
            "SnapshotName": "my-cluster",
            "CacheClusterId": "my-cluster-003",
            "SnapshotStatus": "available",
            "SnapshotSource": "manual",
            "CacheNodeType": "cache.r5.large",
            "Engine": "redis",
            "EngineVersion": "5.0.5",
            "NumCacheNodes": 1,
            "PreferredAvailabilityZone": "us-west-2a",
            "CacheClusterCreateTime": "2019-11-25T23:56:17.186Z",
            "PreferredMaintenanceWindow": "sat:10:00-sat:11:00",
            "TopicArn": "arn:aws:sns:us-west-2:xxxxxxxxxx152:My_Topic",
            "Port": 6379,
            "CacheParameterGroupName": "default.redis5.0",
            "CacheSubnetGroupName": "kxkxk",
            "VpcId": "vpc-a3e97cdb",
            "AutoMinorVersionUpgrade": true,
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "09:00-10:00",
            "NodeSnapshots": [
                {
                    "CacheNodeId": "0001",
                    "CacheSize": "5 MB",
                    "CacheNodeCreateTime": "2019-11-25T23:56:17.186Z",
                    "SnapshotCreateTime": "2019-11-26T03:08:33Z"
                }
            ]
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Backup and Restore for ElastiCache for Redis](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/backups.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-snapshots.html)」を参照してください。

### `describe-update-actions`
<a name="elasticache_DescribeUpdateActions_cli_2_topic"></a>

次のコード例は、`describe-update-actions` を使用する方法を示しています。

**AWS CLI**  
**更新アクションを記述するには**  
次の `describe-update-actions` の例では、更新アクションの詳細を返します。  

```
aws elasticache describe-update-actions
```
出力:  

```
{
    "UpdateActions": [
        {
            "ReplicationGroupId": "mycluster",
            "ServiceUpdateName": "elc-20191007-001",
            "ServiceUpdateReleaseDate": "2019-10-09T16:00:00Z",
            "ServiceUpdateSeverity": "important",
            "ServiceUpdateStatus": "available",
            "ServiceUpdateRecommendedApplyByDate": "2019-11-08T15:59:59Z",
            "ServiceUpdateType": "security-update",
            "UpdateActionAvailableDate": "2019-12-05T19:15:19.995Z",
            "UpdateActionStatus": "complete",
            "NodesUpdated": "9/9",
            "UpdateActionStatusModifiedDate": "2019-12-05T19:15:20.461Z",
            "SlaMet": "n/a",
            "Engine": "redis"
        },
        {
            "CacheClusterId": "my-memcached-cluster",
            "ServiceUpdateName": "elc-20191007-001",
            "ServiceUpdateReleaseDate": "2019-10-09T16:00:00Z",
            "ServiceUpdateSeverity": "important",
            "ServiceUpdateStatus": "available",
            "ServiceUpdateRecommendedApplyByDate": "2019-11-08T15:59:59Z",
            "ServiceUpdateType": "security-update",
            "UpdateActionAvailableDate": "2019-12-04T18:26:05.349Z",
            "UpdateActionStatus": "complete",
            "NodesUpdated": "1/1",
            "UpdateActionStatusModifiedDate": "2019-12-04T18:26:05.352Z",
            "SlaMet": "n/a",
            "Engine": "redis"
        },
        {
            "ReplicationGroupId": "my-cluster",
            "ServiceUpdateName": "elc-20191007-001",
            "ServiceUpdateReleaseDate": "2019-10-09T16:00:00Z",
            "ServiceUpdateSeverity": "important",
            "ServiceUpdateStatus": "available",
            "ServiceUpdateRecommendedApplyByDate": "2019-11-08T15:59:59Z",
            "ServiceUpdateType": "security-update",
            "UpdateActionAvailableDate": "2019-11-26T03:36:26.320Z",
            "UpdateActionStatus": "complete",
            "NodesUpdated": "4/4",
            "UpdateActionStatusModifiedDate": "2019-12-04T22:11:12.664Z",
            "SlaMet": "n/a",
            "Engine": "redis"
        },
        {
            "ReplicationGroupId": "my-cluster2",
            "ServiceUpdateName": "elc-20191007-001",
            "ServiceUpdateReleaseDate": "2019-10-09T16:00:00Z",
            "ServiceUpdateSeverity": "important",
            "ServiceUpdateStatus": "available",
            "ServiceUpdateRecommendedApplyByDate": "2019-11-08T15:59:59Z",
            "ServiceUpdateType": "security-update",
            "UpdateActionAvailableDate": "2019-11-26T01:26:01.617Z",
            "UpdateActionStatus": "complete",
            "NodesUpdated": "3/3",
            "UpdateActionStatusModifiedDate": "2019-11-26T01:26:01.753Z",
            "SlaMet": "n/a",
            "Engine": "redis"
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Self-Service Updates in Amazon ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Self-Service-Updates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUpdateActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-update-actions.html)」を参照してください。

### `describe-user-groups`
<a name="elasticache_DescribeUserGroups_cli_2_topic"></a>

次のコード例は、`describe-user-groups` を使用する方法を示しています。

**AWS CLI**  
**ユーザーグループを記述するには**  
次の `describe-user-groups` の例では、ユーザーグループのリストを返します。  

```
aws elasticache describe-user-groups
```
出力:  

```
{
    "UserGroups": [
        {
            "UserGroupId": "myusergroup",
            "Status": "active",
            "Engine": "redis",
            "UserIds": [
                "default"
            ],
            "ReplicationGroups": [],
            "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:usergroup:myusergroup"
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUserGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-user-groups.html)」を参照してください。

### `describe-users`
<a name="elasticache_DescribeUsers_cli_2_topic"></a>

次のコード例は、`describe-users` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを記述するには**  
次の `describe-users` の例では、ユーザーのリストを返します。  

```
aws elasticache describe-users
```
出力:  

```
{
    "Users": [
        {
            "UserId": "default",
            "UserName": "default",
            "Status": "active",
            "Engine": "redis",
            "AccessString": "on ~* +@all",
            "UserGroupIds": [
                "myusergroup"
            ],
            "Authentication": {
                "Type": "no-password"
            },
            "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:user:default"
        },
        {
            "UserId": "user1",
            "UserName": "myUser",
            "Status": "active",
            "Engine": "redis",
            "AccessString": "on ~* +@all",
            "UserGroupIds": [],
            "Authentication": {
                "Type": "password",
                "PasswordCount": 1
            },
            "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:user:user1"
        },
        {
            "UserId": "user2",
            "UserName": "myUser",
            "Status": "active",
            "Engine": "redis",
            "AccessString": "on ~app::* -@all +@read +@hash +@bitmap +@geo -setbit -bitfield -hset -hsetnx -hmset -hincrby -hincrbyfloat -hdel -bitop -geoadd -georadius -georadiusbymember",
            "UserGroupIds": [],
            "Authentication": {
                "Type": "password",
                "PasswordCount": 1
            },
            "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:user:user2"
        }
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/describe-users.html)」を参照してください。

### `disassociate-global-replication-group`
<a name="elasticache_DisassociateGlobalReplicationGroup_cli_2_topic"></a>

次のコード例は、`disassociate-global-replication-group` を使用する方法を示しています。

**AWS CLI**  
**グローバルレプリケーショングループからセカンダリクラスターの関連付けを解除するには**  
次の `disassociate-global-replication-group` の例では、グローバルデータストアからセカンダリクラスターを削除します。  

```
aws elasticache disassociate-global-replication-group \
    --global-replication-group-id my-grg \
    --replication-group-id my-cluster-grg-secondary \
    --replication-group-region us-east-1
```
出力:  

```
{
    "GlobalReplicationGroup": {
        "GlobalReplicationGroupId": "my-grg",
        "GlobalReplicationGroupDescription": "my-grg",
        "Status": "modifying",
        "CacheNodeType": "cache.r5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.6",
        "Members": [
            {
                "ReplicationGroupId": "my-cluster-grg-secondary",
                "ReplicationGroupRegion": "us-east-1",
                "Role": "SECONDARY",
                "AutomaticFailover": "enabled",
                "Status": "associated"
            },
            {
                "ReplicationGroupId": "my-cluster-grg",
                "ReplicationGroupRegion": "us-west-2",
                "Role": "PRIMARY",
                "AutomaticFailover": "enabled",
                "Status": "associated"
            }
        ],
        "ClusterEnabled": false,
        "AuthTokenEnabled": false,
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、*Elasticache ユーザーガイド*の[「グローバルデータストアを使用した AWS リージョン間のレプリケーション](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Datastore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateGlobalReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/disassociate-global-replication-group.html)」を参照してください。

### `increase-node-groups-in-global-replication-group`
<a name="elasticache_IncreaseNodeGroupsInGlobalReplicationGroup_cli_2_topic"></a>

次のコード例は、`increase-node-groups-in-global-replication-group` を使用する方法を示しています。

**AWS CLI**  
**グローバルレプリケーショングループのノードグループ数を増やすには**  
次の `increase-node-groups-in-global-replication-group` は、Redis エンジンを使用してノードグループ数を増やします。  

```
aws elasticache increase-node-groups-in-global-replication-group \
    --global-replication-group-id sgaui-pat-test-4 \
    --node-group-count 6 \
    --apply-immediately
```
出力:  

```
{
    "GlobalReplicationGroup": {
        "GlobalReplicationGroupId": "sgaui-test-4",
        "GlobalReplicationGroupDescription": "test-4",
        "Status": "modifying",
        "CacheNodeType": "cache.r5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.6",
        "Members": [
            {
                "ReplicationGroupId": "my-cluster-b",
                "ReplicationGroupRegion": "us-east-1",
                "Role": "SECONDARY",
                "AutomaticFailover": "enabled",
                "Status": "associated"
            },
            {
                "ReplicationGroupId": "my-cluster-a",
                "ReplicationGroupRegion": "us-west-2",
                "Role": "PRIMARY",
                "AutomaticFailover": "enabled",
                "Status": "associated"
            }
        ],
        "ClusterEnabled": true,
        "GlobalNodeGroups": [
            {
                "GlobalNodeGroupId": "sgaui-test-4-0001",
                "Slots": "0-234,2420-5461"
            },
            {
                "GlobalNodeGroupId": "sgaui-test-4-0002",
                "Slots": "5462-5904,6997-9830"
            },
            {
                "GlobalNodeGroupId": "sgaui-test-4-0003",
                "Slots": "10923-11190,13375-16383"
            },
            {
                "GlobalNodeGroupId": "sgaui-test-4-0004",
                "Slots": "235-2419,5905-6996"
            },
            {
                "GlobalNodeGroupId": "sgaui-test-4-0005",
                "Slots": "9831-10922,11191-13374"
            }
        ],
        "AuthTokenEnabled": false,
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、*Elasticache ユーザーガイド*の[「グローバルデータストアを使用した AWS リージョン間のレプリケーション](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Datastore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IncreaseNodeGroupsInGlobalReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/increase-node-groups-in-global-replication-group.html)」を参照してください。

### `increase-replica-count`
<a name="elasticache_IncreaseReplicaCount_cli_2_topic"></a>

次のコード例は、`increase-replica-count` を使用する方法を示しています。

**AWS CLI**  
**レプリカ数を増やすには**  
次の `increase-replica-count` の例では、2 つのモノのいずれかを実行します。Redis (クラスターモードが無効) レプリケーショングループのレプリカの数を動的に増やすことができます。または、Redis (クラスターモードが有効) レプリケーショングループの 1 つ以上のノードグループ (シャード) 内のレプリカノードの数を動的に増やすこともできます。このオペレーションは、クラスターのダウンタイムなしで実行されます。  

```
aws elasticache increase-replica-count \
    --replication-group-id "my-cluster" \
    --apply-immediately \
    --new-replica-count 3
```
出力:  

```
{
     "ReplicationGroup": {
         "ReplicationGroupId": "my-cluster",
         "Description": " ",
         "Status": "modifying",
         "PendingModifiedValues": {},
         "MemberClusters": [
             "my-cluster-001",
             "my-cluster-002",
             "my-cluster-003",
             "my-cluster-004"
         ],
         "NodeGroups": [
             {
                 "NodeGroupId": "0001",
                 "Status": "modifying",
                 "PrimaryEndpoint": {
                     "Address": "my-cluster.xxxxxih.ng.0001.usw2.cache.amazonaws.com",
                     "Port": 6379
                 },
                 "ReaderEndpoint": {
                     "Address": "my-cluster-ro.xxxxxxih.ng.0001.usw2.cache.amazonaws.com",
                     "Port": 6379
                 },
                 "NodeGroupMembers": [
                     {
                         "CacheClusterId": "my-cluster-001",
                         "CacheNodeId": "0001",
                         "ReadEndpoint": {
                             "Address": "my-cluster-001.xxxxxih.0001.usw2.cache.amazonaws.com",
                             "Port": 6379
                         },
                         "PreferredAvailabilityZone": "us-west-2a",
                         "CurrentRole": "primary"
                     },
                     {
                         "CacheClusterId": "my-cluster-003",
                         "CacheNodeId": "0001",
                         "ReadEndpoint": {
                             "Address": "my-cluster-003.xxxxxih.0001.usw2.cache.amazonaws.com",
                             "Port": 6379
                         },
                         "PreferredAvailabilityZone": "us-west-2a",
                         "CurrentRole": "replica"
                     }
                 ]
             }
         ],
         "AutomaticFailover": "disabled",
         "SnapshotRetentionLimit": 0,
         "SnapshotWindow": "07:30-08:30",
         "ClusterEnabled": false,
         "CacheNodeType": "cache.r5.xlarge",
         "TransitEncryptionEnabled": false,
         "AtRestEncryptionEnabled": false
     }
 }
```
詳細については、「*ElastiCache ユーザーガイド*」の「[シャードのレプリカ数を増やす](https://docs.aws.amazon.c`m/AmazonElastiCache/latest/red-ug/increase-replica-count.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IncreaseReplicaCount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/increase-replica-count.html)」を参照してください。

### `list-allowed-node-type-modifications`
<a name="elasticache_ListAllowedNodeTypeModifications_cli_2_topic"></a>

次のコード例は、`list-allowed-node-type-modifications` を使用する方法を示しています。

**AWS CLI**  
**許可されたノードの変更を一覧表示するには**  
次の `list-allowed-node-type-modifications` の例では、Redis クラスターまたはレプリケーショングループの現在のノードタイプをスケールできるすべての使用可能なノードタイプを一覧表示します。  

```
aws elasticache list-allowed-node-type-modifications \
    --replication-group-id "my-replication-group"
```
出力:  

```
{
    "ScaleUpModifications": [
        "cache.m5.12xlarge",
        "cache.m5.24xlarge",
        "cache.m5.4xlarge",
        "cache.r5.12xlarge",
        "cache.r5.24xlarge",
        "cache.r5.2xlarge",
        "cache.r5.4xlarge"
    ],
    "ScaleDownModifications": [
        "cache.m3.large",
        "cache.m3.medium",
        "cache.m3.xlarge",
        "cache.m4.large",
        "cache.m4.xlarge",
        "cache.m5.2xlarge",
        "cache.m5.large",
        "cache.m5.xlarge",
        "cache.r3.large",
        "cache.r4.large",
        "cache.r4.xlarge",
        "cache.r5.large",
        "cache.t2.medium",
        "cache.t2.micro",
        "cache.t2.small",
        "cache.t3.medium",
        "cache.t3.micro",
        "cache.t3.small"
    ]
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Scaling ElastiCache for Redis Clusters](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAllowedNodeTypeModifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/list-allowed-node-type-modifications.html)」を参照してください。

### `list-tags-for-resource`
<a name="elasticache_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、リソースのタグを一覧表示します。  

```
aws elasticache list-tags-for-resource \
    --resource-name "arn:aws:elasticache:us-east-1:123456789012:cluster:my-cluster"
```
出力:  

```
{
    "TagList": [
        {
            "Key": "Project",
            "Value": "querySpeedUp"
        },
        {
            "Key": "Environment",
            "Value": "PROD"
        }
    ]
}
```
詳細については、*Elasticache ユーザーガイド*[の「CLI AWS を使用したタグの一覧表示](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Tagging.Managing.CLI.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/list-tags-for-resource.html)」を参照してください。

### `modify-cache-cluster`
<a name="elasticache_ModifyCacheCluster_cli_2_topic"></a>

次のコード例は、`modify-cache-cluster` を使用する方法を示しています。

**AWS CLI**  
**キャッシュクラスターを変更するには**  
次の `modify-cache-cluster` の例では、指定されたクラスターの設定を変更します。  

```
aws elasticache modify-cache-cluster \
    --cache-cluster-id "my-cluster" \
    --num-cache-nodes 1
```
出力:  

```
{
    "CacheCluster": {
        "CacheClusterId": "my-cluster",
        "ClientDownloadLandingPage": "https://console.aws.amazon.com/elasticache/home#client-download:",
        "CacheNodeType": "cache.m5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.5",
        "CacheClusterStatus": "available",
        "NumCacheNodes": 1,
        "PreferredAvailabilityZone": "us-west-2c",
        "CacheClusterCreateTime": "2019-12-04T18:24:56.652Z",
        "PreferredMaintenanceWindow": "sat:10:00-sat:11:00",
        "PendingModifiedValues": {},
        "CacheSecurityGroups": [],
        "CacheParameterGroup": {
            "CacheParameterGroupName": "default.redis5.0",
            "ParameterApplyStatus": "in-sync",
            "CacheNodeIdsToReboot": []
        },
        "CacheSubnetGroupName": "default",
        "AutoMinorVersionUpgrade": true,
        "SnapshotRetentionLimit": 0,
        "SnapshotWindow": "07:00-08:00",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Modifying an ElastiCache Cluster](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.Modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyCacheCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-cache-cluster.html)」を参照してください。

### `modify-cache-parameter-group`
<a name="elasticache_ModifyCacheParameterGroup_cli_2_topic"></a>

次のコード例は、`modify-cache-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**キャッシュパラメータグループを変更するには**  
次の `modify-cache-parameter-group` の例では、指定されたキャッシュパラメータグループのパラメータを変更します。  

```
aws elasticache modify-cache-parameter-group \
    --cache-parameter-group-name "mygroup" \
    --parameter-name-values "ParameterName=activedefrag, ParameterValue=no"
```
出力:  

```
{
    "CacheParameterGroupName": "mygroup"
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Modifying a Parameter Group](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/ParameterGroups.Modifying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyCacheParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-cache-parameter-group.html)」を参照してください。

### `modify-cache-subnet-group`
<a name="elasticache_ModifyCacheSubnetGroup_cli_2_topic"></a>

次のコード例は、`modify-cache-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**キャッシュサブネットグループを変更するには**  
次の `modify-cache-subnet-group` の例では、指定されたキャッシュサブネットグループを変更します。  

```
aws elasticache modify-cache-subnet-group \
    --cache-subnet-group-name kxkxk \
    --cache-subnet-group-description "mygroup"
```
出力:  

```
{
    "CacheSubnetGroup": {
        "CacheSubnetGroupName": "kxkxk",
        "CacheSubnetGroupDescription": "mygroup",
        "VpcId": "vpc-xxxxcdb",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-xxxxbff",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2a"
                }
            }
        ]
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Modifying a Subnet Group](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/SubnetGroups.Modifying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyCacheSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-cache-subnet-group.html)」を参照してください。

### `modify-global-replication-group`
<a name="elasticache_ModifyGlobalReplicationGroup_cli_2_topic"></a>

次のコード例は、`modify-global-replication-group` を使用する方法を示しています。

**AWS CLI**  
**グローバルレプリケーショングループを変更するには**  
次の `modify-global-replication-group` は、Redis エンジンを使用して、グローバルレプリケーショングループのプロパティを変更します。この場合、自動フェイルオーバーは無効化されます。  

```
aws elasticache modify-global-replication-group \
    --global-replication-group-id sgaui-pat-group \
    --apply-immediately \
    --no-automatic-failover-enabled
```
Output  

```
{
    "GlobalReplicationGroup": {
        "GlobalReplicationGroupId": "sgaui-test-group",
        "GlobalReplicationGroupDescription": " ",
        "Status": "modifying",
        "CacheNodeType": "cache.r5.large",
        "Engine": "redis",
        "EngineVersion": "5.0.6",
        "ClusterEnabled": false,
        "AuthTokenEnabled": false,
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、*Elasticache ユーザーガイド*の[「グローバルデータストアを使用した AWS リージョン間のレプリケーション](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Redis-Global-Datastore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyGlobalReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-global-replication-group.html)」を参照してください。

### `modify-replication-group-shard-configuration`
<a name="elasticache_ModifyReplicationGroupShardConfiguration_cli_2_topic"></a>

次のコード例は、`modify-replication-group-shard-configuration` を使用する方法を示しています。

**AWS CLI**  
**レプリケーショングループのシャード設定を変更するには**  
次の `modify-replication-group-shard-configuration` は、Redis エンジンを使用してノードグループの数を減らします。  

```
aws elasticache modify-replication-group-shard-configuration \
    --replication-group-id mycluster \
    --node-group-count 3 \
    --apply-immediately \
    --node-groups-to-remove 0002
```
Output  

```
{
    "ReplicationGroup": {
        "ReplicationGroupId": "mycluster",
        "Description": "mycluster",
        "GlobalReplicationGroupInfo": {},
        "Status": "modifying",
        "PendingModifiedValues": {},
        "MemberClusters": [
            "mycluster-0002-001",
            "mycluster-0002-002",
            "mycluster-0002-003",
            "mycluster-0003-001",
            "mycluster-0003-002",
            "mycluster-0003-003",
            "mycluster-0003-004",
            "mycluster-0004-001",
            "mycluster-0004-002",
            "mycluster-0004-003",
            "mycluster-0005-001",
            "mycluster-0005-002",
            "mycluster-0005-003"
        ],
        "NodeGroups": [
            {
                "NodeGroupId": "0002",
                "Status": "modifying",
                "Slots": "894-1767,3134-4443,5149-5461,6827-7332,12570-13662",
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "mycluster-0002-001",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    },
                    {
                        "CacheClusterId": "mycluster-0002-002",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2a"
                    },
                    {
                        "CacheClusterId": "mycluster-0002-003",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2b"
                    }
                ]
            },
            {
                "NodeGroupId": "0003",
                "Status": "modifying",
                "Slots": "0-324,5462-5692,6784-6826,7698-8191,10923-11075,12441-12569,13663-16383",
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "mycluster-0003-001",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    },
                    {
                        "CacheClusterId": "mycluster-0003-002",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2b"
                    },
                    {
                        "CacheClusterId": "mycluster-0003-003",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2a"
                    },
                    {
                        "CacheClusterId": "mycluster-0003-004",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    }
                ]
            },
            {
                "NodeGroupId": "0004",
                "Status": "modifying",
                "Slots": "325-336,4706-5148,7333-7697,9012-10922,11076-12440",
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "mycluster-0004-001",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2b"
                    },
                    {
                        "CacheClusterId": "mycluster-0004-002",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2a"
                    },
                    {
                        "CacheClusterId": "mycluster-0004-003",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    }
                ]
            },
            {
                "NodeGroupId": "0005",
                "Status": "modifying",
                "Slots": "337-893,1768-3133,4444-4705,5693-6783,8192-9011",
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "mycluster-0005-001",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2a"
                    },
                    {
                        "CacheClusterId": "mycluster-0005-002",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    },
                    {
                        "CacheClusterId": "mycluster-0005-003",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2b"
                    }
                ]
            }
        ],
        "AutomaticFailover": "enabled",
        "MultiAZ": "enabled",
        "ConfigurationEndpoint": {
            "Address": "mycluster.g2xbih.clustercfg.usw2.cache.amazonaws.com",
            "Port": 6379
        },
        "SnapshotRetentionLimit": 1,
        "SnapshotWindow": "13:00-14:00",
        "ClusterEnabled": true,
        "CacheNodeType": "cache.r5.xlarge",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Scaling ElastiCache for Redis Clusters](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyReplicationGroupShardConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-replication-group-shard-configuration.html)」を参照してください。

### `modify-replication-group`
<a name="elasticache_ModifyReplicationGroup_cli_2_topic"></a>

次のコード例は、`modify-replication-group` を使用する方法を説明しています。

**AWS CLI**  
**レプリケーショングループを変更するには**  
次の `modify-replication-group` は、Redis エンジンを使用してマルチ AZ を無効にします。  

```
aws elasticache modify-replication-group \
    --replication-group-id test-cluster \
    --no-multi-az-enabled \
    --apply-immediately
```
Output  

```
{
    "ReplicationGroup": {
        "ReplicationGroupId": "test-cluster",
        "Description": "test-cluster",
        "GlobalReplicationGroupInfo": {
            "GlobalReplicationGroupId": "sgaui-pat-group",
            "GlobalReplicationGroupMemberRole": "PRIMARY"
        },
        "Status": "available",
        "PendingModifiedValues": {},
        "MemberClusters": [
            "test-cluster-001",
            "test-cluster-002",
            "test-cluster-003"
        ],
        "NodeGroups": [
            {
                "NodeGroupId": "0001",
                "Status": "available",
                "PrimaryEndpoint": {
                    "Address": "test-cluster.g2xbih.ng.0001.usw2.cache.amazonaws.com",
                    "Port": 6379
                },
                "ReaderEndpoint": {
                    "Address": "test-cluster-ro.g2xbih.ng.0001.usw2.cache.amazonaws.com",
                    "Port": 6379
                },
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "test-cluster-001",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "test-cluster-001.g2xbih.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2c",
                        "CurrentRole": "primary"
                    },
                    {
                        "CacheClusterId": "test-cluster-002",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "test-cluster-002.g2xbih.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2b",
                        "CurrentRole": "replica"
                    },
                    {
                        "CacheClusterId": "test-cluster-003",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "test-cluster-003.g2xbih.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2a",
                        "CurrentRole": "replica"
                    }
                ]
            }
        ],
        "SnapshottingClusterId": "test-cluster-002",
        "AutomaticFailover": "enabled",
        "MultiAZ": "disabled",
        "SnapshotRetentionLimit": 1,
        "SnapshotWindow": "08:00-09:00",
        "ClusterEnabled": false,
        "CacheNodeType": "cache.r5.large",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Modifying a Replication Group](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Replication.Modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyReplicationGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-replication-group.html)」を参照してください。

### `modify-user-group`
<a name="elasticache_ModifyUserGroup_cli_2_topic"></a>

次のコード例は、`modify-user-group` を使用する方法を示しています。

**AWS CLI**  
**ユーザーグループを変更するには**  
次の `modify-user-group` の例は、ユーザーをユーザーグループに追加します。  

```
aws elasticache modify-user-group \
    --user-group-id myusergroup \
    --user-ids-to-add user1
```
出力:  

```
{
    "UserGroupId": "myusergroup",
    "Status": "modifying",
    "Engine": "redis",
    "UserIds": [
        "default"
    ],
    "PendingChanges": {
        "UserIdsToAdd": [
            "user1"
        ]
    },
    "ReplicationGroups": [],
    "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:usergroup:myusergroup"
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyUserGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-user-group.html)」を参照してください。

### `modify-user`
<a name="elasticache_ModifyUser_cli_2_topic"></a>

次のコード例は、`modify-user` を使用する方法を示しています。

**AWS CLI**  
ユーザーを変更するには  
次の `modify-user` の例では、ユーザーのアクセス文字列を変更します。  

```
aws elasticache modify-user \
    --user-id user2 \
    --append-access-string "on ~* +@all"
```
出力:  

```
{
    "UserId": "user2",
    "UserName": "myUser",
    "Status": "modifying",
    "Engine": "redis",
    "AccessString": "on ~* +@all",
    "UserGroupIds": [],
    "Authentication": {
        "Type": "password",
        "PasswordCount": 1
    },
    "ARN": "arn:aws:elasticache:us-west-2:xxxxxxxxxx52:user:user2"
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Authenticating Users with Role-Based Access Control (RBAC)](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.RBAC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/modify-user.html)」を参照してください。

### `purchase-reserved-cache-nodes-offering`
<a name="elasticache_PurchaseReservedCacheNodesOffering_cli_2_topic"></a>

次のコード例は、`purchase-reserved-cache-nodes-offering` を使用する方法を示しています。

**AWS CLI**  
**reserved-cache-node-offering を購入するには**  
次の `purchase-reserved-cache-nodes-offering` の例では、予約済みキャッシュノードサービスを購入できます。  

```
aws elasticache purchase-reserved-cache-nodes-offering \
    --reserved-cache-nodes-offering-id xxxxxxx-4da5-4b90-b92d-929fbd7abed2
```
Output  

```
{
    "ReservedCacheNode": {
        "ReservedCacheNodeId": "ri-2020-06-30-17-59-40-474",
        "ReservedCacheNodesOfferingId": "xxxxxxx-4da5-4b90-b92d-929fbd7abed2",
        "CacheNodeType": "cache.m3.2xlarge",
        "StartTime": "2020-06-30T17:59:40.474000+00:00",
        "Duration": 31536000,
        "FixedPrice": 1772.0,
        "UsagePrice": 0.0,
        "CacheNodeCount": 1,
        "ProductDescription": "redis",
        "OfferingType": "Heavy Utilization",
        "State": "payment-pending",
        "RecurringCharges": [
            {
                "RecurringChargeAmount": 0.25,
                "RecurringChargeFrequency": "Hourly"
            }
        ]
    }
}
```
詳細については、「*ElastiCache Redis ユーザーガイド*」の「[Getting Info About Reserved Node Offerings](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/reserved-nodes-offerings.html)」または「*ElastiCache Memcached ユーザーガイド*」の「[Getting Info About Reserved Node Offerings](https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-ug/reserved-nodes-offerings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseReservedCacheNodesOffering](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/purchase-reserved-cache-nodes-offering.html)」を参照してください。

### `reboot-cache-cluster`
<a name="elasticache_RebootCacheCluster_cli_2_topic"></a>

次のコード例は、`reboot-cache-cluster` を使用する方法を示しています。

**AWS CLI**  
**キャッシュクラスターを再起動するには**  
次の `reboot-cache-cluster` の例では、プロビジョニングされたクラスター内のキャッシュノードの一部またはすべてを再起動します。このオペレーションは、変更されたキャッシュパラメータグループをクラスターに適用します。再起動オペレーションはできるだけ早急に行われ、クラスターが一時停止になります。再起動中、クラスターステータスは `REBOOTING` に設定されます。  

```
aws elasticache reboot-cache-cluster \
    --cache-cluster-id "my-cluster-001" \
    --cache-node-ids-to-reboot "0001"
```
出力:  

```
{
    "CacheCluster": {
        "CacheClusterId": "my-cluster-001",
        "ClientDownloadLandingPage": "https://console.aws.amazon.com/elasticache/home#client-download:",
        "CacheNodeType": "cache.r5.xlarge",
        "Engine": "redis",
        "EngineVersion": "5.0.5",
        "CacheClusterStatus": "rebooting cache cluster nodes",
        "NumCacheNodes": 1,
        "PreferredAvailabilityZone": "us-west-2a",
        "CacheClusterCreateTime": "2019-11-26T03:35:04.546Z",
        "PreferredMaintenanceWindow": "mon:04:05-mon:05:05",
        "PendingModifiedValues": {},
        "NotificationConfiguration": {
            "TopicArn": "arn:aws:sns:us-west-2:xxxxxxxxxx152:My_Topic",
            "TopicStatus": "active"
        },
        "CacheSecurityGroups": [],
        "CacheParameterGroup": {
            "CacheParameterGroupName": "mygroup",
            "ParameterApplyStatus": "in-sync",
            "CacheNodeIdsToReboot": []
        },
        "CacheSubnetGroupName": "kxkxk",
        "AutoMinorVersionUpgrade": true,
        "SecurityGroups": [
            {
                "SecurityGroupId": "sg-xxxxxxxxxxxxx836",
                "Status": "active"
            },
            {
                "SecurityGroupId": "sg-xxxxxxxx7b",
                "Status": "active"
            }
        ],
        "ReplicationGroupId": "my-cluster",
        "SnapshotRetentionLimit": 0,
        "SnapshotWindow": "07:30-08:30",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「Rebooting a Cluster」<https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/Clusters.Rebooting.html」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootCacheCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/reboot-cache-cluster.html)」を参照してください。

### `reset-cache-parameter-group`
<a name="elasticache_ResetCacheParameterGroup_cli_2_topic"></a>

次のコード例は、`reset-cache-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**キャッシュパラメータグループをリセットするには**  
次の `reset-cache-parameter-group` の例では、キャッシュパラメータグループのパラメータをエンジンまたはシステムのデフォルト値に変更します。パラメータ名のリストを送信することで、特定のパラメータをリセットできます。キャッシュパラメータグループ全体をリセットするには、`--reset-all-parameters` と `--cache-parameter-group-name` パラメータを指定します。  

```
aws elasticache reset-cache-parameter-group \
    --cache-parameter-group-name "mygroup" \
    --reset-all-parameters
```
出力:  

```
{
    "CacheParameterGroupName": "mygroup"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetCacheParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/reset-cache-parameter-group.html)」を参照してください。

### `start-migration`
<a name="elasticache_StartMigration_cli_2_topic"></a>

次のコード例は、`start-migration` を使用する方法を示しています。

**AWS CLI**  
**移行を開始するには**  
次の `start-migration` は、Redis エンジンを使用して、Amazon EC2 のセルフホスト Redis から Amazon ElastiCache にデータを移行します。  

```
aws elasticache start-migration \
   --replication-group-id test \
   --customer-node-endpoint-list "Address='test.g2xbih.ng.0001.usw2.cache.amazonaws.com',Port=6379"
```
Output  

```
{
    "ReplicationGroup": {
        "ReplicationGroupId": "test",
        "Description": "test",
        "GlobalReplicationGroupInfo": {},
        "Status": "modifying",
        "PendingModifiedValues": {},
        "MemberClusters": [
            "test-001",
            "test-002",
            "test-003"
        ],
        "NodeGroups": [
            {
                "NodeGroupId": "0001",
                "Status": "available",
                "PrimaryEndpoint": {
                    "Address": "test.g2xbih.ng.0001.usw2.cache.amazonaws.com",
                    "Port": 6379
                },
                "ReaderEndpoint": {
                    "Address": "test-ro.g2xbih.ng.0001.usw2.cache.amazonaws.com",
                    "Port": 6379
                },
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "test-001",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "test-001.g2xbih.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2a",
                        "CurrentRole": "primary"
                    },
                    {
                        "CacheClusterId": "test-002",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "test-002.g2xbih.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2c",
                        "CurrentRole": "replica"
                    },
                    {
                        "CacheClusterId": "test-003",
                        "CacheNodeId": "0001",
                        "ReadEndpoint": {
                            "Address": "test-003.g2xbih.0001.usw2.cache.amazonaws.com",
                            "Port": 6379
                        },
                        "PreferredAvailabilityZone": "us-west-2b",
                        "CurrentRole": "replica"
                    }
                ]
            }
        ],
        "SnapshottingClusterId": "test-002",
        "AutomaticFailover": "enabled",
        "MultiAZ": "enabled",
        "SnapshotRetentionLimit": 1,
        "SnapshotWindow": "07:30-08:30",
        "ClusterEnabled": false,
        "CacheNodeType": "cache.r5.large",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
詳細については、「*ElastiCache ユーザーガイド*」の「[Online Migration to ElastiCache](https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/OnlineMigration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartMigration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/start-migration.html)」を参照してください。

### `test-failover`
<a name="elasticache_TestFailover_cli_2_topic"></a>

次のコード例は、`test-failover` を使用する方法を示しています。

**AWS CLI**  
**ノードグループのフェイルオーバーをテストするには**  
次の `test-failover` の例では、レプリケーショングループ (コンソールではクラスターと呼ばれる) の指定されたノードグループ (コンソールではシャードと呼ばれる) で、自動フェイルオーバーをテストします。  

```
aws elasticache test-failover /
    --replication-group-id "mycluster" /
    --node-group-id "0001"
```
出力:  

```
{
    "ReplicationGroup": {
        "ReplicationGroupId": "mycluster",
        "Description": "My Cluster",
        "Status": "available",
        "PendingModifiedValues": {},
        "MemberClusters": [
            "mycluster-0001-001",
            "mycluster-0001-002",
            "mycluster-0001-003",
            "mycluster-0002-001",
            "mycluster-0002-002",
            "mycluster-0002-003",
            "mycluster-0003-001",
            "mycluster-0003-002",
            "mycluster-0003-003"
        ],
        "NodeGroups": [
            {
                "NodeGroupId": "0001",
                "Status": "available",
                "Slots": "0-5461",
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "mycluster-0001-001",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2b"
                    },
                    {
                        "CacheClusterId": "mycluster-0001-002",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2a"
                    },
                    {
                        "CacheClusterId": "mycluster-0001-003",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    }
                ]
            },
            {
                "NodeGroupId": "0002",
                "Status": "available",
                "Slots": "5462-10922",
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "mycluster-0002-001",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2a"
                    },
                    {
                        "CacheClusterId": "mycluster-0002-002",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2b"
                    },
                    {
                        "CacheClusterId": "mycluster-0002-003",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    }
                ]
            },
            {
                "NodeGroupId": "0003",
                "Status": "available",
                "Slots": "10923-16383",
                "NodeGroupMembers": [
                    {
                        "CacheClusterId": "mycluster-0003-001",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2c"
                    },
                    {
                        "CacheClusterId": "mycluster-0003-002",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2b"
                    },
                    {
                        "CacheClusterId": "mycluster-0003-003",
                        "CacheNodeId": "0001",
                        "PreferredAvailabilityZone": "us-west-2a"
                    }
                ]
            }
        ],
        "AutomaticFailover": "enabled",
        "ConfigurationEndpoint": {
            "Address": "mycluster.xxxxih.clustercfg.usw2.cache.amazonaws.com",
            "Port": 6379
        },
        "SnapshotRetentionLimit": 1,
        "SnapshotWindow": "13:00-14:00",
        "ClusterEnabled": true,
        "CacheNodeType": "cache.r5.large",
        "TransitEncryptionEnabled": false,
        "AtRestEncryptionEnabled": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestFailover](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticache/test-failover.html)」を参照してください。

# を使用した MediaStore の例 AWS CLI
<a name="cli_2_mediastore_code_examples"></a>

次のコード例は、MediaStore AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-container`
<a name="mediastore_CreateContainer_cli_2_topic"></a>

次のコード例は、`create-container` を使用する方法を示しています。

**AWS CLI**  
**コンテナを作成するには**  
次の `create-container` の例では、新しい空のコンテナを作成します。  

```
aws mediastore create-container --container-name ExampleContainer
```
出力:  

```
{
    "Container": {
        "AccessLoggingEnabled": false,
        "CreationTime": 1563557265,
        "Name": "ExampleContainer",
        "Status": "CREATING",
        "ARN": "arn:aws:mediastore:us-west-2:111122223333:container/ExampleContainer"
    }
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Creating a Container](https://docs.aws.amazon.com/mediastore/latest/ug/containers-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateContainer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/create-container.html)」を参照してください。

### `delete-container-policy`
<a name="mediastore_DeleteContainerPolicy_cli_2_topic"></a>

次のコード例は、`delete-container-policy` を使用する方法を示しています。

**AWS CLI**  
**コンテナポリシーを削除するには**  
次の `delete-container-policy` の例では、指定されたコンテナに割り当てられたポリシーを削除します。ポリシーが削除されると、 AWS Elemental MediaStore は自動的にデフォルトのポリシーをコンテナに割り当てます。  

```
aws mediastore delete-container-policy \
    --container-name LiveEvents
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore API reference*」の「[DeleteContainerPolicy](https://docs.aws.amazon.com/mediastore/latest/apireference/API_DeleteContainerPolicy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteContainerPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/delete-container-policy.html)」を参照してください。

### `delete-container`
<a name="mediastore_DeleteContainer_cli_2_topic"></a>

次のコード例は、`delete-container` を使用する方法を示しています。

**AWS CLI**  
**コンテナを削除するには**  
次の `delete-container` の例では、指定されたコンテナを削除します。コンテナにオブジェクトが含まれていない場合に限り、コンテナを削除できます。  

```
aws mediastore delete-container \
    --container-name=ExampleLiveDemo
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Deleting a Container](https://docs.aws.amazon.com/mediastore/latest/ug/containers-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteContainer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/delete-container.html)」を参照してください。

### `delete-cors-policy`
<a name="mediastore_DeleteCorsPolicy_cli_2_topic"></a>

次のコード例は、`delete-cors-policy` を使用する方法を示しています。

**AWS CLI**  
**CORS ポリシーを削除するには**  
次の `delete-cors-policy` の例では、指定されたコンテナに割り当てられたクロスオリジンリソース共有 (CORS) ポリシーを削除します。  

```
aws mediastore delete-cors-policy \
    --container-name ExampleContainer
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Deleting a CORS Policy](https://docs.aws.amazon.com/mediastore/latest/ug/cors-policy-deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCorsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/delete-cors-policy.html)」を参照してください。

### `delete-lifecycle-policy`
<a name="mediastore_DeleteLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`delete-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのライフサイクルポリシーを削除するには**  
次の `delete-lifecycle-policy` の例では、指定されたコンテナにアタッチされたオブジェクトライフサイクルポリシーを削除します。この変更が有効になるまでに、最大 20 分かかります。  

```
aws mediastore delete-lifecycle-policy \
    --container-name LiveEvents
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Deleting an Object Lifecycle Policy](https://docs.aws.amazon.com/mediastore/latest/ug/policies-object-lifecycle-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/delete-lifecycle-policy.html)」を参照してください。

### `describe-container`
<a name="mediastore_DescribeContainer_cli_2_topic"></a>

次のコード例は、`describe-container` を使用する方法を示しています。

**AWS CLI**  
**コンテナの詳細を表示するには**  
次の `describe-container` の例では、指定されたコンテナの詳細を表示します。  

```
aws mediastore describe-container \
    --container-name ExampleContainer
```
出力:  

```
{
    "Container": {
        "CreationTime": 1563558086,
        "AccessLoggingEnabled": false,
        "ARN": "arn:aws:mediastore:us-west-2:111122223333:container/ExampleContainer",
        "Status": "ACTIVE",
        "Name": "ExampleContainer",
        "Endpoint": "https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com"
    }
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing the Details for a Container](https://docs.aws.amazon.com/mediastore/latest/ug/containers-view-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeContainer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/describe-container.html)」を参照してください。

### `describe-object`
<a name="mediastore_DescribeObject_cli_2_topic"></a>

次のコード例は、`describe-object` を使用する方法を示しています。

**AWS CLI**  
**特定のコンテナに含まれているオブジェクトとフォルダのリストを表示するには**  
次の `describe-object` の例では、特定のコンテナに保存されている項目 (オブジェクトとフォルダ) を表示します。  

```
aws mediastore-data describe-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path /folder_name/file1234.jpg
```
出力:  

```
{
    "ContentType": "image/jpeg",
    "LastModified": "Fri, 19 Jul 2019 21:32:20 GMT",
    "ContentLength": "2307346",
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3"
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing the Details of an Object](https://docs.aws.amazon.com/mediastore/latest/ug/objects-view-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/describe-object.html)」を参照してください。

### `get-container-policy`
<a name="mediastore_GetContainerPolicy_cli_2_topic"></a>

次のコード例は、`get-container-policy` を使用する方法を示しています。

**AWS CLI**  
**コンテナポリシーを表示するには**  
次の `get-container-policy` の例では、指定されたコンテナのリソースベースのポリシーを表示します。  

```
aws mediastore get-container-policy \
    --container-name ExampleLiveDemo
```
出力:  

```
{
    "Policy": {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Sid": "PublicReadOverHttps",
                "Effect": "Allow",
                "Principal": {
                    "AWS": "arn:aws:iam::111122223333:root"
                },
                "Action": [
                    "mediastore:GetObject",
                    "mediastore:DescribeObject"
                ],
                "Resource": "arn:aws:mediastore:us-west-2:111122223333:container/ExampleLiveDemo/",
                "Condition": {
                    "Bool": {
                        "aws:SecureTransport": "true"
                    }
                }
            }
        ]
    }
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing a Container Policy](https://docs.aws.amazon.com/mediastore/latest/ug/policies-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContainerPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/get-container-policy.html)」を参照してください。

### `get-cors-policy`
<a name="mediastore_GetCorsPolicy_cli_2_topic"></a>

次のコード例は、`get-cors-policy` を使用する方法を示しています。

**AWS CLI**  
**CORS ポリシーを表示するには**  
次の `get-cors-policy` の例では、指定されたコンテナに割り当てられたクロスオリジンリソース共有 (CORS) ポリシーを表示します。  

```
aws mediastore get-cors-policy \
    --container-name ExampleContainer \
    --region us-west-2
```
出力:  

```
{
    "CorsPolicy": [
        {
            "AllowedMethods": [
                "GET",
                "HEAD"
            ],
            "MaxAgeSeconds": 3000,
            "AllowedOrigins": [
                ""
            ],
            "AllowedHeaders": [
                ""
            ]
        }
    ]
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing a CORS Policy](https://docs.aws.amazon.com/mediastore/latest/ug/cors-policy-viewing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCorsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/get-cors-policy.html)」を参照してください。

### `get-lifecycle-policy`
<a name="mediastore_GetLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`get-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのライフサイクルポリシーを表示するには**  
次の `get-lifecycle-policy` の例では、指定されたコンテナにアタッチされたオブジェクトライフサイクルポリシーを表示します。  

```
aws mediastore get-lifecycle-policy \
    --container-name LiveEvents
```
出力:  

```
{
    "LifecyclePolicy": {
        "rules": [
            {
                "definition": {
                    "path": [
                        {
                            "prefix": "Football/"
                        },
                        {
                            "prefix": "Baseball/"
                        }
                    ],
                    "days_since_create": [
                        {
                            "numeric": [
                                ">",
                                28
                            ]
                        }
                    ]
                },
                "action": "EXPIRE"
            }
        ]
    }
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing an Object Lifecycle Policy](https://docs.aws.amazon.com/mediastore/latest/ug/policies-object-lifecycle-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/get-lifecycle-policy.html)」を参照してください。

### `get-object`
<a name="mediastore_GetObject_cli_2_topic"></a>

次のコード例は、`get-object` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトをダウンロードするには**  
次の `get-object` の例では、指定されたエンドポイントにオブジェクトをダウンロードします。  

```
aws mediastore-data get-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path=/folder_name/README.md README.md
```
出力:  

```
{
    "ContentLength": "2307346",
    "ContentType": "image/jpeg",
    "LastModified": "Fri, 19 Jul 2019 21:32:20 GMT",
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3",
    "StatusCode": 200
}
```
**オブジェクトの一部をダウンロードするには**  
次の `get-object` の例では、指定されたエンドポイントにオブジェクトの一部をダウンロードします。  

```
aws mediastore-data get-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path /folder_name/README.md \
    --range="bytes=0-100" README2.md
```
出力:  

```
{
    "StatusCode": 206,
    "ContentRange": "bytes 0-100/2307346",
    "ContentLength": "101",
    "LastModified": "Fri, 19 Jul 2019 21:32:20 GMT",
    "ContentType": "image/jpeg",
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3"
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Downloading an Object](https://docs.aws.amazon.com/mediastore/latest/ug/objects-download.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[GetObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/get-object.html)」を参照してください。**

### `list-containers`
<a name="mediastore_ListContainers_cli_2_topic"></a>

次のコード例は、`list-containers` を使用する方法を示しています。

**AWS CLI**  
**コンテナのリストを表示するには**  
次の `list-containers` の例では、アカウントに関連付けられているすべてのコンテナのリストを表示します。  

```
aws mediastore list-containers
```
出力:  

```
{
    "Containers": [
        {
            "CreationTime": 1505317931,
            "Endpoint": "https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com",
            "Status": "ACTIVE",
            "ARN": "arn:aws:mediastore:us-west-2:111122223333:container/ExampleLiveDemo",
            "AccessLoggingEnabled": false,
            "Name": "ExampleLiveDemo"
        },
        {
            "CreationTime": 1506528818,
            "Endpoint": "https://fffggghhhiiijj.data.mediastore.us-west-2.amazonaws.com",
            "Status": "ACTIVE",
            "ARN": "arn:aws:mediastore:us-west-2:111122223333:container/ExampleContainer",
            "AccessLoggingEnabled": false,
            "Name": "ExampleContainer"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing a List of Containers](https://docs.aws.amazon.com/mediastore/latest/ug/containers-view-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListContainers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/list-containers.html)」を参照してください。

### `list-items`
<a name="mediastore_ListItems_cli_2_topic"></a>

次のコード例は、`list-items` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定のコンテナに含まれているオブジェクトとフォルダのリストを表示するには**  
次の `list-items` の例では、指定されたコンテナに保存されている項目 (オブジェクトとフォルダ) を表示します。  

```
aws mediastore-data list-items \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com
```
出力:  

```
{
    "Items": [
        {
            "ContentType": "image/jpeg",
            "LastModified": 1563571859.379,
            "Name": "filename.jpg",
            "Type": "OBJECT",
            "ETag": "543ab21abcd1a234ab123456a1a2b12345ab12abc12a1234abc1a2bc12345a12",
            "ContentLength": 3784
        },
        {
            "Type": "FOLDER",
            "Name": "ExampleLiveDemo"
        }
    ]
}
```
**例 2: 特定のフォルダに含まれているオブジェクトとフォルダのリストを表示するには**  
次の `list-items` の例では、特定のフォルダに保存されている項目 (オブジェクトとフォルダ) を表示します。  

```
aws mediastore-data list-items \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com
```
出力:  

```
{
    "Items": [
        {
            "ContentType": "image/jpeg",
            "LastModified": 1563571859.379,
            "Name": "filename.jpg",
            "Type": "OBJECT",
            "ETag": "543ab21abcd1a234ab123456a1a2b12345ab12abc12a1234abc1a2bc12345a12",
            "ContentLength": 3784
        },
        {
            "Type": "FOLDER",
            "Name": "ExampleLiveDemo"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing a List of Objects](https://docs.aws.amazon.com/mediastore/latest/ug/objects-view-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/list-items.html)」を参照してください。

### `list-tags-for-resource`
<a name="mediastore_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**コンテナのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定されたコンテナに割り当てられたタグキーと値を表示します。  

```
aws mediastore list-tags-for-resource \
    --resource arn:aws:mediastore:us-west-2:1213456789012:container/ExampleContainer
```
出力:  

```
{
    "Tags": [
        {
            "Value": "Test",
            "Key": "Environment"
        },
        {
            "Value": "West",
            "Key": "Region"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaStore API Reference*」の「[ListTagsForResource](https://docs.aws.amazon.com/mediastore/latest/apireference/API_ListTagsForResource.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/list-tags-for-resource.html)」を参照してください。

### `put-container-policy`
<a name="mediastore_PutContainerPolicy_cli_2_topic"></a>

次のコード例は、`put-container-policy` を使用する方法を示しています。

**AWS CLI**  
**コンテナポリシーを編集するには**  
次の `put-container-policy` の例では、指定されたコンテナに異なるポリシーを割り当てます。この例では、更新されたポリシーが `LiveEventsContainerPolicy.json` という名前のファイルで定義されます。  

```
aws mediastore put-container-policy \
    --container-name LiveEvents \
    --policy file://LiveEventsContainerPolicy.json
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Editing a Container Policy](https://docs.aws.amazon.com/mediastore/latest/ug/policies-edit.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutContainerPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/put-container-policy.html)」を参照してください。

### `put-cors-policy`
<a name="mediastore_PutCorsPolicy_cli_2_topic"></a>

次のコード例は、`put-cors-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: CORS ポリシーを追加するには**  
次の `put-cors-policy` の例では、指定されたコンテナにクロスオリジンリソース共有 (CORS) ポリシーを追加します。CORS ポリシーの内容は、`corsPolicy.json` という名前のファイルにあります。  

```
aws mediastore put-cors-policy \
    --container-name ExampleContainer \
    --cors-policy file://corsPolicy.json
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Adding a CORS Policy to a Container](https://docs.aws.amazon.com/mediastore/latest/ug/cors-policy-adding.html)」を参照してください。  
**例 2: CORS ポリシーを編集するには**  
次の `put-cors-policy` の例では、指定されたコンテナに割り当てられたクロスオリジンリソース共有 (CORS) ポリシーを更新します。更新された CORS ポリシーの内容は、`corsPolicy2.json` という名前のファイルにあります。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Editing a CORS Policy](https://docs.aws.amazon.com/mediastore/latest/ug/cors-policy-editing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutCorsPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/put-cors-policy.html)」を参照してください。

### `put-lifecycle-policy`
<a name="mediastore_PutLifecyclePolicy_cli_2_topic"></a>

次のコード例は、`put-lifecycle-policy` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのライフサイクルポリシーを作成するには**  
次の `put-lifecycle-policy` の例では、指定されたコンテナにオブジェクトライフサイクルポリシーをアタッチします。これにより、サービスがコンテナにオブジェクトを保存すべき期間を指定できます。MediaStore は、`LiveEventsLifecyclePolicy.json` という名前のファイルにあるポリシーに示されているように、有効期限に達するとコンテナ内のオブジェクトを削除します。  

```
aws mediastore put-lifecycle-policy \
    --container-name ExampleContainer \
    --lifecycle-policy file://ExampleLifecyclePolicy.json
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Adding an Object Lifecycle Policy to a Container](https://docs.aws.amazon.com/mediastore/latest/ug/policies-object-lifecycle-add.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLifecyclePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/put-lifecycle-policy.html)」を参照してください。

### `put-object`
<a name="mediastore_PutObject_cli_2_topic"></a>

次のコード例は、`put-object` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトをアップロードするには**  
次の `put-object` の例では、指定されたコンテナにオブジェクトをアップロードします。オブジェクトをコンテナ内に保存するフォルダパスを指定できます。フォルダが既に存在する場合、 AWS Elemental MediaStore はオブジェクトをフォルダに保存します。フォルダが存在しない場合は、フォルダが自動的に作成されて、そのフォルダにオブジェクトが保存されます。  

```
aws mediastore-data put-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --body README.md \
    --path /folder_name/README.md \
    --cache-control "max-age=6, public" \
    --content-type binary/octet-stream
```
出力:  

```
{
    "ContentSHA256": "74b5fdb517f423ed750ef214c44adfe2be36e37d861eafe9c842cbe1bf387a9d",
    "StorageClass": "TEMPORAL",
    "ETag": "af3e4731af032167a106015d1f2fe934e68b32ed1aa297a9e325f5c64979277b"
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Uploading an Object](https://docs.aws.amazon.com/mediastore/latest/ug/objects-upload.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/put-object.html)」を参照してください。

### `start-access-logging`
<a name="mediastore_StartAccessLogging_cli_2_topic"></a>

次のコード例は、`start-access-logging` を使用する方法を示しています。

**AWS CLI**  
**コンテナでアクセスログ記録を有効にするには**  
次の `start-access-logging` の例では、指定されたコンテナでアクセスログ記録を有効にします。  

```
aws mediastore start-access-logging \
    --container-name LiveEvents
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Enabling Access Logging for a Container](https://docs.aws.amazon.com/mediastore/latest/ug/monitoring-cloudwatch-logs-enable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartAccessLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/start-access-logging.html)」を参照してください。

### `stop-access-logging`
<a name="mediastore_StopAccessLogging_cli_2_topic"></a>

次のコード例は、`stop-access-logging` を使用する方法を示しています。

**AWS CLI**  
**コンテナでアクセスログ記録を無効にするには**  
次の `stop-access-logging` の例では、指定されたコンテナでアクセスログ記録を無効にします。  

```
aws mediastore stop-access-logging \
    --container-name LiveEvents
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Disabling Access Logging for a Container](https://docs.aws.amazon.com/mediastore/latest/ug/monitoring-cloudwatch-logs-disable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopAccessLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/stop-access-logging.html)」を参照してください。

### `tag-resource`
<a name="mediastore_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**コンテナにタグを追加するには**  
次の `tag-resource` の例では、指定されたコンテナにタグキーと値を追加します。  

```
aws mediastore tag-resource \
    --resource arn:aws:mediastore:us-west-2:123456789012:container/ExampleContainer \
    --tags '[{"Key": "Region", "Value": "West"}, {"Key": "Environment", "Value": "Test"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore API Reference*」の「[TagResource](https://docs.aws.amazon.com/mediastore/latest/apireference/API_TagResource.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="mediastore_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**コンテナからタグを削除するには**  
次の `untag-resource` の例では、指定されたタグキーとその関連付けられた値をコンテナから削除します。  

```
aws mediastore untag-resource \
    --resource arn:aws:mediastore:us-west-2:123456789012:container/ExampleContainer \
    --tag-keys Region
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaStore API Reference*」の「[UntagResource](https://docs.aws.amazon.com/mediastore/latest/apireference/API_UntagResource.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore/untag-resource.html)」を参照してください。

# を使用した Amazon EMR の例 AWS CLI
<a name="cli_2_emr_code_examples"></a>

次のコード例は、Amazon EMR AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-instance-fleet`
<a name="emr_AddInstanceFleet_cli_2_topic"></a>

次のコード例は、`add-instance-fleet` を使用する方法を示しています。

**AWS CLI**  
**タスクインスタンスフリートをクラスターに追加するには**  
この例では、指定されたクラスターに新しいタスクインスタンスフリートを追加します。  
コマンド:  

```
aws emr add-instance-fleet --cluster-id 'j-12ABCDEFGHI34JK' --instance-fleet  InstanceFleetType=TASK,TargetSpotCapacity=1,LaunchSpecifications={SpotSpecification='{TimeoutDurationMinutes=20,TimeoutAction=TERMINATE_CLUSTER}'},InstanceTypeConfigs=['{InstanceType=m3.xlarge,BidPrice=0.5}']
```
出力:  

```
{
   "ClusterId": "j-12ABCDEFGHI34JK",
   "InstanceFleetId": "if-23ABCDEFGHI45JJ"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddInstanceFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/add-instance-fleet.html)」を参照してください。

### `add-steps`
<a name="emr_AddSteps_cli_2_topic"></a>

次のコード例は、`add-steps` を使用する方法を示しています。

**AWS CLI**  
**1. クラスターにカスタム JAR ステップを追加するには**  
コマンド:  

```
aws emr add-steps --cluster-id j-XXXXXXXX --steps Type=CUSTOM_JAR,Name=CustomJAR,ActionOnFailure=CONTINUE,Jar=s3://amzn-s3-demo-bucket/mytest.jar,Args=arg1,arg2,arg3 Type=CUSTOM_JAR,Name=CustomJAR,ActionOnFailure=CONTINUE,Jar=s3://amzn-s3-demo-bucket/mytest.jar,MainClass=mymainclass,Args=arg1,arg2,arg3
```
必須パラメータ:  

```
Jar
```
任意指定のパラメータ:  

```
Type, Name, ActionOnFailure, Args
```
出力:  

```
{
    "StepIds":[
        "s-XXXXXXXX",
        "s-YYYYYYYY"
    ]
}
```
**2。ストリーミングステップをクラスターに追加するには**  
コマンド:  

```
aws emr add-steps --cluster-id j-XXXXXXXX --steps Type=STREAMING,Name='Streaming Program',ActionOnFailure=CONTINUE,Args=[-files,s3://elasticmapreduce/samples/wordcount/wordSplitter.py,-mapper,wordSplitter.py,-reducer,aggregate,-input,s3://elasticmapreduce/samples/wordcount/input,-output,s3://amzn-s3-demo-bucket/wordcount/output]
```
必須パラメータ:  

```
Type, Args
```
任意指定のパラメータ:  

```
Name, ActionOnFailure
```
JSON と同等のもの (Step.json の内容):  

```
 [
  {
    "Name": "JSON Streaming Step",
    "Args": ["-files","s3://elasticmapreduce/samples/wordcount/wordSplitter.py","-mapper","wordSplitter.py","-reducer","aggregate","-input","s3://elasticmapreduce/samples/wordcount/input","-output","s3://amzn-s3-demo-bucket/wordcount/output"],
    "ActionOnFailure": "CONTINUE",
    "Type": "STREAMING"
  }
]
```
注: JSON 引数には、リスト内の独自の項目としてオプションと値を含める必要があります。  
コマンド (step.json を使用):  

```
aws emr add-steps --cluster-id j-XXXXXXXX --steps file://./step.json
```
出力:  

```
{
    "StepIds":[
        "s-XXXXXXXX",
        "s-YYYYYYYY"
    ]
}
```
**3. 複数のファイルを含むストリーミングステップをクラスターに追加するには (JSON のみ)**  
JSON (multiplefiles.json):  

```
[
  {
     "Name": "JSON Streaming Step",
     "Type": "STREAMING",
     "ActionOnFailure": "CONTINUE",
     "Args": [
         "-files",
         "s3://amzn-s3-demo-bucket/mapper.py,s3://amzn-s3-demo-bucket/reducer.py",
         "-mapper",
         "mapper.py",
         "-reducer",
         "reducer.py",
         "-input",
         "s3://amzn-s3-demo-bucket/input",
         "-output",
         "s3://amzn-s3-demo-bucket/output"]
  }
]
```
コマンド:  

```
aws emr add-steps --cluster-id j-XXXXXXXX  --steps file://./multiplefiles.json
```
必須パラメータ:  

```
Type, Args
```
任意指定のパラメータ:  

```
Name, ActionOnFailure
```
出力:  

```
{
    "StepIds":[
        "s-XXXXXXXX",
    ]
}
```
**4. クラスターに Hive ステップを追加するには**  
コマンド:  

```
aws emr add-steps --cluster-id j-XXXXXXXX --steps Type=HIVE,Name='Hive program',ActionOnFailure=CONTINUE,Args=[-f,s3://amzn-s3-demo-bucket/myhivescript.q,-d,INPUT=s3://amzn-s3-demo-bucket/myhiveinput,-d,OUTPUT=s3://amzn-s3-demo-bucket/myhiveoutput,arg1,arg2] Type=HIVE,Name='Hive steps',ActionOnFailure=TERMINATE_CLUSTER,Args=[-f,s3://elasticmapreduce/samples/hive-ads/libs/model-build.q,-d,INPUT=s3://elasticmapreduce/samples/hive-ads/tables,-d,OUTPUT=s3://amzn-s3-demo-bucket/hive-ads/output/2014-04-18/11-07-32,-d,LIBS=s3://elasticmapreduce/samples/hive-ads/libs]
```
必須パラメータ:  

```
Type, Args
```
任意指定のパラメータ:  

```
Name, ActionOnFailure
```
出力:  

```
{
    "StepIds":[
        "s-XXXXXXXX",
        "s-YYYYYYYY"
    ]
}
```
**5。クラスターに Pig ステップを追加するには**  
コマンド:  

```
aws emr add-steps --cluster-id j-XXXXXXXX --steps Type=PIG,Name='Pig program',ActionOnFailure=CONTINUE,Args=[-f,s3://amzn-s3-demo-bucket/mypigscript.pig,-p,INPUT=s3://amzn-s3-demo-bucket/mypiginput,-p,OUTPUT=s3://amzn-s3-demo-bucket/mypigoutput,arg1,arg2] Type=PIG,Name='Pig program',Args=[-f,s3://elasticmapreduce/samples/pig-apache/do-reports2.pig,-p,INPUT=s3://elasticmapreduce/samples/pig-apache/input,-p,OUTPUT=s3://amzn-s3-demo-bucket/pig-apache/output,arg1,arg2]
```
必須パラメータ:  

```
Type, Args
```
任意指定のパラメータ:  

```
Name, ActionOnFailure
```
出力:  

```
{
    "StepIds":[
        "s-XXXXXXXX",
        "s-YYYYYYYY"
    ]
}
```
**6。Impala ステップをクラスターに追加するには**  
コマンド:  

```
aws emr add-steps --cluster-id j-XXXXXXXX --steps Type=IMPALA,Name='Impala program',ActionOnFailure=CONTINUE,Args=--impala-script,s3://myimpala/input,--console-output-path,s3://myimpala/output
```
必須パラメータ:  

```
Type, Args
```
任意指定のパラメータ:  

```
Name, ActionOnFailure
```
出力:  

```
{
    "StepIds":[
        "s-XXXXXXXX",
        "s-YYYYYYYY"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddSteps](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/add-steps.html)」を参照してください。

### `add-tags`
<a name="emr_AddTags_cli_2_topic"></a>

次のコード例は、`add-tags` を使用する方法を示しています。

**AWS CLI**  
**1. クラスターにタグを追加するには**  
コマンド:  

```
aws emr add-tags --resource-id j-xxxxxxx --tags name="John Doe" age=29 sex=male address="123 East NW Seattle"
```
出力:  

```
None
```
**2。クラスターのタグを一覧表示するには**  
--コマンド:  

```
aws emr describe-cluster --cluster-id j-XXXXXXYY --query Cluster.Tags
```
出力:  

```
[
    {
        "Value": "male",
        "Key": "sex"
    },
    {
        "Value": "123 East NW Seattle",
        "Key": "address"
    },
    {
        "Value": "John Doe",
        "Key": "name"
    },
    {
        "Value": "29",
        "Key": "age"
    }
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/add-tags.html)」を参照してください。

### `create-cluster-examples`
<a name="emr_CreateClusterExamples_cli_2_topic"></a>

次のコード例は、`create-cluster-examples` を使用する方法を示しています。

**AWS CLI**  
次の例のほとんどは、Amazon EMR サービスロールと Amazon EC2 インスタンスプロファイルを指定していることを前提としています。これを行っていない場合は、必要な各 IAM ロールを指定するか、クラスターの作成時に `--use-default-roles` パラメータを使用する必要があります。IAM ロールの指定の詳細については、[「Amazon EMR 管理ガイド」の「Configure IAM Roles for Amazon EMR Permissions to AWS Services](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-iam-roles.html)」を参照してください。 **  
**例 1: クラスターを作成するには**  
以下の `create-cluster` の例は、シンプルな EMR クラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.14.0 \
    --instance-type m4.large \
    --instance-count 2
```
このコマンドでは何も出力されません。  
**例 2: デフォルトの ServiceRole ロールと InstanceProfile ロールを使用して Amazon EMR クラスターを作成するには**  
次の `create-cluster` の例では、`--instance-groups` 設定を使用する Amazon EMR クラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.14.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
**例 3: インスタンスフリートを使用する Amazon EMR クラスターを作成するには**  
次の `create-cluster` の例では、`--instance-fleets` 設定を使用する Amazon EMR クラスターを作成し、フリートごとに 2 つのインスタンスタイプと 2 つの EC2 サブネットを指定します。  

```
aws emr create-cluster \
    --release-label emr-5.14.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole,SubnetIds=['subnet-ab12345c','subnet-de67890f'] \
    --instance-fleets InstanceFleetType=MASTER,TargetOnDemandCapacity=1,InstanceTypeConfigs=['{InstanceType=m4.large}'] InstanceFleetType=CORE,TargetSpotCapacity=11,InstanceTypeConfigs=['{InstanceType=m4.large,BidPrice=0.5,WeightedCapacity=3}','{InstanceType=m4.2xlarge,BidPrice=0.9,WeightedCapacity=5}'],LaunchSpecifications={SpotSpecification='{TimeoutDurationMinutes=120,TimeoutAction=SWITCH_TO_ON_DEMAND}'}
```
**例 4: デフォルトロールを使用してクラスターを作成するには**  
次の `create-cluster` 例では、`--use-default-roles` パラメータを使用して、デフォルトのサービスロールとインスタンスプロファイルを指定します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --use-default-roles \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 5: クラスターを作成し、インストールするアプリケーションを指定するには**  
次の `create-cluster` の例では、`--applications` パラメータを使用して、Amazon EMR がインストールするアプリケーションを指定します。この例では、Hadoop、Hive、Pig をインストールします。  

```
aws emr create-cluster \
    --applications Name=Hadoop Name=Hive Name=Pig \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 6: Spark を含むクラスターを作成するには**  
次の例では、Spark をインストールします。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --applications Name=Spark \
    --ec2-attributes KeyName=myKey \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 7: クラスターインスタンスに使用するカスタム AMI を指定するには**  
次の `create-cluster` の例では、ID `ami-a518e6df` を持つ Amazon Linux AMI に基づいてクラスターインスタンスを作成します。  

```
aws emr create-cluster \
    --name "Cluster with My Custom AMI" \
    --custom-ami-id ami-a518e6df \
    --ebs-root-volume-size 20 \
    --release-label emr-5.9.0 \
    --use-default-roles \
    --instance-count 2 \
    --instance-type m4.large
```
**例 8: アプリケーション設定をカスタマイズするには**  
次の例では、`--configurations` パラメータを使用して、Hadoop のアプリケーションのカスタマイズを含む JSON 設定ファイルを指定します。詳細については、「Amazon EMR リリースガイド」の「[アプリケーションの設定](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-configure-apps.html)」を参照してください。  
`configurations.json` の内容:  

```
[
    {
       "Classification": "mapred-site",
       "Properties": {
           "mapred.tasktracker.map.tasks.maximum": 2
       }
    },
    {
        "Classification": "hadoop-env",
        "Properties": {},
        "Configurations": [
            {
                "Classification": "export",
                "Properties": {
                    "HADOOP_DATANODE_HEAPSIZE": 2048,
                    "HADOOP_NAMENODE_OPTS": "-XX:GCTimeRatio=19"
                }
            }
        ]
    }
]
```
以下の例では、ローカルファイルとして `configurations.json` を参照します。  

```
aws emr create-cluster \
    --configurations file://configurations.json \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
次の例では、Amazon S3 のファイルとして `configurations.json` を参照します。  

```
aws emr create-cluster \
    --configurations https://s3.amazonaws.com/amzn-s3-demo-bucket/configurations.json \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 9: マスター、コア、タスクインスタンスグループを使用してクラスターを作成するには**  
次の `create-cluster` の例では、`--instance-groups` を使用して、マスター、コア、タスクインスタンスグループに使用する EC2 インスタンスのタイプと数を指定します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --instance-groups Name=Master,InstanceGroupType=MASTER,InstanceType=m4.large,InstanceCount=1 Name=Core,InstanceGroupType=CORE,InstanceType=m4.large,InstanceCount=2 Name=Task,InstanceGroupType=TASK,InstanceType=m4.large,InstanceCount=2
```
**例 10: すべてのステップを完了した後にクラスターを終了するように指定するには**  
次の `create-cluster` 例では、`--auto-terminate` を使用して、すべてのステップを完了した後にクラスターを自動的にシャットダウンするように指定します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large  InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 11: Amazon EC2 キーペア、ネットワーク設定、セキュリティグループなどのクラスター設定の詳細を指定するには**  
次の `create-cluster` の例では、`myKey` という名前の Amazon EC2 キーペアと `myProfile` という名前のカスタマイズされたインスタンスプロファイルを持つクラスターを作成します。キーペアは、クラスターノード、ほとんどの場合プライマリノードへの SSH 接続を承認するために使用されます。詳細は、「*Amazon EMR 管理ガイド*」の「[SSH 認証情報に EC2 キーペアを使用する](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-access-ssh.html)」を参照してください。  

```
aws emr create-cluster \
    --ec2-attributes KeyName=myKey,InstanceProfile=myProfile \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
次の例では、Amazon VPC サブネットにクラスターを作成します。  

```
aws emr create-cluster \
    --ec2-attributes SubnetId=subnet-xxxxx \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
次の例では、`us-east-1b` アベイラビリティーゾーンにクラスターを作成します。  

```
aws emr create-cluster \
    --ec2-attributes AvailabilityZone=us-east-1b \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
次の例では、クラスターを作成し、Amazon EMR マネージドセキュリティグループのみを指定します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --service-role myServiceRole \
    --ec2-attributes InstanceProfile=myRole,EmrManagedMasterSecurityGroup=sg-master1,EmrManagedSlaveSecurityGroup=sg-slave1 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
次の例では、クラスターを作成し、追加の Amazon EC2 セキュリティグループのみを指定します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --service-role myServiceRole \
    --ec2-attributes InstanceProfile=myRole,AdditionalMasterSecurityGroups=[sg-addMaster1,sg-addMaster2,sg-addMaster3,sg-addMaster4],AdditionalSlaveSecurityGroups=[sg-addSlave1,sg-addSlave2,sg-addSlave3,sg-addSlave4] \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
次の例では、クラスターを作成し、EMR マネージドセキュリティグループと追加のセキュリティグループを指定します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --service-role myServiceRole \
    --ec2-attributes InstanceProfile=myRole,EmrManagedMasterSecurityGroup=sg-master1,EmrManagedSlaveSecurityGroup=sg-slave1,AdditionalMasterSecurityGroups=[sg-addMaster1,sg-addMaster2,sg-addMaster3,sg-addMaster4],AdditionalSlaveSecurityGroups=[sg-addSlave1,sg-addSlave2,sg-addSlave3,sg-addSlave4] \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
次の例では、VPC プライベートサブネットにクラスターを作成し、特定の Amazon EC2 セキュリティグループを使用して Amazon EMR サービスアクセスを有効にします。これは、プライベートサブネットのクラスターに必要です。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --service-role myServiceRole \
    --ec2-attributes InstanceProfile=myRole,ServiceAccessSecurityGroup=sg-service-access,EmrManagedMasterSecurityGroup=sg-master,EmrManagedSlaveSecurityGroup=sg-slave \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
次の例では、ローカルに保存されている `ec2_attributes.json` という名前の JSON ファイルを使用してセキュリティグループ設定パラメータを指定します。注: JSON 引数には、リスト内の独自の項目としてオプションと値を含める必要があります。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --service-role myServiceRole \
    --ec2-attributes file://ec2_attributes.json  \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
`ec2_attributes.json` の内容:  

```
[
    {
        "SubnetId": "subnet-xxxxx",
        "KeyName": "myKey",
        "InstanceProfile":"myRole",
        "EmrManagedMasterSecurityGroup": "sg-master1",
        "EmrManagedSlaveSecurityGroup": "sg-slave1",
        "ServiceAccessSecurityGroup": "sg-service-access",
        "AdditionalMasterSecurityGroups": ["sg-addMaster1","sg-addMaster2","sg-addMaster3","sg-addMaster4"],
        "AdditionalSlaveSecurityGroups": ["sg-addSlave1","sg-addSlave2","sg-addSlave3","sg-addSlave4"]
    }
]
```
**例 12: デバッグを有効にしてログ URI を指定するには**  
次の `create-cluster` の例では、`--enable-debugging` パラメータを使用しており、Amazon EMR コンソールのデバッグツールを使用してログファイルをより簡単に表示できます。`--log-uri` パラメータは `--enable-debugging` で必須です。  

```
aws emr create-cluster \
    --enable-debugging \
    --log-uri s3://amzn-s3-demo-bucket/myLog \
    --release-label emr-5.9.0 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 13: クラスターの作成時にタグを追加するには**  
タグは、クラスターの特定と管理に役立つキーと値のペアです。次の `create-cluster` の例では、`--tags` パラメータを使用してクラスターに 3 つのタグを作成します。1 つ目はキー名 `name` と値 `Shirley Rodriguez`、2 つ目はキー名 `age` と値 `29`、3 つ目のタグはキー名 `department` と値 `Analytics` です。  

```
aws emr create-cluster \
    --tags name="Shirley Rodriguez" age=29 department="Analytics" \
    --release-label emr-5.32.0 \
    --instance-type m5.xlarge \
    --instance-count 3 \
    --use-default-roles
```
次の例では、クラスターに適用されるタグを一覧表示します。  

```
aws emr describe-cluster \
    --cluster-id j-XXXXXXYY \
    --query Cluster.Tags
```
**例 14: 暗号化やその他のセキュリティ機能を有効にするセキュリティ設定を使用するには**  
次の `create-cluster` の例では、`--security-configuration` パラメータを使用して EMR クラスターのセキュリティ設定を指定します。Amazon EMR バージョン 4.8.0 以降では、セキュリティ設定を使用できます。  

```
aws emr create-cluster \
    --instance-type m4.large \
    --release-label emr-5.9.0 \
    --security-configuration mySecurityConfiguration
```
**例 15: インスタンスグループに設定された追加の EBS ストレージボリュームを持つクラスターを作成するには**  
追加の EBS ボリュームを指定する場合は、次の引数が必要です。`EbsBlockDeviceConfigs` が指定されている場合、`VolumeType`、`SizeInGB`。  
次の `create-cluster` の例では、コアインスタンスグループの EC2 インスタンスに複数の EBS ボリュームがアタッチされたクラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0  \
    --use-default-roles \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=d2.xlarge 'InstanceGroupType=CORE,InstanceCount=2,InstanceType=d2.xlarge,EbsConfiguration={EbsOptimized=true,EbsBlockDeviceConfigs=[{VolumeSpecification={VolumeType=gp2,SizeInGB=100}},{VolumeSpecification={VolumeType=io1,SizeInGB=100,Iops=100},VolumesPerInstance=4}]}' \
    --auto-terminate
```
次の例では、マスターインスタンスグループの EC2 インスタンスに複数の EBS ボリュームがアタッチされたクラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --use-default-roles \
    --instance-groups 'InstanceGroupType=MASTER, InstanceCount=1, InstanceType=d2.xlarge, EbsConfiguration={EbsOptimized=true, EbsBlockDeviceConfigs=[{VolumeSpecification={VolumeType=io1, SizeInGB=100, Iops=100}},{VolumeSpecification={VolumeType=standard,SizeInGB=50},VolumesPerInstance=3}]}' InstanceGroupType=CORE,InstanceCount=2,InstanceType=d2.xlarge \
    --auto-terminate
```
**例 16: 自動スケーリングポリシーを使用してクラスターを作成するには**  
Amazon EMR バージョン 4.0 以降を使用して、コアインスタンスグループとタスクインスタンスグループに自動スケーリングポリシーをアタッチできます。自動スケーリングポリシーは、Amazon CloudWatch メトリクスに応答して EC2 インスタンスを動的に追加および削除します。詳細については、「*Amazon EMR 管理ガイド*」の「Amazon EMR で自動スケーリングを使用する <https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-automatic-scaling.html>`\$1」を参照してください。  
自動スケーリングポリシーをアタッチする場合は、`--auto-scaling-role EMR_AutoScaling_DefaultRole` を使用して自動スケーリングのデフォルトロールを指定する必要があります。  
次の `create-cluster` の例では、スケーリングポリシー設定を指定する JSON 構造が埋め込まれた `AutoScalingPolicy` 引数を使用して、`CORE` インスタンスグループの自動スケーリングポリシーを指定します。JSON 構造が埋め込まれたインスタンスグループには、引数のコレクション全体が一重引用符で囲まれている必要があります。JSON 構造が埋め込まれていないインスタンスグループでは、単一引用符の使用はオプションです。  

```
aws emr create-cluster
    --release-label emr-5.9.0 \
    --use-default-roles --auto-scaling-role EMR_AutoScaling_DefaultRole \
    --instance-groups InstanceGroupType=MASTER,InstanceType=d2.xlarge,InstanceCount=1 'InstanceGroupType=CORE,InstanceType=d2.xlarge,InstanceCount=2,AutoScalingPolicy={Constraints={MinCapacity=1,MaxCapacity=5},Rules=[{Name=TestRule,Description=TestDescription,Action={Market=ON_DEMAND,SimpleScalingPolicyConfiguration={AdjustmentType=EXACT_CAPACITY,ScalingAdjustment=2}},Trigger={CloudWatchAlarmDefinition={ComparisonOperator=GREATER_THAN,EvaluationPeriods=5,MetricName=TestMetric,Namespace=EMR,Period=3,Statistic=MAXIMUM,Threshold=4.5,Unit=NONE,Dimensions=[{Key=TestKey,Value=TestValue}]}}}]}'
```
次の例では、JSON ファイルの `instancegroupconfig.json` を使用して、クラスター内のすべてのインスタンスグループの設定を指定します。JSON ファイルは、コアインスタンスグループの自動スケーリングポリシー設定を指定します。  

```
aws emr create-cluster \
    --release-label emr-5.9.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --instance-groups file://myfolder/instancegroupconfig.json \
    --auto-scaling-role EMR_AutoScaling_DefaultRole
```
`instancegroupconfig.json` の内容:  

```
[
    {
        "InstanceCount": 1,
        "Name": "MyMasterIG",
        "InstanceGroupType": "MASTER",
        "InstanceType": "m4.large"
    },
    {
        "InstanceCount": 2,
        "Name": "MyCoreIG",
        "InstanceGroupType": "CORE",
        "InstanceType": "m4.large",
        "AutoScalingPolicy": {
            "Constraints": {
                "MinCapacity": 2,
                "MaxCapacity": 10
            },
            "Rules": [
                {
                    "Name": "Default-scale-out",
                    "Description": "Replicates the default scale-out rule in the console for YARN memory.",
                    "Action": {
                        "SimpleScalingPolicyConfiguration": {
                            "AdjustmentType": "CHANGE_IN_CAPACITY",
                            "ScalingAdjustment": 1,
                            "CoolDown": 300
                        }
                    },
                    "Trigger": {
                        "CloudWatchAlarmDefinition": {
                            "ComparisonOperator": "LESS_THAN",
                            "EvaluationPeriods": 1,
                            "MetricName": "YARNMemoryAvailablePercentage",
                            "Namespace": "AWS/ElasticMapReduce",
                            "Period": 300,
                            "Threshold": 15,
                            "Statistic": "AVERAGE",
                            "Unit": "PERCENT",
                            "Dimensions": [
                                {
                                    "Key": "JobFlowId",
                                    "Value": "${emr.clusterId}"
                                }
                            ]
                        }
                    }
                }
            ]
        }
    }
]
```
**例 17: クラスターを作成するときにカスタム JAR ステップを追加する**  
次の `create-cluster` の例では、Amazon S3 に保存されている JAR ファイルを指定してステップを追加します。ステップではクラスターに作業を送信します。JAR ファイルで定義されたメイン関数は、EC2 インスタンスがプロビジョニングされ、ブートストラップアクションが実行され、アプリケーションがインストールされた後に実行されます。これらのステップは `Type=CUSTOM_JAR` を使用して指定します。  
カスタム JAR ステップには、JAR のパスとファイル名を指定する `Jar=` パラメータが必要です。オプションのパラメータは、`Type`、`Name`、`Args`、`ActionOnFailure`、および `MainClass` です。メインクラスを指定しない場合、JAR ファイルはマニフェストファイルで `Main-Class` を指定する必要があります。  

```
aws emr create-cluster \
    --steps Type=CUSTOM_JAR,Name=CustomJAR,ActionOnFailure=CONTINUE,Jar=s3://amzn-s3-demo-bucket/mytest.jar,Args=arg1,arg2,arg3 Type=CUSTOM_JAR,Name=CustomJAR,ActionOnFailure=CONTINUE,Jar=s3://amzn-s3-demo-bucket/mytest.jar,MainClass=mymainclass,Args=arg1,arg2,arg3  \
    --release-label emr-5.3.1 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 18: クラスターの作成時にストリーミングステップを追加するには**  
次の `create-cluster` の例では、すべてのステップの実行後に終了するストリーミングステップをクラスターに追加します。ストリーミングステップにはパラメータ `Type` と `Args` が必要です。ストリーミングステップのオプションパラメータは `Name` および `ActionOnFailure` です。  
次の例はステップインラインを指定します。  

```
aws emr create-cluster \
    --steps Type=STREAMING,Name='Streaming Program',ActionOnFailure=CONTINUE,Args=[-files,s3://elasticmapreduce/samples/wordcount/wordSplitter.py,-mapper,wordSplitter.py,-reducer,aggregate,-input,s3://elasticmapreduce/samples/wordcount/input,-output,s3://amzn-s3-demo-bucket/wordcount/output] \
    --release-label emr-5.3.1 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
次の例では、`multiplefiles.json` という名前のローカルに保存された JSON 設定ファイルを使用します。JSON 設定では、複数のファイルを指定します。ステップ内で複数のファイルを指定するには、JSON 設定ファイルを使用してステップを指定する必要があります。JSON 引数には、リスト内の独自の項目としてオプションと値を含める必要があります。  

```
aws emr create-cluster \
    --steps file://./multiplefiles.json \
    --release-label emr-5.9.0  \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
`multiplefiles.json` の内容:  

```
[
    {
        "Name": "JSON Streaming Step",
        "Args": [
            "-files",
            "s3://elasticmapreduce/samples/wordcount/wordSplitter.py",
            "-mapper",
            "wordSplitter.py",
            "-reducer",
            "aggregate",
            "-input",
            "s3://elasticmapreduce/samples/wordcount/input",
            "-output",
            "s3://amzn-s3-demo-bucket/wordcount/output"
        ],
        "ActionOnFailure": "CONTINUE",
        "Type": "STREAMING"
    }
]
```
**例 19: クラスターの作成時に Hive ステップを追加するには**  
次の例では、クラスターを作成するときに Hive ステップを追加します。Hive ステップには、パラメータ `Type` と `Args` が必要です。Hive ステップのオプションパラメータは `Name` と `ActionOnFailure`です。  

```
aws emr create-cluster \
    --steps Type=HIVE,Name='Hive program',ActionOnFailure=CONTINUE,ActionOnFailure=TERMINATE_CLUSTER,Args=[-f,s3://elasticmapreduce/samples/hive-ads/libs/model-build.q,-d,INPUT=s3://elasticmapreduce/samples/hive-ads/tables,-d,OUTPUT=s3://amzn-s3-demo-bucket/hive-ads/output/2014-04-18/11-07-32,-d,LIBS=s3://elasticmapreduce/samples/hive-ads/libs] \
    --applications Name=Hive \
    --release-label emr-5.3.1 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
**例 20: クラスターの作成時に Pig ステップを追加するには**  
次の例では、クラスターを作成するときに Pig ステップを追加します。Pig ステップに必要なパラメータは `Type` と `Args` です。Pig ステップのオプションパラメータは `Name` と `ActionOnFailure` です。  

```
aws emr create-cluster \
    --steps Type=PIG,Name='Pig program',ActionOnFailure=CONTINUE,Args=[-f,s3://elasticmapreduce/samples/pig-apache/do-reports2.pig,-p,INPUT=s3://elasticmapreduce/samples/pig-apache/input,-p,OUTPUT=s3://amzn-s3-demo-bucket/pig-apache/output] \
    --applications Name=Pig \
    --release-label emr-5.3.1 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
**例 21: ブートストラップアクションを追加するには**  
次の `create-cluster` の例では、Amazon S3 に保存されているスクリプトとして定義された 2 つのブートストラップアクションを実行します。  

```
aws emr create-cluster \
    --bootstrap-actions Path=s3://amzn-s3-demo-bucket/myscript1,Name=BootstrapAction1,Args=[arg1,arg2] Path=s3://amzn-s3-demo-bucket/myscript2,Name=BootstrapAction2,Args=[arg1,arg2] \
    --release-label emr-5.3.1 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large \
    --auto-terminate
```
**例 22: EMRFS の一貫性のあるビューを有効にし、RetryCount と RetryPeriod の設定をカスタマイズするには**  
次の `create-cluster` の例では、EMRFS の一貫性のあるビューの再試行回数と再試行期間を指定します。`Consistent=true` 引数が必要です。  

```
aws emr create-cluster \
    --instance-type m4.large \
    --release-label emr-5.9.0 \
    --emrfs Consistent=true,RetryCount=6,RetryPeriod=30
```
次の例では、`emrfsconfig.json` という名前のローカルに保存された JSON 設定ファイルを使用して、前の例と同じ EMRFS 設定を指定します。  

```
aws emr create-cluster \
    --instance-type m4.large \
    --release-label emr-5.9.0 \
    --emrfs file://emrfsconfig.json
```
`emrfsconfig.json` の内容:  

```
{
    "Consistent": true,
    "RetryCount": 6,
    "RetryPeriod": 30
}
```
**例 23: Kerberos が設定されたクラスターを作成するには**  
次の `create-cluster` の例では、Kerberos を有効にしたセキュリティ設定を使用してクラスターを作成し、`--kerberos-attributes` を使用してクラスターの Kerberos パラメータを確立します。  
次のコマンドは、クラスターの Kerberos 属性をインラインで指定します。  

```
aws emr create-cluster \
    --instance-type m3.xlarge \
    --release-label emr-5.10.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --security-configuration mySecurityConfiguration \
    --kerberos-attributes Realm=EC2.INTERNAL,KdcAdminPassword=123,CrossRealmTrustPrincipalPassword=123
```
次のコマンドは同じ属性を指定しますが、`kerberos_attributes.json` という名前のローカルに保存された JSON ファイルを参照します。この例では、ファイルはコマンドを実行するディレクトリに保存されます。Amazon S3 に保存されている設定ファイルを参照することもできます。  

```
aws emr create-cluster \
    --instance-type m3.xlarge \
    --release-label emr-5.10.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --security-configuration mySecurityConfiguration \
    --kerberos-attributes file://kerberos_attributes.json
```
`kerberos_attributes.json` の内容:  

```
{
    "Realm": "EC2.INTERNAL",
    "KdcAdminPassword": "123",
    "CrossRealmTrustPrincipalPassword": "123",
}
```
次の `create-cluster` の例では、`--instance-groups` 設定を使用し、マネージドスケーリングポリシーを持つ Amazon EMR クラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.30.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
    --managed-scaling-policy ComputeLimits='{MinimumCapacityUnits=2,MaximumCapacityUnits=4,UnitType=Instances}'
```
次の `create-cluster` の例では、「--log-encryption-kms-key-id」を使用して、ログ暗号化に使用される KMS キー ID を定義する Amazon EMR クラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.30.0 \
    --log-uri s3://amzn-s3-demo-bucket/myLog \
    --log-encryption-kms-key-id arn:aws:kms:us-east-1:110302272565:key/dd559181-283e-45d7-99d1-66da348c4d33 \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=2,InstanceType=m4.large
```
次の `create-cluster` の例では、「-placement-group-configs」設定を使用して、`SPREAD` プレイスメント戦略を使用して EC2 プレイスメントグループ内の高可用性 (HA) クラスターにプライマリノードを配置する Amazon EMR クラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.30.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=3,InstanceType=m4.largeInstanceGroupType=CORE,InstanceCount=1,InstanceType=m4.large \
    --placement-group-configs InstanceRole=MASTER
```
次の `create-cluster` の例では、「--auto-termination-policy」設定を使用してクラスターの自動アイドル終了しきい値を配置する Amazon EMR クラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-5.34.0 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=1,InstanceType=m4.large \
    --auto-termination-policy IdleTimeout=100
```
次の `create-cluster` の例では、「--os-release-label」を使用してクラスター起動用の Amazon Linux リリースを定義する Amazon EMR クラスターを作成します。  

```
aws emr create-cluster \
    --release-label emr-6.6.0 \
    --os-release-label 2.0.20220406.1 \
    --service-role EMR_DefaultRole \
    --ec2-attributes InstanceProfile=EMR_EC2_DefaultRole \
    --instance-groups InstanceGroupType=MASTER,InstanceCount=1,InstanceType=m4.large InstanceGroupType=CORE,InstanceCount=1,InstanceType=m4.large
```
**例 24: EMR リリース 6.15.0 以降で作成されたクラスターインスタンスのサイズ、iops、スループットの EBS ルートボリューム属性を指定するには**  
次の `create-cluster` の例では、ルートボリューム属性を使用して EC2 インスタンスのルートボリューム仕様を設定する Amazon EMR クラスターを作成します。  

```
aws emr create-cluster \
    --name "Cluster with My Custom AMI" \
    --custom-ami-id ami-a518e6df \
    --ebs-root-volume-size 20 \
    --ebs-root-volume-iops 3000 \
    --ebs-root-volume-throughput 125 \
    --release-label emr-6.15.0 \
    --use-default-roles \
    --instance-count 2 \
    --instance-type m4.large
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateClusterExamples](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/create-cluster-examples.html)」を参照してください。

### `create-default-roles`
<a name="emr_CreateDefaultRoles_cli_2_topic"></a>

次のコード例は、`create-default-roles` を使用する方法を示しています。

**AWS CLI**  
**1. EC2 のデフォルトの IAM ロールを作成するには**  
コマンド:  

```
aws emr create-default-roles
```
出力:  

```
If the role already exists then the command returns nothing.

If the role does not exist then the output will be:

[
    {
        "RolePolicy": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Action": [
                        "cloudwatch:*",
                        "dynamodb:*",
                        "ec2:Describe*",
                        "elasticmapreduce:Describe*",
                        "elasticmapreduce:ListBootstrapActions",
                        "elasticmapreduce:ListClusters",
                        "elasticmapreduce:ListInstanceGroups",
                        "elasticmapreduce:ListInstances",
                        "elasticmapreduce:ListSteps",
                        "kinesis:CreateStream",
                        "kinesis:DeleteStream",
                        "kinesis:DescribeStream",
                        "kinesis:GetRecords",
                        "kinesis:GetShardIterator",
                        "kinesis:MergeShards",
                        "kinesis:PutRecord",
                        "kinesis:SplitShard",
                        "rds:Describe*",
                        "s3:*",
                        "sdb:*",
                        "sns:*",
                        "sqs:*"
                    ],
                    "Resource": "*",
                    "Effect": "Allow"
                }
            ]
        },
        "Role": {
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Action": "sts:AssumeRole",
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        }
                    }
                ]
            },
            "RoleId": "AROAIQ5SIQUGL5KMYBJX6",
            "CreateDate": "2015-06-09T17:09:04.602Z",
            "RoleName": "EMR_EC2_DefaultRole",
            "Path": "/",
            "Arn": "arn:aws:iam::176430881729:role/EMR_EC2_DefaultRole"
        }
    },
    {
        "RolePolicy": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Action": [
                        "ec2:AuthorizeSecurityGroupIngress",
                        "ec2:CancelSpotInstanceRequests",
                        "ec2:CreateSecurityGroup",
                        "ec2:CreateTags",
                        "ec2:DeleteTags",
                        "ec2:DescribeAvailabilityZones",
                        "ec2:DescribeAccountAttributes",
                        "ec2:DescribeInstances",
                        "ec2:DescribeInstanceStatus",
                        "ec2:DescribeKeyPairs",
                        "ec2:DescribePrefixLists",
                        "ec2:DescribeRouteTables",
                        "ec2:DescribeSecurityGroups",
                        "ec2:DescribeSpotInstanceRequests",
                        "ec2:DescribeSpotPriceHistory",
                        "ec2:DescribeSubnets",
                        "ec2:DescribeVpcAttribute",
                        "ec2:DescribeVpcEndpoints",
                        "ec2:DescribeVpcEndpointServices",
                        "ec2:DescribeVpcs",
                        "ec2:ModifyImageAttribute",
                        "ec2:ModifyInstanceAttribute",
                        "ec2:RequestSpotInstances",
                        "ec2:RunInstances",
                        "ec2:TerminateInstances",
                        "iam:GetRole",
                        "iam:GetRolePolicy",
                        "iam:ListInstanceProfiles",
                        "iam:ListRolePolicies",
                        "iam:PassRole",
                        "s3:CreateBucket",
                        "s3:Get*",
                        "s3:List*",
                        "sdb:BatchPutAttributes",
                        "sdb:Select",
                        "sqs:CreateQueue",
                        "sqs:Delete*",
                        "sqs:GetQueue*",
                        "sqs:ReceiveMessage"
                    ],
                    "Resource": "*",
                    "Effect": "Allow"
                }
            ]
        },
        "Role": {
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Action": "sts:AssumeRole",
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "elasticmapreduce.amazonaws.com"
                        }
                    }
                ]
            },
            "RoleId": "AROAI3SRVPPVSRDLARBPY",
            "CreateDate": "2015-06-09T17:09:10.401Z",
            "RoleName": "EMR_DefaultRole",
            "Path": "/",
            "Arn": "arn:aws:iam::176430881729:role/EMR_DefaultRole"
        }
    }
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDefaultRoles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/create-default-roles.html)」を参照してください。

### `create-security-configuration`
<a name="emr_CreateSecurityConfiguration_cli_2_topic"></a>

次のコード例は、`create-security-configuration` を使用する方法を示しています。

**AWS CLI**  
**1. 証明書プロバイダーの PEM で転送時の暗号化を有効にし、ローカルディスクキープロバイダーの SSE-S3 暗号化と AWS KMS で保管時の暗号化を有効にしてセキュリティ設定を作成するには S3 **  
コマンド:  

```
 aws emr create-security-configuration --name MySecurityConfig --security-configuration '{
        "EncryptionConfiguration": {
                "EnableInTransitEncryption" : true,
                "EnableAtRestEncryption" : true,
                "InTransitEncryptionConfiguration" : {
                        "TLSCertificateConfiguration" : {
                                "CertificateProviderType" : "PEM",
                                "S3Object" : "s3://mycertstore/artifacts/MyCerts.zip"
                        }
                },
                "AtRestEncryptionConfiguration" : {
                        "S3EncryptionConfiguration" : {
                                "EncryptionMode" : "SSE-S3"
                        },
                        "LocalDiskEncryptionConfiguration" : {
                                "EncryptionKeyProviderType" : "AwsKms",
                                "AwsKmsKey" : "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
                        }
                }
        }
}'
```
出力:  

```
{
"CreationDateTime": 1474070889.129,
"Name": "MySecurityConfig"
}
```
JSON と同等のもの (security\$1configuration.json の内容):  

```
{
    "EncryptionConfiguration": {
        "EnableInTransitEncryption": true,
        "EnableAtRestEncryption": true,
        "InTransitEncryptionConfiguration": {
            "TLSCertificateConfiguration": {
                "CertificateProviderType": "PEM",
                "S3Object": "s3://mycertstore/artifacts/MyCerts.zip"
            }
        },
        "AtRestEncryptionConfiguration": {
            "S3EncryptionConfiguration": {
                "EncryptionMode": "SSE-S3"
            },
            "LocalDiskEncryptionConfiguration": {
                "EncryptionKeyProviderType": "AwsKms",
                "AwsKmsKey": "arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012"
            }
        }
    }
}
```
コマンド (security\$1configuration.json を使用):  

```
aws emr create-security-configuration --name "MySecurityConfig" --security-configuration file://./security_configuration.json
```
出力:  

```
{
"CreationDateTime": 1474070889.129,
"Name": "MySecurityConfig"
}
```
**2。クラスター専用 KDC とクロスレルム信頼を使用して Kerberos を有効にしてセキュリティ設定を作成するには**  
コマンド:  

```
 aws emr create-security-configuration --name MySecurityConfig --security-configuration '{
     "AuthenticationConfiguration": {
         "KerberosConfiguration": {
             "Provider": "ClusterDedicatedKdc",
             "ClusterDedicatedKdcConfiguration": {
                 "TicketLifetimeInHours": 24,
                 "CrossRealmTrustConfiguration": {
                   "Realm": "AD.DOMAIN.COM",
                   "Domain": "ad.domain.com",
                   "AdminServer": "ad.domain.com",
                   "KdcServer": "ad.domain.com"
                 }
             }
         }
     }
}'
```
出力:  

```
{
"CreationDateTime": 1490225558.982,
"Name": "MySecurityConfig"
}
```
JSON と同等のもの (security\$1configuration.json の内容):  

```
{
    "AuthenticationConfiguration": {
        "KerberosConfiguration": {
            "Provider": "ClusterDedicatedKdc",
            "ClusterDedicatedKdcConfiguration": {
                "TicketLifetimeInHours": 24,
                "CrossRealmTrustConfiguration": {
                    "Realm": "AD.DOMAIN.COM",
                    "Domain": "ad.domain.com",
                    "AdminServer": "ad.domain.com",
                    "KdcServer": "ad.domain.com"
                }
            }
        }
    }
}
```
コマンド (security\$1configuration.json を使用):  

```
aws emr create-security-configuration --name "MySecurityConfig" --security-configuration file://./security_configuration.json
```
出力:  

```
{
"CreationDateTime": 1490225558.982,
"Name": "MySecurityConfig"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSecurityConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/create-security-configuration.html)」を参照してください。

### `delete-security-configuration`
<a name="emr_DeleteSecurityConfiguration_cli_2_topic"></a>

次のコード例は、`delete-security-configuration` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンのセキュリティ設定を削除するには**  
コマンド:  

```
aws emr delete-security-configuration --name MySecurityConfig
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSecurityConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/delete-security-configuration.html)」を参照してください。

### `describe-cluster`
<a name="emr_DescribeCluster_cli_2_topic"></a>

次のコード例は、`describe-cluster` を使用する方法を示しています。

**AWS CLI**  
コマンド:  

```
aws emr describe-cluster --cluster-id j-XXXXXXXX
```
出力:  

```
For release-label based uniform instance groups cluster:

        {
            "Cluster": {
                "Status": {
                    "Timeline": {
                        "ReadyDateTime": 1436475075.199,
                        "CreationDateTime": 1436474656.563,
                    },
                    "State": "WAITING",
                    "StateChangeReason": {
                        "Message": "Waiting for steps to run"
                    }
                },
                "Ec2InstanceAttributes": {
                    "ServiceAccessSecurityGroup": "sg-xxxxxxxx",
                    "EmrManagedMasterSecurityGroup": "sg-xxxxxxxx",
                    "IamInstanceProfile": "EMR_EC2_DefaultRole",
                    "Ec2KeyName": "myKey",
                    "Ec2AvailabilityZone": "us-east-1c",
                    "EmrManagedSlaveSecurityGroup": "sg-yyyyyyyyy"
                },
                "Name": "My Cluster",
                "ServiceRole": "EMR_DefaultRole",
                "Tags": [],
                "TerminationProtected": true,
                "UnhealthyNodeReplacement": true,
                "ReleaseLabel": "emr-4.0.0",
                "NormalizedInstanceHours": 96,
                "InstanceGroups": [
                    {
                        "RequestedInstanceCount": 2,
                        "Status": {
                            "Timeline": {
                                "ReadyDateTime": 1436475074.245,
                                "CreationDateTime": 1436474656.564,
                                "EndDateTime": 1436638158.387
                            },
                            "State": "RUNNING",
                            "StateChangeReason": {
                                "Message": "",
                            }
                        },
                        "Name": "CORE",
                        "InstanceGroupType": "CORE",
                        "Id": "ig-YYYYYYY",
                        "Configurations": [],
                        "InstanceType": "m3.large",
                        "Market": "ON_DEMAND",
                        "RunningInstanceCount": 2
                    },
                    {
                        "RequestedInstanceCount": 1,
                        "Status": {
                            "Timeline": {
                                "ReadyDateTime": 1436475074.245,
                                "CreationDateTime": 1436474656.564,
                                "EndDateTime": 1436638158.387
                            },
                            "State": "RUNNING",
                            "StateChangeReason": {
                                "Message": "",
                            }
                        },
                        "Name": "MASTER",
                        "InstanceGroupType": "MASTER",
                        "Id": "ig-XXXXXXXXX",
                        "Configurations": [],
                        "InstanceType": "m3.large",
                        "Market": "ON_DEMAND",
                        "RunningInstanceCount": 1
                    }
                ],
                "Applications": [
                    {
                        "Name": "Hadoop"
                    }
                ],
                "VisibleToAllUsers": true,
                "BootstrapActions": [],
                "MasterPublicDnsName": "ec2-54-147-144-78.compute-1.amazonaws.com",
                "AutoTerminate": false,
                "Id": "j-XXXXXXXX",
                "Configurations": [
                    {
                        "Properties": {
                            "fs.s3.consistent.retryPeriodSeconds": "20",
                            "fs.s3.enableServerSideEncryption": "true",
                            "fs.s3.consistent": "false",
                            "fs.s3.consistent.retryCount": "2"
                        },
                        "Classification": "emrfs-site"
                    }
                ]
            }
        }


For release-label based instance fleet cluster:
{
    "Cluster": {
        "Status": {
            "Timeline": {
                "ReadyDateTime": 1487897289.705,
                "CreationDateTime": 1487896933.942
            },
            "State": "WAITING",
            "StateChangeReason": {
                "Message": "Waiting for steps to run"
            }
        },
        "Ec2InstanceAttributes": {
            "EmrManagedMasterSecurityGroup": "sg-xxxxx",
            "RequestedEc2AvailabilityZones": [],
            "RequestedEc2SubnetIds": [],
            "IamInstanceProfile": "EMR_EC2_DefaultRole",
            "Ec2AvailabilityZone": "us-east-1a",
            "EmrManagedSlaveSecurityGroup": "sg-xxxxx"
        },
        "Name": "My Cluster",
        "ServiceRole": "EMR_DefaultRole",
        "Tags": [],
        "TerminationProtected": false,
        "UnhealthyNodeReplacement": false,
        "ReleaseLabel": "emr-5.2.0",
        "NormalizedInstanceHours": 472,
        "InstanceCollectionType": "INSTANCE_FLEET",
        "InstanceFleets": [
            {
                "Status": {
                    "Timeline": {
                        "ReadyDateTime": 1487897212.74,
                        "CreationDateTime": 1487896933.948
                    },
                    "State": "RUNNING",
                    "StateChangeReason": {
                        "Message": ""
                    }
                },
                "ProvisionedSpotCapacity": 1,
                "Name": "MASTER",
                "InstanceFleetType": "MASTER",
                "LaunchSpecifications": {
                    "SpotSpecification": {
                        "TimeoutDurationMinutes": 60,
                        "TimeoutAction": "TERMINATE_CLUSTER"
                    }
                },
                "TargetSpotCapacity": 1,
                "ProvisionedOnDemandCapacity": 0,
                "InstanceTypeSpecifications": [
                    {
                        "BidPrice": "0.5",
                        "InstanceType": "m3.xlarge",
                        "WeightedCapacity": 1
                    }
                ],
                "Id": "if-xxxxxxx",
                "TargetOnDemandCapacity": 0
            }
        ],
        "Applications": [
            {
                "Version": "2.7.3",
                "Name": "Hadoop"
            }
        ],
        "ScaleDownBehavior": "TERMINATE_AT_INSTANCE_HOUR",
        "VisibleToAllUsers": true,
        "BootstrapActions": [],
        "MasterPublicDnsName": "ec2-xxx-xx-xxx-xx.compute-1.amazonaws.com",
        "AutoTerminate": false,
        "Id": "j-xxxxx",
        "Configurations": []
    }
}

For ami based uniform instance group cluster:

    {
        "Cluster": {
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1399400564.432,
                    "CreationDateTime": 1399400268.62
                },
                "State": "WAITING",
                "StateChangeReason": {
                    "Message": "Waiting for steps to run"
                }
            },
            "Ec2InstanceAttributes": {
                "IamInstanceProfile": "EMR_EC2_DefaultRole",
                "Ec2AvailabilityZone": "us-east-1c"
            },
            "Name": "My Cluster",
            "Tags": [],
            "TerminationProtected": true,
            "UnhealthyNodeReplacement": true,
            "RunningAmiVersion": "2.5.4",
            "InstanceGroups": [
                {
                    "RequestedInstanceCount": 1,
                    "Status": {
                        "Timeline": {
                            "ReadyDateTime": 1399400558.848,
                            "CreationDateTime": 1399400268.621
                        },
                        "State": "RUNNING",
                        "StateChangeReason": {
                            "Message": ""
                        }
                    },
                    "Name": "Master instance group",
                    "InstanceGroupType": "MASTER",
                    "InstanceType": "m1.small",
                    "Id": "ig-ABCD",
                    "Market": "ON_DEMAND",
                    "RunningInstanceCount": 1
                },
                {
                    "RequestedInstanceCount": 2,
                    "Status": {
                        "Timeline": {
                            "ReadyDateTime": 1399400564.439,
                            "CreationDateTime": 1399400268.621
                        },
                        "State": "RUNNING",
                        "StateChangeReason": {
                            "Message": ""
                        }
                    },
                    "Name": "Core instance group",
                    "InstanceGroupType": "CORE",
                    "InstanceType": "m1.small",
                    "Id": "ig-DEF",
                    "Market": "ON_DEMAND",
                    "RunningInstanceCount": 2
                }
            ],
            "Applications": [
                {
                    "Version": "1.0.3",
                    "Name": "hadoop"
                }
            ],
            "BootstrapActions": [],
            "VisibleToAllUsers": false,
            "RequestedAmiVersion": "2.4.2",
            "LogUri": "s3://myLogUri/",
            "AutoTerminate": false,
            "Id": "j-XXXXXXXX"
        }
    }
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/describe-cluster.html)」を参照してください。**

### `describe-step`
<a name="emr_DescribeStep_cli_2_topic"></a>

次のコード例は、`describe-step` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、クラスター ID `j-3SD91U2E1L2QX` を持つクラスターでステップ ID `s-3LZC0QUT43AM` を持つステップを記述します。  

```
aws emr describe-step --cluster-id j-3SD91U2E1L2QX --step-id s-3LZC0QUT43AM
```
出力:  

```
{
    "Step": {
        "Status": {
            "Timeline": {
                "EndDateTime": 1433200470.481,
                "CreationDateTime": 1433199926.597,
                "StartDateTime": 1433200404.959
            },
            "State": "COMPLETED",
            "StateChangeReason": {}
        },
        "Config": {
            "Args": [
                "s3://us-west-2.elasticmapreduce/libs/hive/hive-script",
                "--base-path",
                "s3://us-west-2.elasticmapreduce/libs/hive/",
                "--install-hive",
                "--hive-versions",
                "0.13.1"
            ],
            "Jar": "s3://us-west-2.elasticmapreduce/libs/script-runner/script-runner.jar",
            "Properties": {}
        },
        "Id": "s-3LZC0QUT43AM",
        "ActionOnFailure": "TERMINATE_CLUSTER",
        "Name": "Setup hive"
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeStep](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/describe-step.html)」を参照してください。**

### `get`
<a name="emr_Get_cli_2_topic"></a>

次のコード例は、`get` を使用する方法を示しています。

**AWS CLI**  
次は、クラスター ID `j-3SD91U2E1L2QX` を持つクラスター内のマスターインスタンスから `hadoop-examples.jar` アーカイブをダウンロードします。  

```
aws emr get --cluster-id j-3SD91U2E1L2QX --key-pair-file ~/.ssh/mykey.pem --src /home/hadoop-examples.jar --dest ~
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Get](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/get.html)」を参照してください。

### `list-clusters`
<a name="emr_ListClusters_cli_2_topic"></a>

次のコード例は、`list-clusters` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、現在のリージョン内のすべてのアクティブな EMR クラスターを一覧表示します。  

```
aws emr list-clusters --active
```
出力:  

```
{
    "Clusters": [
        {
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1433200405.353,
                    "CreationDateTime": 1433199926.596
                },
                "State": "WAITING",
                "StateChangeReason": {
                    "Message": "Waiting after step completed"
                }
            },
            "NormalizedInstanceHours": 6,
            "Id": "j-3SD91U2E1L2QX",
            "Name": "my-cluster"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/list-clusters.html)」を参照してください。**

### `list-instance-fleets`
<a name="emr_ListInstanceFleets_cli_2_topic"></a>

次のコード例は、`list-instance-fleets` を使用する方法を示しています。

**AWS CLI**  
**クラスター内のインスタンスフリートの設定情報を取得するには**  
この例では、指定されたクラスター内のインスタンスフリートの詳細を一覧表示します。  
コマンド:  

```
list-instance-fleets --cluster-id 'j-12ABCDEFGHI34JK'
```
出力:  

```
{
  "InstanceFleets": [
      {
          "Status": {
              "Timeline": {
                  "ReadyDateTime": 1488759094.637,
                  "CreationDateTime": 1488758719.817
              },
              "State": "RUNNING",
              "StateChangeReason": {
                  "Message": ""
              }
          },
          "ProvisionedSpotCapacity": 6,
          "Name": "CORE",
          "InstanceFleetType": "CORE",
          "LaunchSpecifications": {
              "SpotSpecification": {
                  "TimeoutDurationMinutes": 60,
                  "TimeoutAction": "TERMINATE_CLUSTER"
              }
          },
          "ProvisionedOnDemandCapacity": 2,
          "InstanceTypeSpecifications": [
              {
                  "BidPrice": "0.5",
                  "InstanceType": "m3.xlarge",
                  "WeightedCapacity": 2
              }
          ],
          "Id": "if-1ABC2DEFGHIJ3"
      },
      {
          "Status": {
              "Timeline": {
                  "ReadyDateTime": 1488759058.598,
                  "CreationDateTime": 1488758719.811
              },
              "State": "RUNNING",
              "StateChangeReason": {
                  "Message": ""
              }
          },
          "ProvisionedSpotCapacity": 0,
          "Name": "MASTER",
          "InstanceFleetType": "MASTER",
          "ProvisionedOnDemandCapacity": 1,
          "InstanceTypeSpecifications": [
              {
                  "BidPriceAsPercentageOfOnDemandPrice": 100.0,
                  "InstanceType": "m3.xlarge",
                  "WeightedCapacity": 1
              }
          ],
         "Id": "if-2ABC4DEFGHIJ4"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInstanceFleets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/list-instance-fleets.html)」を参照してください。

### `list-instances`
<a name="emr_ListInstances_cli_2_topic"></a>

次のコード例は、`list-instances` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、クラスター ID `j-3C6XNQ39VR9WL` を持つクラスターのすべてのインスタンスを一覧表示します。  

```
aws emr list-instances --cluster-id j-3C6XNQ39VR9WL
```
出力:  

```
For a uniform instance group based cluster
  {
    "Instances": [
         {
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1433200400.03,
                    "CreationDateTime": 1433199960.152
                },
                "State": "RUNNING",
                "StateChangeReason": {}
            },
            "Ec2InstanceId": "i-f19ecfee",
            "PublicDnsName": "ec2-52-52-41-150.us-west-2.compute.amazonaws.com",
            "PrivateDnsName": "ip-172-21-11-216.us-west-2.compute.internal",
            "PublicIpAddress": "52.52.41.150",
            "Id": "ci-3NNHQUQ2TWB6Y",
            "PrivateIpAddress": "172.21.11.216"
        },
        {
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1433200400.031,
                    "CreationDateTime": 1433199949.102
                },
                "State": "RUNNING",
                "StateChangeReason": {}
            },
            "Ec2InstanceId": "i-1feee4c2",
            "PublicDnsName": "ec2-52-63-246-32.us-west-2.compute.amazonaws.com",
            "PrivateDnsName": "ip-172-31-24-130.us-west-2.compute.internal",
            "PublicIpAddress": "52.63.246.32",
            "Id": "ci-GAOCMKNKDCV7",
            "PrivateIpAddress": "172.21.11.215"
        },
        {
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1433200400.031,
                    "CreationDateTime": 1433199949.102
                },
                "State": "RUNNING",
                "StateChangeReason": {}
            },
            "Ec2InstanceId": "i-15cfeee3",
            "PublicDnsName": "ec2-52-25-246-63.us-west-2.compute.amazonaws.com",
            "PrivateDnsName": "ip-172-31-24-129.us-west-2.compute.internal",
            "PublicIpAddress": "52.25.246.63",
            "Id": "ci-2W3TDFFB47UAD",
            "PrivateIpAddress": "172.21.11.214"
        }
    ]
  }


For a fleet based cluster:
   {
      "Instances": [
          {
              "Status": {
                  "Timeline": {
                      "ReadyDateTime": 1487810810.878,
                      "CreationDateTime": 1487810588.367,
                      "EndDateTime": 1488022990.924
                  },
                  "State": "TERMINATED",
                  "StateChangeReason": {
                      "Message": "Instance was terminated."
                  }
              },
              "Ec2InstanceId": "i-xxxxx",
              "InstanceFleetId": "if-xxxxx",
              "EbsVolumes": [],
              "PublicDnsName": "ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com",
              "InstanceType": "m3.xlarge",
              "PrivateDnsName": "ip-xx-xx-xxx-xx.ec2.internal",
              "Market": "SPOT",
              "PublicIpAddress": "xx.xx.xxx.xxx",
              "Id": "ci-xxxxx",
              "PrivateIpAddress": "10.47.191.80"
          }
      ]
  }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/list-instances.html)」を参照してください。

### `list-security-configurations`
<a name="emr_ListSecurityConfigurations_cli_2_topic"></a>

次のコード例は、`list-security-configurations` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンのセキュリティ設定を一覧表示するには**  
コマンド:  

```
aws emr list-security-configurations
```
出力:  

```
{
    "SecurityConfigurations": [
        {
            "CreationDateTime": 1473889697.417,
            "Name": "MySecurityConfig-1"
        },
        {
            "CreationDateTime": 1473889697.417,
            "Name": "MySecurityConfig-2"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSecurityConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/list-security-configurations.html)」を参照してください。

### `list-steps`
<a name="emr_ListSteps_cli_2_topic"></a>

次のコード例は、`list-steps` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、クラスター ID `j-3SD91U2E1L2QX` を持つクラスターのすべてのステップを一覧表示します。  

```
aws emr list-steps --cluster-id j-3SD91U2E1L2QX
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListSteps](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/list-steps.html)」を参照してください。**

### `list-studios`
<a name="emr_ListStudios_cli_2_topic"></a>

次の例は、`list-studios` を使用する方法を説明しています。

**AWS CLI**  
**使用可能な EMR Studio を一覧表示するには**  
次の の`list-studios`例では、 AWS アカウントの EMR Studio を一覧表示します。  

```
aws emr list-studios
```
出力:  

```
{
    "Studios": [
        {
            "StudioId": "es-XXXXXXX132E0X7R0W7GAS1MVB",
            "Name": "My_EMR_Studio",
            "Url": "https://es-XXXXXXX132E0X7R0W7GAS1MVB.emrstudio-prod.us-east-1.amazonaws.com",
            "AuthMode": "IAM",
            "CreationTime": 1761664173.624
        }
    ]
}
```
詳細については、[「Amazon EMR 管理ガイド」の「Amazon EMR Studio リソースのモニタリング、更新、削除](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-studio-manage-studio.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStudios](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/list-studios.html)」を参照してください。

### `modify-cluster-attributes`
<a name="emr_ModifyClusterAttributes_cli_2_topic"></a>

次の例は、`modify-cluster-attributes` を使用する方法を説明しています。

**AWS CLI**  
次のコマンドは、ID `j-301CDNY0J5XM4` の EMR クラスターの可視性をすべてのユーザーに設定します。  

```
aws emr modify-cluster-attributes --cluster-id j-301CDNY0J5XM4 --visible-to-all-users
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClusterAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/modify-cluster-attributes.html)」を参照してください。

### `modify-instance-fleet`
<a name="emr_ModifyInstanceFleet_cli_2_topic"></a>

次のコード例は、`modify-instance-fleet` を使用する方法を示しています。

**AWS CLI**  
**インスタンスフリートのターゲット容量を変更するには**  
この例では、指定されたインスタンスフリートのオンデマンドおよびスポットターゲット容量を 1 に変更します。  
コマンド:  

```
aws emr modify-instance-fleet --cluster-id 'j-12ABCDEFGHI34JK' --instance-fleet InstanceFleetId='if-2ABC4DEFGHIJ4',TargetOnDemandCapacity=1,TargetSpotCapacity=1
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyInstanceFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/modify-instance-fleet.html)」を参照してください。

### `put`
<a name="emr_Put_cli_2_topic"></a>

次のコード例は、`put` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`healthcheck.sh` という名前のファイルを、クラスター ID `j-3SD91U2E1L2QX` のクラスター内のマスターインスタンスにアップロードします。  

```
aws emr put --cluster-id j-3SD91U2E1L2QX --key-pair-file ~/.ssh/mykey.pem --src ~/scripts/healthcheck.sh --dest /home/hadoop/bin/healthcheck.sh
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Put](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/put.html)」を参照してください。

### `remove-tags`
<a name="emr_RemoveTags_cli_2_topic"></a>

次のコード例は、`remove-tags` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`prod` キーを持つタグをクラスター ID `j-3SD91U2E1L2QX` のクラスターから削除します。  

```
aws emr remove-tags --resource-id j-3SD91U2E1L2QX --tag-keys prod
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/remove-tags.html)」を参照してください。

### `schedule-hbase-backup`
<a name="emr_ScheduleHbaseBackup_cli_2_topic"></a>

次のコード例は、`schedule-hbase-backup` を使用する方法を示しています。

**AWS CLI**  
**注: このコマンドは、AMI バージョン 2.x および 3.x の HBase でのみ使用できます**  
**1. フル HBase バックアップをスケジュールするには** >>>>>>> 06ab6d6e13564b5733d75abaf3b599f93cf39a23  
コマンド:  

```
aws emr schedule-hbase-backup --cluster-id j-XXXXXXYY --type full --dir
s3://amzn-s3-demo-bucket/backup --interval 10 --unit hours --start-time
2014-04-21T05:26:10Z --consistent
```
出力:  

```
None
```
**2。増分 HBase バックアップをスケジュールするには**  
コマンド:  

```
aws emr schedule-hbase-backup --cluster-id j-XXXXXXYY --type incremental
 --dir s3://amzn-s3-demo-bucket/backup --interval 30 --unit minutes --start-time
2014-04-21T05:26:10Z --consistent
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ScheduleHbaseBackup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/schedule-hbase-backup.html)」を参照してください。

### `socks`
<a name="emr_Socks_cli_2_topic"></a>

次のコード例は、`socks` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、クラスター ID `j-3SD91U2E1L2QX` のクラスター内のマスターインスタンスとのソックス接続を開きます。  

```
aws emr socks --cluster-id j-3SD91U2E1L2QX --key-pair-file ~/.ssh/mykey.pem
```
キーペアファイルオプションは、プライベートキーファイルへのローカルパスを取得します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Socks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/socks.html)」を参照してください。

### `ssh`
<a name="emr_Ssh_cli_2_topic"></a>

次のコード例は、`ssh` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、クラスター ID `j-3SD91U2E1L2QX` のクラスター内のマスターインスタンスとの ssh 接続を開きます。  

```
aws emr ssh --cluster-id j-3SD91U2E1L2QX --key-pair-file ~/.ssh/mykey.pem
```
キーペアファイルオプションは、プライベートキーファイルへのローカルパスを取得します。  
出力:  

```
ssh -o StrictHostKeyChecking=no -o ServerAliveInterval=10 -i /home/local/user/.ssh/mykey.pem hadoop@ec2-52-52-41-150.us-west-2.compute.amazonaws.com
Warning: Permanently added 'ec2-52-52-41-150.us-west-2.compute.amazonaws.com,52.52.41.150' (ECDSA) to the list of known hosts.
Last login: Mon Jun  1 23:15:38 2015

      __|  __|_  )
       _|  (     /   Amazon Linux AMI
      ___|\___|___|

https://aws.amazon.com/amazon-linux-ami/2015.03-release-notes/
26 package(s) needed for security, out of 39 available
Run "sudo yum update" to apply all updates.

--------------------------------------------------------------------------------

Welcome to Amazon Elastic MapReduce running Hadoop and Amazon Linux.

Hadoop is installed in /home/hadoop. Log files are in /mnt/var/log/hadoop. Check
/mnt/var/log/hadoop/steps for diagnosing step failures.

The Hadoop UI can be accessed via the following commands:

  ResourceManager    lynx http://ip-172-21-11-216:9026/
  NameNode           lynx http://ip-172-21-11-216:9101/

--------------------------------------------------------------------------------

[hadoop@ip-172-31-16-216 ~]$
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Ssh](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/ssh.html)」を参照してください。

# を使用した Amazon EMR on EKS の例 AWS CLI
<a name="cli_2_emr-containers_code_examples"></a>

次のコード例は、Amazon EMR on EKS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `update-role-trust-policy`
<a name="emr-containers_UpdateRoleTrustPolicy_cli_2_topic"></a>

次のコード例は、`update-role-trust-policy` を使用する方法を示しています。

**AWS CLI**  
**Amazon EMR on EKS で使用する IAM ロールの信頼ポリシーを更新するには**  
このコマンド例では、**example\$1iam\$1role** という名前のロールの信頼ポリシーを更新して、**example\$1cluster** という名前の EKS クラスターの **example\$1namespace** 名前空間で Amazon EMR on EKS で使用できるようにします。  
コマンド:  

```
aws emr-containers update-role-trust-policy \
    --cluster example_cluster \
    --namespace example_namespace \
    --role-name example_iam_role
```
出力:  

```
If the trust policy has already been updated, then the output will be:
Trust policy statement already exists for role example_iam_role. No
changes were made!

If the trust policy has not been updated yet, then the output will be:
Successfully updated trust policy of role example_iam_role.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoleTrustPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr-containers/update-role-trust-policy.html)」を参照してください。

# を使用した EventBridge の例 AWS CLI
<a name="cli_2_eventbridge_code_examples"></a>

次のコード例は、EventBridge AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-rule`
<a name="eventbridge_DeleteRule_cli_2_topic"></a>

次のコード例は、`delete-rule` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Events ルールを削除するには**  
この例は、EC2InstanceStateChanges という名前のルールを削除します。  

```
aws events delete-rule --name "EC2InstanceStateChanges"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/delete-rule.html)」を参照してください。**

### `describe-rule`
<a name="eventbridge_DescribeRule_cli_2_topic"></a>

次のコード例は、`describe-rule` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Events ルールに関する情報を表示するには**  
この例は、DailyLambdaFunction という名前のルールに関する情報を表示します。  

```
aws events describe-rule --name "DailyLambdaFunction"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/describe-rule.html)」を参照してください。**

### `disable-rule`
<a name="eventbridge_DisableRule_cli_2_topic"></a>

次のコード例は、`disable-rule` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Events ルールを無効にするには**  
この例は、DailyLambdaFunction という名前のルールを無効にします。ルールは削除されません。  

```
aws events disable-rule --name "DailyLambdaFunction"
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[DisableRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/disable-rule.html)」を参照してください。

### `enable-rule`
<a name="eventbridge_EnableRule_cli_2_topic"></a>

次のコード例は、`enable-rule` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Events ルールを有効にするには**  
この例は、無効になっていた DailyLambdaFunction という名前のルールを有効にします。  

```
aws events enable-rule --name "DailyLambdaFunction"
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[EnableRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/enable-rule.html)」を参照してください。

### `list-rule-names-by-target`
<a name="eventbridge_ListRuleNamesByTarget_cli_2_topic"></a>

次のコード例は、`list-rule-names-by-target` を使用する方法を示しています。

**AWS CLI**  
**ターゲットが指定されているルールをすべて表示するには**  
この例は、「MyFunctionName」という名前の Lambda 関数をターゲットとするすべてのルールを表示します。  

```
aws events list-rule-names-by-target --target-arn "arn:aws:lambda:us-east-1:123456789012:function:MyFunctionName"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListRuleNamesByTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/list-rule-names-by-target.html)」を参照してください。**

### `list-rules`
<a name="eventbridge_ListRules_cli_2_topic"></a>

次のコード例は、`list-rules` を使用する方法を示しています。

**AWS CLI**  
**すべての CloudWatch Events ルールを一覧表示するには**  
この例は、リージョン内のすべての CloudWatch Events ルールを表示します。  

```
aws events list-rules
```
**特定の文字列で始まる CloudWatch Events ルールを一覧表示するには**  
この例では、名前が「Daily」で始まるリージョン内のすべての CloudWatch Events ルールを表示します。  

```
aws events list-rules --name-prefix "Daily"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/list-rules.html)」を参照してください。**

### `list-targets-by-rule`
<a name="eventbridge_ListTargetsByRule_cli_2_topic"></a>

次のコード例は、`list-targets-by-rule` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Events ルールのすべてのターゲットを表示するには**  
この例は、DailyLambdaFunction という名前のルールのすべてのターゲットを表示します。  

```
aws events list-targets-by-rule --rule  "DailyLambdaFunction"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListTargetsByRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/list-targets-by-rule.html)」を参照してください。**

### `put-events`
<a name="eventbridge_PutEvents_cli_2_topic"></a>

次のコード例は、`put-events` を使用する方法を示しています。

**AWS CLI**  
**カスタムイベントを CloudWatch Events に送信するには**  
この例は、カスタムイベントを CloudWatch Events に送信します。このイベントは putevents.json ファイルに含まれています。  

```
aws events put-events --entries file://putevents.json
```
putevents.json ファイルの内容は次のとおりです。  

```
[
  {
    "Source": "com.mycompany.myapp",
    "Detail": "{ \"key1\": \"value1\", \"key2\": \"value2\" }",
    "Resources": [
      "resource1",
      "resource2"
    ],
    "DetailType": "myDetailType"
  },
  {
    "Source": "com.mycompany.myapp",
    "Detail": "{ \"key1\": \"value3\", \"key2\": \"value4\" }",
    "Resources": [
      "resource1",
      "resource2"
    ],
    "DetailType": "myDetailType"
   }
]
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/put-events.html)」を参照してください。**

### `put-rule`
<a name="eventbridge_PutRule_cli_2_topic"></a>

次のコード例は、`put-rule` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Events ルールを作成するには**  
この例は、毎日午前 9:00 (UTC) にトリガーされるルールを作成します。put-targets を使用して Lambda 関数をこのルールのターゲットとして追加すると、指定した時刻に Lambda 関数を毎日実行できます。  

```
aws events put-rule --name "DailyLambdaFunction" --schedule-expression "cron(0 9 * * ? *)"
```
この例は、リージョン内の任意の EC2 インスタンスの状態が変わったときにトリガーされるルールを作成します。  

```
aws events put-rule --name "EC2InstanceStateChanges" --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"]}"  --role-arn "arn:aws:iam::123456789012:role/MyRoleForThisRule"
```
この例は、リージョン内の任意の EC2 インスタンスが停止または終了したときにトリガーされるルールを作成します。  

```
aws events put-rule --name "EC2InstanceStateChangeStopOrTerminate" --event-pattern "{\"source\":[\"aws.ec2\"],\"detail-type\":[\"EC2 Instance State-change Notification\"],\"detail\":{\"state\":[\"stopped\",\"terminated\"]}}" --role-arn "arn:aws:iam::123456789012:role/MyRoleForThisRule"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/put-rule.html)」を参照してください。**

### `put-targets`
<a name="eventbridge_PutTargets_cli_2_topic"></a>

次のコード例は、`put-targets` を使用する方法を示しています。

**AWS CLI**  
**CloudWatch Events ルールのターゲットを追加するには**  
この例は、ルールのターゲットとして Lambda 関数を追加します。  

```
aws events put-targets --rule DailyLambdaFunction --targets "Id"="1","Arn"="arn:aws:lambda:us-east-1:123456789012:function:MyFunctionName"
```
この例は、Amazon Kinesis ストリームをターゲットとして設定し、このルールによって捕捉されたイベントがストリームに中継されるようにします。  

```
aws events put-targets --rule EC2InstanceStateChanges --targets "Id"="1","Arn"="arn:aws:kinesis:us-east-1:123456789012:stream/MyStream","RoleArn"="arn:aws:iam::123456789012:role/MyRoleForThisRule"
```
この例は、2 つの Amazon Kinesis ストリームを 1 つのルールのターゲットとして設定します。  

```
aws events put-targets --rule DailyLambdaFunction --targets "Id"="Target1","Arn"="arn:aws:kinesis:us-east-1:379642911888:stream/MyStream1","RoleArn"="arn:aws:iam::379642911888:role/ MyRoleToAccessLambda"  "Id"="Target2"," Arn"="arn:aws:kinesis:us-east-1:379642911888:stream/MyStream2","RoleArn"="arn:aws:iam::379642911888:role/MyRoleToAccessLambda"
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/put-targets.html)」を参照してください。**

### `remove-targets`
<a name="eventbridge_RemoveTargets_cli_2_topic"></a>

次のコード例は、`remove-targets` を使用する方法を示しています。

**AWS CLI**  
**イベントのターゲットを削除するには**  
この例は、MyStream1 という名前の Amazon Kinesis ストリームを、DailyLambdaFunction というルールのターゲットから削除します。DailyLambdaFunction が作成されたとき、このストリームは Target1 の ID を持つターゲットとして設定されました。  

```
aws events remove-targets --rule "DailyLambdaFunction" --ids "Target1"
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[RemoveTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/remove-targets.html)」を参照してください。

### `test-event-pattern`
<a name="eventbridge_TestEventPattern_cli_2_topic"></a>

次のコード例は、`test-event-pattern` を使用する方法を示しています。

**AWS CLI**  
**イベントパターンが指定されたイベントと一致するかどうかを確認するには**  
この例では、パターン「source:com.mycompany.myapp」が指定されたイベントと一致するかどうかをテストします。この例では、出力は「true」になります。  

```
aws events test-event-pattern --event-pattern "{\"source\":[\"com.mycompany.myapp\"]}" --event "{\"id\":\"1\",\"source\":\"com.mycompany.myapp\",\"detail-type\":\"myDetailType\",\"account\":\"123456789012\",\"region\":\"us-east-1\",\"time\":\"2017-04-11T20:11:04Z\"}"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestEventPattern](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/events/test-event-pattern.html)」を参照してください。

# を使用した EventBridge Pipes の例 AWS CLI
<a name="cli_2_pipes_code_examples"></a>

次のコード例は、EventBridge Pipes AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-pipe`
<a name="pipes_CreatePipe_cli_2_topic"></a>

次のコード例は、`create-pipe` を使用する方法を示しています。

**AWS CLI**  
**パイプを作成するには**  
次の `create-pipe` の例では、ソースとして SQS、ターゲットとして CloudWatch Log Group を使用して、`Demo_Pipe` という名前のパイプを作成します。  

```
aws pipes create-pipe \
    --name Demo_Pipe \
    --desired-state RUNNING \
    --role-arn arn:aws:iam::123456789012:role/service-role/Amazon_EventBridge_Pipe_Demo_Pipe_28b3aa4f \
    --source arn:aws:sqs:us-east-1:123456789012:Demo_Queue \
    --target arn:aws:logs:us-east-1:123456789012:log-group:/aws/pipes/Demo_LogGroup
```
出力:  

```
{
    "Arn": "arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe",
    "Name": "Demo_Pipe",
    "DesiredState": "RUNNING",
    "CurrentState": "CREATING",
    "CreationTime": "2024-10-08T12:33:59-05:00",
    "LastModifiedTime": "2024-10-08T12:33:59.684839-05:00"
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreatePipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/create-pipe.html)」を参照してください。

### `delete-pipe`
<a name="pipes_DeletePipe_cli_2_topic"></a>

次のコード例は、`delete-pipe` を使用する方法を示しています。

**AWS CLI**  
**既存のパイプを削除するには**  
次の `delete-pipe` の例では、指定したアカウントから `Demo_Pipe` という名前のパイプを削除します。  

```
aws pipes delete-pipe \
    --name Demo_Pipe
```
出力:  

```
{
    "Arn": "arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe",
    "Name": "Demo_Pipe",
    "DesiredState": "STOPPED",
    "CurrentState": "DELETING",
    "CreationTime": "2024-10-08T09:29:10-05:00",
    "LastModifiedTime": "2024-10-08T11:57:22-05:00"
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeletePipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/delete-pipe.html)」を参照してください。

### `describe-pipe`
<a name="pipes_DescribePipe_cli_2_topic"></a>

次のコード例は、`describe-pipe` を使用する方法を示しています。

**AWS CLI**  
**パイプに関する情報を取得するには**  
次の `describe-pipe` の例では、指定したアカウントのパイプ `Demo_Pipe` に関する情報を表示します。  

```
aws pipes describe-pipe \
    --name Demo_Pipe
```
出力:  

```
{
    "Arn": "arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe",
    "Name": "Demo_Pipe",
    "DesiredState": "RUNNING",
    "CurrentState": "RUNNING",
    "StateReason": "User initiated",
    "Source": "arn:aws:sqs:us-east-1:123456789012:Demo_Queue",
    "SourceParameters": {
        "SqsQueueParameters": {
            "BatchSize": 1
        }
    },
    "EnrichmentParameters": {},
    "Target": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/pipes/Demo_LogGroup",
    "TargetParameters": {},
    "RoleArn": "arn:aws:iam::123456789012:role/service-role/Amazon_EventBridge_Pipe_Demo_Pipe_28b3aa4f",
    "Tags": {},
    "CreationTime": "2024-10-08T09:29:10-05:00",
    "LastModifiedTime": "2024-10-08T10:23:47-05:00",
    "LogConfiguration": {
        "CloudwatchLogsLogDestination": {
            "LogGroupArn": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/vendedlogs/pipes/Demo_Pipe"
        },
        "Level": "ERROR"
    }
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribePipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/describe-pipe.html)」を参照してください。

### `list-pipes`
<a name="pipes_ListPipes_cli_2_topic"></a>

次のコード例は、`list-pipes` を使用する方法を示しています。

**AWS CLI**  
**パイプのリストを取得するには**  
次の `list-pipes` の例では、指定したアカウントのすべてのパイプを表示します。  

```
aws pipes list-pipes
```
出力:  

```
{
    "Pipes": [
        {
            "Name": "Demo_Pipe",
            "Arn": "arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe",
            "DesiredState": "RUNNING",
            "CurrentState": "RUNNING",
            "StateReason": "User initiated",
            "CreationTime": "2024-10-08T09:29:10-05:00",
            "LastModifiedTime": "2024-10-08T10:23:47-05:00",
            "Source": "arn:aws:sqs:us-east-1:123456789012:Demo_Queue",
            "Target": "arn:aws:logs:us-east-1:123456789012:log-group:/aws/pipes/Demo_LogGroup"
        }
    ]
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListPipes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/list-pipes.html)」を参照してください。

### `list-tags-for-resource`
<a name="pipes_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のパイプに関連付けられているタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定したアカウントの `Demo_Pipe` という名前のパイプに関連付けられているすべてのタグを一覧表示します。  

```
aws pipes list-tags-for-resource \
    --resource-arn arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe
```
出力:  

```
{
    "tags": {
        "stack": "Production",
        "team": "DevOps"
    }
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/list-tags-for-resource.html)」を参照してください。

### `start-pipe`
<a name="pipes_StartPipe_cli_2_topic"></a>

次のコード例は、`start-pipe` を使用する方法を示しています。

**AWS CLI**  
**既存のパイプを開始するには**  
次の `start-pipe` の例では、指定したアカウントの `Demo_Pipe` という名前のパイプを開始します。  

```
aws pipes start-pipe \
    --name Demo_Pipe
```
出力:  

```
{
    "Arn": "arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe",
    "Name": "Demo_Pipe",
    "DesiredState": "RUNNING",
    "CurrentState": "STARTING",
    "CreationTime": "2024-10-08T09:29:10-05:00",
    "LastModifiedTime": "2024-10-08T10:17:24-05:00"
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge パイプの開始または停止](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-start-stop.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartPipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/start-pipe.html)」を参照してください。

### `stop-pipe`
<a name="pipes_StopPipe_cli_2_topic"></a>

次のコード例は、`stop-pipe` を使用する方法を示しています。

**AWS CLI**  
**既存のパイプを停止するには**  
次の `stop-pipe` の例では、指定したアカウントの `Demo_Pipe` という名前のパイプを停止します。  

```
aws pipes stop-pipe \
    --name Demo_Pipe
```
出力:  

```
{
    "Arn": "arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe",
    "Name": "Demo_Pipe",
    "DesiredState": "STOPPED",
    "CurrentState": "STOPPING",
    "CreationTime": "2024-10-08T09:29:10-05:00",
    "LastModifiedTime": "2024-10-08T09:29:49-05:00"
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge パイプの開始または停止](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-start-stop.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopPipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/stop-pipe.html)」を参照してください。

### `tag-resource`
<a name="pipes_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のパイプにタグを付けるには**  
次の `tag-resource` の例では、`Demo_Pipe` という名前のパイプにタグを付けます。コマンドが成功した場合、出力は返りません。  

```
aws pipes tag-resource \
    --resource-arn arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe \
    --tags stack=Production
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="pipes_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のパイプからタグを削除するには**  
次の `untag-resource` の例では、`Demo_Pipe` という名前のパイプから、キーが `stack` のタグを削除します。コマンドが成功した場合、出力は返りません。  

```
aws pipes untag-resource \
    --resource-arn arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe \
    --tags stack
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/untag-resource.html)」を参照してください。

### `update-pipe`
<a name="pipes_UpdatePipe_cli_2_topic"></a>

次のコード例は、`update-pipe` を使用する方法を示しています。

**AWS CLI**  
**既存のパイプを更新するには**  
次の `update-pipe` の例では、CloudWatch Log 設定パラメータを追加して `Demo_Pipe` という名前のパイプを更新します。パイプの実行ロールが Log の送信先に対する適切なアクセス許可を持つように更新しています。  

```
aws pipes update-pipe \
    --name Demo_Pipe \
    --desired-state RUNNING \
    --log-configuration CloudwatchLogsLogDestination={LogGroupArn=arn:aws:logs:us-east-1:123456789012:log-group:/aws/vendedlogs/pipes/Demo_Pipe},Level=TRACE \
    --role-arn arn:aws:iam::123456789012:role/service-role/Amazon_EventBridge_Pipe_Demo_Pipe_28b3aa4f
```
出力:  

```
{
    "Arn": "arn:aws:pipes:us-east-1:123456789012:pipe/Demo_Pipe",
    "Name": "Demo_Pipe",
    "DesiredState": "RUNNING",
    "CurrentState": "UPDATING",
    "CreationTime": "2024-10-08T09:29:10-05:00",
    "LastModifiedTime": "2024-10-08T11:35:48-05:00"
}
```
詳細については、*Amazon EventBridge ユーザーガイド*の「[Amazon EventBridge Pipes の概念](https://docs.aws.amazon.com/eventbridge/latest/userguide/pipes-concepts.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[UpdatePipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pipes/update-pipe.html)」を参照してください。

# を使用した Firewall Manager の例 AWS CLI
<a name="cli_2_fms_code_examples"></a>

次のコード例は、Firewall Manager AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-admin-account`
<a name="fms_AssociateAdminAccount_cli_2_topic"></a>

次のコード例は、`associate-admin-account` を使用する方法を示しています。

**AWS CLI**  
Firewall Manager 管理者アカウントを設定するには  
次の `associate-admin-account` の例では、Firewall Manager に管理者アカウントが設定されます。  

```
aws fms associate-admin-account \
    --admin-account 123456789012
```
このコマンドでは何も出力されません。  
詳細については、「 WAF、[AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「Set the Firewall Manager Administrator Account](https://docs.aws.amazon.com/waf/latest/developerguide/enable-integration.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/associate-admin-account.html)」を参照してください。

### `delete-notification-channel`
<a name="fms_DeleteNotificationChannel_cli_2_topic"></a>

次のコード例は、`delete-notification-channel` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager ログの SNS トピック情報を削除するには**  
次の `delete-notification-channel` の例では、SNS トピック情報を削除します。  

```
aws fms delete-notification-channel
```
このコマンドでは何も出力されません。  
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「Amazon SNS 通知と Amazon CloudWatch アラームを設定する](https://docs.aws.amazon.com/waf/latest/developerguide/get-started-fms-shield-cloudwatch.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNotificationChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/delete-notification-channel.html)」を参照してください。

### `delete-policy`
<a name="fms_DeletePolicy_cli_2_topic"></a>

次のコード例は、`delete-policy` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager ポリシーを削除するには**  
次の `delete-policy` の例では、指定された ID を持つポリシーとそのすべてのリソースを削除します。  

```
aws fms delete-policy \
    --policy-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --delete-all-policy-resources
```
このコマンドでは何も出力されません。  
詳細については、「 WAF、[AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「Firewall Manager ポリシーの使用](https://docs.aws.amazon.com/waf/latest/developerguide/working-with-policies.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/delete-policy.html)」を参照してください。

### `disassociate-admin-account`
<a name="fms_DisassociateAdminAccount_cli_2_topic"></a>

次のコード例は、`disassociate-admin-account` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager 管理者アカウントを削除するには**  
次の `disassociate-admin-account` の例では、Firewall Manager から現在の管理者アカウントの関連付けを削除します。  

```
aws fms disassociate-admin-account
```
このコマンドでは何も出力されません。  
詳細については、「 WAF、[AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「Set the Firewall Manager Administrator Account](https://docs.aws.amazon.com/waf/latest/developerguide/enable-integration.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/disassociate-admin-account.html)」を参照してください。

### `get-admin-account`
<a name="fms_GetAdminAccount_cli_2_topic"></a>

次のコード例は、`get-admin-account` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager 管理者アカウントを取得するには**  
次の `get-admin-account` の例では、管理者アカウントを取得します。  

```
aws fms get-admin-account
```
出力:  

```
{
    "AdminAccount": "123456789012",
    "RoleStatus": "READY"
}
```
詳細については、[AWS 「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「Firewall Manager の前提条件](https://docs.aws.amazon.com/waf/latest/developerguide/fms-prereq.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/get-admin-account.html)」を参照してください。

### `get-compliance-detail`
<a name="fms_GetComplianceDetail_cli_2_topic"></a>

次のコード例は、`get-compliance-detail` を使用する方法を示しています。

**AWS CLI**  
**アカウントのコンプライアンス情報を取得するには**  
次の `get-compliance-detail` の例では、指定されたポリシーとメンバーアカウントのコンプライアンス情報を取得します。  

```
aws fms get-compliance-detail \
    --policy-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --member-account 123456789012
```
出力:  

```
{
    "PolicyComplianceDetail": {
    "EvaluationLimitExceeded": false,
    "IssueInfoMap": {},
    "MemberAccount": "123456789012",
    "PolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "PolicyOwner": "123456789012",
    "Violators": []
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「ポリシーによるリソースコンプライアンスの表示](https://docs.aws.amazon.com/waf/latest/developerguide/fms-compliance.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComplianceDetail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/get-compliance-detail.html)」を参照してください。

### `get-notification-channel`
<a name="fms_GetNotificationChannel_cli_2_topic"></a>

次のコード例は、`get-notification-channel` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager ログの SNS トピック情報を取得するには**  
次の `get-notification-channel` の例では、SNS トピック情報を取得します。  

```
aws fms get-notification-channel
```
出力:  

```
{
    "SnsTopicArn": "arn:aws:sns:us-west-2:123456789012:us-west-2-fms",
    "SnsRoleName": "arn:aws:iam::123456789012:role/aws-service-role/fms.amazonaws.com/AWSServiceRoleForFMS"
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「Amazon SNS 通知と Amazon CloudWatch アラームを設定する](https://docs.aws.amazon.com/waf/latest/developerguide/get-started-fms-shield-cloudwatch.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetNotificationChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/get-notification-channel.html)」を参照してください。

### `get-policy`
<a name="fms_GetPolicy_cli_2_topic"></a>

次のコード例は、`get-policy` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager ポリシーを取得するには**  
次の `get-policy` の例では、指定された ID のポリシーを取得します。  

```
aws fms get-policy \
    --policy-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "Policy": {
        "PolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "PolicyName": "test",
        "PolicyUpdateToken": "1:p+2RpKR4wPFx7mcrL1UOQQ==",
        "SecurityServicePolicyData": {
            "Type": "SECURITY_GROUPS_COMMON",
            "ManagedServiceData": "{\"type\":\"SECURITY_GROUPS_COMMON\",\"revertManualSecurityGroupChanges\":true,\"exclusiveResourceSecurityGroupManagement\":false,\"securityGroups\":[{\"id\":\"sg-045c43ccc9724e63e\"}]}"
        },
        "ResourceType": "AWS::EC2::Instance",
        "ResourceTags": [],
        "ExcludeResourceTags": false,
        "RemediationEnabled": false
    },
    "PolicyArn": "arn:aws:fms:us-west-2:123456789012:policy/d1ac59b8-938e-42b3-b2e0-7c620422ddc2"
}
```
詳細については、「 WAF、[AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「Firewall Manager ポリシーの使用](https://docs.aws.amazon.com/waf/latest/developerguide/working-with-policies.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/get-policy.html)」を参照してください。

### `list-compliance-status`
<a name="fms_ListComplianceStatus_cli_2_topic"></a>

次のコード例は、`list-compliance-status` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントのポリシーコンプライアンス情報を取得するには**  
次の `list-compliance-status` の例では、指定されたポリシーのメンバーアカウントコンプライアンス情報を取得します。  

```
aws fms list-compliance-status \
    --policy-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "PolicyComplianceStatusList": [
        {
            "PolicyOwner": "123456789012",
            "PolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "PolicyName": "test",
            "MemberAccount": "123456789012",
            "EvaluationResults": [
                {
                    "ComplianceStatus": "COMPLIANT",
                    "ViolatorCount": 0,
                    "EvaluationLimitExceeded": false
                },
                {
                    "ComplianceStatus": "NON_COMPLIANT",
                    "ViolatorCount": 2,
                    "EvaluationLimitExceeded": false
                }
            ],
            "LastUpdated": 1576283774.0,
            "IssueInfoMap": {}
        }
    ]
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「ポリシーによるリソースコンプライアンスの表示](https://docs.aws.amazon.com/waf/latest/developerguide/fms-compliance.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListComplianceStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/list-compliance-status.html)」を参照してください。

### `list-member-accounts`
<a name="fms_ListMemberAccounts_cli_2_topic"></a>

次のコード例は、`list-member-accounts` を使用する方法を示しています。

**AWS CLI**  
**組織内のメンバーアカウントを取得するには**  
次の `list-member-accounts` の例では、Firewall Manager 管理者の組織内にあるすべてのメンバーアカウントを一覧表示します。  

```
aws fms list-member-accounts
```
出力:  

```
{
    "MemberAccounts": [
        "222222222222",
        "333333333333",
        "444444444444"
    ]
}
```
詳細については、「 WAF」の[AWS 「Firewall Manager](https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html)」、「Firewall Manager」、および「Shield Advanced デベロッパーガイド」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMemberAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/list-member-accounts.html)」を参照してください。

### `list-policies`
<a name="fms_ListPolicies_cli_2_topic"></a>

次のコード例は、`list-policies` を使用する方法を示しています。

**AWS CLI**  
**すべての Firewall Manager ポリシーを取得するには**  
次の `list-policies` の例では、アカウントのポリシーのリストを取得します。この例では、出力はリクエストごとに 2 つの結果に制限されています。各呼び出しは、リストの次の結果セットを取得するために、次の `list-policies` 呼び出しで `--starting-token` パラメータの値として使用できる `NextToken` を返します。  

```
aws fms list-policies \
    --max-items 2
```
出力:  

```
{
    "PolicyList": [
        {
            "PolicyArn": "arn:aws:fms:us-west-2:123456789012:policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "PolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "PolicyName": "test",
            "ResourceType": "AWS::EC2::Instance",
            "SecurityServiceType": "SECURITY_GROUPS_COMMON",
            "RemediationEnabled": false
        },
        {
            "PolicyArn": "arn:aws:fms:us-west-2:123456789012:policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "PolicyId": "457c9b21-fc94-406c-ae63-21217395ba72",
            "PolicyName": "test",
            "ResourceType": "AWS::EC2::Instance",
            "SecurityServiceType": "SECURITY_GROUPS_COMMON",
            "RemediationEnabled": false
        }
    ],
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ=="
}
```
詳細については、「 WAF、[AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「Firewall Manager ポリシーの使用](https://docs.aws.amazon.com/waf/latest/developerguide/working-with-policies.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「AWS CLI Command Reference」の「[ListPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/list-policies.html)」を参照してください。**

### `put-notification-channel`
<a name="fms_PutNotificationChannel_cli_2_topic"></a>

次のコード例は、`put-notification-channel` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager ログの SNS トピック情報を設定するには**  
次の `put-notification-channel` の例では、SNS トピック情報を設定します。  

```
aws fms put-notification-channel \
    --sns-topic-arn arn:aws:sns:us-west-2:123456789012:us-west-2-fms \
    --sns-role-name arn:aws:iam::123456789012:role/aws-service-role/fms.amazonaws.com/AWSServiceRoleForFMS
```
このコマンドでは何も出力されません。  
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「Amazon SNS 通知と Amazon CloudWatch アラームを設定する](https://docs.aws.amazon.com/waf/latest/developerguide/get-started-fms-shield-cloudwatch.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutNotificationChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/put-notification-channel.html)」を参照してください。

### `put-policy`
<a name="fms_PutPolicy_cli_2_topic"></a>

次のコード例は、`put-policy` を使用する方法を示しています。

**AWS CLI**  
**Firewall Manager ポリシーを作成するには**  
次の `put-policy` の例では、Firewall Manager セキュリティグループポリシーを作成します。  

```
aws fms put-policy \
    --cli-input-json file://policy.json
```
`policy.json` の内容:  

```
{
    "Policy": {
        "PolicyName": "test",
        "SecurityServicePolicyData": {
            "Type": "SECURITY_GROUPS_USAGE_AUDIT",
            "ManagedServiceData": "{\"type\":\"SECURITY_GROUPS_USAGE_AUDIT\",\"deleteUnusedSecurityGroups\":false,\"coalesceRedundantSecurityGroups\":true}"
        },
        "ResourceType": "AWS::EC2::SecurityGroup",
        "ResourceTags": [],
        "ExcludeResourceTags": false,
        "RemediationEnabled": false
    },
    "TagList": [
        {
            "Key": "foo",
            "Value": "foo"
        }
    ]
}
```
出力:  

```
{
    "Policy": {
        "PolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "PolicyName": "test",
        "PolicyUpdateToken": "1:X9QGexP7HASDlsFp+G31Iw==",
        "SecurityServicePolicyData": {
            "Type": "SECURITY_GROUPS_USAGE_AUDIT",
            "ManagedServiceData": "{\"type\":\"SECURITY_GROUPS_USAGE_AUDIT\",\"deleteUnusedSecurityGroups\":false,\"coalesceRedundantSecurityGroups\":true,\"optionalDelayForUnusedInMinutes\":null}"
        },
        "ResourceType": "AWS::EC2::SecurityGroup",
        "ResourceTags": [],
        "ExcludeResourceTags": false,
        "RemediationEnabled": false
    },
    "PolicyArn": "arn:aws:fms:us-west-2:123456789012:policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「 WAF、[AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「Firewall Manager ポリシーの使用](https://docs.aws.amazon.com/waf/latest/developerguide/working-with-policies.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fms/put-policy.html)」を参照してください。

# AWS FIS を使用した の例 AWS CLI
<a name="cli_2_fis_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS FIS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-experiment-template`
<a name="fis_CreateExperimentTemplate_cli_2_topic"></a>

次のコード例は、`create-experiment-template` を使用する方法を示しています。

**AWS CLI**  
**実験テンプレートを作成するには**  
次の の`create-experiment-template`例では、FIS AWS アカウントに実験テンプレートを作成します。  

```
aws fis create-experiment-template \
    --cli-input-json file://myfile.json
```
`myfile.json` の内容:  

```
{
    "description": "experimentTemplate",
    "stopConditions": [
        {
            "source": "aws:cloudwatch:alarm",
            "value": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:alarmName"
        }
    ],
    "targets": {
        "Instances-Target-1": {
            "resourceType": "aws:ec2:instance",
            "resourceArns": [
                "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
            ],
            "selectionMode": "ALL"
        }
    },
    "actions": {
        "reboot": {
            "actionId": "aws:ec2:reboot-instances",
            "description": "reboot",
            "parameters": {},
            "targets": {
                "Instances": "Instances-Target-1"
            }
        }
    },
    "roleArn": "arn:aws:iam::123456789012:role/myRole"
}
```
出力:  

```
{
    "experimentTemplate": {
        "id": "ABCDE1fgHIJkLmNop",
        "description": "experimentTemplate",
        "targets": {
            "Instances-Target-1": {
                "resourceType": "aws:ec2:instance",
                "resourceArns": [
                    "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
                ],
                "selectionMode": "ALL"
            }
        },
        "actions": {
            "reboot": {
                "actionId": "aws:ec2:reboot-instances",
                "description": "reboot",
                "parameters": {},
                "targets": {
                    "Instances": "Instances-Target-1"
                }
            }
        },
        "stopConditions": [
            {
                "source": "aws:cloudwatch:alarm",
                "value": "arn:aws:cloudwatch:us-west-2:123456789012:alarm:alarmName"
            }
        ],
        "creationTime": 1616434850.659,
        "lastUpdateTime": 1616434850.659,
        "roleArn": "arn:aws:iam::123456789012:role/myRole",
        "tags": {}
    }
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[実験テンプレートを作成する](https://docs.aws.amazon.com/fis/latest/userguide/working-with-templates.html#create-template)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateExperimentTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/create-experiment-template.html)」を参照してください。

### `delete-experiment-template`
<a name="fis_DeleteExperimentTemplate_cli_2_topic"></a>

次のコード例は、`delete-experiment-template` を使用する方法を示しています。

**AWS CLI**  
**実験テンプレートを削除するには**  
次の `delete-experiment-template` の例では、指定された実験テンプレートを削除します。  

```
aws fis delete-experiment-template \
    --id ABCDE1fgHIJkLmNop
```
出力:  

```
{
    "experimentTemplate": {
        "id": "ABCDE1fgHIJkLmNop",
        "description": "myExperimentTemplate",
        "targets": {
            "Instances-Target-1": {
                "resourceType": "aws:ec2:instance",
                "resourceArns": [
                    "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
                ],
                "selectionMode": "ALL"
            }
        },
        "actions": {
            "testaction": {
                "actionId": "aws:ec2:stop-instances",
                "parameters": {},
                "targets": {
                    "Instances": "Instances-Target-1"
                }
            }
        },
        "stopConditions": [
            {
                "source": "none"
            }
        ],
        "creationTime": 1616017191.124,
        "lastUpdateTime": 1616017859.607,
        "roleArn": "arn:aws:iam::123456789012:role/FISRole"
    }
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[実験テンプレートを削除する](https://docs.aws.amazon.com/fis/latest/userguide/working-with-templates.html#delete-template)」を参照してください。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteExperimentTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/delete-experiment-template.html)」を参照してください。

### `get-action`
<a name="fis_GetAction_cli_2_topic"></a>

次のコード例は、`get-action` を使用する方法を示しています。

**AWS CLI**  
**アクションの詳細を取得するには**  
次の `get-action` の例では、指定されたアクションの詳細を取得します。  

```
aws fis get-action \
    --id aws:ec2:stop-instances
```
出力:  

```
{
    "action": {
        "id": "aws:ec2:stop-instances",
        "description": "Stop the specified EC2 instances.",
        "parameters": {
            "startInstancesAfterDuration": {
                "description": "The time to wait before restarting the instances (ISO 8601 duration).",
                "required": false
            }
        },
        "targets": {
            "Instances": {
                "resourceType": "aws:ec2:instance"
            }
        },
        "tags": {}
    }
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[アクション](https://docs.aws.amazon.com/fis/latest/userguide/actions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/get-action.html)」を参照してください。

### `get-experiment-template`
<a name="fis_GetExperimentTemplate_cli_2_topic"></a>

次のコード例は、`get-experiment-template` を使用する方法を示しています。

**AWS CLI**  
**実験テンプレートの詳細を取得するには**  
次の `get-experiment-template` の例では、指定された実験テンプレートの詳細を取得します。  

```
aws fis get-experiment-template \
    --id ABCDE1fgHIJkLmNop
```
出力:  

```
{
    "experimentTemplate": {
        "id": "ABCDE1fgHIJkLmNop",
        "description": "myExperimentTemplate",
        "targets": {
            "Instances-Target-1": {
                "resourceType": "aws:ec2:instance",
                "resourceArns": [
                    "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
                ],
                "selectionMode": "ALL"
            }
        },
        "actions": {
            "testaction": {
                "actionId": "aws:ec2:stop-instances",
                "parameters": {},
                "targets": {
                    "Instances": "Instances-Target-1"
                }
            }
        },
        "stopConditions": [
            {
                "source": "none"
            }
        ],
        "creationTime": 1616017191.124,
        "lastUpdateTime": 1616017331.51,
        "roleArn": "arn:aws:iam::123456789012:role/FISRole",
        "tags": {
        "key: "value"
        }
    }
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[実験テンプレート](https://docs.aws.amazon.com/fis/latest/userguide/experiment-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetExperimentTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/get-experiment-template.html)」を参照してください。

### `get-experiment`
<a name="fis_GetExperiment_cli_2_topic"></a>

次のコード例は、`get-experiment` を使用する方法を示しています。

**AWS CLI**  
**実験の詳細を取得するには**  
次の `get-experiment` の例では、指定された実験の詳細を取得します。  

```
aws fis get-experiment \
    --id ABC12DeFGhI3jKLMNOP
```
出力:  

```
{
    "experiment": {
        "id": "ABC12DeFGhI3jKLMNOP",
        "experimentTemplateId": "ABCDE1fgHIJkLmNop",
        "roleArn": "arn:aws:iam::123456789012:role/myRole",
        "state": {
            "status": "completed",
            "reason": "Experiment completed."
        },
        "targets": {
            "Instances-Target-1": {
                "resourceType": "aws:ec2:instance",
                "resourceArns": [
                    "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
                ],
                "selectionMode": "ALL"
            }
        },
        "actions": {
            "reboot": {
                "actionId": "aws:ec2:reboot-instances",
                "parameters": {},
                "targets": {
                    "Instances": "Instances-Target-1"
                },
                "state": {
                    "status": "completed",
                    "reason": "Action was completed."
                }
            }
        },
        "stopConditions": [
            {
                "source": "none"
            }
        ],
        "creationTime": 1616432509.662,
        "startTime": 1616432509.962,
        "endTime": 1616432522.307,
        "tags": {}
    }
}
```
詳細については、[「 Fault Injection Simulator User Guide」の「Experiments for AWS FIS](https://docs.aws.amazon.com/fis/latest/userguide/experiments.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetExperiment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/get-experiment.html)」を参照してください。

### `list-actions`
<a name="fis_ListActions_cli_2_topic"></a>

次のコード例は、`list-actions` を使用する方法を示しています。

**AWS CLI**  
**アクションを一覧表示するには**  
次の `list-actions` の例は、使用可能なアクションを一覧表示します。  

```
aws fis list-actions
```
出力:  

```
{
    "actions": [
        {
            "id": "aws:ec2:reboot-instances",
            "description": "Reboot the specified EC2 instances.",
            "targets": {
                "Instances": {
                    "resourceType": "aws:ec2:instance"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:ec2:stop-instances",
            "description": "Stop the specified EC2 instances.",
            "targets": {
                "Instances": {
                    "resourceType": "aws:ec2:instance"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:ec2:terminate-instances",
            "description": "Terminate the specified EC2 instances.",
            "targets": {
                "Instances": {
                    "resourceType": "aws:ec2:instance"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:ecs:drain-container-instances",
            "description": "Drain percentage of underlying EC2 instances on an ECS cluster.",
            "targets": {
                "Clusters": {
                    "resourceType": "aws:ecs:cluster"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:eks:terminate-nodegroup-instances",
            "description": "Terminates a percentage of the underlying EC2 instances in an EKS cluster.",
            "targets": {
                "Nodegroups": {
                    "resourceType": "aws:eks:nodegroup"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:fis:inject-api-internal-error",
            "description": "Cause an AWS service to return internal error responses for specific callers and operations.",
            "targets": {
                "Roles": {
                    "resourceType": "aws:iam:role"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:fis:inject-api-throttle-error",
            "description": "Cause an AWS service to return throttled responses for specific callers and operations.",
            "targets": {
                "Roles": {
                    "resourceType": "aws:iam:role"
                }
            },
            "tags": {}
        },
        {
        "id": "aws:fis:inject-api-unavailable-error",
            "description": "Cause an AWS service to return unavailable error responses for specific callers and operations.",
            "targets": {
                "Roles": {
                    "resourceType": "aws:iam:role"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:fis:wait",
            "description": "Wait for the specified duration. Stop condition monitoring will continue during this time.",
            "tags": {}
        },
        {
            "id": "aws:rds:failover-db-cluster",
            "description": "Failover a DB Cluster to one of the replicas.",
            "targets": {
                "Clusters": {
                    "resourceType": "aws:rds:cluster"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:rds:reboot-db-instances",
            "description": "Reboot the specified DB instances.",
            "targets": {
                "DBInstances": {
                    "resourceType": "aws:rds:db"
                }
            },
            "tags": {}
        },
        {
            "id": "aws:ssm:send-command",
            "description": "Run the specified SSM document.",
            "targets": {
                "Instances": {
                    "resourceType": "aws:ec2:instance"
                }
            },
            "tags": {}
        }
    ]
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[アクション](https://docs.aws.amazon.com/fis/latest/userguide/actions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/list-actions.html)」を参照してください。

### `list-experiment-templates`
<a name="fis_ListExperimentTemplates_cli_2_topic"></a>

次のコード例は、`list-experiment-templates` を使用する方法を示しています。

**AWS CLI**  
**実験テンプレートを一覧表示するには**  
次の の`list-experiment-templates`例では、 AWS アカウントの実験テンプレートを一覧表示します。  

```
aws fis list-experiment-templates
```
出力:  

```
{
    "experimentTemplates": [
        {
            "id": "ABCDE1fgHIJkLmNop",
            "description": "myExperimentTemplate",
            "creationTime": 1616017191.124,
            "lastUpdateTime": 1616017191.124,
            "tags": {
                "key": "value"
            }
        }
    ]
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[実験テンプレート](https://docs.aws.amazon.com/fis/latest/userguide/experiment-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListExperimentTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/list-experiment-templates.html)」を参照してください。

### `list-experiments`
<a name="fis_ListExperiments_cli_2_topic"></a>

次のコード例は、`list-experiments` を使用する方法を示しています。

**AWS CLI**  
**実験を一覧表示するには**  
次の の`list-experiments`例では、 AWS アカウントの実験を一覧表示します。  

```
aws fis list-experiments
```
出力:  

```
{
    "experiments": [
        {
            "id": "ABCdeF1GHiJkLM23NO",
            "experimentTemplateId": "ABCDE1fgHIJkLmNop",
            "state": {
                "status": "running",
                "reason": "Experiment is running."
            },
            "creationTime": 1616017341.197,
            "tags": {
            "key": "value"
            }
        }
    ]
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[実験](https://docs.aws.amazon.com/fis/latest/userguide/experiments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListExperiments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/list-experiments.html)」を参照してください。

### `list-tags-for-resource`
<a name="fis_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定したリソースのタグを一覧表示します。  

```
aws fis list-tags-for-resource \
    --resource-arn arn:aws:fis:us-west-2:123456789012:experiment/ABC12DeFGhI3jKLMNOP
```
出力:  

```
{
    "tags": {
        "key1": "value1",
        "key2": "value2"
    }
}
```
詳細については、「 *AWS Fault Injection Simulator ユーザーガイド*[AWS 」の「FIS リソースのタグ付け](https://docs.aws.amazon.com/fis/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/list-tags-for-resource.html)」を参照してください。

### `start-experiment`
<a name="fis_StartExperiment_cli_2_topic"></a>

次のコード例は、`start-experiment` を使用する方法を示しています。

**AWS CLI**  
**実験を開始するには**  
次の `start-experiment` の例では、指定された実験を開始します。  

```
aws fis start-experiment \
    --experiment-template-id ABCDE1fgHIJkLmNop
```
出力:  

```
{
    "experiment": {
        "id": "ABC12DeFGhI3jKLMNOP",
        "experimentTemplateId": "ABCDE1fgHIJkLmNop",
        "roleArn": "arn:aws:iam::123456789012:role/myRole",
        "state": {
            "status": "initiating",
            "reason": "Experiment is initiating."
        },
        "targets": {
            "Instances-Target-1": {
                "resourceType": "aws:ec2:instance",
                "resourceArns": [
                    "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
                ],
                "selectionMode": "ALL"
            }
        },
        "actions": {
            "reboot": {
                "actionId": "aws:ec2:reboot-instances",
                "parameters": {},
                "targets": {
                    "Instances": "Instances-Target-1"
                },
                "state": {
                    "status": "pending",
                    "reason": "Initial state"
                }
            }
        },
        "stopConditions": [
            {
                "source": "none"
            }
        ],
        "creationTime": 1616432464.025,
        "startTime": 1616432464.374,
        "tags": {}
    }
}
```
詳細については、[「 Fault Injection Simulator User Guide」の「Experiments for AWS FIS](https://docs.aws.amazon.com/fis/latest/userguide/experiments.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartExperiment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/start-experiment.html)」を参照してください。

### `stop-experiment`
<a name="fis_StopExperiment_cli_2_topic"></a>

次のコード例は、`stop-experiment` を使用する方法を示しています。

**AWS CLI**  
**実験を中止するには**  
次の `stop-experiment` の例では、指定された実験の実行を停止します。  

```
aws fis stop-experiment \
    --id ABC12DeFGhI3jKLMNOP
```
出力:  

```
{
    "experiment": {
        "id": "ABC12DeFGhI3jKLMNOP",
        "experimentTemplateId": "ABCDE1fgHIJkLmNop",
        "roleArn": "arn:aws:iam::123456789012:role/myRole",
        "state": {
            "status": "stopping",
            "reason": "Stopping Experiment."
        },
        "targets": {
            "Instances-Target-1": {
                "resourceType": "aws:ec2:instance",
                "resourceArns": [
                    "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
                ],
                "selectionMode": "ALL"
            }
        },
        "actions": {
            "reboot": {
                "actionId": "aws:ec2:reboot-instances",
                "parameters": {},
                "targets": {
                    "Instances": "Instances-Target-1"
                },
                "startAfter": [
                    "wait"
                ],
                "state": {
                    "status": "pending",
                    "reason": "Initial state."
                }
            },
            "wait": {
                "actionId": "aws:fis:wait",
                "parameters": {
                    "duration": "PT5M"
                },
                "state": {
                    "status": "running",
                    "reason": ""
                }
            }
        },
        "stopConditions": [
            {
                "source": "none"
            }
        ],
        "creationTime": 1616432680.927,
        "startTime": 1616432681.177,
        "tags": {}
    }
}
```
詳細については、[「 Fault Injection Simulator User Guide」の「Experiments for AWS FIS](https://docs.aws.amazon.com/fis/latest/userguide/experiments.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopExperiment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/stop-experiment.html)」を参照してください。

### `tag-resource`
<a name="fis_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、指定されたリソースにタグ付けします。  

```
aws fis tag-resource \
    --resource-arn arn:aws:fis:us-west-2:123456789012:experiment/ABC12DeFGhI3jKLMNOP \
    --tags key1=value1,key2=value2
```
このコマンドでは何も出力されません。  
詳細については、「 *AWS Fault Injection Simulator ユーザーガイド*[AWS 」の「FIS リソースのタグ付け](https://docs.aws.amazon.com/fis/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="fis_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを削除するには**  
次の `untag-resource` の例では、指定されたリソースからタグを削除します。  

```
aws fis untag-resource \
    --resource-arn arn:aws:fis:us-west-2:123456789012:experiment/ABC12DeFGhI3jKLMNOP
```
このコマンドでは何も出力されません。  
詳細については、「 *AWS Fault Injection Simulator ユーザーガイド*[AWS 」の「FIS リソースのタグ付け](https://docs.aws.amazon.com/fis/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/untag-resource.html)」を参照してください。

### `update-experiment-template`
<a name="fis_UpdateExperimentTemplate_cli_2_topic"></a>

次のコード例は、`update-experiment-template` を使用する方法を示しています。

**AWS CLI**  
**実験テンプレートを更新するには**  
次の `update-experiment-template` の例では、指定された実験テンプレートの説明を更新します。  

```
aws fis update-experiment-template \
    --id ABCDE1fgHIJkLmNop \
    ---description myExperimentTemplate
```
出力:  

```
{
    "experimentTemplate": {
        "id": "ABCDE1fgHIJkLmNop",
        "description": "myExperimentTemplate",
        "targets": {
            "Instances-Target-1": {
                "resourceType": "aws:ec2:instance",
                "resourceArns": [
                    "arn:aws:ec2:us-west-2:123456789012:instance/i-12a3b4c56d78e9012"
                ],
                "selectionMode": "ALL"
            }
        },
        "actions": {
            "testaction": {
                "actionId": "aws:ec2:stop-instances",
                "parameters": {},
                "targets": {
                    "Instances": "Instances-Target-1"
                }
            }
        },
        "stopConditions": [
            {
                "source": "none"
            }
        ],
        "creationTime": 1616017191.124,
        "lastUpdateTime": 1616017859.607,
        "roleArn": "arn:aws:iam::123456789012:role/FISRole",
        "tags": {
            "key": "value"
        }
    }
}
```
詳細については、「*AWS Fault Injection Simulator ユーザーガイド*」の「[実験テンプレートを更新する](https://docs.aws.amazon.com/fis/latest/userguide/working-with-templates.html#update-template)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateExperimentTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/fis/update-experiment-template.html)」を参照してください。

# を使用した Amazon GameLift サーバーの例 AWS CLI
<a name="cli_2_gamelift_code_examples"></a>

次のコード例は、Amazon GameLift サーバー AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-build`
<a name="gamelift_CreateBuild_cli_2_topic"></a>

次のコード例は、`create-build` を使用する方法を示しています。

**AWS CLI**  
**Example1: S3 バケット内のファイルからゲームビルドを作成するには**  
次の `create-build` の例では、カスタムゲームビルドリソースを作成します。管理している AWS アカウントの S3 の場所に保存されている zip ファイルを使用します。この例では、Amazon GameLift に S3 ロケーションへのアクセス許可を付与する IAM ロールを既に作成していることを前提としています。リクエストはオペレーティングシステムを指定しないため、新しいビルドリソースはデフォルトで WINDOWS\$12012 になります。  

```
aws gamelift create-build \
    --storage-location file://storage-loc.json \
    --name MegaFrogRaceServer.NA \
    --build-version 12345.678
```
`storage-loc.json` の内容:  

```
{
    "Bucket":"MegaFrogRaceServer_NA_build_files"
    "Key":"MegaFrogRaceServer_build_123.zip"
    "RoleArn":"arn:aws:iam::123456789012:role/gamelift"
}
```
出力:  

```
{
    "Build": {
        "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "CreationTime": 1496708916.18,
        "Name": "MegaFrogRaceServer.NA",
        "OperatingSystem": "WINDOWS_2012",
        "SizeOnDisk": 479303,
        "Status": "INITIALIZED",
        "Version": "12345.678"
    },
    "StorageLocation": {
        "Bucket": "MegaFrogRaceServer_NA_build_files",
        "Key": "MegaFrogRaceServer_build_123.zip"
    }
}
```
**Example2: GameLift にファイルを手動でアップロードするためのゲームビルドリソースを作成するには**  
次の `create-build` の例では、新しいビルドリソースを作成します。また、Amazon S3 の GameLift ロケーションにゲームビルドを手動でアップロードできるストレージロケーションと一時的な認証情報も取得します。ビルドが正常にアップロードされると、GameLift サービスはビルドを検証し、新しいビルドのステータスを更新します。  

```
aws gamelift create-build \
    --name MegaFrogRaceServer.NA \
    --build-version 12345.678 \
    --operating-system AMAZON_LINUX
```
出力:  

```
{
    "Build": {
        "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "CreationTime": 1496708916.18,
        "Name": "MegaFrogRaceServer.NA",
        "OperatingSystem": "AMAZON_LINUX",
        "SizeOnDisk": 0,
        "Status": "INITIALIZED",
        "Version": "12345.678"
    },
    "StorageLocation": {
        "Bucket": "gamelift-builds-us-west-2",
        "Key": "123456789012/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    },
    "UploadCredentials": {
        "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "SessionToken": "AgoGb3JpZ2luENz...EXAMPLETOKEN=="
    }
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[カスタムサーバービルドを GameLift にアップロードする](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-build-cli-uploading.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/create-build.html)」を参照してください。

### `create-fleet`
<a name="gamelift_CreateFleet_cli_2_topic"></a>

次のコード例は、`create-fleet` を使用する方法を示しています。

**AWS CLI**  
**例 1: 基本的な Linux フリートを作成するには**  
次の `create-fleet` の例では、カスタムサーバービルドをホストするために、最小限の設定でオンデマンド Linux インスタンスのフリートを作成します。これは、`update-fleet` を使用することで設定を完了できます。  

```
aws gamelift create-fleet \
    --name MegaFrogRaceServer.NA.v2 \
    --description 'Hosts for v2 North America' \
    --build-id build-1111aaaa-22bb-33cc-44dd-5555eeee66ff \
    --certificate-configuration 'CertificateType=GENERATED' \
    --ec2-instance-type c4.large \
    --fleet-type ON_DEMAND \
    --runtime-configuration 'ServerProcesses=[{LaunchPath=/local/game/release-na/MegaFrogRace_Server.exe,ConcurrentExecutions=1}]'
```
出力:  

```
{
    "FleetAttributes": {
        "BuildId": "build-1111aaaa-22bb-33cc-44dd-5555eeee66ff",
        "CertificateConfiguration": {
            "CertificateType": "GENERATED"
        },
        "CreationTime": 1496365885.44,
        "Description": "Hosts for v2 North America",
        "FleetArn": "arn:aws:gamelift:us-west-2:444455556666:fleet/fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "FleetId": "fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "FleetType": "ON_DEMAND",
        "InstanceType": "c4.large",
        "MetricGroups": ["default"],
        "Name": "MegaFrogRace.NA.v2",
        "NewGameSessionProtectionPolicy": "NoProtection",
        "OperatingSystem": "AMAZON_LINUX",
        "ServerLaunchPath": "/local/game/release-na/MegaFrogRace_Server.exe",
        "Status": "NEW"
    }
}
```
**例 2: 基本的な Windows フリートを作成するには**  
次の `create-fleet` の例では、カスタムサーバービルドをホストするために、最小限の設定でスポット Windows インスタンスのフリートを作成します。これは、`update-fleet` を使用することで設定を完了できます。  

```
aws gamelift create-fleet \
    --name MegaFrogRace.NA.v2 \
    --description 'Hosts for v2 North America' \
    --build-id build-2222aaaa-33bb-44cc-55dd-6666eeee77ff  \
    --certificate-configuration 'CertificateType=GENERATED' \
    --ec2-instance-type c4.large \
    --fleet-type SPOT \
    --runtime-configuration 'ServerProcesses=[{LaunchPath=C:\game\Bin64.Release.Dedicated\MegaFrogRace_Server.exe,ConcurrentExecutions=1}]'
```
出力:  

```
{
    "FleetAttributes": {
        "BuildId": "build-2222aaaa-33bb-44cc-55dd-6666eeee77ff",
        "CertificateConfiguration": {
            "CertificateType": "GENERATED"
        },
        "CreationTime": 1496365885.44,
        "Description": "Hosts for v2 North America",
        "FleetArn": "arn:aws:gamelift:us-west-2:444455556666:fleet/fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "FleetId": "fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "FleetType": "SPOT",
        "InstanceType": "c4.large",
        "MetricGroups": ["default"],
        "Name": "MegaFrogRace.NA.v2",
        "NewGameSessionProtectionPolicy": "NoProtection",
        "OperatingSystem": "WINDOWS_2012",
        "ServerLaunchPath": "C:\game\Bin64.Release.Dedicated\MegaFrogRace_Server.exe",
        "Status": "NEW"
    }
}
```
**例 3: 完全に設定されたフリートを作成するには**  
次の `create-fleet` の例では、カスタムサーバービルド用のスポット Windows インスタンスのフリートを作成し、最も一般的に使用される設定を提供します。  

```
aws gamelift create-fleet \
    --name MegaFrogRace.NA.v2 \
    --description 'Hosts for v2 North America' \
    --build-id build-2222aaaa-33bb-44cc-55dd-6666eeee77ff \
    --certificate-configuration 'CertificateType=GENERATED' \
    --ec2-instance-type c4.large \
    --ec2-inbound-permissions 'FromPort=33435,ToPort=33435,IpRange=10.24.34.0/23,Protocol=UDP' \
    --fleet-type SPOT \
    --new-game-session-protection-policy FullProtection \
    --runtime-configuration file://runtime-config.json \
    --metric-groups default \
    --instance-role-arn 'arn:aws:iam::444455556666:role/GameLiftS3Access'
```
`runtime-config.json` の内容:  

```
GameSessionActivationTimeoutSeconds=300,
 MaxConcurrentGameSessionActivations=2,
 ServerProcesses=[
   {LaunchPath=C:\game\Bin64.Release.Dedicated\MegaFrogRace_Server.exe,Parameters=-debug,ConcurrentExecutions=1},
   {LaunchPath=C:\game\Bin64.Release.Dedicated\MegaFrogRace_Server.exe,ConcurrentExecutions=1}]
```
出力:  

```
{
    "FleetAttributes": {
        "InstanceRoleArn": "arn:aws:iam::444455556666:role/GameLiftS3Access",
        "Status": "NEW",
        "InstanceType": "c4.large",
        "FleetArn": "arn:aws:gamelift:us-west-2:444455556666:fleet/fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "FleetId": "fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "Description": "Hosts for v2 North America",
        "FleetType": "SPOT",
        "OperatingSystem": "WINDOWS_2012",
        "Name": "MegaFrogRace.NA.v2",
        "CreationTime": 1569309011.11,
        "MetricGroups": [
            "default"
        ],
        "BuildId": "build-2222aaaa-33bb-44cc-55dd-6666eeee77ff",
        "ServerLaunchParameters": "abc",
        "ServerLaunchPath": "C:\\game\\Bin64.Release.Dedicated\\MegaFrogRace_Server.exe",
        "NewGameSessionProtectionPolicy": "FullProtection",
        "CertificateConfiguration": {
            "CertificateType": "GENERATED"
        }
    }
}
```
**例 4: Realtime サーバーフリートを作成するには**  
次の `create-fleet` の例では、Amazon GameLift にアップロードされたリアルタイム設定スクリプトを使用して、スポットインスタンスのフリートを作成します。すべてのリアルタイムサーバーは Linux マシンにデプロイされます。この例では、アップロードされた Realtime スクリプトに複数のスクリプトファイルが含まれ、`MainScript.js` というスクリプトファイルにある `Init()` 関数があるとします。図に示すように、このファイルはランタイム設定で起動スクリプトとして識別されます。  

```
aws gamelift create-fleet \
    --name MegaFrogRace.NA.realtime \
    --description 'Mega Frog Race Realtime fleet' \
    --script-id script-1111aaaa-22bb-33cc-44dd-5555eeee66ff \
    --ec2-instance-type c4.large \
    --fleet-type SPOT \
    --certificate-configuration 'CertificateType=GENERATED' --runtime-configuration 'ServerProcesses=[{LaunchPath=/local/game/MainScript.js,Parameters=+map Winter444,ConcurrentExecutions=5}]'
```
出力:  

```
{
    "FleetAttributes": {
        "FleetId": "fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "Status": "NEW",
        "CreationTime": 1569310745.212,
        "InstanceType": "c4.large",
        "NewGameSessionProtectionPolicy": "NoProtection",
        "CertificateConfiguration": {
            "CertificateType": "GENERATED"
        },
        "Name": "MegaFrogRace.NA.realtime",
        "ScriptId": "script-1111aaaa-22bb-33cc-44dd-5555eeee66ff",
        "FleetArn": "arn:aws:gamelift:us-west-2:444455556666:fleet/fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
        "FleetType": "SPOT",
        "MetricGroups": [
            "default"
        ],
        "Description": "Mega Frog Race Realtime fleet",
        "OperatingSystem": "AMAZON_LINUX"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/create-fleet.html)」を参照してください。

### `create-game-session-queue`
<a name="gamelift_CreateGameSessionQueue_cli_2_topic"></a>

次のコード例は、`create-game-session-queue` を使用する方法を示しています。

**AWS CLI**  
**例 1: 順序付けられたゲームセッションキューを設定するには**  
次の `create-game-session-queue` の例では、2 つのリージョンに送信先を持つ新しいゲームセッションキューを作成します。また、配置を 10 分待ってからゲームセッションリクエストがタイムアウトするようにキューを設定します。レイテンシーポリシーは定義されていないため、GameLift は最初の送信先がリストされているすべてのゲームセッションを配置しようとします。  

```
aws gamelift create-game-session-queue \
    --name MegaFrogRaceServer-NA \
    --destinations file://destinations.json \
    --timeout-in-seconds 600
```
`destinations.json` の内容:  

```
{
    "Destinations": [
        {"DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" },
        {"DestinationArn": "arn:aws:gamelift:us-west-1::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222" }
    ]
}
```
出力:  

```
{
    "GameSessionQueues": [
        {
            "Name": "MegaFrogRaceServer-NA",
            "GameSessionQueueArn": "arn:aws:gamelift:us-west-2:123456789012:gamesessionqueue/MegaFrogRaceServer-NA",
            "TimeoutInSeconds": 600,
            "Destinations": [
                {"DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"},
                {"DestinationArn": "arn:aws:gamelift:us-west-1::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"}
            ]
        }
    ]
}
```
**例 2: プレイヤーのレイテンシーポリシーを使用してゲームセッションキューを設定するには**  
次の `create-game-session-queue` の例では、2 つのプレイヤーレイテンシーポリシーを持つ新しいゲームセッションキューを作成します。最初のポリシーは、ゲームセッションプレイスメントの最初の 1 分間に強制される 100 ミリ秒のレイテンシー上限を設定します。2 番目のポリシーでは、プレイスメントリクエストが 3 分でタイムアウトするまで、レイテンシーの上限が 200 ミリ秒に引き上げられます。  

```
aws gamelift create-game-session-queue \
    --name MegaFrogRaceServer-NA \
    --destinations file://destinations.json \
    --player-latency-policies file://latency-policies.json \
    --timeout-in-seconds 180
```
`destinations.json` の内容:  

```
{
    "Destinations": [
        { "DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" },
        { "DestinationArn": "arn:aws:gamelift:us-east-1::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222" }
    ]
}
```
`latency-policies.json` の内容:  

```
{
    "PlayerLatencyPolicies": [
        {"MaximumIndividualPlayerLatencyMilliseconds": 200},
        {"MaximumIndividualPlayerLatencyMilliseconds": 100, "PolicyDurationSeconds": 60}
    ]
}
```
出力:  

```
{
    "GameSessionQueue": {
        "Name": "MegaFrogRaceServer-NA",
        "GameSessionQueueArn": "arn:aws:gamelift:us-west-2:111122223333:gamesessionqueue/MegaFrogRaceServer-NA",
        "TimeoutInSeconds": 600,
        "PlayerLatencyPolicies": [
            {
                "MaximumIndividualPlayerLatencyMilliseconds": 100,
                "PolicyDurationSeconds": 60
            },
            {
                "MaximumIndividualPlayerLatencyMilliseconds": 200
            }
        ]
        "Destinations": [
            {"DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"},
            {"DestinationArn": "arn:aws:gamelift:us-east-1::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"}
        ],
    }
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[キューを作成する](https://docs.aws.amazon.com/gamelift/latest/developerguide/queues-creating.html#queues-creating-cli)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGameSessionQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/create-game-session-queue.html)」を参照してください。

### `delete-build`
<a name="gamelift_DeleteBuild_cli_2_topic"></a>

次のコード例は、`delete-build` を使用する方法を示しています。

**AWS CLI**  
**カスタムゲームビルドを削除するには**  
次の `delete-build` の例では、Amazon GameLift アカウントからビルドを削除します。ビルドが削除された後は、それを使用して新しいフリートを作成することはできません。この操作は元に戻すことができません。  

```
aws gamelift delete-build \
   --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/delete-build.html)」を参照してください。

### `delete-fleet`
<a name="gamelift_DeleteFleet_cli_2_topic"></a>

次のコード例は、`delete-fleet` を使用する方法を示しています。

**AWS CLI**  
**使用されていないフリートを削除するには**  
次の `delete-fleet` の例では、ゼロインスタンスにスケールダウンされたフリートを削除します。フリート容量が 0 より大きい場合、リクエストは HTTP 400 エラーで失敗します。  

```
aws gamelift delete-fleet \
   --fleet-id fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[GameLift フリートを管理する](https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-editing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFleet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/delete-fleet.html)」を参照してください。

### `delete-game-session-queue`
<a name="gamelift_DeleteGameSessionQueue_cli_2_topic"></a>

次のコード例は、`delete-game-session-queue` を使用する方法を示しています。

**AWS CLI**  
**ゲームセッションキューを削除するには**  
次の `delete-game-session-queue` の例では、指定されたゲームセッションキューを削除します。  

```
aws gamelift delete-game-session-queue \
    --name MegaFrogRace-NA
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGameSessionQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/delete-game-session-queue.html)」を参照してください。

### `describe-build`
<a name="gamelift_DescribeBuild_cli_2_topic"></a>

次のコード例は、`describe-build` を使用する方法を示しています。

**AWS CLI**  
**カスタムゲームビルドに関する情報を取得するには**  
次の `describe-build` の例では、ゲームサーバービルドリソースのプロパティを取得します。  

```
aws gamelift describe-build \
    --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "Build": {
        "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "CreationTime": 1496708916.18,
        "Name": "My_Game_Server_Build_One",
        "OperatingSystem": "AMAZON_LINUX",
        "SizeOnDisk": 1304924,
        "Status": "READY",
        "Version": "12345.678"
    }
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[カスタムサーバービルドを GameLift にアップロードする](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-build-cli-uploading.html#gamelift-build-cli-uploading-builds)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-build.html)」を参照してください。

### `describe-ec2-instance-limits`
<a name="gamelift_DescribeEc2InstanceLimits_cli_2_topic"></a>

次のコード例は、`describe-ec2-instance-limits` を使用する方法を示しています。

**AWS CLI**  
**EC2 インスタンスタイプのサービス制限を取得するには**  
次の `describe-ec2-instance-limits` の例では、現在のリージョンで指定された EC2 インスタンスタイプで使用されている最大許容インスタンスと現在のインスタンスを表示します。結果は、許可された 20 個のインスタンスのうち 5 個のみが使用されていることを示します。  

```
aws gamelift describe-ec2-instance-limits \
    --ec2-instance-type m5.large
```
出力:  

```
{
    "EC2InstanceLimits": [
        {
            "EC2InstanceType": ""m5.large",
            "CurrentInstances": 5,
            "InstanceLimit": 20
        }
    ]
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[コンピューティングリソースを選択する](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-ec2-instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEc2InstanceLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-ec2-instance-limits.html)」を参照してください。

### `describe-fleet-attributes`
<a name="gamelift_DescribeFleetAttributes_cli_2_topic"></a>

次のコード例は、`describe-fleet-attributes` を使用する方法を示しています。

**AWS CLI**  
**例 1: フリートのリストの属性を表示するには**  
次の `describe-fleet-attributes` の例では、指定された 2 つのフリートのフリート属性を取得します。図に示すように、リクエストされたフリートは同じビルドでデプロイされます。1 つはオンデマンドインスタンス用、もう 1 つはスポットインスタンス用で、設定には若干の違いがあります。  

```
aws gamelift describe-fleet-attributes \
    --fleet-ids arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222
```
出力:  

```
{
    "FleetAttributes": [
        {
            "FleetId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "FleetArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "FleetType": "ON_DEMAND",
            "InstanceType": "c4.large",
            "Description": "On-demand hosts for v2 North America",
            "Name": "MegaFrogRaceServer.NA.v2-od",
            "CreationTime": 1568836191.995,
            "Status": "ACTIVE",
            "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "ServerLaunchPath": "C:\\game\\MegaFrogRace_Server.exe",
            "ServerLaunchParameters": "+gamelift_start_server",
            "NewGameSessionProtectionPolicy": "NoProtection",
            "OperatingSystem": "WINDOWS_2012",
            "MetricGroups": [
                "default"
            ],
            "CertificateConfiguration": {
                "CertificateType": "DISABLED"
            }
        },
        {
            "FleetId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "FleetArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "FleetType": "SPOT",
            "InstanceType": "c4.large",
            "Description": "On-demand hosts for v2 North America",
            "Name": "MegaFrogRaceServer.NA.v2-spot",
            "CreationTime": 1568838275.379,
            "Status": "ACTIVATING",
            "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "ServerLaunchPath": "C:\\game\\MegaFrogRace_Server.exe",
            "NewGameSessionProtectionPolicy": "NoProtection",
            "OperatingSystem": "WINDOWS_2012",
                "MetricGroups": [
                "default"
            ],
            "CertificateConfiguration": {
                "CertificateType": "GENERATED"
            }
        }
    ]
}
```
**Example2: すべてのフリートの属性をリクエストするには**  
次の `describe-fleet-attributes` は、ステータスが のすべてのフリートのフリート属性を返します。この例では、ページ分割パラメータを使用して一度に 1 つのフリートを返す方法を示しています。  

```
aws gamelift describe-fleet-attributes \
    --limit 1
```
出力:  

```
{
    "FleetAttributes": [
        {
            "FleetId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "FleetArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "FleetType": "SPOT",
            "InstanceType": "c4.large",
            "Description": "On-demand hosts for v2 North America",
            "Name": "MegaFrogRaceServer.NA.v2-spot",
            "CreationTime": 1568838275.379,
            "Status": "ACTIVATING",
            "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "ServerLaunchPath": "C:\\game\\MegaFrogRace_Server.exe",
            "NewGameSessionProtectionPolicy": "NoProtection",
            "OperatingSystem": "WINDOWS_2012",
            "MetricGroups": [
                "default"
            ],
            "CertificateConfiguration": {
                "CertificateType": "GENERATED"
            }
        }
    ],
    "NextToken": "eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjEXAMPLE2"
}
```
出力には、コマンドを 2 回呼び出すときに使用できる `NextToken` 値が含まれます。値を `--next-token` パラメータに渡して、出力を受け取る場所を指定します。このコマンドは、出力の 2 つ目の結果を返します。  

```
aws gamelift describe-fleet-attributes \
    --limit 1 \
    --next-token eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjEXAMPLE1
```
レスポンスに `NextToken` 値が含まれなくなるまで繰り返します。  
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[GameLift フリートのセットアップ](https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-intro.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleetAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-fleet-attributes.html)」を参照してください。

### `describe-fleet-capacity`
<a name="gamelift_DescribeFleetCapacity_cli_2_topic"></a>

次のコード例は、`describe-fleet-capacity` を使用する方法を示しています。

**AWS CLI**  
**フリートのリストのキャパシティステータスを表示するには**  
次の `describe-fleet-capacity` の例では、指定された 2 つのフリートの現在のキャパシティを取得します。  

```
aws gamelift describe-fleet-capacity \
    --fleet-ids arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222
```
出力:  

```
{
    "FleetCapacity": [
        {
            "FleetId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "InstanceType": "c5.large",
            "InstanceCounts": {
                "DESIRED": 10,
                "MINIMUM": 1,
                "MAXIMUM": 20,
                "PENDING": 0,
                "ACTIVE": 10,
                "IDLE": 3,
                "TERMINATING": 0
            }
        },
        {
            "FleetId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "InstanceType": "c5.large",
            "InstanceCounts": {
                "DESIRED": 13,
                "MINIMUM": 1,
                "MAXIMUM": 20,
                "PENDING": 0,
                "ACTIVE": 15,
                "IDLE": 2,
                "TERMINATING": 2
            }
        }

    ]
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[フリートの GameLift メトリクス](https://docs.aws.amazon.com/gamelift/latest/developerguide/monitoring-cloudwatch.html#gamelift-metrics-fleet)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleetCapacity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-fleet-capacity.html)」を参照してください。

### `describe-fleet-events`
<a name="gamelift_DescribeFleetEvents_cli_2_topic"></a>

次のコード例は、`describe-fleet-events` を使用する方法を示しています。

**AWS CLI**  
**指定された期間にイベントをリクエストするには**  
次の `describe-fleet-events` の例では、指定された期間に発生したすべてのフリート関連イベントの詳細を表示します。  

```
aws gamelift describe-fleet-events \
    --fleet-id arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --start-time 1579647600 \
    --end-time 1579649400 \
    --limit 5
```
出力:  

```
{
    "Events": [
        {
            "EventId": "a37b6892-5d07-4d3b-8b47-80244ecf66b9",
            "ResourceId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "EventCode": "FLEET_STATE_ACTIVE",
            "Message": "Fleet fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 changed state to ACTIVE",
            "EventTime": 1579649342.191
        },
        {
            "EventId": "67da4ec9-92a3-4d95-886a-5d6772c24063",
            "ResourceId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "EventCode": "FLEET_STATE_ACTIVATING",
            "Message": "Fleet fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 changed state to ACTIVATING",
            "EventTime": 1579649321.427
        },
        {
            "EventId": "23813a46-a9e6-4a53-8847-f12e6a8381ac",
            "ResourceId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "EventCode": "FLEET_STATE_BUILDING",
            "Message": "Fleet fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 changed state to BUILDING",
            "EventTime": 1579649321.243
        },
        {
            "EventId": "3bf217d0-1d44-42f9-9202-433ed475d2e8",
            "ResourceId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "EventCode": "FLEET_STATE_VALIDATING",
            "Message": "Fleet fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 changed state to VALIDATING",
            "EventTime": 1579649197.449
        },
        {
            "EventId": "2ecd0130-5986-44eb-99a7-62df27741084",
            "ResourceId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "EventCode": "FLEET_VALIDATION_LAUNCH_PATH_NOT_FOUND",
            "Message": "Failed to find a valid path",
            "EventTime": 1569319075.839,
            "PreSignedLogUrl": "https://gamelift-event-logs-prod-us-west-2.s3.us-west-2.amazonaws.com/logs/fleet-83422059-8329-42a2-a4d6-c4444386a6f8/events/2ecd0130-5986-44eb-99a7-62df27741084/FLEET_VALIDATION_LAUNCH_PATH_NOT_FOUND.txt?X-Amz-Security-Token=IQoJb3JpZ2luX2VjEB8aCXVzLXdlc3QtMiJHMEUCIHV5K%2FLPx8h310D%2FAvx0%2FZxsDy5XA3cJOwPdu3T0eBa%2FAiEA1yovokcZYy%2FV4CWW6l26aFyiSHO%2Bxz%2FBMAhEHYHMQNcqkQMImP%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FARAAGgw3NDEwNjE1OTIxNzEiDI8rsZtzLzlwEDQhXSrlAtl5Ae%2Fgo6FCIzqXPbXfBOnSvFYqeDlriZarEpKqKrUt8mXQv9iqHResqCph9AKo49lwgSYTT2QoSxnrD7%2FUgv%2BZm2pVuczvuKtUA0fcx6s0GxpjIAzdIE%2F5P%2FB7B9M%2BVZ%2F9KF82hbJi0HTE6Y7BjKsEgFCvk4UXILhfjtan9iQl8%2F21ZTurAcJbm7Y5tuLF9SWSK3%2BEa7VXOcCK4D4O1sMjmdRm0q0CKZ%2FIaXoHkNvg0RVTa0hIqdvpaDQlsSBNdqTXbjHTu6fETE9Y9Ky%2BiJK5KiUG%2F59GjCpDcvS1FqKeLUEmKT7wysGmvjMc2n%2Fr%2F9VxQfte7w9srXwlLAQuwhiXAAyI5ICMZ5JvzjzQwTqD4CHTVKUUDwL%2BRZzbuuqkJObZml02CkRGp%2B74RTAzLbWptVqZTIfzctiCTmWxb%2FmKyELRYsVLrwNJ%2BGJ7%2BCrN0RC%2FjlgfLYIZyeAqjPgAu5HjgX%2BM7jCo9M7wBTrnAXKOFQuf9dvA84SuwXOJFp17LYGjrHMKv0qC3GfbTMrZ6kzeNV9awKCpXB2Gnx9z2KvIlJdqirWVpvHVGwKCmJBCesDzjJHrae3neogI1uW%2F9C6%2B4jIZPME3jXmZcEHqqw5uvAVF7aeIavtUZU8pxpDIWT0YE4p3Kriy2AA7ziCRKtVfjV839InyLk8LUjsioWK2qlpg2HXKFLpAXw1QsQyxYmFMB9sGKOUlbL7Jdkk%2BYUq8%2FDTlLxqj1S%2FiO4TI0Wo7ilAo%2FKKWWF4guuNDexj8EOOynSp1yImB%2BZf2Fua3O44W4eEXAMPLE33333&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20170621T231808Z&X-Amz-SignedHeaders=host&X-Amz-Expires=900&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20170621%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
        }
    ],
    "NextToken": "eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjEXAMPLE2"
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[GameLift フリートの問題をデバッグする](https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-creating-debug.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleetEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-fleet-events.html)」を参照してください。

### `describe-fleet-port-settings`
<a name="gamelift_DescribeFleetPortSettings_cli_2_topic"></a>

次のコード例は、`describe-fleet-port-settings` を使用する方法を示しています。

**AWS CLI**  
**フリートに設定されているインバウンド接続のアクセス許可を表示するには**  
次の `describe-fleet-port-settings` の例では、指定されたフリートの接続設定を取得します。  

```
aws gamelift describe-fleet-port-settings \
    --fleet-id arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "InboundPermissions": [
        {
            "FromPort": 33400,
            "ToPort": 33500,
            "IpRange": "0.0.0.0/0",
            "Protocol": "UDP"
        },
        {
            "FromPort": 1900,
            "ToPort": 2000,
            "IpRange": "0.0.0.0/0",
            "Protocol": "TCP"
        }
    ]
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[GameLift フリートのセットアップ](https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-intro.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleetPortSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-fleet-port-settings.html)」を参照してください。

### `describe-fleet-utilization`
<a name="gamelift_DescribeFleetUtilization_cli_2_topic"></a>

次のコード例は、`describe-fleet-utilization` を使用する方法を示しています。

**AWS CLI**  
**例 1: フリートのリストの使用状況データを表示するには**  
次の `describe-fleet-utilization` の例では、指定された 1 つのフリートの現在の使用状況の情報を取得します。  

```
aws gamelift describe-fleet-utilization \
    --fleet-ids arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "FleetUtilization": [
        {
        "FleetId": "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "ActiveServerProcessCount": 100,
        "ActiveGameSessionCount": 62,
        "CurrentPlayerSessionCount": 329,
        "MaximumPlayerSessionCount": 1000
        }
    ]
}
```
**例 2: すべてのフリートの使用データをリクエストするには**  
次の `describe-fleet-utilization` は、ステータスにかかわらずすべてのフリートのフリート使用状況データを返します。この例では、ページ分割パラメータを使用して、一度に 2 つのフリートのデータを返します。  

```
aws gamelift describe-fleet-utilization \
    --limit 2
```
出力:  

```
{
    "FleetUtilization": [
        {
            "FleetId": "fleet-1111aaaa-22bb-33cc-44dd-5555eeee66ff",
            "ActiveServerProcessCount": 100,
            "ActiveGameSessionCount": 13,
            "CurrentPlayerSessionCount": 98,
            "MaximumPlayerSessionCount": 1000
        },
        {
            "FleetId": "fleet-2222bbbb-33cc-44dd-55ee-6666ffff77aa",
            "ActiveServerProcessCount": 100,
            "ActiveGameSessionCount": 62,
            "CurrentPlayerSessionCount": 329,
            "MaximumPlayerSessionCount": 1000
        }
    ],
    "NextToken": "eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjEXAMPLE2"
}
```
コマンドを 2 回呼び出し、`NextToken` 値を引数として `--next-token` パラメータに渡して、次の 2 つの結果を確認します。  

```
aws gamelift describe-fleet-utilization \
    --limit 2 \
    --next-token eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjEXAMPLE2
```
レスポンスに出力の `NextToken` 値が含まれなくなるまで繰り返します。  
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[フリートの GameLift メトリクス](https://docs.aws.amazon.com/gamelift/latest/developerguide/monitoring-cloudwatch.html#gamelift-metrics-fleet)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFleetUtilization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-fleet-utilization.html)」を参照してください。

### `describe-game-session-queues`
<a name="gamelift_DescribeGameSessionQueues_cli_2_topic"></a>

次のコード例は、`describe-game-session-queues` を使用する方法を示しています。

**AWS CLI**  
**ゲームセッションキューを表示するには**  
次の `describe-game-session-queues` の例では、指定された 2 つのキューのプロパティを取得します。  

```
aws gamelift describe-game-session-queues \
    --names MegaFrogRace-NA MegaFrogRace-EU
```
出力:  

```
{
    "GameSessionQueues": [{
            "Destinations": [{
                    "DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
                },
                {
                    "DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
                }
            ],
            "Name": "MegaFrogRace-NA",
            "TimeoutInSeconds": 600,
            "GameSessionQueueArn": "arn:aws:gamelift:us-west-2::gamesessionqueue/MegaFrogRace-NA",
            "PlayerLatencyPolicies": [{
                    "MaximumIndividualPlayerLatencyMilliseconds": 200
                },
                {
                    "MaximumIndividualPlayerLatencyMilliseconds": 100,
                    "PolicyDurationSeconds": 60
                }
            ],
            "FilterConfiguration": {
                "AllowedLocations": ["us-west-2", "ap-south-1", "us-east-1"]
            },
            "PriorityConfiguration": {
                "PriorityOrder": ["LOCATION", "FLEET_TYPE", "DESTINATION"],
                "LocationOrder": ["us-west-2", "ap-south-1", "us-east-1"]
            }
        },
        {
            "Destinations": [{
                "DestinationArn": "arn:aws:gamelift:eu-west-3::fleet/fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
            }],
            "Name": "MegaFrogRace-EU",
            "TimeoutInSeconds": 600,
            "GameSessionQueueArn": "arn:aws:gamelift:us-west-2::gamesessionqueue/MegaFrogRace-EU"
        }
    ]
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[マルチリージョンキューの使用](https://docs.aws.amazon.com/gamelift/latest/developerguide/queues-intro.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGameSessionQueues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-game-session-queues.html)」を参照してください。

### `describe-runtime-configuration`
<a name="gamelift_DescribeRuntimeConfiguration_cli_2_topic"></a>

次のコード例は、`describe-runtime-configuration` を使用する方法を示しています。

**AWS CLI**  
**フリートのランタイム設定をリクエストするには**  
次の `describe-runtime-configuration` の例では、指定されたフリートの現在のランタイム設定の詳細を取得します。  

```
aws gamelift describe-runtime-configuration \
    --fleet-id fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RuntimeConfiguration": {
        "ServerProcesses": [
            {
                "LaunchPath": "C:\game\Bin64.Release.Dedicated\MegaFrogRace_Server.exe",
                "Parameters": "+gamelift_start_server",
                "ConcurrentExecutions": 3
            },
            {
                "LaunchPath": "C:\game\Bin64.Release.Dedicated\MegaFrogRace_Server.exe",
                "Parameters": "+gamelift_start_server +debug",
                "ConcurrentExecutions": 1
            }
        ],
        "MaxConcurrentGameSessionActivations": 2147483647,
        "GameSessionActivationTimeoutSeconds": 300
    }
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[フリートで複数のプロセスを実行する](https://docs.aws.amazon.com/gamelift/latest/developerguide/fleets-multiprocess.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRuntimeConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/describe-runtime-configuration.html)」を参照してください。

### `list-builds`
<a name="gamelift_ListBuilds_cli_2_topic"></a>

次のコード例は、`list-builds` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムゲームビルドのリストを取得するには**  
次の `list-builds` の例では、現在のリージョン内のすべてのゲームサーバービルドのプロパティを取得します。サンプルリクエストは、ページ分割パラメータ `Limit` と `NextToken` を使用してシーケンシャルセットで結果を取得する方法を示しています。最初のコマンドは、最初の 2 つのビルドを取得します。利用可能な結果が 3 つ以上あるため、レスポンスにはより多くの結果が利用可能であることを示す `NextToken` が含まれます。  

```
aws gamelift list-builds \
    --limit 2
```
出力:  

```
{
    "Builds": [
        {
            "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "CreationTime": 1495664528.723,
            "Name": "My_Game_Server_Build_One",
            "OperatingSystem": "WINDOWS_2012",
            "SizeOnDisk": 8567781,
            "Status": "READY",
            "Version": "12345.678"
        },
        {
            "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "CreationTime": 1495528748.555,
            "Name": "My_Game_Server_Build_Two",
            "OperatingSystem": "AMAZON_LINUX_2",
            "SizeOnDisk": 8567781,
            "Status": "FAILED",
            "Version": "23456.789"
        }
    ],
    "NextToken": "eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjJEXAMPLE="
}
```
その後、次のように `--next-token` パラメータを使用してコマンドを再度呼び出して、次の 2 つのビルドを確認できます。  

```
aws gamelift list-builds \
    --limit 2
    --next-token eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjJEXAMPLE=
```
レスポンスに `NextToken` 値が含まれなくなるまで繰り返します。  
**例 2: 失敗ステータスのカスタムゲームビルドのリストを取得するには**  
次の `list-builds` の例では、現在 ステータスが FAILED になっている現在のリージョンのすべてのゲームサーバービルドのプロパティを取得します。  

```
aws gamelift list-builds \
    --status FAILED
```
出力:  

```
{
    "Builds": [
        {
            "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "CreationTime": 1495528748.555,
            "Name": "My_Game_Server_Build_Two",
            "OperatingSystem": "AMAZON_LINUX_2",
            "SizeOnDisk": 8567781,
            "Status": "FAILED",
            "Version": "23456.789"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBuilds](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/list-builds.html)」を参照してください。

### `list-fleets`
<a name="gamelift_ListFleets_cli_2_topic"></a>

次のコード例は、`list-fleets` を使用する方法を示しています。

**AWS CLI**  
**例 1: リージョン内のすべてのフリートのリストを取得するには**  
次の `list-fleets` の例では、現在のリージョン内のすべてのフリートのフリート ID を表示します。この例では、ページ分割パラメータを使用して、一度に 2 つのフリート ID を取得します。レスポンスには、取得する結果が多いことを示す `next-token` 属性が含まれます。  

```
aws gamelift list-fleets \
    --limit 2
```
出力:  

```
{
    "FleetIds": [
        "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
    ],
    "NextToken": "eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC01NWYxZTZmMS1jY2FlLTQ3YTctOWI5ZS1iYjFkYTQwMjJEXAMPLE="
}
```
次の 2 つの結果を取得するには、ここに示すように、次のコマンドで前のレスポンスの `NextToken` 値を渡すことができます。  

```
aws gamelift list-fleets \
    --limit 2 \
    --next-token eyJhd3NBY2NvdW50SWQiOnsicyI6IjMwMjc3NjAxNjM5OCJ9LCJidWlsZElkIjp7InMiOiJidWlsZC00NDRlZjQxZS1hM2I1LTQ2NDYtODJmMy0zYzI4ZTgxNjVjEXAMPLE=
```
**例 2: 特定のビルドまたはスクリプトを持つリージョン内のすべてのフリートのリストを取得するには**  
次の `list-builds` の例では、指定されたゲームビルドでデプロイされたフリートの ID を取得します。Realtime サーバーを使用している場合は、ビルド ID の代わりにスクリプト ID を指定できます。この例では制限パラメータを指定しないため、結果には最大 16 個のフリート ID を含めることができます。  

```
aws gamelift list-fleets \
    --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "FleetIds": [
        "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
        "fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE44444"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFleets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/list-fleets.html)」を参照してください。

### `request-upload-credentials`
<a name="gamelift_RequestUploadCredentials_cli_2_topic"></a>

次のコード例は、`request-upload-credentials` を使用する方法を示しています。

**AWS CLI**  
**ビルドをアップロードするためのアクセス認証情報を更新するには**  
次の `create-build` の例では、Amazon S3 ロケーションに GameLift ビルドファイルをアップロードするための新しい有効なアクセス認証情報を取得します。認証情報の有効期間は限られています。元の `CreateBuild` リクエストに対するレスポンスからビルド ID を取得します。  

```
aws gamelift request-upload-credentials \
    --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "StorageLocation": {
        "Bucket": "gamelift-builds-us-west-2",
        "Key": "123456789012/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    },
    "UploadCredentials": {
        "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "SessionToken": "AgoGb3JpZ2luENz...EXAMPLETOKEN=="
    }
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[カスタムサーバービルドを GameLift にアップロードする](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-build-cli-uploading.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RequestUploadCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/request-upload-credentials.html)」を参照してください。

### `start-fleet-actions`
<a name="gamelift_StartFleetActions_cli_2_topic"></a>

次のコード例は、`start-fleet-actions` を使用する方法を示しています。

**AWS CLI**  
**フリートの自動スケーリングアクティビティを再起動するには**  
次の `start-fleet-actions` の例では、指定されたフリートに定義されているが、「stop-fleet-actions」を呼び出すことで停止されたすべてのスケーリングポリシーの使用を再開します。開始すると、スケーリングポリシーはすぐにそれぞれのメトリクスの追跡を開始します。  

```
aws gamelift start-fleet-actions \
    --fleet-id fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --actions AUTO_SCALING
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartFleetActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/start-fleet-actions.html)」を参照してください。

### `stop-fleet-actions`
<a name="gamelift_StopFleetActions_cli_2_topic"></a>

次のコード例は、`stop-fleet-actions` を使用する方法を示しています。

**AWS CLI**  
**フリートの自動スケーリングアクティビティを停止するには**  
次の `stop-fleet-actions` の例では、指定されたフリートに定義されているすべてのスケーリングポリシーの使用を停止します。ポリシーが一時停止された後も、手動で調整しない限り、フリートキャパシティは同じアクティブなインスタンス数のままになります。  

```
aws gamelift start-fleet-actions \
    --fleet-id fleet-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --actions AUTO_SCALING
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopFleetActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/stop-fleet-actions.html)」を参照してください。

### `update-build`
<a name="gamelift_UpdateBuild_cli_2_topic"></a>

次のコード例は、`update-build` を使用する方法を示しています。

**AWS CLI**  
**カスタムゲームビルドを更新するには**  
次の `update-build` の例では、指定されたビルドリソースに関連付けられている名前とバージョン情報を変更します。返されたビルドオブジェクトは、変更が正常に行われたことを確認します。  

```
aws gamelift update-build \
    --build-id build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --name MegaFrogRaceServer.NA.east \
    --build-version 12345.east
```
出力:  

```
{
    "Build": {
        "BuildArn": "arn:aws:gamelift:us-west-2::build/build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "BuildId": "build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "CreationTime": 1496708916.18,
        "Name": "MegaFrogRaceServer.NA.east",
        "OperatingSystem": "AMAZON_LINUX_2",
        "SizeOnDisk": 1304924,
        "Status": "READY",
        "Version": "12345.east"
    }
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[ビルドファイルを更新する](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-build-cli-uploading.html#gamelift-build-cli-uploading-update-build-files)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/update-build.html)」を参照してください。

### `update-game-session-queue`
<a name="gamelift_UpdateGameSessionQueue_cli_2_topic"></a>

次のコード例は、`update-game-session-queue` を使用する方法を示しています。

**AWS CLI**  
**ゲームセッションキュー設定を更新するには**  
次の `update-game-session-queue` の例では、新しい送信先を追加し、既存のゲームセッションキューのプレイヤーレイテンシーポリシーを更新します。  

```
aws gamelift update-game-session-queue \
    --name MegaFrogRace-NA \
    --destinations file://destinations.json \
    --player-latency-policies file://latency-policies.json
```
`destinations.json` の内容:  

```
{
    "Destinations": [
        {"DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d"},
        {"DestinationArn": "arn:aws:gamelift:us-east-1::fleet/fleet-5c6d3c4d-5e6f-7a8b-9c0d-1e2f3a4b5a2b"},
        {"DestinationArn": "arn:aws:gamelift:us-east-1::alias/alias-11aa22bb-3c4d-5e6f-000a-1111aaaa22bb"}
    ]
}
```
`latency-policies.json` の内容:  

```
{
    "PlayerLatencyPolicies": [
        {"MaximumIndividualPlayerLatencyMilliseconds": 200},
        {"MaximumIndividualPlayerLatencyMilliseconds": 150, "PolicyDurationSeconds": 120},
        {"MaximumIndividualPlayerLatencyMilliseconds": 100, "PolicyDurationSeconds": 120}
    ]
}
```
出力:  

```
{
    "GameSessionQueue": {
        "Destinations": [
            {"DestinationArn": "arn:aws:gamelift:us-west-2::fleet/fleet-1a2b3c4d-5e6f-7a8b-9c0d-1e2f3a4b5c6d"},
            {"DestinationArn": "arn:aws:gamelift:us-east-1::fleet/fleet-5c6d3c4d-5e6f-7a8b-9c0d-1e2f3a4b5a2b"},
            {"DestinationArn": "arn:aws:gamelift:us-east-1::alias/alias-11aa22bb-3c4d-5e6f-000a-1111aaaa22bb"}
        ],
        "GameSessionQueueArn": "arn:aws:gamelift:us-west-2:111122223333:gamesessionqueue/MegaFrogRace-NA",
        "Name": "MegaFrogRace-NA",
        "TimeoutInSeconds": 600,
        "PlayerLatencyPolicies": [
            {"MaximumIndividualPlayerLatencyMilliseconds": 200},
            {"MaximumIndividualPlayerLatencyMilliseconds": 150, "PolicyDurationSeconds": 120},
            {"MaximumIndividualPlayerLatencyMilliseconds": 100, "PolicyDurationSeconds": 120}
        ]
    }
}
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[マルチリージョンキューの使用](https://docs.aws.amazon.com/gamelift/latest/developerguide/queues-intro.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGameSessionQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/update-game-session-queue.html)」を参照してください。

### `upload-build`
<a name="gamelift_UploadBuild_cli_2_topic"></a>

次のコード例は、`upload-build` を使用する方法を示しています。

**AWS CLI**  
**例 1: Linux ゲームサーバービルドをアップロードするには**  
次の `upload-build` の例では、Linux ゲームサーバービルドファイルをファイルディレクトリから GameLift サービスにアップロードし、ビルドリソースを作成します。  

```
aws gamelift upload-build \
    --name MegaFrogRaceServer.NA \
    --build-version 2.0.1 \
    --build-root ~/MegaFrogRace_Server/release-na \
    --operating-system AMAZON_LINUX_2
    --server-sdk-version 4.0.2
```
出力:  

```
Uploading ~/MegaFrogRace_Server/release-na:  16.0 KiB / 74.6 KiB (21.45%)
Uploading ~/MegaFrogRace_Server/release-na:  32.0 KiB / 74.6 KiB (42.89%)
Uploading ~/MegaFrogRace_Server/release-na:  48.0 KiB / 74.6 KiB (64.34%)
Uploading ~/MegaFrogRace_Server/release-na:  64.0 KiB / 74.6 KiB (85.79%)
Uploading ~/MegaFrogRace_Server/release-na:  74.6 KiB / 74.6 KiB (100.00%)
Successfully uploaded ~/MegaFrogRace_Server/release-na to AWS GameLift
Build ID: build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
**例 2: Windows ゲームサーバービルドをアップロードするには**  
次の `upload-build` 例では、Windows ゲームサーバーのビルドファイルをディレクトリから GameLift サービスにアップロードし、ビルドレコードを作成します。  

```
aws gamelift upload-build \
    --name MegaFrogRaceServer.NA \
    --build-version 2.0.1 \
    --build-root C:\MegaFrogRace_Server\release-na \
    --operating-system WINDOWS_2012
    --server-sdk-version 4.0.2
```
出力:  

```
Uploading C:\MegaFrogRace_Server\release-na:  16.0 KiB / 74.6 KiB (21.45%)
Uploading C:\MegaFrogRace_Server\release-na:  32.0 KiB / 74.6 KiB (42.89%)
Uploading C:\MegaFrogRace_Server\release-na:  48.0 KiB / 74.6 KiB (64.34%)
Uploading C:\MegaFrogRace_Server\release-na:  64.0 KiB / 74.6 KiB (85.79%)
Uploading C:\MegaFrogRace_Server\release-na:  74.6 KiB / 74.6 KiB (100.00%)
Successfully uploaded C:\MegaFrogRace_Server\release-na to AWS GameLift
Build ID: build-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
詳細については、「*Amazon GameLift デベロッパーガイド*」の「[カスタムサーバービルドを GameLift にアップロードする](https://docs.aws.amazon.com/gamelift/latest/developerguide/gamelift-build-cli-uploading.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadBuild](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/gamelift/upload-build.html)」を参照してください。

# を使用した Amazon Glacier の例 AWS CLI
<a name="cli_2_glacier_code_examples"></a>

次のコード例は、Amazon Glacier AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `abort-multipart-upload`
<a name="glacier_AbortMultipartUpload_cli_2_topic"></a>

次のコード例は、`abort-multipart-upload` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトへの進行中のマルチパートアップロードを削除します。  

```
aws glacier abort-multipart-upload --account-id - --vault-name my-vault --upload-id 19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ
```
このコマンドでは、出力が生成されません。Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。アップロード ID は `aws glacier initiate-multipart-upload` コマンドによって返され、`aws glacier list-multipart-uploads` を使用して取得することもできます。  
CLI を使用した Amazon Glacier AWS へのマルチパートアップロードの詳細については、*AWS 「 CLI ユーザーガイド*」のAmazon Glacier の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AbortMultipartUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/abort-multipart-upload.html)」を参照してください。

### `abort-vault-lock`
<a name="glacier_AbortVaultLock_cli_2_topic"></a>

次のコード例は、`abort-vault-lock` を使用する方法を示しています。

**AWS CLI**  
**進行中のボールトロックプロセスを中止するには**  
次の `abort-vault-lock` の例では、指定されたボールトからボールトロックポリシーを削除し、ボールトロックのロック状態をロック解除にリセットします。  

```
aws glacier abort-vault-lock \
    --account-id - \
    --vault-name MyVaultName
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Glacier API デベロッパーガイド*」の「[ボールトロックを中止する (DELETE ロックポリシー)](https://docs.aws.amazon.com/amazonglacier/latest/dev/api-AbortVaultLock.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AbortVaultLock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/abort-vault-lock.html)」を参照してください。

### `add-tags-to-vault`
<a name="glacier_AddTagsToVault_cli_2_topic"></a>

次のコード例は、`add-tags-to-vault` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトに 2 つのタグを追加します。  

```
aws glacier add-tags-to-vault --account-id - --vault-name my-vault --tags id=1234,date=july2015
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTagsToVault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/add-tags-to-vault.html)」を参照してください。

### `complete-multipart-upload`
<a name="glacier_CompleteMultipartUpload_cli_2_topic"></a>

次のコード例は、`complete-multipart-upload` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、3 MiB アーカイブのマルチパートアップロードを完了します。  

```
aws glacier complete-multipart-upload --archive-size 3145728 --checksum 9628195fcdbcbbe76cdde456d4646fa7de5f219fb39823836d81f0cc0e18aa67 --upload-id 19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ --account-id - --vault-name my-vault
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
アップロード ID は `aws glacier initiate-multipart-upload` コマンドによって返され、`aws glacier list-multipart-uploads` を使用して取得することもできます。チェックサムパラメータは、アーカイブの SHA-256 ツリーハッシュを 16 進数で取得します。  
CLI を使用した Amazon Glacier AWS へのマルチパートアップロードの詳細については、「 CLI *AWS ユーザーガイド*」のAmazon Glacier の使用」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CompleteMultipartUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/complete-multipart-upload.html)」を参照してください。**

### `complete-vault-lock`
<a name="glacier_CompleteVaultLock_cli_2_topic"></a>

次のコード例は、`complete-vault-lock` を使用する方法を示しています。

**AWS CLI**  
**進行中のボールトロックプロセスを完了するには**  
次の `complete-vault-lock` の例では、指定されたボールトの進行中のロック進行状況を完了し、ボールトロックのロック状態を `Locked` に設定します。`initiate-lock-process` を実行すると、`lock-id` パラメータの値を取得します。  

```
aws glacier complete-vault-lock \
    --account-id - \
    --vault-name MyVaultName \
    --lock-id 9QZgEXAMPLEPhvL6xEXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Glacier API デベロッパーガイド*」の「[完全なボールトロック (POST lockId)](https://docs.aws.amazon.com/amazonglacier/latest/dev/api-CompleteVaultLock.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CompleteVaultLock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/complete-vault-lock.html)」を参照してください。

### `create-vault`
<a name="glacier_CreateVault_cli_2_topic"></a>

次のコード例は、`create-vault` を使用する方法を示しています。

**AWS CLI**  
次のコマンドでは、`my-vault` という名前の新しいボールトが作成されます。  

```
aws glacier create-vault --vault-name my-vault --account-id -
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/create-vault.html)」を参照してください。

### `delete-archive`
<a name="glacier_DeleteArchive_cli_2_topic"></a>

次のコード例は、`delete-archive` を使用する方法を示しています。

**AWS CLI**  
**ボールトからアーカイブを削除するには**  
次の `delete-archive` の例では、`example_vault` から指定されたアーカイブを削除します。  

```
aws glacier delete-archive \
    --account-id 111122223333  \
    --vault-name example_vault \
    --archive-id Sc0u9ZP8yaWkmh-XGlIvAVprtLhaLCGnNwNl5I5x9HqPIkX5mjc0DrId3Ln-Gi_k2HzmlIDZUz117KSdVMdMXLuFWi9PJUitxWO73edQ43eTlMWkH0pd9zVSAuV_XXZBVhKhyGhJ7w
```
このコマンドは何も出力しません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteArchive](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/delete-archive.html)」を参照してください。

### `delete-vault-access-policy`
<a name="glacier_DeleteVaultAccessPolicy_cli_2_topic"></a>

次のコード例は、`delete-vault-access-policy` を使用する方法を示しています。

**AWS CLI**  
**ボールトのアクセスポリシーを削除するには**  
次の `delete-vault-access-policy` の例では、指定されたボールトのアクセスポリシーを削除します。  

```
aws glacier delete-vault-access-policy \
    --account-id 111122223333 \
    --vault-name example_vault
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVaultAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/delete-vault-access-policy.html)」を参照してください。

### `delete-vault-notifications`
<a name="glacier_DeleteVaultNotifications_cli_2_topic"></a>

次のコード例は、`delete-vault-notifications` を使用する方法を示しています。

**AWS CLI**  
**ボールトの SNS 通知を削除するには**  
次の `delete-vault-notifications` の例は、指定されたボールトに対して Amazon Simple Notiﬁcation Service (Amazon SNS) で送信される通知を削除します。  

```
aws glacier delete-vault-notifications \
    --account-id 111122223333 \
    --vault-name example_vault
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVaultNotifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/delete-vault-notifications.html)」を参照してください。

### `delete-vault`
<a name="glacier_DeleteVault_cli_2_topic"></a>

次のコード例は、`delete-vault` を使用する方法を示しています。

**AWS CLI**  
次のコマンドでは、`my-vault` という名前のボールトが削除されます。  

```
aws glacier delete-vault --vault-name my-vault --account-id -
```
このコマンドでは、出力が生成されません。Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/delete-vault.html)」を参照してください。

### `describe-job`
<a name="glacier_DescribeJob_cli_2_topic"></a>

次のコード例は、`describe-job` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトでのインベントリ取得ジョブに関する情報を取得します。  

```
aws glacier describe-job --account-id - --vault-name my-vault --job-id zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW
```
出力:  

```
{
    "InventoryRetrievalParameters": {
        "Format": "JSON"
    },
    "VaultARN": "arn:aws:glacier:us-west-2:0123456789012:vaults/my-vault",
    "Completed": false,
    "JobId": "zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW",
    "Action": "InventoryRetrieval",
    "CreationDate": "2015-07-17T20:23:41.616Z",
    "StatusCode": "InProgress"
}
```
ジョブ ID は、`aws glacier initiate-job` と `aws glacier list-jobs` の出力にあります。Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/describe-job.html)」を参照してください。

### `describe-vault`
<a name="glacier_DescribeVault_cli_2_topic"></a>

次のコード例は、`describe-vault` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトに関するデータを取得します。  

```
aws glacier describe-vault --vault-name my-vault --account-id -
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeVault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/describe-vault.html)」を参照してください。

### `get-data-retrieval-policy`
<a name="glacier_GetDataRetrievalPolicy_cli_2_topic"></a>

次のコード例は、`get-data-retrieval-policy` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、使用中アカウントのデータ取得ポリシーを取得します。  

```
aws glacier get-data-retrieval-policy --account-id -
```
出力:  

```
{
    "Policy": {
        "Rules": [
            {
                "BytesPerHour": 10737418240,
                "Strategy": "BytesPerHour"
            }
        ]
    }
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDataRetrievalPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/get-data-retrieval-policy.html)」を参照してください。

### `get-job-output`
<a name="glacier_GetJobOutput_cli_2_topic"></a>

次のコード例は、`get-job-output` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ボールトインベントリジョブの出力を、現在のディレクトリの `output.json` という名前のファイルに保存します。  

```
aws glacier get-job-output --account-id - --vault-name my-vault --job-id zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW output.json
```
`job-id` は、`aws glacier list-jobs` の出力にあります。出力ファイル名はオプション名の前に付いていない位置引数であることに注意してください。Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
出力:  

```
{
    "status": 200,
    "acceptRanges": "bytes",
    "contentType": "application/json"
}
```
`output.json`:  

```
{"VaultARN":"arn:aws:glacier:us-west-2:0123456789012:vaults/my-vault","InventoryDate":"2015-04-07T00:26:18Z","ArchiveList":[{"ArchiveId":"kKB7ymWJVpPSwhGP6ycSOAekp9ZYe_--zM_mw6k76ZFGEIWQX-ybtRDvc2VkPSDtfKmQrj0IRQLSGsNuDp-AJVlu2ccmDSyDUmZwKbwbpAdGATGDiB3hHO0bjbGehXTcApVud_wyDw","ArchiveDescription":"multipart upload test","CreationDate":"2015-04-06T22:24:34Z","Size":3145728,"SHA256TreeHash":"9628195fcdbcbbe76cdde932d4646fa7de5f219fb39823836d81f0cc0e18aa67"}]}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetJobOutput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/get-job-output.html)」を参照してください。

### `get-vault-access-policy`
<a name="glacier_GetVaultAccessPolicy_cli_2_topic"></a>

次のコード例は、`get-vault-access-policy` を使用する方法を示しています。

**AWS CLI**  
**ボールトのアクセスポリシーを取得するには**  
次の `get-vault-access-policy` の例では、指定されたボールトのアクセスポリシーを取得します。  

```
aws glacier get-vault-access-policy \
    --account-id 111122223333 \
    --vault-name example_vault
```
出力:  

```
{
    "policy": {
        "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::444455556666:root\"},\"Action\":\"glacier:ListJobs\",\"Resource\":\"arn:aws:glacier:us-east-1:111122223333:vaults/example_vault\"},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::444455556666:root\"},\"Action\":\"glacier:UploadArchive\",\"Resource\":\"arn:aws:glacier:us-east-1:111122223333:vaults/example_vault\"}]}"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVaultAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/get-vault-access-policy.html)」を参照してください。

### `get-vault-lock`
<a name="glacier_GetVaultLock_cli_2_topic"></a>

次のコード例は、`get-vault-lock` を使用する方法を示しています。

**AWS CLI**  
**ボールトロックの詳細を取得するには**  
次の `get-vault-lock` の例では、指定されたボールトのロックに関する詳細情報を取得しました。  

```
aws glacier get-vault-lock \
    --account-id - \
    --vault-name MyVaultName
```
出力:  

```
{
    "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Define-vault-lock\",\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"arn:aws:iam::999999999999:root\"},\"Action\":\"glacier:DeleteArchive\",\"Resource\":\"arn:aws:glacier:us-west-2:99999999999:vaults/MyVaultName\",\"Condition\":{\"NumericLessThanEquals\":{\"glacier:ArchiveAgeinDays\":\"365\"}}}]}",
    "State": "Locked",
    "CreationDate": "2019-07-29T22:25:28.640Z"
}
```
詳細については、「*Amazon Glacier API デベロッパーガイド*」の「[ボールトロックを取得する (GET ロックポリシー)](https://docs.aws.amazon.com/amazonglacier/latest/dev/api-GetVaultLock.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVaultLock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/get-vault-lock.html)」を参照してください。

### `get-vault-notifications`
<a name="glacier_GetVaultNotifications_cli_2_topic"></a>

次のコード例は、`get-vault-notifications` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトの通知設定の説明を取得します。  

```
aws glacier get-vault-notifications --account-id - --vault-name my-vault
```
出力:  

```
{
    "vaultNotificationConfig": {
        "Events": [
            "InventoryRetrievalCompleted",
            "ArchiveRetrievalCompleted"
        ],
        "SNSTopic": "arn:aws:sns:us-west-2:0123456789012:my-vault"
    }
}
```
ボールトに通知が設定されていない場合、エラーが返されます。Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVaultNotifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/get-vault-notifications.html)」を参照してください。

### `initiate-job`
<a name="glacier_InitiateJob_cli_2_topic"></a>

次のコード例は、`initiate-job` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ボールト `my-vault` のインベントリを取得するジョブを開始します。  

```
aws glacier initiate-job --account-id - --vault-name my-vault --job-parameters '{"Type": "inventory-retrieval"}'
```
出力:  

```
{
    "location": "/0123456789012/vaults/my-vault/jobs/zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW",
    "jobId": "zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW"
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
次のコマンドは、ボールト `my-vault` からアーカイブを取得するジョブを開始します。  

```
aws glacier initiate-job --account-id - --vault-name my-vault --job-parameters file://job-archive-retrieval.json
```
`job-archive-retrieval.json` はローカルフォルダ内の JSON ファイルで、ジョブのタイプ、アーカイブ ID、いくつかのオプションパラメータを指定する以下の内容を含みます。  

```
{
  "Type": "archive-retrieval",
  "ArchiveId": "kKB7ymWJVpPSwhGP6ycSOAekp9ZYe_--zM_mw6k76ZFGEIWQX-ybtRDvc2VkPSDtfKmQrj0IRQLSGsNuDp-AJVlu2ccmDSyDUmZwKbwbpAdGATGDiB3hHO0bjbGehXTcApVud_wyDw",
  "Description": "Retrieve archive on 2015-07-17",
  "SNSTopic": "arn:aws:sns:us-west-2:0123456789012:my-topic"
}
```
アーカイブ ID は、`aws glacier upload-archive` および `aws glacier get-job-output` の出力で確認できます。  
出力:  

```
{
    "location": "/011685312445/vaults/mwunderl/jobs/l7IL5-EkXyEY9Ws95fClzIbk2O5uLYaFdAYOi-azsX_Z8V6NH4yERHzars8wTKYQMX6nBDI9cMNHzyZJO59-8N9aHWav",
    "jobId": "l7IL5-EkXy2O5uLYaFdAYOiEY9Ws95fClzIbk-azsX_Z8V6NH4yERHzars8wTKYQMX6nBDI9cMNHzyZJO59-8N9aHWav"
}
```
ジョブパラメータの形式の詳細については、「*Amazon Glacier API リファレンス*」の「ジョブの開始」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InitiateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/initiate-job.html)」を参照してください。

### `initiate-multipart-upload`
<a name="glacier_InitiateMultipartUpload_cli_2_topic"></a>

次のコード例は、`initiate-multipart-upload` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ファイルごとに 1 MiB (1024 x 1024 バイト) のパートサイズで、`my-vault` という名前のボールトへのマルチパートアップロードを開始します。  

```
aws glacier initiate-multipart-upload --account-id - --part-size 1048576 --vault-name my-vault --archive-description "multipart upload test"
```
アーカイブの説明パラメータはオプションです。Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
このコマンドは、成功するとアップロード ID を出力します。`aws glacier upload-multipart-part` でアーカイブの各部分をアップロードするときは、アップロード ID を使用します。CLI を使用した Amazon Glacier AWS へのマルチパートアップロードの詳細については、*AWS 「 CLI ユーザーガイド*」のAmazon Glacier の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InitiateMultipartUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/initiate-multipart-upload.html)」を参照してください。

### `initiate-vault-lock`
<a name="glacier_InitiateVaultLock_cli_2_topic"></a>

次のコード例は、`initiate-vault-lock` を使用する方法を示しています。

**AWS CLI**  
**ボールトロック処理を開始するには**  
次の `initiate-vault-lock` の例では、指定されたボールトにボールトロックポリシーをインストールし、ボールトロックのロック状態を `InProgress` に設定します。ボールトロック処理を完了するには、24 時間以内に `complete-vault-lock` を呼び出してボールトロックの状態を `Locked` に設定します。  

```
aws glacier initiate-vault-lock \
    --account-id - \
    --vault-name MyVaultName \
    --policy file://vault_lock_policy.json
```
`vault_lock_policy.json` の内容:  

```
{"Policy":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Define-vault-lock\",\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"arn:aws:iam::999999999999:root\"},\"Action\":\"glacier:DeleteArchive\",\"Resource\":\"arn:aws:glacier:us-west-2:999999999999:vaults/examplevault\",\"Condition\":{\"NumericLessThanEquals\":{\"glacier:ArchiveAgeinDays\":\"365\"}}}]}"}
```
出力は、ボールトロックプロセスを完了するために使用できるボールトロック ID です。  

```
{
    "lockId": "9QZgEXAMPLEPhvL6xEXAMPLE"
}
```
詳細については、「*Amazon Glacier API デベロッパーガイド*」の「[ボールトロックを開始する (POST ロックポリシー)](https://docs.aws.amazon.com/amazonglacier/latest/dev/api-InitiateVaultLock.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InitiateVaultLock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/initiate-vault-lock.html)」を参照してください。

### `list-jobs`
<a name="glacier_ListJobs_cli_2_topic"></a>

次のコード例は、`list-jobs` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトで進行中のジョブと最近完了したジョブを一覧表示します。  

```
aws glacier list-jobs --account-id - --vault-name my-vault
```
出力:  

```
{
    "JobList": [
        {
            "VaultARN": "arn:aws:glacier:us-west-2:0123456789012:vaults/my-vault",
            "RetrievalByteRange": "0-3145727",
            "SNSTopic": "arn:aws:sns:us-west-2:0123456789012:my-vault",
            "Completed": false,
            "SHA256TreeHash": "9628195fcdbcbbe76cdde932d4646fa7de5f219fb39823836d81f0cc0e18aa67",
            "JobId": "l7IL5-EkXyEY9Ws95fClzIbk2O5uLYaFdAYOi-azsX_Z8V6NH4yERHzars8wTKYQMX6nBDI9cMNHzyZJO59-8N9aHWav",
            "ArchiveId": "kKB7ymWJVpPSwhGP6ycSOAekp9ZYe_--zM_mw6k76ZFGEIWQX-ybtRDvc2VkPSDtfKmQrj0IRQLSGsNuDp-AJVlu2ccmDSyDUmZwKbwbpAdGATGDiB3hHO0bjbGehXTcApVud_wyDw",
            "JobDescription": "Retrieve archive on 2015-07-17",
            "ArchiveSizeInBytes": 3145728,
            "Action": "ArchiveRetrieval",
            "ArchiveSHA256TreeHash": "9628195fcdbcbbe76cdde932d4646fa7de5f219fb39823836d81f0cc0e18aa67",
            "CreationDate": "2015-07-17T21:16:13.840Z",
            "StatusCode": "InProgress"
        },
        {
            "InventoryRetrievalParameters": {
                "Format": "JSON"
            },
            "VaultARN": "arn:aws:glacier:us-west-2:0123456789012:vaults/my-vault",
            "Completed": false,
            "JobId": "zbxcm3Z_3z5UkoroF7SuZKrxgGoDc3RloGduS7Eg-RO47Yc6FxsdGBgf_Q2DK5Ejh18CnTS5XW4_XqlNHS61dsO4CnMW",
            "Action": "InventoryRetrieval",
            "CreationDate": "2015-07-17T20:23:41.616Z",
            "StatusCode": ""InProgress""
        }
    ]
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/list-jobs.html)」を参照してください。

### `list-multipart-uploads`
<a name="glacier_ListMultipartUploads_cli_2_topic"></a>

次のコード例は、`list-multipart-uploads` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトに対して進行中のすべてのマルチパートアップロードを示しています。  

```
aws glacier list-multipart-uploads --account-id - --vault-name my-vault
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
CLI を使用した Amazon Glacier AWS へのマルチパートアップロードの詳細については、*AWS 「 CLI ユーザーガイド*」のAmazon Glacier の使用」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListMultipartUploads](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/list-multipart-uploads.html)」を参照してください。**

### `list-parts`
<a name="glacier_ListParts_cli_2_topic"></a>

次のコード例は、`list-parts` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトへのマルチパートアップロード用にアップロードされたパートを一覧表示します。  

```
aws glacier list-parts --account-id - --vault-name my-vault --upload-id "SYZi7qnL-YGqGwAm8Kn3BLP2ElNCvnB-5961R09CSaPmPwkYGHOqeN_nX3-Vhnd2yF0KfB5FkmbnBU9GubbdrCs8ut-D"
```
出力:  

```
{
    "MultipartUploadId": "SYZi7qnL-YGqGwAm8Kn3BLP2ElNCvnB-5961R09CSaPmPwkYGHOqeN_nX3-Vhnd2yF0KfB5FkmbnBU9GubbdrCs8ut-D",
    "Parts": [
        {
            "RangeInBytes": "0-1048575",
            "SHA256TreeHash": "e1f2a7cd6e047350f69b9f8cfa60fa606fe2f02802097a9a026360a7edc1f553"
        },
        {
            "RangeInBytes": "1048576-2097151",
            "SHA256TreeHash": "43cf3061fb95796aed99a11a6aa3cd8f839eed15e655ab0a597126210636aee6"
        }
    ],
    "VaultARN": "arn:aws:glacier:us-west-2:0123456789012:vaults/my-vault",
    "CreationDate": "2015-07-18T00:05:23.830Z",
    "PartSizeInBytes": 1048576
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
CLI を使用した Amazon Glacier AWS へのマルチパートアップロードの詳細については、*AWS 「 CLI ユーザーガイド*」のAmazon Glacier の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListParts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/list-parts.html)」を参照してください。

### `list-provisioned-capacity`
<a name="glacier_ListProvisionedCapacity_cli_2_topic"></a>

次のコード例は、`list-provisioned-capacity` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされたキャパシティーユニットを取得するには**  
次の `list-provisioned-capacity` の例では、指定されたアカウントのプロビジョニングされたキャパシティユニットの詳細を取得します。  

```
aws glacier list-provisioned-capacity \
    --account-id 111122223333
```
出力:  

```
{
    "ProvisionedCapacityList": [
        {
            "CapacityId": "HpASAuvfRFiVDbOjMfEIcr8K",
            "ExpirationDate": "2020-03-18T19:59:24.000Z",
            "StartDate": "2020-02-18T19:59:24.912Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProvisionedCapacity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/list-provisioned-capacity.html)」を参照してください。

### `list-tags-for-vault`
<a name="glacier_ListTagsForVault_cli_2_topic"></a>

次のコード例は、`list-tags-for-vault` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトに適用されたタグを一覧表示します。  

```
aws glacier list-tags-for-vault --account-id - --vault-name my-vault
```
出力:  

```
{
    "Tags": {
        "date": "july2015",
        "id": "1234"
    }
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForVault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/list-tags-for-vault.html)」を参照してください。

### `list-vaults`
<a name="glacier_ListVaults_cli_2_topic"></a>

次のコード例は、`list-vaults` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、デフォルトのアカウントとリージョンのボールトを一覧表示します。  

```
aws glacier list-vaults --account-id -
```
出力:  

```
{
    "VaultList": [
        {
            "SizeInBytes": 3178496,
            "VaultARN": "arn:aws:glacier:us-west-2:0123456789012:vaults/my-vault",
            "LastInventoryDate": "2015-04-07T00:26:19.028Z",
            "VaultName": "my-vault",
            "NumberOfArchives": 1,
            "CreationDate": "2015-04-06T21:23:45.708Z"
        }
    ]
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVaults](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/list-vaults.html)」を参照してください。

### `purchase-provisioned-capacity`
<a name="glacier_PurchaseProvisionedCapacity_cli_2_topic"></a>

次のコード例は、`purchase-provisioned-capacity` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされたキャパシティーユニットを購入するには**  
次の `purchase-provisioned-capacity` の例では、プロビジョニングされたキャパシティユニットを購入します。  

```
aws glacier purchase-provisioned-capacity \
    --account-id 111122223333
```
出力:  

```
{
    "capacityId": "HpASAuvfRFiVDbOjMfEIcr8K"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseProvisionedCapacity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/purchase-provisioned-capacity.html)」を参照してください。

### `remove-tags-from-vault`
<a name="glacier_RemoveTagsFromVault_cli_2_topic"></a>

次のコード例は、`remove-tags-from-vault` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトから `date` キーを持つタグを削除します。  

```
aws glacier remove-tags-from-vault --account-id - --vault-name my-vault --tag-keys date
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromVault](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/remove-tags-from-vault.html)」を参照してください。

### `set-data-retrieval-policy`
<a name="glacier_SetDataRetrievalPolicy_cli_2_topic"></a>

次のコード例は、`set-data-retrieval-policy` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、使用中アカウントのデータ取得ポリシーを設定します。  

```
aws glacier set-data-retrieval-policy --account-id - --policy file://data-retrieval-policy.json
```
`data-retrieval-policy.json` は、データ取得ポリシーを指定する現在のフォルダ内の JSON ファイルです。  

```
{
  "Rules":[
     {
         "Strategy":"BytesPerHour",
         "BytesPerHour":10737418240
      }
   ]
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
次のコマンドは、インライン JSON を使用するようにデータ取得ポリシーを `FreeTier` に設定します。  

```
aws glacier set-data-retrieval-policy --account-id - --policy '{"Rules":[{"Strategy":"FreeTier"}]}'
```
ポリシー形式の詳細については、「*Amazon Glacier API リファレンス*」の「データ取得ポリシーを設定する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetDataRetrievalPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/set-data-retrieval-policy.html)」を参照してください。

### `set-vault-access-policy`
<a name="glacier_SetVaultAccessPolicy_cli_2_topic"></a>

次のコード例は、`set-vault-access-policy` を使用する方法を示しています。

**AWS CLI**  
**ボールトのアクセスポリシーを設定するには**  
次の `set-vault-access-policy` の例では、指定されたボールトにアクセス許可ポリシーをアタッチします。  

```
aws glacier set-vault-access-policy \
    --account-id 111122223333 \
    --vault-name example_vault
    --policy '{"Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::444455556666:root\"},\"Action\":\"glacier:ListJobs\",\"Resource\":\"arn:aws:glacier:us-east-1:111122223333:vaults/example_vault\"},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::444455556666:root\"},\"Action\":\"glacier:UploadArchive\",\"Resource\":\"arn:aws:glacier:us-east-1:111122223333:vaults/example_vault\"}]}"}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetVaultAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/set-vault-access-policy.html)」を参照してください。

### `set-vault-notifications`
<a name="glacier_SetVaultNotifications_cli_2_topic"></a>

次のコード例は、`set-vault-notifications` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`my-vault` という名前のボールトの SNS 通知を設定します。  

```
aws glacier set-vault-notifications --account-id - --vault-name my-vault --vault-notification-config file://notificationconfig.json
```
`notificationconfig.json` は、現在のフォルダにある JSON ファイルで、公開する SNS トピックとイベントを指定します。  

```
{
  "SNSTopic": "arn:aws:sns:us-west-2:0123456789012:my-vault",
  "Events": ["ArchiveRetrievalCompleted", "InventoryRetrievalCompleted"]
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetVaultNotifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/set-vault-notifications.html)」を参照してください。

### `upload-archive`
<a name="glacier_UploadArchive_cli_2_topic"></a>

次のコード例は、`upload-archive` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`archive.zip` という名前の現在のフォルダにあるアーカイブを、`my-vault` という名前のボールトにアップロードします。  

```
aws glacier upload-archive --account-id - --vault-name my-vault --body archive.zip
```
出力:  

```
{
    "archiveId": "kKB7ymWJVpPSwhGP6ycSOAekp9ZYe_--zM_mw6k76ZFGEIWQX-ybtRDvc2VkPSDtfKmQrj0IRQLSGsNuDp-AJVlu2ccmDSyDUmZwKbwbpAdGATGDiB3hHO0bjbGehXTcApVud_wyDw",
    "checksum": "969fb39823836d81f0cc028195fcdbcbbe76cdde932d4646fa7de5f21e18aa67",
    "location": "/0123456789012/vaults/my-vault/archives/kKB7ymWJVpPSwhGP6ycSOAekp9ZYe_--zM_mw6k76ZFGEIWQX-ybtRDvc2VkPSDtfKmQrj0IRQLSGsNuDp-AJVlu2ccmDSyDUmZwKbwbpAdGATGDiB3hHO0bjbGehXTcApVud_wyDw"
}
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
アップロードしたアーカイブを取得するには、aws glacier initiate-job コマンドを使用して取得ジョブを開始します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadArchive](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/upload-archive.html)」を参照してください。

### `upload-multipart-part`
<a name="glacier_UploadMultipartPart_cli_2_topic"></a>

次のコード例は、`upload-multipart-part` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、アーカイブの最初の 1 MiB (1024 x 1024 バイト) の部分をアップロードします。  

```
aws glacier upload-multipart-part --body part1 --range 'bytes 0-1048575/*' --account-id - --vault-name my-vault --upload-id 19gaRezEXAMPLES6Ry5YYdqthHOC_kGRCT03L9yetr220UmPtBYKk-OssZtLqyFu7sY1_lR7vgFuJV6NtcV5zpsJ
```
Amazon Glacier では、オペレーションを実行する際にアカウント ID 引数が必要ですが、ハイフンを使用して使用中のアカウントを指定できます。  
body パラメータは、ローカルファイルシステム上のパートファイルへのパスを受け取ります。range パラメータは、完了したアーカイブ内でそのパートが占めるバイト数を示す HTTP コンテンツ範囲を受け取ります。アップロード ID は `aws glacier initiate-multipart-upload` コマンドによって返され、`aws glacier list-multipart-uploads` を使用して取得することもできます。  
CLI を使用した Amazon Glacier AWS へのマルチパートアップロードの詳細については、*AWS 「 CLI ユーザーガイド*」のAmazon Glacier の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadMultipartPart](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glacier/upload-multipart-part.html)」を参照してください。

# を使用した Global Accelerator の例 AWS CLI
<a name="cli_2_global-accelerator_code_examples"></a>

次のコード例は、Global Accelerator AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-custom-routing-endpoints`
<a name="global-accelerator_AddCustomRoutingEndpoints_cli_2_topic"></a>

次のコード例は、`add-custom-routing-endpoints` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのエンドポイントグループに VPC サブネットエンドポイントを追加するには**  
次の `add-custom-routing-endpoints` の例では、VPC サブネットエンドポイントをカスタムルーティングアクセラレーターのエンドポイントグループに追加します。  

```
aws globalaccelerator add-custom-routing-endpoints \
    --endpoint-group-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/4321abcd \
    --endpoint-configurations "EndpointId=subnet-1234567890abcdef0"
```
出力:  

```
{
    "EndpointDescriptions": [
        {
            "EndpointId": "subnet-1234567890abcdef0"
        }
    ],
    "EndpointGroupArn":"arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/4321abcd"
}
```
詳細については、Global [Accelerator デベロッパーガイドの AWS 「Global Accelerator のカスタムルーティングアクセラレーターの VPC サブネットエンドポイント](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-endpoints.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddCustomRoutingEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/add-custom-routing-endpoints.html)」を参照してください。

### `advertise-byoip-cidr`
<a name="global-accelerator_AdvertiseByoipCidr_cli_2_topic"></a>

次のコード例は、`advertise-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲をアドバタイズするには**  
次の例では、 AWS リソースで使用するためにプロビジョニングしたアドレス範囲をアドバタイズ AWS するように に`advertise-byoip-cidr`リクエストします。  

```
aws globalaccelerator advertise-byoip-cidr \
    --cidr 198.51.100.0/24
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "198.51.100.0/24",
        "State": "PENDING_ADVERTISING"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator での独自の IP アドレス](https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html)の使用」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AdvertiseByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/advertise-byoip-cidr.html)」を参照してください。

### `allow-custom-routing-traffic`
<a name="global-accelerator_AllowCustomRoutingTraffic_cli_2_topic"></a>

次のコード例は、`allow-custom-routing-traffic` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターの VPC サブネット内の特定の Amazon EC2 インスタンスの送信先へのトラフィックを許可するには**  
次の `allow-custom-routing-traffic` の例では、カスタムルーティングアクセラレーターでトラフィックを受信できる VPC サブネットエンドポイントの特定の Amazon EC2 インスタンス (送信先) IP アドレスとポートへのトラフィックが許可されていることを指定します。  

```
aws globalaccelerator allow-custom-routing-traffic \
    --endpoint-group-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/ab88888example \
    --endpoint-id subnet-abcd123example \
    --destination-addresses "172.31.200.6" "172.31.200.7" \
    --destination-ports 80 81
```
このコマンドでは何も出力されません。  
詳細については、Global [Accelerator デベロッパーガイドの AWS 「Global Accelerator のカスタムルーティングアクセラレーターの VPC サブネットエンドポイント](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-endpoints.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllowCustomRoutingTraffic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/allow-custom-routing-traffic.html)」を参照してください。

### `create-accelerator`
<a name="global-accelerator_CreateAccelerator_cli_2_topic"></a>

次のコード例は、`create-accelerator` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターを作成するには**  
次の `create-accelerator` の例では、2 つの BYOIP 静的 IP アドレスを持つ 2 つのタグを持つアクセラレーターを作成します。アクセラレーターを作成または更新するには、`US-West-2 (Oregon)` リージョンを指定する必要があります。  

```
aws globalaccelerator create-accelerator \
    --name ExampleAccelerator \
    --tags Key="Name",Value="Example Name" Key="Project",Value="Example Project" \
    --ip-addresses 192.0.2.250 198.51.100.52
```
出力:  

```
{
    "Accelerator": {
        "AcceleratorArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh",
        "IpAddressType": "IPV4",
        "Name": "ExampleAccelerator",
        "Enabled": true,
        "Status": "IN_PROGRESS",
        "IpSets": [
            {
                "IpAddresses": [
                    "192.0.2.250",
                    "198.51.100.52"
                ],
                "IpFamily": "IPv4"
            }
        ],
        "DnsName":"a1234567890abcdef.awsglobalaccelerator.com",
        "CreatedTime": 1542394847.0,
        "LastModifiedTime": 1542394847.0
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator の](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-accelerators.html)*AWS アクセラレータ*ー」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAccelerator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/create-accelerator.html)」を参照してください。

### `create-custom-routing-accelerator`
<a name="global-accelerator_CreateCustomRoutingAccelerator_cli_2_topic"></a>

次のコード例は、`create-custom-routing-accelerator` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターを作成するには**  
次の `create-custom-routing-accelerator` の例では、`Name` タグ `Project` タグを使用してカスタムルーティングアクセラレーターを作成します。  

```
aws globalaccelerator create-custom-routing-accelerator \
    --name ExampleCustomRoutingAccelerator \
    --tags Key="Name",Value="Example Name" Key="Project",Value="Example Project" \
    --ip-addresses 192.0.2.250 198.51.100.52
```
出力:  

```
{
    "Accelerator": {
        "AcceleratorArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh",
        "IpAddressType": "IPV4",
        "Name": "ExampleCustomRoutingAccelerator",
        "Enabled": true,
        "Status": "IN_PROGRESS",
        "IpSets": [
            {
                "IpAddresses": [
                    "192.0.2.250",
                    "198.51.100.52"
                ],
                "IpFamily": "IPv4"
            }
        ],
        "DnsName":"a1234567890abcdef.awsglobalaccelerator.com",
        "CreatedTime": 1542394847.0,
        "LastModifiedTime": 1542394847.0
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーター](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-accelerators.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomRoutingAccelerator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/create-custom-routing-accelerator.html)」を参照してください。

### `create-custom-routing-endpoint-group`
<a name="global-accelerator_CreateCustomRoutingEndpointGroup_cli_2_topic"></a>

次のコード例は、`create-custom-routing-endpoint-group` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのエンドポイントグループを作成するには**  
次の `create-custom-routing-endpoint-group` の例では、カスタムルーティングアクセラレーターのエンドポイントグループを作成します。  

```
aws globalaccelerator create-custom-routing-endpoint-group \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz \
    --endpoint-group-region us-east-2 \
    --destination-configurations "FromPort=80,ToPort=81,Protocols=TCP,UDP"
```
出力:  

```
{
    "EndpointGroup": {
        "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/4321abcd",
        "EndpointGroupRegion": "us-east-2",
        "DestinationDescriptions": [
            {
                "FromPort": 80,
                "ToPort": 81,
                "Protocols": [
                    "TCP",
                    "UDP"
                ]
            }
        ],
        "EndpointDescriptions": []
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーターのエンドポイントグループ](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-endpoint-groups.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomRoutingEndpointGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/create-custom-routing-endpoint-group.html)」を参照してください。

### `create-custom-routing-listener`
<a name="global-accelerator_CreateCustomRoutingListener_cli_2_topic"></a>

次のコード例は、`create-custom-routing-listener` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのリスナーを作成するには**  
次の `create-custom-routing-listener` の例では、カスタムルーティングアクセラレーターのポート範囲が 5000～10000 のリスナーを作成します。  

```
aws globalaccelerator create-custom-routing-listener \
    --accelerator-arn arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --port-ranges FromPort=5000,ToPort=10000
```
出力:  

```
{
    "Listener": {
        "PortRange": [
            "FromPort": 5000,
            "ToPort": 10000
        ],
        "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz"
    }
}
```
詳細については、Global [Accelerator デベロッパーガイドの AWS 「Global Accelerator のカスタムルーティングアクセラレーターのリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomRoutingListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/create-custom-routing-listener.html)」を参照してください。

### `create-endpoint-group`
<a name="global-accelerator_CreateEndpointGroup_cli_2_topic"></a>

次のコード例は、`create-endpoint-group` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントグループを作成するには**  
次の `create-endpoint-group` の例では、1 つのエンドポイントを持つエンドポイントグループを作成します。  

```
aws globalaccelerator create-endpoint-group \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz \
    --endpoint-group-region us-east-1 \
    --endpoint-configurations EndpointId=i-1234567890abcdef0,Weight=128
```
出力:  

```
{
    "EndpointGroup": {
        "TrafficDialPercentage": 100.0,
        "EndpointDescriptions": [
            {
                "Weight": 128,
                "EndpointId": "i-1234567890abcdef0"
            }
        ],
        "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/098765zyxwvu",
        "EndpointGroupRegion": "us-east-1"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のエンドポイントグループ](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-endpoint-groups.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEndpointGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/create-endpoint-group.html)」を参照してください。

### `create-listener`
<a name="global-accelerator_CreateListener_cli_2_topic"></a>

次のコード例は、`create-listener` を使用する方法を示しています。

**AWS CLI**  
**リスナーを作成するには**  
次の `create-listener` の例では、2 つのポートを持つリスナーを作成します。  

```
aws globalaccelerator create-listener \
    --accelerator-arn arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --port-ranges FromPort=80,ToPort=80 FromPort=81,ToPort=81 \
    --protocol TCP
```
出力:  

```
{
    "Listener": {
        "PortRanges": [
            {
                "ToPort": 80,
                "FromPort": 80
            },
            {
                "ToPort": 81,
                "FromPort": 81
            }
        ],
        "ClientAffinity": "NONE",
        "Protocol": "TCP",
        "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/create-listener.html)」を参照してください。**

### `deny-custom-routing-traffic`
<a name="global-accelerator_DenyCustomRoutingTraffic_cli_2_topic"></a>

次のコード例は、`deny-custom-routing-traffic` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターでトラフィックを受信できない送信先アドレスを指定するには**  
次の `deny-custom-routing-traffic` の例では、カスタムルーティングアクセラレーターのトラフィックを受信できないサブネットエンドポイントの送信先アドレスを指定します。複数の送信先アドレスを指定するには、アドレスをスペースで区切ります。deny-custom-routing-traffic 呼び出しが成功してもレスポンスはありません。  

```
aws globalaccelerator deny-custom-routing-traffic \
    --endpoint-group-arn "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/ab88888example" \
    --endpoint-id "subnet-abcd123example" \
    --destination-addresses "198.51.100.52"
```
このコマンドでは何も出力されません。  
詳細については、Global [Accelerator デベロッパーガイドの AWS 「Global Accelerator のカスタムルーティングアクセラレーターの VPC サブネットエンドポイント](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-endpoints.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DenyCustomRoutingTraffic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/deny-custom-routing-traffic.html)」を参照してください。

### `deprovision-byoip-cidr`
<a name="global-accelerator_DeprovisionByoipCidr_cli_2_topic"></a>

次のコード例は、`deprovision-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲のプロビジョニングを解除するには**  
次の の`deprovision-byoip-cidr`例では、 AWS リソースで使用するようにプロビジョニングした指定されたアドレス範囲を解放します。  

```
aws globalaccelerator deprovision-byoip-cidr \
    --cidr "198.51.100.0/24"
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "198.51.100.0/24",
        "State": "PENDING_DEPROVISIONING"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator で独自の IP アドレスを使用する](https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html)*AWS *」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeprovisionByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/deprovision-byoip-cidr.html)」を参照してください。

### `describe-accelerator-attributes`
<a name="global-accelerator_DescribeAcceleratorAttributes_cli_2_topic"></a>

次のコード例は、`describe-accelerator-attributes` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターの属性を記述するには**  
次の `describe-accelerator-attributes` の例は、アクセラレーターの属性の詳細を取得します。  

```
aws globalaccelerator describe-accelerator-attributes \
    --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "AcceleratorAttributes": {
        "FlowLogsEnabled": true
        "FlowLogsS3Bucket": flowlogs-abc
        "FlowLogsS3Prefix": bucketprefix-abc
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator の](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-accelerators.html)*AWS アクセラレータ*ー」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAcceleratorAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-accelerator-attributes.html)」を参照してください。

### `describe-accelerator`
<a name="global-accelerator_DescribeAccelerator_cli_2_topic"></a>

次のコード例は、`describe-accelerator` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターを記述するには**  
次の `describe-accelerator` の例では、指定されたアクセラレーターの詳細情報を取得します。  

```
aws globalaccelerator describe-accelerator \
    --accelerator-arn arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "Accelerator": {
        "AcceleratorArn": "arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh",
        "IpAddressType": "IPV4",
        "Name": "ExampleAccelerator",
        "Enabled": true,
        "Status": "IN_PROGRESS",
        "IpSets": [
            {
                "IpAddresses": [
                    "192.0.2.250",
                    "198.51.100.52"
                ],
                "IpFamily": "IPv4"
            }
        ],
        "DnsName":"a1234567890abcdef.awsglobalaccelerator.com",
        "CreatedTime": 1542394847,
        "LastModifiedTime": 1542395013
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator の](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-accelerators.html)*AWS アクセラレータ*ー」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccelerator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-accelerator.html)」を参照してください。

### `describe-custom-routing-accelerator-attributes`
<a name="global-accelerator_DescribeCustomRoutingAcceleratorAttributes_cli_2_topic"></a>

次のコード例は、`describe-custom-routing-accelerator-attributes` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターの属性を記述するには**  
次の `describe-custom-routing-accelerator-attributes` の例では、カスタムルーティングアクセラレーターの属性について記述します。  

```
aws globalaccelerator describe-custom-routing-accelerator-attributes \
   --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "AcceleratorAttributes": {
    "FlowLogsEnabled": false
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーター](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-accelerators.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomRoutingAcceleratorAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-custom-routing-accelerator-attributes.html)」を参照してください。

### `describe-custom-routing-accelerator`
<a name="global-accelerator_DescribeCustomRoutingAccelerator_cli_2_topic"></a>

次のコード例は、`describe-custom-routing-accelerator` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターを記述するには**  
次の `describe-custom-routing-accelerator` の例では、指定されたカスタムルーティングアクセラレーターの詳細を取得します。  

```
aws globalaccelerator describe-custom-routing-accelerator \
    --accelerator-arn arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "Accelerator": {
        "AcceleratorArn": "arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh",
        "IpAddressType": "IPV4",
        "Name": "ExampleCustomRoutingAccelerator",
        "Enabled": true,
        "Status": "IN_PROGRESS",
        "IpSets": [
            {
                "IpAddresses": [
                    "192.0.2.250",
                    "198.51.100.52"
                ],
                "IpFamily": "IPv4"
            }
        ],
        "DnsName":"a1234567890abcdef.awsglobalaccelerator.com",
        "CreatedTime": 1542394847,
        "LastModifiedTime": 1542395013
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーター](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-accelerators.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomRoutingAccelerator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-custom-routing-accelerator.html)」を参照してください。

### `describe-custom-routing-endpoint-group`
<a name="global-accelerator_DescribeCustomRoutingEndpointGroup_cli_2_topic"></a>

次のコード例は、`describe-custom-routing-endpoint-group` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのエンドポイントグループを記述するには**  
次の `describe-custom-routing-endpoint-group` の例では、カスタムルーティングアクセラレーターのエンドポイントグループを記述します。  

```
aws globalaccelerator describe-custom-routing-endpoint-group \
    --endpoint-group-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/6789vxyz/endpoint-group/ab88888example
```
出力:  

```
{
    "EndpointGroup": {
        "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/6789vxyz/endpoint-group/ab88888example",
        "EndpointGroupRegion": "us-east-2",
        "DestinationDescriptions": [
            {
                "FromPort": 5000,
                "ToPort": 10000,
                "Protocols": [
                    "UDP"
                ]
            }
        ],
        "EndpointDescriptions": [
            {
                "EndpointId": "subnet-1234567890abcdef0"
            }
        ]
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーターのエンドポイントグループ](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-endpoint-groups.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomRoutingEndpointGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-custom-routing-endpoint-group.html)」を参照してください。

### `describe-custom-routing-listener`
<a name="global-accelerator_DescribeCustomRoutingListener_cli_2_topic"></a>

次のコード例は、`describe-custom-routing-listener` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのリスナーを記述するには**  
次の `describe-custom-routing-listener` の例では、カスタムルーティングアクセラレーターのリスナーにつを記述します。  

```
aws globalaccelerator describe-custom-routing-listener \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234
```
出力:  

```
{
    "Listener": {
        "PortRanges": [
            "FromPort": 5000,
            "ToPort": 10000
        ],
        "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234"
    }
}
```
詳細については、Global [Accelerator デベロッパーガイドの AWS 「Global Accelerator のカスタムルーティングアクセラレーターのリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomRoutingListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-custom-routing-listener.html)」を参照してください。

### `describe-endpoint-group`
<a name="global-accelerator_DescribeEndpointGroup_cli_2_topic"></a>

次のコード例は、`describe-endpoint-group` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントグループを記述するには**  
次の `describe-endpoint-group` の例では、Amazon EC2 インスタンス、ALB、NLB のエンドポイントを持つエンドポイントグループの詳細を取得します。  

```
aws globalaccelerator describe-endpoint-group \
    --endpoint-group-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/6789vxyz-vxyz-6789-vxyz-6789lmnopqrs/endpoint-group/ab88888example
```
出力:  

```
{
    "EndpointGroup": {
        "TrafficDialPercentage": 100.0,
        "EndpointDescriptions": [
        {
            "Weight": 128,
            "EndpointId": "i-1234567890abcdef0"
        },
        {
            "Weight": 128,
            "EndpointId": "arn:aws:elasticloadbalancing:us-east-1:000123456789:loadbalancer/app/ALBTesting/alb01234567890xyz"
        },
        {
            "Weight": 128,
            "EndpointId": "arn:aws:elasticloadbalancing:us-east-1:000123456789:loadbalancer/net/NLBTesting/alb01234567890qrs"
        }
        ],
        "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/6789vxyz-vxyz-6789-vxyz-6789lmnopqrs/endpoint-group/4321abcd-abcd-4321-abcd-4321abcdefg",
        "EndpointGroupRegion": "us-east-1"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のエンドポイントグループ](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-endpoint-groups.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEndpointGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-endpoint-group.html)」を参照してください。

### `describe-listener`
<a name="global-accelerator_DescribeListener_cli_2_topic"></a>

次のコード例は、`describe-listener` を使用する方法を示しています。

**AWS CLI**  
**リスナーを記述するには**  
次の `describe-listener` の例では、リスナーを記述しています。  

```
aws globalaccelerator describe-listener \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234
```
出力:  

```
{
    "Listener": {
        "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234",
        "PortRanges": [
            {
                "FromPort": 80,
                "ToPort": 80
            }
        ],
        "Protocol": "TCP",
        "ClientAffinity": "NONE"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/describe-listener.html)」を参照してください。

### `list-accelerators`
<a name="global-accelerator_ListAccelerators_cli_2_topic"></a>

次のコード例は、`list-accelerators` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターを一覧表示するには**  
次の の`list-accelerators`例では、 AWS アカウントのアクセラレーターを一覧表示します。このアカウントには 2 つのアクセラレーターがあります。  

```
aws globalaccelerator list-accelerators
```
出力:  

```
{
    "Accelerators": [
        {
            "AcceleratorArn": "arn:aws:globalaccelerator::012345678901:accelerator/5555abcd-abcd-5555-abcd-5555EXAMPLE1",
            "Name": "TestAccelerator",
            "IpAddressType": "IPV4",
            "Enabled": true,
            "IpSets": [
                {
                    "IpFamily": "IPv4",
                    "IpAddresses": [
                        "192.0.2.250",
                        "198.51.100.52"
                    ]
                }
            ],
            "DnsName": "5a5a5a5a5a5a5a5a.awsglobalaccelerator.com",
            "Status": "DEPLOYED",
            "CreatedTime": 1552424416.0,
            "LastModifiedTime": 1569375641.0
        },
        {
            "AcceleratorArn": "arn:aws:globalaccelerator::888888888888:accelerator/8888abcd-abcd-8888-abcd-8888EXAMPLE2",
            "Name": "ExampleAccelerator",
            "IpAddressType": "IPV4",
            "Enabled": true,
            "IpSets": [
                {
                    "IpFamily": "IPv4",
                    "IpAddresses": [
                        "192.0.2.100",
                        "198.51.100.10"
                    ]
                }
            ],
            "DnsName": "6a6a6a6a6a6a6a.awsglobalaccelerator.com",
            "Status": "DEPLOYED",
            "CreatedTime": 1575585564.0,
            "LastModifiedTime": 1579809243.0
        },
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator の](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-accelerators.html)*AWS アクセラレータ*ー」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccelerators](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-accelerators.html)」を参照してください。

### `list-byoip-cidr`
<a name="global-accelerator_ListByoipCidr_cli_2_topic"></a>

次のコード例は、`list-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲を一覧表示するには**  
次の `list-byoip-cidr` の例では、Global Accelerator で使用するようにプロビジョニングした Bring Your Own IP アドレス (BYOIP) アドレス範囲を一覧表示します。  

```
aws globalaccelerator list-byoip-cidrs
```
出力:  

```
{
    "ByoipCidrs": [
        {
            "Cidr": "198.51.100.0/24",
            "State": "READY"
        }
        {
            "Cidr": "203.0.113.25/24",
            "State": "READY"
        }
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator で独自の IP アドレスを使用する](https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html)*AWS *」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-byoip-cidr.html)」を参照してください。

### `list-custom-routing-accelerators`
<a name="global-accelerator_ListCustomRoutingAccelerators_cli_2_topic"></a>

次のコード例は、`list-custom-routing-accelerators` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターを一覧表示するには**  
次の の`list-custom-routing-accelerators`例では、 AWS アカウントのカスタムルーティングアクセラレーターを一覧表示します。  

```
aws globalaccelerator list-custom-routing-accelerators
```
出力:  

```
{
    "Accelerators": [
        {
            "AcceleratorArn": "arn:aws:globalaccelerator::012345678901:accelerator/5555abcd-abcd-5555-abcd-5555EXAMPLE1",
            "Name": "TestCustomRoutingAccelerator",
            "IpAddressType": "IPV4",
            "Enabled": true,
            "IpSets": [
                {
                    "IpFamily": "IPv4",
                    "IpAddresses": [
                        "192.0.2.250",
                        "198.51.100.52"
                    ]
                }
            ],
            "DnsName": "5a5a5a5a5a5a5a5a.awsglobalaccelerator.com",
            "Status": "DEPLOYED",
            "CreatedTime": 1552424416.0,
            "LastModifiedTime": 1569375641.0
        },
        {
            "AcceleratorArn": "arn:aws:globalaccelerator::888888888888:accelerator/8888abcd-abcd-8888-abcd-8888EXAMPLE2",
            "Name": "ExampleCustomRoutingAccelerator",
            "IpAddressType": "IPV4",
            "Enabled": true,
            "IpSets": [
                {
                    "IpFamily": "IPv4",
                    "IpAddresses": [
                        "192.0.2.100",
                        "198.51.100.10"
                    ]
                }
            ],
            "DnsName": "6a6a6a6a6a6a6a.awsglobalaccelerator.com",
            "Status": "DEPLOYED",
            "CreatedTime": 1575585564.0,
            "LastModifiedTime": 1579809243.0
        },
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーター](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-accelerators.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCustomRoutingAccelerators](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-custom-routing-accelerators.html)」を参照してください。

### `list-custom-routing-endpoint-groups`
<a name="global-accelerator_ListCustomRoutingEndpointGroups_cli_2_topic"></a>

次のコード例は、`list-custom-routing-endpoint-groups` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターでリスナーのエンドポイントグループを一覧表示するには**  
次の `list-custom-routing-endpoint-groups` の例では、カスタムルーティングアクセラレーターのリスナーのエンドポイントグループを一覧表示します。  

```
aws globalaccelerator list-custom-routing-endpoint-groups \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234
```
出力:  

```
{
    "EndpointGroups": [
        {
            "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234/endpoint-group/ab88888example",
            "EndpointGroupRegion": "eu-central-1",
            "DestinationDescriptions": [
                {
                    "FromPort": 80,
                    "ToPort": 80,
                    "Protocols": [
                        "TCP",
                        "UDP"
                    ]
                }
            ]
            "EndpointDescriptions": [
                {
                    "EndpointId": "subnet-abcd123example"
                }
            ]
        }
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーターのエンドポイントグループ](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-endpoint-groups.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCustomRoutingEndpointGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-custom-routing-endpoint-groups.html)」を参照してください。

### `list-custom-routing-listeners`
<a name="global-accelerator_ListCustomRoutingListeners_cli_2_topic"></a>

次のコード例は、`list-custom-routing-listeners` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのリスナーを一覧表示するには**  
次の `list-custom-routing-listeners` の例では、カスタムルーティングアクセラレーターのリスナーを一覧表示します。  

```
aws globalaccelerator list-custom-routing-listeners \
    --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234",
            "PortRanges": [
                {
                    "FromPort": 5000,
                    "ToPort": 10000
                }
            ],
            "Protocol": "TCP"
        }
    ]
}
```
詳細については、Global [Accelerator デベロッパーガイドの AWS 「Global Accelerator のカスタムルーティングアクセラレーターのリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCustomRoutingListeners](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-custom-routing-listeners.html)」を参照してください。

### `list-custom-routing-port-mappings-by-destination`
<a name="global-accelerator_ListCustomRoutingPortMappingsByDestination_cli_2_topic"></a>

次のコード例は、`list-custom-routing-port-mappings-by-destination` を使用する方法を示しています。

**AWS CLI**  
**特定のカスタムルーティングアクセラレーターの送信先のポートマッピングを一覧表示するには**  
次の `list-custom-routing-port-mappings-by-destination` の例では、カスタムルーティングアクセラレーターの特定の送信先 EC2 サーバー (送信先アドレス) のポートマッピングを示します。  

```
aws globalaccelerator list-custom-routing-port-mappings-by-destination \
    --endpoint-id subnet-abcd123example \
    --destination-address 198.51.100.52
```
出力:  

```
{
    "DestinationPortMappings": [
        {
            "AcceleratorArn": "arn:aws:globalaccelerator::402092451327:accelerator/24ea29b8-d750-4489-8919-3095f3c4b0a7",
                "AcceleratorSocketAddresses": [
                    {
                        "IpAddress": "192.0.2.250",
                        "Port": 65514
                    },
                    {
                        "IpAddress": "192.10.100.99",
                        "Port": 65514
                    }
                ],
                "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/ab88888example",
                "EndpointId": "subnet-abcd123example",
                "EndpointGroupRegion": "us-west-2",
                "DestinationSocketAddress": {
                    "IpAddress": "198.51.100.52",
                    "Port": 80
                },
                "IpAddressType": "IPv4",
                "DestinationTrafficState": "ALLOW"
        }
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator でのカスタムルーティングアクセラレーターの仕組み](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-how-it-works.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCustomRoutingPortMappingsByDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-custom-routing-port-mappings-by-destination.html)」を参照してください。

### `list-custom-routing-port-mappings`
<a name="global-accelerator_ListCustomRoutingPortMappings_cli_2_topic"></a>

次のコード例は、`list-custom-routing-port-mappings` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのポートマッピングを一覧表示するには**  
次の `list-custom-routing-port-mappings` の例は、カスタムルーティングアクセラレーターのポートマッピングの部分的なリストを示しています。  

```
aws globalaccelerator list-custom-routing-port-mappings \
    --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "PortMappings": [
        {
            "AcceleratorPort": 40480,
            "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/098765zyxwvu",
            "EndpointId": "subnet-1234567890abcdef0",
            "DestinationSocketAddress": {
                "IpAddress": "192.0.2.250",
                "Port": 80
            },
            "Protocols": [
                "TCP",
                "UDP"
            ],
            "DestinationTrafficState": "ALLOW"
        }
        {
            "AcceleratorPort": 40481,
            "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz/endpoint-group/098765zyxwvu",
            "EndpointId": "subnet-1234567890abcdef0",
            "DestinationSocketAddress": {
               "IpAddress": "192.0.2.251",
              "Port": 80
            },
            "Protocols": [
                "TCP",
                "UDP"
            ],
            "DestinationTrafficState": "ALLOW"
        }
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator でのカスタムルーティングアクセラレーターの仕組み](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-how-it-works.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCustomRoutingPortMappings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-custom-routing-port-mappings.html)」を参照してください。

### `list-endpoint-groups`
<a name="global-accelerator_ListEndpointGroups_cli_2_topic"></a>

次のコード例は、`list-endpoint-groups` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントグループを一覧表示するには**  
次の `list-endpoint-groups` の例では、リスナーのエンドポイントグループを一覧表示します。このリスナーには 2 つのエンドポイントグループがあります。  

```
aws globalaccelerator --region us-west-2 list-endpoint-groups \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234
```
出力:  

```
{
    "EndpointGroups": [
        {
            "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234/endpoint-group/ab88888example",
            "EndpointGroupRegion": "eu-central-1",
            "EndpointDescriptions": [],
            "TrafficDialPercentage": 100.0,
            "HealthCheckPort": 80,
            "HealthCheckProtocol": "TCP",
            "HealthCheckIntervalSeconds": 30,
            "ThresholdCount": 3
        }
        {
            "EndpointGroupArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234/endpoint-group/ab99999example",
            "EndpointGroupRegion": "us-east-1",
            "EndpointDescriptions": [],
            "TrafficDialPercentage": 50.0,
            "HealthCheckPort": 80,
            "HealthCheckProtocol": "TCP",
            "HealthCheckIntervalSeconds": 30,
            "ThresholdCount": 3
        }
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のエンドポイントグループ](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-endpoint-groups.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEndpointGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-endpoint-groups.html)」を参照してください。

### `list-listeners`
<a name="global-accelerator_ListListeners_cli_2_topic"></a>

次のコード例は、`list-listeners` を使用する方法を示しています。

**AWS CLI**  
**リスナーを一覧表示するには**  
次の `list-listeners` の例では、アクセラレーターのリスナーを一覧表示します。  

```
aws globalaccelerator list-listeners \
    --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "Listeners": [
        {
            "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/abcdef1234",
            "PortRanges": [
                {
                    "FromPort": 80,
                    "ToPort": 80
                }
            ],
            "Protocol": "TCP",
            "ClientAffinity": "NONE"
        }
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListListeners](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-listeners.html)」を参照してください。

### `list-tags-for-resource`
<a name="global-accelerator_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、特定のアクセラレーターのタグを一覧表示します。  

```
aws globalaccelerator list-tags-for-resource \
    --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Project",
            "Value": "A123456"
        }
    ]
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator でのタグ付け](https://docs.aws.amazon.com/global-accelerator/latest/dg/tagging-in-global-accelerator.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/list-tags-for-resource.html)」を参照してください。

### `provision-byoip-cidr`
<a name="global-accelerator_ProvisionByoipCidr_cli_2_topic"></a>

次のコード例は、`provision-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲をプロビジョニングするには**  
次の の`provision-byoip-cidr`例では、 AWS リソースで使用する指定されたアドレス範囲をプロビジョニングします。  

```
aws globalaccelerator provision-byoip-cidr \
    --cidr 192.0.2.250/24 \
    --cidr-authorization-context Message="$text_message",Signature="$signed_message"
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "192.0.2.250/24",
        "State": "PENDING_PROVISIONING"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator で独自の IP アドレスを使用する](https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html)*AWS *」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ProvisionByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/provision-byoip-cidr.html)」を参照してください。

### `tag-resource`
<a name="global-accelerator_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターにタグを付けるには**  
次の `tag-resource` の例では、タグ Name とタグ Project をアクセラレーターに追加し、それぞれに対応する値を追加します。  

```
aws globalaccelerator tag-resource \
    --resource-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --tags Key="Name",Value="Example Name" Key="Project",Value="Example Project"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator でのタグ付け](https://docs.aws.amazon.com/global-accelerator/latest/dg/tagging-in-global-accelerator.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="global-accelerator_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターからタグを削除するには**  
次の `untag-resource` の例では、アクセラレーターから Name タグと Project タグを削除します。  

```
aws globalaccelerator untag-resource \
    --resource-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --tag-keys Key="Name" Key="Project"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator でのタグ付け](https://docs.aws.amazon.com/global-accelerator/latest/dg/tagging-in-global-accelerator.html)」を参照してください。 *AWS *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/untag-resource.html)」を参照してください。

### `update-accelerator-attributes`
<a name="global-accelerator_UpdateAcceleratorAttributes_cli_2_topic"></a>

次のコード例は、`update-accelerator-attributes` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターの属性を更新するには**  
次の `update-accelerator-attributes` の例では、フローログを有効にするためにアクセラレーターを更新します。アクセラレーター属性を作成または更新するには、`US-West-2 (Oregon)` リージョンを指定する必要があります。  

```
aws globalaccelerator update-accelerator-attributes \
    --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --flow-logs-enabled \
    --flow-logs-s3-bucket flowlogs-abc \
    --flow-logs-s3-prefix bucketprefix-abc
```
出力:  

```
{
    "AcceleratorAttributes": {
        "FlowLogsEnabled": true
        "FlowLogsS3Bucket": flowlogs-abc
        "FlowLogsS3Prefix": bucketprefix-abc
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator の](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-accelerators.html)*AWS アクセラレータ*ー」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAcceleratorAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/update-accelerator-attributes.html)」を参照してください。

### `update-accelerator`
<a name="global-accelerator_UpdateAccelerator_cli_2_topic"></a>

次のコード例は、`update-accelerator` を使用する方法を示しています。

**AWS CLI**  
**アクセラレーターを更新するには**  
次の `update-accelerator` の例では、アクセラレーター名を `ExampleAcceleratorNew` に変更するようにアクセラレーターを変更します。アクセラレーターを作成または更新するには、`US-West-2 (Oregon)` リージョンを指定する必要があります。  

```
aws globalaccelerator update-accelerator \
    --accelerator-arn arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --name ExampleAcceleratorNew
```
出力:  

```
{
    "Accelerator": {
        "AcceleratorArn": "arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh",
        "IpAddressType": "IPV4",
        "Name": "ExampleAcceleratorNew",
        "Enabled": true,
        "Status": "IN_PROGRESS",
        "IpSets": [
            {
                "IpAddresses": [
                    "192.0.2.250",
                    "198.51.100.52"
                ],
                "IpFamily": "IPv4"
            }
        ],
        "DnsName":"a1234567890abcdef.awsglobalaccelerator.com",
        "CreatedTime": 1232394847,
        "LastModifiedTime": 1232395654
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator の](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-accelerators.html)*AWS アクセラレータ*ー」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccelerator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/update-accelerator.html)」を参照してください。

### `update-custom-routing-accelerator-attributes`
<a name="global-accelerator_UpdateCustomRoutingAcceleratorAttributes_cli_2_topic"></a>

次のコード例は、`update-custom-routing-accelerator-attributes` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターの属性を更新するには**  
次の `update-custom-routing-accelerator-attributes` の例では、カスタムルーティングアクセラレーターを更新してフローログを有効にします。  

```
aws globalaccelerator update-custom-routing-accelerator-attributes \
    --accelerator-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --flow-logs-enabled \
    --flow-logs-s3-bucket flowlogs-abc \
    --flow-logs-s3-prefix bucketprefix-abc
```
出力:  

```
{
    "AcceleratorAttributes": {
        "FlowLogsEnabled": true
        "FlowLogsS3Bucket": flowlogs-abc
        "FlowLogsS3Prefix": bucketprefix-abc
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーター](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-accelerators.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCustomRoutingAcceleratorAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/update-custom-routing-accelerator-attributes.html)」を参照してください。

### `update-custom-routing-accelerator`
<a name="global-accelerator_UpdateCustomRoutingAccelerator_cli_2_topic"></a>

次のコード例は、`update-custom-routing-accelerator` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターを更新するには**  
次の `update-custom-routing-accelerator` の例では、カスタムルーティングアクセラレーターを変更して、アクセラレーター名を変更します。  

```
aws globalaccelerator --region us-west-2 update-custom-routing-accelerator \
    --accelerator-arn arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh \
    --name ExampleCustomRoutingAcceleratorNew
```
出力:  

```
{
    "Accelerator": {
        "AcceleratorArn": "arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh",
        "IpAddressType": "IPV4",
        "Name": "ExampleCustomRoutingAcceleratorNew",
        "Enabled": true,
        "Status": "IN_PROGRESS",
        "IpSets": [
            {
                "IpAddresses": [
                    "192.0.2.250",
                    "198.51.100.52"
                ],
                "IpFamily": "IPv4"
            }
        ],
        "DnsName":"a1234567890abcdef.awsglobalaccelerator.com",
        "CreatedTime": 1232394847,
        "LastModifiedTime": 1232395654
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のカスタムルーティングアクセラレーター](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-accelerators.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCustomRoutingAccelerator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/update-custom-routing-accelerator.html)」を参照してください。

### `update-custom-routing-listener`
<a name="global-accelerator_UpdateCustomRoutingListener_cli_2_topic"></a>

次のコード例は、`update-custom-routing-listener` を使用する方法を示しています。

**AWS CLI**  
**カスタムルーティングアクセラレーターのリスナーを更新するには**  
次の `update-custom-routing-listener` の例では、リスナーを更新してポート範囲を変更します。  

```
aws globalaccelerator update-custom-routing-listener \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz \
    --port-ranges FromPort=10000,ToPort=20000
```
出力:  

```
{
    "Listener": {
        "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz
        "PortRanges": [
            {
                "FromPort": 10000,
                "ToPort": 20000
            }
        ],
        "Protocol": "TCP"
    }
}
```
詳細については、Global [Accelerator デベロッパーガイドの AWS 「Global Accelerator のカスタムルーティングアクセラレーターのリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-custom-routing-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCustomRoutingListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/update-custom-routing-listener.html)」を参照してください。

### `update-endpoint-group`
<a name="global-accelerator_UpdateEndpointGroup_cli_2_topic"></a>

次のコード例は、`update-endpoint-group` を使用する方法を示しています。

**AWS CLI**  
**エンドポイントグループを更新するには**  
次の `update-endpoint-group` の例では、Elastic IP アドレス、ALB、NLB の 3 つのエンドポイントをエンドポイントグループに追加します。  

```
aws globalaccelerator update-endpoint-group \
    --endpoint-group-arn arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/6789vxyz-vxyz-6789-vxyz-6789lmnopqrs/endpoint-group/ab88888example \
    --endpoint-configurations \
        EndpointId=eipalloc-eip01234567890abc,Weight=128 \
        EndpointId=arn:aws:elasticloadbalancing:us-east-1:000123456789:loadbalancer/app/ALBTesting/alb01234567890xyz,Weight=128 \
        EndpointId=arn:aws:elasticloadbalancing:us-east-1:000123456789:loadbalancer/net/NLBTesting/alb01234567890qrs,Weight=128
```
出力:  

```
{
    "EndpointGroup": {
        "TrafficDialPercentage": 100,
        "EndpointDescriptions": [
            {
                "Weight": 128,
                "EndpointId": "eip01234567890abc"
            },
            {
                "Weight": 128,
                "EndpointId": "arn:aws:elasticloadbalancing:us-east-1:000123456789:loadbalancer/app/ALBTesting/alb01234567890xyz"
            },
            {
                "Weight": 128,
                "EndpointId": "arn:aws:elasticloadbalancing:us-east-1:000123456789:loadbalancer/net/NLBTesting/alb01234567890qrs"
            }
        ],
        "EndpointGroupArn": "arn:aws:globalaccelerator::123456789012:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/6789vxyz-vxyz-6789-vxyz-6789lmnopqrs/endpoint-group/4321abcd-abcd-4321-abcd-4321abcdefg",
        "EndpointGroupRegion": "us-east-1"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のエンドポイントグループ](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-endpoint-groups.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEndpointGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/update-endpoint-group.html)」を参照してください。

### `update-listener`
<a name="global-accelerator_UpdateListener_cli_2_topic"></a>

次のコード例は、`update-listener` を使用する方法を示しています。

**AWS CLI**  
**リスナーを更新するには**  
次の `update-listener` の例では、リスナーを更新してポートを 100 に変更します。  

```
aws globalaccelerator update-listener \
    --listener-arn arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz \
    --port-ranges FromPort=100,ToPort=100
```
出力:  

```
{
    "Listener": {
        "ListenerArn": "arn:aws:globalaccelerator::012345678901:accelerator/1234abcd-abcd-1234-abcd-1234abcdefgh/listener/0123vxyz
        "PortRanges": [
            {
                "FromPort": 100,
                "ToPort": 100
            }
        ],
        "Protocol": "TCP",
        "ClientAffinity": "NONE"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator のリスナー](https://docs.aws.amazon.com/global-accelerator/latest/dg/about-listeners.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/update-listener.html)」を参照してください。

### `withdraw-byoip-cidr`
<a name="global-accelerator_WithdrawByoipCidr_cli_2_topic"></a>

次のコード例は、`withdraw-byoip-cidr` を使用する方法を示しています。

**AWS CLI**  
**アドレス範囲を取り消すには**  
次の の`withdraw-byoip-cidr`例では、以前に AWS リソースで使用するためにアドバタイズした AWS Global Accelerator からアドレス範囲を取り消します。  

```
aws globalaccelerator withdraw-byoip-cidr \
    --cidr 192.0.2.250/24
```
出力:  

```
{
    "ByoipCidr": {
        "Cidr": "192.0.2.250/24",
        "State": "PENDING_WITHDRAWING"
    }
}
```
詳細については、[AWS 「 Global Accelerator デベロッパーガイド」の「Global Accelerator で独自の IP アドレスを使用する](https://docs.aws.amazon.com/global-accelerator/latest/dg/using-byoip.html)*AWS *」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[WithdrawByoipCidr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/globalaccelerator/withdraw-byoip-cidr.html)」を参照してください。

# AWS Glue を使用した の例 AWS CLI
<a name="cli_2_glue_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-stop-job-run`
<a name="glue_BatchStopJobRun_cli_2_topic"></a>

次のコード例は、`batch-stop-job-run` を使用する方法を示しています。

**AWS CLI**  
**ジョブの実行を停止するには**  
次の `batch-stop-job-run` の例ではジョブの実行を停止します。  

```
aws glue batch-stop-job-run \
    --job-name "my-testing-job" \
    --job-run-id jr_852f1de1f29fb62e0ba4166c33970803935d87f14f96cfdee5089d5274a61d3f
```
出力:  

```
{
    "SuccessfulSubmissions": [
        {
            "JobName": "my-testing-job",
            "JobRunId": "jr_852f1de1f29fb62e0ba4166c33970803935d87f14f96cfdee5089d5274a61d3f"
        }
    ],
    "Errors": [],
    "ResponseMetadata": {
        "RequestId": "66bd6b90-01db-44ab-95b9-6aeff0e73d88",
        "HTTPStatusCode": 200,
        "HTTPHeaders": {
            "date": "Fri, 16 Oct 2020 20:54:51 GMT",
            "content-type": "application/x-amz-json-1.1",
            "content-length": "148",
            "connection": "keep-alive",
            "x-amzn-requestid": "66bd6b90-01db-44ab-95b9-6aeff0e73d88"
        },
        "RetryAttempts": 0
    }
}
```
詳細については、*AWS Glue デベロッパーガイド* の「[ジョブの実行](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchStopJobRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/batch-stop-job-run.html)」を参照してください。

### `create-connection`
<a name="glue_CreateConnection_cli_2_topic"></a>

次の例は、`create-connection` を使用する方法を説明しています。

**AWS CLI**  
** AWS Glue データストアの接続を作成するには**  
次の`create-connection`例では、Kafka データストアの接続情報を提供する接続を AWS Glue データカタログに作成します。  

```
aws glue create-connection \
    --connection-input '{ \
        "Name":"conn-kafka-custom", \
        "Description":"kafka connection with ssl to custom kafka", \
        "ConnectionType":"KAFKA",  \
        "ConnectionProperties":{  \
            "KAFKA_BOOTSTRAP_SERVERS":"<Kafka-broker-server-url>:<SSL-Port>", \
            "KAFKA_SSL_ENABLED":"true", \
            "KAFKA_CUSTOM_CERT": "s3://bucket/prefix/cert-file.pem" \
        }, \
        "PhysicalConnectionRequirements":{ \
            "SubnetId":"subnet-1234", \
            "SecurityGroupIdList":["sg-1234"], \
            "AvailabilityZone":"us-east-1a"} \
    }' \
    --region us-east-1
    --endpoint https://glue.us-east-1.amazonaws.com
```
このコマンドでは何も出力されません。  
詳細については、「 [AWS Glue デベロッパーガイド」の「 Glue データカタログの接続の定義](https://docs.aws.amazon.com/glue/latest/dg/populate-add-connection.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConnection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/create-connection.html)」を参照してください。

### `create-database`
<a name="glue_CreateDatabase_cli_2_topic"></a>

次のコード例は、`create-database` を使用する方法を示しています。

**AWS CLI**  
**データベースを作成するには**  
次の`create-database`例では、 AWS Glue データカタログにデータベースを作成します。  

```
aws glue create-database \
    --database-input "{\"Name\":\"tempdb\"}" \
    --profile my_profile \
    --endpoint https://glue.us-east-1.amazonaws.com
```
このコマンドでは何も出力されません。  
詳細については、*AWS Glue デベロッパーガイド* の「[データカタログにデータベースを定義する](https://docs.aws.amazon.com/glue/latest/dg/define-database.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/create-database.html)」を参照してください。

### `create-job`
<a name="glue_CreateJob_cli_2_topic"></a>

次のコード例は、`create-job` を使用する方法を示しています。

**AWS CLI**  
**データを変換するジョブを作成するには**　  
次の `create-job` 例では、S3 に保存されているスクリプトを実行するストリーミングジョブを作成します。  

```
aws glue create-job \
    --name my-testing-job \
    --role AWSGlueServiceRoleDefault \
    --command '{ \
        "Name": "gluestreaming", \
        "ScriptLocation": "s3://amzn-s3-demo-bucket/folder/" \
    }' \
    --region us-east-1 \
    --output json \
    --default-arguments '{ \
        "--job-language":"scala", \
        "--class":"GlueApp" \
    }' \
    --profile my-profile \
    --endpoint https://glue.us-east-1.amazonaws.com
```
`test_script.scala` の内容:  

```
import com.amazonaws.services.glue.ChoiceOption
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.MappingSpec
import com.amazonaws.services.glue.ResolveSpec
import com.amazonaws.services.glue.errors.CallSite
import com.amazonaws.services.glue.util.GlueArgParser
import com.amazonaws.services.glue.util.Job
import com.amazonaws.services.glue.util.JsonOptions
import org.apache.spark.SparkContext
import scala.collection.JavaConverters._

object GlueApp {
    def main(sysArgs: Array[String]) {
        val spark: SparkContext = new SparkContext()
        val glueContext: GlueContext = new GlueContext(spark)
        // @params: [JOB_NAME]
        val args = GlueArgParser.getResolvedOptions(sysArgs, Seq("JOB_NAME").toArray)
        Job.init(args("JOB_NAME"), glueContext, args.asJava)
        // @type: DataSource
        // @args: [database = "tempdb", table_name = "s3-source", transformation_ctx = "datasource0"]
        // @return: datasource0
        // @inputs: []
        val datasource0 = glueContext.getCatalogSource(database = "tempdb", tableName = "s3-source", redshiftTmpDir = "", transformationContext = "datasource0").getDynamicFrame()
        // @type: ApplyMapping
        // @args: [mapping = [("sensorid", "int", "sensorid", "int"), ("currenttemperature", "int", "currenttemperature", "int"), ("status", "string", "status", "string")], transformation_ctx = "applymapping1"]
        // @return: applymapping1
        // @inputs: [frame = datasource0]
        val applymapping1 = datasource0.applyMapping(mappings = Seq(("sensorid", "int", "sensorid", "int"), ("currenttemperature", "int", "currenttemperature", "int"), ("status", "string", "status", "string")), caseSensitive = false, transformationContext = "applymapping1")
        // @type: SelectFields
        // @args: [paths = ["sensorid", "currenttemperature", "status"], transformation_ctx = "selectfields2"]
        // @return: selectfields2
        // @inputs: [frame = applymapping1]
        val selectfields2 = applymapping1.selectFields(paths = Seq("sensorid", "currenttemperature", "status"), transformationContext = "selectfields2")
        // @type: ResolveChoice
        // @args: [choice = "MATCH_CATALOG", database = "tempdb", table_name = "my-s3-sink", transformation_ctx = "resolvechoice3"]
        // @return: resolvechoice3
        // @inputs: [frame = selectfields2]
        val resolvechoice3 = selectfields2.resolveChoice(choiceOption = Some(ChoiceOption("MATCH_CATALOG")), database = Some("tempdb"), tableName = Some("my-s3-sink"), transformationContext = "resolvechoice3")
        // @type: DataSink
        // @args: [database = "tempdb", table_name = "my-s3-sink", transformation_ctx = "datasink4"]
        // @return: datasink4
        // @inputs: [frame = resolvechoice3]
        val datasink4 = glueContext.getCatalogSink(database = "tempdb", tableName = "my-s3-sink", redshiftTmpDir = "", transformationContext = "datasink4").writeDynamicFrame(resolvechoice3)
        Job.commit()
    }
}
```
出力:  

```
{
    "Name": "my-testing-job"
}
```
詳細については、「 [AWS Glue デベロッパーガイド」の「 Glue でのジョブの作成](https://docs.aws.amazon.com/glue/latest/dg/author-job.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[CreateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/create-job.html)」を参照してください。

### `create-table`
<a name="glue_CreateTable_cli_2_topic"></a>

次のコード例は、`create-table` を使用する方法を示しています。

**AWS CLI**  
**例 1: Kinesis データストリームのテーブルを作成するには**  
次の`create-table`例では、Kinesis データストリームを記述するテーブルを AWS Glue データカタログに作成します。  

```
aws glue create-table \
    --database-name tempdb \
    --table-input  '{"Name":"test-kinesis-input", "StorageDescriptor":{ \
            "Columns":[ \
                {"Name":"sensorid", "Type":"int"}, \
                {"Name":"currenttemperature", "Type":"int"}, \
                {"Name":"status", "Type":"string"}
            ], \
            "Location":"my-testing-stream", \
            "Parameters":{ \
                "typeOfData":"kinesis","streamName":"my-testing-stream", \
                "kinesisUrl":"https://kinesis.us-east-1.amazonaws.com" \
            }, \
            "SerdeInfo":{ \
                "SerializationLibrary":"org.openx.data.jsonserde.JsonSerDe"} \
        }, \
        "Parameters":{ \
            "classification":"json"} \
        }' \
    --profile my-profile \
    --endpoint https://glue.us-east-1.amazonaws.com
```
このコマンドでは何も出力されません。  
詳細については、[「 AWS Glue デベロッパーガイド」の「 Glue データカタログのテーブルの定義](https://docs.aws.amazon.com/glue/latest/dg/tables-described.html)」を参照してください。 *AWS *  
**例 2: Kafka データストアのテーブルを作成するには**  
次の`create-table`例では、Kafka データストアを記述するテーブルを AWS Glue データカタログに作成します。  

```
aws glue create-table \
    --database-name tempdb \
    --table-input  '{"Name":"test-kafka-input", "StorageDescriptor":{ \
            "Columns":[ \
                {"Name":"sensorid", "Type":"int"}, \
                {"Name":"currenttemperature", "Type":"int"}, \
                {"Name":"status", "Type":"string"}
            ], \
            "Location":"glue-topic", \
            "Parameters":{ \
                "typeOfData":"kafka","topicName":"glue-topic", \
                "connectionName":"my-kafka-connection"
            }, \
            "SerdeInfo":{ \
                "SerializationLibrary":"org.apache.hadoop.hive.serde2.OpenCSVSerde"} \
        }, \
        "Parameters":{ \
            "separatorChar":","} \
        }' \
    --profile my-profile \
    --endpoint https://glue.us-east-1.amazonaws.com
```
このコマンドでは何も出力されません。  
詳細については、[「 AWS Glue デベロッパーガイド」の「 Glue データカタログのテーブルの定義](https://docs.aws.amazon.com/glue/latest/dg/tables-described.html)」を参照してください。 *AWS *  
**例 3: AWS S3 データストアのテーブルを作成するには**  
次の`create-table`例では、 AWS Simple Storage Service (AWS S3) データストアを記述するテーブルを AWS Glue データカタログに作成します。  

```
aws glue create-table \
    --database-name tempdb \
    --table-input  '{"Name":"s3-output", "StorageDescriptor":{ \
            "Columns":[ \
                {"Name":"s1", "Type":"string"}, \
                {"Name":"s2", "Type":"int"}, \
                {"Name":"s3", "Type":"string"}
            ], \
            "Location":"s3://bucket-path/", \
            "SerdeInfo":{ \
                "SerializationLibrary":"org.openx.data.jsonserde.JsonSerDe"} \
        }, \
        "Parameters":{ \
            "classification":"json"} \
        }' \
    --profile my-profile \
    --endpoint https://glue.us-east-1.amazonaws.com
```
このコマンドでは何も出力されません。  
詳細については、[「 AWS Glue デベロッパーガイド」の「 Glue データカタログのテーブルの定義](https://docs.aws.amazon.com/glue/latest/dg/tables-described.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTable](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/create-table.html)」を参照してください。

### `delete-job`
<a name="glue_DeleteJob_cli_2_topic"></a>

次のコード例は、`delete-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブを削除するには**  
次の `delete-job` 例では、不要になったジョブを削除します。  

```
aws glue delete-job \
    --job-name my-testing-job
```
出力:  

```
{
    "JobName": "my-testing-job"
}
```
詳細については、「 [AWS Glue デベロッパーガイド」の「 Glue コンソールでのジョブの使用](https://docs.aws.amazon.com/glue/latest/dg/console-jobs.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[DeleteJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/delete-job.html)」を参照してください。

### `get-databases`
<a name="glue_GetDatabases_cli_2_topic"></a>

次の例は、`get-databases` を使用する方法を説明しています。

**AWS CLI**  
** AWS Glue データカタログの一部またはすべてのデータベースの定義を一覧表示するには**  
次の `get-databases` の例では、データカタログのデータベースに関する情報を返します。  

```
aws glue get-databases
```
出力:  

```
{
    "DatabaseList": [
        {
            "Name": "default",
            "Description": "Default Hive database",
            "LocationUri": "file:/spark-warehouse",
            "CreateTime": 1602084052.0,
            "CreateTableDefaultPermissions": [
                {
                    "Principal": {
                        "DataLakePrincipalIdentifier": "IAM_ALLOWED_PRINCIPALS"
                    },
                    "Permissions": [
                        "ALL"
                    ]
                }
            ],
            "CatalogId": "111122223333"
        },
        {
            "Name": "flights-db",
            "CreateTime": 1587072847.0,
            "CreateTableDefaultPermissions": [
                {
                    "Principal": {
                        "DataLakePrincipalIdentifier": "IAM_ALLOWED_PRINCIPALS"
                    },
                    "Permissions": [
                        "ALL"
                    ]
                }
            ],
            "CatalogId": "111122223333"
        },
        {
            "Name": "legislators",
            "CreateTime": 1601415625.0,
            "CreateTableDefaultPermissions": [
                {
                    "Principal": {
                        "DataLakePrincipalIdentifier": "IAM_ALLOWED_PRINCIPALS"
                    },
                    "Permissions": [
                        "ALL"
                    ]
                }
            ],
            "CatalogId": "111122223333"
        },
        {
            "Name": "tempdb",
            "CreateTime": 1601498566.0,
            "CreateTableDefaultPermissions": [
                {
                    "Principal": {
                        "DataLakePrincipalIdentifier": "IAM_ALLOWED_PRINCIPALS"
                    },
                    "Permissions": [
                        "ALL"
                    ]
                }
            ],
            "CatalogId": "111122223333"
        }
    ]
}
```
詳細については、*AWS Glue デベロッパーガイド* の「[データカタログにデータベースを定義する](https://docs.aws.amazon.com/glue/latest/dg/define-database.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[GetDatabases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-databases.html)」を参照してください。

### `get-job-run`
<a name="glue_GetJobRun_cli_2_topic"></a>

次のコード例は、`get-job-run` を使用する方法を示しています。

**AWS CLI**  
**ジョブの実行に関する情報を取得するには**  
次の `get-job-run` の例では、ジョブ実行に関する情報を取得します。　  

```
aws glue get-job-run \
    --job-name "Combine legistators data" \
    --run-id jr_012e176506505074d94d761755e5c62538ee1aad6f17d39f527e9140cf0c9a5e
```
出力:  

```
{
    "JobRun": {
        "Id": "jr_012e176506505074d94d761755e5c62538ee1aad6f17d39f527e9140cf0c9a5e",
        "Attempt": 0,
        "JobName": "Combine legistators data",
        "StartedOn": 1602873931.255,
        "LastModifiedOn": 1602874075.985,
        "CompletedOn": 1602874075.985,
        "JobRunState": "SUCCEEDED",
        "Arguments": {
            "--enable-continuous-cloudwatch-log": "true",
            "--enable-metrics": "",
            "--enable-spark-ui": "true",
            "--job-bookmark-option": "job-bookmark-enable",
            "--spark-event-logs-path": "s3://aws-glue-assets-111122223333-us-east-1/sparkHistoryLogs/"
        },
        "PredecessorRuns": [],
        "AllocatedCapacity": 10,
        "ExecutionTime": 117,
        "Timeout": 2880,
        "MaxCapacity": 10.0,
        "WorkerType": "G.1X",
        "NumberOfWorkers": 10,
        "LogGroupName": "/aws-glue/jobs",
        "GlueVersion": "2.0"
    }
}
```
詳細については、*AWS Glue デベロッパーガイド* の「[ジョブの実行](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[GetJobRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-job-run.html)」を参照してください。

### `get-job-runs`
<a name="glue_GetJobRuns_cli_2_topic"></a>

次のコード例は、`get-job-runs` を使用する方法を示しています。

**AWS CLI**  
**ジョブのすべてのジョブ実行に関する情報を取得するには**  
次の `get-job-runs` の例では、ジョブのジョブ実行に関する情報を取得します。  

```
aws glue get-job-runs \
    --job-name "my-testing-job"
```
出力:  

```
{
    "JobRuns": [
        {
            "Id": "jr_012e176506505074d94d761755e5c62538ee1aad6f17d39f527e9140cf0c9a5e",
            "Attempt": 0,
            "JobName": "my-testing-job",
            "StartedOn": 1602873931.255,
            "LastModifiedOn": 1602874075.985,
            "CompletedOn": 1602874075.985,
            "JobRunState": "SUCCEEDED",
            "Arguments": {
                "--enable-continuous-cloudwatch-log": "true",
                "--enable-metrics": "",
                "--enable-spark-ui": "true",
                "--job-bookmark-option": "job-bookmark-enable",
                "--spark-event-logs-path": "s3://aws-glue-assets-111122223333-us-east-1/sparkHistoryLogs/"
            },
            "PredecessorRuns": [],
            "AllocatedCapacity": 10,
            "ExecutionTime": 117,
            "Timeout": 2880,
            "MaxCapacity": 10.0,
            "WorkerType": "G.1X",
            "NumberOfWorkers": 10,
            "LogGroupName": "/aws-glue/jobs",
            "GlueVersion": "2.0"
        },
        {
            "Id": "jr_03cc19ddab11c4e244d3f735567de74ff93b0b3ef468a713ffe73e53d1aec08f_attempt_2",
            "Attempt": 2,
            "PreviousRunId": "jr_03cc19ddab11c4e244d3f735567de74ff93b0b3ef468a713ffe73e53d1aec08f_attempt_1",
            "JobName": "my-testing-job",
            "StartedOn": 1602811168.496,
            "LastModifiedOn": 1602811282.39,
            "CompletedOn": 1602811282.39,
            "JobRunState": "FAILED",
            "ErrorMessage": "An error occurred while calling o122.pyWriteDynamicFrame.
                Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied;
                Request ID: 021AAB703DB20A2D;
                S3 Extended Request ID: teZk24Y09TkXzBvMPG502L5VJBhe9DJuWA9/TXtuGOqfByajkfL/Tlqt5JBGdEGpigAqzdMDM/U=)",
            "PredecessorRuns": [],
            "AllocatedCapacity": 10,
            "ExecutionTime": 110,
            "Timeout": 2880,
            "MaxCapacity": 10.0,
            "WorkerType": "G.1X",
            "NumberOfWorkers": 10,
            "LogGroupName": "/aws-glue/jobs",
            "GlueVersion": "2.0"
        },
        {
            "Id": "jr_03cc19ddab11c4e244d3f735567de74ff93b0b3ef468a713ffe73e53d1aec08f_attempt_1",
            "Attempt": 1,
            "PreviousRunId": "jr_03cc19ddab11c4e244d3f735567de74ff93b0b3ef468a713ffe73e53d1aec08f",
            "JobName": "my-testing-job",
            "StartedOn": 1602811020.518,
            "LastModifiedOn": 1602811138.364,
            "CompletedOn": 1602811138.364,
            "JobRunState": "FAILED",
            "ErrorMessage": "An error occurred while calling o122.pyWriteDynamicFrame.
                 Access Denied (Service: Amazon S3; Status Code: 403; Error Code: AccessDenied;
                 Request ID: 2671D37856AE7ABB;
                 S3 Extended Request ID: RLJCJw20brV+PpC6GpORahyF2fp9flB5SSb2bTGPnUSPVizLXRl1PN3QZldb+v1o9qRVktNYbW8=)",
            "PredecessorRuns": [],
            "AllocatedCapacity": 10,
            "ExecutionTime": 113,
            "Timeout": 2880,
            "MaxCapacity": 10.0,
            "WorkerType": "G.1X",
            "NumberOfWorkers": 10,
            "LogGroupName": "/aws-glue/jobs",
            "GlueVersion": "2.0"
        }
    ]
}
```
詳細については、*AWS Glue デベロッパーガイド* の「[ジョブの実行](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-runs.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[GetJobRuns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-job-runs.html)」を参照してください。

### `get-job`
<a name="glue_GetJob_cli_2_topic"></a>

次のコード例は、`get-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブに関する情報を取得するには**  
次の `get-job` の例では、ジョブに関する情報を取得します。　  

```
aws glue get-job \
    --job-name my-testing-job
```
出力:  

```
{
    "Job": {
        "Name": "my-testing-job",
        "Role": "Glue_DefaultRole",
        "CreatedOn": 1602805698.167,
        "LastModifiedOn": 1602805698.167,
        "ExecutionProperty": {
            "MaxConcurrentRuns": 1
        },
        "Command": {
            "Name": "gluestreaming",
            "ScriptLocation": "s3://janetst-bucket-01/Scripts/test_script.scala",
            "PythonVersion": "2"
        },
        "DefaultArguments": {
            "--class": "GlueApp",
            "--job-language": "scala"
        },
        "MaxRetries": 0,
        "AllocatedCapacity": 10,
        "MaxCapacity": 10.0,
        "GlueVersion": "1.0"
    }
}
```
詳細については、*AWS Glue デベロッパーガイド* の「[ジョブ](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[GetJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-job.html)」を参照してください。

### `get-plan`
<a name="glue_GetPlan_cli_2_topic"></a>

次のコード例は、`get-plan` を使用する方法を示しています。

**AWS CLI**  
**ソーステーブルからターゲットテーブルにデータをマッピングするために生成されたコードを取得するには**  
次の `get-plan` は、データソースからデータターゲットに列をマッピングするために生成されたコードを取得します。  

```
aws glue get-plan --mapping '[ \
    { \
        "SourcePath":"sensorid", \
        "SourceTable":"anything", \
        "SourceType":"int", \
        "TargetPath":"sensorid", \
        "TargetTable":"anything", \
        "TargetType":"int" \
    }, \
    { \
        "SourcePath":"currenttemperature", \
        "SourceTable":"anything", \
        "SourceType":"int", \
        "TargetPath":"currenttemperature", \
        "TargetTable":"anything", \
        "TargetType":"int" \
    }, \
    { \
        "SourcePath":"status", \
        "SourceTable":"anything", \
        "SourceType":"string", \
        "TargetPath":"status", \
        "TargetTable":"anything", \
        "TargetType":"string" \
    }]' \
    --source '{ \
        "DatabaseName":"tempdb", \
        "TableName":"s3-source" \
    }' \
    --sinks '[ \
        { \
            "DatabaseName":"tempdb", \
            "TableName":"my-s3-sink" \
        }]'
    --language "scala"
    --endpoint https://glue.us-east-1.amazonaws.com
    --output "text"
```
出力:  

```
import com.amazonaws.services.glue.ChoiceOption
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.MappingSpec
import com.amazonaws.services.glue.ResolveSpec
import com.amazonaws.services.glue.errors.CallSite
import com.amazonaws.services.glue.util.GlueArgParser
import com.amazonaws.services.glue.util.Job
import com.amazonaws.services.glue.util.JsonOptions
import org.apache.spark.SparkContext
import scala.collection.JavaConverters._

object GlueApp {
  def main(sysArgs: Array[String]) {
    val spark: SparkContext = new SparkContext()
    val glueContext: GlueContext = new GlueContext(spark)
    // @params: [JOB_NAME]
    val args = GlueArgParser.getResolvedOptions(sysArgs, Seq("JOB_NAME").toArray)
    Job.init(args("JOB_NAME"), glueContext, args.asJava)
    // @type: DataSource
    // @args: [database = "tempdb", table_name = "s3-source", transformation_ctx = "datasource0"]
    // @return: datasource0
    // @inputs: []
    val datasource0 = glueContext.getCatalogSource(database = "tempdb", tableName = "s3-source", redshiftTmpDir = "", transformationContext = "datasource0").getDynamicFrame()
    // @type: ApplyMapping
    // @args: [mapping = [("sensorid", "int", "sensorid", "int"), ("currenttemperature", "int", "currenttemperature", "int"), ("status", "string", "status", "string")], transformation_ctx = "applymapping1"]
    // @return: applymapping1
    // @inputs: [frame = datasource0]
    val applymapping1 = datasource0.applyMapping(mappings = Seq(("sensorid", "int", "sensorid", "int"), ("currenttemperature", "int", "currenttemperature", "int"), ("status", "string", "status", "string")), caseSensitive = false, transformationContext = "applymapping1")
    // @type: SelectFields
    // @args: [paths = ["sensorid", "currenttemperature", "status"], transformation_ctx = "selectfields2"]
    // @return: selectfields2
    // @inputs: [frame = applymapping1]
    val selectfields2 = applymapping1.selectFields(paths = Seq("sensorid", "currenttemperature", "status"), transformationContext = "selectfields2")
    // @type: ResolveChoice
    // @args: [choice = "MATCH_CATALOG", database = "tempdb", table_name = "my-s3-sink", transformation_ctx = "resolvechoice3"]
    // @return: resolvechoice3
    // @inputs: [frame = selectfields2]
    val resolvechoice3 = selectfields2.resolveChoice(choiceOption = Some(ChoiceOption("MATCH_CATALOG")), database = Some("tempdb"), tableName = Some("my-s3-sink"), transformationContext = "resolvechoice3")
    // @type: DataSink
    // @args: [database = "tempdb", table_name = "my-s3-sink", transformation_ctx = "datasink4"]
    // @return: datasink4
    // @inputs: [frame = resolvechoice3]
    val datasink4 = glueContext.getCatalogSink(database = "tempdb", tableName = "my-s3-sink", redshiftTmpDir = "", transformationContext = "datasink4").writeDynamicFrame(resolvechoice3)
    Job.commit()
  }
}
```
詳細については、[AWS 「 Glue デベロッパーガイド」の「 Glue でのスクリプトの編集](https://docs.aws.amazon.com/glue/latest/dg/edit-script.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-plan.html)」を参照してください。

### `get-tables`
<a name="glue_GetTables_cli_2_topic"></a>

次のコード例は、`get-tables` を使用する方法を示しています。

**AWS CLI**  
**指定されたデータベース内で、一部またはすべてのテーブルの定義を一覧表示するには**  
次の `get-tables` の例では、指定されたデータベース内のテーブルに関する情報を返します。  

```
aws glue get-tables --database-name 'tempdb'
```
出力:  

```
{
    "TableList": [
        {
            "Name": "my-s3-sink",
            "DatabaseName": "tempdb",
            "CreateTime": 1602730539.0,
            "UpdateTime": 1602730539.0,
            "Retention": 0,
            "StorageDescriptor": {
                "Columns": [
                    {
                        "Name": "sensorid",
                        "Type": "int"
                    },
                    {
                        "Name": "currenttemperature",
                        "Type": "int"
                    },
                    {
                        "Name": "status",
                        "Type": "string"
                    }
                ],
                "Location": "s3://janetst-bucket-01/test-s3-output/",
                "Compressed": false,
                "NumberOfBuckets": 0,
                "SerdeInfo": {
                    "SerializationLibrary": "org.openx.data.jsonserde.JsonSerDe"
                },
                "SortColumns": [],
                "StoredAsSubDirectories": false
            },
            "Parameters": {
                "classification": "json"
            },
            "CreatedBy": "arn:aws:iam::007436865787:user/JRSTERN",
            "IsRegisteredWithLakeFormation": false,
            "CatalogId": "007436865787"
        },
        {
            "Name": "s3-source",
            "DatabaseName": "tempdb",
            "CreateTime": 1602730658.0,
            "UpdateTime": 1602730658.0,
            "Retention": 0,
            "StorageDescriptor": {
                "Columns": [
                    {
                        "Name": "sensorid",
                        "Type": "int"
                    },
                    {
                        "Name": "currenttemperature",
                        "Type": "int"
                    },
                    {
                        "Name": "status",
                        "Type": "string"
                    }
                ],
                "Location": "s3://janetst-bucket-01/",
                "Compressed": false,
                "NumberOfBuckets": 0,
                "SortColumns": [],
                "StoredAsSubDirectories": false
            },
            "Parameters": {
                "classification": "json"
            },
            "CreatedBy": "arn:aws:iam::007436865787:user/JRSTERN",
            "IsRegisteredWithLakeFormation": false,
            "CatalogId": "007436865787"
        },
        {
            "Name": "test-kinesis-input",
            "DatabaseName": "tempdb",
            "CreateTime": 1601507001.0,
            "UpdateTime": 1601507001.0,
            "Retention": 0,
            "StorageDescriptor": {
                "Columns": [
                    {
                        "Name": "sensorid",
                        "Type": "int"
                    },
                    {
                        "Name": "currenttemperature",
                        "Type": "int"
                    },
                    {
                        "Name": "status",
                        "Type": "string"
                    }
                ],
                "Location": "my-testing-stream",
                "Compressed": false,
                "NumberOfBuckets": 0,
                "SerdeInfo": {
                    "SerializationLibrary": "org.openx.data.jsonserde.JsonSerDe"
                },
                "SortColumns": [],
                "Parameters": {
                    "kinesisUrl": "https://kinesis.us-east-1.amazonaws.com",
                    "streamName": "my-testing-stream",
                    "typeOfData": "kinesis"
                },
                "StoredAsSubDirectories": false
            },
            "Parameters": {
                "classification": "json"
            },
            "CreatedBy": "arn:aws:iam::007436865787:user/JRSTERN",
            "IsRegisteredWithLakeFormation": false,
            "CatalogId": "007436865787"
        }
    ]
}
```
詳細については、[「 AWS Glue デベロッパーガイド」の「 Glue データカタログのテーブルの定義](https://docs.aws.amazon.com/glue/latest/dg/tables-described.html)」を参照してください。 *AWS *  
+  API の詳細については、*AWS CLI  コマンドリファレンス* の「[GetTables](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/get-tables.html)」を参照してください。

### `start-crawler`
<a name="glue_StartCrawler_cli_2_topic"></a>

次のコード例は、`start-crawler` を使用する方法を示しています。

**AWS CLI**  
**クローラーを開始するには**  
次の `start-crawler` の例では、クローラーを開始します。  

```
aws glue start-crawler --name my-crawler
```
出力:  

```
None
```
詳細については、*AWS Glue デベロッパーガイド* の「[クローラーの定義](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[StartCrawler](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/start-crawler.html)」を参照してください。

### `start-job-run`
<a name="glue_StartJobRun_cli_2_topic"></a>

次のコード例は、`start-job-run` を使用する方法を示しています。

**AWS CLI**  
**ジョブの実行を開始するには**　  
次の `start-job-run` の例ではジョブを開始します。  

```
aws glue start-job-run \
    --job-name my-job
```
出力:  

```
{
    "JobRunId": "jr_22208b1f44eb5376a60569d4b21dd20fcb8621e1a366b4e7b2494af764b82ded"
}
```
詳細については、*AWS Glue デベロッパーガイド* の「[ジョブの作成](https://docs.aws.amazon.com/glue/latest/dg/author-job.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[StartJobRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/glue/start-job-run.html)」を参照してください。

# を使用した GuardDuty の例 AWS CLI
<a name="cli_2_guardduty_code_examples"></a>

次のコード例は、GuardDuty AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-invitation`
<a name="guardduty_AcceptInvitation_cli_2_topic"></a>

次のコード例は、`accept-invitation` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンで GuardDuty メンバーアカウントになるための招待を受け入れるには**  
次の `accept-invitation` の例は、現在のリージョンで GuardDuty メンバーアカウントになるための招待を受け入れる方法を示しています。  

```
aws guardduty accept-invitation  \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --master-id 123456789111 \
    --invitation-id d6b94fb03a66ff665f7db8764example
```
このコマンドでは何も出力されません。  
詳細については、「GuardDuty ユーザーガイド」の「[招待による GuardDuty アカウントの管理](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_invitations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptInvitation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/accept-invitation.html)」を参照してください。

### `archive-findings`
<a name="guardduty_ArchiveFindings_cli_2_topic"></a>

次のコード例は、`archive-findings` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンで検出結果をアーカイブするには**  
この `archive-findings` の例では、現在のリージョンで検出結果をアーカイブする方法を示します。  

```
aws guardduty archive-findings \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --finding-ids d6b94fb03a66ff665f7db8764example 3eb970e0de00c16ec14e6910fexample
```
このコマンドでは何も出力されません。  
詳細については、*GuardDuty ユーザーガイド*の「[抑制ルールの作成](https://docs.aws.amazon.com/guardduty/latest/ug/findings_suppression-rules-console.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ArchiveFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/archive-findings.html)」を参照してください。

### `create-detector`
<a name="guardduty_CreateDetector_cli_2_topic"></a>

次のコード例は、`create-detector` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンで GuardDuty を有効にするには**  
この例では、現在のリージョンで GuardDuty を有効にする新しいディテクターを作成する方法を示しています。  

```
aws guardduty create-detector \
    --enable
```
出力:  

```
{
    "DetectorId": "b6b992d6d2f48e64bc59180bfexample"
}
```
詳細については、「*GuardDuty ユーザーガイド*」の「[Amazon GuardDuty を有効にする](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_settingup.html#guardduty_enable-gd)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/create-detector.html)」を参照してください。

### `create-filter`
<a name="guardduty_CreateFilter_cli_2_topic"></a>

次のコード例は、`create-filter` を使用する方法を示しています。

**AWS CLI**  
**例 1: 現在のリージョンに新しいフィルタを作成するには**  
次の `create-filter` の例では、特定のイメージから作成されたインスタンスのすべての Portscan 検出結果に一致するフィルタを作成します。このフィルタは、これらの検出結果を抑制するものではありません。  

```
aws guardduty create-filter \
    --detector-id b6b992d6d2f48e64bc59180bfexample \
    --name myFilterExample \
    --finding-criteria '{"Criterion": {"type": {"Eq": ["Recon:EC2/Portscan"]},"resource.instanceDetails.imageId": {"Eq": ["ami-0a7a207083example"]}}}'
```
出力:  

```
{
    "Name": "myFilterExample"
}
```
詳細については、*GuardDuty ユーザーガイド*の「[GuardDuty 検出結果のフィルタリング](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_filter-findings.html)」を参照してください。  
**例 2: 現在のリージョンで新しいフィルタを作成し、検出結果を抑制するには**  
次の `create-filter` の例では、特定のイメージから作成されたインスタンスのすべての Portscan 検出結果に一致するフィルタを作成します。このフィルタは、これらの検出結果をアーカイブして、現在の検出結果に表示されないようにします。  

```
aws guardduty create-filter \
    --detector-id b6b992d6d2f48e64bc59180bfexample \
    --action ARCHIVE \
    --name myFilterSecondExample \
    --finding-criteria '{"Criterion": {"type": {"Eq": ["Recon:EC2/Portscan"]},"resource.instanceDetails.imageId": {"Eq": ["ami-0a7a207083example"]}}}'
```
出力:  

```
{
    "Name": "myFilterSecondExample"
}
```
詳細については、*GuardDuty ユーザーガイド*の「[GuardDuty 検出結果のフィルタリング](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_filter-findings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/create-filter.html)」を参照してください。

### `create-ip-set`
<a name="guardduty_CreateIpSet_cli_2_topic"></a>

次のコード例は、`create-ip-set` を使用する方法を示しています。

**AWS CLI**  
**信頼された IP セットを作成して有効化するには**  
次の `create-ip-set` の例では、現在のリージョンで信頼された IP セットを作成して有効化します。  

```
aws guardduty create-ip-set \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --name new-ip-set-example \
    --format TXT \
    --location s3://amzn-s3-demo-bucket/customtrustlist.csv \
    --activate
```
出力:  

```
{
    "IpSetId": "d4b94fc952d6912b8f3060768example"
}
```
詳細については、*GuardDuty ユーザーガイド*の「[信頼された IP リストと脅威リストの使用](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload_lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/create-ip-set.html)」を参照してください。

### `create-members`
<a name="guardduty_CreateMembers_cli_2_topic"></a>

次のコード例は、`create-members` を使用する方法を示しています。

**AWS CLI**  
**新しいメンバーを現在のリージョンの GuardDuty マスターアカウントに関連付けるには**  
この例では、現在のアカウントが管理するメンバーアカウントを GuardDuty マスターとして関連付ける方法を示します。  

```
aws guardduty create-members
    --detector-id b6b992d6d2f48e64bc59180bfexample \
    --account-details AccountId=111122223333,Email=first+member@example.com AccountId=111111111111 ,Email=another+member@example.com
```
出力:  

```
{
   "UnprocessedAccounts": []
}
```
詳細については、「GuardDuty ユーザーガイド」の「[複数のアカウントを管理する](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/create-members.html)」を参照してください。

### `create-publishing-destination`
<a name="guardduty_CreatePublishingDestination_cli_2_topic"></a>

次のコード例は、`create-publishing-destination` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンの GuardDuty 検出結果をエクスポートする発行先を作成するには**  
次の `create-publishing-destination` の例では、現在の (アーカイブされていない) GuardDuty の検索結果をエクスポートして、過去の検索結果データを追跡するための、発行先を設定する方法を示します。  

```
aws guardduty create-publishing-destination \
    --detector-id b6b992d6d2f48e64bc59180bfexample \
    --destination-type S3 \
    --destination-properties 'DestinationArn=arn:aws:s3:::amzn-s3-demo-bucket,KmsKeyArn=arn:aws:kms:us-west-1:111122223333:key/84cee9c5-dea1-401a-ab6d-e1de7example'
```
出力:  

```
{
    "DestinationId": "46b99823849e1bbc242dfbe3cexample"
}
```
詳細については、*GuardDuty ユーザーガイド*の「[生成された GuardDuty 検出結果を Amazon S3 バケットにエクスポートする](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_exportfindings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePublishingDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/create-publishing-destination.html)」を参照してください。

### `create-sample-findings`
<a name="guardduty_CreateSampleFindings_cli_2_topic"></a>

次のコード例は、`create-sample-findings` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンでサンプルの GuardDuty 検出結果を作成するには**  
この例では、指定されたタイプのサンプル検出結果を作成する方法を示します。  

```
aws guardduty create-sample-findings \
    --detector-id b6b992d6d2f48e64bc59180bfexample \
    --finding-types UnauthorizedAccess:EC2/TorClient UnauthorizedAccess:EC2/TorRelay
```
このコマンドでは何も出力されません。  
詳細については、「*GuardDuty ユーザーガイド*」の「[サンプルも検出結果](https://docs.aws.amazon.com/guardduty/latest/ug/sample_findings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSampleFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/create-sample-findings.html)」を参照してください。

### `create-threat-intel-set`
<a name="guardduty_CreateThreatIntelSet_cli_2_topic"></a>

次のコード例は、`create-threat-intel-set` を使用する方法を示しています。

**AWS CLI**  
**新しい脅威インテリジェンスセットを作成して有効化するには**  
次の `create-threat-intel-set` の例では、現在のリージョンで脅威インテリジェンスセットを作成して有効化します。  

```
aws guardduty create-threat-intel-set \
    --detector-id b6b992d6d2f48e64bc59180bfexample \
    --name myThreatSet-example \
    --format TXT \
    --location s3://amzn-s3-demo-bucket/threatlist.csv \
    --activate
```
出力:  

```
{
    "ThreatIntelSetId": "20b9a4691aeb33506b808878cexample"
}
```
詳細については、*GuardDuty ユーザーガイド*の「[信頼された IP リストと脅威リストの使用](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload_lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateThreatIntelSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/create-threat-intel-set.html)」を参照してください。

### `decline-invitations`
<a name="guardduty_DeclineInvitations_cli_2_topic"></a>

次のコード例は、`decline-invitations` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンの別のアカウントによって Guardduty が管理される招待を拒否するには**  
この例では、メンバーシップの招待を拒否する方法を示しています。  

```
aws guardduty decline-invitations \
    --account-ids 111122223333
```
出力:  

```
{
    "UnprocessedAccounts": []
}
```
詳細については、「GuardDuty ユーザーガイド」の「[招待による GuardDuty アカウントの管理](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_invitations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeclineInvitations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/decline-invitations.html)」を参照してください。

### `delete-detector`
<a name="guardduty_DeleteDetector_cli_2_topic"></a>

次のコード例は、`delete-detector` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンでディテクターを削除し、GuardDuty を無効にするには**  
この例では、ディテクターを削除する方法を示しています。成功すると、そのディテクターに関連付けられたリージョンで GuardDuty が無効になります。  

```
aws guardduty delete-detector \
    --detector-id b6b992d6d2f48e64bc59180bfexample
```
このコマンドでは何も出力されません。  
詳細については、「*GuardDuty ユーザーガイド*」の「[GuardDuty の一時停止または無効化](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_suspend-disable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/delete-detector.html)」を参照してください。

### `delete-filter`
<a name="guardduty_DeleteFilter_cli_2_topic"></a>

次のコード例は、`delete-filter` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンの既存のフィルターを削除するには**  
この例では、フィルターを削除する方法を示します。  

```
aws guardduty delete-filter \
    --detector-id b6b992d6d2f48e64bc59180bfexample \
    --filter-name byebyeFilter
```
このコマンドでは何も出力されません。  
詳細については、「GuardDuty ユーザーガイド」の「[検出結果のフィルタリング](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_filter-findings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/delete-filter.html)」を参照してください。

### `disable-organization-admin-account`
<a name="guardduty_DisableOrganizationAdminAccount_cli_2_topic"></a>

次のコード例は、`disable-organization-admin-account` を使用する方法を示しています。

**AWS CLI**  
**組織内の GuardDuty の委任管理者としてアカウントを削除するには**  
この例では、GuardDuty の委任管理者としてアカウントを削除する方法を示します。  

```
aws guardduty disable-organization-admin-account \
    --admin-account-id 111122223333
```
このコマンドでは何も出力されません。  
詳細については、*GuardDuty ユーザーガイド*」の[AWS 「組織でのアカウントの管理](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_organizations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableOrganizationAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/disable-organization-admin-account.html)」を参照してください。

### `disassociate-from-master-account`
<a name="guardduty_DisassociateFromMasterAccount_cli_2_topic"></a>

次のコード例は、`disassociate-from-master-account` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンの現在の管理者アカウントとの関連付けを解除するには**  
次の の`disassociate-from-master-account`例では、現在の AWS リージョンの現在の GuardDuty 管理者アカウントからアカウントの関連付けを解除します。  

```
aws guardduty disassociate-from-master-account \
    --detector-id d4b040365221be2b54a6264dcexample
```
このコマンドでは何も出力されません。  
詳細については、*GuardDuty ユーザーガイド*の「[GuardDuty 管理者アカウントとメンバーアカウントの関係について理解する](https://docs.aws.amazon.com/guardduty/latest/ug/administrator_member_relationships.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateFromMasterAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/disassociate-from-master-account.html)」を参照してください。

### `get-detector`
<a name="guardduty_GetDetector_cli_2_topic"></a>

次のコード例は、`get-detector` を使用する方法を示しています。

**AWS CLI**  
**特定のディテクターの詳細を取得するには**  
次の `get-detector` の例では、指定されたディテクターの設定の詳細を表示します。  

```
aws guardduty get-detector \
    --detector-id 12abc34d567e8fa901bc2d34eexample
```
出力:  

```
{
    "Status": "ENABLED",
    "ServiceRole": "arn:aws:iam::111122223333:role/aws-service-role/guardduty.amazonaws.com/AWSServiceRoleForAmazonGuardDuty",
    "Tags": {},
    "FindingPublishingFrequency": "SIX_HOURS",
    "UpdatedAt": "2018-11-07T03:24:22.938Z",
    "CreatedAt": "2017-12-22T22:51:31.940Z"
}
```
詳細については、GuardDuty ユーザーガイドの「[概念と用語](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_concepts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/get-detector.html)」を参照してください。

### `get-findings`
<a name="guardduty_GetFindings_cli_2_topic"></a>

次のコード例は、`get-findings` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定の検出結果の詳細を取得するには**  
次の `get-findings` の例では、指定された検出結果の完全な JSON 検出結果の詳細を取得します。  

```
aws guardduty get-findings \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --finding-id 1ab92989eaf0e742df4a014d5example
```
出力:  

```
{
    "Findings": [
        {
            "Resource": {
                "ResourceType": "AccessKey",
                "AccessKeyDetails": {
                    "UserName": "testuser",
                    "UserType": "IAMUser",
                    "PrincipalId": "AIDACKCEVSQ6C2EXAMPLE",
                    "AccessKeyId": "ASIASZ4SI7REEEXAMPLE"
                }
            },
            "Description": "APIs commonly used to discover the users, groups, policies and permissions in an account, was invoked by IAM principal testuser under unusual circumstances. Such activity is not typically seen from this principal.",
            "Service": {
                "Count": 5,
                "Archived": false,
                "ServiceName": "guardduty",
                "EventFirstSeen": "2020-05-26T22:02:24Z",
                "ResourceRole": "TARGET",
                "EventLastSeen": "2020-05-26T22:33:55Z",
                "DetectorId": "d4b040365221be2b54a6264dcexample",
                "Action": {
                    "ActionType": "AWS_API_CALL",
                    "AwsApiCallAction": {
                        "RemoteIpDetails": {
                            "GeoLocation": {
                                "Lat": 51.5164,
                                "Lon": -0.093
                            },
                            "City": {
                                "CityName": "London"
                            },
                            "IpAddressV4": "52.94.36.7",
                            "Organization": {
                                "Org": "Amazon.com",
                                "Isp": "Amazon.com",
                                "Asn": "16509",
                                "AsnOrg": "AMAZON-02"
                            },
                            "Country": {
                                "CountryName": "United Kingdom"
                            }
                        },
                        "Api": "ListPolicyVersions",
                        "ServiceName": "iam.amazonaws.com",
                        "CallerType": "Remote IP"
                    }
                }
            },
            "Title": "Unusual user permission reconnaissance activity by testuser.",
            "Type": "Recon:IAMUser/UserPermissions",
            "Region": "us-east-1",
            "Partition": "aws",
            "Arn": "arn:aws:guardduty:us-east-1:111122223333:detector/d4b040365221be2b54a6264dcexample/finding/1ab92989eaf0e742df4a014d5example",
            "UpdatedAt": "2020-05-26T22:55:21.703Z",
            "SchemaVersion": "2.0",
            "Severity": 5,
            "Id": "1ab92989eaf0e742df4a014d5example",
            "CreatedAt": "2020-05-26T22:21:48.385Z",
            "AccountId": "111122223333"
        }
    ]
}
```
詳細については、「GuardDuty ユーザーガイド」の「[検出結果](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/get-findings.html)」を参照してください。

### `get-ip-set`
<a name="guardduty_GetIpSet_cli_2_topic"></a>

次のコード例は、`get-ip-set` を使用する方法を示しています。

**AWS CLI**  
**指定された信頼された IP セットの詳細を一覧表示するには**  
次の `get-ip-set` の例では、指定した信頼された IP セットのステータスと詳細を表示します。  

```
aws guardduty get-ip-set \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --ip-set-id d4b94fc952d6912b8f3060768example
```
出力:  

```
{
    "Status": "ACTIVE",
    "Location": "s3://amzn-s3-demo-bucket.s3-us-west-2.amazonaws.com/customlist.csv",
    "Tags": {},
    "Format": "TXT",
    "Name": "test-ip-set-example"
}
```
詳細については、*GuardDuty ユーザーガイド*の「[信頼された IP リストと脅威リストの使用](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload_lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/get-ip-set.html)」を参照してください。

### `get-master-account`
<a name="guardduty_GetMasterAccount_cli_2_topic"></a>

次のコード例は、`get-master-account` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンでマスターアカウントに関する詳細を取得するには**  
次の `get-master-account` の例では、現在のリージョンのディテクターに関連付けられたマスターアカウントのステータスと詳細を表示します。  

```
aws guardduty get-master-account \
    --detector-id 12abc34d567e8fa901bc2d34eexample
```
出力:  

```
{
    "Master": {
        "InvitationId": "04b94d9704854a73f94e061e8example",
        "InvitedAt": "2020-06-09T22:23:04.970Z",
        "RelationshipStatus": "Enabled",
        "AccountId": "111122223333"
    }
}
```
詳細については、*GuardDuty ユーザーガイド*の「[GuardDuty 管理者アカウントとメンバーアカウントの関係について理解する](https://docs.aws.amazon.com/guardduty/latest/ug/administrator_member_relationships.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMasterAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/get-master-account.html)」を参照してください。

### `list-detectors`
<a name="guardduty_ListDetectors_cli_2_topic"></a>

次のコード例は、`list-detectors` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンで使用可能なディテクターを一覧表示するには**  
次の の`list-detectors`例では、現在の AWS リージョンで使用可能なディテクターを一覧表示します。  

```
aws guardduty list-detectors
```
出力:  

```
{
    "DetectorIds": [
        "12abc34d567e8fa901bc2d34eexample"
    ]
}
```
詳細については、GuardDuty ユーザーガイドの「[概念と用語](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_concepts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDetectors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/list-detectors.html)」を参照してください。

### `list-findings`
<a name="guardduty_ListFindings_cli_2_topic"></a>

次のコード例は、`list-findings` を使用する方法を示しています。

**AWS CLI**  
**例 1: 現在のリージョンのすべての検出結果を一覧表示するには**  
次の `list-findings` の例では、現在のリージョンのすべての findingIds のリストを重要度の高いものから低いものの順に表示します。  

```
aws guardduty list-findings \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --sort-criteria '{"AttributeName": "severity","OrderBy":"DESC"}'
```
出力:  

```
{
    "FindingIds": [
        "04b8ab50fd29c64fc771b232dexample",
        "5ab8ab50fd21373735c826d3aexample",
        "90b93de7aba69107f05bbe60bexample",
        ...
    ]
}
```
詳細については、「GuardDuty ユーザーガイド」の「[検出結果](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html)」を参照してください。  
**例 2: 特定の検出結果基準に一致する現在のリージョンの検出結果を一覧表示するには**  
次の `list-findings` の例では、指定された findingIds のリストを表示します。  

```
aws guardduty list-findings \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --finding-criteria  '{"Criterion":{"type": {"Eq":["UnauthorizedAccess:EC2/SSHBruteForce"]}}}'
```
出力:  

```
{
    "FindingIds": [
        "90b93de7aba69107f05bbe60bexample",
        "6eb9430d7023d30774d6f05e3example",
        "2eb91a2d060ac9a21963a5848example",
        "44b8ab50fd2b0039a9e48f570example",
        "9eb8ab4cd2b7e5b66ba4f5e96example",
        "e0b8ab3a38e9b0312cc390ceeexample"
    ]
}
```
詳細については、「GuardDuty ユーザーガイド」の「[検出結果](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html)」を参照してください。  
**例 3: JSON ファイル内で定義された特定の検出基準のセットに一致する現在のリージョンの検出結果を一覧表示するには**  
次の `list-findings` の例では、JSON ファイルで指定されているように、アーカイブされておらず、「testuser」という名前の IAM ユーザーを含む findingIds のリストを表示します。  

```
aws guardduty list-findings \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --finding-criteria  file://myfile.json
```
`myfile.json` の内容:  

```
{"Criterion": {
    "resource.accessKeyDetails.userName":{
                "Eq":[
                    "testuser"
                    ]
                },
    "service.archived": {
                "Eq": [
                    "false"
                ]
            }
        }
}
```
出力:  

```
{
    "FindingIds": [
        "1ab92989eaf0e742df4a014d5example"
    ]
}
```
詳細については、「GuardDuty ユーザーガイド」の「[検出結果](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_findings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/list-findings.html)」を参照してください。

### `list-invitations`
<a name="guardduty_ListInvitations_cli_2_topic"></a>

次のコード例は、`list-invitations` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンのメンバーアカウントになるための招待の詳細を一覧表示するには**  
次の `list-invitations` の例では、現在のリージョンで GuardDuty メンバーアカウントになるための招待の詳細とステータスを一覧表示します。  

```
aws guardduty list-invitations
```
出力:  

```
{
    "Invitations": [
        {
            "InvitationId": "d6b94fb03a66ff665f7db8764example",
            "InvitedAt": "2020-06-10T17:56:38.221Z",
            "RelationshipStatus": "Invited",
            "AccountId": "123456789111"
        }
    ]
}
```
詳細については、「GuardDuty ユーザーガイド」の「[招待による GuardDuty アカウントの管理](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_invitations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInvitations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/list-invitations.html)」を参照してください。

### `list-ip-sets`
<a name="guardduty_ListIpSets_cli_2_topic"></a>

次のコード例は、`list-ip-sets` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンで信頼された IP セットを一覧表示するには**  
次の の`list-ip-sets`例では、現在の AWS リージョンの信頼された IP セットを一覧表示します。  

```
aws guardduty list-ip-sets \
    --detector-id 12abc34d567e8fa901bc2d34eexample
```
出力:  

```
{
    "IpSetIds": [
        "d4b94fc952d6912b8f3060768example"
    ]
}
```
詳細については、「GuardDuty ユーザーガイド」の「[信頼された IP リストと脅威リストの使用](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload_lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIpSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/list-ip-sets.html)」を参照してください。

### `list-members`
<a name="guardduty_ListMembers_cli_2_topic"></a>

次のコード例は、`list-members` を使用する方法を示しています。

**AWS CLI**  
**例 1: 現在のリージョン内の現在のメンバーのみを一覧表示するには**  
次の `list-members` の例では、現在のリージョンで、GuardDuty 管理者アカウントに関連付けられている現在のメンバーアカウントのみを一覧表示し、詳細を出力します。  

```
aws guardduty list-members \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --only-associated="true"
```
出力:  

```
{
    "Members": [
        {
            "RelationshipStatus": "Enabled",
            "InvitedAt": "2020-06-09T22:49:00.910Z",
            "MasterId": "111122223333",
            "DetectorId": "7ab8b2f61b256c87f793f6a86example",
            "UpdatedAt": "2020-06-09T23:08:22.512Z",
            "Email": "your+member@example.com",
            "AccountId": "123456789012"
        }
    ]
}
```
詳細については、*GuardDuty ユーザーガイド*の「[GuardDuty 管理者アカウントとメンバーアカウントの関係について理解する](https://docs.aws.amazon.com/guardduty/latest/ug/administrator_member_relationships.html)」を参照してください。  
**例 2: 現在のリージョン内のすべてのメンバーを一覧表示するには**  
次の `list-members` の例では、現在のリージョンで、関連付けが解除されたメンバーや、GuardDuty 管理者からの招待をまだ承諾していないメンバーを含め、すべてのメンバーアカウントを一覧表示し、詳細を出力します。  

```
aws guardduty list-members \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --only-associated="false"
```
出力:  

```
{
    "Members": [
        {
            "RelationshipStatus": "Enabled",
            "InvitedAt": "2020-06-09T22:49:00.910Z",
            "MasterId": "111122223333",
            "DetectorId": "7ab8b2f61b256c87f793f6a86example",
            "UpdatedAt": "2020-06-09T23:08:22.512Z",
            "Email": "your+other+member@example.com",
            "AccountId": "555555555555"
        }
    ]
}
```
詳細については、*GuardDuty ユーザーガイド*の「[GuardDuty 管理者アカウントとメンバーアカウントの関係について理解する](https://docs.aws.amazon.com/guardduty/latest/ug/administrator_member_relationships.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/list-members.html)」を参照してください。

### `update-detector`
<a name="guardduty_UpdateDetector_cli_2_topic"></a>

次の例は、`update-detector` を使用する方法を説明しています。

**AWS CLI**  
**例 1: GuardDuty でランタイムモニタリングを有効にするには**  
次の `update-detector` の例では、追加の設定なしでランタイムモニタリングを有効にします。  

```
aws guardduty update-detector \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --features 'Name=RUNTIME_MONITORING,Status=ENABLED'
```
このコマンドでは何も出力されません。  
詳細については、「*GuardDuty ユーザーガイド*」の「[ランタイムモニタリング](https://docs.aws.amazon.com/guardduty/latest/ug/runtime-monitoring.html)」を参照してください。  
**例 2: 追加設定でランタイムモニタリングを有効にするには**  
次の `update-detector` の例では、EC2、ECS Fargate、および EKS の追加設定でランタイムモニタリングを有効にします。  

```
aws guardduty update-detector \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --features 'Name=RUNTIME_MONITORING,Status=ENABLED,AdditionalConfiguration=[{Name=EC2_AGENT_MANAGEMENT,Status=ENABLED},{Name=ECS_FARGATE_AGENT_MANAGEMENT,Status=ENABLED},{Name=EKS_ADDON_MANAGEMENT,Status=ENABLED}]'
```
このコマンドでは何も出力されません。  
詳細については、「*GuardDuty ユーザーガイド*」の「[ランタイムモニタリング](https://docs.aws.amazon.com/guardduty/latest/ug/runtime-monitoring.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/update-detector.html)」を参照してください。

### `update-ip-set`
<a name="guardduty_UpdateIpSet_cli_2_topic"></a>

次の例は、`update-ip-set` を使用する方法を説明しています。

**AWS CLI**  
**信頼された IP セットを更新するには**  
次の `update-ip-set` 例は、信頼された IP セットの詳細を更新する方法を示しています。  

```
aws guardduty update-ip-set \
    --detector-id 12abc34d567e8fa901bc2d34eexample \
    --ip-set-id d4b94fc952d6912b8f3060768example \
    --location https://amzn-s3-demo-bucket.s3-us-west-2.amazonaws.com/customtrustlist2.csv
```
このコマンドでは何も出力されません。  
詳細については、*GuardDuty ユーザーガイド*の「[信頼された IP リストと脅威リストの使用](https://docs.aws.amazon.com/guardduty/latest/ug/guardduty_upload_lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/update-ip-set.html)」を参照してください。

# AWS Health を使用した の例 AWS CLI
<a name="cli_2_health_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Health。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-affected-entities`
<a name="health_DescribeAffectedEntities_cli_2_topic"></a>

次の例は、`describe-affected-entities` を使用する方法を説明しています。

**AWS CLI**  
**指定された AWS Health イベントの影響を受けるエンティティを一覧表示するには**  
次の の`describe-affected-entities`例では、指定された AWS Health イベントの影響を受けるエンティティを一覧表示します。このイベントは、 AWS アカウントの請求通知です。  

```
aws health describe-affected-entities \
    --filter "eventArns=arn:aws:health:global::event/BILLING/AWS_BILLING_NOTIFICATION/AWS_BILLING_NOTIFICATION_6ce1d874-e995-40e2-99cd-EXAMPLE11145" \
    --region us-east-1
```
出力:  

```
{
    "entities": [
        {
            "entityArn": "arn:aws:health:global:123456789012:entity/EXAMPLEimSMoULmWHpb",
            "eventArn": "arn:aws:health:global::event/BILLING/AWS_BILLING_NOTIFICATION/AWS_BILLING_NOTIFICATION_6ce1d874-e995-40e2-99cd-EXAMPLE11145",
            "entityValue": "AWS_ACCOUNT",
            "awsAccountId": "123456789012",
            "lastUpdatedTime": 1588356454.08
        }
    ]
}
```
詳細については、「*AWS ユーザーガイド*」の「[イベントログ](https://docs.aws.amazon.com/health/latest/ug/getting-started-phd.html#event-log)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAffectedEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/health/describe-affected-entities.html)」を参照してください。

### `describe-event-details`
<a name="health_DescribeEventDetails_cli_2_topic"></a>

次の例は、`describe-event-details` を使用する方法を説明しています。

**AWS CLI**  
** AWS Health イベントに関する情報を一覧表示するには**  
次の の`describe-event-details`例では、指定された AWS Health イベントに関する情報を一覧表示します。  

```
aws health describe-event-details \
    --event-arns "arn:aws:health:us-east-1::event/EC2/AWS_EC2_OPERATIONAL_ISSUE/AWS_EC2_OPERATIONAL_ISSUE_VKTXI_EXAMPLE111" \
    --region us-east-1
```
出力:  

```
{
    "successfulSet": [
        {
            "event": {
                "arn": "arn:aws:health:us-east-1::event/EC2/AWS_EC2_OPERATIONAL_ISSUE/AWS_EC2_OPERATIONAL_ISSUE_VKTXI_EXAMPLE111",
                "service": "EC2",
                "eventTypeCode": "AWS_EC2_OPERATIONAL_ISSUE",
                "eventTypeCategory": "issue",
                "region": "us-east-1",
                "startTime": 1587462325.096,
                "endTime": 1587464204.774,
                "lastUpdatedTime": 1587464204.865,
                "statusCode": "closed"
            },
            "eventDescription": {
                "latestDescription": "[RESOLVED] Increased API Error Rates and Latencies\n\n[02:45 AM PDT] We are investigating increased API error rates and latencies in the US-EAST-1 Region.\n\n[03:16 AM PDT] Between 2:10 AM and 2:59 AM PDT we experienced increased API error rates and latencies in the US-EAST-1 Region. The issue has been resolved and the service is operating normally."
            }
        }
    ],
    "failedSet": []
}
```
詳細については、「*AWS Health ユーザーガイド*」の「[イベントの詳細ペイン](https://docs.aws.amazon.com/health/latest/ug/getting-started-phd.html#event-details)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/health/describe-event-details.html)」を参照してください。

### `describe-events`
<a name="health_DescribeEvents_cli_2_topic"></a>

次の例は、`describe-events` を使用する方法を説明しています。

**AWS CLI**  
**例 1: AWS ヘルスイベントを一覧表示するには**  
次の の`describe-events`例では、最近の AWS ヘルスイベントを一覧表示します。  

```
aws health describe-events \
    --region us-east-1
```
出力:  

```
{
    "events": [
        {
            "arn": "arn:aws:health:us-west-1::event/ECS/AWS_ECS_OPERATIONAL_ISSUE/AWS_ECS_OPERATIONAL_ISSUE_KWQPY_EXAMPLE111",
            "service": "ECS",
            "eventTypeCode": "AWS_ECS_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "us-west-1",
            "startTime": 1589077890.53,
            "endTime": 1589086345.597,
            "lastUpdatedTime": 1589086345.905,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:global::event/BILLING/AWS_BILLING_NOTIFICATION/AWS_BILLING_NOTIFICATION_6ce1d874-e995-40e2-99cd-EXAMPLE1118b",
            "service": "BILLING",
            "eventTypeCode": "AWS_BILLING_NOTIFICATION",
            "eventTypeCategory": "accountNotification",
            "region": "global",
            "startTime": 1588356000.0,
            "lastUpdatedTime": 1588356524.358,
            "statusCode": "open",
            "eventScopeCode": "ACCOUNT_SPECIFIC"
        },
        {
            "arn": "arn:aws:health:us-west-2::event/CLOUDFORMATION/AWS_CLOUDFORMATION_OPERATIONAL_ISSUE/AWS_CLOUDFORMATION_OPERATIONAL_ISSUE_OHTWY_EXAMPLE111",
            "service": "CLOUDFORMATION",
            "eventTypeCode": "AWS_CLOUDFORMATION_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "us-west-2",
            "startTime": 1588279630.761,
            "endTime": 1588284650.0,
            "lastUpdatedTime": 1588284691.941,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:ap-northeast-1::event/LAMBDA/AWS_LAMBDA_OPERATIONAL_ISSUE/AWS_LAMBDA_OPERATIONAL_ISSUE_JZDND_EXAMPLE111",
            "service": "LAMBDA",
            "eventTypeCode": "AWS_LAMBDA_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "ap-northeast-1",
            "startTime": 1587379534.08,
            "endTime": 1587391771.0,
            "lastUpdatedTime": 1587395689.316,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:us-east-1::event/EC2/AWS_EC2_OPERATIONAL_ISSUE/AWS_EC2_OPERATIONAL_ISSUE_COBXJ_EXAMPLE111",
            "service": "EC2",
            "eventTypeCode": "AWS_EC2_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "us-east-1",
            "startTime": 1586473044.284,
            "endTime": 1586479706.091,
            "lastUpdatedTime": 1586479706.153,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:global::event/SECURITY/AWS_SECURITY_NOTIFICATION/AWS_SECURITY_NOTIFICATION_42007387-8129-42da-8c88-EXAMPLE11139",
            "service": "SECURITY",
            "eventTypeCode": "AWS_SECURITY_NOTIFICATION",
            "eventTypeCategory": "accountNotification",
            "region": "global",
            "startTime": 1585674000.0,
            "lastUpdatedTime": 1585674004.132,
            "statusCode": "open",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:global::event/CLOUDFRONT/AWS_CLOUDFRONT_OPERATIONAL_ISSUE/AWS_CLOUDFRONT_OPERATIONAL_ISSUE_FRQXG_EXAMPLE111",
            "service": "CLOUDFRONT",
            "eventTypeCode": "AWS_CLOUDFRONT_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "global",
            "startTime": 1585610898.589,
            "endTime": 1585617671.0,
            "lastUpdatedTime": 1585620638.869,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:us-east-1::event/SES/AWS_SES_OPERATIONAL_ISSUE/AWS_SES_OPERATIONAL_ISSUE_URNDF_EXAMPLE111",
            "service": "SES",
            "eventTypeCode": "AWS_SES_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "us-east-1",
            "startTime": 1585342008.46,
            "endTime": 1585344017.0,
            "lastUpdatedTime": 1585344355.989,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:global::event/IAM/AWS_IAM_OPERATIONAL_NOTIFICATION/AWS_IAM_OPERATIONAL_NOTIFICATION_b6771c34-6ecd-4aea-9d3e-EXAMPLE1117e",
            "service": "IAM",
            "eventTypeCode": "AWS_IAM_OPERATIONAL_NOTIFICATION",
            "eventTypeCategory": "accountNotification",
            "region": "global",
            "startTime": 1584978300.0,
            "lastUpdatedTime": 1584978553.572,
            "statusCode": "open",
            "eventScopeCode": "ACCOUNT_SPECIFIC"
        },
        {
            "arn": "arn:aws:health:ap-southeast-2::event/EC2/AWS_EC2_OPERATIONAL_ISSUE/AWS_EC2_OPERATIONAL_ISSUE_HNGHE_EXAMPLE111",
            "service": "EC2",
            "eventTypeCode": "AWS_EC2_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "ap-southeast-2",
            "startTime": 1583881487.483,
            "endTime": 1583885056.785,
            "lastUpdatedTime": 1583885057.052,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        }
    ]
}
```
詳細については、[「 Health User Guide」の「Getting started with the AWS Personal Health Dashboard](https://docs.aws.amazon.com/health/latest/ug/getting-started-phd.html)」を参照してください。 *AWS *  
**例 2: サービスおよびイベントステータスコード別に AWS ヘルスイベントを一覧表示するには**  
次の の`describe-events`例では、イベントステータスがクローズされている Amazon Elastic Compute Cloud (Amazon EC2) の AWS ヘルスイベントを一覧表示します。  

```
aws health describe-events \
    --filter "services=EC2,eventStatusCodes=closed"
```
出力:  

```
{
    "events": [
        {
            "arn": "arn:aws:health:us-east-1::event/EC2/AWS_EC2_OPERATIONAL_ISSUE/AWS_EC2_OPERATIONAL_ISSUE_VKTXI_EXAMPLE111",
            "service": "EC2",
            "eventTypeCode": "AWS_EC2_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "us-east-1",
            "startTime": 1587462325.096,
            "endTime": 1587464204.774,
            "lastUpdatedTime": 1587464204.865,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:us-east-1::event/EC2/AWS_EC2_OPERATIONAL_ISSUE/AWS_EC2_OPERATIONAL_ISSUE_COBXJ_EXAMPLE111",
            "service": "EC2",
            "eventTypeCode": "AWS_EC2_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "us-east-1",
            "startTime": 1586473044.284,
            "endTime": 1586479706.091,
            "lastUpdatedTime": 1586479706.153,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        },
        {
            "arn": "arn:aws:health:ap-southeast-2::event/EC2/AWS_EC2_OPERATIONAL_ISSUE/AWS_EC2_OPERATIONAL_ISSUE_HNGHE_EXAMPLE111",
            "service": "EC2",
            "eventTypeCode": "AWS_EC2_OPERATIONAL_ISSUE",
            "eventTypeCategory": "issue",
            "region": "ap-southeast-2",
            "startTime": 1583881487.483,
            "endTime": 1583885056.785,
            "lastUpdatedTime": 1583885057.052,
            "statusCode": "closed",
            "eventScopeCode": "PUBLIC"
        }
    ]
}
```
詳細については、[「 Health User Guide」の「Getting started with the AWS Personal Health Dashboard](https://docs.aws.amazon.com/health/latest/ug/getting-started-phd.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/health/describe-events.html)」を参照してください。

# を使用した HealthImaging の例 AWS CLI
<a name="cli_2_medical-imaging_code_examples"></a>

次のコード例は、HealthImaging AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `copy-image-set`
<a name="medical-imaging_CopyImageSet_cli_2_topic"></a>

次のコード例は、`copy-image-set` を使用する方法を示しています。

**AWS CLI**  
**例 1：コピー先を指定せずに画像セットをコピーするには。**  
次の `copy-image-set` の例では、コピー先を指定せずに画像セットの複製コピーを作成します。  

```
aws medical-imaging copy-image-set \
    --datastore-id 12345678901234567890123456789012 \
    --source-image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    --copy-image-set-information '{"sourceImageSet": {"latestVersionId": "1" } }'
```
出力:  

```
{
    "destinationImageSetProperties": {
        "latestVersionId": "2",
        "imageSetWorkflowStatus": "COPYING",
        "updatedAt": 1680042357.432,
        "imageSetId": "b9a06fef182a5f992842f77f8e0868e5",
        "imageSetState": "LOCKED",
        "createdAt": 1680042357.432
    },
    "sourceImageSetProperties": {
        "latestVersionId": "1",
        "imageSetWorkflowStatus": "COPYING_WITH_READ_ONLY_ACCESS",
        "updatedAt": 1680042357.432,
        "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
        "imageSetState": "LOCKED",
        "createdAt": 1680027126.436
    },
    "datastoreId": "12345678901234567890123456789012"
}
```
**例 2：コピー先を指定して画像セットをコピーするには。**  
次の `copy-image-set` の例では、コピー先を指定して画像セットの複製コピーを作成します。  

```
aws medical-imaging copy-image-set \
    --datastore-id 12345678901234567890123456789012 \
    --source-image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    --copy-image-set-information '{"sourceImageSet": {"latestVersionId": "1" }, "destinationImageSet": { "imageSetId": "b9a06fef182a5f992842f77f8e0868e5", "latestVersionId": "1"} }'
```
出力:  

```
{
    "destinationImageSetProperties": {
        "latestVersionId": "2",
        "imageSetWorkflowStatus": "COPYING",
        "updatedAt": 1680042505.135,
        "imageSetId": "b9a06fef182a5f992842f77f8e0868e5",
        "imageSetState": "LOCKED",
        "createdAt": 1680042357.432
    },
    "sourceImageSetProperties": {
        "latestVersionId": "1",
        "imageSetWorkflowStatus": "COPYING_WITH_READ_ONLY_ACCESS",
        "updatedAt": 1680042505.135,
        "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
        "imageSetState": "LOCKED",
        "createdAt": 1680027126.436
    },
    "datastoreId": "12345678901234567890123456789012"
}
```
**例 3: ソース画像セットからコピー先画像セットにインスタンスのサブセットをコピーするには。**  
次の `copy-image-set` の例では、ソース画像セットからコピー先画像セットに 1 つの DICOM インスタンスをコピーします。force パラメータは、患者、検査、シリーズレベルの属性の不整合を上書きするために提供されます。  

```
aws medical-imaging copy-image-set \
    --datastore-id 12345678901234567890123456789012 \
    --source-image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    --copy-image-set-information '{"sourceImageSet": {"latestVersionId": "1","DICOMCopies": {"copiableAttributes": "{\"SchemaVersion\":\"1.1\",\"Study\":{\"Series\":{\"1.3.6.1.4.1.5962.99.1.3673257865.2104868982.1369432891697.3666.0\":{\"Instances\":{\"1.3.6.1.4.1.5962.99.1.3673257865.2104868982.1369432891697.3669.0\":{}}}}}}"}},"destinationImageSet": {"imageSetId": "b9eb50d8ee682eb9fcf4acbf92f62bb7","latestVersionId": "1"}}' \
    --force
```
出力:  

```
{
    "destinationImageSetProperties": {
        "latestVersionId": "2",
        "imageSetWorkflowStatus": "COPYING",
        "updatedAt": 1680042505.135,
        "imageSetId": "b9eb50d8ee682eb9fcf4acbf92f62bb7",
        "imageSetState": "LOCKED",
        "createdAt": 1680042357.432
    },
    "sourceImageSetProperties": {
        "latestVersionId": "1",
        "imageSetWorkflowStatus": "COPYING_WITH_READ_ONLY_ACCESS",
        "updatedAt": 1680042505.135,
        "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
        "imageSetState": "LOCKED",
        "createdAt": 1680027126.436
    },
    "datastoreId": "12345678901234567890123456789012"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Copying an image set](https://docs.aws.amazon.com/healthimaging/latest/devguide/copy-image-set.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyImageSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/copy-image-set.html)」を参照してください。

### `create-datastore`
<a name="medical-imaging_CreateDatastore_cli_2_topic"></a>

次の例は、`create-datastore` を使用する方法を説明しています。

**AWS CLI**  
**例 1：データストアにタグを付けるには**  
次の `create-datastore` コード例では、`my-datastore` という名が付けられたデータストアを作成しています。を指定せずにデータストアを作成する場合`--lossless-storage-format`、 AWS HealthImaging のデフォルトは HTJ2K (高スループット JPEG 2000) です。  

```
aws medical-imaging create-datastore \
    --datastore-name "my-datastore"
```
出力:  

```
{
    "datastoreId": "12345678901234567890123456789012",
    "datastoreStatus": "CREATING"
}
```
**例 2: JPEG 2000 ロスレスストレージ形式でデータストアを作成するには**  
JPEG 2000 ロスレスストレージ形式で設定されたデータストアは、可逆イメージフレームを JPEG 2000 形式でトランスコードして保持します。その後、画像フレームは JPEG 2000 ロスレス、トランスコーディングなしで取得できます。次の `create-datastore` コード例では、`my-datastore` という名前の JPEG 2000 ロスレスストレージ形式用に設定されたデータストアを作成します。  

```
aws medical-imaging create-datastore \
    --datastore-name "my-datastore" \
    --lossless-storage-format JPEG_2000_LOSSLESS
```
出力:  

```
{
    "datastoreId": "12345678901234567890123456789012",
    "datastoreStatus": "CREATING"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Creating a data store](https://docs.aws.amazon.com/healthimaging/latest/devguide/create-data-store.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDatastore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/create-datastore.html)」を参照してください。

### `delete-datastore`
<a name="medical-imaging_DeleteDatastore_cli_2_topic"></a>

次のコード例は、`delete-datastore` を使用する方法を示しています。

**AWS CLI**  
**データストアを削除するには**  
次の `delete-datastore` コード例では、データストアを削除しています。  

```
aws medical-imaging delete-datastore \
    --datastore-id "12345678901234567890123456789012"
```
出力:  

```
{
    "datastoreId": "12345678901234567890123456789012",
    "datastoreStatus": "DELETING"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Deleting a data store](https://docs.aws.amazon.com/healthimaging/latest/devguide/delete-data-store.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDatastore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/delete-datastore.html)」を参照してください。

### `delete-image-set`
<a name="medical-imaging_DeleteImageSet_cli_2_topic"></a>

次のコード例は、`delete-image-set` を使用する方法を示しています。

**AWS CLI**  
**画像セットを削除するには**  
以下の `delete-image-set` コード例は画像セットを削除しています。  

```
aws medical-imaging delete-image-set \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id ea92b0d8838c72a3f25d00d13616f87e
```
出力:  

```
{
    "imageSetWorkflowStatus": "DELETING",
    "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
    "imageSetState": "LOCKED",
    "datastoreId": "12345678901234567890123456789012"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Deleting an image set](https://docs.aws.amazon.com/healthimaging/latest/devguide/delete-image-set.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteImageSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/delete-image-set.html)」を参照してください。

### `get-datastore`
<a name="medical-imaging_GetDatastore_cli_2_topic"></a>

次の例は、`get-datastore` を使用する方法を説明しています。

**AWS CLI**  
**例 1: データストアのプロパティを取得するには**  
次の `get-datastore` コード例では、データストアのプロパティを取得しています。  

```
aws medical-imaging get-datastore \
    --datastore-id 12345678901234567890123456789012
```
出力:  

```
{
    "datastoreProperties": {
        "datastoreId": "12345678901234567890123456789012",
        "datastoreName": "TestDatastore123",
        "datastoreStatus": "ACTIVE",
        "losslessStorageFormat": "HTJ2K"
        "datastoreArn": "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012",
        "createdAt": "2022-11-15T23:33:09.643000+00:00",
        "updatedAt": "2022-11-15T23:33:09.643000+00:00"
    }
}
```
**例 2: JPEG 2000 用に設定されたデータストアのプロパティを取得するには**  
次の `get-datastore` コード例では、JPEG 2000 ロスレスストレージ形式用に設定されたデータストアのデータストアのプロパティを取得します。  

```
aws medical-imaging get-datastore \
    --datastore-id 12345678901234567890123456789012
```
出力:  

```
{
    "datastoreProperties": {
        "datastoreId": "12345678901234567890123456789012",
        "datastoreName": "TestDatastore123",
        "datastoreStatus": "ACTIVE",
        "losslessStorageFormat": "JPEG_2000_LOSSLESS",
        "datastoreArn": "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012",
        "createdAt": "2022-11-15T23:33:09.643000+00:00",
        "updatedAt": "2022-11-15T23:33:09.643000+00:00"
    }
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Getting data store properties](https://docs.aws.amazon.com/healthimaging/latest/devguide/get-data-store.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDatastore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/get-datastore.html)」を参照してください。

### `get-dicom-import-job`
<a name="medical-imaging_GetDICOMImportJob_cli_2_topic"></a>

次のコード例は、`get-dicom-import-job` を使用する方法を示しています。

**AWS CLI**  
**DICOM インポートジョブのプロパティを取得するには**  
次の `get-dicom-import-job` コード例では、DICOM インポートジョブのプロパティを取得しています。  

```
aws medical-imaging get-dicom-import-job \
    --datastore-id "12345678901234567890123456789012" \
    --job-id "09876543210987654321098765432109"
```
出力:  

```
{
    "jobProperties": {
        "jobId": "09876543210987654321098765432109",
        "jobName": "my-job",
        "jobStatus": "COMPLETED",
        "datastoreId": "12345678901234567890123456789012",
        "dataAccessRoleArn": "arn:aws:iam::123456789012:role/ImportJobDataAccessRole",
        "endedAt": "2022-08-12T11:29:42.285000+00:00",
        "submittedAt": "2022-08-12T11:28:11.152000+00:00",
        "inputS3Uri": "s3://medical-imaging-dicom-input/dicom_input/",
        "outputS3Uri": "s3://medical-imaging-output/job_output/12345678901234567890123456789012-DicomImport-09876543210987654321098765432109/"
    }
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Getting import job properties](https://docs.aws.amazon.com/healthimaging/latest/devguide/get-dicom-import-job.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDICOMImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/get-dicom-import-job.html)」を参照してください。

### `get-image-frame`
<a name="medical-imaging_GetImageFrame_cli_2_topic"></a>

次のコード例は、`get-image-frame` を使用する方法を示しています。

**AWS CLI**  
**画像セットのピクセルデータを取得するには**  
次の `get-image-frame` コード例では、画像フレームを取得しています。  

```
aws medical-imaging get-image-frame \
    --datastore-id "12345678901234567890123456789012" \
    --image-set-id "98765412345612345678907890789012" \
    --image-frame-information imageFrameId=3abf5d5d7ae72f80a0ec81b2c0de3ef4 \
    imageframe.jph
```
注：このコード例には出力は含まれていません。GetImageFrame という操作は、ピクセルデータのストリームを imageframe.jph ファイルに返すからです。画像フレームのデコードと表示については、「HTJ2K デコードライブラリ」を参照してください。  
詳細については、「*AWS HealthImaging Developer Guide*」の「[Getting image set pixel data](https://docs.aws.amazon.com/healthimaging/latest/devguide/get-image-frame.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImageFrame](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/get-image-frame.html)」を参照してください。

### `get-image-set-metadata`
<a name="medical-imaging_GetImageSetMetadata_cli_2_topic"></a>

次のコード例は、`get-image-set-metadata` を使用する方法を示しています。

**AWS CLI**  
**例 1：画像セットのメタデータをバージョンなしで取得するには**  
次の `get-image-set-metadata` コード例では、バージョンを指定せずに画像セットのメタデータを取得しています。  
注：`outfile` は必須のパラメータです  

```
aws medical-imaging get-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    studymetadata.json.gz
```
返されたメタデータは gzip で圧縮され、studymetadata.json.gz ファイルに保存されます。返された JSON オブジェクトの内容を表示するには、まずオブジェクトを解凍する必要があります。  
出力:  

```
{
    "contentType": "application/json",
    "contentEncoding": "gzip"
}
```
**例 2：画像セットのメタデータをバージョン付きで取得するには**  
次の `get-image-set-metadata` コード例では、指定されたバージョンの画像セットのメタデータを取得しています。  
注：`outfile` は必須のパラメータです  

```
aws medical-imaging get-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    --version-id 1 \
    studymetadata.json.gz
```
返されたメタデータは gzip で圧縮され、studymetadata.json.gz ファイルに保存されます。返された JSON オブジェクトの内容を表示するには、まずオブジェクトを解凍する必要があります。  
出力:  

```
{
    "contentType": "application/json",
    "contentEncoding": "gzip"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Getting image set metadata](https://docs.aws.amazon.com/healthimaging/latest/devguide/get-image-set-metadata.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImageSetMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/get-image-set-metadata.html)」を参照してください。

### `get-image-set`
<a name="medical-imaging_GetImageSet_cli_2_topic"></a>

次のコード例は、`get-image-set` を使用する方法を示しています。

**AWS CLI**  
**画像セットのプロパティを取得するには**  
以下の `get-image-set` コード例では、画像セットのプロパティを取得しています。  

```
aws medical-imaging get-image-set \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id 18f88ac7870584f58d56256646b4d92b \
    --version-id 1
```
出力:  

```
{
    "versionId": "1",
    "imageSetWorkflowStatus": "COPIED",
    "updatedAt": 1680027253.471,
    "imageSetId": "18f88ac7870584f58d56256646b4d92b",
    "imageSetState": "ACTIVE",
    "createdAt": 1679592510.753,
    "datastoreId": "12345678901234567890123456789012"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Getting image set properties](https://docs.aws.amazon.com/healthimaging/latest/devguide/get-image-set-properties.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImageSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/get-image-set.html)」を参照してください。

### `list-datastores`
<a name="medical-imaging_ListDatastores_cli_2_topic"></a>

次のコード例は、`list-datastores` を使用する方法を示しています。

**AWS CLI**  
**データストアを一覧表示するには**  
次の `list-datastores` コード例では、利用可能なデータストアを一覧表示しています。  

```
aws medical-imaging list-datastores
```
出力:  

```
{
    "datastoreSummaries": [
        {
            "datastoreId": "12345678901234567890123456789012",
            "datastoreName": "TestDatastore123",
            "datastoreStatus": "ACTIVE",
            "datastoreArn": "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012",
            "createdAt": "2022-11-15T23:33:09.643000+00:00",
            "updatedAt": "2022-11-15T23:33:09.643000+00:00"
        }
    ]
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Listing data stores](https://docs.aws.amazon.com/healthimaging/latest/devguide/list-data-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDatastores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/list-datastores.html)」を参照してください。

### `list-dicom-import-jobs`
<a name="medical-imaging_ListDICOMImportJobs_cli_2_topic"></a>

次のコード例は、`list-dicom-import-jobs` を使用する方法を示しています。

**AWS CLI**  
**DICOM インポートジョブを一覧表示するには**  
次の `list-dicom-import-jobs` コード例では、インポートジョブを一覧表示します。  

```
aws medical-imaging list-dicom-import-jobs \
    --datastore-id "12345678901234567890123456789012"
```
出力:  

```
{
    "jobSummaries": [
        {
            "jobId": "09876543210987654321098765432109",
            "jobName": "my-job",
            "jobStatus": "COMPLETED",
            "datastoreId": "12345678901234567890123456789012",
            "dataAccessRoleArn": "arn:aws:iam::123456789012:role/ImportJobDataAccessRole",
            "endedAt": "2022-08-12T11:21:56.504000+00:00",
            "submittedAt": "2022-08-12T11:20:21.734000+00:00"
        }
    ]
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Listing import jobs](https://docs.aws.amazon.com/healthimaging/latest/devguide/list-dicom-import-jobs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDICOMImportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/list-dicom-import-jobs.html)」を参照してください。

### `list-image-set-versions`
<a name="medical-imaging_ListImageSetVersions_cli_2_topic"></a>

次のコード例は、`list-image-set-versions` を使用する方法を示しています。

**AWS CLI**  
**画像セットバージョンを一覧表示するには**  
次の `list-image-set-versions` コード例では、画像セットのバージョン履歴を一覧表示しています。  

```
aws medical-imaging list-image-set-versions \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id ea92b0d8838c72a3f25d00d13616f87e
```
出力:  

```
{
    "imageSetPropertiesList": [
        {
            "ImageSetWorkflowStatus": "UPDATED",
            "versionId": "4",
            "updatedAt": 1680029436.304,
            "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
            "imageSetState": "ACTIVE",
            "createdAt": 1680027126.436
        },
        {
            "ImageSetWorkflowStatus": "UPDATED",
            "versionId": "3",
            "updatedAt": 1680029163.325,
            "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
            "imageSetState": "ACTIVE",
            "createdAt": 1680027126.436
        },
        {
            "ImageSetWorkflowStatus": "COPY_FAILED",
            "versionId": "2",
            "updatedAt": 1680027455.944,
            "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
            "imageSetState": "ACTIVE",
            "message": "INVALID_REQUEST:  Series of SourceImageSet and DestinationImageSet don't match.",
            "createdAt": 1680027126.436
        },
        {
            "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
            "imageSetState": "ACTIVE",
            "versionId": "1",
            "ImageSetWorkflowStatus": "COPIED",
            "createdAt": 1680027126.436
        }
    ]
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Listing image set versions](https://docs.aws.amazon.com/healthimaging/latest/devguide/list-image-set-versions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListImageSetVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/list-image-set-versions.html)」を参照してください。

### `list-tags-for-resource`
<a name="medical-imaging_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1：データストアリソースのタグを一覧表示するには**  
次の `list-tags-for-resource` コード例では、データストアのタグを一覧表示しています。  

```
aws medical-imaging list-tags-for-resource \
    --resource-arn "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012"
```
出力:  

```
{
    "tags":{
        "Deployment":"Development"
    }
}
```
**例 2：画像セットリソースのタグを一覧表示するには**  
次の `list-tags-for-resource` コード例では、画像セットのタグを一覧表示しています。  

```
aws medical-imaging list-tags-for-resource \
    --resource-arn "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/18f88ac7870584f58d56256646b4d92b"
```
出力:  

```
{
    "tags":{
        "Deployment":"Development"
    }
}
```
詳細については、[AWS HealthImaging デベロッパーガイドの「HealthImaging を使用したリソースのタグ付け](https://docs.aws.amazon.com/healthimaging/latest/devguide/tagging.html)*AWS HealthImaging*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/list-tags-for-resource.html)」を参照してください。

### `search-image-sets`
<a name="medical-imaging_SearchImageSets_cli_2_topic"></a>

次のコード例は、`search-image-sets` を使用する方法を示しています。

**AWS CLI**  
**例 1：EQUAL 演算子を使用して画像セットを検索するには**  
次の `search-image-sets` コード例では、EQUAL 演算子を使用し、特定の値に基づいて画像セットを検索しています。  

```
aws medical-imaging search-image-sets \
    --datastore-id 12345678901234567890123456789012 \
    --search-criteria file://search-criteria.json
```
`search-criteria.json` の内容  

```
{
    "filters": [{
        "values": [{"DICOMPatientId" : "SUBJECT08701"}],
        "operator": "EQUAL"
    }]
}
```
出力:  

```
{
    "imageSetsMetadataSummaries": [{
        "imageSetId": "09876543210987654321098765432109",
        "createdAt": "2022-12-06T21:40:59.429000+00:00",
        "version": 1,
        "DICOMTags": {
            "DICOMStudyId": "2011201407",
            "DICOMStudyDate": "19991122",
             "DICOMPatientSex": "F",
             "DICOMStudyInstanceUID": "1.2.840.99999999.84710745.943275268089",
             "DICOMPatientBirthDate": "19201120",
             "DICOMStudyDescription": "UNKNOWN",
             "DICOMPatientId": "SUBJECT08701",
             "DICOMPatientName": "Melissa844 Huel628",
             "DICOMNumberOfStudyRelatedInstances": 1,
             "DICOMStudyTime": "140728",
             "DICOMNumberOfStudyRelatedSeries": 1
            },
        "updatedAt": "2022-12-06T21:40:59.429000+00:00"
    }]
}
```
**例 2：DICOMStudyDate と DICOMStudyTime を使用することで、BETWEEN 演算子を使用して画像セットを検索するには**  
次の `search-image-sets` コード例では、1990 年 1 月 1 日 (午前 0 時) から 2023 年 1 月 1 日 (午前 0 時) の間に生成された DICOM スタディを含む画像セットを検索します。  
注：DICOMStudyTime は選択可能です。入力されていない場合は、フィルターで指定された日付の時間値は午前 0 時 (1 日の始まり) になります。  

```
aws medical-imaging search-image-sets \
    --datastore-id 12345678901234567890123456789012 \
    --search-criteria file://search-criteria.json
```
`search-criteria.json` の内容  

```
{
    "filters": [{
        "values": [{
            "DICOMStudyDateAndTime": {
                "DICOMStudyDate": "19900101",
                "DICOMStudyTime": "000000"
            }
        },
        {
            "DICOMStudyDateAndTime": {
                "DICOMStudyDate": "20230101",
                "DICOMStudyTime": "000000"
            }
        }],
        "operator": "BETWEEN"
    }]
}
```
出力:  

```
{
    "imageSetsMetadataSummaries": [{
        "imageSetId": "09876543210987654321098765432109",
        "createdAt": "2022-12-06T21:40:59.429000+00:00",
        "version": 1,
        "DICOMTags": {
            "DICOMStudyId": "2011201407",
            "DICOMStudyDate": "19991122",
            "DICOMPatientSex": "F",
            "DICOMStudyInstanceUID": "1.2.840.99999999.84710745.943275268089",
            "DICOMPatientBirthDate": "19201120",
            "DICOMStudyDescription": "UNKNOWN",
            "DICOMPatientId": "SUBJECT08701",
            "DICOMPatientName": "Melissa844 Huel628",
            "DICOMNumberOfStudyRelatedInstances": 1,
            "DICOMStudyTime": "140728",
            "DICOMNumberOfStudyRelatedSeries": 1
        },
        "updatedAt": "2022-12-06T21:40:59.429000+00:00"
    }]
}
```
**例 3：createdAt を使用して BETWEEN 演算子を使用して画像セットを検索するには (スタディが以前に保存されていた時間)**  
次の `search-image-sets` コード例では、UTC タイムゾーンの時間範囲の間で、HealthImaging に保持されている DICOM スタディを含む画像セットを検索します。  
注：createdAt をサンプル形式 ("1985-04-12T23:20:50.52Z") で提供してください。  

```
aws medical-imaging search-image-sets \
    --datastore-id 12345678901234567890123456789012 \
    --search-criteria  file://search-criteria.json
```
`search-criteria.json` の内容  

```
{
    "filters": [{
        "values": [{
            "createdAt": "1985-04-12T23:20:50.52Z"
        },
        {
            "createdAt": "2022-04-12T23:20:50.52Z"
        }],
        "operator": "BETWEEN"
    }]
}
```
出力:  

```
{
    "imageSetsMetadataSummaries": [{
        "imageSetId": "09876543210987654321098765432109",
        "createdAt": "2022-12-06T21:40:59.429000+00:00",
        "version": 1,
        "DICOMTags": {
            "DICOMStudyId": "2011201407",
            "DICOMStudyDate": "19991122",
            "DICOMPatientSex": "F",
            "DICOMStudyInstanceUID": "1.2.840.99999999.84710745.943275268089",
            "DICOMPatientBirthDate": "19201120",
            "DICOMStudyDescription": "UNKNOWN",
            "DICOMPatientId": "SUBJECT08701",
            "DICOMPatientName": "Melissa844 Huel628",
            "DICOMNumberOfStudyRelatedInstances": 1,
            "DICOMStudyTime": "140728",
            "DICOMNumberOfStudyRelatedSeries": 1
        },
        "lastUpdatedAt": "2022-12-06T21:40:59.429000+00:00"
    }]
}
```
**例 4: DICOMSeriesInstanceUID で EQUAL 演算子を使用し、updatedAt で BETWEEN 演算子を使用して画像セットを検索し、updatedAt フィールドのレスポンスを ASC 順序でソートするには**  
次の `search-image-sets` コード例では、DICOMSeriesInstanceUID で EQUAL 演算子を使用し、updatedAt で BETWEEN 演算子を使用して画像セットを検索し、updatedAt フィールドのレスポンスを ASC 順序でソートします。  
注: updatedAt をサンプル形式 ("1985-04-12T23:20:50.52Z") で提供してください。  

```
aws medical-imaging search-image-sets \
    --datastore-id 12345678901234567890123456789012 \
    --search-criteria  file://search-criteria.json
```
`search-criteria.json` の内容  

```
{
    "filters": [{
        "values": [{
            "updatedAt": "2024-03-11T15:00:05.074000-07:00"
        }, {
            "updatedAt": "2024-03-11T16:00:05.074000-07:00"
        }],
        "operator": "BETWEEN"
    }, {
        "values": [{
            "DICOMSeriesInstanceUID": "1.2.840.99999999.84710745.943275268089"
        }],
        "operator": "EQUAL"
    }],
    "sort": {
        "sortField": "updatedAt",
        "sortOrder": "ASC"
    }
}
```
出力:  

```
{
    "imageSetsMetadataSummaries": [{
        "imageSetId": "09876543210987654321098765432109",
        "createdAt": "2022-12-06T21:40:59.429000+00:00",
        "version": 1,
        "DICOMTags": {
            "DICOMStudyId": "2011201407",
            "DICOMStudyDate": "19991122",
            "DICOMPatientSex": "F",
            "DICOMStudyInstanceUID": "1.2.840.99999999.84710745.943275268089",
            "DICOMPatientBirthDate": "19201120",
            "DICOMStudyDescription": "UNKNOWN",
            "DICOMPatientId": "SUBJECT08701",
            "DICOMPatientName": "Melissa844 Huel628",
            "DICOMNumberOfStudyRelatedInstances": 1,
            "DICOMStudyTime": "140728",
            "DICOMNumberOfStudyRelatedSeries": 1
        },
        "lastUpdatedAt": "2022-12-06T21:40:59.429000+00:00"
    }]
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Searching image sets](https://docs.aws.amazon.com/healthimaging/latest/devguide/search-image-sets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchImageSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/search-image-sets.html)」を参照してください。

### `start-dicom-import-job`
<a name="medical-imaging_StartDICOMImportJob_cli_2_topic"></a>

次のコード例は、`start-dicom-import-job` を使用する方法を示しています。

**AWS CLI**  
**DICOM インポートジョブを開始するには**  
次の `start-dicom-import-job` コード例では、DICOM インポートジョブを開始しています。  

```
aws medical-imaging start-dicom-import-job \
    --job-name "my-job" \
    --datastore-id "12345678901234567890123456789012" \
    --input-s3-uri "s3://medical-imaging-dicom-input/dicom_input/" \
    --output-s3-uri "s3://medical-imaging-output/job_output/" \
    --data-access-role-arn "arn:aws:iam::123456789012:role/ImportJobDataAccessRole"
```
出力:  

```
{
    "datastoreId": "12345678901234567890123456789012",
    "jobId": "09876543210987654321098765432109",
    "jobStatus": "SUBMITTED",
    "submittedAt": "2022-08-12T11:28:11.152000+00:00"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Starting an import job](https://docs.aws.amazon.com/healthimaging/latest/devguide/start-dicom-import-job.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDICOMImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/start-dicom-import-job.html)」を参照してください。

### `tag-resource`
<a name="medical-imaging_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1：データストアにタグを付けるには**  
次の `tag-resource` コード例では、データストアにタグを付けています。  

```
aws medical-imaging tag-resource \
  --resource-arn "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012" \
  --tags '{"Deployment":"Development"}'
```
このコマンドでは何も出力されません。  
**例 2：画像セットにタグを付けるには**  
次の `tag-resource` コード例では、画像セットにタグを付けています。  

```
aws medical-imaging tag-resource \
    --resource-arn "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/18f88ac7870584f58d56256646b4d92b" \
    --tags '{"Deployment":"Development"}'
```
このコマンドでは何も出力されません。  
詳細については、[AWS HealthImaging デベロッパーガイドの「HealthImaging を使用したリソースのタグ付け](https://docs.aws.amazon.com/healthimaging/latest/devguide/tagging.html)*AWS HealthImaging*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="medical-imaging_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1：データストアのタグを削除するには**  
次の `untag-resource` コード例では、データストアにタグを削除します。  

```
aws medical-imaging untag-resource \
    --resource-arn "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012" \
    --tag-keys '["Deployment"]'
```
このコマンドでは何も出力されません。  
**例 2：画像セットにタグを削除するには**  
次の `untag-resource` コード例では、画像セットにタグを削除します。  

```
aws medical-imaging untag-resource \
    --resource-arn "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/18f88ac7870584f58d56256646b4d92b" \
    --tag-keys '["Deployment"]'
```
このコマンドでは何も出力されません。  
詳細については、[AWS HealthImaging デベロッパーガイドの「HealthImaging を使用したリソースのタグ付け](https://docs.aws.amazon.com/healthimaging/latest/devguide/tagging.html)*AWS HealthImaging*」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/untag-resource.html)」を参照してください。

### `update-image-set-metadata`
<a name="medical-imaging_UpdateImageSetMetadata_cli_2_topic"></a>

次のコード例は、`update-image-set-metadata` を使用する方法を示しています。

**AWS CLI**  
**例 1: 画像セットメタデータに属性を挿入または更新するには**  
次の `update-image-set-metadata` の例では、画像セットメタデータに属性を挿入または更新します。  

```
aws medical-imaging update-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    --latest-version-id 1 \
    --cli-binary-format raw-in-base64-out \
    --update-image-set-metadata-updates file://metadata-updates.json
```
`metadata-updates.json` の内容  

```
{
    "DICOMUpdates": {
        "updatableAttributes": "{\"SchemaVersion\":1.1,\"Patient\":{\"DICOM\":{\"PatientName\":\"MX^MX\"}}}"
    }
}
```
出力:  

```
{
    "latestVersionId": "2",
    "imageSetWorkflowStatus": "UPDATING",
    "updatedAt": 1680042257.908,
    "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
    "imageSetState": "LOCKED",
    "createdAt": 1680027126.436,
    "datastoreId": "12345678901234567890123456789012"
}
```
**例 2: 画像セットメタデータから属性を削除するには**  
次の `update-image-set-metadata` の例では、画像セットメタデータから属性を削除します。  

```
aws medical-imaging update-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    --latest-version-id 1 \
    --cli-binary-format raw-in-base64-out \
    --update-image-set-metadata-updates file://metadata-updates.json
```
`metadata-updates.json` の内容  

```
{
    "DICOMUpdates": {
        "removableAttributes": "{\"SchemaVersion\":1.1,\"Study\":{\"DICOM\":{\"StudyDescription\":\"CHEST\"}}}"
    }
}
```
出力:  

```
{
    "latestVersionId": "2",
    "imageSetWorkflowStatus": "UPDATING",
    "updatedAt": 1680042257.908,
    "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
    "imageSetState": "LOCKED",
    "createdAt": 1680027126.436,
    "datastoreId": "12345678901234567890123456789012"
}
```
**例 3: 画像セットメタデータからインスタンスを削除するには**  
次の `update-image-set-metadata` の例では、画像セットメタデータからインスタンスを削除します。  

```
aws medical-imaging update-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id ea92b0d8838c72a3f25d00d13616f87e \
    --latest-version-id 1 \
    --cli-binary-format raw-in-base64-out \
    --update-image-set-metadata-updates file://metadata-updates.json \
    --force
```
`metadata-updates.json` の内容  

```
{
    "DICOMUpdates": {
        "removableAttributes": "{\"SchemaVersion\": 1.1,\"Study\": {\"Series\": {\"1.1.1.1.1.1.12345.123456789012.123.12345678901234.1\": {\"Instances\": {\"1.1.1.1.1.1.12345.123456789012.123.12345678901234.1\": {}}}}}}"
    }
}
```
出力:  

```
{
    "latestVersionId": "2",
    "imageSetWorkflowStatus": "UPDATING",
    "updatedAt": 1680042257.908,
    "imageSetId": "ea92b0d8838c72a3f25d00d13616f87e",
    "imageSetState": "LOCKED",
    "createdAt": 1680027126.436,
    "datastoreId": "12345678901234567890123456789012"
}
```
**例 4: 画像セットを以前のバージョンに戻すには**  
次の `update-image-set-metadata` の例は、画像セットを以前のバージョンに戻す方法を示しています。CopyImageSet および UpdateImageSetMetadata アクションは、新しいバージョンの画像セットを作成します。  

```
aws medical-imaging update-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id 53d5fdb05ca4d46ac7ca64b06545c66e \
    --latest-version-id 3 \
    --cli-binary-format raw-in-base64-out \
    --update-image-set-metadata-updates '{"revertToVersionId": "1"}'
```
出力:  

```
{
    "datastoreId": "12345678901234567890123456789012",
    "imageSetId": "53d5fdb05ca4d46ac7ca64b06545c66e",
    "latestVersionId": "4",
    "imageSetState": "LOCKED",
    "imageSetWorkflowStatus": "UPDATING",
    "createdAt": 1680027126.436,
    "updatedAt": 1680042257.908
}
```
**例 5: インスタンスにプライベート DICOM データ要素を追加するには**  
次の `update-image-set-metadata` の例は、画像セット内で指定されたインスタンスにプライベート要素を追加する方法を示しています。DICOM 標準では、標準データ要素に含めることができない情報の通信に、プライベートデータ要素が許可されます。UpdateImageSetMetadata アクションを使用して、プライベートデータ要素を作成、更新、削除できます。  

```
aws medical-imaging update-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id 53d5fdb05ca4d46ac7ca64b06545c66e \
    --latest-version-id 1 \
    --cli-binary-format raw-in-base64-out \
    --force \
    --update-image-set-metadata-updates file://metadata-updates.json
```
`metadata-updates.json` の内容  

```
{
    "DICOMUpdates": {
        "updatableAttributes": "{\"SchemaVersion\": 1.1,\"Study\": {\"Series\": {\"1.1.1.1.1.1.12345.123456789012.123.12345678901234.1\": {\"Instances\": {\"1.1.1.1.1.1.12345.123456789012.123.12345678901234.1\": {\"DICOM\": {\"001910F9\": \"97\"},\"DICOMVRs\": {\"001910F9\": \"DS\"}}}}}}}"
    }
}
```
出力:  

```
{
    "latestVersionId": "2",
    "imageSetWorkflowStatus": "UPDATING",
    "updatedAt": 1680042257.908,
    "imageSetId": "53d5fdb05ca4d46ac7ca64b06545c66e",
    "imageSetState": "LOCKED",
    "createdAt": 1680027126.436,
    "datastoreId": "12345678901234567890123456789012"
}
```
**例 6: プライベート DICOM データ要素をインスタンスに対して更新するには**  
次の `update-image-set-metadata` の例は、画像セット内のインスタンスに属するプライベートデータ要素の値を更新する方法を示しています。  

```
aws medical-imaging update-image-set-metadata \
    --datastore-id 12345678901234567890123456789012 \
    --image-set-id 53d5fdb05ca4d46ac7ca64b06545c66e \
    --latest-version-id 1 \
    --cli-binary-format raw-in-base64-out \
    --force \
    --update-image-set-metadata-updates file://metadata-updates.json
```
`metadata-updates.json` の内容  

```
{
    "DICOMUpdates": {
        "updatableAttributes": "{\"SchemaVersion\": 1.1,\"Study\": {\"Series\": {\"1.1.1.1.1.1.12345.123456789012.123.12345678901234.1\": {\"Instances\": {\"1.1.1.1.1.1.12345.123456789012.123.12345678901234.1\": {\"DICOM\": {\"00091001\": \"GE_GENESIS_DD\"}}}}}}}"
    }
}
```
出力:  

```
{
    "latestVersionId": "2",
    "imageSetWorkflowStatus": "UPDATING",
    "updatedAt": 1680042257.908,
    "imageSetId": "53d5fdb05ca4d46ac7ca64b06545c66e",
    "imageSetState": "LOCKED",
    "createdAt": 1680027126.436,
    "datastoreId": "12345678901234567890123456789012"
}
```
**例 7: force パラメータを使用して SOPInstanceUID を更新するには**  
次の `update-image-set-metadata` の例は、force パラメータを使用して SOPInstanceUID を更新し、DICOM メタデータの制約をオーバーライドする方法を示しています。  

```
aws medical-imaging update-image-set-metadata \
        --datastore-id 12345678901234567890123456789012 \
        --image-set-id 53d5fdb05ca4d46ac7ca64b06545c66e \
        --latest-version-id 1 \
        --cli-binary-format raw-in-base64-out \
        --force \
        --update-image-set-metadata-updates file://metadata-updates.json
```
`metadata-updates.json` の内容  

```
{
    "DICOMUpdates": {
        "updatableAttributes": "{\"SchemaVersion\":1.1,\"Study\":{\"Series\":{\"1.3.6.1.4.1.5962.99.1.3633258862.2104868982.1369432891697.3656.0\":{\"Instances\":{\"1.3.6.1.4.1.5962.99.1.3633258862.2104868982.1369432891697.3659.0\":{\"DICOM\":{\"SOPInstanceUID\":\"1.3.6.1.4.1.5962.99.1.3633258862.2104868982.1369432891697.3659.9\"}}}}}}}"
    }
}
```
出力:  

```
{
    "latestVersionId": "2",
    "imageSetWorkflowStatus": "UPDATING",
    "updatedAt": 1680042257.908,
    "imageSetId": "53d5fdb05ca4d46ac7ca64b06545c66e",
    "imageSetState": "LOCKED",
    "createdAt": 1680027126.436,
    "datastoreId": "12345678901234567890123456789012"
}
```
詳細については、「*AWS HealthImaging Developer Guide*」の「[Updating image set metadata](https://docs.aws.amazon.com/healthimaging/latest/devguide/update-image-set-metadata.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateImageSetMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medical-imaging/update-image-set-metadata.html)」を参照してください。

# を使用した HealthLake の例 AWS CLI
<a name="cli_2_healthlake_code_examples"></a>

次のコード例は、HealthLake AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-fhir-datastore`
<a name="healthlake_CreateFHIRDatastore_cli_2_topic"></a>

次のコード例は、`create-fhir-datastore` を使用する方法を示しています。

**AWS CLI**  
**例 1: SigV4 対応の HealthLake データストアを作成する**  
次の`create-fhir-datastore`例は、 AWS HealthLake で新しいデータストアを作成する方法を示しています。  

```
aws healthlake create-fhir-datastore \
    --datastore-type-version R4 \
    --datastore-name "FhirTestDatastore"
```
出力:  

```
{
    "DatastoreEndpoint": "https://healthlake.us-east-1.amazonaws.com/datastore/(Data store ID)/r4/",
    "DatastoreArn": "arn:aws:healthlake:us-east-1:(AWS Account ID):datastore/(Data store ID)",
    "DatastoreStatus": "CREATING",
    "DatastoreId": "(Data store ID)"
}
```
**例 2: SMART on FHIR 対応の HealthLake データストアを作成する**  
次の`create-fhir-datastore`例は、 AWS HealthLake で FHIR 対応データストアに新しい SMART を作成する方法を示しています。  

```
aws healthlake create-fhir-datastore \
    --datastore-name "your-data-store-name" \
    --datastore-type-version R4 \
    --preload-data-config PreloadDataType="SYNTHEA" \
    --sse-configuration '{ "KmsEncryptionConfig": {  "CmkType": "CUSTOMER_MANAGED_KMS_KEY", "KmsKeyId": "arn:aws:kms:us-east-1:your-account-id:key/your-key-id" } }' \
    --identity-provider-configuration  file://identity_provider_configuration.json
```
`identity_provider_configuration.json` の内容:  

```
{
    "AuthorizationStrategy": "SMART_ON_FHIR_V1",
    "FineGrainedAuthorizationEnabled": true,
    "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
    "Metadata": "{\"issuer\":\"https://ehr.example.com\", \"jwks_uri\":\"https://ehr.example.com/.well-known/jwks.json\",\"authorization_endpoint\":\"https://ehr.example.com/auth/authorize\",\"token_endpoint\":\"https://ehr.token.com/auth/token\",\"token_endpoint_auth_methods_supported\":[\"client_secret_basic\",\"foo\"],\"grant_types_supported\":[\"client_credential\",\"foo\"],\"registration_endpoint\":\"https://ehr.example.com/auth/register\",\"scopes_supported\":[\"openId\",\"profile\",\"launch\"],\"response_types_supported\":[\"code\"],\"management_endpoint\":\"https://ehr.example.com/user/manage\",\"introspection_endpoint\":\"https://ehr.example.com/user/introspect\",\"revocation_endpoint\":\"https://ehr.example.com/user/revoke\",\"code_challenge_methods_supported\":[\"S256\"],\"capabilities\":[\"launch-ehr\",\"sso-openid-connect\",\"client-public\"]}"
}
```
出力:  

```
{
    "DatastoreEndpoint": "https://healthlake.us-east-1.amazonaws.com/datastore/(Data store ID)/r4/",
    "DatastoreArn": "arn:aws:healthlake:us-east-1:(AWS Account ID):datastore/(Data store ID)",
    "DatastoreStatus": "CREATING",
    "DatastoreId": "(Data store ID)"
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「[FHIR データストアの作成とモニタリング](https://docs.aws.amazon.com/healthlake/latest/devguide/working-with-FHIR-healthlake.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateFHIRDatastore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/create-fhir-datastore.html)」を参照してください。

### `delete-fhir-datastore`
<a name="healthlake_DeleteFHIRDatastore_cli_2_topic"></a>

次のコード例は、`delete-fhir-datastore` を使用する方法を示しています。

**AWS CLI**  
**FHIR Data Store を削除するには**  
次の`delete-fhir-datastore`例は、 AWS HealthLake でデータストアとそのすべてのコンテンツを削除する方法を示しています。  

```
aws healthlake delete-fhir-datastore \
    --datastore-id (Data store ID)
```
出力:  

```
{
    "DatastoreEndpoint": "https://healthlake.us-east-1.amazonaws.com/datastore/(Data store ID)/r4/",
    "DatastoreArn": "arn:aws:healthlake:us-east-1:(AWS Account ID):datastore/(Data store ID)",
    "DatastoreStatus": "DELETING",
    "DatastoreId": "(Data store ID)"
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「FHIR データストアの作成とモニタリング <https://docs.aws.amazon.com/healthlake/latest/devguide/working-with-FHIR-healthlake.html>」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteFHIRDatastore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/delete-fhir-datastore.html)」を参照してください。

### `describe-fhir-datastore`
<a name="healthlake_DescribeFHIRDatastore_cli_2_topic"></a>

次のコード例は、`describe-fhir-datastore` を使用する方法を示しています。

**AWS CLI**  
**FHIR データストアの詳細を取得するには**  
次の`describe-fhir-datastore`例は、 AWS HealthLake でデータストアのプロパティを検索する方法を示しています。  

```
aws healthlake describe-fhir-datastore \
    --datastore-id "1f2f459836ac6c513ce899f9e4f66a59"
```
出力:  

```
{
    "DatastoreProperties": {
        "PreloadDataConfig": {
            "PreloadDataType": "SYNTHEA"
        },
        "SseConfiguration": {
            "KmsEncryptionConfig": {
                "CmkType": "CUSTOMER_MANAGED_KMS_KEY",
                "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
            }
        },
        "DatastoreName": "Demo",
        "DatastoreArn": "arn:aws:healthlake:us-east-1:<AWS Account ID>:datastore/<Data store ID>",
        "DatastoreEndpoint": "https://healthlake.us-east-1.amazonaws.com/datastore/<Data store ID>/r4/",
        "DatastoreStatus": "ACTIVE",
        "DatastoreTypeVersion": "R4",
        "CreatedAt": 1603761064.881,
        "DatastoreId": "<Data store ID>",
        "IdentityProviderConfiguration": {
            "AuthorizationStrategy": "AWS_AUTH",
            "FineGrainedAuthorizationEnabled": false
        }
    }
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「[FHIR データストアの作成とモニタリング](https://docs.aws.amazon.com/healthlake/latest/devguide/working-with-FHIR-healthlake.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeFHIRDatastore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/describe-fhir-datastore.html)」を参照してください。

### `describe-fhir-export-job`
<a name="healthlake_DescribeFHIRExportJob_cli_2_topic"></a>

次のコード例は、`describe-fhir-export-job` を使用する方法を示しています。

**AWS CLI**  
**FHIR エクスポートジョブを記述するには**  
次の`describe-fhir-export-job`例は、 AWS HealthLake で FHIR エクスポートジョブのプロパティを検索する方法を示しています。  

```
aws healthlake describe-fhir-export-job \
    --datastore-id (Data store ID) \
    --job-id 9b9a51943afaedd0a8c0c26c49135a31
```
出力:  

```
{
    "ExportJobProperties": {
        "DataAccessRoleArn": "arn:aws:iam::(AWS Account ID):role/(Role Name)",
        "JobStatus": "IN_PROGRESS",
        "JobId": "9009813e9d69ba7cf79bcb3468780f16",
        "SubmitTime": "2024-11-20T11:31:46.672000-05:00",
        "EndTime": "2024-11-20T11:34:01.636000-05:00",
        "OutputDataConfig": {
            "S3Configuration": {
            "S3Uri": "s3://(Bucket Name)/(Prefix Name)/",
            "KmsKeyId": "arn:aws:kms:us-east-1:012345678910:key/d330e7fc-b56c-4216-a250-f4c43ef46e83"
        }

        },
        "DatastoreId": "(Data store ID)"
    }
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「[FHIR データストアからのファイルエクスポート](https://docs.aws.amazon.com/healthlake/latest/devguide/export-datastore.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeFHIRExportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/describe-fhir-export-job.html)」を参照してください。

### `describe-fhir-import-job`
<a name="healthlake_DescribeFHIRImportJob_cli_2_topic"></a>

次のコード例は、`describe-fhir-import-job` を使用する方法を示しています。

**AWS CLI**  
**FHIR インポートジョブを記述するには**  
次の`describe-fhir-import-job`例は、 AWS HealthLake を使用して FHIR インポートジョブのプロパティを学習する方法を示しています。  

```
aws healthlake describe-fhir-import-job \
    --datastore-id (Data store ID) \
    --job-id c145fbb27b192af392f8ce6e7838e34f
```
出力:  

```
{
    "ImportJobProperties": {
    "InputDataConfig": {
        "S3Uri": "s3://(Bucket Name)/(Prefix Name)/"
        { "arrayitem2": 2 }
    },
    "DataAccessRoleArn": "arn:aws:iam::(AWS Account ID):role/(Role Name)",
    "JobStatus": "COMPLETED",
    "JobId": "c145fbb27b192af392f8ce6e7838e34f",
    "SubmitTime": 1606272542.161,
    "EndTime": 1606272609.497,
    "DatastoreId": "(Data store ID)"
    }
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「[FHIR データストアへのファイルインポート](https://docs.aws.amazon.com/healthlake/latest/devguide/import-datastore.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeFHIRImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/describe-fhir-import-job.html)」を参照してください。

### `list-fhir-datastores`
<a name="healthlake_ListFHIRDatastores_cli_2_topic"></a>

次のコード例は、`list-fhir-datastores` を使用する方法を示しています。

**AWS CLI**  
**FHIR データストアを一覧表示するには**  
次の`list-fhir-datastores`例は、 コマンドの使用方法と、 AWS HealthLake のデータストアのステータスに基づいてユーザーが結果をフィルタリングする方法を示しています。  

```
aws healthlake list-fhir-datastores \
    --filter DatastoreStatus=ACTIVE
```
出力:  

```
{
    "DatastorePropertiesList": [
    {
        "PreloadDataConfig": {
            "PreloadDataType": "SYNTHEA"
        },
        "SseConfiguration": {
            "KmsEncryptionConfig": {
                "CmkType": "CUSTOMER_MANAGED_KMS_KEY",
                "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
            }
        },
        "DatastoreName": "Demo",
        "DatastoreArn": "arn:aws:healthlake:us-east-1:<AWS Account ID>:datastore/<Data store ID>",
        "DatastoreEndpoint": "https://healthlake.us-east-1.amazonaws.com/datastore/<Data store ID>/r4/",
        "DatastoreStatus": "ACTIVE",
        "DatastoreTypeVersion": "R4",
        "CreatedAt": 1603761064.881,
        "DatastoreId": "<Data store ID>",
        "IdentityProviderConfiguration": {
            "AuthorizationStrategy": "AWS_AUTH",
            "FineGrainedAuthorizationEnabled": false
        }
    }
    ]
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「[FHIR データストアの作成とモニタリング](https://docs.aws.amazon.com/healthlake/latest/devguide/working-with-FHIR-healthlake.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListFHIRDatastores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/list-fhir-datastores.html)」を参照してください。

### `list-fhir-export-jobs`
<a name="healthlake_ListFHIRExportJobs_cli_2_topic"></a>

次のコード例は、`list-fhir-export-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべての FHIR エクスポートジョブを一覧表示するには**  
次の `list-fhir-export-jobs` の例は、コマンドを使用して、アカウントに関連付けられたエクスポートジョブのリストを表示する方法を示しています。  

```
aws healthlake list-fhir-export-jobs \
    --datastore-id (Data store ID) \
    --submitted-before (DATE like 2024-10-13T19:00:00Z)\
    --submitted-after (DATE like 2020-10-13T19:00:00Z )\
    --job-name "FHIR-EXPORT" \
    --job-status SUBMITTED  \
    --max-results (Integer between 1 and 500)
```
出力:  

```
{
    "ExportJobPropertiesList": [
        {
            "ExportJobProperties": {
                "OutputDataConfig": {
                    "S3Uri": "s3://(Bucket Name)/(Prefix Name)/",
                    "S3Configuration": {
                        "S3Uri": "s3://(Bucket Name)/(Prefix Name)/",
                        "KmsKeyId": "(KmsKey Id)"
                    }
                },
                "DataAccessRoleArn": "arn:aws:iam::(AWS Account ID):role/(Role Name)",
                "JobStatus": "COMPLETED",
                "JobId": "c145fbb27b192af392f8ce6e7838e34f",
                "JobName": "FHIR-EXPORT",
                "SubmitTime": "2024-11-20T11:31:46.672000-05:00",
                "EndTime": "2024-11-20T11:34:01.636000-05:00",
                "DatastoreId": "(Data store ID)"
            }
        }
    ]
}
```
詳細については、 AWS HealthLake デベロッパーガイド[の「FHIR データストアからのファイルのエクスポート](https://docs.aws.amazon.com/healthlake/latest/devguide/export-datastore.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListFHIRExportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/list-fhir-export-jobs.html)」を参照してください。

### `list-fhir-import-jobs`
<a name="healthlake_ListFHIRImportJobs_cli_2_topic"></a>

次のコード例は、`list-fhir-import-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべての FHIR インポートジョブを一覧表示するには**  
次の `list-fhir-import-jobs` の例は、コマンドを使用して、アカウントに関連付けられているすべてのインポートジョブのリストを表示する方法を示しています。  

```
aws healthlake list-fhir-import-jobs \
    --datastore-id (Data store ID) \
    --submitted-before (DATE like 2024-10-13T19:00:00Z) \
    --submitted-after (DATE like 2020-10-13T19:00:00Z ) \
    --job-name "FHIR-IMPORT" \
    --job-status SUBMITTED  \
    -max-results (Integer between 1 and 500)
```
出力:  

```
{
    "ImportJobPropertiesList": [
        {
            "JobId": "c0fddbf76f238297632d4aebdbfc9ddf",
            "JobStatus": "COMPLETED",
            "SubmitTime": "2024-11-20T10:08:46.813000-05:00",
            "EndTime": "2024-11-20T10:10:09.093000-05:00",
            "DatastoreId": "(Data store ID)",
            "InputDataConfig": {
                "S3Uri": "s3://(Bucket Name)/(Prefix Name)/"
            },
            "JobOutputDataConfig": {
                "S3Configuration": {
                    "S3Uri": "s3://(Bucket Name)/import/6407b9ae4c2def3cb6f1a46a0c599ec0-FHIR_IMPORT-c0fddbf76f238297632d4aebdbfc9ddf/",
                    "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/b7f645cb-e564-4981-8672-9e012d1ff1a0"
                }
            },
            "JobProgressReport": {
                "TotalNumberOfScannedFiles": 1,
                "TotalSizeOfScannedFilesInMB": 0.001798,
                "TotalNumberOfImportedFiles": 1,
                "TotalNumberOfResourcesScanned": 1,
                "TotalNumberOfResourcesImported": 1,
                "TotalNumberOfResourcesWithCustomerError": 0,
                "TotalNumberOfFilesReadWithCustomerError": 0,
                "Throughput": 0.0
            },
            "DataAccessRoleArn": "arn:aws:iam::(AWS Account ID):role/(Role Name)"
        }
    ]
}
```
詳細については、 AWS HealthLake デベロッパーガイド[の「FHIR データストアへのファイルのインポート](https://docs.aws.amazon.com/healthlake/latest/devguide/import-examples.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListFHIRImportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/list-fhir-import-jobs.html)」を参照してください。

### `list-tags-for-resource`
<a name="healthlake_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**データストアのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定したデータストアに関連付けられているタグを一覧表示します。  

```
aws healthlake list-tags-for-resource \
    --resource-arn "arn:aws:healthlake:us-east-1:123456789012:datastore/fhir/0725c83f4307f263e16fd56b6d8ebdbe"
```
出力:  

```
{
    "tags": {
        "key": "value",
        "key1": "value1"
    }
}
```
詳細については、[AWS HealthLake デベロッパーガイドの「HealthLake でのリソースのタグ付け](https://docs.aws.amazon.com/healthlake/latest/devguide/tagging.html)」を参照してください。 AWS HealthLake   
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/list-tags-for-resource.html)」を参照してください。

### `start-fhir-export-job`
<a name="healthlake_StartFHIRExportJob_cli_2_topic"></a>

次のコード例は、`start-fhir-export-job` を使用する方法を示しています。

**AWS CLI**  
**FHIR エクスポートジョブを開始するには**  
次の`start-fhir-export-job`例は、 AWS HealthLake を使用して FHIR エクスポートジョブを開始する方法を示しています。  

```
aws healthlake start-fhir-export-job \
    --output-data-config '{"S3Configuration": {"S3Uri":"s3://(Bucket Name)/(Prefix Name)/","KmsKeyId":"arn:aws:kms:us-east-1:012345678910:key/d330e7fc-b56c-4216-a250-f4c43ef46e83"}}' \
    --datastore-id (Data store ID) \
    --data-access-role-arn arn:aws:iam::(AWS Account ID):role/(Role Name)
```
出力:  

```
{
    "DatastoreId": "(Data store ID)",
    "JobStatus": "SUBMITTED",
    "JobId": "9b9a51943afaedd0a8c0c26c49135a31"
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「[FHIR データストアからのファイルエクスポート](https://docs.aws.amazon.com/healthlake/latest/devguide/export-datastore.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartFHIRExportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/start-fhir-export-job.html)」を参照してください。

### `start-fhir-import-job`
<a name="healthlake_StartFHIRImportJob_cli_2_topic"></a>

次のコード例は、`start-fhir-import-job` を使用する方法を示しています。

**AWS CLI**  
**FHIR インポートジョブを開始するには**  
次の`start-fhir-import-job`例は、 AWS HealthLake を使用して FHIR インポートジョブを開始する方法を示しています。  

```
aws healthlake start-fhir-import-job \
    --input-data-config S3Uri="s3://(Bucket Name)/(Prefix Name)/" \
    --job-output-data-config '{"S3Configuration": {"S3Uri":"s3://(Bucket Name)/(Prefix Name)/","KmsKeyId":"arn:aws:kms:us-east-1:012345678910:key/d330e7fc-b56c-4216-a250-f4c43ef46e83"}}' \
    --datastore-id (Data store ID) \
    --data-access-role-arn "arn:aws:iam::(AWS Account ID):role/(Role Name)"
```
出力:  

```
{
    "DatastoreId": "(Data store ID)",
    "JobStatus": "SUBMITTED",
    "JobId": "c145fbb27b192af392f8ce6e7838e34f"
}
```
詳細については、*AWS HealthLake デベロッパーガイド*の「[FHIR データストアへのファイルインポート](https://docs.aws.amazon.com/healthlake/latest/devguide/import-datastore.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartFHIRImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/start-fhir-import-job.html)」を参照してください。

### `tag-resource`
<a name="healthlake_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**データストアにタグを追加するには**  
次の `tag-resource` の例では、データストアにタグを追加する方法を示します。  

```
aws healthlake tag-resource \
    --resource-arn "arn:aws:healthlake:us-east-1:123456789012:datastore/fhir/0725c83f4307f263e16fd56b6d8ebdbe" \
    --tags '[{"Key": "key1", "Value": "value1"}]'
```
このコマンドでは何も出力されません。  
詳細については、*AWS HealthLake デベロッパーガイド*の「[データストアへのタグの追加](https://docs.aws.amazon.com/healthlake/latest/devguide/add-a-tag.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="healthlake_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**データストアからタグを削除するには**  
次の `untag-resource` の例では、データストアからタグを削除する方法を示します。  

```
aws healthlake untag-resource \
    --resource-arn "arn:aws:healthlake:us-east-1:123456789012:datastore/fhir/b91723d65c6fdeb1d26543a49d2ed1fa" \
    --tag-keys '["key1"]'
```
このコマンドでは何も出力されません。  
詳細については、*AWS HealthLake デベロッパーガイド*の「[データストアからのタグの削除](https://docs.aws.amazon.com/healthlake/latest/devguide/remove-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/healthlake/untag-resource.html)」を参照してください。

# を使用した HealthOmics の例 AWS CLI
<a name="cli_2_omics_code_examples"></a>

次のコード例は、HealthOmics AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `abort-multipart-read-set-upload`
<a name="omics_AbortMultipartReadSetUpload_cli_2_topic"></a>

次のコード例は、`abort-multipart-read-set-upload` を使用する方法を示しています。

**AWS CLI**  
**マルチパート読み取りセットのアップロードを停止するには**  
次の `abort-multipart-read-set-upload` の例では、HealthOmics シーケンスストアへのマルチパート読み取りセットのアップロードを停止します。  

```
aws omics abort-multipart-read-set-upload \
    --sequence-store-id 0123456789 \
    --upload-id 1122334455
```
このコマンドでは何も出力されません。  
詳細については、「*AWS HealthOmics User Guide*」の「[Direct upload to a sequence store](https://docs.aws.amazon.com/omics/latest/dev/synchronous-uploads.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AbortMultipartReadSetUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/abort-multipart-read-set-upload.html)」を参照してください。

### `accept-share`
<a name="omics_AcceptShare_cli_2_topic"></a>

次のコード例は、`accept-share` を使用する方法を示しています。

**AWS CLI**  
**分析ストアデータの共有を受け入れるには**  
次の `accept-share` の例では、HealthOmics 分析ストアデータの共有を受け入れます。  

```
aws omics accept-share \
    ----share-id "495c21bedc889d07d0ab69d710a6841e-dd75ab7a1a9c384fa848b5bd8e5a7e0a"
```
出力:  

```
{
    "status": "ACTIVATING"
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Cross-account sharing](https://docs.aws.amazon.com/omics/latest/dev/cross-account-sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/accept-share.html)」を参照してください。

### `batch-delete-read-set`
<a name="omics_BatchDeleteReadSet_cli_2_topic"></a>

次のコード例は、`batch-delete-read-set` を使用する方法を示しています。

**AWS CLI**  
**複数の読み取りセットを削除するには**  
次の `batch-delete-read-set` の例では、2 つの読み取りセットを削除します。  

```
aws omics batch-delete-read-set \
    --sequence-store-id 1234567890 \
    --ids 1234567890 0123456789
```
指定された読み取りセットの削除でエラーが発生した場合、サービスはエラーリストを返します。  

```
{
    "errors": [
        {
            "code": "",
            "id": "0123456789",
            "message": "The specified readset does not exist."
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDeleteReadSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/batch-delete-read-set.html)」を参照してください。

### `cancel-annotation-import-job`
<a name="omics_CancelAnnotationImportJob_cli_2_topic"></a>

次のコード例は、`cancel-annotation-import-job` を使用する方法を示しています。

**AWS CLI**  
**注釈インポートジョブをキャンセルするには**  
次の `cancel-annotation-import-job` の例では、ID `04f57618-xmpl-4fd0-9349-e5a85aefb997` の注釈インポートジョブをキャンセルします。  

```
aws omics cancel-annotation-import-job \
    --job-id 04f57618-xmpl-4fd0-9349-e5a85aefb997
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelAnnotationImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/cancel-annotation-import-job.html)」を参照してください。

### `cancel-run`
<a name="omics_CancelRun_cli_2_topic"></a>

次のコード例は、`cancel-run` を使用する方法を示しています。

**AWS CLI**  
**実行をキャンセルするには**  
次の `cancel-run` の例では、ID `1234567` の実行をキャンセルします。  

```
aws omics cancel-run \
    --id 1234567
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Run lifecycle in a workflow](https://docs.aws.amazon.com/omics/latest/dev/monitoring-runs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/cancel-run.html)」を参照してください。

### `cancel-variant-import-job`
<a name="omics_CancelVariantImportJob_cli_2_topic"></a>

次のコード例は、`cancel-variant-import-job` を使用する方法を示しています。

**AWS CLI**  
**バリアントインポートジョブをキャンセルするには**  
次の `cancel-variant-import-job` の例では、ID `69cb65d6-xmpl-4a4a-9025-4565794b684e` のバリアントインポートジョブをキャンセルします。  

```
aws omics cancel-variant-import-job \
    --job-id 69cb65d6-xmpl-4a4a-9025-4565794b684e
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelVariantImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/cancel-variant-import-job.html)」を参照してください。

### `complete-multipart-read-set-upload`
<a name="omics_CompleteMultipartReadSetUpload_cli_2_topic"></a>

次のコード例は、`complete-multipart-read-set-upload` を使用する方法を示しています。

**AWS CLI**  
**すべてのコンポーネントをアップロードした後で、マルチパートアップロードを終了するには**  
次の `complete-multipart-read-set-upload` の例では、すべてのコンポーネントがアップロードされた後で、シーケンスストアへのマルチパートアップロードを終了します。  

```
aws omics complete-multipart-read-set-upload \
    --sequence-store-id 0123456789 \
    --upload-id 1122334455 \
    --parts '[{"checksum":"gaCBQMe+rpCFZxLpoP6gydBoXaKKDA/Vobh5zBDb4W4=","partNumber":1,"partSource":"SOURCE1"}]'
```
出力:  

```
{
    "readSetId": "0000000001"
    "readSetId": "0000000002"
    "readSetId": "0000000003"
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Direct upload to a sequence store](https://docs.aws.amazon.com/omics/latest/dev/synchronous-uploads.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CompleteMultipartReadSetUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/complete-multipart-read-set-upload.html)」を参照してください。

### `create-annotation-store-version`
<a name="omics_CreateAnnotationStoreVersion_cli_2_topic"></a>

次のコード例は、`create-annotation-store-version` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアの新しいバージョンを作成するには**  
次の `create-annotation-store-version` の例では、注釈ストアの新しいバージョンを作成します。  

```
aws omics create-annotation-store-version \
    --name my_annotation_store \
    --version-name my_version
```
出力:  

```
{
    "creationTime": "2023-07-21T17:15:49.251040+00:00",
    "id": "3b93cdef69d2",
    "name": "my_annotation_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:555555555555:referenceStore/6505293348/reference/5987565360"
    },
    "status": "CREATING",
    "versionName": "my_version"
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Creating new versions of annotation stores](https://docs.aws.amazon.com/omics/latest/dev/annotation-store-versioning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAnnotationStoreVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-annotation-store-version.html)」を参照してください。

### `create-annotation-store`
<a name="omics_CreateAnnotationStore_cli_2_topic"></a>

次のコード例は、`create-annotation-store` を使用する方法を示しています。

**AWS CLI**  
**例 1: VCF 注釈ストアを作成するには**  
次の `create-annotation-store` の例では、VCF 形式の注釈ストアを作成します。  

```
aws omics create-annotation-store \
    --name my_ann_store \
    --store-format VCF \
    --reference referenceArn=arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890
```
出力:  

```
{
    "creationTime": "2022-11-23T22:48:39.226492Z",
    "id": "0a91xmplc71f",
    "name": "my_ann_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
    },
    "status": "CREATING",
    "storeFormat": "VCF"
}
```
**例 2: TSV 注釈ストアを作成するには**  
次の `create-annotation-store` の例では、TSV 形式の注釈ストアを作成します。  

```
aws omics create-annotation-store \
    --name tsv_ann_store \
    --store-format TSV \
    --reference referenceArn=arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890 \
    --store-options file://tsv-store-options.json
```
`tsv-store-options.json` は注釈の形式オプションを設定します。  

```
{
    "tsvStoreOptions": {
        "annotationType": "CHR_START_END_ZERO_BASE",
        "formatToHeader": {
            "CHR": "chromosome",
            "START": "start",
            "END": "end"
        },
        "schema": [
            {
                "chromosome": "STRING"
            },
            {
                "start": "LONG"
            },
            {
                "end": "LONG"
            },
            {
                "name": "STRING"
            }
        ]
    }
}
```
出力:  

```
{
    "creationTime": "2022-11-30T01:28:08.525586Z",
    "id": "861cxmpl96b0",
    "name": "tsv_ann_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
    },
    "status": "CREATING",
    "storeFormat": "TSV",
    "storeOptions": {
        "tsvStoreOptions": {
            "annotationType": "CHR_START_END_ZERO_BASE",
            "formatToHeader": {
                "CHR": "chromosome",
                "END": "end",
                "START": "start"
            },
            "schema": [
                {
                    "chromosome": "STRING"
                },
                {
                    "start": "LONG"
                },
                {
                    "end": "LONG"
                },
                {
                    "name": "STRING"
                }
            ]
        }
    }
}
```
詳細については、「Amazon Omics Developer Guide」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAnnotationStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-annotation-store.html)」を参照してください。

### `create-multipart-read-set-upload`
<a name="omics_CreateMultipartReadSetUpload_cli_2_topic"></a>

次のコード例は、`create-multipart-read-set-upload` を使用する方法を示しています。

**AWS CLI**  
**マルチパート読み取りセットのアップロードを開始するには**  
次の `create-multipart-read-set-upload` の例では、マルチパート読み取りセットのアップロードを開始します。  

```
aws omics create-multipart-read-set-upload \
    --sequence-store-id 0123456789 \
    --name HG00146 \
    --source-file-type FASTQ \
    --subject-id mySubject\
    --sample-id mySample\
    --description "FASTQ for HG00146"\
    --generated-from "1000 Genomes"
```
出力:  

```
{
    "creationTime": "2022-07-13T23:25:20Z",
    "description": "FASTQ for HG00146",
    "generatedFrom": "1000 Genomes",
    "name": "HG00146",
    "sampleId": "mySample",
    "sequenceStoreId": "0123456789",
    "sourceFileType": "FASTQ",
    "subjectId": "mySubject",
    "uploadId": "1122334455"
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Direct upload to a sequence store](https://docs.aws.amazon.com/omics/latest/dev/synchronous-uploads.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMultipartReadSetUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-multipart-read-set-upload.html)」を参照してください。

### `create-reference-store`
<a name="omics_CreateReferenceStore_cli_2_topic"></a>

次のコード例は、`create-reference-store` を使用する方法を示しています。

**AWS CLI**  
**参照ストアを作成するには**  
次の `create-reference-store` の例では、参照ストア `my-ref-store` を作成します。  

```
aws omics create-reference-store \
    --name my-ref-store
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890",
    "creationTime": "2022-11-22T22:13:25.947Z",
    "id": "1234567890",
    "name": "my-ref-store"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReferenceStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-reference-store.html)」を参照してください。

### `create-run-group`
<a name="omics_CreateRunGroup_cli_2_topic"></a>

次のコード例は、`create-run-group` を使用する方法を示しています。

**AWS CLI**  
**実行グループを作成するには**  
次の `create-run-group` の例では、`cram-converter` という名前の実行グループを作成します。  

```
aws omics create-run-group \
    --name cram-converter \
    --max-cpus 20 \
    --max-gpus 10 \
    --max-duration 600 \
    --max-runs 5
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:runGroup/1234567",
    "id": "1234567",
    "tags": {}
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Creating run groups](https://docs.aws.amazon.com/omics/latest/dev/creating-run-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRunGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-run-group.html)」を参照してください。

### `create-sequence-store`
<a name="omics_CreateSequenceStore_cli_2_topic"></a>

次のコード例は、`create-sequence-store` を使用する方法を示しています。

**AWS CLI**  
**シーケンスストアを作成するには**  
次の `create-sequence-store` の例では、シーケンスストアを作成します。  

```
aws omics create-sequence-store \
    --name my-seq-store
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:sequenceStore/1234567890",
    "creationTime": "2022-11-23T01:24:33.629Z",
    "id": "1234567890",
    "name": "my-seq-store"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSequenceStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-sequence-store.html)」を参照してください。

### `create-share`
<a name="omics_CreateShare_cli_2_topic"></a>

次のコード例は、`create-share` を使用する方法を示しています。

**AWS CLI**  
**HealthOmics 分析ストアの共有を作成するには**  
次の `create-share` の例は、アカウント外のサブスクライバーが受け入れることができる HealthOmics 分析ストアの共有を作成する方法を示しています。  

```
aws omics create-share \
    --resource-arn "arn:aws:omics:us-west-2:555555555555:variantStore/omics_dev_var_store" \
    --principal-subscriber "123456789012" \
    --name "my_Share-123"
```
出力:  

```
{
    "shareId": "495c21bedc889d07d0ab69d710a6841e-dd75ab7a1a9c384fa848b5bd8e5a7e0a",
    "name": "my_Share-123",
    "status": "PENDING"
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Cross-acount sharing](https://docs.aws.amazon.com/omics/latest/dev/cross-account-sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-share.html)」を参照してください。

### `create-variant-store`
<a name="omics_CreateVariantStore_cli_2_topic"></a>

次のコード例は、`create-variant-store` を使用する方法を示しています。

**AWS CLI**  
**バリアントストアを作成するには**  
次の `create-variant-store` の例では、`my_var_store` という名前のバリアントストアを作成します。  

```
aws omics create-variant-store \
    --name my_var_store \
    --reference referenceArn=arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890
```
出力:  

```
{
    "creationTime": "2022-11-23T22:09:07.534499Z",
    "id": "02dexmplcfdd",
    "name": "my_var_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
    },
    "status": "CREATING"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVariantStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-variant-store.html)」を参照してください。

### `create-workflow`
<a name="omics_CreateWorkflow_cli_2_topic"></a>

次のコード例は、`create-workflow` を使用する方法を示しています。

**AWS CLI**  
**ワークフローを作成するには**  
次の `create-workflow` の例では、WDL ワークフローを作成します。  

```
aws omics create-workflow \
    --name cram-converter \
    --engine WDL \
    --definition-zip fileb://workflow-crambam.zip \
    --parameter-template file://workflow-params.json
```
`workflow-crambam.zip` は、ワークフロー定義を含む ZIP アーカイブです。`workflow-params.json` は、ワークフローのランタイムパラメータを定義します。  

```
{
    "ref_fasta" : {
        "description": "Reference genome fasta file",
        "optional": false
    },
    "ref_fasta_index" : {
        "description": "Index of the reference genome fasta file",
        "optional": false
    },
    "ref_dict" : {
        "description": "dictionary file for 'ref_fasta'",
        "optional": false
    },
    "input_cram" : {
        "description": "The Cram file to convert to BAM",
        "optional": false
    },
    "sample_name" : {
        "description": "The name of the input sample, used to name the output BAM",
        "optional": false
    }
}
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:workflow/1234567",
    "id": "1234567",
    "status": "CREATING",
    "tags": {}
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Creating private workflows](https://docs.aws.amazon.com/omics/latest/dev/workflows-setup.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWorkflow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/create-workflow.html)」を参照してください。

### `delete-annotation-store-versions`
<a name="omics_DeleteAnnotationStoreVersions_cli_2_topic"></a>

次のコード例は、`delete-annotation-store-versions` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアのバージョンを削除するには**  
次の `delete-annotation-store-versions` の例では、注釈ストアのバージョンを削除します。  

```
aws omics delete-annotation-store-versions \
    --name my_annotation_store \
    --versions my_version
```
出力:  

```
{
    "errors": []
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Creating new versions of annotation stores](https://docs.aws.amazon.com/omics/latest/dev/annotation-store-versioning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAnnotationStoreVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-annotation-store-versions.html)」を参照してください。

### `delete-annotation-store`
<a name="omics_DeleteAnnotationStore_cli_2_topic"></a>

次のコード例は、`delete-annotation-store` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアを削除するには**  
次の `delete-annotation-store` の例では、`my_vcf_store` という名前の注釈ストアを削除します。  

```
aws omics delete-annotation-store \
    --name my_vcf_store
```
出力:  

```
{
    "status": "DELETING"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAnnotationStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-annotation-store.html)」を参照してください。

### `delete-reference-store`
<a name="omics_DeleteReferenceStore_cli_2_topic"></a>

次のコード例は、`delete-reference-store` を使用する方法を示しています。

**AWS CLI**  
**参照ストアを削除するには**  
次の `delete-reference-store` の例では、ID `1234567890` の参照ストアを削除します。  

```
aws omics delete-reference-store \
    --id 1234567890
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReferenceStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-reference-store.html)」を参照してください。

### `delete-reference`
<a name="omics_DeleteReference_cli_2_topic"></a>

次のコード例は、`delete-reference` を使用する方法を示しています。

**AWS CLI**  
**参照を削除するには**  
次の `delete-reference` の例では、参照を削除します。  

```
aws omics delete-reference \
    --reference-store-id 1234567890 \
    --id 1234567890
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-reference.html)」を参照してください。

### `delete-run-group`
<a name="omics_DeleteRunGroup_cli_2_topic"></a>

次のコード例は、`delete-run-group` を使用する方法を示しています。

**AWS CLI**  
**実行グループを削除するには**  
次の `delete-run-group` の例では、ID `1234567` の実行グループを削除します。  

```
aws omics delete-run-group \
    --id 1234567
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Deleting runs and run groups](https://docs.aws.amazon.com/omics/latest/dev/deleting-workflows-and-runs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRunGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-run-group.html)」を参照してください。

### `delete-run`
<a name="omics_DeleteRun_cli_2_topic"></a>

次のコード例は、`delete-run` を使用する方法を示しています。

**AWS CLI**  
**ワークフローの実行を削除するには**  
次の `delete-run` の例では、ID `1234567` の実行を削除します。  

```
aws omics delete-run \
    --id 1234567
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Deleting runs and run groups](https://docs.aws.amazon.com/omics/latest/dev/deleting-workflows-and-runs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-run.html)」を参照してください。

### `delete-sequence-store`
<a name="omics_DeleteSequenceStore_cli_2_topic"></a>

次のコード例は、`delete-sequence-store` を使用する方法を示しています。

**AWS CLI**  
**シーケンスストアを削除するには**  
次の `delete-sequence-store` の例では、ID `1234567890` のシーケンスストアを削除します。  

```
aws omics delete-sequence-store \
    --id 1234567890
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSequenceStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-sequence-store.html)」を参照してください。

### `delete-share`
<a name="omics_DeleteShare_cli_2_topic"></a>

次のコード例は、`delete-share` を使用する方法を示しています。

**AWS CLI**  
**HealthOmics 分析データの共有を削除するには**  
次の `delete-share` の例では、分析データのクロスアカウント共有を削除します。  

```
aws omics delete-share \
    --share-id "495c21bedc889d07d0ab69d710a6841e-dd75ab7a1a9c384fa848b5bd8e5a7e0a"
```
出力:  

```
{
    "status": "DELETING"
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Cross-account sharing](https://docs.aws.amazon.com/omics/latest/dev/cross-account-sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-share.html)」を参照してください。

### `delete-variant-store`
<a name="omics_DeleteVariantStore_cli_2_topic"></a>

次のコード例は、`delete-variant-store` を使用する方法を示しています。

**AWS CLI**  
**バリアントストアを削除するには**  
次の `delete-variant-store` の例では、`my_var_store` というバリアントストアを削除します。  

```
aws omics delete-variant-store \
    --name my_var_store
```
出力:  

```
{
    "status": "DELETING"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVariantStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-variant-store.html)」を参照してください。

### `delete-workflow`
<a name="omics_DeleteWorkflow_cli_2_topic"></a>

次のコード例は、`delete-workflow` を使用する方法を示しています。

**AWS CLI**  
**ワークフローを削除するには**  
次の `delete-workflow` の例では、ID `1234567` のワークフローを削除します。  

```
aws omics delete-workflow \
    --id 1234567
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Delete a private workflow](https://docs.aws.amazon.com/omics/latest/dev/delete-private-workflow.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWorkflow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/delete-workflow.html)」を参照してください。

### `get-annotation-import-job`
<a name="omics_GetAnnotationImportJob_cli_2_topic"></a>

次のコード例は、`get-annotation-import-job` を使用する方法を示しています。

**AWS CLI**  
**注釈インポートジョブを表示するには**  
次の `get-annotation-import-job` の例では、注釈インポートジョブの詳細を取得します。  

```
aws omics get-annotation-import-job \
    --job-id 984162c7-xmpl-4d23-ab47-286f7950bfbf
```
出力:  

```
{
    "creationTime": "2022-11-30T01:40:11.017746Z",
    "destinationName": "tsv_ann_store",
    "id": "984162c7-xmpl-4d23-ab47-286f7950bfbf",
    "items": [
        {
            "jobStatus": "COMPLETED",
            "source": "s3://omics-artifacts-01d6xmpl4e72dd32/targetedregions.bed.gz"
        }
    ],
    "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
    "runLeftNormalization": false,
    "status": "COMPLETED",
    "updateTime": "2022-11-30T01:42:39.134009Z"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAnnotationImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-annotation-import-job.html)」を参照してください。

### `get-annotation-store-version`
<a name="omics_GetAnnotationStoreVersion_cli_2_topic"></a>

次のコード例は、`get-annotation-store-version` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアバージョンのメタデータを取得するには**  
次の `get-annotation-store-version` の例では、リクエストされた注釈ストアバージョンのメタデータを取得します。  

```
aws omics get-annotation-store-version \
    --name my_annotation_store \
    --version-name my_version
```
出力:  

```
{
    "storeId": "4934045d1c6d",
    "id": "2a3f4a44aa7b",
    "status": "ACTIVE",
    "versionArn": "arn:aws:omics:us-west-2:555555555555:annotationStore/my_annotation_store/version/my_version",
    "name": "my_annotation_store",
    "versionName": "my_version",
    "creationTime": "2023-07-21T17:15:49.251040+00:00",
    "updateTime": "2023-07-21T17:15:56.434223+00:00",
    "statusMessage": "",
    "versionSizeBytes": 0
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Creating new versions of annotation stores](https://docs.aws.amazon.com/omics/latest/dev/annotation-store-versioning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAnnotationStoreVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-annotation-store-version.html)」を参照してください。

### `get-annotation-store`
<a name="omics_GetAnnotationStore_cli_2_topic"></a>

次のコード例は、`get-annotation-store` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアを表示するには**  
次の `get-annotation-store` の例では、`my_ann_store` という名前の注釈ストアの詳細を取得します。  

```
aws omics get-annotation-store \
    --name my_ann_store
```
出力:  

```
{
    "creationTime": "2022-11-23T22:48:39.226492Z",
    "id": "0a91xmplc71f",
    "name": "my_ann_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
    },
    "status": "CREATING",
    "storeArn": "arn:aws:omics:us-west-2:123456789012:annotationStore/my_ann_store",
    "storeFormat": "VCF",
    "storeSizeBytes": 0,
    "tags": {}
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAnnotationStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-annotation-store.html)」を参照してください。

### `get-read-set-activation-job`
<a name="omics_GetReadSetActivationJob_cli_2_topic"></a>

次のコード例は、`get-read-set-activation-job` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットのアクティベーションジョブを表示するには**  
次の `get-read-set-activation-job` の例では、読み取りセットのアクティベーションジョブの詳細を取得します。  

```
aws omics get-read-set-activation-job \
    --sequence-store-id 1234567890 \
    --id 1234567890
```
出力:  

```
{
    "completionTime": "2022-12-06T22:33:42.828Z",
    "creationTime": "2022-12-06T22:32:45.213Z",
    "id": "1234567890",
    "sequenceStoreId": "1234567890",
    "sources": [
        {
            "readSetId": "1234567890",
            "status": "FINISHED",
            "statusMessage": "No activation needed as read set is already in ACTIVATING or ACTIVE state."
        }
    ],
    "status": "COMPLETED",
    "statusMessage": "The job completed successfully."
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReadSetActivationJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-read-set-activation-job.html)」を参照してください。

### `get-read-set-export-job`
<a name="omics_GetReadSetExportJob_cli_2_topic"></a>

次のコード例は、`get-read-set-export-job` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットのエクスポートジョブを表示するには**  
次の `get-read-set-export-job` の例では、読み取りセットのエクスポートジョブの詳細を取得します。  

```
aws omics get-read-set-export-job \
    --sequence-store-id 1234567890 \
    --id 1234567890
```
出力:  

```
{
    "completionTime": "2022-12-06T22:39:14.491Z",
    "creationTime": "2022-12-06T22:37:18.612Z",
    "destination": "s3://omics-artifacts-01d6xmpl4e72dd32/read-set-export/",
    "id": "1234567890",
    "sequenceStoreId": "1234567890",
    "status": "COMPLETED",
    "statusMessage": "The job is submitted and will start soon."
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReadSetExportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-read-set-export-job.html)」を参照してください。

### `get-read-set-import-job`
<a name="omics_GetReadSetImportJob_cli_2_topic"></a>

次のコード例は、`get-read-set-import-job` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットのインポートジョブを表示するには**  
次の `get-read-set-import-job` の例では、読み取りセットのインポートジョブの詳細を取得します。  

```
aws omics get-read-set-import-job \
    --sequence-store-id 1234567890 \
    --id 1234567890
```
出力:  

```
{
    "creationTime": "2022-11-23T01:36:38.158Z",
    "id": "1234567890",
    "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
    "sequenceStoreId": "1234567890",
    "sources": [
        {
            "name": "HG00100",
            "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
            "sampleId": "bam-sample",
            "sourceFileType": "BAM",
            "sourceFiles": {
                "source1": "s3://omics-artifacts-01d6xmpl4e72dd32/HG00100.chrom20.ILLUMINA.bwa.GBR.low_coverage.20101123.bam",
                "source2": ""
            },
            "status": "IN_PROGRESS",
            "statusMessage": "The source job is currently in progress.",
            "subjectId": "bam-subject",
            "tags": {
                "aws:omics:sampleId": "bam-sample",
                "aws:omics:subjectId": "bam-subject"
            }
        },
        {
            "name": "HG00146",
            "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
            "sampleId": "fastq-sample",
            "sourceFileType": "FASTQ",
            "sourceFiles": {
                "source1": "s3://omics-artifacts-01d6xmpl4e72dd32/SRR233106_1.filt.fastq.gz",
                "source2": "s3://omics-artifacts-01d6xmpl4e72dd32/SRR233106_2.filt.fastq.gz"
            },
            "status": "IN_PROGRESS",
            "statusMessage": "The source job is currently in progress.",
            "subjectId": "fastq-subject",
            "tags": {
                "aws:omics:sampleId": "fastq-sample",
                "aws:omics:subjectId": "fastq-subject"
            }
        },
        {
            "name": "HG00096",
            "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
            "sampleId": "cram-sample",
            "sourceFileType": "CRAM",
            "sourceFiles": {
                "source1": "s3://omics-artifacts-01d6xmpl4e72dd32/HG00096.alt_bwamem_GRCh38DH.20150718.GBR.low_coverage.cram",
                "source2": ""
            },
            "status": "IN_PROGRESS",
            "statusMessage": "The source job is currently in progress.",
            "subjectId": "cram-subject",
            "tags": {
                "aws:omics:sampleId": "cram-sample",
                "aws:omics:subjectId": "cram-subject"
            }
        }
    ],
    "status": "IN_PROGRESS",
    "statusMessage": "The job is currently in progress."
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReadSetImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-read-set-import-job.html)」を参照してください。

### `get-read-set-metadata`
<a name="omics_GetReadSetMetadata_cli_2_topic"></a>

次のコード例は、`get-read-set-metadata` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットを表示するには**  
次の `get-read-set-metadata` の例では、読み取りセットのファイルの詳細を取得します。  

```
aws omics get-read-set-metadata \
    --sequence-store-id 1234567890 \
    --id 1234567890
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:sequenceStore/1234567890/readSet/1234567890",
    "creationTime": "2022-11-23T21:55:00.515Z",
    "fileType": "FASTQ",
    "files": {
        "source1": {
            "contentLength": 310054739,
            "partSize": 104857600,
            "totalParts": 3
        },
        "source2": {
            "contentLength": 307846621,
            "partSize": 104857600,
            "totalParts": 3
        }
    },
    "id": "1234567890",
    "name": "HG00146",
    "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
    "sampleId": "fastq-sample",
    "sequenceInformation": {
        "alignment": "UNALIGNED",
        "totalBaseCount": 677717384,
        "totalReadCount": 8917334
    },
    "sequenceStoreId": "1234567890",
    "status": "ACTIVE",
    "subjectId": "fastq-subject"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReadSetMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-read-set-metadata.html)」を参照してください。

### `get-read-set`
<a name="omics_GetReadSet_cli_2_topic"></a>

次のコード例は、`get-read-set` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットをダウンロードするには**  
次の `get-read-set` の例では、読み取りセットのパート 3 を `1234567890.3.bam` としてダウンロードします。  

```
aws omics get-read-set \
    --sequence-store-id 1234567890 \
    --id 1234567890 \
    --part-number 3  1234567890.3.bam
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReadSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-read-set.html)」を参照してください。

### `get-reference-import-job`
<a name="omics_GetReferenceImportJob_cli_2_topic"></a>

次のコード例は、`get-reference-import-job` を使用する方法を示しています。

**AWS CLI**  
**参照インポートジョブを表示するには**  
次の `get-reference-import-job` の例では、参照インポートジョブの詳細を取得します。  

```
aws omics get-reference-import-job \
    --reference-store-id 1234567890 \
    --id 1234567890
```
出力:  

```
{
    "creationTime": "2022-11-22T22:25:41.124Z",
    "id": "1234567890",
    "referenceStoreId": "1234567890",
    "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
    "sources": [
        {
            "name": "assembly-38",
            "sourceFile": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta",
            "status": "IN_PROGRESS",
            "statusMessage": "The source job is currently in progress."
        }
    ],
    "status": "IN_PROGRESS",
    "statusMessage": "The job is currently in progress."
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReferenceImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-reference-import-job.html)」を参照してください。

### `get-reference-metadata`
<a name="omics_GetReferenceMetadata_cli_2_topic"></a>

次のコード例は、`get-reference-metadata` を使用する方法を示しています。

**AWS CLI**  
**参照を表示するには**  
次の `get-reference-metadata` の例では、参照の詳細を取得します。  

```
aws omics get-reference-metadata \
    --reference-store-id 1234567890 \
    --id 1234567890
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
    "creationTime": "2022-11-22T22:27:09.033Z",
    "files": {
        "index": {
            "contentLength": 160928,
            "partSize": 104857600,
            "totalParts": 1
        },
        "source": {
            "contentLength": 3249912778,
            "partSize": 104857600,
            "totalParts": 31
        }
    },
    "id": "1234567890",
    "md5": "7ff134953dcca8c8997453bbb80b6b5e",
    "name": "assembly-38",
    "referenceStoreId": "1234567890",
    "status": "ACTIVE",
    "updateTime": "2022-11-22T22:27:09.033Z"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReferenceMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-reference-metadata.html)」を参照してください。

### `get-reference-store`
<a name="omics_GetReferenceStore_cli_2_topic"></a>

次のコード例は、`get-reference-store` を使用する方法を示しています。

**AWS CLI**  
**参照ストアを表示するには**  
次の `get-reference-store` の例では、参照ストアの詳細を取得します。  

```
aws omics get-reference-store \
    --id 1234567890
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890",
    "creationTime": "2022-09-23T23:27:20.364Z",
    "id": "1234567890",
    "name": "my-rstore-0"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReferenceStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-reference-store.html)」を参照してください。

### `get-reference`
<a name="omics_GetReference_cli_2_topic"></a>

次のコード例は、`get-reference` を使用する方法を示しています。

**AWS CLI**  
**ゲノム参照をダウンロードするには**  
次の `get-reference` の例では、ゲノムのパート 1 を `hg38.1.fa` としてダウンロードします。  

```
aws omics get-reference \
    --reference-store-id 1234567890 \
    --id 1234567890 \
    --part-number 1 hg38.1.fa
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReference](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-reference.html)」を参照してください。

### `get-run-group`
<a name="omics_GetRunGroup_cli_2_topic"></a>

次のコード例は、`get-run-group` を使用する方法を示しています。

**AWS CLI**  
**実行グループを表示するには**  
次の `get-run-group` の例では、実行グループの詳細を取得します。  

```
aws omics get-run-group \
    --id 1234567
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:runGroup/1234567",
    "creationTime": "2022-12-01T00:58:42.915219Z",
    "id": "1234567",
    "maxCpus": 20,
    "maxDuration": 600,
    "name": "cram-convert",
    "tags": {}
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Creating run groups](https://docs.aws.amazon.com/omics/latest/dev/creating-run-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRunGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-run-group.html)」を参照してください。

### `get-run-task`
<a name="omics_GetRunTask_cli_2_topic"></a>

次のコード例は、`get-run-task` を使用する方法を示しています。

**AWS CLI**  
**タスクを表示するには**  
次の `get-run-task` の例では、ワークフロータスクの詳細を取得します。  

```
aws omics get-run-task \
    --id 1234567 \
    --task-id 1234567
```
出力:  

```
{
    "cpus": 1,
    "creationTime": "2022-11-30T23:13:00.718651Z",
    "logStream": "arn:aws:logs:us-west-2:123456789012:log-group:/aws/omics/WorkflowLog:log-stream:run/1234567/task/1234567",
    "memory": 15,
    "name": "CramToBamTask",
    "startTime": "2022-11-30T23:17:47.016Z",
    "status": "COMPLETED",
    "stopTime": "2022-11-30T23:18:21.503Z",
    "taskId": "1234567"
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Task lifecycle in a HealthOmics run](https://docs.aws.amazon.com/omics/latest/dev/workflow-run-tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRunTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-run-task.html)」を参照してください。

### `get-run`
<a name="omics_GetRun_cli_2_topic"></a>

次のコード例は、`get-run` を使用する方法を示しています。

**AWS CLI**  
**ワークフローの実行を表示するには**  
次の `get-run` の例では、ワークフロー実行の詳細を取得します。  

```
aws omics get-run \
    --id 1234567
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:run/1234567",
    "creationTime": "2022-11-30T22:58:22.615865Z",
    "digest": "sha256:c54bxmpl742dcc26f7fa1f10e37550ddd8f251f418277c0a58e895b801ed28cf",
    "id": "1234567",
    "name": "cram-to-bam",
    "outputUri": "s3://omics-artifacts-01d6xmpl4e72dd32/workflow-output/",
    "parameters": {
        "ref_dict": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.dict",
        "ref_fasta_index": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta.fai",
        "ref_fasta": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta",
        "sample_name": "NA12878",
        "input_cram": "s3://omics-artifacts-01d6xmpl4e72dd32/NA12878.cram"
    },
    "resourceDigests": {
        "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta.fai": "etag:f76371b113734a56cde236bc0372de0a",
        "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.dict": "etag:3884c62eb0e53fa92459ed9bff133ae6",
        "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta": "etag:e307d81c605fb91b7720a08f00276842-388",
        "s3://omics-artifacts-01d6xmpl4e72dd32/NA12878.cram": "etag:a9f52976381286c6143b5cc681671ec6"
    },
    "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
    "startedBy": "arn:aws:iam::123456789012:user/laptop-2020",
    "status": "STARTING",
    "tags": {},
    "workflowId": "1234567",
    "workflowType": "PRIVATE"
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Run lifecycle in a workflow‭](https://docs.aws.amazon.com/omics/latest/dev/monitoring-runs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-run.html)」を参照してください。

### `get-sequence-store`
<a name="omics_GetSequenceStore_cli_2_topic"></a>

次のコード例は、`get-sequence-store` を使用する方法を示しています。

**AWS CLI**  
**シーケンスストアを表示するには**  
次の `get-sequence-store` の例では、ID `1234567890` のシーケンスストアの詳細を取得します。  

```
aws omics get-sequence-store \
    --id 1234567890
```
出力:  

```
{
    "arn": "arn:aws:omics:us-east-1:123456789012:sequenceStore/1234567890",
    "creationTime": "2022-11-23T19:55:48.376Z",
    "id": "1234567890",
    "name": "my-seq-store"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSequenceStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-sequence-store.html)」を参照してください。

### `get-share`
<a name="omics_GetShare_cli_2_topic"></a>

次のコード例は、`get-share` を使用する方法を示しています。

**AWS CLI**  
**HealthOmics 分析データの共有に関するメタデータを取得するには**  
次の `get-share` の例では、分析データのクロスアカウント共有のメタデータを取得します。  

```
aws omics get-share \
    --share-id "495c21bedc889d07d0ab69d710a6841e-dd75ab7a1a9c384fa848b5bd8e5a7e0a"
```
出力:  

```
{
    "share": {
        "shareId": "495c21bedc889d07d0ab69d710a6841e-dd75ab7a1a9c384fa848b5bd8e5a7e0a",
        "name": "my_Share-123",
        "resourceArn": "arn:aws:omics:us-west-2:555555555555:variantStore/omics_dev_var_store",
        "principalSubscriber": "123456789012",
        "ownerId": "555555555555",
        "status": "PENDING"
    }
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Cross-account sharing](https://docs.aws.amazon.com/omics/latest/dev/cross-account-sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-share.html)」を参照してください。

### `get-variant-import-job`
<a name="omics_GetVariantImportJob_cli_2_topic"></a>

次のコード例は、`get-variant-import-job` を使用する方法を示しています。

**AWS CLI**  
**バリアントインポートジョブを表示するには**  
次の `get-variant-import-job` の例では、バリアントインポートジョブの詳細を取得します。  

```
aws omics get-variant-import-job \
    --job-id edd7b8ce-xmpl-47e2-bc99-258cac95a508
```
出力:  

```
{
    "creationTime": "2022-11-23T22:42:50.037812Z",
    "destinationName": "my_var_store",
    "id": "edd7b8ce-xmpl-47e2-bc99-258cac95a508",
    "items": [
        {
            "jobStatus": "IN_PROGRESS",
            "source": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.known_indels.vcf.gz"
        }
    ],
    "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
    "runLeftNormalization": false,
    "status": "IN_PROGRESS",
    "updateTime": "2022-11-23T22:43:05.898309Z"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVariantImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-variant-import-job.html)」を参照してください。

### `get-variant-store`
<a name="omics_GetVariantStore_cli_2_topic"></a>

次のコード例は、`get-variant-store` を使用する方法を示しています。

**AWS CLI**  
**バリアントストアを表示するには**  
次の `get-variant-store` の例では、バリアントストアの詳細を取得します。  

```
aws omics get-variant-store \
    --name my_var_store
```
出力:  

```
{
    "creationTime": "2022-11-23T22:09:07.534499Z",
    "id": "02dexmplcfdd",
    "name": "my_var_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
    },
    "status": "CREATING",
    "storeArn": "arn:aws:omics:us-west-2:123456789012:variantStore/my_var_store",
    "storeSizeBytes": 0,
    "tags": {},
    "updateTime": "2022-11-23T22:09:24.931711Z"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVariantStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-variant-store.html)」を参照してください。

### `get-workflow`
<a name="omics_GetWorkflow_cli_2_topic"></a>

次のコード例は、`get-workflow` を使用する方法を示しています。

**AWS CLI**  
**ワークフローを表示するには**  
次の `get-workflow` の例では、ID `1234567` のワークフローの詳細を取得します。  

```
aws omics get-workflow \
    --id 1234567
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:workflow/1234567",
    "creationTime": "2022-11-30T22:33:16.225368Z",
    "digest": "sha256:c54bxmpl742dcc26f7fa1f10e37550ddd8f251f418277c0a58e895b801ed28cf",
    "engine": "WDL",
    "id": "1234567",
    "main": "workflow-crambam.wdl",
    "name": "cram-converter",
    "parameterTemplate": {
        "ref_dict": {
            "description": "dictionary file for 'ref_fasta'"
        },
        "ref_fasta_index": {
            "description": "Index of the reference genome fasta file"
        },
        "ref_fasta": {
            "description": "Reference genome fasta file"
        },
        "input_cram": {
            "description": "The Cram file to convert to BAM"
        },
        "sample_name": {
            "description": "The name of the input sample, used to name the output BAM"
        }
    },
    "status": "ACTIVE",
    "statusMessage": "workflow-crambam.wdl\n    workflow CramToBamFlow\n        call CramToBamTask\n        call ValidateSamFile\n    task CramToBamTask\n    task ValidateSamFile\n",
    "tags": {},
    "type": "PRIVATE"
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Creating private workflows](https://docs.aws.amazon.com/omics/latest/dev/workflows-setup.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWorkflow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/get-workflow.html)」を参照してください。

### `list-annotation-import-jobs`
<a name="omics_ListAnnotationImportJobs_cli_2_topic"></a>

次のコード例は、`list-annotation-import-jobs` を使用する方法を示しています。

**AWS CLI**  
**注釈インポートジョブのリストを取得するには**  
次の `list-annotation-import-jobs` は、注釈インポートジョブのリストを取得します。  

```
aws omics list-annotation-import-jobs
```
出力:  

```
{
    "annotationImportJobs": [
        {
            "creationTime": "2022-11-30T01:39:41.478294Z",
            "destinationName": "gff_ann_store",
            "id": "18a9e792-xmpl-4869-a105-e5b602900444",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "runLeftNormalization": false,
            "status": "COMPLETED",
            "updateTime": "2022-11-30T01:47:09.145178Z"
        },
        {
            "creationTime": "2022-11-30T00:45:58.007838Z",
            "destinationName": "my_ann_store",
            "id": "4e9eafc8-xmpl-431e-a0b2-3bda27cb600a",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "runLeftNormalization": false,
            "status": "FAILED",
            "updateTime": "2022-11-30T00:47:01.706325Z"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAnnotationImportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-annotation-import-jobs.html)」を参照してください。

### `list-annotation-store-versions`
<a name="omics_ListAnnotationStoreVersions_cli_2_topic"></a>

次のコード例は、`list-annotation-store-versions` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアのすべてのバージョンを一覧表示するには**  
次の `list-annotation-store-versions` の例では、注釈ストアが存在するすべてのバージョンを一覧表示します。  

```
aws omics list-annotation-store-versions \
    --name my_annotation_store
```
出力:  

```
{
    "annotationStoreVersions": [
        {
        "storeId": "4934045d1c6d",
        "id": "2a3f4a44aa7b",
        "status": "CREATING",
        "versionArn": "arn:aws:omics:us-west-2:555555555555:annotationStore/my_annotation_store/version/my_version_2",
        "name": "my_annotation_store",
        "versionName": "my_version_2",
        "creation Time": "2023-07-21T17:20:59.380043+00:00",
        "versionSizeBytes": 0
},
{
     "storeId": "4934045d1c6d",
     "id": "4934045d1c6d",
     "status": "ACTIVE",
     "versionArn": "arn:aws:omics:us-west-2:555555555555:annotationStore/my_annotation_store/version/my_version_1",
     "name": "my_annotation_store",
     "versionName": "my_version_1",
     "creationTime": "2023-07-21T17:15:49.251040+00:00",
     "updateTime": "2023-07-21T17:15:56.434223+00:00",
     "statusMessage": "",
     "versionSizeBytes": 0
     }

}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Creating new versions of annotation stores](https://docs.aws.amazon.com/omics/latest/dev/annotation-store-versioning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAnnotationStoreVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-annotation-store-versions.html)」を参照してください。

### `list-annotation-stores`
<a name="omics_ListAnnotationStores_cli_2_topic"></a>

次のコード例は、`list-annotation-stores` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアのリストを取得するには**  
次の `list-annotation-stores` の例では、注釈ストアのリストを取得します。  

```
aws omics list-annotation-stores
```
出力:  

```
{
    "annotationStores": [
        {
            "creationTime": "2022-11-23T22:48:39.226492Z",
            "id": "0a91xmplc71f",
            "name": "my_ann_store",
            "reference": {
                "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
            },
            "status": "ACTIVE",
            "statusMessage": "",
            "storeArn": "arn:aws:omics:us-west-2:123456789012:annotationStore/my_ann_store",
            "storeFormat": "VCF",
            "storeSizeBytes": 0,
            "updateTime": "2022-11-23T22:53:27.372840Z"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAnnotationStores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-annotation-stores.html)」を参照してください。

### `list-multipart-read-set-uploads`
<a name="omics_ListMultipartReadSetUploads_cli_2_topic"></a>

次のコード例は、`list-multipart-read-set-uploads` を使用する方法を示しています。

**AWS CLI**  
**すべてのマルチパート読み取りセットのアップロードとそのステータスを一覧表示するには**  
次の `list-multipart-read-set-uploads` の例では、すべてのマルチパート読み取りセットのアップロードとそのステータスを一覧表示します。  

```
aws omics list-multipart-read-set-uploads \
    --sequence-store-id 0123456789
```
出力:  

```
{
"uploads":
    [
        {
           "sequenceStoreId": "0123456789",
           "uploadId": "8749584421",
           "sourceFileType": "FASTQ",
            "subjectId": "mySubject",
            "sampleId": "mySample",
            "generatedFrom": "1000 Genomes",
            "name": "HG00146",
            "description": "FASTQ for HG00146",
            "creationTime": "2023-11-29T19:22:51.349298+00:00"
        },
        {
            "sequenceStoreId": "0123456789",
            "uploadId": "5290538638",
            "sourceFileType": "BAM",
            "subjectId": "mySubject",
            "sampleId": "mySample",
            "generatedFrom": "1000 Genomes",
            "referenceArn": "arn:aws:omics:us-west-2:845448930428:referenceStore/8168613728/reference/2190697383",
            "name": "HG00146",
            "description": "BAM for HG00146",
            "creationTime": "2023-11-29T19:23:33.116516+00:00"
        },
        {
            "sequenceStoreId": "0123456789",
            "uploadId": "4174220862",
            "sourceFileType": "BAM",
            "subjectId": "mySubject",
            "sampleId": "mySample",
            "generatedFrom": "1000 Genomes",
            "referenceArn": "arn:aws:omics:us-west-2:845448930428:referenceStore/8168613728/reference/2190697383",
            "name": "HG00147",
            "description": "BAM for HG00147",
            "creationTime": "2023-11-29T19:23:47.007866+00:00"
        }
    ]
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Direct upload to a sequence store](https://docs.aws.amazon.com/omics/latest/dev/synchronous-uploads.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMultipartReadSetUploads](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-multipart-read-set-uploads.html)」を参照してください。

### `list-read-set-activation-jobs`
<a name="omics_ListReadSetActivationJobs_cli_2_topic"></a>

次のコード例は、`list-read-set-activation-jobs` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットのアクティベーションジョブのリストを取得するには**  
次の `list-read-set-activation-jobs` の例では、ID `1234567890` のシーケンスストアのアクティベーションジョブのリストを取得します。  

```
aws omics list-read-set-activation-jobs \
    --sequence-store-id 1234567890
```
出力:  

```
{
    "activationJobs": [
        {
            "completionTime": "2022-12-06T22:33:42.828Z",
            "creationTime": "2022-12-06T22:32:45.213Z",
            "id": "1234567890",
            "sequenceStoreId": "1234567890",
            "status": "COMPLETED"
        },
        {
            "creationTime": "2022-12-06T22:35:10.100Z",
            "id": "1234567890",
            "sequenceStoreId": "1234567890",
            "status": "IN_PROGRESS"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReadSetActivationJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-read-set-activation-jobs.html)」を参照してください。

### `list-read-set-export-jobs`
<a name="omics_ListReadSetExportJobs_cli_2_topic"></a>

次のコード例は、`list-read-set-export-jobs` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットのエクスポートジョブのリストを取得するには**  
次の `list-read-set-export-jobs` の例では、ID `1234567890` のシーケンスストアのエクスポートジョブのリストを取得します。  

```
aws omics list-read-set-export-jobs \
    --sequence-store-id 1234567890
```
出力:  

```
{
    "exportJobs": [
        {
            "completionTime": "2022-12-06T22:39:14.491Z",
            "creationTime": "2022-12-06T22:37:18.612Z",
            "destination": "s3://omics-artifacts-01d6xmpl4e72dd32/read-set-export/",
            "id": "1234567890",
            "sequenceStoreId": "1234567890",
            "status": "COMPLETED"
        },
        {
            "creationTime": "2022-12-06T22:38:04.871Z",
            "destination": "s3://omics-artifacts-01d6xmpl4e72dd32/read-set-export/",
            "id": "1234567890",
            "sequenceStoreId": "1234567890",
            "status": "IN_PROGRESS"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReadSetExportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-read-set-export-jobs.html)」を参照してください。

### `list-read-set-import-jobs`
<a name="omics_ListReadSetImportJobs_cli_2_topic"></a>

次のコード例は、`list-read-set-import-jobs` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットインポートジョブのリストを取得するには**  
次の `list-read-set-import-jobs` の例では、ID `1234567890` のシーケンスストアのインポートジョブのリストを取得します。  

```
aws omics list-read-set-import-jobs \
    --sequence-store-id 1234567890
```
出力:  

```
{
    "importJobs": [
        {
            "completionTime": "2022-11-29T18:17:49.244Z",
            "creationTime": "2022-11-29T17:32:47.700Z",
            "id": "1234567890",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "sequenceStoreId": "1234567890",
            "status": "COMPLETED"
        },
        {
            "completionTime": "2022-11-23T22:01:34.090Z",
            "creationTime": "2022-11-23T21:52:43.289Z",
            "id": "1234567890",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "sequenceStoreId": "1234567890",
            "status": "COMPLETED_WITH_FAILURES"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReadSetImportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-read-set-import-jobs.html)」を参照してください。

### `list-read-set-upload-parts`
<a name="omics_ListReadSetUploadParts_cli_2_topic"></a>

次のコード例は、`list-read-set-upload-parts` を使用する方法を示しています。

**AWS CLI**  
**シーケンスストアのリクエストされたマルチパートアップロード内のすべてのパートを一覧表示するには**  
次の `list-read-set-upload-parts` の例では、シーケンスストアのリクエストされたマルチパートアップロードのすべてのパートを一覧表示します。  

```
aws omics list-read-set-upload-parts \
    --sequence-store-id 0123456789 \
    --upload-id 1122334455 \
    --part-source SOURCE1
```
出力:  

```
{
    "parts": [
        {
            "partNumber": 1,
            "partSize": 94371840,
            "file": "SOURCE1",
            "checksum": "984979b9928ae8d8622286c4a9cd8e99d964a22d59ed0f5722e1733eb280e635",
            "lastUpdatedTime": "2023-02-02T20:14:47.533000+00:00"
        }
        {
            "partNumber": 2,
            "partSize": 10471840,
            "file": "SOURCE1",
            "checksum": "984979b9928ae8d8622286c4a9cd8e99d964a22d59ed0f5722e1733eb280e635",
            "lastUpdatedTime": "2023-02-02T20:14:47.533000+00:00"
        }
      ]

}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Direct upload to a sequence store](https://docs.aws.amazon.com/omics/latest/dev/synchronous-uploads.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReadSetUploadParts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-read-set-upload-parts.html)」を参照してください。

### `list-read-sets`
<a name="omics_ListReadSets_cli_2_topic"></a>

次のコード例は、`list-read-sets` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットのリストを取得するには**  
次の `list-read-sets` の例では、ID `1234567890` のシーケンスストアの読み取りセットのリストを取得します。  

```
aws omics list-read-sets \
    --sequence-store-id 1234567890
```
出力:  

```
{
    "readSets": [
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:sequenceStore/1234567890/readSet/1234567890",
            "creationTime": "2022-11-23T21:55:00.515Z",
            "fileType": "FASTQ",
            "id": "1234567890",
            "name": "HG00146",
            "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
            "sampleId": "fastq-sample",
            "sequenceStoreId": "1234567890",
            "status": "ACTIVE",
            "subjectId": "fastq-subject"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReadSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-read-sets.html)」を参照してください。

### `list-reference-import-jobs`
<a name="omics_ListReferenceImportJobs_cli_2_topic"></a>

次のコード例は、`list-reference-import-jobs` を使用する方法を示しています。

**AWS CLI**  
**参照インポートジョブのリストを取得するには**  
次の `list-reference-import-jobs` の例では、ID `1234567890` の参照ストアの参照インポートジョブのリストを取得します。  

```
aws omics list-reference-import-jobs \
    --reference-store-id 1234567890
```
出力:  

```
{
    "importJobs": [
        {
            "completionTime": "2022-11-23T19:54:58.204Z",
            "creationTime": "2022-11-23T19:53:20.729Z",
            "id": "1234567890",
            "referenceStoreId": "1234567890",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "status": "COMPLETED"
        },
        {
            "creationTime": "2022-11-23T20:34:03.250Z",
            "id": "1234567890",
            "referenceStoreId": "1234567890",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "status": "IN_PROGRESS"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReferenceImportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-reference-import-jobs.html)」を参照してください。

### `list-reference-stores`
<a name="omics_ListReferenceStores_cli_2_topic"></a>

次のコード例は、`list-reference-stores` を使用する方法を示しています。

**AWS CLI**  
**参照ストアのリストを取得するには**  
次の `list-reference-stores` の例では、参照ストアのリストを取得します。  

```
aws omics list-reference-stores
```
出力:  

```
{
    "referenceStores": [
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890",
            "creationTime": "2022-11-22T22:13:25.947Z",
            "id": "1234567890",
            "name": "my-ref-store"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReferenceStores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-reference-stores.html)」を参照してください。

### `list-references`
<a name="omics_ListReferences_cli_2_topic"></a>

次のコード例は、`list-references` を使用する方法を示しています。

**AWS CLI**  
**参照のリストを取得するには**  
次の `list-references` の例では、ID `1234567890` の参照ストアのゲノム参照のリストを取得します。  

```
aws omics list-references \
    --reference-store-id 1234567890
```
出力:  

```
{
    "references": [
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
            "creationTime": "2022-11-22T22:27:09.033Z",
            "id": "1234567890",
            "md5": "7ff134953dcca8c8997453bbb80b6b5e",
            "name": "assembly-38",
            "referenceStoreId": "1234567890",
            "status": "ACTIVE",
            "updateTime": "2022-11-22T22:27:09.033Z"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReferences](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-references.html)」を参照してください。

### `list-run-groups`
<a name="omics_ListRunGroups_cli_2_topic"></a>

次のコード例は、`list-run-groups` を使用する方法を示しています。

**AWS CLI**  
**実行グループのリストを取得するには**  
次の `list-run-groups` の例では、実行グループのリストを取得します。  

```
aws omics list-run-groups
```
出力:  

```
{
    "items": [
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:runGroup/1234567",
            "creationTime": "2022-12-01T00:58:42.915219Z",
            "id": "1234567",
            "maxCpus": 20,
            "maxDuration": 600,
            "name": "cram-convert"
        }
    ]
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Creating run groups](https://docs.aws.amazon.com/omics/latest/dev/creating-run-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRunGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-run-groups.html)」を参照してください。

### `list-run-tasks`
<a name="omics_ListRunTasks_cli_2_topic"></a>

次のコード例は、`list-run-tasks` を使用する方法を示しています。

**AWS CLI**  
**タスクのリストを取得するには**  
次の `list-run-tasks` の例では、ワークフロー実行のタスクのリストを取得します。  

```
aws omics list-run-tasks \
    --id 1234567
```
出力:  

```
{
    "items": [
        {
            "cpus": 1,
            "creationTime": "2022-11-30T23:13:00.718651Z",
            "memory": 15,
            "name": "CramToBamTask",
            "startTime": "2022-11-30T23:17:47.016Z",
            "status": "COMPLETED",
            "stopTime": "2022-11-30T23:18:21.503Z",
            "taskId": "1234567"
        },
        {
            "cpus": 1,
            "creationTime": "2022-11-30T23:18:32.315606Z",
            "memory": 4,
            "name": "ValidateSamFile",
            "startTime": "2022-11-30T23:23:40.165Z",
            "status": "COMPLETED",
            "stopTime": "2022-11-30T23:24:14.766Z",
            "taskId": "1234567"
        }
    ]
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Task lifecycle in a HealthOmics run](https://docs.aws.amazon.com/omics/latest/dev/workflow-run-tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRunTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-run-tasks.html)」を参照してください。

### `list-runs`
<a name="omics_ListRuns_cli_2_topic"></a>

次のコード例は、`list-runs` を使用する方法を示しています。

**AWS CLI**  
**ワークフロー実行のリストを取得するには**  
次の `list-runs` の例では、ワークフロー実行のリストを取得します。  

```
aws omics list-runs
```
出力:  

```
{
    "items": [
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:run/1234567",
            "creationTime": "2022-12-02T23:20:01.202074Z",
            "id": "1234567",
            "name": "cram-to-bam",
            "priority": 1,
            "startTime": "2022-12-02T23:29:18.115Z",
            "status": "COMPLETED",
            "stopTime": "2022-12-02T23:57:54.428812Z",
            "storageCapacity": 10,
            "workflowId": "1234567"
        },
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:run/1234567",
            "creationTime": "2022-12-03T00:16:57.180066Z",
            "id": "1234567",
            "name": "cram-to-bam",
            "priority": 1,
            "startTime": "2022-12-03T00:26:50.233Z",
            "status": "FAILED",
            "stopTime": "2022-12-03T00:37:21.451340Z",
            "storageCapacity": 10,
            "workflowId": "1234567"
        },
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:run/1234567",
            "creationTime": "2022-12-05T17:57:08.444817Z",
            "id": "1234567",
            "name": "cram-to-bam",
            "status": "STARTING",
            "workflowId": "1234567"
        }
    ]
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Run lifecycle in a workflow‭](https://docs.aws.amazon.com/omics/latest/dev/monitoring-runs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRuns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-runs.html)」を参照してください。

### `list-sequence-stores`
<a name="omics_ListSequenceStores_cli_2_topic"></a>

次のコード例は、`list-sequence-stores` を使用する方法を示しています。

**AWS CLI**  
**シーケンスストアのリストを取得するには**  
次の `list-sequence-stores` の例では、シーケンスストアのリストを取得します。  

```
aws omics list-sequence-stores
```
出力:  

```
{
    "sequenceStores": [
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:sequenceStore/1234567890",
            "creationTime": "2022-11-23T01:24:33.629Z",
            "id": "1234567890",
            "name": "my-seq-store"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSequenceStores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-sequence-stores.html)」を参照してください。

### `list-shares`
<a name="omics_ListShares_cli_2_topic"></a>

次のコード例は、`list-shares` を使用する方法を示しています。

**AWS CLI**  
**HealthOmics 分析データの使用可能な共有を一覧表示するには**  
次の `list-shares` の例では、リソース所有者用に作成されたすべての共有を一覧表示します。  

```
aws omics list-shares \
    --resource-owner SELF
```
出力:  

```
{
    "shares": [
        {
            "shareId": "595c1cbd-a008-4eca-a887-954d30c91c6e",
            "name": "myShare",
            "resourceArn": "arn:aws:omics:us-west-2:555555555555:variantStore/store_1",
            "principalSubscriber": "123456789012",
            "ownerId": "555555555555",
            "status": "PENDING"
        }
        {
            "shareId": "39b65d0d-4368-4a19-9814-b0e31d73c10a",
            "name": "myShare3456",
            "resourceArn": "arn:aws:omics:us-west-2:555555555555:variantStore/store_2",
            "principalSubscriber": "123456789012",
            "ownerId": "555555555555",
            "status": "ACTIVE"
        },
        {
            "shareId": "203152f5-eef9-459d-a4e0-a691668d44ef",
            "name": "myShare4",
            "resourceArn": "arn:aws:omics:us-west-2:555555555555:variantStore/store_3",
            "principalSubscriber": "123456789012",
            "ownerId": "555555555555",
            "status": "ACTIVE"
        }
    ]
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Cross-account sharing](https://docs.aws.amazon.com/omics/latest/dev/cross-account-sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListShares](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-shares.html)」を参照してください。

### `list-tags-for-resource`
<a name="omics_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**タグのリストを取得するには**  
次の `list-tags-for-resource` の例では、ID `1234567` のワークフローのタグのリストを取得します。  

```
aws omics list-tags-for-resource \
    --resource-arn arn:aws:omics:us-west-2:123456789012:workflow/1234567
```
出力:  

```
{
    "tags": {
        "department": "analytics"
    }
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Amazon Omics リソースにタグを付ける](https://docs.aws.amazon.com/omics/latest/dev/workflows.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-tags-for-resource.html)」を参照してください。

### `list-variant-import-jobs`
<a name="omics_ListVariantImportJobs_cli_2_topic"></a>

次のコード例は、`list-variant-import-jobs` を使用する方法を示しています。

**AWS CLI**  
**バリアントインポートジョブのリストを取得するには**  
次の `list-variant-import-jobs` の例では、バリアントインポートジョブのリストを取得します。  

```
aws omics list-variant-import-jobs
```
出力:  

```
{
    "variantImportJobs": [
        {
            "creationTime": "2022-11-23T22:47:02.514002Z",
            "destinationName": "my_var_store",
            "id": "69cb65d6-xmpl-4a4a-9025-4565794b684e",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "runLeftNormalization": false,
            "status": "COMPLETED",
            "updateTime": "2022-11-23T22:49:17.976597Z"
        },
        {
            "creationTime": "2022-11-23T22:42:50.037812Z",
            "destinationName": "my_var_store",
            "id": "edd7b8ce-xmpl-47e2-bc99-258cac95a508",
            "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
            "runLeftNormalization": false,
            "status": "COMPLETED",
            "updateTime": "2022-11-23T22:45:26.009880Z"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVariantImportJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-variant-import-jobs.html)」を参照してください。

### `list-variant-stores`
<a name="omics_ListVariantStores_cli_2_topic"></a>

次のコード例は、`list-variant-stores` を使用する方法を示しています。

**AWS CLI**  
**バリアントストアのリストを取得するには**  
次の `list-variant-stores` の例では、バリアントストアのリストを取得します。  

```
aws omics list-variant-stores
```
出力:  

```
{
    "variantStores": [
        {
            "creationTime": "2022-11-23T22:09:07.534499Z",
            "id": "02dexmplcfdd",
            "name": "my_var_store",
            "reference": {
                "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
            },
            "status": "CREATING",
            "storeArn": "arn:aws:omics:us-west-2:123456789012:variantStore/my_var_store",
            "storeSizeBytes": 0,
            "updateTime": "2022-11-23T22:09:24.931711Z"
        },
        {
            "creationTime": "2022-09-23T23:00:09.140265Z",
            "id": "8777xmpl1a24",
            "name": "myvstore0",
            "status": "ACTIVE",
            "storeArn": "arn:aws:omics:us-west-2:123456789012:variantStore/myvstore0",
            "storeSizeBytes": 0,
            "updateTime": "2022-09-23T23:03:26.013220Z"
        }
    ]
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVariantStores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-variant-stores.html)」を参照してください。

### `list-workflows`
<a name="omics_ListWorkflows_cli_2_topic"></a>

次のコード例は、`list-workflows` を使用する方法を示しています。

**AWS CLI**  
**ワークフローのリストを取得するには**  
次の `list-workflows` の例では、ワークフローのリストを取得します。  

```
aws omics list-workflows
```
出力:  

```
{
    "items": [
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:workflow/1234567",
            "creationTime": "2022-09-23T23:08:22.041227Z",
            "digest": "nSCNo/qMWFxmplXpUdokXJnwgneOaxyyc2YOxVxrJTE=",
            "id": "1234567",
            "name": "my-wkflow-0",
            "status": "ACTIVE",
            "type": "PRIVATE"
        },
        {
            "arn": "arn:aws:omics:us-west-2:123456789012:workflow/1234567",
            "creationTime": "2022-11-30T22:33:16.225368Z",
            "digest": "sha256:c54bxmpl742dcc26f7fa1f10e37550ddd8f251f418277c0a58e895b801ed28cf",
            "id": "1234567",
            "name": "cram-converter",
            "status": "ACTIVE",
            "type": "PRIVATE"
        }
    ]
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Creating private workflows](https://docs.aws.amazon.com/omics/latest/dev/workflows-setup.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWorkflows](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/list-workflows.html)」を参照してください。

### `start-annotation-import-job`
<a name="omics_StartAnnotationImportJob_cli_2_topic"></a>

次のコード例は、`start-annotation-import-job` を使用する方法を示しています。

**AWS CLI**  
**注釈をインポートするには**  
次の `start-annotation-import-job` の例では、Amazon S3 から注釈をインポートします。  

```
aws omics start-annotation-import-job \
    --destination-name tsv_ann_store \
    --no-run-left-normalization \
    --role-arn arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ \
    --items source=s3://omics-artifacts-01d6xmpl4e72dd32/targetedregions.bed.gz
```
出力:  

```
{
    "jobId": "984162c7-xmpl-4d23-ab47-286f7950bfbf"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartAnnotationImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/start-annotation-import-job.html)」を参照してください。

### `start-read-set-activation-job`
<a name="omics_StartReadSetActivationJob_cli_2_topic"></a>

次のコード例は、`start-read-set-activation-job` を使用する方法を示しています。

**AWS CLI**  
**アーカイブされた読み取りセットをアクティブ化するには**  
次の `start-read-set-activation-job` の例では、2 つの読み取りセットをアクティブ化します。  

```
aws omics start-read-set-activation-job \
    --sequence-store-id 1234567890 \
    --sources readSetId=1234567890 readSetId=1234567890
```
出力:  

```
{
    "creationTime": "2022-12-06T22:35:10.100Z",
    "id": "1234567890",
    "sequenceStoreId": "1234567890",
    "status": "SUBMITTED"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartReadSetActivationJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/start-read-set-activation-job.html)」を参照してください。

### `start-read-set-export-job`
<a name="omics_StartReadSetExportJob_cli_2_topic"></a>

次のコード例は、`start-read-set-export-job` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットをエクスポートするには**  
次の `start-read-set-export-job` の例では、2 つの読み取りセットを Amazon S3 にエクスポートします。  

```
   aws omics start-read-set-export-job \
       --sequence-store-id 1234567890 \
       --sources readSetId=1234567890 readSetId=1234567890 \
       --role-arn arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ
\
       --destination s3://omics-artifacts-01d6xmpl4e72dd32/read-set-export/
```
出力:  

```
{
    "creationTime": "2022-12-06T22:37:18.612Z",
    "destination": "s3://omics-artifacts-01d6xmpl4e72dd32/read-set-export/",
    "id": "1234567890",
    "sequenceStoreId": "1234567890",
    "status": "SUBMITTED"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartReadSetExportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/start-read-set-export-job.html)」を参照してください。

### `start-read-set-import-job`
<a name="omics_StartReadSetImportJob_cli_2_topic"></a>

次のコード例は、`start-read-set-import-job` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットをインポートするには**  
次の `start-read-set-import-job` の例では、読み取りセットをインポートします。  

```
aws omics start-read-set-import-job \
    --sequence-store-id 1234567890 \
    --role-arn arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ \
    --sources file://readset-sources.json
```
readset-sources.json は、次のコンテンツを含む JSON ドキュメントです。  

```
[
    {
        "sourceFiles":
        {
            "source1": "s3://omics-artifacts-01d6xmpl4e72dd32/HG00100.chrom20.ILLUMINA.bwa.GBR.low_coverage.20101123.bam"
        },
        "sourceFileType": "BAM",
        "subjectId": "bam-subject",
        "sampleId": "bam-sample",
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890",
        "name": "HG00100"
    }
]
```
出力:  

```
{
    "creationTime": "2022-11-23T01:36:38.158Z",
    "id": "1234567890",
    "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
    "sequenceStoreId": "1234567890",
    "status": "SUBMITTED"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartReadSetImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/start-read-set-import-job.html)」を参照してください。

### `start-reference-import-job`
<a name="omics_StartReferenceImportJob_cli_2_topic"></a>

次のコード例は、`start-reference-import-job` を使用する方法を示しています。

**AWS CLI**  
**参照ゲノムをインポートするには**  
次の `start-reference-import-job` の例では、Amazon S3 から参照ゲノムをインポートします。  

```
aws omics start-reference-import-job \
    --reference-store-id 1234567890 \
    --role-arn arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ \
    --sources sourceFile=s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta,name=assembly-38
```
出力:  

```
{
    "creationTime": "2022-11-22T22:25:41.124Z",
    "id": "1234567890",
    "referenceStoreId": "1234567890",
    "roleArn": "arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ",
    "status": "SUBMITTED"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/sequence-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartReferenceImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/start-reference-import-job.html)」を参照してください。

### `start-run`
<a name="omics_StartRun_cli_2_topic"></a>

次のコード例は、`start-run` を使用する方法を示しています。

**AWS CLI**  
**ワークフローを実行するには**  
次の `start-run` の例では、ID `1234567` のワークフローを実行します。  

```
aws omics start-run \
    --workflow-id 1234567 \
    --role-arn arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ \
    --name 'cram-to-bam' \
    --output-uri s3://omics-artifacts-01d6xmpl4e72dd32/workflow-output/ \
    --run-group-id 1234567 \
    --priority 1 \
    --storage-capacity 10 \
    --log-level ALL \
    --parameters file://workflow-inputs.json
```
workflow-inputs.json は、次のコンテンツを含む JSON ドキュメントです。  

```
{
    "sample_name": "NA12878",
    "input_cram": "s3://omics-artifacts-01d6xmpl4e72dd32/NA12878.cram",
    "ref_dict": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.dict",
    "ref_fasta": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta",
    "ref_fasta_index": "omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.fasta.fai"
}
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:run/1234567",
    "id": "1234567",
    "status": "PENDING",
    "tags": {}
}
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Starting a run](https://docs.aws.amazon.com/omics/latest/dev/starting-a-run.html)」を参照してください。  
**Amazon Omics からソースファイルをロードするには**  
サービス固有の URI を使用して、Amazon Omics Storage からソースファイルをロードすることもできます。次の workflow-inputs.json ファイルの例では、読み取りセットおよび参照ゲノムのソースに Amazon Omics URI を使用します。  

```
{
    "sample_name": "NA12878",
    "input_cram": "omics://123456789012.storage.us-west-2.amazonaws.com/1234567890/readSet/1234567890/source1",
    "ref_dict": "s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.dict",
    "ref_fasta": "omics://123456789012.storage.us-west-2.amazonaws.com/1234567890/reference/1234567890",
    "ref_fasta_index": "omics://123456789012.storage.us-west-2.amazonaws.com/1234567890/reference/1234567890/index"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/start-run.html)」を参照してください。

### `start-variant-import-job`
<a name="omics_StartVariantImportJob_cli_2_topic"></a>

次のコード例は、`start-variant-import-job` を使用する方法を示しています。

**AWS CLI**  
**バリアントファイルをインポートするには**  
次の `start-variant-import-job` の例では、VCF 形式のバリアントファイルをインポートします。  

```
aws omics start-variant-import-job \
    --destination-name my_var_store \
    --no-run-left-normalization  \
    --role-arn arn:aws:iam::123456789012:role/omics-service-role-serviceRole-W8O1XMPL7QZ \
    --items source=s3://omics-artifacts-01d6xmpl4e72dd32/Homo_sapiens_assembly38.known_indels.vcf.gz
```
出力:  

```
{
    "jobId": "edd7b8ce-xmpl-47e2-bc99-258cac95a508"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartVariantImportJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/start-variant-import-job.html)」を参照してください。

### `tag-resource`
<a name="omics_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、ID `1234567` のワークフローに `department` タグを追加します。  

```
aws omics tag-resource \
    --resource-arn arn:aws:omics:us-west-2:123456789012:workflow/1234567 \
    --tags department=analytics
```
詳細については、「*Amazon Omics Developer Guide*」の「[Amazon Omics リソースにタグを付ける](https://docs.aws.amazon.com/omics/latest/dev/workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="omics_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `untag-resource` の例では、ワークフローから `department` タグを削除します。  

```
aws omics untag-resource \
    --resource-arn arn:aws:omics:us-west-2:123456789012:workflow/1234567 \
    --tag-keys department
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Storage](https://docs.aws.amazon.com/omics/latest/dev/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/untag-resource.html)」を参照してください。

### `update-annotation-store`
<a name="omics_UpdateAnnotationStore_cli_2_topic"></a>

次のコード例は、`update-annotation-store` を使用する方法を示しています。

**AWS CLI**  
**注釈ストアを更新するには**  
次の `update-annotation-store` の例では、`my_vcf_store` という名前の注釈ストアの説明を更新します。  

```
aws omics update-annotation-store \
    --name my_vcf_store \
    --description "VCF annotation store"
```
出力:  

```
{
    "creationTime": "2022-12-05T18:00:56.101860Z",
    "description": "VCF annotation store",
    "id": "bd6axmpl2444",
    "name": "my_vcf_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
    },
    "status": "ACTIVE",
    "storeFormat": "VCF",
    "updateTime": "2022-12-05T18:13:16.100051Z"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAnnotationStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/update-annotation-store.html)」を参照してください。

### `update-run-group`
<a name="omics_UpdateRunGroup_cli_2_topic"></a>

次のコード例は、`update-run-group` を使用する方法を示しています。

**AWS CLI**  
**実行グループを更新するには**  
次の `update-run-group` の例では、ID `1234567` の実行グループの設定を更新します。  

```
aws omics update-run-group \
    --id 1234567 \
    --max-cpus 10
```
出力:  

```
{
    "arn": "arn:aws:omics:us-west-2:123456789012:runGroup/1234567",
    "creationTime": "2022-12-01T00:58:42.915219Z",
    "id": "1234567",
    "maxCpus": 10,
    "maxDuration": 600,
    "name": "cram-convert",
    "tags": {}
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Workflows](https://docs.aws.amazon.com/omics/latest/dev/workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRunGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/update-run-group.html)」を参照してください。

### `update-variant-store`
<a name="omics_UpdateVariantStore_cli_2_topic"></a>

次のコード例は、`update-variant-store` を使用する方法を示しています。

**AWS CLI**  
**バリアントストアを更新するには**  
次の `update-variant-store` の例では、`my_var_store` という名前のバリアントストアの説明を更新します。  

```
aws omics update-variant-store \
    --name my_var_store \
    --description "variant store"
```
出力:  

```
{
    "creationTime": "2022-11-23T22:09:07.534499Z",
    "description": "variant store",
    "id": "02dexmplcfdd",
    "name": "my_var_store",
    "reference": {
        "referenceArn": "arn:aws:omics:us-west-2:123456789012:referenceStore/1234567890/reference/1234567890"
    },
    "status": "ACTIVE",
    "updateTime": "2022-12-05T18:23:37.686402Z"
}
```
詳細については、「*Amazon Omics Developer Guide*」の「[Omics Analytics](https://docs.aws.amazon.com/omics/latest/dev/omics-analytics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVariantStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/update-variant-store.html)」を参照してください。

### `update-workflow`
<a name="omics_UpdateWorkflow_cli_2_topic"></a>

次のコード例は、`update-workflow` を使用する方法を示しています。

**AWS CLI**  
**ワークフローを更新するには**  
次の `update-workflow` の例では、ID `1234567` のワークフローの説明を更新します。  

```
aws omics update-workflow \
    --id 1234567 \
    --description "copy workflow"
```
詳細については、「*AWS HealthOmics ユーザーガイド*」の「[Creating or updating a workflow](https://docs.aws.amazon.com/omics/latest/dev/creating-private-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWorkflow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/update-workflow.html)」を参照してください。

### `upload-read-set-part`
<a name="omics_UploadReadSetPart_cli_2_topic"></a>

次のコード例は、`upload-read-set-part` を使用する方法を示しています。

**AWS CLI**  
**読み取りセットのパートをアップロードするには**  
次の `upload-read-set-part` の例では、読み取りセットの指定されたパートをアップロードします。  

```
aws omics upload-read-set-part \
    --sequence-store-id 0123456789 \
    --upload-id 1122334455 \
    --part-source SOURCE1 \
    --part-number 1 \
    --payload /path/to/file/read_1_part_1.fastq.gz
```
出力:  

```
{
    "checksum": "984979b9928ae8d8622286c4a9cd8e99d964a22d59ed0f5722e1733eb280e635"
}
```
詳細については、「*AWS HealthOmics User Guide*」の「[Direct upload to a sequence store](https://docs.aws.amazon.com/omics/latest/dev/synchronous-uploads.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadReadSetPart](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/omics/upload-read-set-part.html)」を参照してください。

# を使用した IAM の例 AWS CLI
<a name="cli_2_iam_code_examples"></a>

次のコード例は、IAM AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-client-id-to-open-id-connect-provider`
<a name="iam_AddClientIdToOpenIdConnectProvider_cli_2_topic"></a>

次のコード例は、`add-client-id-to-open-id-connect-provider` を使用する方法を示しています。

**AWS CLI**  
**Open-ID Connect (OIDC) プロバイダーにクライアント ID (対象者) を追加するには**  
次の `add-client-id-to-open-id-connect-provider` コマンドは、クライアント ID `my-application-ID` を `server.example.com` という名前の OIDC プロバイダーに追加します。  

```
aws iam add-client-id-to-open-id-connect-provider \
    --client-id my-application-ID \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/server.example.com
```
このコマンドでは何も出力されません。  
OIDC プロバイダーを作成するには、`create-open-id-connect-provider` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddClientIdToOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/add-client-id-to-open-id-connect-provider.html)」を参照してください。

### `add-role-to-instance-profile`
<a name="iam_AddRoleToInstanceProfile_cli_2_topic"></a>

次のコード例は、`add-role-to-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**ロールをインスタンスプロファイルに追加するには**  
次の `add-role-to-instance-profile` コマンドは、`S3Access` という名前のロールを `Webserver` という名前のインスタンスプロファイルに追加します。  

```
aws iam add-role-to-instance-profile \
    --role-name S3Access \
    --instance-profile-name Webserver
```
このコマンドでは何も出力されません。  
インスタンスプロファイルを作成するには、`create-instance-profile` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[Amazon EC2 インスタンスで実行されるアプリケーションに IAM ロールを使用してアクセス許可を付与する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddRoleToInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/add-role-to-instance-profile.html)」を参照してください。

### `add-user-to-group`
<a name="iam_AddUserToGroup_cli_2_topic"></a>

次のコード例は、`add-user-to-group` を使用する方法を示しています。

**AWS CLI**  
**IAM グループにユーザーを追加するには**  
次の `add-user-to-group` コマンドは、`Bob` という名前の IAM ユーザーを `Admins` という名前の IAM グループに追加します。  

```
aws iam add-user-to-group \
    --user-name Bob \
    --group-name Admins
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループへのユーザーの追加と削除](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_add-remove-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddUserToGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/add-user-to-group.html)」を参照してください。

### `attach-group-policy`
<a name="iam_AttachGroupPolicy_cli_2_topic"></a>

次のコード例は、`attach-group-policy` を使用する方法を示しています。

**AWS CLI**  
**管理ポリシーを IAM グループにアタッチするには**  
次の`attach-group-policy`コマンドは、 という名前の管理 AWS ポリシー`ReadOnlyAccess`を という名前の IAM グループにアタッチします`Finance`。  

```
aws iam attach-group-policy \
    --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess \
    --group-name Finance
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[管理ポリシーとインラインポリシー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-group-policy.html)」を参照してください。

### `attach-role-policy`
<a name="iam_AttachRolePolicy_cli_2_topic"></a>

次のコード例は、`attach-role-policy` を使用する方法を示しています。

**AWS CLI**  
**管理ポリシーを IAM ロールにアタッチするには**  
次の`attach-role-policy`コマンドは、 という名前の管理 AWS ポリシーを という名前の IAM ロール`ReadOnlyAccess`にアタッチします`ReadOnlyRole`。  

```
aws iam attach-role-policy \
    --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess \
    --role-name ReadOnlyRole
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[管理ポリシーとインラインポリシー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-role-policy.html)」を参照してください。

### `attach-user-policy`
<a name="iam_AttachUserPolicy_cli_2_topic"></a>

次のコード例は、`attach-user-policy` を使用する方法を示しています。

**AWS CLI**  
**管理ポリシーを IAM ユーザーにアタッチするには**  
次の`attach-user-policy`コマンドは、 という名前の AWS マネージドポリシー`AdministratorAccess`を という名前の IAM ユーザーにアタッチします`Alice`。  

```
aws iam attach-user-policy \
    --policy-arn arn:aws:iam::aws:policy/AdministratorAccess \
    --user-name Alice
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[管理ポリシーとインラインポリシー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/attach-user-policy.html)」を参照してください。

### `change-password`
<a name="iam_ChangePassword_cli_2_topic"></a>

次のコード例は、`change-password` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのパスワードを変更するには**  
IAM ユーザーのパスワードを変更するには、`--cli-input-json` パラメータを使用して、古いパスワードと新しいパスワードを含む JSON ファイルを渡すことをお勧めします。この方法を使用すると、英数字以外の文字を含む強力なパスワードを使用できます。英数字以外の文字を含むパスワードをコマンドラインパラメータとして渡す場合、そのパスワードの使用が難しい場合があります。`--cli-input-json` パラメータを使用するには、まず次の例のように、`change-password` コマンドと `--generate-cli-skeleton` パラメータを組み合わせて使用します。  

```
aws iam change-password \
    --generate-cli-skeleton > change-password.json
```
前のコマンドは change-password.json という名前の JSON ファイルを作成し、これを使用して古いパスワードと新しいパスワードを入力できます。例えば、ファイルは次のようになります。  

```
{
    "OldPassword": "3s0K_;xh4~8XXI",
    "NewPassword": "]35d/{pB9Fo9wJ"
}
```
次に、パスワードを変更するには、`change-password` コマンドをもう一度使用します。今度は、JSON ファイルを指定する `--cli-input-json` パラメータを渡します。次の `change-password` コマンドでは、change-password.json という名前の JSON ファイルと共に `--cli-input-json` パラメータを使用します。  

```
aws iam change-password \
    --cli-input-json file://change-password.json
```
このコマンドでは何も出力されません。  
このコマンドは、IAM ユーザーのみが呼び出すことができます。このコマンドが AWS アカウント (ルート) 認証情報を使用して呼び出された場合、コマンドは`InvalidUserType`エラーを返します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーが自分のパスワードを変更する方法](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_user-change-own.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ChangePassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/change-password.html)」を参照してください。

### `create-access-key`
<a name="iam_CreateAccessKey_cli_2_topic"></a>

次のコード例は、`create-access-key` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのアクセスキーを作成するには**  
次の `create-access-key` コマンドは、`Bob` という名前の IAM ユーザーのためにアクセスキー (アクセスキー ID とシークレットアクセスキー) を作成します。  

```
aws iam create-access-key \
    --user-name Bob
```
出力:  

```
{
    "AccessKey": {
        "UserName": "Bob",
        "Status": "Active",
        "CreateDate": "2015-03-09T18:39:23.411Z",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY",
        "AccessKeyId": "AKIAIOSFODNN7EXAMPLE"
    }
}
```
シークレットアクセスキーを安全な場所に保管します。紛失した場合は回復できないため、新しいアクセスキーを作成する必要があります。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアクセスキーの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAccessKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-access-key.html)」を参照してください。

### `create-account-alias`
<a name="iam_CreateAccountAlias_cli_2_topic"></a>

次のコード例は、`create-account-alias` を使用する方法を示しています。

**AWS CLI**  
**アカウントエイリアスを作成するには**  
次の`create-account-alias`コマンドは、`examplecorp` AWS アカウントのエイリアスを作成します。  

```
aws iam create-account-alias \
    --account-alias examplecorp
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM* [ユーザーガイドの「 AWS アカウント ID とそのエイリアス](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateAccountAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-account-alias.html)」を参照してください。

### `create-group`
<a name="iam_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**IAM グループを作成するには**  
次の `create-group` コマンドは、`Admins` という名前の IAM グループを作成します。  

```
aws iam create-group \
    --group-name Admins
```
出力:  

```
{
    "Group": {
        "Path": "/",
        "CreateDate": "2015-03-09T20:30:24.940Z",
        "GroupId": "AIDGPMS9RO4H3FEXAMPLE",
        "Arn": "arn:aws:iam::123456789012:group/Admins",
        "GroupName": "Admins"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-group.html)」を参照してください。

### `create-instance-profile`
<a name="iam_CreateInstanceProfile_cli_2_topic"></a>

次のコード例は、`create-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**インスタンスプロファイルを作成するには**  
次の `create-instance-profile` コマンドは、`Webserver` という名前のインスタンスプロファイルを作成します。  

```
aws iam create-instance-profile \
    --instance-profile-name Webserver
```
出力:  

```
{
    "InstanceProfile": {
        "InstanceProfileId": "AIPAJMBYC7DLSPEXAMPLE",
        "Roles": [],
        "CreateDate": "2015-03-09T20:33:19.626Z",
        "InstanceProfileName": "Webserver",
        "Path": "/",
        "Arn": "arn:aws:iam::123456789012:instance-profile/Webserver"
    }
}
```
インスタンスプロファイルにロールを追加するには、`add-role-to-instance-profile` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[Amazon EC2 インスタンスで実行されるアプリケーションに IAM ロールを使用してアクセス許可を付与する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-instance-profile.html)」を参照してください。

### `create-login-profile`
<a name="iam_CreateLoginProfile_cli_2_topic"></a>

次のコード例は、`create-login-profile` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのパスワードを作成するには**  
IAM ユーザーのパスワードを作成するには、`--cli-input-json` パラメータを使用して、パスワードを含む JSON ファイルを渡すことをお勧めします。この方法を使用すると、英数字以外の文字を含む強力なパスワードを作成できます。英数字以外の文字を含むパスワードをコマンドラインパラメータとして渡す場合、そのパスワードの作成が難しい場合があります。  
`--cli-input-json` パラメータを使用するには、まず次の例のように、`create-login-profile` コマンドと `--generate-cli-skeleton` パラメータを組み合わせて使用します。  

```
aws iam create-login-profile \
    --generate-cli-skeleton > create-login-profile.json
```
前のコマンドでは、create-login-profile.json という名前の JSON ファイルが作成されます。このファイルを使用して、後続の `create-login-profile` コマンドの情報を入力できます。例えば、次のようになります。  

```
{
    "UserName": "Bob",
    "Password": "&1-3a6u:RA0djs",
    "PasswordResetRequired": true
}
```
次に、IAM ユーザーのパスワードを作成するには、`create-login-profile` コマンドをもう一度使用します。今度は、JSON ファイルを指定する `--cli-input-json` パラメータを渡します。次の `create-login-profile` コマンドでは、create-login-profile.json という名前の JSON ファイルと共に `--cli-input-json` パラメータを使用します。  

```
aws iam create-login-profile \
    --cli-input-json file://create-login-profile.json
```
出力:  

```
{
    "LoginProfile": {
        "UserName": "Bob",
        "CreateDate": "2015-03-10T20:55:40.274Z",
        "PasswordResetRequired": true
    }
}
```
新しいパスワードがアカウントのパスワードポリシーに違反している場合、コマンドは `PasswordPolicyViolation` エラーを返します。  
既にパスワードを持っているユーザーのパスワードを変更するには、`update-login-profile` を使用します。アカウントのパスワードポリシーを設定するには、`update-account-password-policy` コマンドを使用します。  
アカウントのパスワードポリシーで許可されている場合、IAM ユーザーは `change-password` コマンドを使用して自分のパスワードを変更できます。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのパスワードの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-login-profile.html)」を参照してください。

### `create-open-id-connect-provider`
<a name="iam_CreateOpenIdConnectProvider_cli_2_topic"></a>

次のコード例は、`create-open-id-connect-provider` を使用する方法を示しています。

**AWS CLI**  
**OpenID Connect (OIDC) プロバイダーを作成するには**  
OpenID Connect (OIDC) プロバイダーを作成するには、`--cli-input-json` パラメータを使用して、必要なパラメータを含む JSON ファイルを渡すことをお勧めします。OIDC プロバイダーを作成するときは、プロバイダーの URL を渡す必要があり、URL は `https://` で始まる必要があります。コマンドライン環境によっては、コロン (:) とフォワードスラッシュ (/) の文字が特別な意味を持つため、URL をコマンドラインパラメータとして渡すのは難しい場合があります。この `--cli-input-json` パラメータを使用すると、この制限を回避できます。  
`--cli-input-json` パラメータを使用するには、まず次の例のように、`create-open-id-connect-provider` コマンドと `--generate-cli-skeleton` パラメータを組み合わせて使用します。  

```
aws iam create-open-id-connect-provider \
    --generate-cli-skeleton > create-open-id-connect-provider.json
```
前のコマンドでは、create-open-id-connect-provider.json という名前の JSON ファイルが作成されます。このファイルを使用して、後続の `create-open-id-connect-provider` コマンドの情報を入力できます。例えば、次のようになります。  

```
{
    "Url": "https://server.example.com",
    "ClientIDList": [
        "example-application-ID"
    ],
    "ThumbprintList": [
        "c3768084dfb3d2b68b7897bf5f565da8eEXAMPLE"
    ]
}
```
次に、OpenID Connect (OIDC) プロバイダーを作成するには、`create-open-id-connect-provider` コマンドをもう一度使用します。今度は、JSON ファイルを指定する `--cli-input-json` パラメータを渡します。次の `create-open-id-connect-provider` コマンドでは、create-open-id-connect-provider.json という名前の JSON ファイルと共に `--cli-input-json` パラメータを使用します。  

```
aws iam create-open-id-connect-provider \
    --cli-input-json file://create-open-id-connect-provider.json
```
出力:  

```
{
    "OpenIDConnectProviderArn": "arn:aws:iam::123456789012:oidc-provider/server.example.com"
}
```
OIDC プロバイダーの詳細については、「*AWS IAM ユーザーガイド*」の「[IAM で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
OIDC プロバイダーのサムプリントの取得に関する詳細については、「*AWS IAM ユーザーガイド*」の「[OpenID Connect ID プロバイダーのサムプリントを取得する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc_verify-thumbprint.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-open-id-connect-provider.html)」を参照してください。

### `create-policy-version`
<a name="iam_CreatePolicyVersion_cli_2_topic"></a>

次のコード例は、`create-policy-version` を使用する方法を示しています。

**AWS CLI**  
**新しいバージョンの管理ポリシーを作成するには**  
この例では、ARN が `arn:aws:iam::123456789012:policy/MyPolicy` である IAM ポリシーの新しい `v2` バージョンを作成し、それをデフォルトのバージョンにします。  

```
aws iam create-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --policy-document file://NewPolicyVersion.json \
    --set-as-default
```
出力:  

```
{
    "PolicyVersion": {
        "CreateDate": "2015-06-16T18:56:03.721Z",
        "VersionId": "v2",
        "IsDefaultVersion": true
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ポリシーのバージョニング](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-versioning.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-policy-version.html)」を参照してください。

### `create-policy`
<a name="iam_CreatePolicy_cli_2_topic"></a>

次のコード例は、`create-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタマー管理ポリシーを作成するには**  
次のコマンドは、`my-policy` という名前でカスタマー管理ポリシーを作成します。このファイル `policy.json` は、現在のフォルダにある JSON ドキュメントで、`amzn-s3-demo-bucket` という名前の Amazon S3 バケット内の `shared` フォルダに対する読み取り専用アクセスを付与します。  

```
aws iam create-policy \
    --policy-name my-policy \
    --policy-document file://policy.json
```
policy.json の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:Get*",
                "s3:List*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket/shared/*"
            ]
        }
    ]
}
```
出力:  

```
{
    "Policy": {
        "PolicyName": "my-policy",
        "CreateDate": "2015-06-01T19:31:18.620Z",
        "AttachmentCount": 0,
        "IsAttachable": true,
        "PolicyId": "ZXR6A36LTYANPAI7NJ5UV",
        "DefaultVersionId": "v1",
        "Path": "/",
        "Arn": "arn:aws:iam::0123456789012:policy/my-policy",
        "UpdateDate": "2015-06-01T19:31:18.620Z"
    }
}
```
文字列パラメータの入力としてファイルを使用する方法の詳細については、「 [CLI ユーザーガイド」の「CLI AWS のパラメータ値を指定する](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters.html)」を参照してください。 *AWS *  
**例 2: 説明を含むカスタマー管理ポリシーを作成するには**  
次のコマンドは、変更不可能な説明を使用して `my-policy` という名前のカスタマー管理ポリシーを作成します。  
このファイル `policy.json` は、`amzn-s3-demo-bucket` という名前の Amazon S3 バケットに対するすべての Put、List、および Get アクションへのアクセスを付与する、現在のフォルダにある JSON ドキュメントです。  

```
aws iam create-policy \
    --policy-name my-policy \
    --policy-document file://policy.json \
    --description "This policy grants access to all Put, Get, and List actions for amzn-s3-demo-bucket"
```
policy.json の内容:  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
       {
           "Effect": "Allow",
           "Action": [
                "s3:ListBucket*",
                "s3:PutBucket*",
                "s3:GetBucket*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket"
            ]
        }
    ]
}
```
出力:  

```
{
    "Policy": {
        "PolicyName": "my-policy",
        "PolicyId": "ANPAWGSUGIDPEXAMPLE",
        "Arn": "arn:aws:iam::123456789012:policy/my-policy",
        "Path": "/",
        "DefaultVersionId": "v1",
        "AttachmentCount": 0,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "CreateDate": "2023-05-24T22:38:47+00:00",
        "UpdateDate": "2023-05-24T22:38:47+00:00"
    }
}
```
アイデンティティベースのポリシーの詳細については、「*AWS IAM ユーザーガイド*」の「[アイデンティティベースおよびリソースベースのポリシー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html)」を参照してください。  
**例 3: タグを使用してカスタマー管理ポリシーを作成するには**  
次のコマンドは、タグを使用して `my-policy` という名前のカスタマー管理ポリシーを作成します。この例では、次の JSON 形式のタグを持つ `--tags` パラメーターを使用します: `'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`。あるいは、`--tags` パラメーターを次の短縮形式のタグとともに使用することもできます: `'Key=Department,Value=Accounting Key=Location,Value=Seattle'`。  
このファイル `policy.json` は、`amzn-s3-demo-bucket` という名前の Amazon S3 バケットに対するすべての Put、List、および Get アクションへのアクセスを付与する、現在のフォルダにある JSON ドキュメントです。  

```
aws iam create-policy \
    --policy-name my-policy \
    --policy-document file://policy.json \
    --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'
```
policy.json の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket*",
                "s3:PutBucket*",
                "s3:GetBucket*"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket"
            ]
        }
    ]
}
```
出力:  

```
{
    "Policy": {
        "PolicyName": "my-policy",
        "PolicyId": "ANPAWGSUGIDPEXAMPLE",
        "Arn": "arn:aws:iam::12345678012:policy/my-policy",
        "Path": "/",
        "DefaultVersionId": "v1",
        "AttachmentCount": 0,
        "PermissionsBoundaryUsageCount": 0,
        "IsAttachable": true,
        "CreateDate": "2023-05-24T23:16:39+00:00",
        "UpdateDate": "2023-05-24T23:16:39+00:00",
        "Tags": [
            {
                "Key": "Department",
                "Value": "Accounting"
            },
                "Key": "Location",
                "Value": "Seattle"
            {
        ]
    }
}
```
ポリシーのタグ付けの詳細については、「*AWS IAM ユーザーガイド*」の「[カスタマー管理ポリシーのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_customer-managed-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-policy.html)」を参照してください。

### `create-role`
<a name="iam_CreateRole_cli_2_topic"></a>

次のコード例は、`create-role` を使用する方法を示しています。

**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 ロールの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)」を参照してください。  
**例 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) の変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-modify_max-session-duration-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 ロールのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_roles.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-role.html)」を参照してください。

### `create-saml-provider`
<a name="iam_CreateSAMLProvider_cli_2_topic"></a>

次のコード例は、`create-saml-provider` を使用する方法を示しています。

**AWS CLI**  
**SAML プロバイダーを作成するには**  
この例では、IAM に `MySAMLProvider` という名前の新しい SAML プロバイダーを作成します。これは、ファイル `SAMLMetaData.xml` 内の SAML メタデータドキュメントによって記述されます。  

```
aws iam create-saml-provider \
    --saml-metadata-document file://SAMLMetaData.xml \
    --name MySAMLProvider
```
出力:  

```
{
    "SAMLProviderArn": "arn:aws:iam::123456789012:saml-provider/MySAMLProvider"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM SAML ID プロバイダーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSAMLProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-saml-provider.html)」を参照してください。

### `create-service-linked-role`
<a name="iam_CreateServiceLinkedRole_cli_2_topic"></a>

次のコード例は、`create-service-linked-role` を使用する方法を示しています。

**AWS CLI**  
**サービスにリンクされたロールを作成するには**  
次の の`create-service-linked-role`例では、指定されたサービスの AWS サービスにリンクされたロールを作成し、指定された説明をアタッチします。  

```
aws iam create-service-linked-role \
    --aws-service-name lex.amazonaws.com \
    --description "My service-linked role to support Lex"
```
出力:  

```
{
    "Role": {
        "Path": "/aws-service-role/lex.amazonaws.com/",
        "RoleName": "AWSServiceRoleForLexBots",
        "RoleId": "AROA1234567890EXAMPLE",
        "Arn": "arn:aws:iam::1234567890:role/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots",
        "CreateDate": "2019-04-17T20:34:14+00:00",
        "AssumeRolePolicyDocument": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Action": [
                        "sts:AssumeRole"
                    ],
                    "Effect": "Allow",
                    "Principal": {
                        "Service": [
                            "lex.amazonaws.com"
                        ]
                    }
                }
            ]
        }
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[サービスにリンクされたロールの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateServiceLinkedRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-service-linked-role.html)」を参照してください。

### `create-service-specific-credential`
<a name="iam_CreateServiceSpecificCredential_cli_2_topic"></a>

次のコード例は、`create-service-specific-credential` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのサービス固有の認証情報のセットを作成する**  
次の `create-service-specific-credential` の例では、設定されたサービスにのみアクセスできるユーザー名とパスワードを作成します。  

```
aws iam create-service-specific-credential \
    --user-name sofia \
    --service-name codecommit.amazonaws.com
```
出力:  

```
{
    "ServiceSpecificCredential": {
        "CreateDate": "2019-04-18T20:45:36+00:00",
        "ServiceName": "codecommit.amazonaws.com",
        "ServiceUserName": "sofia-at-123456789012",
        "ServicePassword": "k1zPZM6uVxMQ3oxqgoYlNuJPyRTZ1vREs76zTQE3eJk=",
        "ServiceSpecificCredentialId": "ACCAEXAMPLE123EXAMPLE",
        "UserName": "sofia",
        "Status": "Active"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[CodeCommit への HTTPS 接続用の Git 認証情報を作成する](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html#setting-up-gc-iam)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateServiceSpecificCredential](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-service-specific-credential.html)」を参照してください。

### `create-user`
<a name="iam_CreateUser_cli_2_topic"></a>

次のコード例は、`create-user` を使用する方法を示しています。

**AWS CLI**  
**例 1: IAM ユーザーを作成するには**  
次の `create-user` コマンドは、現在のアカウントに `Bob` という名前の IAM ユーザーを作成します。  

```
aws iam create-user \
    --user-name Bob
```
出力:  

```
{
    "User": {
        "UserName": "Bob",
        "Path": "/",
        "CreateDate": "2023-06-08T03:20:41.270Z",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:user/Bob"
    }
}
```
詳細については、[「IAM ユーザーガイド」の AWS 「アカウントでの IAM ユーザーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html)」を参照してください。 *AWS *  
**例 2: 指定したパスに IAM ユーザーを作成するには**  
次の `create-user` コマンドは、指定されたパスに `Bob` という名前の IAM ユーザーを作成します。  

```
aws iam create-user \
    --user-name Bob \
    --path /division_abc/subdivision_xyz/
```
出力:  

```
{
    "User": {
        "Path": "/division_abc/subdivision_xyz/",
        "UserName": "Bob",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::12345678012:user/division_abc/subdivision_xyz/Bob",
        "CreateDate": "2023-05-24T18:20:17+00:00"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html)」を参照してください。  
**例 3: タグを使用して IAM ユーザーを作成するには**  
次の `create-user` コマンドは、タグを使用して `Bob` という名前の IAM ユーザーを作成します。この例では、次の JSON 形式のタグを持つ `--tags` パラメータフラグを使用します: `'{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'`。あるいは、`--tags` フラグを次の短縮形式のタグとともに使用することもできます: `'Key=Department,Value=Accounting Key=Location,Value=Seattle'`。  

```
aws iam create-user \
    --user-name Bob \
    --tags '{"Key": "Department", "Value": "Accounting"}' '{"Key": "Location", "Value": "Seattle"}'
```
出力:  

```
{
    "User": {
        "Path": "/",
        "UserName": "Bob",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::12345678012:user/Bob",
        "CreateDate": "2023-05-25T17:14:21+00:00",
        "Tags": [
            {
                "Key": "Department",
                "Value": "Accounting"
            },
            {
                "Key": "Location",
                "Value": "Seattle"
            }
        ]
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」で「[IAM ユーザーのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags_users.html)」を参照してください。  
**例 3: アクセス許可の境界が設定された IAM ユーザーを作成するには**  
次の `create-user` コマンドは、AmazonS3FullAccess のアクセス許可の境界を持つ `Bob` という名前の IAM ユーザーを作成します。  

```
aws iam create-user \
    --user-name Bob \
    --permissions-boundary arn:aws:iam::aws:policy/AmazonS3FullAccess
```
出力:  

```
{
    "User": {
        "Path": "/",
        "UserName": "Bob",
        "UserId": "AIDAIOSFODNN7EXAMPLE",
        "Arn": "arn:aws:iam::12345678012:user/Bob",
        "CreateDate": "2023-05-24T17:50:53+00:00",
        "PermissionsBoundary": {
        "PermissionsBoundaryType": "Policy",
        "PermissionsBoundaryArn": "arn:aws:iam::aws:policy/AmazonS3FullAccess"
        }
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM エンティティのアクセス許可の境界](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-user.html)」を参照してください。

### `create-virtual-mfa-device`
<a name="iam_CreateVirtualMfaDevice_cli_2_topic"></a>

次のコード例は、`create-virtual-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**仮想 MFA デバイスを作成するには**  
この例では、`BobsMFADevice` という新しい仮想 MFA デバイスを作成します。`QRCode.png` というブートストラップ情報を含むファイルを作成し、`C:/` ディレクトリに配置します。この例で使用されているブートストラップメソッドは `QRCodePNG` です。  

```
aws iam create-virtual-mfa-device \
    --virtual-mfa-device-name BobsMFADevice \
    --outfile C:/QRCode.png \
    --bootstrap-method QRCodePNG
```
出力:  

```
{
    "VirtualMFADevice": {
        "SerialNumber": "arn:aws:iam::210987654321:mfa/BobsMFADevice"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[AWSでの多要素認証 (MFA) の使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVirtualMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-virtual-mfa-device.html)」を参照してください。

### `deactivate-mfa-device`
<a name="iam_DeactivateMfaDevice_cli_2_topic"></a>

次のコード例は、`deactivate-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスを無効にするには**  
このコマンドは、ユーザー `Bob` に関連付けられている ARN `arn:aws:iam::210987654321:mfa/BobsMFADevice` を持つ仮想 MFA デバイスを無効にします。  

```
aws iam deactivate-mfa-device \
    --user-name Bob \
    --serial-number arn:aws:iam::210987654321:mfa/BobsMFADevice
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[AWSでの多要素認証 (MFA) の使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeactivateMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/deactivate-mfa-device.html)」を参照してください。

### `decode-authorization-message`
<a name="iam_DecodeAuthorizationMessage_cli_2_topic"></a>

次のコード例は、`decode-authorization-message` を使用する方法を示しています。

**AWS CLI**  
**認証失敗メッセージをデコードするには**  
次の `decode-authorization-message` の例では、必要なアクセス許可なしでインスタンスを起動しようとすると、EC2 コンソールから返されるメッセージをデコードします。  

```
aws sts decode-authorization-message \
    --encoded-message lxzA8VEjEvu-s0TTt3PgYCXik9YakOqsrFJGRZR98xNcyWAxwRq14xIvd-npzbgTevuufCTbjeBAaDARg9cbTK1rJbg3awM33o-Vy3ebPErE2-mWR9hVYdvX-0zKgVOWF9pWjZaJSMqxB-aLXo-I_8TTvBq88x8IFPbMArNdpu0IjxDjzf22PF3SOE3XvIQ-_PEO0aUqHCCcsSrFtvxm6yQD1nbm6VTIVrfa0Bzy8lsoMo7SjIaJ2r5vph6SY5vCCwg6o2JKe3hIHTa8zRrDbZSFMkcXOT6EOPkQXmaBsAC6ciG7Pz1JnEOvuj5NSTlSMljrAXczWuRKAs5GsMYiU8KZXZhokVzdQCUZkS5aVHumZbadu0io53jpgZqhMqvS4fyfK4auK0yKRMtS6JCXPlhkolEs7ZMFA0RVkutqhQqpSDPB5SX5l00lYipWyFK0_AyAx60vumPuVh8P0AzXwdFsT0l4D0m42NFIKxbWXsoJdqaOqVFyFEd0-Xx9AYAAIr6bhcis7C__bZh4dlAAWooHFGKgfoJcWGwgdzgbu9hWyVvKTpeot5hsb8qANYjJRCPXTKpi6PZfdijIkwb6gDMEsJ9qMtr62qP_989mwmtNgnVvBa_ir6oxJxVe_kL9SH1j5nsGDxQFajvPQhxWOHvEQIg_H0bnKWk
```
出力は、任意の JSON テキストプロセッサで解析できる JSON テキストの 1 行文字列としてフォーマットされます。  

```
{
    "DecodedMessage": "{\"allowed\":false,\"explicitDeny\":false,\"matchedStatements\":{\"items\":[]},\"failures\":{\"items\":[]},\"context\":{\"principal\":{\"id\":\"AIDAV3ZUEFP6J7GY7O6LO\",\"name\":\"chain-user\",\"arn\":\"arn:aws:iam::403299380220:user/chain-user\"},\"action\":\"ec2:RunInstances\",\"resource\":\"arn:aws:ec2:us-east-2:403299380220:instance/*\",\"conditions\":{\"items\":[{\"key\":\"ec2:InstanceMarketType\",\"values\":{\"items\":[{\"value\":\"on-demand\"}]}},{\"key\":\"aws:Resource\",\"values\":{\"items\":[{\"value\":\"instance/*\"}]}},{\"key\":\"aws:Account\",\"values\":{\"items\":[{\"value\":\"403299380220\"}]}},{\"key\":\"ec2:AvailabilityZone\",\"values\":{\"items\":[{\"value\":\"us-east-2b\"}]}},{\"key\":\"ec2:ebsOptimized\",\"values\":{\"items\":[{\"value\":\"false\"}]}},{\"key\":\"ec2:IsLaunchTemplateResource\",\"values\":{\"items\":[{\"value\":\"false\"}]}},{\"key\":\"ec2:InstanceType\",\"values\":{\"items\":[{\"value\":\"t2.micro\"}]}},{\"key\":\"ec2:RootDeviceType\",\"values\":{\"items\":[{\"value\":\"ebs\"}]}},{\"key\":\"aws:Region\",\"values\":{\"items\":[{\"value\":\"us-east-2\"}]}},{\"key\":\"aws:Service\",\"values\":{\"items\":[{\"value\":\"ec2\"}]}},{\"key\":\"ec2:InstanceID\",\"values\":{\"items\":[{\"value\":\"*\"}]}},{\"key\":\"aws:Type\",\"values\":{\"items\":[{\"value\":\"instance\"}]}},{\"key\":\"ec2:Tenancy\",\"values\":{\"items\":[{\"value\":\"default\"}]}},{\"key\":\"ec2:Region\",\"values\":{\"items\":[{\"value\":\"us-east-2\"}]}},{\"key\":\"aws:ARN\",\"values\":{\"items\":[{\"value\":\"arn:aws:ec2:us-east-2:403299380220:instance/*\"}]}}]}}}"
}
```
詳細については、「*AWS re:Post*」の「[EC2 インスタンスの起動中に 「UnauthorizedOperation」というエラーを受け取った後、認可失敗のメッセージをデコードするには](https://repost.aws/knowledge-center/ec2-not-auth-launch)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecodeAuthorizationMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/decode-authorization-message.html)」を参照してください。

### `delete-access-key`
<a name="iam_DeleteAccessKey_cli_2_topic"></a>

次のコード例は、`delete-access-key` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのためにアクセスキーを削除するには**  
次の `delete-access-key` コマンドは、`Bob` という名前の IAM ユーザーのために指定されたアクセスキー (アクセスキー ID とシークレットアクセスキー) を削除します。  

```
aws iam delete-access-key \
    --access-key-id AKIDPMS9RO4H3FEXAMPLE \
    --user-name Bob
```
このコマンドでは何も出力されません。  
IAM ユーザーのためにに定義されたアクセスキーを一覧表示するには、`list-access-keys` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアクセスキーの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-access-key.html)」を参照してください。

### `delete-account-alias`
<a name="iam_DeleteAccountAlias_cli_2_topic"></a>

次のコード例は、`delete-account-alias` を使用する方法を示しています。

**AWS CLI**  
**アカウントエイリアスを削除するには**  
次の `delete-account-alias` コマンドは、現在のアカウントのエイリアス `mycompany` を削除します。  

```
aws iam delete-account-alias \
    --account-alias mycompany
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM* [ユーザーガイドの「 AWS アカウント ID とそのエイリアス](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteAccountAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-account-alias.html)」を参照してください。

### `delete-account-password-policy`
<a name="iam_DeleteAccountPasswordPolicy_cli_2_topic"></a>

次のコード例は、`delete-account-password-policy` を使用する方法を示しています。

**AWS CLI**  
**現在のアカウントのパスワードポリシーを削除するには**  
次の `delete-account-password-policy` コマンドは、現在のアカウントのパスワードポリシーを削除します。  

```
aws iam delete-account-password-policy
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアカウントパスワードポリシーの設定](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccountPasswordPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-account-password-policy.html)」を参照してください。

### `delete-group-policy`
<a name="iam_DeleteGroupPolicy_cli_2_topic"></a>

次のコード例は、`delete-group-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM グループからポリシーを削除するには**  
次の `delete-group-policy` コマンドは、`Admins` という名前のグループから `ExamplePolicy` という名前のポリシーを削除します。  

```
aws iam delete-group-policy \
    --group-name Admins \
    --policy-name ExamplePolicy
```
このコマンドでは何も出力されません。  
グループにアタッチされているポリシーを表示するには、`list-group-policies` コマンドを使用します。  
IAM ポリシーの詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ポリシーを管理する](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-group-policy.html)」を参照してください。

### `delete-group`
<a name="iam_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**IAM グループを削除するには**  
次の `delete-group` コマンドは、`MyTestGroup` という名前の IAM グループを削除します。  

```
aws iam delete-group \
    --group-name MyTestGroup
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループの削除](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-group.html)」を参照してください。

### `delete-instance-profile`
<a name="iam_DeleteInstanceProfile_cli_2_topic"></a>

次のコード例は、`delete-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**インスタンスプロファイルを削除するには**  
次の `delete-instance-profile` コマンドは、`ExampleInstanceProfile` という名前のインスタンスプロファイルを削除します。  

```
aws iam delete-instance-profile \
    --instance-profile-name ExampleInstanceProfile
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[インスタンスプロファイルの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-instance-profile.html)」を参照してください。

### `delete-login-profile`
<a name="iam_DeleteLoginProfile_cli_2_topic"></a>

次のコード例は、`delete-login-profile` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのパスワードを削除するには**  
次の `delete-login-profile` コマンドは、`Bob` という名前の IAM ユーザーのパスワードを削除します。  

```
aws iam delete-login-profile \
    --user-name Bob
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのパスワードの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-login-profile.html)」を参照してください。

### `delete-open-id-connect-provider`
<a name="iam_DeleteOpenIdConnectProvider_cli_2_topic"></a>

次のコード例は、`delete-open-id-connect-provider` を使用する方法を示しています。

**AWS CLI**  
**IAM OpenID Connect ID プロバイダーを削除するには**  
この例では、プロバイダー `example.oidcprovider.com` に接続する IAM OIDC プロバイダーを削除します。  

```
aws iam delete-open-id-connect-provider \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-open-id-connect-provider.html)」を参照してください。

### `delete-policy-version`
<a name="iam_DeletePolicyVersion_cli_2_topic"></a>

次のコード例は、`delete-policy-version` を使用する方法を示しています。

**AWS CLI**  
**管理ポリシーのバージョンを削除するには**  
この例では、`v2` と識別されたバージョンを ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーから削除します。  

```
aws iam delete-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --version-id v2
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-policy-version.html)」を参照してください。

### `delete-policy`
<a name="iam_DeletePolicy_cli_2_topic"></a>

次のコード例は、`delete-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM ポリシーを削除するには**  
この例では、ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーを削除します。  

```
aws iam delete-policy \
    --policy-arn arn:aws:iam::123456789012:policy/MySamplePolicy
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-policy.html)」を参照してください。

### `delete-role-permissions-boundary`
<a name="iam_DeleteRolePermissionsBoundary_cli_2_topic"></a>

次のコード例は、`delete-role-permissions-boundary` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールからアクセス許可の境界を削除するには**  
次の `delete-role-permissions-boundary` の例では、指定した IAM ロールのアクセス許可の境界を削除します。アクセス許可の境界をロールに適用するには、`put-role-permissions-boundary` コマンドを使用します。  

```
aws iam delete-role-permissions-boundary \
    --role-name lambda-application-role
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRolePermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-role-permissions-boundary.html)」を参照してください。

### `delete-role-policy`
<a name="iam_DeleteRolePolicy_cli_2_topic"></a>

次のコード例は、`delete-role-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールからポリシーを削除するには**  
次の `delete-role-policy` コマンドは、`Test-Role` という名前のロールから `ExamplePolicy` という名前のポリシーを削除します。  

```
aws iam delete-role-policy \
    --role-name Test-Role \
    --policy-name ExamplePolicy
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[ロールの変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-role-policy.html)」を参照してください。

### `delete-role`
<a name="iam_DeleteRole_cli_2_topic"></a>

次のコード例は、`delete-role` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールを削除するには**  
次の `delete-role` コマンドは、`Test-Role` という名前のロールを削除します。  

```
aws iam delete-role \
    --role-name Test-Role
```
このコマンドでは何も出力されません。  
ロールを削除する前に、インスタンスプロファイルからロールを削除し (`remove-role-from-instance-profile`)、管理ポリシーをデタッチして (`detach-role-policy`)、ロールにアタッチされているインラインポリシーを削除する (`delete-role-policy`) 必要があります。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ロールの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)」および「[インスタンスプロファイルの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-role.html)」を参照してください。

### `delete-saml-provider`
<a name="iam_DeleteSAMLProvider_cli_2_topic"></a>

次のコード例は、`delete-saml-provider` を使用する方法を示しています。

**AWS CLI**  
**SAML プロバイダーを削除するには**  
この例では、ARN が `arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider` である IAM SAML 2.0 プロバイダーを削除します。  

```
aws iam delete-saml-provider \
--saml-provider-arn arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM SAML ID プロバイダーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSAMLProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-saml-provider.html)」を参照してください。

### `delete-server-certificate`
<a name="iam_DeleteServerCertificate_cli_2_topic"></a>

次の例は、`delete-server-certificate` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントからサーバー証明書を削除するには**  
次の `delete-server-certificate` コマンドは、指定されたサーバー証明書を AWS アカウントから削除します。  

```
aws iam delete-server-certificate \
    --server-certificate-name myUpdatedServerCertificate
```
このコマンドでは何も出力されません。  
 AWS アカウントで使用可能なサーバー証明書を一覧表示するには、 `list-server-certificates` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM でのサーバー証明書の管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-server-certificate.html)」を参照してください。

### `delete-service-linked-role`
<a name="iam_DeleteServiceLinkedRole_cli_2_topic"></a>

次のコード例は、`delete-service-linked-role` を使用する方法を示しています。

**AWS CLI**  
**サービスにリンクされたロールを削除するには**  
次の `delete-service-linked-role` の例では、不要になったサービスにリンクされたロールのうち、指定されたものを削除します。削除は非同期で実行されます。`get-service-linked-role-deletion-status` コマンドを使用して、削除のステータスをチェックし、削除がいつ完了したかを確認できます。  

```
aws iam delete-service-linked-role \
    --role-name AWSServiceRoleForLexBots
```
出力:  

```
{
    "DeletionTaskId": "task/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots/1a2b3c4d-1234-abcd-7890-abcdeEXAMPLE"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[サービスにリンクされたロールの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceLinkedRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-service-linked-role.html)」を参照してください。

### `delete-service-specific-credential`
<a name="iam_DeleteServiceSpecificCredential_cli_2_topic"></a>

次のコード例は、`delete-service-specific-credential` を使用する方法を示しています。

**AWS CLI**  
**例 1: リクエストするユーザーのサービス固有の認証情報を削除する**  
次の `delete-service-specific-credential` の例では、リクエストを行うユーザーの指定されたサービス固有の認証情報を削除します。`service-specific-credential-id` は、認証情報を作成するときに提供され、`list-service-specific-credentials` コマンドを使用して取得できます。  

```
aws iam delete-service-specific-credential \
    --service-specific-credential-id ACCAEXAMPLE123EXAMPLE
```
このコマンドでは何も出力されません。  
**例 2: 指定されたユーザーのサービス固有の認証情報を削除する**  
次の `delete-service-specific-credential` の例では、指定されたユーザーの指定されたサービス固有の認証情報を削除します。`service-specific-credential-id` は、認証情報を作成するときに提供され、`list-service-specific-credentials` コマンドを使用して取得できます。  

```
aws iam delete-service-specific-credential \
    --user-name sofia \
    --service-specific-credential-id ACCAEXAMPLE123EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[CodeCommit への HTTPS 接続用の Git 認証情報を作成する](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html#setting-up-gc-iam)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceSpecificCredential](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-service-specific-credential.html)」を参照してください。

### `delete-signing-certificate`
<a name="iam_DeleteSigningCertificate_cli_2_topic"></a>

次のコード例は、`delete-signing-certificate` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーの署名証明書を削除するには**  
次の `delete-signing-certificate` コマンドは、`Bob` という名前の IAM ユーザーの指定された署名証明書を削除します。  

```
aws iam delete-signing-certificate \
    --user-name Bob \
    --certificate-id TA7SMP42TDN5Z26OBPJE7EXAMPLE
```
このコマンドでは何も出力されません。  
署名証明書の ID を取得するには、`list-signing-certificates` コマンドを使用します。  
詳細については、「*Amazon EC2 ユーザーガイド*」の「[署名証明書の管理](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-up-ami-tools.html#ami-tools-managing-certs)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSigningCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-signing-certificate.html)」を参照してください。

### `delete-ssh-public-key`
<a name="iam_DeleteSshPublicKey_cli_2_topic"></a>

次のコード例は、`delete-ssh-public-key` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーにアタッチされた SSH パブリックキーを削除するには**  
次の `delete-ssh-public-key` のコマンドは、IAM ユーザー `sofia` にアタッチされた指定された SSH パブリックキーを削除します。  

```
aws iam delete-ssh-public-key \
    --user-name sofia \
    --ssh-public-key-id APKA123456789EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[CodeCommit で SSH キーと SSH を使用する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html#ssh-keys-code-commit)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSshPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-ssh-public-key.html)」を参照してください。

### `delete-user-permissions-boundary`
<a name="iam_DeleteUserPermissionsBoundary_cli_2_topic"></a>

次のコード例は、`delete-user-permissions-boundary` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーからアクセス許可の境界を削除するには**  
次の `delete-user-permissions-boundary` の例では、`intern` という名前の IAM ユーザーにアタッチされているアクセス許可の境界を削除します。アクセス許可の境界をユーザーに適用するには、`put-user-permissions-boundary` コマンドを使用します。  

```
aws iam delete-user-permissions-boundary \
    --user-name intern
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUserPermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-user-permissions-boundary.html)」を参照してください。

### `delete-user-policy`
<a name="iam_DeleteUserPolicy_cli_2_topic"></a>

次のコード例は、`delete-user-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーからポリシーを削除するには**  
次の `delete-user-policy` コマンドは、指定されたポリシーを `Bob` という名前の IAM ユーザーから削除します。  

```
aws iam delete-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy
```
このコマンドでは何も出力されません。  
IAM ユーザーのポリシーのリストを取得するには、`list-user-policies` コマンドを使用します。  
詳細については、[「IAM ユーザーガイド」の AWS 「アカウントでの IAM ユーザーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-user-policy.html)」を参照してください。

### `delete-user`
<a name="iam_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーを削除するには**  
次の `delete-user` コマンドは、現在のアカウントから `Bob` という名前の IAM ユーザーを削除します。  

```
aws iam delete-user \
    --user-name Bob
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーの削除](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_deleting)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-user.html)」を参照してください。

### `delete-virtual-mfa-device`
<a name="iam_DeleteVirtualMfaDevice_cli_2_topic"></a>

次のコード例は、`delete-virtual-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**仮想 MFA デバイスを削除するには**  
次の `delete-virtual-mfa-device` コマンドは、指定した MFA デバイスを現在のアカウントから削除します。  

```
aws iam delete-virtual-mfa-device \
    --serial-number arn:aws:iam::123456789012:mfa/MFATest
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[MFA デバイスの無効化](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_disable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVirtualMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-virtual-mfa-device.html)」を参照してください。

### `detach-group-policy`
<a name="iam_DetachGroupPolicy_cli_2_topic"></a>

次のコード例は、`detach-group-policy` を使用する方法を示しています。

**AWS CLI**  
**グループからポリシーをデタッチするには**  
この例では、ARN `arn:aws:iam::123456789012:policy/TesterAccessPolicy` を持つ管理ポリシーを `Testers` というグループから削除します。  

```
aws iam detach-group-policy \
    --group-name Testers \
    --policy-arn arn:aws:iam::123456789012:policy/TesterAccessPolicy
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/detach-group-policy.html)」を参照してください。

### `detach-role-policy`
<a name="iam_DetachRolePolicy_cli_2_topic"></a>

次のコード例は、`detach-role-policy` を使用する方法を示しています。

**AWS CLI**  
**ロールからポリシーをデタッチするには**  
この例では、ARN `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy` を持つ管理ポリシーを `FedTesterRole` というロールから削除します。  

```
aws iam detach-role-policy \
    --role-name FedTesterRole \
    --policy-arn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[ロールの変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/detach-role-policy.html)」を参照してください。

### `detach-user-policy`
<a name="iam_DetachUserPolicy_cli_2_topic"></a>

次のコード例は、`detach-user-policy` を使用する方法を示しています。

**AWS CLI**  
**ユーザーからポリシーをデタッチするには**  
この例では、ARN `arn:aws:iam::123456789012:policy/TesterPolicy` を持つ管理ポリシーをユーザー `Bob` から削除します。  

```
aws iam detach-user-policy \
    --user-name Bob \
    --policy-arn arn:aws:iam::123456789012:policy/TesterPolicy
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアクセス許可の変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/detach-user-policy.html)」を参照してください。

### `disable-organizations-root-credentials-management`
<a name="iam_DisableOrganizationsRootCredentialsManagement_cli_2_topic"></a>

次のコード例は、`disable-organizations-root-credentials-management` を使用する方法を示しています。

**AWS CLI**  
**組織で RootCredentialsManagement 機能を無効にするには**  
次の `disable-organizations-root-credentials-management` コマンドは、組織内のメンバーアカウント全体で特権ルートユーザー認証情報の管理を無効にします。  

```
aws iam disable-organizations-root-credentials-management
```
出力:  

```
{
    "EnabledFeatures": [
        "RootSessions"
    ]
    "OrganizationId": "o-aa111bb222"
}
```
詳細については、*AWS IAM ユーザーガイド*の「[メンバーアカウントのルートアクセスを一元化する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DisableOrganizationsRootCredentialsManagement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/disable-organizations-root-credentials-management.html)」を参照してください。

### `disable-organizations-root-sessions`
<a name="iam_DisableOrganizationsRootSessions_cli_2_topic"></a>

次のコード例は、`disable-organizations-root-sessions` を使用する方法を示しています。

**AWS CLI**  
**組織で RootSessions 機能を無効にするには**  
次の `disable-organizations-root-sessions` コマンドは、組織内のメンバーアカウント全体で特権タスクのルートユーザーセッションを無効にします。  

```
aws iam disable-organizations-root-sessions
```
出力:  

```
{
    "EnabledFeatures": [
        "RootCredentialsManagement"
    ]
    "OrganizationId": "o-aa111bb222"
}
```
詳細については、*AWS IAM ユーザーガイド*の「[メンバーアカウントのルートアクセスを一元化する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DisableOrganizationsRootSessions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/disable-organizations-root-sessions.html)」を参照してください。

### `enable-mfa-device`
<a name="iam_EnableMfaDevice_cli_2_topic"></a>

次のコード例は、`enable-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**MFA デバイスを有効にするには**  
`create-virtual-mfa-device` コマンドを使用して新しい仮想 MFA デバイスを作成したら、その MFA デバイスをユーザーに割り当てることができます。次の `enable-mfa-device` の例では、シリアル番号 `arn:aws:iam::210987654321:mfa/BobsMFADevice` を持つ MFA デバイスをユーザー `Bob` に割り当てます。コマンドは、仮想 MFA デバイスからの最初の 2 つのコードを順番に含める AWS ことで、デバイスを と同期します。  

```
aws iam enable-mfa-device \
    --user-name Bob \
    --serial-number arn:aws:iam::210987654321:mfa/BobsMFADevice \
    --authentication-code1 123456 \
    --authentication-code2 789012
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[仮想多要素認証 (MFA) デバイスの有効化 (コンソール)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-mfa-device.html)」を参照してください。

### `enable-organizations-root-credentials-management`
<a name="iam_EnableOrganizationsRootCredentialsManagement_cli_2_topic"></a>

次のコード例は、`enable-organizations-root-credentials-management` を使用する方法を示しています。

**AWS CLI**  
**組織で RootCredentialsManagement 機能を有効にするには**  
次の `enable-organizations-root-credentials-management` コマンドは、組織内のメンバーアカウント全体で特権ルートユーザー認証情報の管理を有効にします。  

```
aws iam enable-organizations-root-credentials-management
```
出力:  

```
{
    "EnabledFeatures": [
        "RootCredentialsManagement"
    ]
    "OrganizationId": "o-aa111bb222"
}
```
詳細については、*AWS IAM ユーザーガイド*の「[メンバーアカウントのルートアクセスを一元化する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[EnableOrganizationsRootCredentialsManagement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-organizations-root-credentials-management.html)」を参照してください。

### `enable-organizations-root-sessions`
<a name="iam_EnableOrganizationsRootSessions_cli_2_topic"></a>

次のコード例は、`enable-organizations-root-sessions` を使用する方法を示しています。

**AWS CLI**  
**組織で RootSessions 機能を有効にするには**  
次の `enable-organizations-root-sessions` コマンドにより、管理アカウントまたは委任管理者が組織内のメンバーアカウントで特権タスクを実行できるようになります。  

```
aws iam enable-organizations-root-sessions
```
出力:  

```
{
    "EnabledFeatures": [
        "RootSessions"
    ]
    "OrganizationId": "o-aa111bb222"
}
```
詳細については、*AWS IAM ユーザーガイド*の「[メンバーアカウントのルートアクセスを一元化する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-enable-root-access.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[EnableOrganizationsRootSessions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/enable-organizations-root-sessions.html)」を参照してください。

### `generate-credential-report`
<a name="iam_GenerateCredentialReport_cli_2_topic"></a>

次のコード例は、`generate-credential-report` を使用する方法を示しています。

**AWS CLI**  
**認証情報レポートを生成するには**  
次の例では、 AWS アカウントの認証情報レポートを生成しようとします。  

```
aws iam generate-credential-report
```
出力:  

```
{
    "State":  "STARTED",
    "Description": "No report exists. Starting a new report generation task"
}
```
詳細については、*AWS IAM* [ユーザーガイドの AWS アカウントの認証情報レポート](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html)の取得を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateCredentialReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/generate-credential-report.html)」を参照してください。

### `generate-organizations-access-report`
<a name="iam_GenerateOrganizationsAccessReport_cli_2_topic"></a>

次のコード例は、`generate-organizations-access-report` を使用する方法を示しています。

**AWS CLI**  
**例 1: 組織内のルートのアクセスレポートを生成するには**  
次の `generate-organizations-access-report` の例では、バックグラウンドジョブを開始して、組織内の指定されたルートのアクセスレポートを作成します。`get-organizations-access-report` コマンドを実行すると、レポートを作成した後に表示できます。  

```
aws iam generate-organizations-access-report \
    --entity-path o-4fxmplt198/r-c3xb
```
出力:  

```
{
    "JobId": "a8b6c06f-aaa4-8xmp-28bc-81da71836359"
}
```
**例 2: 組織内のアカウントのアクセスレポートを生成するには**  
次の `generate-organizations-access-report` の例では、バックグラウンドジョブを開始して、組織 `o-4fxmplt198` のアカウント ID `123456789012` のアクセスレポートを作成します。`get-organizations-access-report` コマンドを実行すると、レポートを作成した後に表示できます。  

```
aws iam generate-organizations-access-report \
    --entity-path o-4fxmplt198/r-c3xb/123456789012
```
出力:  

```
{
    "JobId": "14b6c071-75f6-2xmp-fb77-faf6fb4201d2"
}
```
**例 3: 組織内の組織単位のアカウントのアクセスレポートを生成するには**  
次の `generate-organizations-access-report` の例では、バックグラウンドジョブを開始して、組織 `o-4fxmplt198` の組織単位 `ou-c3xb-lmu7j2yg` にアカウント ID `234567890123` のアクセスレポートを作成します。`get-organizations-access-report` コマンドを実行すると、レポートを作成した後に表示できます。  

```
aws iam generate-organizations-access-report \
    --entity-path o-4fxmplt198/r-c3xb/ou-c3xb-lmu7j2yg/234567890123
```
出力:  

```
{
    "JobId": "2eb6c2e6-0xmp-ec04-1425-c937916a64af"
}
```
組織内のルートと組織単位の詳細については、`organizations list-roots` コマンドと `organizations list-organizational-units-for-parent` コマンドを使用します。  
詳細については、*AWS IAM* [ユーザーガイドの「最終アクセス情報 AWS を使用した でのアクセス許可の改良](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateOrganizationsAccessReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/generate-organizations-access-report.html)」を参照してください。

### `generate-service-last-accessed-details`
<a name="iam_GenerateServiceLastAccessedDetails_cli_2_topic"></a>

次のコード例は、`generate-service-last-accessed-details` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムポリシーのサービスアクセスレポートを生成するには**  
次の `generate-service-last-accessed-details` の例では、バックグラウンドジョブを開始し、`intern-boundary` という名前のカスタムポリシーを使用して IAM ユーザーやその他のエンティティがアクセスしたサービスを一覧表示するレポートを生成します。`get-service-last-accessed-details` コマンドを実行すると、レポートを作成した後に表示できます。  

```
aws iam generate-service-last-accessed-details \
    --arn arn:aws:iam::123456789012:policy/intern-boundary
```
出力:  

```
{
    "JobId": "2eb6c2b8-7b4c-3xmp-3c13-03b72c8cdfdc"
}
```
**例 2: AWS マネージド AdministratorAccess ポリシーのサービスアクセスレポートを生成するには**  
次の の`generate-service-last-accessed-details`例では、バックグラウンドジョブを開始して、IAM ユーザーおよびその他のエンティティが AWS マネージド`AdministratorAccess`ポリシーでアクセスしたサービスを一覧表示するレポートを生成します。`get-service-last-accessed-details` コマンドを実行すると、レポートを作成した後に表示できます。  

```
aws iam generate-service-last-accessed-details \
    --arn arn:aws:iam::aws:policy/AdministratorAccess
```
出力:  

```
{
    "JobId": "78b6c2ba-d09e-6xmp-7039-ecde30b26916"
}
```
詳細については、*AWS IAM* [ユーザーガイドの「最終アクセス情報 AWS を使用した でのアクセス許可の改良](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateServiceLastAccessedDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/generate-service-last-accessed-details.html)」を参照してください。

### `get-access-key-last-used`
<a name="iam_GetAccessKeyLastUsed_cli_2_topic"></a>

次のコード例は、`get-access-key-last-used` を使用する方法を示しています。

**AWS CLI**  
**指定されたアクセスキーの最後の使用時の情報を取得するには**  
次の例では、アクセスキー `ABCDEXAMPLE` が最後に使用されたときに関する情報を取得します。  

```
aws iam get-access-key-last-used \
    --access-key-id ABCDEXAMPLE
```
出力:  

```
{
    "UserName":  "Bob",
    "AccessKeyLastUsed": {
        "Region": "us-east-1",
        "ServiceName": "iam",
        "LastUsedDate": "2015-06-16T22:45:00Z"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアクセスキーの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccessKeyLastUsed](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-access-key-last-used.html)」を参照してください。

### `get-account-authorization-details`
<a name="iam_GetAccountAuthorizationDetails_cli_2_topic"></a>

次の例は、`get-account-authorization-details` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントの IAM ユーザー、グループ、ロール、ポリシーを一覧表示するには**  
次の`get-account-authorization-details`コマンドは、 AWS アカウント内のすべての IAM ユーザー、グループ、ロール、ポリシーに関する情報を返します。  

```
aws iam get-account-authorization-details
```
出力:  

```
{
    "RoleDetailList": [
        {
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "RoleId": "AROA1234567890EXAMPLE",
            "CreateDate": "2014-07-30T17:09:20Z",
            "InstanceProfileList": [
                {
                    "InstanceProfileId": "AIPA1234567890EXAMPLE",
                    "Roles": [
                        {
                            "AssumeRolePolicyDocument": {
                                "Version":"2012-10-17",		 	 	 
                                "Statement": [
                                    {
                                        "Sid": "",
                                        "Effect": "Allow",
                                        "Principal": {
                                            "Service": "ec2.amazonaws.com"
                                        },
                                        "Action": "sts:AssumeRole"
                                    }
                                ]
                            },
                            "RoleId": "AROA1234567890EXAMPLE",
                            "CreateDate": "2014-07-30T17:09:20Z",
                            "RoleName": "EC2role",
                            "Path": "/",
                            "Arn": "arn:aws:iam::123456789012:role/EC2role"
                        }
                    ],
                    "CreateDate": "2014-07-30T17:09:20Z",
                    "InstanceProfileName": "EC2role",
                    "Path": "/",
                    "Arn": "arn:aws:iam::123456789012:instance-profile/EC2role"
                }
            ],
            "RoleName": "EC2role",
            "Path": "/",
            "AttachedManagedPolicies": [
                {
                    "PolicyName": "AmazonS3FullAccess",
                    "PolicyArn": "arn:aws:iam::aws:policy/AmazonS3FullAccess"
                },
                {
                    "PolicyName": "AmazonDynamoDBFullAccess",
                    "PolicyArn": "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess"
                }
            ],
            "RoleLastUsed": {
                "Region": "us-west-2",
                "LastUsedDate": "2019-11-13T17:30:00Z"
            },
            "RolePolicyList": [],
            "Arn": "arn:aws:iam::123456789012:role/EC2role"
        }
    ],
    "GroupDetailList": [
        {
            "GroupId": "AIDA1234567890EXAMPLE",
            "AttachedManagedPolicies": {
                "PolicyName": "AdministratorAccess",
                "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
            },
            "GroupName": "Admins",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:group/Admins",
            "CreateDate": "2013-10-14T18:32:24Z",
            "GroupPolicyList": []
        },
        {
            "GroupId": "AIDA1234567890EXAMPLE",
            "AttachedManagedPolicies": {
                "PolicyName": "PowerUserAccess",
                "PolicyArn": "arn:aws:iam::aws:policy/PowerUserAccess"
            },
            "GroupName": "Dev",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:group/Dev",
            "CreateDate": "2013-10-14T18:33:55Z",
            "GroupPolicyList": []
        },
        {
            "GroupId": "AIDA1234567890EXAMPLE",
            "AttachedManagedPolicies": [],
            "GroupName": "Finance",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:group/Finance",
            "CreateDate": "2013-10-14T18:57:48Z",
            "GroupPolicyList": [
                {
                    "PolicyName": "policygen-201310141157",
                    "PolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Action": "aws-portal:*",
                                "Sid": "Stmt1381777017000",
                                "Resource": "*",
                                "Effect": "Allow"
                            }
                        ]
                    }
                }
            ]
        }
    ],
    "UserDetailList": [
        {
            "UserName": "Alice",
            "GroupList": [
                "Admins"
            ],
            "CreateDate": "2013-10-14T18:32:24Z",
            "UserId": "AIDA1234567890EXAMPLE",
            "UserPolicyList": [],
            "Path": "/",
            "AttachedManagedPolicies": [],
            "Arn": "arn:aws:iam::123456789012:user/Alice"
        },
        {
            "UserName": "Bob",
            "GroupList": [
                "Admins"
            ],
            "CreateDate": "2013-10-14T18:32:25Z",
            "UserId": "AIDA1234567890EXAMPLE",
            "UserPolicyList": [
                {
                    "PolicyName": "DenyBillingAndIAMPolicy",
                    "PolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": {
                            "Effect": "Deny",
                            "Action": [
                                "aws-portal:*",
                                "iam:*"
                            ],
                            "Resource": "*"
                        }
                    }
                }
            ],
            "Path": "/",
            "AttachedManagedPolicies": [],
            "Arn": "arn:aws:iam::123456789012:user/Bob"
        },
        {
            "UserName": "Charlie",
            "GroupList": [
                "Dev"
            ],
            "CreateDate": "2013-10-14T18:33:56Z",
            "UserId": "AIDA1234567890EXAMPLE",
            "UserPolicyList": [],
            "Path": "/",
            "AttachedManagedPolicies": [],
            "Arn": "arn:aws:iam::123456789012:user/Charlie"
        }
    ],
    "Policies": [
        {
            "PolicyName": "create-update-delete-set-managed-policies",
            "CreateDate": "2015-02-06T19:58:34Z",
            "AttachmentCount": 1,
            "IsAttachable": true,
            "PolicyId": "ANPA1234567890EXAMPLE",
            "DefaultVersionId": "v1",
            "PolicyVersionList": [
                {
                    "CreateDate": "2015-02-06T19:58:34Z",
                    "VersionId": "v1",
                    "Document": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": {
                            "Effect": "Allow",
                            "Action": [
                                "iam:CreatePolicy",
                                "iam:CreatePolicyVersion",
                                "iam:DeletePolicy",
                                "iam:DeletePolicyVersion",
                                "iam:GetPolicy",
                                "iam:GetPolicyVersion",
                                "iam:ListPolicies",
                                "iam:ListPolicyVersions",
                                "iam:SetDefaultPolicyVersion"
                            ],
                            "Resource": "*"
                        }
                    },
                    "IsDefaultVersion": true
                }
            ],
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:policy/create-update-delete-set-managed-policies",
            "UpdateDate": "2015-02-06T19:58:34Z"
        },
        {
            "PolicyName": "S3-read-only-specific-bucket",
            "CreateDate": "2015-01-21T21:39:41Z",
            "AttachmentCount": 1,
            "IsAttachable": true,
            "PolicyId": "ANPA1234567890EXAMPLE",
            "DefaultVersionId": "v1",
            "PolicyVersionList": [
                {
                    "CreateDate": "2015-01-21T21:39:41Z",
                    "VersionId": "v1",
                    "Document": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Action": [
                                    "s3:Get*",
                                    "s3:List*"
                                ],
                                "Resource": [
                                    "arn:aws:s3:::amzn-s3-demo-bucket",
                                    "arn:aws:s3:::amzn-s3-demo-bucket/*"
                                ]
                            }
                        ]
                    },
                    "IsDefaultVersion": true
                }
            ],
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:policy/S3-read-only-specific-bucket",
            "UpdateDate": "2015-01-21T23:39:41Z"
        },
        {
            "PolicyName": "AmazonEC2FullAccess",
            "CreateDate": "2015-02-06T18:40:15Z",
            "AttachmentCount": 1,
            "IsAttachable": true,
            "PolicyId": "ANPA1234567890EXAMPLE",
            "DefaultVersionId": "v1",
            "PolicyVersionList": [
                {
                    "CreateDate": "2014-10-30T20:59:46Z",
                    "VersionId": "v1",
                    "Document": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Action": "ec2:*",
                                "Effect": "Allow",
                                "Resource": "*"
                            },
                            {
                                "Effect": "Allow",
                                "Action": "elasticloadbalancing:*",
                                "Resource": "*"
                            },
                            {
                                "Effect": "Allow",
                                "Action": "cloudwatch:*",
                                "Resource": "*"
                            },
                            {
                                "Effect": "Allow",
                                "Action": "autoscaling:*",
                                "Resource": "*"
                            }
                        ]
                    },
                    "IsDefaultVersion": true
                }
            ],
            "Path": "/",
            "Arn": "arn:aws:iam::aws:policy/AmazonEC2FullAccess",
            "UpdateDate": "2015-02-06T18:40:15Z"
        }
    ],
    "Marker": "EXAMPLEkakv9BCuUNFDtxWSyfzetYwEx2ADc8dnzfvERF5S6YMvXKx41t6gCl/eeaCX3Jo94/bKqezEAg8TEVS99EKFLxm3jtbpl25FDWEXAMPLE",
    "IsTruncated": true
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[AWS セキュリティ監査ガイドライン](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-audit-guide.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccountAuthorizationDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-account-authorization-details.html)」を参照してください。

### `get-account-password-policy`
<a name="iam_GetAccountPasswordPolicy_cli_2_topic"></a>

次のコード例は、`get-account-password-policy` を使用する方法を示しています。

**AWS CLI**  
**現在のアカウントのパスワードポリシーを表示するには**  
次の `get-account-password-policy` コマンドは、現在のアカウントのパスワードポリシーに関する詳細を表示します。  

```
aws iam get-account-password-policy
```
出力:  

```
{
    "PasswordPolicy": {
        "AllowUsersToChangePassword": false,
        "RequireLowercaseCharacters": false,
        "RequireUppercaseCharacters": false,
        "MinimumPasswordLength": 8,
        "RequireNumbers": true,
        "RequireSymbols": true
    }
}
```
アカウントのためにパスワードポリシーが定義されていない場合、コマンドは `NoSuchEntity` エラーを返します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアカウントパスワードポリシーの設定](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccountPasswordPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-account-password-policy.html)」を参照してください。

### `get-account-summary`
<a name="iam_GetAccountSummary_cli_2_topic"></a>

次のコード例は、`get-account-summary` を使用する方法を示しています。

**AWS CLI**  
**現在のアカウントの IAM エンティティの使用状況と IAM クォータに関する情報を取得するには**  
次の `get-account-summary` コマンドは、アカウント内の現在の IAM エンティティの使用状況と現在の IAM エンティティのクォータに関する情報を返します。  

```
aws iam get-account-summary
```
出力:  

```
{
    "SummaryMap": {
        "UsersQuota": 5000,
        "GroupsQuota": 100,
        "InstanceProfiles": 6,
        "SigningCertificatesPerUserQuota": 2,
        "AccountAccessKeysPresent": 0,
        "RolesQuota": 250,
        "RolePolicySizeQuota": 10240,
        "AccountSigningCertificatesPresent": 0,
        "Users": 27,
        "ServerCertificatesQuota": 20,
        "ServerCertificates": 0,
        "AssumeRolePolicySizeQuota": 2048,
        "Groups": 7,
        "MFADevicesInUse": 1,
        "Roles": 3,
        "AccountMFAEnabled": 1,
        "MFADevices": 3,
        "GroupsPerUserQuota": 10,
        "GroupPolicySizeQuota": 5120,
        "InstanceProfilesQuota": 100,
        "AccessKeysPerUserQuota": 2,
        "Providers": 0,
        "UserPolicySizeQuota": 2048
    }
}
```
エンティティの制限の詳細については、[IAM ユーザーガイドの「IAM および AWS STS クォータ](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccountSummary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-account-summary.html)」を参照してください。

### `get-context-keys-for-custom-policy`
<a name="iam_GetContextKeysForCustomPolicy_cli_2_topic"></a>

次のコード例は、`get-context-keys-for-custom-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: コマンドラインでパラメータとして指定された 1 つ以上のカスタム JSON ポリシーによって参照されるコンテキストキーを一覧表示するには**  
次の `get-context-keys-for-custom-policy` コマンドは、指定された各ポリシーを解析し、それらのポリシーが使用するコンテキストキーを一覧表示します。このコマンドを使用して、ポリシーシミュレータコマンド `simulate-custom-policy` と `simulate-custom-policy` を正常に使用するために指定する必要があるコンテキストキー値を特定します。また、`get-context-keys-for-custom-policy` コマンドを使用して、IAM ユーザーまたはロールに関連付けられたすべてのポリシーで使用されるコンテキストキーのリストを取得することもできます。`file://` で始まるパラメータ値は、ファイルを読み取り、ファイル名自体ではなくその内容をパラメータの値として使用するようにコマンドに指示します。  

```
aws iam get-context-keys-for-custom-policy \
    --policy-input-list '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/${aws:username}","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
```
出力:  

```
{
    "ContextKeyNames": [
        "aws:username",
        "aws:CurrentTime"
    ]
}
```
**例 2: ファイル入力として提供される 1 つ以上のカスタム JSON ポリシーによって参照されるコンテキストキーを一覧表示するには**  
次の `get-context-keys-for-custom-policy` コマンドは前の例と同じですが、ポリシーがパラメータとしてではなくファイルで提供される点が異なります。このコマンドは JSON 構造のリストではなく JSON 文字列のリストを想定しているため、ファイルは次のような構造にする必要があります。ただし、1 つにまとめることはできます。  

```
[
    "Policy1",
    "Policy2"
]
```
そのため、例えば、前の例のポリシーを含むファイルは次のようになっている必要があります。ポリシー文字列内に埋め込まれている各二重引用符の前に「バックスラッシュ」を付けてエスケープする必要があります。  

```
[ "{\"Version\": \"2012-10-17\", \"Statement\": {\"Effect\": \"Allow\", \"Action\": \"dynamodb:*\", \"Resource\": \"arn:aws:dynamodb:us-west-2:128716708097:table/${aws:username}\", \"Condition\": {\"DateGreaterThan\": {\"aws:CurrentTime\": \"2015-08-16T12:00:00Z\"}}}}" ]
```
その後、このファイルを次のコマンドに送信できます。  

```
aws iam get-context-keys-for-custom-policy \
    --policy-input-list file://policyfile.json
```
出力:  

```
{
    "ContextKeyNames": [
        "aws:username",
        "aws:CurrentTime"
    ]
}
```
詳細については、IAM [ユーザーガイドの「IAM Policy Simulator (AWS CLI および AWS API)](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html#policies-simulator-using-api) の使用」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContextKeysForCustomPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-context-keys-for-custom-policy.html)」を参照してください。

### `get-context-keys-for-principal-policy`
<a name="iam_GetContextKeysForPrincipalPolicy_cli_2_topic"></a>

次のコード例は、`get-context-keys-for-principal-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM プリンシパルに関連付けられているすべてのポリシーが参照するコンテキストキーを一覧表示するには**  
次の `get-context-keys-for-principal-policy` コマンドは、ユーザー `saanvi` とそのユーザーがメンバーとなっているグループにアタッチされているすべてのポリシーを取得します。次に、このコマンドは各ポリシーを解析し、それらのポリシーで使用されているコンテキストキーを一覧表示します。このコマンドを使用して、`simulate-custom-policy` および `simulate-principal-policy` コマンドを正常に使用するために指定する必要があるコンテキストキー値を特定します。`get-context-keys-for-custom-policy` コマンドを使用して、任意の JSON ポリシーで使用されているコンテキストキーのリストを取得することもできます。  

```
aws iam get-context-keys-for-principal-policy \
   --policy-source-arn arn:aws:iam::123456789012:user/saanvi
```
出力:  

```
{
    "ContextKeyNames": [
        "aws:username",
        "aws:CurrentTime"
    ]
}
```
詳細については、IAM [ユーザーガイドの「IAM Policy Simulator (AWS CLI および AWS API)](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html#policies-simulator-using-api) の使用」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContextKeysForPrincipalPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-context-keys-for-principal-policy.html)」を参照してください。

### `get-credential-report`
<a name="iam_GetCredentialReport_cli_2_topic"></a>

次のコード例は、`get-credential-report` を使用する方法を示しています。

**AWS CLI**  
**認証情報レポートを取得するには**  
この例では、返されたレポートを開き、それをテキスト行の配列としてパイプラインに出力します。  

```
aws iam get-credential-report
```
出力:  

```
{
    "GeneratedTime":  "2015-06-17T19:11:50Z",
    "ReportFormat": "text/csv"
}
```
詳細については、*AWS IAM* [ユーザーガイドの AWS アカウントの認証情報レポート](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html)の取得を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCredentialReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-credential-report.html)」を参照してください。

### `get-group-policy`
<a name="iam_GetGroupPolicy_cli_2_topic"></a>

次のコード例は、`get-group-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM グループにアタッチされたポリシーに関する情報を取得するには**  
次の `get-group-policy` コマンドは、`Test-Group` という名前のグループにアタッチされている指定されたポリシーに関する情報を取得します。  

```
aws iam get-group-policy \
    --group-name Test-Group \
    --policy-name S3-ReadOnly-Policy
```
出力:  

```
{
    "GroupName": "Test-Group",
    "PolicyDocument": {
        "Statement": [
            {
                "Action": [
                    "s3:Get*",
                    "s3:List*"
                ],
                "Resource": "*",
                "Effect": "Allow"
            }
        ]
    },
    "PolicyName": "S3-ReadOnly-Policy"
}
```
IAM ポリシーの詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ポリシーを管理する](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-group-policy.html)」を参照してください。

### `get-group`
<a name="iam_GetGroup_cli_2_topic"></a>

次のコード例は、`get-group` を使用する方法を示しています。

**AWS CLI**  
**IAM グループを取得するには**  
この例では、IAM グループ `Admins` に関する詳細を返します。  

```
aws iam get-group \
    --group-name Admins
```
出力:  

```
{
    "Group": {
        "Path": "/",
        "CreateDate": "2015-06-16T19:41:48Z",
        "GroupId": "AIDGPMS9RO4H3FEXAMPLE",
        "Arn": "arn:aws:iam::123456789012:group/Admins",
        "GroupName": "Admins"
    },
    "Users": []
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ID (ユーザー、ユーザーグループ、ロール)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-group.html)」を参照してください。

### `get-instance-profile`
<a name="iam_GetInstanceProfile_cli_2_topic"></a>

次のコード例は、`get-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**インスタンスプロファイルの情報を取得するには**  
次の `get-instance-profile` コマンドは、`ExampleInstanceProfile` という名前のインスタンスプロファイルに関する情報を取得します。  

```
aws iam get-instance-profile \
    --instance-profile-name ExampleInstanceProfile
```
出力:  

```
{
    "InstanceProfile": {
        "InstanceProfileId": "AID2MAB8DPLSRHEXAMPLE",
        "Roles": [
            {
                "AssumeRolePolicyDocument": "<URL-encoded-JSON>",
                "RoleId": "AIDGPMS9RO4H3FEXAMPLE",
                "CreateDate": "2013-01-09T06:33:26Z",
                "RoleName": "Test-Role",
                "Path": "/",
                "Arn": "arn:aws:iam::336924118301:role/Test-Role"
            }
        ],
        "CreateDate": "2013-06-12T23:52:02Z",
        "InstanceProfileName": "ExampleInstanceProfile",
        "Path": "/",
        "Arn": "arn:aws:iam::336924118301:instance-profile/ExampleInstanceProfile"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[インスタンスプロファイルの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-instance-profile.html)」を参照してください。

### `get-login-profile`
<a name="iam_GetLoginProfile_cli_2_topic"></a>

次のコード例は、`get-login-profile` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのパスワード情報を取得するには**  
次の `get-login-profile` コマンドは、`Bob` という名前の IAM ユーザーのパスワードに関する情報を取得します。  

```
aws iam get-login-profile \
    --user-name Bob
```
出力:  

```
{
    "LoginProfile": {
        "UserName": "Bob",
        "CreateDate": "2012-09-21T23:03:39Z"
    }
}
```
`get-login-profile` コマンドを使用して、IAM ユーザーがパスワードを持っていることを確認できます。ユーザーのためにパスワードが定義されていない場合、コマンドは `NoSuchEntity` エラーを返します。  
このコマンドを使用してパスワードを表示することはできません。パスワードを忘れた場合は、ユーザーのパスワードをリセットできます (`update-login-profile`)。または、ユーザーのログインプロファイルを削除し (`delete-login-profile`)、新しいログインプロファイルを作成することもできます (`create-login-profile`)。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのパスワードの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-login-profile.html)」を参照してください。

### `get-mfa-device`
<a name="iam_GetMfaDevice_cli_2_topic"></a>

次のコード例は、`get-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**FIDO セキュリティキーに関する情報を取得するには**  
次の `get-mfa-device` のコマンド例では、指定された FIDO セキュリティキーに関する情報を取得します。  

```
aws iam get-mfa-device \
    --serial-number arn:aws:iam::123456789012:u2f/user/alice/fidokeyname-EXAMPLEBN5FHTECLFG7EXAMPLE
```
出力:  

```
{
    "UserName": "alice",
    "SerialNumber": "arn:aws:iam::123456789012:u2f/user/alice/fidokeyname-EXAMPLEBN5FHTECLFG7EXAMPLE",
    "EnableDate": "2023-09-19T01:49:18+00:00",
    "Certifications": {
        "FIDO": "L1"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[AWSでの多要素認証 (MFA) の使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-mfa-device.html)」を参照してください。

### `get-open-id-connect-provider`
<a name="iam_GetOpenIdConnectProvider_cli_2_topic"></a>

次のコード例は、`get-open-id-connect-provider` を使用する方法を示しています。

**AWS CLI**  
**指定した OpenID Connect プロバイダーに関する情報を返すには**  
この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/server.example.com` である OpenID Connect プロバイダーに関する詳細を返します。  

```
aws iam get-open-id-connect-provider \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/server.example.com
```
出力:  

```
{
    "Url": "server.example.com"
        "CreateDate": "2015-06-16T19:41:48Z",
        "ThumbprintList": [
        "12345abcdefghijk67890lmnopqrst987example"
        ],
        "ClientIDList": [
        "example-application-ID"
        ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-open-id-connect-provider.html)」を参照してください。

### `get-organizations-access-report`
<a name="iam_GetOrganizationsAccessReport_cli_2_topic"></a>

次のコード例は、`get-organizations-access-report` を使用する方法を示しています。

**AWS CLI**  
**アクセスレポートを取得するには**  
次の の`get-organizations-access-report`例では、以前に生成された AWS Organizations エンティティのアクセスレポートを表示します。レポートを生成するには、`generate-organizations-access-report` コマンドを使用します。  

```
aws iam get-organizations-access-report \
    --job-id a8b6c06f-aaa4-8xmp-28bc-81da71836359
```
出力:  

```
{
    "JobStatus": "COMPLETED",
    "JobCreationDate": "2019-09-30T06:53:36.187Z",
    "JobCompletionDate": "2019-09-30T06:53:37.547Z",
    "NumberOfServicesAccessible": 188,
    "NumberOfServicesNotAccessed": 171,
    "AccessDetails": [
        {
            "ServiceName": "Alexa for Business",
            "ServiceNamespace": "a4b",
            "TotalAuthenticatedEntities": 0
        },
        ...
}
```
詳細については、*AWS IAM* [ユーザーガイドの「最終アクセス情報 AWS を使用した でのアクセス許可の改良](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOrganizationsAccessReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-organizations-access-report.html)」を参照してください。

### `get-policy-version`
<a name="iam_GetPolicyVersion_cli_2_topic"></a>

次のコード例は、`get-policy-version` を使用する方法を示しています。

**AWS CLI**  
**指定された管理ポリシーの指定されたバージョンに関する情報を取得するには**  
この例では、ARN が `arn:aws:iam::123456789012:policy/MyManagedPolicy` であるポリシーの v2 バージョンのポリシードキュメントを返します。  

```
aws iam get-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --version-id v2
```
出力:  

```
{
    "PolicyVersion": {
        "Document": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Action": "iam:*",
                    "Resource": "*"
                }
            ]
        },
        "VersionId": "v2",
        "IsDefaultVersion": true,
        "CreateDate": "2023-04-11T00:22:54+00:00"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-policy-version.html)」を参照してください。

### `get-policy`
<a name="iam_GetPolicy_cli_2_topic"></a>

次のコード例は、`get-policy` を使用する方法を示しています。

**AWS CLI**  
**指定した管理ポリシーに関する情報を取得するには**  
この例では、ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` である管理ポリシーに関する詳細を返します。  

```
aws iam get-policy \
    --policy-arn arn:aws:iam::123456789012:policy/MySamplePolicy
```
出力:  

```
{
    "Policy": {
        "PolicyName": "MySamplePolicy",
        "CreateDate": "2015-06-17T19:23;32Z",
        "AttachmentCount": 0,
        "IsAttachable": true,
        "PolicyId": "Z27SI6FQMGNQ2EXAMPLE1",
        "DefaultVersionId": "v1",
        "Path": "/",
        "Arn": "arn:aws:iam::123456789012:policy/MySamplePolicy",
        "UpdateDate": "2015-06-17T19:23:32Z"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-policy.html)」を参照してください。

### `get-role-policy`
<a name="iam_GetRolePolicy_cli_2_topic"></a>

次のコード例は、`get-role-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールにアタッチされたポリシーに関する情報を取得するには**  
次の `get-role-policy` コマンドは、`Test-Role` という名前のロールにアタッチされている指定されたポリシーに関する情報を取得します。  

```
aws iam get-role-policy \
    --role-name Test-Role \
    --policy-name ExamplePolicy
```
出力:  

```
{
  "RoleName": "Test-Role",
  "PolicyDocument": {
      "Statement": [
          {
              "Action": [
                  "s3:ListBucket",
                  "s3:Put*",
                  "s3:Get*",
                  "s3:*MultipartUpload*"
              ],
              "Resource": "*",
              "Effect": "Allow",
              "Sid": "1"
          }
      ]
  }
  "PolicyName": "ExamplePolicy"
}
```
詳細については、「AWS IAM ユーザーガイド」の「[IAM ロールの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-role-policy.html)」を参照してください。

### `get-role`
<a name="iam_GetRole_cli_2_topic"></a>

次のコード例は、`get-role` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールに関する情報を取得するには**  
次の `get-role` コマンドは、`Test-Role` という名前のロールに関する情報を取得します。  

```
aws iam get-role \
    --role-name Test-Role
```
出力:  

```
{
    "Role": {
        "Description": "Test Role",
        "AssumeRolePolicyDocument":"<URL-encoded-JSON>",
        "MaxSessionDuration": 3600,
        "RoleId": "AROA1234567890EXAMPLE",
        "CreateDate": "2019-11-13T16:45:56Z",
        "RoleName": "Test-Role",
        "Path": "/",
        "RoleLastUsed": {
            "Region": "us-east-1",
            "LastUsedDate": "2019-11-13T17:14:00Z"
        },
        "Arn": "arn:aws:iam::123456789012:role/Test-Role"
    }
}
```
このコマンドは、ロールにアタッチされている信頼ポリシーを表示します。ロールにアタッチされているアクセス許可ポリシーを一覧表示するには、`list-role-policies` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ロールの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-role.html)」を参照してください。

### `get-saml-provider`
<a name="iam_GetSamlProvider_cli_2_topic"></a>

次のコード例は、`get-saml-provider` を使用する方法を示しています。

**AWS CLI**  
**SAML プロバイダーのメタドキュメントを取得するには**  
この例では、ARM が `arn:aws:iam::123456789012:saml-provider/SAMLADFS` である SAML 2.0 プロバイダーに関する詳細を取得します。レスポンスには、SAML プロバイダーエンティティを作成するために ID AWS プロバイダーから取得したメタデータドキュメントと、作成日と有効期限が含まれます。  

```
aws iam get-saml-provider \
    --saml-provider-arn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
出力:  

```
{
    "SAMLMetadataDocument": "...SAMLMetadataDocument-XML...",
    "CreateDate": "2017-03-06T22:29:46+00:00",
    "ValidUntil": "2117-03-06T22:29:46.433000+00:00",
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM SAML ID プロバイダーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSamlProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-saml-provider.html)」を参照してください。

### `get-server-certificate`
<a name="iam_GetServerCertificate_cli_2_topic"></a>

次の例は、`get-server-certificate` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのサーバー証明書の詳細を取得するには**  
次の `get-server-certificate` コマンドは、 AWS アカウント内の指定されたサーバー証明書に関する詳細をすべて取得します。  

```
aws iam get-server-certificate \
    --server-certificate-name myUpdatedServerCertificate
```
出力:  

```
{
    "ServerCertificate": {
        "ServerCertificateMetadata": {
            "Path": "/",
            "ServerCertificateName": "myUpdatedServerCertificate",
            "ServerCertificateId": "ASCAEXAMPLE123EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:server-certificate/myUpdatedServerCertificate",
            "UploadDate": "2019-04-22T21:13:44+00:00",
            "Expiration": "2019-10-15T22:23:16+00:00"
        },
        "CertificateBody": "-----BEGIN CERTIFICATE-----
            MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
            VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
            b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
            BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
            MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
            VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
            b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
            YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
            21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
            rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
            Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
            nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
            FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
            NYiytVbZPQUQ5Yaxu2jXnimvrszlaEXAMPLE=-----END CERTIFICATE-----",
        "CertificateChain": "-----BEGIN CERTIFICATE-----\nMIICiTCCAfICCQD6md
            7oRw0uXOjANBgkqhkiG9w0BAqQUFADCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgT
            AldBMRAwDgYDVQQHEwdTZWF0drGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAs
            TC0lBTSBDb25zb2xlMRIwEAYDVsQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQ
            jb20wHhcNMTEwNDI1MjA0NTIxWhtcNMTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBh
            MCVVMxCzAJBgNVBAgTAldBMRAwDgsYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBb
            WF6b24xFDASBgNVBAsTC0lBTSBDb2d5zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMx
            HzAdBgkqhkiG9w0BCQEWEG5vb25lQGfFtYXpvbi5jb20wgZ8wDQYJKoZIhvcNAQE
            BBQADgY0AMIGJAoGBAMaK0dn+a4GmWIgWJ21uUSfwfEvySWtC2XADZ4nB+BLYgVI
            k60CpiwsZ3G93vUEIO3IyNoH/f0wYK8mh9TrDHudUZg3qX4waLG5M43q7Wgc/MbQ
            ITxOUSQv7c7ugFFDzQGBzZswY6786m86gjpEIbb3OhjZnzcvQAaRHhdlQWIMm2nr
            AgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCku4nUhVVxYUntneD9+h8Mg9q6q+auN
            KyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0FlkbFFBjvSfpJIlJ00zbhNYS5f6Guo
            EDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjS;TbNYiytVbZPQUQ5Yaxu2jXnimvw
            3rrszlaEWEG5vb25lQGFtsYXpvbiEXAMPLE=\n-----END CERTIFICATE-----"
    }
}
```
 AWS アカウントで使用可能なサーバー証明書を一覧表示するには、 `list-server-certificates` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM でのサーバー証明書の管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-server-certificate.html)」を参照してください。

### `get-service-last-accessed-details-with-entities`
<a name="iam_GetServiceLastAccessedDetailsWithEntities_cli_2_topic"></a>

次のコード例は、`get-service-last-accessed-details-with-entities` を使用する方法を示しています。

**AWS CLI**  
**サービスの詳細を含むサービスアクセスレポートを取得するには**  
次の `get-service-last-accessed-details-with-entities` の例では、指定されたサービスにアクセスした IAM ユーザーやその他のエンティティに関する詳細を含むレポートを取得します。レポートを生成するには、`generate-service-last-accessed-details` コマンドを使用します。名前空間でアクセスされるサービスのリストを取得するには、`get-service-last-accessed-details` を使用します。  

```
aws iam get-service-last-accessed-details-with-entities \
    --job-id 78b6c2ba-d09e-6xmp-7039-ecde30b26916 \
    --service-namespace lambda
```
出力:  

```
{
    "JobStatus": "COMPLETED",
    "JobCreationDate": "2019-10-01T03:55:41.756Z",
    "JobCompletionDate": "2019-10-01T03:55:42.533Z",
    "EntityDetailsList": [
        {
            "EntityInfo": {
                "Arn": "arn:aws:iam::123456789012:user/admin",
                "Name": "admin",
                "Type": "USER",
                "Id": "AIDAIO2XMPLENQEXAMPLE",
                "Path": "/"
            },
            "LastAuthenticated": "2019-09-30T23:02:00Z"
        },
        {
            "EntityInfo": {
                "Arn": "arn:aws:iam::123456789012:user/developer",
                "Name": "developer",
                "Type": "USER",
                "Id": "AIDAIBEYXMPL2YEXAMPLE",
                "Path": "/"
            },
            "LastAuthenticated": "2019-09-16T19:34:00Z"
        }
    ]
}
```
詳細については、*AWS IAM* [ユーザーガイドの「最終アクセス情報 AWS を使用した でのアクセス許可の改良](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceLastAccessedDetailsWithEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-service-last-accessed-details-with-entities.html)」を参照してください。

### `get-service-last-accessed-details`
<a name="iam_GetServiceLastAccessedDetails_cli_2_topic"></a>

次のコード例は、`get-service-last-accessed-details` を使用する方法を示しています。

**AWS CLI**  
**サービスアクセスレポートを取得するには**  
次の `get-service-last-accessed-details` の例では、IAM エンティティがアクセスしたサービスを一覧表示する、以前に生成したレポートを取得します。レポートを生成するには、`generate-service-last-accessed-details` コマンドを使用します。  

```
aws iam get-service-last-accessed-details \
    --job-id 2eb6c2b8-7b4c-3xmp-3c13-03b72c8cdfdc
```
出力:  

```
{
    "JobStatus": "COMPLETED",
    "JobCreationDate": "2019-10-01T03:50:35.929Z",
    "ServicesLastAccessed": [
        ...
        {
            "ServiceName": "AWS Lambda",
            "LastAuthenticated": "2019-09-30T23:02:00Z",
            "ServiceNamespace": "lambda",
            "LastAuthenticatedEntity": "arn:aws:iam::123456789012:user/admin",
            "TotalAuthenticatedEntities": 6
        },
    ]
}
```
詳細については、*AWS IAM* [ユーザーガイドの「最終アクセス情報 AWS を使用した でのアクセス許可の改良](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_access-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceLastAccessedDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-service-last-accessed-details.html)」を参照してください。

### `get-service-linked-role-deletion-status`
<a name="iam_GetServiceLinkedRoleDeletionStatus_cli_2_topic"></a>

次のコード例は、`get-service-linked-role-deletion-status` を使用する方法を示しています。

**AWS CLI**  
**サービスにリンクされたロールの削除リクエストのステータスを確認するには**  
次の `get-service-linked-role-deletion-status` の例では、サービスにリンクされたロールを削除するという以前のリクエストのステータスが表示されます。削除オペレーションは非同期で実行されます。リクエストを実行すると、このコマンドのパラメータとして指定した `DeletionTaskId` の値を取得します。  

```
aws iam get-service-linked-role-deletion-status \
    --deletion-task-id task/aws-service-role/lex.amazonaws.com/AWSServiceRoleForLexBots/1a2b3c4d-1234-abcd-7890-abcdeEXAMPLE
```
出力:  

```
{
"Status": "SUCCEEDED"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[サービスにリンクされたロールの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceLinkedRoleDeletionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-service-linked-role-deletion-status.html)」を参照してください。

### `get-ssh-public-key`
<a name="iam_GetSshPublicKey_cli_2_topic"></a>

次のコード例は、`get-ssh-public-key` を使用する方法を示しています。

**AWS CLI**  
**例 1: SSH エンコード形式で IAM ユーザーに添付された SSH パブリックキーを取得するには**  
次の `get-ssh-public-key` コマンドは、IAM ユーザー `sofia` から指定された SSH パブリックキーを取得します。出力は SSH エンコーディングです。  

```
aws iam get-ssh-public-key \
    --user-name sofia \
    --ssh-public-key-id APKA123456789EXAMPLE \
    --encoding SSH
```
出力:  

```
{
    "SSHPublicKey": {
        "UserName": "sofia",
        "SSHPublicKeyId": "APKA123456789EXAMPLE",
        "Fingerprint": "12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef",
        "SSHPublicKeyBody": "ssh-rsa <<long encoded SSH string>>",
        "Status": "Inactive",
        "UploadDate": "2019-04-18T17:04:49+00:00"
    }
}
```
**例 2: PEM エンコード形式で IAM ユーザーに添付された SSH パブリックキーを取得するには**  
次の `get-ssh-public-key` コマンドは、IAM ユーザー `sofia` から指定された SSH パブリックキーを取得します。出力は PEM エンコーディングです。  

```
aws iam get-ssh-public-key \
    --user-name sofia \
    --ssh-public-key-id APKA123456789EXAMPLE \
    --encoding PEM
```
出力:  

```
{
    "SSHPublicKey": {
        "UserName": "sofia",
        "SSHPublicKeyId": "APKA123456789EXAMPLE",
        "Fingerprint": "12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef",
        "SSHPublicKeyBody": ""-----BEGIN PUBLIC KEY-----\n<<long encoded PEM string>>\n-----END PUBLIC KEY-----\n"",
        "Status": "Inactive",
        "UploadDate": "2019-04-18T17:04:49+00:00"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[CodeCommit で SSH キーと SSH を使用する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html#ssh-keys-code-commit)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSshPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-ssh-public-key.html)」を参照してください。

### `get-user-policy`
<a name="iam_GetUserPolicy_cli_2_topic"></a>

次のコード例は、`get-user-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのポリシーの詳細を一覧表示するには**  
次の `get-user-policy` コマンドは、`Bob` という名前の IAM ユーザーにアタッチされている指定されたポリシーの詳細を一覧表示します。  

```
aws iam get-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy
```
出力:  

```
{
    "UserName": "Bob",
    "PolicyName": "ExamplePolicy",
    "PolicyDocument": {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Action": "*",
                "Resource": "*",
                "Effect": "Allow"
            }
        ]
    }
}
```
IAM ユーザーのポリシーのリストを取得するには、`list-user-policies` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-user-policy.html)」を参照してください。

### `get-user`
<a name="iam_GetUser_cli_2_topic"></a>

次のコード例は、`get-user` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーに関する情報を取得するには**  
次の `get-user` コマンドは、`Paulo` という名前の IAM ユーザーに関する情報を取得します。  

```
aws iam get-user \
    --user-name Paulo
```
出力:  

```
{
    "User": {
        "UserName": "Paulo",
        "Path": "/",
        "CreateDate": "2019-09-21T23:03:13Z",
        "UserId": "AIDA123456789EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:user/Paulo"
    }
}
```
IAM ポリシーの詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーを管理する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/get-user.html)」を参照してください。

### `list-access-keys`
<a name="iam_ListAccessKeys_cli_2_topic"></a>

次のコード例は、`list-access-keys` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのアクセスキー ID を一覧表示するには**  
次の `list-access-keys` コマンドは、`Bob` という名前の IAM ユーザーのアクセスキー ID を一覧表示します。  

```
aws iam list-access-keys \
    --user-name Bob
```
出力:  

```
{
    "AccessKeyMetadata": [
        {
            "UserName": "Bob",
            "Status": "Active",
            "CreateDate": "2013-06-04T18:17:34Z",
            "AccessKeyId": "AKIAIOSFODNN7EXAMPLE"
        },
        {
            "UserName": "Bob",
            "Status": "Inactive",
            "CreateDate": "2013-06-06T20:42:26Z",
            "AccessKeyId": "AKIAI44QH8DHBEXAMPLE"
        }
    ]
}
```
IAM ユーザーのシークレットアクセスキーを一覧表示することはできません。シークレットアクセスキーを紛失した場合は、`create-access-keys` コマンドを使用して新しいアクセスキーを作成する必要があります。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアクセスキーの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-access-keys.html)」を参照してください。

### `list-account-aliases`
<a name="iam_ListAccountAliases_cli_2_topic"></a>

次のコード例は、`list-account-aliases` を使用する方法を示しています。

**AWS CLI**  
**アカウントエイリアスを一覧表示するには**  
次の `list-account-aliases` コマンドは、現在のアカウントのエイリアスを一覧表示します。  

```
aws iam list-account-aliases
```
出力:  

```
{
    "AccountAliases": [
    "mycompany"
    ]
}
```
詳細については、*AWS IAM* [ユーザーガイドの「 AWS アカウント ID とそのエイリアス](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccountAliases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-account-aliases.html)」を参照してください。

### `list-attached-group-policies`
<a name="iam_ListAttachedGroupPolicies_cli_2_topic"></a>

次のコード例は、`list-attached-group-policies` を使用する方法を示しています。

**AWS CLI**  
**指定されたグループにアタッチされているすべての管理ポリシーを一覧表示するには**  
この例では、 AWS アカウント`Admins`内の という名前の IAM グループにアタッチされている管理ポリシーの名前と ARNs を返します。  

```
aws iam list-attached-group-policies \
    --group-name Admins
```
出力:  

```
{
    "AttachedPolicies": [
        {
            "PolicyName": "AdministratorAccess",
            "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
        },
        {
            "PolicyName": "SecurityAudit",
            "PolicyArn": "arn:aws:iam::aws:policy/SecurityAudit"
        }
    ],
    "IsTruncated": false
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttachedGroupPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-attached-group-policies.html)」を参照してください。

### `list-attached-role-policies`
<a name="iam_ListAttachedRolePolicies_cli_2_topic"></a>

次のコード例は、`list-attached-role-policies` を使用する方法を示しています。

**AWS CLI**  
**指定された IAM ロールにアタッチされている管理ポリシーを一覧表示するには**  
このコマンドは、 AWS アカウント`SecurityAuditRole`で という名前の IAM ロールにアタッチされた管理ポリシーの名前と ARNs を返します。  

```
aws iam list-attached-role-policies \
    --role-name SecurityAuditRole
```
出力:  

```
{
    "AttachedPolicies": [
        {
            "PolicyName": "SecurityAudit",
            "PolicyArn": "arn:aws:iam::aws:policy/SecurityAudit"
        }
    ],
    "IsTruncated": false
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttachedRolePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-attached-role-policies.html)」を参照してください。

### `list-attached-user-policies`
<a name="iam_ListAttachedUserPolicies_cli_2_topic"></a>

次のコード例は、`list-attached-user-policies` を使用する方法を示しています。

**AWS CLI**  
**指定されたユーザーにアタッチされているすべての管理ポリシーを一覧表示するには**  
このコマンドは、 AWS アカウント`Bob`で という名前の IAM ユーザー用の管理ポリシーの名前と ARNs を返します。  

```
aws iam list-attached-user-policies \
    --user-name Bob
```
出力:  

```
{
    "AttachedPolicies": [
        {
            "PolicyName": "AdministratorAccess",
            "PolicyArn": "arn:aws:iam::aws:policy/AdministratorAccess"
        },
        {
            "PolicyName": "SecurityAudit",
            "PolicyArn": "arn:aws:iam::aws:policy/SecurityAudit"
        }
    ],
    "IsTruncated": false
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttachedUserPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-attached-user-policies.html)」を参照してください。

### `list-entities-for-policy`
<a name="iam_ListEntitiesForPolicy_cli_2_topic"></a>

次のコード例は、`list-entities-for-policy` を使用する方法を示しています。

**AWS CLI**  
**指定された管理ポリシーがアタッチされているすべてのユーザー、グループ、ロールを一覧表示するには**  
この例では、ポリシー `arn:aws:iam::123456789012:policy/TestPolicy` がアタッチされている IAM グループ、ロール、ユーザーのリストを返します。  

```
aws iam list-entities-for-policy \
    --policy-arn arn:aws:iam::123456789012:policy/TestPolicy
```
出力:  

```
{
    "PolicyGroups": [
        {
            "GroupName": "Admins",
            "GroupId": "AGPACKCEVSQ6C2EXAMPLE"
        }
    ],
    "PolicyUsers": [
        {
            "UserName": "Alice",
            "UserId": "AIDACKCEVSQ6C2EXAMPLE"
        }
    ],
    "PolicyRoles": [
        {
            "RoleName": "DevRole",
            "RoleId": "AROADBQP57FF2AEXAMPLE"
        }
    ],
    "IsTruncated": false
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEntitiesForPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-entities-for-policy.html)」を参照してください。

### `list-group-policies`
<a name="iam_ListGroupPolicies_cli_2_topic"></a>

次のコード例は、`list-group-policies` を使用する方法を示しています。

**AWS CLI**  
**指定されたグループにアタッチされているすべてのインラインポリシーを一覧表示するには**  
次の `list-group-policies` コマンドは、現在のアカウントの `Admins` という名前の IAM グループにアタッチされているインラインポリシーの名前を一覧表示します。  

```
aws iam list-group-policies \
    --group-name Admins
```
出力:  

```
{
    "PolicyNames": [
        "AdminRoot",
        "ExamplePolicy"
    ]
}
```
IAM ポリシーの詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ポリシーを管理する](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-group-policies.html)」を参照してください。

### `list-groups-for-user`
<a name="iam_ListGroupsForUser_cli_2_topic"></a>

次のコード例は、`list-groups-for-user` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーが属する IAM グループを一覧表示するには**  
次の `list-groups-for-user` コマンドは、`Bob` という IAM ユーザーが属するグループを表示します。  

```
aws iam list-groups-for-user \
    --user-name Bob
```
出力:  

```
{
    "Groups": [
        {
            "Path": "/",
            "CreateDate": "2013-05-06T01:18:08Z",
            "GroupId": "AKIAIOSFODNN7EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/Admin",
            "GroupName": "Admin"
        },
        {
            "Path": "/",
            "CreateDate": "2013-05-06T01:37:28Z",
            "GroupId": "AKIAI44QH8DHBEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/s3-Users",
            "GroupName": "s3-Users"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupsForUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-groups-for-user.html)」を参照してください。

### `list-groups`
<a name="iam_ListGroups_cli_2_topic"></a>

次のコード例は、`list-groups` を使用する方法を示しています。

**AWS CLI**  
**現在のアカウントの IAM グループを一覧表示するには**  
次の `list-groups` コマンドは、現在のアカウントの IAM グループを一覧表示します。  

```
aws iam list-groups
```
出力:  

```
{
    "Groups": [
        {
            "Path": "/",
            "CreateDate": "2013-06-04T20:27:27.972Z",
            "GroupId": "AIDACKCEVSQ6C2EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/Admins",
            "GroupName": "Admins"
        },
        {
            "Path": "/",
            "CreateDate": "2013-04-16T20:30:42Z",
            "GroupId": "AIDGPMS9RO4H3FEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:group/S3-Admins",
            "GroupName": "S3-Admins"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-groups.html)」を参照してください。

### `list-instance-profile-tags`
<a name="iam_ListInstanceProfileTags_cli_2_topic"></a>

次のコード例は、`list-instance-profile-tags` を使用する方法を示しています。

**AWS CLI**  
**インスタンスプロファイルにアタッチされているタグを一覧表示するには**  
次の `list-instance-profile-tags` コマンドは、指定されたインスタンスプロファイルに関連付けられているタグのリストを取得します。  

```
aws iam list-instance-profile-tags \
    --instance-profile-name deployment-role
```
出力:  

```
{
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInstanceProfileTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-instance-profile-tags.html)」を参照してください。

### `list-instance-profiles-for-role`
<a name="iam_ListInstanceProfilesForRole_cli_2_topic"></a>

次のコード例は、`list-instance-profiles-for-role` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールのインスタンスプロファイルを一覧表示するには**  
次の `list-instance-profiles-for-role` コマンドは、ロール `Test-Role` に関連付けられているインスタンスプロファイルを一覧表示します。  

```
aws iam list-instance-profiles-for-role \
    --role-name Test-Role
```
出力:  

```
{
    "InstanceProfiles": [
        {
            "InstanceProfileId": "AIDGPMS9RO4H3FEXAMPLE",
            "Roles": [
                {
                    "AssumeRolePolicyDocument": "<URL-encoded-JSON>",
                    "RoleId": "AIDACKCEVSQ6C2EXAMPLE",
                    "CreateDate": "2013-06-07T20:42:15Z",
                    "RoleName": "Test-Role",
                    "Path": "/",
                    "Arn": "arn:aws:iam::123456789012:role/Test-Role"
                }
            ],
            "CreateDate": "2013-06-07T21:05:24Z",
            "InstanceProfileName": "ExampleInstanceProfile",
            "Path": "/",
            "Arn": "arn:aws:iam::123456789012:instance-profile/ExampleInstanceProfile"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[インスタンスプロファイルの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInstanceProfilesForRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-instance-profiles-for-role.html)」を参照してください。

### `list-instance-profiles`
<a name="iam_ListInstanceProfiles_cli_2_topic"></a>

次のコード例は、`list-instance-profiles` を使用する方法を示しています。

**AWS CLI**  
**アカウントのインスタンスプロファイルを一覧表示するには**  
次の `list-instance-profiles` コマンドは、現在のアカウントに関連付けられているインスタンスプロファイルを一覧表示します。  

```
aws iam list-instance-profiles
```
出力:  

```
{
    "InstanceProfiles": [
        {
            "Path": "/",
            "InstanceProfileName": "example-dev-role",
            "InstanceProfileId": "AIPAIXEU4NUHUPEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:instance-profile/example-dev-role",
            "CreateDate": "2023-09-21T18:17:41+00:00",
            "Roles": [
                {
                    "Path": "/",
                    "RoleName": "example-dev-role",
                    "RoleId": "AROAJ52OTH4H7LEXAMPLE",
                    "Arn": "arn:aws:iam::123456789012:role/example-dev-role",
                    "CreateDate": "2023-09-21T18:17:40+00:00",
                    "AssumeRolePolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": "ec2.amazonaws.com"
                                },
                                "Action": "sts:AssumeRole"
                            }
                        ]
                    }
                }
            ]
        },
        {
            "Path": "/",
            "InstanceProfileName": "example-s3-role",
            "InstanceProfileId": "AIPAJVJVNRIQFREXAMPLE",
            "Arn": "arn:aws:iam::123456789012:instance-profile/example-s3-role",
            "CreateDate": "2023-09-21T18:18:50+00:00",
            "Roles": [
                {
                    "Path": "/",
                    "RoleName": "example-s3-role",
                    "RoleId": "AROAINUBC5O7XLEXAMPLE",
                    "Arn": "arn:aws:iam::123456789012:role/example-s3-role",
                    "CreateDate": "2023-09-21T18:18:49+00:00",
                    "AssumeRolePolicyDocument": {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {
                                    "Service": "ec2.amazonaws.com"
                                },
                                "Action": "sts:AssumeRole"
                            }
                        ]
                    }
                }
            ]
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[インスタンスプロファイルの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInstanceProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-instance-profiles.html)」を参照してください。

### `list-mfa-device-tags`
<a name="iam_ListMfaDeviceTags_cli_2_topic"></a>

次のコード例は、`list-mfa-device-tags` を使用する方法を示しています。

**AWS CLI**  
**MFA デバイスにアタッチされたタグを一覧表示するには**  
次の `list-mfa-device-tags` コマンドは、指定された MFA デバイスに関連付けられているタグのリストを取得します。  

```
aws iam list-mfa-device-tags \
    --serial-number arn:aws:iam::123456789012:mfa/alice
```
出力:  

```
{
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMfaDeviceTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-mfa-device-tags.html)」を参照してください。

### `list-mfa-devices`
<a name="iam_ListMfaDevices_cli_2_topic"></a>

次のコード例は、`list-mfa-devices` を使用する方法を示しています。

**AWS CLI**  
**指定したユーザーのすべての MFA デバイスを一覧表示するには**  
この例では、IAM ユーザー `Bob` に割り当てられた MFA デバイスに関する詳細を返します。  

```
aws iam list-mfa-devices \
    --user-name Bob
```
出力:  

```
{
    "MFADevices": [
        {
            "UserName": "Bob",
            "SerialNumber": "arn:aws:iam::123456789012:mfa/Bob",
            "EnableDate": "2019-10-28T20:37:09+00:00"
        },
        {
            "UserName": "Bob",
            "SerialNumber": "GAKT12345678",
            "EnableDate": "2023-02-18T21:44:42+00:00"
        },
        {
            "UserName": "Bob",
            "SerialNumber": "arn:aws:iam::123456789012:u2f/user/Bob/fidosecuritykey1-7XNL7NFNLZ123456789EXAMPLE",
            "EnableDate": "2023-09-19T02:25:35+00:00"
        },
        {
            "UserName": "Bob",
            "SerialNumber": "arn:aws:iam::123456789012:u2f/user/Bob/fidosecuritykey2-VDRQTDBBN5123456789EXAMPLE",
            "EnableDate": "2023-09-19T01:49:18+00:00"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[AWSでの多要素認証 (MFA) の使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMfaDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-mfa-devices.html)」を参照してください。

### `list-open-id-connect-provider-tags`
<a name="iam_ListOpenIdConnectProviderTags_cli_2_topic"></a>

次のコード例は、`list-open-id-connect-provider-tags` を使用する方法を示しています。

**AWS CLI**  
**OpenID Connect (OIDC) 互換 ID プロバイダーにアタッチされたタグを一覧表示するには**  
次の `list-open-id-connect-provider-tags` コマンドは、指定された OIDC ID プロバイダーに関連付けられているタグのリストを取得します。  

```
aws iam list-open-id-connect-provider-tags \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/server.example.com
```
出力:  

```
{
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOpenIdConnectProviderTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-open-id-connect-provider-tags.html)」を参照してください。

### `list-open-id-connect-providers`
<a name="iam_ListOpenIdConnectProviders_cli_2_topic"></a>

次の例は、`list-open-id-connect-providers` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントの OpenID Connect プロバイダーに関する情報を一覧表示するには**  
この例では、現在の AWS アカウントで定義されているすべての OpenID Connect プロバイダーの ARNS のリストを返します。  

```
aws iam list-open-id-connect-providers
```
出力:  

```
{
    "OpenIDConnectProviderList": [
        {
            "Arn": "arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOpenIdConnectProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-open-id-connect-providers.html)」を参照してください。

### `list-organizations-features`
<a name="iam_ListOrganizationsFeatures_cli_2_topic"></a>

次のコード例は、`list-organizations-features` を使用する方法を示しています。

**AWS CLI**  
**組織で有効になっている一元化されたルートアクセス機能を一覧表示するには**  
次の `list-organizations-features` コマンドは、組織で有効になっている一元化されたルートアクセス機能を一覧表示します。  

```
aws iam list-organizations-features
```
出力:  

```
{
    "EnabledFeatures": [
        "RootCredentialsManagement",
        "RootSessions"
    ]
    "OrganizationId": "o-aa111bb222"
}
```
詳細については、*AWS IAM ユーザーガイド*の「[メンバーアカウントのルートアクセスを一元管理する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#id_root-user-access-management)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListOrganizationsFeatures](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-organizations-features.html)」を参照してください。

### `list-policies-granting-service-access`
<a name="iam_ListPoliciesGrantingServiceAccess_cli_2_topic"></a>

次のコード例は、`list-policies-granting-service-access` を使用する方法を示しています。

**AWS CLI**  
**指定されたサービスへのプリンシパルアクセスを許可するポリシーを一覧表示するには**  
次の の`list-policies-granting-service-access`例では、IAM ユーザーに AWS CodeCommit サービス`sofia`へのアクセスを許可するポリシーのリストを取得します。  

```
aws iam list-policies-granting-service-access \
    --arn arn:aws:iam::123456789012:user/sofia \
    --service-namespaces codecommit
```
出力:  

```
{
    "PoliciesGrantingServiceAccess": [
        {
            "ServiceNamespace": "codecommit",
            "Policies": [
                {
                    "PolicyName": "Grant-Sofia-Access-To-CodeCommit",
                    "PolicyType": "INLINE",
                    "EntityType": "USER",
                    "EntityName": "sofia"
                }
            ]
        }
    ],
    "IsTruncated": false
}
```
詳細については、IAM *AWS ユーザーガイド*の[CodeCommit での IAM の使用: Git 認証情報、SSH キー、 AWS アクセスキー](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPoliciesGrantingServiceAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-policies-granting-service-access.html)」を参照してください。

### `list-policies`
<a name="iam_ListPolicies_cli_2_topic"></a>

次の例は、`list-policies` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントで利用可能な管理ポリシーを一覧表示するには**  
この例では、現在の AWS アカウントで利用可能な最初の 2 つの管理ポリシーのコレクションを返します。  

```
aws iam list-policies \
    --max-items 3
```
出力:  

```
{
    "Policies": [
        {
            "PolicyName": "AWSCloudTrailAccessPolicy",
            "PolicyId": "ANPAXQE2B5PJ7YEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:policy/AWSCloudTrailAccessPolicy",
            "Path": "/",
            "DefaultVersionId": "v1",
            "AttachmentCount": 0,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2019-09-04T17:43:42+00:00",
            "UpdateDate": "2019-09-04T17:43:42+00:00"
        },
        {
            "PolicyName": "AdministratorAccess",
            "PolicyId": "ANPAIWMBCKSKIEE64ZLYK",
            "Arn": "arn:aws:iam::aws:policy/AdministratorAccess",
            "Path": "/",
            "DefaultVersionId": "v1",
            "AttachmentCount": 6,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2015-02-06T18:39:46+00:00",
            "UpdateDate": "2015-02-06T18:39:46+00:00"
        },
        {
            "PolicyName": "PowerUserAccess",
            "PolicyId": "ANPAJYRXTHIB4FOVS3ZXS",
            "Arn": "arn:aws:iam::aws:policy/PowerUserAccess",
            "Path": "/",
            "DefaultVersionId": "v5",
            "AttachmentCount": 1,
            "PermissionsBoundaryUsageCount": 0,
            "IsAttachable": true,
            "CreateDate": "2015-02-06T18:39:47+00:00",
            "UpdateDate": "2023-07-06T22:04:00+00:00"
        }
    ],
    "NextToken": "EXAMPLErZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiA4fQ=="
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-policies.html)」を参照してください。

### `list-policy-tags`
<a name="iam_ListPolicyTags_cli_2_topic"></a>

次のコード例は、`list-policy-tags` を使用する方法を示しています。

**AWS CLI**  
**マネージドポリシーにアタッチされたタグを一覧表示するには**  
次の `list-policy-tags` コマンドは、指定されたマネージドポリシーに関連付けられているタグのリストを取得します。  

```
aws iam list-policy-tags \
    --policy-arn arn:aws:iam::123456789012:policy/billing-access
```
出力:  

```
{
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPolicyTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-policy-tags.html)」を参照してください。

### `list-policy-versions`
<a name="iam_ListPolicyVersions_cli_2_topic"></a>

次のコード例は、`list-policy-versions` を使用する方法を示しています。

**AWS CLI**  
**指定された管理ポリシーのバージョンに関する情報を一覧表示するには**  
この例では、ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーの使用可能なバージョンのリストを返します。  

```
aws iam list-policy-versions \
    --policy-arn arn:aws:iam::123456789012:policy/MySamplePolicy
```
出力:  

```
{
    "IsTruncated": false,
    "Versions": [
        {
        "VersionId": "v2",
        "IsDefaultVersion": true,
        "CreateDate": "2015-06-02T23:19:44Z"
        },
        {
        "VersionId": "v1",
        "IsDefaultVersion": false,
        "CreateDate": "2015-06-02T22:30:47Z"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPolicyVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-policy-versions.html)」を参照してください。

### `list-role-policies`
<a name="iam_ListRolePolicies_cli_2_topic"></a>

次のコード例は、`list-role-policies` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールにアタッチされているポリシーを一覧表示するには**  
次の `list-role-policies` コマンドは、指定された IAM ロールのアクセス許可ポリシーの名前を一覧表示します。  

```
aws iam list-role-policies \
    --role-name Test-Role
```
出力:  

```
{
    "PolicyNames": [
        "ExamplePolicy"
    ]
}
```
ロールにアタッチされている信頼ポリシーを表示するには、`get-role` コマンドを使用します。アクセス許可ポリシーの詳細を表示するには、`get-role-policy` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ロールの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRolePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-role-policies.html)」を参照してください。

### `list-role-tags`
<a name="iam_ListRoleTags_cli_2_topic"></a>

次のコード例は、`list-role-tags` を使用する方法を示しています。

**AWS CLI**  
**ロールにアタッチされたタグを一覧表示するには**  
次の `list-role-tags` コマンドは、指定されたロールに関連付けられているタグのリストを取得します。  

```
aws iam list-role-tags \
    --role-name production-role
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Department",
            "Value": "Accounting"
        },
        {
            "Key": "DeptID",
            "Value": "12345"
        }
    ],
    "IsTruncated": false
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoleTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-role-tags.html)」を参照してください。

### `list-roles`
<a name="iam_ListRoles_cli_2_topic"></a>

次のコード例は、`list-roles` を使用する方法を示しています。

**AWS CLI**  
**現在のアカウントの IAM ロールを一覧表示するには**  
次の `list-roles` コマンドは、現在のアカウントの IAM ロールを一覧表示します。  

```
aws iam list-roles
```
出力:  

```
{
    "Roles": [
        {
            "Path": "/",
            "RoleName": "ExampleRole",
            "RoleId": "AROAJ52OTH4H7LEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:role/ExampleRole",
            "CreateDate": "2017-09-12T19:23:36+00:00",
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "MaxSessionDuration": 3600
        },
        {
            "Path": "/example_path/",
            "RoleName": "ExampleRoleWithPath",
            "RoleId": "AROAI4QRP7UFT7EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:role/example_path/ExampleRoleWithPath",
            "CreateDate": "2023-09-21T20:29:38+00:00",
            "AssumeRolePolicyDocument": {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "ec2.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            },
            "MaxSessionDuration": 3600
        }
    ]
}
```
詳細については、「AWS IAM ユーザーガイド」の「[IAM ロールの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-roles.html)」を参照してください。

### `list-saml-provider-tags`
<a name="iam_ListSamlProviderTags_cli_2_topic"></a>

次のコード例は、`list-saml-provider-tags` を使用する方法を示しています。

**AWS CLI**  
**SAML プロバイダーにアタッチされたタグを一覧表示するには**  
次の `list-saml-provider-tags` コマンドは、指定された SAML プロバイダーに関連付けられているタグのリストを取得します。  

```
aws iam list-saml-provider-tags \
    --saml-provider-arn arn:aws:iam::123456789012:saml-provider/ADFS
```
出力:  

```
{
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSamlProviderTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-saml-provider-tags.html)」を参照してください。

### `list-saml-providers`
<a name="iam_ListSAMLProviders_cli_2_topic"></a>

次の例は、`list-saml-providers` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントの SAML プロバイダーを一覧表示するには**  
この例では、現在の AWS アカウントで作成された SAML 2.0 プロバイダーのリストを取得します。  

```
aws iam list-saml-providers
```
出力:  

```
{
    "SAMLProviderList": [
        {
            "Arn": "arn:aws:iam::123456789012:saml-provider/SAML-ADFS",
            "ValidUntil": "2015-06-05T22:45:14Z",
            "CreateDate": "2015-06-05T22:45:14Z"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM SAML ID プロバイダーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSAMLProviders](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-saml-providers.html)」を参照してください。

### `list-server-certificate-tags`
<a name="iam_ListServerCertificateTags_cli_2_topic"></a>

次のコード例は、`list-server-certificate-tags` を使用する方法を示しています。

**AWS CLI**  
**サーバー証明書にアタッチされているタグを一覧表示するには**  
次の `list-server-certificate-tags` コマンドは、指定されたサーバー証明書に関連付けられているタグを取得します。  

```
aws iam list-server-certificate-tags \
    --server-certificate-name ExampleCertificate
```
出力:  

```
{
    "Tags": [
        {
            "Key": "DeptID",
            "Value": "123456"
        },
        {
            "Key": "Department",
            "Value": "Accounting"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServerCertificateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-server-certificate-tags.html)」を参照してください。

### `list-server-certificates`
<a name="iam_ListServerCertificates_cli_2_topic"></a>

次の例は、`list-server-certificates` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのサーバー証明書を一覧表示するには**  
次の`list-server-certificates`コマンドは、 AWS アカウントに保存され、使用可能なすべてのサーバー証明書を一覧表示します。  

```
aws iam list-server-certificates
```
出力:  

```
{
    "ServerCertificateMetadataList": [
        {
            "Path": "/",
            "ServerCertificateName": "myUpdatedServerCertificate",
            "ServerCertificateId": "ASCAEXAMPLE123EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:server-certificate/myUpdatedServerCertificate",
            "UploadDate": "2019-04-22T21:13:44+00:00",
            "Expiration": "2019-10-15T22:23:16+00:00"
        },
        {
            "Path": "/cloudfront/",
            "ServerCertificateName": "MyTestCert",
            "ServerCertificateId": "ASCAEXAMPLE456EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyTestCert",
            "UploadDate": "2015-04-21T18:14:16+00:00",
            "Expiration": "2018-01-14T17:52:36+00:00"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM でのサーバー証明書の管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListServerCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-server-certificates.html)」を参照してください。

### `list-service-specific-credential`
<a name="iam_ListServiceSpecificCredential_cli_2_topic"></a>

次のコード例は、`list-service-specific-credential` を使用する方法を示しています。

**AWS CLI**  
**例 1: ユーザーのサービス固有の認証情報を一覧表示する**  
次の `list-service-specific-credentials` の例では、指定されたユーザーに割り当てられたすべてのサービス固有の認証情報を表示します。パスワードはレスポンスに含まれません。  

```
aws iam list-service-specific-credentials \
    --user-name sofia
```
出力:  

```
{
    "ServiceSpecificCredential": {
        "CreateDate": "2019-04-18T20:45:36+00:00",
        "ServiceName": "codecommit.amazonaws.com",
        "ServiceUserName": "sofia-at-123456789012",
        "ServiceSpecificCredentialId": "ACCAEXAMPLE123EXAMPLE",
        "UserName": "sofia",
        "Status": "Active"
    }
}
```
**例 2: 指定されたサービスにフィルタリングされたユーザーのサービス固有の認証情報を一覧表示する**  
次の `list-service-specific-credentials` の例では、リクエストを行うユーザーに割り当てられたサービス固有の認証情報を表示します。リストは、指定されたサービスの認証情報のみを含むようにフィルタリングされます。パスワードはレスポンスに含まれません。  

```
aws iam list-service-specific-credentials \
    --service-name codecommit.amazonaws.com
```
出力:  

```
{
    "ServiceSpecificCredential": {
        "CreateDate": "2019-04-18T20:45:36+00:00",
        "ServiceName": "codecommit.amazonaws.com",
        "ServiceUserName": "sofia-at-123456789012",
        "ServiceSpecificCredentialId": "ACCAEXAMPLE123EXAMPLE",
        "UserName": "sofia",
        "Status": "Active"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[CodeCommit への HTTPS 接続用の Git 認証情報を作成する](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html#setting-up-gc-iam)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceSpecificCredential](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-service-specific-credential.html)」を参照してください。

### `list-service-specific-credentials`
<a name="iam_ListServiceSpecificCredentials_cli_2_topic"></a>

次のコード例は、`list-service-specific-credentials` を使用する方法を示しています。

**AWS CLI**  
**認証情報のリストを取得するには**  
次の の`list-service-specific-credentials`例では、 という名前のユーザーの AWS CodeCommit リポジトリへの HTTPS アクセス用に生成された認証情報を一覧表示します`developer`。  

```
aws iam list-service-specific-credentials \
    --user-name developer \
    --service-name codecommit.amazonaws.com
```
出力:  

```
{
    "ServiceSpecificCredentials": [
        {
            "UserName": "developer",
            "Status": "Inactive",
            "ServiceUserName": "developer-at-123456789012",
            "CreateDate": "2019-10-01T04:31:41Z",
            "ServiceSpecificCredentialId": "ACCAQFODXMPL4YFHP7DZE",
            "ServiceName": "codecommit.amazonaws.com"
        },
        {
            "UserName": "developer",
            "Status": "Active",
            "ServiceUserName": "developer+1-at-123456789012",
            "CreateDate": "2019-10-01T04:31:45Z",
            "ServiceSpecificCredentialId": "ACCAQFOXMPL6VW57M7AJP",
            "ServiceName": "codecommit.amazonaws.com"
        }
    ]
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[CodeCommit への HTTPS 接続用の Git 認証情報を作成する](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html#setting-up-gc-iam)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceSpecificCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-service-specific-credentials.html)」を参照してください。

### `list-signing-certificates`
<a name="iam_ListSigningCertificates_cli_2_topic"></a>

次のコード例は、`list-signing-certificates` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーの署名証明書を一覧表示するには**  
次の `list-signing-certificates` コマンドは、`Bob` という名前の IAM ユーザーの署名証明書を一覧表示します。  

```
aws iam list-signing-certificates \
    --user-name Bob
```
出力:  

```
{
    "Certificates": [
        {
            "UserName": "Bob",
            "Status": "Inactive",
            "CertificateBody": "-----BEGIN CERTIFICATE-----<certificate-body>-----END CERTIFICATE-----",
            "CertificateId": "TA7SMP42TDN5Z26OBPJE7EXAMPLE",
            "UploadDate": "2013-06-06T21:40:08Z"
        }
    ]
}
```
詳細については、「*Amazon EC2 ユーザーガイド*」の「[署名証明書の管理](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-up-ami-tools.html#ami-tools-managing-certs)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSigningCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-signing-certificates.html)」を参照してください。

### `list-ssh-public-keys`
<a name="iam_ListSshPublicKeys_cli_2_topic"></a>

次のコード例は、`list-ssh-public-keys` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーにアタッチされた SSH パブリックキーを一覧表示するには**  
次の `list-ssh-public-keys` の例では、IAM ユーザー `sofia` にアタッチされた SSH パブリックキーを一覧表示します。  

```
aws iam list-ssh-public-keys \
    --user-name sofia
```
出力:  

```
{
    "SSHPublicKeys": [
        {
            "UserName": "sofia",
            "SSHPublicKeyId": "APKA1234567890EXAMPLE",
            "Status": "Inactive",
            "UploadDate": "2019-04-18T17:04:49+00:00"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[CodeCommit で SSH キーと SSH を使用する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html#ssh-keys-code-commit)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSshPublicKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-ssh-public-keys.html)」を参照してください。

### `list-user-policies`
<a name="iam_ListUserPolicies_cli_2_topic"></a>

次のコード例は、`list-user-policies` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのポリシーを一覧表示するには**  
次の `list-user-policies` コマンドは、`Bob` という名前の IAM ユーザーにアタッチされているポリシーを一覧表示します。  

```
aws iam list-user-policies \
    --user-name Bob
```
出力:  

```
{
    "PolicyNames": [
        "ExamplePolicy",
        "TestPolicy"
    ]
}
```
詳細については、[「IAM ユーザーガイド」の AWS 「アカウントでの IAM ユーザーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUserPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-user-policies.html)」を参照してください。

### `list-user-tags`
<a name="iam_ListUserTags_cli_2_topic"></a>

次のコード例は、`list-user-tags` を使用する方法を示しています。

**AWS CLI**  
**ユーザーにアタッチされたタグを一覧表示するには**  
次の `list-user-tags` コマンドは、指定された IAM ユーザーに関連付けられているタグを取得します。  

```
aws iam list-user-tags \
    --user-name alice
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Department",
            "Value": "Accounting"
        },
        {
            "Key": "DeptID",
            "Value": "12345"
        }
    ],
    "IsTruncated": false
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUserTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-user-tags.html)」を参照してください。

### `list-users`
<a name="iam_ListUsers_cli_2_topic"></a>

次のコード例は、`list-users` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーを一覧表示するには**  
次の `list-users` コマンドは、現在のアカウントの IAM ユーザーを一覧表示します。  

```
aws iam list-users
```
出力:  

```
{
    "Users": [
        {
            "UserName": "Adele",
            "Path": "/",
            "CreateDate": "2013-03-07T05:14:48Z",
            "UserId": "AKIAI44QH8DHBEXAMPLE",
            "Arn": "arn:aws:iam::123456789012:user/Adele"
        },
        {
            "UserName": "Bob",
            "Path": "/",
            "CreateDate": "2012-09-21T23:03:13Z",
            "UserId": "AKIAIOSFODNN7EXAMPLE",
            "Arn": "arn:aws:iam::123456789012:user/Bob"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーの一覧表示](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_manage.html#id_users_manage_list)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-users.html)」を参照してください。

### `list-virtual-mfa-devices`
<a name="iam_ListVirtualMfaDevices_cli_2_topic"></a>

次のコード例は、`list-virtual-mfa-devices` を使用する方法を示しています。

**AWS CLI**  
**仮想 MFA デバイスを一覧表示するには**  
次の `list-virtual-mfa-devices` コマンドは、現在のアカウントに設定されている仮想 MFA デバイスを一覧表示します。  

```
aws iam list-virtual-mfa-devices
```
出力:  

```
{
    "VirtualMFADevices": [
        {
            "SerialNumber": "arn:aws:iam::123456789012:mfa/ExampleMFADevice"
        },
        {
            "SerialNumber": "arn:aws:iam::123456789012:mfa/Fred"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[仮想多要素認証 (MFA) デバイスの有効化 (コンソール)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_enable_virtual.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVirtualMfaDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/list-virtual-mfa-devices.html)」を参照してください。

### `put-group-policy`
<a name="iam_PutGroupPolicy_cli_2_topic"></a>

次のコード例は、`put-group-policy` を使用する方法を示しています。

**AWS CLI**  
**グループにポリシーを追加するには**  
次の `put-group-policy` コマンドは、`Admins` という名前の IAM グループにポリシーを追加します。  

```
aws iam put-group-policy \
    --group-name Admins \
    --policy-document file://AdminPolicy.json \
    --policy-name AdminRoot
```
このコマンドでは何も出力されません。  
ポリシーは、*AdminPolicy.json* ファイル内で JSON ドキュメントとして定義されます。(ファイル名と拡張子には意味はありません。)  
IAM ポリシーの詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ポリシーを管理する](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-group-policy.html)」を参照してください。

### `put-role-permissions-boundary`
<a name="iam_PutRolePermissionsBoundary_cli_2_topic"></a>

次のコード例は、`put-role-permissions-boundary` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムポリシーに基づくアクセス許可の境界を IAM ロールに適用するには**  
次の `put-role-permissions-boundary` の例では、指定した IAM ロールのアクセス許可の境界として、`intern-boundary` という名前のカスタムポリシーを適用します。  

```
aws iam put-role-permissions-boundary \
    --permissions-boundary arn:aws:iam::123456789012:policy/intern-boundary \
    --role-name lambda-application-role
```
このコマンドでは何も出力されません。  
**例 2: AWS 管理ポリシーに基づくアクセス許可の境界を IAM ロールに適用するには**  
次の の`put-role-permissions-boundary`例では、指定された IAM ロールのアクセス許可の境界として AWS 管理`PowerUserAccess`ポリシーを適用します。  

```
aws iam put-role-permissions-boundary \
    --permissions-boundary arn:aws:iam::aws:policy/PowerUserAccess \
    --role-name x-account-admin
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[ロールの変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRolePermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-role-permissions-boundary.html)」を参照してください。

### `put-role-policy`
<a name="iam_PutRolePolicy_cli_2_topic"></a>

次のコード例は、`put-role-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセス許可ポリシーを IAM ロールにアタッチするには**  
次の `put-role-policy` コマンドは、`Test-Role` という名前のロールにアクセス許可ポリシーを追加します。  

```
aws iam put-role-policy \
    --role-name Test-Role \
    --policy-name ExamplePolicy \
    --policy-document file://AdminPolicy.json
```
このコマンドでは何も出力されません。  
ポリシーは、*AdminPolicy.json* ファイル内で JSON ドキュメントとして定義されます。(ファイル名と拡張子には意味はありません。)  
信頼ポリシーをロールにアタッチするには、`update-assume-role-policy` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[ロールの変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-role-policy.html)」を参照してください。

### `put-user-permissions-boundary`
<a name="iam_PutUserPermissionsBoundary_cli_2_topic"></a>

次のコード例は、`put-user-permissions-boundary` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムポリシーに基づくアクセス許可の境界を IAM ユーザーに適用するには**  
次の `put-user-permissions-boundary` の例では、指定した IAM ユーザーのアクセス許可の境界として、`intern-boundary` という名前のカスタムポリシーを適用します。  

```
aws iam put-user-permissions-boundary \
    --permissions-boundary arn:aws:iam::123456789012:policy/intern-boundary \
    --user-name intern
```
このコマンドでは何も出力されません。  
**例 2: AWS 管理ポリシーに基づいてアクセス許可の境界を IAM ユーザーに適用するには**  
次の の`put-user-permissions-boundary`例では、指定された IAM ユーザーのアクセス許可の境界`PowerUserAccess`として という名前の AWS マネージドポーリーを適用します。  

```
aws iam put-user-permissions-boundary \
    --permissions-boundary arn:aws:iam::aws:policy/PowerUserAccess \
    --user-name developer
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM ユーザーガイド*の「[IAM ID アクセス許可の追加および削除](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutUserPermissionsBoundary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-user-permissions-boundary.html)」を参照してください。

### `put-user-policy`
<a name="iam_PutUserPolicy_cli_2_topic"></a>

次のコード例は、`put-user-policy` を使用する方法を示しています。

**AWS CLI**  
**ポリシーを IAM ユーザーにアタッチするには**  
次の `put-user-policy` コマンドは、`Bob` という名前の IAM ユーザーにポリシーをアタッチします。  

```
aws iam put-user-policy \
    --user-name Bob \
    --policy-name ExamplePolicy \
    --policy-document file://AdminPolicy.json
```
このコマンドでは何も出力されません。  
ポリシーは、*AdminPolicy.json* ファイル内で JSON ドキュメントとして定義されます。(ファイル名と拡張子には意味はありません。)  
詳細については、「AWS IAM ユーザーガイド」の「[IAM ID アクセス許可の追加および削除](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutUserPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/put-user-policy.html)」を参照してください。

### `remove-client-id-from-open-id-connect-provider`
<a name="iam_RemoveClientIdFromOpenIdConnectProvider_cli_2_topic"></a>

次のコード例は、`remove-client-id-from-open-id-connect-provider` を使用する方法を示しています。

**AWS CLI**  
**指定の IAM OpenID Connect プロバイダーに対して登録されているクライアント ID のリストから、指定のクライアント ID を削除するには**  
この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` である IAM OIDC プロバイダーに関連付けられているクライアント ID のリストから、クライアント ID `My-TestApp-3` を削除します。  

```
aws iam remove-client-id-from-open-id-connect-provider
    --client-id My-TestApp-3 \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveClientIdFromOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/remove-client-id-from-open-id-connect-provider.html)」を参照してください。

### `remove-role-from-instance-profile`
<a name="iam_RemoveRoleFromInstanceProfile_cli_2_topic"></a>

次のコード例は、`remove-role-from-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**ロールをインスタンスプロファイルから削除するには**  
次の `remove-role-from-instance-profile` コマンドは、`ExampleInstanceProfile` という名前のインスタンスプロファイルから `Test-Role` という名前のロールを削除します。  

```
aws iam remove-role-from-instance-profile \
    --instance-profile-name ExampleInstanceProfile \
    --role-name Test-Role
```
詳細については、「*AWS IAM ユーザーガイド*」の「[インスタンスプロファイルの使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveRoleFromInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/remove-role-from-instance-profile.html)」を参照してください。

### `remove-user-from-group`
<a name="iam_RemoveUserFromGroup_cli_2_topic"></a>

次のコード例は、`remove-user-from-group` を使用する方法を示しています。

**AWS CLI**  
**IAM グループからユーザーを削除するには**  
次の `remove-user-from-group` コマンドは、`Admins` という名前の IAM グループから `Bob` というユーザーを削除します。  

```
aws iam remove-user-from-group \
    --user-name Bob \
    --group-name Admins
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループへのユーザーの追加と削除](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_add-remove-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveUserFromGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/remove-user-from-group.html)」を参照してください。

### `reset-service-specific-credential`
<a name="iam_ResetServiceSpecificCredential_cli_2_topic"></a>

次のコード例は、`reset-service-specific-credential` を使用する方法を示しています。

**AWS CLI**  
**例 1: リクエストを行うユーザーにアタッチされたサービス固有の認証情報のパスワードをリセットする**  
次の `reset-service-specific-credential` の例では、リクエストを行うユーザーにアタッチされた、指定されたサービス固有の認証情報の新しい暗号化された強力なパスワードを生成します。  

```
aws iam reset-service-specific-credential \
    --service-specific-credential-id ACCAEXAMPLE123EXAMPLE
```
出力:  

```
{
    "ServiceSpecificCredential": {
        "CreateDate": "2019-04-18T20:45:36+00:00",
        "ServiceName": "codecommit.amazonaws.com",
        "ServiceUserName": "sofia-at-123456789012",
        "ServicePassword": "+oaFsNk7tLco+C/obP9GhhcOzGcKOayTmE3LnAmAmH4=",
        "ServiceSpecificCredentialId": "ACCAEXAMPLE123EXAMPLE",
        "UserName": "sofia",
        "Status": "Active"
    }
}
```
**例 2: 指定されたユーザーにアタッチされたサービス固有の認証情報のパスワードをリセットする**  
次の `reset-service-specific-credential` の例では、指定されたユーザーにアタッチされたサービス固有の認証情報の新しい暗号化された強力なパスワードを生成します。  

```
aws iam reset-service-specific-credential \
    --user-name sofia \
    --service-specific-credential-id ACCAEXAMPLE123EXAMPLE
```
出力:  

```
{
    "ServiceSpecificCredential": {
        "CreateDate": "2019-04-18T20:45:36+00:00",
        "ServiceName": "codecommit.amazonaws.com",
        "ServiceUserName": "sofia-at-123456789012",
        "ServicePassword": "+oaFsNk7tLco+C/obP9GhhcOzGcKOayTmE3LnAmAmH4=",
        "ServiceSpecificCredentialId": "ACCAEXAMPLE123EXAMPLE",
        "UserName": "sofia",
        "Status": "Active"
    }
}
```
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[CodeCommit への HTTPS 接続用の Git 認証情報を作成する](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html#setting-up-gc-iam)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetServiceSpecificCredential](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/reset-service-specific-credential.html)」を参照してください。

### `resync-mfa-device`
<a name="iam_ResyncMfaDevice_cli_2_topic"></a>

次のコード例は、`resync-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**MFA デバイスを同期するには**  
次の `resync-mfa-device` の例では、IAM ユーザー `Bob` に関連付けられていて、ARN が `arn:aws:iam::123456789012:mfa/BobsMFADevice` である MFA デバイスを、2 つの認証コードを提供した認証プログラムと同期します。  

```
aws iam resync-mfa-device \
    --user-name Bob \
    --serial-number arn:aws:iam::210987654321:mfa/BobsMFADevice \
    --authentication-code1 123456 \
    --authentication-code2 987654
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[AWSでの多要素認証 (MFA) の使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResyncMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/resync-mfa-device.html)」を参照してください。

### `set-default-policy-version`
<a name="iam_SetDefaultPolicyVersion_cli_2_topic"></a>

次のコード例は、`set-default-policy-version` を使用する方法を示しています。

**AWS CLI**  
**指定されたポリシーの指定されたバージョンを、ポリシーのデフォルトバージョンとして設定するには**  
この例では、ARN が `arn:aws:iam::123456789012:policy/MyPolicy` であるポリシーの `v2` バージョンをデフォルトのアクティブなバージョンとして設定します。  

```
aws iam set-default-policy-version \
    --policy-arn arn:aws:iam::123456789012:policy/MyPolicy \
    --version-id v2
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM のポリシーとアクセス許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetDefaultPolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/set-default-policy-version.html)」を参照してください。

### `set-security-token-service-preferences`
<a name="iam_SetSecurityTokenServicePreferences_cli_2_topic"></a>

次のコード例は、`set-security-token-service-preferences` を使用する方法を示しています。

**AWS CLI**  
**グローバルエンドポイントトークンバージョンを設定するには**  
次の `set-security-token-service-preferences` の例では、グローバルエンドポイントに対して認証するときにバージョン 2 トークンを使用するように Amazon STS を設定します。  

```
aws iam set-security-token-service-preferences \
    --global-endpoint-token-version v2Token
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM ユーザーガイド*[の「 AWS リージョンでの AWS STS の管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetSecurityTokenServicePreferences](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/set-security-token-service-preferences.html)」を参照してください。

### `simulate-custom-policy`
<a name="iam_SimulateCustomPolicy_cli_2_topic"></a>

次のコード例は、`simulate-custom-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: IAM ユーザーまたはロールに関連付けられているすべての IAM ポリシーの効果をシミュレートするには**  
次の `simulate-custom-policy` は、ポリシーと変数値の両方を指定し、API コールをシミュレートして、許可または拒否されているかどうかを確認する方法を示しています。次の例は、指定された日付と時刻の後にのみデータベースアクセスを有効にするポリシーを示しています。シミュレーションは成功します。シミュレーションされたアクションと指定された `aws:CurrentTime` 変数がすべてポリシーの要件と一致するためです。  

```
aws iam simulate-custom-policy \
    --policy-input-list '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"*","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2018-08-16T12:00:00Z"}}}}' \
    --action-names dynamodb:CreateBackup \
    --context-entries "ContextKeyName='aws:CurrentTime',ContextKeyValues='2019-04-25T11:00:00Z',ContextKeyType=date"
```
出力:  

```
{
    "EvaluationResults": [
        {
            "EvalActionName": "dynamodb:CreateBackup",
            "EvalResourceName": "*",
            "EvalDecision": "allowed",
            "MatchedStatements": [
                {
                    "SourcePolicyId": "PolicyInputList.1",
                    "StartPosition": {
                        "Line": 1,
                        "Column": 38
                    },
                    "EndPosition": {
                        "Line": 1,
                        "Column": 167
                    }
                }
            ],
            "MissingContextValues": []
        }
    ]
}
```
**例 2: ポリシーで禁止されているコマンドをシミュレートするには**  
次の `simulate-custom-policy` の例は、ポリシーで禁止されているコマンドをシミュレートした結果を示しています。この例での指定された日付は、ポリシーの条件で必要とされる日付より前です。  

```
aws iam simulate-custom-policy \
    --policy-input-list '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"*","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2018-08-16T12:00:00Z"}}}}' \
    --action-names dynamodb:CreateBackup \
    --context-entries "ContextKeyName='aws:CurrentTime',ContextKeyValues='2014-04-25T11:00:00Z',ContextKeyType=date"
```
出力:  

```
{
    "EvaluationResults": [
        {
            "EvalActionName": "dynamodb:CreateBackup",
            "EvalResourceName": "*",
            "EvalDecision": "implicitDeny",
            "MatchedStatements": [],
            "MissingContextValues": []
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ポリシーシミュレーターを使用した IAM ポリシーのテスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SimulateCustomPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/simulate-custom-policy.html)」を参照してください。

### `simulate-principal-policy`
<a name="iam_SimulatePrincipalPolicy_cli_2_topic"></a>

次のコード例は、`simulate-principal-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: 任意の IAM ポリシーの効果をシミュレートするには**  
次の `simulate-principal-policy` は、API アクションを呼び出すユーザーをシミュレートし、そのユーザーに関連付けられたポリシーがアクションを許可または拒否するかどうかを決定する方法を示します。次の例では、ユーザーに `codecommit:ListRepositories` アクションのみを許可するポリシーがあります。  

```
aws iam simulate-principal-policy \
    --policy-source-arn arn:aws:iam::123456789012:user/alejandro \
    --action-names codecommit:ListRepositories
```
出力:  

```
{
    "EvaluationResults": [
        {
            "EvalActionName": "codecommit:ListRepositories",
            "EvalResourceName": "*",
            "EvalDecision": "allowed",
            "MatchedStatements": [
                {
                    "SourcePolicyId": "Grant-Access-To-CodeCommit-ListRepo",
                    "StartPosition": {
                        "Line": 3,
                        "Column": 19
                    },
                    "EndPosition": {
                        "Line": 9,
                        "Column": 10
                    }
                }
            ],
            "MissingContextValues": []
        }
    ]
}
```
**例 2: 禁止されているコマンドの影響をシミュレートするには**  
次の `simulate-custom-policy` の例は、ユーザーのポリシーのいずれかで禁止されているコマンドをシミュレートした結果を示しています。次の例では、ユーザーに特定の日付と時刻の後にのみ DynamoDB データベースへのアクセスを許可するポリシーがあります。このシミュレーションでは、ポリシーの条件が許可する値よりも前の `aws:CurrentTime` 値でデータベースにアクセスしようとします。  

```
aws iam simulate-principal-policy \
    --policy-source-arn arn:aws:iam::123456789012:user/alejandro \
    --action-names dynamodb:CreateBackup \
    --context-entries "ContextKeyName='aws:CurrentTime',ContextKeyValues='2018-04-25T11:00:00Z',ContextKeyType=date"
```
出力:  

```
{
    "EvaluationResults": [
        {
            "EvalActionName": "dynamodb:CreateBackup",
            "EvalResourceName": "*",
            "EvalDecision": "implicitDeny",
            "MatchedStatements": [],
            "MissingContextValues": []
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ポリシーシミュレーターを使用した IAM ポリシーのテスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_testing-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SimulatePrincipalPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/simulate-principal-policy.html)」を参照してください。

### `tag-instance-profile`
<a name="iam_TagInstanceProfile_cli_2_topic"></a>

次のコード例は、`tag-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**タグをインスタンスプロファイルに追加するには**  
次の `tag-instance-profile` コマンドは、部門名を持つタグを指定したインスタンスプロファイルに追加します。  

```
aws iam tag-instance-profile \
    --instance-profile-name deployment-role \
    --tags '[{"Key": "Department", "Value": "Accounting"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-instance-profile.html)」を参照してください。

### `tag-mfa-device`
<a name="iam_TagMfaDevice_cli_2_topic"></a>

次のコード例は、`tag-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**MFA デバイスにタグを追加するには**  
次の `tag-mfa-device` コマンドは、部門名を持つタグを指定した MFA デバイスに追加します。  

```
aws iam tag-mfa-device \
    --serial-number arn:aws:iam::123456789012:mfa/alice \
    --tags '[{"Key": "Department", "Value": "Accounting"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-mfa-device.html)」を参照してください。

### `tag-open-id-connect-provider`
<a name="iam_TagOpenIdConnectProvider_cli_2_topic"></a>

次のコード例は、`tag-open-id-connect-provider` を使用する方法を示しています。

**AWS CLI**  
**OpenID Connect (OIDC) 互換 ID プロバイダーにタグを追加するには**  
次の `tag-open-id-connect-provider` コマンドは、部門名を持つタグを指定した OIDC ID プロバイダーに追加します。  

```
aws iam tag-open-id-connect-provider \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/server.example.com \
    --tags '[{"Key": "Department", "Value": "Accounting"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-open-id-connect-provider.html)」を参照してください。

### `tag-policy`
<a name="iam_TagPolicy_cli_2_topic"></a>

次のコード例は、`tag-policy` を使用する方法を示しています。

**AWS CLI**  
**カスタマー管理ポリシーにタグを追加するには**  
次の `tag-policy` コマンドは、部門名を持つタグを指定したカスタマー管理ポリシーに追加します。  

```
aws iam tag-policy \
    --policy-arn arn:aws:iam::123456789012:policy/billing-access \
    --tags '[{"Key": "Department", "Value": "Accounting"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-policy.html)」を参照してください。

### `tag-role`
<a name="iam_TagRole_cli_2_topic"></a>

次のコード例は、`tag-role` を使用する方法を示しています。

**AWS CLI**  
**ロールにタグを追加するには**  
次の `tag-role` コマンドは、部門名を持つタグを指定したロールに追加します。  

```
aws iam tag-role --role-name my-role \
    --tags '{"Key": "Department", "Value": "Accounting"}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-role.html)」を参照してください。

### `tag-saml-provider`
<a name="iam_TagSamlProvider_cli_2_topic"></a>

次のコード例は、`tag-saml-provider` を使用する方法を示しています。

**AWS CLI**  
**SAML プロバイダーにタグを追加するには**  
次の `tag-saml-provider` コマンドは、部門名を持つタグを指定した SAML プロバイダーに追加します。  

```
aws iam tag-saml-provider \
    --saml-provider-arn arn:aws:iam::123456789012:saml-provider/ADFS \
    --tags '[{"Key": "Department", "Value": "Accounting"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagSamlProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-saml-provider.html)」を参照してください。

### `tag-server-certificate`
<a name="iam_TagServerCertificate_cli_2_topic"></a>

次のコード例は、`tag-server-certificate` を使用する方法を示しています。

**AWS CLI**  
**サーバー証明書にタグを追加するには**  
次の `tag-saml-provider` コマンドは、部門名を持つタグを指定したサーバー証明書に追加します。  

```
aws iam tag-server-certificate \
    --server-certificate-name ExampleCertificate \
    --tags '[{"Key": "Department", "Value": "Accounting"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-server-certificate.html)」を参照してください。

### `tag-user`
<a name="iam_TagUser_cli_2_topic"></a>

次のコード例は、`tag-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーにタグを追加するには**  
次の `tag-user` コマンドは、関連付けらた部門を持つタグを指定したユーザーに追加します。  

```
aws iam tag-user \
    --user-name alice \
    --tags '{"Key": "Department", "Value": "Accounting"}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/tag-user.html)」を参照してください。

### `untag-instance-profile`
<a name="iam_UntagInstanceProfile_cli_2_topic"></a>

次のコード例は、`untag-instance-profile` を使用する方法を示しています。

**AWS CLI**  
**タグをインスタンスプロファイルから削除するには**  
次の `untag-instance-profile` コマンドは、キー名が「Department」のタグを指定されたインスタンスプロファイルから削除します。  

```
aws iam untag-instance-profile \
    --instance-profile-name deployment-role \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagInstanceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-instance-profile.html)」を参照してください。

### `untag-mfa-device`
<a name="iam_UntagMfaDevice_cli_2_topic"></a>

次のコード例は、`untag-mfa-device` を使用する方法を示しています。

**AWS CLI**  
**MFA デバイスからタグを削除するには**  
次の `untag-mfa-device` コマンドは、キー名が「Department」のタグを指定された MFA デバイスから削除します。  

```
aws iam untag-mfa-device \
    --serial-number arn:aws:iam::123456789012:mfa/alice \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagMfaDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-mfa-device.html)」を参照してください。

### `untag-open-id-connect-provider`
<a name="iam_UntagOpenIdConnectProvider_cli_2_topic"></a>

次のコード例は、`untag-open-id-connect-provider` を使用する方法を示しています。

**AWS CLI**  
**OIDC ID プロバイダーからタグを削除するには**  
次の `untag-open-id-connect-provider` コマンドは、キー名が「Department」のタグを指定された OIDC ID プロバイダーから削除します。  

```
aws iam untag-open-id-connect-provider \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/server.example.com \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagOpenIdConnectProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-open-id-connect-provider.html)」を参照してください。

### `untag-policy`
<a name="iam_UntagPolicy_cli_2_topic"></a>

次のコード例は、`untag-policy` を使用する方法を示しています。

**AWS CLI**  
**カスタマー管理ポリシーからタグを削除するには**  
次の `untag-policy` コマンドは、キー名が「Department」のタグを指定されたカスタマー管理ポリシーから削除します。  

```
aws iam untag-policy \
    --policy-arn arn:aws:iam::452925170507:policy/billing-access \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-policy.html)」を参照してください。

### `untag-role`
<a name="iam_UntagRole_cli_2_topic"></a>

次のコード例は、`untag-role` を使用する方法を示しています。

**AWS CLI**  
**ロールからタグを削除するには**  
次の `untag-role` コマンドは、キー名「Department」のタグを指定されたロールから削除します。  

```
aws iam untag-role \
    --role-name my-role \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-role.html)」を参照してください。

### `untag-saml-provider`
<a name="iam_UntagSamlProvider_cli_2_topic"></a>

次のコード例は、`untag-saml-provider` を使用する方法を示しています。

**AWS CLI**  
**SAML プロバイダーからタグを削除するには**  
次の `untag-saml-provider` コマンドは、キー名が「Department」のタグを指定されたインスタンスプロファイルから削除します。  

```
aws iam untag-saml-provider \
    --saml-provider-arn arn:aws:iam::123456789012:saml-provider/ADFS \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagSamlProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-saml-provider.html)」を参照してください。

### `untag-server-certificate`
<a name="iam_UntagServerCertificate_cli_2_topic"></a>

次のコード例は、`untag-server-certificate` を使用する方法を示しています。

**AWS CLI**  
**サーバー証明書からタグを削除するには**  
次の `untag-server-certificate` コマンドは、キー名が「Department」のタグを指定されたサーバー証明書から削除します。  

```
aws iam untag-server-certificate \
    --server-certificate-name ExampleCertificate \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-server-certificate.html)」を参照してください。

### `untag-user`
<a name="iam_UntagUser_cli_2_topic"></a>

次のコード例は、`untag-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーからタグを削除するには**  
次の `untag-user` コマンドは、キー名が「Department」のタグを指定されたユーザーから削除します。  

```
aws iam untag-user \
    --user-name alice \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「AWS IAM ユーザーガイド」の「[IAM リソースのタグ付け](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/untag-user.html)」を参照してください。

### `update-access-key`
<a name="iam_UpdateAccessKey_cli_2_topic"></a>

次のコード例は、`update-access-key` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのためにアクセスキーをアクティブ化または非アクティブ化するには**  
次の `update-access-key` コマンドは、`Bob` という名前の IAM ユーザーのために指定されたアクセスキー (アクセスキー ID とシークレットアクセスキー) を非アクティブ化します。  

```
aws iam update-access-key \
    --access-key-id AKIAIOSFODNN7EXAMPLE \
    --status Inactive \
    --user-name Bob
```
このコマンドでは何も出力されません。  
キーを非アクティブ化すると、プログラムによるアクセスには使用できません AWS。ただし、キーは引き続き使用可能であり、再アクティブ化することができます。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアクセスキーの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[UpdateAccessKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-access-key.html)」を参照してください。

### `update-account-password-policy`
<a name="iam_UpdateAccountPasswordPolicy_cli_2_topic"></a>

次のコード例は、`update-account-password-policy` を使用する方法を示しています。

**AWS CLI**  
**現在のアカウントのパスワードポリシーを設定または変更するには**  
次の `update-account-password-policy` コマンドは、8 文字以上の長さを要求し、パスワードに 1 つ以上の数字を要求するようにパスワードポリシーを設定します。  

```
aws iam update-account-password-policy \
    --minimum-password-length 8 \
    --require-numbers
```
このコマンドでは何も出力されません。  
アカウントのパスワードポリシーを変更すると、そのアカウントの IAM ユーザー用に作成された新しいパスワードに影響します。パスワードポリシーを変更しても、既存のパスワードには影響しません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのアカウントパスワードポリシーの設定](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_account-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccountPasswordPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-account-password-policy.html)」を参照してください。

### `update-assume-role-policy`
<a name="iam_UpdateAssumeRolePolicy_cli_2_topic"></a>

次のコード例は、`update-assume-role-policy` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールの信頼ポリシーを更新するには**  
次の `update-assume-role-policy` コマンドは、`Test-Role` という名前のロールの信頼ポリシーを更新します。  

```
aws iam update-assume-role-policy \
    --role-name Test-Role \
    --policy-document file://Test-Role-Trust-Policy.json
```
このコマンドでは何も出力されません。  
信頼ポリシーは、*Test-Role-Trust-Policy.json *ファイル内で JSON ドキュメントとして定義されます。(ファイル名と拡張子には意味はありません。) 信頼ポリシーはプリンシパルを指定する必要があります。  
ロールのアクセス許可ポリシーを更新するには、`put-role-policy` コマンドを使用します。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ロールの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAssumeRolePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-assume-role-policy.html)」を参照してください。

### `update-group`
<a name="iam_UpdateGroup_cli_2_topic"></a>

次のコード例は、`update-group` を使用する方法を示しています。

**AWS CLI**  
**IAM グループの名前を変更するには**  
次の `update-group` コマンドは、IAM グループ `Test` の名前を `Test-1` に変更します。  

```
aws iam update-group \
    --group-name Test \
    --new-group-name Test-1
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループの名前の変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_rename.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-group.html)」を参照してください。

### `update-login-profile`
<a name="iam_UpdateLoginProfile_cli_2_topic"></a>

次のコード例は、`update-login-profile` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーのパスワードを更新するには**  
次の `update-login-profile` コマンドは、`Bob` という名前の IAM ユーザーの新しいパスワードを作成します。  

```
aws iam update-login-profile \
    --user-name Bob \
    --password <password>
```
このコマンドでは何も出力されません。  
アカウントのパスワードポリシーを設定するには、`update-account-password-policy` コマンドを使用します。新しいパスワードがアカウントのパスワードポリシーに違反している場合、コマンドは `PasswordPolicyViolation` エラーを返します。  
アカウントのパスワードポリシーで許可されている場合、IAM ユーザーは `change-password` コマンドを使用して自分のパスワードを変更できます。  
パスワードを安全な場所に保存します。パスワードを紛失した場合は回復できないため、`create-login-profile` コマンドを使用して新しいパスワードを作成する必要があります。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーのパスワードの管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_passwords_admin-change-user.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLoginProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-login-profile.html)」を参照してください。

### `update-open-id-connect-provider-thumbprint`
<a name="iam_UpdateOpenIdConnectProviderThumbprint_cli_2_topic"></a>

次のコード例は、`update-open-id-connect-provider-thumbprint` を使用する方法を示しています。

**AWS CLI**  
**サーバー証明書のサムプリントの既存のリストを新しいリストに置き換えるには**  
この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` である OIDC プロバイダーの証明書サムプリントリストを更新して、新しいサムプリントを使用します。  

```
aws iam update-open-id-connect-provider-thumbprint \
    --open-id-connect-provider-arn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com \
    --thumbprint-list 7359755EXAMPLEabc3060bce3EXAMPLEec4542a3
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM で OpenID Connect (OIDC) ID プロバイダーを作成する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateOpenIdConnectProviderThumbprint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-open-id-connect-provider-thumbprint.html)」を参照してください。

### `update-role-description`
<a name="iam_UpdateRoleDescription_cli_2_topic"></a>

次のコード例は、`update-role-description` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールの説明を変更するには**  
次の `update-role` コマンドは、IAM ロール `production-role` の説明を `Main production role` に変更します。  

```
aws iam update-role-description \
    --role-name production-role \
    --description 'Main production role'
```
出力:  

```
{
    "Role": {
        "Path": "/",
        "RoleName": "production-role",
        "RoleId": "AROA1234567890EXAMPLE",
        "Arn": "arn:aws:iam::123456789012:role/production-role",
        "CreateDate": "2017-12-06T17:16:37+00:00",
        "AssumeRolePolicyDocument": {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {
                        "AWS": "arn:aws:iam::123456789012:root"
                    },
                    "Action": "sts:AssumeRole",
                    "Condition": {}
                }
            ]
        },
        "Description": "Main production role"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[ロールの変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoleDescription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-role-description.html)」を参照してください。

### `update-role`
<a name="iam_UpdateRole_cli_2_topic"></a>

次のコード例は、`update-role` を使用する方法を示しています。

**AWS CLI**  
**IAM ロールの説明またはセッション期間を変更するには**  
次の `update-role` コマンドは、IAM ロールの説明 `production-role` を `Main production role` に変更し、最大セッション期間を 12 時間に設定します。  

```
aws iam update-role \
    --role-name production-role \
    --description 'Main production role' \
    --max-session-duration 43200
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[ロールの変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage_modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-role.html)」を参照してください。

### `update-saml-provider`
<a name="iam_UpdateSamlProvider_cli_2_topic"></a>

次のコード例は、`update-saml-provider` を使用する方法を示しています。

**AWS CLI**  
**既存の SAML プロバイダーのメタデータドキュメントを更新するには**  
この例では、ARN が `arn:aws:iam::123456789012:saml-provider/SAMLADFS` である IAM の SAML プロバイダーを、ファイル `SAMLMetaData.xml` の新しい SAML メタデータドキュメントで更新します。  

```
aws iam update-saml-provider \
    --saml-metadata-document file://SAMLMetaData.xml \
    --saml-provider-arn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
出力:  

```
{
    "SAMLProviderArn": "arn:aws:iam::123456789012:saml-provider/SAMLADFS"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM SAML ID プロバイダーの作成](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSamlProvider](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-saml-provider.html)」を参照してください。

### `update-server-certificate`
<a name="iam_UpdateServerCertificate_cli_2_topic"></a>

次の例は、`update-server-certificate` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのサーバー証明書のパスまたは名前を変更するには**  
次の `update-server-certificate` コマンドは、証明書の名前を `myServerCertificate` から `myUpdatedServerCertificate` に変更します。また、Amazon CloudFront サービスからアクセスできるように `/cloudfront/` へのパスも変更します。このコマンドでは何も出力されません。`list-server-certificates` コマンドを実行すると、更新の結果を表示できます。  

```
aws-iam update-server-certificate \
    --server-certificate-name myServerCertificate \
    --new-server-certificate-name myUpdatedServerCertificate \
    --new-path /cloudfront/
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM でのサーバー証明書の管理](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-server-certificate.html)」を参照してください。

### `update-service-specific-credential`
<a name="iam_UpdateServiceSpecificCredential_cli_2_topic"></a>

次のコード例は、`update-service-specific-credential` を使用する方法を示しています。

**AWS CLI**  
**例 1: リクエストするユーザーのサービス固有の認証情報のステータスを更新するには**  
次の `update-service-specific-credential` の例では、`Inactive` にリクエストを行うユーザーの指定された認証情報のステータスを変更します。  

```
aws iam update-service-specific-credential \
    --service-specific-credential-id ACCAEXAMPLE123EXAMPLE \
    --status Inactive
```
このコマンドでは何も出力されません。  
**例 2: 指定されたユーザーのサービス固有の認証情報のステータスを更新するには**  
次の `update-service-specific-credential` の例では、指定されたユーザーの認証情報のステータスを非アクティブに変更します。  

```
aws iam update-service-specific-credential \
    --user-name sofia \
    --service-specific-credential-id ACCAEXAMPLE123EXAMPLE \
    --status Inactive
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CodeCommit ユーザーガイド*」の「[CodeCommit への HTTPS 接続用の Git 認証情報を作成する](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html#setting-up-gc-iam)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServiceSpecificCredential](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-service-specific-credential.html)」を参照してください。

### `update-signing-certificate`
<a name="iam_UpdateSigningCertificate_cli_2_topic"></a>

次のコード例は、`update-signing-certificate` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーの署名証明書を有効または無効にするには**  
次の `update-signing-certificate` コマンドは、`Bob` という名前の IAM ユーザーの指定された署名証明書を無効にします。  

```
aws iam update-signing-certificate \
    --certificate-id TA7SMP42TDN5Z26OBPJE7EXAMPLE \
    --status Inactive \
    --user-name Bob
```
署名証明書の ID を取得するには、`list-signing-certificates` コマンドを使用します。  
詳細については、「*Amazon EC2 ユーザーガイド*」の「[署名証明書の管理](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/set-up-ami-tools.html#ami-tools-managing-certs)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSigningCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-signing-certificate.html)」を参照してください。

### `update-ssh-public-key`
<a name="iam_UpdateSshPublicKey_cli_2_topic"></a>

次のコード例は、`update-ssh-public-key` を使用する方法を示しています。

**AWS CLI**  
**SSH パブリックキーのステータスを変更するには**  
次の `update-ssh-public-key` コマンドは、指定されたパブリックキーのステータスを `Inactive` に変更します。  

```
aws iam update-ssh-public-key \
    --user-name sofia \
    --ssh-public-key-id APKA1234567890EXAMPLE \
    --status Inactive
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[CodeCommit で SSH キーと SSH を使用する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_ssh-keys.html#ssh-keys-code-commit)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSshPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-ssh-public-key.html)」を参照してください。

### `update-user`
<a name="iam_UpdateUser_cli_2_topic"></a>

次のコード例は、`update-user` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザー名を変更するには**  
次の `update-user` コマンドは、IAM ユーザー `Bob` の名前を `Robert` に変更します。  

```
aws iam update-user \
    --user-name Bob \
    --new-user-name Robert
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM ユーザーグループの名前の変更](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups_manage_rename.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/update-user.html)」を参照してください。

### `upload-server-certificate`
<a name="iam_UploadServerCertificate_cli_2_topic"></a>

次の例は、`upload-server-certificate` を使用する方法を説明しています。

**AWS CLI**  
**サーバー証明書を AWS アカウントにアップロードするには**  
次の **upload-server-certificate** コマンドは、サーバー証明書を AWS アカウントにアップロードします。この例では、証明書はファイル `public_key_cert_file.pem` 内に、関連付けられたプライベートキーはファイル `my_private_key.pem` 内に、認証局 (CA) によって提供される証明書チェーンは `my_certificate_chain_file.pem` ファイル内に、それぞれ存在しています。ファイルのアップロードが完了すると、*myServerCertificate* という名前で使用できるようになります。`file://` で始まるパラメータは、ファイルの内容を読み取り、それをファイル名自体の代わりにパラメータ値として使用するようにコマンドに指示します。  

```
aws iam upload-server-certificate \
    --server-certificate-name myServerCertificate \
    --certificate-body file://public_key_cert_file.pem \
    --private-key file://my_private_key.pem \
    --certificate-chain file://my_certificate_chain_file.pem
```
出力:  

```
{
    "ServerCertificateMetadata": {
        "Path": "/",
        "ServerCertificateName": "myServerCertificate",
        "ServerCertificateId": "ASCAEXAMPLE123EXAMPLE",
        "Arn": "arn:aws:iam::1234567989012:server-certificate/myServerCertificate",
        "UploadDate": "2019-04-22T21:13:44+00:00",
        "Expiration": "2019-10-15T22:23:16+00:00"
    }
}
```
詳細については、*IAM の使用*に関するガイドの「サーバー証明書の作成、アップロード、削除」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/upload-server-certificate.html)」を参照してください。

### `upload-signing-certificate`
<a name="iam_UploadSigningCertificate_cli_2_topic"></a>

次のコード例は、`upload-signing-certificate` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーの署名証明書をアップロードするには**  
次の `upload-signing-certificate` コマンドは、`Bob` という名前の IAM ユーザーの署名証明書をアップロードします。  

```
aws iam upload-signing-certificate \
    --user-name Bob \
    --certificate-body file://certificate.pem
```
出力:  

```
{
    "Certificate": {
        "UserName": "Bob",
        "Status": "Active",
        "CertificateBody": "-----BEGIN CERTIFICATE-----<certificate-body>-----END CERTIFICATE-----",
        "CertificateId": "TA7SMP42TDN5Z26OBPJE7EXAMPLE",
        "UploadDate": "2013-06-06T21:40:08.121Z"
    }
}
```
証明書は PEM 形式の *certificate.pem* という名前のファイルにあります。  
詳細については、*IAM の使用*に関するガイドの「Creating and Uploading a User Signing Certificate」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadSigningCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/upload-signing-certificate.html)」を参照してください。

### `upload-ssh-public-key`
<a name="iam_UploadSshPublicKey_cli_2_topic"></a>

次のコード例は、`upload-ssh-public-key` を使用する方法を示しています。

**AWS CLI**  
** SSH パブリックキーをアップロードしてユーザーに関連付けるには**  
次の `upload-ssh-public-key` のコマンドは、`sshkey.pub` ファイルにあるパブリックキーをアップロードし、ユーザー `sofia` にアタッチします。  

```
aws iam upload-ssh-public-key \
    --user-name sofia \
    --ssh-public-key-body file://sshkey.pub
```
出力:  

```
{
    "SSHPublicKey": {
        "UserName": "sofia",
        "SSHPublicKeyId": "APKA1234567890EXAMPLE",
        "Fingerprint": "12:34:56:78:90:ab:cd:ef:12:34:56:78:90:ab:cd:ef",
        "SSHPublicKeyBody": "ssh-rsa <<long string generated by ssh-keygen command>>",
        "Status": "Active",
        "UploadDate": "2019-04-18T17:04:49+00:00"
    }
}
```
このコマンドに適した形式でキーを生成する方法の詳細については、「*AWS CodeCommit* ユーザーガイド」の「[SSH および Linux、macOS、または Unix: Git と CodeCommit のパブリックキーとプライベートキーをセットアップする](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-ssh-unixes.html#setting-up-ssh-unixes-keys)」または「[SSH と Windows: Git と CodeCommit 用のパブリックキーとプライベートキーのセットアップ](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-ssh-windows.html#setting-up-ssh-windows-keys-windows)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadSshPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/upload-ssh-public-key.html)」を参照してください。

# を使用した IAM Access Analyzer の例 AWS CLI
<a name="cli_2_accessanalyzer_code_examples"></a>

次のコード例は、IAM Access Analyzer AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `apply-archive-rule`
<a name="accessanalyzer_ApplyArchiveRule_cli_2_topic"></a>

次の例では、`apply-archive-rule` を使用する方法を説明しています。

**AWS CLI**  
**アーカイブルール基準を満たす既存の検出結果にアーカイブルールを適用する方法**  
次の `apply-archive-rule` の例では、アーカイブルールの基準を満たす既存の検出結果にアーカイブルールを適用します。  

```
aws accessanalyzer apply-archive-rule \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/UnusedAccess-ConsoleAnalyzer-organization \
    --rule-name MyArchiveRule
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[アーカイブのルール](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-archive-rules.html)」を参照してください。  
+  API の詳細については、 「*AWS CLI コマンドリファレンス*」の「[ApplyArchiveRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/apply-archive-rule.html)」を参照してください。

### `cancel-policy-generation`
<a name="accessanalyzer_CancelPolicyGeneration_cli_2_topic"></a>

次の例では、`cancel-policy-generation` を使用する方法を説明しています。

**AWS CLI**  
**ポリシー生成要求をキャンセルする方法**  
次の `cancel-policy-generation` 例では、リクエストされたポリシー生成ジョブ ID をキャンセルします。  

```
aws accessanalyzer cancel-policy-generation \
    --job-id 923a56b0-ebb8-4e80-8a3c-a11ccfbcd6f2
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer ポリシーの生成](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelPolicyGeneration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/cancel-policy-generation.html)」を参照してください。

### `check-access-not-granted`
<a name="accessanalyzer_CheckAccessNotGranted_cli_2_topic"></a>

次の例では、`check-access-not-granted` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアクセスがポリシーによって許可されていないかどうかを確認する方法**  
`check-access-not-granted` の例では、指定されたアクセスがポリシーによって許可されていないかどうかを確認します。  

```
aws accessanalyzer check-access-not-granted \
    --policy-document file://myfile.json \
    --access actions="s3:DeleteBucket","s3:GetBucketLocation" \
    --policy-type IDENTITY_POLICY
```
`myfile.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket",
                "arn:aws:s3:::amzn-s3-demo-bucket/*"
            ]
        }
    ]
}
```
出力:  

```
{
    "result": "PASS",
    "message": "The policy document does not grant access to perform one or more of the listed actions."
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer API でプレビュー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-preview-access-apis.html)」を参照してください。  
+  API の詳細については、 「*AWS CLI コマンドリファレンス*」の「[CheckAccessNotGranted](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/check-access-not-granted.html)」を参照してください。

### `check-no-new-access`
<a name="accessanalyzer_CheckNoNewAccess_cli_2_topic"></a>

次の例では、`check-no-new-access` を使用する方法を説明しています。

**AWS CLI**  
**既存のポリシーと比較して、更新されたポリシーで新しいアクセスが許可されるかどうかを確認する方法**  
`check-no-new-access` の例では、既存のポリシーと比較して、更新されたポリシーで新しいアクセスが許可されるかどうかを確認します。  

```
aws accessanalyzer check-no-new-access \
    --existing-policy-document file://existing-policy.json \
    --new-policy-document file://new-policy.json \
    --policy-type IDENTITY_POLICY
```
`existing-policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket",
                "arn:aws:s3:::amzn-s3-demo-bucket/*"
            ]
        }
    ]
}
```
`new-policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectAcl",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket",
                "arn:aws:s3:::amzn-s3-demo-bucket/*"
            ]
        }
    ]
}
```
出力:  

```
{
    "result": "FAIL",
    "message": "The modified permissions grant new access compared to your existing policy.",
    "reasons": [
        {
            "description": "New access in the statement with index: 0.",
            "statementIndex": 0
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer API でプレビュー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-preview-access-apis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CheckNoNewAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/check-no-new-access.html)」を参照してください。

### `check-no-public-access`
<a name="accessanalyzer_CheckNoPublicAccess_cli_2_topic"></a>

次の例では、`check-no-public-access` を使用する方法を説明しています。

**AWS CLI**  
**リソースポリシーが、指定したリソースタイプへのパブリックアクセスを許可できるかどうかを確認する方法**  
`check-no-public-access` の例では、リソースポリシーが、指定したリソースタイプへのパブリックアクセスを許可できるかどうかを確認します。  

```
aws accessanalyzer check-no-public-access \
    --policy-document file://check-no-public-access-myfile.json \
    --resource-type AWS::S3::Bucket
```
`myfile.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "CheckNoPublicAccess",
            "Effect": "Allow",
            "Principal": { "AWS": "arn:aws:iam::111122223333:user/JohnDoe" },
            "Action": [
                "s3:GetObject"
            ]
        }
    ]
}
```
出力:  

```
{
    "result": "PASS",
    "message": "The resource policy does not grant public access for the given resource type."
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer API でプレビュー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-preview-access-apis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CheckNoPublicAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/check-no-public-access.html)」を参照してください。

### `create-access-preview`
<a name="accessanalyzer_CreateAccessPreview_cli_2_topic"></a>

次の例では、`create-access-preview` を使用する方法を説明しています。

**AWS CLI**  
**リソースアクセス許可をデプロイする前に、リソースの IAM Access Analyzer の検出結果をプレビューできるアクセスプレビューを作成する方法**  
次の`create-access-preview`例では、 AWS アカウントにリソースアクセス許可をデプロイする前に、リソースの IAM Access Analyzer の検出結果をプレビューできるアクセスプレビューを作成します。  

```
aws accessanalyzer create-access-preview \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --configurations file://myfile.json
```
`myfile.json` の内容:  

```
{
    "arn:aws:s3:::amzn-s3-demo-bucket": {
        "s3Bucket": {
            "bucketPolicy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"arn:aws:iam::111122223333:root\"]},\"Action\":[\"s3:PutObject\",\"s3:PutObjectAcl\"],\"Resource\":\"arn:aws:s3:::amzn-s3-demo-bucket/*\"}]}",
            "bucketPublicAccessBlock": {
                "ignorePublicAcls": true,
                "restrictPublicBuckets": true
            },
            "bucketAclGrants": [
                {
                    "grantee": {
                        "id": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be"
                    },
                    "permission": "READ"
                }
            ]
        }
    }
}
```
出力:  

```
{
    "id": "3c65eb13-6ef9-4629-8919-a32043619e6b"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer API でプレビュー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-preview-access-apis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAccessPreview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/create-access-preview.html)」を参照してください。

### `create-analyzer`
<a name="accessanalyzer_CreateAnalyzer_cli_2_topic"></a>

次の例では、`create-analyzer` を使用する方法を説明しています。

**AWS CLI**  
**アナライザーを作成する方法方法**  
次の の`create-analyzer`例では、 AWS アカウントにアナライザーを作成します。  

```
aws accessanalyzer create-analyzer \
    --analyzer-name example \
    --type ACCOUNT
```
出力:  

```
{
    "arn": "arn:aws:access-analyzer:us-east-2:111122223333:analyzer/example"
}
```
詳細については、*AWS IAM* [ユーザーガイドの AWS Identity and Access Management Access Analyzer の検出結果の開始](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-getting-started.html)方法を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAnalyzer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/create-analyzer.html)」を参照してください。

### `create-archive-rule`
<a name="accessanalyzer_CreateArchiveRule_cli_2_topic"></a>

次の例では、`create-archive-rule` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアナライザーのアーカイブルールを作成する方法**  
次の の`create-archive-rule`例では、 AWS アカウントで指定されたアナライザーのアーカイブルールを作成します。  

```
aws accessanalyzer create-archive-rule \
    --analyzer-name UnusedAccess-ConsoleAnalyzer-organization \
    --rule-name MyRule \
    --filter '{"resource": {"contains": ["Cognito"]}, "resourceType": {"eq": ["AWS::IAM::Role"]}}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[アーカイブのルール](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-archive-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateArchiveRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/create-archive-rule.html)」を参照してください。

### `delete-analyzer`
<a name="accessanalyzer_DeleteAnalyzer_cli_2_topic"></a>

次の例では、`delete-analyzer` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアナライザーを削除する方法**  
次の の`delete-analyzer`例では、 AWS アカウントの指定されたアナライザーを削除します。  

```
aws accessanalyzer delete-analyzer \
    --analyzer-name example
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[アーカイブのルール](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-archive-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAnalyzer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/delete-analyzer.html)」を参照してください。

### `delete-archive-rule`
<a name="accessanalyzer_DeleteArchiveRule_cli_2_topic"></a>

次の例では、`delete-archive-rule` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアーカイブルールを削除する方法**  
次の の`delete-archive-rule`例では、 AWS アカウントで指定されたアーカイブルールを削除します。  

```
aws accessanalyzer delete-archive-rule \
    --analyzer-name UnusedAccess-ConsoleAnalyzer-organization \
    --rule-name MyRule
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[アーカイブのルール](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-archive-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteArchiveRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/delete-archive-rule.html)」を参照してください。

### `get-access-preview`
<a name="accessanalyzer_GetAccessPreview_cli_2_topic"></a>

次の例では、`get-access-preview` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアナライザーのアクセスプレビューに関する情報を取得する方法**  
次の の`get-access-preview`例では、 AWS アカウント内の指定されたアナライザーのアクセスプレビューに関する情報を取得します。  

```
aws accessanalyzer get-access-preview \
    --access-preview-id 3c65eb13-6ef9-4629-8919-a32043619e6b \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account
```
出力:  

```
{
    "accessPreview": {
        "id": "3c65eb13-6ef9-4629-8919-a32043619e6b",
        "analyzerArn": "arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account",
        "configurations": {
            "arn:aws:s3:::amzn-s3-demo-bucket": {
                "s3Bucket": {
                    "bucketPolicy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"arn:aws:iam::111122223333:root\"]},\"Action\":[\"s3:PutObject\",\"s3:PutObjectAcl\"],\"Resource\":\"arn:aws:s3:::amzn-s3-demo-bucket/*\"}]}",
                    "bucketAclGrants": [
                        {
                            "permission": "READ",
                            "grantee": {
                                "id": "79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be"
                            }
                        }
                    ],
                    "bucketPublicAccessBlock": {
                        "ignorePublicAcls": true,
                        "restrictPublicBuckets": true
                    }
                }
            }
        },
        "createdAt": "2024-02-17T00:18:44+00:00",
        "status": "COMPLETED"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer API でプレビュー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-preview-access-apis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccessPreview](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-access-preview.html)」を参照してください。

### `get-analyzed-resource`
<a name="accessanalyzer_GetAnalyzedResource_cli_2_topic"></a>

次の例では、`get-analyzed-resource` を使用する方法を説明しています。

**AWS CLI**  
**分析されたリソースに関する情報を取得する方法**  
次の の`get-analyzed-resource`例では、 AWS アカウントで分析されたリソースに関する情報を取得します。  

```
aws accessanalyzer get-analyzed-resource \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --resource-arn arn:aws:s3:::amzn-s3-demo-bucket
```
出力:  

```
{
    "resource": {
        "analyzedAt": "2024-02-15T18:01:53.002000+00:00",
        "isPublic": false,
        "resourceArn": "arn:aws:s3:::amzn-s3-demo-bucket",
        "resourceOwnerAccount": "111122223333",
        "resourceType": "AWS::S3::Bucket"
    }
}
```
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAnalyzedResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-analyzed-resource.html)」を参照してください。

### `get-analyzer`
<a name="accessanalyzer_GetAnalyzer_cli_2_topic"></a>

次の例では、`get-analyzer` を使用する方法を説明しています。

**AWS CLI**  
**指定した管理ポリシーに関する情報を取得する方法**  
次の `get-analyzer`の例では、 AWS アカウント内の指定されたアナライザーに関する情報を取得します。  

```
aws accessanalyzer get-analyzer \
    --analyzer-name ConsoleAnalyzer-account
```
出力:  

```
{
    "analyzer": {
        "arn": "arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account",
        "createdAt": "2019-12-03T07:28:17+00:00",
        "lastResourceAnalyzed": "arn:aws:sns:us-west-2:111122223333:config-topic",
        "lastResourceAnalyzedAt": "2024-02-15T18:01:53.003000+00:00",
        "name": "ConsoleAnalyzer-account",
        "status": "ACTIVE",
        "tags": {
            "auto-delete": "no"
        },
        "type": "ACCOUNT"
    }
}
```
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAnalyzer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-analyzer.html)」を参照してください。

### `get-archive-rule`
<a name="accessanalyzer_GetArchiveRule_cli_2_topic"></a>

次の例では、`get-archive-rule` を使用する方法を説明しています。

**AWS CLI**  
**アーカイブルールに関する情報を取得する方法**  
次の の`get-archive-rule`例では、 AWS アカウントのアーカイブルールに関する情報を取得します。  

```
aws accessanalyzer get-archive-rule \
    --analyzer-name UnusedAccess-ConsoleAnalyzer-organization \
    --rule-name MyArchiveRule
```
出力:  

```
{
    "archiveRule": {
        "createdAt": "2024-02-15T00:49:27+00:00",
        "filter": {
            "resource": {
                "contains": [
                    "Cognito"
                ]
            },
            "resourceType": {
                "eq": [
                    "AWS::IAM::Role"
                ]
            }
        },
        "ruleName": "MyArchiveRule",
        "updatedAt": "2024-02-15T00:49:27+00:00"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[アーカイブのルール](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-archive-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetArchiveRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-archive-rule.html)」を参照してください。

### `get-finding-v2`
<a name="accessanalyzer_GetFindingV2_cli_2_topic"></a>

次の例では、`get-finding-v2` を使用する方法を説明しています。

**AWS CLI**  
**指定された検出結果に関する情報を取得する方法**  
次の の`get-finding-v2`例では、 AWS アカウントで指定された検出結果に関する情報を取得します。  

```
aws accessanalyzer get-finding-v2 \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-organization \
    --id 0910eedb-381e-4e95-adda-0d25c19e6e90
```
出力:  

```
{
    "findingDetails": [
        {
            "externalAccessDetails": {
                "action": [
                    "sts:AssumeRoleWithWebIdentity"
                ],
                "condition": {
                    "cognito-identity.amazonaws.com:aud": "us-west-2:EXAMPLE0-0000-0000-0000-000000000000"
                },
                "isPublic": false,
                "principal": {
                    "Federated": "cognito-identity.amazonaws.com"
                }
            }
        }
    ],
    "resource": "arn:aws:iam::111122223333:role/Cognito_testpoolAuth_Role",
    "status": "ACTIVE",
    "error": null,
    "createdAt": "2021-02-26T21:17:50.905000+00:00",
    "resourceType": "AWS::IAM::Role",
    "findingType": "ExternalAccess",
    "resourceOwnerAccount": "111122223333",
    "analyzedAt": "2024-02-16T18:17:47.888000+00:00",
    "id": "0910eedb-381e-4e95-adda-0d25c19e6e90",
    "updatedAt": "2021-02-26T21:17:50.905000+00:00"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[検出結果の確認](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-findings-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFindingV2](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-finding-v2.html)」を参照してください。

### `get-finding`
<a name="accessanalyzer_GetFinding_cli_2_topic"></a>

次の例では、`get-finding` を使用する方法を説明しています。

**AWS CLI**  
**指定された検出結果に関する情報を取得する方法**  
次の の`get-finding`例では、 AWS アカウントで指定された検出結果に関する情報を取得します。  

```
aws accessanalyzer get-finding \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-organization \
    --id 0910eedb-381e-4e95-adda-0d25c19e6e90
```
出力:  

```
{
    "finding": {
        "id": "0910eedb-381e-4e95-adda-0d25c19e6e90",
        "principal": {
            "Federated": "cognito-identity.amazonaws.com"
        },
        "action": [
            "sts:AssumeRoleWithWebIdentity"
        ],
        "resource": "arn:aws:iam::111122223333:role/Cognito_testpoolAuth_Role",
        "isPublic": false,
        "resourceType": "AWS::IAM::Role",
        "condition": {
            "cognito-identity.amazonaws.com:aud": "us-west-2:EXAMPLE0-0000-0000-0000-000000000000"
        },
        "createdAt": "2021-02-26T21:17:50.905000+00:00",
        "analyzedAt": "2024-02-16T18:17:47.888000+00:00",
        "updatedAt": "2021-02-26T21:17:50.905000+00:00",
        "status": "ACTIVE",
        "resourceOwnerAccount": "111122223333"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[検出結果の確認](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-findings-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFinding](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-finding.html)」を参照してください。

### `get-generated-policy`
<a name="accessanalyzer_GetGeneratedPolicy_cli_2_topic"></a>

次の例では、`get-generated-policy` を使用する方法を説明しています。

**AWS CLI**  
**`StartPolicyGeneration ` API を使用して生成されたポリシーを取得する方法**  
次の の`get-generated-policy`例では、 AWS アカウントの StartPolicyGeneration API を使用して生成されたポリシーを取得します。  

```
aws accessanalyzer get-generated-policy \
    --job-id c557dc4a-0338-4489-95dd-739014860ff9
```
出力:  

```
{
    "generatedPolicyResult": {
        "generatedPolicies": [
            {
                "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"SupportedServiceSid0\",\"Effect\":\"Allow\",\"Action\":[\"access-analyzer:GetAnalyzer\",\"access-analyzer:ListAnalyzers\",\"access-analyzer:ListArchiveRules\",\"access-analyzer:ListFindings\",\"cloudtrail:DescribeTrails\",\"cloudtrail:GetEventDataStore\",\"cloudtrail:GetEventSelectors\",\"cloudtrail:GetInsightSelectors\",\"cloudtrail:GetTrailStatus\",\"cloudtrail:ListChannels\",\"cloudtrail:ListEventDataStores\",\"cloudtrail:ListQueries\",\"cloudtrail:ListTags\",\"cloudtrail:LookupEvents\",\"ec2:DescribeRegions\",\"iam:GetAccountSummary\",\"iam:GetOpenIDConnectProvider\",\"iam:GetRole\",\"iam:ListAccessKeys\",\"iam:ListAccountAliases\",\"iam:ListOpenIDConnectProviders\",\"iam:ListRoles\",\"iam:ListSAMLProviders\",\"kms:ListAliases\",\"s3:GetBucketLocation\",\"s3:ListAllMyBuckets\"],\"Resource\":\"*\"}]}"
            }
        ],
        "properties": {
            "cloudTrailProperties": {
                "endTime": "2024-02-14T22:44:40+00:00",
                "startTime": "2024-02-13T00:30:00+00:00",
                "trailProperties": [
                    {
                        "allRegions": true,
                        "cloudTrailArn": "arn:aws:cloudtrail:us-west-2:111122223333:trail/my-trail",
                        "regions": []
                    }
                ]
            },
            "isComplete": false,
            "principalArn": "arn:aws:iam::111122223333:role/Admin"
        }
    },
    "jobDetails": {
        "completedOn": "2024-02-14T22:47:01+00:00",
        "jobId": "c557dc4a-0338-4489-95dd-739014860ff9",
        "startedOn": "2024-02-14T22:44:41+00:00",
        "status": "SUCCEEDED"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer ポリシーの生成](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGeneratedPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/get-generated-policy.html)」を参照してください。

### `list-access-preview-findings`
<a name="accessanalyzer_ListAccessPreviewFindings_cli_2_topic"></a>

次の例では、`list-access-preview-findings` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアクセスプレビューによって生成されたアクセスプレビュー検出結果の一覧を取得する方法**  
次の の`list-access-preview-findings`例では、 AWS アカウントで指定されたアクセスプレビューによって生成されたアクセスプレビューの検出結果のリストを取得します。  

```
aws accessanalyzer list-access-preview-findings \
    --access-preview-id 3c65eb13-6ef9-4629-8919-a32043619e6b \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account
```
出力:  

```
{
    "findings": [
        {
            "id": "e22fc158-1c87-4c32-9464-e7f405ce8d74",
            "principal": {
                "AWS": "111122223333"
            },
            "action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "condition": {},
            "resource": "arn:aws:s3:::amzn-s3-demo-bucket",
            "isPublic": false,
            "resourceType": "AWS::S3::Bucket",
            "createdAt": "2024-02-17T00:18:46+00:00",
            "changeType": "NEW",
            "status": "ACTIVE",
            "resourceOwnerAccount": "111122223333",
            "sources": [
                {
                    "type": "POLICY"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer API でプレビュー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-preview-access-apis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessPreviewFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-access-preview-findings.html)」を参照してください。

### `list-access-previews`
<a name="accessanalyzer_ListAccessPreviews_cli_2_topic"></a>

次の例では、`list-access-previews` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアナライザーのアクセスプレビューの一覧を取得する方法**  
次の の`list-access-previews`例では、 AWS アカウント内の指定されたアナライザーのアクセスプレビューのリストを取得します。  

```
aws accessanalyzer list-access-previews \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account
```
出力:  

```
{
    "accessPreviews": [
        {
            "id": "3c65eb13-6ef9-4629-8919-a32043619e6b",
            "analyzerArn": "arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account",
            "createdAt": "2024-02-17T00:18:44+00:00",
            "status": "COMPLETED"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer API でプレビュー](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-preview-access-apis.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessPreviews](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-access-previews.html)」を参照してください。

### `list-analyzed-resources`
<a name="accessanalyzer_ListAnalyzedResources_cli_2_topic"></a>

次の例では、`list-analyzed-resources` を使用する方法を説明しています。

**AWS CLI**  
**使用可能なウィジェットを一覧表示するには**  
次の の`list-analyzed-resources`例では、 AWS アカウントで使用可能なウィジェットを一覧表示します。  

```
aws accessanalyzer list-analyzed-resources \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --resource-type AWS::IAM::Role
```
出力:  

```
{
    "analyzedResources": [
        {
            "resourceArn": "arn:aws:sns:us-west-2:111122223333:Validation-Email",
            "resourceOwnerAccount": "111122223333",
            "resourceType": "AWS::SNS::Topic"
        },
        {
            "resourceArn": "arn:aws:sns:us-west-2:111122223333:admin-alerts",
            "resourceOwnerAccount": "111122223333",
            "resourceType": "AWS::SNS::Topic"
        },
        {
            "resourceArn": "arn:aws:sns:us-west-2:111122223333:config-topic",
            "resourceOwnerAccount": "111122223333",
            "resourceType": "AWS::SNS::Topic"
        },
        {
            "resourceArn": "arn:aws:sns:us-west-2:111122223333:inspector-topic",
            "resourceOwnerAccount": "111122223333",
            "resourceType": "AWS::SNS::Topic"
        }
    ]
}
```
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAnalyzedResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-analyzed-resources.html)」を参照してください。

### `list-analyzers`
<a name="accessanalyzer_ListAnalyzers_cli_2_topic"></a>

次の例では、`list-analyzers` を使用する方法を説明しています。

**AWS CLI**  
**アナライザーの一覧を取得する方法**  
次の の`list-analyzers`例では、 AWS アカウントのアナライザーのリストを取得します。  

```
aws accessanalyzer list-analyzers
```
出力:  

```
{
    "analyzers": [
        {
            "arn": "arn:aws:access-analyzer:us-west-2:111122223333:analyzer/UnusedAccess-ConsoleAnalyzer-organization",
            "createdAt": "2024-02-15T00:46:40+00:00",
            "name": "UnusedAccess-ConsoleAnalyzer-organization",
            "status": "ACTIVE",
            "tags": {
                "auto-delete": "no"
            },
            "type": "ORGANIZATION_UNUSED_ACCESS"
        },
        {
            "arn": "arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-organization",
            "createdAt": "2020-04-25T07:43:28+00:00",
            "lastResourceAnalyzed": "arn:aws:s3:::amzn-s3-demo-bucket",
            "lastResourceAnalyzedAt": "2024-02-15T21:51:56.517000+00:00",
            "name": "ConsoleAnalyzer-organization",
            "status": "ACTIVE",
            "tags": {
                "auto-delete": "no"
            },
            "type": "ORGANIZATION"
        },
        {
            "arn": "arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account",
            "createdAt": "2019-12-03T07:28:17+00:00",
            "lastResourceAnalyzed": "arn:aws:sns:us-west-2:111122223333:config-topic",
            "lastResourceAnalyzedAt": "2024-02-15T18:01:53.003000+00:00",
            "name": "ConsoleAnalyzer-account",
            "status": "ACTIVE",
            "tags": {
                "auto-delete": "no"
            },
            "type": "ACCOUNT"
        }
    ]
}
```
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAnalyzers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-analyzers.html)」を参照してください。

### `list-archive-rules`
<a name="accessanalyzer_ListArchiveRules_cli_2_topic"></a>

次の例では、`list-archive-rules` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアナライザー用に作成されたアーカイブルールの一覧を取得する方法**  
次の の`list-archive-rules`例では、 AWS アカウント内の指定されたアナライザー用に作成されたアーカイブルールのリストを取得します。  

```
aws accessanalyzer list-archive-rules \
    --analyzer-name UnusedAccess-ConsoleAnalyzer-organization
```
出力:  

```
{
    "archiveRules": [
        {
            "createdAt": "2024-02-15T00:49:27+00:00",
            "filter": {
                "resource": {
                    "contains": [
                        "Cognito"
                    ]
                },
                "resourceType": {
                    "eq": [
                        "AWS::IAM::Role"
                    ]
                }
            },
            "ruleName": "MyArchiveRule",
            "updatedAt": "2024-02-15T00:49:27+00:00"
        },
        {
            "createdAt": "2024-02-15T23:27:45+00:00",
            "filter": {
                "findingType": {
                    "eq": [
                        "UnusedIAMUserAccessKey"
                    ]
                }
            },
            "ruleName": "ArchiveRule-56125a39-e517-4ff8-afb1-ef06f58db612",
            "updatedAt": "2024-02-15T23:27:45+00:00"
        }
    ]
}
```
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListArchiveRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-archive-rules.html)」を参照してください。

### `list-findings-v2`
<a name="accessanalyzer_ListFindingsV2_cli_2_topic"></a>

次の例では、`list-findings-v2` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアナライザーによって生成された検出結果の一覧を取得する方法**  
次の の`list-findings-v2`例では、 AWS アカウントの指定されたアナライザーによって生成された結果のリストを取得します。この例では、名前に「`Cognito`」が含まれている IAM ロールのみが含まれるように結果をフィルタリングします。  

```
aws accessanalyzer list-findings-v2 \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --filter '{"resource": {"contains": ["Cognito"]}, "resourceType": {"eq": ["AWS::IAM::Role"]}}'
```
出力:  

```
{
    "findings": [
        {
            "analyzedAt": "2024-02-16T18:17:47.888000+00:00",
            "createdAt": "2021-02-26T21:17:24.710000+00:00",
            "id": "597f3bc2-3adc-4c18-9879-5c4b23485e46",
            "resource": "arn:aws:iam::111122223333:role/Cognito_testpoolUnauth_Role",
            "resourceType": "AWS::IAM::Role",
            "resourceOwnerAccount": "111122223333",
            "status": "ACTIVE",
            "updatedAt": "2021-02-26T21:17:24.710000+00:00",
            "findingType": "ExternalAccess"
        },
        {
            "analyzedAt": "2024-02-16T18:17:47.888000+00:00",
            "createdAt": "2021-02-26T21:17:50.905000+00:00",
            "id": "ce0e221a-85b9-4d52-91ff-d7678075442f",
            "resource": "arn:aws:iam::111122223333:role/Cognito_testpoolAuth_Role",
            "resourceType": "AWS::IAM::Role",
            "resourceOwnerAccount": "111122223333",
            "status": "ACTIVE",
            "updatedAt": "2021-02-26T21:17:50.905000+00:00",
            "findingType": "ExternalAccess"
        }
    ]
}
```
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFindingsV2](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-findings-v2.html)」を参照してください。

### `list-findings`
<a name="accessanalyzer_ListFindings_cli_2_topic"></a>

次の例では、`list-findings` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアナライザーによって生成された検出結果の一覧を取得する方法**  
次の の`list-findings`例では、 AWS アカウントの指定されたアナライザーによって生成された結果のリストを取得します。この例では、名前に「`Cognito`」が含まれている IAM ロールのみが含まれるように結果をフィルタリングします。  

```
aws accessanalyzer list-findings \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --filter '{"resource": {"contains": ["Cognito"]}, "resourceType": {"eq": ["AWS::IAM::Role"]}}'
```
出力:  

```
{
    "findings": [
        {
            "id": "597f3bc2-3adc-4c18-9879-5c4b23485e46",
            "principal": {
                "Federated": "cognito-identity.amazonaws.com"
            },
            "action": [
                "sts:AssumeRoleWithWebIdentity"
            ],
            "resource": "arn:aws:iam::111122223333:role/Cognito_testpoolUnauth_Role",
            "isPublic": false,
            "resourceType": "AWS::IAM::Role",
            "condition": {
                "cognito-identity.amazonaws.com:aud": "us-west-2:EXAMPLE0-0000-0000-0000-000000000000"
            },
            "createdAt": "2021-02-26T21:17:24.710000+00:00",
            "analyzedAt": "2024-02-16T18:17:47.888000+00:00",
            "updatedAt": "2021-02-26T21:17:24.710000+00:00",
            "status": "ACTIVE",
            "resourceOwnerAccount": "111122223333"
        },
        {
            "id": "ce0e221a-85b9-4d52-91ff-d7678075442f",
            "principal": {
                "Federated": "cognito-identity.amazonaws.com"
            },
            "action": [
                "sts:AssumeRoleWithWebIdentity"
            ],
            "resource": "arn:aws:iam::111122223333:role/Cognito_testpoolAuth_Role",
            "isPublic": false,
            "resourceType": "AWS::IAM::Role",
            "condition": {
                "cognito-identity.amazonaws.com:aud": "us-west-2:EXAMPLE0-0000-0000-0000-000000000000"
            },
            "createdAt": "2021-02-26T21:17:50.905000+00:00",
            "analyzedAt": "2024-02-16T18:17:47.888000+00:00",
            "updatedAt": "2021-02-26T21:17:50.905000+00:00",
            "status": "ACTIVE",
            "resourceOwnerAccount": "111122223333"
        }
    ]
}
```
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-findings.html)」を参照してください。

### `list-policy-generations`
<a name="accessanalyzer_ListPolicyGenerations_cli_2_topic"></a>

次の例では、`list-policy-generations` を使用する方法を説明しています。

**AWS CLI**  
**過去 7 日間にリクエストされたすべてのポリシー生成を一覧表示する方法**  
次の の`list-policy-generations`例では、 AWS アカウントで過去 7 日間にリクエストされたすべてのポリシー生成を一覧表示します。  

```
aws accessanalyzer list-policy-generations
```
出力:  

```
{
    "policyGenerations": [
        {
            "completedOn": "2024-02-14T23:43:38+00:00",
            "jobId": "923a56b0-ebb8-4e80-8a3c-a11ccfbcd6f2",
            "principalArn": "arn:aws:iam::111122223333:role/Admin",
            "startedOn": "2024-02-14T23:43:02+00:00",
            "status": "CANCELED"
        },
        {
            "completedOn": "2024-02-14T22:47:01+00:00",
            "jobId": "c557dc4a-0338-4489-95dd-739014860ff9",
            "principalArn": "arn:aws:iam::111122223333:role/Admin",
            "startedOn": "2024-02-14T22:44:41+00:00",
            "status": "SUCCEEDED"
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer ポリシーの生成](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPolicyGenerations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-policy-generations.html)」を参照してください。

### `list-tags-for-resource`
<a name="accessanalyzer_ListTagsForResource_cli_2_topic"></a>

次の例では、`list-tags-for-resource` を使用する方法を説明しています。

**AWS CLI**  
**指定されたリソースに適用されたタグの一覧を取得する方法**  
次の の`list-tags-for-resource`例では、 AWS アカウントの指定されたリソースに適用されるタグのリストを取得します。  

```
aws accessanalyzer list-tags-for-resource \
    --resource-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account
```
出力:  

```
{
    "tags": {
        "Zone-of-trust": "Account",
        "Name": "ConsoleAnalyzer"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer ポリシーの生成](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/list-tags-for-resource.html)」を参照してください。

### `start-policy-generation`
<a name="accessanalyzer_StartPolicyGeneration_cli_2_topic"></a>

次の例では、`start-policy-generation` を使用する方法を説明しています。

**AWS CLI**  
**ポリシー生成リクエストを開始する方法**  
次の の`start-policy-generation`例では、 AWS アカウントでポリシー生成リクエストを開始します。  

```
aws accessanalyzer start-policy-generation \
    --policy-generation-details '{"principalArn":"arn:aws:iam::111122223333:role/Admin"}' \
    --cloud-trail-details file://myfile.json
```
`myfile.json` の内容:  

```
{
    "accessRole": "arn:aws:iam::111122223333:role/service-role/AccessAnalyzerMonitorServiceRole",
    "startTime": "2024-02-13T00:30:00Z",
    "trails": [
        {
            "allRegions": true,
            "cloudTrailArn": "arn:aws:cloudtrail:us-west-2:111122223333:trail/my-trail"
        }
    ]
}
```
出力:  

```
{
    "jobId": "c557dc4a-0338-4489-95dd-739014860ff9"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer ポリシーの生成](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartPolicyGeneration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/start-policy-generation.html)」を参照してください。

### `start-resource-scan`
<a name="accessanalyzer_StartResourceScan_cli_2_topic"></a>

次の例では、`start-resource-scan` を使用する方法を説明しています。

**AWS CLI**  
**指定されたリソースに適用されるポリシーのスキャンをすぐに開始する方法**  
次の の`start-resource-scan`例では、 AWS アカウント内の指定されたリソースに適用されるポリシーのスキャンをすぐに開始します。  

```
aws accessanalyzer start-resource-scan \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --resource-arn arn:aws:iam::111122223333:role/Cognito_testpoolAuth_Role
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[IAM Access Analyzer ポリシーの生成](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-policy-generation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartResourceScan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/start-resource-scan.html)」を参照してください。

### `tag-resource`
<a name="accessanalyzer_TagResource_cli_2_topic"></a>

次の例では、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
**指定されたリソースにタグを追加する方法**  
次の の`tag-resource`例では、 AWS アカウントの指定されたリソースにタグを追加します。  

```
aws accessanalyzer tag-resource \
    --resource-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --tags Environment=dev,Purpose=testing
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="accessanalyzer_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**指定されたリソースからタグを削除する方法**  
次の の`untag-resource`例では、 AWS アカウントの指定されたリソースからタグを削除します。  

```
aws accessanalyzer untag-resource \
    --resource-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/ConsoleAnalyzer-account \
    --tag-keys Environment Purpose
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/untag-resource.html)」を参照してください。

### `update-archive-rule`
<a name="accessanalyzer_UpdateArchiveRule_cli_2_topic"></a>

次の例では、`update-archive-rule` を使用する方法を説明しています。

**AWS CLI**  
**指定されたアーカイブルールの基準と値を更新する方法**  
次の の`update-archive-rule`例では、 AWS アカウントで指定されたアーカイブルールの基準と値を更新します。  

```
aws accessanalyzer update-archive-rule \
    --analyzer-name UnusedAccess-ConsoleAnalyzer-organization \
    --rule-name MyArchiveRule \
    --filter '{"resource": {"contains": ["Cognito"]}, "resourceType": {"eq": ["AWS::IAM::Role"]}}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IAM ユーザーガイド*」の「[アーカイブのルール](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-archive-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateArchiveRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/update-archive-rule.html)」を参照してください。

### `update-findings`
<a name="accessanalyzer_UpdateFindings_cli_2_topic"></a>

次の例では、`update-findings` を使用する方法を説明しています。

**AWS CLI**  
**指定された検出結果のステータスを更新する方法**  
次の の`update-findings`例では、 AWS アカウントで指定された検出結果のステータスを更新します。  

```
aws accessanalyzer update-findings \
    --analyzer-arn arn:aws:access-analyzer:us-west-2:111122223333:analyzer/UnusedAccess-ConsoleAnalyzer-organization \
    --ids 4f319ac3-2e0c-4dc4-bf51-7013a086b6ae 780d586a-2cce-4f72-aff6-359d450e7500 \
    --status ARCHIVED
```
このコマンドでは何も出力されません。  
詳細については、*AWS IAM ユーザーガイド*の [AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html) の使用を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/update-findings.html)」を参照してください。

### `validate-policy`
<a name="accessanalyzer_ValidatePolicy_cli_2_topic"></a>

次の例では、`validate-policy` を使用する方法を説明しています。

**AWS CLI**  
**ポリシーの検証をリクエストし、検出結果の一覧を返す方法**  
次の `validate-policy` の例では、ポリシーの検証をリクエストし、検出結果の一覧を返します。この例のポリシーは、ウェブ ID フェデレーションに使用される Amazon Cognito ロールのロール信頼ポリシーです。信頼ポリシーから生成された検出結果は、使用されているロールの引き受けアクション「`sts:AssumeRole`」が正しくないため、空の `Sid` の要素の値とポリシープリンシパルが一致しません。Cognito で使用する正しいロールの引き受けアクションは「`sts:AssumeRoleWithWebIdentity`」です。  

```
aws accessanalyzer validate-policy \
    --policy-document file://myfile.json \
    --policy-type RESOURCE_POLICY
```
`myfile.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Federated": "cognito-identity.amazonaws.com"
            },
            "Action": [
                "sts:AssumeRole",
                "sts:TagSession"
            ],
            "Condition": {
                "StringEquals": {
                    "cognito-identity.amazonaws.com:aud": "us-west-2_EXAMPLE"
                }
            }
        }
    ]
}
```
出力:  

```
{
    "findings": [
        {
            "findingDetails": "Add a value to the empty string in the Sid element.",
            "findingType": "SUGGESTION",
            "issueCode": "EMPTY_SID_VALUE",
            "learnMoreLink": "https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-reference-policy-checks.html#access-analyzer-reference-policy-checks-suggestion-empty-sid-value",
            "locations": [
                {
                    "path": [
                        {
                            "value": "Statement"
                        },
                        {
                            "index": 0
                        },
                        {
                            "value": "Sid"
                        }
                    ],
                    "span": {
                        "end": {
                            "column": 21,
                            "line": 5,
                            "offset": 81
                        },
                        "start": {
                            "column": 19,
                            "line": 5,
                            "offset": 79
                        }
                    }
                }
            ]
        },
        {
            "findingDetails": "The sts:AssumeRole action is invalid with the following principal(s): cognito-identity.amazonaws.com. Use a SAML provider principal with the sts:AssumeRoleWithSAML action or use an OIDC provider principal with the sts:AssumeRoleWithWebIdentity action. Ensure the provider is Federated if you use either of the two options.",
            "findingType": "ERROR",
            "issueCode": "MISMATCHED_ACTION_FOR_PRINCIPAL",
            "learnMoreLink": "https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-reference-policy-checks.html#access-analyzer-reference-policy-checks-error-mismatched-action-for-principal",
            "locations": [
                {
                    "path": [
                        {
                            "value": "Statement"
                        },
                        {
                            "index": 0
                        },
                        {
                            "value": "Action"
                        },
                        {
                            "index": 0
                        }
                    ],
                    "span": {
                        "end": {
                            "column": 32,
                            "line": 11,
                            "offset": 274
                        },
                        "start": {
                            "column": 16,
                            "line": 11,
                            "offset": 258
                        }
                    }
                },
                {
                    "path": [
                        {
                            "value": "Statement"
                        },
                        {
                            "index": 0
                        },
                        {
                            "value": "Principal"
                        },
                        {
                            "value": "Federated"
                        }
                    ],
                    "span": {
                        "end": {
                            "column": 61,
                            "line": 8,
                            "offset": 202
                        },
                        "start": {
                            "column": 29,
                            "line": 8,
                            "offset": 170
                        }
                    }
                }
            ]
        },
        {
            "findingDetails": "The following actions: sts:TagSession are not supported by the condition key cognito-identity.amazonaws.com:aud. The condition will not be evaluated for these actions. We recommend that you move these actions to a different statement without this condition key.",
            "findingType": "ERROR",
            "issueCode": "UNSUPPORTED_ACTION_FOR_CONDITION_KEY",
            "learnMoreLink": "https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-reference-policy-checks.html#access-analyzer-reference-policy-checks-error-unsupported-action-for-condition-key",
            "locations": [
                {
                    "path": [
                        {
                            "value": "Statement"
                        },
                        {
                            "index": 0
                        },
                        {
                            "value": "Action"
                        },
                        {
                            "index": 1
                        }
                    ],
                    "span": {
                        "end": {
                            "column": 32,
                            "line": 12,
                            "offset": 308
                        },
                        "start": {
                            "column": 16,
                            "line": 12,
                            "offset": 292
                        }
                    }
                },
                {
                    "path": [
                        {
                            "value": "Statement"
                        },
                        {
                            "index": 0
                        },
                        {
                            "value": "Condition"
                        },
                        {
                            "value": "StringEquals"
                        },
                        {
                            "value": "cognito-identity.amazonaws.com:aud"
                        }
                    ],
                    "span": {
                        "end": {
                            "column": 79,
                            "line": 16,
                            "offset": 464
                        },
                        "start": {
                            "column": 58,
                            "line": 16,
                            "offset": 443
                        }
                    }
                }
            ]
        }
    ]
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[ポリシーを検証する際の確認事項](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-checks-validating-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ValidatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/accessanalyzer/validate-policy.html)」を参照してください。

# を使用した Image Builder の例 AWS CLI
<a name="cli_2_imagebuilder_code_examples"></a>

次のコード例は、Image Builder AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-component`
<a name="imagebuilder_CreateComponent_cli_2_topic"></a>

次のコード例は、`create-component` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントを作成しするには**  
次の `create-component` の例では、JSON ドキュメントファイルを使用するコンポーネントを作成し、Amazon S3 バケットにアップロードされる YAML 形式のコンポーネントドキュメントを参照します。  

```
aws imagebuilder create-component \
    --cli-input-json file://create-component.json
```
`create-component.json` の内容:  

```
{
    "name": "MyExampleComponent",
    "semanticVersion": "2019.12.02",
    "description": "An example component that builds, validates and tests an image",
    "changeDescription": "Initial version.",
    "platform": "Windows",
    "uri": "s3://s3-bucket-name/s3-bucket-path/component.yaml"
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "componentBuildVersionArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/examplecomponent/2019.12.02/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateComponent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/create-component.html)」を参照してください。

### `create-distribution-configuration`
<a name="imagebuilder_CreateDistributionConfiguration_cli_2_topic"></a>

次のコード例は、`create-distribution-configuration` を使用する方法を示しています。

**AWS CLI**  
**ディストリビューション設定を作成するには**  
次の `create-distribution-configuration` の例では、JSON ファイルを使用してディストリビューション設定を作成します。  

```
aws imagebuilder create-distribution-configuration \
    --cli-input-json file:/create-distribution-configuration.json
```
`create-distribution-configuration.json` の内容:  

```
{
    "name": "MyExampleDistribution",
    "description": "Copies AMI to eu-west-1",
    "distributions": [
        {
            "region": "us-west-2",
            "amiDistributionConfiguration": {
                "name": "Name {{imagebuilder:buildDate}}",
                "description": "An example image name with parameter references",
                "amiTags": {
                    "KeyName": "{{ssm:parameter_name}}"
                },
                "launchPermission": {
                    "userIds": [
                        "123456789012"
                    ]
                }
            }
        },
        {
            "region": "eu-west-1",
            "amiDistributionConfiguration": {
                "name": "My {{imagebuilder:buildVersion}} image {{imagebuilder:buildDate}}",
                "amiTags": {
                    "KeyName": "Value"
                },
                "launchPermission": {
                    "userIds": [
                        "123456789012"
                    ]
                }
            }
        }
    ]
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "distributionConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDistributionConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/create-distribution-configuration.html)」を参照してください。

### `create-image-pipeline`
<a name="imagebuilder_CreateImagePipeline_cli_2_topic"></a>

次のコード例は、`create-image-pipeline` を使用する方法を示しています。

**AWS CLI**  
**イメージパイプラインを作成するには**  
次の `create-image-pipeline` の例では、JSON ファイルを使用してイメージパイプラインを作成します。  

```
aws imagebuilder create-image-pipeline \
    --cli-input-json file://create-image-pipeline.json
```
`create-image-pipeline.json` の内容:  

```
{
    "name": "MyWindows2016Pipeline",
    "description": "Builds Windows 2016 Images",
    "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03",
    "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
    "distributionConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution",
    "imageTestsConfiguration": {
        "imageTestsEnabled": true,
        "timeoutMinutes": 60
    },
    "schedule": {
        "scheduleExpression": "cron(0 0 * * SUN)",
        "pipelineExecutionStartCondition": "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"
    },
    "status": "ENABLED"
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "imagePipelineArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateImagePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/create-image-pipeline.html)」を参照してください。

### `create-image-recipe`
<a name="imagebuilder_CreateImageRecipe_cli_2_topic"></a>

次のコード例は、`create-image-recipe` を使用する方法を示しています。

**AWS CLI**  
**レシピを作成するには**  
次の `create-image-recipe` の例では、JSON ファイルを使用してイメージレシピを作成します。コンポーネントは、指定された順序でインストールされます。  

```
aws imagebuilder create-image-recipe \
    --cli-input-json file://create-image-recipe.json
```
`create-image-recipe.json` の内容:  

```
{
    "name": "MyBasicRecipe",
    "description": "This example image recipe creates a Windows 2016 image.",
    "semanticVersion": "2019.12.03",
    "components":
    [
        {
            "componentArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/myexamplecomponent/2019.12.02/1"
        },
        {
            "componentArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/myimportedcomponent/1.0.0/1"
        }
    ],
    "parentImage": "arn:aws:imagebuilder:us-west-2:aws:image/windows-server-2016-english-full-base-x86/xxxx.x.x"
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateImageRecipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/create-image-recipe.html)」を参照してください。

### `create-image`
<a name="imagebuilder_CreateImage_cli_2_topic"></a>

次のコード例は、`create-image` を使用する方法を示しています。

**AWS CLI**  
**イメージを作成するには**  
次の `create-image` の例ではイメージを作成します。  

```
aws imagebuilder create-image \
    --image-recipe-arn arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03 \
    --infrastructure-configuration-arn arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "imageBuildVersionArn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/create-image.html)」を参照してください。

### `create-infrastructure-configuration`
<a name="imagebuilder_CreateInfrastructureConfiguration_cli_2_topic"></a>

次のコード例は、`create-infrastructure-configuration` を使用する方法を示しています。

**AWS CLI**  
**インフラストラクチャ設定を作成するには**  
次の `create-infrastructure-configuration` の例では、JSON ファイルを使用してインフラストラクチャ設定を作成します。  

```
aws imagebuilder create-infrastructure-configuration \
    --cli-input-json file://create-infrastructure-configuration.json
```
`create-infrastructure-configuration.json` の内容:  

```
{
    "name": "MyExampleInfrastructure",
    "description": "An example that will retain instances of failed builds",
    "instanceTypes": [
        "m5.large", "m5.xlarge"
    ],
    "instanceProfileName": "EC2InstanceProfileForImageBuilder",
    "securityGroupIds": [
        "sg-a1b2c3d4"
    ],
    "subnetId": "subnet-a1b2c3d4",
    "logging": {
        "s3Logs": {
            "s3BucketName": "bucket-name",
            "s3KeyPrefix": "bucket-path"
        }
    },
    "keyPair": "key-pair-name",
    "terminateInstanceOnFailure": false,
    "snsTopicArn": "arn:aws:sns:us-west-2:123456789012:sns-topic-name"
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInfrastructureConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/create-infrastructure-configuration.html)」を参照してください。

### `delete-component`
<a name="imagebuilder_DeleteComponent_cli_2_topic"></a>

次のコード例は、`delete-component` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントを削除するには**  
次の `delete-component` の例は、ARN を指定してコンポーネントのビルドバージョンを削除します。  

```
aws imagebuilder delete-component \
    --component-build-version-arn arn:aws:imagebuilder:us-west-2:123456789012:component/myexamplecomponent/2019.12.02/1
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "componentBuildVersionArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/myexamplecomponent/2019.12.02/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteComponent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/delete-component.html)」を参照してください。

### `delete-image-pipeline`
<a name="imagebuilder_DeleteImagePipeline_cli_2_topic"></a>

次のコード例は、`delete-image-pipeline` を使用する方法を示しています。

**AWS CLI**  
**イメージパイプラインを削除するには**  
次の `delete-image-pipeline` の例では、ARN を指定してイメージパイプラインを削除します。  

```
aws imagebuilder delete-image-pipeline \
    --image-pipeline-arn arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/my-example-pipeline
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imagePipelineArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteImagePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/delete-image-pipeline.html)」を参照してください。

### `delete-image-recipe`
<a name="imagebuilder_DeleteImageRecipe_cli_2_topic"></a>

次のコード例は、`delete-image-recipe` を使用する方法を示しています。

**AWS CLI**  
**イメージレシピを削除するには**  
次の `delete-image-recipe` の例では、ARN を指定してイメージレシピを削除します。  

```
aws imagebuilder delete-image-recipe \
    --image-recipe-arn arn:aws:imagebuilder:us-east-1:123456789012:image-recipe/mybasicrecipe/2019.12.03
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteImageRecipe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/delete-image-recipe.html)」を参照してください。

### `delete-image`
<a name="imagebuilder_DeleteImage_cli_2_topic"></a>

次のコード例は、`delete-image` を使用する方法を示しています。

**AWS CLI**  
**イメージを削除するには**  
次の `delete-image` の例は、ARN を指定してイメージのビルドバージョンを削除します。  

```
aws imagebuilder delete-image \
    --image-build-version-arn arn:aws:imagebuilder:us-west-2:123456789012:image/my-example-image/2019.12.02/1
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imageBuildVersionArn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/delete-image.html)」を参照してください。

### `delete-infrastructure-configuration`
<a name="imagebuilder_DeleteInfrastructureConfiguration_cli_2_topic"></a>

次のコード例は、`delete-infrastructure-configuration` を使用する方法を示しています。

**AWS CLI**  
**インフラストラクチャ設定を削除するには**  
次の `delete-infrastructure-configuration` の例では、ARN を指定してイメージパイプラインを削除します。  

```
aws imagebuilder delete-infrastructure-configuration \
    --infrastructure-configuration-arn arn:aws:imagebuilder:us-east-1:123456789012:infrastructure-configuration/myexampleinfrastructure
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInfrastructureConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/delete-infrastructure-configuration.html)」を参照してください。

### `get-component-policy`
<a name="imagebuilder_GetComponentPolicy_cli_2_topic"></a>

次のコード例は、`get-component-policy` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントポリシーの詳細を取得するには**  
次の `get-component-policy` の例では、ARN を指定してコンポーネントポリシーの詳細を一覧表示します。  

```
aws imagebuilder get-component-policy \
    --component-arn arn:aws:imagebuilder:us-west-2:123456789012:component/my-example-component/2019.12.03/1
```
出力:  

```
{
    "Policy": "{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "123456789012" ] }, "Action": [ "imagebuilder:GetComponent", "imagebuilder:ListComponents" ], "Resource": [ "arn:aws:imagebuilder:us-west-2:123456789012:component/my-example-component/2019.12.03/1" ] } ] }"
}
```
詳細については、EC2 Image Builder ユーザーガイド」の「CLI <https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html>`\$1\$1 AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComponentPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-component-policy.html)」を参照してください。

### `get-component`
<a name="imagebuilder_GetComponent_cli_2_topic"></a>

次のコード例は、`get-component` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントの詳細を取得するには**  
次の `get-component` の例では、ARN を指定してコンポーネントの詳細を一覧表示します。  

```
aws imagebuilder get-component \
    --component-build-version-arn arn:aws:imagebuilder:us-west-2:123456789012:component/component-name/1.0.0/1
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "component": {
        "arn": "arn:aws:imagebuilder:us-west-2:123456789012:component/component-name/1.0.0/1",
        "name": "component-name",
        "version": "1.0.0",
        "type": "TEST",
        "platform": "Linux",
        "owner": "123456789012",
        "data": "name: HelloWorldTestingDocument\ndescription: This is hello world testing document.\nschemaVersion: 1.0\n\nphases:\n  - name: test\n    steps:\n      - name: HelloWorldStep\n        action: ExecuteBash\n        inputs:\n          commands:\n            - echo \"Hello World! Test.\"\n",
        "encrypted": true,
        "dateCreated": "2020-01-27T20:43:30.306Z",
        "tags": {}
    }
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComponent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-component.html)」を参照してください。

### `get-distribution-configuration`
<a name="imagebuilder_GetDistributionConfiguration_cli_2_topic"></a>

次のコード例は、`get-distribution-configuration` を使用する方法を示しています。

**AWS CLI**  
**ディストリビューション設定の詳細を取得するには**  
次の `get-distribution-configuration` の例では、ARN を指定してディストリビューション設定の詳細を表示します。  

```
aws imagebuilder get-distribution-configuration \
    --distribution-configuration-arn arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "distributionConfiguration": {
        "arn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution",
        "name": "MyExampleDistribution",
        "description": "Copies AMI to eu-west-1 and exports to S3",
        "distributions": [
            {
                "region": "us-west-2",
                "amiDistributionConfiguration": {
                    "name": "Name {{imagebuilder:buildDate}}",
                    "description": "An example image name with parameter references",
                    "amiTags": {
                        "KeyName": "{{ssm:parameter_name}}"
                    },
                    "launchPermission": {
                        "userIds": [
                            "123456789012"
                        ]
                    }
                }
            },
            {
                "region": "eu-west-1",
                "amiDistributionConfiguration": {
                    "name": "My {{imagebuilder:buildVersion}} image {{imagebuilder:buildDate}}",
                    "amiTags": {
                        "KeyName": "Value"
                    },
                    "launchPermission": {
                        "userIds": [
                            "123456789012"
                        ]
                    }
                }
            }
        ],
        "dateCreated": "2020-02-19T18:40:10.529Z",
        "tags": {}
    }
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDistributionConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-distribution-configuration.html)」を参照してください。

### `get-image-pipeline`
<a name="imagebuilder_GetImagePipeline_cli_2_topic"></a>

次のコード例は、`get-image-pipeline` を使用する方法を示しています。

**AWS CLI**  
**イメージパイプラインの詳細を取得するには**  
次の `get-image-pipeline` の例では、ARN を指定してイメージパイプラインの詳細を一覧表示します。  

```
aws imagebuilder get-image-pipeline \
    --image-pipeline-arn arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imagePipeline": {
        "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline",
        "name": "MyWindows2016Pipeline",
        "description": "Builds Windows 2016 Images",
        "platform": "Windows",
        "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03",
        "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
        "distributionConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution",
        "imageTestsConfiguration": {
            "imageTestsEnabled": true,
            "timeoutMinutes": 60
        },
        "schedule": {
            "scheduleExpression": "cron(0 0 * * SUN)",
            "pipelineExecutionStartCondition": "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"
        },
        "status": "ENABLED",
        "dateCreated": "2020-02-19T19:04:01.253Z",
        "dateUpdated": "2020-02-19T19:04:01.253Z",
        "tags": {}
    }
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImagePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-image-pipeline.html)」を参照してください。

### `get-image-policy`
<a name="imagebuilder_GetImagePolicy_cli_2_topic"></a>

次のコード例は、`get-image-policy` を使用する方法を示しています。

**AWS CLI**  
**イメージポリシーの詳細を取得するには**  
次の `get-image-policy` の例では、ARN を指定してイメージポリシーの詳細を一覧表示します。  

```
aws imagebuilder get-image-policy \
    --image-arn arn:aws:imagebuilder:us-west-2:123456789012:image/my-example-image/2019.12.03/1
```
出力:  

```
{
    "Policy": "{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "123456789012" ] }, "Action": [ "imagebuilder:GetImage", "imagebuilder:ListImages" ], "Resource": [ "arn:aws:imagebuilder:us-west-2:123456789012:image/my-example-image/2019.12.03/1" ] } ] }"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImagePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-image-policy.html)」を参照してください。

### `get-image-recipe-policy`
<a name="imagebuilder_GetImageRecipePolicy_cli_2_topic"></a>

次のコード例は、`get-image-recipe-policy` を使用する方法を示しています。

**AWS CLI**  
**イメージレシピポリシーの詳細を取得するには**  
次の `get-image-recipe-policy` の例では、ARN を指定してイメージレシピポリシーの詳細を一覧表示します。  

```
aws imagebuilder get-image-recipe-policy \
    --image-recipe-arn arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/my-example-image-recipe/2019.12.03/1
```
出力:  

```
{
    "Policy": "{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "123456789012" ] }, "Action": [ "imagebuilder:GetImageRecipe", "imagebuilder:ListImageRecipes" ], "Resource": [ "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/my-example-image-recipe/2019.12.03/1" ] } ] }"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImageRecipePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-image-recipe-policy.html)」を参照してください。

### `get-image`
<a name="imagebuilder_GetImage_cli_2_topic"></a>

次のコード例は、`get-image` を使用する方法を示しています。

**AWS CLI**  
**イメージの詳細を取得するには**  
次の `get-image` の例では、ARN を指定してイメージの詳細を一覧表示します。  

```
aws imagebuilder get-image \
    --image-build-version-arn arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/1
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "image": {
        "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/1",
        "name": "MyBasicRecipe",
        "version": "2019.12.03/1",
        "platform": "Windows",
        "state": {
            "status": "BUILDING"
        },
        "imageRecipe": {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03",
            "name": "MyBasicRecipe",
            "description": "This example image recipe creates a Windows 2016 image.",
            "platform": "Windows",
            "version": "2019.12.03",
            "components": [
                {
                    "componentArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/myexamplecomponent/2019.12.02/1"
                },
                {
                    "componentArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/myimportedcomponent/1.0.0/1"
                }
            ],
            "parentImage": "arn:aws:imagebuilder:us-west-2:aws:image/windows-server-2016-english-full-base-x86/2019.12.17/1",
            "dateCreated": "2020-02-14T19:46:16.904Z",
            "tags": {}
        },
        "infrastructureConfiguration": {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
            "name": "MyExampleInfrastructure",
            "description": "An example that will retain instances of failed builds",
            "instanceTypes": [
                "m5.large",
                "m5.xlarge"
            ],
            "instanceProfileName": "EC2InstanceProfileForImageFactory",
            "securityGroupIds": [
                "sg-a1b2c3d4"
            ],
            "subnetId": "subnet-a1b2c3d4",
            "logging": {
                "s3Logs": {
                    "s3BucketName": "bucket-name",
                    "s3KeyPrefix": "bucket-path"
                }
            },
            "keyPair": "Sam",
            "terminateInstanceOnFailure": false,
            "snsTopicArn": "arn:aws:sns:us-west-2:123456789012:sns-name",
            "dateCreated": "2020-02-14T21:21:05.098Z",
            "tags": {}
        },
        "imageTestsConfiguration": {
            "imageTestsEnabled": true,
            "timeoutMinutes": 720
        },
        "dateCreated": "2020-02-14T23:14:13.597Z",
        "outputResources": {
            "amis": []
        },
        "tags": {}
    }
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-image.html)」を参照してください。

### `get-infrastructure-configuration`
<a name="imagebuilder_GetInfrastructureConfiguration_cli_2_topic"></a>

次のコード例は、`get-infrastructure-configuration` を使用する方法を示しています。

**AWS CLI**  
**インフラストラクチャ設定の詳細を取得するには**  
次の `get-infrastructure-configuration` の例では、ARN を指定してインフラストラクチャ設定の詳細を一覧表示します。  

```
aws imagebuilder get-infrastructure-configuration \
    --infrastructure-configuration-arn arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "infrastructureConfiguration": {
        "arn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
        "name": "MyExampleInfrastructure",
        "description": "An example that will retain instances of failed builds",
        "instanceTypes": [
            "m5.large",
            "m5.xlarge"
        ],
        "instanceProfileName": "EC2InstanceProfileForImageBuilder",
        "securityGroupIds": [
            "sg-a48c95ef"
        ],
        "subnetId": "subnet-a48c95ef",
        "logging": {
            "s3Logs": {
                "s3BucketName": "bucket-name",
                "s3KeyPrefix": "bucket-path"
            }
        },
        "keyPair": "Name",
        "terminateInstanceOnFailure": false,
        "snsTopicArn": "arn:aws:sns:us-west-2:123456789012:sns-name",
        "dateCreated": "2020-02-19T19:11:51.858Z",
        "tags": {}
    }
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInfrastructureConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/get-infrastructure-configuration.html)」を参照してください。

### `import-component`
<a name="imagebuilder_ImportComponent_cli_2_topic"></a>

次のコード例は、`import-component` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントをインポートするには**  
次の `import-component` の例では、JSON ファイルを使用して既存のスクリプトをインポートします。  

```
aws imagebuilder import-component \
    --cli-input-json file://import-component.json
```
`import-component.json` の内容:  

```
{
    "name": "MyImportedComponent",
    "semanticVersion": "1.0.0",
    "description": "An example of how to import a component",
    "changeDescription": "First commit message.",
    "format": "SHELL",
    "platform": "Windows",
    "type": "BUILD",
    "uri": "s3://s3-bucket-name/s3-bucket-path/component.yaml"
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "componentBuildVersionArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/myimportedcomponent/1.0.0/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportComponent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/import-component.html)」を参照してください。

### `list-component-build-versions`
<a name="imagebuilder_ListComponentBuildVersions_cli_2_topic"></a>

次のコード例は、`list-component-build-versions` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントのビルドバージョンを一覧表示するには**  
次の `list-component-build-versions` の例では、特定のセマンティックバージョンを持つコンポーネントビルドバージョンを一覧表示します。  

```
aws imagebuilder list-component-build-versions --component-version-arn arn:aws:imagebuilder:us-west-2:123456789012:component/myexamplecomponent/2019.12.02
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "componentSummaryList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:component/myexamplecomponent/2019.12.02/1",
            "name": "MyExampleComponent",
            "version": "2019.12.02",
            "platform": "Windows",
            "type": "BUILD",
            "owner": "123456789012",
            "description": "An example component that builds, validates and tests an image",
            "changeDescription": "Initial version.",
            "dateCreated": "2020-02-19T18:53:45.940Z",
            "tags": {
                "KeyName": "KeyValue"
            }
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListComponentBuildVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-component-build-versions.html)」を参照してください。

### `list-components`
<a name="imagebuilder_ListComponents_cli_2_topic"></a>

次のコード例は、`list-components` を使用する方法を示しています。

**AWS CLI**  
**すべてのコンポーネントセマンティックバージョンを一覧表示するには**  
次の `list-components` の例では、アクセスできるすべてのコンポーネントセマンティックバージョンを一覧表示します。必要に応じて、自分が所有するコンポーネント、Amazon が所有するコンポーネント、または他のアカウントによって共有されているコンポーネントを一覧表示するかどうかをフィルタリングできます。  

```
aws imagebuilder list-components
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "componentVersionList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:component/component-name/1.0.0",
            "name": "component-name",
            "version": "1.0.0",
            "platform": "Linux",
            "type": "TEST",
            "owner": "123456789012",
            "dateCreated": "2020-01-27T20:43:30.306Z"
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListComponents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-components.html)」を参照してください。

### `list-distribution-configurations`
<a name="imagebuilder_ListDistributionConfigurations_cli_2_topic"></a>

次のコード例は、`list-distribution-configurations` を使用する方法を示しています。

**AWS CLI**  
**ディストリビューションの一覧表示するには**  
次の `list-distribution-configurations` の例では、すべてのディストリビューションバケットを一覧表示します。  

```
aws imagebuilder list-distribution-configurations
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "distributionConfigurationSummaryList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution",
            "name": "MyExampleDistribution",
            "description": "Copies AMI to eu-west-1 and exports to S3",
            "dateCreated": "2020-02-19T18:40:10.529Z",
            "tags": {
                "KeyName": "KeyValue"
            }
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDistributionConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-distribution-configurations.html)」を参照してください。

### `list-image-build-versions`
<a name="imagebuilder_ListImageBuildVersions_cli_2_topic"></a>

次のコード例は、`list-image-build-versions` を使用する方法を示しています。

**AWS CLI**  
**イメージビルドバージョンを一覧表示するには**  
次の `list-image-build-versions` の例では、セマンティックバージョンを持つすべてのイメージビルドバージョンを一覧表示します。  

```
aws imagebuilder list-image-build-versions \
    --image-version-arn arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imageSummaryList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/7",
            "name": "MyBasicRecipe",
            "version": "2019.12.03/7",
            "platform": "Windows",
            "state": {
                "status": "FAILED",
                "reason": "Can't start SSM Automation for arn arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/7 during building. Parameter \"iamInstanceProfileName\" has a null value."
            },
            "owner": "123456789012",
            "dateCreated": "2020-02-19T18:56:11.511Z",
            "outputResources": {
                "amis": []
            },
            "tags": {}
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/6",
            "name": "MyBasicRecipe",
            "version": "2019.12.03/6",
            "platform": "Windows",
            "state": {
                "status": "FAILED",
                "reason": "An internal error has occurred."
            },
            "owner": "123456789012",
            "dateCreated": "2020-02-18T22:49:08.142Z",
            "outputResources": {
                "amis": [
                    {
                        "region": "us-west-2",
                        "image": "ami-a1b2c3d4567890ab",
                        "name": "MyBasicRecipe 2020-02-18T22-49-38.704Z",
                        "description": "This example image recipe creates a Windows 2016 image."
                    },
                    {
                        "region": "us-west-2",
                        "image": "ami-a1b2c3d4567890ab",
                        "name": "Name 2020-02-18T22-49-08.131Z",
                        "description": "Copies AMI to eu-west-2 and exports to S3"
                    },
                    {
                        "region": "eu-west-2",
                        "image": "ami-a1b2c3d4567890ab",
                        "name": "My 6 image 2020-02-18T22-49-08.131Z",
                        "description": "Copies AMI to eu-west-2 and exports to S3"
                    }
                ]
            },
            "tags": {}
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/5",
            "name": "MyBasicRecipe",
            "version": "2019.12.03/5",
            "platform": "Windows",
            "state": {
                "status": "AVAILABLE"
            },
            "owner": "123456789012",
            "dateCreated": "2020-02-18T16:51:48.403Z",
            "outputResources": {
                "amis": [
                    {
                        "region": "us-west-2",
                        "image": "ami-a1b2c3d4567890ab",
                        "name": "MyBasicRecipe 2020-02-18T16-52-18.965Z",
                        "description": "This example image recipe creates a Windows 2016 image."
                    }
                ]
            },
            "tags": {}
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/4",
            "name": "MyBasicRecipe",
            "version": "2019.12.03/4",
            "platform": "Windows",
            "state": {
                "status": "AVAILABLE"
            },
            "owner": "123456789012",
            "dateCreated": "2020-02-18T16:50:01.827Z",
            "outputResources": {
                "amis": [
                    {
                        "region": "us-west-2",
                        "image": "ami-a1b2c3d4567890ab",
                        "name": "MyBasicRecipe 2020-02-18T16-50-32.280Z",
                        "description": "This example image recipe creates a Windows 2016 image."
                    }
                ]
            },
            "tags": {}
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/3",
            "name": "MyBasicRecipe",
            "version": "2019.12.03/3",
            "platform": "Windows",
            "state": {
                "status": "AVAILABLE"
            },
            "owner": "123456789012",
            "dateCreated": "2020-02-14T23:14:13.597Z",
            "outputResources": {
                "amis": [
                    {
                        "region": "us-west-2",
                        "image": "ami-a1b2c3d4567890ab",
                        "name": "MyBasicRecipe 2020-02-14T23-14-44.243Z",
                        "description": "This example image recipe creates a Windows 2016 image."
                    }
                ]
            },
            "tags": {}
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/2",
            "name": "MyBasicRecipe",
            "version": "2019.12.03/2",
            "platform": "Windows",
            "state": {
                "status": "FAILED",
                "reason": "SSM execution 'a1b2c3d4-5678-90ab-cdef-EXAMPLE11111' failed with status = 'Failed' and failure message = 'Step fails when it is verifying the command has completed. Command a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 returns unexpected invocation result: \n{Status=[Failed], ResponseCode=[1], Output=[\n----------ERROR-------\nfailed to run commands: exit status 1], OutputPayload=[{\"Status\":\"Failed\",\"ResponseCode\":1,\"Output\":\"\\n----------ERROR-------\\nfailed to run commands: exit status 1\",\"CommandId\":\"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111\"}], CommandId=[a1b2c3d4-5678-90ab-cdef-EXAMPLE11111]}. Please refer to Automation Service Troubleshooting Guide for more diagnosis details.'"
            },
            "owner": "123456789012",
            "dateCreated": "2020-02-14T22:57:42.593Z",
            "outputResources": {
                "amis": []
            },
            "tags": {}
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListImageBuildVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-image-build-versions.html)」を参照してください。

### `list-image-pipeline-images`
<a name="imagebuilder_ListImagePipelineImages_cli_2_topic"></a>

次のコード例は、`list-image-pipeline-images` を使用する方法を示しています。

**AWS CLI**  
**イメージパイプラインのパイプラインイメージを一覧表示するには**  
次の `list-image-pipeline-images` の例では、特定のイメージパイプラインによって作成されたすべてのイメージを一覧表示します。  

```
aws imagebuilder list-image-pipeline-images \
    --image-pipeline-arn arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imagePipelineList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline",
            "name": "MyWindows2016Pipeline",
            "description": "Builds Windows 2016 Images",
            "platform": "Windows",
            "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03",
            "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
            "distributionConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution",
            "imageTestsConfiguration": {
                "imageTestsEnabled": true,
                "timeoutMinutes": 60
            },
            "schedule": {
                "scheduleExpression": "cron(0 0 * * SUN)",
                "pipelineExecutionStartCondition": "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"
            },
            "status": "ENABLED",
            "dateCreated": "2020-02-19T19:04:01.253Z",
            "dateUpdated": "2020-02-19T19:04:01.253Z",
            "tags": {
                "KeyName": "KeyValue"
            }
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/sam",
            "name": "PipelineName",
            "platform": "Linux",
            "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/recipe-name-a1b2c3d45678/1.0.0",
            "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/infrastructureconfiguration-name-a1b2c3d45678",
            "imageTestsConfiguration": {
                "imageTestsEnabled": true,
                "timeoutMinutes": 720
            },
            "status": "ENABLED",
            "dateCreated": "2019-12-16T18:19:02.068Z",
            "dateUpdated": "2019-12-16T18:19:02.068Z",
            "tags": {
                "KeyName": "KeyValue"
            }
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListImagePipelineImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-image-pipeline-images.html)」を参照してください。

### `list-image-recipes`
<a name="imagebuilder_ListImageRecipes_cli_2_topic"></a>

次のコード例は、`list-image-recipes` を使用する方法を示しています。

**AWS CLI**  
**イメージレシピを一覧表示するには**  
以下の `list-image-recipes` 例では、すべてのイメージレシピを一覧表示します。  

```
aws imagebuilder list-image-recipes
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imageRecipeSummaryList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03",
            "name": "MyBasicRecipe",
            "platform": "Windows",
            "owner": "123456789012",
            "parentImage": "arn:aws:imagebuilder:us-west-2:aws:image/windows-server-2016-english-full-base-x86/2019.x.x",
            "dateCreated": "2020-02-19T18:54:25.975Z",
            "tags": {
                "KeyName": "KeyValue"
            }
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/recipe-name-a1b2c3d45678/1.0.0",
            "name": "recipe-name-a1b2c3d45678",
            "platform": "Linux",
            "owner": "123456789012",
            "parentImage": "arn:aws:imagebuilder:us-west-2:aws:image/amazon-linux-2-x86/2019.11.21",
            "dateCreated": "2019-12-16T18:19:00.120Z",
            "tags": {
                "KeyName": "KeyValue"
            }
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListImageRecipes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-image-recipes.html)」を参照してください。

### `list-images`
<a name="imagebuilder_ListImages_cli_2_topic"></a>

次のコード例は、`list-images` を使用する方法を示しています。

**AWS CLI**  
**イメージを一覧表示するには**  
次の `list-images` の例では、アクセスできるすべてのセマンティックバージョンを一覧表示します。  

```
aws imagebuilder list-images
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imageVersionList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03",
            "name": "MyBasicRecipe",
            "version": "2019.12.03",
            "platform": "Windows",
            "owner": "123456789012",
            "dateCreated": "2020-02-14T21:29:18.810Z"
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListImages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-images.html)」を参照してください。**

### `list-infrastructure-configurations`
<a name="imagebuilder_ListInfrastructureConfigurations_cli_2_topic"></a>

次のコード例は、`list-infrastructure-configurations` を使用する方法を示しています。

**AWS CLI**  
**インフラストラクチャ設定を一覧表示するには**  
次の `list-infrastructure-configurations` の例では、すべてのインフラストラクチャ設定を一覧表示します。  

```
aws imagebuilder list-infrastructure-configurations
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "infrastructureConfigurationSummaryList": [
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
            "name": "MyExampleInfrastructure",
            "description": "An example that will retain instances of failed builds",
            "dateCreated": "2020-02-19T19:11:51.858Z",
            "tags": {}
        },
        {
            "arn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/infrastructureconfiguration-name-a1b2c3d45678",
            "name": "infrastructureConfiguration-name-a1b2c3d45678",
            "dateCreated": "2019-12-16T18:19:01.038Z",
            "tags": {
                "KeyName": "KeyValue"
            }
        }
    ]
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInfrastructureConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-infrastructure-configurations.html)」を参照してください。

### `list-tags-for-resource`
<a name="imagebuilder_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**特定のリソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、特定のリソースのタグを一覧表示します。  

```
aws imagebuilder list-tags-for-resource \
    --resource-arn arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline
```
出力:  

```
{
    "tags": {
        "KeyName": "KeyValue"
    }
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/list-tags-for-resource.html)」を参照してください。

### `put-component-policy`
<a name="imagebuilder_PutComponentPolicy_cli_2_topic"></a>

次のコード例は、`put-component-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースポリシーをコンポーネントに適用するには**  
次の `put-component-policy` のコマンドは、ビルドコンポーネントにリソースポリシーを適用して、ビルドコンポーネントのクロスアカウント共有を有効にします。RAM CLI コマンド `create-resource-share` を使用することをお勧めします。EC2 Image Builder CLI コマンド `put-component-policy` を使用する場合は、リソースを共有するすべてのプリンシパルにリソースを表示するため、RAM CLI コマンド `promote-resource-share-create-from-policy` も使用する必要があります。  

```
aws imagebuilder put-component-policy \
    --component-arn arn:aws:imagebuilder:us-west-2:123456789012:component/examplecomponent/2019.12.02/1 \
    --policy '{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "123456789012" ] }, "Action": [ "imagebuilder:GetComponent", "imagebuilder:ListComponents" ], "Resource": [ "arn:aws:imagebuilder:us-west-2:123456789012:component/examplecomponent/2019.12.02/1" ] } ] }'
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "componentArn": "arn:aws:imagebuilder:us-west-2:123456789012:component/examplecomponent/2019.12.02/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutComponentPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/put-component-policy.html)」を参照してください。

### `put-image-policy`
<a name="imagebuilder_PutImagePolicy_cli_2_topic"></a>

次のコード例は、`put-image-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースポリシーをイメージに適用するには**  
次の `put-image-policy` のコマンドは、イメージにリソースポリシーを適用して、イメージのクロスアカウント共有を有効にします。RAM CLI コマンド create-resource-share を使用することをお勧めします。EC2 Image Builder CLI コマンド put-image-policy を使用する場合、リソースが共有されているすべてのプリンシパルにリソースを表示するには、RAM CLI コマンド promote-resource-share-create-from-policy も使用する必要があります。  

```
aws imagebuilder put-image-policy \
    --image-arn arn:aws:imagebuilder:us-west-2:123456789012:image/example-image/2019.12.02/1 \
    --policy '{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "123456789012" ] }, "Action": [ "imagebuilder:GetImage", "imagebuilder:ListImages" ], "Resource": [ "arn:aws:imagebuilder:us-west-2:123456789012:image/example-image/2019.12.02/1" ] } ] }'
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imageArn": "arn:aws:imagebuilder:us-west-2:123456789012:image/example-image/2019.12.02/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutImagePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/put-image-policy.html)」を参照してください。

### `put-image-recipe-policy`
<a name="imagebuilder_PutImageRecipePolicy_cli_2_topic"></a>

次のコード例は、`put-image-recipe-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースポリシーをイメージレシピに適用するには**  
次の `put-image-recipe-policy` のコマンドは、イメージレシピにリソースポリシーを適用して、イメージレシピのクロスアカウント共有を有効にします。RAM CLI コマンド `create-resource-share` を使用することをお勧めします。EC2 Image Builder CLI コマンド `put-image-recipe-policy` を使用する場合は、リソースを共有するすべてのプリンシパルにリソースを表示するため、RAM CLI コマンド `promote-resource-share-create-from-policy` も使用する必要があります。  

```
aws imagebuilder put-image-recipe-policy \
    --image-recipe-arn arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/example-image-recipe/2019.12.02 \
    --policy '{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Principal": { "AWS": [ "123456789012" ] }, "Action": [ "imagebuilder:GetImageRecipe", "imagebuilder:ListImageRecipes" ], "Resource": [ "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/example-image-recipe/2019.12.02" ] } ] }'
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/example-image-recipe/2019.12.02/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutImageRecipePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/put-image-recipe-policy.html)」を参照してください。

### `start-image-pipeline-execution`
<a name="imagebuilder_StartImagePipelineExecution_cli_2_topic"></a>

次のコード例は、`start-image-pipeline-execution` を使用する方法を示しています。

**AWS CLI**  
**イメージパイプラインを手動で開始するには**  
次の `start-image-pipeline-execution` の例では、イメージパイプラインを手動で開始します。  

```
aws imagebuilder start-image-pipeline-execution \
    --image-pipeline-arn arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "clientToken": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "imageBuildVersionArn": "arn:aws:imagebuilder:us-west-2:123456789012:image/mybasicrecipe/2019.12.03/1"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartImagePipelineExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/start-image-pipeline-execution.html)」を参照してください。

### `tag-resource`
<a name="imagebuilder_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の `tag-resource` の例では、JSON ファイルを使用して EC2 Image Builder にリソースを追加およびタグ付けします。  

```
aws imagebuilder tag-resource \
    --cli-input-json file://tag-resource.json
```
`tag-resource.json` の内容:  

```
{
    "resourceArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline",
    "tags": {
        "KeyName: "KeyValue"
    }
}
```
このコマンドでは何も出力されません。  
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="imagebuilder_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `untag-resource` の例では、JSON ファイルを使用してリソースからタグを削除します。  

```
aws imagebuilder untag-resource \
    --cli-input-json file://tag-resource.json
```
`untag-resource.json` の内容:  

```
{
    "resourceArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline",
    "tagKeys": [
        "KeyName"
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/untag-resource.html)」を参照してください。

### `update-distribution-configuration`
<a name="imagebuilder_UpdateDistributionConfiguration_cli_2_topic"></a>

次のコード例は、`update-distribution-configuration` を使用する方法を示しています。

**AWS CLI**  
**ディストリビューション設定を更新するには**  
次の `update-distribution-configuration` の例では、JSON ファイルを使用してディストリビューション設定を更新します。  

```
aws imagebuilder update-distribution-configuration \
    --cli-input-json file://update-distribution-configuration.json
```
`update-distribution-configuration.json` の内容:  

```
{
    "distributionConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution",
    "description": "Copies AMI to eu-west-2 and exports to S3",
    "distributions": [
        {
            "region": "us-west-2",
            "amiDistributionConfiguration": {
                "name": "Name {{imagebuilder:buildDate}}",
                "description": "An example image name with parameter references"
            }
        },
        {
            "region": "eu-west-2",
            "amiDistributionConfiguration": {
                "name": "My {{imagebuilder:buildVersion}} image {{imagebuilder:buildDate}}"
            }
        }
    ]
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDistributionConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/update-distribution-configuration.html)」を参照してください。

### `update-image-pipeline`
<a name="imagebuilder_UpdateImagePipeline_cli_2_topic"></a>

次のコード例は、`update-image-pipeline` を使用する方法を示しています。

**AWS CLI**  
**イメージパイプラインを更新するには**  
次の `update-image-pipeline` の例では、JSON ファイルを使用してイメージパイプラインを更新します。  

```
aws imagebuilder update-image-pipeline \
    --cli-input-json file://update-image-pipeline.json
```
`update-image-pipeline.json` の内容:  

```
{
    "imagePipelineArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-pipeline/mywindows2016pipeline",
    "imageRecipeArn": "arn:aws:imagebuilder:us-west-2:123456789012:image-recipe/mybasicrecipe/2019.12.03",
    "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
    "distributionConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:distribution-configuration/myexampledistribution",
    "imageTestsConfiguration": {
        "imageTestsEnabled": true,
        "timeoutMinutes": 120
    },
    "schedule": {
        "scheduleExpression": "cron(0 0 * * MON)",
        "pipelineExecutionStartCondition": "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"
    },
    "status": "DISABLED"
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateImagePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/update-image-pipeline.html)」を参照してください。

### `update-infrastructure-configuration`
<a name="imagebuilder_UpdateInfrastructureConfiguration_cli_2_topic"></a>

次のコード例は、`update-infrastructure-configuration` を使用する方法を示しています。

**AWS CLI**  
**インフラストラクチャ設定を更新するには**  
次の `update-infrastructure-configuration` 例では、JSON ファイルを使用してインフラストラクチャ設定を更新します。  

```
aws imagebuilder update-infrastructure-configuration \
    --cli-input-json file:/update-infrastructure-configuration.json
```
`update-infrastructure-configuration.json` の内容:  

```
{
    "infrastructureConfigurationArn": "arn:aws:imagebuilder:us-west-2:123456789012:infrastructure-configuration/myexampleinfrastructure",
    "description": "An example that will terminate instances of failed builds",
    "instanceTypes": [
        "m5.large", "m5.2xlarge"
    ],
    "instanceProfileName": "EC2InstanceProfileForImageFactory",
    "securityGroupIds": [
        "sg-a48c95ef"
    ],
    "subnetId": "subnet-a48c95ef",
    "logging": {
        "s3Logs": {
            "s3BucketName": "bucket-name",
            "s3KeyPrefix": "bucket-path"
        }
    },
    "terminateInstanceOnFailure": true,
    "snsTopicArn": "arn:aws:sns:us-west-2:123456789012:sns-name"
}
```
出力:  

```
{
    "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、[EC2 Image Builder ユーザーガイド」の「CLI AWS を使用した EC2 Image Builder イメージパイプラインのセットアップと管理](https://docs.aws.amazon.com/imagebuilder/latest/userguide/managing-image-builder-cli.html)」を参照してください。 *EC2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateInfrastructureConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/imagebuilder/update-infrastructure-configuration.html)」を参照してください。

# を使用した Incident Manager の例 AWS CLI
<a name="cli_2_ssm-incidents_code_examples"></a>

次のコード例は、Incident Manager AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-replication-set`
<a name="ssm-incidents_CreateReplicationSet_cli_2_topic"></a>

次のコード例は、`create-replication-set` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションセットを作成するには**  
次の `create-replication-set` の例では、Incident Manager が Amazon Web Services アカウントのデータをレプリケートおよび暗号化するために使用するレプリケーションセットを作成します。この例では、レプリケーションセットの作成時に us-east-1 リージョンと us-east-2 リージョンを使用します。  

```
aws ssm-incidents create-replication-set \
    --regions '{"us-east-1": {"sseKmsKeyId": "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"}, "us-east-2": {"sseKmsKeyId": "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"}}'
```
出力:  

```
{
    "replicationSetArns": [
        "arn:aws:ssm-incidents::111122223333:replication-set/c4bcb603-4bf9-bb3f-413c-08df53673b57"
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[Incident Manager レプリケーションセットの使用](https://docs.aws.amazon.com/incident-manager/latest/userguide/replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateReplicationSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/create-replication-set.html)」を参照してください。

### `create-response-plan`
<a name="ssm-incidents_CreateResponsePlan_cli_2_topic"></a>

次のコード例は、`create-response-plan` を使用する方法を示しています。

**AWS CLI**  
**対応計画を作成するには**  
次の `create-response-plan` の例では、指定された詳細情報を含む対応計画を作成します。  

```
aws ssm-incidents create-response-plan \
    --chat-channel '{"chatbotSns": ["arn:aws:sns:us-east-1:111122223333:Standard_User"]}' \
    --display-name "Example response plan" \
    --incident-template '{"impact": 5, "title": "example-incident"}' \
    --name "example-response" \
    --actions '[{"ssmAutomation": {"documentName": "AWSIncidents-CriticalIncidentRunbookTemplate", "documentVersion": "$DEFAULT", "roleArn": "arn:aws:iam::111122223333:role/aws-service-role/ssm-incidents.amazonaws.com/AWSServiceRoleForIncidentManager", "targetAccount": "RESPONSE_PLAN_OWNER_ACCOUNT"}}]' \
    --engagements '["arn:aws:ssm-contacts:us-east-1:111122223333:contact/example"]'
```
出力:  

```
{
    "arn": "arn:aws:ssm-incidents::111122223333:response-plan/example-response"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの準備](https://docs.aws.amazon.com/incident-manager/latest/userguide/incident-response.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResponsePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/create-response-plan.html)」を参照してください。

### `create-timeline-event`
<a name="ssm-incidents_CreateTimelineEvent_cli_2_topic"></a>

次のコード例は、`create-timeline-event` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムタイムラインイベントを作成するには**  
次の `create-timeline-event` の例では、指定されたインシデントの指定された時間にカスタムタイムラインイベントを作成します。  

```
aws ssm-incidents create-timeline-event \
    --event-data "\"example timeline event\"" \
    --event-time 2022-10-01T20:30:00.000 \
    --event-type "Custom Event" \
    --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4EXAMPLE"
```
出力:  

```
{
    "eventId": "c0bcc885-a41d-eb01-b4ab-9d2deEXAMPLE",
    "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4EXAMPLE"
}
```
**例 2: インシデントノートを使用してタイムラインイベントを作成するには**  
次の `create-timeline-event` の例では、「インシデントメモ」パネルに一覧表示されるタイムラインイベントを作成します。  

```
aws ssm-incidents create-timeline-event \
     --event-data "\"New Note\"" \
     --event-type "Note" \
     --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Test/6cc46130-ca6c-3b38-68f1-f6abeEXAMPLE" \
     --event-time 2023-06-20T12:06:00.000 \
     --event-references '[{"resource":"arn:aws:ssm-incidents::111122223333:incident-record/Test/6cc46130-ca6c-3b38-68f1-f6abeEXAMPLE"}]'
```
出力:  

```
{
    "eventId": "a41dc885-c0bc-b4ab-eb01-de9d2EXAMPLE",
    "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4EXAMPLE"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTimelineEvent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/create-timeline-event.html)」を参照してください。

### `delete-incident-record`
<a name="ssm-incidents_DeleteIncidentRecord_cli_2_topic"></a>

次のコード例は、`delete-incident-record` を使用する方法を示しています。

**AWS CLI**  
**インシデントレコードを削除するには**  
次の `delete-incident-record` の例では、指定されたインシデントレコードを削除します。  

```
aws ssm-incidents delete-incident-record \
    --arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの追跡](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteIncidentRecord](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/delete-incident-record.html)」を参照してください。

### `delete-replication-set`
<a name="ssm-incidents_DeleteReplicationSet_cli_2_topic"></a>

次のコード例は、`delete-replication-set` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションセットを削除するには**  
次の `delete-replication-set` の例では、Amazon Web Services アカウントからレプリケーションセットを削除します。レプリケーションセットを削除すると、Incident Manager のデータもすべて削除されます。これは元に戻すことができません。  

```
aws ssm-incidents delete-replication-set \
    --arn "arn:aws:ssm-incidents::111122223333:replication-set/c4bcb603-4bf9-bb3f-413c-08df53673b57"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[Incident Manager レプリケーションセットの使用](https://docs.aws.amazon.com/incident-manager/latest/userguide/replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteReplicationSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/delete-replication-set.html)」を参照してください。

### `delete-resource-policy`
<a name="ssm-incidents_DeleteResourcePolicy_cli_2_topic"></a>

次のコード例は、`delete-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースポリシーを削除するには**  
次の `delete-resource-policy` の例では、対応計画からリソースポリシーを削除します。これにより、対応計画を共有していたプリンシパルまたは組織からのアクセスが取り消されます。  

```
aws ssm-incidents delete-resource-policy \
    --policy-id "be8b57191f0371f1c6827341aa3f0a03" \
    --resource-arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[共有連絡先と対応計画の操作](https://docs.aws.amazon.com/incident-manager/latest/userguide/sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/delete-resource-policy.html)」を参照してください。

### `delete-response-plan`
<a name="ssm-incidents_DeleteResponsePlan_cli_2_topic"></a>

次のコード例は、`delete-response-plan` を使用する方法を示しています。

**AWS CLI**  
**対応計画を削除するには**  
次の `delete-response-plan` の例では、指定された対応計画を削除します。  

```
aws ssm-incidents delete-response-plan \
    --arn "arn:aws:ssm-incidents::111122223333:response-plan/example-response"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの準備](https://docs.aws.amazon.com/incident-manager/latest/userguide/incident-response.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResponsePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/delete-response-plan.html)」を参照してください。

### `delete-timeline-event`
<a name="ssm-incidents_DeleteTimelineEvent_cli_2_topic"></a>

次のコード例は、`delete-timeline-event` を使用する方法を示しています。

**AWS CLI**  
**タイムラインイベントを削除するには**  
次の `delete-timeline-event` の例では、指定されたインシデントレコードからカスタムタイムラインイベントを削除します。  

```
aws ssm-incidents delete-timeline-event \
    --event-id "c0bcc885-a41d-eb01-b4ab-9d2de193643c" \
    --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTimelineEvent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/delete-timeline-event.html)」を参照してください。

### `get-incident-record`
<a name="ssm-incidents_GetIncidentRecord_cli_2_topic"></a>

次のコード例は、`get-incident-record` を使用する方法を示しています。

**AWS CLI**  
**インシデントレコードを取得するには**  
次の `get-incident-record` の例では、指定されたインシデントレコードの詳細情報を取得します。  

```
aws ssm-incidents get-incident-record \
    --arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
```
出力:  

```
{
    "incidentRecord": {
        "arn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308",
        "automationExecutions": [],
        "creationTime": "2021-05-21T18:16:57.579000+00:00",
        "dedupeString": "c4bcc812-85e7-938d-2b78-17181176ee1a",
        "impact": 5,
        "incidentRecordSource": {
            "createdBy": "arn:aws:iam::111122223333:user/draliatp",
            "invokedBy": "arn:aws:iam::111122223333:user/draliatp",
            "source": "aws.ssm-incidents.custom"
        },
        "lastModifiedBy": "arn:aws:iam::111122223333:user/draliatp",
        "lastModifiedTime": "2021-05-21T18:16:59.149000+00:00",
        "notificationTargets": [],
        "status": "OPEN",
        "title": "Example-Incident"
    }
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIncidentRecord](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/get-incident-record.html)」を参照してください。

### `get-replication-set`
<a name="ssm-incidents_GetReplicationSet_cli_2_topic"></a>

次のコード例は、`get-replication-set` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションセットを取得するには**  
次の `get-replication-set` の例では、Incident Manager が Amazon Web Services アカウントのデータをレプリケートおよび暗号化するために使用するレプリケーションセットの詳細情報を取得します。  

```
aws ssm-incidents get-replication-set \
    --arn "arn:aws:ssm-incidents::111122223333:replication-set/c4bcb603-4bf9-bb3f-413c-08df53673b57"
```
出力:  

```
{
    "replicationSet": {
        "createdBy": "arn:aws:sts::111122223333:assumed-role/Admin/username",
        "createdTime": "2021-05-14T17:57:22.010000+00:00",
        "deletionProtected": false,
        "lastModifiedBy": "arn:aws:sts::111122223333:assumed-role/Admin/username",
        "lastModifiedTime": "2021-05-14T17:57:22.010000+00:00",
        "regionMap": {
            "us-east-1": {
                "sseKmsKeyId": "DefaultKey",
                "status": "ACTIVE"
            },
            "us-east-2": {
                "sseKmsKeyId": "DefaultKey",
                "status": "ACTIVE",
                "statusMessage": "Tagging inaccessible"
            }
        },
        "status": "ACTIVE"
    }
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[Incident Manager レプリケーションセットの使用](https://docs.aws.amazon.com/incident-manager/latest/userguide/replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReplicationSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/get-replication-set.html)」を参照してください。

### `get-resource-policies`
<a name="ssm-incidents_GetResourcePolicies_cli_2_topic"></a>

次のコード例は、`get-resource-policies` を使用する方法を示しています。

**AWS CLI**  
**対応計画のリソースポリシーを一覧表示するには**  
次の `command-name` の例では、指定された対応計画に関連付けられたリソースポリシーを一覧表示します。  

```
aws ssm-incidents get-resource-policies \
--resource-arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan"
```
出力:  

```
{
    "resourcePolicies": [
        {
            "policyDocument": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"d901b37a-dbb0-458a-8842-75575c464219-external-principals\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::222233334444:root\"},\"Action\":[\"ssm-incidents:GetResponsePlan\",\"ssm-incidents:StartIncident\",\"ssm-incidents:UpdateIncidentRecord\",\"ssm-incidents:GetIncidentRecord\",\"ssm-incidents:CreateTimelineEvent\",\"ssm-incidents:UpdateTimelineEvent\",\"ssm-incidents:GetTimelineEvent\",\"ssm-incidents:ListTimelineEvents\",\"ssm-incidents:UpdateRelatedItems\",\"ssm-incidents:ListRelatedItems\"],\"Resource\":[\"arn:aws:ssm-incidents:*:111122223333:response-plan/Example-Response-Plan\",\"arn:aws:ssm-incidents:*:111122223333:incident-record/Example-Response-Plan/*\"]}]}",
            "policyId": "be8b57191f0371f1c6827341aa3f0a03",
            "ramResourceShareRegion": "us-east-1"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[共有連絡先と対応計画の操作](https://docs.aws.amazon.com/incident-manager/latest/userguide/sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourcePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/get-resource-policies.html)」を参照してください。

### `get-response-plan`
<a name="ssm-incidents_GetResponsePlan_cli_2_topic"></a>

次のコード例は、`get-response-plan` を使用する方法を示しています。

**AWS CLI**  
**対応計画の詳細を取得するには**  
次の の`command-name`例では、 AWS アカウントの指定された対応計画に関する詳細を取得します。  

```
aws ssm-incidents get-response-plan \
    --arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan"
```
出力:  

```
{
    "actions": [
        {
            "ssmAutomation": {
                "documentName": "AWSIncidents-CriticalIncidentRunbookTemplate",
                "documentVersion": "$DEFAULT",
                "roleArn": "arn:aws:iam::111122223333:role/aws-service-role/ssm-incidents.amazonaws.com/AWSServiceRoleForIncidentManager",
                "targetAccount": "RESPONSE_PLAN_OWNER_ACCOUNT"
            }
        }
    ],
    "arn": "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan",
    "chatChannel": {
        "chatbotSns": [
            "arn:aws:sns:us-east-1:111122223333:Standard_User"
        ]
    },
    "displayName": "Example response plan",
    "engagements": [
        "arn:aws:ssm-contacts:us-east-1:111122223333:contact/example"
    ],
    "incidentTemplate": {
        "impact": 5,
        "title": "Example-Incident"
    },
    "name": "Example-Response-Plan"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの準備](https://docs.aws.amazon.com/incident-manager/latest/userguide/incident-response.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResponsePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/get-response-plan.html)」を参照してください。

### `get-timeline-event`
<a name="ssm-incidents_GetTimelineEvent_cli_2_topic"></a>

次のコード例は、`get-timeline-event` を使用する方法を示しています。

**AWS CLI**  
**タイムラインイベントの詳細を取得するには**  
次の `get-timeline-event` の例は、指定されたタイムラインイベントの詳細情報を返します。  

```
aws ssm-incidents get-timeline-event \
    --event-id 20bcc812-8a94-4cd7-520c-0ff742111424 \
    --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
```
出力:  

```
{
    "event": {
        "eventData": "\"Incident Started\"",
        "eventId": "20bcc812-8a94-4cd7-520c-0ff742111424",
        "eventTime": "2021-05-21T18:16:57+00:00",
        "eventType": "Custom Event",
        "eventUpdatedTime": "2021-05-21T18:16:59.944000+00:00",
        "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
    }
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTimelineEvent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/get-timeline-event.html)」を参照してください。

### `list-incident-records`
<a name="ssm-incidents_ListIncidentRecords_cli_2_topic"></a>

次のコード例は、`list-incident-records` を使用する方法を示しています。

**AWS CLI**  
**インシデントレコードを一覧表示するには**  
次の `command-name` の例では、Amazon Web Services アカウントのインシデントレコードを一覧表示します。  

```
aws ssm-incidents list-incident-records
```
出力:  

```
{
    "incidentRecordSummaries": [
        {
            "arn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308",
            "creationTime": "2021-05-21T18:16:57.579000+00:00",
            "impact": 5,
            "incidentRecordSource": {
                "createdBy": "arn:aws:iam::111122223333:user/draliatp",
                "invokedBy": "arn:aws:iam::111122223333:user/draliatp",
                "source": "aws.ssm-incidents.custom"
            },
            "status": "OPEN",
            "title": "Example-Incident"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントリスト](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-list.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListIncidentRecords](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/list-incident-records.html)」を参照してください。

### `list-related-items`
<a name="ssm-incidents_ListRelatedItems_cli_2_topic"></a>

次のコード例は、`list-related-items` を使用する方法を示しています。

**AWS CLI**  
**関連項目を一覧表示するには**  
次の `list-related-items` の例では、指定されたインシデントの関連項目を一覧表示します。  

```
aws ssm-incidents list-related-items \
    --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
```
出力:  

```
{
    "relatedItems": [
        {
            "identifier": {
                "type": "OTHER",
                "value": {
                    "url": "https://console.aws.amazon.com/systems-manager/opsitems/oi-8ef82158e190/workbench?region=us-east-1"
                }
            },
            "title": "Example related item"
        },
        {
            "identifier": {
                "type": "PARENT",
                "value": {
                    "arn": "arn:aws:ssm:us-east-1:111122223333:opsitem/oi-8084126392ac"
                }
            },
            "title": "parentItem"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRelatedItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/list-related-items.html)」を参照してください。

### `list-replication-sets`
<a name="ssm-incidents_ListReplicationSets_cli_2_topic"></a>

次のコード例は、`list-replication-sets` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションセットを一覧表示するには**  
次の の`list-replication-set`例では、Incident Manager が AWS アカウントのデータをレプリケートおよび暗号化するために使用するレプリケーションセットを一覧表示します。  

```
aws ssm-incidents list-replication-sets
```
出力:  

```
{
    "replicationSetArns": [
        "arn:aws:ssm-incidents::111122223333:replication-set/c4bcb603-4bf9-bb3f-413c-08df53673b57"
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[Incident Manager レプリケーションセットの使用](https://docs.aws.amazon.com/incident-manager/latest/userguide/replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListReplicationSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/list-replication-sets.html)」を参照してください。

### `list-response-plans`
<a name="ssm-incidents_ListResponsePlans_cli_2_topic"></a>

次のコード例は、`list-response-plans` を使用する方法を示しています。

**AWS CLI**  
**使用可能な対応計画を一覧表示するには**  
次の `list-response-plans` 例では、Amazon Web Services アカウントで使用可能な対応計画を一覧表示します。  

```
aws ssm-incidents list-response-plans
```
出力:  

```
{
    "responsePlanSummaries": [
        {
            "arn": "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan",
            "displayName": "Example response plan",
            "name": "Example-Response-Plan"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの準備](https://docs.aws.amazon.com/incident-manager/latest/userguide/incident-response.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResponsePlans](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/list-response-plans.html)」を参照してください。

### `list-tags-for-resource`
<a name="ssm-incidents_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**対応計画のタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された対応計画に関連付けられたタグを一覧表示します。  

```
aws ssm-incidents list-tags-for-resource \
    --resource-arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan"
```
出力:  

```
{
    "tags": {
    "group1": "1"
    }
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[タグ付け](https://docs.aws.amazon.com/incident-manager/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/list-tags-for-resource.html)」を参照してください。

### `list-timeline-events`
<a name="ssm-incidents_ListTimelineEvents_cli_2_topic"></a>

次のコード例は、`list-timeline-events` を使用する方法を示しています。

**AWS CLI**  
**インシデントのタイムラインイベントを一覧表示するには**  
次の `command-name` の例では、指定されたインシデントのタイムラインイベントを一覧表示します。  

```
aws ssm-incidents list-timeline-events \
    --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
```
出力:  

```
{
    "eventSummaries": [
        {
            "eventId": "8cbcc889-35e1-a42d-2429-d6f100799915",
            "eventTime": "2021-05-21T22:36:13.766000+00:00",
            "eventType": "SSM Incident Record Update",
            "eventUpdatedTime": "2021-05-21T22:36:13.766000+00:00",
            "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
        },
        {
            "eventId": "a2bcc825-aab5-1787-c605-f9bb2640d85b",
            "eventTime": "2021-05-21T18:58:46.443000+00:00",
            "eventType": "SSM Incident Record Update",
            "eventUpdatedTime": "2021-05-21T18:58:46.443000+00:00",
            "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
        },
        {
            "eventId": "5abcc812-89c0-b0a8-9437-1c74223d4685",
            "eventTime": "2021-05-21T18:16:59.149000+00:00",
            "eventType": "SSM Incident Record Update",
            "eventUpdatedTime": "2021-05-21T18:16:59.149000+00:00",
            "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
        },
        {
            "eventId": "06bcc812-8820-405e-4065-8d2b14d29b92",
            "eventTime": "2021-05-21T18:16:58+00:00",
            "eventType": "SSM Automation Execution Start Failure for Incident",
            "eventUpdatedTime": "2021-05-21T18:16:58.689000+00:00",
            "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
        },
        {
            "eventId": "20bcc812-8a94-4cd7-520c-0ff742111424",
            "eventTime": "2021-05-21T18:16:57+00:00",
            "eventType": "Custom Event",
            "eventUpdatedTime": "2021-05-21T18:16:59.944000+00:00",
            "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
        },
        {
            "eventId": "c0bcc885-a41d-eb01-b4ab-9d2de193643c",
            "eventTime": "2020-10-01T20:30:00+00:00",
            "eventType": "Custom Event",
            "eventUpdatedTime": "2021-05-21T22:28:26.299000+00:00",
            "incidentRecordArn": "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTimelineEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/list-timeline-events.html)」を参照してください。

### `put-resource-policy`
<a name="ssm-incidents_PutResourcePolicy_cli_2_topic"></a>

次のコード例は、`put-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**対応計画とインシデントを共有するには**  
次の `command-name` の例では、指定されたプリンシパルと対応計画および関連付けられたインシデントを共有するリソースポリシーを Example-Response-Plan に追加します。  

```
aws ssm-incidents put-resource-policy \
    --resource-arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan" \
    --policy "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"ExampleResourcePolciy\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::222233334444:root\"},\"Action\":[\"ssm-incidents:GetResponsePlan\",\"ssm-incidents:StartIncident\",\"ssm-incidents:UpdateIncidentRecord\",\"ssm-incidents:GetIncidentRecord\",\"ssm-incidents:CreateTimelineEvent\",\"ssm-incidents:UpdateTimelineEvent\",\"ssm-incidents:GetTimelineEvent\",\"ssm-incidents:ListTimelineEvents\",\"ssm-incidents:UpdateRelatedItems\",\"ssm-incidents:ListRelatedItems\"],\"Resource\":[\"arn:aws:ssm-incidents:*:111122223333:response-plan/Example-Response-Plan\",\"arn:aws:ssm-incidents:*:111122223333:incident-record/Example-Response-Plan/*\"]}]}"
```
出力:  

```
{
    "policyId": "be8b57191f0371f1c6827341aa3f0a03"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[共有連絡先と対応計画の操作](https://docs.aws.amazon.com/incident-manager/latest/userguide/sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/put-resource-policy.html)」を参照してください。

### `start-incident`
<a name="ssm-incidents_StartIncident_cli_2_topic"></a>

次のコード例は、`start-incident` を使用する方法を示しています。

**AWS CLI**  
**インシデントを開始するには**  
次の `start-incident` の例では、指定された対応計画を使用してインシデントを開始します。  

```
aws ssm-incidents start-incident \
    --response-plan-arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan"
```
出力:  

```
{
    "incidentRecordArn": "arn:aws:ssm-incidents::682428703967:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの作成](https://docs.aws.amazon.com/incident-manager/latest/userguide/incident-creation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartIncident](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/start-incident.html)」を参照してください。

### `tag-resource`
<a name="ssm-incidents_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**対応計画にタグを付けるには**  
次の `tag-resource` の例では、指定された対応計画に指定されたタグキーと値のペアをタグ付けします。  

```
aws ssm-incidents tag-resource \
    --resource-arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan" \
    --tags '{"group1":"1"}'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[タグ付け](https://docs.aws.amazon.com/incident-manager/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ssm-incidents_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**対応計画からタグを削除するには**  
次の `untag-resource` の例では、指定されたタグを対応計画から削除します。  

```
aws ssm-incidents untag-resource \
    --resource-arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan" \
    --tag-keys '["group1"]'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[タグ付け](https://docs.aws.amazon.com/incident-manager/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/untag-resource.html)」を参照してください。

### `update-deletion-protection`
<a name="ssm-incidents_UpdateDeletionProtection_cli_2_topic"></a>

次のコード例は、`update-deletion-protection` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションセットの削除保護を更新するには**  
次の `update-deletion-protection` の例では、レプリケーションセット内の最後のリージョンを削除しないように、アカウントの削除保護を更新します。  

```
aws ssm-incidents update-deletion-protection \
    --arn "arn:aws:ssm-incidents::111122223333:replication-set/a2bcc5c9-0f53-8047-7fef-c20749989b40" \
    --deletion-protected
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[Incident Manager レプリケーションセットの使用](https://docs.aws.amazon.com/incident-manager/latest/userguide/replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDeletionProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/update-deletion-protection.html)」を参照してください。

### `update-incident-record`
<a name="ssm-incidents_UpdateIncidentRecord_cli_2_topic"></a>

次のコード例は、`update-incident-record` を使用する方法を示しています。

**AWS CLI**  
**インシデントレコードを更新するには**  
次の `command-name` の例では、指定されたインシデントを解決します。  

```
aws ssm-incidents update-incident-record \
    --arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308" \
    --status "RESOLVED"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIncidentRecord](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/update-incident-record.html)」を参照してください。

### `update-related-items`
<a name="ssm-incidents_UpdateRelatedItems_cli_2_topic"></a>

次のコード例は、`update-related-items` を使用する方法を示しています。

**AWS CLI**  
**インシデント関連項目を更新するには**  
次の `update-related-item` の例では、指定されたインシデントレコードから関連項目を削除します。  

```
aws ssm-incidents update-related-items \
    --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308" \
    --related-items-update '{"itemToRemove": {"type": "OTHER", "value": {"url": "https://console.aws.amazon.com/systems-manager/opsitems/oi-8ef82158e190/workbench?region=us-east-1"}}}'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRelatedItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/update-related-items.html)」を参照してください。

### `update-replication-set`
<a name="ssm-incidents_UpdateReplicationSet_cli_2_topic"></a>

次のコード例は、`update-replication-set` を使用する方法を示しています。

**AWS CLI**  
**レプリケーションセットを更新するには**  
次の `command-name` の例では、us-east-2 リージョンをレプリケーションセットから削除します。  

```
aws ssm-incidents update-replication-set \
    --arn "arn:aws:ssm-incidents::111122223333:replication-set/a2bcc5c9-0f53-8047-7fef-c20749989b40" \
    --actions '[{"deleteRegionAction": {"regionName": "us-east-2"}}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[Incident Manager レプリケーションセットの使用](https://docs.aws.amazon.com/incident-manager/latest/userguide/replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateReplicationSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/update-replication-set.html)」を参照してください。

### `update-response-plan`
<a name="ssm-incidents_UpdateResponsePlan_cli_2_topic"></a>

次のコード例は、`update-response-plan` を使用する方法を示しています。

**AWS CLI**  
**対応計画を更新するには**  
次の `update-response-plan` の例では、指定された対応計画からチャットチャネルを削除します。  

```
aws ssm-incidents update-response-plan \
    --arn "arn:aws:ssm-incidents::111122223333:response-plan/Example-Response-Plan" \
    --chat-channel '{"empty":{}}'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの準備](https://docs.aws.amazon.com/incident-manager/latest/userguide/incident-response.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResponsePlan](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/update-response-plan.html)」を参照してください。

### `update-timeline-event`
<a name="ssm-incidents_UpdateTimelineEvent_cli_2_topic"></a>

次のコード例は、`update-timeline-event` を使用する方法を示しています。

**AWS CLI**  
**タイムラインイベントを更新するには**  
次の `update-timeline-event` の例では、イベントが発生した時刻を更新します。  

```
aws ssm-incidents update-timeline-event \
    --event-id 20bcc812-8a94-4cd7-520c-0ff742111424 \
    --incident-record-arn "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/6ebcc812-85f5-b7eb-8b2f-283e4d844308" \
    --event-time "2021-05-21T18:10:57+00:00"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[インシデントの詳細](https://docs.aws.amazon.com/incident-manager/latest/userguide/tracking-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTimelineEvent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-incidents/update-timeline-event.html)」を参照してください。

# を使用した Incident Manager Contacts の例 AWS CLI
<a name="cli_2_ssm-contacts_code_examples"></a>

次のコード例は、Incident Manager Contacts AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-page`
<a name="ssm-contacts_AcceptPage_cli_2_topic"></a>

次のコード例は、`accept-page` を使用する方法を示しています。

**AWS CLI**  
**エンゲージメント中にページを受け入れるには**  
次の `accept-page` の例では、連絡先チャネルに送信された承認コードを使用してページを受け入れます。  

```
aws ssm-contacts accept-page \
    --page-id "arn:aws:ssm-contacts:us-east-2:682428703967:page/akuam/94ea0c7b-56d9-46c3-b84a-a37c8b067ad3" \
    --accept-type READ \
    --accept-code 425440
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptPage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/accept-page.html)」を参照してください。

### `activate-contact-channel`
<a name="ssm-contacts_ActivateContactChannel_cli_2_topic"></a>

次のコード例は、`activate-contact-channel` を使用する方法を示しています。

**AWS CLI**  
**連絡先の連絡先チャネルを有効にする**  
次の `activate-contact-channel` の例では、連絡先チャネルを有効にして、インシデントの一部として使用できるようにします。  

```
aws ssm-contacts activate-contact-channel \
    --contact-channel-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d" \
    --activation-code "466136"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ActivateContactChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/activate-contact-channel.html)」を参照してください。

### `command-name`
<a name="ssm-contacts_CommandName_cli_2_topic"></a>

次のコード例は、`command-name` を使用する方法を示しています。

**AWS CLI**  
**連絡先を削除するには**  
次の `command-name` の例では、連絡先を削除します。連絡先を参照するエスカレーションプランから、連絡先にアクセスできなくなります。  

```
aws ssm-contacts delete-contact \
    --contact-id "arn:aws:ssm-contacts:us-east-1:682428703967:contact/alejr"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CommandName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/command-name.html)」を参照してください。

### `create-contact-channel`
<a name="ssm-contacts_CreateContactChannel_cli_2_topic"></a>

次のコード例は、`create-contact-channel` を使用する方法を示しています。

**AWS CLI**  
**連絡先チャネルを作成するには**  
連絡先 Akua Mansa の SMS タイプの連絡先チャネルを作成します。連絡先チャネルは、SMS、E メール、または音声のタイプで作成できます。  

```
aws ssm-contacts create-contact-channel \
    --contact-id "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam" \
    --name "akuas sms-test" \
    --type SMS \
    --delivery-address '{"SimpleAddress": "+15005550199"}'
```
出力:  

```
{
    "ContactChannelArn": "arn:aws:ssm-contacts:us-east-1:111122223333:contact-channel/akuam/02f506b9-ea5d-4764-af89-2daa793ff024"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateContactChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/create-contact-channel.html)」を参照してください。

### `create-contact`
<a name="ssm-contacts_CreateContact_cli_2_topic"></a>

次のコード例は、`create-contact` を使用する方法を示しています。

**AWS CLI**  
**連絡先を作成するには**  
次の `create-contact` の例では、空白のプランを使用して、環境内で連絡先を作成します。プランは、連絡先チャネルの作成後に更新できます。このコマンドの ARN を出力して create-contact-channel コマンドを使用します。この連絡先の連絡先チャネルを作成したら、update-contact を使用してプランを更新します。  

```
aws ssm-contacts create-contact \
    --alias "akuam" \
    --display-name "Akua Mansa" \
    --type PERSONAL \
    --plan '{"Stages": []}'
```
出力:  

```
{
    "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateContact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/create-contact.html)」を参照してください。

### `deactivate-contact-channel`
<a name="ssm-contacts_DeactivateContactChannel_cli_2_topic"></a>

次のコード例は、`deactivate-contact-channel` を使用する方法を示しています。

**AWS CLI**  
**連絡先チャネルを無効にするには**  
次の `deactivate-contact-channel` の例では、連絡先チャネルを無効にします。連絡先チャネルを無効にすると、インシデント中に連絡先チャネルがページングされなくなります。`activate-contact-channel` コマンドを使用して、必要に応じて連絡先チャネルを再度有効にすることもできます。  

```
aws ssm-contacts deactivate-contact-channel \
    --contact-channel-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeactivateContactChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/deactivate-contact-channel.html)」を参照してください。

### `delete-contact-channel`
<a name="ssm-contacts_DeleteContactChannel_cli_2_topic"></a>

次のコード例は、`delete-contact-channel` を使用する方法を示しています。

**AWS CLI**  
**連絡先チャネルを削除するには**  
次の `delete-contact-channel` の例では、連絡先チャネルを削除します。連絡先チャネルを削除すると、インシデント中に連絡先チャネルがページングされなくなります。  

```
aws ssm-contacts delete-contact-channel \
    --contact-channel-id "arn:aws:ssm-contacts:us-east-1:111122223333:contact-channel/akuam/13149bad-52ee-45ea-ae1e-45857f78f9b2"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteContactChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/delete-contact-channel.html)」を参照してください。

### `delete-contact`
<a name="ssm-contacts_DeleteContact_cli_2_topic"></a>

次のコード例は、`delete-contact` を使用する方法を示しています。

**AWS CLI**  
**連絡先を削除するには**  
次の `delete-contact` の例では、連絡先を削除します。連絡先を参照するエスカレーションプランから、連絡先にアクセスできなくなります。  

```
aws ssm-contacts delete-contact \
    --contact-id "arn:aws:ssm-contacts:us-east-1:111122223333:contact/alejr"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteContact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/delete-contact.html)」を参照してください。

### `describe-engagement`
<a name="ssm-contacts_DescribeEngagement_cli_2_topic"></a>

次のコード例は、`describe-engagement` を使用する方法を示しています。

**AWS CLI**  
**エンゲージメントの詳細を記述するには**  
次の `describe-engagement` の例では、連絡先またはエスカレーションプランへのエンゲージメントの詳細情報を一覧表示します。件名とコンテンツが連絡先チャネルに送信されます。  

```
aws ssm-contacts describe-engagement \
    --engagement-id "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/example_escalation/69e40ce1-8dbb-4d57-8962-5fbe7fc53356"
```
出力:  

```
{
    "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation",
    "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/example_escalation/69e40ce1-8dbb-4d57-8962-5fbe7fc53356",
    "Sender": "cli",
    "Subject": "cli-test",
    "Content": "Testing engagements via CLI",
    "PublicSubject": "cli-test",
    "PublicContent": "Testing engagements va CLI",
    "StartTime": "2021-05-18T18:25:41.151000+00:00"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEngagement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/describe-engagement.html)」を参照してください。

### `describe-page`
<a name="ssm-contacts_DescribePage_cli_2_topic"></a>

次のコード例は、`describe-page` を使用する方法を示しています。

**AWS CLI**  
**連絡先チャネルのページの詳細を一覧表示するには**  
次の `describe-page` の例では、連絡先チャネルのページの詳細情報を一覧表示します。このページには、提供された件名とコンテンツが含まれます。  

```
aws ssm-contacts describe-page \
    --page-id "arn:aws:ssm-contacts:us-east-2:111122223333:page/akuam/ad0052bd-e606-498a-861b-25726292eb93"
```
出力:  

```
{
    "PageArn": "arn:aws:ssm-contacts:us-east-2:111122223333:page/akuam/ad0052bd-e606-498a-861b-25726292eb93",
    "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/78a29753-3674-4ac5-9f83-0468563567f0",
    "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
    "Sender": "cli",
    "Subject": "cli-test",
    "Content": "Testing engagements via CLI",
    "PublicSubject": "cli-test",
    "PublicContent": "Testing engagements va CLI",
    "SentTime": "2021-05-18T18:43:29.301000+00:00",
    "ReadTime": "2021-05-18T18:43:55.708000+00:00",
    "DeliveryTime": "2021-05-18T18:43:55.265000+00:00"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/describe-page.html)」を参照してください。

### `get-contact-channel`
<a name="ssm-contacts_GetContactChannel_cli_2_topic"></a>

次のコード例は、`get-contact-channel` を使用する方法を示しています。

**AWS CLI**  
**連絡先チャネルの詳細を一覧表示するには**  
次の `get-contact-channel` の例では、連絡先チャネルの詳細情報を一覧表示します。  

```
aws ssm-contacts get-contact-channel \
    --contact-channel-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d"
```
出力:  

```
{
    "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
    "ContactChannelArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d",
    "Name": "akuas sms",
    "Type": "SMS",
    "DeliveryAddress": {
        "SimpleAddress": "+15005550199"
    },
    "ActivationStatus": "ACTIVATED"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContactChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/get-contact-channel.html)」を参照してください。

### `get-contact-policy`
<a name="ssm-contacts_GetContactPolicy_cli_2_topic"></a>

次のコード例は、`get-contact-policy` を使用する方法を示しています。

**AWS CLI**  
**連絡先のリソースポリシーを一覧表示するには**  
次の `get-contact-policy` の例では、指定された連絡先に関連付けられているリソースポリシーを一覧表示します。  

```
aws ssm-contacts get-contact-policy \
    --contact-arn "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam"
```
出力:  

```
{
    "ContactArn": "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam",
    "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"SharePolicyForDocumentationDralia\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"222233334444\"},\"Action\":[\"ssm-contacts:GetContact\",\"ssm-contacts:StartEngagement\",\"ssm-contacts:DescribeEngagement\",\"ssm-contacts:ListPagesByEngagement\",\"ssm-contacts:StopEngagement\"],\"Resource\":[\"arn:aws:ssm-contacts:*:111122223333:contact/akuam\",\"arn:aws:ssm-contacts:*:111122223333:engagement/akuam/*\"]}]}"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[共有連絡先と対応計画の操作](https://docs.aws.amazon.com/incident-manager/latest/userguide/sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContactPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/get-contact-policy.html)」を参照してください。

### `get-contact`
<a name="ssm-contacts_GetContact_cli_2_topic"></a>

次のコード例は、`get-contact` を使用する方法を示しています。

**AWS CLI**  
**例 1: 連絡先プランを記述するには**  
次の `get-contact` の例では、連絡先を記述します。  

```
aws ssm-contacts get-contact \
    --contact-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam"
```
出力:  

```
{
    "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
    "Alias": "akuam",
    "DisplayName": "Akua Mansa",
    "Type": "PERSONAL",
    "Plan": {
        "Stages": [
            {
                "DurationInMinutes": 5,
                "Targets": [
                    {
                        "ChannelTargetInfo": {
                            "ContactChannelId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/beb25840-5ac8-4644-95cc-7a8de390fa65",
                            "RetryIntervalInMinutes": 1
                        }
                    }
                ]
            },
            {
                "DurationInMinutes": 5,
                "Targets": [
                    {
                        "ChannelTargetInfo": {
                            "ContactChannelId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/49f3c24d-5f9f-4638-ae25-3f49e04229ad",
                            "RetryIntervalInMinutes": 1
                        }
                    }
                ]
            },
            {
                "DurationInMinutes": 5,
                "Targets": [
                    {
                        "ChannelTargetInfo": {
                            "ContactChannelId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/77d4f447-f619-4954-afff-85551e369c2a",
                            "RetryIntervalInMinutes": 1
                        }
                    }
                ]
            }
        ]
    }
}
```
**例 2: エスカレーションプランを記述するには**  
次の `get-contact` の例では、エスカレーションプランを記述します。  

```
aws ssm-contacts get-contact \
--contact-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation"
```
出力:  

```
{
    "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation",
    "Alias": "example_escalation",
    "DisplayName": "Example Escalation",
    "Type": "ESCALATION",
    "Plan": {
        "Stages": [
            {
                "DurationInMinutes": 5,
                "Targets": [
                    {
                        "ContactTargetInfo": {
                            "ContactId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
                            "IsEssential": true
                        }
                    }
                ]
            },
            {
                "DurationInMinutes": 5,
                "Targets": [
                    {
                        "ContactTargetInfo": {
                            "ContactId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/alejr",
                            "IsEssential": false
                        }
                    }
                ]
            },
            {
                "DurationInMinutes": 0,
                "Targets": [
                    {
                        "ContactTargetInfo": {
                            "ContactId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/anasi",
                            "IsEssential": false
                        }
                    }
                ]
            }
        ]
    }
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/get-contact.html)」を参照してください。

### `list-contact-channels`
<a name="ssm-contacts_ListContactChannels_cli_2_topic"></a>

次のコード例は、`list-contact-channels` を使用する方法を示しています。

**AWS CLI**  
**連絡先の連絡先チャネルを一覧表示するには**  
次の `list-contact-channels` の例では、指定された連絡先で使用可能な連絡先チャネルを一覧表示します。  

```
aws ssm-contacts list-contact-channels \
    --contact-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam"
```
出力:  

```
{
    [
        {
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Name": "akuas email",
            "Type": "EMAIL",
            "DeliveryAddress": {
                "SimpleAddress": "akuam@example.com"
            },
            "ActivationStatus": "NOT_ACTIVATED"
        },
        {
            "ContactChannelArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d",
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Name": "akuas sms",
            "Type": "SMS",
            "DeliveryAddress": {
                "SimpleAddress": "+15005550100"
            },
            "ActivationStatus": "ACTIVATED"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListContactChannels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/list-contact-channels.html)」を参照してください。

### `list-contacts`
<a name="ssm-contacts_ListContacts_cli_2_topic"></a>

次のコード例は、`list-contacts` を使用する方法を示しています。

**AWS CLI**  
**すべてのエスカレーションプランと連絡先を一覧表示するには**  
次の `list-contacts` の例では、アカウントの連絡先とエスカレーションプランを一覧表示します。  

```
aws ssm-contacts list-contacts
```
出力:  

```
{
    "Contacts": [
        {
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Alias": "akuam",
            "DisplayName": "Akua Mansa",
            "Type": "PERSONAL"
        },
        {
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/alejr",
            "Alias": "alejr",
            "DisplayName": "Alejandro Rosalez",
            "Type": "PERSONAL"
        },
        {
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/anasi",
            "Alias": "anasi",
            "DisplayName": "Ana Carolina Silva",
            "Type": "PERSONAL"
        },
        {
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation",
            "Alias": "example_escalation",
            "DisplayName": "Example Escalation",
            "Type": "ESCALATION"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListContacts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/list-contacts.html)」を参照してください。

### `list-engagements`
<a name="ssm-contacts_ListEngagements_cli_2_topic"></a>

次のコード例は、`list-engagements` を使用する方法を示しています。

**AWS CLI**  
**すべてのエンゲージメントを一覧表示するには**  
次の `list-engagements` の例では、エスカレーションプランと連絡先へのエンゲージメントを一覧表示します。1 つのインシデントのエンゲージメントを表示することもできます。  

```
aws ssm-contacts list-engagements
```
出力:  

```
{
    "Engagements": [
        {
            "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/91792571-0b53-4821-9f73-d25d13d9e529",
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Sender": "cli",
            "StartTime": "2021-05-18T20:37:50.300000+00:00"
        },
        {
            "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/78a29753-3674-4ac5-9f83-0468563567f0",
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Sender": "cli",
            "StartTime": "2021-05-18T18:40:26.666000+00:00"
        },
        {
            "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/example_escalation/69e40ce1-8dbb-4d57-8962-5fbe7fc53356",
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation",
            "Sender": "cli",
            "StartTime": "2021-05-18T18:25:41.151000+00:00"
        },
        {
            "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/607ced0e-e8fa-4ea7-8958-a237b8803f8f",
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Sender": "cli",
            "StartTime": "2021-05-18T18:20:58.093000+00:00"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEngagements](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/list-engagements.html)」を参照してください。

### `list-page-receipts`
<a name="ssm-contacts_ListPageReceipts_cli_2_topic"></a>

次のコード例は、`list-page-receipts` を使用する方法を示しています。

**AWS CLI**  
**ページ受信を一覧表示するには**  
次の `command-name` の例は、連絡先がページを受信したかどうかを一覧表示します。  

```
aws ssm-contacts list-page-receipts \
    --page-id "arn:aws:ssm-contacts:us-east-2:111122223333:page/akuam/94ea0c7b-56d9-46c3-b84a-a37c8b067ad3"
```
出力:  

```
{
    "Receipts": [
        {
            "ContactChannelArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d",
            "ReceiptType": "DELIVERED",
            "ReceiptInfo": "425440",
            "ReceiptTime": "2021-05-18T20:42:57.485000+00:00"
        },
        {
            "ContactChannelArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d",
            "ReceiptType": "READ",
            "ReceiptInfo": "425440",
            "ReceiptTime": "2021-05-18T20:42:57.907000+00:00"
        },
        {
            "ContactChannelArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/fc7405c4-46b2-48b7-87b2-93e2f225b90d",
            "ReceiptType": "SENT",
            "ReceiptInfo": "SM6656c19132f1465f9c9c1123a5dde7c9",
            "ReceiptTime": "2021-05-18T20:40:52.962000+00:00"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPageReceipts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/list-page-receipts.html)」を参照してください。

### `list-pages-by-contact`
<a name="ssm-contacts_ListPagesByContact_cli_2_topic"></a>

次のコード例は、`list-pages-by-contact` を使用する方法を示しています。

**AWS CLI**  
**連絡先別にページを一覧表示するには**  
次の `list-pages-by-contact` の例では、指定された連絡先へのすべてのページを一覧表示します。  

```
aws ssm-contacts list-pages-by-contact \
    --contact-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam"
```
出力:  

```
{
    "Pages": [
        {
            "PageArn": "arn:aws:ssm-contacts:us-east-2:111122223333:page/akuam/ad0052bd-e606-498a-861b-25726292eb93",
            "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/78a29753-3674-4ac5-9f83-0468563567f0",
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Sender": "cli",
            "SentTime": "2021-05-18T18:43:29.301000+00:00",
            "DeliveryTime": "2021-05-18T18:43:55.265000+00:00",
            "ReadTime": "2021-05-18T18:43:55.708000+00:00"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListPagesByContact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/list-pages-by-contact.html)」を参照してください。

### `list-pages-by-engagement`
<a name="ssm-contacts_ListPagesByEngagement_cli_2_topic"></a>

次のコード例は、`list-pages-by-engagement` を使用する方法を示しています。

**AWS CLI**  
**エンゲージメントから開始された連絡先チャネルのページを一覧表示するには**  
次の `list-pages-by-engagement` の例は、定義されたエンゲージメントプランのエンゲージ中に発生したページを一覧表示します。  

```
aws ssm-contacts list-pages-by-engagement \
    --engagement-id "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/78a29753-3674-4ac5-9f83-0468563567f0"
```
出力:  

```
{
    "Pages": [
        {
            "PageArn": "arn:aws:ssm-contacts:us-east-2:111122223333:page/akuam/ad0052bd-e606-498a-861b-25726292eb93",
            "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/78a29753-3674-4ac5-9f83-0468563567f0",
            "ContactArn": "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam",
            "Sender": "cli",
            "SentTime": "2021-05-18T18:40:27.245000+00:00"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPagesByEngagement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/list-pages-by-engagement.html)」を参照してください。

### `list-tags-for-resource`
<a name="ssm-contacts_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**連絡先のタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された連絡先のタグを一覧表示します。  

```
aws ssm-contacts list-tags-for-resource \
    --resource-arn "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam"
```
出力:  

```
{
    "Tags": [
        {
            "Key": "group1",
            "Value": "1"
        }
    ]
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[タグ付け](https://docs.aws.amazon.com/incident-manager/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/list-tags-for-resource.html)」を参照してください。

### `put-contact-policy`
<a name="ssm-contacts_PutContactPolicy_cli_2_topic"></a>

次のコード例は、`put-contact-policy` を使用する方法を示しています。

**AWS CLI**  
**連絡先とエンゲージメントを共有するには**  
次の `put-contact-policy` の例では、連絡先および関連するエンゲージメントをプリンシパルと共有するリソースポリシーを連絡先の Akua に追加します。  

```
aws ssm-contacts put-contact-policy \
    --contact-arn "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam" \
    --policy "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"ExampleResourcePolicy\",\"Action\":[\"ssm-contacts:GetContact\",\"ssm-contacts:StartEngagement\",\"ssm-contacts:DescribeEngagement\",\"ssm-contacts:ListPagesByEngagement\",\"ssm-contacts:StopEngagement\"],\"Principal\":{\"AWS\":\"222233334444\"},\"Effect\":\"Allow\",\"Resource\":[\"arn:aws:ssm-contacts:*:111122223333:contact\/akuam\",\"arn:aws:ssm-contacts:*:111122223333:engagement\/akuam\/*\"]}]}"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[共有連絡先と対応計画の操作](https://docs.aws.amazon.com/incident-manager/latest/userguide/sharing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutContactPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/put-contact-policy.html)」を参照してください。

### `send-activation-code`
<a name="ssm-contacts_SendActivationCode_cli_2_topic"></a>

次のコード例は、`send-activation-code` を使用する方法を示しています。

**AWS CLI**  
**アクティベーションコードを送信するには**  
次の `send-activation-code` の例では、指定された連絡先チャネルにアクティベーションコードとメッセージを送信します。  

```
aws ssm-contacts send-activation-code \
    --contact-channel-id "arn:aws:ssm-contacts:us-east-1:111122223333:contact-channel/akuam/8ddae2d1-12c8-4e45-b852-c8587266c400"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendActivationCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/send-activation-code.html)」を参照してください。

### `start-engagement`
<a name="ssm-contacts_StartEngagement_cli_2_topic"></a>

次のコード例は、`start-engagement` を使用する方法を示しています。

**AWS CLI**  
**例 1: 連絡先の連絡先チャネルをページングするには**  
次の `start-engagement` では、連絡先の連絡先チャネルをページングします。送信者、サブジェクト、パブリックサブジェクト、パブリックコンテンツにはすべてフィールドがありません。Incident Manager は、提供された音声または E メールの連絡先チャネルに件名とコンテンツを送信します。Incident Manager は、提供された SMS の連絡先チャネルにパブリックサブジェクトとパブリックコンテンツを送信します。送信者を使用して、エンゲージメントを開始したユーザーを追跡します。  

```
aws ssm-contacts start-engagement \
    --contact-id  "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam" \
    --sender "cli" \
    --subject "cli-test" \
    --content "Testing engagements via CLI" \
    --public-subject "cli-test" \
    --public-content "Testing engagements va CLI"
```
出力:  

```
{
    "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/akuam/607ced0e-e8fa-4ea7-8958-a237b8803f8f"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
**例 2: 指定されたエスカレーションプランの連絡先をページングするには**  
次の `start-engagement` は、エスカレーションプランを通じて連絡先をエンゲージします。各連絡先は、エンゲージメントプランに従ってページングされます。  

```
aws ssm-contacts start-engagement \
    --contact-id  "arn:aws:ssm-contacts:us-east-2:111122223333:contact/example_escalation" \
    --sender "cli" \
    --subject "cli-test" \
    --content "Testing engagements via CLI" \
    --public-subject "cli-test" \
    --public-content "Testing engagements va CLI"
```
出力:  

```
{
    "EngagementArn": "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/example_escalation/69e40ce1-8dbb-4d57-8962-5fbe7fc53356"
}
```
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartEngagement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/start-engagement.html)」を参照してください。

### `stop-engagement`
<a name="ssm-contacts_StopEngagement_cli_2_topic"></a>

次のコード例は、`stop-engagement` を使用する方法を示しています。

**AWS CLI**  
**エンゲージメントを停止するには**  
次の `stop-engagement` の例では、エンゲージメントによる連絡先と連絡先チャネルのさらなるページングを停止します。  

```
aws ssm-contacts stop-engagement \
    --engagement-id "arn:aws:ssm-contacts:us-east-2:111122223333:engagement/example_escalation/69e40ce1-8dbb-4d57-8962-5fbe7fc53356"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopEngagement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/stop-engagement.html)」を参照してください。

### `tag-resource`
<a name="ssm-contacts_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**連絡先にタグを付けるには**  
次の `tag-resource` の例では、指定された連絡先に指定されたタグキーと値のペアをタグ付けします。  

```
aws ssm-contacts tag-resource \
    --resource-arn "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam" \
    --tags '[{"Key":"group1","Value":"1"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[タグ付け](https://docs.aws.amazon.com/incident-manager/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ssm-contacts_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**連絡先からタグを削除するには**  
次の `untag-resource` の例では、指定された連絡先から group1 タグを削除します。  

```
aws ssm-contacts untag-resource \
    --resource-arn "arn:aws:ssm-contacts:us-east-1:111122223333:contact/akuam" \
    --tag-keys "group1"
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[タグ付け](https://docs.aws.amazon.com/incident-manager/latest/userguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/untag-resource.html)」を参照してください。

### `update-contact-channel`
<a name="ssm-contacts_UpdateContactChannel_cli_2_topic"></a>

次のコード例は、`update-contact-channel` を使用する方法を示しています。

**AWS CLI**  
**連絡先チャネルを更新するには**  
次の `update-contact-channel` の例では、連絡先チャネルの名前と配信アドレスを更新します。  

```
aws ssm-contacts update-contact-channel \
    --contact-channel-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/49f3c24d-5f9f-4638-ae25-3f49e04229ad" \
    --name "akuas voice channel" \
    --delivery-address '{"SimpleAddress": "+15005550198"}'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateContactChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/update-contact-channel.html)」を参照してください。

### `update-contact`
<a name="ssm-contacts_UpdateContact_cli_2_topic"></a>

次のコード例は、`update-contact` を使用する方法を示しています。

**AWS CLI**  
**連絡先のエンゲージメントプランを更新するには**  
次の `update-contact` の例では、連絡先 Akua のエンゲージメントプランを更新して、3 種類の連絡先チャネルを含めます。これは、Akua の連絡先チャネルを作成した後に行われます。  

```
aws ssm-contacts update-contact \
    --contact-id "arn:aws:ssm-contacts:us-east-2:111122223333:contact/akuam" \
    --plan '{"Stages": [{"DurationInMinutes": 5, "Targets": [{"ChannelTargetInfo": {"ContactChannelId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/beb25840-5ac8-4644-95cc-7a8de390fa65","RetryIntervalInMinutes": 1 }}]}, {"DurationInMinutes": 5, "Targets": [{"ChannelTargetInfo":{"ContactChannelId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/49f3c24d-5f9f-4638-ae25-3f49e04229ad", "RetryIntervalInMinutes": 1}}]}, {"DurationInMinutes": 5, "Targets": [{"ChannelTargetInfo": {"ContactChannelId": "arn:aws:ssm-contacts:us-east-2:111122223333:contact-channel/akuam/77d4f447-f619-4954-afff-85551e369c2a","RetryIntervalInMinutes": 1 }}]}]}'
```
このコマンドでは何も出力されません。  
詳細については、「*Incident Manager ユーザーガイド*」の「[連絡先](https://docs.aws.amazon.com/incident-manager/latest/userguide/contacts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateContact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm-contacts/update-contact.html)」を参照してください。

# を使用した Amazon Inspector の例 AWS CLI
<a name="cli_2_inspector2_code_examples"></a>

次のコード例は、Amazon Inspector AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-attributes-to-findings`
<a name="inspector_AddAttributesToFindings_cli_2_topic"></a>

次のコード例は、`add-attributes-to-findings` を使用する方法を示しています。

**AWS CLI**  
**検出結果に属性を追加するには**  
次の `add-attribute-to-finding` のコマンドは、`Example` のキーと `example` の値を持つ属性を、`arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-8l1VIE0D/run/0-Z02cjjug/finding/0-T8yM9mEU` の ARN を持つ検出結果に割り当てます。  

```
aws inspector add-attributes-to-findings --finding-arns arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-8l1VIE0D/run/0-Z02cjjug/finding/0-T8yM9mEU --attributes key=Example,value=example
```
出力:  

```
{
    "failedItems": {}
}
```
詳細については、*Amazon Inspector* ガイドの「Amazon Inspector の検出結果」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddAttributesToFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/add-attributes-to-findings.html)」を参照してください。

### `associate-member`
<a name="inspector2_AssociateMember_cli_2_topic"></a>

次の例は、`associate-member` を使用する方法を説明しています。

**AWS CLI**  
**例: AWS アカウントを Amazon Inspector の委任管理者に関連付けるには**  
次の`associate-member`例では、 AWS アカウントを Amazon Inspector の委任管理者に関連付けます。  

```
aws inspector2 associate-member \
    --account-id 123456789012
```
出力:  

```
{
    "accountId": "123456789012"
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「Organizations を使用した Amazon Inspector での複数のアカウントの管理](https://docs.aws.amazon.com/inspector/latest/user/managing-multiple-accounts.html)」を参照してください。 *Amazon Inspector *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AssociateMember](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/associate-member.html)」を参照してください。

### `create-assessment-target`
<a name="inspector_CreateAssessmentTarget_cli_2_topic"></a>

次のコード例は、`create-assessment-target` を使用する方法を示しています。

**AWS CLI**  
**評価ターゲットを作成するには**  
次の `create-assessment-target` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-AB6DMKnv` のリソースグループを使用して、`ExampleAssessmentTarget` という名前の評価ターゲットを作成します。  

```
aws inspector create-assessment-target --assessment-target-name ExampleAssessmentTarget --resource-group-arn arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-AB6DMKnv
```
出力:  

```
{
    "assessmentTargetArn": "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX"
}
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAssessmentTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/create-assessment-target.html)」を参照してください。

### `create-assessment-template`
<a name="inspector_CreateAssessmentTemplate_cli_2_topic"></a>

次のコード例は、`create-assessment-template` を使用する方法を示しています。

**AWS CLI**  
**評価ターゲットテンプレートを作成するには**  
次の `create-assessment-template` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX` の評価ターゲットに `ExampleAssessmentTemplate` という評価テンプレートを作成します。  

```
aws inspector create-assessment-template --assessment-target-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX --assessment-template-name ExampleAssessmentTemplate --duration-in-seconds 180 --rules-package-arns arn:aws:inspector:us-west-2:758058086616:rulespackage/0-9hgA516p --user-attributes-for-findings key=ExampleTag,value=examplevalue
```
出力:  

```
{
    "assessmentTemplateArn": "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T"
}
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAssessmentTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/create-assessment-template.html)」を参照してください。

### `create-filter`
<a name="inspector2_CreateFilter_cli_2_topic"></a>

次のコード例は、`create-filter` を使用する方法を示しています。

**AWS CLI**  
**フィルタを作成するには**  
次の `create-filter` の例では、ECR インスタンスタイプの検出結果を省略する抑制ルールを作成します。  

```
aws inspector2 create-filter \
    --name "ExampleSuppressionRuleECR" \
    --description "This suppression rule omits ECR instance type findings" \
    --action SUPPRESS \
    --filter-criteria 'resourceType=[{comparison="EQUALS", value="AWS_ECR_INSTANCE"}]'
```
出力:  

```
{
    "arn": "arn:aws:inspector2:us-west-2:123456789012:owner/o-EXAMPLE222/filter/EXAMPLE444444444"
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector の検出結果のフィルタリング](https://docs.aws.amazon.com/inspector/latest/user/findings-managing-filtering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/create-filter.html)」を参照してください。

### `create-findings-report`
<a name="inspector2_CreateFindingsReport_cli_2_topic"></a>

次のコード例は、`create-findings-report` を使用する方法を示しています。

**AWS CLI**  
**検出結果レポートを作成するには**  
次の `create-findings-report` の例では、検出結果レポートを作成します。  

```
aws inspector2 create-findings-report \
    --report-format CSV \
    --s3-destination bucketName=inspector-sbom-123456789012,keyPrefix=sbom-key,kmsKeyArn=arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333 \
    --filter-criteria '{"ecrImageRepositoryName":[{"comparison":"EQUALS","value":"debian"}]}'
```
出力:  

```
{
    "reportId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333"
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector での検出結果の管理](https://docs.aws.amazon.com/inspector/latest/user/findings-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFindingsReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/create-findings-report.html)」を参照してください。

### `create-resource-group`
<a name="inspector_CreateResourceGroup_cli_2_topic"></a>

次のコード例は、`create-resource-group` を使用する方法を示しています。

**AWS CLI**  
**リソースグループを作成するには**  
次の `create-resource-group` のコマンドは、`Name` のタグキーと `example` の値を使用してリソースグループを作成します。  

```
aws inspector create-resource-group --resource-group-tags key=Name,value=example
```
出力:  

```
{
   "resourceGroupArn": "arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-AB6DMKnv"
}
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResourceGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/create-resource-group.html)」を参照してください。

### `create-sbom-export`
<a name="inspector2_CreateSbomExport_cli_2_topic"></a>

次のコード例は、`create-sbom-export` を使用する方法を示しています。

**AWS CLI**  
**ソフトウェア部品表 (SBOM) レポートを作成するには**  
次の `create-sbom-export` の例では、ソフトウェア部品表 (SBOM) レポートを作成します。  

```
aws inspector2 create-sbom-export \
    --report-format SPDX_2_3 \
    --resource-filter-criteria 'ecrRepositoryName=[{comparison="EQUALS",value="debian"}]' \
    --s3-destination bucketName=inspector-sbom-123456789012,keyPrefix=sbom-key,kmsKeyArn=arn:aws:kms:us-west-2:123456789012:key/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333
```
出力:  

```
{
    "reportId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333"
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector による SBOM のエクスポート](https://docs.aws.amazon.com/inspector/latest/user/sbom-export.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドレットリファレンス*」の「[CreateSbomExport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/create-sbom-export.html)」を参照してください。

### `delete-assessment-run`
<a name="inspector_DeleteAssessmentRun_cli_2_topic"></a>

次のコード例は、`delete-assessment-run` を使用する方法を示しています。

**AWS CLI**  
**評価実行を削除するには**  
次の `delete-assessment-run` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-11LMTAVe` の評価実行を削除します。  

```
aws inspector delete-assessment-run --assessment-run-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-11LMTAVe
```
詳細については、*Amazon Inspector* ガイドの「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAssessmentRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/delete-assessment-run.html)」を参照してください。

### `delete-assessment-target`
<a name="inspector_DeleteAssessmentTarget_cli_2_topic"></a>

次のコード例は、`delete-assessment-target` を使用する方法を示しています。

**AWS CLI**  
**評価ターゲットを削除するには**  
次の `delete-assessment-target` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq` の評価ターゲットを削除します。  

```
aws inspector delete-assessment-target --assessment-target-arn arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAssessmentTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/delete-assessment-target.html)」を参照してください。

### `delete-assessment-template`
<a name="inspector_DeleteAssessmentTemplate_cli_2_topic"></a>

次のコード例は、`delete-assessment-template` を使用する方法を示しています。

**AWS CLI**  
**評価テンプレートを削除するには**  
次の `delete-assessment-template` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T` の評価テンプレートを削除します。  

```
aws inspector delete-assessment-template --assessment-template-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAssessmentTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/delete-assessment-template.html)」を参照してください。

### `delete-filter`
<a name="inspector2_DeleteFilter_cli_2_topic"></a>

次のコード例は、`delete-filter` を使用する方法を示しています。

**AWS CLI**  
**フィルターを削除するには**  
次の `delete-filter` の例は、フィルターを削除します。  

```
aws inspector2 delete-filter \
    --arn "arn:aws:inspector2:us-west-2:123456789012:owner/o-EXAMPLE222/filter/EXAMPLE444444444"
```
出力:  

```
{
    "arn": "arn:aws:inspector2:us-west-2:123456789012:owner/o-EXAMPLE222/filter/EXAMPLE444444444"
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector の検出結果のフィルタリング](https://docs.aws.amazon.com/inspector/latest/user/findings-managing-filtering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/delete-filter.html)」を参照してください。

### `describe-assessment-runs`
<a name="inspector_DescribeAssessmentRuns_cli_2_topic"></a>

次のコード例は、`describe-assessment-runs` を使用する方法を示しています。

**AWS CLI**  
**評価実行を記述するには**  
次の `describe-assessment-run` のコマンドは、`arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE` の ARN を使用した評価実行について説明します。  

```
aws inspector describe-assessment-runs --assessment-run-arns arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE
```
出力:  

```
{
        "assessmentRuns": [
          {
                "arn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE",
                "assessmentTemplateArn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw",
                "completedAt": 1458680301.4,
                "createdAt": 1458680170.035,
                "dataCollected": true,
                "durationInSeconds": 3600,
                "name": "Run 1 for ExampleAssessmentTemplate",
                "notifications": [],
                "rulesPackageArns": [
                  "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-X1KXtawP"
                ],
                "startedAt": 1458680170.161,
                "state": "COMPLETED",
                "stateChangedAt": 1458680301.4,
                "stateChanges": [
                  {
                        "state": "CREATED",
                        "stateChangedAt": 1458680170.035
                  },
                  {
                        "state": "START_DATA_COLLECTION_PENDING",
                        "stateChangedAt": 1458680170.065
                  },
                  {
                        "state": "START_DATA_COLLECTION_IN_PROGRESS",
                        "stateChangedAt": 1458680170.096
                  },
                  {
                        "state": "COLLECTING_DATA",
                        "stateChangedAt": 1458680170.161
                  },
                  {
                        "state": "STOP_DATA_COLLECTION_PENDING",
                        "stateChangedAt": 1458680239.883
                  },
                  {
                        "state": "DATA_COLLECTED",
                        "stateChangedAt": 1458680299.847
                  },
                  {
                        "state": "EVALUATING_RULES",
                        "stateChangedAt": 1458680300.099
                  },
                  {
                        "state": "COMPLETED",
                        "stateChangedAt": 1458680301.4
                  }
                ],
                "userAttributesForFindings": []
          }
        ],
        "failedItems": {}
}
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssessmentRuns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/describe-assessment-runs.html)」を参照してください。

### `describe-assessment-targets`
<a name="inspector_DescribeAssessmentTargets_cli_2_topic"></a>

次のコード例は、`describe-assessment-targets` を使用する方法を示しています。

**AWS CLI**  
**評価ターゲットを記述するには**  
次の `describe-assessment-targets` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq` の評価ターゲットを記述します。  

```
aws inspector describe-assessment-targets --assessment-target-arns arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq
```
出力:  

```
{
      "assessmentTargets": [
        {
              "arn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq",
              "createdAt": 1458074191.459,
              "name": "ExampleAssessmentTarget",
              "resourceGroupArn": "arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-PyGXopAI",
              "updatedAt": 1458074191.459
        }
      ],
      "failedItems": {}
}
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssessmentTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/describe-assessment-targets.html)」を参照してください。

### `describe-assessment-templates`
<a name="inspector_DescribeAssessmentTemplates_cli_2_topic"></a>

次のコード例は、`describe-assessment-templates` を使用する方法を示しています。

**AWS CLI**  
**評価テンプレートを記述するには**  
次の `describe-assessment-templates` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw` の評価テンプレートを記述します。  

```
aws inspector describe-assessment-templates --assessment-template-arns arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw
```
出力:  

```
{
      "assessmentTemplates": [
        {
              "arn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw",
              "assessmentTargetArn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq",
              "createdAt": 1458074191.844,
              "durationInSeconds": 3600,
              "name": "ExampleAssessmentTemplate",
              "rulesPackageArns": [
                "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-X1KXtawP"
              ],
              "userAttributesForFindings": []
        }
      ],
      "failedItems": {}
}
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssessmentTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/describe-assessment-templates.html)」を参照してください。

### `describe-cross-account-access-role`
<a name="inspector_DescribeCrossAccountAccessRole_cli_2_topic"></a>

次のコード例は、`describe-cross-account-access-role` を使用する方法を示しています。

**AWS CLI**  
**クロスアカウントアクセスロールを記述するには**  
次の`describe-cross-account-access-role`コマンドは、Amazon Inspector が AWS アカウントにアクセスできるようにする IAM ロールについて説明します。  

```
aws inspector describe-cross-account-access-role
```
出力:  

```
{
        "registeredAt": 1458069182.826,
        "roleArn": "arn:aws:iam::123456789012:role/inspector",
        "valid": true
}
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector のセットアップ」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCrossAccountAccessRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/describe-cross-account-access-role.html)」を参照してください。

### `describe-findings`
<a name="inspector_DescribeFindings_cli_2_topic"></a>

次のコード例は、`describe-findings` を使用する方法を示しています。

**AWS CLI**  
**検出結果を記述するには**  
次の `describe-findings` のコマンドは、`arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE/finding/0-HwPnsDm4` の ARN を持つ検出結果を記述します。  

```
aws inspector describe-findings --finding-arns arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE/finding/0-HwPnsDm4
```
出力:  

```
{
      "failedItems": {},
      "findings": [
        {
              "arn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE/finding/0-HwPnsDm4",
              "assetAttributes": {
                "ipv4Addresses": [],
                "schemaVersion": 1
              },
              "assetType": "ec2-instance",
              "attributes": [],
              "confidence": 10,
              "createdAt": 1458680301.37,
              "description": "Amazon Inspector did not find any potential security issues during this assessment.",
              "indicatorOfCompromise": false,
              "numericSeverity": 0,
              "recommendation": "No remediation needed.",
              "schemaVersion": 1,
              "service": "Inspector",
              "serviceAttributes": {
                "assessmentRunArn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE",
                "rulesPackageArn": "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-X1KXtawP",
                "schemaVersion": 1
              },
              "severity": "Informational",
              "title": "No potential security issues found",
              "updatedAt": 1458680301.37,
              "userAttributes": []
        }
      ]
}
```
詳細については、*Amazon Inspector* ガイドの「Amazon Inspector の検出結果」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/describe-findings.html)」を参照してください。

### `describe-resource-groups`
<a name="inspector_DescribeResourceGroups_cli_2_topic"></a>

次のコード例は、`describe-resource-groups` を使用する方法を示しています。

**AWS CLI**  
**リソースグループを記述するには**  
次の`describe-resource-groups`コマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-PyGXopAI` のリソースグループを記述します。  

```
aws inspector describe-resource-groups --resource-group-arns arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-PyGXopAI
```
出力:  

```
{
      "failedItems": {},
      "resourceGroups": [
        {
              "arn": "arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-PyGXopAI",
              "createdAt": 1458074191.098,
              "tags": [
                {
                      "key": "Name",
                      "value": "example"
                }
              ]
        }
      ]
}
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeResourceGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/describe-resource-groups.html)」を参照してください。

### `describe-rules-packages`
<a name="inspector_DescribeRulesPackages_cli_2_topic"></a>

次のコード例は、`describe-rules-packages` を使用する方法を示しています。

**AWS CLI**  
**ルールパッケージを記述するには**  
次の `describe-rules-packages` のコマンドは、`arn:aws:inspector:us-west-2:758058086616:rulespackage/0-9hgA516p` の ARN を持つルールパッケージを記述します。  

```
aws inspector describe-rules-packages --rules-package-arns arn:aws:inspector:us-west-2:758058086616:rulespackage/0-9hgA516p
```
出力:  

```
{
      "failedItems": {},
      "rulesPackages": [
        {
              "arn": "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-9hgA516p",
              "description": "The rules in this package help verify whether the EC2 instances in your application are exposed to Common Vulnerabilities and
              Exposures (CVEs). Attacks can exploit unpatched vulnerabilities to compromise the confidentiality, integrity, or availability of your service
              or data. The CVE system provides a reference for publicly known information security vulnerabilities and exposures. For more information, see
              [https://cve.mitre.org/](https://cve.mitre.org/). If a particular CVE appears in one of the produced Findings at the end of a completed
              Inspector assessment, you can search [https://cve.mitre.org/](https://cve.mitre.org/) using the CVE's ID (for example, \"CVE-2009-0021\") to
              find detailed information about this CVE, its severity, and how to mitigate it. ",
              "name": "Common Vulnerabilities and Exposures",
              "provider": "Amazon Web Services, Inc.",
              "version": "1.1"
        }
      ]
}
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector ルールパッケージとルール」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRulesPackages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/describe-rules-packages.html)」を参照してください。

### `disassociate-member`
<a name="inspector2_DisassociateMember_cli_2_topic"></a>

次のコード例は、`disassociate-member` を使用する方法を示しています。

**AWS CLI**  
**例: メンバーアカウントを Amazon Inspector 委任管理者から関連付け解除するには**  
次の の`disassociate-member`例では、Amazon Inspector 委任管理者から AWS アカウントの関連付けを解除します。  

```
aws inspector2 disassociate-member \
    --account-id 123456789012
```
出力:  

```
{
    "accountId": "123456789012"
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「Organizations を使用した Amazon Inspector での複数のアカウントの管理](https://docs.aws.amazon.com/inspector/latest/user/managing-multiple-accounts.html)」を参照してください。 *Amazon Inspector *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DisassociateMember](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/disassociate-member.html)」を参照してください。

### `get-configuration`
<a name="inspector2_GetConfiguration_cli_2_topic"></a>

次のコード例は、`get-configuration` を使用する方法を示しています。

**AWS CLI**  
**Inspector スキャンの設定を取得するには**  
次の `get-configuration` の例では、Inspector スキャンの設定を取得します。  

```
aws inspector2 get-configuration
```
出力:  

```
{
    "ec2Configuration": {
        "scanModeState": {
            "scanMode": "EC2_HYBRID",
            "scanModeStatus": "SUCCESS"
        }
    },
    "ecrConfiguration": {
        "rescanDurationState": {
            "pullDateRescanDuration": "DAYS_90",
            "rescanDuration": "DAYS_30",
            "status": "SUCCESS",
            "updatedAt": "2024-05-14T21:16:20.237000+00:00"
        }
     }
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector による自動リソーススキャン](https://docs.aws.amazon.com/inspector/latest/user/scanning-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/get-configuration.html)」を参照してください。

### `get-member`
<a name="inspector2_GetMember_cli_2_topic"></a>

次のコード例は、`get-member` を使用する方法を示しています。

**AWS CLI**  
**例: 組織のメンバー情報を取得するには**  
aws inspector2 get-member --account-id 123456789012  
出力:  

```
{
        "member": {
        "accountId": "123456789012",
        "delegatedAdminAccountId": "123456789012",
        "relationshipStatus": "ENABLED",
        "updatedAt": "2023-09-11T09:57:20.520000-07:00"
    }
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「Organizations を使用した Amazon Inspector での複数のアカウントの管理](https://docs.aws.amazon.com/inspector/latest/user/managing-multiple-accounts.html)」を参照してください。 *Amazon Inspector *  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetMember](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/get-member.html)」を参照してください。

### `get-telemetry-metadata`
<a name="inspector_GetTelemetryMetadata_cli_2_topic"></a>

次のコード例は、`get-telemetry-metadata` を使用する方法を示しています。

**AWS CLI**  
**テレメトリメタデータを取得するには**  
次の `get-telemetry-metadata` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE` の評価実行用に収集されたデータに関する情報を生成します。  

```
aws inspector get-telemetry-metadata --assessment-run-arn arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE
```
出力:  

```
{
      "telemetryMetadata": [
        {
              "count": 2,
              "dataSize": 345,
              "messageType": "InspectorDuplicateProcess"
        },
        {
              "count": 3,
              "dataSize": 255,
              "messageType": "InspectorTimeEventMsg"
        },
        {
              "count": 4,
              "dataSize": 1082,
              "messageType": "InspectorNetworkInterface"
        },
        {
              "count": 2,
              "dataSize": 349,
              "messageType": "InspectorDnsEntry"
        },
        {
              "count": 11,
              "dataSize": 2514,
              "messageType": "InspectorDirectoryInfoMsg"
        },
        {
              "count": 1,
              "dataSize": 179,
              "messageType": "InspectorTcpV6ListeningPort"
        },
        {
              "count": 101,
              "dataSize": 10949,
              "messageType": "InspectorTerminal"
        },
        {
              "count": 26,
              "dataSize": 5916,
              "messageType": "InspectorUser"
        },
        {
              "count": 282,
              "dataSize": 32148,
              "messageType": "InspectorDynamicallyLoadedCodeModule"
        },
        {
              "count": 18,
              "dataSize": 10172,
              "messageType": "InspectorCreateProcess"
        },
        {
              "count": 3,
              "dataSize": 8001,
              "messageType": "InspectorProcessPerformance"
        },
        {
              "count": 1,
              "dataSize": 360,
              "messageType": "InspectorOperatingSystem"
        },
        {
              "count": 6,
              "dataSize": 546,
              "messageType": "InspectorStopProcess"
        },
        {
              "count": 1,
              "dataSize": 1553,
              "messageType": "InspectorInstanceMetaData"
        },
        {
              "count": 2,
              "dataSize": 434,
              "messageType": "InspectorTcpV4Connection"
        },
        {
              "count": 474,
              "dataSize": 2960322,
              "messageType": "InspectorPackageInfo"
        },
        {
              "count": 3,
              "dataSize": 2235,
              "messageType": "InspectorSystemPerformance"
        },
        {
              "count": 105,
              "dataSize": 46048,
              "messageType": "InspectorCodeModule"
        },
        {
              "count": 1,
              "dataSize": 182,
              "messageType": "InspectorUdpV6ListeningPort"
        },
        {
              "count": 2,
              "dataSize": 371,
              "messageType": "InspectorUdpV4ListeningPort"
        },
        {
              "count": 18,
              "dataSize": 8362,
              "messageType": "InspectorKernelModule"
        },
        {
              "count": 29,
              "dataSize": 48788,
              "messageType": "InspectorConfigurationInfo"
        },
        {
              "count": 1,
              "dataSize": 79,
              "messageType": "InspectorMonitoringStart"
        },
        {
              "count": 5,
              "dataSize": 0,
              "messageType": "InspectorSplitMsgBegin"
        },
        {
              "count": 51,
              "dataSize": 4593,
              "messageType": "InspectorGroup"
        },
        {
              "count": 1,
              "dataSize": 184,
              "messageType": "InspectorTcpV4ListeningPort"
        },
        {
              "count": 1159,
              "dataSize": 3146579,
              "messageType": "Total"
        },
        {
              "count": 5,
              "dataSize": 0,
              "messageType": "InspectorSplitMsgEnd"
        },
        {
              "count": 1,
              "dataSize": 612,
              "messageType": "InspectorLoadImageInProcess"
        }
      ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTelemetryMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/get-telemetry-metadata.html)」を参照してください。

### `list-account-permissions`
<a name="inspector2_ListAccountPermissions_cli_2_topic"></a>

次のコード例は、`list-account-permissions` を使用する方法を示しています。

**AWS CLI**  
**アカウントのアクセス許可を一覧表示するには**  
次の `list-account-permissions` の例では、アカウントのアクセス許可を一覧表示します。  

```
aws inspector2 list-account-permissions
```
出力:  

```
{
    "permissions": [
        {
            "operation": "ENABLE_SCANNING",
            "service": "ECR"
        },
        {
            "operation": "DISABLE_SCANNING",
            "service": "ECR"
        },
        {
            "operation": "ENABLE_REPOSITORY",
            "service": "ECR"
        },
        {
            "operation": "DISABLE_REPOSITORY",
            "service": "ECR"
        },
        {
            "operation": "ENABLE_SCANNING",
            "service": "EC2"
        },
        {
            "operation": "DISABLE_SCANNING",
            "service": "EC2"
        },
        {
            "operation": "ENABLE_SCANNING",
            "service": "LAMBDA"
        },
        {
            "operation": "DISABLE_SCANNING",
            "service": "LAMBDA"
        }
    ]
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector のアイデンティティとアクセス管理](https://docs.aws.amazon.com/inspector/latest/user/security-iam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccountPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/list-account-permissions.html)」を参照してください。

### `list-assessment-run-agents`
<a name="inspector_ListAssessmentRunAgents_cli_2_topic"></a>

次のコード例は、`list-assessment-run-agents` を使用する方法を示しています。

**AWS CLI**  
**評価実行のエージェントを一覧表示するには**  
次の `list-assessment-run-agents` のコマンドは、指定された ARN を持つ評価実行のエージェントを一覧表示します。  

```
aws inspector list-assessment-run-agents \
    --assessment-run-arn arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE
```
出力:  

```
{
    "assessmentRunAgents": [
        {
            "agentHealth": "HEALTHY",
            "agentHealthCode": "HEALTHY",
            "agentId": "i-49113b93",
            "assessmentRunArn": "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE",
            "telemetryMetadata": [
                {
                    "count": 2,
                    "dataSize": 345,
                    "messageType": "InspectorDuplicateProcess"
                },
                {
                    "count": 3,
                    "dataSize": 255,
                    "messageType": "InspectorTimeEventMsg"
                },
                {
                    "count": 4,
                    "dataSize": 1082,
                    "messageType": "InspectorNetworkInterface"
                },
                {
                    "count": 2,
                    "dataSize": 349,
                    "messageType": "InspectorDnsEntry"
                },
                {
                    "count": 11,
                    "dataSize": 2514,
                    "messageType": "InspectorDirectoryInfoMsg"
                },
                {
                    "count": 1,
                    "dataSize": 179,
                    "messageType": "InspectorTcpV6ListeningPort"
                },
                {
                    "count": 101,
                    "dataSize": 10949,
                    "messageType": "InspectorTerminal"
                },
                {
                    "count": 26,
                    "dataSize": 5916,
                    "messageType": "InspectorUser"
                },
                {
                    "count": 282,
                    "dataSize": 32148,
                    "messageType": "InspectorDynamicallyLoadedCodeModule"
                },
                {
                    "count": 18,
                    "dataSize": 10172,
                    "messageType": "InspectorCreateProcess"
                },
                {
                    "count": 3,
                    "dataSize": 8001,
                    "messageType": "InspectorProcessPerformance"
                },
                {
                    "count": 1,
                    "dataSize": 360,
                    "messageType": "InspectorOperatingSystem"
                },
                {
                    "count": 6,
                    "dataSize": 546,
                    "messageType": "InspectorStopProcess"
                },
                {
                    "count": 1,
                    "dataSize": 1553,
                    "messageType": "InspectorInstanceMetaData"
                },
                {
                    "count": 2,
                    "dataSize": 434,
                    "messageType": "InspectorTcpV4Connection"
                },
                {
                    "count": 474,
                    "dataSize": 2960322,
                    "messageType": "InspectorPackageInfo"
                },
                {
                    "count": 3,
                    "dataSize": 2235,
                    "messageType": "InspectorSystemPerformance"
                },
                {
                    "count": 105,
                    "dataSize": 46048,
                    "messageType": "InspectorCodeModule"
                },
                {
                    "count": 1,
                    "dataSize": 182,
                    "messageType": "InspectorUdpV6ListeningPort"
                },
                {
                    "count": 2,
                    "dataSize": 371,
                    "messageType": "InspectorUdpV4ListeningPort"
                },
                {
                    "count": 18,
                    "dataSize": 8362,
                    "messageType": "InspectorKernelModule"
                },
                {
                    "count": 29,
                    "dataSize": 48788,
                    "messageType": "InspectorConfigurationInfo"
                },
                {
                    "count": 1,
                    "dataSize": 79,
                    "messageType": "InspectorMonitoringStart"
                },
                {
                    "count": 5,
                    "dataSize": 0,
                    "messageType": "InspectorSplitMsgBegin"
                },
                {
                    "count": 51,
                    "dataSize": 4593,
                    "messageType": "InspectorGroup"
                },
                {
                    "count": 1,
                    "dataSize": 184,
                    "messageType": "InspectorTcpV4ListeningPort"
                },
                {
                    "count": 1159,
                    "dataSize": 3146579,
                    "messageType": "Total"
                },
                {
                    "count": 5,
                    "dataSize": 0,
                    "messageType": "InspectorSplitMsgEnd"
                },
                {
                    "count": 1,
                    "dataSize": 612,
                    "messageType": "InspectorLoadImageInProcess"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[AWS エージェント](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_agents.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssessmentRunAgents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-assessment-run-agents.html)」を参照してください。

### `list-assessment-runs`
<a name="inspector_ListAssessmentRuns_cli_2_topic"></a>

次のコード例は、`list-assessment-runs` を使用する方法を示しています。

**AWS CLI**  
**評価実行を一覧表示するには**  
次の `list-assessment-runs` のコマンドは、既存のすべての評価実行を一覧表示します。  

```
aws inspector list-assessment-runs
```
出力:  

```
{
    "assessmentRunArns": [
        "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE",
        "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-v5D6fI3v"
    ]
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector 評価テンプレートと評価実行](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_assessments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssessmentRuns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-assessment-runs.html)」を参照してください。

### `list-assessment-targets`
<a name="inspector_ListAssessmentTargets_cli_2_topic"></a>

次のコード例は、`list-assessment-targets` を使用する方法を示しています。

**AWS CLI**  
**評価ターゲットを一覧表示するには**  
次の `list-assessment-targets` のコマンドは、既存のすべての評価ターゲットを一覧表示します。  

```
aws inspector list-assessment-targets
```
出力:  

```
{
       "assessmentTargetArns": [
       "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq"
       ]
}
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssessmentTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-assessment-targets.html)」を参照してください。

### `list-assessment-templates`
<a name="inspector_ListAssessmentTemplates_cli_2_topic"></a>

次のコード例は、`list-assessment-templates` を使用する方法を示しています。

**AWS CLI**  
**評価テンプレートを一覧表示するには**  
次の `list-assessment-templates` のコマンドは、既存のすべての評価テンプレートを一覧表示します。  

```
aws inspector list-assessment-templates
```
出力:  

```
{
       "assessmentTemplateArns": [
       "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw",
       "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-Uza6ihLh"
       ]
}
```
詳細については、*Amazon Inspector* ガイドの「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssessmentTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-assessment-templates.html)」を参照してください。

### `list-coverage-statistics`
<a name="inspector2_ListCoverageStatistics_cli_2_topic"></a>

次のコード例は、`list-coverage-statistics` を使用する方法を示しています。

**AWS CLI**  
**例 1: グループ別にカバレッジ統計を一覧表示するには**  
次の の`list-coverage-statistics`例では、 AWS 環境のカバレッジ統計をグループ別に一覧表示します。  

```
aws inspector2 list-coverage-statistics \
   --group-by RESOURCE_TYPE
```
出力:  

```
{
    "countsByGroup": [
        {
            "count": 56,
            "groupKey": "AWS_LAMBDA_FUNCTION"
        },
        {
            "count": 27,
            "groupKey": "AWS_ECR_REPOSITORY"
        },
        {
            "count": 18,
            "groupKey": "AWS_EC2_INSTANCE"
        },
        {
            "count": 3,
            "groupKey": "AWS_ECR_CONTAINER_IMAGE"
        },
        {
            "count": 1,
            "groupKey": "AWS_ACCOUNT"
        }
    ],
    "totalCounts": 105
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「環境の Amazon Inspector カバレッジの評価](https://docs.aws.amazon.com/inspector/latest/user/assessing-coverage.html)」を参照してください。 *Amazon Inspector *  
**例 2: リソースタイプ別にカバレッジ統計を一覧表示するには**  
次の の`list-coverage-statistics`例では、 AWS 環境のカバレッジ統計をリソースタイプ別に一覧表示します。  

```
aws inspector2 list-coverage-statistics
    --filter-criteria '{"resourceType":[{"comparison":"EQUALS","value":"AWS_ECR_REPOSITORY"}]}'
    --group-by SCAN_STATUS_REASON
```
出力:  

```
{
    "countsByGroup": [
        {
            "count": 27,
            "groupKey": "SUCCESSFUL"
        }
    ],
    "totalCounts": 27
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「環境の Amazon Inspector カバレッジの評価](https://docs.aws.amazon.com/inspector/latest/user/assessing-coverage.html)」を参照してください。 *Amazon Inspector *  
**例 3: ECR リポジトリ名別にカバレッジ統計を一覧表示するには**  
次の の`list-coverage-statistics`例では、 AWS 環境のカバレッジ統計を ECR リポジトリ名別に一覧表示します。  

```
aws inspector2 list-coverage-statistics
   --filter-criteria '{"ecrRepositoryName":[{"comparison":"EQUALS","value":"debian"}]}'
   --group-by SCAN_STATUS_REASON
```
出力:  

```
{
    "countsByGroup": [
        {
            "count": 3,
            "groupKey": "SUCCESSFUL"
        }
    ],
    "totalCounts": 3
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「環境の Amazon Inspector カバレッジの評価](https://docs.aws.amazon.com/inspector/latest/user/assessing-coverage.html)」を参照してください。 *Amazon Inspector *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCoverageStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/list-coverage-statistics.html)」を参照してください。

### `list-coverage`
<a name="inspector2_ListCoverage_cli_2_topic"></a>

次のコード例は、`list-coverage` を使用する方法を示しています。

**AWS CLI**  
**例 1: 環境に関するカバレッジの詳細を一覧表示するには**  
次の `list-coverage` の例では、環境のカバレッジの詳細を一覧表示します。  

```
aws inspector2 list-coverage
```
出力:  

```
{
    "coveredResources": [
        {
            "accountId": "123456789012",
            "lastScannedAt": "2024-05-20T16:23:20-07:00",
            "resourceId": "i-EXAMPLE55555555555",
            "resourceMetadata": {
                "ec2": {
                    "amiId": "ami-EXAMPLE6666666666",
                    "platform": "LINUX"
                }
            },
            "resourceType": "AWS_EC2_INSTANCE",
            "scanStatus": {
                "reason": "SUCCESSFUL",
                "statusCode": "ACTIVE"
            },
            "scanType": "PACKAGE"
        }
    ]
}
```
**例 2: Lambda 関数リソースタイプに関するカバレッジの詳細を一覧表示するには**  
次の `list-coverage` の例では、Lambda 関数のリソースタイプの詳細を一覧表示します。  

```
aws inspector2 list-coverage
    --filter-criteria '{"resourceType":[{"comparison":"EQUALS","value":"AWS_LAMBDA_FUNCTION"}]}'
```
出力:  

```
{
    "coveredResources": [
        {
            "accountId": "123456789012",
            "resourceId": "arn:aws:lambda:us-west-2:123456789012:function:Eval-container-scan-results:$LATEST",
            "resourceMetadata": {
                "lambdaFunction": {
                    "functionName": "Eval-container-scan-results",
                    "functionTags": {},
                    "layers": [],
                    "runtime": "PYTHON_3_7"
                }
            },
            "resourceType": "AWS_LAMBDA_FUNCTION",
            "scanStatus": {
                "reason": "SUCCESSFUL",
                "statusCode": "ACTIVE"
            },
            "scanType": "CODE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCoverage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/list-coverage.html)」を参照してください。

### `list-delegated-admin-accounts`
<a name="inspector2_ListDelegatedAdminAccounts_cli_2_topic"></a>

次のコード例は、`list-delegated-admin-accounts` を使用する方法を示しています。

**AWS CLI**  
**組織の委任管理者アカウントに関する情報を一覧表示するには**  
次の `list-delegated-admin-accounts` の例は、組織の委任管理者アカウントに関する情報を示しています。  

```
aws inspector2 list-delegated-admin-accounts
```
出力:  

```
{
    "delegatedAdminAccounts": [
        {
            "accountId": "123456789012",
            "status": "ENABLED"
        }
    ]
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector の委任管理者の指定](https://docs.aws.amazon.com/inspector/latest/user/admin-member-relationship.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDelegatedAdminAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/list-delegated-admin-accounts.html)」を参照してください。

### `list-event-subscriptions`
<a name="inspector_ListEventSubscriptions_cli_2_topic"></a>

次のコード例は、`list-event-subscriptions` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを一覧表示するには**  
次の `list-event-subscriptions` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0` の評価テンプレートのすべてのイベントサブスクリプションを一覧表示します。  

```
aws inspector list-event-subscriptions --resource-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0
```
出力:  

```
{
      "subscriptions": [
        {
              "eventSubscriptions": [
                {
                      "event": "ASSESSMENT_RUN_COMPLETED",
                      "subscribedAt": 1459455440.867
                }
              ],
              "resourceArn": "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0",
              "topicArn": "arn:aws:sns:us-west-2:123456789012:exampletopic"
        }
      ]
}
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEventSubscriptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-event-subscriptions.html)」を参照してください。

### `list-filters`
<a name="inspector2_ListFilters_cli_2_topic"></a>

次のコード例は、`list-filters` を使用する方法を示しています。

**AWS CLI**  
**Amazon Inspector のアクティブ化に使用したアカウントに関連付けられたフィルターを一覧表示するには**  
次の `list-filters` の例では、Amazon Inspector のアクティブ化に使用したアカウントに関連付けられたフィルターを一覧表示します。  

```
aws inspector2 list-filters
```
出力:  

```
{
    "filters": [
        {
            "action": "SUPPRESS",
            "arn": "arn:aws:inspector2:us-west-2:123456789012:owner/o-EXAMPLE222/filter/EXAMPLE444444444",
            "createdAt": "2024-05-15T21:11:08.602000+00:00",
            "criteria": {
                "resourceType": [
                    {
                        "comparison": "EQUALS",
                        "value": "AWS_EC2_INSTANCE"
                    },
                ]
            },
            "description": "This suppression rule omits EC2 instance type findings",
            "name": "ExampleSuppressionRuleEC2",
            "ownerId": "o-EXAMPLE222",
            "tags": {},
            "updatedAt": "2024-05-15T21:11:08.602000+00:00"
        },
        {
            "action": "SUPPRESS",
            "arn": "arn:aws:inspector2:us-east-1:813737243517:owner/o-EXAMPLE222/filter/EXAMPLE444444444",
            "createdAt": "2024-05-15T21:28:27.054000+00:00",
            "criteria": {
                "resourceType": [
                    {
                        "comparison": "EQUALS",
                        "value": "AWS_ECR_INSTANCE"
                    }
                ]
            },
            "description": "This suppression rule omits ECR instance type findings",
            "name": "ExampleSuppressionRuleECR",
            "ownerId": "o-EXAMPLE222",
            "tags": {},
            "updatedAt": "2024-05-15T21:28:27.054000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector の検出結果のフィルタリング](https://docs.aws.amazon.com/inspector/latest/user/findings-managing-filtering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFilters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/list-filters.html)」を参照してください。

### `list-findings`
<a name="inspector_ListFindings_cli_2_topic"></a>

次のコード例は、`list-findings` を使用する方法を示しています。

**AWS CLI**  
**検出結果を一覧表示するには**  
次の `list-findings` のコマンドは、生成されたすべての検出結果を一覧表示します。  

```
aws inspector list-findings
```
出力:  

```
{
        "findingArns": [
        "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-MKkpXXPE/finding/0-HwPnsDm4",
        "arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-4r1V2mAw/run/0-v5D6fI3v/finding/0-tyvmqBLy"
      ]
}
```
詳細については、*Amazon Inspector* ガイドの「Amazon Inspector の検出結果」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-findings.html)」を参照してください。

### `list-members`
<a name="inspector2_ListMembers_cli_2_topic"></a>

次のコード例は、`list-members` を使用する方法を示しています。

**AWS CLI**  
**例 1: 組織の Amazon Inspector 委任管理者に関連付けられているすべてのメンバーアカウントを一覧表示するには**  
aws inspector2 list-members --only-associated  
出力:  

```
{
        {
             "members": [
        {
             "accountId": "123456789012",
             "delegatedAdminAccountId": "123456789012",
             "relationshipStatus": "ENABLED",
             "updatedAt": "2023-09-11T09:57:20.520000-07:00"
        },
        {
             "accountId": "123456789012",
             "delegatedAdminAccountId": "123456789012",
             "relationshipStatus": "ENABLED",
             "updatedAt": "2024-08-12T10:13:01.472000-07:00"
        },
        {
             "accountId": "625032911453",
             "delegatedAdminAccountId": "123456789012",
             "relationshipStatus": "ENABLED",
             "updatedAt": "2023-09-11T09:57:20.438000-07:00"
        },
        {
            "accountId": "715411239211",
            "delegatedAdminAccountId": "123456789012",
            "relationshipStatus": "ENABLED",
            "updatedAt": "2024-04-24T09:14:57.471000-07:00"
        }
    ]
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「Organizations を使用した Amazon Inspector での複数のアカウントの管理](https://docs.aws.amazon.com/inspector/latest/user/managing-multiple-accounts.html)」を参照してください。 *Amazon Inspector *  
**例 2: 組織の Amazon Inspector 委任管理者に対して、関連付けられているメンバーアカウントと、関連付けが解除されたメンバーアカウントをすべて一覧表示するには**  
aws inspector2 list-members --no-only-associated  
出力:  

```
{
        {
            "members": [
        {
            "accountId": "123456789012",
            "delegatedAdminAccountId": "123456789012",
            "relationshipStatus": "REMOVED",
            "updatedAt": "2024-05-15T11:34:53.326000-07:00"
        },
        {
            "accountId": "123456789012",
            "delegatedAdminAccountId": "123456789012",
            "relationshipStatus": "ENABLED",
            "updatedAt": "2023-09-11T09:57:20.520000-07:00"
        },
        {
            "accountId": "123456789012",
            "delegatedAdminAccountId": "123456789012",
            "relationshipStatus": "ENABLED",
            "updatedAt": "2024-08-12T10:13:01.472000-07:00"
        },
        {
            "accountId": "123456789012",
            "delegatedAdminAccountId": "123456789012",
            "relationshipStatus": "ENABLED",
            "updatedAt": "2023-09-11T09:57:20.438000-07:00"
        },
        {
            "accountId": "123456789012",
            "delegatedAdminAccountId": "123456789012",
            "relationshipStatus": "ENABLED",
            "updatedAt": "2024-04-24T09:14:57.471000-07:00"
        }
    ]
}
```
詳細については、[Amazon Inspector ユーザーガイド」の AWS 「Organizations を使用した Amazon Inspector での複数のアカウントの管理](https://docs.aws.amazon.com/inspector/latest/user/managing-multiple-accounts.html)」を参照してください。 *Amazon Inspector *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/list-members.html)」を参照してください。

### `list-rules-packages`
<a name="inspector_ListRulesPackages_cli_2_topic"></a>

次のコード例は、`list-rules-packages` を使用する方法を示しています。

**AWS CLI**  
**ルールパッケージを一覧表示するには**  
次の `list-rules-packages` のコマンドは、使用可能なすべての Inspector ルールパッケージを一覧表示します。  

```
aws inspector list-rules-packages
```
出力:  

```
{
       "rulesPackageArns": [
         "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-9hgA516p",
         "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-H5hpSawc",
         "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-JJOtZiqQ",
         "arn:aws:inspector:us-west-2:758058086616:rulespackage/0-vg5GGHSD"
       ]
 }
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector ルールパッケージとルール」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRulesPackages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-rules-packages.html)」を参照してください。

### `list-tags-for-resource`
<a name="inspector_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` のコマンドは、`arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-gcwFliYu` の ARN を持つ評価テンプレートに関連付けられたすべてのタグを一覧表示します。  

```
aws inspector list-tags-for-resource --resource-arn arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-gcwFliYu
```
出力:  

```
{
      "tags": [
        {
              "key": "Name",
              "value": "Example"
        }
      ]
}
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/list-tags-for-resource.html)」を参照してください。

### `list-usage-totals`
<a name="inspector2_ListUsageTotals_cli_2_topic"></a>

次のコード例は、`list-usage-totals` を使用する方法を示しています。

**AWS CLI**  
**過去 30 日間の使用状況の合計を一覧表示するには**  
次の `list-usage-totals` の例では、過去 30 日間の使用状況の合計を一覧表示します。  

```
aws inspector2 list-usage-totals
```
出力:  

```
{
    "totals": [
        {
            "accountId": "123456789012",
            "usage": [
                {
                    "currency": "USD",
                    "estimatedMonthlyCost": 4.6022044647,
                    "total": 1893.4784083333334,
                    "type": "EC2_AGENTLESS_INSTANCE_HOURS"
                },
                {
                    "currency": "USD",
                    "estimatedMonthlyCost": 18.892449279,
                    "total": 10882.050784722222,
                    "type": "EC2_INSTANCE_HOURS"
                },
                {
                    "currency": "USD",
                    "estimatedMonthlyCost": 5.4525363736,
                    "total": 6543.043648333333,
                    "type": "LAMBDA_FUNCTION_CODE_HOURS"
                },
                {
                    "currency": "USD",
                    "estimatedMonthlyCost": 3.9064080309,
                    "total": 9375.379274166668,
                    "type": "LAMBDA_FUNCTION_HOURS"
                },
                {
                    "currency": "USD",
                    "estimatedMonthlyCost": 0.06,
                    "total": 6.0,
                    "type": "ECR_RESCAN"
                },
                {
                    "currency": "USD",
                    "estimatedMonthlyCost": 0.09,
                    "total": 1.0,
                    "type": "ECR_INITIAL_SCAN"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector での使用状況とコストのモニタリング](https://docs.aws.amazon.com/inspector/latest/user/usage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsageTotals](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/list-usage-totals.html)」を参照してください。

### `preview-agents`
<a name="inspector_PreviewAgents_cli_2_topic"></a>

次のコード例は、`preview-agents` を使用する方法を示しています。

**AWS CLI**  
**エージェントをプレビューするには**  
次の `preview-agents` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq` の評価ターゲットの一部である EC2 インスタンスにインストールされたエージェントをプレビューします。  

```
aws inspector preview-agents --preview-agents-arn arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq
```
出力:  

```
{
      "agentPreviews": [
        {
              "agentId": "i-49113b93"
        }
      ]
}
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PreviewAgents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/preview-agents.html)」を参照してください。

### `register-cross-account-access-role`
<a name="inspector_RegisterCrossAccountAccessRole_cli_2_topic"></a>

次のコード例は、`register-cross-account-access-role` を使用する方法を示しています。

**AWS CLI**  
**クロスアカウントアクセスロールを登録するには**  
次の `register-cross-account-access-role` コマンドは、評価実行の開始時または preview-agents コマンドを呼び出す際に Amazon Inspector が EC2 インスタンスを一覧表示するのに使用する ARN が `arn:aws:iam::123456789012:role/inspector` の IAM ロールを登録します。  

```
aws inspector register-cross-account-access-role --role-arn arn:aws:iam::123456789012:role/inspector
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector のセットアップ」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterCrossAccountAccessRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/register-cross-account-access-role.html)」を参照してください。

### `remove-attributes-from-findings`
<a name="inspector_RemoveAttributesFromFindings_cli_2_topic"></a>

次のコード例は、`remove-attributes-from-findings` を使用する方法を示しています。

**AWS CLI**  
**検出結果から属性を削除するには**  
次の `remove-attributes-from-finding` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-8l1VIE0D/run/0-Z02cjjug/finding/0-T8yM9mEU` の検出結果から、キー が `Example` で値が `example` の属性を削除します。  

```
aws inspector remove-attributes-from-findings --finding-arns arn:aws:inspector:us-west-2:123456789012:target/0-0kFIPusq/template/0-8l1VIE0D/run/0-Z02cjjug/finding/0-T8yM9mEU --attribute-keys key=Example,value=example
```
出力:  

```
{
      "failedItems": {}
}
```
詳細については、*Amazon Inspector* ガイドの「Amazon Inspector の検出結果」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveAttributesFromFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/remove-attributes-from-findings.html)」を参照してください。

### `set-tags-for-resource`
<a name="inspector_SetTagsForResource_cli_2_topic"></a>

次のコード例は、`set-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを設定するには**  
次の `set-tags-for-resource` のコマンドは、キーが `Example` で値が `example` のタグを ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0` の評価テンプレートに設定します。  

```
aws inspector set-tags-for-resource --resource-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0 --tags key=Example,value=example
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/set-tags-for-resource.html)」を参照してください。

### `start-assessment-run`
<a name="inspector_StartAssessmentRun_cli_2_topic"></a>

次のコード例は、`start-assessment-run` を使用する方法を示しています。

**AWS CLI**  
**評価実行を開始するには**  
次の `start-assessment-run` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T` の評価テンプレートを使用して、`examplerun` という名前の評価実行を開始します。  

```
aws inspector start-assessment-run --assessment-run-name examplerun --assessment-template-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T
```
出力:  

```
{
      "assessmentRunArn": "arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-jOoroxyY"
}
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartAssessmentRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/start-assessment-run.html)」を参照してください。

### `stop-assessment-run`
<a name="inspector_StopAssessmentRun_cli_2_topic"></a>

次のコード例は、`stop-assessment-run` を使用する方法を示しています。

**AWS CLI**  
**評価実行を停止するには**  
次の `stop-assessment-run` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-jOoroxyY` の評価実行を停止します。  

```
aws inspector stop-assessment-run --assessment-run-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-it5r2S4T/run/0-jOoroxyY
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopAssessmentRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/stop-assessment-run.html)」を参照してください。

### `subscribe-to-event`
<a name="inspector_SubscribeToEvent_cli_2_topic"></a>

次のコード例は、`subscribe-to-event` を使用する方法を示しています。

**AWS CLI**  
**イベントをサブスクライブするには**  
次の例では、`ASSESSMENT_RUN_COMPLETED` イベントに関する Amazon SNS 通知を ARN が `arn:aws:sns:us-west-2:123456789012:exampletopic` のトピックに送信するプロセスを有効にします。  

```
aws inspector subscribe-to-event \
    --event ASSESSMENT_RUN_COMPLETED \
    --resource-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0 \
    --topic-arn arn:aws:sns:us-west-2:123456789012:exampletopic
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Inspector* ガイド」の「[Amazon Inspector 評価テンプレートと評価実行](https://docs.aws.amazon.com/inspector/latest/userguide/inspector_assessments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SubscribeToEvent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/subscribe-to-event.html)」を参照してください。

### `unsubscribe-from-event`
<a name="inspector_UnsubscribeFromEvent_cli_2_topic"></a>

次のコード例は、`unsubscribe-from-event` を使用する方法を示しています。

**AWS CLI**  
**イベントからサブスクライブを解除するには**  
次の `unsubscribe-from-event` コマンドは、`ASSESSMENT_RUN_COMPLETED` イベントに関する Amazon SNS 通知を ARN が `arn:aws:sns:us-west-2:123456789012:exampletopic` のトピックに送信するプロセスを無効にします。  

```
aws inspector unsubscribe-from-event --event ASSESSMENT_RUN_COMPLETED --resource-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0 --topic arn:aws:sns:us-west-2:123456789012:exampletopic
```
詳細については、*Amazon Inspector* ガイドの 「Amazon Inspector 評価テンプレートと評価実行」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UnsubscribeFromEvent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/unsubscribe-from-event.html)」を参照してください。

### `update-assessment-target`
<a name="inspector_UpdateAssessmentTarget_cli_2_topic"></a>

次のコード例は、`update-assessment-target` を使用する方法を示しています。

**AWS CLI**  
**評価ターゲットを更新するには**  
次の `update-assessment-target` のコマンドは、ARN が `arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX` で名前が `Example` の評価ターゲットと ARN が `arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-yNbgL5Pt` のリソースグループを更新します。  

```
aws inspector update-assessment-target --assessment-target-arn arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX --assessment-target-name Example --resource-group-arn arn:aws:inspector:us-west-2:123456789012:resourcegroup/0-yNbgL5Pt
```
詳細については、「*Amazon Inspector* ガイド」の「Amazon Inspector 評価ターゲット」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAssessmentTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector/update-assessment-target.html)」を参照してください。

### `update-filter`
<a name="inspector2_UpdateFilter_cli_2_topic"></a>

次のコード例は、`update-filter` を使用する方法を示しています。

**AWS CLI**  
**フィルタを更新するには**  
次の `update-filter` の例では、ECR インスタンスの検出結果の代わりに Lambda の検出結果を省略するようにフィルターを更新します。  

```
aws inspector2 update-filter \
   --filter-arn "arn:aws:inspector2:us-west-2:123456789012:owner/o-EXAMPLE222/filter/EXAMPLE444444444" \
   --name "ExampleSuppressionRuleLambda" \
   --description "This suppression rule omits Lambda instance findings" \
   --reason "Updating filter to omit Lambda instance findings instead of ECR instance findings"
```
出力:  

```
{
    "filters": [
        {
            "action": "SUPPRESS",
            "arn": "arn:aws:inspector2:us-west-2:123456789012:owner/o-EXAMPLE222/filter/EXAMPLE444444444",
            "createdAt": "2024-05-15T21:28:27.054000+00:00",
            "criteria": {
                "resourceType": [
                    {
                        "comparison": "EQUALS",
                        "value": "AWS_ECR_INSTANCE"
                    }
                ]
            },
            "description": "This suppression rule omits Lambda instance findings",
            "name": "ExampleSuppressionRuleLambda",
            "ownerId": "o-EXAMPLE222",
            "reason": "Updating filter to omit Lambda instance findings instead of ECR instance findings",
            "tags": {},
            "updatedAt": "2024-05-15T22:23:13.665000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Inspector ユーザーガイド*」の「[Amazon Inspector での検出結果の管理](https://docs.aws.amazon.com/inspector/latest/user/findings-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/inspector2/update-filter.html)」を参照してください。

# AWS IoT を使用した の例 AWS CLI
<a name="cli_2_iot_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-certificate-transfer`
<a name="iot_AcceptCertificateTransfer_cli_2_topic"></a>

次の例は、`accept-certificate-transfer` を使用する方法を説明しています。

**AWS CLI**  
**別の AWS アカウントから転送されたデバイス証明書を受け入れるには**  
次の の`accept-certificate-transfer`例では、別の AWS アカウントから転送されたデバイス証明書を受け入れます。証明書は ID で識別されます。  

```
aws iot accept-certificate-transfer \
    --certificate-id 488b6a7f2acdeb00a77384e63c4e40b18bEXAMPLEe57b7272ba44c45e3448142
```
このコマンドでは、出力が生成されません。  
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[証明書を別のアカウントに転送する](https://docs.aws.amazon.com/iot/latest/developerguide/transfer-cert.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptCertificateTransfer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/accept-certificate-transfer.html)」を参照してください。

### `add-thing-to-billing-group`
<a name="iot_AddThingToBillingGroup_cli_2_topic"></a>

次のコード例は、`add-thing-to-billing-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: 請求グループにモノを名前で追加するには**  
次の `add-thing-to-billing-group` の例では、`MyLightBulb` という名前のモノを `GroupOne` という名前の請求グループに追加します。  

```
aws iot add-thing-to-billing-group \
    --billing-group-name GroupOne \
    --thing-name MyLightBulb
```
このコマンドでは何も出力されません。  
**例 2: 請求グループに ARN でモノを追加するには**  
次の `add-thing-to-billing-group` の例では、指定された ARN を持つモノを、指定された ARN を持つ請求グループに追加します。ARN の指定は、複数の AWS リージョンまたはアカウントを使用する場合に役立ちます。これにより、適切なリージョンとアカウントに追加できます。  

```
aws iot add-thing-to-thing-group \
    --billing-group-arn "arn:aws:iot:us-west-2:123456789012:billinggroup/GroupOne" \
    --thing-arn "arn:aws:iot:us-west-2:123456789012:thing/MyOtherLightBulb"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddThingToBillingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/add-thing-to-billing-group.html)」を参照してください。

### `add-thing-to-thing-group`
<a name="iot_AddThingToThingGroup_cli_2_topic"></a>

次のコード例は、`add-thing-to-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノをグループに追加するには**  
次の `add-thing-to-thing-group` の例では、指定されたモノを指定されたモノグループに追加します。  

```
aws iot add-thing-to-thing-group \
    --thing-name MyLightBulb \
    --thing-group-name LightBulbs
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddThingToThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/add-thing-to-thing-group.html)」を参照してください。

### `associate-targets-with-job`
<a name="iot_AssociateTargetsWithJob_cli_2_topic"></a>

次のコード例は、`associate-targets-with-job` を使用する方法を示しています。

**AWS CLI**  
**モノのグループを連続ジョブに関連付けるには**  
次の `associate-targets-with-job` の例では、指定されたモノのグループを指定された連続ジョブに関連付けます。  

```
aws iot associate-targets-with-job \
    --targets "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs" \
    --job-id "example-job-04"
```
出力:  

```
{
    "jobArn": "arn:aws:iot:us-west-2:123456789012:job/example-job-04",
    "jobId": "example-job-04",
    "description": "example continuous job"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateTargetsWithJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/associate-targets-with-job.html)」を参照してください。

### `attach-policy`
<a name="iot_AttachPolicy_cli_2_topic"></a>

次のコード例は、`attach-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: モノのグループにポリシーをアタッチするには**  
次の `attach-policy` の例では、指定されたポリシーを ARN で識別されるモノのグループにアタッチします。  

```
aws iot attach-policy \
    --target "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs" \
    --policy-name "UpdateDeviceCertPolicy"
```
このコマンドでは、出力が生成されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
**例 2: ポリシーを証明書にアタッチするには**  
次の `attach-policy` の例では、証明書で指定されたプリンシパルにポリシー `UpdateDeviceCertPolicy` をアタッチします。  

```
aws iot attach-policy \
    --policy-name UpdateDeviceCertPolicy \
    --target "arn:aws:iot:us-west-2:123456789012:cert/4f0ba725787aa94d67d2fca420eca022242532e8b3c58e7465c7778b443fd65e"
```
このコマンドでは、出力が生成されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「デバイス証明書に IoT ポリシーをアタッチ](https://docs.aws.amazon.com/iot/latest/developerguide/attach-policy-to-certificate.html)*AWS する IoT*」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[AttachPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-policy.html)」を参照してください。**

### `attach-security-profile`
<a name="iot_AttachSecurityProfile_cli_2_topic"></a>

次のコード例は、`attach-security-profile` を使用する方法を示しています。

**AWS CLI**  
**セキュリティプロファイルをすべての未登録のデバイスに関連付けるには**  
次の`attach-security-profile`例では、 という名前の AWS IoT Device Defender セキュリティプロファイルを`Testprofile`、この AWS アカウントの `us-west-2`リージョン内のすべての未登録デバイスと関連付けます。  

```
aws iot attach-security-profile \
    --security-profile-name Testprofile \
    --security-profile-target-arn "arn:aws:iot:us-west-2:123456789012:all/unregistered-things"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス」*の「[AttachSecurityProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-security-profile.html)」を参照してください。

### `attach-thing-principal`
<a name="iot_AttachThingPrincipal_cli_2_topic"></a>

次のコード例は、`attach-thing-principal` を使用する方法を示しています。

**AWS CLI**  
**モノに証明書をアタッチするには**  
次の `attach-thing-principal` 例では、MyTemperatureSensor モノに証明書をアタッチします。証明書は ARN によって識別されます。証明書の ARN は、 AWS IoT コンソールで確認できます。  

```
aws iot attach-thing-principal \
    --thing-name MyTemperatureSensor \
    --principal arn:aws:iot:us-west-2:123456789012:cert/2e1eb273792174ec2b9bf4e9b37e6c6c692345499506002a35159767055278e8
```
このコマンドでは何も出力されません。  
詳細については、「AWS IoT ディベロッパーガイド」の「[レジストリによるモノの管理方法](https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI  API リファレンス*」の「[AttachThingPrincipal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/attach-thing-principal.html)」を参照してください。

### `cancel-audit-mitigation-actions-task`
<a name="iot_CancelAuditMitigationActionsTask_cli_2_topic"></a>

次のコード例は、`cancel-audit-mitigation-actions-task` を使用する方法を示しています。

**AWS CLI**  
**監査緩和アクションタスクをキャンセルするには**  
次の `cancel-audit-mitigations-action-task` の例では、指定されたタスクの緩和アクションの適用をキャンセルします。すでに完了したタスクはキャンセルできません。  

```
aws iot cancel-audit-mitigation-actions-task
    --task-id "myActionsTaskId"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[CancelAuditMitigationActionsTask (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-CancelAuditMitigationActionsTask)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelAuditMitigationActionsTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-audit-mitigation-actions-task.html)」を参照してください。

### `cancel-audit-task`
<a name="iot_CancelAuditTask_cli_2_topic"></a>

次のコード例は、`cancel-audit-task` を使用する方法を示しています。

**AWS CLI**  
**監査タスクをキャンセルするには**  
次の `cancel-audit-task` の例では、指定されたタスク ID を持つ監査タスクをキャンセルします。完了したタスクをキャンセルできません。  

```
aws iot cancel-audit-task \
    --task-id a3aea009955e501a31b764abe1bebd3d
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelAuditTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-audit-task.html)」を参照してください。

### `cancel-certificate-transfer`
<a name="iot_CancelCertificateTransfer_cli_2_topic"></a>

次の例は、`cancel-certificate-transfer` を使用する方法を説明しています。

**AWS CLI**  
**別の AWS アカウントへの証明書の移管をキャンセルするには**  
次の `cancel-certificate-transfer` の例では、指定された証明書転送の転送をキャンセルします。証明書は証明書 ID によって識別されます。証明書の ID は、 AWS IoT コンソールで確認できます。  

```
aws iot cancel-certificate-transfer \
    --certificate-id f0f33678c7c9a046e5cc87b2b1a58dfa0beec26db78addd5e605d630e05c7fc8
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[証明書を別のアカウントに転送する](https://docs.aws.amazon.com/iot/latest/developerguide/transfer-cert.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelCertificateTransfer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-certificate-transfer.html)」を参照してください。

### `cancel-job-execution`
<a name="iot_CancelJobExecution_cli_2_topic"></a>

次のコード例は、`cancel-job-execution` を使用する方法を示しています。

**AWS CLI**  
**デバイスでジョブ実行をキャンセルするには**  
次の `cancel-job-execution` の例では、デバイスで指定されたジョブの実行をキャンセルします。ジョブが `QUEUED` の状態にない場合は、`--force` パラメータを追加する必要があります。  

```
aws iot cancel-job-execution \
    --job-id "example-job-03" \
    --thing-name "MyRPi"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelJobExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-job-execution.html)」を参照してください。

### `cancel-job`
<a name="iot_CancelJob_cli_2_topic"></a>

次のコード例は、`cancel-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブをキャンセルするには**  
以下の `cancel-job` の例では、指定したジョブをキャンセルします。  

```
aws iot cancel-job \
    --job-job "example-job-03"
```
出力:  

```
{
    "jobArn": "arn:aws:iot:us-west-2:123456789012:job/example-job-03",
    "jobId": "example-job-03",
    "description": "example job test"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/cancel-job.html)」を参照してください。

### `clear-default-authorizer`
<a name="iot_ClearDefaultAuthorizer_cli_2_topic"></a>

次のコード例は、`clear-default-authorizer` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのオーソライザーをクリアするには**  
次の `clear-default-authorizer` の例では、現在設定されているデフォルトのカスタムオーソライザーをクリアします。このコマンドを実行すると、デフォルトのオーソライザーはなくなります。カスタムオーソライザーを使用する場合は、HTTP リクエストヘッダーに名前で指定する必要があります。  

```
aws iot clear-default-authorizer
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[ClearDefaultAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_ClearDefaultAuthorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ClearDefaultAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/clear-default-authorizer.html)」を参照してください。

### `confirm-topic-rule-destination`
<a name="iot_ConfirmTopicRuleDestination_cli_2_topic"></a>

次のコード例は、`confirm-topic-rule-destination` を使用する方法を示しています。

**AWS CLI**  
**トピックルールの送信先を確認するには**  
次の `confirm-topic-rule-destination` の例では、HTTP エンドポイントで受信した確認トークンを使用してトピックルールの送信先を確認します。  

```
aws iot confirm-topic-rule-destination \
    --confirmation-token "AYADeIcmtq-ZkxfpiWIQqHWM5ucAXwABABVhd3MtY3J5cHRvLXB1YmxpYy1rZXkAREFxY1E0UmlGeDg0V21BZWZ1VjZtZWFRVUJJUktUYXJaN09OZlJOczJhRENSZmZYL3JHZC9PR3NNcis5T3ZlSitnQT09AAEAB2F3cy1rbXMAS2Fybjphd3M6a21zOnVzLWVhc3QtMTo5ODc5NTE4NTI0OTk6a2V5L2U4YmU3ODViLTU5NWMtNDcxYi1iOWJmLWQ2Y2I4ZjQxODlmNwC4AQIBAHhwz48UWTGWE1ua0P8U1hj27nsFzEaAdf6Hs2K_7wBheAF62zwMuk_A4dPiC6eyPGuMAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQM9vtRMpf9D3CiZ8sMAgEQgDuFd0Txy-aywpPqg8YEsa1lD4B40aJ2s1wEHKMybiF1RoOZzYisI0IvslzQY5UmCkqq3tV-3f7-nKfosgIAAAAADAAAEAAAAAAAAAAAAAAAAAAi9RMgy-V19V9m6Iw2xfbw_____wAAAAEAAAAAAAAAAAAAAAEAAAB1hw4SokgUcxiJ3gTO6n50NLJVpzyQR1UmPIj5sShqXEQGcOsWmXzpYOOx_PWyPVNsIFHApyK7Cc3g4bW8VaLVwOLkC83g6YaZAh7dFEl2-iufgrzTePl8RZYOWr0O6Aj9DiVzJZx-1iD6Pu-G6PUw1kaO7Knzs2B4AD0qfrHUF4pYRTvyUgBnMGUCMQC8ZRmhKqntd_c6Kgrow3bMUDBvNqo2qZr8Z8Jm2rzgseROlAnLgFLGpGShr99oSZkCMEd1v62NBRKX9HQXnybyF3fkg__-PIetJ803Z4IlIlF8xXlcdPGP-PV1dOXFemyL8g"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[トピックルールの送信先の確認](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html#confirm-destination)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmTopicRuleDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/confirm-topic-rule-destination.html)」を参照してください。

### `create-audit-suppression`
<a name="iot_CreateAuditSuppression_cli_2_topic"></a>

次のコード例は、`create-audit-suppression` を使用する方法を示しています。

**AWS CLI**  
**監査検出結果の抑制を作成するには**  
次の `create-audit-suppression` の例では、「virtualMachinePolicy」という名前のポリシーに対して、過度に許容されているというフラグが付けられた監査検出結果の抑制を作成します。  

```
aws iot create-audit-suppression \
    --check-name IOT_POLICY_OVERLY_PERMISSIVE_CHECK \
    --resource-identifier policyVersionIdentifier={"policyName"="virtualMachinePolicy","policyVersionId"="1"} \
    --no-suppress-indefinitely \
    --expiration-date 2020-10-20
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[監査の検出結果の抑制](https://docs.aws.amazon.com/iot/latest/developerguide/audit-finding-suppressions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAuditSuppression](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-audit-suppression.html)」を参照してください。

### `create-authorizer`
<a name="iot_CreateAuthorizer_cli_2_topic"></a>

次のコード例は、`create-authorizer` を使用する方法を示しています。

**AWS CLI**  
**カスタムオーソライザーを作成するには**  
次の `create-authorizer` の例では、カスタム認証サービスの一部として指定された Lambda 関数を使用するカスタムオーソライザーを作成します。  

```
   aws iot create-authorizer \
       --authorizer-name "CustomAuthorizer" \
       --authorizer-function-arn "arn:aws:lambda:us-west-2:123456789012:function:CustomAuthorizerFunction" \
       --token-key-name "MyAuthToken" \
       --status ACTIVE \
       --token-signing-public-keys FIRST_KEY="-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1uJOB4lQPgG/lM6ZfIwo
Z+7ENxAio9q6QD4FFqjGZsvjtYwjoe1RKK0U8Eq9xb5O3kRSmyIwTzwzm/f4Gf0Y
ZUloJ+t3PUUwHrmbYTAgTrCUgRFygjfgVwGCPs5ZAX4Eyqt5cr+AIHIiUDbxSa7p
zwOBKPeic0asNJpqT8PkBbRaKyleJh5oo81NDHHmVtbBm5A5YiJjqYXLaVAowKzZ
+GqsNvAQ9Jy1wI2VrEa1OfL8flDB/BJLm7zjpfPOHDJQgID0XnZwAlNnZcOhCwIx
50g2LW2Oy9R/dmqtDmJiVP97Z4GykxPvwlYHrUXY0iW1R3AR/Ac1NhCTGZMwVDB1
lQIDAQAB
-----END PUBLIC KEY-----"
```
出力:  

```
{
    "authorizerName": "CustomAuthorizer",
    "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer2"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[CreateAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateAuthorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-authorizer.html)」を参照してください。

### `create-billing-group`
<a name="iot_CreateBillingGroup_cli_2_topic"></a>

次のコード例は、`create-billing-group` を使用する方法を示しています。

**AWS CLI**  
**請求グループを作成するには**  
次の `create-billing-group` 例では、`GroupOne` という名前のシンプルな請求グループが作成されます。  

```
aws iot create-billing-group \
    --billing-group-name GroupOne
```
出力:  

```
{
    "billingGroupName": "GroupOne",
    "billingGroupArn": "arn:aws:iot:us-west-2:123456789012:billinggroup/GroupOne",
    "billingGroupId": "103de383-114b-4f51-8266-18f209ef5562"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBillingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-billing-group.html)」を参照してください。

### `create-certificate-from-csr`
<a name="iot_CreateCertificateFromCsr_cli_2_topic"></a>

次のコード例は、`create-certificate-from-csr` を使用する方法を示しています。

**AWS CLI**  
**証明書署名リクエスト (CSR) からデバイス証明書を作成するには**  
次の `create-certificate-from-csr` の例では、CSR からデバイス証明書を作成します。`openssl` コマンドを使用して、CSR を作成できます。  

```
aws iot create-certificate-from-csr \
    --certificate-signing-request=file://certificate.csr
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/c0c57bbc8baaf4631a9a0345c957657f5e710473e3ddbee1428d216d54d53ac9",
        "certificateId": "c0c57bbc8baaf4631a9a0345c957657f5e710473e3ddbee1428d216d54d53ac9",
        "certificatePem": "<certificate-text>"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[CreateCertificateFromCSR](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateCertificateFromCsr.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCertificateFromCsr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-certificate-from-csr.html)」を参照してください。

### `create-custom-metric`
<a name="iot_CreateCustomMetric_cli_2_topic"></a>

次のコード例は、`create-custom-metric` を使用する方法を示しています。

**AWS CLI**  
**デバイスが Device Defender に発行するカスタムメトリクスを作成するには**  
次の `create-custom-metric` の例では、バッテリーの割合を測定するカスタムメトリクスを作成します。  

```
aws iot create-custom-metric \
    --metric-name "batteryPercentage" \
    --metric-type "number" \
    --display-name "Remaining battery percentage." \
    --region us-east-1 \
    --client-request-token "02ccb92b-33e8-4dfa-a0c1-35b181ed26b0"
```
出力:  

```
{
    "metricName": "batteryPercentage",
    "metricArn": "arn:aws:iot:us-east-1:1234564789012:custommetric/batteryPercentage"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[カスタムメトリクス](https://docs.aws.amazon.com/iot/latest/developerguide/dd-detect-custom-metrics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomMetric](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-custom-metric.html)」を参照してください。

### `create-dimension`
<a name="iot_CreateDimension_cli_2_topic"></a>

次のコード例は、`create-dimension` を使用する方法を示しています。

**AWS CLI**  
**ディメンションを作成するには**  
次の `create-dimension` では、`TopicFilterForAuthMessages` という 1 つのトピックフィルターを使用してディメンションを作成します。  

```
aws iot create-dimension \
    --name TopicFilterForAuthMessages \
    --type TOPIC_FILTER \
    --string-values device/+/auth
```
出力:  

```
{
    "name": "TopicFilterForAuthMessages",
    "arn": "arn:aws:iot:eu-west-2:123456789012:dimension/TopicFilterForAuthMessages"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDimension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-dimension.html)」を参照してください。

### `create-domain-configuration`
<a name="iot_CreateDomainConfiguration_cli_2_topic"></a>

次のコード例は、`create-domain-configuration` を使用する方法を示しています。

**AWS CLI**  
**ドメイン設定を作成するには**  
次の`create-domain-configuration`例では、サービスタイプが の AWSマネージドドメイン設定を作成します`DATA`。  

```
aws iot create-domain-configuration \
    --domain-configuration-name "additionalDataDomain" \
    --service-type "DATA"
```
出力:  

```
{
    "domainConfigurationName": "additionalDataDomain",
    "domainConfigurationArn": "arn:aws:iot:us-west-2:123456789012:domainconfiguration/additionalDataDomain/dikMh"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[設定可能なエンドポイント](https://docs.aws.amazon.com/iot/latest/developerguide/iot-custom-endpoints-configurable-aws.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDomainConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-domain-configuration.html)」を参照してください。

### `create-dynamic-thing-group`
<a name="iot_CreateDynamicThingGroup_cli_2_topic"></a>

次のコード例は、`create-dynamic-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノの動的グループを作成するには**  
次の `create-dynamic-thing-group` の例では、60 度を超える温度属性を持つ任意のモノを含むモノの動的グループを作成します。モノの動的グループを使用する前に、 AWS IoT フリートインデックス作成を有効にする必要があります。  

```
aws iot create-dynamic-thing-group \
    --thing-group-name "RoomTooWarm" \
    --query-string "attributes.temperature>60"
```
出力:  

```
{
    "thingGroupName": "RoomTooWarm",
    "thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/RoomTooWarm",
    "thingGroupId": "9d52492a-fc87-43f4-b6e2-e571d2ffcad1",
    "indexName": "AWS_Things",
    "queryString": "attributes.temperature>60",
    "queryVersion": "2017-09-30"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」「[モノの動的グループ](https://docs.aws.amazon.com/iot/latest/developerguide/dynamic-thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDynamicThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-dynamic-thing-group.html)」を参照してください。

### `create-job`
<a name="iot_CreateJob_cli_2_topic"></a>

次のコード例は、`create-job` を使用する方法を示しています。

**AWS CLI**  
**例 1: ジョブを作成するには**  
次の`create-job`例では、`MyRaspberryPi`デバイスに JSON ドキュメントを送信する simple AWS IoT ジョブを作成します。  

```
aws iot create-job \
    --job-id "example-job-01" \
    --targets "arn:aws:iot:us-west-2:123456789012:thing/MyRaspberryPi" \
    --document file://example-job.json \
    --description "example job test" \
    --target-selection SNAPSHOT
```
出力:  

```
{
    "jobArn": "arn:aws:iot:us-west-2:123456789012:job/example-job-01",
    "jobId": "example-job-01",
    "description": "example job test"
}
```
**例 2: 連続ジョブを作成するには**  
次の `create-job` の例では、ターゲットとして指定されたモノがジョブを完了した後も実行し続けるジョブを作成します。この例では、ターゲットはモノのグループであるため、新しいデバイスがグループに追加されると、それらの新しいモノに対して連続ジョブが実行されます。  
aws iot create-job --job-id "example-job-04" --targets "arn:aws:iot:us-west-2:123456789012:thinggroup/DeadBulbs" --document file://example-job.json --description "example continuous job" --target-selection CONTINUOUS  
出力:  

```
{
    "jobArn": "arn:aws:iot:us-west-2:123456789012:job/example-job-04",
    "jobId": "example-job-04",
    "description": "example continuous job"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[CreateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-job.html)」を参照してください。

### `create-keys-and-certificate`
<a name="iot_CreateKeysAndCertificate_cli_2_topic"></a>

次のコード例は、`create-keys-and-certificate` を使用する方法を示しています。

**AWS CLI**  
**RSA キーペアを作成して X.509 証明書を発行するには**  
以下の `create-keys-and-certificate` は、2048 ビットの RSA キーペアを作成し、発行されたパブリックキーを使用して X.509 証明書を発行します。IoT がこの証明書のプライベートキー AWS IoT を提供するのは今回だけです。そのため、必ず安全な場所に保管してください。  

```
aws iot create-keys-and-certificate \
    --certificate-pem-outfile "myTest.cert.pem" \
    --public-key-outfile "myTest.public.key" \
    --private-key-outfile "myTest.private.key"
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/9894ba17925e663f1d29c23af4582b8e3b7619c31f3fbd93adcb51ae54b83dc2",
    "certificateId": "9894ba17925e663f1d29c23af4582b8e3b7619c31f3fbd93adcb51ae54b83dc2",
    "certificatePem": "
-----BEGIN CERTIFICATE-----
MIICiTCCEXAMPLE6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBAgEXAMPLEAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSEXAMPLE2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYEXAMPLEb20wHhcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCEXAMPLEJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDAEXAMPLEsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEXAMPLE25lQGFt
YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+aEXAMPLE
EXAMPLEfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZEXAMPLELG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
Ibb3OhjZnzcvQAEXAMPLEWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9qEXAMPLEyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDEXAMPLEBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----\n",
    "keyPair": {
        "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkEXAMPLEQEFAAOCAQ8AMIIBCgKCAQEAEXAMPLE1nnyJwKSMHw4h\nMMEXAMPLEuuN/dMAS3fyce8DW/4+EXAMPLEyjmoF/YVF/gHr99VEEXAMPLE5VF13\n59VK7cEXAMPLE67GK+y+jikqXOgHh/xJTwo+sGpWEXAMPLEDz18xOd2ka4tCzuWEXAMPLEahJbYkCPUBSU8opVkR7qkEXAMPLE1DR6sx2HocliOOLtu6Fkw91swQWEXAMPLE\GB3ZPrNh0PzQYvjUStZeccyNCx2EXAMPLEvp9mQOUXP6plfgxwKRX2fEXAMPLEDa\nhJLXkX3rHU2xbxJSq7D+XEXAMPLEcw+LyFhI5mgFRl88eGdsAEXAMPLElnI9EesG\nFQIDAQAB\n-----END PUBLIC KEY-----\n",
        "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nkey omittted for security reasons\n-----END RSA PRIVATE KEY-----\n"
    }
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT デバイス証明書の作成と登録](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-create.html)」を参照してください。 **AWS IoT **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateKeysAndCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-keys-and-certificate.html)」を参照してください。

### `create-mitigation-action`
<a name="iot_CreateMitigationAction_cli_2_topic"></a>

次のコード例は、`create-mitigation-action` を使用する方法を示しています。

**AWS CLI**  
**緩和アクションを作成するには**  
次の `create-mitigation-action` の例では、`AddThingsToQuarantineGroup1Action` という名前の緩和アクションを定義しています。この緩和アクションを適用すると、モノは `QuarantineGroup1` という名前のモノのグループに移動します。このアクションは、モノの動的グループをオーバーライドします。  

```
aws iot create-mitigation-action --cli-input-json file::params.json
```
`params.json` の内容:  

```
{
    "actionName": "AddThingsToQuarantineGroup1Action",
    "actionParams": {
        "addThingsToThingGroupParams": {
            "thingGroupNames": [
                "QuarantineGroup1"
            ],
            "overrideDynamicGroups": true
        }
    },
    "roleArn": "arn:aws:iam::123456789012:role/service-role/MoveThingsToQuarantineGroupRole"
}
```
出力:  

```
{
    "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/AddThingsToQuarantineGroup1Action",
    "actionId": "992e9a63-a899-439a-aa50-4e20c52367e1"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[CreateMitigationAction (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/iot/latest/developerguide/iot/latest/developerguide/mitigation-action-commands.html.html#dd-api-iot-CreateMitigationAction)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMitigationAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-mitigation-action.html)」を参照してください。

### `create-ota-update`
<a name="iot_CreateOtaUpdate_cli_2_topic"></a>

次のコード例は、`create-ota-update` を使用する方法を示しています。

**AWS CLI**  
**Amazon FreeRTOS で使用する OTA 更新を作成するには**  
次の`create-ota-update`例では、モノまたはグループのターゲットグループに AWS IoT OTAUpdate を作成します。これは Amazon FreeRTOS の無線通信更新の一部であり、新しいファームウェアイメージを単一のデバイスまたはデバイスのグループにデプロイできます。  

```
aws iot create-ota-update \
    --cli-input-json file://create-ota-update.json
```
`create-ota-update.json` の内容:  

```
{
    "otaUpdateId": "ota12345",
    "description": "A critical update needed right away.",
    "targets": [
        "device1",
        "device2",
        "device3",
        "device4"
    ],
    "targetSelection": "SNAPSHOT",
    "awsJobExecutionsRolloutConfig": {
        "maximumPerMinute": 10
    },
    "files": [
        {
          "fileName": "firmware.bin",
          "fileLocation": {
            "stream": {
              "streamId": "004",
              "fileId":123
            }
          },
          "codeSigning": {
            "awsSignerJobId": "48c67f3c-63bb-4f92-a98a-4ee0fbc2bef6"
          }
        }
    ]
    "roleArn": "arn:aws:iam:123456789012:role/service-role/my_ota_role"
}
```
出力:  

```
{
     "otaUpdateId": "ota12345",
     "awsIotJobId": "job54321",
     "otaUpdateArn": "arn:aws:iot:us-west-2:123456789012:otaupdate/itsaupdate",
     "awsIotJobArn": "arn:aws:iot:us-west-2:123456789012:job/itsajob",
     "otaUpdateStatus": "CREATE_IN_PROGRESS"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[CreateOTAUpdate](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateOTAUpdate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateOtaUpdate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-ota-update.html)」を参照してください。

### `create-policy-version`
<a name="iot_CreatePolicyVersion_cli_2_topic"></a>

次のコード例は、`create-policy-version` を使用する方法を示しています。

**AWS CLI**  
**ポリシーを新しいバージョンで更新するには**  
次の `create-policy-version` の例では、ポリシー定義を更新し、新しいポリシーバージョンを作成します。また、この例では新しいバージョンをデフォルトにします。  

```
aws iot create-policy-version \
    --policy-name UpdateDeviceCertPolicy \
    --policy-document file://policy.json \
    --set-as-default
```
`policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action":  "iot:UpdateCertificate",
            "Resource": "*"
        }
    ]
}
```
出力:  

```
{
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/UpdateDeviceCertPolicy",
    "policyDocument": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Action\":  \"iot:UpdateCertificate\", \"Resource\": \"*\" } ] }",
    "policyVersionId": "2",
    "isDefaultVersion": true
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-policy-version.html)」を参照してください。

### `create-policy`
<a name="iot_CreatePolicy_cli_2_topic"></a>

次の例は、`create-policy` を使用する方法を説明しています。

**AWS CLI**  
** AWS IoT ポリシーを作成するには**  
次の`create-policy`例では、 TemperatureSensorPolicy という名前の AWS IoT ポリシーを作成します。`policy.json` ファイルには、 AWS IoT ポリシーアクションを許可するステートメントが含まれています。  

```
aws iot create-policy \
    --policy-name TemperatureSensorPolicy \
    --policy-document file://policy.json
```
`policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "iot:Publish",
                "iot:Receive"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topic/topic_1",
                "arn:aws:iot:us-west-2:123456789012:topic/topic_2"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Subscribe"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:topicfilter/topic_1",
                "arn:aws:iot:us-west-2:123456789012:topicfilter/topic_2"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "iot:Connect"
            ],
            "Resource": [
                "arn:aws:iot:us-west-2:123456789012:client/basicPubSub"
            ]
        }
    ]
}
```
出力:  

```
{
    "policyName": "TemperatureSensorPolicy",
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/TemperatureSensorPolicy",
    "policyDocument": "{
        \"Version\": \"2012-10-17\",
        \"Statement\": [
            {
                \"Effect\": \"Allow\",
                \"Action\": [
                    \"iot:Publish\",
                    \"iot:Receive\"
                ],
                \"Resource\": [
                    \"arn:aws:iot:us-west-2:123456789012:topic/topic_1\",
                    \"arn:aws:iot:us-west-2:123456789012:topic/topic_2\"
                ]
            },
            {
                \"Effect\": \"Allow\",
                \"Action\": [
                    \"iot:Subscribe\"
                ],
                \"Resource\": [
                    \"arn:aws:iot:us-west-2:123456789012:topicfilter/topic_1\",
                    \"arn:aws:iot:us-west-2:123456789012:topicfilter/topic_2\"
                ]
            },
            {
                \"Effect\": \"Allow\",
                \"Action\": [
                    \"iot:Connect\"
                ],
                \"Resource\": [
                    \"arn:aws:iot:us-west-2:123456789012:client/basicPubSub\"
                ]
            }
        ]
    }",
    "policyVersionId": "1"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-policy.html)」を参照してください。

### `create-provisioning-claim`
<a name="iot_CreateProvisioningClaim_cli_2_topic"></a>

次のコード例は、`create-provisioning-claim` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングクレームを作成するには**  
次の `create-provisioning-claim` の例では、プロビジョニングテンプレートからプロビジョニングクレームを作成します。  

```
aws iot create-provisioning-claim \
    --template-name MyTestProvisioningTemplate
```
出力:  

```
{
    "certificateId": "78de02184b2ce80cf8fb709bda59e62b19fb83513590483eb0434589476ab09f",
    "certificatePem": "-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIUXSZhEBLztMLZ2fHG
14gV0NymYY0wDQYJKoZIhvcNAQEL\nBQAwfjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBg
VBAcM\nB1NlYXR0bGUxGDAWBgNVBAoMD0FtYXpvbi5jb20gSW5jLjEgMB4GA1UECwwXQW1h\nem9uIElvVCBQcm9
2aXNpb25pbmcxDDAKBgNVBAUTAzEuMDAeFw0yMDA3MjgxNjQ0\nMDZaFw0yMDA3MjgxNjUxMDZaMEsxSTBHBgNVB
AMMQDFhNDEyM2VkNmIxYjU3MzE3\nZTgzMTJmY2MzN2FiNTdhY2MzYTZkZGVjOGQ5OGY3NzUwMWRlMjc0YjhmYTQ
xN2Iw\nggEiMA0GCSqGSIb3EXAMPLEAA4IBDwAwggEKAoIBAQDBhKI94ktKLqTwnj+ayOq1\nTAJt/N6s6IJDZvl
rYjkC0E7wzaeY3TprWk03S29vUzVuEOXHXQXZbihgpg2m6fza\nkWm9/wpjzE9ny5+xkPGVH4Wnwz7yK5m8S0agL
T96cRBSWnWmonOWdY0GKVzni0CA\n+iyGudgrFKm7Eae/v18oXrf82KtOAGO4xG0KE2WKYHsT1fx3c9xZhlXP/eX
Lhv00\n+lGp0WVw9PbhKfrxliKJ5q6sL5nVUaUHq6hlQPYwsATeOvAp3u0ak5zgTyL0fg7Y\nPyKk6VYwLW62r+V
YBSForEMOAhkq3LsP/rjxpEKmi2W4lPVS6oFZRKcD+H1Kyil5\nAgMBAAGjIDAeMAwGA1UdEwEB/wQCMAAwDgYDV
R0PAQH/BAQDAgeAMA0GCSqGSIb3\nDQEBCwUAA4IBAQAGgix2k6nVqbZFKq97/fZBzLGS0dyz5rT/E41cDIRX+1j
EPW41\nw0D+2sXheCZLZZnSkvIiP74IToNeXDrjdcaodeGFVHIElRjhMIq+4ZebPbRLtidF\nRc2hfcTAlqq9Z6v
5Vk6BeM1tu0RqH1wPoVUccLPya8EjNCbnJZUmGdOfrN/Y9pho\n5ikV+HPeZhG/k6dhE2GsQJyKFVHL/uBgKSily
1bRyWU1r6qcpWBNBHjUoD7HgOwD\nnzMh4XRb2FQDsqFalkCSYmeL8IVC49sgPD9Otyp5uteGMTy62usAAUQdq/f
ZvrWg\nOkFpwMVnGKVKT7Kg0kKOLzKWOBB2Jm4/gmrJ\n-----END CERTIFICATE-----\n",
    "keyPair": {
        "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCg
KCAQEAwYSiPeJLSi6k8J4/msjq\ntUwCbfzerOiCQ2b5a2I5AtBO8M2nmN06a1pNN0tvb1M1bhDlx10F2W4oYKYN
pun8\n2pFpvf8KY8xPZ8ufsZDxlR+Fp8M+8iuZvEtGoC0/enEQUlp1pqJzlnWNBilc54tA\ngPoshrnYKxSpuxGn
v79fKF63/NirTgBjuMRtChNlimEXAMPLE3PcWYZVz/3ly4b9\nNPpRqdFlcPT24Sn68ZYiieaurC+Z1VGlB6uoZU
D2MLAE3jrwKd7tGpOc4E8i9H4O\n2D8ipOlWMC1utq/lWAUhaKxDDgIZKty7D/648aRCpotluJT1UuqBWUSnA/h9
Ssop\neQIDAQAB\n-----END PUBLIC KEY-----\n",
        "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAwYSiPeJLSi6k8J4/
msjqtUwCbfzerOiCQ2b5a2I5AtBO8M2n\nmN06a1pNN0tvb1M1bhDlx10F2W4oYKYNpun82pFpvf8KY8xPZ8ufsZ
DxlR+Fp8M+\n8iuZvEtGoC0/enEQUlp1pqJzlnWNBilc54tAgPoshrnYKxSpuxGnv79fKF63/Nir\nTgBjuMRtCh
NlimB7E9X8d3PcWYZVz/3ly4b9NPpRqdFlcPT24Sn68ZYiieaurC+Z\n1VGlB6uoZUD2MLAE3jrwKd7tGpOc4E8i
9H4O2D8ipOlWMC1utq/lWAUhaKxDDgIZ\nKty7D/648aRCpotluJT1UuqBWUSnA/h9SsopeQIDAQABAoIBAEAybN
QUtx9T2/nK\ntZT2pA4iugecxI4dz+DmT0XVXs5VJmrx/nBSq6ejXExEpSIMO4RY7LE3ZdJcnd56\nF7tQkkY7yR
VzfxHeXFU1krOIPuxWebNOrRoPZr+1RSer+wv2aBC525+88pVuR6tM\nm3pgkrR2ycCj9FdOUoQxdjHBHaM5PDmJ
9aSxCKdg3nReepeGwsR2TQA+m2vVxWk7\nou0+91eTOP+/QfP7P8ZjOIkO2XivlRcVDyN/E4QXPKuIkM/8vS8VK+
E9pATQ0MtB\n2lw8R/YU5AJd6jlEXAMPLEGU2UzRzInNWiLtkPPPqgqXXhxOf+mxByjcMalVJk0L\nhOG2ROUCgY
EA+ROcHNHy/XbsP7FihOhEh+6Q2QxQ2ncBUPYbBazrR8Hn+7SCICQK\nVyYfd8Ajfq3e7RsKVL5SlMBp7Slidxak
bIn28fKfPn62DaemGCIoyDgLpF+eUxBx\ngzbCiBZga8brfurza43UZjKZLpg3hq721+FeAiXi1Nma4Yr9YWEHEN
8CgYEAxuWt\npzdWWmsiFzfsAw0sy9ySDA/xr5WRWzJyAqUsjsks6rxNzWebpufnYHcmtW7pLdqM\nkboHwN2pXa
kmZvrk2nKkEMq5brBYGDXuxDe+V369Bianx8aZFyIsckA7OwXW1w1h\ngRC5rQ4XOgp3+Jmw7eAO8LRYDjaN846+
QbtO2KcCgYAWS0UL51bijQR0ZwI0dz27\nFQVuCAYsp748aurcRTACCj8jbnK/QbqTNlxWsaH7ssBjZKo2D5sAqY
BRtASWODab\naHXsDhVm2Jye+ESLoHMaCLoyCkT3ll8yqXIcEDStMO7fO1Ryag164EiJvSIrMfny\nNL/fXVjCSH
/udCxdzPt+7QKBgQC+LAD7rxdr4J9538hTqpc4XK9vxRbrMXEH55XH\nHbMa2xONZXpmeTgEQBukyohCVceyRhK9
i0e6irZTjVXghOeoTpC8VXkzcnzouTiQ\neFQQSGfnp7Ioe6UIz23715pKduzSNkMSKrG924ktv7CyDBF1gBQI5g
aDoHnddJBJ\nPRTIZQKBgA8MASXtTxQntRwXXzR92U0vAighiuRkB/mx9jQpUcK1qiqHbkAMqgNF\nPFCBYIUbFT
iYKKKeJNbyJQvjfsJCkAnaFJ+RnTxk0Q6Wjm20peJ/ii4QiDdnigoE\nvdlc5cFQewWb4/zqAtPdinkPlN94ileI
79XQdc7RlJ0jpgTimL+V\n-----END RSA PRIVATE KEY-----\n"
    },
    "expiration": 1595955066.0
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[信頼できるユーザーによるプロビジョニング](https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html#trusted-user)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProvisioningClaim](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-provisioning-claim.html)」を参照してください。

### `create-provisioning-template-version`
<a name="iot_CreateProvisioningTemplateVersion_cli_2_topic"></a>

次のコード例は、`create-provisioning-template-version` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートバージョンを作成するには**  
次の例では、指定されたプロビジョニングテンプレートのバージョンを作成します。新しいバージョンの本文は `template.json` ファイルに記載されています。  

```
aws iot create-provisioning-template-version \
    --template-name widget-template \
    --template-body file://template.json
```
`template.json` の内容:  

```
{
    "Parameters" : {
        "DeviceLocation": {
            "Type": "String"
        }
    },
    "Mappings": {
        "LocationTable": {
            "Seattle": {
                "LocationUrl": "https://example.aws"
            }
        }
    },
    "Resources" : {
        "thing" : {
            "Type" : "AWS::IoT::Thing",
            "Properties" : {
                "AttributePayload" : {
                    "version" : "v1",
                    "serialNumber" : "serialNumber"
                },
                "ThingName" : {"Fn::Join":["",["ThingPrefix_",{"Ref":"SerialNumber"}]]},
                "ThingTypeName" : {"Fn::Join":["",["ThingTypePrefix_",{"Ref":"SerialNumber"}]]},
                "ThingGroups" : ["widgets", "WA"],
                "BillingGroup": "BillingGroup"
            },
            "OverrideSettings" : {
                "AttributePayload" : "MERGE",
                "ThingTypeName" : "REPLACE",
                "ThingGroups" : "DO_NOTHING"
            }
        },
        "certificate" : {
            "Type" : "AWS::IoT::Certificate",
            "Properties" : {
                "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
                "Status" : "Active"
            }
        },
        "policy" : {
            "Type" : "AWS::IoT::Policy",
            "Properties" : {
                "PolicyDocument" : {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [{
                        "Effect": "Allow",
                        "Action":["iot:Publish"],
                        "Resource": ["arn:aws:iot:us-east-1:123456789012:topic/foo/bar"]
                    }]
                }
            }
        }
    },
    "DeviceConfiguration": {
        "FallbackUrl": "https://www.example.com/test-site",
        "LocationUrl": {
            "Fn::FindInMap": ["LocationTable",{"Ref": "DeviceLocation"}, "LocationUrl"]}
        }
    }
}
```
出力:  

```
{
    "templateArn": "arn:aws:iot:us-east-1:123456789012:provisioningtemplate/widget-template",
    "templateName": "widget-template",
    "versionId": 2,
    "isDefaultVersion": false
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[AWS セキュアトンネリング](https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProvisioningTemplateVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-provisioning-template-version.html)」を参照してください。

### `create-provisioning-template`
<a name="iot_CreateProvisioningTemplate_cli_2_topic"></a>

次のコード例は、`create-provisioning-template` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートを作成するには**  
次の `create-provisioning-template` の例では、`template.json` ファイルで定義されるプロビジョニングテンプレートを作成します。  

```
aws iot create-provisioning-template \
    --template-name widget-template \
    --description "A provisioning template for widgets" \
    --provisioning-role-arn arn:aws:iam::123456789012:role/Provision_role \
    --template-body file://template.json
```
`template.json` の内容:  

```
{
    "Parameters" : {
        "DeviceLocation": {
            "Type": "String"
        }
    },
    "Mappings": {
        "LocationTable": {
            "Seattle": {
                "LocationUrl": "https://example.aws"
            }
        }
    },
    "Resources" : {
        "thing" : {
            "Type" : "AWS::IoT::Thing",
            "Properties" : {
                "AttributePayload" : {
                    "version" : "v1",
                    "serialNumber" : "serialNumber"
                },
                "ThingName" : {"Fn::Join":["",["ThingPrefix_",{"Ref":"SerialNumber"}]]},
                "ThingTypeName" : {"Fn::Join":["",["ThingTypePrefix_",{"Ref":"SerialNumber"}]]},
                "ThingGroups" : ["widgets", "WA"],
                "BillingGroup": "BillingGroup"
            },
            "OverrideSettings" : {
                "AttributePayload" : "MERGE",
                "ThingTypeName" : "REPLACE",
                "ThingGroups" : "DO_NOTHING"
            }
        },
        "certificate" : {
            "Type" : "AWS::IoT::Certificate",
            "Properties" : {
                "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
                "Status" : "Active"
            }
        },
        "policy" : {
            "Type" : "AWS::IoT::Policy",
            "Properties" : {
                "PolicyDocument" : {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [{
                        "Effect": "Allow",
                        "Action":["iot:Publish"],
                        "Resource": ["arn:aws:iot:us-east-1:504350838278:topic/foo/bar"]
                    }]
                }
            }
        }
    },
    "DeviceConfiguration": {
        "FallbackUrl": "https://www.example.com/test-site",
        "LocationUrl": {
            "Fn::FindInMap": ["LocationTable",{"Ref": "DeviceLocation"}, "LocationUrl"]}
        }
    }
}
```
出力:  

```
{
    "templateArn": "arn:aws:iot:us-east-1:123456789012:provisioningtemplate/widget-template",
    "templateName": "widget-template",
    "defaultVersionId": 1
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[AWS セキュアトンネリング](https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProvisioningTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-provisioning-template.html)」を参照してください。

### `create-role-alias`
<a name="iot_CreateRoleAlias_cli_2_topic"></a>

次のコード例は、`create-role-alias` を使用する方法を示しています。

**AWS CLI**  
**ロールエイリアスを作成するには**  
次の `create-role-alias` の例では、指定されたロールに `LightBulbRole` というロールエイリアスを作成します。  

```
aws iot create-role-alias \
    --role-alias LightBulbRole \
    --role-arn arn:aws:iam::123456789012:role/lightbulbrole-001
```
出力:  

```
{
    "roleAlias": "LightBulbRole",
    "roleAliasArn": "arn:aws:iot:us-west-2:123456789012:rolealias/LightBulbRole"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[CreateRoleAlias](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateRoleAlias.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoleAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-role-alias.html)」を参照してください。

### `create-scheduled-audit`
<a name="iot_CreateScheduledAudit_cli_2_topic"></a>

次のコード例は、`create-scheduled-audit` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされた監査を作成するには**  
次の `create-scheduled-audit` の例では、CA 証明書またはデバイス証明書の有効期限が切れているかどうかを確認するために、毎週水曜日に実行されるスケジュールされた監査を作成します。  

```
aws iot create-scheduled-audit \
    --scheduled-audit-name WednesdayCertCheck \
    --frequency WEEKLY \
    --day-of-week WED \
    --target-check-names CA_CERTIFICATE_EXPIRING_CHECK DEVICE_CERTIFICATE_EXPIRING_CHECK
```
出力:  

```
{
    "scheduledAuditArn": "arn:aws:iot:us-west-2:123456789012:scheduledaudit/WednesdayCertCheck"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateScheduledAudit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-scheduled-audit.html)」を参照してください。

### `create-security-profile`
<a name="iot_CreateSecurityProfile_cli_2_topic"></a>

次のコード例は、`create-security-profile` を使用する方法を示しています。

**AWS CLI**  
**セキュリティプロファイルを作成するには**  
次の `create-security-profile` の例では、セルラー帯域幅がしきい値を超えているか、または 5 分以内に 10 件を超える認証失敗が発生したかを確認するセキュリティプロファイルを作成します。  

```
aws iot create-security-profile \
    --security-profile-name PossibleIssue \
    --security-profile-description "Check to see if authorization fails 10 times in 5 minutes or if cellular bandwidth exceeds 128"  \
    --behaviors "[{\"name\":\"CellularBandwidth\",\"metric\":\"aws:message-byte-size\",\"criteria\":{\"comparisonOperator\":\"greater-than\",\"value\":{\"count\":128},\"consecutiveDatapointsToAlarm\":1,\"consecutiveDatapointsToClear\":1}},{\"name\":\"Authorization\",\"metric\":\"aws:num-authorization-failures\",\"criteria\":{\"comparisonOperator\":\"less-than\",\"value\":{\"count\":10},\"durationSeconds\":300,\"consecutiveDatapointsToAlarm\":1,\"consecutiveDatapointsToClear\":1}}]"
```
出力:  

```
{
    "securityProfileName": "PossibleIssue",
    "securityProfileArn": "arn:aws:iot:us-west-2:123456789012:securityprofile/PossibleIssue"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSecurityProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-security-profile.html)」を参照してください。

### `create-stream`
<a name="iot_CreateStream_cli_2_topic"></a>

次のコード例は、`create-stream` を使用する方法を示しています。

**AWS CLI**  
**MQTT を介して 1 つ以上の大きなファイルをチャンクで配信するためのストリームを作成するには**  
次の `create-stream` の例では、MQTT を介して 1 つ以上の大きなファイルをチャンクで配信するためのストリームを作成します。ストリームは、S3 のような送信元から MQTT メッセージとしてパッケージ化されたチャンクまたはブロックのデータバイトを転送します。1 つ以上のファイルをストリームに関連付けることができます。  

```
aws iot create-stream \
    --cli-input-json file://create-stream.json
```
`create-stream.json` の内容:  

```
{
    "streamId": "stream12345",
    "description": "This stream is used for Amazon FreeRTOS OTA Update 12345.",
    "files": [
        {
            "fileId": 123,
            "s3Location": {
                "bucket":"codesign-ota-bucket",
                "key":"48c67f3c-63bb-4f92-a98a-4ee0fbc2bef6"
            }
        }
    ],
    "roleArn": "arn:aws:iam:123456789012:role/service-role/my_ota_stream_role"
}
```
出力:  

```
{
     "streamId": "stream12345",
     "streamArn": "arn:aws:iot:us-west-2:123456789012:stream/stream12345",
     "description": "This stream is used for Amazon FreeRTOS OTA Update 12345.",
     "streamVersion": "1"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[CreateStream](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateStream.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-stream.html)」を参照してください。**

### `create-thing-group`
<a name="iot_CreateThingGroup_cli_2_topic"></a>

次のコード例は、`create-thing-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: モノのグループを作成するには**  
次の `create-thing-group` の例では、説明と 2 つの属性を持つ `LightBulbs` という名前のモノのグループを作成します。  

```
aws iot create-thing-group \
    --thing-group-name LightBulbs \
    --thing-group-properties "thingGroupDescription=\"Generic bulb group\", attributePayload={attributes={Manufacturer=AnyCompany,wattage=60}}"
```
出力:  

```
{
    "thingGroupName": "LightBulbs",
    "thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs",
    "thingGroupId": "9198bf9f-1e76-4a88-8e8c-e7140142c331"
}
```
**例 2: 親グループの一部であるモノのグループを作成するには**  
次の `create-thing-group` は、`LightBulbs` という名前の親モノグループを持つ `HalogenBulbs` という名前のモノグループを作成します。  

```
aws iot create-thing-group \
    --thing-group-name HalogenBulbs \
    --parent-group-name LightBulbs
```
出力:  

```
{
    "thingGroupName": "HalogenBulbs",
    "thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/HalogenBulbs",
    "thingGroupId": "f4ec6b84-b42b-499d-9ce1-4dbd4d4f6f6e"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-thing-group.html)」を参照してください。

### `create-thing-type`
<a name="iot_CreateThingType_cli_2_topic"></a>

次のコード例は、`create-thing-type` を使用する方法を示しています。

**AWS CLI**  
**モノのタイプを定義するには**  
次の `create-thing-type` の例では、モノのタイプと関連する属性を定義します。  

```
aws iot create-thing-type \
    --thing-type-name "LightBulb" \
    --thing-type-properties "thingTypeDescription=light bulb type, searchableAttributes=wattage,model"
```
出力:  

```
{
    "thingTypeName": "LightBulb",
    "thingTypeArn": "arn:aws:iot:us-west-2:123456789012:thingtype/LightBulb",
    "thingTypeId": "ce3573b0-0a3c-45a7-ac93-4e0ce14cd190"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」「[モノのタイプ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateThingType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-thing-type.html)」を参照してください。

### `create-thing`
<a name="iot_CreateThing_cli_2_topic"></a>

次のコード例は、`create-thing` を使用する方法を示しています。

**AWS CLI**  
**例 1: レジストリにモノのレコードを作成するには**  
次の`create-thing`例では、 AWS IoT モノレジストリにデバイスのエントリを作成します。  

```
aws iot create-thing \
    --thing-name SampleIoTThing
```
出力:  

```
{
    "thingName": "SampleIoTThing",
    "thingArn": "arn:aws:iot:us-west-2: 123456789012:thing/SampleIoTThing",
    "thingId": " EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE "
}
```
**例 2: モノのタイプに関連付けられているモノを定義するには**  
次の `create-thing` 例では、指定されたモノのタイプとその属性を持つモノを作成します。  

```
aws iot create-thing \
    --thing-name "MyLightBulb" \
    --thing-type-name "LightBulb" \
    --attribute-payload "{"attributes": {"wattage":"75", "model":"123"}}"
```
出力:  

```
{
    "thingName": "MyLightBulb",
    "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyLightBulb",
    "thingId": "40da2e73-c6af-406e-b415-15acae538797"
}
```
詳細については、「*AWS IoT ディベロッパーガイド*」の「[レジストリによるモノの管理方法](https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html)」と「[モノのタイプ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-thing.html)」を参照してください。

### `create-topic-rule-destination`
<a name="iot_CreateTopicRuleDestination_cli_2_topic"></a>

次のコード例は、`create-topic-rule-destination` を使用する方法を示しています。

**AWS CLI**  
**トピックルールの送信先を作成するには**  
次の `create-topic-rule-destination` の例では、HTTP エンドポイントのトピックルールの送信先を作成します。  

```
aws iot create-topic-rule-destination \
    --destination-configuration httpUrlConfiguration={confirmationUrl=https://example.com}
```
出力:  

```
{
    "topicRuleDestination": {
        "arn": "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "status": "IN_PROGRESS",
        "statusReason": "Awaiting confirmation. Confirmation message sent on 2020-07-09T22:47:54.154Z; no response received from the endpoint.",
        "httpUrlProperties": {
            "confirmationUrl": "https://example.com"
        }
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[トピックルールの送信先の作成](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html#create-destination)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTopicRuleDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-topic-rule-destination.html)」を参照してください。

### `create-topic-rule`
<a name="iot_CreateTopicRule_cli_2_topic"></a>

次のコード例は、`create-topic-rule` を使用する方法を示しています。

**AWS CLI**  
**Amazon SNS アラートを送信するルールを作成するには**  
次の`create-topic-rule` 例では、デバイスシャドウにある土壌湿度レベルの読み取り値が低くなったときに Amazon SNS メッセージを送信するルールを作成します。  

```
aws iot create-topic-rule \
    --rule-name "LowMoistureRule" \
    --topic-rule-payload file://plant-rule.json
```
この例では、次の JSON コードを `plant-rule.json` という名前のファイルに保存する必要があります。  

```
{
    "sql": "SELECT * FROM '$aws/things/MyRPi/shadow/update/accepted' WHERE state.reported.moisture = 'low'\n",
    "description": "Sends an alert whenever soil moisture level readings are too low.",
    "ruleDisabled": false,
    "awsIotSqlVersion": "2016-03-23",
    "actions": [{
            "sns": {
                "targetArn": "arn:aws:sns:us-west-2:123456789012:MyRPiLowMoistureTopic",
                "roleArn": "arn:aws:iam::123456789012:role/service-role/MyRPiLowMoistureTopicRole",
                "messageFormat": "RAW"
            }
    }]
}
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「Creating anIoT Rule](https://docs.aws.amazon.com/iot/latest/developerguide/iot-create-rule.html)*AWS IoT*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTopicRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/create-topic-rule.html)」を参照してください。

### `delete-account-audit-configuration`
<a name="iot_DeleteAccountAuditConfiguration_cli_2_topic"></a>

次の例は、`delete-account-audit-configuration` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのすべての監査チェックを無効にするには**  
次の の`delete-account-audit-configuration`例では、このアカウントの AWS IoT Device Defender のデフォルト設定を復元し、すべての監査チェックを無効にして設定データを消去します。また、このアカウントのスケジュールされた監査も削除されます。**このコマンドは注意して使用してください。**  

```
aws iot delete-account-audit-configuration \
    --delete-scheduled-audits
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccountAuditConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-account-audit-configuration.html)」を参照してください。

### `delete-audit-suppression`
<a name="iot_DeleteAuditSuppression_cli_2_topic"></a>

次のコード例は、`delete-audit-suppression` を使用する方法を示しています。

**AWS CLI**  
**監査検出結果の抑制を削除するには**  
次の `delete-audit-suppression` の例では、DEVICE\$1CERTIFICATE\$1EXPIRING\$1CHECK の監査結果の抑制を削除します。  

```
aws iot delete-audit-suppression \
    --check-name DEVICE_CERTIFICATE_EXPIRING_CHECK \
    --resource-identifier deviceCertificateId="c7691e<shortened>"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[監査の検出結果の抑制](https://docs.aws.amazon.com/iot/latest/developerguide/audit-finding-suppressions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAuditSuppression](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-audit-suppression.html)」を参照してください。

### `delete-authorizer`
<a name="iot_DeleteAuthorizer_cli_2_topic"></a>

次のコード例は、`delete-authorizer` を使用する方法を示しています。

**AWS CLI**  
**カスタムオーソライザーを削除するには**  
次の `delete-authorizer` の例では、`CustomAuthorizer` という名前のオーソライザーを削除します。カスタムオーソライザーは、削除する前に `INACTIVE` の状態にある必要があります。  

```
aws iot delete-authorizer \
    --authorizer-name CustomAuthorizer
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」「[DeleteAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteAuthorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-authorizer.html)」を参照してください。

### `delete-billing-group`
<a name="iot_DeleteBillingGroup_cli_2_topic"></a>

次のコード例は、`delete-billing-group` を使用する方法を示しています。

**AWS CLI**  
**請求グループを削除するには**  
次の `delete-billing-group` の例は、指定された請求グループを削除します。請求グループは、1 つ以上のモノが含まれている場合でも削除できます。  

```
aws iot delete-billing-group \
    --billing-group-name BillingGroupTwo
```
このコマンドでは、出力が生成されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBillingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-billing-group.html)」を参照してください。

### `delete-ca-certificate`
<a name="iot_DeleteCaCertificate_cli_2_topic"></a>

次のコード例は、`delete-ca-certificate` を使用する方法を示しています。

**AWS CLI**  
**CA 証明書を削除するには**  
次の `delete-ca-certificate` の例では、指定された証明書 ID を持つ CA 証明書を削除します。  

```
aws iot delete-ca-certificate \
    --certificate-id f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[DeleteCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteCACertificate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCaCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-ca-certificate.html)」を参照してください。

### `delete-certificate`
<a name="iot_DeleteCertificate_cli_2_topic"></a>

次のコード例は、`delete-certificate` を使用する方法を示しています。

**AWS CLI**  
**デバイス証明書を削除するには**  
次の `delete-certificate` 例は、指定した ID のデバイス証明書を削除します。  

```
aws iot delete-certificate \
    --certificate-id c0c57bbc8baaf4631a9a0345c957657f5e710473e3ddbee1428d216d54d53ac9
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[DeleteCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteCertificate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-certificate.html)」を参照してください。

### `delete-custom-metric`
<a name="iot_DeleteCustomMetric_cli_2_topic"></a>

次のコード例は、`delete-custom-metric` を使用する方法を示しています。

**AWS CLI**  
**カスタムメトリクスを削除するには**  
次の `delete-custom-metric` の例では、カスタムメトリクスを削除します。  

```
aws iot delete-custom-metric \
    --metric-name batteryPercentage \
    --region us-east-1
```
出力:  

```
HTTP 200
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[カスタムメトリクス](https://docs.aws.amazon.com/iot/latest/developerguide/dd-detect-custom-metrics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCustomMetric](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-custom-metric.html)」を参照してください。

### `delete-dimension`
<a name="iot_DeleteDimension_cli_2_topic"></a>

次のコード例は、`delete-dimension` を使用する方法を示しています。

**AWS CLI**  
**ディメンションを削除するには**  
次の `delete-dimension` の例では、`TopicFilterForAuthMessages` というディメンションを削除します。  

```
aws iot delete-dimension \
    --name TopicFilterForAuthMessages
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDimension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-dimension.html)」を参照してください。

### `delete-domain-configuration`
<a name="iot_DeleteDomainConfiguration_cli_2_topic"></a>

次のコード例は、`delete-domain-configuration` を使用する方法を示しています。

**AWS CLI**  
**ドメイン設定を削除するには**  
次の の`delete-domain-configuration`例では、 という名前のドメイン設定を AWS アカウント`additionalDataDomain`から削除します。  

```
aws iot delete-domain-configuration \
    --domain-configuration-name "additionalDataDomain" \
    --domain-configuration-status "OK"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[設定可能なエンドポイント](https://docs.aws.amazon.com/iot/latest/developerguide/iot-custom-endpoints-configurable-aws.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDomainConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-domain-configuration.html)」を参照してください。

### `delete-dynamic-thing-group`
<a name="iot_DeleteDynamicThingGroup_cli_2_topic"></a>

次のコード例は、`delete-dynamic-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノの動的グループを削除するには**  
次の `delete-dynamic-thing-group` の例は、指定されたモノの動的グループを削除します。  

```
aws iot delete-dynamic-thing-group \
    --thing-group-name "RoomTooWarm"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」「[モノの動的グループ](https://docs.aws.amazon.com/iot/latest/developerguide/dynamic-thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDynamicThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-dynamic-thing-group.html)」を参照してください。

### `delete-job-execution`
<a name="iot_DeleteJobExecution_cli_2_topic"></a>

次のコード例は、`delete-job-execution` を使用する方法を示しています。

**AWS CLI**  
**ジョブの実行を削除するには**  
次の `delete-job-execution` の例では、デバイス上の指定されたジョブのジョブ実行を削除します。`describe-job-execution` を使用して実行番号を取得します。  

```
aws iot delete-job-execution
    --job-id "example-job-02"
    --thing-name "MyRaspberryPi"
    --execution-number 1
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteJobExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-job-execution.html)」を参照してください。

### `delete-job`
<a name="iot_DeleteJob_cli_2_topic"></a>

次のコード例は、`delete-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブを削除するには**  
次の `delete-job` の例では、指定されたジョブを削除します。`--force` オプションを指定することで、ステータスが `IN_PROGRESS` であってもジョブは削除されます。  

```
aws iot delete-job \
    --job-id "example-job-04" \
    --force
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[DeleteJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-job.html)」を参照してください。

### `delete-mitigation-action`
<a name="iot_DeleteMitigationAction_cli_2_topic"></a>

次のコード例は、`delete-mitigation-action` を使用する方法を示しています。

**AWS CLI**  
**緩和アクションを削除するには**  
次の `delete-mitigation-action` 例は、指定された緩和アクションを削除します。  

```
aws iot delete-mitigation-action \
    --action-name AddThingsToQuarantineGroup1Action
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[DeleteMitigationAction (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-DeleteMitigationAction)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMitigationAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-mitigation-action.html)」を参照してください。

### `delete-ota-update`
<a name="iot_DeleteOtaUpdate_cli_2_topic"></a>

次のコード例は、`delete-ota-update` を使用する方法を示しています。

**AWS CLI**  
**OTA 更新を削除するには**  
次の `delete-ota-update` の例では、指定された OTA 更新を削除します。  

```
aws iot delete-ota-update \
    --ota-update-id ota12345 \
    --delete-stream \
    --force-delete-aws-job
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[DeleteOTAUpdate](https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteOTAUpdate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteOtaUpdate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-ota-update.html)」を参照してください。

### `delete-policy-version`
<a name="iot_DeletePolicyVersion_cli_2_topic"></a>

次のコード例は、`delete-policy-version` を使用する方法を示しています。

**AWS CLI**  
**ポリシーのバージョンを削除するには**  
次の の`delete-policy-version`例では、指定されたポリシーのバージョン 2 を AWS アカウントから削除します。  

```
aws iot delete-policy-version \
    --policy-name UpdateDeviceCertPolicy \
    --policy-version-id 2
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-policy-version.html)」を参照してください。

### `delete-policy`
<a name="iot_DeletePolicy_cli_2_topic"></a>

次のコード例は、`delete-policy` を使用する方法を示しています。

**AWS CLI**  
**ポリシーを削除するには**  
次の の`delete-policy`例では、指定されたポリシーを AWS アカウントから削除します。  

```
aws iot delete-policy --policy-name UpdateDeviceCertPolicy
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-policy.html)」を参照してください。

### `delete-provisioning-template-version`
<a name="iot_DeleteProvisioningTemplateVersion_cli_2_topic"></a>

次のコード例は、`delete-provisioning-template-version` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートのバージョンを削除するには**  
次の `delete-provisioning-template-version` の例では、指定されたプロビジョニングテンプレートのバージョン 2 を削除します。  

```
aws iot delete-provisioning-template-version \
    --version-id 2 \
    --template-name "widget-template"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[AWS セキュアトンネリング](https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProvisioningTemplateVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-provisioning-template-version.html)」を参照してください。

### `delete-provisioning-template`
<a name="iot_DeleteProvisioningTemplate_cli_2_topic"></a>

次のコード例は、`delete-provisioning-template` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートを削除するには**  
次の `delete-provisioning-template` の例は、指定されたプロビジョニングテンプレートを削除します。  

```
aws iot delete-provisioning-template \
    --template-name widget-template
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[AWS セキュアトンネリング](https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProvisioningTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-provisioning-template.html)」を参照してください。

### `delete-registration-code`
<a name="iot_DeleteRegistrationCode_cli_2_topic"></a>

次のコード例は、`delete-registration-code` を使用する方法を示しています。

**AWS CLI**  
**登録コードを削除するには**  
次の の`delete-registration-code`例では、 AWS IoT アカウント固有の登録コードを削除します。  

```
aws iot delete-registration-code
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[独自の証明書を使用する](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRegistrationCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-registration-code.html)」を参照してください。

### `delete-role-alias`
<a name="iot_DeleteRoleAlias_cli_2_topic"></a>

次の例は、`delete-role-alias` を使用する方法を説明しています。

**AWS CLI**  
** AWS IoT ロールエイリアスを削除するには**  
次の の`delete-role-alias`例では、 という名前の AWS IoT ロールエイリアスを削除します`LightBulbRole`。  

```
aws iot delete-role-alias \
    --role-alias LightBulbRole
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 IoT デベロッパーガイド*」の[AWS 「サービスへの直接呼び出しの承認](https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoleAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-role-alias.html)」を参照してください。

### `delete-scheduled-audit`
<a name="iot_DeleteScheduledAudit_cli_2_topic"></a>

次のコード例は、`delete-scheduled-audit` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされた監査を削除するには**  
次の の`delete-scheduled-audit`例では、 という名前の AWS IoT Device Defender スケジュールされた監査を削除します`AWSIoTDeviceDefenderDailyAudit`。  

```
aws iot delete-scheduled-audit \
    --scheduled-audit-name AWSIoTDeviceDefenderDailyAudit
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteScheduledAudit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-scheduled-audit.html)」を参照してください。

### `delete-security-profile`
<a name="iot_DeleteSecurityProfile_cli_2_topic"></a>

次のコード例は、`delete-security-profile` を使用する方法を示しています。

**AWS CLI**  
**セキュリティプロファイルを削除するには**  
次の `delete-security-profile` の例では、`PossibleIssue` という名前のセキュリティプロファイルを削除します。  

```
aws iot delete-security-profile \
    --security-profile-name PossibleIssue
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSecurityProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-security-profile.html)」を参照してください。

### `delete-stream`
<a name="iot_DeleteStream_cli_2_topic"></a>

次のコード例は、`delete-stream` を使用する方法を示しています。

**AWS CLI**  
**ストリームを削除するには**  
以下の `delete-stream` 例は、指定されたストリームを削除します。  

```
aws iot delete-stream \
    --stream-id stream12345
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[DeleteStream](https://docs.aws.amazon.com/iot/latest/apireference/API_DeleteStream.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-stream.html)」を参照してください。

### `delete-thing-group`
<a name="iot_DeleteThingGroup_cli_2_topic"></a>

次のコード例は、`delete-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノのグループを削除するには**  
次の `delete-thing-group` の例は、指定されたモノのグループを削除します。モノの子グループが含まれている場合、モノのグループを削除することはできません。  

```
aws iot delete-thing-group \
    --thing-group-name DefectiveBulbs
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-thing-group.html)」を参照してください。

### `delete-thing-type`
<a name="iot_DeleteThingType_cli_2_topic"></a>

次のコード例は、`delete-thing-type` を使用する方法を示しています。

**AWS CLI**  
**例 1: モノのタイプを削除するには**  
次の `delete-thing-type` の例では、廃止されたモノのタイプを削除します。  

```
aws iot delete-thing-type \
    --thing-type-name "obsoleteThingType"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」「[モノのタイプ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteThingType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-thing-type.html)」を参照してください。

### `delete-thing`
<a name="iot_DeleteThing_cli_2_topic"></a>

次のコード例は、`delete-thing` を使用する方法を示しています。

**AWS CLI**  
**モノに関する詳細情報を表示するには**  
次の の`delete-thing`例では、 AWS アカウントの AWS IoT レジストリからモノを削除します。  
aws iot delete-thing --thing-name "FourthBulb"  
このコマンドでは何も出力されません。  
詳細については、「AWS IoT ディベロッパーガイド」の「[レジストリによるモノの管理方法](https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-thing.html)」を参照してください。

### `delete-topic-rule-destination`
<a name="iot_DeleteTopicRuleDestination_cli_2_topic"></a>

次のコード例は、`delete-topic-rule-destination` を使用する方法を示しています。

**AWS CLI**  
**トピックルールの送信先を削除するには**  
次の `delete-topic-rule-destination` の例では、指定したトピックルールの送信先を削除します。  

```
aws iot delete-topic-rule-destination \
    --arn "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[トピックルールの送信先の削除](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html#delete-destination)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTopicRuleDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-topic-rule-destination.html)」を参照してください。

### `delete-topic-rule`
<a name="iot_DeleteTopicRule_cli_2_topic"></a>

次のコード例は、`delete-topic-rule` を使用する方法を示しています。

**AWS CLI**  
**ルールを削除するには**  
次の `delete-topic-rule` の例は、指定されたルールを削除します。  

```
aws iot delete-topic-rule \
    --rule-name "LowMoistureRule"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[ルールの削除](https://docs.aws.amazon.com/iot/latest/developerguide/iot-delete-rule.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTopicRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-topic-rule.html)」を参照してください。

### `delete-v2-logging-level`
<a name="iot_DeleteV2LoggingLevel_cli_2_topic"></a>

次のコード例は、`delete-v2-logging-level` を使用する方法を示しています。

**AWS CLI**  
**モノのグループのログ記録レベルを削除するには**  
次の `delete-v2-logging-level` の例は、指定されたモノのグループのログ記録レベルを削除します。  

```
aws iot delete-v2-logging-level \
    --target-type THING_GROUP \
    --target-name LightBulbs
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteV2LoggingLevel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/delete-v2-logging-level.html)」を参照してください。

### `deprecate-thing-type`
<a name="iot_DeprecateThingType_cli_2_topic"></a>

次のコード例は、`deprecate-thing-type` を使用する方法を示しています。

**AWS CLI**  
**例 1: モノのタイプを廃止にするには**  
次の `deprecate-thing-type` の例では、ユーザーが新しいモノを関連付けられないように、モノのタイプを廃止します。  

```
aws iot deprecate-thing-type \
    --thing-type-name "obsoleteThingType"
```
このコマンドでは何も出力されません。  
**例 2: モノのタイプの廃止を元に戻すには**  
次の `deprecate-thing-type` の例では、モノのタイプの廃止を元に戻し、ユーザーが新しいモノを再び関連付けることができるようにします。  

```
aws iot deprecate-thing-type \
    --thing-type-name "obsoleteThingType" \
    --undo-deprecate
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」「[モノのタイプ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeprecateThingType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/deprecate-thing-type.html)」を参照してください。

### `describe-account-audit-configuration`
<a name="iot_DescribeAccountAuditConfiguration_cli_2_topic"></a>

次のコード例は、`describe-account-audit-configuration` を使用する方法を示しています。

**AWS CLI**  
**現在の監査設定を表示するには**  
次の の`describe-account-audit-configuration`例では、 AWS IoT Device Defender 監査設定の現在の設定を一覧表示します。  

```
aws iot describe-account-audit-configuration
```
出力:  

```
{
    "roleArn": "arn:aws:iam::123456789012:role/service-role/AWSIoTDeviceDefenderAudit_1551201085996",
    "auditNotificationTargetConfigurations": {
        "SNS": {
            "targetArn": "arn:aws:sns:us-west-2:123456789012:ddaudits",
            "roleArn": "arn:aws:iam::123456789012:role/service-role/AWSIoTDeviceDefenderAudit",
            "enabled": true
        }
    },
    "auditCheckConfigurations": {
        "AUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK": {
            "enabled": true
        },
        "CA_CERTIFICATE_EXPIRING_CHECK": {
            "enabled": true
        },
        "CONFLICTING_CLIENT_IDS_CHECK": {
            "enabled": true
        },
        "DEVICE_CERTIFICATE_EXPIRING_CHECK": {
            "enabled": true
        },
        "DEVICE_CERTIFICATE_SHARED_CHECK": {
            "enabled": true
        },
        "IOT_POLICY_OVERLY_PERMISSIVE_CHECK": {
            "enabled": true
        },
        "LOGGING_DISABLED_CHECK": {
            "enabled": true
        },
        "REVOKED_CA_CERTIFICATE_STILL_ACTIVE_CHECK": {
            "enabled": true
        },
        "REVOKED_DEVICE_CERTIFICATE_STILL_ACTIVE_CHECK": {
            "enabled": true
        },
        "UNAUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK": {
            "enabled": true
        }
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountAuditConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-account-audit-configuration.html)」を参照してください。

### `describe-audit-finding`
<a name="iot_DescribeAuditFinding_cli_2_topic"></a>

次のコード例は、`describe-audit-finding` を使用する方法を示しています。

**AWS CLI**  
**監査検出結果の詳細を一覧表示するには**  
次の の`describe-audit-finding`例では、指定された AWS IoT Device Defender 監査結果の詳細を一覧表示します。監査は複数の検出結果を生成できます。`list-audit-findings` コマンドを使用して、監査から検出結果のリストを取得し、`findingId` を取得します。  

```
aws iot describe-audit-finding \
    --finding-id "ef4826b8-e55a-44b9-b460-5c485355371b"
```
出力:  

```
{
    "finding": {
        "findingId": "ef4826b8-e55a-44b9-b460-5c485355371b",
        "taskId": "873ed69c74a9ec8fa9b8e88e9abc4661",
        "checkName": "IOT_POLICY_OVERLY_PERMISSIVE_CHECK",
        "taskStartTime": 1576012045.745,
        "findingTime": 1576012046.168,
        "severity": "CRITICAL",
        "nonCompliantResource": {
            "resourceType": "IOT_POLICY",
            "resourceIdentifier": {
                "policyVersionIdentifier": {
                    "policyName": "smp-ggrass-group_Core-policy",
                    "policyVersionId": "1"
                }
            }
         },
        "reasonForNonCompliance": "Policy allows broad access to IoT data plane actions: [iot:Subscribe, iot:Connect, iot:GetThingShadow, iot:DeleteThingShadow, iot:UpdateThingShadow, iot:Publish].",
        "reasonForNonComplianceCode": "ALLOWS_BROAD_ACCESS_TO_IOT_DATA_PLANE_ACTIONS"
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[監査結果をチェックする (Audit コマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html#device-defender-AuditCommandsFindings)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAuditFinding](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-audit-finding.html)」を参照してください。

### `describe-audit-mitigation-actions-task`
<a name="iot_DescribeAuditMitigationActionsTask_cli_2_topic"></a>

次のコード例は、`describe-audit-mitigation-actions-task` を使用する方法を示しています。

**AWS CLI**  
**監査緩和アクションタスクの詳細を表示するには**  
次の `describe-audit-mitigation-actions-task` の例は、`ResetPolicyVersionAction` が検出結果に適用された、指定されたタスクの詳細を示しています。結果には、タスクの開始と終了のタイミング、ターゲットとなった検出結果の数 (および結果）、このタスクの一部として適用されるアクションの定義が含まれます。  

```
aws iot describe-audit-mitigation-actions-task \
    --task-id ResetPolicyTask01
```
出力:  

```
{
    "taskStatus": "COMPLETED",
    "startTime": "2019-12-10T15:13:19.457000-08:00",
    "endTime": "2019-12-10T15:13:19.947000-08:00",
    "taskStatistics": {
        "IOT_POLICY_OVERLY_PERMISSIVE_CHECK": {
            "totalFindingsCount": 1,
            "failedFindingsCount": 0,
            "succeededFindingsCount": 1,
            "skippedFindingsCount": 0,
            "canceledFindingsCount": 0
        }
    },
    "target": {
        "findingIds": [
            "ef4826b8-e55a-44b9-b460-5c485355371b"
        ]
    },
    "auditCheckToActionsMapping": {
        "IOT_POLICY_OVERLY_PERMISSIVE_CHECK": [
            "ResetPolicyVersionAction"
        ]
    },
    "actionsDefinition": [
        {
            "name": "ResetPolicyVersionAction",
            "id": "1ea0b415-bef1-4a01-bd13-72fb63c59afb",
            "roleArn": "arn:aws:iam::123456789012:role/service-role/ReplacePolicyVersionRole",
            "actionParams": {
                "replaceDefaultPolicyVersionParams": {
                    "templateName": "BLANK_POLICY"
                }
            }
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[DescribeAuditMitigationActionsTask (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-DescribeAuditMitigationActionsTask)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAuditMitigationActionsTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-audit-mitigation-actions-task.html)」を参照してください。

### `describe-audit-suppression`
<a name="iot_DescribeAuditSuppression_cli_2_topic"></a>

次のコード例は、`describe-audit-suppression` を使用する方法を示しています。

**AWS CLI**  
**監査の検出結果の抑制の詳細を取得するには**  
次の `describe-audit-suppression` の例では、監査の検出結果の抑制の詳細を一覧表示します。  

```
aws iot describe-audit-task \
    --task-id "787ed873b69cb4d6cdbae6ddd06996c5"
```
出力:  

```
{
    "taskStatus": "COMPLETED",
    "taskType": "SCHEDULED_AUDIT_TASK",
    "taskStartTime": 1596168096.157,
    "taskStatistics": {
        "totalChecks": 1,
        "inProgressChecks": 0,
        "waitingForDataCollectionChecks": 0,
        "compliantChecks": 0,
        "nonCompliantChecks": 1,
        "failedChecks": 0,
        "canceledChecks": 0
    },
    "scheduledAuditName": "AWSIoTDeviceDefenderDailyAudit",
    "auditDetails": {
        "DEVICE_CERTIFICATE_EXPIRING_CHECK": {
            "checkRunStatus": "COMPLETED_NON_COMPLIANT",
            "checkCompliant": false,
            "totalResourcesCount": 195,
            "nonCompliantResourcesCount": 2
        }
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[監査の検出結果の抑制](https://docs.aws.amazon.com/iot/latest/developerguide/audit-finding-suppressions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAuditSuppression](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-audit-suppression.html)」を参照してください。

### `describe-audit-task`
<a name="iot_DescribeAuditTask_cli_2_topic"></a>

次のコード例は、`describe-audit-task` を使用する方法を示しています。

**AWS CLI**  
**監査インスタンスの情報を取得するには**  
次の の`describe-audit-task`例では、 AWS IoT Device Defender 監査のインスタンスに関する情報を取得します。監査が完了すると、結果に含まれる実行のサマリー統計が結果に含まれます。  

```
aws iot describe-audit-task \
    --task-id a3aea009955e501a31b764abe1bebd3d
```
出力:  

```
 {
    "taskStatus": "COMPLETED",
    "taskType": "ON_DEMAND_AUDIT_TASK",
    "taskStartTime": 1560356923.434,
    "taskStatistics": {
        "totalChecks": 3,
        "inProgressChecks": 0,
        "waitingForDataCollectionChecks": 0,
        "compliantChecks": 3,
        "nonCompliantChecks": 0,
        "failedChecks": 0,
        "canceledChecks": 0
    },
    "auditDetails": {
        "CA_CERTIFICATE_EXPIRING_CHECK": {
            "checkRunStatus": "COMPLETED_COMPLIANT",
            "checkCompliant": true,
            "totalResourcesCount": 0,
            "nonCompliantResourcesCount": 0
        },
        "DEVICE_CERTIFICATE_EXPIRING_CHECK": {
            "checkRunStatus": "COMPLETED_COMPLIANT",
            "checkCompliant": true,
            "totalResourcesCount": 6,
            "nonCompliantResourcesCount": 0
        },
        "REVOKED_CA_CERTIFICATE_STILL_ACTIVE_CHECK": {
            "checkRunStatus": "COMPLETED_COMPLIANT",
            "checkCompliant": true,
            "totalResourcesCount": 0,
            "nonCompliantResourcesCount": 0
        }
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAuditTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-audit-task.html)」を参照してください。

### `describe-authorizer`
<a name="iot_DescribeAuthorizer_cli_2_topic"></a>

次のコード例は、`describe-authorizer` を使用する方法を示しています。

**AWS CLI**  
**カスタムオーソライザーに関する情報を取得するには**  
次の `describe-authorizer` の例は、指定されたカスタムオーソライザーのヘルスの詳細情報を表示します。  

```
aws iot describe-authorizer \
    --authorizer-name CustomAuthorizer
```
出力:  

```
{
    "authorizerDescription": {
        "authorizerName": "CustomAuthorizer",
        "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer",
        "authorizerFunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:CustomAuthorizerFunction",
        "tokenKeyName": "MyAuthToken",
        "tokenSigningPublicKeys": {
            "FIRST_KEY": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1uJOB4lQPgG/lM6ZfIwo\nZ+7ENxAio9q6QD4FFqjGZsvjtYwjoe1RKK0U8Eq9xb5O3kRSmyIwTzwzm/f4Gf0Y\nZUloJ+t3PUUwHrmbYTAgTrCUgRFygjfgVwGCPs5ZAX4Eyqt5cr+AIHIiUDbxSa7p\nzwOBKPeic0asNJpqT8PkBbRaKyleJh5oo81NDHHmVtbBm5A5YiJjqYXLaVAowKzZ\n+GqsNvAQ9Jy1wI2VrEa1OfL8flDB/BJLm7zjpfPOHDJQgID0XnZwAlNnZcOhCwIx\n50g2LW2Oy9R/dmqtDmJiVP97Z4GykxPvwlYHrUXY0iW1R3AR/Ac1NhCTGZMwVDB1\nlQIDAQAB\n-----END PUBLIC KEY-----"
        },
        "status": "ACTIVE",
        "creationDate": 1571245658.069,
        "lastModifiedDate": 1571245658.069
    }
}
```
詳細については、「*AWS IoT API リファレンス*」の「[DescribeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeAuthorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-authorizer.html)」を参照してください。

### `describe-billing-group`
<a name="iot_DescribeBillingGroup_cli_2_topic"></a>

次のコード例は、`describe-billing-group` を使用する方法を示しています。

**AWS CLI**  
**請求グループに関する情報を取得するには**  
次の `describe-billing-group` の例では、指定された請求グループの情報を取得します。  

```
aws iot describe-billing-group --billing-group-name GroupOne
```
出力:  

```
{
    "billingGroupName": "GroupOne",
    "billingGroupId": "103de383-114b-4f51-8266-18f209ef5562",
    "billingGroupArn": "arn:aws:iot:us-west-2:123456789012:billinggroup/GroupOne",
    "version": 1,
    "billingGroupProperties": {},
    "billingGroupMetadata": {
        "creationDate": 1560199355.378
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBillingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-billing-group.html)」を参照してください。

### `describe-ca-certificate`
<a name="iot_DescribeCaCertificate_cli_2_topic"></a>

次のコード例は、`describe-ca-certificate` を使用する方法を示しています。

**AWS CLI**  
**CA 証明書の詳細を取得するには**  
次の `describe-ca-certificate` の例では、指定された CA 証明書の詳細を表示します。  

```
aws iot describe-ca-certificate \
    --certificate-id f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467
```
出力:  

```
{
    "certificateDescription": {
        "certificateArn": "arn:aws:iot:us-west-2:123456789012:cacert/f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467",
        "certificateId": "f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467",
        "status": "INACTIVE",
        "certificatePem": "-----BEGIN CERTIFICATE-----\nMIICzzCCAbegEXAMPLEJANVEPWXl8taPMA0GCSqGSIb3DQEBBQUAMB4xCzAJBgNV\nBAYTAlVTMQ8wDQYDVQQKDAZBbWF6b24wHhcNMTkwOTI0MjEzMTE1WhcNMjkwOTIx\nMjEzMTE1WjAeMQswCQYDVQQGEwJVUzEPMA0GA1UECgwGQW1hem9uMIIBIjANBgkq\nhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzd3R3ioalCS0MhFWfBrVGR036EK07UAf\nVdz9EXAMPLE1VczICbADnATK522kEIB51/18VzlFtAhQL5V5eybXKnB7QebNer5m\n4Yibx7shR5oqNzFsrXWxuugN5+w5gEfqNMawOjhF4LsculKG49yuqjcDU19/13ua\n3B2gxs1Pe7TiWWvUskzxnbO1F2WCshbEJvqY8fIWtGYCjTeJAgQ9hvZx/69XhKen\nwV9LJwOQxrsUS0Ty8IHwbB8fRy72VM3u7fJoaU+nO4jD5cqaoEPtzoeFUEXAMPLE\nyVAJpqHwgbYbcUfn7V+AB6yh1+0Fa1rEQGuZDPGyJslxwr5vh8nRewIDAQABoxAw\nDjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQA+3a5CV3IJgOnd0AgI\nBgVMtmYzTvqAngx26aG9/spvCjXckh2SBF+EcBlCFwH1yakwjJL1dR4yarnrfxgI\nEqP4AOYVimAVoQ5FBwnloHe16+3qtDiblU9DeXBUCtS55EcfrEXAMPLEYtXdqU5C\nU9ia4KAjV0dxW1+EFYMwX5eGeb0gDTNHBylV6B/fOSZiQAwDYp4x3B+gAP+a/bWB\nu1umOqtBdWe6L6/83L+JhaTByqV25iVJ4c/UZUnG8926wUlDM9zQvEXuEVvzZ7+m\n4PSNqst/nVOvnLpoG4e0WgcJgANuB33CSWtjWSuYsbhmqQRknGhREXAMPLEZT4fm\nfo0e\n-----END CERTIFICATE-----\n",
        "ownedBy": "123456789012",
        "creationDate": 1569365372.053,
        "autoRegistrationStatus": "DISABLE",
        "lastModifiedDate": 1569365372.053,
        "customerVersion": 1,
        "generationId": "c5c2eb95-140b-4f49-9393-6aaac85b2a90",
        "validity": {
            "notBefore": 1569360675.0,
            "notAfter": 1884720675.0
        }
    }
}
```
詳細については、「*AWS IoT API リファレンス*」の「[DescribeCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCACertificate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCaCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-ca-certificate.html)」を参照してください。

### `describe-certificate`
<a name="iot_DescribeCertificate_cli_2_topic"></a>

次のコード例は、`describe-certificate` を使用する方法を示しています。

**AWS CLI**  
**証明書に関する情報を取得するには**  
次の `describe-certificate` の例では、指定された証明書の詳細を表示します。  

```
aws iot describe-certificate \
    --certificate-id "4f0ba725787aa94d67d2fca420eca022242532e8b3c58e7465c7778b443fd65e"
```
出力:  

```
{
    "certificateDescription": {
        "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/4f0ba725787aa94d67d2fca420eca022242532e8b3c58e7465c7778b443fd65e",
        "certificateId": "4f0ba725787aa94d67d2fca420eca022242532e8b3c58e7465c7778b443fd65e",
        "status": "ACTIVE",
        "certificatePem": "-----BEGIN CERTIFICATE-----
MIICiTEXAMPLEQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
VVMxCzAJBgNVBEXAMPLEMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAsTC0lBTSBDEXAMPLElMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5EXAMPLEcNMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNEXAMPLEdBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBEXAMPLEz
b2xEXAMPLEYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5jb20wgZ8EXAMPLEZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYEXAMPLEpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7EXAMPLEGBzZswY6786m86gpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFEXAMPLEAtCu4
nUhVVxYUnEXAMPLE8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GEXAMPLEl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----",
        "ownedBy": "123456789012",
        "creationDate": 1541022751.983,
        "lastModifiedDate": 1541022751.983,
        "customerVersion": 1,
        "transferData": {},
        "generationId": "6974fbed-2e61-4114-bc5e-4204cc79b045",
        "validity": {
            "notBefore": 1541022631.0,
            "notAfter": 2524607999.0
        }
    }
}
```
詳細については、「*AWS IoT API リファレンス*」の「[DescribeCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeCertificate.html)」を参照してください。  
+  API の詳細については、**AWS CLI コマンドリファレンスの「[DescribeCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-certificate.html)」を参照してください。

### `describe-custom-metric`
<a name="iot_DescribeCustomMetric_cli_2_topic"></a>

次のコード例は、`describe-custom-metric` を使用する方法を示しています。

**AWS CLI**  
**Device Defender カスタムメトリクスに関する情報を取得するには**  
次の `describe-custom-metric` 例では、`myCustomMetric` という名前のカスタムメトリクスに関する情報を取得します。  

```
aws iot describe-custom-metric \
    --metric-name myCustomMetric
```
出力:  

```
{
    "metricName": "myCustomMetric",
    "metricArn": "arn:aws:iot:us-east-1:1234564789012:custommetric/myCustomMetric",
    "metricType": "number",
    "displayName": "My custom metric",
    "creationDate": 2020-11-17T23:02:12.879000-09:00,
    "lastModifiedDate": 2020-11-17T23:02:12.879000-09:00
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[カスタムメトリクス](https://docs.aws.amazon.com/iot/latest/developerguide/dd-detect-custom-metrics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomMetric](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-custom-metric.html)」を参照してください。

### `describe-default-authorizer`
<a name="iot_DescribeDefaultAuthorizer_cli_2_topic"></a>

次のコード例は、`describe-default-authorizer` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのカスタムオーソライザーに関する情報を取得するには**  
次の `describe-default-authorizer` の例は、デフォルトのカスタムオーソライザーのヘルスの詳細情報を表示します。  

```
aws iot describe-default-authorizer
```
出力:  

```
{
    "authorizerName": "CustomAuthorizer",
    "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[DescribeDefaultAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeDefautAuthorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDefaultAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-default-authorizer.html)」を参照してください。

### `describe-dimension`
<a name="iot_DescribeDimension_cli_2_topic"></a>

次のコード例は、`describe-dimension` を使用する方法を示しています。

**AWS CLI**  
**ディメンションに関する情報を取得するには**  
次の `describe-dimension` の例では、`TopicFilterForAuthMessages` という名前のディメンションに関する情報を取得します。  

```
aws iot describe-dimension \
    --name TopicFilterForAuthMessages
```
出力:  

```
{
    "name": "TopicFilterForAuthMessages",
    "arn": "arn:aws:iot:eu-west-2:123456789012:dimension/TopicFilterForAuthMessages",
    "type": "TOPIC_FILTER",
    "stringValues": [
        "device/+/auth"
    ],
    "creationDate": 1578620223.255,
    "lastModifiedDate": 1578620223.255
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDimension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-dimension.html)」を参照してください。

### `describe-domain-configuration`
<a name="iot_DescribeDomainConfiguration_cli_2_topic"></a>

次のコード例は、`describe-domain-configuration` を使用する方法を示しています。

**AWS CLI**  
**ドメイン設定を記述するには**  
次の `describe-domain-configuration` の例は、指定されたドメイン設定の詳細を表示します。  

```
aws iot describe-domain-configuration \
    --domain-configuration-name "additionalDataDomain"
```
出力:  

```
{
    "domainConfigurationName": "additionalDataDomain",
    "domainConfigurationArn": "arn:aws:iot:us-east-1:758EXAMPLE143:domainconfiguration/additionalDataDomain/norpw",
    "domainName": "d055exampleed74y71zfd-ats.beta.us-east-1.iot.amazonaws.com",
    "serverCertificates": [],
    "domainConfigurationStatus": "ENABLED",
    "serviceType": "DATA",
    "domainType": "AWS_MANAGED",
    "lastStatusChangeDate": 1601923783.774
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[設定可能なエンドポイント](https://docs.aws.amazon.com/iot/latest/developerguide/iot-custom-endpoints-configurable-aws.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDomainConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-domain-configuration.html)」を参照してください。

### `describe-endpoint`
<a name="iot_DescribeEndpoint_cli_2_topic"></a>

次の例は、`describe-endpoint` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 現在の AWS エンドポイントを取得するには**  
次の の`describe-endpoint`例では、すべてのコマンドが適用されるデフォルトの AWS エンドポイントを取得します。  

```
aws iot describe-endpoint
```
出力:  

```
{
    "endpointAddress": "abc123defghijk.iot.us-west-2.amazonaws.com"
}
```
詳細については、「AWS IoT ディベロッパーガイド」の「[DescribeEndpoint](https://docs.aws.amazon.com/iot/latest/developerguide/iot-commands.html#api-iot-DescribeEndpoint)」を参照してください。**  
**例 2: ATS エンドポイントを取得するには**  
次の `describe-endpoint` の例は、Amazon Trust Services (ATS) エンドポイントを取得します。  

```
aws iot describe-endpoint \
    --endpoint-type iot:Data-ATS
```
出力:  

```
{
    "endpointAddress": "abc123defghijk-ats.iot.us-west-2.amazonaws.com"
}
```
詳細については、*AWS 「 IoT デベロッパーガイド*[」の「X.509 証明書と AWS IoT](https://docs.aws.amazon.com/iot/latest/developerguide/managing-device-certs.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-endpoint.html)」を参照してください。**

### `describe-event-configurations`
<a name="iot_DescribeEventConfigurations_cli_2_topic"></a>

次のコード例は、`describe-event-configurations` を使用する方法を示しています。

**AWS CLI**  
**公開されるイベントタイプを表示するには**  
次の `describe-event-configurations` の例では、何かを追加、更新、または削除したときに生成されるイベントを制御する設定を一覧表示します。  

```
aws iot describe-event-configurations
```
出力:  

```
{
    "eventConfigurations": {
        "CA_CERTIFICATE": {
            "Enabled": false
        },
        "CERTIFICATE": {
            "Enabled": false
        },
        "JOB": {
            "Enabled": false
        },
        "JOB_EXECUTION": {
            "Enabled": false
        },
        "POLICY": {
            "Enabled": false
        },
        "THING": {
            "Enabled": false
        },
        "THING_GROUP": {
            "Enabled": false
        },
        "THING_GROUP_HIERARCHY": {
            "Enabled": false
        },
        "THING_GROUP_MEMBERSHIP": {
            "Enabled": false
        },
        "THING_TYPE": {
            "Enabled": false
        },
        "THING_TYPE_ASSOCIATION": {
            "Enabled": false
        }
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[イベントメッセージ](https://docs.aws.amazon.com/iot/latest/developerguide/iot-events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-event-configurations.html)」を参照してください。

### `describe-index`
<a name="iot_DescribeIndex_cli_2_topic"></a>

次のコード例は、`describe-index` を使用する方法を示しています。

**AWS CLI**  
**モノのインデックスの現在のステータスを取得するには**  
次の `describe-index` の例では、モノのインデックスの現在のステータスを取得します。  

```
aws iot describe-index \
    --index-name "AWS_Things"
```
出力:  

```
{
    "indexName": "AWS_Things",
    "indexStatus": "ACTIVE",
    "schema": "REGISTRY_AND_SHADOW_AND_CONNECTIVITY_STATUS"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのインデックス作成の管理](https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-index.html)」を参照してください。

### `describe-job-execution`
<a name="iot_DescribeJobExecution_cli_2_topic"></a>

次のコード例は、`describe-job-execution` を使用する方法を示しています。

**AWS CLI**  
**デバイス上のジョブの実行の詳細を取得するには**  
次の `describe-job-execution` の例では、指定されたジョブの実行の詳細を取得します。  

```
aws iot describe-job-execution \
    --job-id "example-job-01" \
    --thing-name "MyRaspberryPi"
```
出力:  

```
{
    "execution": {
        "jobId": "example-job-01",
        "status": "QUEUED",
        "statusDetails": {},
        "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyRaspberryPi",
        "queuedAt": 1560787023.636,
        "lastUpdatedAt": 1560787023.636,
        "executionNumber": 1,
        "versionNumber": 1
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJobExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-job-execution.html)」を参照してください。

### `describe-job`
<a name="iot_DescribeJob_cli_2_topic"></a>

次のコード例は、`describe-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブの詳細なステータスを取得するには**  
次の `describe-job` の例では、ID が `example-job-01` のジョブの詳細なステータスを取得します。  

```
aws iot describe-job \
    --job-id "example-job-01"
```
出力:  

```
{
    "job": {
        "jobArn": "arn:aws:iot:us-west-2:123456789012:job/example-job-01",
        "jobId": "example-job-01",
        "targetSelection": "SNAPSHOT",
        "status": "IN_PROGRESS",
        "targets": [
            "arn:aws:iot:us-west-2:123456789012:thing/MyRaspberryPi"
        ],
        "description": "example job test",
        "presignedUrlConfig": {},
        "jobExecutionsRolloutConfig": {},
        "createdAt": 1560787022.733,
        "lastUpdatedAt": 1560787026.294,
        "jobProcessDetails": {
            "numberOfCanceledThings": 0,
            "numberOfSucceededThings": 0,
            "numberOfFailedThings": 0,
            "numberOfRejectedThings": 0,
            "numberOfQueuedThings": 1,
            "numberOfInProgressThings": 0,
            "numberOfRemovedThings": 0,
            "numberOfTimedOutThings": 0
        },
        "timeoutConfig": {}
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-job.html)」を参照してください。

### `describe-mitigation-action`
<a name="iot_DescribeMitigationAction_cli_2_topic"></a>

次のコード例は、`describe-mitigation-action` を使用する方法を示しています。

**AWS CLI**  
**定義された緩和アクションの詳細を表示するには**  
次の `describe-mitigation-action` 例では、指定された緩和アクションの詳細を表示します。  

```
aws iot describe-mitigation-action \
    --action-name AddThingsToQuarantineGroupAction
```
出力:  

```
{
    "actionName": "AddThingsToQuarantineGroupAction",
    "actionType": "ADD_THINGS_TO_THING_GROUP",
    "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/AddThingsToQuarantineGroupAction",
    "actionId": "2fd2726d-98e1-4abf-b10f-09465ccd6bfa",
    "roleArn": "arn:aws:iam::123456789012:role/service-role/MoveThingsToQuarantineGroupRole",
    "actionParams": {
        "addThingsToThingGroupParams": {
            "thingGroupNames": [
                "QuarantineGroup1"
            ],
            "overrideDynamicGroups": true
        }
    },
    "creationDate": "2019-12-10T11:09:35.999000-08:00",
    "lastModifiedDate": "2019-12-10T11:09:35.999000-08:00"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[DescribeMitigationAction (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-DescribeMitigationAction)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMitigationAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-mitigation-action.html)」を参照してください。

### `describe-provisioning-template-version`
<a name="iot_DescribeProvisioningTemplateVersion_cli_2_topic"></a>

次のコード例は、`describe-provisioning-template-version` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートのバージョンを記述するには**  
次の `describe-provisioning-template-version` の例では、プロビジョニングテンプレートのバージョンを記述します。  

```
aws iot describe-provisioning-template-version \
    --template-name MyTestProvisioningTemplate \
    --version-id 1
```
出力:  

```
{
    "versionId": 1,
    "creationDate": 1589308310.574,
    "templateBody": "{
        \"Parameters\":{
            \"SerialNumber\":{
                \"Type\":\"String\"
            },
            \"AWS::IoT::Certificate::Id\":{
                \"Type\":\"String\"
            }
        },
        \"Resources\":{
            \"certificate\":{
                \"Properties\":{
                    \"CertificateId\":{
                        \"Ref\":\"AWS::IoT::Certificate::Id\"
                    },
                    \"Status\":\"Active\"
                },
                \"Type\":\"AWS::IoT::Certificate\"
            },
            \"policy\":{
                \"Properties\":{
                    \"PolicyName\":\"MyIotPolicy\"
                },
                \"Type\":\"AWS::IoT::Policy\"
            },
            \"thing\":{
                \"OverrideSettings\":{
                    \"AttributePayload\":\"MERGE\",
                    \"ThingGroups\":\"DO_NOTHING\",
                    \"ThingTypeName\":\"REPLACE\"
                },
                \"Properties\":{
                    \"AttributePayload\":{},
                    \"ThingGroups\":[],
                    \"ThingName\":{
                        \"Fn::Join\":[
                            \"\",
                            [
                                \"DemoGroup_\",
                                {\"Ref\":\"SerialNumber\"}
                            ]
                        ]
                    },
                    \"ThingTypeName\":\"VirtualThings\"
                },
                \"Type\":\"AWS::IoT::Thing\"
            }
        }
    }",
    "isDefaultVersion": true
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[フリートプロビジョニングを使用したデバイス証明書がないデバイスのプロビジョニング](https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProvisioningTemplateVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-provisioning-template-version.html)」を参照してください。

### `describe-provisioning-template`
<a name="iot_DescribeProvisioningTemplate_cli_2_topic"></a>

次のコード例は、`describe-provisioning-template` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートを記述するには**  
次の `describe-provisioning-template` の例では、プロビジョニングテンプレートを記述します。  

```
aws iot describe-provisioning-template \
    --template-name MyTestProvisioningTemplate
```
出力:  

```
{
    "templateArn": "arn:aws:iot:us-west-2:57EXAMPLE833:provisioningtemplate/MyTestProvisioningTemplate",
    "templateName": "MyTestProvisioningTemplate",
    "creationDate": 1589308310.574,
    "lastModifiedDate": 1589308345.539,
    "defaultVersionId": 1,
    "templateBody": "{
        \"Parameters\":{
            \"SerialNumber\":{
                \"Type\":\"String\"
            },
            \"AWS::IoT::Certificate::Id\":{
                \"Type\":\"String\"
            }
        },
        \"Resources\":{
            \"certificate\":{
                \"Properties\":{
                    \"CertificateId\":{
                        \"Ref\":\"AWS::IoT::Certificate::Id\"
                    },
                    \"Status\":\"Active\"
                },
                \"Type\":\"AWS::IoT::Certificate\"
            },
            \"policy\":{
                \"Properties\":{
                    \"PolicyName\":\"MyIotPolicy\"
                },
                \"Type\":\"AWS::IoT::Policy\"
            },
            \"thing\":{
                \"OverrideSettings\":{
                    \"AttributePayload\":\"MERGE\",
                    \"ThingGroups\":\"DO_NOTHING\",
                    \"ThingTypeName\":\"REPLACE\"
                },
                \"Properties\":{
                    \"AttributePayload\":{},
                    \"ThingGroups\":[],
                    \"ThingName\":{
                        \"Fn::Join\":[
                            \"\",
                            [
                                \"DemoGroup_\",
                                {\"Ref\":\"SerialNumber\"}
                            ]
                        ]
                    },
                    \"ThingTypeName\":\"VirtualThings\"
                },
                \"Type\":\"AWS::IoT::Thing\"
            }
        }
    }",
    "enabled": true,
    "provisioningRoleArn": "arn:aws:iam::571032923833:role/service-role/IoT_access"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[フリートプロビジョニングを使用したデバイス証明書がないデバイスのプロビジョニング](https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProvisioningTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-provisioning-template.html)」を参照してください。

### `describe-role-alias`
<a name="iot_DescribeRoleAlias_cli_2_topic"></a>

次の例は、`describe-role-alias` を使用する方法を説明しています。

**AWS CLI**  
** AWS IoT ロールエイリアスに関する情報を取得するには**  
次の `describe-role-alias` の例は、指定されたロールエイリアスの詳細情報を表示します。  

```
aws iot describe-role-alias \
    --role-alias LightBulbRole
```
出力:  

```
{
    "roleAliasDescription": {
        "roleAlias": "LightBulbRole",
        "roleAliasArn": "arn:aws:iot:us-west-2:123456789012:rolealias/LightBulbRole",
        "roleArn": "arn:aws:iam::123456789012:role/light_bulb_role_001",
        "owner": "123456789012",
        "credentialDurationSeconds": 3600,
        "creationDate": 1570558643.221,
        "lastModifiedDate": 1570558643.221
    }
}
```
詳細については、「*AWS IoT API リファレンス*」の「[DescribeRoleAlias](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeRoleAlias.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeRoleAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-role-alias.html)」を参照してください。

### `describe-scheduled-audit`
<a name="iot_DescribeScheduledAudit_cli_2_topic"></a>

次のコード例は、`describe-scheduled-audit` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされた監査に関する情報を取得するには**  
次の の`describe-scheduled-audit`例では、 という名前の AWS IOT Device Defender スケジュールされた監査に関する詳細情報を取得します`AWSIoTDeviceDefenderDailyAudit`。  

```
aws iot describe-scheduled-audit \
    --scheduled-audit-name AWSIoTDeviceDefenderDailyAudit
```
出力:  

```
{
    "frequency": "DAILY",
    "targetCheckNames": [
        "AUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK",
        "CONFLICTING_CLIENT_IDS_CHECK",
        "DEVICE_CERTIFICATE_SHARED_CHECK",
        "IOT_POLICY_OVERLY_PERMISSIVE_CHECK",
        "REVOKED_CA_CERTIFICATE_STILL_ACTIVE_CHECK",
        "UNAUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK"
    ],
    "scheduledAuditName": "AWSIoTDeviceDefenderDailyAudit",
    "scheduledAuditArn": "arn:aws:iot:us-west-2:123456789012:scheduledaudit/AWSIoTDeviceDefenderDailyAudit"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScheduledAudit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-scheduled-audit.html)」を参照してください。

### `describe-security-profile`
<a name="iot_DescribeSecurityProfile_cli_2_topic"></a>

次のコード例は、`describe-security-profile` を使用する方法を示しています。

**AWS CLI**  
**セキュリティプロファイルに関する情報を取得するには**  
次の の`describe-security-profile`例では、 という名前の AWS IoT Device Defender セキュリティプロファイルに関する情報を取得します。 `PossibleIssue.`  

```
aws iot describe-security-profile \
    --security-profile-name PossibleIssue
```
出力:  

```
{
    "securityProfileName": "PossibleIssue",
    "securityProfileArn": "arn:aws:iot:us-west-2:123456789012:securityprofile/PossibleIssue",
    "securityProfileDescription": "check to see if authorization fails 10 times in 5 minutes or if cellular bandwidth exceeds 128",
    "behaviors": [
        {
            "name": "CellularBandwidth",
            "metric": "aws:message-byte-size",
            "criteria": {
                "comparisonOperator": "greater-than",
                "value": {
                    "count": 128
                },
                "consecutiveDatapointsToAlarm": 1,
                "consecutiveDatapointsToClear": 1
            }
        },
        {
            "name": "Authorization",
            "metric": "aws:num-authorization-failures",
            "criteria": {
                "comparisonOperator": "greater-than",
                "value": {
                    "count": 10
                },
                "durationSeconds": 300,
                "consecutiveDatapointsToAlarm": 1,
                "consecutiveDatapointsToClear": 1
            }
        }
    ],
    "version": 1,
    "creationDate": 1560278102.528,
    "lastModifiedDate": 1560278102.528
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSecurityProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-security-profile.html)」を参照してください。

### `describe-stream`
<a name="iot_DescribeStream_cli_2_topic"></a>

次のコード例は、`describe-stream` を使用する方法を示しています。

**AWS CLI**  
**ストリームに関する情報を取得するには**  
次の `describe-stream` の例は、指定されたストリームの詳細を表示します。  

```
aws iot describe-stream \
    --stream-id stream12345
```
出力:  

```
{
    "streamInfo": {
        "streamId": "stream12345",
        "streamArn": "arn:aws:iot:us-west-2:123456789012:stream/stream12345",
        "streamVersion": 1,
        "description": "This stream is used for Amazon FreeRTOS OTA Update 12345.",
        "files": [
            {
                "fileId": "123",
                "s3Location": {
                    "bucket":"codesign-ota-bucket",
                    "key":"48c67f3c-63bb-4f92-a98a-4ee0fbc2bef6"
                }
            }
        ],
        "createdAt": 1557863215.995,
        "lastUpdatedAt": 1557863215.995,
        "roleArn": "arn:aws:iam:123456789012:role/service-role/my_ota_stream_role"
    }
}
```
詳細については、「*AWS IoT API リファレンス*」の「[DescribeStream](https://docs.aws.amazon.com/iot/latest/apireference/API_DescribeStream.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-stream.html)」を参照してください。**

### `describe-thing-group`
<a name="iot_DescribeThingGroup_cli_2_topic"></a>

次のコード例は、`describe-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノのグループに関する情報を取得するには**  
次の `describe-thing-group` の例では、`HalogenBulbs` という名前のモノのグループに関する情報を取得します。  

```
aws iot describe-thing-group \
    --thing-group-name HalogenBulbs
```
出力:  

```
{
    "thingGroupName": "HalogenBulbs",
    "thingGroupId": "f4ec6b84-b42b-499d-9ce1-4dbd4d4f6f6e",
    "thingGroupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/HalogenBulbs",
    "version": 1,
    "thingGroupProperties": {},
    "thingGroupMetadata": {
        "parentGroupName": "LightBulbs",
        "rootToParentThingGroups": [
            {
                "groupName": "LightBulbs",
                "groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs"
            }
        ],
        "creationDate": 1559927609.897
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-thing-group.html)」を参照してください。

### `describe-thing-type`
<a name="iot_DescribeThingType_cli_2_topic"></a>

次のコード例は、`describe-thing-type` を使用する方法を示しています。

**AWS CLI**  
**モノのタイプに関する情報を取得するには**  
次の の`describe-thing-type`例では、 AWS アカウントで定義された指定されたモノのタイプに関する情報を表示します。  

```
aws iot describe-thing-type \
    --thing-type-name "LightBulb"
```
出力:  

```
{
    "thingTypeName": "LightBulb",
    "thingTypeId": "ce3573b0-0a3c-45a7-ac93-4e0ce14cd190",
    "thingTypeArn": "arn:aws:iot:us-west-2:123456789012:thingtype/LightBulb",
    "thingTypeProperties": {
        "thingTypeDescription": "light bulb type",
        "searchableAttributes": [
            "model",
            "wattage"
        ]
    },
    "thingTypeMetadata": {
        "deprecated": false,
        "creationDate": 1559772562.498
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」「[モノのタイプ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeThingType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-thing-type.html)」を参照してください。

### `describe-thing`
<a name="iot_DescribeThing_cli_2_topic"></a>

次のコード例は、`describe-thing` を使用する方法を示しています。

**AWS CLI**  
**モノに関する詳細情報を表示するには**  
次の の`describe-thing`例では、 AWS アカウントの AWS IoT レジストリで定義されているモノ (デバイス) に関する情報を表示します。  
aws iot describe-thing --thing-name "MyLightBulb"  
出力:  

```
{
    "defaultClientId": "MyLightBulb",
    "thingName": "MyLightBulb",
    "thingId": "40da2e73-c6af-406e-b415-15acae538797",
    "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyLightBulb",
    "thingTypeName": "LightBulb",
    "attributes": {
        "model": "123",
        "wattage": "75"
    },
    "version": 1
}
```
詳細については、「AWS IoT ディベロッパーガイド」の「[レジストリによるモノの管理方法](https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/describe-thing.html)」を参照してください。

### `detach-policy`
<a name="iot_DetachPolicy_cli_2_topic"></a>

次の例は、`detach-policy` を使用する方法を説明しています。

**AWS CLI**  
**例 1: モノのグループから AWS IoT ポリシーをデタッチするには**  
次の `detach-policy` の例では、指定されたポリシーをモノのグループからデタッチし、さらにそのグループとそのグループの子グループからすべてのモノをデタッチします。  

```
aws iot detach-policy \
    --target "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs" \
    --policy-name "MyFirstGroup_Core-policy"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
**例 2: デバイス証明書から AWS IoT ポリシーをデタッチするには**  
次の `detach-policy` の例では、ARN によって識別されるデバイス証明書から TemperatureSensorPolicy ポリシーをデタッチします。  

```
aws iot detach-policy \
    --policy-name TemperatureSensorPolicy \
    --target arn:aws:iot:us-west-2:123456789012:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142
```
このコマンドでは何も出力されません。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetachPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-policy.html)」を参照してください。**

### `detach-security-profile`
<a name="iot_DetachSecurityProfile_cli_2_topic"></a>

次のコード例は、`detach-security-profile` を使用する方法を示しています。

**AWS CLI**  
**ターゲットからセキュリティプロファイルの関連付けを解除するには**  
次の の`detach-security-profile`例では、 という名前の AWS IoT Device Defender セキュリティプロファイル`Testprofile`と、登録されたすべてのモノのターゲットとの関連付けを削除します。  

```
aws iot detach-security-profile \
    --security-profile-name Testprofile \
    --security-profile-target-arn "arn:aws:iot:us-west-2:123456789012:all/registered-things"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachSecurityProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-security-profile.html)」を参照してください。

### `detach-thing-principal`
<a name="iot_DetachThingPrincipal_cli_2_topic"></a>

次のコード例は、`detach-thing-principal` を使用する方法を示しています。

**AWS CLI**  
**モノから証明書/プリンシパルをデタッチするには**  
次の `detach-thing-principal` 例では、指定されたモノからプリンシパルを表す証明書を削除します。  

```
aws iot detach-thing-principal \
    --thing-name "MyLightBulb" \
    --principal "arn:aws:iot:us-west-2:123456789012:cert/604c48437a57b7d5fc5d137c5be75011c6ee67c9a6943683a1acb4b1626bac36"
```
このコマンドでは何も出力されません。  
詳細については、「AWS IoT ディベロッパーガイド」の「[レジストリによるモノの管理方法](https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI  コマンドリファレンス*」の「[DetachThingPrincipal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/detach-thing-principal.html)」を参照してください。

### `disable-topic-rule`
<a name="iot_DisableTopicRule_cli_2_topic"></a>

次のコード例は、`disable-topic-rule` を使用する方法を示しています。

**AWS CLI**  
**トピックルールを無効にするには**  
次の `disable-topic-rule` の例では、指定したトピックルールを無効にします。  

```
aws iot disable-topic-rule \
    --rule-name "MyPlantPiMoistureAlertRule"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[ルールの表示](https://docs.aws.amazon.com/iot/latest/developerguide/iot-view-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableTopicRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/disable-topic-rule.html)」を参照してください。

### `enable-topic-rule`
<a name="iot_EnableTopicRule_cli_2_topic"></a>

次のコード例は、`enable-topic-rule` を使用する方法を示しています。

**AWS CLI**  
**トピックルールを有効にするには**  
次の `enable-topic-rule` の例では、指定されたトピックルールを有効化 (または再有効化) します。  

```
aws iot enable-topic-rule \
    --rule-name "MyPlantPiMoistureAlertRule"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[ルールの表示](https://docs.aws.amazon.com/iot/latest/developerguide/iot-view-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableTopicRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/enable-topic-rule.html)」を参照してください。

### `get-behavior-model-training-summaries`
<a name="iot_GetBehaviorModelTrainingSummaries_cli_2_topic"></a>

次のコード例は、`get-behavior-model-training-summaries` を使用する方法を示しています。

**AWS CLI**  
**Device Defender の ML Detect Security Profile トレーニングモデルのステータスを一覧表示するには**  
次の `get-behavior-model-training-summaries` の例では、選択したセキュリティプロファイルで設定された動作のモデルトレーニングのステータスを一覧表示します。動作ごとに、収集されたデータポイントの名前、モデルステータス、およびパーセンテージが一覧表示されます。  

```
aws iot get-behavior-model-training-summaries \
    --security-profile-name MySecuirtyProfileName
```
出力:  

```
{
    "summaries": [
        {
            "securityProfileName": "MySecuirtyProfileName",
            "behaviorName": "Messages_sent_ML_behavior",
            "modelStatus": "PENDING_BUILD",
            "datapointsCollectionPercentage": 0.0
        },
        {
            "securityProfileName": "MySecuirtyProfileName",
            "behaviorName": "Messages_received_ML_behavior",
            "modelStatus": "PENDING_BUILD",
            "datapointsCollectionPercentage": 0.0
        },
        {
            "securityProfileName": "MySecuirtyProfileName",
            "behaviorName": "Authorization_failures_ML_behavior",
            "modelStatus": "PENDING_BUILD",
            "datapointsCollectionPercentage": 0.0
        },
        {
            "securityProfileName": "MySecuirtyProfileName",
            "behaviorName": "Message_size_ML_behavior",
            "modelStatus": "PENDING_BUILD",
            "datapointsCollectionPercentage": 0.0
        },
        {
            "securityProfileName": "MySecuirtyProfileName",
            "behaviorName": "Connection_attempts_ML_behavior",
            "modelStatus": "PENDING_BUILD",
            "datapointsCollectionPercentage": 0.0
        },
        {
            "securityProfileName": "MySPNoALerts",
            "behaviorName": "Disconnects_ML_behavior",
            "modelStatus": "PENDING_BUILD",
            "datapointsCollectionPercentage": 0.0
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[GetBehaviorModelTrainingSummaries (Detect コマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/detect-commands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBehaviorModelTrainingSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-behavior-model-training-summaries.html)」を参照してください。

### `get-cardinality`
<a name="iot_GetCardinality_cli_2_topic"></a>

次のコード例は、`get-cardinality` を使用する方法を示しています。

**AWS CLI**  
**クエリに一致する一意の値のおおよその数を返すには**  
次のセットアップスクリプトを使用して、10 個の温度センサーを表す 10 個のモノを作成できます。新しいモノにはそれぞれ 3 つの属性があります。  

```
# Bash script. If in other shells, type `bash` before running
Temperatures=(70 71 72 73 74 75 47 97 98 99)
Racks=(Rack1 Rack1 Rack2 Rack2 Rack3 Rack4 Rack5 Rack6 Rack6 Rack6)
IsNormal=(true true true true true true false false false false)
for ((i=0; i<10 ; i++))
do
  thing=$(aws iot create-thing --thing-name "TempSensor$i" --attribute-payload attributes="{temperature=${Temperatures[i]},rackId=${Racks[i]},stateNormal=${IsNormal[i]}}")
  aws iot describe-thing --thing-name "TempSensor$i"
done
```
セットアップスクリプトの出力例:  

```
{
    "version": 1,
    "thingName": "TempSensor0",
    "defaultClientId": "TempSensor0",
    "attributes": {
        "rackId": "Rack1",
        "stateNormal": "true",
        "temperature": "70"
    },
    "thingArn": "arn:aws:iot:us-east-1:123456789012:thing/TempSensor0",
    "thingId": "example1-90ab-cdef-fedc-ba987example"
}
```
次の `get-cardinality` の例では、セットアップスクリプトによって作成された 10 個のセンサーをクエリし、温度センサーが異常な温度値を報告しているラックの数を返します。温度値が 60 未満または 80 を超過する場合、温度センサーは異常な状態になります。  

```
aws iot get-cardinality \
    --aggregation-field "attributes.rackId" \
    --query-string "thingName:TempSensor* AND attributes.stateNormal:false"
```
出力:  

```
{
    "cardinality": 2
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「集計データのクエリ<https://docs.aws.amazon.com/iot/latest/developerguide/index-aggregate.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCardinality](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-cardinality.html)」を参照してください。

### `get-effective-policies`
<a name="iot_GetEffectivePolicies_cli_2_topic"></a>

次のコード例は、`get-effective-policies` を使用する方法を示しています。

**AWS CLI**  
**モノに影響するポリシーを一覧表示するには**  
次の `get-effective-policies` の例では、指定されたモノに影響するポリシーを一覧表示します。これには、それが属するすべてのグループにアタッチされたポリシーが含まれます。  

```
aws iot get-effective-policies \
    --thing-name TemperatureSensor-001 \
    --principal arn:aws:iot:us-west-2:123456789012:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142
```
出力:  

```
{
    "effectivePolicies": [
        {
            "policyName": "TemperatureSensorPolicy",
            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/TemperatureSensorPolicy",
            "policyDocument": "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [
                    {
                        \"Effect\": \"Allow\",
                        \"Action\": [
                            \"iot:Publish\",
                            \"iot:Receive\"
                        ],
                        \"Resource\": [
                            \"arn:aws:iot:us-west-2:123456789012:topic/topic_1\",
                            \"arn:aws:iot:us-west-2:123456789012:topic/topic_2\"
                        ]
                    },
                    {
                        \"Effect\": \"Allow\",
                        \"Action\": [
                            \"iot:Subscribe\"
                        ],
                        \"Resource\": [
                            \"arn:aws:iot:us-west-2:123456789012:topicfilter/topic_1\",
                            \"arn:aws:iot:us-west-2:123456789012:topicfilter/topic_2\"
                        ]
                    },
                    {
                        \"Effect\": \"Allow\",
                        \"Action\": [
                            \"iot:Connect\"
                        ],
                        \"Resource\": [
                            \"arn:aws:iot:us-west-2:123456789012:client/basicPubSub\"
                        ]
                    }
                ]
            }"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の[「モノで有効なポリシーを取得する](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html#group-get-effective-policies)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEffectivePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-effective-policies.html)」を参照してください。

### `get-indexing-configuration`
<a name="iot_GetIndexingConfiguration_cli_2_topic"></a>

次のコード例は、`get-indexing-configuration` を使用する方法を示しています。

**AWS CLI**  
**モノのインデックス作成設定を取得するには**  
次の の`get-indexing-configuration`例では、 AWS IoT フリートインデックス作成の現在の設定データを取得します。  

```
aws iot get-indexing-configuration
```
出力:  

```
{
    "thingIndexingConfiguration": {
        "thingIndexingMode": "OFF",
        "thingConnectivityIndexingMode": "OFF"
    },
    "thingGroupIndexingConfiguration": {
        "thingGroupIndexingMode": "OFF"
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのインデックス作成の管理](https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIndexingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-indexing-configuration.html)」を参照してください。

### `get-job-document`
<a name="iot_GetJobDocument_cli_2_topic"></a>

次のコード例は、`get-job-document` を使用する方法を示しています。

**AWS CLI**  
**ジョブのドキュメントを取得するには**  
次の `get-job-document` の例では、ID が `example-job-01` のジョブのドキュメントの詳細を表示します。  

```
aws iot get-job-document \
    --job-id "example-job-01"
```
出力:  

```
{
    "document": "\n{\n    \"operation\":\"customJob\",\n    \"otherInfo\":\"someValue\"\n}\n"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetJobDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-job-document.html)」を参照してください。

### `get-logging-options`
<a name="iot_GetLoggingOptions_cli_2_topic"></a>

次のコード例は、`get-logging-options` を使用する方法を示しています。

**AWS CLI**  
**ログ記録オプションを取得するには**  
次の の`get-logging-options`例では、 AWS アカウントの現在のログ記録オプションを取得します。  

```
aws iot get-logging-options
```
出力:  

```
{
    "roleArn": "arn:aws:iam::123456789012:role/service-role/iotLoggingRole",
    "logLevel": "ERROR"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」のタイトルを参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-logging-options.html)」を参照してください。

### `get-ota-update`
<a name="iot_GetOtaUpdate_cli_2_topic"></a>

次のコード例は、`get-ota-update` を使用する方法を示しています。

**AWS CLI**  
**OTA 更新に関する情報を取得するには**  
次の `get-ota-update` の例は、指定された OTA 更新の詳細を表示します。  

```
aws iot get-ota-update \
    --ota-update-id ota12345
```
出力:  

```
{
    "otaUpdateInfo": {
        "otaUpdateId": "ota12345",
        "otaUpdateArn": "arn:aws:iot:us-west-2:123456789012:otaupdate/itsaupdate",
        "creationDate": 1557863215.995,
        "lastModifiedDate": 1557863215.995,
        "description": "A critical update needed right away.",
        "targets": [
           "device1",
           "device2",
           "device3",
           "device4"
        ],
        "targetSelection": "SNAPSHOT",
        "protocols": ["HTTP"],
        "awsJobExecutionsRolloutConfig": {
           "maximumPerMinute": 10
        },
        "otaUpdateFiles": [
            {
                "fileName": "firmware.bin",
                "fileLocation": {
                    "stream": {
                        "streamId": "004",
                        "fileId":123
                    }
                },
                "codeSigning": {
                    "awsSignerJobId": "48c67f3c-63bb-4f92-a98a-4ee0fbc2bef6"
                }
            }
        ],
        "roleArn": "arn:aws:iam:123456789012:role/service-role/my_ota_role"
        "otaUpdateStatus": "CREATE_COMPLETE",
        "awsIotJobId": "job54321",
        "awsIotJobArn": "arn:aws:iot:us-west-2:123456789012:job/job54321",
        "errorInfo": {
        }
    }
}
```
詳細については、「*AWS IoT API リファレンス*」の「[GetOTAUpdate](https://docs.aws.amazon.com/iot/latest/apireference/API_GetOTAUpdate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOtaUpdate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-ota-update.html)」を参照してください。

### `get-percentiles`
<a name="iot_GetPercentiles_cli_2_topic"></a>

次のコード例は、`get-percentiles` を使用する方法を示しています。

**AWS CLI**  
**クエリに一致する集計値をパーセンタイルグループにグループ化するには**  
次のセットアップスクリプトを使用して、10 個の温度センサーを表す 10 個のモノを作成できます。新しいモノにはそれぞれ 1 つの属性があります。  

```
# Bash script. If in other shells, type `bash` before running
Temperatures=(70 71 72 73 74 75 47 97 98 99)
for ((i=0; i<10 ; i++))
do
    thing=$(aws iot create-thing --thing-name "TempSensor$i" --attribute-payload attributes="{temperature=${Temperatures[i]}}")
    aws iot describe-thing --thing-name "TempSensor$i"
done
```
セットアップスクリプトの出力例:  

```
{
    "version": 1,
    "thingName": "TempSensor0",
    "defaultClientId": "TempSensor0",
    "attributes": {
        "temperature": "70"
    },
    "thingArn": "arn:aws:iot:us-east-1:123456789012:thing/TempSensor0",
    "thingId": "example1-90ab-cdef-fedc-ba987example"
}
```
次の `get-percentiles` の例では、セットアップスクリプトによって作成された 10 個のセンサーをクエリし、指定されたパーセンタイルグループごとに値を返します。パーセンタイルグループ「10」には、クエリに一致する値の約 10 % に含まれる集計フィールド値が含まれます。次の出力では、\$1"percent": 10.0, "value": 67.7\$1 は、温度値の約 10.0% が 67.7 未満であることを意味します。  

```
aws iot get-percentiles \
    --aggregation-field "attributes.temperature" \
    --query-string "thingName:TempSensor*" \
    --percents 10 25 50 75 90
```
出力:  

```
{
    "percentiles": [
        {
            "percent": 10.0,
            "value": 67.7
        },
        {
            "percent": 25.0,
            "value": 71.25
        },
        {
            "percent": 50.0,
            "value": 73.5
        },
        {
            "percent": 75.0,
            "value": 91.5
        },
        {
            "percent": 90.0,
            "value": 98.1
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[「集計データのクエリ](https://docs.aws.amazon.com/iot/latest/developerguide/index-aggregate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPercentiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-percentiles.html)」を参照してください。

### `get-policy-version`
<a name="iot_GetPolicyVersion_cli_2_topic"></a>

次のコード例は、`get-policy-version` を使用する方法を示しています。

**AWS CLI**  
**ポリシーの特定のバージョンに関する情報を取得するには**  
次の `get-policy-version` の例では、指定されたポリシーの最初のバージョンに関する情報を取得します。  

```
aws iot get-policy \
    --policy-name UpdateDeviceCertPolicy
    --policy-version-id "1"
```
出力:  

```
{
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/UpdateDeviceCertPolicy",
    "policyName": "UpdateDeviceCertPolicy",
    "policyDocument": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Action\":  \"iot:UpdateCertificate\", \"Resource\": \"*\" } ] }",
    "policyVersionId": "1",
    "isDefaultVersion": false,
    "creationDate": 1559925941.924,
    "lastModifiedDate": 1559926175.458,
    "generationId": "5066f1b6712ce9d2a1e56399771649a272d6a921762fead080e24fe52f24e042"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-policy-version.html)」を参照してください。

### `get-policy`
<a name="iot_GetPolicy_cli_2_topic"></a>

次のコード例は、`get-policy` を使用する方法を示しています。

**AWS CLI**  
**ポリシーのデフォルトバージョンに関する情報を取得するには**  
次の `get-policy` の例では、指定されたポリシーのデフォルトバージョンに関する情報を取得します。  

```
aws iot get-policy \
    --policy-name UpdateDeviceCertPolicy
```
出力:  

```
{
    "policyName": "UpdateDeviceCertPolicy",
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/UpdateDeviceCertPolicy",
    "policyDocument": "{ \"Version\": \"2012-10-17\", \"Statement\": [ { \"Effect\": \"Allow\", \"Action\":  \"iot:UpdateCertificate\", \"Resource\": \"*\" } ] }",
    "defaultVersionId": "2",
    "creationDate": 1559925941.924,
    "lastModifiedDate": 1559925941.924,
    "generationId": "5066f1b6712ce9d2a1e56399771649a272d6a921762fead080e24fe52f24e042"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-policy.html)」を参照してください。

### `get-registration-code`
<a name="iot_GetRegistrationCode_cli_2_topic"></a>

次の例は、`get-registration-code` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウント固有の登録コードを取得するには**  
次の の`get-registration-code`例では、 AWS アカウント固有の登録コードを取得します。  

```
aws iot get-registration-code
```
出力:  

```
{
    "registrationCode": "15c51ae5e36ba59ba77042df1115862076bea4bd15841c838fcb68d5010a614c"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[独自の証明書を使用する](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRegistrationCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-registration-code.html)」を参照してください。

### `get-statistics`
<a name="iot_GetStatistics_cli_2_topic"></a>

次のコード例は、`get-statistics` を使用する方法を示しています。

**AWS CLI**  
**集計データのデバイスインデックスを検索するには**  
次の `get-statistics` の例では、`connectivity.connected` というプロパティがデバイスシャドウで `false` に設定されているモノの数 (つまり、接続されていないデバイスの数) を返します。  

```
aws iot get-statistics \
    --index-name AWS_Things \
    --query-string "connectivity.connected:false"
```
出力:  

```
{
    "statistics": {
        "count": 6
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[デバイスフリートに関する統計の取得](https://docs.aws.amazon.com/iot/latest/developerguide/index-aggregate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-statistics.html)」を参照してください。

### `get-topic-rule-destination`
<a name="iot_GetTopicRuleDestination_cli_2_topic"></a>

次のコード例は、`get-topic-rule-destination` を使用する方法を示しています。

**AWS CLI**  
**トピックルールの送信先を取得するには**  
次の `get-topic-rule-destination` の例では、トピックルールの送信先に関する情報を取得します。  

```
aws iot get-topic-rule-destination \
    --arn "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
```
出力:  

```
{
    "topicRuleDestination": {
        "arn": "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
        "status": "DISABLED",
        "httpUrlProperties": {
            "confirmationUrl": "https://example.com"
        }
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[トピックルールの送信先の操作](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTopicRuleDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-topic-rule-destination.html)」を参照してください。

### `get-topic-rule`
<a name="iot_GetTopicRule_cli_2_topic"></a>

次のコード例は、`get-topic-rule` を使用する方法を示しています。

**AWS CLI**  
**ルールに関する情報を取得するには**  
次の `get-topic-rule` の例では、指定されたルールに関する情報を取得します。  

```
aws iot get-topic-rule \
    --rule-name MyRPiLowMoistureAlertRule
```
出力:  

```
{
    "ruleArn": "arn:aws:iot:us-west-2:123456789012:rule/MyRPiLowMoistureAlertRule",
    "rule": {
        "ruleName": "MyRPiLowMoistureAlertRule",
        "sql": "SELECT * FROM '$aws/things/MyRPi/shadow/update/accepted' WHERE state.reported.moisture = 'low'\n                    ",
        "description": "Sends an alert whenever soil moisture level readings are too low.",
        "createdAt": 1558624363.0,
        "actions": [
            {
                "sns": {
                    "targetArn": "arn:aws:sns:us-west-2:123456789012:MyRPiLowMoistureTopic",
                    "roleArn": "arn:aws:iam::123456789012:role/service-role/MyRPiLowMoistureTopicRole",
                    "messageFormat": "RAW"
                }
            }
        ],
        "ruleDisabled": false,
        "awsIotSqlVersion": "2016-03-23"
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ルールの表示](https://docs.aws.amazon.com/iot/latest/developerguide/iot-managae-rule.html#iot-view-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTopicRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-topic-rule.html)」を参照してください。

### `get-v2-logging-options`
<a name="iot_GetV2LoggingOptions_cli_2_topic"></a>

次のコード例は、`get-v2-logging-options` を使用する方法を示しています。

**AWS CLI**  
**現在のログ記録オプションを一覧表示するには**  
次の の`get-v2-logging-options`例では、 AWS IoT の現在のログ記録オプションを一覧表示します。  

```
aws iot get-v2-logging-options
```
出力:  

```
{
    "roleArn": "arn:aws:iam::094249569039:role/service-role/iotLoggingRole",
    "defaultLogLevel": "WARN",
    "disableAllLogs": false
}
```
詳細については、「*AWS IoT デベロッパーガイド*」のタイトルを参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetV2LoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/get-v2-logging-options.html)」を参照してください。

### `list-active-violations`
<a name="iot_ListActiveViolations_cli_2_topic"></a>

次のコード例は、`list-active-violations` を使用する方法を示しています。

**AWS CLI**  
**アクティブな違反を一覧表示するには**  
次の `list-active-violations` の例では、指定されたセキュリティプロファイルに対するすべての違反を一覧表示します。  

```
aws iot list-active-violations \
    --security-profile-name Testprofile
```
出力:  

```
{
    "activeViolations": [
        {
            "violationId": "174db59167fa474c80a652ad1583fd44",
            "thingName": "iotconsole-1560269126751-1",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "Authorization",
                "metric": "aws:num-authorization-failures",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 10
                    },
                    "durationSeconds": 300,
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "lastViolationValue": {
                "count": 0
            },
            "lastViolationTime": 1560293700.0,
            "violationStartTime": 1560279000.0
        },
        {
            "violationId": "c8a9466a093d3b7b35cd44ca58bdbeab",
            "thingName": "TvnQoEoU",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "CellularBandwidth",
                "metric": "aws:message-byte-size",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 128
                    },
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "lastViolationValue": {
                "count": 110
            },
            "lastViolationTime": 1560369000.0,
            "violationStartTime": 1560276600.0
        },
        {
            "violationId": "74aa393adea02e6648f3ac362beed55e",
            "thingName": "iotconsole-1560269232412-2",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "Authorization",
                "metric": "aws:num-authorization-failures",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 10
                    },
                    "durationSeconds": 300,
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "lastViolationValue": {
                "count": 0
            },
            "lastViolationTime": 1560276600.0,
            "violationStartTime": 1560276600.0
        },
        {
            "violationId": "1e6ab5f7cf39a1466fcd154e1377e406",
            "thingName": "TvnQoEoU",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "Authorization",
                "metric": "aws:num-authorization-failures",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 10
                    },
                    "durationSeconds": 300,
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "lastViolationValue": {
                "count": 0
            },
            "lastViolationTime": 1560369000.0,
            "violationStartTime": 1560276600.0
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListActiveViolations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-active-violations.html)」を参照してください。

### `list-attached-policies`
<a name="iot_ListAttachedPolicies_cli_2_topic"></a>

次のコード例は、`list-attached-policies` を使用する方法を示しています。

**AWS CLI**  
**例 1: グループにアタッチされるポリシーを一覧表示するには**  
次の `list-attached-policies` の例では、指定されたグループにアタッチされているポリシーを一覧表示します。  

```
aws iot list-attached-policies \
    --target "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs"
```
出力:  

```
{
    "policies": [
        {
            "policyName": "UpdateDeviceCertPolicy",
            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/UpdateDeviceCertPolicy"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
**例 2: デバイス証明書にアタッチされたポリシーを一覧表示するには**  
次の の`list-attached-policies`例では、デバイス証明書にアタッチされた AWS IoT ポリシーを一覧表示します。証明書は ARN によって識別されます。  

```
aws iot list-attached-policies \
    --target arn:aws:iot:us-west-2:123456789012:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142
```
出力:  

```
{
    "policies": [
        {
            "policyName": "TemperatureSensorPolicy",
            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/TemperatureSensorPolicy"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttachedPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-attached-policies.html)」を参照してください。

### `list-audit-findings`
<a name="iot_ListAuditFindings_cli_2_topic"></a>

次のコード例は、`list-audit-findings` を使用する方法を示しています。

**AWS CLI**  
**例 1: 監査のすべての検出結果を一覧表示するには**  
次の の`list-audit-findings`例では、指定されたタスク ID を使用して、 AWS IoT Device Defender 監査のすべての検出結果を一覧表示します。  

```
aws iot list-audit-findings \
    --task-id a3aea009955e501a31b764abe1bebd3d
```
出力:  

```
{
    "findings": []
}
```
**例 2: 監査チェックタイプの検出結果を一覧表示するには**  
次の`list-audit-findings`例は、デバイスがデバイス証明書を共有している 2019 年 6 月 5 日から 2019 年 6 月 19 日までに実行された AWS IoT Device Defender 監査の結果を示しています。チェック名を指定するときは、開始時刻と終了時刻を指定する必要があります。  

```
aws iot list-audit-findings \
    --check-name DEVICE_CERTIFICATE_SHARED_CHECK \
    --start-time 1559747125 \
    --end-time 1560962028
```
出力:  

```
{
    "findings": [
        {
            "taskId": "eeef61068b0eb03c456d746c5a26ee04",
            "checkName": "DEVICE_CERTIFICATE_SHARED_CHECK",
            "taskStartTime": 1560161017.172,
            "findingTime": 1560161017.592,
            "severity": "CRITICAL",
            "nonCompliantResource": {
                "resourceType": "DEVICE_CERTIFICATE",
                "resourceIdentifier": {
                    "deviceCertificateId": "b193ab7162c0fadca83246d24fa090300a1236fe58137e121b011804d8ac1d6b"
                }
            },
            "relatedResources": [
                {
                    "resourceType": "CLIENT_ID",
                    "resourceIdentifier": {
                        "clientId": "ZipxgAIl"
                    },
                    "additionalInfo": {
                        "CONNECTION_TIME": "1560086374068"
                    }
                },
                {
                    "resourceType": "CLIENT_ID",
                    "resourceIdentifier": {
                        "clientId": "ZipxgAIl"
                    },
                    "additionalInfo": {
                        "CONNECTION_TIME": "1560081552187",
                        "DISCONNECTION_TIME": "1560086371552"
                    }
                },
                {
                    "resourceType": "CLIENT_ID",
                    "resourceIdentifier": {
                        "clientId": "ZipxgAIl"
                    },
                    "additionalInfo": {
                        "CONNECTION_TIME": "1559289863631",
                        "DISCONNECTION_TIME": "1560081532716"
                    }
                }
            ],
            "reasonForNonCompliance": "Certificate shared by one or more devices.",
            "reasonForNonComplianceCode": "CERTIFICATE_SHARED_BY_MULTIPLE_DEVICES"
        },
        {
            "taskId": "bade6b5efd2e1b1569822f6021b39cf5",
            "checkName": "DEVICE_CERTIFICATE_SHARED_CHECK",
            "taskStartTime": 1559988217.27,
            "findingTime": 1559988217.655,
            "severity": "CRITICAL",
            "nonCompliantResource": {
                "resourceType": "DEVICE_CERTIFICATE",
                "resourceIdentifier": {
                    "deviceCertificateId": "b193ab7162c0fadca83246d24fa090300a1236fe58137e121b011804d8ac1d6b"
                }
            },
            "relatedResources": [
                {
                    "resourceType": "CLIENT_ID",
                    "resourceIdentifier": {
                        "clientId": "xShGENLW"
                    },
                    "additionalInfo": {
                        "CONNECTION_TIME": "1559972350825"
                    }
                },
                {
                    "resourceType": "CLIENT_ID",
                    "resourceIdentifier": {
                        "clientId": "xShGENLW"
                    },
                    "additionalInfo": {
                        "CONNECTION_TIME": "1559255062002",
                        "DISCONNECTION_TIME": "1559972350616"
                    }
                }
            ],
            "reasonForNonCompliance": "Certificate shared by one or more devices.",
            "reasonForNonComplianceCode": "CERTIFICATE_SHARED_BY_MULTIPLE_DEVICES"
        },
        {
            "taskId": "c23f6233ba2d35879c4bb2810fb5ffd6",
            "checkName": "DEVICE_CERTIFICATE_SHARED_CHECK",
            "taskStartTime": 1559901817.31,
            "findingTime": 1559901817.767,
            "severity": "CRITICAL",
            "nonCompliantResource": {
                "resourceType": "DEVICE_CERTIFICATE",
                "resourceIdentifier": {
                    "deviceCertificateId": "b193ab7162c0fadca83246d24fa090300a1236fe58137e121b011804d8ac1d6b"
                }
            },
            "relatedResources": [
                {
                    "resourceType": "CLIENT_ID",
                    "resourceIdentifier": {
                        "clientId": "TvnQoEoU"
                    },
                    "additionalInfo": {
                        "CONNECTION_TIME": "1559826729768"
                    }
                },
                {
                    "resourceType": "CLIENT_ID",
                    "resourceIdentifier": {
                        "clientId": "TvnQoEoU"
                    },
                    "additionalInfo": {
                        "CONNECTION_TIME": "1559345920964",
                        "DISCONNECTION_TIME": "1559826728402"
                    }
                }
            ],
            "reasonForNonCompliance": "Certificate shared by one or more devices.",
            "reasonForNonComplianceCode": "CERTIFICATE_SHARED_BY_MULTIPLE_DEVICES"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAuditFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-audit-findings.html)」を参照してください。

### `list-audit-mitigation-actions-executions`
<a name="iot_ListAuditMitigationActionsExecutions_cli_2_topic"></a>

次のコード例は、`list-audit-mitigation-actions-executions` を使用する方法を示しています。

**AWS CLI**  
**監査緩和アクションの実行の詳細を一覧表示するには**  
監査緩和アクションタスクは、 AWS IoT Device Defender 監査からの 1 つ以上の検出結果に緩和アクションを適用します。次の `list-audit-mitigation-actions-executions` の例では、指定された `taskId` と指定された検出結果の緩和アクションタスクの詳細を一覧表示します。  

```
aws iot list-audit-mitigation-actions-executions \
    --task-id myActionsTaskId \
    --finding-id 0edbaaec-2fe1-4cf5-abc9-d4c3e51f7464
```
出力:  

```
{
    "actionsExecutions": [
        {
            "taskId": "myActionsTaskId",
            "findingId": "0edbaaec-2fe1-4cf5-abc9-d4c3e51f7464",
            "actionName": "ResetPolicyVersionAction",
            "actionId": "1ea0b415-bef1-4a01-bd13-72fb63c59afb",
            "status": "COMPLETED",
            "startTime": "2019-12-10T15:19:13.279000-08:00",
            "endTime": "2019-12-10T15:19:13.337000-08:00"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ListAuditMitigationActionsExecutions (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-ListAuditMitigationActionsExecutions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAuditMitigationActionsExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-audit-mitigation-actions-executions.html)」を参照してください。

### `list-audit-mitigation-actions-tasks`
<a name="iot_ListAuditMitigationActionsTasks_cli_2_topic"></a>

次のコード例は、`list-audit-mitigation-actions-tasks` を使用する方法を示しています。

**AWS CLI**  
**監査緩和アクションタスクを一覧表示するには**  
次の `list-audit-mitigation-actions-tasks` の例では、指定された期間内に検出結果に適用された緩和アクションを一覧表示します。  

```
aws iot list-audit-mitigation-actions-tasks \
    --start-time 1594157400 \
    --end-time 1594157430
```
出力:  

```
{
    "tasks": [
        {
                "taskId": "0062f2d6-3999-488f-88c7-bef005414103",
                "startTime": "2020-07-07T14:30:15.172000-07:00",
            "taskStatus": "COMPLETED"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ListAuditMitigationActionsTasks (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-ListAuditMitigationActionsTasks)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAuditMitigationActionsTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-audit-mitigation-actions-tasks.html)」を参照してください。

### `list-audit-suppressions`
<a name="iot_ListAuditSuppressions_cli_2_topic"></a>

次のコード例は、`list-audit-suppressions` を使用する方法を示しています。

**AWS CLI**  
**すべての監査検出結果の抑制を一覧表示するには**  
次の `list-audit-suppressions` の例では、アクティブな監査検出結果の抑制をすべて一覧表示します。  

```
aws iot list-audit-suppressions
```
出力:  

```
{
    "suppressions": [
        {
        "checkName": "DEVICE_CERTIFICATE_EXPIRING_CHECK",
            "resourceIdentifier": {
                "deviceCertificateId": "c7691e<shortened>"
            },
        "expirationDate": 1597881600.0,
        "suppressIndefinitely": false
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[監査の検出結果の抑制](https://docs.aws.amazon.com/iot/latest/developerguide/audit-finding-suppressions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAuditSuppressions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-audit-suppressions.html)」を参照してください。

### `list-audit-tasks`
<a name="iot_ListAuditTasks_cli_2_topic"></a>

次のコード例は、`list-audit-tasks` を使用する方法を示しています。

**AWS CLI**  
**監査からのすべての検出結果を一覧表示するには**  
次の `list-audit-tasks` の例では、2019 年 6 月 5 日から 2019 年 6 月 12 日の間に実行された監査タスクを一覧表示します。  

```
aws iot list-audit-tasks \
    --start-time 1559747125 \
    --end-time 1560357228
```
出力:  

```
{
    "tasks": [
        {
            "taskId": "a3aea009955e501a31b764abe1bebd3d",
            "taskStatus": "COMPLETED",
            "taskType": "ON_DEMAND_AUDIT_TASK"
        },
        {
            "taskId": "f76b4b5102b632cd9ae38a279c266da1",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        },
        {
            "taskId": "51d9967d9f9ff4d26529505f6d2c444a",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        },
        {
            "taskId": "eeef61068b0eb03c456d746c5a26ee04",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        },
        {
            "taskId": "041c49557b7c7b04c079a49514b55589",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        },
        {
            "taskId": "82c7f2afac1562d18a4560be73998acc",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        },
        {
            "taskId": "bade6b5efd2e1b1569822f6021b39cf5",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        },
        {
            "taskId": "c23f6233ba2d35879c4bb2810fb5ffd6",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        },
        {
            "taskId": "ac9086b7222a2f5e2e17bb6fd30b3aeb",
            "taskStatus": "COMPLETED",
            "taskType": "SCHEDULED_AUDIT_TASK"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAuditTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-audit-tasks.html)」を参照してください。

### `list-authorizers`
<a name="iot_ListAuthorizers_cli_2_topic"></a>

次のコード例は、`list-authorizers` を使用する方法を示しています。

**AWS CLI**  
**カスタムオーソライザーを一覧表示するには**  
次の の`list-authorizers`例では、 AWS アカウントのカスタムオーソライザーを一覧表示します。  

```
aws iot list-authorizers
```
出力:  

```
{
    "authorizers": [
        {
            "authorizerName": "CustomAuthorizer",
            "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer"
        },
        {
            "authorizerName": "CustomAuthorizer2",
            "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer2"
        },
        {
            "authorizerName": "CustomAuthorizer3",
            "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer3"
        }
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListAuthorizers](https://docs.aws.amazon.com/iot/latest/apireference/API_ListAuthorizers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAuthorizers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-authorizers.html)」を参照してください。

### `list-billing-groups`
<a name="iot_ListBillingGroups_cli_2_topic"></a>

次の例は、`list-billing-groups` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントとリージョンの請求グループを一覧表示するには**  
次の の`list-billing-groups`例では、 AWS アカウントと AWS リージョンに定義されているすべての請求グループを一覧表示します。  

```
aws iot list-billing-groups
```
出力:  

```
{
    "billingGroups": [
        {
            "groupName": "GroupOne",
            "groupArn": "arn:aws:iot:us-west-2:123456789012:billinggroup/GroupOne"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBillingGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-billing-groups.html)」を参照してください。

### `list-ca-certificates`
<a name="iot_ListCaCertificates_cli_2_topic"></a>

次の例は、`list-ca-certificates` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントに登録されている CA 証明書を一覧表示するには**  
次の の`list-ca-certificates`例では、 AWS アカウントに登録されている CA 証明書を一覧表示します。  

```
aws iot list-ca-certificates
```
出力:  

```
{
    "certificates": [
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cacert/f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467",
            "certificateId": "f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467",
            "status": "INACTIVE",
            "creationDate": 1569365372.053
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[独自の証明書を使用する](https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCaCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-ca-certificates.html)」を参照してください。

### `list-certificates-by-ca`
<a name="iot_ListCertificatesByCa_cli_2_topic"></a>

次のコード例は、`list-certificates-by-ca` を使用する方法を示しています。

**AWS CLI**  
**CA 証明書で署名されたすべてのデバイス証明書を一覧表示するには**  
次の の`list-certificates-by-ca`例では、指定された CA 証明書で署名された AWS アカウント内のすべてのデバイス証明書を一覧表示します。  

```
aws iot list-certificates-by-ca \
    --ca-certificate-id f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467
```
出力:  

```
{
    "certificates": [
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142",
            "certificateId": "488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142",
            "status": "ACTIVE",
            "creationDate": 1569363250.557
        }
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListCertificatesByCA](https://docs.aws.amazon.com/iot/latest/apireference/API_ListCertificatesByCA.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCertificatesByCa](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-certificates-by-ca.html)」を参照してください。

### `list-certificates`
<a name="iot_ListCertificates_cli_2_topic"></a>

次の例は、`list-certificates` を使用する方法を説明しています。

**AWS CLI**  
**例 1: AWS アカウントに登録されている証明書を一覧表示するには**  
次の `list-certificates` 例では、アカウントに登録されているすべての証明書を一覧表示します。デフォルトのページング制限数が 25 を超える場合は、このコマンドの `nextMarker` レスポンス値を使用して次のコマンドに指定し、結果の次のバッチを取得できます。`nextMarker` が値なしで返すまで繰り返します。  

```
aws iot list-certificates
```
出力:  

```
{
    "certificates": [
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/604c48437a57b7d5fc5d137c5be75011c6ee67c9a6943683a1acb4b1626bac36",
            "certificateId": "604c48437a57b7d5fc5d137c5be75011c6ee67c9a6943683a1acb4b1626bac36",
            "status": "ACTIVE",
            "creationDate": 1556810537.617
        },
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/262a1ac8a7d8aa72f6e96e365480f7313aa9db74b8339ec65d34dc3074e1c31e",
            "certificateId": "262a1ac8a7d8aa72f6e96e365480f7313aa9db74b8339ec65d34dc3074e1c31e",
            "status": "ACTIVE",
            "creationDate": 1546447050.885
        },
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/b193ab7162c0fadca83246d24fa090300a1236fe58137e121b011804d8ac1d6b",
            "certificateId": "b193ab7162c0fadca83246d24fa090300a1236fe58137e121b011804d8ac1d6b",
            "status": "ACTIVE",
            "creationDate": 1546292258.322
        },
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/7aebeea3845d14a44ec80b06b8b78a89f3f8a706974b8b34d18f5adf0741db42",
            "certificateId": "7aebeea3845d14a44ec80b06b8b78a89f3f8a706974b8b34d18f5adf0741db42",
            "status": "ACTIVE",
            "creationDate": 1541457693.453
        },
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/54458aa39ebb3eb39c91ffbbdcc3a6ca1c7c094d1644b889f735a6fc2cd9a7e3",
            "certificateId": "54458aa39ebb3eb39c91ffbbdcc3a6ca1c7c094d1644b889f735a6fc2cd9a7e3",
            "status": "ACTIVE",
            "creationDate": 1541113568.611
        },
        {
            "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/4f0ba725787aa94d67d2fca420eca022242532e8b3c58e7465c7778b443fd65e",
            "certificateId": "4f0ba725787aa94d67d2fca420eca022242532e8b3c58e7465c7778b443fd65e",
            "status": "ACTIVE",
            "creationDate": 1541022751.983
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-certificates.html)」を参照してください。

### `list-custom-metrics`
<a name="iot_ListCustomMetrics_cli_2_topic"></a>

次のコード例は、`list-custom-metrics` を使用する方法を示しています。

**AWS CLI**  
**カスタムメトリクスを一覧表示するには**  
以下の `list-custom-metrics` 例では、すべてのカスタムメトリクスをリストアップします。  

```
aws iot list-custom-metrics \
    --region us-east-1
```
出力:  

```
{
    "metricNames": [
        "batteryPercentage"
    ]
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[カスタムメトリクス](https://docs.aws.amazon.com/iot/latest/developerguide/dd-detect-custom-metrics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCustomMetrics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-custom-metrics.html)」を参照してください。

### `list-dimensions`
<a name="iot_ListDimensions_cli_2_topic"></a>

次の例は、`list-dimensions` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのディメンションを一覧表示するには**  
次の の`list-dimensions`例では、 AWS アカウントで定義されているすべての AWS IoT Device Defender ディメンションを一覧表示します。  

```
aws iot list-dimensions
```
出力:  

```
{
    "dimensionNames": [
        "TopicFilterForAuthMessages",
        "TopicFilterForActivityMessages"
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDimensions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-dimensions.html)」を参照してください。

### `list-domain-configurations`
<a name="iot_ListDomainConfigurations_cli_2_topic"></a>

次のコード例は、`list-domain-configurations` を使用する方法を示しています。

**AWS CLI**  
**ドメイン設定を一覧表示するには**  
次の の`list-domain-configurations`例では、指定されたサービスタイプを持つ AWS アカウントのドメイン設定を一覧表示します。  

```
aws iot list-domain-configurations \
    --service-type "DATA"
```
出力:  

```
{
    "domainConfigurations":
    [
        {
            "domainConfigurationName": "additionalDataDomain",
            "domainConfigurationArn": "arn:aws:iot:us-west-2:123456789012:domainconfiguration/additionalDataDomain/dikMh",
            "serviceType": "DATA"
        },

        {
            "domainConfigurationName": "iot:Jobs",
            "domainConfigurationArn": "arn:aws:iot:us-west-2:123456789012:domainconfiguration/iot:Jobs",
            "serviceType": "JOBS"
        },
        {
            "domainConfigurationName": "iot:Data-ATS",
            "domainConfigurationArn": "arn:aws:iot:us-west-2:123456789012:domainconfiguration/iot:Data-ATS",
            "serviceType": "DATA"
        },
        {
            "domainConfigurationName": "iot:CredentialProvider",
            "domainConfigurationArn": "arn:aws:iot:us-west-2:123456789012:domainconfiguration/iot:CredentialProvider",
            "serviceType": "CREDENTIAL_PROVIDER"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[設定可能なエンドポイント](https://docs.aws.amazon.com/iot/latest/developerguide/iot-custom-endpoints-configurable-aws.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDomainConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-domain-configurations.html)」を参照してください。

### `list-indices`
<a name="iot_ListIndices_cli_2_topic"></a>

次のコード例は、`list-indices` を使用する方法を示しています。

**AWS CLI**  
**設定された検索インデックスを一覧表示するには**  
次の の`list-indices`例では、 AWS アカウントに設定されているすべての検索インデックスを一覧表示します。モノのインデックス作成を有効にしていない場合は、インデックスがない可能性があります。  

```
aws iot list-indices
```
出力:  

```
{
    "indexNames": [
        "AWS_Things"
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのインデックス作成の管理](https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIndices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-indices.html)」を参照してください。

### `list-job-executions-for-job`
<a name="iot_ListJobExecutionsForJob_cli_2_topic"></a>

次の例は、`list-job-executions-for-job` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのジョブを一覧表示するには**  
次の の`list-job-executions-for-job`例では、 AWS jobId で指定されたアカウント内のジョブのすべてのジョブ実行を一覧表示します。  

```
aws iot list-job-executions-for-job \
    --job-id my-ota-job
```
出力:  

```
{
     "executionSummaries": [
         {
             "thingArn": "arn:aws:iot:us-east-1:123456789012:thing/my_thing",
             "jobExecutionSummary": {
                 "status": "QUEUED",
                 "queuedAt": "2022-03-07T15:58:42.195000-08:00",
                 "lastUpdatedAt": "2022-03-07T15:58:42.195000-08:00",
                 "executionNumber": 1,
                 "retryAttempt": 0
             }
         }
     ]
 }
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobExecutionsForJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-job-executions-for-job.html)」を参照してください。

### `list-job-executions-for-thing`
<a name="iot_ListJobExecutionsForThing_cli_2_topic"></a>

次のコード例は、`list-job-executions-for-thing` を使用する方法を示しています。

**AWS CLI**  
**モノに対して実行されたジョブを一覧表示するには**  
次の `list-job-executions-for-thing` の例では、`MyRaspberryPi` という名前のモノに対して実行されたすべてのジョブを一覧表示します。  

```
aws iot list-job-executions-for-thing \
    --thing-name "MyRaspberryPi"
```
出力:  

```
{
    "executionSummaries": [
        {
            "jobId": "example-job-01",
            "jobExecutionSummary": {
                "status": "QUEUED",
                "queuedAt": 1560787023.636,
                "lastUpdatedAt": 1560787023.636,
                "executionNumber": 1
            }
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobExecutionsForThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-job-executions-for-thing.html)」を参照してください。

### `list-jobs`
<a name="iot_ListJobs_cli_2_topic"></a>

次の例は、`list-jobs` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのジョブを一覧表示するには**  
次の の`list-jobs`例では、 AWS アカウント内のすべてのジョブをジョブステータスでソートして一覧表示します。  

```
aws iot list-jobs
```
出力:  

```
{
    "jobs": [
        {
            "jobArn": "arn:aws:iot:us-west-2:123456789012:job/example-job-01",
            "jobId": "example-job-01",
            "targetSelection": "SNAPSHOT",
            "status": "IN_PROGRESS",
            "createdAt": 1560787022.733,
            "lastUpdatedAt": 1560787026.294
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-jobs.html)」を参照してください。

### `list-mitigation-actions`
<a name="iot_ListMitigationActions_cli_2_topic"></a>

次のコード例は、`list-mitigation-actions` を使用する方法を示しています。

**AWS CLI**  
**定義されたすべての緩和アクションを一覧表示するには**  
次の の`list-mitigation-actions`例では、 AWS アカウントとリージョンに対して定義されたすべての緩和アクションを一覧表示します。アクションごとに、名前、ARN、作成日が一覧表示されます。  

```
aws iot list-mitigation-actions
```
出力:  

```
{
    "actionIdentifiers": [
        {
            "actionName": "DeactivateCACertAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/DeactivateCACertAction",
            "creationDate": "2019-12-10T11:12:47.574000-08:00"
        },
        {
            "actionName": "ResetPolicyVersionAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/ResetPolicyVersionAction",
            "creationDate": "2019-12-10T11:11:48.920000-08:00"
        },
        {
            "actionName": "PublishFindingToSNSAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/PublishFindingToSNSAction",
            "creationDate": "2019-12-10T11:10:49.546000-08:00"
        },
        {
            "actionName": "AddThingsToQuarantineGroupAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/AddThingsToQuarantineGroupAction",
            "creationDate": "2019-12-10T11:09:35.999000-08:00"
        },
        {
            "actionName": "UpdateDeviceCertAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/UpdateDeviceCertAction",
            "creationDate": "2019-12-10T11:08:44.263000-08:00"
        },
        {
            "actionName": "SampleMitigationAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/SampleMitigationAction",
            "creationDate": "2019-12-10T11:03:41.840000-08:00"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ListMitigationActions (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-ListMitigationActions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMitigationActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-mitigation-actions.html)」を参照してください。

### `list-mitigations-actions`
<a name="iot_ListMitigationsActions_cli_2_topic"></a>

次のコード例は、`list-mitigations-actions` を使用する方法を示しています。

**AWS CLI**  
**定義されたすべての緩和アクションを一覧表示するには**  
次の の`list-mitigations-actions`例では、 AWS アカウントとリージョンに対して定義されたすべての緩和アクションを一覧表示します。アクションごとに、名前、ARN、作成日が一覧表示されます。  

```
aws iot list-mitigation-actions
```
出力:  

```
{
    "actionIdentifiers": [
        {
            "actionName": "DeactivateCACertAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/DeactivateCACertAction",
            "creationDate": "2019-12-10T11:12:47.574000-08:00"
        },
        {
            "actionName": "ResetPolicyVersionAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/ResetPolicyVersionAction",
            "creationDate": "2019-12-10T11:11:48.920000-08:00"
        },
        {
            "actionName": "PublishFindingToSNSAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/PublishFindingToSNSAction",
            "creationDate": "2019-12-10T11:10:49.546000-08:00"
        },
        {
            "actionName": "AddThingsToQuarantineGroupAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/AddThingsToQuarantineGroupAction",
            "creationDate": "2019-12-10T11:09:35.999000-08:00"
        },
        {
            "actionName": "UpdateDeviceCertAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/UpdateDeviceCertAction",
            "creationDate": "2019-12-10T11:08:44.263000-08:00"
        },
        {
            "actionName": "SampleMitigationAction",
            "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/SampleMitigationAction",
            "creationDate": "2019-12-10T11:03:41.840000-08:00"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ListMitigationActions (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-ListMitigationActions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMitigationsActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-mitigations-actions.html)」を参照してください。

### `list-ota-updates`
<a name="iot_ListOtaUpdates_cli_2_topic"></a>

次のコード例は、`list-ota-updates` を使用する方法を示しています。

**AWS CLI**  
**アカウントの OTA 更新を一覧表示するには**  
次の `list-ota-updates` の例では、使用可能な OTA 更新を一覧表示します。  

```
aws iot list-ota-updates
```
出力:  

```
{
    "otaUpdates": [
        {
            "otaUpdateId": "itsaupdate",
            "otaUpdateArn": "arn:aws:iot:us-west-2:123456789012:otaupdate/itsaupdate",
            "creationDate": 1557863215.995
        }
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListOTAUpdates](https://docs.aws.amazon.com/iot/latest/apireference/API_ListOTAUpdates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOtaUpdates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-ota-updates.html)」を参照してください。

### `list-outgoing-certificates`
<a name="iot_ListOutgoingCertificates_cli_2_topic"></a>

次の例は、`list-outgoing-certificates` を使用する方法を説明しています。

**AWS CLI**  
**別の AWS アカウントに転送される証明書を一覧表示するには**  
次の の`list-outgoing-certificates`例では、 `transfer-certificate` コマンドを使用して別の AWS アカウントに転送中のすべてのデバイス証明書を一覧表示します。  

```
aws iot list-outgoing-certificates
```
出力:  

```
{
    "outgoingCertificates": [
        {
            "certificateArn": "arn:aws:iot:us-west-2:030714055129:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142",
            "certificateId": "488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142",
            "transferredTo": "030714055129",
            "transferDate": 1569427780.441,
            "creationDate": 1569363250.557
        }
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListOutgoingCertificates](https://docs.aws.amazon.com/iot/latest/apireference/API_ListOutgoingCertificates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOutgoingCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-outgoing-certificates.html)」を参照してください。

### `list-policies`
<a name="iot_ListPolicies_cli_2_topic"></a>

次の例は、`list-policies` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントで定義されているポリシーを一覧表示するには**  
次の の`list-policies`例では、 AWS アカウントで定義されているすべてのポリシーを一覧表示します。  

```
aws iot list-policies
```
出力:  

```
{
    "policies": [
        {
            "policyName": "UpdateDeviceCertPolicy",
            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/UpdateDeviceCertPolicy"
        },
        {
            "policyName": "PlantIoTPolicy",
            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/PlantIoTPolicy"
        },
        {
            "policyName": "MyPiGroup_Core-policy",
            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/MyPiGroup_Core-policy"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「AWS CLI Command Reference」の「[ListPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-policies.html)」を参照してください。**

### `list-policy-versions`
<a name="iot_ListPolicyVersions_cli_2_topic"></a>

次のコード例は、`list-policy-versions` を使用する方法を示しています。

**AWS CLI**  
**例 1: ポリシーのすべてのバージョンを表示するには**  
次の `list-policy-versions` の例では、指定されたポリシーのすべてのバージョンとその作成日を一覧表示します。  

```
aws iot list-policy-versions \
    --policy-name LightBulbPolicy
```
出力:  

```
{
    "policyVersions": [
        {
            "versionId": "2",
            "isDefaultVersion": true,
            "createDate": 1559925941.924
        },
        {
            "versionId": "1",
            "isDefaultVersion": false,
            "createDate": 1559925941.924
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[AWS IoT ポリシー](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPolicyVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-policy-versions.html)」を参照してください。

### `list-principal-things`
<a name="iot_ListPrincipalThings_cli_2_topic"></a>

次のコード例は、`list-principal-things` を使用する方法を示しています。

**AWS CLI**  
**プリンシパルにアタッチされたモノを一覧表示するには**  
次の `list-principal-things` の例では、ARN によって指定されたプリンシパルにアタッチされたモノを一覧表示します。  

```
aws iot list-principal-things \
    --principal arn:aws:iot:us-west-2:123456789012:cert/2e1eb273792174ec2b9bf4e9b37e6c6c692345499506002a35159767055278e8
```
出力:  

```
{
    "things": [
        "DeskLamp",
        "TableLamp"
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListPrincipalThings](https://docs.aws.amazon.com/iot/latest/apireference/API_ListPrincipleThings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPrincipalThings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-principal-things.html)」を参照してください。

### `list-provisioning-template-versions`
<a name="iot_ListProvisioningTemplateVersions_cli_2_topic"></a>

次のコード例は、`list-provisioning-template-versions` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートのバージョンを一覧表示するには**  
次の `list-provisioning-template-versions` の例では、指定されたプロビジョニングテンプレートの使用可能なバージョンを一覧表示します。  

```
aws iot list-provisioning-template-versions \
    --template-name "widget-template"
```
出力:  

```
{
    "versions": [
        {
            "versionId": 1,
            "creationDate": 1574800471.339,
            "isDefaultVersion": true
        },
        {
            "versionId": 2,
            "creationDate": 1574801192.317,
            "isDefaultVersion": false
        }
    ]
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[AWS セキュアトンネリング](https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProvisioningTemplateVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-provisioning-template-versions.html)」を参照してください。

### `list-provisioning-templates`
<a name="iot_ListProvisioningTemplates_cli_2_topic"></a>

次のコード例は、`list-provisioning-templates` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートを一覧表示するには**  
次の の`list-provisioning-templates`例では、 AWS アカウント内のすべてのプロビジョニングテンプレートを一覧表示します。  

```
aws iot list-provisioning-templates
```
出力:  

```
{
    "templates": [
        {
            "templateArn": "arn:aws:iot:us-east-1:123456789012:provisioningtemplate/widget-template",
            "templateName": "widget-template",
            "description": "A provisioning template for widgets",
            "creationDate": 1574800471.367,
            "lastModifiedDate": 1574801192.324,
            "enabled": false
        }
    ]
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[AWS セキュアトンネリング](https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProvisioningTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-provisioning-templates.html)」を参照してください。

### `list-role-aliases`
<a name="iot_ListRoleAliases_cli_2_topic"></a>

次の例は、`list-role-aliases` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントの AWS IoT ロールエイリアスを一覧表示するには**  
次の の`list-role-aliases`例では、 AWS アカウントの AWS IoT ロールエイリアスを一覧表示します。  

```
aws iot list-role-aliases
```
出力:  

```
{
    "roleAliases": [
        "ResidentAlias",
        "ElectricianAlias"
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListRoleAliases](https://docs.aws.amazon.com/iot/latest/apireference/API_ListRoleAliases.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoleAliases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-role-aliases.html)」を参照してください。

### `list-scheduled-audits`
<a name="iot_ListScheduledAudits_cli_2_topic"></a>

次の例は、`list-scheduled-audits` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのスケジュールされた監査を一覧表示するには**  
次の の`list-scheduled-audits`例では、 AWS アカウントにスケジュールされた監査を一覧表示します。  

```
aws iot list-scheduled-audits
```
出力:  

```
{
    "scheduledAudits": [
        {
            "scheduledAuditName": "AWSIoTDeviceDefenderDailyAudit",
            "scheduledAuditArn": "arn:aws:iot:us-west-2:123456789012:scheduledaudit/AWSIoTDeviceDefenderDailyAudit",
            "frequency": "DAILY"
        },
        {
            "scheduledAuditName": "AWSDeviceDefenderWeeklyAudit",
            "scheduledAuditArn": "arn:aws:iot:us-west-2:123456789012:scheduledaudit/AWSDeviceDefenderWeeklyAudit",
            "frequency": "WEEKLY",
            "dayOfWeek": "SUN"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListScheduledAudits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-scheduled-audits.html)」を参照してください。

### `list-security-profiles-for-target`
<a name="iot_ListSecurityProfilesForTarget_cli_2_topic"></a>

次のコード例は、`list-security-profiles-for-target` を使用する方法を示しています。

**AWS CLI**  
**ターゲットにアタッチされたセキュリティプロファイルを一覧表示するには**  
次の の`list-security-profiles-for-target`例では、未登録のデバイスにアタッチされている AWS IoT Device Defender セキュリティプロファイルを一覧表示します。  

```
aws iot list-security-profiles-for-target  \
    --security-profile-target-arn "arn:aws:iot:us-west-2:123456789012:all/unregistered-things"
```
出力:  

```
{
    "securityProfileTargetMappings": [
        {
            "securityProfileIdentifier": {
                "name": "Testprofile",
                "arn": "arn:aws:iot:us-west-2:123456789012:securityprofile/Testprofile"
            },
            "target": {
                "arn": "arn:aws:iot:us-west-2:123456789012:all/unregistered-things"
            }
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSecurityProfilesForTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-security-profiles-for-target.html)」を参照してください。

### `list-security-profiles`
<a name="iot_ListSecurityProfiles_cli_2_topic"></a>

次の例は、`list-security-profiles` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのセキュリティプロファイルを一覧表示するには**  
次の の`list-security-profiles`例では、 AWS アカウントで定義されているすべての AWS IoT Device Defender セキュリティプロファイルを一覧表示します。  

```
aws iot list-security-profiles
```
出力:  

```
{
    "securityProfileIdentifiers": [
        {
            "name": "Testprofile",
            "arn": "arn:aws:iot:us-west-2:123456789012:securityprofile/Testprofile"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSecurityProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-security-profiles.html)」を参照してください。

### `list-streams`
<a name="iot_ListStreams_cli_2_topic"></a>

次のコード例は、`list-streams` を使用する方法を示しています。

**AWS CLI**  
**アカウントのストリームを一覧表示するには**  
次の の`list-streams`例では、 AWS アカウントのすべてのストリームを一覧表示します。  

```
aws iot list-streams
```
出力:  

```
{
    "streams": [
        {
            "streamId": "stream12345",
            "streamArn": "arn:aws:iot:us-west-2:123456789012:stream/stream12345",
            "streamVersion": 1,
            "description": "This stream is used for Amazon FreeRTOS OTA Update 12345."
        },
        {
            "streamId": "stream54321",
            "streamArn": "arn:aws:iot:us-west-2:123456789012:stream/stream54321",
            "streamVersion": 1,
            "description": "This stream is used for Amazon FreeRTOS OTA Update 54321."
        }
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListStreams](https://docs.aws.amazon.com/iot/latest/apireference/API_ListStreams.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-streams.html)」を参照してください。**

### `list-tags-for-resource`
<a name="iot_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに関連付けられたタグとその値を表示するには**  
次の `list-tags-for-resource` の例では、モノのグループ `LightBulbs` に関連付けられたタグと値を表示します。  

```
aws iot list-tags-for-resource \
    --resource-arn "arn:aws:iot:us-west-2:094249569039:thinggroup/LightBulbs"
```
出力:  

```
{
    "tags": [
        {
            "Key": "Assembly",
            "Value": "Fact1NW"
        },
        {
            "Key": "MyTag",
            "Value": "777"
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT リソースのタグ付け](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-tags-for-resource.html)」を参照してください。

### `list-targets-for-policy`
<a name="iot_ListTargetsForPolicy_cli_2_topic"></a>

次の例は、`list-targets-for-policy` を使用する方法を説明しています。

**AWS CLI**  
** AWS IoT ポリシーに関連付けられているプリンシパルを一覧表示するには**  
次の `list-targets-for-policy` の例では、指定されたポリシーがアタッチされているデバイス証明書を一覧表示します。  

```
aws iot list-targets-for-policy \
    --policy-name UpdateDeviceCertPolicy
```
出力:  

```
{
    "targets": [
        "arn:aws:iot:us-west-2:123456789012:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142",
        "arn:aws:iot:us-west-2:123456789012:cert/d1eb269fb55a628552143c8f96eb3c258fcd5331ea113e766ba0c82bf225f0be"
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTargetsForPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-targets-for-policy.html)」を参照してください。

### `list-targets-for-security-profile`
<a name="iot_ListTargetsForSecurityProfile_cli_2_topic"></a>

次のコード例は、`list-targets-for-security-profile` を使用する方法を示しています。

**AWS CLI**  
**セキュリティプロファイルが適用されるターゲットを一覧表示するには**  
次の の`list-targets-for-security-profile`例では、 という名前の AWS IoT Device Defender セキュリティプロファイル`PossibleIssue`が適用されるターゲットを一覧表示します。  

```
aws iot list-targets-for-security-profile \
    --security-profile-name Testprofile
```
出力:  

```
{
    "securityProfileTargets": [
        {
            "arn": "arn:aws:iot:us-west-2:123456789012:all/unregistered-things"
        },
        {
            "arn": "arn:aws:iot:us-west-2:123456789012:all/registered-things"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTargetsForSecurityProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-targets-for-security-profile.html)」を参照してください。

### `list-thing-groups-for-thing`
<a name="iot_ListThingGroupsForThing_cli_2_topic"></a>

次のコード例は、`list-thing-groups-for-thing` を使用する方法を示しています。

**AWS CLI**  
**モノが属するモノのグループを一覧表示するには**  
次の `list-thing-groups-for-thing` の例では、指定されたモノが属するグループを一覧表示します。  

```
aws iot list-thing-groups-for-thing \
    --thing-name MyLightBulb
```
出力:  

```
{
    "thingGroups": [
        {
            "groupName": "DeadBulbs",
            "groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/DeadBulbs"
        },
        {
            "groupName": "LightBulbs",
            "groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListThingGroupsForThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-thing-groups-for-thing.html)」を参照してください。

### `list-thing-groups`
<a name="iot_ListThingGroups_cli_2_topic"></a>

次の例は、`list-thing-groups` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントで定義されているモノのグループを一覧表示するには**  
次の の`describe-thing-group`例では、 AWS アカウントで定義されているすべてのモノのグループを一覧表示します。  

```
aws iot list-thing-groups
```
出力:  

```
{
    "thingGroups": [
        {
            "groupName": "HalogenBulbs",
            "groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/HalogenBulbs"
        },
        {
            "groupName": "LightBulbs",
            "groupArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/LightBulbs"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListThingGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-thing-groups.html)」を参照してください。

### `list-thing-principals`
<a name="iot_ListThingPrincipals_cli_2_topic"></a>

次のコード例は、`list-thing-principals` を使用する方法を示しています。

**AWS CLI**  
**モノに関連付けられているプリンシパルを一覧表示するには**  
次の `list-thing-principals` の例では、指定されたモノに関連付けられているプリンシパル (X.509 証明書、IAM ユーザー、グループ、ロール、Amazon Cognito ID、またはフェデレーティッド ID) を一覧表示します。  

```
aws iot list-thing-principals \
    --thing-name MyRaspberryPi
```
出力:  

```
{
    "principals": [
        "arn:aws:iot:us-west-2:123456789012:cert/33475ac865079a5ffd5ecd44240640349293facc760642d7d8d5dbb6b4c86893"
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListThingPrincipals](https://docs.aws.amazon.com/iot/latest/apireference/API_ListThingPrincipals.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListThingPrincipals](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-thing-principals.html)」を参照してください。

### `list-thing-types`
<a name="iot_ListThingTypes_cli_2_topic"></a>

次のコード例は、`list-thing-types` を使用する方法を示しています。

**AWS CLI**  
**定義されたモノのタイプを一覧表示するには**  
次の の`list-thing-types`例では、 AWS アカウントで定義されたモノのタイプのリストを表示します。  

```
aws iot list-thing-types
```
出力:  

```
{
    "thingTypes": [
        {
            "thingTypeName": "LightBulb",
            "thingTypeArn": "arn:aws:iot:us-west-2:123456789012:thingtype/LightBulb",
            "thingTypeProperties": {
                "thingTypeDescription": "light bulb type",
                "searchableAttributes": [
                    "model",
                    "wattage"
                ]
            },
            "thingTypeMetadata": {
            "deprecated": false,
            "creationDate": 1559772562.498
            }
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」「[モノのタイプ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListThingTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-thing-types.html)」を参照してください。

### `list-things-in-billing-group`
<a name="iot_ListThingsInBillingGroup_cli_2_topic"></a>

次のコード例は、`list-things-in-billing-group` を使用する方法を示しています。

**AWS CLI**  
**請求グループ内のモノを一覧表示するには**  
次の `list-things-in-billing-group` の例では、指定された請求グループにあるモノを一覧表示します。  

```
aws iot list-things-in-billing-group \
    --billing-group-name GroupOne
```
出力:  

```
{
    "things": [
        "MyOtherLightBulb",
        "MyLightBulb"
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListThingsInBillingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-things-in-billing-group.html)」を参照してください。

### `list-things-in-thing-group`
<a name="iot_ListThingsInThingGroup_cli_2_topic"></a>

次のコード例は、`list-things-in-thing-group` を使用する方法を示しています。

**AWS CLI**  
**グループに属するモノを一覧表示するには**  
次の `list-things-in-thing-group` の例では、指定されたモノのグループに属するモノを一覧表示します。  

```
aws iot list-things-in-thing-group \
    --thing-group-name LightBulbs
```
出力:  

```
{
    "things": [
        "MyLightBulb"
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListThingsInThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-things-in-thing-group.html)」を参照してください。

### `list-things`
<a name="iot_ListThings_cli_2_topic"></a>

次のコード例は、`list-things` を使用する方法を示しています。

**AWS CLI**  
**例 1: レジストリ内のすべてのモノを一覧表示するには**  
次の の`list-things`例では、 AWS アカウントの AWS IoT レジストリで定義されているモノ (デバイス) を一覧表示します。  

```
aws iot list-things
```
出力:  

```
{
    "things": [
        {
            "thingName": "ThirdBulb",
            "thingTypeName": "LightBulb",
            "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/ThirdBulb",
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "version": 2
        },
        {
            "thingName": "MyOtherLightBulb",
            "thingTypeName": "LightBulb",
            "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyOtherLightBulb",
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "version": 3
        },
        {
            "thingName": "MyLightBulb",
            "thingTypeName": "LightBulb",
            "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyLightBulb",
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "version": 1
        },
        {
        "thingName": "SampleIoTThing",
        "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/SampleIoTThing",
        "attributes": {},
        "version": 1
        }
    ]
}
```
**例 2: 特定の属性を持つ定義済みのモノを一覧表示するには**  
次の `list-things` の例は、`wattage` という名前の属性を持つモノのリストを表示します。  

```
aws iot list-things \
    --attribute-name wattage
```
出力:  

```
{
    "things": [
        {
            "thingName": "MyLightBulb",
            "thingTypeName": "LightBulb",
            "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyLightBulb",
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "version": 1
        },
        {
            "thingName": "MyOtherLightBulb",
            "thingTypeName": "LightBulb",
            "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyOtherLightBulb",
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "version": 3
        }
    ]
}
```
詳細については、「AWS IoT ディベロッパーガイド」の「[レジストリによるモノの管理方法](https://docs.aws.amazon.com/iot/latest/developerguide/thing-registry.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListThings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-things.html)」を参照してください。**

### `list-topic-rule-destinations`
<a name="iot_ListTopicRuleDestinations_cli_2_topic"></a>

次のコード例は、`list-topic-rule-destinations` を使用する方法を示しています。

**AWS CLI**  
**トピックルールの送信先を一覧表示するには**  
次の の`list-topic-rule-destinations`例では、現在の AWS リージョンで定義したすべてのトピックルールの送信先を一覧表示します。  

```
aws iot list-topic-rule-destinations
```
出力:  

```
{
    "destinationSummaries": [
        {
            "arn": "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "status": "ENABLED",
            "httpUrlSummary": {
                "confirmationUrl": "https://example.com"
            }
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[トピックルールの送信先の操作](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTopicRuleDestinations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-topic-rule-destinations.html)」を参照してください。

### `list-topic-rules`
<a name="iot_ListTopicRules_cli_2_topic"></a>

次のコード例は、`list-topic-rules` を使用する方法を示しています。

**AWS CLI**  
**ルールを一覧表示するには**  
次の `list-topic-rules` の例では、定義したすべてのルールを一覧表示します。  

```
aws iot list-topic-rules
```
出力:  

```
{
    "rules": [
        {
            "ruleArn": "arn:aws:iot:us-west-2:123456789012:rule/MyRPiLowMoistureAlertRule",
            "ruleName": "MyRPiLowMoistureAlertRule",
            "topicPattern": "$aws/things/MyRPi/shadow/update/accepted",
            "createdAt": 1558624363.0,
            "ruleDisabled": false
        },
        {
            "ruleArn": "arn:aws:iot:us-west-2:123456789012:rule/MyPlantPiMoistureAlertRule",
            "ruleName": "MyPlantPiMoistureAlertRule",
            "topicPattern": "$aws/things/MyPlantPi/shadow/update/accepted",
            "createdAt": 1541458459.0,
            "ruleDisabled": false
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ルールの表示](https://docs.aws.amazon.com/iot/latest/developerguide/iot-managae-rule.html#iot-view-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTopicRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-topic-rules.html)」を参照してください。

### `list-v2-logging-levels`
<a name="iot_ListV2LoggingLevels_cli_2_topic"></a>

次のコード例は、`list-v2-logging-levels` を使用する方法を示しています。

**AWS CLI**  
**ログ記録レベルを一覧表示するには**  
次の `list-v2-logging-levels` の例では、設定されたログ記録レベルを一覧表示します。ログ記録レベルが設定されていない場合、このコマンドを実行すると `NotConfiguredException` が発生します。  

```
aws iot list-v2-logging-levels
```
出力:  

```
{
    "logTargetConfigurations": [
        {
            "logTarget": {
                "targetType": "DEFAULT"
            },
            "logLevel": "ERROR"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListV2LoggingLevels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-v2-logging-levels.html)」を参照してください。

### `list-violation-events`
<a name="iot_ListViolationEvents_cli_2_topic"></a>

次のコード例は、`list-violation-events` を使用する方法を示しています。

**AWS CLI**  
**期間中のセキュリティプロファイル違反を一覧表示するには**  
次の の`list-violation-events`例では、現在の AWS アカウントと AWS リージョンのすべての AWS IoT Device Defender セキュリティプロファイルについて、2019 年 6 月 5 日から 2019 年 6 月 12 日までに発生した違反を一覧表示します。  

```
aws iot list-violation-events \
    --start-time 1559747125 \
    --end-time 1560351925
```
出力:  

```
{
    "violationEvents": [
        {
            "violationId": "174db59167fa474c80a652ad1583fd44",
            "thingName": "iotconsole-1560269126751-1",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "Authorization",
                "metric": "aws:num-authorization-failures",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 10
                    },
                    "durationSeconds": 300,
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "metricValue": {
                "count": 0
            },
            "violationEventType": "in-alarm",
            "violationEventTime": 1560279000.0
        },
        {
            "violationId": "c8a9466a093d3b7b35cd44ca58bdbeab",
            "thingName": "TvnQoEoU",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "CellularBandwidth",
                "metric": "aws:message-byte-size",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 128
                    },
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "metricValue": {
                "count": 110
            },
            "violationEventType": "in-alarm",
            "violationEventTime": 1560276600.0
        },
        {
            "violationId": "74aa393adea02e6648f3ac362beed55e",
            "thingName": "iotconsole-1560269232412-2",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "Authorization",
                "metric": "aws:num-authorization-failures",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 10
                    },
                    "durationSeconds": 300,
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "metricValue": {
                "count": 0
            },
            "violationEventType": "in-alarm",
            "violationEventTime": 1560276600.0
        },
        {
            "violationId": "1e6ab5f7cf39a1466fcd154e1377e406",
            "thingName": "TvnQoEoU",
            "securityProfileName": "Testprofile",
            "behavior": {
                "name": "Authorization",
                "metric": "aws:num-authorization-failures",
                "criteria": {
                    "comparisonOperator": "greater-than",
                    "value": {
                        "count": 10
                    },
                    "durationSeconds": 300,
                    "consecutiveDatapointsToAlarm": 1,
                    "consecutiveDatapointsToClear": 1
                }
            },
            "metricValue": {
                "count": 0
            },
            "violationEventType": "in-alarm",
            "violationEventTime": 1560276600.0
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListViolationEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/list-violation-events.html)」を参照してください。

### `register-ca-certificate`
<a name="iot_RegisterCaCertificate_cli_2_topic"></a>

次のコード例は、`register-ca-certificate` を使用する方法を示しています。

**AWS CLI**  
**認証局 (CA) 証明書を登録するには**  
次の `register-ca-certificate` の例では、CA 証明書を登録します。このコマンドは、CA 証明書と、CA 証明書に関連付けられたプライベートキーを所有していることを証明するキー検証証明書を提供します。  

```
aws iot register-ca-certificate \
    --ca-certificate file://rootCA.pem \
    --verification-cert file://verificationCert.pem
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cacert/f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467",
    "certificateId": "f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467"
 }
```
詳細については、「*AWS IoT API リファレンス*」の「[RegisterCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCACertificate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterCaCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-ca-certificate.html)」を参照してください。

### `register-certificate`
<a name="iot_RegisterCertificate_cli_2_topic"></a>

次のコード例は、`register-certificate` を使用する方法を示しています。

**AWS CLI**  
**自己署名デバイス証明書を登録するには**  
次の `register-certificate` の例では、`rootCA.pem` CA 証明書によって署名された `deviceCert.pem` デバイス証明書を登録します。CA 証明書は、自己署名デバイス証明書の登録に使用する前に登録する必要があります。自己署名証明書は、このコマンドに渡すのと同じ CA 証明書で署名する必要があります。  

```
aws iot register-certificate \
    --certificate-pem file://deviceCert.pem \
    --ca-certificate-pem file://rootCA.pem
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142",
    "certificateId": "488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142"
 }
```
詳細については、「*AWS IoT API リファレンス*」の「[RegisterCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_RegisterCertificate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-certificate.html)」を参照してください。

### `register-thing`
<a name="iot_RegisterThing_cli_2_topic"></a>

次のコード例は、`register-thing` を使用する方法を示しています。

**AWS CLI**  
**モノを登録するには**  
次の `register-thing` の例では、プロビジョニングテンプレートを使用してモノを登録します。  

```
aws iot register-thing \
    --template-body '{"Parameters":{"ThingName":{"Type":"String"},"AWS::IoT::Certificate::Id":{"Type":"String"}},"Resources": {"certificate":{"Properties":{"CertificateId":{"Ref":"AWS::IoT::Certificate::Id"},"Status":"Active"},"Type":"AWS::IoT::Certificate"},"policy":{"Properties":{"PolicyName":"MyIotPolicy"},"Type":"AWS::IoT::Policy"},"thing":{"OverrideSettings":{"AttributePayload":"MERGE","ThingGroups":"DO_NOTHING","ThingTypeName":"REPLACE"},"Properties":{"AttributePayload":{},"ThingGroups":[],"ThingName":{"Ref":"ThingName"},"ThingTypeName":"VirtualThings"},"Type":"AWS::IoT::Thing"}}}' \
    --parameters '{"ThingName":"Register-thing-trial-1","AWS::IoT::Certificate::Id":"799a9ea048a1e6aea42b55EXAMPLEf8697b4bafcd77a318a3068e30404b9233c"}'
```
出力:  

```
{
    "certificatePem": "-----BEGIN CERTIFICATE-----\nMIIDWTCCAkGgAwIBAgIUYLk81I35cIppobpw
HiOJ2jNjboIwDQYJKoZIhvcNAQEL\nBQAwTTFLMEkGA1UECwxCQW1hem9uIFdlYiBTZXJ2aWNlcyBPPUFtYXpvbi
5jb20g\nSW5jLiBMPVNlYXR0bGUgU1Q9V2FzaGluZ3RvbiBDPVVTMB4XDTIwMDcyMzE2NDUw\nOVoXDTQ5MTIzMT
IzNTk1OVowHjEcMBoGA1UEAwwTQVdTIElvVCBDZXJ0aWZpY2F0\nZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
AQoCggEBAO71uADhdBajqTmgrMV5\nmCFfBZQRMo1MdtVoZr2X+M4MzL+RARrtUzH9a2SMAckeX8KeblIOTKzORI
RDXnyE\n6lVOwjgAsd0ku22rFxex4eG2ikha7pYYkvuToqA7L3TxItRvfKrxRI4ZfJoFPip4\nKqiuBJVNOGKTcQ
Hd1RNOrddwwu6kFJLeKDmEXAMPLEdUF0N+qfR9yKnZQkm+g6Q2\nGXu7u0W3hn6nlRN8qVoka0uW12p53xM7oHVz
Gf+cxKBxlbOhGkp6yCfTSkUBm3Sp\n9zLw35kiHXVm4EVpwgNlnk6XcIGIkw8a/iy4pzmvuGAANY1/uU/zgCjymw
ZT5S30\nBV0CAwEAAaNgMF4wHwYDVR0jBBgwFoAUGx0tCcU3q2n1WXAuUCv6hugXjKswHQYD\nVR0OBBYEFOVtvZ
9Aj2RYFnkX7Iu01XTRUdxgMAwGA1UdEwEB/wQCMAAwDgYDVR0P\nAQH/BAQDAgeAMA0GCSqGSIb3DQEBCwUAA4IB
AQCXCQcpOtubS5ftOsDMTcpP/jNX\nDHyArxmjpSc2aCdmm7WX59lTKWyAdxGAvqaDVWqTo0oXI7tZ8w7aINlGi5
pXnifx\n3SBebMUoBbTktrC97yUaeL025mCFv8emDnTR/fE7PTsBKjW0g/rrfpwBxZLXDFwN\nnqkQjy3EDfifj2
6j0xYIqqWMPogyn4srOCKynS5wMJuQZlHQOnabVwnwK4Y0Mflp\np9+4susFUR9aT3BT1AcIwqSpzhlKhh4Iz7ND
kRn4amsUT210jg/zOO1Ow+BTHcVQ\nJly8XDu0CWSu04q6SnaBzHmlySIajxuRTP/AdfRouP1OXe+qlbPOBcvVvF
8o\n-----END CERTIFICATE-----\n",
    "resourceArns": {
        "certificate": "arn:aws:iot:us-west-2:571032923833:cert/799a9ea048a1e6aea42b55EXAMPLEf8697b4bafcd77a318a3068e30404b9233c",
        "thing": "arn:aws:iot:us-west-2:571032923833:thing/Register-thing-trial-1"
    }
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[信頼できるユーザーによるプロビジョニング](https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html#trusted-user)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/register-thing.html)」を参照してください。

### `reject-certificate-transfer`
<a name="iot_RejectCertificateTransfer_cli_2_topic"></a>

次のコード例は、`reject-certificate-transfer` を使用する方法を示しています。

**AWS CLI**  
**証明書の転送を拒否するには**  
次の の`reject-certificate-transfer`例では、指定されたデバイス証明書の別の AWS アカウントからの移管を拒否します。  

```
aws iot reject-certificate-transfer \
    --certificate-id f0f33678c7c9a046e5cc87b2b1a58dfa0beec26db78addd5e605d630e05c7fc8
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[証明書を別のアカウントに転送する](https://docs.aws.amazon.com/iot/latest/developerguide/transfer-cert.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectCertificateTransfer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/reject-certificate-transfer.html)」を参照してください。

### `remove-thing-from-billing-group`
<a name="iot_RemoveThingFromBillingGroup_cli_2_topic"></a>

次のコード例は、`remove-thing-from-billing-group` を使用する方法を示しています。

**AWS CLI**  
**請求グループからモノを削除するには**  
次の `remove-thing-from-billing-group` の例では、請求グループから指定されたモノを削除します。  

```
aws iot remove-thing-from-billing-group \
    --billing-group-name GroupOne \
    --thing-name MyOtherLightBulb
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveThingFromBillingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/remove-thing-from-billing-group.html)」を参照してください。

### `remove-thing-from-thing-group`
<a name="iot_RemoveThingFromThingGroup_cli_2_topic"></a>

次のコード例は、`remove-thing-from-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノのグループからモノを削除するには**  
次の `remove-thing-from-thing-group` 例では、モノのグループから指定されたモノを削除します。  

```
aws iot remove-thing-from-thing-group \
    --thing-name bulb7 \
    --thing-group-name DeadBulbs
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「モノのグループ <https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html >」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveThingFromThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/remove-thing-from-thing-group.html)」を参照してください。

### `replace-topic-rule`
<a name="iot_ReplaceTopicRule_cli_2_topic"></a>

次のコード例は、`replace-topic-rule` を使用する方法を示しています。

**AWS CLI**  
**トピックのルール定義を更新するには**  
次の `replace-topic-rule` の例では、土壌湿度レベルの読み取り値が低すぎると、指定されたルールを更新して SNS アラートを送信します。  

```
aws iot replace-topic-rule \
    --rule-name MyRPiLowMoistureAlertRule \
    --topic-rule-payload "{\"sql\": \"SELECT * FROM '$aws/things/MyRPi/shadow/update/accepted' WHERE state.reported.moisture = 'low'\", \"description\": \"Sends an alert when soil moisture level readings are too low.\",\"actions\": [{\"sns\":{\"targetArn\":\"arn:aws:sns:us-west-2:123456789012:MyRPiLowMoistureTopic\",\"roleArn\":\"arn:aws:iam::123456789012:role/service-role/MyRPiLowMoistureTopicRole\",\"messageFormat\": \"RAW\"}}],\"ruleDisabled\": false,\"awsIotSqlVersion\":\"2016-03-23\"}"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「Creating anIoT Rule](https://docs.aws.amazon.com/iot/latest/developerguide/iot-create-rule.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReplaceTopicRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/replace-topic-rule.html)」を参照してください。

### `search-index`
<a name="iot_SearchIndex_cli_2_topic"></a>

次のコード例は、`search-index` を使用する方法を示しています。

**AWS CLI**  
**モノのインデックスをクエリするには**  
次の `search-index` 例では、`LightBulb` タイプを持つモノについて `AWS_Things` インデックスをクエリします。  

```
aws iot search-index \
    --index-name "AWS_Things" \
    --query-string "thingTypeName:LightBulb"
```
出力:  

```
{
    "things": [
        {
            "thingName": "MyLightBulb",
            "thingId": "40da2e73-c6af-406e-b415-15acae538797",
            "thingTypeName": "LightBulb",
            "thingGroupNames": [
                "LightBulbs",
                "DeadBulbs"
            ],
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "connectivity": {
                "connected": false
            }
        },
        {
            "thingName": "ThirdBulb",
            "thingId": "615c8455-33d5-40e8-95fd-3ee8b24490af",
            "thingTypeName": "LightBulb",
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "connectivity": {
                "connected": false
            }
        },
        {
            "thingName": "MyOtherLightBulb",
            "thingId": "6dae0d3f-40c1-476a-80c4-1ed24ba6aa11",
            "thingTypeName": "LightBulb",
            "attributes": {
                "model": "123",
                "wattage": "75"
            },
            "connectivity": {
                "connected": false
            }
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのインデックス作成の管理](https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/search-index.html)」を参照してください。

### `set-default-authorizer`
<a name="iot_SetDefaultAuthorizer_cli_2_topic"></a>

次のコード例は、`set-default-authorizer` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのオーソライザーを設定するには**  
次の `set-default-authorizer` の例では、`CustomAuthorizer` という名前のカスタムオーソライザーをデフォルトのオーソライザーとして設定します。  

```
aws iot set-default-authorizer \
    --authorizer-name CustomAuthorizer
```
出力:  

```
{
    "authorizerName": "CustomAuthorizer",
    "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[CreateDefaultAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_CreateDefaultAuthorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetDefaultAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/set-default-authorizer.html)」を参照してください。

### `set-default-policy-version`
<a name="iot_SetDefaultPolicyVersion_cli_2_topic"></a>

次のコード例は、`set-default-policy-version` を使用する方法を示しています。

**AWS CLI**  
**ポリシーのデフォルトバージョンを設定するには**  
次の `set-default-policy-version` の例では、`UpdateDeviceCertPolicy` という名前のポリシーのデフォルトバージョンを `2` に設定します。  

```
aws iot set-default-policy-version \
    --policy-name UpdateDeviceCertPolicy \
    --policy-version-id 2
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetDefaultPolicyVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/set-default-policy-version.html)」を参照してください。

### `set-v2-logging-level`
<a name="iot_SetV2LoggingLevel_cli_2_topic"></a>

次のコード例は、`set-v2-logging-level` を使用する方法を示しています。

**AWS CLI**  
**モノのグループのログ記録レベルを設定するには**  
次の `set-v2-logging-level` の例では、指定されたモノのグループの警告をログに記録するようにログ記録レベルを設定します。  

```
aws iot set-v2-logging-level \
    --log-target "{\"targetType\":\"THING_GROUP\",\"targetName\":\"LightBulbs\"}" \
    --log-level WARN
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetV2LoggingLevel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/set-v2-logging-level.html)」を参照してください。

### `set-v2-logging-options`
<a name="iot_SetV2LoggingOptions_cli_2_topic"></a>

次のコード例は、`set-v2-logging-options` を使用する方法を示しています。

**AWS CLI**  
**ログ記録オプションを設定するには**  
次の `set-v2-logging-options` の例では、デフォルトのログ詳細レベルを ERROR に設定し、ログ記録に使用する ARN を指定します。  

```
aws iot set-v2-logging-options \
    --default-log-level ERROR \
    --role-arn "arn:aws:iam::094249569039:role/service-role/iotLoggingRole"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetV2LoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/set-v2-logging-options.html)」を参照してください。

### `start-audit-mitigation-actions-task`
<a name="iot_StartAuditMitigationActionsTask_cli_2_topic"></a>

次のコード例は、`start-audit-mitigation-actions-task` を使用する方法を示しています。

**AWS CLI**  
**監査検出結果に緩和アクションを適用するには**  
次の `start-audit-mitigation-actions-task` の例では、`ResetPolicyVersionAction` アクション (ポリシーをクリアする) を指定された単一の検出結果に適用します。  

```
aws iot start-audit-mitigation-actions-task \
    --task-id "myActionsTaskId" \
    --target "findingIds=[\"0edbaaec-2fe1-4cf5-abc9-d4c3e51f7464\"]" \
    --audit-check-to-actions-mapping "IOT_POLICY_OVERLY_PERMISSIVE_CHECK=[\"ResetPolicyVersionAction\"]" \
    --client-request-token "adhadhahda"
```
出力:  

```
{
    "taskId": "myActionsTaskId"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[StartAuditMitigationActionsTask (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-StartAuditMitigationActionsTask)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartAuditMitigationActionsTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/start-audit-mitigation-actions-task.html)」を参照してください。

### `start-on-demand-audit-task`
<a name="iot_StartOnDemandAuditTask_cli_2_topic"></a>

次のコード例は、`start-on-demand-audit-task` を使用する方法を示しています。

**AWS CLI**  
**監査をすぐに開始するには**  
次の の`start-on-demand-audit-task`例では、 AWS IoT Device Defender 監査を開始し、3 つの証明書チェックを実行します。  

```
aws iot start-on-demand-audit-task \
    --target-check-names CA_CERTIFICATE_EXPIRING_CHECK DEVICE_CERTIFICATE_EXPIRING_CHECK REVOKED_CA_CERTIFICATE_STILL_ACTIVE_CHECK
```
出力:  

```
{
    "taskId": "a3aea009955e501a31b764abe1bebd3d"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartOnDemandAuditTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/start-on-demand-audit-task.html)」を参照してください。

### `tag-resource`
<a name="iot_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグキーと値を指定するには**  
次の `tag-resource` の例では、`Assembly` キーと `Fact1NW` 値を持つタグをモノのグループ `LightBulbs` に適用します。  

```
aws iot tag-resource \
    --tags Key=Assembly,Value="Fact1NW" \
    --resource-arn "arn:aws:iot:us-west-2:094249569039:thinggroup/LightBulbs"
```
このコマンドでは何も出力されません。  
詳細については、[AWS IoT 「 IoT デベロッパーガイド」の「IoT リソースのタグ付け](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/tag-resource.html)」を参照してください。

### `test-authorization`
<a name="iot_TestAuthorization_cli_2_topic"></a>

次の例は、`test-authorization` を使用する方法を説明しています。

**AWS CLI**  
** AWS IoT ポリシーをテストするには**  
次の の`test-authorization`例では、指定されたプリンシパルに関連付けられた AWS IoT ポリシーをテストします。  

```
aws iot test-authorization \
    --auth-infos actionType=CONNECT,resources=arn:aws:iot:us-east-1:123456789012:client/client1 \
    --principal arn:aws:iot:us-west-2:123456789012:cert/aab1068f7f43ac3e3cae4b3a8aa3f308d2a750e6350507962e32c1eb465d9775
```
出力:  

```
{
    "authResults": [
        {
            "authInfo": {
                "actionType": "CONNECT",
                "resources": [
                    "arn:aws:iot:us-east-1:123456789012:client/client1"
                ]
            },
            "allowed": {
                "policies": [
                    {
                        "policyName": "TestPolicyAllowed",
                        "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/TestPolicyAllowed"
                    }
                ]
            },
            "denied": {
                "implicitDeny": {
                    "policies": [
                        {
                            "policyName": "TestPolicyDenied",
                            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/TestPolicyDenied"
                        }
                    ]
                },
                "explicitDeny": {
                    "policies": [
                        {
                            "policyName": "TestPolicyExplicitDenied",
                            "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/TestPolicyExplicitDenied"
                        }
                    ]
                }
            },
            "authDecision": "IMPLICIT_DENY",
            "missingContextValues": []
        }
    ]
}
```
詳細については、「*AWS IoT API リファレンス*」の「[TestAuthorization](https://docs.aws.amazon.com/iot/latest/apireference/API_TestAuthorization.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestAuthorization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/test-authorization.html)」を参照してください。

### `test-invoke-authorizer`
<a name="iot_TestInvokeAuthorizer_cli_2_topic"></a>

次のコード例は、`test-invoke-authorizer` を使用する方法を示しています。

**AWS CLI**  
**カスタムオーソライザーをテストするには**  
次の `test-invoke-authorizer` の例では、カスタムオーソライザーをテストします。  

```
aws iot test-invoke-authorizer \
    --authorizer-name IoTAuthorizer \
    --token allow \
    --token-signature "mE0GvaHqy9nER/FdgtJX5lXYEJ3b3vE7t1gEszc0TKGgLKWXTnPkb2AbKnOAZ8lGyoN5dVtWDWVmr25m7++zjbYIMk2TBvyGXhOmvKFBPkdgyA43KL6SiZy0cTqlPMcQDsP7VX2rXr7CTowCxSNKphGXdQe0/I5dQ+JO6KUaHwCmupt0/MejKtaNwiia064j6wprOAUwG5S1IYFuRd0X+wfo8pb0DubAIX1Ua705kuhRUcTx4SxUShEYKmN4IDEvLB6FsIr0B2wvB7y4iPmcajxzGl02ExvyCUNctCV9dYlRRGJj0nsGzBIXOI4sGytPfqlA7obdgmN22pkDzYvwjQ=="
```
出力:  

```
{
    "isAuthenticated": true,
    "principalId": "principalId",
    "policyDocuments": [
        "{"Version":"2012-10-17",		 	 	 "Statement":[{"Action":"iot:Publish","Effect":"Allow","Resource":"arn:aws:iot:us-west-2:123456789012:topic/customauthtesting"}]}"
    ],
    "refreshAfterInSeconds": 600,
    "disconnectAfterInSeconds": 3600
}
```
詳細については、「*AWS IoT API リファレンス*」の「[TestInvokeAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_TestInvokeAuthorizers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestInvokeAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/test-invoke-authorizer.html)」を参照してください。

### `transfer-certificate`
<a name="iot_TransferCertificate_cli_2_topic"></a>

次の例は、`transfer-certificate` を使用する方法を説明しています。

**AWS CLI**  
**デバイス証明書を別の AWS アカウントに転送するには**  
次の の`transfer-certificate`例では、デバイス証明書を別の AWS アカウントに転送します。証明書と AWS アカウントは ID で識別されます。  

```
aws iot transfer-certificate \
    --certificate-id 488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142 \
    --target-aws-account 030714055129
```
出力:  

```
{
    "transferredCertificateArn": "arn:aws:iot:us-west-2:030714055129:cert/488b6a7f2acdeb00a77384e63c4e40b18b1b3caaae57b7272ba44c45e3448142"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[証明書を別のアカウントに転送する](https://docs.aws.amazon.com/iot/latest/developerguide/transfer-cert.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TransferCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/transfer-certificate.html)」を参照してください。

### `untag-resource`
<a name="iot_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグキーを削除するには**  
次の `untag-resource` の例では、モノのグループ `LightBulbs` からタグ `MyTag` とその値を削除します。  

```
command
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT リソースのタグ付け](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/untag-resource.html)」を参照してください。

### `update-account-audit-configuration`
<a name="iot_UpdateAccountAuditConfiguration_cli_2_topic"></a>

次のコード例は、`update-account-audit-configuration` を使用する方法を示しています。

**AWS CLI**  
**例 1: 監査通知の Amazon SNS 通知を有効にするには**  
次の`update-account-audit-configuration`例では、 AWS IoT Device Defender 監査通知の Amazon SNS 通知を有効にし、ターゲットとそのターゲットへの書き込みに使用されるロールを指定します。  

```
aws iot update-account-audit-configuration \
    --audit-notification-target-configurations "SNS={targetArn=\"arn:aws:sns:us-west-2:123456789012:ddaudits\",roleArn=\"arn:aws:iam::123456789012:role/service-role/AWSIoTDeviceDefenderAudit\",enabled=true}"
```
このコマンドでは何も出力されません。  
**例 2: 監査チェックを有効にするには**  
次の`update-account-audit-configuration`例では、 という名前の AWS IoT Device Defender 監査チェックを有効にします`AUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK`。 AWS アカウントの 1 つ以上のスケジュールされた監査`targetCheckNames`の の一部である場合、監査チェックを無効にすることはできません。  

```
aws iot update-account-audit-configuration \
    --audit-check-configurations "{\"AUTHENTICATED_COGNITO_ROLE_OVERLY_PERMISSIVE_CHECK\":{\"enabled\":true}}"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccountAuditConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-account-audit-configuration.html)」を参照してください。

### `update-audit-suppression`
<a name="iot_UpdateAuditSuppression_cli_2_topic"></a>

次のコード例は、`update-audit-suppression` を使用する方法を示しています。

**AWS CLI**  
**監査検出結果の抑制を更新するには**  
次の `update-audit-suppression` の例では、監査検出結果の抑制の有効期限を 2020-09-21 に更新します。  

```
aws iot update-audit-suppression \
    --check-name DEVICE_CERTIFICATE_EXPIRING_CHECK \
    --resource-identifier deviceCertificateId=c7691e<shortened> \
    --no-suppress-indefinitely \
    --expiration-date 2020-09-21
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[監査の検出結果の抑制](https://docs.aws.amazon.com/iot/latest/developerguide/audit-finding-suppressions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAuditSuppression](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-audit-suppression.html)」を参照してください。

### `update-authorizer`
<a name="iot_UpdateAuthorizer_cli_2_topic"></a>

次のコード例は、`update-authorizer` を使用する方法を示しています。

**AWS CLI**  
**カスタムオーソライザーを更新するには**  
次の `update-authorizer` の例では、状態を `CustomAuthorizer2` から `INACTIVE` にします。  

```
aws iot update-authorizer \
    --authorizer-name CustomAuthorizer2 \
    --status INACTIVE
```
出力:  

```
{
    "authorizerName": "CustomAuthorizer2",
    "authorizerArn": "arn:aws:iot:us-west-2:123456789012:authorizer/CustomAuthorizer2"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[UpdateAuthorizer](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateAuthorizer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAuthorizer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-authorizer.html)」を参照してください。

### `update-billing-group`
<a name="iot_UpdateBillingGroup_cli_2_topic"></a>

次のコード例は、`update-billing-group` を使用する方法を示しています。

**AWS CLI**  
**請求グループに関する情報を更新するには**  
次の `update-billing-group` の例では、指定された請求グループの説明を更新します。  

```
aws iot update-billing-group \
    --billing-group-name GroupOne \
    --billing-group-properties "billingGroupDescription=\"Primary bulb billing group\""
```
出力:  

```
{
    "version": 2
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[請求グループ](https://docs.aws.amazon.com/iot/latest/developerguide/tagging-iot-billing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateBillingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-billing-group.html)」を参照してください。

### `update-ca-certificate`
<a name="iot_UpdateCaCertificate_cli_2_topic"></a>

次のコード例は、`update-ca-certificate` を使用する方法を示しています。

**AWS CLI**  
**認証局 (CA) 証明書を更新するには**  
次の `update-ca-certificate` の例では、指定された CA 証明書を ACTIVE ステータスに設定します。  

```
aws iot update-ca-certificate \
    --certificate-id f4efed62c0142f16af278166f61962501165c4f0536295207426460058cd1467 \
    --new-status ACTIVE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[UpdateCACertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCACertificate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCaCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-ca-certificate.html)」を参照してください。

### `update-certificate`
<a name="iot_UpdateCertificate_cli_2_topic"></a>

次のコード例は、`update-certificate` を使用する方法を示しています。

**AWS CLI**  
**デバイス証明書を更新するには**  
次の `update-certificate` の例では、指定されたデバイス証明書を INACTIVE ステータスに設定します。  

```
aws iot update-certificate \
    --certificate-id d1eb269fb55a628552143c8f96eb3c258fcd5331ea113e766ba0c82bf225f0be \
    --new-status INACTIVE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[UpdateCertificate](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateCertificate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-certificate.html)」を参照してください。

### `update-custom-metric`
<a name="iot_UpdateCustomMetric_cli_2_topic"></a>

次のコード例は、`update-custom-metric` を使用する方法を示しています。

**AWS CLI**  
**カスタムメトリクスを更新するには**  
次の `update-custom-metric` の例では、カスタムメトリクスを更新して新しい `display-name` を取得します。  

```
aws iot update-custom-metric \
    --metric-name batteryPercentage \
    --display-name 'remaining battery percentage on device' \
    --region us-east-1
```
出力:  

```
{
    "metricName": "batteryPercentage",
    "metricArn": "arn:aws:iot:us-east-1:1234564789012:custommetric/batteryPercentage",
    "metricType": "number",
    "displayName": "remaining battery percentage on device",
    "creationDate": "2020-11-17T23:01:35.110000-08:00",
    "lastModifiedDate": "2020-11-17T23:02:12.879000-08:00"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[カスタムメトリクス](https://docs.aws.amazon.com/iot/latest/developerguide/dd-detect-custom-metrics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCustomMetric](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-custom-metric.html)」を参照してください。

### `update-dimension`
<a name="iot_UpdateDimension_cli_2_topic"></a>

次のコード例は、`update-dimension` を使用する方法を示しています。

**AWS CLI**  
**ディメンションを更新するには**  
次の `update-dimension` の例では、ディメンションを更新します。  

```
aws iot update-dimension \
    --name TopicFilterForAuthMessages \
    --string-values device/${iot:ClientId}/auth
```
出力:  

```
{
    "name": "TopicFilterForAuthMessages",
    "lastModifiedDate": 1585866222.317,
    "stringValues": [
        "device/${iot:ClientId}/auth"
    ],
    "creationDate": 1585854500.474,
    "type": "TOPIC_FILTER",
    "arn": "arn:aws:iot:us-west-2:1234564789012:dimension/TopicFilterForAuthMessages"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[ディメンションを使用したセキュリティプロファイルでのメトリクスの範囲設定](https://docs.aws.amazon.com/iot/latest/developerguide/scoping-security-behavior.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDimension](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-dimension.html)」を参照してください。

### `update-domain-configuration`
<a name="iot_UpdateDomainConfiguration_cli_2_topic"></a>

次のコード例は、`update-domain-configuration` を使用する方法を示しています。

**AWS CLI**  
**ドメイン設定を更新するには**  
次の `update-domain-configuration` の例では、指定されたドメイン設定を無効にします。  

```
aws iot update-domain-configuration \
    --domain-configuration-name "additionalDataDomain" \
    --domain-configuration-status "DISABLED"
```
出力:  

```
{
    "domainConfigurationName": "additionalDataDomain",
    "domainConfigurationArn": "arn:aws:iot:us-west-2:123456789012:domainconfiguration/additionalDataDomain/dikMh"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[設定可能なエンドポイント](https://docs.aws.amazon.com/iot/latest/developerguide/iot-custom-endpoints-configurable-aws.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDomainConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-domain-configuration.html)」を参照してください。

### `update-dynamic-thing-group`
<a name="iot_UpdateDynamicThingGroup_cli_2_topic"></a>

次のコード例は、`update-dynamic-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノの動的グループを更新するには**  
次の `update-dynamic-thing-group` の例では、指定されたモノの動的グループを更新します。説明を提供し、クエリ文字列を更新してグループのメンバーシップ条件を変更します。  

```
aws iot update-dynamic-thing-group \
    --thing-group-name "RoomTooWarm"
    --thing-group-properties "thingGroupDescription=\"This thing group contains rooms warmer than 65F.\"" \
    --query-string "attributes.temperature>65"
```
出力:  

```
{
    "version": 2
}
```
詳細については、「*AWS IoT デベロッパーガイド*」「[モノの動的グループ](https://docs.aws.amazon.com/iot/latest/developerguide/dynamic-thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDynamicThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-dynamic-thing-group.html)」を参照してください。

### `update-event-configurations`
<a name="iot_UpdateEventConfigurations_cli_2_topic"></a>

次のコード例は、`update-event-configurations` を使用する方法を示しています。

**AWS CLI**  
**公開されるイベントタイプを表示するには**  
次の `update-event-configurations` の例では、CA 証明書が追加、更新、または削除されたときにメッセージを有効にするように設定を更新します。  

```
aws iot update-event-configurations \
    --event-configurations "{\"CA_CERTIFICATE\":{\"Enabled\":true}}"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[イベントメッセージ](https://docs.aws.amazon.com/iot/latest/developerguide/iot-events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEventConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-event-configurations.html)」を参照してください。

### `update-indexing-configuration`
<a name="iot_UpdateIndexingConfiguration_cli_2_topic"></a>

次のコード例は、`update-indexing-configuration` を使用する方法を示しています。

**AWS CLI**  
**モノのインデックス作成を有効にするには**  
次の`update-indexing-configuration`例では、モノのインデックス作成が AWS、\$1Things インデックスを使用したレジストリデータ、シャドウデータ、モノの接続ステータスの検索をサポートできるようにします。  

```
aws iot update-indexing-configuration
    --thing-indexing-configuration thingIndexingMode=REGISTRY_AND_SHADOW,thingConnectivityIndexingMode=STATUS
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのインデックス作成の管理](https://docs.aws.amazon.com/iot/latest/developerguide/managing-index.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIndexingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-indexing-configuration.html)」を参照してください。

### `update-job`
<a name="iot_UpdateJob_cli_2_topic"></a>

次のコード例は、`update-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブの詳細なステータスを取得するには**  
次の `update-job` の例では、ID が `example-job-01` のジョブの詳細なステータスを取得します。  

```
aws iot describe-job \
    --job-id "example-job-01"
```
出力:  

```
{
    "job": {
        "jobArn": "arn:aws:iot:us-west-2:123456789012:job/example-job-01",
        "jobId": "example-job-01",
        "targetSelection": "SNAPSHOT",
        "status": "IN_PROGRESS",
        "targets": [
            "arn:aws:iot:us-west-2:123456789012:thing/MyRaspberryPi"
        ],
        "description": "example job test",
        "presignedUrlConfig": {},
        "jobExecutionsRolloutConfig": {},
        "createdAt": 1560787022.733,
        "lastUpdatedAt": 1560787026.294,
        "jobProcessDetails": {
            "numberOfCanceledThings": 0,
            "numberOfSucceededThings": 0,
            "numberOfFailedThings": 0,
            "numberOfRejectedThings": 0,
            "numberOfQueuedThings": 1,
            "numberOfInProgressThings": 0,
            "numberOfRemovedThings": 0,
            "numberOfTimedOutThings": 0
        },
        "timeoutConfig": {}
    }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[ジョブ (CLI) の作成と管理](https://docs.aws.amazon.com/iot/latest/developerguide/manage-job-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-job.html)」を参照してください。

### `update-mitigation-action`
<a name="iot_UpdateMitigationAction_cli_2_topic"></a>

次のコード例は、`update-mitigation-action` を使用する方法を示しています。

**AWS CLI**  
**緩和アクションを更新するには**  
次の `update-mitigation-action` の例では、`AddThingsToQuarantineGroupAction` という名前の指定された緩和アクションを更新し、モノのグループ名を変更して、`overrideDynamicGroups` を `false` に設定します。変更は `describe-mitigation-action` コマンドを使用して確認できます。  

```
aws iot update-mitigation-action \
    --cli-input-json "{ \"actionName\": \"AddThingsToQuarantineGroupAction\", \"actionParams\": { \"addThingsToThingGroupParams\": {\"thingGroupNames\":[\"QuarantineGroup2\"],\"overrideDynamicGroups\": false}}}"
```
出力:  

```
{
    "actionArn": "arn:aws:iot:us-west-2:123456789012:mitigationaction/AddThingsToQuarantineGroupAction",
    "actionId": "2fd2726d-98e1-4abf-b10f-09465ccd6bfa"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[UpdateMitigationAction (緩和アクションコマンド)](https://docs.aws.amazon.com/iot/latest/developerguide/mitigation-action-commands.html#dd-api-iot-UpdateMitigationAction)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMitigationAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-mitigation-action.html)」を参照してください。

### `update-provisioning-template`
<a name="iot_UpdateProvisioningTemplate_cli_2_topic"></a>

次のコード例は、`update-provisioning-template` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングテンプレートを更新するには**  
次の `update-provisioning-template` の例では、指定されたプロビジョニングテンプレートの説明とロール ARN を変更し、テンプレートを有効にします。  

```
aws iot update-provisioning-template \
    --template-name widget-template \
    --enabled \
    --description "An updated provisioning template for widgets" \
    --provisioning-role-arn arn:aws:iam::504350838278:role/Provision_role
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[AWS セキュアトンネリング](https://docs.aws.amazon.com/iot/latest/developerguide/secure-tunneling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateProvisioningTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-provisioning-template.html)」を参照してください。

### `update-role-alias`
<a name="iot_UpdateRoleAlias_cli_2_topic"></a>

次のコード例は、`update-role-alias` を使用する方法を示しています。

**AWS CLI**  
**ロールエイリアスを更新するには**  
次の `update-role-alias` 例では、`LightBulbRole` ロールを更新します。  

```
aws iot update-role-alias \
    --role-alias LightBulbRole \
    --role-arn arn:aws:iam::123456789012:role/lightbulbrole-001
```
出力:  

```
{
    "roleAlias": "LightBulbRole",
    "roleAliasArn": "arn:aws:iot:us-west-2:123456789012:rolealias/LightBulbRole"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[UpdateRoleAlias](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateRoleAlias.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoleAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-role-alias.html)」を参照してください。

### `update-scheduled-audit`
<a name="iot_UpdateScheduledAudit_cli_2_topic"></a>

次のコード例は、`update-scheduled-audit` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされた監査定義を更新するには**  
次の の`update-scheduled-audit`例では、 AWS IoT Device Defender のスケジュールされた監査のターゲットチェック名を変更します。  

```
aws iot update-scheduled-audit \
    --scheduled-audit-name WednesdayCertCheck \
    --target-check-names CA_CERTIFICATE_EXPIRING_CHECK DEVICE_CERTIFICATE_EXPIRING_CHECK REVOKED_CA_CERTIFICATE_STILL_ACTIVE_CHECK
```
出力:  

```
{
    "scheduledAuditArn": "arn:aws:iot:us-west-2:123456789012:scheduledaudit/WednesdayCertCheck"
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Audit コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/AuditCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateScheduledAudit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-scheduled-audit.html)」を参照してください。

### `update-security-profile`
<a name="iot_UpdateSecurityProfile_cli_2_topic"></a>

次のコード例は、`update-security-profile` を使用する方法を示しています。

**AWS CLI**  
**セキュリティプロファイルを更新するには**  
次の の`update-security-profile`例では、 AWS IoT Device Defender セキュリティプロファイルの説明と動作の両方を更新します。  

```
aws iot update-security-profile \
    --security-profile-name PossibleIssue \
    --security-profile-description "Check to see if authorization fails 12 times in 5 minutes or if cellular bandwidth exceeds 128"  \
    --behaviors "[{\"name\":\"CellularBandwidth\",\"metric\":\"aws:message-byte-size\",\"criteria\":{\"comparisonOperator\":\"greater-than\",\"value\":{\"count\":128},\"consecutiveDatapointsToAlarm\":1,\"consecutiveDatapointsToClear\":1}},{\"name\":\"Authorization\",\"metric\":\"aws:num-authorization-failures\",\"criteria\":{\"comparisonOperator\":\"less-than\",\"value\":{\"count\":12},\"durationSeconds\":300,\"consecutiveDatapointsToAlarm\":1,\"consecutiveDatapointsToClear\":1}}]"
```
出力:  

```
{
    "securityProfileName": "PossibleIssue",
    "securityProfileArn": "arn:aws:iot:us-west-2:123456789012:securityprofile/PossibleIssue",
    "securityProfileDescription": "check to see if authorization fails 12 times in 5 minutes or if cellular bandwidth exceeds 128",
    "behaviors": [
        {
            "name": "CellularBandwidth",
            "metric": "aws:message-byte-size",
            "criteria": {
                "comparisonOperator": "greater-than",
                "value": {
                    "count": 128
                },
                "consecutiveDatapointsToAlarm": 1,
                "consecutiveDatapointsToClear": 1
            }
        },
        {
            "name": "Authorization",
            "metric": "aws:num-authorization-failures",
            "criteria": {
                "comparisonOperator": "less-than",
                "value": {
                    "count": 12
                },
                "durationSeconds": 300,
                "consecutiveDatapointsToAlarm": 1,
                "consecutiveDatapointsToClear": 1
            }
        }
    ],
    "version": 2,
    "creationDate": 1560278102.528,
    "lastModifiedDate": 1560352711.207
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSecurityProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-security-profile.html)」を参照してください。

### `update-stream`
<a name="iot_UpdateStream_cli_2_topic"></a>

次のコード例は、`update-stream` を使用する方法を示しています。

**AWS CLI**  
**ストリームを更新するには**  
次の `update-stream` の例では、既存のストリームを更新します。ストリームのバージョンが 1 ずつ増えていきます。  

```
aws iot update-stream \
    --cli-input-json file://update-stream.json
```
`update-stream.json` の内容:  

```
{
    "streamId": "stream12345",
    "description": "This stream is used for Amazon FreeRTOS OTA Update 12345.",
    "files": [
        {
            "fileId": 123,
            "s3Location": {
                "bucket":"codesign-ota-bucket",
                "key":"48c67f3c-63bb-4f92-a98a-4ee0fbc2bef6"
            }
        }
    ]
    "roleArn": "arn:aws:iam:us-west-2:123456789012:role/service-role/my_ota_stream_role"
}
```
出力:  

```
{
    "streamId": "stream12345",
    "streamArn": "arn:aws:iot:us-west-2:123456789012:stream/stream12345",
    "description": "This stream is used for Amazon FreeRTOS OTA Update 12345.",
    "streamVersion": 2
}
```
詳細については、「*AWS IoT API リファレンス*」の「[UpdateStream](https://docs.aws.amazon.com/iot/latest/apireference/API_UpdateStream.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-stream.html)」を参照してください。

### `update-thing-group`
<a name="iot_UpdateThingGroup_cli_2_topic"></a>

次のコード例は、`update-thing-group` を使用する方法を示しています。

**AWS CLI**  
**モノのグループの定義を更新するには**  
次の `update-thing-group` の例では、指定されたモノのグループの定義を更新し、説明と 2 つの属性を変更します。  

```
aws iot update-thing-group \
    --thing-group-name HalogenBulbs \
    --thing-group-properties "thingGroupDescription=\"Halogen bulb group\", attributePayload={attributes={Manufacturer=AnyCompany,wattage=60}}"
```
出力:  

```
{
    "version": 2
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateThingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-thing-group.html)」を参照してください。

### `update-thing-groups-for-thing`
<a name="iot_UpdateThingGroupsForThing_cli_2_topic"></a>

次のコード例は、`update-thing-groups-for-thing` を使用する方法を示しています。

**AWS CLI**  
**モノが属するグループを変更するには**  
次の `update-thing-groups-for-thing` の例では、`MyLightBulb` という名前のモノを `DeadBulbs` という名前のグループから削除し、同時に `replaceableItems` という名前のグループに追加します。  

```
aws iot update-thing-groups-for-thing \
    --thing-name MyLightBulb \
    --thing-groups-to-add "replaceableItems" \
    --thing-groups-to-remove "DeadBulbs"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[モノのグループ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateThingGroupsForThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-thing-groups-for-thing.html)」を参照してください。

### `update-thing`
<a name="iot_UpdateThing_cli_2_topic"></a>

次のコード例は、`update-thing` を使用する方法を示しています。

**AWS CLI**  
**モノのタイプにモノを関連付けるには**  
次の`update-thing`例では、 AWS IoT レジストリ内のモノをモノのタイプに関連付けます。関連付けを行うときは、モノのタイプで定義された属性の値を指定します。  

```
aws iot update-thing \
    --thing-name "MyOtherLightBulb" \
    --thing-type-name "LightBulb" \
    --attribute-payload "{"attributes": {"wattage":"75", "model":"123"}}"
```
このコマンドでは、出力が生成されません。`describe-thing` コマンドを使用して結果を表示します。  
詳細については、「*AWS IoT デベロッパーガイド*」「[モノのタイプ](https://docs.aws.amazon.com/iot/latest/developerguide/thing-types.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-thing.html)」を参照してください。

### `update-topic-rule-destination`
<a name="iot_UpdateTopicRuleDestination_cli_2_topic"></a>

次のコード例は、`update-topic-rule-destination` を使用する方法を示しています。

**AWS CLI**  
**例 1: トピックルールの送信先を有効にするには**  
次の `update-topic-rule-destination` の例では、トピックルールの送信先へのトラフィックを有効にします。  

```
aws iot update-topic-rule-destination \
    --arn "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE" \
    --status ENABLED
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[トピックルールの送信先の有効化](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html#enable-destination)」を参照してください。  
**例 2: トピックルールの送信先を無効にするには**  
次の `update-topic-rule-destination` の例では、トピックルールの送信先へのトラフィックを無効にします。  

```
aws iot update-topic-rule-destination \
    --arn "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE" \
    --status DISABLED
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[トピックルールの送信先の無効化](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html#disable-destination)」を参照してください。  
**例 3: 新しい確認メッセージを送信するには**  
次の `update-topic-rule-destination` の例では、トピックルールの送信先に関する新しい確認メッセージを送信します。  

```
aws iot update-topic-rule-destination \
    --arn "arn:aws:iot:us-west-2:123456789012:ruledestination/http/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE" \
    --status IN_PROGRESS
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[新しい確認メッセージの送信](https://docs.aws.amazon.com/iot/latest/developerguide/rule-destination.html#trigger-confirm)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTopicRuleDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/update-topic-rule-destination.html)」を参照してください。

### `validate-security-profile-behaviors`
<a name="iot_ValidateSecurityProfileBehaviors_cli_2_topic"></a>

次のコード例は、`validate-security-profile-behaviors` を使用する方法を示しています。

**AWS CLI**  
**例 1: セキュリティプロファイルの動作パラメータを検証するには**  
次の の`validate-security-profile-behaviors`例では、 AWS IoT Device Defender セキュリティプロファイルの正しい形式の動作のセットを検証します。  

```
aws iot validate-security-profile-behaviors \
    --behaviors "[{\"name\":\"CellularBandwidth\",\"metric\":\"aws:message-byte-size\",\"criteria\":{\"comparisonOperator\":\"greater-than\",\"value\":{\"count\":128},\"consecutiveDatapointsToAlarm\":1,\"consecutiveDatapointsToClear\":1}},{\"name\":\"Authorization\",\"metric\":\"aws:num-authorization-failures\",\"criteria\":{\"comparisonOperator\":\"greater-than\",\"value\":{\"count\":12},\"durationSeconds\":300,\"consecutiveDatapointsToAlarm\":1,\"consecutiveDatapointsToClear\":1}}]"
```
出力:  

```
{
    "valid": true,
    "validationErrors": []
}
```
**例 2: セキュリティプロファイルの不正な動作パラメータを検証するには**  
次の`validate-security-profile-behaviors`例では、 AWS IoT Device Defender セキュリティプロファイルのエラーを含む一連の動作を検証します。  

```
aws iot validate-security-profile-behaviors \
    --behaviors "[{\"name\":\"CellularBandwidth\",\"metric\":\"aws:message-byte-size\",\"criteria\":{\"comparisonOperator\":\"greater-than\",\"value\":{\"count\":128},\"consecutiveDatapointsToAlarm\":1,\"consecutiveDatapointsToClear\":1}},{\"name\":\"Authorization\",\"metric\":\"aws:num-authorization-failures\",\"criteria\":{\"comparisonOperator\":\"greater-than\",\"value\":{\"count\":12},\"durationSeconds\":300,\"consecutiveDatapointsToAlarm\":100000,\"consecutiveDatapointsToClear\":1}}]"
```
出力:  

```
{
    "valid": false,
    "validationErrors": [
        {
            "errorMessage": "Behavior Authorization is malformed. consecutiveDatapointsToAlarm 100000 should be in range[1,10]"
        }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[Detect コマンド](https://docs.aws.amazon.com/iot/latest/developerguide/DetectCommands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ValidateSecurityProfileBehaviors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot/validate-security-profile-behaviors.html)」を参照してください。

# を使用した Device Advisor の例 AWS CLI
<a name="cli_2_iotdeviceadvisor_code_examples"></a>

次のコード例は、Device Advisor AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-suite-definition`
<a name="iotdeviceadvisor_CreateSuiteDefinition_cli_2_topic"></a>

次のコード例は、`create-suite-definition` を使用する方法を示しています。

**AWS CLI**  
**例 1: IoT Device Advisor テストスイートを作成するには**  
次の の`create-suite-definition`例では、指定されたスイート定義設定を使用して、 AWS IoT にデバイスアドバイザーテストスイートを作成します。  

```
aws iotdeviceadvisor create-suite-definition \
    --suite-definition-configuration '{ \
        "suiteDefinitionName": "TestSuiteName", \
        "devices": [{"thingArn":"arn:aws:iot:us-east-1:123456789012:thing/MyIotThing"}], \
        "intendedForQualification": false, \
        "rootGroup": "{\"configuration\":{},\"tests\":[{\"name\":\"MQTT Connect\",\"configuration\":{\"EXECUTION_TIMEOUT\":120},\"tests\":[{\"name\":\"MQTT_Connect\",\"configuration\":{},\"test\":{\"id\":\"MQTT_Connect\",\"testCase\":null,\"version\":\"0.0.0\"}}]}]}", \
        "devicePermissionRoleArn": "arn:aws:iam::123456789012:role/Myrole"}'
```
出力:  

```
{
    "suiteDefinitionId": "0jtsgio7yenu",
    "suiteDefinitionArn": "arn:aws:iotdeviceadvisor:us-east-1:123456789012:suitedefinition/0jtsgio7yenu",
    "suiteDefinitionName": "TestSuiteName",
    "createdAt": "2022-12-02T11:38:13.263000-05:00"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Create a test suite definition](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-create-suite-definition)」を参照してください。  
**例 2: IoT Device Advisor 最新認定テストスイートを作成するには**  
次の の`create-suite-definition`例では、指定されたスイート定義設定を使用して、 AWS IoT の最新バージョンのデバイスアドバイザー認定テストスイートを作成します。  

```
aws iotdeviceadvisor create-suite-definition \
    --suite-definition-configuration '{ \
        "suiteDefinitionName": "TestSuiteName", \
        "devices": [{"thingArn":"arn:aws:iot:us-east-1:123456789012:thing/MyIotThing"}], \
        "intendedForQualification": true, \
        "rootGroup": "", \
        "devicePermissionRoleArn": "arn:aws:iam::123456789012:role/Myrole"}'
```
出力:  

```
{
    "suiteDefinitionId": "txgsuolk2myj",
    "suiteDefinitionArn": "arn:aws:iotdeviceadvisor:us-east-1:123456789012:suitedefinition/txgsuolk2myj",
    "suiteDefinitionName": "TestSuiteName",
    "createdAt": "2022-12-02T11:38:13.263000-05:00"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Create a test suite definition](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-create-suite-definition)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSuiteDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/create-suite-definition.html)」を参照してください。

### `delete-suite-definition`
<a name="iotdeviceadvisor_DeleteSuiteDefinition_cli_2_topic"></a>

次のコード例は、`delete-suite-definition` を使用する方法を示しています。

**AWS CLI**  
**IoT Device Advisor テストスイートを削除するには**  
次の `delete-suite-definition` の例では、指定されたスイート定義 ID を持つ Device Advisor テストスイートを削除します。  

```
aws iotdeviceadvisor delete-suite-definition \
    --suite-definition-id 0jtsgio7yenu
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT API リファレンス*」の「[DeleteSuiteDefinition](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdeviceadvisor_DeleteSuiteDefinition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSuiteDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/delete-suite-definition.html)」を参照してください。

### `get-endpoint`
<a name="iotdeviceadvisor_GetEndpoint_cli_2_topic"></a>

次のコード例は、`get-endpoint` を使用する方法を示しています。

**AWS CLI**  
**例 1: IoT Device Advisor のアカウントレベルのエンドポイントに関する情報を取得するには**  
次の `get-endpoint` の例では、Device Advisor のアカウントレベルのテストエンドポイントに関する情報を取得します。  

```
aws iotdeviceadvisor get-endpoint
```
出力:  

```
{
    "endpoint": "t6y4c143x9sfo.deviceadvisor.iot.us-east-1.amazonaws.com"
}
```
**例 2: IoT Device Advisor のデバイスレベルのエンドポイントに関する情報を取得するには**  
次の `get-endpoint` の例では、指定された thing-arn または certificate-arn を持つ、Device Advisor のデバイスレベルのテストエンドポイントに関する情報を取得します。  

```
aws iotdeviceadvisor get-endpoint \
    --thing-arn arn:aws:iot:us-east-1:123456789012:thing/MyIotThing
```
出力:  

```
{
    "endpoint": "tdb7719be5t6y4c143x9sfo.deviceadvisor.iot.us-east-1.amazonaws.com"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Get a test endpoint](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-get-test-endpoint)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/get-endpoint.html)」を参照してください。

### `get-suite-definition`
<a name="iotdeviceadvisor_GetSuiteDefinition_cli_2_topic"></a>

次のコード例は、`get-suite-definition` を使用する方法を示しています。

**AWS CLI**  
**IoT Device Advisor テストスイートに関する情報を取得するには**  
次の `get-suite-definition` の例では、指定されたスイート定義 ID を持つ Device Advisor テストスイートに関する情報を取得します。  

```
aws iotdeviceadvisor get-suite-definition \
    --suite-definition-id qqcsmtyyjabl
```
出力:  

```
{
    "suiteDefinitionId": "qqcsmtyyjabl",
    "suiteDefinitionArn": "arn:aws:iotdeviceadvisor:us-east-1:123456789012:suitedefinition/qqcsmtyyjabl",
    "suiteDefinitionVersion": "v1",
    "latestVersion": "v1",
    "suiteDefinitionConfiguration": {
        "suiteDefinitionName": "MQTT connection",
        "devices": [],
        "intendedForQualification": false,
        "isLongDurationTest": false,
        "rootGroup": "{\"configuration\":{},\"tests\":[{\"id\":\"uta5d9j1kvwc\",\"name\":\"Test group 1\",\"configuration\":{},\"tests\":[{\"id\":\"awr8pq5vc9yp\",\"name\":\"MQTT Connect\",\"configuration\":{},\"test\":{\"id\":\"MQTT_Connect\",\"testCase\":null,\"version\":\"0.0.0\"}}]}]}",
        "devicePermissionRoleArn": "arn:aws:iam::123456789012:role/Myrole",
        "protocol": "MqttV3_1_1"
    },
    "createdAt": "2022-11-11T22:28:52.389000-05:00",
    "lastModifiedAt": "2022-11-11T22:28:52.389000-05:00",
    "tags": {}
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Get a test suite definition](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-create-suite-definition)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSuiteDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/get-suite-definition.html)」を参照してください。

### `get-suite-run-report`
<a name="iotdeviceadvisor_GetSuiteRunReport_cli_2_topic"></a>

次のコード例は、`get-suite-run-report` を使用する方法を示しています。

**AWS CLI**  
**IoT Device Advisor 認定テストスイートの実行レポートに関する情報を取得するには**  
次の `get-suite-run-report` の例では、指定されたスイート定義 ID とスイート実行 ID を使用して、Device Advisor 認定テストスイートの正常実行に関するレポートダウンロードリンクを取得します。  

```
aws iotdeviceadvisor get-suite-run-report \
    --suite-definition-id ztvb5aek4w4x \
    --suite-run-id p6awv83nre6v
```
出力:  

```
{
    "qualificationReportDownloadUrl": "https://senate-apn-reports-us-east-1-prod.s3.amazonaws.com/report.downloadlink"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Get a qualification report for a successful qualification test suite run](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-qualification-report)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSuiteRunReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/get-suite-run-report.html)」を参照してください。

### `get-suite-run`
<a name="iotdeviceadvisor_GetSuiteRun_cli_2_topic"></a>

次のコード例は、`get-suite-run` を使用する方法を示しています。

**AWS CLI**  
**IoT Device Advisor テストスイートの実行ステータスに関する情報を取得するには**  
次の `get-suite-run` の例では、指定されたスイート定義 ID とスイート実行 ID を使用して、Device Advisor テストスイートの実行ステータスに関する情報を取得します。  

```
aws iotdeviceadvisor get-suite-run \
    --suite-definition-id qqcsmtyyjabl \
    --suite-run-id nzlfyhaa18oa
```
出力:  

```
{
    "suiteDefinitionId": "qqcsmtyyjabl",
    "suiteDefinitionVersion": "v1",
    "suiteRunId": "nzlfyhaa18oa",
    "suiteRunArn": "arn:aws:iotdeviceadvisor:us-east-1:123456789012:suiterun/qqcsmtyyjabl/nzlfyhaa18oa",
    "suiteRunConfiguration": {
        "primaryDevice": {
            "thingArn": "arn:aws:iot:us-east-1:123456789012:thing/MyIotThing",
            "certificateArn": "arn:aws:iot:us-east-1:123456789012:cert/certFile"
        },
        "parallelRun": false
    },
    "testResult": {
        "groups": [
            {
                "groupId": "uta5d9j1kvwc",
                "groupName": "Test group 1",
                "tests": [
                    {
                        "testCaseRunId": "2ve2twrqyr0s",
                        "testCaseDefinitionId": "awr8pq5vc9yp",
                        "testCaseDefinitionName": "MQTT Connect",
                        "status": "PASS",
                        "startTime": "2022-11-12T00:01:53.693000-05:00",
                        "endTime": "2022-11-12T00:02:15.443000-05:00",
                        "logUrl": "https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#logEventViewer:group=/aws/iot/deviceadvisor/qqcsmtyyjabl;stream=nzlfyhaa18oa_2ve2twrqyr0s",
                        "warnings": "null",
                        "failure": "null"
                    }
                ]
            }
        ]
    },
    "startTime": "2022-11-12T00:01:52.673000-05:00",
    "endTime": "2022-11-12T00:02:16.496000-05:00",
    "status": "PASS",
    "tags": {}
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Get a test suite run](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-describe-suite)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSuiteRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/get-suite-run.html)」を参照してください。

### `list-suite-definitions`
<a name="iotdeviceadvisor_ListSuiteDefinitions_cli_2_topic"></a>

次のコード例は、`list-suite-definitions` を使用する方法を示しています。

**AWS CLI**  
**例 1: 作成した IoT Device Advisor テストスイートを一覧表示するには**  
次の の`list-suite-definitions`例では、 AWS IoT で作成したデバイスアドバイザーテストスイートを最大 25 個一覧表示します。テストスイートの数が 25 を超える場合、出力に "nextToken" が表示されます。この "nextToken" を使用して、作成した残りのテストスイートを表示できます。  

```
aws iotdeviceadvisor list-suite-definitions
```
出力:  

```
{
    "suiteDefinitionInformationList": [
        {
            "suiteDefinitionId": "3hsn88h4p2g5",
            "suiteDefinitionName": "TestSuite1",
            "defaultDevices": [
                {
                    "thingArn": "arn:aws:iot:us-east-1:123456789012:thing/MyIotThing"
                }
            ],
            "intendedForQualification": false,
            "isLongDurationTest": false,
            "protocol": "MqttV3_1_1",
            "createdAt": "2022-11-17T14:15:56.830000-05:00"
        },
        {
            ......
        }
    ],
    "nextToken": "nextTokenValue"
}
```
**例 2: 作成した IoT Device Advisor テストスイートを指定された設定で一覧表示するには**  
次の の`list-suite-definitions`例では、 AWS IoT で作成したデバイスアドバイザーテストスイートを、指定された最大結果数で一覧表示します。テストスイートの数が最大数を超える場合、出力に "nextToken" が表示されます。"nextToken" がある場合は、"nextToken" を使用して、作成したテストスイートのうち、表示されていなかったものを表示できます。  

```
aws iotdeviceadvisor list-suite-definitions \
    --max-result 1 \
    --next-token "nextTokenValue"
```
出力:  

```
{
    "suiteDefinitionInformationList": [
        {
            "suiteDefinitionId": "ztvb5aew4w4x",
            "suiteDefinitionName": "TestSuite2",
            "defaultDevices": [],
            "intendedForQualification": true,
            "isLongDurationTest": false,
            "protocol": "MqttV3_1_1",
            "createdAt": "2022-11-17T14:15:56.830000-05:00"
        }
    ],
    "nextToken": "nextTokenValue"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListSuiteDefinitions](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdeviceadvisor_ListSuiteDefinitions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSuiteDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/list-suite-definitions.html)」を参照してください。

### `list-suite-runs`
<a name="iotdeviceadvisor_ListSuiteRuns_cli_2_topic"></a>

次のコード例は、`list-suite-runs` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定された IoT Device Advisor テストスイートの実行ステータスに関するすべての情報を一覧表示するには**  
次の `list-suite-runs` の例では、指定されたスイート定義 ID を使用して、Device Advisor テストスイートの実行ステータスに関するすべての情報を一覧表示します。テストスイートの実行回数が 25 を超える場合、出力に "nextToken" が表示されます。この "nextToken" を使用して、残りのテストスイートの実行を表示できます。  

```
aws iotdeviceadvisor list-suite-runs \
    --suite-definition-id ztvb5aew4w4x
```
出力:  

```
{
    "suiteRunsList": [
        {
            "suiteDefinitionId": "ztvb5aew4w4x",
            "suiteDefinitionVersion": "v1",
            "suiteDefinitionName": "TestSuite",
            "suiteRunId": "p6awv89nre6v",
            "createdAt": "2022-12-01T16:33:14.212000-05:00",
            "startedAt": "2022-12-01T16:33:15.710000-05:00",
            "endAt": "2022-12-01T16:42:03.323000-05:00",
            "status": "PASS",
            "passed": 6,
            "failed": 0
        }
    ]
}
```
**例 2: 指定された IoT Device Advisor テストスイートの実行ステータスに関する情報を、指定された設定で一覧表示するには**  
次の `list-suite-runs` の例では、指定されたスイート定義 ID と指定された最大結果数を使用して、Device Advisor テストスイートの実行ステータスに関する情報を一覧表示します。テストスイートの実行回数が最大数を超える場合、出力に "nextToken" が表示されます。"nextToken" がある場合は、"nextToken" を使用して、表示されていなかったテストスイートの実行を表示できます。  

```
aws iotdeviceadvisor list-suite-runs \
    --suite-definition-id qqcsmtyyjaml \
    --max-result 1 \
    --next-token "nextTokenValue"
```
出力:  

```
{
    "suiteRunsList": [
        {
            "suiteDefinitionId": "qqcsmtyyjaml",
            "suiteDefinitionVersion": "v1",
            "suiteDefinitionName": "MQTT connection",
            "suiteRunId": "gz9vm2s6d2jy",
            "createdAt": "2022-12-01T20:10:27.079000-05:00",
            "startedAt": "2022-12-01T20:10:28.003000-05:00",
            "endAt": "2022-12-01T20:10:45.084000-05:00",
            "status": "STOPPED",
            "passed": 0,
            "failed": 0
        }
    ],
    "nextToken": "nextTokenValue"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[ListSuiteRuns](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdeviceadvisor_ListSuiteRuns.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSuiteRuns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/list-suite-runs.html)」を参照してください。

### `list-tags-for-resource`
<a name="iotdeviceadvisor_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**IoT Device Advisor リソースにアタッチされたタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、Device Advisor リソースにアタッチされたタグを一覧表示します。Device Advisor リソースは、Suitedefinition-Arn または Suiterun-Arn です。  

```
aws iotdeviceadvisor list-tags-for-resource \
    --resource-arn arn:aws:iotdeviceadvisor:us-east-1:123456789012:suitedefinition/ba0uyjpg38ny
```
出力:  

```
{
    "tags": {
        "TestTagKey": "TestTagValue"
    }
}
```
詳細については、*AWS 「 IoT API リファレンス*」の[ListTagsForResource](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdeviceadvisor_ListTagsForResource.html)」および*「サービス認可リファレンス*」の[AWS IoT Core Device Advisor で定義されるリソースタイプ](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotcoredeviceadvisor.html#awsiotcoredeviceadvisor-resources-for-iam-policies)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/list-tags-for-resource.html)」を参照してください。

### `start-suite-run`
<a name="iotdeviceadvisor_StartSuiteRun_cli_2_topic"></a>

次のコード例は、`start-suite-run` を使用する方法を示しています。

**AWS CLI**  
**Device Advisor テストスイートの実行を開始するには**  
次の の`start-suite-run`例では、 AWS アカウントで使用可能なウィジェットを一覧表示します。  

```
aws iotdeviceadvisor start-suite-run \
    --suite-definition-id qqcsmtyyjabl \
    --suite-definition-version v1 \
    --suite-run-configuration '{"primaryDevice":{"thingArn": "arn:aws:iot:us-east-1:123456789012:thing/MyIotThing","certificateArn":"arn:aws:iot:us-east-1:123456789012:cert/certFile"}}'
```
出力:  

```
{
    "suiteRunId": "pwmucgw7lt9s",
    "suiteRunArn": "arn:aws:iotdeviceadvisor:us-east-1:123456789012:suiterun/qqcsmtyyjabl/pwmucgw7lk9s",
    "createdAt": "2022-12-02T15:43:05.581000-05:00"
}
```
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Start a test suite run](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-start-suite-run)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartSuiteRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/start-suite-run.html)」を参照してください。

### `stop-suite-run`
<a name="iotdeviceadvisor_StopSuiteRun_cli_2_topic"></a>

次のコード例は、`stop-suite-run` を使用する方法を示しています。

**AWS CLI**  
**現在実行中の IoT Device Advisor テストスイートを停止するには**  
次の `stop-suite-run` の例では、指定されたスイート定義 ID とスイート実行 ID を使用して、現在実行中の Device Advisor テストスイートを停止します。  

```
aws iotdeviceadvisor stop-suite-run \
    --suite-definition-id qqcsmtyyjabl \
    --suite-run-id nzlfyhaa18oa
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Core デベロッパーガイド*」の「[Stop a test suite run](https://docs.aws.amazon.com/iot/latest/developerguide/device-advisor-workflow.html#device-advisor-workflow-stop-suite-run)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopSuiteRun](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/stop-suite-run.html)」を参照してください。

### `tag-resource`
<a name="iotdeviceadvisor_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**IoT Device Advisor リソースの既存のタグに対する追加と変更を行うには**  
次の `tag-resource` の例では、指定されたリソース arn とタグを使用して、Device Advisor リソースの既存のタグに対する追加と変更を行います。Device Advisor リソースは、Suitedefinition-Arn または Suiterun-Arn です。  

```
aws iotdeviceadvisor tag-resource \
    --resource-arn arn:aws:iotdeviceadvisor:us-east-1:123456789012:suitedefinition/ba0uyjpg38ny \
    --tags '{"TagKey": "TagValue"}'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 IoT API リファレンス*」の[TagResource](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdeviceadvisor_TagResource.html)」および*「サービス認可リファレンス*」の[AWS IoT Core Device Advisor で定義されるリソースタイプ](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotcoredeviceadvisor.html#awsiotcoredeviceadvisor-resources-for-iam-policies)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="iotdeviceadvisor_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**IoT Device Advisor リソースから既存のタグを削除するには**  
次の `untag-resource` の例では、指定されたリソース arn とタグキーを使用して、Device Advisor リソースから既存のタグを削除します。Device Advisor リソースは、Suitedefinition-Arn または Suiterun-Arn です。  

```
aws iotdeviceadvisor untag-resource \
    --resource-arn arn:aws:iotdeviceadvisor:us-east-1:123456789012:suitedefinition/ba0uyjpg38ny \
    --tag-keys "TagKey"
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 IoT API リファレンス*」の[UntagResource](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdeviceadvisor_UntagResource.html)」および*「サービス認可リファレンス*」の[AWS IoT Core Device Advisor で定義されるリソースタイプ](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsiotcoredeviceadvisor.html#awsiotcoredeviceadvisor-resources-for-iam-policies)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/untag-resource.html)」を参照してください。

### `update-suite-definition`
<a name="iotdeviceadvisor_UpdateSuiteDefinition_cli_2_topic"></a>

次のコード例は、`update-suite-definition` を使用する方法を示しています。

**AWS CLI**  
**例 1: IoT Device Advisor テストスイートを更新するには**  
次の の`update-suite-definition`例では、指定されたスイート定義 ID とスイート定義設定を使用して、 AWS IoT のデバイスアドバイザーテストスイートを更新します。  

```
aws iotdeviceadvisor update-suite-definition \
    --suite-definition-id 3hsn88h4p2g5 \
    --suite-definition-configuration '{ \
        "suiteDefinitionName": "TestSuiteName", \
        "devices": [{"thingArn":"arn:aws:iot:us-east-1:123456789012:thing/MyIotThing"}], \
        "intendedForQualification": false, \
        "rootGroup": "{\"configuration\":{},\"tests\":[{\"name\":\"MQTT Connect\",\"configuration\":{\"EXECUTION_TIMEOUT\":120},\"tests\":[{\"name\":\"MQTT_Connect\",\"configuration\":{},\"test\":{\"id\":\"MQTT_Connect\",\"testCase\":null,\"version\":\"0.0.0\"}}]}]}", \
        "devicePermissionRoleArn": "arn:aws:iam::123456789012:role/Myrole"}'
```
出力:  

```
{
    "suiteDefinitionId": "3hsn88h4p2g5",
    "suiteDefinitionName": "TestSuiteName",
    "suiteDefinitionVersion": "v3",
    "createdAt": "2022-11-17T14:15:56.830000-05:00",
    "lastUpdatedAt": "2022-12-02T16:02:45.857000-05:00"
}
```
**例 2: IoT Device Advisor 認定テストスイートを更新するには**  
次の の`update-suite-definition`例では、指定されたスイート定義 ID とスイート定義設定を使用して、 AWS IoT のデバイスアドバイザー認定テストスイートを更新します。  

```
aws iotdeviceadvisor update-suite-definition \
    --suite-definition-id txgsuolk2myj \
    --suite-definition-configuration '{
        "suiteDefinitionName": "TestSuiteName", \
        "devices": [{"thingArn":"arn:aws:iot:us-east-1:123456789012:thing/MyIotThing"}], \
        "intendedForQualification": true, \
        "rootGroup": "", \
        "devicePermissionRoleArn": "arn:aws:iam::123456789012:role/Myrole"}'
```
出力:  

```
{
    "suiteDefinitionId": "txgsuolk2myj",
    "suiteDefinitionName": "TestSuiteName",
    "suiteDefinitionVersion": "v3",
    "createdAt": "2022-11-17T14:15:56.830000-05:00",
    "lastUpdatedAt": "2022-12-02T16:02:45.857000-05:00"
}
```
詳細については、「*AWS IoT API リファレンス*」の「[UpdateSuiteDefinition](https://docs.aws.amazon.com/iot/latest/apireference/API_iotdeviceadvisor_UpdateSuiteDefinition.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSuiteDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotdeviceadvisor/update-suite-definition.html)」を参照してください。

# AWS IoT data を使用した の例 AWS CLI
<a name="cli_2_iot-data-plane_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT data。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-thing-shadow`
<a name="iot-data-plane_DeleteThingShadow_cli_2_topic"></a>

次のコード例は、`delete-thing-shadow` を使用する方法を示しています。

**AWS CLI**  
**デバイスのシャドウドキュメントを削除するには**  
次の `delete-thing-shadow` の例では、`MyRPi` という名前のデバイスのシャドウドキュメント全体を削除します。  

```
aws iot-data delete-thing-shadow \
    --thing-name MyRPi \
    "output.txt"
```
このコマンドではディスプレイに何も出力されませんが、`output.txt` には削除したシャドウドキュメントのバージョンとタイムスタンプを確認する情報が含まれています。  

```
{"version":2,"timestamp":1560270384}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[シャドウの使用](https://docs.aws.amazon.com/iot/latest/developerguide/using-device-shadows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteThingShadow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot-data/delete-thing-shadow.html)」を参照してください。

### `get-thing-shadow`
<a name="iot-data-plane_GetThingShadow_cli_2_topic"></a>

次のコード例は、`get-thing-shadow` を使用する方法を示しています。

**AWS CLI**  
**モノのシャドウドキュメントを取得するには**  
次の `get-thing-shadow` の例では、指定された IoT のモノに関するモノのシャドウドキュメントを取得します。  

```
aws iot-data get-thing-shadow \
    --thing-name MyRPi \
    output.txt
```
このコマンドではディスプレイに何も出力されませんが、`output.txt` の内容を以下に示します。  

```
{
  "state":{
    "reported":{
    "moisture":"low"
    }
  },
  "metadata":{
    "reported":{
      "moisture":{
        "timestamp":1560269319
      }
    }
  },
  "version":1,"timestamp":1560269405
}
```
詳細については、「AWS IoT デベロッパーガイド」の「[Device Shadow サービスのデータフロー](https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-data-flow.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetThingShadow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot-data/get-thing-shadow.html)」を参照してください。

### `update-thing-shadow`
<a name="iot-data-plane_UpdateThingShadow_cli_2_topic"></a>

次のコード例は、`update-thing-shadow` を使用する方法を示しています。

**AWS CLI**  
**モノのシャドウを更新するには**  
次の `update-thing-shadow` の例では、指定されたモノのデバイスシャドウの現在の状態を変更して、ファイル `output.txt` に保存します。  

```
aws iot-data update-thing-shadow \
    --thing-name MyRPi \
    --payload "{"state":{"reported":{"moisture":"okay"}}}" \
    "output.txt"
```
このコマンドではディスプレイに何も出力されませんが、`output.txt` の内容を以下に示します。  

```
{
    "state": {
        "reported": {
            "moisture": "okay"
        }
    },
    "metadata": {
        "reported": {
            "moisture": {
                "timestamp": 1560270036
            }
        }
    },
    "version": 2,
    "timestamp": 1560270036
}
```
詳細については、「AWS IoT デベロッパーガイド」の「[Device Shadow サービスのデータフロー](https://docs.aws.amazon.com/iot/latest/developerguide/device-shadow-data-flow.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateThingShadow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot-data/update-thing-shadow.html)」を参照してください。

# AWS IoT Events を使用した の例 AWS CLI
<a name="cli_2_iot-events_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT Events。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-put-message`
<a name="iot-events_BatchPutMessage_cli_2_topic"></a>

次の例は、`batch-put-message` を使用する方法を説明しています。

**AWS CLI**  
** AWS IoT イベントにメッセージ (入力) を送信するには**  
次の の`batch-put-message`例では、一連のメッセージを AWS IoT Events システムに送信します。各メッセージペイロードは、指定した入力 (`inputName`) に変換され、その入力をモニタリングするディテクターに取り込まれます。複数のメッセージが送信された場合、メッセージが処理される順序は保証されません。順序を保証するには、メッセージを一度に 1 つずつ送信し、成功のレスポンスを待つ必要があります。  

```
aws iotevents-data batch-put-message \
    --cli-input-json file://highPressureMessage.json
```
`highPressureMessage.json` の内容:  

```
{
    "messages": [
        {
            "messageId": "00001",
            "inputName": "PressureInput",
            "payload": "{\"motorid\": \"Fulton-A32\", \"sensorData\": {\"pressure\": 80, \"temperature\": 39} }"
        }
    ]
}
```
出力:  

```
{
    "BatchPutMessageErrorEntries": []
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[BatchPutMessage](https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_BatchPutMessage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchPutMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/batch-put-message.html)」を参照してください。

### `batch-update-detector`
<a name="iot-events_BatchUpdateDetector_cli_2_topic"></a>

次のコード例は、`batch-update-detector` を使用する方法を示しています。

**AWS CLI**  
**ディテクター (インスタンス) を更新するには**  
次の `batch-update-detector` の例では、指定されたディテクターモデルの 1 つ以上のディテクター (インスタンス) の状態、変数値、タイマー設定を更新します。  

```
aws iotevents-data batch-update-detector \
    --cli-input-json file://budFulton-A32.json
```
`budFulton-A32.json` の内容:  

```
{
    "detectors": [
        {
            "messageId": "00001",
            "detectorModelName": "motorDetectorModel",
            "keyValue": "Fulton-A32",
            "state": {
                "stateName": "Normal",
                "variables": [
                    {
                        "name": "pressureThresholdBreached",
                        "value": "0"
                    }
                ],
                "timers": [
                ]
            }
        }
    ]
}
```
出力:  

```
{
    "batchUpdateDetectorErrorEntries": []
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[BatchUpdateDetector](https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_BatchUpdateDetector.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchUpdateDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/batch-update-detector.html)」を参照してください。

### `create-detector-model`
<a name="iot-events_CreateDetectorModel_cli_2_topic"></a>

次のコード例は、`create-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルを作成するには**  
次の `create-detector-model` の例では、パラメータファイルで指定された設定でディテクターモデルを作成します。  

```
aws iotevents create-detector-model  \
    --cli-input-json file://motorDetectorModel.json
```
`motorDetectorModel.json` の内容:  

```
{
    "detectorModelName": "motorDetectorModel",
    "detectorModelDefinition": {
        "states": [
            {
                "stateName": "Normal",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "init",
                            "condition": "true",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "Overpressurized",
                            "condition": "$input.PressureInput.sensorData.pressure &gt; 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "$variable.pressureThresholdBreached + 3"
                                    }
                                }
                            ],
                            "nextState": "Dangerous"
                        }
                    ]
                }
            },
            {
                "stateName": "Dangerous",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Pressure Threshold Breached",
                            "condition": "$variable.pressureThresholdBreached &gt; 1",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "events": [
                        {
                            "eventName": "Overpressurized",
                            "condition": "$input.PressureInput.sensorData.pressure &gt; 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "3"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Pressure Okay",
                            "condition": "$input.PressureInput.sensorData.pressure &lt;= 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "$variable.pressureThresholdBreached - 1"
                                    }
                                }
                            ]
                        }
                    ],
                    "transitionEvents": [
                        {
                            "eventName": "BackToNormal",
                            "condition": "$input.PressureInput.sensorData.pressure &lt;= 70 &amp;&amp; $variable.pressureThresholdBreached &lt;= 1",
                            "nextState": "Normal"
                        }
                    ]
                },
                "onExit": {
                    "events": [
                        {
                            "eventName": "Normal Pressure Restored",
                            "condition": "true",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
        ],
        "initialStateName": "Normal"
    },
    "key": "motorid",
    "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole"
}
```
出力:  

```
{
    "detectorModelConfiguration": {
        "status": "ACTIVATING",
        "lastUpdateTime": 1560796816.077,
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "creationTime": 1560796816.077,
        "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
        "key": "motorid",
        "detectorModelName": "motorDetectorModel",
        "detectorModelVersion": "1"
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[CreateDetectorModel](https://docs.aws.amazon.com/iotevents/latest/apireference/API_CreateDetectorModel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/create-detector-model.html)」を参照してください。

### `create-input`
<a name="iot-events_CreateInput_cli_2_topic"></a>

次のコード例は、`create-input` を使用する方法を示しています。

**AWS CLI**  
**入力を作成するには**  
次の `create-input` の例では、入力を作成します。  

```
aws iotevents create-input  \
    --cli-input-json file://pressureInput.json
```
`pressureInput.json` の内容:  

```
{
    "inputName": "PressureInput",
    "inputDescription": "Pressure readings from a motor",
    "inputDefinition": {
        "attributes": [
            { "jsonPath": "sensorData.pressure" },
            { "jsonPath": "motorid" }
        ]
    }
}
```
出力:  

```
{
    "inputConfiguration": {
        "status": "ACTIVE",
        "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
        "lastUpdateTime": 1560795312.542,
        "creationTime": 1560795312.542,
        "inputName": "PressureInput",
        "inputDescription": "Pressure readings from a motor"
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[CreateInput](https://docs.aws.amazon.com/iotevents/latest/apireference/API_CreateInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/create-input.html)」を参照してください。

### `delete-detector-model`
<a name="iot-events_DeleteDetectorModel_cli_2_topic"></a>

次のコード例は、`delete-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルを削除するには**  
次の `delete-detector-model` の例では、指定されたディテクターモデルを削除します。ディテクターモデルのアクティブなインスタンスも削除されます。  

```
aws iotevents delete-detector-model \
    --detector-model-name motorDetectorModel
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events API リファレンス*」の「[DeleteDetectorModel](https://docs.aws.amazon.com/iotevents/latest/apireference/API_DeleteDetectorModel)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/delete-detector-model.html)」を参照してください。

### `delete-input`
<a name="iot-events_DeleteInput_cli_2_topic"></a>

次のコード例は、`delete-input` を使用する方法を示しています。

**AWS CLI**  
**入力を削除するには**  
次の `delete-input` の例では、指定された入力を削除します。  

```
aws iotevents delete-input \
    --input-name PressureInput
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events API リファレンス*」の「[DeleteInput](https://docs.aws.amazon.com/iotevents/latest/apireference/API_DeleteInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/delete-input.html)」を参照してください。

### `describe-detector-model`
<a name="iot-events_DescribeDetectorModel_cli_2_topic"></a>

次のコード例は、`describe-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルに関する情報を取得するには**  
次の `describe-detector-model` の例では、指定されたディテクターモデルの詳細を表示します。`version` パラメータが指定されていないため、最新バージョンに関する情報が返されます。  

```
aws iotevents describe-detector-model \
    --detector-model-name motorDetectorModel
```
出力:  

```
{
    "detectorModel": {
        "detectorModelConfiguration": {
            "status": "ACTIVE",
            "lastUpdateTime": 1560796816.077,
            "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
            "creationTime": 1560796816.077,
            "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
            "key": "motorid",
            "detectorModelName": "motorDetectorModel",
            "detectorModelVersion": "1"
        },
        "detectorModelDefinition": {
            "states": [
                {
                    "onInput": {
                        "transitionEvents": [
                            {
                                "eventName": "Overpressurized",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "$variable.pressureThresholdBreached + 3"
                                        }
                                    }
                                ],
                                "condition": "$input.PressureInput.sensorData.pressure > 70",
                                "nextState": "Dangerous"
                            }
                        ],
                        "events": []
                    },
                    "stateName": "Normal",
                    "onEnter": {
                        "events": [
                            {
                                "eventName": "init",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "0"
                                        }
                                    }
                                ],
                                "condition": "true"
                            }
                        ]
                    },
                    "onExit": {
                        "events": []
                    }
                },
                {
                    "onInput": {
                        "transitionEvents": [
                            {
                                "eventName": "BackToNormal",
                                "actions": [],
                                "condition": "$input.PressureInput.sensorData.pressure <= 70 && $variable.pressureThresholdBreached <= 1",
                                "nextState": "Normal"
                            }
                        ],
                        "events": [
                            {
                                "eventName": "Overpressurized",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "3"
                                        }
                                    }
                                ],
                                "condition": "$input.PressureInput.sensorData.pressure > 70"
                            },
                            {
                                "eventName": "Pressure Okay",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "$variable.pressureThresholdBreached - 1"
                                        }
                                    }
                                ],
                                "condition": "$input.PressureInput.sensorData.pressure <= 70"
                            }
                        ]
                    },
                    "stateName": "Dangerous",
                    "onEnter": {
                        "events": [
                            {
                                "eventName": "Pressure Threshold Breached",
                                "actions": [
                                    {
                                        "sns": {
                                            "targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"
                                        }
                                    }
                                ],
                                "condition": "$variable.pressureThresholdBreached > 1"
                            }
                        ]
                    },
                    "onExit": {
                        "events": [
                            {
                                "eventName": "Normal Pressure Restored",
                                "actions": [
                                    {
                                        "sns": {
                                            "targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"
                                        }
                                    }
                                ],
                                "condition": "true"
                            }
                        ]
                    }
                }
            ],
            "initialStateName": "Normal"
        }
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[DescribeDetectorModel](https://docs.aws.amazon.com/iotevents/latest/apireference/API_DescribeDetectorModel)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/describe-detector-model.html)」を参照してください。

### `describe-detector`
<a name="iot-events_DescribeDetector_cli_2_topic"></a>

次のコード例は、`describe-detector` を使用する方法を示しています。

**AWS CLI**  
**ディテクター (インスタンス) に関する情報を取得するには**  
次の `describe-detector` の例では、指定されたディテクター (インスタンス) の詳細を表示します。  

```
aws iotevents-data describe-detector \
    --detector-model-name motorDetectorModel \
    --key-value "Fulton-A32"
```
出力:  

```
{
    "detector": {
        "lastUpdateTime": 1560797852.776,
        "creationTime": 1560797852.775,
        "state": {
            "variables": [
                {
                    "name": "pressureThresholdBreached",
                    "value": "3"
                }
            ],
            "stateName": "Dangerous",
            "timers": []
        },
        "keyValue": "Fulton-A32",
        "detectorModelName": "motorDetectorModel",
        "detectorModelVersion": "1"
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[DescribeDetector](https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_DescribeDetector)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/describe-detector.html)」を参照してください。

### `describe-input`
<a name="iot-events_DescribeInput_cli_2_topic"></a>

次のコード例は、`describe-input` を使用する方法を示しています。

**AWS CLI**  
**入力に関する情報を取得するには**  
次の `describe-input` の例では、指定された入力の詳細を表示します。  

```
aws iotevents describe-input \
    --input-name PressureInput
```
出力:  

```
{
    "input": {
        "inputConfiguration": {
            "status": "ACTIVE",
            "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
            "lastUpdateTime": 1560795312.542,
            "creationTime": 1560795312.542,
            "inputName": "PressureInput",
            "inputDescription": "Pressure readings from a motor"
        },
        "inputDefinition": {
            "attributes": [
                {
                    "jsonPath": "sensorData.pressure"
                },
                {
                    "jsonPath": "motorid"
                }
            ]
        }
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[DescribeInput](https://docs.aws.amazon.com/iotevents/latest/apireference/API_DescribeInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/describe-input.html)」を参照してください。

### `describe-logging-options`
<a name="iot-events_DescribeLoggingOptions_cli_2_topic"></a>

次のコード例は、`describe-logging-options` を使用する方法を示しています。

**AWS CLI**  
**ログ記録設定に関する情報を取得するには**  
次の の`describe-logging-options`例では、 AWS IoT Events ログ記録オプションの現在の設定を取得します。  

```
aws iotevents describe-logging-options
```
出力:  

```
{
    "loggingOptions": {
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "enabled": false,
        "level": "ERROR"
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[DescribeLoggingOptions](https://docs.aws.amazon.com/iotevents/latest/apireference/API_DescribeLoggingOptions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/describe-logging-options.html)」を参照してください。

### `list-detector-model-versions`
<a name="iot-events_ListDetectorModelVersions_cli_2_topic"></a>

次のコード例は、`list-detector-model-versions` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルのバージョンに関する情報を取得するには**  
次の `list-detector-model-versions` の例では、ディテクターモデルのすべてのバージョンを一覧表示します。各探知器モデルのバージョンに関連付けられているメタデータのみが返されます。  

```
aws iotevents list-detector-model-versions \
    --detector-model-name motorDetectorModel
```
出力:  

```
{
    "detectorModelVersionSummaries": [
        {
            "status": "ACTIVE",
            "lastUpdateTime": 1560796816.077,
            "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
            "creationTime": 1560796816.077,
            "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
            "detectorModelName": "motorDetectorModel",
            "detectorModelVersion": "1"
        }
    ]
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[ListDetectorModelVersions](https://docs.aws.amazon.com/iotevents/latest/apireference/API_ListDetectorModelVersions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDetectorModelVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/list-detector-model-versions.html)」を参照してください。

### `list-detector-models`
<a name="iot-events_ListDetectorModels_cli_2_topic"></a>

次のコード例は、`list-detector-models` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルのリストを取得するには**  
次の `list-detector-models` の例では、作成したディテクターモデルを一覧表示します。各探知器モデルに関連付けられているメタデータのみが返されます。  

```
aws iotevents list-detector-models
```
出力:  

```
{
    "detectorModelSummaries": [
        {
            "detectorModelName": "motorDetectorModel",
            "creationTime": 1552072424.212
            "detectorModelDescription": "Detect overpressure in a motor."
        }
    ]
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[ListDetectorModels](https://docs.aws.amazon.com/iotevents/latest/apireference/API_ListDetectorModels)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDetectorModels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/list-detector-models.html)」を参照してください。

### `list-detectors`
<a name="iot-events_ListDetectors_cli_2_topic"></a>

次のコード例は、`list-detectors` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルのディテクターのリストを取得するには**  
次の `list-detectors` の例では、アカウント内のディテクター (ディテクターモデルのインスタンス) を一覧表示します。  

```
aws iotevents-data list-detectors \
    --detector-model-name motorDetectorModel
```
出力:  

```
{
    "detectorSummaries": [
        {
            "lastUpdateTime": 1558129925.2,
            "creationTime": 1552073155.527,
            "state": {
                "stateName": "Normal"
            },
            "keyValue": "Fulton-A32",
            "detectorModelName": "motorDetectorModel",
            "detectorModelVersion": "1"
        }
    ]
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[ListDetectors](https://docs.aws.amazon.com/iotevents/latest/apireference/API_iotevents-data_ListDetectors)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDetectors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/list-detectors.html)」を参照してください。

### `list-inputs`
<a name="iot-events_ListInputs_cli_2_topic"></a>

次のコード例は、`list-inputs` を使用する方法を示しています。

**AWS CLI**  
**入力を一覧表示するには**  
次の `list-inputs` の例では、アカウントに作成した入力を一覧表示します。  

```
aws iotevents list-inputs
```
このコマンドでは何も出力されません。出力:  

```
{
    {
        "status": "ACTIVE",
        "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
        "lastUpdateTime": 1551742986.768,
        "creationTime": 1551742986.768,
        "inputName": "PressureInput",
        "inputDescription": "Pressure readings from a motor"
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[ListInputs](https://docs.aws.amazon.com/iotevents/latest/apireference/API_ListInputs)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInputs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/list-inputs.html)」を参照してください。

### `list-tags-for-resource`
<a name="iot-events_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに割り当てられたタグを一覧表示するには。**  
次の `list-tags-for-resource` の例では、リソースに割り当てたタグキーの名前と値を一覧表示します。  

```
aws iotevents list-tags-for-resource \
    --resource-arn "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput"
```
出力:  

```
{
    "tags": [
        {
            "value": "motor",
            "key": "deviceType"
        }
    ]
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[ListTagsForResource](https://docs.aws.amazon.com/iotevents/latest/apireference/API_ListTagsForResource)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/list-tags-for-resource.html)」を参照してください。

### `put-logging-options`
<a name="iot-events_PutLoggingOptions_cli_2_topic"></a>

次のコード例は、`put-logging-options` を使用する方法を示しています。

**AWS CLI**  
**ログ記録オプションを設定するには**  
次の の`put-logging-options`例では、 AWS IoT Events ログ記録オプションを設定または更新します。`loggingOptions` field, it can take up to one minute for the change to take effect. Also, if you change the policy attached to the role you specified in the ``roleArn` のいずれかのフィールドの値を更新する場合 (無効なポリシーを修正するなど)、その変更が有効になるまでに最大 5 分かかることがあります。  

```
aws iotevents put-logging-options \
    --cli-input-json file://logging-options.json
```
`logging-options.json` の内容:  

```
{
    "loggingOptions": {
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "level": "DEBUG",
        "enabled": true,
        "detectorDebugOptions": [
            {
                "detectorModelName": "motorDetectorModel",
                "keyValue": "Fulton-A32"
            }
        ]
    }
}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events API リファレンス*」の「[PutLoggingOptions](https://docs.aws.amazon.com/iotevents/latest/apireference/API_PutLoggingOptions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/put-logging-options.html)」を参照してください。

### `tag-resource`
<a name="iot-events_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加するには**  
次の `tag-resource` の例では、指定されたリソースにアタッチされたタグを追加または変更 (キー `deviceType` が既に存在する場合) します。  

```
aws iotevents tag-resource \
    --cli-input-json file://pressureInput.tag.json
```
`pressureInput.tag.json` の内容:  

```
{
    "resourceArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
    "tags": [
        {
            "key": "deviceType",
            "value": "motor"
        }
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events API リファレンス*」の「[TagResource](https://docs.aws.amazon.com/iotevents/latest/apireference/API_TagResource)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="iot-events_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除する**  
次の `untag-resource` の例では、指定されたキー名を持つタグを指定されたリソースから削除します。  

```
aws iotevents untag-resource \
    --resource-arn arn:aws:iotevents:us-west-2:123456789012:input/PressureInput \
    --tagkeys deviceType
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events API リファレンス*」の「[UntagResource](https://docs.aws.amazon.com/iotevents/latest/apireference/API_UntagResource)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/untag-resource.html)」を参照してください。

### `update-detector-model`
<a name="iot-events_UpdateDetectorModel_cli_2_topic"></a>

次のコード例は、`update-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルを更新するには**  
次の `update-detector-model` の例では、指定されたディテクターモデルを更新します。以前のバージョンによって生成されたディテクター (インスタンス) が削除され、新しい入力が到着すると再作成されます。  

```
aws iotevents update-detector-model \
    --cli-input-json file://motorDetectorModel.update.json
```
`motorDetectorModel.update.json` の内容:  

```
{
    "detectorModelName": "motorDetectorModel",
    "detectorModelDefinition": {
        "states": [
            {
                "stateName": "Normal",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "init",
                            "condition": "true",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "Overpressurized",
                            "condition": "$input.PressureInput.sensorData.pressure > 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "$variable.pressureThresholdBreached + 3"
                                    }
                                }
                            ],
                            "nextState": "Dangerous"
                        }
                    ]
                }
            },
            {
                "stateName": "Dangerous",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Pressure Threshold Breached",
                            "condition": "$variable.pressureThresholdBreached > 1",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "events": [
                        {
                            "eventName": "Overpressurized",
                            "condition": "$input.PressureInput.sensorData.pressure > 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "3"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Pressure Okay",
                            "condition": "$input.PressureInput.sensorData.pressure <= 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "$variable.pressureThresholdBreached - 1"
                                    }
                                }
                            ]
                        }
                    ],
                    "transitionEvents": [
                        {
                            "eventName": "BackToNormal",
                            "condition": "$input.PressureInput.sensorData.pressure <= 70 && $variable.pressureThresholdBreached <= 1",
                            "nextState": "Normal"
                        }
                    ]
                },
                "onExit": {
                    "events": [
                        {
                            "eventName": "Normal Pressure Restored",
                            "condition": "true",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
        ],
        "initialStateName": "Normal"
    },
    "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole"
}
```
出力:  

```
{
    "detectorModelConfiguration": {
        "status": "ACTIVATING",
        "lastUpdateTime": 1560799387.719,
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "creationTime": 1560799387.719,
        "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
        "key": "motorid",
        "detectorModelName": "motorDetectorModel",
        "detectorModelVersion": "2"
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[UpdateDetectorModel](https://docs.aws.amazon.com/iotevents/latest/apireference/API_UpdateDetectorModel)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/update-detector-model.html)」を参照してください。

### `update-input`
<a name="iot-events_UpdateInput_cli_2_topic"></a>

次のコード例は、`update-input` を使用する方法を示しています。

**AWS CLI**  
**入力を更新するには**  
次の `update-input` の例では、指定された入力を新しい説明と定義で更新します。  

```
aws iotevents update-input \
    --cli-input-json file://pressureInput.json
```
`pressureInput.json` の内容:  

```
{
    "inputName": "PressureInput",
    "inputDescription": "Pressure readings from a motor",
    "inputDefinition": {
        "attributes": [
            { "jsonPath": "sensorData.pressure" },
            { "jsonPath": "motorid" }
        ]
    }
}
```
出力:  

```
{
    "inputConfiguration": {
        "status": "ACTIVE",
        "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
        "lastUpdateTime": 1560795976.458,
        "creationTime": 1560795312.542,
        "inputName": "PressureInput",
        "inputDescription": "Pressure readings from a motor"
    }
}
```
詳細については、「*AWS IoT Events API リファレンス*」の「[UpdateInput](https://docs.aws.amazon.com/iotevents/latest/apireference/API_UpdateInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents/update-input.html)」を参照してください。

# AWS IoT Events-Data を使用した の例 AWS CLI
<a name="cli_2_iot-events-data_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT Events-Data。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-put-message`
<a name="iot-events-data_BatchPutMessage_cli_2_topic"></a>

次の例は、`batch-put-message` を使用する方法を説明しています。

**AWS CLI**  
** AWS IoT イベントにメッセージ (入力) を送信するには**  
次の の`batch-put-message`例では、一連のメッセージを AWS IoT Events システムに送信します。各メッセージペイロードは、指定した入力 (`inputName`) に変換され、その入力をモニタリングするディテクターに取り込まれます。複数のメッセージが送信された場合、メッセージが処理される順序は保証されません。順序を保証するには、メッセージを一度に 1 つずつ送信し、成功のレスポンスを待つ必要があります。  

```
aws iotevents-data batch-put-message \
    --cli-binary-format raw-in-base64-out \
    --cli-input-json file://highPressureMessage.json
```
`highPressureMessage.json` の内容:  

```
{
    "messages": [
        {
            "messageId": "00001",
            "inputName": "PressureInput",
            "payload": "{\"motorid\": \"Fulton-A32\", \"sensorData\": {\"pressure\": 80, \"temperature\": 39} }"
        }
    ]
}
```
出力:  

```
{
    "BatchPutMessageErrorEntries": []
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[BatchPutMessage](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-data-BatchPutMessage)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchPutMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/batch-put-message.html)」を参照してください。

### `batch-update-detector`
<a name="iot-events-data_BatchUpdateDetector_cli_2_topic"></a>

次のコード例は、`batch-update-detector` を使用する方法を示しています。

**AWS CLI**  
**ディテクター (インスタンス) を更新するには**  
次の `batch-update-detector` の例では、指定されたディテクターモデルの 1 つ以上のディテクター (インスタンス) の状態、変数値、タイマー設定を更新します。  

```
aws iotevents-data batch-update-detector \
    --cli-input-json file://budFulton-A32.json
```
`budFulton-A32.json` の内容:  

```
{
    "detectors": [
        {
            "messageId": "00001",
            "detectorModelName": "motorDetectorModel",
            "keyValue": "Fulton-A32",
            "state": {
                "stateName": "Normal",
                "variables": [
                    {
                        "name": "pressureThresholdBreached",
                        "value": "0"
                    }
                ],
                "timers": [
                ]
            }
        }
    ]
}
```
出力:  

```
{
    "batchUpdateDetectorErrorEntries": []
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[BatchUpdateDetector](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-data-BatchUpdateDetector)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchUpdateDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/batch-update-detector.html)」を参照してください。

### `create-detector-model`
<a name="iot-events-data_CreateDetectorModel_cli_2_topic"></a>

次のコード例は、`create-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルを作成するには**  
次の `create-detector-model` の例では、ディテクターモデルを作成します。  

```
aws iotevents create-detector-model \
    --cli-input-json file://motorDetectorModel.json
```
`motorDetectorModel.json` の内容:  

```
{
    "detectorModelName": "motorDetectorModel",
    "detectorModelDefinition": {
        "states": [
            {
                "stateName": "Normal",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "init",
                            "condition": "true",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "0"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "transitionEvents": [
                        {
                            "eventName": "Overpressurized",
                            "condition": "$input.PressureInput.sensorData.pressure &gt; 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "$variable.pressureThresholdBreached + 3"
                                    }
                                }
                            ],
                            "nextState": "Dangerous"
                        }
                    ]
                }
            },
            {
                "stateName": "Dangerous",
                "onEnter": {
                    "events": [
                        {
                            "eventName": "Pressure Threshold Breached",
                            "condition": "$variable.pressureThresholdBreached &gt; 1",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"
                                    }
                                }
                            ]
                        }
                    ]
                },
                "onInput": {
                    "events": [
                        {
                            "eventName": "Overpressurized",
                            "condition": "$input.PressureInput.sensorData.pressure &gt; 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "3"
                                    }
                                }
                            ]
                        },
                        {
                            "eventName": "Pressure Okay",
                            "condition": "$input.PressureInput.sensorData.pressure &lt;= 70",
                            "actions": [
                                {
                                    "setVariable": {
                                        "variableName": "pressureThresholdBreached",
                                        "value": "$variable.pressureThresholdBreached - 1"
                                    }
                                }
                            ]
                        }
                    ],
                    "transitionEvents": [
                        {
                            "eventName": "BackToNormal",
                            "condition": "$input.PressureInput.sensorData.pressure &lt;= 70 &amp;&amp; $variable.pressureThresholdBreached &lt;= 1",
                            "nextState": "Normal"
                        }
                    ]
                },
                "onExit": {
                    "events": [
                        {
                            "eventName": "Normal Pressure Restored",
                            "condition": "true",
                            "actions": [
                                {
                                    "sns": {
                                        "targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"
                                    }
                                }
                            ]
                        }
                    ]
                }
            }
        ],
        "initialStateName": "Normal"
    },
    "key": "motorid",
    "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole"
}
```
出力:  

```
{
    "detectorModelConfiguration": {
        "status": "ACTIVATING",
        "lastUpdateTime": 1560796816.077,
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "creationTime": 1560796816.077,
        "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
        "key": "motorid",
        "detectorModelName": "motorDetectorModel",
        "detectorModelVersion": "1"
    }
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[CreateDetectorModel](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-CreateDetectorModel)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/create-detector-model.html)」を参照してください。

### `create-input`
<a name="iot-events-data_CreateInput_cli_2_topic"></a>

次のコード例は、`create-input` を使用する方法を示しています。

**AWS CLI**  
**入力を作成するには**  
次の `create-input` の例では、入力を作成します。  

```
aws iotevents create-input \
    --cli-input-json file://pressureInput.json
```
`pressureInput.json` の内容:  

```
{
    "inputName": "PressureInput",
    "inputDescription": "Pressure readings from a motor",
    "inputDefinition": {
        "attributes": [
                { "jsonPath": "sensorData.pressure" },
                { "jsonPath": "motorid" }
            ]
    }
}
```
出力:  

```
{
    "inputConfiguration": {
        "status": "ACTIVE",
        "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
        "lastUpdateTime": 1560795312.542,
        "creationTime": 1560795312.542,
        "inputName": "PressureInput",
        "inputDescription": "Pressure readings from a motor"
    }
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[CreateInput](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-CreateInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/create-input.html)」を参照してください。

### `delete-detector-model`
<a name="iot-events-data_DeleteDetectorModel_cli_2_topic"></a>

次のコード例は、`delete-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルを削除するには**  
次の `delete-detector-model` の例では、ディテクターモデルを削除します。ディテクターモデルのアクティブなインスタンスも削除されます。  

```
aws iotevents delete-detector-model \
    --detector-model-name motorDetectorModel*
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[DeleteDetectorModel](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-DeleteDetectorModel)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/delete-detector-model.html)」を参照してください。

### `delete-input`
<a name="iot-events-data_DeleteInput_cli_2_topic"></a>

次のコード例は、`delete-input` を使用する方法を示しています。

**AWS CLI**  
**入力を削除するには**  
次の `delete-input` の例では、入力を削除します。  

```
aws iotevents delete-input \
    --input-name PressureInput
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[DeleteInput](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-DeleteInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/delete-input.html)」を参照してください。

### `describe-detector-model`
<a name="iot-events-data_DescribeDetectorModel_cli_2_topic"></a>

次のコード例は、`describe-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルに関する情報を取得するには**  
次の `describe-detector-model` の例では、ディテクターモデルの説明を表示します。`version` パラメータが指定されていない場合、コマンドは最新バージョンに関する情報を返します。  

```
aws iotevents describe-detector-model \
    --detector-model-name motorDetectorModel
```
出力:  

```
{
    "detectorModel": {
        "detectorModelConfiguration": {
            "status": "ACTIVE",
            "lastUpdateTime": 1560796816.077,
            "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
            "creationTime": 1560796816.077,
            "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
            "key": "motorid",
            "detectorModelName": "motorDetectorModel",
            "detectorModelVersion": "1"
        },
        "detectorModelDefinition": {
            "states": [
                {
                    "onInput": {
                        "transitionEvents": [
                            {
                                "eventName": "Overpressurized",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "$variable.pressureThresholdBreached + 3"
                                        }
                                    }
                                ],
                                "condition": "$input.PressureInput.sensorData.pressure > 70",
                                "nextState": "Dangerous"
                            }
                        ],
                        "events": []
                    },
                    "stateName": "Normal",
                    "onEnter": {
                        "events": [
                            {
                                "eventName": "init",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "0"
                                        }
                                    }
                                ],
                                "condition": "true"
                            }
                        ]
                    },
                    "onExit": {
                        "events": []
                    }
                },
                {
                    "onInput": {
                        "transitionEvents": [
                            {
                                "eventName": "BackToNormal",
                                "actions": [],
                                "condition": "$input.PressureInput.sensorData.pressure <= 70 && $variable.pressureThresholdBreached <= 1",
                                "nextState": "Normal"
                            }
                        ],
                        "events": [
                            {
                                "eventName": "Overpressurized",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "3"
                                        }
                                    }
                                ],
                                "condition": "$input.PressureInput.sensorData.pressure > 70"
                            },
                            {
                                "eventName": "Pressure Okay",
                                "actions": [
                                    {
                                        "setVariable": {
                                            "variableName": "pressureThresholdBreached",
                                            "value": "$variable.pressureThresholdBreached - 1"
                                        }
                                    }
                                ],
                                "condition": "$input.PressureInput.sensorData.pressure <= 70"
                            }
                        ]
                    },
                    "stateName": "Dangerous",
                    "onEnter": {
                        "events": [
                            {
                                "eventName": "Pressure Threshold Breached",
                                "actions": [
                                    {
                                        "sns": {
                                            "targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"
                                        }
                                    }
                                ],
                                "condition": "$variable.pressureThresholdBreached > 1"
                            }
                        ]
                    },
                    "onExit": {
                        "events": [
                            {
                                "eventName": "Normal Pressure Restored",
                                "actions": [
                                    {
                                        "sns": {
                                            "targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"
                                        }
                                    }
                                ],
                                "condition": "true"
                            }
                        ]
                    }
                }
            ],
            "initialStateName": "Normal"
        }
    }
}
```
詳細については、「*AWS IoT Events ディベロッパーガイド\$1*」の「[DescribeDetectorModel](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-DescribeDetectorModel)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/describe-detector-model.html)」を参照してください。

### `describe-detector`
<a name="iot-events-data_DescribeDetector_cli_2_topic"></a>

次のコード例は、`describe-detector` を使用する方法を示しています。

**AWS CLI**  
**ディテクター (インスタンス) に関する情報を取得するには**  
次の `describe-detector` の例では、指定されたディテクター (インスタンス) に関する情報を返します。  

```
aws iotevents-data describe-detector \
    --detector-model-name motorDetectorModel \
    --key-value "Fulton-A32"
```
出力:  

```
{
    "detector": {
        "lastUpdateTime": 1560797852.776,
        "creationTime": 1560797852.775,
        "state": {
            "variables": [
                {
                    "name": "pressureThresholdBreached",
                    "value": "3"
                }
            ],
            "stateName": "Dangerous",
            "timers": []
        },
        "keyValue": "Fulton-A32",
        "detectorModelName": "motorDetectorModel",
        "detectorModelVersion": "1"
    }
}
```
詳細については、「*AWS IoT Events ディベロッパーガイド\$1*」の「[DescribeDetector](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-data-DescribeDetector)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDetector](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/describe-detector.html)」を参照してください。

### `describe-input`
<a name="iot-events-data_DescribeInput_cli_2_topic"></a>

次のコード例は、`describe-input` を使用する方法を示しています。

**AWS CLI**  
**入力に関する情報を取得するには**  
次の `describe-input` の例では、入力の詳細を取得します。  

```
aws iotevents describe-input \
    --input-name PressureInput
```
出力:  

```
{
    "input": {
        "inputConfiguration": {
            "status": "ACTIVE",
            "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
            "lastUpdateTime": 1560795312.542,
            "creationTime": 1560795312.542,
            "inputName": "PressureInput",
            "inputDescription": "Pressure readings from a motor"
        },
        "inputDefinition": {
            "attributes": [
                {
                    "jsonPath": "sensorData.pressure"
                },
                {
                    "jsonPath": "motorid"
                }
            ]
        }
    }
}
```
詳細については、「*AWS IoT Events ディベロッパーガイド\$1*」の「[DescribeInput](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-DescribeInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/describe-input.html)」を参照してください。

### `describe-logging-options`
<a name="iot-events-data_DescribeLoggingOptions_cli_2_topic"></a>

次のコード例は、`describe-logging-options` を使用する方法を示しています。

**AWS CLI**  
**ログ記録設定に関する情報を取得するには**  
次の の`describe-logging-options`例では、現在の AWS IoT Events ログ記録オプションを取得します。  

```
aws iotevents describe-logging-options
```
出力:  

```
{
    "loggingOptions": {
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "enabled": false,
        "level": "ERROR"
    }
}
```
詳細については、「*AWS IoT Events ディベロッパーガイド\$1*」の「[DescribeLoggingOptions](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-DescribeLoggingOptions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/describe-logging-options.html)」を参照してください。

### `list-detector-model-versions`
<a name="iot-events-data_ListDetectorModelVersions_cli_2_topic"></a>

次のコード例は、`list-detector-model-versions` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルのバージョンに関する情報を取得するには**  
次の `list-detector-model-versions` の例では、ディテクターモデルのすべてのバージョンを一覧表示します。各探知器モデルのバージョンに関連付けられているメタデータのみが返されます。  

```
aws iotevents list-detector-model-versions \
    --detector-model-name motorDetectorModel
```
出力:  

```
{
    "detectorModelVersionSummaries": [
        {
            "status": "ACTIVE",
            "lastUpdateTime": 1560796816.077,
            "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
            "creationTime": 1560796816.077,
            "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
            "detectorModelName": "motorDetectorModel",
            "detectorModelVersion": "1"
        }
    ]
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[ListDetectorModelVersions](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-ListDetectorModelVersions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDetectorModelVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/list-detector-model-versions.html)」を参照してください。

### `list-detector-models`
<a name="iot-events-data_ListDetectorModels_cli_2_topic"></a>

次のコード例は、`list-detector-models` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルのリストを取得するには**  
次の `list-detector-models` の例では、作成したディテクターモデルを一覧表示します。各探知器モデルに関連付けられているメタデータのみが返されます。  

```
aws iotevents list-detector-models
```
出力:  

```
{
    "detectorModelSummaries": [
        {
            "detectorModelName": "motorDetectorModel",
            "creationTime": 1552072424.212
            "detectorModelDescription": "Detect overpressure in a motor."
        }
    ]
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[ListDetectorModels](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-ListDetectorModels)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDetectorModels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/list-detector-models.html)」を参照してください。

### `list-detectors`
<a name="iot-events-data_ListDetectors_cli_2_topic"></a>

次のコード例は、`list-detectors` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルのディテクターのリストを取得するには**  
次の `list-detectors` の例では、ディテクター (ディテクターモデルのインスタンス) を一覧表示します。  

```
aws iotevents-data list-detectors \
    --detector-model-name motorDetectorModel
```
出力:  

```
{
    "detectorSummaries": [
        {
            "lastUpdateTime": 1558129925.2,
            "creationTime": 1552073155.527,
            "state": {
                "stateName": "Normal"
            },
            "keyValue": "Fulton-A32",
            "detectorModelName": "motorDetectorModel",
            "detectorModelVersion": "1"
        }
    ]
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[ListDetectors](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-ListDetectors)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDetectors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/list-detectors.html)」を参照してください。

### `list-inputs`
<a name="iot-events-data_ListInputs_cli_2_topic"></a>

次のコード例は、`list-inputs` を使用する方法を示しています。

**AWS CLI**  
**入力を一覧表示するには**  
次の `list-inputs` の例では、作成した入力を一覧表示します。  

```
aws iotevents list-inputs
```
出力:  

```
{
    "status": "ACTIVE",
    "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
    "lastUpdateTime": 1551742986.768,
    "creationTime": 1551742986.768,
    "inputName": "PressureInput",
    "inputDescription": "Pressure readings from a motor"
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[ListInputs](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-ListInputs)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInputs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/list-inputs.html)」を参照してください。

### `list-tags-for-resource`
<a name="iot-events-data_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに割り当てられたタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、リソースに割り当てたタグ (メタデータ) を一覧表示します。  

```
aws iotevents list-tags-for-resource \
    --resource-arn "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput"
```
出力:  

```
{
    "tags": [
        {
            "value": "motor",
            "key": "deviceType"
        }
    ]
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[ListTagsForResource](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-ListTagsForResource)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/list-tags-for-resource.html)」を参照してください。

### `put-logging-options`
<a name="iot-events-data_PutLoggingOptions_cli_2_topic"></a>

次のコード例は、`put-logging-options` を使用する方法を示しています。

**AWS CLI**  
**ログ記録オプションを設定するには**  
次の の`list-tags-for-resource`例では、 AWS IoT Events ログ記録オプションを設定または更新します。いずれかの `loggingOptions` フィールドの値を更新する場合、変更が有効になるまでに最大で 1 分かかることに注意してください また、`roleArn` フィールドで指定したロールにアタッチされるポリシーを変更する場合 (たとえば、無効なポリシーを修正するなど)、この変更が有効になるまでには最大で 5 分かかります。  

```
aws iotevents put-logging-options \
    --cli-input-json file://logging-options.json
```
`logging-options.json` の内容:  

```
{
    "loggingOptions": {
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "level": "DEBUG",
        "enabled": true,
        "detectorDebugOptions": [
            {
                "detectorModelName": "motorDetectorModel",
                "keyValue": "Fulton-A32"
            }
        ]
    }
}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events ディベロッパーガイド\$1*」の「[PutLoggingOptions](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-PutLoggingOptions)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/put-logging-options.html)」を参照してください。

### `tag-resource`
<a name="iot-events-data_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加するには**  
次の `tag-resource` の例では、指定されたリソースのタグを追加または変更します。タグは、リソースを管理するために使用できるメタデータです。  

```
aws iotevents tag-resource \
    --cli-input-json file://pressureInput.tag.json
```
`pressureInput.tag.json` の内容:  

```
{
    "resourceArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
    "tags": [
        {
            "key": "deviceType",
            "value": "motor"
        }
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[TagResource](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-TagResource)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="iot-events-data_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除する**  
次の `untag-resource` の例では、指定されたタグをリソースから削除します。  

```
aws iotevents untag-resource \
    --cli-input-json file://pressureInput.untag.json
```
`pressureInput.untag.json` の内容:  

```
{
    "resourceArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
    "tagKeys": [
            "deviceType"
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[UntagResource](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-UntagResource)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/untag-resource.html)」を参照してください。

### `update-detector-model`
<a name="iot-events-data_UpdateDetectorModel_cli_2_topic"></a>

次のコード例は、`update-detector-model` を使用する方法を示しています。

**AWS CLI**  
**ディテクターモデルを更新するには**  
次の `update-detector-model` の例では、ディテクターモデルを更新します。以前のバージョンによって生成されたディテクター (インスタンス) が削除され、新しい入力が到着すると再作成されます。  

```
aws iotevents update-detector-model \
    --cli-input-json file://motorDetectorModel.update.json
```
Contents of motorDetectorModel.update.json:  

```
{
  "detectorModelName": "motorDetectorModel",
  "detectorModelDefinition": {
    "states": [
      {
        "stateName": "Normal",
        "onEnter": {
          "events": [
            {
              "eventName": "init",
              "condition": "true",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "0"
                  }
                }
              ]
            }
          ]
        },
        "onInput": {
          "transitionEvents": [
            {
              "eventName": "Overpressurized",
              "condition": "$input.PressureInput.sensorData.pressure > 70",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "$variable.pressureThresholdBreached + 3"
                  }
                }
              ],
              "nextState": "Dangerous"
            }
          ]
        }
      },
      {
        "stateName": "Dangerous",
        "onEnter": {
          "events": [
            {
              "eventName": "Pressure Threshold Breached",
              "condition": "$variable.pressureThresholdBreached > 1",
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-east-1:123456789012:underPressureAction"
                  }
                }
              ]
            }
          ]
        },
        "onInput": {
          "events": [
            {
              "eventName": "Overpressurized",
              "condition": "$input.PressureInput.sensorData.pressure > 70",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "3"
                  }
                }
              ]
            },
            {
              "eventName": "Pressure Okay",
              "condition": "$input.PressureInput.sensorData.pressure <= 70",
              "actions": [
                {
                  "setVariable": {
                    "variableName": "pressureThresholdBreached",
                    "value": "$variable.pressureThresholdBreached - 1"
                  }
                }
              ]
            }
          ],
          "transitionEvents": [
            {
              "eventName": "BackToNormal",
              "condition": "$input.PressureInput.sensorData.pressure <= 70 && $variable.pressureThresholdBreached <= 1",
              "nextState": "Normal"
            }
          ]
        },
        "onExit": {
          "events": [
            {
              "eventName": "Normal Pressure Restored",
              "condition": "true",
              "actions": [
                {
                  "sns": {
                    "targetArn": "arn:aws:sns:us-east-1:123456789012:pressureClearedAction"
                  }
                }
              ]
            }
          ]
        }
      }
    ],
    "initialStateName": "Normal"
  },
  "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole"
}
```
出力:  

```
{
    "detectorModelConfiguration": {
        "status": "ACTIVATING",
        "lastUpdateTime": 1560799387.719,
        "roleArn": "arn:aws:iam::123456789012:role/IoTEventsRole",
        "creationTime": 1560799387.719,
        "detectorModelArn": "arn:aws:iotevents:us-west-2:123456789012:detectorModel/motorDetectorModel",
        "key": "motorid",
        "detectorModelName": "motorDetectorModel",
        "detectorModelVersion": "2"
    }
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[UpdateDetectorModel](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-UpdateDetectorModel)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDetectorModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/update-detector-model.html)」を参照してください。

### `update-input`
<a name="iot-events-data_UpdateInput_cli_2_topic"></a>

次のコード例は、`update-input` を使用する方法を示しています。

**AWS CLI**  
**入力を更新するには**  
次の `update-input` の例では、入力を更新します。  

```
aws iotevents update-input \
    --cli-input-json file://pressureInput.json
```
`pressureInput.json` の内容:  

```
{
    "inputName": "PressureInput",
    "inputDescription": "Pressure readings from a motor",
    "inputDefinition": {
        "attributes": [
            { "jsonPath": "sensorData.pressure" },
            { "jsonPath": "motorid" }
        ]
    }
}
```
出力:  

```
{
    "inputConfiguration": {
        "status": "ACTIVE",
        "inputArn": "arn:aws:iotevents:us-west-2:123456789012:input/PressureInput",
        "lastUpdateTime": 1560795976.458,
        "creationTime": 1560795312.542,
        "inputName": "PressureInput",
        "inputDescription": "Pressure readings from a motor"
    }
}
```
詳細については、「*AWS IoT Events デベロッパーガイド\$1*」の「[UpdateInput](https://docs.aws.amazon.com/iotevents/latest/developerguide/iotevents-commands.html#api-iotevents-UpdateInput)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotevents-data/update-input.html)」を参照してください。

# AWS IoT Greengrass を使用した の例 AWS CLI
<a name="cli_2_greengrass_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT Greengrass。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-role-to-group`
<a name="greengrass_AssociateRoleToGroup_cli_2_topic"></a>

次のコード例は、`associate-role-to-group` を使用する方法を示しています。

**AWS CLI**  
**ロールを Greengrass グループに関連付けるには**  
次の `associate-role-to-group` の例では、指定された IAM ロールを Greengrass グループに関連付けます。グループロールは、ローカルの Lambda 関数とコネクタが AWS サービスにアクセスするために使用します。例えば、グループロールは CloudWatch Logs 統合に必要なアクセス許可を付与する場合があります。  

```
aws greengrass associate-role-to-group \
    --group-id 2494ee3f-7f8a-4e92-a78b-d205f808b84b \
    --role-arn arn:aws:iam::123456789012:role/GG-Group-Role
```
出力:  

```
{
    "AssociatedAt": "2019-09-10T20:03:30Z"
}
```
グループの詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループロールを設定する](https://docs.aws.amazon.com/greengrass/latest/developerguide/config-iam-roles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateRoleToGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/associate-role-to-group.html)」を参照してください。

### `associate-service-role-to-account`
<a name="greengrass_AssociateServiceRoleToAccount_cli_2_topic"></a>

次の例は、`associate-service-role-to-account` を使用する方法を説明しています。

**AWS CLI**  
**サービスロールを AWS アカウントに関連付けるには**  
次の`associate-service-role-to-account`例では、ARN で指定された IAM サービスロールを AWS アカウントの AWS IoT Greengrass に関連付けます。IAM でサービスロールを事前に作成し、 AWS IoT Greengrass がこのロールを引き受けることを許可するポリシードキュメントを関連付ける必要があります。  

```
aws greengrass associate-service-role-to-account \
    --role-arn "arn:aws:iam::123456789012:role/service-role/Greengrass_ServiceRole"
```
出力:  

```
{
    "AssociatedAt": "2019-06-25T18:12:45Z"
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[Greengrass サービスロール](https://docs.aws.amazon.com/greengrass/latest/developerguide/service-role.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateServiceRoleToAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/associate-service-role-to-account.html)」を参照してください。

### `create-connector-definition-version`
<a name="greengrass_CreateConnectorDefinitionVersion_cli_2_topic"></a>

次のコード例は、`create-connector-definition-version` を使用する方法を示しています。

**AWS CLI**  
**コネクタ定義バージョンを作成するには**  
次の `create-connector-definition-version` の例では、コネクタ定義バージョンを作成し、指定されたコネクタ定義に関連付けます。バージョン内のすべてのコネクタはパラメータの値を定義します。  

```
aws greengrass create-connector-definition-version \
    --connector-definition-id "55d0052b-0d7d-44d6-b56f-21867215e118" \
    --connectors "[{\"Id\": \"MyTwilioNotificationsConnector\", \"ConnectorArn\": \"arn:aws:greengrass:us-west-2::/connectors/TwilioNotifications/versions/2\", \"Parameters\": {\"TWILIO_ACCOUNT_SID\": \"AC1a8d4204890840d7fc482aab38090d57\", \"TwilioAuthTokenSecretArn\": \"arn:aws:secretsmanager:us-west-2:123456789012:secret:greengrass-TwilioAuthToken-ntSlp6\", \"TwilioAuthTokenSecretArn-ResourceId\": \"TwilioAuthToken\", \"DefaultFromPhoneNumber\": \"4254492999\"}}]"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/55d0052b-0d7d-44d6-b56f-21867215e118/versions/33f709a0-c825-49cb-9eea-dc8964fbd635",
    "CreationTimestamp": "2019-06-24T20:46:30.134Z",
    "Id": "55d0052b-0d7d-44d6-b56f-21867215e118",
    "Version": "33f709a0-c825-49cb-9eea-dc8964fbd635"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConnectorDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-connector-definition-version.html)」を参照してください。

### `create-connector-definition`
<a name="greengrass_CreateConnectorDefinition_cli_2_topic"></a>

次のコード例は、`create-connector-definition` を使用する方法を示しています。

**AWS CLI**  
**コネクタ定義を作成するには**  
次の `create-connector-definition` の例では、コネクタ定義と初期コネクタ定義バージョンを作成します。初期バージョンにはコネクタが 1 つ含まれています。バージョン内のすべてのコネクタはパラメータの値を定義します。  

```
aws greengrass create-connector-definition \
    --name MySNSConnector \
    --initial-version "{\"Connectors\": [{\"Id\":\"MySNSConnector\",\"ConnectorArn\":\"arn:aws:greengrass:us-west-2::/connectors/SNS/versions/1\",\"Parameters\": {\"DefaultSNSArn\":\"arn:aws:sns:us-west-2:123456789012:GGConnectorTopic\"}}]}"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
    "CreationTimestamp": "2019-06-19T19:30:01.300Z",
    "Id": "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
    "LastUpdatedTimestamp": "2019-06-19T19:30:01.300Z",
    "LatestVersion": "63c57963-c7c2-4a26-a7e2-7bf478ea2623",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8/versions/63c57963-c7c2-4a26-a7e2-7bf478ea2623",
    "Name": "MySNSConnector"
}
```
詳細については、「**AWS IoT デベロッパーガイド**」の「[Greengrass コネクタの開始方法 (CLI)](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConnectorDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-connector-definition.html)」を参照してください。

### `create-core-definition-version`
<a name="greengrass_CreateCoreDefinitionVersion_cli_2_topic"></a>

次のコード例は、`create-core-definition-version` を使用する方法を示しています。

**AWS CLI**  
**コア定義バージョンを作成するには**  
次の `create-core-definition-version` の例では、コア定義バージョンを作成し、指定したコア定義に関連付けます。バージョンに含めることができるのは 1 つのコアのみです。コアを作成する前に、まず対応する AWS IoT モノを作成してプロビジョニングする必要があります。このプロセスには、`create-core-definition-version` コマンドに必要な `ThingArn` と `CertificateArn` を返す次の `iot` コマンドが含まれます。  
コアデバイスに対応する AWS IoT モノを作成します。  

```
aws iot create-thing \
    --thing-name "MyCoreDevice"
```
出力:  

```
{
    "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyCoreDevice",
    "thingName": "MyCoreDevice",
    "thingId": "cb419a19-9099-4515-9cec-e9b0e760608a"
}
```
パブリックキーとプライベートキー、およびモノのコアデバイス証明書を作成します。この例では `create-keys-and-certificate` コマンドを使用し、現在のディレクトリへの書き込みアクセス許可を必要とします。または、 `create-certificate-from-csr` コマンドを使用できます。  

```
aws iot create-keys-and-certificate \
    --set-as-active \
    --certificate-pem-outfile "myCore.cert.pem" \
    --public-key-outfile "myCore.public.key" \
    --private-key-outfile "myCore.private.key"
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz",
    "certificatePem": "-----BEGIN CERTIFICATE-----\nMIIDWTCAkGgAwIBATgIUCgq6EGqou6zFqWgIZRndgQEFW+gwDQYJKoZIhvc...KdGewQS\n-----END CERTIFICATE-----\n",
    "keyPair": {
        "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBzrqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqKpRgnn6yq26U3y...wIDAQAB\n-----END PUBLIC KEY-----\n",
        "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIABAKCAQEAqKpRgnn6yq26U3yt5YFZquyukfRjbMXDcNOK4rMCxDR...fvY4+te\n-----END RSA PRIVATE KEY-----\n"
    },
    "certificateId": "123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz"
}
```
`iot` および `greengrass`アクションを許可する AWS IoT ポリシーを作成します。簡単にするために、次のポリシーではすべてのリソースに対するアクションが許可されていますが、ポリシーはより制限されている必要があります。  

```
aws iot create-policy \
    --policy-name "Core_Devices" \
    --policy-document "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}"
```
出力:  

```
{
    "policyName": "Core_Devices",
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/Core_Devices",
    "policyDocument": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}",
    "policyVersionId": "1"
}
```
ポリシーを証明書にアタッチします。  

```
aws iot attach-policy \
    --policy-name "Core_Devices" \
    --target "arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz"
```
このコマンドでは何も出力されません。  
モノを証明書にアタッチします。  

```
aws iot attach-thing-principal \
    --thing-name "MyCoreDevice" \
    --principal "arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz"
```
このコマンドでは何も出力されません。  
コア定義バージョンを作成します。  

```
aws greengrass create-core-definition-version \
    --core-definition-id "582efe12-b05a-409e-9a24-a2ba1bcc4a12" \
    --cores "[{\"Id\":\"MyCoreDevice\",\"ThingArn\":\"arn:aws:iot:us-west-2:123456789012:thing/MyCoreDevice\",\"CertificateArn\":\"arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz\",\"SyncShadow\":true}]"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/582efe12-b05a-409e-9a24-a2ba1bcc4a12/versions/3fdc1190-2ce5-44de-b98b-eec8f9571014",
    "Version": "3fdc1190-2ce5-44de-b98b-eec8f9571014",
    "CreationTimestamp": "2019-09-18T00:15:09.838Z",
    "Id": "582efe12-b05a-409e-9a24-a2ba1bcc4a12"
}
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「Configure theIoT Greengrass Core](https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-core.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCoreDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-core-definition-version.html)」を参照してください。

### `create-core-definition`
<a name="greengrass_CreateCoreDefinition_cli_2_topic"></a>

次のコード例は、`create-core-definition` を使用する方法を示しています。

**AWS CLI**  
**例 1: 空のコア定義を作成するには**  
次の `create-core-definition` の例では、空の (初期バージョンなし) Greengrass コア定義を作成します。コアを使用する前に、`create-core-definition-version` コマンドを使用してコアの他のパラメータを指定する必要があります。  

```
aws greengrass create-core-definition \
    --name cliGroup_Core
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/b5c08008-54cb-44bd-9eec-c121b04283b5",
    "CreationTimestamp": "2019-06-25T18:23:22.106Z",
    "Id": "b5c08008-54cb-44bd-9eec-c121b04283b5",
    "LastUpdatedTimestamp": "2019-06-25T18:23:22.106Z",
    "Name": "cliGroup_Core"
}
```
**例 2: 初期バージョンでコア定義を作成するには**  
次の `create-core-definition` の例では、初期コア定義バージョンを含むコアバージョンを作成します。バージョンに含めることができるのは 1 つのコアのみです。コアを作成する前に、まず対応する AWS IoT モノを作成してプロビジョニングする必要があります。このプロセスには、`create-core-definition` コマンドに必要な `ThingArn` と `CertificateArn` を返す次の `iot` コマンドが含まれます。  
コアデバイスに対応する AWS IoT モノを作成します。  

```
aws iot create-thing \
    --thing-name "MyCoreDevice"
```
出力:  

```
{
    "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyCoreDevice",
    "thingName": "MyCoreDevice",
    "thingId": "cb419a19-9099-4515-9cec-e9b0e760608a"
}
```
パブリックキーとプライベートキー、およびモノのコアデバイス証明書を作成します。この例では `create-keys-and-certificate` コマンドを使用し、現在のディレクトリへの書き込みアクセス許可を必要とします。または、 `create-certificate-from-csr` コマンドを使用できます。  

```
aws iot create-keys-and-certificate \
    --set-as-active \
    --certificate-pem-outfile "myCore.cert.pem" \
    --public-key-outfile "myCore.public.key" \
    --private-key-outfile "myCore.private.key"
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz",
    "certificatePem": "-----BEGIN CERTIFICATE-----\nMIIDWTCAkGgAwIBATgIUCgq6EGqou6zFqWgIZRndgQEFW+gwDQYJKoZIhvc...KdGewQS\n-----END CERTIFICATE-----\n",
    "keyPair": {
        "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBzrqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqKpRgnn6yq26U3y...wIDAQAB\n-----END PUBLIC KEY-----\n",
        "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIABAKCAQEAqKpRgnn6yq26U3yt5YFZquyukfRjbMXDcNOK4rMCxDR...fvY4+te\n-----END RSA PRIVATE KEY-----\n"
    },
    "certificateId": "123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz"
}
```
`iot` および `greengrass`アクションを許可する AWS IoT ポリシーを作成します。簡単にするために、次のポリシーではすべてのリソースに対するアクションが許可されていますが、ポリシーはより制限されている必要があります。  

```
aws iot create-policy \
    --policy-name "Core_Devices" \
    --policy-document "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}"
```
出力:  

```
{
    "policyName": "Core_Devices",
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/Core_Devices",
    "policyDocument": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}",
    "policyVersionId": "1"
}
```
ポリシーを証明書にアタッチします。  

```
aws iot attach-policy \
    --policy-name "Core_Devices" \
    --target "arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz"
```
このコマンドでは何も出力されません。  
モノを証明書にアタッチします。  

```
aws iot attach-thing-principal \
    --thing-name "MyCoreDevice" \
    --principal "arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz"
```
このコマンドでは何も出力されません。  
コア定義を作成します。  

```
aws greengrass create-core-definition \
    --name "MyCores" \
    --initial-version "{\"Cores\":[{\"Id\":\"MyCoreDevice\",\"ThingArn\":\"arn:aws:iot:us-west-2:123456789012:thing/MyCoreDevice\",\"CertificateArn\":\"arn:aws:iot:us-west-2:123456789012:cert/123a15ec415668c2349a76170b64ac0878231c1e21ec83c10e92a1EXAMPLExyz\",\"SyncShadow\":true}]}"
```
出力:  

```
{
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/582efe12-b05a-409e-9a24-a2ba1bcc4a12/versions/cc87b5b3-8f4b-465d-944c-1d6de5dbfcdb",
    "Name": "MyCores",
    "LastUpdatedTimestamp": "2019-09-18T00:11:06.197Z",
    "LatestVersion": "cc87b5b3-8f4b-465d-944c-1d6de5dbfcdb",
    "CreationTimestamp": "2019-09-18T00:11:06.197Z",
    "Id": "582efe12-b05a-409e-9a24-a2ba1bcc4a12",
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/582efe12-b05a-409e-9a24-a2ba1bcc4a12"
}
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「Configure theIoT Greengrass Core](https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-core.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCoreDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-core-definition.html)」を参照してください。

### `create-deployment`
<a name="greengrass_CreateDeployment_cli_2_topic"></a>

次のコード例は、`create-deployment` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループのバージョンのデプロイを作成するには**  
次の `create-deployment` の例では、Greengrass グループの指定されたバージョンをデプロイします。  

```
aws greengrass create-deployment \
    --deployment-type NewDeployment \
    --group-id "ce2e7d01-3240-4c24-b8e6-f6f6e7a9eeca" \
    --group-version-id "dc40c1e9-e8c8-4d28-a84d-a9cad5f599c9"
```
出力:  

```
{
    "DeploymentArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/ce2e7d01-3240-4c24-b8e6-f6f6e7a9eeca/deployments/bfceb608-4e97-45bc-af5c-460144270308",
    "DeploymentId": "bfceb608-4e97-45bc-af5c-460144270308"
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[コネクタの開始方法 (CLI)](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors-cli.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-deployment.html)」を参照してください。**

### `create-device-definition-version`
<a name="greengrass_CreateDeviceDefinitionVersion_cli_2_topic"></a>

次のコード例は、`create-device-definition-version` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義バージョンを作成するには**  
次の `create-device-definition-version` の例では、デバイス定義バージョンを作成し、指定したデバイス定義に関連付けます。バージョンは 2 つのデバイスを定義します。Greengrass デバイスを作成する前に、まず対応する AWS IoT モノを作成してプロビジョニングする必要があります。このプロセスには、Greengrass コマンドに必要な情報を取得するために実行する必要がある次の `iot` コマンドが含まれています。  
デバイスに対応する AWS IoT モノを作成します。  

```
aws iot create-thing \
    --thing-name "InteriorTherm"
```
出力:  

```
{
    "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/InteriorTherm",
    "thingName": "InteriorTherm",
    "thingId": "01d4763c-78a6-46c6-92be-7add080394bf"
}
```
パブリックキーとプライベートキー、およびモノのデバイス証明書を作成します。この例では `create-keys-and-certificate` コマンドを使用し、現在のディレクトリへの書き込みアクセス許可を必要とします。または、`create-certificate-from-csr` コマンドを使用できます。  

```
aws iot create-keys-and-certificate \
    --set-as-active \
    --certificate-pem-outfile "myDevice.cert.pem" \
    --public-key-outfile "myDevice.public.key" \
    --private-key-outfile "myDevice.private.key"
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92",
    "certificatePem": "-----BEGIN CERTIFICATE-----\nMIIDWTCAkGgAwIBATgIUCgq6EGqou6zFqWgIZRndgQEFW+gwDQYJKoZIhvc...KdGewQS\n-----END CERTIFICATE-----\n",
    "keyPair": {
        "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBzrqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqKpRgnn6yq26U3y...wIDAQAB\n-----END PUBLIC KEY-----\n",
        "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIABAKCAQEAqKpRgnn6yq26U3yt5YFZquyukfRjbMXDcNOK4rMCxDR...fvY4+te\n-----END RSA PRIVATE KEY-----\n"
    },
    "certificateId": "66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92"
}
```
`iot` および `greengrass`アクションを許可する AWS IoT ポリシーを作成します。簡単にするために、次のポリシーではすべてのリソースに対するアクションが許可されていますが、ポリシーはより制限的になる可能性があります。  

```
aws iot create-policy \
    --policy-name "GG_Devices" \
    --policy-document "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}"
```
出力:  

```
{
    "policyName": "GG_Devices",
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/GG_Devices",
    "policyDocument": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}",
    "policyVersionId": "1"
}
```
ポリシーを証明書にアタッチします。  

```
aws iot attach-policy \
    --policy-name "GG_Devices" \
    --target "arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92"
```
モノを証明書にアタッチします  

```
aws iot attach-thing-principal \
    --thing-name "InteriorTherm" \
    --principal "arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92"
```
上記のように IoT モノを作成して設定したら、次の例の最初の 2 つのコマンドから `ThingArn` と `CertificateArn` を使用します。  

```
aws greengrass create-device-definition-version \
    --device-definition-id "f9ba083d-5ad4-4534-9f86-026a45df1ccd" \
    --devices "[{\"Id\":\"InteriorTherm\",\"ThingArn\":\"arn:aws:iot:us-west-2:123456789012:thing/InteriorTherm\",\"CertificateArn\":\"arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92\",\"SyncShadow\":true},{\"Id\":\"ExteriorTherm\",\"ThingArn\":\"arn:aws:iot:us-west-2:123456789012:thing/ExteriorTherm\",\"CertificateArn\":\"arn:aws:iot:us-west-2:123456789012:cert/6c52ce1b47bde88a637e9ccdd45fe4e4c2c0a75a6866f8f63d980ee22fa51e02\",\"SyncShadow\":true}]"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd/versions/83c13984-6fed-447e-84d5-5b8aa45d5f71",
    "Version": "83c13984-6fed-447e-84d5-5b8aa45d5f71",
    "CreationTimestamp": "2019-09-11T00:15:09.838Z",
    "Id": "f9ba083d-5ad4-4534-9f86-026a45df1ccd"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDeviceDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-device-definition-version.html)」を参照してください。

### `create-device-definition`
<a name="greengrass_CreateDeviceDefinition_cli_2_topic"></a>

次のコード例は、`create-device-definition` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義を作成するには**  
次の `create-device-definition` の例では、初期デバイス定義バージョンを含むデバイス定義を作成します。初期バージョンでは、2 つのデバイスを定義します。Greengrass デバイスを作成する前に、まず対応する AWS IoT モノを作成してプロビジョニングする必要があります。このプロセスには、Greengrass コマンドに必要な情報を取得するために実行する必要がある次の `iot` コマンドが含まれています。  
デバイスに対応する AWS IoT モノを作成します。  

```
aws iot create-thing \
    --thing-name "InteriorTherm"
```
出力:  

```
{
    "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/InteriorTherm",
    "thingName": "InteriorTherm",
    "thingId": "01d4763c-78a6-46c6-92be-7add080394bf"
}
```
パブリックキーとプライベートキー、およびモノのデバイス証明書を作成します。この例では `create-keys-and-certificate` コマンドを使用し、現在のディレクトリへの書き込みアクセス許可を必要とします。または、`create-certificate-from-csr` コマンドを使用できます。  

```
aws iot create-keys-and-certificate \
    --set-as-active \
    --certificate-pem-outfile "myDevice.cert.pem" \
    --public-key-outfile "myDevice.public.key" \
    --private-key-outfile "myDevice.private.key"
```
出力:  

```
{
    "certificateArn": "arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92",
    "certificatePem": "-----BEGIN CERTIFICATE-----\nMIIDWTCAkGgAwIBATgIUCgq6EGqou6zFqWgIZRndgQEFW+gwDQYJKoZIhvc...KdGewQS\n-----END CERTIFICATE-----\n",
    "keyPair": {
        "PublicKey": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBzrqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqKpRgnn6yq26U3y...wIDAQAB\n-----END PUBLIC KEY-----\n",
        "PrivateKey": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIABAKCAQEAqKpRgnn6yq26U3yt5YFZquyukfRjbMXDcNOK4rMCxDR...fvY4+te\n-----END RSA PRIVATE KEY-----\n"
    },
    "certificateId": "66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92"
}
```
`iot` および `greengrass`アクションを許可する AWS IoT ポリシーを作成します。簡単にするために、次のポリシーではすべてのリソースに対するアクションが許可されていますが、ポリシーはより制限的になる可能性があります。  

```
aws iot create-policy \
    --policy-name "GG_Devices" \
    --policy-document "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}"
```
出力:  

```
{
    "policyName": "GG_Devices",
    "policyArn": "arn:aws:iot:us-west-2:123456789012:policy/GG_Devices",
    "policyDocument": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"iot:Publish\",\"iot:Subscribe\",\"iot:Connect\",\"iot:Receive\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"iot:GetThingShadow\",\"iot:UpdateThingShadow\",\"iot:DeleteThingShadow\"],\"Resource\":[\"*\"]},{\"Effect\":\"Allow\",\"Action\":[\"greengrass:*\"],\"Resource\":[\"*\"]}]}",
    "policyVersionId": "1"
}
```
ポリシーを証明書にアタッチします。  

```
aws iot attach-policy \
    --policy-name "GG_Devices" \
    --target "arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92"
```
モノを証明書にアタッチします  

```
aws iot attach-thing-principal \
    --thing-name "InteriorTherm" \
    --principal "arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92"
```
上記のように IoT モノを作成して設定したら、次の例の最初の 2 つのコマンドから `ThingArn` と `CertificateArn` を使用します。  

```
aws greengrass create-device-definition \
    --name "Sensors" \
    --initial-version "{\"Devices\":[{\"Id\":\"InteriorTherm\",\"ThingArn\":\"arn:aws:iot:us-west-2:123456789012:thing/InteriorTherm\",\"CertificateArn\":\"arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92\",\"SyncShadow\":true},{\"Id\":\"ExteriorTherm\",\"ThingArn\":\"arn:aws:iot:us-west-2:123456789012:thing/ExteriorTherm\",\"CertificateArn\":\"arn:aws:iot:us-west-2:123456789012:cert/6c52ce1b47bde88a637e9ccdd45fe4e4c2c0a75a6866f8f63d980ee22fa51e02\",\"SyncShadow\":true}]}"
```
出力:  

```
{
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd/versions/3b5cc510-58c1-44b5-9d98-4ad858ffa795",
    "Name": "Sensors",
    "LastUpdatedTimestamp": "2019-09-11T00:11:06.197Z",
    "LatestVersion": "3b5cc510-58c1-44b5-9d98-4ad858ffa795",
    "CreationTimestamp": "2019-09-11T00:11:06.197Z",
    "Id": "f9ba083d-5ad4-4534-9f86-026a45df1ccd",
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDeviceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-device-definition.html)」を参照してください。

### `create-function-definition-version`
<a name="greengrass_CreateFunctionDefinitionVersion_cli_2_topic"></a>

次のコード例は、`create-function-definition-version` を使用する方法を示しています。

**AWS CLI**  
**関数定義のバージョンを作成するには**  
次の `create-function-definition-version` の例では、指定された関数定義の新しいバージョンを作成します。このバージョンは、ID が `Hello-World-function` の単一の関数を指定し、ファイルシステムへのアクセスを許可し、最大メモリサイズとタイムアウト期間を指定します。  

```
aws greengrass create-function-definition-version \
    --cli-input-json "{\"FunctionDefinitionId\": \"e626e8c9-3b8f-4bf3-9cdc-d26ecdeb9fa3\",\"Functions\": [{\"Id\": \"Hello-World-function\", \"FunctionArn\": \""arn:aws:lambda:us-west-2:123456789012:function:Greengrass_HelloWorld_Counter:gghw-alias"\",\"FunctionConfiguration\": {\"Environment\": {\"AccessSysfs\": true},\"Executable\": \"greengrassHelloWorldCounter.function_handler\",\"MemorySize\": 16000,\"Pinned\": false,\"Timeout\": 25}}]}"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/e626e8c9-3b8f-4bf3-9cdc-d26ecdeb9fa3/versions/74abd1cc-637e-4abe-8684-9a67890f4043",
    "CreationTimestamp": "2019-06-25T22:03:43.376Z",
    "Id": "e626e8c9-3b8f-4bf3-9cdc-d26ecdeb9fa3",
    "Version": "74abd1cc-637e-4abe-8684-9a67890f4043"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFunctionDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-function-definition-version.html)」を参照してください。

### `create-function-definition`
<a name="greengrass_CreateFunctionDefinition_cli_2_topic"></a>

次のコード例は、`create-function-definition` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数定義を作成するには**  
次の `create-function-definition` の例では、Lambda 関数のリスト (この場合は、`TempMonitorFunction` という名前の 1 つの関数のみのリスト) とそれらの設定を指定して、Lambda 関数定義と初期バージョンを作成します。関数定義を作成する前に、Lambda 関数 ARN が必要です。関数とそのエイリアスを作成するには、Lambda の `create-function` コマンドと `publish-version` コマンドを使用します。Lambda の `create-function` コマンドには実行ロールの ARN が必要ですが、アクセス許可は Greengrass グループロールで指定されているため、 AWS IoT Greengrass はそのロールを使用しません。IAM `create-role` コマンドを使用して空のロールを作成し、Lambda の `create-function` で使用する ARN を取得するか、既存の実行ロールを使用できます。  

```
aws greengrass create-function-definition \
    --name MyGreengrassFunctions \
    --initial-version "{\"Functions\": [{\"Id\": \"TempMonitorFunction\", \"FunctionArn\": \"arn:aws:lambda:us-west-2:123456789012:function:TempMonitor:GG_TempMonitor\", \"FunctionConfiguration\": {\"Executable\": \"temp_monitor.function_handler\", \"MemorySize\": 16000,\"Timeout\": 5}}]}"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/3b0d0080-87e7-48c6-b182-503ec743a08b",
    "CreationTimestamp": "2019-06-19T22:24:44.585Z",
    "Id": "3b0d0080-87e7-48c6-b182-503ec743a08b",
    "LastUpdatedTimestamp": "2019-06-19T22:24:44.585Z",
    "LatestVersion": "67f918b9-efb4-40b0-b87c-de8c9faf085b",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/3b0d0080-87e7-48c6-b182-503ec743a08b/versions/67f918b9-efb4-40b0-b87c-de8c9faf085b",
    "Name": "MyGreengrassFunctions"
}
```
詳細については、*AWS 「 IoT Greengrass* [デベロッパーガイド」の AWS 「 コマンドラインインターフェイスを使用してローカルリソースアクセスを設定する方法](https://docs.aws.amazon.com/greengrass/latest/developerguide/lra-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFunctionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-function-definition.html)」を参照してください。

### `create-group-certificate-authority`
<a name="greengrass_CreateGroupCertificateAuthority_cli_2_topic"></a>

次のコード例は、`create-group-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**グループの認証局 (CA) を作成するには**  
次の `create-group-certificate-authority` の例では、指定されたグループの CA を作成またはローテーションします。  

```
aws greengrass create-group-certificate-authority \
    --group-id "8eaadd72-ce4b-4f15-892a-0cc4f3a343f1"
```
出力:  

```
{
    "GroupCertificateAuthorityArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/8eaadd72-ce4b-4f15-892a-0cc4f3a343f1/certificateauthorities/d31630d674c4437f6c5dbc0dca56312a902171ce2d086c38e509c8EXAMPLEcc5"
}
```
グループの詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[AWS IoT Greengrass セキュリティ](https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-sec.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroupCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-group-certificate-authority.html)」を参照してください。

### `create-group-version`
<a name="greengrass_CreateGroupVersion_cli_2_topic"></a>

次のコード例は、`create-group-version` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループのバージョンを作成するには**  
次の `create-group-version` の例では、グループバージョンを作成し、指定したグループに関連付けます。バージョンは、このグループバージョンに含めるエンティティを含むコア、リソース、コネクタ、関数、サブスクリプションバージョンを参照します。グループバージョンを作成する前に、これらのエンティティを作成する必要があります。  
初期バージョンでリソース定義を作成するには、`create-resource-definition` コマンドを使用します。初期バージョンでコネクタ定義を作成するには、`create-connector-definition` を使用します。初期バージョンで関数定義を作成するには、`create-function-definition` を使用します。初期バージョンでサブスクリプション定義を作成するには、`create-subscription-definition` を使用します。初期コア定義バージョンの ARN を取得するには、`get-group-version` コマンドを使用し、最新のグループバージョンの ID を指定します。  

```
aws greengrass create-group-version \
    --group-id "ce2e7d01-3240-4c24-b8e6-f6f6e7a9eeca" \
    --core-definition-version-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/6a630442-8708-4838-ad36-eb98849d975e/versions/6c87151b-1fb4-4cb2-8b31-6ee715d8f8ba" \
    --resource-definition-version-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/c8bb9ebc-c3fd-40a4-9c6a-568d75569d38/versions/a5f94d0b-f6bc-40f4-bb78-7a1c5fe13ba1" \
    --connector-definition-version-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/55d0052b-0d7d-44d6-b56f-21867215e118/versions/78a3331b-895d-489b-8823-17b4f9f418a0" \
    --function-definition-version-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/3b0d0080-87e7-48c6-b182-503ec743a08b/versions/67f918b9-efb4-40b0-b87c-de8c9faf085b" \
    --subscription-definition-version-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/9d611d57-5d5d-44bd-a3b4-feccbdd69112/versions/aa645c47-ac90-420d-9091-8c7ffa4f103f"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/ce2e7d01-3240-4c24-b8e6-f6f6e7a9eeca/versions/e10b0459-4345-4a09-88a4-1af1f5d34638",
    "CreationTimestamp": "2019-06-20T18:42:47.020Z",
    "Id": "ce2e7d01-3240-4c24-b8e6-f6f6e7a9eeca",
    "Version": "e10b0459-4345-4a09-88a4-1af1f5d34638"
}
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「IoT Greengrass グループオブジェクトモデルの概要](https://docs.aws.amazon.com/greengrass/latest/developerguide/deployments.html#api-overview)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroupVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-group-version.html)」を参照してください。

### `create-group`
<a name="greengrass_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**Greeengrass グループを作成するには**  
次の `create-group` の例では、`cli-created-group` という名前のグループが作成されます。  

```
aws greengrass create-group \
    --name cli-created-group
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/4e22bd92-898c-436b-ade5-434d883ff749",
    "CreationTimestamp": "2019-06-25T18:07:17.688Z",
    "Id": "4e22bd92-898c-436b-ade5-434d883ff749",
    "LastUpdatedTimestamp": "2019-06-25T18:07:17.688Z",
    "Name": "cli-created-group"
}
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「IoT Greengrass グループオブジェクトモデルの概要](https://docs.aws.amazon.com/greengrass/latest/developerguide/deployments.html#api-overview)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-group.html)」を参照してください。

### `create-logger-definition-version`
<a name="greengrass_CreateLoggerDefinitionVersion_cli_2_topic"></a>

次のコード例は、`create-logger-definition-version` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義バージョンを作成するには**  
次の `create-logger-definition-version` の例では、ロガー定義バージョンを作成し、ロガー定義に関連付けます。バージョンは、1) コアデバイスのファイルシステム上のシステムコンポーネントログ、2) コアデバイスのファイルシステム上のユーザー定義 Lambda 関数ログ、3) Amazon CloudWatch Logs 内のシステムコンポーネントログ、および 4) Amazon CloudWatch Logs 内のユーザー定義 Lambda 関数ログの 4 つのログ記録設定を定義します。注: CloudWatch Logs 統合の場合、グループロールは適切なアクセス許可を付与する必要があります。  

```
aws greengrass create-logger-definition-version \
    --logger-definition-id "a454b62a-5d56-4ca9-bdc4-8254e1662cb0" \
    --loggers "[{\"Id\":\"1\",\"Component\":\"GreengrassSystem\",\"Level\":\"ERROR\",\"Space\":10240,\"Type\":\"FileSystem\"},{\"Id\":\"2\",\"Component\":\"Lambda\",\"Level\":\"INFO\",\"Space\":10240,\"Type\":\"FileSystem\"},{\"Id\":\"3\",\"Component\":\"GreengrassSystem\",\"Level\":\"WARN\",\"Type\":\"AWSCloudWatch\"},{\"Id\":\"4\",\"Component\":\"Lambda\",\"Level\":\"INFO\",\"Type\":\"AWSCloudWatch\"}]"
```
出力:  

```
{
 "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/a454b62a-5d56-4ca9-bdc4-8254e1662cb0/versions/49aedb1e-01a3-4d39-9871-3a052573f1ea",
 "Version": "49aedb1e-01a3-4d39-9871-3a052573f1ea",
 "CreationTimestamp": "2019-07-24T00:04:48.523Z",
 "Id": "a454b62a-5d56-4ca9-bdc4-8254e1662cb0"
}
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「IoT Greengrass Logs を使用したモニタリング](https://docs.aws.amazon.com/greengrass/latest/developerguide/greengrass-logs-overview.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLoggerDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-logger-definition-version.html)」を参照してください。

### `create-logger-definition`
<a name="greengrass_CreateLoggerDefinition_cli_2_topic"></a>

次のコード例は、`create-logger-definition` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義を作成するには**  
次の `create-logger-definition` の例では、初期ロガー定義バージョンを含むロガー定義を作成します。初期バージョンは、1) コアデバイスのファイルシステム上のシステムコンポーネントログ、2) コアデバイスのファイルシステム上のユーザー定義の Lambda 関数ログ、および 3) Amazon CloudWatch Logs のユーザー定義の Lambda 関数ログの 3 つのログ記録設定を定義します。注: CloudWatch Logs 統合の場合、グループロールは適切なアクセス許可を付与する必要があります。  

```
aws greengrass create-logger-definition \
    --name "LoggingConfigs" \
    --initial-version "{\"Loggers\":[{\"Id\":\"1\",\"Component\":\"GreengrassSystem\",\"Level\":\"ERROR\",\"Space\":10240,\"Type\":\"FileSystem\"},{\"Id\":\"2\",\"Component\":\"Lambda\",\"Level\":\"INFO\",\"Space\":10240,\"Type\":\"FileSystem\"},{\"Id\":\"3\",\"Component\":\"Lambda\",\"Level\":\"INFO\",\"Type\":\"AWSCloudWatch\"}]}"
```
出力:  

```
{
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/a454b62a-5d56-4ca9-bdc4-8254e1662cb0/versions/de1d9854-1588-4525-b25e-b378f60f2322",
    "Name": "LoggingConfigs",
    "LastUpdatedTimestamp": "2019-07-23T23:52:17.165Z",
    "LatestVersion": "de1d9854-1588-4525-b25e-b378f60f2322",
    "CreationTimestamp": "2019-07-23T23:52:17.165Z",
    "Id": "a454b62a-5d56-4ca9-bdc4-8254e1662cb0",
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/a454b62a-5d56-4ca9-bdc4-8254e1662cb0"
}
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「IoT Greengrass Logs を使用したモニタリング](https://docs.aws.amazon.com/greengrass/latest/developerguide/greengrass-logs-overview.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLoggerDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-logger-definition.html)」を参照してください。

### `create-resource-definition-version`
<a name="greengrass_CreateResourceDefinitionVersion_cli_2_topic"></a>

次のコード例は、`create-resource-definition-version` を使用する方法を示しています。

**AWS CLI**  
**リソース定義のバージョンを作成するには**  
次の `create-resource-definition-version` の例では、TwilioAuthToken の新しいバージョンを作成します。  

```
aws greengrass create-resource-definition-version \
    --resource-definition-id "c8bb9ebc-c3fd-40a4-9c6a-568d75569d38" \
    --resources "[{\"Id\": \"TwilioAuthToken\",\"Name\": \"MyTwilioAuthToken\",\"ResourceDataContainer\": {\"SecretsManagerSecretResourceData\": {\"ARN\": \"arn:aws:secretsmanager:us-west-2:123456789012:secret:greengrass-TwilioAuthToken-ntSlp6\"}}}]"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/c8bb9ebc-c3fd-40a4-9c6a-568d75569d38/versions/b3bcada0-5fb6-42df-bf0b-1ee4f15e769e",
    "CreationTimestamp": "2019-06-24T21:17:25.623Z",
    "Id": "c8bb9ebc-c3fd-40a4-9c6a-568d75569d38",
    "Version": "b3bcada0-5fb6-42df-bf0b-1ee4f15e769e"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResourceDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-resource-definition-version.html)」を参照してください。

### `create-resource-definition`
<a name="greengrass_CreateResourceDefinition_cli_2_topic"></a>

次のコード例は、`create-resource-definition` を使用する方法を示しています。

**AWS CLI**  
**リソース定義を作成するには**  
次の `create-resource-definition` の例では、Greengrass グループで使用するリソースのリストを含むリソース定義を作成します。この例では、リソースのリストを提供することで、リソース定義の初期バージョンが含まれます。このリストには、Twilio 認可トークン用の 1 つのリソースと、 AWS Secrets Manager に保存されているシークレット用の ARN が含まれています。リソース定義を作成する前に、シークレットを作成する必要があります。  

```
aws greengrass create-resource-definition \
    --name MyGreengrassResources \
    --initial-version "{\"Resources\": [{\"Id\": \"TwilioAuthToken\",\"Name\": \"MyTwilioAuthToken\",\"ResourceDataContainer\": {\"SecretsManagerSecretResourceData\": {\"ARN\": \"arn:aws:secretsmanager:us-west-2:123456789012:secret:greengrass-TwilioAuthToken-ntSlp6\"}}}]}"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/c8bb9ebc-c3fd-40a4-9c6a-568d75569d38",
    "CreationTimestamp": "2019-06-19T21:51:28.212Z",
    "Id": "c8bb9ebc-c3fd-40a4-9c6a-568d75569d38",
    "LastUpdatedTimestamp": "2019-06-19T21:51:28.212Z",
    "LatestVersion": "a5f94d0b-f6bc-40f4-bb78-7a1c5fe13ba1",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/c8bb9ebc-c3fd-40a4-9c6a-568d75569d38/versions/a5f94d0b-f6bc-40f4-bb78-7a1c5fe13ba1",
    "Name": "MyGreengrassResources"
}
```
詳細については、*AWS 「 IoT Greengrass* [デベロッパーガイド」の AWS 「 コマンドラインインターフェイスを使用してローカルリソースアクセスを設定する方法](https://docs.aws.amazon.com/greengrass/latest/developerguide/lra-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResourceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-resource-definition.html)」を参照してください。

### `create-software-update-job`
<a name="greengrass_CreateSoftwareUpdateJob_cli_2_topic"></a>

次のコード例は、`create-software-update-job` を使用する方法を示しています。

**AWS CLI**  
**コアのソフトウェア更新ジョブを作成するには**  
次の`create-software-update-job`例では、over-the-air (OTA) 更新ジョブを作成して、名前が のコアで AWS IoT Greengrass Core ソフトウェアを更新します`MyFirstGroup_Core`。このコマンドには、Amazon S3 のソフトウェア更新パッケージへのアクセスを許可し、信頼できるエンティティとして `iot.amazonaws.com` を含む IAM ロールが必要です。  

```
aws greengrass create-software-update-job \
    --update-targets-architecture armv7l \
    --update-targets [\"arn:aws:iot:us-west-2:123456789012:thing/MyFirstGroup_Core\"] \
    --update-targets-operating-system raspbian \
    --software-to-update core \
    --s3-url-signer-role arn:aws:iam::123456789012:role/OTA_signer_role \
    --update-agent-log-level WARN
```
出力:  

```
{
    "IotJobId": "GreengrassUpdateJob_30b353e3-3af7-4786-be25-4c446663c09e",
    "IotJobArn": "arn:aws:iot:us-west-2:123456789012:job/GreengrassUpdateJob_30b353e3-3af7-4786-be25-4c446663c09e",
    "PlatformSoftwareVersion": "1.9.3"
}
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「IoT Greengrass Core ソフトウェアの OTA 更新](https://docs.aws.amazon.com/greengrass/latest/developerguide/core-ota-update.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSoftwareUpdateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-software-update-job.html)」を参照してください。

### `create-subscription-definition-version`
<a name="greengrass_CreateSubscriptionDefinitionVersion_cli_2_topic"></a>

次のコード例は、`create-subscription-definition-version` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプションの定義の新しいバージョンを作成するには**  
次の `create-subscription-definition-version` の例では、トリガー通知、温度入力、出力ステータスの 3 つのサブスクリプションを含むサブスクリプション定義の新しいバージョンを作成します。  

```
aws greengrass create-subscription-definition-version \
    --subscription-definition-id "9d611d57-5d5d-44bd-a3b4-feccbdd69112" \
    --subscriptions "[{\"Id\": \"TriggerNotification\", \"Source\": \"arn:aws:lambda:us-west-2:123456789012:function:TempMonitor:GG_TempMonitor\", \"Subject\": \"twilio/txt\", \"Target\": \"arn:aws:greengrass:us-west-2::/connectors/TwilioNotifications/versions/1\"},{\"Id\": \"TemperatureInput\", \"Source\": \"cloud\", \"Subject\": \"temperature/input\", \"Target\": \"arn:aws:lambda:us-west-2:123456789012:function:TempMonitor:GG_TempMonitor\"},{\"Id\": \"OutputStatus\", \"Source\": \"arn:aws:greengrass:us-west-2::/connectors/TwilioNotifications/versions/1\", \"Subject\": \"twilio/message/status\", \"Target\": \"cloud\"}]"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/9d611d57-5d5d-44bd-a3b4-feccbdd69112/versions/7b65dfae-50b6-4d0f-b3e0-27728bfb0620",
    "CreationTimestamp": "2019-06-24T21:21:33.837Z",
    "Id": "9d611d57-5d5d-44bd-a3b4-feccbdd69112",
    "Version": "7b65dfae-50b6-4d0f-b3e0-27728bfb0620"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubscriptionDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-subscription-definition-version.html)」を参照してください。

### `create-subscription-definition`
<a name="greengrass_CreateSubscriptionDefinition_cli_2_topic"></a>

次のコード例は、`create-subscription-definition` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション定義を作成するには**  
次の `create-subscription-definition` の例では、サブスクリプション定義を作成し、その初期バージョンを指定します。最初のバージョンには 3 つのサブスクリプションが含まれています。1 つはコネクタがサブスクライブする MQTT トピック用、もう 1 つは関数が AWS IoT から温度測定値を受信できるようにするサブスクリプション、もう 1 つは AWS IoT がコネクタからステータス情報を受信できるようにするサブスクリプションです。この例では、Lambda の `create-alias` コマンドを使用して以前に作成された Lambda 関数エイリアスの ARN を示します。  

```
aws greengrass create-subscription-definition \
    --initial-version "{\"Subscriptions\": [{\"Id\": \"TriggerNotification\", \"Source\": \"arn:aws:lambda:us-west-2:123456789012:function:TempMonitor:GG_TempMonitor\", \"Subject\": \"twilio/txt\", \"Target\": \"arn:aws:greengrass:us-west-2::/connectors/TwilioNotifications/versions/1\"},{\"Id\": \"TemperatureInput\", \"Source\": \"cloud\", \"Subject\": \"temperature/input\", \"Target\": \"arn:aws:lambda:us-west-2:123456789012:function:TempMonitor:GG_TempMonitor\"},{\"Id\": \"OutputStatus\", \"Source\": \"arn:aws:greengrass:us-west-2::/connectors/TwilioNotifications/versions/1\", \"Subject\": \"twilio/message/status\", \"Target\": \"cloud\"}]}"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/9d611d57-5d5d-44bd-a3b4-feccbdd69112",
    "CreationTimestamp": "2019-06-19T22:34:26.677Z",
    "Id": "9d611d57-5d5d-44bd-a3b4-feccbdd69112",
    "LastUpdatedTimestamp": "2019-06-19T22:34:26.677Z",
    "LatestVersion": "aa645c47-ac90-420d-9091-8c7ffa4f103f",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/9d611d57-5d5d-44bd-a3b4-feccbdd69112/versions/aa645c47-ac90-420d-9091-8c7ffa4f103f"
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[コネクタの開始方法 (CLI)](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubscriptionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/create-subscription-definition.html)」を参照してください。

### `delete-connector-definition`
<a name="greengrass_DeleteConnectorDefinition_cli_2_topic"></a>

次のコード例は、`delete-connector-definition` を使用する方法を示しています。

**AWS CLI**  
**コネクタ定義を削除するには**  
次の `delete-connector-definition` の例では、指定された Greengrass コネクタ定義を削除します。グループが使用するコネクタ定義を削除すると、そのグループは正常にデプロイされません。  

```
aws greengrass delete-connector-definition \
    --connector-definition-id "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConnectorDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-connector-definition.html)」を参照してください。

### `delete-core-definition`
<a name="greengrass_DeleteCoreDefinition_cli_2_topic"></a>

次のコード例は、`delete-core-definition` を使用する方法を示しています。

**AWS CLI**  
**コア定義を削除するには**  
次の `delete-core-definition` の例では、すべてのバージョンを含む、指定された Greengrass コア定義を削除します。Greengrass グループに関連付けられているコアを削除すると、そのグループは正常にデプロイされません。  

```
aws greengrass delete-core-definition \
    --core-definition-id "ff36cc5f-9f98-4994-b468-9d9b6dc52abd"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCoreDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-core-definition.html)」を参照してください。

### `delete-device-definition`
<a name="greengrass_DeleteDeviceDefinition_cli_2_topic"></a>

次のコード例は、`delete-device-definition` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義を削除するには**  
次の `delete-device-definition` の例では、すべてのバージョンを含む、指定されたデバイス定義を削除します。グループバージョンで使用されるデバイス定義バージョンを削除すると、グループバージョンが正常にデプロイされません。  

```
aws greengrass delete-device-definition \
    --device-definition-id "f9ba083d-5ad4-4534-9f86-026a45df1ccd"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDeviceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-device-definition.html)」を参照してください。

### `delete-function-definition`
<a name="greengrass_DeleteFunctionDefinition_cli_2_topic"></a>

次のコード例は、`delete-function-definition` を使用する方法を示しています。

**AWS CLI**  
**関数定義を削除するには**  
次の `delete-function-definition` の例では、指定された Greengrass 関数定義を削除します。グループが使用する関数定義を削除すると、そのグループは正常にデプロイされません。  

```
aws greengrass delete-function-definition \
    --function-definition-id "fd4b906a-dff3-4c1b-96eb-52ebfcfac06a"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFunctionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-function-definition.html)」を参照してください。

### `delete-group`
<a name="greengrass_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**グループを削除するには**  
次の `delete-group` の例は、指定された Greengrass グループを削除します。  

```
aws greengrass delete-group \
    --group-id "4e22bd92-898c-436b-ade5-434d883ff749"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-group.html)」を参照してください。

### `delete-logger-definition`
<a name="greengrass_DeleteLoggerDefinition_cli_2_topic"></a>

次のコード例は、`delete-logger-definition` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義を削除するには**  
次の `delete-logger-definition` の例では、すべてのロガー定義バージョンを含む、指定されたロガー定義を削除します。グループバージョンで使用されるロガー定義バージョンを削除すると、グループバージョンは正常にデプロイされません。  

```
aws greengrass delete-logger-definition \
    --logger-definition-id "a454b62a-5d56-4ca9-bdc4-8254e1662cb0"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「IoT Greengrass Logs を使用したモニタリング](https://docs.aws.amazon.com/greengrass/latest/developerguide/greengrass-logs-overview.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLoggerDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-logger-definition.html)」を参照してください。

### `delete-resource-definition`
<a name="greengrass_DeleteResourceDefinition_cli_2_topic"></a>

次のコード例は、`delete-resource-definition` を使用する方法を示しています。

**AWS CLI**  
**リソース定義を削除するには**  
次の `delete-resource-definition` の例では、すべてのリソースバージョンを含む、指定されたリソース定義を削除します。グループが使用するリソース定義を削除すると、そのグループは正常にデプロイされません。  

```
aws greengrass delete-resource-definition \
    --resource-definition-id "ad8c101d-8109-4b0e-b97d-9cc5802ab658"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-resource-definition.html)」を参照してください。

### `delete-subscription-definition`
<a name="greengrass_DeleteSubscriptionDefinition_cli_2_topic"></a>

次のコード例は、`delete-subscription-definition` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション定義を削除するには**  
次の `delete-subscription-definition` の例では、指定された Greengrass サブスクリプション定義を削除します。グループで使用されているサブスクリプションを削除すると、そのグループは正常にデプロイされません。  

```
aws greengrass delete-subscription-definition \
    --subscription-definition-id "cd6f1c37-d9a4-4e90-be94-01a7404f5967"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubscriptionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/delete-subscription-definition.html)」を参照してください。

### `disassociate-role-from-group`
<a name="greengrass_DisassociateRoleFromGroup_cli_2_topic"></a>

次のコード例は、`disassociate-role-from-group` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループからロールの関連付けを解除するには**  
次の `disassociate-role-from-group` の例では、指定された Greengrass グループから IAM ロールの関連付けを解除します。  

```
aws greengrass disassociate-role-from-group \
    --group-id 2494ee3f-7f8a-4e92-a78b-d205f808b84b
```
出力:  

```
{
    "DisassociatedAt": "2019-09-10T20:05:49Z"
}
```
グループの詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループロールを設定する](https://docs.aws.amazon.com/greengrass/latest/developerguide/config-iam-roles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateRoleFromGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/disassociate-role-from-group.html)」を参照してください。

### `disassociate-service-role-from-account`
<a name="greengrass_DisassociateServiceRoleFromAccount_cli_2_topic"></a>

次の例は、`disassociate-service-role-from-account` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントからサービスロールの関連付けを解除するには**  
次の の`disassociate-service-role-from-account`例では、 AWS アカウントに関連付けられているサービスロールを削除します。どの AWS リージョンでもサービスロールを使用していない場合は、 `delete-role-policy` コマンドを使用してロールから`AWSGreengrassResourceAccessRolePolicy`管理ポリシーをデタッチし、 `delete-role` コマンドを使用してロールを削除します。  

```
aws greengrass disassociate-service-role-from-account
```
出力:  

```
{
    "DisassociatedAt": "2019-06-25T22:12:55Z"
}
```
詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass サービスロール](https://docs.aws.amazon.com/greengrass/latest/developerguide/service-role.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateServiceRoleFromAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/disassociate-service-role-from-account.html)」を参照してください。

### `get-associated-role`
<a name="greengrass_GetAssociatedRole_cli_2_topic"></a>

次のコード例は、`get-associated-role` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループに関連付けられたロールを取得するには**  
次の `get-associated-role` の例では、指定された Greengrass グループに関連付けられている IAM ロールを取得します。グループロールは、ローカルの Lambda 関数とコネクタが AWS サービスにアクセスするために使用します。  

```
aws greengrass get-associated-role \
    --group-id 2494ee3f-7f8a-4e92-a78b-d205f808b84b
```
出力:  

```
{
    "RoleArn": "arn:aws:iam::123456789012:role/GG-Group-Role",
    "AssociatedAt": "2019-09-10T20:03:30Z"
}
```
グループの詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループロールを設定する](https://docs.aws.amazon.com/greengrass/latest/developerguide/config-iam-roles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAssociatedRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-associated-role.html)」を参照してください。

### `get-bulk-deployment-status`
<a name="greengrass_GetBulkDeploymentStatus_cli_2_topic"></a>

次のコード例は、`get-bulk-deployment-status` を使用する方法を示しています。

**AWS CLI**  
**一括デプロイのステータスを確認するには**  
次の `get-bulk-deployment-status` の例では、指定された一括デプロイオペレーションのステータス情報を取得します。この例では、デプロイするグループを指定したファイルの入力レコードが無効です。  

```
aws greengrass get-bulk-deployment-status \
    --bulk-deployment-id "870fb41b-6288-4e0c-bc76-a7ba4b4d3267"
```
出力:  

```
{
    "BulkDeploymentMetrics": {
        "InvalidInputRecords": 1,
        "RecordsProcessed": 1,
        "RetryAttempts": 0
    },
    "BulkDeploymentStatus": "Completed",
    "CreatedAt": "2019-06-25T16:11:33.265Z",
    "tags": {}
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループの一括デプロイを作成する](https://docs.aws.amazon.com/greengrass/latest/developerguide/bulk-deploy-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBulkDeploymentStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-bulk-deployment-status.html)」を参照してください。

### `get-connectivity-info`
<a name="greengrass_GetConnectivityInfo_cli_2_topic"></a>

次のコード例は、`get-connectivity-info` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コアの接続情報を取得するには**  
次の `get-connectivity-info` の例は、デバイスが指定された Greengrass コアへの接続に使用できるエンドポイントを示しています。接続情報は、IP アドレスまたはドメイン名のリストで、対応するポート番号とオプションのカスタマー定義メタデータが含まれます。  

```
aws greengrass get-connectivity-info \
    --thing-name "MyGroup_Core"
```
出力:  

```
{
    "ConnectivityInfo": [
        {
            "Metadata": "",
            "PortNumber": 8883,
            "HostAddress": "127.0.0.1",
            "Id": "AUTOIP_127.0.0.1_0"
        },
        {
            "Metadata": "",
            "PortNumber": 8883,
            "HostAddress": "192.168.1.3",
            "Id": "AUTOIP_192.168.1.3_1"
        },
        {
            "Metadata": "",
            "PortNumber": 8883,
            "HostAddress": "::1",
            "Id": "AUTOIP_::1_2"
        },
        {
            "Metadata": "",
            "PortNumber": 8883,
            "HostAddress": "fe80::1e69:ed93:f5b:f6d",
            "Id": "AUTOIP_fe80::1e69:ed93:f5b:f6d_3"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnectivityInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-connectivity-info.html)」を参照してください。

### `get-connector-definition-version`
<a name="greengrass_GetConnectorDefinitionVersion_cli_2_topic"></a>

次の例は、`get-connector-definition-version` を使用する方法を説明しています。

**AWS CLI**  
**コネクタ定義の特定のバージョンに関する情報を取得するには**  
次の `get-connector-definition-version` の例では、指定されたコネクタ定義の指定されたバージョンに関する情報を取得します。コネクタ定義のすべてのバージョンの ID を取得するには、`list-connector-definition-versions` コマンドを使用します。コネクタ定義に追加された最新バージョンの ID を取得するには、`get-connector-definition` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-connector-definition-version \
    --connector-definition-id "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8" \
    --connector-definition-version-id "63c57963-c7c2-4a26-a7e2-7bf478ea2623"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8/versions/63c57963-c7c2-4a26-a7e2-7bf478ea2623",
    "CreationTimestamp": "2019-06-19T19:30:01.300Z",
    "Definition": {
        "Connectors": [
            {
                "ConnectorArn": "arn:aws:greengrass:us-west-2::/connectors/SNS/versions/1",
                "Id": "MySNSConnector",
                "Parameters": {
                    "DefaultSNSArn": "arn:aws:sns:us-west-2:123456789012:GGConnectorTopic"
                }
            }
        ]
    },
    "Id": "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
    "Version": "63c57963-c7c2-4a26-a7e2-7bf478ea2623"
}
```
詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass コネクタを使用したサービスおよびプロトコルとの統合](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnectorDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-connector-definition-version.html)」を参照してください。

### `get-connector-definition`
<a name="greengrass_GetConnectorDefinition_cli_2_topic"></a>

次のコード例は、`get-connector-definition` を使用する方法を示しています。

**AWS CLI**  
**コネクタ定義に関する情報を取得するには**  
次の `get-connector-definition` の例では、指定されたコネクタ定義に関する情報を取得します。コネクタ定義の ID を取得するには、`list-connector-definitions` コマンドを使用します。  

```
aws greengrass get-connector-definition \
    --connector-definition-id "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
    "CreationTimestamp": "2019-06-19T19:30:01.300Z",
    "Id": "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
    "LastUpdatedTimestamp": "2019-06-19T19:30:01.300Z",
    "LatestVersion": "63c57963-c7c2-4a26-a7e2-7bf478ea2623",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8/versions/63c57963-c7c2-4a26-a7e2-7bf478ea2623",
    "Name": "MySNSConnector",
    "tags": {}
}
```
詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass コネクタを使用したサービスおよびプロトコルとの統合](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnectorDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-connector-definition.html)」を参照してください。

### `get-core-definition-version`
<a name="greengrass_GetCoreDefinitionVersion_cli_2_topic"></a>

次のコード例は、`get-core-definition-version` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コア定義の特定のバージョンに関する詳細を取得するには**  
次の `get-core-definition-version` の例では、指定されたコア定義の指定されたバージョンに関する情報を取得します。コア定義のすべてのバージョンの ID を取得するには、`list-core-definition-versions` コマンドを使用します。コア定義に追加された最後のバージョンの ID を取得するには、`get-core-definition` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-core-definition-version \
    --core-definition-id "c906ed39-a1e3-4822-a981-7b9bd57b4b46"  \
    --core-definition-version-id "42aeeac3-fd9d-4312-a8fd-ffa9404a20e0"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/c906ed39-a1e3-4822-a981-7b9bd57b4b46/versions/42aeeac3-fd9d-4312-a8fd-ffa9404a20e0",
    "CreationTimestamp": "2019-06-18T16:21:21.351Z",
    "Definition": {
        "Cores": [
            {
                "CertificateArn": "arn:aws:iot:us-west-2:123456789012:cert/928dea7b82331b47c3ff77b0e763fc5e64e2f7c884e6ef391baed9b6b8e21b45",
                "Id": "1a39aac7-0885-4417-91f6-23e4cea6c511",
                "SyncShadow": false,
                "ThingArn": "arn:aws:iot:us-west-2:123456789012:thing/GGGroup4Pi3_Core"
            }
        ]
    },
    "Id": "c906ed39-a1e3-4822-a981-7b9bd57b4b46",
    "Version": "42aeeac3-fd9d-4312-a8fd-ffa9404a20e0"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCoreDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-core-definition-version.html)」を参照してください。

### `get-core-definition`
<a name="greengrass_GetCoreDefinition_cli_2_topic"></a>

次のコード例は、`get-core-definition` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コア定義の詳細を取得するには**  
次の `get-core-definition` の例は、指定されたコア定義に関する情報を取得します。コア定義の ID を取得するには、`list-core-definitions` コマンドを使用します。  

```
aws greengrass get-core-definition \
    --core-definition-id "c906ed39-a1e3-4822-a981-7b9bd57b4b46"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/237d6916-27cf-457f-ba0c-e86cfb5d25cd",
    "CreationTimestamp": "2018-10-18T04:47:06.721Z",
    "Id": "237d6916-27cf-457f-ba0c-e86cfb5d25cd",
    "LastUpdatedTimestamp": "2018-10-18T04:47:06.721Z",
    "LatestVersion": "bd2cd6d4-2bc5-468a-8962-39e071e34b68",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/237d6916-27cf-457f-ba0c-e86cfb5d25cd/versions/bd2cd6d4-2bc5-468a-8962-39e071e34b68",
    "tags": {}
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCoreDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-core-definition.html)」を参照してください。

### `get-deployment-status`
<a name="greengrass_GetDeploymentStatus_cli_2_topic"></a>

次のコード例は、`get-deployment-status` を使用する方法を示しています。

**AWS CLI**  
**デプロイのステータスを取得するには**  
次の `get-deployment-status` の例では、指定された Greengrass グループの指定されたデプロイのステータスを取得します。デプロイ ID を取得するには、`list-deployments` コマンドを使用してグループ ID を指定します。  

```
aws greengrass get-deployment-status \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731" \
    --deployment-id "1065b8a0-812b-4f21-9d5d-e89b232a530f"
```
出力:  

```
{
    "DeploymentStatus": "Success",
    "DeploymentType": "NewDeployment",
    "UpdatedAt": "2019-06-18T17:04:44.761Z"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeploymentStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-deployment-status.html)」を参照してください。

### `get-device-definition-version`
<a name="greengrass_GetDeviceDefinitionVersion_cli_2_topic"></a>

次のコード例は、`get-device-definition-version` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義バージョンを取得するには**  
次の `get-device-definition-version` 例では、指定されたデバイス定義の指定されたバージョンに関する情報を取得します。デバイス定義のすべてのバージョンの ID を取得するには、 `list-device-definition-versions` コマンドを使用します。デバイス定義に追加された最新バージョンの ID を取得するには、`get-device-definition` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-device-definition-version \
    --device-definition-id "f9ba083d-5ad4-4534-9f86-026a45df1ccd" \
    --device-definition-version-id "83c13984-6fed-447e-84d5-5b8aa45d5f71"
```
出力:  

```
{
    "Definition": {
        "Devices": [
            {
                "CertificateArn": "arn:aws:iot:us-west-2:123456789012:cert/6c52ce1b47bde88a637e9ccdd45fe4e4c2c0a75a6866f8f63d980ee22fa51e02",
                "ThingArn": "arn:aws:iot:us-west-2:123456789012:thing/ExteriorTherm",
                "SyncShadow": true,
                "Id": "ExteriorTherm"
            },
            {
                "CertificateArn": "arn:aws:iot:us-west-2:123456789012:cert/66a415ec415668c2349a76170b64ac0878231c1e21ec83c10e92a18bd568eb92",
                "ThingArn": "arn:aws:iot:us-west-2:123456789012:thing/InteriorTherm",
                "SyncShadow": true,
                "Id": "InteriorTherm"
            }
        ]
    },
    "Version": "83c13984-6fed-447e-84d5-5b8aa45d5f71",
    "CreationTimestamp": "2019-09-11T00:15:09.838Z",
    "Id": "f9ba083d-5ad4-4534-9f86-026a45df1ccd",
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd/versions/83c13984-6fed-447e-84d5-5b8aa45d5f71"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeviceDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-device-definition-version.html)」を参照してください。

### `get-device-definition`
<a name="greengrass_GetDeviceDefinition_cli_2_topic"></a>

次のコード例は、`get-device-definition` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義を取得するには**  
次の `get-device-definition` の例は、指定されたデバイス定義に関する情報を取得します。デバイス定義の ID を取得するには、`list-device-definitions` コマンドを使用します。  

```
aws greengrass get-device-definition \
    --device-definition-id "f9ba083d-5ad4-4534-9f86-026a45df1ccd"
```
出力:  

```
{
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd/versions/83c13984-6fed-447e-84d5-5b8aa45d5f71",
    "Name": "TemperatureSensors",
    "tags": {},
    "LastUpdatedTimestamp": "2019-09-11T00:19:03.698Z",
    "LatestVersion": "83c13984-6fed-447e-84d5-5b8aa45d5f71",
    "CreationTimestamp": "2019-09-11T00:11:06.197Z",
    "Id": "f9ba083d-5ad4-4534-9f86-026a45df1ccd",
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeviceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-device-definition.html)」を参照してください。

### `get-function-definition-version`
<a name="greengrass_GetFunctionDefinitionVersion_cli_2_topic"></a>

次のコード例は、`get-function-definition-version` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数の特定のバージョンに関する詳細を取得するには**  
次の `get-function-definition-version` は、指定された関数定義の指定されたバージョンに関する情報を取得します。関数定義のすべてのバージョンの ID を取得するには、`list-function-definition-versions` コマンドを使用します。関数定義に追加された最新バージョンの ID を取得するには、`get-function-definition` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-function-definition-version \
    --function-definition-id "063f5d1a-1dd1-40b4-9b51-56f8993d0f85" \
    --function-definition-version-id "9748fda7-1589-4fcc-ac94-f5559e88678b"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/9748fda7-1589-4fcc-ac94-f5559e88678b",
    "CreationTimestamp": "2019-06-18T17:04:30.776Z",
    "Definition": {
        "Functions": [
            {
                "FunctionArn": "arn:aws:lambda:::function:GGIPDetector:1",
                "FunctionConfiguration": {
                    "Environment": {},
                    "MemorySize": 32768,
                    "Pinned": true,
                    "Timeout": 3
                },
                "Id": "26b69bdb-e547-46bc-9812-84ec04b6cc8c"
            },
            {
                "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:Greengrass_HelloWorld:GG_HelloWorld",
                "FunctionConfiguration": {
                    "EncodingType": "json",
                    "Environment": {
                        "Variables": {}
                    },
                    "MemorySize": 16384,
                    "Pinned": true,
                    "Timeout": 25
                },
                "Id": "384465a8-eedf-48c6-b793-4c35f7bfae9b"
            }
        ]
    },
    "Id": "063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
    "Version": "9748fda7-1589-4fcc-ac94-f5559e88678b"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFunctionDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-function-definition-version.html)」を参照してください。

### `get-function-definition`
<a name="greengrass_GetFunctionDefinition_cli_2_topic"></a>

次のコード例は、`get-function-definition` を使用する方法を示しています。

**AWS CLI**  
**関数定義を取得するには**  
次の `get-function-definition` の例は、指定された関数定義の詳細情報を表示します。関数定義の ID を取得するには、`list-function-definitions` コマンドを使用します。  

```
aws greengrass get-function-definition \
    --function-definition-id "063f5d1a-1dd1-40b4-9b51-56f8993d0f85"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
    "CreationTimestamp": "2019-06-18T16:21:21.431Z",
    "Id": "063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
    "LastUpdatedTimestamp": "2019-06-18T16:21:21.431Z",
    "LatestVersion": "9748fda7-1589-4fcc-ac94-f5559e88678b",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/9748fda7-1589-4fcc-ac94-f5559e88678b",
    "tags": {}
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFunctionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-function-definition.html)」を参照してください。

### `get-group-certificate-authority`
<a name="greengrass_GetGroupCertificateAuthority_cli_2_topic"></a>

次のコード例は、`get-group-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループに関連付けられている CA を取得するには**  
次の `get-group-certificate-authority` の例では、指定された Greengrass グループに関連付けられている認証局 (CA) を取得します。認証機関 ID を取得するには、`list-group-certificate-authorities` コマンドを使用してグループ ID を指定します。  

```
aws greengrass get-group-certificate-authority \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731" \
    --certificate-authority-id "f0430e1736ea8ed30cc5d5de9af67a7e3586bad9ae4d89c2a44163f65fdd8cf6"
```
出力:  

```
{
    "GroupCertificateAuthorityArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/certificateauthorities/f0430e1736ea8ed30cc5d5de9af67a7e3586bad9ae4d89c2a44163f65fdd8cf6",
    "GroupCertificateAuthorityId": "f0430e1736ea8ed30cc5d5de9af67a7e3586bad9ae4d89c2a44163f65fdd8cf6",
    "PemEncodedCertificate": "-----BEGIN CERTIFICATE-----
MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBWEXAMPLEGA1UEBhMC
VVMxCzAJBgNVBAgTAldBMRAwDEXAMPLEEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
b24xFDASBgNVBAEXAMPLESBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jEXAMPLENMTEwNDI1MjA0NTIxWhcN
MTIwNDI0MjA0EXAMPLEBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWEXAMPLEDASBgNVBAsTC0lBTSBDb25z
b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWEXAMPLEgkqhkiG9w0BCQEWEG5vb25lQGFt
YXpvbi5EXAMPLE8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CEXAMPLE93vUEIO3IyNoH/f0wYK8m9T
rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswYEXAMPLEgpE
Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKEXAMPLEAQEFBQADgYEAtCu4
nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
-----END CERTIFICATE-----\n"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroupCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-group-certificate-authority.html)」を参照してください。

### `get-group-certificate-configuration`
<a name="greengrass_GetGroupCertificateConfiguration_cli_2_topic"></a>

次のコード例は、`get-group-certificate-configuration` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループが使用する認証機関の設定を取得するには**  
次の `get-group-certificate-configuration` の例では、指定された Greengrass グループで使用される認証局 (CA) の設定を取得します。  

```
aws greengrass get-group-certificate-configuration \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731"
```
出力:  

```
{
    "CertificateAuthorityExpiryInMilliseconds": 2524607999000,
    "CertificateExpiryInMilliseconds": 604800000,
    "GroupId": "1013db12-8b58-45ff-acc7-704248f66731"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroupCertificateConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-group-certificate-configuration.html)」を参照してください。

### `get-group-version`
<a name="greengrass_GetGroupVersion_cli_2_topic"></a>

次のコード例は、`get-group-version` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループのバージョンに関する情報を取得するには**  
次の `get-group-version` の例は、指定されたグループの指定されたバージョンに関する情報を取得します。グループのすべてのバージョンの ID を取得するには、`list-group-versions` コマンドを使用します。グループに最後に追加されたバージョンの ID を取得するには、`get-group` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-group-version \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731"  \
    --group-version-id "115136b3-cfd7-4462-b77f-8741a4b00e5e"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/115136b3-cfd7-4462-b77f-8741a4b00e5e",
    "CreationTimestamp": "2019-06-18T17:04:30.915Z",
    "Definition": {
        "CoreDefinitionVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/c906ed39-a1e3-4822-a981-7b9bd57b4b46/versions/42aeeac3-fd9d-4312-a8fd-ffa9404a20e0",
        "FunctionDefinitionVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/9748fda7-1589-4fcc-ac94-f5559e88678b",
        "SubscriptionDefinitionVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152/versions/88ae8699-12ac-4663-ba3f-4d7f0519140b"
    },
    "Id": "1013db12-8b58-45ff-acc7-704248f66731",
    "Version": "115136b3-cfd7-4462-b77f-8741a4b00e5e"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroupVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-group-version.html)」を参照してください。

### `get-group`
<a name="greengrass_GetGroup_cli_2_topic"></a>

次のコード例は、`get-group` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループに関する情報を取得するには**  
次の `get-group` の例では、指定された Greengrass グループに関する情報を取得します。グループの ID を取得するには、`list-groups` コマンドを使用します。  

```
aws greengrass get-group \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731",
    "CreationTimestamp": "2019-06-18T16:21:21.457Z",
    "Id": "1013db12-8b58-45ff-acc7-704248f66731",
    "LastUpdatedTimestamp": "2019-06-18T16:21:21.457Z",
    "LatestVersion": "115136b3-cfd7-4462-b77f-8741a4b00e5e",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/115136b3-cfd7-4462-b77f-8741a4b00e5e",
    "Name": "GGGroup4Pi3",
    "tags": {}
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-group.html)」を参照してください。

### `get-logger-definition-version`
<a name="greengrass_GetLoggerDefinitionVersion_cli_2_topic"></a>

次のコード例は、`get-logger-definition-version` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義バージョンに関する情報を取得するには**  
次の `get-logger-definition-version` の例では、指定されたロガー定義の指定されたバージョンに関する情報を取得します。ロガー定義のすべてのバージョンの ID を取得するには、`list-logger-definition-versions` コマンドを使用します。ロガー定義に追加された最新バージョンの ID を取得するには、`get-logger-definition` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-logger-definition-version \
    --logger-definition-id "49eeeb66-f1d3-4e34-86e3-3617262abf23" \
    --logger-definition-version-id "5e3f6f64-a565-491e-8de0-3c0d8e0f2073"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/49eeeb66-f1d3-4e34-86e3-3617262abf23/versions/5e3f6f64-a565-491e-8de0-3c0d8e0f2073",
    "CreationTimestamp": "2019-05-08T16:10:13.866Z",
    "Definition": {
        "Loggers": []
    },
    "Id": "49eeeb66-f1d3-4e34-86e3-3617262abf23",
    "Version": "5e3f6f64-a565-491e-8de0-3c0d8e0f2073"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoggerDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-logger-definition-version.html)」を参照してください。

### `get-logger-definition`
<a name="greengrass_GetLoggerDefinition_cli_2_topic"></a>

次のコード例は、`get-logger-definition` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義に関する情報を取得するには**  
次の `get-logger-definition` の例は、指定されたロガー定義に関する情報を取得します。ロガー定義の ID を取得するには、`list-logger-definitions` コマンドを使用します。  

```
aws greengrass get-logger-definition \
    --logger-definition-id "49eeeb66-f1d3-4e34-86e3-3617262abf23"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/49eeeb66-f1d3-4e34-86e3-3617262abf23",
    "CreationTimestamp": "2019-05-08T16:10:13.809Z",
    "Id": "49eeeb66-f1d3-4e34-86e3-3617262abf23",
    "LastUpdatedTimestamp": "2019-05-08T16:10:13.809Z",
    "LatestVersion": "5e3f6f64-a565-491e-8de0-3c0d8e0f2073",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/49eeeb66-f1d3-4e34-86e3-3617262abf23/versions/5e3f6f64-a565-491e-8de0-3c0d8e0f2073",
    "tags": {}
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoggerDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-logger-definition.html)」を参照してください。

### `get-resource-definition-version`
<a name="greengrass_GetResourceDefinitionVersion_cli_2_topic"></a>

次のコード例は、`get-resource-definition-version` を使用する方法を示しています。

**AWS CLI**  
**リソース定義の特定のバージョンに関する情報を取得するには**  
次の `get-resource-definition-version` の例では、指定されたリソース定義の指定されたバージョンに関する情報を取得します。リソース定義のすべてのバージョンの ID を取得するには、`list-resource-definition-versions` コマンドを使用します。リソース定義に追加された最新バージョンの ID を取得するには、`get-resource-definition` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-resource-definition-version \
    --resource-definition-id "ad8c101d-8109-4b0e-b97d-9cc5802ab658" \
    --resource-definition-version-id "26e8829a-491a-464d-9c87-664bf6f6f2be"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658/versions/26e8829a-491a-464d-9c87-664bf6f6f2be",
    "CreationTimestamp": "2019-06-19T16:40:59.392Z",
    "Definition": {
        "Resources": [
            {
                "Id": "26ff3f7b-839a-4217-9fdc-a218308b3963",
                "Name": "usb-port",
                "ResourceDataContainer": {
                    "LocalDeviceResourceData": {
                        "GroupOwnerSetting": {
                            "AutoAddGroupOwner": false
                        },
                        "SourcePath": "/dev/bus/usb"
                    }
                }
            }
        ]
    },
    "Id": "ad8c101d-8109-4b0e-b97d-9cc5802ab658",
    "Version": "26e8829a-491a-464d-9c87-664bf6f6f2be"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-resource-definition-version.html)」を参照してください。

### `get-resource-definition`
<a name="greengrass_GetResourceDefinition_cli_2_topic"></a>

次のコード例は、`get-resource-definition` を使用する方法を示しています。

**AWS CLI**  
**リソース定義に関する情報を取得するには**  
次の `get-resource-definition` の例では、指定されたリソース定義に関する情報を取得します。リソース定義の ID を取得するには、`list-resource-definitions` コマンドを使用します。  

```
aws greengrass get-resource-definition \
    --resource-definition-id "ad8c101d-8109-4b0e-b97d-9cc5802ab658"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658",
    "CreationTimestamp": "2019-06-19T16:40:59.261Z",
    "Id": "ad8c101d-8109-4b0e-b97d-9cc5802ab658",
    "LastUpdatedTimestamp": "2019-06-19T16:40:59.261Z",
    "LatestVersion": "26e8829a-491a-464d-9c87-664bf6f6f2be",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658/versions/26e8829a-491a-464d-9c87-664bf6f6f2be",
    "tags": {}
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-resource-definition.html)」を参照してください。

### `get-service-role-for-account`
<a name="greengrass_GetServiceRoleForAccount_cli_2_topic"></a>

次のコード例は、`get-service-role-for-account` を使用する方法を示しています。

**AWS CLI**  
**アカウントにアタッチされているサービスロールの詳細を取得するには**  
次の の`get-service-role-for-account`例では、 AWS アカウントにアタッチされているサービスロールに関する情報を取得します。  

```
aws greengrass get-service-role-for-account
```
出力:  

```
{
    "AssociatedAt": "2018-10-18T15:59:20Z",
    "RoleArn": "arn:aws:iam::123456789012:role/service-role/Greengrass_ServiceRole"
}
```
詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass サービスロール](https://docs.aws.amazon.com/greengrass/latest/developerguide/service-role.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceRoleForAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-service-role-for-account.html)」を参照してください。

### `get-subscription-definition-version`
<a name="greengrass_GetSubscriptionDefinitionVersion_cli_2_topic"></a>

次のコード例は、`get-subscription-definition-version` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション定義の特定のバージョンに関する情報を取得するには**  
次の `get-subscription-definition-version` の例では、指定されたサブスクリプション定義の指定されたバージョンに関する情報を取得します。サブスクリプション定義のすべてのバージョンの ID を取得するには、`list-subscription-definition-versions` コマンドを使用します。サブスクリプション定義に追加された最新バージョンの ID を取得するには、`get-subscription-definition` コマンドを使用して `LatestVersion` プロパティを確認します。  

```
aws greengrass get-subscription-definition-version \
    --subscription-definition-id "70e49321-83d5-45d2-bc09-81f4917ae152" \
    --subscription-definition-version-id "88ae8699-12ac-4663-ba3f-4d7f0519140b"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152/versions/88ae8699-12ac-4663-ba3f-4d7f0519140b",
    "CreationTimestamp": "2019-06-18T17:03:52.499Z",
    "Definition": {
        "Subscriptions": [
            {
                "Id": "692c4484-d89f-4f64-8edd-1a041a65e5b6",
                "Source": "arn:aws:lambda:us-west-2:123456789012:function:Greengrass_HelloWorld:GG_HelloWorld",
                "Subject": "hello/world",
                "Target": "cloud"
            }
        ]
    },
    "Id": "70e49321-83d5-45d2-bc09-81f4917ae152",
    "Version": "88ae8699-12ac-4663-ba3f-4d7f0519140b"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSubscriptionDefinitionVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-subscription-definition-version.html)」を参照してください。

### `get-subscription-definition`
<a name="greengrass_GetSubscriptionDefinition_cli_2_topic"></a>

次のコード例は、`get-subscription-definition` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション定義に関する情報を取得するには**  
次の `get-subscription-definition` の例では、指定されたサブスクリプション定義に関する情報を取得します。サブスクリプション定義の ID を取得するには、`list-subscription-definitions` コマンドを使用します。  

```
aws greengrass get-subscription-definition \
    --subscription-definition-id "70e49321-83d5-45d2-bc09-81f4917ae152"
```
出力:  

```
{
    "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152",
    "CreationTimestamp": "2019-06-18T17:03:52.392Z",
    "Id": "70e49321-83d5-45d2-bc09-81f4917ae152",
    "LastUpdatedTimestamp": "2019-06-18T17:03:52.392Z",
    "LatestVersion": "88ae8699-12ac-4663-ba3f-4d7f0519140b",
    "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152/versions/88ae8699-12ac-4663-ba3f-4d7f0519140b",
    "tags": {}
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSubscriptionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-subscription-definition.html)」を参照してください。

### `get-thing-runtime-configuration`
<a name="greengrass_GetThingRuntimeConfiguration_cli_2_topic"></a>

次のコード例は、`get-thing-runtime-configuration` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コアのランタイム設定を取得するには**  
次の `get-thing-runtime-configuration` の例では、Greengrass コアのランタイム設定を取得します。ランタイム設定を取得する前に、`update-thing-runtime-configuration` コマンドを使用してコアのランタイム設定を作成する必要があります。  

```
aws greengrass get-thing-runtime-configuration \
    --thing-name SampleGreengrassCore
```
出力:  

```
{
    "RuntimeConfiguration": {
        "TelemetryConfiguration": {
            "ConfigurationSyncStatus": "OutOfSync",
            "Telemetry": "On"
        }
    }
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[テレメトリ設定の設定](https://docs.aws.amazon.com/greengrass/latest/developerguide/telemetry.html#configure-telemetry-settings)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetThingRuntimeConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/get-thing-runtime-configuration.html)」を参照してください。

### `list-bulk-deployment-detailed-reports`
<a name="greengrass_ListBulkDeploymentDetailedReports_cli_2_topic"></a>

次のコード例は、`list-bulk-deployment-detailed-reports` を使用する方法を示しています。

**AWS CLI**  
**一括デプロイの個々のデプロイに関する情報を一覧表示するには**  
次の `list-bulk-deployment-detailed-reports` の例では、ステータスを含む、一括デプロイオペレーションの個々のデプロイに関する情報を表示します。  

```
aws greengrass list-bulk-deployment-detailed-reports \
    --bulk-deployment-id 42ce9c42-489b-4ed4-b905-8996aa50ef9d
```
出力:  

```
{
    "Deployments": [
        {
            "DeploymentType": "NewDeployment",
            "DeploymentStatus": "Success",
            "DeploymentId": "123456789012:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "DeploymentArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333/deployments/123456789012:123456789012:a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "GroupArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333/versions/123456789012:a1b2c3d4-5678-90ab-cdef-EXAMPLE44444",
            "CreatedAt": "2020-01-21T21:34:16.501Z"
        },
        {
            "DeploymentType": "NewDeployment",
            "DeploymentStatus": "InProgress",
            "DeploymentId": "123456789012:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "DeploymentArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/a1b2c3d4-5678-90ab-cdef-EXAMPLE55555/deployments/123456789012:123456789012:a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "GroupArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/a1b2c3d4-5678-90ab-cdef-EXAMPLE55555/versions/a1b2c3d4-5678-90ab-cdef-EXAMPLE66666",
            "CreatedAt": "2020-01-21T21:34:16.486Z"
        },
        ...
    ]
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループの一括デプロイを作成する](https://docs.aws.amazon.com/greengrass/latest/developerguide/bulk-deploy-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBulkDeploymentDetailedReports](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-bulk-deployment-detailed-reports.html)」を参照してください。

### `list-bulk-deployments`
<a name="greengrass_ListBulkDeployments_cli_2_topic"></a>

次のコード例は、`list-bulk-deployments` を使用する方法を示しています。

**AWS CLI**  
**一括デプロイを一覧表示するには**  
次の `list-bulk-deployments` の例では、すべての一括デプロイを一覧表示します。  

```
aws greengrass list-bulk-deployments
```
出力:  

```
{
    "BulkDeployments": [
        {
            "BulkDeploymentArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/bulk/deployments/870fb41b-6288-4e0c-bc76-a7ba4b4d3267",
            "BulkDeploymentId": "870fb41b-6288-4e0c-bc76-a7ba4b4d3267",
            "CreatedAt": "2019-06-25T16:11:33.265Z"
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループの一括デプロイを作成する](https://docs.aws.amazon.com/greengrass/latest/developerguide/bulk-deploy-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBulkDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-bulk-deployments.html)」を参照してください。

### `list-connector-definition-versions`
<a name="greengrass_ListConnectorDefinitionVersions_cli_2_topic"></a>

次のコード例は、`list-connector-definition-versions` を使用する方法を示しています。

**AWS CLI**  
**コネクタ定義で使用できるバージョンを一覧表示するには**  
次の `list-connector-definition-versions` の例では、指定されたコネクタ定義で使用できるバージョンを一覧表示します。`list-connector-definitions` コマンドを使用して、コネクタ定義 ID を取得します。  

```
aws greengrass list-connector-definition-versions \
    --connector-definition-id "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8"
```
出力:  

```
{
    "Versions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8/versions/63c57963-c7c2-4a26-a7e2-7bf478ea2623",
            "CreationTimestamp": "2019-06-19T19:30:01.300Z",
            "Id": "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
            "Version": "63c57963-c7c2-4a26-a7e2-7bf478ea2623"
        }
    ]
}
```
詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass コネクタを使用したサービスおよびプロトコルとの統合](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConnectorDefinitionVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-connector-definition-versions.html)」を参照してください。

### `list-connector-definitions`
<a name="greengrass_ListConnectorDefinitions_cli_2_topic"></a>

次のコード例は、`list-connector-definitions` を使用する方法を示しています。

**AWS CLI**  
**定義されている Greengrass コネクタを一覧表示するには**  
次の の`list-connector-definitions`例では、 AWS アカウントに定義されているすべての Greengrass コネクタを一覧表示します。  

```
aws greengrass list-connector-definitions
```
出力:  

```
{
    "Definitions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
            "CreationTimestamp": "2019-06-19T19:30:01.300Z",
            "Id": "b5c4ebfd-f672-49a3-83cd-31c7216a7bb8",
            "LastUpdatedTimestamp": "2019-06-19T19:30:01.300Z",
            "LatestVersion": "63c57963-c7c2-4a26-a7e2-7bf478ea2623",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/connectors/b5c4ebfd-f672-49a3-83cd-31c7216a7bb8/versions/63c57963-c7c2-4a26-a7e2-7bf478ea2623",
            "Name": "MySNSConnector"
        }
    ]
}
```
詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass コネクタを使用したサービスおよびプロトコルとの統合](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListConnectorDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-connector-definitions.html)」を参照してください。

### `list-core-definition-versions`
<a name="greengrass_ListCoreDefinitionVersions_cli_2_topic"></a>

次のコード例は、`list-core-definition-versions` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コア定義のバージョンを一覧表示するには**  
次の `list-core-definitions` の例では、指定された Greengrass コア定義のすべてのバージョンを一覧表示します。`list-core-definitions` コマンドを使用してバージョン ID を取得できます。  

```
aws greengrass list-core-definition-versions \
    --core-definition-id "eaf280cb-138c-4d15-af36-6f681a1348f7"
```
出力:  

```
{
    "Versions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/eaf280cb-138c-4d15-af36-6f681a1348f7/versions/467c36e4-c5da-440c-a97b-084e62593b4c",
            "CreationTimestamp": "2019-06-18T16:14:17.709Z",
            "Id": "eaf280cb-138c-4d15-af36-6f681a1348f7",
            "Version": "467c36e4-c5da-440c-a97b-084e62593b4c"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCoreDefinitionVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-core-definition-versions.html)」を参照してください。

### `list-core-definitions`
<a name="greengrass_ListCoreDefinitions_cli_2_topic"></a>

次のコード例は、`list-core-definitions` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コア定義を一覧表示するには**  
次の の`list-core-definitions`例では、 AWS アカウントのすべての Greengrass コア定義を一覧表示します。  

```
aws greengrass list-core-definitions
```
出力:  

```
{
    "Definitions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/0507843c-c1ef-4f06-b051-817030df7e7d",
            "CreationTimestamp": "2018-10-17T04:30:32.786Z",
            "Id": "0507843c-c1ef-4f06-b051-817030df7e7d",
            "LastUpdatedTimestamp": "2018-10-17T04:30:32.786Z",
            "LatestVersion": "bcdf9e86-3793-491e-93af-3cdfbf4e22b7",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/0507843c-c1ef-4f06-b051-817030df7e7d/versions/bcdf9e86-3793-491e-93af-3cdfbf4e22b7"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/31c22500-3509-4271-bafd-cf0655cda438",
            "CreationTimestamp": "2019-06-18T16:24:16.064Z",
            "Id": "31c22500-3509-4271-bafd-cf0655cda438",
            "LastUpdatedTimestamp": "2019-06-18T16:24:16.064Z",
            "LatestVersion": "2f350395-6d09-4c8a-8336-9ae5b57ace84",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/31c22500-3509-4271-bafd-cf0655cda438/versions/2f350395-6d09-4c8a-8336-9ae5b57ace84"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/c906ed39-a1e3-4822-a981-7b9bd57b4b46",
            "CreationTimestamp": "2019-06-18T16:21:21.351Z",
            "Id": "c906ed39-a1e3-4822-a981-7b9bd57b4b46",
            "LastUpdatedTimestamp": "2019-06-18T16:21:21.351Z",
            "LatestVersion": "42aeeac3-fd9d-4312-a8fd-ffa9404a20e0",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/c906ed39-a1e3-4822-a981-7b9bd57b4b46/versions/42aeeac3-fd9d-4312-a8fd-ffa9404a20e0"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/eaf280cb-138c-4d15-af36-6f681a1348f7",
            "CreationTimestamp": "2019-06-18T16:14:17.709Z",
            "Id": "eaf280cb-138c-4d15-af36-6f681a1348f7",
            "LastUpdatedTimestamp": "2019-06-18T16:14:17.709Z",
            "LatestVersion": "467c36e4-c5da-440c-a97b-084e62593b4c",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/cores/eaf280cb-138c-4d15-af36-6f681a1348f7/versions/467c36e4-c5da-440c-a97b-084e62593b4c"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCoreDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-core-definitions.html)」を参照してください。

### `list-deployments`
<a name="greengrass_ListDeployments_cli_2_topic"></a>

次のコード例は、`list-deployments` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループのデプロイを一覧表示するには**  
次の `list-deployments` の例では、指定された Greengrass グループのデプロイを一覧表示します。`list-groups` コマンドを使用して、グループ ID を検索できます。  

```
aws greengrass list-deployments \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731"
```
出力:  

```
{
    "Deployments": [
        {
            "CreatedAt": "2019-06-18T17:04:32.702Z",
            "DeploymentId": "1065b8a0-812b-4f21-9d5d-e89b232a530f",
            "DeploymentType": "NewDeployment",
            "GroupArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/115136b3-cfd7-4462-b77f-8741a4b00e5e"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-deployments.html)」を参照してください。

### `list-device-definition-versions`
<a name="greengrass_ListDeviceDefinitionVersions_cli_2_topic"></a>

次のコード例は、`list-device-definition-versions` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義のバージョンを一覧表示するには**  
次の `list-device-definition-versions` の例では、指定されたデバイス定義に関連付けられたデバイス定義バージョンを表示します。  

```
aws greengrass list-device-definition-versions \
    --device-definition-id "f9ba083d-5ad4-4534-9f86-026a45df1ccd"
```
出力:  

```
{
    "Versions": [
        {
            "Version": "83c13984-6fed-447e-84d5-5b8aa45d5f71",
            "CreationTimestamp": "2019-09-11T00:15:09.838Z",
            "Id": "f9ba083d-5ad4-4534-9f86-026a45df1ccd",
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd/versions/83c13984-6fed-447e-84d5-5b8aa45d5f71"
        },
        {
            "Version": "3b5cc510-58c1-44b5-9d98-4ad858ffa795",
            "CreationTimestamp": "2019-09-11T00:11:06.197Z",
            "Id": "f9ba083d-5ad4-4534-9f86-026a45df1ccd",
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd/versions/3b5cc510-58c1-44b5-9d98-4ad858ffa795"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeviceDefinitionVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-device-definition-versions.html)」を参照してください。

### `list-device-definitions`
<a name="greengrass_ListDeviceDefinitions_cli_2_topic"></a>

次のコード例は、`list-device-definitions` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義を一覧表示するには**  
次の の`list-device-definitions`例では、指定された AWS リージョンの AWS アカウントのデバイス定義の詳細を表示します。  

```
aws greengrass list-device-definitions \
    --region us-west-2
```
出力:  

```
{
    "Definitions": [
        {
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/50f3274c-3f0a-4f57-b114-6f46085281ab/versions/c777b0f5-1059-449b-beaa-f003ebc56c34",
            "LastUpdatedTimestamp": "2019-06-14T15:42:09.059Z",
            "LatestVersion": "c777b0f5-1059-449b-beaa-f003ebc56c34",
            "CreationTimestamp": "2019-06-14T15:42:09.059Z",
            "Id": "50f3274c-3f0a-4f57-b114-6f46085281ab",
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/50f3274c-3f0a-4f57-b114-6f46085281ab"
        },
        {
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/e01951c9-6134-479a-969a-1a15cac11c40/versions/514d57aa-4ee6-401c-9fac-938a9f7a51e5",
            "Name": "TestDeviceDefinition",
            "LastUpdatedTimestamp": "2019-04-16T23:17:43.245Z",
            "LatestVersion": "514d57aa-4ee6-401c-9fac-938a9f7a51e5",
            "CreationTimestamp": "2019-04-16T23:17:43.245Z",
            "Id": "e01951c9-6134-479a-969a-1a15cac11c40",
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/e01951c9-6134-479a-969a-1a15cac11c40"
        },
        {
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd/versions/83c13984-6fed-447e-84d5-5b8aa45d5f71",
            "Name": "TemperatureSensors",
            "LastUpdatedTimestamp": "2019-09-10T00:19:03.698Z",
            "LatestVersion": "83c13984-6fed-447e-84d5-5b8aa45d5f71",
            "CreationTimestamp": "2019-09-11T00:11:06.197Z",
            "Id": "f9ba083d-5ad4-4534-9f86-026a45df1ccd",
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/devices/f9ba083d-5ad4-4534-9f86-026a45df1ccd"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeviceDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-device-definitions.html)」を参照してください。

### `list-function-definition-versions`
<a name="greengrass_ListFunctionDefinitionVersions_cli_2_topic"></a>

次のコード例は、`list-function-definition-versions` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数バージョンを一覧表示するには**  
次の `list-function-definition-versions` の例では、指定された Lambda 関数のすべてのバージョンを一覧表示します。`list-function-definitions` コマンドを使用して ID を取得できます。  

```
aws greengrass list-function-definition-versions \
    --function-definition-id "063f5d1a-1dd1-40b4-9b51-56f8993d0f85"
```
出力:  

```
{
    "Versions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/9748fda7-1589-4fcc-ac94-f5559e88678b",
            "CreationTimestamp": "2019-06-18T17:04:30.776Z",
            "Id": "063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
            "Version": "9748fda7-1589-4fcc-ac94-f5559e88678b"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/9b08df77-26f2-4c29-93d2-769715edcfec",
            "CreationTimestamp": "2019-06-18T17:02:44.087Z",
            "Id": "063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
            "Version": "9b08df77-26f2-4c29-93d2-769715edcfec"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/4236239f-94f7-4b90-a2f8-2a24c829d21e",
            "CreationTimestamp": "2019-06-18T17:01:42.284Z",
            "Id": "063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
            "Version": "4236239f-94f7-4b90-a2f8-2a24c829d21e"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/343408bb-549a-4fbe-b043-853643179a39",
            "CreationTimestamp": "2019-06-18T16:21:21.431Z",
            "Id": "063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
            "Version": "343408bb-549a-4fbe-b043-853643179a39"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFunctionDefinitionVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-function-definition-versions.html)」を参照してください。

### `list-function-definitions`
<a name="greengrass_ListFunctionDefinitions_cli_2_topic"></a>

次のコード例は、`list-function-definitions` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数を一覧表示するには**  
次の の`list-function-definitions`例では、 AWS アカウントに定義されているすべての Lambda 関数を一覧表示します。  

```
aws greengrass list-function-definitions
```
出力:  

```
{
    "Definitions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/017970a5-8952-46dd-b1c1-020b3ae8e960",
            "CreationTimestamp": "2018-10-17T04:30:32.884Z",
            "Id": "017970a5-8952-46dd-b1c1-020b3ae8e960",
            "LastUpdatedTimestamp": "2018-10-17T04:30:32.884Z",
            "LatestVersion": "4380b302-790d-4ed8-92bf-02e88afecb15",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/017970a5-8952-46dd-b1c1-020b3ae8e960/versions/4380b302-790d-4ed8-92bf-02e88afecb15"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
            "CreationTimestamp": "2019-06-18T16:21:21.431Z",
            "Id": "063f5d1a-1dd1-40b4-9b51-56f8993d0f85",
            "LastUpdatedTimestamp": "2019-06-18T16:21:21.431Z",
            "LatestVersion": "9748fda7-1589-4fcc-ac94-f5559e88678b",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/063f5d1a-1dd1-40b4-9b51-56f8993d0f85/versions/9748fda7-1589-4fcc-ac94-f5559e88678b"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/6598e653-a262-440c-9967-e2697f64da7b",
            "CreationTimestamp": "2019-06-18T16:24:16.123Z",
            "Id": "6598e653-a262-440c-9967-e2697f64da7b",
            "LastUpdatedTimestamp": "2019-06-18T16:24:16.123Z",
            "LatestVersion": "38bc6ccd-98a2-4ce7-997e-16c84748fae4",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/6598e653-a262-440c-9967-e2697f64da7b/versions/38bc6ccd-98a2-4ce7-997e-16c84748fae4"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/c668df84-fad2-491b-95f4-655d2cad7885",
            "CreationTimestamp": "2019-06-18T16:14:17.784Z",
            "Id": "c668df84-fad2-491b-95f4-655d2cad7885",
            "LastUpdatedTimestamp": "2019-06-18T16:14:17.784Z",
            "LatestVersion": "37dd68c4-a64f-40ba-aa13-71fecc3ebded",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/functions/c668df84-fad2-491b-95f4-655d2cad7885/versions/37dd68c4-a64f-40ba-aa13-71fecc3ebded"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFunctionDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-function-definitions.html)」を参照してください。

### `list-group-certificate-authorities`
<a name="greengrass_ListGroupCertificateAuthorities_cli_2_topic"></a>

次のコード例は、`list-group-certificate-authorities` を使用する方法を示しています。

**AWS CLI**  
**グループの現在の CA を一覧表示するには**  
次の `list-group-certificate-authorities` の例では、指定された Greengrass グループの現在の認証局 (CA) を一覧表示します。  

```
aws greengrass list-group-certificate-authorities \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731"
```
出力:  

```
{
    "GroupCertificateAuthorities": [
        {
            "GroupCertificateAuthorityArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/certificateauthorities/f0430e1736ea8ed30cc5d5de9af67a7e3586bad9ae4d89c2a44163f65fdd8cf6",
            "GroupCertificateAuthorityId": "f0430e1736ea8ed30cc5d5de9af67a7e3586bad9ae4d89c2a44163f65fdd8cf6"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupCertificateAuthorities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-group-certificate-authorities.html)」を参照してください。

### `list-group-versions`
<a name="greengrass_ListGroupVersions_cli_2_topic"></a>

次のコード例は、`list-group-versions` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループのバージョンを一覧表示するには**  
次の `list-group-versions` の例では、指定された Greengrass のすべてのバージョンを一覧表示します。  

```
aws greengrass list-group-versions \
    --group-id "1013db12-8b58-45ff-acc7-704248f66731"
```
出力:  

```
{
    "Versions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/115136b3-cfd7-4462-b77f-8741a4b00e5e",
            "CreationTimestamp": "2019-06-18T17:04:30.915Z",
            "Id": "1013db12-8b58-45ff-acc7-704248f66731",
            "Version": "115136b3-cfd7-4462-b77f-8741a4b00e5e"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/4340669d-d14d-44e3-920c-46c928750750",
            "CreationTimestamp": "2019-06-18T17:03:52.663Z",
            "Id": "1013db12-8b58-45ff-acc7-704248f66731",
            "Version": "4340669d-d14d-44e3-920c-46c928750750"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/1b06e099-2d5b-4f10-91b9-78c4e060f5da",
            "CreationTimestamp": "2019-06-18T17:02:44.189Z",
            "Id": "1013db12-8b58-45ff-acc7-704248f66731",
            "Version": "1b06e099-2d5b-4f10-91b9-78c4e060f5da"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/2d3f27f1-3b43-4554-ab7a-73ec30477efe",
            "CreationTimestamp": "2019-06-18T17:01:42.401Z",
            "Id": "1013db12-8b58-45ff-acc7-704248f66731",
            "Version": "2d3f27f1-3b43-4554-ab7a-73ec30477efe"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/d20f7ae9-3444-4c1c-b025-e2ede23cdd31",
            "CreationTimestamp": "2019-06-18T16:21:21.457Z",
            "Id": "1013db12-8b58-45ff-acc7-704248f66731",
            "Version": "d20f7ae9-3444-4c1c-b025-e2ede23cdd31"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-group-versions.html)」を参照してください。

### `list-groups`
<a name="greengrass_ListGroups_cli_2_topic"></a>

次のコード例は、`list-groups` を使用する方法を示しています。

**AWS CLI**  
**Greengrass グループを一覧表示するには**  
次の の`list-groups`例では、 AWS アカウントで定義されているすべての Greengrass グループを一覧表示します。  

```
aws greengrass list-groups
```
出力:  

```
{
    "Groups": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731",
            "CreationTimestamp": "2019-06-18T16:21:21.457Z",
            "Id": "1013db12-8b58-45ff-acc7-704248f66731",
            "LastUpdatedTimestamp": "2019-06-18T16:21:21.457Z",
            "LatestVersion": "115136b3-cfd7-4462-b77f-8741a4b00e5e",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731/versions/115136b3-cfd7-4462-b77f-8741a4b00e5e",
            "Name": "GGGroup4Pi3"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1402daf9-71cf-4cfe-8be0-d5e80526d0d8",
            "CreationTimestamp": "2018-10-31T21:52:46.603Z",
            "Id": "1402daf9-71cf-4cfe-8be0-d5e80526d0d8",
            "LastUpdatedTimestamp": "2018-10-31T21:52:46.603Z",
            "LatestVersion": "749af901-60ab-456f-a096-91b12d983c29",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1402daf9-71cf-4cfe-8be0-d5e80526d0d8/versions/749af901-60ab-456f-a096-91b12d983c29",
            "Name": "MyTestGroup"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/504b5c8d-bbed-4635-aff1-48ec5b586db5",
            "CreationTimestamp": "2018-12-31T21:39:36.771Z",
            "Id": "504b5c8d-bbed-4635-aff1-48ec5b586db5",
            "LastUpdatedTimestamp": "2018-12-31T21:39:36.771Z",
            "LatestVersion": "46911e8e-f9bc-4898-8b63-59c7653636ec",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/504b5c8d-bbed-4635-aff1-48ec5b586db5/versions/46911e8e-f9bc-4898-8b63-59c7653636ec",
            "Name": "smp-ggrass-group"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-groups.html)」を参照してください。

### `list-logger-definition-versions`
<a name="greengrass_ListLoggerDefinitionVersions_cli_2_topic"></a>

次のコード例は、`list-logger-definition-versions` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義のバージョンのリストを取得するには**  
次の `list-logger-definition-versions` の例では、指定されたロガー定義のすべてのバージョンのリストを取得します。  

```
aws greengrass list-logger-definition-versions \
    --logger-definition-id "49eeeb66-f1d3-4e34-86e3-3617262abf23"
```
出力:  

```
{
    "Versions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/49eeeb66-f1d3-4e34-86e3-3617262abf23/versions/5e3f6f64-a565-491e-8de0-3c0d8e0f2073",
            "CreationTimestamp": "2019-05-08T16:10:13.866Z",
            "Id": "49eeeb66-f1d3-4e34-86e3-3617262abf23",
            "Version": "5e3f6f64-a565-491e-8de0-3c0d8e0f2073"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/49eeeb66-f1d3-4e34-86e3-3617262abf23/versions/3ec6d3af-eb85-48f9-a16d-1c795fe696d7",
            "CreationTimestamp": "2019-05-08T16:10:13.809Z",
            "Id": "49eeeb66-f1d3-4e34-86e3-3617262abf23",
            "Version": "3ec6d3af-eb85-48f9-a16d-1c795fe696d7"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLoggerDefinitionVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-logger-definition-versions.html)」を参照してください。

### `list-logger-definitions`
<a name="greengrass_ListLoggerDefinitions_cli_2_topic"></a>

次のコード例は、`list-logger-definitions` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義のリストを取得するには**  
次の の`list-logger-definitions`例では、 AWS アカウントのすべてのロガー定義を一覧表示します。  

```
aws greengrass list-logger-definitions
```
出力:  

```
{
    "Definitions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/49eeeb66-f1d3-4e34-86e3-3617262abf23",
            "CreationTimestamp": "2019-05-08T16:10:13.809Z",
            "Id": "49eeeb66-f1d3-4e34-86e3-3617262abf23",
            "LastUpdatedTimestamp": "2019-05-08T16:10:13.809Z",
            "LatestVersion": "5e3f6f64-a565-491e-8de0-3c0d8e0f2073",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/loggers/49eeeb66-f1d3-4e34-86e3-3617262abf23/versions/5e3f6f64-a565-491e-8de0-3c0d8e0f2073"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLoggerDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-logger-definitions.html)」を参照してください。

### `list-resource-definition-versions`
<a name="greengrass_ListResourceDefinitionVersions_cli_2_topic"></a>

次のコード例は、`list-resource-definition-versions` を使用する方法を示しています。

**AWS CLI**  
**リソース定義のバージョンを一覧表示するには**  
次の `list-resource-definition-versions` の例では、指定された Greengrass リソースのバージョンを一覧表示します。  

```
aws greengrass list-resource-definition-versions \
    --resource-definition-id "ad8c101d-8109-4b0e-b97d-9cc5802ab658"
```
出力:  

```
{
    "Versions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658/versions/26e8829a-491a-464d-9c87-664bf6f6f2be",
            "CreationTimestamp": "2019-06-19T16:40:59.392Z",
            "Id": "ad8c101d-8109-4b0e-b97d-9cc5802ab658",
            "Version": "26e8829a-491a-464d-9c87-664bf6f6f2be"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658/versions/432d92f6-12de-4ec9-a704-619a942a62aa",
            "CreationTimestamp": "2019-06-19T16:40:59.261Z",
            "Id": "ad8c101d-8109-4b0e-b97d-9cc5802ab658",
            "Version": "432d92f6-12de-4ec9-a704-619a942a62aa"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceDefinitionVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-resource-definition-versions.html)」を参照してください。

### `list-resource-definitions`
<a name="greengrass_ListResourceDefinitions_cli_2_topic"></a>

次のコード例は、`list-resource-definitions` を使用する方法を示しています。

**AWS CLI**  
**定義されているリソースを一覧表示するには**  
次の の`list-resource-definitions`例では、 AWS IoT Greengrass が使用するリソースを一覧表示します。  

```
aws greengrass list-resource-definitions
```
出力:  

```
{
    "Definitions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658",
            "CreationTimestamp": "2019-06-19T16:40:59.261Z",
            "Id": "ad8c101d-8109-4b0e-b97d-9cc5802ab658",
            "LastUpdatedTimestamp": "2019-06-19T16:40:59.261Z",
            "LatestVersion": "26e8829a-491a-464d-9c87-664bf6f6f2be",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658/versions/26e8829a-491a-464d-9c87-664bf6f6f2be"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/c8bb9ebc-c3fd-40a4-9c6a-568d75569d38",
            "CreationTimestamp": "2019-06-19T21:51:28.212Z",
            "Id": "c8bb9ebc-c3fd-40a4-9c6a-568d75569d38",
            "LastUpdatedTimestamp": "2019-06-19T21:51:28.212Z",
            "LatestVersion": "a5f94d0b-f6bc-40f4-bb78-7a1c5fe13ba1",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/c8bb9ebc-c3fd-40a4-9c6a-568d75569d38/versions/a5f94d0b-f6bc-40f4-bb78-7a1c5fe13ba1",
            "Name": "MyGreengrassResources"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-resource-definitions.html)」を参照してください。

### `list-subscription-definition-versions`
<a name="greengrass_ListSubscriptionDefinitionVersions_cli_2_topic"></a>

次のコード例は、`list-subscription-definition-versions` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション定義のバージョンを一覧表示するには**  
次の `list-subscription-definition-versions` の例では、指定されたサブスクリプションのすべてのバージョンを一覧表示します。`list-subscription-definitions` コマンドを使用して、サブスクリプション ID を検索できます。  

```
aws greengrass list-subscription-definition-versions \
    --subscription-definition-id "70e49321-83d5-45d2-bc09-81f4917ae152"
```
出力:  

```
{
    "Versions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152/versions/88ae8699-12ac-4663-ba3f-4d7f0519140b",
            "CreationTimestamp": "2019-06-18T17:03:52.499Z",
            "Id": "70e49321-83d5-45d2-bc09-81f4917ae152",
            "Version": "88ae8699-12ac-4663-ba3f-4d7f0519140b"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152/versions/7e320ba3-c369-4069-a2f0-90acb7f219d6",
            "CreationTimestamp": "2019-06-18T17:03:52.392Z",
            "Id": "70e49321-83d5-45d2-bc09-81f4917ae152",
            "Version": "7e320ba3-c369-4069-a2f0-90acb7f219d6"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSubscriptionDefinitionVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-subscription-definition-versions.html)」を参照してください。

### `list-subscription-definitions`
<a name="greengrass_ListSubscriptionDefinitions_cli_2_topic"></a>

次のコード例は、`list-subscription-definitions` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション定義のリストを取得するには**  
次の の`list-subscription-definitions`例では、 AWS アカウントで定義されているすべての AWS IoT Greengrass サブスクリプションを一覧表示します。  

```
aws greengrass list-subscription-definitions
```
出力:  

```
{
    "Definitions": [
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152",
            "CreationTimestamp": "2019-06-18T17:03:52.392Z",
            "Id": "70e49321-83d5-45d2-bc09-81f4917ae152",
            "LastUpdatedTimestamp": "2019-06-18T17:03:52.392Z",
            "LatestVersion": "88ae8699-12ac-4663-ba3f-4d7f0519140b",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/70e49321-83d5-45d2-bc09-81f4917ae152/versions/88ae8699-12ac-4663-ba3f-4d7f0519140b"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/cd6f1c37-d9a4-4e90-be94-01a7404f5967",
            "CreationTimestamp": "2018-10-18T15:45:34.024Z",
            "Id": "cd6f1c37-d9a4-4e90-be94-01a7404f5967",
            "LastUpdatedTimestamp": "2018-10-18T15:45:34.024Z",
            "LatestVersion": "d1cf8fac-284f-4f6a-98fe-a2d36d089373",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/cd6f1c37-d9a4-4e90-be94-01a7404f5967/versions/d1cf8fac-284f-4f6a-98fe-a2d36d089373"
        },
        {
            "Arn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/fa81bc84-3f59-4377-a84b-5d0134da359b",
            "CreationTimestamp": "2018-10-22T17:09:31.429Z",
            "Id": "fa81bc84-3f59-4377-a84b-5d0134da359b",
            "LastUpdatedTimestamp": "2018-10-22T17:09:31.429Z",
            "LatestVersion": "086d1b08-b25a-477c-a16f-6f9b3a9c295a",
            "LatestVersionArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/subscriptions/fa81bc84-3f59-4377-a84b-5d0134da359b/versions/086d1b08-b25a-477c-a16f-6f9b3a9c295a"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSubscriptionDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-subscription-definitions.html)」を参照してください。

### `list-tags-for-resource`
<a name="greengrass_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにアタッチされたタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定されたリソースにアタッチされているタグとその値を一覧表示します。  

```
aws greengrass list-tags-for-resource \
    --resource-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658"
```
出力:  

```
{
    "tags": {
        "ResourceSubType": "USB",
        "ResourceType": "Device"
    }
}
```
グループの詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass リソースのタグ付け](https://docs.aws.amazon.com/greengrass/latest/developerguide/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/list-tags-for-resource.html)」を参照してください。

### `reset-deployments`
<a name="greengrass_ResetDeployments_cli_2_topic"></a>

次のコード例は、`reset-deployments` を使用する方法を説明しています。

**AWS CLI**  
**Greengrass グループのデプロイ情報をクリーンアップするには**  
次の `reset-deployments` の例では、指定された Greengrass グループのデプロイ情報をクリーンアップします。`--force option` を追加すると、コアデバイスが応答するのを待たずにデプロイ情報がリセットされます。  

```
aws greengrass reset-deployments \
    --group-id "1402daf9-71cf-4cfe-8be0-d5e80526d0d8" \
    --force
```
出力:  

```
{
    "DeploymentArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1402daf9-71cf-4cfe-8be0-d5e80526d0d8/deployments/7dd4e356-9882-46a3-9e28-6d21900c011a",
    "DeploymentId": "7dd4e356-9882-46a3-9e28-6d21900c011a"
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[デプロイをリセットする](https://docs.aws.amazon.com/greengrass/latest/developerguide/reset-deployments-scenario.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/reset-deployments.html)」を参照してください。

### `start-bulk-deployment`
<a name="greengrass_StartBulkDeployment_cli_2_topic"></a>

次のコード例は、`start-bulk-deployment` を使用する方法を示しています。

**AWS CLI**  
**一括デプロイオペレーションを開始するには**  
次の `start-bulk-deployment` の例では、S3 バケットに保存されているファイルを使用して、デプロイするグループを指定して、一括デプロイオペレーションを開始します。  

```
aws greengrass start-bulk-deployment \
    --cli-input-json "{\"InputFileUri\":\"https://gg-group-deployment1.s3-us-west-2.amazonaws.com/MyBulkDeploymentInputFile.txt\", \"ExecutionRoleArn\":\"arn:aws:iam::123456789012:role/ggCreateDeploymentRole\",\"AmznClientToken\":\"yourAmazonClientToken\"}"
```
出力:  

```
{
    "BulkDeploymentArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/bulk/deployments/870fb41b-6288-4e0c-bc76-a7ba4b4d3267",
    "BulkDeploymentId": "870fb41b-6288-4e0c-bc76-a7ba4b4d3267"
}
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループの一括デプロイを作成する](https://docs.aws.amazon.com/greengrass/latest/developerguide/bulk-deploy-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartBulkDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/start-bulk-deployment.html)」を参照してください。

### `stop-bulk-deployment`
<a name="greengrass_StopBulkDeployment_cli_2_topic"></a>

次のコード例は、`stop-bulk-deployment` を使用する方法を示しています。

**AWS CLI**  
**一括デプロイを停止するには**  
次の `stop-bulk-deployment` の例では、指定された一括デプロイを停止します。完了した一括デプロイを停止しようとすると、次のエラーが表示されます: `InvalidInputException: Cannot change state of finished execution.`  

```
aws greengrass stop-bulk-deployment \
    --bulk-deployment-id "870fb41b-6288-4e0c-bc76-a7ba4b4d3267"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[グループの一括デプロイを作成する](https://docs.aws.amazon.com/greengrass/latest/developerguide/bulk-deploy-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopBulkDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/stop-bulk-deployment.html)」を参照してください。

### `tag-resource`
<a name="greengrass_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを適用するには**  
次の `tag-resource` の例では、指定された Greengrass リソースに `ResourceSubType` タグと `ResourceType` タグを適用します。このオペレーションでは、新しいタグと値を追加したり、既存のタグの値を更新したりできます。タグを削除するには、`untag-resource` コマンドを使用します。  

```
aws greengrass tag-resource \
    --resource-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/definition/resources/ad8c101d-8109-4b0e-b97d-9cc5802ab658" \
    --tags "ResourceType=Device,ResourceSubType=USB"
```
このコマンドでは何も出力されません。  
グループの詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass リソースのタグ付け](https://docs.aws.amazon.com/greengrass/latest/developerguide/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="greengrass_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグとその値を削除するには**  
次の `untag-resource` の例では、キーが `Category` のタグを指定された Greengrass グループから削除します。指定されたリソースに `Category` キーが存在しない場合、エラーは返されません。  

```
aws greengrass untag-resource \
    --resource-arn "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/1013db12-8b58-45ff-acc7-704248f66731" \
    --tag-keys "Category"
```
このコマンドでは何も出力されません。  
グループの詳細については、「**AWS IoT Greengrass デベロッパーガイド**」の「[Greengrass リソースのタグ付け](https://docs.aws.amazon.com/greengrass/latest/developerguide/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/untag-resource.html)」を参照してください。

### `update-connectivity-info`
<a name="greengrass_UpdateConnectivityInfo_cli_2_topic"></a>

次のコード例は、`update-connectivity-info` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コアの接続情報を更新するには**  
次の `update-connectivity-info` の例では、デバイスが指定された Greengrass コアへの接続に使用できるエンドポイントを変更します。接続情報は、IP アドレスまたはドメイン名のリストで、対応するポート番号とオプションのカスタマー定義メタデータが含まれます。ローカルネットワークが変更されると、接続情報を更新する必要がある場合があります。  

```
aws greengrass update-connectivity-info \
    --thing-name "MyGroup_Core" \
    --connectivity-info "[{\"Metadata\":\"\",\"PortNumber\":8883,\"HostAddress\":\"127.0.0.1\",\"Id\":\"localhost_127.0.0.1_0\"},{\"Metadata\":\"\",\"PortNumber\":8883,\"HostAddress\":\"192.168.1.3\",\"Id\":\"localIP_192.168.1.3\"}]"
```
出力:  

```
{
    "Version": "312de337-59af-4cf9-a278-2a23bd39c300"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateConnectivityInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-connectivity-info.html)」を参照してください。

### `update-connector-definition`
<a name="greengrass_UpdateConnectorDefinition_cli_2_topic"></a>

次のコード例は、`update-connector-definition` を使用する方法を示しています。

**AWS CLI**  
**コネクタ定義の名前を更新するには**  
次の `update-connector-definition` の例では、指定されたコネクタ定義の名前を更新します。コネクタの詳細を更新する場合は、`create-connector-definition-version` コマンドを使用して新しいバージョンを作成します。  

```
aws greengrass update-connector-definition \
    --connector-definition-id "55d0052b-0d7d-44d6-b56f-21867215e118" \
    --name "GreengrassConnectors2019"
```
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[コネクタを使用したサービスおよびプロトコルとの統合](https://docs.aws.amazon.com/greengrass/latest/developerguide/connectors.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateConnectorDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-connector-definition.html)」を参照してください。

### `update-core-definition`
<a name="greengrass_UpdateCoreDefinition_cli_2_topic"></a>

次のコード例は、`update-core-definition` を使用する方法を示しています。

**AWS CLI**  
**コア定義を更新するには**  
次の `update-core-definition` の例では、指定されたコア定義の名前を変更します。更新できるのは、コア定義の `name` プロパティのみです。  

```
aws greengrass update-core-definition \
    --core-definition-id "582efe12-b05a-409e-9a24-a2ba1bcc4a12" \
    --name "MyCoreDevices"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「Configure theIoT Greengrass Core](https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-core.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCoreDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-core-definition.html)」を参照してください。

### `update-device-definition`
<a name="greengrass_UpdateDeviceDefinition_cli_2_topic"></a>

次のコード例は、`update-device-definition` を使用する方法を示しています。

**AWS CLI**  
**デバイス定義を更新するには**  
次の `update-device-definition` の例では、指定されたデバイス定義の名前を変更します。デバイス定義の `name` プロパティのみを更新できます。  

```
aws greengrass update-device-definition \
    --device-definition-id "f9ba083d-5ad4-4534-9f86-026a45df1ccd" \
    --name "TemperatureSensors"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDeviceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-device-definition.html)」を参照してください。

### `update-function-definition`
<a name="greengrass_UpdateFunctionDefinition_cli_2_topic"></a>

次のコード例は、`update-function-definition` を使用する方法を示しています。

**AWS CLI**  
**関数定義の名前を更新するには**  
次の `update-function-definition` の例では、指定された関数定義の名前を更新します。関数の詳細を更新する場合は、`create-function-definition-version` コマンドを使用して新しいバージョンを作成します。  

```
aws greengrass update-function-definition \
    --function-definition-id "e47952bd-dea9-4e2c-a7e1-37bbe8807f46" \
    --name ObsoleteFunction
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[ローカル Lambda 関数を実行する](https://docs.aws.amazon.com/greengrass/latest/developerguide/lambda-functions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFunctionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-function-definition.html)」を参照してください。

### `update-group-certificate-configuration`
<a name="greengrass_UpdateGroupCertificateConfiguration_cli_2_topic"></a>

次のコード例は、`update-group-certificate-configuration` を使用する方法を示しています。

**AWS CLI**  
**グループの証明書の有効期限を更新するには**  
次の `update-group-certificate-configuration` の例では、指定されたグループに対して生成された証明書に 10 日間の有効期限を設定します。  

```
aws greengrass update-group-certificate-configuration \
    --group-id "8eaadd72-ce4b-4f15-892a-0cc4f3a343f1" \
    --certificate-expiry-in-milliseconds 864000000
```
出力:  

```
{
    "CertificateExpiryInMilliseconds": 864000000,
    "CertificateAuthorityExpiryInMilliseconds": 2524607999000,
    "GroupId": "8eaadd72-ce4b-4f15-892a-0cc4f3a343f1"
}
```
グループの詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[AWS IoT Greengrass セキュリティ](https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-sec.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroupCertificateConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-group-certificate-configuration.html)」を参照してください。

### `update-group`
<a name="greengrass_UpdateGroup_cli_2_topic"></a>

次のコード例は、`update-group` を使用する方法を示しています。

**AWS CLI**  
**グループ名を更新するには**  
次の `update-group` の例では、指定された Greengrass グループの名前を更新します。グループの詳細を更新する場合は、`create-group-version` コマンドを使用して新しいバージョンを作成します。  

```
aws greengrass update-group \
    --group-id "1402daf9-71cf-4cfe-8be0-d5e80526d0d8" \
    --name TestGroup4of6
```
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「ConfigureIoT Greengrass on AWS IoT](https://docs.aws.amazon.com/greengrass/latest/developerguide/gg-config.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-group.html)」を参照してください。

### `update-logger-definition`
<a name="greengrass_UpdateLoggerDefinition_cli_2_topic"></a>

次のコード例は、`update-logger-definition` を使用する方法を示しています。

**AWS CLI**  
**ロガー定義を更新するには**  
次の `update-logger-definition` の例では、指定されたロガー定義の名前を変更します。更新できるのは、ロガー定義の `name` プロパティのみです。  

```
aws greengrass update-logger-definition \
    --logger-definition-id "a454b62a-5d56-4ca9-bdc4-8254e1662cb0" \
    --name "LoggingConfigsForSensors"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Greengrass デベロッパーガイド」の「IoT Greengrass Logs を使用したモニタリング](https://docs.aws.amazon.com/greengrass/latest/developerguide/greengrass-logs-overview.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLoggerDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-logger-definition.html)」を参照してください。

### `update-resource-definition`
<a name="greengrass_UpdateResourceDefinition_cli_2_topic"></a>

次のコード例は、`update-resource-definition` を使用する方法を示しています。

**AWS CLI**  
**リソース定義の名前を更新するには**  
次の `update-resource-definition` の例では、指定されたリソース定義の名前を更新します。リソースの詳細を変更する場合は、`create-resource-definition-version` コマンドを使用して新しいバージョンを作成します。  

```
aws greengrass update-resource-definition \
    --resource-definition-id "c8bb9ebc-c3fd-40a4-9c6a-568d75569d38" \
    --name GreengrassConnectorResources
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT デベロッパーガイド*」の「[Lambda 関数とコネクタを使用したローカルリソースへのアクセス](https://docs.aws.amazon.com/greengrass/latest/developerguide/access-local-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResourceDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-resource-definition.html)」を参照してください。

### `update-subscription-definition`
<a name="greengrass_UpdateSubscriptionDefinition_cli_2_topic"></a>

次のコード例は、`update-subscription-definition` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション定義の名前を更新するには**  
次の `update-subscription-definition` の例では、指定されたサブスクリプション定義の名前を更新します。サブスクリプションの詳細を変更する場合は、`create-subscription-definition-version` コマンドを使用して新しいバージョンを作成します。  

```
aws greengrass update-subscription-definition \
    --subscription-definition-id "fa81bc84-3f59-4377-a84b-5d0134da359b" \
    --name "ObsoleteSubscription"
```
このコマンドでは何も出力されません。  
詳細については、*ガイド*のタイトルを参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSubscriptionDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-subscription-definition.html)」を参照してください。

### `update-thing-runtime-configuration`
<a name="greengrass_UpdateThingRuntimeConfiguration_cli_2_topic"></a>

次のコード例は、`update-thing-runtime-configuration` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コアのランタイム設定でテレメトリを有効にするには**  
次の `update-thing-runtime-configuration` の例では、Greengrass コアのランタイム設定を更新してテレメトリを有効にします。  

```
aws greengrass update-thing-runtime-configuration \
    --thing-name SampleGreengrassCore \
    --telemetry-configuration {\"Telemetry\":\"On\"}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Greengrass デベロッパーガイド*」の「[テレメトリ設定の設定](https://docs.aws.amazon.com/greengrass/latest/developerguide/telemetry.html#configure-telemetry-settings)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateThingRuntimeConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrass/update-thing-runtime-configuration.html)」を参照してください。

# AWS IoT Greengrass V2 を使用した の例 AWS CLI
<a name="cli_2_greengrassv2_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT Greengrass V2。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-service-role-to-account`
<a name="greengrassv2_AssociateServiceRoleToAccount_cli_2_topic"></a>

次の例は、`associate-service-role-to-account` を使用する方法を説明しています。

**AWS CLI**  
**Greengrass サービスロールを AWS アカウントに関連付けるには**  
次の の`associate-service-role-to-account`例では、 AWS サービスロールをアカウントの AWS IoT Greengrass に関連付けます。  

```
aws greengrassv2 associate-service-role-to-account \
    --role-arn arn:aws:iam::123456789012:role/service-role/Greengrass_ServiceRole
```
出力:  

```
{
    "associatedAt": "2022-01-19T19:21:53Z"
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[Greengrass サービスロール](https://docs.aws.amazon.com/greengrass/v2/developerguide/greengrass-service-role.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateServiceRoleToAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/associate-service-role-to-account.html)」を参照してください。

### `batch-associate-client-device-with-core-device`
<a name="greengrassv2_BatchAssociateClientDeviceWithCoreDevice_cli_2_topic"></a>

次のコード例は、`batch-associate-client-device-with-core-device` を使用する方法を示しています。

**AWS CLI**  
**クライアントデバイスをコアデバイスと関連付けるには**  
次の `batch-associate-client-device-with-core-device` の例では、2 つのクライアントデバイスを 1 つのコアデバイスに関連付けます。  

```
aws greengrassv2 batch-associate-client-device-with-core-device \
  --core-device-thing-name MyGreengrassCore \
  --entries thingName=MyClientDevice1 thingName=MyClientDevice2
```
出力:  

```
{
    "errorEntries": []
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[ローカル IoT デバイスとやり取りする](https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html)」参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchAssociateClientDeviceWithCoreDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/batch-associate-client-device-with-core-device.html)」を参照してください。

### `batch-disassociate-client-device-from-core-device`
<a name="greengrassv2_BatchDisassociateClientDeviceFromCoreDevice_cli_2_topic"></a>

次のコード例は、`batch-disassociate-client-device-from-core-device` を使用する方法を示しています。

**AWS CLI**  
**クライアントデバイスのコアデバイスとの関連付けを解除するには**  
次の `batch-disassociate-client-device-from-core-device` の例では、2 つのクライアントデバイスをコアデバイスから関連付け解除します。  

```
aws greengrassv2 batch-disassociate-client-device-from-core-device \
  --core-device-thing-name MyGreengrassCore \
  --entries thingName=MyClientDevice1 thingName=MyClientDevice2
```
出力:  

```
{
    "errorEntries": []
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[ローカル IoT デバイスとやり取りする](https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html)」参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDisassociateClientDeviceFromCoreDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/batch-disassociate-client-device-from-core-device.html)」を参照してください。

### `cancel-deployment`
<a name="greengrassv2_CancelDeployment_cli_2_topic"></a>

次のコード例は、`cancel-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイをキャンセルするには**  
次の `cancel-deployment` の例では、モノのグループへの継続的なデプロイを停止します。  

```
aws greengrassv2 cancel-deployment \
    --deployment-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "message": "SUCCESS"
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[デプロイをキャンセルする](https://docs.aws.amazon.com/greengrass/v2/developerguide/cancel-deployments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス」*の「[CancelDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/cancel-deployment.html)」を参照してください。

### `create-component-version`
<a name="greengrassv2_CreateComponentVersion_cli_2_topic"></a>

次のコード例は、`create-component-version` を使用する方法を示しています。

**AWS CLI**  
**例 1: レシピからコンポーネントバージョンを作成するには**  
次の `create-component-version` の例では、レシピファイルから Hello World コンポーネントのバージョンを作成します。  

```
aws greengrassv2 create-component-version \
    --inline-recipe fileb://com.example.HelloWorld-1.0.0.json
```
`com.example.HelloWorld-1.0.0.json` の内容:  

```
{
    "RecipeFormatVersion": "2020-01-25",
    "ComponentName": "com.example.HelloWorld",
    "ComponentVersion": "1.0.0",
    "ComponentDescription": "My first AWS IoT Greengrass component.",
    "ComponentPublisher": "Amazon",
    "ComponentConfiguration": {
        "DefaultConfiguration": {
            "Message": "world"
        }
    },
    "Manifests": [
        {
            "Platform": {
                "os": "linux"
            },
            "Lifecycle": {
                "Run": "echo 'Hello {configuration:/Message}'"
            }
        }
    ]
}
```
出力:  

```
{
    "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0",
    "componentName": "com.example.HelloWorld",
    "componentVersion": "1.0.0",
    "creationTimestamp": "2021-01-07T16:24:33.650000-08:00",
    "status": {
        "componentState": "REQUESTED",
        "message": "NONE",
        "errors": {}
    }
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[カスタムコンポーネントを作成する](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-components.html)」および「[デプロイするコンポーネントをアップロードする](https://docs.aws.amazon.com/greengrass/v2/developerguide/upload-components.html)」を参照してください。  
**例 2: AWS Lambda 関数からコンポーネントバージョンを作成するには**  
次の`create-component-version`例では、 AWS Lambda 関数から Hello World コンポーネントのバージョンを作成します。  

```
aws greengrassv2 create-component-version \
    --cli-input-json file://lambda-function-component.json
```
`lambda-function-component.json` の内容:  

```
{
    "lambdaFunction": {
        "lambdaArn": "arn:aws:lambda:us-west-2:123456789012:function:HelloWorldPythonLambda:1",
        "componentName": "com.example.HelloWorld",
        "componentVersion": "1.0.0",
        "componentLambdaParameters": {
            "eventSources": [
                {
                    "topic": "hello/world/+",
                    "type": "IOT_CORE"
                }
            ]
        }
    }
}
```
出力:  

```
{
    "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0",
    "componentName": "com.example.HelloWorld",
    "componentVersion": "1.0.0",
    "creationTimestamp": "2021-01-07T17:05:27.347000-08:00",
    "status": {
        "componentState": "REQUESTED",
        "message": "NONE",
        "errors": {}
    }
}
```
詳細については、*AWS 「 IoT Greengrass V2 デベロッパーガイド*」の[AWS 「Lambda 関数の実行](https://docs.aws.amazon.com/greengrass/v2/developerguide/run-lambda-functions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateComponentVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/create-component-version.html)」を参照してください。

### `create-deployment`
<a name="greengrassv2_CreateDeployment_cli_2_topic"></a>

次のコード例は、`create-deployment` を使用する方法を示しています。

**AWS CLI**  
**例 1: デプロイを作成するには**  
次の の`create-deployment`例では、 AWS IoT Greengrass コマンドラインインターフェイスをコアデバイスにデプロイします。  

```
aws greengrassv2 create-deployment \
    --cli-input-json file://cli-deployment.json
```
`cli-deployment.json` の内容:  

```
{
    "targetArn": "arn:aws:iot:us-west-2:123456789012:thing/MyGreengrassCore",
    "deploymentName": "Deployment for MyGreengrassCore",
    "components": {
        "aws.greengrass.Cli": {
            "componentVersion": "2.0.3"
        }
    },
    "deploymentPolicies": {
        "failureHandlingPolicy": "DO_NOTHING",
        "componentUpdatePolicy": {
            "timeoutInSeconds": 60,
            "action": "NOTIFY_COMPONENTS"
        },
        "configurationValidationPolicy": {
            "timeoutInSeconds": 60
        }
    },
    "iotJobConfiguration": {}
}
```
出力:  

```
{
    "deploymentId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[デプロイを作成する](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html)」を参照してください。  
**例 2: コンポーネント設定を更新するデプロイを作成するには**  
次の`create-deployment`例では、 AWS IoT Greengrass nucleus コンポーネントをコアデバイスのグループにデプロイします。このデプロイでは、nucleus コンポーネントに対して以下の設定更新が適用されます。  
ターゲットデバイスのプロキシ設定をデフォルトのプロキシなし設定にリセットします。ターゲットデバイスの MQTT 設定をデフォルトにリセットします。nucleus の JVM オプションを設定します。nucleus のログ記録レベルを設定します。  

```
aws greengrassv2 create-deployment \
    --cli-input-json file://nucleus-deployment.json
```
`nucleus-deployment.json` の内容:  

```
{
    "targetArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/MyGreengrassCoreGroup",
    "deploymentName": "Deployment for MyGreengrassCoreGroup",
    "components": {
        "aws.greengrass.Nucleus": {
            "componentVersion": "2.0.3",
            "configurationUpdate": {
                "reset": [
                    "/networkProxy",
                    "/mqtt"
                ],
                "merge": "{\"jvmOptions\":\"-Xmx64m\",\"logging\":{\"level\":\"WARN\"}}"
            }
        }
    },
    "deploymentPolicies": {
        "failureHandlingPolicy": "ROLLBACK",
        "componentUpdatePolicy": {
            "timeoutInSeconds": 60,
            "action": "NOTIFY_COMPONENTS"
        },
        "configurationValidationPolicy": {
            "timeoutInSeconds": 60
        }
    },
    "iotJobConfiguration": {}
}
```
出力:  

```
{
    "deploymentId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "iotJobId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "iotJobArn": "arn:aws:iot:us-west-2:123456789012:job/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
}
```
詳細は、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[デプロイを作成する](https://docs.aws.amazon.com/greengrass/v2/developerguide/create-deployments.html)」と「[コンポーネント設定を更新する](https://docs.aws.amazon.com/greengrass/v2/developerguide/update-component-configurations.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/create-deployment.html)」を参照してください。**

### `delete-component`
<a name="greengrassv2_DeleteComponent_cli_2_topic"></a>

次のコード例は、`delete-component` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントバージョンを削除するには**  
次の `delete-component` の例では、Hello World コンポーネントを削除します。  

```
aws greengrassv2 delete-component \
    --arn arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteComponent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/delete-component.html)」を参照してください。

### `delete-core-device`
<a name="greengrassv2_DeleteCoreDevice_cli_2_topic"></a>

次のコード例は、`delete-core-device` を使用する方法を示しています。

**AWS CLI**  
**コアデバイスを削除するには**  
次の の`delete-core-device`例では、 AWS IoT Greengrass コアデバイスを削除します。  

```
aws greengrassv2 delete-core-device \
    --core-device-thing-name MyGreengrassCore
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Greengrass V2 デベロッパーガイド」の「Uninstall theIoT Greengrass Core software](https://docs.aws.amazon.com/greengrass/v2/developerguide/configure-greengrass-core-v2.html#uninstall-greengrass-core-v2)」を参照してください。 *AWS IoT V2 *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCoreDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/delete-core-device.html)」を参照してください。

### `describe-component`
<a name="greengrassv2_DescribeComponent_cli_2_topic"></a>

次のコード例は、`describe-component` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントバージョンを記述するには**  
次の `describe-component` の例では、Hello World コンポーネントを記述します。  

```
aws greengrassv2 describe-component \
    --arn arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0
```
出力:  

```
{
    "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0",
    "componentName": "com.example.HelloWorld",
    "componentVersion": "1.0.0",
    "creationTimestamp": "2021-01-07T17:12:11.133000-08:00",
    "publisher": "Amazon",
    "description": "My first AWS IoT Greengrass component.",
    "status": {
        "componentState": "DEPLOYABLE",
        "message": "NONE",
        "errors": {}
    },
    "platforms": [
        {
            "attributes": {
                "os": "linux"
            }
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeComponent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/describe-component.html)」を参照してください。

### `disassociate-service-role-from-account`
<a name="greengrassv2_DisassociateServiceRoleFromAccount_cli_2_topic"></a>

次の例は、`disassociate-service-role-from-account` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントから Greengrass サービスロールの関連付けを解除するには**  
次の の`disassociate-service-role-from-account`例では、 AWS アカウントの Greengrass サービスロールと AWS IoT Greengrass の関連付けを解除します。  

```
aws greengrassv2 disassociate-service-role-from-account
```
出力:  

```
{
    "disassociatedAt": "2022-01-19T19:26:09Z"
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[Greengrass サービスロール](https://docs.aws.amazon.com/greengrass/v2/developerguide/greengrass-service-role.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateServiceRoleFromAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/disassociate-service-role-from-account.html)」を参照してください。

### `get-component-version-artifact`
<a name="greengrassv2_GetComponentVersionArtifact_cli_2_topic"></a>

次のコード例は、`get-component-version-artifact` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントアーティファクトをダウンロードする URL を取得するには**  
次の `get-component-version-artifact` の例では、ローカルデバッグコンソールコンポーネントの JAR ファイルをダウンロードするための URL を取得します。  

```
aws greengrassv2 get-component-version-artifact \
    --arn arn:aws:greengrass:us-west-2:aws:components:aws.greengrass.LocalDebugConsole:versions:2.0.3 \
    --artifact-name "Uvt6ZEzQ9TKiAuLbfXBX_APdY0TWks3uc46tHFHTzBM=/aws.greengrass.LocalDebugConsole.jar"
```
出力:  

```
{
    "preSignedUrl": "https://evergreencomponentmanageme-artifactbucket7410c9ef-g18n1iya8kwr.s3.us-west-2.amazonaws.com/public/aws.greengrass.LocalDebugConsole/2.0.3/s3/ggv2-component-releases-prod-pdx/EvergreenHttpDebugView/2ffc496ba41b39568968b22c582b4714a937193ee7687a45527238e696672521/aws.greengrass.LocalDebugConsole/aws.greengrass.LocalDebugConsole.jar?X-Amz-Security-Token=KwfLKSdEXAMPLE..."
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComponentVersionArtifact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/get-component-version-artifact.html)」を参照してください。

### `get-component`
<a name="greengrassv2_GetComponent_cli_2_topic"></a>

次のコード例は、`get-component` を使用する方法を示しています。

**AWS CLI**  
**例 1: コンポーネントのレシピを YAML 形式でダウンロードするには (Linux、macOS または Unix)**  
次の `get-component` の例では、Hello World コンポーネントのレシピを YAML 形式のファイルにダウンロードします。このコマンドは次のことを行います。  
`--output` および `--query` パラメータを使用して、コマンドの出力を制御します。これらのパラメータは、コマンドの出力からレシピ BLOB を抽出します。詳細については、「*AWS コマンドラインインターフェイスユーザーガイド*」の「[コマンド出力の制御](https://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html)」を参照してください。`base64` ユーティリティを使用します。このユーティリティは、抽出された BLOB を元のテキストにデコードします。成功した `get-component` コマンドによって返される BLOB は base64 でエンコードされたテキストです。元のテキストを取得するには、この BLOB をデコードする必要があります。デコードされたテキストを ファイルに保存します。コマンド (`> com.example.HelloWorld-1.0.0.json`) の最後のセクションでは、デコードされたテキストがファイルに保存されます。  

```
aws greengrassv2 get-component \
    --arn arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0 \
    --recipe-output-format YAML \
    --query recipe \
    --output text | base64 --decode > com.example.HelloWorld-1.0.0.json
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
**例 2: コンポーネントのレシピを YAML 形式でダウンロードするには (Windows CMD)**  
次の `get-component` の例では、Hello World コンポーネントのレシピを YAML 形式のファイルにダウンロードします。このコマンドは `certutil` ユーティリティを使用します。  

```
aws greengrassv2 get-component ^
    --arn arn:aws:greengrass:us-west-2:675946970638:components:com.example.HelloWorld:versions:1.0.0 ^
    --recipe-output-format YAML ^
    --query recipe ^
    --output text > com.example.HelloWorld-1.0.0.yaml.b64

certutil -decode com.example.HelloWorld-1.0.0.yaml.b64 com.example.HelloWorld-1.0.0.yaml
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
**例 3: コンポーネントのレシピを YAML 形式でダウンロードするには (Windows PowerShell)**  
次の `get-component` の例では、Hello World コンポーネントのレシピを YAML 形式のファイルにダウンロードします。このコマンドは `certutil` ユーティリティを使用します。  

```
aws greengrassv2 get-component `
    --arn arn:aws:greengrass:us-west-2:675946970638:components:com.example.HelloWorld:versions:1.0.0 `
    --recipe-output-format YAML `
    --query recipe `
    --output text > com.example.HelloWorld-1.0.0.yaml.b64

certutil -decode com.example.HelloWorld-1.0.0.yaml.b64 com.example.HelloWorld-1.0.0.yaml
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComponent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/get-component.html)」を参照してください。

### `get-connectivity-info`
<a name="greengrassv2_GetConnectivityInfo_cli_2_topic"></a>

次のコード例は、`get-connectivity-info` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コアデバイスの接続情報を取得するには**  
次の `get-connectivity-info` の例では、Greengrass コアデバイスの接続情報を取得します。クライアントデバイスはこの情報を使用して、このコアデバイスで実行される MQTT ブローカーに接続します。  

```
aws greengrassv2 get-connectivity-info \
    --thing-name MyGreengrassCore
```
出力:  

```
{
    "connectivityInfo": [
        {
            "id": "localIP_192.0.2.0",
            "hostAddress": "192.0.2.0",
            "portNumber": 8883
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コアデバイスエンドポイントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-core-device-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnectivityInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/get-connectivity-info.html)」を参照してください。

### `get-core-device`
<a name="greengrassv2_GetCoreDevice_cli_2_topic"></a>

次のコード例は、`get-core-device` を使用する方法を示しています。

**AWS CLI**  
**コアデバイスを取得するには**  
次の の`get-core-device`例では、 AWS IoT Greengrass コアデバイスに関する情報を取得します。  

```
aws greengrassv2 get-core-device \
    --core-device-thing-name MyGreengrassCore
```
出力:  

```
{
    "coreDeviceThingName": "MyGreengrassCore",
    "coreVersion": "2.0.3",
    "platform": "linux",
    "architecture": "amd64",
    "status": "HEALTHY",
    "lastStatusUpdateTimestamp": "2021-01-08T04:57:58.838000-08:00",
    "tags": {}
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コアデバイスのステータスを確認する](https://docs.aws.amazon.com/greengrass/v2/developerguide/device-status.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCoreDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/get-core-device.html)」を参照してください。

### `get-deployment`
<a name="greengrassv2_GetDeployment_cli_2_topic"></a>

次のコード例は、`get-deployment` を使用する方法を示しています。

**AWS CLI**  
**デプロイを取得するには**  
次の の`get-deployment`例では、 AWS IoT Greengrass nucleus コンポーネントのコアデバイスのグループへのデプロイに関する情報を取得します。  

```
aws greengrassv2 get-deployment \
    --deployment-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "targetArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/MyGreengrassCoreGroup",
    "revisionId": "14",
    "deploymentId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "deploymentName": "Deployment for MyGreengrassCoreGroup",
    "deploymentStatus": "ACTIVE",
    "iotJobId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "iotJobArn": "arn:aws:iot:us-west-2:123456789012:job/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "components": {
        "aws.greengrass.Nucleus": {
            "componentVersion": "2.0.3",
            "configurationUpdate": {
                "merge": "{\"jvmOptions\":\"-Xmx64m\",\"logging\":{\"level\":\"WARN\"}}",
                "reset": [
                    "/networkProxy",
                    "/mqtt"
                ]
            }
        }
    },
    "deploymentPolicies": {
        "failureHandlingPolicy": "ROLLBACK",
        "componentUpdatePolicy": {
            "timeoutInSeconds": 60,
            "action": "NOTIFY_COMPONENTS"
        },
        "configurationValidationPolicy": {
            "timeoutInSeconds": 60
        }
    },
    "iotJobConfiguration": {},
    "creationTimestamp": "2021-01-07T17:21:20.691000-08:00",
    "isLatestForTarget": false,
    "tags": {}
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントをデバイスにデプロイする](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-deployments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/get-deployment.html)」を参照してください。

### `get-service-role-for-account`
<a name="greengrassv2_GetServiceRoleForAccount_cli_2_topic"></a>

次の例は、`get-service-role-for-account` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントの Greengrass サービスロールを取得するには**  
次の の`get-service-role-for-account`例では、 AWS アカウントの AWS IoT Greengrass に関連付けられているサービスロールを取得します。  

```
aws greengrassv2 get-service-role-for-account
```
出力:  

```
{
    "associatedAt": "2022-01-19T19:21:53Z",
    "roleArn": "arn:aws:iam::123456789012:role/service-role/Greengrass_ServiceRole"
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[Greengrass サービスロール](https://docs.aws.amazon.com/greengrass/v2/developerguide/greengrass-service-role.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceRoleForAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/get-service-role-for-account.html)」を参照してください。

### `list-client-devices-associated-with-core-device`
<a name="greengrassv2_ListClientDevicesAssociatedWithCoreDevice_cli_2_topic"></a>

次のコード例は、`list-client-devices-associated-with-core-device` を使用する方法を示しています。

**AWS CLI**  
**コアデバイスに関連付けられたクライアントデバイスを一覧表示するには**  
次の `list-client-devices-associated-with-core-device` の例では、コアデバイスに関連付けられているすべてのクライアントデバイスを一覧表示します。  

```
aws greengrassv2 list-client-devices-associated-with-core-device \
  --core-device-thing-name MyTestGreengrassCore
```
出力:  

```
{
    "associatedClientDevices": [
        {
            "thingName": "MyClientDevice2",
            "associationTimestamp": "2021-07-12T16:33:55.843000-07:00"
        },
        {
            "thingName": "MyClientDevice1",
            "associationTimestamp": "2021-07-12T16:33:55.843000-07:00"
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[ローカル IoT デバイスとやり取りする](https://docs.aws.amazon.com/greengrass/v2/developerguide/interact-with-local-iot-devices.html)」参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListClientDevicesAssociatedWithCoreDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-client-devices-associated-with-core-device.html)」を参照してください。

### `list-component-versions`
<a name="greengrassv2_ListComponentVersions_cli_2_topic"></a>

次のコード例は、`list-component-versions` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントのバージョンを一覧表示するには**  
次の `list-component-versions` の例では、Hello World コンポーネントのすべてのバージョンを一覧表示します。  

```
aws greengrassv2 list-component-versions \
    --arn arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld
```
出力:  

```
{
    "componentVersions": [
        {
            "componentName": "com.example.HelloWorld",
            "componentVersion": "1.0.1",
            "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.1"
        },
        {
            "componentName": "com.example.HelloWorld",
            "componentVersion": "1.0.0",
            "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.0"
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListComponentVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-component-versions.html)」を参照してください。

### `list-components`
<a name="greengrassv2_ListComponents_cli_2_topic"></a>

次のコード例は、`list-components` を使用する方法を示しています。

**AWS CLI**  
**コンポーネントを一覧表示するには**  
次の の`list-components`例では、現在のリージョンの AWS アカウントで定義されている各コンポーネントとその最新バージョンを一覧表示します。  

```
aws greengrassv2 list-components
```
出力:  

```
{
    "components": [
        {
            "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld",
            "componentName": "com.example.HelloWorld",
            "latestVersion": {
                "arn": "arn:aws:greengrass:us-west-2:123456789012:components:com.example.HelloWorld:versions:1.0.1",
                "componentVersion": "1.0.1",
                "creationTimestamp": "2021-01-08T16:51:07.352000-08:00",
                "description": "My first AWS IoT Greengrass component.",
                "publisher": "Amazon",
                "platforms": [
                    {
                        "attributes": {
                            "os": "linux"
                        }
                    }
                ]
            }
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListComponents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-components.html)」を参照してください。

### `list-core-devices`
<a name="greengrassv2_ListCoreDevices_cli_2_topic"></a>

次のコード例は、`list-core-devices` を使用する方法を示しています。

**AWS CLI**  
**コアデバイスを一覧表示するには**  
次の の`list-core-devices`例では、現在のリージョンの AWS アカウントの AWS IoT Greengrass コアデバイスを一覧表示します。  

```
aws greengrassv2 list-core-devices
```
出力:  

```
{
    "coreDevices": [
        {
            "coreDeviceThingName": "MyGreengrassCore",
            "status": "HEALTHY",
            "lastStatusUpdateTimestamp": "2021-01-08T04:57:58.838000-08:00"
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コアデバイスのステータスを確認する](https://docs.aws.amazon.com/greengrass/v2/developerguide/device-status.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCoreDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-core-devices.html)」を参照してください。

### `list-deployments`
<a name="greengrassv2_ListDeployments_cli_2_topic"></a>

次のコード例は、`list-deployments` を使用する方法を示しています。

**AWS CLI**  
**デプロイを一覧表示するには**  
次の の`list-deployments`例では、現在のリージョンの AWS アカウントで定義された各デプロイの最新リビジョンを一覧表示します。  

```
aws greengrassv2 list-deployments
```
出力:  

```
{
    "deployments": [
        {
            "targetArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/MyGreengrassCoreGroup",
            "revisionId": "14",
            "deploymentId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "deploymentName": "Deployment for MyGreengrassCoreGroup",
            "creationTimestamp": "2021-01-07T17:21:20.691000-08:00",
            "deploymentStatus": "ACTIVE",
            "isLatestForTarget": false
        },
        {
            "targetArn": "arn:aws:iot:us-west-2:123456789012:thing/MyGreengrassCore",
            "revisionId": "1",
            "deploymentId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "deploymentName": "Deployment for MyGreengrassCore",
            "creationTimestamp": "2021-01-06T16:10:42.407000-08:00",
            "deploymentStatus": "COMPLETED",
            "isLatestForTarget": false
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コンポーネントをデバイスにデプロイする](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-deployments.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-deployments.html)」を参照してください。

### `list-effective-deployments`
<a name="greengrassv2_ListEffectiveDeployments_cli_2_topic"></a>

次のコード例は、`list-effective-deployments` を使用する方法を示しています。

**AWS CLI**  
**デプロイジョブを一覧表示するには**  
次の の`list-effective-deployments`例では、 AWS IoT Greengrass コアデバイスに適用されるデプロイを一覧表示します。  

```
aws greengrassv2 list-effective-deployments \
    --core-device-thing-name MyGreengrassCore
```
出力:  

```
{
    "effectiveDeployments": [
        {
            "deploymentId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "deploymentName": "Deployment for MyGreengrassCore",
            "iotJobId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "targetArn": "arn:aws:iot:us-west-2:123456789012:thing/MyGreengrassCore",
            "coreDeviceExecutionStatus": "COMPLETED",
            "reason": "SUCCESSFUL",
            "creationTimestamp": "2021-01-06T16:10:42.442000-08:00",
            "modifiedTimestamp": "2021-01-08T17:21:27.830000-08:00"
        },
        {
            "deploymentId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "deploymentName": "Deployment for MyGreengrassCoreGroup",
            "iotJobId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE44444",
            "iotJobArn": "arn:aws:iot:us-west-2:123456789012:job/a1b2c3d4-5678-90ab-cdef-EXAMPLE44444",
            "targetArn": "arn:aws:iot:us-west-2:123456789012:thinggroup/MyGreengrassCoreGroup",
            "coreDeviceExecutionStatus": "SUCCEEDED",
            "reason": "SUCCESSFUL",
            "creationTimestamp": "2021-01-07T17:19:20.394000-08:00",
            "modifiedTimestamp": "2021-01-07T17:21:20.721000-08:00"
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コアデバイスのステータスを確認する](https://docs.aws.amazon.com/greengrass/v2/developerguide/device-status.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEffectiveDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-effective-deployments.html)」を参照してください。

### `list-installed-components`
<a name="greengrassv2_ListInstalledComponents_cli_2_topic"></a>

次のコード例は、`list-installed-components` を使用する方法を示しています。

**AWS CLI**  
**コアデバイスにインストールされているコンポーネントを一覧表示するには**  
次の の`list-installed-components`例では、 AWS IoT Greengrass コアデバイスにインストールされているコンポーネントを一覧表示します。  

```
aws greengrassv2 list-installed-components \
    --core-device-thing-name MyGreengrassCore
```
出力:  

```
{
    "installedComponents": [
        {
            "componentName": "aws.greengrass.Cli",
            "componentVersion": "2.0.3",
            "lifecycleState": "RUNNING",
            "isRoot": true
        },
        {
            "componentName": "aws.greengrass.Nucleus",
            "componentVersion": "2.0.3",
            "lifecycleState": "FINISHED",
            "isRoot": true
        }
    ]
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コアデバイスのステータスを確認する](https://docs.aws.amazon.com/greengrass/v2/developerguide/device-status.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInstalledComponents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-installed-components.html)」を参照してください。

### `list-tags-for-resource`
<a name="greengrassv2_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の の`list-tags-for-resource`例では、 AWS IoT Greengrass コアデバイスのすべてのタグを一覧表示します。  

```
aws greengrassv2 list-tags-for-resource \
    --resource-arn arn:aws:greengrass:us-west-2:123456789012:coreDevices:MyGreengrassCore
```
出力:  

```
{
    "tags": {
        "Owner": "richard-roe"
    }
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[リソースのタグ付け](https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/list-tags-for-resource.html)」を参照してください。

### `tag-resource`
<a name="greengrassv2_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加**  
次の`tag-resource`例では、 AWS IoT Greengrass コアデバイスに所有者タグを追加します。このタグを使用して、コアデバイスを所有するユーザーに基づいてコアデバイスへのアクセスを制御できます。  

```
aws greengrassv2 tag-resource \
    --resource-arn arn:aws:greengrass:us-west-2:123456789012:coreDevices:MyGreengrassCore \
    --tags Owner=richard-roe
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[リソースのタグ付け](https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="greengrassv2_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の の`untag-resource`例では、 AWS IoT Greengrass コアデバイスから所有者タグを削除します。  

```
aws iotsitewise untag-resource \
    --resource-arn arn:aws:greengrass:us-west-2:123456789012:coreDevices:MyGreengrassCore \
    --tag-keys Owner
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[リソースのタグ付け](https://docs.aws.amazon.com/greengrass/v2/developerguide/tag-resources.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/untag-resource.html)」を参照してください。

### `update-connectivity-info`
<a name="greengrassv2_UpdateConnectivityInfo_cli_2_topic"></a>

次のコード例は、`update-connectivity-info` を使用する方法を示しています。

**AWS CLI**  
**Greengrass コアデバイスの接続情報を更新するには**  
次の `update-connectivity-info` の例では、Greengrass コアデバイスの接続情報を取得します。クライアントデバイスはこの情報を使用して、このコアデバイスで実行される MQTT ブローカーに接続します。  

```
aws greengrassv2 update-connectivity-info \
    --thing-name MyGreengrassCore \
    --cli-input-json file://core-device-connectivity-info.json
```
`core-device-connectivity-info.json` の内容:  

```
{
    "connectivityInfo": [
        {
            "hostAddress": "192.0.2.0",
            "portNumber": 8883,
            "id": "localIP_192.0.2.0"
        }
    ]
}
```
出力:  

```
{
    "version": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*AWS IoT Greengrass V2 デベロッパーガイド*」の「[コアデバイスエンドポイントを管理する](https://docs.aws.amazon.com/greengrass/v2/developerguide/manage-core-device-endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateConnectivityInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/greengrassv2/update-connectivity-info.html)」を参照してください。

# AWS IoT ジョブ SDK リリース を使用した の例 AWS CLI
<a name="cli_2_iot-jobs-data-plane_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT ジョブ SDK リリース。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-job-execution`
<a name="iot-jobs-data-plane_DescribeJobExecution_cli_2_topic"></a>

次のコード例は、`describe-job-execution` を使用する方法を示しています。

**AWS CLI**  
**ジョブ実行の詳細を取得するには**  
次の `describe-job-execution` の例では、指定されたジョブとモノの最新の実行の詳細を取得します。  

```
aws iot-jobs-data describe-job-execution \
    --job-id SampleJob \
    --thing-name MotionSensor1 \
    --endpoint-url https://1234567890abcd.jobs.iot.us-west-2.amazonaws.com
```
出力:  

```
{
    "execution": {
        "approximateSecondsBeforeTimedOut": 88,
        "executionNumber": 2939653338,
        "jobId": "SampleJob",
        "lastUpdatedAt": 1567701875.743,
        "queuedAt": 1567701902.444,
        "status": "QUEUED",
        "thingName": "MotionSensor1 ",
        "versionNumber": 3
   }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[デバイスとジョブ](https://docs.aws.amazon.com/iot/latest/developerguide/jobs-devices.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJobExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot-jobs-data/describe-job-execution.html)」を参照してください。

### `get-pending-job-executions`
<a name="iot-jobs-data-plane_GetPendingJobExecutions_cli_2_topic"></a>

次のコード例は、`get-pending-job-executions` を使用する方法を示しています。

**AWS CLI**  
**モノに対する終了ステータスにないすべてのジョブのリストを取得するには**  
次の `get-pending-job-executions` の例では、指定されたモノに対する終了状態にないすべてのジョブのリストを表示します。  

```
aws iot-jobs-data get-pending-job-executions \
    --thing-name MotionSensor1
    --endpoint-url https://1234567890abcd.jobs.iot.us-west-2.amazonaws.com
```
出力:  

```
{
    "inProgressJobs": [
    ],
    "queuedJobs": [
        {
            "executionNumber": 2939653338,
            "jobId": "SampleJob",
            "lastUpdatedAt": 1567701875.743,
            "queuedAt": 1567701902.444,
            "versionNumber": 3
      }
    ]
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[デバイスとジョブ](https://docs.aws.amazon.com/iot/latest/developerguide/jobs-devices.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPendingJobExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot-jobs-data/get-pending-job-executions.html)」を参照してください。

### `start-next-pending-job-execution`
<a name="iot-jobs-data-plane_StartNextPendingJobExecution_cli_2_topic"></a>

次のコード例は、`start-next-pending-job-execution` を使用する方法を示しています。

**AWS CLI**  
**モノに対する保留中の次のジョブ実行を取得して開始するには**  
次の `start-next-pending-job-execution` の例では、指定されたモノに対する IN\$1PROGRESS または QUEUED ステータスの次のジョブ実行を取得して開始します。  

```
aws iot-jobs-data start-next-pending-job-execution \
    --thing-name MotionSensor1
    --endpoint-url https://1234567890abcd.jobs.iot.us-west-2.amazonaws.com
```
出力:  

```
{
    "execution": {
        "approximateSecondsBeforeTimedOut": 88,
        "executionNumber": 2939653338,
        "jobId": "SampleJob",
        "lastUpdatedAt": 1567714853.743,
        "queuedAt": 1567701902.444,
        "startedAt": 1567714871.690,
        "status": "IN_PROGRESS",
        "thingName": "MotionSensor1 ",
        "versionNumber": 3
   }
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[デバイスとジョブ](https://docs.aws.amazon.com/iot/latest/developerguide/jobs-devices.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartNextPendingJobExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot-jobs-data/start-next-pending-job-execution.html)」を参照してください。

### `update-job-execution`
<a name="iot-jobs-data-plane_UpdateJobExecution_cli_2_topic"></a>

次のコード例は、`update-job-execution` を使用する方法を示しています。

**AWS CLI**  
**ジョブ実行のステータスを更新するには**  
次の `update-job-execution` の例では、指定されたジョブとモノのステータスを更新します。  

```
aws iot-jobs-data update-job-execution \
    --job-id SampleJob \
    --thing-name MotionSensor1 \
    --status REMOVED \
    --endpoint-url https://1234567890abcd.jobs.iot.us-west-2.amazonaws.com
```
出力:  

```
{
    "executionState": {
        "status": "REMOVED",
        "versionNumber": 3
    },
}
```
詳細については、「*AWS IoT デベロッパーガイド*」の「[デバイスとジョブ](https://docs.aws.amazon.com/iot/latest/developerguide/jobs-devices.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateJobExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iot-jobs-data/update-job-execution.html)」を参照してください。

# AWS IoT SiteWise を使用した の例 AWS CLI
<a name="cli_2_iotsitewise_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT SiteWise。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-assets`
<a name="iotsitewise_AssociateAssets_cli_2_topic"></a>

次のコード例は、`associate-assets` を使用する方法を示しています。

**AWS CLI**  
**子アセットを親アセットに関連付けるには**  
次の `associate-assets` の例では、風力タービンアセットを風力発電所アセットに関連付けます。風力タービンアセットモデルは、風力発電所アセットモデルに階層として存在します。  

```
aws iotsitewise associate-assets \
    --asset-id a1b2c3d4-5678-90ab-cdef-44444EXAMPLE \
    --hierarchy-id a1b2c3d4-5678-90ab-cdef-77777EXAMPLE \
    --child-asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Associating assets](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/add-associated-assets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/associate-assets.html)」を参照してください。

### `batch-associate-project-assets`
<a name="iotsitewise_BatchAssociateProjectAssets_cli_2_topic"></a>

次のコード例は、`batch-associate-project-assets` を使用する方法を示しています。

**AWS CLI**  
**アセットをプロジェクトに関連付けるには**  
次の `batch-associate-project-assets` の例では、風力発電所アセットをプロジェクトに関連付けます。  

```
aws iotsitewise batch-associate-project-assets \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE \
    --asset-ids a1b2c3d4-5678-90ab-cdef-44444EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[Adding assets to projects](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/add-assets-to-projects-sd.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchAssociateProjectAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/batch-associate-project-assets.html)」を参照してください。

### `batch-disassociate-project-assets`
<a name="iotsitewise_BatchDisassociateProjectAssets_cli_2_topic"></a>

次のコード例は、`batch-disassociate-project-assets` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトからアセットの関連付けを解除するには**  
次の `batch-disassociate-project-assets` の例では、プロジェクトから風力発電所アセットの関連付けを解除します。  

```
aws iotsitewise batch-disassociate-project-assets \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE \
    --asset-ids a1b2c3d4-5678-90ab-cdef-44444EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[Adding assets to projects](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/add-assets-to-projects-sd.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDisassociateProjectAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/batch-disassociate-project-assets.html)」を参照してください。

### `batch-put-asset-property-value`
<a name="iotsitewise_BatchPutAssetPropertyValue_cli_2_topic"></a>

次のコード例は、`batch-put-asset-property-value` を使用する方法を示しています。

**AWS CLI**  
**アセットプロパティにデータを送信するには**  
次の `batch-put-asset-property-value` の例では、プロパティエイリアスによって識別されるアセットプロパティに電力と温度のデータを送信します。  

```
aws iotsitewise batch-put-asset-property-value \
    --cli-input-json file://batch-put-asset-property-value.json
```
`batch-put-asset-property-value.json` の内容:  

```
{
    "entries": [
        {
            "entryId": "1575691200-company-windfarm-3-turbine-7-power",
            "propertyAlias": "company-windfarm-3-turbine-7-power",
            "propertyValues": [
                {
                    "value": {
                        "doubleValue": 4.92
                    },
                    "timestamp": {
                        "timeInSeconds": 1575691200
                    },
                    "quality": "GOOD"
                }
            ]
        },
        {
            "entryId": "1575691200-company-windfarm-3-turbine-7-temperature",
            "propertyAlias": "company-windfarm-3-turbine-7-temperature",
            "propertyValues": [
                {
                    "value": {
                        "integerValue": 38
                    },
                    "timestamp": {
                        "timeInSeconds": 1575691200
                    }
                }
            ]
        }
    ]
}
```
出力:  

```
{
    "errorEntries": []
}
```
詳細については、[AWS 「 IoT SiteWise ユーザーガイド」の「IoT SiteWise API を使用したデータの取り込み](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/ingest-api.html)」を参照してください。 *AWS IoT SiteWise *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchPutAssetPropertyValue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/batch-put-asset-property-value.html)」を参照してください。

### `create-access-policy`
<a name="iotsitewise_CreateAccessPolicy_cli_2_topic"></a>

次のコード例は、`create-access-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: ポータルへのユーザー管理アクセスを許可するには**  
次の `create-access-policy` の例では、風力発電所会社のウェブポータルへの管理者アクセス権をユーザーに付与するアクセスポリシーを作成します。  

```
aws iotsitewise create-access-policy \
    --cli-input-json file://create-portal-administrator-access-policy.json
```
`create-portal-administrator-access-policy.json` の内容:  

```
{
    "accessPolicyIdentity": {
        "user": {
            "id": "a1b2c3d4e5-a1b2c3d4-5678-90ab-cdef-bbbbbEXAMPLE"
        }
    },
    "accessPolicyPermission": "ADMINISTRATOR",
    "accessPolicyResource": {
        "portal": {
            "id": "a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE"
        }
    }
}
```
出力:  

```
{
    "accessPolicyId": "a1b2c3d4-5678-90ab-cdef-cccccEXAMPLE",
    "accessPolicyArn": "arn:aws:iotsitewise:us-west-2:123456789012:access-policy/a1b2c3d4-5678-90ab-cdef-cccccEXAMPLE"
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Adding or removing portal administrators](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html#portal-change-admins)」を参照してください。  
**例 2: プロジェクトへの読み取り専用アクセス権をユーザーに付与するには**  
次の `create-access-policy` の例では、風力発電所プロジェクトへの読み取り専用アクセス権をユーザーに付与するアクセスポリシーを作成します。  

```
aws iotsitewise create-access-policy \
    --cli-input-json file://create-project-viewer-access-policy.json
```
`create-project-viewer-access-policy.json` の内容:  

```
{
    "accessPolicyIdentity": {
        "user": {
            "id": "a1b2c3d4e5-a1b2c3d4-5678-90ab-cdef-bbbbbEXAMPLE"
        }
    },
    "accessPolicyPermission": "VIEWER",
    "accessPolicyResource": {
        "project": {
            "id": "a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE"
        }
    }
}
```
出力:  

```
{
    "accessPolicyId": "a1b2c3d4-5678-90ab-cdef-dddddEXAMPLE",
    "accessPolicyArn": "arn:aws:iotsitewise:us-west-2:123456789012:access-policy/a1b2c3d4-5678-90ab-cdef-dddddEXAMPLE"
}
```
詳細については、「*AWS SiteWise Monitor アプリケーションガイド*」の「[Assigning project viewers](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/assign-project-viewers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/create-access-policy.html)」を参照してください。

### `create-asset-model`
<a name="iotsitewise_CreateAssetModel_cli_2_topic"></a>

次のコード例は、`create-asset-model` を使用する方法を示しています。

**AWS CLI**  
**アセットモデルを作成するには**  
次の `create-asset-model` の例では、次のプロパティを使用して風力タービンを定義するアセットモデルを作成します。  
シリアル番号 - 風力タービンのシリアル番号 発電電力 - 風力タービンからの発電電力のデータストリーム 温度 C - 風力タービンからの温度のデータストリーム (摂氏) 温度 F - 摂氏から華氏にマップされた温度のデータポイント  

```
aws iotsitewise create-asset-model \
    --cli-input-json file://create-wind-turbine-model.json
```
`create-wind-turbine-model.json` の内容:  

```
{
    "assetModelName": "Wind Turbine Model",
    "assetModelDescription": "Represents a wind turbine",
    "assetModelProperties": [
        {
            "name": "Serial Number",
            "dataType": "STRING",
            "type": {
                "attribute": {}
            }
        },
        {
            "name": "Generated Power",
            "dataType": "DOUBLE",
            "unit": "kW",
            "type": {
                "measurement": {}
            }
        },
        {
            "name": "Temperature C",
            "dataType": "DOUBLE",
            "unit": "Celsius",
            "type": {
                "measurement": {}
            }
        },
        {
            "name": "Temperature F",
            "dataType": "DOUBLE",
            "unit": "Fahrenheit",
            "type": {
                "transform": {
                    "expression": "temp_c * 9 / 5 + 32",
                    "variables": [
                        {
                            "name": "temp_c",
                            "value": {
                                "propertyId": "Temperature C"
                            }
                        }
                    ]
                }
            }
        },
        {
            "name": "Total Generated Power",
            "dataType": "DOUBLE",
            "unit": "kW",
            "type": {
                "metric": {
                    "expression": "sum(power)",
                    "variables": [
                        {
                            "name": "power",
                            "value": {
                                "propertyId": "Generated Power"
                            }
                        }
                    ],
                    "window": {
                        "tumbling": {
                            "interval": "1h"
                        }
                    }
                }
            }
        }
    ]
}
```
出力:  

```
{
    "assetModelId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
    "assetModelArn": "arn:aws:iotsitewise:us-west-2:123456789012:asset-model/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
    "assetModelStatus": {
        "state": "CREATING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Defining asset models](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/define-models.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAssetModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/create-asset-model.html)」を参照してください。

### `create-asset`
<a name="iotsitewise_CreateAsset_cli_2_topic"></a>

次のコード例は、`create-asset` を使用する方法を示しています。

**AWS CLI**  
**アセットを作成するには**  
次の `create-asset` の例では、風力タービンアセットモデルから風力タービンアセットを作成します。  

```
aws iotsitewise create-asset \
    --asset-model-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE \
    --asset-name "Wind Turbine 1"
```
出力:  

```
{
    "assetId": "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
    "assetArn": "arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
    "assetStatus": {
        "state": "CREATING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Creating assets](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/create-assets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/create-asset.html)」を参照してください。

### `create-dashboard`
<a name="iotsitewise_CreateDashboard_cli_2_topic"></a>

次のコード例は、`create-dashboard` を使用する方法を示しています。

**AWS CLI**  
**ダッシュボードを作成するには**  
次の `create-dashboard` の例では、風力発電所の総発電電力が表示される折れ線グラフを含むダッシュボードを作成します。  

```
aws iotsitewise create-dashboard \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE \
    --dashboard-name "Wind Farm" \
    --dashboard-definition file://create-wind-farm-dashboard.json
```
`create-wind-farm-dashboard.json` の内容:  

```
{
    "widgets": [
        {
            "type": "monitor-line-chart",
            "title": "Generated Power",
            "x": 0,
            "y": 0,
            "height": 3,
            "width": 3,
            "metrics": [
                {
                    "label": "Power",
                    "type": "iotsitewise",
                    "assetId": "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
                    "propertyId": "a1b2c3d4-5678-90ab-cdef-99999EXAMPLE"
                }
            ]
        }
    ]
}
```
出力:  

```
{
    "dashboardId": "a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE",
    "dashboardArn": "arn:aws:iotsitewise:us-west-2:123456789012:dashboard/a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE"
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Creating dashboards (CLI)](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/create-dashboards-using-aws-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/create-dashboard.html)」を参照してください。

### `create-gateway`
<a name="iotsitewise_CreateGateway_cli_2_topic"></a>

次のコード例は、`create-gateway` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイを作成するには**  
次の`create-gateway`例では、 AWS IoT Greengrass で実行されるゲートウェイを作成します。  

```
aws iotsitewise create-gateway \
    --gateway-name ExampleCorpGateway \
    --gateway-platform greengrass={groupArn=arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/a1b2c3d4-5678-90ab-cdef-1b1b1EXAMPLE}
```
出力:  

```
{
    "gatewayId": "a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE",
    "gatewayArn": "arn:aws:iotsitewise:us-west-2:123456789012:gateway/a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE"
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Configuring a gateway](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/configure-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/create-gateway.html)」を参照してください。

### `create-portal`
<a name="iotsitewise_CreatePortal_cli_2_topic"></a>

次のコード例は、`create-portal` を使用する方法を示しています。

**AWS CLI**  
**ポータルを作成するには**  
次の `create-portal` の例では、風力発電所会社のウェブポータルを作成します。ポータルは、 AWS シングルサインオンを有効にしたのと同じリージョンでのみ作成できます。  

```
aws iotsitewise create-portal \
    --portal-name WindFarmPortal \
    --portal-description "A portal that contains wind farm projects for Example Corp." \
    --portal-contact-email support@example.com \
    --role-arn arn:aws:iam::123456789012:role/service-role/MySiteWiseMonitorServiceRole
```
出力:  

```
{
    "portalId": "a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE",
    "portalArn": "arn:aws:iotsitewise:us-west-2:123456789012:portal/a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE",
    "portalStartUrl": "https://a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE.app.iotsitewise.aws",
    "portalStatus": {
        "state": "CREATING"
    },
    "ssoApplicationId": "ins-a1b2c3d4-EXAMPLE"
}
```
詳細については、[AWS 「 IoT SiteWise ユーザーガイド」の「IoT SiteWise Monitor の開始方法](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/monitor-getting-started.html)」および「 IoT SiteWise [AWS ユーザーガイド」の「SSO の有効化](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/monitor-getting-started.html#monitor-enable-sso)」を参照してください。 *AWS IoT SiteWise * *AWS IoT SiteWise *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePortal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/create-portal.html)」を参照してください。

### `create-project`
<a name="iotsitewise_CreateProject_cli_2_topic"></a>

次のコード例は、`create-project` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトを作成するには**  
次の `create-project` の例では、風力発電所プロジェクトを作成します。  

```
aws iotsitewise create-project \
    --portal-id a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE \
    --project-name "Wind Farm 1" \
    --project-description "Contains asset visualizations for Wind Farm #1 for Example Corp."
```
出力:  

```
{
    "projectId": "a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE",
    "projectArn": "arn:aws:iotsitewise:us-west-2:123456789012:project/a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE"
}
```
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[Creating projects](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/create-projects.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/create-project.html)」を参照してください。**

### `delete-access-policy`
<a name="iotsitewise_DeleteAccessPolicy_cli_2_topic"></a>

次のコード例は、`delete-access-policy` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトまたはポータルへのユーザーのアクセス権を取り消すには**  
次の `delete-access-policy` の例では、ポータルへの管理者アクセス権をユーザーに付与するアクセスポリシーを削除します。  

```
aws iotsitewise delete-access-policy \
    --access-policy-id a1b2c3d4-5678-90ab-cdef-cccccEXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Adding or removing portal administrators](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html#portal-change-admins)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/delete-access-policy.html)」を参照してください。

### `delete-asset-model`
<a name="iotsitewise_DeleteAssetModel_cli_2_topic"></a>

次のコード例は、`delete-asset-model` を使用する方法を示しています。

**AWS CLI**  
**アセットモデルを削除するには**  
次の `delete-asset-model` の例では、風力タービンアセットモデルを削除します。  

```
aws iotsitewise delete-asset-model \
    --asset-model-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "assetModelStatus": {
        "state": "DELETING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Deleting asset models](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/delete-assets-and-models.html#delete-asset-models)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAssetModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/delete-asset-model.html)」を参照してください。

### `delete-asset`
<a name="iotsitewise_DeleteAsset_cli_2_topic"></a>

次のコード例は、`delete-asset` を使用する方法を示しています。

**AWS CLI**  
**アセットを削除するには**  
次の `delete-asset` の例では、風力タービンアセットを削除します。  

```
aws iotsitewise delete-asset \
    --asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
```
出力:  

```
{
    "assetStatus": {
        "state": "DELETING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Deleting assets](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/delete-assets-and-models.html#delete-assets)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/delete-asset.html)」を参照してください。

### `delete-dashboard`
<a name="iotsitewise_DeleteDashboard_cli_2_topic"></a>

次のコード例は、`delete-dashboard` を使用する方法を示しています。

**AWS CLI**  
**ダッシュボードを削除するには**  
次の `delete-dashboard` の例では、風力タービンダッシュボードを削除します。  

```
aws iotsitewise delete-dashboard \
    --dashboard-id a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[ダッシュボードの削除](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/delete-dashboards.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/delete-dashboard.html)」を参照してください。

### `delete-gateway`
<a name="iotsitewise_DeleteGateway_cli_2_topic"></a>

次のコード例は、`delete-gateway` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイを削除するには**  
次の `delete-gateway` の例では、ゲートウェイを削除します。  

```
aws iotsitewise delete-gateway \
    --gateway-id a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Ingesting data using a gateway](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/delete-gateway.html)」を参照してください。

### `delete-portal`
<a name="iotsitewise_DeletePortal_cli_2_topic"></a>

次のコード例は、`delete-portal` を使用する方法を示しています。

**AWS CLI**  
**ポータルを削除するには**  
次の `delete-portal` の例では、風力発電所会社のウェブポータルを削除します。  

```
aws iotsitewise delete-portal \
    --portal-id a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE
```
出力:  

```
{
    "portalStatus": {
        "state": "DELETING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Deleting a portal](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html#portal-delete-portal)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePortal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/delete-portal.html)」を参照してください。

### `delete-project`
<a name="iotsitewise_DeleteProject_cli_2_topic"></a>

次のコード例は、`delete-project` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトを削除するには**  
次の `delete-project` の例では、風力発電所プロジェクトを削除します。  

```
aws iotsitewise delete-project \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[Deleting projects](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/delete-projects.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/delete-project.html)」を参照してください。

### `describe-access-policy`
<a name="iotsitewise_DescribeAccessPolicy_cli_2_topic"></a>

次のコード例は、`describe-access-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセスポリシーの説明を表示するには**  
次の `describe-access-policy` の例では、風力発電所会社のウェブポータルへの管理者アクセス権をユーザーに付与するアクセスポリシーの説明を表示します。  

```
aws iotsitewise describe-access-policy \
    --access-policy-id a1b2c3d4-5678-90ab-cdef-cccccEXAMPLE
```
出力:  

```
{
    "accessPolicyId": "a1b2c3d4-5678-90ab-cdef-cccccEXAMPLE",
    "accessPolicyArn": "arn:aws:iotsitewise:us-west-2:123456789012:access-policy/a1b2c3d4-5678-90ab-cdef-cccccEXAMPLE",
    "accessPolicyIdentity": {
        "user": {
            "id": "a1b2c3d4e5-a1b2c3d4-5678-90ab-cdef-bbbbbEXAMPLE"
        }
    },
    "accessPolicyResource": {
        "portal": {
            "id": "a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE"
        }
    },
    "accessPolicyPermission": "ADMINISTRATOR",
    "accessPolicyCreationDate": "2020-02-20T22:35:15.552880124Z",
    "accessPolicyLastUpdateDate": "2020-02-20T22:35:15.552880124Z"
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Adding or removing portal administrators](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html#portal-change-admins)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-access-policy.html)」を参照してください。

### `describe-asset-model`
<a name="iotsitewise_DescribeAssetModel_cli_2_topic"></a>

次のコード例は、`describe-asset-model` を使用する方法を示しています。

**AWS CLI**  
**アセットモデルの説明を表示するには**  
次の `describe-asset-model` の例では、風力発電所アセットモデルの説明を表示します。  

```
aws iotsitewise describe-asset-model \
    --asset-model-id a1b2c3d4-5678-90ab-cdef-22222EXAMPLE
```
出力:  

```
{
    "assetModelId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
    "assetModelArn": "arn:aws:iotsitewise:us-west-2:123456789012:asset-model/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
    "assetModelName": "Wind Farm Model",
    "assetModelDescription": "Represents a wind farm that comprises many wind turbines",
    "assetModelProperties": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-99999EXAMPLE",
            "name": "Total Generated Power",
            "dataType": "DOUBLE",
            "unit": "kW",
            "type": {
                "metric": {
                    "expression": "sum(power)",
                    "variables": [
                        {
                            "name": "power",
                            "value": {
                                "propertyId": "a1b2c3d4-5678-90ab-cdef-66666EXAMPLE",
                                "hierarchyId": "a1b2c3d4-5678-90ab-cdef-77777EXAMPLE"
                            }
                        }
                    ],
                    "window": {
                        "tumbling": {
                            "interval": "1h"
                        }
                    }
                }
            }
        },
        {
            "id": "a1b2c3d4-5678-90ab-cdef-88888EXAMPLE",
            "name": "Region",
            "dataType": "STRING",
            "type": {
                "attribute": {
                    "defaultValue": " "
                }
            }
        }
    ],
    "assetModelHierarchies": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-77777EXAMPLE",
            "name": "Wind Turbines",
            "childAssetModelId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
        }
    ],
    "assetModelCreationDate": 1575671284.0,
    "assetModelLastUpdateDate": 1575671988.0,
    "assetModelStatus": {
        "state": "ACTIVE"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Describing a specific asset model](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/discover-asset-resources.html#describe-asset-model)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssetModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-asset-model.html)」を参照してください。

### `describe-asset-property`
<a name="iotsitewise_DescribeAssetProperty_cli_2_topic"></a>

次のコード例は、`describe-asset-property` を使用する方法を示しています。

**AWS CLI**  
**アセットプロパティの説明を表示するには**  
次の `describe-asset-property` の例では、風力発電所アセットの総発電電力プロパティの説明を表示します。  

```
aws iotsitewise describe-asset-property \
    --asset-id a1b2c3d4-5678-90ab-cdef-44444EXAMPLE \
    --property-id a1b2c3d4-5678-90ab-cdef-99999EXAMPLE
```
出力:  

```
{
    "assetId": "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
    "assetName": "Wind Farm 1",
    "assetModelId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
    "assetProperty": {
        "id": "a1b2c3d4-5678-90ab-cdef-99999EXAMPLE",
        "name": "Total Generated Power",
        "notification": {
            "topic": "$aws/sitewise/asset-models/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE/assets/a1b2c3d4-5678-90ab-cdef-44444EXAMPLE/properties/a1b2c3d4-5678-90ab-cdef-99999EXAMPLE",
            "state": "DISABLED"
        },
        "dataType": "DOUBLE",
        "unit": "kW",
        "type": {
            "metric": {
                "expression": "sum(power)",
                "variables": [
                    {
                        "name": "power",
                        "value": {
                            "propertyId": "a1b2c3d4-5678-90ab-cdef-66666EXAMPLE",
                            "hierarchyId": "a1b2c3d4-5678-90ab-cdef-77777EXAMPLE"
                        }
                    }
                ],
                "window": {
                    "tumbling": {
                        "interval": "1h"
                    }
                }
            }
        }
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Describing a specific asset property](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/discover-asset-resources.html#describe-asset-property)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssetProperty](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-asset-property.html)」を参照してください。

### `describe-asset`
<a name="iotsitewise_DescribeAsset_cli_2_topic"></a>

次のコード例は、`describe-asset` を使用する方法を示しています。

**AWS CLI**  
**アセットの説明を表示するには**  
次の `describe-asset` の例では、風力発電所アセットの説明を表示します。  

```
aws iotsitewise describe-asset \
    --asset-id a1b2c3d4-5678-90ab-cdef-44444EXAMPLE
```
出力:  

```
{
    "assetId": "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
    "assetArn": "arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
    "assetName": "Wind Farm 1",
    "assetModelId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
    "assetProperties": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-88888EXAMPLE",
            "name": "Region",
            "dataType": "STRING"
        },
        {
            "id": "a1b2c3d4-5678-90ab-cdef-99999EXAMPLE",
            "name": "Total Generated Power",
            "dataType": "DOUBLE",
            "unit": "kW"
        }
    ],
    "assetHierarchies": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-77777EXAMPLE",
            "name": "Wind Turbines"
        }
    ],
    "assetCreationDate": 1575672453.0,
    "assetLastUpdateDate": 1575672453.0,
    "assetStatus": {
        "state": "ACTIVE"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Describing a specific asset](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/discover-asset-resources.html#describe-asset)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-asset.html)」を参照してください。

### `describe-dashboard`
<a name="iotsitewise_DescribeDashboard_cli_2_topic"></a>

次のコード例は、`describe-dashboard` を使用する方法を示しています。

**AWS CLI**  
**ダッシュボードの説明を表示するには**  
次の `describe-dashboard` の例では、指定された風力発電所ダッシュボードの説明を表示します。  

```
aws iotsitewise describe-dashboard \
    --dashboard-id a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE
```
出力:  

```
{
    "dashboardId": "a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE",
    "dashboardArn": "arn:aws:iotsitewise:us-west-2:123456789012:dashboard/a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE",
    "dashboardName": "Wind Farm",
    "projectId": "a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE",
    "dashboardDefinition": "{\"widgets\":[{\"type\":\"monitor-line-chart\",\"title\":\"Generated Power\",\"x\":0,\"y\":0,\"height\":3,\"width\":3,\"metrics\":[{\"label\":\"Power\",\"type\":\"iotsitewise\",\"assetId\":\"a1b2c3d4-5678-90ab-cdef-44444EXAMPLE\",\"propertyId\":\"a1b2c3d4-5678-90ab-cdef-99999EXAMPLE\"}]}]}",
    "dashboardCreationDate": "2020-05-01T20:32:12.228476348Z",
    "dashboardLastUpdateDate": "2020-05-01T20:32:12.228476348Z"
}
```
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[ダッシュボードの表示](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/view-dashboards.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-dashboard.html)」を参照してください。

### `describe-gateway-capability-configuration`
<a name="iotsitewise_DescribeGatewayCapabilityConfiguration_cli_2_topic"></a>

次のコード例は、`describe-gateway-capability-configuration` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイ機能の説明を表示するには**  
次の `describe-gateway-capability-configuration` の例では、OPC-UA ソース機能の説明を表示します。  

```
aws iotsitewise describe-gateway-capability-configuration \
    --gateway-id a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE \
    --capability-namespace "iotsitewise:opcuacollector:1"
```
出力:  

```
{
    "gatewayId": "a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE",
    "capabilityNamespace": "iotsitewise:opcuacollector:1",
    "capabilityConfiguration": "{\"sources\":[{\"name\":\"Wind Farm #1\",\"endpoint\":{\"certificateTrust\":{\"type\":\"TrustAny\"},\"endpointUri\":\"opc.tcp://203.0.113.0:49320\",\"securityPolicy\":\"BASIC256\",\"messageSecurityMode\":\"SIGN_AND_ENCRYPT\",\"identityProvider\":{\"type\":\"Username\",\"usernameSecretArn\":\"arn:aws:secretsmanager:us-east-1:123456789012:secret:greengrass-factory1-auth-3QNDmM\"},\"nodeFilterRules\":[]},\"measurementDataStreamPrefix\":\"\"}]}",
    "capabilitySyncStatus": "IN_SYNC"
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Configuring data sources](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/configure-sources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGatewayCapabilityConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-gateway-capability-configuration.html)」を参照してください。

### `describe-gateway`
<a name="iotsitewise_DescribeGateway_cli_2_topic"></a>

次のコード例は、`describe-gateway` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイの説明を表示するには**  
次の `describe-gateway` の例では、ゲートウェイの説明を表示します。  

```
aws iotsitewise describe-gateway \
    --gateway-id a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE
```
出力:  

```
{
    "gatewayId": "a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE",
    "gatewayName": "ExampleCorpGateway",
    "gatewayArn": "arn:aws:iotsitewise:us-west-2:123456789012:gateway/a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE",
    "gatewayPlatform": {
        "greengrass": {
            "groupArn": "arn:aws:greengrass:us-west-2:123456789012:/greengrass/groups/a1b2c3d4-5678-90ab-cdef-1b1b1EXAMPLE"
        }
    },
    "gatewayCapabilitySummaries": [
        {
            "capabilityNamespace": "iotsitewise:opcuacollector:1",
            "capabilitySyncStatus": "IN_SYNC"
        }
    ],
    "creationDate": 1588369971.457,
    "lastUpdateDate": 1588369971.457
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Ingesting data using a gateway](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-gateway.html)」を参照してください。

### `describe-logging-options`
<a name="iotsitewise_DescribeLoggingOptions_cli_2_topic"></a>

次の例は、`describe-logging-options` を使用する方法を説明しています。

**AWS CLI**  
**current AWS IoT SiteWise ログ記録オプションを取得するには**  
次の の`describe-logging-options`例では、現在のリージョンの AWS アカウントの現在の AWS IoT SiteWise ログ記録オプションを取得します。  

```
aws iotsitewise describe-logging-options
```
出力:  

```
{
    "loggingOptions": {
        "level": "INFO"
    }
}
```
詳細については、「 IoT [ SiteWise ユーザーガイド」の「Monitoring AWS IoT SiteWise with Amazon CloudWatch Logs](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/monitor-cloudwatch-logs.html)」を参照してください。 *AWS IoT SiteWise *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-logging-options.html)」を参照してください。

### `describe-portal`
<a name="iotsitewise_DescribePortal_cli_2_topic"></a>

次のコード例は、`describe-portal` を使用する方法を示しています。

**AWS CLI**  
**ポータルの説明を表示するには**  
次の `describe-portal` の例では、風力発電所会社のウェブポータルの説明を表示します。  

```
aws iotsitewise describe-portal \
    --portal-id a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE
```
出力:  

```
{
    "portalId": "a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE",
    "portalArn": "arn:aws:iotsitewise:us-west-2:123456789012:portal/a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE",
    "portalName": "WindFarmPortal",
    "portalDescription": "A portal that contains wind farm projects for Example Corp.",
    "portalClientId": "E-a1b2c3d4e5f6_a1b2c3d4e5f6EXAMPLE",
    "portalStartUrl": "https://a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE.app.iotsitewise.aws",
    "portalContactEmail": "support@example.com",
    "portalStatus": {
        "state": "ACTIVE"
    },
    "portalCreationDate": "2020-02-04T23:01:52.90248068Z",
    "portalLastUpdateDate": "2020-02-04T23:01:52.90248078Z",
    "roleArn": "arn:aws:iam::123456789012:role/MySiteWiseMonitorServiceRole"
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Administering your portals](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePortal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-portal.html)」を参照してください。

### `describe-project`
<a name="iotsitewise_DescribeProject_cli_2_topic"></a>

次のコード例は、`describe-project` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトの説明を表示するには**  
次の `describe-project` の例では、風力発電所プロジェクトの説明を表示します。  

```
aws iotsitewise describe-project \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE
```
出力:  

```
{
    "projectId": "a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE",
    "projectArn": "arn:aws:iotsitewise:us-west-2:123456789012:project/a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE",
    "projectName": "Wind Farm 1",
    "portalId": "a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE",
    "projectDescription": "Contains asset visualizations for Wind Farm #1 for Example Corp.",
    "projectCreationDate": "2020-02-20T21:58:43.362246001Z",
    "projectLastUpdateDate": "2020-02-20T21:58:43.362246095Z"
}
```
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[プロジェクト詳細の表示](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/view-project-details.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/describe-project.html)」を参照してください。

### `disassociate-assets`
<a name="iotsitewise_DisassociateAssets_cli_2_topic"></a>

次のコード例は、`disassociate-assets` を使用する方法を示しています。

**AWS CLI**  
**親アセットから子アセットの関連付けを解除するには**  
次の `disassociate-assets` の例では、風力発電所アセットから風力タービンアセットの関連付けを解除します。  

```
aws iotsitewise disassociate-assets \
    --asset-id a1b2c3d4-5678-90ab-cdef-44444EXAMPLE \
    --hierarchy-id a1b2c3d4-5678-90ab-cdef-77777EXAMPLE \
    --child-asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Associating assets](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/add-associated-assets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/disassociate-assets.html)」を参照してください。

### `get-asset-property-aggregates`
<a name="iotsitewise_GetAssetPropertyAggregates_cli_2_topic"></a>

次のコード例は、`get-asset-property-aggregates` を使用する方法を示しています。

**AWS CLI**  
**アセットプロパティの集計された平均とカウントの値を取得するには**  
次の `get-asset-property-aggregates` の例では、風力タービンアセットの 1 時間の平均総電力と総電力データポイント数を取得します。  

```
aws iotsitewise get-asset-property-aggregates \
    --asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --property-id a1b2c3d4-5678-90ab-cdef-66666EXAMPLE \
    --start-date 1580849400 \
    --end-date 1580853000 \
    --aggregate-types AVERAGE COUNT \
    --resolution 1h
```
出力:  

```
{
    "aggregatedValues": [
        {
            "timestamp": 1580850000.0,
            "quality": "GOOD",
            "value": {
                "average": 8723.46538886233,
                "count": 12.0
            }
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Querying asset property aggregates](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/query-industrial-data.html#aggregates)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAssetPropertyAggregates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/get-asset-property-aggregates.html)」を参照してください。

### `get-asset-property-value-history`
<a name="iotsitewise_GetAssetPropertyValueHistory_cli_2_topic"></a>

次のコード例は、`get-asset-property-value-history` を使用する方法を示しています。

**AWS CLI**  
**アセットプロパティの過去の値を取得するには**  
次の `get-asset-property-value-history` の例では、風力タービンアセットの 20 分間の総電力値を取得します。  

```
aws iotsitewise get-asset-property-value-history \
    --asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --property-id a1b2c3d4-5678-90ab-cdef-66666EXAMPLE \
    --start-date 1580851800 \
    --end-date 1580853000
```
出力:  

```
{
    "assetPropertyValueHistory": [
        {
            "value": {
                "doubleValue": 7217.787046814844
            },
            "timestamp": {
                "timeInSeconds": 1580852100,
                "offsetInNanos": 0
            },
            "quality": "GOOD"
        },
        {
            "value": {
                "doubleValue": 6941.242811875451
            },
            "timestamp": {
                "timeInSeconds": 1580852400,
                "offsetInNanos": 0
            },
            "quality": "GOOD"
        },
        {
            "value": {
                "doubleValue": 6976.797662266717
            },
            "timestamp": {
                "timeInSeconds": 1580852700,
                "offsetInNanos": 0
            },
            "quality": "GOOD"
        },
        {
            "value": {
                "doubleValue": 6890.8677520453875
            },
            "timestamp": {
                "timeInSeconds": 1580853000,
                "offsetInNanos": 0
            },
            "quality": "GOOD"
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[履歴アセットプロパティ値をクエリする](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/query-industrial-data.html#historical-values)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAssetPropertyValueHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/get-asset-property-value-history.html)」を参照してください。

### `get-asset-property-value`
<a name="iotsitewise_GetAssetPropertyValue_cli_2_topic"></a>

次のコード例は、`get-asset-property-value` を使用する方法を示しています。

**AWS CLI**  
**アセットプロパティの現在の値を取得するには**  
次の `get-asset-property-value` の例では、風力タービンアセットの現在の総電力を取得します。  

```
aws iotsitewise get-asset-property-value \
    --asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --property-id a1b2c3d4-5678-90ab-cdef-66666EXAMPLE
```
出力:  

```
{
    "propertyValue": {
        "value": {
            "doubleValue": 6890.8677520453875
        },
        "timestamp": {
            "timeInSeconds": 1580853000,
            "offsetInNanos": 0
        },
        "quality": "GOOD"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[現在のアセットプロパティ値をクエリする](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/query-industrial-data.html#current-values)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAssetPropertyValue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/get-asset-property-value.html)」を参照してください。

### `list-access-policies`
<a name="iotsitewise_ListAccessPolicies_cli_2_topic"></a>

次のコード例は、`list-access-policies` を使用する方法を示しています。

**AWS CLI**  
**すべてのアクセスポリシーを一覧表示するには**  
次の `list-access-policies` の例では、ポータル管理者であるユーザーのすべてのアクセスポリシーを一覧表示します。  

```
aws iotsitewise list-access-policies \
    --identity-type USER \
    --identity-id a1b2c3d4e5-a1b2c3d4-5678-90ab-cdef-bbbbbEXAMPLE
```
出力:  

```
{
    "accessPolicySummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-cccccEXAMPLE",
            "identity": {
                "user": {
                    "id": "a1b2c3d4e5-a1b2c3d4-5678-90ab-cdef-bbbbbEXAMPLE"
                }
            },
            "resource": {
                "portal": {
                    "id": "a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE"
                }
            },
            "permission": "ADMINISTRATOR"
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Administering your portals](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-access-policies.html)」を参照してください。

### `list-asset-models`
<a name="iotsitewise_ListAssetModels_cli_2_topic"></a>

次のコード例は、`list-asset-models` を使用する方法を示しています。

**AWS CLI**  
**すべてのアセットモデルを一覧表示するには**  
次の の`list-asset-models`例では、現在のリージョンの AWS アカウントで定義されているすべてのアセットモデルを一覧表示します。  

```
aws iotsitewise list-asset-models
```
出力:  

```
{
    "assetModelSummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
            "arn": "arn:aws:iotsitewise:us-west-2:123456789012:asset-model/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
            "name": "Wind Farm Model",
            "description": "Represents a wind farm that comprises many wind turbines",
            "creationDate": 1575671284.0,
            "lastUpdateDate": 1575671988.0,
            "status": {
                "state": "ACTIVE"
            }
        },
        {
            "id": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "arn": "arn:aws:iotsitewise:us-west-2:123456789012:asset-model/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "name": "Wind Turbine Model",
            "description": "Represents a wind turbine manufactured by Example Corp",
            "creationDate": 1575671207.0,
            "lastUpdateDate": 1575686273.0,
            "status": {
                "state": "ACTIVE"
            }
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[すべてのアセットモデルのリスト表示](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/discover-asset-resources.html#list-asset-models)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssetModels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-asset-models.html)」を参照してください。

### `list-assets`
<a name="iotsitewise_ListAssets_cli_2_topic"></a>

次のコード例は、`list-assets` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべての最上位アセットを一覧表示するには**  
次の の`list-assets`例では、アセット階層ツリーの最上位にあり、現在のリージョンの AWS アカウントで定義されているすべてのアセットを一覧表示します。  

```
aws iotsitewise list-assets \
    --filter TOP_LEVEL
```
出力:  

```
{
    "assetSummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
            "arn": "arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
            "name": "Wind Farm 1",
            "assetModelId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
            "creationDate": 1575672453.0,
            "lastUpdateDate": 1575672453.0,
            "status": {
                "state": "ACTIVE"
            },
            "hierarchies": [
                {
                    "id": "a1b2c3d4-5678-90ab-cdef-77777EXAMPLE",
                    "name": "Wind Turbines"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[アセットのリスト表示](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/discover-asset-resources.html#list-assets)」を参照してください。  
**例 2: アセットモデルに基づくすべてのアセットを一覧表示するには**  
次の の`list-assets`例では、アセットモデルに基づいて、現在のリージョンの AWS アカウントで定義されているすべてのアセットを一覧表示します。  

```
aws iotsitewise list-assets \
    --asset-model-id a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "assetSummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
            "arn": "arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
            "name": "Wind Turbine 1",
            "assetModelId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "creationDate": 1575671550.0,
            "lastUpdateDate": 1575686308.0,
            "status": {
                "state": "ACTIVE"
            },
            "hierarchies": []
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[アセットのリスト表示](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/discover-asset-resources.html#list-assets)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-assets.html)」を参照してください。

### `list-associated-assets`
<a name="iotsitewise_ListAssociatedAssets_cli_2_topic"></a>

次のコード例は、`list-associated-assets` を使用する方法を示しています。

**AWS CLI**  
**特定のアセットに関連付けられているすべてのアセットを一覧表示するには**  
次の `list-associated-assets` の例では、指定された風力発電所アセットに関連付けられているすべての風力タービンアセットを一覧表示します。  

```
aws iotsitewise list-associated-assets \
    --asset-id a1b2c3d4-5678-90ab-cdef-44444EXAMPLE \
    --hierarchy-id a1b2c3d4-5678-90ab-cdef-77777EXAMPLE
```
出力:  

```
{
    "assetSummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
            "arn": "arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE",
            "name": "Wind Turbine 1",
            "assetModelId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "creationDate": 1575671550.0,
            "lastUpdateDate": 1575686308.0,
            "status": {
                "state": "ACTIVE"
            },
            "hierarchies": []
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[特定のアセットに関連付けられているアセットのリスト表示](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/discover-asset-resources.html#list-associated-assets)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssociatedAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-associated-assets.html)」を参照してください。

### `list-dashboards`
<a name="iotsitewise_ListDashboards_cli_2_topic"></a>

次のコード例は、`list-dashboards` を使用する方法を示しています。

**AWS CLI**  
**プロジェクト内のすべてのダッシュボードを一覧表示するには**  
次の `list-dashboards` の例では、プロジェクトで定義されているすべてのダッシュボードを一覧表示します。  

```
aws iotsitewise list-dashboards \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE
```
出力:  

```
{
    "dashboardSummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE",
            "name": "Wind Farm",
            "creationDate": "2020-05-01T20:32:12.228476348Z",
            "lastUpdateDate": "2020-05-01T20:32:12.228476348Z"
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[ダッシュボードの表示](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/view-dashboards.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDashboards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-dashboards.html)」を参照してください。

### `list-gateways`
<a name="iotsitewise_ListGateways_cli_2_topic"></a>

次のコード例は、`list-gateways` を使用する方法を示しています。

**AWS CLI**  
**すべてのゲートウェイを一覧表示するには**  
次の の`list-gateways`例では、現在のリージョンの AWS アカウントで定義されているすべてのゲートウェイを一覧表示します。  

```
aws iotsitewise list-gateways
```
出力:  

```
{
    "gatewaySummaries": [
        {
            "gatewayId": "a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE",
            "gatewayName": "ExampleCorpGateway",
            "gatewayCapabilitySummaries": [
                {
                    "capabilityNamespace": "iotsitewise:opcuacollector:1",
                    "capabilitySyncStatus": "IN_SYNC"
                }
            ],
            "creationDate": 1588369971.457,
            "lastUpdateDate": 1588369971.457
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Ingesting data using a gateway](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-gateways.html)」を参照してください。

### `list-portals`
<a name="iotsitewise_ListPortals_cli_2_topic"></a>

次のコード例は、`list-portals` を使用する方法を示しています。

**AWS CLI**  
**すべてのポータルを一覧表示するには**  
次の の`list-portals`例では、現在のリージョンの AWS アカウントで定義されているすべてのポータルを一覧表示します。  

```
aws iotsitewise list-portals
```
出力:  

```
{
    "portalSummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE",
            "name": "WindFarmPortal",
            "description": "A portal that contains wind farm projects for Example Corp.",
            "startUrl": "https://a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE.app.iotsitewise.aws",
            "creationDate": "2020-02-04T23:01:52.90248068Z",
            "lastUpdateDate": "2020-02-04T23:01:52.90248078Z",
            "roleArn": "arn:aws:iam::123456789012:role/service-role/MySiteWiseMonitorServiceRole"
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Administering your portals](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPortals](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-portals.html)」を参照してください。

### `list-project-assets`
<a name="iotsitewise_ListProjectAssets_cli_2_topic"></a>

次のコード例は、`list-project-assets` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトに関連付けられているすべてのアセットを一覧表示するには**  
次の `list-project-assets` の例では、風力発電所プロジェクトに関連付けられているすべてのアセットを一覧表示します。  

```
aws iotsitewise list-projects \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE
```
出力:  

```
{
    "assetIds": [
        "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE"
    ]
}
```
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[Adding assets to projects](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/add-assets-to-projects-sd.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProjectAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-project-assets.html)」を参照してください。

### `list-projects`
<a name="iotsitewise_ListProjects_cli_2_topic"></a>

次のコード例は、`list-projects` を使用する方法を示しています。

**AWS CLI**  
**ポータル内のすべてのプロジェクトを一覧表示するには**  
次の `list-projects` の例では、ポータルで定義されているすべてのプロジェクトを一覧表示します。  

```
aws iotsitewise list-projects \
    --portal-id a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE
```
出力:  

```
{
    "projectSummaries": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE",
            "name": "Wind Farm 1",
            "description": "Contains asset visualizations for Wind Farm #1 for Example Corp.",
            "creationDate": "2020-02-20T21:58:43.362246001Z",
            "lastUpdateDate": "2020-02-20T21:58:43.362246095Z"
        }
    ]
}
```
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[プロジェクト詳細の表示](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/view-project-details.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-projects.html)」を参照してください。

### `list-tags-for-resource`
<a name="iotsitewise_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、風力タービンアセットのすべてのタグを一覧表示します。  

```
aws iotsitewise list-tags-for-resource \
    --resource-arn arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE
```
出力:  

```
{
    "tags": {
        "Owner": "richard-roe"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[リソースへのタグ付け](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/tag-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/list-tags-for-resource.html)」を参照してください。

### `put-logging-options`
<a name="iotsitewise_PutLoggingOptions_cli_2_topic"></a>

次のコード例は、`put-logging-options` を使用する方法を示しています。

**AWS CLI**  
**ログ記録のレベルを指定するには**  
次の`put-logging-options`例では、 AWS IoT SiteWise で`INFO`レベルログ記録を有効にします。その他のレベルには、`DEBUG` と `OFF` があります。  

```
aws iotsitewise put-logging-options \
    --logging-options level=INFO
```
このコマンドでは何も出力されません。  
詳細については、「 IoT [ SiteWise ユーザーガイド」の「Monitoring AWS IoT SiteWise with Amazon CloudWatch Logs](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/monitor-cloudwatch-logs.html)」を参照してください。 *AWS IoT SiteWise *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLoggingOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/put-logging-options.html)」を参照してください。

### `tag-resource`
<a name="iotsitewise_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加**  
次の `tag-resource` の例では、風力タービンアセットに所有者タグを追加します。これにより、アセットの所有者に基づいてアセットへのアクセスを制御できます。  

```
aws iotsitewise tag-resource \
    --resource-arn arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --tags Owner=richard-roe
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[リソースへのタグ付け](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/tag-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="iotsitewise_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `untag-resource` の例では、風力タービンアセットから所有者タグを削除します。  

```
aws iotsitewise untag-resource \
    --resource-arn arn:aws:iotsitewise:us-west-2:123456789012:asset/a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --tag-keys Owner
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[リソースへのタグ付け](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/tag-resources.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/untag-resource.html)」を参照してください。

### `update-access-policy`
<a name="iotsitewise_UpdateAccessPolicy_cli_2_topic"></a>

次のコード例は、`update-access-policy` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトビューワーにプロジェクトの所有権を付与するには**  
次の `update-access-policy` の例では、プロジェクトビューワーにプロジェクトの所有権を付与するアクセスポリシーを更新します。  

```
aws iotsitewise update-access-policy \
    --access-policy-id a1b2c3d4-5678-90ab-cdef-dddddEXAMPLE \
    --cli-input-json file://update-project-viewer-access-policy.json
```
`update-project-viewer-access-policy.json` の内容:  

```
{
    "accessPolicyIdentity": {
        "user": {
            "id": "a1b2c3d4e5-a1b2c3d4-5678-90ab-cdef-bbbbbEXAMPLE"
        }
    },
    "accessPolicyPermission": "ADMINISTRATOR",
    "accessPolicyResource": {
        "project": {
            "id": "a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE"
        }
    }
}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS SiteWise Monitor アプリケーションガイド*」の「[プロジェクトの所有者を割り当てる](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/assign-project-owners.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAccessPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-access-policy.html)」を参照してください。

### `update-asset-model`
<a name="iotsitewise_UpdateAssetModel_cli_2_topic"></a>

次のコード例は、`update-asset-model` を使用する方法を示しています。

**AWS CLI**  
**アセットモデルを更新するには**  
次の `update-asset-model` の例では、風力発電所アセットモデルの説明を更新します。`update-asset-model` は既存のモデルを新しいモデルで上書きするため、この例にはモデルの既存の ID と定義が含まれています。  

```
aws iotsitewise update-asset-model \
    --cli-input-json file://update-wind-farm-model.json
```
`update-wind-farm-model.json` の内容:  

```
{
    "assetModelName": "Wind Farm Model",
    "assetModelDescription": "Represents a wind farm that comprises many wind turbines",
    "assetModelProperties": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-88888EXAMPLE",
            "name": "Region",
            "dataType": "STRING",
            "type": {
                "attribute": {}
            }
        },
        {
            "id": "a1b2c3d4-5678-90ab-cdef-99999EXAMPLE",
            "name": "Total Generated Power",
            "dataType": "DOUBLE",
            "unit": "kW",
            "type": {
                "metric": {
                    "expression": "sum(power)",
                    "variables": [
                        {
                            "name": "power",
                            "value": {
                                "hierarchyId": "a1b2c3d4-5678-90ab-cdef-77777EXAMPLE",
                                "propertyId": "a1b2c3d4-5678-90ab-cdef-66666EXAMPLE"
                            }
                        }
                    ],
                    "window": {
                        "tumbling": {
                            "interval": "1h"
                        }
                    }
                }
            }
        }
    ],
    "assetModelHierarchies": [
        {
            "id": "a1b2c3d4-5678-90ab-cdef-77777EXAMPLE",
            "name": "Wind Turbines",
            "childAssetModelId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
        }
    ]
}
```
出力:  

```
{
    "assetModelId": "a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
    "assetModelArn": "arn:aws:iotsitewise:us-west-2:123456789012:asset-model/a1b2c3d4-5678-90ab-cdef-22222EXAMPLE",
    "assetModelStatus": {
        "state": "CREATING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[アセットモデルの更新](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/update-assets-and-models.html#update-asset-models)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAssetModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-asset-model.html)」を参照してください。

### `update-asset-property`
<a name="iotsitewise_UpdateAssetProperty_cli_2_topic"></a>

次のコード例は、`update-asset-property` を使用する方法を示しています。

**AWS CLI**  
**例 1: アセットプロパティのエイリアスを更新するには**  
次の `update-asset-property` の例では、風力タービンアセットの電力プロパティエイリアスを更新します。  

```
aws iotsitewise update-asset-property \
    --asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --property-id a1b2c3d4-5678-90ab-cdef-55555EXAMPLE \
    --property-alias "/examplecorp/windfarm/1/turbine/1/power" \
    --property-notification-state DISABLED
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[アセットプロパティへの産業データストリームのマッピング](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/connect-data-streams.html)」を参照してください 。  
**例 2: アセットプロパティの通知を有効にするには**  
次の `update-asset-property` の例では、風力タービンアセットの電力プロパティのアセットプロパティ更新通知を有効にします。プロパティ値の更新は MQTT トピック `$aws/sitewise/asset-models/<assetModelId>/assets/<assetId>/properties/<propertyId>` に発行されます。各 ID はアセットプロパティのプロパティ、アセット、モデル ID に置き換えられます。  

```
aws iotsitewise update-asset-property \
    --asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --property-id a1b2c3d4-5678-90ab-cdef-66666EXAMPLE \
    --property-notification-state ENABLED \
    --property-alias "/examplecorp/windfarm/1/turbine/1/power"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[その他のサービスの操作](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/interact-with-other-services.html)」を参照してください 。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAssetProperty](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-asset-property.html)」を参照してください。

### `update-asset`
<a name="iotsitewise_UpdateAsset_cli_2_topic"></a>

次のコード例は、`update-asset` を使用する方法を示しています。

**AWS CLI**  
**アセットの名前を更新するには**  
次の `update-asset` の例では、風力タービンアセットの名前を更新します。  

```
aws iotsitewise update-asset \
    --asset-id a1b2c3d4-5678-90ab-cdef-33333EXAMPLE \
    --asset-name "Wind Turbine 2"
```
出力:  

```
{
    "assetStatus": {
        "state": "UPDATING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[アセットの更新](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/update-assets-and-models.html#update-assets)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-asset.html)」を参照してください。

### `update-dashboard`
<a name="iotsitewise_UpdateDashboard_cli_2_topic"></a>

次のコード例は、`update-dashboard` を使用する方法を示しています。

**AWS CLI**  
**ダッシュボードを更新するには**  
次の `update-dashboard` の例では、風力発電所の総発電電力が表示されるダッシュボードの折れ線グラフのタイトルを変更します。  

```
aws iotsitewise update-dashboard \
    --project-id a1b2c3d4-5678-90ab-cdef-fffffEXAMPLE \
    --dashboard-name "Wind Farm" \
    --dashboard-definition file://update-wind-farm-dashboard.json
```
`update-wind-farm-dashboard.json` の内容:  

```
{
    "widgets": [
        {
            "type": "monitor-line-chart",
            "title": "Total Generated Power",
            "x": 0,
            "y": 0,
            "height": 3,
            "width": 3,
            "metrics": [
                {
                    "label": "Power",
                    "type": "iotsitewise",
                    "assetId": "a1b2c3d4-5678-90ab-cdef-44444EXAMPLE",
                    "propertyId": "a1b2c3d4-5678-90ab-cdef-99999EXAMPLE"
                }
            ]
        }
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Creating dashboards (CLI)](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/create-dashboards-using-aws-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDashboard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-dashboard.html)」を参照してください。

### `update-gateway-capability-configuration`
<a name="iotsitewise_UpdateGatewayCapabilityConfiguration_cli_2_topic"></a>

次のコード例は、`update-gateway-capability-configuration` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイ機能を更新するには**  
次の `update-gateway-capability-configuration` の例では、次のプロパティを使用して OPC-UA ソースを設定します。  
証明書を信頼します。Basic256 アルゴリズムを使用してメッセージを保護します。SignAndEncrypt モードを使用して接続を保護します。 AWS Secrets Manager シークレットに保存されている認証情報を使用します。  

```
aws iotsitewise update-gateway-capability-configuration \
    --gateway-id a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE \
    --capability-namespace "iotsitewise:opcuacollector:1" \
    --capability-configuration file://opc-ua-capability-configuration.json
```
`opc-ua-capability-configuration.json` の内容:  

```
{
    "sources": [
        {
            "name": "Wind Farm #1",
            "endpoint": {
                "certificateTrust": {
                    "type": "TrustAny"
                },
                "endpointUri": "opc.tcp://203.0.113.0:49320",
                "securityPolicy": "BASIC256",
                "messageSecurityMode": "SIGN_AND_ENCRYPT",
                "identityProvider": {
                    "type": "Username",
                    "usernameSecretArn": "arn:aws:secretsmanager:us-west-2:123456789012:secret:greengrass-windfarm1-auth-1ABCDE"
                },
                "nodeFilterRules": []
            },
            "measurementDataStreamPrefix": ""
        }
    ]
}
```
出力:  

```
{
    "capabilityNamespace": "iotsitewise:opcuacollector:1",
    "capabilitySyncStatus": "OUT_OF_SYNC"
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Configuring data sources](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/configure-sources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGatewayCapabilityConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-gateway-capability-configuration.html)」を参照してください。

### `update-gateway`
<a name="iotsitewise_UpdateGateway_cli_2_topic"></a>

次のコード例は、`update-gateway` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイの名前を更新するには**  
次の `update-gateway` の例では、ゲートウェイの名前を更新します。  

```
aws iotsitewise update-gateway \
    --gateway-id a1b2c3d4-5678-90ab-cdef-1a1a1EXAMPLE \
    --gateway-name ExampleCorpGateway1
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Ingesting data using a gateway](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/gateways.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-gateway.html)」を参照してください。

### `update-portal`
<a name="iotsitewise_UpdatePortal_cli_2_topic"></a>

次のコード例は、`update-portal` を使用する方法を示しています。

**AWS CLI**  
**ポータルの詳細を更新するには**  
次の `update-portal` の例では、風力発電所会社のウェブポータルを更新します。  

```
aws iotsitewise update-portal \
    --portal-id a1b2c3d4-5678-90ab-cdef-aaaaaEXAMPLE \
    --portal-name WindFarmPortal \
    --portal-description "A portal that contains wind farm projects for Example Corp." \
    --portal-contact-email support@example.com \
    --role-arn arn:aws:iam::123456789012:role/MySiteWiseMonitorServiceRole
```
出力:  

```
{
    "portalStatus": {
        "state": "UPDATING"
    }
}
```
詳細については、「*AWS IoT SiteWise ユーザーガイド*」の「[Administering your portals](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/administer-portals.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePortal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-portal.html)」を参照してください。

### `update-project`
<a name="iotsitewise_UpdateProject_cli_2_topic"></a>

次のコード例は、`update-project` を使用する方法を示しています。

**AWS CLI**  
**プロジェクトの詳細を更新するには**  
次の `update-project` の例では、風力発電所プロジェクトを更新します。  

```
aws iotsitewise update-project \
    --project-id a1b2c3d4-5678-90ab-cdef-eeeeeEXAMPLE \
    --project-name "Wind Farm 1" \
    --project-description "Contains asset visualizations for Wind Farm #1 for Example Corp."
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT SiteWise Monitor アプリケーションガイド*」の「[プロジェクト詳細の変更](https://docs.aws.amazon.com/iot-sitewise/latest/appguide/edit-project-details.html)を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateProject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotsitewise/update-project.html)」を参照してください。

# AWS IoT Things Graph を使用した の例 AWS CLI
<a name="cli_2_iotthingsgraph_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT Things Graph。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-entity-to-thing`
<a name="iotthingsgraph_AssociateEntityToThing_cli_2_topic"></a>

次のコード例は、`associate-entity-to-thing` を使用する方法を示しています。

**AWS CLI**  
**モノをデバイスに関連付けるには**  
次の `associate-entity-to-thing` の例では、モノをデバイスに関連付けます。この例では、パブリック名前空間にあるモーションセンサーデバイスを使用しています。  

```
aws iotthingsgraph associate-entity-to-thing \
    --thing-name "MotionSensorName" \
    --entity-id "urn:tdm:aws/examples:Device:HCSR501MotionSensor"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[モデルの作成とアップロード](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models-gs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateEntityToThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/associate-entity-to-thing.html)」を参照してください。

### `create-flow-template`
<a name="iotthingsgraph_CreateFlowTemplate_cli_2_topic"></a>

次のコード例は、`create-flow-template` を使用する方法を示しています。

**AWS CLI**  
**フローを作成するには**  
次の `create-flow-template` の例では、フロー (ワークフロー) を作成します。`MyFlowDefinition` という値は、フローをモデル化する GraphQL です。  

```
aws iotthingsgraph create-flow-template \
    --definition language=GRAPHQL,text="MyFlowDefinition"
```
出力:  

```
{
    "summary": {
        "createdAt": 1559248067.545,
        "id": "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow",
        "revisionNumber": 1
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[フローでの作業](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFlowTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/create-flow-template.html)」を参照してください。

### `create-system-instance`
<a name="iotthingsgraph_CreateSystemInstance_cli_2_topic"></a>

次のコード例は、`create-system-instance` を使用する方法を示しています。

**AWS CLI**  
**システムインスタンスを作成するには**  
次の `create-system-instance` の例では、システムインスタンスを作成します。`MySystemInstanceDefinition` という値は、システムインスタンスをモデル化する GraphQL です。  

```
aws iotthingsgraph create-system-instance -\
    -definition language=GRAPHQL,text="MySystemInstanceDefinition" \
    --target CLOUD \
    --flow-actions-role-arn myRoleARN
```
出力:  

```
{
    "summary": {
        "id": "urn:tdm:us-west-2/123456789012/default:Deployment:Room218",
        "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room218",
        "status": "NOT_DEPLOYED",
        "target": "CLOUD",
        "createdAt": 1559249315.208,
        "updatedAt": 1559249315.208
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムとフロー設定の使用](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSystemInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/create-system-instance.html)」を参照してください。

### `create-system-template`
<a name="iotthingsgraph_CreateSystemTemplate_cli_2_topic"></a>

次のコード例は、`create-system-template` を使用する方法を示しています。

**AWS CLI**  
**システムを作成するには**  
次の `create-system-template` の例では、システムを作成します。MySystemDefinition という値は、システムをモデル化する GraphQL です。  

```
aws iotthingsgraph create-system-template \
    --definition language=GRAPHQL,text="MySystemDefinition"
```
出力:  

```
{
    "summary": {
        "createdAt": 1559249776.254,
        "id": "urn:tdm:us-west-2/123456789012/default:System:MySystem",
        "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:System/default/MySystem",
        "revisionNumber": 1
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムの作成](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy-systems.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSystemTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/create-system-template.html)」を参照してください。

### `delete-flow-template`
<a name="iotthingsgraph_DeleteFlowTemplate_cli_2_topic"></a>

次のコード例は、`delete-flow-template` を使用する方法を示しています。

**AWS CLI**  
**フローを削除するには**  
次の `delete-flow-template` の例では、フロー (ワークフロー) を削除します。  

```
aws iotthingsgraph delete-flow-template \
    --id "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph エンティティ、フロー、システム、デプロイのライフサイクル管理](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-lifecycle.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFlowTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/delete-flow-template.html)」を参照してください。

### `delete-namespace`
<a name="iotthingsgraph_DeleteNamespace_cli_2_topic"></a>

次のコード例は、`delete-namespace` を使用する方法を示しています。

**AWS CLI**  
**名前空間を削除するには**  
次の `delete-namespace` の例では、名前空間を削除します。  

```
aws iotthingsgraph delete-namespace
```
出力:  

```
{
   "namespaceArn": "arn:aws:iotthingsgraph:us-west-2:123456789012",
   "namespaceName": "us-west-2/123456789012/default"
}
```
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph エンティティ、フロー、システム、デプロイのライフサイクル管理](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-lifecycle.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/delete-namespace.html)」を参照してください。

### `delete-system-instance`
<a name="iotthingsgraph_DeleteSystemInstance_cli_2_topic"></a>

次のコード例は、`delete-system-instance` を使用する方法を示しています。

**AWS CLI**  
**システムインスタンスを削除するには**  
次の `delete-system-instance` の例では、システムインスタンスを削除します。  

```
aws iotthingsgraph delete-system-instance \
    --id "urn:tdm:us-west-2/123456789012/default:Deployment:Room218"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph エンティティ、フロー、システム、デプロイのライフサイクル管理](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-lifecycle.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSystemInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/delete-system-instance.html)」を参照してください。

### `delete-system-template`
<a name="iotthingsgraph_DeleteSystemTemplate_cli_2_topic"></a>

次のコード例は、`delete-system-template` を使用する方法を示しています。

**AWS CLI**  
**システムを削除するには**  
次の `delete-system-template` の例では、システムを削除します。  

```
aws iotthingsgraph delete-system-template \
    --id "urn:tdm:us-west-2/123456789012/default:System:MySystem"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph エンティティ、フロー、システム、デプロイのライフサイクル管理](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-lifecycle.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSystemTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/delete-system-template.html)」を参照してください。

### `deploy-system-instance`
<a name="iotthingsgraph_DeploySystemInstance_cli_2_topic"></a>

次のコード例は、`deploy-system-instance` を使用する方法を示しています。

**AWS CLI**  
**システムインスタンスをデプロイするには**  
次の `delete-system-template` の例では、システムインスタンスをデプロイします。  

```
aws iotthingsgraph deploy-system-instance \
    --id "urn:tdm:us-west-2/123456789012/default:Deployment:Room218"
```
出力:  

```
{
   "summary": {
      "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment:Room218",
      "createdAt": 1559249776.254,
      "id": "urn:tdm:us-west-2/123456789012/default:Deployment:Room218",
      "status": "DEPLOYED_IN_TARGET",
      "target": "CLOUD",
      "updatedAt": 1559249776.254
   }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムとフロー設定の使用](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeploySystemInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/deploy-system-instance.html)」を参照してください。

### `deprecate-flow-template`
<a name="iotthingsgraph_DeprecateFlowTemplate_cli_2_topic"></a>

次のコード例は、`deprecate-flow-template` を使用する方法を示しています。

**AWS CLI**  
**フローを非推奨にするには**  
次の `deprecate-flow-template` の例では、フロー (ワークフロー) を非推奨にします。  

```
aws iotthingsgraph deprecate-flow-template \
    --id "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph エンティティ、フロー、システム、デプロイのライフサイクル管理](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-lifecycle.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeprecateFlowTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/deprecate-flow-template.html)」を参照してください。

### `deprecate-system-template`
<a name="iotthingsgraph_DeprecateSystemTemplate_cli_2_topic"></a>

次のコード例は、`deprecate-system-template` を使用する方法を示しています。

**AWS CLI**  
**システムを非推奨にするには**  
次の `deprecate-system-template` の例では、システムを非推奨にします。  

```
aws iotthingsgraph deprecate-system-template \
    --id "urn:tdm:us-west-2/123456789012/default:System:MySystem"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph エンティティ、フロー、システム、デプロイのライフサイクル管理](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-lifecycle.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeprecateSystemTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/deprecate-system-template.html)」を参照してください。

### `describe-namespace`
<a name="iotthingsgraph_DescribeNamespace_cli_2_topic"></a>

次のコード例は、`describe-namespace` を使用する方法を示しています。

**AWS CLI**  
**名前空間の説明を取得するには**  
次の `describe-namespace` の例では、名前空間の説明を取得します。  

```
aws iotthingsgraph describe-namespace
```
出力:  

```
{
    "namespaceName": "us-west-2/123456789012/default",
    "trackingNamespaceName": "aws",
    "trackingNamespaceVersion": 1,
    "namespaceVersion": 5
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[名前空間](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-whatis-namespace.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNamespace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/describe-namespace.html)」を参照してください。

### `dissociate-entity-from-thing`
<a name="iotthingsgraph_DissociateEntityFromThing_cli_2_topic"></a>

次のコード例は、`dissociate-entity-from-thing` を使用する方法を示しています。

**AWS CLI**  
**デバイスからモノの関連付けを解除するには**  
次の `dissociate-entity-from-thing` の例では、デバイスからモノの関連付けを解除します。  

```
aws iotthingsgraph dissociate-entity-from-thing \
    --thing-name "MotionSensorName" \
    --entity-type "DEVICE"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[モデルの作成とアップロード](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models-gs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DissociateEntityFromThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/dissociate-entity-from-thing.html)」を参照してください。

### `get-entities`
<a name="iotthingsgraph_GetEntities_cli_2_topic"></a>

次のコード例は、`get-entities` を使用する方法を示しています。

**AWS CLI**  
**エンティティの定義を取得するには**  
次の `get-entities` の例では、デバイスモデルの定義を取得します。  

```
aws iotthingsgraph get-entities \
    --ids "urn:tdm:aws/examples:DeviceModel:MotionSensor"
```
出力:  

```
{
    "descriptions": [
        {
            "id": "urn:tdm:aws/examples:DeviceModel:MotionSensor",
            "type": "DEVICE_MODEL",
            "createdAt": 1559256190.599,
            "definition": {
                "language": "GRAPHQL",
                "text": "##\n# Specification of motion sensor devices interface.\n##\ntype MotionSensor @deviceModel(id: \"urn:tdm:aws/examples:deviceModel:MotionSensor\",\n        capability: \"urn:tdm:aws/examples:capability:MotionSensorCapability\") {ignore:void}"
            }
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[モデルの作成とアップロード](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models-gs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-entities.html)」を参照してください。

### `get-flow-template-revisions`
<a name="iotthingsgraph_GetFlowTemplateRevisions_cli_2_topic"></a>

次のコード例は、`get-flow-template-revisions` を使用する方法を示しています。

**AWS CLI**  
**フローに関するリビジョン情報を取得するには**  
次の `get-flow-template-revisions` の例では、フロー (ワークフロー) に関するリビジョン情報を取得します。  

```
aws iotthingsgraph get-flow-template-revisions \
    --id urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow
```
出力:  

```
{
    "summaries": [
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow",
            "revisionNumber": 1,
            "createdAt": 1559247540.292
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[フローでの作業](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFlowTemplateRevisions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-flow-template-revisions.html)」を参照してください。

### `get-flow-template`
<a name="iotthingsgraph_GetFlowTemplate_cli_2_topic"></a>

次のコード例は、`get-flow-template` を使用する方法を示しています。

**AWS CLI**  
**フロー定義を取得するには**  
次の `get-flow-template` の例では、フロー (ワークフロー) の定義を取得します。  

```
aws iotthingsgraph get-flow-template \
    --id "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow"
```
出力:  

```
{
    "description": {
        "summary": {
            "id": "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow",
            "revisionNumber": 1,
            "createdAt": 1559247540.292
        },
        "definition": {
            "language": "GRAPHQL",
            "text": "{\nquery MyFlow($camera: string!, $screen: string!) @workflowType(id: \"urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow\") @annotation(type: \"tgc:FlowEvent\", id: \"sledged790c1b2bcd949e09da0c9bfc077f79d\", x: 1586, y: 653) @triggers(definition: \"{MotionSensor(description: \\\"\\\") @position(x: 1045, y: 635.6666564941406) {\\n  condition(expr: \\\"devices[name == \\\\\\\"motionSensor\\\\\\\"].events[name == \\\\\\\"StateChanged\\\\\\\"].lastEvent\\\")\\n  action(expr: \\\"\\\")\\n}}\") {\n  variables {\n    cameraResult @property(id: \"urn:tdm:aws/examples:property:CameraStateProperty\")\n  }\n  steps {\n    step(name: \"Camera\", outEvent: [\"sledged790c1b2bcd949e09da0c9bfc077f79d\"]) @position(x: 1377, y: 638.6666564941406) {\n      DeviceActivity(deviceModel: \"urn:tdm:aws/examples:deviceModel:Camera\", out: \"cameraResult\", deviceId: \"${camera}\") {\n        capture\n      }\n    }\n    step(name: \"Screen\", inEvent: [\"sledged790c1b2bcd949e09da0c9bfc077f79d\"]) @position(x: 1675.6666870117188, y: 637.9999847412109) {\n      DeviceActivity(deviceModel: \"urn:tdm:aws/examples:deviceModel:Screen\", deviceId: \"${screen}\") {\n        display(imageUrl: \"${cameraResult.lastClickedImage}\")\n      }\n    }\n  }\n}\n}"
        },
        "validatedNamespaceVersion": 5
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[フローでの作業](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFlowTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-flow-template.html)」を参照してください。

### `get-namespace-deletion-status`
<a name="iotthingsgraph_GetNamespaceDeletionStatus_cli_2_topic"></a>

次のコード例は、`get-namespace-deletion-status` を使用する方法を示しています。

**AWS CLI**  
**名前空間削除タスクのステータスを取得するには**  
次の `get-namespace-deletion-status` の例では、名前空間削除タスクのステータスを取得します。  

```
aws iotthingsgraph get-namespace-deletion-status
```
出力:  

```
{
   "namespaceArn": "arn:aws:iotthingsgraph:us-west-2:123456789012",
   "namespaceName": "us-west-2/123456789012/default"
   "status": "SUCCEEDED "
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[名前空間](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-whatis-namespace.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetNamespaceDeletionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-namespace-deletion-status.html)」を参照してください。

### `get-system-instance`
<a name="iotthingsgraph_GetSystemInstance_cli_2_topic"></a>

次のコード例は、`get-system-instance` を使用する方法を示しています。

**AWS CLI**  
**システムインスタンスを取得するには**  
次の `get-system-instance` の例では、システムインスタンスの定義を取得します。  

```
aws iotthingsgraph get-system-instance \
    --id "urn:tdm:us-west-2/123456789012/default:Deployment:Room218"
```
出力:  

```
{
    "description": {
        "summary": {
            "id": "urn:tdm:us-west-2/123456789012/default:Deployment:Room218",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room218",
            "status": "NOT_DEPLOYED",
            "target": "CLOUD",
            "createdAt": 1559249315.208,
            "updatedAt": 1559249315.208
        },
        "definition": {
            "language": "GRAPHQL",
            "text": "{\r\nquery Room218 @deployment(id: \"urn:tdm:us-west-2/123456789012/default:Deployment:Room218\", systemId: \"urn:tdm:us-west-2/123456789012/default:System:SecurityFlow\") {\r\n    motionSensor(deviceId: \"MotionSensorName\")\r\n    screen(deviceId: \"ScreenName\")\r\n    camera(deviceId: \"CameraName\") \r\n    triggers {MotionEventTrigger(description: \"a trigger\") {  \r\n    condition(expr: \"devices[name == 'motionSensor'].events[name == 'StateChanged'].lastEvent\") \r\n    action(expr: \"ThingsGraph.startFlow('SecurityFlow', bindings[name == 'camera'].deviceId, bindings[name == 'screen'].deviceId)\")\r\n    }\r\n   }\r\n  }\r\n  }"
        },
        "metricsConfiguration": {
            "cloudMetricEnabled": false
        },
        "validatedNamespaceVersion": 5,
        "flowActionsRoleArn": "arn:aws:iam::123456789012:role/ThingsGraphRole"
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムとフロー設定の使用](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSystemInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-system-instance.html)」を参照してください。

### `get-system-template-revisions`
<a name="iotthingsgraph_GetSystemTemplateRevisions_cli_2_topic"></a>

次のコード例は、`get-system-template-revisions` を使用する方法を示しています。

**AWS CLI**  
**システムに関するリビジョン情報を取得するには**  
次の `get-system-template-revisions` の例では、システムに関するリビジョン情報を取得します。  

```
aws iotthingsgraph get-system-template-revisions \
    --id "urn:tdm:us-west-2/123456789012/default:System:MySystem"
```
出力:  

```
{
    "summaries": [
        {
            "id": "urn:tdm:us-west-2/123456789012/default:System:MySystem",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:System/default/MySystem",
            "revisionNumber": 1,
            "createdAt": 1559247540.656
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムとフロー設定の使用](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSystemTemplateRevisions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-system-template-revisions.html)」を参照してください。

### `get-system-template`
<a name="iotthingsgraph_GetSystemTemplate_cli_2_topic"></a>

次のコード例は、`get-system-template` を使用する方法を示しています。

**AWS CLI**  
**システムを取得するには**  
次の `get-system-template` の例では、システムの定義を取得します。  

```
aws iotthingsgraph get-system-template \
    --id "urn:tdm:us-west-2/123456789012/default:System:MySystem"
```
出力:  

```
{
    "description": {
        "summary": {
            "id": "urn:tdm:us-west-2/123456789012/default:System:MySystem",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:System/default/MyFlow",
            "revisionNumber": 1,
            "createdAt": 1559247540.656
        },
        "definition": {
            "language": "GRAPHQL",
            "text": "{\ntype MySystem @systemType(id: \"urn:tdm:us-west-2/123456789012/default:System:MySystem\", description: \"\") {\n  camera: Camera @thing(id: \"urn:tdm:aws/examples:deviceModel:Camera\")\n  screen: Screen @thing(id: \"urn:tdm:aws/examples:deviceModel:Screen\")\n  motionSensor: MotionSensor @thing(id: \"urn:tdm:aws/examples:deviceModel:MotionSensor\")\n  MyFlow: MyFlow @workflow(id: \"urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow\")\n}\n}"
        },
        "validatedNamespaceVersion": 5
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムとフロー設定の使用](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSystemTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-system-template.html)」を参照してください。

### `get-upload-status`
<a name="iotthingsgraph_GetUploadStatus_cli_2_topic"></a>

次のコード例は、`get-upload-status` を使用する方法を示しています。

**AWS CLI**  
**エンティティアップロードのステータスを取得するには**  
次の `get-upload-status` の例では、エンティティアップロードオペレーションのステータスを取得します。`MyUploadId` という値は、`upload-entity-definitions` オペレーションによって返される ID 値です。  

```
aws iotthingsgraph get-upload-status \
    --upload-id "MyUploadId"
```
出力:  

```
{
    "namespaceName": "us-west-2/123456789012/default",
    "namespaceVersion": 5,
    "uploadId": "f6294f1e-b109-4bbe-9073-f451a2dda2da",
    "uploadStatus": "SUCCEEDED"
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[エンティティのモデリング](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-modelmanagement.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetUploadStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/get-upload-status.html)」を参照してください。

### `list-flow-execution-messages`
<a name="iotthingsgraph_ListFlowExecutionMessages_cli_2_topic"></a>

次のコード例は、`list-flow-execution-messages` を使用する方法を示しています。

**AWS CLI**  
**フロー実行中のイベントに関する情報を取得するには**  
次の `list-flow-execution-messages` の例では、フロー実行中のイベントに関する情報を取得します。  

```
aws iotthingsgraph list-flow-execution-messages \
    --flow-execution-id "urn:tdm:us-west-2/123456789012/default:Workflow:SecurityFlow_2019-05-11T19:39:55.317Z_MotionSensor_69b151ad-a611-42f5-ac21-fe537f9868ad"
```
出力:  

```
{
    "messages": [
        {
         "eventType": "EXECUTION_STARTED",
         "messageId": "f6294f1e-b109-4bbe-9073-f451a2dda2da",
         "payload": "Flow execution started",
         "timestamp": 1559247540.656
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[フローでの作業](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFlowExecutionMessages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/list-flow-execution-messages.html)」を参照してください。

### `list-tags-for-resource`
<a name="iotthingsgraph_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのすべてのタグを一覧表示するには**  
次の の`list-tags-for-resource`例では、 AWS IoT Things Graph リソースのすべてのタグを一覧表示します。  

```
aws iotthingsgraph list-tags-for-resource \
    --resource-arn "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room218"
```
出力:  

```
{
   "tags": [
      {
         "key": "Type",
         "value": "Residential"
      }
   ]
}
```
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph リソースのタグ付け](https://docs.aws.amazon.com/thingsgraph/latest/ug/tagging-tg.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/list-tags-for-resource.html)」を参照してください。

### `search-entities`
<a name="iotthingsgraph_SearchEntities_cli_2_topic"></a>

次のコード例は、`search-entities` を使用する方法を示しています。

**AWS CLI**  
**エンティティを検索するには**  
次の `search-entities` の例では、タイプが `EVENT` のすべてのエンティティを検索します。  

```
aws iotthingsgraph search-entities \
    --entity-types "EVENT"
```
出力:  

```
{
    "descriptions": [
        {
            "id": "urn:tdm:aws/examples:Event:MotionSensorEvent",
            "type": "EVENT",
            "definition": {
                "language": "GRAPHQL",
                "text": "##\n# Description of events emitted by motion sensor.\n##\ntype MotionSensorEvent @eventType(id: \"urn:tdm:aws/examples:event:MotionSensorEvent\",\n            payload: \"urn:tdm:aws/examples:property:MotionSensorStateProperty\") {ignore:void}"
            }
        },
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Event:CameraClickedEventV2",
            "type": "EVENT",
            "definition": {
                "language": "GRAPHQL",
                "text": "type CameraClickedEventV2 @eventType(id: \"urn:tdm:us-west-2/123456789012/default:event:CameraClickedEventV2\",\r\npayload: \"urn:tdm:aws:Property:Boolean\"){ignore:void}"
            }
        },
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Event:MotionSensorEventV2",
            "type": "EVENT",
            "definition": {
                "language": "GRAPHQL",
                "text": "# Event emitted by the motion sensor.\r\ntype MotionSensorEventV2 @eventType(id: \"urn:tdm:us-west-2/123456789012/default:event:MotionSensorEventV2\",\r\npayload: \"urn:tdm:us-west-2/123456789012/default:property:MotionSensorStateProperty2\") {ignore:void}"
            }
        }
    ],
    "nextToken": "urn:tdm:us-west-2/123456789012/default:Event:MotionSensorEventV2"
}
```
詳細については、「AWS IoT Things Graph ユーザーガイド」の「[AWS IoT Things Graph データモデルのリファレンス](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchEntities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/search-entities.html)」を参照してください。

### `search-flow-executions`
<a name="iotthingsgraph_SearchFlowExecutions_cli_2_topic"></a>

次のコード例は、`search-flow-executions` を使用する方法を示しています。

**AWS CLI**  
**フロー実行を検索するには**  
次の `search-flow-executions` の例では、指定されたシステムインスタンス内のフローのすべての実行を検索します。  

```
aws iotthingsgraph search-flow-executions \
    --system-instance-id "urn:tdm:us-west-2/123456789012/default:Deployment:Room218"
```
出力:  

```
{
   "summaries": [
      {
         "createdAt": 1559247540.656,
         "flowExecutionId": "f6294f1e-b109-4bbe-9073-f451a2dda2da",
         "flowTemplateId": "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow",
         "status": "RUNNING ",
         "systemInstanceId": "urn:tdm:us-west-2/123456789012/default:System:MySystem",
         "updatedAt": 1559247540.656
      }
   ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムとフロー設定の使用](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchFlowExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/search-flow-executions.html)」を参照してください。

### `search-flow-templates`
<a name="iotthingsgraph_SearchFlowTemplates_cli_2_topic"></a>

次のコード例は、`search-flow-templates` を使用する方法を示しています。

**AWS CLI**  
**フロー (またはワークフロー) を検索するには**  
次の `search-flow-templates` の例では、Camera デバイスモデルを含むすべてのフロー (ワークフロー) を検索します。  

```
aws iotthingsgraph search-flow-templates \
    --filters name="DEVICE_MODEL_ID",value="urn:tdm:aws/examples:DeviceModel:Camera"
```
出力:  

```
{
    "summaries": [
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow",
            "revisionNumber": 1,
            "createdAt": 1559247540.292
        },
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Workflow:SecurityFlow",
            "revisionNumber": 3,
            "createdAt": 1548283099.27
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[フローでの作業](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchFlowTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/search-flow-templates.html)」を参照してください。

### `search-system-instances`
<a name="iotthingsgraph_SearchSystemInstances_cli_2_topic"></a>

次のコード例は、`search-system-instances` を使用する方法を示しています。

**AWS CLI**  
**システムインスタンスを検索するには**  
次の `search-system-instances` の例では、指定されたシステムを含むすべてのシステムインスタンスを検索します。  

```
aws iotthingsgraph search-system-instances \
    --filters name="SYSTEM_TEMPLATE_ID",value="urn:tdm:us-west-2/123456789012/default:System:SecurityFlow"
```
出力:  

```
{
    "summaries": [
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Deployment:DeploymentForSample",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/DeploymentForSample",
            "status": "NOT_DEPLOYED",
            "target": "GREENGRASS",
            "greengrassGroupName": "ThingsGraphGrnGr",
            "createdAt": 1555716314.707,
            "updatedAt": 1555716314.707
        },
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Deployment:MockDeployment",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/MockDeployment",
            "status": "DELETED_IN_TARGET",
            "target": "GREENGRASS",
            "greengrassGroupName": "ThingsGraphGrnGr",
            "createdAt": 1549416462.049,
            "updatedAt": 1549416722.361,
            "greengrassGroupId": "01d04b07-2a51-467f-9d03-0c90b3cdcaaf",
            "greengrassGroupVersionId": "7365aed7-2d3e-4d13-aad8-75443d45eb05"
        },
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Deployment:MockDeployment2",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/MockDeployment2",
            "status": "DEPLOYED_IN_TARGET",
            "target": "GREENGRASS",
            "greengrassGroupName": "ThingsGraphGrnGr",
            "createdAt": 1549572385.774,
            "updatedAt": 1549572418.408,
            "greengrassGroupId": "01d04b07-2a51-467f-9d03-0c90b3cdcaaf",
            "greengrassGroupVersionId": "bfa70ab3-2bf7-409c-a4d4-bc8328ae5b86"
        },
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Deployment:Room215",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room215",
            "status": "NOT_DEPLOYED",
            "target": "GREENGRASS",
            "greengrassGroupName": "ThingsGraphGG",
            "createdAt": 1547056918.413,
            "updatedAt": 1547056918.413
        },
        {
            "id": "urn:tdm:us-west-2/123456789012/default:Deployment:Room218",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room218",
            "status": "NOT_DEPLOYED",
            "target": "CLOUD",
            "createdAt": 1559249315.208,
            "updatedAt": 1559249315.208
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムとフロー設定の使用](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchSystemInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/search-system-instances.html)」を参照してください。

### `search-system-templates`
<a name="iotthingsgraph_SearchSystemTemplates_cli_2_topic"></a>

次のコード例は、`search-system-templates` を使用する方法を示しています。

**AWS CLI**  
**システムを検索するには**  
次の `search-system-templates` の例では、指定されたフローを含むすべてのシステムを検索します。  

```
aws iotthingsgraph search-system-templates \
    --filters name="FLOW_TEMPLATE_ID",value="urn:tdm:us-west-2/123456789012/default:Workflow:SecurityFlow"
```
出力:  

```
{
    "summaries": [
        {
            "id": "urn:tdm:us-west-2/123456789012/default:System:SecurityFlow",
            "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:System/default/SecurityFlow",
            "revisionNumber": 1,
            "createdAt": 1548283099.433
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[フローでの作業](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchSystemTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/search-system-templates.html)」を参照してください。

### `search-things`
<a name="iotthingsgraph_SearchThings_cli_2_topic"></a>

次のコード例は、`search-things` を使用する方法を示しています。

**AWS CLI**  
**デバイスとデバイスモデルに関連付けられているモノを検索するには**  
次の `search-things` の例では、HCSR501MotionSensor デバイスに関連付けられているすべてのモノを検索します。  

```
aws iotthingsgraph search-things \
    --entity-id "urn:tdm:aws/examples:Device:HCSR501MotionSensor"
```
出力:  

```
{
    "things": [
        {
            "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MotionSensor1",
            "thingName": "MotionSensor1"
        },
        {
            "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/TG_MS",
            "thingName": "TG_MS"
        }
    ]
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[モデルの作成とアップロード](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-models-gs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchThings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/search-things.html)」を参照してください。

### `tag-resource`
<a name="iotthingsgraph_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを作成するには**  
次の `tag-resource` の例では、指定されたリソースのタグを作成します。  

```
aws iotthingsgraph tag-resource \
    --resource-arn "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room218" \
    --tags key="Type",value="Residential"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph リソースのタグ付け](https://docs.aws.amazon.com/thingsgraph/latest/ug/tagging-tg.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/tag-resource.html)」を参照してください。

### `undeploy-system-instance`
<a name="iotthingsgraph_UndeploySystemInstance_cli_2_topic"></a>

次のコード例は、`undeploy-system-instance` を使用する方法を示しています。

**AWS CLI**  
**ターゲットからシステムインスタンスをデプロイ解除するには**  
次の `undeploy-system-instance` の例では、ターゲットからシステムインスタンスを削除します。  

```
aws iotthingsgraph undeploy-system-instance \
    --id "urn:tdm:us-west-2/123456789012/default:Deployment:Room215"
```
出力:  

```
{
    "summary": {
        "id": "urn:tdm:us-west-2/123456789012/default:Deployment:Room215",
        "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room215",
        "status": "PENDING_DELETE",
        "target": "GREENGRASS",
        "greengrassGroupName": "ThingsGraphGrnGr",
        "createdAt": 1553189694.255,
        "updatedAt": 1559344549.601,
        "greengrassGroupId": "01d04b07-2a51-467f-9d03-0c90b3cdcaaf",
        "greengrassGroupVersionId": "731b371d-d644-4b67-ac64-3934e99b75d7"
    }
}
```
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph エンティティ、フロー、システム、デプロイのライフサイクル管理](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-lifecycle.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UndeploySystemInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/undeploy-system-instance.html)」を参照してください。

### `untag-resource`
<a name="iotthingsgraph_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを削除するには**  
次の `untag-resource` の例では、指定されたリソースのタグを削除します。  

```
aws iotthingsgraph untag-resource \
    --resource-arn "arn:aws:iotthingsgraph:us-west-2:123456789012:Deployment/default/Room218" \
    --tag-keys "Type"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT Things Graph ユーザーガイド」の「IoT Things Graph リソースのタグ付け](https://docs.aws.amazon.com/thingsgraph/latest/ug/tagging-tg.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/untag-resource.html)」を参照してください。

### `update-flow-template`
<a name="iotthingsgraph_UpdateFlowTemplate_cli_2_topic"></a>

次のコード例は、`update-flow-template` を使用する方法を示しています。

**AWS CLI**  
**フローを更新するには**  
次の `update-flow-template` の例では、フロー (ワークフロー) を更新します。`MyFlowDefinition` という値は、フローをモデル化する GraphQL です。  

```
aws iotthingsgraph update-flow-template \
    --id "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow" \
    --definition language=GRAPHQL,text="MyFlowDefinition"
```
出力:  

```
{
    "summary": {
        "createdAt": 1559248067.545,
        "id": "urn:tdm:us-west-2/123456789012/default:Workflow:MyFlow",
        "revisionNumber": 2
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[フローでの作業](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-workflows.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFlowTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/update-flow-template.html)」を参照してください。

### `update-system-template`
<a name="iotthingsgraph_UpdateSystemTemplate_cli_2_topic"></a>

次のコード例は、`update-system-template` を使用する方法を示しています。

**AWS CLI**  
**システムを更新するには**  
次の `update-system-template` の例では、システムを更新します。`MySystemDefinition` という値は、システムをモデル化する GraphQL です。  

```
aws iotthingsgraph update-system-template \
    --id "urn:tdm:us-west-2/123456789012/default:System:MySystem" \
    --definition language=GRAPHQL,text="MySystemDefinition"
```
出力:  

```
{
    "summary": {
        "createdAt": 1559249776.254,
        "id": "urn:tdm:us-west-2/123456789012/default:System:MySystem",
        "arn": "arn:aws:iotthingsgraph:us-west-2:123456789012:System/default/MySystem",
        "revisionNumber": 2
    }
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[システムの作成](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-sysdeploy-systems.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSystemTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/update-system-template.html)」を参照してください。

### `upload-entity-definitions`
<a name="iotthingsgraph_UploadEntityDefinitions_cli_2_topic"></a>

次のコード例は、`upload-entity-definitions` を使用する方法を示しています。

**AWS CLI**  
**エンティティ定義をアップロードするには**  
次の `upload-entity-definitions` の例では、エンティティ定義を名前空間にアップロードします。`MyEntityDefinitions` という値は、エンティティをモデル化する GraphQL です。  

```
aws iotthingsgraph upload-entity-definitions \
    --document language=GRAPHQL,text="MyEntityDefinitions"
```
出力:  

```
{
    "uploadId": "f6294f1e-b109-4bbe-9073-f451a2dda2da"
}
```
詳細については、「*AWS IoT Things Graph ユーザーガイド*」の「[エンティティのモデリング](https://docs.aws.amazon.com/thingsgraph/latest/ug/iot-tg-modelmanagement.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadEntityDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotthingsgraph/upload-entity-definitions.html)」を参照してください。

# AWS IoT Wireless を使用した の例 AWS CLI
<a name="cli_2_iot-wireless_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT Wireless。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-aws-account-with-partner-account`
<a name="iot-wireless_AssociateAwsAccountWithPartnerAccount_cli_2_topic"></a>

次の例は、`associate-aws-account-with-partner-account` を使用する方法を説明しています。

**AWS CLI**  
**パートナーアカウントを AWS アカウントに関連付けるには**  
次の`associate-aws-account-with-partner-account`例では、次の Sidewalk アカウントの認証情報を AWS アカウントに関連付けます。  

```
aws iotwireless associate-aws-account-with-partner-account \
    --sidewalk AmazonId="12345678901234",AppServerPrivateKey="a123b45c6d78e9f012a34cd5e6a7890b12c3d45e6f78a1b234c56d7e890a1234"
```
出力:  

```
{
    "Sidewalk": {
        "AmazonId": "12345678901234",
        "AppServerPrivateKey": "a123b45c6d78e9f012a34cd5e6a7890b12c3d45e6f78a1b234c56d7e890a1234"
    }
}
```
詳細については、「 IoT デベロッパーガイド」の[「Amazon Sidewalk Integration for AWS IoT Core](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sidewalk.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateAwsAccountWithPartnerAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/associate-aws-account-with-partner-account.html)」を参照してください。

### `associate-wireless-device-with-thing`
<a name="iot-wireless_AssociateWirelessDeviceWithThing_cli_2_topic"></a>

次のコード例は、`associate-wireless-device-with-thing` を使用する方法を示しています。

**AWS CLI**  
**モノをワイヤレスデバイスに関連付けるには**  
次の `associate-wireless-device-with-thing` の例では、指定された ID を持つワイヤレスデバイスにモノを関連付けます。  

```
aws iotwireless associate-wireless-device-with-thing \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d" \
    --thing-arn "arn:aws:iot:us-east-1:123456789012:thing/MyIoTWirelessThing"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にゲートウェイとワイヤレスデバイスを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-onboard-devices.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateWirelessDeviceWithThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/associate-wireless-device-with-thing.html)」を参照してください。

### `associate-wireless-gateway-with-certificate`
<a name="iot-wireless_AssociateWirelessGatewayWithCertificate_cli_2_topic"></a>

次のコード例は、`associate-wireless-gateway-with-certificate` を使用する方法を示しています。

**AWS CLI**  
**証明書をワイヤレスゲートウェイに関連付けるには**  
次の `associate-wireless-gateway-with-certificate` は、ワイヤレスゲートウェイを証明書に関連付けます。  

```
aws iotwireless associate-wireless-gateway-with-certificate \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d" \
    --iot-certificate-id "a123b45c6d78e9f012a34cd5e6a7890b12c3d45e6f78a1b234c56d7e890a1234"
```
出力:  

```
{
    "IotCertificateId": "a123b45c6d78e9f012a34cd5e6a7890b12c3d45e6f78a1b234c56d7e890a1234"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にゲートウェイとワイヤレスデバイスを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-onboard-devices.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateWirelessGatewayWithCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/associate-wireless-gateway-with-certificate.html)」を参照してください。

### `associate-wireless-gateway-with-thing`
<a name="iot-wireless_AssociateWirelessGatewayWithThing_cli_2_topic"></a>

次のコード例は、`associate-wireless-gateway-with-thing` を使用する方法を示しています。

**AWS CLI**  
**モノをワイヤレスゲートウェイに関連付けるには**  
次の `associate-wireless-gateway-with-thing` の例では、モノをワイヤレスゲートウェイに関連付けます。  

```
aws iotwireless associate-wireless-gateway-with-thing \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d" \
    --thing-arn "arn:aws:iot:us-east-1:123456789012:thing/MyIoTWirelessThing"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にゲートウェイとワイヤレスデバイスを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-onboard-devices.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateWirelessGatewayWithThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/associate-wireless-gateway-with-thing.html)」を参照してください。

### `create-destination`
<a name="iot-wireless_CreateDestination_cli_2_topic"></a>

次のコード例は、`create-destination` を使用する方法を示しています。

**AWS CLI**  
**IoT ワイヤレス送信先を作成するには**  
次の`create-destination`例では、デバイスメッセージを AWS IoT ルールにマッピングするための送信先を作成します。このコマンドを実行する前に、IoT AWS IoT ルールにデータを送信するために必要なアクセス許可を AWS IoT Core for LoRaWAN に付与する IAM ロールを作成しておく必要があります。  

```
aws iotwireless create-destination \
    --name IoTWirelessDestination \
    --expression-type RuleName \
    --expression IoTWirelessRule \
    --role-arn arn:aws:iam::123456789012:role/IoTWirelessDestinationRole
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:Destination/IoTWirelessDestination",
    "Name": "IoTWirelessDestination"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN への送信先の追加](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-create-destinations.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/create-destination.html)」を参照してください。

### `create-device-profile`
<a name="iot-wireless_CreateDeviceProfile_cli_2_topic"></a>

次のコード例は、`create-device-profile` を使用する方法を示しています。

**AWS CLI**  
**新しいデバイスプロファイルを作成するには**  
次の `create-device-profile` の例では、新しい IoT ワイヤレスデバイスプロファイルを作成します。  

```
aws iotwireless create-device-profile
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:DeviceProfile/12345678-a1b2-3c45-67d8-e90fa1b2c34d",
    "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDeviceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/create-device-profile.html)」を参照してください。

### `create-service-profile`
<a name="iot-wireless_CreateServiceProfile_cli_2_topic"></a>

次のコード例は、`create-service-profile` を使用する方法を示しています。

**AWS CLI**  
**新しいサービスプロファイルを作成するには**  
次の `create-service-profile` の例では、新しい IoT ワイヤレスサービスプロファイルを作成します。  

```
aws iotwireless create-service-profile
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:ServiceProfile/12345678-a1b2-3c45-67d8-e90fa1b2c34d",
    "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateServiceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/create-service-profile.html)」を参照してください。

### `create-wireless-device`
<a name="iot-wireless_CreateWirelessDevice_cli_2_topic"></a>

次のコード例は、`create-wireless-device` を使用する方法を示しています。

**AWS CLI**  
**IoT ワイヤレスデバイスを作成するには**  
次の `create-wireless-device` の例では、LoRaWAN タイプのワイヤレスデバイスリソースを作成します。  

```
aws iotwireless create-wireless-device \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "Description": "My LoRaWAN wireless device"
    "DestinationName": "IoTWirelessDestination"
    "LoRaWAN": {
        "DeviceProfileId": "ab0c23d3-b001-45ef-6a01-2bc3de4f5333",
        "ServiceProfileId": "fe98dc76-cd12-001e-2d34-5550432da100",
        "OtaaV1_1": {
            "AppKey": "3f4ca100e2fc675ea123f4eb12c4a012",
            "JoinEui": "b4c231a359bc2e3d",
            "NwkKey": "01c3f004a2d6efffe32c4eda14bcd2b4"
        },
        "DevEui": "ac12efc654d23fc2"
    },
    "Name": "SampleIoTWirelessThing"
    "Type": LoRaWAN
}
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:WirelessDevice/1ffd32c8-8130-4194-96df-622f072a315f",
    "Id": "1ffd32c8-8130-4194-96df-622f072a315f"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWirelessDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/create-wireless-device.html)」を参照してください。

### `create-wireless-gateway-task-definition`
<a name="iot-wireless_CreateWirelessGatewayTaskDefinition_cli_2_topic"></a>

次のコード例は、`create-wireless-gateway-task-definition` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイタスク定義を作成するには**  
次の `create-wireless-gateway-task-definition` の例では、指定された現在のバージョンを持つすべてのゲートウェイに対して、このタスク定義を使用してタスクを自動的に作成します。  

```
aws iotwireless create-wireless-gateway-task-definition \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "AutoCreateTasks": true,
    "Name": "TestAutoUpdate",
    "Update":{
        "UpdateDataSource" : "s3://cupsalphagafirmwarebin/station",
        "UpdateDataRole" : "arn:aws:iam::001234567890:role/SDK_Test_Role",
        "LoRaWAN" :{
            "CurrentVersion" :{
                "PackageVersion" : "1.0.0",
                "Station" : "2.0.5",
                "Model" : "linux"
            },
            "UpdateVersion" :{
                "PackageVersion" : "1.0.1",
                "Station" : "2.0.5",
                "Model" : "minihub"
            }
        }
    }
}
```
出力:  

```
{
    "Id": "b7d3baad-25c7-35e7-a4e1-1683a0d61da9"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWirelessGatewayTaskDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/create-wireless-gateway-task-definition.html)」を参照してください。

### `create-wireless-gateway-task`
<a name="iot-wireless_CreateWirelessGatewayTask_cli_2_topic"></a>

次のコード例は、`create-wireless-gateway-task` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイのタスクを作成するには**  
次の `create-wireless-gateway-task` の例では、ワイヤレスゲートウェイのタスクを作成します。  

```
aws iotwireless create-wireless-gateway-task \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d" \
    --wireless-gateway-task-definition-id "aa000102-0304-b0cd-ef56-a1b23cde456a"
```
出力:  

```
{
    "WirelessGatewayTaskDefinitionId": "aa204003-0604-30fb-ac82-a4f95aaf450a",
    "Status": "Success"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWirelessGatewayTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/create-wireless-gateway-task.html)」を参照してください。

### `create-wireless-gateway`
<a name="iot-wireless_CreateWirelessGateway_cli_2_topic"></a>

次のコード例は、`create-wireless-gateway` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイを作成するには**  
次の `create-wireless-gateway` の例では、ワイヤレス LoRaWAN デバイスゲートウェイを作成します。  

```
aws iotwireless create-wireless-gateway \
    --lorawan GatewayEui="a1b2c3d4567890ab",RfRegion="US915" \
    --name "myFirstLoRaWANGateway" \
    --description "Using my first LoRaWAN gateway"
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:WirelessGateway/12345678-a1b2-3c45-67d8-e90fa1b2c34d",
    "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWirelessGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/create-wireless-gateway.html)」を参照してください。

### `delete-destination`
<a name="iot-wireless_DeleteDestination_cli_2_topic"></a>

次のコード例は、`delete-destination` を使用する方法を示しています。

**AWS CLI**  
**IoT ワイヤレス送信先を削除するには**  
次の `delete-destination` の例では、作成した `IoTWirelessDestination` という名前のワイヤレス送信先リソースを削除します。  

```
aws iotwireless delete-destination \
    --name "IoTWirelessDestination"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN への送信先の追加](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-create-destinations.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/delete-destination.html)」を参照してください。

### `delete-device-profile`
<a name="iot-wireless_DeleteDeviceProfile_cli_2_topic"></a>

次のコード例は、`delete-device-profile` を使用する方法を示しています。

**AWS CLI**  
**デバイスプロファイルを削除するには**  
次の `delete-device-profile` の例では、指定された ID を持つ、自分で作成したデバイスプロファイルを削除します。  

```
aws iotwireless delete-device-profile \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDeviceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/delete-device-profile.html)」を参照してください。

### `delete-service-profile`
<a name="iot-wireless_DeleteServiceProfile_cli_2_topic"></a>

次のコード例は、`delete-service-profile` を使用する方法を示しています。

**AWS CLI**  
**サービスプロファイルを削除するには**  
次の `delete-service-profile` の例では、指定された ID を持つ、自分で作成したサービスプロファイルを削除します。  

```
aws iotwireless delete-service-profile \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/delete-service-profile.html)」を参照してください。

### `delete-wireless-device`
<a name="iot-wireless_DeleteWirelessDevice_cli_2_topic"></a>

次のコード例は、`delete-wireless-device` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスデバイスを削除するには**  
次の `delete-wireless-device` の例では、指定された ID を持つワイヤレスデバイスを削除します。  

```
aws iotwireless delete-wireless-device \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWirelessDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/delete-wireless-device.html)」を参照してください。

### `delete-wireless-gateway-task-definition`
<a name="iot-wireless_DeleteWirelessGatewayTaskDefinition_cli_2_topic"></a>

次のコード例は、`delete-wireless-gateway-task-definition` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイタスク定義を削除するには**  
次の `delete-wireless-gateway-task-definition` の例では、次の ID で作成したワイヤレスゲートウェイタスク定義を削除します。  

```
aws iotwireless delete-wireless-gateway-task-definition \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWirelessGatewayTaskDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/delete-wireless-gateway-task-definition.html)」を参照してください。

### `delete-wireless-gateway-task`
<a name="iot-wireless_DeleteWirelessGatewayTask_cli_2_topic"></a>

次のコード例は、`delete-wireless-gateway-task` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイタスクを削除するには**  
次の `delete-wireless-gateway-task` の例では、指定された ID を持つワイヤレスゲートウェイタスクを削除します。  

```
aws iotwireless delete-wireless-gateway-task \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWirelessGatewayTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/delete-wireless-gateway-task.html)」を参照してください。

### `delete-wireless-gateway`
<a name="iot-wireless_DeleteWirelessGateway_cli_2_topic"></a>

次のコード例は、`delete-wireless-gateway` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイを削除するには**  
次の `delete-wireless-gateway` の例では、指定された ID を持つワイヤレスゲートウェイを削除します。  

```
aws iotwireless delete-wireless-gateway \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWirelessGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/delete-wireless-gateway.html)」を参照してください。

### `disassociate-aws-account-from-partner-account`
<a name="iot-wireless_DisassociateAwsAccountFromPartnerAccount_cli_2_topic"></a>

次の例は、`disassociate-aws-account-from-partner-account` を使用する方法を説明しています。

**AWS CLI**  
**パートナーアカウントの AWS アカウントとの関連付けを解除するには**  
次の の`disassociate-aws-account-from-partner-account`例では、現在関連付けられているアカウントからパートナー AWS アカウントの関連付けを解除します。  

```
aws iotwireless disassociate-aws-account-from-partner-account \
    --partner-account-id "12345678901234" \
    --partner-type "Sidewalk"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にゲートウェイとワイヤレスデバイスを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-onboard-devices.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateAwsAccountFromPartnerAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/disassociate-aws-account-from-partner-account.html)」を参照してください。

### `disassociate-wireless-device-from-thing`
<a name="iot-wireless_DisassociateWirelessDeviceFromThing_cli_2_topic"></a>

次のコード例は、`disassociate-wireless-device-from-thing` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスデバイスからモノの関連付けを解除するには**  
次の `disassociate-wireless-device-from-thing` の例では、現在関連付けられているモノからワイヤレスデバイスの関連付けを解除します。  

```
aws iotwireless disassociate-wireless-device-from-thing \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にゲートウェイとワイヤレスデバイスを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-onboard-devices.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateWirelessDeviceFromThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/disassociate-wireless-device-from-thing.html)」を参照してください。

### `disassociate-wireless-gateway-from-certificate`
<a name="iot-wireless_DisassociateWirelessGatewayFromCertificate_cli_2_topic"></a>

次のコード例は、`disassociate-wireless-gateway-from-certificate` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイから証明書の関連付けを解除するには**  
次の `disassociate-wireless-gateway-from-certificate` は、現在関連付けられている証明書からワイヤレスゲートウェイの関連付けを解除します。  

```
aws iotwireless disassociate-wireless-gateway-from-certificate \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にゲートウェイとワイヤレスデバイスを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-onboard-devices.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateWirelessGatewayFromCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/disassociate-wireless-gateway-from-certificate.html)」を参照してください。

### `disassociate-wireless-gateway-from-thing`
<a name="iot-wireless_DisassociateWirelessGatewayFromThing_cli_2_topic"></a>

次のコード例は、`disassociate-wireless-gateway-from-thing` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイからモノの関連付けを解除するには**  
次の `disassociate-wireless-gateway-from-thing` の例では、現在関連付けられているモノからワイヤレスゲートウェイの関連付け解除します。  

```
aws iotwireless disassociate-wireless-gateway-from-thing \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にゲートウェイとワイヤレスデバイスを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-onboard-devices.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateWirelessGatewayFromThing](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/disassociate-wireless-gateway-from-thing.html)」を参照してください。

### `get-destination`
<a name="iot-wireless_GetDestination_cli_2_topic"></a>

次のコード例は、`get-destination` を使用する方法を示しています。

**AWS CLI**  
**IoT ワイヤレス送信先に関する情報を取得するには**  
次の `get-destination` の例では、作成した `IoTWirelessDestination` という名前の送信先リソースに関する情報を取得します。  

```
aws iotwireless get-destination \
    --name "IoTWirelessDestination"
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:Destination/IoTWirelessDestination",
    "Name": "IoTWirelessDestination",
    "Expression": "IoTWirelessRule",
    "ExpressionType": "RuleName",
    "RoleArn": "arn:aws:iam::123456789012:role/IoTWirelessDestinationRole"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN への送信先の追加](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-create-destinations.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-destination.html)」を参照してください。

### `get-device-profile`
<a name="iot-wireless_GetDeviceProfile_cli_2_topic"></a>

次のコード例は、`get-device-profile` を使用する方法を示しています。

**AWS CLI**  
**デバイスプロファイルに関する情報を取得するには**  
次の `get-device-profile` の例では、指定された ID を持つ、自分で作成したデバイスプロファイルに関する情報を取得します。  

```
aws iotwireless get-device-profile \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:DeviceProfile/12345678-a1b2-3c45-67d8-e90fa1b2c34d",
    "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d",
    "LoRaWAN": {
    "MacVersion": "1.0.3",
    "MaxDutyCycle": 10,
    "Supports32BitFCnt": false,
    "RegParamsRevision": "RP002-1.0.1",
    "SupportsJoin": true,
    "RfRegion": "US915",
    "MaxEirp": 13,
    "SupportsClassB": false,
    "SupportsClassC": false
    }
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeviceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-device-profile.html)」を参照してください。

### `get-partner-account`
<a name="iot-wireless_GetPartnerAccount_cli_2_topic"></a>

次のコード例は、`get-partner-account` を使用する方法を示しています。

**AWS CLI**  
**パートナーアカウントの情報を取得するには**  
次の `get-partner-account` の例では、次の ID を持つ Sidewalk アカウントに関する情報を取得します。  

```
aws iotwireless get-partner-account \
    --partner-account-id "12345678901234" \
    --partner-type "Sidewalk"
```
出力:  

```
{
    "Sidewalk": {
        "AmazonId": "12345678901234",
        "Fingerprint": "a123b45c6d78e9f012a34cd5e6a7890b12c3d45e6f78a1b234c56d7e890a1234"
    },
    "AccountLinked": false
}
```
詳細については、「 IoT デベロッパーガイド」の[「Amazon Sidewalk Integration for AWS IoT Core](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sidewalk.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPartnerAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-partner-account.html)」を参照してください。

### `get-service-endpoint`
<a name="iot-wireless_GetServiceEndpoint_cli_2_topic"></a>

次のコード例は、`get-service-endpoint` を使用する方法を示しています。

**AWS CLI**  
**サービスエンドポイントを取得するには**  
次の `get-service-endpoint` の例では、CUPS プロトコルのアカウント固有のエンドポイントを取得します。  

```
aws iotwireless get-service-endpoint
```
出力:  

```
{
    "ServiceType": "CUPS",
    "ServiceEndpoint": "https://A1RMKZ37ACAGOT.cups.lorawan.us-east-1.amazonaws.com:443",
    "ServerTrust": "-----BEGIN CERTIFICATE-----\n
    MIIESTCCAzGgAwIBAgITBn+UV4WH6Kx33rJTMlu8mYtWDTANBgkqhkiG9w0BAQsF\n
    ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n
    b24gUm9vdCBDQSAxMB4XDTE1MTAyMjAwMDAwMFoXDTI1MTAxOTAwMDAwMFowRjEL\n
    MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEVMBMGA1UECxMMU2VydmVyIENB\n
    IDFCMQ8wDQYDVQQDEwZBbWF6b24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\n
    AoIBAQDCThZn3c68asg3Wuw6MLAd5tES6BIoSMzoKcG5blPVo+sDORrMd4f2AbnZ\n
    cMzPa43j4wNxhplty6aUKk4T1qe9BOwKFjwK6zmxxLVYo7bHViXsPlJ6qOMpFge5\n
    blDP+18x+B26A0piiQOuPkfyDyeR4xQghfj66Yo19V+emU3nazfvpFA+ROz6WoVm\n
    B5x+F2pV8xeKNR7u6azDdU5YVX1TawprmxRC1+WsAYmz6qP+z8ArDITC2FMVy2fw\n
    0IjKOtEXc/VfmtTFch5+AfGYMGMqqvJ6LcXiAhqG5TI+Dr0RtM88k+8XUBCeQ8IG\n
    KuANaL7TiItKZYxK1MMuTJtV9IblAgMBAAGjggE7MIIBNzASBgNVHRMBAf8ECDAG\n
    AQH/AgEAMA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUWaRmBlKge5WSPKOUByeW\n
    dFv5PdAwHwYDVR0jBBgwFoAUhBjMhTTsvAyUlC4IWZzHshBOCggwewYIKwYBBQUH\n
    AQEEbzBtMC8GCCsGAQUFBzABhiNodHRwOi8vb2NzcC5yb290Y2ExLmFtYXpvbnRy\n
    dXN0LmNvbTA6BggrBgEFBQcwAoYuaHR0cDovL2NydC5yb290Y2ExLmFtYXpvbnRy\n
    dXN0LmNvbS9yb290Y2ExLmNlcjA/BgNVHR8EODA2MDSgMqAwhi5odHRwOi8vY3Js\n
    LnJvb3RjYTEuYW1hem9udHJ1c3QuY29tL3Jvb3RjYTEuY3JsMBMGA1UdIAQMMAow\n
    CAYGZ4EMAQIBMA0GCSqGSIb3DQEBCwUAA4IBAQCFkr41u3nPo4FCHOTjY3NTOVI1\n
    59Gt/a6ZiqyJEi+752+a1U5y6iAwYfmXss2lJwJFqMp2PphKg5625kXg8kP2CN5t\n
    6G7bMQcT8C8xDZNtYTd7WPD8UZiRKAJPBXa30/AbwuZe0GaFEQ8ugcYQgSn+IGBI\n
    8/LwhBNTZTUVEWuCUUBVV18YtbAiPq3yXqMB48Oz+ctBWuZSkbvkNodPLamkB2g1\n
    upRyzQ7qDn1X8nn8N8V7YJ6y68AtkHcNSRAnpTitxBKjtKPISLMVCx7i4hncxHZS\n
    yLyKQXhw2W2Xs0qLeC1etA+jTGDK4UfLeC0SF7FSi8o5LL21L8IzApar2pR/\n
    -----END CERTIFICATE-----\n"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-service-endpoint.html)」を参照してください。

### `get-service-profile`
<a name="iot-wireless_GetServiceProfile_cli_2_topic"></a>

次のコード例は、`get-service-profile` を使用する方法を示しています。

**AWS CLI**  
**サービスプロファイルに関する情報を取得するには**  
次の `get-service-profile` の例では、指定された ID を持つ、自分で作成したサービスプロファイルに関する情報を取得します。  

```
aws iotwireless get-service-profile \
    --id "12345678-a1b2-3c45-67d8-e90fa1b2c34d"
```
出力:  

```
{
    "Arn": "arn:aws:iotwireless:us-east-1:651419225604:ServiceProfile/538185bb-d7e7-4b95-96a0-c51aa4a5b9a0",
    "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d",
    "LoRaWAN": {
        "HrAllowed": false,
        "NwkGeoLoc": false,
        "DrMax": 15,
        "UlBucketSize": 4096,
        "PrAllowed": false,
        "ReportDevStatusBattery": false,
        "DrMin": 0,
        "DlRate": 60,
        "AddGwMetadata": false,
        "ReportDevStatusMargin": false,
        "MinGwDiversity": 1,
        "RaAllowed": false,
        "DlBucketSize": 4096,
        "DevStatusReqFreq": 24,
        "TargetPer": 5,
        "UlRate": 60
    }
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-service-profile.html)」を参照してください。

### `get-wireless-device-statistics`
<a name="iot-wireless_GetWirelessDeviceStatistics_cli_2_topic"></a>

次のコード例は、`get-wireless-device-statistics` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスデバイスに関する運用情報を取得するには**  
次の `get-wireless-device-statistics` の例では、ワイヤレスデバイスに関する運用情報を取得します。  

```
aws iotwireless get-wireless-device-statistics \
    --wireless-device-id "1ffd32c8-8130-4194-96df-622f072a315f"
```
出力:  

```
{
    "WirelessDeviceId": "1ffd32c8-8130-4194-96df-622f072a315f"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessDeviceStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-device-statistics.html)」を参照してください。

### `get-wireless-device`
<a name="iot-wireless_GetWirelessDevice_cli_2_topic"></a>

次のコード例は、`get-wireless-device` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスデバイスに関する情報を取得するには**  
次の の`get-wireless-device`例では、 AWS アカウントで使用可能なウィジェットを一覧表示します。  

```
aws iotwireless get-wireless-device \
    --identifier "1ffd32c8-8130-4194-96df-622f072a315f" \
    --identifier-type WirelessDeviceID
```
出力:  

```
{
    "Name": "myLoRaWANDevice",
    "ThingArn": "arn:aws:iot:us-east-1:123456789012:thing/44b87eb4-9bce-423d-b5fc-973f5ecc358b",
    "DestinationName": "IoTWirelessDestination",
    "Id": "1ffd32c8-8130-4194-96df-622f072a315f",
    "ThingName": "44b87eb4-9bce-423d-b5fc-973f5ecc358b",
    "Type": "LoRaWAN",
    "LoRaWAN": {
        "DeviceProfileId": "ab0c23d3-b001-45ef-6a01-2bc3de4f5333",
        "ServiceProfileId": "fe98dc76-cd12-001e-2d34-5550432da100",
        "OtaaV1_1": {
            "AppKey": "3f4ca100e2fc675ea123f4eb12c4a012",
            "JoinEui": "b4c231a359bc2e3d",
            "NwkKey": "01c3f004a2d6efffe32c4eda14bcd2b4"
        },
        "DevEui": "ac12efc654d23fc2"
    },
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:WirelessDevice/1ffd32c8-8130-4194-96df-622f072a315f",
    "Description": "My LoRaWAN wireless device"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-device.html)」を参照してください。

### `get-wireless-gateway-certificate`
<a name="iot-wireless_GetWirelessGatewayCertificate_cli_2_topic"></a>

次のコード例は、`get-wireless-gateway-certificate` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイに関連付けられている証明書の ID を取得するには**  
次の `get-wireless-gateway-certificate` の例では、指定された ID を持つワイヤレスゲートウェイに関連付けられている証明書 ID を取得します。  

```
aws iotwireless get-wireless-gateway-certificate \
    --id "6c44ab31-8b4d-407a-bed3-19b6c7cda551"
```
出力:  

```
{
    "IotCertificateId": "8ea4aeae3db34c78cce75d9abd830356869ead6972997e0603e5fd032c804b6f"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessGatewayCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-gateway-certificate.html)」を参照してください。

### `get-wireless-gateway-firmware-information`
<a name="iot-wireless_GetWirelessGatewayFirmwareInformation_cli_2_topic"></a>

次のコード例は、`get-wireless-gateway-firmware-information` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイに関するファームウェア情報を取得するには**  
次の `get-wireless-gateway-firmware-information` 例では、ワイヤレスゲートウェイに関するファームウェアバージョンとその他の情報を取得します。  

```
aws iotwireless get-wireless-gateway-firmware-information \
    --id "3039b406-5cc9-4307-925b-9948c63da25b"
```
出力:  

```
{
    "LoRaWAN" :{
        "CurrentVersion" :{
            "PackageVersion" : "1.0.0",
            "Station" : "2.0.5",
            "Model" : "linux"
        }
    }
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessGatewayFirmwareInformation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-gateway-firmware-information.html)」を参照してください。

### `get-wireless-gateway-statistics`
<a name="iot-wireless_GetWirelessGatewayStatistics_cli_2_topic"></a>

次のコード例は、`get-wireless-gateway-statistics` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイに関する運用情報を取得するには**  
次の `get-wireless-gateway-statistics` の例では、ワイヤレスゲートウェイに関する運用情報を取得します。  

```
aws iotwireless get-wireless-gateway-statistics \
    --wireless-gateway-id "3039b406-5cc9-4307-925b-9948c63da25b"
```
出力:  

```
{
    "WirelessGatewayId": "3039b406-5cc9-4307-925b-9948c63da25b"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessGatewayStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-gateway-statistics.html)」を参照してください。

### `get-wireless-gateway-task-definition`
<a name="iot-wireless_GetWirelessGatewayTaskDefinition_cli_2_topic"></a>

次のコード例は、`get-wireless-gateway-task-definition` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイタスク定義に関する情報を取得するには**  
次の `get-wireless-gateway-task-definition` の例では、指定された ID を持つワイヤレスタスク定義に関する情報を取得します。  

```
aws iotwireless get-wireless-gateway-task-definition \
    --id "b7d3baad-25c7-35e7-a4e1-1683a0d61da9"
```
出力:  

```
{
    "AutoCreateTasks": true,
    "Name": "TestAutoUpdate",
    "Update":{
        "UpdateDataSource" : "s3://cupsalphagafirmwarebin/station",
        "UpdateDataRole" : "arn:aws:iam::001234567890:role/SDK_Test_Role",
        "LoRaWAN" :{
            "CurrentVersion" :{
                "PackageVersion" : "1.0.0",
                "Station" : "2.0.5",
                "Model" : "linux"
            },
            "UpdateVersion" :{
                "PackageVersion" : "1.0.1",
                "Station" : "2.0.5",
                "Model" : "minihub"
            }
        }
    }
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessGatewayTaskDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-gateway-task-definition.html)」を参照してください。

### `get-wireless-gateway-task`
<a name="iot-wireless_GetWirelessGatewayTask_cli_2_topic"></a>

次のコード例は、`get-wireless-gateway-task` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイタスクに関する情報を取得するには**  
次の `get-wireless-gateway-task` の例では、指定された ID を持つワイヤレスゲートウェイタスク定義に関する情報を取得します。  

```
aws iotwireless get-wireless-gateway-task \
    --id "11693a46-6866-47c3-a031-c9a616e7644b"
```
出力:  

```
{
    "WirelessGatewayId": "6c44ab31-8b4d-407a-bed3-19b6c7cda551",
    "WirelessGatewayTaskDefinitionId": "b7d3baad-25c7-35e7-a4e1-1683a0d61da9",
    "Status": "Success"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessGatewayTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-gateway-task.html)」を参照してください。

### `get-wireless-gateway`
<a name="iot-wireless_GetWirelessGateway_cli_2_topic"></a>

次のコード例は、`get-wireless-gateway` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイに関する情報を取得するには**  
次の `get-wireless-gateway` の例では、ワイヤレスゲートウェイ `myFirstLoRaWANGateway` に関する情報を取得します。  

```
aws iotwireless get-wireless-gateway \
    --identifier "12345678-a1b2-3c45-67d8-e90fa1b2c34d" \
    --identifier-type WirelessGatewayId
```
出力:  

```
{
    "Description": "My first LoRaWAN gateway",
    "ThingArn": "arn:aws:iot:us-east-1:123456789012:thing/a1b2c3d4-5678-90ab-cdef-12ab345c67de",
    "LoRaWAN": {
        "RfRegion": "US915",
        "GatewayEui": "a1b2c3d4567890ab"
    },
    "ThingName": "a1b2c3d4-5678-90ab-cdef-12ab345c67de",
    "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d",
    "Arn": "arn:aws:iotwireless:us-east-1:123456789012:WirelessGateway/6c44ab31-8b4d-407a-bed3-19b6c7cda551",
    "Name": "myFirstLoRaWANGateway"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWirelessGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/get-wireless-gateway.html)」を参照してください。

### `list-destinations`
<a name="iot-wireless_ListDestinations_cli_2_topic"></a>

次のコード例は、`list-destinations` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレス送信先を一覧表示するには**  
次の の`list-destinations`例では、 AWS アカウントに登録されている利用可能な送信先を一覧表示します。  

```
aws iotwireless list-destinations
```
出力:  

```
{
    "DestinationList": [
        {
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:Destination/IoTWirelessDestination",
            "Name": "IoTWirelessDestination",
            "Expression": "IoTWirelessRule",
            "Description": "Destination for messages processed using IoTWirelessRule",
            "RoleArn": "arn:aws:iam::123456789012:role/IoTWirelessDestinationRole"
        },
        {
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:Destination/IoTWirelessDestination2",
            "Name": "IoTWirelessDestination2",
            "Expression": "IoTWirelessRule2",
            "RoleArn": "arn:aws:iam::123456789012:role/IoTWirelessDestinationRole"
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN への送信先の追加](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-create-destinations.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDestinations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-destinations.html)」を参照してください。

### `list-device-profiles`
<a name="iot-wireless_ListDeviceProfiles_cli_2_topic"></a>

次のコード例は、`list-device-profiles` を使用する方法を示しています。

**AWS CLI**  
**デバイスプロファイルを一覧表示するには**  
次の の`list-device-profiles`例では、 AWS アカウントに登録されている使用可能なデバイスプロファイルを一覧表示します。  

```
aws iotwireless list-device-profiles
```
出力:  

```
{
    "DeviceProfileList": [
        {
            "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d",
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:DeviceProfile/12345678-a1b2-3c45-67d8-e90fa1b2c34d"
        },
        {
            "Id": "a1b2c3d4-5678-90ab-cdef-12ab345c67de",
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:DeviceProfile/a1b2c3d4-5678-90ab-cdef-12ab345c67de"
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeviceProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-device-profiles.html)」を参照してください。

### `list-partner-accounts`
<a name="iot-wireless_ListPartnerAccounts_cli_2_topic"></a>

次のコード例は、`list-partner-accounts` を使用する方法を示しています。

**AWS CLI**  
**パートナーアカウントを一覧表示するには**  
次の の`list-partner-accounts`例では、アカウントに関連付けられている利用可能なパートナー AWS アカウントを一覧表示します。  

```
aws iotwireless list-partner-accounts
```
出力:  

```
{
    "Sidewalk": [
        {
            "AmazonId": "78965678771228",
            "Fingerprint": "bd96d8ef66dbfd2160eb60e156849e82ad7018b8b73c1ba0b4fc65c32498ee35"
        },
        {
            "AmazonId": "89656787651228",
            "Fingerprint": "bc5e99e151c07be14be7e6603e4489c53f858b271213a36ebe3370777ba06e9b"
        }
    ]
}
```
詳細については、「 IoT デベロッパーガイド」の[「Amazon Sidewalk Integration for AWS IoT Core](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sidewalk.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPartnerAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-partner-accounts.html)」を参照してください。

### `list-service-profiles`
<a name="iot-wireless_ListServiceProfiles_cli_2_topic"></a>

次のコード例は、`list-service-profiles` を使用する方法を示しています。

**AWS CLI**  
**サービスプロファイルを一覧表示するには**  
次の の`list-service-profiles`例では、 AWS アカウントに登録されている利用可能なサービスプロファイルを一覧表示します。  

```
aws iotwireless list-service-profiles
```
出力:  

```
{
    "ServiceProfileList": [
        {
            "Id": "12345678-a1b2-3c45-67d8-e90fa1b2c34d",
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:ServiceProfile/538185bb-d7e7-4b95-96a0-c51aa4a5b9a0"
        },
        {
            "Id": "a1b2c3d4-5678-90ab-cdef-12ab345c67de",
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:ServiceProfile/ea8bc823-5d13-472e-8d26-9550737d8100"
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN にプロファイルを追加する](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-define-profiles.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-service-profiles.html)」を参照してください。

### `list-tags-for-resource`
<a name="iot-wireless_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに割り当てられたタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、ワイヤレス送信先リソースに割り当てられたタグを一覧表示します。  

```
aws iotwireless list-tags-for-resource \
    --resource-arn "arn:aws:iotwireless:us-east-1:123456789012:Destination/IoTWirelessDestination"
```
出力:  

```
{
    "Tags": [
        {
            "Value": "MyValue",
            "Key": "MyTag"
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「Describe yourIoT Core for LoRaWAN resources](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-describe-resource.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-tags-for-resource.html)」を参照してください。

### `list-wireless-devices`
<a name="iot-wireless_ListWirelessDevices_cli_2_topic"></a>

次のコード例は、`list-wireless-devices` を使用する方法を示しています。

**AWS CLI**  
**使用可能なワイヤレスデバイスを一覧表示するには**  
次の の`list-wireless-devices`例では、 AWS アカウントに登録されている使用可能なワイヤレスデバイスを一覧表示します。  

```
aws iotwireless list-wireless-devices
```
出力:  

```
{
    "WirelessDeviceList": [
        {
            "Name": "myLoRaWANDevice",
            "DestinationName": "IoTWirelessDestination",
            "Id": "1ffd32c8-8130-4194-96df-622f072a315f",
            "Type": "LoRaWAN",
            "LoRaWAN": {
                "DevEui": "ac12efc654d23fc2"
            },
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:WirelessDevice/1ffd32c8-8130-4194-96df-622f072a315f"
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWirelessDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-wireless-devices.html)」を参照してください。

### `list-wireless-gateway-task-definitions`
<a name="iot-wireless_ListWirelessGatewayTaskDefinitions_cli_2_topic"></a>

次のコード例は、`list-wireless-gateway-task-definitions` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイタスク定義を一覧表示するには**  
次の の`list-wireless-gateway-task-definitions`例では、 AWS アカウントに登録されている使用可能なワイヤレスゲートウェイタスク定義を一覧表示します。  

```
aws iotwireless list-wireless-gateway-task-definitions
```
出力:  

```
{
    "TaskDefinitions": [
        {
            "Id": "b7d3baad-25c7-35e7-a4e1-1683a0d61da9",
            "LoRaWAN" :
                {
                "CurrentVersion" :{
                    "PackageVersion" : "1.0.0",
                    "Station" : "2.0.5",
                    "Model" : "linux"
                },
                "UpdateVersion" :{
                    "PackageVersion" : "1.0.1",
                    "Station" : "2.0.5",
                    "Model" : "minihub"
                }
            }
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWirelessGatewayTaskDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-wireless-gateway-task-definitions.html)」を参照してください。

### `list-wireless-gateways`
<a name="iot-wireless_ListWirelessGateways_cli_2_topic"></a>

次のコード例は、`list-wireless-gateways` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイを一覧表示するには**  
次の の`list-wireless-gateways`例では、 AWS アカウントで使用可能なワイヤレスゲートウェイを一覧表示します。  

```
aws iotwireless list-wireless-gateways
```
出力:  

```
{
    "WirelessGatewayList": [
        {
            "Description": "My first LoRaWAN gateway",
            "LoRaWAN": {
                "RfRegion": "US915",
                "GatewayEui": "dac632ebc01d23e4"
            },
            "Id": "3039b406-5cc9-4307-925b-9948c63da25b",
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:WirelessGateway/3039b406-5cc9-4307-925b-9948c63da25b",
            "Name": "myFirstLoRaWANGateway"
        },
        {
            "Description": "My second LoRaWAN gateway",
            "LoRaWAN": {
                "RfRegion": "US915",
                "GatewayEui": "cda123fffe92ecd2"
            },
            "Id": "3285bdc7-5a12-4991-84ed-dadca65e342e",
            "Arn": "arn:aws:iotwireless:us-east-1:123456789012:WirelessGateway/3285bdc7-5a12-4991-84ed-dadca65e342e",
            "Name": "mySecondLoRaWANGateway"
        }
    ]
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWirelessGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/list-wireless-gateways.html)」を参照してください。

### `send-data-to-wireless-device`
<a name="iot-wireless_SendDataToWirelessDevice_cli_2_topic"></a>

次のコード例は、`send-data-to-wireless-device` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスデバイスにデータを送信するには**  
次の `send-data-to-wireless-device` の例では、復号されたアプリケーションデータフレームをワイヤレスデバイスに送信します。  

```
aws iotwireless send-data-to-wireless-device \
    --id "11aa5eae-2f56-4b8e-a023-b28d98494e49" \
    --transmit-mode "1" \
    --payload-data "SGVsbG8gVG8gRGV2c2lt" \
    --wireless-metadata LoRaWAN={FPort=1}
```
出力:  

```
{
    MessageId: "6011dd36-0043d6eb-0072-0008"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendDataToWirelessDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/send-data-to-wireless-device.html)」を参照してください。

### `tag-resource`
<a name="iot-wireless_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグキーと値を指定するには**  
次の `tag-resource` の例では、ワイヤレス送信先 `IoTWirelessDestination` にキー `MyTag` と値 `MyValue` でタグ付けします。  

```
aws iotwireless tag-resource \
    --resource-arn "arn:aws:iotwireless:us-east-1:651419225604:Destination/IoTWirelessDestination" \
    --tags Key="MyTag",Value="MyValue"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「Describe yourIoT Core for LoRaWAN resources](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-describe-resource.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/tag-resource.html)」を参照してください。

### `test-wireless-device`
<a name="iot-wireless_TestWirelessDevice_cli_2_topic"></a>

次のコード例は、`test-wireless-device` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスデバイスをテストするには**  
次の `test-wireless-device` の例では、`Hello` のアップリンクデータを、指定された ID を持つデバイスに送信します。  

```
aws iotwireless test-wireless-device \
    --id "11aa5eae-2f56-4b8e-a023-b28d98494e49"
```
出力:  

```
{
    Result: "Test succeeded. one message is sent with payload: hello"
}
```
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TestWirelessDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/test-wireless-device.html)」を参照してください。

### `untag-resource`
<a name="iot-wireless_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースから 1 つ以上のタグを削除するには**  
次の `untag-resource` の例では、ワイヤレス送信先 `IoTWirelessDestination` からタグ `MyTag` とその値を削除します。  

```
aws iotwireless untag-resource \
    --resource-arn "arn:aws:iotwireless:us-east-1:123456789012:Destination/IoTWirelessDestination" \
    --tag-keys "MyTag"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「Describe yourIoT Core for LoRaWAN resources](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-describe-resource.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/untag-resource.html)」を参照してください。

### `update-destination`
<a name="iot-wireless_UpdateDestination_cli_2_topic"></a>

次のコード例は、`update-destination` を使用する方法を示しています。

**AWS CLI**  
**送信先のプロパティを更新するには**  
次の `update-destination` の例では、ワイヤレス送信先の説明プロパティを更新します。  

```
aws iotwireless update-destination \
    --name "IoTWirelessDestination" \
    --description "Destination for messages processed using IoTWirelessRule"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN への送信先の追加](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan-create-destinations.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDestination](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/update-destination.html)」を参照してください。

### `update-partner-account`
<a name="iot-wireless_UpdatePartnerAccount_cli_2_topic"></a>

次のコード例は、`update-partner-account` を使用する方法を示しています。

**AWS CLI**  
**パートナーアカウントのプロパティを更新するには**  
次の `update-partner-account` は、指定された ID を持つアカウントの `AppServerPrivateKey` を更新します。  

```
aws iotwireless update-partner-account \
    --partner-account-id "78965678771228" \
    --partner-type "Sidewalk" \
    --sidewalk AppServerPrivateKey="f798ab4899346a88599180fee9e14fa1ada7b6df989425b7c6d2146dd6c815bb"
```
このコマンドでは何も出力されません。  
詳細については、「 IoT デベロッパーガイド」の[「Amazon Sidewalk Integration for AWS IoT Core](https://docs.aws.amazon.com/iot/latest/developerguide/iot-sidewalk.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePartnerAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/update-partner-account.html)」を参照してください。

### `update-wireless-device`
<a name="iot-wireless_UpdateWirelessDevice_cli_2_topic"></a>

次のコード例は、`update-wireless-device` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスデバイスのプロパティを更新するには**  
次の の`update-wireless-device`例では、 AWS アカウントに登録されているワイヤレスデバイスのプロパティを更新します。  

```
aws iotwireless update-wireless-device \
    --id "1ffd32c8-8130-4194-96df-622f072a315f" \
    --destination-name IoTWirelessDestination2 \
    --description "Using my first LoRaWAN device"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWirelessDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/update-wireless-device.html)」を参照してください。

### `update-wireless-gateway`
<a name="iot-wireless_UpdateWirelessGateway_cli_2_topic"></a>

次のコード例は、`update-wireless-gateway` を使用する方法を示しています。

**AWS CLI**  
**ワイヤレスゲートウェイを更新するには**  
次の `update-wireless-gateway` の例では、ワイヤレスゲートウェイの説明を更新します。  

```
aws iotwireless update-wireless-gateway \
    --id "3285bdc7-5a12-4991-84ed-dadca65e342e" \
    --description "Using my LoRaWAN gateway"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 IoT デベロッパーガイド」の「IoT Core for LoRaWAN へのデバイスとゲートウェイの接続](https://docs.aws.amazon.com/iot/latest/developerguide/connect-iot-lorawan.html)」を参照してください。 *AWS IoT *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWirelessGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iotwireless/update-wireless-gateway.html)」を参照してください。

# を使用した Amazon IVS の例 AWS CLI
<a name="cli_2_ivs_code_examples"></a>

次のコード例は、Amazon IVS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-get-channel`
<a name="ivs_BatchGetChannel_cli_2_topic"></a>

次のコード例は、`batch-get-channel` を使用する方法を示しています。

**AWS CLI**  
**複数のチャネルに関するチャネル設定情報を取得するには**  
次の `batch-get-channel` の例では、指定されたチャネルに関する情報を一覧表示します。  

```
aws ivs batch-get-channel \
    --arns arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh \
        arn:aws:ivs:us-west-2:123456789012:channel/efghEFGHijkl
```
出力:  

```
{
    "channels": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "authorized": false,
            "containerFormat": "TS",
            "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
            "insecureIngest": false,
            "latencyMode": "LOW",
            "multitrackInputConfiguration": {
                "enabled": false,
                "maximumResolution": "FULL_HD",
                "policy": "ALLOW"
            },
            "name": "channel-1",
            "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel-1.abcdEFGH.m3u8",
            "preset": "",
            "playbackRestrictionPolicyArn": "",
            "recordingConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh",
            "srt": {
                "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
                "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
            },
            "tags": {},
            "type": "STANDARD"
        },
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:channel/efghEFGHijkl",
            "authorized": false,
            "containerFormat": "FRAGMENTED_MP4",
            "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
            "insecureIngest": false,
            "latencyMode": "LOW",
            "multitrackInputConfiguration": {
                "enabled": true,
                "maximumResolution": "FULL_HD",
                "policy": "ALLOW"
            },
            "name": "channel-2",
            "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel-2.abcdEFGH.m3u8",
            "preset": "",
            "playbackRestrictionPolicyArn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ"",
            "recordingConfigurationArn": "",
            "srt": {
                "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
                "passphrase": "BA1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
            },
            "tags": {},
            "type": "STANDARD"
        }
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/batch-get-channel.html)」を参照してください。

### `batch-get-stream-key`
<a name="ivs_BatchGetStreamKey_cli_2_topic"></a>

次のコード例は、`batch-get-stream-key` を使用する方法を示しています。

**AWS CLI**  
**複数のストリームキーに関する情報を取得するには**  
次の `batch-get-stream-key` の例では、指定されたストリームキーに関する情報を取得します。  

```
aws ivs batch-get-stream-key \
    --arns arn:aws:ivs:us-west-2:123456789012:stream-key/skSKABCDefgh \
       arn:aws:ivs:us-west-2:123456789012:stream-key/skSKIJKLmnop
```
出力:  

```
{
    "streamKeys": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/skSKABCDefgh",
            "value": "sk_us-west-2_abcdABCDefgh_567890abcdef",
            "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "tags": {}
        },
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/skSKIJKLmnop",
            "value": "sk_us-west-2_abcdABCDefgh_567890ghijkl",
            "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "tags": {}
        }
     ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetStreamKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/batch-get-stream-key.html)」を参照してください。

### `batch-start-viewer-session-revocation`
<a name="ivs_BatchStartViewerSessionRevocation_cli_2_topic"></a>

次のコード例は、`batch-start-viewer-session-revocation` を使用する方法を示しています。

**AWS CLI**  
**複数の channel-ARN と viewer-ID のペアのビューワーセッションを取り消すには**  
次の `batch-start-viewer-session-revocation` の例では、複数のチャネル ARN とビューワー ID のペアに対してセッションの取り消しを同時に実行します。発信者に指定されたセッションを取り消すアクセス許可がない場合は、リクエストは正常に完了しても、エラーフィールドで値が返されることがあります。  

```
aws ivs batch-start-viewer-session-revocation \
    --viewer-sessions '[{"channelArn":"arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh1","viewerId":"abcdefg1","viewerSessionVersionsLessThanOrEqualTo":1234567890}, \
      {"channelArn":"arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh2","viewerId":"abcdefg2","viewerSessionVersionsLessThanOrEqualTo":1234567890}]'
```
出力:  

```
{
    "errors": [
        {
            "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh1",
            "viewerId": "abcdefg1",
            "code": "403",
            "message": "not authorized",
        },
        {
            "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh2",
            "viewerId": "abcdefg2",
            "code": "403",
            "message": "not authorized",
        }
    ]
}
```
詳細については、「Amazon Interactive Video Service ユーザーガイド」の「[プライベートチャネルの設定](https://docs.aws.amazon.com/ivs/latest/userguide/private-channels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchStartViewerSessionRevocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/batch-start-viewer-session-revocation.html)」を参照してください。

### `create-channel`
<a name="ivs_CreateChannel_cli_2_topic"></a>

次のコード例は、`create-channel` を使用する方法を示しています。

**AWS CLI**  
**例 1: 録画なしでチャネルを作成するには**  
次の `create-channel` の例では、新しいチャネルとストリーミングを開始するための関連ストリームキーを作成します。  

```
aws ivs create-channel \
    --name 'test-channel' \
    --no-insecure-ingest
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "authorized": false,
        "containerFormat": "TS",
        "name": "test-channel",
        "latencyMode": "LOW",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "tags": {},
        "type": "STANDARD"
    },
    "streamKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/g1H2I3j4k5L6",
        "value": "sk_us-west-2_abcdABCDefgh_567890abcdef",
        "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
**例 2: ARN で指定された RecordingConfiguration リソースを使用して、録画を有効にしたチャネルを作成するには**  
次の `create-channel` の例では、新しいチャネルとストリーミングを開始するための関連ストリームキーを作成し、チャネルの録画を設定します。  

```
aws ivs create-channel \
    --name test-channel-with-recording \
    --insecure-ingest \
    --recording-configuration-arn 'arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh'
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "containerFormat": "TS",
        "name": "test-channel-with-recording",
        "latencyMode": "LOW",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "BA1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": true,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {},
        "type": "STANDARD"
    },
    "streamKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/abcdABCDefgh",
        "value": "sk_us-west-2_abcdABCDefgh_567890abcdef",
        "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/record-to-s3.html)」を参照してください。  
**例 3: ARN で指定された再生制限ポリシーを使用してチャネルを作成するには**  
次の `create-channel` の例では、新しいチャネルとストリーミングを開始するための関連ストリームキーを作成し、チャネルの再生制限ポリシーを設定します。  

```
aws ivs create-channel \
    --name test-channel-with-playback-restriction-policy\
    --insecure-ingest \
    --playback-restriction-policy-arn 'arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ'
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "containerFormat": "TS",
        "name": "test-channel-with-playback-restriction-policy",
        "latencyMode": "LOW",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2edfGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": true,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {},
        "type": "STANDARD"
    },
    "streamKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/abcdABCDefgh",
        "value": "sk_us-west-2_abcdABCDefgh_567890abcdef",
        "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
**例 4: マルチトラックを有効にしてチャネルを作成するには**  
次の `create-channel` の例では、新しいチャネルと関連ストリームキーを作成してストリーミングを開始し、マルチトラックを有効にします。  

```
aws ivs create-channel \
    --name 'test-channel' \
    --no-insecure-ingest \
    --container-format 'FRAGMENTED_MP4' \
    --multitrack-input-configuration '{"enabled": true,"maximumResolution": "FULL_HD","policy": "ALLOW"}'
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "authorized": false,
        "containerFormat": "FRAGMENTED_MP4",
        "name": "test-channel",
        "latencyMode": "LOW",
        "multitrackInputConfiguration": {
            "enabled": true,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "tags": {},
        "type": "STANDARD"
    },
    "streamKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/g1H2I3j4k5L6",
        "value": "sk_us-west-2_abcdABCDefgh_567890abcdef",
        "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multitrack-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/create-channel.html)」を参照してください。

### `create-playback-restriction-policy`
<a name="ivs_CreatePlaybackRestrictionPolicy_cli_2_topic"></a>

次のコード例は、`create-playback-restriction-policy` を使用する方法を示しています。

**AWS CLI**  
**再生制限ポリシーを作成するには**  
次の `create-playback-restriction-policy` の例では、新しい再生制限ポリシーを作成します。  

```
aws ivs create-playback-restriction-policy \
    --name "test-playback-restriction-policy" \
    --enable-strict-origin-enforcement \
    --tags "key1=value1, key2=value2" \
    --allowed-countries US MX \
    --allowed-origins https://www.website1.com https://www.website2.com
```
出力:  

```
{
    "playbackRestrictionPolicy": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
        "allowedCountries": [
            "US",
            "MX"
        ],
        "allowedOrigins": [
            "https://www.website1.com",
            "https://www.website2.com"
        ],
        "enableStrictOriginEnforcement": true,
        "name": "test-playback-restriction-policy",
        "tags": {
            "key1": "value1",
            "key2": "value2"
        }
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePlaybackRestrictionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/create-playback-restriction-policy.html)」を参照してください。

### `create-recording-configuration`
<a name="ivs_CreateRecordingConfiguration_cli_2_topic"></a>

次のコード例は、`create-recording-configuration` を使用する方法を示しています。

**AWS CLI**  
**RecordingConfiguration リソースを作成するには**  
次の `create-recording-configuration` の例では、Amazon S3 への録画を有効にする RecordingConfiguration リソースを作成します。  

```
aws ivs create-recording-configuration \
    --name "test-recording-config" \
    --recording-reconnect-window-seconds 60 \
    --tags "key1=value1, key2=value2" \
    --rendition-configuration renditionSelection="CUSTOM",renditions="HD" \
    --thumbnail-configuration recordingMode="INTERVAL",targetIntervalSeconds=1,storage="LATEST",resolution="LOWEST_RESOLUTION" \
    --destination-configuration s3={bucketName=demo-recording-bucket}
```
出力:  

```
{
    "recordingConfiguration": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABcdef34ghIJ",
        "name": "test-recording-config",
        "destinationConfiguration": {
            "s3": {
                "bucketName": "demo-recording-bucket"
            }
        },
        "state": "CREATING",
        "tags": {
            "key1": "value1",
            "key2": "value2"
        },
        "thumbnailConfiguration": {
            "recordingMode": "INTERVAL",
            "targetIntervalSeconds": 1,
            "resolution": "LOWEST_RESOLUTION",
            "storage": [
                "LATEST"
            ]
        },
        "recordingReconnectWindowSeconds": 60,
        "renditionConfiguration": {
            "renditionSelection": "CUSTOM",
            "renditions": [
                "HD"
            ]
        }
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/userguide/record-to-s3.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRecordingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/create-recording-configuration.html)」を参照してください。

### `create-stream-key`
<a name="ivs_CreateStreamKey_cli_2_topic"></a>

次のコード例は、`create-stream-key` を使用する方法を示しています。

**AWS CLI**  
**ストリームキーを作成するには**  
次の `create-stream-key` の例では、指定された ARN (Amazon リソースネーム) のストリームキーを作成します。  

```
aws ivs create-stream-key \
    --channel-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh
```
出力:  

```
{
    "streamKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/abcdABCDefgh",
        "value": "sk_us-west-2_abcdABCDefgh_567890abcdef",
        "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStreamKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/create-stream-key.html)」を参照してください。

### `delete-channel`
<a name="ivs_DeleteChannel_cli_2_topic"></a>

次のコード例は、`delete-channel` を使用する方法を示しています。

**AWS CLI**  
**チャネルとその関連ストリームキーを削除するには**  
次の `delete-channel` の例では、指定された ARN (Amazon リソースネーム) を持つチャネルを削除します。  

```
aws ivs delete-channel \
    --arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh
```
このコマンドは何も出力しません。  
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/delete-channel.html)」を参照してください。

### `delete-playback-key-pair`
<a name="ivs_DeletePlaybackKeyPair_cli_2_topic"></a>

次のコード例は、`delete-playback-key-pair` を使用する方法を示しています。

**AWS CLI**  
**指定された再生キーペアを削除するには**  
次の `delete-playback-key-pair` の例では、指定されたキーペアのフィンガープリントを返します。  

```
aws ivs delete-playback-key-pair \
    --arn arn:aws:ivs:us-west-2:123456789012:playback-key/abcd1234efgh
```
このコマンドは何も出力しません。  
詳細については、「Amazon Interactive Video Service ユーザーガイド」の「[プライベートチャネルの設定](https://docs.aws.amazon.com/ivs/latest/userguide/private-channels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePlaybackKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/delete-playback-key-pair.html)」を参照してください。

### `delete-playback-restriction-policy`
<a name="ivs_DeletePlaybackRestrictionPolicy_cli_2_topic"></a>

次のコード例は、`delete-playback-restriction-policy` を使用する方法を示しています。

**AWS CLI**  
**再生制限ポリシーを削除するには**  
次の `delete-playback-restriction-policy` の例では、指定されたポリシー ARN (Amazon リソースネーム) を持つ再生制限ポリシーを削除します。  

```
aws ivs delete-playback-restriction-policy \
    --arn "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ"
```
このコマンドは何も出力しません。  
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePlaybackRestrictionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/delete-playback-restriction-policy.html)」を参照してください。

### `delete-recording-configuration`
<a name="ivs_DeleteRecordingConfiguration_cli_2_topic"></a>

次のコード例は、`delete-recording-configuration` を使用する方法を示しています。

**AWS CLI**  
**ARN で指定された RecordingConfiguration リソースを削除するには**  
次の `delete-recording-configuration` の例では、指定された ARN を持つ RecordingConfiguration リソースを削除します。  

```
aws ivs delete-recording-configuration \
    --arn "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABcdef34ghIJ"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/userguide/record-to-s3.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRecordingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/delete-recording-configuration.html)」を参照してください。

### `delete-stream-key`
<a name="ivs_DeleteStreamKey_cli_2_topic"></a>

次のコード例は、`delete-stream-key` を使用する方法を示しています。

**AWS CLI**  
**ストリームキーを削除するには**  
次の `delete-stream-key` の例では、指定された ARN (Amazon リソースネーム) のストリームキーを削除して、ストリーミングに使用できないようにします。  

```
aws ivs delete-stream-key \
    --arn arn:aws:ivs:us-west-2:123456789012:stream-key/g1H2I3j4k5L6
```
このコマンドは何も出力しません。  
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStreamKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/delete-stream-key.html)」を参照してください。

### `get-channel`
<a name="ivs_GetChannel_cli_2_topic"></a>

次のコード例は、`get-channel` を使用する方法を示しています。

**AWS CLI**  
**チャネルの設定情報を取得するには**  
次の `get-channel` の例では、指定されたチャネル ARN (Amazon リソースネーム) のチャネル設定を取得します。  

```
aws ivs get-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh'
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "authorized": false,
        "containerFormat": "TS",
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "latencyMode": "LOW",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "name": "channel-1",
        "playbackRestrictionPolicyArn": "",
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "tags": {}
        "type": "STANDARD",
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/get-channel.html)」を参照してください。

### `get-playback-key-pair`
<a name="ivs_GetPlaybackKeyPair_cli_2_topic"></a>

次のコード例は、`get-playback-key-pair` を使用する方法を示しています。

**AWS CLI**  
**指定された再生キーペアを取得するには**  
次の `get-playback-key-pair` の例では、指定されたキーペアのフィンガープリントを返します。  

```
aws ivs get-playback-key-pair \
    --arn arn:aws:ivs:us-west-2:123456789012:playback-key/abcd1234efgh
```
出力:  

```
{
    "keyPair": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:playback-key/abcd1234efgh",
        "name": "my-playback-key",
        "fingerprint": "0a:1b:2c:ab:cd:ef:34:56:70:b1:b2:71:01:2a:a3:72",
        "tags": {}
    }
}
```
詳細については、「Amazon Interactive Video Service ユーザーガイド」の「[プライベートチャネルの設定](https://docs.aws.amazon.com/ivs/latest/userguide//private-channels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPlaybackKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/get-playback-key-pair.html)」を参照してください。

### `get-playback-restriction-policy`
<a name="ivs_GetPlaybackRestrictionPolicy_cli_2_topic"></a>

次のコード例は、`get-playback-restriction-policy` を使用する方法を示しています。

**AWS CLI**  
**再生制限ポリシーの設定情報を取得するには**  
次の `get-playback-restriction-policy` の例では、指定されたポリシー ARN (Amazon リソースネーム) を持つ再生制限ポリシーの設定を取得します。  

```
aws ivs get-playback-restriction-policy \
    --arn "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ"
```
出力:  

```
{
    "playbackRestrictionPolicy": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
        "allowedCountries": [
            "US",
            "MX"
        ],
        "allowedOrigins": [
            "https://www.website1.com",
            "https://www.website2.com"
        ],
        "enableStrictOriginEnforcement": true,
        "name": "test-playback-restriction-policy",
        "tags": {
            "key1": "value1",
            "key2": "value2"
        }
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPlaybackRestrictionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/get-playback-restriction-policy.html)」を参照してください。

### `get-recording-configuration`
<a name="ivs_GetRecordingConfiguration_cli_2_topic"></a>

次のコード例は、`get-recording-configuration` を使用する方法を示しています。

**AWS CLI**  
**RecordingConfiguration リソースに関する情報を取得するには**  
次の `get-recording-configuration` の例では、指定された ARN の RecordingConfiguration リソースに関する情報を取得します。  

```
aws ivs get-recording-configuration \
    --arn "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABcdef34ghIJ"
```
出力:  

```
{
    "recordingConfiguration": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABcdef34ghIJ",
        "destinationConfiguration": {
            "s3": {
                "bucketName": "demo-recording-bucket"
            }
        },
        "name": "test-recording-config",
        "recordingReconnectWindowSeconds": 60,
        "state": "ACTIVE",
        "tags": {
            "key1" : "value1",
            "key2" : "value2"
        },
        "thumbnailConfiguration": {
            "recordingMode": "INTERVAL",
            "targetIntervalSeconds": 1,
            "resolution": "LOWEST_RESOLUTION",
            "storage": [
                "LATEST"
            ]
        },
        "renditionConfiguration": {
            "renditionSelection": "CUSTOM",
            "renditions": [
                "HD"
            ]
        }
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/userguide/record-to-s3.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRecordingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/get-recording-configuration.html)」を参照してください。

### `get-stream-key`
<a name="ivs_GetStreamKey_cli_2_topic"></a>

次のコード例は、`get-stream-key` を使用する方法を示しています。

**AWS CLI**  
**ストリームに関する情報を取得するには**  
次の `get-stream-key` の例では、指定されたストリームキーに関する情報を取得します。  

```
aws ivs get-stream-key \
    --arn arn:aws:ivs:us-west-2:123456789012:stream-key/skSKABCDefgh --region=us-west-2
```
出力:  

```
{
    "streamKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/skSKABCDefgh",
        "value": "sk_us-west-2_abcdABCDefgh_567890abcdef",
        "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStreamKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/get-stream-key.html)」を参照してください。

### `get-stream-session`
<a name="ivs_GetStreamSession_cli_2_topic"></a>

次のコード例は、`get-stream-session` を使用する方法を示しています。

**AWS CLI**  
**指定されたストリームのメタデータを取得するには**  
次の `get-stream-session` の例では、指定されたチャネル ARN (Amazon リソースネーム) と指定されたストリームのメタデータ設定を取得します。`streamId` が指定されていない場合、チャネルの最新のストリームが選択されます。  

```
aws ivs get-stream-session \
    --channel-arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --stream-id 'mystream'
```
出力:  

```
{
    "streamSession": {
        "streamId": "mystream1",
        "startTime": "2023-06-26T19:09:28+00:00",
        "channel": {
            "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "name": "mychannel",
            "latencyMode": "LOW",
            "type": "STANDARD",
            "recordingConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABcdef34ghIJ",
            "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
            "playbackUrl": "url-string",
            "authorized": false,
            "insecureIngest": false,
            "preset": ""
        },
        "ingestConfiguration": {
            "audio": {
                "channels": 2,
                "codec": "mp4a.40.2",
                "sampleRate": 8000,
                "targetBitrate": 46875,
                "track": "Track0"
            },
            "video": {
                "avcProfile": "Baseline",
                "avcLevel": "4.2",
                "codec": "avc1.42C02A",
                "encoder": "Lavf58.45.100",
                "level": "4.2",
                "profile": "Baseline",
                "targetBitrate": 8789062,
                "targetFramerate": 60,
                "track": "Track0",
                "videoHeight": 1080,
                "videoWidth": 1920
            }
        },
        "ingestConfigurations": {
            "audioConfigurations": [
                {
                    "channels": 2,
                    "codec": "mp4a.40.2",
                    "sampleRate": 8000,
                    "targetBitrate": 46875,
                    "track": "Track0"
                }
            ],
            "videoConfigurations": [
                {
                    "codec": "avc1.42C02A",
                    "encoder": "Lavf58.45.100",
                    "level": "4.2",
                    "profile": "Baseline",
                    "targetBitrate": 8789062,
                    "targetFramerate": 60,
                    "track": "Track0",
                    "videoHeight": 1080,
                    "videoWidth": 1920
                }
            ]
        },
        "recordingConfiguration": {
            "arn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABcdef34ghIJ",
            "name": "test-recording-config",
            "destinationConfiguration": {
                "s3": {
                    "bucketName": "demo-recording-bucket"
                }
            },
            "state": "ACTIVE",
            "tags": {
                "key1": "value1",
                "key2": "value2"
            },
            "thumbnailConfiguration": {
                "recordingMode": "INTERVAL",
                "targetIntervalSeconds": 1,
                "resolution": "LOWEST_RESOLUTION",
                "storage": [
                    "LATEST"
                ]
            },
            "recordingReconnectWindowSeconds": 60,
            "renditionConfiguration": {
                "renditionSelection": "CUSTOM",
                "renditions": [
                    "HD"
                ]
            }
        },
        "truncatedEvents": [
            {
                "code": "StreamTakeoverInvalidPriority",
                "name": "Stream Takeover Failure",
                "type": "IVS Stream State Change",
                "eventTime": "2023-06-26T19:09:48+00:00"
            },
            {
                "name": "Stream Takeover",
                "type": "IVS Stream State Change",
                "eventTime": "2023-06-26T19:09:47+00:00"
            },
            {
                "name": "Recording Start",
                "type": "IVS Recording State Change",
                "eventTime": "2023-06-26T19:09:35+00:00"
            },
            {
                "name": "Stream Start",
                "type": "IVS Stream State Change",
                "eventTime": "2023-06-26T19:09:34+00:00"
            },
            {
                "name": "Session Created",
                "type": "IVS Stream State Change",
                "eventTime": "2023-06-26T19:09:28+00:00"
            }
        ]
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStreamSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/get-stream-session.html)」を参照してください。

### `get-stream`
<a name="ivs_GetStream_cli_2_topic"></a>

次のコード例は、`get-stream` を使用する方法を示しています。

**AWS CLI**  
**ストリームに関する情報を取得するには**  
次の `get-stream` の例では、指定されたチャネルのストリームに関する情報を取得します。  

```
aws ivs get-stream \
    --channel-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh
```
出力:  

```
{
    "stream": {
        "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "startTime": "2020-05-05T21:55:38Z",
        "state": "LIVE",
        "health": "HEALTHY",
        "streamId": "st-ABCDEfghij01234KLMN5678",
        "viewerCount": 1
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/get-stream.html)」を参照してください。

### `import-playback-key-pair`
<a name="ivs_ImportPlaybackKeyPair_cli_2_topic"></a>

次のコード例は、`import-playback-key-pair` を使用する方法を示しています。

**AWS CLI**  
**新しいキーペアのパブリック部分をインポートするには**  
次の `import-playback-key-pair` の例では、指定されたパブリックキー (PEM 形式の文字列として指定) をインポートし、新しいキーペアの arn とフィンガープリントを返します。  

```
aws ivs import-playback-key-pair \
    --name "my-playback-key" \
    --public-key-material "G1lbnQxOTA3BgNVBAMMMFdoeSBhcmUgeW91IGRl..."
```
出力:  

```
{
    "keyPair": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:playback-key/abcd1234efgh",
        "name": "my-playback-key",
        "fingerprint": "0a:1b:2c:ab:cd:ef:34:56:70:b1:b2:71:01:2a:a3:72",
        "tags": {}
    }
}
```
詳細については、「Amazon Interactive Video Service ユーザーガイド」の「[プライベートチャネルの設定](https://docs.aws.amazon.com/ivs/latest/userguide//private-channels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportPlaybackKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/import-playback-key-pair.html)」を参照してください。

### `list-channels`
<a name="ivs_ListChannels_cli_2_topic"></a>

次のコード例は、`list-channels` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのチャネルに関する概要情報を取得するには**  
次の の`list-channels`例では、 AWS アカウントのすべてのチャネルを一覧表示します。  

```
aws ivs list-channels
```
出力:  

```
{
    "channels": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "name": "channel-1",
            "latencyMode": "LOW",
            "authorized": false,
            "insecureIngest": false,
            "preset": "",
            "playbackRestrictionPolicyArn": "",
            "recordingConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh",
            "tags": {},
            "type": "STANDARD"
        },
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:channel/efghEFGHijkl",
            "name": "channel-2",
            "latencyMode": "LOW",
            "authorized": false,
            "preset": "",
            "playbackRestrictionPolicyArn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
            "recordingConfigurationArn": "",
            "tags": {},
            "type": "STANDARD"
        }
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
**例 2: すべてのチャネルに関する概要情報を、指定された RecordingConfiguration ARN でフィルタリングして取得するには**  
次の の`list-channels`例では、指定された RecordingConfiguration ARN に関連付けられている AWS アカウントのすべてのチャネルを一覧表示します。  

```
aws ivs list-channels \
    --filter-by-recording-configuration-arn "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh"
```
出力:  

```
{
    "channels": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "name": "channel-1",
            "latencyMode": "LOW",
            "authorized": false,
            "insecureIngest": false,
            "preset": "",
            "playbackRestrictionPolicyArn": "",
            "recordingConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh",
            "tags": {},
            "type": "STANDARD"
        }
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/record-to-s3.html)」を参照してください。  
**例 3: すべてのチャネルに関する概要情報を、指定された PlaybackRestrictionPolicy ARN でフィルタリングして取得するには**  
次の の`list-channels`例では、指定された PlaybackRestrictionPolicy ARN に関連付けられている AWS アカウントのすべてのチャネルを一覧表示します。  

```
aws ivs list-channels \
    --filter-by-playback-restriction-policy-arn "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ"
```
出力:  

```
{
    "channels": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:channel/efghEFGHijkl",
            "name": "channel-2",
            "latencyMode": "LOW",
            "authorized": false,
            "preset": "",
            "playbackRestrictionPolicyArn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
            "recordingConfigurationArn": "",
            "tags": {},
            "type": "STANDARD"
        }
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListChannels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-channels.html)」を参照してください。**

### `list-playback-key-pairs`
<a name="ivs_ListPlaybackKeyPairs_cli_2_topic"></a>

次のコード例は、`list-playback-key-pairs` を使用する方法を示しています。

**AWS CLI**  
**すべての再生キーペアに関する概要情報を取得するには**  
次の `list-playback-key-pairs` の例では、すべてのキーペアに関する情報を返します。  

```
aws ivs list-playback-key-pairs
```
出力:  

```
{
    "keyPairs": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:playback-key/abcd1234efgh",
            "name": "test-key-0",
            "tags": {}
        },
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:playback-key/ijkl5678mnop",
            "name": "test-key-1",
            "tags": {}
        }
    ]
}
```
詳細については、「Amazon Interactive Video Service ユーザーガイド」の「[プライベートチャネルの設定](https://docs.aws.amazon.com/ivs/latest/userguide//private-channels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPlaybackKeyPairs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-playback-key-pairs.html)」を参照してください。

### `list-playback-restriction-policies`
<a name="ivs_ListPlaybackRestrictionPolicies_cli_2_topic"></a>

次のコード例は、`list-playback-restriction-policies` を使用する方法を示しています。

**AWS CLI**  
**すべての再生制限ポリシーに関する概要情報を取得するには**  
次の の`list-playback-restriction-policies`例では、 AWS アカウントのすべての再生制限ポリシーを一覧表示します。  

```
aws ivs list-playback-restriction-policies
```
出力:  

```
{
    "playbackRestrictionPolicies": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
            "allowedCountries": [
                "US",
                "MX"
            ],
            "allowedOrigins": [
                "https://www.website1.com",
                "https://www.website2.com"
            ],
            "enableStrictOriginEnforcement": true,
            "name": "test-playback-restriction-policy",
            "tags": {
                "key1": "value1",
                "key2": "value2"
            }
        }
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPlaybackRestrictionPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-playback-restriction-policies.html)」を参照してください。

### `list-recording-configurations`
<a name="ivs_ListRecordingConfigurations_cli_2_topic"></a>

次のコード例は、`list-recording-configurations` を使用する方法を示しています。

**AWS CLI**  
**このアカウントで作成されたすべての RecordingConfiguration リソースを一覧表示するには**  
次の `list-recording-configurations` の例では、アカウント内のすべての RecordingConfiguration リソースに関する情報を取得します。  

```
aws ivs list-recording-configurations
```
出力:  

```
{
    "recordingConfigurations": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABcdef34ghIJ",
            "name": "test-recording-config-1",
            "destinationConfiguration": {
                "s3": {
                    "bucketName": "demo-recording-bucket-1"
                }
            },
            "state": "ACTIVE",
            "tags": {}
        },
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/CD12abcdGHIJ",
            "name": "test-recording-config-2",
            "destinationConfiguration": {
                "s3": {
                    "bucketName": "demo-recording-bucket-2"
                }
            },
            "state": "ACTIVE",
            "tags": {}
        }
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/userguide/record-to-s3.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRecordingConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-recording-configurations.html)」を参照してください。

### `list-stream-keys`
<a name="ivs_ListStreamKeys_cli_2_topic"></a>

次のコード例は、`list-stream-keys` を使用する方法を示しています。

**AWS CLI**  
**ストリームキーのリストを取得するには**  
次の `list-stream-keys` の例では、指定された ARN (Amazon リソースネーム) のすべてのストリームキーを一覧表示します。  

```
aws ivs list-stream-keys \
    --channel-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh
```
出力:  

```
{
    "streamKeys": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:stream-key/abcdABCDefgh",
            "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "tags": {}
        }
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStreamKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-stream-keys.html)」を参照してください。

### `list-stream-sessions`
<a name="ivs_ListStreamSessions_cli_2_topic"></a>

次の例は、`list-stream-sessions` を使用する方法を説明しています。

**AWS CLI**  
**現在の AWS リージョンで指定されたチャネルの現在および以前のストリームの概要を取得するには**  
次の `list-stream-sessions` の例では、指定されたチャネル ARN (Amazon リソースネーム) のストリームの概要情報をレポートします。  

```
aws ivs list-stream-sessions \
    --channel-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh \
    --max-results 25 \
    --next-token ""
```
出力:  

```
{
    "nextToken": "set-2",
    "streamSessions": [
        {
            "startTime": 1641578182,
            "endTime": 1641579982,
            "hasErrorEvent": false,
            "streamId": "mystream"
        }
        ...
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStreamSessions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-stream-sessions.html)」を参照してください。

### `list-streams`
<a name="ivs_ListStreams_cli_2_topic"></a>

次のコード例は、`list-streams` を使用する方法を示しています。

**AWS CLI**  
**ライブストリームとその状態のリストを取得するには**  
次の の`list-streams`例では、 AWS アカウントのすべてのライブストリームを一覧表示します。  

```
aws ivs list-streams
```
出力:  

```
{
   "streams": [
        {
            "channelArn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
            "state": "LIVE",
            "health": "HEALTHY",
            "streamId": "st-ABCDEfghij01234KLMN5678",
            "viewerCount": 1
        }
    ]
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-streams.html)」を参照してください。**

### `list-tags-for-resource`
<a name="ivs_ListTagsForResource_cli_2_topic"></a>

次の例は、`list-tags-for-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースのすべてのタグを一覧表示するには (チャネル、ストリームキーなど)**  
次の `list-tags-for-resource` の例では、指定されたリソース ARN (Amazon リソースネーム) のすべてのタグを一覧表示します。  

```
aws ivs list-tags-for-resource \
    --resource-arn arn:aws:ivs:us-west-2:12345689012:channel/abcdABCDefgh
```
出力:  

```
{
    "tags":
    {
        "key1": "value1",
        "key2": "value2"
    }
}
```
詳細については、「*Amazon Interactive Video Service API リファレンス*」の「[Tagging](https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/list-tags-for-resource.html)」を参照してください。

### `put-metadata`
<a name="ivs_PutMetadata_cli_2_topic"></a>

次のコード例は、`put-metadata` を使用する方法を示しています。

**AWS CLI**  
**指定されたチャネルのアクティブなストリームにメタデータを挿入するには**  
次の `put-metadata` の例では、指定されたメタデータを、指定されたチャネルのストリームに挿入します。  

```
aws ivs put-metadata \
    --channel-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh \
    --metadata '{"my": "metadata"}'
```
このコマンドは何も出力しません。  
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/put-metadata.html)」を参照してください。

### `start-viewer-session-revocation`
<a name="ivs_StartViewerSessionRevocation_cli_2_topic"></a>

次のコード例は、`start-viewer-session-revocation` を使用する方法を示しています。

**AWS CLI**  
**特定の複数の channel-ARN と viewer-ID ペアのビューワーセッションを取り消すには**  
次の `start-viewer-session-revocation` の例では、指定されたチャネル ARN とビューワー ID に関連付けられたビューワーセッションのうち、指定されたセッションバージョン番号以下のものを取り消すプロセスを開始します。バージョンが指定されていない場合は、デフォルトで 0 になります。  

```
aws ivs batch-start-viewer-session-revocation \
    --channel-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh \
    --viewer-id abcdefg \
    --viewer-session-versions-less-than-or-equal-to 1234567890
```
このコマンドは何も出力しません。  
詳細については、「Amazon Interactive Video Service ユーザーガイド」の「[プライベートチャネルの設定](https://docs.aws.amazon.com/ivs/latest/userguide/private-channels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartViewerSessionRevocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/start-viewer-session-revocation.html)」を参照してください。

### `stop-stream`
<a name="ivs_StopStream_cli_2_topic"></a>

次のコード例は、`stop-stream` を使用する方法を示しています。

**AWS CLI**  
**指定されたストリームを停止するには**  
次の `stop-stream` の例では、指定されたチャネルのストリームを停止します。  

```
aws ivs stop-stream \
    --channel-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh
```
このコマンドは何も出力しません。  
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/stop-stream.html)」を参照してください。

### `tag-resource`
<a name="ivs_TagResource_cli_2_topic"></a>

次の例は、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースのタグを追加または更新するには (チャネル、ストリームキーなど)**  
次の `tag-resource` の例では、指定されたリソース ARN (Amazon リソースネーム) のタグを追加または更新します。  

```
aws ivs tag-resource \
    --resource-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh \
    --tags "tagkey1=tagvalue1, tagkey2=tagvalue2"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service API リファレンス*」の「[Tagging](https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ivs_UntagResource_cli_2_topic"></a>

次の例は、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースのタグを削除するには (チャネル、ストリームキーなど)**  
次の `untag-resource` の例では、指定されたリソース ARN (Amazon リソースネーム) の指定されたタグを削除します。  

```
aws ivs untag-resource \
    --resource-arn arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh \
    --tag-keys "tagkey1, tagkey2"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service API リファレンス*」の「[Tagging](https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/untag-resource.html)」を参照してください。

### `update-channel`
<a name="ivs_UpdateChannel_cli_2_topic"></a>

次のコード例は、`update-channel` を使用する方法を示しています。

**AWS CLI**  
**例 1: チャネルの設定情報を更新するには**  
次の `update-channel` の例では、指定されたチャネル ARN のチャネル設定を更新して、チャネル名を変更します。これは、このチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --name 'channel-1' \
    --insecure-ingest
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "name": "channel-1",
        "latencyMode": "LOW",
        "containerFormat": "TS",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": true,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {}
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/getting-started-create-channel.html)」を参照してください。  
**例 2: チャネルの設定を更新して録画を有効にするには**  
次の `update-channel` の例では、指定されたチャネル ARN のチャネル設定を更新して、録画を有効にします。これは、このチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --no-insecure-ingest \
    --recording-configuration-arn 'arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh'
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "name": "test-channel-with-recording",
        "latencyMode": "LOW",
        "containerFormat": "TS",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:recording-configuration/ABCD12cdEFgh",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "BA1C2defGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/record-to-s3.html)」を参照してください。  
**例 3: チャネルの設定を更新して録画を無効にするには**  
次の `update-channel` の例では、指定されたチャネル ARN のチャネル設定を更新して、録画を無効にします。これは、このチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --recording-configuration-arn ''
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "name": "test-channel-with-recording",
        "latencyMode": "LOW",
        "containerFormat": "TS",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2edfGHijkLMNo3PqQRstUvwxyzaBCDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[Amazon S3 に記録](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/record-to-s3.html)」を参照してください。  
**例 4: チャネルの設定を更新して再生制限を有効にするには**  
次の `update-channel` の例では、指定されたチャネル ARN のチャネル設定を更新して、再生制限ポリシーを適用します。これは、このチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --no-insecure-ingest \
    --playback-restriction-policy-arn 'arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ'
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "name": "test-channel-with-playback-restriction-policy",
        "latencyMode": "LOW",
        "containerFormat": "TS",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaCBDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
**例 5: チャネルの設定を更新して再生制限を無効にするには**  
次の `update-channel` の例では、指定されたチャネル ARN のチャネル設定を更新して、再生制限を無効にします。これは、このチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --playback-restriction-policy-arn ''
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "name": "test-channel-with-playback-restriction-policy",
        "latencyMode": "LOW",
        "containerFormat": "TS",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaBCDeFghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
**例 6: チャネルの設定を更新してマルチトラックを有効にするには**  
次の `update-channel` の例では、指定されたチャネル ARN のチャネル設定を更新して、マルチトラックを有効にします。これは、このチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --container-format 'FRAGMENTED_MP4' \
    --multitrack-input-configuration '{"enabled": true,"maximumResolution": "FULL_HD","policy": "ALLOW"}'
```
出力:  

```
{
    "channel": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "containerFormat": "FRAGMENTED_MP4",
        "name": "test-channel-with-multitrack",
        "latencyMode": "LOW",
        "multitrackInputConfiguration": {
            "enabled": true,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaCBDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multitrack-video.html)」を参照してください。  
**例 7: チャネルの設定を更新して再生制限を無効にするには**  
次の `update-channel` の例では、指定されたチャネル ARN のチャネル設定を更新して、マルチトラックを無効にします。これは、このチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-channel \
    --arn 'arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh' \
    --container-format 'TS' \
    --multitrack-input-configuration '{"enabled": false}'
```
出力:  

```
{
    "channel": {
        ""arn": "arn:aws:ivs:us-west-2:123456789012:channel/abcdABCDefgh",
        "containerFormat": "TS",
        "name": "test-channel-with-multitrack",
        "latencyMode": "LOW",
        "multitrackInputConfiguration": {
            "enabled": false,
            "maximumResolution": "FULL_HD",
            "policy": "ALLOW"
        },
        "type": "STANDARD",
        "playbackRestrictionPolicyArn": "",
        "recordingConfigurationArn": "",
        "srt": {
            "endpoint": "a1b2c3d4e5f6.srt.live-video.net",
            "passphrase": "AB1C2defGHijkLMNo3PqQRstUvwxyzaCBDEfghh4ijklMN5opqrStuVWxyzAbCDEfghIJ"
        },
        "ingestEndpoint": "a1b2c3d4e5f6.global-contribute.live-video.net",
        "insecureIngest": false,
        "playbackUrl": "https://a1b2c3d4e5f6.us-west-2.playback.live-video.net/api/video/v1/us-west-2.123456789012.channel.abcdEFGH.m3u8",
        "preset": "",
        "authorized": false,
        "tags": {}
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multitrack-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/update-channel.html)」を参照してください。

### `update-playback-restriction-policy`
<a name="ivs_UpdatePlaybackRestrictionPolicy_cli_2_topic"></a>

次のコード例は、`update-playback-restriction-policy` を使用する方法を示しています。

**AWS CLI**  
**再生制限ポリシーを更新するには**  
次の `update-playback-restriction-policy` の例では、指定されたポリシー ARN を持つ再生制限ポリシーを更新して、厳格なオリジン強制を無効にします。これは、関連付けられたチャネルの進行中のストリームには影響しません。変更を有効にするには、ストリームを停止して再開する必要があります。  

```
aws ivs update-playback-restriction-policy \
    --arn "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ" \
    --no-enable-strict-origin-enforcement
```
出力:  

```
{
    "playbackRestrictionPolicy": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:playback-restriction-policy/ABcdef34ghIJ",
        "allowedCountries": [
            "US",
            "MX"
        ],
        "allowedOrigins": [
            "https://www.website1.com",
            "https://www.website2.com"
        ],
        "enableStrictOriginEnforcement": false,
        "name": "test-playback-restriction-policy",
        "tags": {
            "key1": "value1",
            "key2": "value2"
        }
    }
}
```
詳細については、「*IVS Low-Latency ユーザーガイド*」の「[望ましくないコンテンツと視聴者](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/undesired-content.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePlaybackRestrictionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs/update-playback-restriction-policy.html)」を参照してください。

# を使用した Amazon IVS Chat の例 AWS CLI
<a name="cli_2_ivschat_code_examples"></a>

次のコード例は、Amazon IVS Chat AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-chat-token`
<a name="ivschat_CreateChatToken_cli_2_topic"></a>

次のコード例は、`create-chat-token` を使用する方法を示しています。

**AWS CLI**  
**チャットトークンを作成するには**  
次の `create-chat-token` の例では、ルームへの個々の WebSocket 接続の確立に使用される暗号化されたチャットトークンを作成します。トークンは 1 分間有効であり、トークンで確立された接続 (セッション) は指定された期間有効です。  

```
aws ivschat create-chat-token \
    --roomIdentifier "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6", \
    --userId" "11231234" \
    --capabilities "SEND_MESSAGE", \
    --sessionDurationInMinutes" 30
```
出力:  

```
{
    "token": "ACEGmnoq#1rstu2...BDFH3vxwy!4hlm!#5",
    "sessionExpirationTime": "2022-03-16T04:44:09+00:00"
    "state": "CREATING",
    "tokenExpirationTime": "2022-03-16T03:45:09+00:00"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[ステップ 3: チャットクライアントの認証と認可](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateChatToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/create-chat-token.html)」を参照してください。

### `create-logging-configuration`
<a name="ivschat_CreateLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`create-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**チャットの LoggingConfiguration リソースを作成するには**  
次の `create-logging-configuration` の例では、クライアントが送信されたメッセージを保存および記録できるようにする LoggingConfiguration リソースを作成します。  

```
aws ivschat create-logging-configuration \
    --destination-configuration s3={bucketName=demo-logging-bucket} \
    --name "test-logging-config" \
    --tags "key1=value1, key2=value2"
```
出力:  

```
{
    "arn": "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ",
    "createTime": "2022-09-14T17:48:00.653000+00:00",
    "destinationConfiguration": {
        "s3": {
            "bucketName": "demo-logging-bucket"
        }
    },
    "id": "ABcdef34ghIJ",
    "name": "test-logging-config",
    "state": "ACTIVE",
    "tags": { "key1" : "value1", "key2" : "value2" },
    "updateTime": "2022-09-14T17:48:01.104000+00:00"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/create-logging-configuration.html)」を参照してください。

### `create-room`
<a name="ivschat_CreateRoom_cli_2_topic"></a>

次のコード例は、`create-room` を使用する方法を示しています。

**AWS CLI**  
**ルームを作成するには**  
次の `create-room` の例では、新しいルームを作成します。  

```
aws ivschat create-room \
    --name "test-room-1" \
    --logging-configuration-identifiers "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ" \
    --maximum-message-length 256 \
    --maximum-message-rate-per-second 5
```
出力:  

```
{
    "arn": "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6",
    "id": "g1H2I3j4k5L6",
    "createTime": "2022-03-16T04:44:09+00:00",
    "loggingConfigurationIdentifiers": ["arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"],
    "maximumMessageLength": 256,
    "maximumMessageRatePerSecond": 5,
    "name": "test-room-1",
    "tags": {}
    "updateTime": "2022-03-16T07:22:09+00:00"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[ステップ 2: チャットルームを作成する](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/create-room.html)」を参照してください。

### `delete-logging-configuration`
<a name="ivschat_DeleteLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`delete-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**チャットの LoggingConfiguration リソースを削除するには**  
次の `delete-logging-configuration` の例では、指定された ARN の LoggingConfiguration リソースを削除します。  

```
aws ivschat delete-logging-configuration \
    --identifier "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/delete-logging-configuration.html)」を参照してください。

### `delete-message`
<a name="ivschat_DeleteMessage_cli_2_topic"></a>

次のコード例は、`delete-message` を使用する方法を示しています。

**AWS CLI**  
**指定されたルームからメッセージを削除するには**  
次の `delete-message` の例では、指定されたルームにイベントを送信し、指定されたメッセージを削除するようにクライアントに指示します。つまり、メッセージのレンダリング内容をビューから削除し、クライアントのチャット履歴からメッセージを削除します。  

```
aws ivschat delete-message \
    --roomIdentifier "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6" \
    --id "ABC123def456" \
    --reason "Message contains profanity"
```
出力:  

```
{
    "id": "12345689012"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/delete-message.html)」を参照してください。**

### `delete-room`
<a name="ivschat_DeleteRoom_cli_2_topic"></a>

次のコード例は、`delete-room` を使用する方法を示しています。

**AWS CLI**  
**ルームを削除するには**  
次の `delete-room` の例では、指定されたルームを削除します。接続されているクライアントは切断されます。成功すると、レスポンスの本文が空の HTTP 204 が返されます。  

```
aws ivschat delete-room \
    --identifier "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/delete-room.html)」を参照してください。

### `disconnect-user`
<a name="ivschat_DisconnectUser_cli_2_topic"></a>

次のコード例は、`disconnect-user` を使用する方法を示しています。

**AWS CLI**  
**ルームからユーザーを切断するには**  
次の `disconnect-user` の例では、指定されたユーザーのすべての接続を指定されたルームから切断します。成功すると、レスポンスの本文が空の HTTP 200 が返されます。  

```
aws ivschat disconnect-user \
    --roomIdentifier "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6" \
    --userId "ABC123def456" \
    --reason "Violated terms of service"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisconnectUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/disconnect-user.html)」を参照してください。

### `get-logging-configuration`
<a name="ivschat_GetLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`get-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**LoggingConfiguration リソースに関する情報を取得するには**  
次の `get-logging-configuration` の例では、指定された ARN の LoggingConfiguration リソースに関する情報を取得します。  

```
aws ivschat get-logging-configuration \
    --identifier "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"
```
出力:  

```
{
    "arn": "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ",
    "createTime": "2022-09-14T17:48:00.653000+00:00",
    "destinationConfiguration": {
        "s3": {
            "bucketName": "demo-logging-bucket"
        }
    },
    "id": "ABcdef34ghIJ",
    "name": "test-logging-config",
    "state": "ACTIVE",
    "tags": { "key1" : "value1", "key2" : "value2" },
    "updateTime": "2022-09-14T17:48:01.104000+00:00"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/get-logging-configuration.html)」を参照してください。

### `get-room`
<a name="ivschat_GetRoom_cli_2_topic"></a>

次のコード例は、`get-room` を使用する方法を示しています。

**AWS CLI**  
**指定されたルームを取得するには**  
次の `get-room` の例では、指定されたルームに関する情報を取得します。  

```
aws ivschat get-room \
    --identifier "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6"
```
出力:  

```
{
    "arn": "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6",
    "createTime": "2022-03-16T04:44:09+00:00",
    "id": "g1H2I3j4k5L6",
    "loggingConfigurationIdentifiers": ["arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"],
    "maximumMessageLength": 256,
    "maximumMessageRatePerSecond": 5,
    "name": "test-room-1",
    "tags": {},
    "updateTime": "2022-03-16T07:22:09+00:00"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/get-room.html)」を参照してください。

### `list-logging-configurations`
<a name="ivschat_ListLoggingConfigurations_cli_2_topic"></a>

次の例は、`list-logging-configurations` を使用する方法を説明しています。

**AWS CLI**  
**API リクエストが処理される AWS リージョンのユーザーのすべてのログ記録設定に関する概要情報を取得するには**  
次の の`list-logging-configurations`例では、API リクエストが処理される AWS リージョンのユーザーのすべての LoggingConfiguration リソースに関する情報を一覧表示します。  

```
aws ivschat list-logging-configurations \
    --max-results 2 \
    --next-token ""
```
出力:  

```
{
    "nextToken": "set-2",
    "loggingConfigurations": [
        {
            "arn": "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ",
            "createTime": "2022-09-14T17:48:00.653000+00:00",
            "destinationConfiguration": {
                "s3": {
                    "bucketName": "demo-logging-bucket"
                }
            },
            "id": "ABcdef34ghIJ",
            "name": "test-logging-config",
            "state": "ACTIVE",
            "tags": { "key1" : "value1", "key2" : "value2" },
            "updateTime": "2022-09-14T17:48:01.104000+00:00"
        }
        ...
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLoggingConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/list-logging-configurations.html)」を参照してください。

### `list-rooms`
<a name="ivschat_ListRooms_cli_2_topic"></a>

次のコード例は、`list-rooms` を使用する方法を示しています。

**AWS CLI**  
**現在のリージョンのすべてのルームに関する概要情報を取得するには**  
次の の`list-rooms`例では、リクエストが処理される AWS リージョン内のすべてのルームに関する概要情報を取得します。結果は updateTime の降順でソートされます。  

```
aws ivschat list-rooms \
    --logging-configuration-identifier "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ" \
    --max-results 10 \
    --next-token ""
```
出力:  

```
{
    "nextToken": "page3",
    "rooms": [
        {
            "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6",
            "createTime": "2022-03-16T04:44:09+00:00",
            "id": "g1H2I3j4k5L6",
            "loggingConfigurationIdentifiers": ["arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"],
            "name": "test-room-1",
            "tags": {},
            "updateTime": "2022-03-16T07:22:09+00:00"
        }
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRooms](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/list-rooms.html)」を参照してください。

### `list-tags-for-resource`
<a name="ivschat_ListTagsForResource_cli_2_topic"></a>

次の例は、`list-tags-for-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースのすべてのタグを一覧表示するには (例: Room)**  
次の `list-tags-for-resource` の例では、指定されたリソース ARN (Amazon リソースネーム) のすべてのタグを一覧表示します。  

```
aws ivschat list-tags-for-resource \
    --resource-arn arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6
```
出力:  

```
{
    "tags":
    {
        "key1": "value1",
        "key2": "value2"
    }
}
```
詳細については、「*Amazon Interactive Video Service API リファレンス*」の「[Tagging](https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/list-tags-for-resource.html)」を参照してください。

### `send-event`
<a name="ivschat_SendEvent_cli_2_topic"></a>

次のコード例は、`send-event` を使用する方法を示しています。

**AWS CLI**  
**イベントをルームに送信するには**  
次の `send-event` の例では、指定されたイベントを指定されたルームに送信します。  

```
aws ivschat send-event \
    --roomIdentifier "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6" \
    --eventName "SystemMessage" \
    --attributes \
        "msgType"="user-notification", \
        "msgText"="This chat room will close in 15 minutes."
```
出力:  

```
{
    "id": "12345689012"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendEvent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/send-event.html)」を参照してください。

### `tag-resource`
<a name="ivschat_TagResource_cli_2_topic"></a>

次の例は、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースのタグを追加または更新するには (例: Room)**  
次の `tag-resource` の例では、指定されたリソース ARN (Amazon リソースネーム) のタグを追加または更新します。成功すると、レスポンスの本文が空の HTTP 200 が返されます。  

```
aws ivschat tag-resource \
    --resource-arn arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6 \
    --tags "tagkey1=tagkeyvalue1, tagkey2=tagkeyvalue2"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service API リファレンス*」の「[Tagging](https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ivschat_UntagResource_cli_2_topic"></a>

次の例は、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースのタグを削除するには (例: Room)**  
次の `untag-resource` の例では、指定されたリソース ARN (Amazon リソースネーム) の指定されたタグを削除します。成功すると、レスポンスの本文が空の HTTP 200 が返されます。  

```
aws ivschat untag-resource \
    --resource-arn arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6 \
    --tag-keys "tagkey1, tagkey2"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service API リファレンス*」の「[Tagging](https://docs.aws.amazon.com/ivs/latest/APIReference/Welcome.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/untag-resource.html)」を参照してください。

### `update-logging-configuration`
<a name="ivschat_UpdateLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`update-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**ルームのログ記録設定を更新するには**  
次の `update-logging-configuration` の例では、指定されたデータを使用して LoggingConfiguration リソースを更新します。  

```
aws ivschat update-logging-configuration \
    --destination-configuration s3={bucketName=demo-logging-bucket} \
    --identifier "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ" \
    --name "test-logging-config"
```
出力:  

```
{
    "arn": "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ",
    "createTime": "2022-09-14T17:48:00.653000+00:00",
    "destinationConfiguration": {
        "s3": {
            "bucketName": "demo-logging-bucket"
        }
    },
    "id": "ABcdef34ghIJ",
    "name": "test-logging-config",
    "state": "ACTIVE",
    "tags": { "key1" : "value1", "key2" : "value2" },
    "updateTime": "2022-09-14T17:48:01.104000+00:00"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UpdateLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/update-logging-configuration.html)」を参照してください。

### `update-room`
<a name="ivschat_UpdateRoom_cli_2_topic"></a>

次のコード例は、`update-room` を使用する方法を示しています。

**AWS CLI**  
**ルームの設定を更新するには**  
次の `update-room` の例では、指定されたデータを使用して、指定されたルームの設定を更新します。  

```
aws ivschat update-room \
    --identifier "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6" \
    --logging-configuration-identifiers "arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ" \
    --name "chat-room-a" \
    --maximum-message-length 256 \
    --maximum-message-rate-per-second 5
```
出力:  

```
{
    "arn": "arn:aws:ivschat:us-west-2:12345689012:room/g1H2I3j4k5L6",
    "createTime": "2022-03-16T04:44:09+00:00",
    "id": "g1H2I3j4k5L6",
    "loggingConfigurationIdentifiers": ["arn:aws:ivschat:us-west-2:123456789012:logging-configuration/ABcdef34ghIJ"],
    "maximumMessageLength": 256,
    "maximumMessageRatePerSecond": 5,
    "name": "chat-room-a",
    "tags": {},
    "updateTime": "2022-03-16T07:22:09+00:00"
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS Chat の開始方法](https://docs.aws.amazon.com/ivs/latest/userguide/getting-started-chat.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRoom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivschat/update-room.html)」を参照してください。

# を使用した Amazon IVS リアルタイムストリーミングの例 AWS CLI
<a name="cli_2_ivs-realtime_code_examples"></a>

次のコード例は、Amazon IVS リアルタイムストリーミング AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-encoder-configuration`
<a name="ivs-realtime_CreateEncoderConfiguration_cli_2_topic"></a>

次のコード例は、`create-encoder-configuration` を使用する方法を示しています。

**AWS CLI**  
**コンポジションエンコーダー設定を作成するには**  
次の `create-encoder-configuration` の例では、指定されたプロパティを使用してコンポジションエンコーダー設定を作成します。  

```
aws ivs-realtime create-encoder-configuration \
    --name test-ec --video bitrate=3500000,framerate=30.0,height=1080,width=1920
```
出力:  

```
{
    "encoderConfiguration": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef",
        "name": "test-ec",
        "tags": {},
        "video": {
            "bitrate": 3500000,
            "framerate": 30,
            "height": 1080,
            "width": 1920
        }
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEncoderConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/create-encoder-configuration.html)」を参照してください。

### `create-ingest-configuration`
<a name="ivs-realtime_CreateIngestConfiguration_cli_2_topic"></a>

次のコード例は、`create-ingest-configuration` を使用する方法を示しています。

**AWS CLI**  
**取り込み設定を作成するには**  
次の `create-ingest-configuration` の例では、RTMPS プロトコルを使用して取り込み設定を作成します。  

```
aws ivs-realtime create-ingest-configuration \
    --name ingest1 \
    --ingest-protocol rtmps
```
出力:  

```
{
    "ingestConfiguration": {
        "name": "ingest1",
        "arn": "arn:aws:ivs:us-west-2:123456789012:ingest-configuration/AbCdEfGh1234",
        "ingestProtocol": "RTMPS",
        "streamKey": "rt_123456789012_us-west-2_AbCdEfGh1234_abcd1234efgh5678ijkl9012MNOP34",
        "stageArn": "",
        "participantId": "xyZ654abC321",
        "state": "INACTIVE",
        "userId": "",
        "tags": {}
    }
}
```
詳細については、*Amazon Interactive Video Service ユーザーガイド*の「[IVS ストリーム取り込み \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-stream-ingest.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateIngestConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/create-ingest-configuration.html)」を参照してください。

### `create-participant-token`
<a name="ivs-realtime_CreateParticipantToken_cli_2_topic"></a>

次のコード例は、`create-participant-token` を使用する方法を示しています。

**AWS CLI**  
**ステージ参加者トークンを作成するには**  
次の `create-participant-token` の例では、指定されたステージの参加者トークンを作成します。  

```
aws ivs-realtime create-participant-token \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --user-id bob
```
出力:  

```
{
    "participantToken": {
        "expirationTime": "2023-03-07T09:47:43+00:00",
        "participantId": "ABCDEfghij01234KLMN6789",
        "token": "abcd1234defg5678"
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/userguide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateParticipantToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/create-participant-token.html)」を参照してください。

### `create-stage`
<a name="ivs-realtime_CreateStage_cli_2_topic"></a>

次のコード例は、`create-stage` を使用する方法を示しています。

**AWS CLI**  
**例 1: ステージを作成するには**  
次の `create-stage` の例では、指定されたユーザーのステージとステージ参加者トークンを作成します。  

```
aws ivs-realtime create-stage \
    --name stage1 \
    --participant-token-configurations userId=alice
```
出力:  

```
{
    "participantTokens": [
        {
            "participantId": "ABCDEfghij01234KLMN5678",
            "token": "a1b2c3d4567890ab",
            "userId": "alice"
        }
    ],
    "stage": {
        "activeSessionId": "st-a1b2c3d4e5f6g",
        "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
        "autoParticipantRecordingConfiguration": {
            "storageConfigurationArn": "",
            "mediaTypes": [
                "AUDIO_VIDEO"
            ],
            "thumbnailConfiguration": {
                "targetIntervalSeconds": 60,
                "storage": [
                    "SEQUENTIAL"
                ],
                "recordingMode": "DISABLED"
            },
            "recordingReconnectWindowSeconds": 0,
            "hlsConfiguration": {
                "targetSegmentDurationSeconds": 6
            },
            "recordParticipantReplicas": true
        },
        "endpoints": {
            "events": "wss://global.events.live-video.net",
            "rtmp": "rtmp://9x0y8z7s6t5u.global-contribute-staging.live-video.net/app/",
            "rtmps": "rtmps://9x0y8z7s6t5u.global-contribute-staging.live-video.net:443/app/",
            "whip": "https://9x0y8z7s6t5u.global-bm.whip.live-video.net"
        },
        "name": "stage1",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 2: ステージを作成し、個々の参加者の録画を設定するには**  
次の `create-stage` の例では、ステージを作成し、個々の参加者の録画を設定します。  

```
aws ivs-realtime create-stage \
    --name stage1 \
    --auto-participant-recording-configuration '{"mediaTypes": ["AUDIO_VIDEO"],"storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh", "recordingReconnectWindowSeconds": 100, \
        "hlsConfiguration": {"targetSegmentDurationSeconds": 5}}'
```
出力:  

```
{
    "stage": {
        "activeSessionId": "st-a1b2c3d4e5f6g",
        "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
        "autoParticipantRecordingConfiguration": {
            "storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh"
            "mediaTypes": [
                "AUDIO_VIDEO"
            ],
            "thumbnailConfiguration": {
                "targetIntervalSeconds": 60,
                "storage": [
                    "SEQUENTIAL"
                ],
                "recordingMode": "DISABLED"
            },
            "recordingReconnectWindowSeconds": 100,
            "hlsConfiguration": {
                "targetSegmentDurationSeconds": 5
            },
            "recordParticipantReplicas": true
        },
        "endpoints": {
            "events": "wss://global.events.live-video.net",
            "rtmp": "rtmp://9x0y8z7s6t5u.global-contribute-staging.live-video.net/app/",
            "rtmps": "rtmps://9x0y8z7s6t5u.global-contribute-staging.live-video.net:443/app/",
            "whip": "https://9x0y8z7s6t5u.global-bm.whip.live-video.net"
        },
        "name": "stage1",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 3: ステージを作成し、サムネイルの記録が有効になっている個々の参加者の録画を設定するには**  
次の `create-stage` の例では、ステージを作成し、サムネイルの記録が有効になっている個々の参加者の録画を設定します。  

```
aws ivs-realtime create-stage \
    --name stage1 \
    --auto-participant-recording-configuration '{"mediaTypes": ["AUDIO_VIDEO"],"storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh", \
        "thumbnailConfiguration": {"recordingMode": "INTERVAL","storage": ["SEQUENTIAL"],"targetIntervalSeconds": 60}}'
```
出力:  

```
{
    "stage": {
        "activeSessionId": "st-a1b2c3d4e5f6g",
        "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
        "autoParticipantRecordingConfiguration": {
            "storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh",
            "mediaTypes": [
                "AUDIO_VIDEO"
            ],
            "thumbnailConfiguration": {
                "targetIntervalSeconds": 60,
                "storage": [
                    "SEQUENTIAL"
                ],
                "recordingMode": "INTERVAL"
            },
            "recordingReconnectWindowSeconds": 0,
            "hlsConfiguration": {
                "targetSegmentDurationSeconds": 6
            },
            "recordParticipantReplicas": true
        },
        "endpoints": {
            "events": "wss://global.events.live-video.net",
            "rtmp": "rtmp://9x0y8z7s6t5u.global-contribute-staging.live-video.net/app/",
            "rtmps": "rtmps://9x0y8z7s6t5u.global-contribute-staging.live-video.net:443/app/",
            "whip": "https://9x0y8z7s6t5u.global-bm.whip.live-video.net"
        },
        "name": "stage1",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/create-stage.html)」を参照してください。

### `create-storage-configuration`
<a name="ivs-realtime_CreateStorageConfiguration_cli_2_topic"></a>

次のコード例は、`create-storage-configuration` を使用する方法を示しています。

**AWS CLI**  
**コンポジションストレージ設定を作成するには**  
次の `create-storage-configuration` の例では、指定されたプロパティを使用してコンポジションストレージ設定を作成します。  

```
aws ivs-realtime create-storage-configuration \
    --name "test-sc" --s3 "bucketName=amzn-s3-demo-bucket"
```
出力:  

```
{
    "storageConfiguration": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/ABabCDcdEFef",
        "name": "test-sc",
        "s3": {
            "bucketName": "amzn-s3-demo-bucket"
        },
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStorageConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/create-storage-configuration.html)」を参照してください。

### `delete-encoder-configuration`
<a name="ivs-realtime_DeleteEncoderConfiguration_cli_2_topic"></a>

次のコード例は、`delete-encoder-configuration` を使用する方法を示しています。

**AWS CLI**  
**コンポジションエンコーダー設定を削除するには**  
次の `delete-encoder-configuration` は、指定の ARN (Amazon リソースネーム) で指定されたコンポジションエンコーダー設定を削除します。  

```
aws ivs-realtime delete-encoder-configuration \
    --arn "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEncoderConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/delete-encoder-configuration.html)」を参照してください。

### `delete-ingest-configuration`
<a name="ivs-realtime_DeleteIngestConfiguration_cli_2_topic"></a>

次のコード例は、`delete-ingest-configuration` を使用する方法を示しています。

**AWS CLI**  
**例 1: 非アクティブな取り込み設定を削除するには**  
次の `delete-ingest-configuration` の例では、指定した取り込み設定 ARN (Amazon リソースネーム) の非アクティブな取り込み設定を削除します。  

```
aws ivs-realtime delete-ingest-configuration \
    --arn arn:aws:ivs:us-west-2:123456789012:ingest-configuration/AbCdEfGh1234
```
このコマンドでは何も出力されません。  
詳細については、*Amazon Interactive Video Service ユーザーガイド*の「[IVS ストリーム取り込み \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-stream-ingest.html)」を参照してください。  
**例 2: アクティブな取り込み設定を強制的に削除するには**  
次の `delete-ingest-configuration` の例では、指定した取り込み設定 ARN (Amazon リソースネーム) のアクティブな取り込み設定を強制的に削除します。  

```
aws ivs-realtime delete-ingest-configuration \
    --arn arn:aws:ivs:us-west-2:123456789012:ingest-configuration/AbCdEfGh1234 \
    --force
```
このコマンドでは何も出力されません。  
詳細については、*Amazon Interactive Video Service ユーザーガイド*の「[IVS ストリーム取り込み \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-stream-ingest.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteIngestConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/delete-ingest-configuration.html)」を参照してください。

### `delete-public-key`
<a name="ivs-realtime_DeletePublicKey_cli_2_topic"></a>

次のコード例は、`delete-public-key` を使用する方法を示しています。

**AWS CLI**  
**パブリックキーを削除するには**  
次の `delete-public-key` は、指定されたパブリックキーを削除します。  

```
aws ivs-realtime delete-public-key \
    --arn arn:aws:ivs:us-west-2:123456789012:public-key/abcdABC1efg2
```
このコマンドは何も出力しません。  
詳細については、「*Amazon IVS Real-Time Streaming ユーザーガイド*」の「[参加者トークンを配布する](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/getting-started-distribute-tokens.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/delete-public-key.html)」を参照してください。

### `delete-stage`
<a name="ivs-realtime_DeleteStage_cli_2_topic"></a>

次のコード例は、`delete-stage` を使用する方法を示しています。

**AWS CLI**  
**ステージを削除するには**  
次の `delete-stage` の例では、指定されたステージを削除します。  

```
aws ivs-realtime delete-stage \
    --arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/userguide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/delete-stage.html)」を参照してください。

### `delete-storage-configuration`
<a name="ivs-realtime_DeleteStorageConfiguration_cli_2_topic"></a>

次のコード例は、`delete-storage-configuration` を使用する方法を示しています。

**AWS CLI**  
**コンポジションストレージ設定を削除するには**  
次の `delete-storage-configuration` は、指定の ARN (Amazon リソースネーム) で指定されたコンポジションストレージ設定を削除します。  

```
aws ivs-realtime delete-storage-configuration \
    --arn "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/ABabCDcdEFef"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStorageConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/delete-storage-configuration.html)」を参照してください。

### `disconnect-participant`
<a name="ivs-realtime_DisconnectParticipant_cli_2_topic"></a>

次のコード例は、`disconnect-participant` を使用する方法を示しています。

**AWS CLI**  
**ステージ参加者を切断するには**  
次の `disconnect-participant` の例では、指定された参加者を指定されたステージから切断します。  

```
aws ivs-realtime disconnect-participant \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --participant-id ABCDEfghij01234KLMN5678
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/userguide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisconnectParticipant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/disconnect-participant.html)」を参照してください。

### `get-composition`
<a name="ivs-realtime_GetComposition_cli_2_topic"></a>

次のコード例は、`get-composition` を使用する方法を示しています。

**AWS CLI**  
**例 1: デフォルトのレイアウト設定でコンポジションを取得するには**  
次の `get-composition` の例では、指定された ARN (Amazon リソースネーム) のコンポジションを取得します。  

```
aws ivs-realtime get-composition \
    --arn "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh"
```
出力:  

```
{
    "composition": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh",
        "destinations": [
            {
                "configuration": {
                    "channel": {
                        "channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg",
                        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                    },
                    "name": ""
                },
                "id": "AabBCcdDEefF",
                "startTime": "2023-10-16T23:26:00+00:00",
                "state": "ACTIVE"
            },
            {
                "configuration": {
                    "name": "",
                    "s3": {
                        "encoderConfigurationArns": [
                            "arn:aws:ivs:arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                        ],
                        "recordingConfiguration": {
                            "format": "HLS",
                            "hlsConfiguration": {
                                "targetSegmentDurationSeconds": 2
                            }
                        },
                        "storageConfigurationArn": "arn:arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE",
                    }
                },
                "detail": {
                    "s3": {
                        "recordingPrefix": "aBcDeFgHhGfE/AbCdEfGhHgFe/GHFabcgefABC/composite"
                    }
                },
                "id": "GHFabcgefABC",
                "startTime": "2023-10-16T23:26:00+00:00",
                "state": "STARTING"
            }
        ],
        "layout": {
            "grid": {
                "featuredParticipantAttribute": "",
                "gridGap": 2,
                "omitStoppedVideo": false,
                "participantOrderAttribute": "",
                "videoAspectRatio": "VIDEO",
                "videoFillMode": ""
            }
        },
        "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
        "startTime": "2023-10-16T23:24:00+00:00",
        "state": "ACTIVE",
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[IVS Composite Recording \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-composite-recording.html)」を参照してください。  
**例 2: PiP レイアウトのコンポジションを取得するには**  
次の `get-composition` の例では、PiP レイアウトを使用している、指定された ARN (Amazon リソースネーム) のコンポジションを取得します。  

```
aws ivs-realtime get-composition \
    --arn "arn:aws:ivs:ap-northeast-1:123456789012:composition/wxyzWXYZpqrs"
```
出力:  

```
{
    "composition": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/wxyzWXYZpqrs",
        "destinations": [
            {
                "configuration": {
                    "channel": {
                        "channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg",
                        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                    },
                    "name": ""
                },
                "id": "AabBCcdDEefF",
                "startTime": "2023-10-16T23:26:00+00:00",
                "state": "ACTIVE"
            },
            {
                "configuration": {
                    "name": "",
                    "s3": {
                        "encoderConfigurationArns": [
                            "arn:aws:ivs:arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                        ],
                        "recordingConfiguration": {
                            "format": "HLS",
                            "hlsConfiguration": {
                                "targetSegmentDurationSeconds": 2
                            }
                        },
                        "storageConfigurationArn": "arn:arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE"
                    }
                },
                "detail": {
                    "s3": {
                        "recordingPrefix": "aBcDeFgHhGfE/AbCdEfGhHgFe/GHFabcgefABC/composite"
                    }
                },
                "id": "GHFabcgefABC",
                "startTime": "2023-10-16T23:26:00+00:00",
                "state": "STARTING"
            }
        ],
        "layout": {
            "pip": {
                "featuredParticipantAttribute": "abcdefg",
                "gridGap": 0,
                "omitStoppedVideo": false,
                "participantOrderAttribute": "",
                "pipBehavior": "STATIC",
                "pipOffset": 0,
                "pipParticipantAttribute": "",
                "pipPosition": "BOTTOM_RIGHT",
                "videoFillMode": "COVER"
            }
        },
        "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
        "startTime": "2023-10-16T23:24:00+00:00",
        "state": "ACTIVE",
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[IVS Composite Recording \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-composite-recording.html)」を参照してください。  
**例 3: サムネイルの記録が有効になっているコンポジションを取得するには**  
次の `get-composition` の例では、デフォルト設定でサムネイルの記録が有効になっている、指定された ARN (Amazon リソースネーム) のコンポジションを取得します。  

```
aws ivs-realtime get-composition \
    --arn "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh"
```
出力:  

```
{
    "composition": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh",
        "destinations": [
            {
                "configuration": {
                    "channel": {
                        "channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg",
                        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                    },
                    "name": ""
                },
                "id": "AabBCcdDEefF",
                "startTime": "2023-10-16T23:26:00+00:00",
                "state": "ACTIVE"
            },
            {
                "configuration": {
                    "name": "",
                    "s3": {
                        "encoderConfigurationArns": [
                            "arn:aws:ivs:arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                        ],
                        "recordingConfiguration": {
                            "format": "HLS",
                            "hlsConfiguration": {
                                "targetSegmentDurationSeconds": 2
                            }
                        },
                        "storageConfigurationArn": "arn:arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE",
                        "thumbnailConfigurations": [
                           {
                              "targetIntervalSeconds": 60,
                              "storage": [
                                  "SEQUENTIAL"
                              ],
                           }
                        ]
                    }
                },
                "detail": {
                    "s3": {
                        "recordingPrefix": "aBcDeFgHhGfE/AbCdEfGhHgFe/GHFabcgefABC/composite"
                    }
                },
                "id": "GHFabcgefABC",
                "startTime": "2023-10-16T23:26:00+00:00",
                "state": "STARTING"
            }
        ],
        "layout": {
            "grid": {
                "featuredParticipantAttribute": ""
                "gridGap": 2,
                "omitStoppedVideo": false,
                "participantOrderAttribute": "",
                "videoAspectRatio": "VIDEO",
                "videoFillMode": ""                }
        },
        "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
        "startTime": "2023-10-16T23:24:00+00:00",
        "state": "ACTIVE",
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[IVS Composite Recording \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-composite-recording.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetComposition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-composition.html)」を参照してください。

### `get-encoder-configuration`
<a name="ivs-realtime_GetEncoderConfiguration_cli_2_topic"></a>

次のコード例は、`get-encoder-configuration` を使用する方法を示しています。

**AWS CLI**  
**コンポジションエンコーダー設定を取得するには**  
次の `get-encoder-configuration` の例では、指定の ARN (Amazon リソースネーム) で指定されたコンポジションエンコーダー設定を取得します。  

```
aws ivs-realtime get-encoder-configuration \
    --arn "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/abcdABCDefgh"
```
出力:  

```
{
    "encoderConfiguration": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/abcdABCDefgh",
        "name": "test-ec",
        "tags": {},
        "video": {
            "bitrate": 3500000,
            "framerate": 30,
            "height": 1080,
            "width": 1920
        }
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEncoderConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-encoder-configuration.html)」を参照してください。

### `get-ingest-configuration`
<a name="ivs-realtime_GetIngestConfiguration_cli_2_topic"></a>

次のコード例は、`get-ingest-configuration` を使用する方法を示しています。

**AWS CLI**  
**取り込み設定情報を取得するには**  
次の `get-ingest-configuration` の例では、指定した取り込み設定 ARN (Amazon リソースネーム) の取り込み設定を取得します。  

```
aws ivs-realtime get-ingest-configuration \
    --arn arn:aws:ivs:us-west-2:123456789012:ingest-configuration/AbCdEfGh1234
```
出力:  

```
{
    "ingestConfiguration": {
        "name": "ingest1",
        "arn": "arn:aws:ivs:us-west-2:123456789012:ingest-configuration/AbCdEfGh1234",
        "ingestProtocol": "RTMPS",
        "streamKey": "rt_123456789012_us-west-2_AbCdEfGh1234_abcd1234efgh5678ijkl9012MNOP34",
        "stageArn": "",
        "participantId": "xyZ654abC321",
        "state": "INACTIVE",
        "userId": "",
        "tags": {}
    }
}
```
詳細については、*Amazon Interactive Video Service ユーザーガイド*の「[IVS ストリーム取り込み \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-stream-ingest.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetIngestConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-ingest-configuration.html)」を参照してください。

### `get-participant`
<a name="ivs-realtime_GetParticipant_cli_2_topic"></a>

次のコード例は、`get-participant` を使用する方法を示しています。

**AWS CLI**  
**例 1: ステージ参加者を取得するには**  
次の `get-participant` の例では、指定されたステージ ARN (Amazon リソースネーム) で、指定された参加者 ID とセッション ID のステージ参加者を取得します。  

```
aws ivs-realtime get-participant \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "participant": {
        "browserName": "Google Chrome",
        "browserVersion": "116",
        "firstJoinTime": "2023-04-26T20:30:34+00:00",
        "ispName": "Comcast",
        "osName": "Microsoft Windows 10 Pro",
        "osVersion": "10.0.19044",
        "participantId": "abCDEf12GHIj",
        "published": true,
        "recordingS3BucketName": "bucket-name",
        "recordingS3Prefix": "abcdABCDefgh/st-a1b2c3d4e5f6g/abCDEf12GHIj/1234567890",
        "recordingState": "ACTIVE",
        "sdkVersion": "",
        "state": "CONNECTED",
        "userId": ""
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 2: 別のステージにレプリケートされたステージ参加者を取得するには**  
次の `get-participant` の例では、参加者が別のステージにも複製されている場合に、指定されたステージ ARN (Amazon リソースネーム) で、指定された参加者 ID とセッション ID のステージ参加者を取得します。  

```
aws ivs-realtime get-participant \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "participant": {
        "browserName": "Google Chrome",
        "browserVersion": "116",
        "firstJoinTime": "2023-04-26T20:30:34+00:00",
        "ispName": "Comcast",
        "osName": "Microsoft Windows 10 Pro",
        "osVersion": "10.0.19044",
        "participantId": "abCDEf12GHIj",
        "published": true,
        "recordingS3BucketName": "bucket-name",
        "recordingS3Prefix": "abcdABCDefgh/st-a1b2c3d4e5f6g/abCDEf12GHIj/1234567890",
        "recordingState": "ACTIVE",
        "replicationState": "ACTIVE",
        "replicationType": "SOURCE",
        "sdkVersion": "",
        "state": "CONNECTED",
        "userId": ""
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 3: 別のステージからレプリケートされたステージ参加者を取得するには**  
次の `get-participant` の例では、参加者が別のステージから複製されている場合に、指定されたステージ ARN (Amazon リソースネーム) で、指定された参加者 ID とセッション ID のステージ参加者を取得します。  

```
aws ivs-realtime get-participant \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "participant": {
        "browserName": "Google Chrome",
        "browserVersion": "116",
        "firstJoinTime": "2023-04-26T20:30:34+00:00",
        "ispName": "Comcast",
        "osName": "Microsoft Windows 10 Pro",
        "osVersion": "10.0.19044",
        "participantId": "abCDEf12GHIj",
        "published": true,
        "recordingS3BucketName": "bucket-name",
        "recordingS3Prefix": "abcdABCDefgh/st-a1b2c3d4e5f6g/abCDEf12GHIj/1234567890",
        "recordingState": "ACTIVE",
        "replicationState": "ACTIVE",
        "replicationType": "REPLICA",
        "sdkVersion": "",
        "state": "CONNECTED",
        "userId": ""
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParticipant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-participant.html)」を参照してください。

### `get-public-key`
<a name="ivs-realtime_GetPublicKey_cli_2_topic"></a>

次のコード例は、`get-public-key` を使用する方法を示しています。

**AWS CLI**  
**ステージ参加者トークンの署名に使用される既存のパブリックキーを取得するには**  
次の `get-public-key` の例では、ステージ参加者トークンの署名用に、指定の ARN で指定されたパブリックキーを取得します。  

```
aws ivs-realtime get-public-key \
    --arn arn:aws:ivs:us-west-2:123456789012:public-key/abcdABC1efg2
```
出力:  

```
{
    "publicKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:public-key/abcdABC1efg2",
        "name": "",
        "publicKeyMaterial": "-----BEGIN PUBLIC KEY-----\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEqVWUtqs6EktQMR1sCYmEzGvRwtaycI16\n9pmzcpiWu/uhNStGlteJ5odRfRwVkoQUMnSZXTCcbn9bBTTmiWo4mJcFOOAzsthH\n0UAb8NdD4tUE0At4a9hYP9IETEXAMPLE\n-----END PUBLIC KEY-----",
        "fingerprint": "12:a3:44:56:bc:7d:e8:9f:10:2g:34:hi:56:78:90:12",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Real-Time Streaming ユーザーガイド*」の「[参加者トークンを配布する](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/getting-started-distribute-tokens.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-public-key.html)」を参照してください。

### `get-stage-session`
<a name="ivs-realtime_GetStageSession_cli_2_topic"></a>

次のコード例は、`get-stage-session` を使用する方法を示しています。

**AWS CLI**  
**ステージセッションを取得するには**  
次の `get-stage-session` の例では、指定されたステージ ARN (Amazon リソースネーム) の指定されたセッション ID に対するステージセッションを取得します。  

```
aws ivs-realtime get-stage-session \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g
```
出力:  

```
{
    "stageSession": {
        "endTime": "2023-04-26T20:36:29+00:00",
        "sessionId": "st-a1b2c3d4e5f6g",
        "startTime": "2023-04-26T20:30:29.602000+00:00"
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/userguide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStageSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-stage-session.html)」を参照してください。

### `get-stage`
<a name="ivs-realtime_GetStage_cli_2_topic"></a>

次のコード例は、`get-stage` を使用する方法を示しています。

**AWS CLI**  
**ステージの設定情報を取得するには**  
次の `get-stage` の例では、指定されたステージ ARN (Amazon リソースネーム) のステージ設定を取得します。  

```
aws ivs-realtime get-stage \
    --arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh
```
出力:  

```
{
    "stage": {
        "activeSessionId": "st-a1b2c3d4e5f6g",
        "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
        "autoParticipantRecordingConfiguration": {
            "storageConfigurationArn": "",
            "mediaTypes": [
                "AUDIO_VIDEO"
            ],
            "thumbnailConfiguration": {
                "targetIntervalSeconds": 60,
                "storage": [
                    "SEQUENTIAL"
                ],
                "recordingMode": "DISABLED"
            },
            "recordingReconnectWindowSeconds": 0,
            "hlsConfiguration": {
                "targetSegmentDurationSeconds": 6
            },
            "recordParticipantReplicas": true
        },
        "endpoints": {
            "events": "wss://global.events.live-video.net",
            "rtmp": "rtmp://9x0y8z7s6t5u.global-contribute-staging.live-video.net/app/",
            "rtmps": "rtmps://9x0y8z7s6t5u.global-contribute-staging.live-video.net:443/app/",
            "whip": "https://9x0y8z7s6t5u.global-bm.whip.live-video.net"
        },
        "name": "test",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-stage.html)」を参照してください。

### `get-storage-configuration`
<a name="ivs-realtime_GetStorageConfiguration_cli_2_topic"></a>

次のコード例は、`get-storage-configuration` を使用する方法を示しています。

**AWS CLI**  
**コンポジションストレージ設定を取得するには**  
次の `get-storage-configuration` の例では、指定の ARN (Amazon リソースネーム) で指定されたコンポジションストレージ設定を取得します。  

```
aws ivs-realtime get-storage-configuration \
    --name arn "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/abcdABCDefgh"
```
出力:  

```
{
    "storageConfiguration": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/abcdABCDefgh",
        "name": "test-sc",
        "s3": {
            "bucketName": "amzn-s3-demo-bucket"
        },
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStorageConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/get-storage-configuration.html)」を参照してください。

### `import-public-key`
<a name="ivs-realtime_ImportPublicKey_cli_2_topic"></a>

次のコード例は、`import-public-key` を使用する方法を示しています。

**AWS CLI**  
**ステージ参加者トークンの署名に使用される既存のパブリックキーをインポートするには**  
次の `import-public-key` の例では、ステージ参加者トークンの署名に使用されるパブリックキーをマテリアルファイルからインポートします。  

```
aws ivs-realtime import-public-key \
    --public-key-material="`cat public.pem`"
```
出力:  

```
{
    "publicKey": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:public-key/abcdABC1efg2",
        "name": "",
        "publicKeyMaterial": "-----BEGIN PUBLIC KEY-----\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEqVWUtqs6EktQMR1sCYmEzGvRwtaycI16\n9pmzcpiWu/uhNStGlteJ5odRfRwVkoQUMnSZXTCcbn9bBTTmiWo4mJcFOOAzsthH\n0UAb8NdD4tUE0At4a9hYP9IETEXAMPLE\n-----END PUBLIC KEY-----",
        "fingerprint": "12:a3:44:56:bc:7d:e8:9f:10:2g:34:hi:56:78:90:12",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Real-Time Streaming ユーザーガイド*」の「[参加者トークンを配布する](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/getting-started-distribute-tokens.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/import-public-key.html)」を参照してください。

### `list-compositions`
<a name="ivs-realtime_ListCompositions_cli_2_topic"></a>

次のコード例は、`list-compositions` を使用する方法を示しています。

**AWS CLI**  
**コンポジションのリストを取得するには**  
API リクエストが処理される AWS リージョンにおける AWS アカウントのすべての構成を以下`list-compositions`に示します。  

```
aws ivs-realtime list-compositions
```
出力:  

```
{
    "compositions": [
        {
            "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh",
            "destinations": [
                {
                    "id": "AabBCcdDEefF",
                    "startTime": "2023-10-16T23:25:23+00:00",
                    "state": "ACTIVE"
                }
            ],
            "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
            "startTime": "2023-10-16T23:25:21+00:00",
            "state": "ACTIVE",
            "tags": {}
        },
        {
            "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/ABcdabCDefgh",
            "destinations": [
                {
                    "endTime": "2023-10-16T23:25:00.786512+00:00",
                    "id": "aABbcCDdeEFf",
                    "startTime": "2023-10-16T23:24:01+00:00",
                    "state": "STOPPED"
                },
                {
                    "endTime": "2023-10-16T23:25:00.786512+00:00",
                    "id": "deEFfaABbcCD",
                    "startTime": "2023-10-16T23:24:01+00:00",
                    "state": "STOPPED"
                }
            ],
            "endTime": "2023-10-16T23:25:00+00:00",
            "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/efghabcdABCD",
            "startTime": "2023-10-16T23:24:00+00:00",
            "state": "STOPPED",
            "tags": {}
        }
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCompositions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-compositions.html)」を参照してください。

### `list-encoder-configurations`
<a name="ivs-realtime_ListEncoderConfigurations_cli_2_topic"></a>

次のコード例は、`list-encoder-configurations` を使用する方法を示しています。

**AWS CLI**  
**コンポジションエンコーダー設定を一覧表示するには**  
API リクエストが処理される AWS リージョンにおける AWS 、アカウントのすべてのコンポジションエンコーダー設定を以下`list-encoder-configurations`に示します。  

```
aws ivs-realtime list-encoder-configurations
```
出力:  

```
{
    "encoderConfigurations": [
        {
            "arn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/abcdABCDefgh",
            "name": "test-ec-1",
            "tags": {}
        },
        {
            "arn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABCefgEFGabc",
            "name": "test-ec-2",
            "tags": {}
        }
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEncoderConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-encoder-configurations.html)」を参照してください。

### `list-ingest-configurations`
<a name="ivs-realtime_ListIngestConfigurations_cli_2_topic"></a>

次のコード例は、`list-ingest-configurations` を使用する方法を示しています。

**AWS CLI**  
**すべての取り込み設定に関する概要情報を取得するには**  
次の の`list-ingest-configurations`例では、API リクエストが処理される AWS リージョンにおける AWS アカウントのすべての取り込み設定を一覧表示します。  

```
aws ivs-realtime list-ingest-configurations
```
出力:  

```
{
    "ingestConfigurations": [
        {
            "name": "",
            "arn": "arn:aws:ivs:us-west-2:123456789012:ingest-configuration/XYZuvwSt4567",
            "ingestProtocol": "RTMPS",
            "stageArn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
            "participnatId": "abC789Xyz456",
            "state": "INACTIVE"
            "userId": "",
        }
    ]
}
```
詳細については、*Amazon Interactive Video Service ユーザーガイド*の「[IVS ストリーム取り込み \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-stream-ingest.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListIngestConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-ingest-configurations.html)」を参照してください。

### `list-participant-events`
<a name="ivs-realtime_ListParticipantEvents_cli_2_topic"></a>

次のコード例は、`list-participant-events` を使用する方法を示しています。

**AWS CLI**  
**例 1: ステージ参加者イベントのリストを取得するには**  
次の `list-participant-events` の例では、指定されたステージ ARN (Amazon リソースネーム) の指定された参加者 ID とセッション ID に対するすべての参加者イベントを一覧表示します。  

```
aws ivs-realtime list-participant-events \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "events": [
        {
            "eventTime": "2023-04-26T20:36:28+00:00",
            "name": "LEFT",
            "participantId": "abCDEf12GHIj"
        },
        {
            "eventTime": "2023-04-26T20:36:28+00:00",
            "name": "PUBLISH_STOPPED",
            "participantId": "abCDEf12GHIj"
        },
        {
            "eventTime": "2023-04-26T20:30:34+00:00",
            "name": "JOINED",
            "participantId": "abCDEf12GHIj"
        },
        {
            "eventTime": "2023-04-26T20:30:34+00:00",
            "name": "PUBLISH_STARTED",
            "participantId": "abCDEf12GHIj"
        }
    ]
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 2: 参加者のレプリケーションの停止と開始を含むステージ参加者のイベントのリストを取得するには**  
次の `list-participant-events` の例では、参加者が別のステージにレプリケートされている、指定されたステージ ARN (Amazon リソースネーム) の指定された参加者 ID とセッション ID に対するすべての参加者イベントを一覧表示します。  

```
aws ivs-realtime list-participant-events \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "events": [
        {
            "eventTime": "2025-04-26T20:36:28+00:00",
            "name": "LEFT",
            "participantId": "abCDEf12GHIj"
        },
        {
            "eventTime": "2025-04-26T20:36:28+00:00",
            "name": "PUBLISH_STOPPED",
            "participantId": "abCDEf12GHIj"
        },
        {
            "eventTime": "2025-04-26T20:30:34+00:00",
            "name": "JOINED",
            "participantId": "abCDEf12GHIj"
        },
        {
            "eventTime": "2025-04-26T20:30:34+00:00",
            "name": "PUBLISH_STARTED",
            "participantId": "abCDEf12GHIj"
        },
        {
            "name": "REPLICATION_STARTED",
            "participantId": "abCDEf12GHIj",
            "eventTime": "2025-04-26T20:30:34+00:00",
            "destinationStageArn": "arn:aws:ivs:us-west-2:12345678901:stage/ABCDabcdefgh",
            "destinationSessionId": "st-b1c2d3e4f5g6a"
        },
        {
            "name": "REPLICATION_STOPPED",
            "participantId": "abCDEf12GHIj",
            "eventTime": "2025-04-26T20:32:34+00:00",
            "destinationStageArn": "arn:aws:ivs:us-west-2:12345678901:stage/ABCDabcdefgh",
            "destinationSessionId": "st-b1c2d3e4f5g6a"
        }
    ]
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListParticipantEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-participant-events.html)」を参照してください。

### `list-participant-replicas`
<a name="ivs-realtime_ListParticipantReplicas_cli_2_topic"></a>

次のコード例は、`list-participant-replicas` を使用する方法を示しています。

**AWS CLI**  
**ステージ参加者のレプリカのリストを取得するには**  
次の `list-participant-replicas` の例では、指定されたソースステージ ARN (Amazon リソースネーム) から別のステージにレプリケートされたすべてのステージ参加者を一覧表示します。  

```
aws ivs-realtime list-participant-replicas \
    --source-stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "replicas": [
        {
            "sourceStageArn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
            "participantId": "abCDEf12GHIj",
            "sourceSessionId": "st-a1b2c3d4e5f6g",
            "destinationStageArn": "arn:aws:ivs:us-west-2:012345678901:stage/ABCDabcdefgh",
            "destinationSessionId": "st-b1c2d3e4f5g6a",
            "replicationState": "ACTIVE"
        }
    ]
}
```
詳細については、「*Amazon IVS Real-Time Streaming ユーザーガイド*」の「[IVS 参加者のレプリケーション](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-participant-replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListParticipantReplicas](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-participant-replicas.html)」を参照してください。

### `list-participants`
<a name="ivs-realtime_ListParticipants_cli_2_topic"></a>

次のコード例は、`list-participants` を使用する方法を示しています。

**AWS CLI**  
**例 1: ステージ参加者のリストを取得するには**  
次の `list-participants` の例では、指定されたステージ ARN (Amazon リソースネーム) の指定されたセッション ID に対するすべての参加者を一覧表示します。  

```
aws ivs-realtime list-participants \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g
```
出力:  

```
{
    "participants": [
        {
            "firstJoinTime": "2023-04-26T20:30:34+00:00",
            "participantId": "abCDEf12GHIj",
            "published": true,
            "recordingState": "STOPPED",
            "state": "DISCONNECTED",
            "userId": ""
        }
    ]
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 2: 参加者が別のステージにレプリケートされたときにステージ参加者のリストを取得するには**  
次の `list-participants` の例では、参加者が別のステージにレプリケートされている場合に、指定されたステージ ARN (Amazon リソースネーム) の指定されたセッション ID のすべての参加者を一覧表示します。  

```
aws ivs-realtime list-participants \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g
```
出力:  

```
{
    "participants": [
        {
            "firstJoinTime": "2023-04-26T20:30:34+00:00",
            "participantId": "abCDEf12GHIj",
            "published": true,
            "recordingState": "STOPPED",
            "state": "DISCONNECTED",
            "userId": "",
            "replicationState": "ACTIVE",
            "replicationType": "SOURCE",
            "sourceStageArn": "",
            "sourceSessionId": ""
        }
    ]
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 3: 参加者が別のステージからレプリケートされた場合にステージ参加者のリストを取得するには**  
次の `list-participants` の例では、参加者が別のステージからレプリケートされている場合に、指定されたステージ ARN (Amazon リソースネーム) の指定されたセッション ID のすべての参加者を一覧表示します。  

```
aws ivs-realtime list-participants \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --session-id st-a1b2c3d4e5f6g
```
出力:  

```
{
    "participants": [
        {
            "firstJoinTime": "2023-04-26T20:30:34+00:00",
            "participantId": "abCDEf12GHIj",
            "published": true,
            "recordingState": "STOPPED",
            "state": "DISCONNECTED",
            "userId": "",
            "replicationState": "ACTIVE",
            "replicationType": "REPLICA",
            "sourceStageArn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
            "sourceSessionId": "st-a1b2c3d4e5f6g"
        }
    ]
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListParticipants](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-participants.html)」を参照してください。

### `list-public-keys`
<a name="ivs-realtime_ListPublicKeys_cli_2_topic"></a>

次のコード例は、`list-public-keys` を使用する方法を示しています。

**AWS CLI**  
**ステージ参加者トークンの署名に使用できる既存のパブリックキーを一覧表示するには**  
次の の`list-public-keys`例では、API リクエストが処理される AWS リージョンで、ステージ参加者トークンのシギニングに使用できるすべてのパブリックキーを一覧表示します。  

```
aws ivs-realtime list-public-keys
```
出力:  

```
{
    "publicKeys": [
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:public-key/abcdABC1efg2",
            "name": "",
            "tags": {}
        },
        {
            "arn": "arn:aws:ivs:us-west-2:123456789012:public-key/3bcdABCDefg4",
            "name": "",
            "tags": {}
        }
    ]
}
```
詳細については、「*Amazon IVS Real-Time Streaming ユーザーガイド*」の「[参加者トークンを配布する](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/getting-started-distribute-tokens.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPublicKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-public-keys.html)」を参照してください。

### `list-stage-sessions`
<a name="ivs-realtime_ListStageSessions_cli_2_topic"></a>

次のコード例は、`list-stage-sessions` を使用する方法を示しています。

**AWS CLI**  
**ステージセッションのリストを取得するには**  
次の `list-stage-sessions` の例では、指定されたステージ ARN (Amazon リソースネーム) のすべてのセッションを一覧表示します。  

```
aws ivs-realtime list-stage-sessions \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh
```
出力:  

```
{
    "stageSessions": [
        {
            "endTime": "2023-04-26T20:36:29+00:00",
            "sessionId": "st-a1b2c3d4e5f6g",
            "startTime": "2023-04-26T20:30:29.602000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/userguide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStageSessions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-stage-sessions.html)」を参照してください。

### `list-stages`
<a name="ivs-realtime_ListStages_cli_2_topic"></a>

次のコード例は、`list-stages` を使用する方法を示しています。

**AWS CLI**  
**すべてのステージに関する概要情報を取得するには**  
次の の`list-stages`例では、API リクエストが処理される AWS リージョンの AWS アカウントのすべてのステージを一覧表示します。  

```
aws ivs-realtime list-stages
```
出力:  

```
{
    "stages": [
        {
            "activeSessionId": "st-a1b2c3d4e5f6g",
            "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
            "name": "stage1",
            "tags": {}
        },
        {
            "activeSessionId": "st-a123bcd456efg",
            "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcd1234ABCD",
            "name": "stage2",
            "tags": {}
        },
        {
            "activeSessionId": "st-abcDEF1234ghi",
            "arn": "arn:aws:ivs:us-west-2:123456789012:stage/ABCD1234efgh",
            "name": "stage3",
            "tags": {}
        }
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-stages.html)」を参照してください。

### `list-storage-configurations`
<a name="ivs-realtime_ListStorageConfigurations_cli_2_topic"></a>

次のコード例は、`list-storage-configurations` を使用する方法を示しています。

**AWS CLI**  
**コンポジションストレージ設定を一覧表示するには**  
API リクエストが処理される AWS リージョンにおける、 AWS アカウントのすべてのコンポジションストレージ設定を以下`list-storage-configurations`に示します。  

```
aws ivs-realtime list-storage-configurations
```
出力:  

```
{
    "storageConfigurations": [
        {
            "arn": "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/abcdABCDefgh",
            "name": "test-sc-1",
            "s3": {
                "bucketName": "amzn-s3-demo-bucket-1"
            },
            "tags": {}
        },
        {
            "arn": "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/ABCefgEFGabc",
            "name": "test-sc-2",
            "s3": {
                "bucketName": "amzn-s3-demo-bucket-2"
            },
            "tags": {}
        }
    ]
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStorageConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/list-storage-configurations.html)」を参照してください。

### `start-composition`
<a name="ivs-realtime_StartComposition_cli_2_topic"></a>

次のコード例は、`start-composition` を使用する方法を示しています。

**AWS CLI**  
**例 1: デフォルトのレイアウト設定でコンポジションを開始するには**  
次の `start-composition` の例では、指定された場所にストリーミングされるコンポジションを指定されたステージに対して開始します。  

```
aws ivs-realtime start-composition \
    --stage-arn arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd \
    --destinations '[{"channel": {"channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg", \
        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"}}, \
        {"s3":{"encoderConfigurationArns":["arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"], \
        "recordingConfiguration": {"hlsConfiguration": {"targetSegmentDurationSeconds": 5}}, \
        "storageConfigurationArn":"arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE"}}]'
```
出力:  

```
{
    "composition": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh",
        "destinations": [
            {
                "configuration": {
                    "channel": {
                        "channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg",
                        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                    },
                    "name": ""
                },
                "id": "AabBCcdDEefF",
                "state": "STARTING"
            },
            {
                "configuration": {
                    "name": "",
                    "s3": {
                        "encoderConfigurationArns": [
                            "arn:aws:ivs:arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                        ],
                        "recordingConfiguration": {
                            "format": "HLS",
                            "hlsConfiguration": {
                                "targetSegmentDurationSeconds": 5
                            }
                        },
                        "storageConfigurationArn": "arn:arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE"
                    }
                },
                "detail": {
                    "s3": {
                        "recordingPrefix": "aBcDeFgHhGfE/AbCdEfGhHgFe/GHFabcgefABC/composite"
                    }
                },
                "id": "GHFabcgefABC",
                "state": "STARTING"
            }
        ],
        "layout": {
            "grid": {
                "featuredParticipantAttribute": ""
                "gridGap": 2,
                "omitStoppedVideo": false,
                "participantOrderAttribute": "",
                "videoAspectRatio": "VIDEO",
                "videoFillMode": ""
            }
        },
        "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
        "startTime": "2023-10-16T23:24:00+00:00",
        "state": "STARTING",
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[IVS Composite Recording \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-composite-recording.html)」を参照してください。  
**例 2: PiP レイアウトのコンポジションを開始するには**  
次の `start-composition` の例では、PiP レイアウトを使用して、指定された場所にストリーミングされるコンポジションを指定されたステージに対して開始します。  

```
aws ivs-realtime start-composition \
    --stage-arn arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd \
    --destinations '[{"channel": {"channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg", \
        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"}}, \
        {"s3":{"encoderConfigurationArns":["arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"], \
        "storageConfigurationArn":"arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE"}}]' \
    --layout pip='{featuredParticipantAttribute="abcdefg"}'
```
出力:  

```
{
    "composition": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/wxyzWXYZpqrs",
        "destinations": [
            {
                "configuration": {
                    "channel": {
                        "channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg",
                        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                    },
                    "name": ""
                },
                "id": "AabBCcdDEefF",
                "state": "STARTING"
            },
            {
                "configuration": {
                    "name": "",
                    "s3": {
                        "encoderConfigurationArns": [
                            "arn:aws:ivs:arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                        ],
                        "recordingConfiguration": {
                            "format": "HLS",
                            "hlsConfiguration": {
                                "targetSegmentDurationSeconds": 2
                            }
                        },
                        "storageConfigurationArn": "arn:arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE"
                    }
                },
                "detail": {
                    "s3": {
                        "recordingPrefix": "aBcDeFgHhGfE/AbCdEfGhHgFe/GHFabcgefABC/composite"
                    }
                },
                "id": "GHFabcgefABC",
                "state": "STARTING"
            }
        ],
        "layout": {
            "pip": {
                "featuredParticipantAttribute": "abcdefg",
                "gridGap": 0,
                "omitStoppedVideo": false,
                "participantOrderAttribute": "",
                "pipBehavior": "STATIC",
                "pipOffset": 0,
                "pipParticipantAttribute": "",
                "pipPosition": "BOTTOM_RIGHT",
                "videoFillMode": "COVER"
            }
        },
        "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
        "startTime": "2023-10-16T23:24:00+00:00",
        "state": "STARTING",
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[IVS Composite Recording \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-composite-recording.html)」を参照してください。  
**例 3: サムネイルの記録が有効になっているコンポジションを開始するには**  
次の `start-composition` の例では、サムネイルの記録が有効になっており、指定された場所にストリーミングされるコンポジションを、指定されたステージに対して開始します。  

```
aws ivs-realtime start-composition \
    --stage-arn arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd \
    --destinations '[{"channel": {"channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg", \
        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"}}, \
        {"s3": {"encoderConfigurationArns": ["arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"], \
        "storageConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE", \
        "thumbnailConfigurations": [{"storage": ["SEQUENTIAL"],"targetIntervalSeconds": 60}]}}]'
```
出力:  

```
{
    "composition": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh",
        "destinations": [
            {
                "configuration": {
                    "channel": {
                        "channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg",
                        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                    },
                    "name": ""
                },
                "id": "AabBCcdDEefF",
                "state": "STARTING"
            },
            {
                "configuration": {
                    "name": "",
                    "s3": {
                        "encoderConfigurationArns": [
                            "arn:aws:ivs:arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                        ],
                        "recordingConfiguration": {
                            "format": "HLS",
                            "hlsConfiguration": {
                                "targetSegmentDurationSeconds": 2
                            }
                        },
                        "storageConfigurationArn": "arn:arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE",
                        "thumbnailConfigurations": [
                           {
                              "targetIntervalSeconds": 60,
                              "storage": [
                                  "SEQUENTIAL"
                              ]
                           }
                        ]
                    }
                },
                "detail": {
                    "s3": {
                        "recordingPrefix": "aBcDeFgHhGfE/AbCdEfGhHgFe/GHFabcgefABC/composite"
                    }
                },
                "id": "GHFabcgefABC",
                "state": "STARTING"
            }
        ],
        "layout": {
            "grid": {
                "featuredParticipantAttribute": ""
                "gridGap": 2,
                "omitStoppedVideo": false,
                "participantOrderAttribute": "",
                "videoAspectRatio": "VIDEO",
                "videoFillMode": ""
            }
        },
        "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
        "startTime": "2023-10-16T23:24:00+00:00",
        "state": "STARTING",
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Composite Recording (リアルタイムストリーミング)](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-composite-recording.html)」を参照してください。  
**例 4: カスタム参加者の順序でグリッドレイアウトを使用してコンポジションを開始するには**  
次の `start-composition` の例では、カスタム参加者の順序でグリッドレイアウトを使用して、指定された場所にストリーミングされるコンポジションを指定されたステージに対して開始します。  

```
aws ivs-realtime start-composition \
    --stage-arn arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd \
    --destinations '[{"channel": {"channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg", \
        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"}}, \
        {"s3": {"encoderConfigurationArns": ["arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"], \
        "storageConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE", \
        "thumbnailConfigurations": [{"storage": ["SEQUENTIAL"],"targetIntervalSeconds": 60}]}}]' \
    --layout grid='{participantOrderAttribute="abcdefg"}'
```
出力:  

```
{
    "composition": {
        "arn": "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh",
        "destinations": [
            {
                "configuration": {
                    "channel": {
                        "channelArn": "arn:aws:ivs:ap-northeast-1:123456789012:channel/abcABCdefDEg",
                        "encoderConfigurationArn": "arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                    },
                    "name": ""
                },
                "id": "AabBCcdDEefF",
                "state": "STARTING"
            },
            {
                "configuration": {
                    "name": "",
                    "s3": {
                        "encoderConfigurationArns": [
                            "arn:aws:ivs:arn:aws:ivs:ap-northeast-1:123456789012:encoder-configuration/ABabCDcdEFef"
                        ],
                        "recordingConfiguration": {
                            "format": "HLS",
                            "hlsConfiguration": {
                                "targetSegmentDurationSeconds": 2
                            }
                        },
                        "storageConfigurationArn": "arn:arn:aws:ivs:ap-northeast-1:123456789012:storage-configuration/FefABabCDcdE",
                        "thumbnailConfigurations": [
                           {
                              "targetIntervalSeconds": 60,
                              "storage": [
                                  "SEQUENTIAL"
                              ]
                           }
                        ]
                    }
                },
                "detail": {
                    "s3": {
                        "recordingPrefix": "aBcDeFgHhGfE/AbCdEfGhHgFe/GHFabcgefABC/composite"
                    }
                },
                "id": "GHFabcgefABC",
                "state": "STARTING"
            }
        ],
        "layout": {
            "grid": {
                "featuredParticipantAttribute": ""
                "gridGap": 2,
                "omitStoppedVideo": false,
                "participantOrderAttribute": "abcdefg",
                "videoAspectRatio": "VIDEO",
                "videoFillMode": ""
            }
        },
        "stageArn": "arn:aws:ivs:ap-northeast-1:123456789012:stage/defgABCDabcd",
        "startTime": "2023-10-16T23:24:00+00:00",
        "state": "STARTING",
        "tags": {}
    }
}
```
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[IVS Composite Recording \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-composite-recording.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartComposition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/start-composition.html)」を参照してください。

### `start-participant-replication`
<a name="ivs-realtime_StartParticipantReplication_cli_2_topic"></a>

次のコード例は、`start-participant-replication` を使用する方法を示しています。

**AWS CLI**  
**あるステージから別のステージへの参加者のレプリケートを開始するには**  
次の `start-participant-replication` の例では、参加者をソースステージから宛先ステージにレプリケートし、各ステージを ARN (Amazon リソースネーム) で指定します。  

```
aws ivs-realtime start-participant-replication \
    --source-stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --destination-stage-arn arn:aws:ivs:us-west-2:234567890123:stage/bcdABCDefghi \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "accessControlAllowOrigin": "*",
    "accessControlExposeHeaders": "Access-Control-Allow-Origin,Access-Control-Expose-Headers,Cache-Control,Content-Length, \
    Content-Security-Policy,Content-Type,date,Strict-Transport-Security,x-amz-apigw-id,x-amzn-errormessage,x-amzn-errortype, \
    x-amzn-requestid,x-amzn-trace-id,X-Content-Type-Options,X-Frame-Options",
    "cacheControl": "no-store, no-cache",
    "contentSecurityPolicy": "default-src 'self'; upgrade-insecure-requests;",
    "strictTransportSecurity": "max-age:47304000; includeSubDomains",
    "xContentTypeOptions": "nosniff",
    "xFrameOptions": "DENY"
}
```
詳細については、「*Amazon IVS Real-Time Streaming ユーザーガイド*」の「[IVS 参加者のレプリケーション](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-participant-replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartParticipantReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/start-participant-replication.html)」を参照してください。

### `stop-composition`
<a name="ivs-realtime_StopComposition_cli_2_topic"></a>

次のコード例は、`stop-composition` を使用する方法を示しています。

**AWS CLI**  
**コンポジションを停止するには**  
次の `stop-composition` は、指定の ARN (Amazon リソースネーム) で指定されたコンポジションを停止します。  

```
aws ivs-realtime stop-composition \
    --arn "arn:aws:ivs:ap-northeast-1:123456789012:composition/abcdABCDefgh"
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Interactive Video Service ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopComposition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/stop-composition.html)」を参照してください。

### `stop-participant-replication`
<a name="ivs-realtime_StopParticipantReplication_cli_2_topic"></a>

次のコード例は、`stop-participant-replication` を使用する方法を示しています。

**AWS CLI**  
**あるステージから別のステージへの参加者のレプリケートを停止するには**  
次の `stop-participant-replication` の例では、ARN (Amazon リソースネーム) で指定された各ステージを使用して、送信元ステージから送信先ステージへの参加者のレプリケートを停止します。  

```
aws ivs-realtime stop-participant-replication \
    --source-stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --destination-stage-arn arn:aws:ivs:us-west-2:234567890123:stage/bcdABCDefghi \
    --participant-id abCDEf12GHIj
```
出力:  

```
{
    "accessControlAllowOrigin": "*",
    "accessControlExposeHeaders": "Access-Control-Allow-Origin,Access-Control-Expose-Headers,Cache-Control,Content-Length, \
    Content-Security-Policy,Content-Type,date,Strict-Transport-Security,x-amz-apigw-id,x-amzn-errormessage,x-amzn-errortype, \
    x-amzn-requestid,x-amzn-trace-id,X-Content-Type-Options,X-Frame-Options",
    "cacheControl": "no-store, no-cache",
    "contentSecurityPolicy": "default-src 'self'; upgrade-insecure-requests;",
    "strictTransportSecurity": "max-age:47304000; includeSubDomains",
    "xContentTypeOptions": "nosniff",
    "xFrameOptions": "DENY"
}
```
詳細については、「*Amazon IVS Real-Time Streaming ユーザーガイド*」の「[IVS 参加者のレプリケーション](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-participant-replication.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopParticipantReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/stop-participant-replication.html)」を参照してください。

### `update-ingest-configuration`
<a name="ivs-realtime_UpdateIngestConfiguration_cli_2_topic"></a>

次のコード例は、`update-ingest-configuration` を使用する方法を示しています。

**AWS CLI**  
**取り込み設定を更新するには**  
次の `update-inegst-configuration` の例では、取り込み設定を更新してステージにアタッチします。  

```
aws ivs-realtime update-ingest-configuration \
    --arn arn:aws:ivs:us-west-2:123456789012:ingest-configuration/AbCdEfGh1234 \
    --stage-arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh
```
出力:  

```
{
    "ingestConfiguration": {
        "name": "ingest1",
        "arn": "arn:aws:ivs:us-west-2:123456789012:ingest-configuration/AbCdEfGh1234",
        "ingestProtocol": "RTMPS",
        "streamKey": "rt_123456789012_us-west-2_AbCdEfGh1234_abcd1234efgh5678ijkl9012MNOP34",
        "stageArn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
        "participantId": "xyZ654abC321",
        "state": "INACTIVE",
        "userId": "",
        "tags": {}
    }
}
```
詳細については、*Amazon Interactive Video Service ユーザーガイド*の「[IVS ストリーム取り込み \$1 リアルタイムストリーミング](https://docs.aws.amazon.com/ivs/latest/RealTimeUserGuide/rt-stream-ingest.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[UpdateIngestConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/update-ingest-configuration.html)」を参照してください。

### `update-stage`
<a name="ivs-realtime_UpdateStage_cli_2_topic"></a>

次のコード例は、`update-stage` を使用する方法を示しています。

**AWS CLI**  
**例 1: ステージの設定を更新するには**  
次の `update-stage` の例では、指定されたステージ ARN のステージを更新して、ステージ名を更新し、サムネイルの記録が有効になっている個々の参加者の録画を設定します。  

```
aws ivs-realtime update-stage \
    --arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --auto-participant-recording-configuration '{"mediaTypes": ["AUDIO_VIDEO"],"storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh", "recordingReconnectWindowSeconds": 100, \
        "thumbnailConfiguration": {"recordingMode": "INTERVAL","storage": ["SEQUENTIAL"],"targetIntervalSeconds": 60}} \
        "hlsConfiguration": {"targetSegmentDurationSeconds": 5}}' \
    --name stage1a
```
出力:  

```
{
    "stage": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
        "autoParticipantRecordingConfiguration": {
            "mediaTypes": [
                "AUDIO_VIDEO"
            ],
            "storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh",
            "thumbnailConfiguration": {
                "targetIntervalSeconds": 60,
                "storage": [
                    "SEQUENTIAL"
                ],
                "recordingMode": "INTERVAL"
            },
            "recordingReconnectWindowSeconds": 100,
            "hlsConfiguration": {
                "targetSegmentDurationSeconds": 5
            },
            "recordParticipantReplicas": true
        },
        "endpoints": {
            "events": "wss://global.events.live-video.net",
            "rtmp": "rtmp://9x0y8z7s6t5u.global-contribute-staging.live-video.net/app/",
            "rtmps": "rtmps://9x0y8z7s6t5u.global-contribute-staging.live-video.net:443/app/",
            "whip": "https://1a2b3c4d5e6f.global-bm.whip.live-video.net"
        },
        "name": "stage1a",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
**例 2: 参加者のレプリカ記録の無効化を含むステージの設定を更新するには**  
次の `update-stage` の例では、指定されたステージ ARN のステージを更新してステージ名を更新し、個々の参加者の記録を、サムネイルの記録を有効にし、参加者のレプリカ記録を無効にして設定します。  

```
aws ivs-realtime update-stage \
    --arn arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh \
    --auto-participant-recording-configuration '{"mediaTypes": ["AUDIO_VIDEO"],"storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh", "recordingReconnectWindowSeconds": 100, \
        "thumbnailConfiguration": {"recordingMode": "INTERVAL","storage": ["SEQUENTIAL"],"targetIntervalSeconds": 60}, "recordParticipantReplicas":false} \
        "hlsConfiguration": {"targetSegmentDurationSeconds": 5}}' \
    --name stage1a
```
出力:  

```
{
    "stage": {
        "arn": "arn:aws:ivs:us-west-2:123456789012:stage/abcdABCDefgh",
        "autoParticipantRecordingConfiguration": {
            "mediaTypes": [
                "AUDIO_VIDEO"
            ],
            "storageConfigurationArn": "arn:aws:ivs:us-west-2:123456789012:storage-configuration/abcdABCDefgh",
            "thumbnailConfiguration": {
                "targetIntervalSeconds": 60,
                "storage": [
                    "SEQUENTIAL"
                ],
                "recordingMode": "INTERVAL"
            },
            "recordingReconnectWindowSeconds": 100,
            "hlsConfiguration": {
                "targetSegmentDurationSeconds": 5
            },
            "recordParticipantReplicas": false
        },
        "endpoints": {
            "events": "wss://global.events.live-video.net",
            "rtmp": "rtmp://9x0y8z7s6t5u.global-contribute-staging.live-video.net/app/",
            "rtmps": "rtmps://9x0y8z7s6t5u.global-contribute-staging.live-video.net:443/app/",
            "whip": "https://1a2b3c4d5e6f.global-bm.whip.live-video.net"
        },
        "name": "stage1a",
        "tags": {}
    }
}
```
詳細については、「*Amazon IVS Low-Latency Streaming ユーザーガイド*」の「[Amazon IVS ストリームで複数ホストを有効にする](https://docs.aws.amazon.com/ivs/latest/LowLatencyUserGuide/multiple-hosts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ivs-realtime/update-stage.html)」を参照してください。

# を使用した Amazon Kendra の例 AWS CLI
<a name="cli_2_kendra_code_examples"></a>

次のコード例は、Amazon Kendra AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-data-source`
<a name="kendra_CreateDataSource_cli_2_topic"></a>

次のコード例は、`create-data-source` を使用する方法を示しています。

**AWS CLI**  
**Amazon Kendra データソースコネクタを作成するには**  
次の `create-data-source` は、Amazon Kendra データソースコネクタを作成して設定します。`describe-data-source` を使用してデータソースコネクタのステータスを表示し、ステータスが、データソースコネクタが完全に作成されなかったことを示す "FAILED" の場合は、エラーメッセージを確認することができます。  

```
aws kendra create-data-source \
    --name "example data source 1" \
    --description "Example data source 1 for example index 1 contains the first set of example documents" \
    --tags '{"Key": "test resources", "Value": "kendra"}, {"Key": "test resources", "Value": "aws"}' \
    --role-arn "arn:aws:iam::my-account-id:role/KendraRoleForS3TemplateConfigDataSource" \
    --index-id exampleindex1 \
    --language-code "es" \
    --schedule "0 0 18 ? * TUE,MON,WED,THU,FRI,SAT *" \
    --configuration '{"TemplateConfiguration": {"Template": file://s3schemaconfig.json}}' \
    --type "TEMPLATE" \
    --custom-document-enrichment-configuration '{"PostExtractionHookConfiguration": {"LambdaArn": "arn:aws:iam::my-account-id:function/my-function-ocr-docs", "S3Bucket": "s3://amzn-s3-demo-bucket/scanned-image-text-example-docs"}, "RoleArn": "arn:aws:iam:my-account-id:role/KendraRoleForCDE"}' \
    --vpc-configuration '{"SecurityGroupIds": ["sg-1234567890abcdef0"], "SubnetIds": ["subnet-1c234","subnet-2b134"]}'
```
出力:  

```
{
    "Id": "exampledatasource1"
}
```
詳細については、「**Amazon Kendra デベロッパーガイド」の「[Getting started with an Amazon Kendra index and data source connector](https://docs.aws.amazon.com/kendra/latest/dg/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDataSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kendra/create-data-source.html)」を参照してください。

### `create-index`
<a name="kendra_CreateIndex_cli_2_topic"></a>

次のコード例は、`create-index` を使用する方法を示しています。

**AWS CLI**  
**Amazon Kendra インデックスを作成するには**  
次の `create-index` は、Amazon Kendra インデックスを作成して設定します。`describe-index` を使用してインデックスのステータスを表示し、ステータスが、インデックスが完全に作成されなかったことを示す "FAILED" の場合は、エラーメッセージを確認することができます。  

```
aws kendra create-index \
    --name "example index 1" \
    --description "Example index 1 contains the first set of example documents" \
    --tags '{"Key": "test resources", "Value": "kendra"}, {"Key": "test resources", "Value": "aws"}' \
    --role-arn "arn:aws:iam::my-account-id:role/KendraRoleForExampleIndex" \
    --edition "DEVELOPER_EDITION" \
    --server-side-encryption-configuration '{"KmsKeyId": "my-kms-key-id"}' \
    --user-context-policy "USER_TOKEN" \
    --user-token-configurations '{"JsonTokenTypeConfiguration": {"GroupAttributeField": "groupNameField", "UserNameAttributeField": "userNameField"}}'
```
出力:  

```
{
   "Id": index1
}
```
詳細については、「**Amazon Kendra デベロッパーガイド」の「[Getting started with an Amazon Kendra index and data source connector](https://docs.aws.amazon.com/kendra/latest/dg/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kendra/create-index.html)」を参照してください。

### `describe-data-source`
<a name="kendra_DescribeDataSource_cli_2_topic"></a>

次のコード例は、`describe-data-source` を使用する方法を示しています。

**AWS CLI**  
**Amazon Kendra データソースコネクタに関する情報を取得するには**  
次の `describe-data-source` は、Amazon Kendra データソースコネクタに関する情報を取得します。データソースコネクタの設定を表示し、ステータスが、データソースコネクタが完全に作成されなかったことを示す "FAILED" の場合は、エラーメッセージを確認することができます。  

```
aws kendra describe-data-source \
    --id exampledatasource1 \
    --index-id exampleindex1
```
出力:  

```
{
    "Configuration": {
        "TemplateConfiguration": {
            "Template": {
                "connectionConfiguration": {
                    "repositoryEndpointMetadata": {
                        "BucketName": "amzn-s3-demo-bucket"
                    }
                },
                "repositoryConfigurations": {
                    "document":{
                        "fieldMappings": [
                            {
                                "indexFieldName":"_document_title",
                                "indexFieldType":"STRING",
                                "dataSourceFieldName": "title"
                            },
                            {
                                "indexFieldName":"_last_updated_at",
                                "indexFieldType":"DATE",
                                "dataSourceFieldName": "modified_date"
                            }
                        ]
                    }
                },
                "additionalProperties": {
                    "inclusionPatterns": [
                        "*.txt",
                        "*.doc",
                        "*.docx"
                    ],
                    "exclusionPatterns": [
                        "*.json"
                    ],
                    "inclusionPrefixes": [
                        "PublicExampleDocsFolder"
                    ],
                    "exclusionPrefixes": [
                        "PrivateDocsFolder/private"
                    ],
                    "aclConfigurationFilePath": "ExampleDocsFolder/AclConfig.json",
                    "metadataFilesPrefix": "metadata"
                },
                "syncMode": "FULL_CRAWL",
                "type" : "S3",
                "version": "1.0.0"
            }
        }
    },
    "CreatedAt": 2024-02-25T13:30:10+00:00,
    "CustomDocumentEnrichmentConfiguration": {
        "PostExtractionHookConfiguration": {
            "LambdaArn": "arn:aws:iam::my-account-id:function/my-function-ocr-docs",
            "S3Bucket": "s3://amzn-s3-demo-bucket/scanned-image-text-example-docs/function"
        },
        "RoleArn": "arn:aws:iam:my-account-id:role/KendraRoleForCDE"
    }
    "Description": "Example data source 1 for example index 1 contains the first set of example documents",
    "Id": exampledatasource1,
    "IndexId": exampleindex1,
    "LanguageCode": "en",
    "Name": "example data source 1",
    "RoleArn": "arn:aws:iam::my-account-id:role/KendraRoleForS3TemplateConfigDataSource",
    "Schedule": "0 0 18 ? * TUE,MON,WED,THU,FRI,SAT *",
    "Status": "ACTIVE",
    "Type": "TEMPLATE",
    "UpdatedAt": 1709163615,
    "VpcConfiguration": {
        "SecurityGroupIds": ["sg-1234567890abcdef0"],
        "SubnetIds": ["subnet-1c234","subnet-2b134"]
    }
}
```
詳細については、「**Amazon Kendra デベロッパーガイド」の「[Getting started with an Amazon Kendra index and data source connector](https://docs.aws.amazon.com/kendra/latest/dg/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDataSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kendra/describe-data-source.html)」を参照してください。

### `describe-index`
<a name="kendra_DescribeIndex_cli_2_topic"></a>

次のコード例は、`describe-index` を使用する方法を示しています。

**AWS CLI**  
**Amazon Kendra インデックスに関する情報を取得するには**  
次の `describe-index` は、Amazon Kendra インデックスに関する情報を取得します。インデックスの設定を表示し、ステータスが、インデックスが完全に作成されなかったことを示す "FAILED" の場合は、エラーメッセージを確認することができます。  

```
aws kendra describe-index \
    --id exampleindex1
```
出力:  

```
{
    "CapacityUnits": {
        "QueryCapacityUnits": 0,
        "StorageCapacityUnits": 0
    },
    "CreatedAt": 2024-02-25T12:30:10+00:00,
    "Description": "Example index 1 contains the first set of example documents",
    "DocumentMetadataConfigurations": [
        {
            "Name": "_document_title",
            "Relevance": {
                "Importance": 8
            },
            "Search": {
                "Displayable": true,
                "Facetable": false,
                "Searchable": true,
                "Sortable": false
            },
            "Type": "STRING_VALUE"
        },
        {
            "Name": "_document_body",
            "Relevance": {
                "Importance": 5
            },
            "Search": {
                "Displayable": true,
                "Facetable": false,
                "Searchable": true,
                "Sortable": false
            },
            "Type": "STRING_VALUE"
        },
        {
            "Name": "_last_updated_at",
            "Relevance": {
                "Importance": 6,
                "Duration": "2628000s",
                "Freshness": true
            },
            "Search": {
                "Displayable": true,
                "Facetable": false,
                "Searchable": true,
                "Sortable": true
            },
            "Type": "DATE_VALUE"
        },
        {
            "Name": "department_custom_field",
            "Relevance": {
                "Importance": 7,
                "ValueImportanceMap": {
                    "Human Resources" : 4,
                    "Marketing and Sales" : 2,
                    "Research and innvoation" : 3,
                    "Admin" : 1
                }
            },
            "Search": {
                "Displayable": true,
                "Facetable": true,
                "Searchable": true,
                "Sortable": true
            },
            "Type": "STRING_VALUE"
        }
    ],
    "Edition": "DEVELOPER_EDITION",
    "Id": "index1",
    "IndexStatistics": {
        "FaqStatistics": {
            "IndexedQuestionAnswersCount": 10
        },
        "TextDocumentStatistics": {
            "IndexedTextBytes": 1073741824,
            "IndexedTextDocumentsCount": 1200
        }
    },
    "Name": "example index 1",
    "RoleArn": "arn:aws:iam::my-account-id:role/KendraRoleForExampleIndex",
    "ServerSideEncryptionConfiguration": {
        "KmsKeyId": "my-kms-key-id"
    },
    "Status": "ACTIVE",
    "UpdatedAt": 1709163615,
    "UserContextPolicy": "USER_TOKEN",
    "UserTokenConfigurations": [
        {
            "JsonTokenTypeConfiguration": {
                "GroupAttributeField": "groupNameField",
                "UserNameAttributeField": "userNameField"
            }
        }
    ]
}
```
詳細については、「**Amazon Kendra デベロッパーガイド」の「[Getting started with an Amazon Kendra index and data source connector](https://docs.aws.amazon.com/kendra/latest/dg/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kendra/describe-index.html)」を参照してください。

### `update-data-source`
<a name="kendra_UpdateDataSource_cli_2_topic"></a>

次のコード例は、`update-data-source` を使用する方法を示しています。

**AWS CLI**  
**Amazon Kendra データソースコネクタを更新するには**  
次の `update-data-source` は、Amazon Kendra データソースコネクタの設定を更新します。アクションが成功すると、サービスは出力なし、HTTP ステータスコード 200、または AWS CLI がコード 0 を返します。`describe-data-source` を使用して、データソースコネクタの設定とステータスを表示できます。  

```
aws kendra update-data-source \
    --id exampledatasource1 \
    --index-id exampleindex1 \
    --name "new name for example data source 1" \
    --description "new description for example data source 1" \
    --role-arn arn:aws:iam::my-account-id:role/KendraNewRoleForExampleDataSource \
    --configuration '{"TemplateConfiguration": {"Template": file://s3schemanewconfig.json}}' \
    --custom-document-enrichment-configuration '{"PostExtractionHookConfiguration": {"LambdaArn": "arn:aws:iam::my-account-id:function/my-function-ocr-docs", "S3Bucket": "s3://amzn-s3-demo-bucket/scanned-image-text-example-docs"}, "RoleArn": "arn:aws:iam:my-account-id:role/KendraNewRoleForCDE"}' \
    --language-code "es" \
    --schedule "0 0 18 ? * MON,WED,FRI *" \
    --vpc-configuration '{"SecurityGroupIds": ["sg-1234567890abcdef0"], "SubnetIds": ["subnet-1c234","subnet-2b134"]}'
```
このコマンドは何も出力しません。  
詳細については、「**Amazon Kendra デベロッパーガイド」の「[Getting started with an Amazon Kendra index and data source connector](https://docs.aws.amazon.com/kendra/latest/dg/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDataSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kendra/update-data-source.html)」を参照してください。

### `update-index`
<a name="kendra_UpdateIndex_cli_2_topic"></a>

次のコード例は、`update-index` を使用する方法を示しています。

**AWS CLI**  
**Amazon Kendra インデックスを更新するには**  
次の `update-index` は、Amazon Kendra インデックスの設定を更新します。アクションが成功すると、サービスは出力なし、HTTP ステータスコード 200、または AWS CLI がコード 0 を返します。`describe-index` を使用して、インデックスの設定とステータスを表示できます。  

```
aws kendra update-index \
    --id enterpriseindex1 \
    --name "new name for Enterprise Edition index 1" \
    --description "new description for Enterprise Edition index 1" \
    --role-arn arn:aws:iam::my-account-id:role/KendraNewRoleForEnterpriseIndex \
    --capacity-units '{"QueryCapacityUnits": 2, "StorageCapacityUnits": 1}' \
    --document-metadata-configuration-updates '{"Name": "_document_title", "Relevance": {"Importance": 6}}, {"Name": "_last_updated_at", "Relevance": {"Importance": 8}}' \
    --user-context-policy "USER_TOKEN" \
    --user-token-configurations '{"JsonTokenTypeConfiguration": {"GroupAttributeField": "groupNameField", "UserNameAttributeField": "userNameField"}}'
```
このコマンドは何も出力しません。  
詳細については、「**Amazon Kendra デベロッパーガイド」の「[Getting started with an Amazon Kendra index and data source connector](https://docs.aws.amazon.com/kendra/latest/dg/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kendra/update-index.html)」を参照してください。

# を使用した Kinesis の例 AWS CLI
<a name="cli_2_kinesis_code_examples"></a>

次のコード例は、Kinesis AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags-to-stream`
<a name="kinesis_AddTagsToStream_cli_2_topic"></a>

次のコード例は、`add-tags-to-stream` を使用する方法を示しています。

**AWS CLI**  
**データストリームにタグを追加するには**  
次の `add-tags-to-stream` の例では、キー `samplekey` と値 `example` を持つタグを指定されたストリームに割り当てます。  

```
aws kinesis add-tags-to-stream \
    --stream-name samplestream \
    --tags samplekey=example
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Kinesis Data Streams Developer Guide*」の「[Tagging Your Streams](https://docs.aws.amazon.com/streams/latest/dev/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddTagsToStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/add-tags-to-stream.html)」を参照してください。

### `create-stream`
<a name="kinesis_CreateStream_cli_2_topic"></a>

次のコード例は、`create-stream` を使用する方法を示しています。

**AWS CLI**  
**データストリームを作成するには**  
次の `create-stream` の例は、3 つのシャードを含む samplestream という名前のデータストリームを作成します。  

```
aws kinesis create-stream \
    --stream-name samplestream \
    --shard-count 3
```
このコマンドは何も出力しません。  
詳細については、「Amazon Kinesis Data Streams ディベロッパーガイド」の「[API を使用したストリームの作成](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-create-stream.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/create-stream.html)」を参照してください。**

### `decrease-stream-retention-period`
<a name="kinesis_DecreaseStreamRetentionPeriod_cli_2_topic"></a>

次のコード例は、`decrease-stream-retention-period` を使用する方法を示しています。

**AWS CLI**  
**データストリームの保持期間を短縮するには**  
次の `decrease-stream-retention-period` の例では、samplestream という名前のストリームの保持期間 (データレコードがストリームに追加された後、アクセス可能な期間) を 48 時間に短縮します。  

```
aws kinesis decrease-stream-retention-period \
    --stream-name samplestream \
    --retention-period-hours 48
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[データ保持期間の変更](https://docs.aws.amazon.com/streams/latest/dev/kinesis-extended-retention.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecreaseStreamRetentionPeriod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/decrease-stream-retention-period.html)」を参照してください。

### `delete-stream`
<a name="kinesis_DeleteStream_cli_2_topic"></a>

次のコード例は、`delete-stream` を使用する方法を示しています。

**AWS CLI**  
**データストリームを削除するには**  
次の `delete-stream` の例は、指定されたデータストリームを削除します。  

```
aws kinesis delete-stream \
    --stream-name samplestream
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Kinesis Data Streams ディベロッパーガイド*」の「[ストリームを削除する](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-delete-stream.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/delete-stream.html)」を参照してください。

### `deregister-stream-consumer`
<a name="kinesis_DeregisterStreamConsumer_cli_2_topic"></a>

次のコード例は、`deregister-stream-consumer` を使用する方法を示しています。

**AWS CLI**  
**データストリームコンシューマーの登録を解除するには**  
次の `deregister-stream-consumer` 例では、指定されたコンシューマーを指定されたデータストリームから登録解除します。  

```
aws kinesis deregister-stream-consumer \
    --stream-arn arn:aws:kinesis:us-west-2:123456789012:stream/samplestream \
    --consumer-name KinesisConsumerApplication
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Kinesis Data Streams Developer Guide*」の「[Developing Consumers with Enhanced Fan-Out Using the Kinesis Data Streams API](https://docs.aws.amazon.com/streams/latest/dev/building-enhanced-consumers-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterStreamConsumer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/deregister-stream-consumer.html)」を参照してください。

### `describe-limits`
<a name="kinesis_DescribeLimits_cli_2_topic"></a>

次のコード例は、`describe-limits` を使用する方法を示しています。

**AWS CLI**  
**シャード制限の説明を表示には**  
次の の`describe-limits`例では、現在の AWS アカウントのシャード制限と使用状況を表示します。  

```
aws kinesis describe-limits
```
出力:  

```
{
    "ShardLimit": 500,
    "OpenShardCount": 29
}
```
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[ストリームをリシャーディングする](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-resharding.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLimits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/describe-limits.html)」を参照してください。

### `describe-stream-consumer`
<a name="kinesis_DescribeStreamConsumer_cli_2_topic"></a>

次のコード例は、`describe-stream-consumer` を使用する方法を示しています。

**AWS CLI**  
**データストリームコンシューマーの説明を表示するには**  
次の `describe-stream-consumer` の例では、指定されたデータストリームに登録された、指定されたコンシューマーの説明を返します。  

```
aws kinesis describe-stream-consumer \
    --stream-arn arn:aws:kinesis:us-west-2:012345678912:stream/samplestream \
    --consumer-name KinesisConsumerApplication
```
出力:  

```
{
    "ConsumerDescription": {
        "ConsumerName": "KinesisConsumerApplication",
        "ConsumerARN": "arn:aws:kinesis:us-west-2:123456789012:stream/samplestream/consumer/KinesisConsumerApplication:1572383852",
        "ConsumerStatus": "ACTIVE",
        "ConsumerCreationTimestamp": 1572383852.0,
        "StreamARN": "arn:aws:kinesis:us-west-2:123456789012:stream/samplestream"
    }
}
```
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[Reading Data from Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/building-consumers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStreamConsumer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/describe-stream-consumer.html)」を参照してください。

### `describe-stream-summary`
<a name="kinesis_DescribeStreamSummary_cli_2_topic"></a>

次のコード例は、`describe-stream-summary` を使用する方法を示しています。

**AWS CLI**  
**データストリームの概要説明を表示するには**  
次の `describe-stream-summary` の例では、指定されたデータストリームの概要説明 (シャードリストなし) を提供します。  

```
aws kinesis describe-stream-summary \
    --stream-name samplestream
```
出力:  

```
{
    "StreamDescriptionSummary": {
        "StreamName": "samplestream",
        "StreamARN": "arn:aws:kinesis:us-west-2:123456789012:stream/samplestream",
        "StreamStatus": "ACTIVE",
        "RetentionPeriodHours": 48,
        "StreamCreationTimestamp": 1572297168.0,
        "EnhancedMonitoring": [
            {
                "ShardLevelMetrics": []
            }
        ],
        "EncryptionType": "NONE",
        "OpenShardCount": 3,
        "ConsumerCount": 0
    }
}
```
詳細については、「Amazon Kinesis Data Streams ディベロッパーガイド」の「[ストリームの作成と管理](https://docs.aws.amazon.com/streams/latest/dev/working-with-streams.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStreamSummary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/describe-stream-summary.html)」を参照してください。

### `describe-stream`
<a name="kinesis_DescribeStream_cli_2_topic"></a>

次のコード例は、`describe-stream` を使用する方法を示しています。

**AWS CLI**  
**データストリームを記述するには**  
次の `describe-stream` の例は、指定されたデータストリームの詳細を返します。  

```
aws kinesis describe-stream \
    --stream-name samplestream
```
出力:  

```
{
    "StreamDescription": {
        "Shards": [
            {
                "ShardId": "shardId-000000000000",
                "HashKeyRange": {
                    "StartingHashKey": "0",
                    "EndingHashKey": "113427455640312821154458202477256070484"
                },
                "SequenceNumberRange": {
                    "StartingSequenceNumber": "49600871682957036442365024926191073437251060580128653314"
                }
            },
            {
                "ShardId": "shardId-000000000001",
                "HashKeyRange": {
                    "StartingHashKey": "113427455640312821154458202477256070485",
                    "EndingHashKey": "226854911280625642308916404954512140969"
                },
                "SequenceNumberRange": {
                    "StartingSequenceNumber": "49600871682979337187563555549332609155523708941634633746"
                }
            },
            {
                "ShardId": "shardId-000000000002",
                "HashKeyRange": {
                    "StartingHashKey": "226854911280625642308916404954512140970",
                    "EndingHashKey": "340282366920938463463374607431768211455"
                },
                "SequenceNumberRange": {
                    "StartingSequenceNumber": "49600871683001637932762086172474144873796357303140614178"
                }
            }
        ],
        "StreamARN": "arn:aws:kinesis:us-west-2:123456789012:stream/samplestream",
        "StreamName": "samplestream",
        "StreamStatus": "ACTIVE",
        "RetentionPeriodHours": 24,
        "EnhancedMonitoring": [
            {
                "ShardLevelMetrics": []
            }
        ],
        "EncryptionType": "NONE",
        "KeyId": null,
        "StreamCreationTimestamp": 1572297168.0
    }
}
```
詳細については、「Amazon Kinesis Data Streams ディベロッパーガイド」の「[ストリームの作成と管理](https://docs.aws.amazon.com/streams/latest/dev/working-with-streams.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/describe-stream.html)」を参照してください。**

### `disable-enhanced-monitoring`
<a name="kinesis_DisableEnhancedMonitoring_cli_2_topic"></a>

次のコード例は、`disable-enhanced-monitoring` を使用する方法を示しています。

**AWS CLI**  
**シャードレベルメトリクスの拡張モニタリングを無効にするには**  
次の `disable-enhanced-monitoring` の例では、シャードレベルメトリクスの拡張 Kinesis データストリームモニタリングを無効にします。  

```
aws kinesis disable-enhanced-monitoring \
    --stream-name samplestream --shard-level-metrics ALL
```
出力:  

```
{
    "StreamName": "samplestream",
    "CurrentShardLevelMetrics": [
        "IncomingBytes",
        "OutgoingRecords",
        "IteratorAgeMilliseconds",
        "IncomingRecords",
        "ReadProvisionedThroughputExceeded",
        "WriteProvisionedThroughputExceeded",
        "OutgoingBytes"
    ],
    "DesiredShardLevelMetrics": []
}
```
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[Monitoring Streams in Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/monitoring.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableEnhancedMonitoring](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/disable-enhanced-monitoring.html)」を参照してください。

### `enable-enhanced-monitoring`
<a name="kinesis_EnableEnhancedMonitoring_cli_2_topic"></a>

次のコード例は、`enable-enhanced-monitoring` を使用する方法を示しています。

**AWS CLI**  
**シャードレベルメトリクスの拡張モニタリングを有効にするには**  
次の `enable-enhanced-monitoring` の例では、シャードレベルメトリクスの拡張 Kinesis データストリームモニタリングを有効にします。  

```
aws kinesis enable-enhanced-monitoring \
    --stream-name samplestream \
    --shard-level-metrics ALL
```
出力:  

```
{
    "StreamName": "samplestream",
    "CurrentShardLevelMetrics": [],
    "DesiredShardLevelMetrics": [
        "IncomingBytes",
        "OutgoingRecords",
        "IteratorAgeMilliseconds",
        "IncomingRecords",
        "ReadProvisionedThroughputExceeded",
        "WriteProvisionedThroughputExceeded",
        "OutgoingBytes"
    ]
}
```
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[Monitoring Streams in Amazon Kinesis Data Streams](https://docs.aws.amazon.com/streams/latest/dev/monitoring.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableEnhancedMonitoring](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/enable-enhanced-monitoring.html)」を参照してください。

### `get-records`
<a name="kinesis_GetRecords_cli_2_topic"></a>

次のコード例は、`get-records` を使用する方法を示しています。

**AWS CLI**  
**シャードからレコードを取得するには**  
次の `get-records` の例は、指定されたシャードイテレーターを使用して Kinesis データストリームのシャードからデータレコードを取得します。  

```
aws kinesis get-records \
    --shard-iterator AAAAAAAAAAF7/0mWD7IuHj1yGv/TKuNgx2ukD5xipCY4cy4gU96orWwZwcSXh3K9tAmGYeOZyLZrvzzeOFVf9iN99hUPw/w/b0YWYeehfNvnf1DYt5XpDJghLKr3DzgznkTmMymDP3R+3wRKeuEw6/kdxY2yKJH0veaiekaVc4N2VwK/GvaGP2Hh9Fg7N++q0Adg6fIDQPt4p8RpavDbk+A4sL9SWGE1
```
出力:  

```
{
    "Records": [],
    "MillisBehindLatest": 80742000
}
```
詳細については、[「Amazon Kinesis Data Streams デベロッパーガイド」の AWS 「 SDK for Java での Kinesis Data Streams API を使用したコンシューマーの開発](https://docs.aws.amazon.com/streams/latest/dev/developing-consumers-with-sdk.html)」を参照してください。 *Amazon Kinesis *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRecords](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/get-records.html)」を参照してください。

### `get-shard-iterator`
<a name="kinesis_GetShardIterator_cli_2_topic"></a>

次のコード例は、`get-shard-iterator` を使用する方法を示しています。

**AWS CLI**  
**シャードイテレータを取得するには**  
次の `get-shard-iterator` の例では、`AT_SEQUENCE_NUMBER` シャードイテレータタイプを使用してシャードイテレータを生成し、指定されたシーケンス番号で示される位置からデータレコードの読み取りを正確に開始します。  

```
aws kinesis get-shard-iterator \
    --stream-name samplestream \
    --shard-id shardId-000000000001 \
    --shard-iterator-type LATEST
```
出力:  

```
{
    "ShardIterator": "AAAAAAAAAAFEvJjIYI+3jw/4aqgH9FifJ+n48XWTh/IFIsbILP6o5eDueD39NXNBfpZ10WL5K6ADXk8w+5H+Qhd9cFA9k268CPXCz/kebq1TGYI7Vy+lUkA9BuN3xvATxMBGxRY3zYK05gqgvaIRn94O8SqeEqwhigwZxNWxID3Ej7YYYcxQi8Q/fIrCjGAy/n2r5Z9G864YpWDfN9upNNQAR/iiOWKs"
}
```
詳細については、[「Amazon Kinesis Data Streams デベロッパーガイド」の AWS 「 SDK for Java での Kinesis Data Streams API を使用したコンシューマーの開発](https://docs.aws.amazon.com/streams/latest/dev/developing-consumers-with-sdk.html)」を参照してください。 *Amazon Kinesis *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetShardIterator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/get-shard-iterator.html)」を参照してください。

### `increase-stream-retention-period`
<a name="kinesis_IncreaseStreamRetentionPeriod_cli_2_topic"></a>

次のコード例は、`increase-stream-retention-period` を使用する方法を示しています。

**AWS CLI**  
**データストリームの保持期間を延長するには**  
次の `increase-stream-retention-period` の例では、指定されたストリームの保持期間 (データレコードがストリームに追加された後、アクセス可能な期間) を 168 時間に延長します。  

```
aws kinesis increase-stream-retention-period \
    --stream-name samplestream \
    --retention-period-hours 168
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[データ保持期間の変更](https://docs.aws.amazon.com/streams/latest/dev/kinesis-extended-retention.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IncreaseStreamRetentionPeriod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/increase-stream-retention-period.html)」を参照してください。

### `list-shards`
<a name="kinesis_ListShards_cli_2_topic"></a>

次のコード例は、`list-shards` を使用する方法を示しています。

**AWS CLI**  
**データストリーム内のシャードを一覧表示するには**  
次の `list-shards` の例では、指定されたストリーム内のシャードのうち、ID が指定された `exclusive-start-shard-id` (`shardId-000000000000`) 以降のものをすべて一覧表示します。  

```
aws kinesis list-shards \
    --stream-name samplestream \
    --exclusive-start-shard-id shardId-000000000000
```
出力:  

```
{
    "Shards": [
        {
            "ShardId": "shardId-000000000001",
            "HashKeyRange": {
                "StartingHashKey": "113427455640312821154458202477256070485",
                "EndingHashKey": "226854911280625642308916404954512140969"
            },
            "SequenceNumberRange": {
                "StartingSequenceNumber": "49600871682979337187563555549332609155523708941634633746"
            }
        },
        {
            "ShardId": "shardId-000000000002",
            "HashKeyRange": {
                "StartingHashKey": "226854911280625642308916404954512140970",
                "EndingHashKey": "340282366920938463463374607431768211455"
            },
            "SequenceNumberRange": {
                "StartingSequenceNumber": "49600871683001637932762086172474144873796357303140614178"
            }
        }
    ]
}
```
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[シャードの一覧表示](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-list-shards.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListShards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/list-shards.html)」を参照してください。

### `list-streams`
<a name="kinesis_ListStreams_cli_2_topic"></a>

次のコード例は、`list-streams` を使用する方法を示しています。

**AWS CLI**  
**データストリームを一覧表示するには**  
次の `list-streams` の例は、現在のアカウントとリージョンのすべてのアクティブなデータストリームを一覧表示します。  

```
aws kinesis list-streams
```
出力:  

```
{
    "StreamNames": [
        "samplestream",
        "samplestream1"
    ]
}
```
詳細については、「Amazon Kinesis Data Streams ディベロッパーガイド」の「[ストリームのリスト](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-list-streams.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/list-streams.html)」を参照してください。**

### `list-tags-for-stream`
<a name="kinesis_ListTagsForStream_cli_2_topic"></a>

次のコード例は、`list-tags-for-stream` を使用する方法を示しています。

**AWS CLI**  
**データストリームのタグを一覧表示するには**  
次の `list-tags-for-stream` の例では、指定されたデータストリームにアタッチされたタグを一覧表示します。  

```
aws kinesis list-tags-for-stream \
    --stream-name samplestream
```
出力:  

```
{
    "Tags": [
        {
            "Key": "samplekey",
            "Value": "example"
        }
    ],
    "HasMoreTags": false
}
```
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[ストリームのタグ付け](https://docs.aws.amazon.com/streams/latest/dev/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/list-tags-for-stream.html)」を参照してください。

### `merge-shards`
<a name="kinesis_MergeShards_cli_2_topic"></a>

次のコード例は、`merge-shards` を使用する方法を示しています。

**AWS CLI**  
**シャードをマージするには**  
次の `merge-shards` の例では、指定されたデータストリーム内の 2 つの隣接するシャード (ID が shardId-000000000000 と shardId-000000000001) をマージし、1 つのシャードに結合します。  

```
aws kinesis merge-shards \
    --stream-name samplestream \
    --shard-to-merge shardId-000000000000 \
    --adjacent-shard-to-merge shardId-000000000001
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[2 つのシャードを結合する](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-resharding-merge.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MergeShards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/merge-shards.html)」を参照してください。

### `put-record`
<a name="kinesis_PutRecord_cli_2_topic"></a>

次のコード例は、`put-record` を使用する方法を示しています。

**AWS CLI**  
**データストリームにデータレコードを書き込むには**  
次の `put-record` の例は、指定されたパーティションキーを使用して、指定されたデータストリームに単一のデータレコードを書き込みます。  

```
aws kinesis put-record \
    --stream-name samplestream \
    --data sampledatarecord \
    --partition-key samplepartitionkey
```
出力:  

```
{
    "ShardId": "shardId-000000000009",
    "SequenceNumber": "49600902273357540915989931256901506243878407835297513618",
    "EncryptionType": "KMS"
}
```
詳細については、[Amazon Kinesis Data Streams デベロッパーガイド」の「Amazon Kinesis Data Streams API と AWS SDK for Java を使用したプロデューサーの開発](https://docs.aws.amazon.com/streams/latest/dev/developing-producers-with-sdk.html)」を参照してください。 *Amazon Kinesis *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutRecord](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/put-record.html)」を参照してください。**

### `put-records`
<a name="kinesis_PutRecords_cli_2_topic"></a>

次のコード例は、`put-records` を使用する方法を示しています。

**AWS CLI**  
**複数のレコードをデータストリームに書き込むには**  
次の `put-records` の例では、指定されたパーティションキーを使用してデータレコードを書き込み、1 回の呼び出しで別のパーティションキーを使用して別のデータレコードを書き込みます。  

```
aws kinesis put-records \
    --stream-name samplestream \
    --records Data=blob1,PartitionKey=partitionkey1 Data=blob2,PartitionKey=partitionkey2
```
出力:  

```
{
    "FailedRecordCount": 0,
    "Records": [
        {
            "SequenceNumber": "49600883331171471519674795588238531498465399900093808706",
            "ShardId": "shardId-000000000004"
        },
        {
            "SequenceNumber": "49600902273357540915989931256902715169698037101720764562",
            "ShardId": "shardId-000000000009"
        }
    ],
    "EncryptionType": "KMS"
}
```
詳細については、[Amazon Kinesis Data Streams デベロッパーガイド」の「Amazon Kinesis Data Streams API と AWS SDK for Java を使用したプロデューサーの開発](https://docs.aws.amazon.com/streams/latest/dev/developing-producers-with-sdk.html)」を参照してください。 *Amazon Kinesis *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutRecords](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/put-records.html)」を参照してください。

### `register-stream-consumer`
<a name="kinesis_RegisterStreamConsumer_cli_2_topic"></a>

次のコード例は、`register-stream-consumer` を使用する方法を示しています。

**AWS CLI**  
**データストリームコンシューマーを登録するには**  
次の `register-stream-consumer` の例では、`KinesisConsumerApplication` というコンシューマーを指定されたデータストリームに登録します。  

```
aws kinesis register-stream-consumer \
    --stream-arn arn:aws:kinesis:us-west-2:012345678912:stream/samplestream \
    --consumer-name KinesisConsumerApplication
```
出力:  

```
{
    "Consumer": {
        "ConsumerName": "KinesisConsumerApplication",
        "ConsumerARN": "arn:aws:kinesis:us-west-2: 123456789012:stream/samplestream/consumer/KinesisConsumerApplication:1572383852",
        "ConsumerStatus": "CREATING",
        "ConsumerCreationTimestamp": 1572383852.0
    }
}
```
詳細については、「*Amazon Kinesis Data Streams ディベロッパーガイド*」の「[Kinesis Data Streams API を使用して拡張ファンアウトコンシューマーを開発する](https://docs.aws.amazon.com/streams/latest/dev/building-enhanced-consumers-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI API リファレンス*」の「[RegisterStreamConsumer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/register-stream-consumer.html)」を参照してください。

### `remove-tags-from-stream`
<a name="kinesis_RemoveTagsFromStream_cli_2_topic"></a>

次のコード例は、`remove-tags-from-stream` を使用する方法を示しています。

**AWS CLI**  
**データストリームからタグを削除するには**  
次の `remove-tags-from-stream` の例では、指定されたキーを持つタグを指定されたデータストリームから削除します。  

```
aws kinesis remove-tags-from-stream \
    --stream-name samplestream \
    --tag-keys samplekey
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[ストリームのタグ付け](https://docs.aws.amazon.com/streams/latest/dev/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/remove-tags-from-stream.html)」を参照してください。

### `split-shard`
<a name="kinesis_SplitShard_cli_2_topic"></a>

次のコード例は、`split-shard` を使用する方法を示しています。

**AWS CLI**  
**シャードを分割するには**  
次の `split-shard` の例では、新しい開始ハッシュキー 10 を使用して、指定されたシャードを 2 つの新しいシャードに分割します。  

```
aws kinesis split-shard \
    --stream-name samplestream \
    --shard-to-split shardId-000000000000 \
    --new-starting-hash-key 10
```
このコマンドは何も出力しません。  
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[シャードの分割](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-resharding-split.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SplitShard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/split-shard.html)」を参照してください。

### `start-stream-encryption`
<a name="kinesis_StartStreamEncryption_cli_2_topic"></a>

次のコード例は、`start-stream-encryption` を使用する方法を示しています。

**AWS CLI**  
**データストリームの暗号化を有効にするには**  
次の の`start-stream-encryption`例では、指定された AWS KMS キーを使用して、指定されたストリームのサーバー側の暗号化を有効にします。  

```
aws kinesis start-stream-encryption \
    --encryption-type KMS \
    --key-id arn:aws:kms:us-west-2:012345678912:key/a3c4a7cd-728b-45dd-b334-4d3eb496e452 \
    --stream-name samplestream
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Kinesis Data Streams Developer Guide*」の「[Amazon Kinesis Data Streams のデータ保護](https://docs.aws.amazon.com/streams/latest/dev/server-side-encryption.html)」をご参照ください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartStreamEncryption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/start-stream-encryption.html)」を参照してください。

### `stop-stream-encryption`
<a name="kinesis_StopStreamEncryption_cli_2_topic"></a>

次のコード例は、`stop-stream-encryption` を使用する方法を示しています。

**AWS CLI**  
**データストリームの暗号化を無効にするには**  
次の の`stop-stream-encryption`例では、指定された AWS KMS キーを使用して、指定されたストリームのサーバー側の暗号化を無効にします。  

```
aws kinesis start-stream-encryption \
    --encryption-type KMS \
    --key-id arn:aws:kms:us-west-2:012345678912:key/a3c4a7cd-728b-45dd-b334-4d3eb496e452 \
    --stream-name samplestream
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Kinesis Data Streams Developer Guide*」の「[Amazon Kinesis Data Streams のデータ保護](https://docs.aws.amazon.com/streams/latest/dev/server-side-encryption.html)」をご参照ください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopStreamEncryption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/stop-stream-encryption.html)」を参照してください。

### `update-shard-count`
<a name="kinesis_UpdateShardCount_cli_2_topic"></a>

次のコード例は、`update-shard-count` を使用する方法を示しています。

**AWS CLI**  
**データストリームのシャード数を更新するには**  
次の `update-shard-count` の例では、指定されたデータストリームのシャード数を 6 に更新します。この例では、同じサイズのシャードが作成される均一なスケーリングを使用します。  

```
aws kinesis update-shard-count \
    --stream-name samplestream \
    --scaling-type UNIFORM_SCALING \
    --target-shard-count 6
```
出力:  

```
{
    "StreamName": "samplestream",
    "CurrentShardCount": 3,
    "TargetShardCount": 6
}
```
詳細については、「*Amazon Kinesis Data Streams デベロッパーガイド*」の「[ストリームをリシャーディングする](https://docs.aws.amazon.com/streams/latest/dev/kinesis-using-sdk-java-resharding.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateShardCount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kinesis/update-shard-count.html)」を参照してください。

# AWS KMS を使用した の例 AWS CLI
<a name="cli_2_kms_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `cancel-key-deletion`
<a name="kms_CancelKeyDeletion_cli_2_topic"></a>

次のコード例は、`cancel-key-deletion` を使用する方法を示しています。

**AWS CLI**  
**カスタマーマネージド KMS キーのスケジュールされた削除をキャンセルするには**  
次の `cancel-key-deletion` の例では、カスタマーマネージド KMS キーのスケジュールされた削除をキャンセルします。  

```
aws kms cancel-key-deletion \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "KeyId": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab"
}
```
`cancel-key-deletion` コマンドが成功すると、スケジュールされた削除はキャンセルされます。ただし、KMS キーのキー状態は `Disabled` であるため、暗号化オペレーションで KMS キーを使用することはできません。機能を復元するには、`enable-key` コマンドを使用します。  
詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[キーの削除のスケジュールとキャンセル](https://docs.aws.amazon.com/kms/latest/developerguide/deleting-keys.html#deleting-keys-scheduling-key-deletion)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelKeyDeletion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/cancel-key-deletion.html)」を参照してください。

### `connect-custom-key-store`
<a name="kms_ConnectCustomKeyStore_cli_2_topic"></a>

次のコード例は、`connect-custom-key-store` を使用する方法を示しています。

**AWS CLI**  
**カスタムキーストアを接続するには**  
次の `connect-custom-key-store` の例では、指定されたカスタムキーストアを再接続します。このようなコマンドを使用すると、カスタムキーストアを初めて接続したり、切断されたキーストアを再接続したりできます。  
このコマンドを使用して、 AWS CloudHSM キーストアまたは外部キーストアを接続できます。  

```
aws kms connect-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0
```
このコマンドは出力を返しません。コマンドが有効であることを確認するには、`describe-custom-key-stores` コマンドを使用します。  
 AWS CloudHSM キーストアの接続については、[「 Key Management Service デベロッパーガイド」の AWS CloudHSM キーストアの接続と切断](https://docs.aws.amazon.com/kms/latest/developerguide/disconnect-keystore.html)」を参照してください。 *AWS *  
外部キーストアの接続については、「*AWS Key Management Service デベロッパーガイド*」の「[外部キーストアの接続と切断](https://docs.aws.amazon.com/kms/latest/developerguide/xks-connect-disconnect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConnectCustomKeyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/connect-custom-key-store.html)」を参照してください。

### `create-alias`
<a name="kms_CreateAlias_cli_2_topic"></a>

次のコード例は、`create-alias` を使用する方法を示しています。

**AWS CLI**  
**KMS キーのエイリアスを作成するには**  
次の `create-alias` コマンドは、キー ID `1234abcd-12ab-34cd-56ef-1234567890ab` で識別される KMS キーの `example-alias` という名前のエイリアスを作成します。  
エイリアス名は `alias/` で始める必要があります。で始まるエイリアス名は使用しないでください`alias/aws`。これらは で使用するために予約されています AWS。  

```
aws kms create-alias \
    --alias-name alias/example-alias \
    --target-key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
このコマンドは出力を返しません。新しいエイリアスを確認するには、`list-aliases` コマンドを使用します。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[エイリアスの使用](https://docs.aws.amazon.com/kms/latest/developerguide/kms-alias.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/create-alias.html)」を参照してください。**

### `create-custom-key-store`
<a name="kms_CreateCustomKeyStore_cli_2_topic"></a>

次の例は、`create-custom-key-store` を使用する方法を説明しています。

**AWS CLI**  
**例 1: AWS CloudHSM キーストアを作成するには**  
次の の`create-custom-key-store`例では、必要なパラメータを使用して AWS CloudHSM クラスターによってバックアップされた AWS CloudHSM キーストアを作成します。また、`custom-key-store-type``parameter with the default value: ``AWS_CLOUDHSM` を追加することもできます  
 AWS CLI で `trust-anchor-certificate` コマンドのファイル入力を指定するには、 `file://` プレフィックスが必要です。  

```
aws kms create-custom-key-store \
    --custom-key-store-name ExampleCloudHSMKeyStore \
    --cloud-hsm-cluster-id cluster-1a23b4cdefg \
    --key-store-password kmsPswd \
    --trust-anchor-certificate file://customerCA.crt
```
出力:  

```
{
    "CustomKeyStoreId": cks-1234567890abcdef0
}
```
詳細については、「 Key Management Service [デベロッパーガイド」の AWS CloudHSM キーストア](https://docs.aws.amazon.com/kms/latest/developerguide/create-keystore.html)の作成」を参照してください。 *AWS *  
**例 2: パブリックエンドポイント接続を使用する外部キーストアを作成するには**  
次の`create-custom-key-store`例では、インターネット経由で KMS と通信する外部キーストア (XKS) AWS を作成します。  
この例では、`XksProxyUriPath` はオプションのプレフィックス `example-prefix` を使用します。  
注: AWS CLI バージョン 1.0 を使用する場合は、XksProxyUriEndpoint パラメータなどの HTTP または HTTPS 値を持つパラメータを指定する前に、次のコマンドを実行します。  

```
aws configure set cli_follow_urlparam false
```
それ以外の場合、 AWS CLI バージョン 1.0 はパラメータ値をその URI アドレスにあるコンテンツに置き換えます。  

```
aws kms create-custom-key-store \
    --custom-key-store-name ExamplePublicEndpointXKS \
    --custom-key-store-type EXTERNAL_KEY_STORE \
    --xks-proxy-connectivity PUBLIC_ENDPOINT \
    --xks-proxy-uri-endpoint "https://myproxy.xks.example.com" \
    --xks-proxy-uri-path "/example-prefix/kms/xks/v1" \
    --xks-proxy-authentication-credential "AccessKeyId=ABCDE12345670EXAMPLE, RawSecretAccessKey=DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo="
```
出力:  

```
{
    "CustomKeyStoreId": cks-2234567890abcdef0
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[外部キーストアの作成](https://docs.aws.amazon.com/kms/latest/developerguide/create-keystorecreate-xks-keystore.html)」を参照してください。**  
**例 3: VPC エンドポイントサービス接続を使用する外部キーストアを作成するには**  
次の`create-custom-key-store`例では、Amazon VPC エンドポイントサービスを使用して KMS と通信する外部キーストア (XKS) AWS を作成します。  
注: AWS CLI バージョン 1.0 を使用する場合は、XksProxyUriEndpoint パラメータなどの HTTP または HTTPS 値を持つパラメータを指定する前に、次のコマンドを実行します。  

```
aws configure set cli_follow_urlparam false
```
それ以外の場合、 AWS CLI バージョン 1.0 はパラメータ値をその URI アドレスにあるコンテンツに置き換えます。  

```
aws kms create-custom-key-store \
    --custom-key-store-name ExampleVPCEndpointXKS \
    --custom-key-store-type EXTERNAL_KEY_STORE \
    --xks-proxy-connectivity VPC_ENDPOINT_SERVICE \
    --xks-proxy-uri-endpoint "https://myproxy-private.xks.example.com" \
    --xks-proxy-uri-path "/kms/xks/v1" \
    --xks-proxy-vpc-endpoint-service-name "com.amazonaws.vpce.us-east-1.vpce-svc-example1" \
    --xks-proxy-authentication-credential "AccessKeyId=ABCDE12345670EXAMPLE, RawSecretAccessKey=DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo="
```
出力:  

```
{
    "CustomKeyStoreId": cks-3234567890abcdef0
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[外部キーストアの作成](https://docs.aws.amazon.com/kms/latest/developerguide/create-keystorecreate-xks-keystore.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomKeyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/create-custom-key-store.html)」を参照してください。

### `create-grant`
<a name="kms_CreateGrant_cli_2_topic"></a>

次のコード例は、`create-grant` を使用する方法を示しています。

**AWS CLI**  
**権限を作成するには**  
次の `create-grant` の例は、`exampleUser` ユーザーが `1234abcd-12ab-34cd-56ef-1234567890ab` の KMS キーで `decrypt` コマンドを使用する権限を作成します。廃止するプリンシパルは `adminRole` ロールです。この権限は `EncryptionContextSubset` 権限の制約を使用して `"Department": "IT"` キー値ペアを含む `decrypt` リクエストでの暗号化のみを許可します。  

```
aws kms create-grant \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --grantee-principal arn:aws:iam::123456789012:user/exampleUser \
    --operations Decrypt \
    --constraints EncryptionContextSubset={Department=IT} \
    --retiring-principal arn:aws:iam::123456789012:role/adminRole
```
出力:  

```
{
    "GrantId": "1a2b3c4d2f5e69f440bae30eaec9570bb1fb7358824f9ddfa1aa5a0dab1a59b2",
    "GrantToken": "<grant token here>"
}
```
権限に関する詳細情報を表示するには、`list-grants` コマンドを使用します。  
詳細については、*AWS 「 Key Management Service デベロッパーガイド*」の[「KMS AWS でのグラン](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html)ト」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateGrant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/create-grant.html)」を参照してください。**

### `create-key`
<a name="kms_CreateKey_cli_2_topic"></a>

次の例は、`create-key` を使用する方法を説明しています。

**AWS CLI**  
**例 1: KMS でカスタマーマネージド KMS AWS キーを作成するには**  
次の `create-key` の例は、対称暗号化 KMS キーを作成します。  
基本的な KMS キー (対称暗号化キー) を作成するには、パラメータを指定する必要はありません。対称暗号化キーは、これらのパラメータのデフォルト値によって作成されます。  
このコマンドはキーポリシーを指定しないため、KMS キーにはプログラムで作成された KMS キーの[デフォルトキーポリシー](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html#key-policy-default)が適用されます。キーポリシーを表示するには、`get-key-policy` コマンドを使用します。キーポリシーを変更するには、`put-key-policy` コマンドを使用します。  

```
aws kms create-key
```
この `create-key` コマンドは、新しい KMS キーのキー ID と ARN を含むキーメタデータを返します。これらの値を使用して、他の KMS オペレーションで KMS AWS キーを識別できます。出力にはタグは含まれません。KMS キーのタグを表示するには、`list-resource-tags command` を使用します。  
出力:  

```
{
    "KeyMetadata": {
        "AWSAccountId": "111122223333",
        "Arn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "CreationDate": "2017-07-05T14:04:55-07:00",
        "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6",
        "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
        "Description": "",
        "Enabled": true,
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "SYMMETRIC_DEFAULT",
        "KeyState": "Enabled",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "MultiRegion": false,
        "Origin": "AWS_KMS"
        "EncryptionAlgorithms": [
            "SYMMETRIC_DEFAULT"
        ]
    }
}
```
注: この `create-key` コマンドではエイリアスを指定できません。新しい KMS キーのエイリアスを作成するには、`create-alias` コマンドを使用してください。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[キーの作成](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)」を参照してください。**  
**例 2: 暗号化と復号用の非対称 RSA KMS キーを作成するには**  
次の `create-key` の例は、暗号化と復号用の非対称 RSA キーペアを含む KMS キーを作成します。キーの作成後は、キー仕様とキーの使用方法を変更することはできません。  

```
aws kms create-key \
   --key-spec RSA_4096 \
   --key-usage ENCRYPT_DECRYPT
```
出力:  

```
{
    "KeyMetadata": {
        "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "AWSAccountId": "111122223333",
        "CreationDate": "2021-04-05T14:04:55-07:00",
        "CustomerMasterKeySpec": "RSA_4096",
        "Description": "",
        "Enabled": true,
        "EncryptionAlgorithms": [
            "RSAES_OAEP_SHA_1",
            "RSAES_OAEP_SHA_256"
        ],
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "RSA_4096",
        "KeyState": "Enabled",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "MultiRegion": false,
        "Origin": "AWS_KMS"
    }
}
```
詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
**例 3: 署名と検証用に非対称楕円曲線 KMS キーを作成するには**  
署名と検証用に非対称楕円曲線 (ECC) キーペアを持つ非対称 KMS キーを作成します。`SIGN_VERIFY` は ECC KMS キーの唯一の有効な値ですが、`--key-usage` パラメータは必須です。キーの作成後は、キー仕様とキーの使用方法を変更することはできません。  

```
aws kms create-key \
    --key-spec ECC_NIST_P521 \
    --key-usage SIGN_VERIFY
```
出力:  

```
{
    "KeyMetadata": {
        "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "AWSAccountId": "111122223333",
        "CreationDate": "2019-12-02T07:48:55-07:00",
        "CustomerMasterKeySpec": "ECC_NIST_P521",
        "Description": "",
        "Enabled": true,
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "ECC_NIST_P521",
        "KeyState": "Enabled",
        "KeyUsage": "SIGN_VERIFY",
        "MultiRegion": false,
        "Origin": "AWS_KMS",
        "SigningAlgorithms": [
            "ECDSA_SHA_512"
        ]
    }
}
```
詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
**例 4: 署名と検証用に非対称 ML-DSA KMS キーを作成するには**  
この例では、署名と検証用の Module-Lattice Digital Signature Algorithm (ML-DSA) キーを作成します。`SIGN_VERIFY` は ML-DSA キーの唯一の有効な値ですが、key-usage パラメータは必須です。  

```
aws kms create-key \
    --key-spec ML_DSA_65 \
    --key-usage SIGN_VERIFY
```
出力:  

```
{
    "KeyMetadata": {
        "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "AWSAccountId": "111122223333",
        "CreationDate": "2019-12-02T07:48:55-07:00",
        "Description": "",
        "Enabled": true,
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "ML_DSA_65",
        "KeyState": "Enabled",
        "KeyUsage": "SIGN_VERIFY",
        "MultiRegion": false,
        "Origin": "AWS_KMS",
        "SigningAlgorithms": [
            "ML_DSA_SHAKE_256"
        ]
    }
}
```
詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
**例 5: HMAC KMS キーを作成するには**  
次の `create-key` の例は、384-bit HMAC KMS キーを作成します。`--key-usage` パラメータの値 `GENERATE_VERIFY_MAC` は HMAC KMS キーの唯一の有効な値ですが、この値は必須です。  

```
aws kms create-key \
    --key-spec HMAC_384 \
    --key-usage GENERATE_VERIFY_MAC
```
出力:  

```
{
    "KeyMetadata": {
        "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "AWSAccountId": "111122223333",
        "CreationDate": "2022-04-05T14:04:55-07:00",
        "CustomerMasterKeySpec": "HMAC_384",
        "Description": "",
        "Enabled": true,
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "HMAC_384",
        "KeyState": "Enabled",
        "KeyUsage": "GENERATE_VERIFY_MAC",
        "MacAlgorithms": [
            "HMAC_SHA_384"
        ],
        "MultiRegion": false,
        "Origin": "AWS_KMS"
    }
}
```
詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の HMAC キー](https://docs.aws.amazon.com/kms/latest/developerguide/hmac.html)」を参照してください。 *AWS *  
**例 6: マルチリージョンのプライマリ KMS キーを作成するには**  
次の `create-key` の例は、マルチリージョンのプライマリ対称暗号化キーを作成します。すべてのパラメータのデフォルト値によって対称暗号化キーが作成されるため、この KMS キーに必要なのは `--multi-region` パラメータだけです。 AWS CLI で、ブールパラメータが true であることを示すには、パラメータ名を指定します。  

```
aws kms create-key \
    --multi-region
```
出力:  

```
{
    "KeyMetadata": {
        "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef12345678990ab",
        "AWSAccountId": "111122223333",
        "CreationDate": "2021-09-02T016:15:21-09:00",
        "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6",
        "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
        "Description": "",
        "Enabled": true,
        "EncryptionAlgorithms": [
          "SYMMETRIC_DEFAULT"
        ],
        "KeyId": "mrk-1234abcd12ab34cd56ef12345678990ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "SYMMETRIC_DEFAULT",
        "KeyState": "Enabled",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "MultiRegion": true,
        "MultiRegionConfiguration": {
            "MultiRegionKeyType": "PRIMARY",
            "PrimaryKey": {
                "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef12345678990ab",
                "Region": "us-west-2"
            },
            "ReplicaKeys": []
        },
        "Origin": "AWS_KMS"
    }
}
```
詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
**例 7: インポートされたキーマテリアルの KMS キーを作成するには**  
次の `create-key` の例は、キーマテリアルなしで KMS キーを作成します。操作が完了すると、独自のキーマテリアルを KMS キーにインポートできます。この KMS キーを作成するには、`--origin` パラメータを `EXTERNAL` に設定します。  

```
aws kms create-key \
    --origin EXTERNAL
```
出力:  

```
{
     "KeyMetadata": {
         "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
         "AWSAccountId": "111122223333",
         "CreationDate": "2019-12-02T07:48:55-07:00",
         "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
         "Description": "",
         "Enabled": false,
         "EncryptionAlgorithms": [
             "SYMMETRIC_DEFAULT"
         ],
         "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
         "KeyManager": "CUSTOMER",
         "KeySpec": "SYMMETRIC_DEFAULT",
         "KeyState": "PendingImport",
         "KeyUsage": "ENCRYPT_DECRYPT",
         "MultiRegion": false,
         "Origin": "EXTERNAL"
     }
 }
```
詳細については、[「 Key Management Service デベロッパーガイド」の「KMS AWS キーでのキーマテリアルのインポート](https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys.html)」を参照してください。 *AWS *  
**例 6: AWS CloudHSM キーストアに KMS キーを作成するには**  
次の の`create-key`例では、指定された AWS CloudHSM キーストアに KMS キーを作成します。オペレーションは、KMS で KMS AWS キーとそのメタデータを作成し、カスタムキーストアに関連付けられた AWS CloudHSM クラスターにキーマテリアルを作成します。`--custom-key-store-id` および `--origin` パラメータが必要です。  

```
aws kms create-key \
    --origin AWS_CLOUDHSM \
    --custom-key-store-id cks-1234567890abcdef0
```
出力:  

```
{
    "KeyMetadata": {
        "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "AWSAccountId": "111122223333",
        "CloudHsmClusterId": "cluster-1a23b4cdefg",
        "CreationDate": "2019-12-02T07:48:55-07:00",
        "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
        "CustomKeyStoreId": "cks-1234567890abcdef0",
        "Description": "",
        "Enabled": true,
        "EncryptionAlgorithms": [
            "SYMMETRIC_DEFAULT"
        ],
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "SYMMETRIC_DEFAULT",
        "KeyState": "Enabled",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "MultiRegion": false,
        "Origin": "AWS_CLOUDHSM"
    }
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[AWS CloudHSM キーストア](https://docs.aws.amazon.com/kms/latest/developerguide/keystore-cloudhsm.html)」を参照してください。**  
**例 8: 外部キーストアに KMS キーを作成するには**  
次の `create-key` の例は、指定された外部キーストアに KMS キーを作成します。このコマンドでは、`--custom-key-store-id`、`--origin`、および `--xks-key-id` パラメータが必須です。  
`--xks-key-id` パラメータは、外部キーマネージャーにある既存の対称暗号化キーの ID を指定します。このキーは KMS キーの外部キーマテリアルとして機能します。`--origin` パラメータの値は、`EXTERNAL_KEY_STORE` である必要があります。`custom-key-store-id` パラメータは、外部キーストアプロキシに接続されている外部キーストアを識別する必要があります。  

```
aws kms create-key \
    --origin EXTERNAL_KEY_STORE \
    --custom-key-store-id cks-9876543210fedcba9 \
    --xks-key-id bb8562717f809024
```
出力:  

```
{
    "KeyMetadata": {
        "Arn": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "AWSAccountId": "111122223333",
        "CreationDate": "2022-12-02T07:48:55-07:00",
        "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
        "CustomKeyStoreId": "cks-9876543210fedcba9",
        "Description": "",
        "Enabled": true,
        "EncryptionAlgorithms": [
            "SYMMETRIC_DEFAULT"
        ],
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeySpec": "SYMMETRIC_DEFAULT",
        "KeyState": "Enabled",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "MultiRegion": false,
        "Origin": "EXTERNAL_KEY_STORE",
        "XksKeyConfiguration": {
            "Id": "bb8562717f809024"
        }
    }
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[外部キーストア](https://docs.aws.amazon.com/kms/latest/developerguide/keystore-external.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/create-key.html)」を参照してください。**

### `decrypt`
<a name="kms_Decrypt_cli_2_topic"></a>

次のコード例は、`decrypt` を使用する方法を示しています。

**AWS CLI**  
**例 1: 対称 KMS キーを使用して暗号化されたメッセージを復号するには (Linux および macOS)**  
次の`decrypt`コマンド例は、 AWS CLI でデータを復号化するための推奨方法を示しています。このバージョンは、対称 KMS キーを使用してデータを復号する方法を示しています。  
ファイルに暗号文を指定します。`--ciphertext-blob` パラメータの値には、バイナリファイルからデータを読み取るように CLI に指示する `fileb://` プレフィックスを使用します。ファイルが現在のディレクトリにない場合は、ファイルへのフルパスを入力します。ファイルから AWS CLI パラメータ値を読み取る方法の詳細については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の「Load AWS CLI parameters from a file <https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html>」および*AWS 「 コマンドラインツールブログ*」の「Best Practices for Local File Parameters<https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/>」を参照してください。暗号化テキストを復号する KMS キーを指定します。対称 KMS キーで復号する場合、 `--key-id` パラメータは必要ありません。 AWS KMS は、暗号化テキストのメタデータからデータを暗号化するために使用された KMS キーのキー ID を取得できます。ただし、ベストプラクティスは常に、使用している KMS キーを指定することです。この方法により、意図した KMS キーを使用することができ、信頼できない KMS キーを使用して誤って暗号文を復号するのを防ぐことができます。プレーンテキストの出力をテキスト値としてリクエストします。`--query` パラメータは、出力から `Plaintext` フィールドの値のみを取得するように CLI に指示します。`--output` パラメータは出力を text.Base64 でデコードしたプレーンテキストとして返し、ファイルに保存します。次の例では、`Plaintext` パラメータの値を Base64 ユーティリティにパイプ (\$1) して、Base64 ユーティリティでデコードします。次に、デコードされた出力を `ExamplePlaintext` ファイルにリダイレクト (>) します。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。  

```
aws kms decrypt \
    --ciphertext-blob fileb://ExampleEncryptedFile \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --output text \
    --query Plaintext | base64 \
    --decode > ExamplePlaintextFile
```
このコマンドでは何も出力されません。`decrypt` コマンドからの出力は base64 でデコードされ、ファイルに保存されます。  
詳細については、「AWS Key Management Service API リファレンス」の「[Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html)」を参照してください。**  
**例 2: 対称 KMS キーを使用して暗号化されたメッセージを復号するには (Windows コマンドプロンプト)**  
次の例は、`certutil` ユーティリティを使用してプレーンテキストデータを Base64 でデコードする点を除いて、前の例と同じです。この手順には、次の例に示すように 2 つのコマンドが必要です。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。  

```
aws kms decrypt ^
    --ciphertext-blob fileb://ExampleEncryptedFile ^
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^
    --output text ^
    --query Plaintext > ExamplePlaintextFile.base64
```
`certutil` コマンドを実行します。  

```
certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile
```
出力:  

```
Input Length = 18
Output Length = 12
CertUtil: -decode command completed successfully.
```
詳細については、「AWS Key Management Service API リファレンス」の「[Decrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.html)」を参照してください。**  
**例 3: 非対称 KMS キーを使用して暗号化されたメッセージを復号するには (Linux および macOS)**  
次の `decrypt` コマンドの例は、RSA 非対称 KMS キーで暗号化されたデータを復号する方法を示します。  
非対称 KMS キーを使用する場合は、プレーンテキストの暗号化に使用するアルゴリズムを指定する `encryption-algorithm` パラメータが必要です。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。  

```
aws kms decrypt \
    --ciphertext-blob fileb://ExampleEncryptedFile \
    --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \
    --encryption-algorithm RSAES_OAEP_SHA_256 \
    --output text \
    --query Plaintext | base64 \
    --decode > ExamplePlaintextFile
```
このコマンドでは何も出力されません。`decrypt` コマンドからの出力は base64 でデコードされ、ファイルに保存されます。  
詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[Decrypt](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/decrypt.html)」を参照してください。**

### `delete-alias`
<a name="kms_DeleteAlias_cli_2_topic"></a>

次の例は、`delete-alias` を使用する方法を説明しています。

**AWS CLI**  
** AWS KMS エイリアスを削除するには**  
次の `delete-alias` の例は、エイリアス `alias/example-alias` を削除します。エイリアス名は alias/ で始まる必要があります。  

```
aws kms delete-alias \
    --alias-name alias/example-alias
```
このコマンドは何も出力しません。エイリアスを見つけるには、`list-aliases` コマンドを使用します。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[エイリアスの削除](https://docs.aws.amazon.com/kms/latest/developerguide/alias-manage.html#alias-delete)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/delete-alias.html)」を参照してください。**

### `delete-custom-key-store`
<a name="kms_DeleteCustomKeyStore_cli_2_topic"></a>

次のコード例は、`delete-custom-key-store` を使用する方法を示しています。

**AWS CLI**  
**カスタムキーストアを削除するには**  
次の `delete-custom-key-store` の例では、指定されたカスタムキーストアを削除します。  
 AWS CloudHSM キーストアを削除しても、関連付けられた CloudHSM クラスターには影響しません。外部キーストアを削除しても、関連付けられた外部キーストアプロキシ、外部キーマネージャー、または外部キーには影響しません。  
**注:** カスタムキーストアを削除する前に、カスタムキーストア内のすべての KMS キーの削除をスケジュールし、それらの KMS キーが削除されるまで待つ必要があります。その後、カスタムキーストアを切断する必要があります。カスタムキーストアで KMS キーを検索する方法については、*AWS 「 Key Management Service* [デベロッパーガイド」の「Delete an AWS CloudHSM key store (API)](https://docs.aws.amazon.com/kms/latest/developerguide/delete-keystore.html#delete-keystore-api)」を参照してください。  

```
delete-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0
```
このコマンドは出力を返しません。カスタムキーストアが削除されたことを確認するには、`describe-custom-key-stores` コマンドを使用します。  
 AWS CloudHSM キーストアの削除については、「 Key Management Service [デベロッパーガイド」の AWS CloudHSM キーストア](https://docs.aws.amazon.com/kms/latest/developerguide/delete-keystore.html)の削除」を参照してください。 *AWS *  
外部キーストアの削除については、「*AWS Key Management Service デベロッパーガイド*」の「[外部キーストアの削除](https://docs.aws.amazon.com/kms/latest/developerguide/delete-xks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCustomKeyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/delete-custom-key-store.html)」を参照してください。

### `delete-imported-key-material`
<a name="kms_DeleteImportedKeyMaterial_cli_2_topic"></a>

次のコード例は、`delete-imported-key-material` を使用する方法を示しています。

**AWS CLI**  
**KMS キーからインポートされたキーマテリアルを削除するには**  
次の `delete-imported-key-material` の例では、KMS キーにインポートされたキーマテリアルを削除します。  

```
aws kms delete-imported-key-material \
   --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6"
}
```
詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[Deleting imported key material](https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys-delete-key-material.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteImportedKeyMaterial](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/delete-imported-key-material.html)」を参照してください。

### `derive-shared-secret`
<a name="kms_DeriveSharedSecret_cli_2_topic"></a>

次のコード例は、`derive-shared-secret` を使用する方法を示しています。

**AWS CLI**  
**共有シークレットを取得するには**  
次の `derive-shared-secret` の例では、キーアグリーメントアルゴリズムを使用して共有シークレットを取得します。  
DeriveSharedSecret を呼び出すには、NIST 推奨楕円曲線 (ECC) または SM2 (中国リージョンのみ) の非対称 KMS キーペアを使用し、`KeyUsage`の値として `KEY_AGREEMENT` を指定する必要があります。  

```
aws kms derive-shared-secret \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --key-agreement-algorithm ECDH \
    --public-key "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvH3Yj0wbkLEpUl95Cv1cJVjsVNSjwGq3tCLnzXfhVwVvmzGN8pYj3U8nKwgouaHbBWNJYjP5VutbbkKS4Kv4GojwZBJyHN17kmxo8yTjRmjR15SKIQ8cqRA2uaERMLnpztIXdZp232PQPbWGxDyXYJ0aJ5EFSag"
```
出力:  

```
{
    "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
    "SharedSecret": "MEYCIQCKZLWyTk5runarx6XiAkU9gv3lbwPO/pHa+DXFehzdDwIhANwpsIV2g/9SPWLLsF6p/hiSskuIXMTRwqrMdVKWTMHG",
    "KeyAgreementAlgorithm": "ECDH",
    "KeyOrigin": "AWS_KMS"
}
```
詳細については、「*AWS Key Management Service API リファレンス*」の「[DeriveSharedSecret](https://docs.aws.amazon.com/kms/latest/APIReference/API_DeriveSharedSecret.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeriveSharedSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/derive-shared-secret.html)」を参照してください。

### `describe-custom-key-stores`
<a name="kms_DescribeCustomKeyStores_cli_2_topic"></a>

次の例は、`describe-custom-key-stores` を使用する方法を説明しています。

**AWS CLI**  
**例 1: AWS CloudHSM キーストアの詳細を取得するには**  
次の の`describe-custom-key-store`例では、指定された AWS CloudHSM キーストアの詳細を表示します。コマンドはどのタイプのカスタムキーストアでも同じですが、出力はキーストアのタイプと接続オプション (外部キーストアの場合) によって異なります。  
デフォルトでは、このコマンドはアカウントとリージョン内のすべてのカスタムキーストアに関する情報を表示します。特定のカスタムキーストアに関する情報を表示するには、`custom-key-store-name` または `custom-key-store-id` パラメータを使用します。  

```
aws kms describe-custom-key-stores \
    --custom-key-store-name ExampleCloudHSMKeyStore
```
このコマンドの出力には、接続状態 () を含む AWS CloudHSM キーストアに関する有用な詳細が含まれます`ConnectionState`。接続状態が `FAILED` の場合、出力には問題を説明する `ConnectionErrorCode` が含まれています。  
出力:  

```
{
    "CustomKeyStores": [
        {
            "CloudHsmClusterId": "cluster-1a23b4cdefg",
            "ConnectionState": "CONNECTED",
            "CreationDate": "2022-04-05T14:04:55-07:00",
            "CustomKeyStoreId": "cks-1234567890abcdef0",
            "CustomKeyStoreName": "ExampleExternalKeyStore",
            "TrustAnchorCertificate": "<certificate appears here>"
        }
    ]
}
```
詳細については、[「 Key Management Service デベロッパーガイド」の AWS CloudHSM キーストア](https://docs.aws.amazon.com/kms/latest/developerguide/view-keystore.html)の表示」を参照してください。 *AWS *  
**例 2: パブリックエンドポイント接続を使用する外部キーストアの詳細を取得するには**  
次の `describe-custom-key-store` の例では、指定された外部キーストアの詳細を表示します。コマンドはどのタイプのカスタムキーストアでも同じですが、出力はキーストアのタイプと接続オプション (外部キーストアの場合) によって異なります。  
デフォルトでは、このコマンドはアカウントとリージョン内のすべてのカスタムキーストアに関する情報を表示します。特定のカスタムキーストアに関する情報を表示するには、`custom-key-store-name` または `custom-key-store-id` パラメータを使用します。  

```
aws kms describe-custom-key-stores \
    --custom-key-store-id cks-9876543210fedcba9
```
このコマンドの出力には、接続状態 (`ConnectionState`) など、外部キーストアに関する有益な詳細が含まれています。接続状態が `FAILED` の場合、出力には問題を説明する `ConnectionErrorCode` が含まれています。  
出力:  

```
{
    "CustomKeyStores": [
        {
            "CustomKeyStoreId": "cks-9876543210fedcba9",
            "CustomKeyStoreName": "ExampleXKS",
            "ConnectionState": "CONNECTED",
            "CreationDate": "2022-12-02T07:48:55-07:00",
            "CustomKeyStoreType": "EXTERNAL_KEY_STORE",
            "XksProxyConfiguration": {
                "AccessKeyId": "ABCDE12345670EXAMPLE",
                "Connectivity": "PUBLIC_ENDPOINT",
                "UriEndpoint": "https://myproxy.xks.example.com",
                "UriPath": "/example-prefix/kms/xks/v1"
            }
        }
    ]
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[外部キーストアを表示する](https://docs.aws.amazon.com/kms/latest/developerguide/view-xks-keystore.html)」を参照してください。**  
**例 3: VPC エンドポイントサービス接続を使用する外部キーストアの詳細を取得するには**  
次の `describe-custom-key-store` の例では、指定された外部キーストアの詳細を表示します。コマンドはどのタイプのカスタムキーストアでも同じですが、出力はキーストアのタイプと接続オプション (外部キーストアの場合) によって異なります。  
デフォルトでは、このコマンドはアカウントとリージョン内のすべてのカスタムキーストアに関する情報を表示します。特定のカスタムキーストアに関する情報を表示するには、`custom-key-store-name` または `custom-key-store-id` パラメータを使用します。  

```
aws kms describe-custom-key-stores \
    --custom-key-store-id cks-2234567890abcdef0
```
このコマンドの出力には、接続状態 (`ConnectionState`) など、外部キーストアに関する有益な詳細が含まれています。接続状態が `FAILED` の場合、出力には問題を説明する `ConnectionErrorCode` が含まれています。  
出力:  

```
{
    "CustomKeyStores": [
        {
            "CustomKeyStoreId": "cks-3234567890abcdef0",
            "CustomKeyStoreName": "ExampleVPCExternalKeyStore",
            "ConnectionState": "CONNECTED",
            "CreationDate": "2022-12-22T07:48:55-07:00",
            "CustomKeyStoreType": "EXTERNAL_KEY_STORE",
            "XksProxyConfiguration": {
                "AccessKeyId": "ABCDE12345670EXAMPLE",
                "Connectivity": "VPC_ENDPOINT_SERVICE",
                "UriEndpoint": "https://myproxy-private.xks.example.com",
                "UriPath": "/kms/xks/v1",
                "VpcEndpointServiceName": "com.amazonaws.vpce.us-east-1.vpce-svc-example1"
            }
        }
    ]
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[外部キーストアを表示する](https://docs.aws.amazon.com/kms/latest/developerguide/view-xks-keystore.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCustomKeyStores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/describe-custom-key-stores.html)」を参照してください。

### `describe-key`
<a name="kms_DescribeKey_cli_2_topic"></a>

次のコード例は、`describe-key` を使用する方法を示しています。

**AWS CLI**  
**例 1: KMS キーの詳細情報を取得するには**  
次の の`describe-key`例では、サンプルアカウントとリージョンの Amazon S3 の AWS マネージドキーに関する詳細情報を取得します。このコマンドを使用して、 AWS マネージドキーとカスタマーマネージドキーの詳細を検索できます。  
KMS キーを指定するには、`key-id` パラメータを使用します。この例では、エイリアス名値を使用していますが、このコマンドでは、キー ID、キー ARN、エイリアス名、またはエイリアス ARN を使用できます。  

```
aws kms describe-key \
    --key-id alias/aws/s3
```
出力:  

```
{
    "KeyMetadata": {
        "AWSAccountId": "846764612917",
        "KeyId": "b8a9477d-836c-491f-857e-07937918959b",
        "Arn": "arn:aws:kms:us-west-2:846764612917:key/b8a9477d-836c-491f-857e-07937918959b",
        "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6",
        "CreationDate": 2017-06-30T21:44:32.140000+00:00,
        "Enabled": true,
        "Description": "Default KMS key that protects my S3 objects when no other key is defined",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "KeyState": "Enabled",
        "Origin": "AWS_KMS",
        "KeyManager": "AWS",
        "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
        "EncryptionAlgorithms": [
            "SYMMETRIC_DEFAULT"
        ]
    }
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[キーの表示](https://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html)」を参照してください。**  
**例 2: RSA 非対称 KMS キーの詳細を取得するには**  
次の `describe-key` の例は、署名と検証に使用される非対称 RSA KMS キーに関する詳細情報を取得します。  

```
aws kms describe-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "KeyMetadata": {
        "AWSAccountId": "111122223333",
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "Arn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "CreationDate": "2019-12-02T19:47:14.861000+00:00",
        "CustomerMasterKeySpec": "RSA_2048",
        "Enabled": false,
        "Description": "",
        "KeyState": "Disabled",
        "Origin": "AWS_KMS",
        "MultiRegion": false,
        "KeyManager": "CUSTOMER",
        "KeySpec": "RSA_2048",
        "KeyUsage": "SIGN_VERIFY",
        "SigningAlgorithms": [
            "RSASSA_PKCS1_V1_5_SHA_256",
            "RSASSA_PKCS1_V1_5_SHA_384",
            "RSASSA_PKCS1_V1_5_SHA_512",
            "RSASSA_PSS_SHA_256",
            "RSASSA_PSS_SHA_384",
            "RSASSA_PSS_SHA_512"
        ]
    }
}
```
**例 3: マルチリージョンのレプリカキーに関する詳細を取得するには**  
次の `describe-key` の例は、マルチリージョンのレプリカキーのメタデータを取得します。このマルチリージョンキーは対称暗号化キーです。マルチリージョンキーの `describe-key` コマンドの出力は、プライマリキーとそのすべてのレプリカに関する情報を返します。  

```
aws kms describe-key \
    --key-id arn:aws:kms:ap-northeast-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab
```
出力:  

```
{
    "KeyMetadata": {
        "MultiRegion": true,
        "AWSAccountId": "111122223333",
        "Arn": "arn:aws:kms:ap-northeast-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab",
        "CreationDate": "2021-06-28T21:09:16.114000+00:00",
        "CurrentKeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6",
        "Description": "",
        "Enabled": true,
        "KeyId": "mrk-1234abcd12ab34cd56ef1234567890ab",
        "KeyManager": "CUSTOMER",
        "KeyState": "Enabled",
        "KeyUsage": "ENCRYPT_DECRYPT",
        "Origin": "AWS_KMS",
        "CustomerMasterKeySpec": "SYMMETRIC_DEFAULT",
        "EncryptionAlgorithms": [
            "SYMMETRIC_DEFAULT"
        ],
        "MultiRegionConfiguration": {
            "MultiRegionKeyType": "PRIMARY",
            "PrimaryKey": {
                "Arn": "arn:aws:kms:us-west-2:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab",
                "Region": "us-west-2"
            },
            "ReplicaKeys": [
                {
                    "Arn": "arn:aws:kms:eu-west-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab",
                    "Region": "eu-west-1"
                },
                {
                    "Arn": "arn:aws:kms:ap-northeast-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab",
                    "Region": "ap-northeast-1"
                },
                {
                    "Arn": "arn:aws:kms:sa-east-1:111122223333:key/mrk-1234abcd12ab34cd56ef1234567890ab",
                    "Region": "sa-east-1"
                }
            ]
        }
    }
}
```
**例 4: HMAC KMS キーの詳細を取得するには**  
次の `describe-key` の例は、HMAC KMS キーの詳細情報を取得します。  

```
aws kms describe-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "KeyMetadata": {
        "AWSAccountId": "123456789012",
        "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
        "Arn": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab",
        "CreationDate": "2022-04-03T22:23:10.194000+00:00",
        "Enabled": true,
        "Description": "Test key",
        "KeyUsage": "GENERATE_VERIFY_MAC",
        "KeyState": "Enabled",
        "Origin": "AWS_KMS",
        "KeyManager": "CUSTOMER",
        "CustomerMasterKeySpec": "HMAC_256",
        "MacAlgorithms": [
            "HMAC_SHA_256"
        ],
        "MultiRegion": false
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/describe-key.html)」を参照してください。**

### `disable-key-rotation`
<a name="kms_DisableKeyRotation_cli_2_topic"></a>

次のコード例は、`disable-key-rotation` を使用する方法を示しています。

**AWS CLI**  
**KMS キーの自動ローテーションを無効にするには**  
次の `disable-key-rotation` の例では、カスタマーマネージド KMS キーの自動ローテーションを無効にします。自動ローテーションを再度有効にするには、`enable-key-rotation` コマンドを使用します。  

```
aws kms disable-key-rotation \
    --key-id arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
```
このコマンドは何も出力しません。KMS キーの自動ローテーションが無効になったことを確認するには、`get-key-rotation-status` コマンドを使用します。  
詳細については、「*AWS Key Management Service Developer Guide*」の「[Rotating keys](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableKeyRotation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/disable-key-rotation.html)」を参照してください。

### `disable-key`
<a name="kms_DisableKey_cli_2_topic"></a>

次のコード例は、`disable-key` を使用する方法を示しています。

**AWS CLI**  
**KMS キーを一時的に無効にするには**  
次の `disable-key` コマンドは、カスタマーマネージド KMS キーを無効にします。KMS キーを再度有効にするには、`enable-key` コマンドを使用します。  

```
aws kms disable-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
このコマンドは何も出力しません。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[キーの有効化と無効化](https://docs.aws.amazon.com/kms/latest/developerguide/enabling-keys.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[DisableKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/disable-key.html)」を参照してください。

### `disconnect-custom-key-store`
<a name="kms_DisconnectCustomKeyStore_cli_2_topic"></a>

次のコード例は、`disconnect-custom-key-store` を使用する方法を示しています。

**AWS CLI**  
**カスタムキーストアを切断するには**  
次の の`disconnect-custom-key-store`例では、 AWS CloudHSM クラスターからカスタムキーストアを切断します。キーストアを切断するのは、問題をトラブルシューティングする場合、キーストアの設定を更新する場合、キーストアの KMS キーが暗号化オペレーションで使用されないようにする場合です。  
このコマンドは、 AWS CloudHSM キーストアや外部キーストアなど、すべてのカスタムキーストアで同じです。  
このコマンドを実行する前に、例のカスタムキーストア ID を有効な ID に置き換えます。  

```
$ aws kms disconnect-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0
```
このコマンドでは何も出力されません。コマンドが有効であることを確認するには、`describe-custom-key-stores` コマンドを使用します。  
 AWS CloudHSM キーストアの切断の詳細については、「 Key *AWS Management Service デベロッパーガイド*[」の AWS CloudHSM キーストアの接続と切断](https://docs.aws.amazon.com/kms/latest/developerguide/disconnect-keystore.html)」を参照してください。  
外部キーストアの切断については、「*AWS Key Management Service デベロッパーガイド*」の「[外部キーストアの接続と切断](https://docs.aws.amazon.com/kms/latest/developerguide/xks-connect-disconnect.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisconnectCustomKeyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/disconnect-custom-key-store.html)」を参照してください。

### `enable-key-rotation`
<a name="kms_EnableKeyRotation_cli_2_topic"></a>

次のコード例は、`enable-key-rotation` を使用する方法を示しています。

**AWS CLI**  
**KMS キーの自動ローテーションを有効化するには**  
次の`enable-key-rotation` 例では、カスタマーマネージド KMS キーの自動ローテーションを、ローテーション期間が 180 日となるよう有効化します。KMS キーは、このコマンドの完了日から 1 年後 (約 365 日後) にローテーションされ、その後も毎年自動ローテーションされます。  
`--key-id` パラメータは KMS キーを識別します。この例ではキーの ARN 値を使用していますが、KMS キーのキー ID または ARN のどちらでも使用可能です。`--rotation-period-in-days` パラメータで次のローテーション日までの日数を指定します。90 日から 2560 日までの範囲で値を指定してください。値を指定しない場合、デフォルトは 365 日になります。  

```
aws kms enable-key-rotation \
    --key-id arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab \
    --rotation-period-in-days 180
```
このコマンドは何も出力しません。KMS キーが有効になっていることを確認するには、`get-key-rotation-status` コマンドを使用します。  
詳細については、「*AWS Key Management Service Developer Guide*」の「[Rotating keys](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableKeyRotation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/enable-key-rotation.html)」を参照してください。

### `enable-key`
<a name="kms_EnableKey_cli_2_topic"></a>

次のコード例は、`enable-key` を使用する方法を示しています。

**AWS CLI**  
**KMS キーを有効にするには**  
次の `enable-key` の例は、カスタマーマネージドキーを有効にします。このようなコマンドでは、`disable-key` コマンドを使用して一時的に無効にした KMS キーを有効にできます。また、削除が予定されていて削除がキャンセルされたために無効になっている KMS キーを有効にすることもできます。  
KMS キーを指定するには、`key-id` パラメータを使用します。この例では、キー ID 値を使用していますが、このコマンドでは、キー ID またはキー ARN 値を使用できます。  
このコマンドを実行する前に、サンプルキー ID を有効なキー ID に置き換えます。  

```
aws kms enable-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
このコマンドは何も出力しません。KMS キーが有効になっていることを確認するには、`describe-key` コマンドを使用します。`describe-key` 出力の `KeyState` および `Enabled` フィールドの値を参照してください。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[キーの有効化と無効化](https://docs.aws.amazon.com/kms/latest/developerguide/enabling-keys.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[EnableKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/enable-key.html)」を参照してください。

### `encrypt`
<a name="kms_Encrypt_cli_2_topic"></a>

次のコード例は、`encrypt` を使用する方法を示しています。

**AWS CLI**  
**例 1: Linux または MacOS でファイルの内容を暗号化するには**  
次の`encrypt`コマンドは、 AWS CLI でデータを暗号化するために推奨される方法を示しています。  

```
aws kms encrypt \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --plaintext fileb://ExamplePlaintextFile \
    --output text \
    --query CiphertextBlob | base64 \
    --decode > ExampleEncryptedFile
```
このコマンドは、以下の操作を行います。  
`--plaintext` パラメータを使用して暗号化するデータを指定します。このパラメータ値は base64 でエンコードされている必要があります。 `plaintext`パラメータの値は base64 でエンコードされている必要があります。または、 ファイルからバイナリデータを読み取るように AWS CLI に指示する `fileb://` プレフィックスを使用する必要があります。ファイルが現在のディレクトリにない場合は、ファイルへのフルパスを入力します。例えば、`fileb:///var/tmp/ExamplePlaintextFile` や `fileb://C:\Temp\ExamplePlaintextFile` などです。ファイルからの AWS CLI パラメータ値の読み取りの詳細については、*AWS 「 コマンドラインインターフェイスユーザーガイド*」の[「ファイルからのパラメータのロード](https://docs.aws.amazon.com/cli/latest/userguide/cli-using-param.html#cli-using-param-file)」および「 コマンドラインツールブログ」の[「ローカルファイルパラメータのベストプラクティス](https://blogs.aws.amazon.com/cli/post/TxLWWN1O25V1HE/Best-Practices-for-Local-File-Parameters)」を参照してください。 `--output`および AWS `--query`パラメータを使用して、コマンドの出力を制御します。これらのパラメータは、コマンドの出力から*暗号化テキスト*と呼ばれる暗号化されたデータを抽出します。出力の制御の詳細については、「 コマンド*AWS ラインインターフェイスユーザーガイド*[」の「コマンド出力の制御](https://docs.aws.amazon.com/cli/latest/userguide/controlling-output.html)」を参照してください。 `base64`ユーティリティを使用して、抽出された出力をバイナリデータにデコードします。`encrypt`コマンドが成功した場合に返される暗号化テキストは base64 でエンコードされたテキストです。 AWS CLI を使用して復号する前に、このテキストをデコードする必要があります。 はバイナリ暗号文を ファイルに保存します。 コマンド (`> ExampleEncryptedFile`) の最後の部分では、復号を容易にするためにバイナリ暗号文を ファイルに保存します。 AWS CLI を使用してデータを復号するコマンドの例については、復号の例を参照してください。  
**例 2: CLI AWS を使用して Windows でデータを暗号化する**  
この例は前の例と同じですが、`base64` の代わりに `certutil` ツールを使用します。この手順には、次の例に示すように 2 つのコマンドが必要です。  

```
aws kms encrypt \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --plaintext fileb://ExamplePlaintextFile \
    --output text \
    --query CiphertextBlob > C:\Temp\ExampleEncryptedFile.base64

certutil -decode C:\Temp\ExampleEncryptedFile.base64 C:\Temp\ExampleEncryptedFile
```
**例 3: 非対称 KMS キーを使用して暗号化する**  
次の `encrypt` コマンドは、プレーンテキストを非対称 KMS キーで暗号化する方法を示しています。`--encryption-algorithm` パラメータは必須です。すべての `encrypt` CLI コマンドと同様に、 `plaintext`パラメータは base64 でエンコードされているか、 `fileb://` プレフィックスを使用する必要があります。プレフィックスは、 ファイルからバイナリデータを読み取るように CLI AWS に指示します。  

```
aws kms encrypt \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --encryption-algorithm RSAES_OAEP_SHA_256 \
    --plaintext fileb://ExamplePlaintextFile \
    --output text \
    --query CiphertextBlob | base64 \
    --decode > ExampleEncryptedFile
```
このコマンドでは何も出力されません。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[Encrypt](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/encrypt.html)」を参照してください。**

### `generate-data-key-pair-without-plaintext`
<a name="kms_GenerateDataKeyPairWithoutPlaintext_cli_2_topic"></a>

次のコード例は、`generate-data-key-pair-without-plaintext` を使用する方法を示しています。

**AWS CLI**  
**ECC NIST P384 非対称データキーペアを生成するには**  
次の`generate-data-key-pair-without-plaintext`例では、ECC NIST P384 キーペアの外部での使用をリクエストします AWS。  
このコマンドは、プレーンテキストのパブリックキーとおよび指定された KMS キーで暗号化されたプライベートキーのコピーを返します。プレーンテキストのプライベートキーは返されません。暗号化されたプライベートキーを暗号化されたデータに安全に保存し、使用する必要がある場合は KMS AWS を呼び出してプライベートキーを復号できます。  
ECC NIST P384 非同期データキーペアをリクエストするには、値 `ECC_NIST_P384` を含む `key-pair-spec` パラメータを使用します。  
指定する KMS キーは、対称暗号化 KMS キー、つまり `KeySpec` が `SYMMETRIC_DEFAULT` の KMS キーである必要があります。  
注: この例の出力の値は、表示のために一部が切り捨てられています。  

```
aws kms generate-data-key-pair-without-plaintext \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --key-pair-spec ECC_NIST_P384
```
出力:  

```
{
    "PrivateKeyCiphertextBlob": "AQIDAHi6LtupRpdKl2aJTzkK6FbhOtQkMlQJJH3PdtHvS/y+hAFFxmiD134doUDzMGmfCEtcAAAHaTCCB2UGCSqGSIb3DQEHBqCCB1...",
    "PublicKey": "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA3A3eGMyPrvSn7+LdlJE1oUoQV5HpEuHAVbdOyND+NmYDH/mL1OSIEuLrcdZ5hrMH4pk83r40l...",
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6",
    "KeyPairSpec": "ECC_NIST_P384"
}
```
`PublicKey` と `PrivateKeyCiphertextBlob` は base64 でエンコードされた形式で返されます。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[データキーペア](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-key-pairs)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateDataKeyPairWithoutPlaintext](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/generate-data-key-pair-without-plaintext.html)」を参照してください。

### `generate-data-key-pair`
<a name="kms_GenerateDataKeyPair_cli_2_topic"></a>

次のコード例は、`generate-data-key-pair` を使用する方法を示しています。

**AWS CLI**  
**2048 ビット RSA 非対称データキーペアを生成するには**  
次の`generate-data-key-pair`例では、 の外部で使用する 2048 ビット RSA 非対称データキーペアをリクエストします AWS。このコマンドは、すぐに使用および削除できるプレーンテキストのパブリックキーとプレーンテキストのプライベートキー、および指定された KMS キーで暗号化されたプライベートキーのコピーを返します。暗号化されたデータとともに、暗号化されたプライベートキーを安全に保存できます。  
2048 ビットの RSA 非同期データキーペアをリクエストするには、値 `RSA_2048` を含む `key-pair-spec` パラメータを使用します。  
指定する KMS キーは、対称暗号化 KMS キー、つまり `KeySpec` が `SYMMETRIC_DEFAULT` の KMS キーである必要があります。  
注: この例の出力の値は、表示のために一部が切り捨てられています。  

```
aws kms generate-data-key-pair \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --key-pair-spec RSA_2048
```
出力:  

```
{
    "PrivateKeyCiphertextBlob": "AQIDAHi6LtupRpdKl2aJTzkK6FbhOtQkMlQJJH3PdtHvS/y+hAFFxmiD134doUDzMGmfCEtcAAAHaTCCB2UGCSqGSIb3DQEHBqCCB1...",
    "PrivateKeyPlaintext": "MIIG/QIBADANBgkqhkiG9w0BAQEFAASCBucwggbjAgEAAoIBgQDcDd4YzI+u9Kfv4t2UkTWhShBXkekS4cBVt07I0P42ZgMf+YvU5IgS4ut...",
    "PublicKey": "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA3A3eGMyPrvSn7+LdlJE1oUoQV5HpEuHAVbdOyND+NmYDH/mL1OSIEuLrcdZ5hrMH4pk83r40l...",
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6"
    "KeyPairSpec": "RSA_2048"
}
```
`PublicKey`、`PrivateKeyPlaintext`、`PrivateKeyCiphertextBlob` が base64 エンコード形式で返されます。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[データキーペア](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-key-pairs)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateDataKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/generate-data-key-pair.html)」を参照してください。

### `generate-data-key-without-plaintext`
<a name="kms_GenerateDataKeyWithoutPlaintext_cli_2_topic"></a>

次のコード例は、`generate-data-key-without-plaintext` を使用する方法を示しています。

**AWS CLI**  
**プレーンテキストキーを使用せずに 256 ビットの対称データキーを生成するには**  
次の `generate-data-key-without-plaintext` の例は、256 ビットの対称データキーの暗号化コピーを AWSの外部で使用するようにリクエストします。使用する準備ができたら、KMS AWS を呼び出してデータキーを復号化できます。  
256 ビットのデータキーをリクエストするには、値 `AES_256` を含む `key-spec` パラメータを使用します。128 ビットのデータキーをリクエストするには、値 `AES_128` を含む `key-spec` パラメータを使用します。その他のすべてのデータキー長には、`number-of-bytes` パラメーターを使用します。  
指定する KMS キーは、対称暗号化 KMS キー、つまりキースペック値が SYMMETRIC\$1DEFAULT の KMS キーである必要があります。  

```
aws kms generate-data-key-without-plaintext \
    --key-id "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" \
    --key-spec AES_256
```
出力:  

```
{
    "CiphertextBlob": "AQEDAHjRYf5WytIc0C857tFSnBaPn2F8DgfmThbJlGfR8P3WlwAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDEFogL",
    "KeyId": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6"
}
```
`CiphertextBlob` (暗号化されたデータキー) は base64 でエンコードされた形式で返されます。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[データキー](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#data-keys)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GenerateDataKeyWithoutPlaintext](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/generate-data-key-without-plaintext.html)」を参照してください。**

### `generate-data-key`
<a name="kms_GenerateDataKey_cli_2_topic"></a>

次のコード例は、`generate-data-key` を使用する方法を示しています。

**AWS CLI**  
**例 1: 256 ビットの対称データキーを生成するには**  
次の`generate-data-key`例では、 の外部で使用する 256 ビット対称データキーをリクエストします AWS。このコマンドは、すぐに使用および削除できるプレーンテキストのデータキーと、指定された KMS キーで暗号化されたデータキーのコピーを返します。暗号化されたデータとともに、暗号化されたデータキーを安全に保存できます。  
256 ビットのデータキーをリクエストするには、値 `AES_256` を含む `key-spec` パラメータを使用します。128 ビットのデータキーをリクエストするには、値 `AES_128` を含む `key-spec` パラメータを使用します。その他のすべてのデータキー長には、`number-of-bytes` パラメーターを使用します。  
指定する KMS キーは、対称暗号化 KMS キー、つまりキースペック値が SYMMETRIC\$1DEFAULT の KMS キーである必要があります。  

```
aws kms generate-data-key \
    --key-id alias/ExampleAlias \
    --key-spec AES_256
```
出力:  

```
{
    "Plaintext": "VdzKNHGzUAzJeRBVY+uUmofUGGiDzyB3+i9fVkh3piw=",
    "KeyId": "arn:aws:kms:us-east-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6",
    "CiphertextBlob": "AQEDAHjRYf5WytIc0C857tFSnBaPn2F8DgfmThbJlGfR8P3WlwAAAH4wfAYJKoZIhvcNAQcGoG8wbQIBADBoBgkqhkiG9w0BBwEwHgYJYIZIAWUDBAEuMBEEDEFogLqPWZconQhwHAIBEIA7d9AC7GeJJM34njQvg4Wf1d5sw0NIo1MrBqZa+YdhV8MrkBQPeac0ReRVNDt9qleAt+SHgIRF8P0H+7U="
}
```
`Plaintext` (プレーンテキストデータキー) と `CiphertextBlob` (暗号化データキー) は base64 でエンコードされた形式で返されます。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[データキー](https://docs.aws.amazon.com/kms/latest/developerguide/data-keys.html)」を参照してください。****例 2: 512 ビットの対称データキーを生成するには**  
次の `generate-data-key` の例は、暗号化と復号用の 512 ビットの対称データキーを要求します。このコマンドは、すぐに使用および削除できるプレーンテキストのデータキーと、指定された KMS キーで暗号化されたデータキーのコピーを返します。暗号化されたデータとともに、暗号化されたデータキーを安全に保存できます。  
128 ビットまたは 256 ビット以外のキー長をリクエストするには、`number-of-bytes` パラメーターを使用します。512 ビットのデータキーをリクエストするために、次の例では値が 64 (バイト) の `number-of-bytes` パラメータを使用します。  
指定する KMS キーは、対称暗号化 KMS キー、つまりキースペック値が SYMMETRIC\$1DEFAULT の KMS キーである必要があります。  
注: この例の出力の値は、表示のために一部が切り捨てられています。  

```
aws kms generate-data-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --number-of-bytes 64
```
出力:  

```
{
    "CiphertextBlob": "AQIBAHi6LtupRpdKl2aJTzkK6FbhOtQkMlQJJH3PdtHvS/y+hAEnX/QQNmMwDfg2korNMEc8AAACaDCCAmQGCSqGSIb3DQEHBqCCAlUwggJRAgEAMIICSgYJKoZ...",
    "Plaintext": "ty8Lr0Bk6OF07M2BWt6qbFdNB+G00ZLtf5MSEb4al3R2UKWGOp06njAwy2n72VRm2m7z/Pm9Wpbvttz6a4lSo9hgPvKhZ5y6RTm4OovEXiVfBveyX3DQxDzRSwbKDPk/...",
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6"
}
```
`Plaintext` (プレーンテキストデータキー) と `CiphertextBlob` (暗号化データキー) は base64 でエンコードされた形式で返されます。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[データキー](https://docs.aws.amazon.com/kms/latest/developerguide/data-keys.html)」を参照してください。**  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GenerateDataKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/generate-data-key.html)」を参照してください。

### `generate-mac`
<a name="kms_GenerateMac_cli_2_topic"></a>

次のコード例は、`generate-mac` を使用する方法を示しています。

**AWS CLI**  
**例 1: メッセージの HMAC を生成するには**  
次の `generate-mac` コマンドは、メッセージの HMAC、HMAC KMS キー、および MAC アルゴリズムを生成します。アルゴリズムは、指定された HMAC KMS キーでサポートされる必要があります。  
 AWS CLI v2 では、 `message`パラメータの値は Base64-encodedされている必要があります。または、メッセージをファイルに保存し、 `fileb://` プレフィックスを使用して、ファイルからバイナリデータを読み取るように AWS CLI に指示することもできます。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。キー ID は、キー用途が `GENERATE_VERIFY_MAC` の HMAC KMS キーを表す必要があります。  

```
msg=(echo 'Hello World' | base64)

aws kms generate-mac \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --message fileb://Message \
    --mac-algorithm HMAC_SHA_384
```
出力:  

```
{
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "Mac": "<HMAC_TAG>",
    "MacAlgorithm": "HMAC_SHA_384"
}
```
KMS での HMAC KMS AWS キーの使用の詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS での HMAC キー](https://docs.aws.amazon.com/kms/latest/developerguide/hmac.html)」を参照してください。 *AWS *  
**例 2: HMAC をファイルに保存するには (Linux および macOS)**  
次の `generate-mac` の例では、ローカルファイルに保存されている短いメッセージ向けの HMAC を生成します。コマンドはレスポンスから `Mac` プロパティも取得し、これを Base64 デコードして ExampleMac ファイルに保存します。この MAC ファイルを、MAC を検証する `verify-mac` コマンドで使用できます。  
`generate-mac` コマンドには、Base64 エンコードされたメッセージと、HMAC KMS キーがサポートする MAC アルゴリズムが必要です。KMS キーがサポートする MAC アルゴリズムを取得するには、`describe-key` コマンドを使用します。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。キー ID は、キー用途が GENERATE\$1VERIFY\$1MAC である非対称 KMS キーを表している必要があります。  

```
echo 'hello world' | base64 > EncodedMessage

aws kms generate-mac \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --message fileb://EncodedMessage \
    --mac-algorithm HMAC_SHA_384 \
    --output text \
    --query Mac | base64 --decode > ExampleMac
```
このコマンドでは何も出力されません。この例では、出力の `Mac` プロパティを抽出し、ファイルに保存します。  
KMS での HMAC KMS AWS キーの使用の詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS での HMAC キー](https://docs.aws.amazon.com/kms/latest/developerguide/hmac.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateMac](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/generate-mac.html)」を参照してください。

### `generate-random`
<a name="kms_GenerateRandom_cli_2_topic"></a>

次のコード例は、`generate-random` を使用する方法を示しています。

**AWS CLI**  
**例 1: 256 ビットのランダムバイト文字列を生成するには (Linux または macOs)**  
次の `generate-random` の例は、256 ビット (32 バイト) の base64 でエンコードされたランダムバイト文字列を生成します。この例は、バイト文字列をデコードしてランダムファイルに保存します。  
このコマンドを実行する際は、`number-of-bytes` パラメーターを使用してランダム値の長さをバイト単位で指定する必要があります。  
このコマンドを実行する際は、KMS キーは指定しません。ランダムバイト文字列は KMS キーとは関係ありません。  
デフォルトでは、 AWS KMS は乱数を生成します。ただし、[カスタムキーストア](https://docs.aws.amazon.com/kms/latest/developerguide/custom-key-store-overview.html)を指定すると、カスタムキーストアに関連付けられた AWS CloudHSM クラスターにランダムなバイト文字列が生成されます。  
この例は以下のパラメータと値を使用します。  
値 を持つ必須`--number-of-bytes`パラメータを使用して `32` 32 バイト (256 ビット) をリクエストします。string.It は の値 を持つ `--output`パラメータを使用して CLI AWS `text`に出力をテキストとして返すように指示します。JSON.It は を使用して response.It パイプ ( \$1 ) から `Plaintext` プロパティの値を`--query parameter`抽出し`base64`、抽出された output.It はリダイレクト演算子 ( > ) を使用してデコードされたバイト文字列を `ExampleRandom` file.It に保存します。  

```
aws kms generate-random \
    --number-of-bytes 32 \
    --output text \
    --query Plaintext | base64 --decode > ExampleRandom
```
このコマンドでは何も出力されません。  
詳細については、「AWS Key Management Service API リファレンス」の「[GenerateRandom](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateRandom.html)」を参照してください。**  
**例 2: 256 ビットの乱数を生成するには (Windows コマンドプロンプト)**  
次の例は、`generate-random` コマンドを使用して、base64 でエンコードされた 256 ビット (32 バイト) のランダムバイト文字列を生成します。この例は、バイト文字列をデコードしてランダムファイルに保存します。この例は前の例と同じですが、Windows の `certutil` のユーティリティを使用して、ランダムバイト文字列を base64 でデコードしてからファイルに保存する点が異なります。  
最初に base64 でエンコードされたランダムバイト文字列を生成し、テンポラリファイル (`ExampleRandom.base64`) に保存します。  

```
aws kms generate-random \
    --number-of-bytes 32 \
    --output text \
    --query Plaintext > ExampleRandom.base64
```
`generate-random` コマンドの出力はファイルに保存されるため、この例では何も出力されません。  
次に、`certutil -decode` コマンドを使用して、`ExampleRandom.base64` ファイル内の base64 でエンコードされたバイト文字列をデコードします。その後、デコードされたバイト文字列を `ExampleRandom` ファイルに保存します。  

```
certutil -decode ExampleRandom.base64 ExampleRandom
```
出力:  

```
Input Length = 18
Output Length = 12
CertUtil: -decode command completed successfully.
```
詳細については、「AWS Key Management Service API リファレンス」の「[GenerateRandom](https://docs.aws.amazon.com/kms/latest/APIReference/API_GenerateRandom.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GenerateRandom](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/generate-random.html)」を参照してください。**

### `get-key-policy`
<a name="kms_GetKeyPolicy_cli_2_topic"></a>

次のコード例は、`get-key-policy` を使用する方法を示しています。

**AWS CLI**  
**ある KMS キーから別の KMS キーにキーポリシーをコピーするには**  
次の `get-key-policy` の例は、ある KMS キーからキーポリシーを取得し、テキストファイルに保存します。その後、テキストファイルをポリシー入力として使用して、別の KMS キーのポリシーを置き換えます。  
`put-key-policy` の `--policy` パラメータには文字列が必要なため、JSON ではなくテキスト文字列として出力を返す `--output text` オプションを使用する必要があります。  

```
aws kms get-key-policy \
    --policy-name default \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --query Policy \
    --output text > policy.txt

aws kms put-key-policy \
    --policy-name default \
    --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \
    --policy file://policy.txt
```
このコマンドは何も出力しません。  
詳細については、「AWS KMS API リファレンス」の「[PutKeyPolicy](https://docs.aws.amazon.com/kms/latest/APIReference/API_PutKeyPolicy.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetKeyPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/get-key-policy.html)」を参照してください。**

### `get-key-rotation-status`
<a name="kms_GetKeyRotationStatus_cli_2_topic"></a>

次のコード例は、`get-key-rotation-status` を使用する方法を示しています。

**AWS CLI**  
**KMS キーのローテーションステータスを取得するには**  
次の `get-key-rotation-status` の例では、自動ローテーションが有効になっているかどうか、ローテーション期間、次にスケジュールされているローテーション日など、指定された KMS キーのローテーションステータスに関する情報を返します。このコマンドは、カスタマーマネージド KMS キーと AWS マネージド KMS キーで使用できます。ただし、すべての AWS マネージド KMS キーは毎年自動的にローテーションされます。  

```
aws kms get-key-rotation-status \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyRotationEnabled": true,
    "NextRotationDate": "2024-02-14T18:14:33.587000+00:00",
    "RotationPeriodInDays": 365
}
```
詳細については、「*AWS Key Management Service Developer Guide*」の「[Rotating keys](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetKeyRotationStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/get-key-rotation-status.html)」を参照してください。

### `get-parameters-for-import`
<a name="kms_GetParametersForImport_cli_2_topic"></a>

次のコード例は、`get-parameters-for-import` を使用する方法を示しています。

**AWS CLI**  
**キーマテリアルを KMS キーにインポートするために必要な項目を取得するには**  
次の `get-parameters-for-import` の例では、キーマテリアルを KMS キーにインポートするために必要なパブリックキーとインポートトークンを取得します。`import-key-material` コマンドを使用する際には、同じ `get-parameters-for-import` コマンドで返されたパブリックキーによって暗号化されたインポートトークンとキーマテリアルを必ず使用してください。また、このコマンドで指定するラップアルゴリズムは、キーマテリアルをパブリックキーで暗号化するために使用するアルゴリズムである必要があります。  
KMS キーを指定するには、`key-id` パラメータを使用します。この例ではキー ID を使用していますが、このコマンドでは、キー ID またはキー ARN を使用できます。  

```
aws kms get-parameters-for-import \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --wrapping-algorithm RSAES_OAEP_SHA_256 \
    --wrapping-key-spec RSA_2048
```
出力:  

```
{
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "PublicKey": "<public key base64 encoded data>",
    "ImportToken": "<import token base64 encoded data>",
    "ParametersValidTo": 1593893322.32
}
```
詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[パブリックキーおよびインポートトークンのダウンロード](https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys-get-public-key-and-token.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParametersForImport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/get-parameters-for-import.html)」を参照してください。

### `get-public-key`
<a name="kms_GetPublicKey_cli_2_topic"></a>

次のコード例は、`get-public-key` を使用する方法を示しています。

**AWS CLI**  
**例 1: 非対称 KMS キーのパブリックキーをダウンロードするには**  
次の `get-public-key` の例では、非対称 KMS キーのパブリックキーをダウンロードします。  
パブリックキーを返すだけでなく、出力には、キーの使用やサポートされている暗号化アルゴリズムなど、KMS AWS の外部でパブリックキーを安全に使用するために必要な情報が含まれます。  

```
aws kms get-public-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "PublicKey": "jANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAl5epvg1/QtJhxSi2g9SDEVg8QV/...",
    "CustomerMasterKeySpec": "RSA_4096",
    "KeyUsage": "ENCRYPT_DECRYPT",
    "EncryptionAlgorithms": [
        "RSAES_OAEP_SHA_1",
        "RSAES_OAEP_SHA_256"
    ]
}
```
KMS で非対称 KMS AWS キーを使用する方法の詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS ***例 2: パブリックキーを DER 形式に変換するには (Linux および macOS)**  
次の `get-public-key` の例では、非対称 KMS キーのパブリックキーをダウンロードして DER ファイルに保存します。  
 AWS CLI で `get-public-key` コマンドを使用すると、Base64-encodedされた X.509 パブリックキーが返されます。この例では、`PublicKey` プロパティの値をテキストとして取得します。この `PublicKey` を Base64 でエンコードして `public_key.der` ファイルに保存します。`output` パラメータは、JSON ではなくテキストとして出力を返します。`--query` パラメータは `PublicKey`プロパティのみを取得し、KMS AWS の外部でパブリックキーを安全に使用するために必要なプロパティは取得しません。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。  

```
aws kms get-public-key \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --output text \
    --query PublicKey | base64 --decode > public_key.der
```
このコマンドでは何も出力されません。  
KMS で非対称 KMS AWS キーを使用する方法の詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/get-public-key.html)」を参照してください。

### `import-key-material`
<a name="kms_ImportKeyMaterial_cli_2_topic"></a>

次のコード例は、`import-key-material` を使用する方法を示しています。

**AWS CLI**  
**キーマテリアルを KMS キーにインポートするには**  
次の `import-key-material` の例では、キーマテリアルなしで作成された KMS キーにキーマテリアルをアップロードします。KMS キーのキーストアは `PendingImport` である必要があります。  
このコマンドは、`get-parameters-for-import` コマンドが返したパブリックキーで暗号化したキーマテリアルを使用します。また、同じ `get-parameters-for-import` コマンドからのインポートトークンも使用します。  
`expiration-model` パラメータは、キーマテリアルが `valid-to` パラメータで指定された日時に自動的に期限切れになることを示します。キーマテリアルの有効期限が切れると、 AWS KMS はキーマテリアルを削除`Pending import`し、KMS キーのキー状態は に変わり、KMS キーは使用できなくなります。KMS キーを復元するには、同じキーマテリアルを再インポートする必要があります。別のキーマテリアルを使用するには、新しい KMS キーを作成する必要があります。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID またはキー ARN に置き換えます。  

```
aws kms import-key-material \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --encrypted-key-material fileb://EncryptedKeyMaterial.bin \
    --import-token fileb://ImportToken.bin \
    --expiration-model KEY_MATERIAL_EXPIRES \
    --valid-to 2021-09-21T19:00:00Z
```
出力:  

```
{
    "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
    "KeyMaterialId": "0b7fd7ddbac6eef27907413567cad8c810e2883dc8a7534067a82ee1142fc1e6"
}
```
AWS KMS へのキーマテリアルのインポートの詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[キーマテリアルのインポート](https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportKeyMaterial](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/import-key-material.html)」を参照してください。

### `list-aliases`
<a name="kms_ListAliases_cli_2_topic"></a>

次の例は、`list-aliases` を使用する方法を説明しています。

**AWS CLI**  
**例 1: AWS アカウントとリージョン内のすべてのエイリアスを一覧表示するには**  
次の例では、 `list-aliases` コマンドを使用して、 AWS アカウントのデフォルトリージョン内のすべてのエイリアスを一覧表示します。出力には、 AWS マネージド KMS キーとカスタマーマネージド KMS キーに関連付けられたエイリアスが含まれます。  

```
aws kms list-aliases
```
出力:  

```
{
    "Aliases": [
        {
            "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/testKey",
            "AliasName": "alias/testKey",
            "TargetKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab"
        },
        {
            "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/FinanceDept",
            "AliasName": "alias/FinanceDept",
            "TargetKeyId": "0987dcba-09fe-87dc-65ba-ab0987654321"
        },
        {
            "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/aws/dynamodb",
            "AliasName": "alias/aws/dynamodb",
            "TargetKeyId": "1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d"
        },
        {
            "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/aws/ebs",
            "AliasName": "alias/aws/ebs",
            "TargetKeyId": "0987ab65-43cd-21ef-09ab-87654321cdef"
        },
        ...
    ]
}
```
**例 2: 特定の KMS キーのすべてのエイリアスを一覧表示するには**  
次の例では、`list-aliases` コマンドとその `key-id` パラメータを使用して、特定の KMS キーに関連するすべてのエイリアスを一覧表示します。  
各エイリアスは 1 つの KMS のみに関連付けられますが、1 つの KMS キーには複数のエイリアスを設定することができます。このコマンドは、KMS AWS コンソールに KMS キーごとに 1 つのエイリアスしか一覧表示されないため、非常に便利です。KMS キーのすべてのエイリアスを検索するには、`list-aliases` コマンドを使用する必要があります。  
この例では、KMS キーのキー ID を `--key-id` パラメータに使用しますが、キー ID、キー ARN、エイリアス名、またはエイリアス ARN を使用することもできます。  

```
aws kms list-aliases --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "Aliases": [
        {
            "TargetKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
            "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/oregon-test-key",
            "AliasName": "alias/oregon-test-key"
        },
        {
            "TargetKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
            "AliasArn": "arn:aws:kms:us-west-2:111122223333:alias/project121-test",
            "AliasName": "alias/project121-test"
        }
    ]
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[エイリアスの使用](https://docs.aws.amazon.com/kms/latest/developerguide/programming-aliases.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListAliases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/list-aliases.html)」を参照してください。**

### `list-grants`
<a name="kms_ListGrants_cli_2_topic"></a>

次の例は、`list-grants` を使用する方法を説明しています。

**AWS CLI**  
**KMS AWS キーの許可を表示するには**  
次の の`list-grants`例では、アカウントの Amazon DynamoDB の指定された AWS マネージド KMS キーに対するすべての許可を表示します。この権限により、DynamoDB はユーザーに代わって KMS キーを使用して、DynamoDB テーブルをディスクに書き込む前に暗号化できます。このようなコマンドを使用して、 AWS アカウントとリージョンの AWS マネージド KMS キーとカスタマーマネージド KMS キーの許可を表示できます。  
このコマンドは、キー ID を含む `key-id` パラメータを使用して KMS キーを識別します。ユーザーは、キー ID またはキー ARN を使用して KMS キーを識別できます。 AWS マネージド KMS キーのキー ID またはキー ARN を取得するには、 `list-keys`または `list-aliases` コマンドを使用します。  

```
aws kms list-grants \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
これにより、暗号化操作において Amazon DynamoDB に KMS キーを使用する権限が付与され、KMS キーに関する詳細情報を表示する権限 (`DescribeKey`) と権限を廃止する権限 (`RetireGrant`) が付与されていることが出力に表示されます。`EncryptionContextSubset` の制約により、これらの権限は指定された暗号化コンテキストペアを含むリクエストに限定されます。そのため、この権限のアクセス許可は指定されたアカウントと DynamoDB テーブルでのみ有効です。  

```
{
    "Grants": [
        {
            "Constraints": {
                "EncryptionContextSubset": {
                    "aws:dynamodb:subscriberId": "123456789012",
                    "aws:dynamodb:tableName": "Services"
                }
            },
            "IssuingAccount": "arn:aws:iam::123456789012:root",
            "Name": "8276b9a6-6cf0-46f1-b2f0-7993a7f8c89a",
            "Operations": [
                "Decrypt",
                "Encrypt",
                "GenerateDataKey",
                "ReEncryptFrom",
                "ReEncryptTo",
                "RetireGrant",
                "DescribeKey"
            ],
            "GrantId": "1667b97d27cf748cf05b487217dd4179526c949d14fb3903858e25193253fe59",
            "KeyId": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab",
            "RetiringPrincipal": "dynamodb.us-west-2.amazonaws.com",
            "GranteePrincipal": "dynamodb.us-west-2.amazonaws.com",
            "CreationDate": "2021-05-13T18:32:45.144000+00:00"
        }
    ]
}
```
詳細については、*AWS 「 Key Management Service デベロッパーガイド*」の[「KMS AWS でのグラン](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html)ト」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListGrants](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/list-grants.html)」を参照してください。**

### `list-key-policies`
<a name="kms_ListKeyPolicies_cli_2_topic"></a>

次のコード例は、`list-key-policies` を使用する方法を示しています。

**AWS CLI**  
**KMS キーのキーポリシーの名前を取得するには**  
次の `list-key-policies` の例は、サンプルアカウントとリージョンのカスタマーマネージドキーのキーポリシーの名前を取得します。このコマンドを使用して、 AWS マネージドキーとカスタマーマネージドキーのキーポリシーの名前を検索できます。  
有効なキーポリシー名は `default` のみであるため、このコマンドは有用ではありません。  
KMS キーを指定するには、`key-id` パラメータを使用します。この例では、キー ID 値を使用していますが、このコマンドでは、キー ID またはキー ARN を使用できます。  

```
aws kms list-key-policies \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "PolicyNames": [
    "default"
    ]
}
```
KMS キーポリシーの詳細については、 AWS 「 Key Management Service デベロッパーガイド」の[「KMS AWS でのキーポリシー](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)の使用」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListKeyPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/list-key-policies.html)」を参照してください。**

### `list-key-rotations`
<a name="kms_ListKeyRotations_cli_2_topic"></a>

次のコード例は、`list-key-rotations` を使用する方法を示しています。

**AWS CLI**  
**完了したすべてのキーマテリアルローテーションに関する情報を取得するには**  
次の `list-key-rotations` の例では、指定された KMS キーに対して完了したすべてのキーマテリアルローテーションに関する情報を一覧表示します。  

```
aws kms list-key-rotations \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "Rotations": [
        {
            "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
            "RotationDate": "2024-03-02T10:11:36.564000+00:00",
            "RotationType": "AUTOMATIC"
        },
        {
            "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab",
            "RotationDate": "2024-04-05T15:14:47.757000+00:00",
            "RotationType": "ON_DEMAND"
        }
    ],
    "Truncated": false
}
```
詳細については、「*AWS Key Management Service Developer Guide*」の「[Rotating keys](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListKeyRotations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/list-key-rotations.html)」を参照してください。

### `list-keys`
<a name="kms_ListKeys_cli_2_topic"></a>

次のコード例は、`list-keys` を使用する方法を示しています。

**AWS CLI**  
**アカウントとリージョンの KMS キーを取得するには**  
次の `list-keys` の例は、アカウントとリージョンの KMS キーを取得します。このコマンドは、 AWS マネージドキーとカスタマーマネージドキーの両方を返します。  

```
aws kms list-keys
```
出力:  

```
{
    "Keys": [
        {
            "KeyArn": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
            "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab"
        },
        {
            "KeyArn": "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321",
            "KeyId": "0987dcba-09fe-87dc-65ba-ab0987654321"
        },
        {
            "KeyArn": "arn:aws:kms:us-east-2:111122223333:key/1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d",
            "KeyId": "1a2b3c4d-5e6f-1a2b-3c4d-5e6f1a2b3c4d"
        }
    ]
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[キーの表示](https://docs.aws.amazon.com/kms/latest/developerguide/viewing-keys.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/list-keys.html)」を参照してください。**

### `list-resource-tags`
<a name="kms_ListResourceTags_cli_2_topic"></a>

次のコード例は、`list-resource-tags` を使用する方法を示しています。

**AWS CLI**  
**KMS キーのタグを取得するには**  
次の `list-resource-tags` の例では、KMS キーのタグを取得します。KMS キーのリソースタグを追加または置換するには、`tag-resource` コマンドを使用します。出力は、この KMS キーに 2 つのリソースタグがあり、それぞれにキーと値があることを示しています。  
KMS キーを指定するには、`key-id` パラメータを使用します。この例では、キー ID 値を使用していますが、このコマンドでは、キー ID またはキー ARN を使用できます。  

```
aws kms list-resource-tags \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "Tags": [
    {
        "TagKey": "Dept",
        "TagValue": "IT"
    },
    {
        "TagKey": "Purpose",
        "TagValue": "Test"
    }
    ],
    "Truncated": false
}
```
KMS でのタグの使用の詳細については、「 Key Management Service AWS デベロッパーガイド[」の「キーのタグ付け](https://docs.aws.amazon.com/kms/latest/developerguide/tagging-keys.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/list-resource-tags.html)」を参照してください。

### `list-retirable-grants`
<a name="kms_ListRetirableGrants_cli_2_topic"></a>

次のコード例は、`list-retirable-grants` を使用する方法を示しています。

**AWS CLI**  
**プリンシパルが廃止できる許可を表示するには**  
次の の`list-retirable-grants`例では、`ExampleAdmin`ユーザーが AWS アカウントとリージョンの KMS キーで廃止できるすべての許可を表示します。このようなコマンドを使用して、アカウントプリンシパルがアカウント AWS とリージョンの KMS キーで廃止できる許可を表示できます。  
必須の `retiring-principal` パラメータの値は、アカウント、ユーザー、またはロールの Amazon リソースネーム (ARN) である必要があります。  
このコマンドで `retiring-principal` の値としてサービスを指定することはできません。ただし、サービスが廃止プリンシパルである場合があります。特定のサービスが廃止プリンシパルである許可を見つけるには、`list-grants` コマンドを使用します。  
出力は、`ExampleAdmin` ユーザーがアカウントとリージョン内の 2 つの異なる KMS キーに対する許可を廃止するアクセス許可を持っていることを示しています。廃止プリンシパルに加えて、アカウントには、アカウント内の許可を廃止するアクセス許可があります。  

```
aws kms list-retirable-grants \
    --retiring-principal arn:aws:iam::111122223333:user/ExampleAdmin
```
出力:  

```
{
    "Grants": [
        {
            "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
            "GrantId": "156b69c63cb154aa21f59929ff19760717be8d9d82b99df53e18b94a15a5e88e",
            "Name": "",
            "CreationDate": 2021-01-14T20:17:36.419000+00:00,
            "GranteePrincipal": "arn:aws:iam::111122223333:user/ExampleUser",
            "RetiringPrincipal": "arn:aws:iam::111122223333:user/ExampleAdmin",
            "IssuingAccount": "arn:aws:iam::111122223333:root",
            "Operations": [
                "Encrypt"
            ],
            "Constraints": {
                "EncryptionContextSubset": {
                    "Department": "IT"
                }
            }
        },
        {
            "KeyId": "arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321",
            "GrantId": "8c94d1f12f5e69f440bae30eaec9570bb1fb7358824f9ddfa1aa5a0dab1a59b2",
            "Name": "",
            "CreationDate": "2021-02-02T19:49:49.638000+00:00",
            "GranteePrincipal": "arn:aws:iam::111122223333:role/ExampleRole",
            "RetiringPrincipal": "arn:aws:iam::111122223333:user/ExampleAdmin",
            "IssuingAccount": "arn:aws:iam::111122223333:root",
            "Operations": [
                "Decrypt"
            ],
            "Constraints": {
                "EncryptionContextSubset": {
                    "Department": "IT"
                }
            }
        }
    ],
    "Truncated": false
}
```
詳細については、*AWS 「 Key Management Service デベロッパーガイド*」の[「KMS AWS でのグラン](https://docs.aws.amazon.com/kms/latest/developerguide/grants.html)ト」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRetirableGrants](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/list-retirable-grants.html)」を参照してください。

### `put-key-policy`
<a name="kms_PutKeyPolicy_cli_2_topic"></a>

次のコード例は、`put-key-policy` を使用する方法を示しています。

**AWS CLI**  
**KMS キーのキーポリシーを変更するには**  
次の `put-key-policy` の例は、カスタマーマネージドキーのキーポリシーを変更します。  
まず、キーポリシーを作成して、ローカルの JSON ファイルに保存します。この例では、`key_policy.json` がこのファイルです。また、キーポリシーを `policy` パラメータの文字列値として指定することもできます。  
このキーポリシーの最初のステートメントは、IAM ポリシーを使用して KMS キーへのアクセスを制御するアクセス許可を AWS アカウントに付与します。2 番目のステートメントは、KMS キーで `describe-key` コマンドおよび `list-keys` コマンドを実行する権限を `test-user` ユーザーに付与します。  
`key_policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Id" : "key-default-1",
    "Statement" : [
        {
            "Sid" : "Enable IAM User Permissions",
            "Effect" : "Allow",
            "Principal" : {
                "AWS" : "arn:aws:iam::111122223333:root"
            },
            "Action" : "kms:*",
            "Resource" : "*"
        },
        {
            "Sid" : "Allow Use of Key",
            "Effect" : "Allow",
            "Principal" : {
                "AWS" : "arn:aws:iam::111122223333:user/test-user"
            },
            "Action" : [
                "kms:DescribeKey",
                "kms:ListKeys"
            ],
            "Resource" : "*"
        }
    ]
}
```
この例では KMS キーの識別にキー ID を使用しますが、キー ARN を使用することもできます。キーポリシーを指定するために、このコマンドは `policy` パラメータを使用します。ポリシーがファイル内にあることを示すには、必要な `file://` プレフィックスを使用します。このプレフィックスは、サポートされているすべてのオペレーティングシステムでファイルを識別するために必要です。最後に、コマンドは値が `default` の `policy-name` パラメーターを使用します。ポリシー名を指定しない場合、デフォルト値は `default` となります。唯一の有効な値は `default` です。  

```
aws kms put-key-policy \
    --policy-name default \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --policy file://key_policy.json
```
このコマンドでは、出力が生成されません。コマンドが有効であることを確認するには、`get-key-policy` コマンドを使用します。次のコマンド例は、同じ KMS キーのキーポリシーを取得します。値が `text` の `output` パラメータは、読みやすいテキスト形式を返します。  

```
aws kms get-key-policy \
    --policy-name default \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --output text
```
出力:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Id" : "key-default-1",
    "Statement" : [
        {
            "Sid" : "Enable IAM User Permissions",
            "Effect" : "Allow",
            "Principal" : {
                "AWS" : "arn:aws:iam::111122223333:root"
            },
            "Action" : "kms:*",
            "Resource" : "*"
            },
            {
            "Sid" : "Allow Use of Key",
            "Effect" : "Allow",
            "Principal" : {
                "AWS" : "arn:aws:iam::111122223333:user/test-user"
            },
            "Action" : [ "kms:Describe", "kms:List" ],
            "Resource" : "*"
        }
    ]
}
```
詳細については、「AWS Key Management Service デベロッパーガイド」の「[キーポリシーの変更](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutKeyPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/put-key-policy.html)」を参照してください。**

### `re-encrypt`
<a name="kms_ReEncrypt_cli_2_topic"></a>

次のコード例は、`re-encrypt` を使用する方法を示しています。

**AWS CLI**  
**例 1: 異なる対称 KMS キーで暗号化されたメッセージを再暗号化するには (Linux と macOS)**  
次の`re-encrypt`コマンド例は、 CLI AWS でデータを再暗号化するための推奨方法を示しています。  
ファイルに暗号文を指定します。`--ciphertext-blob` パラメータの値には、バイナリファイルからデータを読み取るように CLI に指示する `fileb://` プレフィックスを使用します。ファイルが現在のディレクトリにない場合は、ファイルへのフルパスを入力します。ファイルから AWS CLI パラメータ値を読み取る方法の詳細については、*AWS 「 コマンドラインインターフェイスユーザーガイド*[AWS 」の「ファイルからの CLI パラメータのロード](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html)」および*AWS 「 コマンドラインツールブログ*」の[「ローカルファイルパラメータのベストプラクティス](https://aws.amazon.com/blogs/developer/best-practices-for-local-file-parameters/)」を参照してください。暗号化テキストを復号するソース KMS キーを指定します。対称暗号化 KMS キーで復号する場合、 `--source-key-id` パラメータは必要ありません。 AWS KMS は、暗号化テキスト BLOB のメタデータからデータを暗号化するために使用された KMS キーを取得できます。ただし、ベストプラクティスは常に、使用している KMS キーを指定することです。この方法により、意図した KMS キーを使用することができ、信頼できない KMS キーを使用して誤って暗号文を復号するのを防ぐことができます。送信先の KMS キーを指定して、データを再暗号化します。`--destination-key-id` パラメータは常に必須です。この例ではキー ARN を使用していますが、有効である限り任意のキー識別子を使用できます。プレーンテキストの出力をテキスト値としてリクエストします。`--query` パラメータは、出力から `Plaintext` フィールドの値のみを取得するよう CLI に命令します。`--output` パラメータは出力を text.Base64 でデコードしたプレーンテキストとして返し、ファイルに保存します。次の例では、`Plaintext` パラメータの値を Base64 ユーティリティにパイプ (\$1) して、Base64 ユーティリティでデコードします。次に、デコードされた出力を `ExamplePlaintext` ファイルにリダイレクト (>) します。  
このコマンドを実行する前に、サンプルキー IDsを AWS アカウントの有効なキー識別子に置き換えます。  

```
aws kms re-encrypt \
    --ciphertext-blob fileb://ExampleEncryptedFile \
    --source-key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --destination-key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \
    --query CiphertextBlob \
    --output text | base64 --decode > ExampleReEncryptedFile
```
このコマンドでは何も出力されません。`re-encrypt` コマンドからの出力は base64 でデコードされ、ファイルに保存されます。  
詳細については、「*AWS Key Management Service API リファレンス*」の「[ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html)」を参照してください。  
**例 2: 異なる対称 KMS キーで暗号化されたメッセージを再暗号化するには (Windows コマンドプロンプト)**  
次の `re-encrypt` の例は、`certutil` ユーティリティを使用してプレーンテキストデータを Base64 でデコードする点を除いて、前の例と同じです。この手順には、次の例に示すように 2 つのコマンドが必要です。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。  

```
aws kms re-encrypt ^
    --ciphertext-blob fileb://ExampleEncryptedFile ^
    --source-key-id 1234abcd-12ab-34cd-56ef-1234567890ab ^
    --destination-key-id 0987dcba-09fe-87dc-65ba-ab0987654321 ^
    --query CiphertextBlob ^
    --output text > ExampleReEncryptedFile.base64
```
その後、`certutil` ユーティリティーを使用します。  

```
certutil -decode ExamplePlaintextFile.base64 ExamplePlaintextFile
```
出力:  

```
Input Length = 18
Output Length = 12
CertUtil: -decode command completed successfully.
```
詳細については、「*AWS Key Management Service API リファレンス*」の「[ReEncrypt](https://docs.aws.amazon.com/kms/latest/APIReference/API_ReEncrypt.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ReEncrypt](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/re-encrypt.html)」を参照してください。**

### `retire-grant`
<a name="kms_RetireGrant_cli_2_topic"></a>

次のコード例は、`retire-grant` を使用する方法を示しています。

**AWS CLI**  
**カスタマーマスターキーの権限を廃止するには**  
次の `retire-grant` の例は、KMS キーから権限を削除します。  
次のコマンド例は、`grant-id` パラメータと `key-id` パラメータを指定します。`key-id` パラメータの値は、KMS キーのキー ARN である必要があります。  

```
aws kms retire-grant \
    --grant-id 1234a2345b8a4e350500d432bccf8ecd6506710e1391880c4f7f7140160c9af3 \
    --key-id arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab
```
このコマンドは何も出力しません。権限が廃止されたことを確認するには、`list-grants` コマンドを使用します。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[グラントの使用停止と取り消し](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#grant-delete)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[RetireGrant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/retire-grant.html)」を参照してください。**

### `revoke-grant`
<a name="kms_RevokeGrant_cli_2_topic"></a>

次のコード例は、`revoke-grant` を使用する方法を示しています。

**AWS CLI**  
**カスタマーマスターキーの権限を取り消すには**  
次の `revoke-grant` の例は、KMS キーから権限を削除します。次のコマンド例は、`grant-id` パラメータと `key-id` パラメータを指定します。`key-id` パラメータの値には、KMS キーのキー ID またはキー ARN を使用できます。  

```
aws kms revoke-grant \
    --grant-id 1234a2345b8a4e350500d432bccf8ecd6506710e1391880c4f7f7140160c9af3 \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
このコマンドは何も出力しません。権限が取り消されたことを確認するには、`list-grants` コマンドを使用します。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[グラントの使用停止と取り消し](https://docs.aws.amazon.com/kms/latest/developerguide/grant-manage.html#grant-delete)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[RevokeGrant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/revoke-grant.html)」を参照してください。**

### `rotate-key-on-demand`
<a name="kms_RotateKeyOnDemand_cli_2_topic"></a>

次のコード例は、`rotate-key-on-demand` を使用する方法を示しています。

**AWS CLI**  
**KMS キーのオンデマンドローテーションを実行するには**  
次の `rotate-key-on-demand` の例では、指定された KMS キーのキーマテリアルのローテーションをすぐに開始します。  

```
aws kms rotate-key-on-demand \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
出力:  

```
{
    "KeyId": "1234abcd-12ab-34cd-56ef-1234567890ab"
}
```
詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[How to perform on-demand key rotation](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html#rotating-keys-on-demand)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RotateKeyOnDemand](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/rotate-key-on-demand.html)」を参照してください。

### `schedule-key-deletion`
<a name="kms_ScheduleKeyDeletion_cli_2_topic"></a>

次のコード例は、`schedule-key-deletion` を使用する方法を示しています。

**AWS CLI**  
**カスタマーマネージド KMS キーの削除をスケジュールするには**  
次の `schedule-key-deletion` の例は、指定されたカスタマーマネージド KMS キーを 15 日後に削除するようにスケジュールします。  
`--key-id` パラメータは KMS キーを識別します。この例では、キーの ARN 値を使用していますが、キー ID または KMS キー ARN のいずれかを使用できます。`--pending-window-in-days` パラメータは 7 ～ 30 日の待機期間の長さを指定します。デフォルトでは、待機時間は 30 日です。この例では、値として 15 を指定し、コマンドの完了から 15 日後に AWS に KMS キーを完全に削除するように指示します。  

```
aws kms schedule-key-deletion \
    --key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \
    --pending-window-in-days 15
```
レスポンスには、キー ARN、キーの状態、待機期間 (`PendingWindowInDays`)、および UNIX 時間の削除日が含まれます。削除日を現地時間で表示するには、KMS AWS コンソールを使用します。`PendingDeletion` キー状態の KMS キーを暗号化処理で使用することはできません。  

```
{
    "KeyId": "arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "DeletionDate": "2022-06-18T23:43:51.272000+00:00",
    "KeyState": "PendingDeletion",
    "PendingWindowInDays": 15
}
```
詳細については、「**AWS Key Management Service デベロッパーガイド」の「[Deleting keys](https://docs.aws.amazon.com/kms/latest/developerguide/deleting-keys.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ScheduleKeyDeletion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/schedule-key-deletion.html)」を参照してください。**

### `sign`
<a name="kms_Sign_cli_2_topic"></a>

次のコード例は、`sign` を使用する方法を示しています。

**AWS CLI**  
**例 1: メッセージ向けデジタル署名を生成するには**  
次の `sign` 例では、短いメッセージ向けの暗号化署名を生成します。コマンドの出力には、`verify` コマンドを使用して検証できる、Base64 エンコードされた `Signature` フィールドが含まれています。  
署名するメッセージと、非対称 KMS キーがサポートする署名アルゴリズムを指定する必要があります。KMS キー向け署名アルゴリズムを取得するには、`describe-key` コマンドを使用します。  
 AWS CLI v2 では、 `message`パラメータの値は Base64-encodedされている必要があります。または、メッセージをファイルに保存し、 `fileb://` プレフィックスを使用して、ファイルからバイナリデータを読み取るように AWS CLI に指示することもできます。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。キー ID は、キー用途が SIGN\$1VERIFY である非対称 KMS キーを表している必要があります。  

```
msg=(echo 'Hello World' | base64)

aws kms sign \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --message fileb://UnsignedMessage \
    --message-type RAW \
    --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256
```
出力:  

```
{
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "Signature": "ABCDEFhpyVYyTxbafE74ccSvEJLJr3zuoV1Hfymz4qv+/fxmxNLA7SE1SiF8lHw80fKZZ3bJ...",
    "SigningAlgorithm": "RSASSA_PKCS1_V1_5_SHA_256"
}
```
KMS で非対称 KMS AWS キーを使用する方法の詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
**例 2: デジタル署名をファイルに保存するには (Linux および macOs)**  
次の `sign` 例では、ローカルファイルに保存されている短いメッセージ向けの暗号化署名を生成します。コマンドはレスポンスから `Signature` プロパティも取得し、これを Base64 デコードして ExampleSignature ファイルに保存します。この署名ファイルを、署名検証用の `verify` コマンドで使用できます。  
`sign` コマンドには、Base64 エンコードされたメッセージと、非対称 KMS キーがサポートする署名アルゴリズムが必要です。KMS キーがサポートする署名アルゴリズムを取得するには、`describe-key` コマンドを使用します。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。キー ID は、キー用途が SIGN\$1VERIFY である非対称 KMS キーを表している必要があります。  

```
echo 'hello world' | base64 > EncodedMessage

aws kms sign \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --message fileb://EncodedMessage \
    --message-type RAW \
    --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256 \
    --output text \
    --query Signature | base64 --decode > ExampleSignature
```
このコマンドは何も出力しません。この例では、出力の `Signature` プロパティを抽出し、ファイルに保存します。  
KMS で非対称 KMS AWS キーを使用する方法の詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS の非対称](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)キー」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Sign](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/sign.html)」を参照してください。

### `tag-resource`
<a name="kms_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**KMS キーにタグを追加するには**  
次の `tag-resource` 例では、カスタマーマネージド KMS キーに `"Purpose":"Test"` タグと `"Dept":"IT"` タグを追加します。これらのタグを使用して KMS キーにラベルを付け、アクセス許可用と監査用の KMS キーカテゴリを作成できます。  
KMS キーを指定するには、`key-id` パラメータを使用します。この例では、キー ID 値を使用していますが、このコマンドでは、キー ID またはキー ARN を使用できます。  

```
aws kms tag-resource \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --tags TagKey='Purpose',TagValue='Test' TagKey='Dept',TagValue='IT'
```
このコマンドでは何も出力されません。KMS KMS AWS キーのタグを表示するには、 `list-resource-tags` コマンドを使用します。  
KMS でのタグの使用の詳細については、「 Key Management Service AWS デベロッパーガイド[」の「キーのタグ付け](https://docs.aws.amazon.com/kms/latest/developerguide/tagging-keys.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="kms_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**KMS キーからタグを削除するには**  
次の `untag-resource` の例では、カスタマーマネージド KMS キーから `"Purpose"` キーを持つタグを削除します。  
KMS キーを指定するには、`key-id` パラメータを使用します。この例では、キー ID 値を使用していますが、このコマンドでは、キー ID またはキー ARN を使用できます。このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。  

```
aws kms untag-resource \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --tag-key 'Purpose'
```
このコマンドでは何も出力されません。KMS KMS AWS キーのタグを表示するには、 `list-resource-tags` コマンドを使用します。  
KMS でのタグの使用の詳細については、「 Key Management Service AWS デベロッパーガイド[」の「キーのタグ付け](https://docs.aws.amazon.com/kms/latest/developerguide/tagging-keys.html)」を参照してください。 *AWS *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/untag-resource.html)」を参照してください。

### `update-alias`
<a name="kms_UpdateAlias_cli_2_topic"></a>

次のコード例は、`update-alias` を使用する方法を示しています。

**AWS CLI**  
**エイリアスを別の KMS キーに関連付けるには**  
次の `update-alias` の例は、エイリアス `alias/test-key` を別の KMS キーに関連付けます。  
`--alias-name` パラメータはエイリアス名を指定します。エイリアス名の値は `alias/` で始まる必要があります。`--target-key-id` パラメータは、エイリアスに関連付ける KMS キーを指定します。エイリアスの現在の KMS キーを指定する必要はありません。  

```
aws kms update-alias \
    --alias-name alias/test-key \
    --target-key-id 1234abcd-12ab-34cd-56ef-1234567890ab
```
このコマンドは何も出力しません。エイリアスを見つけるには、`list-aliases` コマンドを使用します。  
詳細については、「AWS Key Management Service デベロッパーガイド」の「[エイリアスの更新](https://docs.aws.amazon.com/kms/latest/developerguide/alias-manage.html#alias-update)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/update-alias.html)」を参照してください。**

### `update-custom-key-store`
<a name="kms_UpdateCustomKeyStore_cli_2_topic"></a>

次のコード例は、`update-custom-key-store` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムキーストアのわかりやすい名前を編集するには**  
次の `update-custom-key-store` の例では、カスタムキーストアの名前を変更します。この例では、 AWS CloudHSM キーストアまたは外部キーストアで動作します。  
`custom-key-store-id` を使用して、キーストアを識別します。`new-custom-key-store-name` パラメータを使用して、新しいフレンドリ名を指定します。  
 AWS CloudHSM キーストアのフレンドリ名を更新するには、まず `disconnect-custom-key-store` コマンドを使用するなどしてキーストアを切断する必要があります。外部キーストアのわかりやすい名前は、外部キーストアが接続されていても切断されていても更新できます。カスタムキーストアの接続状態を確認するには、`describe-custom-key-store` コマンドを使用します。  

```
aws kms update-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0 \
    --new-custom-key-store-name ExampleKeyStore
```
このコマンドはデータを返しません。コマンドが機能したことを確認するには、`describe-custom-key-stores` コマンドを使用します。  
 AWS CloudHSM キーストアの更新の詳細については、「 Key Management Service デベロッパーガイド」の[「Editing AWS CloudHSM key store settings](https://docs.aws.amazon.com/kms/latest/developerguide/update-keystore.html)」を参照してください。 *AWS *  
外部キーストアの更新の詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[外部キーストアのプロパティの編集](https://docs.aws.amazon.com/kms/latest/developerguide/update-xks-keystore.html)」を参照してください。  
**例 2: AWS CloudHSM キーストアの kmsuser パスワードを編集するには**  
次の `update-custom-key-store` 例では、`kmsuser` パスワードの値を、指定されたキーストアに関連付けられた CloudHSM クラスター内の `kmsuser` の現在のパスワードに更新します。このコマンドは、クラスターの `kmsuser` パスワードを変更しません。現在のパスワードを KMS AWS に伝えるだけです。KMS に現在の`kmsuser`パスワードがない場合は、 AWS CloudHSM キーストアに接続できません。  
**注:** AWS CloudHSM キーストアを更新する前に、そのキーストアを切断する必要があります。`disconnect-custom-key-store` コマンドを使用します。コマンドが完了したら、 AWS CloudHSM キーストアを再接続できます。`connect-custom-key-store` コマンドを使用します。  

```
aws kms update-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0 \
    --key-store-password ExamplePassword
```
このコマンドは出力を返しません。変更が有効であることを確認するには、`describe-custom-key-stores` コマンドを使用します。  
 AWS CloudHSM キーストアの更新の詳細については、「 Key Management Service デベロッパーガイド」の[「Editing AWS CloudHSM key store settings](https://docs.aws.amazon.com/kms/latest/developerguide/update-keystore.html)」を参照してください。 *AWS *  
**例 3: AWS CloudHSM キーストアの AWS CloudHSM クラスターを編集するには**  
次の例では、 AWS CloudHSM キーストアに関連付けられている AWS CloudHSM クラスターを、同じクラスターの別のバックアップなど、関連するクラスターに変更します。  
**注:** AWS CloudHSM キーストアを更新する前に、そのキーストアを切断する必要があります。`disconnect-custom-key-store` コマンドを使用します。コマンドが完了したら、 AWS CloudHSM キーストアを再接続できます。`connect-custom-key-store` コマンドを使用します。  

```
aws kms update-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0 \
    --cloud-hsm-cluster-id cluster-1a23b4cdefg
```
このコマンドは出力を返しません。変更が有効であることを確認するには、`describe-custom-key-stores` コマンドを使用します。  
 AWS CloudHSM キーストアの更新の詳細については、「 Key Management Service デベロッパーガイド」の[「Editing AWS CloudHSM key store settings](https://docs.aws.amazon.com/kms/latest/developerguide/update-keystore.html)」を参照してください。 *AWS *  
**例 4: 外部キーストアのプロキシ認証情報を編集するには**  
次の例では、外部キーストアのプロキシ認証の認証情報を更新を更新します。値のうち 1 つを変更する場合でも、`raw-secret-access-key` と `access-key-id` の両方を指定する必要があります。この機能を使用して、無効な認証情報を修正したり、外部キーストアプロキシが認証情報をローテーションしたときに認証情報を変更したりできます。  
外部キーストアで KMS AWS のプロキシ認証情報を確立します。次に、このコマンドを使用して認証情報を KMS AWS に提供します。 AWS KMS はこの認証情報を使用して、外部キーストアプロキシへのリクエストに署名します。  
外部キーストアの接続または切断中にプロキシ認証情報を更新できます。カスタムキーストアの接続状態を確認するには、`describe-custom-key-store` コマンドを使用します。  

```
aws kms update-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0 \
    --xks-proxy-authentication-credential "AccessKeyId=ABCDE12345670EXAMPLE, RawSecretAccessKey=DXjSUawnel2fr6SKC7G25CNxTyWKE5PF9XX6H/u9pSo="
```
このコマンドは出力を返しません。変更が有効であることを確認するには、`describe-custom-key-stores` コマンドを使用します。  
外部キーストアの更新の詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[外部キーストアのプロパティの編集](https://docs.aws.amazon.com/kms/latest/developerguide/update-xks-keystore.html)」を参照してください。  
**例 5: 外部キーストアのプロキシ接続を編集するには**  
次の例では、外部キーストアのプロキシ接続オプションをパブリックエンドポイント接続から VPC エンドポイントサービス接続に変更します。`xks-proxy-connectivity` 値を変更するだけでなく、VPC エンドポイントサービスに関連付けられたプライベート DNS 名を反映するように `xks-proxy-uri-endpoint` 値を変更する必要があります。また、`xks-proxy-vpc-endpoint-service-name` 値を追加する必要があります。  
**注:** 外部ストアのプロキシ接続を更新する前に、プロキシ接続を切断する必要があります。`disconnect-custom-key-store` コマンドを使用します。コマンドが完了したら、`connect-custom-key-store` コマンドを使用して外部キーストアを再接続できます。  

```
aws kms update-custom-key-store \
    --custom-key-store-id cks-1234567890abcdef0 \
    --xks-proxy-connectivity VPC_ENDPOINT_SERVICE \
    --xks-proxy-uri-endpoint "https://myproxy-private.xks.example.com" \
    --xks-proxy-vpc-endpoint-service-name "com.amazonaws.vpce.us-east-1.vpce-svc-example"
```
このコマンドは出力を返しません。変更が有効であることを確認するには、`describe-custom-key-stores` コマンドを使用します。  
外部キーストアの更新の詳細については、「*AWS Key Management Service デベロッパーガイド*」の「[外部キーストアのプロパティの編集](https://docs.aws.amazon.com/kms/latest/developerguide/update-xks-keystore.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCustomKeyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/update-custom-key-store.html)」を参照してください。

### `update-key-description`
<a name="kms_UpdateKeyDescription_cli_2_topic"></a>

次のコード例は、`update-key-description` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタマーマネージド KMS キーに説明を追加または変更するには**  
次の `update-key-description` 例では、カスタマーマネージド KMS キーに説明を追加します。同じコマンドを使用して、既存の説明を変更できます。  
`--key-id` パラメータは、コマンドの KMS キーを識別します。この例では、キーの ARN 値を使用していますが、キー ID または KMS キー ARN のいずれかを使用できます。`--description` パラメータは新しい説明を指定します。このパラメータの値は、KMS キーの現在の説明 (ある場合) を置き換えます。  

```
aws kms update-key-description \
    --key-id arn:aws:kms:us-west-2:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab \
    --description "IT Department test key"
```
このコマンドは何も出力しません。KMS キーの説明を表示するには、`describe-key` コマンドを使用します。  
詳細については、「AWS Key Management Service API リファレンス」の「[UpdateKeyDescription](https://docs.aws.amazon.com/cli/latest/reference/kms/update-key-description.html)」を参照してください。**  
**例 2: カスタマーマネージド KMS キーの説明を削除するには**  
次の `update-key-description` の例では、カスタマーマネージド KMS キーの説明を削除します。  
`--key-id` パラメータは、コマンドの KMS キーを識別します。この例ではキー ID 値を使用しますが、KMS キーのキー ID またはキー ARN を使用できます。空の文字列値 ('') を持つ `--description` パラメータは、既存の説明を削除します。  

```
aws kms update-key-description \
    --key-id 0987dcba-09fe-87dc-65ba-ab0987654321 \
    --description ''
```
このコマンドは何も出力しません。KMS キーの説明を表示するには、describe-key コマンドを使用します。  
詳細については、「AWS Key Management Service API リファレンス」の「[UpdateKeyDescription](https://docs.aws.amazon.com/cli/latest/reference/kms/update-key-description.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateKeyDescription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/update-key-description.html)」を参照してください。

### `verify-mac`
<a name="kms_VerifyMac_cli_2_topic"></a>

次のコード例は、`verify-mac` を使用する方法を示しています。

**AWS CLI**  
**例 1: HMAC を検証するには**  
次の `verify-mac` コマンドは、特定のメッセージの HMAC、HMAC KMS キー、および MAC アルゴリズムを検証します。レスポンスの MacValid 値が「true」の場合、HMAC は有効であることを示します。  
 AWS CLI v2 では、 `message`パラメータの値は Base64-encodedされている必要があります。または、メッセージをファイルに保存し、 `fileb://` プレフィックスを使用して、ファイルからバイナリデータを読み取るように AWS CLI に指示することもできます。  
指定する MAC は Base64 でエンコードされているものであってはなりません。`generate-mac` コマンドが返す MAC のデコードについては、`generate-mac` コマンドの例を参照してください。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。キー ID は、キー用途が `GENERATE_VERIFY_MAC` の HMAC KMS キーを表す必要があります。  

```
msg=(echo 'Hello World' | base64)

aws kms verify-mac \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --message fileb://Message \
    --mac-algorithm HMAC_SHA_384 \
    --mac fileb://ExampleMac
```
出力:  

```
{
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "MacValid": true,
    "MacAlgorithm": "HMAC_SHA_384"
}
```
KMS での HMAC KMS AWS キーの使用の詳細については、「 Key Management Service デベロッパーガイド」の[「KMS AWS での HMAC キー](https://docs.aws.amazon.com/kms/latest/developerguide/hmac.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyMac](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/verify-mac.html)」を参照してください。

### `verify`
<a name="kms_Verify_cli_2_topic"></a>

次のコード例は、`verify` を使用する方法を示しています。

**AWS CLI**  
**デジタル署名を検証するには**  
次の `verify` は、短い Base64 でエンコードされたメッセージの暗号化署名を検証します。キー ID、メッセージ、メッセージタイプ、署名アルゴリズムは、メッセージの署名に使用されたものと同じである必要があります。  
 AWS CLI v2 では、 `message`パラメータの値は Base64-encodedされている必要があります。または、メッセージをファイルに保存し、 `fileb://` プレフィックスを使用して、ファイルからバイナリデータを読み取るように AWS CLI に指示することもできます。  
指定する署名は Base64 エンコードされているものであってはなりません。`sign` コマンドが返す署名のデコードについては、`sign` コマンドの例を参照してください。  
コマンドの出力には、署名が検証済みであることを示すブール値 `SignatureValid` フィールドが含まれます。署名の検証が失敗した場合、`verify` コマンドの実行結果も失敗となります。  
このコマンドを実行する前に、サンプルキー ID を AWS アカウントの有効なキー ID に置き換えます。  

```
aws kms verify \
    --key-id 1234abcd-12ab-34cd-56ef-1234567890ab \
    --message fileb://EncodedMessage \
    --message-type RAW \
    --signing-algorithm RSASSA_PKCS1_V1_5_SHA_256 \
    --signature fileb://ExampleSignature
```
出力:  

```
{
    "KeyId": "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
    "SignatureValid": true,
    "SigningAlgorithm": "RSASSA_PKCS1_V1_5_SHA_256"
}
```
KMS で非対称 KMS AWS キーを使用する方法の詳細については、*AWS 「 Key Management Service* [デベロッパーガイド」の「非対称キー](https://docs.aws.amazon.com/kms/latest/developerguide/symmetric-asymmetric.html)の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Verify](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kms/verify.html)」を参照してください。

# を使用した Lake Formation の例 AWS CLI
<a name="cli_2_lakeformation_code_examples"></a>

次のコード例は、Lake Formation AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-lf-tags-to-resource`
<a name="lakeformation_AddLfTagsToResource_cli_2_topic"></a>

次のコード例は、`add-lf-tags-to-resource` を使用する方法を示しています。

**AWS CLI**  
**1 つまたは複数の LF タグを既存のリソースにアタッチするには**  
次の `add-lf-tags-to-resource` の例では、特定の LF タグをテーブルリソースにアタッチします。  

```
aws lakeformation add-lf-tags-to-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Resource": {
        "Table": {
            "CatalogId": "123456789111",
            "DatabaseName": "tpc",
            "Name": "dl_tpc_promotion"
        }
    },
    "LFTags": [{
        "CatalogId": "123456789111",
        "TagKey": "usergroup",
        "TagValues": [
            "analyst"
        ]
    }]
}
```
出力:  

```
{
    "Failures": []
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Assigning LF-Tags to Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/TBAC-assigning-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddLfTagsToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/add-lf-tags-to-resource.html)」を参照してください。

### `batch-grant-permissions`
<a name="lakeformation_BatchGrantPermissions_cli_2_topic"></a>

次のコード例は、`batch-grant-permissions` を使用する方法を示しています。

**AWS CLI**  
**リソースに対するアクセス許可をプリンシパルに一括で付与するには**  
次の `batch-grant-permissions` の例では、指定されたリソースに対するアクセス許可をプリンシパルに一括で付与します。  

```
aws lakeformation batch-grant-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Entries": [{
            "Id": "1",
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
            },
            "Resource": {
                "Table": {
                    "CatalogId": "123456789111",
                    "DatabaseName": "tpc",
                    "Name": "dl_tpc_promotion"
                }
            },
            "Permissions": [
                "ALL"
            ],
            "PermissionsWithGrantOption": [
                "ALL"
            ]
        },
        {
            "Id": "2",
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
            },
            "Resource": {
                "Table": {
                    "CatalogId": "123456789111",
                    "DatabaseName": "tpc",
                    "Name": "dl_tpc_customer"
                }
            },
            "Permissions": [
                "ALL"
            ],
            "PermissionsWithGrantOption": [
                "ALL"
            ]
        },
        {
            "Id": "3",
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-business-analyst"
            },
            "Resource": {
                "Table": {
                    "CatalogId": "123456789111",
                    "DatabaseName": "tpc",
                    "Name": "dl_tpc_promotion"
                }
            },
            "Permissions": [
                "ALL"
            ],
            "PermissionsWithGrantOption": [
                "ALL"
            ]
        },
        {
            "Id": "4",
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
            },
            "Resource": {
                "DataCellsFilter": {
                    "TableCatalogId": "123456789111",
                    "DatabaseName": "tpc",
                    "TableName": "dl_tpc_item",
                    "Name": "developer_item"
                }
            },
            "Permissions": [
                "SELECT"
            ],
            "PermissionsWithGrantOption": []
        }
    ]
}
```
出力:  

```
{
    "Failures": []
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGrantPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/batch-grant-permissions.html)」を参照してください。

### `batch-revoke-permissions`
<a name="lakeformation_BatchRevokePermissions_cli_2_topic"></a>

次のコード例は、`batch-revoke-permissions` を使用する方法を示しています。

**AWS CLI**  
**リソースに対するアクセス許可をプリンシパルから一括で取り消すには**  
次の `batch-revoke-permissions` の例では、指定されたリソースに対するアクセス許可をプリンシパルから一括で取り消します。  

```
aws lakeformation batch-revoke-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Entries": [{
            "Id": "1",
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
            },
            "Resource": {
                "Table": {
                    "CatalogId": "123456789111",
                    "DatabaseName": "tpc",
                    "Name": "dl_tpc_promotion"
                }
            },
            "Permissions": [
                "ALL"
            ],
            "PermissionsWithGrantOption": [
                "ALL"
            ]
        },
        {
            "Id": "2",
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-business-analyst"
            },
            "Resource": {
                "Table": {
                    "CatalogId": "123456789111",
                    "DatabaseName": "tpc",
                    "Name": "dl_tpc_promotion"
                }
            },
            "Permissions": [
                "ALL"
            ],
            "PermissionsWithGrantOption": [
                "ALL"
            ]
        }
    ]
}
```
出力:  

```
{
    "Failures": []
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchRevokePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/batch-revoke-permissions.html)」を参照してください。

### `cancel-transaction`
<a name="lakeformation_CancelTransaction_cli_2_topic"></a>

次のコード例は、`cancel-transaction` を使用する方法を示しています。

**AWS CLI**  
**トランザクションをキャンセルするには**  
次の `cancel-transaction` の例では、トランザクションをキャンセルします。  

```
aws lakeformation cancel-transaction \
    --transaction-id='b014d972ca8347b89825e33c5774aec4'
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/cancel-transaction.html)」を参照してください。

### `commit-transaction`
<a name="lakeformation_CommitTransaction_cli_2_topic"></a>

次のコード例は、`commit-transaction` を使用する方法を示しています。

**AWS CLI**  
**トランザクションをコミットするには**  
次の `commit-transaction` の例では、トランザクションをコミットします。  

```
aws lakeformation commit-transaction \
    --transaction-id='b014d972ca8347b89825e33c5774aec4'
```
出力:  

```
{
    "TransactionStatus": "committed"
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CommitTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/commit-transaction.html)」を参照してください。

### `create-data-cells-filter`
<a name="lakeformation_CreateDataCellsFilter_cli_2_topic"></a>

次のコード例は、`create-data-cells-filter` を使用する方法を示しています。

**AWS CLI**  
**例 1: データセルフィルターを作成するには**  
次の `create-data-cells-filter` の例では、データセルフィルターを作成し、行の条件に基づいて特定の列へのアクセス許可を付与できるようにします。  

```
aws lakeformation create-data-cells-filter \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "TableData": {
        "ColumnNames": ["p_channel_details", "p_start_date_sk", "p_promo_name"],
        "DatabaseName": "tpc",
        "Name": "developer_promotion",
        "RowFilter": {
            "FilterExpression": "p_promo_name='ese'"
        },
        "TableCatalogId": "123456789111",
        "TableName": "dl_tpc_promotion"
    }
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Data filtering and cell-level security in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/data-filtering.html)」を参照してください。  
**例 2: 列フィルターを作成するには**  
次の `create-data-cells-filter` の例では、データフィルターを作成し、特定の列へのアクセス許可を付与できるようにします。  

```
aws lakeformation create-data-cells-filter \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "TableData": {
        "ColumnNames": ["p_channel_details", "p_start_date_sk", "p_promo_name"],
        "DatabaseName": "tpc",
        "Name": "developer_promotion_allrows",
        "RowFilter": {
            "AllRowsWildcard": {}
        },
        "TableCatalogId": "123456789111",
        "TableName": "dl_tpc_promotion"
    }
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Data filtering and cell-level security in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/data-filtering.html)」を参照してください。  
**例 3: 列を除外するデータフィルターを作成するには**  
次の `create-data-cells-filter` の例では、データフィルターを作成し、指定された列を除くすべてへのアクセス許可を付与できるようにします。  

```
aws lakeformation create-data-cells-filter \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "TableData": {
        "ColumnWildcard": {
            "ExcludedColumnNames": ["p_channel_details", "p_start_date_sk"]
        },
        "DatabaseName": "tpc",
        "Name": "developer_promotion_excludecolumn",
        "RowFilter": {
            "AllRowsWildcard": {}
        },
        "TableCatalogId": "123456789111",
        "TableName": "dl_tpc_promotion"
    }
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Data filtering and cell-level security in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/data-filtering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDataCellsFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/create-data-cells-filter.html)」を参照してください。

### `create-lf-tag`
<a name="lakeformation_CreateLfTag_cli_2_topic"></a>

次のコード例は、`create-lf-tag` を使用する方法を示しています。

**AWS CLI**  
**LF タグを作成するには**  
次の `create-lf-tag` の例では、指定された名前とキーを持つ LF タグを作成します。  

```
aws lakeformation create-lf-tag \
    --catalog-id '123456789111' \
    --tag-key 'usergroup' \
    --tag-values '["developer","analyst","campaign"]'
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Managing LF-Tags for metadata access control](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLfTag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/create-lf-tag.html)」を参照してください。

### `delete-data-cells-filter`
<a name="lakeformation_DeleteDataCellsFilter_cli_2_topic"></a>

次のコード例は、`delete-data-cells-filter` を使用する方法を示しています。

**AWS CLI**  
**データセルフィルターを削除するには**  
次の `delete-data-cells-filter` の例では、指定されたデータセルフィルターを削除します。  

```
aws lakeformation delete-data-cells-filter \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "TableCatalogId": "123456789111",
    "DatabaseName": "tpc",
    "TableName": "dl_tpc_promotion",
    "Name": "developer_promotion"
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Data filtering and cell-level security in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/data-filtering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDataCellsFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/delete-data-cells-filter.html)」を参照してください。

### `delete-lf-tag`
<a name="lakeformation_DeleteLfTag_cli_2_topic"></a>

次のコード例は、`delete-lf-tag` を使用する方法を示しています。

**AWS CLI**  
**LF タグ定義を削除するには**  
次の `delete-lf-tag` の例では、LF タグ定義を削除します。  

```
aws lakeformation delete-lf-tag \
    --catalog-id '123456789111' \
    --tag-key 'usergroup'
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Managing LF-Tags for metadata access control](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLfTag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/delete-lf-tag.html)」を参照してください。

### `delete-objects-on-cancel`
<a name="lakeformation_DeleteObjectsOnCancel_cli_2_topic"></a>

次のコード例は、`delete-objects-on-cancel` を使用する方法を示しています。

**AWS CLI**  
**トランザクションがキャンセルされたときにオブジェクトを削除するには**  
次の `delete-objects-on-cancel` の例では、トランザクションがキャンセルされたときに、一覧表示されている S3 オブジェクトを削除します。  

```
aws lakeformation delete-objects-on-cancel \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "012345678901",
    "DatabaseName": "tpc",
    "TableName": "dl_tpc_household_demographics_gov",
    "TransactionId": "1234d972ca8347b89825e33c5774aec4",
    "Objects": [{
        "Uri": "s3://lf-data-lake-012345678901/target/dl_tpc_household_demographics_gov/run-unnamed-1-part-block-0-r-00000-snappy-ff26b17504414fe88b302cd795eabd00.parquet",
        "ETag": "1234ab1fc50a316b149b4e1f21a73800"
    }]
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteObjectsOnCancel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/delete-objects-on-cancel.html)」を参照してください。

### `deregister-resource`
<a name="lakeformation_DeregisterResource_cli_2_topic"></a>

次のコード例は、`deregister-resource` を使用する方法を示しています。

**AWS CLI**  
**データレイクストレージの登録を解除するには**  
次の `deregister-resource` の例では、Lake Formation によって管理されるリソースの登録を解除します。  

```
aws lakeformation deregister-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ResourceArn": "arn:aws:s3:::lf-emr-athena-result-123"
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Adding an Amazon S3 location to your data lake](https://docs.aws.amazon.com/lake-formation/latest/dg/register-data-lake.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/deregister-resource.html)」を参照してください。

### `describe-transaction`
<a name="lakeformation_DescribeTransaction_cli_2_topic"></a>

次のコード例は、`describe-transaction` を使用する方法を示しています。

**AWS CLI**  
**トランザクションの詳細を取得するには**  
次の `describe-transaction` の例では、単一のトランザクションの詳細を返します。  

```
aws lakeformation describe-transaction \
    --transaction-id='8cb4b1a7cc8d486fbaca9a64e7d9f5ce'
```
出力:  

```
{
    "TransactionDescription": {
        "TransactionId": "12345972ca8347b89825e33c5774aec4",
        "TransactionStatus": "committed",
        "TransactionStartTime": "2022-08-10T14:29:04.046000+00:00",
        "TransactionEndTime": "2022-08-10T14:29:09.681000+00:00"
    }
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/describe-transaction.html)」を参照してください。

### `extend-transaction`
<a name="lakeformation_ExtendTransaction_cli_2_topic"></a>

次のコード例は、`extend-transaction` を使用する方法を示しています。

**AWS CLI**  
**トランザクションを拡張するには**  
次の `extend-transaction` の例では、トランザクションを拡張します。  

```
aws lakeformation extend-transaction \
    --transaction-id='8cb4b1a7cc8d486fbaca9a64e7d9f5ce'
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExtendTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/extend-transaction.html)」を参照してください。

### `get-data-lake-settings`
<a name="lakeformation_GetDataLakeSettings_cli_2_topic"></a>

次の例は、`get-data-lake-settings` を使用する方法を説明しています。

**AWS CLI**  
** AWS Lake Formation が管理するデータレイク設定を取得するには**  
次の `get-data-lake-settings` の例では、データレイク管理者およびその他のデータレイク設定のリストを取得します。  

```
aws lakeformation get-data-lake-settings \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111"
}
```
出力:  

```
{
    "DataLakeSettings": {
        "DataLakeAdmins": [{
            "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-admin"
        }],
        "CreateDatabaseDefaultPermissions": [],
        "CreateTableDefaultPermissions": [
                {
                        "Principal": {
                            "DataLakePrincipalIdentifier": "IAM_ALLOWED_PRINCIPALS"
                        },
                        "Permissions": [
                            "ALL"
                        ]
                }
        ],
        "TrustedResourceOwners": [],
        "AllowExternalDataFiltering": true,
        "ExternalDataFilteringAllowList": [{
            "DataLakePrincipalIdentifier": "123456789111"
        }],
        "AuthorizedSessionTagValueList": [
            "Amazon EMR"
        ]
    }
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Changing the default security settings for your data lake](https://docs.aws.amazon.com/lake-formation/latest/dg/change-settings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDataLakeSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-data-lake-settings.html)」を参照してください。

### `get-effective-permissions-for-path`
<a name="lakeformation_GetEffectivePermissionsForPath_cli_2_topic"></a>

次のコード例は、`get-effective-permissions-for-path` を使用する方法を示しています。

**AWS CLI**  
**特定のパスにあるリソースに対するアクセス許可を取得するには**  
次の `get-effective-permissions-for-path` の例では、Amazon S3 のパスにある指定されたテーブルまたはデータベースリソースに対する Lake Formation アクセス許可を返します。  

```
aws lakeformation get-effective-permissions-for-path \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "ResourceArn": "arn:aws:s3:::lf-data-lake-123456789111"
}
```
出力:  

```
{
    "Permissions": [{
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-campaign-manager"
            },
            "Resource": {
                "Database": {
                    "Name": "tpc"
                }
            },
            "Permissions": [
                "DESCRIBE"
            ],
            "PermissionsWithGrantOption": []
        },
        {
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:role/EMR-RuntimeRole"
            },
            "Resource": {
                "Database": {
                    "Name": "tpc"
                }
            },
            "Permissions": [
                "ALL"
            ],
            "PermissionsWithGrantOption": []
        },
        {
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:saml-provider/oktaSAMLProvider:user/emr-developer"
            },
            "Resource": {
                "Database": {
                    "Name": "tpc"
                }
            },
            "Permissions": [
                "ALL",
                "DESCRIBE"
            ],
            "PermissionsWithGrantOption": []
        },
        {
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-admin"
            },
            "Resource": {
                "Database": {
                    "Name": "tpc"
                }
            },
            "Permissions": [
                "ALL",
                "ALTER",
                "CREATE_TABLE",
                "DESCRIBE",
                "DROP"
            ],
            "PermissionsWithGrantOption": [
                "ALL",
                "ALTER",
                "CREATE_TABLE",
                "DESCRIBE",
                "DROP"
            ]
        },
        {
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:role/LF-GlueServiceRole"
            },
            "Resource": {
                "Database": {
                    "Name": "tpc"
                }
            },
            "Permissions": [
                "CREATE_TABLE"
            ],
            "PermissionsWithGrantOption": []
        }
    ],
    "NextToken": "E5SlJDSTZleUp6SWpvaU9UQTNORE0zTXpFeE5Ua3pJbjE5TENKbGVIQnBjbUYwYVc5dUlqcDdJbk5sWTI5dVpITWlPakUyTm=="
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Lake Formation アクセス許可の管理](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEffectivePermissionsForPath](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-effective-permissions-for-path.html)」を参照してください。

### `get-lf-tag`
<a name="lakeformation_GetLfTag_cli_2_topic"></a>

次のコード例は、`get-lf-tag` を使用する方法を示しています。

**AWS CLI**  
**LF タグ定義を取得するには**  
次の `get-lf-tag` の例では、LF タグ定義を取得します。  

```
aws lakeformation get-lf-tag \
    --catalog-id '123456789111' \
    --tag-key 'usergroup'
```
出力:  

```
{
    "CatalogId": "123456789111",
    "TagKey": "usergroup",
    "TagValues": [
        "analyst",
        "campaign",
        "developer"
    ]
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Managing LF-Tags for metadata access control](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLfTag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-lf-tag.html)」を参照してください。

### `get-query-state`
<a name="lakeformation_GetQueryState_cli_2_topic"></a>

次のコード例は、`get-query-state` を使用する方法を示しています。

**AWS CLI**  
**送信されたクエリの状態を取得するには**  
次の `get-query-state` の例では、以前に送信されたクエリの状態を返します。  

```
aws lakeformation get-query-state \
    --query-id='1234273f-4a62-4cda-8d98-69615ee8be9b'
```
出力:  

```
{
    "State": "FINISHED"
}
```
詳細については、「*AWS Developer Guide*」の「[Transactional data operations](https://docs.aws.amazon.com/lake-formation/latest/dg/transactions-data-operations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetQueryState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-query-state.html)」を参照してください。

### `get-query-statistics`
<a name="lakeformation_GetQueryStatistics_cli_2_topic"></a>

次のコード例は、`get-query-statistics` を使用する方法を示しています。

**AWS CLI**  
**クエリ統計を取得するには**  
次の `get-query-statistics` の例では、クエリの計画と実行に関する統計を取得します。  

```
aws lakeformation get-query-statistics \
    --query-id='1234273f-4a62-4cda-8d98-69615ee8be9b'
```
出力:  

```
{
    "ExecutionStatistics": {
        "AverageExecutionTimeMillis": 0,
        "DataScannedBytes": 0,
        "WorkUnitsExecutedCount": 0
    },
    "PlanningStatistics": {
        "EstimatedDataToScanBytes": 43235,
        "PlanningTimeMillis": 2377,
        "QueueTimeMillis": 440,
        "WorkUnitsGeneratedCount": 1
    },
    "QuerySubmissionTime": "2022-08-11T02:14:38.641870+00:00"
}
```
詳細については、「*AWS Developer Guide*」の「[Transactional data operations](https://docs.aws.amazon.com/lake-formation/latest/dg/transactions-data-operations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetQueryStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-query-statistics.html)」を参照してください。

### `get-resource-lf-tags`
<a name="lakeformation_GetResourceLfTags_cli_2_topic"></a>

次のコード例は、`get-resource-lf-tags` を使用する方法を示しています。

**AWS CLI**  
**LF タグを一覧表示するには**  
次の `list-lf-tags` の例では、リクエストしたユーザーが閲覧アクセス許可を持っている LF タグのリストを返します。  

```
aws lakeformation list-lf-tags \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "ResourceShareType": "ALL",
    "MaxResults": 2
}
```
出力:  

```
{
"LFTags": [{
        "CatalogId": "123456789111",
        "TagKey": "category",
        "TagValues": [
            "private",
            "public"
        ]
    },
    {
        "CatalogId": "123456789111",
        "TagKey": "group",
        "TagValues": [
            "analyst",
            "campaign",
            "developer"
        ]
    }],
    "NextToken": "kIiwiZXhwaXJhdGlvbiI6eyJzZWNvbmRzIjoxNjYwMDY4dCI6ZmFsc2V9"
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Managing LF-Tags for metadata access control](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceLfTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-resource-lf-tags.html)」を参照してください。

### `get-table-objects`
<a name="lakeformation_GetTableObjects_cli_2_topic"></a>

次のコード例は、`get-table-objects` を使用する方法を示しています。

**AWS CLI**  
**管理対象テーブルのオブジェクトを一覧表示するには**  
次の `get-table-objects` の例では、指定された管理対象テーブルを構成する Amazon S3 オブジェクトのセットを返します。  

```
aws lakeformation get-table-objects \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "012345678901",
    "DatabaseName": "tpc",
    "TableName": "dl_tpc_household_demographics_gov",
    "QueryAsOfTime": "2022-08-10T15:00:00"
}
```
出力:  

```
{
    "Objects": [{
        "PartitionValues": [],
        "Objects": [{
            "Uri": "s3://lf-data-lake-012345678901/target/dl_tpc_household_demographics_gov/run-unnamed-1-part-block-0-r-00000-snappy-ff26b17504414fe88b302cd795eabd00.parquet",
            "ETag": "12345b1fc50a316b149b4e1f21a73800",
            "Size": 43235
        }]
    }]
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTableObjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-table-objects.html)」を参照してください。

### `get-work-unit-results`
<a name="lakeformation_GetWorkUnitResults_cli_2_topic"></a>

次のコード例は、`get-work-unit-results` を使用する方法を示しています。

**AWS CLI**  
**特定のクエリの作業単位を取得するには**  
次の `get-work-unit-results` の例では、クエリから得られた作業単位を返します。  

```
aws lakeformation get-work-units \
    --query-id='1234273f-4a62-4cda-8d98-69615ee8be9b' \
    --work-unit-id '0' \
    --work-unit-token 'B2fMSdmQXe9umX8Ux8XCo4=' outfile
```
出力:  

```
outfile with Blob content.
```
詳細については、「*AWS Developer Guide*」の「[Transactional data operations](https://docs.aws.amazon.com/lake-formation/latest/dg/transactions-data-operations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWorkUnitResults](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-work-unit-results.html)」を参照してください。

### `get-work-units`
<a name="lakeformation_GetWorkUnits_cli_2_topic"></a>

次のコード例は、`get-work-units` を使用する方法を示しています。

**AWS CLI**  
**作業単位を取得するには**  
次の `get-work-units` の例では、StartQueryPlanning オペレーションによって生成された作業単位を取得します。  

```
aws lakeformation get-work-units \
    --query-id='1234273f-4a62-4cda-8d98-69615ee8be9b'
```
出力:  

```
{
    "WorkUnitRanges": [{
        "WorkUnitIdMax": 0,
        "WorkUnitIdMin": 0,
        "WorkUnitToken": "1234eMAk4kLO4umqEL4Z5WuxL04AXwABABVhd3MtY3J5cHRvLXB1YmxpYy1rZXkAREEwYm9QbkhINmFYTWphbmMxZW1PQmEyMGlUb0JFbXNlWmRYc0NmckRIR1dmQ0hjY2YzNFdMcmNXb2JGZmhEK0QvZz09AAEAB2F3cy1rbXMAS2Fybjphd3M6a21zOnVzLWVhc3QtMTo3MDkxNTAyNDkyNDk6a2V5L2VmYmI3NDUyLTY1MjYtNGJiOS1iNmZhLTEzYzJkMTM3MmU2OQC4AQIBAHg6eWNF2ZrQATTAuPDJVCEAQSyIF67vX+f88jzGrYq22gE6jkQlpOB+Oet2eqNUmFudAAAAfjB8BgkqhkiG9w0BBwagbzBtAgEAMGgGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMCOEWRdafowek3RUmAgEQgDsYZZE84nnnbNmvsqCBPLh19nLQ10mUWOg9IfiaOwefEn6L920V0x1LpJACo7MtIBLXnbGcz2dFDZjFygIAAAAADAAAEAAAAAAAAAAAAAAAAAAQSQf8XDSI5pvR4Fx4JsrS/////wAAAAEAAAAAAAAAAAAAAAEAAACX3/w5h75QAPomfKH+cyEKYU1yccUmBl+VSojiGOtdsUk7vcjYXUUboYm3dvqRqX2s4gROMOn+Ij8R0/8jYmnHkpvyAFNVRPyETyIKg7k5Z9+5I1c2d3446Jw/moWGGxjH8AEG9h27ytmOhozxDOEi/F2ZoXz6wlGDfGUo/2WxCkYOhTyNaw6TM+7drTM7yrW4iNVLUM0LX0xnFjIAhLhooWJek6vjQZUAZzBlAjBH8okRtYP8R7AY2Wls/hqFBhG0V4l42AC0LxsuZbMQrE2SzWZUZ0E9Uew7/n0cyX4CMQDR79INyv4ysMByW9kKGGKyba+cCNklExMR+btBQBmMuB2fMSdmQXe9umX8Ux8XCo4="
    }],
    "QueryId": "1234273f-4a62-4cda-8d98-69615ee8be9b"
}
```
詳細については、「*AWS Developer Guide*」の「[Transactional data operations](https://docs.aws.amazon.com/lake-formation/latest/dg/transactions-data-operations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWorkUnits](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/get-work-units.html)」を参照してください。

### `grant-permissions`
<a name="lakeformation_GrantPermissions_cli_2_topic"></a>

次のコード例は、`grant-permissions` を使用する方法を示しています。

**AWS CLI**  
**例 1: LF タグを使用してリソースに対するアクセス許可をプリンシパルに付与するには**  
次の `grant-permissions` の例では、LF タグポリシーに一致するデータベースリソースに対する ALL アクセス許可をプリンシパルに付与します。  

```
aws lakeformation grant-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Principal": {
        "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-admin"
    },
    "Resource": {
        "LFTagPolicy": {
            "CatalogId": "123456789111",
            "ResourceType": "DATABASE",
            "Expression": [{
                "TagKey": "usergroup",
                "TagValues": [
                    "analyst",
                    "developer"
                ]
            }]
        }
    },
    "Permissions": [
        "ALL"
    ],
    "PermissionsWithGrantOption": [
        "ALL"
    ]
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
**例 2: 列レベルのアクセス許可をプリンシパルに付与するには**  
次の `grant-permissions` の例では、特定の列を選択するアクセス許可をプリンシパルに付与します。  

```
aws lakeformation grant-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Principal": {
        "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
    },
    "Resource": {
        "TableWithColumns": {
            "CatalogId": "123456789111",
            "ColumnNames": ["p_end_date_sk"],
            "DatabaseName": "tpc",
            "Name": "dl_tpc_promotion"
        }
    },
    "Permissions": [
        "SELECT"
    ],
    "PermissionsWithGrantOption": []
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
**例 3: テーブルのアクセス許可をプリンシパルに付与するには**  
次の `grant-permissions` の例では、特定のデータベースのすべてのテーブルに対する選択アクセス許可をプリンシパルに付与します。  

```
aws lakeformation grant-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Principal": {
        "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
    },
    "Resource": {
        "Table": {
            "CatalogId": "123456789111",
            "DatabaseName": "tpc",
            "TableWildcard": {}
        }
    },
    "Permissions": [
        "SELECT"
    ],
    "PermissionsWithGrantOption": []
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
**例 4: LF タグに対するアクセス許可をプリンシパルに付与するには**  
次の `grant-permissions` の例では、LF タグに対する関連付けアクセス許可をプリンシパルに付与します。  

```
aws lakeformation grant-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Principal": {
        "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
    },
    "Resource": {
        "LFTag": {
            "CatalogId": "123456789111",
            "TagKey": "category",
            "TagValues": [
                "private", "public"
            ]
        }

    },
    "Permissions": [
        "ASSOCIATE"
    ],
    "PermissionsWithGrantOption": []
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
**例 5: データロケーションに対するアクセス許可をプリンシパルに付与するには**  
次の `grant-permissions` の例では、データロケーションに対するアクセス許可をプリンシパルに付与します。  

```
aws lakeformation grant-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Principal": {
        "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
    },
    "Resource": {
        "DataLocation": {
            "CatalogId": "123456789111",
            "ResourceArn": "arn:aws:s3:::lf-data-lake-123456789111"
        }
    },
    "Permissions": [
        "DATA_LOCATION_ACCESS"
    ],
    "PermissionsWithGrantOption": []
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GrantPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/grant-permissions.html)」を参照してください。

### `list-data-cells-filter`
<a name="lakeformation_ListDataCellsFilter_cli_2_topic"></a>

次のコード例は、`list-data-cells-filter` を使用する方法を示しています。

**AWS CLI**  
**データセルフィルターを一覧表示するには**  
次の `list-data-cells-filter` の例では、特定のテーブルのデータセルフィルターを一覧表示します。  

```
aws lakeformation list-data-cells-filter \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "MaxResults": 2,
    "Table": {
        "CatalogId": "123456789111",
        "DatabaseName": "tpc",
        "Name": "dl_tpc_promotion"
    }
}
```
出力:  

```
{
    "DataCellsFilters": [{
            "TableCatalogId": "123456789111",
            "DatabaseName": "tpc",
            "TableName": "dl_tpc_promotion",
            "Name": "developer_promotion",
            "RowFilter": {
                "FilterExpression": "p_promo_name='ese'"
            },
            "ColumnNames": [
                "p_channel_details",
                "p_start_date_sk",
                "p_purpose",
                "p_promo_id",
                "p_promo_name",
                "p_end_date_sk",
                "p_discount_active"
            ]
        },
        {
            "TableCatalogId": "123456789111",
            "DatabaseName": "tpc",
            "TableName": "dl_tpc_promotion",
            "Name": "developer_promotion_allrows",
            "RowFilter": {
                "FilterExpression": "TRUE",
                "AllRowsWildcard": {}
            },
            "ColumnNames": [
                "p_channel_details",
                "p_start_date_sk",
                "p_promo_name"
            ]
        }
    ],
    "NextToken": "2MDA2MTgwNiwibmFub3MiOjE0MDAwMDAwMH19"
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Data filtering and cell-level security in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/data-filtering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDataCellsFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/list-data-cells-filter.html)」を参照してください。

### `list-permissions`
<a name="lakeformation_ListPermissions_cli_2_topic"></a>

次のコード例は、`list-permissions` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースに対するプリンシパルアクセス許可のリストを取得するには**  
次の `list-permissions` の例では、データベースリソースに対するプリンシパルアクセス許可のリストを返します。  

```
aws lakeformation list-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "ResourceType": "DATABASE",
    "MaxResults": 2
}
```
出力:  

```
{
    "PrincipalResourcePermissions": [{
        "Principal": {
            "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-campaign-manager"
        },
        "Resource": {
            "Database": {
                "CatalogId": "123456789111",
                "Name": "tpc"
            }
        },
        "Permissions": [
            "DESCRIBE"
        ],
        "PermissionsWithGrantOption": []
    }],
    "NextToken": "E5SlJDSTZleUp6SWpvaU9UQTNORE0zTXpFeE5Ua3pJbjE5TENKbGVIQnBjbUYwYVc5dUlqcDdJbk5sWTI5dVpITWlPakUyTm"
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Lake Formation アクセス許可の管理](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-permissions.html)」を参照してください。  
**例 2: データフィルターを使用してテーブルに対するプリンシパルアクセス許可のリストを取得するには**  
次の `list-permissions` の例では、プリンシパルに付与された関連するデータフィルターを使用して、テーブルに対するアクセス許可を一覧表示します。  

```
aws lakeformation list-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Resource": {
        "Table": {
            "CatalogId": "123456789111",
            "DatabaseName": "tpc",
            "Name": "dl_tpc_customer"
        }
    },
    "IncludeRelated": "TRUE",
    "MaxResults": 10
}
```
出力:  

```
{
    "PrincipalResourcePermissions": [{
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:role/Admin"
            },
            "Resource": {
                "Table": {
                    "CatalogId": "123456789111",
                    "DatabaseName": "customer",
                    "Name": "customer_invoice"
                }
            },
            "Permissions": [
                "ALL",
                "ALTER",
                "DELETE",
                "DESCRIBE",
                "DROP",
                "INSERT"
            ],
            "PermissionsWithGrantOption": [
                "ALL",
                "ALTER",
                "DELETE",
                "DESCRIBE",
                "DROP",
                "INSERT"
            ]
        },
        {
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:role/Admin"
            },
            "Resource": {
                "TableWithColumns": {
                    "CatalogId": "123456789111",
                    "DatabaseName": "customer",
                    "Name": "customer_invoice",
                    "ColumnWildcard": {}
                }
            },
            "Permissions": [
                "SELECT"
            ],
            "PermissionsWithGrantOption": [
                "SELECT"
            ]
        },
        {
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:role/Admin"
            },
            "Resource": {
                "DataCellsFilter": {
                    "TableCatalogId": "123456789111",
                    "DatabaseName": "customer",
                    "TableName": "customer_invoice",
                    "Name": "dl_us_customer"
                }
            },
            "Permissions": [
                "DESCRIBE",
                "SELECT",
                "DROP"
            ],
            "PermissionsWithGrantOption": []
        }
    ],
    "NextToken": "VyeUFjY291bnRQZXJtaXNzaW9ucyI6ZmFsc2V9"
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Lake Formation アクセス許可の管理](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-permissions.html)」を参照してください。  
**例 3: LF タグに対するプリンシパルアクセス許可のリストを取得するには**  
次の `list-permissions` の例では、プリンシパルに付与された LF タグに対するアクセス許可を一覧表示します。  

```
aws lakeformation list-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Resource": {
        "LFTag": {
            "CatalogId": "123456789111",
            "TagKey": "category",
            "TagValues": [
                "private"
            ]
        }
    },
    "MaxResults": 10
}
```
出力:  

```
{
    "PrincipalResourcePermissions": [{
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-admin"
            },
            "Resource": {
                "LFTag": {
                    "CatalogId": "123456789111",
                    "TagKey": "category",
                    "TagValues": [
                        "*"
                    ]
                }
            },
            "Permissions": [
                "DESCRIBE"
            ],
            "PermissionsWithGrantOption": [
                "DESCRIBE"
            ]
        },
        {
            "Principal": {
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-admin"
            },
            "Resource": {
                "LFTag": {
                    "CatalogId": "123456789111",
                    "TagKey": "category",
                    "TagValues": [
                        "*"
                    ]
                }
            },
            "Permissions": [
                "ASSOCIATE"
            ],
            "PermissionsWithGrantOption": [
                "ASSOCIATE"
            ]
        }
    ],
    "NextToken": "EJwY21GMGFXOXVJanA3SW5Ocm1pc3Npb25zIjpmYWxzZX0="
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Lake Formation アクセス許可の管理](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/list-permissions.html)」を参照してください。

### `list-resources`
<a name="lakeformation_ListResources_cli_2_topic"></a>

次のコード例は、`list-resources` を使用する方法を示しています。

**AWS CLI**  
**Lake Formation によって管理されるリソースを一覧表示するには**  
次の `list-resources` の例では、Lake Formation によって管理される条件に一致するリソースを一覧表示します。  

```
aws lakeformation list-resources \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "FilterConditionList": [{
        "Field": "ROLE_ARN",
        "ComparisonOperator": "CONTAINS",
        "StringValueList": [
            "123456789111"
        ]
    }],
    "MaxResults": 10
}
```
出力:  

```
{
    "ResourceInfoList": [{
            "ResourceArn": "arn:aws:s3:::lf-data-lake-123456789111",
            "RoleArn": "arn:aws:iam::123456789111:role/LF-GlueServiceRole",
            "LastModified": "2022-07-21T02:12:46.669000+00:00"
        },
        {
            "ResourceArn": "arn:aws:s3:::lf-emr-test-123456789111",
            "RoleArn": "arn:aws:iam::123456789111:role/EMRLFS3Role",
            "LastModified": "2022-07-29T16:22:03.211000+00:00"
        }
    ]
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Lake Formation アクセス許可の管理](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/list-resources.html)」を参照してください。

### `list-transactions`
<a name="lakeformation_ListTransactions_cli_2_topic"></a>

次のコード例は、`list-transactions` を使用する方法を示しています。

**AWS CLI**  
**すべてのトランザクションの詳細を一覧表示するには**  
次の `list-transactions` の例では、トランザクションとそのステータスに関するメタデータを返します。  

```
aws lakeformation list-transactions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "StatusFilter": "ALL",
    "MaxResults": 3
}
```
出力:  

```
{
    "Transactions": [{
            "TransactionId": "1234569f08804cb790d950d4d0fe485e",
            "TransactionStatus": "committed",
            "TransactionStartTime": "2022-08-10T14:32:29.220000+00:00",
            "TransactionEndTime": "2022-08-10T14:32:33.751000+00:00"
        },
        {
            "TransactionId": "12345972ca8347b89825e33c5774aec4",
            "TransactionStatus": "committed",
            "TransactionStartTime": "2022-08-10T14:29:04.046000+00:00",
            "TransactionEndTime": "2022-08-10T14:29:09.681000+00:00"
        },
        {
            "TransactionId": "12345daf6cb047dbba8ad9b0414613b2",
            "TransactionStatus": "committed",
            "TransactionStartTime": "2022-08-10T13:56:51.261000+00:00",
            "TransactionEndTime": "2022-08-10T13:56:51.547000+00:00"
        }
    ],
    "NextToken": "77X1ebypsI7os+X2lhHsZLGNCDK3nNGpwRdFpicSOHgcX1/QMoniUAKcpR3kj3ts3PVdMA=="
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTransactions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/list-transactions.html)」を参照してください。

### `put-data-lake-settings`
<a name="lakeformation_PutDataLakeSettings_cli_2_topic"></a>

次の例は、`put-data-lake-settings` を使用する方法を説明しています。

**AWS CLI**  
** AWS Lake Formation が管理するデータレイクの設定を行うには**  
次の `put-data-lake-settings` の例では、データレイク管理者およびその他のデータレイク設定のリストを設定します。  

```
aws lakeformation put-data-lake-settings \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "DataLakeSettings": {
        "DataLakeAdmins": [{
                "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-admin"
            }
        ],
        "CreateDatabaseDefaultPermissions": [],
        "CreateTableDefaultPermissions": [],
        "TrustedResourceOwners": [],
        "AllowExternalDataFiltering": true,
        "ExternalDataFilteringAllowList": [{
            "DataLakePrincipalIdentifier ": "123456789111"
        }],
        "AuthorizedSessionTagValueList": ["Amazon EMR"]
    }
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Changing the default security settings for your data lake](https://docs.aws.amazon.com/lake-formation/latest/dg/change-settings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutDataLakeSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/put-data-lake-settings.html)」を参照してください。

### `register-resource`
<a name="lakeformation_RegisterResource_cli_2_topic"></a>

次のコード例は、`register-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: サービスリンクロールを使用してデータレイクストレージを登録するには**  
次の `register-resource` の例では、サービスリンクロールを使用して Lake Formation によって管理されるリソースを登録します。  

```
aws lakeformation register-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ResourceArn": "arn:aws:s3:::lf-emr-athena-result-123",
    "UseServiceLinkedRole": true
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Adding an Amazon S3 location to your data lake](https://docs.aws.amazon.com/lake-formation/latest/dg/register-data-lake.html)」を参照してください。  
**例 2: カスタムロールを使用してデータレイクストレージを登録するには**  
次の `register-resource` の例では、カスタムロールを使用して Lake Formation によって管理されるリソースを登録します。  

```
aws lakeformation register-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "ResourceArn": "arn:aws:s3:::lf-emr-athena-result-123",
    "UseServiceLinkedRole": false,
    "RoleArn": "arn:aws:iam::123456789111:role/LF-GlueServiceRole"
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Adding an Amazon S3 location to your data lake](https://docs.aws.amazon.com/lake-formation/latest/dg/register-data-lake.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/register-resource.html)」を参照してください。

### `remove-lf-tags-from-resource`
<a name="lakeformation_RemoveLfTagsFromResource_cli_2_topic"></a>

次のコード例は、`remove-lf-tags-from-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースから LF タグを削除するには**  
次の `remove-lf-tags-from-resource` の例では、LF タグとテーブルリソースとの関連付けを削除します。  

```
aws lakeformation remove-lf-tags-from-resource \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Resource": {
        "Table": {
            "CatalogId": "123456789111",
            "DatabaseName": "tpc",
            "Name": "dl_tpc_promotion"
        }
    },
    "LFTags": [{
        "CatalogId": "123456789111",
        "TagKey": "usergroup",
        "TagValues": [
            "developer"
        ]
    }]
}
```
出力:  

```
{
    "Failures": []
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Assigning LF-Tags to Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/TBAC-assigning-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveLfTagsFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/remove-lf-tags-from-resource.html)」を参照してください。

### `revoke-permissions`
<a name="lakeformation_RevokePermissions_cli_2_topic"></a>

次のコード例は、`revoke-permissions` を使用する方法を示しています。

**AWS CLI**  
**リソースに対するアクセス許可をプリンシパルから取り消すには**  
次の `revoke-permissions` の例では、指定されたデータベースの特定のテーブルへのプリンシパルアクセス許可を取り消します。  

```
aws lakeformation revoke-permissions \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "123456789111",
    "Principal": {
        "DataLakePrincipalIdentifier": "arn:aws:iam::123456789111:user/lf-developer"
    },
    "Resource": {
        "Table": {
            "CatalogId": "123456789111",
            "DatabaseName": "tpc",
            "Name": "dl_tpc_promotion"
        }
    },
    "Permissions": [
        "ALL"
    ],
    "PermissionsWithGrantOption": []
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Granting and revoking permissions on Data Catalog resources](https://docs.aws.amazon.com/lake-formation/latest/dg/granting-catalog-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/revoke-permissions.html)」を参照してください。

### `search-databases-by-lf-tags`
<a name="lakeformation_SearchDatabasesByLfTags_cli_2_topic"></a>

次のコード例は、`search-databases-by-lf-tags` を使用する方法を示しています。

**AWS CLI**  
**LFTags でデータベースリソースの検索を行うには**  
次の `search-databases-by-lf-tags` の例では、LFTag 式に一致するデータベースリソースの検索を行います。  

```
aws lakeformation search-databases-by-lf-tags \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "MaxResults": 1,
    "CatalogId": "123456789111",
    "Expression": [{
        "TagKey": "usergroup",
        "TagValues": [
            "developer"
        ]
    }]
}
```
出力:  

```
{
    "DatabaseList": [{
        "Database": {
            "CatalogId": "123456789111",
            "Name": "tpc"
        },
        "LFTags": [{
            "CatalogId": "123456789111",
            "TagKey": "usergroup",
            "TagValues": [
                "developer"
            ]
        }]
    }]
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Viewing the resources that a LF-Tag is assigned to](https://docs.aws.amazon.com/lake-formation/latest/dg/TBAC-view-tag-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchDatabasesByLfTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/search-databases-by-lf-tags.html)」を参照してください。

### `search-tables-by-lf-tags`
<a name="lakeformation_SearchTablesByLfTags_cli_2_topic"></a>

次のコード例は、`search-tables-by-lf-tags` を使用する方法を示しています。

**AWS CLI**  
**LFTags でテーブルリソースの検索を行うには**  
次の `search-tables-by-lf-tags` の例では、LFTag 式に一致するテーブルリソースの検索を行います。  

```
aws lakeformation search-tables-by-lf-tags \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "MaxResults": 2,
    "CatalogId": "123456789111",
    "Expression": [{
        "TagKey": "usergroup",
        "TagValues": [
            "developer"
        ]
    }]
}
```
出力:  

```
{
    "NextToken": "c2VhcmNoQWxsVGFnc0luVGFibGVzIjpmYWxzZX0=",
    "TableList": [{
        "Table": {
            "CatalogId": "123456789111",
            "DatabaseName": "tpc",
            "Name": "dl_tpc_item"
        },
        "LFTagOnDatabase": [{
            "CatalogId": "123456789111",
            "TagKey": "usergroup",
            "TagValues": [
                "developer"
            ]
        }],
        "LFTagsOnTable": [{
            "CatalogId": "123456789111",
            "TagKey": "usergroup",
            "TagValues": [
                "developer"
            ]
        }],
        "LFTagsOnColumns": [{
                "Name": "i_item_desc",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_container",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_wholesale_cost",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_manufact_id",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_brand_id",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_formulation",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_current_price",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_size",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_rec_start_date",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_manufact",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_item_sk",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_manager_id",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_item_id",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_class_id",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_class",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_category",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_category_id",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_brand",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_units",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_rec_end_date",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_color",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            },
            {
                "Name": "i_product_name",
                "LFTags": [{
                    "CatalogId": "123456789111",
                    "TagKey": "usergroup",
                    "TagValues": [
                        "developer"
                    ]
                }]
            }
        ]
    }]
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Viewing the resources that a LF-Tag is assigned to](https://docs.aws.amazon.com/lake-formation/latest/dg/TBAC-view-tag-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchTablesByLfTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/search-tables-by-lf-tags.html)」を参照してください。

### `start-query-planning`
<a name="lakeformation_StartQueryPlanning_cli_2_topic"></a>

次のコード例は、`start-query-planning` を使用する方法を示しています。

**AWS CLI**  
**クエリステートメントを処理するには**  
次の `start-query-planning` の例では、クエリステートメントを処理するリクエストを送信します。  

```
aws lakeformation start-query-planning \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "QueryPlanningContext": {
        "CatalogId": "012345678901",
        "DatabaseName": "tpc"
    },
    "QueryString": "select * from dl_tpc_household_demographics_gov where hd_income_band_sk=9"
}
```
出力:  

```
{
    "QueryId": "772a273f-4a62-4cda-8d98-69615ee8be9b"
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartQueryPlanning](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/start-query-planning.html)」を参照してください。

### `start-transaction`
<a name="lakeformation_StartTransaction_cli_2_topic"></a>

次のコード例は、`start-transaction` を使用する方法を示しています。

**AWS CLI**  
**新しいトランザクションを開始するには**  
次の `start-transaction` の例では、新しいトランザクションを開始し、そのトランザクション ID を返します。  

```
aws lakeformation start-transaction \
    --transaction-type = 'READ_AND_WRITE'
```
出力:  

```
{
    "TransactionId": "b014d972ca8347b89825e33c5774aec4"
}
```
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/start-transaction.html)」を参照してください。

### `update-lf-tag`
<a name="lakeformation_UpdateLfTag_cli_2_topic"></a>

次のコード例は、`update-lf-tag` を使用する方法を示しています。

**AWS CLI**  
**LF タグ定義を更新するには**  
次の `update-lf-tag` の例では、LF タグ定義を更新します。  

```
aws lakeformation update-lf-tag \
    --catalog-id '123456789111' \
    --tag-key 'usergroup' \
    --tag-values-to-add '["admin"]'
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Managing LF-Tags for metadata access control](https://docs.aws.amazon.com/lake-formation/latest/dg/managing-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLfTag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/update-lf-tag.html)」を参照してください。

### `update-table-objects`
<a name="lakeformation_UpdateTableObjects_cli_2_topic"></a>

次のコード例は、`update-table-objects` を使用する方法を示しています。

**AWS CLI**  
**管理対象テーブルのオブジェクトを変更するには**  
次の `update-table-objects` の例では、指定された管理対象テーブルに、提供された S3 オブジェクトを追加します。  

```
aws lakeformation update-table-objects \
    --cli-input-json file://input.json
```
`input.json` の内容:  

```
{
    "CatalogId": "012345678901",
    "DatabaseName": "tpc",
    "TableName": "dl_tpc_household_demographics_gov",
    "TransactionId": "12347a9f75424b9b915f6ff201d2a190",
    "WriteOperations": [{
        "AddObject": {
            "Uri": "s3://lf-data-lake-012345678901/target/dl_tpc_household_demographics_gov/run-unnamed-1-part-block-0-r-00000-snappy-ff26b17504414fe88b302cd795eabd00.parquet",
            "ETag": "1234ab1fc50a316b149b4e1f21a73800",
            "Size": 42200
        }
    }]
}
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lake Formation Developer Guide*」の「[Reading from and writing to the data lake within transactions](https://docs.aws.amazon.com/lake-formation/latest/dg/transaction-ops.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTableObjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lakeformation/update-table-objects.html)」を参照してください。

# を使用した Lambda の例 AWS CLI
<a name="cli_2_lambda_code_examples"></a>

次のコード例は、Lambda AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-layer-version-permission`
<a name="lambda_AddLayerVersionPermission_cli_2_topic"></a>

次のコード例は、`add-layer-version-permission` を使用する方法を示しています。

**AWS CLI**  
**レイヤーバージョンに対するアクセス許可を追加するには**  
次の `add-layer-version-permission` の例では、指定されたアカウントがレイヤー `my-layer` のバージョン 1 を使用するアクセス許可を付与します。  

```
aws lambda add-layer-version-permission \
    --layer-name my-layer \
    --statement-id xaccount \
    --action lambda:GetLayerVersion  \
    --principal 123456789012 \
    --version-number 1
```
出力:  

```
{
    "RevisionId": "35d87451-f796-4a3f-a618-95a3671b0a0c",
    "Statement":
    {
        "Sid":"xaccount",
        "Effect":"Allow",
        "Principal":{
            "AWS":"arn:aws:iam::210987654321:root"
        },
        "Action":"lambda:GetLayerVersion",
        "Resource":"arn:aws:lambda:us-east-2:123456789012:layer:my-layer:1"
    }
}
```
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddLayerVersionPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/add-layer-version-permission.html)」を参照してください。

### `add-permission`
<a name="lambda_AddPermission_cli_2_topic"></a>

次のコード例は、`add-permission` を使用する方法を示しています。

**AWS CLI**  
**既存の Lambda 関数に対するアクセス許可を追加するには**  
次の `add-permission` の例では、`my-function` という名前の関数を呼び出すためのアクセス許可を Amazon SNS サービスに付与します。  

```
aws lambda add-permission \
    --function-name my-function \
    --action lambda:InvokeFunction \
    --statement-id sns \
    --principal sns.amazonaws.com
```
出力:  

```
{
    "Statement":
    {
        "Sid":"sns",
        "Effect":"Allow",
        "Principal":{
            "Service":"sns.amazonaws.com"
        },
        "Action":"lambda:InvokeFunction",
        "Resource":"arn:aws:lambda:us-east-2:123456789012:function:my-function"
    }
}
```
詳細については、[Lambda デベロッパーガイドの AWS 「Lambda でのリソースベースのポリシーの使用](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/add-permission.html)」を参照してください。

### `create-alias`
<a name="lambda_CreateAlias_cli_2_topic"></a>

次のコード例は、`create-alias` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数のエイリアスを作成する方法**  
次の `create-alias` の例では、`my-function` Lambda 関数のバージョン 1 を参照する `LIVE` という名前のエイリアスを作成します。  

```
aws lambda create-alias \
    --function-name my-function \
    --description "alias for live version of function" \
    --function-version 1 \
    --name LIVE
```
出力:  

```
{
    "FunctionVersion": "1",
    "Name": "LIVE",
    "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:LIVE",
    "RevisionId": "873282ed-4cd3-4dc8-a069-d0c647e470c6",
    "Description": "alias for live version of function"
}
```
詳細については、[AWS 「Lambda デベロッパーガイド」の「Lambda 関数エイリアスの設定](https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html)」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/create-alias.html)」を参照してください。**

### `create-event-source-mapping`
<a name="lambda_CreateEventSourceMapping_cli_2_topic"></a>

次の例は、`create-event-source-mapping` を使用する方法を説明しています。

**AWS CLI**  
**イベントソースと AWS Lambda 関数間のマッピングを作成するには**  
次の `create-event-source-mapping` の例では、SQS キューと `my-function` Lambda 関数間のマッピングを作成します。  

```
aws lambda create-event-source-mapping \
    --function-name my-function \
    --batch-size 5 \
    --event-source-arn arn:aws:sqs:us-west-2:123456789012:mySQSqueue
```
出力:  

```
{
    "UUID": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
    "StateTransitionReason": "USER_INITIATED",
    "LastModified": 1569284520.333,
    "BatchSize": 5,
    "State": "Creating",
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "EventSourceArn": "arn:aws:sqs:us-west-2:123456789012:mySQSqueue"
}
```
詳細については、「*AWS Developer Guide*」の「[AWS Lambda Event Source Mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEventSourceMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/create-event-source-mapping.html)」を参照してください。

### `create-function`
<a name="lambda_CreateFunction_cli_2_topic"></a>

次のコード例は、`create-function` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数を作成するには**  
次の `create-function` の例では、`my-function` という名前の Lambda 関数を作成します。  

```
aws lambda create-function \
    --function-name my-function \
    --runtime nodejs22.x \
    --zip-file fileb://my-function.zip \
    --handler my-function.handler \
    --role arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-tges6bf4
```
`my-function.zip` の内容:  

```
This file is a deployment package that contains your function code and any dependencies.
```
出力:  

```
{
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "PFn4S+er27qk+UuZSTKEQfNKG/XNn7QJs90mJgq6oH8=",
    "FunctionName": "my-function",
    "CodeSize": 308,
    "RevisionId": "873282ed-4cd3-4dc8-a069-d0c647e470c6",
    "MemorySize": 128,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "Version": "$LATEST",
    "Role": "arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-zgur6bf4",
    "Timeout": 3,
    "LastModified": "2025-10-14T22:26:11.234+0000",
    "Handler": "my-function.handler",
    "Runtime": "nodejs22.x",
    "Description": ""
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[Lambda 関数のメモリを設定する](https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/create-function.html)」を参照してください。

### `delete-alias`
<a name="lambda_DeleteAlias_cli_2_topic"></a>

次のコード例は、`delete-alias` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数のエイリアスを削除する方法**  
次の `delete-alias` の例では、`my-function` Lambda 関数から `LIVE` という名前のエイリアスを削除します。  

```
aws lambda delete-alias \
    --function-name my-function \
    --name LIVE
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Lambda デベロッパーガイド」の「Lambda 関数エイリアスの設定](https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html)」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-alias.html)」を参照してください。**

### `delete-event-source-mapping`
<a name="lambda_DeleteEventSourceMapping_cli_2_topic"></a>

次の例は、`delete-event-source-mapping` を使用する方法を説明しています。

**AWS CLI**  
**イベントソースと AWS Lambda 関数間のマッピングを削除するには**  
次の `delete-event-source-mapping` の例では、SQS キューと `my-function` Lambda 関数間のマッピングを削除します。  

```
aws lambda delete-event-source-mapping \
    --uuid  a1b2c3d4-5678-90ab-cdef-11111EXAMPLE
```
出力:  

```
{
    "UUID": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
    "StateTransitionReason": "USER_INITIATED",
    "LastModified": 1569285870.271,
    "BatchSize": 5,
    "State": "Deleting",
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "EventSourceArn": "arn:aws:sqs:us-west-2:123456789012:mySQSqueue"
}
```
詳細については、「*AWS Developer Guide*」の「[AWS Lambda Event Source Mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEventSourceMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-event-source-mapping.html)」を参照してください。

### `delete-function-concurrency`
<a name="lambda_DeleteFunctionConcurrency_cli_2_topic"></a>

次のコード例は、`delete-function-concurrency` を使用する方法を示しています。

**AWS CLI**  
**関数から同時実行制限を削除する方法**  
次の `delete-function-concurrency` の例では、予約済みの同時実行制限を `my-function` 関数から削除します。  

```
aws lambda delete-function-concurrency \
    --function-name  my-function
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lambda デベロッパーガイド*」の「[Lambda 関数の同時実行の予約](https://docs.aws.amazon.com/lambda/latest/dg/per-function-concurrency.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFunctionConcurrency](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-function-concurrency.html)」を参照してください。

### `delete-function-event-invoke-config`
<a name="lambda_DeleteFunctionEventInvokeConfig_cli_2_topic"></a>

次のコード例は、`delete-function-event-invoke-config` を使用する方法を示しています。

**AWS CLI**  
**非同期呼び出し設定を削除するには**  
次の `delete-function-event-invoke-config` の例では、指定された関数の `GREEN` エイリアスの非同期呼び出し設定を削除します。  

```
aws lambda delete-function-event-invoke-config --function-name my-function:GREEN
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFunctionEventInvokeConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-function-event-invoke-config.html)」を参照してください。

### `delete-function`
<a name="lambda_DeleteFunction_cli_2_topic"></a>

次のコード例は、`delete-function` を使用する方法を示しています。

**AWS CLI**  
**例 1: Lambda 関数を関数名で削除するには**  
次の `delete-function` の例では、関数名を指定して `my-function` という Lambda 関数を削除します。  

```
aws lambda delete-function \
    --function-name my-function
```
このコマンドは何も出力しません。  
**例 2: Lambda 関数を関数 ARN で削除するには**  
次の `delete-function` の例では、関数 ARN を指定して `my-function` という Lambda 関数を削除します。  

```
aws lambda delete-function \
    --function-name arn:aws:lambda:us-west-2:123456789012:function:my-function
```
このコマンドは何も出力しません。  
**例 3: Lambda 関数を関数 ARN の一部で削除するには**  
次の `delete-function` の例では、関数 ARN の一部を指定して `my-function` という Lambda 関数を削除します。  

```
aws lambda delete-function \
    --function-name 123456789012:function:my-function
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lambda デベロッパーガイド*」の「[AWS Lambda 関数の設定](https://docs.aws.amazon.com/lambda/latest/dg/resource-model.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-function.html)」を参照してください。

### `delete-layer-version`
<a name="lambda_DeleteLayerVersion_cli_2_topic"></a>

次のコード例は、`delete-layer-version` を使用する方法を示しています。

**AWS CLI**  
**Lambda レイヤーのバージョンを削除するには**  
次の `delete-layer-version` の例では、`my-layer` という名前のレイヤーのバージョン 2 を削除します。  

```
aws lambda delete-layer-version \
    --layer-name my-layer \
    --version-number 2
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLayerVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-layer-version.html)」を参照してください。

### `delete-provisioned-concurrency-config`
<a name="lambda_DeleteProvisionedConcurrencyConfig_cli_2_topic"></a>

次のコード例は、`delete-provisioned-concurrency-config` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされた同時実行数の設定を削除する方法**  
次の `delete-provisioned-concurrency-config` の例では、指定した関数の `GREEN` エイリアスのプロビジョニングされた同時実行設定を削除します。  

```
aws lambda delete-provisioned-concurrency-config \
    --function-name my-function \
    --qualifier GREEN
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProvisionedConcurrencyConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/delete-provisioned-concurrency-config.html)」を参照してください。

### `get-account-settings`
<a name="lambda_GetAccountSettings_cli_2_topic"></a>

次の例は、`get-account-settings` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョンのアカウントに関する詳細を取得するには**  
次の `get-account-settings` の例では、アカウントの Lambda 制限および使用情報を表示します。  

```
aws lambda get-account-settings
```
出力:  

```
{
    "AccountLimit": {
       "CodeSizeUnzipped": 262144000,
       "UnreservedConcurrentExecutions": 1000,
       "ConcurrentExecutions": 1000,
       "CodeSizeZipped": 52428800,
       "TotalCodeSize": 80530636800
    },
    "AccountUsage": {
       "FunctionCount": 4,
       "TotalCodeSize": 9426
    }
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[AWS Lambda の制限](https://docs.aws.amazon.com/lambda/latest/dg/limits.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccountSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-account-settings.html)」を参照してください。

### `get-alias`
<a name="lambda_GetAlias_cli_2_topic"></a>

次のコード例は、`get-alias` を使用する方法を示しています。

**AWS CLI**  
**関数エイリアスに関する詳細を取得する方法**  
次の `get-alias` の例では、`my-function` Lambda 関数に `LIVE` という名前のエイリアスの詳細が表示されます。  

```
aws lambda get-alias \
    --function-name my-function \
    --name LIVE
```
出力:  

```
{
    "FunctionVersion": "3",
    "Name": "LIVE",
    "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:LIVE",
    "RevisionId": "594f41fb-b85f-4c20-95c7-6ca5f2a92c93",
    "Description": "alias for live version of function"
}
```
詳細については、[AWS 「Lambda デベロッパーガイド」の「Lambda 関数エイリアスの設定](https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-alias.html)」を参照してください。

### `get-event-source-mapping`
<a name="lambda_GetEventSourceMapping_cli_2_topic"></a>

次のコード例は、`get-event-source-mapping` を使用する方法を示しています。

**AWS CLI**  
**イベントソースマッピングの詳細を取得するには**  
次の `get-event-source-mapping` の例では、SQS キューと `my-function` Lambda 関数間のマッピングの詳細を表示します。  

```
aws lambda get-event-source-mapping \
    --uuid "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
```
出力:  

```
{
    "UUID": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
    "StateTransitionReason": "USER_INITIATED",
    "LastModified": 1569284520.333,
    "BatchSize": 5,
    "State": "Enabled",
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "EventSourceArn": "arn:aws:sqs:us-west-2:123456789012:mySQSqueue"
}
```
詳細については、「*AWS Developer Guide*」の「[AWS Lambda Event Source Mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEventSourceMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-event-source-mapping.html)」を参照してください。

### `get-function-concurrency`
<a name="lambda_GetFunctionConcurrency_cli_2_topic"></a>

次のコード例は、`get-function-concurrency` を使用する方法を示しています。

**AWS CLI**  
**関数の予約済み同時実行設定を表示する方法**  
次の `get-function-concurrency` の例では、指定した関数の予約済み同時実行設定を取得します。  

```
aws lambda get-function-concurrency \
    --function-name my-function
```
出力:  

```
{
    "ReservedConcurrentExecutions": 250
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFunctionConcurrency](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-function-concurrency.html)」を参照してください。

### `get-function-configuration`
<a name="lambda_GetFunctionConfiguration_cli_2_topic"></a>

次のコード例は、`get-function-configuration` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数のバージョン固有設定を取得する方法**  
次の `get-function-configuration` の例では、`my-function` 関数のバージョン 2 の設定が表示されます。  

```
aws lambda get-function-configuration \
    --function-name  my-function:2
```
出力:  

```
{
    "FunctionName": "my-function",
    "LastModified": "2019-09-26T20:28:40.438+0000",
    "RevisionId": "e52502d4-9320-4688-9cd6-152a6ab7490d",
    "MemorySize": 256,
    "Version": "2",
    "Role": "arn:aws:iam::123456789012:role/service-role/my-function-role-uy3l9qyq",
    "Timeout": 3,
    "Runtime": "nodejs10.x",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "5tT2qgzYUHaqwR716pZ2dpkn/0J1FrzJmlKidWoaCgk=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "VpcId": "",
        "SecurityGroupIds": []
    },
    "CodeSize": 304,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:2",
    "Handler": "index.handler"
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[AWS Lambda 関数の設定](https://docs.aws.amazon.com/lambda/latest/dg/resource-model.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFunctionConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-function-configuration.html)」を参照してください。

### `get-function-event-invoke-config`
<a name="lambda_GetFunctionEventInvokeConfig_cli_2_topic"></a>

次のコード例は、`get-function-event-invoke-config` を使用する方法を示しています。

**AWS CLI**  
**非同期呼び出し設定を表示するには**  
次の `get-function-event-invoke-config` の例では、指定された関数の `BLUE` エイリアスの非同期呼び出し設定を取得します。  

```
aws lambda get-function-event-invoke-config \
    --function-name my-function:BLUE
```
出力:  

```
{
    "LastModified": 1577824396.653,
    "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:BLUE",
    "MaximumRetryAttempts": 0,
    "MaximumEventAgeInSeconds": 3600,
    "DestinationConfig": {
        "OnSuccess": {},
        "OnFailure": {
            "Destination": "arn:aws:sqs:us-east-2:123456789012:failed-invocations"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFunctionEventInvokeConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-function-event-invoke-config.html)」を参照してください。

### `get-function`
<a name="lambda_GetFunction_cli_2_topic"></a>

次のコード例は、`get-function` を使用する方法を示しています。

**AWS CLI**  
**関数に関する情報を取得するには**  
次の例 `get-function` では、`my-function` 関数の情報が表示されます。  

```
aws lambda get-function \
    --function-name  my-function
```
出力:  

```
{
    "Concurrency": {
        "ReservedConcurrentExecutions": 100
    },
    "Code": {
        "RepositoryType": "S3",
        "Location": "https://awslambda-us-west-2-tasks.s3.us-west-2.amazonaws.com/snapshots/123456789012/my-function..."
    },
    "Configuration": {
        "TracingConfig": {
            "Mode": "PassThrough"
        },
        "Version": "$LATEST",
        "CodeSha256": "5tT2qgzYUHoqwR616pZ2dpkn/0J1FrzJmlKidWaaCgk=",
        "FunctionName": "my-function",
        "VpcConfig": {
            "SubnetIds": [],
            "VpcId": "",
            "SecurityGroupIds": []
        },
        "MemorySize": 128,
        "RevisionId": "28f0fb31-5c5c-43d3-8955-03e76c5c1075",
        "CodeSize": 304,
        "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
        "Handler": "index.handler",
        "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
        "Timeout": 3,
        "LastModified": "2025-09-24T18:20:35.054+0000",
        "Runtime": "nodejs22.x",
        "Description": ""
    }
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[Lambda 関数のメモリを設定する](https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-function.html)」を参照してください。

### `get-layer-version-by-arn`
<a name="lambda_GetLayerVersionByArn_cli_2_topic"></a>

次のコード例は、`get-layer-version-by-arn` を使用する方法を示しています。

**AWS CLI**  
**Lambda レイヤーバージョンに関する情報を取得するには**  
次の `get-layer-version-by-arn` の例では、指定された Amazon リソースネーム (ARN) を持つレイヤーバージョンに関する情報を表示します。  

```
aws lambda get-layer-version-by-arn \
    --arn "arn:aws:lambda:us-west-2:123456789012:layer:AWSLambda-Python311-SciPy1x:2"
```
出力:  

```
{
    "LayerVersionArn": "arn:aws:lambda:us-west-2:123456789012:layer:AWSLambda-Python311-SciPy1x:2",
    "Description": "AWS Lambda SciPy layer for Python 3.11 (scipy-1.1.0, numpy-1.15.4) https://github.com/scipy/scipy/releases/tag/v1.1.0 https://github.com/numpy/numpy/releases/tag/v1.15.4",
    "CreatedDate": "2023-10-12T10:09:38.398+0000",
    "LayerArn": "arn:aws:lambda:us-west-2:123456789012:layer:AWSLambda-Python311-SciPy1x",
    "Content": {
        "CodeSize": 41784542,
        "CodeSha256": "GGmv8ocUw4cly0T8HL0Vx/f5V4RmSCGNjDIslY4VskM=",
        "Location": "https://awslambda-us-west-2-layers.s3.us-west-2.amazonaws.com/snapshots/123456789012/..."
    },
    "Version": 2,
    "CompatibleRuntimes": [
        "python3.11"
    ],
    "LicenseInfo": "SciPy: https://github.com/scipy/scipy/blob/main/LICENSE.txt, NumPy: https://github.com/numpy/numpy/blob/main/LICENSE.txt"
}
```
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLayerVersionByArn](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-layer-version-by-arn.html)」を参照してください。

### `get-layer-version-policy`
<a name="lambda_GetLayerVersionPolicy_cli_2_topic"></a>

次のコード例は、`get-layer-version-policy` を使用する方法を示しています。

**AWS CLI**  
**Lambda レイヤーバージョンのアクセス許可ポリシーを取得するには**  
次の `get-layer-version-policy` の例では、`my-layer` という名前のレイヤーのバージョン 1 に関するポリシー情報を表示します。  

```
aws lambda get-layer-version-policy \
    --layer-name my-layer \
    --version-number 1
```
出力:  

```
{
    "Policy": {
        "Version":"2012-10-17",		 	 	 
        "Id":"default",
        "Statement":
        [
            {
                "Sid":"xaccount",
                "Effect":"Allow",
                "Principal": {"AWS":"arn:aws:iam::123456789012:root"},
                "Action":"lambda:GetLayerVersion",
                "Resource":"arn:aws:lambda:us-west-2:123456789012:layer:my-layer:1"
            }
        ]
    },
    "RevisionId": "c68f21d2-cbf0-4026-90f6-1375ee465cd0"
}
```
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLayerVersionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-layer-version-policy.html)」を参照してください。

### `get-layer-version`
<a name="lambda_GetLayerVersion_cli_2_topic"></a>

次のコード例は、`get-layer-version` を使用する方法を示しています。

**AWS CLI**  
**Lambda レイヤーバージョンに関する情報を取得するには**  
次の `get-layer-version` の例では、`my-layer` という名前のレイヤーのバージョン 1 の情報を表示します。  

```
aws lambda get-layer-version \
    --layer-name my-layer \
    --version-number 1
```
出力:  

```
{
    "Content": {
        "Location": "https://awslambda-us-east-2-layers.s3.us-east-2.amazonaws.com/snapshots/123456789012/my-layer-4aaa2fbb-ff77-4b0a-ad92-5b78a716a96a?versionId=27iWyA73cCAYqyH...",
        "CodeSha256": "tv9jJO+rPbXUUXuRKi7CwHzKtLDkDRJLB3cC3Z/ouXo=",
        "CodeSize": 169
    },
    "LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer",
    "LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:1",
    "Description": "My Python layer",
    "CreatedDate": "2018-11-14T23:03:52.894+0000",
    "Version": 1,
    "LicenseInfo": "MIT",
    "CompatibleRuntimes": [
        "python3.10",
        "python3.11"
    ]
}
```
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLayerVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-layer-version.html)」を参照してください。

### `get-policy`
<a name="lambda_GetPolicy_cli_2_topic"></a>

次のコード例は、`get-policy` を使用する方法を示しています。

**AWS CLI**  
**関数、バージョン、エイリアスのリソースベースの IAM ポリシーを取得する方法**  
次の `get-policy` の例では、`my-function` Lambda 関数に関する情報が表示されます。  

```
aws lambda get-policy \
    --function-name my-function
```
出力:  

```
{
    "Policy": {
        "Version":"2012-10-17",		 	 	 
        "Id":"default",
        "Statement":
        [
            {
                "Sid":"iot-events",
                "Effect":"Allow",
                "Principal": {"Service":"iotevents.amazonaws.com"},
                "Action":"lambda:InvokeFunction",
                "Resource":"arn:aws:lambda:us-west-2:123456789012:function:my-function"
            }
        ]
    },
    "RevisionId": "93017fc9-59cb-41dc-901b-4845ce4bf668"
}
```
詳細については、[Lambda デベロッパーガイドの AWS 「Lambda でのリソースベースのポリシーの使用](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-policy.html)」を参照してください。

### `get-provisioned-concurrency-config`
<a name="lambda_GetProvisionedConcurrencyConfig_cli_2_topic"></a>

次のコード例は、`get-provisioned-concurrency-config` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされた同時実行設定を表示する方法**  
次の `get-provisioned-concurrency-config` の例では、指定した関数の `BLUE` エイリアスにプロビジョニングされた同時実行設定の詳細が表示されます。  

```
aws lambda get-provisioned-concurrency-config \
    --function-name my-function \
    --qualifier BLUE
```
出力:  

```
{
    "RequestedProvisionedConcurrentExecutions": 100,
    "AvailableProvisionedConcurrentExecutions": 100,
    "AllocatedProvisionedConcurrentExecutions": 100,
    "Status": "READY",
    "LastModified": "2019-12-31T20:28:49+0000"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetProvisionedConcurrencyConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/get-provisioned-concurrency-config.html)」を参照してください。

### `invoke`
<a name="lambda_Invoke_cli_2_topic"></a>

次のコード例は、`invoke` を使用する方法を示しています。

**AWS CLI**  
**例 1: Lambda 関数を同期的に呼び出すには**  
次の例 `invoke` では、`my-function` 関数を同期的に呼び出します。CLI バージョン 2 AWS を使用している場合は、 `cli-binary-format`オプションが必要です。詳細については、「*AWS コマンドラインインターフェイスのユーザーガイド*」の「[AWS CLI でサポートされているグローバルコマンドラインオプション](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-options.html#cli-configure-options-list)」を参照してください。  

```
aws lambda invoke \
    --function-name my-function \
    --cli-binary-format raw-in-base64-out \
    --payload '{ "name": "Bob" }' \
    response.json
```
出力:  

```
{
    "ExecutedVersion": "$LATEST",
    "StatusCode": 200
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[Lambda 関数を同期的に呼び出す](https://docs.aws.amazon.com/lambda/latest/dg/invocation-sync.html)」を参照してください。  
**例 2: Lambda 関数を非同期で呼び出すには**  
次の例 `invoke` では、`my-function` 関数を非同期で呼び出します。CLI バージョン 2 AWS を使用している場合は、 `cli-binary-format`オプションが必要です。詳細については、「*AWS コマンドラインインターフェイスのユーザーガイド*」の「[AWS CLI でサポートされているグローバルコマンドラインオプション](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-options.html#cli-configure-options-list)」を参照してください。  

```
aws lambda invoke \
    --function-name my-function \
    --invocation-type Event \
    --cli-binary-format raw-in-base64-out \
    --payload '{ "name": "Bob" }' \
    response.json
```
出力:  

```
{
    "StatusCode": 202
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[Lambda 関数を非同期的に呼び出す](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Invoke](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/invoke.html)」を参照してください。

### `list-aliases`
<a name="lambda_ListAliases_cli_2_topic"></a>

次のコード例は、`list-aliases` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数のエイリアスのリストを取得するには**  
次の `list-aliases` の例では、`my-function` Lambda 関数のエイリアスのリストを表示します。  

```
aws lambda list-aliases \
    --function-name my-function
```
出力:  

```
{
    "Aliases": [
        {
            "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:BETA",
            "RevisionId": "a410117f-ab16-494e-8035-7e204bb7933b",
            "FunctionVersion": "2",
            "Name": "BETA",
            "Description": "alias for beta version of function"
        },
        {
            "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:LIVE",
            "RevisionId": "21d40116-f8b1-40ba-9360-3ea284da1bb5",
            "FunctionVersion": "1",
            "Name": "LIVE",
            "Description": "alias for live version of function"
        }
    ]
}
```
詳細については、[AWS 「Lambda デベロッパーガイド」の「Lambda 関数エイリアスの設定](https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html)」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListAliases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-aliases.html)」を参照してください。**

### `list-event-source-mappings`
<a name="lambda_ListEventSourceMappings_cli_2_topic"></a>

次のコード例は、`list-event-source-mappings` を使用する方法を示しています。

**AWS CLI**  
**関数のイベントソースマッピングを一覧表示するには**  
次の `list-event-source-mappings` の例では、`my-function` Lambda 関数のイベントソースマッピングのリストを表示します。  

```
aws lambda list-event-source-mappings \
    --function-name my-function
```
出力:  

```
{
    "EventSourceMappings": [
        {
            "UUID": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
            "StateTransitionReason": "USER_INITIATED",
            "LastModified": 1569284520.333,
            "BatchSize": 5,
            "State": "Enabled",
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
            "EventSourceArn": "arn:aws:sqs:us-west-2:123456789012:mySQSqueue"
        }
    ]
}
```
詳細については、「*AWS Developer Guide*」の「[AWS Lambda Event Source Mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEventSourceMappings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-event-source-mappings.html)」を参照してください。

### `list-function-event-invoke-configs`
<a name="lambda_ListFunctionEventInvokeConfigs_cli_2_topic"></a>

次のコード例は、`list-function-event-invoke-configs` を使用する方法を示しています。

**AWS CLI**  
**非同期呼び出し設定のリストを表示するには**  
次の `list-function-event-invoke-configs` の例では、指定された関数の非同期呼び出し設定を一覧表示します。  

```
aws lambda list-function-event-invoke-configs \
    --function-name my-function
```
出力:  

```
{
    "FunctionEventInvokeConfigs": [
        {
            "LastModified": 1577824406.719,
            "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:GREEN",
            "MaximumRetryAttempts": 2,
            "MaximumEventAgeInSeconds": 1800
        },
        {
            "LastModified": 1577824396.653,
            "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:BLUE",
            "MaximumRetryAttempts": 0,
            "MaximumEventAgeInSeconds": 3600
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFunctionEventInvokeConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-function-event-invoke-configs.html)」を参照してください。

### `list-functions`
<a name="lambda_ListFunctions_cli_2_topic"></a>

次のコード例は、`list-functions` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数の一覧を取得するには**  
次の例 `list-functions` では、現在のユーザーのすべての関数を一覧表示します。  

```
aws lambda list-functions
```
出力:  

```
{
    "Functions": [
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "dBG9m8SGdmlEjw/JYXlhhvCrAv5TxvXsbL/RMr0fT/I=",
            "FunctionName": "helloworld",
            "MemorySize": 128,
            "RevisionId": "1718e831-badf-4253-9518-d0644210af7b",
            "CodeSize": 294,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:helloworld",
            "Handler": "helloworld.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-zgur6bf4",
            "Timeout": 3,
            "LastModified": "2025-09-23T18:32:33.857+0000",
            "Runtime": "nodejs22.x",
            "Description": ""
        },
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "sU0cJ2/hOZevwV/lTxCuQqK3gDZP3i8gUoqUUVRmY6E=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "93017fc9-59cb-41dc-901b-4845ce4bf668",
            "CodeSize": 266,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2025-10-01T16:47:28.490+0000",
            "Runtime": "nodejs22.x",
            "Description": ""
        },
        {
            "Layers": [
                {
                    "CodeSize": 41784542,
                    "Arn": "arn:aws:lambda:us-west-2:420165488524:layer:AWSLambda-Python37-SciPy1x:2"
                },
                {
                    "CodeSize": 4121,
                    "Arn": "arn:aws:lambda:us-west-2:123456789012:layer:pythonLayer:1"
                }
            ],
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "ZQukCqxtkqFgyF2cU41Avj99TKQ/hNihPtDtRcc08mI=",
            "FunctionName": "my-python-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 128,
            "RevisionId": "80b4eabc-acf7-4ea8-919a-e874c213707d",
            "CodeSize": 299,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-python-function",
            "Handler": "lambda_function.lambda_handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/my-python-function-role-z5g7dr6n",
            "Timeout": 3,
            "LastModified": "2025-10-01T19:40:41.643+0000",
            "Runtime": "python3.11",
            "Description": ""
        }
    ]
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[Lambda 関数のメモリを設定する](https://docs.aws.amazon.com/lambda/latest/dg/configuration-memory.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFunctions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-functions.html)」を参照してください。

### `list-layer-versions`
<a name="lambda_ListLayerVersions_cli_2_topic"></a>

次の例は、`list-layer-versions` を使用する方法を説明しています。

**AWS CLI**  
** AWS Lambda レイヤーのバージョンを一覧表示するには**  
次の `list-layers-versions` の例では、`my-layer` という名前のレイヤーのバージョンに関する情報を表示します。  

```
aws lambda list-layer-versions \
    --layer-name my-layer
```
出力:  

```
{
    "Layers": [
        {
            "LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:2",
            "Version": 2,
            "Description": "My layer",
            "CreatedDate": "2023-11-15T00:37:46.592+0000",
            "CompatibleRuntimes": [
                "python3.10",
                "python3.11"
            ]
        }
    ]
}
```
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLayerVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-layer-versions.html)」を参照してください。

### `list-layers`
<a name="lambda_ListLayers_cli_2_topic"></a>

次のコード例は、`list-layers` を使用する方法を示しています。

**AWS CLI**  
**関数のランタイムと互換性のあるレイヤーを一覧表示するには**  
次の `list-layers` の例では、Python 3.11 ランタイムと互換性のあるレイヤーに関する情報を表示します。  

```
aws lambda list-layers \
    --compatible-runtime python3.11
```
出力:  

```
{
    "Layers": [
        {
            "LayerName": "my-layer",
            "LayerArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer",
            "LatestMatchingVersion": {
                "LayerVersionArn": "arn:aws:lambda:us-east-2:123456789012:layer:my-layer:2",
                "Version": 2,
                "Description": "My layer",
                "CreatedDate": "2023-11-15T00:37:46.592+0000",
                "CompatibleRuntimes": [
                    "python3.10",
                    "python3.11"
                ]
            }
        }
    ]
}
```
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLayers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-layers.html)」を参照してください。

### `list-provisioned-concurrency-configs`
<a name="lambda_ListProvisionedConcurrencyConfigs_cli_2_topic"></a>

次のコード例は、`list-provisioned-concurrency-configs` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされた同時実行設定のリストを取得する方法**  
次の `list-provisioned-concurrency-configs` の例では、指定された関数にプロビジョニングされた同時実行設定がリストされます。  

```
aws lambda list-provisioned-concurrency-configs \
    --function-name my-function
```
出力:  

```
{
    "ProvisionedConcurrencyConfigs": [
        {
            "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:GREEN",
            "RequestedProvisionedConcurrentExecutions": 100,
            "AvailableProvisionedConcurrentExecutions": 100,
            "AllocatedProvisionedConcurrentExecutions": 100,
            "Status": "READY",
            "LastModified": "2019-12-31T20:29:00+0000"
        },
        {
            "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:BLUE",
            "RequestedProvisionedConcurrentExecutions": 100,
            "AvailableProvisionedConcurrentExecutions": 100,
            "AllocatedProvisionedConcurrentExecutions": 100,
            "Status": "READY",
            "LastModified": "2019-12-31T20:28:49+0000"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProvisionedConcurrencyConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-provisioned-concurrency-configs.html)」を参照してください。

### `list-tags`
<a name="lambda_ListTags_cli_2_topic"></a>

次のコード例は、`list-tags` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数のタグのリストを取得する方法**  
次の `list-tags` の例では、`my-function` Lambda 関数にアタッチされたタグが表示されます。  

```
aws lambda list-tags \
    --resource arn:aws:lambda:us-west-2:123456789012:function:my-function
```
出力:  

```
{
    "Tags": {
        "Category": "Web Tools",
        "Department": "Sales"
    }
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[ Lambda 関数のタグ付け](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-tags.html)」を参照してください。

### `list-versions-by-function`
<a name="lambda_ListVersionsByFunction_cli_2_topic"></a>

次のコード例は、`list-versions-by-function` を使用する方法を示しています。

**AWS CLI**  
**関数のバージョンのリストを取得する方法**  
次の `list-versions-by-function` の例は、`my-function` Lambda 関数のバージョンのリストが表示されます。  

```
aws lambda list-versions-by-function \
    --function-name my-function
```
出力:  

```
{
    "Versions": [
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "$LATEST",
            "CodeSha256": "sU0cJ2/hOZevwV/lTxCuQqK3gDZP3i8gUoqUUVRmY6E=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "93017fc9-59cb-41dc-901b-4845ce4bf668",
            "CodeSize": 266,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:$LATEST",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2019-10-01T16:47:28.490+0000",
            "Runtime": "nodejs10.x",
            "Description": ""
        },
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "1",
            "CodeSha256": "5tT2qgzYUHoqwR616pZ2dpkn/0J1FrzJmlKidWaaCgk=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "949c8914-012e-4795-998c-e467121951b1",
            "CodeSize": 304,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:1",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2019-09-26T20:28:40.438+0000",
            "Runtime": "nodejs10.x",
            "Description": "new version"
        },
        {
            "TracingConfig": {
                "Mode": "PassThrough"
            },
            "Version": "2",
            "CodeSha256": "sU0cJ2/hOZevwV/lTxCuQqK3gDZP3i8gUoqUUVRmY6E=",
            "FunctionName": "my-function",
            "VpcConfig": {
                "SubnetIds": [],
                "VpcId": "",
                "SecurityGroupIds": []
            },
            "MemorySize": 256,
            "RevisionId": "cd669f21-0f3d-4e1c-9566-948837f2e2ea",
            "CodeSize": 266,
            "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:2",
            "Handler": "index.handler",
            "Role": "arn:aws:iam::123456789012:role/service-role/helloWorldPython-role-uy3l9qyq",
            "Timeout": 3,
            "LastModified": "2019-10-01T16:47:28.490+0000",
            "Runtime": "nodejs10.x",
            "Description": "newer version"
        }
    ]
}
```
詳細については、[AWS 「 Lambda デベロッパーガイド」の「Lambda 関数エイリアスの設定](https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVersionsByFunction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/list-versions-by-function.html)」を参照してください。

### `publish-layer-version`
<a name="lambda_PublishLayerVersion_cli_2_topic"></a>

次のコード例は、`publish-layer-version` を使用する方法を示しています。

**AWS CLI**  
**Lambda レイヤーバージョンを作成するには**  
次の `publish-layer-version` の例では、新しい Python ライブラリレイヤーバージョンを作成します。このコマンドは、指定された S3 バケット内の `layer.zip` という名前のファイルのレイヤーコンテンツを取得します。  

```
aws lambda publish-layer-version \
    --layer-name my-layer \
    --description "My Python layer" \
    --license-info "MIT" \
    --content S3Bucket=lambda-layers-us-west-2-123456789012,S3Key=layer.zip \
    --compatible-runtimes python3.10 python3.11
```
出力:  

```
{
    "Content": {
        "Location": "https://awslambda-us-west-2-layers.s3.us-west-2.amazonaws.com/snapshots/123456789012/my-layer-4aaa2fbb-ff77-4b0a-ad92-5b78a716a96a?versionId=27iWyA73cCAYqyH...",
        "CodeSha256": "tv9jJO+rPbXUUXuRKi7CwHzKtLDkDRJLB3cC3Z/ouXo=",
        "CodeSize": 169
    },
    "LayerArn": "arn:aws:lambda:us-west-2:123456789012:layer:my-layer",
    "LayerVersionArn": "arn:aws:lambda:us-west-2:123456789012:layer:my-layer:1",
    "Description": "My Python layer",
    "CreatedDate": "2023-11-14T23:03:52.894+0000",
    "Version": 1,
    "LicenseInfo": "MIT",
    "CompatibleRuntimes": [
        "python3.10",
        "python3.11"
    ]
}
```
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PublishLayerVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/publish-layer-version.html)」を参照してください。

### `publish-version`
<a name="lambda_PublishVersion_cli_2_topic"></a>

次のコード例は、`publish-version` を使用する方法を示しています。

**AWS CLI**  
**関数の新しいバージョンを発行する方法**  
次の `publish-version` の例では、`my-function` Lambda 関数の新しいバージョンを発行します。  

```
aws lambda publish-version \
    --function-name my-function
```
出力:  

```
{
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "dBG9m8SGdmlEjw/JYXlhhvCrAv5TxvXsbL/RMr0fT/I=",
    "FunctionName": "my-function",
    "CodeSize": 294,
    "RevisionId": "f31d3d39-cc63-4520-97d4-43cd44c94c20",
    "MemorySize": 128,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:3",
    "Version": "2",
    "Role": "arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-zgur6bf4",
    "Timeout": 3,
    "LastModified": "2019-09-23T18:32:33.857+0000",
    "Handler": "my-function.handler",
    "Runtime": "nodejs10.x",
    "Description": ""
}
```
詳細については、[AWS 「 Lambda デベロッパーガイド」の「Lambda 関数エイリアスの設定](https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PublishVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/publish-version.html)」を参照してください。

### `put-function-concurrency`
<a name="lambda_PutFunctionConcurrency_cli_2_topic"></a>

次のコード例は、`put-function-concurrency` を使用する方法を示しています。

**AWS CLI**  
**関数に予約済み同時実行制限を設定する方法**  
次の `put-function-concurrency` の例では、`my-function` 関数に 100 個の予約済み同時実行数を設定します。  

```
aws lambda put-function-concurrency \
    --function-name  my-function  \
    --reserved-concurrent-executions 100
```
出力:  

```
{
    "ReservedConcurrentExecutions": 100
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[Lambda 関数の同時実行の予約](https://docs.aws.amazon.com/lambda/latest/dg/per-function-concurrency.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutFunctionConcurrency](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/put-function-concurrency.html)」を参照してください。

### `put-function-event-invoke-config`
<a name="lambda_PutFunctionEventInvokeConfig_cli_2_topic"></a>

次のコード例は、`put-function-event-invoke-config` を使用する方法を示しています。

**AWS CLI**  
**非同期呼び出しのエラー処理を設定するには**  
次の `put-function-event-invoke-config` の例では、最大イベント期間を 1 時間に設定し、指定された関数の再試行を無効にします。  

```
aws lambda put-function-event-invoke-config \
    --function-name my-function \
    --maximum-event-age-in-seconds 3600 \
    --maximum-retry-attempts 0
```
出力:  

```
{
    "LastModified": 1573686021.479,
    "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:$LATEST",
    "MaximumRetryAttempts": 0,
    "MaximumEventAgeInSeconds": 3600,
    "DestinationConfig": {
        "OnSuccess": {},
        "OnFailure": {}
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutFunctionEventInvokeConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/put-function-event-invoke-config.html)」を参照してください。

### `put-provisioned-concurrency-config`
<a name="lambda_PutProvisionedConcurrencyConfig_cli_2_topic"></a>

次のコード例は、`put-provisioned-concurrency-config` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングされた同時実行数を配分する方法**  
次の `put-provisioned-concurrency-config` の例では、指定した関数の `BLUE` エイリアスに 100 個のプロビジョニングされた同時実行数を割り当てます。  

```
aws lambda put-provisioned-concurrency-config \
    --function-name my-function \
    --qualifier BLUE \
    --provisioned-concurrent-executions 100
```
出力:  

```
{
    "Requested ProvisionedConcurrentExecutions": 100,
    "Allocated ProvisionedConcurrentExecutions": 0,
    "Status": "IN_PROGRESS",
    "LastModified": "2019-11-21T19:32:12+0000"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutProvisionedConcurrencyConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/put-provisioned-concurrency-config.html)」を参照してください。

### `remove-layer-version-permission`
<a name="lambda_RemoveLayerVersionPermission_cli_2_topic"></a>

次のコード例は、`remove-layer-version-permission` を使用する方法を示しています。

**AWS CLI**  
**レイヤーバージョンのアクセス許可を削除するには**  
次の `remove-layer-version-permission` の例では、アカウントがレイヤーバージョンを設定するアクセス許可を削除します。  

```
aws lambda remove-layer-version-permission \
    --layer-name my-layer \
    --statement-id xaccount \
    --version-number 1
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lambda Developer Guide*」の「[AWS Lambda Layers](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveLayerVersionPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/remove-layer-version-permission.html)」を参照してください。

### `remove-permission`
<a name="lambda_RemovePermission_cli_2_topic"></a>

次のコード例は、`remove-permission` を使用する方法を示しています。

**AWS CLI**  
**既存の Lambda 関数から許可を削除する方法**  
次の `remove-permission` の例では、`my-function` という名前の関数を呼び出す許可を削除します。  

```
aws lambda remove-permission \
    --function-name my-function \
    --statement-id sns
```
このコマンドでは何も出力されません。  
詳細については、[Lambda デベロッパーガイドの AWS 「Lambda でのリソースベースのポリシーの使用](https://docs.aws.amazon.com/lambda/latest/dg/access-control-resource-based.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemovePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/remove-permission.html)」を参照してください。

### `tag-resource`
<a name="lambda_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**既存の Lambda 関数にタグを追加する方法**  
次の `tag-resource` の例では、指定した Lambda 関数に `DEPARTMENT` のキー名と `Department A` の値を持つタグを追加します。  

```
aws lambda tag-resource \
    --resource arn:aws:lambda:us-west-2:123456789012:function:my-function \
    --tags "DEPARTMENT=Department A"
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lambda デベロッパーガイド*」の「[ Lambda 関数のタグ付け](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="lambda_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**既存の Lambda 関数からタグを削除する方法**  
次の `untag-resource` の例では、`DEPARTMENT` タグというキー名のタグを `my-function` Lambda 関数から削除します。  

```
aws lambda untag-resource \
    --resource arn:aws:lambda:us-west-2:123456789012:function:my-function \
    --tag-keys DEPARTMENT
```
このコマンドは何も出力しません。  
詳細については、「*AWS Lambda デベロッパーガイド*」の「[ Lambda 関数のタグ付け](https://docs.aws.amazon.com/lambda/latest/dg/tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/untag-resource.html)」を参照してください。

### `update-alias`
<a name="lambda_UpdateAlias_cli_2_topic"></a>

次のコード例は、`update-alias` を使用する方法を示しています。

**AWS CLI**  
**関数エイリアスを更新する方法**  
次の `update-alias` の例では、`my-function` Lambda 関数のバージョン 3 を参照するように、`LIVE` という名前のエイリアスを更新します。  

```
aws lambda update-alias \
    --function-name my-function \
    --function-version 3 \
    --name LIVE
```
出力:  

```
{
    "FunctionVersion": "3",
    "Name": "LIVE",
    "AliasArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function:LIVE",
    "RevisionId": "594f41fb-b85f-4c20-95c7-6ca5f2a92c93",
    "Description": "alias for live version of function"
}
```
詳細については、[AWS 「Lambda デベロッパーガイド」の「Lambda 関数エイリアスの設定](https://docs.aws.amazon.com/lambda/latest/dg/aliases-intro.html)」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-alias.html)」を参照してください。**

### `update-event-source-mapping`
<a name="lambda_UpdateEventSourceMapping_cli_2_topic"></a>

次の例は、`update-event-source-mapping` を使用する方法を説明しています。

**AWS CLI**  
**イベントソースと AWS Lambda 関数間のマッピングを更新するには**  
次の `update-event-source-mapping` の例では、指定したマッピングでバッチサイズを 8 に更新します。  

```
aws lambda update-event-source-mapping \
    --uuid  "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE" \
    --batch-size 8
```
出力:  

```
{
    "UUID": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE",
    "StateTransitionReason": "USER_INITIATED",
    "LastModified": 1569284520.333,
    "BatchSize": 8,
    "State": "Updating",
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "EventSourceArn": "arn:aws:sqs:us-west-2:123456789012:mySQSqueue"
}
```
詳細については、「*AWS Developer Guide*」の「[AWS Lambda Event Source Mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEventSourceMapping](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-event-source-mapping.html)」を参照してください。

### `update-function-code`
<a name="lambda_UpdateFunctionCode_cli_2_topic"></a>

次のコード例は、`update-function-code` を使用する方法を示しています。

**AWS CLI**  
**Lambda 関数のコードを更新するには**  
次の例 `update-function-code` では、未公開 (\$1LATEST) バージョンの `my-function` 関数のコードを、指定した zip ファイルの内容に置き換えます。  

```
aws lambda update-function-code \
    --function-name  my-function \
    --zip-file fileb://my-function.zip
```
出力:  

```
{
    "FunctionName": "my-function",
    "LastModified": "2019-09-26T20:28:40.438+0000",
    "RevisionId": "e52502d4-9320-4688-9cd6-152a6ab7490d",
    "MemorySize": 256,
    "Version": "$LATEST",
    "Role": "arn:aws:iam::123456789012:role/service-role/my-function-role-uy3l9qyq",
    "Timeout": 3,
    "Runtime": "nodejs10.x",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "5tT2qgzYUHaqwR716pZ2dpkn/0J1FrzJmlKidWoaCgk=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "VpcId": "",
        "SecurityGroupIds": []
    },
    "CodeSize": 304,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "Handler": "index.handler"
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[AWS Lambda 関数の設定](https://docs.aws.amazon.com/lambda/latest/dg/resource-model.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFunctionCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-code.html)」を参照してください。

### `update-function-configuration`
<a name="lambda_UpdateFunctionConfiguration_cli_2_topic"></a>

次のコード例は、`update-function-configuration` を使用する方法を示しています。

**AWS CLI**  
**関数の設定を変更するには**  
次の`update-function-configuration` の例では、未公開 (\$1LATEST) バージョンの `my-function` 関数のメモリサイズを 256 MB に変更しています。  

```
aws lambda update-function-configuration \
    --function-name  my-function \
    --memory-size 256
```
出力:  

```
{
    "FunctionName": "my-function",
    "LastModified": "2019-09-26T20:28:40.438+0000",
    "RevisionId": "e52502d4-9320-4688-9cd6-152a6ab7490d",
    "MemorySize": 256,
    "Version": "$LATEST",
    "Role": "arn:aws:iam::123456789012:role/service-role/my-function-role-uy3l9qyq",
    "Timeout": 3,
    "Runtime": "nodejs10.x",
    "TracingConfig": {
        "Mode": "PassThrough"
    },
    "CodeSha256": "5tT2qgzYUHaqwR716pZ2dpkn/0J1FrzJmlKidWoaCgk=",
    "Description": "",
    "VpcConfig": {
        "SubnetIds": [],
        "VpcId": "",
        "SecurityGroupIds": []
    },
    "CodeSize": 304,
    "FunctionArn": "arn:aws:lambda:us-west-2:123456789012:function:my-function",
    "Handler": "index.handler"
}
```
詳細については、「*AWS Lambda デベロッパーガイド*」の「[AWS Lambda 関数の設定](https://docs.aws.amazon.com/lambda/latest/dg/resource-model.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFunctionConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-configuration.html)」を参照してください。

### `update-function-event-invoke-config`
<a name="lambda_UpdateFunctionEventInvokeConfig_cli_2_topic"></a>

次のコード例は、`update-function-event-invoke-config` を使用する方法を示しています。

**AWS CLI**  
**非同期呼び出し設定を更新するには**  
次の `update-function-event-invoke-config` の例では、指定された関数の既存の非同期呼び出し設定に障害発生時の送信先を追加します。  

```
aws lambda update-function-event-invoke-config \
    --function-name my-function \
    --destination-config '{"OnFailure":{"Destination": "arn:aws:sqs:us-east-2:123456789012:destination"}}'
```
出力:  

```
{
    "LastModified": 1573687896.493,
    "FunctionArn": "arn:aws:lambda:us-east-2:123456789012:function:my-function:$LATEST",
    "MaximumRetryAttempts": 0,
    "MaximumEventAgeInSeconds": 3600,
    "DestinationConfig": {
        "OnSuccess": {},
        "OnFailure": {
            "Destination": "arn:aws:sqs:us-east-2:123456789012:destination"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFunctionEventInvokeConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lambda/update-function-event-invoke-config.html)」を参照してください。

# を使用した License Manager の例 AWS CLI
<a name="cli_2_license-manager_code_examples"></a>

次のコード例は、License Manager AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-license-configuration`
<a name="license-manager_CreateLicenseConfiguration_cli_2_topic"></a>

次のコード例は、`create-license-configuration` を使用する方法を示しています。

**AWS CLI**  
**例 1: ライセンス設定を作成するには**  
次の `create-license-configuration` の例では、ハード制限が 10 コアのライセンス設定を作成します。  

```
aws license-manager create-license-configuration --name my-license-configuration \
    --license-counting-type Core \
    --license-count 10 \
    --license-count-hard-limit
```
出力:  

```
{
  "LicenseConfigurationArn": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-6eb6586f508a786a2ba41EXAMPLE1111"
}
```
**例 2: ライセンス設定を作成するには**  
次の `create-license-configuration` の例では、ソフト制限が 100 vCPU のライセンス設定を作成します。ルールを使用して vCPU 最適化を有効にします。  

```
aws license-manager create-license-configuration --name my-license-configuration
    --license-counting-type vCPU \
    --license-count 100 \
    --license-rules "#honorVcpuOptimization=true"
```
出力:  

```
{
  "LicenseConfigurationArn": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-6eb6586f508a786a2ba41EXAMPLE2222"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLicenseConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/create-license-configuration.html)」を参照してください。

### `delete-license-configuration`
<a name="license-manager_DeleteLicenseConfiguration_cli_2_topic"></a>

次のコード例は、`delete-license-configuration` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定を削除するには**  
次の `delete-license-configuration` の例では、指定されたライセンス設定を削除します。  

```
aws license-manager delete-license-configuration \
    --license-configuration-arn arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-6eb6586f508a786a2ba4f56c1EXAMPLE
```
このコマンドは何も出力しません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLicenseConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/delete-license-configuration.html)」を参照してください。

### `get-license-configuration`
<a name="license-manager_GetLicenseConfiguration_cli_2_topic"></a>

次のコード例は、`get-license-configuration` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定情報を取得するには**  
次の `get-license-configuration` の例では、指定されたライセンス設定の詳細を表示します。  

```
aws license-manager get-license-configuration \
    --license-configuration-arn arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-38b658717b87478aaa7c00883EXAMPLE
```
出力:  

```
{
    "LicenseConfigurationId": "lic-38b658717b87478aaa7c00883EXAMPLE",
    "LicenseConfigurationArn": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-38b658717b87478aaa7c00883EXAMPLE",
    "Name": "my-license-configuration",
    "LicenseCountingType": "vCPU",
    "LicenseRules": [],
    "LicenseCountHardLimit": false,
    "ConsumedLicenses": 0,
    "Status": "AVAILABLE",
    "OwnerAccountId": "123456789012",
    "ConsumedLicenseSummaryList": [
        {
            "ResourceType": "EC2_INSTANCE",
            "ConsumedLicenses": 0
        },
        {
            "ResourceType": "EC2_HOST",
            "ConsumedLicenses": 0
        },
        {
            "ResourceType": "SYSTEMS_MANAGER_MANAGED_INSTANCE",
            "ConsumedLicenses": 0
        }
    ],
    "ManagedResourceSummaryList": [
        {
            "ResourceType": "EC2_INSTANCE",
            "AssociationCount": 0
        },
        {
            "ResourceType": "EC2_HOST",
            "AssociationCount": 0
        },
        {
            "ResourceType": "EC2_AMI",
            "AssociationCount": 2
        },
        {
            "ResourceType": "SYSTEMS_MANAGER_MANAGED_INSTANCE",
            "AssociationCount": 0
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLicenseConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/get-license-configuration.html)」を参照してください。

### `get-service-settings`
<a name="license-manager_GetServiceSettings_cli_2_topic"></a>

次のコード例は、`get-service-settings` を使用する方法を示しています。

**AWS CLI**  
**License Manager の設定を取得するには**  
次の `get-service-settings` の例では、現在のリージョンの License Manager のサービス設定を表示します。  

```
aws license-manager get-service-settings
```
クロスアカウントリソース検出が無効になっている場合の出力例を次に示します。  

```
{
    "OrganizationConfiguration": {
        "EnableIntegration": false
    },
    "EnableCrossAccountsDiscovery": false
}
```
クロスアカウントリソース検出が有効になっている場合の出力例を次に示します。  

```
{
    "S3BucketArn": "arn:aws:s3:::aws-license-manager-service-c22d6279-35c4-47c4-bb",
    "OrganizationConfiguration": {
        "EnableIntegration": true
    },
    "EnableCrossAccountsDiscovery": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/get-service-settings.html)」を参照してください。

### `list-associations-for-license-configuration`
<a name="license-manager_ListAssociationsForLicenseConfiguration_cli_2_topic"></a>

次のコード例は、`list-associations-for-license-configuration` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定の関連付けを取得するには**  
次の `list-associations-for-license-configuration` の例では、指定されたライセンス設定の関連付けに関する詳細情報を表示します。  

```
aws license-manager list-associations-for-license-configuration \
    --license-configuration-arn arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-38b658717b87478aaa7c00883EXAMPLE
```
出力:  

```
{
    "LicenseConfigurationAssociations": [
        {
            "ResourceArn": "arn:aws:ec2:us-west-2::image/ami-1234567890abcdef0",
            "ResourceType": "EC2_AMI",
            "ResourceOwnerId": "123456789012",
            "AssociationTime": 1568825118.617
        },
        {
            "ResourceArn": "arn:aws:ec2:us-west-2::image/ami-0abcdef1234567890",
            "ResourceType": "EC2_AMI",
            "ResourceOwnerId": "123456789012",
            "AssociationTime": 1568825118.946
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssociationsForLicenseConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/list-associations-for-license-configuration.html)」を参照してください。

### `list-license-configurations`
<a name="license-manager_ListLicenseConfigurations_cli_2_topic"></a>

次のコード例は、`list-license-configurations` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのライセンス設定を一覧表示するには**  
次の `list-license-configurations` の例では、すべてのライセンス設定を一覧表示します。  

```
aws license-manager list-license-configurations
```
出力:  

```
{
    "LicenseConfigurations": [
        {
            "LicenseConfigurationId": "lic-6eb6586f508a786a2ba4f56c1EXAMPLE",
            "LicenseConfigurationArn": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-6eb6586f508a786a2ba4f56c1EXAMPLE",
            "Name": "my-license-configuration",
            "LicenseCountingType": "Core",
            "LicenseRules": [],
            "LicenseCount": 10,
            "LicenseCountHardLimit": true,
            "ConsumedLicenses": 0,
            "Status": "AVAILABLE",
            "OwnerAccountId": "123456789012",
            "ConsumedLicenseSummaryList": [
                {
                    "ResourceType": "EC2_INSTANCE",
                    "ConsumedLicenses": 0
                },
                {
                    "ResourceType": "EC2_HOST",
                    "ConsumedLicenses": 0
                },
                {
                    "ResourceType": "SYSTEMS_MANAGER_MANAGED_INSTANCE",
                    "ConsumedLicenses": 0
                }
            ],
            "ManagedResourceSummaryList": [
                {
                    "ResourceType": "EC2_INSTANCE",
                    "AssociationCount": 0
                },
                {
                    "ResourceType": "EC2_HOST",
                    "AssociationCount": 0
                },
                {
                    "ResourceType": "EC2_AMI",
                    "AssociationCount": 0
                },
                {
                    "ResourceType": "SYSTEMS_MANAGER_MANAGED_INSTANCE",
                    "AssociationCount": 0
                }
            ]
        },
        {
            ...
        }
    ]
}
```
**例 2: 特定のライセンス設定を一覧表示するには**  
次の `list-license-configurations` の例では、指定されたライセンス設定のみを一覧表示します。  

```
aws license-manager list-license-configurations \
    --license-configuration-arns arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-38b658717b87478aaa7c00883EXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLicenseConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/list-license-configurations.html)」を参照してください。

### `list-license-specifications-for-resource`
<a name="license-manager_ListLicenseSpecificationsForResource_cli_2_topic"></a>

次のコード例は、`list-license-specifications-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのライセンス設定を一覧表示するには**  
次の `list-license-specifications-for-resource` の例では、指定された Amazon マシンイメージ (AMI) に関連付けられたライセンス設定を一覧表示します。  

```
aws license-manager list-license-specifications-for-resource \
    --resource-arn arn:aws:ec2:us-west-2::image/ami-1234567890abcdef0
```
出力:  

```
{
    "LicenseConfigurationArn": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-38b658717b87478aaa7c00883EXAMPLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLicenseSpecificationsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/list-license-specifications-for-resource.html)」を参照してください。

### `list-resource-inventory`
<a name="license-manager_ListResourceInventory_cli_2_topic"></a>

次のコード例は、`list-resource-inventory` を使用する方法を示しています。

**AWS CLI**  
**リソースインベントリ内のリソースを一覧表示するには**  
次の `list-resource-inventory` の例では、Systems Manager インベントリを使用して管理されるリソースを一覧表示します。  

```
aws license-manager list-resource-inventory
```
出力:  

```
{
    "ResourceInventoryList": [
        {
            "Platform": "Red Hat Enterprise Linux Server",
            "ResourceType": "EC2Instance",
            "PlatformVersion": "7.4",
            "ResourceArn": "arn:aws:ec2:us-west-2:1234567890129:instance/i-05d3cdfb05bd36376",
            "ResourceId": "i-05d3cdfb05bd36376",
            "ResourceOwningAccountId": "1234567890129"
        },
        {
            "Platform": "Amazon Linux",
            "ResourceType": "EC2Instance",
            "PlatformVersion": "2",
            "ResourceArn": "arn:aws:ec2:us-west-2:1234567890129:instance/i-0b1d036cfd4594808",
            "ResourceId": "i-0b1d036cfd4594808",
            "ResourceOwningAccountId": "1234567890129"
        },
        {
            "Platform": "Microsoft Windows Server 2019 Datacenter",
            "ResourceType": "EC2Instance",
            "PlatformVersion": "10.0.17763",
            "ResourceArn": "arn:aws:ec2:us-west-2:1234567890129:instance/i-0cdb3b54a2a8246ad",
            "ResourceId": "i-0cdb3b54a2a8246ad",
            "ResourceOwningAccountId": "1234567890129"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceInventory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/list-resource-inventory.html)」を参照してください。

### `list-tags-for-resource`
<a name="license-manager_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定のタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定されたライセンス設定のタグを一覧表示します。  

```
aws license-manager list-tags-for-resource \
    --resource-arn arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-6eb6586f508a786a2ba4f56c1EXAMPLE
```
出力:  

```
{
    "Tags": [
        {
            "Key": "project",
            "Value": "lima"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/list-tags-for-resource.html)」を参照してください。

### `list-usage-for-license-configuration`
<a name="license-manager_ListUsageForLicenseConfiguration_cli_2_topic"></a>

次のコード例は、`list-usage-for-license-configuration` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定で使用されているライセンスを一覧表示するには**  
次の `list-usage-for-license-configuration` の例では、指定されたライセンス設定のライセンスを使用するリソースに関する情報を示します。例えば、ライセンスタイプが vCPU の場合、インスタンスは vCPU ごとに 1 つのライセンスを使用します。  

```
aws license-manager list-usage-for-license-configuration \
    --license-configuration-arn arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-38b658717b87478aaa7c00883EXAMPLE
```
出力:  

```
{
    "LicenseConfigurationUsageList": [
        {
            "ResourceArn": "arn:aws:ec2:us-west-2:123456789012:instance/i-04a636d18e83cfacb",
            "ResourceType": "EC2_INSTANCE",
            "ResourceStatus": "running",
            "ResourceOwnerId": "123456789012",
            "AssociationTime": 1570892850.519,
            "ConsumedLicenses": 2
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsageForLicenseConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/list-usage-for-license-configuration.html)」を参照してください。

### `tag-resource`
<a name="license-manager_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定にタグを追加するには**  
次の `tag-resource` の例では、指定されたタグ (キー名と値) を、指定されたライセンス設定に追加します。  

```
aws license-manager tag-resource \
    --tags Key=project,Value=lima \
    --resource-arn arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-6eb6586f508a786a2ba4f56c1EXAMPLE
```
このコマンドは何も出力しません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="license-manager_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定からタグを削除するには**  
次の `untag-resource` の例では、指定されたライセンス設定から、指定されたタグ (キー名とリソース) を削除します。  

```
aws license-manager untag-resource \
    --tag-keys project \
    --resource-arn arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-6eb6586f508a786a2ba4f56c1EXAMPLE
```
このコマンドは何も出力しません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/untag-resource.html)」を参照してください。

### `update-license-configuration`
<a name="license-manager_UpdateLicenseConfiguration_cli_2_topic"></a>

次のコード例は、`update-license-configuration` を使用する方法を示しています。

**AWS CLI**  
**ライセンス設定を更新するには**  
次の `update-license-configuration` の例では、指定されたライセンス設定を更新して、ハード制限を削除します。  

```
aws license-manager update-license-configuration \
    --no-license-count-hard-limit \
    --license-configuration-arn arn:aws:license-manager:us-west-2:880185128111:license-configuration:lic-6eb6586f508a786a2ba4f56c1EXAMPLE
```
このコマンドは何も出力しません。  
次の `update-license-configuration` の例では、指定されたライセンス設定を更新して、ステータスを `DISABLED` に変更します。  

```
aws license-manager update-license-configuration \
    --license-configuration-status DISABLED
    --license-configuration-arn arn:aws:license-manager:us-west-2:880185128111:license-configuration:lic-6eb6586f508a786a2ba4f56c1EXAMPLE
```
このコマンドは何も出力しません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLicenseConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/update-license-configuration.html)」を参照してください。

### `update-license-specifications-for-resource`
<a name="license-manager_UpdateLicenseSpecificationsForResource_cli_2_topic"></a>

次のコード例は、`update-license-specifications-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのライセンス設定を更新するには**  
次の `update-license-specifications-for-resource` の例では、1 つのライセンス設定を削除して別のライセンス設定を追加することにより、指定された Amazon マシンイメージ (AMI) に関連付けられたライセンス設定を置き換えます。  

```
aws license-manager update-license-specifications-for-resource \
    --resource-arn arn:aws:ec2:us-west-2::image/ami-1234567890abcdef0 \
    --remove-license-specifications LicenseConfigurationArn=arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-38b658717b87478aaa7c00883EXAMPLE \
    --add-license-specifications LicenseConfigurationArn=arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-42b6deb06e5399a980d555927EXAMPLE
```
このコマンドは何も出力しません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLicenseSpecificationsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/update-license-specifications-for-resource.html)」を参照してください。

### `update-service-settings`
<a name="license-manager_UpdateServiceSettings_cli_2_topic"></a>

次のコード例は、`update-service-settings` を使用する方法を示しています。

**AWS CLI**  
**License Manager の設定を更新するには**  
次の`update-service-settings`例では、現在の AWS リージョンで License Manager のクロスアカウントリソース検出を有効にします。Amazon S3 バケットは、Systems Manager インベントリに必要なリソースデータ同期です。  

```
aws license-manager update-service-settings \
    --organization-configuration EnableIntegration=true \
    --enable-cross-accounts-discovery \
    --s3-bucket-arn arn:aws:s3:::aws-license-manager-service-abcd1234EXAMPLE
```
このコマンドは何も出力しません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServiceSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/license-manager/update-service-settings.html)」を参照してください。

# Lightsail を使用した の例 AWS CLI
<a name="cli_2_lightsail_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示していますLightsail。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `allocate-static-ip`
<a name="lightsail_AllocateStaticIp_cli_2_topic"></a>

次のコード例は、`allocate-static-ip` を使用する方法を示しています。

**AWS CLI**  
**静的 IP を作成するには**  
次の `allocate-static-ip` の例では、インスタンスにアタッチできる指定された静的 IP を作成します。  

```
aws lightsail allocate-static-ip \
    --static-ip-name StaticIp-1
```
出力:  

```
{
    "operations": [
        {
            "id": "b5d06d13-2f19-4683-889f-dEXAMPLEed79",
            "resourceName": "StaticIp-1",
            "resourceType": "StaticIp",
            "createdAt": 1571071325.076,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "AllocateStaticIp",
            "status": "Succeeded",
            "statusChangedAt": 1571071325.274
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AllocateStaticIp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/allocate-static-ip.html)」を参照してください。

### `attach-disk`
<a name="lightsail_AttachDisk_cli_2_topic"></a>

次のコード例は、`attach-disk` を使用する方法を示しています。

**AWS CLI**  
**ブロックストレージディスクをインスタンスにアタッチするには**  
次の `attach-disk` の例では、ディスクパス `/dev/xvdf` を使用してディスク `Disk-1` をインスタンス `WordPress_Multisite-1` にアタッチします。  

```
aws lightsail attach-disk \
    --disk-name Disk-1 \
    --disk-path /dev/xvdf \
    --instance-name WordPress_Multisite-1
```
出力:  

```
{
    "operations": [
        {
            "id": "10a08267-19ce-43be-b913-6EXAMPLE7e80",
            "resourceName": "Disk-1",
            "resourceType": "Disk",
            "createdAt": 1571071465.472,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "WordPress_Multisite-1",
            "operationType": "AttachDisk",
            "status": "Started",
            "statusChangedAt": 1571071465.472
        },
        {
            "id": "2912c477-5295-4539-88c9-bEXAMPLEd1f0",
            "resourceName": "WordPress_Multisite-1",
            "resourceType": "Instance",
            "createdAt": 1571071465.474,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "Disk-1",
            "operationType": "AttachDisk",
            "status": "Started",
            "statusChangedAt": 1571071465.474
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachDisk](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/attach-disk.html)」を参照してください。

### `attach-instances-to-load-balancer`
<a name="lightsail_AttachInstancesToLoadBalancer_cli_2_topic"></a>

次のコード例は、`attach-instances-to-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**インスタンスをロードバランサーにアタッチするには**  
次の `attach-instances-to-load-balancer` の例では、インスタンス `MEAN-1`、`MEAN-2`、および `MEAN-3` をロードバランサー `LoadBalancer-1` にアタッチします。  

```
aws lightsail attach-instances-to-load-balancer \
    --instance-names {"MEAN-1","MEAN-2","MEAN-3"} \
    --load-balancer-name LoadBalancer-1
```
出力:  

```
{
    "operations": [
        {
            "id": "8055d19d-abb2-40b9-b527-1EXAMPLE3c7b",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571071699.892,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "MEAN-2",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Started",
            "statusChangedAt": 1571071699.892
        },
        {
            "id": "c35048eb-8538-456a-a118-0EXAMPLEfb73",
            "resourceName": "MEAN-2",
            "resourceType": "Instance",
            "createdAt": 1571071699.887,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "LoadBalancer-1",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Started",
            "statusChangedAt": 1571071699.887
        },
        {
            "id": "910d09e0-adc5-4372-bc2e-0EXAMPLEd891",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571071699.882,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "MEAN-3",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Started",
            "statusChangedAt": 1571071699.882
        },
        {
            "id": "178b18ac-43e8-478c-9bed-1EXAMPLE4755",
            "resourceName": "MEAN-3",
            "resourceType": "Instance",
            "createdAt": 1571071699.901,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "LoadBalancer-1",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Started",
            "statusChangedAt": 1571071699.901
        },
        {
            "id": "fb62536d-2a98-4190-a6fc-4EXAMPLE7470",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571071699.885,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "MEAN-1",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Started",
            "statusChangedAt": 1571071699.885
        },
        {
            "id": "787dac0d-f98d-46c3-8571-3EXAMPLE5a85",
            "resourceName": "MEAN-1",
            "resourceType": "Instance",
            "createdAt": 1571071699.901,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "LoadBalancer-1",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Started",
            "statusChangedAt": 1571071699.901
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachInstancesToLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/attach-instances-to-load-balancer.html)」を参照してください。

### `attach-load-balancer-tls-certificate`
<a name="lightsail_AttachLoadBalancerTlsCertificate_cli_2_topic"></a>

次のコード例は、`attach-load-balancer-tls-certificate` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーに TLS 証明書をアタッチするには**  
次の `attach-load-balancer-tls-certificate` の例では、ロードバランサー TLS 証明書 `Certificate2` をロードバランサー `LoadBalancer-1` にアタッチします。  

```
aws lightsail attach-load-balancer-tls-certificate \
    --certificate-name Certificate2 \
    --load-balancer-name LoadBalancer-1
```
出力:  

```
{
    "operations": [
        {
            "id": "cf1ad6e3-3cbb-4b8a-a7f2-3EXAMPLEa118",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571072255.416,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "Certificate2",
            "operationType": "AttachLoadBalancerTlsCertificate",
            "status": "Succeeded",
            "statusChangedAt": 1571072255.416
        },
        {
            "id": "dae1bcfb-d531-4c06-b4ea-bEXAMPLEc04e",
            "resourceName": "Certificate2",
            "resourceType": "LoadBalancerTlsCertificate",
            "createdAt": 1571072255.416,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "LoadBalancer-1",
            "operationType": "AttachLoadBalancerTlsCertificate",
            "status": "Succeeded",
            "statusChangedAt": 1571072255.416
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachLoadBalancerTlsCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/attach-load-balancer-tls-certificate.html)」を参照してください。

### `attach-static-ip`
<a name="lightsail_AttachStaticIp_cli_2_topic"></a>

次のコード例は、`attach-static-ip` を使用する方法を示しています。

**AWS CLI**  
**インスタンスに静的 IP をアタッチするには**  
次の `attach-static-ip` の例では、静的 IP `StaticIp-1` をインスタンス `MEAN-1` にアタッチします。  

```
aws lightsail attach-static-ip \
    --static-ip-name StaticIp-1 \
    --instance-name MEAN-1
```
出力:  

```
{
    "operations": [
        {
            "id": "45e6fa13-4808-4b8d-9292-bEXAMPLE20b2",
            "resourceName": "StaticIp-1",
            "resourceType": "StaticIp",
            "createdAt": 1571072569.375,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "MEAN-1",
            "operationType": "AttachStaticIp",
            "status": "Succeeded",
            "statusChangedAt": 1571072569.375
        },
        {
            "id": "9ee09a17-863c-4e51-8a6d-3EXAMPLE5475",
            "resourceName": "MEAN-1",
            "resourceType": "Instance",
            "createdAt": 1571072569.376,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "StaticIp-1",
            "operationType": "AttachStaticIp",
            "status": "Succeeded",
            "statusChangedAt": 1571072569.376
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AttachStaticIp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/attach-static-ip.html)」を参照してください。

### `close-instance-public-ports`
<a name="lightsail_CloseInstancePublicPorts_cli_2_topic"></a>

次のコード例は、`close-instance-public-ports` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのファイアウォールポートを閉じるには**  
次の `close-instance-public-ports` の例では、インスタンス `MEAN-2` の TCP ポート `22` を閉じます。  

```
aws lightsail close-instance-public-ports \
    --instance-name MEAN-2 \
    --port-info fromPort=22,protocol=TCP,toPort=22
```
出力:  

```
{
    "operation": {
        "id": "4f328636-1c96-4649-ae6d-1EXAMPLEf446",
        "resourceName": "MEAN-2",
        "resourceType": "Instance",
        "createdAt": 1571072845.737,
        "location": {
            "availabilityZone": "us-west-2a",
            "regionName": "us-west-2"
        },
        "isTerminal": true,
        "operationDetails": "22/tcp",
        "operationType": "CloseInstancePublicPorts",
        "status": "Succeeded",
        "statusChangedAt": 1571072845.737
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CloseInstancePublicPorts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/close-instance-public-ports.html)」を参照してください。

### `copy-snapshot`
<a name="lightsail_CopySnapshot_cli_2_topic"></a>

次の例は、`copy-snapshot` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 同じ AWS リージョン内でスナップショットをコピーするには**  
次の の`copy-snapshot`例では、インスタンススナップショットを同じ AWS リージョン `MEAN-1-Copy`内のインスタンススナップショット`MEAN-1-1571075291`としてコピーします`us-west-2`。  

```
aws lightsail copy-snapshot \
    --source-snapshot-name MEAN-1-1571075291 \
    --target-snapshot-name MEAN-1-Copy \
    --source-region us-west-2
```
出力:  

```
{
    "operations": [
        {
            "id": "ced16fc1-f401-4556-8d82-1EXAMPLEb982",
            "resourceName": "MEAN-1-Copy",
            "resourceType": "InstanceSnapshot",
            "createdAt": 1571075581.498,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "us-west-2:MEAN-1-1571075291",
            "operationType": "CopySnapshot",
            "status": "Started",
            "statusChangedAt": 1571075581.498
        }
    ]
}
```
詳細については、*Lightsail「 開発ガイド*[」の「 で 1 つの AWS リージョンから別のリージョンにスナップショットをコピーするAmazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-copying-snapshots-from-one-region-to-another)」を参照してください。  
**例 2: あるリージョンから別の AWS リージョンにスナップショットをコピーするには**  
次の`copy-snapshot`例では、インスタンススナップショットをインスタンススナップショット`MEAN-1-1571075291`として AWS リージョン`MEAN-1-1571075291-Copy`から にコピー`us-west-2`します`us-east-1`。  

```
aws lightsail copy-snapshot \
    --source-snapshot-name MEAN-1-1571075291 \
    --target-snapshot-name MEAN-1-1571075291-Copy \
    --source-region us-west-2 \
    --region us-east-1
```
出力:  

```
{
    "operations": [
        {
            "id": "91116b79-119c-4451-b44a-dEXAMPLEd97b",
            "resourceName": "MEAN-1-1571075291-Copy",
            "resourceType": "InstanceSnapshot",
            "createdAt": 1571075695.069,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-east-1"
            },
            "isTerminal": false,
            "operationDetails": "us-west-2:MEAN-1-1571075291",
            "operationType": "CopySnapshot",
            "status": "Started",
            "statusChangedAt": 1571075695.069
        }
    ]
}
```
詳細については、*Lightsail「 開発ガイド*[」の「 で 1 つの AWS リージョンから別のリージョンにスナップショットをコピーAmazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-copying-snapshots-from-one-region-to-another)する」を参照してください。  
**例 3: 同じ AWS リージョン内で自動スナップショットをコピーするには**  
次の `2019-10-14`の`copy-snapshot`例では、インスタンスの自動スナップショットを AWS リージョン `WordPress-1-10142019`の手動スナップショット`WordPress-1`としてコピーします`us-west-2`。  

```
aws lightsail copy-snapshot \
    --source-resource-name WordPress-1 \
    --restore-date 2019-10-14 \
    --target-snapshot-name WordPress-1-10142019 \
    --source-region us-west-2
```
出力:  

```
{
    "operations": [
        {
            "id": "be3e6754-cd1d-48e6-ad9f-2EXAMPLE1805",
            "resourceName": "WordPress-1-10142019",
            "resourceType": "InstanceSnapshot",
            "createdAt": 1571082412.311,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "us-west-2:WordPress-1",
            "operationType": "CopySnapshot",
            "status": "Started",
            "statusChangedAt": 1571082412.311
        }
    ]
}
```
詳細については、「*Lightsail Dev Guide*」の「[Keeping automatic snapshots of instances or disks in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots)」を参照してください。  
**例 4: 自動スナップショットをあるリージョンから別の AWS リージョンにコピーするには**  
次の`copy-snapshot`例では`2019-10-14`、インスタンスの自動スナップショットを手動スナップショット`WordPress-1`として AWS リージョン`WordPress-1-10142019`から `us-west-2` にコピーします`us-east-1`。  

```
aws lightsail copy-snapshot \
    --source-resource-name WordPress-1 \
    --restore-date 2019-10-14 \
    --target-snapshot-name WordPress-1-10142019 \
    --source-region us-west-2 \
    --region us-east-1
```
出力:  

```
{
    "operations": [
        {
            "id": "dffa128b-0b07-476e-b390-bEXAMPLE3775",
            "resourceName": "WordPress-1-10142019",
            "resourceType": "InstanceSnapshot",
            "createdAt": 1571082493.422,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-east-1"
            },
            "isTerminal": false,
            "operationDetails": "us-west-2:WordPress-1",
            "operationType": "CopySnapshot",
            "status": "Started",
            "statusChangedAt": 1571082493.422
        }
    ]
}
```
詳細については、「*Lightsail Dev Guide*」の「[Keeping automatic snapshots of instances or disks in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopySnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/copy-snapshot.html)」を参照してください。

### `create-disk-from-snapshot`
<a name="lightsail_CreateDiskFromSnapshot_cli_2_topic"></a>

次のコード例は、`create-disk-from-snapshot` を使用する方法を示しています。

**AWS CLI**  
**ディスクスナップショットからディスクを作成するには**  
次の `create-disk-from-snapshot` の例では、指定されたブロックストレージディスクスナップショットから `Disk-2` という名前のブロックストレージディスクを作成します。ディスクは、指定された AWS リージョンとアベイラビリティーゾーンに 32 GB のストレージ領域で作成されます。  

```
aws lightsail create-disk-from-snapshot \
    --disk-name Disk-2 \
    --disk-snapshot-name Disk-1-1566839161 \
    --availability-zone us-west-2a \
    --size-in-gb 32
```
出力:  

```
{
    "operations": [
        {
            "id": "d42b605d-5ef1-4b4a-8791-7a3e8b66b5e7",
            "resourceName": "Disk-2",
            "resourceType": "Disk",
            "createdAt": 1569624941.471,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateDiskFromSnapshot",
            "status": "Started",
            "statusChangedAt": 1569624941.791
        }
    ]
}
```
詳細については、「*Lightsail Developer Guide*」の「[Creating a block storage disk from a snapshot in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/create-new-block-storage-disk-from-snapshot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDiskFromSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-disk-from-snapshot.html)」を参照してください。

### `create-disk-snapshot`
<a name="lightsail_CreateDiskSnapshot_cli_2_topic"></a>

次のコード例は、`create-disk-snapshot` を使用する方法を示しています。

**AWS CLI**  
**例 1: ディスクのスナップショットを作成するには**  
次の `create-disk-snapshot` の例では、指定されたブロックストレージディスクの `DiskSnapshot-1` という名前のスナップショットを作成します。  

```
aws lightsail create-disk-snapshot \
    --disk-name Disk-1 \
    --disk-snapshot-name DiskSnapshot-1
```
出力:  

```
{
    "operations": [
        {
            "id": "fa74c6d2-03a3-4f42-a7c7-792f124d534b",
            "resourceName": "DiskSnapshot-1",
            "resourceType": "DiskSnapshot",
            "createdAt": 1569625129.739,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "Disk-1",
            "operationType": "CreateDiskSnapshot",
            "status": "Started",
            "statusChangedAt": 1569625129.739
        },
        {
            "id": "920a25df-185c-4528-87cd-7b85f5488c06",
            "resourceName": "Disk-1",
            "resourceType": "Disk",
            "createdAt": 1569625129.739,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "DiskSnapshot-1",
            "operationType": "CreateDiskSnapshot",
            "status": "Started",
            "statusChangedAt": 1569625129.739
        }
    ]
}
```
**例 2: インスタンスのシステムディスクのスナップショットを作成するには**  
次の `create-disk-snapshot` の例では、指定されたインスタンスのシステムディスクのスナップショットを作成します。  

```
aws lightsail create-disk-snapshot \
    --instance-name WordPress-1 \
    --disk-snapshot-name SystemDiskSnapshot-1
```
出力:  

```
{
    "operations": [
        {
            "id": "f508cf1c-6597-42a6-a4c3-4aebd75af0d9",
            "resourceName": "SystemDiskSnapshot-1",
            "resourceType": "DiskSnapshot",
            "createdAt": 1569625294.685,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "WordPress-1",
            "operationType": "CreateDiskSnapshot",
            "status": "Started",
            "statusChangedAt": 1569625294.685
        },
        {
            "id": "0bb9f712-da3b-4d99-b508-3bf871d989e5",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1569625294.685,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "SystemDiskSnapshot-1",
            "operationType": "CreateDiskSnapshot",
            "status": "Started",
            "statusChangedAt": 1569625294.685
        }
    ]
}
```
詳細については、「*Lightsail Developer Guide*」の「[Snapshots in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/understanding-instance-snapshots-in-amazon-lightsail)」および「[Creating a snapshot of an instance root volume in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-create-an-instance-root-volume-snapshot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDiskSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-disk-snapshot.html)」を参照してください。

### `create-disk`
<a name="lightsail_CreateDisk_cli_2_topic"></a>

次のコード例は、`create-disk` を使用する方法を示しています。

**AWS CLI**  
**ブロックストレージディスクを作成するには**  
次の の`create-disk`例では、指定された AWS リージョンとアベイラビリティーゾーン`Disk-1`に 32 GB のストレージ容量を持つブロックストレージディスクを作成します。  

```
aws lightsail create-disk \
    --disk-name Disk-1 \
    --availability-zone us-west-2a \
    --size-in-gb 32
```
出力:  

```
{
    "operations": [
        {
            "id": "1c85e2ec-86ba-4697-b936-77f4d3dc013a",
            "resourceName": "Disk-1",
            "resourceType": "Disk",
            "createdAt": 1569449220.36,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateDisk",
            "status": "Started",
            "statusChangedAt": 1569449220.588
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDisk](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-disk.html)」を参照してください。

### `create-domain-entry`
<a name="lightsail_CreateDomainEntry_cli_2_topic"></a>

次のコード例は、`create-domain-entry` を使用する方法を示しています。

**AWS CLI**  
**ドメインエントリを作成するには (DNS レコード)**  
次の `create-domain-entry` の例では、インスタンスの IP アドレスを指す指定されたドメインの Apex の DNS レコード (A) を作成します。  
**注:** Lightsailのドメイン関連の API オペレーションは、 `us-east-1`リージョンでのみ使用できます。CLI プロファイルが別のリージョンを使用するように設定されている場合は、`--region us-east-1` パラメータを含める必要があります。そうしないと、コマンドは失敗します。  

```
aws lightsail create-domain-entry \
    --region us-east-1 \
    --domain-name example.com \
    --domain-entry name=example.com,type=A,target=192.0.2.0
```
出力:  

```
{
    "operation": {
        "id": "5be4494d-56f4-41fc-8730-693dcd0ef9e2",
        "resourceName": "example.com",
        "resourceType": "Domain",
        "createdAt": 1569865296.519,
        "location": {
            "availabilityZone": "all",
            "regionName": "global"
        },
        "isTerminal": true,
        "operationType": "CreateDomainEntry",
        "status": "Succeeded",
        "statusChangedAt": 1569865296.519
    }
}
```
詳細については、「*Lightsail Developer Guide*」の「[DNS in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/understanding-dns-in-amazon-lightsail)」および「[Creating a DNS zone to manage your domain's DNS records in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/lightsail-how-to-create-dns-entry)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDomainEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-domain-entry.html)」を参照してください。

### `create-domain`
<a name="lightsail_CreateDomain_cli_2_topic"></a>

次のコード例は、`create-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインを作成するには (DNS ゾーン)**  
次の `create-domain` の例では、指定されたドメインの DNS ゾーンを作成します。  
**注:** Lightsailのドメイン関連の API オペレーションは、 `us-east-1`リージョンでのみ使用できます。CLI プロファイルが別のリージョンを使用するように設定されている場合は、`--region us-east-1` パラメータを含める必要があります。そうしないと、コマンドは失敗します。  

```
aws lightsail create-domain \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "operation": {
        "id": "64e522c8-9ae1-4c05-9b65-3f237324dc34",
        "resourceName": "example.com",
        "resourceType": "Domain",
        "createdAt": 1569864291.92,
        "location": {
            "availabilityZone": "all",
            "regionName": "global"
        },
        "isTerminal": true,
        "operationType": "CreateDomain",
        "status": "Succeeded",
        "statusChangedAt": 1569864292.109
    }
}
```
詳細については、「*Lightsail Developer Guide*」の「[DNS in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/understanding-dns-in-amazon-lightsail)」および「[Creating a DNS zone to manage your domain's DNS records in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/lightsail-how-to-create-dns-entry)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-domain.html)」を参照してください。

### `create-instance-snapshot`
<a name="lightsail_CreateInstanceSnapshot_cli_2_topic"></a>

次のコード例は、`create-instance-snapshot` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのスナップショットを作成するには**  
次の `create-instance-snapshot` の例では、指定されたインスタンスからスナップショットを作成します。  

```
aws lightsail create-instance-snapshot \
    --instance-name WordPress-1 \
    --instance-snapshot-name WordPress-Snapshot-1
```
出力:  

```
{
    "operations": [
        {
            "id": "4c3db559-9dd0-41e7-89c0-2cb88c19786f",
            "resourceName": "WordPress-Snapshot-1",
            "resourceType": "InstanceSnapshot",
            "createdAt": 1569866438.48,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "WordPress-1",
            "operationType": "CreateInstanceSnapshot",
            "status": "Started",
            "statusChangedAt": 1569866438.48
        },
        {
            "id": "c04fdc45-2981-488c-88b5-d6d2fd759a6a",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1569866438.48,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "WordPress-Snapshot-1",
            "operationType": "CreateInstanceSnapshot",
            "status": "Started",
            "statusChangedAt": 1569866438.48
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInstanceSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-instance-snapshot.html)」を参照してください。

### `create-instances-from-snapshot`
<a name="lightsail_CreateInstancesFromSnapshot_cli_2_topic"></a>

次のコード例は、`create-instances-from-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットからインスタンスを作成するには**  
次の の`create-instances-from-snapshot`例では、12 USD のバンドルを使用して、指定された AWS リージョンとアベイラビリティーゾーンの指定されたインスタンススナップショットからインスタンスを作成します。  
**注:** 指定するバンドルは、スナップショットの作成に使用される元のソースインスタンスのバンドルと同等の仕様か、それ以上である必要があります。  

```
aws lightsail create-instances-from-snapshot \
    --instance-snapshot-name WordPress-1-1569866208 \
    --instance-names WordPress-2 \
    --availability-zone us-west-2a \
    --bundle-id small_3_0
```
出力:  

```
{
    "operations": [
        {
            "id": "003f8271-b711-464d-b9b8-7f3806cb496e",
            "resourceName": "WordPress-2",
            "resourceType": "Instance",
            "createdAt": 1569865914.908,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateInstancesFromSnapshot",
            "status": "Started",
            "statusChangedAt": 1569865914.908
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInstancesFromSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-instances-from-snapshot.html)」を参照してください。

### `create-instances`
<a name="lightsail_CreateInstances_cli_2_topic"></a>

次のコード例は、`create-instances` を使用する方法を示しています。

**AWS CLI**  
**例 1: 単一のインスタンスを作成するには**  
次の の`create-instances`例では、WordPress ブループリントと 5.00 USD バンドルを使用して、指定された AWS リージョンとアベイラビリティーゾーンにインスタンスを作成します。  

```
aws lightsail create-instances \
    --instance-names Instance-1 \
    --availability-zone us-west-2a \
    --blueprint-id wordpress \
    --bundle-id nano_3_0
```
出力:  

```
{
    "operations": [
        {
            "id": "9a77158f-7be3-4d6d-8054-cf5ae2b720cc",
            "resourceName": "Instance-1",
            "resourceType": "Instance",
            "createdAt": 1569447986.061,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateInstance",
            "status": "Started",
            "statusChangedAt": 1569447986.061
        }
    ]
}
```
**例 2: 一度に複数のインスタンスを作成するには**  
次の の`create-instances`例では、WordPress ブループリントと 5.00 USD バンドルを使用して、指定された AWS リージョンとアベイラビリティーゾーンに 3 つのインスタンスを作成します。  

```
aws lightsail create-instances \
    --instance-names {"Instance1","Instance2","Instance3"} \
    --availability-zone us-west-2a \
    --blueprint-id wordpress \
    --bundle-id nano_3_0
```
出力:  

```
{
    "operations": [
        {
            "id": "5492f015-9d2e-48c6-8eea-b516840e6903",
            "resourceName": "Instance1",
            "resourceType": "Instance",
            "createdAt": 1569448780.054,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateInstance",
            "status": "Started",
            "statusChangedAt": 1569448780.054
        },
        {
            "id": "c58b5f46-2676-44c8-b95c-3ad375898515",
            "resourceName": "Instance2",
            "resourceType": "Instance",
            "createdAt": 1569448780.054,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateInstance",
            "status": "Started",
            "statusChangedAt": 1569448780.054
        },
        {
            "id": "a5ad8006-9bee-4499-9eb7-75e42e6f5882",
            "resourceName": "Instance3",
            "resourceType": "Instance",
            "createdAt": 1569448780.054,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateInstance",
            "status": "Started",
            "statusChangedAt": 1569448780.054
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-instances.html)」を参照してください。

### `create-key-pair`
<a name="lightsail_CreateKeyPair_cli_2_topic"></a>

次のコード例は、`create-key-pair` を使用する方法を示しています。

**AWS CLI**  
**キーペアを作成するには**  
次の `create-key-pair` の例では、インスタンスの認証と接続に使用できるキーペアを作成します。  

```
aws lightsail create-key-pair \
    --key-pair-name MyPersonalKeyPair
```
出力はプライベートキー base64 値を提供します。この値は、作成したキーペアを使用するインスタンスへの認証に使用できます。**注:** プライベートキー base64 値は後で取得できないため、コピーして安全な場所に貼り付けます。  

```
{
    "keyPair": {
        "name": "MyPersonalKeyPair",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:KeyPair/55025c71-198f-403b-b42f-a69433e724fb",
        "supportCode": "621291663362/MyPersonalKeyPair",
        "createdAt": 1569866556.567,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "resourceType": "KeyPair"
    },
    "publicKeyBase64": "ssh-rsa ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCV0xUEwx96amPERH7K1bVT1tTFl9OmNk6o7m5YVHk9xlOdMbDRbFvhtXvw4jzJXXz5pBMxWOaGMz5K8QyTVOznoqp13Z8SBooH29hgmBNXiII1XPzEwqbj8mfo1+YVM5s5VuxWwm+BHUgedGUXno6uF7agqxZNO1kPLJBIVTW26SSYBJ0tE+y804UyVsjrbUqCaMXDhmfXpWulMPwuXhwcKh7e8hwoTfkiX0E6Ql+KqF/MiA3w6DCjEqvvdIO7SiEZJFsuGNfYDDN3w60Rel5MUhmn3OJdn4y/A7NWb3IxL4pPfVE4rgFRKU8n1jp9kwRnlVMVBOWuGXk6n+H6M2f1 ",
    "privateKeyBase64": "-----BEGIN RSA PRIVATE KEY-----EXAMPLETCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC\nVVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6\nb24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsEXAMPLEd\nBgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN\nMTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD\nVQQHEwdTZWF0dGxlMQ8wDQEXAMPLEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z\nb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt\nYXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMEXAMPLE4GmWIWJ\n21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T\nrDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE\nIbb3OhjZnzcvQAaREXAMPLEMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4\nnUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb\nFFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OEXAMPLELvjx79LjSTb\nNYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=\n-----END RSA PRIVATE KEY-----",
    "operation": {
        "id": "67f984db-9994-45fe-ad38-59bafcaf82ef",
        "resourceName": "MyPersonalKeyPair",
        "resourceType": "KeyPair",
        "createdAt": 1569866556.567,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "isTerminal": true,
        "operationType": "CreateKeyPair",
        "status": "Succeeded",
        "statusChangedAt": 1569866556.704
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-key-pair.html)」を参照してください。

### `create-load-balancer-tls-certificate`
<a name="lightsail_CreateLoadBalancerTlsCertificate_cli_2_topic"></a>

次のコード例は、`create-load-balancer-tls-certificate` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーの TLS 証明書を作成するには**  
次の `create-load-balancer-tls-certificate` の例では、指定されたロードバランサーにアタッチされた TLS 証明書を作成します。作成された証明書は、指定されたドメインに適用されます。**注:** ロードバランサーに対して作成できる証明書は 2 つだけです。  

```
aws lightsail create-load-balancer-tls-certificate \
    --certificate-alternative-names abc.example.com \
    --certificate-domain-name example.com \
    --certificate-name MySecondCertificate \
    --load-balancer-name MyFirstLoadBalancer
```
出力:  

```
{
    "operations": [
        {
            "id": "be663aed-cb46-41e2-9b23-e2f747245bd4",
            "resourceName": "MySecondCertificate",
            "resourceType": "LoadBalancerTlsCertificate",
            "createdAt": 1569867364.971,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "MyFirstLoadBalancer",
            "operationType": "CreateLoadBalancerTlsCertificate",
            "status": "Succeeded",
            "statusChangedAt": 1569867365.219
        },
        {
            "id": "f3dfa930-969e-41cc-ac7d-337178716f6d",
            "resourceName": "MyFirstLoadBalancer",
            "resourceType": "LoadBalancer",
            "createdAt": 1569867364.971,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "MySecondCertificate",
            "operationType": "CreateLoadBalancerTlsCertificate",
            "status": "Succeeded",
            "statusChangedAt": 1569867365.219
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLoadBalancerTlsCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-load-balancer-tls-certificate.html)」を参照してください。

### `create-load-balancer`
<a name="lightsail_CreateLoadBalancer_cli_2_topic"></a>

次のコード例は、`create-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーを作成するには**  
次の `create-load-balancer` の例では、TLS 証明書を使用してロードバランサーを作成します。TLS 証明書は、指定されたドメインに適用され、トラフィックをポート 80 のインスタンスにルーティングします。  

```
aws lightsail create-load-balancer \
    --certificate-alternative-names www.example.com test.example.com \
    --certificate-domain-name example.com \
    --certificate-name Certificate-1 \
    --instance-port 80 \
    --load-balancer-name LoadBalancer-1
```
出力:  

```
{
    "operations": [
        {
            "id": "cc7b920a-83d8-4762-a74e-9174fe1540be",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1569867169.406,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateLoadBalancer",
            "status": "Started",
            "statusChangedAt": 1569867169.406
        },
        {
            "id": "658ed43b-f729-42f3-a8e4-3f8024d3c98d",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancerTlsCertificate",
            "createdAt": 1569867170.193,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "LoadBalancer-1",
            "operationType": "CreateLoadBalancerTlsCertificate",
            "status": "Succeeded",
            "statusChangedAt": 1569867170.54
        },
        {
            "id": "4757a342-5181-4870-b1e0-227eebc35ab5",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1569867170.193,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "Certificate-1",
            "operationType": "CreateLoadBalancerTlsCertificate",
            "status": "Succeeded",
            "statusChangedAt": 1569867170.54
        }
    ]
}
```
詳細については、「*Lightsail Developer Guide*」の「[Lightsail load balancers](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/understanding-lightsail-load-balancers)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-load-balancer.html)」を参照してください。**

### `create-relational-database-from-snapshot`
<a name="lightsail_CreateRelationalDatabaseFromSnapshot_cli_2_topic"></a>

次のコード例は、`create-relational-database-from-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットからマネージドデータベースを作成するには**  
次の の`create-relational-database-from-snapshot`例では、15 USD の標準データベースバンドルを使用して、指定された AWS リージョンとアベイラビリティーゾーンの指定されたスナップショットからマネージドデータベースを作成します。**注:** 指定するバンドルは、スナップショットの作成に使用される元のソースデータベースのバンドルと同等の仕様か、それ以上である必要があります。  

```
aws lightsail create-relational-database-from-snapshot \
    --relational-database-snapshot-name Database-Oregon-1-1566839359 \
    --relational-database-name Database-1 \
    --availability-zone us-west-2a \
    --relational-database-bundle-id micro_1_0 \
    --no-publicly-accessible
```
出力:  

```
{
    "operations": [
        {
            "id": "ad6d9193-9d5c-4ea1-97ae-8fe6de600b4c",
            "resourceName": "Database-1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1569867916.938,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateRelationalDatabaseFromSnapshot",
            "status": "Started",
            "statusChangedAt": 1569867918.643
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRelationalDatabaseFromSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-relational-database-from-snapshot.html)」を参照してください。

### `create-relational-database-snapshot`
<a name="lightsail_CreateRelationalDatabaseSnapshot_cli_2_topic"></a>

次のコード例は、`create-relational-database-snapshot` を使用する方法を示しています。

**AWS CLI**  
**マネージドデータベースのスナップショットを作成するには**  
次の `create-relational-database-snapshot` の例では、指定されたマネージドデータベースのスナップショットを作成します。  

```
aws lightsail create-relational-database-snapshot \
    --relational-database-name Database1 \
    --relational-database-snapshot-name RelationalDatabaseSnapshot1
```
出力:  

```
{
    "operations": [
        {
            "id": "853667fb-ea91-4c02-8d20-8fc5fd43b9eb",
            "resourceName": "RelationalDatabaseSnapshot1",
            "resourceType": "RelationalDatabaseSnapshot",
            "createdAt": 1569868074.645,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "Database1",
            "operationType": "CreateRelationalDatabaseSnapshot",
            "status": "Started",
            "statusChangedAt": 1569868074.645
        },
        {
            "id": "fbafa521-3cac-4be8-9773-1c143780b239",
            "resourceName": "Database1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1569868074.645,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "RelationalDatabaseSnapshot1",
            "operationType": "CreateRelationalDatabaseSnapshot",
            "status": "Started",
            "statusChangedAt": 1569868074.645
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRelationalDatabaseSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-relational-database-snapshot.html)」を参照してください。

### `create-relational-database`
<a name="lightsail_CreateRelationalDatabase_cli_2_topic"></a>

次のコード例は、`create-relational-database` を使用する方法を示しています。

**AWS CLI**  
**マネージドデータベースを作成するには**  
次の の`create-relational-database`例では、MySQL 5.6 データベースエンジン (mysql\$15\$16) と 15 USD の標準データベースバンドル (micro\$11\$10) を使用して、指定された AWS リージョンとアベイラビリティーゾーンにマネージドデータベースを作成します。マネージドデータベースにはマスターユーザー名があらかじめ入力されており、パブリックにアクセスすることはできません。  

```
aws lightsail create-relational-database \
    --relational-database-name Database-1 \
    --availability-zone us-west-2a \
    --relational-database-blueprint-id mysql_5_6 \
    --relational-database-bundle-id micro_1_0 \
    --master-database-name dbmaster \
    --master-username user \
    --no-publicly-accessible
```
出力:  

```
{
    "operations": [
        {
            "id": "b52bedee-73ed-4798-8d2a-9c12df89adcd",
            "resourceName": "Database-1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1569450017.244,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "CreateRelationalDatabase",
            "status": "Started",
            "statusChangedAt": 1569450018.637
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRelationalDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/create-relational-database.html)」を参照してください。

### `delete-auto-snapshot`
<a name="lightsail_DeleteAutoSnapshot_cli_2_topic"></a>

次のコード例は、`delete-auto-snapshot` を使用する方法を示しています。

**AWS CLI**  
**自動スナップショットは削除するには**  
次の `delete-auto-snapshot` の例では、インスタンス `WordPress-1` の自動スナップショット `2019-10-10` を削除します。  

```
aws lightsail delete-auto-snapshot \
    --resource-name WordPress-1 \
    --date 2019-10-10
```
出力:  

```
{
    "operations": [
        {
            "id": "31c36e09-3d52-46d5-b6d8-7EXAMPLE534a",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1571088141.501,
            "location": {
                "availabilityZone": "us-west-2",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "DeleteAutoSnapshot-2019-10-10",
            "operationType": "DeleteAutoSnapshot",
            "status": "Succeeded"
        }
    ]
}
```
詳細については、「*Lightsail Dev Guide*」の「[Deleting automatic snapshots of instances or disks in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-deleting-automatic-snapshots)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAutoSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-auto-snapshot.html)」を参照してください。

### `delete-disk-snapshot`
<a name="lightsail_DeleteDiskSnapshot_cli_2_topic"></a>

次のコード例は、`delete-disk-snapshot` を使用する方法を示しています。

**AWS CLI**  
**ブロックストレージディスクのスナップショットを削除するには**  
次の `delete-disk-snapshot` の例では、ブロックストレージディスクの指定されたスナップショットを削除します。  

```
aws lightsail delete-disk-snapshot \
    --disk-snapshot-name DiskSnapshot-1
```
出力:  

```
{
    "operations": [
        {
            "id": "d1e5766d-b81e-4595-ad5d-02afbccfcd5d",
            "resourceName": "DiskSnapshot-1",
            "resourceType": "DiskSnapshot",
            "createdAt": 1569873552.79,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "DeleteDiskSnapshot",
            "status": "Succeeded",
            "statusChangedAt": 1569873552.79
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDiskSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-disk-snapshot.html)」を参照してください。

### `delete-disk`
<a name="lightsail_DeleteDisk_cli_2_topic"></a>

次のコード例は、`delete-disk` を使用する方法を示しています。

**AWS CLI**  
**ブロックストレージディスクを削除するには**  
次の `delete-disk` の例では、指定されたブロックストレージディスクを削除します。  

```
aws lightsail delete-disk \
    --disk-name Disk-1
```
出力:  

```
{
    "operations": [
        {
            "id": "6378c70f-4d75-4f7a-ab66-730fca0bb2fc",
            "resourceName": "Disk-1",
            "resourceType": "Disk",
            "createdAt": 1569872887.864,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "DeleteDisk",
            "status": "Succeeded",
            "statusChangedAt": 1569872887.864
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDisk](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-disk.html)」を参照してください。

### `delete-domain-entry`
<a name="lightsail_DeleteDomainEntry_cli_2_topic"></a>

次のコード例は、`delete-domain-entry` を使用する方法を示しています。

**AWS CLI**  
**ドメインエントリを削除するには (DNS レコード)**  
次の `delete-domain-entry` の例では、既存のドメインから、指定されたドメインエントリを削除します。  
**注:** Lightsailのドメイン関連の API オペレーションは、 `us-east-1`リージョンでのみ使用できます。CLI プロファイルが別のリージョンを使用するように設定されている場合は、`--region us-east-1` パラメータを含める必要があります。そうしないと、コマンドは失敗します。  

```
aws lightsail delete-domain-entry \
    --region us-east-1 \
    --domain-name example.com \
    --domain-entry name=123.example.com,target=192.0.2.0,type=A
```
出力:  

```
{
    "operation": {
        "id": "06eacd01-d785-420e-8daa-823150c7dca1",
        "resourceName": "example.com ",
        "resourceType": "Domain",
        "createdAt": 1569874157.005,
        "location": {
            "availabilityZone": "all",
            "regionName": "global"
        },
        "isTerminal": true,
        "operationType": "DeleteDomainEntry",
        "status": "Succeeded",
        "statusChangedAt": 1569874157.005
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDomainEntry](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-domain-entry.html)」を参照してください。

### `delete-domain`
<a name="lightsail_DeleteDomain_cli_2_topic"></a>

次のコード例は、`delete-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインを削除するには (DNS ゾーン)**  
次の `delete-domain` の例では、指定されたドメインとドメイン内のすべてのエントリ (DNS レコード) を削除します。  
**注:** Lightsailのドメイン関連の API オペレーションは、 `us-east-1`リージョンでのみ使用できます。CLI プロファイルが別のリージョンを使用するように設定されている場合は、`--region us-east-1` パラメータを含める必要があります。そうしないと、コマンドは失敗します。  

```
aws lightsail delete-domain \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "operation": {
        "id": "fcef5265-5af1-4a46-a3d7-90b5e18b9b32",
        "resourceName": "example.com",
        "resourceType": "Domain",
        "createdAt": 1569873788.13,
        "location": {
            "availabilityZone": "all",
            "regionName": "global"
        },
        "isTerminal": true,
        "operationType": "DeleteDomain",
        "status": "Succeeded",
        "statusChangedAt": 1569873788.13
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-domain.html)」を参照してください。

### `delete-instance-snapshot`
<a name="lightsail_DeleteInstanceSnapshot_cli_2_topic"></a>

次のコード例は、`delete-instance-snapshot` を使用する方法を示しています。

**AWS CLI**  
**title**  
次の `delete-instance-snapshot` の例では、インスタンスの指定されたスナップショットを削除します。  

```
aws lightsail delete-instance-snapshot \
    --instance-snapshot-name WordPress-1-Snapshot-1
```
出力:  

```
{
    "operations": [
        {
            "id": "14dad182-976a-46c6-bfd4-9480482bf0ea",
            "resourceName": "WordPress-1-Snapshot-1",
            "resourceType": "InstanceSnapshot",
            "createdAt": 1569874524.562,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "DeleteInstanceSnapshot",
            "status": "Succeeded",
            "statusChangedAt": 1569874524.562
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInstanceSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-instance-snapshot.html)」を参照してください。

### `delete-instance`
<a name="lightsail_DeleteInstance_cli_2_topic"></a>

次のコード例は、`delete-instance` を使用する方法を示しています。

**AWS CLI**  
**インスタンスを削除するには**  
次の `delete-instance` の例では、指定されたインスタンスを削除します。  

```
aws lightsail delete-instance \
    --instance-name WordPress-1
```
出力:  

```
{
    "operations": [
        {
            "id": "d77345a3-8f80-4d2e-b47d-aaa622718df2",
            "resourceName": "Disk-1",
            "resourceType": "Disk",
            "createdAt": 1569874357.469,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "WordPress-1",
            "operationType": "DetachDisk",
            "status": "Started",
            "statusChangedAt": 1569874357.469
        },
        {
            "id": "708fa606-2bfd-4e48-a2c1-0b856585b5b1",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1569874357.465,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "Disk-1",
            "operationType": "DetachDisk",
            "status": "Started",
            "statusChangedAt": 1569874357.465
        },
        {
            "id": "3187e823-8acb-405d-b098-fad5ceb17bec",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1569874357.829,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "DeleteInstance",
            "status": "Succeeded",
            "statusChangedAt": 1569874357.829
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-instance.html)」を参照してください。

### `delete-key-pair`
<a name="lightsail_DeleteKeyPair_cli_2_topic"></a>

次のコード例は、`delete-key-pair` を使用する方法を示しています。

**AWS CLI**  
**キーペアを削除するには**  
次の `delete-key-pair` の例では、指定されたキーペアを削除します。  

```
aws lightsail delete-key-pair \
    --key-pair-name MyPersonalKeyPair
```
出力:  

```
{
    "operation": {
        "id": "81621463-df38-4810-b866-6e801a15abbf",
        "resourceName": "MyPersonalKeyPair",
        "resourceType": "KeyPair",
        "createdAt": 1569874626.466,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "isTerminal": true,
        "operationType": "DeleteKeyPair",
        "status": "Succeeded",
        "statusChangedAt": 1569874626.685
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-key-pair.html)」を参照してください。

### `delete-known-host-keys`
<a name="lightsail_DeleteKnownHostKeys_cli_2_topic"></a>

次のコード例は、`delete-known-host-keys` を使用する方法を示しています。

**AWS CLI**  
**インスタンスから既知のホストキーを削除するには**  
次の `delete-known-host-keys` の例では、指定されたインスタンスから既知のホストキーを削除します。  

```
aws lightsail delete-known-host-keys \
    --instance-name Instance-1
```
出力:  

```
{
    "operations": [
        {
            "id": "c61afe9c-45a4-41e6-a97e-d212364da3f5",
            "resourceName": "Instance-1",
            "resourceType": "Instance",
            "createdAt": 1569874760.201,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "DeleteKnownHostKeys",
            "status": "Succeeded",
            "statusChangedAt": 1569874760.201
        }
    ]
}
```
詳細については、「*Lightsail Dev Guide*」の「[Troubleshooting connection issues with the Amazon Lightsail browser-based SSH or RDP client](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-troubleshooting-browser-based-ssh-rdp-client-connection)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteKnownHostKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-known-host-keys.html)」を参照してください。

### `delete-load-balancer-tls-certificate`
<a name="lightsail_DeleteLoadBalancerTlsCertificate_cli_2_topic"></a>

次のコード例は、`delete-load-balancer-tls-certificate` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーの TLS 証明書を削除するには**  
次の `delete-load-balancer-tls-certificate` の例では、指定されたロードバランサーから、指定された TLS 証明書を削除します。  

```
aws lightsail delete-load-balancer-tls-certificate \
    --load-balancer-name MyFirstLoadBalancer \
    --certificate-name MyFirstCertificate
```
出力:  

```
{
    "operations": [
        {
            "id": "50bec274-e45e-4caa-8a69-b763ef636583",
            "resourceName": "MyFirstCertificate",
            "resourceType": "LoadBalancerTlsCertificate",
            "createdAt": 1569874989.48,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "DeleteLoadBalancerTlsCertificate",
            "status": "Started",
            "statusChangedAt": 1569874989.48
        },
        {
            "id": "78c58cdc-a59a-4b27-8213-500638634a8f",
            "resourceName": "MyFirstLoadBalancer",
            "resourceType": "LoadBalancer",
            "createdAt": 1569874989.48,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "DeleteLoadBalancerTlsCertificate",
            "status": "Started",
            "statusChangedAt": 1569874989.48
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLoadBalancerTlsCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-load-balancer-tls-certificate.html)」を参照してください。

### `delete-load-balancer`
<a name="lightsail_DeleteLoadBalancer_cli_2_topic"></a>

次のコード例は、`delete-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーを削除するには**  
次の `delete-load-balancer` の例では、指定されたロードバランサーと関連する TLS 証明書を削除します。  

```
aws lightsail delete-load-balancer \
    --load-balancer-name MyFirstLoadBalancer
```
出力:  

```
{
    "operations": [
        {
            "id": "a8c968c7-72a3-4680-a714-af8f03eea535",
            "resourceName": "MyFirstLoadBalancer",
            "resourceType": "LoadBalancer",
            "createdAt": 1569875092.125,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "DeleteLoadBalancer",
            "status": "Succeeded",
            "statusChangedAt": 1569875092.125
        },
        {
            "id": "f91a29fc-8ce3-4e69-a227-ea70ca890bf5",
            "resourceName": "MySecondCertificate",
            "resourceType": "LoadBalancerTlsCertificate",
            "createdAt": 1569875091.938,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "DeleteLoadBalancerTlsCertificate",
            "status": "Started",
            "statusChangedAt": 1569875091.938
        },
        {
            "id": "cf64c060-154b-4eb4-ba57-84e2e41563d6",
            "resourceName": "MyFirstLoadBalancer",
            "resourceType": "LoadBalancer",
            "createdAt": 1569875091.94,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "DeleteLoadBalancerTlsCertificate",
            "status": "Started",
            "statusChangedAt": 1569875091.94
        }
    ]
}
```
詳細については、*ガイド*のタイトルを参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-load-balancer.html)」を参照してください。**

### `delete-relational-database-snapshot`
<a name="lightsail_DeleteRelationalDatabaseSnapshot_cli_2_topic"></a>

次のコード例は、`delete-relational-database-snapshot` を使用する方法を示しています。

**AWS CLI**  
**マネージドデータベースのスナップショットを削除するには**  
次の `delete-relational-database-snapshot` の例では、マネージドデータベースの指定されたスナップショットを削除します。  

```
aws lightsail delete-relational-database-snapshot \
    --relational-database-snapshot-name Database-Oregon-1-1566839359
```
出力:  

```
{
    "operations": [
        {
            "id": "b99acae8-735b-4823-922f-30af580e3729",
            "resourceName": "Database-Oregon-1-1566839359",
            "resourceType": "RelationalDatabaseSnapshot",
            "createdAt": 1569875293.58,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "DeleteRelationalDatabaseSnapshot",
            "status": "Succeeded",
            "statusChangedAt": 1569875293.58
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRelationalDatabaseSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-relational-database-snapshot.html)」を参照してください。

### `delete-relational-database`
<a name="lightsail_DeleteRelationalDatabase_cli_2_topic"></a>

次のコード例は、`delete-relational-database` を使用する方法を示しています。

**AWS CLI**  
**マネージドデータベースを削除するには**  
次の `delete-relational-database` の例では、指定されたマネージドデータベースを削除します。  

```
aws lightsail delete-relational-database \
    --relational-database-name Database-1
```
出力:  

```
{
    "operations": [
        {
            "id": "3b0c41c1-053d-46f0-92a3-14f76141dc86",
            "resourceName": "Database-1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1569875210.999,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "DeleteRelationalDatabase",
            "status": "Started",
            "statusChangedAt": 1569875210.999
        },
        {
            "id": "01ddeae8-a87a-4a4b-a1f3-092c71bf9180",
            "resourceName": "Database-1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1569875211.029,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "Database-1-FinalSnapshot-1569875210793",
            "operationType": "CreateRelationalDatabaseSnapshot",
            "status": "Started",
            "statusChangedAt": 1569875211.029
        },
        {
            "id": "74d73681-30e8-4532-974e-1f23cd3f9f73",
            "resourceName": "Database-1-FinalSnapshot-1569875210793",
            "resourceType": "RelationalDatabaseSnapshot",
            "createdAt": 1569875211.029,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "Database-1",
            "operationType": "CreateRelationalDatabaseSnapshot",
            "status": "Started",
            "statusChangedAt": 1569875211.029
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRelationalDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/delete-relational-database.html)」を参照してください。

### `detach-static-ip`
<a name="lightsail_DetachStaticIp_cli_2_topic"></a>

次のコード例は、`detach-static-ip` を使用する方法を示しています。

**AWS CLI**  
**インスタンスから静的 IP をデタッチするには**  
次の `detach-static-ip` の例では、アタッチされたインスタンスから静的 IP `StaticIp-1` をデタッチします。  

```
aws lightsail detach-static-ip \
    --static-ip-name StaticIp-1
```
出力:  

```
{
    "operations": [
        {
            "id": "2a43d8a3-9f2d-4fe7-bdd0-eEXAMPLE3cf3",
            "resourceName": "StaticIp-1",
            "resourceType": "StaticIp",
            "createdAt": 1571088261.999,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "MEAN-1",
            "operationType": "DetachStaticIp",
            "status": "Succeeded",
            "statusChangedAt": 1571088261.999
        },
        {
            "id": "41a7d40c-74e8-4d2e-a837-cEXAMPLEf747",
            "resourceName": "MEAN-1",
            "resourceType": "Instance",
            "createdAt": 1571088262.022,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "StaticIp-1",
            "operationType": "DetachStaticIp",
            "status": "Succeeded",
            "statusChangedAt": 1571088262.022
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DetachStaticIp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/detach-static-ip.html)」を参照してください。

### `get-active-names`
<a name="lightsail_GetActiveNames_cli_2_topic"></a>

次のコード例は、`get-active-names` を使用する方法を示しています。

**AWS CLI**  
**アクティブなリソース名を取得するには**  
次の の`get-active-names`例では、設定された AWS リージョンのアクティブなリソース名を返します。  

```
aws lightsail get-active-names
```
出力:  

```
{
    "activeNames": [
        "WordPress-1",
        "StaticIp-1",
        "MEAN-1",
        "Plesk_Hosting_Stack_on_Ubuntu-1"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetActiveNames](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-active-names.html)」を参照してください。

### `get-auto-snapshots`
<a name="lightsail_GetAutoSnapshots_cli_2_topic"></a>

次のコード例は、`get-auto-snapshots` を使用する方法を示しています。

**AWS CLI**  
**インスタンスで使用可能な自動スナップショットを取得するには**  
次の `get-auto-snapshots` の例では、インスタンス `WordPress-1` で使用可能な自動スナップショットを返します。  

```
aws lightsail get-auto-snapshots \
    --resource-name WordPress-1
```
出力:  

```
{
    "resourceName": "WordPress-1",
    "resourceType": "Instance",
    "autoSnapshots": [
        {
            "date": "2019-10-14",
            "createdAt": 1571033872.0,
            "status": "Success",
            "fromAttachedDisks": []
        },
        {
            "date": "2019-10-13",
            "createdAt": 1570947473.0,
            "status": "Success",
            "fromAttachedDisks": []
        },
        {
            "date": "2019-10-12",
            "createdAt": 1570861072.0,
            "status": "Success",
            "fromAttachedDisks": []
        },
        {
            "date": "2019-10-11",
            "createdAt": 1570774672.0,
            "status": "Success",
            "fromAttachedDisks": []
        }
    ]
}
```
詳細については、「*Lightsail Dev Guide*」の「[Keeping automatic snapshots of instances or disks in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-keeping-automatic-snapshots)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAutoSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-auto-snapshots.html)」を参照してください。

### `get-blueprints`
<a name="lightsail_GetBlueprints_cli_2_topic"></a>

次のコード例は、`get-blueprints` を使用する方法を示しています。

**AWS CLI**  
**新しいインスタンスのブループリントを取得するには**  
次の `get-blueprints` の例では、Amazon Lightsail で新しいインスタンスを作成するために使用できるすべてのブループリントの詳細を表示します。  

```
aws lightsail get-blueprints
```
出力:  

```
{
    "blueprints": [
        {
            "blueprintId": "wordpress",
            "name": "WordPress",
            "group": "wordpress",
            "type": "app",
            "description": "Bitnami, the leaders in application packaging, and Automattic, the experts behind WordPress, have teamed up to offer this official WordPress image. This image is a pre-configured, ready-to-run image for running WordPress on Amazon Lightsail. WordPress is the world's most popular content management platform. Whether it's for an enterprise or small business website, or a personal or corporate blog, content authors can easily create content using its new Gutenberg editor, and developers can extend the base platform with additional features. Popular plugins like Jetpack, Akismet, All in One SEO Pack, WP Mail, Google Analytics for WordPress, and Amazon Polly are all pre-installed in this image. Let's Encrypt SSL certificates are supported through an auto-configuration script.",
            "isActive": true,
            "minPower": 0,
            "version": "6.5.3-0",
            "versionCode": "1",
            "productUrl": "https://aws.amazon.com/marketplace/pp/B00NN8Y43U",
            "licenseUrl": "https://aws.amazon.com/marketplace/pp/B00NN8Y43U#pdp-usage",
            "platform": "LINUX_UNIX"
        },
        {
            "blueprintId": "lamp_8_bitnami",
            "name": "LAMP (PHP 8)",
            "group": "lamp_8",
            "type": "app",
            "description": "LAMP with PHP 8.X packaged by Bitnami enables you to quickly start building your websites and applications by providing a coding framework. As a developer, it provides standalone project directories to store your applications. This blueprint is configured for production environments. It includes SSL auto-configuration with Let's Encrypt certificates, and the latest releases of PHP, Apache, and MariaDB on Linux. This application also includes phpMyAdmin, PHP main modules and Composer.",
            "isActive": true,
            "minPower": 0,
            "version": "8.2.18-4",
            "versionCode": "1",
            "productUrl": "https://aws.amazon.com/marketplace/pp/prodview-6g3gzfcih6dvu",
            "licenseUrl": "https://aws.amazon.com/marketplace/pp/prodview-6g3gzfcih6dvu#pdp-usage",
            "platform": "LINUX_UNIX"
        },
        {
            "blueprintId": "nodejs",
            "name": "Node.js",
            "group": "node",
            "type": "app",
            "description": "Node.js packaged by Bitnami is a pre-configured, ready to run image for Node.js on Amazon EC2. It includes the latest version of Node.js, Apache, Python and Redis. The image supports multiple Node.js applications, each with its own virtual host and project directory. It is configured for production use and is secure by default, as all ports except HTTP, HTTPS and SSH ports are closed. Let's Encrypt SSL certificates are supported through an auto-configuration script. Developers benefit from instant access to a secure, update and consistent Node.js environment without having to manually install and configure multiple components and libraries.",
            "isActive": true,
            "minPower": 0,
            "version": "18.20.2-0",
            "versionCode": "1",
            "productUrl": "https://aws.amazon.com/marketplace/pp/B00NNZUAKO",
            "licenseUrl": "https://aws.amazon.com/marketplace/pp/B00NNZUAKO#pdp-usage",
            "platform": "LINUX_UNIX"
        },
        ...
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBlueprints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-blueprints.html)」を参照してください。

### `get-bundles`
<a name="lightsail_GetBundles_cli_2_topic"></a>

次のコード例は、`get-bundles` を使用する方法を示しています。

**AWS CLI**  
**新しいインスタンスのバンドルを取得するには**  
次の `get-bundles` の例では、Amazon Lightsail で新しいインスタンスを作成するために使用できるすべてのバンドルの詳細を表示します。  

```
aws lightsail get-bundles
```
出力:  

```
{
    "bundles": [
        {
            "price": 5.0,
            "cpuCount": 2,
            "diskSizeInGb": 20,
            "bundleId": "nano_3_0",
            "instanceType": "nano",
            "isActive": true,
            "name": "Nano",
            "power": 298,
            "ramSizeInGb": 0.5,
            "transferPerMonthInGb": 1024,
            "supportedPlatforms": [
                "LINUX_UNIX"
            ]
        },
        {
            "price": 7.0,
            "cpuCount": 2,
            "diskSizeInGb": 40,
            "bundleId": "micro_3_0",
            "instanceType": "micro",
            "isActive": true,
            "name": "Micro",
            "power": 500,
            "ramSizeInGb": 1.0,
            "transferPerMonthInGb": 2048,
            "supportedPlatforms": [
                "LINUX_UNIX"
            ]
        },
        {
            "price": 12.0,
            "cpuCount": 2,
            "diskSizeInGb": 60,
            "bundleId": "small_3_0",
            "instanceType": "small",
            "isActive": true,
            "name": "Small",
            "power": 1000,
            "ramSizeInGb": 2.0,
            "transferPerMonthInGb": 3072,
            "supportedPlatforms": [
                "LINUX_UNIX"
            ]
        },
        ...
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBundles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-bundles.html)」を参照してください。

### `get-cloud-formation-stack-records`
<a name="lightsail_GetCloudFormationStackRecords_cli_2_topic"></a>

次のコード例は、`get-cloud-formation-stack-records` を使用する方法を示しています。

**AWS CLI**  
**CloudFormation スタックレコードと関連するスタックを取得するには**  
次の `get-cloud-formation-stack-records` の例では、エクスポートされた Amazon Lightsail スナップショットから Amazon EC2 リソースを作成するために使用される CloudFormation スタックレコードと、それらに関連するスタックの詳細を示します。  

```
aws lightsail get-cloud-formation-stack-records
```
出力:  

```
{
    "cloudFormationStackRecords": [
        {
            "name": "CloudFormationStackRecord-588a4243-e2d1-490d-8200-3a7513ecebdf",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:CloudFormationStackRecord/28d646ab-27bc-48d9-a422-1EXAMPLE6d37",
            "createdAt": 1565301666.586,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "CloudFormationStackRecord",
            "state": "Succeeded",
            "sourceInfo": [
                {
                    "resourceType": "ExportSnapshotRecord",
                    "name": "ExportSnapshotRecord-e02f23d7-0453-4aa9-9c95-91aa01a141dd",
                    "arn": "arn:aws:lightsail:us-west-2:111122223333:ExportSnapshotRecord/f12b8792-f3ea-4d6f-b547-2EXAMPLE8796"
                }
            ],
            "destinationInfo": {
                "id": "arn:aws:cloudformation:us-west-2:111122223333:stack/Lightsail-Stack-588a4243-e2d1-490d-8200-3EXAMPLEebdf/063203b0-ba28-11e9-838b-0EXAMPLE8b00",
                "service": "Aws::CloudFormation::Stack"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCloudFormationStackRecords](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-cloud-formation-stack-records.html)」を参照してください。

### `get-disk-snapshot`
<a name="lightsail_GetDiskSnapshot_cli_2_topic"></a>

次のコード例は、`get-disk-snapshot` を使用する方法を示しています。

**AWS CLI**  
**ディスクスナップショットに関する情報を取得するには**  
次の `get-disk-snapshot` の例では、ディスクスナップショット `Disk-1-1566839161` の詳細を表示します。  

```
aws lightsail get-disk-snapshot \
    --disk-snapshot-name Disk-1-1566839161
```
出力:  

```
{
    "diskSnapshot": {
        "name": "Disk-1-1566839161",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:DiskSnapshot/e2d0fa53-8ee0-41a0-8e56-0EXAMPLE1051",
        "supportCode": "6EXAMPLE3362/snap-0EXAMPLE06100d09",
        "createdAt": 1566839163.749,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "resourceType": "DiskSnapshot",
        "tags": [],
        "sizeInGb": 8,
        "state": "completed",
        "progress": "100%",
        "fromDiskName": "Disk-1",
        "fromDiskArn": "arn:aws:lightsail:us-west-2:111122223333:Disk/c21cfb0a-07f2-44ae-9a23-bEXAMPLE8096",
        "isFromAutoSnapshot": false
    }
}
```
詳細については、*ガイド*のタイトルを参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDiskSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-disk-snapshot.html)」を参照してください。

### `get-disk-snapshots`
<a name="lightsail_GetDiskSnapshots_cli_2_topic"></a>

次のコード例は、`get-disk-snapshots` を使用する方法を示しています。

**AWS CLI**  
**すべてのディスクスナップショットに関する情報を取得するには**  
次の の`get-disk-snapshots`例では、設定された AWS リージョン内のすべてのディスクスナップショットの詳細を表示します。  

```
aws lightsail get-disk-snapshots
```
出力:  

```
{
    "diskSnapshots": [
        {
            "name": "Disk-2-1571090588",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:DiskSnapshot/32e889a9-38d4-4687-9f21-eEXAMPLE7839",
            "supportCode": "6EXAMPLE3362/snap-0EXAMPLE1ca192a4",
            "createdAt": 1571090591.226,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "DiskSnapshot",
            "tags": [],
            "sizeInGb": 8,
            "state": "completed",
            "progress": "100%",
            "fromDiskName": "Disk-2",
            "fromDiskArn": "arn:aws:lightsail:us-west-2:111122223333:Disk/6a343ff8-6341-422d-86e2-bEXAMPLE16c2",
            "isFromAutoSnapshot": false
        },
        {
            "name": "Disk-1-1566839161",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:DiskSnapshot/e2d0fa53-8ee0-41a0-8e56-0EXAMPLE1051",
            "supportCode": "6EXAMPLE3362/snap-0EXAMPLEe06100d09",
            "createdAt": 1566839163.749,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "DiskSnapshot",
            "tags": [],
            "sizeInGb": 8,
            "state": "completed",
            "progress": "100%",
            "fromDiskName": "Disk-1",
            "fromDiskArn": "arn:aws:lightsail:us-west-2:111122223333:Disk/c21cfb0a-07f2-44ae-9a23-bEXAMPLE8096",
            "isFromAutoSnapshot": false
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDiskSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-disk-snapshots.html)」を参照してください。

### `get-disk`
<a name="lightsail_GetDisk_cli_2_topic"></a>

次のコード例は、`get-disk` を使用する方法を示しています。

**AWS CLI**  
**ブロックストレージディスクに関する情報を取得するには**  
次の `get-disk` の例では、ディスク `Disk-1` に関する詳細を表示します。  

```
aws lightsail get-disk \
    --disk-name Disk-1
```
出力:  

```
{
    "disk": {
        "name": "Disk-1",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:Disk/c21cfb0a-07f2-44ae-9a23-bEXAMPLE8096",
        "supportCode": "6EXAMPLE3362/vol-0EXAMPLEf2f88b32f",
        "createdAt": 1566585439.587,
        "location": {
            "availabilityZone": "us-west-2a",
            "regionName": "us-west-2"
        },
        "resourceType": "Disk",
        "tags": [],
        "sizeInGb": 8,
        "isSystemDisk": false,
        "iops": 100,
        "path": "/dev/xvdf",
        "state": "in-use",
        "attachedTo": "WordPress_Multisite-1",
        "isAttached": true,
        "attachmentState": "attached"
    }
}
```
詳細については、*ガイド*のタイトルを参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDisk](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-disk.html)」を参照してください。

### `get-disks`
<a name="lightsail_GetDisks_cli_2_topic"></a>

次のコード例は、`get-disks` を使用する方法を示しています。

**AWS CLI**  
**すべてのブロックストレージディスクに関する情報を取得するには**  
次の の`get-disks`例では、設定された AWS リージョン内のすべてのディスクに関する詳細を表示します。  

```
aws lightsail get-disks
```
出力:  

```
{
    "disks": [
        {
            "name": "Disk-2",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:Disk/6a343ff8-6341-422d-86e2-bEXAMPLE16c2",
            "supportCode": "6EXAMPLE3362/vol-0EXAMPLE929602087",
            "createdAt": 1571090461.634,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "resourceType": "Disk",
            "tags": [],
            "sizeInGb": 8,
            "isSystemDisk": false,
            "iops": 100,
            "state": "available",
            "isAttached": false,
            "attachmentState": "detached"
        },
        {
            "name": "Disk-1",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:Disk/c21cfb0a-07f2-44ae-9a23-bEXAMPLE8096",
            "supportCode": "6EXAMPLE3362/vol-0EXAMPLEf2f88b32f",
            "createdAt": 1566585439.587,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "resourceType": "Disk",
            "tags": [],
            "sizeInGb": 8,
            "isSystemDisk": false,
            "iops": 100,
            "path": "/dev/xvdf",
            "state": "in-use",
            "attachedTo": "WordPress_Multisite-1",
            "isAttached": true,
            "attachmentState": "attached"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDisks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-disks.html)」を参照してください。

### `get-domain`
<a name="lightsail_GetDomain_cli_2_topic"></a>

次のコード例は、`get-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインに関する情報を取得するには**  
次の `get-domain` の例では、ドメイン `example.com` の詳細を表示します。  
**注:** Lightsailのドメイン関連の API オペレーションは、 `us-east-1` AWS リージョンでのみ使用できます。CLI プロファイルが別のリージョンを使用するように設定されている場合は、`` --region us-east-1`` パラメータを含める必要があります。そうしないと、コマンドは失敗します。  

```
aws lightsail get-domain \
    --domain-name example.com \
    --region us-east-1
```
出力:  

```
{
    "domain": {
        "name": "example.com",
        "arn": "arn:aws:lightsail:global:111122223333:Domain/28cda903-3f15-44b2-9baf-3EXAMPLEb304",
        "supportCode": "6EXAMPLE3362//hostedzone/ZEXAMPLEONGSC1",
        "createdAt": 1570728588.6,
        "location": {
            "availabilityZone": "all",
            "regionName": "global"
        },
        "resourceType": "Domain",
        "tags": [],
        "domainEntries": [
            {
                "id": "-1682899164",
                "name": "example.com",
                "target": "192.0.2.0",
                "isAlias": false,
                "type": "A"
            },
            {
                "id": "1703104243",
                "name": "example.com",
                "target": "ns-137.awsdns-17.com",
                "isAlias": false,
                "type": "NS"
            },
            {
                "id": "-1038331153",
                "name": "example.com",
                "target": "ns-1710.awsdns-21.co.uk",
                "isAlias": false,
                "type": "NS"
            },
            {
                "id": "-2107289565",
                "name": "example.com",
                "target": "ns-692.awsdns-22.net",
                "isAlias": false,
                "type": "NS"
            },
            {
                "id": "1582095705",
                "name": "example.com",
                "target": "ns-1436.awsdns-51.org",
                "isAlias": false,
                "type": "NS"
            },
            {
                "id": "-1769796132",
                "name": "example.com",
                "target": "ns-1710.awsdns-21.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400",
                "isAlias": false,
                "type": "SOA"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-domain.html)」を参照してください。

### `get-domains`
<a name="lightsail_GetDomains_cli_2_topic"></a>

次のコード例は、`get-domains` を使用する方法を示しています。

**AWS CLI**  
**すべてのドメインに関する情報を取得するには**  
次の の`get-domains`例では、設定された AWS リージョン内のすべてのドメインに関する詳細を表示します。  
**注:** Lightsailのドメイン関連の API オペレーションは、 `us-east-1` AWS リージョンでのみ使用できます。CLI プロファイルが別のリージョンを使用するように設定されている場合は、`--region us-east-1` パラメータを含める必要があります。そうしないと、コマンドは失敗します。  

```
aws lightsail get-domains \
    --region us-east-1
```
出力:  

```
{
    "domains": [
        {
            "name": "example.com",
            "arn": "arn:aws:lightsail:global:111122223333:Domain/28cda903-3f15-44b2-9baf-3EXAMPLEb304",
            "supportCode": "6EXAMPLE3362//hostedzone/ZEXAMPLEONGSC1",
            "createdAt": 1570728588.6,
            "location": {
                "availabilityZone": "all",
                "regionName": "global"
            },
            "resourceType": "Domain",
            "tags": [],
            "domainEntries": [
                {
                    "id": "-1682899164",
                    "name": "example.com",
                    "target": "192.0.2.0",
                    "isAlias": false,
                    "type": "A"
                },
                {
                    "id": "1703104243",
                    "name": "example.com",
                    "target": "ns-137.awsdns-17.com",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "-1038331153",
                    "name": "example.com",
                    "target": "ns-4567.awsdns-21.co.uk",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "-2107289565",
                    "name": "example.com",
                    "target": "ns-333.awsdns-22.net",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "1582095705",
                    "name": "example.com",
                    "target": "ns-1111.awsdns-51.org",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "-1769796132",
                    "name": "example.com",
                    "target": "ns-1234.awsdns-21.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400",
                    "isAlias": false,
                    "type": "SOA"
                },
                {
                    "id": "1029454894",
                    "name": "_dead6a124ede046a0319eb44a4eb3cbc.example.com",
                    "target": "_be133b0a0899fb7b6bf79d9741d1a383.hkvuiqjoua.acm-validations.aws",
                    "isAlias": false,
                    "type": "CNAME"
                }
            ]
        },
        {
            "name": "example.net",
            "arn": "arn:aws:lightsail:global:111122223333:Domain/9c9f0d70-c92e-4753-86c2-6EXAMPLE029d",
            "supportCode": "6EXAMPLE3362//hostedzone/ZEXAMPLE5TPKMV",
            "createdAt": 1556661071.384,
            "location": {
                "availabilityZone": "all",
                "regionName": "global"
            },
            "resourceType": "Domain",
            "tags": [],
            "domainEntries": [
                {
                    "id": "-766320943",
                    "name": "example.net",
                    "target": "192.0.2.2",
                    "isAlias": false,
                    "type": "A"
                },
                {
                    "id": "-453913825",
                    "name": "example.net",
                    "target": "ns-123.awsdns-10.net",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "1553601564",
                    "name": "example.net",
                    "target": "ns-4444.awsdns-47.co.uk",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "1653797661",
                    "name": "example.net",
                    "target": "ns-7890.awsdns-61.org",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "706414698",
                    "name": "example.net",
                    "target": "ns-123.awsdns-44.com",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "337271745",
                    "name": "example.net",
                    "target": "ns-4444.awsdns-47.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400",
                    "isAlias": false,
                    "type": "SOA"
                },
                {
                    "id": "-1785431096",
                    "name": "www.example.net",
                    "target": "192.0.2.2",
                    "isAlias": false,
                    "type": "A"
                }
            ]
        },
        {
            "name": "example.org",
            "arn": "arn:aws:lightsail:global:111122223333:Domain/f0f13ba3-3df0-4fdc-8ebb-1EXAMPLEf26e",
            "supportCode": "6EXAMPLE3362//hostedzone/ZEXAMPLEAFO38",
            "createdAt": 1556661199.106,
            "location": {
                "availabilityZone": "all",
                "regionName": "global"
            },
            "resourceType": "Domain",
            "tags": [],
            "domainEntries": [
                {
                    "id": "2065301345",
                    "name": "example.org",
                    "target": "192.0.2.4",
                    "isAlias": false,
                    "type": "A"
                },
                {
                    "id": "-447198516",
                    "name": "example.org",
                    "target": "ns-123.awsdns-45.com",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "136463022",
                    "name": "example.org",
                    "target": "ns-9999.awsdns-15.co.uk",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "1395941679",
                    "name": "example.org",
                    "target": "ns-555.awsdns-01.net",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "872052569",
                    "name": "example.org",
                    "target": "ns-6543.awsdns-38.org",
                    "isAlias": false,
                    "type": "NS"
                },
                {
                    "id": "1001949377",
                    "name": "example.org",
                    "target": "ns-1234.awsdns-15.co.uk. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400",
                    "isAlias": false,
                    "type": "SOA"
                },
                {
                    "id": "1046191192",
                    "name": "www.example.org",
                    "target": "192.0.2.4",
                    "isAlias": false,
                    "type": "A"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-domains.html)」を参照してください。

### `get-export-snapshot-record`
<a name="lightsail_GetExportSnapshotRecord_cli_2_topic"></a>

次のコード例は、`get-export-snapshot-record` を使用する方法を示しています。

**AWS CLI**  
**Amazon EC2 にエクスポートされたスナップショットのレコードを取得するには**  
次の `get-export-snapshot-record` の例では、Amazon EC2 にエクスポートされた Amazon Lightsail インスタンスまたはディスクスナップショットの詳細を表示します。  

```
aws lightsail get-export-snapshot-records
```
出力:  

```
{
    "exportSnapshotRecords": [
        {
            "name": "ExportSnapshotRecord-d2da10ce-0b3c-4ae1-ab3a-2EXAMPLEa586",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:ExportSnapshotRecord/076c7060-b0cc-4162-98f0-2EXAMPLEe28e",
            "createdAt": 1543534665.678,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "ExportSnapshotRecord",
            "state": "Succeeded",
            "sourceInfo": {
                "resourceType": "InstanceSnapshot",
                "createdAt": 1540339310.706,
                "name": "WordPress-512MB-Oregon-1-1540339219",
                "arn": "arn:aws:lightsail:us-west-2:111122223333:InstanceSnapshot/5446f534-ed60-4c17-b4a5-bEXAMPLEf8b7",
                "fromResourceName": "WordPress-512MB-Oregon-1",
                "fromResourceArn": "arn:aws:lightsail:us-west-2:111122223333:Instance/4b8f1f24-e4d1-4cf3-88ff-cEXAMPLEa397",
                "instanceSnapshotInfo": {
                    "fromBundleId": "nano_2_0",
                    "fromBlueprintId": "wordpress_4_9_8",
                    "fromDiskInfo": [
                        {
                            "path": "/dev/sda1",
                            "sizeInGb": 20,
                            "isSystemDisk": true
                        }
                    ]
                }
            },
            "destinationInfo": {
                "id": "ami-0EXAMPLEc0d65058e",
                "service": "Aws::EC2::Image"
            }
        },
        {
            "name": "ExportSnapshotRecord-1c94e884-40ff-4fe1-9302-0EXAMPLE14c2",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:ExportSnapshotRecord/fb392ce8-6567-4013-9bfd-3EXAMPLE5b4c",
            "createdAt": 1543432110.2,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "ExportSnapshotRecord",
            "state": "Succeeded",
            "sourceInfo": {
                "resourceType": "InstanceSnapshot",
                "createdAt": 1540833603.545,
                "name": "LAMP_PHP_5-512MB-Oregon-1-1540833565",
                "arn": "arn:aws:lightsail:us-west-2:111122223333:InstanceSnapshot/82334399-b5f2-49ec-8382-0EXAMPLEe45f",
                "fromResourceName": "LAMP_PHP_5-512MB-Oregon-1",
                "fromResourceArn": "arn:aws:lightsail:us-west-2:111122223333:Instance/863b9f35-ab1e-4418-bdd2-1EXAMPLEbab2",
                "instanceSnapshotInfo": {
                    "fromBundleId": "nano_2_0",
                    "fromBlueprintId": "lamp_5_6_37_2",
                    "fromDiskInfo": [
                        {
                            "path": "/dev/sda1",
                            "sizeInGb": 20,
                            "isSystemDisk": true
                        }
                    ]
                }
            },
            "destinationInfo": {
                "id": "ami-0EXAMPLE7c5ec84e2",
                "service": "Aws::EC2::Image"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetExportSnapshotRecord](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-export-snapshot-record.html)」を参照してください。

### `get-instance-access-details`
<a name="lightsail_GetInstanceAccessDetails_cli_2_topic"></a>

次のコード例は、`get-instance-access-details` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのホストキー情報を取得するには**  
次の `get-instance-access-details` の例では、インスタンス `WordPress_Multisite-1` のホストキー情報を表示します。  

```
aws lightsail get-instance-access-details \
    --instance-name WordPress_Multisite-1
```
出力:  

```
{
    "accessDetails": {
        "certKey": "ssh-rsa-cert-v01@openssh.com AEXAMPLEaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgNf076Dt3ppmPd0fPxZVMmS491aEAYYH9cHqAJ3fNML8AAAADAQABAAABAQD4APep5Ta2gHLk7m/vEXAMPLE2eBWJyQvn7ol/i0+s966h5sx8qUD79lPB7q5UESd5VZGFtytrykfQJnjiwqe7EV5agzvjblLj26Fb37EKda9HVfCOu8pWbvky7Tyn9w299a6CsG5o8HrkOymDE2c59lYxXGkilKo5I9aZLBAdXn3t3oKtq9zsjYGjyEmarPYoVDT1ft8HaUGu4aCv1peI0+ZEXAMPLEAWaucW9Huh0WYN5yrmL252c4v13JTVmytaEZvLvt5itVoWXQY0ZDyrLUcZSKxyq5n00Mgvj2fiZdt+xMfQM9xVz0rXZmqx8uJidJpRgLCMTviofwQJU/K1EXAMPLEAAAAAAAABAAAALS00MzMzMDU4MzA4ODg1MTY2NjM4Onp6UWlndHk4UElRSG9STitOTG5QSEE9PQAAAAsAAAAHYml0bmFtaQAAAABdpPL7AAEXAMPLEgcAAAAAAAAAggAAABVwZXJtaXQtWDExLWZvcndhcmRpbmcAAAAAAAAAF3Blcm1pdC1hZ2VudC1mb3J3YXJkaW5nAAAAAAAAABZwZXJtaXQtEXAMPLEmb3J3YXJkaW5nAAAAAAAAAApwZXJtaXQtcHR5AAAAAAAAAA5wZXJtaXQtdXNlci1yYwAAAAAAAAAAAAACFwAAAAdzc2gtcnNhAAAAAwEAAQEXAMPLECqCbiK9b450HtRD1ZpiksT6oxc8U7nLNkVFC1j7JqZvP9ee3ux+LiB+ozNbUA0cdNL9Y67x7qPv/R7XhTc21+2A+8+GuVpK/Kz9dqDMKNAEXAMPLE+YYN+tiXm7Y8OgziK+7iDB7xUuQ4vghmn4+qgz9mKwYgWvVe2+0XLuV7cnWPB7iUlHQg+E3LUKrV4ZFw9pj7X2dFdNKfMxwWgI1ISWKimEXAMPLEeHjrf1Rqc/QH6TpWCvPfcx8uvwVqdwTfkE/SfA5BCzbGGI1UmIUadh8nHcb5FamQ1hK7kECy47K/x9FMn/KwmM7pCwJbSLDMO7n9bnbvck6m8ZoB2N2YLMG5dW7BerEXAMPLEobqfdtyYJHHel1EyyEJs1fWNU3D5JIGlgzcPAV+ZlbQyUCZXf0oslSa+HE85fO/FRq9SVSBSHrmbeb0frlPhgMzgSmqLeyhlbr6wwWIDbREXAMPLEJZ49H7RdQxdKyYrZPWvRgcr0qI2EL0tAajnpQQ8UZqeO9/Aqter0xN5PhFL0J49OWTacwCGRAjLhibAx7K1t/1ZXWo6c+ijq8clll327EXAMPLE/e89GC89KcmKCxfGQniDAUgF8UqofIbq3ZOUgiAAYCVXclI4L68NhVXyoWuQXPBRQSEXAMPLEWm74tDL9tFN3c7tSe/Oz0cTR+4sAAAIPAAAAB3NzaC1yc2EAAAIAQnG/L0DqiSnLrWhEox4aHqMgd0m0oLLAYx6OQH9F0TM9EXAMPLE961rzSCMon7ZgsWNnL0OwZQgDG+rtJ4N0B7HOVwns4ynUFbzNQ3qFGGeE3lKwX1L41vV1iSy7sDk8aI0LmrKJi1LE1Qc1l8uboRlwoXOYEXAMPLEaUCeX+10+WEXAMPLEg6Y4U4ZvE2B3xyRdpvysb5TGFNtk5qPslacnVkoLOGsZZXMpLGJnG4OBpQLLtpj9sNMxAgZPCAUjhkqkQWYJxJzvFN7sUMOArUwKPFJE2kaEXAMPLEOUrVGBbCTioRztlPsxY7hoXm73N929eZpNhxP3U+nxO9O4NUZ2pTWbVSUaV1gm6pug9xbwNO1Im21t34JeLlKTqxcJ6zzS8W0c0KKpAm5c4hWkseMbyutS2jav/4hiS+BhrYgptzfwe5qRXEXAMPLEHZQr3YfGzYoBJ/lLK3NHhxOihhsfAYwMei0BFZT1F/7CT3IH4iitEkIgodi06/Mw6UDqMPozyQCK1lEA6LFhYCOZG9drWcoRa74lM4kY9TP028Za8gDMh1WpkXLq9Gixon5OHP8aM/sEXAMPLEr2+fnkw+1BtoO5L6+VKoPlXaGqZ/fBYEXAMPLEAMQHjnLM1JYNvtEEPhp+TNzXHzuixWf/Ht04m0AVpXrzIDXaS1O2tXY=",
        "ipAddress": "192.0.2.0",
        "privateKey": "-----BEGIN RSA PRIVATE KEY-----\nEXAMPLEBAAKCAQEA+AD3qeU2toBy5O5v7wnRLVo/tngVickL5+6Jf4tPrPeuoebM\nfKlA+/ZTwe6uVBEneVWRhbcra8pH0CZ44sKnuxFeWoM7425S49uhW9+xCnWvR1Xw\njrvKVm75Mu08p/cNvfWugrBuaPB65DspgxNnOfZWMVxpIpSqOSPWmSwQHV597d6C\nrEXAMPLEo8hJmqz2KFQ09X7fB2lBruGgr9aXiNPmWmovYKqwFmrnFvR7odFmDecq\n5EXAMPLE9dyU1ZsrWhGby77eYrVaFl0GNGQ8qy1HGUiscquZ9NDIL49n4mXbfsTH\n0EXAMPLE12ZqsfLiYnSaUYCwjE74qH8ECVPytQIDAQABAoIBAHeZV9Z58JHAjifz\nCEXAMPLEEqC3doOVDgXSlkKI92qNo4z2VcUEho878paCuVVXVHcCGgSnGeyIh2tN\nMEXAMPLESohR427BhH3YLA+3Z5SIvnejbTgYPfLC37B8khTaYqkqMvdZiFVZK5qn\nIEXAMPLEM93oF9eSZCjcLKB/jGHsfb0eCDMP8BshHE2beuqzVMoK1DxOnvoP3+Fp\nAEXAMPLESq6pDpCo9YVUX8g1u3Ro9cPl2LXHDy+oVEY5KhbZQJ7VU1I72WOvppWW\nOEXAMPLEkgYlq7p6qYtYcSgTEjz14gDiMfQ7SyHB3alkIoNONQ9ZPaWHyJvymeud\noQTNuz0CgYEA/LFWNTEZrzdzdR1kJmyNRmAermU0B6utyNENChAlHGSHkB+1lVSh\nbEXAMPLEQo9ooUeW5UxO3YwacZLoDT1mwxw1Ptc1+PNycZoLe1fE9UdARrdmGTob\n8l7CPLSXp3xuR8VqSp2fnIc7hfiQs/NrPX9gm/EOrB0we0RKyDSzWScCgYEA+z/r\niob+nJZq0YbnOSuP6oMULP4vnWniWj8MIhUJU53LwSAM8DeJdONKDdkuiOd52aAL\nVgn7nLo88rVWKhJwVc4tu/rNgZLcR3bP4+kL6zand0KQnMLyOzNA2Ys26aa5udH1\nqWl0WTt9WEm/h10ndC1knOMectrvsG17b38y5sMCgYEA54NiRGGz8oCPW6GN/FZA\nKEXAMPLE5tw34GEH3Uxlc9n3CejDaQmczOATwX4nIwRZDEqWyYZcS0btg1jhGiBD\nYEXAMPLEkc8Z71L/agZEAaVCEog9FqfSqwB+XTfoKh8qur74X1yCu9p6gof1q6k9\neEXAMPLEchJcNNOg4ETIfMkCgYBdVORRhE4mqvWpOdzA7v66FdEz2YSkjAXKkmsW\naEXAMPLE8Z/8yBSmuBv1Qv03XA12my462uB92uzzGAuW+1yBc2Kn1sXqYTy0y1z0\ngEXAMPLEBogjw4MqHKL1bPKMHyQU8/q24PaYgzHPzy13wlH6pTYf1XqlHdE2D6Vv\nyEXAMPLEgQC3i/kVVhky/2XRwRVlC7JO2Bg3QGTx38hpmDa5IuofKANjA+Wa3/zy\nbEXAMPLE6ytQgD9GN/YtBq+uhO+2ZkvXPL+CWRi0ZRXpPwYDBBFU9Cw0AuWWGlL8\nwEXAMPLExMlcysRgcWB9RNgf3AuOpFd2i6XT/riNsvvkpmJ+VooU8g==\n-----END RSA PRIVATE KEY-----\n",
        "protocol": "ssh",
        "instanceName": "WordPress_Multisite-1",
        "username": "bitnami",
        "hostKeys": [
            {
                "algorithm": "ssh-rsa",
                "publicKey": "AEXAMPLEaC1yc2EAAAADAQABAAABAQCoeR9ieZTjQ3pXCHczuAYZFjlF7t+uBkXuqeGMRex78pCvmS+DiEXAMPLEuJ1Q8dcKhrQL4HpXbD9dosVCTaJnJwb4MQqsuSVFdHFzy3guP+BKclWqtxJEXAMPLEsBGqZZlrIv6a9bTA0TCplZ8AD+hSRTaSXXqg6FT+Qf16IktH0XlMs7xIEXAMPLEmNtjCpzZiGXDHzytoMvUgwa8uHPp44Og36EUu4VqQxoUHPJKoXvcQizyk3K8ym0hP0TpDZhD8cqwRfd6EHp4Q1br/Ot6y9HwvykEXAMPLEAfbKjbR42+u6+OSlkr4d339q2U1sTDytJhhs8HUel1wTfGRfp",
                "witnessedAt": 1570744377.699,
                "fingerprintSHA1": "SHA1:GEXAMPLEMoYgUg0ucadqU9Bt3Lk",
                "fingerprintSHA256": "SHA256:IEXAMPLEcB5vgxnAUoJawbdZ+MwELhIp6FUxuwq/LIU"
            },
            {
                "algorithm": "ssh-ed25519",
                "publicKey": "AEXAMPLEaC1lZDI1NTE5AAAAIC1gwGPDfGaONxEXAMPLEJX3UNap781QxHQmn8nzlrUv",
                "witnessedAt": 1570744377.697,
                "fingerprintSHA1": "SHA1:VEXAMPLE5ReqSmTgv03sSUw9toU",
                "fingerprintSHA256": "SHA256:0EXAMPLEdE6tI95k3TJpG+qhJbAoknB0yz9nAEaDt3A"
            },
            {
                "algorithm": "ecdsa-sha2-nistp256",
                "publicKey": "AEXAMPLEZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABEXAMPLE9B4mZy8YSsZW7cixCDq5yHSAAxjJkDo54C+EnKlDCsYtUkxxEXAMPLE6VOWL2z63RTKa2AUPgd8irjxWI=",
                "witnessedAt": 1570744377.707,
                "fingerprintSHA1": "SHA1:UEXAMPLEOYCfXsCf2G6tDg+7YG0",
                "fingerprintSHA256": "SHA256:wEXAMPLEQ9a/iEXAMPLEhRufm6U9vFU4cpkMPHnBsNA"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceAccessDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instance-access-details.html)」を参照してください。

### `get-instance-metric-data`
<a name="lightsail_GetInstanceMetricData_cli_2_topic"></a>

次のコード例は、`get-instance-metric-data` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのメトリクスデータを取得するには**  
次の `get-instance-metric-data` の例では、インスタンス `MEAN-1` の `1571342400` と `1571428800` の間の `7200` 秒 (2 時間) ごとの `CPUUtilization` の平均パーセントを返します。  
Unix タイムコンバーターを使用して、開始時刻と終了時刻を特定することをお勧めします。  

```
aws lightsail get-instance-metric-data \
    --instance-name MEAN-1 \
    --metric-name CPUUtilization \
    --period 7200 \
    --start-time 1571342400 \
    --end-time 1571428800 \
    --unit Percent \
    --statistics Average
```
出力:  

```
{
    "metricName": "CPUUtilization",
    "metricData": [
        {
            "average": 0.26113718770120725,
            "timestamp": 1571342400.0,
            "unit": "Percent"
        },
        {
            "average": 0.26861268928111953,
            "timestamp": 1571392800.0,
            "unit": "Percent"
        },
        {
            "average": 0.28187475104748777,
            "timestamp": 1571378400.0,
            "unit": "Percent"
        },
        {
            "average": 0.2651936960458352,
            "timestamp": 1571421600.0,
            "unit": "Percent"
        },
        {
            "average": 0.2561856213712188,
            "timestamp": 1571371200.0,
            "unit": "Percent"
        },
        {
            "average": 0.3021383254607764,
            "timestamp": 1571356800.0,
            "unit": "Percent"
        },
        {
            "average": 0.2618381649223539,
            "timestamp": 1571407200.0,
            "unit": "Percent"
        },
        {
            "average": 0.26331929394825787,
            "timestamp": 1571400000.0,
            "unit": "Percent"
        },
        {
            "average": 0.2576348407007818,
            "timestamp": 1571385600.0,
            "unit": "Percent"
        },
        {
            "average": 0.2513008454658378,
            "timestamp": 1571364000.0,
            "unit": "Percent"
        },
        {
            "average": 0.26329974562758346,
            "timestamp": 1571414400.0,
            "unit": "Percent"
        },
        {
            "average": 0.2667092536656445,
            "timestamp": 1571349600.0,
            "unit": "Percent"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceMetricData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instance-metric-data.html)」を参照してください。

### `get-instance-port-states`
<a name="lightsail_GetInstancePortStates_cli_2_topic"></a>

次のコード例は、`get-instance-port-states` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのファイアウォール情報を取得するには**  
次の `get-instance-port-states` の例では、インスタンス `MEAN-1` 用に設定されたファイアウォールポートを返します。  

```
aws lightsail get-instance-port-states \
    --instance-name MEAN-1
```
出力:  

```
{
    "portStates": [
        {
            "fromPort": 80,
            "toPort": 80,
            "protocol": "tcp",
            "state": "open"
        },
        {
            "fromPort": 22,
            "toPort": 22,
            "protocol": "tcp",
            "state": "open"
        },
        {
            "fromPort": 443,
            "toPort": 443,
            "protocol": "tcp",
            "state": "open"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstancePortStates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instance-port-states.html)」を参照してください。

### `get-instance-snapshot`
<a name="lightsail_GetInstanceSnapshot_cli_2_topic"></a>

次のコード例は、`get-instance-snapshot` を使用する方法を示しています。

**AWS CLI**  
**指定されたインスタンススナップショットに関する情報を取得するには**  
次の `get-instance-snapshot` の例では、指定されたインスタンススナップショットの詳細を表示します。  

```
aws lightsail get-instance-snapshot \
    --instance-snapshot-name MEAN-1-1571419854
```
出力:  

```
{
    "instanceSnapshot": {
        "name": "MEAN-1-1571419854",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:InstanceSnapshot/ac54700c-48a8-40fd-b065-2EXAMPLEac8f",
        "supportCode": "6EXAMPLE3362/ami-0EXAMPLE67a73020d",
        "createdAt": 1571419891.927,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "resourceType": "InstanceSnapshot",
        "tags": [],
        "state": "available",
        "fromAttachedDisks": [],
        "fromInstanceName": "MEAN-1",
        "fromInstanceArn": "arn:aws:lightsail:us-west-2:111122223333:Instance/bd470fc5-a68b-44c5-8dbc-8EXAMPLEbada",
        "fromBlueprintId": "mean",
        "fromBundleId": "medium_3_0",
        "isFromAutoSnapshot": false,
        "sizeInGb": 80
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instance-snapshot.html)」を参照してください。

### `get-instance-snapshots`
<a name="lightsail_GetInstanceSnapshots_cli_2_topic"></a>

次のコード例は、`get-instance-snapshots` を使用する方法を示しています。

**AWS CLI**  
**すべてのインスタンススナップショットに関する情報を取得するには**  
次の の`get-instance-snapshots`例では、設定された AWS リージョン内のすべてのインスタンススナップショットの詳細を表示します。  

```
aws lightsail get-instance-snapshots
```
出力:  

```
{
    "instanceSnapshots": [
        {
            "name": "MEAN-1-1571421498",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:InstanceSnapshot/a20e6ebe-b0ee-4ae4-a750-3EXAMPLEcb0c",
            "supportCode": "6EXAMPLE3362/ami-0EXAMPLEe33cabfa1",
            "createdAt": 1571421527.755,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "InstanceSnapshot",
            "tags": [
                {
                    "key": "no_delete"
                }
            ],
            "state": "available",
            "fromAttachedDisks": [],
            "fromInstanceName": "MEAN-1",
            "fromInstanceArn": "arn:aws:lightsail:us-west-2:111122223333:Instance/1761aa0a-6038-4f25-8b94-2EXAMPLE19fd",
            "fromBlueprintId": "wordpress",
            "fromBundleId": "micro_3_0",
            "isFromAutoSnapshot": false,
            "sizeInGb": 40
        },
        {
            "name": "MEAN-1-1571419854",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:InstanceSnapshot/ac54700c-48a8-40fd-b065-2EXAMPLEac8f",
            "supportCode": "6EXAMPLE3362/ami-0EXAMPLE67a73020d",
            "createdAt": 1571419891.927,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "InstanceSnapshot",
            "tags": [],
            "state": "available",
            "fromAttachedDisks": [],
            "fromInstanceName": "MEAN-1",
            "fromInstanceArn": "arn:aws:lightsail:us-west-2:111122223333:Instance/bd470fc5-a68b-44c5-8dbc-8EXAMPLEbada",
            "fromBlueprintId": "mean",
            "fromBundleId": "medium_3_0",
            "isFromAutoSnapshot": false,
            "sizeInGb": 80
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instance-snapshots.html)」を参照してください。

### `get-instance-state`
<a name="lightsail_GetInstanceState_cli_2_topic"></a>

次のコード例は、`get-instance-state` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの状態に関する情報を取得するには**  
次の `get-instance-state` の例では、指定されたインスタンスの状態を返します。  

```
aws lightsail get-instance-state \
    --instance-name MEAN-1
```
出力:  

```
{
    "state": {
        "code": 16,
        "name": "running"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstanceState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instance-state.html)」を参照してください。

### `get-instance`
<a name="lightsail_GetInstance_cli_2_topic"></a>

次のコード例は、`get-instance` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの情報を取得するには**  
次の `get-instance` の例では、指定されたインスタンス `MEAN-1` の詳細を表示します。  

```
aws lightsail get-instance \
    --instance-name MEAN-1
```
出力:  

```
{
    "instance": {
        "name": "MEAN-1",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:Instance/bd470fc5-a68b-44c5-8dbc-EXAMPLE4bada",
        "supportCode": "6EXAMPLE3362/i-05EXAMPLE407c97d3",
        "createdAt": 1570635023.124,
        "location": {
            "availabilityZone": "us-west-2a",
            "regionName": "us-west-2"
        },
        "resourceType": "Instance",
        "tags": [],
        "blueprintId": "mean",
        "blueprintName": "MEAN",
        "bundleId": "medium_3_0",
        "isStaticIp": false,
        "privateIpAddress": "192.0.2.0",
        "publicIpAddress": "192.0.2.0",
        "hardware": {
            "cpuCount": 2,
            "disks": [
                {
                    "createdAt": 1570635023.124,
                    "sizeInGb": 80,
                    "isSystemDisk": true,
                    "iops": 240,
                    "path": "/dev/xvda",
                    "attachedTo": "MEAN-1",
                    "attachmentState": "attached"
                }
            ],
            "ramSizeInGb": 4.0
        },
        "networking": {
            "monthlyTransfer": {
                "gbPerMonthAllocated": 4096
            },
            "ports": [
                {
                    "fromPort": 80,
                    "toPort": 80,
                    "protocol": "tcp",
                    "accessFrom": "Anywhere (0.0.0.0/0)",
                    "accessType": "public",
                    "commonName": "",
                    "accessDirection": "inbound"
                },
                {
                    "fromPort": 22,
                    "toPort": 22,
                    "protocol": "tcp",
                    "accessFrom": "Anywhere (0.0.0.0/0)",
                    "accessType": "public",
                    "commonName": "",
                    "accessDirection": "inbound"
                },
                {
                    "fromPort": 443,
                    "toPort": 443,
                    "protocol": "tcp",
                    "accessFrom": "Anywhere (0.0.0.0/0)",
                    "accessType": "public",
                    "commonName": "",
                    "accessDirection": "inbound"
                }
            ]
        },
        "state": {
            "code": 16,
            "name": "running"
        },
        "username": "bitnami",
        "sshKeyName": "MyKey"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instance.html)」を参照してください。

### `get-instances`
<a name="lightsail_GetInstances_cli_2_topic"></a>

次のコード例は、`get-instances` を使用する方法を示しています。

**AWS CLI**  
**すべてのインスタンスに関する情報を取得するには**  
次の の`get-instances`例では、設定された AWS リージョン内のすべてのインスタンスに関する詳細を表示します。  

```
aws lightsail get-instances
```
出力:  

```
{
    "instances": [
        {
            "name": "Windows_Server_2022-1",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:Instance/0f44fbb9-8f55-4e47-a25e-EXAMPLE04763",
            "supportCode": "62EXAMPLE362/i-0bEXAMPLE71a686b9",
            "createdAt": 1571332358.665,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "resourceType": "Instance",
            "tags": [],
            "blueprintId": "windows_server_2022",
            "blueprintName": "Windows Server 2022",
            "bundleId": "large_win_3_0",
            "isStaticIp": false,
            "privateIpAddress": "192.0.2.0",
            "publicIpAddress": "192.0.2.0",
            "hardware": {
                "cpuCount": 1,
                "disks": [
                    {
                        "createdAt": 1571332358.665,
                        "sizeInGb": 160,
                        "isSystemDisk": true,
                        "iops": 180,
                        "path": "/dev/sda1",
                        "attachedTo": "Windows_Server_2022-1",
                        "attachmentState": "attached"
                    },
                    {
                        "name": "my-disk-for-windows-server",
                        "arn": "arn:aws:lightsail:us-west-2:111122223333:Disk/4123a81c-484c-49ea-afea-5EXAMPLEda87",
                        "supportCode": "6EXAMPLE3362/vol-0EXAMPLEb2b99ca3d",
                        "createdAt": 1571355063.494,
                        "location": {
                            "availabilityZone": "us-west-2a",
                            "regionName": "us-west-2"
                        },
                        "resourceType": "Disk",
                        "tags": [],
                        "sizeInGb": 128,
                        "isSystemDisk": false,
                        "iops": 384,
                        "path": "/dev/xvdf",
                        "state": "in-use",
                        "attachedTo": "Windows_Server_2022-1",
                        "isAttached": true,
                        "attachmentState": "attached"
                    }
                ],
                "ramSizeInGb": 8.0
            },
            "networking": {
                "monthlyTransfer": {
                    "gbPerMonthAllocated": 3072
                },
                "ports": [
                    {
                        "fromPort": 80,
                        "toPort": 80,
                        "protocol": "tcp",
                        "accessFrom": "Anywhere (0.0.0.0/0)",
                        "accessType": "public",
                        "commonName": "",
                        "accessDirection": "inbound"
                    },
                    {
                        "fromPort": 22,
                        "toPort": 22,
                        "protocol": "tcp",
                        "accessFrom": "Anywhere (0.0.0.0/0)",
                        "accessType": "public",
                        "commonName": "",
                        "accessDirection": "inbound"
                    },
                    {
                        "fromPort": 3389,
                        "toPort": 3389,
                        "protocol": "tcp",
                        "accessFrom": "Anywhere (0.0.0.0/0)",
                        "accessType": "public",
                        "commonName": "",
                        "accessDirection": "inbound"
                    }
                ]
            },
            "state": {
                "code": 16,
                "name": "running"
            },
            "username": "Administrator",
            "sshKeyName": "LightsailDefaultKeyPair"
        },
        {
            "name": "MEAN-1",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:Instance/bd470fc5-a68b-44c5-8dbc-8EXAMPLEbada",
            "supportCode": "6EXAMPLE3362/i-0EXAMPLEa407c97d3",
            "createdAt": 1570635023.124,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "resourceType": "Instance",
            "tags": [],
            "blueprintId": "mean",
            "blueprintName": "MEAN",
            "bundleId": "medium_3_0",
            "isStaticIp": false,
            "privateIpAddress": "192.0.2.0",
            "publicIpAddress": "192.0.2.0",
            "hardware": {
                "cpuCount": 2,
                "disks": [
                    {
                        "name": "Disk-1",
                        "arn": "arn:aws:lightsail:us-west-2:111122223333:Disk/c21cfb0a-07f2-44ae-9a23-bEXAMPLE8096",
                        "supportCode": "6EXAMPLE3362/vol-0EXAMPLEf2f88b32f",
                        "createdAt": 1566585439.587,
                        "location": {
                            "availabilityZone": "us-west-2a",
                            "regionName": "us-west-2"
                        },
                        "resourceType": "Disk",
                        "tags": [
                            {
                                "key": "test"
                            }
                        ],
                        "sizeInGb": 8,
                        "isSystemDisk": false,
                        "iops": 240,
                        "path": "/dev/xvdf",
                        "state": "in-use",
                        "attachedTo": "MEAN-1",
                        "isAttached": true,
                        "attachmentState": "attached"
                    },
                    {
                        "createdAt": 1570635023.124,
                        "sizeInGb": 80,
                        "isSystemDisk": true,
                        "iops": 240,
                        "path": "/dev/sda1",
                        "attachedTo": "MEAN-1",
                        "attachmentState": "attached"
                    }
                ],
                "ramSizeInGb": 4.0
            },
            "networking": {
                "monthlyTransfer": {
                    "gbPerMonthAllocated": 4096
                },
                "ports": [
                    {
                        "fromPort": 80,
                        "toPort": 80,
                        "protocol": "tcp",
                        "accessFrom": "Anywhere (0.0.0.0/0)",
                        "accessType": "public",
                        "commonName": "",
                        "accessDirection": "inbound"
                    },
                    {
                        "fromPort": 22,
                        "toPort": 22,
                        "protocol": "tcp",
                        "accessFrom": "Anywhere (0.0.0.0/0)",
                        "accessType": "public",
                        "commonName": "",
                        "accessDirection": "inbound"
                    },
                    {
                        "fromPort": 443,
                        "toPort": 443,
                        "protocol": "tcp",
                        "accessFrom": "Anywhere (0.0.0.0/0)",
                        "accessType": "public",
                        "commonName": "",
                        "accessDirection": "inbound"
                    }
                ]
            },
            "state": {
                "code": 16,
                "name": "running"
            },
            "username": "bitnami",
            "sshKeyName": "MyTestKey"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-instances.html)」を参照してください。

### `get-key-pair`
<a name="lightsail_GetKeyPair_cli_2_topic"></a>

次のコード例は、`get-key-pair` を使用する方法を示しています。

**AWS CLI**  
**キーペアに関する情報を取得するには**  
次の `get-key-pair` の例では、指定されたキーペアの詳細を表示します。  

```
aws lightsail get-key-pair \
    --key-pair-name MyKey1
```
出力:  

```
{
    "keyPair": {
        "name": "MyKey1",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:KeyPair/19a4efdf-3054-43d6-91fd-eEXAMPLE21bf",
        "supportCode": "6EXAMPLE3362/MyKey1",
        "createdAt": 1571255026.975,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "resourceType": "KeyPair",
        "tags": [],
        "fingerprint": "00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:gg:hh:ii:jj"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetKeyPair](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-key-pair.html)」を参照してください。

### `get-key-pairs`
<a name="lightsail_GetKeyPairs_cli_2_topic"></a>

次のコード例は、`get-key-pairs` を使用する方法を示しています。

**AWS CLI**  
**すべてのキーペアに関する情報を取得するには**  
次の の`get-key-pairs`例では、設定済み AWS リージョンのすべてのキーペアに関する詳細を表示します。  

```
aws lightsail get-key-pairs
```
出力:  

```
{
    "keyPairs": [
        {
            "name": "MyKey1",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:KeyPair/19a4efdf-3054-43d6-91fd-eEXAMPLE21bf",
            "supportCode": "6EXAMPLE3362/MyKey1",
            "createdAt": 1571255026.975,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "KeyPair",
            "tags": [],
            "fingerprint": "00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:gg:hh:ii:jj"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetKeyPairs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-key-pairs.html)」を参照してください。

### `get-load-balancer-tls-certificates`
<a name="lightsail_GetLoadBalancerTlsCertificates_cli_2_topic"></a>

次のコード例は、`get-load-balancer-tls-certificates` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーの TLS 証明書に関する情報を取得するには**  
次の `get-load-balancer-tls-certificates` の例では、指定されたロードバランサーの TLS 証明書の詳細を表示します。  

```
aws lightsail get-load-balancer-tls-certificates \
    --load-balancer-name LoadBalancer-1
```
出力:  

```
{
    "tlsCertificates": [
        {
            "name": "example-com",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:LoadBalancerTlsCertificate/d7bf4643-6a02-4cd4-b3c4-fEXAMPLE9b4d",
            "supportCode": "6EXAMPLE3362/arn:aws:acm:us-west-2:333322221111:certificate/9af8e32c-a54e-4a67-8c63-cEXAMPLEb314",
            "createdAt": 1571678025.3,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "LoadBalancerTlsCertificate",
            "loadBalancerName": "LoadBalancer-1",
            "isAttached": false,
            "status": "ISSUED",
            "domainName": "example.com",
            "domainValidationRecords": [
                {
                    "name": "_dEXAMPLE4ede046a0319eb44a4eb3cbc.example.com.",
                    "type": "CNAME",
                    "value": "_bEXAMPLE0899fb7b6bf79d9741d1a383.hkvuiqjoua.acm-validations.aws.",
                    "validationStatus": "SUCCESS",
                    "domainName": "example.com"
                }
            ],
            "issuedAt": 1571678070.0,
            "issuer": "Amazon",
            "keyAlgorithm": "RSA-2048",
            "notAfter": 1605960000.0,
            "notBefore": 1571616000.0,
            "serial": "00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff",
            "signatureAlgorithm": "SHA256WITHRSA",
            "subject": "CN=example.com",
            "subjectAlternativeNames": [
                "example.com"
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoadBalancerTlsCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-load-balancer-tls-certificates.html)」を参照してください。

### `get-load-balancer`
<a name="lightsail_GetLoadBalancer_cli_2_topic"></a>

次のコード例は、`get-load-balancer` を使用する方法を示しています。

**AWS CLI**  
**ロードバランサーに関する情報を取得するには**  
次の `get-load-balancer` の例では、指定されたロードバランサーの詳細を表示します。  

```
aws lightsail get-load-balancer \
    --load-balancer-name LoadBalancer-1
```
出力:  

```
{
    "loadBalancer": {
        "name": "LoadBalancer-1",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:LoadBalancer/40486b2b-1ad0-4152-83e4-cEXAMPLE6f4b",
        "supportCode": "6EXAMPLE3362/arn:aws:elasticloadbalancing:us-west-2:333322221111:loadbalancer/app/bEXAMPLE128cb59d86f946a9395dd304/1EXAMPLE8dd9d77e",
        "createdAt": 1571677906.723,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "resourceType": "LoadBalancer",
        "tags": [],
        "dnsName": "bEXAMPLE128cb59d86f946a9395dd304-1486911371.us-west-2.elb.amazonaws.com",
        "state": "active",
        "protocol": "HTTP",
        "publicPorts": [
            80
        ],
        "healthCheckPath": "/",
        "instancePort": 80,
        "instanceHealthSummary": [
            {
                "instanceName": "MEAN-3",
                "instanceHealth": "healthy"
            },
            {
                "instanceName": "MEAN-1",
                "instanceHealth": "healthy"
            },
            {
                "instanceName": "MEAN-2",
                "instanceHealth": "healthy"
            }
        ],
        "tlsCertificateSummaries": [
            {
                "name": "example-com",
                "isAttached": false
            }
        ],
        "configurationOptions": {
            "SessionStickinessEnabled": "false",
            "SessionStickiness_LB_CookieDurationSeconds": "86400"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoadBalancer](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-load-balancer.html)」を参照してください。

### `get-load-balancers`
<a name="lightsail_GetLoadBalancers_cli_2_topic"></a>

次のコード例は、`get-load-balancers` を使用する方法を示しています。

**AWS CLI**  
**すべてのロードバランサーに関する情報を取得するには**  
次の の`get-load-balancers`例では、設定された AWS リージョン内のすべてのロードバランサーの詳細を表示します。  

```
aws lightsail get-load-balancers
```
出力:  

```
{
    "loadBalancers": [
        {
            "name": "LoadBalancer-1",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:LoadBalancer/40486b2b-1ad0-4152-83e4-cEXAMPLE6f4b",
            "supportCode": "6EXAMPLE3362/arn:aws:elasticloadbalancing:us-west-2:333322221111:loadbalancer/app/bEXAMPLE128cb59d86f946a9395dd304/1EXAMPLE8dd9d77e",
            "createdAt": 1571677906.723,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "LoadBalancer",
            "tags": [],
            "dnsName": "bEXAMPLE128cb59d86f946a9395dd304-1486911371.us-west-2.elb.amazonaws.com",
            "state": "active",
            "protocol": "HTTP",
            "publicPorts": [
                80
            ],
            "healthCheckPath": "/",
            "instancePort": 80,
            "instanceHealthSummary": [
                {
                    "instanceName": "MEAN-3",
                    "instanceHealth": "healthy"
                },
                {
                    "instanceName": "MEAN-1",
                    "instanceHealth": "healthy"
                },
                {
                    "instanceName": "MEAN-2",
                    "instanceHealth": "healthy"
                }
            ],
            "tlsCertificateSummaries": [
                {
                    "name": "example-com",
                    "isAttached": false
                }
            ],
            "configurationOptions": {
                "SessionStickinessEnabled": "false",
                "SessionStickiness_LB_CookieDurationSeconds": "86400"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoadBalancers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-load-balancers.html)」を参照してください。

### `get-operation`
<a name="lightsail_GetOperation_cli_2_topic"></a>

次のコード例は、`get-operation` を使用する方法を示しています。

**AWS CLI**  
**単一のオペレーションに関する情報を取得するには**  
次の `get-operation` の例では、指定されたオペレーションの詳細を表示します。  

```
aws lightsail get-operation \
    --operation-id e5700e8a-daf2-4b49-bc01-3EXAMPLE910a
```
出力:  

```
{
    "operation": {
        "id": "e5700e8a-daf2-4b49-bc01-3EXAMPLE910a",
        "resourceName": "Instance-1",
        "resourceType": "Instance",
        "createdAt": 1571679872.404,
        "location": {
            "availabilityZone": "us-west-2a",
            "regionName": "us-west-2"
        },
        "isTerminal": true,
        "operationType": "CreateInstance",
        "status": "Succeeded",
        "statusChangedAt": 1571679890.304
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOperation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-operation.html)」を参照してください。

### `get-operations-for-resource`
<a name="lightsail_GetOperationsForResource_cli_2_topic"></a>

次のコード例は、`get-operations-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのすべてのオペレーションを取得するには**  
次の `get-operations-for-resource` の例では、指定されたリソースのすべてのオペレーションの詳細を表示します。  

```
aws lightsail get-operations-for-resource \
    --resource-name LoadBalancer-1
```
出力:  

```
{
    "operations": [
        {
            "id": "e2973046-43f8-4252-a4b4-9EXAMPLE69ce",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571678786.071,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "MEAN-1",
            "operationType": "DetachInstancesFromLoadBalancer",
            "status": "Succeeded",
            "statusChangedAt": 1571679087.57
        },
        {
            "id": "2d742a18-0e7f-48c8-9705-3EXAMPLEf98a",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571678782.784,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "MEAN-1",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Succeeded",
            "statusChangedAt": 1571678798.465
        },
        {
            "id": "6c700fcc-4246-40ab-952b-1EXAMPLEdac2",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571678775.297,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "MEAN-3",
            "operationType": "AttachInstancesToLoadBalancer",
            "status": "Succeeded",
            "statusChangedAt": 1571678842.806
        },
        ...
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOperationsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-operations-for-resource.html)」を参照してください。

### `get-operations`
<a name="lightsail_GetOperations_cli_2_topic"></a>

次のコード例は、`get-operations` を使用する方法を示しています。

**AWS CLI**  
**すべてのオペレーションに関する情報を取得するには**  
次の の`get-operations`例では、設定された AWS リージョンのすべてのオペレーションに関する詳細を表示します。  

```
aws lightsail get-operations
```
出力:  

```
{
    "operations": [
        {
            "id": "e5700e8a-daf2-4b49-bc01-3EXAMPLE910a",
            "resourceName": "Instance-1",
            "resourceType": "Instance",
            "createdAt": 1571679872.404,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "CreateInstance",
            "status": "Succeeded",
            "statusChangedAt": 1571679890.304
        },
        {
            "id": "701a3339-930e-4914-a9f9-7EXAMPLE68d7",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1571678786.072,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "LoadBalancer-1",
            "operationType": "DetachInstancesFromLoadBalancer",
            "status": "Succeeded",
            "statusChangedAt": 1571679086.399
        },
        {
            "id": "e2973046-43f8-4252-a4b4-9EXAMPLE69ce",
            "resourceName": "LoadBalancer-1",
            "resourceType": "LoadBalancer",
            "createdAt": 1571678786.071,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "WordPress-1",
            "operationType": "DetachInstancesFromLoadBalancer",
            "status": "Succeeded",
            "statusChangedAt": 1571679087.57
        },
        ...
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOperations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-operations.html)」を参照してください。

### `get-regions`
<a name="lightsail_GetRegions_cli_2_topic"></a>

次の例は、`get-regions` を使用する方法を説明しています。

**AWS CLI**  
**のすべての AWS リージョンを取得するには Amazon Lightsail**  
次の の`get-regions`例では、 のすべての AWS リージョンの詳細を表示しますAmazon Lightsail。  

```
aws lightsail get-regions
```
出力:  

```
{
    "regions": [
        {
            "continentCode": "NA",
            "description": "This region is recommended to serve users in the eastern United States",
            "displayName": "Virginia",
            "name": "us-east-1",
            "availabilityZones": [],
            "relationalDatabaseAvailabilityZones": []
        },
        {
            "continentCode": "NA",
            "description": "This region is recommended to serve users in the eastern United States",
            "displayName": "Ohio",
            "name": "us-east-2",
            "availabilityZones": [],
            "relationalDatabaseAvailabilityZones": []
        },
        {
            "continentCode": "NA",
            "description": "This region is recommended to serve users in the northwestern United States, Alaska, and western Canada",
            "displayName": "Oregon",
            "name": "us-west-2",
            "availabilityZones": [],
            "relationalDatabaseAvailabilityZones": []
        },
        ...
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRegions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-regions.html)」を参照してください。

### `get-relational-database-blueprints`
<a name="lightsail_GetRelationalDatabaseBlueprints_cli_2_topic"></a>

次のコード例は、`get-relational-database-blueprints` を使用する方法を示しています。

**AWS CLI**  
**新しいリレーショナルデータベースのブループリントを取得するには**  
次の `get-relational-database-blueprints` の例では、Amazon Lightsail で新しいリレーショナルデータベースを作成するために使用できる、すべての使用可能なリレーショナルデータベースブループリントの詳細を表示します。  

```
aws lightsail get-relational-database-blueprints
```
出力:  

```
{
    "blueprints": [
        {
            "blueprintId": "mysql_5_6",
            "engine": "mysql",
            "engineVersion": "5.6.44",
            "engineDescription": "MySQL Community Edition",
            "engineVersionDescription": "MySQL 5.6.44",
            "isEngineDefault": false
        },
        {
            "blueprintId": "mysql_5_7",
            "engine": "mysql",
            "engineVersion": "5.7.26",
            "engineDescription": "MySQL Community Edition",
            "engineVersionDescription": "MySQL 5.7.26",
            "isEngineDefault": true
        },
        {
            "blueprintId": "mysql_8_0",
            "engine": "mysql",
            "engineVersion": "8.0.16",
            "engineDescription": "MySQL Community Edition",
            "engineVersionDescription": "MySQL 8.0.16",
            "isEngineDefault": false
        },
        {
            "blueprintId": "postgres_9_6",
            "engine": "postgres",
            "engineVersion": "9.6.15",
            "engineDescription": "PostgreSQL",
            "engineVersionDescription": "PostgreSQL 9.6.15-R1",
            "isEngineDefault": false
        },
        {
            "blueprintId": "postgres_10",
            "engine": "postgres",
            "engineVersion": "10.10",
            "engineDescription": "PostgreSQL",
            "engineVersionDescription": "PostgreSQL 10.10-R1",
            "isEngineDefault": false
        },
        {
            "blueprintId": "postgres_11",
            "engine": "postgres",
            "engineVersion": "11.5",
            "engineDescription": "PostgreSQL",
            "engineVersionDescription": "PostgreSQL 11.5-R1",
            "isEngineDefault": true
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseBlueprints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-blueprints.html)」を参照してください。

### `get-relational-database-bundles`
<a name="lightsail_GetRelationalDatabaseBundles_cli_2_topic"></a>

次のコード例は、`get-relational-database-bundles` を使用する方法を示しています。

**AWS CLI**  
**新しいリレーショナルデータベースのバンドルを取得するには**  
次の `get-relational-database-bundles` の例では、Amazon Lightsail で新しいリレーショナルデータベースを作成するために使用できる、すべての使用可能なリレーショナルデータベースバンドルの詳細を表示します。コマンドで `--include-inactive` フラグが指定されていないため、レスポンスには非アクティブなバンドルが含まれていないことに注意してください。非アクティブなバンドルを使用して新しいリレーショナルデータベースを作成することはできません。  

```
aws lightsail get-relational-database-bundles
```
出力:  

```
{
    "bundles": [
        {
            "bundleId": "micro_2_0",
            "name": "Micro",
            "price": 15.0,
            "ramSizeInGb": 1.0,
            "diskSizeInGb": 40,
            "transferPerMonthInGb": 100,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        },
        {
            "bundleId": "micro_ha_2_0",
            "name": "Micro with High Availability",
            "price": 30.0,
            "ramSizeInGb": 1.0,
            "diskSizeInGb": 40,
            "transferPerMonthInGb": 100,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        },
        {
            "bundleId": "small_2_0",
            "name": "Small",
            "price": 30.0,
            "ramSizeInGb": 2.0,
            "diskSizeInGb": 80,
            "transferPerMonthInGb": 100,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        },
        {
            "bundleId": "small_ha_2_0",
            "name": "Small with High Availability",
            "price": 60.0,
            "ramSizeInGb": 2.0,
            "diskSizeInGb": 80,
            "transferPerMonthInGb": 100,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        },
        {
            "bundleId": "medium_2_0",
            "name": "Medium",
            "price": 60.0,
            "ramSizeInGb": 4.0,
            "diskSizeInGb": 120,
            "transferPerMonthInGb": 100,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        },
        {
            "bundleId": "medium_ha_2_0",
            "name": "Medium with High Availability",
            "price": 120.0,
            "ramSizeInGb": 4.0,
            "diskSizeInGb": 120,
            "transferPerMonthInGb": 100,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        },
        {
            "bundleId": "large_2_0",
            "name": "Large",
            "price": 115.0,
            "ramSizeInGb": 8.0,
            "diskSizeInGb": 240,
            "transferPerMonthInGb": 200,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        },
        {
            "bundleId": "large_ha_2_0",
            "name": "Large with High Availability",
            "price": 230.0,
            "ramSizeInGb": 8.0,
            "diskSizeInGb": 240,
            "transferPerMonthInGb": 200,
            "cpuCount": 2,
            "isEncrypted": true,
            "isActive": true
        }
    ]
}
```
詳細については、「*Amazon Lightsail Developer Guide*」の「[Creating a database in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-creating-a-database)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseBundles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-bundles.html)」を参照してください。

### `get-relational-database-events`
<a name="lightsail_GetRelationalDatabaseEvents_cli_2_topic"></a>

次のコード例は、`get-relational-database-events` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースのイベントを取得するには**  
次の `get-relational-database-events` の例では、指定されたリレーショナルデータベースの過去 17 時間 (1020 分) のイベントの詳細を表示します。  

```
aws lightsail get-relational-database-events \
    --relational-database-name Database-1 \
    --duration-in-minutes 1020
```
出力:  

```
{
    "relationalDatabaseEvents": [
        {
            "resource": "Database-1",
            "createdAt": 1571654146.553,
            "message": "Backing up Relational Database",
            "eventCategories": [
                "backup"
            ]
        },
        {
            "resource": "Database-1",
            "createdAt": 1571654249.98,
            "message": "Finished Relational Database backup",
            "eventCategories": [
                "backup"
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-events.html)」を参照してください。

### `get-relational-database-log-events`
<a name="lightsail_GetRelationalDatabaseLogEvents_cli_2_topic"></a>

次のコード例は、`get-relational-database-log-events` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースのログイベントを取得するには**  
次の `get-relational-database-log-events` の例では、リレーショナルデータベース `Database1` の `1570733176` と `1571597176` の間の指定されたログの詳細を表示します。返される情報は、`head` から開始するように設定されています。  
Unix タイムコンバーターを使用して、開始時刻と終了時刻を特定することをお勧めします。  

```
aws lightsail get-relational-database-log-events \
    --relational-database-name Database1 \
    --log-stream-name error \
    --start-from-head \
    --start-time 1570733176 \
    --end-time 1571597176
```
出力:  

```
{
    "resourceLogEvents": [
        {
            "createdAt": 1570820267.0,
            "message": "2019-10-11 18:57:47 20969 [Warning] IP address '192.0.2.0' could not be resolved: Name or service not known"
        },
        {
            "createdAt": 1570860974.0,
            "message": "2019-10-12 06:16:14 20969 [Warning] IP address '8192.0.2.0' could not be resolved: Temporary failure in name resolution"
        },
        {
            "createdAt": 1570860977.0,
            "message": "2019-10-12 06:16:17 20969 [Warning] IP address '192.0.2.0' could not be resolved: Temporary failure in name resolution"
        },
        {
            "createdAt": 1570860979.0,
            "message": "2019-10-12 06:16:19 20969 [Warning] IP address '192.0.2.0' could not be resolved: Temporary failure in name resolution"
        },
        {
            "createdAt": 1570860981.0,
            "message": "2019-10-12 06:16:21 20969 [Warning] IP address '192.0.2.0' could not be resolved: Temporary failure in name resolution"
        },
        {
            "createdAt": 1570860982.0,
            "message": "2019-10-12 06:16:22 20969 [Warning] IP address '192.0.2.0' could not be resolved: Temporary failure in name resolution"
        },
        {
            "createdAt": 1570860984.0,
            "message": "2019-10-12 06:16:24 20969 [Warning] IP address '192.0.2.0' could not be resolved: Temporary failure in name resolution"
        },
        {
            "createdAt": 1570860986.0,
            "message": "2019-10-12 06:16:26 20969 [Warning] IP address '192.0.2.0' could not be resolved: Temporary failure in name resolution"
        },
        ...
        }
    ],
    "nextBackwardToken": "eEXAMPLEZXJUZXh0IjoiZnRWb3F3cUpRSlQ5NndMYThxelRUZlFhR3J6c2dKWEEvM2kvajZMZzVVVWpqRDN0YjFXTjNrak5pRk9iVFRZdjkwVGlpZGw5NFJGSFRQTEdJSjdpQnFCRk5CZFJlYTZaSXpScStuZjJEYXhqM2grUFVJOEpIYlU5YWJ2QitvQWN5cEFyVUo3VDk1QWY3bVF6MEwvcVovVldZdGc9Iiwibm9uY2UiOiJBNHpzdWMvUkZZKzRvUzhEIiwiY2lwaGVyIjoiQUVTL0dDTS9Ob1BhZGEXAMPLEQ==",
    "nextForwardToken": "eEXAMPLEZXJUZXh0IjoiT09Lb0Z6ZFRJbHhaNEQ5N2tPbkkwRmwwNUxPZjFTbFFwUklQbzlSaWgvMWVXbEk4aG56VHg4bW1Gb3grbDVodUVNZEdiZXN0TzVYcjlLK1FUdFB2RlJLS2FMcU05WkN3Rm1uVzBkOFpDR2g0b1BBVlg2NVFGNDNPazZzRXJieHRuU0xzdkRNTkFUMTZibU9HM2YyaGxiS0hUUDA9Iiwibm9uY2UiOiJFQmI4STQ3cU5aWXNXZ0g4IiwiY2lwaGVyIjoiQUVTL0dDTS9Ob1BhZGEXAMPLEQ=="
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseLogEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-log-events.html)」を参照してください。

### `get-relational-database-log-streams`
<a name="lightsail_GetRelationalDatabaseLogStreams_cli_2_topic"></a>

次のコード例は、`get-relational-database-log-streams` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースのログストリームを取得するには**  
次の `get-relational-database-log-streams` の例では、指定されたリレーショナルデータベースで使用できるすべてのログストリームを返します。  

```
aws lightsail get-relational-database-log-streams \
--relational-database-name Database1
```
出力:  

```
{
    "logStreams": [
        "audit",
        "error",
        "general",
        "slowquery"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseLogStreams](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-log-streams.html)」を参照してください。

### `get-relational-database-master-user-password`
<a name="lightsail_GetRelationalDatabaseMasterUserPassword_cli_2_topic"></a>

次のコード例は、`get-relational-database-master-user-password` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースのマスターユーザーパスワードを取得するには**  
次の `get-relational-database-master-user-password` の例では、指定されたリレーショナルデータベースのマスターユーザーパスワードに関する情報を返します。  

```
aws lightsail get-relational-database-master-user-password \
    --relational-database-name Database-1
```
出力:  

```
{
    "masterUserPassword": "VEXAMPLEec.9qvx,_t<)Wkf)kwboM,>2",
    "createdAt": 1571259453.959
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseMasterUserPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-master-user-password.html)」を参照してください。

### `get-relational-database-metric-data`
<a name="lightsail_GetRelationalDatabaseMetricData_cli_2_topic"></a>

次のコード例は、`get-relational-database-metric-data` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースのメトリクスデータを取得するには**  
次の `get-relational-database-metric-data` の例では、リレーショナルデータベース `Database1` の `1570733176` と `1571597176` の間の 24 時間 (`86400` 秒) にわたるメトリクス `DatabaseConnections` のカウント合計を返します。  
Unix タイムコンバーターを使用して、開始時刻と終了時刻を特定することをお勧めします。  

```
aws lightsail get-relational-database-metric-data \
    --relational-database-name Database1 \
    --metric-name DatabaseConnections \
    --period 86400 \
    --start-time 1570733176 \
    --end-time 1571597176 \
    --unit Count \
    --statistics Sum
```
出力:  

```
{
    "metricName": "DatabaseConnections",
    "metricData": [
        {
            "sum": 1.0,
            "timestamp": 1571510760.0,
            "unit": "Count"
        },
        {
            "sum": 1.0,
            "timestamp": 1570733160.0,
            "unit": "Count"
        },
        {
            "sum": 1.0,
            "timestamp": 1570992360.0,
            "unit": "Count"
        },
        {
            "sum": 0.0,
            "timestamp": 1571251560.0,
            "unit": "Count"
        },
        {
            "sum": 721.0,
            "timestamp": 1570819560.0,
            "unit": "Count"
        },
        {
            "sum": 1.0,
            "timestamp": 1571078760.0,
            "unit": "Count"
        },
        {
            "sum": 2.0,
            "timestamp": 1571337960.0,
            "unit": "Count"
        },
        {
            "sum": 684.0,
            "timestamp": 1570905960.0,
            "unit": "Count"
        },
        {
            "sum": 0.0,
            "timestamp": 1571165160.0,
            "unit": "Count"
        },
        {
            "sum": 1.0,
            "timestamp": 1571424360.0,
            "unit": "Count"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseMetricData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-metric-data.html)」を参照してください。

### `get-relational-database-parameters`
<a name="lightsail_GetRelationalDatabaseParameters_cli_2_topic"></a>

次のコード例は、`get-relational-database-parameters` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースのパラメータを取得するには**  
次の `get-relational-database-parameters` の例では、指定されたリレーショナルデータベースで使用可能なすべてのパラメータに関する情報を返します。  

```
aws lightsail get-relational-database-parameters \
    --relational-database-name Database-1
```
出力:  

```
{
    "parameters": [
        {
            "allowedValues": "0,1",
            "applyMethod": "pending-reboot",
            "applyType": "dynamic",
            "dataType": "boolean",
            "description": "Automatically set all granted roles as active after the user has authenticated successfully.",
            "isModifiable": true,
            "parameterName": "activate_all_roles_on_login",
            "parameterValue": "0"
        },
        {
            "allowedValues": "0,1",
            "applyMethod": "pending-reboot",
            "applyType": "static",
            "dataType": "boolean",
            "description": "Controls whether user-defined functions that have only an xxx symbol for the main function can be loaded",
            "isModifiable": false,
            "parameterName": "allow-suspicious-udfs"
        },
        {
            "allowedValues": "0,1",
            "applyMethod": "pending-reboot",
            "applyType": "dynamic",
            "dataType": "boolean",
            "description": "Sets the autocommit mode",
            "isModifiable": true,
            "parameterName": "autocommit"
        },
        {
            "allowedValues": "0,1",
            "applyMethod": "pending-reboot",
            "applyType": "static",
            "dataType": "boolean",
            "description": "Controls whether the server autogenerates SSL key and certificate files in the data directory, if they do not already exist.",
            "isModifiable": false,
            "parameterName": "auto_generate_certs"
        },
        ...
        }
    ]
}
```
詳細については、「*Lightsail Dev Guide*」の「[Updating database parameters in Amazon Lightsail](https://lightsail.aws.amazon.com/ls/docs/en_us/articles/amazon-lightsail-updating-database-parameters)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-parameters.html)」を参照してください。

### `get-relational-database-snapshot`
<a name="lightsail_GetRelationalDatabaseSnapshot_cli_2_topic"></a>

次のコード例は、`get-relational-database-snapshot` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースのスナップショットに関する情報を取得するには**  
次の `get-relational-database-snapshot` の例では、指定されたリレーショナルデータベーススナップショットの詳細を表示します。  

```
aws lightsail get-relational-database-snapshot \
    --relational-database-snapshot-name Database-1-1571350042
```
出力:  

```
{
    "relationalDatabaseSnapshot": {
        "name": "Database-1-1571350042",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabaseSnapshot/0389bbad-4b85-4c3d-9EXAMPLEaee3643d2",
        "supportCode": "6EXAMPLE3362/ls-8EXAMPLE2ba7ad041451946fafc2ad19cfbd9eb2",
        "createdAt": 1571350046.238,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "resourceType": "RelationalDatabaseSnapshot",
        "tags": [],
        "engine": "mysql",
        "engineVersion": "8.0.16",
        "sizeInGb": 40,
        "state": "available",
        "fromRelationalDatabaseName": "Database-1",
        "fromRelationalDatabaseArn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabase/7ea932b1-b85a-4bd5-9b3e-bEXAMPLE8cc4",
        "fromRelationalDatabaseBundleId": "micro_1_0",
        "fromRelationalDatabaseBlueprintId": "mysql_8_0"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-snapshot.html)」を参照してください。

### `get-relational-database-snapshots`
<a name="lightsail_GetRelationalDatabaseSnapshots_cli_2_topic"></a>

次のコード例は、`get-relational-database-snapshots` を使用する方法を示しています。

**AWS CLI**  
**すべてのリレーショナルデータベースのスナップショットに関する情報を取得するには**  
次の の`get-relational-database-snapshots`例では、設定された AWS リージョンのすべてのリレーショナルデータベーススナップショットの詳細を表示します。  

```
aws lightsail get-relational-database-snapshots
```
出力:  

```
{
    "relationalDatabaseSnapshots": [
        {
            "name": "Database-1-1571350042",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabaseSnapshot/0389bbad-4b85-4c3d-9861-6EXAMPLE43d2",
            "supportCode": "6EXAMPLE3362/ls-8EXAMPLE2ba7ad041451946fafc2ad19cfbd9eb2",
            "createdAt": 1571350046.238,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "RelationalDatabaseSnapshot",
            "tags": [],
            "engine": "mysql",
            "engineVersion": "8.0.16",
            "sizeInGb": 40,
            "state": "available",
            "fromRelationalDatabaseName": "Database-1",
            "fromRelationalDatabaseArn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabase/7ea932b1-b85a-4bd5-9b3e-bEXAMPLE8cc4",
            "fromRelationalDatabaseBundleId": "micro_1_0",
            "fromRelationalDatabaseBlueprintId": "mysql_8_0"
        },
        {
            "name": "Database1-Console",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabaseSnapshot/8b94136e-06ec-4b1a-a3fb-5EXAMPLEe1e9",
            "supportCode": "6EXAMPLE3362/ls-9EXAMPLE14b000d34c8d1c432734e137612d5b5c",
            "createdAt": 1571249981.025,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "RelationalDatabaseSnapshot",
            "tags": [
                {
                    "key": "test"
                }
            ],
            "engine": "mysql",
            "engineVersion": "5.6.44",
            "sizeInGb": 40,
            "state": "available",
            "fromRelationalDatabaseName": "Database1",
            "fromRelationalDatabaseArn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabase/a6161cb7-4535-4f16-9dcf-8EXAMPLE3d4e",
            "fromRelationalDatabaseBundleId": "micro_1_0",
            "fromRelationalDatabaseBlueprintId": "mysql_5_6"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabaseSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database-snapshots.html)」を参照してください。

### `get-relational-database`
<a name="lightsail_GetRelationalDatabase_cli_2_topic"></a>

次のコード例は、`get-relational-database` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースに関する情報を取得するには**  
次の `get-relational-database` の例では、指定されたリレーショナルデータベースの詳細を表示します。  

```
aws lightsail get-relational-database \
    --relational-database-name Database-1
```
出力:  

```
{
    "relationalDatabase": {
        "name": "Database-1",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabase/7ea932b1-b85a-4bd5-9b3e-bEXAMPLE8cc4",
        "supportCode": "6EXAMPLE3362/ls-9EXAMPLE8ad863723b62cc8901a8aa6e794ae0d2",
        "createdAt": 1571259453.795,
        "location": {
            "availabilityZone": "us-west-2a",
            "regionName": "us-west-2"
        },
        "resourceType": "RelationalDatabase",
        "tags": [],
        "relationalDatabaseBlueprintId": "mysql_8_0",
        "relationalDatabaseBundleId": "micro_1_0",
        "masterDatabaseName": "dbmaster",
        "hardware": {
            "cpuCount": 1,
            "diskSizeInGb": 40,
            "ramSizeInGb": 1.0
        },
        "state": "available",
        "backupRetentionEnabled": false,
        "pendingModifiedValues": {},
        "engine": "mysql",
        "engineVersion": "8.0.16",
        "masterUsername": "dbmasteruser",
        "parameterApplyStatus": "in-sync",
        "preferredBackupWindow": "10:01-10:31",
        "preferredMaintenanceWindow": "sat:11:14-sat:11:44",
        "publiclyAccessible": true,
        "masterEndpoint": {
            "port": 3306,
            "address": "ls-9EXAMPLE8ad863723b62ccEXAMPLEa6e794ae0d2.czowadgeezqi.us-west-2.rds.amazonaws.com"
        },
        "pendingMaintenanceActions": []
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-database.html)」を参照してください。

### `get-relational-databases`
<a name="lightsail_GetRelationalDatabases_cli_2_topic"></a>

次のコード例は、`get-relational-databases` を使用する方法を示しています。

**AWS CLI**  
**すべてのリレーショナルデータベースに関する情報を取得するには**  
次の の`get-relational-databases`例では、設定された AWS リージョン内のすべてのリレーショナルデータベースの詳細を表示します。  

```
aws lightsail get-relational-databases
```
出力:  

```
{
    "relationalDatabases": [
        {
            "name": "MySQL",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabase/8529020c-3ab9-4d51-92af-5EXAMPLE8979",
            "supportCode": "6EXAMPLE3362/ls-3EXAMPLEa995d8c3b06b4501356e5f2f28e1aeba",
            "createdAt": 1554306019.155,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "resourceType": "RelationalDatabase",
            "tags": [],
            "relationalDatabaseBlueprintId": "mysql_8_0",
            "relationalDatabaseBundleId": "micro_1_0",
            "masterDatabaseName": "dbmaster",
            "hardware": {
                "cpuCount": 1,
                "diskSizeInGb": 40,
                "ramSizeInGb": 1.0
            },
            "state": "available",
            "backupRetentionEnabled": true,
            "pendingModifiedValues": {},
            "engine": "mysql",
            "engineVersion": "8.0.15",
            "latestRestorableTime": 1571686200.0,
            "masterUsername": "dbmasteruser",
            "parameterApplyStatus": "in-sync",
            "preferredBackupWindow": "07:51-08:21",
            "preferredMaintenanceWindow": "tue:12:18-tue:12:48",
            "publiclyAccessible": true,
            "masterEndpoint": {
                "port": 3306,
                "address": "ls-3EXAMPLEa995d8c3b06b4501356e5f2fEXAMPLEa.czowadgeezqi.us-west-2.rds.amazonaws.com"
            },
            "pendingMaintenanceActions": []
        },
        {
            "name": "Postgres",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:RelationalDatabase/e9780b6b-d0ab-4af2-85f1-1EXAMPLEac68",
            "supportCode": "6EXAMPLE3362/ls-3EXAMPLEb4fffb5cec056220c734713e14bd5fcd",
            "createdAt": 1554306000.814,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "resourceType": "RelationalDatabase",
            "tags": [],
            "relationalDatabaseBlueprintId": "postgres_11",
            "relationalDatabaseBundleId": "micro_1_0",
            "masterDatabaseName": "dbmaster",
            "hardware": {
                "cpuCount": 1,
                "diskSizeInGb": 40,
                "ramSizeInGb": 1.0
            },
            "state": "available",
            "backupRetentionEnabled": true,
            "pendingModifiedValues": {},
            "engine": "postgres",
            "engineVersion": "11.1",
            "latestRestorableTime": 1571686339.0,
            "masterUsername": "dbmasteruser",
            "parameterApplyStatus": "in-sync",
            "preferredBackupWindow": "06:19-06:49",
            "preferredMaintenanceWindow": "sun:10:19-sun:10:49",
            "publiclyAccessible": false,
            "masterEndpoint": {
                "port": 5432,
                "address": "ls-3EXAMPLEb4fffb5cec056220c734713eEXAMPLEd.czowadgeezqi.us-west-2.rds.amazonaws.com"
            },
            "pendingMaintenanceActions": []
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRelationalDatabases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-relational-databases.html)」を参照してください。

### `get-static-ip`
<a name="lightsail_GetStaticIp_cli_2_topic"></a>

次のコード例は、`get-static-ip` を使用する方法を示しています。

**AWS CLI**  
**静的 IP に関する情報を取得するには**  
次の `get-static-ip` の例では、指定された静的 IP の詳細を表示します。  

```
aws lightsail get-static-ip \
    --static-ip-name StaticIp-1
```
出力:  

```
{
    "staticIp": {
        "name": "StaticIp-1",
        "arn": "arn:aws:lightsail:us-west-2:111122223333:StaticIp/2257cd76-1f0e-4ac0-82e2-2EXAMPLE23ad",
        "supportCode": "6EXAMPLE3362/192.0.2.0",
        "createdAt": 1571071325.076,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "resourceType": "StaticIp",
        "ipAddress": "192.0.2.0",
        "isAttached": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStaticIp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-static-ip.html)」を参照してください。

### `get-static-ips`
<a name="lightsail_GetStaticIps_cli_2_topic"></a>

次のコード例は、`get-static-ips` を使用する方法を示しています。

**AWS CLI**  
**すべての静的 IP に関する情報を取得するには**  
次の の`get-static-ips`例では、設定された AWS リージョンのすべての静的 IPs の詳細を表示します。  

```
aws lightsail get-static-ips
```
出力:  

```
{
    "staticIps": [
        {
            "name": "StaticIp-1",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:StaticIp/2257cd76-1f0e-4ac0-8EXAMPLE16f9423ad",
            "supportCode": "6EXAMPLE3362/192.0.2.0",
            "createdAt": 1571071325.076,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "StaticIp",
            "ipAddress": "192.0.2.0",
            "isAttached": false
        },
        {
            "name": "StaticIP-2",
            "arn": "arn:aws:lightsail:us-west-2:111122223333:StaticIp/c61edb40-e5f0-4fd6-ae7c-8EXAMPLE19f8",
            "supportCode": "6EXAMPLE3362/192.0.2.2",
            "createdAt": 1568305385.681,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "resourceType": "StaticIp",
            "ipAddress": "192.0.2.2",
            "attachedTo": "WordPress-1",
            "isAttached": true
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetStaticIps](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/get-static-ips.html)」を参照してください。

### `is-vpc-peered`
<a name="lightsail_IsVpcPeered_cli_2_topic"></a>

次のコード例は、`is-vpc-peered` を使用する方法を示しています。

**AWS CLI**  
**Amazon Lightsail 仮想プライベートクラウドがピアリングされているかどうかを確認するには**  
次の の`is-vpc-peered`例では、指定された AWS リージョンの Amazon Lightsail Virtual Private Cloud (VPC) のピアリングステータスを返します。  

```
aws lightsail is-vpc-peered \
    --region us-west-2
```
出力:  

```
{
    "isPeered": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IsVpcPeered](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/is-vpc-peered.html)」を参照してください。

### `open-instance-public-ports`
<a name="lightsail_OpenInstancePublicPorts_cli_2_topic"></a>

次のコード例は、`open-instance-public-ports` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのファイアウォールポートを開くには**  
次の `open-instance-public-ports` の例では、指定されたインスタンスで TCP ポート 22 を開きます。  

```
aws lightsail open-instance-public-ports \
    --instance-name MEAN-2 \
    --port-info fromPort=22,protocol=TCP,toPort=22
```
出力:  

```
{
    "operation": {
        "id": "719744f0-a022-46f2-9f11-6EXAMPLE4642",
        "resourceName": "MEAN-2",
        "resourceType": "Instance",
        "createdAt": 1571072906.849,
        "location": {
            "availabilityZone": "us-west-2a",
            "regionName": "us-west-2"
        },
        "isTerminal": true,
        "operationDetails": "22/tcp",
        "operationType": "OpenInstancePublicPorts",
        "status": "Succeeded",
        "statusChangedAt": 1571072906.849
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[OpenInstancePublicPorts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/open-instance-public-ports.html)」を参照してください。

### `peer-vpc`
<a name="lightsail_PeerVpc_cli_2_topic"></a>

次のコード例は、`peer-vpc` を使用する方法を示しています。

**AWS CLI**  
**Amazon Lightsail 仮想プライベートクラウドをピアリングするには**  
次の の`peer-vpc`例では、指定された AWS リージョンのAmazon Lightsail仮想プライベートクラウド (VPC) をピアリングします。  

```
aws lightsail peer-vpc \
    --region us-west-2
```
出力:  

```
{
    "operation": {
        "id": "787e846a-54ac-497f-bce2-9EXAMPLE5d91",
        "resourceName": "vpc-0EXAMPLEa5261efb3",
        "resourceType": "PeeredVpc",
        "createdAt": 1571694233.104,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "isTerminal": true,
        "operationDetails": "vpc-e2b3eb9b",
        "operationType": "PeeredVpc",
        "status": "Succeeded",
        "statusChangedAt": 1571694233.104
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PeerVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/peer-vpc.html)」を参照してください。

### `reboot-instance`
<a name="lightsail_RebootInstance_cli_2_topic"></a>

次のコード例は、`reboot-instance` を使用する方法を示しています。

**AWS CLI**  
**インスタンスを再起動するには**  
次の `reboot-instance` の例では、指定されたインスタンスを再起動します。  

```
aws lightsail reboot-instance \
    --instance-name MEAN-1
```
出力:  

```
{
    "operations": [
        {
            "id": "2b679f1c-8b71-4bb4-8e97-8EXAMPLEed93",
            "resourceName": "MEAN-1",
            "resourceType": "Instance",
            "createdAt": 1571694445.49,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationDetails": "",
            "operationType": "RebootInstance",
            "status": "Succeeded",
            "statusChangedAt": 1571694445.49
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/reboot-instance.html)」を参照してください。

### `reboot-relational-database`
<a name="lightsail_RebootRelationalDatabase_cli_2_topic"></a>

次のコード例は、`reboot-relational-database` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースを再起動するには**  
次の `reboot-relational-database` の例では、指定されたリレーショナルデータベースを再起動します。  

```
aws lightsail reboot-relational-database \
    --relational-database-name Database-1
```
出力:  

```
{
    "operations": [
        {
            "id": "e4c980c0-3137-496c-9c91-1EXAMPLEdec2",
            "resourceName": "Database-1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1571694532.91,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationDetails": "",
            "operationType": "RebootRelationalDatabase",
            "status": "Started",
            "statusChangedAt": 1571694532.91
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootRelationalDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/reboot-relational-database.html)」を参照してください。

### `release-static-ip`
<a name="lightsail_ReleaseStaticIp_cli_2_topic"></a>

次のコード例は、`release-static-ip` を使用する方法を示しています。

**AWS CLI**  
**静的 IP を削除するには**  
次の `release-static-ip` の例では、指定された静的 IP を削除します。  

```
aws lightsail release-static-ip \
    --static-ip-name StaticIp-1
```
出力:  

```
{
    "operations": [
        {
            "id": "e374c002-dc6d-4c7f-919f-2EXAMPLE13ce",
            "resourceName": "StaticIp-1",
            "resourceType": "StaticIp",
            "createdAt": 1571694962.003,
            "location": {
                "availabilityZone": "all",
                "regionName": "us-west-2"
            },
            "isTerminal": true,
            "operationType": "ReleaseStaticIp",
            "status": "Succeeded",
            "statusChangedAt": 1571694962.003
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReleaseStaticIp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/release-static-ip.html)」を参照してください。

### `start-instance`
<a name="lightsail_StartInstance_cli_2_topic"></a>

次のコード例は、`start-instance` を使用する方法を示しています。

**AWS CLI**  
**インスタンスを開始するには**  
次の `start-instance` の例では、指定されたインスタンスを起動します。  

```
aws lightsail start-instance \
    --instance-name WordPress-1
```
出力:  

```
{
    "operations": [
        {
            "id": "f88d2a93-7cea-4165-afce-2d688cb18f23",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1571695583.463,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "StartInstance",
            "status": "Started",
            "statusChangedAt": 1571695583.463
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/start-instance.html)」を参照してください。

### `start-relational-database`
<a name="lightsail_StartRelationalDatabase_cli_2_topic"></a>

次のコード例は、`start-relational-database` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースを開始するには**  
次の `start-relational-database` の例では、指定されたリレーショナルデータベースを開始します。  

```
aws lightsail start-relational-database \
    --relational-database-name Database-1
```
出力:  

```
{
    "operations": [
        {
            "id": "4d5294ec-a38a-4fda-9e37-aEXAMPLE0d24",
            "resourceName": "Database-1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1571695998.822,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "StartRelationalDatabase",
            "status": "Started",
            "statusChangedAt": 1571695998.822
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartRelationalDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/start-relational-database.html)」を参照してください。

### `stop-instance`
<a name="lightsail_StopInstance_cli_2_topic"></a>

次のコード例は、`stop-instance` を使用する方法を示しています。

**AWS CLI**  
**インスタンスを停止するには**  
次の `stop-instance` の例では、指定されたインスタンスを停止します。  

```
aws lightsail stop-instance \
--instance-name WordPress-1
```
出力:  

```
{
    "operations": [
        {
            "id": "265357e2-2943-4d51-888a-1EXAMPLE7585",
            "resourceName": "WordPress-1",
            "resourceType": "Instance",
            "createdAt": 1571695471.134,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "StopInstance",
            "status": "Started",
            "statusChangedAt": 1571695471.134
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/stop-instance.html)」を参照してください。

### `stop-relational-database`
<a name="lightsail_StopRelationalDatabase_cli_2_topic"></a>

次のコード例は、`stop-relational-database` を使用する方法を示しています。

**AWS CLI**  
**リレーショナルデータベースを停止するには**  
次の `stop-relational-database` の例では、指定されたリレーショナルデータベースを停止します。  

```
aws lightsail stop-relational-database \
    --relational-database-name Database-1
```
出力:  

```
{
    "operations": [
        {
            "id": "cc559c19-4adb-41e4-b75b-5EXAMPLE4e61",
            "resourceName": "Database-1",
            "resourceType": "RelationalDatabase",
            "createdAt": 1571695526.29,
            "location": {
                "availabilityZone": "us-west-2a",
                "regionName": "us-west-2"
            },
            "isTerminal": false,
            "operationType": "StopRelationalDatabase",
            "status": "Started",
            "statusChangedAt": 1571695526.29
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopRelationalDatabase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/stop-relational-database.html)」を参照してください。

### `unpeer-vpc`
<a name="lightsail_UnpeerVpc_cli_2_topic"></a>

次のコード例は、`unpeer-vpc` を使用する方法を示しています。

**AWS CLI**  
**Amazon Lightsail 仮想プライベートクラウドをピアリングするには**  
次の の`unpeer-vpc`例では、指定された AWS リージョンの Amazon Lightsail Virtual Private Cloud (VPC) のピアリングを解除します。  

```
aws lightsail unpeer-vpc \
    --region us-west-2
```
出力:  

```
{
    "operation": {
        "id": "531aca64-7157-47ab-84c6-eEXAMPLEd898",
        "resourceName": "vpc-0EXAMPLEa5261efb3",
        "resourceType": "PeeredVpc",
        "createdAt": 1571694109.945,
        "location": {
            "availabilityZone": "all",
            "regionName": "us-west-2"
        },
        "isTerminal": true,
        "operationDetails": "vpc-e2b3eb9b",
        "operationType": "UnpeeredVpc",
        "status": "Succeeded",
        "statusChangedAt": 1571694109.945
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UnpeerVpc](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/lightsail/unpeer-vpc.html)」を参照してください。

# を使用した Macie の例 AWS CLI
<a name="cli_2_macie2_code_examples"></a>

次のコード例は、Macie AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-buckets`
<a name="macie2_DescribeBuckets_cli_2_topic"></a>

次のコード例は、`describe-buckets` を使用する方法を示しています。

**AWS CLI**  
**Amazon Macie がアカウントのモニタリングおよび分析を行う 1 つ以上の S3 バケットに関するデータのクエリを実行するには**  
次の`describe-buckets`例では、名前が amzn-S3-demo-bucket で始まり、現在の AWS リージョンにあるすべての S3 バケットのメタデータをクエリします。  

```
aws macie2 describe-buckets \
    --criteria '{"bucketName":{"prefix":"amzn-s3-demo-bucket"}}'
```
出力:  

```
{
    "buckets": [
        {
            "accountId": "123456789012",
            "allowsUnencryptedObjectUploads": "FALSE",
            "automatedDiscoveryMonitoringStatus": "MONITORED",
            "bucketArn": "arn:aws:s3:::amzn-s3-demo-bucket1",
            "bucketCreatedAt": "2020-05-18T19:54:00+00:00",
            "bucketName": "amzn-s3-demo-bucket1",
            "classifiableObjectCount": 13,
            "classifiableSizeInBytes": 1592088,
            "jobDetails": {
                "isDefinedInJob": "TRUE",
                "isMonitoredByJob": "TRUE",
                "lastJobId": "08c81dc4a2f3377fae45c9ddaEXAMPLE",
                "lastJobRunTime": "2024-08-19T14:55:30.270000+00:00"
            },
            "lastAutomatedDiscoveryTime": "2024-10-22T19:11:25.364000+00:00",
            "lastUpdated": "2024-10-25T07:33:06.337000+00:00",
            "objectCount": 13,
            "objectCountByEncryptionType": {
                "customerManaged": 0,
                "kmsManaged": 2,
                "s3Managed": 7,
                "unencrypted": 4,
                "unknown": 0
            },
            "publicAccess": {
                "effectivePermission": "NOT_PUBLIC",
                "permissionConfiguration": {
                    "accountLevelPermissions": {
                        "blockPublicAccess": {
                            "blockPublicAcls": true,
                            "blockPublicPolicy": true,
                            "ignorePublicAcls": true,
                            "restrictPublicBuckets": true
                        }
                    },
                    "bucketLevelPermissions": {
                        "accessControlList": {
                            "allowsPublicReadAccess": false,
                            "allowsPublicWriteAccess": false
                        },
                        "blockPublicAccess": {
                            "blockPublicAcls": true,
                            "blockPublicPolicy": true,
                            "ignorePublicAcls": true,
                            "restrictPublicBuckets": true
                        },
                        "bucketPolicy": {
                            "allowsPublicReadAccess": false,
                            "allowsPublicWriteAccess": false
                        }
                    }
                }
            },
            "region": "us-west-2",
            "replicationDetails": {
                "replicated": false,
                "replicatedExternally": false,
                "replicationAccounts": []
            },
            "sensitivityScore": 78,
            "serverSideEncryption": {
                "kmsMasterKeyId": null,
                "type": "NONE"
            },
            "sharedAccess": "NOT_SHARED",
            "sizeInBytes": 4549746,
            "sizeInBytesCompressed": 0,
            "tags": [
                {
                    "key": "Division",
                    "value": "HR"
                },
                {
                    "key": "Team",
                    "value": "Recruiting"
                }
            ],
            "unclassifiableObjectCount": {
                "fileType": 0,
                "storageClass": 0,
                "total": 0
            },
            "unclassifiableObjectSizeInBytes": {
                "fileType": 0,
                "storageClass": 0,
                "total": 0
            },
            "versioning": true
        },
        {
            "accountId": "123456789012",
            "allowsUnencryptedObjectUploads": "TRUE",
            "automatedDiscoveryMonitoringStatus": "MONITORED",
            "bucketArn": "arn:aws:s3:::amzn-s3-demo-bucket2",
            "bucketCreatedAt": "2020-11-25T18:24:38+00:00",
            "bucketName": "amzn-s3-demo-bucket2",
            "classifiableObjectCount": 8,
            "classifiableSizeInBytes": 133810,
            "jobDetails": {
                "isDefinedInJob": "TRUE",
                "isMonitoredByJob": "FALSE",
                "lastJobId": "188d4f6044d621771ef7d65f2EXAMPLE",
                "lastJobRunTime": "2024-07-09T19:37:11.511000+00:00"
            },
            "lastAutomatedDiscoveryTime": "2024-10-24T19:11:25.364000+00:00",
            "lastUpdated": "2024-10-25T07:33:06.337000+00:00",
            "objectCount": 8,
            "objectCountByEncryptionType": {
                "customerManaged": 0,
                "kmsManaged": 0,
                "s3Managed": 8,
                "unencrypted": 0,
                "unknown": 0
            },
            "publicAccess": {
                "effectivePermission": "NOT_PUBLIC",
                "permissionConfiguration": {
                    "accountLevelPermissions": {
                        "blockPublicAccess": {
                            "blockPublicAcls": true,
                            "blockPublicPolicy": true,
                            "ignorePublicAcls": true,
                            "restrictPublicBuckets": true
                        }
                    },
                    "bucketLevelPermissions": {
                        "accessControlList": {
                            "allowsPublicReadAccess": false,
                            "allowsPublicWriteAccess": false
                        },
                        "blockPublicAccess": {
                            "blockPublicAcls": true,
                            "blockPublicPolicy": true,
                            "ignorePublicAcls": true,
                            "restrictPublicBuckets": true
                        },
                        "bucketPolicy": {
                            "allowsPublicReadAccess": false,
                            "allowsPublicWriteAccess": false
                        }
                    }
                }
            },
            "region": "us-west-2",
            "replicationDetails": {
                "replicated": false,
                "replicatedExternally": false,
                "replicationAccounts": []
            },
            "sensitivityScore": 95,
            "serverSideEncryption": {
                "kmsMasterKeyId": null,
                "type": "AES256"
            },
            "sharedAccess": "EXTERNAL",
            "sizeInBytes": 175978,
            "sizeInBytesCompressed": 0,
            "tags": [
                {
                    "key": "Division",
                    "value": "HR"
                },
                {
                    "key": "Team",
                    "value": "Recruiting"
                }
            ],
            "unclassifiableObjectCount": {
                "fileType": 3,
                "storageClass": 0,
                "total": 3
            },
            "unclassifiableObjectSizeInBytes": {
                "fileType": 2999826,
                "storageClass": 0,
                "total": 2999826
            },
            "versioning": true
        }
    ]
}
```
詳細については、「*Amazon Macie User Guide*」の「[Filtering your S3 bucket inventory](https://docs.aws.amazon.com/macie/latest/user/monitoring-s3-inventory-filter.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBuckets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/macie2/describe-buckets.html)」を参照してください。

# を使用した Amazon Managed Grafana の例 AWS CLI
<a name="cli_2_grafana_code_examples"></a>

次のコード例は、Amazon Managed Grafana AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `list-workspaces`
<a name="grafana_ListWorkspaces_cli_2_topic"></a>

次のコード例は、`list-workspaces` を使用する方法を示しています。

**AWS CLI**  
**ユーザー認証情報で指定されたリージョン内のアカウントのワークスペースを一覧表示するには**  
次の `list-workspaces` の例では、アカウントのリージョンの Grafana ワークスペースを一覧表示します。  

```
aws grafana list-workspaces
```
出力:  

```
{
    "workspaces": [
        {
            "authentication": {
                "providers": [
                    "AWS_SSO"
                ]
            },
            "created": "2022-04-04T16:20:21.796000-07:00",
            "description": "to test tags",
            "endpoint": "g-949e7b44df.grafana-workspace.us-east-1.amazonaws.com",
            "grafanaVersion": "8.2",
            "id": "g-949e7b44df",
            "modified": "2022-04-04T16:20:21.796000-07:00",
            "name": "testtag2",
            "notificationDestinations": [
                "SNS"
            ],
            "status": "ACTIVE"
        },
        {
            "authentication": {
                "providers": [
                    "AWS_SSO"
                ]
            },
            "created": "2022-04-20T10:22:15.115000-07:00",
            "description": "ww",
            "endpoint": "g-bffa51ed1b.grafana-workspace.us-east-1.amazonaws.com",
            "grafanaVersion": "8.2",
            "id": "g-bffa51ed1b",
            "modified": "2022-04-20T10:22:15.115000-07:00",
            "name": "ww",
            "notificationDestinations": [
                "SNS"
            ],
            "status": "ACTIVE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/grafana/list-workspaces.html)」を参照してください。

# を使用した MediaConnect の例 AWS CLI
<a name="cli_2_mediaconnect_code_examples"></a>

次のコード例は、MediaConnect AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-flow-outputs`
<a name="mediaconnect_AddFlowOutputs_cli_2_topic"></a>

次のコード例は、`add-flow-outputs` を使用する方法を示しています。

**AWS CLI**  
**出力をフローに追加するには**  
次の `add-flow-outputs` の例では、指定されたフローに出力を追加します。  

```
aws mediaconnect add-flow-outputs \
--flow-arn arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame \
--outputs Description='NYC stream',Destination=192.0.2.12,Name=NYC,Port=3333,Protocol=rtp-fec,SmoothingLatency=100 Description='LA stream',Destination=203.0.113.9,Name=LA,Port=4444,Protocol=rtp-fec,SmoothingLatency=100
```
出力:  

```
{
    "Outputs": [
        {
            "Port": 3333,
            "OutputArn": "arn:aws:mediaconnect:us-east-1:111122223333:output:2-3aBC45dEF67hiJ89-c34de5fG678h:NYC",
            "Name": "NYC",
            "Description": "NYC stream",
            "Destination": "192.0.2.12",
            "Transport": {
                "Protocol": "rtp-fec",
                "SmoothingLatency": 100
            }
        },
        {
            "Port": 4444,
            "OutputArn": "arn:aws:mediaconnect:us-east-1:111122223333:output:2-987655dEF67hiJ89-c34de5fG678h:LA",
            "Name": "LA",
            "Description": "LA stream",
            "Destination": "203.0.113.9",
            "Transport": {
                "Protocol": "rtp-fec",
                "SmoothingLatency": 100
            }
        }
    ],
    "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame"
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Adding Outputs to a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/outputs-add.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddFlowOutputs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/add-flow-outputs.html)」を参照してください。

### `create-flow`
<a name="mediaconnect_CreateFlow_cli_2_topic"></a>

次のコード例は、`create-flow` を使用する方法を示しています。

**AWS CLI**  
**フローを作成するには**  
次の `create-flow` の例では、指定された設定でフローを作成します。  

```
aws mediaconnect create-flow \
    --availability-zone us-west-2c \
    --name ExampleFlow \
    --source Description='Example source, backup',IngestPort=1055,Name=BackupSource,Protocol=rtp,WhitelistCidr=10.24.34.0/23
```
出力:  

```
{
    "Flow": {
        "FlowArn": "arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:ExampleFlow",
        "AvailabilityZone": "us-west-2c",
        "EgressIp": "54.245.71.21",
        "Source": {
            "IngestPort": 1055,
            "SourceArn": "arn:aws:mediaconnect:us-east-1:123456789012:source:2-3aBC45dEF67hiJ89-c34de5fG678h:BackupSource",
            "Transport": {
                "Protocol": "rtp",
                "MaxBitrate": 80000000
            },
            "Description": "Example source, backup",
            "IngestIp": "54.245.71.21",
            "WhitelistCidr": "10.24.34.0/23",
            "Name": "mySource"
        },
        "Entitlements": [],
        "Name": "ExampleFlow",
        "Outputs": [],
        "Status": "STANDBY",
        "Description": "Example source, backup"
    }
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Creating a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/flows-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFlow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/create-flow.html)」を参照してください。

### `delete-flow`
<a name="mediaconnect_DeleteFlow_cli_2_topic"></a>

次のコード例は、`delete-flow` を使用する方法を示しています。

**AWS CLI**  
**フローを削除するには**  
次の `delete-flow` の例では、指定されたフローを削除します。  

```
aws mediaconnect delete-flow \
    --flow-arn arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow
```
出力:  

```
{
    "FlowArn": "arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow",
    "Status": "DELETING"
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Deleting a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/flows-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFlow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/delete-flow.html)」を参照してください。

### `describe-flow`
<a name="mediaconnect_DescribeFlow_cli_2_topic"></a>

次のコード例は、`describe-flow` を使用する方法を示しています。

**AWS CLI**  
**フローの詳細を表示するには**  
次の `describe-flow` の例では、ARN、アベイラビリティーゾーン、ステータス、ソース、権限、出力など、指定されたフローの詳細を表示します。  

```
aws mediaconnect describe-flow \
    --flow-arn arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow
```
出力:  

```
{
    "Flow": {
        "EgressIp": "54.201.4.39",
        "AvailabilityZone": "us-west-2c",
        "Status": "ACTIVE",
        "FlowArn": "arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow",
        "Entitlements": [
            {
                "EntitlementArn": "arn:aws:mediaconnect:us-west-2:123456789012:entitlement:1-AaBb11CcDd22EeFf-34DE5fG12AbC:MyEntitlement",
                "Description": "Assign to this account",
                "Name": "MyEntitlement",
                "Subscribers": [
                    "444455556666"
                ]
            }
        ],
        "Description": "NYC awards show",
        "Name": "AwardsShow",
        "Outputs": [
            {
                "Port": 2355,
                "Name": "NYC",
                "Transport": {
                    "SmoothingLatency": 0,
                    "Protocol": "rtp-fec"
                },
                "OutputArn": "arn:aws:mediaconnect:us-east-1:123456789012:output:2-3aBC45dEF67hiJ89-c34de5fG678h:NYC",
                "Destination": "192.0.2.0"
            },
            {
                "Port": 3025,
                "Name": "LA",
                "Transport": {
                    "SmoothingLatency": 0,
                    "Protocol": "rtp-fec"
                },
                "OutputArn": "arn:aws:mediaconnect:us-east-1:123456789012:output:2-987655dEF67hiJ89-c34de5fG678h:LA",
                "Destination": "192.0.2.0"
            }
        ],
        "Source": {
            "IngestIp": "54.201.4.39",
            "SourceArn": "arn:aws:mediaconnect:us-east-1:123456789012:source:3-4aBC56dEF78hiJ90-4de5fG6Hi78Jk:ShowSource",
            "Transport": {
                "MaxBitrate": 80000000,
                "Protocol": "rtp"
            },
            "IngestPort": 1069,
            "Description": "Saturday night show",
            "Name": "ShowSource",
            "WhitelistCidr": "10.24.34.0/23"
        }
    }
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Viewing the Details of a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/flows-view-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFlow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/describe-flow.html)」を参照してください。

### `grant-flow-entitlements`
<a name="mediaconnect_GrantFlowEntitlements_cli_2_topic"></a>

次のコード例は、`grant-flow-entitlements` を使用する方法を示しています。

**AWS CLI**  
**フローに権限を付与するには**  
次の の`grant-flow-entitlements`例では、指定された既存のフローに、コンテンツを別の AWS アカウントと共有するためのエンタイトルメントを付与します。  

```
aws mediaconnect grant-flow-entitlements \
    --flow-arn arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame \
    --entitlements Description='For AnyCompany',Encryption={"Algorithm=aes128,KeyType=static-key,RoleArn=arn:aws:iam::111122223333:role/MediaConnect-ASM,SecretArn=arn:aws:secretsmanager:us-west-2:111122223333:secret:mySecret1"},Name=AnyCompany_Entitlement,Subscribers=444455556666 Description='For Example Corp',Name=ExampleCorp,Subscribers=777788889999
```
出力:  

```
{
    "Entitlements": [
        {
            "Name": "AnyCompany_Entitlement",
            "EntitlementArn": "arn:aws:mediaconnect:us-west-2:111122223333:entitlement:1-11aa22bb11aa22bb-3333cccc4444:AnyCompany_Entitlement",
            "Subscribers": [
                "444455556666"
            ],
            "Description": "For AnyCompany",
            "Encryption": {
                "SecretArn": "arn:aws:secretsmanager:us-west-2:111122223333:secret:mySecret1",
                "Algorithm": "aes128",
                "RoleArn": "arn:aws:iam::111122223333:role/MediaConnect-ASM",
                "KeyType": "static-key"
            }
        },
        {
            "Name": "ExampleCorp",
            "EntitlementArn": "arn:aws:mediaconnect:us-west-2:111122223333:entitlement:1-3333cccc4444dddd-1111aaaa2222:ExampleCorp",
            "Subscribers": [
                "777788889999"
            ],
            "Description": "For Example Corp"
        }
    ],
    "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame"
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Granting an Entitlement on a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/entitlements-grant.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GrantFlowEntitlements](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/grant-flow-entitlements.html)」を参照してください。

### `list-entitlements`
<a name="mediaconnect_ListEntitlements_cli_2_topic"></a>

次のコード例は、`list-entitlements` を使用する方法を示しています。

**AWS CLI**  
**権限のリストを表示するには**  
次の `list-entitlements` の例では、アカウントに付与されたすべての権限のリストを表示します。  

```
aws mediaconnect list-entitlements
```
出力:  

```
{
    "Entitlements": [
        {
            "EntitlementArn": "arn:aws:mediaconnect:us-west-2:111122223333:entitlement:1-11aa22bb11aa22bb-3333cccc4444:MyEntitlement",
            "EntitlementName": "MyEntitlement"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaConnect API Reference*」の「[ListEntitlements](https://docs.aws.amazon.com/mediaconnect/latest/api/v1-entitlements.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEntitlements](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/list-entitlements.html)」を参照してください。

### `list-flows`
<a name="mediaconnect_ListFlows_cli_2_topic"></a>

次のコード例は、`list-flows` を使用する方法を示しています。

**AWS CLI**  
**フローのリストを表示するには**  
次の `list-flows` の例では、フローのリストを表示します。  

```
aws mediaconnect list-flows
```
出力:  

```
{
    "Flows": [
        {
            "Status": "STANDBY",
            "SourceType": "OWNED",
            "AvailabilityZone": "us-west-2a",
            "Description": "NYC awards show",
            "Name": "AwardsShow",
            "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow"
        },
        {
            "Status": "STANDBY",
            "SourceType": "OWNED",
            "AvailabilityZone": "us-west-2c",
            "Description": "LA basketball game",
            "Name": "BasketballGame",
            "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BasketballGame"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Viewing a List of Flows](https://docs.aws.amazon.com/mediaconnect/latest/ug/flows-view-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFlows](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/list-flows.html)」を参照してください。

### `list-tags-for-resource`
<a name="mediaconnect_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**MediaConnect リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された MediaConnect に関連付けられたタグキーと値を表示します。  

```
aws mediaconnect list-tags-for-resource \
    --resource-arn arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BasketballGame
```
出力:  

```
{
    "Tags": {
        "region": "west",
        "stage": "prod"
    }
}
```
詳細については、「*AWS Elemental MediaConnect API Reference*」の「[ListTagsForResource, TagResource, UntagResource](https://docs.aws.amazon.com/mediaconnect/latest/api/tags-resourcearn.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/list-tags-for-resource.html)」を参照してください。

### `remove-flow-output`
<a name="mediaconnect_RemoveFlowOutput_cli_2_topic"></a>

次のコード例は、`remove-flow-output` を使用する方法を示しています。

**AWS CLI**  
**フローから出力を削除するには**  
次の `remove-flow-output` の例では、指定されたフローから出力を削除します。  

```
aws mediaconnect remove-flow-output \
    --flow-arn arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame \
    --output-arn arn:aws:mediaconnect:us-east-1:111122223333:output:2-3aBC45dEF67hiJ89-c34de5fG678h:NYC
```
出力:  

```
{
    "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame",
    "OutputArn": "arn:aws:mediaconnect:us-east-1:111122223333:output:2-3aBC45dEF67hiJ89-c34de5fG678h:NYC"
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Removing Outputs from a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/outputs-remove.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveFlowOutput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/remove-flow-output.html)」を参照してください。

### `revoke-flow-entitlement`
<a name="mediaconnect_RevokeFlowEntitlement_cli_2_topic"></a>

次のコード例は、`revoke-flow-entitlement` を使用する方法を示しています。

**AWS CLI**  
**権限を取り消すには**  
次の `revoke-flow-entitlement` の例では、指定されたフローの権限を取り消します。  

```
aws mediaconnect revoke-flow-entitlement \
    --flow-arn arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame \
    --entitlement-arn arn:aws:mediaconnect:us-west-2:111122223333:entitlement:1-11aa22bb11aa22bb-3333cccc4444:AnyCompany_Entitlement
```
出力:  

```
{
    "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame",
    "EntitlementArn": "arn:aws:mediaconnect:us-west-2:111122223333:entitlement:1-11aa22bb11aa22bb-3333cccc4444:AnyCompany_Entitlement"
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Revoking an Entitlement](https://docs.aws.amazon.com/mediaconnect/latest/ug/entitlements-revoke.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokeFlowEntitlement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/revoke-flow-entitlement.html)」を参照してください。

### `start-flow`
<a name="mediaconnect_StartFlow_cli_2_topic"></a>

次のコード例は、`start-flow` を使用する方法を示しています。

**AWS CLI**  
**フローを開始するには**  
次の `start-flow` の例では、指定されたフローを起動します。  

```
aws mediaconnect start-flow \
    --flow-arn arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow
```
このコマンドは何も出力しません。出力:  

```
{
    "FlowArn": "arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow",
    "Status": "STARTING"
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Starting a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/flows-start.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartFlow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/start-flow.html)」を参照してください。

### `stop-flow`
<a name="mediaconnect_StopFlow_cli_2_topic"></a>

次のコード例は、`stop-flow` を使用する方法を示しています。

**AWS CLI**  
**フローを停止するには**  
次の `stop-flow` の例では、指定されたフローを停止します。  

```
aws mediaconnect stop-flow \
    --flow-arn arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow
```
出力:  

```
{
    "Status": "STOPPING",
    "FlowArn": "arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow"
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Stopping a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/flows-stop.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopFlow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/stop-flow.html)」を参照してください。

### `tag-resource`
<a name="mediaconnect_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**MediaConnect リソースにタグを追加するには**  
次の `tag-resource` の例では、指定された MediaConnect リソースにキー名と値を持つタグを追加します。  

```
aws mediaconnect tag-resource \
    --resource-arn arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BasketballGame
    --tags region=west
```
このコマンドは何も出力しません。  
詳細については、「*AWS Elemental MediaConnect API Reference*」の「[ListTagsForResource, TagResource, UntagResource](https://docs.aws.amazon.com/mediaconnect/latest/api/tags-resourcearn.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="mediaconnect_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**MediaConnect リソースからタグを削除するには**  
次の `untag-resource` の例では、MediaConnect リソースから、指定されたキー名と関連付けられた値のタグを削除します。  

```
aws mediaconnect untag-resource \
    --resource-arn arn:aws:mediaconnect:us-east-1:123456789012:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BasketballGame \
    --tag-keys region
```
このコマンドは何も出力しません。  
詳細については、「*AWS Elemental MediaConnect API Reference*」の「[ListTagsForResource, TagResource, UntagResource](https://docs.aws.amazon.com/mediaconnect/latest/api/tags-resourcearn.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/untag-resource.html)」を参照してください。

### `update-flow-entitlement`
<a name="mediaconnect_UpdateFlowEntitlement_cli_2_topic"></a>

次のコード例は、`update-flow-entitlement` を使用する方法を示しています。

**AWS CLI**  
**権限を更新するには**  
次の `update-flow-entitlement` の例では、指定された権限を新しい説明とサブスクライバーで更新します。  

```
aws mediaconnect update-flow-entitlement \
    --flow-arn arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame \
    --entitlement-arn arn:aws:mediaconnect:us-west-2:111122223333:entitlement:1-11aa22bb11aa22bb-3333cccc4444:AnyCompany_Entitlement \
    --description 'For AnyCompany Affiliate' \
    --subscribers 777788889999
```
出力:  

```
{
    "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame",
    "Entitlement": {
        "Name": "AnyCompany_Entitlement",
        "Description": "For AnyCompany Affiliate",
        "EntitlementArn": "arn:aws:mediaconnect:us-west-2:111122223333:entitlement:1-11aa22bb11aa22bb-3333cccc4444:AnyCompany_Entitlement",
        "Encryption": {
            "KeyType": "static-key",
            "Algorithm": "aes128",
            "RoleArn": "arn:aws:iam::111122223333:role/MediaConnect-ASM",
            "SecretArn": "arn:aws:secretsmanager:us-west-2:111122223333:secret:mySecret1"
        },
        "Subscribers": [
            "777788889999"
        ]
    }
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Updating an Entitlement](https://docs.aws.amazon.com/mediaconnect/latest/ug/entitlements-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFlowEntitlement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/update-flow-entitlement.html)」を参照してください。

### `update-flow-output`
<a name="mediaconnect_UpdateFlowOutput_cli_2_topic"></a>

次のコード例は、`update-flow-output` を使用する方法を示しています。

**AWS CLI**  
**フローの出力を更新するには**  
次の `update-flow-output` の例では、指定されたフローの出力を更新します。  

```
aws mediaconnect update-flow-output \
    --flow-arn arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame \
    --output-arn arn:aws:mediaconnect:us-east-1:111122223333:output:2-3aBC45dEF67hiJ89-c34de5fG678h:NYC \
    --port 3331
```
出力:  

```
{
    "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:BaseballGame",
    "Output": {
        "Name": "NYC",
        "Port": 3331,
        "Description": "NYC stream",
        "Transport": {
            "Protocol": "rtp-fec",
            "SmoothingLatency": 100
        },
        "OutputArn": "arn:aws:mediaconnect:us-east-1:111122223333:output:2-3aBC45dEF67hiJ89-c34de5fG678h:NYC",
        "Destination": "192.0.2.12"
    }
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Updating Outputs on a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/outputs-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFlowOutput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/update-flow-output.html)」を参照してください。

### `update-flow-source`
<a name="mediaconnect_UpdateFlowSource_cli_2_topic"></a>

次のコード例は、`update-flow-source` を使用する方法を示しています。

**AWS CLI**  
**既存のフローのソースを更新するには**  
次の `update-flow-source` の例では、既存のフローのソースを更新します。  

```
aws mediaconnect update-flow-source \
    --flow-arn arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow \
    --source-arn arn:aws:mediaconnect:us-east-1:111122223333:source:3-4aBC56dEF78hiJ90-4de5fG6Hi78Jk:ShowSource \
    --description 'Friday night show' \
    --ingest-port 3344 \
    --protocol rtp-fec \
    --whitelist-cidr 10.24.34.0/23
```
出力:  

```
{
    "FlowArn": "arn:aws:mediaconnect:us-east-1:111122223333:flow:1-23aBC45dEF67hiJ8-12AbC34DE5fG:AwardsShow",
    "Source": {
        "IngestIp": "34.210.136.56",
        "WhitelistCidr": "10.24.34.0/23",
        "Transport": {
            "Protocol": "rtp-fec"
        },
        "IngestPort": 3344,
        "Name": "ShowSource",
        "Description": "Friday night show",
        "SourceArn": "arn:aws:mediaconnect:us-east-1:111122223333:source:3-4aBC56dEF78hiJ90-4de5fG6Hi78Jk:ShowSource"
    }
}
```
詳細については、「*AWS Elemental MediaConnect User Guide*」の「[Updating the Source of a Flow](https://docs.aws.amazon.com/mediaconnect/latest/ug/source-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFlowSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconnect/update-flow-source.html)」を参照してください。

# を使用した MediaConvert の例 AWS CLI
<a name="cli_2_mediaconvert_code_examples"></a>

次のコード例は、MediaConvert AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `cancel-job`
<a name="mediaconvert_CancelJob_cli_2_topic"></a>

次のコード例は、`cancel-job` を使用する方法を示しています。

**AWS CLI**  
**キューにあるジョブをキャンセルするには**  
次の `cancel-job` の例では、ID `1234567891234-abc123` のジョブをキャンセルします。サービスが処理を開始したジョブはキャンセルできません。  

```
aws mediaconvert cancel-job \
    --endpoint-url https://abcd1234.mediaconvert.region-name-1.amazonaws.com \
    --region region-name-1 \
    --id 1234567891234-abc123
```
アカウント固有のエンドポイントを取得するには、`describe-endpoints` を使用するか、エンドポイントを指定せずにコマンドを送信します。このサービスは、エラーとエンドポイントを返します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Jobs](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-jobs.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/cancel-job.html)」を参照してください。

### `create-job-template`
<a name="mediaconvert_CreateJobTemplate_cli_2_topic"></a>

次のコード例は、`create-job-template` を使用する方法を示しています。

**AWS CLI**  
**ジョブテンプレートを作成するには**  
次の `create-job-template` の例では、システムにあるファイル `job-template.json` に指定されているトランスコーディング設定を使用してジョブテンプレートを作成します。  

```
aws mediaconvert create-job-template \
    --endpoint-url https://abcd1234.mediaconvert.region-name-1.amazonaws.com \
    --region region-name-1 \
    --name JobTemplate1 \
    --cli-input-json file://~/job-template.json
```
`get-job-template` を使用してジョブテンプレートの JSON ファイルを作成し、ファイルを変更した場合、`JobTemplate` オブジェクトを削除しますが、設定の子オブジェクトはその中に保持します。また、`LastUpdated`、`Arn`、`Type`、および `CreatedAt` のキーと値のペアも必ず削除してください。カテゴリ、説明、名前、およびキューは、JSON ファイルまたはコマンドラインで指定できます。  
アカウント固有のエンドポイントを取得するには、`describe-endpoints` を使用するか、エンドポイントを指定せずにコマンドを送信します。このサービスは、エラーとエンドポイントを返します。  
リクエストが正常に処理されると、サービスは作成したジョブテンプレートの JSON 仕様を返します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Job Templates](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-job-templates.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateJobTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/create-job-template.html)」を参照してください。

### `create-job`
<a name="mediaconvert_CreateJob_cli_2_topic"></a>

次のコード例は、`create-job` を使用する方法を示しています。

**AWS CLI**  
**ジョブを作成するには**  
次の `create-job` の例では、コマンドの送信元となるシステム上のファイル `job.json` に指定されている設定を使用してトランスコーディングジョブを作成します。この JSON ジョブ仕様では、各設定を個別に指定したり、ジョブテンプレートを参照したり、出力プリセットを参照したりできます。  

```
aws mediaconvert create-job \
    --endpoint-url https://abcd1234.mediaconvert.region-name-1.amazonaws.com \
    --region region-name-1 \
    --cli-input-json file://~/job.json
```
 AWS Elemental MediaConvert コンソールを使用して JSON ジョブ仕様を生成するには、ジョブ設定を選択し、ジョブ****セクションの下部にある**ジョブ JSON **の表示を選択します。  
アカウント固有のエンドポイントを取得するには、`describe-endpoints` を使用するか、エンドポイントを指定せずにコマンドを送信します。このサービスは、エラーとエンドポイントを返します。  
リクエストが正常に処理されると、サービスはリクエストとともに送信した JSON ジョブ仕様を返します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Jobs](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-jobs.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[CreateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/create-job.html)」を参照してください。

### `create-preset`
<a name="mediaconvert_CreatePreset_cli_2_topic"></a>

次のコード例は、`create-preset` を使用する方法を示しています。

**AWS CLI**  
**カスタム出力プリセットを作成するには**  
次の `create-preset` の例では、ファイル `preset.json` で指定された出力設定に基づいてカスタム出力プリセットを作成します。カテゴリ、説明、および名前は、JSON ファイルまたはコマンドラインで指定できます。  

```
aws mediaconvert create-preset \
    --endpoint-url https://abcd1234.mediaconvert.region-name-1.amazonaws.com
    --region region-name-1 \
    --cli-input-json file://~/preset.json
```
`get-preset` を使用してプリセット JSON ファイルを作成し、出力ファイルを変更する場合は、`LastUpdated`、`Arn`、`Type` および `CreatedAt` のキーと値のペアを必ず削除してください。  
アカウント固有のエンドポイントを取得するには、`describe-endpoints` を使用するか、エンドポイントを指定せずにコマンドを送信します。このサービスは、エラーとエンドポイントを返します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Output Presets](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-presets.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePreset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/create-preset.html)」を参照してください。

### `create-queue`
<a name="mediaconvert_CreateQueue_cli_2_topic"></a>

次のコード例は、`create-queue` を使用する方法を示しています。

**AWS CLI**  
**カスタムキューを作成するには**  
次の `create-queue` の例では、カスタムトランスコーディングキューを作成します。  

```
aws mediaconvert create-queue \
    --endpoint-url https://abcd1234.mediaconvert.region-name-1.amazonaws.com \
    --region region-name-1 \
    --name Queue1 \
    --description "Keep this queue empty unless job is urgent."
```
アカウント固有のエンドポイントを取得するには、`describe-endpoints` を使用するか、エンドポイントを指定せずにコマンドを送信します。このサービスは、エラーとエンドポイントを返します。  
出力:  

```
{
    "Queue": {
        "Status": "ACTIVE",
        "Name": "Queue1",
        "LastUpdated": 1518034928,
        "Arn": "arn:aws:mediaconvert:region-name-1:012345678998:queues/Queue1",
        "Type": "CUSTOM",
        "CreatedAt": 1518034928,
        "Description": "Keep this queue empty unless job is urgent."
    }
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Queues](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-queues.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/create-queue.html)」を参照してください。**

### `delete-job-template`
<a name="mediaconvert_DeleteJobTemplate_cli_2_topic"></a>

次のコード例は、`delete-job-template` を使用する方法を示しています。

**AWS CLI**  
**ジョブテンプレートを削除するには**  
次の `delete-job-template` の例では、指定されたカスタムジョブテンプレートを削除します。  

```
aws mediaconvert delete-job-template \
    --name "DASH Streaming" \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
このコマンドは何も出力しません。`aws mediaconvert list-job-templates` を実行して、テンプレートが削除されたことを確認します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Job Templates](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-job-templates.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteJobTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/delete-job-template.html)」を参照してください。

### `delete-preset`
<a name="mediaconvert_DeletePreset_cli_2_topic"></a>

次のコード例は、`delete-preset` を使用する方法を示しています。

**AWS CLI**  
**カスタムオンデマンドキューを削除するには**  
次の `delete-preset` の例では、指定されたカスタムプリセットを削除します。  

```
aws mediaconvert delete-preset \
    --name SimpleMP4 \
    --endpoint-url  https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
このコマンドは何も出力しません。`aws mediaconvert list-presets` を実行して、プリセットが削除されたことを確認します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Output Presets](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-presets.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePreset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/delete-preset.html)」を参照してください。

### `delete-queue`
<a name="mediaconvert_DeleteQueue_cli_2_topic"></a>

次のコード例は、`delete-queue` を使用する方法を示しています。

**AWS CLI**  
**カスタムオンデマンドキューを削除するには**  
次の `delete-queue` の例では、指定されたカスタムオンデマンドキューを削除します。  
デフォルトのキューを削除することはできません。有効な料金プランがある、または未処理のジョブを含む予約済みのキューを削除することはできません。  

```
aws mediaconvert delete-queue \
    --name Customer1 \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
このコマンドは何も出力しません。`aws mediaconvert list-queues` を実行して、キューが削除されたことを確認します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Queues](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-queues.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[DeleteQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/delete-queue.html)」を参照してください。

### `describe-endpoints`
<a name="mediaconvert_DescribeEndpoints_cli_2_topic"></a>

次のコード例は、`describe-endpoints` を使用する方法を示しています。

**AWS CLI**  
**アカウント固有のエンドポイントを取得するには**  
次の `describe-endpoints` の例では、他のリクエストをサービスに送信する必要があるエンドポイントを取得します。  

```
aws mediaconvert describe-endpoints
```
出力:  

```
{
    "Endpoints": [
        {
            "Url": "https://abcd1234.mediaconvert.region-name-1.amazonaws.com"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaConvert API Reference*」の「[Getting Started with MediaConvert Using the API](https://docs.aws.amazon.com/mediaconvert/latest/apireference/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/describe-endpoints.html)」を参照してください。

### `get-job-template`
<a name="mediaconvert_GetJobTemplate_cli_2_topic"></a>

次のコード例は、`get-job-template` を使用する方法を示しています。

**AWS CLI**  
**ジョブテンプレートの詳細を取得するには**  
次の `get-job-template` の例では、指定されたカスタムジョブテンプレートの JSON 定義を表示します。  

```
aws mediaconvert get-job-template \
    --name "DASH Streaming" \
    --endpoint-url https://abcd1234.mediaconvert.us-east-1.amazonaws.com
```
出力:  

```
{
    "JobTemplate": {
        "StatusUpdateInterval": "SECONDS_60",
        "LastUpdated": 1568652998,
        "Description": "Create a DASH streaming ABR stack",
        "CreatedAt": 1568652998,
        "Priority": 0,
        "Name": "DASH Streaming",
        "Settings": {
            ...<truncatedforbrevity>...
        },
        "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:jobTemplates/DASH Streaming",
        "Type": "CUSTOM"
    }
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Job Templates](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-job-templates.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetJobTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/get-job-template.html)」を参照してください。

### `get-job`
<a name="mediaconvert_GetJob_cli_2_topic"></a>

次のコード例は、`get-job` を使用する方法を示しています。

**AWS CLI**  
**特定のジョブの詳細を取得するには**  
次の例は、ID `1234567890987-1ab2c3` のジョブの情報をリクエストしていますが、エラーで終了します。  

```
aws mediaconvert get-job \
    --endpoint-url https://abcd1234.mediaconvert.region-name-1.amazonaws.com \
    --region region-name-1 \
    --id 1234567890987-1ab2c3
```
アカウント固有のエンドポイントを取得するには、`describe-endpoints` を使用するか、エンドポイントを指定せずにコマンドを送信します。このサービスは、エラーとエンドポイントを返します。  
リクエストが正常に処理されると、サービスは次のようなジョブ設定、返されたエラー、その他のジョブデータなどのジョブ情報を含む JSON ファイルを返します。  

```
{
    "Job": {
        "Status": "ERROR",
        "Queue": "arn:aws:mediaconvert:region-name-1:012345678998:queues/Queue1",
        "Settings": {
            ...<truncated for brevity>...
        },
        "ErrorMessage": "Unable to open input file [s3://my-input-bucket/file-name.mp4]: [Failed probe/open: [Failed to read data: AssumeRole failed]]",
        "ErrorCode": 1434,
        "Role": "arn:aws:iam::012345678998:role/MediaConvertServiceRole",
        "Arn": "arn:aws:mediaconvert:us-west-1:012345678998:jobs/1234567890987-1ab2c3",
        "UserMetadata": {},
        "Timing": {
            "FinishTime": 1517442131,
            "SubmitTime": 1517442103,
            "StartTime": 1517442104
        },
        "Id": "1234567890987-1ab2c3",
        "CreatedAt": 1517442103
    }
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Jobs](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-jobs.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[GetJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/get-job.html)」を参照してください。

### `get-preset`
<a name="mediaconvert_GetPreset_cli_2_topic"></a>

次のコード例は、`get-preset` を使用する方法を示しています。

**AWS CLI**  
**特定のプリセットの詳細を取得するには**  
次の `get-preset` の例では、指定されたカスタムプリセットの JSON 定義をリクエストします。  

```
aws mediaconvert get-preset \
    --name SimpleMP4 \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "Preset": {
        "Description": "Creates basic MP4 file. No filtering or preproccessing.",
        "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:presets/SimpleMP4",
        "LastUpdated": 1568843141,
        "Name": "SimpleMP4",
        "Settings": {
            "ContainerSettings": {
                "Mp4Settings": {
                    "FreeSpaceBox": "EXCLUDE",
                    "CslgAtom": "INCLUDE",
                    "MoovPlacement": "PROGRESSIVE_DOWNLOAD"
                },
                "Container": "MP4"
            },
            "AudioDescriptions": [
                {
                    "LanguageCodeControl": "FOLLOW_INPUT",
                    "AudioTypeControl": "FOLLOW_INPUT",
                    "CodecSettings": {
                        "AacSettings": {
                            "RawFormat": "NONE",
                            "CodecProfile": "LC",
                            "AudioDescriptionBroadcasterMix": "NORMAL",
                            "SampleRate": 48000,
                            "Bitrate": 96000,
                            "RateControlMode": "CBR",
                            "Specification": "MPEG4",
                            "CodingMode": "CODING_MODE_2_0"
                        },
                        "Codec": "AAC"
                    }
                }
            ],
            "VideoDescription": {
                "RespondToAfd": "NONE",
                "TimecodeInsertion": "DISABLED",
                "Sharpness": 50,
                "ColorMetadata": "INSERT",
                "CodecSettings": {
                    "H264Settings": {
                        "FramerateControl": "INITIALIZE_FROM_SOURCE",
                        "SpatialAdaptiveQuantization": "ENABLED",
                        "Softness": 0,
                        "Telecine": "NONE",
                        "CodecLevel": "AUTO",
                        "QualityTuningLevel": "SINGLE_PASS",
                        "UnregisteredSeiTimecode": "DISABLED",
                        "Slices": 1,
                        "Syntax": "DEFAULT",
                        "GopClosedCadence": 1,
                        "AdaptiveQuantization": "HIGH",
                        "EntropyEncoding": "CABAC",
                        "InterlaceMode": "PROGRESSIVE",
                        "ParControl": "INITIALIZE_FROM_SOURCE",
                        "NumberBFramesBetweenReferenceFrames": 2,
                        "GopSizeUnits": "FRAMES",
                        "RepeatPps": "DISABLED",
                        "CodecProfile": "MAIN",
                        "FieldEncoding": "PAFF",
                        "GopSize": 90.0,
                        "SlowPal": "DISABLED",
                        "SceneChangeDetect": "ENABLED",
                        "GopBReference": "DISABLED",
                        "RateControlMode": "CBR",
                        "FramerateConversionAlgorithm": "DUPLICATE_DROP",
                        "FlickerAdaptiveQuantization": "DISABLED",
                        "DynamicSubGop": "STATIC",
                        "MinIInterval": 0,
                        "TemporalAdaptiveQuantization": "ENABLED",
                        "Bitrate": 400000,
                        "NumberReferenceFrames": 3
                    },
                    "Codec": "H_264"
                },
                "AfdSignaling": "NONE",
                "AntiAlias": "ENABLED",
                "ScalingBehavior": "DEFAULT",
                "DropFrameTimecode": "ENABLED"
            }
        },
        "Type": "CUSTOM",
        "CreatedAt": 1568841521
    }
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Output Presets](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-presets.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPreset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/get-preset.html)」を参照してください。

### `get-queue`
<a name="mediaconvert_GetQueue_cli_2_topic"></a>

次のコード例は、`get-queue` を使用する方法を示しています。

**AWS CLI**  
**キューの詳細を取得するには**  
次の `get-queue` の例では、指定されたカスタムキューの詳細を取得します。  

```
aws mediaconvert get-queue \
    --name Customer1 \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "Queue": {
        "LastUpdated": 1526428502,
        "Type": "CUSTOM",
        "SubmittedJobsCount": 0,
        "Status": "ACTIVE",
        "PricingPlan": "ON_DEMAND",
        "CreatedAt": 1526428502,
        "ProgressingJobsCount": 0,
        "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:queues/Customer1",
        "Name": "Customer1"
    }
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Queues](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-queues.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/get-queue.html)」を参照してください。

### `list-job-templates`
<a name="mediaconvert_ListJobTemplates_cli_2_topic"></a>

次のコード例は、`list-job-templates` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムジョブテンプレートを一覧表示するには**  
次の `list-job-templates` の例では、現在のリージョンのすべてのカスタムジョブテンプレートを一覧表示します。システムジョブテンプレートを一覧表示するには、次の例を参照してください。  

```
aws mediaconvert list-job-templates \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "JobTemplates": [
        {
            "Description": "Create a DASH streaming ABR stack",
            "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:jobTemplates/DASH Streaming",
            "Name": "DASH Streaming",
            "LastUpdated": 1568653007,
            "Priority": 0,
            "Settings": {
                ...<truncatedforbrevity>...
            },
            "Type": "CUSTOM",
            "StatusUpdateInterval": "SECONDS_60",
            "CreatedAt": 1568653007
        },
        {
            "Description": "Create a high-res file",
            "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:jobTemplates/File",
            "Name": "File",
            "LastUpdated": 1568653007,
            "Priority": 0,
            "Settings": {
                ...<truncatedforbrevity>...
            },
            "Type": "CUSTOM",
            "StatusUpdateInterval": "SECONDS_60",
            "CreatedAt": 1568653023
        }
    ]
}
```
**例 2: MediaConvert システムジョブテンプレートを一覧表示するには**  
次の `list-job-templates` の例では、すべてのシステムジョブテンプレートを一覧表示します。  

```
aws mediaconvert list-job-templates \
    --endpoint-url https://abcd1234.mediaconvert.us-east-1.amazonaws.com \
    --list-by SYSTEM
```
出力:  

```
{
    "JobTemplates": [
        {
            "CreatedAt": 1568321779,
            "Arn": "arn:aws:mediaconvert:us-east-1:123456789012:jobTemplates/System-Generic_Mp4_Hev1_Avc_Aac_Sdr_Qvbr",
            "Name": "System-Generic_Mp4_Hev1_Avc_Aac_Sdr_Qvbr",
            "Description": "GENERIC, MP4, AVC + HEV1(HEVC,SDR), AAC, SDR, QVBR",
            "Category": "GENERIC",
            "Settings": {
                "AdAvailOffset": 0,
                "OutputGroups": [
                    {
                        "Outputs": [
                            {
                                "Extension": "mp4",
                                "Preset": "System-Generic_Hd_Mp4_Avc_Aac_16x9_Sdr_1280x720p_30Hz_5Mbps_Qvbr_Vq9",
                                "NameModifier": "_Generic_Hd_Mp4_Avc_Aac_16x9_Sdr_1280x720p_30Hz_5000Kbps_Qvbr_Vq9"
                            },
                            {
                                "Extension": "mp4",
                                "Preset": "System-Generic_Hd_Mp4_Avc_Aac_16x9_Sdr_1920x1080p_30Hz_10Mbps_Qvbr_Vq9",
                                "NameModifier": "_Generic_Hd_Mp4_Avc_Aac_16x9_Sdr_1920x1080p_30Hz_10000Kbps_Qvbr_Vq9"
                            },
                            {
                                "Extension": "mp4",
                                "Preset": "System-Generic_Sd_Mp4_Avc_Aac_16x9_Sdr_640x360p_30Hz_0.8Mbps_Qvbr_Vq7",
                                "NameModifier": "_Generic_Sd_Mp4_Avc_Aac_16x9_Sdr_640x360p_30Hz_800Kbps_Qvbr_Vq7"
                            },
                            {
                                "Extension": "mp4",
                                "Preset": "System-Generic_Hd_Mp4_Hev1_Aac_16x9_Sdr_1280x720p_30Hz_4Mbps_Qvbr_Vq9",
                                "NameModifier": "_Generic_Hd_Mp4_Hev1_Aac_16x9_Sdr_1280x720p_30Hz_4000Kbps_Qvbr_Vq9"
                            },
                            {
                                "Extension": "mp4",
                                "Preset": "System-Generic_Hd_Mp4_Hev1_Aac_16x9_Sdr_1920x1080p_30Hz_8Mbps_Qvbr_Vq9",
                                "NameModifier": "_Generic_Hd_Mp4_Hev1_Aac_16x9_Sdr_1920x1080p_30Hz_8000Kbps_Qvbr_Vq9"
                            },
                            {
                                "Extension": "mp4",
                                "Preset": "System-Generic_Uhd_Mp4_Hev1_Aac_16x9_Sdr_3840x2160p_30Hz_12Mbps_Qvbr_Vq9",
                                "NameModifier": "_Generic_Uhd_Mp4_Hev1_Aac_16x9_Sdr_3840x2160p_30Hz_12000Kbps_Qvbr_Vq9"
                            }
                        ],
                        "OutputGroupSettings": {
                            "FileGroupSettings": {

                            },
                            "Type": "FILE_GROUP_SETTINGS"
                        },
                        "Name": "File Group"
                    }
                ]
            },
            "Type": "SYSTEM",
            "LastUpdated": 1568321779
        },
        ...<truncatedforbrevity>...
    ]
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Job Templates](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-job-templates.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/list-job-templates.html)」を参照してください。

### `list-jobs`
<a name="mediaconvert_ListJobs_cli_2_topic"></a>

次のコード例は、`list-jobs` を使用する方法を示しています。

**AWS CLI**  
**リージョン内のすべてのジョブの詳細を取得するには**  
次の例は、指定されたリージョンのすべてのジョブの情報をリクエストします。  

```
aws mediaconvert list-jobs \
    --endpoint-url https://abcd1234.mediaconvert.region-name-1.amazonaws.com \
    --region region-name-1
```
アカウント固有のエンドポイントを取得するには、`describe-endpoints` を使用するか、エンドポイントを指定せずにコマンドを送信します。このサービスは、エラーとエンドポイントを返します。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Jobs](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-jobs.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/list-jobs.html)」を参照してください。

### `list-presets`
<a name="mediaconvert_ListPresets_cli_2_topic"></a>

次のコード例は、`list-presets` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタム出力プリセットを一覧表示するには**  
次の `list-presets` の例では、カスタム出力プリセットを一覧表示します。システムプリセットを一覧表示するには、次の例を参照してください。  

```
aws mediaconvert list-presets \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "Presets": [
        {
            "Name": "SimpleMP4",
            "CreatedAt": 1568841521,
            "Settings": {
                ......
            },
            "Arn": "arn:aws:mediaconvert:us-east-1:003235472598:presets/SimpleMP4",
            "Type": "CUSTOM",
            "LastUpdated": 1568843141,
            "Description": "Creates basic MP4 file. No filtering or preproccessing."
        },
        {
            "Name": "SimpleTS",
            "CreatedAt": 1568843113,
            "Settings": {
                ... truncated for brevity ...
            },
            "Arn": "arn:aws:mediaconvert:us-east-1:003235472598:presets/SimpleTS",
            "Type": "CUSTOM",
            "LastUpdated": 1568843113,
            "Description": "Create a basic transport stream."
        }
    ]
}
```
**例 2: システム出力プリセットを一覧表示するには**  
次の `list-presets` の例では、使用可能な MediaConvert システムプリセットを一覧表示します。カスタムプリセットを一覧表示するには、前の例を参照してください。  

```
aws mediaconvert list-presets \
    --list-by SYSTEM \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "Presets": [
        {
            "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:presets/System-Avc_16x9_1080p_29_97fps_8500kbps",
            "Name": "System-Avc_16x9_1080p_29_97fps_8500kbps",
            "CreatedAt": 1568321789,
            "Description": "Wifi, 1920x1080, 16:9, 29.97fps, 8500kbps",
            "LastUpdated": 1568321789,
            "Type": "SYSTEM",
            "Category": "HLS",
            "Settings": {
            ...<output settings removed for brevity>...
            }
        },

        ...<list of presets shortened for brevity>...

        {
            "Arn": "arn:aws:mediaconvert:us-east-1:123456789012:presets/System-Xdcam_HD_1080i_29_97fps_35mpbs",
            "Name": "System-Xdcam_HD_1080i_29_97fps_35mpbs",
            "CreatedAt": 1568321790,
            "Description": "XDCAM MPEG HD, 1920x1080i, 29.97fps, 35mbps",
            "LastUpdated": 1568321790,
            "Type": "SYSTEM",
            "Category": "MXF",
            "Settings": {
            ...<output settings removed for brevity>...
            }
        }
    ]
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Output Presets](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-presets.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPresets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/list-presets.html)」を参照してください。

### `list-queues`
<a name="mediaconvert_ListQueues_cli_2_topic"></a>

次のコード例は、`list-queues` を使用する方法を示しています。

**AWS CLI**  
**キューを一覧表示するには**  
次の `list-queues` の例では、すべての MediaConvert キューを一覧表示します。  

```
aws mediaconvert list-queues \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "Queues": [
        {
            "PricingPlan": "ON_DEMAND",
            "Type": "SYSTEM",
            "Status": "ACTIVE",
            "CreatedAt": 1503451595,
            "Name": "Default",
            "SubmittedJobsCount": 0,
            "ProgressingJobsCount": 0,
            "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:queues/Default",
            "LastUpdated": 1534549158
        },
        {
            "PricingPlan": "ON_DEMAND",
            "Type": "CUSTOM",
            "Status": "ACTIVE",
            "CreatedAt": 1537460025,
            "Name": "Customer1",
            "SubmittedJobsCount": 0,
            "Description": "Jobs we run for our cusotmer.",
            "ProgressingJobsCount": 0,
            "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:queues/Customer1",
            "LastUpdated": 1537460025
        },
        {
            "ProgressingJobsCount": 0,
            "Status": "ACTIVE",
            "Name": "transcode-library",
            "SubmittedJobsCount": 0,
            "LastUpdated": 1564066204,
            "ReservationPlan": {
                "Status": "ACTIVE",
                "ReservedSlots": 1,
                "PurchasedAt": 1564066203,
                "Commitment": "ONE_YEAR",
                "ExpiresAt": 1595688603,
                "RenewalType": "EXPIRE"
            },
            "PricingPlan": "RESERVED",
            "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:queues/transcode-library",
            "Type": "CUSTOM",
            "CreatedAt": 1564066204
        }
    ]
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Queues](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-queues.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListQueues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/list-queues.html)」を参照してください。**

### `list-tags-for-resource`
<a name="mediaconvert_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**MediaConvert キュー、ジョブテンプレート、または出力プリセットのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された出力プリセットのタグを一覧表示します。  

```
aws mediaconvert list-tags-for-resource \
    --arn arn:aws:mediaconvert:us-west-2:123456789012:presets/SimpleMP4 \
    --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "ResourceTags": {
        "Tags": {
            "customer": "zippyVideo"
        },
        "Arn": "arn:aws:mediaconvert:us-west-2:123456789012:presets/SimpleMP4"
    }
}
```
詳細については、「 [Elemental MediaConvert AWS ユーザーガイド」の「Elemental MediaConvert キュー、ジョブテンプレート、出力プリセットのタグ付け](https://docs.aws.amazon.com/mediaconvert/latest/ug/tagging-queues-templates-presets.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/list-tags-for-resource.html)」を参照してください。

### `update-job-template`
<a name="mediaconvert_UpdateJobTemplate_cli_2_topic"></a>

次のコード例は、`update-job-template` を使用する方法を示しています。

**AWS CLI**  
**ジョブテンプレートを変更するには**  
次の `update-job-template` の例では、指定されたカスタムジョブテンプレートの JSON 定義を、指定されたファイルの JSON 定義に置き換えます。  
aws mediaconvert update-job-template --name File1 --endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com --cli-input-json file://\$1/job-template-update.json  
`job-template-update.json` の内容:  

```
{
    "Description": "A simple job template that generates a single file output.",
    "Queue": "arn:aws:mediaconvert:us-east-1:012345678998:queues/Default",
    "Name": "SimpleFile",
    "Settings": {
      "OutputGroups": [
        {
          "Name": "File Group",
          "Outputs": [
            {
              "ContainerSettings": {
                "Container": "MP4",
                "Mp4Settings": {
                  "CslgAtom": "INCLUDE",
                  "FreeSpaceBox": "EXCLUDE",
                  "MoovPlacement": "PROGRESSIVE_DOWNLOAD"
                }
              },
              "VideoDescription": {
                "ScalingBehavior": "DEFAULT",
                "TimecodeInsertion": "DISABLED",
                "AntiAlias": "ENABLED",
                "Sharpness": 50,
                "CodecSettings": {
                  "Codec": "H_264",
                  "H264Settings": {
                    "InterlaceMode": "PROGRESSIVE",
                    "NumberReferenceFrames": 3,
                    "Syntax": "DEFAULT",
                    "Softness": 0,
                    "GopClosedCadence": 1,
                    "GopSize": 90,
                    "Slices": 1,
                    "GopBReference": "DISABLED",
                    "SlowPal": "DISABLED",
                    "SpatialAdaptiveQuantization": "ENABLED",
                    "TemporalAdaptiveQuantization": "ENABLED",
                    "FlickerAdaptiveQuantization": "DISABLED",
                    "EntropyEncoding": "CABAC",
                    "Bitrate": 400000,
                    "FramerateControl": "INITIALIZE_FROM_SOURCE",
                    "RateControlMode": "CBR",
                    "CodecProfile": "MAIN",
                    "Telecine": "NONE",
                    "MinIInterval": 0,
                    "AdaptiveQuantization": "HIGH",
                    "CodecLevel": "AUTO",
                    "FieldEncoding": "PAFF",
                    "SceneChangeDetect": "ENABLED",
                    "QualityTuningLevel": "SINGLE_PASS",
                    "FramerateConversionAlgorithm": "DUPLICATE_DROP",
                    "UnregisteredSeiTimecode": "DISABLED",
                    "GopSizeUnits": "FRAMES",
                    "ParControl": "INITIALIZE_FROM_SOURCE",
                    "NumberBFramesBetweenReferenceFrames": 2,
                    "RepeatPps": "DISABLED",
                    "DynamicSubGop": "STATIC"
                  }
                },
                "AfdSignaling": "NONE",
                "DropFrameTimecode": "ENABLED",
                "RespondToAfd": "NONE",
                "ColorMetadata": "INSERT"
              },
              "AudioDescriptions": [
                {
                  "AudioTypeControl": "FOLLOW_INPUT",
                  "CodecSettings": {
                    "Codec": "AAC",
                    "AacSettings": {
                      "AudioDescriptionBroadcasterMix": "NORMAL",
                      "Bitrate": 96000,
                      "RateControlMode": "CBR",
                      "CodecProfile": "LC",
                      "CodingMode": "CODING_MODE_2_0",
                      "RawFormat": "NONE",
                      "SampleRate": 48000,
                      "Specification": "MPEG4"
                    }
                  },
                  "LanguageCodeControl": "FOLLOW_INPUT"
                }
              ]
            }
          ],
          "OutputGroupSettings": {
            "Type": "FILE_GROUP_SETTINGS",
            "FileGroupSettings": {}
          }
        }
      ],
      "AdAvailOffset": 0
    },
    "StatusUpdateInterval": "SECONDS_60",
    "Priority": 0
}
```
リクエストでエラーが発生した場合でも、システムはリクエストで送信した JSON ペイロードを返します。したがって、返される JSON は必ずしもジョブテンプレートの新しい定義ではありません。  
JSON ペイロードが長くなる可能性があるため、上にスクロールしてエラーメッセージを表示しなければならない場合があります。  
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Job Templates](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-job-templates.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateJobTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/update-job-template.html)」を参照してください。

### `update-preset`
<a name="mediaconvert_UpdatePreset_cli_2_topic"></a>

次のコード例は、`update-preset` を使用する方法を示しています。

**AWS CLI**  
**プリセットを変更するには**  
次の `update-preset` の例では、指定されたプリセットの説明を置き換えます。  

```
aws mediaconvert update-preset \
--name Customer1 \
--description "New description text."
--endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
このコマンドは何も出力しません。出力:  

```
{
    "Preset": {
        "Arn": "arn:aws:mediaconvert:us-east-1:003235472598:presets/SimpleMP4",
        "Settings": {
        ...<output settings removed for brevity>...
        },
        "Type": "CUSTOM",
        "LastUpdated": 1568938411,
        "Description": "New description text.",
        "Name": "SimpleMP4",
        "CreatedAt": 1568938240
    }
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Output Presets](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-presets.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePreset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/update-preset.html)」を参照してください。

### `update-queue`
<a name="mediaconvert_UpdateQueue_cli_2_topic"></a>

次のコード例は、`update-queue` を使用する方法を示しています。

**AWS CLI**  
**キューを変更するには**  
次の `update-queue` の例では、ステータスを `PAUSED` に変更することで、指定されたキューを一時停止します。  

```
aws mediaconvert update-queue \
--name Customer1 \
--status PAUSED
--endpoint-url https://abcd1234.mediaconvert.us-west-2.amazonaws.com
```
出力:  

```
{
    "Queue": {
        "LastUpdated": 1568839845,
        "Status": "PAUSED",
        "ProgressingJobsCount": 0,
        "CreatedAt": 1526428516,
        "Arn": "arn:aws:mediaconvert:us-west-1:123456789012:queues/Customer1",
        "Name": "Customer1",
        "SubmittedJobsCount": 0,
        "PricingPlan": "ON_DEMAND",
        "Type": "CUSTOM"
    }
}
```
詳細については、[AWS 「 Elemental MediaConvert ユーザーガイド」の「Working with Elemental MediaConvert Queues](https://docs.aws.amazon.com/mediaconvert/latest/ug/working-with-queues.html)」を参照してください。 *AWS MediaConvert *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediaconvert/update-queue.html)」を参照してください。

# を使用した MediaLive の例 AWS CLI
<a name="cli_2_medialive_code_examples"></a>

次のコード例は、MediaLive AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-channel`
<a name="medialive_CreateChannel_cli_2_topic"></a>

次のコード例は、`create-channel` を使用する方法を示しています。

**AWS CLI**  
**チャネルを作成するには**  
次の `create-channel` の例では、指定したいパラメータを含む JSON ファイルを渡すことでチャネルを作成します。  
この例のチャネルは、ビデオ、オーディオ、埋め込みキャプションを含むソースに接続する HLS PULL 入力を取り込みます。チャネルは、Akamai サーバーを送信先として 1 つの HLS 出力グループを作成します。出力グループには、H.265 ビデオと AAC オーディオ用の出力と、Web-VTT キャプション用の出力の 2 つの出力があります (英語のみ)。  
このサンプルチャネルの JSON には、HLS PULL 入力を使用し、Akamai を送信先とする HLS 出力グループを生成するチャネルに必要な最小パラメータが含まれています。JSON には、次の主要なセクションが含まれています。  
`InputAttachments`。オーディオのソースを 1 つ、キャプションのソースを 1 つ指定します。ビデオセレクタは指定しません。つまり、MediaLive はソースで見つけた最初のビデオを抽出します。`Destinations` には、このチャネル内の単一の出力グループの 2 つの IP アドレス (URL) が含まれます。これらのアドレスにはパスワードが必要です。`EncoderSettings` にはサブセクションが含まれています。`AudioDescriptions` は、チャネルに InputAttachments のソースを使用する 1 つのオーディオ出力アセットが含まれ、AAC 形式でオーディオを生成することを指定します。`CaptionDescriptions` は、チャネルに InputAttachments のソースを使用する 1 つのキャプション出力アセットが含まれ、Web-VTT 形式でキャプションを生成することを指定します。`VideoDescriptions` は、指定した解像度の 1 つのビデオ出力アセットが、チャネルに含まれていることを指定します。`OutputGroups` は、出力グループを指定します。この例では、`Akamai` という名前の 1 つのグループがあります。接続は HLS PUT を使用して行われます。出力グループには 2 つの出力が含まれます。1 つの出力は、ビデオアセット (`Video_high` という名前) とオーディオアセット (`Audio_EN` という名前) 用です。1 つの出力は、キャプションアセット (`WebVTT_EN` という名前) 用です。  
この例では、一部のパラメータに値が含まれないか、ネストされた空のパラメータが含まれています。例えば、`Video_and_audio` 出力の OutputSettings には、空のパラメータ M3u8Settings で終わるいくつかのネストされたパラメータが含まれています。このパラメータを含める必要がありますが、1 つ、複数、またはすべての子を省略できます。つまり、子はデフォルト値を使用するか null になります。  
このサンプルチャネルに適用されるが、このファイルで指定されていないすべてのパラメータは、デフォルト値を使用するか、null に設定されるか、MediaLive によって生成された一意の値を取得します。  

```
aws medialive create-channel \
    --cli-input-json file://channel-in-hls-out-hls-akamai.json
```
`channel-in-hls-out-hls-akamai.json` の内容:  

```
{
    "Name": "News_West",
    "RoleArn": "arn:aws:iam::111122223333:role/MediaLiveAccessRole",
    "InputAttachments": [
        {
            "InputAttachmentName": "local_news",
            "InputId": "1234567",
            "InputSettings": {
                "AudioSelectors": [
                    {
                        "Name": "English-Audio",
                        "SelectorSettings": {
                            "AudioLanguageSelection": {
                                "LanguageCode": "EN"
                            }
                        }
                    }
                ],
                "CaptionSelectors": [
                    {
                        "LanguageCode": "ENE",
                        "Name": "English_embedded"
                    }
                ]
            }
        }
    ],
    "Destinations": [
        {
            "Id": "akamai-server-west",
            "Settings": [
                {
                    "PasswordParam": "/medialive/examplecorp1",
                    "Url": "http://203.0.113.55/news/news_west",
                    "Username": "examplecorp"
                },
                {
                    "PasswordParam": "/medialive/examplecorp2",
                    "Url": "http://203.0.113.82/news/news_west",
                    "Username": "examplecorp"
                }
            ]
        }
    ],
    "EncoderSettings": {
        "AudioDescriptions": [
            {
                "AudioSelectorName": "English-Audio",
                "CodecSettings": {
                    "AacSettings": {}
                },
                "Name": "Audio_EN"
            }
        ],
        "CaptionDescriptions": [
            {
                "CaptionSelectorName": "English_embedded",
                "DestinationSettings": {
                    "WebvttDestinationSettings": {}
                },
                "Name": "WebVTT_EN"
            }
        ],
        "VideoDescriptions": [
            {
                "Height": 720,
                "Name": "Video_high",
                "Width": 1280
            }
        ],
        "OutputGroups": [
            {
                "Name": "Akamai",
                "OutputGroupSettings": {
                    "HlsGroupSettings": {
                        "Destination": {
                            "DestinationRefId": "akamai-server-west"
                        },
                        "HlsCdnSettings": {
                            "HlsBasicPutSettings": {}
                        }
                    }
                },
                "Outputs": [
                    {
                        "AudioDescriptionNames": [
                            "Audio_EN"
                        ],
                        "OutputName": "Video_and_audio",
                        "OutputSettings": {
                            "HlsOutputSettings": {
                                "HlsSettings": {
                                    "StandardHlsSettings": {
                                        "M3u8Settings": {}
                                    }
                                },
                                "NameModifier": "_1"
                            }
                        },
                        "VideoDescriptionName": "Video_high"
                    },
                    {
                        "CaptionDescriptionNames": [
                            "WebVTT_EN"
                        ],
                        "OutputName": "Captions-WebVTT",
                        "OutputSettings": {
                            "HlsOutputSettings": {
                                "HlsSettings": {
                                    "StandardHlsSettings": {
                                        "M3u8Settings": {}
                                    }
                                },
                                "NameModifier": "_2"
                            }
                        }
                    }
                ]
            }
        ],
        "TimecodeConfig": {
            "Source": "EMBEDDED"
        }
    }
}
```
**出力:**  
出力は、JSON ファイルの内容と次の値を反復して返します。すべてのパラメータはアルファベット順に並べられます。  
チャネルの `ARN`。ARN の最後の部分は一意のチャネル ID です。`EgressEndpoints` は PUSH 入力にのみ使用されるため、このサンプルチャネルでは空白です。適用すると、コンテンツがプッシュされる MediaLive のアドレスが表示されます。`OutputGroups`、`Outputs`。これらは、含めなかったけれどもこのチャネルに関連するものなど、出力グループと出力のすべてのパラメータを表示します。パラメータは空であるか (おそらく、このチャネル設定でパラメータまたは機能が無効化されていることを示す)、適用されるデフォルト値を示す場合があります。`LogLevel` はデフォルト (DISABLED) に設定されます。`Tags` はデフォルト (null) に設定されます。`PipelinesRunningCount` および `State` はチャネルの現在のステータスを表示します。  
詳細については、「*AWS Elemental MediaLive User Guide*」の「[Creating a Channel from Scratch](https://docs.aws.amazon.com/medialive/latest/ug/creating-channel-scratch.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/create-channel.html)」を参照してください。

### `create-input`
<a name="medialive_CreateInput_cli_2_topic"></a>

次のコード例は、`create-input` を使用する方法を示しています。

**AWS CLI**  
**入力を作成するには**  
次の `create-input` の例では、このタイプの入力に適用されるパラメータを含む JSON ファイルで渡して `HLS PULL` 入力を作成します。この入力例の JSON は、取り込みの冗長性をサポートするために、入力への 2 つのソース (アドレス) を指定します。これらのアドレスにはパスワードが必要です。  

```
aws medialive create-input \
    --cli-input-json file://input-hls-pull-news.json
```
`input-hls-pull-news.json` の内容:  

```
{
    "Name": "local_news",
    "RequestId": "cli000059",
    "Sources": [
            {
                    "Url": "https://203.0.113.13/newschannel/anytownusa.m3u8",
                    "Username": "examplecorp",
                    "PasswordParam": "/medialive/examplecorp1"
            },
       {
                    "Url": "https://198.51.100.54/fillervideos/oceanwaves.mp4",
                    "Username": "examplecorp",
                    "PasswordParam": "examplecorp2"
            }
    ],
    "Type": "URL_PULL"
}
```
**出力:**  
出力は、JSON ファイルの内容と次の値を反復して返します。すべてのパラメータはアルファベット順に並べられます。  
入力の `Arn`。ARN の最後の部分は一意の入力 ID です。`Attached Channels` は、新しく作成された入力では常に空です。`Destinations` は、PUSH 入力でのみ使用されるためにこの例では空です。`Id` は、入力用で ARN の ID と同じです。`MediaConnectFlows` は、MediaConnect タイプの入力でのみ使用されるためにこの例では空です。`SecurityGroups` は、PUSH 入力でのみ使用されるためにこの例では空です。この入力の `State`。`Tags` は空です (このパラメータのデフォルト)。  
詳細については、「*AWS Elemental MediaLive User Guide*」の「[Creating an Input](https://docs.aws.amazon.com/medialive/latest/ug/create-input.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInput](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/medialive/create-input.html)」を参照してください。

# を使用した MediaPackage の例 AWS CLI
<a name="cli_2_mediapackage_code_examples"></a>

次のコード例は、MediaPackage AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-channel`
<a name="mediapackage_CreateChannel_cli_2_topic"></a>

次のコード例は、`create-channel` を使用する方法を示しています。

**AWS CLI**  
**チャネルを作成するには**  
次の `create-channel` コマンドは、現在のアカウントに `sportschannel` という名前のチャネルを作成します。  

```
aws mediapackage create-channel --id sportschannel
```
出力:  

```
{
   "Arn": "arn:aws:mediapackage:us-west-2:111222333:channels/6d345804ec3f46c9b454a91d4a80d0e0",
   "HlsIngest": {
        "IngestEndpoints": [
            {
                "Id": "6d345804ec3f46c9b454a91d4a80d0e0",
                "Password": "generatedwebdavpassword1",
                "Url": "https://f31c86aed53b815a.mediapackage.us-west-2.amazonaws.com/in/v2/6d345804ec3f46c9b454a91d4a80d0e0/6d345804ec3f46c9b454a91d4a80d0e0/channel",
                "Username": "generatedwebdavusername1"
            },
            {
                "Id": "2daa32878af24803b24183727211b8ff",
                "Password": "generatedwebdavpassword2",
                "Url": "https://6ebbe7e04c4b0afa.mediapackage.us-west-2.amazonaws.com/in/v2/6d345804ec3f46c9b454a91d4a80d0e0/2daa32878af24803b24183727211b8ff/channel",
                "Username": "generatedwebdavusername2"
            }
        ]
    },
    "Id": "sportschannel",
    "Tags": {
        "region": "west"
    }
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[チャネルの作成](https://docs.aws.amazon.com/mediapackage/latest/ug/channels-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/create-channel.html)」を参照してください。

### `create-origin-endpoint`
<a name="mediapackage_CreateOriginEndpoint_cli_2_topic"></a>

次のコード例は、`create-origin-endpoint` を使用する方法を示しています。

**AWS CLI**  
**オリジンエンドポイントを作成するには**  
次の `create-origin-endpoint` コマンドは、JSON ファイルで提供されるパッケージ設定と指定されたエンドポイント設定を使用して、`cmafsports` という名前のオリジンエンドポイントを作成します。  

```
aws mediapackage create-origin-endpoint \
    --channel-id sportschannel \
    --id cmafsports \
    --cmaf-package file://file/path/cmafpkg.json --description "cmaf output of sports" \
    --id cmaf_sports \
    --manifest-name sports_channel \
    --startover-window-seconds 300 \
    --tags region=west,media=sports \
    --time-delay-seconds 10
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage:us-west-2:111222333:origin_endpoints/1dc6718be36f4f34bb9cd86bc50925e6",
    "ChannelId": "sportschannel",
    "CmafPackage": {
        "HlsManifests": [
            {
                "AdMarkers": "PASSTHROUGH",
                "Id": "cmaf_sports_endpoint",
                "IncludeIframeOnlyStream": true,
                "ManifestName": "index",
                "PlaylistType": "EVENT",
                "PlaylistWindowSeconds": 300,
                "ProgramDateTimeIntervalSeconds": 300,
                "Url": "https://c4af3793bf76b33c.mediapackage.us-west-2.amazonaws.com/out/v1/1dc6718be36f4f34bb9cd86bc50925e6/cmaf_sports_endpoint/index.m3u8"
            }
        ],
        "SegmentDurationSeconds": 2,
        "SegmentPrefix": "sportschannel"
    },
    "Description": "cmaf output of sports",
    "Id": "cmaf_sports",
    "ManifestName": "sports_channel",
    "StartoverWindowSeconds": 300,
    "Tags": {
        "region": "west",
        "media": "sports"
    },
    "TimeDelaySeconds": 10,
    "Url": "",
    "Whitelist": []
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[エンドポイントの作成](https://docs.aws.amazon.com/mediapackage/latest/ug/endpoints-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateOriginEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/create-origin-endpoint.html)」を参照してください。

### `delete-channel`
<a name="mediapackage_DeleteChannel_cli_2_topic"></a>

次のコード例は、`delete-channel` を使用する方法を示しています。

**AWS CLI**  
**チャンネルを削除するには**  
次の `delete-channel` コマンドは、`test` という名前のチャネルを削除します。  

```
aws mediapackage delete-channel \
    --id test
```
このコマンドは何も出力しません。  
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[チャネルの削除](https://docs.aws.amazon.com/mediapackage/latest/ug/channels-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/delete-channel.html)」を参照してください。

### `delete-origin-endpoint`
<a name="mediapackage_DeleteOriginEndpoint_cli_2_topic"></a>

次のコード例は、`delete-origin-endpoint` を使用する方法を示しています。

**AWS CLI**  
**オリジンエンドポイントを削除するには**  
次の `delete-origin-endpoint` コマンドは、`tester2` という名前のオリジンエンドポイントを削除します。  

```
aws mediapackage delete-origin-endpoint \
    --id tester2
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[エンドポイントの削除](https://docs.aws.amazon.com/mediapackage/latest/ug/endpoints-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteOriginEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/delete-origin-endpoint.html)」を参照してください。

### `describe-channel`
<a name="mediapackage_DescribeChannel_cli_2_topic"></a>

次のコード例は、`describe-channel` を使用する方法を示しています。

**AWS CLI**  
**チャンネルについて説明するには**  
次の `describe-channel` コマンドは、`test` という名前のチャンネルの詳細をすべて表示します。  

```
aws mediapackage describe-channel \
    --id test
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage:us-west-2:111222333:channels/584797f1740548c389a273585dd22a63",
    "HlsIngest": {
        "IngestEndpoints": [
            {
                "Id": "584797f1740548c389a273585dd22a63",
                "Password": "webdavgeneratedpassword1",
                "Url": "https://9be9c4405c474882.mediapackage.us-west-2.amazonaws.com/in/v2/584797f1740548c389a273585dd22a63/584797f1740548c389a273585dd22a63/channel",
                "Username": "webdavgeneratedusername1"
            },
            {
                "Id": "7d187c8616fd455f88aaa5a9fcf74442",
                "Password": "webdavgeneratedpassword2",
                "Url": "https://7bf454c57220328d.mediapackage.us-west-2.amazonaws.com/in/v2/584797f1740548c389a273585dd22a63/7d187c8616fd455f88aaa5a9fcf74442/channel",
                "Username": "webdavgeneratedusername2"
            }
        ]
    },
    "Id": "test",
    "Tags": {}
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「チャネルの詳細の表示 <https://docs.aws.amazon.com/mediapackage/latest/ug/channels-view.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/describe-channel.html)」を参照してください。

### `describe-origin-endpoint`
<a name="mediapackage_DescribeOriginEndpoint_cli_2_topic"></a>

次のコード例は、`describe-origin-endpoint` を使用する方法を示しています。

**AWS CLI**  
**オリジンエンドポイントについて説明するには**  
次の `describe-origin-endpoint` コマンドは、`cmaf_sports` という名前のオリジンエンドポイントのすべての詳細を表示します。  

```
aws mediapackage describe-origin-endpoint \
    --id cmaf_sports
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage:us-west-2:111222333:origin_endpoints/1dc6718be36f4f34bb9cd86bc50925e6",
    "ChannelId": "sportschannel",
    "CmafPackage": {
        "HlsManifests": [
            {
                "AdMarkers": "NONE",
                "Id": "cmaf_sports_endpoint",
                "IncludeIframeOnlyStream": false,
                "PlaylistType": "EVENT",
                "PlaylistWindowSeconds": 60,
                "ProgramDateTimeIntervalSeconds": 0,
                "Url": "https://c4af3793bf76b33c.mediapackage.us-west-2.amazonaws.com/out/v1/1dc6718be36f4f34bb9cd86bc50925e6/cmaf_sports_endpoint/index.m3u8"
            }
        ],
        "SegmentDurationSeconds": 2,
        "SegmentPrefix": "sportschannel"
    },
    "Id": "cmaf_sports",
    "ManifestName": "index",
    "StartoverWindowSeconds": 0,
    "Tags": {
        "region": "west",
        "media": "sports"
    },
    "TimeDelaySeconds": 0,
    "Url": "",
    "Whitelist": []
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[単一のエンドポイントの表示](https://docs.aws.amazon.com/mediapackage/latest/ug/endpoints-view-one.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOriginEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/describe-origin-endpoint.html)」を参照してください。

### `list-channels`
<a name="mediapackage_ListChannels_cli_2_topic"></a>

次のコード例は、`list-channels` を使用する方法を示しています。

**AWS CLI**  
**すべてのチャネルを一覧表示するには**  
次の`list-channels`コマンドは、現在の AWS アカウントに設定されているすべてのチャネルを一覧表示します。  

```
aws mediapackage list-channels
```
出力:  

```
{
    "Channels": [
        {
            "Arn": "arn:aws:mediapackage:us-west-2:111222333:channels/584797f1740548c389a273585dd22a63",
            "HlsIngest": {
                "IngestEndpoints": [
                    {
                        "Id": "584797f1740548c389a273585dd22a63",
                        "Password": "webdavgeneratedpassword1",
                        "Url": "https://9be9c4405c474882.mediapackage.us-west-2.amazonaws.com/in/v2/584797f1740548c389a273585dd22a63/584797f1740548c389a273585dd22a63/channel",
                        "Username": "webdavgeneratedusername1"
                    },
                    {
                        "Id": "7d187c8616fd455f88aaa5a9fcf74442",
                        "Password": "webdavgeneratedpassword2",
                        "Url": "https://7bf454c57220328d.mediapackage.us-west-2.amazonaws.com/in/v2/584797f1740548c389a273585dd22a63/7d187c8616fd455f88aaa5a9fcf74442/channel",
                        "Username": "webdavgeneratedusername2"
                    }
                ]
            },
            "Id": "test",
            "Tags": {}
        }
    ]
}
```
詳細については、「AWS Elemental MediaPackage ユーザーガイド」の「[チャネルの詳細の表示](https://docs.aws.amazon.com/mediapackage/latest/ug/channels-view.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListChannels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/list-channels.html)」を参照してください。**

### `list-origin-endpoints`
<a name="mediapackage_ListOriginEndpoints_cli_2_topic"></a>

次のコード例は、`list-origin-endpoints` を使用する方法を示しています。

**AWS CLI**  
**チャネルのすべてのオリジンエンドポイントを一覧表示するには**  
次の `list-origin-endpoints` コマンドは、`test` という名前のチャネルに設定されているすべてのオリジンエンドポイントを一覧表示します。  

```
aws mediapackage list-origin-endpoints \
    --channel-id test
```
出力:  

```
{
    "OriginEndpoints": [
        {
            "Arn": "arn:aws:mediapackage:us-west-2:111222333:origin_endpoints/247cff871f2845d3805129be22f2c0a2",
            "ChannelId": "test",
            "DashPackage": {
                "ManifestLayout": "FULL",
                "ManifestWindowSeconds": 60,
                "MinBufferTimeSeconds": 30,
                "MinUpdatePeriodSeconds": 15,
                "PeriodTriggers": [],
                "Profile": "NONE",
                "SegmentDurationSeconds": 2,
                "SegmentTemplateFormat": "NUMBER_WITH_TIMELINE",
                "StreamSelection": {
                    "MaxVideoBitsPerSecond": 2147483647,
                    "MinVideoBitsPerSecond": 0,
                    "StreamOrder": "ORIGINAL"
                },
                "SuggestedPresentationDelaySeconds": 25
            },
            "Id": "tester2",
            "ManifestName": "index",
            "StartoverWindowSeconds": 0,
            "Tags": {},
            "TimeDelaySeconds": 0,
            "Url": "https://8343f7014c0ea438.mediapackage.us-west-2.amazonaws.com/out/v1/247cff871f2845d3805129be22f2c0a2/index.mpd",
            "Whitelist": []
        },
        {
            "Arn": "arn:aws:mediapackage:us-west-2:111222333:origin_endpoints/869e237f851549e9bcf10e3bc2830839",
            "ChannelId": "test",
            "HlsPackage": {
                "AdMarkers": "NONE",
                "IncludeIframeOnlyStream": false,
                "PlaylistType": "EVENT",
                "PlaylistWindowSeconds": 60,
                "ProgramDateTimeIntervalSeconds": 0,
                "SegmentDurationSeconds": 6,
                "StreamSelection": {
                    "MaxVideoBitsPerSecond": 2147483647,
                    "MinVideoBitsPerSecond": 0,
                    "StreamOrder": "ORIGINAL"
                },
                "UseAudioRenditionGroup": false
            },
            "Id": "tester",
            "ManifestName": "index",
            "StartoverWindowSeconds": 0,
            "Tags": {},
            "TimeDelaySeconds": 0,
            "Url": "https://8343f7014c0ea438.mediapackage.us-west-2.amazonaws.com/out/v1/869e237f851549e9bcf10e3bc2830839/index.m3u8",
            "Whitelist": []
        }
    ]
}
```
詳細については、「AWS Elemental MediaPackage ユーザーガイド」の「[チャネルに関連付けられたすべてのエンドポイントの表示](https://docs.aws.amazon.com/mediapackage/latest/ug/endpoints-view-all.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListOriginEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/list-origin-endpoints.html)」を参照してください。**

### `list-tags-for-resource`
<a name="mediapackage_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに割り当てられたタグを一覧表示するには**  
次の `list-tags-for-resource` コマンドは、指定されたリソースに割り当てられたタグを一覧表示します。  

```
aws mediapackage list-tags-for-resource \
    --resource-arn arn:aws:mediapackage:us-west-2:111222333:channels/6d345804ec3f46c9b454a91d4a80d0e0
```
出力:  

```
{
    "Tags": {
        "region": "west"
    }
}
```
詳細については、「 [Elemental MediaPackage AWS ユーザーガイド」の「Elemental MediaPackage でのリソースのタグ付け](https://docs.aws.amazon.com/mediapackage/latest/ug/tagging.html)」を参照してください。 *AWS MediaPackage *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/list-tags-for-resource.html)」を参照してください。

### `rotate-ingest-endpoint-credentials`
<a name="mediapackage_RotateIngestEndpointCredentials_cli_2_topic"></a>

次のコード例は、`rotate-ingest-endpoint-credentials` を使用する方法を示しています。

**AWS CLI**  
**取り込み認証情報をローテーションするには**  
次の `rotate-ingest-endpoint-credentials` コマンドは、指定された取り込みエンドポイントの WebDAV ユーザー名とパスワードを更新します。  

```
aws mediapackage rotate-ingest-endpoint-credentials \
    --id test \
    --ingest-endpoint-id 584797f1740548c389a273585dd22a63
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage:us-west-2:111222333:channels/584797f1740548c389a273585dd22a63",
    "HlsIngest": {
        "IngestEndpoints": [
            {
                "Id": "584797f1740548c389a273585dd22a63",
                "Password": "webdavregeneratedpassword1",
                "Url": "https://9be9c4405c474882.mediapackage.us-west-2.amazonaws.com/in/v2/584797f1740548c389a273585dd22a63/584797f1740548c389a273585dd22a63/channel",
                "Username": "webdavregeneratedusername1"
            },
            {
                "Id": "7d187c8616fd455f88aaa5a9fcf74442",
                "Password": "webdavgeneratedpassword2",
                "Url": "https://7bf454c57220328d.mediapackage.us-west-2.amazonaws.com/in/v2/584797f1740548c389a273585dd22a63/7d187c8616fd455f88aaa5a9fcf74442/channel",
                "Username": "webdavgeneratedusername2"
            }
        ]
    },
    "Id": "test",
    "Tags": {}
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[入力 URL での認証情報の更新](https://docs.aws.amazon.com/mediapackage/latest/ug/channels-rotate-creds)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RotateIngestEndpointCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/rotate-ingest-endpoint-credentials.html)」を参照してください。

### `tag-resource`
<a name="mediapackage_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加**  
次の `tag-resource` コマンドは、指定されたリソースに `region=west` キーと値のペアを追加します。  

```
aws mediapackage tag-resource \
    --resource-arn arn:aws:mediapackage:us-west-2:111222333:channels/6d345804ec3f46c9b454a91d4a80d0e0 \
    --tags region=west
```
このコマンドでは何も出力されません。  
詳細については、「 [Elemental MediaPackage AWS ユーザーガイド」の「Elemental MediaPackage でのリソースのタグ付け](https://docs.aws.amazon.com/mediapackage/latest/ug/tagging.html)」を参照してください。 *AWS MediaPackage *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="mediapackage_UntagResource_cli_2_topic"></a>

次の例では、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `untag-resource` コマンドは、指定されたチャネルからキー `region` を持つタグを削除します。  

```
aws mediapackage untag-resource \
    --resource-arn arn:aws:mediapackage:us-west-2:111222333:channels/6d345804ec3f46c9b454a91d4a80d0e0 \
    --tag-keys region
```
詳細については、「 [Elemental MediaPackage AWS ユーザーガイド」の「Elemental MediaPackage でのリソースのタグ付け](https://docs.aws.amazon.com/mediapackage/latest/ug/tagging.html)」を参照してください。 *AWS MediaPackage *  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/untag-resource.html)」を参照してください。

### `update-channel`
<a name="mediapackage_UpdateChannel_cli_2_topic"></a>

次のコード例は、`update-channel` を使用する方法を示しています。

**AWS CLI**  
**チャネルを更新するには**  
次の `update-channel` コマンドは、`sportschannel` という名前のチャンネルを更新して、`24x7 sports` という説明を含めます。  

```
aws mediapackage update-channel \
    --id sportschannel \
    --description "24x7 sports"
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage:us-west-2:111222333:channels/6d345804ec3f46c9b454a91d4a80d0e0",
    "Description": "24x7 sports",
    "HlsIngest": {
        "IngestEndpoints": [
            {
                "Id": "6d345804ec3f46c9b454a91d4a80d0e0",
                "Password": "generatedwebdavpassword1",
                "Url": "https://f31c86aed53b815a.mediapackage.us-west-2.amazonaws.com/in/v2/6d345804ec3f46c9b454a91d4a80d0e0/6d345804ec3f46c9b454a91d4a80d0e0/channel",
                "Username": "generatedwebdavusername1"
            },
            {
                "Id": "2daa32878af24803b24183727211b8ff",
                "Password": "generatedwebdavpassword2",
                "Url": "https://6ebbe7e04c4b0afa.mediapackage.us-west-2.amazonaws.com/in/v2/6d345804ec3f46c9b454a91d4a80d0e0/2daa32878af24803b24183727211b8ff/channel",
                "Username": "generatedwebdavusername2"
            }
        ]
    },
    "Id": "sportschannel",
    "Tags": {}
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[チャネルの編集](https://docs.aws.amazon.com/mediapackage/latest/ug/channels-edit.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/update-channel.html)」を参照してください。

### `update-origin-endpoint`
<a name="mediapackage_UpdateOriginEndpoint_cli_2_topic"></a>

次のコード例は、`update-origin-endpoint` を使用する方法を示しています。

**AWS CLI**  
**オリジンエンドポイントを更新するには**  
次の `update-origin-endpoint` コマンドは、`cmaf_sports` という名前のオリジンエンドポイントを更新します。これにより、遅延時間が `0` 秒に変更されます。  

```
aws mediapackage update-origin-endpoint \
    --id cmaf_sports \
    --time-delay-seconds 0
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage:us-west-2:111222333:origin_endpoints/1dc6718be36f4f34bb9cd86bc50925e6",
    "ChannelId": "sportschannel",
    "CmafPackage": {
        "HlsManifests": [
            {
                "AdMarkers": "NONE",
                "Id": "cmaf_sports_endpoint",
                "IncludeIframeOnlyStream": false,
                "PlaylistType": "EVENT",
                "PlaylistWindowSeconds": 60,
                "ProgramDateTimeIntervalSeconds": 0,
                "Url": "https://c4af3793bf76b33c.mediapackage.us-west-2.amazonaws.com/out/v1/1dc6718be36f4f34bb9cd86bc50925e6/cmaf_sports_endpoint/index.m3u8"
            }
        ],
        "SegmentDurationSeconds": 2,
        "SegmentPrefix": "sportschannel"
    },
    "Id": "cmaf_sports",
    "ManifestName": "index",
    "StartoverWindowSeconds": 0,
    "Tags": {
        "region": "west",
        "media": "sports"
    },
    "TimeDelaySeconds": 0,
    "Url": "",
    "Whitelist": []
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[エンドポイントの編集](https://docs.aws.amazon.com/mediapackage/latest/ug/endpoints-edit.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateOriginEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage/update-origin-endpoint.html)」を参照してください。

# を使用した MediaPackage VOD の例 AWS CLI
<a name="cli_2_mediapackage-vod_code_examples"></a>

次のコード例は、MediaPackage VOD AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-asset`
<a name="mediapackage-vod_CreateAsset_cli_2_topic"></a>

次のコード例は、`create-asset` を使用する方法を示しています。

**AWS CLI**  
**アセットを作成するには**  
次の の`create-asset`例では、現在の AWS アカウントに という名前`Chicken_Asset`のアセットを作成します。アセットはファイル `30sec_chicken.smil` を MediaPackage に取り込みます。  

```
aws mediapackage-vod create-asset \
    --id chicken_asset \
    --packaging-group-id hls_chicken_gp \
    --source-role-arn arn:aws:iam::111122223333:role/EMP_Vod \
    --source-arn arn:aws:s3::111122223333:video-bucket/A/30sec_chicken.smil
```
出力:  

```
{
    "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:assets/chicken_asset",
    "Id":"chicken_asset",
    "PackagingGroupId":"hls_chicken_gp",
    "SourceArn":"arn:aws:s3::111122223333:video-bucket/A/30sec_chicken.smil",
    "SourceRoleArn":"arn:aws:iam::111122223333:role/EMP_Vod",
    "EgressEndpoints":[
        {
            "PackagingConfigurationId":"New_config_1",
            "Url":"https://c75ea2668ab49d02bca7ae10ef31c59e.egress.mediapackage-vod.us-west-2.amazonaws.com/out/v1/6644b55df1744261ab3732a8e5cdaf07/904b06a58c7645e08d57d40d064216ac/f5b2e633ff4942228095d164c10074f3/index.m3u8"
        },
        {
            "PackagingConfigurationId":"new_hls",
            "Url":" https://c75ea2668ab49d02bca7ae10ef31c59e.egress.mediapackage-vod.us-west-2.amazonaws.com/out/v1/6644b55df1744261ab3732a8e5cdaf07/fe8f1f00a80e424cb4f8da4095835e9e/7370ec57432343af816332356d2bd5c6/string.m3u8"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[アセットの取り込み](https://docs.aws.amazon.com/mediapackage/latest/ug/asset-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/create-asset.html)」を参照してください。

### `create-packaging-configuration`
<a name="mediapackage-vod_CreatePackagingConfiguration_cli_2_topic"></a>

次のコード例は、`create-packaging-configuration` を使用する方法を示しています。

**AWS CLI**  
**パッケージング設定を作成するには**  
次の `create-packaging-configuration` の例では、`hls_chicken` という名前のパッケージンググループに `new_hls` という名前のパッケージング設定を作成します。この例では、`hls_pc.json` という名前のディスク上のファイルを使用して詳細を提供します。  

```
aws mediapackage-vod create-packaging-configuration \
    --id new_hls \
    --packaging-group-id hls_chicken \
    --hls-package file://hls_pc.json
```
`hls_pc.json` の内容:  

```
{
    "HlsManifests":[
        {
            "AdMarkers":"NONE",
            "IncludeIframeOnlyStream":false,
            "ManifestName":"string",
            "ProgramDateTimeIntervalSeconds":60,
            "RepeatExtXKey":true,
            "StreamSelection":{
                "MaxVideoBitsPerSecond":1000,
                "MinVideoBitsPerSecond":0,
                "StreamOrder":"ORIGINAL"
            }
        }
    ],
    "SegmentDurationSeconds":6,
    "UseAudioRenditionGroup":false
}
```
出力:  

```
{
    "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-configurations/new_hls",
    "Id":"new_hls",
    "PackagingGroupId":"hls_chicken",
    "HlsManifests":{
        "SegmentDurationSeconds":6,
        "UseAudioRenditionGroup":false,
        "HlsMarkers":[
            {
                "AdMarkers":"NONE",
                "IncludeIframeOnlyStream":false,
                "ManifestName":"string",
                "ProgramDateTimeIntervalSeconds":60,
                "RepeatExtXKey":true,
                "StreamSelection":{
                    "MaxVideoBitsPerSecond":1000,
                    "MinVideoBitsPerSecond":0,
                    "StreamOrder":"ORIGINAL"
                }
            }
        ]
    }
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[パッケージ設定の作成](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-cfig-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePackagingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/create-packaging-configuration.html)」を参照してください。

### `create-packaging-group`
<a name="mediapackage-vod_CreatePackagingGroup_cli_2_topic"></a>

次のコード例は、`create-packaging-group` を使用する方法を示しています。

**AWS CLI**  
**パッケージンググループを作成するには**  
次の の`create-packaging-group`例では、現在の AWS アカウントで設定されているすべてのパッケージンググループを一覧表示します。  

```
aws mediapackage-vod create-packaging-group \
    --id hls_chicken
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-groups/hls_chicken",
    "Id": "hls_chicken"
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[パッケージンググループの作成](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-group-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePackagingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/create-packaging-group.html)」を参照してください。

### `delete-asset`
<a name="mediapackage-vod_DeleteAsset_cli_2_topic"></a>

次のコード例は、`delete-asset` を使用する方法を示しています。

**AWS CLI**  
**アセットを削除するには**  
次の `delete-asset` の例では、`30sec_chicken` という名前のアセットを削除します。  

```
aws mediapackage-vod delete-asset \
    --id 30sec_chicken
```
このコマンドは何も出力しません。  
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[アセットの削除](https://docs.aws.amazon.com/mediapackage/latest/ug/asset-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/delete-asset.html)」を参照してください。

### `delete-packaging-configuration`
<a name="mediapackage-vod_DeletePackagingConfiguration_cli_2_topic"></a>

次のコード例は、`delete-packaging-configuration` を使用する方法を示しています。

**AWS CLI**  
**パッケージング設定を削除するには**  
次の `delete-packaging-configuration` の例では、`CMAF` という名前のパッケージング設定を削除します。  

```
aws mediapackage-vod delete-packaging-configuration \
    --id CMAF
```
このコマンドは何も出力しません。  
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[パッケージング設定の削除](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-cfig-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePackagingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/delete-packaging-configuration.html)」を参照してください。

### `delete-packaging-group`
<a name="mediapackage-vod_DeletePackagingGroup_cli_2_topic"></a>

次のコード例は、`delete-packaging-group` を使用する方法を示しています。

**AWS CLI**  
**パッケージンググループを削除するには**  
次の `delete-packaging-group` の例では、`Dash_widevine` という名前のパッケージンググループを削除します。  

```
aws mediapackage-vod delete-packaging-group \
    --id Dash_widevine
```
このコマンドは何も出力しません。  
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[パッケージンググループの削除](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-group-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePackagingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/delete-packaging-group.html)」を参照してください。

### `describe-asset`
<a name="mediapackage-vod_DescribeAsset_cli_2_topic"></a>

次のコード例は、`describe-asset` を使用する方法を示しています。

**AWS CLI**  
**アセットについて説明するには**  
次の `describe-asset` の例では、`30sec_chicken` という名前のアセットの詳細をすべて表示します。  

```
aws mediapackage-vod describe-asset \
    --id 30sec_chicken
```
出力:  

```
{
    "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:assets/30sec_chicken",
    "Id":"30sec_chicken",
    "PackagingGroupId":"Packaging_group_1",
    "SourceArn":"arn:aws:s3::111122223333:video-bucket/A/30sec_chicken.smil",
    "SourceRoleArn":"arn:aws:iam::111122223333:role/EMP_Vod",
    "EgressEndpoints":[
        {
            "PackagingConfigurationId":"DASH",
            "Url":"https://a5f46a44118ba3e3724ef39ef532e701.egress.mediapackage-vod.us-west-2.amazonaws.com/out/v1/aad7962c569946119c2d5a691be5663c/66c25aff456d463aae0855172b3beb27/4ddfda6da17c4c279a1b8401cba31892/index.mpd"
        },
        {
            "PackagingConfigurationId":"HLS",
            "Url":"https://a5f46a44118ba3e3724ef39ef532e701.egress.mediapackage-vod.us-west-2.amazonaws.com/out/v1/aad7962c569946119c2d5a691be5663c/6e5bf286a3414254a2bf0d22ae148d7e/06b5875b4d004c3cbdc4da2dc4d14638/index.m3u8"
        },
        {
            "PackagingConfigurationId":"CMAF",
            "Url":"https://a5f46a44118ba3e3724ef39ef532e701.egress.mediapackage-vod.us-west-2.amazonaws.com/out/v1/aad7962c569946119c2d5a691be5663c/628fb5d8d89e4702958b020af27fde0e/05eb062214064238ad6330a443aff7f7/index.m3u8"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[アセットの詳細の表示](https://docs.aws.amazon.com/mediapackage/latest/ug/asset-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAsset](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/describe-asset.html)」を参照してください。

### `describe-packaging-configuration`
<a name="mediapackage-vod_DescribePackagingConfiguration_cli_2_topic"></a>

次のコード例は、`describe-packaging-configuration` を使用する方法を示しています。

**AWS CLI**  
**パッケージング設定について説明するには**  
次の `describe-packaging-configuration` の例では、`DASH` という名前のパッケージング設定の詳細をすべて表示します。  

```
aws mediapackage-vod describe-packaging-configuration \
    --id DASH
```
出力:  

```
{
    "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-configurations/DASH",
    "Id":"DASH",
    "PackagingGroupId":"Packaging_group_1",
    "DashPackage":[
        {
            "SegmentDurationSeconds":"2"
        },
        {
            "DashManifests":{
                "ManifestName":"index",
                "MinBufferTimeSeconds":"30",
                "Profile":"NONE"
            }
        }
    ]
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[Viewing Packaging Configuration Details](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-cfig-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePackagingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/describe-packaging-configuration.html)」を参照してください。

### `describe-packaging-group`
<a name="mediapackage-vod_DescribePackagingGroup_cli_2_topic"></a>

次のコード例は、`describe-packaging-group` を使用する方法を示しています。

**AWS CLI**  
**パッケージンググループについて説明するには**  
次の `describe-packaging-group` の例では、`Packaging_group_1` という名前のパッケージンググループの詳細をすべて表示します。  

```
aws mediapackage-vod describe-packaging-group \
    --id Packaging_group_1
```
出力:  

```
{
    "Arn": "arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-groups/Packaging_group_1",
    "Id": "Packaging_group_1"
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[Viewing Packaging Group Details](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-group-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePackagingGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/describe-packaging-group.html)」を参照してください。

### `list-assets`
<a name="mediapackage-vod_ListAssets_cli_2_topic"></a>

次のコード例は、`list-assets` を使用する方法を示しています。

**AWS CLI**  
**すべてのアセットを一覧表示するには**  
次の の`list-assets`例では、現在の AWS アカウントに設定されているすべてのアセットを一覧表示します。  

```
aws mediapackage-vod list-assets
```
出力:  

```
{
    "Assets": [
        "Arn": "arn:aws:mediapackage-vod:us-west-2:111122223333:assets/30sec_chicken",
        "Id": "30sec_chicken",
        "PackagingGroupId": "Packaging_group_1",
        "SourceArn": "arn:aws:s3::111122223333:video-bucket/A/30sec_chicken.smil",
        "SourceRoleArn": "arn:aws:iam::111122223333:role/EMP_Vod"
    ]
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[アセットの詳細の表示](https://docs.aws.amazon.com/mediapackage/latest/ug/asset-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/list-assets.html)」を参照してください。

### `list-packaging-configurations`
<a name="mediapackage-vod_ListPackagingConfigurations_cli_2_topic"></a>

次のコード例は、`list-packaging-configurations` を使用する方法を示しています。

**AWS CLI**  
**すべてのパッケージング設定を一覧表示するには**  
次の `list-packaging-configurations` の例では、`Packaging_group_1` という名前のパッケージンググループで設定されているすべてのパッケージング設定を一覧表示します。  

```
aws mediapackage-vod list-packaging-configurations \
    --packaging-group-id Packaging_group_1
```
出力:  

```
{
    "PackagingConfigurations":[
        {
            "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-configurations/CMAF",
            "Id":"CMAF",
            "PackagingGroupId":"Packaging_group_1",
            "CmafPackage":[
                {
                    "SegmentDurationSeconds":"2"
                },
                {
                    "HlsManifests":{
                        "AdMarkers":"NONE",
                        "RepeatExtXKey":"False",
                        "ManifestName":"index",
                        "ProgramDateTimeIntervalSeconds":"0",
                        "IncludeIframeOnlyStream":"False"
                    }
                }
            ]
        },
        {
            "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-configurations/DASH",
            "Id":"DASH",
            "PackagingGroupId":"Packaging_group_1",
            "DashPackage":[
                {
                    "SegmentDurationSeconds":"2"
                },
                {
                    "DashManifests":{
                        "ManifestName":"index",
                        "MinBufferTimeSeconds":"30",
                        "Profile":"NONE"
                    }
                }
            ]
        },
        {
            "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-configurations/HLS",
            "Id":"HLS",
            "PackagingGroupId":"Packaging_group_1",
            "HlsPackage":[
                {
                    "SegmentDurationSeconds":"6",
                    "UseAudioRenditionGroup":"False"
                },
                {
                    "HlsManifests":{
                        "AdMarkers":"NONE",
                        "RepeatExtXKey":"False",
                        "ManifestName":"index",
                        "ProgramDateTimeIntervalSeconds":"0",
                        "IncludeIframeOnlyStream":"False"
                    }
                }
            ]
        },
        {
            "Arn":"arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-configurations/New_config_0_copy",
            "Id":"New_config_0_copy",
            "PackagingGroupId":"Packaging_group_1",
            "HlsPackage":[
                {
                    "SegmentDurationSeconds":"6",
                    "UseAudioRenditionGroup":"False"
                },
                {
                    "Encryption":{
                        "EncryptionMethod":"AWS_128",
                        "SpekeKeyProvider":{
                           "RoleArn":"arn:aws:iam:111122223333::role/SPEKERole",
                            "Url":"https://lfgubdvs97.execute-api.us-west-2.amazonaws.com/EkeStage/copyProtection/",
                            "SystemIds":[
                                "81376844-f976-481e-a84e-cc25d39b0b33"
                            ]
                        }
                    }
                },
                {
                    "HlsManifests":{
                        "AdMarkers":"NONE",
                        "RepeatExtXKey":"False",
                        "ManifestName":"index",
                        "ProgramDateTimeIntervalSeconds":"0",
                        "IncludeIframeOnlyStream":"False"
                    }
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[Viewing Packaging Configuration Details](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-cfig-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPackagingConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/list-packaging-configurations.html)」を参照してください。

### `list-packaging-groups`
<a name="mediapackage-vod_ListPackagingGroups_cli_2_topic"></a>

次のコード例は、`list-packaging-groups` を使用する方法を示しています。

**AWS CLI**  
**すべてのパッケージンググループを一覧表示するには**  
次の の`list-packaging-groups`例では、現在の AWS アカウントで設定されているすべてのパッケージンググループを一覧表示します。  

```
aws mediapackage-vod list-packaging-groups
```
出力:  

```
{
    "PackagingGroups": [
        {
            "Arn": "arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-groups/Dash_widevine",
            "Id": "Dash_widevine"
        },
        {
            "Arn": "arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-groups/Encrypted_HLS",
            "Id": "Encrypted_HLS"
        },
        {
            "Arn": "arn:aws:mediapackage-vod:us-west-2:111122223333:packaging-groups/Packaging_group_1",
            "Id": "Packaging_group_1"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaPackage ユーザーガイド*」の「[Viewing Packaging Group Details](https://docs.aws.amazon.com/mediapackage/latest/ug/pkg-group-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPackagingGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediapackage-vod/list-packaging-groups.html)」を参照してください。

# を使用した MediaStore データプレーンの例 AWS CLI
<a name="cli_2_mediastore-data_code_examples"></a>

次のコード例は、MediaStore データプレーン AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-object`
<a name="mediastore-data_DeleteObject_cli_2_topic"></a>

次のコード例は、`delete-object` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトを削除するには**  
次の `delete-object` の例では、指定されたオブジェクトを削除します。  

```
aws mediastore-data delete-object \
    --endpoint=https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path=/folder_name/README.md
```
このコマンドは何も出力しません。  
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Deleting an Object](https://docs.aws.amazon.com/mediastore/latest/ug/objects-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore-data/delete-object.html)」を参照してください。

### `describe-object`
<a name="mediastore-data_DescribeObject_cli_2_topic"></a>

次のコード例は、`describe-object` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのヘッダーを表示するには**  
次の `describe-object` の例では、指定されたパスにあるオブジェクトのヘッダーを表示します。  

```
aws mediastore-data describe-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path events/baseball/setup.jpg
```
出力:  

```
{
    "LastModified": "Fri, 19 Jul 2019 21:50:31 GMT",
    "ContentType": "image/jpeg",
    "ContentLength": "3860266",
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3"
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing the Details of an Object](https://docs.aws.amazon.com/mediastore/latest/ug/objects-view-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore-data/describe-object.html)」を参照してください。

### `get-object`
<a name="mediastore-data_GetObject_cli_2_topic"></a>

次のコード例は、`get-object` を使用する方法を示しています。

**AWS CLI**  
**例 1: オブジェクト全体をダウンロードするには**  
次の `get-object` の例では、指定されたオブジェクトをダウンロードします。  

```
aws mediastore-data get-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path events/baseball/setup.jpg setup.jpg
```
出力:  

```
{
    "ContentType": "image/jpeg",
    "StatusCode": 200,
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3",
    "ContentLength": "3860266",
    "LastModified": "Fri, 19 Jul 2019 21:50:31 GMT"
}
```
**例 2: オブジェクトの一部をダウンロードするには**  
次の `get-object` の例では、オブジェクトの指定された部分をダウンロードします。  

```
aws mediastore-data get-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path events/baseball/setup.jpg setup.jpg \
    --range "bytes=0-100"
```
出力:  

```
{
    "StatusCode": 206,
    "LastModified": "Fri, 19 Jul 2019 21:50:31 GMT",
    "ContentType": "image/jpeg",
    "ContentRange": "bytes 0-100/3860266",
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3",
    "ContentLength": "101"
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Downloading an Object](https://docs.aws.amazon.com/mediastore/latest/ug/objects-download.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[GetObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore-data/get-object.html)」を参照してください。**

### `list-items`
<a name="mediastore-data_ListItems_cli_2_topic"></a>

次のコード例は、`list-items` を使用する方法を示しています。

**AWS CLI**  
**例 1: コンテナに保存されている項目 (オブジェクトとフォルダ) のリストを表示するには**  
次の `list-items` の例では、指定されたコンテナに保存されている項目 (オブジェクトとフォルダ) のリストを表示します。  

```
aws mediastore-data list-items \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com
```
出力:  

```
{
    "Items": [
        {
            "Type": "OBJECT",
            "ContentLength": 3784,
            "Name": "setup.jpg",
            "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3",
            "ContentType": "image/jpeg",
            "LastModified": 1563571859.379
        },
        {
            "Type": "FOLDER",
            "Name": "events"
        }
    ]
}
```
**例 2: フォルダに保存されている項目 (オブジェクトとフォルダ) のリストを表示するには**  
次の `list-items` の例では、指定されたフォルダに保存されている項目 (オブジェクトとフォルダ) のリストを表示します。  

```
aws mediastore-data list-items \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --path events/baseball
```
出力:  

```
{
    "Items": [
        {
            "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3",
            "ContentType": "image/jpeg",
            "Type": "OBJECT",
            "ContentLength": 3860266,
            "LastModified": 1563573031.872,
            "Name": "setup.jpg"
        }
    ]
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Viewing a List of Objects](https://docs.aws.amazon.com/mediastore/latest/ug/objects-view-list.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore-data/list-items.html)」を参照してください。

### `put-object`
<a name="mediastore-data_PutObject_cli_2_topic"></a>

次のコード例は、`put-object` を使用する方法を示しています。

**AWS CLI**  
**例 1: オブジェクトをコンテナにアップロードするには**  
次の `put-object` の例では、指定されたコンテナにオブジェクトをアップロードします。  

```
aws mediastore-data put-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --body ReadMe.md \
    --path ReadMe.md \
    --cache-control "max-age=6, public" \
    --content-type binary/octet-stream
```
出力:  

```
{
    "ContentSHA256": "f29bc64a9d3732b4b9035125fdb3285f5b6455778edca72414671e0ca3b2e0de",
    "StorageClass": "TEMPORAL",
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3"
}
```
**例 2: オブジェクトをコンテナ内のフォルダにアップロードするには**  
次の `put-object` の例では、コンテナ内の指定されたフォルダにオブジェクトをアップロードします。  

```
aws mediastore-data put-object \
    --endpoint https://aaabbbcccdddee.data.mediastore.us-west-2.amazonaws.com \
    --body ReadMe.md \
    --path /september-events/ReadMe.md \
    --cache-control "max-age=6, public" \
    --content-type binary/octet-stream
```
出力:  

```
{
    "ETag": "2aa333bbcc8d8d22d777e999c88d4aa9eeeeee4dd89ff7f555555555555da6d3",
    "ContentSHA256": "f29bc64a9d3732b4b9035125fdb3285f5b6455778edca72414671e0ca3b2e0de",
    "StorageClass": "TEMPORAL"
}
```
詳細については、「*AWS Elemental MediaStore User Guide*」の「[Uploading an Object](https://docs.aws.amazon.com/mediastore/latest/ug/objects-upload.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediastore-data/put-object.html)」を参照してください。

# を使用した MediaTailor の例 AWS CLI
<a name="cli_2_mediatailor_code_examples"></a>

次のコード例は、MediaTailor AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-playback-configuration`
<a name="mediatailor_DeletePlaybackConfiguration_cli_2_topic"></a>

次のコード例は、`delete-playback-configuration` を使用する方法を示しています。

**AWS CLI**  
**設定を削除するには**  
次の `delete-playback-configuration` では、`campaign_short` という名前の設定を削除します。  

```
aws mediatailor delete-playback-configuration \
    --name campaign_short
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Elemental MediaTailor User Guide*」の「[Deleting a Configuration](https://docs.aws.amazon.com/mediatailor/latest/ug/configurations-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePlaybackConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediatailor/delete-playback-configuration.html)」を参照してください。

### `get-playback-configuration`
<a name="mediatailor_GetPlaybackConfiguration_cli_2_topic"></a>

次のコード例は、`get-playback-configuration` を使用する方法を示しています。

**AWS CLI**  
**設定について説明するには**  
次の `get-playback-configuration` は、`west_campaign` という名前の設定の詳細をすべて表示します。  

```
aws mediatailor get-playback-configuration \
    --name west_campaign
```
出力:  

```
{
     "AdDecisionServerUrl": "http://your.ads.url",
     "CdnConfiguration": {},
     "DashConfiguration": {
         "ManifestEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com/v1/dash/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/west_campaign/",
         "MpdLocation": "EMT_DEFAULT",
         "OriginManifestType": "MULTI_PERIOD"
     },
     "HlsConfiguration": {
         "ManifestEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com/v1/master/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/west_campaign/"
     },
     "Name": "west_campaign",
     "PlaybackConfigurationArn": "arn:aws:mediatailor:us-west-2:123456789012:playbackConfiguration/west_campaign",
     "PlaybackEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com",
     "SessionInitializationEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com/v1/session/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/west_campaign/",
     "Tags": {},
     "VideoContentSourceUrl": "https://8343f7014c0ea438.mediapackage.us-west-2.amazonaws.com/out/v1/683f0f2ff7cd43a48902e6dcd5e16dcf/index.m3u8"
}
```
詳細については、「*AWS Elemental MediaTailor User Guide*」の「[Viewing a Configuration](https://docs.aws.amazon.com/mediatailor/latest/ug/configurations-view.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPlaybackConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediatailor/get-playback-configuration.html)」を参照してください。

### `list-playback-configurations`
<a name="mediatailor_ListPlaybackConfigurations_cli_2_topic"></a>

次のコード例は、`list-playback-configurations` を使用する方法を示しています。

**AWS CLI**  
**すべての設定を一覧表示するには**  
以下は、現在の AWS アカウントの設定のすべての詳細`list-playback-configurations`を表示します。  

```
aws mediatailor list-playback-configurations
```
出力:  

```
{
    "Items": [
        {
            "AdDecisionServerUrl": "http://your.ads.url",
            "CdnConfiguration": {},
            "DashConfiguration": {
                "ManifestEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com/v1/dash/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/west_campaign/",
                "MpdLocation": "EMT_DEFAULT",
                "OriginManifestType": "MULTI_PERIOD"
            },
            "HlsConfiguration": {
                "ManifestEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com/v1/master/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/west_campaign/"
            },
            "Name": "west_campaign",
            "PlaybackConfigurationArn": "arn:aws:mediatailor:us-west-2:123456789012:playbackConfiguration/west_campaign",
            "PlaybackEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com",
            "SessionInitializationEndpointPrefix": "https://170c14299689462897d0cc45fc2000bb.mediatailor.us-west-2.amazonaws.com/v1/session/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/west_campaign/",
            "Tags": {},
            "VideoContentSourceUrl": "https://8343f7014c0ea438.mediapackage.us-west-2.amazonaws.com/out/v1/683f0f2ff7cd43a48902e6dcd5e16dcf/index.m3u8"
        },
        {
            "AdDecisionServerUrl": "http://your.ads.url",
            "CdnConfiguration": {},
            "DashConfiguration": {
                "ManifestEndpointPrefix": "https://73511f91d6a24ca2b93f3cf1d7cedd67.mediatailor.us-west-2.amazonaws.com/v1/dash/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/sports_campaign/",
                "MpdLocation": "DISABLED",
                "OriginManifestType": "MULTI_PERIOD"
            },
            "HlsConfiguration": {
                "ManifestEndpointPrefix": "https://73511f91d6a24ca2b93f3cf1d7cedd67.mediatailor.us-west-2.amazonaws.com/v1/master/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/sports_campaign/"
            },
            "Name": "sports_campaign",
            "PlaybackConfigurationArn": "arn:aws:mediatailor:us-west-2:123456789012:playbackConfiguration/sports_campaign",
            "PlaybackEndpointPrefix": "https://73511f91d6a24ca2b93f3cf1d7cedd67.mediatailor.us-west-2.amazonaws.com",
            "SessionInitializationEndpointPrefix": "https://73511f91d6a24ca2b93f3cf1d7cedd67.mediatailor.us-west-2.amazonaws.com/v1/session/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/sports_campaign/",
            "SlateAdUrl": "http://s3.bucket/slate_ad.mp4",
            "Tags": {},
            "VideoContentSourceUrl": "https://c4af3793bf76b33c.mediapackage.us-west-2.amazonaws.com/out/v1/1dc6718be36f4f34bb9cd86bc50925e6/sports_endpoint/index.m3u8"
        }
    ]
}
```
詳細については、*「AWS Elemental MediaTailor User Guide*」の「Viewing a Configuration <https://docs.aws.amazon.com/mediatailor/latest/ug/configurations-view.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPlaybackConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediatailor/list-playback-configurations.html)」を参照してください。

### `put-playback-configuration`
<a name="mediatailor_PutPlaybackConfiguration_cli_2_topic"></a>

次のコード例は、`put-playback-configuration` を使用する方法を示しています。

**AWS CLI**  
**設定を作成するには**  
次の `put-playback-configuration` では、`campaign_short` という名前の設定を作成します。  

```
aws mediatailor put-playback-configuration \
    --name campaign_short \
    --ad-decision-server-url http://your.ads.url \
    --video-content-source-url http://video.bucket/index.m3u8
```
出力:  

```
{
    "AdDecisionServerUrl": "http://your.ads.url",
    "CdnConfiguration": {},
    "DashConfiguration": {
         "ManifestEndpointPrefix": "https://13484114d38f4383bc0d6a7cb879bd00.mediatailor.us-west-2.amazonaws.com/v1/dash/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/campaign_short/",
         "MpdLocation": "EMT_DEFAULT",
         "OriginManifestType": "MULTI_PERIOD"
    },
    "HlsConfiguration": {
        "ManifestEndpointPrefix": "https://13484114d38f4383bc0d6a7cb879bd00.mediatailor.us-west-2.amazonaws.com/v1/master/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/campaign_short/"
    },
    "Name": "campaign_short",
    "PlaybackConfigurationArn": "arn:aws:mediatailor:us-west-2:123456789012:playbackConfiguration/campaign_short",
    "PlaybackEndpointPrefix": "https://13484114d38f4383bc0d6a7cb879bd00.mediatailor.us-west-2.amazonaws.com",
    "SessionInitializationEndpointPrefix": "https://13484114d38f4383bc0d6a7cb879bd00.mediatailor.us-west-2.amazonaws.com/v1/session/1cbfeaaecb69778e0c167d0505a2bc57da2b1754/campaign_short/",
    "Tags": {},
    "VideoContentSourceUrl": "http://video.bucket/index.m3u8"
}
```
詳細については、「*AWS Elemental MediaTailor User Guide*」の「[Creating a Configuration](https://docs.aws.amazon.com/mediatailor/latest/ug/configurations-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutPlaybackConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/mediatailor/put-playback-configuration.html)」を参照してください。

# を使用した MemoryDB の例 AWS CLI
<a name="cli_2_memorydb_code_examples"></a>

次のコード例は、MemoryDB AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `copy-snapshot`
<a name="memorydb_CopySnapshot_cli_2_topic"></a>

次のコード例は、`copy-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットをコピーするには**  
次の `copy-snapshot` の例では、スナップショットのコピーを作成します。  

```
aws memorydb copy-snapshot \
    --source-snapshot-name my-cluster-snapshot \
    --target-snapshot-name my-cluster-snapshot-copy
```
Output  

```
{
    "Snapshot": {
        "Name": "my-cluster-snapshot-copy",
        "Status": "creating",
        "Source": "manual",
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:snapshot/my-cluster-snapshot-copy",
        "ClusterConfiguration": {
            "Name": "my-cluster",
            "Description": " ",
            "NodeType": "db.r6g.large",
            "EngineVersion": "6.2",
            "MaintenanceWindow": "wed:03:00-wed:04:00",
            "Port": 6379,
            "ParameterGroupName": "default.memorydb-redis6",
            "SubnetGroupName": "my-sg",
            "VpcId": "vpc-xx2574fc",
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "04:30-05:30",
            "NumShards": 2
        }
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Copying a snapshot](https://docs.aws.amazon.com/memorydb/latest/devguide/snapshots-copying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopySnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/copy-snapshot.html)」を参照してください。

### `create-acl`
<a name="memorydb_CreateAcl_cli_2_topic"></a>

次のコード例は、`create-acl` を使用する方法を示しています。

**AWS CLI**  
**ACL を作成するには**  
次の `create-acl` の例では、新しいアクセスコントロールリストを作成します。  

```
aws memorydb create-acl \
    --acl-name "new-acl-1" \
    --user-names "my-user"
```
出力:  

```
{
    "ACL": {
        "Name": "new-acl-1",
        "Status": "creating",
        "UserNames": [
            "my-user"
        ],
        "MinimumEngineVersion": "6.2",
        "Clusters": [],
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:acl/new-acl-1"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Authenticating users with Access Control Lists](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.acls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/create-acl.html)」を参照してください。

### `create-cluster`
<a name="memorydb_CreateCluster_cli_2_topic"></a>

次のコード例は、`create-cluster` を使用する方法を示しています。

**AWS CLI**  
**クラスターを作成するには**  
次の `create-cluster` の例では、新しいクラスターを作成します。  

```
aws memorydb create-cluster \
    --cluster-name my-new-cluster \
    --node-type db.r6g.large \
    --acl-name my-acl \
    --subnet-group my-sg
```
出力:  

```
{
    "Cluster": {
        "Name": "my-new-cluster",
        "Status": "creating",
        "NumberOfShards": 1,
        "AvailabilityMode": "MultiAZ",
        "ClusterEndpoint": {
            "Port": 6379
        },
        "NodeType": "db.r6g.large",
        "EngineVersion": "6.2",
        "EnginePatchVersion": "6.2.6",
        "ParameterGroupName": "default.memorydb-redis6",
        "ParameterGroupStatus": "in-sync",
        "SubnetGroupName": "my-sg",
        "TLSEnabled": true,
        "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxx:cluster/my-new-cluster",
        "SnapshotRetentionLimit": 0,
        "MaintenanceWindow": "sat:10:00-sat:11:00",
        "SnapshotWindow": "07:30-08:30",
        "ACLName": "my-acl",
        "AutoMinorVersionUpgrade": true
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Managing Clusters](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/create-cluster.html)」を参照してください。

### `create-parameter-group`
<a name="memorydb_CreateParameterGroup_cli_2_topic"></a>

次のコード例は、`create-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループを作成するには**  
次の `create-parameter-group` の例では、パラメータグループを作成します。  

```
aws memorydb create-parameter-group \
    --parameter-group-name myRedis6x \
    --family memorydb_redis6 \
    --description "my-parameter-group"
```
出力:  

```
{
    "ParameterGroup": {
        "Name": "myredis6x",
        "Family": "memorydb_redis6",
        "Description": "my-parameter-group",
        "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxx:parametergroup/myredis6x"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Creating a parameter group](https://docs.aws.amazon.com/memorydb/latest/devguide/parametergroups.creating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/create-parameter-group.html)」を参照してください。

### `create-snapshot`
<a name="memorydb_CreateSnapshot_cli_2_topic"></a>

次のコード例は、`create-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットを作成するには**  
次の `create-snapshot` の例では、スナップショットを作成します。  

```
aws memorydb create-snapshot \
    --cluster-name my-cluster \
    --snapshot-name my-cluster-snapshot
```
出力:  

```
{
    "Snapshot": {
        "Name": "my-cluster-snapshot1",
        "Status": "creating",
        "Source": "manual",
        "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxx:snapshot/my-cluster-snapshot",
        "ClusterConfiguration": {
            "Name": "my-cluster",
            "Description": "",
            "NodeType": "db.r6g.large",
            "EngineVersion": "6.2",
            "MaintenanceWindow": "wed:03:00-wed:04:00",
            "Port": 6379,
            "ParameterGroupName": "default.memorydb-redis6",
            "SubnetGroupName": "my-sg",
            "VpcId": "vpc-862xxxxc",
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "04:30-05:30",
            "NumShards": 2
        }
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Making manual snapshots](https://docs.aws.amazon.com/memorydb/latest/devguide/snapshots-manual.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/create-snapshot.html)」を参照してください。

### `create-subnet-group`
<a name="memorydb_CreateSubnetGroup_cli_2_topic"></a>

次のコード例は、`create-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループを作成するには**  
次の `create-subnet-group` の例では、サブネットグループを作成します。  

```
aws memorydb create-subnet-group \
    --subnet-group-name mysubnetgroup \
    --description "my subnet group" \
    --subnet-ids subnet-5623xxxx
```
出力:  

```
{
    "SubnetGroup": {
        "Name": "mysubnetgroup",
        "Description": "my subnet group",
        "VpcId": "vpc-86257xxx",
        "Subnets": [
            {
                "Identifier": "subnet-5623xxxx",
                "AvailabilityZone": {
                    "Name": "us-east-1a"
                }
            }
        ],
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:subnetgroup/mysubnetgroup"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Creating a subnet group](https://docs.aws.amazon.com/memorydb/latest/devguide/subnetgroups.creating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/create-subnet-group.html)」を参照してください。

### `create-user`
<a name="memorydb_CreateUser_cli_2_topic"></a>

次のコード例は、`create-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを作成するには**  
次の `create-user` の例では、新しいユーザーを作成します。  

```
aws memorydb create-user \
    --user-name user-name-1 \
    --access-string "~objects:* ~items:* ~public:*" \
     --authentication-mode \
         Passwords="enterapasswordhere",Type=password
```
出力:  

```
{
    "User": {
        "Name": "user-name-1",
        "Status": "active",
        "AccessString": "off ~objects:* ~items:* ~public:* resetchannels -@all",
        "ACLNames": [],
        "MinimumEngineVersion": "6.2",
        "Authentication": {
            "Type": "password",
            "PasswordCount": 1
        },
        "ARN": "arn:aws:memorydb:us-west-2:491658xxxxxx:user/user-name-1"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Authenticating users with Access Control Lists](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.acls.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/create-user.html)」を参照してください。

### `delete-acl`
<a name="memorydb_DeleteAcl_cli_2_topic"></a>

次のコード例は、`delete-acl` を使用する方法を示しています。

**AWS CLI**  
**ACL を削除するには**  
次の `delete-acl` の例では、アクセスコントロールリストを削除します。  

```
aws memorydb delete-acl \
    --acl-name "new-acl-1"
```
出力:  

```
{
    "ACL": {
        "Name": "new-acl-1",
        "Status": "deleting",
        "UserNames": [
            "pat"
        ],
        "MinimumEngineVersion": "6.2",
        "Clusters": [],
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:acl/new-acl-1"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Authenticating users with Access Control Lists](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.acls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/delete-acl.html)」を参照してください。

### `delete-cluster`
<a name="memorydb_DeleteCluster_cli_2_topic"></a>

次のコード例は、`delete-cluster` を使用する方法を示しています。

**AWS CLI**  
**クラスターを削除するには**  
次の `delete-cluster` の例では、クラスターを削除します。  

```
aws memorydb delete-cluster \
    --cluster-name my-new-cluster
```
出力:  

```
{
    "Cluster": {
        "Name": "my-new-cluster",
        "Status": "deleting",
        "NumberOfShards": 1,
        "ClusterEndpoint": {
            "Address": "clustercfg.my-new-cluster.xxxxx.memorydb.us-east-1.amazonaws.com",
            "Port": 6379
        },
        "NodeType": "db.r6g.large",
        "EngineVersion": "6.2",
        "EnginePatchVersion": "6.2.6",
        "ParameterGroupName": "default.memorydb-redis6",
        "ParameterGroupStatus": "in-sync",
        "SubnetGroupName": "my-sg",
        "TLSEnabled": true,
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:cluster/my-new-cluster",
        "SnapshotRetentionLimit": 0,
        "MaintenanceWindow": "sat:10:00-sat:11:00",
        "SnapshotWindow": "07:30-08:30",
        "AutoMinorVersionUpgrade": true
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Deleting a cluster](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/delete-cluster.html)」を参照してください。

### `delete-parameter-group`
<a name="memorydb_DeleteParameterGroup_cli_2_topic"></a>

次のコード例は、`delete-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループを削除するには**  
次の `delete-parameter-group` の例では、パラメータグループを削除します。  

```
aws memorydb delete-parameter-group \
    --parameter-group-name myRedis6x
```
出力:  

```
{
    "ParameterGroup": {
        "Name": "myredis6x",
        "Family": "memorydb_redis6",
        "Description": "my-parameter-group",
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:parametergroup/myredis6x"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Deleting a parameter group](https://docs.aws.amazon.com/memorydb/latest/devguide/parametergroups.deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/delete-parameter-group.html)」を参照してください。

### `delete-snapshot`
<a name="memorydb_DeleteSnapshot_cli_2_topic"></a>

次のコード例は、`delete-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットを削除するには**  
次の `delete-snapshot` の例では、スナップショットを削除します。  

```
aws memorydb delete-snapshot \
    --snapshot-name my-cluster-snapshot
```
出力:  

```
{
    "Snapshot": {
        "Name": "my-cluster-snapshot",
        "Status": "deleting",
        "Source": "manual",
        "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxx:snapshot/my-cluster-snapshot",
        "ClusterConfiguration": {
            "Name": "my-cluster",
            "Description": "",
            "NodeType": "db.r6g.large",
            "EngineVersion": "6.2",
            "MaintenanceWindow": "wed:03:00-wed:04:00",
            "Port": 6379,
            "ParameterGroupName": "default.memorydb-redis6",
            "SubnetGroupName": "my-sg",
            "VpcId": "vpc-862xxxxc",
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "04:30-05:30",
            "NumShards": 2
        }
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Deleting a snapshot](https://docs.aws.amazon.com/memorydb/latest/devguide/snapshots-deleting.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/delete-snapshot.html)」を参照してください。

### `delete-subnet-group`
<a name="memorydb_DeleteSubnetGroup_cli_2_topic"></a>

次のコード例は、`delete-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループを削除するには**  
次の `delete-subnet-group` の例では、サブネットを削除します。  

```
aws memorydb delete-subnet-group \
    --subnet-group-name mysubnetgroup
```
出力:  

```
{
    "SubnetGroup": {
        "Name": "mysubnetgroup",
        "Description": "my subnet group",
        "VpcId": "vpc-86xxxx4fc",
        "Subnets": [
            {
                "Identifier": "subnet-56xxx61b",
                "AvailabilityZone": {
                    "Name": "us-east-1a"
                }
            }
        ],
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:subnetgroup/mysubnetgroup"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Deleting a subnet group](https://docs.aws.amazon.com/memorydb/latest/devguide/subnetgroups.deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/delete-subnet-group.html)」を参照してください。

### `delete-user`
<a name="memorydb_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
次の `delete-user` の例では、ユーザーを削除します。  

```
aws memorydb delete-user \
    --user-name my-user
```
出力:  

```
{
    "User": {
        "Name": "my-user",
        "Status": "deleting",
        "AccessString": "on ~app::* resetchannels -@all +@read",
        "ACLNames": [
            "my-acl"
        ],
        "MinimumEngineVersion": "6.2",
        "Authentication": {
            "Type": "password",
            "PasswordCount": 1
        },
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:user/my-user"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Authenticating users with Access Control Lists](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.acls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/delete-user.html)」を参照してください。

### `describe-acls`
<a name="memorydb_DescribeAcls_cli_2_topic"></a>

次のコード例は、`describe-acls` を使用する方法を示しています。

**AWS CLI**  
**ACL のリストを返すには**  
次の describe-acls` は、ACL のリストを返します。  

```
aws memorydb describe-acls
```
出力:  

```
{
    "ACLs": [
        {
            "Name": "open-access",
            "Status": "active",
            "UserNames": [
                "default"
            ],
            "MinimumEngineVersion": "6.2",
            "Clusters": [],
            "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:acl/open-access"
        },
        {
            "Name": my-acl",
            "Status": "active",
            "UserNames": [],
            "MinimumEngineVersion": "6.2",
            "Clusters": [
                "my-cluster"
            ],
            "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxxx:acl/my-acl"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Authenticating users with Access Control Lists](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.acls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAcls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-acls.html)」を参照してください。

### `describe-clusters`
<a name="memorydb_DescribeClusters_cli_2_topic"></a>

次のコード例は、`describe-clusters` を使用する方法を示しています。

**AWS CLI**  
**クラスターのリストを返すには**  
次の describe-clusters` は、クラスターのリストを返します。  

```
aws memorydb describe-clusters
```
出力:  

```
{
    "Clusters": [
        {
                "Name": "my-cluster",
                "Status": "available",
                "NumberOfShards": 2,
                "ClusterEndpoint": {
                    "Address": "clustercfg.my-cluster.llru6f.memorydb.us-east-1.amazonaws.com",
                    "Port": 6379
                },
                "NodeType": "db.r6g.large",
                "EngineVersion": "6.2",
                "EnginePatchVersion": "6.2.6",
                "ParameterGroupName": "default.memorydb-redis6",
                "ParameterGroupStatus": "in-sync",
                "SecurityGroups": [
                    {
                        "SecurityGroupId": "sg-0a1434xxxxxc9fae",
                        "Status": "active"
                    }
                ],
                "SubnetGroupName": "pat-sg",
                "TLSEnabled": true,
                "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxx:cluster/my-cluster",
                "SnapshotRetentionLimit": 0,
                "MaintenanceWindow": "wed:03:00-wed:04:00",
                "SnapshotWindow": "04:30-05:30",
                "ACLName": "my-acl",
                "AutoMinorVersionUpgrade": true
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Managing clusters](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-clusters.html)」を参照してください。

### `describe-engine-versions`
<a name="memorydb_DescribeEngineVersions_cli_2_topic"></a>

次のコード例は、`describe-engine-versions` を使用する方法を示しています。

**AWS CLI**  
**エンジンバージョンのリストを返すには**  
次の describe-engine-versions は、エンジンバージョンのリストを返します。  

```
aws memorydb describe-engine-versions
```
出力:  

```
{
    "EngineVersions": [
        {
            "EngineVersion": "6.2",
            "EnginePatchVersion": "6.2.6",
            "ParameterGroupFamily": "memorydb_redis6"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Engine versions and upgrading](https://docs.aws.amazon.com/memorydb/latest/devguide/engine-versions.htmll)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEngineVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-engine-versions.html)」を参照してください。

### `describe-events`
<a name="memorydb_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
**イベントのリストを返すには**  
次の describe-events` はイベントのリストを返します。  

```
aws memorydb describe-events
```
出力:  

```
{
    "Events": [
        {
            "SourceName": "my-cluster",
            "SourceType": "cluster",
            "Message": "Increase replica count started for replication group my-cluster on 2022-07-22T14:09:01.440Z",
            "Date": "2022-07-22T07:09:01.443000-07:00"
        },
        {
            "SourceName": "my-user",
            "SourceType": "user",
            "Message": "Create user my-user operation completed.",
            "Date": "2022-07-22T07:00:02.975000-07:00"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Monitoring events](https://docs.aws.amazon.com/memorydb/latest/devguide/monitoring-events.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-events.html)」を参照してください。

### `describe-parameter-groups`
<a name="memorydb_DescribeParameterGroups_cli_2_topic"></a>

次のコード例は、`describe-parameter-groups` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループのリストを返すには**  
次の describe-parameter-groups` は、パラメータグループのリストを返します。  

```
aws memorydb describe-parameter-groups
```
出力:  

```
{
    "ParameterGroups": [
        {
            "Name": "default.memorydb-redis6",
            "Family": "memorydb_redis6",
            "Description": "Default parameter group for memorydb_redis6",
            "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:parametergroup/default.memorydb-redis6"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Configuring engine parameters using parameter groups](https://docs.aws.amazon.com/memorydb/latest/devguide/parametergroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeParameterGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-parameter-groups.html)」を参照してください。

### `describe-parameters`
<a name="memorydb_DescribeParameters_cli_2_topic"></a>

次のコード例は、`describe-parameters` を使用する方法を示しています。

**AWS CLI**  
**パラメータのリストを返すには**  
次の describe-parameters` はパラメータのリストを返します。  

```
aws memorydb describe-parameters
```
出力:  

```
{
    "Parameters": [
        {
            "Name": "acllog-max-len",
            "Value": "128",
            "Description": "The maximum length of the ACL Log",
            "DataType": "integer",
            "AllowedValues": "1-10000",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "activedefrag",
            "Value": "no",
            "Description": "Enabled active memory defragmentation",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "active-defrag-cycle-max",
            "Value": "75",
            "Description": "Maximal effort for defrag in CPU percentage",
            "DataType": "integer",
            "AllowedValues": "1-75",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "active-defrag-cycle-min",
            "Value": "5",
            "Description": "Minimal effort for defrag in CPU percentage",
            "DataType": "integer",
            "AllowedValues": "1-75",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "active-defrag-ignore-bytes",
            "Value": "104857600",
            "Description": "Minimum amount of fragmentation waste to start active defrag",
            "DataType": "integer",
            "AllowedValues": "1048576-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "active-defrag-max-scan-fields",
            "Value": "1000",
            "Description": "Maximum number of set/hash/zset/list fields that will be processed from the main dictionary scan",
            "DataType": "integer",
            "AllowedValues": "1-1000000",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "active-defrag-threshold-lower",
            "Value": "10",
            "Description": "Minimum percentage of fragmentation to start active defrag",
            "DataType": "integer",
            "AllowedValues": "1-100",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "active-defrag-threshold-upper",
            "Value": "100",
            "Description": "Maximum percentage of fragmentation at which we use maximum effort",
            "DataType": "integer",
            "AllowedValues": "1-100",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "active-expire-effort",
            "Value": "1",
            "Description": "The amount of effort that redis uses to expire items in the active expiration job",
            "DataType": "integer",
            "AllowedValues": "1-10",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "activerehashing",
            "Value": "yes",
            "Description": "Apply rehashing or not",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "client-output-buffer-limit-normal-hard-limit",
            "Value": "0",
            "Description": "Normal client output buffer hard limit in bytes",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "client-output-buffer-limit-normal-soft-limit",
            "Value": "0",
            "Description": "Normal client output buffer soft limit in bytes",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "client-output-buffer-limit-normal-soft-seconds",
            "Value": "0",
            "Description": "Normal client output buffer soft limit in seconds",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "client-output-buffer-limit-pubsub-hard-limit",
            "Value": "33554432",
            "Description": "Pubsub client output buffer hard limit in bytes",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "client-output-buffer-limit-pubsub-soft-limit",
            "Value": "8388608",
            "Description": "Pubsub client output buffer soft limit in bytes",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "client-output-buffer-limit-pubsub-soft-seconds",
            "Value": "60",
            "Description": "Pubsub client output buffer soft limit in seconds",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "hash-max-ziplist-entries",
            "Value": "512",
            "Description": "The maximum number of hash entries in order for the dataset to be compressed",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "hash-max-ziplist-value",
            "Value": "64",
            "Description": "The threshold of biggest hash entries in order for the dataset to be compressed",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "hll-sparse-max-bytes",
            "Value": "3000",
            "Description": "HyperLogLog sparse representation bytes limit",
            "DataType": "integer",
            "AllowedValues": "1-16000",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "lazyfree-lazy-eviction",
            "Value": "no",
            "Description": "Perform an asynchronous delete on evictions",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "lazyfree-lazy-expire",
            "Value": "no",
            "Description": "Perform an asynchronous delete on expired keys",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "lazyfree-lazy-server-del",
            "Value": "no",
            "Description": "Perform an asynchronous delete on key updates",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "lazyfree-lazy-user-del",
            "Value": "no",
            "Description": "Specifies whether the default behavior of DEL command acts the same as UNLINK",
            "DataType": "string",
            "AllowedValues": "yes,no",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "lfu-decay-time",
            "Value": "1",
            "Description": "The amount of time in minutes to decrement the key counter for LFU eviction policyd",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "lfu-log-factor",
            "Value": "10",
            "Description": "The log factor for incrementing key counter for LFU eviction policy",
            "DataType": "integer",
            "AllowedValues": "1-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "list-compress-depth",
            "Value": "0",
            "Description": "Number of quicklist ziplist nodes from each side of the list to exclude from compression. The head and tail of the list are always uncompressed for fast push/pop operations",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "maxmemory-policy",
            "Value": "noeviction",
            "Description": "Max memory policy",
            "DataType": "string",
            "AllowedValues": "volatile-lru,allkeys-lru,volatile-lfu,allkeys-lfu,volatile-random,allkeys-random,volatile-ttl,noeviction",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "maxmemory-samples",
            "Value": "3",
            "Description": "Max memory samples",
            "DataType": "integer",
            "AllowedValues": "1-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "notify-keyspace-events",
            "Description": "The keyspace events for Redis to notify Pub/Sub clients about. By default all notifications are disabled",
            "DataType": "string",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "set-max-intset-entries",
            "Value": "512",
            "Description": "The limit in the size of the set in order for the dataset to be compressed",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "slowlog-log-slower-than",
            "Value": "10000",
            "Description": "The execution time, in microseconds, to exceed in order for the command to get logged. Note that a negative number disables the slow log, while a value of zero forces the logging of every command",
            "DataType": "integer",
            "AllowedValues": "-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "slowlog-max-len",
            "Value": "128",
            "Description": "The length of the slow log. There is no limit to this length. Just be aware that it will consume memory. You can reclaim memory used by the slow log with SLOWLOG RESET.",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "stream-node-max-bytes",
            "Value": "4096",
            "Description": "The maximum size of a single node in a stream in bytes",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "stream-node-max-entries",
            "Value": "100",
            "Description": "The maximum number of items a single node in a stream can contain",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "tcp-keepalive",
            "Value": "300",
            "Description": "If non-zero, send ACKs every given number of seconds",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "timeout",
            "Value": "0",
            "Description": "Close connection if client is idle for a given number of seconds, or never if 0",
            "DataType": "integer",
            "AllowedValues": "0,20-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "tracking-table-max-keys",
            "Value": "1000000",
            "Description": "The maximum number of keys allowed for the tracking table for client side caching",
            "DataType": "integer",
            "AllowedValues": "1-100000000",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "zset-max-ziplist-entries",
            "Value": "128",
            "Description": "The maximum number of sorted set entries in order for the dataset to be compressed",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        },
        {
            "Name": "zset-max-ziplist-value",
            "Value": "64",
            "Description": "The threshold of biggest sorted set entries in order for the dataset to be compressed",
            "DataType": "integer",
            "AllowedValues": "0-",
            "MinimumEngineVersion": "6.2.4"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Configuring engine parameters using parameter groups](https://docs.aws.amazon.com/memorydb/latest/devguide/parametergroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-parameters.html)」を参照してください。

### `describe-snapshots`
<a name="memorydb_DescribeSnapshots_cli_2_topic"></a>

次のコード例は、`describe-snapshots` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのリストを返すには**  
次の describe-snapshots` はスナップショットのリストを返します。  

```
aws memorydb describe-snapshots
```
出力:  

```
{
"Snapshots": [
    {
        "Name": "my-cluster-snapshot",
        "Status": "available",
        "Source": "manual",
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx2:snapshot/my-cluster-snapshot",
        "ClusterConfiguration": {
            "Name": "my-cluster",
            "Description": " ",
            "NodeType": "db.r6g.large",
            "EngineVersion": "6.2",
            "MaintenanceWindow": "wed:03:00-wed:04:00",
            "Port": 6379,
            "ParameterGroupName": "default.memorydb-redis6",
            "SubnetGroupName": "my-sg",
            "VpcId": "vpc-862574fc",
            "SnapshotRetentionLimit": 0,
            "SnapshotWindow": "04:30-05:30",
            "NumShards": 2
        }
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Snapshot and restore](https://docs.aws.amazon.com/memorydb/latest/devguide/snapshots.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-snapshots.html)」を参照してください。

### `describe-subnet-groups`
<a name="memorydb_DescribeSubnetGroups_cli_2_topic"></a>

次のコード例は、`describe-subnet-groups` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループのリストを返すには**  
次の describe-subnet-groups は、サブネットグループのリストを返します。  

```
aws memorydb describe-subnet-groups
```
Output  

```
{
    "SubnetGroups": [
        {
            "Name": "my-sg",
            "Description": "pat-sg",
            "VpcId": "vpc-86xxx4fc",
            "Subnets": [
                {
                    "Identifier": "subnet-faxx84a6",
                    "AvailabilityZone": {
                        "Name": "us-east-1b"
                    }
                },
                {
                    "Identifier": "subnet-56xxf61b",
                    "AvailabilityZone": {
                        "Name": "us-east-1a"
                    }
                }
            ],
            "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxx:subnetgroup/my-sg"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Subnets and subnet groups](https://docs.aws.amazon.com/memorydb/latest/devguide/subnetgroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSubnetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-subnet-groups.html)」を参照してください。

### `describe-users`
<a name="memorydb_DescribeUsers_cli_2_topic"></a>

次のコード例は、`describe-users` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのリストを返すには**  
次の describe-users` は、ユーザーのリストを返します。  

```
aws memorydb describe-users
```
Output  

```
{
    "Users": [
        {
            "Name": "default",
            "Status": "active",
            "AccessString": "on ~* &* +@all",
            "ACLNames": [
                "open-access"
            ],
            "MinimumEngineVersion": "6.0",
            "Authentication": {
                "Type": "no-password"
            },
            "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:user/default"
        },
        {
            "Name": "my-user",
            "Status": "active",
            "AccessString": "off ~objects:* ~items:* ~public:* resetchannels -@all",
            "ACLNames": [],
            "MinimumEngineVersion": "6.2",
            "Authentication": {
                "Type": "password",
                "PasswordCount": 2
            },
            "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:user/my-user"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Authenticating users with Access Control Lists](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.acls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/describe-users.html)」を参照してください。

### `failover-shard`
<a name="memorydb_FailoverShard_cli_2_topic"></a>

次のコード例は、`failover-shard` を使用する方法を示しています。

**AWS CLI**  
**シャードをフェイルオーバーするには**  
次の failover-shard` はシャードをフェイルオーバーします。  

```
aws memorydb failover-shard \
    --cluster-name my-cluster --shard-name 0001
```
出力:  

```
{
    "Cluster": {
        "Name": "my-cluster",
        "Status": "available",
        "NumberOfShards": 2,
        "ClusterEndpoint": {
            "Address": "clustercfg.my-cluster.xxxxxx.memorydb.us-east-1.amazonaws.com",
            "Port": 6379
        },
        "NodeType": "db.r6g.large",
        "EngineVersion": "6.2",
        "EnginePatchVersion": "6.2.6",
        "ParameterGroupName": "default.memorydb-redis6",
        "ParameterGroupStatus": "in-sync",
        "SecurityGroups": [
            {
                "SecurityGroupId": "sg-0a143xxxx45c9fae",
                "Status": "active"
            }
        ],
        "SubnetGroupName": "my-sg",
        "TLSEnabled": true,
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:cluster/my-cluster",
        "SnapshotRetentionLimit": 0,
        "MaintenanceWindow": "wed:03:00-wed:04:00",
        "SnapshotWindow": "04:30-05:30",
        "AutoMinorVersionUpgrade": true
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Minimizing downtime with MultiAZ](https://docs.aws.amazon.com/memorydb/latest/devguide/autofailover.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[FailoverShard](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/failover-shard.html)」を参照してください。

### `list-allowed-node-type-updates`
<a name="memorydb_ListAllowedNodeTypeUpdates_cli_2_topic"></a>

次のコード例は、`list-allowed-node-type-updates` を使用する方法を示しています。

**AWS CLI**  
**許可されたノードタイプの更新のリストを返すには**  
次の list-allowed-node-type-updates は、使用可能なノードタイプの更新のリストを返します。  

```
aws memorydb list-allowed-node-type-updates
```
出力:  

```
{
    "Cluster": {
        "Name": "my-cluster",
        "Status": "available",
        "NumberOfShards": 2,
        "ClusterEndpoint": {
            "Address": "clustercfg.my-cluster.xxxxxx.memorydb.us-east-1.amazonaws.com",
            "Port": 6379
        },
        "NodeType": "db.r6g.large",
        "EngineVersion": "6.2",
        "EnginePatchVersion": "6.2.6",
        "ParameterGroupName": "default.memorydb-redis6",
        "ParameterGroupStatus": "in-sync",
        "SecurityGroups": [
            {
                "SecurityGroupId": "sg-0a143xxxx45c9fae",
                "Status": "active"
            }
        ],
        "SubnetGroupName": "my-sg",
        "TLSEnabled": true,
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:cluster/my-cluster",
        "SnapshotRetentionLimit": 0,
        "MaintenanceWindow": "wed:03:00-wed:04:00",
        "SnapshotWindow": "04:30-05:30",
        "AutoMinorVersionUpgrade": true
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Scaling](https://docs.aws.amazon.com/memorydb/latest/devguide/scaling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAllowedNodeTypeUpdates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/list-allowed-node-type-updates.html)」を参照してください。

### `list-tags`
<a name="memorydb_ListTags_cli_2_topic"></a>

次のコード例は、`list-tags` を使用する方法を示しています。

**AWS CLI**  
**タグのリストを返すには**  
次の list-tags は、タグのリストを返します。  

```
aws memorydb list-tags \
    --resource-arn arn:aws:memorydb:us-east-1:491658xxxxxx:cluster/my-cluster
```
出力:  

```
{
    "TagList": [
        {
            "Key": "mytag",
            "Value": "myvalue"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Tagging resources](https://docs.aws.amazon.com/memorydb/latest/devguide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/list-tags.html)」を参照してください。

### `reset-parameter-group`
<a name="memorydb_ResetParameterGroup_cli_2_topic"></a>

次のコード例は、`reset-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループをリセットするには**  
次の reset-parameter-group` は、パラメータグループをリセットします。  

```
aws memorydb reset-parameter-group \
    --parameter-group-name my-parameter-group \
    --all-parameters
```
出力:  

```
{
    "ParameterGroup": {
        "Name": "my-parameter-group",
        "Family": "memorydb_redis6",
        "Description": "my parameter group",
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:parametergroup/my-parameter-group"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Configuring engine parameters using parameter groups](https://docs.aws.amazon.com/memorydb/latest/devguide/parametergroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/reset-parameter-group.html)」を参照してください。

### `tag-resource`
<a name="memorydb_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを付けるには**  
次の tag-resource` は、リソースにタグを追加します。  

```
aws memorydb tag-resource \
    --resource-arn arn:aws:memorydb:us-east-1:491658xxxxxx:cluster/my-cluster \
    --tags Key="mykey",Value="myvalue"
```
出力:  

```
{
    "TagList": [
        {
            "Key": "mytag",
            "Value": "myvalue"
        },
        {
            "Key": "mykey",
            "Value": "myvalue"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Tagging resources](https://docs.aws.amazon.com/memorydb/latest/devguide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="memorydb_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**ACL を更新するには**  
次の update-acl` は、ユーザーを追加することにより ACL を更新します。  

```
aws memorydb untag-resource \
    --resource-arn arn:aws:memorydb:us-east-1:491658xxxxx:cluster/my-cluster \
    --tag-keys mykey
```
出力:  

```
{
    "TagList": [
        {
            "Key": "mytag",
            "Value": "myvalue"
        }
    ]
}
```
詳細については、「*MemoryDB User Guide*」の「[Tagging resources](https://docs.aws.amazon.com/memorydb/latest/devguide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/untag-resource.html)」を参照してください。

### `update-cluster`
<a name="memorydb_UpdateCluster_cli_2_topic"></a>

次のコード例は、`update-cluster` を使用する方法を示しています。

**AWS CLI**  
**クラスターを更新するには**  
次の update-cluster`` は、クラスターのパラメータグループを my-parameter-group に更新します。  

```
aws memorydb update-cluster \
    --cluster-name my-cluster \
    --parameter-group-name my-parameter-group
```
出力:  

```
{
    "Cluster": {
        "Name": "my-cluster",
        "Status": "available",
        "NumberOfShards": 2,
        "AvailabilityMode": "MultiAZ",
        "ClusterEndpoint": {
            "Address": "clustercfg.my-cluster.llru6f.memorydb.us-east-1.amazonaws.com",
            "Port": 6379
        },
        "NodeType": "db.r6g.large",
        "EngineVersion": "6.2",
        "EnginePatchVersion": "6.2.6",
        "ParameterGroupName": "my-parameter-group",
        "ParameterGroupStatus": "in-sync",
        "SecurityGroups": [
            {
                "SecurityGroupId": "sg-0a143xxxxxc9fae",
                "Status": "active"
            }
        ],
        "SubnetGroupName": "pat-sg",
        "TLSEnabled": true,
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:cluster/my-cluster",
        "SnapshotRetentionLimit": 0,
        "MaintenanceWindow": "wed:03:00-wed:04:00",
        "SnapshotWindow": "04:30-05:30",
        "ACLName": "my-acl",
        "AutoMinorVersionUpgrade": true
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Modifying a cluster](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.modify.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/update-cluster.html)」を参照してください。

### `update-parameter-group`
<a name="memorydb_UpdateParameterGroup_cli_2_topic"></a>

次のコード例は、`update-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループを更新するには**  
次の update-parameter-group`` は、パラメータグループを更新します。  

```
aws memorydb update-parameter-group \
    --parameter-group-name my-parameter-group \
    --parameter-name-values "ParameterName=activedefrag, ParameterValue=no"
```
出力:  

```
{
    "ParameterGroup": {
        "Name": "my-parameter-group",
        "Family": "memorydb_redis6",
        "Description": "my parameter group",
        "ARN": "arn:aws:memorydb:us-east-1:49165xxxxxx:parametergroup/my-parameter-group"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Modifying a parameter group](https://docs.aws.amazon.com/memorydb/latest/devguide/parametergroups.modifying.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/update-parameter-group.html)」を参照してください。

### `update-subnet-group`
<a name="memorydb_UpdateSubnetGroup_cli_2_topic"></a>

次のコード例は、`update-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**サブネットグループを更新するには**  
次の update-subnet-group` は、サブネットグループのサブネット ID を更新します。  

```
aws memorydb update-subnet-group \
    --subnet-group-name my-sg \
    --subnet-ids subnet-01f29d458f3xxxxx
```
出力:  

```
{
    "SubnetGroup": {
        "Name": "my-sg-1",
        "Description": "my-sg",
        "VpcId": "vpc-09d2cfc01xxxxxxx",
        "Subnets": [
            {
                "Identifier": "subnet-01f29d458fxxxxxx",
                "AvailabilityZone": {
                    "Name": "us-east-1a"
                }
            }
        ],
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:subnetgroup/my-sg"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Subnets and subnet groups](https://docs.aws.amazon.com/memorydb/latest/devguide/subnetgroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/update-subnet-group.html)」を参照してください。

### `update-user`
<a name="memorydb_UpdateUser_cli_2_topic"></a>

次のコード例は、`update-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを更新するには**  
次の `update-user` は、ユーザーのアクセス文字列を変更します。  

```
aws memorydb update-user \
    --user-name my-user \
    --access-string "off ~objects:* ~items:* ~public:* resetchannels -@all"
```
出力:  

```
{
    "User": {
        "Name": "my-user",
        "Status": "modifying",
        "AccessString": "off ~objects:* ~items:* ~public:* resetchannels -@all",
        "ACLNames": [
            "myt-acl"
        ],
        "MinimumEngineVersion": "6.2",
        "Authentication": {
            "Type": "password",
            "PasswordCount": 2
        },
        "ARN": "arn:aws:memorydb:us-east-1:491658xxxxxx:user/my-user"
    }
}
```
詳細については、「*MemoryDB User Guide*」の「[Authenticating users with Access Control Lists](https://docs.aws.amazon.com/memorydb/latest/devguide/clusters.acls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/memorydb/update-user.html)」を参照してください。

# を使用した Amazon MSK の例 AWS CLI
<a name="cli_2_kafka_code_examples"></a>

次のコード例は、Amazon MSK AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-cluster`
<a name="kafka_CreateCluster_cli_2_topic"></a>

次のコード例は、`create-cluster` を使用する方法を示しています。

**AWS CLI**  
**Amazon MSK クラスターを作成するには**  
次の `create-cluster` の例では、`MessagingCluster` という名前の MSK クラスターを 3 つのブローカーノードで作成します。`brokernodegroupinfo.json` という名前の JSON ファイルでは、Amazon MSK がブローカーノードを分散する 3 つのサブネットを指定します。この例ではモニタリングレベルを指定しないため、クラスターのレベルは `DEFAULT` になります。  

```
aws kafka create-cluster \
    --cluster-name "MessagingCluster" \
    --broker-node-group-info file://brokernodegroupinfo.json \
    --kafka-version "2.2.1" \
    --number-of-broker-nodes 3
```
`brokernodegroupinfo.json` の内容:  

```
{
    "InstanceType": "kafka.m5.xlarge",
    "BrokerAZDistribution": "DEFAULT",
    "ClientSubnets": [
        "subnet-0123456789111abcd",
        "subnet-0123456789222abcd",
        "subnet-0123456789333abcd"
    ]
}
```
出力:  

```
{
    "ClusterArn": "arn:aws:kafka:us-west-2:123456789012:cluster/MessagingCluster/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE-2",
    "ClusterName": "MessagingCluster",
    "State": "CREATING"
}
```
詳細については、「*Amazon Managed Streaming for Apache Kafka*」の「[Amazon MSK クラスターを作成する](https://docs.aws.amazon.com/msk/latest/developerguide/msk-create-cluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kafka/create-cluster.html)」を参照してください。

### `create-configuration`
<a name="kafka_CreateConfiguration_cli_2_topic"></a>

次のコード例は、`create-configuration` を使用する方法を示しています。

**AWS CLI**  
**カスタム Amazon MSK 設定を作成するには**  
次の `create-configuration` の例では、入力ファイルで指定されたサーバープロパティを使用してカスタム MSK 設定を作成します。  

```
aws kafka create-configuration \
    --name "CustomConfiguration" \
    --description "Topic autocreation enabled; Apache ZooKeeper timeout 2000 ms; Log rolling 604800000 ms." \
    --kafka-versions "2.2.1" \
    --server-properties file://configuration.txt
```
`configuration.txt` の内容:  

```
auto.create.topics.enable = true
zookeeper.connection.timeout.ms = 2000
log.roll.ms = 604800000
```
このコマンドは何も出力しません。出力:  

```
{
    "Arn": "arn:aws:kafka:us-west-2:123456789012:configuration/CustomConfiguration/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE-2",
    "CreationTime": "2019-10-09T15:26:05.548Z",
    "LatestRevision":
        {
            "CreationTime": "2019-10-09T15:26:05.548Z",
            "Description": "Topic autocreation enabled; Apache ZooKeeper timeout 2000 ms; Log rolling 604800000 ms.",
            "Revision": 1
        },
    "Name": "CustomConfiguration"
}
```
詳細については、「*Amazon Managed Streaming for Apache Kafka デベロッパーガイド*」の「[Amazon MSK 設定オペレーション](https://docs.aws.amazon.com/msk/latest/developerguide/msk-configuration-operations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kafka/create-configuration.html)」を参照してください。

### `describe-cluster`
<a name="kafka_DescribeCluster_cli_2_topic"></a>

次のコード例は、`describe-cluster` を使用する方法を示しています。

**AWS CLI**  
**クラスターの説明を表示するには**  
次の `describe-cluster` の例では、Amazon MSK クラスターの説明を表示します。  

```
aws kafka describe-cluster \
    --cluster-arn arn:aws:kafka:us-east-1:123456789012:cluster/demo-cluster-1/6357e0b2-0e6a-4b86-a0b4-70df934c2e31-5
```
出力:  

```
{
    "ClusterInfo": {
        "BrokerNodeGroupInfo": {
            "BrokerAZDistribution": "DEFAULT",
            "ClientSubnets": [
                "subnet-cbfff283",
                "subnet-6746046b"
            ],
            "InstanceType": "kafka.m5.large",
            "SecurityGroups": [
                "sg-f839b688"
            ],
            "StorageInfo": {
                "EbsStorageInfo": {
                    "VolumeSize": 100
                }
            }
        },
        "ClusterArn": "arn:aws:kafka:us-east-1:123456789012:cluster/demo-cluster-1/6357e0b2-0e6a-4b86-a0b4-70df934c2e31-5",
        "ClusterName": "demo-cluster-1",
        "CreationTime": "2020-07-09T02:31:36.223000+00:00",
        "CurrentBrokerSoftwareInfo": {
            "KafkaVersion": "2.2.1"
        },
        "CurrentVersion": "K3AEGXETSR30VB",
        "EncryptionInfo": {
            "EncryptionAtRest": {
                "DataVolumeKMSKeyId": "arn:aws:kms:us-east-1:123456789012:key/a7ca56d5-0768-4b64-a670-339a9fbef81c"
            },
            "EncryptionInTransit": {
                "ClientBroker": "TLS_PLAINTEXT",
                "InCluster": true
            }
        },
        "EnhancedMonitoring": "DEFAULT",
        "OpenMonitoring": {
            "Prometheus": {
                "JmxExporter": {
                    "EnabledInBroker": false
                },
                "NodeExporter": {
                    "EnabledInBroker": false
                }
            }
        },
        "NumberOfBrokerNodes": 2,
        "State": "ACTIVE",
        "Tags": {},
        "ZookeeperConnectString": "z-2.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:2181,z-1.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:2181,z-3.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:2181"
    }
}
```
詳細については、「*Amazon Managed Streaming for Apache Kafka デベロッパーガイド*」の「[Amazon MSK クラスターを一覧表示する](https://docs.aws.amazon.com/msk/latest/developerguide/msk-list-clusters.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kafka/describe-cluster.html)」を参照してください。**

### `get-bootstrap-brokers`
<a name="kafka_GetBootstrapBrokers_cli_2_topic"></a>

次のコード例は、`get-bootstrap-brokers` を使用する方法を示しています。

**AWS CLI**  
**ブートストラップブローカーを取得するには**  
次の `get-bootstrap-brokers` の例では、Amazon MSK クラスターのブートストラップブローカー情報を取得します。  

```
aws kafka get-bootstrap-brokers \
    --cluster-arn arn:aws:kafka:us-east-1:123456789012:cluster/demo-cluster-1/6357e0b2-0e6a-4b86-a0b4-70df934c2e31-5
```
出力:  

```
{
    "BootstrapBrokerString": "b-1.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:9092,b-2.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:9092",
    "BootstrapBrokerStringTls": "b-1.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:9094,b-2.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:9094"
}
```
詳細については、「*Amazon Managed Streaming for Apache Kafka デベロッパーガイド*」の「[ブートストラップブローカーをの取得](https://docs.aws.amazon.com/msk/latest/developerguide/msk-get-bootstrap-brokers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBootstrapBrokers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kafka/get-bootstrap-brokers.html)」を参照してください。

### `list-clusters`
<a name="kafka_ListClusters_cli_2_topic"></a>

次のコード例は、`list-clusters` を使用する方法を示しています。

**AWS CLI**  
**使用可能なクラスターを一覧表示するには**  
次の の`list-clusters`例では、 AWS アカウントの Amazon MSK クラスターを一覧表示します。  

```
aws kafka list-clusters
```
出力:  

```
{
    "ClusterInfoList": [
        {
            "BrokerNodeGroupInfo": {
                "BrokerAZDistribution": "DEFAULT",
                "ClientSubnets": [
                    "subnet-cbfff283",
                    "subnet-6746046b"
                ],
                "InstanceType": "kafka.m5.large",
                "SecurityGroups": [
                    "sg-f839b688"
                ],
                "StorageInfo": {
                    "EbsStorageInfo": {
                        "VolumeSize": 100
                    }
                }
            },
            "ClusterArn": "arn:aws:kafka:us-east-1:123456789012:cluster/demo-cluster-1/6357e0b2-0e6a-4b86-a0b4-70df934c2e31-5",
            "ClusterName": "demo-cluster-1",
            "CreationTime": "2020-07-09T02:31:36.223000+00:00",
            "CurrentBrokerSoftwareInfo": {
                "KafkaVersion": "2.2.1"
            },
            "CurrentVersion": "K3AEGXETSR30VB",
            "EncryptionInfo": {
                "EncryptionAtRest": {
                    "DataVolumeKMSKeyId": "arn:aws:kms:us-east-1:123456789012:key/a7ca56d5-0768-4b64-a670-339a9fbef81c"
                },
                "EncryptionInTransit": {
                    "ClientBroker": "TLS_PLAINTEXT",
                    "InCluster": true
                }
            },
            "EnhancedMonitoring": "DEFAULT",
            "OpenMonitoring": {
                "Prometheus": {
                    "JmxExporter": {
                        "EnabledInBroker": false
                    },
                    "NodeExporter": {
                        "EnabledInBroker": false
                    }
                }
            },
            "NumberOfBrokerNodes": 2,
            "State": "ACTIVE",
            "Tags": {},
            "ZookeeperConnectString": "z-2.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:2181,z-1.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:2181,z-3.demo-cluster-1.xuy0sb.c5.kafka.us-east-1.amazonaws.com:2181"
        }
    ]
}
```
詳細については、「*Amazon Managed Streaming for Apache Kafka デベロッパーガイド*」の「[Amazon MSK クラスターを一覧表示する](https://docs.aws.amazon.com/msk/latest/developerguide/msk-list-clusters.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kafka/list-clusters.html)」を参照してください。**

### `update-broker-storage`
<a name="kafka_UpdateBrokerStorage_cli_2_topic"></a>

次のコード例は、`update-broker-storage` を使用する方法を示しています。

**AWS CLI**  
**ブローカーの EBS ストレージを更新するには**  
次の `update-broker-storage` の例では、クラスター内のすべてのブローカーの EBS ストレージの量を更新します。Amazon MSK は、各ブローカーのターゲットストレージ量を、例で指定された量に設定します。クラスターの現在のバージョンは、クラスターの説明を表示するか、すべてのクラスターを一覧表示することで取得できます。  

```
aws kafka update-broker-storage \
    --cluster-arn "arn:aws:kafka:us-west-2:123456789012:cluster/MessagingCluster/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE-2" \
    --current-version "K21V3IB1VIZYYH" \
    --target-broker-ebs-volume-info "KafkaBrokerNodeId=ALL,VolumeSizeGB=1100"
```
出力は、この `update-broker-storage` オペレーションの ARN を返します。このオペレーションが完了したかどうかを判断するには、この ARN を入力として指定した `describe-cluster-operation` コマンドを使用します。  

```
{
    "ClusterArn": "arn:aws:kafka:us-west-2:123456789012:cluster/MessagingCluster/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE-2",
    "ClusterOperationArn": "arn:aws:kafka:us-west-2:123456789012:cluster-operation/V123450123/a1b2c3d4-1234-abcd-cdef-22222EXAMPLE-2/a1b2c3d4-abcd-1234-bcde-33333EXAMPLE"
}
```
詳細については、「*Amazon Managed Streaming for Apache Kafka デベロッパーガイド*」の「[ブローカー用 EBS ストレージを更新する](https://docs.aws.amazon.com/msk/latest/developerguide/msk-update-storage.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateBrokerStorage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kafka/update-broker-storage.html)」を参照してください。

### `update-cluster-configuration`
<a name="kafka_UpdateClusterConfiguration_cli_2_topic"></a>

次のコード例は、`update-cluster-configuration` を使用する方法を示しています。

**AWS CLI**  
**Amazon MSK クラスターの設定を更新するには**  
次の `update-cluster-configuration` の例では、指定された既存の MSK クラスターの設定を更新します。ここでは、カスタム MSK 設定を使用します。  

```
aws kafka update-cluster-configuration \
    --cluster-arn "arn:aws:kafka:us-west-2:123456789012:cluster/MessagingCluster/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE-2" \
    --configuration-info file://configuration-info.json \
    --current-version "K21V3IB1VIZYYH"
```
`configuration-info.json` の内容:  

```
{
    "Arn": "arn:aws:kafka:us-west-2:123456789012:configuration/CustomConfiguration/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE-2",
    "Revision": 1
}
```
出力は、この `update-cluster-configuration` オペレーションの ARN を返します。このオペレーションが完了したかどうかを判断するには、この ARN を入力として指定した `describe-cluster-operation` コマンドを使用します。  

```
{
    "ClusterArn": "arn:aws:kafka:us-west-2:123456789012:cluster/MessagingCluster/a1b2c3d4-5678-90ab-cdef-11111EXAMPLE-2",
    "ClusterOperationArn": "arn:aws:kafka:us-west-2:123456789012:cluster-operation/V123450123/a1b2c3d4-1234-abcd-cdef-22222EXAMPLE-2/a1b2c3d4-abcd-1234-bcde-33333EXAMPLE"
}
```
詳細については、「*Amazon Managed Streaming for Apache Kafka デベロッパーガイド*」の「[Amazon MSK クラスターの設定を更新する](https://docs.aws.amazon.com/msk/latest/developerguide/msk-update-cluster-cofig.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateClusterConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/kafka/update-cluster-configuration.html)」を参照してください。

# を使用した Network Flow Monitor の例 AWS CLI
<a name="cli_2_networkflowmonitor_code_examples"></a>

次のコード例は、Network Flow Monitor AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-monitor`
<a name="networkflowmonitor_CreateMonitor_cli_2_topic"></a>

次のコード例は、`create-monitor` を使用する方法を示しています。

**AWS CLI**  
**モニターを作成するには**  
次の `create-monitor` の例では、指定したアカウントに `demo` という名前のモニターを作成します。  

```
aws networkflowmonitor create-monitor \
    --monitor-name demo \
    --local-resources type="AWS::EC2::VPC",identifier="arn:aws:ec2:us-east-1:123456789012:vpc/vpc-03ea55eeda25adbb0"  \
    --scope-arn arn:aws:networkflowmonitor:us-east-1:123456789012:scope/e21cda79-30a0-4c12-9299-d8629d76d8cf
```
出力:  

```
{
    "monitorArn": "arn:aws:networkflowmonitor:us-east-1:123456789012:monitor/demo",
    "monitorName": "demo",
    "monitorStatus": "ACTIVE",
    "tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor でモニターを作成する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-monitors-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/create-monitor.html)」を参照してください。

### `create-scope`
<a name="networkflowmonitor_CreateScope_cli_2_topic"></a>

次のコード例は、`create-scope` を使用する方法を示しています。

**AWS CLI**  
**スコープを作成するには**  
次の `create-scope` の例では、Network Flow Monitor によってネットワークトラフィックメトリクスが生成される対象となるリソースのセットを含むスコープを作成します。  

```
aws networkflowmonitor create-scope \
    --targets '[{"targetIdentifier":{"targetId":{"accountId":"123456789012"},"targetType":"ACCOUNT"},"region":"us-east-1"}]'
```
出力:  

```
{
    "scopeId": "97626f8d-8a21-4b5d-813a-1a0962dd4615",
    "status": "IN_PROGRESS",
    "tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor のコンポーネントと機能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-components.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/create-scope.html)」を参照してください。

### `delete-monitor`
<a name="networkflowmonitor_DeleteMonitor_cli_2_topic"></a>

次のコード例は、`delete-monitor` を使用する方法を示しています。

**AWS CLI**  
**モニターを削除するには**  
次の `delete-monitor` の例では、指定したアカウントから `demo` という名前のモニターを削除します。  

```
aws networkflowmonitor delete-monitor \
    --monitor-name demo
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor でモニターを削除する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-monitors-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/delete-monitor.html)」を参照してください。

### `delete-scope`
<a name="networkflowmonitor_DeleteScope_cli_2_topic"></a>

次のコード例は、`delete-scope` を使用する方法を示しています。

**AWS CLI**  
**スコープを削除するには**  
次の `delete-scope` の例では、指定したスコープを削除します。  

```
aws networkflowmonitor delete-scope \
    --scope-id fdc20616-6bb4-4242-a24e-a748e65ca7ac
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor のコンポーネントと機能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-components.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/delete-scope.html)」を参照してください。

### `get-monitor`
<a name="networkflowmonitor_GetMonitor_cli_2_topic"></a>

次のコード例は、`get-monitor` を使用する方法を示しています。

**AWS CLI**  
**モニターに関する情報を取得するには**  
次の `get-monitor` の例では、指定されたアカウントの `demo` という名前のモニターに関する情報が表示されます。  

```
aws networkflowmonitor get-monitor \
    --monitor-name Demo
```
出力:  

```
{
    "monitorArn": "arn:aws:networkflowmonitor:us-east-1:123456789012:monitor/Demo",
    "monitorName": "Demo",
    "monitorStatus": "ACTIVE",
    "localResources": [
        {
            "type": "AWS::EC2::VPC",
            "identifier": "arn:aws:ec2:us-east-1:123456789012:vpc/vpc-03ea55eeda25adbb0"
        }
    ],
    "remoteResources": [],
    "createdAt": "2024-12-09T12:21:51.616000-06:00",
    "modifiedAt": "2024-12-09T12:21:55.412000-06:00",
    "tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor のコンポーネントと機能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/get-monitor.html)」を参照してください。

### `get-query-results-workload-insights-top-contributors-data`
<a name="networkflowmonitor_GetQueryResultsWorkloadInsightsTopContributorsData_cli_2_topic"></a>

次のコード例は、`get-query-results-workload-insights-top-contributors-data` を使用する方法を示しています。

**AWS CLI**  
**ワークロードインサイトでトップコントリビューターデータを取得するには**  
次の `get-query-results-workload-insights-top-contributors-data` の例では、指定したクエリのデータを返します。  

```
aws networkflowmonitor get-query-results-workload-insights-top-contributors-data \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --query-id cc4f4ab3-3103-33b8-80ff-d6597a0c6cea
```
出力:  

```
{
    "datapoints": [
        {
            "timestamps": [
                "2024-12-09T19:00:00+00:00",
                "2024-12-09T19:05:00+00:00",
                "2024-12-09T19:10:00+00:00"
            ],
            "values": [
                259943.0,
                194856.0,
                216432.0
            ],
            "label": "use1-az6"
        }
    ],
    "unit": "Bytes"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetQueryResultsWorkloadInsightsTopContributorsData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/get-query-results-workload-insights-top-contributors-data.html)」を参照してください。

### `get-query-results-workload-insights-top-contributors`
<a name="networkflowmonitor_GetQueryResultsWorkloadInsightsTopContributors_cli_2_topic"></a>

次のコード例は、`get-query-results-workload-insights-top-contributors` を使用する方法を示しています。

**AWS CLI**  
**ワークロードインサイトでトップコントリビューターを取得するには**  
次の `get-query-results-workload-insights-top-contributors` の例では、指定したクエリのデータを返します。  

```
aws networkflowmonitor get-query-results-workload-insights-top-contributors \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --query-id 1fc423d3-b144-37a6-80e6-e2c7d26eea0c
```
出力:  

```
{
    "topContributors": [
        {
            "accountId": "123456789012",
            "localSubnetId": "subnet-0a5b30fb95dca2c14",
            "localAz": "use1-az6",
            "localVpcId": "vpc-03ea55eeda25adbb0",
            "localRegion": "us-east-1",
            "remoteIdentifier": "",
            "value": 908443,
            "localSubnetArn": "arn:aws:ec2:us-east-1:123456789012:subnet/subnet-0a5b30fb95dca2c14",
            "localVpcArn": "arn:aws:ec2:us-east-1:123456789012:vpc/vpc-03ea55eeda25adbb0"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetQueryResultsWorkloadInsightsTopContributors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/get-query-results-workload-insights-top-contributors.html)」を参照してください。

### `get-query-status-monitor-top-contributors`
<a name="networkflowmonitor_GetQueryStatusMonitorTopContributors_cli_2_topic"></a>

次のコード例は、`get-query-status-monitor-top-contributors` を使用する方法を示しています。

**AWS CLI**  
**クエリのステータスを取得するには**  
次の `get-query-status-monitor-top-contributors` の例では、指定したアカウントのクエリの現在のステータスを表示します。  

```
aws networkflowmonitor get-query-status-monitor-top-contributors \
    --monitor-name Demo \
    --query-id 5398eabd-bc40-3f5f-aba3-bcb639d3c7ca
```
出力:  

```
{
    "status": "SUCCEEDED"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetQueryStatusMonitorTopContributors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/get-query-status-monitor-top-contributors.html)」を参照してください。

### `get-query-status-workload-insights-top-contributors-data`
<a name="networkflowmonitor_GetQueryStatusWorkloadInsightsTopContributorsData_cli_2_topic"></a>

次のコード例は、`get-query-status-workload-insights-top-contributors-data` を使用する方法を示しています。

**AWS CLI**  
**クエリのステータスを取得するには**  
次の `get-query-status-workload-insights-top-contributors-data` の例では、指定したアカウントのクエリの現在のステータスを表示します。  

```
aws networkflowmonitor get-query-status-workload-insights-top-contributors-data \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --query-id 4333754d-8ae1-3f29-b6b7-c36db2e7f8ac
```
出力:  

```
{
    "status": "SUCCEEDED"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetQueryStatusWorkloadInsightsTopContributorsData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/get-query-status-workload-insights-top-contributors-data.html)」を参照してください。

### `get-query-status-workload-insights-top-contributors`
<a name="networkflowmonitor_GetQueryStatusWorkloadInsightsTopContributors_cli_2_topic"></a>

次のコード例は、`get-query-status-workload-insights-top-contributors` を使用する方法を示しています。

**AWS CLI**  
**クエリのステータスを取得するには**  
次の `get-query-status-workload-insights-top-contributors` の例では、指定したアカウントのクエリの現在のステータスを表示します。  

```
aws networkflowmonitor get-query-status-workload-insights-top-contributors \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --query-id f2a87c70-3e5a-362e-8beb-4747d13d8419
```
出力:  

```
{
    "status": "SUCCEEDED"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetQueryStatusWorkloadInsightsTopContributors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/get-query-status-workload-insights-top-contributors.html)」を参照してください。

### `get-scope`
<a name="networkflowmonitor_GetScope_cli_2_topic"></a>

次のコード例は、`get-scope` を使用する方法を示しています。

**AWS CLI**  
**スコープに関する情報を取得するには**  
次の `get-scope` の例では、ステータス、タグ、名前、ターゲットの詳細など、スコープに関する情報を表示します。  

```
aws networkflowmonitor get-scope \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf
```
出力:  

```
{
    "scopeId": "e21cda79-30a0-4c12-9299-d8629d76d8cf",
    "status": "SUCCEEDED",
    "scopeArn": "arn:aws:networkflowmonitor:us-east-1:123456789012:scope/e21cda79-30a0-4c12-9299-d8629d76d8cf",
    "targets": [
        {
            "targetIdentifier": {
                "targetId": {
                    "accountId": "123456789012"
                },
                "targetType": "ACCOUNT"
            },
            "region": "us-east-1"
        }
    ],
    "tags": {}
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor のコンポーネントと機能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-components.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[GetScope](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/get-scope.html)」を参照してください。

### `list-monitors`
<a name="networkflowmonitor_ListMonitors_cli_2_topic"></a>

次のコード例は、`list-monitors` を使用する方法を示しています。

**AWS CLI**  
**モニターのリストを取得するには**  
次の `list-monitors` の例では、指定したアカウントのすべてのモニターを返します。  

```
aws networkflowmonitor list-monitors
```
出力:  

```
{
    "monitors": [
        {
            "monitorArn": "arn:aws:networkflowmonitor:us-east-1:123456789012:monitor/Demo",
            "monitorName": "Demo",
            "monitorStatus": "ACTIVE"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor のコンポーネントと機能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMonitors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/list-monitors.html)」を参照してください。

### `list-scopes`
<a name="networkflowmonitor_ListScopes_cli_2_topic"></a>

次のコード例は、`list-scopes` を使用する方法を示しています。

**AWS CLI**  
**スコープのリストを取得するには**  
次の `list-scopes` の例では、指定したアカウントのすべてのスコープを一覧表示します。  

```
aws networkflowmonitor list-scopes
```
出力:  

```
{
    "scopes": [
        {
            "scopeId": "fdc20616-6bb4-4242-a24e-a748e65ca7ac",
            "status": "SUCCEEDED",
            "scopeArn": "arn:aws:networkflowmonitor:us-east-1:123456789012:scope/fdc20616-6bb4-4242-a24e-a748e65ca7ac"
        }
    ]
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor のコンポーネントと機能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-components.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[ListScopes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/list-scopes.html)」を参照してください。

### `list-tags-for-resource`
<a name="networkflowmonitor_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**タグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定したリソースに関連付けられているすべてのタグを返します。  

```
aws networkflowmonitor list-tags-for-resource \
    --resource-arn arn:aws:networkflowmonitor:us-east-1:123456789012:monitor/Demo
```
出力:  

```
{
    "tags": {
        "Value": "Production",
        "Key": "stack"
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Amazon CloudWatch リソースのタグ付け](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/list-tags-for-resource.html)」を参照してください。

### `start-query-monitor-top-contributors`
<a name="networkflowmonitor_StartQueryMonitorTopContributors_cli_2_topic"></a>

次のコード例は、`start-query-monitor-top-contributors` を使用する方法を示しています。

**AWS CLI**  
**クエリを開始するには**  
次の `start-query-monitor-top-contributors` の例では、トップコントリビューターを取得するためのクエリ ID を返すクエリを開始します。  

```
aws networkflowmonitor start-query-monitor-top-contributors \
    --monitor-name Demo \
    --start-time 2024-12-09T19:00:00Z \
    --end-time 2024-12-09T19:15:00Z \
    --metric-name DATA_TRANSFERRED \
    --destination-category UNCLASSIFIED
```
出力:  

```
{
    "queryId": "aecd3a88-0283-35b0-a17d-6e944dc8531d"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartQueryWorkloadInsightsTopContributorsData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/start-query-monitor-top-contributors.html)」を参照してください。

### `start-query-workload-insights-top-contributors-data`
<a name="networkflowmonitor_StartQueryWorkloadInsightsTopContributorsData_cli_2_topic"></a>

次のコード例は、`start-query-workload-insights-top-contributors-data` を使用する方法を示しています。

**AWS CLI**  
**クエリを開始するには**  
次の `start-query-workload-insights-top-contributors-data` の例では、トップコントリビューターを取得するためのクエリ ID を返すクエリを開始します。  

```
aws networkflowmonitor start-query-workload-insights-top-contributors-data \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --start-time 2024-12-09T19:00:00Z \
    --end-time 2024-12-09T19:15:00Z \
    --metric-name DATA_TRANSFERRED \
    --destination-category UNCLASSIFIED
```
出力:  

```
{
    "queryId": "cc4f4ab3-3103-33b8-80ff-d6597a0c6cea"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartQueryWorkloadInsightsTopContributorsData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/start-query-workload-insights-top-contributors-data.html)」を参照してください。

### `start-query-workload-insights-top-contributors`
<a name="networkflowmonitor_StartQueryWorkloadInsightsTopContributors_cli_2_topic"></a>

次のコード例は、`start-query-workload-insights-top-contributors` を使用する方法を示しています。

**AWS CLI**  
**クエリを開始するには**  
次の `start-query-workload-insights-top-contributors` の例では、トップコントリビューターを取得するためのクエリ ID を返すクエリを開始します。  

```
aws networkflowmonitor start-query-workload-insights-top-contributors \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --start-time 2024-12-09T19:00:00Z \
    --end-time 2024-12-09T19:15:00Z \
    --metric-name DATA_TRANSFERRED \
    --destination-category UNCLASSIFIED
```
出力:  

```
{
    "queryId": "1fc423d3-b144-37a6-80e6-e2c7d26eea0c"
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StartQueryWorkloadInsightsTopContributors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/start-query-workload-insights-top-contributors.html)」を参照してください。

### `stop-query-monitor-top-contributors`
<a name="networkflowmonitor_StopQueryMonitorTopContributors_cli_2_topic"></a>

次のコード例は、`stop-query-monitor-top-contributors` を使用する方法を示しています。

**AWS CLI**  
**クエリを停止するには**  
次の `stop-query-monitor-top-contributors` の例では、指定したアカウントのクエリを停止します。  

```
aws networkflowmonitor stop-query-monitor-top-contributors \
    --monitor-name Demo \
    --query-id aecd3a88-0283-35b0-a17d-6e944dc8531d
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopQueryMonitorTopContributors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/stop-query-monitor-top-contributors.html)」を参照してください。

### `stop-query-workload-insights-top-contributors-data`
<a name="networkflowmonitor_StopQueryWorkloadInsightsTopContributorsData_cli_2_topic"></a>

次のコード例は、`stop-query-workload-insights-top-contributors-data` を使用する方法を示しています。

**AWS CLI**  
**クエリを停止するには**  
次の `stop-query-workload-insights-top-contributors-data` の例では、指定したアカウントのクエリを停止します。  

```
aws networkflowmonitor stop-query-workload-insights-top-contributors-data \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --query-id cc4f4ab3-3103-33b8-80ff-d6597a0c6cea
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopQueryWorkloadInsightsTopContributorsData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/stop-query-workload-insights-top-contributors-data.html)」を参照してください。

### `stop-query-workload-insights-top-contributors`
<a name="networkflowmonitor_StopQueryWorkloadInsightsTopContributors_cli_2_topic"></a>

次のコード例は、`stop-query-workload-insights-top-contributors` を使用する方法を示しています。

**AWS CLI**  
**クエリを停止するには**  
次の `stop-query-workload-insights-top-contributors` の例では、指定したアカウントのクエリを停止します。  

```
aws networkflowmonitor stop-query-workload-insights-top-contributors \
    --scope-id e21cda79-30a0-4c12-9299-d8629d76d8cf \
    --query-id 1fc423d3-b144-37a6-80e6-e2c7d26eea0c
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[ワークロードインサイトを使用してネットワークフローを評価する](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-configure-evaluate-flows.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[StopQueryWorkloadInsightsTopContributors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/stop-query-workload-insights-top-contributors.html)」を参照してください。

### `tag-resource`
<a name="networkflowmonitor_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定されたリソースにタグを追加する方法**  
次の `tag-resource` の例では、指定したアカウントのモニターにタグを追加します。  

```
aws networkflowmonitor tag-resource \
    --resource-arn arn:aws:networkflowmonitor:us-east-1:123456789012:monitor/Demo \
    --tags Key=stack,Value=Production
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Amazon CloudWatch リソースのタグ付け](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="networkflowmonitor_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**指定したリソースからタグを削除するには**  
次の `untag-resource` の例では、指定したアカウントのモニターからタグを削除します。  

```
aws networkflowmonitor untag-resource \
    --resource-arn arn:aws:networkflowmonitor:us-east-1:123456789012:monitor/Demo \
    --tag-keys stack
```
このコマンドでは何も出力されません。  
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Amazon CloudWatch リソースのタグ付け](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/untag-resource.html)」を参照してください。

### `update-monitor`
<a name="networkflowmonitor_UpdateMonitor_cli_2_topic"></a>

次のコード例は、`update-monitor` を使用する方法を示しています。

**AWS CLI**  
**既存のモニターを更新するには**  
次の `update-monitor` の例では、指定したアカウントの `Demo` という名前のモニターを更新します。  

```
aws networkflowmonitor update-monitor \
    --monitor-name Demo \
    --local-resources-to-add type="AWS::EC2::VPC",identifier="arn:aws:ec2:us-east-1:123456789012:vpc/vpc-048d08dfbec623f94"
```
出力:  

```
{
    "monitorArn": "arn:aws:networkflowmonitor:us-east-1:123456789012:monitor/Demo",
    "monitorName": "Demo",
    "monitorStatus": "ACTIVE",
    "tags": {
        "Value": "Production",
        "Key": "stack"
    }
}
```
詳細については、*Amazon CloudWatch ユーザーガイド*の「[Network Flow Monitor のコンポーネントと機能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-NetworkFlowMonitor-components.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMonitor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkflowmonitor/update-monitor.html)」を参照してください。

# を使用した Network Manager の例 AWS CLI
<a name="cli_2_networkmanager_code_examples"></a>

次のコード例は、Network Manager AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-customer-gateway`
<a name="networkmanager_AssociateCustomerGateway_cli_2_topic"></a>

次のコード例は、`associate-customer-gateway` を使用する方法を示しています。

**AWS CLI**  
**カスタマーゲートウェイを関連付けるには**  
次の `associate-customer-gateway` の例では、指定されたグローバルネットワーク内のカスタマーゲートウェイ `cgw-11223344556677889` をデバイス `device-07f6fd08867abc123` に関連付けます。  

```
aws networkmanager associate-customer-gateway \
    --customer-gateway-arn arn:aws:ec2:us-west-2:123456789012:customer-gateway/cgw-11223344556677889  \
    --global-network-id global-network-01231231231231231 \
    --device-id device-07f6fd08867abc123 \
    --region us-west-2
```
出力:  

```
{
    "CustomerGatewayAssociation": {
        "CustomerGatewayArn": "arn:aws:ec2:us-west-2:123456789012:customer-gateway/cgw-11223344556677889",
        "GlobalNetworkId": "global-network-01231231231231231",
        "DeviceId": "device-07f6fd08867abc123",
        "State": "PENDING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Customer Gateway Associations](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#cgw-association)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateCustomerGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/associate-customer-gateway.html)」を参照してください。

### `associate-link`
<a name="networkmanager_AssociateLink_cli_2_topic"></a>

次のコード例は、`associate-link` を使用する方法を示しています。

**AWS CLI**  
**リンクを関連付けるには**  
次の `associate-link` の例では、リンク `link-11112222aaaabbbb1` をデバイス `device-07f6fd08867abc123` に関連付けます。リンクとデバイスは、指定されたグローバルネットワークにあります。  

```
aws networkmanager associate-link \
    --global-network-id global-network-01231231231231231 \
    --device-id device-07f6fd08867abc123 \
    --link-id link-11112222aaaabbbb1 \
    --region us-west-2
```
出力:  

```
{
    "LinkAssociation": {
        "GlobalNetworkId": "global-network-01231231231231231",
        "DeviceId": "device-07f6fd08867abc123",
        "LinkId": "link-11112222aaaabbbb1",
        "LinkAssociationState": "PENDING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Device and Link Associations](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#device-link-association)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/associate-link.html)」を参照してください。

### `create-core-network`
<a name="networkmanager_CreateCoreNetwork_cli_2_topic"></a>

次のコード例は、`create-core-network` を使用する方法を示しています。

**AWS CLI**  
**コアネットワークを作成するには**  
次の`create-core-network`例では、 AWS Cloud WAN グローバルネットワーク内でオプションの説明とタグを使用してコアネットワークを作成します。  

```
aws networkmanager create-core-network \
    --global-network-id global-network-cdef-EXAMPLE22222 \
    --description "Main headquarters location" \
    --tags Key=Name,Value="New York City office"
```
出力:  

```
{
    "CoreNetwork": {
        "GlobalNetworkId": "global-network-cdef-EXAMPLE22222",
        "CoreNetworkId": "core-network-cdef-EXAMPLE33333",
        "CoreNetworkArn": "arn:aws:networkmanager::987654321012:core-network/core-network-cdef-EXAMPLE33333",
        "Description": "Main headquarters location",
        "CreatedAt": "2022-01-10T19:53:59+00:00",
        "State": "AVAILABLE",
        "Tags": [
            {
                "Key": "Name",
                "Value": "New York City office"
            }
        ]
    }
}
```
詳細については、「*AWS Cloud WAN User Guide*」の「[Global and core networks](https://docs.aws.amazon.com/network-manager/latest/cloudwan/cloudwan-core-network-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCoreNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/create-core-network.html)」を参照してください。

### `create-device`
<a name="networkmanager_CreateDevice_cli_2_topic"></a>

次のコード例は、`create-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスを作成するには**  
次の `create-device` の例では、指定されたグローバルネットワークにデバイスを作成します。デバイスの詳細には、説明、タイプ、ベンダー、モデル、およびシリアル番号が含まれます。  

```
aws networkmanager create-device
    --global-network-id global-network-01231231231231231 \
    --description "New York office device" \
    --type "office device" \
    --vendor "anycompany" \
    --model "abcabc" \
    --serial-number "1234" \
    --region us-west-2
```
出力:  

```
{
    "Device": {
        "DeviceId": "device-07f6fd08867abc123",
        "DeviceArn": "arn:aws:networkmanager::123456789012:device/global-network-01231231231231231/device-07f6fd08867abc123",
        "GlobalNetworkId": "global-network-01231231231231231",
        "Description": "New York office device",
        "Type": "office device",
        "Vendor": "anycompany",
        "Model": "abcabc",
        "SerialNumber": "1234",
        "CreatedAt": 1575554005.0,
        "State": "PENDING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Devices](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-devices)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/create-device.html)」を参照してください。

### `create-global-network`
<a name="networkmanager_CreateGlobalNetwork_cli_2_topic"></a>

次のコード例は、`create-global-network` を使用する方法を示しています。

**AWS CLI**  
**グローバルネットワークを作成するには**  
次の `create-global-network` の例では、新しいグローバルネットワークを作成します。作成時の初期状態は `PENDING` です。  

```
aws networkmanager create-global-network
```
出力:  

```
{
    "GlobalNetwork": {
        "GlobalNetworkId": "global-network-00a77fc0f722dae74",
        "GlobalNetworkArn": "arn:aws:networkmanager::987654321012:global-network/global-network-00a77fc0f722dae74",
        "CreatedAt": "2022-03-14T20:31:56+00:00",
        "State": "PENDING"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGlobalNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/create-global-network.html)」を参照してください。

### `create-link`
<a name="networkmanager_CreateLink_cli_2_topic"></a>

次のコード例は、`create-link` を使用する方法を示しています。

**AWS CLI**  
**リンクを作成するには**  
次の `create-link` の例では、指定されたグローバルネットワークにリンクを作成します。リンクには、リンクタイプ、帯域幅、プロバイダーの説明と詳細が含まれます。サイト ID は、リンクが関連付けられているサイトを示します。  

```
aws networkmanager create-link \
    --global-network-id global-network-01231231231231231 \
    --description "VPN Link" \
    --type "broadband" \
    --bandwidth UploadSpeed=10,DownloadSpeed=20 \
    --provider "AnyCompany" \
    --site-id site-444555aaabbb11223 \
    --region us-west-2
```
出力:  

```
{
    "Link": {
        "LinkId": "link-11112222aaaabbbb1",
        "LinkArn": "arn:aws:networkmanager::123456789012:link/global-network-01231231231231231/link-11112222aaaabbbb1",
        "GlobalNetworkId": "global-network-01231231231231231",
        "SiteId": "site-444555aaabbb11223",
        "Description": "VPN Link",
        "Type": "broadband",
        "Bandwidth": {
            "UploadSpeed": 10,
            "DownloadSpeed": 20
        },
        "Provider": "AnyCompany",
        "CreatedAt": 1575555811.0,
        "State": "PENDING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Links](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-links)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/create-link.html)」を参照してください。

### `create-site`
<a name="networkmanager_CreateSite_cli_2_topic"></a>

次のコード例は、`create-site` を使用する方法を示しています。

**AWS CLI**  
**サイトを作成するには**  
次の `create-site` の例では、指定されたグローバルネットワークにサイトを作成します。サイトの詳細には、説明と位置情報が含まれます。  

```
aws networkmanager create-site \
    --global-network-id global-network-01231231231231231 \
    --description  "New York head office" \
    --location Latitude=40.7128,Longitude=-74.0060 \
    --region us-west-2
```
出力:  

```
{
    "Site": {
        "SiteId": "site-444555aaabbb11223",
        "SiteArn": "arn:aws:networkmanager::123456789012:site/global-network-01231231231231231/site-444555aaabbb11223",
        "GlobalNetworkId": "global-network-01231231231231231",
        "Description": "New York head office",
        "Location": {
            "Latitude": "40.7128",
            "Longitude": "-74.0060"
        },
        "CreatedAt": 1575554300.0,
        "State": "PENDING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Sites](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-sites)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSite](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/create-site.html)」を参照してください。

### `create-vpc-attachment`
<a name="networkmanager_CreateVpcAttachment_cli_2_topic"></a>

次のコード例は、`create-vpc-attachment` を使用する方法を示しています。

**AWS CLI**  
**VPC アタッチメントを作成するには**  
次の `create-vpc-attachment` の例では、コアネットワークで IPv6 をサポートする VPC アタッチメントを作成します。  

```
aws networkmanager create-vpc-attachment \
    --core-network-id core-network-0fab62fe438d94db6 \
    --vpc-arn arn:aws:ec2:us-east-1:987654321012:vpc/vpc-09f37f69e2786eeb8  \
    --subnet-arns arn:aws:ec2:us-east-1:987654321012:subnet/subnet-04ca4e010857e7bb7 \
    --Ipv6Support=true
```
出力:  

```
{
    "VpcAttachment": {
        "Attachment": {
            "CoreNetworkId": "core-network-0fab62fe438d94db6",
            "AttachmentId": "attachment-05e1da6eba87a06e6",
            "OwnerAccountId": "987654321012",
            "AttachmentType": "VPC",
            "State": "CREATING",
            "EdgeLocation": "us-east-1",
            "ResourceArn": "arn:aws:ec2:us-east-1:987654321012:vpc/vpc-09f37f69e2786eeb8",
            "Tags": [],
            "CreatedAt": "2022-03-10T20:59:14+00:00",
            "UpdatedAt": "2022-03-10T20:59:14+00:00"
        },
        "SubnetArns": [
            "arn:aws:ec2:us-east-1:987654321012:subnet/subnet-04ca4e010857e7bb7"
        ],
        "Options": {
            "Ipv6Support": true
        }
    }
}
```
詳細については、「*Cloud WAN User Guide*」の「[Create an attachment](https://docs.aws.amazon.com/vpc/latest/cloudwan/cloudwan-create-attachment.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVpcAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/create-vpc-attachment.html)」を参照してください。

### `delete-attachment`
<a name="networkmanager_DeleteAttachment_cli_2_topic"></a>

次のコード例は、`delete-attachment` を使用する方法を示しています。

**AWS CLI**  
**アタッチメントを削除するには**  
次の `delete-attachment` の例では、Connect アタッチメントを削除します。  

```
aws networkmanager delete-attachment \
    --attachment-id attachment-01feddaeae26ab68c
```
出力:  

```
{
    "Attachment": {
        "CoreNetworkId": "core-network-0f4b0a9d5ee7761d1",
        "AttachmentId": "attachment-01feddaeae26ab68c",
        "OwnerAccountId": "987654321012",
        "AttachmentType": "CONNECT",
        "State": "DELETING",
        "EdgeLocation": "us-east-1",
        "ResourceArn": "arn:aws:networkmanager::987654321012:attachment/attachment-02c3964448fedf5aa",
        "CreatedAt": "2022-03-15T19:18:41+00:00",
        "UpdatedAt": "2022-03-15T19:28:59+00:00"
    }
}
```
詳細については、「*Cloud WAN User Guide*」の「[Delete attachments](https://docs.aws.amazon.com/vpc/latest/cloudwan/cloudwan-attachments-working-with.html#cloudwan-attachments-deleting)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-attachment.html)」を参照してください。

### `delete-bucket-analytics-configuration`
<a name="networkmanager_DeleteBucketAnalyticsConfiguration_cli_2_topic"></a>

次のコード例は、`delete-bucket-analytics-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットの分析設定を削除するには**  
次の `delete-bucket-analytics-configuration` の例では、指定されたバケットと ID の分析設定を削除します。  

```
aws s3api delete-bucket-analytics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 1
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketAnalyticsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-bucket-analytics-configuration.html)」を参照してください。

### `delete-bucket-metrics-configuration`
<a name="networkmanager_DeleteBucketMetricsConfiguration_cli_2_topic"></a>

次のコード例は、`delete-bucket-metrics-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットのメトリクス設定を削除するには**  
次の `delete-bucket-metrics-configuration` の例では、指定したバケットと ID のメトリクス設定を削除します。  

```
aws s3api delete-bucket-metrics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 123
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketMetricsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-bucket-metrics-configuration.html)」を参照してください。

### `delete-core-network`
<a name="networkmanager_DeleteCoreNetwork_cli_2_topic"></a>

次のコード例は、`delete-core-network` を使用する方法を示しています。

**AWS CLI**  
**コアネットワークを削除するには**  
次の `delete-core-network` の例では、Cloud WAN グローバルネットワークからコアネットワークを削除します。  

```
aws networkmanager delete-core-network \
    --core-network-id core-network-0fab62fe438d94db6
```
出力:  

```
{
    "CoreNetwork": {
        "GlobalNetworkId": "global-network-0d59060f16a73bc41",
        "CoreNetworkId": "core-network-0fab62fe438d94db6",
        "Description": "Main headquarters location",
        "CreatedAt": "2021-12-09T18:31:11+00:00",
        "State": "DELETING",
        "Segments": [
            {
                "Name": "dev",
                "EdgeLocations": [
                    "us-east-1"
                ],
                "SharedSegments": []
            }
        ],
        "Edges": [
            {
                "EdgeLocation": "us-east-1",
                "Asn": 64512,
                "InsideCidrBlocks": []
            }
        ]
    }
}
```
詳細については、「*Cloud WAN User Guide*」の「[Core networks](https://docs.aws.amazon.com/vpc/latest/cloudwan/cloudwan-networks-working-with.html#cloudwan-core-networks)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCoreNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-core-network.html)」を参照してください。

### `delete-device`
<a name="networkmanager_DeleteDevice_cli_2_topic"></a>

次のコード例は、`delete-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスを削除するには**  
次の `delete-device` の例では、指定されたグローバルネットワークから、指定されたデバイスを削除します。  

```
aws networkmanager delete-device \
    --global-network-id global-network-01231231231231231 \
    --device-id device-07f6fd08867abc123 \
    --region us-west-2
```
出力:  

```
{
    "Device": {
        "DeviceId": "device-07f6fd08867abc123",
        "DeviceArn": "arn:aws:networkmanager::123456789012:device/global-network-01231231231231231/device-07f6fd08867abc123",
        "GlobalNetworkId": "global-network-01231231231231231",
        "Description": "New York office device",
        "Type": "office device",
        "Vendor": "anycompany",
        "Model": "abcabc",
        "SerialNumber": "1234",
        "SiteId": "site-444555aaabbb11223",
        "CreatedAt": 1575554005.0,
        "State": "DELETING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Devices](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-devices)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-device.html)」を参照してください。

### `delete-global-network`
<a name="networkmanager_DeleteGlobalNetwork_cli_2_topic"></a>

次のコード例は、`delete-global-network` を使用する方法を示しています。

**AWS CLI**  
**グローバルネットワークを削除するには**  
次の `delete-global-network` の例では、グローバルネットワークを削除します。  

```
aws networkmanager delete-global-network \
    --global-network-id global-network-052bedddccb193b6b
```
出力:  

```
{
    "GlobalNetwork": {
        "GlobalNetworkId": "global-network-052bedddccb193b6b",
        "GlobalNetworkArn": "arn:aws:networkmanager::987654321012:global-network/global-network-052bedddccb193b6b",
        "CreatedAt": "2021-12-09T18:19:12+00:00",
        "State": "DELETING"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGlobalNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-global-network.html)」を参照してください。

### `delete-link`
<a name="networkmanager_DeleteLink_cli_2_topic"></a>

次のコード例は、`delete-link` を使用する方法を示しています。

**AWS CLI**  
**リンクを削除するには**  
次の `delete-link` の例では、指定されたグローバルネットワークから、指定されたリンクを削除します。  

```
aws networkmanager delete-link \
    --global-network-id global-network-01231231231231231  \
    --link-id link-11112222aaaabbbb1 \
    --region us-west-2
```
出力:  

```
{
    "Link": {
        "LinkId": "link-11112222aaaabbbb1",
        "LinkArn": "arn:aws:networkmanager::123456789012:link/global-network-01231231231231231/link-11112222aaaabbbb1",
        "GlobalNetworkId": "global-network-01231231231231231",
        "SiteId": "site-444555aaabbb11223",
        "Description": "VPN Link",
        "Type": "broadband",
        "Bandwidth": {
            "UploadSpeed": 20,
            "DownloadSpeed": 20
        },
        "Provider": "AnyCompany",
        "CreatedAt": 1575555811.0,
        "State": "DELETING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Links](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-links)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-link.html)」を参照してください。

### `delete-public-access-block`
<a name="networkmanager_DeletePublicAccessBlock_cli_2_topic"></a>

次のコード例は、`delete-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**バケットのブロックパブリックアクセス設定を削除するには**  
次の `delete-public-access-block` の例では、指定したバケットのブロックパブリックアクセス設定を削除します。  

```
aws s3api delete-public-access-block \
    --bucket amzn-s3-demo-bucket
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeletePublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-public-access-block.html)」を参照してください。

### `delete-site`
<a name="networkmanager_DeleteSite_cli_2_topic"></a>

次のコード例は、`delete-site` を使用する方法を示しています。

**AWS CLI**  
**サイトを削除するには**  
次の `delete-site` の例では、指定されたグローバルネットワークで、指定されたサイト (`site-444555aaabbb11223`) を削除します。  

```
aws networkmanager delete-site \
    --global-network-id global-network-01231231231231231  \
    --site-id site-444555aaabbb11223 \
    --region us-west-2
```
出力:  

```
{
    "Site": {
        "SiteId": "site-444555aaabbb11223",
        "SiteArn": "arn:aws:networkmanager::123456789012:site/global-network-01231231231231231/site-444555aaabbb11223",
        "GlobalNetworkId": "global-network-01231231231231231",
        "Description": "New York head office",
        "Location": {
            "Latitude": "40.7128",
            "Longitude": "-74.0060"
        },
        "CreatedAt": 1575554300.0,
        "State": "DELETING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Sites](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-sites)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSite](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/delete-site.html)」を参照してください。

### `deregister-transit-gateway`
<a name="networkmanager_DeregisterTransitGateway_cli_2_topic"></a>

次のコード例は、`deregister-transit-gateway` を使用する方法を示しています。

**AWS CLI**  
**グローバルネットワークからトランジットゲートウェイを登録解除するには**  
次の `deregister-transit-gateway` の例では、指定されたグローバルネットワークから、指定されたトランジットゲートウェイの登録を解除します。  

```
aws networkmanager deregister-transit-gateway \
    --global-network-id global-network-01231231231231231 \
    --transit-gateway-arn arn:aws:ec2:us-west-2:123456789012:transit-gateway/tgw-123abc05e04123abc \
    --region us-west-2
```
出力:  

```
{
    "TransitGatewayRegistration": {
        "GlobalNetworkId": "global-network-01231231231231231",
        "TransitGatewayArn": "arn:aws:ec2:us-west-2:123456789012:transit-gateway/tgw-123abc05e04123abc",
        "State": {
            "Code": "DELETING"
        }
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Transit Gateway Registrations](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-registrations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTransitGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/deregister-transit-gateway.html)」を参照してください。

### `describe-global-networks`
<a name="networkmanager_DescribeGlobalNetworks_cli_2_topic"></a>

次のコード例は、`describe-global-networks` を使用する方法を示しています。

**AWS CLI**  
**グローバルネットワークについて説明するには**  
次の `describe-global-networks` の例では、アカウント内のすべてのグローバルネットワークについて説明します。  

```
aws networkmanager describe-global-networks \
    --region us-west-2
```
出力:  

```
{
    "GlobalNetworks": [
        {
            "GlobalNetworkId": "global-network-01231231231231231",
            "GlobalNetworkArn": "arn:aws:networkmanager::123456789012:global-network/global-network-01231231231231231",
            "Description": "Company 1 global network",
            "CreatedAt": 1575553525.0,
            "State": "AVAILABLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGlobalNetworks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/describe-global-networks.html)」を参照してください。

### `disassociate-customer-gateway`
<a name="networkmanager_DisassociateCustomerGateway_cli_2_topic"></a>

次のコード例は、`disassociate-customer-gateway` を使用する方法を示しています。

**AWS CLI**  
**カスタマーゲートウェイの関連付けを解除するには**  
次の `disassociate-customer-gateway` の例では、指定されたカスタマーゲートウェイ (`cgw-11223344556677889`) の関連付けを、指定されたグローバルネットワークから解除します。  

```
aws networkmanager disassociate-customer-gateway \
    --global-network-id global-network-01231231231231231 \
    --customer-gateway-arn arn:aws:ec2:us-west-2:123456789012:customer-gateway/cgw-11223344556677889 \
    --region us-west-2
```
出力:  

```
{
    "CustomerGatewayAssociation": {
        "CustomerGatewayArn": "arn:aws:ec2:us-west-2:123456789012:customer-gateway/cgw-11223344556677889",
        "GlobalNetworkId": "global-network-01231231231231231",
        "DeviceId": "device-07f6fd08867abc123",
        "State": "DELETING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Customer Gateway Associations](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#cgw-association)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateCustomerGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/disassociate-customer-gateway.html)」を参照してください。

### `disassociate-link`
<a name="networkmanager_DisassociateLink_cli_2_topic"></a>

次のコード例は、`disassociate-link` を使用する方法を示しています。

**AWS CLI**  
**リンクの関連付けを解除するには**  
次の `disassociate-link` の例では、指定されたグローバルネットワークのデバイス `device-07f6fd08867abc123` から、指定されたリンクの関連付けを解除します。  

```
aws networkmanager disassociate-link \
    --global-network-id global-network-01231231231231231 \
    --device-id device-07f6fd08867abc123 \
    --link-id link-11112222aaaabbbb1 \
    --region us-west-2
```
出力:  

```
{
    "LinkAssociation": {
        "GlobalNetworkId": "global-network-01231231231231231",
        "DeviceId": "device-07f6fd08867abc123",
        "LinkId": "link-11112222aaaabbbb1",
        "LinkAssociationState": "DELETING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Device and Link Associations](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#device-link-association)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/disassociate-link.html)」を参照してください。

### `get-bucket-analytics-configuration`
<a name="networkmanager_GetBucketAnalyticsConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-analytics-configuration` を使用する方法を示しています。

**AWS CLI**  
**特定の ID を持つバケットの分析設定を取得するには**  
次の `get-bucket-analytics-configuration` の例では、指定されたバケットと ID の分析設定を表示します。  

```
aws s3api get-bucket-analytics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 1
```
出力:  

```
{
    "AnalyticsConfiguration": {
        "StorageClassAnalysis": {},
        "Id": "1"
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketAnalyticsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-bucket-analytics-configuration.html)」を参照してください。

### `get-bucket-metrics-configuration`
<a name="networkmanager_GetBucketMetricsConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-metrics-configuration` を使用する方法を示しています。

**AWS CLI**  
**特定の ID を持つバケットのメトリクス設定を取得するには**  
次の `get-bucket-metrics-configuration` の例では、指定したバケットと ID のメトリクス設定を表示します。  

```
aws s3api get-bucket-metrics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 123
```
出力:  

```
{
    "MetricsConfiguration": {
        "Filter": {
            "Prefix": "logs"
        },
        "Id": "123"
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketMetricsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-bucket-metrics-configuration.html)」を参照してください。

### `get-customer-gateway-associations`
<a name="networkmanager_GetCustomerGatewayAssociations_cli_2_topic"></a>

次のコード例は、`get-customer-gateway-associations` を使用する方法を示しています。

**AWS CLI**  
**カスタマーゲートウェイの関連付けを取得するには**  
次の `get-customer-gateway-associations` の例では、指定されたグローバルネットワークのカスタマーゲートウェイの関連付けを取得します。  

```
aws networkmanager get-customer-gateway-associations \
    --global-network-id global-network-01231231231231231 \
    --region us-west-2
```
出力:  

```
{
    "CustomerGatewayAssociations": [
        {
            "CustomerGatewayArn": "arn:aws:ec2:us-west-2:123456789012:customer-gateway/cgw-11223344556677889",
            "GlobalNetworkId": "global-network-01231231231231231",
            "DeviceId": "device-07f6fd08867abc123",
            "State": "AVAILABLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCustomerGatewayAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-customer-gateway-associations.html)」を参照してください。

### `get-devices`
<a name="networkmanager_GetDevices_cli_2_topic"></a>

次のコード例は、`get-devices` を使用する方法を示しています。

**AWS CLI**  
**デバイスを取得するには**  
次の `get-devices` の例では、指定されたグローバルネットワークでデバイスを取得します。  

```
aws networkmanager get-devices \
    --global-network-id global-network-01231231231231231 \
    --region us-west-2
```
出力:  

```
{
    "Devices": [
        {
            "DeviceId": "device-07f6fd08867abc123",
            "DeviceArn": "arn:aws:networkmanager::123456789012:device/global-network-01231231231231231/device-07f6fd08867abc123",
            "GlobalNetworkId": "global-network-01231231231231231",
            "Description": "NY office device",
            "Type": "office device",
            "Vendor": "anycompany",
            "Model": "abcabc",
            "SerialNumber": "1234",
            "CreatedAt": 1575554005.0,
            "State": "AVAILABLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDevices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-devices.html)」を参照してください。

### `get-link-associations`
<a name="networkmanager_GetLinkAssociations_cli_2_topic"></a>

次のコード例は、`get-link-associations` を使用する方法を示しています。

**AWS CLI**  
**リンクの関連付けを取得するには**  
次の `get-link-associations` の例では、指定されたグローバルネットワークでリンクの関連付けを取得します。  

```
aws networkmanager get-link-associations \
    --global-network-id global-network-01231231231231231 \
    --region us-west-2
```
出力:  

```
{
    "LinkAssociations": [
        {
            "GlobalNetworkId": "global-network-01231231231231231",
            "DeviceId": "device-07f6fd08867abc123",
            "LinkId": "link-11112222aaaabbbb1",
            "LinkAssociationState": "AVAILABLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLinkAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-link-associations.html)」を参照してください。

### `get-links`
<a name="networkmanager_GetLinks_cli_2_topic"></a>

次のコード例は、`get-links` を使用する方法を示しています。

**AWS CLI**  
**リンクを取得するには**  
次の `get-links` の例では、指定されたグローバルネットワークでリンクを取得します。  

```
aws networkmanager get-links \
    --global-network-id global-network-01231231231231231 \
    --region us-west-2
```
出力:  

```
{
    "Links": [
        {
            "LinkId": "link-11112222aaaabbbb1",
            "LinkArn": "arn:aws:networkmanager::123456789012:link/global-network-01231231231231231/link-11112222aaaabbbb1",
            "GlobalNetworkId": "global-network-01231231231231231",
            "SiteId": "site-444555aaabbb11223",
            "Description": "VPN Link",
            "Type": "broadband",
            "Bandwidth": {
                "UploadSpeed": 10,
                "DownloadSpeed": 20
            },
            "Provider": "AnyCompany",
            "CreatedAt": 1575555811.0,
            "State": "AVAILABLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLinks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-links.html)」を参照してください。

### `get-object-retention`
<a name="networkmanager_GetObjectRetention_cli_2_topic"></a>

次のコード例は、`get-object-retention` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのオブジェクト保持設定を取得するには**  
次の `get-object-retention` の例では、指定されたオブジェクトの保持設定を取得します。  

```
aws s3api get-object-retention \
    --bucket amzn-s3-demo-bucket-with-object-lock \
    --key doc1.rtf
```
出力:  

```
{
    "Retention": {
        "Mode": "GOVERNANCE",
        "RetainUntilDate": "2025-01-01T00:00:00.000Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetObjectRetention](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-object-retention.html)」を参照してください。

### `get-public-access-block`
<a name="networkmanager_GetPublicAccessBlock_cli_2_topic"></a>

次のコード例は、`get-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**バケットのブロックパブリックアクセス設定を指定または削除するには**  
次の `get-public-access-block` の例では、指定したバケットのブロックパブリックアクセス設定を表示します。  

```
aws s3api get-public-access-block --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "PublicAccessBlockConfiguration": {
        "IgnorePublicAcls": true,
        "BlockPublicPolicy": true,
        "BlockPublicAcls": true,
        "RestrictPublicBuckets": true
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-public-access-block.html)」を参照してください。

### `get-sites`
<a name="networkmanager_GetSites_cli_2_topic"></a>

次のコード例は、`get-sites` を使用する方法を示しています。

**AWS CLI**  
**サイトを取得するには**  
次の `get-sites` の例では、指定されたグローバルネットワークでサイトを取得します。  

```
aws networkmanager get-sites \
    --global-network-id global-network-01231231231231231 \
    --region us-west-2
```
出力:  

```
{
    "Sites": [
        {
            "SiteId": "site-444555aaabbb11223",
            "SiteArn": "arn:aws:networkmanager::123456789012:site/global-network-01231231231231231/site-444555aaabbb11223",
            "GlobalNetworkId": "global-network-01231231231231231",
            "Description": "NY head office",
            "Location": {
                "Latitude": "40.7128",
                "Longitude": "-74.0060"
            },
            "CreatedAt": 1575554528.0,
            "State": "AVAILABLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSites](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-sites.html)」を参照してください。

### `get-transit-gateway-registrations`
<a name="networkmanager_GetTransitGatewayRegistrations_cli_2_topic"></a>

次のコード例は、`get-transit-gateway-registrations` を使用する方法を示しています。

**AWS CLI**  
**トランジットゲートウェイの登録を取得するには**  
次の `get-transit-gateway-registrations` の例では、指定されたグローバルネットワークに登録されているトランジットゲートウェイを取得します。  

```
aws networkmanager get-transit-gateway-registrations \
    --global-network-id global-network-01231231231231231 \
    --region us-west-2
```
出力:  

```
{
    "TransitGatewayRegistrations": [
        {
            "GlobalNetworkId": "global-network-01231231231231231",
            "TransitGatewayArn": "arn:aws:ec2:us-west-2:123456789012:transit-gateway/tgw-123abc05e04123abc",
            "State": {
                "Code": "AVAILABLE"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTransitGatewayRegistrations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-transit-gateway-registrations.html)」を参照してください。

### `get-vpc-attachment`
<a name="networkmanager_GetVpcAttachment_cli_2_topic"></a>

次の例は、`get-vpc-attachment` を使用する方法を説明しています。

**AWS CLI**  
**VPC アタッチメントを取得するには**  
次の `get-vpc-attachment` の例では、VPC アタッチメントに関する情報を返します。　  

```
aws networkmanager get-vpc-attachment \
    --attachment-id  attachment-03b7ea450134787da
```
出力:  

```
{
    "VpcAttachment": {
        "Attachment": {
            "CoreNetworkId": "core-network-0522de1b226a5d7b3",
            "AttachmentId": "attachment-03b7ea450134787da",
            "OwnerAccountId": "987654321012",
            "AttachmentType": "VPC",
            "State": "CREATING",
            "EdgeLocation": "us-east-1",
            "ResourceArn": "arn:aws:ec2:us-east-1:987654321012:vpc/vpc-a7c4bbda",
            "Tags": [
                {
                    "Key": "Name",
                    "Value": "DevVPC"
                }
            ],
            "CreatedAt": "2022-03-11T17:48:58+00:00",
            "UpdatedAt": "2022-03-11T17:48:58+00:00"
        },
        "SubnetArns": [
            "arn:aws:ec2:us-east-1:987654321012:subnet/subnet-202cde6c",
            "arn:aws:ec2:us-east-1:987654321012:subnet/subnet-e5022dba",
            "arn:aws:ec2:us-east-1:987654321012:subnet/subnet-2387ae02",
            "arn:aws:ec2:us-east-1:987654321012:subnet/subnet-cda9dffc"
        ],
        "Options": {
            "Ipv6Support": false
        }
    }
}
```
詳細については、「*Cloud WAN User Guide*」の「[Attachments](https://docs.aws.amazon.com/vpc/latest/cloudwan/cloudwan-attachments-working-with.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVpcAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/get-vpc-attachment.html)」を参照してください。

### `list-bucket-analytics-configurations`
<a name="networkmanager_ListBucketAnalyticsConfigurations_cli_2_topic"></a>

次のコード例は、`list-bucket-analytics-configurations` を使用する方法を示しています。

**AWS CLI**  
**バケットの分析設定のリストを取得するには**  
次の `list-bucket-analytics-configurations` の例では、指定したバケットの分析設定のリストを取得します。  

```
aws s3api list-bucket-analytics-configurations \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "AnalyticsConfigurationList": [
        {
            "StorageClassAnalysis": {},
            "Id": "1"
        }
    ],
    "IsTruncated": false
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[ListBucketAnalyticsConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/list-bucket-analytics-configurations.html)」を参照してください。

### `list-bucket-metrics-configurations`
<a name="networkmanager_ListBucketMetricsConfigurations_cli_2_topic"></a>

次のコード例は、`list-bucket-metrics-configurations` を使用する方法を示しています。

**AWS CLI**  
**バケットのメトリクス設定のリストを取得するには**  
次の `list-bucket-metrics-configurations` の例では、指定されたバケットのメトリクス設定のリストを取得します。  

```
aws s3api list-bucket-metrics-configurations \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "IsTruncated": false,
    "MetricsConfigurationList": [
        {
            "Filter": {
                "Prefix": "logs"
            },
            "Id": "123"
        },
        {
            "Filter": {
                "Prefix": "tmp"
            },
            "Id": "234"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBucketMetricsConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/list-bucket-metrics-configurations.html)」を参照してください。

### `list-tags-for-resource`
<a name="networkmanager_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定されたデバイスリソース (`device-07f6fd08867abc123`) のタグを一覧表示します。  

```
aws networkmanager list-tags-for-resource \
    --resource-arn arn:aws:networkmanager::123456789012:device/global-network-01231231231231231/device-07f6fd08867abc123 \
    --region us-west-2
```
出力:  

```
{
    "TagList": [
        {
            "Key": "Network",
            "Value": "Northeast"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/list-tags-for-resource.html)」を参照してください。

### `put-bucket-metrics-configuration`
<a name="networkmanager_PutBucketMetricsConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-metrics-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットのメトリクス設定を指定するには**  
次の `put-bucket-metrics-configuration` の例では、指定されたバケットに対して ID 123 のメトリクス設定を指定します。  

```
aws s3api put-bucket-metrics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 123 \
    --metrics-configuration '{"Id": "123", "Filter": {"Prefix": "logs"}}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutBucketMetricsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/put-bucket-metrics-configuration.html)」を参照してください。

### `put-object-retention`
<a name="networkmanager_PutObjectRetention_cli_2_topic"></a>

次のコード例は、`put-object-retention` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのオブジェクト保持設定を指定するには**  
次の `put-object-retention` の例では、指定されたオブジェクトのオブジェクト保持設定を 2025-01-01 まで設定します。  

```
aws s3api put-object-retention \
    --bucket amzn-s3-demo-bucket-with-object-lock \
    --key doc1.rtf \
    --retention '{ "Mode": "GOVERNANCE", "RetainUntilDate": "2025-01-01T00:00:00" }'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObjectRetention](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/put-object-retention.html)」を参照してください。

### `put-public-access-block`
<a name="networkmanager_PutPublicAccessBlock_cli_2_topic"></a>

次のコード例は、`put-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**バケットのブロックパブリックアクセス設定を指定するには**  
次の `put-public-access-block` の例では、指定されたバケットの制限ブロックパブリックアクセス設定を指定します。  

```
aws s3api put-public-access-block \
    --bucket amzn-s3-demo-bucket \
    --public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutPublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/put-public-access-block.html)」を参照してください。

### `register-transit-gateway`
<a name="networkmanager_RegisterTransitGateway_cli_2_topic"></a>

次のコード例は、`register-transit-gateway` を使用する方法を示しています。

**AWS CLI**  
**トランジットゲートウェイをグローバルネットワークに登録するには**  
次の `register-transit-gateway` の例では、指定されたグローバルネットワークにトランジットゲートウェイ `tgw-123abc05e04123abc` を登録します。  

```
aws networkmanager register-transit-gateway \
    --global-network-id global-network-01231231231231231 \
    --transit-gateway-arn arn:aws:ec2:us-west-2:123456789012:transit-gateway/tgw-123abc05e04123abc \
    --region us-west-2
```
出力:  

```
{
    "TransitGatewayRegistration": {
        "GlobalNetworkId": "global-network-01231231231231231",
        "TransitGatewayArn": "arn:aws:ec2:us-west-2:123456789012:transit-gateway/tgw-123abc05e04123abc",
        "State": {
            "Code": "PENDING"
        }
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Transit Gateway Registrations](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-registrations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTransitGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/register-transit-gateway.html)」を参照してください。

### `reject-attachment`
<a name="networkmanager_RejectAttachment_cli_2_topic"></a>

次のコード例は、`reject-attachment` を使用する方法を示しています。

**AWS CLI**  
**アタッチメントを拒否するには**  
次の `reject-attachment` の例では、VPC アタッチメントリクエストを拒否します。  

```
aws networkmanager reject-attachment \
    --attachment-id  attachment-03b7ea450134787da
```
出力:  

```
{
    "Attachment": {
        "CoreNetworkId": "core-network-0522de1b226a5d7b3",
        "AttachmentId": "attachment-03b7ea450134787da",
        "OwnerAccountId": "987654321012",
        "AttachmentType": "VPC",
        "State": "AVAILABLE",
        "EdgeLocation": "us-east-1",
        "ResourceArn": "arn:aws:ec2:us-east-1:987654321012:vpc/vpc-a7c4bbda",
        "CreatedAt": "2022-03-11T17:48:58+00:00",
        "UpdatedAt": "2022-03-11T17:51:25+00:00"
    }
}
```
詳細については、「*Cloud WAN User Guide*」の「[Attachment acceptance](https://docs.aws.amazon.com/vpc/latest/cloudwan/cloudwan-attachments-working-with.html#cloudwan-attachments-acceptance)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectAttachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/reject-attachment.html)」を参照してください。

### `start-route-analysis`
<a name="networkmanager_StartRouteAnalysis_cli_2_topic"></a>

次のコード例は、`start-route-analysis` を使用する方法を示しています。

**AWS CLI**  
**ルート分析を開始するには**  
次の `start-route-analysis` の例では、オプションの `include-return-path` など、ソースと宛先間の分析を開始します。  

```
aws networkmanager start-route-analysis \
    --global-network-id global-network-00aa0aaa0b0aaa000 \
    --source TransitGatewayAttachmentArn=arn:aws:ec2:us-east-1:503089527312:transit-gateway-attachment/tgw-attach-0d4a2d491bf68c093,IpAddress=10.0.0.0 \
    --destination TransitGatewayAttachmentArn=arn:aws:ec2:us-west-1:503089527312:transit-gateway-attachment/tgw-attach-002577f30bb181742,IpAddress=11.0.0.0 \
    --include-return-path
```
出力:  

```
{
    "RouteAnalysis": {
        "GlobalNetworkId": "global-network-00aa0aaa0b0aaa000
        "OwnerAccountId": "1111222233333",
        "RouteAnalysisId": "a1873de1-273c-470c-1a2bc2345678",
        "StartTimestamp": 1695760154.0,
        "Status": "RUNNING",
        "Source": {
            "TransitGatewayAttachmentArn": "arn:aws:ec2:us-east-1:111122223333:transit-gateway-attachment/tgw-attach-1234567890abcdef0,
            "TransitGatewayArn": "arn:aws:ec2:us-east-1:111122223333:transit-gateway/tgw-abcdef01234567890",
            "IpAddress": "10.0.0.0"
        },
        "Destination": {
            "TransitGatewayAttachmentArn": "arn:aws:ec2:us-west-1:555555555555:transit-gateway-attachment/tgw-attach-021345abcdef6789",
            "TransitGatewayArn": "arn:aws:ec2:us-west-1:111122223333:transit-gateway/tgw-09876543210fedcba0",
            "IpAddress": "11.0.0.0"
        },
        "IncludeReturnPath": true,
        "UseMiddleboxes": false
    }
}
```
詳細については、「*AWS Global Networks for Transit Gateways User Guide*」の「[Route Analyzer](https://docs.aws.amazon.com/network-manager/latest/tgwnm/route-analyzer.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartRouteAnalysis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/start-route-analysis.html)」を参照してください。

### `tag-resource`
<a name="networkmanager_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを適用するには**  
次の `tag-resource` の例では、タグ `Network=Northeast` をデバイス `device-07f6fd08867abc123` に適用します。  

```
aws networkmanager tag-resource \
    --resource-arn arn:aws:networkmanager::123456789012:device/global-network-01231231231231231/device-07f6fd08867abc123 \
    --tags Key=Network,Value=Northeast \
    --region us-west-2
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="networkmanager_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除する**  
次の `untag-resource` の例では、キー `Network` のタグをデバイス `device-07f6fd08867abc123` から削除します。  

```
aws networkmanager untag-resource \
    --resource-arn arn:aws:networkmanager::123456789012:device/global-network-01231231231231231/device-07f6fd08867abc123 ]
    --tag-keys Network \
    --region us-west-2
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/untag-resource.html)」を参照してください。

### `update-device`
<a name="networkmanager_UpdateDevice_cli_2_topic"></a>

次のコード例は、`update-device` を使用する方法を示しています。

**AWS CLI**  
**デバイスを更新するには**  
次の `update-device` の例では、デバイスのサイト ID を指定してデバイス `device-07f6fd08867abc123` を更新します。  

```
aws networkmanager update-device \
    --global-network-id global-network-01231231231231231 \
    --device-id device-07f6fd08867abc123 \
    --site-id site-444555aaabbb11223 \
    --region us-west-2
```
出力:  

```
{
    "Device": {
        "DeviceId": "device-07f6fd08867abc123",
        "DeviceArn": "arn:aws:networkmanager::123456789012:device/global-network-01231231231231231/device-07f6fd08867abc123",
        "GlobalNetworkId": "global-network-01231231231231231",
        "Description": "NY office device",
        "Type": "Office device",
        "Vendor": "anycompany",
        "Model": "abcabc",
        "SerialNumber": "1234",
        "SiteId": "site-444555aaabbb11223",
        "CreatedAt": 1575554005.0,
        "State": "UPDATING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Devices](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-devices)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDevice](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/update-device.html)」を参照してください。

### `update-global-network`
<a name="networkmanager_UpdateGlobalNetwork_cli_2_topic"></a>

次のコード例は、`update-global-network` を使用する方法を示しています。

**AWS CLI**  
**グローバルネットワークを更新するには**  
次の `update-global-network` の例では、グローバルネットワーク `global-network-01231231231231231` の説明を更新します。  

```
aws networkmanager update-global-network \
    --global-network-id global-network-01231231231231231 \
    --description "Head offices" \
    --region us-west-2
```
出力:  

```
{
    "GlobalNetwork": {
        "GlobalNetworkId": "global-network-01231231231231231",
        "GlobalNetworkArn": "arn:aws:networkmanager::123456789012:global-network/global-network-01231231231231231",
        "Description": "Head offices",
        "CreatedAt": 1575553525.0,
        "State": "UPDATING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Global Networks](https://docs.aws.amazon.com/vpc/latest/tgw/global-networks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGlobalNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/update-global-network.html)」を参照してください。

### `update-link`
<a name="networkmanager_UpdateLink_cli_2_topic"></a>

次のコード例は、`update-link` を使用する方法を示しています。

**AWS CLI**  
**リンクを更新するには**  
次の `update-link` の例では、リンク `link-11112222aaaabbbb1` の帯域幅情報を更新します。  

```
aws networkmanager update-link \
    --global-network-id global-network-01231231231231231 \
    --link-id link-11112222aaaabbbb1 \
    --bandwidth  UploadSpeed=20,DownloadSpeed=20 \
    --region us-west-2
```
出力:  

```
{
    "Link": {
        "LinkId": "link-11112222aaaabbbb1",
        "LinkArn": "arn:aws:networkmanager::123456789012:link/global-network-01231231231231231/link-11112222aaaabbbb1",
        "GlobalNetworkId": "global-network-01231231231231231",
        "SiteId": "site-444555aaabbb11223",
        "Description": "VPN Link",
        "Type": "broadband",
        "Bandwidth": {
            "UploadSpeed": 20,
            "DownloadSpeed": 20
        },
        "Provider": "AnyCompany",
        "CreatedAt": 1575555811.0,
        "State": "UPDATING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Links](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-links)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateLink](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/update-link.html)」を参照してください。

### `update-site`
<a name="networkmanager_UpdateSite_cli_2_topic"></a>

次のコード例は、`update-site` を使用する方法を示しています。

**AWS CLI**  
**サイトを更新するには**  
次の `update-site` の例では、指定されたグローバルネットワークのサイト `site-444555aaabbb11223` の説明を更新します。  

```
aws networkmanager update-site \
    --global-network-id global-network-01231231231231231 \
    --site-id site-444555aaabbb11223 \
    --description "New York Office site" \
    --region us-west-2
```
出力:  

```
{
    "Site": {
        "SiteId": "site-444555aaabbb11223",
        "SiteArn": "arn:aws:networkmanager::123456789012:site/global-network-01231231231231231/site-444555aaabbb11223",
        "GlobalNetworkId": "global-network-01231231231231231",
        "Description": "New York Office site",
        "Location": {
            "Latitude": "40.7128",
            "Longitude": "-74.0060"
        },
        "CreatedAt": 1575554528.0,
        "State": "UPDATING"
    }
}
```
詳細については、「*Transit Gateway Network Manager Guide*」の「[Working with Sites](https://docs.aws.amazon.com/vpc/latest/tgw/on-premises-networks.html#working-with-sites)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSite](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/networkmanager/update-site.html)」を参照してください。

# を使用した OpenSearch Service の例 AWS CLI
<a name="cli_2_elasticsearch-service_code_examples"></a>

次のコード例は、OpenSearch Service AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-elasticsearch-domain`
<a name="elasticsearch-service_CreateElasticsearchDomain_cli_2_topic"></a>

次のコード例は、`create-elasticsearch-domain` を使用する方法を示しています。

**AWS CLI**  
**Amazon Elasticsearch Service ドメインを作成するには**  
次の `create-elasticsearch-domain` コマンドは、VPC 内に新しい Amazon Elasticsearch Service ドメインを作成し、1 人のユーザーへのアクセスを制限します。Amazon ES は、指定されたサブネットとセキュリティグループ ID から VPC ID を推測します。  

```
aws es create-elasticsearch-domain \
    --domain-name vpc-cli-example \
    --elasticsearch-version 6.2 \
    --elasticsearch-cluster-config InstanceType=m4.large.elasticsearch,InstanceCount=1 \
    --ebs-options EBSEnabled=true,VolumeType=standard,VolumeSize=10 \
    --access-policies '{"Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Principal": {"AWS": "arn:aws:iam::123456789012:root" }, "Action":"es:*", "Resource": "arn:aws:es:us-west-1:123456789012:domain/vpc-cli-example/*" } ] }' \
    --vpc-options SubnetIds=subnet-1a2a3a4a,SecurityGroupIds=sg-2a3a4a5a
```
出力:  

```
{
    "DomainStatus": {
        "ElasticsearchClusterConfig": {
            "DedicatedMasterEnabled": false,
            "InstanceCount": 1,
            "ZoneAwarenessEnabled": false,
            "InstanceType": "m4.large.elasticsearch"
        },
        "DomainId": "123456789012/vpc-cli-example",
        "CognitoOptions": {
            "Enabled": false
        },
        "VPCOptions": {
            "SubnetIds": [
                "subnet-1a2a3a4a"
            ],
            "VPCId": "vpc-3a4a5a6a",
            "SecurityGroupIds": [
                "sg-2a3a4a5a"
            ],
            "AvailabilityZones": [
                "us-west-1c"
            ]
        },
        "Created": true,
        "Deleted": false,
        "EBSOptions": {
            "VolumeSize": 10,
            "VolumeType": "standard",
            "EBSEnabled": true
        },
        "Processing": true,
        "DomainName": "vpc-cli-example",
        "SnapshotOptions": {
            "AutomatedSnapshotStartHour": 0
        },
        "ElasticsearchVersion": "6.2",
        "AccessPolicies": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:root\"},\"Action\":\"es:*\",\"Resource\":\"arn:aws:es:us-west-1:123456789012:domain/vpc-cli-example/*\"}]}",
        "AdvancedOptions": {
            "rest.action.multi.allow_explicit_index": "true"
        },
        "EncryptionAtRestOptions": {
            "Enabled": false
        },
        "ARN": "arn:aws:es:us-west-1:123456789012:domain/vpc-cli-example"
    }
}
```
詳細については、「*Amazon Elasticsearch Service デベロッパーガイド*」の「[Creating and Managing Amazon Elasticsearch Service Domains](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateElasticsearchDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/es/create-elasticsearch-domain.html)」を参照してください。

### `describe-elasticsearch-domain-config`
<a name="elasticsearch-service_DescribeElasticsearchDomainConfig_cli_2_topic"></a>

次のコード例は、`describe-elasticsearch-domain-config` を使用する方法を示しています。

**AWS CLI**  
**ドメイン設定の詳細を取得するには**  
次の `describe-elasticsearch-domain-config` の例では、特定のドメインの設定の詳細と、各ドメインコンポーネントのステータス情報を示します。  

```
aws es describe-elasticsearch-domain-config \
    --domain-name cli-example
```
出力:  

```
{
    "DomainConfig": {
        "ElasticsearchVersion": {
            "Options": "7.4",
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "ElasticsearchClusterConfig": {
            "Options": {
                "InstanceType": "c5.large.elasticsearch",
                "InstanceCount": 1,
                "DedicatedMasterEnabled": true,
                "ZoneAwarenessEnabled": false,
                "DedicatedMasterType": "c5.large.elasticsearch",
                "DedicatedMasterCount": 3,
                "WarmEnabled": true,
                "WarmType": "ultrawarm1.medium.elasticsearch",
                "WarmCount": 2
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "EBSOptions": {
            "Options": {
                "EBSEnabled": true,
                "VolumeType": "gp2",
                "VolumeSize": 10
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "AccessPolicies": {
            "Options": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":\"es:*\",\"Resource\":\"arn:aws:es:us-east-1:123456789012:domain/cli-example/*\"}]}",
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "SnapshotOptions": {
            "Options": {
                "AutomatedSnapshotStartHour": 0
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "VPCOptions": {
            "Options": {},
            "Status": {
                "CreationDate": 1591210426.162,
                "UpdateDate": 1591210426.162,
                "UpdateVersion": 18,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "CognitoOptions": {
            "Options": {
                "Enabled": false
            },
            "Status": {
                "CreationDate": 1591210426.163,
                "UpdateDate": 1591210426.163,
                "UpdateVersion": 18,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "EncryptionAtRestOptions": {
            "Options": {
                "Enabled": true,
                "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/1a2a3a4a-1a2a-1a2a-1a2a-1a2a3a4a5a6a"
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "NodeToNodeEncryptionOptions": {
            "Options": {
                "Enabled": true
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "AdvancedOptions": {
            "Options": {
                "rest.action.multi.allow_explicit_index": "true"
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "LogPublishingOptions": {
            "Options": {},
            "Status": {
                "CreationDate": 1591210426.164,
                "UpdateDate": 1591210426.164,
                "UpdateVersion": 18,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "DomainEndpointOptions": {
            "Options": {
                "EnforceHTTPS": true,
                "TLSSecurityPolicy": "Policy-Min-TLS-1-0-2019-07"
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589395827.325,
                "UpdateVersion": 8,
                "State": "Active",
                "PendingDeletion": false
            }
        },
        "AdvancedSecurityOptions": {
            "Options": {
                "Enabled": true,
                "InternalUserDatabaseEnabled": true
            },
            "Status": {
                "CreationDate": 1589395034.946,
                "UpdateDate": 1589827485.577,
                "UpdateVersion": 14,
                "State": "Active",
                "PendingDeletion": false
            }
        }
    }
}
```
詳細については、「*Amazon Elasticsearch Service デベロッパーガイド*」の「[Creating and Managing Amazon Elasticsearch Service Domains](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeElasticsearchDomainConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/es/describe-elasticsearch-domain-config.html)」を参照してください。

### `describe-elasticsearch-domain`
<a name="elasticsearch-service_DescribeElasticsearchDomain_cli_2_topic"></a>

次のコード例は、`describe-elasticsearch-domain` を使用する方法を示しています。

**AWS CLI**  
**単一ドメインの詳細を取得するには**  
次の `describe-elasticsearch-domain` の例では、特定のドメインの設定の詳細を示します。  

```
aws es describe-elasticsearch-domain \
    --domain-name cli-example
```
出力:  

```
{
    "DomainStatus": {
        "DomainId": "123456789012/cli-example",
        "DomainName": "cli-example",
        "ARN": "arn:aws:es:us-east-1:123456789012:domain/cli-example",
        "Created": true,
        "Deleted": false,
        "Endpoint": "search-cli-example-1a2a3a4a5a6a7a8a9a0a.us-east-1.es.amazonaws.com",
        "Processing": false,
        "UpgradeProcessing": false,
        "ElasticsearchVersion": "7.4",
        "ElasticsearchClusterConfig": {
            "InstanceType": "c5.large.elasticsearch",
            "InstanceCount": 1,
            "DedicatedMasterEnabled": true,
            "ZoneAwarenessEnabled": false,
            "DedicatedMasterType": "c5.large.elasticsearch",
            "DedicatedMasterCount": 3,
            "WarmEnabled": true,
            "WarmType": "ultrawarm1.medium.elasticsearch",
            "WarmCount": 2
        },
        "EBSOptions": {
            "EBSEnabled": true,
            "VolumeType": "gp2",
            "VolumeSize": 10
        },
        "AccessPolicies": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":\"es:*\",\"Resource\":\"arn:aws:es:us-east-1:123456789012:domain/cli-example/*\"}]}",
        "SnapshotOptions": {
            "AutomatedSnapshotStartHour": 0
        },
        "CognitoOptions": {
            "Enabled": false
        },
        "EncryptionAtRestOptions": {
            "Enabled": true,
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/1a2a3a4a-1a2a-1a2a-1a2a-1a2a3a4a5a6a"
        },
        "NodeToNodeEncryptionOptions": {
            "Enabled": true
        },
        "AdvancedOptions": {
            "rest.action.multi.allow_explicit_index": "true"
        },
        "ServiceSoftwareOptions": {
            "CurrentVersion": "R20200522",
            "NewVersion": "",
            "UpdateAvailable": false,
            "Cancellable": false,
            "UpdateStatus": "COMPLETED",
            "Description": "There is no software update available for this domain.",
            "AutomatedUpdateDate": 0.0
        },
        "DomainEndpointOptions": {
            "EnforceHTTPS": true,
            "TLSSecurityPolicy": "Policy-Min-TLS-1-0-2019-07"
        },
        "AdvancedSecurityOptions": {
            "Enabled": true,
            "InternalUserDatabaseEnabled": true
        }
    }
}
```
詳細については、「*Amazon Elasticsearch Service デベロッパーガイド*」の「[Creating and Managing Amazon Elasticsearch Service Domains](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeElasticsearchDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/es/describe-elasticsearch-domain.html)」を参照してください。

### `describe-elasticsearch-domains`
<a name="elasticsearch-service_DescribeElasticsearchDomains_cli_2_topic"></a>

次のコード例は、`describe-elasticsearch-domains` を使用する方法を示しています。

**AWS CLI**  
**1 つ以上のドメインの詳細を取得するには**  
次の `describe-elasticsearch-domains` の例では、1 つ以上のドメインの設定の詳細を示します。  

```
aws es describe-elasticsearch-domains \
    --domain-names cli-example-1 cli-example-2
```
出力:  

```
{
    "DomainStatusList": [{
            "DomainId": "123456789012/cli-example-1",
            "DomainName": "cli-example-1",
            "ARN": "arn:aws:es:us-east-1:123456789012:domain/cli-example-1",
            "Created": true,
            "Deleted": false,
            "Endpoint": "search-cli-example-1-1a2a3a4a5a6a7a8a9a0a.us-east-1.es.amazonaws.com",
            "Processing": false,
            "UpgradeProcessing": false,
            "ElasticsearchVersion": "7.4",
            "ElasticsearchClusterConfig": {
                "InstanceType": "c5.large.elasticsearch",
                "InstanceCount": 1,
                 "DedicatedMasterEnabled": true,
                "ZoneAwarenessEnabled": false,
                "DedicatedMasterType": "c5.large.elasticsearch",
                "DedicatedMasterCount": 3,
                "WarmEnabled": true,
                "WarmType": "ultrawarm1.medium.elasticsearch",
                "WarmCount": 2
            },
            "EBSOptions": {
                "EBSEnabled": true,
                "VolumeType": "gp2",
                "VolumeSize": 10
            },
            "AccessPolicies": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":\"es:*\",\"Resource\":\"arn:aws:es:us-east-1:123456789012:domain/cli-example-1/*\"}]}",
            "SnapshotOptions": {
                "AutomatedSnapshotStartHour": 0
            },
            "CognitoOptions": {
                "Enabled": false
            },
            "EncryptionAtRestOptions": {
                "Enabled": true,
                "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/1a2a3a4a-1a2a-1a2a-1a2a-1a2a3a4a5a6a"
            },
            "NodeToNodeEncryptionOptions": {
                "Enabled": true
            },
            "AdvancedOptions": {
                "rest.action.multi.allow_explicit_index": "true"
            },
            "ServiceSoftwareOptions": {
                "CurrentVersion": "R20200522",
                "NewVersion": "",
                "UpdateAvailable": false,
                "Cancellable": false,
                "UpdateStatus": "COMPLETED",
                "Description": "There is no software update available for this domain.",
                "AutomatedUpdateDate": 0.0
            },
            "DomainEndpointOptions": {
                "EnforceHTTPS": true,
                "TLSSecurityPolicy": "Policy-Min-TLS-1-0-2019-07"
            },
            "AdvancedSecurityOptions": {
                "Enabled": true,
                "InternalUserDatabaseEnabled": true
            }
        },
        {
            "DomainId": "123456789012/cli-example-2",
            "DomainName": "cli-example-2",
            "ARN": "arn:aws:es:us-east-1:123456789012:domain/cli-example-2",
            "Created": true,
            "Deleted": false,
            "Processing": true,
            "UpgradeProcessing": false,
            "ElasticsearchVersion": "7.4",
            "ElasticsearchClusterConfig": {
                "InstanceType": "r5.large.elasticsearch",
                "InstanceCount": 1,
                "DedicatedMasterEnabled": false,
                "ZoneAwarenessEnabled": false,
                "WarmEnabled": false
            },
            "EBSOptions": {
                "EBSEnabled": true,
                "VolumeType": "gp2",
                "VolumeSize": 10
            },
            "AccessPolicies": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":{\"AWS\":\"*\"},\"Action\":\"es:*\",\"Resource\":\"arn:aws:es:us-east-1:123456789012:domain/cli-example-2/*\"}]}",
            "SnapshotOptions": {
                "AutomatedSnapshotStartHour": 0
            },
            "CognitoOptions": {
                "Enabled": false
            },
            "EncryptionAtRestOptions": {
                "Enabled": false
            },
            "NodeToNodeEncryptionOptions": {
                "Enabled": false
            },
            "AdvancedOptions": {
                "rest.action.multi.allow_explicit_index": "true"
            },
            "ServiceSoftwareOptions": {
                "CurrentVersion": "",
                "NewVersion": "",
                "UpdateAvailable": false,
                "Cancellable": false,
                "UpdateStatus": "COMPLETED",
                "Description": "There is no software update available for this domain.",
                "AutomatedUpdateDate": 0.0
            },
            "DomainEndpointOptions": {
                "EnforceHTTPS": false,
                "TLSSecurityPolicy": "Policy-Min-TLS-1-0-2019-07"
            },
            "AdvancedSecurityOptions": {
                "Enabled": false,
                "InternalUserDatabaseEnabled": false
            }
        }
    ]
}
```
詳細については、「*Amazon Elasticsearch Service デベロッパーガイド*」の「[Creating and Managing Amazon Elasticsearch Service Domains](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeElasticsearchDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/es/describe-elasticsearch-domains.html)」を参照してください。

### `describe-reserved-elasticsearch-instances`
<a name="elasticsearch-service_DescribeReservedElasticsearchInstances_cli_2_topic"></a>

次のコード例は、`describe-reserved-elasticsearch-instances` を使用する方法を示しています。

**AWS CLI**  
**すべての予約済みインスタンスを表示するには**  
次の `describe-elasticsearch-domains` の例は、リージョンで予約したすべてのインスタンスの概要を示しています。  

```
aws es describe-reserved-elasticsearch-instances
```
出力:  

```
{
    "ReservedElasticsearchInstances": [{
        "FixedPrice": 100.0,
        "ReservedElasticsearchInstanceOfferingId": "1a2a3a4a5-1a2a-3a4a-5a6a-1a2a3a4a5a6a",
        "ReservationName": "my-reservation",
        "PaymentOption": "PARTIAL_UPFRONT",
        "UsagePrice": 0.0,
        "ReservedElasticsearchInstanceId": "9a8a7a6a-5a4a-3a2a-1a0a-9a8a7a6a5a4a",
        "RecurringCharges": [{
            "RecurringChargeAmount": 0.603,
            "RecurringChargeFrequency": "Hourly"
        }],
        "State": "payment-pending",
        "StartTime": 1522872571.229,
        "ElasticsearchInstanceCount": 3,
        "Duration": 31536000,
        "ElasticsearchInstanceType": "m4.2xlarge.elasticsearch",
        "CurrencyCode": "USD"
    }]
}
```
詳細については、「Amazon Elasticsearch Service デベロッパーガイド」の「[Reserved Instances](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/aes-ri.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedElasticsearchInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/es/describe-reserved-elasticsearch-instances.html)」を参照してください。

### `list-domain-names`
<a name="elasticsearch-service_ListDomainNames_cli_2_topic"></a>

次のコード例は、`list-domain-names` を使用する方法を示しています。

**AWS CLI**  
**すべてのドメインを一覧表示するには**  
次の `list-domain-names` の例は、リージョン内のすべてのドメインの簡単な概要を示します。  

```
aws es list-domain-names
```
出力:  

```
{
    "DomainNames": [{
            "DomainName": "cli-example-1"
        },
        {
            "DomainName": "cli-example-2"
        }
    ]
}
```
詳細については、「*Amazon Elasticsearch Service デベロッパーガイド*」の「[Creating and Managing Amazon Elasticsearch Service Domains](https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-createupdatedomains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDomainNames](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/es/list-domain-names.html)」を参照してください。

# を使用した Organizations の例 AWS CLI
<a name="cli_2_organizations_code_examples"></a>

次のコード例は、Organizations AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-handshake`
<a name="organizations_AcceptHandshake_cli_2_topic"></a>

次のコード例は、`accept-handshake` を使用する方法を示しています。

**AWS CLI**  
**別のアカウントからハンドシェイクを受け入れるには**  
組織の所有者である Bill は、以前に Juan のアカウントを組織に参加するよう招待しました。次の例は、Juan のアカウントがハンドシェイクを受け入れ、招待に同意したことを示しています。  

```
aws organizations accept-handshake --handshake-id h-examplehandshakeid111
```
出力は、次のように表示されます。  

```
{
        "Handshake": {
                "Action": "INVITE",
                "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111",
                "RequestedTimestamp": 1481656459.257,
                "ExpirationTimestamp": 1482952459.257,
                "Id": "h-examplehandshakeid111",
                "Parties": [
                        {
                                "Id": "o-exampleorgid",
                                "Type": "ORGANIZATION"
                        },
                        {
                                "Id": "juan@example.com",
                                "Type": "EMAIL"
                        }
                ],
                "Resources": [
                        {
                                "Resources": [
                                        {
                                                "Type": "MASTER_EMAIL",
                                                "Value": "bill@amazon.com"
                                        },
                                        {
                                                "Type": "MASTER_NAME",
                                                "Value": "Org Master Account"
                                        },
                                        {
                                                "Type": "ORGANIZATION_FEATURE_SET",
                                                "Value": "ALL"
                                        }
                                ],
                                "Type": "ORGANIZATION",
                                "Value": "o-exampleorgid"
                        },
                        {
                                "Type": "EMAIL",
                                "Value": "juan@example.com"
                        }
                ],
                "State": "ACCEPTED"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptHandshake](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/accept-handshake.html)」を参照してください。

### `attach-policy`
<a name="organizations_AttachPolicy_cli_2_topic"></a>

次のコード例は、`attach-policy` を使用する方法を示しています。

**AWS CLI**  
**root、OU、またはアカウントにポリシーをアタッチするには**  
**例 1**  
次の例は、サービスコントロールポリシーを OU にアタッチする方法を示しています。  

```
aws organizations attach-policy
                --policy-id p-examplepolicyid111
                --target-id ou-examplerootid111-exampleouid111
```
**例 2**  
次の例は、サービスコントロールポリシーをアカウントに直接アタッチする方法を示しています。  

```
aws organizations attach-policy
                --policy-id p-examplepolicyid111
                --target-id 333333333333
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[AttachPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/attach-policy.html)」を参照してください。**

### `cancel-handshake`
<a name="organizations_CancelHandshake_cli_2_topic"></a>

次のコード例は、`cancel-handshake` を使用する方法を示しています。

**AWS CLI**  
**別のアカウントから送信されたハンドシェイクをキャンセルするには**  
Bill は以前に、Susan のアカウントに組織に参加する招待を送信しました。Susan が承諾する前に、Bill は考えを変え、招待をキャンセルすることにしました。次の例は、Bill のキャンセルを示しています。  

```
aws organizations cancel-handshake --handshake-id h-examplehandshakeid111
```
出力には、現在の状態が `CANCELED` であることを示すハンドシェイクオブジェクトが含まれます。  

```
{
        "Handshake": {
                "Id": "h-examplehandshakeid111",
                "State":"CANCELED",
                "Action": "INVITE",
                "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111",
                "Parties": [
                        {
                                "Id": "o-exampleorgid",
                                "Type": "ORGANIZATION"
                        },
                        {
                                "Id": "susan@example.com",
                                "Type": "EMAIL"
                        }
                ],
                "Resources": [
                        {
                                "Type": "ORGANIZATION",
                                "Value": "o-exampleorgid",
                                "Resources": [
                                        {
                                                "Type": "MASTER_EMAIL",
                                                "Value": "bill@example.com"
                                        },
                                        {
                                                "Type": "MASTER_NAME",
                                                "Value": "Master Account"
                                        },
                                        {
                                                "Type": "ORGANIZATION_FEATURE_SET",
                                                "Value": "CONSOLIDATED_BILLING"
                                        }
                                ]
                        },
                        {
                                "Type": "EMAIL",
                                "Value": "anika@example.com"
                        },
                        {
                                "Type": "NOTES",
                                "Value": "This is a request for Susan's account to join Bob's organization."
                        }
                ],
                "RequestedTimestamp": 1.47008383521E9,
                "ExpirationTimestamp": 1.47137983521E9
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelHandshake](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/cancel-handshake.html)」を参照してください。

### `create-account`
<a name="organizations_CreateAccount_cli_2_topic"></a>

次のコード例は、`create-account` を使用する方法を示しています。

**AWS CLI**  
**自動的に組織の一部となるメンバーアカウントを作成するには**  
次の例は、組織のメンバーアカウントを作成する方法を示しています。メンバーアカウントは、「プロダクションアカウント」という名前と E メールアドレス (susan@example.com) で構成されます。roleName パラメータが指定されていないため、Organizations では OrganizationAccountAccessRole というデフォルト名を使用して IAM ロールが自動的に作成されます。また、IamUserAccessToBilling パラメータが指定されていないため、必要な権限を持つ IAM ユーザーまたはロールにアカウントの請求データへのアクセスを許可する設定には、デフォルト値 ALLOW が使用されます。Organizations はスーザンに「ようこそ AWS」という E メールを自動的に送信します。  

```
aws organizations create-account --email susan@example.com --account-name "Production Account"
```
出力には、ステータスが現在の `IN_PROGRESS` 状態であることを示すリクエストオブジェクトが含まれます。  

```
{
        "CreateAccountStatus": {
                "State": "IN_PROGRESS",
                "Id": "car-examplecreateaccountrequestid111"
        }
}
```
describe-create-account-status コマンドに Id レスポンス値を create-account-request-id parameter の値として指定することで、後でリクエストの現在のステータスをクエリすることができます。  
詳細については、「 Organizations ユーザーガイド」の「組織での AWS アカウントの作成」を参照してください。 *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-account.html)」を参照してください。**

### `create-organization`
<a name="organizations_CreateOrganization_cli_2_topic"></a>

次のコード例は、`create-organization` を使用する方法を示しています。

**AWS CLI**  
**例 1: 新しい組織を作成するには**  
Bill は、アカウント 111111111111 の認証情報を使用して組織を作成したいと考えています。次の例は、このアカウントが新しい組織のマスターアカウントになることを示しています。Bill は機能セットを指定していないため、新しい組織ではデフォルトですべての機能が有効になり、サービスコントロールポリシーがルート上で有効になります。  

```
aws organizations create-organization
```
出力には、新しい組織に関する詳細を含む組織オブジェクトが含まれます。  

```
{
        "Organization": {
                "AvailablePolicyTypes": [
                        {
                                "Status": "ENABLED",
                                "Type": "SERVICE_CONTROL_POLICY"
                        }
                ],
                "MasterAccountId": "111111111111",
                "MasterAccountArn": "arn:aws:organizations::111111111111:account/o-exampleorgid/111111111111",
                "MasterAccountEmail": "bill@example.com",
                "FeatureSet": "ALL",
                "Id": "o-exampleorgid",
                "Arn": "arn:aws:organizations::111111111111:organization/o-exampleorgid"
        }
}
```
**例 2: 一括決済機能のみを有効にした新しい組織を作成するには**  
次の例では、一括決済機能のみをサポートする組織を作成します。  

```
aws organizations create-organization --feature-set CONSOLIDATED_BILLING
```
出力には、新しい組織に関する詳細を含む組織オブジェクトが含まれます。  

```
{
        "Organization": {
                "Arn": "arn:aws:organizations::111111111111:organization/o-exampleorgid",
                "AvailablePolicyTypes": [],
                "Id": "o-exampleorgid",
                "MasterAccountArn": "arn:aws:organizations::111111111111:account/o-exampleorgid/111111111111",
                "MasterAccountEmail": "bill@example.com",
                "MasterAccountId": "111111111111",
                "FeatureSet": "CONSOLIDATED_BILLING"
        }
}
```
詳細については、「AWS Organizations ユーザーガイド」の「Creating an Organization」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-organization.html)」を参照してください。**

### `create-organizational-unit`
<a name="organizations_CreateOrganizationalUnit_cli_2_topic"></a>

次のコード例は、`create-organizational-unit` を使用する方法を示しています。

**AWS CLI**  
**ルート OU または親 OU に OU を作成するには**  
次の例は、AccountingOU という名前の OU を作成する方法を示しています。  

```
aws organizations create-organizational-unit --parent-id r-examplerootid111 --name AccountingOU
```
出力には、新しい OU に関する詳細を含む organizationalUnit オブジェクトが含まれます。  

```
{
        "OrganizationalUnit": {
                "Id": "ou-examplerootid111-exampleouid111",
                "Arn": "arn:aws:organizations::111111111111:ou/o-exampleorgid/ou-examplerootid111-exampleouid111",
                "Name": "AccountingOU"
        }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateOrganizationalUnit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-organizational-unit.html)」を参照してください。**

### `create-policy`
<a name="organizations_CreatePolicy_cli_2_topic"></a>

次のコード例は、`create-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: JSON ポリシーのテキストソースファイルを使用してポリシーを作成するには**  
次の例は、`AllowAllS3Actions` という名前のサービスコントロールポリシーを作成する方法を示しています。ポリシーの内容は、`policy.json` というローカルコンピューター上のファイルから取得されます。  

```
aws organizations create-policy --content file://policy.json --name AllowAllS3Actions, --type SERVICE_CONTROL_POLICY --description "Allows delegation of all S3 actions"
```
出力には、新しいポリシーの詳細を含むポリシーオブジェクトが含まれます。  

```
{
        "Policy": {
                "Content": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}",
                "PolicySummary": {
                        "Arn": "arn:aws:organizations::o-exampleorgid:policy/service_control_policy/p-examplepolicyid111",
                        "Description": "Allows delegation of all S3 actions",
                        "Name": "AllowAllS3Actions",
                        "Type":"SERVICE_CONTROL_POLICY"
                }
        }
}
```
**例 2: JSON ポリシーをパラメータとしてポリシーを作成するには**  
次の例は、ポリシーの内容を JSON 文字列としてパラメータに埋め込むことで、同じ SCP を作成する方法を示しています。文字列は、パラメータ内でリテラルとして扱われるように、二重引用符の前にバックスラッシュを付けてエスケープする必要があります。パラメータ自体も二重引用符で囲みます。  

```
aws organizations create-policy --content "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}" --name AllowAllS3Actions --type SERVICE_CONTROL_POLICY --description "Allows delegation of all S3 actions"
```
Organizations でのポリシーの作成と使用の詳細については、「*AWS Organizations ユーザーガイド*」の「Organizations のポリシーの管理」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/create-policy.html)」を参照してください。

### `decline-handshake`
<a name="organizations_DeclineHandshake_cli_2_topic"></a>

次のコード例は、`decline-handshake` を使用する方法を示しています。

**AWS CLI**  
**別のアカウントから送信されたハンドシェイクを拒否するには**  
次の例は、アカウント 222222222222 の所有者である管理者である Susan が、Bill の組織への招待を拒否したことを示しています。DeclineHandshake オペレーションはハンドシェイクオブジェクトを返し、状態が DECLINED になったことを示します。  

```
aws organizations decline-handshake --handshake-id h-examplehandshakeid111
```
出力には、新しい状態 `DECLINED` を示すハンドシェイクオブジェクトが含まれます。  

```
{
        "Handshake": {
                "Id": "h-examplehandshakeid111",
                "State": "DECLINED",
                "Resources": [
                        {
                                "Type": "ORGANIZATION",
                                "Value": "o-exampleorgid",
                                "Resources": [
                                        {
                                                "Type": "MASTER_EMAIL",
                                                "Value": "bill@example.com"
                                        },
                                        {
                                                "Type": "MASTER_NAME",
                                                "Value": "Master Account"
                                        }
                                ]
                        },
                        {
                                "Type": "EMAIL",
                                "Value": "susan@example.com"
                        },
                        {
                                "Type": "NOTES",
                                "Value": "This is an invitation to Susan's account to join the Bill's organization."
                        }
                ],
                "Parties": [
                        {
                                "Type": "EMAIL",
                                "Id": "susan@example.com"
                        },
                        {
                                "Type": "ORGANIZATION",
                                "Id": "o-exampleorgid"
                        }
                ],
                "Action": "INVITE",
                "RequestedTimestamp": 1470684478.687,
                "ExpirationTimestamp": 1471980478.687,
                "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeclineHandshake](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/decline-handshake.html)」を参照してください。

### `delete-organization`
<a name="organizations_DeleteOrganization_cli_2_topic"></a>

次のコード例は、`delete-organization` を使用する方法を示しています。

**AWS CLI**  
**組織を削除するには**  
次の例は、組織を削除する方法を示しています。この操作を実行するには、組織のマスターアカウントの管理者である必要があります。この例では、組織からメンバーアカウント、OU、ポリシーをすべて削除済みであることを前提としています。  

```
aws organizations delete-organization
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/delete-organization.html)」を参照してください。**

### `delete-organizational-unit`
<a name="organizations_DeleteOrganizationalUnit_cli_2_topic"></a>

次のコード例は、`delete-organizational-unit` を使用する方法を示しています。

**AWS CLI**  
**OU を削除するには**  
次の例は、OU を削除する方法を示しています。この例では、OU からすべてのアカウントと他の OU を削除済みであることを前提としています。  

```
aws organizations delete-organizational-unit --organizational-unit-id ou-examplerootid111-exampleouid111
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteOrganizationalUnit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/delete-organizational-unit.html)」を参照してください。**

### `delete-policy`
<a name="organizations_DeletePolicy_cli_2_topic"></a>

次のコード例は、`delete-policy` を使用する方法を示しています。

**AWS CLI**  
**ポリシーを削除するには**  
次の例は、組織からポリシーを削除する方法を示しています。この例では、ポリシーをすべてのエンティティから事前にデタッチしたことを前提としています。  

```
aws organizations delete-policy --policy-id p-examplepolicyid111
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/delete-policy.html)」を参照してください。

### `describe-account`
<a name="organizations_DescribeAccount_cli_2_topic"></a>

次のコード例は、`describe-account` を使用する方法を示しています。

**AWS CLI**  
**アカウントの詳細を取得するには**  
次の例は、アカウントの詳細をリクエストする方法を示しています。  

```
aws organizations describe-account --account-id 555555555555
```
出力には、アカウントに関する詳細を含むアカウントオブジェクトが表示されます。  

```
{
        "Account": {
                "Id": "555555555555",
                "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/555555555555",
                "Name": "Beta account",
                "Email": "anika@example.com",
                "JoinedMethod": "INVITED",
                "JoinedTimeStamp": 1481756563.134,
                "Status": "ACTIVE"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/describe-account.html)」を参照してください。

### `describe-create-account-status`
<a name="organizations_DescribeCreateAccountStatus_cli_2_topic"></a>

次のコード例は、`describe-create-account-status` を使用する方法を示しています。

**AWS CLI**  
**アカウントの作成リクエストに関する最新のステータスを取得するには**  
次の例は、以前のリクエストの最新ステータスを依頼して組織内にアカウントを作成する方法を示しています。指定された --request-id は、create-account への元の呼び出しのレスポンスから得られたものです。アカウント作成リクエストは、Organizations がアカウントの作成を正常に完了したことをステータスフィールドで表示します。  
コマンド:  

```
aws organizations describe-create-account-status --create-account-request-id car-examplecreateaccountrequestid111
```
出力:  

```
{
  "CreateAccountStatus": {
    "State": "SUCCEEDED",
    "AccountId": "555555555555",
    "AccountName": "Beta account",
    "RequestedTimestamp": 1470684478.687,
    "CompletedTimestamp": 1470684532.472,
    "Id": "car-examplecreateaccountrequestid111"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCreateAccountStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/describe-create-account-status.html)」を参照してください。

### `describe-handshake`
<a name="organizations_DescribeHandshake_cli_2_topic"></a>

次のコード例は、`describe-handshake` を使用する方法を示しています。

**AWS CLI**  
**ハンドシェイクに関する情報を取得するには**  
次の例は、ハンドシェイクの詳細をリクエストする方法を示しています。ハンドシェイク ID は、`InviteAccountToOrganization` への元の呼び出しか、`ListHandshakesForAccount` または `ListHandshakesForOrganization` への呼び出しから得られたものです。  

```
aws organizations describe-handshake --handshake-id h-examplehandshakeid111
```
出力には、リクエストされたハンドシェイクに関するすべての詳細を含むハンドシェイクオブジェクトが含まれます。  

```
{
        "Handshake": {
                "Id": "h-examplehandshakeid111",
                "State": "OPEN",
                "Resources": [
                        {
                                "Type": "ORGANIZATION",
                                "Value": "o-exampleorgid",
                                "Resources": [
                                        {
                                                "Type": "MASTER_EMAIL",
                                                "Value": "bill@example.com"
                                        },
                                        {
                                                "Type": "MASTER_NAME",
                                                "Value": "Master Account"
                                        }
                                ]
                        },
                        {
                                "Type": "EMAIL",
                                "Value": "anika@example.com"
                        }
                ],
                "Parties": [
                        {
                                "Type": "ORGANIZATION",
                                "Id": "o-exampleorgid"
                        },
                        {
                                "Type": "EMAIL",
                                "Id": "anika@example.com"
                        }
                ],
                "Action": "INVITE",
                "RequestedTimestamp": 1470158698.046,
                "ExpirationTimestamp": 1471454698.046,
                "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHandshake](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/describe-handshake.html)」を参照してください。

### `describe-organization`
<a name="organizations_DescribeOrganization_cli_2_topic"></a>

次のコード例は、`describe-organization` を使用する方法を示しています。

**AWS CLI**  
**現在の組織に関する情報を取得するには**  
次の例は、組織の詳細をリクエストする方法を示しています。  

```
aws organizations describe-organization
```
出力には、組織に関する詳細を含む組織オブジェクトが含まれます。  

```
{
        "Organization": {
                "MasterAccountArn": "arn:aws:organizations::111111111111:account/o-exampleorgid/111111111111",
                "MasterAccountEmail": "bill@example.com",
                "MasterAccountId": "111111111111",
                "Id": "o-exampleorgid",
                "FeatureSet": "ALL",
                "Arn": "arn:aws:organizations::111111111111:organization/o-exampleorgid",
                "AvailablePolicyTypes": [
                        {
                                "Status": "ENABLED",
                                "Type": "SERVICE_CONTROL_POLICY"
                        }
                ]
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/describe-organization.html)」を参照してください。

### `describe-organizational-unit`
<a name="organizations_DescribeOrganizationalUnit_cli_2_topic"></a>

次のコード例は、`describe-organizational-unit` を使用する方法を示しています。

**AWS CLI**  
**OU に関する情報を取得するには**  
次の `describe-organizational-unit` の例では、OU の詳細をリクエストします。  

```
aws organizations describe-organizational-unit \
    --organizational-unit-id ou-examplerootid111-exampleouid111
```
出力:  

```
{
    "OrganizationalUnit": {
        "Name": "Accounting Group",
        "Arn": "arn:aws:organizations::123456789012:ou/o-exampleorgid/ou-examplerootid111-exampleouid111",
        "Id": "ou-examplerootid111-exampleouid111"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOrganizationalUnit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/describe-organizational-unit.html)」を参照してください。

### `describe-policy`
<a name="organizations_DescribePolicy_cli_2_topic"></a>

次のコード例は、`describe-policy` を使用する方法を示しています。

**AWS CLI**  
**ポリシーに関する情報を取得するには**  
次の例は、ポリシーに関する情報をリクエストする方法を示しています。  

```
aws organizations describe-policy --policy-id p-examplepolicyid111
```
出力には、ポリシーの詳細を含むポリシーオブジェクトが含まれます。  

```
{
        "Policy": {
                "Content": "{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Action\": \"*\",\n      \"Resource\": \"*\"\n    }\n  ]\n}",
                "PolicySummary": {
                        "Arn": "arn:aws:organizations::111111111111:policy/o-exampleorgid/service_control_policy/p-examplepolicyid111",
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Id": "p-examplepolicyid111",
                        "AwsManaged": false,
                        "Name": "AllowAllS3Actions",
                        "Description": "Enables admins to delegate S3 permissions"
                }
        }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/describe-policy.html)」を参照してください。**

### `detach-policy`
<a name="organizations_DetachPolicy_cli_2_topic"></a>

次のコード例は、`detach-policy` を使用する方法を示しています。

**AWS CLI**  
**root、OU、またはアカウントからポリシーをデタッチするには**  
次のコード例は、OU からポリシーをデタッチする方法を示しています。  

```
aws organizations  detach-policy  --target-id ou-examplerootid111-exampleouid111 --policy-id p-examplepolicyid111
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetachPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/detach-policy.html)」を参照してください。**

### `disable-policy-type`
<a name="organizations_DisablePolicyType_cli_2_topic"></a>

次のコード例は、`disable-policy-type` を使用する方法を示しています。

**AWS CLI**  
**ルートのポリシータイプを無効にするには**  
次の例は、ルートでサービスコントロールポリシー (SCP) ポリシータイプを無効にする方法を示しています。  

```
aws organizations disable-policy-type --root-id r-examplerootid111 --policy-type SERVICE_CONTROL_POLICY
```
出力は、PolicyTypes レスポンス要素に SERVICE\$1CONTROL\$1POLICY が含まれなくなったことを示します。  

```
{
        "Root": {
                "PolicyTypes": [],
                "Name": "Root",
                "Id": "r-examplerootid111",
                "Arn": "arn:aws:organizations::111111111111:root/o-exampleorgid/r-examplerootid111"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisablePolicyType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/disable-policy-type.html)」を参照してください。

### `enable-all-features`
<a name="organizations_EnableAllFeatures_cli_2_topic"></a>

次のコード例は、`enable-all-features` を使用する方法を示しています。

**AWS CLI**  
**組織内のすべての機能を有効にするには**  
この例では、管理者が組織内のすべての招待アカウントに対して、組織内の有効なすべての機能を承認するように求めています。 AWS 組織は、招待されたすべてのメンバーアカウントに登録されているアドレスに E メールを送信し、送信されたハンドシェイクを受け入れることで、所有者にすべての機能の変更を承認するように求めます。招待されたすべてのメンバーアカウントがハンドシェイクを受け入れると、組織管理者はすべての機能の変更を確定し、適切なアクセス許可を持つメンバーアカウントがポリシーを作成し、ルート、OU、およびアカウントに適用できるようになります。  

```
aws organizations enable-all-features
```
出力はハンドシェイクオブジェクトであり、招待されたすべてのメンバーアカウントに送信され、承認されます。  

```
{
        "Handshake": {
                "Action": "ENABLE_ALL_FEATURES",
                "Arn":"arn:aws:organizations::111111111111:handshake/o-exampleorgid/enable_all_features/h-examplehandshakeid111",
                "ExpirationTimestamp":1.483127868609E9,
                "Id":"h-examplehandshakeid111",
                "Parties": [
                        {
                                "id":"o-exampleorgid",
                                "type":"ORGANIZATION"
                        }
                ],
                "requestedTimestamp":1.481831868609E9,
                "resources": [
                        {
                                "type":"ORGANIZATION",
                                "value":"o-exampleorgid"
                        }
                ],
                "state":"REQUESTED"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableAllFeatures](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/enable-all-features.html)」を参照してください。

### `enable-policy-type`
<a name="organizations_EnablePolicyType_cli_2_topic"></a>

次のコード例は、`enable-policy-type` を使用する方法を示しています。

**AWS CLI**  
**ルートでポリシータイプの使用を有効にするには**  
次の例は、ルートでサービスコントロールポリシー (SCP) ポリシータイプを有効にする方法を示しています。  

```
aws organizations enable-policy-type --root-id r-examplerootid111 --policy-type SERVICE_CONTROL_POLICY
```
出力には、SCP が有効になったことを示す policyTypes レスポンス要素を持つルートオブジェクトが表示されます。  

```
{
        "Root": {
                "PolicyTypes": [
                        {
                                "Status":"ENABLED",
                                "Type":"SERVICE_CONTROL_POLICY"
                        }
                ],
                "Id": "r-examplerootid111",
                "Name": "Root",
                "Arn": "arn:aws:organizations::111111111111:root/o-exampleorgid/r-examplerootid111"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnablePolicyType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/enable-policy-type.html)」を参照してください。

### `invite-account-to-organization`
<a name="organizations_InviteAccountToOrganization_cli_2_topic"></a>

次のコード例は、`invite-account-to-organization` を使用する方法を示しています。

**AWS CLI**  
**組織に参加するようアカウントを招待するには**  
次の例は、bill@example.com が所有するマスターアカウントで、juan@example.com が所有するアカウントを組織に参加するよう招待しています。  

```
aws organizations invite-account-to-organization --target '{"Type": "EMAIL", "Id": "juan@example.com"}' --notes "This is a request for Juan's account to join Bill's organization."
```
出力には、招待されたアカウントに送信される内容を示すハンドシェイク構造が含まれます。  

```
{
        "Handshake": {
                "Action": "INVITE",
                "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111",
                "ExpirationTimestamp": 1482952459.257,
                "Id": "h-examplehandshakeid111",
                "Parties": [
                        {
                                "Id": "o-exampleorgid",
                                "Type": "ORGANIZATION"
                        },
                        {
                                "Id": "juan@example.com",
                                "Type": "EMAIL"
                        }
                ],
                "RequestedTimestamp": 1481656459.257,
                "Resources": [
                        {
                                "Resources": [
                                        {
                                                "Type": "MASTER_EMAIL",
                                                "Value": "bill@amazon.com"
                                        },
                                        {
                                                "Type": "MASTER_NAME",
                                                "Value": "Org Master Account"
                                        },
                                        {
                                                "Type": "ORGANIZATION_FEATURE_SET",
                                                "Value": "FULL"
                                        }
                                ],
                                "Type": "ORGANIZATION",
                                "Value": "o-exampleorgid"
                        },
                        {
                                "Type": "EMAIL",
                                "Value": "juan@example.com"
                        }
                ],
                "State": "OPEN"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InviteAccountToOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/invite-account-to-organization.html)」を参照してください。

### `leave-organization`
<a name="organizations_LeaveOrganization_cli_2_topic"></a>

次のコード例は、`leave-organization` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントとして組織を離れるには**  
次の例は、現在メンバーである組織を離れることをリクエストしているメンバーアカウントの管理者を示しています。  

```
aws organizations leave-organization
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[LeaveOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/leave-organization.html)」を参照してください。

### `list-accounts-for-parent`
<a name="organizations_ListAccountsForParent_cli_2_topic"></a>

次のコード例は、`list-accounts-for-parent` を使用する方法を示しています。

**AWS CLI**  
**指定された親ルートまたは OU 内のすべてのアカウントのリストを取得するには**  
次の例は、OU 内のアカウントのリストをリクエストする方法を示しています。  

```
aws organizations list-accounts-for-parent --parent-id ou-examplerootid111-exampleouid111
```
出力には、アカウントサマリーオブジェクトのリストが含まれます。  

```
{
        "Accounts": [
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/333333333333",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835795.536,
                        "Id": "333333333333",
                        "Name": "Development Account",
                        "Email": "juan@example.com",
                        "Status": "ACTIVE"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/444444444444",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835812.143,
                        "Id": "444444444444",
                        "Name": "Test Account",
                        "Email": "anika@example.com",
                        "Status": "ACTIVE"
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccountsForParent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-accounts-for-parent.html)」を参照してください。

### `list-accounts`
<a name="organizations_ListAccounts_cli_2_topic"></a>

次のコード例は、`list-accounts` を使用する方法を示しています。

**AWS CLI**  
**組織内のすべてのアカウントのリストを取得するには**  
次の例は、組織内のアカウントのリストをリクエストする方法を示しています。  

```
aws organizations list-accounts
```
出力には、アカウントサマリーオブジェクトのリストが含まれます。  

```
{
        "Accounts": [
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/111111111111",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481830215.45,
                        "Id": "111111111111",
                        "Name": "Master Account",
                        "Email": "bill@example.com",
                        "Status": "ACTIVE"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/222222222222",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835741.044,
                        "Id": "222222222222",
                        "Name": "Production Account",
                        "Email": "alice@example.com",
                        "Status": "ACTIVE"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/333333333333",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835795.536,
                        "Id": "333333333333",
                        "Name": "Development Account",
                        "Email": "juan@example.com",
                        "Status": "ACTIVE"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/444444444444",
                        "JoinedMethod": "INVITED",
                        "JoinedTimestamp": 1481835812.143,
                        "Id": "444444444444",
                        "Name": "Test Account",
                        "Email": "anika@example.com",
                        "Status": "ACTIVE"
                }
        ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-accounts.html)」を参照してください。**

### `list-children`
<a name="organizations_ListChildren_cli_2_topic"></a>

次のコード例は、`list-children` を使用する方法を示しています。

**AWS CLI**  
**親 OU またはルートの子アカウントと OU を取得するには**  
次の例は、そのアカウント 444444444444 を含むルートまたは OU を一覧表示する方法を示しています。  

```
aws organizations list-children --child-type ORGANIZATIONAL_UNIT --parent-id ou-examplerootid111-exampleouid111
```
出力には、親に含まれる 2 つの子 OU が表示されます。  

```
{
        "Children": [
                {
                        "Id": "ou-examplerootid111-exampleouid111",
                        "Type":"ORGANIZATIONAL_UNIT"
                },
                {
                        "Id":"ou-examplerootid111-exampleouid222",
                        "Type":"ORGANIZATIONAL_UNIT"
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListChildren](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-children.html)」を参照してください。

### `list-create-account-status`
<a name="organizations_ListCreateAccountStatus_cli_2_topic"></a>

次のコード例は、`list-create-account-status` を使用する方法を示しています。

**AWS CLI**  
**例 1: 現在の組織で行われたアカウント作成リクエストのリストを取得するには**  
次の例は、正常に完了した組織のアカウント作成リクエストのリストを依頼する方法を示しています。  

```
aws organizations list-create-account-status --states SUCCEEDED
```
出力には、各リクエストに関する情報を含むオブジェクトの配列が含まれます。  

```
{
        "CreateAccountStatuses": [
                {
                        "AccountId": "444444444444",
                        "AccountName": "Developer Test Account",
                        "CompletedTimeStamp": 1481835812.143,
                        "Id": "car-examplecreateaccountrequestid111",
                        "RequestedTimeStamp": 1481829432.531,
                        "State": "SUCCEEDED"
                }
        ]
}
```
**例 2: 現在の組織で行われた進行中のアカウント作成リクエストのリストを取得するには**  
次の例では、組織の進行中のアカウント作成リクエストのリストを取得します。  

```
aws organizations list-create-account-status --states IN_PROGRESS
```
出力には、各リクエストに関する情報を含むオブジェクトの配列が含まれます。  

```
{
        "CreateAccountStatuses": [
                {
                  "State": "IN_PROGRESS",
                  "Id": "car-examplecreateaccountrequestid111",
                  "RequestedTimeStamp": 1481829432.531,
                  "AccountName": "Production Account"
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCreateAccountStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-create-account-status.html)」を参照してください。

### `list-handshakes-for-account`
<a name="organizations_ListHandshakesForAccount_cli_2_topic"></a>

次のコード例は、`list-handshakes-for-account` を使用する方法を示しています。

**AWS CLI**  
**アカウントに送信されたハンドシェイクのリストを取得するには**  
次の例は、オペレーションの呼び出しに使用された認証情報のアカウントに関連付けられているすべてのハンドシェイクのリストを取得する方法を示しています。  

```
aws organizations list-handshakes-for-account
```
出力には、現在の状態を含む各ハンドシェイクに関する情報と共にハンドシェイク構造のリストが含まれます。  

```
{
        "Handshake": {
                "Action": "INVITE",
                "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111",
                "ExpirationTimestamp": 1482952459.257,
                "Id": "h-examplehandshakeid111",
                "Parties": [
                        {
                                "Id": "o-exampleorgid",
                                "Type": "ORGANIZATION"
                        },
                        {
                                "Id": "juan@example.com",
                                "Type": "EMAIL"
                        }
                ],
                "RequestedTimestamp": 1481656459.257,
                "Resources": [
                        {
                                "Resources": [
                                        {
                                                "Type": "MASTER_EMAIL",
                                                "Value": "bill@amazon.com"
                                        },
                                        {
                                                "Type": "MASTER_NAME",
                                                "Value": "Org Master Account"
                                        },
                                        {
                                                "Type": "ORGANIZATION_FEATURE_SET",
                                                "Value": "FULL"
                                        }
                                ],
                                "Type": "ORGANIZATION",
                                "Value": "o-exampleorgid"
                        },
                        {
                                "Type": "EMAIL",
                                "Value": "juan@example.com"
                        }
                ],
                "State": "OPEN"
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHandshakesForAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-handshakes-for-account.html)」を参照してください。

### `list-handshakes-for-organization`
<a name="organizations_ListHandshakesForOrganization_cli_2_topic"></a>

次のコード例は、`list-handshakes-for-organization` を使用する方法を示しています。

**AWS CLI**  
**組織に関連付けられているハンドシェイクのリストを取得するには**  
次の例は、現在の組織に関連付けられているハンドシェイクのリストを取得する方法を示しています。  

```
aws organizations list-handshakes-for-organization
```
出力には 2 つのハンドシェイクが表示されます。1 つ目は Juan のアカウントへの招待で、OPEN 状態を示します。2 つ目は Anika のアカウントへの招待で、ACCEPTED 状態を示します。  

```
{
        "Handshakes": [
                {
                        "Action": "INVITE",
                        "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111",
                        "ExpirationTimestamp": 1482952459.257,
                        "Id": "h-examplehandshakeid111",
                        "Parties": [
                                {
                                        "Id": "o-exampleorgid",
                                        "Type": "ORGANIZATION"
                                },
                                {
                                        "Id": "juan@example.com",
                                        "Type": "EMAIL"
                                }
                        ],
                        "RequestedTimestamp": 1481656459.257,
                        "Resources": [
                                {
                                        "Resources": [
                                                {
                                                        "Type": "MASTER_EMAIL",
                                                        "Value": "bill@amazon.com"
                                                },
                                                {
                                                        "Type": "MASTER_NAME",
                                                        "Value": "Org Master Account"
                                                },
                                                {
                                                        "Type": "ORGANIZATION_FEATURE_SET",
                                                        "Value": "FULL"
                                                }
                                        ],
                                        "Type": "ORGANIZATION",
                                        "Value": "o-exampleorgid"
                                },
                                {
                                        "Type": "EMAIL",
                                        "Value": "juan@example.com"
                                },
                                {
                                        "Type":"NOTES",
                                        "Value":"This is an invitation to Juan's account to join Bill's organization."
                                }
                        ],
                        "State": "OPEN"
                },
                {
                        "Action": "INVITE",
                        "State":"ACCEPTED",
                        "Arn": "arn:aws:organizations::111111111111:handshake/o-exampleorgid/invite/h-examplehandshakeid111",
                        "ExpirationTimestamp": 1.471797437427E9,
                        "Id": "h-examplehandshakeid222",
                        "Parties": [
                                {
                                        "Id": "o-exampleorgid",
                                        "Type": "ORGANIZATION"
                                },
                                {
                                        "Id": "anika@example.com",
                                        "Type": "EMAIL"
                                }
                        ],
                        "RequestedTimestamp": 1.469205437427E9,
                        "Resources": [
                                {
                                        "Resources": [
                                                {
                                                        "Type":"MASTER_EMAIL",
                                                        "Value":"bill@example.com"
                                                },
                                                {
                                                        "Type":"MASTER_NAME",
                                                        "Value":"Master Account"
                                                }
                                        ],
                                        "Type":"ORGANIZATION",
                                        "Value":"o-exampleorgid"
                                },
                                {
                                        "Type":"EMAIL",
                                        "Value":"anika@example.com"
                                },
                                {
                                        "Type":"NOTES",
                                        "Value":"This is an invitation to Anika's account to join Bill's organization."
                                }
                        ]
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHandshakesForOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-handshakes-for-organization.html)」を参照してください。

### `list-organizational-units-for-parent`
<a name="organizations_ListOrganizationalUnitsForParent_cli_2_topic"></a>

次のコード例は、`list-organizational-units-for-parent` を使用する方法を示しています。

**AWS CLI**  
**親 OU またはルートの OU のリストを取得するには**  
次の例は、指定されたルート内の OU のリストを取得する方法を示しています。  

```
aws organizations list-organizational-units-for-parent --parent-id r-examplerootid111
```
出力は、指定されたルートに 2 つの OU が含まれていることを示し、それぞれの詳細を示します。  

```
{
        "OrganizationalUnits": [
                {
                        "Name": "AccountingDepartment",
                        "Arn": "arn:aws:organizations::o-exampleorgid:ou/r-examplerootid111/ou-examplerootid111-exampleouid111"
                },
                {
                        "Name": "ProductionDepartment",
                        "Arn": "arn:aws:organizations::o-exampleorgid:ou/r-examplerootid111/ou-examplerootid111-exampleouid222"
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOrganizationalUnitsForParent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-organizational-units-for-parent.html)」を参照してください。

### `list-parents`
<a name="organizations_ListParents_cli_2_topic"></a>

次のコード例は、`list-parents` を使用する方法を示しています。

**AWS CLI**  
**アカウントまたは子 OU の親 OU またはルートを一覧表示するには**  
次の例は、そのアカウント 444444444444 を含むルートまたは親 OU を一覧表示する方法を示しています。  

```
aws organizations list-parents --child-id 444444444444
```
出力は、指定されたアカウントが、指定された ID を持つ OU にあることを示します。  

```
{
  "Parents": [
        {
          "Id": "ou-examplerootid111-exampleouid111",
          "Type": "ORGANIZATIONAL_UNIT"
        }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListParents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-parents.html)」を参照してください。

### `list-policies-for-target`
<a name="organizations_ListPoliciesForTarget_cli_2_topic"></a>

次のコード例は、`list-policies-for-target` を使用する方法を示しています。

**AWS CLI**  
**アカウントに直接アタッチされた SCP のリストを取得するには**  
次の例は、アカウントに直接アタッチされた Filter パラメータで指定されたすべてのサービスコントロールポリシー (SCP) のリストを取得する方法を示しています。  

```
aws organizations list-policies-for-target --filter SERVICE_CONTROL_POLICY --target-id 444444444444
```
出力には、ポリシーに関するポリシー構造のリストと概要情報が含まれます。このリストには、OU 階層内の場所からの継承のためにアカウントに適用されるポリシーは含まれません。  

```
{
        "Policies": [
                {
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Name": "AllowAllEC2Actions",
                        "AwsManaged", false,
                        "Id": "p-examplepolicyid222",
                        "Arn": "arn:aws:organizations::o-exampleorgid:policy/service_control_policy/p-examplepolicyid222",
                        "Description": "Enables account admins to delegate permissions for any EC2 actions to users and roles in their accounts."
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPoliciesForTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-policies-for-target.html)」を参照してください。

### `list-policies`
<a name="organizations_ListPolicies_cli_2_topic"></a>

次のコード例は、`list-policies` を使用する方法を示しています。

**AWS CLI**  
**特定のタイプの組織のすべてのポリシーのリストを取得するには**  
次の例は、フィルターパラメータで指定された SCP のリストを取得する方法を示しています。  

```
aws organizations list-policies --filter SERVICE_CONTROL_POLICY
```
出力には、ポリシーのリストと概要情報が含まれます。  

```
{
        "Policies": [
                {
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Name": "AllowAllS3Actions",
                        "AwsManaged": false,
                        "Id": "p-examplepolicyid111",
                        "Arn": "arn:aws:organizations::111111111111:policy/service_control_policy/p-examplepolicyid111",
                        "Description": "Enables account admins to delegate permissions for any S3 actions to users and roles in their accounts."
                },
                {
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Name": "AllowAllEC2Actions",
                        "AwsManaged": false,
                        "Id": "p-examplepolicyid222",
                        "Arn": "arn:aws:organizations::111111111111:policy/service_control_policy/p-examplepolicyid222",
                        "Description": "Enables account admins to delegate permissions for any EC2 actions to users and roles in their accounts."
                },
                {
                        "AwsManaged": true,
                        "Description": "Allows access to every operation",
                        "Type": "SERVICE_CONTROL_POLICY",
                        "Id": "p-FullAWSAccess",
                        "Arn": "arn:aws:organizations::aws:policy/service_control_policy/p-FullAWSAccess",
                        "Name": "FullAWSAccess"
                }
        ]
}
```
+  API の詳細については、「AWS CLI Command Reference」の「[ListPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-policies.html)」を参照してください。**

### `list-roots`
<a name="organizations_ListRoots_cli_2_topic"></a>

次のコード例は、`list-roots` を使用する方法を示しています。

**AWS CLI**  
**組織内のルートのリストを取得するには**  
この例では、組織のルートのリストを取得する方法を示します。  

```
aws organizations list-roots
```
出力には、ルート構造のリストと概要情報が含まれます。  

```
{
        "Roots": [
                {
                        "Name": "Root",
                        "Arn": "arn:aws:organizations::111111111111:root/o-exampleorgid/r-examplerootid111",
                        "Id": "r-examplerootid111",
                        "PolicyTypes": [
                                {
                                        "Status":"ENABLED",
                                        "Type":"SERVICE_CONTROL_POLICY"
                                }
                        ]
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRoots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-roots.html)」を参照してください。

### `list-targets-for-policy`
<a name="organizations_ListTargetsForPolicy_cli_2_topic"></a>

次のコード例は、`list-targets-for-policy` を使用する方法を示しています。

**AWS CLI**  
**ポリシーがアタッチされているすべてのルート、OU、およびアカウントのリストを取得するには**  
次の例は、指定されたポリシーがアタッチされているルート、OU、およびアカウントのリストを取得する方法を示しています。  

```
aws organizations list-targets-for-policy --policy-id p-FullAWSAccess
```
出力には、ルート、OU、およびポリシーがアタッチされているアカウントに関する概要情報と共にアタッチメントオブジェクトのリストが含まれます。  

```
{
        "Targets": [
                {
                        "Arn": "arn:aws:organizations::111111111111:root/o-exampleorgid/r-examplerootid111",
                        "Name": "Root",
                        "TargetId":"r-examplerootid111",
                        "Type":"ROOT"
                },
                {
                        "Arn": "arn:aws:organizations::111111111111:account/o-exampleorgid/333333333333;",
                        "Name": "Developer Test Account",
                        "TargetId": "333333333333",
                        "Type": "ACCOUNT"
                },
                {
                        "Arn":"arn:aws:organizations::111111111111:ou/o-exampleorgid/ou-examplerootid111-exampleouid111",
                        "Name":"Accounting",
                        "TargetId":"ou-examplerootid111-exampleouid111",
                        "Type":"ORGANIZATIONAL_UNIT"
                }
        ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTargetsForPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/list-targets-for-policy.html)」を参照してください。

### `move-account`
<a name="organizations_MoveAccount_cli_2_topic"></a>

次のコード例は、`move-account` を使用する方法を示しています。

**AWS CLI**  
**ルートまたは OU 間でアカウントを移動するには**  
次の例は、組織内のマスターアカウントをルートから OU に移動する方法を示しています。  

```
aws organizations move-account --account-id 333333333333 --source-parent-id r-examplerootid111 --destination-parent-id ou-examplerootid111-exampleouid111
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MoveAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/move-account.html)」を参照してください。

### `remove-account-from-organization`
<a name="organizations_RemoveAccountFromOrganization_cli_2_topic"></a>

次のコード例は、`remove-account-from-organization` を使用する方法を示しています。

**AWS CLI**  
**マスターアカウントとして組織からアカウントを削除するには**  
次の例は、組織からアカウントを削除する方法を示しています。  

```
aws organizations remove-account-from-organization --account-id 333333333333
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveAccountFromOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/remove-account-from-organization.html)」を参照してください。

### `update-organizational-unit`
<a name="organizations_UpdateOrganizationalUnit_cli_2_topic"></a>

次のコード例は、`update-organizational-unit` を使用する方法を示しています。

**AWS CLI**  
**OU の名前を変更するには**  
この例では、OU の名前を変更する方法を示します。この例では、OU の名前は「AccountingOU」に変更されます。  

```
aws organizations update-organizational-unit --organizational-unit-id ou-examplerootid111-exampleouid111 --name AccountingOU
```
出力には新しい名前が表示されます。  

```
{
        "OrganizationalUnit": {
                "Id": "ou-examplerootid111-exampleouid111"
                "Name": "AccountingOU",
                "Arn": "arn:aws:organizations::111111111111:ou/o-exampleorgid/ou-examplerootid111-exampleouid111""
        }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateOrganizationalUnit](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/update-organizational-unit.html)」を参照してください。

### `update-policy`
<a name="organizations_UpdatePolicy_cli_2_topic"></a>

次のコード例は、`update-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: ポリシーの名前を変更するには**  
次の `update-policy` の例では、ポリシーの名前を変更し、新しい説明を提供します。  

```
aws organizations update-policy \
    --policy-id p-examplepolicyid111 \
    --name Renamed-Policy \
    --description "This description replaces the original."
```
出力には新しい名前と説明が表示されます。  

```
{
    "Policy": {
        "Content": "{\n  \"Version\":\"2012-10-17\",\n  \"Statement\":{\n    \"Effect\":\"Allow\",\n    \"Action\":\"ec2:*\",\n    \"Resource\":\"*\"\n  }\n}\n",
        "PolicySummary": {
            "Id": "p-examplepolicyid111",
            "AwsManaged": false,
            "Arn":"arn:aws:organizations::111111111111:policy/o-exampleorgid/service_control_policy/p-examplepolicyid111",
            "Description": "This description replaces the original.",
            "Name": "Renamed-Policy",
            "Type": "SERVICE_CONTROL_POLICY"
        }
    }
}
```
**例 2: ポリシーの JSON テキストコンテンツを置き換えるには**  
次の例は、前の例の SCP の JSON テキストを、EC2 の代わりに S3 を許可する新しい JSON ポリシーテキスト文字列に置き換える方法を示しています。  

```
aws organizations update-policy \
    --policy-id p-examplepolicyid111 \
    --content "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}}"
```
出力には新しいコンテンツが表示されます。  

```
{
    "Policy": {
        "Content": "{ \"Version\": \"2012-10-17\", \"Statement\": { \"Effect\": \"Allow\", \"Action\": \"s3:*\", \"Resource\": \"*\" } }",
        "PolicySummary": {
            "Arn": "arn:aws:organizations::111111111111:policy/o-exampleorgid/service_control_policy/p-examplepolicyid111",
            "AwsManaged": false;
            "Description": "This description replaces the original.",
            "Id": "p-examplepolicyid111",
            "Name": "Renamed-Policy",
            "Type": "SERVICE_CONTROL_POLICY"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/organizations/update-policy.html)」を参照してください。

# AWS Outposts を使用した の例 AWS CLI
<a name="cli_2_outposts_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Outposts。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-outpost-instance-types`
<a name="outposts_GetOutpostInstanceTypes_cli_2_topic"></a>

次のコード例は、`get-outpost-instance-types` を使用する方法を示しています。

**AWS CLI**  
**Outpost のインスタンスタイプを取得するには**  
次の `get-outpost-instance-types` の例では、指定された Outpost のインスタンスタイプを取得します。  

```
aws outposts get-outpost-instance-types \
    --outpost-id op-0ab23c4567EXAMPLE
```
出力:  

```
{
    "InstanceTypes": [
        {
            "InstanceType": "c5d.large"
        },
        {
            "InstanceType": "i3en.24xlarge"
        },
        {
            "InstanceType": "m5d.large"
        },
        {
            "InstanceType": "r5d.large"
        }
    ],
    "OutpostId": "op-0ab23c4567EXAMPLE",
    "OutpostArn": "arn:aws:outposts:us-west-2:123456789012:outpost/op-0ab23c4567EXAMPLE"
}
```
詳細については、「*AWS Outposts User Guide*」の「[Launch an instance on your Outpost](https://docs.aws.amazon.com/outposts/latest/userguide/launch-instance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOutpostInstanceTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/outposts/get-outpost-instance-types.html)」を参照してください。

### `get-outpost`
<a name="outposts_GetOutpost_cli_2_topic"></a>

次のコード例は、`get-outpost` を使用する方法を示しています。

**AWS CLI**  
**Outpost の詳細を取得するには**  
次の `get-outpost` の例では、指定された Outpost の詳細を表示します。  

```
aws outposts get-outpost \
    --outpost-id op-0ab23c4567EXAMPLE
```
出力:  

```
{
    "Outpost": {
        "OutpostId": "op-0ab23c4567EXAMPLE",
        "OwnerId": "123456789012",
        "OutpostArn": "arn:aws:outposts:us-west-2:123456789012:outpost/op-0ab23c4567EXAMPLE",
        "SiteId": "os-0ab12c3456EXAMPLE",
        "Name": "EXAMPLE",
        "LifeCycleStatus": "ACTIVE",
        "AvailabilityZone": "us-west-2a",
        "AvailabilityZoneId": "usw2-az1",
        "Tags": {}
    }
}
```
詳細については、「*AWS Outposts User Guide*」の「[Working with Outposts](https://docs.aws.amazon.com/outposts/latest/userguide/work-with-outposts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOutpost](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/outposts/get-outpost.html)」を参照してください。

### `list-outposts`
<a name="outposts_ListOutposts_cli_2_topic"></a>

次のコード例は、`list-outposts` を使用する方法を示しています。

**AWS CLI**  
**Outpost を一覧表示するには**  
次の の`list-outposts`例では、 AWS アカウントの Outposts を一覧表示します。  

```
aws outposts list-outposts
```
出力:  

```
{
    "Outposts": [
        {
            "OutpostId": "op-0ab23c4567EXAMPLE",
            "OwnerId": "123456789012",
            "OutpostArn": "arn:aws:outposts:us-west-2:123456789012:outpost/op-0ab23c4567EXAMPLE",
            "SiteId": "os-0ab12c3456EXAMPLE",
            "Name": "EXAMPLE",
            "Description": "example",
            "LifeCycleStatus": "ACTIVE",
            "AvailabilityZone": "us-west-2a",
            "AvailabilityZoneId": "usw2-az1",
            "Tags": {
                "Name": "EXAMPLE"
            }
        },
        {
            "OutpostId": "op-4fe3dc21baEXAMPLE",
            "OwnerId": "123456789012",
            "OutpostArn": "arn:aws:outposts:us-west-2:123456789012:outpost/op-4fe3dc21baEXAMPLE",
            "SiteId": "os-0ab12c3456EXAMPLE",
            "Name": "EXAMPLE2",
            "LifeCycleStatus": "ACTIVE",
            "AvailabilityZone": "us-west-2a",
            "AvailabilityZoneId": "usw2-az1",
            "Tags": {}
        }
    ]
}
```
詳細については、「*AWS Outposts User Guide*」の「[Working with Outposts](https://docs.aws.amazon.com/outposts/latest/userguide/work-with-outposts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOutposts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/outposts/list-outposts.html)」を参照してください。

### `list-sites`
<a name="outposts_ListSites_cli_2_topic"></a>

次のコード例は、`list-sites` を使用する方法を示しています。

**AWS CLI**  
**サイトを一覧表示するには**  
次の の`list-sites`例では、 AWS アカウントで使用可能な Outpost サイトを一覧表示します。  

```
aws outposts list-sites
```
出力:  

```
{
    "Sites": [
        {
            "SiteId": "os-0ab12c3456EXAMPLE",
            "AccountId": "123456789012",
            "Name": "EXAMPLE",
            "Description": "example",
            "Tags": {}
        }
    ]
}
```
詳細については、「*AWS Outposts User Guide*」の「[Working with Outposts](https://docs.aws.amazon.com/outposts/latest/userguide/work-with-outposts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSites](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/outposts/list-sites.html)」を参照してください。

# AWS Payment Cryptography を使用した の例 AWS CLI
<a name="cli_2_payment-cryptography_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Payment Cryptography。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-alias`
<a name="payment-cryptography_CreateAlias_cli_2_topic"></a>

次のコード例は、`create-alias` を使用する方法を示しています。

**AWS CLI**  
**キーのエイリアスを作成するには**  
次の `create-alias` の例では、キーのエイリアスを作成します。  

```
aws payment-cryptography create-alias \
    --alias-name alias/sampleAlias1 \
    --key-arn arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h
```
出力:  

```
{
    "Alias": {
        "AliasName": "alias/sampleAlias1",
        "KeyArn": "arn:aws:payment-cryptography:us-west-2:123456789012:key/kwapwa6qaifllw2h"
    }
}
```
詳細については、「*AWS Payment Cryptography ユーザーガイド*」の「[エイリアスについて](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/alias-about.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/create-alias.html)」を参照してください。**

### `create-key`
<a name="payment-cryptography_CreateKey_cli_2_topic"></a>

次のコード例は、`create-key` を使用する方法を示しています。

**AWS CLI**  
**キーを作成するには**  
次の `create-key` の例では、CVV/CVV2 値の生成と検証に使用できる 2KEY TDES キーを生成します。  

```
aws payment-cryptography create-key \
    --exportable \
    --key-attributes KeyAlgorithm=TDES_2KEY, KeyUsage=TR31_C0_CARD_VERIFICATION_KEY,KeyClass=SYMMETRIC_KEY, KeyModesOfUse={Generate=true,Verify=true}
```
出力:  

```
{
    "Key": {
        "CreateTimestamp": "1686800690",
        "Enabled": true,
        "Exportable": true,
        "KeyArn": "arn:aws:payment-cryptography:us-west-2:123456789012:key/kwapwa6qaifllw2h",
        "KeyAttributes": {
            "KeyAlgorithm": "TDES_2KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyModesOfUse": {
                "Decrypt": false,
                "DeriveKey": false,
                "Encrypt": false,
                "Generate": true,
                "NoRestrictions": false,
                "Sign": false,
                "Unwrap": false,
                "Verify": true,
                "Wrap": false
            },
            "KeyUsage": "TR31_C0_CARD_VERIFICATION_KEY"
        },
        "KeyCheckValue": "F2E50F",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
        "KeyState": "CREATE_COMPLETE",
        "UsageStartTimestamp": "1686800690"
    }
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Generating keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/create-keys.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/create-key.html)」を参照してください。**

### `delete-alias`
<a name="payment-cryptography_DeleteAlias_cli_2_topic"></a>

次のコード例は、`delete-alias` を使用する方法を示しています。

**AWS CLI**  
**エイリアスを削除するには**  
次の `delete-alias` の例では、エイリアスを削除します。これによるキーへの影響はありません。  

```
aws payment-cryptography delete-alias \
    --alias-name alias/sampleAlias1
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Payment Cryptography ユーザーガイド*」の「[エイリアスについて](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/alias-about.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/delete-alias.html)」を参照してください。**

### `delete-key`
<a name="payment-cryptography_DeleteKey_cli_2_topic"></a>

次のコード例は、`delete-key` を使用する方法を示しています。

**AWS CLI**  
**キーを削除するには**  
次の `delete-key` の例では、デフォルトの待機期間である 7 日後にキーの削除をスケジュールします。  

```
aws payment-cryptography delete-key \
    --key-identifier arn:aws:payment-cryptography:us-west-2:123456789012:key/kwapwa6qaifllw2h
```
出力:  

```
{
    "Key": {
        "CreateTimestamp": "1686801198",
        "DeletePendingTimestamp": "1687405998",
        "Enabled": true,
        "Exportable": true,
        "KeyArn": "arn:aws:payment-cryptography:us-west-2:123456789012:key/kwapwa6qaifllw2h",
        "KeyAttributes": {
            "KeyAlgorithm": "TDES_2KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyModesOfUse": {
                "Decrypt": false,
                "DeriveKey": false,
                "Encrypt": false,
                "Generate": true,
                "NoRestrictions": false,
                "Sign": false,
                "Unwrap": false,
                "Verify": true,
                "Wrap": false
            },
            "KeyUsage": "TR31_C0_CARD_VERIFICATION_KEY"
        },
        "KeyCheckValue": "F2E50F",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
        "KeyState": "DELETE_PENDING",
        "UsageStartTimestamp": "1686801190"
    }
}
```
詳細については、「*AWS Payment Cryptography ユーザーガイド*」の「[キーの削除](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/delete-key.html)」を参照してください。

### `export-key`
<a name="payment-cryptography_ExportKey_cli_2_topic"></a>

次のコード例は、`export-key` を使用する方法を示しています。

**AWS CLI**  
**キーをエクスポートするには**  
次の `export-key` の例では、キーをエクスポートします。  

```
aws payment-cryptography export-key \
    --export-key-identifier arn:aws:payment-cryptography:us-west-2:123456789012:key/lco3w6agsk7zgu2l \
    --key-material '{"Tr34KeyBlock": { \
        "CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-west-2:123456789012:key/ftobshq7pvioc5fx", \
        "ExportToken": "export-token-cu4lg26ofcziixny", \
        "KeyBlockFormat": "X9_TR34_2012", \
        "WrappingKeyCertificate": file://wrapping-key-certificate.pem }}'
```
`wrapping-key-certificate.pem` の内容:  

```
LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUV2VENDQXFXZ0F3SUJBZ0lSQU1ZZS8xMXFUK2svVzlRUDJQOElVdWd3RFFZSktvWklodmNOQVFFTkJRQXcKZ1lreEN6QUpCZ05WQkFZVEFsVlRNUmt3RndZRFZRUUtEQkJCVjFNZ1EzSjVjSFJ2WjNKaGNHaDVNU0V3SHdZRApWUVFMREJoQlYxTWdVR0Y1YldWdWRDQkRjbmx3ZEc5bmNtRndhSGt4RVRBUEJnTlZCQWdNQ0ZacGNtZHBibWxoCk1SVXdFd1lEVlFRRERBd3dOelUxTlRZNU5UTTNOVEF4RWpBUUJnTlZCQWNNQ1VGeWJHbHVaM1J2YmpBZUZ3MHkKTXpBMk1UTXhOelV6TVROYUZ3MHlNekEyTWpBeE9EVXpNVEphTUN3eEZUQVRCZ05WQkFNTUREQTNOVFUxTmprMQpNemMxTURFVE1CRUdBMVVFQlJNS09URTFNRGMzTnpRMk9EQ0NBU0l3RFFZSktvWklodmNOQVFFQkJRQURnZ0VQCkFEQ0NBUW9DZ2dFQkFNUjZsVTZ0SFJwcWtCQmI1Z2FFa0FrbVRxNEgwNUQ2UXR2MS9WemhSaThtNVBFMjVtMFIKVnRtZmsxcUEySi94TEROTEl3dHFDR3BIVldOM0JMdFhuSmh2Y1dNNkI0QlRRVXNicENMbG9PYW1jMGF0UXRmeQo0ZUhoWHJoT2lDMFVpR05zeTc5ZlltTkZ3Q3RrSDhvZzJXTEdYNldXNSszRzlTaFZKR3dhbWpNamtlOVo1a0FhCnJKZHk4Y2tsMTFBTS8wQjVZRFR2TU5KVTcyZnVUMlJ5KzVoRmdFTE14aS8vbGE1TnFCQWp5VTY0cmV3eGdVSjAKZ1pVM3lJU2F2UjFwMElNOFNvZzdXUHlkVlNNTitZeTdLMG1OL3lFa3FZTWQxZWxvS1I0OVV3V0hvdzFMcHVzcwpzMDh5a0diWGxsMnBvZ3NvSmZZaFFGWTc4UmRsTU9vY2dOc0NBd0VBQWFOOE1Ib3dDUVlEVlIwVEJBSXdBREFmCkJnTlZIU01FR0RBV2dCU2tDVlVEZzJGZDdPZWpVSUlVRnBvbUpxWG9FREFkQmdOVkhRNEVGZ1FVZU1sRzJ5dkgKamxsQzM2OUV2U3hIcXBBODVkMHdEZ1lEVlIwUEFRSC9CQVFEQWdXZ01CMEdBMVVkSlFRV01CUUdDQ3NHQVFVRgpCd01CQmdnckJnRUZCUWNEQWpBTkJna3Foa2lHOXcwQkFRMEZBQU9DQWdFQURNS2gxbnhYWWtncVkwYmMwVjA1ClNCUTBlcm5vMmsxbXdRQnhpUDBpcUpMdWNFUnF6b0RzOTBJWTN5SjhjMkMzU2kzU1JrVzBmQUhKR0VucTlzblgKbGdGWnRBZmtNbzR4Wllpb1JGZmY1TWdSOUdNaUZNQnVQS2tIeGxKc0R2NllSbnp1Zmkza1lDT1NzeWE4U2tTMQp2M2l2UEpLcTk3aDBBaThoNFQ3clBtN0NNSnYxZ0JTUEF4UVdtdndES2RrTjFsd0VudmtGdzlLZjhqeVpaNjhGCjlmUFV4Z1RvYm1MSmNialZxaFdsQ3U1VE9mSGNPR2RLRURwZE54RE12ODNZZ1ZaWUszclc4UHVxWWIyWFdMR2IKdmFISXh2RGVnOVJwNDByVVpETGVyalptb0gwUWpEZmxCV1RYK0JqU3ZLMm5yUGpzZzJIUC91S1VncVIwQWM5eAo0UjF5YjU2cHh3eU54TUU2NmFTVWNVQ3F1WTloY1Q3eWxWNjc3REVhRHpLTG1abnpMcWdWZU5PaUtzQTMvTi9hCnI2UW56VjNabEtJbCs5aWZwNTVPaTVLMXFyWFkyeVlPL1V2SXBXZjAxcFNFUERHN0hXSllnaGorbXpDRFVkM24KdldBeHBjUXlYRGlybS8wSkRZTWtuYzhjK2Z4QmxQR3ZiT2cwWldOeVUwSVpqRmx3aDVwUnIrMnRkT3lhRkZrNApWNytmMkpRWXdKZWgzWDdQL0N6WldKMlQvbnVzaVZXd0Y2K0hueDQ2ZHVGTzhXSWJZTnJUU1hTQnFEV04vdWpZCjBwYUhwS1poUTJOVnV1M0t3a2JaTDUzRjBRM09EVjcydGtiTHJyajZvOUNGd3JGUFluV0owSWtsemN0d1VtQ24KNjd5TzlSVjVzcC83YlNxTkhYNFRuNmc9Ci0tLS0tRU5EIENFUlRJRklDQVRFEXAMPLE=
```
出力:  

```
{
    "WrappedKey": {
        "KeyMaterial": "308205A106092A864886F70D010702A08205923082058E020101310D300B06096086480165030402013082031F06092A864886F70D010703A08203100482030C020100318201F4308201F002010030819F308189310B300906035504061302555331193017060355040A0C104157532043727970746F6772617068793121301F060355040B0C18415753205061796D656E742043727970746F6772617068793111300F06035504080C0856697267696E69613115301306035504030C0C3037353535363935333735303112301006035504070C0941726C696E67746F6E021100C61EFF5D6A4FE93F5BD40FD8FF0852E8304506092A864886F70D0101073038300D06096086480165030402010500301806092A864886F70D010108300B0609608648016503040201300D06092A864886F70D0101090400048201008B09AFE9DFF1EA4E97F8651B6B3B51A3BFF68B0365F3956AD34A64B015185BB3FFB3DC7D5812B0D21D58436EAEC131F8110389E2A9F22DA146805A4D818BDCD6AA0387284188CEF5691565A849659C117AAD0042DF5D2C290386710B58A8C63A298C99280EB75861B793302F78299DE64853433227F23DBB383A605DA23620546DCA92B2D3CD8B486339D303844D807C2D6AF17CF1ABF191F63ACFF0E0F8A91AA5B22C1A0D9EE663854D1D76CEE37FE3A0113C8577B57F173ECD69FA752A8A1AEF49AB2A62D39F091FF9AA0FD4CB695D084637DBA7EF7DA2E657BBBF0C5FCC355DB37866B7BBD5AE065DC0FD399A8E0FC19C10943D5059507DC822DED6AFA67A3082010D06092A864886F70D0107013081FF06082A864886F70D030704085050B8007C2CE5608081E8DC683EECE2BF1FC1D209D5F6642E01E58DC76FF7926B576CB6884B6723C63DDE91D8E6C75DFC4E94F1CDDA8A3E863BE8A7E1DFCD2115E251675F73388D022A28247ED66D7892AA57800750A5F84313ACC3616449A703D7DFC770F50C816F224FB038E675FB1751916699FD00585C1B2EA19FECEE696611FA65B4E8516210D884E351201A888A47D874B1ACDDF4AE7F6F59D0780A5BE3E788DD6FB4E6AC1B9D966443881E9998A625CFB10A35D943B21A3ABB902CF68AD6F7FE7B0C18FF05B94C10E254017203541AFF71E440A42C8B915A84B341F923EF657280DB7B19F769E29725FF7E5999859C318202553082025102010130819E308189310B300906035504061302555331193017060355040A0C104157532043727970746F6772617068793121301F060355040B0C18415753205061796D656E742043727970746F6772617068793111300F06035504080C0856697267696E69613115301306035504030C0C3037353535363935333735303112301006035504070C0941726C696E67746F6E02106BD452CE836B7D2A717B69DB8FAF3679300B0609608648016503040201A0818A301806092A864886F70D010903310B06092A864886F70D010703301C06092A864886F70D010905310F170D3233303631333139303234305A301F06092A864886F70D0107013112041044303131324B30544230304530303030302F06092A864886F70D010904312204209AD3A76A89E2F58433DF669174A6F4D4B6B3D60A8A7341712CB666CA6AE4125E300D06092A864886F70D0101010500048201009BA48B242A227AD05243DBB99ACF6249D626CEF086DAFD8B064592EFF1205CFE6713D5FC373D8CD53AF9A88292E143A4B9C1887792E8E7F6310503B1FD8F0F89F735DFF11CC55114859B902841E4D163D64E19DFAE0151B93590C8D770E47E939DF08242897F9319DC6AB272C26DE2ACC539BF055CE528B139D61B45542FF35D2ABDE34EEF5BE19D1C48679187B455864EDD3D976CDC80070A6A6635DF5A00AF08CBBF309C4D59A4710A531A719562D390394A736E9F2DED502B2F766BA56727DFB0C6A92FD4D2BABC69BDDBD6B17EB376FA9ADD83C2974292447E63F26D168E66A4558ED97E417BDE97837188DB4F414A2219BAC50A8D726CD54C3C1EXAMPLE",
        "WrappedKeyMaterialFormat": "TR34_KEY_BLOCK"
    }
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Export keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExportKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/export-key.html)」を参照してください。

### `get-alias`
<a name="payment-cryptography_GetAlias_cli_2_topic"></a>

次のコード例は、`get-alias` を使用する方法を示しています。

**AWS CLI**  
**エイリアスを取得するには**  
次の `get-alias` の例では、エイリアスに関連付けられたキーの ARN を返します。  

```
aws payment-cryptography get-alias \
    --alias-name alias/sampleAlias1
```
出力:  

```
{
    "Alias": {
        "AliasName": "alias/sampleAlias1",
        "KeyArn": "arn:aws:payment-cryptography:us-west-2:123456789012:key/kwapwa6qaifllw2h"
    }
}
```
詳細については、「*AWS Payment Cryptography ユーザーガイド*」の「[エイリアスについて](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/alias-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/get-alias.html)」を参照してください。

### `get-key`
<a name="payment-cryptography_GetKey_cli_2_topic"></a>

次のコード例は、`get-key` を使用する方法を示しています。

**AWS CLI**  
**キーのメタデータを取得するには**  
次の `get-key` の例では、エイリアスに関連付けられたキーのメタデータを返します。このオペレーションは暗号化マテリアルを返しません。  

```
aws payment-cryptography get-key \
    --key-identifier alias/sampleAlias1
```
出力:  

```
{
    "Key": {
        "CreateTimestamp": "1686800690",
        "DeletePendingTimestamp": "1687405998",
        "Enabled": true,
        "Exportable": true,
        "KeyArn": "arn:aws:payment-cryptography:us-west-2:123456789012:key/kwapwa6qaifllw2h",
        "KeyAttributes": {
            "KeyAlgorithm": "TDES_2KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyModesOfUse": {
                "Decrypt": false,
                "DeriveKey": false,
                "Encrypt": false,
                "Generate": true,
                "NoRestrictions": false,
                "Sign": false,
                "Unwrap": false,
                "Verify": true,
                "Wrap": false
            },
            "KeyUsage": "TR31_C0_CARD_VERIFICATION_KEY"
        },
        "KeyCheckValue": "F2E50F",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
        "KeyState": "DELETE_PENDING",
        "UsageStartTimestamp": "1686801190"
    }
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Get keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/getkeys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/get-key.html)」を参照してください。

### `get-parameters-for-export`
<a name="payment-cryptography_GetParametersForExport_cli_2_topic"></a>

次のコード例は、`get-parameters-for-export` を使用する方法を示しています。

**AWS CLI**  
**エクスポートプロセスを初期化するには**  
次の `get-parameters-for-export` の例では、キーペアを生成し、キーに署名してから、証明書と証明書ルートを返します。  

```
aws payment-cryptography get-parameters-for-export \
    --signing-key-algorithm RSA_2048 \
    --key-material-type TR34_KEY_BLOCK
```
出力:  

```
{
    "ExportToken": "export-token-ep5cwyzune7oya53",
    "ParametersValidUntilTimestamp": "1687415640",
    "SigningKeyAlgorithm": "RSA_2048",
    "SigningKeyCertificate":

    "MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
    VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
    b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
    BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
    MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
    VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
    b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
    YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
    21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
    rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
    Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
    nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
    FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
    NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=",
    "SigningKeyCertificateChain":
    "NIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
    VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
    b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
    BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
    MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
    VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
    b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
    YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
    21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
    rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
    Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
    nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
    FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
    NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE="
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Export keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-export.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParametersForExport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/get-parameters-for-export.html)」を参照してください。

### `get-parameters-for-import`
<a name="payment-cryptography_GetParametersForImport_cli_2_topic"></a>

次のコード例は、`get-parameters-for-import` を使用する方法を示しています。

**AWS CLI**  
**インポートプロセスを初期化するには**  
次の `get-parameters-for-import` の例では、キーペアを生成し、キーに署名してから、証明書と証明書ルートを返します。  

```
aws payment-cryptography get-parameters-for-import \
    --key-material-type TR34_KEY_BLOCK \
    --wrapping-key-algorithm RSA_2048
```
出力:  

```
{
    "ImportToken": "import-token-qgmafpaa7nt2kfbb",
    "ParametersValidUntilTimestamp": "1687415640",
    "WrappingKeyAlgorithm": "RSA_2048",
    "WrappingKeyCertificate":
    "MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
    VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
    b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
    BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
    MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
    VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
    b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
    YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
    21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
    rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
    Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
    nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
    FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
    NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=",
    "WrappingKeyCertificateChain":
    "NIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
    VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
    b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
    BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
    MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
    VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
    b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
    YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
    21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
    rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
    Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
    nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
    FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
    NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE="
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Import keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-import.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParametersForImport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/get-parameters-for-import.html)」を参照してください。

### `get-public-key-certificate`
<a name="payment-cryptography_GetPublicKeyCertificate_cli_2_topic"></a>

次のコード例は、`get-public-key-certificate` を使用する方法を示しています。

**AWS CLI**  
**パブリックキーを返すには**  
次の `get-public-key-certificate` の例では、キーペアのパブリックキー部分を返します。  

```
aws payment-cryptography get-public-key-certificate \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h
```
出力:  

```
{
    "KeyCertificate":
    "MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
    VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
    b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
    BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
    MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
    VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
    b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
    YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
    21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
    rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
    Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
    nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
    FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
    NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=",
    "KeyCertificateChain":
    "NIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
    VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
    b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
    BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
    MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
    VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
    b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
    YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
    21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
    rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
    Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
    nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
    FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
    NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE="
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Get the public key/certificate associated with a key pair](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys.getpubliccertificate-example.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicKeyCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/get-public-key-certificate.html)」を参照してください。

### `import-key`
<a name="payment-cryptography_ImportKey_cli_2_topic"></a>

次のコード例は、`import-key` を使用する方法を示しています。

**AWS CLI**  
**TR-34 キーをインポートするには**  
次の `import-key` の例では、TR-34 キーをインポートします。  

```
aws payment-cryptography import-key \
        --key-material='{ "Tr34KeyBlock": {" \
            CertificateAuthorityPublicKeyIdentifier": "arn:aws:payment-cryptography:us-west-2:123456789012:key/rmm5wn2q564njnjm", \
            "ImportToken": "import-token-5ott6ho5nts7bbcg", \
            "KeyBlockFormat": "X9_TR34_2012", \
            "SigningKeyCertificate": file://signing-key-certificate.pem, \
            "WrappedKeyBlock": file://wrapped-key-block.pem }}'
```
`signing-key-certificate.pem` の内容:  

```
LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUV2RENDQXFTZ0F3SUJBZ0lRYWVCK25IbE1WZU1PR1ZiNjU1Q2JzREFOQmdrcWhraUc5dzBCQVEwRkFEQ0IKaVRFTE1Ba0dBMVVFQmhNQ1ZWTXhHVEFYQmdOVkJBb01FRUZYVXlCRGNubHdkRzluY21Gd2FIa3hJVEFmQmdOVgpCQXNNR0VGWFV5QlFZWGx0Wlc1MElFTnllWEIwYjJkeVlYQm9lVEVSTUE4R0ExVUVDQXdJVm1seVoybHVhV0V4CkZUQVRCZ05WQkFNTUREVXlPVEF5TnpRMU5UUTVOVEVTTUJBR0ExVUVCd3dKUVhKc2FXNW5kRzl1TUI0WERUSXoKTURZd09USXlNVEkxTUZvWERUSXpNRFl4TmpJek1USTFNRm93TERFVk1CTUdBMVVFQXd3TU5USTVNREkzTkRVMQpORGsxTVJNd0VRWURWUVFGRXdvek1EVTRNVGszTkRjNE1JSUJJakFOQmdrcWhraUc5dzBCQVFFRkFBT0NBUThBCk1JSUJDZ0tDQVFFQXdMc0dGb0pqOTVJY0UxL1p1OGZxak40SDVHTFJHVGZQSkFyWWJLbjA4WXVrQTE0SjRBSHEKWGR6ZlY5MjcvVTJZTWN2S3FsNlk5SVQwejZhTVBGbDVYemZWNU1YVW5YMlJxYTladU1ndDhGSDJJYWxsMEQ3bgo0V0RjUkg3TERQdEhXZTRaVmh3aExRVEFQa1I2dUxTWC84UDhSN2lrSWpkVkI4SytjVitnbHh0clB1Vkh5TzNxCjhXRUl3a1lYVTFDVjJybHptNklzWjcycjhPcXJWcHNiZEhERENBelJ2YUtPN3hMNU1RUGVFMFcvdkxmRGdrYmoKb2h4VHl6Z3dRSlJFK21tUXdCRmlIeXdaY2F5Y1FZdXdzTktoK0xPWXJpN0ZGM2lRRTJlYlY5Mm4zZER5NDRtcQpUSjFHUWJENndFM3ZHS0xnYXNqMVl0WVNSTk9xNld1UTV3SURBUUFCbzN3d2VqQUpCZ05WSFJNRUFqQUFNQjhHCkExVWRJd1FZTUJhQUZHMVBsWElaUGdETVU0WjVwRTc3dE8xYmV2eDVNQjBHQTFVZERnUVdCQlFwanByQXFoZGMKVmF2dElTRnBBNkswVzJMcmJUQU9CZ05WSFE4QkFmOEVCQU1DQmFBd0hRWURWUjBsQkJZd0ZBWUlLd1lCQlFVSApBd0VHQ0NzR0FRVUZCd01DTUEwR0NTcUdTSWIzRFFFQkRRVUFBNElDQVFCOXVxcFVadU1oK1kzQXhXSklNUkx5Cmlob2gvR0xIanh1aVhxK1IvdFRxbTBNYTA3R2dvbGxhRkdIZzZMei9ELy9ZRDB2UHdYc1dVOE5qY0Vib095aGcKc0hmay9hVGxjRnovZm51MVlkRUpvYUpFdW15bDkwSTBMNyswUmJNYXJScWU0bC9yQlQ4YTM3R0JyQ0x0ZUlyRgorcnp1cmovU1BDM1FiUWkvOVBzWmlieTFKMlFxTzVVRUJncEYreklaVk84dzgwMzVEK1YrUXhsY2RaUGVLS2JnCmI5WHNSeHF3cUZIVUVRM2tybXdVZUZveERlbm91QmxKMVFzOTVXUHBpVk9zYUFvbkJkYUtEbFBaRTlqdG1zZkwKMER3b1lRRy92bHdWN0pIVnNNd0dleml2VGJXaWFNdmZTTkxIMmVZMG9rblhFcHlHcmlWMjczSVFqVU1QTXBMNgpjODh3OUYzcTJnY0x6Nk0ycEFHUTZ0SVBrZ2c3aUZjbk9haGp4Ty9ORFZrS0xxbXZ0eFFlcUk2VDRveWRuWkVWCkdOMjBISStZcFVud09Eem1GL1k5TXZQQXFtdGJka2dZZGRJWExtbU9ORlF1dm4wenp0Tm01NzNTN0NSYWxCNTgKeFhyNm1iak1MQU1tcmZGQmNrU0NYaUZ6Y3gvNHJTRGJtbU9INWM0dGxiNEM3SzF5QU96NWo3OHhWOWNQOTM3SQpwczcrZUFZRkFpYTdzZGpuS3hNUDN4ZVVTM0tNS2FGMzg2TGRYbkRwdTFyczhVRWhPeDhqakt6RWplWU9qV3hLClo5Mjd1Yzd0b2kwZlcvT2tzT3NnWVlybmttSEhyd3p0NXRBc2llcjFyWXFGK2lYa1Y4TzRxSzI0bHc4cXFPanUKS3htVHMzY0NlTmdGNUZhVmhCV1Zjdz09Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0=
```
`wrapped-key-block.pem` の内容:  

```
3082059806092A864886F70D010702A082058930820585020101310D300B06096086480165030402013082031606092A864886F70D010703A082030704820303020100318201F3308201EF02010030819E308189310B300906035504061302555331193017060355040A0C104157532043727970746F6772617068793121301F060355040B0C18415753205061796D656E742043727970746F6772617068793111300F06035504080C0856697267696E69613115301306035504030C0C3532393032373435353439353112301006035504070C0941726C696E67746F6E021026C5E52507841B72C59D9F0065548DC1304506092A864886F70D0101073038300D06096086480165030402010500301806092A864886F70D010108300B0609608648016503040201300D06092A864886F70D01010904000482010013D3C2E9405CA45A947BA6EA098DD5A83A7E6CFF4E140B141634EBFF9E0F78057B5C22013574BA8C8D8D64B43C391E1D9CDF081B33D15CDE3AB2DB21CAE7380E64B0A09A8C45B8A0F87659638E6E30D4351E9B941EDD384183DA169ADDF71FC64E06487F8750B74B2CD3AB4F8534C024AE04BD7C070CB685A250EB2A8C1EEDEBFA387935466D152E063D3EBEDD6231216EEE5145983C74D755C050D191E6E41DC2BDB09E78CDA203C2767270E3E56C6E24EB1090904462743B054098DE278A18C71577CAE1EC13CF776055224F299DBF1BC96C11F339DEE1A2CD130A275959820FBE5C34C0CB21DB6404F868B348D5A6F8ED8E5DC5BC681F6115BA278879FF8F3082010506092A864886F70D0107013081F706082A864886F70D0307040857F8BFE99B4493AD8081E05DEE59D9E60520DB8A15869BB840F1CC908DAE6CC6F6BE79DDF72DD8EA84F881D7DFB4A186CDC622B29E3F97AEB7C00872D1BB47FE235D9204F80A4D3EF502309ECD967F8F70A2F741738ACE7B7CA0AA2EBB0DACD3126F7831F79AF6DC3C74CEBF7D0947301245F42C59508FBC0318C03F02E37EDF014C4D0170ACC4E992EC7E9B85D95BF87F75FD2E0B938E2D8E807872DE4017F8530D59A48C9F68AF5BEC1B2115D7555C248F980DF28C69619E508317F0C20461AE26CD0D55896FEE71E1EA89F7F9B5DC047F9BD063210E1F09D9566EF2AF6472AD44A8ACC0180AC1995CDE318202553082025102010130819E308189310B300906035504061302555331193017060355040A0C104157532043727970746F6772617068793121301F060355040B0C18415753205061796D656E742043727970746F6772617068793111300F06035504080C0856697267696E69613115301306035504030C0C3532393032373435353439353112301006035504070C0941726C696E67746F6E021069E07E9C794C55E30E1956FAE7909BB0300B0609608648016503040201A0818A301806092A864886F70D010903310B06092A864886F70D010703301C06092A864886F70D010905310F170D3233303630393233333934365A301F06092A864886F70D0107013112041044303131324330544330304530303030302F06092A864886F70D01090431220420D6413C502DC4552B495B9A8449F9A3BF9E6DCB31AD56A1D158DB482BDF06EEAD300D06092A864886F70D010101050004820100313BA7BCDFE6C55F3544A8E7D9973A346DDAD17CC5C506DE72B8B7E490891702E753C445FED78D5477C5E5A2BF63378B2F12CE6C22C1A543BCC41FA978568F65C0171DBF3E438E70FD68DAB52BA1DEB294C4ED92CD6EAA684B4352AF6C53924048931595FC7F1FF642E82B12DBD8B8578DA200DC0CCE2FA075897CDA6D5257C78DC2B515015CC414E78B49075AFF333C7CEAFF81F5EEC44C5C9F6BD32898E6983A7CEA40DD5C0CF9CD51DB3E712ED1C755E0A9DA38286872B46D7119088A76728DC08AECB0F624B34E15349E5B2334900E57885A6461AC6E74B35A3FFF5C010ACE5F15DE9D867A5160D30217997E7DE6319A74F5D55D44A934908A3BC1602D22
```
出力:  

```
{
    "Key": {
        "CreateTimestamp": "2023-06-09T16:56:27.621000-07:00",
        "Enabled": true,
        "KeyArn": "arn:aws:payment-cryptography:us-west-2:123456789012:key/bzmvgyxdg3sktwxd",
        "KeyAttributes": {
            "KeyAlgorithm": "TDES_2KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyModesOfUse": {
                "Decrypt": false,
                "DeriveKey": false,
                "Encrypt": false,
                "Generate": true,
                "NoRestrictions": false,
                "Sign": false,
                "Unwrap": false,
                "Verify": true,
                "Wrap": false
            },
            "KeyUsage": "TR31_C0_CARD_VERIFICATION_KEY"
        },
        "KeyCheckValue": "D9B20E",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "KeyOrigin": "EXTERNAL",
        "KeyState": "CREATE_COMPLETE",
        "UsageStartTimestamp": "2023-06-09T16:56:27.621000-07:00"
    }
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Import keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-import.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/import-key.html)」を参照してください。

### `list-aliases`
<a name="payment-cryptography_ListAliases_cli_2_topic"></a>

次のコード例は、`list-aliases` を使用する方法を示しています。

**AWS CLI**  
**エイリアスのリストを取得するには**  
次の `list-aliases` の例では、このリージョンのアカウント内のすべてのエイリアスを表示します。  

```
aws payment-cryptography list-aliases
```
出力:  

```
{
    "Aliases": [
        {
            "AliasName": "alias/sampleAlias1",
            "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h"
        },
        {
            "AliasName": "alias/sampleAlias2",
            "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h"
        }
    ]
}
```
詳細については、「*AWS Payment Cryptography ユーザーガイド*」の「[エイリアスについて](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/alias-about.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListAliases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/list-aliases.html)」を参照してください。**

### `list-keys`
<a name="payment-cryptography_ListKeys_cli_2_topic"></a>

次のコード例は、`list-keys` を使用する方法を示しています。

**AWS CLI**  
**キーのリストを取得するには**  
次の `list-keys` の例では、このリージョンのアカウントのすべてのキーを表示します。  

```
aws payment-cryptography list-keys
```
出力:  

```
{
    "Keys": [
    {
        "CreateTimestamp": "1666506840",
        "Enabled": false,
        "Exportable": true,
        "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h",
        "KeyAttributes": {
            "KeyAlgorithm": "TDES_3KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyModesOfUse": {
                "Decrypt": true,
                "DeriveKey": false,
                "Encrypt": true,
                "Generate": false,
                "NoRestrictions": false,
                "Sign": false,
                "Unwrap": true,
                "Verify": false,
                "Wrap": true
            },
            "KeyUsage": "TR31_P1_PIN_GENERATION_KEY"
        },
        "KeyCheckValue": "369D",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
        "KeyState": "CREATE_COMPLETE",
        "UsageStopTimestamp": "1666938840"
    }
    ]
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[List keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/alias-about.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/list-keys.html)」を参照してください。**

### `list-tags-for-resource`
<a name="payment-cryptography_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**キーのタグのリストを取得するには**  
次の `list-tags-for-resource` の例では、キーのタグを取得します。  

```
aws payment-cryptography list-tags-for-resource \
    --resource-arn arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h
```
出力:  

```
{
    "Tags": [
        {
            "Key": "BIN",
            "Value": "20151120"
        },
        {
            "Key": "Project",
            "Value": "Production"
        }
    ]
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Managing key tags with API operations](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/manage-tags-api.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/list-tags-for-resource.html)」を参照してください。

### `restore-key`
<a name="payment-cryptography_RestoreKey_cli_2_topic"></a>

次のコード例は、`restore-key` を使用する方法を示しています。

**AWS CLI**  
**削除予定のキーを復元するには**  
次の `restore-key` の例では、キーの削除をキャンセルします。  

```
aws payment-cryptography restore-key \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h
```
出力:  

```
{
    "Key": {
        "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h",
        "KeyAttributes": {
            "KeyUsage": "TR31_V2_VISA_PIN_VERIFICATION_KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyAlgorithm": "TDES_3KEY",
            "KeyModesOfUse": {
                "Encrypt": false,
                "Decrypt": false,
                "Wrap": false,
                "Unwrap": false,
                "Generate": true,
                "Sign": false,
                "Verify": true,
                "DeriveKey": false,
                "NoRestrictions": false
            }
        },
        "KeyCheckValue": "",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "Enabled": false,
        "Exportable": true,
        "KeyState": "CREATE_COMPLETE",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
        "CreateTimestamp": "1686800690",
        "UsageStopTimestamp": "1687405998"
    }
}
```
詳細については、「*AWS Payment Cryptography ユーザーガイド*」の「[キーの削除](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/restore-key.html)」を参照してください。

### `start-key-usage`
<a name="payment-cryptography_StartKeyUsage_cli_2_topic"></a>

次のコード例は、`start-key-usage` を使用する方法を示しています。

**AWS CLI**  
**キーを有効にするには**  
次の `start-key-usage` の例では、キーの使用を有効にします。  

```
aws payment-cryptography start-key-usage \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h
```
出力:  

```
{
    "Key": {
        "CreateTimestamp": "1686800690",
        "Enabled": true,
        "Exportable": true,
        "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/alsuwfxug3pgy6xh",
        "KeyAttributes": {
            "KeyAlgorithm": "TDES_3KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyModesOfUse": {
                "Decrypt": true,
                "DeriveKey": false,
                "Encrypt": true,
                "Generate": false,
                "NoRestrictions": false,
                "Sign": false,
                "Unwrap": true,
                "Verify": false,
                "Wrap": true
            },
            "KeyUsage": "TR31_P1_PIN_GENERATION_KEY"
        },
        "KeyCheckValue": "369D",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
        "KeyState": "CREATE_COMPLETE",
        "UsageStartTimestamp": "1686800690"
    }
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Enabling and disabling keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-enable-disable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartKeyUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/start-key-usage.html)」を参照してください。

### `stop-key-usage`
<a name="payment-cryptography_StopKeyUsage_cli_2_topic"></a>

次のコード例は、`stop-key-usage` を使用する方法を示しています。

**AWS CLI**  
**キーを無効にするには**  
次の `stop-key-usage` の例では、キーを無効にします。  

```
aws payment-cryptography stop-key-usage \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h
```
出力:  

```
{
    "Key": {
        "CreateTimestamp": "1686800690",
        "Enabled": true,
        "Exportable": true,
        "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/alsuwfxug3pgy6xh",
        "KeyAttributes": {
            "KeyAlgorithm": "TDES_3KEY",
            "KeyClass": "SYMMETRIC_KEY",
            "KeyModesOfUse": {
                "Decrypt": true,
                "DeriveKey": false,
                "Encrypt": true,
                "Generate": false,
                "NoRestrictions": false,
                "Sign": false,
                "Unwrap": true,
                "Verify": false,
                "Wrap": true
            },
            "KeyUsage": "TR31_P1_PIN_GENERATION_KEY"
        },
        "KeyCheckValue": "369D",
        "KeyCheckValueAlgorithm": "ANSI_X9_24",
        "KeyOrigin": "AWS_PAYMENT_CRYPTOGRAPHY",
        "KeyState": "CREATE_COMPLETE",
        "UsageStartTimestamp": "1686800690"
    }
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Enabling and disabling keys](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/keys-enable-disable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopKeyUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/stop-key-usage.html)」を参照してください。

### `tag-resource`
<a name="payment-cryptography_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**キーにタグを付けるには**  
次の `tag-resource` の例では、キーにタグを付けます。  

```
aws payment-cryptography tag-resource \
    --resource-arn arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h \
    --tags Key=sampleTag,Value=sampleValue
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Payment Cryptography User Guide*」の「[Managing key tags](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/manage-tags-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="payment-cryptography_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**キーからタグを削除するには**  
次の `untag-resource` の例では、タグをキーから削除します。  

```
aws payment-cryptography untag-resource \
    --resource-arn arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h \
    --tag-keys sampleTag
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Payment Cryptography User Guide*」の「[Managing key tags](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/manage-tags-api.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/untag-resource.html)」を参照してください。

### `update-alias`
<a name="payment-cryptography_UpdateAlias_cli_2_topic"></a>

次のコード例は、`update-alias` を使用する方法を示しています。

**AWS CLI**  
**エイリアスを更新するには**  
次の `update-alias` の例では、エイリアスを別のキーに関連付けます。  

```
aws payment-cryptography update-alias \
    --alias-name alias/sampleAlias1 \
    --key-arn arn:aws:payment-cryptography:us-east-2:123456789012:key/tqv5yij6wtxx64pi
```
出力:  

```
{
    "Alias": {
        "AliasName": "alias/sampleAlias1",
        "KeyArn": "arn:aws:payment-cryptography:us-west-2:123456789012:key/tqv5yij6wtxx64pi "
    }
}
```
詳細については、「*AWS Payment Cryptography ユーザーガイド*」の「[エイリアスについて](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/alias-about.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography/update-alias.html)」を参照してください。**

# AWS Payment Cryptography を使用したデータプレーンの例 AWS CLI
<a name="cli_2_payment-cryptography-data_code_examples"></a>

次のコード例は、 AWS Payment Cryptography Data Plane AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `decrypt-data`
<a name="payment-cryptography-data_DecryptData_cli_2_topic"></a>

次のコード例は、`decrypt-data` を使用する方法を示しています。

**AWS CLI**  
**暗号文を復号するには**  
次の `decrypt-data` の例では、対称キーを使用して暗号文データを復号します。このオペレーションでは、キーの `KeyModesOfUse` が `Decrypt` に設定され、`KeyUsage` が `TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY` に設定されている必要があります。  

```
aws payment-cryptography-data decrypt-data \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h \
    --cipher-text 33612AB9D6929C3A828EB6030082B2BD \
    --decryption-attributes 'Symmetric={Mode=CBC}'
```
出力:  

```
{
    "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h",
    "KeyCheckValue": "71D7AE",
    "PlainText": "31323334313233343132333431323334"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Decrypt data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/decrypt-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecryptData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/decrypt-data.html)」を参照してください。

### `encrypt-data`
<a name="payment-cryptography-data_EncryptData_cli_2_topic"></a>

次のコード例は、`encrypt-data` を使用する方法を示しています。

**AWS CLI**  
**データを暗号化するには**  
次の `encrypt-data` の例では、対称キーを使用してプレーンテキストデータを暗号化します。このオペレーションでは、キーの `KeyModesOfUse` が `Encrypt` に設定され、`KeyUsage` が `TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY` に設定されている必要があります。  

```
aws payment-cryptography-data encrypt-data \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h \
    --plain-text 31323334313233343132333431323334 \
    --encryption-attributes 'Symmetric={Mode=CBC}'
```
出力:  

```
{
    "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h",
    "KeyCheckValue": "71D7AE",
    "CipherText": "33612AB9D6929C3A828EB6030082B2BD"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Encrypt data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/encrypt-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EncryptData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/encrypt-data.html)」を参照してください。

### `generate-card-validation-data`
<a name="payment-cryptography-data_GenerateCardValidationData_cli_2_topic"></a>

次のコード例は、`generate-card-validation-data` を使用する方法を示しています。

**AWS CLI**  
**CVV を生成するには**  
次の `generate-card-validation-data` の例では、CVV/CVV2 を生成します。  

```
aws payment-cryptography-data generate-card-validation-data \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h \
    --primary-account-number=171234567890123 \
    --generation-attributes CardVerificationValue2={CardExpiryDate=0123}
```
出力:  

```
{
    "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h",
    "KeyCheckValue": "CADDA1",
    "ValidationData": "801"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Generate card data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/generate-card-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateCardValidationData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/generate-card-validation-data.html)」を参照してください。

### `generate-mac`
<a name="payment-cryptography-data_GenerateMac_cli_2_topic"></a>

次のコード例は、`generate-mac` を使用する方法を示しています。

**AWS CLI**  
**MAC を生成するには**  
次の `generate-card-validation-data` の例では、HMAC\$1SHA256 アルゴリズムと HMAC 暗号化キーを使用してカードデータ認証用の Hash-based Message Authentication Code (HMAC) を生成します。キーでは `KeyUsage` が `TR31_M7_HMAC_KEY` に設定され、`KeyModesOfUse` が `Generate` に設定されている必要があります。  

```
aws payment-cryptography-data generate-mac \
    --key-identifier arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h \
    --message-data "3b313038383439303031303733393431353d32343038323236303030373030303f33" \
    --generation-attributes Algorithm=HMAC_SHA256
```
出力:  

```
{
    "KeyArn": "arn:aws:payment-cryptography:us-east-2:123456789012:key/kwapwa6qaifllw2h,
    "KeyCheckValue": "2976E7",
    "Mac": "ED87F26E961C6D0DDB78DA5038AA2BDDEA0DCE03E5B5E96BDDD494F4A7AA470C"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Generate MAC](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/generate-mac.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateMac](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/generate-mac.html)」を参照してください。

### `generate-pin-data`
<a name="payment-cryptography-data_GeneratePinData_cli_2_topic"></a>

次のコード例は、`generate-pin-data` を使用する方法を示しています。

**AWS CLI**  
**PIN を生成するには**  
次の `generate-card-validation-data` の例では、Visa PIN スキームを使用して新しいランダム PIN を生成します。  

```
aws payment-cryptography-data generate-pin-data \
    --generation-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/37y2tsl45p5zjbh2 \
    --encryption-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/ivi5ksfsuplneuyt \
    --primary-account-number 171234567890123 \
    --pin-block-format ISO_FORMAT_0 \
    --generation-attributes VisaPin={PinVerificationKeyIndex=1}
```
出力:  

```
{
    "GenerationKeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/37y2tsl45p5zjbh2",
    "GenerationKeyCheckValue": "7F2363",
    "EncryptionKeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ivi5ksfsuplneuyt",
    "EncryptionKeyCheckValue": "7CC9E2",
    "EncryptedPinBlock": "AC17DC148BDA645E",
    "PinData": {
        "VerificationValue": "5507"
    }
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Generate PIN data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/generate-pin-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GeneratePinData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/generate-pin-data.html)」を参照してください。

### `re-encrypt-data`
<a name="payment-cryptography-data_ReEncryptData_cli_2_topic"></a>

次のコード例は、`re-encrypt-data` を使用する方法を示しています。

**AWS CLI**  
**別のキーを使用してデータを再暗号化するには**  
次の `re-encrypt-data` の例では、AES 対称キーを使用して暗号化された暗号文を復号し、トランザクション単位の派生ユニークキー (DUKPT) を使用して再暗号化します。  

```
aws payment-cryptography-data re-encrypt-data \
    --incoming-key-identifier arn:aws:payment-cryptography:us-west-2:111122223333:key/hyvv7ymboitd4vfy \
    --outgoing-key-identifier arn:aws:payment-cryptography:us-west-2:111122223333:key/jl6ythkcvzesbxen \
    --cipher-text 4D2B0BDBA192D5AEFEAA5B3EC28E4A65383C313FFA25140101560F75FE1B99F27192A90980AB9334 \
    --incoming-encryption-attributes "Dukpt={Mode=ECB,KeySerialNumber=0123456789111111}" \
    --outgoing-encryption-attributes '{"Symmetric": {"Mode": "ECB"}}'
```
出力:  

```
{
    "CipherText": "F94959DA30EEFF0C035483C6067667CF6796E3C1AD28C2B61F9CFEB772A8DD41C0D6822931E0D3B1",
    "KeyArn": "arn:aws:payment-cryptography:us-west-2:111122223333:key/jl6ythkcvzesbxen",
    "KeyCheckValue": "2E8CD9"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Encrypt and decrypt data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/crypto-ops.encryptdecrypt.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReEncryptData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/re-encrypt-data.html)」を参照してください。

### `translate-pin-data`
<a name="payment-cryptography-data_TranslatePinData_cli_2_topic"></a>

次のコード例は、`translate-pin-data` を使用する方法を示しています。

**AWS CLI**  
**PIN データを変換するには**  
次の `translate-pin-data` の例では、ISO 0 PIN ブロックを使用する PEK TDES 暗号化から、DUKPT アルゴリズムを使用する AES ISO 4 PIN ブロックに PIN を変換します。  

```
aws payment-cryptography-data translate-pin-data \
    --encrypted-pin-block "AC17DC148BDA645E" \
    --incoming-translation-attributes=IsoFormat0='{PrimaryAccountNumber=171234567890123}' \
    --incoming-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/ivi5ksfsuplneuyt \
    --outgoing-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/4pmyquwjs3yj4vwe \
    --outgoing-translation-attributes IsoFormat4="{PrimaryAccountNumber=171234567890123}" \
    --outgoing-dukpt-attributes KeySerialNumber="FFFF9876543210E00008"
```
出力:  

```
{
    "PinBlock": "1F4209C670E49F83E75CC72E81B787D9",
    "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ivi5ksfsuplneuyt
    "KeyCheckValue": "7CC9E2"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Translate PIN data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/translate-pin-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TranslatePinData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/translate-pin-data.html)」を参照してください。

### `verify-auth-request-cryptogram`
<a name="payment-cryptography-data_VerifyAuthRequestCryptogram_cli_2_topic"></a>

次のコード例は、`verify-auth-request-cryptogram` を使用する方法を示しています。

**AWS CLI**  
**認証リクエストを検証するには**  
次の `verify-auth-request-cryptogram` の例では、Authorization Request Cryptogram (ARQC) を検証します。  

```
aws payment-cryptography-data verify-auth-request-cryptogram \
    --auth-request-cryptogram F6E1BD1E6037FB3E \
    --auth-response-attributes '{"ArpcMethod1": {"AuthResponseCode": "1111"}}' \
    --key-identifier arn:aws:payment-cryptography:us-west-2:111122223333:key/pboipdfzd4mdklya \
    --major-key-derivation-mode "EMV_OPTION_A" \
    --session-key-derivation-attributes '{"EmvCommon": {"ApplicationTransactionCounter": "1234","PanSequenceNumber": "01","PrimaryAccountNumber": "471234567890123"}}' \
    --transaction-data "123456789ABCDEF"
```
出力:  

```
{
    "AuthResponseValue": "D899B8C6FBF971AA",
    "KeyArn": "arn:aws:payment-cryptography:us-west-2:111122223333:key/pboipdfzd4mdklya",
    "KeyCheckValue": "985792"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Verify auth request (ARQC) cryptogram](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/data-operations.verifyauthrequestcryptogram.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyAuthRequestCryptogram](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/verify-auth-request-cryptogram.html)」を参照してください。

### `verify-card-validation-data`
<a name="payment-cryptography-data_VerifyCardValidationData_cli_2_topic"></a>

次のコード例は、`verify-card-validation-data` を使用する方法を示しています。

**AWS CLI**  
**CVV を検証するには**  
次の `verify-card-validation-data` の例では、PAN の CVV/CVV2 を検証します。  

```
aws payment-cryptography-data verify-card-validation-data \
    --key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/tqv5yij6wtxx64pi \
    --primary-account-number=171234567890123 \
    --verification-attributes CardVerificationValue2={CardExpiryDate=0123} \
    --validation-data 801
```
出力:  

```
{
    "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/tqv5yij6wtxx64pi",
    "KeyCheckValue": "CADDA1"
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Verify card data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/verify-card-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyCardValidationData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/verify-card-validation-data.html)」を参照してください。

### `verify-mac`
<a name="payment-cryptography-data_VerifyMac_cli_2_topic"></a>

次のコード例は、`verify-mac` を使用する方法を示しています。

**AWS CLI**  
**MAC を検証するには**  
次の `verify-mac` の例では、HMAC\$1SHA256 アルゴリズムと HMAC 暗号化キーを使用してカードデータ認証用の Hash-based Message Authentication Code (HMAC) を検証します。  

```
aws payment-cryptography-data verify-mac \
    --key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/qnobl5lghrzunce6 \
    --message-data "3b343038383439303031303733393431353d32343038323236303030373030303f33" \
    --verification-attributes='Algorithm=HMAC_SHA256' \
    --mac ED87F26E961C6D0DDB78DA5038AA2BDDEA0DCE03E5B5E96BDDD494F4A7AA470C
```
出力:  

```
{
    "KeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/qnobl5lghrzunce6,
    "KeyCheckValue": "2976E7",
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Verify MAC](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/verify-mac.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyMac](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/verify-mac.html)」を参照してください。

### `verify-pin-data`
<a name="payment-cryptography-data_VerifyPinData_cli_2_topic"></a>

次のコード例は、`verify-pin-data` を使用する方法を示しています。

**AWS CLI**  
**PIN を検証するには**  
次の `verify-pin-data` の例では、PAN の PIN を検証します。  

```
aws payment-cryptography-data verify-pin-data \
    --verification-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/37y2tsl45p5zjbh2 \
    --encryption-key-identifier arn:aws:payment-cryptography:us-east-2:111122223333:key/ivi5ksfsuplneuyt \
    --primary-account-number 171234567890123 \
    --pin-block-format ISO_FORMAT_0 \
    --verification-attributes VisaPin="{PinVerificationKeyIndex=1,VerificationValue=5507}" \
    --encrypted-pin-block AC17DC148BDA645E
```
出力:  

```
{
    "VerificationKeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/37y2tsl45p5zjbh2",
    "VerificationKeyCheckValue": "7F2363",
    "EncryptionKeyArn": "arn:aws:payment-cryptography:us-east-2:111122223333:key/ivi5ksfsuplneuyt",
    "EncryptionKeyCheckValue": "7CC9E2",
}
```
詳細については、「*AWS Payment Cryptography User Guide*」の「[Verify PIN data](https://docs.aws.amazon.com/payment-cryptography/latest/userguide/verify-pin-data.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyPinData](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/payment-cryptography-data/verify-pin-data.html)」を参照してください。

# を使用した Amazon Pinpoint の例 AWS CLI
<a name="cli_2_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-app`
<a name="pinpoint_CreateApp_cli_2_topic"></a>

次のコード例は、`create-app` を使用する方法を示しています。

**AWS CLI**  
**例 1: アプリケーションを作成するには**  
次の `create-app` の例は、新しいアプリケーション (プロジェクト) を作成します。  

```
aws pinpoint create-app \
    --create-application-request Name=ExampleCorp
```
出力:  

```
{
    "ApplicationResponse": {
        "Arn": "arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example",
        "Id": "810c7aab86d42fb2b56c8c966example",
        "Name": "ExampleCorp",
        "tags": {}
    }
}
```
**例 2: タグが付けられたアプリケーションを作成するには**  
次の `create-app` の例は、新しいアプリケーション (プロジェクト) を作成し、タグ (キーと値) をアプリケーションに関連付けます。  

```
aws pinpoint create-app \
    --create-application-request Name=ExampleCorp,tags={"Stack"="Test"}
```
出力:  

```
{
    "ApplicationResponse": {
        "Arn": "arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example",
        "Id": "810c7aab86d42fb2b56c8c966example",
        "Name": "ExampleCorp",
        "tags": {
            "Stack": "Test"
        }
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateApp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/create-app.html)」を参照してください。**

### `create-sms-template`
<a name="pinpoint_CreateSmsTemplate_cli_2_topic"></a>

次のコード例は、`create-sms-template` を使用する方法を示しています。

**AWS CLI**  
**SMS チャンネルを介して送信されるメッセージのメッセージテンプレートを作成します**  
次の `create-sms-template` の例では、SMS メッセージテンプレートを作成します。  

```
aws pinpoint create-sms-template \
    --template-name TestTemplate \
    --sms-template-request file://myfile.json \
    --region us-east-1
```
`myfile.json` の内容:  

```
{
    "Body": "hello\n how are you?\n food is good",
    "TemplateDescription": "Test SMS Template"
}
```
出力:  

```
{
    "CreateTemplateMessageBody": {
        "Arn": "arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:templates/TestTemplate/SMS",
        "Message": "Created",
        "RequestID": "8c36b17f-a0b0-400f-ac21-29e9b62a975d"
    }
}
```
詳細については、「*Amazon Pinpoint User Guide*」の「[Amazon Pinpoint message templates](https://docs.aws.amazon.com/pinpoint/latest/userguide/messages-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSmsTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/create-sms-template.html)」を参照してください。

### `delete-app`
<a name="pinpoint_DeleteApp_cli_2_topic"></a>

次のコード例は、`delete-app` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションを削除するには**  
次の `delete-app` の例は、アプリケーション (プロジェクト) を削除します。  

```
aws pinpoint delete-app \
    --application-id 810c7aab86d42fb2b56c8c966example
```
出力:  

```
{
    "ApplicationResponse": {
        "Arn": "arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example",
        "Id": "810c7aab86d42fb2b56c8c966example",
        "Name": "ExampleCorp",
        "tags": {}
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteApp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/delete-app.html)」を参照してください。**

### `get-apns-channel`
<a name="pinpoint_GetApnsChannel_cli_2_topic"></a>

次のコード例は、`get-apns-channel` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの APN チャネルのステータスと設定に関する情報を取得するには**  
次の `get-apns-channel` の例では、アプリケーションの APN チャネルのステータスと設定に関する情報を取得します。  

```
aws pinpoint get-apns-channel \
    --application-id 9ab1068eb0a6461c86cce7f27ce0efd7 \
    --region us-east-1
```
出力:  

```
{
    "APNSChannelResponse": {
        "ApplicationId": "9ab1068eb0a6461c86cce7f27ce0efd7",
        "CreationDate": "2019-05-09T21:54:45.082Z",
        "DefaultAuthenticationMethod": "CERTIFICATE",
        "Enabled": true,
        "HasCredential": true,
        "HasTokenKey": false,
        "Id": "apns",
        "IsArchived": false,
        "LastModifiedDate": "2019-05-09T22:04:01.067Z",
        "Platform": "APNS",
        "Version": 2
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApnsChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-apns-channel.html)」を参照してください。

### `get-app`
<a name="pinpoint_GetApp_cli_2_topic"></a>

次のコード例は、`get-app` を使用する方法を示しています。

**AWS CLI**  
**アプリケーション (プロジェクト) に関する情報を取得するには**  
次の `get-app` の例では、アプリケーション (プロジェクト) に関する情報を取得します。  

```
aws pinpoint get-app \
    --application-id 810c7aab86d42fb2b56c8c966example \
    --region us-east-1
```
出力:  

```
{
    "ApplicationResponse": {
        "Arn": "arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example",
        "Id": "810c7aab86d42fb2b56c8c966example",
        "Name": "ExampleCorp",
        "tags": {
                "Year": "2019",
                "Stack": "Production"
            }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-app.html)」を参照してください。

### `get-apps`
<a name="pinpoint_GetApps_cli_2_topic"></a>

次のコード例は、`get-apps` を使用する方法を示しています。

**AWS CLI**  
**すべてのアプリケーションに関する情報を取得するには**  
次の `get-apps` の例では、すべてのアプリケーション (プロジェクト) に関する情報を取得します。  

```
aws pinpoint get-apps
```
出力:  

```
{
    "ApplicationsResponse": {
        "Item": [
            {
                "Arn": "arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example",
                "Id": "810c7aab86d42fb2b56c8c966example",
                "Name": "ExampleCorp",
                "tags": {
                    "Year": "2019",
                    "Stack": "Production"
                }
            },
            {
                "Arn": "arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/42d8c7eb0990a57ba1d5476a3example",
                "Id": "42d8c7eb0990a57ba1d5476a3example",
                "Name": "AnyCompany",
                "tags": {}
            },
            {
                "Arn": "arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/80f5c382b638ffe5ad12376bbexample",
                "Id": "80f5c382b638ffe5ad12376bbexample",
                "Name": "ExampleCorp_Test",
                "tags": {
                    "Year": "2019",
                    "Stack": "Test"
                }
            }
        ],
        "NextToken": "eyJDcmVhdGlvbkRhdGUiOiIyMDE5LTA3LTE2VDE0OjM4OjUzLjkwM1oiLCJBY2NvdW50SWQiOiI1MTIzOTcxODM4NzciLCJBcHBJZCI6Ijk1ZTM2MGRiMzBkMjQ1ZjRiYTYwYjhlMzllMzZlNjZhIn0"
    }
}
```
`NextToken` レスポンス値の存在は、使用可能な出力がさらにあることを示します。コマンドを再度呼び出し、その値を `NextToken` 入力パラメータとして指定します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetApps](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-apps.html)」を参照してください。

### `get-campaign`
<a name="pinpoint_GetCampaign_cli_2_topic"></a>

次のコード例は、`get-campaign` を使用する方法を示しています。

**AWS CLI**  
**キャンペーンのステータス、構成、およびその他の設定に関する情報を取得するには**  
次の `get-campaign` の例では、キャンペーンのステータス、構成、およびその他の設定に関する情報を取得します。  

```
aws pinpoint get-campaign \
    --application-id 6e0b7591a90841d2b5d93fa11143e5a7 \
    --campaign-id a1e63c6cc0eb43ed826ffcc3cc90b30d \
    --region us-east-1
```
出力:  

```
{
    "CampaignResponse": {
        "AdditionalTreatments": [],
        "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
        "Arn": "arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:apps/6e0b7591a90841d2b5d93fa11143e5a7/campaigns/a1e63c6cc0eb43ed826ffcc3cc90b30d",
        "CreationDate": "2019-10-08T18:40:16.581Z",
        "Description": " ",
        "HoldoutPercent": 0,
        "Id": "a1e63c6cc0eb43ed826ffcc3cc90b30d",
        "IsPaused": false,
        "LastModifiedDate": "2019-10-08T18:40:16.581Z",
        "Limits": {
            "Daily": 0,
            "MaximumDuration": 60,
            "MessagesPerSecond": 50,
            "Total": 0
        },
        "MessageConfiguration": {
            "EmailMessage": {
                "FromAddress": "sender@example.com",
                "HtmlBody": "<!DOCTYPE html>\n  <html lang=\"en\">\n    <head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n</head>\n<body>Hello</body>\n</html>",
                "Title": "PinpointDemo"
            }
        },
        "Name": "MyCampaign",
        "Schedule": {
            "IsLocalTime": false,
            "StartTime": "IMMEDIATE",
            "Timezone": "utc"
        },
        "SegmentId": "b66c9e42f71444b2aa2e0ffc1df28f60",
        "SegmentVersion": 1,
        "State": {
            "CampaignStatus": "COMPLETED"
        },
        "tags": {},
        "TemplateConfiguration": {},
        "Version": 1
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCampaign](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-campaign.html)」を参照してください。

### `get-campaigns`
<a name="pinpoint_GetCampaigns_cli_2_topic"></a>

次のコード例は、`get-campaigns` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションに関連付けられているすべてのキャンペーンのステータス、構成、およびその他の設定に関する情報を取得するには**  
次の `get-campaigns` の例では、アプリケーションに関連付けられているすべてのキャンペーンのステータス、構成、およびその他の設定に関する情報を取得します。  

```
aws pinpoint get-campaigns \
    --application-id 6e0b7591a90841d2b5d93fa11143e5a7 \
    --region us-east-1
```
出力:  

```
{
    "CampaignsResponse": {
        "Item": [
            {
                "AdditionalTreatments": [],
                "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
                "Arn": "arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:apps/6e0b7591a90841d2b5d93fa11143e5a7/campaigns/7e1280344c8f4a9aa40a00b006fe44f1",
                "CreationDate": "2019-10-08T18:40:22.905Z",
                "Description": " ",
                "HoldoutPercent": 0,
                "Id": "7e1280344c8f4a9aa40a00b006fe44f1",
                "IsPaused": false,
                "LastModifiedDate": "2019-10-08T18:40:22.905Z",
                "Limits": {},
                "MessageConfiguration": {
                    "EmailMessage": {
                        "FromAddress": "sender@example.com",
                        "HtmlBody": "<!DOCTYPE html>\n    <html lang=\"en\">\n    <head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n</head>\n<body>Hello</body>\n</html>",
                        "Title": "PInpointDemo Test"
                    }
                },
                "Name": "MyCampaign1",
                "Schedule": {
                    "IsLocalTime": false,
                    "QuietTime": {},
                    "StartTime": "IMMEDIATE",
                    "Timezone": "UTC"
                },
                "SegmentId": "b66c9e42f71444b2aa2e0ffc1df28f60",
                "SegmentVersion": 1,
                "State": {
                    "CampaignStatus": "COMPLETED"
                },
                "tags": {},
                "TemplateConfiguration": {},
                "Version": 1
            },
            {
                "AdditionalTreatments": [],
                "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
                "Arn": "arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:apps/6e0b7591a90841d2b5d93fa11143e5a7/campaigns/a1e63c6cc0eb43ed826ffcc3cc90b30d",
                "CreationDate": "2019-10-08T18:40:16.581Z",
                "Description": " ",
                "HoldoutPercent": 0,
                "Id": "a1e63c6cc0eb43ed826ffcc3cc90b30d",
                "IsPaused": false,
                "LastModifiedDate": "2019-10-08T18:40:16.581Z",
                "Limits": {
                    "Daily": 0,
                    "MaximumDuration": 60,
                    "MessagesPerSecond": 50,
                    "Total": 0
                },
                "MessageConfiguration": {
                    "EmailMessage": {
                        "FromAddress": "sender@example.com",
                        "HtmlBody": "<!DOCTYPE html>\n    <html lang=\"en\">\n    <head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n</head>\n<body>Demo</body>\n</html>",
                        "Title": "PinpointDemo"
                    }
                },
                "Name": "MyCampaign2",
                "Schedule": {
                    "IsLocalTime": false,
                    "StartTime": "IMMEDIATE",
                    "Timezone": "utc"
                },
                "SegmentId": "b66c9e42f71444b2aa2e0ffc1df28f60",
                "SegmentVersion": 1,
                "State": {
                    "CampaignStatus": "COMPLETED"
                },
                "tags": {},
                "TemplateConfiguration": {},
                "Version": 1
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCampaigns](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-campaigns.html)」を参照してください。

### `get-channels`
<a name="pinpoint_GetChannels_cli_2_topic"></a>

次のコード例は、`get-channels` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの各チャンネルの履歴とステータスに関する情報を取得するには**  
次の `get-channels` の例では、アプリケーションの各チャンネルの履歴とステータスに関する情報を取得します。  

```
aws pinpoint get-channels \
    --application-id 6e0b7591a90841d2b5d93fa11143e5a7 \
    --region us-east-1
```
出力:  

```
{
    "ChannelsResponse": {
        "Channels": {
            "GCM": {
                "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
                "CreationDate": "2019-10-08T18:28:23.182Z",
                "Enabled": true,
                "HasCredential": true,
                "Id": "gcm",
                "IsArchived": false,
                "LastModifiedDate": "2019-10-08T18:28:23.182Z",
                "Version": 1
            },
            "SMS": {
                "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
                "CreationDate": "2019-10-08T18:39:18.511Z",
                "Enabled": true,
                "Id": "sms",
                "IsArchived": false,
                "LastModifiedDate": "2019-10-08T18:39:18.511Z",
                "Version": 1
            },
            "EMAIL": {
                "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
                "CreationDate": "2019-10-08T18:27:23.990Z",
                "Enabled": true,
                "Id": "email",
                "IsArchived": false,
                "LastModifiedDate": "2019-10-08T18:27:23.990Z",
                "Version": 1
            },
            "IN_APP": {
                "Enabled": true,
                "IsArchived": false,
                "Version": 0
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetChannels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-channels.html)」を参照してください。

### `get-email-channel`
<a name="pinpoint_GetEmailChannel_cli_2_topic"></a>

次のコード例は、`get-email-channel` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの E メールチャネルのステータスと設定に関する情報を取得するには**  
次の `get-email-channel` の例では、アプリケーションの E メールチャネルのステータスと設定を取得します。  

```
aws pinpoint get-email-channel \
    --application-id 6e0b7591a90841d2b5d93fa11143e5a7 \
    --region us-east-1
```
出力:  

```
{
    "EmailChannelResponse": {
        "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
        "CreationDate": "2019-10-08T18:27:23.990Z",
        "Enabled": true,
        "FromAddress": "sender@example.com",
        "Id": "email",
        "Identity": "arn:aws:ses:us-east-1:AIDACKCEVSQ6C2EXAMPLE:identity/sender@example.com",
        "IsArchived": false,
        "LastModifiedDate": "2019-10-08T18:27:23.990Z",
        "MessagesPerSecond": 1,
        "Platform": "EMAIL",
        "RoleArn": "arn:aws:iam::AIDACKCEVSQ6C2EXAMPLE:role/pinpoint-events",
        "Version": 1
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEmailChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-email-channel.html)」を参照してください。

### `get-endpoint`
<a name="pinpoint_GetEndpoint_cli_2_topic"></a>

次のコード例は、`get-endpoint` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの特定のエンドポイントの設定と属性に関する情報を取得するには**  
次の `get-endpoint` の例は、アプリケーションの指定されたエンドポイントの設定と属性に関する情報を取得します。  

```
aws pinpoint get-endpoint \
    --application-id 611e3e3cdd47474c9c1399a505665b91 \
    --endpoint-id testendpoint \
    --region us-east-1
```
出力:  

```
{
    "EndpointResponse": {
        "Address": "+11234567890",
        "ApplicationId": "611e3e3cdd47474c9c1399a505665b91",
        "Attributes": {},
        "ChannelType": "SMS",
        "CohortId": "63",
        "CreationDate": "2019-01-28T23:55:11.534Z",
        "EffectiveDate": "2021-08-06T00:04:51.763Z",
        "EndpointStatus": "ACTIVE",
        "Id": "testendpoint",
        "Location": {
            "Country": "USA"
        },
        "Metrics": {
            "SmsDelivered": 1.0
        },
        "OptOut": "ALL",
        "RequestId": "a204b1f2-7e26-48a7-9c80-b49a2143489d",
        "User": {
            "UserAttributes": {
                "Age": [
                    "24"
                ]
            },
        "UserId": "testuser"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-endpoint.html)」を参照してください。

### `get-gcm-channel`
<a name="pinpoint_GetGcmChannel_cli_2_topic"></a>

次のコード例は、`get-gcm-channel` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの GCM チャネルのステータスと設定に関する情報を取得するには**  
次の `get-gcm-channel` の例では、アプリケーションの GCM チャネルのステータスと設定に関する情報を取得します。  

```
aws pinpoint get-gcm-channel \
    --application-id 6e0b7591a90841d2b5d93fa11143e5a7 \
    --region us-east-1
```
出力:  

```
{
    "GCMChannelResponse": {
        "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
        "CreationDate": "2019-10-08T18:28:23.182Z",
        "Enabled": true,
        "HasCredential": true,
        "Id": "gcm",
        "IsArchived": false,
        "LastModifiedDate": "2019-10-08T18:28:23.182Z",
        "Platform": "GCM",
        "Version": 1
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGcmChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-gcm-channel.html)」を参照してください。

### `get-sms-channel`
<a name="pinpoint_GetSmsChannel_cli_2_topic"></a>

次のコード例は、`get-sms-channel` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの SMS チャネルのステータスおよび設定に関する情報を取得するには**  
次の `get-sms-channel` の例は、アプリケーションの SMS チャネルのステータスと設定を取得します。  

```
aws pinpoint get-sms-channel \
    --application-id 6e0b7591a90841d2b5d93fa11143e5a7 \
    --region us-east-1
```
出力:  

```
{
    "SMSChannelResponse": {
        "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
        "CreationDate": "2019-10-08T18:39:18.511Z",
        "Enabled": true,
        "Id": "sms",
        "IsArchived": false,
        "LastModifiedDate": "2019-10-08T18:39:18.511Z",
        "Platform": "SMS",
        "PromotionalMessagesPerSecond": 20,
        "TransactionalMessagesPerSecond": 20,
        "Version": 1
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetSmsChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-sms-channel.html)」を参照してください。**

### `get-sms-template`
<a name="pinpoint_GetSmsTemplate_cli_2_topic"></a>

次のコード例は、`get-sms-template` を使用する方法を示しています。

**AWS CLI**  
**SMS チャネルを介して送信されるメッセージのメッセージテンプレートの内容と設定を取得します**  
次の `get-sms-template` の例では、SMS メッセージテンプレートの内容と設定を取得します。  

```
aws pinpoint get-sms-template \
    --template-name TestTemplate \
    --region us-east-1
```
出力:  

```
{
    "SMSTemplateResponse": {
        "Arn": "arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:templates/TestTemplate/SMS",
        "Body": "hello\n how are you?\n food is good",
        "CreationDate": "2023-06-20T21:37:30.124Z",
        "LastModifiedDate": "2023-06-20T21:37:30.124Z",
        "tags": {},
        "TemplateDescription": "Test SMS Template",
        "TemplateName": "TestTemplate",
        "TemplateType": "SMS",
        "Version": "1"
    }
}
```
詳細については、「*Amazon Pinpoint User Guide*」の「[Amazon Pinpoint message templates](https://docs.aws.amazon.com/pinpoint/latest/userguide/messages-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSmsTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-sms-template.html)」を参照してください。

### `get-voice-channel`
<a name="pinpoint_GetVoiceChannel_cli_2_topic"></a>

次のコード例は、`get-voice-channel` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションの音声チャンネルのステータスと設定に関する情報を取得するには**  
次の `get-voice-channel` の例では、アプリケーションの音声チャネルのステータスと設定を取得します。  

```
aws pinpoint get-voice-channel \
    --application-id 6e0b7591a90841d2b5d93fa11143e5a7 \
    --region us-east-1
```
出力:  

```
{
    "VoiceChannelResponse": {
        "ApplicationId": "6e0b7591a90841d2b5d93fa11143e5a7",
        "CreationDate": "2022-04-28T00:17:03.836Z",
        "Enabled": true,
        "Id": "voice",
        "IsArchived": false,
        "LastModifiedDate": "2022-04-28T00:17:03.836Z",
        "Platform": "VOICE",
        "Version": 1
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVoiceChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/get-voice-channel.html)」を参照してください。

### `list-tags-for-resource`
<a name="pinpoint_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグの一覧を取得するには**  
次の `list-tags-for-resource` の例では、指定されたリソースに関連付けられているすべてのタグ (キー名と値) を取得します。  

```
aws pinpoint list-tags-for-resource \
    --resource-arn arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example
```
出力:  

```
{
    "TagsModel": {
        "tags": {
            "Year": "2019",
            "Stack": "Production"
        }
    }
}
```
詳細については、「*Amazon Pinpoint Developer Guide*」の「Tagging Amazon Pinpoint Resources <https://docs.aws.amazon.com/pinpoint/latest/developerguide/tagging-resources.html>」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/list-tags-for-resource.html)」を参照してください。

### `phone-number-validate`
<a name="pinpoint_PhoneNumberValidate_cli_2_topic"></a>

次のコード例は、`phone-number-validate` を使用する方法を示しています。

**AWS CLI**  
**電話番号に関する情報を取得します**  
次の `phone-number-validate` では、電話番号に関する情報を取得します。　  

```
aws pinpoint phone-number-validate \
    --number-validate-request PhoneNumber="+12065550142" \
    --region us-east-1
```
出力:  

```
{
    "NumberValidateResponse": {
        "Carrier": "ExampleCorp Mobile",
        "City": "Seattle",
        "CleansedPhoneNumberE164": "+12065550142",
        "CleansedPhoneNumberNational": "2065550142",
        "Country": "United States",
        "CountryCodeIso2": "US",
        "CountryCodeNumeric": "1",
        "OriginalPhoneNumber": "+12065550142",
        "PhoneType": "MOBILE",
        "PhoneTypeCode": 0,
        "Timezone": "America/Los_Angeles",
        "ZipCode": "98101"
    }
}
```
詳細については、「Amazon Pinpoint ユーザーガイド」の「[Amazon Pinpoint SMS チャンネル](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PhoneNumberValidate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/phone-number-validate.html)」を参照してください。

### `send-messages`
<a name="pinpoint_SendMessages_cli_2_topic"></a>

次のコード例は、`send-messages` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションのエンドポイントを使用して SMS メッセージを送信するには**  
次の `send-messages` の例は、エンドポイントを使用してアプリケーションにダイレクトメッセージを送信します。  

```
aws pinpoint send-messages \
    --application-id 611e3e3cdd47474c9c1399a505665b91 \
    --message-request file://myfile.json \
    --region us-west-2
```
`myfile.json` の内容:  

```
{
    "MessageConfiguration": {
        "SMSMessage": {
            "Body": "hello, how are you?"
        }
    },
    "Endpoints": {
        "testendpoint": {}
    }
}
```
出力:  

```
{
    "MessageResponse": {
        "ApplicationId": "611e3e3cdd47474c9c1399a505665b91",
        "EndpointResult": {
            "testendpoint": {
                "Address": "+12345678900",
                "DeliveryStatus": "SUCCESSFUL",
                "MessageId": "itnuqhai5alf1n6ahv3udc05n7hhddr6gb3lq6g0",
                "StatusCode": 200,
                "StatusMessage": "MessageId: itnuqhai5alf1n6ahv3udc05n7hhddr6gb3lq6g0"
            }
        },
        "RequestId": "c7e23264-04b2-4a46-b800-d24923f74753"
    }
}
```
詳細については、「Amazon Pinpoint ユーザーガイド」の「[Amazon Pinpoint SMS チャンネル](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[SendMessages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/send-messages.html)」を参照してください。

### `send-users-messages`
<a name="pinpoint_SendUsersMessages_cli_2_topic"></a>

次のコード例は、`send-users-messages` を使用する方法を示しています。

**AWS CLI**  
**アプリケーションのユーザーに SMS メッセージを送信するには**  
次の `send-users-messages` の例では、アプリケーションのユーザー向けのダイレクトメッセージを送信します。  

```
aws pinpoint send-users-messages \
    --application-id 611e3e3cdd47474c9c1399a505665b91 \
    --send-users-message-request file://myfile.json \
    --region us-west-2
```
`myfile.json` の内容:  

```
{
    "MessageConfiguration": {
        "SMSMessage": {
            "Body": "hello, how are you?"
        }
    },
    "Users": {
        "testuser": {}
    }
}
```
出力:  

```
{
    "SendUsersMessageResponse": {
        "ApplicationId": "611e3e3cdd47474c9c1399a505665b91",
        "RequestId": "e0b12cf5-2359-11e9-bb0b-d5fb91876b25",
        "Result": {
            "testuser": {
                "testuserendpoint": {
                    "DeliveryStatus": "SUCCESSFUL",
                    "MessageId": "7qu4hk5bqhda3i7i2n4pjf98qcuh8b7p45ifsmo0",
                    "StatusCode": 200,
                    "StatusMessage": "MessageId: 7qu4hk5bqhda3i7i2n4pjf98qcuh8b7p45ifsmo0",
                    "Address": "+12345678900"
                }
            }
        }
    }
}
```
詳細については、「Amazon Pinpoint ユーザーガイド」の「[Amazon Pinpoint SMS チャンネル](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendUsersMessages](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/send-users-messages.html)」を参照してください。

### `tag-resource`
<a name="pinpoint_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加するには**  
次の例では、リソースに 2 つのタグ (キー名と値) を追加します。  

```
aws pinpoint list-tags-for-resource \
    --resource-arn arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example \
    --tags-model tags={Stack=Production,Year=2019}
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Pinpoint Developer Guide*」の「Tagging Amazon Pinpoint Resources <https://docs.aws.amazon.com/pinpoint/latest/developerguide/tagging-resources.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="pinpoint_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースからタグを削除するには**  
次の `untag-resource` の例では、指定されたタグ (キー名と値) をリソースから削除します。  

```
aws pinpoint untag-resource \
    --resource-arn arn:aws:mobiletargeting:us-west-2:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example \
    --tag-keys Year
```
このコマンドでは何も出力されません。  
**例 2: リソースから複数のタグを削除するには**  
次の `untag-resource` の例では、指定されたタグ (キー名と値) をリソースから削除します。  

```
aws pinpoint untag-resource \
    --resource-arn arn:aws:mobiletargeting:us-east-1:AIDACKCEVSQ6C2EXAMPLE:apps/810c7aab86d42fb2b56c8c966example \
    --tag-keys Year Stack
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Pinpoint Developer Guide*」の「Tagging Amazon Pinpoint Resources <https://docs.aws.amazon.com/pinpoint/latest/developerguide/tagging-resources.html>」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/untag-resource.html)」を参照してください。

### `update-sms-channel`
<a name="pinpoint_UpdateSmsChannel_cli_2_topic"></a>

次のコード例は、`update-sms-channel` を使用する方法を示しています。

**AWS CLI**  
**SMS チャネルを有効にするか、アプリケーションの SMS チャネルのステータスと設定を更新するには**  
次の `update-sms-channel` の例では、アプリケーションの SMS チャネルの SMS チャネルを有効にします。  

```
aws pinpoint update-sms-channel \
    --application-id 611e3e3cdd47474c9c1399a505665b91 \
    --sms-channel-request Enabled=true \
    --region us-west-2
```
出力:  

```
{
    "SMSChannelResponse": {
        "ApplicationId": "611e3e3cdd47474c9c1399a505665b91",
        "CreationDate": "2019-01-28T23:25:25.224Z",
        "Enabled": true,
        "Id": "sms",
        "IsArchived": false,
        "LastModifiedDate": "2023-05-18T23:22:50.977Z",
        "Platform": "SMS",
        "PromotionalMessagesPerSecond": 20,
        "TransactionalMessagesPerSecond": 20,
        "Version": 3
    }
}
```
詳細については、「Amazon Pinpoint ユーザーガイド」の「[Amazon Pinpoint SMS チャンネル](https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSmsChannel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pinpoint/update-sms-channel.html)」を参照してください。

# を使用した Amazon Polly の例 AWS CLI
<a name="cli_2_polly_code_examples"></a>

次のコード例は、Amazon Polly AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-lexicon`
<a name="polly_DeleteLexicon_cli_2_topic"></a>

次のコード例は、`delete-lexicon` を使用する方法を示しています。

**AWS CLI**  
**レキシコンを削除するには**  
次の `delete-lexicon` の例は、指定されたレキシコンを削除します。  

```
aws polly delete-lexicon \
    --name w3c
```
このコマンドでは何も出力されません。  
詳細については、「Amazon Polly ディベロッパーガイド」の「[DeleteLexicon オペレーションの使用](https://docs.aws.amazon.com/polly/latest/dg/gs-delete-lexicon.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteLexicon](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/polly/delete-lexicon.html)」を参照してください。**

### `get-lexicon`
<a name="polly_GetLexicon_cli_2_topic"></a>

次のコード例は、`get-lexicon` を使用する方法を示しています。

**AWS CLI**  
**レキシコンの内容を取得するには**  
次の `get-lexicon` の例は、指定された発音レキシコンの内容を取得します。  

```
aws polly get-lexicon \
    --name w3c
```
出力:  

```
{
    "Lexicon": {
        "Content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<lexicon version=\"1.0\" \n      xmlns=    \"http://www.w3.org/2005/01/pronunciation-lexicon\"\n      xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" \n          xsi:schemaLocation=\"http://www.w3.org/2005/01/pronunciation-lexicon \n        http://www.w3.org/TR/2007/CR-pronunciation-    lexicon-20071212/pls.xsd\"\n      alphabet=\"ipa\" \n      xml:lang=\"en-US\">\n  <lexeme>\n    <grapheme>W3C</grapheme>\n        <alias>World Wide Web Consortium</alias>\n  </lexeme>\n</lexicon>\n",
        "Name": "w3c"
    },
    "LexiconAttributes": {
        "Alphabet": "ipa",
        "LanguageCode": "en-US",
        "LastModified": 1603908910.99,
        "LexiconArn": "arn:aws:polly:us-west-2:880185128111:lexicon/w3c",
        "LexemesCount": 1,
        "Size": 492
    }
}
```
詳細については、「Amazon Polly ディベロッパーガイド」の「[GetLexicon オペレーションの使用](https://docs.aws.amazon.com/polly/latest/dg/gs-get-lexicon.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetLexicon](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/polly/get-lexicon.html)」を参照してください。**

### `get-speech-synthesis-task`
<a name="polly_GetSpeechSynthesisTask_cli_2_topic"></a>

次のコード例は、`get-speech-synthesis-task` を使用する方法を示しています。

**AWS CLI**  
**音声合成タスクに関する情報を取得するには**  
次の `get-speech-synthesis-task` の例は、指定された音声合成タスクに関する情報を取得します。  

```
aws polly get-speech-synthesis-task \
    --task-id 70b61c0f-57ce-4715-a247-cae8729dcce9
```
出力:  

```
{
    "SynthesisTask": {
        "TaskId": "70b61c0f-57ce-4715-a247-cae8729dcce9",
        "TaskStatus": "completed",
        "OutputUri": "https://s3.us-west-2.amazonaws.com/amzn-s3-demo-bucket/70b61c0f-57ce-4715-a247-cae8729dcce9.mp3",
        "CreationTime": 1603911042.689,
        "RequestCharacters": 1311,
        "OutputFormat": "mp3",
        "TextType": "text",
        "VoiceId": "Joanna"
    }
}
```
詳細については、「Amazon Polly ディベロッパーガイド」の「[長いオーディオファイルの作成 (CLI)](https://docs.aws.amazon.com/polly/latest/dg/longer-cli.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetSpeechSynthesisTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/polly/get-speech-synthesis-task.html)」を参照してください。**

### `list-lexicons`
<a name="polly_ListLexicons_cli_2_topic"></a>

次のコード例は、`list-lexicons` を使用する方法を示しています。

**AWS CLI**  
**レキシコンを一覧表示するには**  
次の `list-lexicons` の例は、発音レキシコンを一覧表示します。  

```
aws polly list-lexicons
```
出力:  

```
{
    "Lexicons": [
        {
            "Name": "w3c",
            "Attributes": {
                "Alphabet": "ipa",
                "LanguageCode": "en-US",
                "LastModified": 1603908910.99,
                "LexiconArn": "arn:aws:polly:us-east-2:123456789012:lexicon/w3c",
                "LexemesCount": 1,
                "Size": 492
            }
        }
    ]
}
```
詳細については、「Amazon Polly ディベロッパーガイド」の「[ListLexicons オペレーションの使用](https://docs.aws.amazon.com/polly/latest/dg/gs-list-lexicons.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListLexicons](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/polly/list-lexicons.html)」を参照してください。**

### `list-speech-synthesis-tasks`
<a name="polly_ListSpeechSynthesisTasks_cli_2_topic"></a>

次のコード例は、`list-speech-synthesis-tasks` を使用する方法を示しています。

**AWS CLI**  
**音声合成タスクを一覧表示するには**  
次の `list-speech-synthesis-tasks` の例では、音声合成タスクを一覧表示します。  

```
aws polly list-speech-synthesis-tasks
```
出力:  

```
{
    "SynthesisTasks": [
        {
            "TaskId": "70b61c0f-57ce-4715-a247-cae8729dcce9",
            "TaskStatus": "completed",
            "OutputUri": "https://s3.us-west-2.amazonaws.com/amzn-s3-demo-bucket/70b61c0f-57ce-4715-a247-cae8729dcce9.mp3",
            "CreationTime": 1603911042.689,
            "RequestCharacters": 1311,
            "OutputFormat": "mp3",
            "TextType": "text",
            "VoiceId": "Joanna"
        }
    ]
}
```
詳細については、「Amazon Polly ディベロッパーガイド」の「[長いオーディオファイルの作成 (CLI)](https://docs.aws.amazon.com/polly/latest/dg/longer-cli.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSpeechSynthesisTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/polly/list-speech-synthesis-tasks.html)」を参照してください。

### `put-lexicon`
<a name="polly_PutLexicon_cli_2_topic"></a>

次のコード例は、`put-lexicon` を使用する方法を示しています。

**AWS CLI**  
**レキシコンを保存するには**  
次の `put-lexicon` の例は、指定された発音レキシコンを保存します。`example.pls` ファイルは W3C PLS 準拠のレキシコンを指定します。  

```
aws polly put-lexicon \
    --name w3c \
    --content file://example.pls
```
`example.pls` の内容  

```
{
    <?xml version="1.0" encoding="UTF-8"?>
    <lexicon version="1.0"
        xmlns="http://www.w3.org/2005/01/pronunciation-lexicon"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.w3.org/2005/01/pronunciation-lexicon
            http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd"
        alphabet="ipa"
        xml:lang="en-US">
        <lexeme>
            <grapheme>W3C</grapheme>
            <alias>World Wide Web Consortium</alias>
        </lexeme>
    </lexicon>
}
```
このコマンドでは何も出力されません。  
詳細については、「Amazon Polly ディベロッパーガイド」の「[PutLexicon オペレーションの使用](https://docs.aws.amazon.com/polly/latest/dg/gs-put-lexicon.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutLexicon](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/polly/put-lexicon.html)」を参照してください。**

### `start-speech-synthesis-task`
<a name="polly_StartSpeechSynthesisTask_cli_2_topic"></a>

次のコード例は、`start-speech-synthesis-task` を使用する方法を示しています。

**AWS CLI**  
**テキストを合成するには**  
次の `start-speech-synthesis-task` の例は、`text_file.txt` 内のテキストを合成し、生成された MP3 ファイルを指定されたバケットに保存します。  

```
aws polly start-speech-synthesis-task \
    --output-format mp3 \
    --output-s3-bucket-name amzn-s3-demo-bucket \
    --text  file://text_file.txt \
    --voice-id Joanna
```
出力:  

```
{
    "SynthesisTask": {
        "TaskId": "70b61c0f-57ce-4715-a247-cae8729dcce9",
        "TaskStatus": "scheduled",
        "OutputUri": "https://s3.us-east-2.amazonaws.com/amzn-s3-demo-bucket/70b61c0f-57ce-4715-a247-cae8729dcce9.mp3",
        "CreationTime": 1603911042.689,
        "RequestCharacters": 1311,
        "OutputFormat": "mp3",
        "TextType": "text",
        "VoiceId": "Joanna"
    }
}
```
詳細については、「Amazon Polly ディベロッパーガイド」の「[長いオーディオファイルの作成 (CLI)](https://docs.aws.amazon.com/polly/latest/dg/longer-cli.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[StartSpeechSynthesisTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/polly/start-speech-synthesis-task.html)」を参照してください。**

# AWS の料金表 を使用した の例 AWS CLI
<a name="cli_2_pricing_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS の料金表。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-services`
<a name="pricing_DescribeServices_cli_2_topic"></a>

次のコード例は、`describe-services` を使用する方法を示しています。

**AWS CLI**  
**サービスメタデータを取得するには**  
この例では、Amazon EC2 サービスコードのメタデータを取得します。  
コマンド:  

```
aws pricing describe-services --service-code AmazonEC2 --format-version aws_v1 --max-items 1
```
出力:  

```
{
  "Services": [
      {
          "ServiceCode": "AmazonEC2",
          "AttributeNames": [
              "volumeType",
              "maxIopsvolume",
              "instance",
              "instanceCapacity10xlarge",
              "locationType",
              "instanceFamily",
              "operatingSystem",
              "clockSpeed",
              "LeaseContractLength",
              "ecu",
              "networkPerformance",
              "instanceCapacity8xlarge",
              "group",
              "maxThroughputvolume",
              "gpuMemory",
              "ebsOptimized",
              "elasticGpuType",
              "maxVolumeSize",
              "gpu",
              "processorFeatures",
              "intelAvxAvailable",
              "instanceCapacity4xlarge",
              "servicecode",
              "groupDescription",
              "processorArchitecture",
              "physicalCores",
              "productFamily",
              "enhancedNetworkingSupported",
              "intelTurboAvailable",
              "memory",
              "dedicatedEbsThroughput",
              "vcpu",
              "OfferingClass",
              "instanceCapacityLarge",
              "capacitystatus",
              "termType",
              "storage",
              "intelAvx2Available",
              "storageMedia",
              "physicalProcessor",
              "provisioned",
              "servicename",
              "PurchaseOption",
              "instanceCapacity18xlarge",
              "instanceType",
              "tenancy",
              "usagetype",
              "normalizationSizeFactor",
              "instanceCapacity2xlarge",
              "instanceCapacity16xlarge",
              "maxIopsBurstPerformance",
              "instanceCapacity12xlarge",
              "instanceCapacity32xlarge",
              "instanceCapacityXlarge",
              "licenseModel",
              "currentGeneration",
              "preInstalledSw",
              "location",
              "instanceCapacity24xlarge",
              "instanceCapacity9xlarge",
              "instanceCapacityMedium",
              "operation"
          ]
      }
  ],
  "FormatVersion": "aws_v1"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pricing/describe-services.html)」を参照してください。

### `get-attribute-values`
<a name="pricing_GetAttributeValues_cli_2_topic"></a>

次のコード例は、`get-attribute-values` を使用する方法を示しています。

**AWS CLI**  
**属性値のリストを取得するには**  
次の `get-attribute-values` の例では、特定の属性で使用できる値のリストを取得します。  

```
aws pricing get-attribute-values \
    --service-code AmazonEC2 \
    --attribute-name volumeType \
    --max-items 2
```
出力:  

```
{
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ==",
    "AttributeValues": [
        {
            "Value": "Cold HDD"
        },
        {
            "Value": "General Purpose"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAttributeValues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pricing/get-attribute-values.html)」を参照してください。

### `get-products`
<a name="pricing_GetProducts_cli_2_topic"></a>

次のコード例は、`get-products` を使用する方法を示しています。

**AWS CLI**  
**製品のリストを取得するには**  
この例では、指定された条件に一致する製品のリストを取得します。  
コマンド:  

```
aws pricing get-products --filters file://filters.json --format-version aws_v1 --max-results 1 --service-code AmazonEC2
```
filters.json:  

```
        [
  {
    "Type": "TERM_MATCH",
    "Field": "ServiceCode",
    "Value": "AmazonEC2"
  },
  {
    "Type": "TERM_MATCH",
    "Field": "volumeType",
    "Value": "Provisioned IOPS"
  }
]
```
出力:  

```
{
  "FormatVersion": "aws_v1",
  "NextToken": "WGDY7ko8fQXdlaUZVdasFQ==:RVSagyIFn770XQOzdUIcO9BY6ucBG9itXAZGZF/zioUzOsUKh6PCcPWaOyPZRiMePb986TeoKYB9l55fw/CyoMq5ymnGmT1Vj39TljbbAlhcqnVfTmPIilx8Uy5bdDaBYy/e/2Ofw9Edzsykbs8LTBuNbiDQ+BBds5yeI9AQkUepruKk3aEahFPxJ55kx/zk",
  "PriceList": [
      "{\"product\":{\"productFamily\":\"Storage\",\"attributes\":{\"storageMedia\":\"SSD-backed\",\"maxThroughputvolume\":\"320 MB/sec\",\"volumeType\":\"Provisioned IOPS\",\"maxIopsvolume\":\"20000\",\"servicecode\":\"AmazonEC2\",\"usagetype\":\"APS1-EBS:VolumeUsage.piops\",\"locationType\":\"AWS Region\",\"location\":\"Asia Pacific (Singapore)\",\"servicename\":\"Amazon Elastic Compute Cloud\",\"maxVolumeSize\":\"16 TiB\",\"operation\":\"\"},\"sku\":\"3MKHN58N7RDDVGKJ\"},\"serviceCode\":\"AmazonEC2\",\"terms\":{\"OnDemand\":{\"3MKHN58N7RDDVGKJ.JRTCKXETXF\":{\"priceDimensions\":{\"3MKHN58N7RDDVGKJ.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"GB-Mo\",\"endRange\":\"Inf\",\"description\":\"$0.138 per GB-month of Provisioned IOPS SSD (io1)  provisioned storage - Asia Pacific (Singapore)\",\"appliesTo\":[],\"rateCode\":\"3MKHN58N7RDDVGKJ.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.1380000000\"}}},\"sku\":\"3MKHN58N7RDDVGKJ\",\"effectiveDate\":\"2018-08-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20180808005701\",\"publicationDate\":\"2018-08-08T00:57:01Z\"}"
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetProducts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pricing/get-products.html)」を参照してください。

# AWS Private CA を使用した の例 AWS CLI
<a name="cli_2_acm-pca_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Private CA。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-certificate-authority-audit-report`
<a name="acm-pca_CreateCertificateAuthorityAuditReport_cli_2_topic"></a>

次のコード例では、`create-certificate-authority-audit-report` を使用する方法を示しています。

**AWS CLI**  
**認証機関監査レポートを作成する方法**  
次の `create-certificate-authority-audit-report` のコマンドは、ARN によって識別されるプライベート CA の監査レポートを作成します。  

```
aws acm-pca create-certificate-authority-audit-report --certificate-authority-arn arn:aws:acm-pca:us-east-1:accountid:certificate-authority/12345678-1234-1234-1234-123456789012 --s3-bucket-name your-bucket-name --audit-report-response-format JSON
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCertificateAuthorityAuditReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/create-certificate-authority-audit-report.html)」を参照してください。

### `create-certificate-authority`
<a name="acm-pca_CreateCertificateAuthority_cli_2_topic"></a>

次のコード例では、`create-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**プライベート認証局を作成する方法**  
次の`create-certificate-authority`コマンドは、 AWS アカウントにプライベート認証機関を作成します。  

```
aws acm-pca create-certificate-authority --certificate-authority-configuration file://C:\ca_config.txt --revocation-configuration file://C:\revoke_config.txt --certificate-authority-type "SUBORDINATE" --idempotency-token 98256344
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/create-certificate-authority.html)」を参照してください。

### `delete-certificate-authority`
<a name="acm-pca_DeleteCertificateAuthority_cli_2_topic"></a>

次のコード例では、`delete-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**プライベート認証局を削除する方法**  
次の `delete-certificate-authority` のコマンドは、ARN によって識別される認証局を削除します。  

```
aws acm-pca delete-certificate-authority --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/delete-certificate-authority.html)」を参照してください。

### `describe-certificate-authority-audit-report`
<a name="acm-pca_DescribeCertificateAuthorityAuditReport_cli_2_topic"></a>

次のコード例では、`describe-certificate-authority-audit-report` を使用する方法を示しています。

**AWS CLI**  
**認証機関監査レポートを作成する方法**  
次の `describe-certificate-authority-audit-report` のコマンドは、ARN によって識別される CA の指定された監査レポートに関する情報を一覧表示します。  

```
aws acm-pca describe-certificate-authority-audit-report --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/99999999-8888-7777-6666-555555555555 --audit-report-id 11111111-2222-3333-4444-555555555555
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCertificateAuthorityAuditReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/describe-certificate-authority-audit-report.html)」を参照してください。

### `describe-certificate-authority`
<a name="acm-pca_DescribeCertificateAuthority_cli_2_topic"></a>

次のコード例では、`describe-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**プライベート認証局を作成する方法**  
次の `describe-certificate-authority` のコマンドは、ARN によって識別されるプライベート CA に関する情報を一覧表示します。  

```
aws acm-pca describe-certificate-authority --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/describe-certificate-authority.html)」を参照してください。

### `get-certificate-authority-certificate`
<a name="acm-pca_GetCertificateAuthorityCertificate_cli_2_topic"></a>

次のコード例では、`get-certificate-authority-certificate` を使用する方法を示しています。

**AWS CLI**  
**認証局 (CA) 証明書を取得する方法**  
次の `get-certificate-authority-certificate` のコマンドは、ARN によって指定されたプライベート CA の認証と認証チェーンの証明書を取得します。  

```
aws acm-pca get-certificate-authority-certificate --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012 --output text
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCertificateAuthorityCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/get-certificate-authority-certificate.html)」を参照してください。

### `get-certificate-authority-csr`
<a name="acm-pca_GetCertificateAuthorityCsr_cli_2_topic"></a>

次のコード例では、`get-certificate-authority-csr` を使用する方法を示しています。

**AWS CLI**  
**認証機関の証明書署名リクエストを取得する方法**  
次の `get-certificate-authority-csr` のコマンドは、ARN によって指定されたプライベート CA の CSR を取得します。  

```
aws acm-pca get-certificate-authority-csr --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012 --output text
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCertificateAuthorityCsr](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/get-certificate-authority-csr.html)」を参照してください。

### `get-certificate`
<a name="acm-pca_GetCertificate_cli_2_topic"></a>

次のコード例では、`get-certificate` を使用する方法を示しています。

**AWS CLI**  
**発行された証明書を取得する方法**  
次の `get-certificate` の例では、指定されたプライベート CA から証明書を取得します。  

```
aws acm-pca get-certificate \
    --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012 \
    --certificate-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012/certificate/6707447683a9b7f4055627ffd55cebcc \
    --output text
```
出力:  

```
-----BEGIN CERTIFICATE-----
MIIEDzCCAvegAwIBAgIRAJuJ8f6ZVYL7gG/rS3qvrZMwDQYJKoZIhvcNAQELBQAw
cTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1Nl
    ....certificate body truncated for brevity....
tKCSglgZZrd4FdLw1EkGm+UVXnodwMtJEQyy3oTfZjURPIyyaqskTu/KSS7YDjK0
KQNy73D6LtmdOEbAyq10XiDxqY41lvKHJ1eZrPaBmYNABxU=
-----END CERTIFICATE---- -----BEGIN CERTIFICATE-----
MIIDrzCCApegAwIBAgIRAOskdzLvcj1eShkoyEE693AwDQYJKoZIhvcNAQELBQAw
cTELMAkGA1UEBhMCVVMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1Nl
    ...certificate body truncated for brevity....
kdRGB6P2hpxstDOUIwAoCbhoaWwfA4ybJznf+jOQhAziNlRdKQRR8nODWpKt7H9w
dJ5nxsTk/fniJz86Ddtp6n8s82wYdkN3cVffeK72A9aTCOU=
-----END CERTIFICATE-----
```
出力の最初のパートは証明書それ自体です。2 番目のパートは、ルート CA 証明書に連鎖する証明書チェーンです。`--output text` オプションを使用すると、2 つの証明書部分の間に `TAB` 文字が挿入されることに注意してください (これによってテキストがインデントされます）。この出力を取得し、証明書を他のツールで解析する場合は、`TAB` 文字を削除して正しく処理する必要が生じる場合があります。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/get-certificate.html)」を参照してください。

### `import-certificate-authority-certificate`
<a name="acm-pca_ImportCertificateAuthorityCertificate_cli_2_topic"></a>

次のコード例では、`import-certificate-authority-certificate` を使用する方法を示しています。

**AWS CLI**  
**認証局証明書を ACM PCA にインポートする方法**  
次の `import-certificate-authority-certificate` のコマンドは、ARN によって指定された CA の署名付きプライベート CA 証明書を ACM PCA にインポートします。  

```
aws acm-pca import-certificate-authority-certificate --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012 --certificate file://C:\ca_cert.pem --certificate-chain file://C:\ca_cert_chain.pem
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportCertificateAuthorityCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/import-certificate-authority-certificate.html)」を参照してください。

### `issue-certificate`
<a name="acm-pca_IssueCertificate_cli_2_topic"></a>

次のコード例では、`issue-certificate` を使用する方法を示しています。

**AWS CLI**  
**プライベート証明書を発行する方法**  
次の `issue-certificate` のコマンドは、ARN で指定されたプライベート CA を使用してプライベート証明書を発行します。  

```
aws acm-pca issue-certificate --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012 --csr file://C:\cert_1.csr --signing-algorithm "SHA256WITHRSA" --validity Value=365,Type="DAYS" --idempotency-token 1234
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IssueCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/issue-certificate.html)」を参照してください。

### `list-certificate-authorities`
<a name="acm-pca_ListCertificateAuthorities_cli_2_topic"></a>

次のコード例では、`list-certificate-authorities` を使用する方法を示しています。

**AWS CLI**  
**プライベート認証機関を一覧表示する方法**  
次の `list-certificate-authorities` のコマンドは、アカウントのすべてのプライベート CA に関する情報を一覧表示します。  

```
aws acm-pca list-certificate-authorities --max-results 10
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCertificateAuthorities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/list-certificate-authorities.html)」を参照してください。

### `list-tags`
<a name="acm-pca_ListTags_cli_2_topic"></a>

次のコード例では、`list-tags` を使用する方法を示しています。

**AWS CLI**  
**認証機関のタグを一覧表示する方法**  
次の `list-tags` のコマンドは、ARN で指定されたプライベート CA に関連付けられたタグを一覧表示します。  

```
aws acm-pca list-tags --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/123455678-1234-1234-1234-123456789012 --max-results 10
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/list-tags.html)」を参照してください。

### `revoke-certificate`
<a name="acm-pca_RevokeCertificate_cli_2_topic"></a>

次のコード例では、`revoke-certificate` を使用する方法を示しています。

**AWS CLI**  
**プライベート証明書を取り消す方法**  
次の `revoke-certificate` のコマンドは、ARN によって識別された CA からプライベート証明書を取り消します。  

```
aws acm-pca revoke-certificate --certificate-authority-arn arn:aws:acm-pca:us-west-2:1234567890:certificate-authority/12345678-1234-1234-1234-123456789012 --certificate-serial 67:07:44:76:83:a9:b7:f4:05:56:27:ff:d5:5c:eb:cc --revocation-reason "KEY_COMPROMISE"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokeCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/revoke-certificate.html)」を参照してください。

### `tag-certificate-authority`
<a name="acm-pca_TagCertificateAuthority_cli_2_topic"></a>

次のコード例では、`tag-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**プライベート認証機関にタグを追加する方法**  
次の `tag-certificate-authority` のコマンドは、プライベート CA に 1 つ以上のタグを追加します。  

```
aws acm-pca tag-certificate-authority --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012 --tags Key=Admin,Value=Alice
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/tag-certificate-authority.html)」を参照してください。

### `untag-certificate-authority`
<a name="acm-pca_UntagCertificateAuthority_cli_2_topic"></a>

次のコード例では、`untag-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**プライベート認証局から 1 つ以上のタグを削除する方法**  
次の `untag-certificate-authority` のコマンドは、ARN によって識別されるプライベート CA からタグを削除します。  

```
aws acm-pca untag-certificate-authority --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-123456789012 --tags Key=Purpose,Value=Website
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/untag-certificate-authority.html)」を参照してください。

### `update-certificate-authority`
<a name="acm-pca_UpdateCertificateAuthority_cli_2_topic"></a>

次のコード例では、`update-certificate-authority` を使用する方法を示しています。

**AWS CLI**  
**プライベート認証局の構成を更新する方法**  
次の `update-certificate-authority` のコマンドは、ARN によって識別されるプライベート CA のステータスと構成を更新します。  

```
aws acm-pca update-certificate-authority --certificate-authority-arn arn:aws:acm-pca:us-west-2:123456789012:certificate-authority/12345678-1234-1234-1234-1232456789012 --revocation-configuration file://C:\revoke_config.txt --status "DISABLED"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateCertificateAuthority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/acm-pca/update-certificate-authority.html)」を参照してください。

# AWS Proton を使用した の例 AWS CLI
<a name="cli_2_proton_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Proton。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `cancel-service-instance-deployment`
<a name="proton_CancelServiceInstanceDeployment_cli_2_topic"></a>

次のコード例は、`cancel-service-instance-deployment` を使用する方法を示しています。

**AWS CLI**  
**サービスインスタンスのデプロイをキャンセルするには**  
次の `cancel-service-instance-deployment` の例では、サービスインスタンスのデプロイをキャンセルします。  

```
aws proton cancel-service-instance-deployment \
    --service-instance-name "instance-one" \
    --service-name "simple-svc"
```
出力:  

```
{
    "serviceInstance": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/service-instance/instance-one",
        "createdAt": "2021-04-02T21:29:59.962000+00:00",
        "deploymentStatus": "CANCELLING",
        "environmentName": "simple-env",
        "lastDeploymentAttemptedAt": "2021-04-02T21:45:15.406000+00:00",
        "lastDeploymentSucceededAt": "2021-04-02T21:38:00.823000+00:00",
        "name": "instance-one",
        "serviceName": "simple-svc",
        "spec": "proton: ServiceSpec\npipeline:\n  my_sample_pipeline_optional_input: abc\n  my_sample_pipeline_required_input: '123'\ninstances:\n- name: my-instance\n  environment: MySimpleEnv\n  spec:\n    my_sample_service_instance_optional_input: def\n    my_sample_service_instance_required_input: '456'\n- name: my-other-instance\n  environment: MySimpleEnv\n  spec:\n    my_sample_service_instance_required_input: '789'\n",
        "templateMajorVersion": "1",
        "templateMinorVersion": "1",
        "templateName": "svc-simple"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*[」の「サービスインスタンスの更新](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-instance-update.html)」または* AWS 「 Proton ユーザーガイド*」の[「サービスインスタンスの更新](https://docs.aws.amazon.com/proton/latest/userguide/ug-svc-instance-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelServiceInstanceDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/cancel-service-instance-deployment.html)」を参照してください。

### `cancel-service-pipeline-deployment`
<a name="proton_CancelServicePipelineDeployment_cli_2_topic"></a>

次のコード例は、`cancel-service-pipeline-deployment` を使用する方法を示しています。

**AWS CLI**  
**サービスパイプラインのデプロイをキャンセルするには**  
次の `cancel-service-pipeline-deployment` の例では、サービスパイプラインのデプロイをキャンセルします。  

```
aws proton cancel-service-pipeline-deployment \
    --service-name "simple-svc"
```
出力:  

```
{
    "pipeline": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/pipeline",
        "createdAt": "2021-04-02T21:29:59.962000+00:00",
        "deploymentStatus": "CANCELLING",
        "lastDeploymentAttemptedAt": "2021-04-02T22:02:45.095000+00:00",
        "lastDeploymentSucceededAt": "2021-04-02T21:39:28.991000+00:00",
        "templateMajorVersion": "1",
        "templateMinorVersion": "1",
        "templateName": "svc-simple"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*[」の「サービスパイプラインの更新](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-pipeline-update.html)」または* AWS 「 Proton ユーザーガイド*」の[「サービスパイプラインの更新](https://docs.aws.amazon.com/proton/latest/userguide/ag-svc-pipeline-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelServicePipelineDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/cancel-service-pipeline-deployment.html)」を参照してください。

### `create-service`
<a name="proton_CreateService_cli_2_topic"></a>

次のコード例は、`create-service` を使用する方法を示しています。

**AWS CLI**  
**サービスを作成するには**  
次の `create-service` の例では、サービスパイプラインを使用してサービスを作成します。  

```
aws proton create-service \
    --name "MySimpleService" \
    --template-name "fargate-service" \
    --template-major-version "1" \
    --branch-name "mainline" \
    --repository-connection-arn "arn:aws:codestar-connections:region-id:account-id:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" \
    --repository-id "myorg/myapp" \
    --spec file://spec.yaml
```
`spec.yaml` の内容:  

```
proton: ServiceSpec

pipeline:
    my_sample_pipeline_required_input: "hello"
    my_sample_pipeline_optional_input: "bye"

instances:
    - name: "acme-network-dev"
        environment: "ENV_NAME"
        spec:
            my_sample_service_instance_required_input: "hi"
            my_sample_service_instance_optional_input: "ho"
```
出力:  

```
{
    "service": {
        "arn": "arn:aws:proton:region-id:123456789012:service/MySimpleService",
        "createdAt": "2020-11-18T19:50:27.460000+00:00",
        "lastModifiedAt": "2020-11-18T19:50:27.460000+00:00",
        "name": "MySimpleService",
        "repositoryConnectionArn": "arn:aws:codestar-connections:region-id:123456789012connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "repositoryId": "myorg/myapp",
        "status": "CREATE_IN_PROGRESS",
        "templateName": "fargate-service"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*[」の](https://docs.aws.amazon.com/proton/latest/adminguide/ag-create-svc.html)「サービスの作成」および* AWS 「 Proton ユーザーガイド*」の[「サービスの作成](https://docs.aws.amazon.com/proton/latest/userguide/ug-svc-create.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/create-service.html)」を参照してください。**

### `delete-service`
<a name="proton_DeleteService_cli_2_topic"></a>

次のコード例は、`delete-service` を使用する方法を示しています。

**AWS CLI**  
**サービスを削除する方法**  
次の `delete-service` の例では、サービスを削除します。  

```
aws proton delete-service \
    --name "simple-svc"
```
出力:  

```
{
    "service": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc",
        "branchName": "mainline",
        "createdAt": "2020-11-28T22:40:50.512000+00:00",
        "description": "Edit by updating description",
        "lastModifiedAt": "2020-11-29T00:30:39.248000+00:00",
        "name": "simple-svc",
        "repositoryConnectionArn": "arn:aws:codestar-connections:region-id:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "repositoryId": "myorg/myapp",
        "status": "DELETE_IN_PROGRESS",
        "templateName": "fargate-service"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*[」の「サービスの削除](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/delete-service.html)」を参照してください。

### `get-service-instance`
<a name="proton_GetServiceInstance_cli_2_topic"></a>

次のコード例は、`get-service-instance` を使用する方法を示しています。

**AWS CLI**  
**サービスインスタンスの詳細を取得するには**  
次の `get-service-instance` の例では、サービスインスタンスの詳細データを取得します。  

```
aws proton get-service-instance \
    --name "instance-one" \
    --service-name "simple-svc"
```
出力:  

```
{
    "serviceInstance": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/service-instance/instance-one",
        "createdAt": "2020-11-28T22:40:50.512000+00:00",
        "deploymentStatus": "SUCCEEDED",
        "environmentName": "simple-env",
        "lastDeploymentAttemptedAt": "2020-11-28T22:40:50.512000+00:00",
        "lastDeploymentSucceededAt": "2020-11-28T22:40:50.512000+00:00",
        "name": "instance-one",
        "serviceName": "simple-svc",
        "spec": "proton: ServiceSpec\npipeline:\n  my_sample_pipeline_optional_input: hello world\n  my_sample_pipeline_required_input: pipeline up\ninstances:\n- name: instance-one\n  environment: my-simple-env\n  spec:\n    my_sample_service_instance_optional_input: Ola\n    my_sample_service_instance_required_input: Ciao\n",
        "templateMajorVersion": "1",
        "templateMinorVersion": "0",
        "templateName": "svc-simple"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*」の[「サービスデータ](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-view.html)の表示」または[「 Proton ユーザーガイド」の「サービスデータ](https://docs.aws.amazon.com/proton/latest/userguide/ug-svc-view.html)の表示」を参照してください。 * AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/get-service-instance.html)」を参照してください。

### `get-service`
<a name="proton_GetService_cli_2_topic"></a>

次のコード例は、`get-service` を使用する方法を示しています。

**AWS CLI**  
**サービスの詳細を取得するには**  
次の `get-service` の例では、サービスの詳細データを取得します。  

```
aws proton get-service \
    --name "simple-svc"
```
出力:  

```
{
    "service": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc",
        "branchName": "mainline",
        "createdAt": "2020-11-28T22:40:50.512000+00:00",
        "lastModifiedAt": "2020-11-28T22:44:51.207000+00:00",
        "name": "simple-svc",
        "pipeline": {
            "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/pipeline/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "createdAt": "2020-11-28T22:40:50.512000+00:00",
            "deploymentStatus": "SUCCEEDED",
            "lastDeploymentAttemptedAt": "2020-11-28T22:40:50.512000+00:00",
            "lastDeploymentSucceededAt": "2020-11-28T22:40:50.512000+00:00",
            "spec": "proton: ServiceSpec\npipeline:\n  my_sample_pipeline_required_input: hello\n  my_sample_pipeline_optional_input: bye\ninstances:\n- name: instance-svc-simple\n  environment: my-simple-env\n  spec:\n    my_sample_service_instance_required_input: hi\n    my_sample_service_instance_optional_input: ho\n",
            "templateMajorVersion": "1",
            "templateMinorVersion": "1",
            "templateName": "svc-simple"
        },
        "repositoryConnectionArn": "arn:aws:codestar-connections:region-id:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "repositoryId": "myorg/myapp",
        "spec": "proton: ServiceSpec\npipeline:\n  my_sample_pipeline_required_input: hello\n  my_sample_pipeline_optional_input: bye\ninstances:\n- name: instance-svc-simple\n  environment: my-simple-env\n  spec:\n    my_sample_service_instance_required_input: hi\n    my_sample_service_instance_optional_input: ho\n",
        "status": "ACTIVE",
        "templateName": "svc-simple"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*」の[「サービスデータ](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-view.html)の表示」または[「 Proton ユーザーガイド」の「サービスデータ](https://docs.aws.amazon.com/proton/latest/userguide/ug-svc-view.html)の表示」を参照してください。 * AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/get-service.html)」を参照してください。

### `list-service-instances`
<a name="proton_ListServiceInstances_cli_2_topic"></a>

次のコード例は、`list-service-instances` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのサービスインスタンスを一覧表示するには**  
次の `list-service-instances` の例では、サービスインスタンスを一覧表示します。  

```
aws proton list-service-instances
```
出力:  

```
{
    "serviceInstances": [
        {
            "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/service-instance/instance-one",
            "createdAt": "2020-11-28T22:40:50.512000+00:00",
            "deploymentStatus": "SUCCEEDED",
            "environmentArn": "arn:aws:proton:region-id:123456789012:environment/simple-env",
            "lastDeploymentAttemptedAt": "2020-11-28T22:40:50.512000+00:00",
            "lastDeploymentSucceededAt": "2020-11-28T22:40:50.512000+00:00",
            "name": "instance-one",
            "serviceName": "simple-svc",
            "templateMajorVersion": "1",
            "templateMinorVersion": "0",
            "templateName": "fargate-service"
        }
    ]
}
```
詳細については、* AWS 「 Proton 管理者ガイド*」の[「サービスインスタンスデータ](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-instance-view.html)の表示」または[「 Proton ユーザーガイド」の「サービスインスタンスデータ](https://docs.aws.amazon.com/proton/latest/userguide/ag-svc-instance-view.html)の表示」を参照してください。 * AWS *  
**例 2: 指定されたサービスインスタンスを一覧表示するには**  
次の `get-service-instance` の例では、サービスインスタンスを取得します。  

```
aws proton get-service-instance \
    --name "instance-one" \
    --service-name "simple-svc"
```
出力:  

```
{
    "serviceInstance": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/service-instance/instance-one",
        "createdAt": "2020-11-28T22:40:50.512000+00:00",
        "deploymentStatus": "SUCCEEDED",
        "environmentName": "simple-env",
        "lastDeploymentAttemptedAt": "2020-11-28T22:40:50.512000+00:00",
        "lastDeploymentSucceededAt": "2020-11-28T22:40:50.512000+00:00",
        "name": "instance-one",
        "serviceName": "simple-svc",
        "spec": "proton: ServiceSpec\npipeline:\n  my_sample_pipeline_optional_input: hello world\n  my_sample_pipeline_required_input: pipeline up\ninstances:\n- name: instance-one\n  environment: my-simple-env\n  spec:\n    my_sample_service_instance_optional_input: Ola\n    my_sample_service_instance_required_input: Ciao\n",
        "templateMajorVersion": "1",
        "templateMinorVersion": "0",
        "templateName": "svc-simple"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*」の[「サービスインスタンスデータ](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-instance-view.html)の表示」または[「 Proton ユーザーガイド」の「サービスインスタンスデータ](https://docs.aws.amazon.com/proton/latest/userguide/ag-svc-instance-view.html)の表示」を参照してください。 * AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/list-service-instances.html)」を参照してください。

### `update-service-instance`
<a name="proton_UpdateServiceInstance_cli_2_topic"></a>

次のコード例は、`update-service-instance` を使用する方法を示しています。

**AWS CLI**  
**サービスインスタンスを新しいマイナーバージョンに更新するには**  
次の `update-service-instance` の例では、サービスインスタンスをサービステンプレートの新しいマイナーバージョンに更新し、「my-other-instance」という名前の新しいインスタンスを新しい必須の入力に追加します。  

```
aws proton update-service-instance \
    --service-name "simple-svc" \
    --spec "file://service-spec.yaml " \
    --template-major-version "1" \
    --template-minor-version "1" \
    --deployment-type "MINOR_VERSION" \
    --name "instance-one"
```
`service-spec.yaml` の内容:  

```
proton: ServiceSpec
pipeline:
    my_sample_pipeline_optional_input: "abc"
    my_sample_pipeline_required_input: "123"
instances:
    - name: "instance-one"
        environment: "simple-env"
        spec:
            my_sample_service_instance_optional_input: "def"
            my_sample_service_instance_required_input: "456"
    - name: "my-other-instance"
        environment: "simple-env"
        spec:
            my_sample_service_instance_required_input: "789"
```
出力:  

```
{
    "serviceInstance": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/service-instance/instance-one",
        "createdAt": "2021-04-02T21:29:59.962000+00:00",
        "deploymentStatus": "IN_PROGRESS",
        "environmentName": "arn:aws:proton:region-id:123456789012:environment/simple-env",
        "lastDeploymentAttemptedAt": "2021-04-02T21:38:00.823000+00:00",
        "lastDeploymentSucceededAt": "2021-04-02T21:29:59.962000+00:00",
        "name": "instance-one",
        "serviceName": "simple-svc",
        "templateMajorVersion": "1",
        "templateMinorVersion": "0",
        "templateName": "svc-simple"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*[」の「サービスインスタンスの更新](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-instance-update.html)」または* AWS 「 Proton ユーザーガイド*」の[「サービスインスタンスの更新](https://docs.aws.amazon.com/proton/latest/userguide/ag-svc-instance-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServiceInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/update-service-instance.html)」を参照してください。

### `update-service-pipeline`
<a name="proton_UpdateServicePipeline_cli_2_topic"></a>

次のコード例は、`update-service-pipeline` を使用する方法を示しています。

**AWS CLI**  
**サービスパイプラインを更新するには**  
次の `update-service-pipeline` の例では、サービスパイプラインをサービステンプレートの新しいマイナーバージョンに更新します。  

```
aws proton update-service-pipeline \
    --service-name "simple-svc" \
    --spec "file://service-spec.yaml" \
    --template-major-version "1" \
    --template-minor-version "1" \
    --deployment-type "MINOR_VERSION"
```
出力:  

```
{
    "pipeline": {
        "arn": "arn:aws:proton:region-id:123456789012:service/simple-svc/pipeline/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "createdAt": "2021-04-02T21:29:59.962000+00:00",
        "deploymentStatus": "IN_PROGRESS",
        "lastDeploymentAttemptedAt": "2021-04-02T21:39:28.991000+00:00",
        "lastDeploymentSucceededAt": "2021-04-02T21:29:59.962000+00:00",
        "spec": "proton: ServiceSpec\n\npipeline:\n  my_sample_pipeline_optional_input: \"abc\"\n  my_sample_pipeline_required_input: \"123\"\n\ninstances:\n  - name: \"my-instance\"\n    environment: \"MySimpleEnv\"\n    spec:\n      my_sample_service_instance_optional_input: \"def\"\n      my_sample_service_instance_required_input: \"456\"\n  - name: \"my-other-instance\"\n    environment: \"MySimpleEnv\"\n    spec:\n      my_sample_service_instance_required_input: \"789\"\n",
        "templateMajorVersion": "1",
        "templateMinorVersion": "0",
        "templateName": "svc-simple"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*[」の「サービスパイプラインの更新](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-pipeline-update.html)」または* AWS 「 Proton ユーザーガイド*」の[「サービスパイプラインの更新](https://docs.aws.amazon.com/proton/latest/userguide/ag-svc-pipeline-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServicePipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/update-service-pipeline.html)」を参照してください。

### `update-service`
<a name="proton_UpdateService_cli_2_topic"></a>

次のコード例は、`update-service` を使用する方法を示しています。

**AWS CLI**  
**サービスを更新するには**  
次の `update-service` の例では、サービスの説明を編集します。  

```
aws proton update-service \
    --name "MySimpleService" \
    --description "Edit by updating description"
```
出力:  

```
{
    "service": {
        "arn": "arn:aws:proton:region-id:123456789012:service/MySimpleService",
        "branchName": "mainline",
        "createdAt": "2021-03-12T22:39:42.318000+00:00",
        "description": "Edit by updating description",
        "lastModifiedAt": "2021-03-12T22:44:21.975000+00:00",
        "name": "MySimpleService",
        "repositoryConnectionArn": "arn:aws:codestar-connections:region-id:123456789012:connection/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "repositoryId": "myorg/myapp",
        "status": "ACTIVE",
        "templateName": "fargate-service"
    }
}
```
詳細については、* AWS 「 Proton 管理者ガイド*[」の「サービスの編集](https://docs.aws.amazon.com/proton/latest/adminguide/ag-svc-update.html)」または* AWS 「 Proton ユーザーガイド*」の[「サービスの編集](https://docs.aws.amazon.com/proton/latest/userguide/ug-svc-update.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/proton/update-service.html)」を参照してください。**

# を使用した Amazon RDS の例 AWS CLI
<a name="cli_2_rds_code_examples"></a>

次のコード例は、Amazon RDS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-option-to-option-group`
<a name="rds_AddOptionToOptionGroup_cli_2_topic"></a>

次のコード例は、`add-option-to-option-group` を使用する方法を示しています。

**AWS CLI**  
**オプショングループにオプションを追加するには**  
次の `add-option-to-option-group` の例では、オプションを指定したオプショングループに追加します。  

```
aws rds add-option-to-option-group \
    --option-group-name myoptiongroup \
    --options OptionName=OEM,Port=5500,DBSecurityGroupMemberships=default \
    --apply-immediately
```
出力:  

```
{
    "OptionGroup": {
        "OptionGroupName": "myoptiongroup",
        "OptionGroupDescription": "Test Option Group",
        "EngineName": "oracle-ee",
        "MajorEngineVersion": "12.1",
        "Options": [
            {
                "OptionName": "Timezone",
                "OptionDescription": "Change time zone",
                "Persistent": true,
                "Permanent": false,
                "OptionSettings": [
                    {
                        "Name": "TIME_ZONE",
                        "Value": "Australia/Sydney",
                        "DefaultValue": "UTC",
                        "Description": "Specifies the timezone the user wants to change the system time to",
                        "ApplyType": "DYNAMIC",
                        "DataType": "STRING",
                        "AllowedValues": "Africa/Cairo,Africa/Casablanca,Africa/Harare,Africa/Lagos,Africa/Luanda,Africa/Monrovia,Africa/Nairobi,Africa/Tripoli,Africa/Windhoek,America/Araguaina,America/Argentina/Buenos_Aires,America/Asuncion,America/Bogota,America/Caracas,America/Chicago,America/Chihuahua,America/Cuiaba,America/Denver,America/Detroit,America/Fortaleza,America/Godthab,America/Guatemala,America/Halifax,America/Lima,America/Los_Angeles,America/Manaus,America/Matamoros,America/Mexico_City,America/Monterrey,America/Montevideo,America/New_York,America/Phoenix,America/Santiago,America/Sao_Paulo,America/Tijuana,America/Toronto,Asia/Amman,Asia/Ashgabat,Asia/Baghdad,Asia/Baku,Asia/Bangkok,Asia/Beirut,Asia/Calcutta,Asia/Damascus,Asia/Dhaka,Asia/Hong_Kong,Asia/Irkutsk,Asia/Jakarta,Asia/Jerusalem,Asia/Kabul,Asia/Karachi,Asia/Kathmandu,Asia/Kolkata,Asia/Krasnoyarsk,Asia/Magadan,Asia/Manila,Asia/Muscat,Asia/Novosibirsk,Asia/Rangoon,Asia/Riyadh,Asia/Seoul,Asia/Shanghai,Asia/Singapore,Asia/Taipei,Asia/Tehran,Asia/Tokyo,Asia/Ulaanbaatar,Asia/Vladivostok,Asia/Yakutsk,Asia/Yerevan,Atlantic/Azores,Atlantic/Cape_Verde,Australia/Adelaide,Australia/Brisbane,Australia/Darwin,Australia/Eucla,Australia/Hobart,Australia/Lord_Howe,Australia/Perth,Australia/Sydney,Brazil/DeNoronha,Brazil/East,Canada/Newfoundland,Canada/Saskatchewan,Etc/GMT-3,Europe/Amsterdam,Europe/Athens,Europe/Berlin,Europe/Dublin,Europe/Helsinki,Europe/Kaliningrad,Europe/London,Europe/Madrid,Europe/Moscow,Europe/Paris,Europe/Prague,Europe/Rome,Europe/Sarajevo,Pacific/Apia,Pacific/Auckland,Pacific/Chatham,Pacific/Fiji,Pacific/Guam,Pacific/Honolulu,Pacific/Kiritimati,Pacific/Marquesas,Pacific/Samoa,Pacific/Tongatapu,Pacific/Wake,US/Alaska,US/Central,US/East-Indiana,US/Eastern,US/Pacific,UTC",
                        "IsModifiable": true,
                        "IsCollection": false
                    }
                ],
                "DBSecurityGroupMemberships": [],
                "VpcSecurityGroupMemberships": []
            },
            {
                "OptionName": "OEM",
                "OptionDescription": "Oracle 12c EM Express",
                "Persistent": false,
                "Permanent": false,
                "Port": 5500,
                "OptionSettings": [],
                "DBSecurityGroupMemberships": [
                    {
                        "DBSecurityGroupName": "default",
                        "Status": "authorized"
                    }
                ],
                "VpcSecurityGroupMemberships": []
            }
        ],
        "AllowsVpcAndNonVpcInstanceMemberships": false,
        "OptionGroupArn": "arn:aws:rds:us-east-1:123456789012:og:myoptiongroup"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[オプショングループにオプションを追加する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithOptionGroups.html#USER_WorkingWithOptionGroups.AddOption)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddOptionToOptionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/add-option-to-option-group.html)」を参照してください。

### `add-role-to-db-cluster`
<a name="rds_AddRoleToDbCluster_cli_2_topic"></a>

次の例は、`add-role-to-db-cluster` を使用する方法を説明しています。

**AWS CLI**  
** AWS Identity and Access Management (IAM) ロールを DB クラスターに関連付けるには**  
次の `add-role-to-db-cluster` の例では、DB クラスターにロールを関連付けます。  

```
aws rds add-role-to-db-cluster \
    --db-cluster-identifier mydbcluster \
    --role-arn arn:aws:iam::123456789012:role/RDSLoadFromS3
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Aurora ユーザーガイド*」の「[IAM ロールと Amazon Aurora MySQL DB クラスターの関連付け](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.Authorizing.IAM.AddRoleToDBCluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddRoleToDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/add-role-to-db-cluster.html)」を参照してください。

### `add-role-to-db-instance`
<a name="rds_AddRoleToDbInstance_cli_2_topic"></a>

次の例は、`add-role-to-db-instance` を使用する方法を説明しています。

**AWS CLI**  
** AWS Identity and Access Management (IAM) ロールを DB インスタンスに関連付けるには**  
次の `add-role-to-db-instance` の例では、`test-instance` という名前の Oracle DB インスタンスにこのロールを追加します。  

```
aws rds add-role-to-db-instance \
    --db-instance-identifier test-instance \
    --feature-name S3_INTEGRATION \
    --role-arn arn:aws:iam::111122223333:role/rds-s3-integration-role
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS Oracle と Amazon S3 を統合する前提条件](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/oracle-s3-integration.html#oracle-s3-integration.preparing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddRoleToDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/add-role-to-db-instance.html)」を参照してください。

### `add-source-identifier-to-subscription`
<a name="rds_AddSourceIdentifierToSubscription_cli_2_topic"></a>

次のコード例は、`add-source-identifier-to-subscription` を使用する方法を示しています。

**AWS CLI**  
**ソース識別子をサブスクリプションに追加するには**  
次の `add-source-identifier` の例では、別のソース識別子を既存のサブスクリプションに追加します。  

```
aws rds add-source-identifier-to-subscription \
    --subscription-name my-instance-events \
    --source-identifier test-instance-repl
```
出力:  

```
{
    "EventSubscription": {
        "SubscriptionCreationTime": "Tue Jul 31 23:22:01 UTC 2018",
        "CustSubscriptionId": "my-instance-events",
        "EventSubscriptionArn": "arn:aws:rds:us-east-1:123456789012:es:my-instance-events",
        "Enabled": false,
        "Status": "modifying",
        "EventCategoriesList": [
            "backup",
            "recovery"
        ],
        "CustomerAwsId": "123456789012",
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:interesting-events",
        "SourceType": "db-instance",
        "SourceIdsList": [
            "test-instance",
            "test-instance-repl"
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddSourceIdentifierToSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/add-source-identifier-to-subscription.html)」を参照してください。

### `add-tags-to-resource`
<a name="rds_AddTagsToResource_cli_2_topic"></a>

次のコード例は、`add-tags-to-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを追加するには**  
次の `add-tags-to-resource` の例では、RDS データベースにタグを追加します。  

```
aws rds add-tags-to-resource \
    --resource-name arn:aws:rds:us-east-1:123456789012:db:database-mysql \
    --tags "[{\"Key\": \"Name\",\"Value\": \"MyDatabase\"},{\"Key\": \"Environment\",\"Value\": \"test\"}]"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS リソースのタグ付け](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AddTagsToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/add-tags-to-resource.html)」を参照してください。

### `apply-pending-maintenance-action`
<a name="rds_ApplyPendingMaintenanceAction_cli_2_topic"></a>

次のコード例は、`apply-pending-maintenance-action` を使用する方法を示しています。

**AWS CLI**  
**保留中のメンテナンスアクションを適用するには**  
次の `apply-pending-maintenance-action` の例では、DB クラスターの保留中のメンテナンスアクションを適用します。  

```
aws rds apply-pending-maintenance-action \
    --resource-identifier arn:aws:rds:us-east-1:123456789012:cluster:my-db-cluster \
    --apply-action system-update \
    --opt-in-type immediate
```
出力:  

```
{
    "ResourcePendingMaintenanceActions": {
        "ResourceIdentifier": "arn:aws:rds:us-east-1:123456789012:cluster:my-db-cluster",
        "PendingMaintenanceActionDetails": [
            {
                "Action": "system-update",
                "OptInStatus": "immediate",
                "CurrentApplyDate": "2021-01-23T01:07:36.100Z",
                "Description": "Upgrade to Aurora PostgreSQL 3.3.2"
            }
        ]
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB インスタンスのメンテナンス](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html)」および「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB インスタンスのメンテナンス](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_UpgradeDBInstance.Maintenance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ApplyPendingMaintenanceAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/apply-pending-maintenance-action.html)」を参照してください。

### `authorize-db-security-group-ingress`
<a name="rds_AuthorizeDbSecurityGroupIngress_cli_2_topic"></a>

次の例は、`authorize-db-security-group-ingress` を使用する方法を説明しています。

**AWS CLI**  
** AWS Identity and Access Management (IAM) ロールを DB インスタンスに関連付けるには**  
次の `authorize-db-security-group-ingress` の例では、CIDR IP 範囲 192.0.2.0/24 の進入ルールを使用してデフォルトのセキュリティグループを設定します。  

```
aws rds authorize-db-security-group-ingress \
    --db-security-group-name default \
    --cidrip 192.0.2.0/24
```
出力:  

```
{
    "DBSecurityGroup": {
        "OwnerId": "123456789012",
        "DBSecurityGroupName": "default",
        "DBSecurityGroupDescription": "default",
        "EC2SecurityGroups": [],
        "IPRanges": [
            {
                "Status": "authorizing",
                "CIDRIP": "192.0.2.0/24"
            }
        ],
        "DBSecurityGroupArn": "arn:aws:rds:us-east-1:111122223333:secgrp:default"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[IP 範囲からのネットワークアクセスを DB セキュリティグループに許可する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithSecurityGroups.html#USER_WorkingWithSecurityGroups.Authorizing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AuthorizeDbSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/authorize-db-security-group-ingress.html)」を参照してください。

### `backtrack-db-cluster`
<a name="rds_BacktrackDbCluster_cli_2_topic"></a>

次のコード例は、`backtrack-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**Aurora DB クラスターをバックトラックするには**  
次の `backtrack-db-cluster` の例では、指定された DB クラスター sample-cluster を 2018 年 3 月 19 日午前 10 時までバックトラックします。  

```
aws rds backtrack-db-cluster --db-cluster-identifier sample-cluster --backtrack-to 2018-03-19T10:00:00+00:00
```
このコマンドは、RDS リソースの変更を承認する JSON ブロックを出力します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BacktrackDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/backtrack-db-cluster.html)」を参照してください。

### `cancel-export-task`
<a name="rds_CancelExportTask_cli_2_topic"></a>

次のコード例は、`cancel-export-task` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 に対するスナップショットのエクスポートをキャンセルするには**  
次の `cancel-export-task` の例では、スナップショットを Amazon S3 にエクスポートする進行中のエクスポートタスクをキャンセルします。  

```
aws rds cancel-export-task \
    --export-task-identifier my-s3-export-1
```
出力:  

```
{
    "ExportTaskIdentifier": "my-s3-export-1",
    "SourceArn": "arn:aws:rds:us-east-1:123456789012:snapshot:publisher-final-snapshot",
    "SnapshotTime": "2019-03-24T20:01:09.815Z",
    "S3Bucket": "amzn-s3-demo-bucket",
    "S3Prefix": "",
    "IamRoleArn": "arn:aws:iam::123456789012:role/service-role/export-snap-S3-role",
    "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/abcd0000-7bfd-4594-af38-aabbccddeeff",
    "Status": "CANCELING",
    "PercentProgress": 0,
    "TotalExtractedDataInGB": 0
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[スナップショットエクスポートタスクのキャンセル](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ExportSnapshot.html#USER_ExportSnapshot.Canceling)」または「*Amazon Aurora ユーザーガイド*」の「[スナップショットエクスポートタスクのキャンセル](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_ExportSnapshot.html#USER_ExportSnapshot.Canceling)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelExportTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/cancel-export-task.html)」を参照してください。

### `copy-db-cluster-parameter-group`
<a name="rds_CopyDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`copy-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターパラメータグループをコピーするには**  
次の `copy-db-cluster-parameter-group` の例では、DB クラスターパラメータグループのコピーを作成します。  

```
aws rds copy-db-cluster-parameter-group \
    --source-db-cluster-parameter-group-identifier mydbclusterpg \
    --target-db-cluster-parameter-group-identifier mydbclusterpgcopy \
    --target-db-cluster-parameter-group-description "Copy of mydbclusterpg parameter group"
```
出力:  

```
{
    "DBClusterParameterGroup": {
        "DBClusterParameterGroupName": "mydbclusterpgcopy",
        "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:mydbclusterpgcopy",
        "DBParameterGroupFamily": "aurora-mysql5.7",
        "Description": "Copy of mydbclusterpg parameter group"
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスターパラメータグループのコピー](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html#USER_WorkingWithParamGroups.CopyingCluster)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/copy-db-cluster-parameter-group.html)」を参照してください。

### `copy-db-cluster-snapshot`
<a name="rds_CopyDbClusterSnapshot_cli_2_topic"></a>

次のコード例は、`copy-db-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB クラスタースナップショットをコピーするには**  
次の `copy-db-cluster-snapshot` の例では、タグを含む DB クラスタースナップショットのコピーを作成します。  

```
aws rds copy-db-cluster-snapshot \
    --source-db-cluster-snapshot-identifier arn:aws:rds:us-east-1:123456789012:cluster-snapshot:rds:myaurora-2019-06-04-09-16
    --target-db-cluster-snapshot-identifier myclustersnapshotcopy \
    --copy-tags
```
出力:  

```
{
    "DBClusterSnapshot": {
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1b",
            "us-east-1e"
        ],
        "DBClusterSnapshotIdentifier": "myclustersnapshotcopy",
        "DBClusterIdentifier": "myaurora",
        "SnapshotCreateTime": "2019-06-04T09:16:42.649Z",
        "Engine": "aurora-mysql",
        "AllocatedStorage": 0,
        "Status": "available",
        "Port": 0,
        "VpcId": "vpc-6594f31c",
        "ClusterCreateTime": "2019-04-15T14:18:42.785Z",
        "MasterUsername": "myadmin",
        "EngineVersion": "5.7.mysql_aurora.2.04.2",
        "LicenseModel": "aurora-mysql",
        "SnapshotType": "manual",
        "PercentProgress": 100,
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE",
        "DBClusterSnapshotArn": "arn:aws:rds:us-east-1:123456789012:cluster-snapshot:myclustersnapshotcopy",
        "IAMDatabaseAuthenticationEnabled": false
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*の「[スナップショットのコピー](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_CopySnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyDbClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/copy-db-cluster-snapshot.html)」を参照してください。

### `copy-db-parameter-group`
<a name="rds_CopyDbParameterGroup_cli_2_topic"></a>

次のコード例は、`copy-db-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターパラメータグループをコピーするには**  
次の `copy-db-parameter-group` の例では、DB パラメータグループのコピーを作成します。  

```
aws rds copy-db-parameter-group \
    --source-db-parameter-group-identifier mydbpg \
    --target-db-parameter-group-identifier mydbpgcopy \
    --target-db-parameter-group-description "Copy of mydbpg parameter group"
```
出力:  

```
{
    "DBParameterGroup": {
        "DBParameterGroupName": "mydbpgcopy",
        "DBParameterGroupArn": "arn:aws:rds:us-east-1:814387698303:pg:mydbpgcopy",
        "DBParameterGroupFamily": "mysql5.7",
        "Description": "Copy of mydbpg parameter group"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB パラメータグループをコピーする](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html#USER_WorkingWithParamGroups.Copying)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyDbParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/copy-db-parameter-group.html)」を参照してください。

### `copy-db-snapshot`
<a name="rds_CopyDbSnapshot_cli_2_topic"></a>

次のコード例は、`copy-db-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB スナップショットをコピーするには**  
次の `copy-db-snapshot` の例では、DB スナップショットのコピーを作成します。  

```
aws rds copy-db-snapshot \
    --source-db-snapshot-identifier rds:database-mysql-2019-06-06-08-38
    --target-db-snapshot-identifier mydbsnapshotcopy
```
出力:  

```
{
    "DBSnapshot": {
        "VpcId": "vpc-6594f31c",
        "Status": "creating",
        "Encrypted": true,
        "SourceDBSnapshotIdentifier": "arn:aws:rds:us-east-1:123456789012:snapshot:rds:database-mysql-2019-06-06-08-38",
        "MasterUsername": "admin",
        "Iops": 1000,
        "Port": 3306,
        "LicenseModel": "general-public-license",
        "DBSnapshotArn": "arn:aws:rds:us-east-1:123456789012:snapshot:mydbsnapshotcopy",
        "EngineVersion": "5.6.40",
        "OptionGroupName": "default:mysql-5-6",
        "ProcessorFeatures": [],
        "Engine": "mysql",
        "StorageType": "io1",
        "DbiResourceId": "db-ZI7UJ5BLKMBYFGX7FDENCKADC4",
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE",
        "SnapshotType": "manual",
        "IAMDatabaseAuthenticationEnabled": false,
        "SourceRegion": "us-east-1",
        "DBInstanceIdentifier": "database-mysql",
        "InstanceCreateTime": "2019-04-30T15:45:53.663Z",
        "AvailabilityZone": "us-east-1f",
        "PercentProgress": 0,
        "AllocatedStorage": 100,
        "DBSnapshotIdentifier": "mydbsnapshotcopy"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*の「[スナップショットのコピー](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyDbSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/copy-db-snapshot.html)」を参照してください。

### `copy-option-group`
<a name="rds_CopyOptionGroup_cli_2_topic"></a>

次のコード例は、`copy-option-group` を使用する方法を示しています。

**AWS CLI**  
**オプショングループをコピーするには**  
次の `copy-option-group` の例では、オプショングループのコピーを作成します。  

```
aws rds copy-option-group \
    --source-option-group-identifier myoptiongroup \
    --target-option-group-identifier new-option-group \
    --target-option-group-description "My option group copy"
```
出力:  

```
{
    "OptionGroup": {
        "Options": [],
        "OptionGroupName": "new-option-group",
        "MajorEngineVersion": "11.2",
        "OptionGroupDescription": "My option group copy",
        "AllowsVpcAndNonVpcInstanceMemberships": true,
        "EngineName": "oracle-ee",
        "OptionGroupArn": "arn:aws:rds:us-east-1:123456789012:og:new-option-group"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[オプショングループのコピーの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithOptionGroups.html#USER_WorkingWithOptionGroups.Copy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyOptionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/copy-option-group.html)」を参照してください。

### `create-blue-green-deployment`
<a name="rds_CreateBlueGreenDeployment_cli_2_topic"></a>

次のコード例は、`create-blue-green-deployment` を使用する方法を示しています。

**AWS CLI**  
**例 1: RDS for MySQL DB インスタンス用にブルー/グリーンデプロイを作成するには**  
次の `create-blue-green-deployment` の例では、MySQL DB インスタンスのブルー/グリーンデプロイを作成します。  

```
aws rds create-blue-green-deployment \
    --blue-green-deployment-name bgd-cli-test-instance \
    --source arn:aws:rds:us-east-1:123456789012:db:my-db-instance \
    --target-engine-version 8.0 \
    --target-db-parameter-group-name mysql-80-group
```
出力:  

```
{
    "BlueGreenDeployment": {
        "BlueGreenDeploymentIdentifier": "bgd-v53303651eexfake",
        "BlueGreenDeploymentName": "bgd-cli-test-instance",
        "Source": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
        "SwitchoverDetails": [
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3"
            }
        ],
        "Tasks": [
            {
                "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                "Status": "PENDING"
            },
            {
                "Name": "DB_ENGINE_VERSION_UPGRADE",
                "Status": "PENDING"
            },
            {
                "Name": "CONFIGURE_BACKUPS",
                "Status": "PENDING"
            },
            {
                "Name": "CREATING_TOPOLOGY_OF_SOURCE",
                "Status": "PENDING"
            }
        ],
        "Status": "PROVISIONING",
        "CreateTime": "2022-02-25T21:18:51.183000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[ブルー/グリーンデプロイの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-creating.html)」を参照してください。  
**例 2: Aurora MySQL DB クラスター用にブルー/グリーンデプロイを作成するには**  
次の `create-blue-green-deployment` の例では、Aurora MySQL DB クラスターのブルー/グリーンデプロイを作成します。  

```
aws rds create-blue-green-deployment \
    --blue-green-deployment-name my-blue-green-deployment \
    --source arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster \
    --target-engine-version 8.0 \
    --target-db-cluster-parameter-group-name ams-80-binlog-enabled \
    --target-db-parameter-group-name mysql-80-cluster-group
```
出力:  

```
{
      "BlueGreenDeployment": {
        "BlueGreenDeploymentIdentifier": "bgd-wi89nwzglccsfake",
        "BlueGreenDeploymentName": "my-blue-green-deployment",
        "Source": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
        "SwitchoverDetails": [
          {
            "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
            "Status": "PROVISIONING"
          },
          {
            "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1",
            "Status": "PROVISIONING"
          },
          {
            "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2",
            "Status": "PROVISIONING"
          },
          {
            "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3",
            "Status": "PROVISIONING"
          },
          {
            "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint",
            "Status": "PROVISIONING"
          },
          {
            "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint",
            "Status": "PROVISIONING"
          }
        ],
        "Tasks": [
          {
            "Name": "CREATING_READ_REPLICA_OF_SOURCE",
            "Status": "PENDING"
          },
          {
            "Name": "DB_ENGINE_VERSION_UPGRADE",
            "Status": "PENDING"
          },
          {
            "Name": "CREATE_DB_INSTANCES_FOR_CLUSTER",
            "Status": "PENDING"
          },
          {
            "Name": "CREATE_CUSTOM_ENDPOINTS",
            "Status": "PENDING"
          }
        ],
        "Status": "PROVISIONING",
        "CreateTime": "2022-02-25T21:12:00.288000+00:00"
      }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[ブルー/グリーンデプロイの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments-creating.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBlueGreenDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-blue-green-deployment.html)」を参照してください。

### `create-db-cluster-endpoint`
<a name="rds_CreateDbClusterEndpoint_cli_2_topic"></a>

次のコード例は、`create-db-cluster-endpoint` を使用する方法を示しています。

**AWS CLI**  
**カスタム DB クラスターエンドポイントを作成するには**  
次の `create-db-cluster-endpoint` の例では、カスタム DB クラスターエンドポイントを作成し、指定された Aurora DB クラスターに関連付けます。  

```
aws rds create-db-cluster-endpoint \
    --db-cluster-endpoint-identifier mycustomendpoint \
    --endpoint-type reader \
    --db-cluster-identifier mydbcluster \
    --static-members dbinstance1 dbinstance2
```
出力:  

```
{
    "DBClusterEndpointIdentifier": "mycustomendpoint",
    "DBClusterIdentifier": "mydbcluster",
    "DBClusterEndpointResourceIdentifier": "cluster-endpoint-ANPAJ4AE5446DAEXAMPLE",
    "Endpoint": "mycustomendpoint.cluster-custom-cnpexample.us-east-1.rds.amazonaws.com",
    "Status": "creating",
    "EndpointType": "CUSTOM",
    "CustomEndpointType": "READER",
    "StaticMembers": [
        "dbinstance1",
        "dbinstance2"
    ],
    "ExcludedMembers": [],
    "DBClusterEndpointArn": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:mycustomendpoint"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora 接続管理](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbClusterEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-cluster-endpoint.html)」を参照してください。

### `create-db-cluster-parameter-group`
<a name="rds_CreateDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`create-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターパラメータグループを作成するには**  
次の `create-db-cluster-parameter-group` の例は、DB クラスターパラメータグループを作成します。  

```
aws rds create-db-cluster-parameter-group \
    --db-cluster-parameter-group-name mydbclusterparametergroup \
    --db-parameter-group-family aurora5.6 \
    --description "My new cluster parameter group"
```
出力:  

```
{
    "DBClusterParameterGroup": {
        "DBClusterParameterGroupName": "mydbclusterparametergroup",
        "DBParameterGroupFamily": "aurora5.6",
        "Description": "My new cluster parameter group",
        "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:mydbclusterparametergroup"
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスターパラメータグループの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html#USER_WorkingWithParamGroups.CreatingCluster)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-cluster-parameter-group.html)」を参照してください。

### `create-db-cluster-snapshot`
<a name="rds_CreateDbClusterSnapshot_cli_2_topic"></a>

次のコード例は、`create-db-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB クラスタースナップショットを作成するには**  
次の `create-db-cluster-snapshot` の例は、DB クラスタースナップショットを作成します。  

```
aws rds create-db-cluster-snapshot \
    --db-cluster-identifier mydbcluster \
    --db-cluster-snapshot-identifier mydbclustersnapshot
```
出力:  

```
{
    "DBClusterSnapshot": {
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1b",
            "us-east-1e"
        ],
        "DBClusterSnapshotIdentifier": "mydbclustersnapshot",
        "DBClusterIdentifier": "mydbcluster",
        "SnapshotCreateTime": "2019-06-18T21:21:00.469Z",
        "Engine": "aurora-mysql",
        "AllocatedStorage": 1,
        "Status": "creating",
        "Port": 0,
        "VpcId": "vpc-6594f31c",
        "ClusterCreateTime": "2019-04-15T14:18:42.785Z",
        "MasterUsername": "myadmin",
        "EngineVersion": "5.7.mysql_aurora.2.04.2",
        "LicenseModel": "aurora-mysql",
        "SnapshotType": "manual",
        "PercentProgress": 0,
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE",
        "DBClusterSnapshotArn": "arn:aws:rds:us-east-1:123456789012:cluster-snapshot:mydbclustersnapshot",
        "IAMDatabaseAuthenticationEnabled": false
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスタースナップショットの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_CreateSnapshotCluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-cluster-snapshot.html)」を参照してください。

### `create-db-cluster`
<a name="rds_CreateDbCluster_cli_2_topic"></a>

次のコード例は、`create-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**例 1: MySQL 5.7 互換 DB クラスターを作成するには**  
次の `create-db-cluster` の例は、デフォルトのエンジンバージョンを使用して MySQL 5.7 互換 DB クラスターを作成します。サンプルパスワード `secret99` を安全なパスワードに置き換えます。コンソールを使用して DB クラスターを作成する場合、Amazon RDS は DB クラスターのライター DB インスタンスを自動作成します。ただし、CLI を使用して DB AWS クラスターを作成する場合は、`create-db-instance` AWS CLI コマンドを使用して DB クラスターのライター DB インスタンスを明示的に作成する必要があります。  

```
aws rds create-db-cluster \
    --db-cluster-identifier sample-cluster \
    --engine aurora-mysql \
    --engine-version 5.7 \
    --master-username admin \
    --master-user-password secret99 \
    --db-subnet-group-name default \
    --vpc-security-group-ids sg-0b9130572daf3dc16
```
出力:  

```
{
    "DBCluster": {
        "DBSubnetGroup": "default",
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-0b9130572daf3dc16",
                "Status": "active"
            }
        ],
        "AllocatedStorage": 1,
        "AssociatedRoles": [],
        "PreferredBackupWindow": "09:12-09:42",
        "ClusterCreateTime": "2023-02-27T23:21:33.048Z",
        "DeletionProtection": false,
        "IAMDatabaseAuthenticationEnabled": false,
        "ReadReplicaIdentifiers": [],
        "EngineMode": "provisioned",
        "Engine": "aurora-mysql",
        "StorageEncrypted": false,
        "MultiAZ": false,
        "PreferredMaintenanceWindow": "mon:04:31-mon:05:01",
        "HttpEndpointEnabled": false,
        "BackupRetentionPeriod": 1,
        "DbClusterResourceId": "cluster-ANPAJ4AE5446DAEXAMPLE",
        "DBClusterIdentifier": "sample-cluster",
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1b",
            "us-east-1e"
        ],
        "MasterUsername": "master",
        "EngineVersion": "5.7.mysql_aurora.2.11.1",
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-cluster",
        "DBClusterMembers": [],
        "Port": 3306,
        "Status": "creating",
        "Endpoint": "sample-cluster.cluster-cnpexample.us-east-1.rds.amazonaws.com",
        "DBClusterParameterGroup": "default.aurora-mysql5.7",
        "HostedZoneId": "Z2R2ITUGPM61AM",
        "ReaderEndpoint": "sample-cluster.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
        "CopyTagsToSnapshot": false
    }
}
```
**例 2: PostgreSQL 互換 DB クラスターを作成するには**  
次の `create-db-cluster` の例では、デフォルトのエンジンバージョンを使用して PostgreSQL 互換 DB クラスターを作成します。例のパスワード `secret99` を安全なパスワードに置き換えます。コンソールを使用して DB クラスターを作成する場合、Amazon RDS は DB クラスターのライター DB インスタンスを自動作成します。ただし、CLI を使用して DB AWS クラスターを作成する場合は、`create-db-instance` AWS CLI コマンドを使用して DB クラスターのライター DB インスタンスを明示的に作成する必要があります。  

```
aws rds create-db-cluster \
    --db-cluster-identifier sample-pg-cluster \
    --engine aurora-postgresql \
    --master-username master \
    --master-user-password secret99 \
    --db-subnet-group-name default \
    --vpc-security-group-ids sg-0b9130572daf3dc16
```
出力:  

```
{
    "DBCluster": {
        "Endpoint": "sample-pg-cluster.cluster-cnpexample.us-east-1.rds.amazonaws.com",
        "HttpEndpointEnabled": false,
        "DBClusterMembers": [],
        "EngineMode": "provisioned",
        "CopyTagsToSnapshot": false,
        "HostedZoneId": "Z2R2ITUGPM61AM",
        "IAMDatabaseAuthenticationEnabled": false,
        "AllocatedStorage": 1,
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-0b9130572daf3dc16",
                "Status": "active"
            }
        ],
        "DeletionProtection": false,
        "StorageEncrypted": false,
        "BackupRetentionPeriod": 1,
        "PreferredBackupWindow": "09:56-10:26",
        "ClusterCreateTime": "2023-02-27T23:26:08.371Z",
        "DBClusterParameterGroup": "default.aurora-postgresql13",
        "EngineVersion": "13.7",
        "Engine": "aurora-postgresql",
        "Status": "creating",
        "DBClusterIdentifier": "sample-pg-cluster",
        "MultiAZ": false,
        "Port": 5432,
        "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:sample-pg-cluster",
        "AssociatedRoles": [],
        "DbClusterResourceId": "cluster-ANPAJ4AE5446DAEXAMPLE",
        "PreferredMaintenanceWindow": "wed:03:33-wed:04:03",
        "ReaderEndpoint": "sample-pg-cluster.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
        "MasterUsername": "master",
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1b",
            "us-east-1c"
        ],
        "ReadReplicaIdentifiers": [],
        "DBSubnetGroup": "default"
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスターの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.CreateInstance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-cluster.html)」を参照してください。

### `create-db-instance-read-replica`
<a name="rds_CreateDbInstanceReadReplica_cli_2_topic"></a>

次のコード例は、`create-db-instance-read-replica` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスのリードレプリカを作成するには**  
この例では、`test-instance` という名前の既存の DB インスタンスのリードレプリカを作成します。リードレプリカの名前は `test-instance-repl` です。  

```
aws rds create-db-instance-read-replica \
    --db-instance-identifier test-instance-repl \
    --source-db-instance-identifier test-instance
```
出力:  

```
{
    "DBInstance": {
        "IAMDatabaseAuthenticationEnabled": false,
        "MonitoringInterval": 0,
        "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:test-instance-repl",
        "ReadReplicaSourceDBInstanceIdentifier": "test-instance",
        "DBInstanceIdentifier": "test-instance-repl",
        ...some output truncated...
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbInstanceReadReplica](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-instance-read-replica.html)」を参照してください。

### `create-db-instance`
<a name="rds_CreateDBInstance_cli_2_topic"></a>

次のコード例は、`create-db-instance` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスを作成するには**  
次の `create-db-instance` の例は、必須のオプションを使用して新しい DB インスタンスを起動します。  

```
aws rds create-db-instance \
    --db-instance-identifier test-mysql-instance \
    --db-instance-class db.t3.micro \
    --engine mysql \
    --master-username admin \
    --master-user-password secret99 \
    --allocated-storage 20
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "test-mysql-instance",
        "DBInstanceClass": "db.t3.micro",
        "Engine": "mysql",
        "DBInstanceStatus": "creating",
        "MasterUsername": "admin",
        "AllocatedStorage": 20,
        "PreferredBackupWindow": "12:55-13:25",
        "BackupRetentionPeriod": 1,
        "DBSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-12345abc",
                "Status": "active"
            }
        ],
        "DBParameterGroups": [
            {
                "DBParameterGroupName": "default.mysql5.7",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "DBSubnetGroup": {
            "DBSubnetGroupName": "default",
            "DBSubnetGroupDescription": "default",
            "VpcId": "vpc-2ff2ff2f",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-########",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2c"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-########",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2d"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-########",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-########",
                    "SubnetAvailabilityZone": {
                        "Name": "us-west-2b"
                    },
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "sun:08:07-sun:08:37",
        "PendingModifiedValues": {
            "MasterUserPassword": "****"
        },
        "MultiAZ": false,
        "EngineVersion": "5.7.22",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "general-public-license",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "default:mysql-5-7",
                "Status": "in-sync"
            }
        ],
        "PubliclyAccessible": true,
        "StorageType": "gp2",
        "DbInstancePort": 0,
        "StorageEncrypted": false,
        "DbiResourceId": "db-5555EXAMPLE44444444EXAMPLE",
        "CACertificateIdentifier": "rds-ca-2019",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:test-mysql-instance",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": []
    }
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[Amazon RDS DB インスタンスの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateDBInstance.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDBInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-instance.html)」を参照してください。

### `create-db-parameter-group`
<a name="rds_CreateDBParameterGroup_cli_2_topic"></a>

次のコード例は、`create-db-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB パラメータグループを作成するには**  
次の `create-db-parameter-group` の例は、DB パラメータグループを作成します。  

```
aws rds create-db-parameter-group \
    --db-parameter-group-name mydbparametergroup \
    --db-parameter-group-family MySQL5.6 \
    --description "My new parameter group"
```
出力:  

```
{
    "DBParameterGroup": {
        "DBParameterGroupName": "mydbparametergroup",
        "DBParameterGroupFamily": "mysql5.6",
        "Description": "My new parameter group",
        "DBParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:pg:mydbparametergroup"
    }
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB パラメータグループを作成する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html#USER_WorkingWithParamGroups.Creating)」を参照してください。**  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateDBParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-parameter-group.html)」を参照してください。

### `create-db-proxy-endpoint`
<a name="rds_CreateDbProxyEndpoint_cli_2_topic"></a>

次のコード例は、`create-db-proxy-endpoint` を使用する方法を示しています。

**AWS CLI**  
**RDS データベースの DB プロキシエンドポイントを作成するには**  
次の `create-db-proxy-endpoint` の例では、DB プロキシエンドポイントを作成します。  

```
aws rds create-db-proxy-endpoint \
    --db-proxy-name proxyExample \
    --db-proxy-endpoint-name "proxyep1" \
    --vpc-subnet-ids subnetgroup1 subnetgroup2
```
出力:  

```
{
"DBProxyEndpoint": {
        "DBProxyEndpointName": "proxyep1",
        "DBProxyEndpointArn": "arn:aws:rds:us-east-1:123456789012:db-proxy-endpoint:prx-endpoint-0123a01b12345c0ab",
        "DBProxyName": "proxyExample",
        "Status": "creating",
        "VpcId": "vpc-1234567",
        "VpcSecurityGroupIds": [
            "sg-1234",
            "sg-5678"
        ],
        "VpcSubnetIds": [
            "subnetgroup1",
            "subnetgroup2"
        ],
        "Endpoint": "proxyep1.endpoint.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
        "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
        "TargetRole": "READ_WRITE",
        "IsDefault": false
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[プロキシエンドポイントの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.CreatingEndpoint)」および「*Amazon Aurora ユーザーガイド*」の「[プロキシエンドポイントの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.CreatingEndpoint)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbProxyEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-proxy-endpoint.html)」を参照してください。

### `create-db-proxy`
<a name="rds_CreateDbProxy_cli_2_topic"></a>

次のコード例は、`create-db-proxy` を使用する方法を示しています。

**AWS CLI**  
**RDS データベースの DB プロキシを作成するには**  
次の `create-db-proxy` の例では、DB プロキシを作成します。  

```
aws rds create-db-proxy \
    --db-proxy-name proxyExample \
    --engine-family MYSQL \
    --auth Description="proxydescription1",AuthScheme="SECRETS",SecretArn="arn:aws:secretsmanager:us-west-2:123456789123:secret:secretName-1234f",IAMAuth="DISABLED",ClientPasswordAuthType="MYSQL_NATIVE_PASSWORD" \
    --role-arn arn:aws:iam::123456789123:role/ProxyRole \
    --vpc-subnet-ids subnetgroup1 subnetgroup2
```
出力:  

```
{
"DBProxy": {
        "DBProxyName": "proxyExample",
        "DBProxyArn": "arn:aws:rds:us-east-1:123456789012:db-proxy:prx-0123a01b12345c0ab",
        "EngineFamily": "MYSQL",
        "VpcId": "vpc-1234567",
        "VpcSecuritytGroupIds": [
            "sg-1234",
            "sg-5678",
            "sg-9101"
        ],
        "VpcSubnetIds": [
            "subnetgroup1",
            "subnetgroup2"
        ],
        "Auth": "[
            {
                "Description": "proxydescription1",
                "AuthScheme": "SECRETS",
                "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789123:secret:proxysecret1-Abcd1e",
                "IAMAuth": "DISABLED"
            }
        ]",
        "RoleArn": "arn:aws:iam::12345678912:role/ProxyRole",
        "Endpoint": "proxyExample.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
        "RequireTLS": false,
        "IdleClientTimeout": 1800,
        "DebuggingLogging": false,
        "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
        "UpdatedDate": "2023-04-13T01:49:38.568000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html#rds-proxy-creating)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-setup.html#rds-proxy-creating)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbProxy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-proxy.html)」を参照してください。

### `create-db-security-group`
<a name="rds_CreateDbSecurityGroup_cli_2_topic"></a>

次のコード例は、`create-db-security-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon RDS セキュリティグループを作成するには**  
次の `create-db-security-group` コマンドは、新しい Amazon RDS DB セキュリティグループを作成します。  

```
aws rds create-db-security-group --db-security-group-name mysecgroup --db-security-group-description "My Test Security Group"
```
この例では、新しい DB セキュリティグループに `mysecgroup` という名前が付けられ、説明があります。  
出力:  

```
{
    "DBSecurityGroup": {
        "OwnerId": "123456789012",
        "DBSecurityGroupName": "mysecgroup",
        "DBSecurityGroupDescription": "My Test Security Group",
        "VpcId": "vpc-a1b2c3d4",
        "EC2SecurityGroups": [],
        "IPRanges": [],
        "DBSecurityGroupArn": "arn:aws:rds:us-west-2:123456789012:secgrp:mysecgroup"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-security-group.html)」を参照してください。

### `create-db-shard-group`
<a name="rds_CreateDbShardGroup_cli_2_topic"></a>

次のコード例は、`create-db-shard-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: Aurora PostgreSQL プライマリ DB クラスターを作成するには**  
次の `create-db-cluster` の例では、Aurora Serverless v2 および Aurora Limitless Database と互換性のある Aurora PostgreSQL SQL プライマリ DB クラスターを作成します。  

```
aws rds create-db-cluster \
    --db-cluster-identifier my-sv2-cluster \
    --engine aurora-postgresql \
    --engine-version 15.2-limitless \
    --storage-type aurora-iopt1 \
    --serverless-v2-scaling-configuration MinCapacity=2,MaxCapacity=16 \
    --enable-limitless-database \
    --master-username myuser \
    --master-user-password mypassword \
    --enable-cloudwatch-logs-exports postgresql
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-east-2b",
            "us-east-2c",
            "us-east-2a"
        ],
        "BackupRetentionPeriod": 1,
        "DBClusterIdentifier": "my-sv2-cluster",
        "DBClusterParameterGroup": "default.aurora-postgresql15",
        "DBSubnetGroup": "default",
        "Status": "creating",
        "Endpoint": "my-sv2-cluster.cluster-cekycexample.us-east-2.rds.amazonaws.com",
        "ReaderEndpoint": "my-sv2-cluster.cluster-ro-cekycexample.us-east-2.rds.amazonaws.com",
        "MultiAZ": false,
        "Engine": "aurora-postgresql",
        "EngineVersion": "15.2-limitless",
        "Port": 5432,
        "MasterUsername": "myuser",
        "PreferredBackupWindow": "06:05-06:35",
        "PreferredMaintenanceWindow": "mon:08:25-mon:08:55",
        "ReadReplicaIdentifiers": [],
        "DBClusterMembers": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-########",
                "Status": "active"
            }
        ],
        "HostedZoneId": "Z2XHWR1EXAMPLE",
        "StorageEncrypted": false,
        "DbClusterResourceId": "cluster-XYEDT6ML6FHIXH4Q2J1EXAMPLE",
        "DBClusterArn": "arn:aws:rds:us-east-2:123456789012:cluster:my-sv2-cluster",
        "AssociatedRoles": [],
        "IAMDatabaseAuthenticationEnabled": false,
        "ClusterCreateTime": "2024-02-19T16:24:07.771000+00:00",
        "EnabledCloudwatchLogsExports": [
            "postgresql"
        ],
        "EngineMode": "provisioned",
        "DeletionProtection": false,
        "HttpEndpointEnabled": false,
        "CopyTagsToSnapshot": false,
        "CrossAccountClone": false,
        "DomainMemberships": [],
        "TagList": [],
        "StorageType": "aurora-iopt1",
        "AutoMinorVersionUpgrade": true,
        "ServerlessV2ScalingConfiguration": {
            "MinCapacity": 2.0,
            "MaxCapacity": 16.0
        },
        "NetworkType": "IPV4",
        "IOOptimizedNextAllowedModificationTime": "2024-03-21T16:24:07.781000+00:00",
        "LimitlessDatabase": {
            "Status": "not-in-use",
            "MinRequiredACU": 96.0
        }
    }
}
```
**例 2: プライマリ (ライター) DB インスタンスを作成するには**  
次の `create-db-instance` の例では、Aurora Serverless v2 プライマリ (ライター) DB インスタンスを作成します。コンソールを使用して DB クラスターを作成する場合、Amazon RDS は DB クラスターのライター DB インスタンスを自動作成します。ただし、CLI を使用して DB AWS クラスターを作成する場合は、`create-db-instance` AWS CLI コマンドを使用して DB クラスターのライター DB インスタンスを明示的に作成する必要があります。  

```
aws rds create-db-instance \
    --db-instance-identifier my-sv2-instance \
    --db-cluster-identifier my-sv2-cluster \
    --engine aurora-postgresql \
    --db-instance-class db.serverless
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "my-sv2-instance",
        "DBInstanceClass": "db.serverless",
        "Engine": "aurora-postgresql",
        "DBInstanceStatus": "creating",
        "MasterUsername": "myuser",
        "AllocatedStorage": 1,
        "PreferredBackupWindow": "06:05-06:35",
        "BackupRetentionPeriod": 1,
        "DBSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-########",
                "Status": "active"
            }
        ],
        "DBParameterGroups": [
            {
                "DBParameterGroupName": "default.aurora-postgresql15",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "DBSubnetGroup": {
            "DBSubnetGroupName": "default",
            "DBSubnetGroupDescription": "default",
            "VpcId": "vpc-########",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-########",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-2c"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-########",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-2a"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-########",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-2b"
                    },
                    "SubnetOutpost": {},
                    "SubnetStatus": "Active"
                }
            ]
        },
        "PreferredMaintenanceWindow": "fri:09:01-fri:09:31",
        "PendingModifiedValues": {
            "PendingCloudwatchLogsExports": {
                "LogTypesToEnable": [
                    "postgresql"
                ]
            }
        },
        "MultiAZ": false,
        "EngineVersion": "15.2-limitless",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "postgresql-license",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "default:aurora-postgresql-15",
                "Status": "in-sync"
            }
        ],
        "PubliclyAccessible": false,
        "StorageType": "aurora-iopt1",
        "DbInstancePort": 0,
        "DBClusterIdentifier": "my-sv2-cluster",
        "StorageEncrypted": false,
        "DbiResourceId": "db-BIQTE3B3K3RM7M74SK5EXAMPLE",
        "CACertificateIdentifier": "rds-ca-rsa2048-g1",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "PromotionTier": 1,
        "DBInstanceArn": "arn:aws:rds:us-east-2:123456789012:db:my-sv2-instance",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": [],
        "TagList": [],
        "CustomerOwnedIpEnabled": false,
        "BackupTarget": "region",
        "NetworkType": "IPV4",
        "StorageThroughput": 0,
        "CertificateDetails": {
            "CAIdentifier": "rds-ca-rsa2048-g1"
        },
        "DedicatedLogVolume": false
    }
}
```
**例 3: DB シャードグループを作成するには**  
次の `create-db-shard-group` の例では、Aurora PostgreSQL プライマリ DB クラスターに DB シャードグループを作成します。  

```
aws rds create-db-shard-group \
    --db-shard-group-identifier my-db-shard-group \
    --db-cluster-identifier my-sv2-cluster \
    --max-acu 768
```
出力:  

```
{
    "DBShardGroupResourceId": "shardgroup-a6e3a0226aa243e2ac6c7a1234567890",
    "DBShardGroupIdentifier": "my-db-shard-group",
    "DBClusterIdentifier": "my-sv2-cluster",
    "MaxACU": 768.0,
    "ComputeRedundancy": 0,
    "Status": "creating",
    "PubliclyAccessible": false,
    "Endpoint": "my-sv2-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Aurora Serverless v2 を使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless-v2.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateDbShardGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-shard-group.html)」を参照してください。

### `create-db-snapshot`
<a name="rds_CreateDBSnapshot_cli_2_topic"></a>

次のコード例は、`create-db-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB スナップショットを作成するには**  
次の `create-db-snapshot` の例は、DB スナップショットを作成します。  

```
aws rds create-db-snapshot \
    --db-instance-identifier database-mysql \
    --db-snapshot-identifier mydbsnapshot
```
出力:  

```
{
    "DBSnapshot": {
        "DBSnapshotIdentifier": "mydbsnapshot",
        "DBInstanceIdentifier": "database-mysql",
        "Engine": "mysql",
        "AllocatedStorage": 100,
        "Status": "creating",
        "Port": 3306,
        "AvailabilityZone": "us-east-1b",
        "VpcId": "vpc-6594f31c",
        "InstanceCreateTime": "2019-04-30T15:45:53.663Z",
        "MasterUsername": "admin",
        "EngineVersion": "5.6.40",
        "LicenseModel": "general-public-license",
        "SnapshotType": "manual",
        "Iops": 1000,
        "OptionGroupName": "default:mysql-5-6",
        "PercentProgress": 0,
        "StorageType": "io1",
        "Encrypted": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE",
        "DBSnapshotArn": "arn:aws:rds:us-east-1:123456789012:snapshot:mydbsnapshot",
        "IAMDatabaseAuthenticationEnabled": false,
        "ProcessorFeatures": [],
        "DbiResourceId": "db-AKIAIOSFODNN7EXAMPLE"
    }
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB スナップショットの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateSnapshot.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDBSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-snapshot.html)」を参照してください。

### `create-db-subnet-group`
<a name="rds_CreateDbSubnetGroup_cli_2_topic"></a>

次のコード例は、`create-db-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**DB サブネットグループを作成するには**  
次の `create-db-subnet-group` の例では、既存のサブネットを使用して `mysubnetgroup` という名前の DB サブネットグループを作成します。  

```
aws rds create-db-subnet-group \
    --db-subnet-group-name mysubnetgroup \
    --db-subnet-group-description "test DB subnet group" \
    --subnet-ids '["subnet-0a1dc4e1a6f123456","subnet-070dd7ecb3aaaaaaa","subnet-00f5b198bc0abcdef"]'
```
出力:  

```
{
    "DBSubnetGroup": {
        "DBSubnetGroupName": "mysubnetgroup",
        "DBSubnetGroupDescription": "test DB subnet group",
        "VpcId": "vpc-0f08e7610a1b2c3d4",
        "SubnetGroupStatus": "Complete",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-070dd7ecb3aaaaaaa",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2b"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-00f5b198bc0abcdef",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2d"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-0a1dc4e1a6f123456",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2b"
                },
                "SubnetStatus": "Active"
            }
        ],
        "DBSubnetGroupArn": "arn:aws:rds:us-west-2:0123456789012:subgrp:mysubnetgroup"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[VPC に DB インスタンスを作成する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html#USER_VPC.InstanceInVPC)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDbSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-subnet-group.html)」を参照してください。

### `create-event-subscription`
<a name="rds_CreateEventSubscription_cli_2_topic"></a>

次のコード例は、`create-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを作成するには**  
次の の`create-event-subscription`例では、現在の AWS アカウントの DB インスタンスのバックアップイベントとリカバリイベントのサブスクリプションを作成します。通知は、`--sns-topic-arn` で指定された Amazon Simple Notification Service のトピックに送信されます。  

```
aws rds create-event-subscription \
    --subscription-name my-instance-events \
    --source-type db-instance \
    --event-categories '["backup","recovery"]' \
    --sns-topic-arn arn:aws:sns:us-east-1:123456789012:interesting-events
```
出力:  

```
{
    "EventSubscription": {
        "Status": "creating",
        "CustSubscriptionId": "my-instance-events",
        "SubscriptionCreationTime": "Tue Jul 31 23:22:01 UTC 2018",
        "EventCategoriesList": [
            "backup",
            "recovery"
        ],
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:interesting-events",
        "CustomerAwsId": "123456789012",
        "EventSubscriptionArn": "arn:aws:rds:us-east-1:123456789012:es:my-instance-events",
        "SourceType": "db-instance",
        "Enabled": true
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-event-subscription.html)」を参照してください。

### `create-global-cluster`
<a name="rds_CreateGlobalCluster_cli_2_topic"></a>

次のコード例は、`create-global-cluster` を使用する方法を示しています。

**AWS CLI**  
**グローバル DB クラスターを作成するには**  
次の `create-global-cluster` の例では、新しい Aurora MySQL 互換のグローバル DB クラスターを作成します。  

```
aws rds create-global-cluster \
    --global-cluster-identifier myglobalcluster \
    --engine aurora-mysql
```
出力:  

```
{
    "GlobalCluster": {
        "GlobalClusterIdentifier": "myglobalcluster",
        "GlobalClusterResourceId": "cluster-f0e523bfe07aabb",
        "GlobalClusterArn": "arn:aws:rds::123456789012:global-cluster:myglobalcluster",
        "Status": "available",
        "Engine": "aurora-mysql",
        "EngineVersion": "5.7.mysql_aurora.2.07.2",
        "StorageEncrypted": false,
        "DeletionProtection": false,
        "GlobalClusterMembers": []
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Aurora グローバルデータベースの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-getting-started.html#aurora-global-database-creating)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGlobalCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-global-cluster.html)」を参照してください。

### `create-option-group`
<a name="rds_CreateOptionGroup_cli_2_topic"></a>

次のコード例は、`create-option-group` を使用する方法を示しています。

**AWS CLI**  
**Amazon RDS オプショングループを作成するには**  
次の `create-option-group` コマンドは、`Oracle Enterprise Edition` バージョン `11.2`, is named ``MyOptionGroup` の新しい Amazon RDS オプショングループを作成し、説明を含めます。  

```
aws rds create-option-group \
    --option-group-name MyOptionGroup \
    --engine-name oracle-ee \
    --major-engine-version 11.2 \
    --option-group-description "Oracle Database Manager Database Control"
```
出力:  

```
{
    "OptionGroup": {
        "OptionGroupName": "myoptiongroup",
        "OptionGroupDescription": "Oracle Database Manager Database Control",
        "EngineName": "oracle-ee",
        "MajorEngineVersion": "11.2",
        "Options": [],
        "AllowsVpcAndNonVpcInstanceMemberships": true,
        "OptionGroupArn": "arn:aws:rds:us-west-2:123456789012:og:myoptiongroup"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateOptionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-option-group.html)」を参照してください。

### `delete-blue-green-deployment`
<a name="rds_DeleteBlueGreenDeployment_cli_2_topic"></a>

次のコード例は、`delete-blue-green-deployment` を使用する方法を示しています。

**AWS CLI**  
**例 1: RDS for MySQL DB インスタンスのグリーン環境でリソースを削除するには**  
次の `delete-blue-green-deployment` の例では、RDS for MySQL DB インスタンスのグリーン環境内のリソースを削除します。  

```
aws rds delete-blue-green-deployment \
    --blue-green-deployment-identifier bgd-v53303651eexfake \
    --delete-target
```
出力:  

```
{
    "BlueGreenDeployment": {
        "BlueGreenDeploymentIdentifier": "bgd-v53303651eexfake",
        "BlueGreenDeploymentName": "bgd-cli-test-instance",
        "Source": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
        "Target": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-green-rkfbpe",
        "SwitchoverDetails": [
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-green-rkfbpe",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1-green-j382ha",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2-green-ejv4ao",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3-green-vlpz3t",
                "Status": "AVAILABLE"
            }
        ],
        "Tasks": [
            {
                "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                "Status": "COMPLETED"
            },
            {
                "Name": "DB_ENGINE_VERSION_UPGRADE",
                "Status": "COMPLETED"
            },
            {
                "Name": "CONFIGURE_BACKUPS",
                "Status": "COMPLETED"
            },
            {
                "Name": "CREATING_TOPOLOGY_OF_SOURCE",
                "Status": "COMPLETED"
            }
        ],
        "Status": "DELETING",
        "CreateTime": "2022-02-25T21:18:51.183000+00:00",
        "DeleteTime": "2022-02-25T22:25:31.331000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[ブルー/グリーンデプロイの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-deleting.html)」を参照してください。  
**例 2: Aurora MySQL DB クラスターのグリーン環境でリソースを削除するには**  
次の `delete-blue-green-deployment` の例では、Aurora MySQL DB クラスターのグリーン環境内のリソースを削除します。  

```
aws rds delete-blue-green-deployment \
    --blue-green-deployment-identifier bgd-wi89nwzglccsfake \
    --delete-target
```
出力:  

```
{
    "BlueGreenDeployment": {
        "BlueGreenDeploymentIdentifier": "bgd-wi89nwzglccsfake",
        "BlueGreenDeploymentName": "my-blue-green-deployment",
        "Source": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
        "Target": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3rnukl",
        "SwitchoverDetails": [
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3rnukl",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1-green-gpmaxf",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2-green-j2oajq",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3-green-mkxies",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint-green-4sqjrq",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint-green-gwwzlg",
                "Status": "AVAILABLE"
            }
        ],
        "Tasks": [
            {
                "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                "Status": "COMPLETED"
            },
            {
                "Name": "DB_ENGINE_VERSION_UPGRADE",
                "Status": "COMPLETED"
            },
            {
                "Name": "CREATE_DB_INSTANCES_FOR_CLUSTER",
                "Status": "COMPLETED"
            },
            {
                "Name": "CREATE_CUSTOM_ENDPOINTS",
                "Status": "COMPLETED"
            }
        ],
        "Status": "DELETING",
        "CreateTime": "2022-02-25T21:12:00.288000+00:00",
        "DeleteTime": "2022-02-25T22:29:11.336000+00:00"
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[ブルー/グリーンデプロイの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments-deleting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBlueGreenDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-blue-green-deployment.html)」を参照してください。

### `delete-db-cluster-endpoint`
<a name="rds_DeleteDbClusterEndpoint_cli_2_topic"></a>

次のコード例は、`delete-db-cluster-endpoint` を使用する方法を示しています。

**AWS CLI**  
**カスタム DB クラスターエンドポイントを削除するには**  
次の `delete-db-cluster-endpoint` の例では、指定されたカスタム DB クラスターエンドポイントを削除します。  

```
aws rds delete-db-cluster-endpoint \
    --db-cluster-endpoint-identifier mycustomendpoint
```
出力:  

```
{
    "DBClusterEndpointIdentifier": "mycustomendpoint",
    "DBClusterIdentifier": "mydbcluster",
    "DBClusterEndpointResourceIdentifier": "cluster-endpoint-ANPAJ4AE5446DAEXAMPLE",
    "Endpoint": "mycustomendpoint.cluster-custom-cnpexample.us-east-1.rds.amazonaws.com",
    "Status": "deleting",
    "EndpointType": "CUSTOM",
    "CustomEndpointType": "READER",
    "StaticMembers": [
        "dbinstance1",
        "dbinstance2",
        "dbinstance3"
    ],
    "ExcludedMembers": [],
    "DBClusterEndpointArn": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:mycustomendpoint"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora 接続管理](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbClusterEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-cluster-endpoint.html)」を参照してください。

### `delete-db-cluster-parameter-group`
<a name="rds_DeleteDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`delete-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターパラメータグループを削除するには**  
次の `delete-db-cluster-parameter-group` の例では、指定された DB クラスターパラメータグループを削除します。  

```
aws rds delete-db-cluster-parameter-group \
    --db-cluster-parameter-group-name mydbclusterparametergroup
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-cluster-parameter-group.html)」を参照してください。

### `delete-db-cluster-snapshot`
<a name="rds_DeleteDbClusterSnapshot_cli_2_topic"></a>

次のコード例は、`delete-db-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB クラスタースナップショットを削除するには**  
次の `delete-db-cluster-snapshot` の例では、指定したクラスタースナップショットを削除します。  

```
aws rds delete-db-cluster-snapshot \
    --db-cluster-snapshot-identifier mydbclustersnapshot
```
出力:  

```
{
    "DBClusterSnapshot": {
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1b",
            "us-east-1e"
        ],
        "DBClusterSnapshotIdentifier": "mydbclustersnapshot",
        "DBClusterIdentifier": "mydbcluster",
        "SnapshotCreateTime": "2019-06-18T21:21:00.469Z",
        "Engine": "aurora-mysql",
        "AllocatedStorage": 0,
        "Status": "available",
        "Port": 0,
        "VpcId": "vpc-6594f31c",
        "ClusterCreateTime": "2019-04-15T14:18:42.785Z",
        "MasterUsername": "myadmin",
        "EngineVersion": "5.7.mysql_aurora.2.04.2",
        "LicenseModel": "aurora-mysql",
        "SnapshotType": "manual",
        "PercentProgress": 100,
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE",
        "DBClusterSnapshotArn": "arn:aws:rds:us-east-1:123456789012:cluster-snapshot:mydbclustersnapshot",
        "IAMDatabaseAuthenticationEnabled": false
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[スナップショットの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DeleteSnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-cluster-snapshot.html)」を参照してください。

### `delete-db-cluster`
<a name="rds_DeleteDbCluster_cli_2_topic"></a>

次のコード例は、`delete-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB クラスター内の DB インスタンスを削除するには**  
次の `delete-db-instance` の例では、DB クラスター内の最後の DB インスタンスを削除します。**削除**状態にない DB インスタンスが含まれている DB クラスターは削除できません。DB クラスター内の DB インスタンスを削除するときに、最終的なスナップショットを作成することはできません。  

```
aws rds delete-db-instance \
    --db-instance-identifier database-3
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "database-3",
        "DBInstanceClass": "db.r4.large",
        "Engine": "aurora-postgresql",
        "DBInstanceStatus": "deleting",

    ...output omitted...

    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスターで DB インスタンスを削除する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DeleteInstance.html)」を参照してください。  
**例 2: DB クラスターを削除するには**  
次の `delete-db-cluster` の例では、`mycluster` という名前の DB クラスターを削除し、`mycluster-final-snapshot` という名前の最終スナップショットを作成します。DB クラスターのステータスは、スナップショットの作成中に**表示されるようになります**。削除の進行状況を確認するには、`describe-db-clusters` CLI コマンドを使用します。  

```
aws rds delete-db-cluster \
    --db-cluster-identifier mycluster \
    --no-skip-final-snapshot \
    --final-db-snapshot-identifier mycluster-final-snapshot
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 20,
        "AvailabilityZones": [
            "eu-central-1b",
            "eu-central-1c",
            "eu-central-1a"
        ],
        "BackupRetentionPeriod": 7,
        "DBClusterIdentifier": "mycluster",
        "DBClusterParameterGroup": "default.aurora-postgresql10",
        "DBSubnetGroup": "default-vpc-aa11bb22",
        "Status": "available",

    ...output omitted...

    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[単一 DB インスタンスの Aurora クラスター](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DeleteInstance.html#USER_DeleteInstance.LastInstance)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-cluster.html)」を参照してください。

### `delete-db-instance-automated-backup`
<a name="rds_DeleteDbInstanceAutomatedBackup_cli_2_topic"></a>

次のコード例は、`delete-db-instance-automated-backup` を使用する方法を示しています。

**AWS CLI**  
**リージョンからレプリケートされた自動バックアップを削除するには**  
次の `delete-db-instance-automated-backup` の例では、指定された Amazon リソースネーム (ARN) で自動バックアップを削除します。  

```
aws rds delete-db-instance-automated-backup \
    --db-instance-automated-backups-arn "arn:aws:rds:us-west-2:123456789012:auto-backup:ab-jkib2gfq5rv7replzadausbrktni2bn4example"
```
出力:  

```
{
    "DBInstanceAutomatedBackup": {
        "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:new-orcl-db",
        "DbiResourceId": "db-JKIB2GFQ5RV7REPLZA4EXAMPLE",
        "Region": "us-east-1",
        "DBInstanceIdentifier": "new-orcl-db",
        "RestoreWindow": {},
        "AllocatedStorage": 20,
        "Status": "deleting",
        "Port": 1521,
        "AvailabilityZone": "us-east-1b",
        "VpcId": "vpc-########",
        "InstanceCreateTime": "2020-12-04T15:28:31Z",
        "MasterUsername": "admin",
        "Engine": "oracle-se2",
        "EngineVersion": "12.1.0.2.v21",
        "LicenseModel": "bring-your-own-license",
        "OptionGroupName": "default:oracle-se2-12-1",
        "Encrypted": false,
        "StorageType": "gp2",
        "IAMDatabaseAuthenticationEnabled": false,
        "BackupRetentionPeriod": 7,
        "DBInstanceAutomatedBackupsArn": "arn:aws:rds:us-west-2:123456789012:auto-backup:ab-jkib2gfq5rv7replzadausbrktni2bn4example"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[レプリケーションされたバックアップの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReplicateBackups.html#AutomatedBackups.Delete)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbInstanceAutomatedBackup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-instance-automated-backup.html)」を参照してください。

### `delete-db-instance`
<a name="rds_DeleteDBInstance_cli_2_topic"></a>

次のコード例は、`delete-db-instance` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスを削除するには**  
次の `delete-db-instance` の例は、`test-instance-final-snap` という名前の最終 DB スナップショットを作成した後に、指定された DB インスタンスを削除します。  

```
aws rds delete-db-instance \
    --db-instance-identifier test-instance \
    --final-db-snapshot-identifier test-instance-final-snap
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "test-instance",
        "DBInstanceStatus": "deleting",
        ...some output truncated...
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDBInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-instance.html)」を参照してください。

### `delete-db-parameter-group`
<a name="rds_DeleteDBParameterGroup_cli_2_topic"></a>

次のコード例は、`delete-db-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB パラメータグループを削除するには**  
次の `command` の例は、DB パラメータグループを削除します。  

```
aws rds delete-db-parameter-group \
    --db-parameter-group-name mydbparametergroup
```
このコマンドでは何も出力されません。  
詳細については、「Amazon RDS ユーザーガイド」の「[DB パラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDBParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-parameter-group.html)」を参照してください。

### `delete-db-proxy-endpoint`
<a name="rds_DeleteDbProxyEndpoint_cli_2_topic"></a>

次のコード例は、`delete-db-proxy-endpoint` を使用する方法を示しています。

**AWS CLI**  
**RDS データベースの DB プロキシエンドポイントを削除するには**  
次の `delete-db-proxy-endpoint` の例では、ターゲットデータベースの DB プロキシエンドポイントを削除します。  

```
aws rds delete-db-proxy-endpoint \
    --db-proxy-endpoint-name proxyEP1
```
出力:  

```
{
"DBProxyEndpoint":
    {
        "DBProxyEndpointName": "proxyEP1",
        "DBProxyEndpointArn": "arn:aws:rds:us-east-1:123456789012:db-proxy-endpoint:prx-endpoint-0123a01b12345c0ab",
        "DBProxyName": "proxyExample",
        "Status": "deleting",
        "VpcId": "vpc-1234567",
        "VpcSecurityGroupIds": [
            "sg-1234",
            "sg-5678"
        ],
        "VpcSubnetIds": [
            "subnetgroup1",
            "subnetgroup2"
        ],
        "Endpoint": "proxyEP1.endpoint.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
        "CreatedDate": "2023-04-13T01:49:38.568000+00:00",
        "TargetRole": "READ_ONLY",
        "IsDefault": false
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[プロキシエンドポイントの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.DeletingEndpoint)」および「*Amazon Aurora ユーザーガイド*」の「[プロキシエンドポイントの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.DeletingEndpoint)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbProxyEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-proxy-endpoint.html)」を参照してください。

### `delete-db-proxy`
<a name="rds_DeleteDbProxy_cli_2_topic"></a>

次のコード例は、`delete-db-proxy` を使用する方法を示しています。

**AWS CLI**  
**RDS データベースの DB プロキシを削除するには**  
次の `delete-db-proxy` の例は、DB プロキシを削除します。  

```
aws rds delete-db-proxy \
    --db-proxy-name proxyExample
```
出力:  

```
{
        "DBProxy":
        {
            "DBProxyName": "proxyExample",
            "DBProxyArn": "arn:aws:rds:us-east-1:123456789012:db-proxy:prx-0123a01b12345c0ab",
            "Status": "deleting",
            "EngineFamily": "PostgreSQL",
            "VpcId": "vpc-1234567",
            "VpcSecurityGroupIds": [
                "sg-1234",
                "sg-5678"
            ],
            "VpcSubnetIds": [
                "subnetgroup1",
                "subnetgroup2"
            ],
            "Auth": "[
                {
                "Description": "proxydescription`"
                "AuthScheme": "SECRETS",
                "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789123:secret:proxysecret1-Abcd1e",
                "IAMAuth": "DISABLED"
                } ],
            "RoleArn": "arn:aws:iam::12345678912:role/ProxyPostgreSQLRole",
            "Endpoint": "proxyExample.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
            "RequireTLS": false,
            "IdleClientTimeout": 1800,
            "DebuggingLogging": false,
        "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
        "UpdatedDate": "2023-04-13T01:49:38.568000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-managing.html#rds-proxy-deleting)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-managing.html#rds-proxy-deleting)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbProxy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-proxy.html)」を参照してください。

### `delete-db-security-group`
<a name="rds_DeleteDbSecurityGroup_cli_2_topic"></a>

次のコード例は、`delete-db-security-group` を使用する方法を示しています。

**AWS CLI**  
**DB セキュリティグループを削除するには**  
次の `delete-db-security-group` の例では、`mysecuritygroup` という名前の DB セキュリティプロファイルを削除します。  

```
aws rds delete-db-security-group \
    --db-security-group-name mysecuritygroup
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB セキュリティグループの操作 (EC2-Classic プラットフォーム)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithSecurityGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-security-group.html)」を参照してください。

### `delete-db-shard-group`
<a name="rds_DeleteDbShardGroup_cli_2_topic"></a>

次のコード例は、`delete-db-shard-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB シャードグループの削除に失敗するには**  
次の `delete-db-shard-group` の例は、すべてのデータベースとスキーマを削除する前に DB シャードグループを削除しようとすると発生するエラーを示しています。  

```
aws rds delete-db-shard-group \
    --db-shard-group-identifier limitless-test-shard-grp
```
出力:  

```
An error occurred (InvalidDBShardGroupState) when calling the DeleteDBShardGroup operation: Unable to delete the DB shard group limitless-test-db-shard-group.
Delete all of your Limitless Database databases and schemas, then try again.
```
**例 2: DB シャードグループを正常に削除するには**  
次の `delete-db-shard-group` 例では、`public` スキーマを含むすべてのデータベースとスキーマを削除した後、DB シャードグループを削除します。  

```
aws rds delete-db-shard-group \
    --db-shard-group-identifier limitless-test-shard-grp
```
出力:  

```
{
    "DBShardGroupResourceId": "shardgroup-7bb446329da94788b3f957746example",
    "DBShardGroupIdentifier": "limitless-test-shard-grp",
    "DBClusterIdentifier": "limitless-test-cluster",
    "MaxACU": 768.0,
    "ComputeRedundancy": 0,
    "Status": "deleting",
    "PubliclyAccessible": true,
    "Endpoint": "limitless-test-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Aurora DB クラスターと DB インスタンスを削除する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_DeleteCluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbShardGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-shard-group.html)」を参照してください。

### `delete-db-snapshot`
<a name="rds_DeleteDbSnapshot_cli_2_topic"></a>

次のコード例は、`delete-db-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB スナップショットを削除するには**  
次の `delete-db-snapshot` の例では、指定した DB スナップショットを削除します。  

```
aws rds delete-db-snapshot \
    --db-snapshot-identifier mydbsnapshot
```
出力:  

```
{
    "DBSnapshot": {
        "DBSnapshotIdentifier": "mydbsnapshot",
        "DBInstanceIdentifier": "database-mysql",
        "SnapshotCreateTime": "2019-06-18T22:08:40.702Z",
        "Engine": "mysql",
        "AllocatedStorage": 100,
        "Status": "deleted",
        "Port": 3306,
        "AvailabilityZone": "us-east-1b",
        "VpcId": "vpc-6594f31c",
        "InstanceCreateTime": "2019-04-30T15:45:53.663Z",
        "MasterUsername": "admin",
        "EngineVersion": "5.6.40",
        "LicenseModel": "general-public-license",
        "SnapshotType": "manual",
        "Iops": 1000,
        "OptionGroupName": "default:mysql-5-6",
        "PercentProgress": 100,
        "StorageType": "io1",
        "Encrypted": true,
        "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE",
        "DBSnapshotArn": "arn:aws:rds:us-east-1:123456789012:snapshot:mydbsnapshot",
        "IAMDatabaseAuthenticationEnabled": false,
        "ProcessorFeatures": [],
        "DbiResourceId": "db-AKIAIOSFODNN7EXAMPLE"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[スナップショットの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_DeleteSnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-snapshot.html)」を参照してください。

### `delete-db-subnet-group`
<a name="rds_DeleteDbSubnetGroup_cli_2_topic"></a>

次のコード例は、`delete-db-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**DB サブネットグループを削除するには**  
次の `delete-db-subnet-group` の例では、`mysubnetgroup` という名前の DB サブネットグループを削除します。  

```
aws rds delete-db-subnet-group --db-subnet-group-name mysubnetgroup
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[VPC 内の DB インスタンスの使用](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDbSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-subnet-group.html)」を参照してください。

### `delete-event-subscription`
<a name="rds_DeleteEventSubscription_cli_2_topic"></a>

次のコード例は、`delete-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを削除するには**  
次の `delete-event-subscription` の例では、指定したイベントサブスクリプションを削除します。  

```
aws rds delete-event-subscription --subscription-name my-instance-events
```
出力:  

```
{
    "EventSubscription": {
        "EventSubscriptionArn": "arn:aws:rds:us-east-1:123456789012:es:my-instance-events",
        "CustomerAwsId": "123456789012",
        "Enabled": false,
        "SourceIdsList": [
            "test-instance"
        ],
        "SourceType": "db-instance",
        "EventCategoriesList": [
            "backup",
            "recovery"
        ],
        "SubscriptionCreationTime": "2018-07-31 23:22:01.893",
        "CustSubscriptionId": "my-instance-events",
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:interesting-events",
        "Status": "deleting"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-event-subscription.html)」を参照してください。

### `delete-global-cluster`
<a name="rds_DeleteGlobalCluster_cli_2_topic"></a>

次のコード例は、`delete-global-cluster` を使用する方法を示しています。

**AWS CLI**  
**グローバル DB クラスターを削除するには**  
次の `delete-global-cluster` の例では、Aurora MySQL 互換のグローバル DB クラスターを削除します。出力には、削除しているクラスターが表示されますが、後続の `describe-global-clusters` コマンドにはその DB クラスターはリストされません。  

```
aws rds delete-global-cluster \
    --global-cluster-identifier myglobalcluster
```
出力:  

```
{
    "GlobalCluster": {
        "GlobalClusterIdentifier": "myglobalcluster",
        "GlobalClusterResourceId": "cluster-f0e523bfe07aabb",
        "GlobalClusterArn": "arn:aws:rds::123456789012:global-cluster:myglobalcluster",
        "Status": "available",
        "Engine": "aurora-mysql",
        "EngineVersion": "5.7.mysql_aurora.2.07.2",
        "StorageEncrypted": false,
        "DeletionProtection": false,
        "GlobalClusterMembers": []
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Aurora グローバルデータベースの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-managing.html#aurora-global-database-deleting)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGlobalCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-global-cluster.html)」を参照してください。

### `delete-option-group`
<a name="rds_DeleteOptionGroup_cli_2_topic"></a>

次のコード例は、`delete-option-group` を使用する方法を示しています。

**AWS CLI**  
**オプショングループを削除するには**  
次の `delete-option-group` の例は、指定されたオプショングループを削除します。  

```
aws rds delete-option-group \
    --option-group-name myoptiongroup
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[オプショングループの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithOptionGroups.html#USER_WorkingWithOptionGroups.Delete)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteOptionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-option-group.html)」を参照してください。

### `deregister-db-proxy-targets`
<a name="rds_DeregisterDbProxyTargets_cli_2_topic"></a>

次のコード例は、`deregister-db-proxy-targets` を使用する方法を示しています。

**AWS CLI**  
**DB プロキシターゲットをデータベースターゲットグループから登録解除するには**  
次の `deregister-db-proxy-targets` の例では、プロキシ `proxyExample` とそのターゲット間の関連付けを削除します。  

```
aws rds deregister-db-proxy-targets \
    --db-proxy-name proxyExample \
    --db-instance-identifiers database-1
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-managing.html#rds-proxy-deleting)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-managing.html#rds-proxy-deleting)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterDbProxyTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/deregister-db-proxy-targets.html)」を参照してください。

### `describe-account-attributes`
<a name="rds_DescribeAccountAttributes_cli_2_topic"></a>

次のコード例は、`describe-account-attributes` を使用する方法を示しています。

**AWS CLI**  
**アカウントの属性を記述するには**  
次の の`describe-account-attributes`例では、現在の AWS アカウントの属性を取得します。  

```
aws rds describe-account-attributes
```
出力:  

```
{
    "AccountQuotas": [
        {
            "Max": 40,
            "Used": 4,
            "AccountQuotaName": "DBInstances"
        },
        {
            "Max": 40,
            "Used": 0,
            "AccountQuotaName": "ReservedDBInstances"
        },
        {
            "Max": 100000,
            "Used": 40,
            "AccountQuotaName": "AllocatedStorage"
        },
        {
            "Max": 25,
            "Used": 0,
            "AccountQuotaName": "DBSecurityGroups"
        },
        {
            "Max": 20,
            "Used": 0,
            "AccountQuotaName": "AuthorizationsPerDBSecurityGroup"
        },
        {
            "Max": 50,
            "Used": 1,
            "AccountQuotaName": "DBParameterGroups"
        },
        {
            "Max": 100,
            "Used": 3,
            "AccountQuotaName": "ManualSnapshots"
        },
        {
            "Max": 20,
            "Used": 0,
            "AccountQuotaName": "EventSubscriptions"
        },
        {
            "Max": 50,
            "Used": 1,
            "AccountQuotaName": "DBSubnetGroups"
        },
        {
            "Max": 20,
            "Used": 1,
            "AccountQuotaName": "OptionGroups"
        },
        {
            "Max": 20,
            "Used": 6,
            "AccountQuotaName": "SubnetsPerDBSubnetGroup"
        },
        {
            "Max": 5,
            "Used": 0,
            "AccountQuotaName": "ReadReplicasPerMaster"
        },
        {
            "Max": 40,
            "Used": 1,
            "AccountQuotaName": "DBClusters"
        },
        {
            "Max": 50,
            "Used": 0,
            "AccountQuotaName": "DBClusterParameterGroups"
        },
        {
            "Max": 5,
            "Used": 0,
            "AccountQuotaName": "DBClusterRoles"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-account-attributes.html)」を参照してください。

### `describe-blue-green-deployments`
<a name="rds_DescribeBlueGreenDeployments_cli_2_topic"></a>

次のコード例は、`describe-blue-green-deployments` を使用する方法を示しています。

**AWS CLI**  
**例 1: 作成完了後の RDS DB インスタンスのブルー/グリーンデプロイを記述するには**  
次の `describe-blue-green-deployment` の例では、作成が完了した後にブルー/グリーンデプロイの詳細を取得します。  

```
aws rds describe-blue-green-deployments \
    --blue-green-deployment-identifier bgd-v53303651eexfake
```
出力:  

```
{
    "BlueGreenDeployments": [
        {
            "BlueGreenDeploymentIdentifier": "bgd-v53303651eexfake",
            "BlueGreenDeploymentName": "bgd-cli-test-instance",
            "Source": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
            "Target": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-green-rkfbpe",
            "SwitchoverDetails": [
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-green-rkfbpe",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1-green-j382ha",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2-green-ejv4ao",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3-green-vlpz3t",
                    "Status": "AVAILABLE"
                }
            ],
            "Tasks": [
                {
                    "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "DB_ENGINE_VERSION_UPGRADE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CONFIGURE_BACKUPS",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATING_TOPOLOGY_OF_SOURCE",
                    "Status": "COMPLETED"
                }
            ],
            "Status": "AVAILABLE",
            "CreateTime": "2022-02-25T21:18:51.183000+00:00"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[ブルー/グリーンデプロイの表示](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-viewing.html)」を参照してください。  
**例 2: Aurora MySQL DB クラスター用にブルー/グリーンデプロイを記述するには**  
次の `describe-blue-green-deployment` の例では、ブルー/グリーンデプロイの詳細を取得します。  

```
aws rds describe-blue-green-deployments \
    --blue-green-deployment-identifier bgd-wi89nwzglccsfake
```
出力:  

```
{
    "BlueGreenDeployments": [
        {
            "BlueGreenDeploymentIdentifier": "bgd-wi89nwzglccsfake",
            "BlueGreenDeploymentName": "my-blue-green-deployment",
            "Source": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
            "Target": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3rnukl",
            "SwitchoverDetails": [
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3rnukl",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1-green-gpmaxf",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2-green-j2oajq",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3-green-mkxies",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint-green-4sqjrq",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint-green-gwwzlg",
                    "Status": "AVAILABLE"
                }
            ],
            "Tasks": [
                {
                    "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "DB_ENGINE_VERSION_UPGRADE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATE_DB_INSTANCES_FOR_CLUSTER",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATE_CUSTOM_ENDPOINTS",
                    "Status": "COMPLETED"
                }
            ],
            "Status": "AVAILABLE",
            "CreateTime": "2022-02-25T21:12:00.288000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[ブルー/グリーンデプロイの表示](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments-viewing.html)」を参照してください。  
**例 3: スイッチオーバー後の Aurora MySQL クラスターのブルー/グリーンデプロイを記述するには**  
次の `describe-blue-green-deployment` の例では、グリーン環境を本番環境に昇格した後のブルー/グリーンデプロイの詳細を取得します。  

```
aws rds describe-blue-green-deployments \
    --blue-green-deployment-identifier bgd-wi89nwzglccsfake
```
出力:  

```
{
    "BlueGreenDeployments": [
        {
            "BlueGreenDeploymentIdentifier": "bgd-wi89nwzglccsfake",
            "BlueGreenDeploymentName": "my-blue-green-deployment",
            "Source": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-old1",
            "Target": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
            "SwitchoverDetails": [
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint",
                    "Status": "SWITCHOVER_COMPLETED"
                }
            ],
            "Tasks": [
                {
                    "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "DB_ENGINE_VERSION_UPGRADE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATE_DB_INSTANCES_FOR_CLUSTER",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATE_CUSTOM_ENDPOINTS",
                    "Status": "COMPLETED"
                }
            ],
            "Status": "SWITCHOVER_COMPLETED",
            "CreateTime": "2022-02-25T22:38:49.522000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[ブルー/グリーンデプロイの表示](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments-viewing.html)」を参照してください。  
**例 4: ブルーとグリーンを組み合わせたデプロイを記述するには**  
次の `describe-blue-green-deployment` 例では、ブルーとグリーンを組み合わせたデプロイの詳細を取得します。  

```
aws rds describe-blue-green-deployments
```
出力:  

```
{
    "BlueGreenDeployments": [
        {
            "BlueGreenDeploymentIdentifier": "bgd-wi89nwzgfakelccs",
            "BlueGreenDeploymentName": "my-blue-green-deployment",
            "Source": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
            "Target": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3rnukl",
            "SwitchoverDetails": [
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3rnukl",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1-green-gpmaxf",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2-green-j2oajq",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3-green-mkxies",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint-green-4sqjrq",
                    "Status": "AVAILABLE"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint-green-gwwzlg",
                    "Status": "AVAILABLE"
                }
            ],
            "Tasks": [
                {
                    "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "DB_ENGINE_VERSION_UPGRADE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATE_DB_INSTANCES_FOR_CLUSTER",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATE_CUSTOM_ENDPOINTS",
                    "Status": "COMPLETED"
                }
            ],
            "Status": "AVAILABLE",
            "CreateTime": "2022-02-25T21:12:00.288000+00:00"
        },
        {
            "BlueGreenDeploymentIdentifier": "bgd-v5330365fake1eex",
            "BlueGreenDeploymentName": "bgd-cli-test-instance",
            "Source": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-old1",
            "Target": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
            "SwitchoverDetails": [
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2",
                    "Status": "SWITCHOVER_COMPLETED"
                },
                {
                    "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3-old1",
                    "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3",
                    "Status": "SWITCHOVER_COMPLETED"
                }
            ],
            "Tasks": [
                {
                    "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "DB_ENGINE_VERSION_UPGRADE",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CONFIGURE_BACKUPS",
                    "Status": "COMPLETED"
                },
                {
                    "Name": "CREATING_TOPOLOGY_OF_SOURCE",
                    "Status": "COMPLETED"
                }
            ],
            "Status": "SWITCHOVER_COMPLETED",
            "CreateTime": "2022-02-25T22:33:22.225000+00:00"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[ブルー/グリーンデプロイの表示](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-viewing.html)」および「*Amazon Aurora ユーザーガイド*」の「[ブルー/グリーンデプロイの表示](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments-viewing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeBlueGreenDeployments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-blue-green-deployments.html)」を参照してください。

### `describe-certificates`
<a name="rds_DescribeCertificates_cli_2_topic"></a>

次のコード例は、`describe-certificates` を使用する方法を示しています。

**AWS CLI**  
**証明書を記述するには**  
次の `describe-certificates` の例では、ユーザーのデフォルトリージョンに関連付けられた証明書の詳細を取得します。  

```
aws rds describe-certificates
```
出力:  

```
{
    "Certificates": [
        {
            "CertificateIdentifier": "rds-ca-ecc384-g1",
            "CertificateType": "CA",
            "Thumbprint": "2ee3dcc06e50192559b13929e73484354f23387d",
            "ValidFrom": "2021-05-24T22:06:59+00:00",
            "ValidTill": "2121-05-24T23:06:59+00:00",
            "CertificateArn": "arn:aws:rds:us-west-2::cert:rds-ca-ecc384-g1",
            "CustomerOverride": false
        },
        {
            "CertificateIdentifier": "rds-ca-rsa4096-g1",
            "CertificateType": "CA",
            "Thumbprint": "19da4f2af579a8ae1f6a0fa77aa5befd874b4cab",
            "ValidFrom": "2021-05-24T22:03:20+00:00",
            "ValidTill": "2121-05-24T23:03:20+00:00",
            "CertificateArn": "arn:aws:rds:us-west-2::cert:rds-ca-rsa4096-g1",
            "CustomerOverride": false
        },
        {
            "CertificateIdentifier": "rds-ca-rsa2048-g1",
            "CertificateType": "CA",
            "Thumbprint": "7c40cb42714b6fdb2b296f9bbd0e8bb364436a76",
            "ValidFrom": "2021-05-24T21:59:00+00:00",
            "ValidTill": "2061-05-24T22:59:00+00:00",
            "CertificateArn": "arn:aws:rds:us-west-2::cert:rds-ca-rsa2048-g1",
            "CustomerOverride": true,
            "CustomerOverrideValidTill": "2061-05-24T22:59:00+00:00"
        },
        {
            "CertificateIdentifier": "rds-ca-2019",
            "CertificateType": "CA",
            "Thumbprint": "d40ddb29e3750dffa671c3140bbf5f478d1c8096",
            "ValidFrom": "2019-08-22T17:08:50+00:00",
            "ValidTill": "2024-08-22T17:08:50+00:00",
            "CertificateArn": "arn:aws:rds:us-west-2::cert:rds-ca-2019",
            "CustomerOverride": false
        }
    ],
    "DefaultCertificateForNewLaunches": "rds-ca-rsa2048-g1"
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[SSL/TLS を使用して DB インスタンスへの接続を暗号化する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html)」および「*Amazon Aurora ユーザーガイド*」の「[SSL/TLS を使用して DB クラスターへの接続を暗号化する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/UsingWithRDS.SSL.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-certificates.html)」を参照してください。

### `describe-db-cluster-backtracks`
<a name="rds_DescribeDbClusterBacktracks_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-backtracks` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターのバックトラックを記述するには**  
次の `describe-db-cluster-backtracks` の例は、指定された DB クラスターの詳細情報を取得します。  

```
aws rds describe-db-cluster-backtracks \
    --db-cluster-identifier mydbcluster
```
出力:  

```
{
    "DBClusterBacktracks": [
        {
            "DBClusterIdentifier": "mydbcluster",
            "BacktrackIdentifier": "2f5f5294-0dd2-44c9-9f50-EXAMPLE",
            "BacktrackTo": "2021-02-12T04:59:22Z",
            "BacktrackedFrom": "2021-02-12T14:37:31.640Z",
            "BacktrackRequestCreationTime": "2021-02-12T14:36:18.819Z",
            "Status": "COMPLETED"
        },
        {
            "DBClusterIdentifier": "mydbcluster",
            "BacktrackIdentifier": "3c7a6421-af2a-4ea3-ae95-EXAMPLE",
            "BacktrackTo": "2021-02-11T22:53:46Z",
            "BacktrackedFrom": "2021-02-12T00:09:27.006Z",
            "BacktrackRequestCreationTime": "2021-02-12T00:07:53.487Z",
            "Status": "COMPLETED"
        }
    ]
}
```
詳細については、「Amazon Aurora ユーザーガイド」の「[Aurora DB クラスターのバックトラック](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Managing.Backtrack.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterBacktracks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-cluster-backtracks.html)」を参照してください。

### `describe-db-cluster-endpoints`
<a name="rds_DescribeDbClusterEndpoints_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-endpoints` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB クラスターエンドポイントを記述するには**  
次の `describe-db-cluster-endpoints` の例では、DB クラスターエンドポイントの詳細を取得します。最も一般的な種類の Aurora クラスターには 2 つのエンドポイントがあります。1 つのエンドポイントのタイプは `WRITER` です。このエンドポイントは、すべての SQL ステートメントに使用できます。もう 1 つのエンドポイントのタイプは `READER` です。このエンドポイントは、SELECT およびその他の読み取り専用 SQL ステートメントでのみ使用できます。  

```
aws rds describe-db-cluster-endpoints
```
出力:  

```
{
    "DBClusterEndpoints": [
        {
            "DBClusterIdentifier": "my-database-1",
            "Endpoint": "my-database-1.cluster-cnpexample.us-east-1.rds.amazonaws.com",
            "Status": "creating",
            "EndpointType": "WRITER"
        },
        {
            "DBClusterIdentifier": "my-database-1",
            "Endpoint": "my-database-1.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
            "Status": "creating",
            "EndpointType": "READER"
        },
        {
            "DBClusterIdentifier": "mydbcluster",
            "Endpoint": "mydbcluster.cluster-cnpexamle.us-east-1.rds.amazonaws.com",
            "Status": "available",
            "EndpointType": "WRITER"
        },
        {
            "DBClusterIdentifier": "mydbcluster",
            "Endpoint": "mydbcluster.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
            "Status": "available",
            "EndpointType": "READER"
        }
    ]
}
```
**例 2: 単一の DB クラスターの DB クラスターエンドポイントを記述するには**  
次の `describe-db-cluster-endpoints` の例では、単一の指定された DB クラスターの DB クラスターエンドポイントの詳細を取得します。Aurora Serverless クラスターには、`WRITER` タイプのエンドポイントが 1 つだけあります。  

```
aws rds describe-db-cluster-endpoints \
    --db-cluster-identifier serverless-cluster
```
出力:  

```
{
    "DBClusterEndpoints": [
        {
            "Status": "available",
            "Endpoint": "serverless-cluster.cluster-cnpexample.us-east-1.rds.amazonaws.com",
            "DBClusterIdentifier": "serverless-cluster",
            "EndpointType": "WRITER"
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora 接続管理](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-cluster-endpoints.html)」を参照してください。

### `describe-db-cluster-parameter-groups`
<a name="rds_DescribeDbClusterParameterGroups_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-parameter-groups` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターパラメータグループを記述するには**  
次の `describe-db-cluster-parameter-groups` の例では、DB クラスターパラメータグループの詳細を取得します。  

```
aws rds describe-db-cluster-parameter-groups
```
出力:  

```
{
    "DBClusterParameterGroups": [
        {
            "DBClusterParameterGroupName": "default.aurora-mysql5.7",
            "DBParameterGroupFamily": "aurora-mysql5.7",
            "Description": "Default cluster parameter group for aurora-mysql5.7",
            "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:default.aurora-mysql5.7"
        },
        {
            "DBClusterParameterGroupName": "default.aurora-postgresql9.6",
            "DBParameterGroupFamily": "aurora-postgresql9.6",
            "Description": "Default cluster parameter group for aurora-postgresql9.6",
            "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:default.aurora-postgresql9.6"
        },
        {
            "DBClusterParameterGroupName": "default.aurora5.6",
            "DBParameterGroupFamily": "aurora5.6",
            "Description": "Default cluster parameter group for aurora5.6",
            "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:default.aurora5.6"
        },
        {
            "DBClusterParameterGroupName": "mydbclusterpg",
            "DBParameterGroupFamily": "aurora-mysql5.7",
            "Description": "My DB cluster parameter group",
            "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:mydbclusterpg"
        },
        {
            "DBClusterParameterGroupName": "mydbclusterpgcopy",
            "DBParameterGroupFamily": "aurora-mysql5.7",
            "Description": "Copy of mydbclusterpg parameter group",
            "DBClusterParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:cluster-pg:mydbclusterpgcopy"
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterParameterGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-cluster-parameter-groups.html)」を参照してください。

### `describe-db-cluster-parameters`
<a name="rds_DescribeDbClusterParameters_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-parameters` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB クラスターパラメータグループのパラメータを記述するには**  
次の `describe-db-cluster-parameters` の例では、DB パラメータグループのパラメータに関する詳細を取得します。  

```
aws rds describe-db-cluster-parameters \
    --db-cluster-parameter-group-name mydbclusterpg
```
出力:  

```
{
    "Parameters": [
        {
            "ParameterName": "allow-suspicious-udfs",
            "Description": "Controls whether user-defined functions that have only an xxx symbol for the main function can be loaded",
            "Source": "engine-default",
            "ApplyType": "static",
            "DataType": "boolean",
            "AllowedValues": "0,1",
            "IsModifiable": false,
            "ApplyMethod": "pending-reboot",
            "SupportedEngineModes": [
                "provisioned"
            ]
        },
        {
            "ParameterName": "aurora_lab_mode",
            "ParameterValue": "0",
            "Description": "Enables new features in the Aurora engine.",
            "Source": "engine-default",
            "ApplyType": "static",
            "DataType": "boolean",
            "AllowedValues": "0,1",
            "IsModifiable": true,
            "ApplyMethod": "pending-reboot",
            "SupportedEngineModes": [
                "provisioned"
            ]
        },
        ...some output truncated...
    ]
}
```
**例 2: DB クラスターパラメータグループのパラメータ名のみを一覧表示するには**  
次の `describe-db-cluster-parameters` の例では、DB クラスターパラメータグループ内のパラメータの名前のみを取得します。  

```
aws rds describe-db-cluster-parameters \
    --db-cluster-parameter-group-name default.aurora-mysql5.7 \
    --query 'Parameters[].{ParameterName:ParameterName}'
```
出力:  

```
[
    {
        "ParameterName": "allow-suspicious-udfs"
    },
    {
        "ParameterName": "aurora_binlog_read_buffer_size"
    },
    {
        "ParameterName": "aurora_binlog_replication_max_yield_seconds"
    },
    {
        "ParameterName": "aurora_binlog_use_large_read_buffer"
    },
    {
        "ParameterName": "aurora_lab_mode"
    },

    ...some output truncated...
    }
]
```
**例 3: DB クラスターパラメータグループ内の変更可能なパラメータのみを記述するには**  
次の `describe-db-cluster-parameters` の例では、DB クラスターパラメータグループで変更できるパラメータの名前のみを取得します。  

```
aws rds describe-db-cluster-parameters \
    --db-cluster-parameter-group-name default.aurora-mysql5.7 \
    --query 'Parameters[].{ParameterName:ParameterName,IsModifiable:IsModifiable} | [?IsModifiable == `true`]'
```
出力:  

```
[
    {
        "ParameterName": "aurora_binlog_read_buffer_size",
        "IsModifiable": true
    },
    {
        "ParameterName": "aurora_binlog_replication_max_yield_seconds",
        "IsModifiable": true
    },
    {
        "ParameterName": "aurora_binlog_use_large_read_buffer",
        "IsModifiable": true
    },
    {
        "ParameterName": "aurora_lab_mode",
        "IsModifiable": true
    },

    ...some output truncated...
    }
]
```
**例 4: DB クラスターパラメータグループ内の変更可能なブールパラメータのみを記述するには**  
次の `describe-db-cluster-parameters` の例では、DB クラスターパラメータグループで変更できるパラメータとブール値データ型を持つパラメータの名前のみを取得します。  

```
aws rds describe-db-cluster-parameters \
    --db-cluster-parameter-group-name default.aurora-mysql5.7 \
    --query 'Parameters[].{ParameterName:ParameterName,DataType:DataType,IsModifiable:IsModifiable} | [?DataType == `boolean`] | [?IsModifiable == `true`]'
```
出力:  

```
[
    {
        "DataType": "boolean",
        "ParameterName": "aurora_binlog_use_large_read_buffer",
        "IsModifiable": true
    },
    {
        "DataType": "boolean",
        "ParameterName": "aurora_lab_mode",
        "IsModifiable": true
    },
    {
        "DataType": "boolean",
        "ParameterName": "autocommit",
        "IsModifiable": true
    },
    {
        "DataType": "boolean",
        "ParameterName": "automatic_sp_privileges",
        "IsModifiable": true
    },
    ...some output truncated...
    }
]
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-cluster-parameters.html)」を参照してください。

### `describe-db-cluster-snapshot-attributes`
<a name="rds_DescribeDbClusterSnapshotAttributes_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-snapshot-attributes` を使用する方法を示しています。

**AWS CLI**  
**DB クラスタースナップショットの属性名と値を記述するには**  
次の `describe-db-cluster-snapshot-attributes` の例では、指定された DB クラスタースナップショットの属性名と値の詳細を取得します。  

```
aws rds describe-db-cluster-snapshot-attributes \
    --db-cluster-snapshot-identifier myclustersnapshot
```
出力:  

```
{
    "DBClusterSnapshotAttributesResult": {
        "DBClusterSnapshotIdentifier": "myclustersnapshot",
        "DBClusterSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "123456789012"
                ]
            }
        ]
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスタースナップショットの共有](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_ShareSnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterSnapshotAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-cluster-snapshot-attributes.html)」を参照してください。

### `describe-db-cluster-snapshots`
<a name="rds_DescribeDbClusterSnapshots_cli_2_topic"></a>

次のコード例は、`describe-db-cluster-snapshots` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターの DB クラスタースナップショットを記述するには**  
次の `describe-db-cluster-snapshots` の例では、指定された DB クラスターの DB クラスタースナップショットの詳細を取得します。  

```
aws rds describe-db-cluster-snapshots \
    --db-cluster-identifier mydbcluster
```
出力:  

```
{
    "DBClusterSnapshots": [
        {
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1e"
            ],
            "DBClusterSnapshotIdentifier": "myclustersnapshotcopy",
            "DBClusterIdentifier": "mydbcluster",
            "SnapshotCreateTime": "2019-06-04T09:16:42.649Z",
            "Engine": "aurora-mysql",
            "AllocatedStorage": 0,
            "Status": "available",
            "Port": 0,
            "VpcId": "vpc-6594f31c",
            "ClusterCreateTime": "2019-04-15T14:18:42.785Z",
            "MasterUsername": "myadmin",
            "EngineVersion": "5.7.mysql_aurora.2.04.2",
            "LicenseModel": "aurora-mysql",
            "SnapshotType": "manual",
            "PercentProgress": 100,
            "StorageEncrypted": true,
            "KmsKeyId": "arn:aws:kms:us-east-1:123456789012:key/AKIAIOSFODNN7EXAMPLE",
            "DBClusterSnapshotArn": "arn:aws:rds:us-east-1:814387698303:cluster-snapshot:myclustersnapshotcopy",
            "IAMDatabaseAuthenticationEnabled": false
        },
        {
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1e"
            ],
            "DBClusterSnapshotIdentifier": "rds:mydbcluster-2019-06-20-09-16",
            "DBClusterIdentifier": "mydbcluster",
            "SnapshotCreateTime": "2019-06-20T09:16:26.569Z",
            "Engine": "aurora-mysql",
            "AllocatedStorage": 0,
            "Status": "available",
            "Port": 0,
            "VpcId": "vpc-6594f31c",
            "ClusterCreateTime": "2019-04-15T14:18:42.785Z",
            "MasterUsername": "myadmin",
            "EngineVersion": "5.7.mysql_aurora.2.04.2",
            "LicenseModel": "aurora-mysql",
            "SnapshotType": "automated",
            "PercentProgress": 100,
            "StorageEncrypted": true,
            "KmsKeyId": "arn:aws:kms:us-east-1:814387698303:key/AKIAIOSFODNN7EXAMPLE",
            "DBClusterSnapshotArn": "arn:aws:rds:us-east-1:123456789012:cluster-snapshot:rds:mydbcluster-2019-06-20-09-16",
            "IAMDatabaseAuthenticationEnabled": false
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスタースナップショットの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_CreateSnapshotCluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusterSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-cluster-snapshots.html)」を参照してください。

### `describe-db-clusters`
<a name="rds_DescribeDbClusters_cli_2_topic"></a>

次のコード例は、`describe-db-clusters` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB クラスターを記述するには**  
次の `describe-db-clusters` の例は、指定された DB クラスターの詳細情報を取得します。  

```
aws rds describe-db-clusters \
    --db-cluster-identifier mydbcluster
```
出力:  

```
{
    "DBClusters": [
        {
            "AllocatedStorage": 1,
            "AvailabilityZones": [
                "us-east-1a",
                "us-east-1b",
                "us-east-1e"
            ],
            "BackupRetentionPeriod": 1,
            "DatabaseName": "mydbcluster",
            "DBClusterIdentifier": "mydbcluster",
            "DBClusterParameterGroup": "default.aurora-mysql5.7",
            "DBSubnetGroup": "default",
            "Status": "available",
            "EarliestRestorableTime": "2019-06-19T09:16:28.210Z",
            "Endpoint": "mydbcluster.cluster-cnpexample.us-east-1.rds.amazonaws.com",
            "ReaderEndpoint": "mydbcluster.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
            "MultiAZ": true,
            "Engine": "aurora-mysql",
            "EngineVersion": "5.7.mysql_aurora.2.04.2",
            "LatestRestorableTime": "2019-06-20T22:38:14.908Z",
            "Port": 3306,
            "MasterUsername": "myadmin",
            "PreferredBackupWindow": "09:09-09:39",
            "PreferredMaintenanceWindow": "sat:04:09-sat:04:39",
            "ReadReplicaIdentifiers": [],
            "DBClusterMembers": [
                {
                    "DBInstanceIdentifier": "dbinstance3",
                    "IsClusterWriter": false,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                },
                {
                    "DBInstanceIdentifier": "dbinstance1",
                    "IsClusterWriter": false,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                },
                {
                    "DBInstanceIdentifier": "dbinstance2",
                    "IsClusterWriter": false,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                },
                {
                    "DBInstanceIdentifier": "mydbcluster",
                    "IsClusterWriter": false,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                },
                {
                    "DBInstanceIdentifier": "mydbcluster-us-east-1b",
                    "IsClusterWriter": false,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                },
                {
                    "DBInstanceIdentifier": "mydbcluster",
                    "IsClusterWriter": true,
                    "DBClusterParameterGroupStatus": "in-sync",
                    "PromotionTier": 1
                }
            ],
            "VpcSecurityGroups": [
                {
                    "VpcSecurityGroupId": "sg-0b9130572daf3dc16",
                    "Status": "active"
                }
            ],
            "HostedZoneId": "Z2R2ITUGPM61AM",
            "StorageEncrypted": true,
            "KmsKeyId": "arn:aws:kms:us-east-1:814387698303:key/AKIAIOSFODNN7EXAMPLE",
            "DbClusterResourceId": "cluster-AKIAIOSFODNN7EXAMPLE",
            "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:mydbcluster",
            "AssociatedRoles": [],
            "IAMDatabaseAuthenticationEnabled": false,
            "ClusterCreateTime": "2019-04-15T14:18:42.785Z",
            "EngineMode": "provisioned",
            "DeletionProtection": false,
            "HttpEndpointEnabled": false
        }
    ]
}
```
**例 2: すべての DB クラスターの特定の属性を一覧表示するには**  
次の の`describe-db-clusters`例では`DBClusterIdentifier`、現在の AWS リージョン内のすべての DB クラスターの 、`Endpoint`、および `ReaderEndpoint` 属性のみを取得します。  

```
aws rds describe-db-clusters \
    --query 'DBClusters[].{DBClusterIdentifier:DBClusterIdentifier,Endpoint:Endpoint,ReaderEndpoint:ReaderEndpoint}'
```
出力:  

```
[
    {
        "Endpoint": "cluster-57-2020-05-01-2270.cluster-cnpexample.us-east-1.rds.amazonaws.com",
        "ReaderEndpoint": "cluster-57-2020-05-01-2270.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
        "DBClusterIdentifier": "cluster-57-2020-05-01-2270"
    },
    {
        "Endpoint": "cluster-57-2020-05-01-4615.cluster-cnpexample.us-east-1.rds.amazonaws.com",
        "ReaderEndpoint": "cluster-57-2020-05-01-4615.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
        "DBClusterIdentifier": "cluster-57-2020-05-01-4615"
    },
    {
        "Endpoint": "pg2-cluster.cluster-cnpexample.us-east-1.rds.amazonaws.com",
        "ReaderEndpoint": "pg2-cluster.cluster-ro-cnpexample.us-east-1.rds.amazonaws.com",
        "DBClusterIdentifier": "pg2-cluster"
    },
    ...output omitted...
    }
]
```
**例 3: 特定の属性を持つ DB クラスターを一覧表示するには**  
次の `describe-db-clusters` の例では、`aurora-postgresql` DB エンジンを使用する DB クラスターの `DBClusterIdentifier` および `Engine` 属性のみを取得します。  

```
aws rds describe-db-clusters \
    --query 'DBClusters[].{DBClusterIdentifier:DBClusterIdentifier,Engine:Engine} | [?Engine == `aurora-postgresql`]'
```
出力:  

```
[
    {
        "Engine": "aurora-postgresql",
        "DBClusterIdentifier": "pg2-cluster"
    }
]
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスター](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-clusters.html)」を参照してください。

### `describe-db-engine-versions`
<a name="rds_DescribeDBEngineVersions_cli_2_topic"></a>

次のコード例は、`describe-db-engine-versions` を使用する方法を示しています。

**AWS CLI**  
**MySQL DB エンジンの DB エンジンバージョンを記述するには**  
次の `describe-db-engine-versions` の例は、指定された DB エンジンの各 DB エンジンバージョンに関する詳細が表示されます。  

```
aws rds describe-db-engine-versions \
    --engine mysql
```
出力:  

```
{
    "DBEngineVersions": [
        {
            "Engine": "mysql",
            "EngineVersion": "5.5.46",
            "DBParameterGroupFamily": "mysql5.5",
            "DBEngineDescription": "MySQL Community Edition",
            "DBEngineVersionDescription": "MySQL 5.5.46",
            "ValidUpgradeTarget": [
                {
                    "Engine": "mysql",
                    "EngineVersion": "5.5.53",
                    "Description": "MySQL 5.5.53",
                    "AutoUpgrade": false,
                    "IsMajorVersionUpgrade": false
                },
                {
                    "Engine": "mysql",
                    "EngineVersion": "5.5.54",
                    "Description": "MySQL 5.5.54",
                    "AutoUpgrade": false,
                    "IsMajorVersionUpgrade": false
                },
                {
                    "Engine": "mysql",
                    "EngineVersion": "5.5.57",
                    "Description": "MySQL 5.5.57",
                    "AutoUpgrade": false,
                    "IsMajorVersionUpgrade": false
                },
                ...some output truncated...
            ]
        }
```
詳細については、「Amazon RDS ユーザーガイド」の「[Amazon Relational Database Service (Amazon RDS) とは](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeDBEngineVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-engine-versions.html)」を参照してください。**

### `describe-db-instance-automated-backups`
<a name="rds_DescribeDbInstanceAutomatedBackups_cli_2_topic"></a>

次のコード例は、`describe-db-instance-automated-backups` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスの自動バックアップを記述するには**  
次の `describe-db-instance-automated-backups` の例では、指定された DB インスタンスの自動バックアップの詳細を表示します。詳細には、他の AWS リージョンでのレプリケートされた自動バックアップが含まれます。  

```
aws rds describe-db-instance-automated-backups \
    --db-instance-identifier new-orcl-db
```
出力:  

```
{
    "DBInstanceAutomatedBackups": [
        {
            "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:new-orcl-db",
            "DbiResourceId": "db-JKIB2GFQ5RV7REPLZA4EXAMPLE",
            "Region": "us-east-1",
            "DBInstanceIdentifier": "new-orcl-db",
            "RestoreWindow": {
                "EarliestTime": "2020-12-07T21:05:20.939Z",
                "LatestTime": "2020-12-07T21:05:20.939Z"
            },
            "AllocatedStorage": 20,
            "Status": "replicating",
            "Port": 1521,
            "InstanceCreateTime": "2020-12-04T15:28:31Z",
            "MasterUsername": "admin",
            "Engine": "oracle-se2",
            "EngineVersion": "12.1.0.2.v21",
            "LicenseModel": "bring-your-own-license",
            "OptionGroupName": "default:oracle-se2-12-1",
            "Encrypted": false,
            "StorageType": "gp2",
            "IAMDatabaseAuthenticationEnabled": false,
            "BackupRetentionPeriod": 14,
            "DBInstanceAutomatedBackupsArn": "arn:aws:rds:us-west-2:123456789012:auto-backup:ab-jkib2gfq5rv7replzadausbrktni2bn4example"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[レプリケーションされたバックアップに関する情報の検索](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReplicateBackups.html#AutomatedBackups.Replicating.Describe)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbInstanceAutomatedBackups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-instance-automated-backups.html)」を参照してください。

### `describe-db-instances`
<a name="rds_DescribeDBInstances_cli_2_topic"></a>

次のコード例は、`describe-db-instances` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスを記述するには**  
次の `describe-db-instances` の例は、指定された DB インスタンスの詳細情報を取得します。  

```
aws rds describe-db-instances \
    --db-instance-identifier mydbinstancecf
```
出力:  

```
{
    "DBInstances": [
        {
            "DBInstanceIdentifier": "mydbinstancecf",
            "DBInstanceClass": "db.t3.small",
            "Engine": "mysql",
            "DBInstanceStatus": "available",
            "MasterUsername": "masterawsuser",
            "Endpoint": {
                "Address": "mydbinstancecf.abcexample.us-east-1.rds.amazonaws.com",
                "Port": 3306,
                "HostedZoneId": "Z2R2ITUGPM61AM"
            },
            ...some output truncated...
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeDBInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-instances.html)」を参照してください。**

### `describe-db-log-files`
<a name="rds_DescribeDbLogFiles_cli_2_topic"></a>

次のコード例は、`describe-db-log-files` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスのログファイルを記述するには**  
次の `describe-db-log-files` の例は、指定された DB インスタンスのログファイルの詳細を取得します。  

```
aws rds describe-db-log-files -\
    -db-instance-identifier test-instance
```
出力:  

```
{
    "DescribeDBLogFiles": [
        {
            "Size": 0,
            "LastWritten": 1533060000000,
            "LogFileName": "error/mysql-error-running.log"
        },
        {
            "Size": 2683,
            "LastWritten": 1532994300000,
            "LogFileName": "error/mysql-error-running.log.0"
        },
        {
            "Size": 107,
            "LastWritten": 1533057300000,
            "LogFileName": "error/mysql-error-running.log.18"
        },
        {
            "Size": 13105,
            "LastWritten": 1532991000000,
            "LogFileName": "error/mysql-error-running.log.23"
        },
        {
            "Size": 0,
            "LastWritten": 1533061200000,
            "LogFileName": "error/mysql-error.log"
        },
        {
            "Size": 3519,
            "LastWritten": 1532989252000,
            "LogFileName": "mysqlUpgrade"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbLogFiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-log-files.html)」を参照してください。

### `describe-db-parameter-groups`
<a name="rds_DescribeDBParameterGroups_cli_2_topic"></a>

次のコード例は、`describe-db-parameter-groups` を使用する方法を示しています。

**AWS CLI**  
**DB パラメータグループを記述するには**  
次の `describe-db-parameter-groups` の例では、DB パラメータグループに関する詳細を取得します。  

```
aws rds describe-db-parameter-groups
```
出力:  

```
{
    "DBParameterGroups": [
        {
            "DBParameterGroupName": "default.aurora-mysql5.7",
            "DBParameterGroupFamily": "aurora-mysql5.7",
            "Description": "Default parameter group for aurora-mysql5.7",
            "DBParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:pg:default.aurora-mysql5.7"
        },
        {
            "DBParameterGroupName": "default.aurora-postgresql9.6",
            "DBParameterGroupFamily": "aurora-postgresql9.6",
            "Description": "Default parameter group for aurora-postgresql9.6",
            "DBParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:pg:default.aurora-postgresql9.6"
        },
        {
            "DBParameterGroupName": "default.aurora5.6",
            "DBParameterGroupFamily": "aurora5.6",
            "Description": "Default parameter group for aurora5.6",
            "DBParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:pg:default.aurora5.6"
        },
        {
            "DBParameterGroupName": "default.mariadb10.1",
            "DBParameterGroupFamily": "mariadb10.1",
            "Description": "Default parameter group for mariadb10.1",
            "DBParameterGroupArn": "arn:aws:rds:us-east-1:123456789012:pg:default.mariadb10.1"
        },
        ...some output truncated...
    ]
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB パラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeDBParameterGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-parameter-groups.html)」を参照してください。**

### `describe-db-parameters`
<a name="rds_DescribeDBParameters_cli_2_topic"></a>

次のコード例は、`describe-db-parameters` を使用する方法を示しています。

**AWS CLI**  
**DB パラメータグループのパラメータを記述するには**  
次の `describe-db-parameters` の例では、指定された DB パラメータグループに関する詳細を取得します。  

```
aws rds describe-db-parameters \
    --db-parameter-group-name mydbpg
```
出力:  

```
{
    "Parameters": [
        {
            "ParameterName": "allow-suspicious-udfs",
            "Description": "Controls whether user-defined functions that have only an xxx symbol for the main function can be loaded",
            "Source": "engine-default",
            "ApplyType": "static",
            "DataType": "boolean",
            "AllowedValues": "0,1",
            "IsModifiable": false,
            "ApplyMethod": "pending-reboot"
        },
        {
            "ParameterName": "auto_generate_certs",
            "Description": "Controls whether the server autogenerates SSL key and certificate files in the data directory, if they do not already exist.",
            "Source": "engine-default",
            "ApplyType": "static",
            "DataType": "boolean",
            "AllowedValues": "0,1",
            "IsModifiable": false,
            "ApplyMethod": "pending-reboot"
        },
        ...some output truncated...
    ]
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB パラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeDBParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-parameters.html)」を参照してください。**

### `describe-db-proxies`
<a name="rds_DescribeDbProxies_cli_2_topic"></a>

次のコード例は、`describe-db-proxies` を使用する方法を示しています。

**AWS CLI**  
**RDS データベースの DB プロキシを記述するには**  
次の `describe-db-proxies` の例では、DB プロキシに関する情報を取得します。　  

```
aws rds describe-db-proxies
```
出力:  

```
{
    "DBProxies": [
        {
            "DBProxyName": "proxyExample1",
            "DBProxyArn": "arn:aws:rds:us-east-1:123456789012:db-proxy:prx-0123a01b12345c0ab",
            "Status": "available",
            "EngineFamily": "PostgreSQL",
            "VpcId": "vpc-1234567",
            "VpcSecurityGroupIds": [
                "sg-1234"
            ],
            "VpcSubnetIds": [
                "subnetgroup1",
                "subnetgroup2"
            ],
            "Auth": "[
                {
                    "Description": "proxydescription1"
                    "AuthScheme": "SECRETS",
                    "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789123:secret:secretName-1234f",
                    "IAMAuth": "DISABLED"
                }
            ]",
            "RoleArn": "arn:aws:iam::12345678912??:role/ProxyPostgreSQLRole",
            "Endpoint": "proxyExample1.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
            "RequireTLS": false,
            "IdleClientTimeout": 1800,
            "DebuggingLogging": false,
            "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
            "UpdatedDate": "2023-04-13T01:49:38.568000+00:00"
        },
        {
            "DBProxyName": "proxyExample2",
            "DBProxyArn": "arn:aws:rds:us-east-1:123456789012:db-proxy:prx-1234a12b23456c1ab",
            "Status": "available",
            "EngineFamily": "PostgreSQL",
            "VpcId": "sg-1234567",
            "VpcSecurityGroupIds": [
                "sg-1234"
            ],
            "VpcSubnetIds": [
                "subnetgroup1",
                "subnetgroup2"
            ],
            "Auth": "[
                {
                    "Description": "proxydescription2"
                    "AuthScheme": "SECRETS",
                    "SecretArn": "aarn:aws:secretsmanager:us-west-2:123456789123:secret:secretName-1234f",
                    "IAMAuth": "DISABLED"
                }
            ]",
            "RoleArn": "arn:aws:iam::12345678912:role/ProxyPostgreSQLRole",
            "Endpoint": "proxyExample2.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
            "RequireTLS": false,
            "IdleClientTimeout": 1800,
            "DebuggingLogging": false,
            "CreatedDate": "2022-01-05T16:19:33.452000+00:00",
            "UpdatedDate": "2023-04-13T01:49:38.568000+00:00"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの表示](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html#rds-proxy-viewing)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの表示](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-setup.html#rds-proxy-viewing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbProxies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-proxies.html)」を参照してください。

### `describe-db-proxy-endpoints`
<a name="rds_DescribeDbProxyEndpoints_cli_2_topic"></a>

次のコード例は、`describe-db-proxy-endpoints` を使用する方法を示しています。

**AWS CLI**  
**DB プロキシエンドポイントを記述するには**  
次の `describe-db-proxy-endpoints` の例では、DB プロキシエンドポイントに関する情報を返します。  

```
aws rds describe-db-proxy-endpoints
```
出力:  

```
{
    "DBProxyEndpoints": [
        {
            "DBProxyEndpointName": "proxyEndpoint1",
            "DBProxyEndpointArn": "arn:aws:rds:us-east-1:123456789012:db-proxy-endpoint:prx-endpoint-0123a01b12345c0ab",
            "DBProxyName": "proxyExample",
            "Status": "available",
            "VpcId": "vpc-1234567",
            "VpcSecurityGroupIds": [
                "sg-1234"
            ],
            "VpcSubnetIds": [
                "subnetgroup1",
                "subnetgroup2"
            ],
            "Endpoint": "proxyEndpoint1.endpoint.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
            "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
            "TargetRole": "READ_WRITE",
            "IsDefault": false
        },
        {
            "DBProxyEndpointName": "proxyEndpoint2",
            "DBProxyEndpointArn": "arn:aws:rds:us-east-1:123456789012:db-proxy-endpoint:prx-endpoint-4567a01b12345c0ab",
            "DBProxyName": "proxyExample2",
            "Status": "available",
            "VpcId": "vpc1234567",
            "VpcSecurityGroupIds": [
                "sg-5678"
            ],
            "VpcSubnetIds": [
                "subnetgroup1",
                "subnetgroup2"
            ],
            "Endpoint": "proxyEndpoint2.endpoint.proxy-cd1ef2klmnop.us-east-1.rds.amazonaws.com",
            "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
            "TargetRole": "READ_WRITE",
            "IsDefault": false
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[プロキシエンドポイントの表示](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.DescribingEndpoint)」および「*Amazon Aurora ユーザーガイド*」の「[プロキシエンドポイントの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.DescribingEndpoint)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbProxyEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-proxy-endpoints.html)」を参照してください。

### `describe-db-proxy-target-groups`
<a name="rds_DescribeDbProxyTargetGroups_cli_2_topic"></a>

次のコード例は、`describe-db-proxy-target-groups` を使用する方法を示しています。

**AWS CLI**  
**DB プロキシエンドポイントを記述するには**  
次の `describe-db-proxy-target-groups` の例では、DB プロキシターゲットグループに関する情報を取得します。　  

```
aws rds describe-db-proxy-target-groups \
    --db-proxy-name proxyExample
```
出力:  

```
{
"TargetGroups":
    {
        "DBProxyName": "proxyExample",
        "TargetGroupName": "default",
        "TargetGroupArn": "arn:aws:rds:us-east-1:123456789012:target-group:prx-tg-0123a01b12345c0ab",
        "IsDefault": true,
        "Status": "available",
        "ConnectionPoolConfig": {
            "MaxConnectionsPercent": 100,
            "MaxIdleConnectionsPercent": 50,
            "ConnectionBorrowTimeout": 120,
            "SessionPinningFilters": []
        },
        "CreatedDate": "2023-05-02T18:41:19.495000+00:00",
        "UpdatedDate": "2023-05-02T18:41:21.762000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの表示](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html#rds-proxy-viewing)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの表示](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-setup.html#rds-proxy-viewing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbProxyTargetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-proxy-target-groups.html)」を参照してください。

### `describe-db-proxy-targets`
<a name="rds_DescribeDbProxyTargets_cli_2_topic"></a>

次のコード例は、`describe-db-proxy-targets` を使用する方法を示しています。

**AWS CLI**  
**DB プロキシターゲットを記述するには**  
次の `describe-db-proxy-targets` の例では、DB プロキシターゲットに関する情報を返します。  

```
aws rds describe-db-proxy-targets \
    --db-proxy-name proxyExample
```
出力:  

```
{
    "Targets": [
        {
            "Endpoint": "database1.ab0cd1efghij.us-east-1.rds.amazonaws.com",
            "TrackedClusterId": "database1",
            "RdsResourceId": "database1-instance-1",
            "Port": 3306,
            "Type": "RDS_INSTANCE",
            "Role": "READ_WRITE",
            "TargetHealth": {
                "State": "UNAVAILABLE",
                "Reason": "PENDING_PROXY_CAPACITY",
                "Description": "DBProxy Target is waiting for proxy to scale to desired capacity"
            }
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの表示](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html#rds-proxy-viewing)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの表示](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-setup.html#rds-proxy-viewing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbProxyTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-proxy-targets.html)」を参照してください。

### `describe-db-recommendations`
<a name="rds_DescribeDbRecommendations_cli_2_topic"></a>

次のコード例は、`describe-db-recommendations` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべての DB レコメンデーションを一覧表示するには**  
次の の`describe-db-recommendations`例では、 AWS アカウント内のすべての DB レコメンデーションを一覧表示します。  

```
aws rds describe-db-recommendations
```
出力:  

```
{
    "DBRecommendations": [
        {
            "RecommendationId": "12ab3cde-f456-7g8h-9012-i3j45678k9lm",
            "TypeId": "config_recommendation::old_minor_version",
            "Severity": "informational",
            "ResourceArn": "arn:aws:rds:us-west-2:111122223333:db:database-1",
            "Status": "active",
            "CreatedTime": "2024-02-21T23:14:19.292000+00:00",
            "UpdatedTime": "2024-02-21T23:14:19+00:00",
            "Detection": "**[resource-name]** is not running the latest minor DB engine version",
            "Recommendation": "Upgrade to latest engine version",
            "Description": "Your database resources aren't running the latest minor DB engine version. The latest minor version contains the latest security fixes and other improvements.",
            "RecommendedActions": [
                {
                    "ActionId": "12ab34c5de6fg7h89i0jk1lm234n5678",
                    "Operation": "modifyDbInstance",
                    "Parameters": [
                        {
                            "Key": "EngineVersion",
                            "Value": "5.7.44"
                        },
                        {
                            "Key": "DBInstanceIdentifier",
                            "Value": "database-1"
                        }
                    ],
                    "ApplyModes": [
                        "immediately",
                        "next-maintenance-window"
                    ],
                    "Status": "ready",
                    "ContextAttributes": [
                        {
                            "Key": "Recommended value",
                            "Value": "5.7.44"
                        },
                        {
                            "Key": "Current engine version",
                            "Value": "5.7.42"
                        }
                    ]
                }
            ],
            "Category": "security",
            "Source": "RDS",
            "TypeDetection": "**[resource-count] resources** are not running the latest minor DB engine version",
            "TypeRecommendation": "Upgrade to latest engine version",
            "Impact": "Reduced database performance and data security at risk",
            "AdditionalInfo": "We recommend that you maintain your database with the latest DB engine minor version as this version includes the latest security and functionality fixes. The DB engine minor version upgrades contain only the changes which are backward-compatible with earlier minor versions of the same major version of the DB engine.",
            "Links": [
                {
                    "Text": "Upgrading an RDS DB instance engine version",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html"
                },
                {
                    "Text": "Using Amazon RDS Blue/Green Deployments for database updates for Amazon Aurora",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments.html"
                },
                {
                    "Text": "Using Amazon RDS Blue/Green Deployments for database updates for Amazon RDS",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments.html"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/monitoring-recommendations.html)」および「*Amazon Aurora ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/monitoring-recommendations.html)」を参照してください。  
**例 2: 重要度の高い DB レコメンデーションを一覧表示するには**  
次の の`describe-db-recommendations`例では、 AWS アカウントの重要度の高い DB レコメンデーションを一覧表示します。  

```
aws rds describe-db-recommendations \
    --filters Name=severity,Values=high
```
出力:  

```
{
    "DBRecommendations": [
        {
            "RecommendationId": "12ab3cde-f456-7g8h-9012-i3j45678k9lm",
            "TypeId": "config_recommendation::rds_extended_support",
            "Severity": "high",
            "ResourceArn": "arn:aws:rds:us-west-2:111122223333:db:database-1",
            "Status": "active",
            "CreatedTime": "2024-02-21T23:14:19.392000+00:00",
            "UpdatedTime": "2024-02-21T23:14:19+00:00",
            "Detection": "Your databases will be auto-enrolled to RDS Extended Support on February 29",
            "Recommendation": "Upgrade your major version before February 29, 2024 to avoid additional charges",
            "Description": "Your PostgreSQL 11 and MySQL 5.7 databases will be automatically enrolled into RDS Extended Support on February 29, 2024. To avoid the increase in charges due to RDS Extended Support, we recommend upgrading your databases to a newer major engine version before February 29, 2024.\nTo learn more about the RDS Extended Support pricing, refer to the pricing page.",
            "RecommendedActions": [
                {
                    "ActionId": "12ab34c5de6fg7h89i0jk1lm234n5678",
                    "Parameters": [],
                    "ApplyModes": [
                        "manual"
                    ],
                    "Status": "ready",
                    "ContextAttributes": []
                }
            ],
            "Category": "cost optimization",
            "Source": "RDS",
            "TypeDetection": "Your database will be auto-enrolled to RDS Extended Support on February 29",
            "TypeRecommendation": "Upgrade your major version before February 29, 2024 to avoid additional charges",
            "Impact": "Increase in charges due to RDS Extended Support",
            "AdditionalInfo": "With Amazon RDS Extended Support, you can continue running your database on a major engine version past the RDS end of standard support date for an additional cost. This paid feature gives you more time to upgrade to a supported major engine version.\nDuring Extended Support, Amazon RDS will supply critical CVE patches and bug fixes.",
            "Links": [
                {
                    "Text": "Amazon RDS Extended Support pricing for RDS for MySQL",
                    "Url": "https://aws.amazon.com/rds/mysql/pricing/"
                },
                {
                    "Text": "Amazon RDS Extended Support for RDS for MySQL and PostgreSQL databases",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/extended-support.html"
                },
                {
                    "Text": "Amazon RDS Extended Support pricing for Amazon Aurora PostgreSQL",
                    "Url": "https://aws.amazon.com/rds/aurora/pricing/"
                },
                {
                    "Text": "Amazon RDS Extended Support for Aurora PostgreSQL databases",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/extended-support.html"
                },
                {
                    "Text": "Amazon RDS Extended Support pricing for RDS for PostgreSQL",
                    "Url": "https://aws.amazon.com/rds/postgresql/pricing/"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/monitoring-recommendations.html)」および「*Amazon Aurora ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/monitoring-recommendations.html)」を参照してください。  
**例 3: 指定された DB インスタンスの DB レコメンデーションを一覧表示するには**  
次の `describe-db-recommendations` の例では、指定された DB インスタンスのすべての DB レコメンデーションを一覧表示します。  

```
aws rds describe-db-recommendations \
    --filters Name=dbi-resource-id,Values=database-1
```
出力:  

```
{
    "DBRecommendations": [
        {
            "RecommendationId": "12ab3cde-f456-7g8h-9012-i3j45678k9lm",
            "TypeId": "config_recommendation::old_minor_version",
            "Severity": "informational",
            "ResourceArn": "arn:aws:rds:us-west-2:111122223333:db:database-1",
            "Status": "active",
            "CreatedTime": "2024-02-21T23:14:19.292000+00:00",
            "UpdatedTime": "2024-02-21T23:14:19+00:00",
            "Detection": "**[resource-name]** is not running the latest minor DB engine version",
            "Recommendation": "Upgrade to latest engine version",
            "Description": "Your database resources aren't running the latest minor DB engine version. The latest minor version contains the latest security fixes and other improvements.",
            "RecommendedActions": [
                {
                    "ActionId": "12ab34c5de6fg7h89i0jk1lm234n5678",
                    "Operation": "modifyDbInstance",
                    "Parameters": [
                        {
                            "Key": "EngineVersion",
                            "Value": "5.7.44"
                        },
                        {
                            "Key": "DBInstanceIdentifier",
                            "Value": "database-1"
                        }
                    ],
                    "ApplyModes": [
                        "immediately",
                        "next-maintenance-window"
                    ],
                    "Status": "ready",
                    "ContextAttributes": [
                        {
                            "Key": "Recommended value",
                            "Value": "5.7.44"
                        },
                        {
                            "Key": "Current engine version",
                            "Value": "5.7.42"
                        }
                    ]
                }
            ],
            "Category": "security",
            "Source": "RDS",
            "TypeDetection": "**[resource-count] resources** are not running the latest minor DB engine version",
            "TypeRecommendation": "Upgrade to latest engine version",
            "Impact": "Reduced database performance and data security at risk",
            "AdditionalInfo": "We recommend that you maintain your database with the latest DB engine minor version as this version includes the latest security and functionality fixes. The DB engine minor version upgrades contain only the changes which are backward-compatible with earlier minor versions of the same major version of the DB engine.",
            "Links": [
                {
                    "Text": "Upgrading an RDS DB instance engine version",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html"
                },
                {
                    "Text": "Using Amazon RDS Blue/Green Deployments for database updates for Amazon Aurora",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments.html"
                },
                {
                    "Text": "Using Amazon RDS Blue/Green Deployments for database updates for Amazon RDS",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments.html"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/monitoring-recommendations.html)」および「*Amazon Aurora ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/monitoring-recommendations.html)」を参照してください。  
**例 4: アクティブな DB レコメンデーションをすべて一覧表示するには**  
次の の`describe-db-recommendations`例では、 AWS アカウント内のすべてのアクティブな DB レコメンデーションを一覧表示します。  

```
aws rds describe-db-recommendations \
    --filters Name=status,Values=active
```
出力:  

```
{
    "DBRecommendations": [
        {
            "RecommendationId": "12ab3cde-f456-7g8h-9012-i3j45678k9lm",
            "TypeId": "config_recommendation::old_minor_version",
            "Severity": "informational",
            "ResourceArn": "arn:aws:rds:us-west-2:111122223333:db:database-1",
            "Status": "active",
            "CreatedTime": "2024-02-21T23:14:19.292000+00:00",
            "UpdatedTime": "2024-02-21T23:14:19+00:00",
            "Detection": "**[resource-name]** is not running the latest minor DB engine version",
            "Recommendation": "Upgrade to latest engine version",
            "Description": "Your database resources aren't running the latest minor DB engine version. The latest minor version contains the latest security fixes and other improvements.",
            "RecommendedActions": [
                {
                    "ActionId": "12ab34c5de6fg7h89i0jk1lm234n5678",
                    "Operation": "modifyDbInstance",
                    "Parameters": [
                        {
                            "Key": "EngineVersion",
                            "Value": "5.7.44"
                        },
                        {
                            "Key": "DBInstanceIdentifier",
                            "Value": "database-1"
                        }
                    ],
                    "ApplyModes": [
                        "immediately",
                        "next-maintenance-window"
                    ],
                    "Status": "ready",
                    "ContextAttributes": [
                        {
                            "Key": "Recommended value",
                            "Value": "5.7.44"
                        },
                        {
                            "Key": "Current engine version",
                            "Value": "5.7.42"
                        }
                    ]
                }
            ],
            "Category": "security",
            "Source": "RDS",
            "TypeDetection": "**[resource-count] resources** are not running the latest minor DB engine version",
            "TypeRecommendation": "Upgrade to latest engine version",
            "Impact": "Reduced database performance and data security at risk",
            "AdditionalInfo": "We recommend that you maintain your database with the latest DB engine minor version as this version includes the latest security and functionality fixes. The DB engine minor version upgrades contain only the changes which are backward-compatible with earlier minor versions of the same major version of the DB engine.",
            "Links": [
                {
                    "Text": "Upgrading an RDS DB instance engine version",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Upgrading.html"
                },
                {
                    "Text": "Using Amazon RDS Blue/Green Deployments for database updates for Amazon Aurora",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments.html"
                },
                {
                    "Text": "Using Amazon RDS Blue/Green Deployments for database updates for Amazon RDS",
                    "Url": "https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments.html"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/monitoring-recommendations.html)」および「*Amazon Aurora ユーザーガイド*」の「[Amazon RDS 推奨事項の表示と対応](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/monitoring-recommendations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbRecommendations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-recommendations.html)」を参照してください。

### `describe-db-security-groups`
<a name="rds_DescribeDbSecurityGroups_cli_2_topic"></a>

次のコード例は、`describe-db-security-groups` を使用する方法を示しています。

**AWS CLI**  
**DB セキュリティグループを一覧表示するには**  
次の `describe-db-security-groups` の例では、DB セキュリティグループを一覧表示します。  

```
aws rds describe-db-security-groups
```
出力:  

```
{
    "DBSecurityGroups": [
        {
            "OwnerId": "123456789012",
            "DBSecurityGroupName": "default",
            "DBSecurityGroupDescription": "default",
            "EC2SecurityGroups": [],
            "IPRanges": [],
            "DBSecurityGroupArn": "arn:aws:rds:us-west-1:111122223333:secgrp:default"
        },
        {
            "OwnerId": "123456789012",
            "DBSecurityGroupName": "mysecgroup",
            "DBSecurityGroupDescription": "My Test Security Group",
            "VpcId": "vpc-1234567f",
            "EC2SecurityGroups": [],
            "IPRanges": [],
            "DBSecurityGroupArn": "arn:aws:rds:us-west-1:111122223333:secgrp:mysecgroup"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[利用可能な DB セキュリティグループを一覧表示する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithSecurityGroups.html#USER_WorkingWithSecurityGroups.Listing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbSecurityGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-security-groups.html)」を参照してください。

### `describe-db-shard-groups`
<a name="rds_DescribeDbShardGroups_cli_2_topic"></a>

次のコード例は、`describe-db-shard-groups` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB シャードグループを記述するには**  
次の `describe-db-shard-groups` の例では、DB シャードグループに関する詳細を取得します。  

```
aws rds describe-db-shard-groups
```
出力:  

```
{
    "DBShardGroups": [
        {
            "DBShardGroupResourceId": "shardgroup-7bb446329da94788b3f957746example",
            "DBShardGroupIdentifier": "limitless-test-shard-grp",
            "DBClusterIdentifier": "limitless-test-cluster",
            "MaxACU": 768.0,
            "ComputeRedundancy": 0,
            "Status": "available",
            "PubliclyAccessible": true,
            "Endpoint": "limitless-test-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        },
        {
            "DBShardGroupResourceId": "shardgroup-a6e3a0226aa243e2ac6c7a1234567890",
            "DBShardGroupIdentifier": "my-db-shard-group",
            "DBClusterIdentifier": "my-sv2-cluster",
            "MaxACU": 768.0,
            "ComputeRedundancy": 0,
            "Status": "available",
            "PubliclyAccessible": false,
            "Endpoint": "my-sv2-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスター](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbShardGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-shard-groups.html)」を参照してください。

### `describe-db-snapshot-attributes`
<a name="rds_DescribeDbSnapshotAttributes_cli_2_topic"></a>

次のコード例は、`describe-db-snapshot-attributes` を使用する方法を示しています。

**AWS CLI**  
**DB スナップショットの属性名と値を記述するには**  
次の `describe-db-snapshot-attributes` の例では、DB スナップショットの属性名と値について説明します。  

```
aws rds describe-db-snapshot-attributes \
    --db-snapshot-identifier mydbsnapshot
```
出力:  

```
{
    "DBSnapshotAttributesResult": {
        "DBSnapshotIdentifier": "mydbsnapshot",
        "DBSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "123456789012",
                    "210987654321"
                ]
            }
        ]
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB スナップショットの共有](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ShareSnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbSnapshotAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-snapshot-attributes.html)」を参照してください。

### `describe-db-snapshots`
<a name="rds_DescribeDBSnapshots_cli_2_topic"></a>

次のコード例は、`describe-db-snapshots` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB インスタンスの DB スナップショットを記述するには**  
次の `describe-db-snapshots` の例は、DB インスタンスの DB スナップショットの詳細を取得します。  

```
aws rds describe-db-snapshots \
    --db-snapshot-identifier mydbsnapshot
```
出力:  

```
{
    "DBSnapshots": [
        {
            "DBSnapshotIdentifier": "mydbsnapshot",
            "DBInstanceIdentifier": "mysqldb",
            "SnapshotCreateTime": "2018-02-08T22:28:08.598Z",
            "Engine": "mysql",
            "AllocatedStorage": 20,
            "Status": "available",
            "Port": 3306,
            "AvailabilityZone": "us-east-1f",
            "VpcId": "vpc-6594f31c",
            "InstanceCreateTime": "2018-02-08T22:24:55.973Z",
            "MasterUsername": "mysqladmin",
            "EngineVersion": "5.6.37",
            "LicenseModel": "general-public-license",
            "SnapshotType": "manual",
            "OptionGroupName": "default:mysql-5-6",
            "PercentProgress": 100,
            "StorageType": "gp2",
            "Encrypted": false,
            "DBSnapshotArn": "arn:aws:rds:us-east-1:123456789012:snapshot:mydbsnapshot",
            "IAMDatabaseAuthenticationEnabled": false,
            "ProcessorFeatures": [],
            "DbiResourceId": "db-AKIAIOSFODNN7EXAMPLE"
        }
    ]
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB スナップショットの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateSnapshot.html)」を参照してください。**  
**例 2: 手動で作成されたスナップショットの数を調べるには**  
次の`describe-db-snapshots`例では、 `--query`オプションの `length`演算子を使用して、特定の AWS リージョンで作成された手動スナップショットの数を返します。  

```
aws rds describe-db-snapshots \
    --snapshot-type manual \
    --query "length(*[].{DBSnapshots:SnapshotType})" \
    --region eu-central-1
```
出力:  

```
35
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB スナップショットの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateSnapshot.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeDBSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-snapshots.html)」を参照してください。**

### `describe-db-subnet-groups`
<a name="rds_DescribeDbSubnetGroups_cli_2_topic"></a>

次のコード例は、`describe-db-subnet-groups` を使用する方法を示しています。

**AWS CLI**  
**DB サブネットグループを記述するには**  
次の `describe-db-subnet-groups` の例では、指定された DB サブネットグループに関する詳細を取得します。  

```
aws rds describe-db-subnet-groups
```
出力:  

```
{
    "DBSubnetGroups": [
        {
            "DBSubnetGroupName": "mydbsubnetgroup",
            "DBSubnetGroupDescription": "My DB Subnet Group",
            "VpcId": "vpc-971c12ee",
            "SubnetGroupStatus": "Complete",
            "Subnets": [
                {
                    "SubnetIdentifier": "subnet-d8c8e7f4",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-718fdc7d",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1f"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-cbc8e7e7",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1a"
                    },
                    "SubnetStatus": "Active"
                },
                {
                    "SubnetIdentifier": "subnet-0ccde220",
                    "SubnetAvailabilityZone": {
                        "Name": "us-east-1a"
                    },
                    "SubnetStatus": "Active"
                }
            ],
            "DBSubnetGroupArn": "arn:aws:rds:us-east-1:123456789012:subgrp:mydbsubnetgroup"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon Virtual Private Cloud VPC および Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDbSubnetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-db-subnet-groups.html)」を参照してください。

### `describe-engine-default-cluster-parameters`
<a name="rds_DescribeEngineDefaultClusterParameters_cli_2_topic"></a>

次のコード例は、`describe-engine-default-cluster-parameters` を使用する方法を示しています。

**AWS CLI**  
**Aurora データベースエンジンのデフォルトのエンジンおよびシステムパラメータ情報を記述するには**  
次の `describe-engine-default-cluster-parameters` の例では、MySQL 5.7 互換の Aurora DB クラスターのデフォルトのエンジンおよびシステムパラメータ情報の詳細を取得します。  

```
aws rds describe-engine-default-cluster-parameters \
    --db-parameter-group-family aurora-mysql5.7
```
出力:  

```
{
    "EngineDefaults": {
        "Parameters": [
            {
                "ParameterName": "aurora_load_from_s3_role",
                "Description": "IAM role ARN used to load data from AWS S3",
                "Source": "engine-default",
                "ApplyType": "dynamic",
                "DataType": "string",
                "IsModifiable": true,
                "SupportedEngineModes": [
                    "provisioned"
                ]
            },
            ...some output truncated...
        ]
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEngineDefaultClusterParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-engine-default-cluster-parameters.html)」を参照してください。

### `describe-engine-default-parameters`
<a name="rds_DescribeEngineDefaultParameters_cli_2_topic"></a>

次のコード例は、`describe-engine-default-parameters` を使用する方法を示しています。

**AWS CLI**  
**データベースエンジンのデフォルトのエンジンおよびシステムパラメータ情報を記述するには**  
次の `describe-engine-default-parameters` の例では、MySQL 5.7 DB インスタンスのデフォルトのエンジンおよびシステムパラメータ情報の詳細を取得します。  

```
aws rds describe-engine-default-parameters \
    --db-parameter-group-family mysql5.7
```
出力:  

```
{
    "EngineDefaults": {
        "Parameters": [
            {
                "ParameterName": "allow-suspicious-udfs",
                "Description": "Controls whether user-defined functions that have only an xxx symbol for the main function can be loaded",
                "Source": "engine-default",
                "ApplyType": "static",
                "DataType": "boolean",
                "AllowedValues": "0,1",
                "IsModifiable": false
            },
            ...some output truncated...
        ]
    }
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB パラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html)」を参照してください。**  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DescribeEngineDefaultParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-engine-default-parameters.html)」を参照してください。

### `describe-event-categories`
<a name="rds_DescribeEventCategories_cli_2_topic"></a>

次のコード例は、`describe-event-categories` を使用する方法を示しています。

**AWS CLI**  
**イベントカテゴリについて表示するには**  
次の `describe-event-categories` の例では、使用可能なすべてのイベントソースのイベントカテゴリの詳細を取得します。  

```
aws rds describe-event-categories
```
出力:  

```
{
    "EventCategoriesMapList": [
        {
            "SourceType": "db-instance",
            "EventCategories": [
                "deletion",
                "read replica",
                "failover",
                "restoration",
                "maintenance",
                "low storage",
                "configuration change",
                "backup",
                "creation",
                "availability",
                "recovery",
                "failure",
                "backtrack",
                "notification"
            ]
        },
        {
            "SourceType": "db-security-group",
            "EventCategories": [
                "configuration change",
                "failure"
            ]
        },
        {
            "SourceType": "db-parameter-group",
            "EventCategories": [
                "configuration change"
            ]
        },
        {
            "SourceType": "db-snapshot",
            "EventCategories": [
                "deletion",
                "creation",
                "restoration",
                "notification"
            ]
        },
        {
            "SourceType": "db-cluster",
            "EventCategories": [
                "failover",
                "failure",
                "notification"
            ]
        },
        {
            "SourceType": "db-cluster-snapshot",
            "EventCategories": [
                "backup"
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventCategories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-event-categories.html)」を参照してください。

### `describe-event-subscriptions`
<a name="rds_DescribeEventSubscriptions_cli_2_topic"></a>

次のコード例は、`describe-event-subscriptions` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを記述するには**  
この例では、現在の AWS アカウントのすべての Amazon RDS イベントサブスクリプションについて説明します。  

```
aws rds describe-event-subscriptions
```
出力:  

```
{
    "EventSubscriptionsList": [
        {
            "EventCategoriesList": [
                "backup",
                "recovery"
            ],
            "Enabled": true,
            "EventSubscriptionArn": "arn:aws:rds:us-east-1:123456789012:es:my-instance-events",
            "Status": "creating",
            "SourceType": "db-instance",
            "CustomerAwsId": "123456789012",
            "SubscriptionCreationTime": "2018-07-31 23:22:01.893",
            "CustSubscriptionId": "my-instance-events",
            "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:interesting-events"
        },
        ...some output truncated...
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventSubscriptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-event-subscriptions.html)」を参照してください。

### `describe-events`
<a name="rds_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
**イベントを記述するには**  
次の `describe-events` の例では、指定した DB インスタンスで発生したイベントの詳細を取得します。  

```
aws rds describe-events \
    --source-identifier test-instance \
    --source-type db-instance
```
出力:  

```
{
    "Events": [
        {
            "SourceType": "db-instance",
            "SourceIdentifier": "test-instance",
            "EventCategories": [
                "backup"
            ],
            "Message": "Backing up DB instance",
            "Date": "2018-07-31T23:09:23.983Z",
            "SourceArn": "arn:aws:rds:us-east-1:123456789012:db:test-instance"
        },
        {
            "SourceType": "db-instance",
            "SourceIdentifier": "test-instance",
            "EventCategories": [
                "backup"
            ],
            "Message": "Finished DB Instance backup",
            "Date": "2018-07-31T23:15:13.049Z",
            "SourceArn": "arn:aws:rds:us-east-1:123456789012:db:test-instance"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-events.html)」を参照してください。

### `describe-export-tasks`
<a name="rds_DescribeExportTasks_cli_2_topic"></a>

次のコード例は、`describe-export-tasks` を使用する方法を示しています。

**AWS CLI**  
**スナップショットエクスポートタスクを記述するには**  
次の `describe-export-tasks` の例では、Amazon S3 へのスナップショットのエクスポートに関する情報を返します。  

```
aws rds describe-export-tasks
```
出力:  

```
{
    "ExportTasks": [
        {
            "ExportTaskIdentifier": "test-snapshot-export",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:snapshot:test-snapshot",
            "SnapshotTime": "2020-03-02T18:26:28.163Z",
            "TaskStartTime": "2020-03-02T18:57:56.896Z",
            "TaskEndTime": "2020-03-02T19:10:31.985Z",
            "S3Bucket": "amzn-s3-demo-bucket",
            "S3Prefix": "",
            "IamRoleArn": "arn:aws:iam::123456789012:role/service-role/ExportRole",
            "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/abcd0000-7fca-4128-82f2-aabbccddeeff",
            "Status": "COMPLETE",
            "PercentProgress": 100,
            "TotalExtractedDataInGB": 0
        },
        {
            "ExportTaskIdentifier": "my-s3-export",
            "SourceArn": "arn:aws:rds:us-west-2:123456789012:snapshot:db5-snapshot-test",
            "SnapshotTime": "2020-03-27T20:48:42.023Z",
            "S3Bucket": "amzn-s3-demo-bucket",
            "S3Prefix": "",
            "IamRoleArn": "arn:aws:iam::123456789012:role/service-role/ExportRole",
            "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/abcd0000-7fca-4128-82f2-aabbccddeeff",
            "Status": "STARTING",
            "PercentProgress": 0,
            "TotalExtractedDataInGB": 0
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[スナップショットのエクスポートのモニタリング](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ExportSnapshot.html#USER_ExportSnapshot.Monitoring)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DescribeExportTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-export-tasks.html)」を参照してください。

### `describe-global-clusters`
<a name="rds_DescribeGlobalClusters_cli_2_topic"></a>

次のコード例は、`describe-global-clusters` を使用する方法を示しています。

**AWS CLI**  
**グローバル DB クラスターを記述するには**  
次の の`describe-global-clusters`例では、現在の AWS リージョンの Aurora グローバル DB クラスターを一覧表示します。  

```
aws rds describe-global-clusters
```
出力:  

```
{
    "GlobalClusters": [
        {
            "GlobalClusterIdentifier": "myglobalcluster",
            "GlobalClusterResourceId": "cluster-f5982077e3b5aabb",
            "GlobalClusterArn": "arn:aws:rds::123456789012:global-cluster:myglobalcluster",
            "Status": "available",
            "Engine": "aurora-mysql",
            "EngineVersion": "5.7.mysql_aurora.2.07.2",
            "StorageEncrypted": false,
            "DeletionProtection": false,
            "GlobalClusterMembers": []
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Aurora グローバルデータベースの管理](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGlobalClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-global-clusters.html)」を参照してください。

### `describe-option-group-options`
<a name="rds_DescribeOptionGroupOptions_cli_2_topic"></a>

次のコード例は、`describe-option-group-options` を使用する方法を示しています。

**AWS CLI**  
**使用可能なすべてのオプションを記述するには**  
次の `describe-option-group-options` の例では、Oracle Database 19c インスタンスの 2 つのオプションを一覧表示します。  

```
aws rds describe-option-group-options \
    --engine-name oracle-ee \
    --major-engine-version 19 \
    --max-items 2
```
出力:  

```
{
    "OptionGroupOptions": [
        {
            "Name": "APEX",
            "Description": "Oracle Application Express Runtime Environment",
            "EngineName": "oracle-ee",
            "MajorEngineVersion": "19",
            "MinimumRequiredMinorEngineVersion": "0.0.0.ru-2019-07.rur-2019-07.r1",
            "PortRequired": false,
            "OptionsDependedOn": [],
            "OptionsConflictsWith": [],
            "Persistent": false,
            "Permanent": false,
            "RequiresAutoMinorEngineVersionUpgrade": false,
            "VpcOnly": false,
            "SupportsOptionVersionDowngrade": false,
            "OptionGroupOptionSettings": [],
            "OptionGroupOptionVersions": [
                {
                    "Version": "19.1.v1",
                    "IsDefault": true
                },
                {
                    "Version": "19.2.v1",
                    "IsDefault": false
                }
            ]
        },
        {
            "Name": "APEX-DEV",
            "Description": "Oracle Application Express Development Environment",
            "EngineName": "oracle-ee",
            "MajorEngineVersion": "19",
            "MinimumRequiredMinorEngineVersion": "0.0.0.ru-2019-07.rur-2019-07.r1",
            "PortRequired": false,
            "OptionsDependedOn": [
                "APEX"
            ],
            "OptionsConflictsWith": [],
            "Persistent": false,
            "Permanent": false,
            "RequiresAutoMinorEngineVersionUpgrade": false,
            "VpcOnly": false,
            "OptionGroupOptionSettings": []
        }
    ],
    "NextToken": "eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ=="
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[オプショングループのオプションとそれらの設定を一覧表示する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithOptionGroups.html#USER_WorkingWithOptionGroups.ListOption)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOptionGroupOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-option-group-options.html)」を参照してください。

### `describe-option-groups`
<a name="rds_DescribeOptionGroups_cli_2_topic"></a>

次のコード例は、`describe-option-groups` を使用する方法を示しています。

**AWS CLI**  
**使用可能なオプショングループの説明を表示するには**  
次の `describe-option-groups` の例では、Oracle Database 19c インスタンスのオプショングループを一覧表示します。  

```
aws rds describe-option-groups \
    --engine-name oracle-ee \
    --major-engine-version 19
```
出力:  

```
{
    "OptionGroupsList": [
        {
            "OptionGroupName": "default:oracle-ee-19",
            "OptionGroupDescription": "Default option group for oracle-ee 19",
            "EngineName": "oracle-ee",
            "MajorEngineVersion": "19",
            "Options": [],
            "AllowsVpcAndNonVpcInstanceMemberships": true,
            "OptionGroupArn": "arn:aws:rds:us-west-1:111122223333:og:default:oracle-ee-19"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[オプショングループのオプションとそれらの設定を一覧表示する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithOptionGroups.html#USER_WorkingWithOptionGroups.ListOption)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOptionGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-option-groups.html)」を参照してください。

### `describe-orderable-db-instance-options`
<a name="rds_DescribeOrderableDBInstanceOptions_cli_2_topic"></a>

次のコード例は、`describe-orderable-db-instance-options` を使用する方法を示しています。

**AWS CLI**  
**順序設定可能な DB インスタンスオプションを記述するには**  
次の `describe-orderable-db-instance-options` の例は、MySQL DB エンジンを実行する DB インスタンスの順序設定可能なオプションの詳細を取得します。  

```
aws rds describe-orderable-db-instance-options \
    --engine mysql
```
出力:  

```
{
    "OrderableDBInstanceOptions": [
        {
            "MinStorageSize": 5,
            "ReadReplicaCapable": true,
            "MaxStorageSize": 6144,
            "AvailabilityZones": [
                {
                    "Name": "us-east-1a"
                },
                {
                    "Name": "us-east-1b"
                },
                {
                    "Name": "us-east-1c"
                },
                {
                    "Name": "us-east-1d"
                }
            ],
            "SupportsIops": false,
            "AvailableProcessorFeatures": [],
            "MultiAZCapable": true,
            "DBInstanceClass": "db.m1.large",
            "Vpc": true,
            "StorageType": "gp2",
            "LicenseModel": "general-public-license",
            "EngineVersion": "5.5.46",
            "SupportsStorageEncryption": false,
            "SupportsEnhancedMonitoring": true,
            "Engine": "mysql",
            "SupportsIAMDatabaseAuthentication": false,
            "SupportsPerformanceInsights": false
        }
    ]
    ...some output truncated...
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeOrderableDBInstanceOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-orderable-db-instance-options.html)」を参照してください。**

### `describe-pending-maintenance-actions`
<a name="rds_DescribePendingMaintenanceActions_cli_2_topic"></a>

次のコード例は、`describe-pending-maintenance-actions` を使用する方法を示しています。

**AWS CLI**  
**少なくとも 1 つの保留中のメンテナンスアクションを持つリソースを一覧表示するには**  
次の `describe-pending-maintenance-actions` の例では、DB インスタンスの保留中のメンテナンスアクションを一覧表示します。  

```
aws rds describe-pending-maintenance-actions
```
出力:  

```
{
    "PendingMaintenanceActions": [
        {
            "ResourceIdentifier": "arn:aws:rds:us-west-2:123456789012:cluster:global-db1-cl1",
            "PendingMaintenanceActionDetails": [
                {
                    "Action": "system-update",
                    "Description": "Upgrade to Aurora PostgreSQL 2.4.2"
                }
            ]
        }
    ]
}
```
詳細については、「[Amazon RDS ユーザーガイド](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Maintenance.html)」の「*DB インスタンスのメンテナンス*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePendingMaintenanceActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-pending-maintenance-actions.html)」を参照してください。

### `describe-reserved-db-instances-offerings`
<a name="rds_DescribeReservedDbInstancesOfferings_cli_2_topic"></a>

次のコード例は、`describe-reserved-db-instances-offerings` を使用する方法を示しています。

**AWS CLI**  
**リザーブド DB インスタンスの提供を記述するには**  
次の `describe-reserved-db-instances-offerings` の例では、`oracle` のリザーブド DB インスタンスオプションの詳細を取得します。  

```
aws rds describe-reserved-db-instances-offerings \
    --product-description oracle
```
出力:  

```
{
    "ReservedDBInstancesOfferings": [
        {
            "CurrencyCode": "USD",
            "UsagePrice": 0.0,
            "ProductDescription": "oracle-se2(li)",
            "ReservedDBInstancesOfferingId": "005bdee3-9ef4-4182-aa0c-58ef7cb6c2f8",
            "MultiAZ": true,
            "DBInstanceClass": "db.m4.xlarge",
            "OfferingType": "Partial Upfront",
            "RecurringCharges": [
                {
                    "RecurringChargeAmount": 0.594,
                    "RecurringChargeFrequency": "Hourly"
                }
            ],
            "FixedPrice": 4089.0,
            "Duration": 31536000
        },
    ...some output truncated...
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedDbInstancesOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-reserved-db-instances-offerings.html)」を参照してください。

### `describe-reserved-db-instances`
<a name="rds_DescribeReservedDbInstances_cli_2_topic"></a>

次のコード例は、`describe-reserved-db-instances` を使用する方法を示しています。

**AWS CLI**  
**リザーブド DB インスタンスを記述するには**  
次の の`describe-reserved-db-instances`例では、現在の AWS アカウントのリザーブド DB インスタンスの詳細を取得します。  

```
aws rds describe-reserved-db-instances
```
出力:  

```
{
    "ReservedDBInstances": [
        {
            "ReservedDBInstanceId": "myreservedinstance",
            "ReservedDBInstancesOfferingId": "12ab34cd-59af-4b2c-a660-1abcdef23456",
            "DBInstanceClass": "db.t3.micro",
            "StartTime": "2020-06-01T13:44:21.436Z",
            "Duration": 31536000,
            "FixedPrice": 0.0,
            "UsagePrice": 0.0,
            "CurrencyCode": "USD",
            "DBInstanceCount": 1,
            "ProductDescription": "sqlserver-ex(li)",
            "OfferingType": "No Upfront",
            "MultiAZ": false,
            "State": "payment-pending",
            "RecurringCharges": [
                {
                    "RecurringChargeAmount": 0.014,
                    "RecurringChargeFrequency": "Hourly"
                }
            ],
            "ReservedDBInstanceArn": "arn:aws:rds:us-west-2:123456789012:ri:myreservedinstance",
            "LeaseId": "a1b2c3d4-6b69-4a59-be89-5e11aa446666"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS のリザーブド DB インスタンス](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithReservedDBInstances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedDbInstances](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-reserved-db-instances.html)」を参照してください。

### `describe-source-regions`
<a name="rds_DescribeSourceRegions_cli_2_topic"></a>

次のコード例は、`describe-source-regions` を使用する方法を示しています。

**AWS CLI**  
**ソースリージョンを記述するには**  
次の の`describe-source-regions`例では、すべてのソース AWS リージョンの詳細を取得します。また、自動バックアップは米国西部 (オレゴン) から送信先 AWS リージョンである米国東部 (バージニア北部) にのみレプリケートできることを示しています。  

```
aws rds describe-source-regions \
    --region us-east-1
```
出力:  

```
{
    "SourceRegions": [
        {
            "RegionName": "af-south-1",
            "Endpoint": "https://rds.af-south-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": false
        },
        {
            "RegionName": "ap-east-1",
            "Endpoint": "https://rds.ap-east-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": false
        },
        {
            "RegionName": "ap-northeast-1",
            "Endpoint": "https://rds.ap-northeast-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "ap-northeast-2",
            "Endpoint": "https://rds.ap-northeast-2.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "ap-northeast-3",
            "Endpoint": "https://rds.ap-northeast-3.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": false
        },
        {
            "RegionName": "ap-south-1",
            "Endpoint": "https://rds.ap-south-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "ap-southeast-1",
            "Endpoint": "https://rds.ap-southeast-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "ap-southeast-2",
            "Endpoint": "https://rds.ap-southeast-2.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "ap-southeast-3",
            "Endpoint": "https://rds.ap-southeast-3.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": false
        },
        {
            "RegionName": "ca-central-1",
            "Endpoint": "https://rds.ca-central-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "eu-north-1",
            "Endpoint": "https://rds.eu-north-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "eu-south-1",
            "Endpoint": "https://rds.eu-south-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": false
        },
        {
            "RegionName": "eu-west-1",
            "Endpoint": "https://rds.eu-west-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "eu-west-2",
            "Endpoint": "https://rds.eu-west-2.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "eu-west-3",
            "Endpoint": "https://rds.eu-west-3.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "me-central-1",
             "Endpoint": "https://rds.me-central-1.amazonaws.com",
             "Status": "available",
             "SupportsDBInstanceAutomatedBackupsReplication": false
        },
        {
            "RegionName": "me-south-1",
            "Endpoint": "https://rds.me-south-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": false
        },
        {
            "RegionName": "sa-east-1",
            "Endpoint": "https://rds.sa-east-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "us-east-2",
            "Endpoint": "https://rds.us-east-2.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "us-west-1",
            "Endpoint": "https://rds.us-west-1.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        },
        {
            "RegionName": "us-west-2",
           "Endpoint": "https://rds.us-west-2.amazonaws.com",
            "Status": "available",
            "SupportsDBInstanceAutomatedBackupsReplication": true
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[レプリケーションされたバックアップに関する情報の検索](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReplicateBackups.html#AutomatedBackups.Replicating.Describe)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSourceRegions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-source-regions.html)」を参照してください。

### `describe-valid-db-instance-modifications`
<a name="rds_DescribeValidDbInstanceModifications_cli_2_topic"></a>

次のコード例は、`describe-valid-db-instance-modifications` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスの有効な変更を記述するには**  
次の `describe-valid-db-instance-modifications` の例は、指定された DB インスタンスの有効な変更に関する詳細を取得します。  

```
aws rds describe-valid-db-instance-modifications \
    --db-instance-identifier test-instance
```
出力:  

```
{
    "ValidDBInstanceModificationsMessage": {
        "ValidProcessorFeatures": [],
        "Storage": [
            {
                "StorageSize": [
                    {
                        "Step": 1,
                        "To": 20,
                        "From": 20
                    },
                    {
                        "Step": 1,
                        "To": 6144,
                        "From": 22
                    }
                ],
                "ProvisionedIops": [
                    {
                        "Step": 1,
                        "To": 0,
                        "From": 0
                    }
                ],
                "IopsToStorageRatio": [
                    {
                        "To": 0.0,
                        "From": 0.0
                    }
                ],
                "StorageType": "gp2"
            },
            {
                "StorageSize": [
                    {
                        "Step": 1,
                        "To": 6144,
                        "From": 100
                    }
                ],
                "ProvisionedIops": [
                    {
                        "Step": 1,
                        "To": 40000,
                        "From": 1000
                    }
                ],
                "IopsToStorageRatio": [
                    {
                        "To": 50.0,
                        "From": 1.0
                    }
                ],
                "StorageType": "io1"
            },
            {
                "StorageSize": [
                    {
                        "Step": 1,
                        "To": 20,
                        "From": 20
                    },
                    {
                        "Step": 1,
                        "To": 3072,
                        "From": 22
                    }
                ],
                "ProvisionedIops": [
                    {
                        "Step": 1,
                        "To": 0,
                        "From": 0
                    }
                ],
                "IopsToStorageRatio": [
                    {
                        "To": 0.0,
                        "From": 0.0
                    }
                ],
                "StorageType": "magnetic"
            }
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeValidDbInstanceModifications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/describe-valid-db-instance-modifications.html)」を参照してください。

### `download-db-log-file-portion`
<a name="rds_DownloadDbLogFilePortion_cli_2_topic"></a>

次のコード例は、`download-db-log-file-portion` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB ログファイルの最新部分をダウンロードするには**  
次の `download-db-log-file-portion` の例では、ログファイルの最新の部分のみをダウンロードし、`tail.txt` という名前のローカルファイルに保存します。  

```
aws rds download-db-log-file-portion \
    --db-instance-identifier test-instance \
    --log-file-name log.txt \
    --output text > tail.txt
```
保存されたファイルには空白行が含まれている場合があります。ダウンロード中にログファイルの各部分の最後に表示されます。  
**例 2: DB ログファイル全体をダウンロードするには**  
次の `download-db-log-file-portion` の例では、`--starting-token 0` パラメータを使用してログファイル全体をダウンロードし、出力を `full.txt` という名前のローカルファイルに保存します。  

```
aws rds download-db-log-file-portion \
    --db-instance-identifier test-instance \
    --log-file-name log.txt \
    --starting-token 0 \
    --output text > full.txt
```
保存されたファイルには空白行が含まれている場合があります。ダウンロード中にログファイルの各部分の最後に表示されます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DownloadDbLogFilePortion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/download-db-log-file-portion.html)」を参照してください。

### `generate-auth-token`
<a name="rds_GenerateAuthToken_cli_2_topic"></a>

次のコード例は、`generate-auth-token` を使用する方法を示しています。

**AWS CLI**  
**認証トークンを生成するには**  
次の `generate-db-auth-token` の例では、IAM データベース認証で使用する認証トークンを生成します。  

```
aws rds generate-db-auth-token \
    --hostname aurmysql-test.cdgmuqiadpid.us-west-2.rds.amazonaws.com \
    --port 3306 \
    --region us-east-1 \
    --username jane_doe
```
出力:  

```
aurmysql-test.cdgmuqiadpid.us-west-2.rds.amazonaws.com:3306/?Action=connect&DBUser=jane_doe&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIESZCNJ3OEXAMPLE%2F20180731%2Fus-east-1%2Frds-db%2Faws4_request&X-Amz-Date=20180731T235209Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=5a8753ebEXAMPLEa2c724e5667797EXAMPLE9d6ec6e3f427191fa41aeEXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateAuthToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/generate-auth-token.html)」を参照してください。

### `generate-db-auth-token`
<a name="rds_GenerateDbAuthToken_cli_2_topic"></a>

次のコード例は、`generate-db-auth-token` を使用する方法を示しています。

**AWS CLI**  
**IAM 認証トークンを生成するには**  
次の `generate-db-auth-token` の例では、IAM 認証トークンを生成してデータベースに接続します。  

```
aws rds generate-db-auth-token \
    --hostname mydb.123456789012.us-east-1.rds.amazonaws.com \
    --port 3306 \
    --region us-east-1 \
    --username db_user
```
出力:  

```
mydb.123456789012.us-east-1.rds.amazonaws.com:3306/?Action=connect&DBUser=db_user&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIEXAMPLE%2Fus-east-1%2Frds-db%2Faws4_request&X-Amz-Date=20210123T011543Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=88987EXAMPLE1EXAMPLE2EXAMPLE3EXAMPLE4EXAMPLE5EXAMPLE6
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[IAM 認証を使用した DB インスタンスへの接続](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Connecting.html)」および「*Amazon Aurora ユーザーガイド*」の「[IAM 認証を使用した DB クラスターへの接続](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/UsingWithRDS.IAMDBAuth.Connecting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GenerateDbAuthToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/generate-db-auth-token.html)」を参照してください。

### `list-tags-for-resource`
<a name="rds_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**Amazon RDS リソースのすべてのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、DB インスタンスのすべてのタグを一覧表示します。  

```
aws rds list-tags-for-resource \
    --resource-name arn:aws:rds:us-east-1:123456789012:db:orcl1
```
出力:  

```
{
    "TagList": [
        {
            "Key": "Environment",
            "Value": "test"
        },
        {
            "Key": "Name",
            "Value": "MyDatabase"
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS リソースのタグ付け](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/list-tags-for-resource.html)」を参照してください。

### `modify-certificates`
<a name="rds_ModifyCertificates_cli_2_topic"></a>

次のコード例は、`modify-certificates` を使用する方法を示しています。

**AWS CLI**  
**新しい DB インスタンスのシステムデフォルト SSL/TLS 証明書を一時的に上書きするには**  
次の `modify-certificates` の例では、新しい DB インスタンスのシステムデフォルト SSL/TLS 証明書を一時的に上書きします。  

```
aws rds modify-certificates \
    --certificate-identifier rds-ca-2019
```
出力:  

```
{
    "Certificate": {
        "CertificateIdentifier": "rds-ca-2019",
        "CertificateType": "CA",
        "Thumbprint": "EXAMPLE123456789012",
        "ValidFrom": "2019-09-19T18:16:53Z",
        "ValidTill": "2024-08-22T17:08:50Z",
        "CertificateArn": "arn:aws:rds:us-east-1::cert:rds-ca-2019",
        "CustomerOverride": true,
        "CustomerOverrideValidTill": "2024-08-22T17:08:50Z"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[SSL/TLS 証明書のローテーション](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL-certificate-rotation.html)」および「*Amazon Aurora ユーザーガイド*」の「[SSL/TLS 証明書のローテーション](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/UsingWithRDS.SSL-certificate-rotation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-certificates.html)」を参照してください。

### `modify-current-db-cluster-capacity`
<a name="rds_ModifyCurrentDbClusterCapacity_cli_2_topic"></a>

次のコード例は、`modify-current-db-cluster-capacity` を使用する方法を示しています。

**AWS CLI**  
**Aurora Serverless DB クラスターの容量を拡張するには**  
次の `modify-current-db-cluster-capacity` の例では、Aurora Serverless DB クラスターの容量を 8 にスケーリングします。  

```
aws rds modify-current-db-cluster-capacity \
    --db-cluster-identifier mydbcluster \
    --capacity 8
```
出力:  

```
{
    "DBClusterIdentifier": "mydbcluster",
    "PendingCapacity": 8,
    "CurrentCapacity": 1,
    "SecondsBeforeTimeout": 300,
    "TimeoutAction": "ForceApplyCapacityChange"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Aurora Serverless v1 DB クラスターのキャパシティーを手動でスケーリングする](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-serverless.setting-capacity.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyCurrentDbClusterCapacity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-current-db-cluster-capacity.html)」を参照してください。

### `modify-db-cluster-endpoint`
<a name="rds_ModifyDbClusterEndpoint_cli_2_topic"></a>

次のコード例は、`modify-db-cluster-endpoint` を使用する方法を示しています。

**AWS CLI**  
**カスタム DB クラスターエンドポイントを変更するには**  
次の `modify-db-cluster-endpoint` の例では、指定されたカスタム DB クラスターエンドポイントを変更します。  

```
aws rds modify-db-cluster-endpoint \
    --db-cluster-endpoint-identifier mycustomendpoint \
    --static-members dbinstance1 dbinstance2 dbinstance3
```
出力:  

```
{
    "DBClusterEndpointIdentifier": "mycustomendpoint",
    "DBClusterIdentifier": "mydbcluster",
    "DBClusterEndpointResourceIdentifier": "cluster-endpoint-ANPAJ4AE5446DAEXAMPLE",
    "Endpoint": "mycustomendpoint.cluster-custom-cnpexample.us-east-1.rds.amazonaws.com",
    "Status": "modifying",
    "EndpointType": "CUSTOM",
    "CustomEndpointType": "READER",
    "StaticMembers": [
        "dbinstance1",
        "dbinstance2",
        "dbinstance3"
    ],
    "ExcludedMembers": [],
    "DBClusterEndpointArn": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:mycustomendpoint"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora 接続管理](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.Endpoints.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbClusterEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-cluster-endpoint.html)」を参照してください。

### `modify-db-cluster-parameter-group`
<a name="rds_ModifyDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`modify-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターパラメータグループのパラメータを変更するには**  
次の `modify-db-cluster-parameter-group` の例は、DB クラスターパラメータのパラメータの値を変更します。  

```
aws rds modify-db-cluster-parameter-group \
    --db-cluster-parameter-group-name mydbclusterpg \
    --parameters "ParameterName=server_audit_logging,ParameterValue=1,ApplyMethod=immediate" \
                 "ParameterName=server_audit_logs_upload,ParameterValue=1,ApplyMethod=immediate"
```
出力:  

```
{
    "DBClusterParameterGroupName": "mydbclusterpg"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-cluster-parameter-group.html)」を参照してください。

### `modify-db-cluster-snapshot-attribute`
<a name="rds_ModifyDbClusterSnapshotAttribute_cli_2_topic"></a>

次のコード例は、`modify-db-cluster-snapshot-attribute` を使用する方法を示しています。

**AWS CLI**  
**DB クラスタースナップショット属性を変更するには**  
次の `modify-db-cluster-snapshot-attribute` の例では、指定された DB クラスタースナップショット属性を変更します。  

```
aws rds modify-db-cluster-snapshot-attribute \
    --db-cluster-snapshot-identifier myclustersnapshot \
    --attribute-name restore \
    --values-to-add 123456789012
```
出力:  

```
{
    "DBClusterSnapshotAttributesResult": {
        "DBClusterSnapshotIdentifier": "myclustersnapshot",
        "DBClusterSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "123456789012"
                ]
            }
        ]
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスターのスナップショットからの復元](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_RestoreFromSnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbClusterSnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-cluster-snapshot-attribute.html)」を参照してください。

### `modify-db-cluster`
<a name="rds_ModifyDbCluster_cli_2_topic"></a>

次のコード例は、`modify-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB クラスターを変更するには**  
次の `modify-db-cluster` の例では、`cluster-2` という名前の DB クラスターのマスターユーザーパスワードを変更し、バックアップ保持期間を 14 日間に設定します。`--apply-immediately` パラメータを使用することで、次のメンテナンスウィンドウを待つことなく、すぐに変更することができます。  

```
aws rds modify-db-cluster \
    --db-cluster-identifier cluster-2 \
    --backup-retention-period 14 \
    --master-user-password newpassword99 \
    --apply-immediately
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "eu-central-1b",
            "eu-central-1c",
            "eu-central-1a"
        ],
        "BackupRetentionPeriod": 14,
        "DatabaseName": "",
        "DBClusterIdentifier": "cluster-2",
        "DBClusterParameterGroup": "default.aurora5.6",
        "DBSubnetGroup": "default-vpc-2305ca49",
        "Status": "available",
        "EarliestRestorableTime": "2020-06-03T02:07:29.637Z",
        "Endpoint": "cluster-2.cluster-############.eu-central-1.rds.amazonaws.com",
        "ReaderEndpoint": "cluster-2.cluster-ro-############.eu-central-1.rds.amazonaws.com",
        "MultiAZ": false,
        "Engine": "aurora",
        "EngineVersion": "5.6.10a",
        "LatestRestorableTime": "2020-06-04T15:11:25.748Z",
        "Port": 3306,
        "MasterUsername": "admin",
        "PreferredBackupWindow": "01:55-02:25",
        "PreferredMaintenanceWindow": "thu:21:14-thu:21:44",
        "ReadReplicaIdentifiers": [],
        "DBClusterMembers": [
            {
                "DBInstanceIdentifier": "cluster-2-instance-1",
                "IsClusterWriter": true,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            }
        ],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-20a5c047",
                "Status": "active"
            }
        ],
        "HostedZoneId": "Z1RLNU0EXAMPLE",
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:eu-central-1:123456789012:key/d1bd7c8f-5cdb-49ca-8a62-a1b2c3d4e5f6",
        "DbClusterResourceId": "cluster-AGJ7XI77XVIS6FUXHU1EXAMPLE",
        "DBClusterArn": "arn:aws:rds:eu-central-1:123456789012:cluster:cluster-2",
        "AssociatedRoles": [],
        "IAMDatabaseAuthenticationEnabled": false,
        "ClusterCreateTime": "2020-04-03T14:44:02.764Z",
        "EngineMode": "provisioned",
        "DeletionProtection": false,
        "HttpEndpointEnabled": false,
        "CopyTagsToSnapshot": true,
        "CrossAccountClone": false,
        "DomainMemberships": []
    }
}
```
詳細については、[Amazon Aurora ユーザーガイド](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Modifying.html)の「*Amazon Aurora DB クラスターの変更*」を参照してください。  
**例 2: VPC セキュリティグループを DB クラスターと関連付けるには**  
次の `modify-db-instance` の例では、特定の VPC セキュリティグループを関連付け、DB クラスターから DB セキュリティグループを削除します。  

```
aws rds modify-db-cluster \
    --db-cluster-identifier dbName \
    --vpc-security-group-ids sg-ID
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-west-2c",
            "us-west-2b",
            "us-west-2a"
        ],
        "BackupRetentionPeriod": 1,
        "DBClusterIdentifier": "dbName",
        "DBClusterParameterGroup": "default.aurora-mysql8.0",
        "DBSubnetGroup": "default",
        "Status": "available",
        "EarliestRestorableTime": "2024-02-15T01:12:13.966000+00:00",
        "Endpoint": "dbName.cluster-abcdefghji.us-west-2.rds.amazonaws.com",
        "ReaderEndpoint": "dbName.cluster-ro-abcdefghji.us-west-2.rds.amazonaws.com",
        "MultiAZ": false,
        "Engine": "aurora-mysql",
        "EngineVersion": "8.0.mysql_aurora.3.04.1",
        "LatestRestorableTime": "2024-02-15T02:25:33.696000+00:00",
        "Port": 3306,
        "MasterUsername": "admin",
        "PreferredBackupWindow": "10:59-11:29",
        "PreferredMaintenanceWindow": "thu:08:54-thu:09:24",
        "ReadReplicaIdentifiers": [],
        "DBClusterMembers": [
            {
                "DBInstanceIdentifier": "dbName-instance-1",
                "IsClusterWriter": true,
                "DBClusterParameterGroupStatus": "in-sync",
                "PromotionTier": 1
            }
        ],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-ID",
                "Status": "active"
            }
        ],
        ...output omitted...
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[セキュリティグループによるアクセス制御](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Overview.RDSSecurityGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-cluster.html)」を参照してください。

### `modify-db-instance`
<a name="rds_ModifyDBInstance_cli_2_topic"></a>

次のコード例は、`modify-db-instance` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB インスタンスを変更するには**  
次の `modify-db-instance` の例は、オプショングループとパラメータグループを互換性のある Microsoft SQL Server DB インスタンスに関連付けます。`--apply-immediately` パラメータを使用することで、次のメンテナンスウィンドウを待つことなく、オプショングループとパラメータグループをすぐに関連付けることができます。  

```
aws rds modify-db-instance \
    --db-instance-identifier database-2 \
    --option-group-name test-se-2017 \
    --db-parameter-group-name test-sqlserver-se-2017 \
    --apply-immediately
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "database-2",
        "DBInstanceClass": "db.r4.large",
        "Engine": "sqlserver-se",
        "DBInstanceStatus": "available",

        ...output omitted...

        "DBParameterGroups": [
            {
                "DBParameterGroupName": "test-sqlserver-se-2017",
                "ParameterApplyStatus": "applying"
            }
        ],
        "AvailabilityZone": "us-west-2d",

        ...output omitted...

        "MultiAZ": true,
        "EngineVersion": "14.00.3281.6.v1",
        "AutoMinorVersionUpgrade": false,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "license-included",
        "OptionGroupMemberships": [
            {
                "OptionGroupName": "test-se-2017",
                "Status": "pending-apply"
            }
        ],
        "CharacterSetName": "SQL_Latin1_General_CP1_CI_AS",
        "SecondaryAvailabilityZone": "us-west-2c",
        "PubliclyAccessible": true,
        "StorageType": "gp2",

        ...output omitted...

        "DeletionProtection": false,
        "AssociatedRoles": [],
        "MaxAllocatedStorage": 1000
    }
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[Amazon RDS DB インスタンスを変更する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.Modifying.html)」を参照してください。**  
**例 2: VPC セキュリティグループを DB インスタンスと関連付けるには**  
次の `modify-db-instance` の例では、特定の VPC セキュリティグループを関連付け、DB インスタンスから DB セキュリティグループを削除します。  

```
aws rds modify-db-instance \
    --db-instance-identifier dbName \
    --vpc-security-group-ids sg-ID
```
出力:  

```
{
"DBInstance": {
    "DBInstanceIdentifier": "dbName",
    "DBInstanceClass": "db.t3.micro",
    "Engine": "mysql",
    "DBInstanceStatus": "available",
    "MasterUsername": "admin",
    "Endpoint": {
        "Address": "dbName.abcdefghijk.us-west-2.rds.amazonaws.com",
        "Port": 3306,
        "HostedZoneId": "ABCDEFGHIJK1234"
    },
    "AllocatedStorage": 20,
    "InstanceCreateTime": "2024-02-15T00:37:58.793000+00:00",
    "PreferredBackupWindow": "11:57-12:27",
    "BackupRetentionPeriod": 7,
    "DBSecurityGroups": [],
    "VpcSecurityGroups": [
        {
            "VpcSecurityGroupId": "sg-ID",
            "Status": "active"
        }
    ],
    ... output omitted ...
    "MultiAZ": false,
    "EngineVersion": "8.0.35",
    "AutoMinorVersionUpgrade": true,
    "ReadReplicaDBInstanceIdentifiers": [],
    "LicenseModel": "general-public-license",

    ... output omitted ...
    }
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[セキュリティグループによるアクセス制御](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSSecurityGroups.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[ModifyDBInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-instance.html)」を参照してください。

### `modify-db-parameter-group`
<a name="rds_ModifyDBParameterGroup_cli_2_topic"></a>

次のコード例は、`modify-db-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**DB パラメータグループを変更するには**  
次の `modify-db-parameter-group` の例は、DB パラメータグループの `clr enabled` パラメータの値を変更します。`--apply-immediately` パラメータを使用することで、次のメンテナンスウィンドウを待つことなく、DB パラメータグループをすぐに変更することができます。  

```
aws rds modify-db-parameter-group \
    --db-parameter-group-name test-sqlserver-se-2017 \
    --parameters "ParameterName='clr enabled',ParameterValue=1,ApplyMethod=immediate"
```
出力:  

```
{
    "DBParameterGroupName": "test-sqlserver-se-2017"
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB パラメータグループのパラメータの変更](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html#USER_WorkingWithParamGroups.Modifying)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス** の「[ModifyDBParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-parameter-group.html)」を参照してください。

### `modify-db-proxy-endpoint`
<a name="rds_ModifyDbProxyEndpoint_cli_2_topic"></a>

次のコード例は、`modify-db-proxy-endpoint` を使用する方法を示しています。

**AWS CLI**  
**RDS データベースの DB プロキシエンドポイントを変更するには**  
次の `modify-db-proxy-endpoint` の例では、DB プロキシエンドポイント `proxyEndpoint` を変更して、読み取りタイムアウトを 65 秒に設定します。  

```
aws rds modify-db-proxy-endpoint \
    --db-proxy-endpoint-name proxyEndpoint \
    --cli-read-timeout 65
```
出力:  

```
{
"DBProxyEndpoint":
    {
        "DBProxyEndpointName": "proxyEndpoint",
        "DBProxyEndpointArn": "arn:aws:rds:us-east-1:123456789012:db-proxy-endpoint:prx-endpoint-0123a01b12345c0ab",
        "DBProxyName": "proxyExample",
        "Status": "available",
        "VpcId": "vpc-1234567",
        "VpcSecurityGroupIds": [
            "sg-1234"
        ],
        "VpcSubnetIds": [
            "subnetgroup1",
            "subnetgroup2"
        ],
        "Endpoint": "proxyEndpoint.endpoint.proxyExample-ab0cd1efghij.us-east-1.rds.amazonaws.com",
        "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
        "TargetRole": "READ_WRITE",
        "IsDefault": "false"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[プロキシエンドポイントの変更](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.ModifyingEndpoint)」および「*Amazon Aurora ユーザーガイド*」の「[プロキシエンドポイントの変更](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-endpoints.html#rds-proxy-endpoints.ModifyingEndpoint)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbProxyEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-proxy-endpoint.html)」を参照してください。

### `modify-db-proxy-target-group`
<a name="rds_ModifyDbProxyTargetGroup_cli_2_topic"></a>

次のコード例は、`modify-db-proxy-target-group` を使用する方法を示しています。

**AWS CLI**  
**DB プロキシエンドポイントを変更するには**  
次の `modify-db-proxy-target-group` の例では、DB プロキシターゲットグループを変更して、最大接続数を 80%、最大アイドル接続数を 10% に設定します。  

```
aws rds modify-db-proxy-target-group \
    --target-group-name default \
    --db-proxy-name proxyExample \
    --connection-pool-config MaxConnectionsPercent=80,MaxIdleConnectionsPercent=10
```
出力:  

```
{
"DBProxyTargetGroup":
    {
        "DBProxyName": "proxyExample",
        "TargetGroupName": "default",
        "TargetGroupArn": "arn:aws:rds:us-east-1:123456789012:target-group:prx-tg-0123a01b12345c0ab",
        "IsDefault": true,
        "Status": "available",
        "ConnectionPoolConfig": {
            "MaxConnectionsPercent": 80,
            "MaxIdleConnectionsPercent": 10,
            "ConnectionBorrowTimeout": 120,
            "SessionPinningFilters": []
        },
        "CreatedDate": "2023-05-02T18:41:19.495000+00:00",
        "UpdatedDate": "2023-05-02T18:41:21.762000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの変更](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-managing.html#rds-proxy-modifying-proxy)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの変更](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-managing.html#rds-proxy-modifying-proxy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbProxyTargetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-proxy-target-group.html)」を参照してください。

### `modify-db-proxy`
<a name="rds_ModifyDbProxy_cli_2_topic"></a>

次のコード例は、`modify-db-proxy` を使用する方法を示しています。

**AWS CLI**  
**RDS データベースの DB プロキシを変更するには**  
次の `modify-db-proxy` の例では、`proxyExample` という名前の DB プロキシを変更して、接続に SSL を要求するようにしています。  

```
aws rds modify-db-proxy \
    --db-proxy-name proxyExample \
    --require-tls
```
出力:  

```
{
"DBProxy":
    {
        "DBProxyName": "proxyExample",
        "DBProxyArn": "arn:aws:rds:us-east-1:123456789012:db-proxy:prx-0123a01b12345c0ab",
        "Status": "modifying"
        "EngineFamily": "PostgreSQL",
        "VpcId": "sg-1234567",
        "VpcSecurityGroupIds": [
            "sg-1234"
        ],
        "VpcSubnetIds": [
            "subnetgroup1",
            "subnetgroup2"
        ],
        "Auth": "[
            {
                "Description": "proxydescription1",
                "AuthScheme": "SECRETS",
                "SecretArn": "arn:aws:secretsmanager:us-west-2:123456789123:secret:proxysecret1-Abcd1e",
                "IAMAuth": "DISABLED"
            }
        ]",
        "RoleArn": "arn:aws:iam::12345678912:role/ProxyPostgreSQLRole",
        "Endpoint": "proxyExample.proxy-ab0cd1efghij.us-east-1.rds.amazonaws.com",
        "RequireTLS": true,
        "IdleClientTimeout": 1800,
        "DebuggingLogging": false,
        "CreatedDate": "2023-04-05T16:09:33.452000+00:00",
        "UpdatedDate": "2023-04-13T01:49:38.568000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの変更](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-managing.html#rds-proxy-modifying-proxy)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-managing.html#rds-proxy-modifying-proxy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbProxy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-proxy.html)」を参照してください。

### `modify-db-shard-group`
<a name="rds_ModifyDbShardGroup_cli_2_topic"></a>

次のコード例は、`modify-db-shard-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB シャードグループを変更するには**  
次の `modify-db-shard-group` の例では、DB シャードグループの最大容量を変更します。  

```
aws rds modify-db-shard-group \
    --db-shard-group-identifier my-db-shard-group \
    --max-acu 1000
```
出力:  

```
{
    "DBShardGroups": [
        {
            "DBShardGroupResourceId": "shardgroup-a6e3a0226aa243e2ac6c7a1234567890",
            "DBShardGroupIdentifier": "my-db-shard-group",
            "DBClusterIdentifier": "my-sv2-cluster",
            "MaxACU": 768.0,
            "ComputeRedundancy": 0,
            "Status": "available",
            "PubliclyAccessible": false,
            "Endpoint": "my-sv2-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスター](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.html)」を参照してください。  
**例 2: DB シャードグループを記述するには**  
次の `describe-db-shard-groups` の例では、`modify-db-shard-group` コマンドの実行後に DB シャードグループの詳細を取得します。DB シャードグループ `my-db-shard-group` の最大容量は、1000 Aurora キャパシティーユニット (ACU) になりました。  

```
aws rds describe-db-shard-groups
```
出力:  

```
{
    "DBShardGroups": [
        {
            "DBShardGroupResourceId": "shardgroup-7bb446329da94788b3f957746example",
            "DBShardGroupIdentifier": "limitless-test-shard-grp",
            "DBClusterIdentifier": "limitless-test-cluster",
            "MaxACU": 768.0,
            "ComputeRedundancy": 0,
            "Status": "available",
            "PubliclyAccessible": true,
            "Endpoint": "limitless-test-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        },
        {
            "DBShardGroupResourceId": "shardgroup-a6e3a0226aa243e2ac6c7a1234567890",
            "DBShardGroupIdentifier": "my-db-shard-group",
            "DBClusterIdentifier": "my-sv2-cluster",
            "MaxACU": 1000.0,
            "ComputeRedundancy": 0,
            "Status": "available",
            "PubliclyAccessible": false,
            "Endpoint": "my-sv2-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        }
    ]
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスター](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Overview.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbShardGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-shard-group.html)」を参照してください。

### `modify-db-snapshot-attribute`
<a name="rds_ModifyDbSnapshotAttribute_cli_2_topic"></a>

次の例は、`modify-db-snapshot-attribute` を使用する方法を説明しています。

**AWS CLI**  
**例 1: 2 つの AWS アカウントで DB スナップショットを復元できるようにするには**  
次の`modify-db-snapshot-attribute`例では、識別子 `111122223333`と を持つ 2 つの AWS アカウントに`444455556666`、 という名前の DB スナップショットを復元するアクセス許可を付与します`mydbsnapshot`。  

```
aws rds modify-db-snapshot-attribute \
    --db-snapshot-identifier mydbsnapshot \
    --attribute-name restore \
    --values-to-add {"111122223333","444455556666"}
```
出力:  

```
{
    "DBSnapshotAttributesResult": {
        "DBSnapshotIdentifier": "mydbsnapshot",
        "DBSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "111122223333",
                    "444455556666"
                ]
            }
        ]
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[スナップショットの共有](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ShareSnapshot.html#USER_ShareSnapshot.Sharing)」を参照してください。  
**例 2: AWS アカウントが DB スナップショットを復元できないようにするには**  
次の の`modify-db-snapshot-attribute`例では、 という名前の DB スナップショットを復元するアクセス許可を特定の AWS アカウントから削除します`mydbsnapshot`。単一のアカウントを指定する場合、アカウント識別子を引用符や中括弧で囲むことはできません。  

```
aws rds modify-db-snapshot-attribute \
    --db-snapshot-identifier mydbsnapshot \
    --attribute-name restore \
    --values-to-remove 444455556666
```
出力:  

```
{
    "DBSnapshotAttributesResult": {
        "DBSnapshotIdentifier": "mydbsnapshot",
        "DBSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "111122223333"
                ]
            }
        ]
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[スナップショットの共有](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ShareSnapshot.html#USER_ShareSnapshot.Sharing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbSnapshotAttribute](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-snapshot-attribute.html)」を参照してください。

### `modify-db-snapshot-attributes`
<a name="rds_ModifyDbSnapshotAttributes_cli_2_topic"></a>

次のコード例は、`modify-db-snapshot-attributes` を使用する方法を示しています。

**AWS CLI**  
**DB スナップショット属性を変更するには**  
次の`modify-db-snapshot-attribute`例では、 `111122223333`と の 2 つの AWS アカウント識別子に`444455556666`、 という名前の DB スナップショットの復元を許可します`mydbsnapshot`。  

```
aws rds modify-db-snapshot-attribute \
    --db-snapshot-identifier mydbsnapshot \
    --attribute-name restore \
    --values-to-add '["111122223333","444455556666"]'
```
出力:  

```
{
    "DBSnapshotAttributesResult": {
        "DBSnapshotIdentifier": "mydbsnapshot",
        "DBSnapshotAttributes": [
            {
                "AttributeName": "restore",
                "AttributeValues": [
                    "111122223333",
                    "444455556666"
                ]
            }
        ]
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[スナップショットの共有](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ShareSnapshot.html#USER_ShareSnapshot.Sharing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbSnapshotAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-snapshot-attributes.html)」を参照してください。

### `modify-db-snapshot`
<a name="rds_ModifyDbSnapshot_cli_2_topic"></a>

次のコード例は、`modify-db-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB スナップショットを変更するには**  
次の `modify-db-snapshot` の例では、`db5-snapshot-upg-test` という名前の PostgeSQL 10.6 スナップショットを PostgreSQL 11.7 にアップグレードします。新しい DB エンジンバージョンは、スナップショットのアップグレードが完了し、そのステータスが**使用可能**になった後に表示されます。  

```
aws rds modify-db-snapshot \
    --db-snapshot-identifier db5-snapshot-upg-test \
    --engine-version 11.7
```
出力:  

```
{
    "DBSnapshot": {
        "DBSnapshotIdentifier": "db5-snapshot-upg-test",
        "DBInstanceIdentifier": "database-5",
        "SnapshotCreateTime": "2020-03-27T20:49:17.092Z",
        "Engine": "postgres",
        "AllocatedStorage": 20,
        "Status": "upgrading",
        "Port": 5432,
        "AvailabilityZone": "us-west-2a",
        "VpcId": "vpc-2ff27557",
        "InstanceCreateTime": "2020-03-27T19:59:04.735Z",
        "MasterUsername": "postgres",
        "EngineVersion": "10.6",
        "LicenseModel": "postgresql-license",
        "SnapshotType": "manual",
        "OptionGroupName": "default:postgres-11",
        "PercentProgress": 100,
        "StorageType": "gp2",
        "Encrypted": false,
        "DBSnapshotArn": "arn:aws:rds:us-west-2:123456789012:snapshot:db5-snapshot-upg-test",
        "IAMDatabaseAuthenticationEnabled": false,
        "ProcessorFeatures": [],
        "DbiResourceId": "db-GJMF75LM42IL6BTFRE4UZJ5YM4"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[PostgreSQL DB スナップショットをアップグレードする](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBSnapshot.PostgreSQL.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-snapshot.html)」を参照してください。

### `modify-db-subnet-group`
<a name="rds_ModifyDbSubnetGroup_cli_2_topic"></a>

次のコード例は、`modify-db-subnet-group` を使用する方法を示しています。

**AWS CLI**  
**DB サブネットグループを変更するには**  
次の `modify-db-subnet-group` の例では、`mysubnetgroup` という名前の DB サブネットグループに ID が `subnet-08e41f9e230222222` のサブネットを追加します。既存のサブネットをサブネットグループに保持するには、`--subnet-ids` オプションに ID を値として含めます。DB サブネットグループに最低 2 つの異なるアベイラビリティーゾーンがあるサブネットであることを確認します。  

```
aws rds modify-db-subnet-group \
    --db-subnet-group-name mysubnetgroup \
    --subnet-ids '["subnet-0a1dc4e1a6f123456","subnet-070dd7ecb3aaaaaaa","subnet-00f5b198bc0abcdef","subnet-08e41f9e230222222"]'
```
出力:  

```
{
    "DBSubnetGroup": {
        "DBSubnetGroupName": "mysubnetgroup",
        "DBSubnetGroupDescription": "test DB subnet group",
        "VpcId": "vpc-0f08e7610a1b2c3d4",
        "SubnetGroupStatus": "Complete",
        "Subnets": [
            {
                "SubnetIdentifier": "subnet-08e41f9e230222222",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2a"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-070dd7ecb3aaaaaaa",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2b"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-00f5b198bc0abcdef",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2d"
                },
                "SubnetStatus": "Active"
            },
            {
                "SubnetIdentifier": "subnet-0a1dc4e1a6f123456",
                "SubnetAvailabilityZone": {
                    "Name": "us-west-2b"
                },
                "SubnetStatus": "Active"
            }
        ],
        "DBSubnetGroupArn": "arn:aws:rds:us-west-2:534026745191:subgrp:mysubnetgroup"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[ステップ 3: DB サブネットグループの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_VPC.WorkingWithRDSInstanceinaVPC.html#USER_VPC.CreateDBSubnetGroup)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDbSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-db-subnet-group.html)」を参照してください。

### `modify-event-subscription`
<a name="rds_ModifyEventSubscription_cli_2_topic"></a>

次のコード例は、`modify-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを変更するには**  
次の `modify-event-subscription` の例では、指定されたイベントサブスクリプションを無効にするため、指定された Amazon Simple Notification Service トピックに通知を発行しなくなります。  

```
aws rds modify-event-subscription \
    --subscription-name my-instance-events \
    --no-enabled
```
出力:  

```
{
    "EventSubscription": {
        "EventCategoriesList": [
            "backup",
            "recovery"
        ],
        "CustomerAwsId": "123456789012",
        "SourceType": "db-instance",
        "SubscriptionCreationTime": "Tue Jul 31 23:22:01 UTC 2018",
        "EventSubscriptionArn": "arn:aws:rds:us-east-1:123456789012:es:my-instance-events",
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:interesting-events",
        "CustSubscriptionId": "my-instance-events",
        "Status": "modifying",
        "Enabled": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-event-subscription.html)」を参照してください。

### `modify-global-cluster`
<a name="rds_ModifyGlobalCluster_cli_2_topic"></a>

次のコード例は、`modify-global-cluster` を使用する方法を示しています。

**AWS CLI**  
**グローバル DB クラスターを変更するには**  
次の `modify-global-cluster` の例では、Aurora MySQL 互換のグローバル DB クラスターの削除保護を有効にします。  

```
aws rds modify-global-cluster \
    --global-cluster-identifier myglobalcluster \
    --deletion-protection
```
出力:  

```
{
    "GlobalCluster": {
        "GlobalClusterIdentifier": "myglobalcluster",
        "GlobalClusterResourceId": "cluster-f0e523bfe07aabb",
        "GlobalClusterArn": "arn:aws:rds::123456789012:global-cluster:myglobalcluster",
        "Status": "available",
        "Engine": "aurora-mysql",
        "EngineVersion": "5.7.mysql_aurora.2.07.2",
        "StorageEncrypted": false,
        "DeletionProtection": true,
        "GlobalClusterMembers": []
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Aurora グローバルデータベースの管理](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyGlobalCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/modify-global-cluster.html)」を参照してください。

### `promote-read-replica-db-cluster`
<a name="rds_PromoteReadReplicaDbCluster_cli_2_topic"></a>

次のコード例は、`promote-read-replica-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターリードレプリカを昇格するには**  
次の `promote-read-replica-db-cluster` の例では、指定されたリードレプリカをスタンドアロン DB クラスターに昇格させます。  

```
aws rds promote-read-replica-db-cluster \
    --db-cluster-identifier mydbcluster-1
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1b",
            "us-east-1c"
        ],
        "BackupRetentionPeriod": 1,
        "DatabaseName": "",
        "DBClusterIdentifier": "mydbcluster-1",
        ...some output truncated...
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[リードレプリカを DB クラスターに昇格させる](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Replication.CrossRegion.html#AuroraMySQL.Replication.CrossRegion.Promote)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PromoteReadReplicaDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/promote-read-replica-db-cluster.html)」を参照してください。

### `promote-read-replica`
<a name="rds_PromoteReadReplica_cli_2_topic"></a>

次のコード例は、`promote-read-replica` を使用する方法を示しています。

**AWS CLI**  
**リードレプリカを昇格させるには**  
次の `promote-read-replica` の例では、指定されたリードレプリカをスタンドアロン DB インスタンスに昇格させます。  

```
aws rds promote-read-replica \
    --db-instance-identifier test-instance-repl
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:test-instance-repl",
        "StorageType": "standard",
        "ReadReplicaSourceDBInstanceIdentifier": "test-instance",
        "DBInstanceStatus": "modifying",
        ...some output truncated...
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PromoteReadReplica](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/promote-read-replica.html)」を参照してください。

### `purchase-reserved-db-instance`
<a name="rds_PurchaseReservedDbInstance_cli_2_topic"></a>

次のコード例は、`purchase-reserved-db-instance` を使用する方法を示しています。

**AWS CLI**  
**リザーブド DB インスタンスを購入するには**  
次の `purchase-reserved-db-instances-offering` の例では、リザーブド DB インスタンスサービスを購入します。`reserved-db-instances-offering-id` は、`describe-reserved-db-instances-offering` コマンドによって返される有効なオファリング ID である必要があります。  
aws rds purchase-reserved-db-instances-offering --reserved-db-instances-offering-id 438012d3-4a52-4cc7-b2e3-8dff72e0e706  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseReservedDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/purchase-reserved-db-instance.html)」を参照してください。

### `purchase-reserved-db-instances-offerings`
<a name="rds_PurchaseReservedDbInstancesOfferings_cli_2_topic"></a>

次のコード例は、`purchase-reserved-db-instances-offerings` を使用する方法を示しています。

**AWS CLI**  
**例 1: 購入するリザーブド DB インスタンスを検索するには**  
次の `describe-reserved-db-instances-offerings` の例では、db.t2.micro インスタンスクラスと 1 年間の利用可能なリザーブド MySQL DB インスタンスを一覧表示します。オファリング ID は、リザーブド DB インスタンスの購入に必要です。  

```
aws rds describe-reserved-db-instances-offerings \
    --product-description mysql \
    --db-instance-class db.t2.micro \
    --duration 1
```
出力:  

```
{
    "ReservedDBInstancesOfferings": [
        {
            "ReservedDBInstancesOfferingId": "8ba30be1-b9ec-447f-8f23-6114e3f4c7b4",
            "DBInstanceClass": "db.t2.micro",
            "Duration": 31536000,
            "FixedPrice": 51.0,
            "UsagePrice": 0.0,
            "CurrencyCode": "USD",
            "ProductDescription": "mysql",
            "OfferingType": "Partial Upfront",
            "MultiAZ": false,
            "RecurringCharges": [
                {
                    "RecurringChargeAmount": 0.006,
                    "RecurringChargeFrequency": "Hourly"
                }
            ]
        },
    ... some output truncated ...
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS のリザーブド DB インスタンス](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithReservedDBInstances.html)」を参照してください。  
**例 2: リザーブド DB インスタンスを購入するには**  
次の `purchase-reserved-db-instances-offering` の例は、前の例からのリザーブド DB インスタンスサービスを購入する方法を示しています。  
aws rds purchase-reserved-db-instances-offering --reserved-db-instances-offering-id 8ba30be1-b9ec-447f-8f23-6114e3f4c7b4  
出力:  

```
{
    "ReservedDBInstance": {
        "ReservedDBInstanceId": "ri-2020-06-29-16-54-57-670",
        "ReservedDBInstancesOfferingId": "8ba30be1-b9ec-447f-8f23-6114e3f4c7b4",
        "DBInstanceClass": "db.t2.micro",
        "StartTime": "2020-06-29T16:54:57.670Z",
        "Duration": 31536000,
        "FixedPrice": 51.0,
        "UsagePrice": 0.0,
        "CurrencyCode": "USD",
        "DBInstanceCount": 1,
        "ProductDescription": "mysql",
        "OfferingType": "Partial Upfront",
        "MultiAZ": false,
        "State": "payment-pending",
        "RecurringCharges": [
            {
                "RecurringChargeAmount": 0.006,
                "RecurringChargeFrequency": "Hourly"
            }
        ],
        "ReservedDBInstanceArn": "arn:aws:rds:us-west-2:123456789012:ri:ri-2020-06-29-16-54-57-670"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS のリザーブド DB インスタンス](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithReservedDBInstances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseReservedDbInstancesOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/purchase-reserved-db-instances-offerings.html)」を参照してください。

### `reboot-db-instance`
<a name="rds_RebootDBInstance_cli_2_topic"></a>

次のコード例は、`reboot-db-instance` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスを再起動するには**  
次の `reboot-db-instance` の例は、指定された DB インスタンスを再起動します。  

```
aws rds reboot-db-instance \
    --db-instance-identifier test-mysql-instance
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "test-mysql-instance",
        "DBInstanceClass": "db.t3.micro",
        "Engine": "mysql",
        "DBInstanceStatus": "rebooting",
        "MasterUsername": "admin",
        "Endpoint": {
            "Address": "test-mysql-instance.############.us-west-2.rds.amazonaws.com",
            "Port": 3306,
            "HostedZoneId": "Z1PVIF0EXAMPLE"
        },

    ... output omitted...

    }
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[DB インスタンスの再起動](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_RebootInstance.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[RebootDBInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/reboot-db-instance.html)」を参照してください。**

### `reboot-db-shard-group`
<a name="rds_RebootDbShardGroup_cli_2_topic"></a>

次のコード例は、`reboot-db-shard-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB シャードグループを再起動するには**  
次の `reboot-db-shard-group` の例では、DB シャードグループを再起動します。  

```
aws rds reboot-db-shard-group \
    --db-shard-group-identifier my-db-shard-group
```
出力:  

```
{
    "DBShardGroups": [
        {
            "DBShardGroupResourceId": "shardgroup-a6e3a0226aa243e2ac6c7a1234567890",
            "DBShardGroupIdentifier": "my-db-shard-group",
            "DBClusterIdentifier": "my-sv2-cluster",
            "MaxACU": 1000.0,
            "ComputeRedundancy": 0,
            "Status": "available",
            "PubliclyAccessible": false,
            "Endpoint": "my-sv2-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        }
    ]
}
```
詳細については、「[Amazon Aurora ユーザーガイド](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_RebootCluster.html)」の「*Amazon Aurora DB クラスターまたは Amazon Aurora DB インスタンスの再起動*」を参照してください。  
**例 2: DB シャードグループを記述するには**  
次の `describe-db-shard-groups` の例では、`reboot-db-shard-group` コマンドの実行後に DB シャードグループの詳細を取得します。DB シャードグループ `my-db-shard-group` を再起動しています。  

```
aws rds describe-db-shard-groups
```
出力:  

```
{
    "DBShardGroups": [
        {
            "DBShardGroupResourceId": "shardgroup-7bb446329da94788b3f957746example",
            "DBShardGroupIdentifier": "limitless-test-shard-grp",
            "DBClusterIdentifier": "limitless-test-cluster",
            "MaxACU": 768.0,
            "ComputeRedundancy": 0,
            "Status": "available",
            "PubliclyAccessible": true,
            "Endpoint": "limitless-test-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        },
        {
            "DBShardGroupResourceId": "shardgroup-a6e3a0226aa243e2ac6c7a1234567890",
            "DBShardGroupIdentifier": "my-db-shard-group",
            "DBClusterIdentifier": "my-sv2-cluster",
            "MaxACU": 1000.0,
            "ComputeRedundancy": 0,
            "Status": "rebooting",
            "PubliclyAccessible": false,
            "Endpoint": "my-sv2-cluster.limitless-cekycexample.us-east-2.rds.amazonaws.com"
        }
    ]
}
```
詳細については、「[Amazon Aurora ユーザーガイド](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_RebootCluster.html)」の「*Amazon Aurora DB クラスターまたは Amazon Aurora DB インスタンスの再起動*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootDbShardGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/reboot-db-shard-group.html)」を参照してください。

### `register-db-proxy-targets`
<a name="rds_RegisterDbProxyTargets_cli_2_topic"></a>

次のコード例は、`register-db-proxy-targets` を使用する方法を示しています。

**AWS CLI**  
**DB プロキシをデータベースに登録するには**  
次の `register-db-proxy-targets` の例では、データベースとプロキシ間の関連付けを作成します。  

```
aws rds register-db-proxy-targets \
    --db-proxy-name proxyExample \
    --db-cluster-identifiers database-5
```
出力:  

```
{
    "DBProxyTargets": [
        {
            "RdsResourceId": "database-5",
            "Port": 3306,
            "Type": "TRACKED_CLUSTER",
            "TargetHealth": {
                "State": "REGISTERING"
            }
        },
        {
            "Endpoint": "database-5instance-1.ab0cd1efghij.us-east-1.rds.amazonaws.com",
            "RdsResourceId": "database-5",
            "Port": 3306,
            "Type": "RDS_INSTANCE",
            "TargetHealth": {
                "State": "REGISTERING"
            }
        }
    ]
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[RDS プロキシの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html#rds-proxy-creating)」および「*Amazon Aurora ユーザーガイド*」の「[RDS プロキシの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/rds-proxy-setup.html#rds-proxy-creating)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterDbProxyTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/register-db-proxy-targets.html)」を参照してください。

### `remove-from-global-cluster`
<a name="rds_RemoveFromGlobalCluster_cli_2_topic"></a>

次のコード例は、`remove-from-global-cluster` を使用する方法を示しています。

**AWS CLI**  
**Aurora グローバルデータベースクラスターから Aurora セカンダリクラスターをデタッチするには**  
次の `remove-from-global-cluster` の例では、Aurora グローバルデータベースクラスターから Aurora セカンダリクラスターをデタッチします。クラスターは読み取り専用から、読み取り/書き込み機能を備えたスタンドアロンクラスターに変わります。  

```
aws rds remove-from-global-cluster \
    --region us-west-2 \
    --global-cluster-identifier myglobalcluster \
    --db-cluster-identifier arn:aws:rds:us-west-2:123456789012:cluster:DB-1
```
出力:  

```
{
    "GlobalCluster": {
        "GlobalClusterIdentifier": "myglobalcluster",
        "GlobalClusterResourceId": "cluster-abc123def456gh",
        "GlobalClusterArn": "arn:aws:rds::123456789012:global-cluster:myglobalcluster",
        "Status": "available",
        "Engine": "aurora-postgresql",
        "EngineVersion": "10.11",
        "StorageEncrypted": true,
        "DeletionProtection": false,
        "GlobalClusterMembers": [
            {
                "DBClusterArn": "arn:aws:rds:us-east-1:123456789012:cluster:js-global-cluster",
                "Readers": [
                    "arn:aws:rds:us-west-2:123456789012:cluster:DB-1"
                ],
                "IsWriter": true
            },
            {
                "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:DB-1",
                "Readers": [],
                "IsWriter": false,
                "GlobalWriteForwardingStatus": "disabled"
            }
        ]
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora Global Database からのクラスターの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-global-database-managing.html#aurora-global-database-detaching)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveFromGlobalCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/remove-from-global-cluster.html)」を参照してください。

### `remove-option-from-option-group`
<a name="rds_RemoveOptionFromOptionGroup_cli_2_topic"></a>

次のコード例は、`remove-option-from-option-group` を使用する方法を示しています。

**AWS CLI**  
**オプショングループからオプションを削除するには**  
次の `remove-option-from-option-group` の例では、`OEM` オプションを `myoptiongroup` から削除しています。  

```
aws rds remove-option-from-option-group \
    --option-group-name myoptiongroup \
    --options OEM \
    --apply-immediately
```
出力:  

```
{
    "OptionGroup": {
        "OptionGroupName": "myoptiongroup",
        "OptionGroupDescription": "Test",
        "EngineName": "oracle-ee",
        "MajorEngineVersion": "19",
        "Options": [],
        "AllowsVpcAndNonVpcInstanceMemberships": true,
        "OptionGroupArn": "arn:aws:rds:us-east-1:123456789012:og:myoptiongroup"
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[オプショングループからオプションを削除する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithOptionGroups.html#USER_WorkingWithOptionGroups.RemoveOption)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveOptionFromOptionGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/remove-option-from-option-group.html)」を参照してください。

### `remove-role-from-db-cluster`
<a name="rds_RemoveRoleFromDbCluster_cli_2_topic"></a>

次の例は、`remove-role-from-db-cluster` を使用する方法を説明しています。

**AWS CLI**  
**DB クラスターから AWS Identity and Access Management (IAM) ロールの関連付けを解除するには**  
次の `remove-role-from-db-cluster` の例では、DB クラスターからロールを削除します。  

```
aws rds remove-role-from-db-cluster \
    --db-cluster-identifier mydbcluster \
    --role-arn arn:aws:iam::123456789012:role/RDSLoadFromS3
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Aurora ユーザーガイド*」の「[IAM ロールと Amazon Aurora MySQL DB クラスターの関連付け](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Integrating.Authorizing.IAM.AddRoleToDBCluster.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveRoleFromDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/remove-role-from-db-cluster.html)」を参照してください。

### `remove-role-from-db-instance`
<a name="rds_RemoveRoleFromDbInstance_cli_2_topic"></a>

次の例は、`remove-role-from-db-instance` を使用する方法を説明しています。

**AWS CLI**  
**DB インスタンスから AWS Identity and Access Management (IAM) ロールの関連付けを解除するには**  
次の `remove-role-from-db-instance` の例では、`test-instance` という名前の Oracle DB インスタンスから `rds-s3-integration-role` という名前のロールを削除します。  

```
aws rds remove-role-from-db-instance \
    --db-instance-identifier test-instance \
    --feature-name S3_INTEGRATION \
    --role-arn arn:aws:iam::111122223333:role/rds-s3-integration-role
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[S3 との RDS SQL Server 統合の無効化](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/User.SQLServer.Options.S3-integration.html#Appendix.SQLServer.Options.S3-integration.disabling)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveRoleFromDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/remove-role-from-db-instance.html)」を参照してください。

### `remove-source-identifier-from-subscription`
<a name="rds_RemoveSourceIdentifierFromSubscription_cli_2_topic"></a>

次のコード例は、`remove-source-identifier-from-subscription` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプションからソース識別子を削除するには**  
次の `remove-source-identifier` の例は、ソース識別子を既存のサブスクリプションから削除します。  

```
aws rds remove-source-identifier-from-subscription \
    --subscription-name my-instance-events \
    --source-identifier test-instance-repl
```
出力:  

```
{
    "EventSubscription": {
        "EventSubscriptionArn": "arn:aws:rds:us-east-1:123456789012:es:my-instance-events",
        "SubscriptionCreationTime": "Tue Jul 31 23:22:01 UTC 2018",
        "EventCategoriesList": [
            "backup",
            "recovery"
        ],
        "SnsTopicArn": "arn:aws:sns:us-east-1:123456789012:interesting-events",
        "Status": "modifying",
        "CustSubscriptionId": "my-instance-events",
        "CustomerAwsId": "123456789012",
        "SourceIdsList": [
            "test-instance"
        ],
        "SourceType": "db-instance",
        "Enabled": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveSourceIdentifierFromSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/remove-source-identifier-from-subscription.html)」を参照してください。

### `remove-tags-from-resource`
<a name="rds_RemoveTagsFromResource_cli_2_topic"></a>

次のコード例は、`remove-tags-from-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除する**  
次の `remove-tags-from-resource` の例では、リソースからタグが削除されます。  

```
aws rds remove-tags-from-resource \
    --resource-name arn:aws:rds:us-east-1:123456789012:db:mydbinstance \
    --tag-keys Name Environment
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon RDS リソースのタグ付け](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html)」および「*Amazon Aurora ユーザーガイド*」の「[Amazon RDS リソースのタグ付け](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_Tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/remove-tags-from-resource.html)」を参照してください。

### `reset-db-cluster-parameter-group`
<a name="rds_ResetDbClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`reset-db-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのパラメータをデフォルト値にリセットするには**  
次の `reset-db-cluster-parameter-group` の例では、顧客が作成した DB クラスターパラメータグループのパラメータ値をデフォルト値にリセットします。  

```
aws rds reset-db-cluster-parameter-group \
    --db-cluster-parameter-group-name mydbclpg \
    --reset-all-parameters
```
出力:  

```
{
    "DBClusterParameterGroupName": "mydbclpg"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
**例 2: 特定のパラメータをデフォルト値にリセットするには**  
次の `reset-db-cluster-parameter-group` の例では、特定のパラメータのパラメータ値を顧客が作成した DB クラスターパラメータグループのデフォルト値にリセットします。  

```
aws rds reset-db-cluster-parameter-group \
    --db-cluster-parameter-group-name mydbclpgy \
    --parameters "ParameterName=max_connections,ApplyMethod=immediate" \
                 "ParameterName=max_allowed_packet,ApplyMethod=immediate"
```
出力:  

```
{
    "DBClusterParameterGroupName": "mydbclpg"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetDbClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/reset-db-cluster-parameter-group.html)」を参照してください。

### `reset-db-parameter-group`
<a name="rds_ResetDbParameterGroup_cli_2_topic"></a>

次のコード例は、`reset-db-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのパラメータをデフォルト値にリセットするには**  
次の `reset-db-parameter-group` の例では、顧客が作成した DB パラメータグループのパラメータ値をデフォルト値にリセットします。  

```
aws rds reset-db-parameter-group \
    --db-parameter-group-name mypg \
    --reset-all-parameters
```
出力:  

```
{
    "DBParameterGroupName": "mypg"
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB パラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html)」および「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
**例 2: 特定のパラメータをデフォルト値にリセットするには**  
次の `reset-db-parameter-group` の例では、特定のパラメータのパラメータ値を顧客が作成した DB パラメータグループのデフォルト値にリセットします。  

```
aws rds reset-db-parameter-group \
    --db-parameter-group-name mypg \
    --parameters "ParameterName=max_connections,ApplyMethod=immediate" \
                 "ParameterName=max_allowed_packet,ApplyMethod=immediate"
```
出力:  

```
{
    "DBParameterGroupName": "mypg"
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB パラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithParamGroups.html)」および「*Amazon Aurora ユーザーガイド*」の「[DB パラメータグループおよび DB クラスターパラメータグループを使用する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_WorkingWithParamGroups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetDbParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/reset-db-parameter-group.html)」を参照してください。

### `restore-db-cluster-from-s3`
<a name="rds_RestoreDbClusterFromS3_cli_2_topic"></a>

次のコード例は、`restore-db-cluster-from-s3` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 バケットから Amazon Aurora DB クラスターを復元するには**  
次の `restore-db-cluster-from-s3` の例では、Amazon Aurora MySQL バージョン 5.7 互換 DB クラスターを Amazon S3 の MySQL 5.7 DB バックアップファイルから復元します。  

```
aws rds restore-db-cluster-from-s3 \
    --db-cluster-identifier cluster-s3-restore \
    --engine aurora-mysql \
    --master-username admin \
    --master-user-password mypassword \
    --s3-bucket-name amzn-s3-demo-bucket \
    --s3-prefix test-backup \
    --s3-ingestion-role-arn arn:aws:iam::123456789012:role/service-role/TestBackup \
    --source-engine mysql \
    --source-engine-version 5.7.28
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-west-2c",
            "us-west-2a",
            "us-west-2b"
        ],
        "BackupRetentionPeriod": 1,
        "DBClusterIdentifier": "cluster-s3-restore",
        "DBClusterParameterGroup": "default.aurora-mysql5.7",
        "DBSubnetGroup": "default",
        "Status": "creating",
        "Endpoint": "cluster-s3-restore.cluster-co3xyzabc123.us-west-2.rds.amazonaws.com",
        "ReaderEndpoint": "cluster-s3-restore.cluster-ro-co3xyzabc123.us-west-2.rds.amazonaws.com",
        "MultiAZ": false,
        "Engine": "aurora-mysql",
        "EngineVersion": "5.7.12",
        "Port": 3306,
        "MasterUsername": "admin",
        "PreferredBackupWindow": "11:15-11:45",
        "PreferredMaintenanceWindow": "thu:12:19-thu:12:49",
        "ReadReplicaIdentifiers": [],
        "DBClusterMembers": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-########",
                "Status": "active"
            }
        ],
        "HostedZoneId": "Z1PVIF0EXAMPLE",
        "StorageEncrypted": false,
        "DbClusterResourceId": "cluster-SU5THYQQHOWCXZZDGXREXAMPLE",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:cluster-s3-restore",
        "AssociatedRoles": [],
        "IAMDatabaseAuthenticationEnabled": false,
        "ClusterCreateTime": "2020-07-27T14:22:08.095Z",
        "EngineMode": "provisioned",
        "DeletionProtection": false,
        "HttpEndpointEnabled": false,
        "CopyTagsToSnapshot": false,
        "CrossAccountClone": false,
        "DomainMemberships": []
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon S3 バケットを使用した MySQL からのデータ移行](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraMySQL.Migrating.ExtMySQL.html#AuroraMySQL.Migrating.ExtMySQL.S3)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbClusterFromS3](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/restore-db-cluster-from-s3.html)」を参照してください。

### `restore-db-cluster-from-snapshot`
<a name="rds_RestoreDbClusterFromSnapshot_cli_2_topic"></a>

次のコード例は、`restore-db-cluster-from-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットから DB クラスターを復元するには**  
次の `restore-db-cluster-from-snapshot` は、PostgreSQL バージョン 10.7 と互換性のある Aurora PostgreSQL DB クラスターを、`test-instance-snapshot` という名前の DB クラスタースナップショットから復元します。  

```
aws rds restore-db-cluster-from-snapshot \
    --db-cluster-identifier newdbcluster \
    --snapshot-identifier test-instance-snapshot \
    --engine aurora-postgresql \
    --engine-version 10.7
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-west-2c",
            "us-west-2a",
            "us-west-2b"
        ],
        "BackupRetentionPeriod": 7,
        "DatabaseName": "",
        "DBClusterIdentifier": "newdbcluster",
        "DBClusterParameterGroup": "default.aurora-postgresql10",
        "DBSubnetGroup": "default",
        "Status": "creating",
        "Endpoint": "newdbcluster.cluster-############.us-west-2.rds.amazonaws.com",
        "ReaderEndpoint": "newdbcluster.cluster-ro-############.us-west-2.rds.amazonaws.com",
        "MultiAZ": false,
        "Engine": "aurora-postgresql",
        "EngineVersion": "10.7",
        "Port": 5432,
        "MasterUsername": "postgres",
        "PreferredBackupWindow": "09:33-10:03",
        "PreferredMaintenanceWindow": "sun:12:22-sun:12:52",
        "ReadReplicaIdentifiers": [],
        "DBClusterMembers": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-########",
                "Status": "active"
            }
        ],
        "HostedZoneId": "Z1PVIF0EXAMPLE",
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/287364e4-33e3-4755-a3b0-a1b2c3d4e5f6",
        "DbClusterResourceId": "cluster-5DSB5IFQDDUVAWOUWM1EXAMPLE",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:newdbcluster",
        "AssociatedRoles": [],
        "IAMDatabaseAuthenticationEnabled": false,
        "ClusterCreateTime": "2020-06-05T15:06:58.634Z",
        "EngineMode": "provisioned",
        "DeletionProtection": false,
        "HttpEndpointEnabled": false,
        "CopyTagsToSnapshot": false,
        "CrossAccountClone": false,
        "DomainMemberships": []
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスターのスナップショットからの復元](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_RestoreFromSnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbClusterFromSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/restore-db-cluster-from-snapshot.html)」を参照してください。

### `restore-db-cluster-to-point-in-time`
<a name="rds_RestoreDbClusterToPointInTime_cli_2_topic"></a>

次のコード例は、`restore-db-cluster-to-point-in-time` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターを特定の時点に復元するには**  
次の `restore-db-cluster-to-point-in-time` の例では、`database-4` という名前の DB クラスターを可能な限り最新の時刻に復元します。`copy-on-write` を復元タイプとして使用すると、新しい DB クラスターがソース DB クラスターのクローンとして復元されます。  

```
aws rds restore-db-cluster-to-point-in-time \
    --source-db-cluster-identifier database-4 \
    --db-cluster-identifier sample-cluster-clone \
    --restore-type copy-on-write \
    --use-latest-restorable-time
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-west-2c",
            "us-west-2a",
            "us-west-2b"
        ],
        "BackupRetentionPeriod": 7,
        "DatabaseName": "",
        "DBClusterIdentifier": "sample-cluster-clone",
        "DBClusterParameterGroup": "default.aurora-postgresql10",
        "DBSubnetGroup": "default",
        "Status": "creating",
        "Endpoint": "sample-cluster-clone.cluster-############.us-west-2.rds.amazonaws.com",
        "ReaderEndpoint": "sample-cluster-clone.cluster-ro-############.us-west-2.rds.amazonaws.com",
        "MultiAZ": false,
        "Engine": "aurora-postgresql",
        "EngineVersion": "10.7",
        "Port": 5432,
        "MasterUsername": "postgres",
        "PreferredBackupWindow": "09:33-10:03",
        "PreferredMaintenanceWindow": "sun:12:22-sun:12:52",
        "ReadReplicaIdentifiers": [],
        "DBClusterMembers": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sg-########",
                "Status": "active"
            }
        ],
        "HostedZoneId": "Z1PVIF0EXAMPLE",
        "StorageEncrypted": true,
        "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/287364e4-33e3-4755-a3b0-a1b2c3d4e5f6",
        "DbClusterResourceId": "cluster-BIZ77GDSA2XBSTNPFW1EXAMPLE",
        "DBClusterArn": "arn:aws:rds:us-west-2:123456789012:cluster:sample-cluster-clone",
        "AssociatedRoles": [],
        "IAMDatabaseAuthenticationEnabled": false,
        "CloneGroupId": "8d19331a-099a-45a4-b4aa-11aa22bb33cc44dd",
        "ClusterCreateTime": "2020-03-10T19:57:38.967Z",
        "EngineMode": "provisioned",
        "DeletionProtection": false,
        "HttpEndpointEnabled": false,
        "CopyTagsToSnapshot": false,
        "CrossAccountClone": false
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[DB クラスターを指定の時点の状態に復元する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PIT.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbClusterToPointInTime](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/restore-db-cluster-to-point-in-time.html)」を参照してください。

### `restore-db-instance-from-db-snapshot`
<a name="rds_RestoreDbInstanceFromDbSnapshot_cli_2_topic"></a>

次のコード例は、`restore-db-instance-from-db-snapshot` を使用する方法を示しています。

**AWS CLI**  
**DB スナップショットから DB インスタンスを復元するには**  
次の `restore-db-instance-from-db-snapshot` の例では、指定された DB スナップショットから `db.t3.small` DB インスタンスクラスで `db7-new-instance` という名前の新しい DB インスタンスを作成します。スナップショットが作成されたソース DB インスタンスは、廃止された DB インスタンスクラスを使用するため、アップグレードできません。  

```
aws rds restore-db-instance-from-db-snapshot \
    --db-instance-identifier db7-new-instance \
    --db-snapshot-identifier db7-test-snapshot \
    --db-instance-class db.t3.small
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "db7-new-instance",
        "DBInstanceClass": "db.t3.small",
        "Engine": "mysql",
        "DBInstanceStatus": "creating",

        ...output omitted...

        "PreferredMaintenanceWindow": "mon:07:37-mon:08:07",
        "PendingModifiedValues": {},
        "MultiAZ": false,
        "EngineVersion": "5.7.22",
        "AutoMinorVersionUpgrade": true,
        "ReadReplicaDBInstanceIdentifiers": [],
        "LicenseModel": "general-public-license",

        ...output omitted...

        "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:db7-new-instance",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": []
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB スナップショットからの復元](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_RestoreFromSnapshot.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbInstanceFromDbSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/restore-db-instance-from-db-snapshot.html)」を参照してください。

### `restore-db-instance-from-s3`
<a name="rds_RestoreDbInstanceFromS3_cli_2_topic"></a>

次のコード例は、`restore-db-instance-from-s3` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 のバックアップから DB インスタンスを復元するには**  
次の `restore-db-instance-from-s3` の例では、`my-backups` S3 バケット内の既存のバックアップから `restored-test-instance` という名前の新しい DB インスタンスを作成します。  

```
aws rds restore-db-instance-from-s3 \
    --db-instance-identifier restored-test-instance \
    --allocated-storage 250 --db-instance-class db.m4.large --engine mysql \
    --master-username master --master-user-password secret99 \
    --s3-bucket-name my-backups --s3-ingestion-role-arn arn:aws:iam::123456789012:role/my-role \
    --source-engine mysql --source-engine-version 5.6.27
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbInstanceFromS3](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/restore-db-instance-from-s3.html)」を参照してください。

### `restore-db-instance-to-point-in-time`
<a name="rds_RestoreDbInstanceToPointInTime_cli_2_topic"></a>

次のコード例は、`restore-db-instance-to-point-in-time` を使用する方法を示しています。

**AWS CLI**  
**例 1: DB インスタンスを特定の時点に復元するには**  
次の `restore-db-instance-to-point-in-time` の例は、指定された時刻に `test-instance` を `restored-test-instance` という新しい DB インスタンスに復元します。  

```
aws rds restore-db-instance-to-point-in-time \
    --source-db-instance-identifier test-instance \
    --target-db-instance restored-test-instance \
    --restore-time 2018-07-30T23:45:00.000Z
```
出力:  

```
{
    "DBInstance": {
        "AllocatedStorage": 20,
        "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:restored-test-instance",
        "DBInstanceStatus": "creating",
        "DBInstanceIdentifier": "restored-test-instance",
        ...some output omitted...
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[DB インスタンスを指定の時点の状態に復元する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PIT.html)」を参照してください。  
**例 2: レプリケーションされたバックアップから指定された時刻に DB インスタンスを復元するには**  
次の `restore-db-instance-to-point-in-time` の例では、Oracle DB インスタンスをレプリケートされた自動バックアップから指定された時間に復元します。  

```
aws rds restore-db-instance-to-point-in-time \
    --source-db-instance-automated-backups-arn "arn:aws:rds:us-west-2:123456789012:auto-backup:ab-jkib2gfq5rv7replzadausbrktni2bn4example" \
    --target-db-instance-identifier myorclinstance-from-replicated-backup \
    --restore-time 2020-12-08T18:45:00.000Z
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceIdentifier": "myorclinstance-from-replicated-backup",
        "DBInstanceClass": "db.t3.micro",
        "Engine": "oracle-se2",
        "DBInstanceStatus": "creating",
        "MasterUsername": "admin",
        "DBName": "ORCL",
        "AllocatedStorage": 20,
        "PreferredBackupWindow": "07:45-08:15",
        "BackupRetentionPeriod": 14,
        ... some output omitted ...
        "DbiResourceId": "db-KGLXG75BGVIWKQT7NQ4EXAMPLE",
        "CACertificateIdentifier": "rds-ca-2019",
        "DomainMemberships": [],
        "CopyTagsToSnapshot": false,
        "MonitoringInterval": 0,
        "DBInstanceArn": "arn:aws:rds:us-west-2:123456789012:db:myorclinstance-from-replicated-backup",
        "IAMDatabaseAuthenticationEnabled": false,
        "PerformanceInsightsEnabled": false,
        "DeletionProtection": false,
        "AssociatedRoles": [],
        "TagList": []
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[レプリケーションされたバックアップから指定された時刻への復元](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReplicateBackups.html#AutomatedBackups.PiTR)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreDbInstanceToPointInTime](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/restore-db-instance-to-point-in-time.html)」を参照してください。

### `start-activity-stream`
<a name="rds_StartActivityStream_cli_2_topic"></a>

次のコード例は、`start-activity-stream` を使用する方法を示しています。

**AWS CLI**  
**データベースアクティビティストリーミングをスタートするには**  
次の `start-activity-stream` の例では、my-pg-cluster という名前の Aurora クラスターをモニタリングするための非同期アクティビティストリームを開始します。  

```
aws rds start-activity-stream \
    --region us-east-1 \
    --mode async \
    --kms-key-id arn:aws:kms:us-east-1:1234567890123:key/a12c345d-6ef7-890g-h123-456i789jk0l1 \
    --resource-arn arn:aws:rds:us-east-1:1234567890123:cluster:my-pg-cluster \
    --apply-immediately
```
出力:  

```
{
    "KmsKeyId": "arn:aws:kms:us-east-1:1234567890123:key/a12c345d-6ef7-890g-h123-456i789jk0l1",
    "KinesisStreamName": "aws-rds-das-cluster-0ABCDEFGHI1JKLM2NOPQ3R4S",
    "Status": "starting",
    "Mode": "async",
    "ApplyImmediately": true
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[データベースアクティビティストリームの開始](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/DBActivityStreams.html#DBActivityStreams.Enabling)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartActivityStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/start-activity-stream.html)」を参照してください。

### `start-db-cluster`
<a name="rds_StartDbCluster_cli_2_topic"></a>

次のコード例は、`start-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターを開始するには**  
次の `start-db-cluster` の例では、DB クラスターとその DB インスタンスを起動します。  

```
aws rds start-db-cluster \
    --db-cluster-identifier mydbcluster
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1e",
            "us-east-1b"
        ],
        "BackupRetentionPeriod": 1,
        "DatabaseName": "mydb",
        "DBClusterIdentifier": "mydbcluster",
        ...some output truncated...
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスターの停止と開始](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-cluster-stop-start.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/start-db-cluster.html)」を参照してください。

### `start-db-instance-automated-backups-replication`
<a name="rds_StartDbInstanceAutomatedBackupsReplication_cli_2_topic"></a>

次のコード例は、`start-db-instance-automated-backups-replication` を使用する方法を示しています。

**AWS CLI**  
**クロスリージョン自動バックアップを有効にするには**  
次の `start-db-instance-automated-backups-replication` の例では、米国東部 (バージニア北部) リージョン の DB インスタンスから 米国西部 (オレゴン) リージョン への自動バックアップをレプリケーションします。バックアップ保持期間は 14 日間です。  

```
aws rds start-db-instance-automated-backups-replication \
    --region us-west-2 \
    --source-db-instance-arn "arn:aws:rds:us-east-1:123456789012:db:new-orcl-db" \
    --backup-retention-period 14
```
出力:  

```
{
    "DBInstanceAutomatedBackup": {
        "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:new-orcl-db",
        "DbiResourceId": "db-JKIB2GFQ5RV7REPLZA4EXAMPLE",
        "Region": "us-east-1",
        "DBInstanceIdentifier": "new-orcl-db",
        "RestoreWindow": {},
        "AllocatedStorage": 20,
        "Status": "pending",
        "Port": 1521,
        "InstanceCreateTime": "2020-12-04T15:28:31Z",
        "MasterUsername": "admin",
        "Engine": "oracle-se2",
        "EngineVersion": "12.1.0.2.v21",
        "LicenseModel": "bring-your-own-license",
        "OptionGroupName": "default:oracle-se2-12-1",
        "Encrypted": false,
        "StorageType": "gp2",
        "IAMDatabaseAuthenticationEnabled": false,
        "BackupRetentionPeriod": 14,
        "DBInstanceAutomatedBackupsArn": "arn:aws:rds:us-west-2:123456789012:auto-backup:ab-jkib2gfq5rv7replzadausbrktni2bn4example"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[クロスリージョン自動バックアップの有効化](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReplicateBackups.html#AutomatedBackups.Replicating.Enable)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDbInstanceAutomatedBackupsReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/start-db-instance-automated-backups-replication.html)」を参照してください。

### `start-db-instance`
<a name="rds_StartDbInstance_cli_2_topic"></a>

次のコード例は、`start-db-instance` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスを開始するには**  
次の `start-db-instance` の例では、指定された DB インスタンスを起動します。  

```
aws rds start-db-instance \
    --db-instance-identifier test-instance
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceStatus": "starting",
        ...some output truncated...
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/start-db-instance.html)」を参照してください。

### `start-export-task`
<a name="rds_StartExportTask_cli_2_topic"></a>

次のコード例は、`start-export-task` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 にスナップショットをエクスポートするには**  
次の `start-export-task` の例では、`db5-snapshot-test` という名前の DB スナップショットを `amzn-s3-demo-bucket` という名前の Amazon S3 バケットにエクスポートします。  

```
aws rds start-export-task \
    --export-task-identifier my-s3-export \
    --source-arn arn:aws:rds:us-west-2:123456789012:snapshot:db5-snapshot-test \
    --s3-bucket-name amzn-s3-demo-bucket \
    --iam-role-arn arn:aws:iam::123456789012:role/service-role/ExportRole \
    --kms-key-id arn:aws:kms:us-west-2:123456789012:key/abcd0000-7fca-4128-82f2-aabbccddeeff
```
出力:  

```
{
    "ExportTaskIdentifier": "my-s3-export",
    "SourceArn": "arn:aws:rds:us-west-2:123456789012:snapshot:db5-snapshot-test",
    "SnapshotTime": "2020-03-27T20:48:42.023Z",
    "S3Bucket": "amzn-s3-demo-bucket",
    "IamRoleArn": "arn:aws:iam::123456789012:role/service-role/ExportRole",
    "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/abcd0000-7fca-4128-82f2-aabbccddeeff",
    "Status": "STARTING",
    "PercentProgress": 0,
    "TotalExtractedDataInGB": 0
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[Amazon S3 バケットへのスナップショットのエクスポート](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ExportSnapshot.html#USER_ExportSnapshot.Exporting)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartExportTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/start-export-task.html)」を参照してください。

### `stop-activity-stream`
<a name="rds_StopActivityStream_cli_2_topic"></a>

次のコード例は、`stop-activity-stream` を使用する方法を示しています。

**AWS CLI**  
**データベースアクティビティストリーミングを停止するには**  
次の `stop-activity-stream` の例では、my-pg-cluster という名前の Aurora クラスター内のアクティビティストリームを停止します。  

```
aws rds stop-activity-stream \
    --region us-east-1 \
    --resource-arn arn:aws:rds:us-east-1:1234567890123:cluster:my-pg-cluster \
    --apply-immediately
```
出力:  

```
{
    "KmsKeyId": "arn:aws:kms:us-east-1:1234567890123:key/a12c345d-6ef7-890g-h123-456i789jk0l1",
    "KinesisStreamName": "aws-rds-das-cluster-0ABCDEFGHI1JKLM2NOPQ3R4S",
    "Status": "stopping"
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[アクティビティストリームの停止](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/DBActivityStreams.html#DBActivityStreams.Disabling)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopActivityStream](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/stop-activity-stream.html)」を参照してください。

### `stop-db-cluster`
<a name="rds_StopDbCluster_cli_2_topic"></a>

次のコード例は、`stop-db-cluster` を使用する方法を示しています。

**AWS CLI**  
**DB クラスターを停止するには**  
次の `stop-db-cluster` 例では、DB クラスターとその DB インスタンスを停止します。  

```
aws rds stop-db-cluster \
    --db-cluster-identifier mydbcluster
```
出力:  

```
{
    "DBCluster": {
        "AllocatedStorage": 1,
        "AvailabilityZones": [
            "us-east-1a",
            "us-east-1e",
            "us-east-1b"
        ],
        "BackupRetentionPeriod": 1,
        "DatabaseName": "mydb",
        "DBClusterIdentifier": "mydbcluster",
        ...some output truncated...
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[Amazon Aurora DB クラスターの停止と開始](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/aurora-cluster-stop-start.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopDbCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/stop-db-cluster.html)」を参照してください。

### `stop-db-instance-automated-backups-replication`
<a name="rds_StopDbInstanceAutomatedBackupsReplication_cli_2_topic"></a>

次のコード例は、`stop-db-instance-automated-backups-replication` を使用する方法を示しています。

**AWS CLI**  
**自動バックアップのレプリケーションを停止するには**  
次の `stop-db-instance-automated-backups-replication` は、米国西部 (オレゴン) リージョンへの自動バックアップのレプリケーションを終了します。レプリケーションされたバックアップは、設定されたバックアップ保持期間に従って保持されます。  

```
aws rds stop-db-instance-automated-backups-replication \
    --region us-west-2 \
    --source-db-instance-arn "arn:aws:rds:us-east-1:123456789012:db:new-orcl-db"
```
出力:  

```
{
    "DBInstanceAutomatedBackup": {
        "DBInstanceArn": "arn:aws:rds:us-east-1:123456789012:db:new-orcl-db",
        "DbiResourceId": "db-JKIB2GFQ5RV7REPLZA4EXAMPLE",
        "Region": "us-east-1",
        "DBInstanceIdentifier": "new-orcl-db",
        "RestoreWindow": {
            "EarliestTime": "2020-12-04T23:13:21.030Z",
            "LatestTime": "2020-12-07T19:59:57Z"
        },
        "AllocatedStorage": 20,
        "Status": "replicating",
        "Port": 1521,
        "InstanceCreateTime": "2020-12-04T15:28:31Z",
        "MasterUsername": "admin",
        "Engine": "oracle-se2",
        "EngineVersion": "12.1.0.2.v21",
        "LicenseModel": "bring-your-own-license",
        "OptionGroupName": "default:oracle-se2-12-1",
        "Encrypted": false,
        "StorageType": "gp2",
        "IAMDatabaseAuthenticationEnabled": false,
        "BackupRetentionPeriod": 7,
        "DBInstanceAutomatedBackupsArn": "arn:aws:rds:us-west-2:123456789012:auto-backup:ab-jkib2gfq5rv7replzadausbrktni2bn4example"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[自動バックアップレプリケーションの停止](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_ReplicateBackups.html#AutomatedBackups.StopReplicating)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopDbInstanceAutomatedBackupsReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/stop-db-instance-automated-backups-replication.html)」を参照してください。

### `stop-db-instance`
<a name="rds_StopDbInstance_cli_2_topic"></a>

次のコード例は、`stop-db-instance` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスを停止するには**  
次の `stop-db-instance` の例では、指定された DB インスタンスを停止します。  

```
aws rds stop-db-instance \
    --db-instance-identifier test-instance
```
出力:  

```
{
    "DBInstance": {
        "DBInstanceStatus": "stopping",
        ...some output truncated...
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopDbInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/stop-db-instance.html)」を参照してください。

### `switchover-blue-green-deployment`
<a name="rds_SwitchoverBlueGreenDeployment_cli_2_topic"></a>

次のコード例は、`switchover-blue-green-deployment` を使用する方法を示しています。

**AWS CLI**  
**例 1: RDS DB インスタンスのブルー/グリーンデプロイを切り替えるには**  
次の `switchover-blue-green-deployment` の例では、指定されたグリーン環境を新しい本番環境として昇格させます。  

```
aws rds switchover-blue-green-deployment \
    --blue-green-deployment-identifier bgd-wi89nwzglccsfake \
    --switchover-timeout 300
```
出力:  

```
{
    "BlueGreenDeployment": {
        "BlueGreenDeploymentIdentifier": "bgd-v53303651eexfake",
        "BlueGreenDeploymentName": "bgd-cli-test-instance",
        "Source": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
        "Target": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-green-blhi1e",
        "SwitchoverDetails": [
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-green-blhi1e",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-1-green-k5fv7u",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-2-green-ggsh8m",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-db-instance-replica-3-green-o2vwm0",
                "Status": "AVAILABLE"
            }
        ],
        "Tasks": [
            {
                "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                "Status": "COMPLETED"
            },
            {
                "Name": "DB_ENGINE_VERSION_UPGRADE",
                "Status": "COMPLETED"
            },
            {
                "Name": "CONFIGURE_BACKUPS",
                "Status": "COMPLETED"
            },
            {
                "Name": "CREATING_TOPOLOGY_OF_SOURCE",
                "Status": "COMPLETED"
            }
        ],
        "Status": "SWITCHOVER_IN_PROGRESS",
        "CreateTime": "2022-02-25T22:33:22.225000+00:00"
    }
}
```
詳細については、「*Amazon RDS ユーザーガイド*」の「[ブルー/グリーンデプロイの切り替え](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/blue-green-deployments-switching.html)」を参照してください。  
**例 2: Aurora MySQL DB クラスターのブルー/グリーンデプロイを昇格させるには**  
次の `switchover-blue-green-deployment` の例では、指定されたグリーン環境を新しい本番環境として昇格させます。  

```
aws rds switchover-blue-green-deployment \
    --blue-green-deployment-identifier bgd-wi89nwzglccsfake \
    --switchover-timeout 300
```
出力:  

```
{
    "BlueGreenDeployment": {
        "BlueGreenDeploymentIdentifier": "bgd-wi89nwzglccsfake",
        "BlueGreenDeploymentName": "my-blue-green-deployment",
        "Source": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
        "Target": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3ud8z6",
        "SwitchoverDetails": [
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster:my-aurora-mysql-cluster-green-3ud8z6",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-1-green-bvxc73",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-2-green-7wc4ie",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:db:my-aurora-mysql-cluster-3-green-p4xxkz",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-excluded-member-endpoint-green-np1ikl",
                "Status": "AVAILABLE"
            },
            {
                "SourceMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint",
                "TargetMember": "arn:aws:rds:us-east-1:123456789012:cluster-endpoint:my-reader-endpoint-green-miszlf",
                "Status": "AVAILABLE"
            }
        ],
        "Tasks": [
            {
                "Name": "CREATING_READ_REPLICA_OF_SOURCE",
                "Status": "COMPLETED"
            },
            {
                "Name": "DB_ENGINE_VERSION_UPGRADE",
                "Status": "COMPLETED"
            },
            {
                "Name": "CREATE_DB_INSTANCES_FOR_CLUSTER",
                "Status": "COMPLETED"
            },
            {
                "Name": "CREATE_CUSTOM_ENDPOINTS",
                "Status": "COMPLETED"
            }
        ],
        "Status": "SWITCHOVER_IN_PROGRESS",
        "CreateTime": "2022-02-25T22:38:49.522000+00:00"
    }
}
```
詳細については、「*Amazon Aurora ユーザーガイド*」の「[ブルー/グリーンデプロイの切り替え](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/blue-green-deployments-switching.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SwitchoverBlueGreenDeployment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/switchover-blue-green-deployment.html)」を参照してください。

# を使用した Amazon RDS Data Service の例 AWS CLI
<a name="cli_2_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-execute-statement`
<a name="rds-data_BatchExecuteStatement_cli_2_topic"></a>

次のコード例は、`batch-execute-statement` を使用する方法を示しています。

**AWS CLI**  
**バッチ SQL ステートメントを実行するには**  
次の `batch-execute-statement` の例では、パラメータセットを使用してデータの配列に対してバッチ SQL ステートメントを実行します。  

```
aws rds-data batch-execute-statement \
    --resource-arn "arn:aws:rds:us-west-2:123456789012:cluster:mydbcluster" \
    --database "mydb" \
    --secret-arn "arn:aws:secretsmanager:us-west-2:123456789012:secret:mysecret" \
    --sql "insert into mytable values (:id, :val)" \
    --parameter-sets "[[{\"name\": \"id\", \"value\": {\"longValue\": 1}},{\"name\": \"val\", \"value\": {\"stringValue\": \"ValueOne\"}}],
        [{\"name\": \"id\", \"value\": {\"longValue\": 2}},{\"name\": \"val\", \"value\": {\"stringValue\": \"ValueTwo\"}}],
        [{\"name\": \"id\", \"value\": {\"longValue\": 3}},{\"name\": \"val\", \"value\": {\"stringValue\": \"ValueThree\"}}]]"
```
このコマンドでは何も出力されません。  
詳細については、「Amazon RDS ユーザーガイド」の「[Aurora Serverless v1 の Data API の使用](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchExecuteStatement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds-data/batch-execute-statement.html)」を参照してください。

### `begin-transaction`
<a name="rds-data_BeginTransaction_cli_2_topic"></a>

次のコード例は、`begin-transaction` を使用する方法を示しています。

**AWS CLI**  
**SQL トランザクションを開始するには**  
次の `begin-transaction` の例では、SQL トランザクションを開始します。  

```
aws rds-data begin-transaction \
    --resource-arn "arn:aws:rds:us-west-2:123456789012:cluster:mydbcluster" \
    --database "mydb" \
    --secret-arn "arn:aws:secretsmanager:us-west-2:123456789012:secret:mysecret"
```
出力:  

```
{
    "transactionId": "ABC1234567890xyz"
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[Aurora Serverless v1 の Data API の使用](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BeginTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds-data/begin-transaction.html)」を参照してください。

### `commit-transaction`
<a name="rds-data_CommitTransaction_cli_2_topic"></a>

次のコード例は、`commit-transaction` を使用する方法を示しています。

**AWS CLI**  
**SQL トランザクションをコミットするには**  
次の `commit-transaction` の例では、指定された SQL トランザクションを終了し、そのトランザクションの一部として行った変更をコミットします。  

```
aws rds-data commit-transaction \
    --resource-arn "arn:aws:rds:us-west-2:123456789012:cluster:mydbcluster" \
    --secret-arn "arn:aws:secretsmanager:us-west-2:123456789012:secret:mysecret" \
    --transaction-id "ABC1234567890xyz"
```
出力:  

```
{
    "transactionStatus": "Transaction Committed"
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[Aurora Serverless v1 の Data API の使用](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CommitTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds-data/commit-transaction.html)」を参照してください。

### `execute-statement`
<a name="rds-data_ExecuteStatement_cli_2_topic"></a>

次のコード例は、`execute-statement` を使用する方法を示しています。

**AWS CLI**  
**例 1: トランザクションの一部である SQL ステートメントを実行するには**  
次の `execute-statement` の例は、トランザクションの一部である SQL ステートメントを実行します。  

```
aws rds-data execute-statement \
    --resource-arn "arn:aws:rds:us-west-2:123456789012:cluster:mydbcluster" \
    --database "mydb" \
    --secret-arn "arn:aws:secretsmanager:us-west-2:123456789012:secret:mysecret" \
    --sql "update mytable set quantity=5 where id=201" \
    --transaction-id "ABC1234567890xyz"
```
出力:  

```
{
    "numberOfRecordsUpdated": 1
}
```
**例 2: パラメータを使用して SQL ステートメントを実行するには**  
以下の `execute-statement` の例は、パラメータを使用して SQL ステートメントを実行します。  

```
aws rds-data execute-statement \
    --resource-arn "arn:aws:rds:us-east-1:123456789012:cluster:mydbcluster" \
    --database "mydb" \
    --secret-arn "arn:aws:secretsmanager:us-east-1:123456789012:secret:mysecret" \
    --sql "insert into mytable values (:id, :val)" \
    --parameters "[{\"name\": \"id\", \"value\": {\"longValue\": 1}},{\"name\": \"val\", \"value\": {\"stringValue\": \"value1\"}}]"
```
出力:  

```
{
    "numberOfRecordsUpdated": 1
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[Aurora Serverless v1 の Data API の使用](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ExecuteStatement](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds-data/execute-statement.html)」を参照してください。

### `rollback-transaction`
<a name="rds-data_RollbackTransaction_cli_2_topic"></a>

次のコード例は、`rollback-transaction` を使用する方法を示しています。

**AWS CLI**  
**SQL トランザクションをロールバックするには**  
次の `rollback-transaction` の例では、指定された SQL トランザクションをロールバックします。  

```
aws rds-data rollback-transaction \
    --resource-arn "arn:aws:rds:us-west-2:123456789012:cluster:mydbcluster" \
    --secret-arn "arn:aws:secretsmanager:us-west-2:123456789012:secret:mysecret" \
    --transaction-id "ABC1234567890xyz"
```
出力:  

```
{
    "transactionStatus": "Rollback Complete"
}
```
詳細については、「Amazon RDS ユーザーガイド」の「[Aurora Serverless v1 の Data API の使用](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RollbackTransaction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds-data/rollback-transaction.html)」を参照してください。

# を使用した Amazon RDS Performance Insights の例 AWS CLI
<a name="cli_2_pi_code_examples"></a>

次のコード例は、Amazon RDS Performance Insights AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-performance-analysis-report`
<a name="pi_CreatePerformanceAnalysisReport_cli_2_topic"></a>

次のコード例は、`create-performance-analysis-report` を使用する方法を示しています。

**AWS CLI**  
**パフォーマンス分析レポートを表示するには**  
次の `create-performance-analysis-report` の例では、データベースの `db-abcdefg123456789` に対して、開始時間 `1682969503` と終了時間 `1682979503` を使用してパフォーマンス分析レポートを作成します。  

```
aws pi create-performance-analysis-report \
    --service-type RDS \
    --identifier db-abcdefg123456789 \
    --start-time 1682969503 \
    --end-time 1682979503
```
出力:  

```
{
    "AnalysisReportId": "report-0234d3ed98e28fb17"
}
```
パフォーマンス分析レポートの作成の詳細については、「*Amazon RDS ユーザーガイド*」の「[Performance Insights でのパフォーマンス分析レポートの作成](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.CreatingPerfAnlysisReport.html)」および「*Amazon Aurora ユーザーガイド*」の「[Performance Insights でのパフォーマンス分析レポートの作成](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.CreatingPerfAnlysisReport.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePerformanceAnalysisReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/create-performance-analysis-report.html)」を参照してください。

### `delete-performance-analysis-report`
<a name="pi_DeletePerformanceAnalysisReport_cli_2_topic"></a>

次のコード例は、`delete-performance-analysis-report` を使用する方法を示しています。

**AWS CLI**  
**パフォーマンス分析レポートを削除するには**  
次の `delete-performance-analysis-report` 例では、レポート ID が `report-0d99cc91c4422ee61` であるパフォーマンス分析レポートを削除します。  

```
aws pi delete-performance-analysis-report \
    --service-type RDS \
    --identifier db-abcdefg123456789 \
    --analysis-report-id report-0d99cc91c4422ee61
```
このコマンドでは何も出力されません。  
パフォーマンス分析レポートの削除の詳細については、「*Amazon RDS ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートの削除](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.DeletePerfAnalysisReport.html)」および「*Amazon Aurora ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートの削除](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.DeletePerfAnalysisReport.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePerformanceAnalysisReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/delete-performance-analysis-report.html)」を参照してください。

### `describe-dimension-keys`
<a name="pi_DescribeDimensionKeys_cli_2_topic"></a>

次のコード例は、`describe-dimension-keys` を使用する方法を示しています。

**AWS CLI**  
**例 1: ディメンションキーについて説明するには**  
この例では、すべての待機イベントの名前をリクエストします。データは、イベント名と、指定された期間におけるそれらのイベントの集計値によって要約されます。  
コマンド:  

```
aws pi describe-dimension-keys --service-type RDS --identifier db-LKCGOBK26374TPTDFXOIWVCPPM --start-time 1527026400 --end-time 1527080400 --metric db.load.avg --group-by '{"Group":"db.wait_event"}'
```
出力:  

```
{
    "AlignedEndTime": 1.5270804E9,
    "AlignedStartTime": 1.5270264E9,
    "Keys": [
        {
            "Dimensions": {"db.wait_event.name": "wait/synch/mutex/innodb/aurora_lock_thread_slot_futex"},
            "Total": 0.05906906851195666
        },
        {
            "Dimensions": {"db.wait_event.name": "wait/io/aurora_redo_log_flush"},
            "Total": 0.015824722186149193
        },
        {
            "Dimensions": {"db.wait_event.name": "CPU"},
            "Total": 0.008014396230265477
        },
        {
            "Dimensions": {"db.wait_event.name": "wait/io/aurora_respond_to_client"},
            "Total": 0.0036361612526204477
        },
        {
            "Dimensions": {"db.wait_event.name": "wait/io/table/sql/handler"},
            "Total": 0.0019108398419382965
        },
        {
            "Dimensions": {"db.wait_event.name": "wait/synch/cond/mysys/my_thread_var::suspend"},
            "Total": 8.533847837782684E-4
        },
        {
            "Dimensions": {"db.wait_event.name": "wait/io/file/csv/data"},
            "Total": 6.864181956477376E-4
        },
        {
            "Dimensions": {"db.wait_event.name": "Unknown"},
            "Total": 3.895887056379051E-4
        },
        {
            "Dimensions": {"db.wait_event.name": "wait/synch/mutex/sql/FILE_AS_TABLE::LOCK_shim_lists"},
            "Total": 3.710368625122906E-5
        },
        {
            "Dimensions": {"db.wait_event.name": "wait/lock/table/sql/handler"},
            "Total": 0
        }
    ]
}
```
**例 2: DB 負荷に最も寄与するステートメントの SQL ID を検索するには**  
次の `describe-dimension-keys` は、DB 負荷に最も寄与した 10 のステートメントの SQL ステートメントと SQL ID をリクエストします。  

```
aws pi describe-dimension-keys \
    --service-type RDS \
    --identifier db-abcdefg123456789 \
    --start-time 2023-05-01T00:00:00Z \
    --end-time 2023-05-01T01:00:00Z \
    --metric db.load.avg \
    --group-by '{"Group": "db.sql", "Dimensions": ["db.sql.id", "db.sql.statement"],"Limit": 10}'
```
出力:  

```
{
    "AlignedEndTime": 1.5270804E9,
    "AlignedStartTime": 1.5270264E9,
    "Identifier": "db-abcdefg123456789",
    "MetricList": [
        {
            "Keys": [
                {
                    "Dimensions": {"db.sql.id": "AKIAIOSFODNN7EXAMPLE", "db.sql.statement": "SELECT * FROM customers WHERE customer_id = 123"},
                    "Total": 25.5,"Partitions": [12.3, 13.2]
                }
            ]
        }
    ]
}
```
Performance Insights のディメンションの詳細については、「*Amazon RDS ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」および「*Amazon Aurora ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDimensionKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/describe-dimension-keys.html)」を参照してください。

### `get-dimension-key-details`
<a name="pi_GetDimensionKeyDetails_cli_2_topic"></a>

次のコード例は、`get-dimension-key-details` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスの指定されたディメンショングループの詳細を取得するには**  
次の `get-dimension-key-details` 例では、DB インスタンス `db-10BCD2EFGHIJ3KL4M5NO6PQRS5` の SQL ステートメントの全文を取得します。`--group` は `db.sql` であり、`--group-identifier` は `db.sql.id` です。この例では、`example-sql-id` は `get-resource-metrics` または `describe-dimension-keys` オペレーションを使用して取得された SQL ID を表します。この例では、ディメンションの詳細を使用できます。したがって、Performance Insights は、SQL ステートメントを切り捨てることなく、その全文を取得します。  

```
aws pi get-dimension-key-details \
    --service-type RDS \
    --identifier db-10BCD2EFGHIJ3KL4M5NO6PQRS5 \
    --group db.sql \
    --group-identifier example-sql-id \
    --requested-dimensions statement
```
出力:  

```
{
    "Dimensions":[
        {
            "Value": "SELECT e.last_name, d.department_name FROM employees e, departments d WHERE e.department_id=d.department_id",
            "Dimension": "db.sql.statement",
            "Status": "AVAILABLE"
        },
    ...
    ]
}
```
Performance Insights のディメンションの詳細については、「*Amazon RDS ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」および「*Amazon Aurora ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDimensionKeyDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/get-dimension-key-details.html)」を参照してください。

### `get-performance-analysis-report`
<a name="pi_GetPerformanceAnalysisReport_cli_2_topic"></a>

次のコード例は、`get-performance-analysis-report` を使用する方法を示しています。

**AWS CLI**  
**パフォーマンス分析レポートを表示するには**  
次の `get-performance-analysis-report` 例では、レポート ID `report-0d99cc91c4422ee61` を持つデータベース `db-abcdefg123456789` のパフォーマンス分析レポートを取得します。レスポンスには、レポートのステータス、ID、時間の詳細、およびインサイトが表示されます。  

```
aws pi get-performance-analysis-report \
    --service-type RDS \
    --identifier db-abcdefg123456789 \
    --analysis-report-id report-0d99cc91c4422ee61
```
出力:  

```
{
    "AnalysisReport": {
        "Status": "Succeeded",
        "ServiceType": "RDS",
        "Identifier": "db-abcdefg123456789",
        "StartTime": 1680583486.584,
        "AnalysisReportId": "report-0d99cc91c4422ee61",
        "EndTime": 1680587086.584,
        "CreateTime": 1680587087.139,
        "Insights": [
            ... (Condensed for space)
       ]
    }
}
```
パフォーマンス分析レポートの詳細については、「*Amazon RDS ユーザーガイド*」の「[一定期間のデータベースパフォーマンスの分析](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.AnalyzePerformanceTimePeriod.html)」および*「Amazon Aurora ユーザーガイド*」の「[一定期間のデータベースパフォーマンスの分析](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.AnalyzePerformanceTimePeriod.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPerformanceAnalysisReport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/get-performance-analysis-report.html)」を参照してください。

### `get-resource-metadata`
<a name="pi_GetResourceMetadata_cli_2_topic"></a>

次のコード例は、`get-resource-metadata` を使用する方法を示しています。

**AWS CLI**  
**データベースのリソースメタデータを取得するには**  
次の `get-resource-metadata` 例では、データベース `db-abcdefg123456789` のリソースメタデータを取得します。レスポンスは、SQL ダイジェスト統計が有効になっていることを示しています。  

```
aws pi get-resource-metadata \
    --service-type RDS \
    --identifier db-abcdefg123456789
```
出力:  

```
{
    "Identifier": "db-abcdefg123456789",
    "Features":{
        "SQL_DIGEST_STATISTICS":{
            "Status": "ENABLED"
        }
    }
}
```
Performance Insights の SQL 統計の詳細については、「*Amazon RDS ユーザーガイド*」の「[Performance Insights の SQL 統計](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/sql-statistics.html)」および「*Amazon Aurora ユーザーガイド*」の「[Performance Insights の SQL 統計](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/sql-statistics.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/get-resource-metadata.html)」を参照してください。

### `get-resource-metrics`
<a name="pi_GetResourceMetrics_cli_2_topic"></a>

次のコード例は、`get-resource-metrics` を使用する方法を示しています。

**AWS CLI**  
**リソースメトリクスを取得するには**  
この例では、*db.wait\$1event* ディメンショングループと、そのグループ内の *db.wait\$1event.name* ディメンションのデータポイントをリクエストします。レスポンスでは、関連するデータポイントは、リクエストされたディメンション (*db.wait\$1event.name*) によってグループ化されます。  
コマンド:  

```
aws pi get-resource-metrics --service-type RDS --identifier db-LKCGOBK26374TPTDFXOIWVCPPM --start-time 1527026400 --end-time 1527080400 --period-in-seconds 300 --metric db.load.avg --metric-queries file://metric-queries.json
```
`--metric-queries` の引数は、JSON ファイル `metric-queries.json` に保存されます。ファイルの内容は次のとおりです。  

```
[
    {
        "Metric": "db.load.avg",
        "GroupBy": {
            "Group":"db.wait_event"
        }
    }
]
```
出力:  

```
{
    "AlignedEndTime": 1.5270804E9,
    "AlignedStartTime": 1.5270264E9,
    "Identifier": "db-LKCGOBK26374TPTDFXOIWVCPPM",
    "MetricList": [
        {
            "Key": {
                "Metric": "db.load.avg"
            },
            "DataPoints": [
                {
                    "Timestamp": 1527026700.0,
                    "Value": 1.3533333333333333
                },
                {
                    "Timestamp": 1527027000.0,
                    "Value": 0.88
                },
                <...remaining output omitted...>
            ]
        },
        {
            "Key": {
                "Metric": "db.load.avg",
                "Dimensions": {
                    "db.wait_event.name": "wait/synch/mutex/innodb/aurora_lock_thread_slot_futex"
                }
            },
            "DataPoints": [
                {
                    "Timestamp": 1527026700.0,
                    "Value": 0.8566666666666667
                },
                {
                    "Timestamp": 1527027000.0,
                    "Value": 0.8633333333333333
                },
                <...remaining output omitted...>
            ],
        },
            <...remaining output omitted...>
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceMetrics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/get-resource-metrics.html)」を参照してください。

### `list-available-resource-dimensions`
<a name="pi_ListAvailableResourceDimensions_cli_2_topic"></a>

次のコード例は、`list-available-resource-dimensions` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスでメトリクスタイプに対してクエリできるディメンションを一覧表示するには**  
次の `list-available-resource-dimensions` 例では、データベース `db-abcdefg123456789` に対してクエリできる `db.load` メトリクスを一覧表示します。  

```
aws pi list-available-resource-dimensions \
    --service-type RDS \
    --identifier db-abcdefg123456789 \
    --metrics db.load
```
出力:  

```
{
    "MetricDimensions": [
        {
            "Metric": "db.load",
            "Groups": [
                {
                    "Group": "db.user",
                    "Dimensions": [
                        {
                            "Identifier": "db.user.id"
                        },
                        {
                            "Identifier": "db.user.name"
                        }
                    ]
                },
                {
                    "Group": "db.sql_tokenized",
                    "Dimensions": [
                        {
                            "Identifier": "db.sql_tokenized.id"
                        },
                        {
                            "Identifier": "db.sql_tokenized.db_id"
                        },
                        {
                            "Identifier": "db.sql_tokenized.statement"
                        }
                    ]
                },
                ...
            ]
        }
    ]
}
```
Performance Insights のディメンションの詳細については、「*Amazon RDS ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」および「*Amazon Aurora ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAvailableResourceDimensions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/list-available-resource-dimensions.html)」を参照してください。

### `list-available-resource-metrics`
<a name="pi_ListAvailableResourceMetrics_cli_2_topic"></a>

次のコード例は、`list-available-resource-metrics` を使用する方法を示しています。

**AWS CLI**  
**DB インスタンスのメトリクスタイプに対してクエリできるメトリクスを一覧表示するには**  
次の `list-available-resource-metrics` 例では、データベース `db-abcdefg123456789` に対してクエリできる `db.load` メトリクスを一覧表示します。  

```
aws pi list-available-resource-metrics \
    --service-type RDS \
    --identifier db-abcdefg123456789 \
    --metric-types "os" "db"
```
出力:  

```
{
    "Metrics": [
        {
            "Description": "The number of virtual CPUs for the DB instance",
            "Metric": "os.general.numVCPUs",
            "Unit": "vCPUs"
        },
        ......,
        {
            "Description": "Time spent reading data file blocks by backends in this instance",
            "Metric": "db.IO.read_latency",
            "Unit": "Milliseconds per block"
        },
        ......
    ]
}
```
Performance Insights のメトリクスの詳細については、「*Amazon RDS ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」および「*Amazon Aurora ユーザーガイド*」の「[データベース負荷](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.Overview.ActiveSessions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAvailableResourceMetrics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/list-available-resource-metrics.html)」を参照してください。

### `list-performance-analysis-reports`
<a name="pi_ListPerformanceAnalysisReports_cli_2_topic"></a>

次のコード例は、`list-performance-analysis-reports` を使用する方法を示しています。

**AWS CLI**  
**データベースのパフォーマンス分析レポートを一覧表示するには**  
次の `list-performance-analysis-reports` 例は、データベース `db-abcdefg123456789` のパフォーマンス分析レポートを一覧表示します。レスポンスには、すべてのレポートがレポートの ID、ステータス、および時間の詳細とともに一覧表示されます。  

```
aws pi list-performance-analysis-reports \
    --service-type RDS \
    --identifier db-abcdefg123456789
```
出力:  

```
{
    "AnalysisReports": [
        {
            "Status": "Succeeded",
            "EndTime": 1680587086.584,
            "CreateTime": 1680587087.139,
            "StartTime": 1680583486.584,
            "AnalysisReportId": "report-0d99cc91c4422ee61"
        },
        {
            "Status": "Succeeded",
            "EndTime": 1681491137.914,
            "CreateTime": 1681491145.973,
            "StartTime": 1681487537.914,
            "AnalysisReportId": "report-002633115cc002233"
        },
        {
            "Status": "Succeeded",
            "EndTime": 1681493499.849,
            "CreateTime": 1681493507.762,
            "StartTime": 1681489899.849,
            "AnalysisReportId": "report-043b1e006b47246f9"
        },
        {
            "Status": "InProgress",
            "EndTime": 1682979503.0,
            "CreateTime": 1682979618.994,
            "StartTime": 1682969503.0,
            "AnalysisReportId": "report-01ad15f9b88bcbd56"
        }
    ]
}
```
パフォーマンス分析レポートの詳細については、「*Amazon RDS ユーザーガイド*」の「[一定期間のデータベースパフォーマンスの分析](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.AnalyzePerformanceTimePeriod.html)」および*「Amazon Aurora ユーザーガイド*」の「[一定期間のデータベースパフォーマンスの分析](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.AnalyzePerformanceTimePeriod.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPerformanceAnalysisReports](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/list-performance-analysis-reports.html)」を参照してください。

### `list-tags-for-resource`
<a name="pi_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**パフォーマンス分析レポートのタグを一覧表示するには**  
次の `list-tags-for-resource` 例では、レポート ID `report-0d99cc91c4422ee61` を持つパフォーマンス分析レポートのタグを一覧表示します。  

```
aws pi list-tags-for-resource \
    --service-type RDS \
    --resource-arn arn:aws:pi:us-west-2:123456789012:perf-reports/RDS/db-abcdefg123456789/report-0d99cc91c4422ee61
```
出力:  

```
{
    "Tags": [
        {
            "Value": "test-tag",
            "Key": "name"
        }
    ]
}
```
パフォーマンス分析レポートのタグ付けの詳細については、「*Amazon RDS ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートにタグを追加する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.ManagePerfAnalysisReportTags.html)」および「*Amazon Aurora ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートにタグを追加する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.ManagePerfAnalysisReportTags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/list-tags-for-resource.html)」を参照してください。

### `tag-resource`
<a name="pi_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**パフォーマンス分析レポートにタグを追加するには**  
次の `tag-resource` 例では、タグ値 `test-tag` を持つタグキー `name` を、レポート ID `report-0d99cc91c4422ee61` を持つパフォーマンス分析レポートに追加します。  

```
aws pi tag-resource \
    --service-type RDS \
    --resource-arn arn:aws:pi:us-west-2:123456789012:perf-reports/RDS/db-abcdefg123456789/report-0d99cc91c4422ee61 \
    --tags Key=name,Value=test-tag
```
このコマンドでは何も出力されません。  
パフォーマンス分析レポートのタグ付けの詳細については、「*Amazon RDS ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートにタグを追加する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.ManagePerfAnalysisReportTags.html)」および「*Amazon Aurora ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートにタグを追加する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.ManagePerfAnalysisReportTags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="pi_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**パフォーマンス分析レポートにタグを削除するには**  
次の `untag-resource` 例では、レポート ID `report-0d99cc91c4422ee61` を持つパフォーマンス分析レポートのタグ `name` を削除します。  

```
aws pi untag-resource \
    --service-type RDS \
    --resource-arn arn:aws:pi:us-west-2:123456789012:perf-reports/RDS/db-abcdefg123456789/report-0d99cc91c4422ee61 \
    --tag-keys name
```
このコマンドでは何も出力されません。  
パフォーマンス分析レポートのタグ付けの詳細については、「*Amazon RDS ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートにタグを追加する](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_PerfInsights.UsingDashboard.ManagePerfAnalysisReportTags.html)」および「*Amazon Aurora ユーザーガイド*」の「[Performance Insights のパフォーマンス分析レポートにタグを追加する](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/USER_PerfInsights.UsingDashboard.ManagePerfAnalysisReportTags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/pi/untag-resource.html)」を参照してください。

# を使用した Amazon Redshift の例 AWS CLI
<a name="cli_2_redshift_code_examples"></a>

次のコード例は、Amazon Redshift AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-reserved-node-exchange`
<a name="redshift_AcceptReservedNodeExchange_cli_2_topic"></a>

次のコード例は、`accept-reserved-node-exchange` を使用する方法を示しています。

**AWS CLI**  
**リザーブドノード交換を受け入れるには**  
次の `accept-reserved-node-exchange` の例では、DC1 リザーブドノードと DC2 リザーブドノードの交換を受け入れます。  

```
aws redshift accept-reserved-node-exchange /
    --reserved-node-id 12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE /
    --target-reserved-node-offering-id 12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE
```
出力:  

```
{
    "ExchangedReservedNode": {
        "ReservedNodeId": "12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE",
        "ReservedNodeOfferingId": "12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE",
        "NodeType": "dc2.large",
        "StartTime": "2019-12-06T21:17:26Z",
        "Duration": 31536000,
        "FixedPrice": 0.0,
        "UsagePrice": 0.0,
        "CurrencyCode": "USD",
        "NodeCount": 1,
        "State": "exchanging",
        "OfferingType": "All Upfront",
        "RecurringCharges": [
            {
                "RecurringChargeAmount": 0.0,
                "RecurringChargeFrequency": "Hourly"
            }
        ],
        "ReservedNodeOfferingType": "Regular"
    }
}
```
詳細については、*「Amazon Redshift クラスター管理ガイド*[」の AWS 「 CLI を使用したリザーブドノードのアップグレード](https://docs.aws.amazon.com/redshift/latest/mgmt/purchase-reserved-node-offering-console.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptReservedNodeExchange](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/accept-reserved-node-exchange.html)」を参照してください。

### `authorize-cluster-security-group-ingress`
<a name="redshift_AuthorizeClusterSecurityGroupIngress_cli_2_topic"></a>

次のコード例は、`authorize-cluster-security-group-ingress` を使用する方法を示しています。

**AWS CLI**  
EC2 セキュリティ グループへのアクセスを承認する この例では、名前付き Amazon EC2 セキュリティグループへのアクセスを許可します。コマンド:  

```
aws redshift authorize-cluster-security-group-ingress --cluster-security-group-name mysecuritygroup --ec2-security-group-name myec2securitygroup --ec2-security-group-owner-id 123445677890
```
CIDR 範囲へのアクセスの許可 この例では、CIDR 範囲へのアクセスを許可します。コマンド：  

```
aws redshift authorize-cluster-security-group-ingress --cluster-security-group-name mysecuritygroup --cidrip 192.168.100.100/32
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AuthorizeClusterSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/authorize-cluster-security-group-ingress.html)」を参照してください。

### `authorize-snapshot-access`
<a name="redshift_AuthorizeSnapshotAccess_cli_2_topic"></a>

次の例は、`authorize-snapshot-access` を使用する方法を説明しています。

**AWS CLI**  
 AWS アカウントがSnapshotThis、 AWS アカウントがスナップショットを復元`444455556666`することを許可します`my-snapshot-id`。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift authorize-snapshot-access --snapshot-id my-snapshot-id --account-with-restore-access 444455556666
```
結果:  

```
{
   "Snapshot": {
      "Status": "available",
      "SnapshotCreateTime": "2013-07-17T22:04:18.947Z",
      "EstimatedSecondsToCompletion": 0,
      "AvailabilityZone": "us-east-1a",
      "ClusterVersion": "1.0",
      "MasterUsername": "adminuser",
      "Encrypted": false,
      "OwnerAccount": "111122223333",
      "BackupProgressInMegabytes": 11.0,
      "ElapsedTimeInSeconds": 0,
      "DBName": "dev",
      "CurrentBackupRateInMegabytesPerSecond: 0.1534,
      "ClusterCreateTime": "2013-01-22T21:59:29.559Z",
      "ActualIncrementalBackupSizeInMegabytes"; 11.0,
      "SnapshotType": "manual",
      "NodeType": "dw.hs1.xlarge",
      "ClusterIdentifier": "mycluster",
      "TotalBackupSizeInMegabytes": 20.0,
      "Port": 5439,
      "NumberOfNodes": 2,
      "SnapshotIdentifier": "my-snapshot-id"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AuthorizeSnapshotAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/authorize-snapshot-access.html)」を参照してください。

### `batch-delete-cluster-snapshots`
<a name="redshift_BatchDeleteClusterSnapshots_cli_2_topic"></a>

次のコード例は、`batch-delete-cluster-snapshots` を使用する方法を示しています。

**AWS CLI**  
**一連のクラスタースナップショットを削除するには**  
次の `batch-delete-cluster-snapshots` の例では、手動クラスタースナップショットのセットを削除します。  

```
aws redshift batch-delete-cluster-snapshots \
        --identifiers SnapshotIdentifier=mycluster-2019-11-06-14-12 SnapshotIdentifier=mycluster-2019-11-06-14-20
```
出力:  

```
{
    "Resources": [
        "mycluster-2019-11-06-14-12",
        "mycluster-2019-11-06-14-20"
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift スナップショット](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDeleteClusterSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/batch-delete-cluster-snapshots.html)」を参照してください。

### `batch-modify-cluster-snapshots`
<a name="redshift_BatchModifyClusterSnapshots_cli_2_topic"></a>

次のコード例は、`batch-modify-cluster-snapshots` を使用する方法を示しています。

**AWS CLI**  
**一連のクラスタースナップショットを変更するには**  
次の `batch-modify-cluster-snapshots` の例では、一連のクラスタースナップショットの設定を変更します。  

```
aws redshift batch-modify-cluster-snapshots \
    --snapshot-identifier-list mycluster-2019-11-06-16-31 mycluster-2019-11-06-16-32 \
    --manual-snapshot-retention-period 30
```
出力:  

```
{
    "Resources": [
        "mycluster-2019-11-06-16-31",
        "mycluster-2019-11-06-16-32"
    ],
    "Errors": [],
    "ResponseMetadata": {
        "RequestId": "12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE",
        "HTTPStatusCode": 200,
        "HTTPHeaders": {
                "x-amzn-requestid": "12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE,
                "content-type": "text/xml",
                "content-length": "480",
                "date": "Sat, 07 Dec 2019 00:36:09 GMT",
                "connection": "keep-alive"
        },
        "RetryAttempts": 0
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift スナップショット](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchModifyClusterSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/batch-modify-cluster-snapshots.html)」を参照してください。

### `cancel-resize`
<a name="redshift_CancelResize_cli_2_topic"></a>

次のコード例は、`cancel-resize` を使用する方法を示しています。

**AWS CLI**  
**クラスターのサイズ変更をキャンセルするには**  
次の `cancel-resize` の例では、クラスターの従来のサイズ変更オペレーションをキャンセルします。  

```
aws redshift cancel-resize \
    --cluster-identifier mycluster
```
出力:  

```
{
    "TargetNodeType": "dc2.large",
    "TargetNumberOfNodes": 2,
    "TargetClusterType": "multi-node",
    "Status": "CANCELLING",
    "ResizeType": "ClassicResize",
    "TargetEncryptionType": "NONE"
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift クラスターのサイズ調整](https://docs.aws.amazon.com/redshift/latest/mgmt/rs-resize-tutorial.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「CancelResize」を参照してください。[https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/cancel-resize.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/cancel-resize.html)

### `copy-cluster-snapshot`
<a name="redshift_CopyClusterSnapshot_cli_2_topic"></a>

次のコード例は、`copy-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
すべてのクラスターバージョンの記述を取得する この例は、すべてのクラスターバージョンの記述を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift copy-cluster-snapshot --source-snapshot-identifier cm:examplecluster-2013-01-22-19-27-58 --target-snapshot-identifier my-saved-snapshot-copy
```
結果:  

```
{
   "Snapshot": {
      "Status": "available",
      "SnapshotCreateTime": "2013-01-22T19:27:58.931Z",
      "AvailabilityZone": "us-east-1c",
      "ClusterVersion": "1.0",
      "MasterUsername": "adminuser",
      "DBName": "dev",
      "ClusterCreateTime": "2013-01-22T19:23:59.368Z",
      "SnapshotType": "manual",
      "NodeType": "dw.hs1.xlarge",
      "ClusterIdentifier": "examplecluster",
      "Port": 5439,
      "NumberOfNodes": "2",
      "SnapshotIdentifier": "my-saved-snapshot-copy"
   },
   "ResponseMetadata": {
      "RequestId": "3b279691-64e3-11e2-bec0-17624ad140dd"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/copy-cluster-snapshot.html)」を参照してください。

### `create-cluster-parameter-group`
<a name="redshift_CreateClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`create-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
クラスターパラメータグループを作成する この例では、新しいクラスターパラメータグループを作成します。コマンド:  

```
aws redshift create-cluster-parameter-group --parameter-group-name myclusterparametergroup --parameter-group-family redshift-1.0 --description "My first cluster parameter group"
```
結果:  

```
{
   "ClusterParameterGroup": {
      "ParameterGroupFamily": "redshift-1.0",
      "Description": "My first cluster parameter group",
      "ParameterGroupName": "myclusterparametergroup"
   },
   "ResponseMetadata": {
      "RequestId": "739448f0-64cc-11e2-8f7d-3b939af52818"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-cluster-parameter-group.html)」を参照してください。

### `create-cluster-security-group`
<a name="redshift_CreateClusterSecurityGroup_cli_2_topic"></a>

次のコード例は、`create-cluster-security-group` を使用する方法を示しています。

**AWS CLI**  
クラスターセキュリティグループの作成 この例では、新しいクラスターセキュリティグループを作成します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift create-cluster-security-group --cluster-security-group-name mysecuritygroup --description "This is my cluster security group"
```
結果:  

```
{
   "create_cluster_security_group_response": {
      "create_cluster_security_group_result": {
         "cluster_security_group": {
            "description": "This is my cluster security group",
            "owner_id": "300454760768",
            "cluster_security_group_name": "mysecuritygroup",
            "ec2_security_groups": \[],
            "ip_ranges": \[]
         }
      },
      "response_metadata": {
         "request_id": "5df486a0-343a-11e2-b0d8-d15d0ef48549"
      }
   }
}
```
`--output text` オプションコマンドを使用して、同じ情報をテキスト形式で取得することもできます。  
`--output text` オプションコマンド:  
 オプションコマンド:  

```
aws redshift create-cluster-security-group --cluster-security-group-name mysecuritygroup --description "This is my cluster security group" --output text
```
結果:  

```
This is my cluster security group   300454760768    mysecuritygroup
a0c0bfab-343a-11e2-95d2-c3dc9fe8ab57
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateClusterSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-cluster-security-group.html)」を参照してください。

### `create-cluster-snapshot`
<a name="redshift_CreateClusterSnapshot_cli_2_topic"></a>

次のコード例は、`create-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
クラスタースナップショットを作成する この例では、新しいクラスターを作成します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift create-cluster-snapshot --cluster-identifier mycluster --snapshot-identifier my-snapshot-id
```
結果:  

```
{
   "Snapshot": {
      "Status": "creating",
      "SnapshotCreateTime": "2013-01-22T22:20:33.548Z",
      "AvailabilityZone": "us-east-1a",
      "ClusterVersion": "1.0",
      "MasterUsername": "adminuser",
      "DBName": "dev",
      "ClusterCreateTime": "2013-01-22T21:59:29.559Z",
      "SnapshotType": "manual",
      "NodeType": "dw.hs1.xlarge",
      "ClusterIdentifier": "mycluster",
      "Port": 5439,
      "NumberOfNodes": "2",
      "SnapshotIdentifier": "my-snapshot-id"
   },
   "ResponseMetadata": {
      "RequestId": "f024d1a5-64e1-11e2-88c5-53eb05787dfb"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-cluster-snapshot.html)」を参照してください。

### `create-cluster-subnet-group`
<a name="redshift_CreateClusterSubnetGroup_cli_2_topic"></a>

次のコード例は、`create-cluster-subnet-group` を使用する方法を示しています。

**AWS CLI**  
クラスターサブネットグループを作成する この例では、新しいクラスターサブネットグループを作成します。コマンド:  

```
aws redshift create-cluster-subnet-group --cluster-subnet-group-name mysubnetgroup  --description "My subnet group" --subnet-ids subnet-763fdd1c
```
結果:  

```
{
   "ClusterSubnetGroup": {
      "Subnets": [
         {
            "SubnetStatus": "Active",
            "SubnetIdentifier": "subnet-763fdd1c",
            "SubnetAvailabilityZone": {
               "Name": "us-east-1a"
            }
         } ],
      "VpcId": "vpc-7e3fdd14",
      "SubnetGroupStatus": "Complete",
      "Description": "My subnet group",
      "ClusterSubnetGroupName": "mysubnetgroup"
   },
   "ResponseMetadata": {
      "RequestId": "500b8ce2-698f-11e2-9790-fd67517fb6fd"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateClusterSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-cluster-subnet-group.html)」を参照してください。

### `create-cluster`
<a name="redshift_CreateCluster_cli_2_topic"></a>

次のコード例は、`create-cluster` を使用する方法を示しています。

**AWS CLI**  
この例では、最小限のパラメータセットでクラスターを作成します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift create-cluster --node-type dw.hs1.xlarge --number-of-nodes 2 --master-username adminuser --master-user-password TopSecret1 --cluster-identifier mycluster
```
結果:  

```
{
   "Cluster": {
      "NodeType": "dw.hs1.xlarge",
      "ClusterVersion": "1.0",
      "PubliclyAccessible": "true",
      "MasterUsername": "adminuser",
      "ClusterParameterGroups": [
         {
            "ParameterApplyStatus": "in-sync",
            "ParameterGroupName": "default.redshift-1.0"
         } ],
      "ClusterSecurityGroups": [
         {
            "Status": "active",
            "ClusterSecurityGroupName": "default"
         } ],
      "AllowVersionUpgrade": true,
      "VpcSecurityGroups": \[],
      "PreferredMaintenanceWindow": "sat:03:30-sat:04:00",
      "AutomatedSnapshotRetentionPeriod": 1,
      "ClusterStatus": "creating",
      "ClusterIdentifier": "mycluster",
      "DBName": "dev",
      "NumberOfNodes": 2,
      "PendingModifiedValues": {
         "MasterUserPassword": "\****"
      }
   },
   "ResponseMetadata": {
      "RequestId": "7cf4bcfc-64dd-11e2-bea9-49e0ce183f07"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-cluster.html)」を参照してください。

### `create-event-subscription`
<a name="redshift_CreateEventSubscription_cli_2_topic"></a>

次のコード例は、`create-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントの通知サブスクリプションを作成するには**  
次の `create-event-subscription` の例は、イベント通知サブスクリプションを作成します。  

```
aws redshift create-event-subscription \
    --subscription-name mysubscription \
    --sns-topic-arn arn:aws:sns:us-west-2:123456789012:MySNStopic \
    --source-type cluster \
    --source-ids mycluster
```
出力:  

```
{
        "EventSubscription": {
        "CustomerAwsId": "123456789012",
        "CustSubscriptionId": "mysubscription",
        "SnsTopicArn": "arn:aws:sns:us-west-2:123456789012:MySNStopic",
        "Status": "active",
        "SubscriptionCreationTime": "2019-12-09T20:05:19.365Z",
        "SourceType": "cluster",
        "SourceIdsList": [
            "mycluster"
        ],
        "EventCategoriesList": [],
        "Severity": "INFO",
        "Enabled": true,
        "Tags": []
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift イベント通知のサブスクライブ](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-event-subscription.html)」を参照してください。

### `create-hsm-client-certificate`
<a name="redshift_CreateHsmClientCertificate_cli_2_topic"></a>

次のコード例は、`create-hsm-client-certificate` を使用する方法を示しています。

**AWS CLI**  
**HSM クライアント証明書を作成するには**  
次の `create-hsm-client-certificate` の例では、クラスターが HSM への接続に使用できる HSM クライアント証明書を生成します。  

```
aws redshift create-hsm-client-certificate \
    --hsm-client-certificate-identifier myhsmclientcert
```
出力:  

```
{
    "HsmClientCertificate": {
        "HsmClientCertificateIdentifier": "myhsmclientcert",
        "HsmClientCertificatePublicKey": "-----BEGIN CERTIFICATE-----
        MIICiEXAMPLECQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
        VVMxCzAJBgNVBAgTEXAMPLEwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
        b24xFDASBgNVBAsTC0lBTSBDb25EXAMPLEIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
        BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb2EXAMPLETEwNDI1MjA0NTIxWhcN
        MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBEXAMPLEMRAwDgYD
        EXAMPLETZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
        b2xlMRIwEAEXAMPLEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
        YXpvbi5jb20wgZ8wDQYJKEXAMPLEAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
        21uUSfwfEvySWtC2XADZ4nB+BLYgVIk6EXAMPLE3G93vUEIO3IyNoH/f0wYK8m9T
        rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugEXAMPLEzZswY6786m86gpE
        Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEEXAMPLEEAtCu4
        nUhVVxYUEXAMPLEh8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
        FFBjvSfpJIlJ00zbhNYS5f6GEXAMPLEl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
        NYiytVbZPQUQ5Yaxu2jXnimvw3rEXAMPLE=-----END CERTIFICATE-----\n",
    "Tags": []
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift API アクセス許可のリファレンス](https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateHsmClientCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-hsm-client-certificate.html)」を参照してください。

### `create-hsm-configuration`
<a name="redshift_CreateHsmConfiguration_cli_2_topic"></a>

次のコード例は、`create-hsm-configuration` を使用する方法を示しています。

**AWS CLI**  
**HSM 設定を作成するには**  
次の `create-hsm-configuration` の例は、クラスターがハードウェアセキュリティモジュール (HSM) においてデータベース暗号化キーを保存または使用する際に必要とする情報を含んだ HSM 設定を作成します。  

```
aws redshift create-hsm-configuration /
    --hsm-configuration-identifier myhsmconnection
    --description "My HSM connection"
    --hsm-ip-address 192.0.2.09
    --hsm-partition-name myhsmpartition /
    --hsm-partition-password A1b2c3d4 /
    --hsm-server-public-certificate myhsmclientcert
```
出力:  

```
{
    "HsmConfiguration": {
        "HsmConfigurationIdentifier": "myhsmconnection",
        "Description": "My HSM connection",
        "HsmIpAddress": "192.0.2.09",
        "HsmPartitionName": "myhsmpartition",
        "Tags": []
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateHsmConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-hsm-configuration.html)」を参照してください。

### `create-snapshot-copy-grant`
<a name="redshift_CreateSnapshotCopyGrant_cli_2_topic"></a>

次のコード例は、`create-snapshot-copy-grant` を使用する方法を示しています。

**AWS CLI**  
**スナップショットコピーエージェントを作成するには**  
次の の`create-snapshot-copy-grant`例では、スナップショットコピー許可を作成し、コピー先の AWS リージョンでコピーされたスナップショットを暗号化します。  

```
aws redshift create-snapshot-copy-grant \
    --snapshot-copy-grant-name mysnapshotcopygrantname
```
出力:  

```
{
    "SnapshotCopyGrant": {
        "SnapshotCopyGrantName": "mysnapshotcopygrantname",
        "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/bPxRfih3yCo8nvbEXAMPLEKEY",
        "Tags": []
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift データベースの暗号化](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-db-encryption.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSnapshotCopyGrant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-snapshot-copy-grant.html)」を参照してください。

### `create-snapshot-schedule`
<a name="redshift_CreateSnapshotSchedule_cli_2_topic"></a>

次のコード例は、`create-snapshot-schedule` を使用する方法を示しています。

**AWS CLI**  
**スナップショットスケジュールを作成するには**  
次の `create-snapshot-schedule` の例では、指定された説明と 12 時間ごとのレートでスナップショットスケジュールを作成します。  

```
aws redshift create-snapshot-schedule \
    --schedule-definitions "rate(12 hours)" \
    --schedule-identifier mysnapshotschedule \
    --schedule-description "My schedule description"
```
出力:  

```
{
    "ScheduleDefinitions": [
        "rate(12 hours)"
    ],
    "ScheduleIdentifier": "mysnapshotschedule",
    "ScheduleDescription": "My schedule description",
    "Tags": []
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[自動スナップショットのスケジュール](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#automated-snapshot-schedules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSnapshotSchedule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-snapshot-schedule.html)」を参照してください。

### `create-tags`
<a name="redshift_CreateTags_cli_2_topic"></a>

次のコード例は、`create-tags` を使用する方法を示しています。

**AWS CLI**  
**クラスターのタグを作成するには**  
次の `create-tags` の例では、指定されたタグキーと値のペアを指定されたクラスターに追加します。  

```
aws redshift create-tags \
    --resource-name arn:aws:redshift:us-west-2:123456789012:cluster:mycluster \
    --tags "Key"="mytags","Value"="tag1"
```
このコマンドでは、出力が生成されません。  
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift のリソースへのタグ付け](https://docs.aws.amazon.com/redshift/latest/mgmt/amazon-redshift-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/create-tags.html)」を参照してください。

### `delete-cluster-parameter-group`
<a name="redshift_DeleteClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`delete-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
クラスターパラメータグループを削除する この例では、クラスターパラメータグループを削除します。コマンド:  

```
aws redshift delete-cluster-parameter-group --parameter-group-name myclusterparametergroup
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-cluster-parameter-group.html)」を参照してください。

### `delete-cluster-security-group`
<a name="redshift_DeleteClusterSecurityGroup_cli_2_topic"></a>

次のコード例は、`delete-cluster-security-group` を使用する方法を示しています。

**AWS CLI**  
クラスターセキュリティグループを削除する この例では、クラスターセキュリティグループを削除します。コマンド:  

```
aws redshift delete-cluster-security-group --cluster-security-group-name mysecuritygroup
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteClusterSecurityGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-cluster-security-group.html)」を参照してください。

### `delete-cluster-snapshot`
<a name="redshift_DeleteClusterSnapshot_cli_2_topic"></a>

次のコード例は、`delete-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
クラスタースナップショットを削除する この例では、クラスタースナップショットを削除します。コマンド:  

```
aws redshift delete-cluster-snapshot --snapshot-identifier my-snapshot-id
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-cluster-snapshot.html)」を参照してください。

### `delete-cluster-subnet-group`
<a name="redshift_DeleteClusterSubnetGroup_cli_2_topic"></a>

次のコード例は、`delete-cluster-subnet-group` を使用する方法を示しています。

**AWS CLI**  
クラスターサブネットグループを削除する この例では、クラスターサブネットグループを削除します。コマンド:  

```
aws redshift delete-cluster-subnet-group --cluster-subnet-group-name mysubnetgroup
```
結果:  

```
{
   "ResponseMetadata": {
      "RequestId": "253fbffd-6993-11e2-bc3a-47431073908a"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteClusterSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-cluster-subnet-group.html)」を参照してください。

### `delete-cluster`
<a name="redshift_DeleteCluster_cli_2_topic"></a>

次のコード例は、`delete-cluster` を使用する方法を示しています。

**AWS CLI**  
この例では、クラスターを削除してデータを強制的に削除し、最終的なクラスターのスナップショットは作成されません。コマンドは次のとおりです。  

```
aws redshift delete-cluster --cluster-identifier mycluster --skip-final-cluster-snapshot
```
この例では、クラスターは削除しますが、最終クラスターのスナップショットを指定しています。コマンドは次のとおりです。  

```
aws redshift delete-cluster --cluster-identifier mycluster --final-cluster-snapshot-identifier myfinalsnapshot
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-cluster.html)」を参照してください。

### `delete-event-subscription`
<a name="redshift_DeleteEventSubscription_cli_2_topic"></a>

次のコード例は、`delete-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを削除するには**  
次の `delete-event-subscription` の例では、指定したイベント通知サブスクリプションを削除します。  

```
aws redshift delete-event-subscription \
    --subscription-name mysubscription
```
このコマンドでは、出力が生成されません。  
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift イベント通知のサブスクライブ](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-event-subscription.html)」を参照してください。

### `delete-hsm-client-certificate`
<a name="redshift_DeleteHsmClientCertificate_cli_2_topic"></a>

次のコード例は、`delete-hsm-client-certificate` を使用する方法を示しています。

**AWS CLI**  
**HSM** クライアント証明書を削除するには  
次の `delete-hsm-client-certificate` の例では、HSM クライアント証明書を削除します。  

```
aws redshift delete-hsm-client-certificate \
    --hsm-client-certificate-identifier myhsmclientcert
```
このコマンドでは、出力が生成されません。  
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift API アクセス許可のリファレンス](https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteHsmClientCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-hsm-client-certificate.html)」を参照してください。

### `delete-hsm-configuration`
<a name="redshift_DeleteHsmConfiguration_cli_2_topic"></a>

次のコード例は、`delete-hsm-configuration` を使用する方法を示しています。

**AWS CLI**  
**HSM 設定を削除するには**  
次の の`delete-hsm-configuration`例では、現在の AWS アカウントから指定された HSM 設定を削除します。  

```
aws redshift delete-hsm-configuration /
    --hsm-configuration-identifier myhsmconnection
```
このコマンドでは、出力が生成されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteHsmConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-hsm-configuration.html)」を参照してください。

### `delete-scheduled-action`
<a name="redshift_DeleteScheduledAction_cli_2_topic"></a>

次のコード例は、`delete-scheduled-action` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされたアクションを削除するには**  
以下の `delete-scheduled-action` の例では、指定したアクションスケジュールを削除します。  

```
aws redshift delete-scheduled-action \
    --scheduled-action-name myscheduledaction
```
このコマンドでは、出力が生成されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteScheduledAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-scheduled-action.html)」を参照してください。

### `delete-snapshot-copy-grant`
<a name="redshift_DeleteSnapshotCopyGrant_cli_2_topic"></a>

次のコード例は、`delete-snapshot-copy-grant` を使用する方法を示しています。

**AWS CLI**  
**スナップショットコピー権限を削除するには**  
次の `delete-snapshot-copy-grant` の例では、指定したスナップショットコピー権限を削除します。  

```
aws redshift delete-snapshot-copy-grant \
    --snapshot-copy-grant-name mysnapshotcopygrantname
```
このコマンドでは、出力が生成されません。  
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift データベースの暗号化](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-db-encryption.html)」を参照してください。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteSnapshotCopyGrant](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-snapshot-copy-grant.html)」を参照してください。

### `delete-snapshot-schedule`
<a name="redshift_DeleteSnapshotSchedule_cli_2_topic"></a>

次のコード例は、`delete-snapshot-schedule` を使用する方法を示しています。

**AWS CLI**  
**スナップショットスケジュールを削除するには**  
次の `delete-snapshot-schedule` の例では、指定したスナップショットスケジュールを削除します。スケジュールを削除する前に、クラスターの関連付けを解除する必要があります。  

```
aws redshift delete-snapshot-schedule \
    --schedule-identifier mysnapshotschedule
```
このコマンドでは、出力が生成されません。  
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[自動スナップショットのスケジュール](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#automated-snapshot-schedules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSnapshotSchedule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-snapshot-schedule.html)」を参照してください。

### `delete-tags`
<a name="redshift_DeleteTags_cli_2_topic"></a>

次のコード例は、`delete-tags` を使用する方法を示しています。

**AWS CLI**  
**クラスターからタグを削除するには**  
次の `delete-tags` の例では、指定されたキー名を持つタグを指定されたクラスターから削除します。  

```
aws redshift delete-tags \
    --resource-name arn:aws:redshift:us-west-2:123456789012:cluster:mycluster \
    --tag-keys "clustertagkey" "clustertagvalue"
```
このコマンドでは、出力が生成されません。  
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift のリソースへのタグ付け](https://docs.aws.amazon.com/redshift/latest/mgmt/amazon-redshift-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/delete-tags.html)」を参照してください。

### `describe-account-attributes`
<a name="redshift_DescribeAccountAttributes_cli_2_topic"></a>

次の例は、`describe-account-attributes` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントの属性を記述するには**  
次の の`describe-account-attributes`例では、呼び出し元の AWS アカウントにアタッチされた属性を表示します。  

```
aws redshift describe-account-attributes
```
出力:  

```
{
    "AccountAttributes": [
        {
            "AttributeName": "max-defer-maintenance-duration",
            "AttributeValues": [
                {
                    "AttributeValue": "45"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAccountAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-account-attributes.html)」を参照してください。

### `describe-cluster-db-revisions`
<a name="redshift_DescribeClusterDbRevisions_cli_2_topic"></a>

次のコード例は、`describe-cluster-db-revisions` を使用する方法を示しています。

**AWS CLI**  
**クラスターの DB リビジョンを記述するには**  
次の `describe-cluster-db-revisions` の例は、指定されたクラスターの `ClusterDbRevision` オブジェクトの配列の詳細を表示します。  

```
aws redshift describe-cluster-db-revisions \
    --cluster-identifier mycluster
```
出力:  

```
{
    "ClusterDbRevisions": [
        {
            "ClusterIdentifier": "mycluster",
            "CurrentDatabaseRevision": "11420",
            "DatabaseRevisionReleaseDate": "2019-11-22T16:43:49.597Z",
            "RevisionTargets": []
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterDbRevisions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-db-revisions.html)」を参照してください。

### `describe-cluster-parameter-groups`
<a name="redshift_DescribeClusterParameterGroups_cli_2_topic"></a>

次のコード例は、`describe-cluster-parameter-groups` を使用する方法を示しています。

**AWS CLI**  
すべてのクラスターパラメータグループの記述を取得する この例は、アカウントのすべてのクラスターパラメータグループの説明と列ヘッダーを返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-cluster-parameter-groups
```
結果:  

```
{
   "ParameterGroups": [
      {
         "ParameterGroupFamily": "redshift-1.0",
         "Description": "My first cluster parameter group",
         "ParameterGroupName": "myclusterparametergroup"
      } ],
   "ResponseMetadata": {
      "RequestId": "8ceb8f6f-64cc-11e2-bea9-49e0ce183f07"
   }
}
```
`--output text` オプションコマンドを使用して、同じ情報をテキスト形式で取得することもできます。  
`--output text` オプションコマンド:  
 オプションコマンド:  

```
aws redshift describe-cluster-parameter-groups --output text
```
結果:  

```
redshift-1.0        My first cluster parameter group        myclusterparametergroup
RESPONSEMETADATA    9e665a36-64cc-11e2-8f7d-3b939af52818
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterParameterGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-parameter-groups.html)」を参照してください。

### `describe-cluster-parameters`
<a name="redshift_DescribeClusterParameters_cli_2_topic"></a>

次のコード例は、`describe-cluster-parameters` を使用する方法を示しています。

**AWS CLI**  
指定されたクラスターパラメータグループのパラメータを取得する この例では、名前付きパラメータグループのパラメータを取得します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-cluster-parameters --parameter-group-name myclusterparametergroup
```
結果:  

```
{
   "Parameters": [
      {
         "Description": "Sets the display format for date and time values.",
         "DataType": "string",
         "IsModifiable": true,
         "Source": "engine-default",
         "ParameterValue": "ISO, MDY",
         "ParameterName": "datestyle"
      },
      {
         "Description": "Sets the number of digits displayed for floating-point values",
         "DataType": "integer",
         "IsModifiable": true,
         "AllowedValues": "-15-2",
         "Source": "engine-default",
         "ParameterValue": "0",
         "ParameterName": "extra_float_digits"
      },
      (...remaining output omitted...)
   ]
}
```
`--output text` オプションコマンドを使用して、同じ情報をテキスト形式で取得することもできます。  
`--output text` オプションコマンド:  
 オプションコマンド:  

```
aws redshift describe-cluster-parameters --parameter-group-name myclusterparametergroup --output text
```
結果:  

```
RESPONSEMETADATA    cdac40aa-64cc-11e2-9e70-918437dd236d
Sets the display format for date and time values.   string  True    engine-default  ISO, MDY        datestyle
Sets the number of digits displayed for floating-point values       integer True    -15-2   engine-default  0       extra_float_digits
This parameter applies a user-defined label to a group of queries that are run during the same session..    string  True    engine-default  default query_group
require ssl for all databaseconnections     boolean True    true,false      engine-default  false   require_ssl
Sets the schema search order for names that are not schema-qualified.       string  True    engine-default  $user, public   search_path
Aborts any statement that takes over the specified number of milliseconds.  integer True    engine-default  0       statement_timeout
wlm json configuration      string  True    engine-default  \[{"query_concurrency":5}]      wlm_json_configuration
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-parameters.html)」を参照してください。

### `describe-cluster-security-groups`
<a name="redshift_DescribeClusterSecurityGroups_cli_2_topic"></a>

次のコード例は、`describe-cluster-security-groups` を使用する方法を示しています。

**AWS CLI**  
すべてのクラスターセキュリティグループの記述を取得する この例は、アカウントのすべてのクラスターセキュリティグループの記述を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-cluster-security-groups
```
結果:  

```
{
   "ClusterSecurityGroups": [
      {
         "OwnerId": "100447751468",
         "Description": "default",
         "ClusterSecurityGroupName": "default",
         "EC2SecurityGroups": \[],
         "IPRanges": [
            {
               "Status": "authorized",
               "CIDRIP": "0.0.0.0/0"
            }
         ]
      },
      {
         "OwnerId": "100447751468",
         "Description": "This is my cluster security group",
         "ClusterSecurityGroupName": "mysecuritygroup",
         "EC2SecurityGroups": \[],
         "IPRanges": \[]
      },
      (...remaining output omitted...)
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterSecurityGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-security-groups.html)」を参照してください。

### `describe-cluster-snapshots`
<a name="redshift_DescribeClusterSnapshots_cli_2_topic"></a>

次のコード例は、`describe-cluster-snapshots` を使用する方法を示しています。

**AWS CLI**  
すべてのクラスタースナップショットの記述を取得する この例は、アカウントのすべてのクラスタースナップショットの記述を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-cluster-snapshots
```
結果:  

```
{
   "Snapshots": [
      {
         "Status": "available",
         "SnapshotCreateTime": "2013-07-17T22:02:22.852Z",
         "EstimatedSecondsToCompletion": -1,
         "AvailabilityZone": "us-east-1a",
         "ClusterVersion": "1.0",
         "MasterUsername": "adminuser",
         "Encrypted": false,
         "OwnerAccount": "111122223333",
         "BackupProgressInMegabytes": 20.0,
         "ElapsedTimeInSeconds": 0,
         "DBName": "dev",
         "CurrentBackupRateInMegabytesPerSecond: 0.0,
         "ClusterCreateTime": "2013-01-22T21:59:29.559Z",
         "ActualIncrementalBackupSizeInMegabytes"; 20.0
         "SnapshotType": "automated",
         "NodeType": "dw.hs1.xlarge",
         "ClusterIdentifier": "mycluster",
         "Port": 5439,
         "TotalBackupSizeInMegabytes": 20.0,
         "NumberOfNodes": "2",
         "SnapshotIdentifier": "cm:mycluster-2013-01-22-22-04-18"
      },
      {
         "EstimatedSecondsToCompletion": 0,
         "OwnerAccount": "111122223333",
         "CurrentBackupRateInMegabytesPerSecond: 0.1534,
         "ActualIncrementalBackupSizeInMegabytes"; 11.0,
         "NumberOfNodes": "2",
         "Status": "available",
         "ClusterVersion": "1.0",
         "MasterUsername": "adminuser",
         "AccountsWithRestoreAccess": [
            {
               "AccountID": "444455556666"
            } ],
         "TotalBackupSizeInMegabytes": 20.0,
         "DBName": "dev",
         "BackupProgressInMegabytes": 11.0,
         "ClusterCreateTime": "2013-01-22T21:59:29.559Z",
         "ElapsedTimeInSeconds": 0,
         "ClusterIdentifier": "mycluster",
         "SnapshotCreateTime": "2013-07-17T22:04:18.947Z",
         "AvailabilityZone": "us-east-1a",
         "NodeType": "dw.hs1.xlarge",
         "Encrypted": false,
         "SnapshotType": "manual",
         "Port": 5439,
         "SnapshotIdentifier": "my-snapshot-id"
      } ]
   }
   (...remaining output omitted...)
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterSnapshots](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-snapshots.html)」を参照してください。

### `describe-cluster-subnet-groups`
<a name="redshift_DescribeClusterSubnetGroups_cli_2_topic"></a>

次のコード例は、`describe-cluster-subnet-groups` を使用する方法を示しています。

**AWS CLI**  
すべてのクラスターサブネットグループの記述を取得する この例では、すべてのクラスターサブネットグループの説明を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-cluster-subnet-groups
```
結果:  

```
{
   "ClusterSubnetGroups": [
      {
         "Subnets": [
            {
               "SubnetStatus": "Active",
               "SubnetIdentifier": "subnet-763fdd1c",
               "SubnetAvailabilityZone": {
                  "Name": "us-east-1a"
               }
            }
         ],
         "VpcId": "vpc-7e3fdd14",
         "SubnetGroupStatus": "Complete",
         "Description": "My subnet group",
         "ClusterSubnetGroupName": "mysubnetgroup"
      }
   ],
   "ResponseMetadata": {
      "RequestId": "37fa8c89-6990-11e2-8f75-ab4018764c77"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterSubnetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-subnet-groups.html)」を参照してください。

### `describe-cluster-tracks`
<a name="redshift_DescribeClusterTracks_cli_2_topic"></a>

次のコード例は、`describe-cluster-tracks` を使用する方法を示しています。

**AWS CLI**  
**クラスタートラックを記述するには**  
次の `describe-cluster-tracks` の例では、使用可能なメンテナンストラックの詳細を表示します。  

```
aws redshift describe-cluster-tracks \
    --maintenance-track-name current
```
出力:  

```
{
    "MaintenanceTracks": [
        {
            "MaintenanceTrackName": "current",
            "DatabaseVersion": "1.0.11420",
            "UpdateTargets": [
                {
                    "MaintenanceTrackName": "preview_features",
                    "DatabaseVersion": "1.0.11746",
                    "SupportedOperations": [
                        {
                            "OperationName": "restore-from-cluster-snapshot"
                        }
                    ]
                },
                {
                    "MaintenanceTrackName": "trailing",
                    "DatabaseVersion": "1.0.11116",
                    "SupportedOperations": [
                        {
                            "OperationName": "restore-from-cluster-snapshot"
                        },
                        {
                            "OperationName": "modify-cluster"
                        }
                    ]
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[クラスターメンテナンストラックの選択](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-mgmt-maintenance-tracks)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterTracks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-tracks.html)」を参照してください。

### `describe-cluster-versions`
<a name="redshift_DescribeClusterVersions_cli_2_topic"></a>

次のコード例は、`describe-cluster-versions` を使用する方法を示しています。

**AWS CLI**  
すべてのクラスターバージョンの記述を取得する この例は、すべてのクラスターバージョンの記述を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-cluster-versions
```
結果:  

```
{
   "ClusterVersions": [
      {
      "ClusterVersion": "1.0",
      "Description": "Initial release",
      "ClusterParameterGroupFamily": "redshift-1.0"
      } ],
   "ResponseMetadata": {
      "RequestId": "16a53de3-64cc-11e2-bec0-17624ad140dd"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusterVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-cluster-versions.html)」を参照してください。

### `describe-clusters`
<a name="redshift_DescribeClusters_cli_2_topic"></a>

次のコード例は、`describe-clusters` を使用する方法を示しています。

**AWS CLI**  
この例は、アカウントのすべてのクラスターの記述を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-clusters
```
結果:  

```
{
   "Clusters": [
   {
      "NodeType": "dw.hs1.xlarge",
      "Endpoint": {
         "Port": 5439,
         "Address": "mycluster.coqoarplqhsn.us-east-1.redshift.amazonaws.com"
      },
      "ClusterVersion": "1.0",
      "PubliclyAccessible": "true",
      "MasterUsername": "adminuser",
      "ClusterParameterGroups": [
         {
            "ParameterApplyStatus": "in-sync",
            "ParameterGroupName": "default.redshift-1.0"
         } ],
      "ClusterSecurityGroups": [
         {
            "Status": "active",
            "ClusterSecurityGroupName": "default"
         } ],
      "AllowVersionUpgrade": true,
      "VpcSecurityGroups": \[],
      "AvailabilityZone": "us-east-1a",
      "ClusterCreateTime": "2013-01-22T21:59:29.559Z",
      "PreferredMaintenanceWindow": "sat:03:30-sat:04:00",
      "AutomatedSnapshotRetentionPeriod": 1,
      "ClusterStatus": "available",
      "ClusterIdentifier": "mycluster",
      "DBName": "dev",
      "NumberOfNodes": 2,
      "PendingModifiedValues": {}
   } ],
   "ResponseMetadata": {
      "RequestId": "65b71cac-64df-11e2-8f5b-e90bd6c77476"
   }
}
```
`--output text` オプションコマンドを使用して、同じ情報をテキスト形式で取得することもできます。  
`--output text` オプションコマンド:  
 オプションコマンド:  

```
aws redshift describe-clusters --output text
```
結果:  

```
dw.hs1.xlarge       1.0     true    adminuser       True    us-east-1a      2013-01-22T21:59:29.559Z        sat:03:30-sat:04:00     1       available       mycluster       dev     2
ENDPOINT    5439    mycluster.coqoarplqhsn.us-east-1.redshift.amazonaws.com
in-sync     default.redshift-1.0
active      default
PENDINGMODIFIEDVALUES
RESPONSEMETADATA    934281a8-64df-11e2-b07c-f7fbdd006c67
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeClusters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-clusters.html)」を参照してください。

### `describe-default-cluster-parameters`
<a name="redshift_DescribeDefaultClusterParameters_cli_2_topic"></a>

次のコード例は、`describe-default-cluster-parameters` を使用する方法を示しています。

**AWS CLI**  
デフォルトクラスターパラメータの記述を取得する この例では、`redshift-1.0` ファミリーのデフォルトクラスターパラメータの説明を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-default-cluster-parameters --parameter-group-family redshift-1.0
```
結果:  

```
{
   "DefaultClusterParameters": {
   "ParameterGroupFamily": "redshift-1.0",
   "Parameters": [
      {
         "Description": "Sets the display format for date and time values.",
         "DataType": "string",
         "IsModifiable": true,
         "Source": "engine-default",
         "ParameterValue": "ISO, MDY",
         "ParameterName": "datestyle"
      },
      {
         "Description": "Sets the number of digits displayed for floating-point values",
         "DataType": "integer",
         "IsModifiable": true,
         "AllowedValues": "-15-2",
         "Source": "engine-default",
         "ParameterValue": "0",
         "ParameterName": "extra_float_digits"
      },
      (...remaining output omitted...)
      ]
   }
}
```
有効なパラメータグループファミリーのリストを表示するには、`describe-cluster-parameter-groups` コマンドを使用します。  
`describe-cluster-parameter-groups` コマンド。  
 コマンド。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDefaultClusterParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-default-cluster-parameters.html)」を参照してください。

### `describe-event-categories`
<a name="redshift_DescribeEventCategories_cli_2_topic"></a>

次のコード例は、`describe-event-categories` を使用する方法を示しています。

**AWS CLI**  
**クラスターのイベントカテゴリを記述するには**  
次の `describe-event-categories` の例では、クラスターのイベントカテゴリの詳細を表示します。  

```
aws redshift describe-event-categories \
    --source-type cluster
```
出力:  

```
{
    "EventCategoriesMapList": [
        {
            "SourceType": "cluster",
            "Events": [
                {
                    "EventId": "REDSHIFT-EVENT-2000",
                    "EventCategories": [
                        "management"
                    ],
                    "EventDescription": "Cluster <cluster name> created at <time in UTC>.",
                    "Severity": "INFO"
                },
                {
                    "EventId": "REDSHIFT-EVENT-2001",
                    "EventCategories": [
                        "management"
                    ],
                    "EventDescription": "Cluster <cluster name> deleted at <time in UTC>.",
                    "Severity": "INFO"
                },
                {
                    "EventId": "REDSHIFT-EVENT-3625",
                    "EventCategories": [
                        "monitoring"
                    ],
                    "EventDescription": "The cluster <cluster name> can't be resumed with its previous elastic network interface <ENI id>. We will allocate a new elastic network interface and associate it with the cluster node.",
                    "Severity": "INFO"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventCategories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-event-categories.html)」を参照してください。

### `describe-event-subscriptions`
<a name="redshift_DescribeEventSubscriptions_cli_2_topic"></a>

次のコード例は、`describe-event-subscriptions` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションについて表示するには**  
次の `describe-event-subscriptions` の例では、指定されたサブスクリプションのイベント通知サブスクリプションを表示します。  

```
aws redshift describe-event-subscriptions \
    --subscription-name mysubscription
```
出力:  

```
{
    "EventSubscriptionsList": [
        {
            "CustomerAwsId": "123456789012",
            "CustSubscriptionId": "mysubscription",
            "SnsTopicArn": "arn:aws:sns:us-west-2:123456789012:MySNStopic",
            "Status": "active",
            "SubscriptionCreationTime": "2019-12-09T21:50:21.332Z",
            "SourceIdsList": [],
            "EventCategoriesList": [
                "management"
            ],
            "Severity": "ERROR",
            "Enabled": true,
            "Tags": []
        }
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift イベント通知のサブスクライブ](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEventSubscriptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-event-subscriptions.html)」を参照してください。

### `describe-events`
<a name="redshift_DescribeEvents_cli_2_topic"></a>

次のコード例は、`describe-events` を使用する方法を示しています。

**AWS CLI**  
すべてのイベントを記述する この例では、すべてのイベントを返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-events
```
結果:  

```
{
   "Events": [
      {
      "Date": "2013-01-22T19:17:03.640Z",
      "SourceIdentifier": "myclusterparametergroup",
      "Message": "Cluster parameter group myclusterparametergroup has been created.",
      "SourceType": "cluster-parameter-group"
      } ],
   "ResponseMetadata": {
      "RequestId": "9f056111-64c9-11e2-9390-ff04f2c1e638"
   }
}
```
`--output text` オプションコマンドを使用して、同じ情報をテキスト形式で取得することもできます。  
`--output text` オプションコマンド:  
 オプションコマンド:  

```
aws redshift describe-events --output text
```
結果:  

```
2013-01-22T19:17:03.640Z    myclusterparametergroup Cluster parameter group myclusterparametergroup has been created.       cluster-parameter-group
RESPONSEMETADATA    8e5fe765-64c9-11e2-bce3-e56f52c50e17
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-events.html)」を参照してください。

### `describe-hsm-client-certificates`
<a name="redshift_DescribeHsmClientCertificates_cli_2_topic"></a>

次のコード例は、`describe-hsm-client-certificates` を使用する方法を示しています。

**AWS CLI**  
**HSM クライアント証明書を記述するには**  
次の `describe-hsm-client-certificates` の例は、指定された HSM クライアント証明書の詳細を表示します。  

```
aws redshift describe-hsm-client-certificates \
    --hsm-client-certificate-identifier myhsmclientcert
```
出力:  

```
{
    "HsmClientCertificates": [
        {
        "HsmClientCertificateIdentifier": "myhsmclientcert",
        "HsmClientCertificatePublicKey": "-----BEGIN CERTIFICATE-----\
        EXAMPLECAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
        VVMxCzAJBgNVBAEXAMPLERAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
        b24xFDASBgNVBAsTC0lBTSBDb25zEXAMPLEwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
        BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhEXAMPLEDI1MjA0EXAMPLEN
        EXAMPLE0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
        VQQHEwdTZWF0dGEXAMPLEQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
        b2xlMRIwEAYDVQQDEwlUZXN0Q2lsEXAMPLEdBgkqhkiG9w0BCQEWEG5vb25lQGFt
        YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIEXAMPLEMaK0dn+a4GmWIWJ
        21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
        rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY67EXAMPLEE
        EXAMPLEZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
        nUhVVxYUntneD9EXAMPLE6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
        FFBjvSfpJIlJ00zbhNYS5f6GuoEDEXAMPLEBHjJnyp378OD8uTs7fLvjx79LjSTb
        NYiytVbZPQUQ5Yaxu2jXnimvw3rEXAMPLE=-----END CERTIFICATE-----\n",
        "Tags": []
        }
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift API アクセス許可のリファレンス](https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-policy-resources.resource-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHsmClientCertificates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-hsm-client-certificates.html)」を参照してください。

### `describe-hsm-configurations`
<a name="redshift_DescribeHsmConfigurations_cli_2_topic"></a>

次のコード例は、`describe-hsm-configurations` を使用する方法を示しています。

**AWS CLI**  
**HSM 設定を記述するには**  
次の の`describe-hsm-configurations`例では、呼び出し元の AWS アカウントで使用可能な HSM 設定の詳細を表示します。  

```
aws redshift describe-hsm-configurations /
    --hsm-configuration-identifier myhsmconnection
```
出力:  

```
{
    "HsmConfigurations": [
        {
            "HsmConfigurationIdentifier": "myhsmconnection",
            "Description": "My HSM connection",
            "HsmIpAddress": "192.0.2.09",
            "HsmPartitionName": "myhsmpartition",
            "Tags": []
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHsmConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-hsm-configurations.html)」を参照してください。

### `describe-logging-status`
<a name="redshift_DescribeLoggingStatus_cli_2_topic"></a>

次のコード例は、`describe-logging-status` を使用する方法を示しています。

**AWS CLI**  
**クラスターのログ記録ステータスを記述するには**  
次の `describe-logging-status` の例は、クエリや接続試行などの情報がクラスターに対してログに記録されているかどうかを示しています。  

```
aws redshift describe-logging-status \
    --cluster-identifier mycluster
```
出力:  

```
{
    "LoggingEnabled": false
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[データベース監査ログ記録](https://docs.aws.amazon.com/redshift/latest/mgmt/db-auditing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLoggingStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-logging-status.html)」を参照してください。

### `describe-node-configuration-options`
<a name="redshift_DescribeNodeConfigurationOptions_cli_2_topic"></a>

次のコード例は、`describe-node-configuration-options` を使用する方法を示しています。

**AWS CLI**  
**ノード設定オプションを記述するには**  
次の `describe-node-configuration-options` の例は、ノードタイプ、ノード数、指定されたクラスタースナップショットのディスク使用量など、可能なノード設定のプロパティを示しています。  

```
aws redshift describe-node-configuration-options \
    --action-type restore-cluster \
    --snapshot-identifier rs:mycluster-2019-12-09-16-42-43
```
出力:  

```
{
    "NodeConfigurationOptionList": [
        {
            "NodeType": "dc2.large",
            "NumberOfNodes": 2,
            "EstimatedDiskUtilizationPercent": 19.61
        },
        {
            "NodeType": "dc2.large",
            "NumberOfNodes": 4,
            "EstimatedDiskUtilizationPercent": 9.96
        },
        {
            "NodeType": "ds2.xlarge",
            "NumberOfNodes": 2,
            "EstimatedDiskUtilizationPercent": 1.53
        },
        {
            "NodeType": "ds2.xlarge",
            "NumberOfNodes": 4,
            "EstimatedDiskUtilizationPercent": 0.78
        }
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift リザーブドノードの購入](https://docs.aws.amazon.com/redshift/latest/mgmt/purchase-reserved-node-instance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNodeConfigurationOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-node-configuration-options.html)」を参照してください。

### `describe-orderable-cluster-options`
<a name="redshift_DescribeOrderableClusterOptions_cli_2_topic"></a>

次のコード例は、`describe-orderable-cluster-options` を使用する方法を示しています。

**AWS CLI**  
すべての注文可能なクラスターオプションの記述 この例では、注文可能なすべてのクラスターオプションの説明を返します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift describe-orderable-cluster-options
```
結果:  

```
{
   "OrderableClusterOptions": [
      {
         "NodeType": "dw.hs1.8xlarge",
         "AvailabilityZones": [
            { "Name": "us-east-1a" },
            { "Name": "us-east-1b" },
            { "Name": "us-east-1c" } ],
         "ClusterVersion": "1.0",
         "ClusterType": "multi-node"
      },
      {
         "NodeType": "dw.hs1.xlarge",
         "AvailabilityZones": [
            { "Name": "us-east-1a" },
            { "Name": "us-east-1b" },
            { "Name": "us-east-1c" } ],
         "ClusterVersion": "1.0",
         "ClusterType": "multi-node"
      },
      {
      "NodeType": "dw.hs1.xlarge",
      "AvailabilityZones": [
         { "Name": "us-east-1a" },
         { "Name": "us-east-1b" },
         { "Name": "us-east-1c" } ],
      "ClusterVersion": "1.0",
      "ClusterType": "single-node"
      } ],
   "ResponseMetadata": {
      "RequestId": "f6000035-64cb-11e2-9135-ff82df53a51a"
   }
}
```
`--output text` オプションコマンドを使用して、同じ情報をテキスト形式で取得することもできます。  
`--output text` オプションコマンド:  
 オプションコマンド:  

```
aws redshift describe-orderable-cluster-options --output text
```
結果:  

```
dw.hs1.8xlarge      1.0     multi-node
us-east-1a
us-east-1b
us-east-1c
dw.hs1.xlarge       1.0     multi-node
us-east-1a
us-east-1b
us-east-1c
dw.hs1.xlarge       1.0     single-node
us-east-1a
us-east-1b
us-east-1c
RESPONSEMETADATA    e648696b-64cb-11e2-bec0-17624ad140dd
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOrderableClusterOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-orderable-cluster-options.html)」を参照してください。

### `describe-reserved-node-offerings`
<a name="redshift_DescribeReservedNodeOfferings_cli_2_topic"></a>

次のコード例は、`describe-reserved-node-offerings` を使用する方法を示しています。

**AWS CLI**  
リザーブドノードオファリングを記述する この例は、購入可能なリザーブドノードオファリングをすべて示しています。コマンド:  

```
aws redshift describe-reserved-node-offerings
```
結果:  

```
{
   "ReservedNodeOfferings": [
      {
         "OfferingType": "Heavy Utilization",
         "FixedPrice": "",
         "NodeType": "dw.hs1.xlarge",
         "UsagePrice": "",
         "RecurringCharges": [
            {
               "RecurringChargeAmount": "",
               "RecurringChargeFrequency": "Hourly"
            } ],
         "Duration": 31536000,
         "ReservedNodeOfferingId": "ceb6a579-cf4c-4343-be8b-d832c45ab51c"
      },
      {
         "OfferingType": "Heavy Utilization",
         "FixedPrice": "",
         "NodeType": "dw.hs1.8xlarge",
         "UsagePrice": "",
         "RecurringCharges": [
            {
            "RecurringChargeAmount": "",
            "RecurringChargeFrequency": "Hourly"
            } ],
         "Duration": 31536000,
         "ReservedNodeOfferingId": "e5a2ff3b-352d-4a9c-ad7d-373c4cab5dd2"
      },
      ...remaining output omitted...
   ],
   "ResponseMetadata": {
      "RequestId": "8b1a1a43-75ff-11e2-9666-e142fe91ddd1"
   }
}
```
リザーブドノードオファリングを購入する場合は、有効な *ReservedNodeOfferingId* を使用して `purchase-reserved-node-offering` を呼び出すことができます。  
有効な *ReservedNodeOfferingId* を使用する `purchase-reserved-node-offering`。  
 有効な *ReservedNodeOfferingId* の使用。  
*ReservedNodeOfferingId*。  
.  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedNodeOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-reserved-node-offerings.html)」を参照してください。

### `describe-reserved-nodes`
<a name="redshift_DescribeReservedNodes_cli_2_topic"></a>

次のコード例は、`describe-reserved-nodes` を使用する方法を示しています。

**AWS CLI**  
リザーブドノードを記述する この例は、購入したリザーブドノードオファリングを示しています。コマンド:  

```
aws redshift describe-reserved-nodes
```
結果:  

```
{
   "ResponseMetadata": {
      "RequestId": "bc29ce2e-7600-11e2-9949-4b361e7420b7"
   },
   "ReservedNodes": [
      {
         "OfferingType": "Heavy Utilization",
         "FixedPrice": "",
         "NodeType": "dw.hs1.xlarge",
         "ReservedNodeId": "1ba8e2e3-bc01-4d65-b35d-a4a3e931547e",
         "UsagePrice": "",
         "RecurringCharges": [
            {
               "RecurringChargeAmount": "",
               "RecurringChargeFrequency": "Hourly"
            } ],
         "NodeCount": 1,
         "State": "payment-pending",
         "StartTime": "2013-02-13T17:08:39.051Z",
         "Duration": 31536000,
         "ReservedNodeOfferingId": "ceb6a579-cf4c-4343-be8b-d832c45ab51c"
      }
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeReservedNodes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-reserved-nodes.html)」を参照してください。

### `describe-resize`
<a name="redshift_DescribeResize_cli_2_topic"></a>

次のコード例は、`describe-resize` を使用する方法を示しています。

**AWS CLI**  
サイズ変更を記述する この例では、クラスターの最新のサイズ変更について記述します。リクエストは、タイプ `dw.hs1.8xlarge` の 3 つのノードに対して行われました。コマンド:  

```
aws redshift describe-resize --cluster-identifier mycluster
```
結果:  

```
{
   "Status": "NONE",
   "TargetClusterType": "multi-node",
   "TargetNodeType": "dw.hs1.8xlarge",
   "ResponseMetadata": {
      "RequestId": "9f52b0b4-7733-11e2-aa9b-318b2909bd27"
   },
   "TargetNumberOfNodes": "3"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeResize](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-resize.html)」を参照してください。

### `describe-scheduled-actions`
<a name="redshift_DescribeScheduledActions_cli_2_topic"></a>

次のコード例は、`describe-scheduled-actions` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされたアクションを記述するには**  
次の `describe-scheduled-actions` の例では、現在スケジュールされているアクションの詳細を表示します。  

```
aws redshift describe-scheduled-actions
```
出力:  

```
{
    "ScheduledActions": [
        {
            "ScheduledActionName": "resizecluster",
            "TargetAction": {
                "ResizeCluster": {
                    "ClusterIdentifier": "mycluster",
                    "NumberOfNodes": 4,
                    "Classic": false
                }
            },
            "Schedule": "at(2019-12-10T00:07:00)",
            "IamRole": "arn:aws:iam::123456789012:role/myRedshiftRole",
            "State": "ACTIVE",
            "NextInvocations": [
                "2019-12-10T00:07:00Z"
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeScheduledActions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-scheduled-actions.html)」を参照してください。

### `describe-snapshot-copy-grants`
<a name="redshift_DescribeSnapshotCopyGrants_cli_2_topic"></a>

次のコード例は、`describe-snapshot-copy-grants` を使用する方法を示しています。

**AWS CLI**  
**スナップショットコピー権限を記述するには**  
次の `describe-snapshot-copy-grants` の例では、指定したクラスタースナップショットコピー権限を表示します。  

```
aws redshift describe-snapshot-copy-grants \
    --snapshot-copy-grant-name mysnapshotcopygrantname
```
出力:  

```
{
    "SnapshotCopyGrants": [
        {
            "SnapshotCopyGrantName": "mysnapshotcopygrantname",
            "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/bPxRfih3yCo8nvbEXAMPLEKEY",
            "Tags": []
        }
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift データベースの暗号化](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-db-encryption.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSnapshotCopyGrants](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-snapshot-copy-grants.html)」を参照してください。

### `describe-snapshot-schedules`
<a name="redshift_DescribeSnapshotSchedules_cli_2_topic"></a>

次のコード例は、`describe-snapshot-schedules` を使用する方法を示しています。

**AWS CLI**  
**スナップショットスケジュールを記述するには**  
次の `describe-snapshot-schedules` の例では、指定されたクラスタースナップショットスケジュールの詳細を表示します。  

```
aws redshift describe-snapshot-schedules \
    --cluster-identifier mycluster \
    --schedule-identifier mysnapshotschedule
```
出力:  

```
{
    "SnapshotSchedules": [
        {
            "ScheduleDefinitions": [
                "rate(12 hours)"
            ],
            "ScheduleIdentifier": "mysnapshotschedule",
            "ScheduleDescription": "My schedule description",
            "Tags": [],
            "AssociatedClusterCount": 1,
            "AssociatedClusters": [
                {
                    "ClusterIdentifier": "mycluster",
                    "ScheduleAssociationState": "ACTIVE"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[自動スナップショットのスケジュール](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#automated-snapshot-schedules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSnapshotSchedules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-snapshot-schedules.html)」を参照してください。

### `describe-storage`
<a name="redshift_DescribeStorage_cli_2_topic"></a>

次のコード例は、`describe-storage` を使用する方法を示しています。

**AWS CLI**  
**ストレージを記述するには**  
次の `describe-storage` の例では、アカウントのバックアップストレージとプロビジョナルストレージサイズの詳細を表示します。  

```
aws redshift describe-storage
```
出力:  

```
{
    "TotalBackupSizeInMegaBytes": 193149.0,
    "TotalProvisionedStorageInMegaBytes": 655360.0
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[スナップショットストレージの管理](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#managing-snapshot-storage)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStorage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-storage.html)」を参照してください。

### `describe-table-restore-status`
<a name="redshift_DescribeTableRestoreStatus_cli_2_topic"></a>

次のコード例は、`describe-table-restore-status` を使用する方法を示しています。

**AWS CLI**  
**クラスタースナップショットからテーブル復元リクエストのステータスを記述するには**  
次の `describe-table-restore-status` の例では、指定されたクラスターに対して行われたテーブル復元リクエストの詳細を表示します。  

```
aws redshift describe-table-restore-status /
    --cluster-identifier mycluster
```
出力:  

```
{
    "TableRestoreStatusDetails": [
        {
            "TableRestoreRequestId": "z1116630-0e80-46f4-ba86-bd9670411ebd",
            "Status": "IN_PROGRESS",
            "RequestTime": "2019-12-27T18:22:12.257Z",
            "ClusterIdentifier": "mycluster",
            "SnapshotIdentifier": "mysnapshotid",
            "SourceDatabaseName": "dev",
            "SourceSchemaName": "public",
            "SourceTableName": "mytable",
            "TargetDatabaseName": "dev",
            "TargetSchemaName": "public",
            "NewTableName": "mytable-clone"
        }
    ]
}
```
詳細については、「*Amazon Redshift 管理ガイド*」の「[スナップショットからのテーブルの復元](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#working-with-snapshot-restore-table-from-snapshot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTableRestoreStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-table-restore-status.html)」を参照してください。

### `describe-tags`
<a name="redshift_DescribeTags_cli_2_topic"></a>

次のコード例は、`describe-tags` を使用する方法を示しています。

**AWS CLI**  
**タグを記述するには**  
次の `describe-tags` の例では、指定されたタグ名と値に関連付けられた、指定されたクラスターのリソースを表示します。  

```
aws redshift describe-tags \
    --resource-name arn:aws:redshift:us-west-2:123456789012:cluster:mycluster \
    --tag-keys clustertagkey \
    --tag-values clustertagvalue
```
出力:  

```
{
    "TaggedResources": [
                    {
            "Tag": {
                "Key": "clustertagkey",
                "Value": "clustertagvalue"
            },
            "ResourceName": "arn:aws:redshift:us-west-2:123456789012:cluster:mycluster",
            "ResourceType": "cluster"
        }
    ]
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift のリソースへのタグ付け](https://docs.aws.amazon.com/redshift/latest/mgmt/amazon-redshift-tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/describe-tags.html)」を参照してください。

### `disable-snapshot-copy`
<a name="redshift_DisableSnapshotCopy_cli_2_topic"></a>

次のコード例は、`disable-snapshot-copy` を使用する方法を示しています。

**AWS CLI**  
**クラスターのスナップショットコピーを無効にするには**  
次の `disable-snapshot-copy` の例では、指定されたクラスターのスナップショットの自動コピーを無効にします。  

```
aws redshift disable-snapshot-copy \
    --cluster-identifier mycluster
```
出力:  

```
{
    "Cluster": {
        "ClusterIdentifier": "mycluster",
        "NodeType": "dc2.large",
        "ClusterStatus": "available",
        "ClusterAvailabilityStatus": "Available",
        "MasterUsername": "adminuser",
        "DBName": "dev",
        "Endpoint": {
            "Address": "mycluster.cmeaswqeuae.us-west-2.redshift.amazonaws.com",
            "Port": 5439
        },
        "ClusterCreateTime": "2019-12-05T18:44:36.991Z",
        "AutomatedSnapshotRetentionPeriod": 3,
        "ManualSnapshotRetentionPeriod": -1,
        "ClusterSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sh-i9b431cd",
                "Status": "active"
            }
        ],
        "ClusterParameterGroups": [
            {
                "ParameterGroupName": "default.redshift-1.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "ClusterSubnetGroupName": "default",
        "VpcId": "vpc-b1fel7t9",
        "AvailabilityZone": "us-west-2f",
        "PreferredMaintenanceWindow": "sat:16:00-sat:16:30",
        "PendingModifiedValues": {
            "NodeType": "dc2.large",
            "NumberOfNodes": 2,
            "ClusterType": "multi-node"
        },
        "ClusterVersion": "1.0",
        "AllowVersionUpgrade": true,
        "NumberOfNodes": 4,
        "PubliclyAccessible": false,
        "Encrypted": false,
        "Tags": [
            {
                "Key": "mytags",
                "Value": "tag1"
            }
        ],
        "EnhancedVpcRouting": false,
        "IamRoles": [
            {
                "IamRoleArn": "arn:aws:iam::123456789012:role/myRedshiftRole",
                "ApplyStatus": "in-sync"
            }
        ],
        "MaintenanceTrackName": "current",
        "DeferredMaintenanceWindows": [],
        "ExpectedNextSnapshotScheduleTime": "2019-12-10T04:42:43.390Z",
        "ExpectedNextSnapshotScheduleTimeStatus": "OnTrack",
        "NextMaintenanceWindowStartTime": "2019-12-14T16:00:00Z"
    }
}
```
詳細については、*「Amazon Redshift クラスター管理ガイド*[」の「別の AWS リージョンへのスナップショットのコピー](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#cross-region-snapshot-copy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableSnapshotCopy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/disable-snapshot-copy.html)」を参照してください。

### `enable-snapshot-copy`
<a name="redshift_EnableSnapshotCopy_cli_2_topic"></a>

次のコード例は、`enable-snapshot-copy` を使用する方法を示しています。

**AWS CLI**  
**クラスターのスナップショットコピーを有効にするには**  
次の `enable-snapshot-copy` の例では、指定されたクラスターのスナップショットの自動コピーを有効にします。  

```
aws redshift enable-snapshot-copy \
    --cluster-identifier mycluster \
    --destination-region us-west-1
```
出力:  

```
{
    "Cluster": {
        "ClusterIdentifier": "mycluster",
        "NodeType": "dc2.large",
        "ClusterStatus": "available",
        "ClusterAvailabilityStatus": "Available",
        "MasterUsername": "adminuser",
        "DBName": "dev",
        "Endpoint": {
            "Address": "mycluster.cmeaswqeuae.us-west-2.redshift.amazonaws.com",
            "Port": 5439
        },
        "ClusterCreateTime": "2019-12-05T18:44:36.991Z",
        "AutomatedSnapshotRetentionPeriod": 3,
        "ManualSnapshotRetentionPeriod": -1,
        "ClusterSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sh-f4c731cd",
                "Status": "active"
            }
        ],
        "ClusterParameterGroups": [
            {
                "ParameterGroupName": "default.redshift-1.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "ClusterSubnetGroupName": "default",
        "VpcId": "vpc-b1ael7t9",
        "AvailabilityZone": "us-west-2f",
        "PreferredMaintenanceWindow": "sat:16:00-sat:16:30",
        "PendingModifiedValues": {
            "NodeType": "dc2.large",
            "NumberOfNodes": 2,
            "ClusterType": "multi-node"
        },
        "ClusterVersion": "1.0",
        "AllowVersionUpgrade": true,
        "NumberOfNodes": 4,
        "PubliclyAccessible": false,
        "Encrypted": false,
        "ClusterSnapshotCopyStatus": {
            "DestinationRegion": "us-west-1",
            "RetentionPeriod": 7,
            "ManualSnapshotRetentionPeriod": -1
        },
        "Tags": [
            {
                "Key": "mytags",
                "Value": "tag1"
            }
        ],
        "EnhancedVpcRouting": false,
        "IamRoles": [
            {
                "IamRoleArn": "arn:aws:iam::123456789012:role/myRedshiftRole",
                "ApplyStatus": "in-sync"
            }
        ],
        "MaintenanceTrackName": "current",
        "DeferredMaintenanceWindows": [],
        "ExpectedNextSnapshotScheduleTime": "2019-12-10T04:42:43.390Z",
        "ExpectedNextSnapshotScheduleTimeStatus": "OnTrack",
        "NextMaintenanceWindowStartTime": "2019-12-14T16:00:00Z"
    }
}
```
詳細については、*「Amazon Redshift クラスター管理ガイド*[」の「別の AWS リージョンへのスナップショットのコピー](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#cross-region-snapshot-copy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableSnapshotCopy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/enable-snapshot-copy.html)」を参照してください。

### `get-cluster-credentials`
<a name="redshift_GetClusterCredentials_cli_2_topic"></a>

次の例は、`get-cluster-credentials` を使用する方法を説明しています。

**AWS CLI**  
** AWS アカウントのクラスター認証情報を取得するには**  
次の `get-cluster-credentials` の例では、Amazon Redshift データベースへのアクセスを有効にする一時的な認証情報を取得します。  

```
aws redshift get-cluster-credentials \
    --db-user adminuser --db-name dev \
    --cluster-identifier mycluster
```
出力:  

```
{
    "DbUser": "IAM:adminuser",
    "DbPassword": "AMAFUyyuros/QjxPTtgzcsuQsqzIasdzJEN04aCtWDzXx1O9d6UmpkBtvEeqFly/EXAMPLE==",
    "Expiration": "2019-12-10T17:25:05.770Z"
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift CLI または API を使用した IAM データベース認証情報の生成](https://docs.aws.amazon.com/redshift/latest/mgmt/generating-iam-credentials-cli-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetClusterCredentials](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/get-cluster-credentials.html)」を参照してください。

### `get-reserved-node-exchange-offerings`
<a name="redshift_GetReservedNodeExchangeOfferings_cli_2_topic"></a>

次のコード例は、`get-reserved-node-exchange-offerings` を使用する方法を示しています。

**AWS CLI**  
**リザーブドノード交換オファリングを取得するには**  
次の `get-reserved-node-exchange-offerings` の例では、指定された `DC1` リザーブドノードに一致する `DC2` `ReservedNodeOfferings` の配列を取得します。  

```
aws redshift get-reserved-node-exchange-offerings \
    --reserved-node-id 12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE
```
出力:  

```
{
    "ReservedNodeOfferings": [
        {
            "ReservedNodeOfferingId": "12345678-12ab-12a1-1a2a-12ab-12a12EXAMPLE",
            "NodeType": "dc2.large",
            "Duration": 31536000,
            "FixedPrice": 0.0,
            "UsagePrice": 0.0,
            "CurrencyCode": "USD",
            "OfferingType": "All Upfront",
            "RecurringCharges": [
                {
                    "RecurringChargeAmount": 0.0,
                    "RecurringChargeFrequency": "Hourly"
                }
            ],
            "ReservedNodeOfferingType": "Regular"
        }
    ]
}
```
詳細については、[「Amazon Redshift クラスター管理ガイド」の AWS 「 CLI を使用したリザーブドノードのアップグレード](https://docs.aws.amazon.com/redshift/latest/mgmt/purchase-reserved-node-offering-console.html)」を参照してください。 **  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetReservedNodeExchangeOfferings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/get-reserved-node-exchange-offerings.html)」を参照してください。

### `modify-cluster-iam-roles`
<a name="redshift_ModifyClusterIamRoles_cli_2_topic"></a>

次のコード例は、`modify-cluster-iam-roles` を使用する方法を示しています。

**AWS CLI**  
**クラスターの IAM ロールを変更するには**  
次の の`modify-cluster-iam-roles`例では、指定されたクラスターから指定された AWS IAM ロールを削除します。  

```
aws redshift modify-cluster-iam-roles \
    --cluster-identifier mycluster \
    --remove-iam-roles arn:aws:iam::123456789012:role/myRedshiftRole
```
出力:  

```
{
    "Cluster": {
        "ClusterIdentifier": "mycluster",
        "NodeType": "dc2.large",
        "ClusterStatus": "available",
        "ClusterAvailabilityStatus": "Available",
        "MasterUsername": "adminuser",
        "DBName": "dev",
        "Endpoint": {
            "Address": "mycluster.cmeaswqeuae.us-west-2.redshift.amazonaws.com",
            "Port": 5439
        },
        "ClusterCreateTime": "2019-12-05T18:44:36.991Z",
        "AutomatedSnapshotRetentionPeriod": 3,
        "ManualSnapshotRetentionPeriod": -1,
        "ClusterSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sh-f9b731sd",
                "Status": "active"
            }
        ],
        "ClusterParameterGroups": [
            {
                "ParameterGroupName": "default.redshift-1.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "ClusterSubnetGroupName": "default",
        "VpcId": "vpc-b2fal7t9",
        "AvailabilityZone": "us-west-2f",
        "PreferredMaintenanceWindow": "sat:16:00-sat:16:30",
        "PendingModifiedValues": {
            "NodeType": "dc2.large",
            "NumberOfNodes": 2,
            "ClusterType": "multi-node"
        },
        "ClusterVersion": "1.0",
        "AllowVersionUpgrade": true,
        "NumberOfNodes": 4,
        "PubliclyAccessible": false,
        "Encrypted": false,
        "ClusterSnapshotCopyStatus": {
            "DestinationRegion": "us-west-1",
            "RetentionPeriod": 7,
            "ManualSnapshotRetentionPeriod": -1
        },
        "Tags": [
            {
                "Key": "mytags",
                "Value": "tag1"
            }
        ],
        "EnhancedVpcRouting": false,
        "IamRoles": [],
        "MaintenanceTrackName": "current",
        "DeferredMaintenanceWindows": [],
        "ExpectedNextSnapshotScheduleTime": "2019-12-11T04:42:55.631Z",
        "ExpectedNextSnapshotScheduleTimeStatus": "OnTrack",
        "NextMaintenanceWindowStartTime": "2019-12-14T16:00:00Z"
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift でのアイデンティティベースのポリシー (IAM ポリシー) の使用](https://docs.aws.amazon.com/redshift/latest/mgmt/redshift-iam-access-control-identity-based.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClusterIamRoles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-cluster-iam-roles.html)」を参照してください。

### `modify-cluster-maintenance`
<a name="redshift_ModifyClusterMaintenance_cli_2_topic"></a>

次のコード例は、`modify-cluster-maintenance` を使用する方法を示しています。

**AWS CLI**  
**クラスターのメンテナンスを変更するには**  
次の `modify-cluster-maintenance` の例では、指定されたクラスターのメンテナンスを 30 日間延期します。  

```
aws redshift modify-cluster-maintenance \
    --cluster-identifier mycluster \
    --defer-maintenance \
    --defer-maintenance-duration 30
```
出力:  

```
{
    "Cluster": {
        "ClusterIdentifier": "mycluster",
        "NodeType": "dc2.large",
        "ClusterStatus": "available",
        "ClusterAvailabilityStatus": "Available",
        "MasterUsername": "adminuser",
        "DBName": "dev",
        "Endpoint": {
            "Address": "mycluster.cmeaswqeuae.us-west-2.redshift.amazonaws.com",
            "Port": 5439
        },
        "ClusterCreateTime": "2019-12-05T18:44:36.991Z",
        "AutomatedSnapshotRetentionPeriod": 3,
        "ManualSnapshotRetentionPeriod": -1,
        "ClusterSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sh-a1a123ab",
                "Status": "active"
            }
        ],
        "ClusterParameterGroups": [
            {
                "ParameterGroupName": "default.redshift-1.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "ClusterSubnetGroupName": "default",
        "VpcId": "vpc-b1ael7t9",
        "AvailabilityZone": "us-west-2f",
        "PreferredMaintenanceWindow": "sat:16:00-sat:16:30",
        "PendingModifiedValues": {
            "NodeType": "dc2.large",
            "NumberOfNodes": 2,
            "ClusterType": "multi-node"
        },
        "ClusterVersion": "1.0",
        "AllowVersionUpgrade": true,
        "NumberOfNodes": 4,
        "PubliclyAccessible": false,
        "Encrypted": false,
        "ClusterSnapshotCopyStatus": {
            "DestinationRegion": "us-west-1",
            "RetentionPeriod": 7,
            "ManualSnapshotRetentionPeriod": -1
        },
        "Tags": [
            {
                "Key": "mytags",
                "Value": "tag1"
            }
        ],
        "EnhancedVpcRouting": false,
        "IamRoles": [],
        "MaintenanceTrackName": "current",
        "DeferredMaintenanceWindows": [
            {
                "DeferMaintenanceIdentifier": "dfm-mUdVIfFcT1B4SGhw6fyF",
                "DeferMaintenanceStartTime": "2019-12-10T18:18:39.354Z",
                "DeferMaintenanceEndTime": "2020-01-09T18:18:39.354Z"
            }
        ],
        "ExpectedNextSnapshotScheduleTime": "2019-12-11T04:42:55.631Z",
        "ExpectedNextSnapshotScheduleTimeStatus": "OnTrack",
        "NextMaintenanceWindowStartTime": "2020-01-11T16:00:00Z"
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[クラスターのメンテナンス](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#rs-cluster-maintenance)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClusterMaintenance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-cluster-maintenance.html)」を参照してください。

### `modify-cluster-parameter-group`
<a name="redshift_ModifyClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`modify-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
**パラメータグループ内のパラメータを変更する**  
次の `modify-cluster-parameter-group` の例は、*wlm\$1json\$1configuration* パラメータを使用して、ワークロード管理を変更します。以下に示す JSON コンテンツを含むファイルからパラメータを受け入れます。  

```
aws redshift modify-cluster-parameter-group \
    --parameter-group-name myclusterparametergroup \
    --parameters file://modify_pg.json
```
`modify_pg.json` の内容:  

```
[
    {
        "ParameterName": "wlm_json_configuration",
        "ParameterValue": "[{\"user_group\":\"example_user_group1\",\"query_group\": \"example_query_group1\", \"query_concurrency\":7},{\"query_concurrency\":5}]"
    }
]
```
出力:  

```
{
   "ParameterGroupStatus": "Your parameter group has been updated but changes won't get applied until you reboot the associated Clusters.",
   "ParameterGroupName": "myclusterparametergroup",
   "ResponseMetadata": {
      "RequestId": "09974cc0-64cd-11e2-bea9-49e0ce183f07"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-cluster-parameter-group.html)」を参照してください。

### `modify-cluster-snapshot-schedule`
<a name="redshift_ModifyClusterSnapshotSchedule_cli_2_topic"></a>

次のコード例は、`modify-cluster-snapshot-schedule` を使用する方法を示しています。

**AWS CLI**  
**クラスタースナップショットのスケジュールを変更するには**  
次の `modify-cluster-snapshot-schedule` の例では、指定されたクラスターから指定されたスナップショットスケジュールを削除します。  

```
aws redshift modify-cluster-snapshot-schedule \
    --cluster-identifier mycluster \
    --schedule-identifier mysnapshotschedule \
    --disassociate-schedule
```
このコマンドでは、出力が生成されません。  
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[自動スナップショットのスケジュール](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#automated-snapshot-schedules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClusterSnapshotSchedule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-cluster-snapshot-schedule.html)」を参照してください。

### `modify-cluster-snapshot`
<a name="redshift_ModifyClusterSnapshot_cli_2_topic"></a>

次のコード例は、`modify-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**クラスタースナップショットを変更するには**  
次の `modify-cluster-snapshot` の例では、指定されたクラスタースナップショットの手動保持期間設定を 10 日の値に設定します。  

```
aws redshift modify-cluster-snapshot \
    --snapshot-identifier mycluster-2019-11-06-16-32 \
    --manual-snapshot-retention-period 10
```
出力:  

```
{
    "Snapshot": {
        "SnapshotIdentifier": "mycluster-2019-11-06-16-32",
        "ClusterIdentifier": "mycluster",
        "SnapshotCreateTime": "2019-12-07T00:34:05.633Z",
        "Status": "available",
        "Port": 5439,
        "AvailabilityZone": "us-west-2f",
        "ClusterCreateTime": "2019-12-05T18:44:36.991Z",
        "MasterUsername": "adminuser",
        "ClusterVersion": "1.0",
        "SnapshotType": "manual",
        "NodeType": "dc2.large",
        "NumberOfNodes": 2,
        "DBName": "dev",
        "VpcId": "vpc-b1cel7t9",
        "Encrypted": false,
        "EncryptedWithHSM": false,
        "OwnerAccount": "123456789012",
        "TotalBackupSizeInMegaBytes": 64384.0,
        "ActualIncrementalBackupSizeInMegaBytes": 24.0,
        "BackupProgressInMegaBytes": 24.0,
        "CurrentBackupRateInMegaBytesPerSecond": 13.0011,
        "EstimatedSecondsToCompletion": 0,
        "ElapsedTimeInSeconds": 1,
        "Tags": [
            {
                "Key": "mytagkey",
                "Value": "mytagvalue"
            }
        ],
        "EnhancedVpcRouting": false,
        "MaintenanceTrackName": "current",
        "ManualSnapshotRetentionPeriod": 10,
        "ManualSnapshotRemainingDays": 6,
        "SnapshotRetentionStartTime": "2019-12-07T00:34:07.479Z"
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift スナップショット](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-cluster-snapshot.html)」を参照してください。

### `modify-cluster-subnet-group`
<a name="redshift_ModifyClusterSubnetGroup_cli_2_topic"></a>

次のコード例は、`modify-cluster-subnet-group` を使用する方法を示しています。

**AWS CLI**  
クラスターサブネットグループのサブネットを変更する この例は、キャッシュサブネットグループ内のサブネットのリストを変更する方法を示しています。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift modify-cluster-subnet-group --cluster-subnet-group-name mysubnetgroup --subnet-ids subnet-763fdd1 subnet-ac830e9
```
結果:  

```
{
   "ClusterSubnetGroup":
   {
      "Subnets": [
         {
            "SubnetStatus": "Active",
            "SubnetIdentifier": "subnet-763fdd1c",
            "SubnetAvailabilityZone":
               { "Name": "us-east-1a" }
         },
         {
            "SubnetStatus": "Active",
            "SubnetIdentifier": "subnet-ac830e9",
            "SubnetAvailabilityZone":
               { "Name": "us-east-1b" }
         } ],
      "VpcId": "vpc-7e3fdd14",
      "SubnetGroupStatus": "Complete",
      "Description": "My subnet group",
      "ClusterSubnetGroupName": "mysubnetgroup"
   },
   "ResponseMetadata": {
      "RequestId": "8da93e89-8372-f936-93a8-873918938197a"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyClusterSubnetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-cluster-subnet-group.html)」を参照してください。

### `modify-cluster`
<a name="redshift_ModifyCluster_cli_2_topic"></a>

次のコード例は、`modify-cluster` を使用する方法を示しています。

**AWS CLI**  
この例は、クラスターセキュリティグループを指定されたクラスターに関連付ける方法を示しています。コマンドは次のとおりです。  

```
aws redshift modify-cluster --cluster-identifier mycluster --cluster-security-groups mysecuritygroup
```
この例は、各週のクラスターの優先メンテナンスウィンドウを、日曜日の午後 11 時 15 分から月曜日の午前 3 時 15 分までの 4 時間に変更する方法を示しています。コマンドは次のとおりです。  

```
aws redshift modify-cluster --cluster-identifier mycluster --preferred-maintenance-window Sun:23:15-Mon:03:15
```
この例では、クラスターのマスターパスワードを変更する方法を示しています。コマンドは次のとおりです。  

```
aws redshift modify-cluster --cluster-identifier mycluster --master-user-password A1b2c3d4
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[ModifyCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-cluster.html)」を参照してください。

### `modify-event-subscription`
<a name="redshift_ModifyEventSubscription_cli_2_topic"></a>

次のコード例は、`modify-event-subscription` を使用する方法を示しています。

**AWS CLI**  
**イベントサブスクリプションを変更するには**  
次の `modify-event-subscription` の例では、指定したイベント通知サブスクリプションを無効にします。  

```
aws redshift modify-event-subscription \
    --subscription-name mysubscription \
    --no-enabled
```
出力:  

```
{
    "EventSubscription": {
        "CustomerAwsId": "123456789012",
        "CustSubscriptionId": "mysubscription",
        "SnsTopicArn": "arn:aws:sns:us-west-2:123456789012:MySNStopic",
        "Status": "active",
        "SubscriptionCreationTime": "2019-12-09T21:50:21.332Z",
        "SourceIdsList": [],
        "EventCategoriesList": [
            "management"
        ],
        "Severity": "ERROR",
        "Enabled": false,
        "Tags": []
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift イベント通知のサブスクライブ](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-event-notifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyEventSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-event-subscription.html)」を参照してください。

### `modify-scheduled-action`
<a name="redshift_ModifyScheduledAction_cli_2_topic"></a>

次のコード例は、`modify-scheduled-action` を使用する方法を示しています。

**AWS CLI**  
**スケジュールされたアクションを編集するには**  
次の `modify-scheduled-action` の例では、指定された既存のスケジュールされたアクションに説明を追加します。  

```
aws redshift modify-scheduled-action \
    --scheduled-action-name myscheduledaction \
    --scheduled-action-description "My scheduled action"
```
出力:  

```
{
    "ScheduledActionName": "myscheduledaction",
    "TargetAction": {
        "ResizeCluster": {
            "ClusterIdentifier": "mycluster",
            "NumberOfNodes": 2,
            "Classic": false
        }
    },
    "Schedule": "at(2019-12-25T00:00:00)",
    "IamRole": "arn:aws:iam::123456789012:role/myRedshiftRole",
    "ScheduledActionDescription": "My scheduled action",
    "State": "ACTIVE",
    "NextInvocations": [
        "2019-12-25T00:00:00Z"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyScheduledAction](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-scheduled-action.html)」を参照してください。

### `modify-snapshot-copy-retention-period`
<a name="redshift_ModifySnapshotCopyRetentionPeriod_cli_2_topic"></a>

次のコード例は、`modify-snapshot-copy-retention-period` を使用する方法を示しています。

**AWS CLI**  
**スナップショットコピー保持期間を変更するには**  
次の の`modify-snapshot-copy-retention-period`例では、コピー元 AWS リージョンからコピーされた後、コピー先 AWS リージョンで指定されたクラスターのスナップショットを保持する日数を変更します。  

```
aws redshift modify-snapshot-copy-retention-period \
    --cluster-identifier mycluster \
    --retention-period 15
```
出力:  

```
{
    "Cluster": {
        "ClusterIdentifier": "mycluster",
        "NodeType": "dc2.large",
        "ClusterStatus": "available",
        "ClusterAvailabilityStatus": "Available",
        "MasterUsername": "adminuser",
        "DBName": "dev",
        "Endpoint": {
            "Address": "mycluster.cmeaswqeuae.us-west-2.redshift.amazonaws.com",
            "Port": 5439
        },
        "ClusterCreateTime": "2019-12-05T18:44:36.991Z",
        "AutomatedSnapshotRetentionPeriod": 3,
        "ManualSnapshotRetentionPeriod": -1,
        "ClusterSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sh-a1a123ab",
                "Status": "active"
            }
        ],
        "ClusterParameterGroups": [
            {
                "ParameterGroupName": "default.redshift-1.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "ClusterSubnetGroupName": "default",
        "VpcId": "vpc-b1fet7t9",
        "AvailabilityZone": "us-west-2f",
        "PreferredMaintenanceWindow": "sat:16:00-sat:16:30",
        "PendingModifiedValues": {
            "NodeType": "dc2.large",
            "NumberOfNodes": 2,
            "ClusterType": "multi-node"
        },
        "ClusterVersion": "1.0",
        "AllowVersionUpgrade": true,
        "NumberOfNodes": 4,
        "PubliclyAccessible": false,
        "Encrypted": false,
        "ClusterSnapshotCopyStatus": {
            "DestinationRegion": "us-west-1",
            "RetentionPeriod": 15,
            "ManualSnapshotRetentionPeriod": -1
        },
        "Tags": [
            {
                "Key": "mytags",
                "Value": "tag1"
            }
        ],
        "EnhancedVpcRouting": false,
        "IamRoles": [],
        "MaintenanceTrackName": "current",
        "DeferredMaintenanceWindows": [
            {
                "DeferMaintenanceIdentifier": "dfm-mUdVSfDcT1F4SGhw6fyF",
                "DeferMaintenanceStartTime": "2019-12-10T18:18:39.354Z",
                "DeferMaintenanceEndTime": "2020-01-09T18:18:39.354Z"
            }
        ],
        "NextMaintenanceWindowStartTime": "2020-01-11T16:00:00Z"
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[スナップショットスケジュール形式](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#working-with-snapshot-scheduling)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifySnapshotCopyRetentionPeriod](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-snapshot-copy-retention-period.html)」を参照してください。

### `modify-snapshot-schedule`
<a name="redshift_ModifySnapshotSchedule_cli_2_topic"></a>

次のコード例は、`modify-snapshot-schedule` を使用する方法を示しています。

**AWS CLI**  
**スナップショットのスケジュールを変更するには**  
次の `modify-snapshot-schedule` の例では、指定されたスナップショットスケジュールのレートを 10 時間ごとに変更します。  

```
aws redshift modify-snapshot-schedule \
    --schedule-identifier mysnapshotschedule \
    --schedule-definitions "rate(10 hours)"
```
出力:  

```
{
    "ScheduleDefinitions": [
        "rate(10 hours)"
    ],
    "ScheduleIdentifier": "mysnapshotschedule",
    "ScheduleDescription": "My schedule description",
    "Tags": []
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[スナップショットスケジュール形式](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#working-with-snapshot-scheduling)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifySnapshotSchedule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/modify-snapshot-schedule.html)」を参照してください。

### `purchase-reserved-node-offering`
<a name="redshift_PurchaseReservedNodeOffering_cli_2_topic"></a>

次のコード例は、`purchase-reserved-node-offering` を使用する方法を示しています。

**AWS CLI**  
リザーブドノードを購入する この例は、リザーブドノードオファリングを購入する方法を示しています。`reserved-node-offering-id` は、`describe-reserved-node-offerings` を呼び出すことにより取得します。コマンド:  

```
aws redshift purchase-reserved-node-offering --reserved-node-offering-id ceb6a579-cf4c-4343-be8b-d832c45ab51c
```
結果:  

```
{
   "ReservedNode": {
      "OfferingType": "Heavy Utilization",
      "FixedPrice": "",
      "NodeType": "dw.hs1.xlarge",
      "ReservedNodeId": "1ba8e2e3-bc01-4d65-b35d-a4a3e931547e",
      "UsagePrice": "",
      "RecurringCharges": [
         {
            "RecurringChargeAmount": "",
            "RecurringChargeFrequency": "Hourly"
         }
      ],
      "NodeCount": 1,
      "State": "payment-pending",
      "StartTime": "2013-02-13T17:08:39.051Z",
      "Duration": 31536000,
      "ReservedNodeOfferingId": "ceb6a579-cf4c-4343-be8b-d832c45ab51c"
   },
   "ResponseMetadata": {
      "RequestId": "01bda7bf-7600-11e2-b605-2568d7396e7f"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurchaseReservedNodeOffering](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/purchase-reserved-node-offering.html)」を参照してください。

### `reboot-cluster`
<a name="redshift_RebootCluster_cli_2_topic"></a>

次のコード例は、`reboot-cluster` を使用する方法を示しています。

**AWS CLI**  
クラスターを再起動する この例では、クラスターを再起動します。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift reboot-cluster --cluster-identifier mycluster
```
結果:  

```
{
   "Cluster": {
      "NodeType": "dw.hs1.xlarge",
      "Endpoint": {
         "Port": 5439,
         "Address": "mycluster.coqoarplqhsn.us-east-1.redshift.amazonaws.com"
      },
      "ClusterVersion": "1.0",
      "PubliclyAccessible": "true",
      "MasterUsername": "adminuser",
      "ClusterParameterGroups": [
         {
         "ParameterApplyStatus": "in-sync",
         "ParameterGroupName": "default.redshift-1.0"
         }
      ],
      "ClusterSecurityGroups": [
         {
         "Status": "active",
         "ClusterSecurityGroupName": "default"
         }
      ],
      "AllowVersionUpgrade": true,
      "VpcSecurityGroups": \[],
      "AvailabilityZone": "us-east-1a",
      "ClusterCreateTime": "2013-01-22T21:59:29.559Z",
      "PreferredMaintenanceWindow": "sun:23:15-mon:03:15",
      "AutomatedSnapshotRetentionPeriod": 1,
      "ClusterStatus": "rebooting",
      "ClusterIdentifier": "mycluster",
      "DBName": "dev",
      "NumberOfNodes": 2,
      "PendingModifiedValues": {}
   },
   "ResponseMetadata": {
      "RequestId": "61c8b564-64e8-11e2-8f7d-3b939af52818"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/reboot-cluster.html)」を参照してください。

### `reset-cluster-parameter-group`
<a name="redshift_ResetClusterParameterGroup_cli_2_topic"></a>

次のコード例は、`reset-cluster-parameter-group` を使用する方法を示しています。

**AWS CLI**  
パラメータのパラメータをリセットする この例は、パラメータグループのすべてのパラメータをリセットする方法を示しています。コマンド:  

```
aws redshift reset-cluster-parameter-group --parameter-group-name myclusterparametergroup --reset-all-parameters
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetClusterParameterGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/reset-cluster-parameter-group.html)」を参照してください。

### `resize-cluster`
<a name="redshift_ResizeCluster_cli_2_topic"></a>

次のコード例は、`resize-cluster` を使用する方法を示しています。

**AWS CLI**  
**クラスターのサイズを変更するには**  
次の `resize-cluster` の例は、指定したクラスターのサイズを変更します。  

```
aws redshift resize-cluster \
    --cluster-identifier mycluster \
    --cluster-type multi-node \
    --node-type dc2.large \
    --number-of-nodes 6 \
    --classic
```
出力:  

```
{
    "Cluster": {
        "ClusterIdentifier": "mycluster",
        "NodeType": "dc2.large",
        "ClusterStatus": "resizing",
        "ClusterAvailabilityStatus": "Modifying",
        "MasterUsername": "adminuser",
        "DBName": "dev",
        "Endpoint": {
            "Address": "mycluster.cmeaswqeuae.us-west-2.redshift.amazonaws.com",
            "Port": 5439
        },
        "ClusterCreateTime": "2019-12-05T18:44:36.991Z",
        "AutomatedSnapshotRetentionPeriod": 3,
        "ManualSnapshotRetentionPeriod": -1,
        "ClusterSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sh-a1a123ab",
                "Status": "active"
            }
        ],
        "ClusterParameterGroups": [
            {
                "ParameterGroupName": "default.redshift-1.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "ClusterSubnetGroupName": "default",
        "VpcId": "vpc-a1abc1a1",
        "AvailabilityZone": "us-west-2f",
        "PreferredMaintenanceWindow": "sat:16:00-sat:16:30",
        "PendingModifiedValues": {
            "NodeType": "dc2.large",
            "NumberOfNodes": 6,
            "ClusterType": "multi-node"
        },
        "ClusterVersion": "1.0",
        "AllowVersionUpgrade": true,
        "NumberOfNodes": 4,
        "PubliclyAccessible": false,
        "Encrypted": false,
        "ClusterSnapshotCopyStatus": {
            "DestinationRegion": "us-west-1",
            "RetentionPeriod": 15,
            "ManualSnapshotRetentionPeriod": -1
        },
        "Tags": [
            {
                "Key": "mytags",
                "Value": "tag1"
            }
        ],
        "EnhancedVpcRouting": false,
        "IamRoles": [],
        "MaintenanceTrackName": "current",
        "DeferredMaintenanceWindows": [
            {
                "DeferMaintenanceIdentifier": "dfm-mUdVCfDcT1B4SGhw6fyF",
                "DeferMaintenanceStartTime": "2019-12-10T18:18:39.354Z",
                "DeferMaintenanceEndTime": "2020-01-09T18:18:39.354Z"
            }
        ],
        "NextMaintenanceWindowStartTime": "2020-01-11T16:00:00Z",
        "ResizeInfo": {
            "ResizeType": "ClassicResize",
            "AllowCancelResize": true
        }
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[クラスターのサイズ調整](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html#cluster-resize-intro)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResizeCluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/resize-cluster.html)」を参照してください。

### `restore-from-cluster-snapshot`
<a name="redshift_RestoreFromClusterSnapshot_cli_2_topic"></a>

次のコード例は、`restore-from-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
スナップショットからクラスターを復元する この例では、スナップショットからクラスターを復元します。コマンド:  

```
aws redshift restore-from-cluster-snapshot --cluster-identifier mycluster-clone --snapshot-identifier my-snapshot-id
```
結果:  

```
{
   "Cluster": {
      "NodeType": "dw.hs1.xlarge",
      "ClusterVersion": "1.0",
      "PubliclyAccessible": "true",
      "MasterUsername": "adminuser",
      "ClusterParameterGroups": [
         {
         "ParameterApplyStatus": "in-sync",
         "ParameterGroupName": "default.redshift-1.0"
         }
      ],
      "ClusterSecurityGroups": [
         {
         "Status": "active",
         "ClusterSecurityGroupName": "default"
         }
      ],
      "AllowVersionUpgrade": true,
      "VpcSecurityGroups": \[],
      "PreferredMaintenanceWindow": "sun:23:15-mon:03:15",
      "AutomatedSnapshotRetentionPeriod": 1,
      "ClusterStatus": "creating",
      "ClusterIdentifier": "mycluster-clone",
      "DBName": "dev",
      "NumberOfNodes": 2,
      "PendingModifiedValues": {}
   },
   "ResponseMetadata": {
      "RequestId": "77fd512b-64e3-11e2-8f5b-e90bd6c77476"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreFromClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/restore-from-cluster-snapshot.html)」を参照してください。

### `restore-table-from-cluster-snapshot`
<a name="redshift_RestoreTableFromClusterSnapshot_cli_2_topic"></a>

次のコード例は、`restore-table-from-cluster-snapshot` を使用する方法を示しています。

**AWS CLI**  
**スナップショットからテーブルを復元するには**  
次の `restore-table-from-cluster-snapshot` の例では、指定されたクラスタースナップショットの指定されたテーブルから新しいテーブルを作成します。  

```
aws redshift restore-table-from-cluster-snapshot /
    --cluster-identifier mycluster /
    --snapshot-identifier mycluster-2019-11-19-16-17 /
    --source-database-name dev /
    --source-schema-name public /
    --source-table-name mytable /
    --target-database-name dev /
    --target-schema-name public /
    --new-table-name mytable-clone
```
出力:  

```
{
    "TableRestoreStatus": {
        "TableRestoreRequestId": "a123a12b-abc1-1a1a-a123-a1234ab12345",
        "Status": "PENDING",
        "RequestTime": "2019-12-20T00:20:16.402Z",
        "ClusterIdentifier": "mycluster",
        "SnapshotIdentifier": "mycluster-2019-11-19-16-17",
        "SourceDatabaseName": "dev",
        "SourceSchemaName": "public",
        "SourceTableName": "mytable",
        "TargetDatabaseName": "dev",
        "TargetSchemaName": "public",
        "NewTableName": "mytable-clone"
    }
}
```
詳細については、「*Amazon Redshift 管理ガイド*」の「[スナップショットからのテーブルの復元](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html#working-with-snapshot-restore-table-from-snapshot)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[RestoreTableFromClusterSnapshot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/restore-table-from-cluster-snapshot.html)」を参照してください。

### `revoke-cluster-security-group-ingress`
<a name="redshift_RevokeClusterSecurityGroupIngress_cli_2_topic"></a>

次のコード例は、`revoke-cluster-security-group-ingress` を使用する方法を示しています。

**AWS CLI**  
EC2 セキュリティグループへのアクセスを取り消す この例では、名前付き Amazon EC2 セキュリティグループへのアクセスを取り消します。コマンド:  

```
aws redshift revoke-cluster-security-group-ingress --cluster-security-group-name mysecuritygroup --ec2-security-group-name myec2securitygroup --ec2-security-group-owner-id 123445677890
```
CIDR 範囲へのアクセスを取り消す この例では、CIDR 範囲へのアクセスを取り消します。コマンド:  

```
aws redshift revoke-cluster-security-group-ingress --cluster-security-group-name mysecuritygroup --cidrip 192.168.100.100/32
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokeClusterSecurityGroupIngress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/revoke-cluster-security-group-ingress.html)」を参照してください。

### `revoke-snapshot-access`
<a name="redshift_RevokeSnapshotAccess_cli_2_topic"></a>

次の例は、`revoke-snapshot-access` を使用する方法を説明しています。

**AWS CLI**  
スナップショットを復元する AWS アカウントの認可を取り消す SnapshotThis、スナップショットを復元`444455556666`する AWS アカウントの認可を取り消します`my-snapshot-id`。デフォルトの出力は JSON 形式です。コマンドは次のとおりです。  

```
aws redshift revoke-snapshot-access --snapshot-id my-snapshot-id --account-with-restore-access 444455556666
```
結果:  

```
{
   "Snapshot": {
      "Status": "available",
      "SnapshotCreateTime": "2013-07-17T22:04:18.947Z",
      "EstimatedSecondsToCompletion": 0,
      "AvailabilityZone": "us-east-1a",
      "ClusterVersion": "1.0",
      "MasterUsername": "adminuser",
      "Encrypted": false,
      "OwnerAccount": "111122223333",
      "BackupProgressInMegabytes": 11.0,
      "ElapsedTimeInSeconds": 0,
      "DBName": "dev",
      "CurrentBackupRateInMegabytesPerSecond: 0.1534,
      "ClusterCreateTime": "2013-01-22T21:59:29.559Z",
      "ActualIncrementalBackupSizeInMegabytes"; 11.0,
      "SnapshotType": "manual",
      "NodeType": "dw.hs1.xlarge",
      "ClusterIdentifier": "mycluster",
      "TotalBackupSizeInMegabytes": 20.0,
      "Port": 5439,
      "NumberOfNodes": 2,
      "SnapshotIdentifier": "my-snapshot-id"
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RevokeSnapshotAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/revoke-snapshot-access.html)」を参照してください。

### `rotate-encryption-key`
<a name="redshift_RotateEncryptionKey_cli_2_topic"></a>

次のコード例は、`rotate-encryption-key` を使用する方法を示しています。

**AWS CLI**  
**クラスターの暗号化キーをローテーションするには**  
次の `rotate-encryption-key` の例では、指定されたクラスターの暗号化キーをローテーションします。  

```
aws redshift rotate-encryption-key \
    --cluster-identifier mycluster
```
出力:  

```
{
    "Cluster": {
        "ClusterIdentifier": "mycluster",
        "NodeType": "dc2.large",
        "ClusterStatus": "rotating-keys",
        "ClusterAvailabilityStatus": "Modifying",
        "MasterUsername": "adminuser",
        "DBName": "dev",
        "Endpoint": {
            "Address": "mycluster.cmeaswqeuae.us-west-2.redshift.amazonaws.com",
            "Port": 5439
        },
        "ClusterCreateTime": "2019-12-10T19:25:45.886Z",
        "AutomatedSnapshotRetentionPeriod": 30,
        "ManualSnapshotRetentionPeriod": -1,
        "ClusterSecurityGroups": [],
        "VpcSecurityGroups": [
            {
                "VpcSecurityGroupId": "sh-a1a123ab",
                "Status": "active"
            }
        ],
        "ClusterParameterGroups": [
            {
                "ParameterGroupName": "default.redshift-1.0",
                "ParameterApplyStatus": "in-sync"
            }
        ],
        "ClusterSubnetGroupName": "default",
        "VpcId": "vpc-a1abc1a1",
        "AvailabilityZone": "us-west-2a",
        "PreferredMaintenanceWindow": "sat:16:00-sat:16:30",
        "PendingModifiedValues": {},
        "ClusterVersion": "1.0",
        "AllowVersionUpgrade": true,
        "NumberOfNodes": 2,
        "PubliclyAccessible": false,
        "Encrypted": true,
        "Tags": [],
        "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/bPxRfih3yCo8nvbEXAMPLEKEY",
        "EnhancedVpcRouting": false,
        "IamRoles": [
            {
                "IamRoleArn": "arn:aws:iam::123456789012:role/myRedshiftRole",
                "ApplyStatus": "in-sync"
            }
        ],
        "MaintenanceTrackName": "current",
        "DeferredMaintenanceWindows": [],
        "NextMaintenanceWindowStartTime": "2019-12-14T16:00:00Z"
    }
}
```
詳細については、「*Amazon Redshift クラスター管理ガイド*」の「[Amazon Redshift データベースの暗号化](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-db-encryption.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RotateEncryptionKey](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/redshift/rotate-encryption-key.html)」を参照してください。

# を使用した Amazon Rekognition の例 AWS CLI
<a name="cli_2_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `compare-faces`
<a name="rekognition_CompareFaces_cli_2_topic"></a>

次のコード例は、`compare-faces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を比較する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)」を参照してください。

**AWS CLI**  
**2 つの画像内の顔を比較するには**  
次の `compare-faces` コマンドは、Amazon S3 バケットに保存されている 2 つの画像の顔を比較します。  

```
aws rekognition compare-faces \
    --source-image '{"S3Object":{"Bucket":"MyImageS3Bucket","Name":"source.jpg"}}' \
    --target-image '{"S3Object":{"Bucket":"MyImageS3Bucket","Name":"target.jpg"}}'
```
出力:  

```
{
    "UnmatchedFaces": [],
    "FaceMatches": [
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.12368916720151901,
                    "Top": 0.16007372736930847,
                    "Left": 0.5901257991790771,
                    "Height": 0.25140416622161865
                },
                "Confidence": 100.0,
                "Pose": {
                    "Yaw": -3.7351467609405518,
                    "Roll": -0.10309021919965744,
                    "Pitch": 0.8637830018997192
                },
                "Quality": {
                    "Sharpness": 95.51618957519531,
                    "Brightness": 65.29893493652344
                },
                "Landmarks": [
                    {
                        "Y": 0.26721030473709106,
                        "X": 0.6204193830490112,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.26831310987472534,
                        "X": 0.6776827573776245,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.3514654338359833,
                        "X": 0.6241428852081299,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.35258132219314575,
                        "X": 0.6713621020317078,
                        "Type": "mouthRight"
                    },
                    {
                        "Y": 0.3140771687030792,
                        "X": 0.6428444981575012,
                        "Type": "nose"
                    }
                ]
            },
            "Similarity": 100.0
        }
    ],
    "SourceImageFace": {
        "BoundingBox": {
            "Width": 0.12368916720151901,
            "Top": 0.16007372736930847,
            "Left": 0.5901257991790771,
            "Height": 0.25140416622161865
        },
        "Confidence": 100.0
    }
}
```
詳細については、「Amazon Rekognition ディベロッパーガイド」の「[イメージ間の顔の比較](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「*CompareFaces*」を参照してください。[https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/compare-faces.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/compare-faces.html)

### `create-collection`
<a name="rekognition_CreateCollection_cli_2_topic"></a>

次のコード例は、`create-collection` を使用する方法を示しています。

詳細については、「[コレクションを作成する](https://docs.aws.amazon.com/rekognition/latest/dg/create-collection-procedure.html)」を参照してください。

**AWS CLI**  
**コレクションを作成するには**  
次の `create-collection` コマンドは、指定された名前のコレクションを作成します。  

```
aws rekognition create-collection \
    --collection-id "MyCollection"
```
出力:  

```
{
    "CollectionArn": "aws:rekognition:us-west-2:123456789012:collection/MyCollection",
    "FaceModelVersion": "4.0",
    "StatusCode": 200
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[コレクションの作成](https://docs.aws.amazon.com/rekognition/latest/dg/create-collection-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateCollection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/create-collection.html)」を参照してください。**

### `create-stream-processor`
<a name="rekognition_CreateStreamProcessor_cli_2_topic"></a>

次のコード例は、`create-stream-processor` を使用する方法を示しています。

**AWS CLI**  
**新しいストリームプロセッサを作成するには**  
次の `create-stream-processor` の例では、指定された設定で新しいストリームプロセッサを作成します。  

```
aws rekognition create-stream-processor --name my-stream-processor\
    --input '{"KinesisVideoStream":{"Arn":"arn:aws:kinesisvideo:us-west-2:123456789012:stream/macwebcam/1530559711205"}}'\
    --stream-processor-output '{"KinesisDataStream":{"Arn":"arn:aws:kinesis:us-west-2:123456789012:stream/AmazonRekognitionRekStream"}}'\
    --role-arn arn:aws:iam::123456789012:role/AmazonRekognitionDetect\
    --settings '{"FaceSearch":{"CollectionId":"MyCollection","FaceMatchThreshold":85.5}}'
```
出力:  

```
{
    "StreamProcessorArn": "arn:aws:rekognition:us-west-2:123456789012:streamprocessor/my-stream-processor"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ストリーミングビデオの使用](https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateStreamProcessor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/create-stream-processor.html)」を参照してください。

### `delete-collection`
<a name="rekognition_DeleteCollection_cli_2_topic"></a>

次のコード例は、`delete-collection` を使用する方法を示しています。

詳細については、「[コレクションを削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-collection-procedure.html)」を参照してください。

**AWS CLI**  
**コレクションを削除するには**  
次の `delete-collection` コマンドは、指定されたコレクションを削除します。  

```
aws rekognition delete-collection \
    --collection-id MyCollection
```
出力:  

```
{
    "StatusCode": 200
}
```
詳細については、「Amazon Rekognition ディベロッパーガイド」の「[コレクションの削除](https://docs.aws.amazon.com/rekognition/latest/dg/delete-collection-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteCollection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/delete-collection.html)」を参照してください。**

### `delete-faces`
<a name="rekognition_DeleteFaces_cli_2_topic"></a>

次のコード例は、`delete-faces` を使用する方法を示しています。

詳細については、「[コレクションから顔を削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-faces-procedure.html)」を参照してください。

**AWS CLI**  
**コレクションから顔を削除するには**  
次の `delete-faces` コマンドは、コレクションから指定された顔を削除します。  

```
aws rekognition delete-faces \
    --collection-id MyCollection
    --face-ids '["0040279c-0178-436e-b70a-e61b074e96b0"]'
```
出力:  

```
{
    "DeletedFaces": [
        "0040279c-0178-436e-b70a-e61b074e96b0"
    ]
}
```
詳細については、「Amazon Rekognition ディベロッパーガイド」の「[コレクションからの顔の削除](https://docs.aws.amazon.com/rekognition/latest/dg/delete-faces-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[DeleteFaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/delete-faces.html)」を参照してください。

### `delete-stream-processor`
<a name="rekognition_DeleteStreamProcessor_cli_2_topic"></a>

次のコード例は、`delete-stream-processor` を使用する方法を示しています。

**AWS CLI**  
**ストリームプロセッサを削除するには**  
次の `delete-stream-processor` コマンドを実行して、指定されたストリームプロセッサを削除します。  

```
aws rekognition delete-stream-processor \
    --name my-stream-processor
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ストリーミングビデオの使用](https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteStreamProcessor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/delete-stream-processor.html)」を参照してください。

### `describe-collection`
<a name="rekognition_DescribeCollection_cli_2_topic"></a>

次のコード例は、`describe-collection` を使用する方法を示しています。

詳細については、「[コレクションを定義する](https://docs.aws.amazon.com/rekognition/latest/dg/describe-collection-procedure.html)」を参照してください。

**AWS CLI**  
**コレクションを記述するには**  
次の `describe-collection` の例は、指定されたコレクションの詳細を表示します。  

```
aws rekognition describe-collection \
    --collection-id MyCollection
```
出力:  

```
{
    "FaceCount": 200,
    "CreationTimestamp": 1569444828.274,
    "CollectionARN": "arn:aws:rekognition:us-west-2:123456789012:collection/MyCollection",
    "FaceModelVersion": "4.0"
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[コレクションの定義](https://docs.aws.amazon.com/rekognition/latest/dg/describe-collection-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeCollection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/describe-collection.html)」を参照してください。**

### `describe-stream-processor`
<a name="rekognition_DescribeStreamProcessor_cli_2_topic"></a>

次のコード例は、`describe-stream-processor` を使用する方法を示しています。

**AWS CLI**  
**ストリームプロセッサに関する情報を取得するには**  
次の `describe-stream-processor` コマンドは、指定されたストリームプロセッサの詳細を表示します。  

```
aws rekognition describe-stream-processor \
    --name my-stream-processor
```
出力:  

```
{
    "Status": "STOPPED",
    "Name": "my-stream-processor",
    "LastUpdateTimestamp": 1532449292.712,
    "Settings": {
        "FaceSearch": {
            "FaceMatchThreshold": 80.0,
            "CollectionId": "my-collection"
        }
    },
    "RoleArn": "arn:aws:iam::123456789012:role/AmazonRekognitionDetectStream",
    "StreamProcessorArn": "arn:aws:rekognition:us-west-2:123456789012:streamprocessor/my-stream-processpr",
    "Output": {
        "KinesisDataStream": {
            "Arn": "arn:aws:kinesis:us-west-2:123456789012:stream/AmazonRekognitionRekStream"
        }
    },
    "Input": {
        "KinesisVideoStream": {
            "Arn": "arn:aws:kinesisvideo:us-west-2:123456789012:stream/macwebcam/123456789012"
        }
    },
    "CreationTimestamp": 1532449292.712
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ストリーミングビデオの使用](https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStreamProcessor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/describe-stream-processor.html)」を参照してください。

### `detect-faces`
<a name="rekognition_DetectFaces_cli_2_topic"></a>

次のコード例は、`detect-faces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を検出する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html)」を参照してください。

**AWS CLI**  
**画像内の顔を検出するには**  
次の `detect-faces` コマンドは、Amazon S3 バケットに保存されている指定された画像の顔を検出します。  

```
aws rekognition detect-faces \
    --image '{"S3Object":{"Bucket":"MyImageS3Bucket","Name":"MyFriend.jpg"}}' \
    --attributes "ALL"
```
出力:  

```
{
    "FaceDetails": [
        {
            "Confidence": 100.0,
            "Eyeglasses": {
                "Confidence": 98.91107940673828,
                "Value": false
            },
            "Sunglasses": {
                "Confidence": 99.7966537475586,
                "Value": false
            },
            "Gender": {
                "Confidence": 99.56611633300781,
                "Value": "Male"
            },
            "Landmarks": [
                {
                    "Y": 0.26721030473709106,
                    "X": 0.6204193830490112,
                    "Type": "eyeLeft"
                },
                {
                    "Y": 0.26831310987472534,
                    "X": 0.6776827573776245,
                    "Type": "eyeRight"
                },
                {
                    "Y": 0.3514654338359833,
                    "X": 0.6241428852081299,
                    "Type": "mouthLeft"
                },
                {
                    "Y": 0.35258132219314575,
                    "X": 0.6713621020317078,
                    "Type": "mouthRight"
                },
                {
                    "Y": 0.3140771687030792,
                    "X": 0.6428444981575012,
                    "Type": "nose"
                },
                {
                    "Y": 0.24662546813488007,
                    "X": 0.6001564860343933,
                    "Type": "leftEyeBrowLeft"
                },
                {
                    "Y": 0.24326619505882263,
                    "X": 0.6303644776344299,
                    "Type": "leftEyeBrowRight"
                },
                {
                    "Y": 0.23818562924861908,
                    "X": 0.6146903038024902,
                    "Type": "leftEyeBrowUp"
                },
                {
                    "Y": 0.24373626708984375,
                    "X": 0.6640064716339111,
                    "Type": "rightEyeBrowLeft"
                },
                {
                    "Y": 0.24877218902111053,
                    "X": 0.7025929093360901,
                    "Type": "rightEyeBrowRight"
                },
                {
                    "Y": 0.23938551545143127,
                    "X": 0.6823262572288513,
                    "Type": "rightEyeBrowUp"
                },
                {
                    "Y": 0.265746533870697,
                    "X": 0.6112898588180542,
                    "Type": "leftEyeLeft"
                },
                {
                    "Y": 0.2676128149032593,
                    "X": 0.6317071914672852,
                    "Type": "leftEyeRight"
                },
                {
                    "Y": 0.262735515832901,
                    "X": 0.6201658248901367,
                    "Type": "leftEyeUp"
                },
                {
                    "Y": 0.27025148272514343,
                    "X": 0.6206279993057251,
                    "Type": "leftEyeDown"
                },
                {
                    "Y": 0.268223375082016,
                    "X": 0.6658390760421753,
                    "Type": "rightEyeLeft"
                },
                {
                    "Y": 0.2672517001628876,
                    "X": 0.687832236289978,
                    "Type": "rightEyeRight"
                },
                {
                    "Y": 0.26383838057518005,
                    "X": 0.6769183874130249,
                    "Type": "rightEyeUp"
                },
                {
                    "Y": 0.27138751745224,
                    "X": 0.676596462726593,
                    "Type": "rightEyeDown"
                },
                {
                    "Y": 0.32283174991607666,
                    "X": 0.6350004076957703,
                    "Type": "noseLeft"
                },
                {
                    "Y": 0.3219289481639862,
                    "X": 0.6567046642303467,
                    "Type": "noseRight"
                },
                {
                    "Y": 0.3420318365097046,
                    "X": 0.6450609564781189,
                    "Type": "mouthUp"
                },
                {
                    "Y": 0.3664324879646301,
                    "X": 0.6455618143081665,
                    "Type": "mouthDown"
                },
                {
                    "Y": 0.26721030473709106,
                    "X": 0.6204193830490112,
                    "Type": "leftPupil"
                },
                {
                    "Y": 0.26831310987472534,
                    "X": 0.6776827573776245,
                    "Type": "rightPupil"
                },
                {
                    "Y": 0.26343393325805664,
                    "X": 0.5946047306060791,
                    "Type": "upperJawlineLeft"
                },
                {
                    "Y": 0.3543180525302887,
                    "X": 0.6044883728027344,
                    "Type": "midJawlineLeft"
                },
                {
                    "Y": 0.4084877669811249,
                    "X": 0.6477024555206299,
                    "Type": "chinBottom"
                },
                {
                    "Y": 0.3562754988670349,
                    "X": 0.707981526851654,
                    "Type": "midJawlineRight"
                },
                {
                    "Y": 0.26580461859703064,
                    "X": 0.7234612107276917,
                    "Type": "upperJawlineRight"
                }
            ],
            "Pose": {
                "Yaw": -3.7351467609405518,
                "Roll": -0.10309021919965744,
                "Pitch": 0.8637830018997192
            },
            "Emotions": [
                {
                    "Confidence": 8.74203109741211,
                    "Type": "SURPRISED"
                },
                {
                    "Confidence": 2.501944065093994,
                    "Type": "ANGRY"
                },
                {
                    "Confidence": 0.7378743290901184,
                    "Type": "DISGUSTED"
                },
                {
                    "Confidence": 3.5296201705932617,
                    "Type": "HAPPY"
                },
                {
                    "Confidence": 1.7162904739379883,
                    "Type": "SAD"
                },
                {
                    "Confidence": 9.518536567687988,
                    "Type": "CONFUSED"
                },
                {
                    "Confidence": 0.45474427938461304,
                    "Type": "FEAR"
                },
                {
                    "Confidence": 72.79895782470703,
                    "Type": "CALM"
                }
            ],
            "AgeRange": {
                "High": 48,
                "Low": 32
            },
            "EyesOpen": {
                "Confidence": 98.93987274169922,
                "Value": true
            },
            "BoundingBox": {
                "Width": 0.12368916720151901,
                "Top": 0.16007372736930847,
                "Left": 0.5901257991790771,
                "Height": 0.25140416622161865
            },
            "Smile": {
                "Confidence": 93.4493179321289,
                "Value": false
            },
            "MouthOpen": {
                "Confidence": 90.53053283691406,
                "Value": false
            },
            "Quality": {
                "Sharpness": 95.51618957519531,
                "Brightness": 65.29893493652344
            },
            "Mustache": {
                "Confidence": 89.85221099853516,
                "Value": false
            },
            "Beard": {
                "Confidence": 86.1991195678711,
                "Value": true
            }
        }
    ]
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[イメージ内の顔の検出](https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectFaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/detect-faces.html)」を参照してください。**

### `detect-labels`
<a name="rekognition_DetectLabels_cli_2_topic"></a>

次のコード例は、`detect-labels` を使用する方法を示しています。

詳細については、「[イメージ内のラベルを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。

**AWS CLI**  
**画像内のラベルを検出するには**  
次の `detect-labels` の例は、Amazon S3 バケットに保存されている画像内のシーンとオブジェクトを検出します。  

```
aws rekognition detect-labels \
    --image '{"S3Object":{"Bucket":"bucket","Name":"image"}}'
```
出力:  

```
{
    "Labels": [
        {
            "Instances": [],
            "Confidence": 99.15271759033203,
            "Parents": [
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ],
            "Name": "Automobile"
        },
        {
            "Instances": [],
            "Confidence": 99.15271759033203,
            "Parents": [
                {
                    "Name": "Transportation"
                }
            ],
            "Name": "Vehicle"
        },
        {
            "Instances": [],
            "Confidence": 99.15271759033203,
            "Parents": [],
            "Name": "Transportation"
        },
        {
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.10616336017847061,
                        "Top": 0.5039216876029968,
                        "Left": 0.0037978808395564556,
                        "Height": 0.18528179824352264
                    },
                    "Confidence": 99.15271759033203
                },
                {
                    "BoundingBox": {
                        "Width": 0.2429988533258438,
                        "Top": 0.5251884460449219,
                        "Left": 0.7309805154800415,
                        "Height": 0.21577216684818268
                    },
                    "Confidence": 99.1286392211914
                },
                {
                    "BoundingBox": {
                        "Width": 0.14233611524105072,
                        "Top": 0.5333095788955688,
                        "Left": 0.6494812965393066,
                        "Height": 0.15528248250484467
                    },
                    "Confidence": 98.48368072509766
                },
                {
                    "BoundingBox": {
                        "Width": 0.11086395382881165,
                        "Top": 0.5354844927787781,
                        "Left": 0.10355594009160995,
                        "Height": 0.10271988064050674
                    },
                    "Confidence": 96.45606231689453
                },
                {
                    "BoundingBox": {
                        "Width": 0.06254628300666809,
                        "Top": 0.5573825240135193,
                        "Left": 0.46083059906959534,
                        "Height": 0.053911514580249786
                    },
                    "Confidence": 93.65448760986328
                },
                {
                    "BoundingBox": {
                        "Width": 0.10105438530445099,
                        "Top": 0.534368634223938,
                        "Left": 0.5743985772132874,
                        "Height": 0.12226245552301407
                    },
                    "Confidence": 93.06217193603516
                },
                {
                    "BoundingBox": {
                        "Width": 0.056389667093753815,
                        "Top": 0.5235804319381714,
                        "Left": 0.9427769780158997,
                        "Height": 0.17163699865341187
                    },
                    "Confidence": 92.6864013671875
                },
                {
                    "BoundingBox": {
                        "Width": 0.06003860384225845,
                        "Top": 0.5441341400146484,
                        "Left": 0.22409997880458832,
                        "Height": 0.06737709045410156
                    },
                    "Confidence": 90.4227066040039
                },
                {
                    "BoundingBox": {
                        "Width": 0.02848697081208229,
                        "Top": 0.5107086896896362,
                        "Left": 0,
                        "Height": 0.19150497019290924
                    },
                    "Confidence": 86.65286254882812
                },
                {
                    "BoundingBox": {
                        "Width": 0.04067881405353546,
                        "Top": 0.5566273927688599,
                        "Left": 0.316415935754776,
                        "Height": 0.03428703173995018
                    },
                    "Confidence": 85.36471557617188
                },
                {
                    "BoundingBox": {
                        "Width": 0.043411049991846085,
                        "Top": 0.5394920110702515,
                        "Left": 0.18293385207653046,
                        "Height": 0.0893595889210701
                    },
                    "Confidence": 82.21705627441406
                },
                {
                    "BoundingBox": {
                        "Width": 0.031183116137981415,
                        "Top": 0.5579366683959961,
                        "Left": 0.2853088080883026,
                        "Height": 0.03989990055561066
                    },
                    "Confidence": 81.0157470703125
                },
                {
                    "BoundingBox": {
                        "Width": 0.031113790348172188,
                        "Top": 0.5504819750785828,
                        "Left": 0.2580395042896271,
                        "Height": 0.056484755128622055
                    },
                    "Confidence": 56.13441467285156
                },
                {
                    "BoundingBox": {
                        "Width": 0.08586374670267105,
                        "Top": 0.5438792705535889,
                        "Left": 0.5128012895584106,
                        "Height": 0.08550430089235306
                    },
                    "Confidence": 52.37760925292969
                }
            ],
            "Confidence": 99.15271759033203,
            "Parents": [
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ],
            "Name": "Car"
        },
        {
            "Instances": [],
            "Confidence": 98.9914321899414,
            "Parents": [],
            "Name": "Human"
        },
        {
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.19360728561878204,
                        "Top": 0.35072067379951477,
                        "Left": 0.43734854459762573,
                        "Height": 0.2742200493812561
                    },
                    "Confidence": 98.9914321899414
                },
                {
                    "BoundingBox": {
                        "Width": 0.03801717236638069,
                        "Top": 0.5010883808135986,
                        "Left": 0.9155802130699158,
                        "Height": 0.06597328186035156
                    },
                    "Confidence": 85.02790832519531
                }
            ],
            "Confidence": 98.9914321899414,
            "Parents": [],
            "Name": "Person"
        },
        {
            "Instances": [],
            "Confidence": 93.24951934814453,
            "Parents": [],
            "Name": "Machine"
        },
        {
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.03561960905790329,
                        "Top": 0.6468243598937988,
                        "Left": 0.7850857377052307,
                        "Height": 0.08878646790981293
                    },
                    "Confidence": 93.24951934814453
                },
                {
                    "BoundingBox": {
                        "Width": 0.02217046171426773,
                        "Top": 0.6149078607559204,
                        "Left": 0.04757237061858177,
                        "Height": 0.07136218994855881
                    },
                    "Confidence": 91.5025863647461
                },
                {
                    "BoundingBox": {
                        "Width": 0.016197510063648224,
                        "Top": 0.6274210214614868,
                        "Left": 0.6472989320755005,
                        "Height": 0.04955997318029404
                    },
                    "Confidence": 85.14686584472656
                },
                {
                    "BoundingBox": {
                        "Width": 0.020207518711686134,
                        "Top": 0.6348286867141724,
                        "Left": 0.7295016646385193,
                        "Height": 0.07059963047504425
                    },
                    "Confidence": 83.34547424316406
                },
                {
                    "BoundingBox": {
                        "Width": 0.020280985161662102,
                        "Top": 0.6171894669532776,
                        "Left": 0.08744934946298599,
                        "Height": 0.05297485366463661
                    },
                    "Confidence": 79.9981460571289
                },
                {
                    "BoundingBox": {
                        "Width": 0.018318990245461464,
                        "Top": 0.623889148235321,
                        "Left": 0.6836880445480347,
                        "Height": 0.06730121374130249
                    },
                    "Confidence": 78.87144470214844
                },
                {
                    "BoundingBox": {
                        "Width": 0.021310249343514442,
                        "Top": 0.6167286038398743,
                        "Left": 0.004064912907779217,
                        "Height": 0.08317798376083374
                    },
                    "Confidence": 75.89361572265625
                },
                {
                    "BoundingBox": {
                        "Width": 0.03604431077837944,
                        "Top": 0.7030032277107239,
                        "Left": 0.9254803657531738,
                        "Height": 0.04569442570209503
                    },
                    "Confidence": 64.402587890625
                },
                {
                    "BoundingBox": {
                        "Width": 0.009834849275648594,
                        "Top": 0.5821820497512817,
                        "Left": 0.28094568848609924,
                        "Height": 0.01964157074689865
                    },
                    "Confidence": 62.79907989501953
                },
                {
                    "BoundingBox": {
                        "Width": 0.01475677452981472,
                        "Top": 0.6137543320655823,
                        "Left": 0.5950819253921509,
                        "Height": 0.039063986390829086
                    },
                    "Confidence": 59.40483474731445
                }
            ],
            "Confidence": 93.24951934814453,
            "Parents": [
                {
                    "Name": "Machine"
                }
            ],
            "Name": "Wheel"
        },
        {
            "Instances": [],
            "Confidence": 92.61514282226562,
            "Parents": [],
            "Name": "Road"
        },
        {
            "Instances": [],
            "Confidence": 92.37877655029297,
            "Parents": [
                {
                    "Name": "Person"
                }
            ],
            "Name": "Sport"
        },
        {
            "Instances": [],
            "Confidence": 92.37877655029297,
            "Parents": [
                {
                    "Name": "Person"
                }
            ],
            "Name": "Sports"
        },
        {
            "Instances": [
                {
                    "BoundingBox": {
                        "Width": 0.12326609343290329,
                        "Top": 0.6332163214683533,
                        "Left": 0.44815489649772644,
                        "Height": 0.058117982000112534
                    },
                    "Confidence": 92.37877655029297
                }
            ],
            "Confidence": 92.37877655029297,
            "Parents": [
                {
                    "Name": "Person"
                },
                {
                    "Name": "Sport"
                }
            ],
            "Name": "Skateboard"
        },
        {
            "Instances": [],
            "Confidence": 90.62931060791016,
            "Parents": [
                {
                    "Name": "Person"
                }
            ],
            "Name": "Pedestrian"
        },
        {
            "Instances": [],
            "Confidence": 88.81334686279297,
            "Parents": [],
            "Name": "Asphalt"
        },
        {
            "Instances": [],
            "Confidence": 88.81334686279297,
            "Parents": [],
            "Name": "Tarmac"
        },
        {
            "Instances": [],
            "Confidence": 88.23201751708984,
            "Parents": [],
            "Name": "Path"
        },
        {
            "Instances": [],
            "Confidence": 80.26520538330078,
            "Parents": [],
            "Name": "Urban"
        },
        {
            "Instances": [],
            "Confidence": 80.26520538330078,
            "Parents": [
                {
                    "Name": "Building"
                },
                {
                    "Name": "Urban"
                }
            ],
            "Name": "Town"
        },
        {
            "Instances": [],
            "Confidence": 80.26520538330078,
            "Parents": [],
            "Name": "Building"
        },
        {
            "Instances": [],
            "Confidence": 80.26520538330078,
            "Parents": [
                {
                    "Name": "Building"
                },
                {
                    "Name": "Urban"
                }
            ],
            "Name": "City"
        },
        {
            "Instances": [],
            "Confidence": 78.37934875488281,
            "Parents": [
                {
                    "Name": "Car"
                },
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ],
            "Name": "Parking Lot"
        },
        {
            "Instances": [],
            "Confidence": 78.37934875488281,
            "Parents": [
                {
                    "Name": "Car"
                },
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ],
            "Name": "Parking"
        },
        {
            "Instances": [],
            "Confidence": 74.37590026855469,
            "Parents": [
                {
                    "Name": "Building"
                },
                {
                    "Name": "Urban"
                },
                {
                    "Name": "City"
                }
            ],
            "Name": "Downtown"
        },
        {
            "Instances": [],
            "Confidence": 69.84622955322266,
            "Parents": [
                {
                    "Name": "Road"
                }
            ],
            "Name": "Intersection"
        },
        {
            "Instances": [],
            "Confidence": 57.68518829345703,
            "Parents": [
                {
                    "Name": "Sports Car"
                },
                {
                    "Name": "Car"
                },
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ],
            "Name": "Coupe"
        },
        {
            "Instances": [],
            "Confidence": 57.68518829345703,
            "Parents": [
                {
                    "Name": "Car"
                },
                {
                    "Name": "Vehicle"
                },
                {
                    "Name": "Transportation"
                }
            ],
            "Name": "Sports Car"
        },
        {
            "Instances": [],
            "Confidence": 56.59492111206055,
            "Parents": [
                {
                    "Name": "Path"
                }
            ],
            "Name": "Sidewalk"
        },
        {
            "Instances": [],
            "Confidence": 56.59492111206055,
            "Parents": [
                {
                    "Name": "Path"
                }
            ],
            "Name": "Pavement"
        },
        {
            "Instances": [],
            "Confidence": 55.58770751953125,
            "Parents": [
                {
                    "Name": "Building"
                },
                {
                    "Name": "Urban"
                }
            ],
            "Name": "Neighborhood"
        }
    ],
    "LabelModelVersion": "2.0"
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[イメージ内のラベルの検出](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectLabels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/detect-labels.html)」を参照してください。**

### `detect-moderation-labels`
<a name="rekognition_DetectModerationLabels_cli_2_topic"></a>

次のコード例は、`detect-moderation-labels` を使用する方法を示しています。

詳細については、「[不適切なイメージを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-images.html)」を参照してください。

**AWS CLI**  
**画像内の安全でないコンテンツを検出するには**  
次の `detect-moderation-labels` コマンドは、Amazon S3 バケットに保存されている指定された画像の安全でないコンテンツを検出します。  

```
aws rekognition detect-moderation-labels \
    --image "S3Object={Bucket=MyImageS3Bucket,Name=gun.jpg}"
```
出力:  

```
{
    "ModerationModelVersion": "3.0",
    "ModerationLabels": [
        {
            "Confidence": 97.29618072509766,
            "ParentName": "Violence",
            "Name": "Weapon Violence"
        },
        {
            "Confidence": 97.29618072509766,
            "ParentName": "",
            "Name": "Violence"
        }
    ]
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[不適切なイメージの検出](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-images.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectModerationLabels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/detect-moderation-labels.html)」を参照してください。**

### `detect-text`
<a name="rekognition_DetectText_cli_2_topic"></a>

次のコード例は、`detect-text` を使用する方法を示しています。

詳細については、「[イメージ内のテキストを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/text-detecting-text-procedure.html)」を参照してください。

**AWS CLI**  
**画像内のテキストを検出するには**  
次の `detect-text` コマンドは、指定された画像内のテキストを検出します。  

```
aws rekognition detect-text \
    --image '{"S3Object":{"Bucket":"MyImageS3Bucket","Name":"ExamplePicture.jpg"}}'
```
出力:  

```
{
    "TextDetections": [
        {
            "Geometry": {
                "BoundingBox": {
                    "Width": 0.24624845385551453,
                    "Top": 0.28288066387176514,
                    "Left": 0.391388863325119,
                    "Height": 0.022687450051307678
                },
                "Polygon": [
                    {
                        "Y": 0.28288066387176514,
                        "X": 0.391388863325119
                    },
                    {
                        "Y": 0.2826388478279114,
                        "X": 0.6376373171806335
                    },
                    {
                        "Y": 0.30532628297805786,
                        "X": 0.637677013874054
                    },
                    {
                        "Y": 0.305568128824234,
                        "X": 0.39142853021621704
                    }
                ]
            },
            "Confidence": 94.35709381103516,
            "DetectedText": "ESTD 1882",
            "Type": "LINE",
            "Id": 0
        },
        {
            "Geometry": {
                "BoundingBox": {
                    "Width": 0.33933889865875244,
                    "Top": 0.32603850960731506,
                    "Left": 0.34534579515457153,
                    "Height": 0.07126858830451965
                },
                "Polygon": [
                    {
                        "Y": 0.32603850960731506,
                        "X": 0.34534579515457153
                    },
                    {
                        "Y": 0.32633158564567566,
                        "X": 0.684684693813324
                    },
                    {
                        "Y": 0.3976001739501953,
                        "X": 0.684575080871582
                    },
                    {
                        "Y": 0.3973070979118347,
                        "X": 0.345236212015152
                    }
                ]
            },
            "Confidence": 99.95779418945312,
            "DetectedText": "BRAINS",
            "Type": "LINE",
            "Id": 1
        },
        {
            "Confidence": 97.22098541259766,
            "Geometry": {
                "BoundingBox": {
                    "Width": 0.061079490929841995,
                    "Top": 0.2843210697174072,
                    "Left": 0.391391396522522,
                    "Height": 0.021029088646173477
                },
                "Polygon": [
                    {
                        "Y": 0.2843210697174072,
                        "X": 0.391391396522522
                    },
                    {
                        "Y": 0.2828207015991211,
                        "X": 0.4524524509906769
                    },
                    {
                        "Y": 0.3038259446620941,
                        "X": 0.4534534513950348
                    },
                    {
                        "Y": 0.30532634258270264,
                        "X": 0.3923923969268799
                    }
                ]
            },
            "DetectedText": "ESTD",
            "ParentId": 0,
            "Type": "WORD",
            "Id": 2
        },
        {
            "Confidence": 91.49320983886719,
            "Geometry": {
                "BoundingBox": {
                    "Width": 0.07007007300853729,
                    "Top": 0.2828207015991211,
                    "Left": 0.5675675868988037,
                    "Height": 0.02250562608242035
                },
                "Polygon": [
                    {
                        "Y": 0.2828207015991211,
                        "X": 0.5675675868988037
                    },
                    {
                        "Y": 0.2828207015991211,
                        "X": 0.6376376152038574
                    },
                    {
                        "Y": 0.30532634258270264,
                        "X": 0.6376376152038574
                    },
                    {
                        "Y": 0.30532634258270264,
                        "X": 0.5675675868988037
                    }
                ]
            },
            "DetectedText": "1882",
            "ParentId": 0,
            "Type": "WORD",
            "Id": 3
        },
        {
            "Confidence": 99.95779418945312,
            "Geometry": {
                "BoundingBox": {
                    "Width": 0.33933934569358826,
                    "Top": 0.32633158564567566,
                    "Left": 0.3453453481197357,
                    "Height": 0.07127484679222107
                },
                "Polygon": [
                    {
                        "Y": 0.32633158564567566,
                        "X": 0.3453453481197357
                    },
                    {
                        "Y": 0.32633158564567566,
                        "X": 0.684684693813324
                    },
                    {
                        "Y": 0.39759939908981323,
                        "X": 0.6836836934089661
                    },
                    {
                        "Y": 0.39684921503067017,
                        "X": 0.3453453481197357
                    }
                ]
            },
            "DetectedText": "BRAINS",
            "ParentId": 1,
            "Type": "WORD",
            "Id": 4
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectText](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/detect-text.html)」を参照してください。**

### `get-celebrity-info`
<a name="rekognition_GetCelebrityInfo_cli_2_topic"></a>

次の例は、`get-celebrity-info` を使用する方法を説明しています。

**AWS CLI**  
**有名人に関する情報を取得するには**  
次の `get-celebrity-info` コマンドは、指定された有名人に関する詳細情報を表示します。`id` パラメータは以前に `recognize-celebrities` を呼び出したときのものです。  

```
aws rekognition get-celebrity-info --id nnnnnnn
```
出力:  

```
{
    "Name": "Celeb A",
    "Urls": [
        "www.imdb.com/name/aaaaaaaaa"
    ]
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[有名人に関する情報の取得](https://docs.aws.amazon.com/rekognition/latest/dg/get-celebrity-info-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetCelebrityInfo](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/get-celebrity-info.html)」を参照してください。**

### `get-celebrity-recognition`
<a name="rekognition_GetCelebrityRecognition_cli_2_topic"></a>

次のコード例は、`get-celebrity-recognition` を使用する方法を示しています。

**AWS CLI**  
**有名人認識オペレーションの結果を取得するには**  
次の `get-celebrity-recognition` コマンドは、`start-celebrity-recognition` を呼び出すことで以前に開始した有名人認識オペレーションの結果を表示します。  

```
aws rekognition get-celebrity-recognition  \
    --job-id 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
```
出力:  

```
{
    "NextToken": "3D01ClxlCiT31VsRDkAO3IybLb/h5AtDWSGuhYi+N1FIJwwPtAkuKzDhL2rV3GcwmNt77+12",
    "Celebrities": [
        {
            "Timestamp": 0,
            "Celebrity": {
                "Confidence": 96.0,
                "Face": {
                    "BoundingBox": {
                        "Width": 0.70333331823349,
                        "Top": 0.16750000417232513,
                        "Left": 0.19555555284023285,
                        "Height": 0.3956249952316284
                    },
                    "Landmarks": [
                        {
                            "Y": 0.31031012535095215,
                            "X": 0.441436767578125,
                            "Type": "eyeLeft"
                        },
                        {
                            "Y": 0.3081788718700409,
                            "X": 0.6437258720397949,
                            "Type": "eyeRight"
                        },
                        {
                            "Y": 0.39542075991630554,
                            "X": 0.5572493076324463,
                            "Type": "nose"
                        },
                        {
                            "Y": 0.4597957134246826,
                            "X": 0.4579732120037079,
                            "Type": "mouthLeft"
                        },
                        {
                            "Y": 0.45688048005104065,
                            "X": 0.6349081993103027,
                            "Type": "mouthRight"
                        }
                    ],
                    "Pose": {
                        "Yaw": 8.943398475646973,
                        "Roll": -2.0309247970581055,
                        "Pitch": -0.5674862861633301
                    },
                    "Quality": {
                        "Sharpness": 99.40211486816406,
                        "Brightness": 89.47132110595703
                    },
                    "Confidence": 99.99861145019531
                },
                "Name": "CelebrityA",
                "Urls": [
                    "www.imdb.com/name/111111111"
                ],
                "Id": "nnnnnn"
            }
        },
        {
            "Timestamp": 467,
            "Celebrity": {
                "Confidence": 99.0,
                "Face": {
                    "BoundingBox": {
                        "Width": 0.6877777576446533,
                        "Top": 0.18437500298023224,
                        "Left": 0.20555555820465088,
                        "Height": 0.3868750035762787
                    },
                    "Landmarks": [
                        {
                            "Y": 0.31895750761032104,
                            "X": 0.4411413371562958,
                            "Type": "eyeLeft"
                        },
                        {
                            "Y": 0.3140959143638611,
                            "X": 0.6523157954216003,
                            "Type": "eyeRight"
                        },
                        {
                            "Y": 0.4016456604003906,
                            "X": 0.5682755708694458,
                            "Type": "nose"
                        },
                        {
                            "Y": 0.46894142031669617,
                            "X": 0.4597797095775604,
                            "Type": "mouthLeft"
                        },
                        {
                            "Y": 0.46971091628074646,
                            "X": 0.6286435127258301,
                            "Type": "mouthRight"
                        }
                    ],
                    "Pose": {
                        "Yaw": 10.433465957641602,
                        "Roll": -3.347442388534546,
                        "Pitch": 1.3709543943405151
                    },
                    "Quality": {
                        "Sharpness": 99.5531005859375,
                        "Brightness": 88.5764389038086
                    },
                    "Confidence": 99.99148559570312
                },
                "Name": "Jane Celebrity",
                "Urls": [
                    "www.imdb.com/name/111111111"
                ],
                "Id": "nnnnnn"
            }
        }
    ],
    "JobStatus": "SUCCEEDED",
    "VideoMetadata": {
        "Format": "QuickTime / MOV",
        "FrameRate": 29.978118896484375,
        "Codec": "h264",
        "DurationMillis": 4570,
        "FrameHeight": 1920,
        "FrameWidth": 1080
    }
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存されたビデオ内の有名人の認識](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-video-sqs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCelebrityRecognition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/get-celebrity-recognition.html)」を参照してください。

### `get-content-moderation`
<a name="rekognition_GetContentModeration_cli_2_topic"></a>

次のコード例は、`get-content-moderation` を使用する方法を示しています。

**AWS CLI**  
**安全でないコンテンツオペレーションの結果を取得するには**  
次の `get-content-moderation` コマンドは、`start-content-moderation` を呼び出して以前に開始した安全でないコンテンツオペレーションの結果を表示します。  

```
aws rekognition get-content-moderation \
    --job-id 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
```
出力:  

```
{
    "NextToken": "dlhcKMHMzpCBGFukz6IO3JMcWiJAamCVhXHt3r6b4b5Tfbyw3q7o+Jeezt+ZpgfOnW9FCCgQ",
    "ModerationLabels": [
        {
            "Timestamp": 0,
            "ModerationLabel": {
                "Confidence": 97.39583587646484,
                "ParentName": "",
                "Name": "Violence"
            }
        },
        {
            "Timestamp": 0,
            "ModerationLabel": {
                "Confidence": 97.39583587646484,
                "ParentName": "Violence",
                "Name": "Weapon Violence"
            }
        }
    ],
    "JobStatus": "SUCCEEDED",
    "VideoMetadata": {
        "Format": "QuickTime / MOV",
        "FrameRate": 29.97515869140625,
        "Codec": "h264",
        "DurationMillis": 6039,
        "FrameHeight": 1920,
        "FrameWidth": 1080
    }
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存された安全でないビデオの検出](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-videos.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContentModeration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/get-content-moderation.html)」を参照してください。

### `get-face-detection`
<a name="rekognition_GetFaceDetection_cli_2_topic"></a>

次のコード例は、`get-face-detection` を使用する方法を示しています。

**AWS CLI**  
**顔検出オペレーションの結果を取得するには**  
次の `get-face-detection` コマンドは、`start-face-detection` を呼び出して以前に開始した顔検出オペレーションの結果を表示します。  

```
aws rekognition get-face-detection \
    --job-id 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
```
出力:  

```
{
    "Faces": [
        {
            "Timestamp": 467,
            "Face": {
                "BoundingBox": {
                    "Width": 0.1560753583908081,
                    "Top": 0.13555361330509186,
                    "Left": -0.0952017530798912,
                    "Height": 0.6934483051300049
                },
                "Landmarks": [
                    {
                        "Y": 0.4013825058937073,
                        "X": -0.041750285774469376,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.41695496439933777,
                        "X": 0.027979329228401184,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.6375303268432617,
                        "X": -0.04034662991762161,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.6497718691825867,
                        "X": 0.013960429467260838,
                        "Type": "mouthRight"
                    },
                    {
                        "Y": 0.5238034129142761,
                        "X": 0.008022055961191654,
                        "Type": "nose"
                    }
                ],
                "Pose": {
                    "Yaw": -58.07863998413086,
                    "Roll": 1.9384294748306274,
                    "Pitch": -24.66305160522461
                },
                "Quality": {
                    "Sharpness": 83.14741516113281,
                    "Brightness": 25.75942611694336
                },
                "Confidence": 87.7622299194336
            }
        },
        {
            "Timestamp": 967,
            "Face": {
                "BoundingBox": {
                    "Width": 0.28559377789497375,
                    "Top": 0.19436298310756683,
                    "Left": 0.024553587660193443,
                    "Height": 0.7216082215309143
                },
                "Landmarks": [
                    {
                        "Y": 0.4650231599807739,
                        "X": 0.16269078850746155,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.4843238294124603,
                        "X": 0.2782580852508545,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.71530681848526,
                        "X": 0.1741468608379364,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.7310671210289001,
                        "X": 0.26857468485832214,
                        "Type": "mouthRight"
                    },
                    {
                        "Y": 0.582602322101593,
                        "X": 0.2566150426864624,
                        "Type": "nose"
                    }
                ],
                "Pose": {
                    "Yaw": 11.487052917480469,
                    "Roll": 5.074230670928955,
                    "Pitch": 15.396159172058105
                },
                "Quality": {
                    "Sharpness": 73.32209777832031,
                    "Brightness": 54.96497344970703
                },
                "Confidence": 99.99998474121094
            }
        }
    ],
    "NextToken": "OzL223pDKy9116O/02KXRqFIEAwxjy4PkgYcm3hSo0rdysbXg5Ex0eFgTGEj0ADEac6S037U",
    "JobStatus": "SUCCEEDED",
    "VideoMetadata": {
        "Format": "QuickTime / MOV",
        "FrameRate": 29.970617294311523,
        "Codec": "h264",
        "DurationMillis": 6806,
        "FrameHeight": 1080,
        "FrameWidth": 1920
    }
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存済みビデオ内の顔の検出](https://docs.aws.amazon.com/rekognition/latest/dg/faces-sqs-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFaceDetection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/get-face-detection.html)」を参照してください。

### `get-face-search`
<a name="rekognition_GetFaceSearch_cli_2_topic"></a>

次のコード例は、`get-face-search` を使用する方法を示しています。

**AWS CLI**  
**顔検索オペレーションの結果を取得するには**  
次の `get-face-search` コマンドは、`start-face-search` を呼び出して以前に開始した顔検索オペレーションの結果を表示します。  

```
aws rekognition get-face-search  \
    --job-id 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
```
出力:  

```
{
    "Persons": [
        {
            "Timestamp": 467,
            "FaceMatches": [],
            "Person": {
                "Index": 0,
                "Face": {
                    "BoundingBox": {
                        "Width": 0.1560753583908081,
                        "Top": 0.13555361330509186,
                        "Left": -0.0952017530798912,
                        "Height": 0.6934483051300049
                    },
                    "Landmarks": [
                        {
                            "Y": 0.4013825058937073,
                            "X": -0.041750285774469376,
                            "Type": "eyeLeft"
                        },
                        {
                            "Y": 0.41695496439933777,
                            "X": 0.027979329228401184,
                            "Type": "eyeRight"
                        },
                        {
                            "Y": 0.6375303268432617,
                            "X": -0.04034662991762161,
                            "Type": "mouthLeft"
                        },
                        {
                            "Y": 0.6497718691825867,
                            "X": 0.013960429467260838,
                            "Type": "mouthRight"
                        },
                        {
                            "Y": 0.5238034129142761,
                            "X": 0.008022055961191654,
                            "Type": "nose"
                        }
                    ],
                    "Pose": {
                        "Yaw": -58.07863998413086,
                        "Roll": 1.9384294748306274,
                        "Pitch": -24.66305160522461
                    },
                    "Quality": {
                        "Sharpness": 83.14741516113281,
                        "Brightness": 25.75942611694336
                    },
                    "Confidence": 87.7622299194336
                }
            }
        },
        {
            "Timestamp": 967,
            "FaceMatches": [
                {
                    "Face": {
                        "BoundingBox": {
                            "Width": 0.12368900328874588,
                            "Top": 0.16007399559020996,
                            "Left": 0.5901259779930115,
                            "Height": 0.2514039874076843
                        },
                        "FaceId": "056a95fa-2060-4159-9cab-7ed4daa030fa",
                        "ExternalImageId": "image3.jpg",
                        "Confidence": 100.0,
                        "ImageId": "08f8a078-8929-37fd-8e8f-aadf690e8232"
                    },
                    "Similarity": 98.44476318359375
                }
            ],
            "Person": {
                "Index": 1,
                "Face": {
                    "BoundingBox": {
                        "Width": 0.28559377789497375,
                        "Top": 0.19436298310756683,
                        "Left": 0.024553587660193443,
                        "Height": 0.7216082215309143
                    },
                    "Landmarks": [
                        {
                            "Y": 0.4650231599807739,
                            "X": 0.16269078850746155,
                            "Type": "eyeLeft"
                        },
                        {
                            "Y": 0.4843238294124603,
                            "X": 0.2782580852508545,
                            "Type": "eyeRight"
                        },
                        {
                            "Y": 0.71530681848526,
                            "X": 0.1741468608379364,
                            "Type": "mouthLeft"
                        },
                        {
                            "Y": 0.7310671210289001,
                            "X": 0.26857468485832214,
                            "Type": "mouthRight"
                        },
                        {
                            "Y": 0.582602322101593,
                            "X": 0.2566150426864624,
                            "Type": "nose"
                        }
                    ],
                    "Pose": {
                        "Yaw": 11.487052917480469,
                        "Roll": 5.074230670928955,
                        "Pitch": 15.396159172058105
                    },
                    "Quality": {
                        "Sharpness": 73.32209777832031,
                        "Brightness": 54.96497344970703
                    },
                    "Confidence": 99.99998474121094
                }
            }
        }
    ],
    "NextToken": "5bkgcezyuaqhtWk3C8OTW6cjRghrwV9XDMivm5B3MXm+Lv6G+L+GejyFHPhoNa/ldXIC4c/d",
    "JobStatus": "SUCCEEDED",
    "VideoMetadata": {
        "Format": "QuickTime / MOV",
        "FrameRate": 29.970617294311523,
        "Codec": "h264",
        "DurationMillis": 6806,
        "FrameHeight": 1080,
        "FrameWidth": 1920
    }
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存済みビデオ内の顔の検索](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-person-search-videos.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFaceSearch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/get-face-search.html)」を参照してください。

### `get-label-detection`
<a name="rekognition_GetLabelDetection_cli_2_topic"></a>

次のコード例は、`get-label-detection` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトとシーンの検出オペレーションの結果を取得するには**  
次の `get-label-detection` コマンドは、`start-label-detection` を呼び出して以前に開始したオブジェクトとシーンの検出オペレーションの結果を表示します。  

```
aws rekognition get-label-detection  \
    --job-id 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
```
出力:  

```
{
    "Labels": [
        {
            "Timestamp": 0,
            "Label": {
                "Instances": [],
                "Confidence": 50.19071578979492,
                "Parents": [
                    {
                        "Name": "Person"
                    },
                    {
                        "Name": "Crowd"
                    }
                ],
                "Name": "Audience"
            }
        },
        {
            "Timestamp": 0,
            "Label": {
                "Instances": [],
                "Confidence": 55.74115753173828,
                "Parents": [
                    {
                        "Name": "Room"
                    },
                    {
                        "Name": "Indoors"
                    },
                    {
                        "Name": "School"
                    }
                ],
                "Name": "Classroom"
            }
        }
    ],
    "JobStatus": "SUCCEEDED",
    "LabelModelVersion": "2.0",
    "VideoMetadata": {
        "Format": "QuickTime / MOV",
        "FrameRate": 29.970617294311523,
        "Codec": "h264",
        "DurationMillis": 6806,
        "FrameHeight": 1080,
        "FrameWidth": 1920
    },
    "NextToken": "BMugzAi4L72IERzQdbpyMQuEFBsjlo5W0Yx3mfG+sR9mm98E1/CpObenspRfs/5FBQFs4X7G"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ビデオ内のラベルの検出](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detecting-labels-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLabelDetection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/get-label-detection.html)」を参照してください。

### `get-person-tracking`
<a name="rekognition_GetPersonTracking_cli_2_topic"></a>

次のコード例は、`get-person-tracking` を使用する方法を示しています。

**AWS CLI**  
**人物パスオペレーションの結果を取得するには**  
次の `get-person-tracking` コマンドは、`start-person-tracking` を呼び出して以前に開始した人物パスオペレーションの結果を表示します。  

```
aws rekognition get-person-tracking  \
    --job-id 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
```
出力:  

```
{
    "Persons": [
        {
            "Timestamp": 500,
            "Person": {
                "BoundingBox": {
                    "Width": 0.4151041805744171,
                    "Top": 0.07870370149612427,
                    "Left": 0.0,
                    "Height": 0.9212962985038757
                },
                "Index": 0
            }
        },
        {
            "Timestamp": 567,
            "Person": {
                "BoundingBox": {
                    "Width": 0.4755208194255829,
                    "Top": 0.07777778059244156,
                    "Left": 0.0,
                    "Height": 0.9194444417953491
                },
                "Index": 0
            }
        }
    ],
    "NextToken": "D/vRIYNyhG79ugdta3f+8cRg9oSRo+HigGOuxRiYpTn0ExnqTi1CJektVAc4HrAXDv25eHYk",
    "JobStatus": "SUCCEEDED",
    "VideoMetadata": {
        "Format": "QuickTime / MOV",
        "FrameRate": 29.970617294311523,
        "Codec": "h264",
        "DurationMillis": 6806,
        "FrameHeight": 1080,
        "FrameWidth": 1920
    }
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[人物パス](https://docs.aws.amazon.com/rekognition/latest/dg/persons.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPersonTracking](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/get-person-tracking.html)」を参照してください。

### `index-faces`
<a name="rekognition_IndexFaces_cli_2_topic"></a>

次のコード例は、`index-faces` を使用する方法を示しています。

詳細については、「[コレクションに顔を追加する](https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html)」を参照してください。

**AWS CLI**  
**コレクションに顔を追加するには**  
次の `index-faces` コマンドは、画像内の顔を指定されたコレクションに追加します。  

```
aws rekognition index-faces \
    --image '{"S3Object":{"Bucket":"MyVideoS3Bucket","Name":"MyPicture.jpg"}}' \
    --collection-id MyCollection \
    --max-faces 1 \
    --quality-filter "AUTO" \
    --detection-attributes "ALL" \
    --external-image-id "MyPicture.jpg"
```
出力:  

```
{
    "FaceRecords": [
        {
            "FaceDetail": {
                "Confidence": 99.993408203125,
                "Eyeglasses": {
                    "Confidence": 99.11750030517578,
                    "Value": false
                },
                "Sunglasses": {
                    "Confidence": 99.98249053955078,
                    "Value": false
                },
                "Gender": {
                    "Confidence": 99.92769622802734,
                    "Value": "Male"
                },
                "Landmarks": [
                    {
                        "Y": 0.26750367879867554,
                        "X": 0.6202793717384338,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.26642778515815735,
                        "X": 0.6787431836128235,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.31361380219459534,
                        "X": 0.6421601176261902,
                        "Type": "nose"
                    },
                    {
                        "Y": 0.3495299220085144,
                        "X": 0.6216195225715637,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.35194727778434753,
                        "X": 0.669899046421051,
                        "Type": "mouthRight"
                    },
                    {
                        "Y": 0.26844894886016846,
                        "X": 0.6210268139839172,
                        "Type": "leftPupil"
                    },
                    {
                        "Y": 0.26707562804222107,
                        "X": 0.6817160844802856,
                        "Type": "rightPupil"
                    },
                    {
                        "Y": 0.24834522604942322,
                        "X": 0.6018546223640442,
                        "Type": "leftEyeBrowLeft"
                    },
                    {
                        "Y": 0.24397172033786774,
                        "X": 0.6172008514404297,
                        "Type": "leftEyeBrowUp"
                    },
                    {
                        "Y": 0.24677404761314392,
                        "X": 0.6339119076728821,
                        "Type": "leftEyeBrowRight"
                    },
                    {
                        "Y": 0.24582654237747192,
                        "X": 0.6619398593902588,
                        "Type": "rightEyeBrowLeft"
                    },
                    {
                        "Y": 0.23973053693771362,
                        "X": 0.6804757118225098,
                        "Type": "rightEyeBrowUp"
                    },
                    {
                        "Y": 0.24441994726657867,
                        "X": 0.6978968977928162,
                        "Type": "rightEyeBrowRight"
                    },
                    {
                        "Y": 0.2695908546447754,
                        "X": 0.6085202693939209,
                        "Type": "leftEyeLeft"
                    },
                    {
                        "Y": 0.26716896891593933,
                        "X": 0.6315826177597046,
                        "Type": "leftEyeRight"
                    },
                    {
                        "Y": 0.26289820671081543,
                        "X": 0.6202316880226135,
                        "Type": "leftEyeUp"
                    },
                    {
                        "Y": 0.27123287320137024,
                        "X": 0.6205548048019409,
                        "Type": "leftEyeDown"
                    },
                    {
                        "Y": 0.2668408751487732,
                        "X": 0.6663622260093689,
                        "Type": "rightEyeLeft"
                    },
                    {
                        "Y": 0.26741549372673035,
                        "X": 0.6910083889961243,
                        "Type": "rightEyeRight"
                    },
                    {
                        "Y": 0.2614026665687561,
                        "X": 0.6785826086997986,
                        "Type": "rightEyeUp"
                    },
                    {
                        "Y": 0.27075251936912537,
                        "X": 0.6789616942405701,
                        "Type": "rightEyeDown"
                    },
                    {
                        "Y": 0.3211299479007721,
                        "X": 0.6324167847633362,
                        "Type": "noseLeft"
                    },
                    {
                        "Y": 0.32276326417922974,
                        "X": 0.6558475494384766,
                        "Type": "noseRight"
                    },
                    {
                        "Y": 0.34385165572166443,
                        "X": 0.6444970965385437,
                        "Type": "mouthUp"
                    },
                    {
                        "Y": 0.3671635091304779,
                        "X": 0.6459195017814636,
                        "Type": "mouthDown"
                    }
                ],
                "Pose": {
                    "Yaw": -9.54541015625,
                    "Roll": -0.5709401965141296,
                    "Pitch": 0.6045494675636292
                },
                "Emotions": [
                    {
                        "Confidence": 39.90074157714844,
                        "Type": "HAPPY"
                    },
                    {
                        "Confidence": 23.38753890991211,
                        "Type": "CALM"
                    },
                    {
                        "Confidence": 5.840933322906494,
                        "Type": "CONFUSED"
                    }
                ],
                "AgeRange": {
                    "High": 63,
                    "Low": 45
                },
                "EyesOpen": {
                    "Confidence": 99.80887603759766,
                    "Value": true
                },
                "BoundingBox": {
                    "Width": 0.18562500178813934,
                    "Top": 0.1618015021085739,
                    "Left": 0.5575000047683716,
                    "Height": 0.24770642817020416
                },
                "Smile": {
                    "Confidence": 99.69740295410156,
                    "Value": false
                },
                "MouthOpen": {
                    "Confidence": 99.97393798828125,
                    "Value": false
                },
                "Quality": {
                    "Sharpness": 95.54405975341797,
                    "Brightness": 63.867706298828125
                },
                "Mustache": {
                    "Confidence": 97.05007934570312,
                    "Value": false
                },
                "Beard": {
                    "Confidence": 87.34505462646484,
                    "Value": false
                }
            },
            "Face": {
                "BoundingBox": {
                    "Width": 0.18562500178813934,
                    "Top": 0.1618015021085739,
                    "Left": 0.5575000047683716,
                    "Height": 0.24770642817020416
                },
                "FaceId": "ce7ed422-2132-4a11-ab14-06c5c410f29f",
                "ExternalImageId": "example-image.jpg",
                "Confidence": 99.993408203125,
                "ImageId": "8d67061e-90d2-598f-9fbd-29c8497039c0"
            }
        }
    ],
    "UnindexedFaces": [],
    "FaceModelVersion": "3.0",
    "OrientationCorrection": "ROTATE_0"
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[コレクションへの顔の追加](https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[IndexFaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/index-faces.html)」を参照してください。**

### `list-collections`
<a name="rekognition_ListCollections_cli_2_topic"></a>

次のコード例は、`list-collections` を使用する方法を示しています。

コレクションの詳細については、「[コレクションを一覧表示する](https://docs.aws.amazon.com/rekognition/latest/dg/list-collection-procedure.html)」を参照してください。

**AWS CLI**  
**使用可能なコレクションを一覧表示するには**  
次の`list-collections`コマンドは、 AWS アカウントで使用可能なコレクションを一覧表示します。  

```
aws rekognition list-collections
```
出力:  

```
{
    "FaceModelVersions": [
        "2.0",
        "3.0",
        "3.0",
        "3.0",
        "4.0",
        "1.0",
        "3.0",
        "4.0",
        "4.0",
        "4.0"
    ],
    "CollectionIds": [
        "MyCollection1",
        "MyCollection2",
        "MyCollection3",
        "MyCollection4",
        "MyCollection5",
        "MyCollection6",
        "MyCollection7",
        "MyCollection8",
        "MyCollection9",
        "MyCollection10"
    ]
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[コレクションの一覧表示](https://docs.aws.amazon.com/rekognition/latest/dg/list-collection-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListCollections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/list-collections.html)」を参照してください。**

### `list-faces`
<a name="rekognition_ListFaces_cli_2_topic"></a>

次のコード例は、`list-faces` を使用する方法を示しています。

詳細については、「[コレクションに顔を保存する](https://docs.aws.amazon.com/rekognition/latest/dg/list-faces-in-collection-procedure.html)」を参照してください。

**AWS CLI**  
**コレクション内の顔を一覧表示するには**  
次の `list-faces` コマンドは、指定されたコレクション内の顔を一覧表示します。  

```
aws rekognition list-faces \
    --collection-id MyCollection
```
出力:  

```
{
    "FaceModelVersion": "3.0",
    "Faces": [
        {
            "BoundingBox": {
                "Width": 0.5216310024261475,
                "Top": 0.3256250023841858,
                "Left": 0.13394300639629364,
                "Height": 0.3918749988079071
            },
            "FaceId": "0040279c-0178-436e-b70a-e61b074e96b0",
            "ExternalImageId": "image1.jpg",
            "Confidence": 100.0,
            "ImageId": "f976e487-3719-5e2d-be8b-ea2724c26991"
        },
        {
            "BoundingBox": {
                "Width": 0.5074880123138428,
                "Top": 0.3774999976158142,
                "Left": 0.18302799761295319,
                "Height": 0.3812499940395355
            },
            "FaceId": "086261e8-6deb-4bc0-ac73-ab22323cc38d",
            "ExternalImageId": "image2.jpg",
            "Confidence": 99.99930572509766,
            "ImageId": "ae1593b0-a8f6-5e24-a306-abf529e276fa"
        },
        {
            "BoundingBox": {
                "Width": 0.5574039816856384,
                "Top": 0.37187498807907104,
                "Left": 0.14559100568294525,
                "Height": 0.4181250035762787
            },
            "FaceId": "11c4bd3c-19c5-4eb8-aecc-24feb93a26e1",
            "ExternalImageId": "image3.jpg",
            "Confidence": 99.99960327148438,
            "ImageId": "80739b4d-883f-5b78-97cf-5124038e26b9"
        },
        {
            "BoundingBox": {
                "Width": 0.18562500178813934,
                "Top": 0.1618019938468933,
                "Left": 0.5575000047683716,
                "Height": 0.24770599603652954
            },
            "FaceId": "13692fe4-990a-4679-b14a-5ac23d135eab",
            "ExternalImageId": "image4.jpg",
            "Confidence": 99.99340057373047,
            "ImageId": "8df18239-9ad1-5acd-a46a-6581ff98f51b"
        },
        {
            "BoundingBox": {
                "Width": 0.5307819843292236,
                "Top": 0.2862499952316284,
                "Left": 0.1564060002565384,
                "Height": 0.3987500071525574
            },
            "FaceId": "2eb5f3fd-e2a9-4b1c-a89f-afa0a518fe06",
            "ExternalImageId": "image5.jpg",
            "Confidence": 99.99970245361328,
            "ImageId": "3c314792-197d-528d-bbb6-798ed012c150"
        },
        {
            "BoundingBox": {
                "Width": 0.5773710012435913,
                "Top": 0.34437501430511475,
                "Left": 0.12396000325679779,
                "Height": 0.4337500035762787
            },
            "FaceId": "57189455-42b0-4839-a86c-abda48b13174",
            "ExternalImageId": "image6.jpg",
            "Confidence": 100.0,
            "ImageId": "0aff2f37-e7a2-5dbc-a3a3-4ef6ec18eaa0"
        },
        {
            "BoundingBox": {
                "Width": 0.5349419713020325,
                "Top": 0.29124999046325684,
                "Left": 0.16389399766921997,
                "Height": 0.40187498927116394
            },
            "FaceId": "745f7509-b1fa-44e0-8b95-367b1359638a",
            "ExternalImageId": "image7.jpg",
            "Confidence": 99.99979400634766,
            "ImageId": "67a34327-48d1-5179-b042-01e52ccfeada"
        },
        {
            "BoundingBox": {
                "Width": 0.41499999165534973,
                "Top": 0.09187500178813934,
                "Left": 0.28083300590515137,
                "Height": 0.3112500011920929
            },
            "FaceId": "8d3cfc70-4ba8-4b36-9644-90fba29c2dac",
            "ExternalImageId": "image8.jpg",
            "Confidence": 99.99769592285156,
            "ImageId": "a294da46-2cb1-5cc4-9045-61d7ca567662"
        },
        {
            "BoundingBox": {
                "Width": 0.48166701197624207,
                "Top": 0.20999999344348907,
                "Left": 0.21250000596046448,
                "Height": 0.36125001311302185
            },
            "FaceId": "bd4ceb4d-9acc-4ab7-8ef8-1c2d2ba0a66a",
            "ExternalImageId": "image9.jpg",
            "Confidence": 99.99949645996094,
            "ImageId": "5e1a7588-e5a0-5ee3-bd00-c642518dfe3a"
        },
        {
            "BoundingBox": {
                "Width": 0.18562500178813934,
                "Top": 0.1618019938468933,
                "Left": 0.5575000047683716,
                "Height": 0.24770599603652954
            },
            "FaceId": "ce7ed422-2132-4a11-ab14-06c5c410f29f",
            "ExternalImageId": "image10.jpg",
            "Confidence": 99.99340057373047,
            "ImageId": "8d67061e-90d2-598f-9fbd-29c8497039c0"
        }
    ]
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[コレクション内の顔と関連するユーザーを一覧表示します。](https://docs.aws.amazon.com/rekognition/latest/dg/list-faces-in-collection-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListFaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/list-faces.html)」を参照してください。**

### `list-stream-processors`
<a name="rekognition_ListStreamProcessors_cli_2_topic"></a>

次のコード例は、`list-stream-processors` を使用する方法を示しています。

**AWS CLI**  
**アカウントのストリームプロセッサを一覧表示するには**  
次の `list-stream-processors` コマンドは、アカウントのストリームプロセッサとそれぞれの状態を一覧表示します。  

```
aws rekognition list-stream-processors
```
出力:  

```
{
    "StreamProcessors": [
        {
            "Status": "STOPPED",
            "Name": "my-stream-processor"
        }
    ]
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ストリーミングビデオの使用](https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStreamProcessors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/list-stream-processors.html)」を参照してください。

### `recognize-celebrities`
<a name="rekognition_RecognizeCelebrities_cli_2_topic"></a>

次のコード例は、`recognize-celebrities` を使用する方法を示しています。

詳細については、「[イメージ内で有名人を認識する](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-procedure-image.html)」を参照してください。

**AWS CLI**  
**画像内の有名人を認識するには**  
次の `recognize-celebrities` コマンドは、Amazon S3 バケットに保存されている指定された画像の有名人を識別します。  

```
aws rekognition recognize-celebrities \
    --image "S3Object={Bucket=MyImageS3Bucket,Name=moviestars.jpg}"
```
出力:  

```
{
    "UnrecognizedFaces": [
        {
            "BoundingBox": {
                "Width": 0.14416666328907013,
                "Top": 0.07777778059244156,
                "Left": 0.625,
                "Height": 0.2746031880378723
            },
            "Confidence": 99.9990234375,
            "Pose": {
                "Yaw": 10.80408763885498,
                "Roll": -12.761146545410156,
                "Pitch": 10.96889877319336
            },
            "Quality": {
                "Sharpness": 94.1185531616211,
                "Brightness": 79.18367004394531
            },
            "Landmarks": [
                {
                    "Y": 0.18220913410186768,
                    "X": 0.6702951788902283,
                    "Type": "eyeLeft"
                },
                {
                    "Y": 0.16337193548679352,
                    "X": 0.7188183665275574,
                    "Type": "eyeRight"
                },
                {
                    "Y": 0.20739148557186127,
                    "X": 0.7055801749229431,
                    "Type": "nose"
                },
                {
                    "Y": 0.2889308035373688,
                    "X": 0.687512218952179,
                    "Type": "mouthLeft"
                },
                {
                    "Y": 0.2706988751888275,
                    "X": 0.7250053286552429,
                    "Type": "mouthRight"
                }
            ]
        }
    ],
    "CelebrityFaces": [
        {
            "MatchConfidence": 100.0,
            "Face": {
                "BoundingBox": {
                    "Width": 0.14000000059604645,
                    "Top": 0.1190476194024086,
                    "Left": 0.82833331823349,
                    "Height": 0.2666666805744171
                },
                "Confidence": 99.99359130859375,
                "Pose": {
                    "Yaw": -10.509642601013184,
                    "Roll": -14.51749324798584,
                    "Pitch": 13.799399375915527
                },
                "Quality": {
                    "Sharpness": 78.74752044677734,
                    "Brightness": 42.201324462890625
                },
                "Landmarks": [
                    {
                        "Y": 0.2290833294391632,
                        "X": 0.8709492087364197,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.20639978349208832,
                        "X": 0.9153988361358643,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.25417643785476685,
                        "X": 0.8907724022865295,
                        "Type": "nose"
                    },
                    {
                        "Y": 0.32729196548461914,
                        "X": 0.8876466155052185,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.3115464746952057,
                        "X": 0.9238573312759399,
                        "Type": "mouthRight"
                    }
                ]
            },
            "Name": "Celeb A",
            "Urls": [
                "www.imdb.com/name/aaaaaaaaa"
            ],
            "Id": "1111111"
        },
        {
            "MatchConfidence": 97.0,
            "Face": {
                "BoundingBox": {
                    "Width": 0.13333334028720856,
                    "Top": 0.24920634925365448,
                    "Left": 0.4449999928474426,
                    "Height": 0.2539682686328888
                },
                "Confidence": 99.99979400634766,
                "Pose": {
                    "Yaw": 6.557040691375732,
                    "Roll": -7.316643714904785,
                    "Pitch": 9.272967338562012
                },
                "Quality": {
                    "Sharpness": 83.23492431640625,
                    "Brightness": 78.83267974853516
                },
                "Landmarks": [
                    {
                        "Y": 0.3625510632991791,
                        "X": 0.48898839950561523,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.35366007685661316,
                        "X": 0.5313721299171448,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.3894785940647125,
                        "X": 0.5173314809799194,
                        "Type": "nose"
                    },
                    {
                        "Y": 0.44889405369758606,
                        "X": 0.5020005702972412,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.4408611059188843,
                        "X": 0.5351271629333496,
                        "Type": "mouthRight"
                    }
                ]
            },
            "Name": "Celeb B",
            "Urls": [
                "www.imdb.com/name/bbbbbbbbb"
            ],
            "Id": "2222222"
        },
        {
            "MatchConfidence": 100.0,
            "Face": {
                "BoundingBox": {
                    "Width": 0.12416666746139526,
                    "Top": 0.2968254089355469,
                    "Left": 0.2150000035762787,
                    "Height": 0.23650793731212616
                },
                "Confidence": 99.99958801269531,
                "Pose": {
                    "Yaw": 7.801797866821289,
                    "Roll": -8.326810836791992,
                    "Pitch": 7.844768047332764
                },
                "Quality": {
                    "Sharpness": 86.93206024169922,
                    "Brightness": 79.81291198730469
                },
                "Landmarks": [
                    {
                        "Y": 0.4027804136276245,
                        "X": 0.2575301229953766,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.3934555947780609,
                        "X": 0.2956969439983368,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.4309830069541931,
                        "X": 0.2837020754814148,
                        "Type": "nose"
                    },
                    {
                        "Y": 0.48186683654785156,
                        "X": 0.26812544465065,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.47338807582855225,
                        "X": 0.29905644059181213,
                        "Type": "mouthRight"
                    }
                ]
            },
            "Name": "Celeb C",
            "Urls": [
                "www.imdb.com/name/ccccccccc"
            ],
            "Id": "3333333"
        },
        {
            "MatchConfidence": 97.0,
            "Face": {
                "BoundingBox": {
                    "Width": 0.11916666477918625,
                    "Top": 0.3698412775993347,
                    "Left": 0.008333333767950535,
                    "Height": 0.22698412835597992
                },
                "Confidence": 99.99999237060547,
                "Pose": {
                    "Yaw": 16.38478660583496,
                    "Roll": -1.0260354280471802,
                    "Pitch": 5.975185394287109
                },
                "Quality": {
                    "Sharpness": 83.23492431640625,
                    "Brightness": 61.408443450927734
                },
                "Landmarks": [
                    {
                        "Y": 0.4632347822189331,
                        "X": 0.049406956881284714,
                        "Type": "eyeLeft"
                    },
                    {
                        "Y": 0.46388113498687744,
                        "X": 0.08722897619009018,
                        "Type": "eyeRight"
                    },
                    {
                        "Y": 0.5020678639411926,
                        "X": 0.0758260041475296,
                        "Type": "nose"
                    },
                    {
                        "Y": 0.544157862663269,
                        "X": 0.054029736667871475,
                        "Type": "mouthLeft"
                    },
                    {
                        "Y": 0.5463630557060242,
                        "X": 0.08464983850717545,
                        "Type": "mouthRight"
                    }
                ]
            },
            "Name": "Celeb D",
            "Urls": [
                "www.imdb.com/name/ddddddddd"
            ],
            "Id": "4444444"
        }
    ]
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[イメージ内の有名人の認識](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-procedure-image.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[RecognizeCelebrities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/recognize-celebrities.html)」を参照してください。**

### `search-faces-by-image`
<a name="rekognition_SearchFacesByImage_cli_2_topic"></a>

次のコード例は、`search-faces-by-image` を使用する方法を示しています。

詳細については、「[顔を検索する (イメージ)](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-image-procedure.html)」を参照してください。

**AWS CLI**  
**画像内の最大の顔と一致するコレクション内の顔を検索するには**  
次の `search-faces-by-image` コマンドは、指定された画像内の最大の顔と一致するコレクション内の顔を検索します。  

```
aws rekognition search-faces-by-image \
    --image '{"S3Object":{"Bucket":"MyImageS3Bucket","Name":"ExamplePerson.jpg"}}' \
    --collection-id MyFaceImageCollection

{
    "SearchedFaceBoundingBox": {
        "Width": 0.18562500178813934,
        "Top": 0.1618015021085739,
        "Left": 0.5575000047683716,
        "Height": 0.24770642817020416
    },
    "SearchedFaceConfidence": 99.993408203125,
    "FaceMatches": [
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.18562500178813934,
                    "Top": 0.1618019938468933,
                    "Left": 0.5575000047683716,
                    "Height": 0.24770599603652954
                },
                "FaceId": "ce7ed422-2132-4a11-ab14-06c5c410f29f",
                "ExternalImageId": "example-image.jpg",
                "Confidence": 99.99340057373047,
                "ImageId": "8d67061e-90d2-598f-9fbd-29c8497039c0"
            },
            "Similarity": 99.97913360595703
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.18562500178813934,
                    "Top": 0.1618019938468933,
                    "Left": 0.5575000047683716,
                    "Height": 0.24770599603652954
                },
                "FaceId": "13692fe4-990a-4679-b14a-5ac23d135eab",
                "ExternalImageId": "image3.jpg",
                "Confidence": 99.99340057373047,
                "ImageId": "8df18239-9ad1-5acd-a46a-6581ff98f51b"
            },
            "Similarity": 99.97913360595703
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.41499999165534973,
                    "Top": 0.09187500178813934,
                    "Left": 0.28083300590515137,
                    "Height": 0.3112500011920929
                },
                "FaceId": "8d3cfc70-4ba8-4b36-9644-90fba29c2dac",
                "ExternalImageId": "image2.jpg",
                "Confidence": 99.99769592285156,
                "ImageId": "a294da46-2cb1-5cc4-9045-61d7ca567662"
            },
            "Similarity": 99.18069458007812
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.48166701197624207,
                    "Top": 0.20999999344348907,
                    "Left": 0.21250000596046448,
                    "Height": 0.36125001311302185
                },
                "FaceId": "bd4ceb4d-9acc-4ab7-8ef8-1c2d2ba0a66a",
                "ExternalImageId": "image1.jpg",
                "Confidence": 99.99949645996094,
                "ImageId": "5e1a7588-e5a0-5ee3-bd00-c642518dfe3a"
            },
            "Similarity": 98.66607666015625
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5349419713020325,
                    "Top": 0.29124999046325684,
                    "Left": 0.16389399766921997,
                    "Height": 0.40187498927116394
                },
                "FaceId": "745f7509-b1fa-44e0-8b95-367b1359638a",
                "ExternalImageId": "image9.jpg",
                "Confidence": 99.99979400634766,
                "ImageId": "67a34327-48d1-5179-b042-01e52ccfeada"
            },
            "Similarity": 98.24278259277344
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5307819843292236,
                    "Top": 0.2862499952316284,
                    "Left": 0.1564060002565384,
                    "Height": 0.3987500071525574
                },
                "FaceId": "2eb5f3fd-e2a9-4b1c-a89f-afa0a518fe06",
                "ExternalImageId": "image10.jpg",
                "Confidence": 99.99970245361328,
                "ImageId": "3c314792-197d-528d-bbb6-798ed012c150"
            },
            "Similarity": 98.10665893554688
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5074880123138428,
                    "Top": 0.3774999976158142,
                    "Left": 0.18302799761295319,
                    "Height": 0.3812499940395355
                },
                "FaceId": "086261e8-6deb-4bc0-ac73-ab22323cc38d",
                "ExternalImageId": "image6.jpg",
                "Confidence": 99.99930572509766,
                "ImageId": "ae1593b0-a8f6-5e24-a306-abf529e276fa"
            },
            "Similarity": 98.10526275634766
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5574039816856384,
                    "Top": 0.37187498807907104,
                    "Left": 0.14559100568294525,
                    "Height": 0.4181250035762787
                },
                "FaceId": "11c4bd3c-19c5-4eb8-aecc-24feb93a26e1",
                "ExternalImageId": "image5.jpg",
                "Confidence": 99.99960327148438,
                "ImageId": "80739b4d-883f-5b78-97cf-5124038e26b9"
            },
            "Similarity": 97.94659423828125
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5773710012435913,
                    "Top": 0.34437501430511475,
                    "Left": 0.12396000325679779,
                    "Height": 0.4337500035762787
                },
                "FaceId": "57189455-42b0-4839-a86c-abda48b13174",
                "ExternalImageId": "image8.jpg",
                "Confidence": 100.0,
                "ImageId": "0aff2f37-e7a2-5dbc-a3a3-4ef6ec18eaa0"
            },
            "Similarity": 97.93476867675781
        }
    ],
    "FaceModelVersion": "3.0"
}
```
詳細については、「Amazon Rekognition 開発者ガイド」の「[画像付きの顔を検索する](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-image-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[SearchFacesByImage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/search-faces-by-image.html)」を参照してください。**

### `search-faces`
<a name="rekognition_SearchFaces_cli_2_topic"></a>

次のコード例は、`search-faces` を使用する方法を示しています。

詳細については、[顔 (フェイス ID) を検索する](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-id-procedure.html) を参照してください。

**AWS CLI**  
**顔 ID に一致するコレクション内の顔を検索するには**  
次の `search-faces` コマンドは、指定され顔 ID に一致するコレクション内の顔を検索します。  

```
aws rekognition search-faces \
    --face-id 8d3cfc70-4ba8-4b36-9644-90fba29c2dac \
    --collection-id MyCollection
```
出力:  

```
{
    "SearchedFaceId": "8d3cfc70-4ba8-4b36-9644-90fba29c2dac",
    "FaceModelVersion": "3.0",
    "FaceMatches": [
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.48166701197624207,
                    "Top": 0.20999999344348907,
                    "Left": 0.21250000596046448,
                    "Height": 0.36125001311302185
                },
                "FaceId": "bd4ceb4d-9acc-4ab7-8ef8-1c2d2ba0a66a",
                "ExternalImageId": "image1.jpg",
                "Confidence": 99.99949645996094,
                "ImageId": "5e1a7588-e5a0-5ee3-bd00-c642518dfe3a"
            },
            "Similarity": 99.30997467041016
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.18562500178813934,
                    "Top": 0.1618019938468933,
                    "Left": 0.5575000047683716,
                    "Height": 0.24770599603652954
                },
                "FaceId": "ce7ed422-2132-4a11-ab14-06c5c410f29f",
                "ExternalImageId": "example-image.jpg",
                "Confidence": 99.99340057373047,
                "ImageId": "8d67061e-90d2-598f-9fbd-29c8497039c0"
            },
            "Similarity": 99.24862670898438
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.18562500178813934,
                    "Top": 0.1618019938468933,
                    "Left": 0.5575000047683716,
                    "Height": 0.24770599603652954
                },
                "FaceId": "13692fe4-990a-4679-b14a-5ac23d135eab",
                "ExternalImageId": "image3.jpg",
                "Confidence": 99.99340057373047,
                "ImageId": "8df18239-9ad1-5acd-a46a-6581ff98f51b"
            },
            "Similarity": 99.24862670898438
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5349419713020325,
                    "Top": 0.29124999046325684,
                    "Left": 0.16389399766921997,
                    "Height": 0.40187498927116394
                },
                "FaceId": "745f7509-b1fa-44e0-8b95-367b1359638a",
                "ExternalImageId": "image9.jpg",
                "Confidence": 99.99979400634766,
                "ImageId": "67a34327-48d1-5179-b042-01e52ccfeada"
            },
            "Similarity": 96.73158264160156
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5307819843292236,
                    "Top": 0.2862499952316284,
                    "Left": 0.1564060002565384,
                    "Height": 0.3987500071525574
                },
                "FaceId": "2eb5f3fd-e2a9-4b1c-a89f-afa0a518fe06",
                "ExternalImageId": "image10.jpg",
                "Confidence": 99.99970245361328,
                "ImageId": "3c314792-197d-528d-bbb6-798ed012c150"
            },
            "Similarity": 96.48291015625
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5074880123138428,
                    "Top": 0.3774999976158142,
                    "Left": 0.18302799761295319,
                    "Height": 0.3812499940395355
                },
                "FaceId": "086261e8-6deb-4bc0-ac73-ab22323cc38d",
                "ExternalImageId": "image6.jpg",
                "Confidence": 99.99930572509766,
                "ImageId": "ae1593b0-a8f6-5e24-a306-abf529e276fa"
            },
            "Similarity": 96.43287658691406
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5574039816856384,
                    "Top": 0.37187498807907104,
                    "Left": 0.14559100568294525,
                    "Height": 0.4181250035762787
                },
                "FaceId": "11c4bd3c-19c5-4eb8-aecc-24feb93a26e1",
                "ExternalImageId": "image5.jpg",
                "Confidence": 99.99960327148438,
                "ImageId": "80739b4d-883f-5b78-97cf-5124038e26b9"
            },
            "Similarity": 95.25305938720703
        },
        {
            "Face": {
                "BoundingBox": {
                    "Width": 0.5773710012435913,
                    "Top": 0.34437501430511475,
                    "Left": 0.12396000325679779,
                    "Height": 0.4337500035762787
                },
                "FaceId": "57189455-42b0-4839-a86c-abda48b13174",
                "ExternalImageId": "image8.jpg",
                "Confidence": 100.0,
                "ImageId": "0aff2f37-e7a2-5dbc-a3a3-4ef6ec18eaa0"
            },
            "Similarity": 95.22837829589844
        }
    ]
}
```
詳細については、「Amazon Rekognition ディベロッパーガイド」の「[Face ID で顔を検索する](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-id-procedure.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[SearchFaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/search-faces.html)」を参照してください。**

### `start-celebrity-recognition`
<a name="rekognition_StartCelebrityRecognition_cli_2_topic"></a>

次のコード例は、`start-celebrity-recognition` を使用する方法を示しています。

**AWS CLI**  
**保存したビデオ内の有名人の認識を開始するには**  
次の `start-celebrity-recognition` コマンドは、Amazon S3 バケットに保存されている指定されたビデオファイル内の有名人を検索するジョブを開始します。  

```
aws rekognition start-celebrity-recognition \
    --video "S3Object={Bucket=MyVideoS3Bucket,Name=MyVideoFile.mpg}"
```
出力:  

```
{
    "JobId": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存されたビデオ内の有名人の認識](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-video-sqs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartCelebrityRecognition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/start-celebrity-recognition.html)」を参照してください。

### `start-content-moderation`
<a name="rekognition_StartContentModeration_cli_2_topic"></a>

次のコード例は、`start-content-moderation` を使用する方法を示しています。

**AWS CLI**  
**保存したビデオ内の安全でないコンテンツの認識を開始するには**  
次の `start-content-moderation` コマンドは、Amazon S3 バケットに保存されている指定されたビデオの安全でないコンテンツを検出するジョブを開始します。  

```
aws rekognition start-content-moderation \
    --video "S3Object={Bucket=MyVideoS3Bucket,Name=MyVideoFile.mpg}"
```
出力:  

```
{
    "JobId": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存された安全でないビデオの検出](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-videos.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartContentModeration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/start-content-moderation.html)」を参照してください。

### `start-face-detection`
<a name="rekognition_StartFaceDetection_cli_2_topic"></a>

次のコード例は、`start-face-detection` を使用する方法を示しています。

**AWS CLI**  
**ビデオ内の顔を検出するには**  
次の `start-face-detection` コマンドは、Amazon S3 バケットに保存されている指定されたビデオの顔を検出するジョブを開始します。  

```
aws rekognition start-face-detection
    --video "S3Object={Bucket=MyVideoS3Bucket,Name=MyVideoFile.mpg}"
```
出力:  

```
{
    "JobId": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存済みビデオ内の顔の検出](https://docs.aws.amazon.com/rekognition/latest/dg/faces-sqs-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartFaceDetection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/start-face-detection.html)」を参照してください。

### `start-face-search`
<a name="rekognition_StartFaceSearch_cli_2_topic"></a>

次のコード例は、`start-face-search` を使用する方法を示しています。

**AWS CLI**  
**ビデオで検出された顔に一致するコレクション内の顔を検索するには**  
次の `start-face-search` コマンドは、Amazon S3 バケット内の指定されたビデオファイルで検出された顔と一致するコレクション内の顔を検索するジョブを開始します。  

```
aws rekognition start-face-search \
    --video "S3Object={Bucket=MyVideoS3Bucket,Name=MyVideoFile.mpg}" \
    --collection-id collection
```
出力:  

```
{
    "JobId": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[保存済みビデオ内の顔の検索](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-person-search-videos.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartFaceSearch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/start-face-search.html)」を参照してください。

### `start-label-detection`
<a name="rekognition_StartLabelDetection_cli_2_topic"></a>

次のコード例は、`start-label-detection` を使用する方法を示しています。

**AWS CLI**  
**ビデオ内のオブジェクトとシーンを検出するには**  
次の `start-label-detection` コマンドは、Amazon S3 バケットに保存されている指定されたビデオのオブジェクトとシーンを検出するジョブを開始します。  

```
aws rekognition start-label-detection \
    --video "S3Object={Bucket=MyVideoS3Bucket,Name=MyVideoFile.mpg}"
```
出力:  

```
{
    "JobId": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ビデオ内のラベルの検出](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detecting-labels-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartLabelDetection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/start-label-detection.html)」を参照してください。

### `start-person-tracking`
<a name="rekognition_StartPersonTracking_cli_2_topic"></a>

次のコード例は、`start-person-tracking` を使用する方法を示しています。

**AWS CLI**  
**保存されたビデオの人物のパスを開始するには**  
次の `start-person-tracking` コマンドは、Amazon S3 バケットに保存されている指定されたビデオフィールでユーザーが取るパスを追跡するジョブを開始します。  

```
aws rekognition start-person-tracking \
    --video "S3Object={Bucket=MyVideoS3Bucket,Name=MyVideoFile.mpg}"
```
出力:  

```
{
    "JobId": "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
}
```
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[人物パス](https://docs.aws.amazon.com/rekognition/latest/dg/persons.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartPersonTracking](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/start-person-tracking.html)」を参照してください。

### `start-stream-processor`
<a name="rekognition_StartStreamProcessor_cli_2_topic"></a>

次のコード例は、`start-stream-processor` を使用する方法を示しています。

**AWS CLI**  
**ストリームプロセッサを開始するには**  
次の `start-stream-processor` コマンドは、指定されたビデオストリームプロセッサを起動します。  

```
aws rekognition start-stream-processor \
    --name my-stream-processor
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ストリーミングビデオの使用](https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartStreamProcessor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/start-stream-processor.html)」を参照してください。

### `stop-stream-processor`
<a name="rekognition_StopStreamProcessor_cli_2_topic"></a>

次のコード例は、`stop-stream-processor` を使用する方法を示しています。

**AWS CLI**  
**実行中のストリームプロセッサを停止するには**  
次の `stop-stream-processor` コマンドは、指定された実行中のストリームプロセッサを停止します。  

```
aws rekognition stop-stream-processor \
    --name my-stream-processor
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Rekognition デベロッパーガイド*」の「[ストリーミングビデオの使用](https://docs.aws.amazon.com/rekognition/latest/dg/streaming-video.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopStreamProcessor](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rekognition/stop-stream-processor.html)」を参照してください。

# AWS RAM を使用した の例 AWS CLI
<a name="cli_2_ram_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS RAM。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-resource-share-invitation`
<a name="ram_AcceptResourceShareInvitation_cli_2_topic"></a>

次のコード例は、`accept-resource-share-invitation` を使用する方法を示しています。

**AWS CLI**  
**リソース共有の招待を受け入れるには**  
次の `accept-resource-share-invitation` の例では、指定されたリソース共有の招待を受け入れます。招待されたアカウントのプリンシパルは、共有内のリソースの使用をすぐに開始できます。  

```
aws ram accept-resource-share-invitation \
    --resource-share-invitation-arn arn:aws:ram:us-west-2:111111111111:resource-share-invitation/1e3477be-4a95-46b4-bbe0-c4001EXAMPLE
```
出力:  

```
{
    "resourceShareInvitation": {
        "resourceShareInvitationArn": "arn:aws:ram:us-west-2:111111111111:resource-share-invitation/1e3477be-4a95-46b4-bbe0-c4001EXAMPLE",
        "resourceShareName": "MyLicenseShare",
        "resourceShareArn": "arn:aws:ram:us-west-2:111111111111:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE",
        "senderAccountId": "111111111111",
        "receiverAccountId": "222222222222",
        "invitationTimestamp": "2021-09-22T15:07:35.620000-07:00",
        "status": "ACCEPTED"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptResourceShareInvitation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/accept-resource-share-invitation.html)」を参照してください。

### `associate-resource-share-permission`
<a name="ram_AssociateResourceSharePermission_cli_2_topic"></a>

次のコード例は、`associate-resource-share-permission` を使用する方法を示しています。

**AWS CLI**  
**RAM マネージドアクセス許可をリソース共有に関連付けるには**  
次の `associate-resource-share-permission` の例では、関連するリソースタイプの既存のマネージドアクセス許可を、指定されたマネージドアクセス許可に置き換えます。関連するリソースタイプのすべてのリソースへのアクセスは、新しいアクセス許可によって管理されます。  

```
aws ram associate-resource-share-permission \
    --permission-arn arn:aws:ram::aws:permission/AWSRAMPermissionGlueDatabaseReadWrite \
    --replace \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE
```
出力:  

```
{
    "returnValue": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateResourceSharePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/associate-resource-share-permission.html)」を参照してください。

### `associate-resource-share`
<a name="ram_AssociateResourceShare_cli_2_topic"></a>

次のコード例は、`associate-resource-share` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソースをリソース共有に関連付けるには**  
次の `associate-resource-share` の例では、指定されたリソース共有にライセンス設定 を追加します。  

```
aws ram associate-resource-share \
    --resource-share arn:aws:ram:us-west-2:123456789012:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE \
    --resource-arns arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-36be0485f5ae379cc74cf8e92EXAMPLE
```
出力:  

```
{
    "resourceShareAssociations": [
        {
           "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE",
           "associatedEntity": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-36be0485f5ae379cc74cf8e92EXAMPLE",
           "associationType": "RESOURCE",
           "status": "ASSOCIATING",
           "external": false
        }
    ]
}
```
**例 2: プリンシパルをリソース共有に関連付けるには**  
次の `associate-resource-share` の例では、指定された組織単位内のすべてのアカウントに、指定されたリソース共有へのアクセスを許可します。  

```
aws ram associate-resource-share \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE \
    --principals arn:aws:organizations::123456789012:ou/o-63bEXAMPLE/ou-46xi-rEXAMPLE
```
出力:  

```
{
    "resourceShareAssociations": [
        {
            "status": "ASSOCIATING",
            "associationType": "PRINCIPAL",
            "associatedEntity": "arn:aws:organizations::123456789012:ou/o-63bEXAMPLE/ou-46xi-rEXAMPLE",
            "external": false,
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateResourceShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/associate-resource-share.html)」を参照してください。

### `create-resource-share`
<a name="ram_CreateResourceShare_cli_2_topic"></a>

次のコード例は、`create-resource-share` を使用する方法を示しています。

**AWS CLI**  
**例 1: リソース共有を作成するには**  
次の `create-resource-share` の例では、指定された名前で空のリソース共有を作成します。リソース、プリンシパル、およびアクセス許可を共有に個別に追加する必要があります。  

```
aws ram create-resource-share \
    --name MyNewResourceShare
```
出力:  

```
{
    "resourceShare": {
        "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/4476c27d-8feb-4b21-afe9-7de23EXAMPLE",
        "name": "MyNewResourceShare",
        "owningAccountId": "123456789012",
        "allowExternalPrincipals": true,
        "status": "ACTIVE",
        "creationTime": 1634586271.302,
        "lastUpdatedTime": 1634586271.302
    }
}
```
**例 2: AWS アカウントをプリンシパルとしてリソース共有を作成するには**  
次の の`create-resource-share`例では、リソース共有を作成し、指定された AWS アカウント (222222222222) へのアクセスを許可します。指定されたプリンシパルが同じ AWS Organization の一部でない場合、招待が送信され、アクセスを許可する前に承諾する必要があります。  

```
aws ram create-resource-share \
    --name MyNewResourceShare \
    --principals 222222222222
```
**例 3: Organization に制限されたリソース共有を作成するには AWS **  
次の`create-resource-share`例では、アカウントがメンバーである AWS Organization 内のアカウントに制限されたリソース共有を作成し、指定された OU をプリンシパルとして追加します。その OU 内のすべてのアカウントは、リソース共有のリソースを使用できます。  

```
aws ram create-resource-share \
    --name MyNewResourceShare \
    --no-allow-external-principals \
    --principals arn:aws:organizations::123456789012:ou/o-63bEXAMPLE/ou-46xi-rEXAMPLE
```
出力:  

```
{
    "resourceShare": {
        "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7be8694e-095c-41ca-9ce8-7be4aEXAMPLE",
        "name": "MyNewResourceShare",
        "owningAccountId": "123456789012",
        "allowExternalPrincipals": false,
        "status": "ACTIVE",
        "creationTime": 1634587042.49,
        "lastUpdatedTime": 1634587042.49
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResourceShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/create-resource-share.html)」を参照してください。

### `delete-resource-share`
<a name="ram_DeleteResourceShare_cli_2_topic"></a>

次のコード例は、`delete-resource-share` を使用する方法を示しています。

**AWS CLI**  
**リソース共有を削除するには**  
次の `delete-resource-share` の例では、指定されたリソース共有を削除します。  

```
aws ram delete-resource-share \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE
```
次の出力は、正しく処理されたことを示しています。  

```
{
    "returnValue": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourceShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/delete-resource-share.html)」を参照してください。

### `disassociate-resource-share-permission`
<a name="ram_DisassociateResourceSharePermission_cli_2_topic"></a>

次のコード例は、`disassociate-resource-share-permission` を使用する方法を示しています。

**AWS CLI**  
**リソース共有からリソースタイプの RAM 管理アクセス許可を削除するには**  
次の `disassociate-resource-share-permission` の例では、指定されたリソース共有から Glue データベースの RAM 管理アクセス許可を削除します。  

```
aws ram disassociate-resource-share-permission \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE \
    --permission-arn arn:aws:ram::aws:permission/AWSRAMPermissionGlueDatabaseReadWrite
```
出力:  

```
{
    "returnValue": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateResourceSharePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/disassociate-resource-share-permission.html)」を参照してください。

### `disassociate-resource-share`
<a name="ram_DisassociateResourceShare_cli_2_topic"></a>

次のコード例は、`disassociate-resource-share` を使用する方法を示しています。

**AWS CLI**  
**リソース共有からリソースを削除するには**  
次の `disassociate-resource-share` の例では、指定されたリソース、この場合は VPC サブネットを指定されたリソース共有から削除します。リソース共有にアクセスできるプリンシパルは、そのリソースに対してオペレーションを実行できなくなります。  

```
aws ram disassociate-resource-share \
    --resource-arns arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0250c25a1fEXAMPLE \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE
```
出力:  

```
{
    "resourceShareAssociations": [
        "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE",
        "associatedEntity": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0250c25a1fEXAMPLE",
        "associationType": "RESOURCE",
        "status": "DISASSOCIATING",
        "external": false
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateResourceShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/disassociate-resource-share.html)」を参照してください。

### `enable-sharing-with-aws-organization`
<a name="ram_EnableSharingWithAwsOrganization_cli_2_topic"></a>

次の例は、`enable-sharing-with-aws-organization` を使用する方法を説明しています。

**AWS CLI**  
** AWS Organizations 間でリソース共有を有効にするには**  
次の `enable-sharing-with-aws-organization` の例では、組織および組織単位間でリソース共有を有効にします。  

```
aws ram enable-sharing-with-aws-organization
```
次の出力は、正しく処理されたことを示しています。  

```
{
    "returnValue": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableSharingWithAwsOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/enable-sharing-with-aws-organization.html)」を参照してください。

### `get-permission`
<a name="ram_GetPermission_cli_2_topic"></a>

次のコード例は、`get-permission` を使用する方法を示しています。

**AWS CLI**  
**RAM 管理アクセス許可の詳細を取得するには**  
次の `get-permission` の例では、指定された RAM 管理アクセス許可のデフォルトバージョンの詳細を表示します。  

```
aws ram get-permission \
    --permission-arn arn:aws:ram::aws:permission/AWSRAMPermissionGlueTableReadWriteForDatabase
```
出力:  

```
{
    "permission": {
        "arn": "arn:aws:ram::aws:permission/AWSRAMPermissionGlueTableReadWriteForDatabase",
        "version": "2",
        "defaultVersion": true,
        "name": "AWSRAMPermissionGlueTableReadWriteForDatabase",
        "resourceType": "glue:Database",
        "permission": "{\"Effect\":\"Allow\",\"Action\":[\"glue:GetTable\", \"glue:UpdateTable\", \"glue:DeleteTable\", \"glue:BatchDeleteTable\", \"glue:BatchDeleteTableVersion\", \"glue:GetTableVersion\", \"glue:GetTableVersions\", \"glue:GetPartition\", \"glue:GetPartitions\", \"glue:BatchGetPartition\", \"glue:BatchCreatePartition\", \"glue:CreatePartition\", \"glue:UpdatePartition\", \"glue:BatchDeletePartition\", \"glue:DeletePartition\", \"glue:GetTables\", \"glue:SearchTables\"]}",
        "creationTime": 1624912434.431,
        "lastUpdatedTime": 1624912434.431,
        "isResourceTypeDefault": false
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/get-permission.html)」を参照してください。

### `get-resource-policies`
<a name="ram_GetResourcePolicies_cli_2_topic"></a>

次のコード例は、`get-resource-policies` を使用する方法を示しています。

**AWS CLI**  
**リソースのポリシーを取得するには**  
次の `get-resource-policies` の例では、リソース共有に関連付けられている指定されたリソースのリソースベースのアクセス許可ポリシーを表示します。  

```
aws ram get-resource-policies \
    --resource-arns arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0250c25a1fEXAMPLE
```
出力:  

```
{
    "policies": [
         "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Sid\":\"RamStatement1\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[]},\"Action\":[\"ec2:RunInstances\",\"ec2:CreateNetworkInterface\",\"ec2:DescribeSubnets\"],\"Resource\":\"arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0250c25a1fEXAMPLE\"}]}"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourcePolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/get-resource-policies.html)」を参照してください。

### `get-resource-share-associations`
<a name="ram_GetResourceShareAssociations_cli_2_topic"></a>

次のコード例は、`get-resource-share-associations` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのリソースタイプのすべてのリソース関連付けを一覧表示するには**  
次の `get-resource-share-associations` の例では、すべてのリソース共有の全リソースタイプのリソース関連付けを一覧表示します。  

```
aws ram get-resource-share-associations \
    --association-type RESOURCE
```
出力:  

```
{
    "resourceShareAssociations": [
        {
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE",
            "associatedEntity": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-0250c25a1fEXAMPLE",
            "resourceShareName": "MySubnetShare",
            "associationType": "RESOURCE",
            "status": "ASSOCIATED",
            "creationTime": 1565303590.973,
            "lastUpdatedTime": 1565303591.695,
            "external": false
        },
        {
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/8167bdfe-4480-4a01-8632-315e0EXAMPLE",
            "associatedEntity": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-36be0485f5ae379cc74cf8e92EXAMPLE",
            "resourceShareName": "MyLicenseShare",
            "associationType": "RESOURCE",
            "status": "ASSOCIATED",
            "creationTime": 1632342958.457,
            "lastUpdatedTime": 1632342958.907,
            "external": false
        }
    ]
}
```
**例 2: リソース共有のプリンシパル関連付けを一覧表示するには**  
次の `get-resource-share-associations` の例では、指定されたリソース共有のみのプリンシパル関連付けのみを一覧表示します。  

```
aws ram get-resource-share-associations \
   --resource-share-arns arn:aws:ram:us-west-2:123456789012:resource-share/7be8694e-095c-41ca-9ce8-7be4aEXAMPLE \
   --association-type PRINCIPAL
```
出力:  

```
{
    "resourceShareAssociations": [
        {
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7be8694e-095c-41ca-9ce8-7be4aEXAMPLE",
            "resourceShareName": "MyNewResourceShare",
            "associatedEntity": "arn:aws:organizations::123456789012:ou/o-63bEXAMPLE/ou-46xi-rEXAMPLE",
            "associationType": "PRINCIPAL",
            "status": "ASSOCIATED",
            "creationTime": 1634587042.49,
            "lastUpdatedTime": 1634587044.291,
            "external": false
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceShareAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/get-resource-share-associations.html)」を参照してください。

### `get-resource-share-invitations`
<a name="ram_GetResourceShareInvitations_cli_2_topic"></a>

次のコード例は、`get-resource-share-invitations` を使用する方法を示しています。

**AWS CLI**  
**リソース共有の招待を一覧表示するには**  
次の `get-resource-share-invitations` の例では、現在のリソース共有の招待を一覧表示します。  

```
aws ram get-resource-share-invitations
```
出力:  

```
{
    "resourceShareInvitations": [
        {
            "resourceShareInvitationArn": "arn:aws:ram:us-west2-1:111111111111:resource-share-invitation/32b639f0-14b8-7e8f-55ea-e6117EXAMPLE",
            "resourceShareName": "project-resource-share",
            "resourceShareArn": "arn:aws:ram:us-west-2:111111111111:resource-share/fcb639f0-1449-4744-35bc-a983fEXAMPLE",
            "senderAccountId": "111111111111",
            "receiverAccountId": "222222222222",
            "invitationTimestamp": 1565312166.258,
            "status": "PENDING"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceShareInvitations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/get-resource-share-invitations.html)」を参照してください。

### `get-resource-shares`
<a name="ram_GetResourceShares_cli_2_topic"></a>

次のコード例は、`get-resource-shares` を使用する方法を示しています。

**AWS CLI**  
**例 1: 自分が所有し、他のユーザーと共有しているリソース共有を一覧表示するには**  
次の `get-resource-shares` の例では、作成され、他のユーザーと共有しているリソース共有を一覧表示します。  

```
aws ram get-resource-shares \
    --resource-owner SELF
```
出力:  

```
{
    "resourceShares": [
        {
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/3ab63985-99d9-1cd2-7d24-75e93EXAMPLE",
            "name": "my-resource-share",
            "owningAccountId": "123456789012",
            "allowExternalPrincipals": false,
            "status": "ACTIVE",
            "tags": [
                {
                    "key": "project",
                    "value": "lima"
                }
            ]
            "creationTime": 1565295733.282,
            "lastUpdatedTime": 1565295733.282
        },
        {
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE",
            "name": "my-resource-share",
            "owningAccountId": "123456789012",
            "allowExternalPrincipals": true,
            "status": "ACTIVE",
            "creationTime": 1565295733.282,
            "lastUpdatedTime": 1565295733.282
        }
    ]
}
```
**例 2: 他のユーザーが所有し、共有しているリソース共有を一覧表示するには**  
次の `get-resource-shares` の例では、他のユーザーが作成して共有したリソース共有を一覧表示します。この例では、何もありません。  

```
aws ram get-resource-shares \
    --resource-owner OTHER-ACCOUNTS
```
出力:  

```
{
    "resourceShares": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceShares](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/get-resource-shares.html)」を参照してください。

### `list-pending-invitation-resources`
<a name="ram_ListPendingInvitationResources_cli_2_topic"></a>

次のコード例は、`list-pending-invitation-resources` を使用する方法を示しています。

**AWS CLI**  
**保留中のリソース共有で利用可能なリソースを一覧表示するには**  
次の `list-pending-invitation-resources` の例では、指定された招待に関連付けられているリソース共有内のすべてのリソースを一覧表示します。  

```
aws ram list-pending-invitation-resources \
    --resource-share-invitation-arn arn:aws:ram:us-west-2:123456789012:resource-share-invitation/1e3477be-4a95-46b4-bbe0-c4001EXAMPLE
```
出力:  

```
{
   "resources": [
        {
            "arn": "arn:aws:ec2:us-west-2:123456789012:subnet/subnet-04a555b0e6EXAMPLE",
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7be8694e-095c-41ca-9ce8-7be4aEXAMPLE",
            "creationTime": 1634676051.269,
            "lastUpdatedTime": 1634676052.07,
            "status": "AVAILABLE",
            "type": "ec2:Subnet"
        },
        {
            "arn": "arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-36be0485f5ae379cc74cf8e92EXAMPLE",
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE",
            "creationTime": 1624912434.431,
            "lastUpdatedTime": 1624912434.431,
            "status": "AVAILABLE",
            "type": "license-manager:LicenseConfiguration"
      }
   ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPendingInvitationResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/list-pending-invitation-resources.html)」を参照してください。

### `list-permissions`
<a name="ram_ListPermissions_cli_2_topic"></a>

次のコード例は、`list-permissions` を使用する方法を示しています。

**AWS CLI**  
**使用可能な RAM 管理アクセス許可を一覧表示するには**  
次の の`list-permissions`例では、 Glue データベースリソースタイプでのみ使用可能なすべての RAM AWS 管理アクセス許可を一覧表示します。  

```
aws ram list-permissions \
    --resource-type glue:Database
```
出力:  

```
{
    "permissions": [
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMDefaultPermissionGlueDatabase",
            "version": "1",
            "defaultVersion": true,
            "name": "AWSRAMDefaultPermissionGlueDatabase",
            "resourceType": "glue:Database",
            "creationTime": 1592007820.935,
            "lastUpdatedTime": 1592007820.935,
            "isResourceTypeDefault": true
        },
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMPermissionGlueAllTablesReadWriteForDatabase",
            "version": "2",
            "defaultVersion": true,
            "name": "AWSRAMPermissionGlueAllTablesReadWriteForDatabase",
            "resourceType": "glue:Database",
            "creationTime": 1624912413.323,
            "lastUpdatedTime": 1624912413.323,
            "isResourceTypeDefault": false
        },
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMPermissionGlueDatabaseReadWrite",
            "version": "2",
            "defaultVersion": true,
            "name": "AWSRAMPermissionGlueDatabaseReadWrite",
            "resourceType": "glue:Database",
            "creationTime": 1624912417.4,
            "lastUpdatedTime": 1624912417.4,
            "isResourceTypeDefault": false
        },
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMPermissionGlueTableReadWriteForDatabase",
            "version": "2",
            "defaultVersion": true,
            "name": "AWSRAMPermissionGlueTableReadWriteForDatabase",
            "resourceType": "glue:Database",
            "creationTime": 1624912434.431,
            "lastUpdatedTime": 1624912434.431,
            "isResourceTypeDefault": false
        }
    ]
}
```
次の `list-permissions` の例では、すべてのリソースタイプで使用可能な RAM 管理アクセス許可を表示します。  

```
aws ram list-permissions
```
出力:  

```
{
    "permissions": [
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMBlankEndEntityCertificateAPICSRPassthroughIssuanceCertificateAuthority",
            "version": "1",
            "defaultVersion": true,
            "name": "AWSRAMBlankEndEntityCertificateAPICSRPassthroughIssuanceCertificateAuthority",
            "resourceType": "acm-pca:CertificateAuthority",
            "creationTime": 1623264861.085,
            "lastUpdatedTime": 1623264861.085,
            "isResourceTypeDefault": false
        },
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMDefaultPermissionAppMesh",
            "version": "1",
            "defaultVersion": true,
            "name": "AWSRAMDefaultPermissionAppMesh",
            "resourceType": "appmesh:Mesh",
            "creationTime": 1589307188.584,
            "lastUpdatedTime": 1589307188.584,
            "isResourceTypeDefault": true
        },
        ...TRUNCATED FOR BREVITY...
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMSubordinateCACertificatePathLen0IssuanceCertificateAuthority",
            "version": "1",
            "defaultVersion": true,
            "name": "AWSRAMSubordinateCACertificatePathLen0IssuanceCertificateAuthority",
            "resourceType": "acm-pca:CertificateAuthority",
            "creationTime": 1623264876.75,
            "lastUpdatedTime": 1623264876.75,
            "isResourceTypeDefault": false
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/list-permissions.html)」を参照してください。

### `list-principals`
<a name="ram_ListPrincipals_cli_2_topic"></a>

次のコード例は、`list-principals` を使用する方法を示しています。

**AWS CLI**  
**リソースにアクセスできるプリンシパルを一覧表示するには**  
次の `list-principals` の例では、任意のリソース共有を通じて指定されたタイプのリソースにアクセスできるプリンシパルのリストを表示します。  

```
aws ram list-principals \
    --resource-type ec2:Subnet
```
出力:  

```
{
    "principals": [
        {
            "id": "arn:aws:organizations::123456789012:ou/o-gx7EXAMPLE/ou-29c5-zEXAMPLE",
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE",
            "creationTime": 1565298209.737,
            "lastUpdatedTime": 1565298211.019,
            "external": false
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPrincipals](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/list-principals.html)」を参照してください。

### `list-resource-share-permissions`
<a name="ram_ListResourceSharePermissions_cli_2_topic"></a>

次のコード例は、`list-resource-share-permissions` を使用する方法を示しています。

**AWS CLI**  
**リソース共有に現在アタッチされているすべての RAM 管理アクセス許可を一覧表示するには**  
次の `list-resource-share-permissions` の例では、指定されたリソース共有にアタッチされているすべての RAM 管理アクセス許可を一覧表示します。  

```
aws ram list-resource-share-permissions \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/27d09b4b-5e12-41d1-a4f2-19dedEXAMPLE
```
出力:  

```
{
    "permissions": [
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMDefaultPermissionLicenseConfiguration",
            "version": "1",
            "resourceType": "license-manager:LicenseConfiguration",
            "status": "ASSOCIATED",
            "lastUpdatedTime": 1632342984.234
        },
        {
            "arn": "arn:aws:ram::aws:permission/AWSRAMPermissionGlueDatabaseReadWrite",
            "version": "2",
            "resourceType": "glue:Database",
            "status": "ASSOCIATED",
            "lastUpdatedTime": 1632512462.297
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceSharePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/list-resource-share-permissions.html)」を参照してください。

### `list-resource-types`
<a name="ram_ListResourceTypes_cli_2_topic"></a>

次の例は、`list-resource-types` を使用する方法を説明しています。

**AWS CLI**  
**RAM AWS でサポートされているリソースタイプを一覧表示するには**  
次の の`list-resource-types`例では、RAM AWS で現在サポートされているすべてのリソースタイプを一覧表示します。  

```
aws ram list-resource-types
```
出力:  

```
{
    "resourceTypes": [
        {
            "resourceType": "route53resolver:FirewallRuleGroup",
            "serviceName": "route53resolver"
        },
        {
            "resourceType": "ec2:LocalGatewayRouteTable",
            "serviceName": "ec2"
        },
        ...OUTPUT TRUNCATED FOR BREVITY...
        {
            "resourceType": "ec2:Subnet",
            "serviceName": "ec2"
        },
        {
            "resourceType": "ec2:TransitGatewayMulticastDomain",
            "serviceName": "ec2"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/list-resource-types.html)」を参照してください。

### `list-resources`
<a name="ram_ListResources_cli_2_topic"></a>

次のコード例は、`list-resources` を使用する方法を示しています。

**AWS CLI**  
**リソース共有に関連付けられているリソースを一覧表示するには**  
次の `list-resources` の例では、指定されたリソースタイプの、指定されたリソース共有内のすべてのリソースを一覧表示します。  

```
aws ram list-resources \
    --resource-type ec2:Subnet \
    --resource-owner SELF \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE
```
出力:  

```
{
    "resources": [
        {
            "arn": "aarn:aws:ec2:us-west-2:123456789012:subnet/subnet-0250c25a1f4e15235",
            "type": "ec2:Subnet",
            "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE",
            "creationTime": 1565301545.023,
            "lastUpdatedTime": 1565301545.947
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/list-resources.html)」を参照してください。

### `promote-resource-share-created-from-policy`
<a name="ram_PromoteResourceShareCreatedFromPolicy_cli_2_topic"></a>

次の例は、`promote-resource-share-created-from-policy` を使用する方法を説明しています。

**AWS CLI**  
**リソースポリシーベースのリソース共有を RAM AWS の全機能に昇格させるには**  
次の`promote-resource-share-created-from-policy`例では、リソースベースのポリシーをアタッチして暗黙的に作成したリソース共有を取得し、RAM AWS コンソールとその CLI および API オペレーションで完全に機能するように変換します。  

```
aws ram promote-resource-share-created-from-policy \
    --resource-share-arn arn:aws:ram:us-east-1:123456789012:resource-share/91fa8429-2d06-4032-909a-90909EXAMPLE
```
出力:  

```
{
    "returnValue": true
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンスの*」の「[PromoteResourceShareCreatedFromPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/promote-resource-share-created-from-policy.html)」を参照してください。

### `reject-resource-share-invitation`
<a name="ram_RejectResourceShareInvitation_cli_2_topic"></a>

次のコード例は、`reject-resource-share-invitation` を使用する方法を示しています。

**AWS CLI**  
**リソース共有の招待を拒否するには**  
次の `reject-resource-share-invitation` の例では、指定されたリソース共有の招待を拒否します。  

```
aws ram reject-resource-share-invitation \
    --resource-share-invitation-arn arn:aws:ram:us-west-2:111111111111:resource-share-invitation/32b639f0-14b8-7e8f-55ea-e6117EXAMPLE
```
出力:  

```
"resourceShareInvitations": [
    {
        "resourceShareInvitationArn": "arn:aws:ram:us-west2-1:111111111111:resource-share-invitation/32b639f0-14b8-7e8f-55ea-e6117EXAMPLE",
        "resourceShareName": "project-resource-share",
        "resourceShareArn": "arn:aws:ram:us-west-2:111111111111:resource-share/fcb639f0-1449-4744-35bc-a983fEXAMPLE",
        "senderAccountId": "111111111111",
        "receiverAccountId": "222222222222",
        "invitationTimestamp": 1565319592.463,
        "status": "REJECTED"
    }
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectResourceShareInvitation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/reject-resource-share-invitation.html)」を参照してください。

### `tag-resource`
<a name="ram_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソース共有にタグを追加するには**  
次の `tag-resource` の例では、指定されたリソース共有にタグキー `project` と関連付けられた値 `lima` を追加します。  

```
aws ram tag-resource \
    --tags key=project,value=lima \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="ram_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソース共有からタグを削除するには**  
次の `untag-resource` の例では、指定されたリソース共有から `project` タグキーと関連付けられた値を削除します。  

```
aws ram untag-resource \
    --tag-keys project \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/untag-resource.html)」を参照してください。

### `update-resource-share`
<a name="ram_UpdateResourceShare_cli_2_topic"></a>

次のコード例は、`update-resource-share` を使用する方法を示しています。

**AWS CLI**  
**リソース共有を更新するには**  
次の の`update-resource-share`例では、指定されたリソース共有を変更して、 AWS 組織内にない外部プリンシパルを許可します。  

```
aws ram update-resource-share \
    --allow-external-principals \
    --resource-share-arn arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE
```
出力:  

```
{
    "resourceShare": {
        "resourceShareArn": "arn:aws:ram:us-west-2:123456789012:resource-share/7ab63972-b505-7e2a-420d-6f5d3EXAMPLE",
        "name": "my-resource-share",
        "owningAccountId": "123456789012",
        "allowExternalPrincipals": true,
        "status": "ACTIVE",
        "creationTime": 1565295733.282,
        "lastUpdatedTime": 1565303080.023
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResourceShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ram/update-resource-share.html)」を参照してください。

# を使用した Resource Explorer の例 AWS CLI
<a name="cli_2_resource-explorer-2_code_examples"></a>

次のコード例は、Resource Explorer AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-default-view`
<a name="resource-explorer-2_AssociateDefaultView_cli_2_topic"></a>

次の例は、`associate-default-view` を使用する方法を説明しています。

**AWS CLI**  
**Resource Explorer ビューをその AWS リージョンのデフォルトとして設定するには**  
次の`associate-default-view`例では、ARN で指定されたビューを、 オペレーションを呼び出す AWS リージョンのデフォルトビューに設定します。  

```
aws resource-explorer-2 associate-default-view \
    --view-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-Main-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111
```
出力:  

```
{
    "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-Main-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
}
```
詳細については、*AWS 「Resource Explorer ユーザーガイド*」の「 [AWS リージョンでのデフォルトビューの設定](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-set-default.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateDefaultView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/associate-default-view.html)」を参照してください。

### `batch-get-view`
<a name="resource-explorer-2_BatchGetView_cli_2_topic"></a>

次のコード例は、`batch-get-view` を使用する方法を示しています。

**AWS CLI**  
**複数の Resource Explorer ビューの詳細を取得するには**  
次の `batch-get-view` の例では、ARN で指定された 2 つのビューの詳細を表示します。スペースを使用して、--view-arn パラメータ内の複数の ARN を区切ります。  

```
aws resource-explorer-2 batch-get-view \
    --view-arns arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222, \
                arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-Main-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111
```
出力:  

```
{
    "Views": [
        {
            "Filters": {
                "FilterString": "service:ec2"
            },
            "IncludedProperties": [
                {
                    "Name": "tags"
                }
            ],
            "LastUpdatedAt": "2022-07-13T21:33:45.249000+00:00",
            "Owner": "123456789012",
            "Scope": "arn:aws:iam::123456789012:root",
            "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222"
        },
        {
            "Filters": {
                "FilterString": ""
            },
            "IncludedProperties": [
                {
                    "Name": "tags"
                }
            ],
            "LastUpdatedAt": "2022-07-13T20:34:11.314000+00:00",
            "Owner": "123456789012",
            "Scope": "arn:aws:iam::123456789012:root",
            "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-Main-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
        }
    ]
    "Errors": []
}
```
ビューの詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[Resource Explorer ビューについて](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/batch-get-view.html)」を参照してください。

### `create-index`
<a name="resource-explorer-2_CreateIndex_cli_2_topic"></a>

次の例は、`create-index` を使用する方法を説明しています。

**AWS CLI**  
**インデックスを作成して AWS リージョンで Resource Explorer を有効にするには**  
次の`create-index`例では、 オペレーションが呼び出される AWS リージョンにローカルインデックスを作成します。 AWS CLI はランダムな`client-token`パラメータ値を自動的に生成し、値を指定 AWS しない場合は の呼び出しに含めます。  

```
aws resource-explorer-2 create-index \
    --region us-east-1
```
出力:  

```
{
    "Arn": "arn:aws:resource-explorer-2:us-east-1:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222c",
    "CreatedAt": "2022-11-01T20:00:59.149Z",
    "State": "CREATING"
}
```
ローカルインデックスを作成したら、[update-index-type](https://docs.aws.amazon.com/cli/latest/reference/resource-explorer-2/update-index-type.html) コマンドを実行して、アカウントのアグリゲータインデックスに変換できます。  
詳細については、[「Resource Explorer ユーザーガイド」の「 AWS リージョンで Resource Explorer を有効にしてリソースのインデックス](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-service-register.html)を作成する」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/create-index.html)」を参照してください。

### `create-view`
<a name="resource-explorer-2_CreateView_cli_2_topic"></a>

次の例は、`create-view` を使用する方法を説明しています。

**AWS CLI**  
**例 1: AWS リージョンでインデックスのフィルタリングされていないビューを作成するには**  
次の の`create-view`例では、指定された AWS リージョンにビューを作成し、フィルタリングなしでリージョン内のすべての結果を返します。ビューには、返された結果のオプションのタグフィールドが含まれます。このビューはアグリゲータインデックスを含むリージョンで作成されるため、Resource Explorer インデックスを含むアカウント内のすべてのリージョンの結果を含めることができます。  

```
aws resource-explorer-2 create-view \
    --view-name My-Main-View \
    --included-properties Name=tags \
    --region us-east-1
```
出力:  

```
{
    "View": {
        "Filters": {
            "FilterString": ""
        },
        "IncludedProperties": [
            {
                "Name": "tags"
            }
        ],
        "LastUpdatedAt": "2022-07-13T20:34:11.314000+00:00",
        "Owner": "123456789012",
        "Scope": "arn:aws:iam::123456789012:root",
        "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-Main-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
    }
}
```
**例 2: Amazon EC2 に関連付けられたリソースのみ返すビューを作成するには**  
以下では、Amazon EC2 サービスに関連付けられている AWS リージョン内のリソースのみを`us-east-1`返すビューをリージョンに`create-view`作成します。ビューには、返された結果のオプションの `Tags` フィールドが含まれます。このビューはアグリゲータインデックスを含むリージョンで作成されるため、Resource Explorer インデックスを含むアカウント内のすべてのリージョンの結果を含めることができます。  

```
aws resource-explorer-2 create-view \
    --view-name My-EC2-Only-View \
    --included-properties Name=tags \
    --filters FilterString="service:ec2" \
    --region us-east-1
```
出力:  

```
{
    "View": {
        "Filters": {
            "FilterString": "service:ec2"
        },
        "IncludedProperties": [
            {
                "Name":"tags"
            }
        ],
        "LastUpdatedAt": "2022-07-13T21:35:09.059Z",
        "Owner": "123456789012",
        "Scope": "arn:aws:iam::123456789012:root",
        "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222"
    }
}
```
詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[検索に使用するビューの作成](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/create-view.html)」を参照してください。

### `delete-index`
<a name="resource-explorer-2_DeleteIndex_cli_2_topic"></a>

次の例は、`delete-index` を使用する方法を説明しています。

**AWS CLI**  
**インデックスを削除して AWS リージョンで Resource Explorer をオフにするには**  
次の の`delete-index`例では、リクエストを行った AWS リージョンで指定された Resource Explorer インデックスを削除します。  

```
aws resource-explorer-2 delete-index \
    --arn arn:aws:resource-explorer-2:us-west-2:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222 \
    --region us-west-2
```
出力:  

```
{
    "Arn": "arn:aws:resource-explorer-2:us-west-2:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222",
    "State": "DELETING"
}
```
インデックスの削除の詳細については、[AWS 「Resource Explorer ユーザーガイド」の「 AWS リージョンで Resource Explorer をオフにする](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-service-deregister.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/delete-index.html)」を参照してください。

### `delete-view`
<a name="resource-explorer-2_DeleteView_cli_2_topic"></a>

次のコード例は、`delete-view` を使用する方法を示しています。

**AWS CLI**  
**Resource Explorer ビューを削除するには**  
次の `delete-view` の例では、ARN で指定されたビューを削除します。  

```
aws resource-explorer-2 delete-view \
    --view-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111
```
出力:  

```
{
    "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
}
```
詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[ビューの削除](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/delete-view.html)」を参照してください。

### `disassociate-default-view`
<a name="resource-explorer-2_DisassociateDefaultView_cli_2_topic"></a>

次の例は、`disassociate-default-view` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョンのデフォルトの Resource Explorer ビューを削除するには**  
以下では、 オペレーションを呼び出す AWS リージョンのデフォルトの Resource Explorer ビュー`disassociate-default-view`を削除します。このオペレーションを実行した後、リージョン内のすべての検索オペレーションでビューを明示的に指定する必要があります。指定しない場合、オペレーションは失敗します。  

```
aws resource-explorer-2 disassociate-default-view
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「Resource Explorer ユーザーガイド*」の「 [AWS リージョンでのデフォルトビューの設定](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-set-default.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateDefaultView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/disassociate-default-view.html)」を参照してください。

### `get-default-view`
<a name="resource-explorer-2_GetDefaultView_cli_2_topic"></a>

次の例は、`get-default-view` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョンのデフォルトビューである Resource Explorer ビューを取得するには**  
次の の`get-default-view`例では、 オペレーションを呼び出す AWS リージョンのデフォルトであるビューの ARN を取得します。  

```
aws resource-explorer-2 get-default-view
```
出力:  

```
{
    "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/default-view/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
}
```
詳細については、*AWS 「Resource Explorer ユーザーガイド*」の「 [AWS リージョンでのデフォルトビューの設定](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-set-default.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDefaultView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/get-default-view.html)」を参照してください。

### `get-index`
<a name="resource-explorer-2_GetIndex_cli_2_topic"></a>

次のコード例は、`get-index` を使用する方法を示しています。

**AWS CLI**  
**例 1: Resource Explorer アグリゲータインデックスの詳細を取得するには**  
次の の`get-index`例では、指定された AWS リージョンの Resource Explorer インデックスの詳細を表示します。指定されたリージョンにはアカウントのアグリゲータインデックスが含まれているため、出力には、このリージョンのインデックスにデータをレプリケートするリージョンが一覧表示されます。  

```
aws resource-explorer-2 get-index \
    --region us-east-1
```
出力:  

```
{
    "Arn": "arn:aws:resource-explorer-2:us-east-1:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111",
    "CreatedAt": "2022-07-12T18:59:10.503000+00:00",
    "LastUpdatedAt": "2022-07-13T18:41:58.799000+00:00",
    "ReplicatingFrom": [
        "ap-south-1",
        "us-west-2"
    ],
    "State": "ACTIVE",
    "Tags": {},
    "Type": "AGGREGATOR"
}
```
**例 2: Resource Explorer ローカルインデックスの詳細を取得するには**  
次の の`get-index`例では、指定された AWS リージョンの Resource Explorer インデックスの詳細を表示します。指定されたリージョンにはローカルインデックスが含まれているため、出力には、このリージョンのインデックスからデータをレプリケートするリージョンが一覧表示されます。  

```
aws resource-explorer-2 get-index \
    --region us-west-2
```
出力:  

```
{
    "Arn": "arn:aws:resource-explorer-2:us-west-2:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222",
    "CreatedAt": "2022-07-12T18:59:10.503000+00:00",
    "LastUpdatedAt": "2022-07-13T18:41:58.799000+00:00",
    "ReplicatingTo": [
        "us-west-2"
    ],
    "State": "ACTIVE",
    "Tags": {},
    "Type": "LOCAL"
}
```
インデックスの詳細については、[「Resource Explorer ユーザーガイド」の「Resource Explorer が有効になっている AWS リージョン](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-service-check.html)の確認」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIndex](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/get-index.html)」を参照してください。

### `get-view`
<a name="resource-explorer-2_GetView_cli_2_topic"></a>

次のコード例は、`get-view` を使用する方法を示しています。

**AWS CLI**  
**Resource Explorer ビューの詳細を取得するには**  
次の `get-view` の例では、ARN で指定されたビューの詳細を表示します。  

```
aws resource-explorer-2 get-view \
    --view-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111
```
出力:  

```
{
  "Tags" : {},
  "View" : {
        "Filters" : {
            "FilterString" : "service:ec2"
        },
        "IncludedProperties" : [
            {
                "Name" : "tags"
            }
        ],
        "LastUpdatedAt" : "2022-07-13T21:33:45.249Z",
        "Owner" : "123456789012",
        "Scope" : "arn:aws:iam::123456789012:root",
        "ViewArn" : "arn:aws:resource-explorer-2:us-east-1:123456789012:view/EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
  }
}
```
ビューの詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[Resource Explorer ビューについて](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/get-view.html)」を参照してください。

### `list-indexes`
<a name="resource-explorer-2_ListIndexes_cli_2_topic"></a>

次の例は、`list-indexes` を使用する方法を説明しています。

**AWS CLI**  
**Resource Explorer にインデックスがある AWS リージョンを一覧表示するには**  
次の `list-indexes` の例では、Resource Explorer にインデックスがあるすべてのリージョンのインデックスを一覧表示します。レスポンスは、各インデックスのタイプ、 AWS リージョン、および ARN を指定します。  

```
aws resource-explorer-2 list-indexes
```
出力:  

```
{
    "Indexes": [
        {
            "Arn": "arn:aws:resource-explorer-2:us-west-2:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111",
            "Region": "us-west-2",
            "Type": "AGGREGATOR"
        },
        {
            "Arn": "arn:aws:resource-explorer-2:us-east-1:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222",
            "Region": "us-east-1",
            "Type": "LOCAL"
        },
        {
            "Arn": "arn:aws:resource-explorer-2:us-east-2:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE33333",
            "Region": "us-east-2",
            "Type": "LOCAL"
        },
        {
            "Arn": "arn:aws:resource-explorer-2:us-west-1:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE44444",
            "Region": "us-west-1",
            "Type": "LOCAL"
        }
    ]
}
```
インデックスの詳細については、[「Resource Explorer ユーザーガイド」の「Resource Explorer が有効になっている AWS リージョン](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-service-check.html)の確認」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIndexes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/list-indexes.html)」を参照してください。

### `list-supported-resource-types`
<a name="resource-explorer-2_ListSupportedResourceTypes_cli_2_topic"></a>

次の例は、`list-supported-resource-types` を使用する方法を説明しています。

**AWS CLI**  
**Resource Explorer にインデックスがある AWS リージョンを一覧表示するには**  
次の `list-supported-resource-types` の例では、&AREXlong; で現在サポートされているすべてのリソースタイプを一覧表示します。レスポンスの例には、追加の呼び出しで取得できる出力が多いことを示す `NextToken` 値が含まれています。  

```
aws resource-explorer-2 list-supported-resource-types \
    --max-items 10
```
出力:  

```
{
    "ResourceTypes": [
        {
            "ResourceType": "cloudfront:cache-policy",
            "Service": "cloudfront"
        },
        {
            "ResourceType": "cloudfront:distribution",
            "Service": "cloudfront"
        },
        {
            "ResourceType": "cloudfront:function",
            "Service": "cloudfront"
        },
        {
            "ResourceType": "cloudfront:origin-access-identity",
            "Service": "cloudfront"
        },
        {
            "ResourceType": "cloudfront:origin-request-policy",
            "Service": "cloudfront"
        },
        {
            "ResourceType": "cloudfront:realtime-log-config",
            "Service": "cloudfront"
        },
        {
            "ResourceType": "cloudfront:response-headers-policy",
            "Service": "cloudfront"
        },
        {
            "ResourceType": "cloudwatch:alarm",
            "Service": "cloudwatch"
        },
        {
            "ResourceType": "cloudwatch:dashboard",
            "Service": "cloudwatch"
        },
        {
            "ResourceType": "cloudwatch:insight-rule",
            "Service": "cloudwatch"
        }
    ],
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0="
}
```
出力の次の部分を取得するには、オペレーションを再度呼び出し、前の呼び出しの `NextToken` レスポンス値を `--starting-token` の値として渡します。`NextToken` がレスポンスに存在しなくなるまで繰り返します。  

```
aws resource-explorer-2 list-supported-resource-types \
    --max-items 10  \
    --starting-token eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0=
```
出力:  

```
{
    "ResourceTypes": [
        {
            "ResourceType": "cloudwatch:metric-stream",
            "Service": "cloudwatch"
        },
        {
            "ResourceType": "dynamodb:table",
            "Service": "dynamodb"
        },
        {
            "ResourceType": "ec2:capacity-reservation",
            "Service": "ec2"
        },
        {
            "ResourceType": "ec2:capacity-reservation-fleet",
            "Service": "ec2"
        },
        {
            "ResourceType": "ec2:client-vpn-endpoint",
            "Service": "ec2"
        },
        {
            "ResourceType": "ec2:customer-gateway",
            "Service": "ec2"
        },
        {
            "ResourceType": "ec2:dedicated-host",
            "Service": "ec2"
        },
        {
            "ResourceType": "ec2:dhcp-options",
            "Service": "ec2"
        },
        {
            "ResourceType": "ec2:egress-only-internet-gateway",
            "Service": "ec2"
        },
        {
            "ResourceType": "ec2:elastic-gpu",
            "Service": "ec2"
        }
    ],
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyMH0="
}
```
インデックスの詳細については、[「Resource Explorer ユーザーガイド」の「Resource Explorer が有効になっている AWS リージョン](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-service-check.html)の確認」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSupportedResourceTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/list-supported-resource-types.html)」を参照してください。

### `list-tags-for-resource`
<a name="resource-explorer-2_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**Resource Explorer ビューまたはインデックスにアタッチされたタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された ARN で表示するためにアタッチされたタグキーと値のペアを一覧表示します。リソースを含む AWS リージョンから オペレーションを呼び出す必要があります。  

```
aws resource-explorer-2 list-tags-for-resource \
    --resource-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111
```
出力:  

```
{
    "Tags": {
        "application": "MainCorpApp",
        "department": "1234"
    }
}
```
ビューのタグ付けの詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[アクセス制御のビューのタグ付け](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-tag.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/list-tags-for-resource.html)」を参照してください。

### `list-views`
<a name="resource-explorer-2_ListViews_cli_2_topic"></a>

次の例は、`list-views` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョンで使用できる Resource Explorer ビューを一覧表示するには**  
次の `list-views` の例では、 オペレーションを呼び出すリージョンで使用可能なすべてのビューを一覧表示します。  

```
aws resource-explorer-2 list-views
```
出力:  

```
{
    "Views": [
        "arn:aws:resource-explorer-2:us-east-1:123456789012:view/EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111",
        "arn:aws:resource-explorer-2:us-east-1:123456789012:view/Default-All-Resources-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222",
        "arn:aws:resource-explorer-2:us-east-1:123456789012:view/Production-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE33333"
    ]
}
```
ビューの詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[Resource Explorer ビューについて](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListViews](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/list-views.html)」を参照してください。

### `search`
<a name="resource-explorer-2_Search_cli_2_topic"></a>

次のコード例は、`search` を使用する方法を示しています。

**AWS CLI**  
**例 1: デフォルトビューを使用して検索するには**  
次の `search` の例では、 サービスに関連付けられている、指定された 内のすべてのリソースを表示します。検索では、リージョンのデフォルトビューを使用します。レスポンスの例には、追加の呼び出しで取得できる出力が多いことを示す `NextToken` 値が含まれています。  

```
aws resource-explorer-2 search \
    --query-string "service:iam"
```
出力:  

```
{
    "Count": {
        "Complete": true,
        "TotalResources": 55
    },
    "NextToken": "AG9VOEF1KLEXAMPLEOhJHVwo5chEXAMPLER5XiEpNrgsEXAMPLE...b0CmOFOryHEXAMPLE",
    "Resources": [{
        "Arn": "arn:aws:iam::123456789012:policy/service-role/Some-Policy-For-A-Service-Role",
        "LastReportedAt": "2022-07-21T12:34:42Z",
        "OwningAccountId": "123456789012",
        "Properties": [],
        "Region": "global",
        "ResourceType": "iam:policy",
        "Service": "iam"
    }, {
        "Arn": "arn:aws:iam::123456789012:policy/service-role/Another-Policy-For-A-Service-Role",
        "LastReportedAt": "2022-07-21T12:34:42Z",
        "OwningAccountId": "123456789012",
        "Properties": [],
        "Region": "global",
        "ResourceType": "iam:policy",
        "Service": "iam"
    }, {
       ... TRUNCATED FOR BREVITY ...
    }],
    "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/my-default-view/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
}
```
**例 2: 指定されたビューを使用して検索するには**  
次の検索`search`例では、指定されたビューに表示される、指定された AWS リージョン内のすべてのリソース (「\$1」) を表示します。結果には、ビューにアタッチされたフィルターが原因で、Amazon EC2 に関連付けられたリソースのみが含まれます。  

```
aws resource-explorer-2 search \
    -- query-string "*" \
    -- view-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-EC2-view/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222
```
出力:  

```
HTTP/1.1 200 OK
Date: Tue, 01 Nov 2022 20:00:59 GMT
Content-Type: application/json
Content-Length: <PayloadSizeBytes>

    {
        "Count": {
            "Complete": true,
            "TotalResources": 67
        },
        "Resources": [{
            "Arn": "arn:aws:ec2:us-east-1:123456789012:network-acl/acl-1a2b3c4d",
            "LastReportedAt": "2022-07-21T18:52:02Z",
            "OwningAccountId": "123456789012",
            "Properties": [{
                "Data": [{
                    "Key": "Department",
                    "Value": "AppDevelopment"
                }, {
                    "Key": "Environment",
                    "Value": "Production"
                }],
                "LastReportedAt": "2021-11-15T14:48:29Z",
                "Name": "tags"
            }],
            "Region": "us-east-1",
            "ResourceType": "ec2:network-acl",
            "Service": "ec2"
        }, {
            "Arn": "arn:aws:ec2:us-east-1:123456789012:subnet/subnet-1a2b3c4d",
            "LastReportedAt": "2022-07-21T21:22:23Z",
            "OwningAccountId": "123456789012",
            "Properties": [{
                "Data": [{
                    "Key": "Department",
                    "Value": "AppDevelopment"
                }, {
                    "Key": "Environment",
                    "Value": "Production"
                }],
                "LastReportedAt": "2021-07-29T19:02:39Z",
                "Name": "tags"
            }],
            "Region": "us-east-1",
            "ResourceType": "ec2:subnet",
            "Service": "ec2"
        }, {
            "Arn": "arn:aws:ec2:us-east-1:123456789012:dhcp-options/dopt-1a2b3c4d",
            "LastReportedAt": "2022-07-21T06:08:53Z",
            "OwningAccountId": "123456789012",
            "Properties": [{
                "Data": [{
                    "Key": "Department",
                    "Value": "AppDevelopment"
                }, {
                    "Key": "Environment",
                    "Value": "Production"
                }],
                "LastReportedAt": "2021-11-15T15:11:05Z",
                "Name": "tags"
            }],
            "Region": "us-east-1",
            "ResourceType": "ec2:dhcpoptions",
            "Service": "ec2"
        }, {
            ... TRUNCATED FOR BREVITY ...
        }],
        "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-EC2-view/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222"
    }
```
詳細については、[AWS 「Resource Explorer ユーザーガイド」の「Resource Explorer を使用してリソースを検索する](https://docs.aws.amazon.com/resource-explorer/latest/userguide/using-search.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Search](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/search.html)」を参照してください。

### `tag-resource`
<a name="resource-explorer-2_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**Resource Explorer ビューにタグを付けるには**  
次の `tag-resource` の例では、指定された ARN を持つビューに、値「production」を持つタグキー「environment」を追加します。  

```
aws resource-explorer-2 tag-resource \
    --resource-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-View//EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111 \
    --tags environment=production
```
このコマンドでは何も出力されません。  
ビューのタグ付けの詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[アクセス制御のビューのタグ付け](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-tag.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="resource-explorer-2_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**Resource Explorer ビューからタグを削除するには**  
次の `untag-resource` の例では、指定された ARN からキー名「environment」を持つタグが削除されます。  

```
aws resource-explorer-2 untag-resource \
    --resource-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-View//EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111 \
    --tag-keys environment
```
このコマンドでは何も出力されません。  
ビューのタグ付けの詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[アクセス制御のビューのタグ付け](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-tag.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/untag-resource.html)」を参照してください。

### `update-index-type`
<a name="resource-explorer-2_UpdateIndexType_cli_2_topic"></a>

次のコード例は、`update-index-type` を使用する方法を示しています。

**AWS CLI**  
**Resource Explorer インデックスのタイプを変更するには**  
次の の`update-index-type`例では、指定されたインデックスを type から `local` type に変換`aggregator`して、アカウント内のすべての AWS リージョンでリソースを検索する機能を有効にします。更新するインデックスを含む AWS リージョンにリクエストを送信する必要があります。  

```
aws resource-explorer-2 update-index-type \
    --arn arn:aws:resource-explorer-2:us-east-1:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111 \
    --type aggregator \
    --region us-east-1
```
出力:  

```
{
    "Arn":"arn:aws:resource-explorer-2:us-east-1:123456789012:index/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111",
    "LastUpdatedAt":"2022-07-13T18:41:58.799Z",
    "State":"updating",
    "Type":"aggregator"
}
```
アグリゲータインデックスとローカルインデックスとの違いについては、「AWS Resource Explorer ユーザーガイド」の「[アグリゲータインデックスを作成してクロスリージョン検索をオンにする](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-aggregator-region.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIndexType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/update-index-type.html)」を参照してください。

### `update-view`
<a name="resource-explorer-2_UpdateView_cli_2_topic"></a>

次のコード例は、`update-view` を使用する方法を示しています。

**AWS CLI**  
**例 1: Resource Explorer ビューの IncludedProperties フィールドを更新するには**  
次の `update-view` の例では、オプションの ``tags`` に ``IncludedProperties`` を追加して、指定されたビューを更新します。このオペレーションを実行した後、このビューを使用する検索オペレーションには、結果に表示されるリソースにアタッチされたタグに関する情報が含まれます。  

```
aws resource-explorer-2 update-view \
    --included-properties Name=tags \
    --view-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222
```
出力:  

```
{
    "View": {
        "Filters": {
            "FilterString": ""
        },
        "IncludedProperties": [
            {
                "Name": "tags"
            }
        ],
        "LastUpdatedAt": "2022-07-19T17:41:21.710000+00:00",
        "Owner": "123456789012",
        "Scope": "arn:aws:iam::123456789012:root",
        "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-EC2-Only-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE11111"
    }
}
```
**例 2: ビューにアタッチされたフィルターを更新するには**  
次の `update-view` の例では、Amazon EC2 サービスに関連付けられているリソースタイプにのみ結果を制限するフィルターを使用するように、指定されたビューを更新します。  

```
aws resource-explorer-2 update-view \
    --filters FilterString="service:ec2" \
    --view-arn arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222
```
出力:  

```
{
    "View": {
    "Filters": {
        "FilterString": "service:ec2"
    },
    "IncludedProperties": [],
    "LastUpdatedAt": "2022-07-19T17:41:21.710000+00:00",
        "Owner": "123456789012",
        "Scope": "arn:aws:iam::123456789012:root",
        "ViewArn": "arn:aws:resource-explorer-2:us-east-1:123456789012:view/My-View/EXAMPLE8-90ab-cdef-fedc-EXAMPLE22222"
    }
}
```
ビューの詳細については、「*AWS Resource Explorer ユーザーガイド*」の「[Resource Explorer ビューについて](https://docs.aws.amazon.com/resource-explorer/latest/userguide/manage-views-about.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateView](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-explorer-2/update-view.html)」を参照してください。

# を使用した Resource Groups の例 AWS CLI
<a name="cli_2_resource-groups_code_examples"></a>

次のコード例は、Resource Groups AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-group`
<a name="resource-groups_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: タグベースのリソースグループを作成するには**  
次の `create-group` の例では、現在のリージョンに Amazon EC2 インスタンスのタグベースのリソースグループを作成します。これは、キー `Name` と値 `WebServers` でタグ付けされたリソースのクエリに基づいています。グループ名は `tbq-WebServer` です。クエリは、 コマンドに渡される別の JSON ファイルにあります。  

```
aws resource-groups create-group \
    --name tbq-WebServer \
    --resource-query file://query.json
```
`query.json` の内容:  

```
{
    "Type": "TAG_FILTERS_1_0",
    "Query": "{\"ResourceTypeFilters\":[\"AWS::EC2::Instance\"],\"TagFilters\":[{\"Key\":\"Name\", \"Values\":[\"WebServers\"]}]}"
}
```
出力:  

```
{
    "Group": {
        "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer",
        "Name": "tbq-WebServer"
    },
    "ResourceQuery": {
        "Type": "TAG_FILTERS_1_0",
        "Query": "{\"ResourceTypeFilters\":[\"AWS::EC2::Instance\"],\"TagFilters\":[{\"Key\":\"Name\", \"Values\":[\"WebServers\"]}]}"
    }
}
```
**例 2: CloudFormation スタックベースのリソースグループを作成するには**  
次の`create-group`例では、 という名前の AWS CloudFormation スタックベースのリソースグループを作成します`sampleCFNstackgroup`。クエリには、Resource Groups でサポートされている指定された CloudFormation スタック内のすべての AWS リソースが含まれます。  

```
aws resource-groups create-group \
    --name cbq-CFNstackgroup \
    --resource-query file://query.json
```
`query.json` の内容:  

```
{
    "Type": "CLOUDFORMATION_STACK_1_0",
    "Query": "{\"ResourceTypeFilters\":[\"AWS::AllSupported\"],\"StackIdentifier\":\"arn:aws:cloudformation:us-west-2:123456789012:stack/MyCFNStack/1415z9z0-z39z-11z8-97z5-500z212zz6fz\"}"
}
```
出力:  

```
{
    "Group": {
        "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/cbq-CFNstackgroup",
        "Name": "cbq-CFNstackgroup"
    },
    "ResourceQuery": {
        "Type": "CLOUDFORMATION_STACK_1_0",
        "Query": "{\"ResourceTypeFilters\":[\"AWS::AllSupported\"],\"StackIdentifier\":\"arn:aws:cloudformation:us-east-2:123456789012:stack/MyCFNStack/1415z9z0-z39z-11z8-97z5-500z212zz6fz\"}"}'
    }
}
```
詳細については、「*AWS Resource Groups ユーザーガイド*」の「[グループの作成](https://docs.aws.amazon.com/ARG/latest/userguide/gettingstarted-query.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/create-group.html)」を参照してください。

### `delete-group`
<a name="resource-groups_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**リソースグループの説明を更新するには**  
次の `delete-group` の例では、指定されたリソースグループを更新します。  

```
aws resource-groups delete-group \
    --group-name tbq-WebServer
```
出力:  

```
{
    "Group": {
        "GroupArn": "arn:aws:resource-groups:us-west-2:1234567890:group/tbq-WebServer",
        "Name": "tbq-WebServer"
    }
}
```
詳細については、「*AWS Resource Groups ユーザーガイド*」の「[グループの削除](https://docs.aws.amazon.com/ARG/latest/userguide/deleting-resource-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/delete-group.html)」を参照してください。

### `get-group-query`
<a name="resource-groups_GetGroupQuery_cli_2_topic"></a>

次のコード例は、`get-group-query` を使用する方法を示しています。

**AWS CLI**  
**リソースグループにアタッチされたクエリを取得するには**  
次の `get-group-query` の例では、指定されたリソースグループにアタッチされたクエリを表示します。  

```
aws resource-groups get-group-query \
    --group-name tbq-WebServer
```
出力:  

```
{
    "GroupQuery": {
        "GroupName": "tbq-WebServer",
        "ResourceQuery": {
            "Type": "TAG_FILTERS_1_0",
            "Query": "{\"ResourceTypeFilters\":[\"AWS::EC2::Instance\"],\"TagFilters\":[{\"Key\":\"Name\", \"Values\":[\"WebServers\"]}]}"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroupQuery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/get-group-query.html)」を参照してください。

### `get-group`
<a name="resource-groups_GetGroup_cli_2_topic"></a>

次のコード例は、`get-group` を使用する方法を示しています。

**AWS CLI**  
**リソースグループに関する情報を取得するには**  
次の `get-group` の例では、指定したリソースグループに関する詳細を表示します。クエリをグループにアタッチするには、`get-group-query` を使用します。  

```
aws resource-groups get-group \
    --group-name tbq-WebServer
```
出力:  

```
{
    "Group": {
        "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer",
        "Name": "tbq-WebServer",
        "Description": "A tag-based query resource group of WebServers."
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/get-group.html)」を参照してください。

### `get-tags`
<a name="resource-groups_GetTags_cli_2_topic"></a>

次のコード例は、`get-tags` を使用する方法を示しています。

**AWS CLI**  
**リソースグループにアタッチされたタグを取得するには**  
次の `get-tags` の例では、指定されたリソースグループ (メンバーではなくグループ自体) にアタッチされたタグキーと値のペアを表示します。  

```
aws resource-groups get-tags \
    --arn arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer
```
出力:  

```
{
    "Arn": "arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer",
    "Tags": {
        "QueryType": "tags",
        "QueryResources": "ec2-instances"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/get-tags.html)」を参照してください。

### `list-group-resources`
<a name="resource-groups_ListGroupResources_cli_2_topic"></a>

次のコード例は、`list-group-resources` を使用する方法を示しています。

**AWS CLI**  
**リソースグループ内のすべてのリソースを一覧表示するには**  
例 1: 次の `list-resource-groups` の例では、指定されたリソースグループの一部であるすべてのリソースを一覧表示します。  

```
aws resource-groups list-group-resources \
    --group-name tbq-WebServer
```
出力:  

```
{
    "ResourceIdentifiers": [
        {
            "ResourceArn": "arn:aws:ec2:us-west-2:123456789012:instance/i-09f77fa38c12345ab",
            "ResourceType": "AWS::EC2::Instance"
        }
    ]
}
```
例 2: 次の例では、'AWS::EC2::Instance' の 'resource-type' も持つグループ内のすべてのリソースを一覧表示します。  
aws resource-groups list-group-resources --group-name tbq-WebServer --filters Name=resource-type,Values=AWS::EC2::Instance  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/list-group-resources.html)」を参照してください。

### `list-groups`
<a name="resource-groups_ListGroups_cli_2_topic"></a>

次のコード例は、`list-groups` を使用する方法を示しています。

**AWS CLI**  
**使用可能なリソースグループを一覧表示するには**  
次の `list-groups` の例では、すべてのリソースグループのリストを表示します。  

```
aws resource-groups list-groups
```
出力:  

```
{
    "GroupIdentifiers": [
        {
            "GroupName": "tbq-WebServer",
            "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer3"
        },
        {
            "GroupName": "cbq-CFNStackQuery",
            "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/cbq-CFNStackQuery"
        }
    ],
    "Groups": [
        {
            "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer",
            "Name": "tbq-WebServer"
        },
        {
            "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/cbq-CFNStackQuery",
            "Name": "cbq-CFNStackQuery"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/list-groups.html)」を参照してください。

### `list-resource-groups`
<a name="resource-groups_ListResourceGroups_cli_2_topic"></a>

次のコード例は、`list-resource-groups` を使用する方法を示しています。

**AWS CLI**  
**リソースグループ内のすべてのリソースを一覧表示するには**  
次の `list-resource-groups` の例では、指定されたリソースグループの一部であるすべてのリソースを一覧表示します。  

```
aws resource-groups list-group-resources \
    --group-name tbq-WebServer
```
出力:  

```
{
    "ResourceIdentifiers": [
        {
            "ResourceArn": "arn:aws:ec2:us-west-2:123456789012:instance/i-09f77fa38c12345ab",
            "ResourceType": "AWS::EC2::Instance"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/list-resource-groups.html)」を参照してください。

### `put-group-configuration`
<a name="resource-groups_PutGroupConfiguration_cli_2_topic"></a>

次のコード例は、`put-group-configuration` を使用する方法を示しています。

**AWS CLI**  
**リソースグループにサービス設定をアタッチするには**  
例 1: 次の `put-group-configuration` の例では、リソースグループに `C5` または `M5` ファミリーのインスタンスの Amazon EC2 キャパシティ予約のみを含めるように指定しています。  

```
aws resource-groups put-group-configuration \
    --group MyTestGroup \
    --configuration file://config.json
```
`config.json` の内容:  

```
[
    {
        "Type": "AWS::EC2::HostManagement",
        "Parameters": [
            {
                "Name": "allowed-host-families",
                "Values": [ "c5", "m5" ]
            },
                {
                    "Name": "any-host-based-license-configuration",
                    "Values": [ "true" ]
                }
        ]
    },
    {
        "Type": "AWS::ResourceGroups::Generic",
        "Parameters": [
            {
                "Name": "allowed-resource-types",
                "Values": [ "AWS::EC2::Host" ]
            },
            {
                "Name": "deletion-protection",
                "Values": [ "UNLESS_EMPTY" ]
            }
        ]
    }
]
```
このコマンドが成功した場合、出力は生成されません。  
詳細については、「*リソースグループ API リファレンスガイド*」の「[リソースグループのサービス設定](https://docs.aws.amazon.com/ARG/latest/APIReference/about-slg.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutGroupConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/put-group-configuration.html)」を参照してください。

### `search-resources`
<a name="resource-groups_SearchResources_cli_2_topic"></a>

次のコード例は、`search-resources` を使用する方法を示しています。

**AWS CLI**  
**クエリに一致するリソースを検索するには**  
次の の`search-resources`例では、指定されたクエリに一致するすべての AWS リソースのリストを取得します。  

```
aws resource-groups search-resources \
    --resource-query file://query.json
```
`query.json` の内容:  

```
{
    "Type": "TAG_FILTERS_1_0",
    "Query": "{\"ResourceTypeFilters\":[\"AWS::EC2::Instance\"],\"TagFilters\":[{\"Key\":\"Patch Group\", \"Values\":[\"Dev\"]}]}"
}
```
出力:  

```
{
    "ResourceIdentifiers": [
        {
            "ResourceArn": "arn:aws:ec2:us-west-2:123456789012:instance/i-01a23bc45d67890ef",
            "ResourceType": "AWS::EC2::Instance"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/search-resources.html)」を参照してください。

### `tag`
<a name="resource-groups_Tag_cli_2_topic"></a>

次のコード例は、`tag` を使用する方法を示しています。

**AWS CLI**  
**リソースグループにタグをアタッチするには**  
次の `tag` の例では、指定されたタグキーと値のペアを、指定されたリソースグループ (メンバーではなくグループ自体) にアタッチします。  

```
aws resource-groups tag \
    --tags QueryType=tags,QueryResources=ec2-instances \
    --arn arn:aws:resource-groups:us-west-2:128716708097:group/tbq-WebServer
```
出力:  

```
{
    "Arn": "arn:aws:resource-groups:us-west-2:128716708097:group/tbq-WebServer",
    "Tags": {
        "QueryType": "tags",
        "QueryResources": "ec2-instances"
    }
}
```
詳細については、「*AWS Resource Groups ユーザーガイド*」の「[タグの管理](https://docs.aws.amazon.com/ARG/latest/userguide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Tag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/tag.html)」を参照してください。

### `untag`
<a name="resource-groups_Untag_cli_2_topic"></a>

次のコード例は、`untag` を使用する方法を示しています。

**AWS CLI**  
**リソースグループからタグを削除するには**  
次の `untags` の例では、メンバーではなくリソースグループ自体から指定したキーを持つタグを削除します。  

```
aws resource-groups untag \
    --arn arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer \
    --keys QueryType
```
出力:  

```
{
    "Arn": "arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer",
    "Keys": [
        "QueryType"
    ]
}
```
詳細については、「*AWS Resource Groups ユーザーガイド*」の「[タグの管理](https://docs.aws.amazon.com/ARG/latest/userguide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Untag](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/untag.html)」を参照してください。

### `update-group-query`
<a name="resource-groups_UpdateGroupQuery_cli_2_topic"></a>

次のコード例は、`update-group-query` を使用する方法を示しています。

**AWS CLI**  
**例 1: タグベースのリソースグループのクエリを更新するには**  
次の `update-group-query` の例では、指定されたタグベースのリソースグループにアタッチされたクエリを更新します。  

```
aws resource-groups update-group-query \
    --group-name tbq-WebServer \
    --resource-query '{"Type":"TAG_FILTERS_1_0", "Query":"{\"ResourceTypeFilters\":[\"AWS::EC2::Instance\"],\"TagFilters\":[{\"Key\":\"Name\", \"Values\":[\"WebServers\"]}]}"}'
```
出力:  

```
{
    "Group": {
        "GroupArn": "arn:aws:resource-groups:us-east-2:123456789012:group/tbq-WebServer",
        "Name": "tbq-WebServer"
    },
    "ResourceQuery": {
        "Type": "TAG_FILTERS_1_0",
        "Query": "{\"ResourceTypeFilters\":[\"AWS::EC2::Instance\"],\"TagFilters\":[{\"Key\":\"Name\", \"Values\":[\"WebServers\"]}]}"
    }
}
```
詳細については、「*AWS Resource Groups ユーザーガイド*」の「[グループの更新](https://docs.aws.amazon.com/ARG/latest/userguide/updating-resource-groups.html)」を参照してください。  
**例 2: CloudFormation スタックベースのリソースグループのクエリを更新するには**  
次の の`update-group-query`例では、指定された AWS CloudFormation スタックベースのリソースグループにアタッチされたクエリを更新します。  

```
aws resource-groups update-group-query \
    --group-name cbq-CFNstackgroup \
    --resource-query '{"Type": "CLOUDFORMATION_STACK_1_0", "Query": "{\"ResourceTypeFilters\":[\"AWS::AllSupported\"],\"StackIdentifier\":\"arn:aws:cloudformation:us-west-2:123456789012:stack/MyCFNStack/1415z9z0-z39z-11z8-97z5-500z212zz6fz\"}"}'
```
出力:  

```
{
    "Group": {
        "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/cbq-CFNstackgroup",
        "Name": "cbq-CFNstackgroup"
    },
    "ResourceQuery": {
        "Type": "CLOUDFORMATION_STACK_1_0",
        "Query": "{\"ResourceTypeFilters\":[\"AWS::AllSupported\"],\"StackIdentifier\":\"arn:aws:cloudformation:us-west-2:123456789012:stack/MyCFNStack/1415z9z0-z39z-11z8-97z5-500z212zz6fz\"}"
    }
}
```
詳細については、「*AWS Resource Groups ユーザーガイド*」の「[グループの更新](https://docs.aws.amazon.com/ARG/latest/userguide/updating-resource-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroupQuery](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/update-group-query.html)」を参照してください。

### `update-group`
<a name="resource-groups_UpdateGroup_cli_2_topic"></a>

次のコード例は、`update-group` を使用する方法を示しています。

**AWS CLI**  
**リソースグループの説明を更新するには**  
次の `update-group` 例では、指定されたリソースグループの説明を更新します。  

```
aws resource-groups update-group \
    --group-name tbq-WebServer \
    --description "Resource group for all web server resources."
```
出力:  

```
{
    "Group": {
        "GroupArn": "arn:aws:resource-groups:us-west-2:123456789012:group/tbq-WebServer",
        "Name": "tbq-WebServer"
        "Description": "Resource group for all web server resources."
    }
}
```
詳細については、「*AWS Resource Groups ユーザーガイド*」の「[グループの更新](https://docs.aws.amazon.com/ARG/latest/userguide/updating-resource-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resource-groups/update-group.html)」を参照してください。

# を使用した Resource Groups Tagging API の例 AWS CLI
<a name="cli_2_resource-groups-tagging-api_code_examples"></a>

次のコード例は、Resource Groups Tagging API AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-resources`
<a name="resource-groups-tagging-api_GetResources_cli_2_topic"></a>

次のコード例は、`get-resources` を使用する方法を示しています。

**AWS CLI**  
**タグ付きリソースのリストを取得するには**  
次の `get-resources` の例では、指定されたキー名と値でタグ付けされたアカウント内のリソースのリストを表示します。  

```
aws resourcegroupstaggingapi get-resources \
    --tag-filters Key=Environment,Values=Production \
    --tags-per-page 100
```
出力:  

```
{
    "ResourceTagMappingList": [
        {
            "ResourceARN": " arn:aws:inspector:us-west-2:123456789012:target/0-nvgVhaxX/template/0-7sbz2Kz0",
            "Tags": [
                {
                    "Key": "Environment",
                    "Value": "Production"
                }
            ]
        }
    ]
}
```
詳細については、「*Resource Groups Tagging API リファレンス*」の「[GetResources](https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetResources.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resourcegroupstaggingapi/get-resources.html)」を参照してください。**

### `get-tag-keys`
<a name="resource-groups-tagging-api_GetTagKeys_cli_2_topic"></a>

次のコード例は、`get-tag-keys` を使用する方法を示しています。

**AWS CLI**  
**すべてのタグキーのリストを取得するには**  
次の `get-tag-keys` の例では、 アカウントのリソースで使用されるすべてのタグキー名のリストを取得します。  

```
aws resourcegroupstaggingapi get-tag-keys
```
出力:  

```
{
    "TagKeys": [
        "Environment",
        "CostCenter",
        "Department"
    ]
}
```
詳細については、「*Resource Groups Tagging API リファレンス*」の「[GetTagKeys](https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetTagKeys.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTagKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resourcegroupstaggingapi/get-tag-keys.html)」を参照してください。

### `get-tag-values`
<a name="resource-groups-tagging-api_GetTagValues_cli_2_topic"></a>

次のコード例は、`get-tag-values` を使用する方法を示しています。

**AWS CLI**  
**すべてのタグ値のリストを取得するには**  
次の `get-tag-values` の例では、 内のすべてのリソースの指定されたキーに使用されるすべての値を表示します。  

```
aws resourcegroupstaggingapi get-tag-values \
    --key=Environment
```
出力:  

```
{
    "TagValues": [
        "Alpha",
        "Gamma",
        "Production"
    ]
}
```
詳細については、「*Resource Groups Tagging API リファレンス*」の「[GetTagValues](https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_GetTagValues.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTagValues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resourcegroupstaggingapi/get-tag-values.html)」を参照してください。

### `tag-resources`
<a name="resource-groups-tagging-api_TagResources_cli_2_topic"></a>

次のコード例は、`tag-resources` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグをアタッチするには**  
次の `tag-resources` の例では、キー名と値付きの指定したリソースにタグを付けます。  

```
aws resourcegroupstaggingapi tag-resources \
    --resource-arn-list arn:aws:s3:::MyProductionBucket \
    --tags Environment=Production,CostCenter=1234
```
出力:  

```
{
    "FailedResourcesMap": {}
}
```
詳細については、「*Resource Groups Tagging API リファレンス*」の「[TagResources](https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_TagResources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resourcegroupstaggingapi/tag-resources.html)」を参照してください。

### `untag-resources`
<a name="resource-groups-tagging-api_UntagResources_cli_2_topic"></a>

次のコード例は、`untag-resources` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `untag-resources` の例では、指定されたリソースから指定されたタグキーと関連付けられた値を削除します。  

```
aws resourcegroupstaggingapi untag-resources \
    --resource-arn-list arn:aws:s3:::amzn-s3-demo-bucket \
    --tag-keys Environment CostCenter
```
出力:  

```
{
    "FailedResourcesMap": {}
}
```
詳細については、「*Resource Groups Tagging API リファレンス*」の「[UntagResources](https://docs.aws.amazon.com/resourcegroupstagging/latest/APIReference/API_UntagResources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UntagResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/resourcegroupstaggingapi/untag-resources.html)」を参照してください。

# を使用した Route 53 の例 AWS CLI
<a name="cli_2_route-53_code_examples"></a>

次のコード例は、Route 53 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `change-resource-record-sets`
<a name="route-53_ChangeResourceRecordSets_cli_2_topic"></a>

次のコード例は、`change-resource-record-sets` を使用する方法を示しています。

**AWS CLI**  
**リソースレコードセットを作成、更新、または削除するには**  
次の `change-resource-record-sets` コマンドは、ファイル `C:\awscli\route53\change-resource-record-sets.json` の `hosted-zone-id` `Z1R8UBAEXAMPLE` と JSON 形式の設定を使用してリソースレコードセットを作成します。  

```
aws route53 change-resource-record-sets --hosted-zone-id Z1R8UBAEXAMPLE --change-batch file://C:\awscli\route53\change-resource-record-sets.json
```
詳細については、*Amazon Route 53 API リファレンス*の「POST ChangeResourceRecordSets」を参照してください。  
JSON ファイルの設定は、作成するリソースレコードセットの種類によって異なります。  
BasicWeightedAliasWeighted AliasLatencyLatency AliasFailoverFailover Alias  
**基本構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "TTL": time to live in seconds,
        "ResourceRecords": [
          {
            "Value": "applicable value for the record type"
          },
          {...}
        ]
      }
    },
    {...}
  ]
}
```
**加重構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "SetIdentifier": "unique description for this resource record set",
        "Weight": value between 0 and 255,
        "TTL": time to live in seconds,
        "ResourceRecords": [
          {
            "Value": "applicable value for the record type"
          },
          {...}
        ],
        "HealthCheckId": "optional ID of an Amazon Route 53 health check"
      }
    },
    {...}
  ]
}
```
**エイリアス構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "AliasTarget": {
          "HostedZoneId": "hosted zone ID for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or Amazon Route 53 hosted zone",
          "DNSName": "DNS domain name for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or another resource record set in this hosted zone",
          "EvaluateTargetHealth": true|false
        },
        "HealthCheckId": "optional ID of an Amazon Route 53 health check"
      }
    },
    {...}
  ]
}
```
**加重エイリアス構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "SetIdentifier": "unique description for this resource record set",
        "Weight": value between 0 and 255,
        "AliasTarget": {
          "HostedZoneId": "hosted zone ID for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or Amazon Route 53 hosted zone",
          "DNSName": "DNS domain name for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or another resource record set in this hosted zone",
          "EvaluateTargetHealth": true|false
        },
        "HealthCheckId": "optional ID of an Amazon Route 53 health check"
      }
    },
    {...}
  ]
}
```
**レイテンシー構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "SetIdentifier": "unique description for this resource record set",
        "Region": "Amazon EC2 region name",
        "TTL": time to live in seconds,
        "ResourceRecords": [
          {
            "Value": "applicable value for the record type"
          },
          {...}
        ],
        "HealthCheckId": "optional ID of an Amazon Route 53 health check"
      }
    },
    {...}
  ]
}
```
**レイテンシーエイリアス構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "SetIdentifier": "unique description for this resource record set",
        "Region": "Amazon EC2 region name",
        "AliasTarget": {
          "HostedZoneId": "hosted zone ID for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or Amazon Route 53 hosted zone",
          "DNSName": "DNS domain name for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or another resource record set in this hosted zone",
          "EvaluateTargetHealth": true|false
        },
        "HealthCheckId": "optional ID of an Amazon Route 53 health check"
      }
    },
    {...}
  ]
}
```
**フェイルオーバー構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "SetIdentifier": "unique description for this resource record set",
        "Failover": "PRIMARY" | "SECONDARY",
        "TTL": time to live in seconds,
        "ResourceRecords": [
          {
            "Value": "applicable value for the record type"
          },
          {...}
        ],
        "HealthCheckId": "ID of an Amazon Route 53 health check"
      }
    },
    {...}
  ]
}
```
**フェイルオーバーエイリアス構文**:  

```
{
  "Comment": "optional comment about the changes in this change batch request",
  "Changes": [
    {
      "Action": "CREATE"|"DELETE"|"UPSERT",
      "ResourceRecordSet": {
        "Name": "DNS domain name",
        "Type": "SOA"|"A"|"TXT"|"NS"|"CNAME"|"MX"|"PTR"|"SRV"|"SPF"|"AAAA",
        "SetIdentifier": "unique description for this resource record set",
        "Failover": "PRIMARY" | "SECONDARY",
        "AliasTarget": {
          "HostedZoneId": "hosted zone ID for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or Amazon Route 53 hosted zone",
          "DNSName": "DNS domain name for your CloudFront distribution, Amazon S3 bucket, Elastic Load Balancing load balancer, or another resource record set in this hosted zone",
          "EvaluateTargetHealth": true|false
        },
        "HealthCheckId": "optional ID of an Amazon Route 53 health check"
      }
    },
    {...}
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ChangeResourceRecordSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/change-resource-record-sets.html)」を参照してください。

### `change-tags-for-resource`
<a name="route-53_ChangeTagsForResource_cli_2_topic"></a>

次のコード例は、`change-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、ID で指定されたヘルスチェックリソースに `owner` というタグを追加します。  

```
aws route53 change-tags-for-resource --resource-type healthcheck --resource-id 6233434j-18c1-34433-ba8e-3443434 --add-tags Key=owner,Value=myboss
```
次のコマンドは、ID で指定されたホストゾーンリソースから `owner` というタグを削除します。  

```
aws route53 change-tags-for-resource --resource-type hostedzone --resource-id Z1523434445 --remove-tag-keys owner
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ChangeTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/change-tags-for-resource.html)」を参照してください。

### `create-health-check`
<a name="route-53_CreateHealthCheck_cli_2_topic"></a>

次のコード例は、`create-health-check` を使用する方法を示しています。

**AWS CLI**  
**ヘルスチェックを作成するには**  
次の `create-health-check` コマンドは、`C:\awscli\route53\create-health-check.json` ファイルで発信者リファレンス `2014-04-01-18:47` と JSON 形式の設定を使用してヘルスチェックを作成します。  

```
aws route53 create-health-check --caller-reference 2014-04-01-18:47 --health-check-config file://C:\awscli\route53\create-health-check.json
```
JSON 構文:  

```
{
  "IPAddress": "IP address of the endpoint to check",
  "Port": port on the endpoint to check--required when Type is "TCP",
  "Type": "HTTP"|"HTTPS"|"HTTP_STR_MATCH"|"HTTPS_STR_MATCH"|"TCP",
  "ResourcePath": "path of the file that you want Amazon Route 53 to request--all Types except TCP",
  "FullyQualifiedDomainName": "domain name of the endpoint to check--all Types except TCP",
  "SearchString": "if Type is HTTP_STR_MATCH or HTTPS_STR_MATCH, the string to search for in the response body from the specified resource",
  "RequestInterval": 10 | 30,
  "FailureThreshold": integer between 1 and 10
}
```
Route 53 リソースレコードセットにヘルスチェックを追加するには、`change-resource-record-sets` コマンドを使用します。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「Amazon Route 53 ヘルスチェックと DNS フェイルオーバー」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateHealthCheck](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/create-health-check.html)」を参照してください。

### `create-hosted-zone`
<a name="route-53_CreateHostedZone_cli_2_topic"></a>

次のコード例は、`create-hosted-zone` を使用する方法を示しています。

**AWS CLI**  
**ホストゾーンを作成するには**  
次の `create-hosted-zone` コマンドは、発信者リファレンス `2014-04-01-18:47` を使用して `example.com` という名前のホストゾーンを追加します。オプションのコメントは、スペースを含むため、引用符で囲む必要があります。  

```
aws route53 create-hosted-zone --name example.com --caller-reference 2014-04-01-18:47 --hosted-zone-config Comment="command-line version"
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「ホストゾーンの使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドレットリファレンス*」の「[CreateHostedZone](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/create-hosted-zone.html)」を参照してください。

### `delete-health-check`
<a name="route-53_DeleteHealthCheck_cli_2_topic"></a>

次のコード例は、`delete-health-check` を使用する方法を示しています。

**AWS CLI**  
**ヘルスチェックを削除するには**  
次の `delete-health-check` コマンドは、`e75b48d9-547a-4c3d-88a5-ae4002397608` の `health-check-id` を使用してヘルスチェックを削除します。  

```
aws route53 delete-health-check --health-check-id e75b48d9-547a-4c3d-88a5-ae4002397608
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteHealthCheck](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/delete-health-check.html)」を参照してください。

### `delete-hosted-zone`
<a name="route-53_DeleteHostedZone_cli_2_topic"></a>

次のコード例は、`delete-hosted-zone` を使用する方法を示しています。

**AWS CLI**  
**ホストゾーンを削除するには**  
次の `delete-hosted-zone` コマンドは、`Z36KTIQEXAMPLE` の `id` を使用してホストゾーンを削除します。  

```
aws route53 delete-hosted-zone --id Z36KTIQEXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteHostedZone](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/delete-hosted-zone.html)」を参照してください。

### `get-change`
<a name="route-53_GetChange_cli_2_topic"></a>

次のコード例は、`get-change` を使用する方法を示しています。

**AWS CLI**  
**リソースレコードセットの変更のステータスを取得するには**  
次の `get-change` コマンドは、`/change/CWPIK4URU2I5S` の `Id` を持つ `change-resource-record-sets` リクエストのステータスとその他の情報を取得します。  

```
aws route53 get-change --id /change/CWPIK4URU2I5S
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetChange](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/get-change.html)」を参照してください。

### `get-health-check`
<a name="route-53_GetHealthCheck_cli_2_topic"></a>

次のコード例は、`get-health-check` を使用する方法を示しています。

**AWS CLI**  
**ヘルスチェックに関する情報を取得するには**  
次の `get-health-check` コマンドは、`02ec8401-9879-4259-91fa-04e66d094674` の `health-check-id` を持つヘルスチェックに関する情報を取得します。  

```
aws route53 get-health-check --health-check-id 02ec8401-9879-4259-91fa-04e66d094674
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetHealthCheck](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/get-health-check.html)」を参照してください。

### `get-hosted-zone`
<a name="route-53_GetHostedZone_cli_2_topic"></a>

次のコード例は、`get-hosted-zone` を使用する方法を示しています。

**AWS CLI**  
**ホストゾーンに関する情報を取得するには**  
次の `get-hosted-zone` コマンドは、`Z1R8UBAEXAMPLE` の `id` を使用してホストゾーンに関する情報を取得します。  

```
aws route53 get-hosted-zone --id Z1R8UBAEXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetHostedZone](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/get-hosted-zone.html)」を参照してください。

### `list-health-checks`
<a name="route-53_ListHealthChecks_cli_2_topic"></a>

次の例は、`list-health-checks` を使用する方法を説明しています。

**AWS CLI**  
**現在の AWS アカウントに関連付けられているヘルスチェックを一覧表示するには**  
次の`list-health-checks`コマンドは、現在の AWS アカウントに関連付けられている最初の 100 件のヘルスチェックに関する詳細情報を一覧表示します。  

```
aws route53 list-health-checks
```
ヘルスチェックが 100 個を超える場合や、100 個未満のグループでヘルスチェックを一覧表示する場合は、`--maxitems` パラメータを含めます。例えば、ヘルスチェックを一度に一覧表示するには、次のコマンドを使用します。  

```
aws route53 list-health-checks --max-items 1
```
次のヘルスチェックに関する情報を表示するには、前のコマンドに対する応答から `NextToken` の値を取得し、その値を `--starting-token` パラメーターに含めます。次に例を示します。  

```
aws route53 list-health-checks --max-items 1 --starting-token Z3M3LMPEXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHealthChecks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/list-health-checks.html)」を参照してください。

### `list-hosted-zones-by-name`
<a name="route-53_ListHostedZonesByName_cli_2_topic"></a>

次のコード例は、`list-hosted-zones-by-name` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、最大 100 個のホストゾーンをドメイン名順に一覧表示します。  

```
aws route53 list-hosted-zones-by-name
```
出力:  

```
{
  "HostedZones": [
      {
          "ResourceRecordSetCount": 2,
          "CallerReference": "test20150527-2",
          "Config": {
              "Comment": "test2",
              "PrivateZone": false
          },
          "Id": "/hostedzone/Z119WBBTVP5WFX",
          "Name": "2.example.com."
      },
      {
          "ResourceRecordSetCount": 2,
          "CallerReference": "test20150527-1",
          "Config": {
              "Comment": "test",
              "PrivateZone": false
          },
          "Id": "/hostedzone/Z3P5QSUBK4POTI",
          "Name": "www.example.com."
      }
  ],
  "IsTruncated": false,
  "MaxItems": "100"
}
```
次のコマンドは、`www.example.com` で始まる名前順にホストゾーンを一覧表示します。  

```
aws route53 list-hosted-zones-by-name --dns-name www.example.com
```
出力:  

```
{
  "HostedZones": [
      {
          "ResourceRecordSetCount": 2,
          "CallerReference": "mwunderl20150527-1",
          "Config": {
              "Comment": "test",
              "PrivateZone": false
          },
          "Id": "/hostedzone/Z3P5QSUBK4POTI",
          "Name": "www.example.com."
      }
  ],
  "DNSName": "www.example.com",
  "IsTruncated": false,
  "MaxItems": "100"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHostedZonesByName](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/list-hosted-zones-by-name.html)」を参照してください。

### `list-hosted-zones`
<a name="route-53_ListHostedZones_cli_2_topic"></a>

次の例は、`list-hosted-zones` を使用する方法を説明しています。

**AWS CLI**  
**現在の AWS アカウントに関連付けられているホストゾーンを一覧表示するには**  
次の`list-hosted-zones`コマンドは、現在の AWS アカウントに関連付けられている最初の 100 個のホストゾーンに関する概要情報を一覧表示します。  

```
aws route53 list-hosted-zones
```
ホストゾーンが 100 個を超える場合や、100 個未満のグループにホストゾーンを一覧表示する場合は、`--max-items` パラメータを含めてください。例えば、ホストゾーンを一度に一覧表示するには、次のコマンドを使用します。  

```
aws route53 list-hosted-zones --max-items 1
```
次のホストゾーンに関する情報を表示するには、前のコマンドに対する応答から `NextToken` の値を取得し、その値を `--starting-token` パラメーターに含めます。次に例を示します。  

```
aws route53 list-hosted-zones --max-items 1 --starting-token Z3M3LMPEXAMPLE
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListHostedZones](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/list-hosted-zones.html)」を参照してください。

### `list-query-logging-configs`
<a name="route-53_ListQueryLoggingConfigs_cli_2_topic"></a>

次のコード例は、`list-query-logging-configs` を使用する方法を示しています。

**AWS CLI**  
**クエリログ記録の設定を一覧表示するには**  
次の の`list-query-logging-configs`例では AWS 、ホストゾーン の最初の 100 個のクエリログ記録設定に関する情報を一覧表示します`Z1OX3WQEXAMPLE`。  

```
aws route53 list-query-logging-configs \
    --hosted-zone-id Z1OX3WQEXAMPLE
```
出力:  

```
{
    "QueryLoggingConfigs": [
        {
            "Id": "964ff34e-ae03-4f06-80a2-9683cexample",
            "HostedZoneId": "Z1OX3WQEXAMPLE",
            "CloudWatchLogsLogGroupArn": "arn:aws:logs:us-east-1:111122223333:log-group:/aws/route53/example.com:*"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[DNS クエリのログ](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListQueryLoggingConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/list-query-logging-configs.html)」を参照してください。

### `list-resource-record-sets`
<a name="route-53_ListResourceRecordSets_cli_2_topic"></a>

次のコード例は、`list-resource-record-sets` を使用する方法を示しています。

**AWS CLI**  
**ホストゾーンのリソースレコードセットを一覧表示するには**  
次の `list-resource-record-sets` コマンドは、指定されたホストゾーンの最初の 100 個のリソースレコードセットに関する概要情報を一覧表示します。  

```
aws route53 list-resource-record-sets --hosted-zone-id Z2LD58HEXAMPLE
```
ホストゾーンが 100 個を超えるリソースレコードセットを含む場合や、100 個未満のグループでリソースレコードセットを一覧表示する場合は、`--maxitems` パラメータを含めてください。例えば、リソースレコードセットを一度に一覧表示するには、次のコマンドを使用します。  

```
aws route53 list-resource-record-sets --hosted-zone-id Z2LD58HEXAMPLE --max-items 1
```
ホストゾーンの次のリソースレコードセットに関する情報を表示するには、前のコマンドに対する応答から `NextToken` の値を取得し、その値を `--starting-token` パラメーターに含めます。次に例を示します。  

```
aws route53 list-resource-record-sets --hosted-zone-id Z2LD58HEXAMPLE --max-items 1 --starting-token Z3M3LMPEXAMPLE
```
特定の名前のすべてのリソースレコードセットを表示するには、`--query` パラメータを使用してフィルタリングします。例えば、次のようになります。  

```
aws route53 list-resource-record-sets --hosted-zone-id Z2LD58HEXAMPLE --query "ResourceRecordSets[?Name == 'example.domain.']"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceRecordSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53/list-resource-record-sets.html)」を参照してください。

# を使用した Route 53 ドメイン登録の例 AWS CLI
<a name="cli_2_route-53-domains_code_examples"></a>

次のコード例は、Route 53 ドメイン登録 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `check-domain-availability`
<a name="route-53-domains_CheckDomainAvailability_cli_2_topic"></a>

次のコード例は、`check-domain-availability` を使用する方法を示しています。

**AWS CLI**  
**Route 53 を使用してドメイン名を登録できるかどうかを確認するには**  
次の `check-domain-availability` コマンドは、Route 53 を使用してドメイン名 `example.com` を登録できるかどうかに関する情報を返します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains check-domain-availability \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "Availability": "UNAVAILABLE"
}
```
Route 53 は、`.com` や `.jp` など、多数の最上位ドメイン (TLD) をサポートしていますが、利用可能なすべての TLD をサポートしているわけではありません。ドメインの可用性を確認し、Route 53 が TLD をサポートしていない場合、`check-domain-availability` は次のメッセージを返します。  

```
An error occurred (UnsupportedTLD) when calling the CheckDomainAvailability operation: <top-level domain> tld is not supported.
```
Route 53 を使用してドメインを登録する時に使用できる TLD の一覧については、「*Amazon Route 53 デベロッパーガイド*」の「[Amazon Route 53 に登録できるドメイン](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar-tld-list.html)」を参照してください。Amazon Route 53 を使用してドメインを登録する方法の詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[新しいドメインを登録する](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-register.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CheckDomainAvailability](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/check-domain-availability.html)」を参照してください。

### `check-domain-transferability`
<a name="route-53-domains_CheckDomainTransferability_cli_2_topic"></a>

次のコード例は、`check-domain-transferability` を使用する方法を示しています。

**AWS CLI**  
**Route 53 にドメインを転送できるかどうかを確認するには**  
次の `check-domain-transferability` コマンドは、ドメイン名 `example.com` を Route 53 に転送できるかどうかに関する情報を返します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains check-domain-transferability \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "Transferability": {
        "Transferable": "UNTRANSFERABLE"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[ドメイン登録の Amazon Route 53 への移管](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-to-route-53.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CheckDomainTransferability](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/check-domain-transferability.html)」を参照してください。

### `delete-tags-for-domain`
<a name="route-53-domains_DeleteTagsForDomain_cli_2_topic"></a>

次のコード例は、`delete-tags-for-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインのタグを削除するには**  
次の `delete-tags-for-domain` コマンドは、指定されたドメインから 3 つのタグを削除します。タグ値ではなく、タグキーのみを指定することに注意してください。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains delete-tags-for-domain \
    --region us-east-1 \
    --domain-name example.com \
    --tags-to-delete accounting-key hr-key engineering-key
```
このコマンドでは何も出力されません。  
タグが削除されたことを確認するには、[list-tags-for-domain](https://docs.aws.amazon.com/cli/latest/reference/route53domains/list-tags-for-domain.html) を実行します。詳細については、「Amazon Route 53 デベロッパーガイド」の「[Tagging Amazon Route 53 Resources](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTagsForDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/delete-tags-for-domain.html)」を参照してください。

### `disable-domain-auto-renew`
<a name="route-53-domains_DisableDomainAutoRenew_cli_2_topic"></a>

次のコード例は、`disable-domain-auto-renew` を使用する方法を示しています。

**AWS CLI**  
**ドメインの自動更新を無効にするには**  
次の `disable-domain-auto-renew` のコマンドは、ドメインの登録の有効期限が切れる前にドメイン `example.com` を自動的に更新*しないように* Route 53 を設定します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains disable-domain-auto-renew \
    --region us-east-1 \
    --domain-name example.com
```
このコマンドでは何も出力されません。  
設定が変更されたことを確認するには、[get-domain-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-domain-detail.html) を実行します。自動更新が無効になっている場合、`AutoRenew` の値は `False` となります。自動更新の詳細については、「*Amazon Route 53デベロッパーガイド*」の「Renewing Registration for a Domain <https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-renew.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableDomainAutoRenew](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/disable-domain-auto-renew.html)」を参照してください。

### `disable-domain-transfer-lock`
<a name="route-53-domains_DisableDomainTransferLock_cli_2_topic"></a>

次のコード例は、`disable-domain-transfer-lock` を使用する方法を示しています。

**AWS CLI**  
**ドメインの転送ロックを無効にするには**  
次の `disable-domain-transfer-lock` のコマンドは、ドメインを別のレジストラに転送できるように、ドメイン `example.com` の転送ロックを削除します。このコマンドは `clientTransferProhibited` ステータスを変更します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains disable-domain-transfer-lock \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "OperationId": "3f28e0ac-126a-4113-9048-cc930example"
}
```
転送ロックが変更されていることを確認するには、[get-domain-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-domain-detail.html) を実行します。転送ロックが無効になっている場合、`StatusList` の値には `clientTransferProhibited` が*含まれません*。  
転送プロセスの詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Transferring a Domain from Amazon Route 53 to Another Registrar](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-from-route-53.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableDomainTransferLock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/disable-domain-transfer-lock.html)」を参照してください。

### `enable-domain-auto-renew`
<a name="route-53-domains_EnableDomainAutoRenew_cli_2_topic"></a>

次のコード例は、`enable-domain-auto-renew` を使用する方法を示しています。

**AWS CLI**  
**ドメインの自動更新を有効にするには**  
次の `enable-domain-auto-renew` のコマンドは、ドメインの登録の有効期限が切れる前にドメイン `example.com` を自動的に更新するように Route 53 を設定します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains enable-domain-auto-renew \
    --region us-east-1 \
    --domain-name example.com
```
このコマンドでは何も出力されません。設定が変更されたことを確認するには、[get-domain-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-domain-detail.html) を実行します。自動更新が有効になっている場合、`AutoRenew` の値は `True` です。  
自動更新の詳細については、「*Amazon Route 53デベロッパーガイド*」の「Renewing Registration for a Domain <https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-renew.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableDomainAutoRenew](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/enable-domain-auto-renew.html)」を参照してください。

### `enable-domain-transfer-lock`
<a name="route-53-domains_EnableDomainTransferLock_cli_2_topic"></a>

次のコード例は、`enable-domain-transfer-lock` を使用する方法を示しています。

**AWS CLI**  
**ドメインで転送ロックを有効にするには**  
次の `enable-domain-transfer-lock` のコマンドは、指定されたドメインをロックして、別のレジストラに転送できないようにします。このコマンドは `clientTransferProhibited` ステータスを変更します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains enable-domain-transfer-lock \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "OperationId": "3f28e0ac-126a-4113-9048-cc930example"
}
```
転送ロックが変更されていることを確認するには、[get-domain-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-domain-detail.html) を実行します。転送ロックを有効にすると、`StatusList` の値には `clientTransferProhibited` が含まれます。  
転送プロセスの詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Transferring a Domain from Amazon Route 53 to Another Registrar](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-from-route-53.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableDomainTransferLock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/enable-domain-transfer-lock.html)」を参照してください。

### `get-contact-reachability-status`
<a name="route-53-domains_GetContactReachabilityStatus_cli_2_topic"></a>

次のコード例は、`get-contact-reachability-status` を使用する方法を示しています。

**AWS CLI**  
**登録者の連絡先が確認メールに応答したかどうかを判断するには**  
次の `get-contact-reachability-status` コマンドは、指定されたドメインの登録者の連絡先が確認 E メールに応答したかどうかに関する情報を返します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains get-contact-reachability-status \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "domainName": "example.com",
    "status": "DONE"
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Resending Authorization and Confirmation Emails](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-click-email-link.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetContactReachabilityStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/get-contact-reachability-status.html)」を参照してください。

### `get-domain-detail`
<a name="route-53-domains_GetDomainDetail_cli_2_topic"></a>

次のコード例は、`get-domain-detail` を使用する方法を示しています。

**AWS CLI**  
**指定されたドメインに関する詳細情報を取得するには**  
次の `get-domain-detail` コマンドは、指定されたドメインに関する詳細情報を表示します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains get-domain-detail \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "DomainName": "example.com",
    "Nameservers": [
        {
            "Name": "ns-2048.awsdns-64.com",
            "GlueIps": []
        },
        {
            "Name": "ns-2049.awsdns-65.net",
            "GlueIps": []
        },
        {
            "Name": "ns-2050.awsdns-66.org",
            "GlueIps": []
        },
        {
            "Name": "ns-2051.awsdns-67.co.uk",
            "GlueIps": []
        }
    ],
    "AutoRenew": true,
    "AdminContact": {
        "FirstName": "Saanvi",
        "LastName": "Sarkar",
        "ContactType": "COMPANY",
        "OrganizationName": "Example",
        "AddressLine1": "123 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "ssarkar@example.com",
        "ExtraParams": []
    },
    "RegistrantContact": {
        "FirstName": "Alejandro",
        "LastName": "Rosalez",
        "ContactType": "COMPANY",
        "OrganizationName": "Example",
        "AddressLine1": "123 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "arosalez@example.com",
        "ExtraParams": []
    },
    "TechContact": {
        "FirstName": "Wang",
        "LastName": "Xiulan",
        "ContactType": "COMPANY",
        "OrganizationName": "Example",
        "AddressLine1": "123 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "wxiulan@example.com",
        "ExtraParams": []
    },
    "AdminPrivacy": true,
    "RegistrantPrivacy": true,
    "TechPrivacy": true,
    "RegistrarName": "Amazon Registrar, Inc.",
    "WhoIsServer": "whois.registrar.amazon",
    "RegistrarUrl": "http://registrar.amazon.com",
    "AbuseContactEmail": "abuse@registrar.amazon.com",
    "AbuseContactPhone": "+1.2062661000",
    "CreationDate": 1444934889.601,
    "ExpirationDate": 1602787689.0,
    "StatusList": [
        "clientTransferProhibited"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomainDetail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/get-domain-detail.html)」を参照してください。

### `get-domain-suggestions`
<a name="route-53-domains_GetDomainSuggestions_cli_2_topic"></a>

次のコード例は、`get-domain-suggestions` を使用する方法を示しています。

**AWS CLI**  
**推奨されるドメイン名のリストを取得するには**  
次の `get-domain-suggestions` コマンドは、ドメイン名 `example.com` に基づいて推奨されるドメイン名のリストを表示します。レスポンスには、利用可能なドメイン名のみが含まれます。このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains get-domain-suggestions \
    --region us-east-1 \
    --domain-name example.com \
    --suggestion-count 10 \
    --only-available
```
出力:  

```
{
    "SuggestionsList": [
        {
            "DomainName": "egzaampal.com",
            "Availability": "AVAILABLE"
        },
        {
            "DomainName": "examplelaw.com",
            "Availability": "AVAILABLE"
        },
        {
            "DomainName": "examplehouse.net",
            "Availability": "AVAILABLE"
        },
        {
            "DomainName": "homeexample.net",
            "Availability": "AVAILABLE"
        },
        {
            "DomainName": "examplelist.com",
            "Availability": "AVAILABLE"
       },
        {
            "DomainName": "examplenews.net",
            "Availability": "AVAILABLE"
        },
        {
            "DomainName": "officeexample.com",
            "Availability": "AVAILABLE"
        },
        {
            "DomainName": "exampleworld.com",
            "Availability": "AVAILABLE"
        },
        {
            "DomainName": "exampleart.com",
            "Availability": "AVAILABLE"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDomainSuggestions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/get-domain-suggestions.html)」を参照してください。

### `get-operation-detail`
<a name="route-53-domains_GetOperationDetail_cli_2_topic"></a>

次のコード例は、`get-operation-detail` を使用する方法を示しています。

**AWS CLI**  
**オペレーションの現在のステータスを取得するには**  
一部のドメイン登録オペレーションは非同期的に動作し、完了する前にレスポンスを返します。これらのオペレーションは、現在のステータスを取得するために使用できるオペレーション ID を返します。次の `get-operation-detail` コマンドは、指定されたオペレーションのステータスを返します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains get-operation-detail \
    --region us-east-1 \
    --operation-id edbd8d63-7fe7-4343-9bc5-54033example
```
出力:  

```
{
    "OperationId": "edbd8d63-7fe7-4343-9bc5-54033example",
    "Status": "SUCCESSFUL",
    "DomainName": "example.com",
    "Type": "DOMAIN_LOCK",
    "SubmittedDate": 1573749367.864
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOperationDetail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/get-operation-detail.html)」を参照してください。

### `list-domains`
<a name="route-53-domains_ListDomains_cli_2_topic"></a>

次の例は、`list-domains` を使用する方法を説明しています。

**AWS CLI**  
**現在の AWS アカウントに登録されているドメインを一覧表示するには**  
次の`list-domains`コマンドは、現在の AWS アカウントに登録されているドメインに関する概要情報を一覧表示します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains list-domains
    --region us-east-1
```
出力:  

```
{
    "Domains": [
        {
            "DomainName": "example.com",
            "AutoRenew": true,
            "TransferLock": true,
            "Expiry": 1602712345.0
        },
        {
            "DomainName": "example.net",
            "AutoRenew": true,
            "TransferLock": true,
            "Expiry": 1602723456.0
        },
        {
            "DomainName": "example.org",
            "AutoRenew": true,
            "TransferLock": true,
            "Expiry": 1602734567.0
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/list-domains.html)」を参照してください。

### `list-operations`
<a name="route-53-domains_ListOperations_cli_2_topic"></a>

次のコード例は、`list-operations` を使用する方法を示しています。

**AWS CLI**  
**オペレーション ID を返すオペレーションのステータスを一覧表示するには**  
一部のドメイン登録オペレーションは非同期的に実行され、完了する前にレスポンスを返します。これらのオペレーションは、現在のステータスを取得するために使用できるオペレーション ID を返します。次の `list-operations` コマンドは、現在のドメイン登録オペレーションに関するステータスを含む概要情報を一覧表示します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains list-operations
    --region us-east-1
```
出力:  

```
{
    "Operations": [
        {
            "OperationId": "aab9822f-1da0-4bf3-8a15-fd4e0example",
            "Status": "SUCCESSFUL",
            "Type": "DOMAIN_LOCK",
            "SubmittedDate": 1455321739.986
        },
        {
            "OperationId": "c24379ed-76be-42f8-bdad-9379bexample",
            "Status": "SUCCESSFUL",
            "Type": "UPDATE_NAMESERVER",
            "SubmittedDate": 1468960475.109
        },
        {
            "OperationId": "f47e1297-ef9e-4c2b-ae1e-a5fcbexample",
            "Status": "SUCCESSFUL",
            "Type": "RENEW_DOMAIN",
            "SubmittedDate": 1473561835.943
        },
        {
            "OperationId": "75584f23-b15f-459e-aed7-dc6f5example",
            "Status": "SUCCESSFUL",
            "Type": "UPDATE_DOMAIN_CONTACT",
            "SubmittedDate": 1547501003.41
        }
    ]
}
```
出力には、オペレーション ID を返し、現在の AWS アカウントを使用して登録したすべてのドメインで実行したすべてのオペレーションが含まれます。指定した日付以降に送信したオペレーションのみを取得する場合は、`submitted-since` パラメータを含めて、Unix 形式と協定世界時 (UTC) で日付を指定できます。次のコマンドは、2020 年 1 月 1 日の UTC 午前 12 時以降に送信されたすべてのオペレーションのステータスを取得します。  

```
aws route53domains list-operations \
    --submitted-since 1577836800
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOperations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/list-operations.html)」を参照してください。

### `list-tags-for-domain`
<a name="route-53-domains_ListTagsForDomain_cli_2_topic"></a>

次のコード例は、`list-tags-for-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインのタグを一覧表示するには**  
次の `list-tags-for-domain` のコマンドは、指定されたドメインに現在関連付けられているタグを一覧表示します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains list-tags-for-domain \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "TagList": [
        {
            "Key": "key1",
            "Value": "value1"
        },
        {
            "Key": "key2",
            "Value": "value2"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Tagging Amazon Route 53 Resources](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/list-tags-for-domain.html)」を参照してください。

### `register-domain`
<a name="route-53-domains_RegisterDomain_cli_2_topic"></a>

次のコード例は、`register-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインを登録するには**  
次の `register-domain` コマンドはドメインを登録し、JSON 形式のファイルからすべてのパラメータ値を取得します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains register-domain \
    --region us-east-1 \
    --cli-input-json file://register-domain.json
```
`register-domain.json` の内容:  

```
{
    "DomainName": "example.com",
    "DurationInYears": 1,
    "AutoRenew": true,
    "AdminContact": {
        "FirstName": "Martha",
        "LastName": "Rivera",
        "ContactType": "PERSON",
        "OrganizationName": "Example",
        "AddressLine1": "1 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "mrivera@example.com"
    },
    "RegistrantContact": {
        "FirstName": "Li",
        "LastName": "Juan",
        "ContactType": "PERSON",
        "OrganizationName": "Example",
        "AddressLine1": "1 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "ljuan@example.com"
    },
    "TechContact": {
        "FirstName": "Mateo",
        "LastName": "Jackson",
        "ContactType": "PERSON",
        "OrganizationName": "Example",
        "AddressLine1": "1 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "mjackson@example.com"
    },
    "PrivacyProtectAdminContact": true,
    "PrivacyProtectRegistrantContact": true,
    "PrivacyProtectTechContact": true
}
```
出力:  

```
{
    "OperationId": "b114c44a-9330-47d1-a6e8-a0b11example"
}
```
オペレーションが成功したことを確認するには、`get-operation-detail` を実行します。詳細については、「[get-operation-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-operation-detail.html)」を参照してください。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[新しいドメインの登録](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-register.html)」を参照してください。  
`ExtraParams` の最上位ドメイン (TLD) に必要な値と有効な値については「*Amazon Route 53 API リファレンス*」の「[ExtraParam](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ExtraParam.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/register-domain.html)」を参照してください。

### `renew-domain`
<a name="route-53-domains_RenewDomain_cli_2_topic"></a>

次のコード例は、`renew-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインを更新するには**  
次の `renew-domain` コマンドは、指定されたドメインを 5 年間更新します。`current-expiry-year` の値を取得するには、`get-domain-detail` コマンドを使用し、Unix 形式から `ExpirationDate` の値を変換します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains renew-domain \
    --region us-east-1 \
    --domain-name example.com \
    --duration-in-years 5 \
    --current-expiry-year 2020
```
出力:  

```
{
    "OperationId": "3f28e0ac-126a-4113-9048-cc930example"
}
```
オペレーションが成功したことを確認するには、`get-operation-detail` を実行します。詳細については、「[get-operation-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-operation-detail.html)」を参照してください。  
.com や .org など、各最上位ドメイン (TLD) のレジストリは、ドメインを更新できる最大年数を制御します。ドメインの最大更新期間を取得するには、「*Amazon Route 53 デベロッパーガイド*」の「[Domains That You Can Register with Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar-tld-list.html)」のTLD の登録と更新期間についてのセクションを参照してください。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Renewing Registration for a Domain](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-renew.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RenewDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/renew-domain.html)」を参照してください。

### `resend-contact-reachability-email`
<a name="route-53-domains_ResendContactReachabilityEmail_cli_2_topic"></a>

次のコード例は、`resend-contact-reachability-email` を使用する方法を示しています。

**AWS CLI**  
**登録者の連絡先の現在の E メールアドレスに確認 E メールを再送信するには**  
次の `resend-contact-reachability-email` コマンドは、example.com ドメインの登録者の連絡先の現在の E メールアドレスに確認 E メールを再送信します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains resend-contact-reachability-email \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "domainName": "example.com",
    "emailAddress": "moliveira@example.com",
    "isAlreadyVerified": true
}
```
この例のように、`isAlreadyVerified` の値が `true` の場合、登録者の連絡先は、指定された E メールアドレスに到達可能であることを既に確認しています。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Resending Authorization and Confirmation Emails](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-click-email-link.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResendContactReachabilityEmail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/resend-contact-reachability-email.html)」を参照してください。

### `retrieve-domain-auth-code`
<a name="route-53-domains_RetrieveDomainAuthCode_cli_2_topic"></a>

次のコード例は、`retrieve-domain-auth-code` を使用する方法を示しています。

**AWS CLI**  
**ドメインの承認コードを取得して、ドメインを別のレジストラに転送できるようにするには**  
次の `retrieve-domain-auth-code` コマンドは、example.com ドメインの現在の承認コードを取得します。この値を別のドメインレジストラに渡すのは、ドメインをそのレジストラに転送する場合です。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains retrieve-domain-auth-code \
    --region us-east-1 \
    --domain-name example.com
```
出力:  

```
{
    "AuthCode": ")o!v3dJeXampLe"
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Transferring a Domain from Amazon Route 53 to Another Registrar](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-from-route-53.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RetrieveDomainAuthCode](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/retrieve-domain-auth-code.html)」を参照してください。

### `transfer-domain`
<a name="route-53-domains_TransferDomain_cli_2_topic"></a>

次のコード例は、`transfer-domain` を使用する方法を示しています。

**AWS CLI**  
**Amazon Route 53 にドメインを転送するには**  
次の `transfer-domain` コマンドは、JSON 形式のファイル `C:\temp\transfer-domain.json` によって提供されるパラメータを使用して、ドメインを Route 53 に転送します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains transfer-domain \
    --region us-east-1 \
    --cli-input-json file://C:\temp\transfer-domain.json
```
`transfer-domain.json` の内容:  

```
{
    "DomainName": "example.com",
    "DurationInYears": 1,
    "Nameservers": [
        {
            "Name": "ns-2048.awsdns-64.com"
        },
        {
            "Name": "ns-2049.awsdns-65.net"
        },
        {
            "Name": "ns-2050.awsdns-66.org"
        },
        {
            "Name": "ns-2051.awsdns-67.co.uk"
        }
    ],
    "AuthCode": ")o!v3dJeXampLe",
    "AutoRenew": true,
    "AdminContact": {
        "FirstName": "Martha",
        "LastName": "Rivera",
        "ContactType": "PERSON",
        "OrganizationName": "Example",
        "AddressLine1": "1 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "mrivera@example.com"
    },
    "RegistrantContact": {
        "FirstName": "Li",
        "LastName": "Juan",
        "ContactType": "PERSON",
        "OrganizationName": "Example",
        "AddressLine1": "1 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "ljuan@example.com"
    },
    "TechContact": {
        "FirstName": "Mateo",
        "LastName": "Jackson",
        "ContactType": "PERSON",
        "OrganizationName": "Example",
        "AddressLine1": "1 Main Street",
        "City": "Anytown",
        "State": "WA",
        "CountryCode": "US",
        "ZipCode": "98101",
        "PhoneNumber": "+1.8005551212",
        "Email": "mjackson@example.com"
    },
    "PrivacyProtectAdminContact": true,
    "PrivacyProtectRegistrantContact": true,
    "PrivacyProtectTechContact": true
}
```
出力:  

```
{
    "OperationId": "b114c44a-9330-47d1-a6e8-a0b11example"
}
```
オペレーションが成功したことを確認するには、`get-operation-detail` を実行します。詳細については、「[get-operation-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-operation-detail.html)」を参照してください。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Transferring Registration for a Domain to Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-to-route-53.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TransferDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/transfer-domain.html)」を参照してください。

### `update-domain-contact-privacy`
<a name="route-53-domains_UpdateDomainContactPrivacy_cli_2_topic"></a>

次のコード例は、`update-domain-contact-privacy` を使用する方法を示しています。

**AWS CLI**  
**ドメインの連絡先のプライバシー設定を更新するには**  
次の `update-domain-contact-privacy` コマンドは、example.com ドメインの管理連絡先のプライバシー保護をオフにします。このコマンドは `us-east-1` リージョンでのみ実行されます。  
デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains update-domain-contact-privacy \
    --region us-east-1 \
    --domain-name example.com \
    --no-admin-privacy
```
出力:  

```
{
    "OperationId": "b3a219e9-d801-4244-b533-b7256example"
}
```
オペレーションが成功したことを確認するには、`get-operation-detail` を実行します。詳細については、「[get-operation-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-operation-detail.html)」を参照してください。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Enabling or Disabling Privacy Protection for Contact Information for a Domain](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-privacy-protection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDomainContactPrivacy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/update-domain-contact-privacy.html)」を参照してください。

### `update-domain-contact`
<a name="route-53-domains_UpdateDomainContact_cli_2_topic"></a>

次のコード例は、`update-domain-contact` を使用する方法を示しています。

**AWS CLI**  
**ドメインの連絡先情報を更新するには**  
次の `update-domain-contact` コマンドは、ドメインの連絡先情報を更新し、JSON 形式のファイル `C:\temp\update-domain-contact.json` からパラメータを取得します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains update-domain-contact \
    --region us-east-1 \
    --cli-input-json file://C:\temp\update-domain-contact.json
```
`update-domain-contact.json` の内容:  

```
{
    "AdminContact": {
        "AddressLine1": "101 Main Street",
        "AddressLine2": "Suite 1a",
        "City": "Seattle",
        "ContactType": "COMPANY",
        "CountryCode": "US",
        "Email": "w.xiulan@example.com",
        "FirstName": "Wang",
        "LastName": "Xiulan",
        "OrganizationName": "Example",
        "PhoneNumber": "+1.8005551212",
        "State": "WA",
        "ZipCode": "98101"
    },
    "DomainName": "example.com",
    "RegistrantContact": {
        "AddressLine1": "101 Main Street",
        "AddressLine2": "Suite 1a",
        "City": "Seattle",
        "ContactType": "COMPANY",
        "CountryCode": "US",
        "Email": "w.xiulan@example.com",
        "FirstName": "Wang",
        "LastName": "Xiulan",
        "OrganizationName": "Example",
        "PhoneNumber": "+1.8005551212",
        "State": "WA",
        "ZipCode": "98101"
    },
    "TechContact": {
        "AddressLine1": "101 Main Street",
        "AddressLine2": "Suite 1a",
        "City": "Seattle",
        "ContactType": "COMPANY",
        "CountryCode": "US",
        "Email": "w.xiulan@example.com",
        "FirstName": "Wang",
        "LastName": "Xiulan",
        "OrganizationName": "Example",
        "PhoneNumber": "+1.8005551212",
        "State": "WA",
        "ZipCode": "98101"
    }
}
```
出力:  

```
{
    "OperationId": "b3a219e9-d801-4244-b533-b7256example"
}
```
オペレーションが成功したことを確認するには、[get-domain-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-domain-detail.html) を実行します。詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Updating Contact Information for a Domain](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-update-contacts.html#domain-update-contacts-basic)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDomainContact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/update-domain-contact.html)」を参照してください。

### `update-domain-nameservers`
<a name="route-53-domains_UpdateDomainNameservers_cli_2_topic"></a>

次のコード例は、`update-domain-nameservers` を使用する方法を示しています。

**AWS CLI**  
**ドメインのネームサーバーを更新するには**  
次の `update-domain-nameservers` コマンドは、ドメインのネームサーバーを更新します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains update-domain-nameservers \
    --region us-east-1 \
    --domain-name example.com \
    --nameservers Name=ns-1.awsdns-01.org Name=ns-2.awsdns-02.co.uk Name=ns-3.awsdns-03.net Name=ns-4.awsdns-04.com
```
出力:  

```
{
    "OperationId": "f1691ec4-0e7a-489e-82e0-b19d3example"
}
```
オペレーションが成功したことを確認するには、[get-domain-detail](https://docs.aws.amazon.com/cli/latest/reference/route53domains/get-domain-detail.html) を実行します。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Adding or Changing Name Servers and Glue Records for a Domain](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-name-servers-glue-records.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDomainNameservers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/update-domain-nameservers.html)」を参照してください。

### `update-tags-for-domain`
<a name="route-53-domains_UpdateTagsForDomain_cli_2_topic"></a>

次のコード例は、`update-tags-for-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインのタグを追加または更新するには**  
次の `update-tags-for-domain` コマンドは、example.com ドメインの 2 つのキーと対応する値を追加または更新します。キーの値を更新するには、キーと新しい値を含めます。タグを追加または更新できるのは、一度に 1 つのドメインのみです。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains update-tags-for-domain \
    --region us-east-1 \
    --domain-name example.com \
    --tags-to-update "Key=key1,Value=value1" "Key=key2,Value=value2"
```
このコマンドでは何も出力されません。タグが追加または更新されたことを確認するには、[list-tags-for-domain](https://docs.aws.amazon.com/cli/latest/reference/route53domains/list-tags-for-domain.html) を実行します。  
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Tagging Amazon Route 53 Resources](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTagsForDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/update-tags-for-domain.html)」を参照してください。

### `view-billing`
<a name="route-53-domains_ViewBilling_cli_2_topic"></a>

次の例は、`view-billing` を使用する方法を説明しています。

**AWS CLI**  
**現在の AWS アカウントのドメイン登録料金の請求情報を取得するには**  
次の `view-billing` コマンドは、2018 年 1 月 1 日 (Unix 時間で 1514764800) から 2019 年 12 月 31 日深夜 (Unix 時間で 1577836800) までの間、現在のアカウントのすべてのドメイン関連の請求レコードを返します。  
このコマンドは `us-east-1` リージョンでのみ実行されます。デフォルトのリージョンが `us-east-1` に設定されている場合は、`region` パラメータを省略できます。  

```
aws route53domains view-billing \
    --region us-east-1 \
    --start-time 1514764800 \
    --end-time 1577836800
```
出力:  

```
{
    "BillingRecords": [
        {
            "DomainName": "example.com",
            "Operation": "RENEW_DOMAIN",
            "InvoiceId": "149962827",
            "BillDate": 1536618063.181,
            "Price": 12.0
        },
        {
            "DomainName": "example.com",
            "Operation": "RENEW_DOMAIN",
            "InvoiceId": "290913289",
            "BillDate": 1568162630.884,
            "Price": 12.0
        }
    ]
}
```
詳細については、「*Amazon Route 53 API リファレンス*」の「[ViewBilling](https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ViewBilling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ViewBilling](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53domains/view-billing.html)」を参照してください。

# を使用した Route 53 Profiles の例 AWS CLI
<a name="cli_2_route53profiles_code_examples"></a>

次のコード例は、Route 53 Profiles AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-profile`
<a name="route53profiles_AssociateProfile_cli_2_topic"></a>

次のコード例は、`associate-profile` を使用する方法を示しています。

**AWS CLI**  
**プロファイルを関連付けるには**  
次の `associate-profile` の例では、プロファイルを VPC に関連付けます。  

```
aws route53profiles associate-profile \
    --name test-association \
    --profile-id rp-4987774726example \
    --resource-id vpc-0af3b96b3example
```
出力:  

```
{
    "ProfileAssociation": {
        "CreationTime": 1710851336.527,
        "Id": "rpassoc-489ce212fexample",
        "ModificationTime": 1710851336.527,
        "Name": "test-association",
        "OwnerId": "123456789012",
        "ProfileId": "rp-4987774726example",
        "ResourceId": "vpc-0af3b96b3example",
        "Status": "CREATING",
        "StatusMessage": "Creating Profile Association"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[プロファイルの使用](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/profile-high-level-steps.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/associate-profile.html)」を参照してください。

### `associate-resource-to-profile`
<a name="route53profiles_AssociateResourceToProfile_cli_2_topic"></a>

次のコード例は、`associate-resource-to-profile` を使用する方法を示しています。

**AWS CLI**  
**リソースをプロファイルに関連付けるには**  
次の `associate-resource-to-profile` の例では、DNS Firewall ルールグループを優先度 102 でプロファイルに関連付けます。  

```
aws route53profiles associate-resource-to-profile \
    --name test-resource-association \
    --profile-id rp-4987774726example \
    --resource-arn arn:aws:route53resolver:us-east-1:123456789012:firewall-rule-group/rslvr-frg-cfe7f72example \
    --resource-properties "{\"priority\": 102}"
```
出力:  

```
{
    "ProfileResourceAssociation": {
        "CreationTime": 1710851216.613,
        "Id": "rpr-001913120a7example",
        "ModificationTime": 1710851216.613,
        "Name": "test-resource-association",
        "OwnerId": "123456789012",
        "ProfileId": "rp-4987774726example",
        "ResourceArn": "arn:aws:route53resolver:us-east-1:123456789012:firewall-rule-group/rslvr-frg-cfe7f72example",
        "ResourceProperties": "{\"priority\":102}",
        "ResourceType": "FIREWALL_RULE_GROUP",
        "Status": "UPDATING",
        "StatusMessage": "Updating the Profile to DNS Firewall rule group association"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*.」の「[AssociateResourceToProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/associate-resource-to-profile.html)」を参照してください。

### `create-profile`
<a name="route53profiles_CreateProfile_cli_2_topic"></a>

次のコード例は、`create-profile` を使用する方法を示しています。

**AWS CLI**  
**プロファイルを作成するには**  
次の `create-profile` の例では、プロファイルを作成します。  

```
aws route53profiles create-profile \
    --name test
```
出力:  

```
{
    "Profile": {
        "Arn": "arn:aws:route53profiles:us-east-1:123456789012:profile/rp-6ffe47d5example",
        "ClientToken": "2ca1a304-32b3-4f5f-bc4c-EXAMPLE11111",
        "CreationTime": 1710850903.578,
        "Id": "rp-6ffe47d5example",
        "ModificationTime": 1710850903.578,
        "Name": "test",
        "OwnerId": "123456789012",
        "ShareStatus": "NOT_SHARED",
        "Status": "COMPLETE",
        "StatusMessage": "Created Profile"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/create-profile.html)」を参照してください。

### `delete-profile`
<a name="route53profiles_DeleteProfile_cli_2_topic"></a>

次のコード例は、`delete-profile` を使用する方法を示しています。

**AWS CLI**  
**プロファイルを削除するには**  
次の `delete-profile` の例では、プロファイルを削除します。  

```
aws route53profiles delete-profile \
    --profile-id rp-6ffe47d5example
```
出力:  

```
{
    "Profile": {
        "Arn": "arn:aws:route53profiles:us-east-1:123456789012:profile/rp-6ffe47d5example",
        "ClientToken": "0a15fec0-05d9-4f78-bec0-EXAMPLE11111",
        "CreationTime": 1710850903.578,
        "Id": "rp-6ffe47d5example",
        "ModificationTime": 1710850903.578,
        "Name": "test",
        "OwnerId": "123456789012",
        "ShareStatus": "NOT_SHARED",
        "Status": "DELETED",
        "StatusMessage": "Deleted Profile"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/delete-profile.html)」を参照してください。

### `disassociate-profile`
<a name="route53profiles_DisassociateProfile_cli_2_topic"></a>

次のコード例は、`disassociate-profile` を使用する方法を示しています。

**AWS CLI**  
**プロファイルの関連付けを解除するには**  
次の `disassociate-profile` の例では、VPC からプロファイルの関連付けを解除します。  

```
aws route53profiles disassociate-profile \
    --profile-id rp-4987774726example \
    --resource-id vpc-0af3b96b3example
```
出力:  

```
{
    "ProfileAssociation": {
        "CreationTime": 1710851336.527,
        "Id": "rpassoc-489ce212fexample",
        "ModificationTime": 1710851401.362,
        "Name": "test-association",
        "OwnerId": "123456789012",
        "ProfileId": "rp-4987774726example",
        "ResourceId": "vpc-0af3b96b3example",
        "Status": "DELETING",
        "StatusMessage": "Deleting Profile Association"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/disassociate-profile.html)」を参照してください。

### `disassociate-resource-from-profile`
<a name="route53profiles_DisassociateResourceFromProfile_cli_2_topic"></a>

次のコード例は、`disassociate-resource-from-profile` を使用する方法を示しています。

**AWS CLI**  
**プロファイルからリソースの関連付けを解除するには**  
次の `disassociate-resource-from-profile` の例では、プロファイルから DNS Firewall ルールグループの関連付けを解除します。  

```
aws route53profiles disassociate-resource-from-profile \
    --profile-id rp-4987774726example \
    --resource-arn arn:aws:route53resolver:us-east-1:123456789012:firewall-rule-group/rslvr-frg-cfe7f72example
```
出力:  

```
{
    "ProfileResourceAssociation": {
        "CreationTime": 1710851216.613,
        "Id": "rpr-001913120a7example",
        "ModificationTime": 1710852624.36,
        "Name": "test-resource-association",
        "OwnerId": "123456789012",
        "ProfileId": "rp-4987774726example",
        "ResourceArn": "arn:aws:route53resolver:us-east-1:123456789012:firewall-rule-group/rslvr-frg-cfe7f72example",
        "ResourceProperties": "{\"priority\":105}",
        "ResourceType": "FIREWALL_RULE_GROUP",
        "Status": "DELETING",
        "StatusMessage": "Deleting the Profile to DNS Firewall rule group association"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateResourceFromProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/disassociate-resource-from-profile.html)」を参照してください。

### `get-profile-association`
<a name="route53profiles_GetProfileAssociation_cli_2_topic"></a>

次のコード例は、`get-profile-association` を使用する方法を示しています。

**AWS CLI**  
**プロファイルの関連付けに関する情報を取得するには**  
次の `get-profile-association` は、指定されたプロファイルの関連付けに関する情報を返します。  

```
aws route53profiles get-profile-association \
    --profile-association-id rpassoc-489ce212fexample
```
出力:  

```
{
    "ProfileAssociation": {
        "CreationTime": 1709338817.148,
        "Id": "rrpassoc-489ce212fexample",
        "ModificationTime": 1709338974.772,
        "Name": "test-association",
        "OwnerId": "123456789012",
        "ProfileId": "rp-4987774726example",
        "ResourceId": "vpc-0af3b96b3example",
        "Status": "COMPLETE",
        "StatusMessage": "Created Profile Association"
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetProfileAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/get-profile-association.html)」を参照してください。

### `get-profile-resource-association`
<a name="route53profiles_GetProfileResourceAssociation_cli_2_topic"></a>

次のコード例は、`get-profile-resource-association` を使用する方法を示しています。

**AWS CLI**  
**プロファイルに関連付けられたリソースに関する情報を取得するには**  
次の `get-profile-resource-association` は、プロファイルへの指定されたリソースの関連付けに関する情報を返します。  

```
aws route53profiles get-profile-resource-association \
    --profile-resource-association-id rpr-001913120a7example
```
出力:  

```
{
    "ProfileResourceAssociation": {
        "CreationTime": 1710851216.613,
        "Id": "rpr-001913120a7example",
        "ModificationTime": 1710852303.798,
        "Name": "test-resource-association",
        "OwnerId": "123456789012",
        "ProfileId": "rp-4987774726example",
        "ResourceArn": "arn:aws:route53resolver:us-east-1:123456789012:firewall-rule-group/rslvr-frg-cfe7f72example",
        "ResourceProperties": "{\"priority\":105}",
        "ResourceType": "FIREWALL_RULE_GROUP",
        "Status": "COMPLETE",
        "StatusMessage": "Completed creation of Profile to DNS Firewall rule group association"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetProfileResourceAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/get-profile-resource-association.html)」を参照してください。

### `get-profile`
<a name="route53profiles_GetProfile_cli_2_topic"></a>

次のコード例は、`get-profile` を使用する方法を示しています。

**AWS CLI**  
**プロファイルの情報を取得するには**  
次の `get-profile` は、指定されたプロファイルの情報を返します。  

```
aws route53profiles get-profile \
    --profile-id rp-4987774726example
```
出力:  

```
{
    "Profile": {
        "Arn": "arn:aws:route53profiles:us-east-1:123456789012:profile/rp-4987774726example",
        "ClientToken": "0cbc5ae7-4921-4204-bea9-EXAMPLE11111",
        "CreationTime": 1710851044.288,
        "Id": "rp-4987774726example",
        "ModificationTime": 1710851044.288,
        "Name": "test",
        "OwnerId": "123456789012",
        "ShareStatus": "NOT_SHARED",
        "Status": "COMPLETE",
        "StatusMessage": "Created Profile"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/get-profile.html)」を参照してください。

### `list-profile-associations`
<a name="route53profiles_ListProfileAssociations_cli_2_topic"></a>

次のコード例は、`list-profile-associations` を使用する方法を示しています。

**AWS CLI**  
**プロファイルの関連付けを一覧表示するには**  
 AWS アカウントのプロファイルの関連付けを以下`list-profile-associations`に示します。  

```
aws route53profiles list-profile-associations
```
出力:  

```
{
    "ProfileAssociations": [
        {
            "CreationTime": 1709338817.148,
            "Id": "rpassoc-489ce212fexample",
            "ModificationTime": 1709338974.772,
            "Name": "test-association",
            "OwnerId": "123456789012",
            "ProfileId": "rp-4987774726example",
            "ResourceId": "vpc-0af3b96b3example",
            "Status": "COMPLETE",
            "StatusMessage": "Created Profile Association"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProfileAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/list-profile-associations.html)」を参照してください。

### `list-profile-resource-associations`
<a name="route53profiles_ListProfileResourceAssociations_cli_2_topic"></a>

次のコード例は、`list-profile-resource-associations` を使用する方法を示しています。

**AWS CLI**  
**プロファイルリソースの関連付けを一覧表示するには**  
次の `list-profile-resource-associations` では、指定されたプロファイルのプロファイルリソースの関連付けを一覧表示します。  

```
aws route53profiles list-profile-resource-associations \
    --profile-id rp-4987774726example
```
出力:  

```
{
     "ProfileResourceAssociations": [
         {
             "CreationTime": 1710851216.613,
             "Id": "rpr-001913120a7example",
             "ModificationTime": 1710851216.613,
             "Name": "test-resource-association",
             "OwnerId": "123456789012",
             "ProfileId": "rp-4987774726example",
             "ResourceArn": "arn:aws:route53resolver:us-east-1:123456789012:firewall-rule-group/rslvr-frg-cfe7f72example",
             "ResourceProperties": "{\"priority\":102}",
             "ResourceType": "FIREWALL_RULE_GROUP",
             "Status": "COMPLETE",
             "StatusMessage": "Completed creation of Profile to DNS Firewall rule group association"
         }
     ]
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProfileResourceAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/list-profile-resource-associations.html)」を参照してください。

### `list-profiles`
<a name="route53profiles_ListProfiles_cli_2_topic"></a>

次のコード例は、`list-profiles` を使用する方法を示しています。

**AWS CLI**  
**プロファイルを一覧表示するには**  
以下は、 AWS アカウントのプロファイルを`list-profiles`一覧表示し、それらに関する追加情報を表示します。  

```
aws route53profiles list-profiles
```
出力:  

```
{
     "ProfileSummaries": [
         {
             "Arn": "arn:aws:route53profiles:us-east-1:123456789012:profile/rp-4987774726example",
             "Id": "rp-4987774726example",
             "Name": "test",
             "ShareStatus": "NOT_SHARED"
         }
     ]
 }
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/list-profiles.html)」を参照してください。

### `list-tags-for-resource`
<a name="route53profiles_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` では、指定したリソースのタグを一覧表示します。  

```
aws route53profiles list-tags-for-resource \
    --resource-arn arn:aws:route53profiles:us-east-1:123456789012:profile/rp-4987774726example
```
出力:  

```
{
    "Tags": {
        "my-key-2": "my-value-2",
        "my-key-1": "my-value-1"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/list-tags-for-resource.html)」を参照してください。

### `update-profile-resource-association`
<a name="route53profiles_UpdateProfileResourceAssociation_cli_2_topic"></a>

次のコード例は、`update-profile-resource-association` を使用する方法を示しています。

**AWS CLI**  
**プロファイルに関連付けられたリソースを更新するには**  
次の `update-profile-resource-association` では、プロファイルに関連付けられている DNS Firewall ルールグループの優先度を更新します。  

```
aws route53profiles update-profile-resource-association \
    --profile-resource-association-id rpr-001913120a7example \
    --resource-properties "{\"priority\": 105}"
```
出力:  

```
{
    "ProfileResourceAssociation": {
        "CreationTime": 1710851216.613,
        "Id": "rpr-001913120a7example",
        "ModificationTime": 1710852303.798,
        "Name": "test-resource-association",
        "OwnerId": "123456789012",
        "ProfileId": "rp-4987774726example",
        "ResourceArn": "arn:aws:route53resolver:us-east-1:123456789012:firewall-rule-group/rslvr-frg-cfe7f72example",
        "ResourceProperties": "{\"priority\":105}",
        "ResourceType": "FIREWALL_RULE_GROUP",
        "Status": "UPDATING",
        "StatusMessage": "Updating the Profile to DNS Firewall rule group association"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateProfileResourceAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53profiles/update-profile-resource-association.html)」を参照してください。

# を使用した Route 53 Resolver の例 AWS CLI
<a name="cli_2_route53resolver_code_examples"></a>

次のコード例は、Route 53 Resolver AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-firewall-rule-group`
<a name="route53resolver_AssociateFirewallRuleGroup_cli_2_topic"></a>

次のコード例は、`associate-firewall-rule-group` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールグループを VPC に関連付けるには**  
次の `associate-firewall-rule-group` の例では、DNS Firewall ルールグループを Amazon VPC に関連付けます。  

```
aws route53resolver associate-firewall-rule-group \
    --name test-association \
    --firewall-rule-group-id rslvr-frg-47f93271fexample \
    --vpc-id vpc-31e92222 \
    --priority 101
```
出力:  

```
{
    "FirewallRuleGroupAssociation": {
        "Id": "rslvr-frgassoc-57e8873d7example",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group-association/rslvr-frgassoc-57e8873d7example",
        "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
        "VpcId": "vpc-31e92222",
        "Name": "test-association",
        "Priority": 101,
        "MutationProtection": "DISABLED",
        "Status": "UPDATING",
        "StatusMessage": "Creating Firewall Rule Group Association",
        "CreatorRequestId": "2ca1a304-32b3-4f5f-bc4c-EXAMPLE11111",
        "CreationTime": "2021-05-25T21:47:48.755768Z",
        "ModificationTime": "2021-05-25T21:47:48.755768Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing associations between your VPC and Route 53 Resolver DNS Firewall rule groups](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-associating-rule-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateFirewallRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/associate-firewall-rule-group.html)」を参照してください。

### `associate-resolver-endpoint-ip-address`
<a name="route53resolver_AssociateResolverEndpointIpAddress_cli_2_topic"></a>

次のコード例は、`associate-resolver-endpoint-ip-address` を使用する方法を示しています。

**AWS CLI**  
**別の IP アドレスを Resolver エンドポイントに関連付けるには**  
次の `associate-resolver-endpoint-ip-address` の例では、別の IP アドレスをインバウンド Resolver エンドポイントに関連付けます。サブネット ID のみを指定し、`--ip-address` パラメータから IP アドレスを省略すると、Resolver は指定したサブネット内の使用可能な IP アドレスの中から IP アドレスを選択します。  

```
aws route53resolver associate-resolver-endpoint-ip-address \
    --resolver-endpoint-id rslvr-in-497098ad5example \
    --ip-address="SubnetId=subnet-12d8exam,Ip=192.0.2.118"
```
出力:  

```
{
    "ResolverEndpoint": {
        "Id": "rslvr-in-497098ad5example",
        "CreatorRequestId": "AWSConsole.25.0123456789",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-in-497098ad5example",
        "Name": "my-inbound-endpoint",
        "SecurityGroupIds": [
            "sg-05cd7b25d6example"
        ],
        "Direction": "INBOUND",
        "IpAddressCount": 3,
        "HostVPCId": "vpc-304bexam",
        "Status": "UPDATING",
        "StatusMessage": "Updating the Resolver Endpoint",
        "CreationTime": "2020-01-02T23:25:45.538Z",
        "ModificationTime": "2020-01-02T23:25:45.538Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[インバウンドエンドポイントを作成または編集するときに指定する値](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-inbound-queries.html#resolver-forwarding-inbound-queries-values)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateResolverEndpointIpAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/associate-resolver-endpoint-ip-address.html)」を参照してください。

### `associate-resolver-rule`
<a name="route53resolver_AssociateResolverRule_cli_2_topic"></a>

次のコード例は、`associate-resolver-rule` を使用する方法を示しています。

**AWS CLI**  
**Resolver ルールグループを VPC に関連付けるには**  
次の `associate-resolver-rule` の例では、Resolver ルールを Amazon VPC に関連付けます。コマンドを実行すると、Resolver はルールの設定に基づいて DNS クエリ (転送されるクエリのドメイン名など) をネットワークに転送し始めます。  

```
aws route53resolver associate-resolver-rule \
    --name my-resolver-rule-association \
    --resolver-rule-id rslvr-rr-42b60677c0example \
    --vpc-id vpc-304bexam
```
出力:  

```
{
    "ResolverRuleAssociation": {
        "Id": "rslvr-rrassoc-d61cbb2c8bexample",
        "ResolverRuleId": "rslvr-rr-42b60677c0example",
        "Name": "my-resolver-rule-association",
        "VPCId": "vpc-304bexam",
        "Status": "CREATING",
        "StatusMessage": "[Trace id: 1-5dc5a8fa-ec2cc480d2ef07617example] Creating the association."
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Forwarding Outbound DNS Queries to Your Network](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-outbound-queries.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateResolverRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/associate-resolver-rule.html)」を参照してください。

### `create-firewall-domain-list`
<a name="route53resolver_CreateFirewallDomainList_cli_2_topic"></a>

次のコード例は、`create-firewall-domain-list` を使用する方法を示しています。

**AWS CLI**  
**Route 53 Resolver DNS Firewall のドメインリストを作成するには**  
次の`create-firewall-domain-list`例では、 AWS アカウントに test という名前の Route 53 Resolver DNS Firewall ドメインリストを作成します。  

```
aws route53resolver create-firewall-domain-list \
    --creator-request-id my-request-id \
    --name test
```
出力:  

```
{
    "FirewallDomainList": {
        "Id": "rslvr-fdl-d61cbb2cbexample",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-domain-list/rslvr-fdl-d61cbb2cbexample",
        "Name": "test",
        "DomainCount": 0,
        "Status": "COMPLETE",
        "StatusMessage": "Created Firewall Domain List",
        "CreatorRequestId": "my-request-id",
        "CreationTime": "2021-05-25T15:55:51.115365Z",
        "ModificationTime": "2021-05-25T15:55:51.115365Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing your own domain lists](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-user-managed-domain-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFirewallDomainList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/create-firewall-domain-list.html)」を参照してください。

### `create-firewall-rule-group`
<a name="route53resolver_CreateFirewallRuleGroup_cli_2_topic"></a>

次のコード例は、`create-firewall-rule-group` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールグループを作成するには**  
次の `create-firewall-rule-group` の例では、DNS Firewall ルールグループを作成します。  

```
aws route53resolver create-firewall-rule-group \
    --creator-request-id my-request-id \
    --name test
```
出力:  

```
{
    "FirewallRuleGroup": {
        "Id": "rslvr-frg-47f93271fexample",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group/rslvr-frg-47f93271fexample",
        "Name": "test",
        "RuleCount": 0,
        "Status": "COMPLETE",
        "StatusMessage": "Created Firewall Rule Group",
        "OwnerId": "123456789012",
        "CreatorRequestId": "my-request-id",
        "ShareStatus": "NOT_SHARED",
        "CreationTime": "2021-05-25T18:59:26.490017Z",
        "ModificationTime": "2021-05-25T18:59:26.490017Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFirewallRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/create-firewall-rule-group.html)」を参照してください。

### `create-firewall-rule`
<a name="route53resolver_CreateFirewallRule_cli_2_topic"></a>

次のコード例は、`create-firewall-rule` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールを作成するには**  
次の `create-firewall-rule` の例では、DNS Firewall ドメインリストに一覧表示されているドメインの DNS Firewall ルールにファイアウォールルールを作成します。  

```
aws route53resolver create-firewall-rule \
    --name allow-rule \
    --firewall-rule-group-id rslvr-frg-47f93271fexample \
    --firewall-domain-list-id rslvr-fdl-9e956e9ffexample \
    --priority 101 \
    --action ALLOW
```
出力:  

```
{
    "FirewallRule": {
        "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
        "FirewallDomainListId": "rslvr-fdl-9e956e9ffexample",
        "Name": "allow-rule",
        "Priority": 101,
        "Action": "ALLOW",
        "CreatorRequestId": "d81e3fb7-020b-415e-939f-EXAMPLE11111",
        "CreationTime": "2021-05-25T21:44:00.346093Z",
        "ModificationTime": "2021-05-25T21:44:00.346093Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFirewallRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/create-firewall-rule.html)」を参照してください。

### `create-resolver-endpoint`
<a name="route53resolver_CreateResolverEndpoint_cli_2_topic"></a>

次のコード例は、`create-resolver-endpoint` を使用する方法を示しています。

**AWS CLI**  
**インバウンド Resolver エンドポイントを作成するには**  
次の `create-resolver-endpoint` の例では、インバウンド Resolver エンドポイントを作成します。同じコマンドを使用して、インバウンドエンドポイントとアウトバウンドエンドポイントの両方を作成できます。  
aws route53resolver create-resolver-endpoint --name my-inbound-endpoint --creator-request-id 2020-01-01-18:47 --security-group-ids「sg-f62bexam」 --direction INBOUND --ip-addresses SubnetId =subnet-ba47exam,Ip=192.0.2.255 SubnetId =subnet-12d8exam,Ip=192.0.2.254  
出力:  

```
{
    "ResolverEndpoint": {
        "Id": "rslvr-in-f9ab8a03f1example",
        "CreatorRequestId": "2020-01-01-18:47",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-in-f9ab8a03f1example",
        "Name": "my-inbound-endpoint",
        "SecurityGroupIds": [
            "sg-f62bexam"
        ],
        "Direction": "INBOUND",
        "IpAddressCount": 2,
        "HostVPCId": "vpc-304examp",
        "Status": "CREATING",
        "StatusMessage": "[Trace id: 1-5dc1ff84-f3477826e4a190025example] Creating the Resolver Endpoint",
        "CreationTime": "2020-01-01T23:02:29.583Z",
        "ModificationTime": "2020-01-01T23:02:29.583Z"
    }
}
```
**アウトバウンド Resolver のエンドポイントを作成するには**  
次の `create-resolver-endpoint` の例では、JSON 形式のドキュメント `create-outbound-resolver-endpoint.json` の値を使用してアウトバウンド Resolver エンドポイントを作成します。  

```
aws route53resolver create-resolver-endpoint \
    --cli-input-json file://c:\temp\create-outbound-resolver-endpoint.json
```
`create-outbound-resolver-endpoint.json` の内容:  

```
{
   "CreatorRequestId": "2020-01-01-18:47",
   "Direction": "OUTBOUND",
   "IpAddresses": [
      {
         "Ip": "192.0.2.255",
         "SubnetId": "subnet-ba47exam"
      },
      {
         "Ip": "192.0.2.254",
         "SubnetId": "subnet-12d8exam"
      }
   ],
   "Name": "my-outbound-endpoint",
   "SecurityGroupIds": [ "sg-05cd7b25d6example" ],
   "Tags": [
      {
         "Key": "my-key-name",
         "Value": "my-key-value"
      }
   ]
}
```
詳細については、*Amazon Route 53 デベロッパーガイド*の「[VPC とネットワーク間の DNS クエリの解決](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResolverEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/create-resolver-endpoint.html)」を参照してください。

### `create-resolver-rule`
<a name="route53resolver_CreateResolverRule_cli_2_topic"></a>

次のコード例は、`create-resolver-rule` を使用する方法を示しています。

**AWS CLI**  
**Resolver ルールを作成するには**  
次の `create-resolver-rule` の例では、Resolver 転送ルールを作成します。このルールは、アウトバウンドエンドポイント rslvr-out-d5e5920e37example を使用して、`example.com` の DNS クエリを IP アドレス 10.24.8.75 および 10.24.8.156 に転送します。  

```
aws route53resolver create-resolver-rule \
    --creator-request-id 2020-01-02-18:47 \
    --domain-name example.com \
    --name my-rule \
    --resolver-endpoint-id rslvr-out-d5e5920e37example \
    --rule-type FORWARD \
    --target-ips "Ip=10.24.8.75" "Ip=10.24.8.156"
```
出力:  

```
{
    "ResolverRule": {
        "Status": "COMPLETE",
        "RuleType": "FORWARD",
        "ResolverEndpointId": "rslvr-out-d5e5920e37example",
        "Name": "my-rule",
        "DomainName": "example.com.",
        "CreationTime": "2022-05-10T21:35:30.923187Z",
        "TargetIps": [
            {
                "Ip": "10.24.8.75",
                "Port": 53
            },
            {
                "Ip": "10.24.8.156",
                "Port": 53
            }
        ],
        "CreatorRequestId": "2022-05-10-16:33",
        "ModificationTime": "2022-05-10T21:35:30.923187Z",
        "ShareStatus": "NOT_SHARED",
        "Arn": "arn:aws:route53resolver:us-east-1:111117012054:resolver-rule/rslvr-rr-b1e0b905e93611111",
        "OwnerId": "111111111111",
        "Id": "rslvr-rr-rslvr-rr-b1e0b905e93611111",
        "StatusMessage": "[Trace id: 1-22222222-3e56afcc71a3724664f22e24] Successfully created Resolver Rule."
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResolverRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/create-resolver-rule.html)」を参照してください。

### `delete-firewall-domain-list`
<a name="route53resolver_DeleteFirewallDomainList_cli_2_topic"></a>

次のコード例は、`delete-firewall-domain-list` を使用する方法を示しています。

**AWS CLI**  
**Route 53 Resolver DNS Firewall のドメインリストを削除するには**  
次の の`delete-firewall-domain-list`例では、 AWS アカウントのテストという名前の Route 53 Resolver DNS Firewall ドメインリストを削除します。  

```
aws route53resolver delete-firewall-domain-list \
    --firewall-domain-list-id rslvr-fdl-9e956e9ffexample
```
出力:  

```
{
    "FirewallDomainList": {
        "Id": "rslvr-fdl-9e956e9ffexample",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-domain-list/rslvr-fdl-9e956e9ffexample",
        "Name": "test",
        "DomainCount": 6,
        "Status": "DELETING",
        "StatusMessage": "Deleting the Firewall Domain List",
        "CreatorRequestId": "my-request-id",
        "CreationTime": "2021-05-25T15:55:51.115365Z",
        "ModificationTime": "2021-05-25T18:58:05.588024Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing your own domain lists](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-user-managed-domain-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFirewallDomainList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/delete-firewall-domain-list.html)」を参照してください。

### `delete-firewall-rule-group`
<a name="route53resolver_DeleteFirewallRuleGroup_cli_2_topic"></a>

次のコード例は、`delete-firewall-rule-group` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールグループを削除するには**  
次の `delete-firewall-rule-group` の例では、ファイアウォールルールグループを削除します。  

```
aws route53resolver delete-firewall-rule-group \
    --firewall-rule-group-id rslvr-frg-47f93271fexample
```
出力:  

```
{
    "FirewallRuleGroup": {
        "Id": "rslvr-frg-47f93271fexample",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group/rslvr-frg-47f93271fexample",
        "Name": "test",
        "RuleCount": 0,
        "Status": "UPDATING",
        "StatusMessage": "Updating Firewall Rule Group",
        "OwnerId": "123456789012",
        "CreatorRequestId": "my-request-id",
        "ShareStatus": "NOT_SHARED",
        "CreationTime": "2021-05-25T18:59:26.490017Z",
        "ModificationTime": "2021-05-25T21:51:53.028688Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFirewallRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/delete-firewall-rule-group.html)」を参照してください。

### `delete-firewall-rule`
<a name="route53resolver_DeleteFirewallRule_cli_2_topic"></a>

次のコード例は、`delete-firewall-rule` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールを削除するには**  
次の `delete-firewall-rule` の例は、指定されたファイアウォールルールを削除します。  

```
aws route53resolver delete-firewall-rule \
    --firewall-rule-group-id rslvr-frg-47f93271fexample \
    --firewall-domain-list-id rslvr-fdl-9e956e9ffexample
```
出力:  

```
{
    "FirewallRule": {
        "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
        "FirewallDomainListId": "rslvr-fdl-9e956e9ffexample",
        "Name": "allow-rule",
        "Priority": 102,
        "Action": "ALLOW",
        "CreatorRequestId": "d81e3fb7-020b-415e-939f-EXAMPLE11111",
        "CreationTime": "2021-05-25T21:44:00.346093Z",
        "ModificationTime": "2021-05-25T21:45:59.611600Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFirewallRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/delete-firewall-rule.html)」を参照してください。

### `delete-resolver-endpoint`
<a name="route53resolver_DeleteResolverEndpoint_cli_2_topic"></a>

次のコード例は、`delete-resolver-endpoint` を使用する方法を示しています。

**AWS CLI**  
**Resolver エンドポイントを削除するには**  
次の `delete-resolver-endpoint` の例では、指定されたエンドポイントを削除します。  
**重要** インバウンドエンドポイントを削除すると、そのエンドポイントで指定していた VPC 内の Resolver に対しては、ネットワークからの DNS クエリが転送されなくなります。アウトバウンドエンドポイントを削除すると、Resolver は、削除されたアウトバウンドエンドポイントを指定するルールに基づいた、VPC からネットワークへの DNS クエリの転送を停止します。  

```
aws route53resolver delete-resolver-endpoint \
    --resolver-endpoint-id rslvr-in-497098ad59example
```
出力:  

```
{
    "ResolverEndpoint": {
        "Id": "rslvr-in-497098ad59example",
        "CreatorRequestId": "AWSConsole.25.157290example",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-in-497098ad59example",
        "Name": "my-inbound-endpoint",
        "SecurityGroupIds": [
            "sg-05cd7b25d6example"
        ],
        "Direction": "INBOUND",
        "IpAddressCount": 5,
        "HostVPCId": "vpc-304bexam",
        "Status": "DELETING",
        "StatusMessage": "[Trace id: 1-5dc5b658-811b5be0922bbc382example] Deleting ResolverEndpoint.",
        "CreationTime": "2020-01-01T23:25:45.538Z",
        "ModificationTime": "2020-01-02T23:25:45.538Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResolverEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/delete-resolver-endpoint.html)」を参照してください。

### `delete-resolver-rule`
<a name="route53resolver_DeleteResolverRule_cli_2_topic"></a>

次のコード例は、`delete-resolver-rule` を使用する方法を示しています。

**AWS CLI**  
**Resolver ルールを削除するには**  
次の `delete-resolver-rule` の例では、指定されたルールを削除します。  
**注** ルールが VPC に関連付けられている場合は、ルールを削除する前に、VPC からルールの関連付けを解除する必要があります。  

```
aws route53resolver delete-resolver-rule \
    --resolver-rule-id rslvr-rr-5b3809426bexample
```
出力:  

```
{
    "ResolverRule": {
        "Id": "rslvr-rr-5b3809426bexample",
        "CreatorRequestId": "2020-01-03-18:47",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-rule/rslvr-rr-5b3809426bexample",
        "DomainName": "zenith.example.com.",
        "Status": "DELETING",
        "StatusMessage": "[Trace id: 1-5dc5e05b-602e67b052cb74f05example] Deleting Resolver Rule.",
        "RuleType": "FORWARD",
        "Name": "my-resolver-rule",
        "TargetIps": [
            {
                "Ip": "192.0.2.50",
                "Port": 53
            }
        ],
        "ResolverEndpointId": "rslvr-out-d5e5920e3example",
        "OwnerId": "111122223333",
        "ShareStatus": "NOT_SHARED"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResolverRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/delete-resolver-rule.html)」を参照してください。

### `disassociate-firewall-rule-group`
<a name="route53resolver_DisassociateFirewallRuleGroup_cli_2_topic"></a>

次のコード例は、`disassociate-firewall-rule-group` を使用する方法を示しています。

**AWS CLI**  
**VPC からファイアウォールルールグループの関連付けを解除するには**  
次の `disassociate-firewall-rule-group` の例では、Amazon VPC から DNS Firewall ルールグループの関連付けを解除します。  

```
aws route53resolver disassociate-firewall-rule-group \
    --firewall-rule-group-association-id rslvr-frgassoc-57e8873d7example
```
出力:  

```
{
    "FirewallRuleGroupAssociation": {
        "Id": "rslvr-frgassoc-57e8873d7example",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group-association/rslvr-frgassoc-57e8873d7example",
        "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
        "VpcId": "vpc-31e92222",
        "Name": "test-association",
        "Priority": 103,
        "MutationProtection": "DISABLED",
        "Status": "DELETING",
        "StatusMessage": "Deleting the Firewall Rule Group Association",
        "CreatorRequestId": "2ca1a304-32b3-4f5f-bc4c-EXAMPLE11111",
        "CreationTime": "2021-05-25T21:47:48.755768Z",
        "ModificationTime": "2021-05-25T21:51:02.377887Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing associations between your VPC and Route 53 Resolver DNS Firewall rule groups](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-associating-rule-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateFirewallRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/disassociate-firewall-rule-group.html)」を参照してください。

### `disassociate-resolver-endpoint-ip-address`
<a name="route53resolver_DisassociateResolverEndpointIpAddress_cli_2_topic"></a>

次のコード例は、`disassociate-resolver-endpoint-ip-address` を使用する方法を示しています。

**AWS CLI**  
**Resolver エンドポイントから IP アドレスの関連付けを解除するには**  
次の `disassociate-resolver-endpoint-ip-address` の例では、指定された Resolver インバウンドエンドポイントまたはアウトバウンドエンドポイントから IP アドレスを削除します。  
**注** エンドポイントには少なくとも 2 つの IP アドレスが必要です。エンドポイントに現在 2 つの IP アドレスしかなく、1 つのアドレスを別のアドレスに置き換える場合は、まず [associate-resolver-endpoint-ip-address](https://docs.aws.amazon.com/cli/latest/reference/route53resolver/associate-resolver-endpoint-ip-address.html) を使用して新しい IP アドレスを関連付ける必要があります。その後、元の IP アドレスの 1 つをエンドポイントから関連付け解除できます。  

```
aws route53resolver disassociate-resolver-endpoint-ip-address \
    --resolver-endpoint-id rslvr-in-f9ab8a03f1example \
    --ip-address="SubnetId=subnet-12d8a459,Ip=172.31.40.121"
```
出力:  

```
{
    "ResolverEndpoint": {
        "Id": "rslvr-in-f9ab8a03f1example",
        "CreatorRequestId": "2020-01-01-18:47",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-in-f9ab8a03f1example",
        "Name": "my-inbound-endpoint",
        "SecurityGroupIds": [
            "sg-f62bexam"
        ],
        "Direction": "INBOUND",
        "IpAddressCount": 3,
        "HostVPCId": "vpc-304bexam",
        "Status": "UPDATING",
        "StatusMessage": "Updating the Resolver Endpoint",
        "CreationTime": "2020-01-01T23:02:29.583Z",
        "ModificationTime": "2020-01-05T23:02:29.583Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateResolverEndpointIpAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/disassociate-resolver-endpoint-ip-address.html)」を参照してください。

### `disassociate-resolver-rule`
<a name="route53resolver_DisassociateResolverRule_cli_2_topic"></a>

次のコード例は、`disassociate-resolver-rule` を使用する方法を示しています。

**AWS CLI**  
**Amazon VPC から Resolver ルールの関連付けを解除するには**  
次の `disassociate-resolver-rule` の例では、指定された Resolver ルールと指定された VPC の間の関連付けを削除します。以下の場合は、ルールと VPC の関連付けを解除します。  
この VPC から送信される DNS クエリについては、Resolver が、ルールで指定したドメイン名のクエリを自分のネットワークに転送しないようにします。転送ルールを削除します。ルールが現在 1 つ以上の VPC に関連付けられている場合は、ルールを削除する前に、すべての VPC からルールの関連付けを解除する必要があります。  

```
aws route53resolver disassociate-resolver-rule \
    --resolver-rule-id rslvr-rr-4955cb98ceexample \
    --vpc-id vpc-304bexam
```
出力:  

```
{
    "ResolverRuleAssociation": {
        "Id": "rslvr-rrassoc-322f4e8b9cexample",
        "ResolverRuleId": "rslvr-rr-4955cb98ceexample",
        "Name": "my-resolver-rule-association",
        "VPCId": "vpc-304bexam",
        "Status": "DELETING",
        "StatusMessage": "[Trace id: 1-5dc5ffa2-a26c38004c1f94006example] Deleting Association"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateResolverRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/disassociate-resolver-rule.html)」を参照してください。

### `get-firewall-config`
<a name="route53resolver_GetFirewallConfig_cli_2_topic"></a>

次のコード例は、`get-firewall-config` を使用する方法を示しています。

**AWS CLI**  
**VPC のファイアウォール設定を取得するには**  
次の `get-firewall-config` の例では、指定された VPC の DNS Firewall の動作を取得します。  

```
aws route53resolver get-firewall-config \
    --resource-id vpc-31e92222
```
出力:  

```
{
    "FirewallConfig": {
        "Id": "rslvr-fc-86016850cexample",
        "ResourceId": "vpc-31e9222",
        "OwnerId": "123456789012",
        "FirewallFailOpen": "DISABLED"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[DNS Firewall VPC configuration](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFirewallConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-firewall-config.html)」を参照してください。

### `get-firewall-domain-list`
<a name="route53resolver_GetFirewallDomainList_cli_2_topic"></a>

次のコード例は、`get-firewall-domain-list` を使用する方法を示しています。

**AWS CLI**  
**Route 53 Resolver DNS Firewall のドメインリストを取得するには**  
次の `get-firewall-domain-list` の例では、指定した ID を持つドメインリストを取得します。  

```
aws route53resolver get-firewall-domain-list \
    --firewall-domain-list-id rslvr-fdl-42b60677cexample
```
出力:  

```
{
    "FirewallDomainList": {
        "Id": "rslvr-fdl-9e956e9ffexample",
        "Arn": "arn:aws:route53resolver:us-west-2:123457689012:firewall-domain-list/rslvr-fdl-42b60677cexample",
        "Name": "test",
        "DomainCount": 0,
        "Status": "COMPLETE",
        "StatusMessage": "Created Firewall Domain List",
        "CreatorRequestId": "my-request-id",
        "CreationTime": "2021-05-25T15:55:51.115365Z",
        "ModificationTime": "2021-05-25T15:55:51.115365Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing your own domain lists](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-user-managed-domain-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFirewallDomainList](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-firewall-domain-list.html)」を参照してください。

### `get-firewall-rule-group-association`
<a name="route53resolver_GetFirewallRuleGroupAssociation_cli_2_topic"></a>

次のコード例は、`get-firewall-rule-group-association` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールグループの関連付けを取得するには**  
次の `get-firewall-rule-group-association` の例では、ファイアウォールルールグループの関連付けを取得します。  

```
aws route53resolver get-firewall-rule-group-association \
    --firewall-rule-group-association-id rslvr-frgassoc-57e8873d7example
```
出力:  

```
{
    "FirewallRuleGroupAssociation": {
        "Id": "rslvr-frgassoc-57e8873d7example",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group-association/rslvr-frgassoc-57e8873d7example",
        "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
        "VpcId": "vpc-31e92222",
        "Name": "test-association",
        "Priority": 101,
        "MutationProtection": "DISABLED",
        "Status": "COMPLETE",
        "StatusMessage": "Finished rule group association update",
        "CreatorRequestId": "2ca1a304-32b3-4f5f-bc4c-EXAMPLE11111",
        "CreationTime": "2021-05-25T21:47:48.755768Z",
        "ModificationTime": "2021-05-25T21:47:48.755768Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing associations between your VPC and Route 53 Resolver DNS Firewall rule groups](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-associating-rule-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFirewallRuleGroupAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-firewall-rule-group-association.html)」を参照してください。

### `get-firewall-rule-group-policy`
<a name="route53resolver_GetFirewallRuleGroupPolicy_cli_2_topic"></a>

次の例は、`get-firewall-rule-group-policy` を使用する方法を説明しています。

**AWS CLI**  
**IAM AWS ポリシーを取得するには**  
次の の`get-firewall-rule-group-policy`例では、指定されたルールグループを共有するための AWS Identity and Access Management (AWS IAM) ポリシーを取得します。  

```
aws route53resolver get-firewall-rule-group-policy \
    --arn arn:aws:route53resolver:us-west-2:AWS_ACCOUNT_ID:firewall-rule-group/rslvr-frg-47f93271fexample
```
出力:  

```
{
    "FirewallRuleGroupPolicy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"test\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::AWS_ACCOUNT_ID:root\"},\"Action\":[\"route53resolver:GetFirewallRuleGroup\",\"route53resolver:ListFirewallRuleGroups\"],\"Resource\":\"arn:aws:route53resolver:us-east-1:AWS_ACCOUNT_ID:firewall-rule-group/rslvr-frg-47f93271fexample\"}]}"
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFirewallRuleGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-firewall-rule-group-policy.html)」を参照してください。

### `get-firewall-rule-group`
<a name="route53resolver_GetFirewallRuleGroup_cli_2_topic"></a>

次のコード例は、`get-firewall-rule-group` を使用する方法を示しています。

**AWS CLI**  
**Firewall ルールグループを取得するには**  
次の `get-firewall-rule-group` の例では、指定した ID を持つ DNS Firewall ルールグループに関する情報を取得します。  

```
aws route53resolver get-firewall-rule-group \
    --firewall-rule-group-id rslvr-frg-47f93271fexample
```
出力:  

```
{
    "FirewallRuleGroup": {
        "Id": "rslvr-frg-47f93271fexample",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group/rslvr-frg-47f93271fexample",
        "Name": "test",
        "RuleCount": 0,
        "Status": "COMPLETE",
        "StatusMessage": "Created Firewall Rule Group",
        "OwnerId": "123456789012",
        "CreatorRequestId": "my-request-id",
        "ShareStatus": "NOT_SHARED",
        "CreationTime": "2021-05-25T18:59:26.490017Z",
        "ModificationTime": "2021-05-25T18:59:26.490017Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFirewallRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-firewall-rule-group.html)」を参照してください。

### `get-resolver-endpoint`
<a name="route53resolver_GetResolverEndpoint_cli_2_topic"></a>

次のコード例は、`get-resolver-endpoint` を使用する方法を示しています。

**AWS CLI**  
**Resolver エンドポイントに関する情報を取得するには**  
次の `get-resolver-endpoint` の例では、指定されたアウトバウンドエンドポイントの詳細情報を表示します。該当するエンドポイント ID を指定することで、インバウンドエンドポイントとアウトバウンドエンドポイントの両方に `get-resolver-endpoint` を使用できます。  

```
aws route53resolver get-resolver-endpoint \
    --resolver-endpoint-id rslvr-out-d5e5920e37example
```
出力:  

```
{
    "ResolverEndpoint": {
        "Id": "rslvr-out-d5e5920e37example",
        "CreatorRequestId": "2020-01-01-18:47",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-out-d5e5920e37example",
        "Name": "my-outbound-endpoint",
        "SecurityGroupIds": [
            "sg-05cd7b25d6example"
        ],
        "Direction": "OUTBOUND",
        "IpAddressCount": 2,
        "HostVPCId": "vpc-304bexam",
        "Status": "OPERATIONAL",
        "StatusMessage": "This Resolver Endpoint is operational.",
        "CreationTime": "2020-01-01T23:50:50.979Z",
        "ModificationTime": "2020-01-02T23:50:50.979Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[インバウンドエンドポイントを作成または編集するときに指定する値](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-inbound-queries.html#resolver-forwarding-inbound-queries-values)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResolverEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-resolver-endpoint.html)」を参照してください。

### `get-resolver-rule-association`
<a name="route53resolver_GetResolverRuleAssociation_cli_2_topic"></a>

次のコード例は、`get-resolver-rule-association` を使用する方法を示しています。

**AWS CLI**  
**Resolver ルールと VPC の間の関連付けに関する情報を取得するには**  
次の `get-resolver-rule-association` の例では、指定された Resolver ルールと VPC の関連付けに関する詳細情報を表示します。[associate-resolver-rule](https://docs.aws.amazon.com/cli/latest/reference/route53resolver/associate-resolver-rule.html) を使用して、リゾルバールールと VPC を関連付けます。  

```
aws route53resolver get-resolver-rule-association \
    --resolver-rule-association-id rslvr-rrassoc-d61cbb2c8bexample
```
出力:  

```
{
    "ResolverRuleAssociation": {
        "Id": "rslvr-rrassoc-d61cbb2c8bexample",
        "ResolverRuleId": "rslvr-rr-42b60677c0example",
        "Name": "my-resolver-rule-association",
        "VPCId": "vpc-304bexam",
        "Status": "COMPLETE",
        "StatusMessage": ""
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResolverRuleAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-resolver-rule-association.html)」を参照してください。

### `get-resolver-rule`
<a name="route53resolver_GetResolverRule_cli_2_topic"></a>

次のコード例は、`get-resolver-rule` を使用する方法を示しています。

**AWS CLI**  
**Resolver ルールに関する情報を取得する**  
次の `get-resolver-rule` の例では、ルールが DNS クエリを転送するドメイン名や、ルールが関連付けられているアウトバウンドリゾルバーエンドポイントの ID など、指定された Resolver ルールの詳細情報を表示します。  

```
aws route53resolver get-resolver-rule \
    --resolver-rule-id rslvr-rr-42b60677c0example
```
出力:  

```
{
    "ResolverRule": {
        "Id": "rslvr-rr-42b60677c0example",
        "CreatorRequestId": "2020-01-01-18:47",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-rule/rslvr-rr-42b60677c0example",
        "DomainName": "example.com.",
        "Status": "COMPLETE",
        "StatusMessage": "[Trace id: 1-5dc4b177-ff1d9d001a0f80005example] Successfully created Resolver Rule.",
        "RuleType": "FORWARD",
        "Name": "my-rule",
        "TargetIps": [
            {
                "Ip": "192.0.2.45",
                "Port": 53
            }
        ],
        "ResolverEndpointId": "rslvr-out-d5e5920e37example",
        "OwnerId": "111122223333",
        "ShareStatus": "NOT_SHARED"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[ルールを作成または編集するときに指定する値](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-outbound-queries.html#resolver-forwarding-outbound-queries-rule-values)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResolverRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/get-resolver-rule.html)」を参照してください。

### `import-firewall-domains`
<a name="route53resolver_ImportFirewallDomains_cli_2_topic"></a>

次のコード例は、`import-firewall-domains` を使用する方法を示しています。

**AWS CLI**  
**ドメインをドメインリストにインポートするには**  
次の `import-firewall-domains` の例では、一連のドメインをファイルから指定した DNS Firewall ドメインリストにインポートします。  

```
aws route53resolver import-firewall-domains \
    --firewall-domain-list-id rslvr-fdl-d61cbb2cbexample \
    --operation REPLACE \
    --domain-file-url s3://PATH/TO/YOUR/FILE
```
出力:  

```
{
    "Id": "rslvr-fdl-d61cbb2cbexample",
    "Name": "test",
    "Status": "IMPORTING",
    "StatusMessage": "Importing domains from provided file."
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing your own domain lists](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-user-managed-domain-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportFirewallDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/import-firewall-domains.html)」を参照してください。

### `list-firewall-configs`
<a name="route53resolver_ListFirewallConfigs_cli_2_topic"></a>

次のコード例は、`list-firewall-configs` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォール設定を一覧表示するには**  
次の `list-firewall-configs` の例では、DNS Firewall 設定を一覧表示します。  

```
aws route53resolver list-firewall-configs
```
出力:  

```
{
    "FirewallConfigs": [
        {
            "Id": "rslvr-fc-86016850cexample",
            "ResourceId": "vpc-31e92222",
            "OwnerId": "123456789012",
            "FirewallFailOpen": "DISABLED"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[DNS Firewall VPC configuration](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFirewallConfigs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-firewall-configs.html)」を参照してください。

### `list-firewall-domain-lists`
<a name="route53resolver_ListFirewallDomainLists_cli_2_topic"></a>

次のコード例は、`list-firewall-domain-lists` を使用する方法を示しています。

**AWS CLI**  
**Route 53 Resolver DNS Firewall のドメインリストを一覧表示するには**  
次の `list-firewall-domain-lists` の例では、すべてのドメインリストを一覧表示します。  

```
aws route53resolver list-firewall-domain-lists
```
出力:  

```
{
    "FirewallDomainLists": [
        {
            "Id": "rslvr-fdl-2c46f2ecfexample",
            "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-domain-list/rslvr-fdl-2c46f2ecfexample",
            "Name": "AWSManagedDomainsMalwareDomainList",
            "CreatorRequestId": "AWSManagedDomainsMalwareDomainList",
            "ManagedOwnerName": "Route 53 Resolver DNS Firewall"
        },
        {
            "Id": "rslvr-fdl-aa970e9e1example",
            "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-domain-list/rslvr-fdl-aa970e9e1example",
            "Name": "AWSManagedDomainsBotnetCommandandControl",
            "CreatorRequestId": "AWSManagedDomainsBotnetCommandandControl",
            "ManagedOwnerName": "Route 53 Resolver DNS Firewall"
        },
        {
            "Id": "rslvr-fdl-42b60677cexample",
            "Arn": "arn:aws:route53resolver:us-west-2:123456789111:firewall-domain-list/rslvr-fdl-42b60677cexample",
            "Name": "test",
            "CreatorRequestId": "my-request-id"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Route 53 Resolver DNS Firewall domain lists](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-domain-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFirewallDomainLists](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-firewall-domain-lists.html)」を参照してください。

### `list-firewall-domains`
<a name="route53resolver_ListFirewallDomains_cli_2_topic"></a>

次のコード例は、`list-firewall-domains` を使用する方法を示しています。

**AWS CLI**  
**ドメインリスト内のドメインを一覧表示するには**  
次の `list-firewall-domains` の例では、指定した DNS Firewall ドメインリスト内のドメインを一覧表示します。  

```
aws route53resolver list-firewall-domains \
    --firewall-domain-list-id rslvr-fdl-d61cbb2cbexample
```
出力:  

```
{
    "Domains": [
        "test1.com.",
        "test2.com.",
        "test3.com."
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing your own domain lists](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-user-managed-domain-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFirewallDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-firewall-domains.html)」を参照してください。

### `list-firewall-rule-group-associations`
<a name="route53resolver_ListFirewallRuleGroupAssociations_cli_2_topic"></a>

次のコード例は、`list-firewall-rule-group-associations` を使用する方法を示しています。

**AWS CLI**  
**DNS Firewall ルールグループの関連付けを一覧表示するには**  
次の `list-firewall-rule-group-associations` の例では、DNS Firewall ルールグループと Amazon VPC との関連付けを一覧表示します。  

```
aws route53resolver list-firewall-rule-group-associations
```
出力:  

```
{
    "FirewallRuleGroupAssociations": [
        {
            "Id": "rslvr-frgassoc-57e8873d7example",
            "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group-association/rslvr-frgassoc-57e8873d7example",
            "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
            "VpcId": "vpc-31e92222",
            "Name": "test-association",
            "Priority": 101,
            "MutationProtection": "DISABLED",
            "Status": "UPDATING",
            "StatusMessage": "Creating Firewall Rule Group Association",
            "CreatorRequestId": "2ca1a304-32b3-4f5f-bc4c-EXAMPLE11111",
            "CreationTime": "2021-05-25T21:47:48.755768Z",
            "ModificationTime": "2021-05-25T21:47:48.755768Z"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing associations between your VPC and Route 53 Resolver DNS Firewall rule group](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-associating-rule-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFirewallRuleGroupAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-firewall-rule-group-associations.html)」を参照してください。

### `list-firewall-rule-groups`
<a name="route53resolver_ListFirewallRuleGroups_cli_2_topic"></a>

次のコード例は、`list-firewall-rule-groups` を使用する方法を示しています。

**AWS CLI**  
**Firewall ルールグループのリストを取得するには**  
次の `list-firewall-rule-groups` の例では、DNS Firewall ルールグループを一覧表示します。  

```
aws route53resolver list-firewall-rule-groups
```
出力:  

```
{
    "FirewallRuleGroups": [
        {
            "Id": "rslvr-frg-47f93271fexample",
            "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group/rslvr-frg-47f93271fexample",
            "Name": "test",
            "OwnerId": "123456789012",
            "CreatorRequestId": "my-request-id",
            "ShareStatus": "NOT_SHARED"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFirewallRuleGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-firewall-rule-groups.html)」を参照してください。

### `list-firewall-rules`
<a name="route53resolver_ListFirewallRules_cli_2_topic"></a>

次のコード例は、`list-firewall-rules` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールを一覧表示するには**  
次の `list-firewall-rules` の例では、ファイアウォールルールグループ内のすべての DNS Firewall ルールを一覧表示します。  

```
aws route53resolver list-firewall-rules \
    --firewall-rule-group-id rslvr-frg-47f93271fexample
```
出力:  

```
{
    "FirewallRules": [
        {
            "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
            "FirewallDomainListId": "rslvr-fdl-9e956e9ffexample",
            "Name": "allow-rule",
            "Priority": 101,
            "Action": "ALLOW",
            "CreatorRequestId": "d81e3fb7-020b-415e-939f-EXAMPLE11111",
            "CreationTime": "2021-05-25T21:44:00.346093Z",
            "ModificationTime": "2021-05-25T21:44:00.346093Z"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFirewallRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-firewall-rules.html)」を参照してください。

### `list-resolver-endpoint-ip-addresses`
<a name="route53resolver_ListResolverEndpointIpAddresses_cli_2_topic"></a>

次のコード例は、`list-resolver-endpoint-ip-addresses` を使用する方法を示しています。

**AWS CLI**  
**指定されたインバウンドエンドポイントまたはアウトバウンドエンドポイントの IP アドレスを一覧表示するには**  
次の `list-resolver-endpoint-ip-addresses` の例は、インバウンドエンドポイント `rslvr-in-f9ab8a03f1example` と関連付けられている IP アドレスに関する情報を一覧表示します。該当するエンドポイント ID を指定することで、アウトバウンドエンドポイントに `list-resolver-endpoint-ip-addresses` を使用することもできます。  

```
aws route53resolver list-resolver-endpoint-ip-addresses \
    --resolver-endpoint-id rslvr-in-f9ab8a03f1example
```
出力:  

```
{
    "MaxResults": 10,
    "IpAddresses": [
        {
            "IpId": "rni-1de60cdbfeexample",
            "SubnetId": "subnet-ba47exam",
            "Ip": "192.0.2.44",
            "Status": "ATTACHED",
            "StatusMessage": "This IP address is operational.",
            "CreationTime": "2020-01-03T23:02:29.587Z",
            "ModificationTime": "2020-01-03T23:03:05.555Z"
        },
        {
            "IpId": "rni-aac7085e38example",
            "SubnetId": "subnet-12d8exam",
            "Ip": "192.0.2.45",
            "Status": "ATTACHED",
            "StatusMessage": "This IP address is operational.",
            "CreationTime": "2020-01-03T23:02:29.593Z",
            "ModificationTime": "2020-01-03T23:02:55.060Z"
        }
    ]
}
```
出力の値の詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Values That You Specify When You Create or Edit Inbound Endpoints](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-inbound-queries.html#resolver-forwarding-inbound-queries-values)」と「[Values That You Specify When You Create or Edit Outbound Endpoints](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-outbound-queries.html#resolver-forwarding-outbound-queries-endpoint-values)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResolverEndpointIpAddresses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-resolver-endpoint-ip-addresses.html)」を参照してください。

### `list-resolver-endpoints`
<a name="route53resolver_ListResolverEndpoints_cli_2_topic"></a>

次の例は、`list-resolver-endpoints` を使用する方法を説明しています。

**AWS CLI**  
** AWS リージョンのリゾルバーエンドポイントを一覧表示するには**  
次の `list-resolver-endpoints` の例では、現在のアカウントに存在するインバウンドおよびアウトバウンドの Resolver エンドポイントを一覧表示します。  

```
aws route53resolver list-resolver-endpoints
```
出力:  

```
{
    "MaxResults": 10,
    "ResolverEndpoints": [
        {
            "Id": "rslvr-in-497098ad59example",
            "CreatorRequestId": "2020-01-01-18:47",
            "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-in-497098ad59example",
            "Name": "my-inbound-endpoint",
            "SecurityGroupIds": [
                "sg-05cd7b25d6example"
            ],
            "Direction": "INBOUND",
            "IpAddressCount": 2,
            "HostVPCId": "vpc-304bexam",
            "Status": "OPERATIONAL",
            "StatusMessage": "This Resolver Endpoint is operational.",
            "CreationTime": "2020-01-01T23:25:45.538Z",
            "ModificationTime": "2020-01-01T23:25:45.538Z"
        },
        {
            "Id": "rslvr-out-d5e5920e37example",
            "CreatorRequestId": "2020-01-01-18:48",
            "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-out-d5e5920e37example",
            "Name": "my-outbound-endpoint",
            "SecurityGroupIds": [
                "sg-05cd7b25d6example"
            ],
            "Direction": "OUTBOUND",
            "IpAddressCount": 2,
            "HostVPCId": "vpc-304bexam",
            "Status": "OPERATIONAL",
            "StatusMessage": "This Resolver Endpoint is operational.",
            "CreationTime": "2020-01-01T23:50:50.979Z",
            "ModificationTime": "2020-01-01T23:50:50.979Z"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResolverEndpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-resolver-endpoints.html)」を参照してください。

### `list-resolver-rule-associations`
<a name="route53resolver_ListResolverRuleAssociations_cli_2_topic"></a>

次のコード例は、`list-resolver-rule-associations` を使用する方法を示しています。

**AWS CLI**  
**Resolver ルールと VPC の間の関連付けを一覧表示するには**  
次の の`list-resolver-rule-associations`例では、現在の AWS アカウントのリゾルバールールと VPCs間の関連付けを一覧表示します。  

```
aws route53resolver list-resolver-rule-associations
```
出力:  

```
{
    "MaxResults": 30,
    "ResolverRuleAssociations": [
        {
            "Id": "rslvr-autodefined-assoc-vpc-304bexam-internet-resolver",
            "ResolverRuleId": "rslvr-autodefined-rr-internet-resolver",
            "Name": "System Rule Association",
            "VPCId": "vpc-304bexam",
            "Status": "COMPLETE",
            "StatusMessage": ""
        },
        {
            "Id": "rslvr-rrassoc-d61cbb2c8bexample",
            "ResolverRuleId": "rslvr-rr-42b60677c0example",
            "Name": "my-resolver-rule-association",
            "VPCId": "vpc-304bexam",
            "Status": "COMPLETE",
            "StatusMessage": ""
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Route 53 Resolver で VPC からネットワークに DNS クエリを転送する方法](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver.html#resolver-overview-forward-vpc-to-network)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResolverRuleAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-resolver-rule-associations.html)」を参照してください。

### `list-resolver-rules`
<a name="route53resolver_ListResolverRules_cli_2_topic"></a>

次のコード例は、`list-resolver-rules` を使用する方法を示しています。

**AWS CLI**  
**Resolver ルールを一覧表示するには**  
次の の`list-resolver-rules`例では、現在の AWS アカウントのすべてのリゾルバールールを一覧表示します。  

```
aws route53resolver list-resolver-rules
```
出力:  

```
{
    "MaxResults": 30,
    "ResolverRules": [
        {
            "Id": "rslvr-autodefined-rr-internet-resolver",
            "CreatorRequestId": "",
            "Arn": "arn:aws:route53resolver:us-west-2::autodefined-rule/rslvr-autodefined-rr-internet-resolver",
            "DomainName": ".",
            "Status": "COMPLETE",
            "RuleType": "RECURSIVE",
            "Name": "Internet Resolver",
            "OwnerId": "Route 53 Resolver",
            "ShareStatus": "NOT_SHARED"
        },
        {
            "Id": "rslvr-rr-42b60677c0example",
            "CreatorRequestId": "2020-01-01-18:47",
            "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-rule/rslvr-rr-42b60677c0bc4e299",
            "DomainName": "example.com.",
            "Status": "COMPLETE",
            "StatusMessage": "[Trace id: 1-5dc4b177-ff1d9d001a0f80005example] Successfully created Resolver Rule.",
            "RuleType": "FORWARD",
            "Name": "my-rule",
            "TargetIps": [
                {
                    "Ip": "192.0.2.45",
                    "Port": 53
                }
            ],
            "ResolverEndpointId": "rslvr-out-d5e5920e37example",
            "OwnerId": "111122223333",
            "ShareStatus": "NOT_SHARED"
        }
    ]
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Route 53 Resolver で VPC からネットワークに DNS クエリを転送する方法](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver.html#resolver-overview-forward-vpc-to-network)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResolverRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-resolver-rules.html)」を参照してください。

### `list-tags-for-resource`
<a name="route53resolver_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**Resolver リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された Resolver ルールに割り当てられたタグを一覧表示します。  

```
aws route53resolver list-tags-for-resource \
    --resource-arn "arn:aws:route53resolver:us-west-2:111122223333:resolver-rule/rslvr-rr-42b60677c0example"
```
出力:  

```
{
    "Tags": [
        {
            "Key": "my-key-1",
            "Value": "my-value-1"
        },
        {
            "Key": "my-key-2",
            "Value": "my-value-2"
        }
    ]
}
```
コスト配分でのタグの使用の詳細については、「*AWS Billing and Cost Management ユーザーガイド*」の「[コスト配分タグの使用](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/list-tags-for-resource.html)」を参照してください。

### `put-firewall-rule-group-policy`
<a name="route53resolver_PutFirewallRuleGroupPolicy_cli_2_topic"></a>

次の例は、`put-firewall-rule-group-policy` を使用する方法を説明しています。

**AWS CLI**  
**Firewall AWS ルールグループポリシーを共有する IAM ポリシーをアタッチするには**  
次の`put-firewall-rule-group-policy`例では、ルールグループを共有するための AWS Identity and Access Management (AWS IAM) ポリシーをアタッチします。  

```
aws route53resolver put-firewall-rule-group-policy \
    --firewall-rule-group-policy "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"test\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::AWS_ACCOUNT_ID:root\"},\"Action\":[\"route53resolver:GetFirewallRuleGroup\",\"route53resolver:ListFirewallRuleGroups\"],\"Resource\":\"arn:aws:route53resolver:us-east-1:AWS_ACCOUNT_ID:firewall-rule-group/rslvr-frg-47f93271fexample\"}]}"
```
出力:  

```
{
    "ReturnValue": true
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutFirewallRuleGroupPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/put-firewall-rule-group-policy.html)」を参照してください。

### `put-resolver-rule-policy`
<a name="route53resolver_PutResolverRulePolicy_cli_2_topic"></a>

次の例は、`put-resolver-rule-policy` を使用する方法を説明しています。

**AWS CLI**  
**Resolver ルールを別の AWS アカウントと共有するには**  
次の`put-resolver-rule-policy`例では、別の AWS アカウントと共有したいリゾルバールール、ルールを共有するアカウント、およびアカウントがルールに対して実行できるようにするルール関連のオペレーションを指定します。  
**注** このコマンドは、ルールを作成したのと同じアカウントの認証情報を使用して実行する必要があります。  

```
aws route53resolver put-resolver-rule-policy \
    --region us-east-1 \
    --arn "arn:aws:route53resolver:us-east-1:111122223333:resolver-rule/rslvr-rr-42b60677c0example" \
    --resolver-rule-policy "{\"Version\": \"2012-10-17\", \
        \"Statement\": [ { \
        \"Effect\" : \"Allow\", \
        \"Principal\" : {\"AWS\" : \"444455556666\" }, \
        \"Action\" : [ \
            \"route53resolver:GetResolverRule\", \
            \"route53resolver:AssociateResolverRule\", \
            \"route53resolver:DisassociateResolverRule\", \
            \"route53resolver:ListResolverRules\", \
            \"route53resolver:ListResolverRuleAssociations\" ], \
        \"Resource\" : [ \"arn:aws:route53resolver:us-east-1:111122223333:resolver-rule/rslvr-rr-42b60677c0example\" ] } ] }"
```
出力:  

```
{
    "ReturnValue": true
}
```
`put-resolver-rule-policy` を実行したら、次の 2 つの Resource Access Manager (RAM) コマンドを実行できます。ルールを共有するアカウントを使用する必要があります。  
`get-resource-share-invitations` は 値 `resourceShareInvitationArn` を返します。共有ルールを使用するための招待を受け入れるには、この値が必要です。`accept-resource-share-invitation` は共有ルールを使用するための招待を受け入れます。  
詳細については、次のドキュメントを参照してください。  
*Amazon Route 53 デベロッパーガイド*の[get-resource-share-invitations](https://docs.aws.amazon.com/cli/latest/reference/ram/get-resource-share-invitations.html)[accept-resource-share-invitations](https://docs.aws.amazon.com/cli/latest/reference/ram/accept-resource-share-invitation.html)[転送ルールを他の AWS アカウントと共有し、共有ルールを使用する](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-rules-managing.html#resolver-rules-managing-sharing)」  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutResolverRulePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/put-resolver-rule-policy.html)」を参照してください。

### `tag-resource`
<a name="route53resolver_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**タグを Resolver リソースに関連付けるには**  
次の `tag-resource` の例では、2 つのタグキーと値のペアを指定された Resolver ルールに関連付けます。  

```
aws route53resolver tag-resource \
    --resource-arn "arn:aws:route53resolver:us-west-2:111122223333:resolver-rule/rslvr-rr-42b60677c0example" \
    --tags "Key=my-key-1,Value=my-value-1" "Key=my-key-2,Value=my-value-2"
```
このコマンドでは何も出力されません。  
コスト配分でのタグの使用の詳細については、「*AWS Billing and Cost Management ユーザーガイド*」の「[コスト配分タグの使用](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="route53resolver_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**Resolver リソースからタグを削除するには**  
次の `untag-resource` の例では、指定された Resolver ルールから 2 つのタグを削除します。  

```
aws route53resolver untag-resource \
    --resource-arn "arn:aws:route53resolver:us-west-2:111122223333:resolver-rule/rslvr-rr-42b60677c0example" \
    --tag-keys my-key-1 my-key-2
```
このコマンドでは何も出力されません。タグが削除されたことを確認するには、[list-tags-for-resource ](https://docs.aws.amazon.com/cli/latest/reference/route53resolver/list-tags-for-resource.html)を使用します。  
コスト配分でのタグの使用の詳細については、「*AWS Billing and Cost Management ユーザーガイド*」の「[コスト配分タグの使用](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/untag-resource.html)」を参照してください。

### `update-firewall-config`
<a name="route53resolver_UpdateFirewallConfig_cli_2_topic"></a>

次のコード例は、`update-firewall-config` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォール設定を更新するには**  
次の `update-firewall-config` の例では、DNS Firewall 設定を更新します。  

```
aws route53resolver update-firewall-config \
    --resource-id vpc-31e92222 \
    --firewall-fail-open DISABLED
```
出力:  

```
{
    "FirewallConfig": {
        "Id": "rslvr-fc-86016850cexample",
        "ResourceId": "vpc-31e92222",
        "OwnerId": "123456789012",
        "FirewallFailOpen": "DISABLED"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[DNS Firewall VPC configuration](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFirewallConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/update-firewall-config.html)」を参照してください。

### `update-firewall-domains`
<a name="route53resolver_UpdateFirewallDomains_cli_2_topic"></a>

次のコード例は、`update-firewall-domains` を使用する方法を示しています。

**AWS CLI**  
**ドメインリストを更新するには**  
次の `update-firewall-domains` の例では、指定した ID を使用してドメインをドメインリストに追加します。  

```
aws route53resolver update-firewall-domains \
    --firewall-domain-list-id rslvr-fdl-42b60677cexampleb \
    --operation ADD \
    --domains test1.com test2.com test3.com
```
出力:  

```
{
    "Id": "rslvr-fdl-42b60677cexample",
    "Name": "test",
    "Status": "UPDATING",
    "StatusMessage": "Updating the Firewall Domain List"
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing your own domain lists](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-user-managed-domain-lists.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFirewallDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/update-firewall-domains.html)」を参照してください。

### `update-firewall-rule-group-association`
<a name="route53resolver_UpdateFirewallRuleGroupAssociation_cli_2_topic"></a>

次のコード例は、`update-firewall-rule-group-association` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールグループの関連付けを更新するには**  
次の `update-firewall-rule-group-association` の例では、ファイアウォールルールグループの関連付けを更新します。  

```
aws route53resolver update-firewall-rule-group-association \
    --firewall-rule-group-association-id rslvr-frgassoc-57e8873d7example \
    --priority 103
```
出力:  

```
{
    "FirewallRuleGroupAssociation": {
        "Id": "rslvr-frgassoc-57e8873d7example",
        "Arn": "arn:aws:route53resolver:us-west-2:123456789012:firewall-rule-group-association/rslvr-frgassoc-57e8873d7example",
        "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
        "VpcId": "vpc-31e92222",
        "Name": "test-association",
        "Priority": 103,
        "MutationProtection": "DISABLED",
        "Status": "UPDATING",
        "StatusMessage": "Updating the Firewall Rule Group Association Attributes",
        "CreatorRequestId": "2ca1a304-32b3-4f5f-bc4c-EXAMPLE11111",
        "CreationTime": "2021-05-25T21:47:48.755768Z",
        "ModificationTime": "2021-05-25T21:50:09.272569Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing associations between your VPC and Route 53 Resolver DNS Firewall rule group](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-vpc-associating-rule-group.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFirewallRuleGroupAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/update-firewall-rule-group-association.html)」を参照してください。

### `update-firewall-rule`
<a name="route53resolver_UpdateFirewallRule_cli_2_topic"></a>

次のコード例は、`update-firewall-rule` を使用する方法を示しています。

**AWS CLI**  
**ファイアウォールルールを更新するには**  
次の `update-firewall-rule` の例では、指定したパラメータを使用してファイアウォールルールを更新します。  

```
aws route53resolver update-firewall-rule \
    --firewall-rule-group-id rslvr-frg-47f93271fexample \
    --firewall-domain-list-id rslvr-fdl-9e956e9ffexample \
    --priority 102
```
出力:  

```
{
    "FirewallRule": {
        "FirewallRuleGroupId": "rslvr-frg-47f93271fexample",
        "FirewallDomainListId": "rslvr-fdl-9e956e9ffexample",
        "Name": "allow-rule",
        "Priority": 102,
        "Action": "ALLOW",
        "CreatorRequestId": "d81e3fb7-020b-415e-939f-EXAMPLE11111",
        "CreationTime": "2021-05-25T21:44:00.346093Z",
        "ModificationTime": "2021-05-25T21:45:59.611600Z"
    }
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[Managing rule groups and rules in DNS Firewall](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-dns-firewall-rule-group-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFirewallRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/update-firewall-rule.html)」を参照してください。

### `update-resolver-endpoint`
<a name="route53resolver_UpdateResolverEndpoint_cli_2_topic"></a>

次のコード例は、`update-resolver-endpoint` を使用する方法を示しています。

**AWS CLI**  
**Resolver エンドポイントの名前を更新するには**  
次の `update-resolver-endpoint` の例では、Resolver エンドポイントの名前を更新します。他の値の更新はサポートされていません。  

```
aws route53resolver update-resolver-endpoint \
    --resolver-endpoint-id rslvr-in-b5d45e32bdc445f09 \
    --name my-renamed-inbound-endpoint
```
出力:  

```
{
    "ResolverEndpoint": {
        "Id": "rslvr-in-b5d45e32bdexample",
        "CreatorRequestId": "2020-01-02-18:48",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-endpoint/rslvr-in-b5d45e32bdexample",
        "Name": "my-renamed-inbound-endpoint",
        "SecurityGroupIds": [
            "sg-f62bexam"
        ],
        "Direction": "INBOUND",
        "IpAddressCount": 2,
        "HostVPCId": "vpc-304bexam",
        "Status": "OPERATIONAL",
        "StatusMessage": "This Resolver Endpoint is operational.",
        "CreationTime": "2020-01-01T18:33:59.265Z",
        "ModificationTime": "2020-01-08T18:33:59.265Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResolverEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/update-resolver-endpoint.html)」を参照してください。

### `update-resolver-rule`
<a name="route53resolver_UpdateResolverRule_cli_2_topic"></a>

次のコード例は、`update-resolver-rule` を使用する方法を示しています。

**AWS CLI**  
**例 1: Resolver エンドポイントの設定を更新するには**  
次の `update-resolver-rule` の例では、ルールの名前、DNS クエリの転送先でオンプレミスネットワーク上の IP アドレス、クエリをネットワークに転送するために使用するアウトバウンド Resolver エンドポイントの ID を更新します。  
**注** `TargetIps` の既存の値は上書きされるため、更新後にルールに含めるすべての IP アドレスを指定する必要があります。  

```
aws route53resolver update-resolver-rule \
    --resolver-rule-id rslvr-rr-1247fa64f3example \
    --config Name="my-2nd-rule",TargetIps=[{Ip=192.0.2.45,Port=53},{Ip=192.0.2.46,Port=53}],ResolverEndpointId=rslvr-out-7b89ed0d25example
```
出力:  

```
{
    "ResolverRule": {
        "Id": "rslvr-rr-1247fa64f3example",
        "CreatorRequestId": "2020-01-02-18:47",
        "Arn": "arn:aws:route53resolver:us-west-2:111122223333:resolver-rule/rslvr-rr-1247fa64f3example",
        "DomainName": "www.example.com.",
        "Status": "COMPLETE",
        "StatusMessage": "[Trace id: 1-5dcc90b9-8a8ee860aba1ebd89example] Successfully updated Resolver Rule.",
        "RuleType": "FORWARD",
        "Name": "my-2nd-rule",
        "TargetIps": [
            {
                "Ip": "192.0.2.45",
                "Port": 53
            },
            {
                "Ip": "192.0.2.46",
                "Port": 53
            }
        ],
        "ResolverEndpointId": "rslvr-out-7b89ed0d25example",
        "OwnerId": "111122223333",
        "ShareStatus": "NOT_SHARED"
    }
}
```
**例 2: 「config」設定ファイルを使用して Resolver エンドポイント設定を更新するには**  
または、JSON ファイルに `config` 設定を含め、`update-resolver-rule` を呼び出すときにそのファイルを指定することもできます。  

```
aws route53resolver update-resolver-rule \
    --resolver-rule-id rslvr-rr-1247fa64f3example \
    --config file://c:\temp\update-resolver-rule.json
```
`update-resolver-rule.json` の内容。  

```
{
    "Name": "my-2nd-rule",
    "TargetIps": [
        {
            "Ip": "192.0.2.45",
            "Port": 53
        },
        {
            "Ip": "192.0.2.46",
            "Port": 53
        }
    ],
    "ResolverEndpointId": "rslvr-out-7b89ed0d25example"
}
```
詳細については、「*Amazon Route 53 デベロッパーガイド*」の「[ルールを作成または編集するときに指定する値](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-outbound-queries.html#resolver-forwarding-outbound-queries-rule-values)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResolverRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/route53resolver/update-resolver-rule.html)」を参照してください。

# を使用した Amazon S3 の例 AWS CLI
<a name="cli_2_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `abort-multipart-upload`
<a name="s3_AbortMultipartUpload_cli_2_topic"></a>

次のコード例は、`abort-multipart-upload` を使用する方法を示しています。

**AWS CLI**  
**指定したマルチパートアップロードを中止するには**  
次の `abort-multipart-upload` コマンドは、バケット `amzn-s3-demo-bucket` 内のキー `multipart/01` のマルチパートアップロードを中止します。  

```
aws s3api abort-multipart-upload \
    --bucket amzn-s3-demo-bucket \
    --key multipart/01 \
    --upload-id dfRtDYU0WWCCcH43C3WFbkRONycyCpTJJvxu2i5GYkZljF.Yxwh6XG7WfS2vC4to6HiV6Yjlx.cph0gtNBtJ8P3URCSbB7rjxI5iEwVDmgaXZOGgkk5nVTW16HOQ5l0R
```
このコマンドに必要なアップロード ID `create-multipart-upload` はによって出力され、`list-multipart-uploads` で取得することもできます。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AbortMultipartUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/abort-multipart-upload.html)」を参照してください。

### `complete-multipart-upload`
<a name="s3_CompleteMultipartUpload_cli_2_topic"></a>

次のコード例は、`complete-multipart-upload` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、バケット `amzn-s3-demo-bucket` 内のキー `multipart/01` のマルチパートアップロードを完了します。  

```
aws s3api complete-multipart-upload --multipart-upload file://mpustruct --bucket amzn-s3-demo-bucket --key 'multipart/01' --upload-id dfRtDYU0WWCCcH43C3WFbkRONycyCpTJJvxu2i5GYkZljF.Yxwh6XG7WfS2vC4to6HiV6Yjlx.cph0gtNBtJ8P3URCSbB7rjxI5iEwVDmgaXZOGgkk5nVTW16HOQ5l0R
```
このコマンドに必要なアップロード ID `create-multipart-upload` はによって出力され、`list-multipart-uploads` で取得することもできます。  
上記のコマンドのマルチパートアップロードオプションは、完全なファイルに再構成する必要があるマルチパートアップロードの部分を記述した JSON 構造を採用しています。この例では、`file://` プレフィックスを使用して、`mpustruct` という名前のローカルフォルダーにあるファイルから JSON 構造を読み込みます。  
mpustruct:  

```
{
  "Parts": [
    {
      "ETag": "e868e0f4719e394144ef36531ee6824c",
      "PartNumber": 1
    },
    {
      "ETag": "6bb2b12753d66fe86da4998aa33fffb0",
      "PartNumber": 2
    },
    {
      "ETag": "d0a0112e841abec9c9ec83406f0159c8",
      "PartNumber": 3
    }
  ]
}
```
各パートの ETag 値は、`upload-part` コマンドを使用してパートをアップロードするたびに出力されます。また、`list-parts` を呼び出して取得したり、各パートの MD5 チェックサムを取得して計算したりすることもできます。  
出力:  

```
{
    "ETag": "\"3944a9f7a4faab7f78788ff6210f63f0-3\"",
    "Bucket": "amzn-s3-demo-bucket",
    "Location": "https://amzn-s3-demo-bucket.s3.amazonaws.com/multipart%2F01",
    "Key": "multipart/01"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CompleteMultipartUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/complete-multipart-upload.html)」を参照してください。**

### `copy-object`
<a name="s3_CopyObject_cli_2_topic"></a>

次のコード例は、`copy-object` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`bucket-1` から `bucket-2` にオブジェクトをコピーします。  

```
aws s3api copy-object --copy-source bucket-1/test.txt --key test.txt --bucket bucket-2
```
出力:  

```
{
    "CopyObjectResult": {
        "LastModified": "2015-11-10T01:07:25.000Z",
        "ETag": "\"589c8b79c230a6ecd5a7e1d040a9a030\""
    },
    "VersionId": "YdnYvTCVDqRRFA.NFJjy36p0hxifMlkA"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/copy-object.html)」を参照してください。

### `cp`
<a name="s3_Cp_cli_2_topic"></a>

次のコード例は、`cp` を使用する方法を示しています。

**AWS CLI**  
**例 1: ローカルファイルを S3 にコピーする**  
次の `cp` コマンドは、1 つのファイルを指定されたバケットとキーにコピーします。  

```
aws s3 cp test.txt s3://amzn-s3-demo-bucket/test2.txt
```
出力:  

```
upload: test.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 2: 有効期限のある S3 にローカルファイルをコピーする**  
次の `cp` コマンドは、指定された ISO 8601 タイムスタンプで期限切れになる指定されたバケットとキーに 1 つのファイルをコピーします。  

```
aws s3 cp test.txt s3://amzn-s3-demo-bucket/test2.txt \
    --expires 2014-10-01T20:30:00Z
```
出力:  

```
upload: test.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 3: S3 から S3 にファイルをコピーする**  
次の `cp` コマンドは、単一の S3 オブジェクトを指定されたバケットとキーにコピーします。  

```
aws s3 cp s3://amzn-s3-demo-bucket/test.txt s3://amzn-s3-demo-bucket/test2.txt
```
出力:  

```
copy: s3://amzn-s3-demo-bucket/test.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 4: S3 オブジェクトをローカルファイルにコピーする**  
次の `cp` コマンドは、1 つのオブジェクトを指定されたファイルにローカルにコピーします。  

```
aws s3 cp s3://amzn-s3-demo-bucket/test.txt test2.txt
```
出力:  

```
download: s3://amzn-s3-demo-bucket/test.txt to test2.txt
```
**例 5: バケットから別のバケットに S3 オブジェクトをコピーする**  
次の `cp` コマンドは、元の名前を保持しながら、単一のオブジェクトを指定されたバケットにコピーします。  

```
aws s3 cp s3://amzn-s3-demo-bucket/test.txt s3://amzn-s3-demo-bucket2/
```
出力:  

```
copy: s3://amzn-s3-demo-bucket/test.txt to s3://amzn-s3-demo-bucket2/test.txt
```
**例 6: S3 オブジェクトを再帰的にローカルディレクトリにコピーする**  
パラメータ `--recursive` で渡された場合、次の `cp` コマンドは、指定されたプレフィックスとバケットのすべてのオブジェクトを指定されたディレクトリに再帰的にコピーします。この例では、バケット `amzn-s3-demo-bucket` にはオブジェクト `test1.txt` と `test2.txt` があります。  

```
aws s3 cp s3://amzn-s3-demo-bucket . \
    --recursive
```
出力:  

```
download: s3://amzn-s3-demo-bucket/test1.txt to test1.txt
download: s3://amzn-s3-demo-bucket/test2.txt to test2.txt
```
**例 7: ローカルファイルを S3 に再帰的にコピーする**  
パラメータ `--recursive` で渡された場合、次の `cp` コマンドは、`--exclude`パラメータを使用して一部のファイルを除外しながら、指定されたディレクトリ内のすべてのファイルを指定されたバケットとプレフィックスに再帰的にコピーします。この例では、`myDir` ディレクトリにファイル `test1.txt` と `test2.jpg` があります。  

```
aws s3 cp myDir s3://amzn-s3-demo-bucket/ \
    --recursive \
    --exclude "*.jpg"
```
出力:  

```
upload: myDir/test1.txt to s3://amzn-s3-demo-bucket/test1.txt
```
**例 8: S3 オブジェクトを別のバケットに再帰的にコピーする**  
パラメータ `--recursive` で渡された場合、次の `cp` コマンドは、`--exclude` パラメータを使用して一部のオブジェクトを除外しながら、指定されたバケット内のすべてのオブジェクトを別のバケットに再帰的にコピーします。この例では、バケット `amzn-s3-demo-bucket` にはオブジェクト `test1.txt` と `another/test1.txt` があります。  

```
aws s3 cp s3://amzn-s3-demo-bucket/ s3://amzn-s3-demo-bucket2/ \
    --recursive \
    --exclude "another/*"
```
出力:  

```
copy: s3://amzn-s3-demo-bucket/test1.txt to s3://amzn-s3-demo-bucket2/test1.txt
```
`--exclude` と `--include` のオプションを組み合わせて、パターンに一致するオブジェクトのみをコピーできます。ただし、他のすべてのオブジェクトはコピーできません。  

```
aws s3 cp s3://amzn-s3-demo-bucket/logs/ s3://amzn-s3-demo-bucket2/logs/ \
    --recursive \
    --exclude "*" \
    --include "*.log"
```
出力:  

```
copy: s3://amzn-s3-demo-bucket/logs/test/test.log to s3://amzn-s3-demo-bucket2/logs/test/test.log
copy: s3://amzn-s3-demo-bucket/logs/test3.log to s3://amzn-s3-demo-bucket2/logs/test3.log
```
**例 9: S3 オブジェクトのコピー中にアクセスコントロールリスト (ACL) を設定する**  
次の `cp` コマンドは、ACL を `public-read-write` に設定しながら、単一のオブジェクトを指定されたバケットとキーにコピーします。  

```
aws s3 cp s3://amzn-s3-demo-bucket/test.txt s3://amzn-s3-demo-bucket/test2.txt \
    --acl public-read-write
```
出力:  

```
copy: s3://amzn-s3-demo-bucket/test.txt to s3://amzn-s3-demo-bucket/test2.txt
```
`--acl` オプションを使用している場合は、関連する IAM ポリシーに `"s3:PutObjectAcl"` アクションが含まれていることを確認してください。  

```
aws iam get-user-policy \
    --user-name myuser \
    --policy-name mypolicy
```
出力:  

```
{
    "UserName": "myuser",
    "PolicyName": "mypolicy",
    "PolicyDocument": {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Action": [
                    "s3:PutObject",
                    "s3:PutObjectAcl"
                ],
                "Resource": [
                    "arn:aws:s3:::amzn-s3-demo-bucket/*"
                ],
                "Effect": "Allow",
                "Sid": "Stmt1234567891234"
            }
        ]
    }
}
```
**例 10: S3 オブジェクトにアクセス許可を付与する**  
次の `cp` コマンドは、URI で識別されるすべてのユーザーに読み取りアクセスを付与し、正規 ID で識別される特定のユーザーに完全なコントロールを付与する `--grants` オプションの使用方法を示しています。  

```
aws s3 cp file.txt s3://amzn-s3-demo-bucket/ --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers full=id=79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be
```
出力:  

```
upload: file.txt to s3://amzn-s3-demo-bucket/file.txt
```
**例 11: ローカルファイルストリームを S3 にアップロードする**  
PowerShell は、パイプ入力のエンコーディングを変更したり、パイプ入力に CRLF を追加したりする場合があります。  
次の `cp` コマンドは、ローカルファイルストリームを標準入力から指定されたバケットとキーにアップロードします。  

```
aws s3 cp - s3://amzn-s3-demo-bucket/stream.txt
```
**例 12: 50GB を超えるローカルファイルストリームを S3 にアップロードする**  
次の `cp` コマンドは、51GB のローカルファイルストリームを標準入力から指定されたバケットとキーにアップロードします。`--expected-size` オプションを指定する必要があります。指定しないと、デフォルトのパート制限である 10,000 に達したときにアップロードに失敗する可能性があります。  

```
aws s3 cp - s3://amzn-s3-demo-bucket/stream.txt --expected-size 54760833024
```
**例 13: S3 オブジェクトをローカルファイルストリームとしてダウンロードする**  
PowerShell は、パイプ出力またはリダイレクト出力のエンコーディングを変更したり、CRLF を追加したりすることがあります。  
次の `cp` コマンドは、標準出力へのストリームとして S3 オブジェクトをローカルにダウンロードします。ストリームとしてのダウンロードは現在、`--recursive` パラメータと互換性がありません。  

```
aws s3 cp s3://amzn-s3-demo-bucket/stream.txt -
```
**例 14: S3 アクセスポイントにアップロードする**  
次の `cp` コマンドは、キー (`mykey`) のアクセスポイント (`myaccesspoint`) に単一のファイル (`mydoc.txt`) をアップロードします。  

```
aws s3 cp mydoc.txt s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey
```
出力:  

```
upload: mydoc.txt to s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey
```
**例 15: S3 アクセスポイントからダウンロードする**  
次の `cp` コマンドは、アクセスポイント (`myaccesspoint`) からローカルファイル (`mydoc.txt`) に単一のオブジェクト (`mykey`) をダウンロードします。  

```
aws s3 cp s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey mydoc.txt
```
出力:  

```
download: s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey to mydoc.txt
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Cp](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/cp.html)」を参照してください。

### `create-bucket`
<a name="s3_CreateBucket_cli_2_topic"></a>

次のコード例は、`create-bucket` を使用する方法を示しています。

**AWS CLI**  
**例 1: バケットを作成するには**  
次の `create-bucket` の例は、`amzn-s3-demo-bucket` という名前のバケットを作成します。  

```
aws s3api create-bucket \
    --bucket amzn-s3-demo-bucket \
    --region us-east-1
```
出力:  

```
{
    "Location": "/amzn-s3-demo-bucket"
}
```
詳細については、「*Amazon S3 ユーザーガイド*」の「[バケットの作成](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)」を参照してください。  
**例 2: 所有者の強制を使用してバケットを作成するには**  
次の `create-bucket` の例は、S3 オブジェクトの所有権のバケット所有者の強制設定を使用して、`amzn-s3-demo-bucket` という名前のバケットを作成します。  

```
aws s3api create-bucket \
    --bucket amzn-s3-demo-bucket \
    --region us-east-1 \
    --object-ownership BucketOwnerEnforced
```
出力:  

```
{
    "Location": "/amzn-s3-demo-bucket"
}
```
詳細については、*Amazon S3 ユーザーガイド*の[オブジェクトの所有権のコントロールと ACL の無効化](https://docs.aws.amazon.com/AmazonS3/latest/userguide/about-object-ownership.html)を参照してください。  
**例 3: ``us-east-1`` リージョンの外にバケットを作成するには**  
次の `create-bucket` の例は、`eu-west-1` リージョンに `amzn-s3-demo-bucket` という名前のバケットを作成します。`us-east-1` の外にある目的のリージョンにバケットを作成するには、適切な `LocationConstraint` を指定する必要があります。  

```
aws s3api create-bucket \
    --bucket amzn-s3-demo-bucket \
    --region eu-west-1 \
    --create-bucket-configuration LocationConstraint=eu-west-1
```
出力:  

```
{
    "Location": "http://amzn-s3-demo-bucket.s3.amazonaws.com/"
}
```
詳細については、「*Amazon S3 ユーザーガイド*」の「[バケットの作成](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateBucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/create-bucket.html)」を参照してください。

### `create-multipart-upload`
<a name="s3_CreateMultipartUpload_cli_2_topic"></a>

次のコード例は、`create-multipart-upload` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、キー `multipart/01` を使用して、バケット `amzn-s3-demo-bucket` にマルチパートアップロードを作成します。  

```
aws s3api create-multipart-upload --bucket amzn-s3-demo-bucket --key 'multipart/01'
```
出力:  

```
{
    "Bucket": "amzn-s3-demo-bucket",
    "UploadId": "dfRtDYU0WWCCcH43C3WFbkRONycyCpTJJvxu2i5GYkZljF.Yxwh6XG7WfS2vC4to6HiV6Yjlx.cph0gtNBtJ8P3URCSbB7rjxI5iEwVDmgaXZOGgkk5nVTW16HOQ5l0R",
    "Key": "multipart/01"
}
```
完成したファイルは、`amzn-s3-demo-bucket` バケット内の `multipart` というフォルダで `01` という名前が付けられます。`upload-part` コマンドで使用できるように、アップロード ID、キー、バケット名を保存します。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateMultipartUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/create-multipart-upload.html)」を参照してください。**

### `delete-bucket-analytics-configuration`
<a name="s3_DeleteBucketAnalyticsConfiguration_cli_2_topic"></a>

次のコード例は、`delete-bucket-analytics-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットの分析設定を削除するには**  
次の `delete-bucket-analytics-configuration` の例では、指定されたバケットと ID の分析設定を削除します。  

```
aws s3api delete-bucket-analytics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 1
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketAnalyticsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-analytics-configuration.html)」を参照してください。

### `delete-bucket-cors`
<a name="s3_DeleteBucketCors_cli_2_topic"></a>

次のコード例は、`delete-bucket-cors` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットから Cross-Origin Resource Sharing 設定を削除します。  

```
aws s3api delete-bucket-cors --bucket amzn-s3-demo-bucket
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteBucketCors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-cors.html)」を参照してください。**

### `delete-bucket-encryption`
<a name="s3_DeleteBucketEncryption_cli_2_topic"></a>

次のコード例は、`delete-bucket-encryption` を使用する方法を示しています。

**AWS CLI**  
**バケットのサーバー側の暗号化設定を削除するには**  
次の `delete-bucket-encryption` の例では、指定したバケットのサーバー側の暗号化設定を削除します。  

```
aws s3api delete-bucket-encryption \
    --bucket amzn-s3-demo-bucket
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketEncryption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-encryption.html)」を参照してください。

### `delete-bucket-intelligent-tiering-configuration`
<a name="s3_DeleteBucketIntelligentTieringConfiguration_cli_2_topic"></a>

次のコード例は、`delete-bucket-intelligent-tiering-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットの S3 Intelligent-Tiering 設定を削除するには**  
次の `delete-bucket-intelligent-tiering-configuration` の例では、ExampleConfig という名前の S3 Intelligent-Tiering 設定をバケットから削除します。  

```
aws s3api delete-bucket-intelligent-tiering-configuration \
    --bucket amzn-s3-demo-bucket \
    --id ExampleConfig
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon S3 ユーザーガイド*」の「[S3 Intelligent-Tiering の使用](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-intelligent-tiering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBucketIntelligentTieringConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-intelligent-tiering-configuration.html)」を参照してください。

### `delete-bucket-inventory-configuration`
<a name="s3_DeleteBucketInventoryConfiguration_cli_2_topic"></a>

次のコード例は、`delete-bucket-inventory-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットのインベントリ設定を削除するには**  
次の `delete-bucket-inventory-configuration` の例では、指定したバケットで ID `1` を持つインベントリ設定を削除します。  

```
aws s3api delete-bucket-inventory-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 1
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketInventoryConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-inventory-configuration.html)」を参照してください。

### `delete-bucket-lifecycle`
<a name="s3_DeleteBucketLifecycle_cli_2_topic"></a>

次のコード例は、`delete-bucket-lifecycle` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットからライフサイクル設定を削除します。  

```
aws s3api delete-bucket-lifecycle --bucket amzn-s3-demo-bucket
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteBucketLifecycle](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-lifecycle.html)」を参照してください。**

### `delete-bucket-metrics-configuration`
<a name="s3_DeleteBucketMetricsConfiguration_cli_2_topic"></a>

次のコード例は、`delete-bucket-metrics-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットのメトリクス設定を削除するには**  
次の `delete-bucket-metrics-configuration` の例では、指定したバケットと ID のメトリクス設定を削除します。  

```
aws s3api delete-bucket-metrics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 123
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketMetricsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-metrics-configuration.html)」を参照してください。

### `delete-bucket-ownership-controls`
<a name="s3_DeleteBucketOwnershipControls_cli_2_topic"></a>

次のコード例は、`delete-bucket-ownership-controls` を使用する方法を示しています。

**AWS CLI**  
**バケットのバケット所有権設定を削除するには**  
次の `delete-bucket-ownership-controls` の例では、バケットのバケット所有権設定を削除します。  

```
aws s3api delete-bucket-ownership-controls \
    --bucket amzn-s3-demo-bucket
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon S3 ユーザーガイド*」の「[既存のバケットでのオブジェクトの所有権の設定](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-ownership-existing-bucket.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBucketOwnershipControls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-ownership-controls.html)」を参照してください。

### `delete-bucket-policy`
<a name="s3_DeleteBucketPolicy_cli_2_topic"></a>

次のコード例は、`delete-bucket-policy` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットからバケットポリシーを削除します。  

```
aws s3api delete-bucket-policy --bucket amzn-s3-demo-bucket
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteBucketPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-policy.html)」を参照してください。**

### `delete-bucket-replication`
<a name="s3_DeleteBucketReplication_cli_2_topic"></a>

次のコード例は、`delete-bucket-replication` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットからレプリケーションの設定を削除します。  

```
aws s3api delete-bucket-replication --bucket amzn-s3-demo-bucket
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-replication.html)」を参照してください。

### `delete-bucket-tagging`
<a name="s3_DeleteBucketTagging_cli_2_topic"></a>

次のコード例は、`delete-bucket-tagging` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットからタグの設定を削除します。  

```
aws s3api delete-bucket-tagging --bucket amzn-s3-demo-bucket
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteBucketTagging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-tagging.html)」を参照してください。

### `delete-bucket-website`
<a name="s3_DeleteBucketWebsite_cli_2_topic"></a>

次のコード例は、`delete-bucket-website` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットからウェブサイト設定を削除します。  

```
aws s3api delete-bucket-website --bucket amzn-s3-demo-bucket
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteBucketWebsite](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket-website.html)」を参照してください。**

### `delete-bucket`
<a name="s3_DeleteBucket_cli_2_topic"></a>

次のコード例は、`delete-bucket` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットを削除します。  

```
aws s3api delete-bucket --bucket amzn-s3-demo-bucket --region us-east-1
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteBucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-bucket.html)」を参照してください。

### `delete-object-tagging`
<a name="s3_DeleteObjectTagging_cli_2_topic"></a>

次のコード例は、`delete-object-tagging` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのタグセットを削除するには**  
次の `delete-object-tagging` の例では、指定したキーを持つタグをオブジェクト `doc1.rtf` から削除します。  

```
aws s3api delete-object-tagging \
    --bucket amzn-s3-demo-bucket \
    --key doc1.rtf
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeleteObjectTagging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-object-tagging.html)」を参照してください。

### `delete-object`
<a name="s3_DeleteObject_cli_2_topic"></a>

次のコード例は、`delete-object` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットから `test.txt` という名前のオブジェクトを削除します。  

```
aws s3api delete-object --bucket amzn-s3-demo-bucket --key test.txt
```
バケットバージョニングが有効になっている場合、出力には削除マーカーのバージョン ID が含まれます。  

```
{
  "VersionId": "9_gKg5vG56F.TTEUdwkxGpJ3tNDlWlGq",
  "DeleteMarker": true
}
```
オブジェクトの削除の詳細については、「Amazon S3 ユーザーガイド」の「オブジェクトの削除」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-object.html)」を参照してください。

### `delete-objects`
<a name="s3_DeleteObjects_cli_2_topic"></a>

次のコード例は、`delete-objects` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットからオブジェクトを削除します。  

```
aws s3api delete-objects --bucket amzn-s3-demo-bucket --delete file://delete.json
```
`delete.json` は、現在のディレクトリにある JSON ドキュメントで、削除するオブジェクトを指定します。  

```
{
  "Objects": [
    {
      "Key": "test1.txt"
    }
  ],
  "Quiet": false
}
```
出力:  

```
{
    "Deleted": [
        {
            "DeleteMarkerVersionId": "mYAT5Mc6F7aeUL8SS7FAAqUPO1koHwzU",
            "Key": "test1.txt",
            "DeleteMarker": true
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteObjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-objects.html)」を参照してください。

### `delete-public-access-block`
<a name="s3_DeletePublicAccessBlock_cli_2_topic"></a>

次のコード例は、`delete-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**バケットのブロックパブリックアクセス設定を削除するには**  
次の `delete-public-access-block` の例では、指定したバケットのブロックパブリックアクセス設定を削除します。  

```
aws s3api delete-public-access-block \
    --bucket amzn-s3-demo-bucket
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeletePublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/delete-public-access-block.html)」を参照してください。

### `get-bucket-accelerate-configuration`
<a name="s3_GetBucketAccelerateConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-accelerate-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットの加速設定を取得するには**  
次の `get-bucket-accelerate-configuration` の例では、指定したバケットの加速設定を取得します。  

```
aws s3api get-bucket-accelerate-configuration \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Status": "Enabled"
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketAccelerateConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-accelerate-configuration.html)」を参照してください。

### `get-bucket-acl`
<a name="s3_GetBucketAcl_cli_2_topic"></a>

次のコード例は、`get-bucket-acl` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのアクセス制御リストを取得します。  

```
aws s3api get-bucket-acl --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Owner": {
        "DisplayName": "my-username",
        "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
    },
    "Grants": [
        {
            "Grantee": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
            },
            "Permission": "FULL_CONTROL"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetBucketAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-acl.html)」を参照してください。**

### `get-bucket-analytics-configuration`
<a name="s3_GetBucketAnalyticsConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-analytics-configuration` を使用する方法を示しています。

**AWS CLI**  
**特定の ID を持つバケットの分析設定を取得するには**  
次の `get-bucket-analytics-configuration` の例では、指定されたバケットと ID の分析設定を表示します。  

```
aws s3api get-bucket-analytics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 1
```
出力:  

```
{
    "AnalyticsConfiguration": {
        "StorageClassAnalysis": {},
        "Id": "1"
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketAnalyticsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-analytics-configuration.html)」を参照してください。

### `get-bucket-cors`
<a name="s3_GetBucketCors_cli_2_topic"></a>

次のコード例は、`get-bucket-cors` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットの Cross-Origin Resource Sharing 設定を取得します。  

```
aws s3api get-bucket-cors --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "CORSRules": [
        {
            "AllowedHeaders": [
                "*"
            ],
            "ExposeHeaders": [
                "x-amz-server-side-encryption"
            ],
            "AllowedMethods": [
                "PUT",
                "POST",
                "DELETE"
            ],
            "MaxAgeSeconds": 3000,
            "AllowedOrigins": [
                "http://www.example.com"
            ]
        },
        {
            "AllowedHeaders": [
                "Authorization"
            ],
            "MaxAgeSeconds": 3000,
            "AllowedMethods": [
                "GET"
            ],
            "AllowedOrigins": [
                "*"
            ]
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetBucketCors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-cors.html)」を参照してください。**

### `get-bucket-encryption`
<a name="s3_GetBucketEncryption_cli_2_topic"></a>

次のコード例は、`get-bucket-encryption` を使用する方法を示しています。

**AWS CLI**  
**バケットのサーバー側の暗号化設定を取得するには**  
次の `get-bucket-encryption` の例では、バケット `amzn-s3-demo-bucket` のサーバー側の暗号化設定を取得します。  

```
aws s3api get-bucket-encryption \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "ServerSideEncryptionConfiguration": {
        "Rules": [
            {
                "ApplyServerSideEncryptionByDefault": {
                    "SSEAlgorithm": "AES256"
                }
            }
        ]
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketEncryption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-encryption.html)」を参照してください。

### `get-bucket-intelligent-tiering-configuration`
<a name="s3_GetBucketIntelligentTieringConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-intelligent-tiering-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットで S3 Intelligent-Tiering 設定を取得するには**  
次の `get-bucket-intelligent-tiering-configuration` の例では、バケットで ExampleConfig という名前の S3 Intelligent-Tiering 設定を取得します。  

```
aws s3api get-bucket-intelligent-tiering-configuration \
    --bucket amzn-s3-demo-bucket \
    --id ExampleConfig
```
出力:  

```
{
    "IntelligentTieringConfiguration": {
        "Id": "ExampleConfig2",
        "Filter": {
            "Prefix": "images"
        },
        "Status": "Enabled",
        "Tierings": [
            {
                "Days": 90,
                "AccessTier": "ARCHIVE_ACCESS"
            },
            {
                "Days": 180,
                "AccessTier": "DEEP_ARCHIVE_ACCESS"
            }
        ]
    }
}
```
詳細については、「*Amazon S3 ユーザーガイド*」の「[S3 Intelligent-Tiering の使用](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-intelligent-tiering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBucketIntelligentTieringConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-intelligent-tiering-configuration.html)」を参照してください。

### `get-bucket-inventory-configuration`
<a name="s3_GetBucketInventoryConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-inventory-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットのインベントリ設定を取得するには**  
次の `get-bucket-inventory-configuration` の例では、ID `1` を持つ指定したバケットのインベントリ設定を取得します。  

```
aws s3api get-bucket-inventory-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 1
```
出力:  

```
{
    "InventoryConfiguration": {
        "IsEnabled": true,
        "Destination": {
            "S3BucketDestination": {
                "Format": "ORC",
                "Bucket": "arn:aws:s3:::amzn-s3-demo-bucket",
                "AccountId": "123456789012"
            }
        },
        "IncludedObjectVersions": "Current",
        "Id": "1",
        "Schedule": {
            "Frequency": "Weekly"
        }
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketInventoryConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-inventory-configuration.html)」を参照してください。

### `get-bucket-lifecycle-configuration`
<a name="s3_GetBucketLifecycleConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-lifecycle-configuration` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのライフサイクル設定を取得します。  

```
aws s3api get-bucket-lifecycle-configuration --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Rules": [
        {
            "ID": "Move rotated logs to Glacier",
            "Prefix": "rotated/",
            "Status": "Enabled",
            "Transitions": [
                {
                    "Date": "2015-11-10T00:00:00.000Z",
                    "StorageClass": "GLACIER"
                }
            ]
        },
        {
            "Status": "Enabled",
            "Prefix": "",
            "NoncurrentVersionTransitions": [
                {
                    "NoncurrentDays": 0,
                    "StorageClass": "GLACIER"
                }
            ],
            "ID": "Move old versions to Glacier"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetBucketLifecycleConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-lifecycle-configuration.html)」を参照してください。**

### `get-bucket-lifecycle`
<a name="s3_GetBucketLifecycle_cli_2_topic"></a>

次のコード例は、`get-bucket-lifecycle` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのライフサイクル設定を取得します。  

```
aws s3api get-bucket-lifecycle --bucket amzn-s3-demo-bucket
```
出力:  

```
{
  "Rules": [
    {
      "ID": "Move to Glacier after sixty days (objects in logs/2015/)",
      "Prefix": "logs/2015/",
      "Status": "Enabled",
      "Transition": {
        "Days": 60,
        "StorageClass": "GLACIER"
      }
    },
    {
      "Expiration": {
        "Date": "2016-01-01T00:00:00.000Z"
      },
      "ID": "Delete 2014 logs in 2016.",
      "Prefix": "logs/2014/",
      "Status": "Enabled"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBucketLifecycle](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-lifecycle.html)」を参照してください。

### `get-bucket-location`
<a name="s3_GetBucketLocation_cli_2_topic"></a>

次のコード例は、`get-bucket-location` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットの場所の制約を取得します (制約が存在する場合)。  

```
aws s3api get-bucket-location --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "LocationConstraint": "us-west-2"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetBucketLocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-location.html)」を参照してください。**

### `get-bucket-logging`
<a name="s3_GetBucketLogging_cli_2_topic"></a>

次のコード例は、`get-bucket-logging` を使用する方法を示しています。

**AWS CLI**  
**バケットのログ記録ステータスを取得するには**  
次の `get-bucket-logging` の例では、指定したバケットのログ記録ステータスを取得します。  

```
aws s3api get-bucket-logging \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "LoggingEnabled": {
        "TargetPrefix": "",
        "TargetBucket": "amzn-s3-demo-bucket-logs"
          }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-logging.html)」を参照してください。

### `get-bucket-metrics-configuration`
<a name="s3_GetBucketMetricsConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-metrics-configuration` を使用する方法を示しています。

**AWS CLI**  
**特定の ID を持つバケットのメトリクス設定を取得するには**  
次の `get-bucket-metrics-configuration` の例では、指定したバケットと ID のメトリクス設定を表示します。  

```
aws s3api get-bucket-metrics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 123
```
出力:  

```
{
    "MetricsConfiguration": {
        "Filter": {
            "Prefix": "logs"
        },
        "Id": "123"
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketMetricsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-metrics-configuration.html)」を参照してください。

### `get-bucket-notification-configuration`
<a name="s3_GetBucketNotificationConfiguration_cli_2_topic"></a>

次のコード例は、`get-bucket-notification-configuration` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットの通知設定を取得します。  

```
aws s3api get-bucket-notification-configuration --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "TopicConfigurations": [
        {
            "Id": "YmQzMmEwM2EjZWVlI0NGItNzVtZjI1MC00ZjgyLWZDBiZWNl",
            "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-notification-topic",
            "Events": [
                "s3:ObjectCreated:*"
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBucketNotificationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-notification-configuration.html)」を参照してください。

### `get-bucket-notification`
<a name="s3_GetBucketNotification_cli_2_topic"></a>

次のコード例は、`get-bucket-notification` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットの通知設定を取得します。  

```
aws s3api get-bucket-notification --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "TopicConfiguration": {
        "Topic": "arn:aws:sns:us-west-2:123456789012:my-notification-topic",
        "Id": "YmQzMmEwM2EjZWVlI0NGItNzVtZjI1MC00ZjgyLWZDBiZWNl",
        "Event": "s3:ObjectCreated:*",
        "Events": [
            "s3:ObjectCreated:*"
        ]
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-notification.html)」を参照してください。

### `get-bucket-ownership-controls`
<a name="s3_GetBucketOwnershipControls_cli_2_topic"></a>

次のコード例は、`get-bucket-ownership-controls` を使用する方法を示しています。

**AWS CLI**  
**バケットのバケット所有権設定を取得するには**  
次の `get-bucket-ownership-controls` の例では、バケットのバケット所有権設定を取得します。  

```
aws s3api get-bucket-ownership-controls \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "OwnershipControls": {
        "Rules": [
            {
                "ObjectOwnership": "BucketOwnerEnforced"
            }
        ]
    }
}
```
詳細については、「*Amazon S3 ユーザーガイド*」の「[S3 バケットのオブジェクト所有権設定の表示](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-ownership-retrieving.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetBucketOwnershipControls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-ownership-controls.html)」を参照してください。

### `get-bucket-policy-status`
<a name="s3_GetBucketPolicyStatus_cli_2_topic"></a>

次のコード例は、`get-bucket-policy-status` を使用する方法を示しています。

**AWS CLI**  
**バケットがパブリックかどうかを示すバケットのポリシーステータスを取得するには**  
次の `get-bucket-policy-status` の例では、バケット `amzn-s3-demo-bucket` のポリシーステータスを取得します。  

```
aws s3api get-bucket-policy-status \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "PolicyStatus": {
        "IsPublic": false
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketPolicyStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-policy-status.html)」を参照してください。

### `get-bucket-policy`
<a name="s3_GetBucketPolicy_cli_2_topic"></a>

次のコード例は、`get-bucket-policy` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのバケットポリシーを取得します。  

```
aws s3api get-bucket-policy --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Policy": "{\"Version\":\"2008-10-17\",\"Statement\":[{\"Sid\":\"\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::amzn-s3-demo-bucket/*\"},{\"Sid\":\"\",\"Effect\":\"Deny\",\"Principal\":\"*\",\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:::amzn-s3-demo-bucket/secret/*\"}]}"
}
```
次の例は、Amazon S3 バケットポリシーをダウンロードしてファイルを変更し、`put-bucket-policy` を使用して変更したバケットポリシーを適用する方法を示しています。バケットポリシーをファイルにダウンロードするには、以下を実行します。  

```
aws s3api get-bucket-policy --bucket amzn-s3-demo-bucket --query Policy --output text > policy.json
```
その後、必要に応じて `policy.json` ファイルを変更できます。最後に、次のコマンドを実行して、変更したポリシーを S3 バケットに適用することができます。  
必要に応じて `policy.json` ファイル。最後に、次のコマンドを実行して、変更したポリシーを S3 バケットに適用することができます。  
 必要に応じてファイル。最後に、次のコマンドを実行して、変更したポリシーを S3 バケットに適用することができます。  

```
aws s3api put-bucket-policy --bucket amzn-s3-demo-bucket --policy file://policy.json
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetBucketPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-policy.html)」を参照してください。**

### `get-bucket-replication`
<a name="s3_GetBucketReplication_cli_2_topic"></a>

次のコード例は、`get-bucket-replication` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのレプリケーション設定を取得します。  

```
aws s3api get-bucket-replication --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "ReplicationConfiguration": {
        "Rules": [
            {
                "Status": "Enabled",
                "Prefix": "",
                "Destination": {
                    "Bucket": "arn:aws:s3:::amzn-s3-demo-bucket-backup",
                    "StorageClass": "STANDARD"
                },
                "ID": "ZmUwNzE4ZmQ4tMjVhOS00MTlkLOGI4NDkzZTIWJjNTUtYTA1"
            }
        ],
        "Role": "arn:aws:iam::123456789012:role/s3-replication-role"
    }
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-replication.html)」を参照してください。

### `get-bucket-request-payment`
<a name="s3_GetBucketRequestPayment_cli_2_topic"></a>

次のコード例は、`get-bucket-request-payment` を使用する方法を示しています。

**AWS CLI**  
**バケットのリクエストの支払い設定を取得するには**  
次の `get-bucket-request-payment` の例では、指定したバケットのリクエスタ支払いの設定を取得します。  

```
aws s3api get-bucket-request-payment \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Payer": "BucketOwner"
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketRequestPayment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-request-payment.html)」を参照してください。

### `get-bucket-tagging`
<a name="s3_GetBucketTagging_cli_2_topic"></a>

次のコード例は、`get-bucket-tagging` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのタグ付け設定を取得します。  

```
aws s3api get-bucket-tagging --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "TagSet": [
        {
            "Value": "marketing",
            "Key": "organization"
        }
    ]
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketTagging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-tagging.html)」を参照してください。

### `get-bucket-versioning`
<a name="s3_GetBucketVersioning_cli_2_topic"></a>

次のコード例は、`get-bucket-versioning` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのバージョニング設定を取得します。  

```
aws s3api get-bucket-versioning --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Status": "Enabled"
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetBucketVersioning](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-versioning.html)」を参照してください。

### `get-bucket-website`
<a name="s3_GetBucketWebsite_cli_2_topic"></a>

次のコード例は、`get-bucket-website` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットの静的ウェブサイト設定を取得します。  

```
aws s3api get-bucket-website --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "IndexDocument": {
        "Suffix": "index.html"
    },
    "ErrorDocument": {
        "Key": "error.html"
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetBucketWebsite](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-bucket-website.html)」を参照してください。**

### `get-object-acl`
<a name="s3_GetObjectAcl_cli_2_topic"></a>

次のコード例は、`get-object-acl` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケット内のオブジェクトのアクセス制御リストを取得します。  

```
aws s3api get-object-acl --bucket amzn-s3-demo-bucket --key index.html
```
出力:  

```
{
    "Owner": {
        "DisplayName": "my-username",
        "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
    },
    "Grants": [
        {
            "Grantee": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd538e11f6b6606438875e7c86c5b672f46db45460ddcd087d36c32"
            },
            "Permission": "FULL_CONTROL"
        },
        {
            "Grantee": {
                "URI": "http://acs.amazonaws.com/groups/global/AllUsers"
            },
            "Permission": "READ"
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetObjectAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object-acl.html)」を参照してください。**

### `get-object-attributes`
<a name="s3_GetObjectAttributes_cli_2_topic"></a>

次のコード例は、`get-object-attributes` を使用する方法を示しています。

**AWS CLI**  
**オブジェクト自体を返さずにオブジェクトからメタデータを取得するには**  
次の `get-object-attributes` の例は、オブジェクト `doc1.rtf` からメタデータを取得します。  

```
aws s3api get-object-attributes \
    --bucket amzn-s3-demo-bucket \
    --key doc1.rtf \
    --object-attributes "StorageClass" "ETag" "ObjectSize"
```
出力:  

```
{
    "LastModified": "2022-03-15T19:37:31+00:00",
    "VersionId": "IuCPjXTDzHNfldAuitVBIKJpF2p1fg4P",
    "ETag": "b662d79adeb7c8d787ea7eafb9ef6207",
    "StorageClass": "STANDARD",
    "ObjectSize": 405
}
```
詳細については、「Amazon S3 API リファレンス」の [GetObjectAttributes](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjectAttributes.html) を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[GetObjectAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object-attributes.html)」を参照してください。**

### `get-object-legal-hold`
<a name="s3_GetObjectLegalHold_cli_2_topic"></a>

次のコード例は、`get-object-legal-hold` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのリーガルホールドステータスを取得する**  
次の `get-object-legal-hold` の例では、指定したオブジェクトのリーガルホールドステータスを取得します。  

```
aws s3api get-object-legal-hold \
    --bucket amzn-s3-demo-bucket-with-object-lock \
    --key doc1.rtf
```
出力:  

```
{
    "LegalHold": {
        "Status": "ON"
    }
}
```
+  API の詳細については、**AWS CLI コマンドリファレンスの「[GetObjectLegalHold](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object-legal-hold.html)」を参照してください。

### `get-object-lock-configuration`
<a name="s3_GetObjectLockConfiguration_cli_2_topic"></a>

次のコード例は、`get-object-lock-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットのオブジェクトロック設定を取得するには**  
次の `get-object-lock-configuration` 例では、指定されたバケットのオブジェクトロック設定を取得します。  

```
aws s3api get-object-lock-configuration \
    --bucket amzn-s3-demo-bucket-with-object-lock
```
出力:  

```
{
    "ObjectLockConfiguration": {
        "ObjectLockEnabled": "Enabled",
        "Rule": {
            "DefaultRetention": {
                "Mode": "COMPLIANCE",
                "Days": 50
            }
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetObjectLockConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object-lock-configuration.html)」を参照してください。

### `get-object-retention`
<a name="s3_GetObjectRetention_cli_2_topic"></a>

次のコード例は、`get-object-retention` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのオブジェクト保持設定を取得するには**  
次の `get-object-retention` の例では、指定されたオブジェクトの保持設定を取得します。  

```
aws s3api get-object-retention \
    --bucket amzn-s3-demo-bucket-with-object-lock \
    --key doc1.rtf
```
出力:  

```
{
    "Retention": {
        "Mode": "GOVERNANCE",
        "RetainUntilDate": "2025-01-01T00:00:00.000Z"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetObjectRetention](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object-retention.html)」を参照してください。

### `get-object-tagging`
<a name="s3_GetObjectTagging_cli_2_topic"></a>

次のコード例は、`get-object-tagging` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトにアタッチされたタグを取得するには**  
次の `get-object-tagging` 指定したオブジェクトから指定したキーの値を取得します。  

```
aws s3api get-object-tagging \
    --bucket amzn-s3-demo-bucket \
    --key doc1.rtf
```
出力:  

```
{
    "TagSet": [
        {
            "Value": "confidential",
            "Key": "designation"
        }
    ]
}
```
次の `get-object-tagging` の例では、タグのないオブジェクト `doc2.rtf` のタグセットの取得を試行します。  

```
aws s3api get-object-tagging \
    --bucket amzn-s3-demo-bucket \
    --key doc2.rtf
```
出力:  

```
{
    "TagSet": []
}
```
次の `get-object-tagging` の例では、複数のタグがあるオブジェクト `doc3.rtf` のタグセットの取得を試行します。  

```
aws s3api get-object-tagging \
    --bucket amzn-s3-demo-bucket \
    --key doc3.rtf
```
出力:  

```
{
    "TagSet": [
        {
            "Value": "confidential",
            "Key": "designation"
        },
        {
            "Value": "finance",
            "Key": "department"
        },
        {
            "Value": "payroll",
            "Key": "team"
        }
    ]
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[GetObjectTagging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object-tagging.html)」を参照してください。

### `get-object-torrent`
<a name="s3_GetObjectTorrent_cli_2_topic"></a>

次のコード例は、`get-object-torrent` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケット内のオブジェクトのトレントを作成します。  

```
aws s3api get-object-torrent --bucket amzn-s3-demo-bucket --key large-video-file.mp4 large-video-file.torrent
```
トレントファイルは、現在のフォルダにローカルに保存されます。出力ファイル名 (`large-video-file.torrent`) はオプション名なしで指定され、コマンドの最後の引数である必要があります。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetObjectTorrent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object-torrent.html)」を参照してください。

### `get-object`
<a name="s3_GetObject_cli_2_topic"></a>

次のコード例は、`get-object` を使用する方法を示しています。

**AWS CLI**  
次の例は `get-object` コマンドを使用して、Amazon S3 からオブジェクトをダウンロードします。  

```
aws s3api get-object --bucket text-content --key dir/my_images.tar.bz2 my_images.tar.bz2
```
outfile パラメータは、「--outfile」などのオプション名なしで指定されていることに注意してください。出力ファイルの名前はコマンドの最後のパラメータでなければなりません。  
次の例は `--range` を使用して、オブジェクトから特定のバイト範囲をダウンロードする方法を示しています。バイト範囲には「bytes=」というプレフィックスを付ける必要があることに注意してください。  

```
aws s3api get-object --bucket text-content --key dir/my_data --range bytes=8888-9999 my_data_range
```
オブジェクトの取得の詳細については、「Amazon S3 ユーザーガイド」の「オブジェクトを取得する」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-object.html)」を参照してください。

### `get-public-access-block`
<a name="s3_GetPublicAccessBlock_cli_2_topic"></a>

次のコード例は、`get-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**バケットのブロックパブリックアクセス設定を指定または削除するには**  
次の `get-public-access-block` の例では、指定したバケットのブロックパブリックアクセス設定を表示します。  

```
aws s3api get-public-access-block \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "PublicAccessBlockConfiguration": {
        "IgnorePublicAcls": true,
        "BlockPublicPolicy": true,
        "BlockPublicAcls": true,
        "RestrictPublicBuckets": true
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/get-public-access-block.html)」を参照してください。

### `head-bucket`
<a name="s3_HeadBucket_cli_2_topic"></a>

次のコード例は、`head-bucket` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットへのアクセスを確認します。  

```
aws s3api head-bucket --bucket amzn-s3-demo-bucket
```
バケットが存在し、そのバケットにアクセスできる場合、出力は返されません。それ以外の場合は、エラーメッセージが表示されます。例えば、次のようになります。  

```
A client error (404) occurred when calling the HeadBucket operation: Not Found
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[HeadBucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/head-bucket.html)」を参照してください。

### `head-object`
<a name="s3_HeadObject_cli_2_topic"></a>

次のコード例は、`head-object` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケット内のオブジェクトのメタデータを取得します。  

```
aws s3api head-object --bucket amzn-s3-demo-bucket --key index.html
```
出力:  

```
{
    "AcceptRanges": "bytes",
    "ContentType": "text/html",
    "LastModified": "Thu, 16 Apr 2015 18:19:14 GMT",
    "ContentLength": 77,
    "VersionId": "null",
    "ETag": "\"30a6ec7e1a9ad79c203d05a589c8b400\"",
    "Metadata": {}
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[HeadObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/head-object.html)」を参照してください。**

### `list-bucket-analytics-configurations`
<a name="s3_ListBucketAnalyticsConfigurations_cli_2_topic"></a>

次のコード例は、`list-bucket-analytics-configurations` を使用する方法を示しています。

**AWS CLI**  
**バケットの分析設定のリストを取得するには**  
次の `list-bucket-analytics-configurations` の例では、指定したバケットの分析設定のリストを取得します。  

```
aws s3api list-bucket-analytics-configurations \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "AnalyticsConfigurationList": [
        {
            "StorageClassAnalysis": {},
            "Id": "1"
        }
    ],
    "IsTruncated": false
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[ListBucketAnalyticsConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-bucket-analytics-configurations.html)」を参照してください。

### `list-bucket-intelligent-tiering-configurations`
<a name="s3_ListBucketIntelligentTieringConfigurations_cli_2_topic"></a>

次のコード例は、`list-bucket-intelligent-tiering-configurations` を使用する方法を示しています。

**AWS CLI**  
**バケットのすべての S3 Intelligent-Tiering 設定を取得するには**  
次の `list-bucket-intelligent-tiering-configurations` の例では、バケットのすべての S3 Intelligent-Tiering 設定を取得します。  

```
aws s3api list-bucket-intelligent-tiering-configurations \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "IsTruncated": false,
    "IntelligentTieringConfigurationList": [
        {
            "Id": "ExampleConfig",
            "Filter": {
                "Prefix": "images"
            },
            "Status": "Enabled",
            "Tierings": [
                {
                    "Days": 90,
                    "AccessTier": "ARCHIVE_ACCESS"
                },
                {
                    "Days": 180,
                    "AccessTier": "DEEP_ARCHIVE_ACCESS"
                }
            ]
        },
        {
            "Id": "ExampleConfig2",
            "Status": "Disabled",
            "Tierings": [
                {
                    "Days": 730,
                    "AccessTier": "ARCHIVE_ACCESS"
                }
            ]
        },
        {
            "Id": "ExampleConfig3",
            "Filter": {
                "Tag": {
                    "Key": "documents",
                    "Value": "taxes"
                }
            },
            "Status": "Enabled",
            "Tierings": [
                {
                    "Days": 90,
                    "AccessTier": "ARCHIVE_ACCESS"
                },
                {
                    "Days": 365,
                    "AccessTier": "DEEP_ARCHIVE_ACCESS"
                }
            ]
        }
    ]
}
```
詳細については、「*Amazon S3 ユーザーガイド*」の「[S3 Intelligent-Tiering の使用](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-intelligent-tiering.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBucketIntelligentTieringConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-bucket-intelligent-tiering-configurations.html)」を参照してください。

### `list-bucket-inventory-configurations`
<a name="s3_ListBucketInventoryConfigurations_cli_2_topic"></a>

次のコード例は、`list-bucket-inventory-configurations` を使用する方法を示しています。

**AWS CLI**  
**バケットのインベントリ設定のリストを取得するには**  
次の `list-bucket-inventory-configurations` の例では、指定したバケットのインベントリ設定をリスト表示します。  

```
aws s3api list-bucket-inventory-configurations \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "InventoryConfigurationList": [
        {
            "IsEnabled": true,
            "Destination": {
                "S3BucketDestination": {
                    "Format": "ORC",
                    "Bucket": "arn:aws:s3:::amzn-s3-demo-bucket",
                    "AccountId": "123456789012"
                }
            },
            "IncludedObjectVersions": "Current",
            "Id": "1",
            "Schedule": {
                "Frequency": "Weekly"
            }
        },
        {
            "IsEnabled": true,
            "Destination": {
                "S3BucketDestination": {
                    "Format": "CSV",
                    "Bucket": "arn:aws:s3:::amzn-s3-demo-bucket",
                    "AccountId": "123456789012"
                }
            },
            "IncludedObjectVersions": "Current",
            "Id": "2",
            "Schedule": {
                "Frequency": "Daily"
            }
        }
    ],
    "IsTruncated": false
}
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[ListBucketInventoryConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-bucket-inventory-configurations.html)」を参照してください。

### `list-bucket-metrics-configurations`
<a name="s3_ListBucketMetricsConfigurations_cli_2_topic"></a>

次のコード例は、`list-bucket-metrics-configurations` を使用する方法を示しています。

**AWS CLI**  
**バケットのメトリクス設定のリストを取得するには**  
次の `list-bucket-metrics-configurations` の例では、指定されたバケットのメトリクス設定のリストを取得します。  

```
aws s3api list-bucket-metrics-configurations \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "IsTruncated": false,
    "MetricsConfigurationList": [
        {
            "Filter": {
                "Prefix": "logs"
            },
            "Id": "123"
        },
        {
            "Filter": {
                "Prefix": "tmp"
            },
            "Id": "234"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListBucketMetricsConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-bucket-metrics-configurations.html)」を参照してください。

### `list-buckets`
<a name="s3_ListBuckets_cli_2_topic"></a>

次のコード例は、`list-buckets` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`list-buckets` コマンドを使用してすべての Amazon S3 バケット (すべてのリージョン) の名前を表示します。  

```
aws s3api list-buckets --query "Buckets[].Name"
```
クエリオプションで `list-buckets` の出力をバケット名のみにフィルタリングします。  
バケットの詳細については、「Amazon S3 ユーザーガイド」の「バケットの使用」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListBuckets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-buckets.html)」を参照してください。**

### `list-multipart-uploads`
<a name="s3_ListMultipartUploads_cli_2_topic"></a>

次のコード例は、`list-multipart-uploads` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのすべてのアクティブなマルチパートアップロードを一覧表示します。  

```
aws s3api list-multipart-uploads --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Uploads": [
        {
            "Initiator": {
                "DisplayName": "username",
                "ID": "arn:aws:iam::0123456789012:user/username"
            },
            "Initiated": "2015-06-02T18:01:30.000Z",
            "UploadId": "dfRtDYU0WWCCcH43C3WFbkRONycyCpTJJvxu2i5GYkZljF.Yxwh6XG7WfS2vC4to6HiV6Yjlx.cph0gtNBtJ8P3URCSbB7rjxI5iEwVDmgaXZOGgkk5nVTW16HOQ5l0R",
            "StorageClass": "STANDARD",
            "Key": "multipart/01",
            "Owner": {
                "DisplayName": "aws-account-name",
                "ID": "100719349fc3b6dcd7c820a124bf7aecd408092c3d7b51b38494939801fc248b"
            }
        }
    ],
    "CommonPrefixes": []
}
```
進行中のマルチパートアップロードでは、Amazon S3 のストレージコストが発生します。アクティブなマルチパートアップロードを完了または中止して、その一部をアカウントから削除します。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListMultipartUploads](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-multipart-uploads.html)」を参照してください。**

### `list-object-versions`
<a name="s3_ListObjectVersions_cli_2_topic"></a>

次のコード例は、`list-object-versions` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケット内のオブジェクトのバージョン情報を取得します。  

```
aws s3api list-object-versions --bucket amzn-s3-demo-bucket --prefix index.html
```
出力:  

```
{
    "DeleteMarkers": [
        {
            "Owner": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd660687538875e7c86c5b672fe116bd438f46db45460ddcd036c32"
            },
            "IsLatest": true,
            "VersionId": "B2VsEK5saUNNHKcOAJj7hIE86RozToyq",
            "Key": "index.html",
            "LastModified": "2015-11-10T00:57:03.000Z"
        },
        {
            "Owner": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd660687538875e7c86c5b672fe116bd438f46db45460ddcd036c32"
            },
            "IsLatest": false,
            "VersionId": ".FLQEZscLIcfxSq.jsFJ.szUkmng2Yw6",
            "Key": "index.html",
            "LastModified": "2015-11-09T23:32:20.000Z"
        }
    ],
    "Versions": [
        {
            "LastModified": "2015-11-10T00:20:11.000Z",
            "VersionId": "Rb_l2T8UHDkFEwCgJjhlgPOZC0qJ.vpD",
            "ETag": "\"0622528de826c0df5db1258a23b80be5\"",
            "StorageClass": "STANDARD",
            "Key": "index.html",
            "Owner": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd660687538875e7c86c5b672fe116bd438f46db45460ddcd036c32"
            },
            "IsLatest": false,
            "Size": 38
        },
        {
            "LastModified": "2015-11-09T23:26:41.000Z",
            "VersionId": "rasWWGpgk9E4s0LyTJgusGeRQKLVIAFf",
            "ETag": "\"06225825b8028de826c0df5db1a23be5\"",
            "StorageClass": "STANDARD",
            "Key": "index.html",
            "Owner": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd660687538875e7c86c5b672fe116bd438f46db45460ddcd036c32"
            },
            "IsLatest": false,
            "Size": 38
        },
        {
            "LastModified": "2015-11-09T22:50:50.000Z",
            "VersionId": "null",
            "ETag": "\"d1f45267a863c8392e07d24dd592f1b9\"",
            "StorageClass": "STANDARD",
            "Key": "index.html",
            "Owner": {
                "DisplayName": "my-username",
                "ID": "7009a8971cd660687538875e7c86c5b672fe116bd438f46db45460ddcd036c32"
            },
            "IsLatest": false,
            "Size": 533823
        }
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListObjectVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-object-versions.html)」を参照してください。**

### `list-objects-v2`
<a name="s3_ListObjectsV2_cli_2_topic"></a>

次のコード例は、`list-objects-v2` を使用する方法を示しています。

**AWS CLI**  
**バケット内のオブジェクトのリストを取得するには**  
次の `list-objects-v2` の例では、指定したバケットのオブジェクトを一覧表示します。  

```
aws s3api list-objects-v2 \
    --bucket amzn-s3-demo-bucket
```
出力:  

```
{
    "Contents": [
        {
            "LastModified": "2019-11-05T23:11:50.000Z",
            "ETag": "\"621503c373607d548b37cff8778d992c\"",
            "StorageClass": "STANDARD",
            "Key": "doc1.rtf",
            "Size": 391
        },
        {
            "LastModified": "2019-11-05T23:11:50.000Z",
            "ETag": "\"a2cecc36ab7c7fe3a71a273b9d45b1b5\"",
            "StorageClass": "STANDARD",
            "Key": "doc2.rtf",
            "Size": 373
        },
        {
            "LastModified": "2019-11-05T23:11:50.000Z",
            "ETag": "\"08210852f65a2e9cb999972539a64d68\"",
            "StorageClass": "STANDARD",
            "Key": "doc3.rtf",
            "Size": 399
        },
        {
            "LastModified": "2019-11-05T23:11:50.000Z",
            "ETag": "\"d1852dd683f404306569471af106988e\"",
            "StorageClass": "STANDARD",
            "Key": "doc4.rtf",
            "Size": 6225
        }
    ]
}
```
+  API の詳細については、「AWS CLI API リファレンス」の「[ListObjectsV2](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-objects-v2.html)」を参照してください。**

### `list-objects`
<a name="s3_ListObjects_cli_2_topic"></a>

次のコード例は、`list-objects` を使用する方法を示しています。

**AWS CLI**  
次の例は、`list-objects` コマンドを使用して、指定されたバケット内のすべてのオブジェクトの名前を表示します。  

```
aws s3api list-objects --bucket text-content --query 'Contents[].{Key: Key, Size: Size}'
```
この例では、`--query` 引数を使用して `list-objects` の出力を各オブジェクトのキー値とサイズでフィルタリングしています。  
オブジェクトの詳細については、「Amazon S3 デベロッパーガイド」の「Working with Amazon S3 Objects」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListObjects](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-objects.html)」を参照してください。

### `list-parts`
<a name="s3_ListParts_cli_2_topic"></a>

次のコード例は、`list-parts` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、バケット `multipart/01` 内のキーを使用してマルチパートアップロード用にアップロードされたすべてのパートを一覧表示します`amzn-s3-demo-bucket`。  

```
aws s3api list-parts --bucket amzn-s3-demo-bucket --key 'multipart/01' --upload-id dfRtDYU0WWCCcH43C3WFbkRONycyCpTJJvxu2i5GYkZljF.Yxwh6XG7WfS2vC4to6HiV6Yjlx.cph0gtNBtJ8P3URCSbB7rjxI5iEwVDmgaXZOGgkk5nVTW16HOQ5l0R
```
出力:  

```
{
    "Owner": {
        "DisplayName": "aws-account-name",
        "ID": "100719349fc3b6dcd7c820a124bf7aecd408092c3d7b51b38494939801fc248b"
    },
    "Initiator": {
        "DisplayName": "username",
        "ID": "arn:aws:iam::0123456789012:user/username"
    },
    "Parts": [
        {
            "LastModified": "2015-06-02T18:07:35.000Z",
            "PartNumber": 1,
            "ETag": "\"e868e0f4719e394144ef36531ee6824c\"",
            "Size": 5242880
        },
        {
            "LastModified": "2015-06-02T18:07:42.000Z",
            "PartNumber": 2,
            "ETag": "\"6bb2b12753d66fe86da4998aa33fffb0\"",
            "Size": 5242880
        },
        {
            "LastModified": "2015-06-02T18:07:47.000Z",
            "PartNumber": 3,
            "ETag": "\"d0a0112e841abec9c9ec83406f0159c8\"",
            "Size": 5242880
        }
    ],
    "StorageClass": "STANDARD"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListParts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/list-parts.html)」を参照してください。

### `ls`
<a name="s3_Ls_cli_2_topic"></a>

次のコード例は、`ls` を使用する方法を示しています。

**AWS CLI**  
**例 1: ユーザー所有のすべてのバケットを一覧表示する**  
次の `ls` コマンドは、ユーザーが所有しているすべてのバケットを一覧表示します。この例では、ユーザーがバケット `amzn-s3-demo-bucket` と `amzn-s3-demo-bucket2` を所有しています。タイムスタンプは、バケットが作成された日付で、マシンのタイムゾーンに表示されます。この日付は、バケットポリシーの編集など、バケットに変更を加えるときに変更される可能性があります。`s3://` がパス引数 `<S3Uri>` に使用される場合、すべてのバケットも一覧表示されます。  

```
aws s3 ls
```
出力:  

```
2013-07-11 17:08:50 amzn-s3-demo-bucket
2013-07-24 14:55:44 amzn-s3-demo-bucket2
```
**例 2: バケット内のすべてのプレフィックスとオブジェクトを一覧表示する**  
次の `ls` コマンドは、指定されたバケットとプレフィックスの下にあるオブジェクトと共通のプレフィックスを一覧表示します。この例では、ユーザーはオブジェクト `test.txt` と `amzn-s3-demo-bucket` を使用してバケット `somePrefix/test.txt` を所有します。`LastWriteTime` と `Length` は任意です。`ls` コマンドはローカルファイルシステムとやり取りしないため、あいまいさを解決するために URI `s3://` スキームを必要とせず、省略される場合があることに注意してください。  

```
aws s3 ls s3://amzn-s3-demo-bucket
```
出力:  

```
                           PRE somePrefix/
2013-07-25 17:06:27         88 test.txt
```
**例 3: 特定のバケットとプレフィックス内のすべてのプレフィックスとオブジェクトを一覧表示する**  
次の `ls` コマンドは、指定されたバケットとプレフィックスの下にあるオブジェクトと共通のプレフィックスを一覧表示します。ただし、指定されたバケットとプレフィックスの下にオブジェクトや共通のプレフィックスはありません。  

```
aws s3 ls s3://amzn-s3-demo-bucket/noExistPrefix
```
出力:  

```
None
```
**例 4: バケット内のすべてのプレフィックスとオブジェクトを再帰的に一覧表示する**  
次の `ls` コマンドは、バケット内のオブジェクトを再帰的に一覧表示します。出力に `PRE dirname/` が表示されるのではなく、バケット内のすべてのコンテンツが順番に表示されます。  

```
aws s3 ls s3://amzn-s3-demo-bucket \
    --recursive
```
出力:  

```
2013-09-02 21:37:53         10 a.txt
2013-09-02 21:37:53    2863288 foo.zip
2013-09-02 21:32:57         23 foo/bar/.baz/a
2013-09-02 21:32:58         41 foo/bar/.baz/b
2013-09-02 21:32:57        281 foo/bar/.baz/c
2013-09-02 21:32:57         73 foo/bar/.baz/d
2013-09-02 21:32:57        452 foo/bar/.baz/e
2013-09-02 21:32:57        896 foo/bar/.baz/hooks/bar
2013-09-02 21:32:57        189 foo/bar/.baz/hooks/foo
2013-09-02 21:32:57        398 z.txt
```
**例 5: バケット内のすべてのプレフィックスとオブジェクトを要約する**  
次の `ls` コマンドは、--human-readable オプションと --summarize オプションを使用して同じコマンドを示しています。--human-readable は、ファイルサイズを Bytes/MiB /KiB /GiB /TiB /PiB /EiB で表示します。--summarize は、結果リストの最後にオブジェクトの合計数と合計サイズを表示します。  

```
aws s3 ls s3://amzn-s3-demo-bucket \
    --recursive \
    --human-readable \
    --summarize
```
出力:  

```
2013-09-02 21:37:53   10 Bytes a.txt
2013-09-02 21:37:53  2.9 MiB foo.zip
2013-09-02 21:32:57   23 Bytes foo/bar/.baz/a
2013-09-02 21:32:58   41 Bytes foo/bar/.baz/b
2013-09-02 21:32:57  281 Bytes foo/bar/.baz/c
2013-09-02 21:32:57   73 Bytes foo/bar/.baz/d
2013-09-02 21:32:57  452 Bytes foo/bar/.baz/e
2013-09-02 21:32:57  896 Bytes foo/bar/.baz/hooks/bar
2013-09-02 21:32:57  189 Bytes foo/bar/.baz/hooks/foo
2013-09-02 21:32:57  398 Bytes z.txt

Total Objects: 10
   Total Size: 2.9 MiB
```
**例 6: S3 アクセスポイントから一覧表示する**  
次の `ls` コマンドは、アクセスポイント (`myaccesspoint`) からのオブジェクトを一覧表示します。  

```
aws s3 ls s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/
```
出力:  

```
                           PRE somePrefix/
2013-07-25 17:06:27         88 test.txt
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Ls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/ls.html)」を参照してください。

### `mb`
<a name="s3_Mb_cli_2_topic"></a>

次のコード例は、`mb` を使用する方法を示しています。

**AWS CLI**  
**例 1: バケットを作成する**  
以下の `mb` コマンドはバケットを作成します。この例では、ユーザーはバケット `amzn-s3-demo-bucket` を作成しています。バケットは、ユーザーの設定ファイルで指定されたリージョンに作成されます。  

```
aws s3 mb s3://amzn-s3-demo-bucket
```
出力:  

```
make_bucket: s3://amzn-s3-demo-bucket
```
**例 2: 指定されたリージョンにバケットを作成する**  
次の `mb` コマンドは、`--region` パラメータで指定されたリージョンにバケットを作成します。この例では、ユーザーはリージョン `us-west-1` にバケット `amzn-s3-demo-bucket` を作成します。  

```
aws s3 mb s3://amzn-s3-demo-bucket \
    --region us-west-1
```
出力:  

```
make_bucket: s3://amzn-s3-demo-bucket
```
**例 3: 指定されたタグを使用してバケットを作成する**  
次の `mb` コマンドは、`--tags` パラメータを使用して指定されたタグのあるバケットを作成します。この例では、ユーザーはキー `Key1` と `Key2` の 2 つのタグのあるバケット `amzn-s3-demo-bucket` をそれぞれ作成します。  

```
aws s3 mb s3://amzn-s3-demo-bucket \
    --tags Key1 Value1 \
    --tags Key2 Value2
```
出力:  

```
make_bucket: s3://amzn-s3-demo-bucket
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Mb](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/mb.html)」を参照してください。

### `mv`
<a name="s3_Mv_cli_2_topic"></a>

次のコード例は、`mv` を使用する方法を示しています。

**AWS CLI**  
**例 1: 指定されたバケットにローカルファイルを移動する**  
次の `mv` コマンドは、1 つのファイルを指定されたバケットとキーに移動します。  

```
aws s3 mv test.txt s3://amzn-s3-demo-bucket/test2.txt
```
出力:  

```
move: test.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 2: オブジェクトを指定されたバケットとキーに移動する**  
次の `mv` コマンドは、1 つの s3 オブジェクトを指定されたバケットとキーに移動します。  

```
aws s3 mv s3://amzn-s3-demo-bucket/test.txt s3://amzn-s3-demo-bucket/test2.txt
```
出力:  

```
move: s3://amzn-s3-demo-bucket/test.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 3: S3 オブジェクトをローカルディレクトリに移動する**  
次の `mv` コマンドは、1 つのオブジェクトを指定されたファイルにローカルに移動します。  

```
aws s3 mv s3://amzn-s3-demo-bucket/test.txt test2.txt
```
出力:  

```
move: s3://amzn-s3-demo-bucket/test.txt to test2.txt
```
**例 4: 元の名前のオブジェクトを指定されたバケットに移動する**  
次の `mv` コマンドは、元の名前を保持しながら、1 つのオブジェクトを指定されたバケットに移動します。  

```
aws s3 mv s3://amzn-s3-demo-bucket/test.txt s3://amzn-s3-demo-bucket2/
```
出力:  

```
move: s3://amzn-s3-demo-bucket/test.txt to s3://amzn-s3-demo-bucket2/test.txt
```
**例 5: バケット内のすべてのオブジェクトとプレフィックスをローカルディレクトリに移動する**  
パラメータ `--recursive` で渡された場合、次の `mv` コマンドは、指定されたプレフィックスとバケットのすべてのオブジェクトを指定されたディレクトリに再帰的に移動します。この例では、バケット `amzn-s3-demo-bucket` にはオブジェクト `test1.txt` と `test2.txt` があります。  

```
aws s3 mv s3://amzn-s3-demo-bucket . \
    --recursive
```
出力:  

```
move: s3://amzn-s3-demo-bucket/test1.txt to test1.txt
move: s3://amzn-s3-demo-bucket/test2.txt to test2.txt
```
**例 6: バケット内のすべてのオブジェクトとプレフィックスをローカルディレクトリに移動する（「.jpg」ファイルは除く）**  
パラメータ `--recursive` で渡された場合、次の `mv` コマンドは、`--exclude` パラメータを使用して一部のファイルを除外しながら、指定されたディレクトリ内のすべてのファイルを指定されたバケットとプレフィックスに再帰的に移動します。この例では、`myDir` ディレクトリにファイル `test1.txt` と `test2.jpg` があります。  

```
aws s3 mv myDir s3://amzn-s3-demo-bucket/ \
    --recursive \
    --exclude "*.jpg"
```
出力:  

```
move: myDir/test1.txt to s3://amzn-s3-demo-bucket2/test1.txt
```
**例 7: バケット内のすべてのオブジェクトとプレフィックスをローカルディレクトリに移動する（指定されたプレフィックスは除く）**  
パラメータ `--recursive` で渡された場合、次の `mv` コマンドは、`--exclude` パラメータを使用して一部のオブジェクトを除外しながら、指定されたバケット内のすべてのオブジェクトを別のバケットに再帰的に移動します。この例では、バケット `amzn-s3-demo-bucket` にはオブジェクト `test1.txt` と `another/test1.txt` があります。  

```
aws s3 mv s3://amzn-s3-demo-bucket/ s3://amzn-s3-demo-bucket2/ \
    --recursive \
    --exclude "amzn-s3-demo-bucket/another/*"
```
出力:  

```
move: s3://amzn-s3-demo-bucket/test1.txt to s3://amzn-s3-demo-bucket2/test1.txt
```
**例 8: 指定されたバケットにオブジェクトを移動し、ACL を設定する**  
次の `mv` コマンドは、ACL を `public-read-write` に設定しながら、1 つのオブジェクトを指定されたバケットとキーに移動します。  

```
aws s3 mv s3://amzn-s3-demo-bucket/test.txt s3://amzn-s3-demo-bucket/test2.txt \
    --acl public-read-write
```
出力:  

```
move: s3://amzn-s3-demo-bucket/test.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 9: ローカルファイルを指定されたバケットに移動し、アクセス許可を付与する**  
次の `mv` コマンドは、すべてのユーザーに読み取りアクセスを付与し、E メールアドレスで識別される特定のユーザーに完全なコントロールを付与する `--grants` オプションの使用方法を示しています。  

```
aws s3 mv file.txt s3://amzn-s3-demo-bucket/ \
    --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers full=emailaddress=user@example.com
```
出力:  

```
move: file.txt to s3://amzn-s3-demo-bucket/file.txt
```
**例 10: ファイルを S3 アクセスポイントに移動する**  
次の `mv` コマンドは、`mykey` という名前のキーで `myaccesspoint` という名前のアクセスポイントに `mydoc.txt` という名前の 1 つのファイルを移動します。  

```
aws s3 mv mydoc.txt s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey
```
出力:  

```
move: mydoc.txt to s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Mv](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/mv.html)」を参照してください。

### `presign`
<a name="s3_Presign_cli_2_topic"></a>

次のコード例は、`presign` を使用する方法を示しています。

**AWS CLI**  
**例 1: S3 バケット内のオブジェクトにリンクするデフォルトの 1 時間の有効期間を持つ署名付き URL を作成するには**  
次の `presign` コマンドは、指定されたバケットと 1 時間有効なキーの署名付き URL を生成します。  

```
aws s3 presign s3://amzn-s3-demo-bucket/test2.txt
```
出力:  

```
https://amzn-s3-demo-bucket.s3.us-west-2.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAEXAMPLE123456789%2F20210621%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210621T041609Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=EXAMBLE1234494d5fba3fed607f98018e1dfc62e2529ae96d844123456
```
**例 2: S3 バケット内のオブジェクトにリンクするカスタムの有効期間を持つ署名付き URL を作成するには**  
次の `presign` コマンドは、指定されたバケットと 1 週間有効なキーの署名付き URL を生成します。  

```
aws s3 presign s3://amzn-s3-demo-bucket/test2.txt \
    --expires-in 604800
```
出力:  

```
https://amzn-s3-demo-bucket.s3.us-west-2.amazonaws.com/key?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAEXAMPLE123456789%2F20210621%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20210621T041609Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=EXAMBLE1234494d5fba3fed607f98018e1dfc62e2529ae96d844123456
```
詳細については、「*S3 デベロッパーガイド*」の「[他ユーザーとのオブジェクトの共有](https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURL.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Presign](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/presign.html)」を参照してください。

### `put-bucket-accelerate-configuration`
<a name="s3_PutBucketAccelerateConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-accelerate-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットの加速設定を指定するには**  
次の `put-bucket-accelerate-configuration` の例では、指定したバケットの加速設定を有効にします。  

```
aws s3api put-bucket-accelerate-configuration \
    --bucket amzn-s3-demo-bucket \
    --accelerate-configuration Status=Enabled
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[PutBucketAccelerateConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-accelerate-configuration.html)」を参照してください。

### `put-bucket-acl`
<a name="s3_PutBucketAcl_cli_2_topic"></a>

次の例は、`put-bucket-acl` を使用する方法を説明しています。

**AWS CLI**  
この例では`full control`、2 人の AWS ユーザー (*user1@example.com* と *user2@example.com*) に とアクセス`read`許可をすべてのユーザーに付与します。  

```
aws s3api put-bucket-acl --bucket amzn-s3-demo-bucket --grant-full-control emailaddress=user1@example.com,emailaddress=user2@example.com --grant-read uri=http://acs.amazonaws.com/groups/global/AllUsers
```
カスタム ACL の詳細については、http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html を参照してください (`put-bucket-acl` などの s3api ACL コマンドは、同じ略記法を使用します)。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutBucketAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-acl.html)」を参照してください。**

### `put-bucket-analytics-configuration`
<a name="s3_PutBucketAnalyticsConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-analytics-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットの分析設定を設定するには**  
次の `put-bucket-analytics-configuration` の例では、指定されたバケットと ID の分析を設定します。  

```
aws s3api put-bucket-analytics-configuration \
    --bucket amzn-s3-demo-bucket --id 1 \
    --analytics-configuration '{"Id": "1","StorageClassAnalysis": {}}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutBucketAnalyticsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-analytics-configuration.html)」を参照してください。

### `put-bucket-cors`
<a name="s3_PutBucketCors_cli_2_topic"></a>

次のコード例は、`put-bucket-cors` を使用する方法を示しています。

**AWS CLI**  
次の例は、*www.example.com* からの `PUT`、`POST`、および `DELETE` の各リクエストを有効化し、任意のドメインからの `GET` リクエストを有効化します。  

```
aws s3api put-bucket-cors --bucket amzn-s3-demo-bucket --cors-configuration file://cors.json

cors.json:
{
  "CORSRules": [
    {
      "AllowedOrigins": ["http://www.example.com"],
      "AllowedHeaders": ["*"],
      "AllowedMethods": ["PUT", "POST", "DELETE"],
      "MaxAgeSeconds": 3000,
      "ExposeHeaders": ["x-amz-server-side-encryption"]
    },
    {
      "AllowedOrigins": ["*"],
      "AllowedHeaders": ["Authorization"],
      "AllowedMethods": ["GET"],
      "MaxAgeSeconds": 3000
    }
  ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutBucketCors](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-cors.html)」を参照してください。**

### `put-bucket-encryption`
<a name="s3_PutBucketEncryption_cli_2_topic"></a>

次のコード例は、`put-bucket-encryption` を使用する方法を示しています。

**AWS CLI**  
**バケットのサーバー側の暗号化を設定するには**  
次の `put-bucket-encryption` の例では、指定したバケットのデフォルトとして AES256 暗号化を設定します。  

```
aws s3api put-bucket-encryption \
    --bucket amzn-s3-demo-bucket \
    --server-side-encryption-configuration '{"Rules": [{"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"}}]}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[PutBucketEncryption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-encryption.html)」を参照してください。

### `put-bucket-intelligent-tiering-configuration`
<a name="s3_PutBucketIntelligentTieringConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-intelligent-tiering-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットの S3 Intelligent-Tiering 設定を更新するには**  
次の `put-bucket-intelligent-tiering-configuration` の例では、バケットの ExampleConfig という名前の S3 Intelligent-Tiering 設定を更新します。この設定では、プレフィックスイメージでアクセスされていないオブジェクトは、90 日後にアーカイブアクセス、180 日後にディープアーカイブアクセスに移行されます。  

```
aws s3api put-bucket-intelligent-tiering-configuration \
    --bucket amzn-s3-demo-bucket \
    --id "ExampleConfig" \
    --intelligent-tiering-configuration file://intelligent-tiering-configuration.json
```
`intelligent-tiering-configuration.json` の内容:  

```
{
    "Id": "ExampleConfig",
    "Status": "Enabled",
    "Filter": {
        "Prefix": "images"
        },
    "Tierings": [
        {
            "Days": 90,
            "AccessTier": "ARCHIVE_ACCESS"
        },
        {
            "Days": 180,
            "AccessTier": "DEEP_ARCHIVE_ACCESS"
        }
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon S3 ユーザーガイド*」の「[既存のバケットでのオブジェクトの所有権の設定](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-ownership-existing-bucket.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutBucketIntelligentTieringConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-intelligent-tiering-configuration.html)」を参照してください。

### `put-bucket-inventory-configuration`
<a name="s3_PutBucketInventoryConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-inventory-configuration` を使用する方法を示しています。

**AWS CLI**  
**例 1: バケットのインベントリ設定を設定するには**  
次の `put-bucket-inventory-configuration` の例では、バケット `amzn-s3-demo-bucket` の毎週の ORC 形式のインベントリレポートを設定します。  

```
aws s3api put-bucket-inventory-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 1 \
    --inventory-configuration '{"Destination": { "S3BucketDestination": { "AccountId": "123456789012", "Bucket": "arn:aws:s3:::amzn-s3-demo-bucket", "Format": "ORC" }}, "IsEnabled": true, "Id": "1", "IncludedObjectVersions": "Current", "Schedule": { "Frequency": "Weekly" }}'
```
このコマンドでは何も出力されません。  
**例 2: バケットのインベントリ設定を指定するには**  
次の `put-bucket-inventory-configuration` の例では、バケット `amzn-s3-demo-bucket` の毎日の CSV 形式のインベントリレポートを設定します。  

```
aws s3api put-bucket-inventory-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 2 \
    --inventory-configuration '{"Destination": { "S3BucketDestination": { "AccountId": "123456789012", "Bucket": "arn:aws:s3:::amzn-s3-demo-bucket", "Format": "CSV" }}, "IsEnabled": true, "Id": "2", "IncludedObjectVersions": "Current", "Schedule": { "Frequency": "Daily" }}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutBucketInventoryConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-inventory-configuration.html)」を参照してください。

### `put-bucket-lifecycle-configuration`
<a name="s3_PutBucketLifecycleConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-lifecycle-configuration` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットにライフサイクル設定を適用します。  

```
aws s3api put-bucket-lifecycle-configuration --bucket amzn-s3-demo-bucket --lifecycle-configuration  file://lifecycle.json
```
`lifecycle.json` ファイルは、現在のフォルダ内の JSON ドキュメントで、次の 2 つのルールを指定します。  

```
{
    "Rules": [
        {
            "ID": "Move rotated logs to Glacier",
            "Prefix": "rotated/",
            "Status": "Enabled",
            "Transitions": [
                {
                    "Date": "2015-11-10T00:00:00.000Z",
                    "StorageClass": "GLACIER"
                }
            ]
        },
        {
            "Status": "Enabled",
            "Prefix": "",
            "NoncurrentVersionTransitions": [
                {
                    "NoncurrentDays": 2,
                    "StorageClass": "GLACIER"
                }
            ],
            "ID": "Move old versions to Glacier"
        }
    ]
}
```
1 つ目のルールは、指定した日付に、プレフィックス `rotated` の付いたファイルを Glacier に移動します。2 つ目のルールは、最新でない古いオブジェクトバージョンを Glacier に移動します。詳細については、「AWS CLI ユーザーガイド」の「Specifying Parameter Values」を参照してください。**  
+  API の詳細については、**AWS CLI コマンドリファレンスの「[PutBucketLifecycleConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-lifecycle-configuration.html)」を参照してください。

### `put-bucket-lifecycle`
<a name="s3_PutBucketLifecycle_cli_2_topic"></a>

次のコード例は、`put-bucket-lifecycle` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、バケット `amzn-s3-demo-bucket` にライフサイクル設定を適用します。  

```
aws s3api put-bucket-lifecycle --bucket amzn-s3-demo-bucket --lifecycle-configuration file://lifecycle.json
```
`lifecycle.json` ファイルは、現在のフォルダ内の JSON ドキュメントで、次の 2 つのルールを指定します。  

```
{
  "Rules": [
    {
      "ID": "Move to Glacier after sixty days (objects in logs/2015/)",
      "Prefix": "logs/2015/",
      "Status": "Enabled",
      "Transition": {
        "Days": 60,
        "StorageClass": "GLACIER"
      }
    },
    {
      "Expiration": {
        "Date": "2016-01-01T00:00:00.000Z"
      },
      "ID": "Delete 2014 logs in 2016.",
      "Prefix": "logs/2014/",
      "Status": "Enabled"
    }
  ]
}
```
最初のルールは、60 日後にファイルを Amazon Glacier に移動します。2 番目のルールは、指定した日付に Amazon S3 からファイルを削除します。詳細については、「AWS CLI ユーザーガイド」の「Specifying Parameter Values」を参照してください。**  
上記の例の各ルールは、適用されるポリシー (`Transition` または `Expiration`) とファイルプレフィックス (フォルダ名) を指定します。空白のプレフィックスを指定して、バケット全体に適用されるルールを作成することもできます。  

```
{
  "Rules": [
    {
      "ID": "Move to Glacier after sixty days (all objects in bucket)",
      "Prefix": "",
      "Status": "Enabled",
      "Transition": {
        "Days": 60,
        "StorageClass": "GLACIER"
      }
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutBucketLifecycle](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-lifecycle.html)」を参照してください。

### `put-bucket-logging`
<a name="s3_PutBucketLogging_cli_2_topic"></a>

次のコード例は、`put-bucket-logging` を使用する方法を示しています。

**AWS CLI**  
**例 1: バケットポリシーのログ記録を設定するには**  
次の `put-bucket-logging` の例では、*amzn-s3-demo-bucket* のログ記録ポリシーを設定します。まず、`put-bucket-policy` コマンドを使用して、バケットポリシーでログ記録サービスプリンシパルに許可を付与します。  

```
aws s3api put-bucket-policy \
    --bucket amzn-s3-demo-bucket \
    --policy file://policy.json
```
`policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "S3ServerAccessLogsPolicy",
            "Effect": "Allow",
            "Principal": {"Service": "logging.s3.amazonaws.com"},
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/Logs/*",
            "Condition": {
                "ArnLike": {"aws:SourceARN": "arn:aws:s3:::SOURCE-BUCKET-NAME"},
                "StringEquals": {"aws:SourceAccount": "SOURCE-AWS-ACCOUNT-ID"}
            }
        }
    ]
}
```
ログ記録ポリシーを適用するには、`put-bucket-logging` を使用します。  

```
aws s3api put-bucket-logging \
    --bucket amzn-s3-demo-bucket \
    --bucket-logging-status file://logging.json
```
`logging.json` の内容:  

```
{
     "LoggingEnabled": {
         "TargetBucket": "amzn-s3-demo-bucket",
         "TargetPrefix": "Logs/"
     }
 }
```
`put-bucket-policy` コマンドは、ログ記録サービスプリンシパルに `s3:PutObject` アクセス許可を付与するために必要です。  
詳細については、「*Amazon S3 ユーザーガイド*」の「[Amazon S3 サーバーアクセスのログ記録](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerLogs.html)」を参照してください。  
**例 2: 1 人のユーザーのみにアクセスをログ記録するためのバケットポリシーを設定するには**  
次の `put-bucket-logging` の例では、*amzn-s3-demo-bucket* のログ記録ポリシーを設定します。 AWS ユーザー *bob@example.com* はログファイルを完全に制御でき、他のユーザーはアクセスできません。まず、`put-bucket-acl` で S3 アクセス許可を付与します。  

```
aws s3api put-bucket-acl \
    --bucket amzn-s3-demo-bucket \
    --grant-write URI=http://acs.amazonaws.com/groups/s3/LogDelivery \
    --grant-read-acp URI=http://acs.amazonaws.com/groups/s3/LogDelivery
```
次に、`put-bucket-logging` を使用してログ記録ポリシーを適用します。  

```
aws s3api put-bucket-logging \
    --bucket amzn-s3-demo-bucket \
    --bucket-logging-status file://logging.json
```
`logging.json` の内容:  

```
{
    "LoggingEnabled": {
        "TargetBucket": "amzn-s3-demo-bucket",
        "TargetPrefix": "amzn-s3-demo-bucket-logs/",
        "TargetGrants": [
            {
                "Grantee": {
                    "Type": "AmazonCustomerByEmail",
                    "EmailAddress": "bob@example.com"
                },
                "Permission": "FULL_CONTROL"
            }
        ]
    }
}
```
`put-bucket-acl` コマンドは、Amazon S3 のログ配信システムに必要なアクセス許可 (write および read-acp アクセス許可) を付与するために必要です。  
詳細については、「*Amazon S3 デベロッパーガイド*」の「[Amazon S3 サーバーアクセスログ](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ServerLogs.html)」を参照してください。  
+  API の詳細については、**AWS CLI コマンドリファレンスの「[PutBucketLogging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-logging.html)」を参照してください。

### `put-bucket-metrics-configuration`
<a name="s3_PutBucketMetricsConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-metrics-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットのメトリクス設定を指定するには**  
次の `put-bucket-metrics-configuration` の例では、指定されたバケットに対して ID 123 のメトリクス設定を指定します。  

```
aws s3api put-bucket-metrics-configuration \
    --bucket amzn-s3-demo-bucket \
    --id 123 \
    --metrics-configuration '{"Id": "123", "Filter": {"Prefix": "logs"}}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutBucketMetricsConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-metrics-configuration.html)」を参照してください。

### `put-bucket-notification-configuration`
<a name="s3_PutBucketNotificationConfiguration_cli_2_topic"></a>

次のコード例は、`put-bucket-notification-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットへの指定された通知を有効にするには**  
次の `put-bucket-notification-configuration` の例では、`amzn-s3-demo-bucket` という名前のバケットに通知設定を適用します。`notification.json` ファイルは、現在のフォルダにある JSON ファイルで、モニタリングする SNS トピックとイベントタイプを指定します。  

```
aws s3api put-bucket-notification-configuration \
    --bucket amzn-s3-demo-bucket \
    --notification-configuration file://notification.json
```
`notification.json` の内容:  

```
{
    "TopicConfigurations": [
        {
            "TopicArn": "arn:aws:sns:us-west-2:123456789012:s3-notification-topic",
            "Events": [
                "s3:ObjectCreated:*"
            ]
        }
    ]
}
```
SNS トピックには、Amazon S3 に公開を許可する IAM ポリシーがアタッチされている必要があります。  

```
{
    "Version":"2012-10-17",		 	 	 
    "Id": "example-ID",
    "Statement": [
        {
            "Sid": "example-statement-ID",
            "Effect": "Allow",
            "Principal": {
                "Service": "s3.amazonaws.com"
            },
            "Action": [
                "SNS:Publish"
            ],
            "Resource": "arn:aws:sns:us-west-2:123456789012::s3-notification-topic",
            "Condition": {
                "ArnLike": {
                    "aws:SourceArn": "arn:aws:s3:*:*:amzn-s3-demo-bucket"
                }
            }
        }
    ]
}
```
+  API の詳細については、**AWS CLI コマンドリファレンスの「[PutBucketNotificationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-notification-configuration.html)」を参照してください。

### `put-bucket-notification`
<a name="s3_PutBucketNotification_cli_2_topic"></a>

次のコード例は、`put-bucket-notification` を使用する方法を示しています。

**AWS CLI**  
`amzn-s3-demo-bucket` という名前のバケットに通知設定を適用します。  

```
aws s3api put-bucket-notification --bucket amzn-s3-demo-bucket --notification-configuration file://notification.json
```
`notification.json` ファイルは、現在のフォルダにある JSON ファイルで、モニタリングする SNS トピックとイベントタイプを指定します。  

```
{
  "TopicConfiguration": {
    "Event": "s3:ObjectCreated:*",
    "Topic": "arn:aws:sns:us-west-2:123456789012:s3-notification-topic"
  }
}
```
SNS トピックには、Amazon S3 に公開を許可する IAM ポリシーがアタッチされている必要があります。  

```
{
 "Version":"2012-10-17",		 	 	 
 "Id": "example-ID",
 "Statement": [
  {
   "Sid": "example-statement-ID",
   "Effect": "Allow",
   "Principal": {
     "Service": "s3.amazonaws.com"
   },
   "Action": [
    "SNS:Publish"
   ],
   "Resource": "arn:aws:sns:us-west-2:123456789012:amzn-s3-demo-bucket",
   "Condition": {
      "ArnLike": {
      "aws:SourceArn": "arn:aws:s3:*:*:amzn-s3-demo-bucket"
    }
   }
  }
 ]
}
```
+  API の詳細については、**AWS CLI コマンドリファレンスの「[PutBucketNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-notification.html)」を参照してください。

### `put-bucket-ownership-controls`
<a name="s3_PutBucketOwnershipControls_cli_2_topic"></a>

次のコード例は、`put-bucket-ownership-controls` を使用する方法を示しています。

**AWS CLI**  
**バケットのバケット所有権設定を更新するには**  
次の `put-bucket-ownership-controls` の例では、バケットのバケット所有権設定を更新します。  

```
aws s3api put-bucket-ownership-controls \
    --bucket amzn-s3-demo-bucket \
    --ownership-controls="Rules=[{ObjectOwnership=BucketOwnerEnforced}]"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon S3 ユーザーガイド*」の「[既存のバケットでのオブジェクトの所有権の設定](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-ownership-existing-bucket.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutBucketOwnershipControls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-ownership-controls.html)」を参照してください。

### `put-bucket-policy`
<a name="s3_PutBucketPolicy_cli_2_topic"></a>

次のコード例は、`put-bucket-policy` を使用する方法を示しています。

**AWS CLI**  
この例では、*MySecretFolder* 内のものを除いて、すべてのユーザーが *amzn-s3-demo-bucket* 内の任意のオブジェクトを取得できるようにしています。また、 AWS アカウントのルートユーザーに `put`および アクセス`delete`許可を付与します`1234-5678-9012`。  

```
aws s3api put-bucket-policy --bucket amzn-s3-demo-bucket --policy file://policy.json

policy.json:
{
   "Statement": [
      {
         "Effect": "Allow",
         "Principal": "*",
         "Action": "s3:GetObject",
         "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
      },
      {
         "Effect": "Deny",
         "Principal": "*",
         "Action": "s3:GetObject",
         "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/MySecretFolder/*"
      },
      {
         "Effect": "Allow",
         "Principal": {
            "AWS": "arn:aws:iam::123456789012:root"
         },
         "Action": [
            "s3:DeleteObject",
            "s3:PutObject"
         ],
         "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
      }
   ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutBucketPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-policy.html)」を参照してください。**

### `put-bucket-replication`
<a name="s3_PutBucketReplication_cli_2_topic"></a>

次のコード例は、`put-bucket-replication` を使用する方法を示しています。

**AWS CLI**  
**S3 バケットのレプリケーションを設定するには**  
次の `put-bucket-replication` の例では、指定した S3 バケットにレプリケーション設定を適用します。  

```
aws s3api put-bucket-replication \
    --bucket amzn-s3-demo-bucket1 \
    --replication-configuration file://replication.json
```
`replication.json` の内容:  

```
{
    "Role": "arn:aws:iam::123456789012:role/s3-replication-role",
    "Rules": [
        {
            "Status": "Enabled",
            "Priority": 1,
            "DeleteMarkerReplication": { "Status": "Disabled" },
            "Filter" : { "Prefix": ""},
            "Destination": {
                "Bucket": "arn:aws:s3:::amzn-s3-demo-bucket2"
            }
        }
    ]
}
```
レプリケーション先のバケットではバージョニングが有効になっている必要があります。指定したロールは、レプリケーション先のバケットへの書き込みアクセス許可を持ち、Amazon S3 がそのロールを引き受けることを許可する信頼関係が必要です。  
ロールのアクセス許可ポリシーの例:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetReplicationConfiguration",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket1"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObjectVersion",
                "s3:GetObjectVersionAcl",
                "s3:GetObjectVersionTagging"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket1/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ReplicateObject",
                "s3:ReplicateDelete",
                "s3:ReplicateTags"
            ],
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket2/*"
        }
    ]
}
```
信頼関係ポリシーの例:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "s3.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、「**Amazon Simple Storage Service コンソールユーザーガイド」の「[チュートリアル: レプリケーションの設定例](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/enable-replication.html)」を参照してください。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[PutBucketReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-replication.html)」を参照してください。

### `put-bucket-request-payment`
<a name="s3_PutBucketRequestPayment_cli_2_topic"></a>

次のコード例は、`put-bucket-request-payment` を使用する方法を示しています。

**AWS CLI**  
**例 1: バケットの「リクエスタ支払い」設定を有効にするには**  
次の `put-bucket-request-payment` の例では、指定したバケットの `requester pays` を有効にします。  

```
aws s3api put-bucket-request-payment \
    --bucket amzn-s3-demo-bucket \
    --request-payment-configuration '{"Payer":"Requester"}'
```
このコマンドでは何も出力されません。  
**例 2: バケットの「リクエスタ支払い」設定を無効にするには**  
次の `put-bucket-request-payment` の例では、指定したバケットの `requester pays` を無効にします。  

```
aws s3api put-bucket-request-payment \
    --bucket amzn-s3-demo-bucket \
    --request-payment-configuration '{"Payer":"BucketOwner"}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[PutBucketRequestPayment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-request-payment.html)」を参照してください。

### `put-bucket-tagging`
<a name="s3_PutBucketTagging_cli_2_topic"></a>

次のコード例は、`put-bucket-tagging` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、タグ付けの設定を `amzn-s3-demo-bucket` という名前のバケットに適用します。  

```
aws s3api put-bucket-tagging --bucket amzn-s3-demo-bucket --tagging file://tagging.json
```
この `tagging.json` ファイルは、タグを指定する現在のフォルダ内の JSON ドキュメントです。  

```
{
   "TagSet": [
     {
       "Key": "organization",
       "Value": "marketing"
     }
   ]
}
```
または、コマンドラインから直接タグ設定を `amzn-s3-demo-bucket` に適用します。  

```
aws s3api put-bucket-tagging --bucket amzn-s3-demo-bucket --tagging 'TagSet=[{Key=organization,Value=marketing}]'
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[PutBucketTagging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-tagging.html)」を参照してください。

### `put-bucket-versioning`
<a name="s3_PutBucketVersioning_cli_2_topic"></a>

次のコード例は、`put-bucket-versioning` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットのバージョニングを有効にします。  

```
aws s3api put-bucket-versioning --bucket amzn-s3-demo-bucket --versioning-configuration Status=Enabled
```
次のコマンドはバージョニングを有効にします。これは、MFA コードを使用します。  

```
aws s3api put-bucket-versioning --bucket amzn-s3-demo-bucket --versioning-configuration Status=Enabled --mfa "SERIAL 123456"
```
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[PutBucketVersioning](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-versioning.html)」を参照してください。

### `put-bucket-website`
<a name="s3_PutBucketWebsite_cli_2_topic"></a>

次のコード例は、`put-bucket-website` を使用する方法を示しています。

**AWS CLI**  
`amzn-s3-demo-bucket` という名前のバケットに静的なウェブサイト設定を適用します。  

```
aws s3api put-bucket-website --bucket amzn-s3-demo-bucket --website-configuration file://website.json
```
`website.json` ファイルは現在のフォルダ内の JSON ドキュメントで、ウェブサイトのインデックスページとエラーページを指定します。  

```
{
    "IndexDocument": {
        "Suffix": "index.html"
    },
    "ErrorDocument": {
        "Key": "error.html"
    }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutBucketWebsite](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-bucket-website.html)」を参照してください。**

### `put-object-acl`
<a name="s3_PutObjectAcl_cli_2_topic"></a>

次の例は、`put-object-acl` を使用する方法を説明しています。

**AWS CLI**  
次のコマンド`full control`は、2 人の AWS ユーザー (*user1@example.com* と *user2@example.com*) に を付与し、すべてのユーザーに アクセス`read`許可を付与します。  

```
aws s3api put-object-acl --bucket amzn-s3-demo-bucket --key file.txt --grant-full-control emailaddress=user1@example.com,emailaddress=user2@example.com --grant-read uri=http://acs.amazonaws.com/groups/global/AllUsers
```
カスタム ACL の詳細については、http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html を参照してください (`put-object-acl` などの s3api ACL コマンドは、同じ略記法を使用します)。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutObjectAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-object-acl.html)」を参照してください。**

### `put-object-legal-hold`
<a name="s3_PutObjectLegalHold_cli_2_topic"></a>

次のコード例は、`put-object-legal-hold` を使用する方法を示しています。

**AWS CLI**  
**リーガルホールドをオブジェクトに適用するには**  
次の `put-object-legal-hold` 例では、`doc1.rtf` という名前のバケットのオブジェクトにリーガルホールドを設定します。  

```
aws s3api put-object-legal-hold \
    --bucket amzn-s3-demo-bucket-with-object-lock \
    --key doc1.rtf \
    --legal-hold Status=ON
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObjectLegalHold](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-object-legal-hold.html)」を参照してください。

### `put-object-lock-configuration`
<a name="s3_PutObjectLockConfiguration_cli_2_topic"></a>

次のコード例は、`put-object-lock-configuration` を使用する方法を示しています。

**AWS CLI**  
**バケットにオブジェクトロック設定を指定するには**  
次の `put-object-lock-configuration` 例では、指定したバケットに 50 日間のオブジェクトロックを設定します。  

```
aws s3api put-object-lock-configuration \
    --bucket amzn-s3-demo-bucket-with-object-lock \
    --object-lock-configuration '{ "ObjectLockEnabled": "Enabled", "Rule": { "DefaultRetention": { "Mode": "COMPLIANCE", "Days": 50 }}}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObjectLockConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-object-lock-configuration.html)」を参照してください。

### `put-object-retention`
<a name="s3_PutObjectRetention_cli_2_topic"></a>

次のコード例は、`put-object-retention` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトのオブジェクト保持設定を指定するには**  
次の `put-object-retention` の例では、指定されたオブジェクトのオブジェクト保持設定を 2025-01-01 まで設定します。  

```
aws s3api put-object-retention \
    --bucket amzn-s3-demo-bucket-with-object-lock \
    --key doc1.rtf \
    --retention '{ "Mode": "GOVERNANCE", "RetainUntilDate": "2025-01-01T00:00:00" }'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObjectRetention](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-object-retention.html)」を参照してください。

### `put-object-tagging`
<a name="s3_PutObjectTagging_cli_2_topic"></a>

次のコード例は、`put-object-tagging` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトにタグを設定するには**  
次の `put-object-tagging` の例では、指定されたオブジェクトにキー `designation` と値 `confidential` を持つタグを設定します。  

```
aws s3api put-object-tagging \
    --bucket amzn-s3-demo-bucket \
    --key doc1.rtf \
    --tagging '{"TagSet": [{ "Key": "designation", "Value": "confidential" }]}'
```
このコマンドでは何も出力されません。  
次の `put-object-tagging` 例では、指定されたオブジェクトに複数のタグセットを設定します。  

```
aws s3api put-object-tagging \
    --bucket amzn-s3-demo-bucket-example \
    --key doc3.rtf \
    --tagging '{"TagSet": [{ "Key": "designation", "Value": "confidential" }, { "Key": "department", "Value": "finance" }, { "Key": "team", "Value": "payroll" } ]}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObjectTagging](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-object-tagging.html)」を参照してください。

### `put-object`
<a name="s3_PutObject_cli_2_topic"></a>

次のコード例は、`put-object` を使用する方法を示しています。

**AWS CLI**  
**例 1: オブジェクトを Amazon S3 にアップロードする**  
次の `put-object` コマンドの例では、オブジェクトを Amazon S3 にアップロードします。  

```
aws s3api put-object \
    --bucket amzn-s3-demo-bucket \
    --key my-dir/MySampleImage.png \
    --body MySampleImage.png
```
オブジェクトのアップロードの詳細については、*Amazon S3 デベロッパーガイド*の「オブジェクトのアップロード < http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html>」を参照してください。  
**例 2: ビデオファイルを Amazon S3 にアップロードする**  
次の `put-object` コマンドの例では、ビデオファイルをアップロードします。  

```
aws s3api put-object \
    --bucket amzn-s3-demo-bucket \
    --key my-dir/big-video-file.mp4 \
    --body /media/videos/f-sharp-3-data-services.mp4
```
オブジェクトのアップロードの詳細については、*Amazon S3 デベロッパーガイド*の「オブジェクトのアップロード < http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-object.html)」を参照してください。

### `put-public-access-block`
<a name="s3_PutPublicAccessBlock_cli_2_topic"></a>

次のコード例は、`put-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**バケットのブロックパブリックアクセス設定を指定するには**  
次の `put-public-access-block` の例では、指定されたバケットの制限ブロックパブリックアクセス設定を指定します。  

```
aws s3api put-public-access-block \
    --bucket amzn-s3-demo-bucket \
    --public-access-block-configuration "BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutPublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/put-public-access-block.html)」を参照してください。

### `rb`
<a name="s3_Rb_cli_2_topic"></a>

次のコード例は、`rb` を使用する方法を示しています。

**AWS CLI**  
**例 1: バケットを削除する**  
次の `rb` コマンドはバケットを削除します。この例では、ユーザーのバケットは `amzn-s3-demo-bucket` です。削除するには、バケットが空である必要があります。  

```
aws s3 rb s3://amzn-s3-demo-bucket
```
出力:  

```
remove_bucket: amzn-s3-demo-bucket
```
**例 2: バケットを強制的に削除する**  
次の `rb` コマンドは、`--force` パラメータを使用して、まずバケット内のすべてのオブジェクトを削除し、次にバケット自体を削除します。この例では、ユーザーのバケットは `amzn-s3-demo-bucket` で、`amzn-s3-demo-bucket` 内のオブジェクトは `test1.txt` および `test2.txt` です。  

```
aws s3 rb s3://amzn-s3-demo-bucket \
    --force
```
出力:  

```
delete: s3://amzn-s3-demo-bucket/test1.txt
delete: s3://amzn-s3-demo-bucket/test2.txt
remove_bucket: amzn-s3-demo-bucket
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Rb](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/rb.html)」を参照してください。

### `restore-object`
<a name="s3_RestoreObject_cli_2_topic"></a>

次のコード例は、`restore-object` を使用する方法を示しています。

**AWS CLI**  
**オブジェクトの復元リクエストを作成するには**  
次の `restore-object` の例では、指定された Amazon S3 Glacier オブジェクトをバケット `my-glacier-bucket` に 10 日間復元します。  

```
aws s3api restore-object \
    --bucket my-glacier-bucket \
    --key doc1.rtf \
    --restore-request Days=10
```
このコマンドでは何も出力されません。  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[RestoreObject](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/restore-object.html)」を参照してください。

### `rm`
<a name="s3_Rm_cli_2_topic"></a>

次のコード例は、`rm` を使用する方法を示しています。

**AWS CLI**  
**例 1: S3 オブジェクトを削除する**  
次の `rm` コマンドは、単一の s3 オブジェクトを削除します。  

```
aws s3 rm s3://amzn-s3-demo-bucket/test2.txt
```
出力:  

```
delete: s3://amzn-s3-demo-bucket/test2.txt
```
**例 2: バケット内のすべてのコンテンツを削除する**  
次の `rm` コマンドは、パラメータ `--recursive` で渡されると、指定されたバケットとプレフィックスのすべてのオブジェクトを再帰的に削除します。この例では、バケット `amzn-s3-demo-bucket` にオブジェクト `test1.txt` と `test2.txt` が含まれています。  

```
aws s3 rm s3://amzn-s3-demo-bucket \
    --recursive
```
出力:  

```
delete: s3://amzn-s3-demo-bucket/test1.txt
delete: s3://amzn-s3-demo-bucket/test2.txt
```
**例 3: 「.jpg」ファイルを除くバケット内のすべてのコンテンツを削除する**  
次の `rm` コマンドは、パラメータ `--recursive` で渡されたときに、パラメータ `--exclude` を使用して一部のオブジェクトを除外しながら、指定されたバケットとプレフィックス内のすべてのオブジェクトを再帰的に削除します。この例では、バケット `amzn-s3-demo-bucket` にはオブジェクト `test1.txt` と `test2.jpg` があります。  

```
aws s3 rm s3://amzn-s3-demo-bucket/ \
    --recursive \
    --exclude "*.jpg"
```
出力:  

```
delete: s3://amzn-s3-demo-bucket/test1.txt
```
**例 4: 指定されたプレフィックスの下にあるオブジェクトを除く、バケット内のすべてのコンテンツを削除する**  
次の `rm` コマンドは、パラメータ `--recursive` で渡されたときに、パラメータ `--exclude` を使用して特定のプレフィックス内のオブジェクトをすべて除外しながら、指定されたバケットとプレフィックス内のすべてのオブジェクトを再帰的に削除します。この例では、バケット `amzn-s3-demo-bucket` にはオブジェクト `test1.txt` と `another/test.txt` があります。  

```
aws s3 rm s3://amzn-s3-demo-bucket/ \
    --recursive \
    --exclude "another/*"
```
出力:  

```
delete: s3://amzn-s3-demo-bucket/test1.txt
```
**例 5: S3 アクセスポイントからオブジェクトを削除する**  
次の `rm` コマンドは、アクセスポイント (`myaccesspoint`) から単一のオブジェクト (`mykey`) を削除します。:: 次の `rm` コマンドは、アクセスポイント (`myaccesspoint`) から単一のオブジェクト (`mykey`) を削除します。  

```
aws s3 rm s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey
```
出力:  

```
delete: s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/mykey
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Rm](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/rm.html)」を参照してください。

### `select-object-content`
<a name="s3_SelectObjectContent_cli_2_topic"></a>

次のコード例は、`select-object-content` を使用する方法を示しています。

**AWS CLI**  
**SQL ステートメントに基づいて Amazon S3 オブジェクトの内容をフィルタリングするには**  
次の `select-object-content` 例では、指定された SQL ステートメントで `my-data-file.csv` オブジェクトをフィルタリングし、出力をファイルに送信します。  

```
aws s3api select-object-content \
    --bucket amzn-s3-demo-bucket \
    --key my-data-file.csv \
    --expression "select * from s3object limit 100" \
    --expression-type 'SQL' \
    --input-serialization '{"CSV": {}, "CompressionType": "NONE"}' \
    --output-serialization '{"CSV": {}}' "output.csv"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SelectObjectContent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/select-object-content.html)」を参照してください。

### `sync`
<a name="s3_Sync_cli_2_topic"></a>

次のコード例は、`sync` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのローカルオブジェクトを指定されたバケットに同期する**  
次の `sync` コマンドは、ローカルファイルを S3 にアップロードすることで、ローカルディレクトリから指定されたプレフィックスとバケットにオブジェクトを同期します。ローカルファイルのサイズが S3 オブジェクトのサイズと異なる場合、ローカルファイルの最終変更時刻が S3 オブジェクトの最終変更時刻よりも新しい場合、またはローカルファイルが指定されたバケットとプレフィックスの下に存在しない場合、ローカルファイルのアップロードが必要になります。この例では、ユーザーはバケット `amzn-s3-demo-bucket` をローカルの現在のディレクトリに同期します。ローカルの現在のディレクトリには、`test.txt` ファイルと `test2.txt` ファイルが含まれています。バケット `amzn-s3-demo-bucket` にはオブジェクトが含まれていません。  

```
aws s3 sync . s3://amzn-s3-demo-bucket
```
出力:  

```
upload: test.txt to s3://amzn-s3-demo-bucket/test.txt
upload: test2.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 2: 指定された S3 バケットから別のバケットにすべての S3 オブジェクトを同期する**  
次の `sync` コマンドは、S3 オブジェクトをコピーすることで、指定されたプレフィックスとバケットの下のオブジェクトを、別の指定されたプレフィックスとバケットの下のオブジェクトに同期します。2 つの S3 オブジェクトのサイズが異なる場合、ソースの最終変更時刻が送信先の最終変更時刻よりも新しい場合、または指定されたバケットとプレフィックスの送信先の下に S3 オブジェクトが存在しない場合、S3 オブジェクトをコピーする必要があります。  
この例では、ユーザーはバケット `amzn-s3-demo-bucket` をバケット `amzn-s3-demo-bucket2` に同期します。バケット `amzn-s3-demo-bucket` には、 オブジェクト `test.txt` と `test2.txt` が含まれています。バケット `amzn-s3-demo-bucket2` にはオブジェクトが含まれていません。  

```
aws s3 sync s3://amzn-s3-demo-bucket s3://amzn-s3-demo-bucket2
```
出力:  

```
copy: s3://amzn-s3-demo-bucket/test.txt to s3://amzn-s3-demo-bucket2/test.txt
copy: s3://amzn-s3-demo-bucket/test2.txt to s3://amzn-s3-demo-bucket2/test2.txt
```
**例 3: 指定された S3 バケットからローカルディレクトリにすべての S3 オブジェクトを同期する**  
次の `sync` コマンドは、S3 オブジェクトをダウンロードすることで、指定された S3 バケットからローカルディレクトリにファイルを同期します。S3 オブジェクトのサイズがローカルファイルのサイズと異なる場合、S3 オブジェクトの最終変更時刻がローカルファイルの最終変更時刻よりも新しい場合、または S3 オブジェクトがローカルディレクトリに存在しない場合、S3 オブジェクトのダウンロードが必要になります。オブジェクトが S3 からダウンロードされると、ローカルファイルの最終変更時刻が S3 オブジェクトの最終変更時刻に変更されることに注意してください。この例では、ユーザーはバケット `amzn-s3-demo-bucket` を現在のローカルディレクトリに同期します。バケット `amzn-s3-demo-bucket` には、オブジェクト `test.txt` と `test2.txt` が含まれています。現在のローカルディレクトリにはファイルがありません。  

```
aws s3 sync s3://amzn-s3-demo-bucket .
```
出力:  

```
download: s3://amzn-s3-demo-bucket/test.txt to test.txt
download: s3://amzn-s3-demo-bucket/test2.txt to test2.txt
```
**例 4: すべてのローカルオブジェクトを指定されたバケットに同期し、一致しないすべてのファイルを削除する**  
次の `sync` コマンドは、ローカルファイルを S3 にアップロードすることで、指定されたプレフィックスとバケットの下にあるオブジェクトをローカルディレクトリ内のファイルに同期します。パラメータ `--delete` により、指定されたプレフィックスとバケットの下には存在するが、ローカルディレクトリには存在しないファイルはすべて削除されます。この例では、ユーザーはバケット `amzn-s3-demo-bucket` をローカルの現在のディレクトリに同期します。ローカルの現在のディレクトリには、`test.txt` ファイルと `test2.txt` ファイルが含まれています。バケット `amzn-s3-demo-bucket` にはオブジェクト `test3.txt` が含まれます。  

```
aws s3 sync . s3://amzn-s3-demo-bucket \
    --delete
```
出力:  

```
upload: test.txt to s3://amzn-s3-demo-bucket/test.txt
upload: test2.txt to s3://amzn-s3-demo-bucket/test2.txt
delete: s3://amzn-s3-demo-bucket/test3.txt
```
**例 5: 「.jpg」ファイルを除くすべてのローカルオブジェクトを指定されたバケットに同期する**  
次の `sync` コマンドは、ローカルファイルを S3 にアップロードすることで、指定されたプレフィックスとバケットの下にあるオブジェクトをローカルディレクトリ内のファイルに同期します。`--exclude` パラメータにより、S3 とローカルの両方に存在するパターンに一致するすべてのファイルは同期から除外されます。この例では、ユーザーはバケット `amzn-s3-demo-bucket` をローカルの現在のディレクトリに同期します。ローカルの現在のディレクトリには、`test.jpg` ファイルと `test2.txt` ファイルが含まれています。バケット `amzn-s3-demo-bucket` には、ローカルの `test.jpg` とは異なるサイズのオブジェクト `test.jpg` が含まれています。  

```
aws s3 sync . s3://amzn-s3-demo-bucket \
    --exclude "*.jpg"
```
出力:  

```
upload: test2.txt to s3://amzn-s3-demo-bucket/test2.txt
```
**例 6: 指定したディレクトリファイルを除くすべてのローカルオブジェクトを指定したバケットに同期する**  
次の `sync` コマンドは、S3 オブジェクトをダウンロードすることで、ローカルディレクトリの下にあるファイルを、指定されたプレフィックスとバケットの下にあるオブジェクトに同期します。この例では、`--exclude` パラメータフラグを使用して、指定されたディレクトリと S3 プレフィックスを `sync` コマンドから除外します。この例では、ユーザーはローカルの現在のディレクトリをバケット `amzn-s3-demo-bucket` に同期します。ローカルの現在のディレクトリには、`test.txt` ファイルと `another/test2.txt` ファイルが含まれています。バケット `amzn-s3-demo-bucket` には、オブジェクト `another/test5.txt` と `test1.txt` が含まれます。  

```
aws s3 sync s3://amzn-s3-demo-bucket/ . \
    --exclude "*another/*"
```
出力:  

```
download: s3://amzn-s3-demo-bucket/test1.txt to test1.txt
```
**例 7: 異なるリージョンのバケット間ですべてのオブジェクトを同期する**  
次の `sync` コマンドは、異なるリージョンの 2 つのバケット間でファイルを同期します。  

```
aws s3 sync s3://my-us-west-2-bucket s3://my-us-east-1-bucket \
    --source-region us-west-2 \
    --region us-east-1
```
出力:  

```
download: s3://my-us-west-2-bucket/test1.txt to s3://my-us-east-1-bucket/test1.txt
```
**例 8: S3 アクセスポイントに同期する**  
次の `sync` コマンドは、現在のディレクトリをアクセスポイント (`myaccesspoint`) に同期します。  

```
aws s3 sync . s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/
```
出力:  

```
upload: test.txt to s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/test.txt
upload: test2.txt to s3://arn:aws:s3:us-west-2:123456789012:accesspoint/myaccesspoint/test2.txt
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Sync](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/sync.html)」を参照してください。

### `upload-part-copy`
<a name="s3_UploadPartCopy_cli_2_topic"></a>

次のコード例は、`upload-part-copy` を使用する方法を示しています。

**AWS CLI**  
**既存のオブジェクトからデータソースとしてデータをコピーしてオブジェクトの一部をアップロードするには**  
次の `upload-part-copy` 例では、既存のオブジェクトからデータをデータソースとしてコピーし、一部をアップロードします。  

```
aws s3api upload-part-copy \
    --bucket amzn-s3-demo-bucket \
    --key "Map_Data_June.mp4" \
    --copy-source "amzn-s3-demo-bucket/copy_of_Map_Data_June.mp4" \
    --part-number 1 \
    --upload-id "bq0tdE1CDpWQYRPLHuNG50xAT6pA5D.m_RiBy0ggOH6b13pVRY7QjvLlf75iFdJqp_2wztk5hvpUM2SesXgrzbehG5hViyktrfANpAD0NO.Nk3XREBqvGeZF6U3ipiSm"
```
出力:  

```
{
    "CopyPartResult": {
        "LastModified": "2019-12-13T23:16:03.000Z",
        "ETag": "\"711470fc377698c393d94aed6305e245\""
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UploadPartCopy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/upload-part-copy.html)」を参照してください。

### `upload-part`
<a name="s3_UploadPart_cli_2_topic"></a>

次のコード例は、`upload-part` を使用する方法を示しています。

**AWS CLI**  
次のコマンドは、`create-multipart-upload` コマンドで開始されたマルチパートアップロードの最初の部分をアップロードします。  

```
aws s3api upload-part --bucket amzn-s3-demo-bucket --key 'multipart/01' --part-number 1 --body part01 --upload-id  "dfRtDYU0WWCCcH43C3WFbkRONycyCpTJJvxu2i5GYkZljF.Yxwh6XG7WfS2vC4to6HiV6Yjlx.cph0gtNBtJ8P3URCSbB7rjxI5iEwVDmgaXZOGgkk5nVTW16HOQ5l0R"
```
`body` オプションは、アップロードするローカルファイルの名前またはパスを指定します (file://プレフィックスは使用しないでください)。各パートの最小サイズは 5 MB です。アップロード ID は `create-multipart-upload` によって返され、`list-multipart-uploads` を使用して取得することもできます。バケットとキーは、マルチパートアップロードの作成時に指定されます。  
出力:  

```
{
    "ETag": "\"e868e0f4719e394144ef36531ee6824c\""
}
```
後で使用できるように、各パートの ETag 値を保存します。これらはマルチパートアップロードを完了するために必要です。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UploadPart](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/upload-part.html)」を参照してください。**

### `website`
<a name="s3_Website_cli_2_topic"></a>

次のコード例は、`website` を使用する方法を示しています。

**AWS CLI**  
**S3 バケットを静的ウェブサイトとして設定する**  
次のコマンドは、`amzn-s3-demo-bucket` という名前のバケットを静的ウェブサイトとして設定します。インデックスドキュメントオプションは、訪問者がウェブサイト URL に移動するときに誘導される `amzn-s3-demo-bucket` のファイルを指定します。この場合、バケットは us-west-2 リージョンにあるため、サイトは `http://amzn-s3-demo-bucket.s3-website-us-west-2.amazonaws.com` に表示されます。  
静的サイトに表示されるバケット内のすべてのファイルは、訪問者が開けるように設定する必要があります。ファイルアクセス許可は、バケットウェブサイトの設定とは別に設定されます。  

```
aws s3 website s3://amzn-s3-demo-bucket/ \
    --index-document index.html \
    --error-document error.html
```
Amazon S3 での静的ウェブサイトのホスティングに関する詳細については、「*Amazon Simple Storage Service デベロッパーガイドガイド*」の「[静的ウェブサイトをホスティングする](https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteHosting.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Website](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3api/website.html)」を参照してください。

# を使用した Amazon S3 Control の例 AWS CLI
<a name="cli_2_s3-control_code_examples"></a>

次のコード例は、Amazon S3 Control AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-access-point`
<a name="s3-control_CreateAccessPoint_cli_2_topic"></a>

次のコード例は、`create-access-point` を使用する方法を示しています。

**AWS CLI**  
**アクセスポイントを作成するには**  
次の `create-access-point` の例では、アカウント 123456789012 のバケット `business-records` に `finance-ap` という名前のアクセスポイントを作成します。この例を実行する前に、アクセスポイント名、バケット名、アカウント番号をユースケースに適した値に置き換えます。  

```
aws s3control create-access-point \
    --account-id 123456789012 \
    --bucket business-records \
    --name finance-ap
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[アクセスポイントの作成](https://docs.aws.amazon.com/AmazonS3/latest/dev/creating-access-points.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAccessPoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/create-access-point.html)」を参照してください。

### `create-job`
<a name="s3-control_CreateJob_cli_2_topic"></a>

次のコード例は、`create-job` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 バッチオペレーションジョブを作成するには**  
次の `create-job` の例では、オブジェクトを `confidential` in the bucket ``employee-records` としてタグ付けする Amazon S3 バッチオペレーションジョブを作成します。  

```
aws s3control create-job \
    --account-id 123456789012 \
    --operation '{"S3PutObjectTagging": { "TagSet": [{"Key":"confidential", "Value":"true"}] }}' \
    --report '{"Bucket":"arn:aws:s3:::employee-records-logs","Prefix":"batch-op-create-job", "Format":"Report_CSV_20180820","Enabled":true,"ReportScope":"AllTasks"}' \
    --manifest '{"Spec":{"Format":"S3BatchOperations_CSV_20180820","Fields":["Bucket","Key"]},"Location":{"ObjectArn":"arn:aws:s3:::employee-records-logs/inv-report/7a6a9be4-072c-407e-85a2-ec3e982f773e.csv","ETag":"69f52a4e9f797e987155d9c8f5880897"}}' \
    --priority 42 \
    --role-arn arn:aws:iam::123456789012:role/S3BatchJobRole
```
出力:  

```
{
    "JobId": "93735294-df46-44d5-8638-6356f335324e"
}
```
+  API の詳細については、*AWS CLI コマンドリファレンス* の「[CreateJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/create-job.html)」を参照してください。

### `delete-access-point-policy`
<a name="s3-control_DeleteAccessPointPolicy_cli_2_topic"></a>

次のコード例は、`delete-access-point-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセスポイントポリシーを削除するには**  
次の `delete-access-point-policy` の例では、アカウント 123456789012 の `finance-ap` という名前のアクセスポイントからアクセスポイントポリシーを削除します。この例を実行する前に、アクセスポイント名とアカウント番号をユースケースに適した値に置き換えます。  

```
aws s3control delete-access-point-policy \
    --account-id 123456789012 \
    --name finance-ap
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[Amazon S3 Access Points を使用したデータアクセスの管理](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessPointPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/delete-access-point-policy.html)」を参照してください。

### `delete-access-point`
<a name="s3-control_DeleteAccessPoint_cli_2_topic"></a>

次のコード例は、`delete-access-point` を使用する方法を示しています。

**AWS CLI**  
**アクセスポイントを削除するには**  
次の `delete-access-point` の例では、アカウント 123456789012 で `finance-ap` という名前のアクセスポイントを削除します。この例を実行する前に、アクセスポイント名とアカウント番号をユースケースに適した値に置き換えます。  

```
aws s3control delete-access-point \
    --account-id 123456789012 \
    --name finance-ap
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[Amazon S3 Access Points を使用したデータアクセスの管理](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessPoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/delete-access-point.html)」を参照してください。

### `delete-public-access-block`
<a name="s3-control_DeletePublicAccessBlock_cli_2_topic"></a>

次のコード例は、`delete-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**アカウントのブロックパブリックアクセス設定を削除するには**  
次の `delete-public-access-block` の例では、指定されたアカウントのブロックパブリックアクセス設定を削除します。  

```
aws s3control delete-public-access-block \
    --account-id 123456789012
```
このコマンドでは何も出力されません。  
+  API の詳細については、「**AWS CLI コマンドリファレンス」の「[DeletePublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/delete-public-access-block.html)」を参照してください。

### `describe-job`
<a name="s3-control_DescribeJob_cli_2_topic"></a>

次のコード例は、`describe-job` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 バッチオペレーションジョブを記述するには**  
次の `describe-job` の例では、指定されたバッチオペレーションジョブの設定パラメータとステータスを示します。  

```
aws s3control describe-job \
    --account-id 123456789012 \
    --job-id 93735294-df46-44d5-8638-6356f335324e
```
出力:  

```
{
    "Job": {
        "TerminationDate": "2019-10-03T21:49:53.944Z",
        "JobId": "93735294-df46-44d5-8638-6356f335324e",
        "FailureReasons": [],
        "Manifest": {
            "Spec": {
                "Fields": [
                    "Bucket",
                    "Key"
                ],
                "Format": "S3BatchOperations_CSV_20180820"
            },
            "Location": {
                "ETag": "69f52a4e9f797e987155d9c8f5880897",
                "ObjectArn": "arn:aws:s3:::employee-records-logs/inv-report/7a6a9be4-072c-407e-85a2-ec3e982f773e.csv"
            }
        },
        "Operation": {
            "S3PutObjectTagging": {
                "TagSet": [
                    {
                        "Value": "true",
                        "Key": "confidential"
                    }
                ]
            }
        },
        "RoleArn": "arn:aws:iam::123456789012:role/S3BatchJobRole",
        "ProgressSummary": {
            "TotalNumberOfTasks": 8,
            "NumberOfTasksFailed": 0,
            "NumberOfTasksSucceeded": 8
        },
        "Priority": 42,
        "Report": {
            "ReportScope": "AllTasks",
            "Format": "Report_CSV_20180820",
            "Enabled": true,
            "Prefix": "batch-op-create-job",
            "Bucket": "arn:aws:s3:::employee-records-logs"
        },
        "JobArn": "arn:aws:s3:us-west-2:123456789012:job/93735294-df46-44d5-8638-6356f335324e",
        "CreationTime": "2019-10-03T21:48:48.048Z",
        "Status": "Complete"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/describe-job.html)」を参照してください。

### `get-access-point-policy-status`
<a name="s3-control_GetAccessPointPolicyStatus_cli_2_topic"></a>

次のコード例は、`get-access-point-policy-status` を使用する方法を示しています。

**AWS CLI**  
**アクセスポイントポリシーのステータスを取得するには**  
次の `get-access-point-policy-status` の例では、アカウント 123456789012 で `finance-ap` という名前のアクセスポイントのアクセスポイントポリシーステータスを取得します。アクセスポイントポリシーのステータスは、アクセスポイントのポリシーがパブリックアクセスを許可するかどうかを示します。この例を実行する前に、アクセスポイント名とアカウント番号をユースケースに適した値に置き換えます。  

```
aws s3control get-access-point-policy-status \
    --account-id 123456789012 \
    --name finance-ap
```
出力:  

```
{
    "PolicyStatus": {
        "IsPublic": false
    }
}
```
アクセスポイントポリシーをパブリックと見なす場合の詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[『パブリック』の意味](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html#access-control-block-public-access-policy-status)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccessPointPolicyStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/get-access-point-policy-status.html)」を参照してください。

### `get-access-point-policy`
<a name="s3-control_GetAccessPointPolicy_cli_2_topic"></a>

次のコード例は、`get-access-point-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセスポイントポリシーを取得するには**  
次の `get-access-point-policy` の例では、アカウント 123456789012 の `finance-ap` という名前のアクセスポイントからアクセスポイントポリシーを取得します。この例を実行する前に、アクセスポイント名とアカウント番号をユースケースに適した値に置き換えます。  

```
aws s3control get-access-point-policy \
    --account-id 123456789012 \
    --name finance-ap
```
出力:  

```
{
    "Policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:role/Admin\"},\"Action\":\"s3:GetObject\",\"Resource\":\"arn:aws:s3:us-west-2:123456789012:accesspoint/finance-ap/object/records/*\"}]}"
}
```
詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[Amazon S3 Access Points を使用したデータアクセスの管理](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccessPointPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/get-access-point-policy.html)」を参照してください。

### `get-access-point`
<a name="s3-control_GetAccessPoint_cli_2_topic"></a>

次のコード例は、`get-access-point` を使用する方法を示しています。

**AWS CLI**  
**アクセスポイントの設定の詳細を取得するには**  
以下の `get-access-point` の例では、アカウント 123456789012 の `finance-ap` というアクセスポイントの設定の詳細を取得します。この例を実行する前に、アクセスポイント名とアカウント番号をユースケースに適した値に置き換えます。  

```
aws s3control get-access-point \
    --account-id 123456789012 \
    --name finance-ap
```
出力:  

```
{
    "Name": "finance-ap",
    "Bucket": "business-records",
    "NetworkOrigin": "Internet",
    "PublicAccessBlockConfiguration": {
        "BlockPublicAcls": false,
        "IgnorePublicAcls": false,
        "BlockPublicPolicy": false,
        "RestrictPublicBuckets": false
    },
    "CreationDate": "2020-01-01T00:00:00Z"
}
```
詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[Amazon S3 Access Points を使用したデータアクセスの管理](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccessPoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/get-access-point.html)」を参照してください。

### `get-multi-region-access-point-routes`
<a name="s3-control_GetMultiRegionAccessPointRoutes_cli_2_topic"></a>

次のコード例は、`get-multi-region-access-point-routes` を使用する方法を示しています。

**AWS CLI**  
**現在の Multi-Region Access Point ルート設定をクエリするには**  
次の `get-multi-region-access-point-routes` の例では、指定された Multi-Region Access Point の現在のルート設定を返します。  

```
aws s3control get-multi-region-access-point-routes \
    --region Region \
    --account-id 111122223333 \
    --mrap MultiRegionAccessPoint_ARN
```
出力:  

```
{
    "Mrap": "arn:aws:s3::111122223333:accesspoint/0000000000000.mrap",
    "Routes": [
        {
            "Bucket": "amzn-s3-demo-bucket1",
            "Region": "ap-southeast-2",
            "TrafficDialPercentage": 100
        },
        {
            "Bucket": "amzn-s3-demo-bucket2",
            "Region": "us-west-1",
            "TrafficDialPercentage": 0
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMultiRegionAccessPointRoutes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/get-multi-region-access-point-routes.html)」を参照してください。

### `get-public-access-block`
<a name="s3-control_GetPublicAccessBlock_cli_2_topic"></a>

次のコード例は、`get-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**アカウントのパブリックアクセスブロックの設定を一覧表示するには**  
次の `get-public-access-block` の例では、指定されたアカウントのブロックパブリックアクセス設定を表示します。  

```
aws s3control get-public-access-block \
    --account-id 123456789012
```
出力:  

```
{
   "PublicAccessBlockConfiguration": {
      "BlockPublicPolicy": true,
      "RestrictPublicBuckets": true,
      "IgnorePublicAcls": true,
      "BlockPublicAcls": true
   }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/get-public-access-block.html)」を参照してください。

### `list-access-points`
<a name="s3-control_ListAccessPoints_cli_2_topic"></a>

次のコード例は、`list-access-points` を使用する方法を示しています。

**AWS CLI**  
**例 1: アカウントのすべてのアクセスポイントのリストを取得するには**  
次の `list-access-points` の例では、アカウント 123456789012 が所有するバケットにアタッチされたすべてのアクセスポイントのリストを表示します。  

```
aws s3control list-access-points \
    --account-id 123456789012
```
出力:  

```
{
    "AccessPointList": [
        {
            "Name": "finance-ap",
            "NetworkOrigin": "Internet",
            "Bucket": "business-records"
        },
        {
            "Name": "managers-ap",
            "NetworkOrigin": "Internet",
            "Bucket": "business-records"
        },
        {
            "Name": "private-network-ap",
            "NetworkOrigin": "VPC",
            "VpcConfiguration": {
                "VpcId": "1a2b3c"
            },
            "Bucket": "business-records"
        },
        {
            "Name": "customer-ap",
            "NetworkOrigin": "Internet",
            "Bucket": "external-docs"
        },
        {
            "Name": "public-ap",
            "NetworkOrigin": "Internet",
            "Bucket": "external-docs"
        }
    ]
}
```
**例 2: バケットのすべてのアクセスポイントのリストを取得するには**  
次の `list-access-points` の例では、アカウント 123456789012 が所有するバケット `external-docs` にアタッチされたすべてのアクセスポイントのリストを取得します。  

```
aws s3control list-access-points \
    --account-id 123456789012 \
    --bucket external-docs
```
出力:  

```
{
    "AccessPointList": [
        {
            "Name": "customer-ap",
            "NetworkOrigin": "Internet",
            "Bucket": "external-docs"
        },
        {
            "Name": "public-ap",
            "NetworkOrigin": "Internet",
            "Bucket": "external-docs"
        }
    ]
}
```
詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[Amazon S3 Access Points を使用したデータアクセスの管理](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessPoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/list-access-points.html)」を参照してください。

### `list-jobs`
<a name="s3-control_ListJobs_cli_2_topic"></a>

次のコード例は、`list-jobs` を使用する方法を示しています。

**AWS CLI**  
**アカウント Amazon S3 バッチオペレーションジョブを一覧表示するには**  
次の `list-jobs` の例では、指定されたアカウントの最近のバッチオペレーションジョブをすべて一覧表示します。  

```
aws s3control list-jobs \
    --account-id 123456789012
```
出力:  

```
{
    "Jobs": [
        {
            "Operation": "S3PutObjectTagging",
            "ProgressSummary": {
                "NumberOfTasksFailed": 0,
                "NumberOfTasksSucceeded": 8,
                "TotalNumberOfTasks": 8
            },
            "CreationTime": "2019-10-03T21:48:48.048Z",
            "Status": "Complete",
            "JobId": "93735294-df46-44d5-8638-6356f335324e",
            "Priority": 42
        },
        {
            "Operation": "S3PutObjectTagging",
            "ProgressSummary": {
                "NumberOfTasksFailed": 0,
                "NumberOfTasksSucceeded": 0,
                "TotalNumberOfTasks": 0
            },
            "CreationTime": "2019-10-03T21:46:07.084Z",
            "Status": "Failed",
            "JobId": "3f3c7619-02d3-4779-97f6-1d98dd313108",
            "Priority": 42
        },
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/list-jobs.html)」を参照してください。

### `put-access-point-policy`
<a name="s3-control_PutAccessPointPolicy_cli_2_topic"></a>

次のコード例は、`put-access-point-policy` を使用する方法を示しています。

**AWS CLI**  
**アクセスポイントポリシーを設定するには**  
次の `put-access-point-policy` の例では、アクセスポイント `finance-ap` の指定されたアクセスポイントポリシーをアカウント 123456789012 に配置します。アクセスポイント `finance-ap` に既にポリシーがある場合、このコマンドは既存のポリシーをこのコマンドで指定されたポリシーに置き換えます。この例を実行する前に、アカウント番号、アクセスポイント名、ポリシーステートメントをユースケースに適した値に置き換えます。  

```
aws s3control put-access-point-policy \
    --account-id 123456789012 \
    --name finance-ap \
    --policy file://ap-policy.json
```
`ap-policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:user/Alice"
            },
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:us-west-2:123456789012:accesspoint/finance-ap/object/Alice/*"
        }
    ]
}
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Simple Storage Service デベロッパーガイド*」の「[Amazon S3 Access Points を使用したデータアクセスの管理](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-points.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAccessPointPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/put-access-point-policy.html)」を参照してください。

### `put-public-access-block`
<a name="s3-control_PutPublicAccessBlock_cli_2_topic"></a>

次のコード例は、`put-public-access-block` を使用する方法を示しています。

**AWS CLI**  
**アカウントのブロックパブリックアクセス設定を編集するには**  
次の `put-public-access-block` の例では、指定されたアカウントのブロックパブリックアクセス設定をすべて `true` に切り替えます。  

```
aws s3control put-public-access-block \
    --account-id 123456789012 \
    --public-access-block-configuration '{"BlockPublicAcls": true, "IgnorePublicAcls": true, "BlockPublicPolicy": true, "RestrictPublicBuckets": true}'
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutPublicAccessBlock](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/put-public-access-block.html)」を参照してください。

### `submit-multi-region-access-point-routes`
<a name="s3-control_SubmitMultiRegionAccessPointRoutes_cli_2_topic"></a>

次のコード例は、`submit-multi-region-access-point-routes` を使用する方法を示しています。

**AWS CLI**  
**マルチリージョンアクセスポイントのルーティング設定を更新するには**  
次の `submit-multi-region-access-point-routes` の例では、マルチリージョンアクセスポイントの `ap-southeast-2` リージョンでの `amzn-s3-demo-bucket1` および `amzn-s3-demo-bucket2` のルーティングステータスを更新します。  

```
aws s3control submit-multi-region-access-point-routes \
    --region ap-southeast-2 \
    --account-id 111122223333 \
    --mrap MultiRegionAccessPoint_ARN \
    --route-updates Bucket=amzn-s3-demo-bucket1,TrafficDialPercentage=100 Bucket=amzn-s3-demo-bucket2,TrafficDialPercentage=0
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SubmitMultiRegionAccessPointRoutes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/submit-multi-region-access-point-routes.html)」を参照してください。

### `update-job-priority`
<a name="s3-control_UpdateJobPriority_cli_2_topic"></a>

次のコード例は、`update-job-priority` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 バッチオペレーションジョブのジョブ優先度を更新するには**  
次の `update-job-priority` の例では、指定されたジョブを新しい優先度に更新します。  

```
aws s3control update-job-priority \
    --account-id 123456789012 \
    --job-id 8d9a18fe-c303-4d39-8ccc-860d372da386 \
    --priority 52
```
出力:  

```
{
    "JobId": "8d9a18fe-c303-4d39-8ccc-860d372da386",
    "Priority": 52
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateJobPriority](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/update-job-priority.html)」を参照してください。

### `update-job-status`
<a name="s3-control_UpdateJobStatus_cli_2_topic"></a>

次のコード例は、`update-job-status` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 バッチオペレーションジョブのステータスを更新するには**  
次の `update-job-status` の例では、承認待ちの指定されたジョブをキャンセルします。  

```
aws s3control update-job-status \
    --account-id 123456789012 \
    --job-id 8d9a18fe-c303-4d39-8ccc-860d372da386 \
    --requested-job-status Cancelled
```
出力:  

```
{
    "Status": "Cancelled",
    "JobId": "8d9a18fe-c303-4d39-8ccc-860d372da386"
}
```
次の `update-job-status` の例では、承認待ちの指定されたジョブを確認して実行します。  

```
aws s3control update-job-status \
    --account-id 123456789012 \
    --job-id 5782949f-3301-4fb3-be34-8d5bab54dbca \
    --requested-job-status Ready

Output::

{
    "Status": "Ready",
    "JobId": "5782949f-3301-4fb3-be34-8d5bab54dbca"
}
```
次の `update-job-status` の例では、実行中の指定されたジョブをキャンセルします。  

```
 aws s3control update-job-status \
    --account-id 123456789012 \
    --job-id 5782949f-3301-4fb3-be34-8d5bab54dbca \
    --requested-job-status Cancelled

Output::
{
         "Status": "Cancelling",
         "JobId": "5782949f-3301-4fb3-be34-8d5bab54dbca"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateJobStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3control/update-job-status.html)」を参照してください。

# を使用した Secrets Manager の例 AWS CLI
<a name="cli_2_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-get-secret-value`
<a name="secrets-manager_BatchGetSecretValue_cli_2_topic"></a>

次のコード例は、`batch-get-secret-value` を使用する方法を示しています。

**AWS CLI**  
**例 1: 名前順に表示されたシークレットグループのシークレット値を取得するには**  
次の `batch-get-secret-value` の例では、3 つのシークレットのシークレット値を取得します。  

```
aws secretsmanager batch-get-secret-value \
    --secret-id-list MySecret1 MySecret2 MySecret3
```
出力:  

```
{
    "SecretValues": [
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MySecret1-a1b2c3",
            "Name": "MySecret1",
            "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLEaaaaa",
            "SecretString": "{\"username\":\"diego_ramirez\",\"password\":\"EXAMPLE-PASSWORD\",\"engine\":\"mysql\",\"host\":\"secretsmanagertutorial.cluster.us-west-2.rds.amazonaws.com\",\"port\":3306,\"dbClusterIdentifier\":\"secretsmanagertutorial\"}",
            "VersionStages": [
                "AWSCURRENT"
            ],
            "CreatedDate": "1523477145.729"
        },
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MySecret2-a1b2c3",
            "Name": "MySecret2",
            "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLEbbbbb",
            "SecretString": "{\"username\":\"akua_mansa\",\"password\":\"EXAMPLE-PASSWORD\"",
            "VersionStages": [
                "AWSCURRENT"
            ],
            "CreatedDate": "1673477781.275"
        },
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MySecret3-a1b2c3",
            "Name": "MySecret3",
            "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLEccccc",
            "SecretString": "{\"username\":\"jie_liu\",\"password\":\"EXAMPLE-PASSWORD\"",
            "VersionStages": [
                "AWSCURRENT"
            ],
            "CreatedDate": "1373477721.124"
        }
    ],
    "Errors": []
}
```
詳細については、「*AWS Secrets Manager ユーザーガイド*」の「[バッチ内のシークレットのグループを取得する](https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets_batch.html)」を参照してください。  
**例 2: フィルターで選択されたシークレットグループのシークレット値を取得するには**  
次の `batch-get-secret-value` の例は、アカウント内にあり、名前に `MySecret` が含まれているシークレット値のシークレットを取得します。名前によるフィルタリングでは、大文字と小文字が区別されます。  

```
aws secretsmanager batch-get-secret-value \
    --filters Key="name",Values="MySecret"
```
出力:  

```
{
    "SecretValues": [
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MySecret1-a1b2c3",
            "Name": "MySecret1",
            "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLEaaaaa",
            "SecretString": "{\"username\":\"diego_ramirez\",\"password\":\"EXAMPLE-PASSWORD\",\"engine\":\"mysql\",\"host\":\"secretsmanagertutorial.cluster.us-west-2.rds.amazonaws.com\",\"port\":3306,\"dbClusterIdentifier\":\"secretsmanagertutorial\"}",
            "VersionStages": [
                "AWSCURRENT"
            ],
            "CreatedDate": "1523477145.729"
        },
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MySecret2-a1b2c3",
            "Name": "MySecret2",
            "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLEbbbbb",
            "SecretString": "{\"username\":\"akua_mansa\",\"password\":\"EXAMPLE-PASSWORD\"",
            "VersionStages": [
                "AWSCURRENT"
            ],
            "CreatedDate": "1673477781.275"
        },
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MySecret3-a1b2c3",
            "Name": "MySecret3",
            "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLEccccc",
            "SecretString": "{\"username\":\"jie_liu\",\"password\":\"EXAMPLE-PASSWORD\"",
            "VersionStages": [
                "AWSCURRENT"
            ],
            "CreatedDate": "1373477721.124"
        }
    ],
    "Errors": []
}
```
詳細については、「*AWS Secrets Manager ユーザーガイド*」の「[バッチ内のシークレットのグループを取得する](https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets_batch.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetSecretValue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/batch-get-secret-value.html)」を参照してください。

### `cancel-rotate-secret`
<a name="secrets-manager_CancelRotateSecret_cli_2_topic"></a>

次のコード例は、`cancel-rotate-secret` を使用する方法を示しています。

**AWS CLI**  
**シークレットの自動ローテーションをオフにするには**  
次の `cancel-rotate-secret` の例では、シークレットの自動ローテーションをオフにします。ローテーションを再開するには、`rotate-secret` を呼び出します。  

```
aws secretsmanager cancel-rotate-secret \
    --secret-id MyTestSecret
```
出力:  

```
{
  "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
  "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットをローテーションする](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelRotateSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/cancel-rotate-secret.html)」を参照してください。

### `create-secret`
<a name="secrets-manager_CreateSecret_cli_2_topic"></a>

次のコード例は、`create-secret` を使用する方法を示しています。

**AWS CLI**  
**例 1: JSON ファイルの認証情報からシークレットを作成するには**  
次の `create-secret` の例は、ファイル内の認証情報からシークレットを作成します。詳細については、「 [CLI AWS ユーザーガイド」の「ファイルからの CLI パラメータのロード](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html)」を参照してください。 *AWS *  

```
aws secretsmanager create-secret \
    --name MyTestSecret \
    --secret-string file://mycreds.json
```
`mycreds.json` の内容:  

```
{
  "engine": "mysql",
  "username": "saanvis",
  "password": "EXAMPLE-PASSWORD",
  "host": "my-database-endpoint.us-west-2.rds.amazonaws.com",
  "dbname": "myDatabase",
  "port": "3306"
}
```
出力:  

```
{
  "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
  "Name": "MyTestSecret",
  "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレットの作成](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)」を参照してください。**  
**例 2: シークレットを作成するには**  
次に、2 つのキーと値のペアを持つシークレットを作成する、`create-secret` の例をします。コマンドシェルにコマンドを入力すると、コマンド履歴がアクセスされたり、ユーティリティからコマンドパラメータにアクセスされたりするリスクがあります。これは、コマンドにシークレットの値が含まれている場合に懸念されます。詳細については、「*Secrets Manager ユーザーガイド*」の「[コマンドラインツールを使用してシークレットを保存するする際のリスクを軽減する](https://docs.aws.amazon.com/secretsmanager/latest/userguide/security_cli-exposure-risks.html)」を参照してください。  

```
aws secretsmanager create-secret \
    --name MyTestSecret \
    --description "My test secret created with the CLI." \
    --secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}"
```
出力:  

```
{
  "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
  "Name": "MyTestSecret",
  "VersionId": "EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE"
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレットの作成](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_create-basic-secret.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/create-secret.html)」を参照してください。**

### `delete-resource-policy`
<a name="secrets-manager_DeleteResourcePolicy_cli_2_topic"></a>

次のコード例は、`delete-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**シークレットにアタッチされたリソースベースのポリシーを削除するには**  
次に、シークレットにアタッチされているリソースベースのアポリシーを削除する、`delete-resource-policy` の例を示します。  

```
aws secretsmanager delete-resource-policy \
    --secret-id MyTestSecret
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[認証とアクセスコントロール](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/delete-resource-policy.html)」を参照してください。

### `delete-secret`
<a name="secrets-manager_DeleteSecret_cli_2_topic"></a>

次のコード例は、`delete-secret` を使用する方法を示しています。

**AWS CLI**  
**例 1: シークレットを削除するには**  
次の `delete-secret` の例は、シークレットを削除します。`restore-secret` レスポンスフィールドで示される日時までは、`DeletionDate` でこのシークレットを復旧できます。他のリージョンにレプリカが作成されているシークレットを削除する場合は、まずそのレプリカを `remove-regions-from-replication` で削除してから、`delete-secret` を呼び出します。  

```
aws secretsmanager delete-secret \
    --secret-id MyTestSecret \
    --recovery-window-in-days 7
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret",
    "DeletionDate": 1524085349.095
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレットの削除](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_delete-secret.html)」を参照してください。**  
**例 2: シークレットを直ちに削除するには**  
次の `delete-secret` の例は、復旧期間なしでシークレットを直ちに削除します。この場合のシークレットは復元できません。  

```
aws secretsmanager delete-secret \
    --secret-id MyTestSecret \
    --force-delete-without-recovery
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret",
    "DeletionDate": 1508750180.309
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレットの削除](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_delete-secret.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/delete-secret.html)」を参照してください。**

### `describe-secret`
<a name="secrets-manager_DescribeSecret_cli_2_topic"></a>

次のコード例は、`describe-secret` を使用する方法を示しています。

**AWS CLI**  
**シークレットの詳細を取得するには**  
次の `describe-secret` の例は、シークレットの詳細を表示します。  

```
aws secretsmanager describe-secret \
    --secret-id MyTestSecret
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-Ca8JGt",
    "Name": "MyTestSecret",
    "Description": "My test secret",
    "KmsKeyId": "arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE",
    "RotationEnabled": true,
    "RotationLambdaARN": "arn:aws:lambda:us-west-2:123456789012:function:MyTestRotationLambda",
    "RotationRules": {
        "AutomaticallyAfterDays": 2,
        "Duration": "2h",
        "ScheduleExpression": "cron(0 16 1,15 * ? *)"
    },
    "LastRotatedDate": 1525747253.72,
    "LastChangedDate": 1523477145.729,
    "LastAccessedDate": 1524572133.25,
    "Tags": [
        {
            "Key": "SecondTag",
            "Value": "AnotherValue"
        },
        {
            "Key": "FirstTag",
            "Value": "SomeValue"
        }
    ],
    "VersionIdsToStages": {
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111": [
            "AWSPREVIOUS"
        ],
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222": [
            "AWSCURRENT"
        ],
        "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333": [
            "AWSPENDING"
        ]
    },
    "CreatedDate": 1521534252.66,
    "PrimaryRegion": "us-west-2",
    "ReplicationStatus": [
        {
            "Region": "eu-west-3",
            "KmsKeyId": "alias/aws/secretsmanager",
            "Status": "InSync",
            "StatusMessage": "Replication succeeded"
        }
    ]
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレット](https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_secret)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DescribeSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/describe-secret.html)」を参照してください。**

### `get-random-password`
<a name="secrets-manager_GetRandomPassword_cli_2_topic"></a>

次のコード例は、`get-random-password` を使用する方法を示しています。

**AWS CLI**  
**ランダムなパスワードを生成するには**  
次の `get-random-password` の例では、少なくとも 1 つの大文字、小文字、数字、句読点を含む 20 文字のランダムなパスワードを生成します。  

```
aws secretsmanager get-random-password \
    --require-each-included-type \
    --password-length 20
```
出力:  

```
{
    "RandomPassword": "EXAMPLE-PASSWORD"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットの作成と管理](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRandomPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/get-random-password.html)」を参照してください。

### `get-resource-policy`
<a name="secrets-manager_GetResourcePolicy_cli_2_topic"></a>

次のコード例は、`get-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**シークレットにアタッチされているリソースベースポリシーを取得するには**  
次に、シークレットにアタッチされたリソースベースのポリシーを取得する、`get-resource-policy` の例を示します。  

```
aws secretsmanager get-resource-policy \
    --secret-id MyTestSecret
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret",
    "ResourcePolicy": "{\n\"Version\":\"2012-10-17\",\n\"Statement\":[{\n\"Effect\":\"Allow\",\n
    \"Principal\":{\n\"AWS\":\"arn:aws:iam::123456789012:root\"\n},\n\"Action\":
    \"secretsmanager:GetSecretValue\",\n\"Resource\":\"*\"\n}]\n}"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[認証とアクセスコントロール](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/get-resource-policy.html)」を参照してください。

### `get-secret-value`
<a name="secrets-manager_GetSecretValue_cli_2_topic"></a>

次のコード例は、`get-secret-value` を使用する方法を示しています。

**AWS CLI**  
**例 1: シークレットの暗号化されたシークレット値を取得するには**  
次の `get-secret-value` の例は、現在のシークレット値を取得します。  

```
aws secretsmanager get-secret-value \
    --secret-id MyTestSecret
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret",
    "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "SecretString": "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}",
    "VersionStages": [
        "AWSCURRENT"
    ],
    "CreatedDate": 1523477145.713
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレットの取得](https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html)」を参照してください。**  
**例 2: 前のシークレット値を取得するには**  
次の `get-secret-value` の例は、前のシークレット値を取得します。  

```
aws secretsmanager get-secret-value \
    --secret-id MyTestSecret
    --version-stage AWSPREVIOUS
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret",
    "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
    "SecretString": "{\"user\":\"diegor\",\"password\":\"PREVIOUS-EXAMPLE-PASSWORD\"}",
    "VersionStages": [
        "AWSPREVIOUS"
    ],
    "CreatedDate": 1523477145.713
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレットの取得](https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetSecretValue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/get-secret-value.html)」を参照してください。**

### `list-secret-version-ids`
<a name="secrets-manager_ListSecretVersionIds_cli_2_topic"></a>

次のコード例は、`list-secret-version-ids` を使用する方法を示しています。

**AWS CLI**  
**シークレットに関連付けられているすべてのシークレットバージョンを一覧表示するには**  
次の `list-secret-version-ids` の例では、シークレットのすべてのバージョンのリストを取得します。  

```
aws secretsmanager list-secret-version-ids \
    --secret-id MyTestSecret
```
出力:  

```
{
  "Versions": [
    {
        "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "VersionStages": [
            "AWSPREVIOUS"
        ],
        "LastAccessedDate": 1523477145.713,
        "CreatedDate": 1523477145.713
    },
    {
        "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "VersionStages": [
            "AWSCURRENT"
        ],
        "LastAccessedDate": 1523477145.713,
        "CreatedDate": 1523486221.391
    },
    {
        "CreatedDate": 1.51197446236E9,
        "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333;"
    }
    ],
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[バージョン](https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_version)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSecretVersionIds](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/list-secret-version-ids.html)」を参照してください。

### `list-secrets`
<a name="secrets-manager_ListSecrets_cli_2_topic"></a>

次のコード例は、`list-secrets` を使用する方法を示しています。

**AWS CLI**  
**例 1: アカウント内のシークレットを一覧表示するには**  
以下の `list-secrets` の例は、アカウント内のシークレットの一覧を取得します。  

```
aws secretsmanager list-secrets
```
出力:  

```
{
    "SecretList": [
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
            "Name": "MyTestSecret",
            "LastChangedDate": 1523477145.729,
            "SecretVersionsToStages": {
                "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111": [
                    "AWSCURRENT"
                ]
            }
        },
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:AnotherSecret-d4e5f6",
            "Name": "AnotherSecret",
            "LastChangedDate": 1523482025.685,
            "SecretVersionsToStages": {
                "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222": [
                    "AWSCURRENT"
                ]
            }
        }
    ]
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットを検索する](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_search-secret.html)」を参照してください。  
**例 2: アカウント内のシークレットの一覧をフィルタリングするには**  
次の `list-secrets` の例は、アカウント内にあり、名前に `Test` が含まれているシークレットの一覧を取得します。名前によるフィルタリングでは、大文字と小文字が区別されます。  

```
aws secretsmanager list-secrets \
    --filter Key="name",Values="Test"
```
出力:  

```
{
    "SecretList": [
        {
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
            "Name": "MyTestSecret",
            "LastChangedDate": 1523477145.729,
            "SecretVersionsToStages": {
                "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111": [
                    "AWSCURRENT"
                ]
            }
        }
    ]
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットを検索する](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_search-secret.html)」を参照してください。  
**例 3: 別のサービスで管理されているアカウントのシークレットを一覧表示するには**  
次の `list-secrets` の例は、Amazon RDS によって管理されているアカウントのシークレットを返します。  

```
aws secretsmanager list-secrets \
    --filter Key="owning-service",Values="rds"
```
出力:  

```
{
    "SecretList": [
        {
            "Name": "rds!cluster-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Tags": [
                {
                    "Value": "arn:aws:rds:us-west-2:123456789012:cluster:database-1",
                    "Key": "aws:rds:primaryDBClusterArn"
                },
                {
                    "Value": "rds",
                    "Key": "aws:secretsmanager:owningService"
                }
            ],
            "RotationRules": {
                "AutomaticallyAfterDays": 1
            },
            "LastChangedDate": 1673477781.275,
            "LastRotatedDate": 1673477781.26,
            "SecretVersionsToStages": {
                "a1b2c3d4-5678-90ab-cdef-EXAMPLEaaaaa": [
                    "AWSPREVIOUS"
                ],
                "a1b2c3d4-5678-90ab-cdef-EXAMPLEbbbbb": [
                    "AWSCURRENT",
                    "AWSPENDING"
                ]
            },
            "OwningService": "rds",
            "RotationEnabled": true,
            "CreatedDate": 1673467300.7,
            "LastAccessedDate": 1673395200.0,
            "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:rds!cluster-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111-a1b2c3",
            "Description": "Secret associated with primary RDS DB cluster: arn:aws:rds:us-west-2:123456789012:cluster:database-1"
        }
    ]
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[他のサービスによって管理されるのシークレット](https://docs.aws.amazon.com/secretsmanager/latest/userguide/service-linked-secrets.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListSecrets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/list-secrets.html)」を参照してください。**

### `put-resource-policy`
<a name="secrets-manager_PutResourcePolicy_cli_2_topic"></a>

次のコード例は、`put-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースベースのポリシーをシークレットに追加するには**  
次の `put-resource-policy` の例では、ポリシーが広範なアクセスをシークレットに提供していないことを最初に確認しながら、シークレットに許可ポリシーを追加しています。このポリシーは、ファイルから読み込まれます。詳細については、「 [CLI AWS ユーザーガイド」の「ファイルからの CLI パラメータのロード](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html)」を参照してください。 *AWS *  

```
aws secretsmanager put-resource-policy \
    --secret-id MyTestSecret \
    --resource-policy file://mypolicy.json \
    --block-public-policy
```
`mypolicy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:role/MyRole"
            },
            "Action": "secretsmanager:GetSecretValue",
            "Resource": "*"
        }
    ]
}
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[アクセス許可ポリシーをシークレットにアタッチする](https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_resource-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/put-resource-policy.html)」を参照してください。

### `put-secret-value`
<a name="secrets-manager_PutSecretValue_cli_2_topic"></a>

次のコード例は、`put-secret-value` を使用する方法を示しています。

**AWS CLI**  
**例 1: シークレットの新しいシークレット値を保存するには**  
次の `put-secret-value` の例は、キーと値の 2 つのペアを含むシークレットの新しいバージョンを作成します。  

```
aws secretsmanager put-secret-value \
    --secret-id MyTestSecret \
    --secret-string "{\"user\":\"diegor\",\"password\":\"EXAMPLE-PASSWORD\"}"
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-1a2b3c",
    "Name": "MyTestSecret",
    "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "VersionStages": [
        "AWSCURRENT"
    ]
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットの変更](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_update-secret.html)」を参照してください。  
**例 2: 認証情報の新しいシークレット値を JSON ファイルに保存するには**  
次の `put-secret-value` の例では、ファイル内の認証情報からシークレットの新しいバージョンが作成されます。詳細については、「 [CLI AWS ユーザーガイド」の「ファイルからの CLI パラメータのロード](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html)」を参照してください。 *AWS *  

```
aws secretsmanager put-secret-value \
    --secret-id MyTestSecret \
    --secret-string file://mycreds.json
```
`mycreds.json` の内容:  

```
{
  "engine": "mysql",
  "username": "saanvis",
  "password": "EXAMPLE-PASSWORD",
  "host": "my-database-endpoint.us-west-2.rds.amazonaws.com",
  "dbname": "myDatabase",
  "port": "3306"
}
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret",
    "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "VersionStages": [
        "AWSCURRENT"
    ]
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットの変更](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_update-secret.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutSecretValue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/put-secret-value.html)」を参照してください。**

### `remove-regions-from-replication`
<a name="secrets-manager_RemoveRegionsFromReplication_cli_2_topic"></a>

次のコード例は、`remove-regions-from-replication` を使用する方法を示しています。

**AWS CLI**  
**レプリカシークレットを削除するには**  
次の `remove-regions-from-replication` の例では、eu-west-3 にあるレプリカシークレットを削除しています。他のリージョンにレプリカが作成されているプライマリシークレットを削除するには、まずそのレプリカを削除してから `delete-secret` を呼び出します。  

```
aws secretsmanager remove-regions-from-replication \
    --secret-id MyTestSecret \
    --remove-replica-regions eu-west-3
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-1a2b3c",
    "ReplicationStatus": []
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[レプリカシークレットの削除](https://docs.aws.amazon.com/secretsmanager/latest/userguide/delete-replica.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveRegionsFromReplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/remove-regions-from-replication.html)」を参照してください。

### `replicate-secret-to-regions`
<a name="secrets-manager_ReplicateSecretToRegions_cli_2_topic"></a>

次のコード例は、`replicate-secret-to-regions` を使用する方法を示しています。

**AWS CLI**  
**シークレットを異なるリージョンにレプリケートするには**  
次に、シークレットをeu-west-3 にレプリケートする、`replicate-secret-to-regions` の例を示します。レプリカは AWS マネージドキー で暗号化されます`aws/secretsmanager`。  

```
aws secretsmanager replicate-secret-to-regions \
    --secret-id MyTestSecret \
    --add-replica-regions Region=eu-west-3
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-1a2b3c",
    "ReplicationStatus": [
        {
            "Region": "eu-west-3",
            "KmsKeyId": "alias/aws/secretsmanager",
            "Status": "InProgress"
        }
    ]
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットを異なるリージョンにレプリケートする](https://docs.aws.amazon.com/secretsmanager/latest/userguide/replicate-existing-secret.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ReplicateSecretToRegions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/replicate-secret-to-regions.html)」を参照してください。

### `restore-secret`
<a name="secrets-manager_RestoreSecret_cli_2_topic"></a>

次のコード例は、`restore-secret` を使用する方法を示しています。

**AWS CLI**  
**以前に削除したシークレットを復元するには**  
次の `restore-secret` の例では、スケジュールにより以前に削除されたシークレットを復元します。  

```
aws secretsmanager restore-secret \
    --secret-id MyTestSecret
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「Secrets Manager ユーザーガイド」の「[シークレットの削除](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_delete-secret.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/restore-secret.html)」を参照してください。

### `rotate-secret`
<a name="secrets-manager_RotateSecret_cli_2_topic"></a>

次のコード例は、`rotate-secret` を使用する方法を示しています。

**AWS CLI**  
**例 1: シークレットの自動ローテーションを設定して開始するには**  
次の `rotate-secret` の例では、シークレットの自動ローテーションを設定して開始します。Secrets Manager は、シークレットを直ちに 1 回ローテーションし、その後 8 時間ごとに 2 時間の時間枠でローテーションします。出力には、ローテーションによって作成された新しいシークレットバージョンの `VersionId` が表示されます。  

```
aws secretsmanager rotate-secret \
    --secret-id MyTestDatabaseSecret \
    --rotation-lambda-arn arn:aws:lambda:us-west-2:1234566789012:function:SecretsManagerTestRotationLambda \
    --rotation-rules "{\"ScheduleExpression\": \"cron(0 8/8 * * ? *)\", \"Duration\": \"2h\"}"
```
出力:  

```
{
    "ARN": "aws:arn:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3",
    "Name": "MyTestDatabaseSecret",
    "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットのローテーション](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html)」を参照してください。  
**例 2: ローテーション間隔で自動ローテーションを設定および開始するには**  
次の `rotate-secret` の例では、シークレットの自動ローテーションを設定して開始します。Secrets Manager はシークレットを直ちに 1 回ローテーションし、その後は 10 日ごとにローテーションします。出力には、ローテーションによって作成された新しいシークレットバージョンの `VersionId` が表示されます。  

```
aws secretsmanager rotate-secret \
    --secret-id MyTestDatabaseSecret \
    --rotation-lambda-arn arn:aws:lambda:us-west-2:1234566789012:function:SecretsManagerTestRotationLambda \
    --rotation-rules "{\"ScheduleExpression\": \"rate(10 days)\"}"
```
出力:  

```
{
    "ARN": "aws:arn:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3",
    "Name": "MyTestDatabaseSecret",
    "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットのローテーション](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html)」を参照してください。  
**例 3: シークレットを直ちに削除するには**  
次の `rotate-secret` の例では、すぐにローテーションが開始されます。出力には、ローテーションによって作成された新しいシークレットバージョンの `VersionId` が表示されます。シークレットのローテーションは、すでに設定されている必要があります。  

```
aws secretsmanager rotate-secret \
    --secret-id MyTestDatabaseSecret
```
出力:  

```
{
    "ARN": "aws:arn:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3",
    "Name": "MyTestDatabaseSecret",
    "VersionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットのローテーション](https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RotateSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/rotate-secret.html)」を参照してください。

### `stop-replication-to-replica`
<a name="secrets-manager_StopReplicationToReplica_cli_2_topic"></a>

次のコード例は、`stop-replication-to-replica` を使用する方法を示しています。

**AWS CLI**  
**レプリカシークレットをプライマリに昇格させるには**  
次の `stop-replication-to-replica` の例は、レプリカシークレットからプライマリへのリンクを削除します。このレプリカシークレットは、レプリカのリージョンでプライマリシークレットに昇格されます。`stop-replication-to-replica` は、レプリカリージョン内から呼び出す必要があります。  

```
aws secretsmanager stop-replication-to-replica \
    --secret-id MyTestSecret
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[レプリカシークレットを昇格させる](https://docs.aws.amazon.com/secretsmanager/latest/userguide/standalone-secret.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopReplicationToReplica](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/stop-replication-to-replica.html)」を参照してください。

### `tag-resource`
<a name="secrets-manager_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: シークレットにタグを追加するには**  
次の例は、短縮構文を使用してタグをアタッチする方法を示しています。  

```
aws secretsmanager tag-resource \
    --secret-id MyTestSecret \
    --tags Key=FirstTag,Value=FirstValue
```
このコマンドでは何も出力されません。  
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットにタグ付けする](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets_tagging.html)」を参照してください。  
**例 2: シークレットに複数のタグを追加するには**  
次の `tag-resource` の例では、キーと値のタグ 2 個がシークレットにアタッチされます。  

```
aws secretsmanager tag-resource \
    --secret-id MyTestSecret \
    --tags '[{"Key": "FirstTag", "Value": "FirstValue"}, {"Key": "SecondTag", "Value": "SecondValue"}]'
```
このコマンドでは何も出力されません。  
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットにタグ付けする](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets_tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="secrets-manager_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**シークレットからタグを削除するには**  
次の `untag-resource` の例では、シークレットから 2 個のタグが削除されます。タグごとに、キーと値の両方が削除されます。  

```
aws secretsmanager untag-resource \
    --secret-id MyTestSecret \
    --tag-keys '[ "FirstTag", "SecondTag"]'
```
このコマンドでは何も出力されません。  
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットにタグ付けする](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets_tagging.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/untag-resource.html)」を参照してください。

### `update-secret-version-stage`
<a name="secrets-manager_UpdateSecretVersionStage_cli_2_topic"></a>

次のコード例は、`update-secret-version-stage` を使用する方法を示しています。

**AWS CLI**  
**例 1: シークレットを以前のバージョンに戻すには**  
次の`update-secret-version-stage`例では、 AWS CURRENT ステージングラベルを以前のバージョンのシークレットに移動し、シークレットを以前のバージョンに戻します。以前のバージョンの ID を検索するには、`list-secret-version-ids` を使用します。この例では、 AWS CURRENT ラベルを持つバージョンは a1b2c3d4-5678-90ab-cdef-EXAMPLE11111で、 AWS PREVIOUS ラベルを持つバージョンは a1b2c3d4-5678-90ab-cdef-EXAMPLE222222 です。この例では、 AWS CURRENT ラベルをバージョン 11111 から 22222 に移動します。 AWS CURRENT ラベルはバージョンから削除されるため、 `update-secret-version-stage`は自動的に AWS PREVIOUS ラベルをそのバージョン (11111) に移動します。その結果、CURRENT AWSバージョンと AWS PREVIOUS バージョンがスワップされます。  

```
aws secretsmanager update-secret-version-stage \
    --secret-id MyTestSecret \
    --version-stage AWSCURRENT \
    --move-to-version-id a1b2c3d4-5678-90ab-cdef-EXAMPLE22222 \
    --remove-from-version-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[バージョン](https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_version)」を参照してください。  
**例 2: シークレットのバージョンにアタッチされたステージングラベルを追加するには**  
次の `update-secret-version-stage` の例では、シークレットのバージョンにステージングラベルを追加します。`list-secret-version-ids` を実行して影響のあるバージョンの `VersionStages` レスポンスフィールドを表示することで、結果を確認できます。  

```
aws secretsmanager update-secret-version-stage \
    --secret-id MyTestSecret \
    --version-stage STAGINGLABEL1 \
    --move-to-version-id EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[バージョン](https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_version)」を参照してください。  
**例 3: シークレットのバージョンにアタッチされたステージングラベルを削除するには**  
次の `update-secret-version-stage` の例では、シークレットのバージョンにアタッチされているステージングラベルを削除します。`list-secret-version-ids` を実行して影響のあるバージョンの `VersionStages` レスポンスフィールドを表示することで、結果を確認できます。  

```
aws secretsmanager update-secret-version-stage \
    --secret-id MyTestSecret \
    --version-stage STAGINGLABEL1 \
    --remove-from-version-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[バージョン](https://docs.aws.amazon.com/secretsmanager/latest/userguide/getting-started.html#term_version)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UpdateSecretVersionStage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/update-secret-version-stage.html)」を参照してください。

### `update-secret`
<a name="secrets-manager_UpdateSecret_cli_2_topic"></a>

次のコード例は、`update-secret` を使用する方法を示しています。

**AWS CLI**  
**例 1: シークレットの記述を更新するには**  
次の `update-secret` の例は、シークレットの記述を更新します。  

```
aws secretsmanager update-secret \
    --secret-id MyTestSecret \
    --description "This is a new description for the secret."
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットの変更](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_update-secret.html)」を参照してください。  
**例 2: シークレットに関連付けられた暗号化キーを更新するには**  
次の `update-secret` の例は、シークレット値の暗号化に使用される KMS キーを更新します。KMS キーは、シークレットと同じリージョンに存在する必要があります。  

```
aws secretsmanager update-secret \
    --secret-id MyTestSecret \
    --kms-key-id arn:aws:kms:us-west-2:123456789012:key/EXAMPLE1-90ab-cdef-fedc-ba987EXAMPLE
```
出力:  

```
{
    "ARN": "arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestSecret-a1b2c3",
    "Name": "MyTestSecret"
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[シークレットの変更](https://docs.aws.amazon.com/secretsmanager/latest/userguide/manage_update-secret.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateSecret](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/update-secret.html)」を参照してください。**

### `validate-resource-policy`
<a name="secrets-manager_ValidateResourcePolicy_cli_2_topic"></a>

次のコード例は、`validate-resource-policy` を使用する方法を示しています。

**AWS CLI**  
**リソースポリシーを検証するには**  
次の `validate-resource-policy` の例では、リソースポリシーがシークレットへの幅広いアクセスを許可していないことを確認します。このポリシーは、ディスクのファイルから読み込まれます。詳細については、「 [CLI AWS ユーザーガイド」の「ファイルからの CLI パラメータのロード](https://docs.aws.amazon.com/cli/latest/userguide/cli-usage-parameters-file.html)」を参照してください。 *AWS *  

```
aws secretsmanager validate-resource-policy \
    --resource-policy file://mypolicy.json
```
`mypolicy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:role/MyRole"
            },
            "Action": "secretsmanager:GetSecretValue",
            "Resource": "*"
        }
    ]
}
```
出力:  

```
{
    "PolicyValidationPassed": true,
    "ValidationErrors": []
}
```
詳細については、「*Secrets Manager ユーザーガイド*」の「[Secrets Manager のアクセス許可のリファレンス](https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ValidateResourcePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/secretsmanager/validate-resource-policy.html)」を参照してください。

# を使用した Security Hub CSPM の例 AWS CLI
<a name="cli_2_securityhub_code_examples"></a>

次のコード例は、Security Hub CSPM AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-administrator-invitation`
<a name="securityhub_AcceptAdministratorInvitation_cli_2_topic"></a>

次のコード例は、`accept-administrator-invitation` を使用する方法を示しています。

**AWS CLI**  
**管理者アカウントからの招待を受け入れるには**  
次の `accept-administrator-invitation` の例では、指定された管理者アカウントからの指定された招待を受け入れます。  

```
aws securityhub accept-invitation \
    --administrator-id 123456789012 \
    --invitation-id 7ab938c5d52d7904ad09f9e7c20cc4eb
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptAdministratorInvitation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/accept-administrator-invitation.html)」を参照してください。

### `accept-invitation`
<a name="securityhub_AcceptInvitation_cli_2_topic"></a>

次のコード例は、`accept-invitation` を使用する方法を示しています。

**AWS CLI**  
**管理者アカウントからの招待を受け入れるには**  
次の `accept-invitation` の例では、指定された管理者アカウントからの指定された招待を受け入れます。  

```
aws securityhub accept-invitation \
    --master-id 123456789012 \
    --invitation-id 7ab938c5d52d7904ad09f9e7c20cc4eb
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptInvitation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/accept-invitation.html)」を参照してください。

### `batch-delete-automation-rules`
<a name="securityhub_BatchDeleteAutomationRules_cli_2_topic"></a>

次のコード例は、`batch-delete-automation-rules` を使用する方法を示しています。

**AWS CLI**  
**自動化ルールを削除するには**  
次の `batch-delete-automation-rules` の例は、指定された自動化ルールを削除します。1 つのコマンドで 1 つ以上のルールを削除できます。Security Hub 管理者アカウントのみ、このコマンドを実行できます。  

```
aws securityhub batch-delete-automation-rules \
    --automation-rules-arns '["arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"]'
```
出力:  

```
{
    "ProcessedAutomationRules": [
        "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    ],
    "UnprocessedAutomationRules": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[自動化ルールの削除](https://docs.aws.amazon.com/securityhub/latest/userguide/automation-rules.html#delete-automation-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDeleteAutomationRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-delete-automation-rules.html)」を参照してください。

### `batch-disable-standards`
<a name="securityhub_BatchDisableStandards_cli_2_topic"></a>

次のコード例は、`batch-disable-standards` を使用する方法を示しています。

**AWS CLI**  
**標準を無効にするには**  
次の `batch-disable-standards` の例では、指定されたサブスクリプション ARN に関連付けられた標準を無効にします。  

```
aws securityhub batch-disable-standards \
    --standards-subscription-arns "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1"
```
出力:  

```
{
    "StandardsSubscriptions": [
        {
            "StandardsArn": "arn:aws:securityhub:eu-central-1::standards/pci-dss/v/3.2.1",
            "StandardsInput": { },
            "StandardsStatus": "DELETING",
            "StandardsSubscriptionArn": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1"
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[セキュリティ標準の無効化または有効化](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchDisableStandards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-disable-standards.html)」を参照してください。

### `batch-enable-standards`
<a name="securityhub_BatchEnableStandards_cli_2_topic"></a>

次のコード例は、`batch-enable-standards` を使用する方法を示しています。

**AWS CLI**  
**標準を有効にするには**  
次の `batch-enable-standards` の例では、リクエスト元のアカウントの PCI DSS 標準を有効にします。  

```
aws securityhub batch-enable-standards \
    --standards-subscription-requests '{"StandardsArn":"arn:aws:securityhub:us-west-1::standards/pci-dss/v/3.2.1"}'
```
出力:  

```
{
    "StandardsSubscriptions": [
        {
            "StandardsArn": "arn:aws:securityhub:us-west-1::standards/pci-dss/v/3.2.1",
            "StandardsInput": { },
            "StandardsStatus": "PENDING",
            "StandardsSubscriptionArn": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1"
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[セキュリティ標準の無効化または有効化](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchEnableStandards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-enable-standards.html)」を参照してください。

### `batch-get-automation-rules`
<a name="securityhub_BatchGetAutomationRules_cli_2_topic"></a>

次のコード例は、`batch-get-automation-rules` を使用する方法を示しています。

**AWS CLI**  
**自動化ルールの詳細を取得するには**  
次の `batch-get-automation-rules` の例は、指定された自動化ルールの詳細情報を取得します。1 つのコマンドで 1 つ以上の自動化ルールの詳細情報を取得できます。  

```
aws securityhub batch-get-automation-rules \
    --automation-rules-arns '["arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"]'
```
出力:  

```
{
    "Rules": [
        {
            "RuleArn": "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "RuleStatus": "ENABLED",
            "RuleOrder": 1,
            "RuleName": "Suppress informational findings",
            "Description": "Suppress GuardDuty findings with Informational severity",
            "IsTerminal": false,
            "Criteria": {
                "ProductName": [
                    {
                        "Value": "GuardDuty",
                        "Comparison": "EQUALS"
                    }
                ],
                "SeverityLabel": [
                    {
                        "Value": "INFORMATIONAL",
                        "Comparison": "EQUALS"
                    }
                ],
                "WorkflowStatus": [
                    {
                        "Value": "NEW",
                        "Comparison": "EQUALS"
                    }
                ],
                "RecordState": [
                    {
                        "Value": "ACTIVE",
                        "Comparison": "EQUALS"
                    }
                ]
            },
            "Actions": [
                {
                    "Type": "FINDING_FIELDS_UPDATE",
                    "FindingFieldsUpdate": {
                        "Note": {
                            "Text": "Automatically suppress GuardDuty findings with Informational severity",
                            "UpdatedBy": "sechub-automation"
                        },
                        "Workflow": {
                            "Status": "SUPPRESSED"
                        }
                    }
                }
            ],
            "CreatedAt": "2023-05-31T17:56:14.837000+00:00",
            "UpdatedAt": "2023-05-31T17:59:38.466000+00:00",
            "CreatedBy": "arn:aws:iam::123456789012:role/Admin"
        }
    ],
    "UnprocessedAutomationRules": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[自動化ルールを表示する](https://docs.aws.amazon.com/securityhub/latest/userguide/automation-rules.html#view-automation-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetAutomationRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-get-automation-rules.html)」を参照してください。

### `batch-get-configuration-policy-associations`
<a name="securityhub_BatchGetConfigurationPolicyAssociations_cli_2_topic"></a>

次のコード例は、`batch-get-configuration-policy-associations` を使用する方法を示しています。

**AWS CLI**  
**ターゲットのバッチの設定の関連付けに関する詳細を取得するには**  
次の `batch-get-configuration-policy-associations` の例では、指定されたターゲットの関連付けに関する詳細情報を取得します。ターゲットのアカウント ID、組織単位 ID、またはルート ID を指定できます。  

```
aws securityhub batch-get-configuration-policy-associations \
    --target '{"OrganizationalUnitId": "ou-6hi7-8j91kl2m"}'
```
出力:  

```
{
    "ConfigurationPolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
    "TargetId": "ou-6hi7-8j91kl2m",
    "TargetType": "ORGANIZATIONAL_UNIT",
    "AssociationType": "APPLIED",
    "UpdatedAt": "2023-09-26T21:13:01.816000+00:00",
    "AssociationStatus": "SUCCESS",
    "AssociationStatusMessage": "Association applied successfully on this target."
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの表示](https://docs.aws.amazon.com/securityhub/latest/userguide/view-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetConfigurationPolicyAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-get-configuration-policy-associations.html)」を参照してください。

### `batch-get-security-controls`
<a name="securityhub_BatchGetSecurityControls_cli_2_topic"></a>

次のコード例は、`batch-get-security-controls` を使用する方法を示しています。

**AWS CLI**  
**セキュリティコントロールの詳細を取得するには**  
次の の`batch-get-security-controls`例では、現在の AWS アカウントと AWS リージョンのセキュリティコントロール ACM.1 と IAM.1 の詳細を取得します。  

```
aws securityhub batch-get-security-controls \
    --security-control-ids '["ACM.1", "IAM.1"]'
```
出力:  

```
{
    "SecurityControls": [
        {
            "SecurityControlId": "ACM.1",
            "SecurityControlArn": "arn:aws:securityhub:us-east-2:123456789012:security-control/ACM.1",
            "Title": "Imported and ACM-issued certificates should be renewed after a specified time period",
            "Description": "This control checks whether an AWS Certificate Manager (ACM) certificate is renewed within the specified time period. It checks both imported certificates and certificates provided by ACM. The control fails if the certificate isn't renewed within the specified time period. Unless you provide a custom parameter value for the renewal period, Security Hub uses a default value of 30 days.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/ACM.1/remediation",
            "SeverityRating": "MEDIUM",
            "SecurityControlStatus": "ENABLED"
            "UpdateStatus": "READY",
            "Parameters": {
                "daysToExpiration": {
                    "ValueType": CUSTOM,
                    "Value": {
                        "Integer": 15
                    }
                }
            },
            "LastUpdateReason": "Updated control parameter"
        },
        {
            "SecurityControlId": "IAM.1",
            "SecurityControlArn": "arn:aws:securityhub:us-east-2:123456789012:security-control/IAM.1",
            "Title": "IAM policies should not allow full \"*\" administrative privileges",
            "Description": "This AWS control checks whether the default version of AWS Identity and Access Management (IAM) policies (also known as customer managed policies) do not have administrator access with a statement that has \"Effect\": \"Allow\" with \"Action\": \"*\" over \"Resource\": \"*\". It only checks for the Customer Managed Policies that you created, but not inline and AWS Managed Policies.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/IAM.1/remediation",
            "SeverityRating": "HIGH",
            "SecurityControlStatus": "ENABLED"
            "UpdateStatus": "READY",
            "Parameters": {}
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[コントロールの詳細の表示](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-control-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*.」の「[BatchGetSecurityControls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-get-security-controls.html)」を参照してください。

### `batch-get-standards-control-associations`
<a name="securityhub_BatchGetStandardsControlAssociations_cli_2_topic"></a>

次のコード例は、`batch-get-standards-control-associations` を使用する方法を示しています。

**AWS CLI**  
**コントロールの有効化ステータスを取得するには**  
次の `batch-get-standards-control-associations` の例では、指定されたコントロールが指定された標準で有効になっているかどうかを示します。  

```
aws securityhub batch-get-standards-control-associations \
    --standards-control-association-ids '[{"SecurityControlId": "Config.1","StandardsArn": "arn:aws:securityhub:us-east-1:123456789012:ruleset/cis-aws-foundations-benchmark/v/1.2.0"}, {"SecurityControlId": "IAM.6","StandardsArn": "arn:aws:securityhub:us-east-1:123456789012:standards/aws-foundational-security-best-practices/v/1.0.0"}]'
```
出力:  

```
{
    "StandardsControlAssociationDetails": [
        {
            "StandardsArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",
            "SecurityControlId": "Config.1",
            "SecurityControlArn": "arn:aws:securityhub:us-east-1:068873283051:security-control/Config.1",
            "AssociationStatus": "ENABLED",
            "RelatedRequirements": [
                "CIS AWS Foundations 2.5"
            ],
            "UpdatedAt": "2022-10-27T16:07:12.960000+00:00",
            "StandardsControlTitle": "Ensure AWS Config is enabled",
            "StandardsControlDescription": "AWS Config is a web service that performs configuration management of supported AWS resources within your account and delivers log files to you. The recorded information includes the configuration item (AWS resource), relationships between configuration items (AWS resources), and any configuration changes between resources. It is recommended to enable AWS Config in all regions.",
            "StandardsControlArns": [
                "arn:aws:securityhub:us-east-1:068873283051:control/cis-aws-foundations-benchmark/v/1.2.0/2.5"
            ]
        },
        {
            "StandardsArn": "arn:aws:securityhub:us-east-1::standards/aws-foundational-security-best-practices/v/1.0.0",
            "SecurityControlId": "IAM.6",
            "SecurityControlArn": "arn:aws:securityhub:us-east-1:068873283051:security-control/IAM.6",
            "AssociationStatus": "DISABLED",
            "RelatedRequirements": [],
            "UpdatedAt": "2022-11-22T21:30:35.080000+00:00",
            "UpdatedReason": "test",
            "StandardsControlTitle": "Hardware MFA should be enabled for the root user",
            "StandardsControlDescription": "This AWS control checks whether your AWS account is enabled to use a hardware multi-factor authentication (MFA) device to sign in with root user credentials.",
            "StandardsControlArns": [
                "arn:aws:securityhub:us-east-1:068873283051:control/aws-foundational-security-best-practices/v/1.0.0/IAM.6"
            ]
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[特定の標準コントロールの有効化と無効化](https://docs.aws.amazon.com/securityhub/latest/userguide/controls-configure.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchGetStandardsControlAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-get-standards-control-associations.html)」を参照してください。

### `batch-import-findings`
<a name="securityhub_BatchImportFindings_cli_2_topic"></a>

次のコード例は、`batch-import-findings` を使用する方法を示しています。

**AWS CLI**  
**検出結果を更新するには**  
次の `batch-import-findings` の例では、検出結果を更新します。  

```
aws securityhub batch-import-findings \
     --findings '
        [{
            "AwsAccountId": "123456789012",
            "CreatedAt": "2020-05-27T17:05:54.832Z",
            "Description": "Vulnerability in a CloudTrail trail",
            "FindingProviderFields": {
                "Severity": {
                    "Label": "LOW",
                    "Original": "10"
                },
                "Types": [
                    "Software and Configuration Checks/Vulnerabilities/CVE"
                ]
            },
            "GeneratorId": "TestGeneratorId",
            "Id": "Id1",
            "ProductArn": "arn:aws:securityhub:us-west-1:123456789012:product/123456789012/default",
            "Resources": [
                {
                    "Id": "arn:aws:cloudtrail:us-west-1:123456789012:trail/TrailName",
                    "Partition": "aws",
                    "Region": "us-west-1",
                    "Type": "AwsCloudTrailTrail"
                }
            ],
            "SchemaVersion": "2018-10-08",
            "Title": "CloudTrail trail vulnerability",
            "UpdatedAt": "2020-06-02T16:05:54.832Z"
        }]'
```
出力:  

```
{
    "FailedCount": 0,
    "SuccessCount": 1,
    "FailedFindings": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[BatchImportFindings を使用して検出結果を作成および更新する](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-update-batchimportfindings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchImportFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-import-findings.html)」を参照してください。

### `batch-update-automation-rules`
<a name="securityhub_BatchUpdateAutomationRules_cli_2_topic"></a>

次のコード例は、`batch-update-automation-rules` を使用する方法を示しています。

**AWS CLI**  
**自動化ルールを更新するには**  
次の `batch-update-automation-rules` の例では、指定された自動化ルールを更新します。1 つのコマンドで 1 つ以上のルールを更新できます。Security Hub 管理者アカウントのみ、このコマンドを実行できます。  

```
aws securityhub batch-update-automation-rules \
    --update-automation-rules-request-items '[ \
        { \
            "Actions": [{ \
                "Type": "FINDING_FIELDS_UPDATE", \
                "FindingFieldsUpdate": { \
                    "Note": { \
                        "Text": "Known issue that is a risk", \
                        "UpdatedBy": "sechub-automation" \
                    }, \
                    "Workflow": { \
                        "Status": "NEW" \
                    } \
                } \
            }], \
            "Criteria": { \
                "SeverityLabel": [{ \
                    "Value": "LOW", \
                    "Comparison": "EQUALS" \
                }] \
            }, \
            "RuleArn": "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", \
            "RuleOrder": 1, \
            "RuleStatus": "DISABLED" \
        } \
    ]'
```
出力:  

```
{
    "ProcessedAutomationRules": [
        "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    ],
    "UnprocessedAutomationRules": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[自動化ルールの編集](https://docs.aws.amazon.com/securityhub/latest/userguide/automation-rules.html#edit-automation-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchUpdateAutomationRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-update-automation-rules.html)」を参照してください。

### `batch-update-findings`
<a name="securityhub_BatchUpdateFindings_cli_2_topic"></a>

次のコード例は、`batch-update-findings` を使用する方法を示しています。

**AWS CLI**  
**例 1: 検出結果を更新するには**  
以下の `batch-update-findings` の例では、2 つの検出結果を更新して、メモを追加し、重要度ラベルを変更してから、それらを解決します。  

```
aws securityhub batch-update-findings \
    --finding-identifiers '[{"Id": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111", "ProductArn": "arn:aws:securityhub:us-west-1::product/aws/securityhub"}, {"Id": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222", "ProductArn": "arn:aws:securityhub:us-west-1::product/aws/securityhub"}]' \
    --note '{"Text": "Known issue that is not a risk.", "UpdatedBy": "user1"}' \
    --severity '{"Label": "LOW"}' \
    --workflow '{"Status": "RESOLVED"}'
```
出力:  

```
{
    "ProcessedFindings": [
        {
            "Id": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ProductArn": "arn:aws:securityhub:us-west-1::product/aws/securityhub"
        },
        {
            "Id": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "ProductArn": "arn:aws:securityhub:us-west-1::product/aws/securityhub"
        }
    ],
    "UnprocessedFindings": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[BatchUpdateFindings を使用して検出結果を更新する](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-update-batchupdatefindings.html)」を参照してください。  
**例 2: 省略構文を使用して検出結果を更新するには**  
以下の `batch-update-findings` の例では、省略構文を使用して 2 つの検出結果を更新し、メモを追加して、重要度ラベルを変更してから、それらを解決します。  

```
aws securityhub batch-update-findings \
    --finding-identifiers Id="arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",ProductArn="arn:aws:securityhub:us-west-1::product/aws/securityhub" Id="arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",ProductArn="arn:aws:securityhub:us-west-1::product/aws/securityhub" \
    --note Text="Known issue that is not a risk.",UpdatedBy="user1" \
    --severity Label="LOW" \
    --workflow Status="RESOLVED"
```
出力:  

```
{
    "ProcessedFindings": [
        {
            "Id": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ProductArn": "arn:aws:securityhub:us-west-1::product/aws/securityhub"
        },
        {
            "Id": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "ProductArn": "arn:aws:securityhub:us-west-1::product/aws/securityhub"
        }
    ],
    "UnprocessedFindings": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[BatchUpdateFindings を使用して検出結果を更新する](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-update-batchupdatefindings.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchUpdateFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-update-findings.html)」を参照してください。

### `batch-update-standards-control-associations`
<a name="securityhub_BatchUpdateStandardsControlAssociations_cli_2_topic"></a>

次のコード例は、`batch-update-standards-control-associations` を使用する方法を示しています。

**AWS CLI**  
**有効な標準でコントロールの有効化ステータスを更新するには**  
次の `batch-update-standards-control-associations` の例では、指定された標準で CloudTrail.1 を無効にします。  

```
aws securityhub batch-update-standards-control-associations \
    --standards-control-association-updates '[{"SecurityControlId": "CloudTrail.1", "StandardsArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0", "AssociationStatus": "DISABLED", "UpdatedReason": "Not applicable to environment"}, {"SecurityControlId": "CloudTrail.1", "StandardsArn": "arn:aws:securityhub:::standards/cis-aws-foundations-benchmark/v/1.4.0", "AssociationStatus": "DISABLED", "UpdatedReason": "Not applicable to environment"}]'
```
このコマンドが成功した場合、出力は生成されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[特定の標準のコントロールを有効にする](https://docs.aws.amazon.com/securityhub/latest/userguide/controls-configure.html)」と「[特定の標準コントロールの有効化と無効化](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable-controls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchUpdateStandardsControlAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/batch-update-standards-control-associations.html)」を参照してください。

### `create-action-target`
<a name="securityhub_CreateActionTarget_cli_2_topic"></a>

次のコード例は、`create-action-target` を使用する方法を示しています。

**AWS CLI**  
**カスタムアクションを作成するには**  
次の `create-action-target` の例では、カスタムアクションを作成します。アクションの名前、説明、識別子を指定します。  

```
aws securityhub create-action-target \
    --name "Send to remediation" \
    --description "Action to send the finding for remediation tracking" \
    --id "Remediation"
```
出力:  

```
{
    "ActionTargetArn": "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムアクションを作成し、CloudWatch Events ルールに関連付ける](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-cloudwatch-events.html#securityhub-cwe-configure)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateActionTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/create-action-target.html)」を参照してください。

### `create-automation-rule`
<a name="securityhub_CreateAutomationRule_cli_2_topic"></a>

次のコード例は、`create-automation-rule` を使用する方法を示しています。

**AWS CLI**  
**自動化ルールを作成するには**  
次の の`create-automation-rule`例では、現在の AWS アカウントと AWS リージョンにオートメーションルールを作成します。Security Hub は、指定された基準に基づいて検出結果をフィルタリングし、一致する検出結果にアクションを適用します。Security Hub 管理者アカウントのみ、このコマンドを実行できます。  

```
aws securityhub create-automation-rule \
    --actions '[{ \
        "Type": "FINDING_FIELDS_UPDATE", \
        "FindingFieldsUpdate": { \
            "Severity": { \
                "Label": "HIGH" \
            }, \
            "Note": { \
                "Text": "Known issue that is a risk. Updated by automation rules", \
                "UpdatedBy": "sechub-automation" \
            } \
        } \
    }]' \
    --criteria '{ \
        "SeverityLabel": [{ \
            "Value": "INFORMATIONAL", \
            "Comparison": "EQUALS" \
        }] \
    }' \
    --description "A sample rule" \
    --no-is-terminal \
    --rule-name "sample rule" \
    --rule-order 1 \
    --rule-status "ENABLED"
```
出力:  

```
{
    "RuleArn": "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[自動化ルールの作成](https://docs.aws.amazon.com/securityhub/latest/userguide/automation-rules.html#create-automation-rules)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAutomationRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/create-automation-rule.html)」を参照してください。

### `create-configuration-policy`
<a name="securityhub_CreateConfigurationPolicy_cli_2_topic"></a>

次のコード例は、`create-configuration-policy` を使用する方法を示しています。

**AWS CLI**  
**設定ポリシーを作成するには**  
次の `create-configuration-policy` の例では、指定された設定で設定ポリシーを作成します。  

```
aws securityhub create-configuration-policy \
    --name "SampleConfigurationPolicy" \
    --description "SampleDescription" \
    --configuration-policy '{"SecurityHub": {"ServiceEnabled": true, "EnabledStandardIdentifiers": ["arn:aws:securityhub:eu-central-1::standards/aws-foundational-security-best-practices/v/1.0.0","arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0"],"SecurityControlsConfiguration":{"DisabledSecurityControlIdentifiers": ["CloudTrail.2"], "SecurityControlCustomParameters": [{"SecurityControlId": "ACM.1", "Parameters": {"daysToExpiration": {"ValueType": "CUSTOM", "Value": {"Integer": 15}}}}]}}}' \
    --tags '{"Environment": "Prod"}'
```
出力:  

```
{
    "Arn": "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "Name": "SampleConfigurationPolicy",
    "Description": "SampleDescription",
    "UpdatedAt": "2023-11-28T20:28:04.494000+00:00",
    "CreatedAt": "2023-11-28T20:28:04.494000+00:00",
    "ConfigurationPolicy": {
        "SecurityHub": {
            "ServiceEnabled": true,
            "EnabledStandardIdentifiers": [
                "arn:aws:securityhub:eu-central-1::standards/aws-foundational-security-best-practices/v/1.0.0",
                "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0"
            ],
            "SecurityControlsConfiguration": {
                "DisabledSecurityControlIdentifiers": [
                    "CloudTrail.2"
                ],
                "SecurityControlCustomParameters": [
                    {
                        "SecurityControlId": "ACM.1",
                        "Parameters": {
                            "daysToExpiration": {
                                "ValueType": "CUSTOM",
                                "Value": {
                                    "Integer": 15
                                }
                            }
                        }
                    }
                ]
            }
        }
    }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの作成と関連付け](https://docs.aws.amazon.com/securityhub/latest/userguide/create-associate-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateConfigurationPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/create-configuration-policy.html)」を参照してください。

### `create-finding-aggregator`
<a name="securityhub_CreateFindingAggregator_cli_2_topic"></a>

次のコード例は、`create-finding-aggregator` を使用する方法を示しています。

**AWS CLI**  
**検出結果の集約を有効にするには**  
次の `create-finding-aggregator` の例では、検出結果の集約を設定します。これは、米国東部 (バージニア) を集約リージョンとして指定する米国東部 (バージニア) から実行されます。指定されたリージョンのみをリンクし、新しいリージョンを自動的にリンクするとは限らないことを示します。リンクされたリージョンとして、米国西部 (北カリフォルニア) と米国西部 (オレゴン) が選択されます。  

```
aws securityhub create-finding-aggregator \
    --region us-east-1 \
    --region-linking-mode SPECIFIED_REGIONS \
    --regions us-west-1,us-west-2
```
出力:  

```
{
    "FindingAggregatorArn": "arn:aws:securityhub:us-east-1:222222222222:finding-aggregator/123e4567-e89b-12d3-a456-426652340000",
    "FindingAggregationRegion": "us-east-1",
    "RegionLinkingMode": "SPECIFIED_REGIONS",
    "Regions": "us-west-1,us-west-2"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[検出結果の集約を有効にする](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-aggregation-enable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFindingAggregator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/create-finding-aggregator.html)」を参照してください。

### `create-insight`
<a name="securityhub_CreateInsight_cli_2_topic"></a>

次のコード例は、`create-insight` を使用する方法を示しています。

**AWS CLI**  
**カスタムインサイトを作成するには**  
次の`create-insight`例では、ロールに関連する重要な検出結果を返す「重要な AWS ロールの検出結果」という名前のカスタムインサイトを作成します。  

```
aws securityhub create-insight \
    --filters '{"ResourceType": [{ "Comparison": "EQUALS", "Value": "AwsIamRole"}], "SeverityLabel": [{"Comparison": "EQUALS", "Value": "CRITICAL"}]}' \
    --group-by-attribute "ResourceId" \
    --name "Critical role findings"
```
出力:  

```
{
    "InsightArn": "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムインサイトの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-custom-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateInsight](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/create-insight.html)」を参照してください。

### `create-members`
<a name="securityhub_CreateMembers_cli_2_topic"></a>

次のコード例は、`create-members` を使用する方法を示しています。

**AWS CLI**  
**アカウントをメンバーアカウントとして追加するには**  
次の `create-members` の例では、リクエスト元の管理者アカウントに 2 つのアカウントをメンバーアカウントとして追加します。  

```
aws securityhub create-members \
    --account-details '[{"AccountId": "123456789111"}, {"AccountId": "123456789222"}]'
```
出力:  

```
{
    "UnprocessedAccounts": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/create-members.html)」を参照してください。

### `decline-invitations`
<a name="securityhub_DeclineInvitations_cli_2_topic"></a>

次のコード例は、`decline-invitations` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントへの招待を拒否するには**  
次の `decline-invitations` の例では、指定された管理者アカウントのメンバーアカウントへの招待を拒否します。メンバーアカウントはリクエスト元のアカウントです。  

```
aws securityhub decline-invitations \
    --account-ids "123456789012"
```
出力:  

```
{
    "UnprocessedAccounts": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeclineInvitations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/decline-invitations.html)」を参照してください。

### `delete-action-target`
<a name="securityhub_DeleteActionTarget_cli_2_topic"></a>

次のコード例は、`delete-action-target` を使用する方法を示しています。

**AWS CLI**  
**カスタムアクションを削除するには**  
次の `delete-action-target` の例では、指定された ARN によって識別されたカスタムアクションを削除します。  

```
aws securityhub delete-action-target \
    --action-target-arn "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation"
```
出力:  

```
{
    "ActionTargetArn": "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムアクションを作成し、CloudWatch Events ルールに関連付ける](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-cloudwatch-events.html#securityhub-cwe-configure)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteActionTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/delete-action-target.html)」を参照してください。

### `delete-configuration-policy`
<a name="securityhub_DeleteConfigurationPolicy_cli_2_topic"></a>

次のコード例は、`delete-configuration-policy` を使用する方法を示しています。

**AWS CLI**  
**設定ポリシーを削除するには**  
次の `delete-configuration-policy` の例では、指定された設定ポリシーを削除します。  

```
aws securityhub delete-configuration-policy \
    --identifier "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの削除と関連付けの解除](https://docs.aws.amazon.com/securityhub/latest/userguide/delete-disassociate-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteConfigurationPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/delete-configuration-policy.html)」を参照してください。

### `delete-finding-aggregator`
<a name="securityhub_DeleteFindingAggregator_cli_2_topic"></a>

次のコード例は、`delete-finding-aggregator` を使用する方法を示しています。

**AWS CLI**  
**検索結果の集約を停止するには**  
次の `delete-finding-aggregator` の例では、検索結果の集約を停止します。コマンドは、集約リージョンである米国東部 (バージニア) から実行されます。  

```
aws securityhub delete-finding-aggregator \
    --region us-east-1 \
    --finding-aggregator-arn arn:aws:securityhub:us-east-1:222222222222:finding-aggregator/123e4567-e89b-12d3-a456-426652340000
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[検索結果の集約を停止する](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-aggregation-stop.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFindingAggregator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/delete-finding-aggregator.html)」を参照してください。

### `delete-insight`
<a name="securityhub_DeleteInsight_cli_2_topic"></a>

次のコード例は、`delete-insight` を使用する方法を示しています。

**AWS CLI**  
**カスタムインサイトを削除するには**  
次の `delete-insight` の例では、指定された ARN を持つカスタムインサイトを削除します。  

```
aws securityhub delete-insight \
    --insight-arn "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
```
出力:  

```
{
   "InsightArn": "arn:aws:securityhub:eu-central-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムインサイトの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-custom-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInsight](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/delete-insight.html)」を参照してください。

### `delete-invitations`
<a name="securityhub_DeleteInvitations_cli_2_topic"></a>

次のコード例は、`delete-invitations` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントへの招待を削除するには**  
次の `delete-invitations` の例では、指定された管理者アカウントのメンバーアカウントへの招待を削除します。メンバーアカウントはリクエスト元のアカウントです。  

```
aws securityhub delete-invitations \
    --account-ids "123456789012"
```
出力:  

```
{
    "UnprocessedAccounts": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInvitations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/delete-invitations.html)」を参照してください。

### `delete-members`
<a name="securityhub_DeleteMembers_cli_2_topic"></a>

次のコード例は、`delete-members` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントを削除するには**  
次の `delete-members` の例では、リクエスト元の管理者アカウントから指定されたメンバーアカウントを削除します。  

```
aws securityhub delete-members \
    --account-ids "123456789111" "123456789222"
```
出力:  

```
{
    "UnprocessedAccounts": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/delete-members.html)」を参照してください。

### `describe-action-targets`
<a name="securityhub_DescribeActionTargets_cli_2_topic"></a>

次のコード例は、`describe-action-targets` を使用する方法を示しています。

**AWS CLI**  
**カスタムアクションの詳細情報を取得するには**  
次の `describe-action-targets` の例では、指定された ARN によって識別されるカスタムアクションに関する情報を取得します。  

```
aws securityhub describe-action-targets \
    --action-target-arns "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation"
```
出力:  

```
{
    "ActionTargets": [
        {
            "ActionTargetArn": "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation",
            "Description": "Action to send the finding for remediation tracking",
            "Name": "Send to remediation"
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムアクションを作成し、CloudWatch Events ルールに関連付ける](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-cloudwatch-events.html#securityhub-cwe-configure)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeActionTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/describe-action-targets.html)」を参照してください。

### `describe-hub`
<a name="securityhub_DescribeHub_cli_2_topic"></a>

次のコード例は、`describe-hub` を使用する方法を示しています。

**AWS CLI**  
**ハブリソースに関する情報を取得するには**  
次の `describe-hub` の例では、指定されたハブリソースのサブスクリプション日と他の構成設定を返します。ハブリソースは ARN によって識別されます。  

```
aws securityhub describe-hub \
    --hub-arn "arn:aws:securityhub:us-west-1:123456789012:hub/default"
```
出力:  

```
{
    "HubArn": "arn:aws:securityhub:us-west-1:123456789012:hub/default",
    "SubscribedAt": "2019-11-19T23:15:10.046Z",
    "AutoEnableControls": true,
    "ControlFindingGenerator": "SECURITY_CONTROL"
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[AWS::SecurityHub::Hub](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-securityhub-hub.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeHub](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/describe-hub.html)」を参照してください。

### `describe-organization-configuration`
<a name="securityhub_DescribeOrganizationConfiguration_cli_2_topic"></a>

次のコード例は、`describe-organization-configuration` を使用する方法を示しています。

**AWS CLI**  
**組織の Security Hub の設定方法を表示するには**  
次の `describe-organization-configuration` の例では、Security Hub で組織を設定する方法に関する情報を返します。この例では、組織は中央設定を使用します。Security Hub 管理者アカウントのみ、このコマンドを実行できます。  

```
aws securityhub describe-organization-configuration
```
出力:  

```
{
    "AutoEnable": false,
    "MemberAccountLimitReached": false,
    "AutoEnableStandards": "NONE",
    "OrganizationConfiguration": {
        "ConfigurationType": "LOCAL",
        "Status": "ENABLED",
        "StatusMessage": "Central configuration has been enabled successfully"
    }
}
```
詳細については、*AWS Security Hub ユーザーガイド*の[AWS 「Organizations でアカウントを管理する](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts-orgs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOrganizationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/describe-organization-configuration.html)」を参照してください。

### `describe-products`
<a name="securityhub_DescribeProducts_cli_2_topic"></a>

次のコード例は、`describe-products` を使用する方法を示しています。

**AWS CLI**  
**使用可能な製品統合に関する情報を返すには**  
次の `describe-products` の例では、使用可能な製品統合を一度に 1 つずつ返します。  

```
aws securityhub describe-products \
    --max-results 1
```
出力:  

```
{
    "NextToken": "U2FsdGVkX18vvPlOqb7RDrWRWVFBJI46MOIAb+nZmRJmR15NoRi2gm13sdQEn3O/pq/78dGs+bKpgA+7HMPHO0qX33/zoRI+uIG/F9yLNhcOrOWzFUdy36JcXLQji3Rpnn/cD1SVkGA98qI3zPOSDg==",
    "Products": [
        {
            "ProductArn": "arn:aws:securityhub:us-west-1:123456789333:product/crowdstrike/crowdstrike-falcon",
            "ProductName": "CrowdStrike Falcon",
            "CompanyName": "CrowdStrike",
            "Description": "CrowdStrike Falcon's single lightweight sensor unifies next-gen antivirus, endpoint detection and response, and 24/7 managed hunting, via the cloud.",
            "Categories": [
                "Endpoint Detection and Response (EDR)",
                "AV Scanning and Sandboxing",
                "Threat Intelligence Feeds and Reports",
                "Endpoint Forensics",
                "Network Forensics"
            ],
            "IntegrationTypes": [
                "SEND_FINDINGS_TO_SECURITY_HUB"
            ],
            "MarketplaceUrl": "https://aws.amazon.com/marketplace/seller-profile?id=a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ActivationUrl": "https://falcon.crowdstrike.com/support/documentation",
            "ProductSubscriptionResourcePolicy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"123456789333\"},\"Action\":[\"securityhub:BatchImportFindings\"],\"Resource\":\"arn:aws:securityhub:us-west-1:123456789012:product-subscription/crowdstrike/crowdstrike-falcon\",\"Condition\":{\"StringEquals\":{\"securityhub:TargetAccount\":\"123456789012\"}}},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"123456789012\"},\"Action\":[\"securityhub:BatchImportFindings\"],\"Resource\":\"arn:aws:securityhub:us-west-1:123456789333:product/crowdstrike/crowdstrike-falcon\",\"Condition\":{\"StringEquals\":{\"securityhub:TargetAccount\":\"123456789012\"}}}]}"
        }
   ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[製品統合の管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-integrations-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProducts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/describe-products.html)」を参照してください。

### `describe-standards-controls`
<a name="securityhub_DescribeStandardsControls_cli_2_topic"></a>

次のコード例は、`describe-standards-controls` を使用する方法を示しています。

**AWS CLI**  
有効な標準のコントロールの一覧をリクエストするには  
次の `describe-standards-controls` の例では、リクエスタアカウントの PCI DSS 標準へのサブスクリプション内のコントロール一覧をリクエストします。リクエストは、一度に 2 つのコントロールを返します。  

```
aws securityhub describe-standards-controls \
    --standards-subscription-arn "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1" \
    --max-results 2
```
出力:  

```
{
    "Controls": [
        {
            "StandardsControlArn": "arn:aws:securityhub:us-west-1:123456789012:control/pci-dss/v/3.2.1/PCI.AutoScaling.1",
            "ControlStatus": "ENABLED",
            "ControlStatusUpdatedAt": "2020-05-15T18:49:04.473000+00:00",
            "ControlId": "PCI.AutoScaling.1",
            "Title": "Auto scaling groups associated with a load balancer should use health checks",
            "Description": "This AWS control checks whether your Auto Scaling groups that are associated with a load balancer are using Elastic Load Balancing health checks.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/PCI.AutoScaling.1/remediation",
            "SeverityRating": "LOW",
            "RelatedRequirements": [
                "PCI DSS 2.2"
            ]
        },
        {
            "StandardsControlArn": "arn:aws:securityhub:us-west-1:123456789012:control/pci-dss/v/3.2.1/PCI.CW.1",
            "ControlStatus": "ENABLED",
            "ControlStatusUpdatedAt": "2020-05-15T18:49:04.498000+00:00",
            "ControlId": "PCI.CW.1",
            "Title": "A log metric filter and alarm should exist for usage of the \"root\" user",
            "Description": "This control checks for the CloudWatch metric filters using the following pattern { $.userIdentity.type = \"Root\" && $.userIdentity.invokedBy NOT EXISTS && $.eventType != \"AwsServiceEvent\" } It checks that the log group name is configured for use with active multi-region CloudTrail, that there is at least one Event Selector for a Trail with IncludeManagementEvents set to true and ReadWriteType set to All, and that there is at least one active subscriber to an SNS topic associated with the alarm.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/PCI.CW.1/remediation",
            "SeverityRating": "MEDIUM",
            "RelatedRequirements": [
                "PCI DSS 7.2.1"
            ]
        }
    ],
    "NextToken": "U2FsdGVkX1+eNkPoZHVl11ip5HUYQPWSWZGmftcmJiHL8JoKEsCDuaKayiPDyLK+LiTkShveoOdvfxXCkOBaGhohIXhsIedN+LSjQV/l7kfCfJcq4PziNC1N9xe9aq2pjlLVZnznTfSImrodT5bRNHe4fELCQq/z+5ka+5Lzmc11axcwTd5lKgQyQqmUVoeriHZhyIiBgWKf7oNYdBVG8OEortVWvSkoUTt+B2ThcnC7l43kI0UNxlkZ6sc64AsW"
}
```
この標準の詳細については、「AWS Security Hub ユーザーガイド」の「[標準の詳細の表示](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-view-controls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStandardsControls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/describe-standards-controls.html)」を参照してください。

### `describe-standards`
<a name="securityhub_DescribeStandards_cli_2_topic"></a>

次のコード例は、`describe-standards` を使用する方法を示しています。

**AWS CLI**  
**使用可能な標準のリストを返すには**  
次の `describe-standards` の例では、使用可能な標準のリストを返します。  

```
aws securityhub describe-standards
```
出力:  

```
{
    "Standards": [
        {
            "StandardsArn": "arn:aws:securityhub:us-west-1::standards/aws-foundational-security-best-practices/v/1.0.0",
            "Name": "AWS Foundational Security Best Practices v1.0.0",
            "Description": "The AWS Foundational Security Best Practices standard is a set of automated security checks that detect when AWS accounts and deployed resources do not align to security best practices. The standard is defined by AWS security experts. This curated set of controls helps improve your security posture in AWS, and cover AWS's most popular and foundational services.",
            "EnabledByDefault": true
        },
        {
            "StandardsArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",
            "Name": "CIS AWS Foundations Benchmark v1.2.0",
            "Description": "The Center for Internet Security (CIS) AWS Foundations Benchmark v1.2.0 is a set of security configuration best practices for AWS. This Security Hub standard automatically checks for your compliance readiness against a subset of CIS requirements.",
            "EnabledByDefault": true
        },
        {
            "StandardsArn": "arn:aws:securityhub:us-west-1::standards/pci-dss/v/3.2.1",
            "Name": "PCI DSS v3.2.1",
            "Description": "The Payment Card Industry Data Security Standard (PCI DSS) v3.2.1 is an information security standard for entities that store, process, and/or transmit cardholder data. This Security Hub standard automatically checks for your compliance readiness against a subset of PCI DSS requirements.",
            "EnabledByDefault": false
        }
    ]
}
```
詳細については、[「 Security Hub ユーザーガイド」の「 AWS Security Hub のセキュリティ標準](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeStandards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/describe-standards.html)」を参照してください。

### `disable-import-findings-for-product`
<a name="securityhub_DisableImportFindingsForProduct_cli_2_topic"></a>

次のコード例は、`disable-import-findings-for-product` を使用する方法を示しています。

**AWS CLI**  
**製品統合からの検出結果の受信を停止するには**  
次の `disable-import-findings-for-product` の例では、製品統合への指定されたサブスクリプションの検出結果の流れを無効にします。  

```
aws securityhub disable-import-findings-for-product \
    --product-subscription-arn "arn:aws:securityhub:us-west-1:123456789012:product-subscription/crowdstrike/crowdstrike-falcon"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[製品統合の管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-integrations-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableImportFindingsForProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/disable-import-findings-for-product.html)」を参照してください。

### `disable-organization-admin-account`
<a name="securityhub_DisableOrganizationAdminAccount_cli_2_topic"></a>

次のコード例は、`disable-organization-admin-account` を使用する方法を示しています。

**AWS CLI**  
**Security Hub 管理者アカウントを削除するには**  
次の の`disable-organization-admin-account`例では、指定されたアカウントの AWS Organizations の Security Hub 管理者アカウントとしての割り当てを取り消します。  

```
aws securityhub disable-organization-admin-account \
    --admin-account-id 777788889999
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 管理者アカウントの指定](https://docs.aws.amazon.com/securityhub/latest/userguide/designate-orgs-admin-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableOrganizationAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/disable-organization-admin-account.html)」を参照してください。

### `disable-security-hub`
<a name="securityhub_DisableSecurityHub_cli_2_topic"></a>

次の例は、`disable-security-hub` を使用する方法を説明しています。

**AWS CLI**  
** AWS Security Hub を無効にするには**  
次の の`disable-security-hub`例では、リクエスト元のアカウントの AWS Security Hub を無効にします。  

```
aws securityhub disable-security-hub
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 Security Hub ユーザーガイド」の「Security Hub の無効化](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-disable.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisableSecurityHub](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/disable-security-hub.html)」を参照してください。

### `disassociate-from-administrator-account`
<a name="securityhub_DisassociateFromAdministratorAccount_cli_2_topic"></a>

次のコード例は、`disassociate-from-administrator-account` を使用する方法を示しています。

**AWS CLI**  
**管理者アカウントから関連付けを解除するには**  
次の `disassociate-from-administrator-account` の例では、リクエスト元のアカウントと現在の管理者アカウントの関連付けを解除します。  

```
aws securityhub disassociate-from-administrator-account
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateFromAdministratorAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/disassociate-from-administrator-account.html)」を参照してください。

### `disassociate-from-master-account`
<a name="securityhub_DisassociateFromMasterAccount_cli_2_topic"></a>

次のコード例は、`disassociate-from-master-account` を使用する方法を示しています。

**AWS CLI**  
**管理者アカウントから関連付けを解除するには**  
次の `disassociate-from-master-account` の例では、リクエスト元のアカウントと現在の管理者アカウントの関連付けを解除します。  

```
aws securityhub disassociate-from-master-account
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateFromMasterAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/disassociate-from-master-account.html)」を参照してください。

### `disassociate-members`
<a name="securityhub_DisassociateMembers_cli_2_topic"></a>

次のコード例は、`disassociate-members` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントの関連付けを解除するには**  
次の `disassociate-members` の例では、リクエスト元の管理者アカウントから指定されたメンバーアカウントの関連付けを解除します。  

```
aws securityhub disassociate-members  \
    --account-ids "123456789111" "123456789222"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/disassociate-members.html)」を参照してください。

### `enable-import-findings-for-product`
<a name="securityhub_EnableImportFindingsForProduct_cli_2_topic"></a>

次のコード例は、`enable-import-findings-for-product` を使用する方法を示しています。

**AWS CLI**  
**製品統合からの検出結果の受け取りを開始するには**  
次の `enable-import-findings-for-product` の例では、指定された製品統合からの検出結果の流れを有効にします。  

```
aws securityhub enable-import-findings-for-product \
    --product-arn "arn:aws:securityhub:us-east-1:123456789333:product/crowdstrike/crowdstrike-falcon"
```
出力:  

```
{
    "ProductSubscriptionArn": "arn:aws:securityhub:us-east-1:123456789012:product-subscription/crowdstrike/crowdstrike-falcon"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[製品統合の管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-integrations-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableImportFindingsForProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/enable-import-findings-for-product.html)」を参照してください。

### `enable-organization-admin-account`
<a name="securityhub_EnableOrganizationAdminAccount_cli_2_topic"></a>

次のコード例は、`enable-organization-admin-account` を使用する方法を示しています。

**AWS CLI**  
**組織アカウントを Security Hub 管理者アカウントとして指定するには**  
次の `enable-organization-admin-account` の例では、指定されたアカウントを Security Hub 管理者アカウントとして指定します。  

```
aws securityhub enable-organization-admin-account \
    --admin-account-id 777788889999
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 管理者アカウントの指定](https://docs.aws.amazon.com/securityhub/latest/userguide/designate-orgs-admin-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableOrganizationAdminAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/enable-organization-admin-account.html)」を参照してください。

### `enable-security-hub`
<a name="securityhub_EnableSecurityHub_cli_2_topic"></a>

次の例は、`enable-security-hub` を使用する方法を説明しています。

**AWS CLI**  
** AWS Security Hub を有効にするには**  
次の`enable-security-hub`例では、リクエスト元のアカウントの AWS Security Hub を有効にします。デフォルトの標準が有効になるように Security Hub を設定します。ハブリソースの場合、タグ `Department` に値 `Security` を割り当てます。  

```
aws securityhub enable-security-hub \
    --enable-default-standards \
    --tags '{"Department": "Security"}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub を有効にする](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-settingup.html#securityhub-enable)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[EnableSecurityHub](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/enable-security-hub.html)」を参照してください。

### `get-administrator-account`
<a name="securityhub_GetAdministratorAccount_cli_2_topic"></a>

次のコード例は、`get-administrator-account` を使用する方法を示しています。

**AWS CLI**  
**管理者アカウントに関する情報を取得するには**  
次の `get-administrator-account` の例では、リクエスト元アカウントの管理者アカウントに関する情報を取得します。  

```
aws securityhub get-administrator-account
```
出力:  

```
{
   "Master": {
      "AccountId": "123456789012",
      "InvitationId": "7ab938c5d52d7904ad09f9e7c20cc4eb",
      "InvitedAt": 2020-06-01T20:21:18.042000+00:00,
      "MemberStatus": "ASSOCIATED"
   }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAdministratorAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-administrator-account.html)」を参照してください。

### `get-configuration-policy-association`
<a name="securityhub_GetConfigurationPolicyAssociation_cli_2_topic"></a>

次のコード例は、`get-configuration-policy-association` を使用する方法を示しています。

**AWS CLI**  
**ターゲットの設定関連付けの詳細を取得するには**  
次の `get-configuration-policy-association` の例では、指定されたターゲットの関連付けに関する詳細情報を取得します。ターゲットのアカウント ID、組織単位 ID、またはルート ID を指定できます。  

```
aws securityhub get-configuration-policy-association \
    --target '{"OrganizationalUnitId": "ou-6hi7-8j91kl2m"}'
```
出力:  

```
{
    "ConfigurationPolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
    "TargetId": "ou-6hi7-8j91kl2m",
    "TargetType": "ORGANIZATIONAL_UNIT",
    "AssociationType": "APPLIED",
    "UpdatedAt": "2023-09-26T21:13:01.816000+00:00",
    "AssociationStatus": "SUCCESS",
    "AssociationStatusMessage": "Association applied successfully on this target."
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの表示](https://docs.aws.amazon.com/securityhub/latest/userguide/view-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConfigurationPolicyAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-configuration-policy-association.html)」を参照してください。

### `get-configuration-policy`
<a name="securityhub_GetConfigurationPolicy_cli_2_topic"></a>

次のコード例は、`get-configuration-policy` を使用する方法を示しています。

**AWS CLI**  
**設定ポリシーの詳細を表示するには**  
次の `get-configuration-policy` の例では、指定された設定ポリシーの詳細情報を取得します。  

```
aws securityhub get-configuration-policy \
   --identifier "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
```
出力:  

```
{
    "Arn": "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "Id": "ce5ed1e7-9639-4e2f-9313-fa87fcef944b",
    "Name": "SampleConfigurationPolicy",
    "Description": "SampleDescription",
    "UpdatedAt": "2023-11-28T20:28:04.494000+00:00",
    "CreatedAt": "2023-11-28T20:28:04.494000+00:00",
    "ConfigurationPolicy": {
        "SecurityHub": {
            "ServiceEnabled": true,
            "EnabledStandardIdentifiers": [
                "arn:aws:securityhub:eu-central-1::standards/aws-foundational-security-best-practices/v/1.0.0",
                "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0"
            ],
            "SecurityControlsConfiguration": {
                "DisabledSecurityControlIdentifiers": [
                    "CloudTrail.2"
                ],
                "SecurityControlCustomParameters": [
                    {
                        "SecurityControlId": "ACM.1",
                        "Parameters": {
                            "daysToExpiration": {
                                "ValueType": "CUSTOM",
                                "Value": {
                                    "Integer": 15
                                }
                            }
                        }
                    }
                ]
            }
        }
    }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの表示](https://docs.aws.amazon.com/securityhub/latest/userguide/view-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConfigurationPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-configuration-policy.html)」を参照してください。

### `get-enabled-standards`
<a name="securityhub_GetEnabledStandards_cli_2_topic"></a>

次のコード例は、`get-enabled-standards` を使用する方法を示しています。

**AWS CLI**  
**有効な標準に関する情報を取得するには**  
次の `get-enabled-standards` の例では、PCI DSS 標準に関する情報を取得します。  

```
aws securityhub get-enabled-standards \
    --standards-subscription-arn "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1"
```
出力:  

```
{
    "StandardsSubscriptions": [
        {
            "StandardsArn": "arn:aws:securityhub:us-west-1::standards/pci-dss/v/3.2.1",
            "StandardsInput": { },
            "StandardsStatus": "READY",
            "StandardsSubscriptionArn": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1"
        }
    ]
}
```
詳細については、[「 Security Hub ユーザーガイド」の「 AWS Security Hub のセキュリティ標準](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEnabledStandards](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-enabled-standards.html)」を参照してください。

### `get-finding-aggregator`
<a name="securityhub_GetFindingAggregator_cli_2_topic"></a>

次のコード例は、`get-finding-aggregator` を使用する方法を示しています。

**AWS CLI**  
**現在の検索結果の集約設定を取得するには**  
次の `get-finding-aggregator` の例では、現在の検出結果の集約設定を取得します。  

```
aws securityhub get-finding-aggregator \
    --finding-aggregator-arn arn:aws:securityhub:us-east-1:222222222222:finding-aggregator/123e4567-e89b-12d3-a456-426652340000
```
出力:  

```
{
    "FindingAggregatorArn": "arn:aws:securityhub:us-east-1:222222222222:finding-aggregator/123e4567-e89b-12d3-a456-426652340000",
    "FindingAggregationRegion": "us-east-1",
    "RegionLinkingMode": "SPECIFIED_REGIONS",
    "Regions": "us-west-1,us-west-2"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[現在の検出結果の集約設定を表示する](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-aggregation-view-config.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFindingAggregator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-finding-aggregator.html)」を参照してください。

### `get-finding-history`
<a name="securityhub_GetFindingHistory_cli_2_topic"></a>

次のコード例は、`get-finding-history` を使用する方法を示しています。

**AWS CLI**  
**検出結果の履歴を取得するには**  
次の `get-finding-history` の例では、指定された検出結果の過去 90 日間の履歴を取得します。この例では、結果は検出結果履歴の 2 つのレコードに制限されています。  

```
aws securityhub get-finding-history \
    --finding-identifier Id="arn:aws:securityhub:us-east-1:123456789012:security-control/S3.17/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",ProductArn="arn:aws:securityhub:us-east-1::product/aws/securityhub"
```
出力:  

```
{
    "Records": [
        {
            "FindingIdentifier": {
                "Id": "arn:aws:securityhub:us-east-1:123456789012:security-control/S3.17/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
                "ProductArn": "arn:aws:securityhub:us-east-1::product/aws/securityhub"
            },
            "UpdateTime": "2023-06-02T03:15:25.685000+00:00",
            "FindingCreated": false,
            "UpdateSource": {
                "Type": "BATCH_IMPORT_FINDINGS",
                "Identity": "arn:aws:securityhub:us-east-1::product/aws/securityhub"
            },
            "Updates": [
                {
                    "UpdatedField": "Compliance.RelatedRequirements",
                    "OldValue": "[\"NIST.800-53.r5 SC-12(2)\",\"NIST.800-53.r5 SC-12(3)\",\"NIST.800-53.r5 SC-12(6)\",\"NIST.800-53.r5 CM-3(6)\",\"NIST.800-53.r5 SC-13\",\"NIST.800-53.r5 SC-28\",\"NIST.800-53.r5 SC-28(1)\",\"NIST.800-53.r5 SC-7(10)\"]",
                    "NewValue": "[\"NIST.800-53.r5 SC-12(2)\",\"NIST.800-53.r5 CM-3(6)\",\"NIST.800-53.r5 SC-13\",\"NIST.800-53.r5 SC-28\",\"NIST.800-53.r5 SC-28(1)\",\"NIST.800-53.r5 SC-7(10)\",\"NIST.800-53.r5 CA-9(1)\",\"NIST.800-53.r5 SI-7(6)\",\"NIST.800-53.r5 AU-9\"]"
                },
                {
                    "UpdatedField": "LastObservedAt",
                    "OldValue": "2023-06-01T09:15:38.587Z",
                    "NewValue": "2023-06-02T03:15:22.946Z"
                },
                {
                    "UpdatedField": "UpdatedAt",
                    "OldValue": "2023-06-01T09:15:31.049Z",
                    "NewValue": "2023-06-02T03:15:14.861Z"
                },
                {
                    "UpdatedField": "ProcessedAt",
                    "OldValue": "2023-06-01T09:15:41.058Z",
                    "NewValue": "2023-06-02T03:15:25.685Z"
                }
            ]
        },
        {
            "FindingIdentifier": {
                "Id": "arn:aws:securityhub:us-east-1:123456789012:security-control/S3.17/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
                "ProductArn": "arn:aws:securityhub:us-east-1::product/aws/securityhub"
            },
            "UpdateTime": "2023-05-23T02:06:51.518000+00:00",
            "FindingCreated": "true",
            "UpdateSource": {
                "Type": "BATCH_IMPORT_FINDINGS",
                "Identity": "arn:aws:securityhub:us-east-1::product/aws/securityhub"
            },
            "Updates": []
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[検出結果の履歴](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-view-details.html#finding-history)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFindingHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-finding-history.html)」を参照してください。

### `get-findings`
<a name="securityhub_GetFindings_cli_2_topic"></a>

次のコード例は、`get-findings` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定の標準に対して生成された検出結果を返すには**  
次の `get-findings` の例では、PCI DSS 標準の検出結果を返します。  

```
aws securityhub get-findings \
    --filters '{"GeneratorId":[{"Value": "pci-dss","Comparison":"PREFIX"}]}' \
    --max-items 1
```
出力:  

```
{
    "Findings": [
        {
            "SchemaVersion": "2018-10-08",
            "Id": "arn:aws:securityhub:eu-central-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ProductArn": "arn:aws:securityhub:us-west-1::product/aws/securityhub",
            "GeneratorId": "pci-dss/v/3.2.1/PCI.Lambda.2",
            "AwsAccountId": "123456789012",
            "Types": [
                "Software and Configuration Checks/Industry and Regulatory Standards/PCI-DSS"
            ],
            "FindingProviderFields": {
                "Severity": {
                    "Original": 0,
                    "Label": "INFORMATIONAL"
                },
                "Types": [
                    "Software and Configuration Checks/Industry and Regulatory Standards/PCI-DSS"
                ]
            },
            "FirstObservedAt": "2020-06-02T14:02:49.159Z",
            "LastObservedAt": "2020-06-02T14:02:52.397Z",
            "CreatedAt": "2020-06-02T14:02:49.159Z",
            "UpdatedAt": "2020-06-02T14:02:52.397Z",
            "Severity": {
                "Original": 0,
                "Label": "INFORMATIONAL",
                "Normalized": 0
            },
            "Title": "PCI.Lambda.2 Lambda functions should be in a VPC",
            "Description": "This AWS control checks whether a Lambda function is in a VPC.",
            "Remediation": {
                "Recommendation": {
                    "Text": "For directions on how to fix this issue, please consult the AWS Security Hub PCI DSS documentation.",
                    "Url": "https://docs.aws.amazon.com/console/securityhub/PCI.Lambda.2/remediation"
                }
            },
            "ProductFields": {
                "StandardsArn": "arn:aws:securityhub:::standards/pci-dss/v/3.2.1",
                "StandardsSubscriptionArn": "arn:aws:securityhub:us-west-1:123456789012:subscription/pci-dss/v/3.2.1",
                "ControlId": "PCI.Lambda.2",
                "RecommendationUrl": "https://docs.aws.amazon.com/console/securityhub/PCI.Lambda.2/remediation",
                "RelatedAWSResources:0/name": "securityhub-lambda-inside-vpc-0e904a3b",
                "RelatedAWSResources:0/type": "AWS::Config::ConfigRule",
                "StandardsControlArn": "arn:aws:securityhub:us-west-1:123456789012:control/pci-dss/v/3.2.1/PCI.Lambda.2",
                "aws/securityhub/SeverityLabel": "INFORMATIONAL",
                "aws/securityhub/ProductName": "Security Hub",
                "aws/securityhub/CompanyName": "AWS",
                "aws/securityhub/FindingId": "arn:aws:securityhub:eu-central-1::product/aws/securityhub/arn:aws:securityhub:eu-central-1:123456789012:subscription/pci-dss/v/3.2.1/PCI.Lambda.2/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        },
            "Resources": [
                {
                    "Type": "AwsAccount",
                    "Id": "AWS::::Account:123456789012",
                    "Partition": "aws",
                    "Region": "us-west-1"
                }
            ],
            "Compliance": {
                "Status": "PASSED",
                "RelatedRequirements": [
                    "PCI DSS 1.2.1",
                    "PCI DSS 1.3.1",
                    "PCI DSS 1.3.2",
                    "PCI DSS 1.3.4"
                ]
            },
            "WorkflowState": "NEW",
            "Workflow": {
                "Status": "NEW"
            },
            "RecordState": "ARCHIVED"
        }
    ],
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxfQ=="
}
```
**例 2: ワークフローステータスが NOTIFIED である重大な検出結果を返すには**  
次の `get-findings` の例では、重要度ラベル値が CRITICAL で、ワークフローステータスが NOTIFIED の結果を返します。結果は、信頼度の値で降順で並べ替えられます。  

```
aws securityhub get-findings \
    --filters '{"SeverityLabel":[{"Value": "CRITICAL","Comparison":"EQUALS"}],"WorkflowStatus": [{"Value":"NOTIFIED","Comparison":"EQUALS"}]}' \
    --sort-criteria '{ "Field": "Confidence", "SortOrder": "desc"}' \
    --max-items 1
```
出力:  

```
{
    "Findings": [
        {
            "SchemaVersion": "2018-10-08",
            "Id": "arn:aws:securityhub:us-west-1: 123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/1.13/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ProductArn": "arn:aws:securityhub:us-west-2::product/aws/securityhub",
            "GeneratorId": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0/rule/1.13",
            "AwsAccountId": "123456789012",
            "Types": [
                "Software and Configuration Checks/Industry and Regulatory Standards/CIS AWS Foundations Benchmark"
            ],
            "FindingProviderFields" {
                "Severity": {
                    "Original": 90,
                    "Label": "CRITICAL"
                },
                "Types": [
                    "Software and Configuration Checks/Industry and Regulatory Standards/CIS AWS Foundations Benchmark"
                ]
            },
            "FirstObservedAt": "2020-05-21T20:16:34.752Z",
            "LastObservedAt": "2020-06-09T08:16:37.171Z",
            "CreatedAt": "2020-05-21T20:16:34.752Z",
            "UpdatedAt": "2020-06-09T08:16:36.430Z",
            "Severity": {
                "Original": 90,
                "Label": "CRITICAL",
                "Normalized": 90
            },
            "Title": "1.13 Ensure MFA is enabled for the \"root\" account",
            "Description": "The root account is the most privileged user in an AWS account. MFA adds an extra layer of protection on top of a user name and password. With MFA enabled, when a user signs in to an AWS website, they will be prompted for their user name and password as well as for an authentication code from their AWS MFA device.",
            "Remediation": {
                "Recommendation": {
                    "Text": "For directions on how to fix this issue, please consult the AWS Security Hub CIS documentation.",
                    "Url": "https://docs.aws.amazon.com/console/securityhub/standards-cis-1.13/remediation"
                }
            },
            "ProductFields": {
                "StandardsGuideArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",
                "StandardsGuideSubscriptionArn": "arn:aws:securityhub:us-west-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0",
                "RuleId": "1.13",
                "RecommendationUrl": "https://docs.aws.amazon.com/console/securityhub/standards-cis-1.13/remediation",
                "RelatedAWSResources:0/name": "securityhub-root-account-mfa-enabled-5pftha",
                "RelatedAWSResources:0/type": "AWS::Config::ConfigRule",
                "StandardsControlArn": "arn:aws:securityhub:us-west-1:123456789012:control/cis-aws-foundations-benchmark/v/1.2.0/1.13",
                "aws/securityhub/SeverityLabel": "CRITICAL",
                "aws/securityhub/ProductName": "Security Hub",
                "aws/securityhub/CompanyName": "AWS",
                "aws/securityhub/FindingId": "arn:aws:securityhub:us-west-1::product/aws/securityhub/arn:aws:securityhub:us-west-1:123456789012:subscription/cis-aws-foundations-benchmark/v/1.2.0/1.13/finding/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
            },
            "Resources": [
                {
                    "Type": "AwsAccount",
                    "Id": "AWS::::Account:123456789012",
                    "Partition": "aws",
                    "Region": "us-west-1"
                }
            ],
            "Compliance": {
                "Status": "FAILED"
            },
            "WorkflowState": "NEW",
            "Workflow": {
                "Status": "NOTIFIED"
            },
            "RecordState": "ACTIVE"
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[検出結果のフィルタリングとグループ化](https://docs.aws.amazon.com/securityhub/latest/userguide/findings-filtering-grouping.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFindings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-findings.html)」を参照してください。

### `get-insight-results`
<a name="securityhub_GetInsightResults_cli_2_topic"></a>

次のコード例は、`get-insight-results` を使用する方法を示しています。

**AWS CLI**  
**インサイトの結果を取得するには**  
次の `get-insight-results` の例では、指定された ARN を持つインサイトのインサイト結果のリストを返します。  

```
aws securityhub get-insight-results \
    --insight-arn "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
```
出力:  

```
{
    "InsightResults": {
        "GroupByAttribute": "ResourceId",
        "InsightArn": "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "ResultValues": [
            {
                "Count": 10,
                "GroupByAttributeValue": "AWS::::Account:123456789111"
            },
            {
                "Count": 3,
                "GroupByAttributeValue": "AWS::::Account:123456789222"
            }
        ]
    }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[インサイト結果と検出結果の表示とアクションの実行](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-insights-view-take-action.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInsightResults](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-insight-results.html)」を参照してください。

### `get-insights`
<a name="securityhub_GetInsights_cli_2_topic"></a>

次のコード例は、`get-insights` を使用する方法を示しています。

**AWS CLI**  
**インサイトの詳細を取得するには**  
次の `get-insights` の例では、指定された ARN を使用してインサイトの設定の詳細情報を取得します。  

```
aws securityhub get-insights \
    --insight-arns "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
```
出力:  

```
{
    "Insights": [
        {
            "Filters": {
               "ResourceType": [
                    {
                        "Comparison": "EQUALS",
                        "Value": "AwsIamRole"
                    }
                ],
                "SeverityLabel": [
                    {
                        "Comparison": "EQUALS",
                        "Value": "CRITICAL"
                    }
                ],
            },
            "GroupByAttribute": "ResourceId",
            "InsightArn": "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Name": "Critical role findings"
        }
    ]
}
```
詳細については、[AWS Security Hub ユーザーガイドの「Security Hub のインサイト](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-insights.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInsights](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-insights.html)」を参照してください。

### `get-invitations-count`
<a name="securityhub_GetInvitationsCount_cli_2_topic"></a>

次のコード例は、`get-invitations-count` を使用する方法を示しています。

**AWS CLI**  
**受け入れられなかった招待の数を取得するには**  
次の `get-invitations-count` の例では、リクエスト元のアカウントが拒否したか応答しなかった招待の数を取得します。  

```
aws securityhub get-invitations-count
```
出力:  

```
{
  "InvitationsCount": 3
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInvitationsCount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-invitations-count.html)」を参照してください。

### `get-master-account`
<a name="securityhub_GetMasterAccount_cli_2_topic"></a>

次のコード例は、`get-master-account` を使用する方法を示しています。

**AWS CLI**  
**管理者アカウントに関する情報を取得するには**  
次の `get-master-account` の例では、リクエスト元アカウントの管理者アカウントに関する情報を取得します。  

```
aws securityhub get-master-account
```
出力:  

```
{
   "Master": {
      "AccountId": "123456789012",
      "InvitationId": "7ab938c5d52d7904ad09f9e7c20cc4eb",
      "InvitedAt": 2020-06-01T20:21:18.042000+00:00,
      "MemberStatus": "ASSOCIATED"
   }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMasterAccount](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-master-account.html)」を参照してください。

### `get-members`
<a name="securityhub_GetMembers_cli_2_topic"></a>

次のコード例は、`get-members` を使用する方法を示しています。

**AWS CLI**  
**選択したメンバーアカウントに関する情報を取得するには**  
次の `get-members` の例では、選択したメンバーアカウントに関する情報を取得します。  

```
aws securityhub get-members \
    --account-ids "444455556666" "777788889999"
```
出力:  

```
{
    "Members": [
        {
            "AccountId": "123456789111",
            "AdministratorId": "123456789012",
            "InvitedAt": 2020-06-01T20:15:15.289000+00:00,
            "MasterId": "123456789012",
            "MemberStatus": "ASSOCIATED",
            "UpdatedAt": 2020-06-01T20:15:15.289000+00:00
        },
        {
            "AccountId": "123456789222",
            "AdministratorId": "123456789012",
            "InvitedAt": 2020-06-01T20:15:15.289000+00:00,
            "MasterId": "123456789012",
            "MemberStatus": "ASSOCIATED",
            "UpdatedAt": 2020-06-01T20:15:15.289000+00:00
        }
    ],
    "UnprocessedAccounts": [ ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-members.html)」を参照してください。

### `get-security-control-definition`
<a name="securityhub_GetSecurityControlDefinition_cli_2_topic"></a>

次のコード例は、`get-security-control-definition` を使用する方法を示しています。

**AWS CLI**  
**セキュリティコントロール定義の詳細を取得するには**  
次の `get-security-control-definition` の例では、Security Hub セキュリティコントロールの定義の詳細情報を取得します。詳細には、コントロールタイトル、説明、利用可能なリージョン、パラメータ、その他の情報が含まれます。  

```
aws securityhub get-security-control-definition \
    --security-control-id ACM.1
```
出力:  

```
{
    "SecurityControlDefinition": {
        "SecurityControlId": "ACM.1",
        "Title": "Imported and ACM-issued certificates should be renewed after a specified time period",
        "Description": "This control checks whether an AWS Certificate Manager (ACM) certificate is renewed within the specified time period. It checks both imported certificates and certificates provided by ACM. The control fails if the certificate isn't renewed within the specified time period. Unless you provide a custom parameter value for the renewal period, Security Hub uses a default value of 30 days.",
        "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/ACM.1/remediation",
        "SeverityRating": "MEDIUM",
        "CurrentRegionAvailability": "AVAILABLE",
        "ParameterDefinitions": {
            "daysToExpiration": {
                "Description": "Number of days within which the ACM certificate must be renewed",
                "ConfigurationOptions": {
                    "Integer": {
                        "DefaultValue": 30,
                        "Min": 14,
                        "Max": 365
                    }
                }
            }
        }
    }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムコントロールパラメータ](https://docs.aws.amazon.com/securityhub/latest/userguide/custom-control-parameters.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSecurityControlDefinition](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/get-security-control-definition.html)」を参照してください。

### `invite-members`
<a name="securityhub_InviteMembers_cli_2_topic"></a>

次のコード例は、`invite-members` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントに招待を送信するには**  
次の `invite-members` の例では、指定されたメンバーアカウントに招待を送信します。  

```
aws securityhub invite-members \
    --account-ids "123456789111" "123456789222"
```
出力:  

```
{
    "UnprocessedAccounts": []
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InviteMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/invite-members.html)」を参照してください。

### `list-automation-rules`
<a name="securityhub_ListAutomationRules_cli_2_topic"></a>

次のコード例は、`list-automation-rules` を使用する方法を示しています。

**AWS CLI**  
**自動化ルールのリストを表示するには**  
次の の`list-automation-rules`例では、 AWS アカウントの自動化ルールを一覧表示します。Security Hub 管理者アカウントのみ、このコマンドを実行できます。  

```
aws securityhub list-automation-rules \
    --max-results 3 \
    --next-token NULL
```
出力:  

```
{
    "AutomationRulesMetadata": [
        {
            "RuleArn": "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "RuleStatus": "ENABLED",
            "RuleOrder": 1,
            "RuleName": "Suppress informational findings",
            "Description": "Suppress GuardDuty findings with Informational severity",
            "IsTerminal": false,
            "CreatedAt": "2023-05-31T17:56:14.837000+00:00",
            "UpdatedAt": "2023-05-31T17:59:38.466000+00:00",
            "CreatedBy": "arn:aws:iam::123456789012:role/Admin"
        },
        {
            "RuleArn": "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "RuleStatus": "ENABLED",
            "RuleOrder": 1,
            "RuleName": "sample rule",
            "Description": "A sample rule",
            "IsTerminal": false,
            "CreatedAt": "2023-07-15T23:37:20.223000+00:00",
            "UpdatedAt": "2023-07-15T23:37:20.223000+00:00",
            "CreatedBy": "arn:aws:iam::123456789012:role/Admin"
        },
        {
            "RuleArn": "arn:aws:securityhub:us-east-1:123456789012:automation-rule/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "RuleStatus": "ENABLED",
            "RuleOrder": 1,
            "RuleName": "sample rule",
            "Description": "A sample rule",
            "IsTerminal": false,
            "CreatedAt": "2023-07-15T23:45:25.126000+00:00",
            "UpdatedAt": "2023-07-15T23:45:25.126000+00:00",
            "CreatedBy": "arn:aws:iam::123456789012:role/Admin"
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[自動化ルールを表示する](https://docs.aws.amazon.com/securityhub/latest/userguide/automation-rules.html#view-automation-rules)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListAutomationRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-automation-rules.html)」を参照してください。

### `list-configuration-policies`
<a name="securityhub_ListConfigurationPolicies_cli_2_topic"></a>

次のコード例は、`list-configuration-policies` を使用する方法を示しています。

**AWS CLI**  
**設定ポリシーの概要を一覧表示するには**  
次の `list-configuration-policies` の例は、組織の設定ポリシーの概要を示します。  

```
aws securityhub list-configuration-policies \
    --max-items 3
```
出力:  

```
{
    "ConfigurationPolicySummaries": [
        {
            "Arn": "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Name": "SampleConfigurationPolicy1",
            "Description": "SampleDescription1",
            "UpdatedAt": "2023-09-26T21:08:36.214000+00:00",
            "ServiceEnabled": true
        },
        {
            "Arn": "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "Name": "SampleConfigurationPolicy2",
            "Description": "SampleDescription2"
            "UpdatedAt": "2023-11-28T19:26:25.207000+00:00",
            "ServiceEnabled": true
        },
        {
            "Arn": "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "Name": "SampleConfigurationPolicy3",
            "Description": "SampleDescription3",
            "UpdatedAt": "2023-11-28T20:28:04.494000+00:00",
            "ServiceEnabled": true
        }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの表示](https://docs.aws.amazon.com/securityhub/latest/userguide/view-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConfigurationPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-configuration-policies.html)」を参照してください。

### `list-configuration-policy-associations`
<a name="securityhub_ListConfigurationPolicyAssociations_cli_2_topic"></a>

次のコード例は、`list-configuration-policy-associations` を使用する方法を示しています。

**AWS CLI**  
**設定の関連付けを一覧表示するには**  
次の `list-configuration-policy-associations` の例では、組織の設定関連付けの概要を一覧表示します。レスポンスには、設定ポリシーとセルフマネージド動作との関連付けが含まれます。  

```
aws securityhub list-configuration-policy-associations \
    --filters '{"AssociationType": "APPLIED"}' \
    --max-items 4
```
出力:  

```
{
    "ConfigurationPolicyAssociationSummaries": [
        {
            "ConfigurationPolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "TargetId": "r-1ab2",
            "TargetType": "ROOT",
            "AssociationType": "APPLIED",
            "UpdatedAt": "2023-11-28T19:26:49.417000+00:00",
            "AssociationStatus": "FAILED",
            "AssociationStatusMessage": "Policy association failed because 2 organizational units or accounts under this root failed."
        },
        {
            "ConfigurationPolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "TargetId": "ou-1ab2-c3de4f5g",
            "TargetType": "ORGANIZATIONAL_UNIT",
            "AssociationType": "APPLIED",
            "UpdatedAt": "2023-09-26T21:14:05.283000+00:00",
            "AssociationStatus": "FAILED",
            "AssociationStatusMessage": "One or more children under this target failed association."
        },
        {
            "ConfigurationPolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
            "TargetId": "ou-6hi7-8j91kl2m",
            "TargetType": "ORGANIZATIONAL_UNIT",
            "AssociationType": "APPLIED",
            "UpdatedAt": "2023-09-26T21:13:01.816000+00:00",
            "AssociationStatus": "SUCCESS",
            "AssociationStatusMessage": "Association applied successfully on this target."
        },
        {
            "ConfigurationPolicyId": "SELF_MANAGED_SECURITY_HUB",
            "TargetId": "111122223333",
            "TargetType": "ACCOUNT",
            "AssociationType": "APPLIED",
            "UpdatedAt": "2023-11-28T22:01:26.409000+00:00",
            "AssociationStatus": "SUCCESS"
    }
}
```
詳細については、*AWS Security Hub ユーザーガイド*の「[設定ポリシーのステータスと詳細の表示](https://docs.aws.amazon.com/securityhub/latest/userguide/view-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListConfigurationPolicyAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-configuration-policy-associations.html)」を参照してください。

### `list-enabled-products-for-import`
<a name="securityhub_ListEnabledProductsForImport_cli_2_topic"></a>

次のコード例は、`list-enabled-products-for-import` を使用する方法を示しています。

**AWS CLI**  
**有効な製品統合のリストを返すには**  
次の `list-enabled-products-for-import` の例では、現在有効な製品統合のサブスクリプション ARNS のリストを返します。  

```
aws securityhub list-enabled-products-for-import
```
出力:  

```
{
    "ProductSubscriptions": [ "arn:aws:securityhub:us-west-1:123456789012:product-subscription/crowdstrike/crowdstrike-falcon", "arn:aws:securityhub:us-west-1:123456789012:product-subscription/aws/securityhub" ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[製品統合の管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-integrations-managing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEnabledProductsForImport](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-enabled-products-for-import.html)」を参照してください。

### `list-finding-aggregators`
<a name="securityhub_ListFindingAggregators_cli_2_topic"></a>

次のコード例は、`list-finding-aggregators` を使用する方法を示しています。

**AWS CLI**  
**使用可能なウィジェットを一覧表示するには**  
次の `list-finding-aggregators` の例では、検出結果集約設定の ARN を返します。  

```
aws securityhub list-finding-aggregators
```
出力:  

```
{
    "FindingAggregatorArn": "arn:aws:securityhub:us-east-1:222222222222:finding-aggregator/123e4567-e89b-12d3-a456-426652340000"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[現在の検出結果の集約設定を表示する](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-aggregation-view-config.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFindingAggregators](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-finding-aggregators.html)」を参照してください。

### `list-invitations`
<a name="securityhub_ListInvitations_cli_2_topic"></a>

次のコード例は、`list-invitations` を使用する方法を示しています。

**AWS CLI**  
**招待のリストを表示するには**  
次の `list-invitations` の例では、リクエスト元のアカウントに送信された招待のリストを取得します。  

```
aws securityhub list-invitations
```
出力:  

```
{
    "Invitations": [
        {
            "AccountId": "123456789012",
            "InvitationId": "7ab938c5d52d7904ad09f9e7c20cc4eb",
            "InvitedAt": 2020-06-01T20:21:18.042000+00:00,
            "MemberStatus": "ASSOCIATED"
        }
    ],
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInvitations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-invitations.html)」を参照してください。

### `list-members`
<a name="securityhub_ListMembers_cli_2_topic"></a>

次のコード例は、`list-members` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントのリストを取得するには**  
次の `list-members` の例では、リクエスト元の管理者アカウントのメンバーアカウントのリストを返します。  

```
aws securityhub list-members
```
出力:  

```
{
    "Members": [
        {
            "AccountId": "123456789111",
            "AdministratorId": "123456789012",
            "InvitedAt": 2020-06-01T20:15:15.289000+00:00,
            "MasterId": "123456789012",
            "MemberStatus": "ASSOCIATED",
            "UpdatedAt": 2020-06-01T20:15:15.289000+00:00
        },
        {
            "AccountId": "123456789222",
            "AdministratorId": "123456789012",
            "InvitedAt": 2020-06-01T20:15:15.289000+00:00,
            "MasterId": "123456789012",
            "MemberStatus": "ASSOCIATED",
            "UpdatedAt": 2020-06-01T20:15:15.289000+00:00
        }
    ],
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[管理者アカウントおよびメンバーアカウントの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-members.html)」を参照してください。

### `list-organization-admin-accounts`
<a name="securityhub_ListOrganizationAdminAccounts_cli_2_topic"></a>

次のコード例は、`list-organization-admin-accounts` を使用する方法を示しています。

**AWS CLI**  
**指定された Security Hub 管理者アカウントを一覧表示するには**  
次の `list-organization-admin-accounts` の例では、組織の Security Hub 管理者アカウントを一覧表示します。  

```
aws securityhub list-organization-admin-accounts
```
出力:  

```
{
    AdminAccounts": [
        { "AccountId": "777788889999" },
        { "Status": "ENABLED" }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 管理者アカウントの指定](https://docs.aws.amazon.com/securityhub/latest/userguide/designate-orgs-admin-account.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOrganizationAdminAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-organization-admin-accounts.html)」を参照してください。

### `list-security-control-definitions`
<a name="securityhub_ListSecurityControlDefinitions_cli_2_topic"></a>

次のコード例は、`list-security-control-definitions` を使用する方法を示しています。

**AWS CLI**  
**例 1: 使用可能なすべてのセキュリティコントロールを一覧表示するには**  
次の `list-security-control-definitions` の例では、すべての Security Hub 標準で使用可能なセキュリティコントロールを一覧表示します。この例では、結果を 3 つのコントロールに制限します。  

```
aws securityhub list-security-control-definitions \
    --max-items 3
```
出力:  

```
{
    "SecurityControlDefinitions": [
        {
            "SecurityControlId": "ACM.1",
            "Title": "Imported and ACM-issued certificates should be renewed after a specified time period",
            "Description": "This control checks whether an AWS Certificate Manager (ACM) certificate is renewed within the specified time period. It checks both imported certificates and certificates provided by ACM. The control fails if the certificate isn't renewed within the specified time period. Unless you provide a custom parameter value for the renewal period, Security Hub uses a default value of 30 days.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/ACM.1/remediation",
            "SeverityRating": "MEDIUM",
            "CurrentRegionAvailability": "AVAILABLE",
            "CustomizableProperties": [
                "Parameters"
            ]
        },
        {
            "SecurityControlId": "ACM.2",
            "Title": "RSA certificates managed by ACM should use a key length of at least 2,048 bits",
            "Description": "This control checks whether RSA certificates managed by AWS Certificate Manager use a key length of at least 2,048 bits. The control fails if the key length is smaller than 2,048 bits.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/ACM.2/remediation",
            "SeverityRating": "HIGH",
            "CurrentRegionAvailability": "AVAILABLE",
            "CustomizableProperties": []
        },
        {
            "SecurityControlId": "APIGateway.1",
            "Title": "API Gateway REST and WebSocket API execution logging should be enabled",
            "Description": "This control checks whether all stages of an Amazon API Gateway REST or WebSocket API have logging enabled. The control fails if the 'loggingLevel' isn't 'ERROR' or 'INFO' for all stages of the API. Unless you provide custom parameter values to indicate that a specific log type should be enabled, Security Hub produces a passed finding if the logging level is either 'ERROR' or 'INFO'.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/APIGateway.1/remediation",
            "SeverityRating": "MEDIUM",
            "CurrentRegionAvailability": "AVAILABLE",
            "CustomizableProperties": [
                "Parameters"
            ]
        }
    ],
    "NextToken": "U2FsdGVkX1/UprCPzxVbkDeHikDXbDxfgJZ1w2RG1XWsFPTMTIQPVE0m/FduIGxS7ObRtAbaUt/8/RCQcg2PU0YXI20hH/GrhoOTgv+TSm0qvQVFhkJepWmqh+NYawjocVBeos6xzn/8qnbF9IuwGg=="
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[標準の詳細の表示](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-view-controls.html)」を参照してください。  
**例 2: 特定の標準で使用可能なセキュリティコントロールを一覧表示するには**  
次の の`list-security-control-definitions`例では、CIS AWS Foundations Benchmark v1.4.0 で使用可能なセキュリティコントロールを一覧表示します。この例では、結果を 3 つのコントロールに制限します。  

```
aws securityhub list-security-control-definitions \
    --standards-arn "arn:aws:securityhub:us-east-1::standards/cis-aws-foundations-benchmark/v/1.4.0" \
    --max-items 3
```
出力:  

```
{
    "SecurityControlDefinitions": [
        {
            "SecurityControlId": "CloudTrail.1",
            "Title": "CloudTrail should be enabled and configured with at least one multi-Region trail that includes read and write management events",
            "Description": "This AWS control checks that there is at least one multi-region AWS CloudTrail trail includes read and write management events.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/CloudTrail.1/remediation",
            "SeverityRating": "HIGH",
            "CurrentRegionAvailability": "AVAILABLE",
            "CustomizableProperties": []
        },
        {
            "SecurityControlId": "CloudTrail.2",
            "Title": "CloudTrail should have encryption at-rest enabled",
            "Description": "This AWS control checks whether AWS CloudTrail is configured to use the server side encryption (SSE) AWS Key Management Service (AWS KMS) customer master key (CMK) encryption. The check will pass if the KmsKeyId is defined.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/CloudTrail.2/remediation",
            "SeverityRating": "MEDIUM",
            "CurrentRegionAvailability": "AVAILABLE",
            "CustomizableProperties": []
        },
        {
            "SecurityControlId": "CloudTrail.4",
            "Title": "CloudTrail log file validation should be enabled",
            "Description": "This AWS control checks whether CloudTrail log file validation is enabled.",
            "RemediationUrl": "https://docs.aws.amazon.com/console/securityhub/CloudTrail.4/remediation",
            "SeverityRating": "MEDIUM",
            "CurrentRegionAvailability": "AVAILABLE",
            "CustomizableProperties": []
        }
    ],
    "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAzfQ=="
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[標準の詳細の表示](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-view-controls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSecurityControlDefinitions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-security-control-definitions.html)」を参照してください。

### `list-standards-control-associations`
<a name="securityhub_ListStandardsControlAssociations_cli_2_topic"></a>

次のコード例は、`list-standards-control-associations` を使用する方法を示しています。

**AWS CLI**  
**有効な各標準でコントロールの有効化ステータスを取得するには**  
次の `list-standards-control-associations` の例では、有効な各標準における CloudTrail.1 の有効化ステータスを一覧表示します。  

```
aws securityhub list-standards-control-associations \
    --security-control-id CloudTrail.1
```
出力:  

```
{
    "StandardsControlAssociationSummaries": [
        {
            "StandardsArn": "arn:aws:securityhub:us-east-2::standards/nist-800-53/v/5.0.0",
            "SecurityControlId": "CloudTrail.1",
            "SecurityControlArn": "arn:aws:securityhub:us-east-2:123456789012:security-control/CloudTrail.1",
            "AssociationStatus": "ENABLED",
            "RelatedRequirements": [
                "NIST.800-53.r5 AC-2(4)",
                "NIST.800-53.r5 AC-4(26)",
                "NIST.800-53.r5 AC-6(9)",
                "NIST.800-53.r5 AU-10",
                "NIST.800-53.r5 AU-12",
                "NIST.800-53.r5 AU-2",
                "NIST.800-53.r5 AU-3",
                "NIST.800-53.r5 AU-6(3)",
                "NIST.800-53.r5 AU-6(4)",
                "NIST.800-53.r5 AU-14(1)",
                "NIST.800-53.r5 CA-7",
                "NIST.800-53.r5 SC-7(9)",
                "NIST.800-53.r5 SI-3(8)",
                "NIST.800-53.r5 SI-4(20)",
                "NIST.800-53.r5 SI-7(8)",
                "NIST.800-53.r5 SA-8(22)"
            ],
            "UpdatedAt": "2023-05-15T17:52:21.304000+00:00",
            "StandardsControlTitle": "CloudTrail should be enabled and configured with at least one multi-Region trail that includes read and write management events",
            "StandardsControlDescription": "This AWS control checks that there is at least one multi-region AWS CloudTrail trail includes read and write management events."
        },
        {
            "StandardsArn": "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0",
            "SecurityControlId": "CloudTrail.1",
            "SecurityControlArn": "arn:aws:securityhub:us-east-2:123456789012:security-control/CloudTrail.1",
            "AssociationStatus": "ENABLED",
            "RelatedRequirements": [
                "CIS AWS Foundations 2.1"
            ],
            "UpdatedAt": "2020-02-10T21:22:53.998000+00:00",
            "StandardsControlTitle": "Ensure CloudTrail is enabled in all regions",
            "StandardsControlDescription": "AWS CloudTrail is a web service that records AWS API calls for your account and delivers log files to you. The recorded information includes the identity of the API caller, the time of the API call, the source IP address of the API caller, the request parameters, and the response elements returned by the AWS service."
        },
        {
            "StandardsArn": "arn:aws:securityhub:us-east-2::standards/aws-foundational-security-best-practices/v/1.0.0",
            "SecurityControlId": "CloudTrail.1",
            "SecurityControlArn": "arn:aws:securityhub:us-east-2:123456789012:security-control/CloudTrail.1",
            "AssociationStatus": "DISABLED",
            "RelatedRequirements": [],
            "UpdatedAt": "2023-05-15T19:31:52.671000+00:00",
            "UpdatedReason": "Alternative compensating controls are in place",
            "StandardsControlTitle": "CloudTrail should be enabled and configured with at least one multi-Region trail that includes read and write management events",
            "StandardsControlDescription": "This AWS control checks that there is at least one multi-region AWS CloudTrail trail includes read and write management events."
        },
        {
            "StandardsArn": "arn:aws:securityhub:us-east-2::standards/cis-aws-foundations-benchmark/v/1.4.0",
            "SecurityControlId": "CloudTrail.1",
            "SecurityControlArn": "arn:aws:securityhub:us-east-2:123456789012:security-control/CloudTrail.1",
            "AssociationStatus": "ENABLED",
            "RelatedRequirements": [
                "CIS AWS Foundations Benchmark v1.4.0/3.1"
            ],
            "UpdatedAt": "2022-11-10T15:40:36.021000+00:00",
            "StandardsControlTitle": "Ensure CloudTrail is enabled in all regions",
            "StandardsControlDescription": "AWS CloudTrail is a web service that records AWS API calls for your account and delivers log files to you. The recorded information includes the identity of the API caller, the time of the API call, the source IP address of the API caller, the request parameters, and the response elements returned by the AWS service. CloudTrail provides a history of AWS API calls for an account, including API calls made via the Management Console, SDKs, command line tools, and higher-level AWS services (such as CloudFormation)."
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[特定の標準におけるコントロールの有効化と無効化](https://docs.aws.amazon.com/securityhub/latest/userguide/controls-configure.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListStandardsControlAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-standards-control-associations.html)」を参照してください。

### `list-tags-for-resource`
<a name="securityhub_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに割り当てられたタグを取得するには**  
次の `list-tags-for-resource` の例では、指定されたハブリソースに割り当てられたタグを返します。  

```
aws securityhub list-tags-for-resource \
    --resource-arn "arn:aws:securityhub:us-west-1:123456789012:hub/default"
```
出力:  

```
{
    "Tags": {
        "Department" : "Operations",
        "Area" : "USMidwest"
    }
}
```
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[AWS::SecurityHub::Hub](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-hub.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/list-tags-for-resource.html)」を参照してください。

### `start-configuration-policy-association`
<a name="securityhub_StartConfigurationPolicyAssociation_cli_2_topic"></a>

次のコード例は、`start-configuration-policy-association` を使用する方法を示しています。

**AWS CLI**  
**例 1: 設定ポリシーを関連付けるには**  
次の `start-configuration-policy-association` の例では、指定された設定ポリシーを指定された組織単位に関連付けます。設定は、ターゲットアカウント、組織単位、またはルートに関連付けることができます。  

```
aws securityhub start-configuration-policy-association \
    --configuration-policy-identifier "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333" \
    --target '{"OrganizationalUnitId": "ou-6hi7-8j91kl2m"}'
```
出力:  

```
{
    "ConfigurationPolicyId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE33333",
    "TargetId": "ou-6hi7-8j91kl2m",
    "TargetType": "ORGANIZATIONAL_UNIT",
    "AssociationType": "APPLIED",
    "UpdatedAt": "2023-11-29T17:40:52.468000+00:00",
    "AssociationStatus": "PENDING"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの作成と関連付け](https://docs.aws.amazon.com/securityhub/latest/userguide/create-associate-policy.html)」を参照してください。  
**例 2: セルフマネージド設定を関連付けるには**  
次の `start-configuration-policy-association` の例では、セルフマネージド設定を指定されたアカウントと関連付けます。  

```
aws securityhub start-configuration-policy-association \
    --configuration-policy-identifier "SELF_MANAGED_SECURITY_HUB" \
    --target '{"OrganizationalUnitId": "123456789012"}'
```
出力:  

```
{
    "ConfigurationPolicyId": "SELF_MANAGED_SECURITY_HUB",
    "TargetId": "123456789012",
    "TargetType": "ACCOUNT",
    "AssociationType": "APPLIED",
    "UpdatedAt": "2023-11-29T17:40:52.468000+00:00",
    "AssociationStatus": "PENDING"
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの作成と関連付け](https://docs.aws.amazon.com/securityhub/latest/userguide/create-associate-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartConfigurationPolicyAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/start-configuration-policy-association.html)」を参照してください。

### `start-configuration-policy-disassociation`
<a name="securityhub_StartConfigurationPolicyDisassociation_cli_2_topic"></a>

次のコード例は、`start-configuration-policy-disassociation` を使用する方法を示しています。

**AWS CLI**  
**例 1: 設定ポリシーの関連付けを解除するには**  
次の `start-configuration-policy-disassociation` の例では、指定された組織単位から設定ポリシーの関連付けを解除します。設定は、ターゲットアカウント、組織単位、またはルートからの関連付けを解除できます。  

```
aws securityhub start-configuration-policy-disassociation \
    --configuration-policy-identifier "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE33333" \
    --target '{"OrganizationalUnitId": "ou-6hi7-8j91kl2m"}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[アカウントと OU からの設定の関連付けの解除](https://docs.aws.amazon.com/securityhub/latest/userguide/delete-disassociate-policy.html#disassociate-policy)」を参照してください。  
**例 2: セルフマネージド設定の関連付けを解除するには**  
次の `start-configuration-policy-disassociation` の例では、指定されたアカウントからセルフマネージド設定の関連付けを解除します。  

```
aws securityhub start-configuration-policy-disassociation \
    --configuration-policy-identifier "SELF_MANAGED_SECURITY_HUB" \
    --target '{"AccountId": "123456789012"}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[アカウントと OU からの設定の関連付けの解除](https://docs.aws.amazon.com/securityhub/latest/userguide/delete-disassociate-policy.html#disassociate-policy)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartConfigurationPolicyDisassociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/start-configuration-policy-disassociation.html)」を参照してください。

### `tag-resource`
<a name="securityhub_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを割り当てるには**  
次の `tag-resource` の例では、指定されたハブリソースに部署およびエリアタグの値を割り当てます。  

```
aws securityhub tag-resource \
    --resource-arn "arn:aws:securityhub:us-west-1:123456789012:hub/default" \
    --tags '{"Department":"Operations", "Area":"USMidwest"}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[AWS::SecurityHub::Hub](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-hub.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="securityhub_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグ値を削除するには**  
次の `untag-resource` の例では、指定されたハブリソースから部署タグを削除しています。  

```
aws securityhub untag-resource \
    --resource-arn "arn:aws:securityhub:us-west-1:123456789012:hub/default" \
    --tag-keys "Department"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS CloudFormation ユーザーガイド*」の「[AWS::SecurityHub::Hub](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-securityhub-hub.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/untag-resource.html)」を参照してください。

### `update-action-target`
<a name="securityhub_UpdateActionTarget_cli_2_topic"></a>

次のコード例は、`update-action-target` を使用する方法を示しています。

**AWS CLI**  
**カスタムアクションを更新するには**  
次の `update-action-target` の例では、指定された ARN によって識別されるカスタムアクションの名前を更新します。  

```
aws securityhub update-action-target \
    --action-target-arn "arn:aws:securityhub:us-west-1:123456789012:action/custom/Remediation" \
    --name "Send to remediation"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムアクションを作成し、CloudWatch Events ルールに関連付ける](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-cloudwatch-events.html#securityhub-cwe-configure)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateActionTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-action-target.html)」を参照してください。

### `update-configuration-policy`
<a name="securityhub_UpdateConfigurationPolicy_cli_2_topic"></a>

次のコード例は、`update-configuration-policy` を使用する方法を示しています。

**AWS CLI**  
**設定ポリシーを更新するには**  
次の `update-configuration-policy` の例では、既存の設定ポリシーを更新して、指定された設定を使用します。  

```
aws securityhub update-configuration-policy \
    --identifier "arn:aws:securityhub:eu-central-1:508236694226:configuration-policy/09f37766-57d8-4ede-9d33-5d8b0fecf70e" \
    --name "SampleConfigurationPolicyUpdated" \
    --description "SampleDescriptionUpdated" \
    --configuration-policy '{"SecurityHub": {"ServiceEnabled": true, "EnabledStandardIdentifiers": ["arn:aws:securityhub:eu-central-1::standards/aws-foundational-security-best-practices/v/1.0.0","arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0"],"SecurityControlsConfiguration":{"DisabledSecurityControlIdentifiers": ["CloudWatch.1"], "SecurityControlCustomParameters": [{"SecurityControlId": "ACM.1", "Parameters": {"daysToExpiration": {"ValueType": "CUSTOM", "Value": {"Integer": 21}}}}]}}}' \
    --updated-reason "Disabling CloudWatch.1 and changing parameter value"
```
出力:  

```
{
    "Arn": "arn:aws:securityhub:eu-central-1:123456789012:configuration-policy/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
    "Name": "SampleConfigurationPolicyUpdated",
    "Description": "SampleDescriptionUpdated",
    "UpdatedAt": "2023-11-28T20:28:04.494000+00:00",
    "CreatedAt": "2023-11-28T20:28:04.494000+00:00",
    "ConfigurationPolicy": {
        "SecurityHub": {
            "ServiceEnabled": true,
            "EnabledStandardIdentifiers": [
                "arn:aws:securityhub:eu-central-1::standards/aws-foundational-security-best-practices/v/1.0.0",
                "arn:aws:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0"
            ],
            "SecurityControlsConfiguration": {
                "DisabledSecurityControlIdentifiers": [
                    "CloudWatch.1"
                ],
                "SecurityControlCustomParameters": [
                    {
                        "SecurityControlId": "ACM.1",
                        "Parameters": {
                            "daysToExpiration": {
                                "ValueType": "CUSTOM",
                                "Value": {
                                    "Integer": 21
                                }
                            }
                        }
                    }
                ]
            }
        }
    }
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[Security Hub 設定ポリシーの更新](https://docs.aws.amazon.com/securityhub/latest/userguide/update-policy.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateConfigurationPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-configuration-policy.html)」を参照してください。

### `update-finding-aggregator`
<a name="securityhub_UpdateFindingAggregator_cli_2_topic"></a>

次のコード例は、`update-finding-aggregator` を使用する方法を示しています。

**AWS CLI**  
**現在の検索結果の集約設定を更新するには**  
次の `update-finding-aggregator` の例では、選択したリージョンからリンクするように検出結果集約設定を変更します。コマンドは、集約リージョンである米国東部 (バージニア) から実行されます。リンクされたリージョンとして、米国西部 (北カリフォルニア) と米国西部 (オレゴン) が選択されます。  

```
aws securityhub update-finding-aggregator \
    --region us-east-1 \
    --finding-aggregator-arn arn:aws:securityhub:us-east-1:222222222222:finding-aggregator/123e4567-e89b-12d3-a456-426652340000 \
    --region-linking-mode SPECIFIED_REGIONS \
    --regions us-west-1,us-west-2
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[検出結果の集約設定を更新する](https://docs.aws.amazon.com/securityhub/latest/userguide/finding-aggregation-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFindingAggregator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-finding-aggregator.html)」を参照してください。

### `update-insight`
<a name="securityhub_UpdateInsight_cli_2_topic"></a>

次のコード例は、`update-insight` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムインサイトのフィルターを変更するには**  
次の `update-insight` の例では、カスタムインサイトのフィルターを変更します。更新されたインサイトは、 AWS ロールに関連する重要度の高い結果を検索します。  

```
aws securityhub update-insight \
    --insight-arn "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" \
    --filters '{"ResourceType": [{ "Comparison": "EQUALS", "Value": "AwsIamRole"}], "SeverityLabel": [{"Comparison": "EQUALS", "Value": "HIGH"}]}' \
    --name "High severity role findings"
```
**例 2: カスタムインサイトのグループ化属性を変更するには**  
次の `update-insight` の例では、指定された ARN を使用してカスタムインサイトのグループ化属性を変更します。新しいグループ化属性はリソース ID です。  

```
aws securityhub update-insight \
    --insight-arn "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111" \
    --group-by-attribute "ResourceId" \
    --name "Critical role findings"
```
出力:  

```
{
    "Insights": [
        {
            "InsightArn": "arn:aws:securityhub:us-west-1:123456789012:insight/123456789012/custom/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Name": "Critical role findings",
            "Filters": {
                "SeverityLabel": [
                    {
                        "Value": "CRITICAL",
                        "Comparison": "EQUALS"
                    }
                ],
                "ResourceType": [
                    {
                        "Value": "AwsIamRole",
                        "Comparison": "EQUALS"
                    }
                ]
            },
            "GroupByAttribute": "ResourceId"
        }
    ]
}
```
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムインサイトの管理](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-custom-insights.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateInsight](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-insight.html)」を参照してください。

### `update-organization-configuration`
<a name="securityhub_UpdateOrganizationConfiguration_cli_2_topic"></a>

次のコード例は、`update-organization-configuration` を使用する方法を示しています。

**AWS CLI**  
**組織の Security Hub の設定方法を更新するには**  
次の `update-organization-configuration` の例では、Security Hub が中央設定を使用して組織を設定するように指定します。このコマンドを実行した後は、委任された Security Hub 管理者は、組織を設定するための設定ポリシーを作成して管理できます。委任された管理者は、このコマンドを使用して中央設定からローカル設定に切り替えることもできます。ローカル設定が設定タイプである場合、委任された管理者が、新しい組織アカウントで Security Hub とデフォルトのセキュリティ標準を自動的に有効にするかどうかを選択できます。  

```
aws securityhub update-organization-configuration \
    --no-auto-enable \
    --organization-configuration '{"ConfigurationType": "CENTRAL"}'
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「Security Hub ユーザーガイド*」の[AWS 「Organizations でアカウントを管理する](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-accounts-orgs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateOrganizationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-organization-configuration.html)」を参照してください。

### `update-security-control`
<a name="securityhub_UpdateSecurityControl_cli_2_topic"></a>

次のコード例は、`update-security-control` を使用する方法を示しています。

**AWS CLI**  
**セキュリティコントロールのプロパティを更新するには**  
次の `update-security-control` の例では、Security Hub セキュリティコントロールパラメータのカスタム値を指定します。  

```
aws securityhub update-security-control \
    --security-control-id ACM.1 \
    --parameters '{"daysToExpiration": {"ValueType": "CUSTOM", "Value": {"Integer": 15}}}' \
    --last-update-reason "Internal compliance requirement"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[カスタムコントロールパラメータ](https://docs.aws.amazon.com/securityhub/latest/userguide/custom-control-parameters.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSecurityControl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-security-control.html)」を参照してください。

### `update-security-hub-configuration`
<a name="securityhub_UpdateSecurityHubConfiguration_cli_2_topic"></a>

次のコード例は、`update-security-hub-configuration` を使用する方法を示しています。

**AWS CLI**  
**Security Hub 設定を更新するには**  
次の `update-security-hub-configuration` 例では、Security Hub を設定して、有効な標準で新しいコントロールを自動的に有効にします。  

```
aws securityhub update-security-hub-configuration \
    --auto-enable-controls
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[新しいコントロールを自動的に有効化する](https://docs.aws.amazon.com/securityhub/latest/userguide/controls-auto-enable.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSecurityHubConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-security-hub-configuration.html)」を参照してください。

### `update-standards-control`
<a name="securityhub_UpdateStandardsControl_cli_2_topic"></a>

次のコード例は、`update-standards-control` を使用する方法を示しています。

**AWS CLI**  
**例 1: コントロールを無効にするには**  
次の `update-standards-control` の例では、PCI.AutoScaling.1 コントロールを無効にします。  

```
aws securityhub update-standards-control \
    --standards-control-arn "arn:aws:securityhub:us-west-1:123456789012:control/pci-dss/v/3.2.1/PCI.AutoScaling.1" \
    --control-status "DISABLED" \
    --disabled-reason "Not applicable for my service"
```
このコマンドでは何も出力されません。  
**例 2: コントロールを有効にするには**  
次の `update-standards-control` の例では、PCI.AutoScaling.1 コントロールを有効にします。  

```
aws securityhub update-standards-control \
    --standards-control-arn "arn:aws:securityhub:us-west-1:123456789012:control/pci-dss/v/3.2.1/PCI.AutoScaling.1" \
    --control-status "ENABLED"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Security Hub ユーザーガイド*」の「[個々のコントロールの無効化と有効化化](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-standards-enable-disable-controls.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateStandardsControl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securityhub/update-standards-control.html)」を参照してください。

# を使用した Security Lake の例 AWS CLI
<a name="cli_2_securitylake_code_examples"></a>

次のコード例は、Security Lake AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-aws-log-source`
<a name="securitylake_CreateAwsLogSource_cli_2_topic"></a>

次のコード例は、`create-aws-log-source` を使用する方法を示しています。

**AWS CLI**  
**ネイティブにサポートされている Amazon Web Service を Amazon Security Lake ソースとして追加するには**  
次の `create-aws-logsource` の例では、指定されたアカウントとリージョンに Security Lake ソースとして VPC フローログを追加します。  

```
aws securitylake create-aws-log-source \
    --sources '[{"regions": ["us-east-1"], "accounts": ["123456789012"], "sourceName": "SH_FINDINGS", "sourceVersion": "2.0"}]'
```
出力:  

```
{
    "failed": [
        "123456789012"
    ]
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*[」の「ソースとしての AWS サービスの追加](https://docs.aws.amazon.com/security-lake/latest/userguide/internal-sources.html#add-internal-sources)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateAwsLogSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/create-aws-log-source.html)」を参照してください。

### `create-custom-log-source`
<a name="securitylake_CreateCustomLogSource_cli_2_topic"></a>

次のコード例は、`create-custom-log-source` を使用する方法を示しています。

**AWS CLI**  
**Amazon Security Lake ソースとしてカスタムソースを追加するには**  
次の `create-custom-logsource` の例では、指定されたログプロバイダーアカウントと指定されたリージョンに、Security Lake ソースとしてカスタムソースを追加します。  

```
aws securitylake create-custom-log-source \
    --source-name "VPC_FLOW" \
    --event-classes '["DNS_ACTIVITY", "NETWORK_ACTIVITY"]' \
    --configuration '{"crawlerConfiguration": {"roleArn": "arn:aws:glue:eu-west-2:123456789012:crawler/E1WG1ZNPRXT0D4"},"providerIdentity": {"principal": "029189416600","externalId": "123456789012"}}' --region "us-east-1"
```
出力:  

```
{
    "customLogSource": {
        "attributes": {
            "crawlerArn": "arn:aws:glue:eu-west-2:123456789012:crawler/E1WG1ZNPRXT0D4",
            "databaseArn": "arn:aws:glue:eu-west-2:123456789012:database/E1WG1ZNPRXT0D4",
            "tableArn": "arn:aws:glue:eu-west-2:123456789012:table/E1WG1ZNPRXT0D4"
        },
        "provider": {
            "location": "amzn-s3-demo-bucket--usw2-az1--x-s3",
            "roleArn": "arn:aws:iam::123456789012:role/AmazonSecurityLake-Provider-testCustom2-eu-west-2"
        },
        "sourceName": "testCustom2"
        "sourceVersion": "2.0"
    }
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[カスタムソースの追加](https://docs.aws.amazon.com/security-lake/latest/userguide/custom-sources.html#adding-custom-sources)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[CreateCustomLogSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/create-custom-log-source.html)」を参照してください。

### `create-data-lake-exception-subscription`
<a name="securitylake_CreateDataLakeExceptionSubscription_cli_2_topic"></a>

次のコード例は、`create-data-lake-exception-subscription` を使用する方法を示しています。

**AWS CLI**  
**Security Lake の例外の通知を送信するには**  
次の `create-data-lake-exception-subscription` の例では、Security Lake の例外の通知を SMS 配信を介して指定されたアカウントに送信します。例外メッセージは、指定された期間保持されます。  

```
aws securitylake create-data-lake-exception-subscription \
    --notification-endpoint "123456789012" \
    --exception-time-to-live 30 \
    --subscription-protocol "sms"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Amazon Security Lake のトラブルシューティング](https://docs.aws.amazon.com/security-lake/latest/userguide/security-lake-troubleshoot.html#securitylake-data-lake-troubleshoot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDataLakeExceptionSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/create-data-lake-exception-subscription.html)」を参照してください。

### `create-data-lake-organization-configuration`
<a name="securitylake_CreateDataLakeOrganizationConfiguration_cli_2_topic"></a>

次のコード例は、`create-data-lake-organization-configuration` を使用する方法を示しています。

**AWS CLI**  
**新しい組織アカウントで Security Lake を設定するには**  
次の `create-data-lake-organization-configuration` の例では、Security Lake を有効にし、指定されたソースイベントとログを新しい組織アカウントで収集します。  

```
aws securitylake create-data-lake-organization-configuration \
    --auto-enable-new-account '[{"region":"us-east-1","sources":[{"sourceName":"SH_FINDINGS","sourceVersion": "1.0"}]}]'
```
このコマンドでは何も出力されません。  
詳細については、*「Amazon Security Lake ユーザーガイド*」の[AWS 「Organizations で複数のアカウントを管理する](https://docs.aws.amazon.com/security-lake/latest/userguide/multi-account-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDataLakeOrganizationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/create-data-lake-organization-configuration.html)」を参照してください。

### `create-data-lake`
<a name="securitylake_CreateDataLake_cli_2_topic"></a>

次のコード例は、`create-data-lake` を使用する方法を示しています。

**AWS CLI**  
**例 1: 複数のリージョンでデータレイクを設定するには**  
次の`create-data-lake`例では、複数の AWS リージョンで Amazon Security Lake を有効にし、データレイクを設定します。  

```
aws securitylake create-data-lake \
    --configurations '[{"encryptionConfiguration": {"kmsKeyId":"S3_MANAGED_KEY"},"region":"us-east-1","lifecycleConfiguration": {"expiration":{"days":365},"transitions":[{"days":60,"storageClass":"ONEZONE_IA"}]}}, {"encryptionConfiguration": {"kmsKeyId":"S3_MANAGED_KEY"},"region":"us-east-2","lifecycleConfiguration": {"expiration":{"days":365},"transitions":[{"days":60,"storageClass":"ONEZONE_IA"}]}}]' \
    --meta-store-manager-role-arn "arn:aws:iam:us-east-1:123456789012:role/service-role/AmazonSecurityLakeMetaStoreManager"
```
出力:  

```
{
    "dataLakes": [
        {
            "createStatus": "COMPLETED",
            "dataLakeArn": "arn:aws:securitylake:us-east-1:522481757177:data-lake/default",
            "encryptionConfiguration": {
                "kmsKeyId": "S3_MANAGED_KEY"
            },
            "lifecycleConfiguration": {
                "expiration": {
                    "days": 365
                },
                "transitions": [
                    {
                        "days": 60,
                        "storageClass": "ONEZONE_IA"
                    }
                ]
            },
            "region": "us-east-1",
            "replicationConfiguration": {
                "regions": [
                    "ap-northeast-3"
                ],
                "roleArn": "arn:aws:securitylake:ap-northeast-3:522481757177:data-lake/default"
            },
            "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-1-gnevt6s8z7bzby8oi3uiaysbr8v2ml",
            "updateStatus": {
                "exception": {},
                "requestId": "f20a6450-d24a-4f87-a6be-1d4c075a59c2",
                "status": "INITIALIZED"
            }
        },
        {
            "createStatus": "COMPLETED",
            "dataLakeArn": "arn:aws:securitylake:us-east-2:522481757177:data-lake/default",
            "encryptionConfiguration": {
                "kmsKeyId": "S3_MANAGED_KEY"
            },
            "lifecycleConfiguration": {
                "expiration": {
                    "days": 365
                },
                "transitions": [
                    {
                        "days": 60,
                        "storageClass": "ONEZONE_IA"
                    }
                ]
            },
            "region": "us-east-2",
            "replicationConfiguration": {
                "regions": [
                    "ap-northeast-3"
                ],
                "roleArn": "arn:aws:securitylake:ap-northeast-3:522481757177:data-lake/default"
            },
            "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-2-cehuifzl5rwmhm6m62h7zhvtseogr9",
            "updateStatus": {
                "exception": {},
                "requestId": "f20a6450-d24a-4f87-a6be-1d4c075a59c2",
                "status": "INITIALIZED"
            }
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Getting started with Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/getting-started.html)」を参照してください。  
**例 2: 1 つのリージョンでデータレイクを設定するには**  
次の`create-data-lake`例では、単一の AWS リージョンで Amazon Security Lake を有効にし、データレイクを設定します。  

```
aws securitylake create-data-lake \
    --configurations '[{"encryptionConfiguration": {"kmsKeyId":"1234abcd-12ab-34cd-56ef-1234567890ab"},"region":"us-east-2","lifecycleConfiguration": {"expiration":{"days":500},"transitions":[{"days":30,"storageClass":"GLACIER"}]}}]' \
    --meta-store-manager-role-arn "arn:aws:iam:us-east-1:123456789012:role/service-role/AmazonSecurityLakeMetaStoreManager"
```
出力:  

```
{
    "dataLakes": [
        {
            "createStatus": "COMPLETED",
            "dataLakeArn": "arn:aws:securitylake:us-east-2:522481757177:data-lake/default",
            "encryptionConfiguration": {
                "kmsKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab"
            },
            "lifecycleConfiguration": {
                "expiration": {
                    "days": 500
                },
                "transitions": [
                    {
                        "days": 30,
                        "storageClass": "GLACIER"
                    }
                ]
            },
            "region": "us-east-2",
            "replicationConfiguration": {
                "regions": [
                    "ap-northeast-3"
                ],
                "roleArn": "arn:aws:securitylake:ap-northeast-3:522481757177:data-lake/default"
            },
            "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-2-cehuifzl5rwmhm6m62h7zhvtseogr9",
            "updateStatus": {
                "exception": {},
                "requestId": "77702a53-dcbf-493e-b8ef-518e362f3003",
                "status": "INITIALIZED"
            }
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[ Amazon Security Lake の使用開始](https://docs.aws.amazon.com/security-lake/latest/userguide/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDataLake](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/create-data-lake.html)」を参照してください。

### `create-subscriber-notification`
<a name="securitylake_CreateSubscriberNotification_cli_2_topic"></a>

次のコード例は、`create-subscriber-notification` を使用する方法を示しています。

**AWS CLI**  
**サブスクライバー通知を作成するには**  
次の `create-subscriber-notification` の例は、サブスクライバー通知を指定して、新しいデータがデータレイクに書き込まれたときに通知を作成する方法を示します。  

```
aws securitylake create-subscriber-notification \
    --subscriber-id "12345ab8-1a34-1c34-1bd4-12345ab9012" \
    --configuration '{"httpsNotificationConfiguration": {"targetRoleArn":"arn:aws:iam::XXX:role/service-role/RoleName", "endpoint":"https://account-management.$3.$2.securitylake.aws.dev/v1/datalake"}}'
```
出力:  

```
{
    "subscriberEndpoint": [
        "https://account-management.$3.$2.securitylake.aws.dev/v1/datalake"
    ]
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[サブスクライバー管理](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubscriberNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/create-subscriber-notification.html)」を参照してください。

### `create-subscriber`
<a name="securitylake_CreateSubscriber_cli_2_topic"></a>

次のコード例は、`create-subscriber` を使用する方法を示しています。

**AWS CLI**  
**例 1: データにアクセスできるサブスクライバーを作成するには**  
次の の`create-subscriber`例では、 AWS ソースの指定されたサブスクライバー ID の現在の AWS リージョンのデータにアクセスできる、Security Lake にサブスクライバーを作成します。  

```
aws securitylake create-subscriber \
    --access-types "S3" \
    --sources '[{"awsLogSource": {"sourceName": "VPC_FLOW","sourceVersion": "2.0"}}]' \
    --subscriber-name 'opensearch-s3' \
    --subscriber-identity '{"principal": "029189416600","externalId": "123456789012"}'
```
出力:  

```
{
    "subscriber": {
        "accessTypes": [
            "S3"
        ],
        "createdAt": "2024-07-17T19:08:26.787000+00:00",
        "roleArn": "arn:aws:iam::773172568199:role/AmazonSecurityLake-896f218b-cfba-40be-a255-8b49a65d0407",
        "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-1-um632ufwpvxkyz0bc5hkb64atycnf3",
        "sources": [
            {
                "awsLogSource": {
                    "sourceName": "VPC_FLOW",
                    "sourceVersion": "2.0"
                }
            }
        ],
        "subscriberArn": "arn:aws:securitylake:us-east-1:773172568199:subscriber/896f218b-cfba-40be-a255-8b49a65d0407",
        "subscriberId": "896f218b-cfba-40be-a255-8b49a65d0407",
        "subscriberIdentity": {
            "externalId": "123456789012",
            "principal": "029189416600"
        },
        "subscriberName": "opensearch-s3",
        "subscriberStatus": "ACTIVE",
        "updatedAt": "2024-07-17T19:08:27.133000+00:00"
    }
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[データアクセス権を持つサブスクライバーの作成](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-data-access.html#create-subscriber-data-access)」を参照してください。  
**例 2: クエリにアクセスできるサブスクライバーを作成するには**  
次の の`create-subscriber`例では、Security Lake に、指定されたサブスクライバー ID の現在の AWS リージョンでクエリアクセスを持つサブスクライバーを作成します。  

```
aws securitylake create-subscriber \
    --access-types "LAKEFORMATION" \
    --sources '[{"awsLogSource": {"sourceName": "VPC_FLOW","sourceVersion": "2.0"}}]' \
    --subscriber-name 'opensearch-s3' \
    --subscriber-identity '{"principal": "029189416600","externalId": "123456789012"}'
```
出力:  

```
{
    "subscriber": {
        "accessTypes": [
            "LAKEFORMATION"
        ],
        "createdAt": "2024-07-18T01:05:55.853000+00:00",
        "resourceShareArn": "arn:aws:ram:us-east-1:123456789012:resource-share/8c31da49-c224-4f1e-bb12-37ab756d6d8a",
        "resourceShareName": "LakeFormation-V2-NAMENAMENA-123456789012",
        "sources": [
            {
                "awsLogSource": {
                    "sourceName": "VPC_FLOW",
                    "sourceVersion": "2.0"
                }
            }
        ],
        "subscriberArn": "arn:aws:securitylake:us-east-1:123456789012:subscriber/e762aabb-ce3d-4585-beab-63474597845d",
        "subscriberId": "e762aabb-ce3d-4585-beab-63474597845d",
        "subscriberIdentity": {
            "externalId": "123456789012",
            "principal": "029189416600"
        },
        "subscriberName": "opensearch-s3",
        "subscriberStatus": "ACTIVE",
        "updatedAt": "2024-07-18T01:05:58.393000+00:00"
    }
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[クエリアクセス権を持つサブスクライバーの作成](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-query-access.html#create-query-subscriber-procedures)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドレットリファレンス*」の「[CreateSubscriber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/create-subscriber.html)」を参照してください。

### `delete-aws-log-source`
<a name="securitylake_DeleteAwsLogSource_cli_2_topic"></a>

次の例は、`delete-aws-log-source` を使用する方法を説明しています。

**AWS CLI**  
**ネイティブにサポートされている AWS サービスを削除するには。**  
次の `delete-aws-logsource` の例では、指定されたアカウントとリージョンの Security Lake ソースとして VPC フローログを削除します。  

```
aws securitylake delete-aws-log-source \
    --sources '[{"regions": ["us-east-1"], "accounts": ["123456789012"], "sourceName": "SH_FINDINGS", "sourceVersion": "2.0"}]'
```
出力:  

```
{
    "failed": [
        "123456789012"
    ]
}
```
詳細については、*「Amazon Security Lake* [ユーザーガイド」の「ソースとしての AWS サービス](https://docs.aws.amazon.com/security-lake/latest/userguide/internal-sources.html#remove-internal-sources)の削除」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteAwsLogSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/delete-aws-log-source.html)」を参照してください。

### `delete-custom-log-source`
<a name="securitylake_DeleteCustomLogSource_cli_2_topic"></a>

次のコード例は、`delete-custom-log-source` を使用する方法を示しています。

**AWS CLI**  
**カスタムソースを削除するには。**  
次の `delete-custom-logsource` の例では、指定されたリージョンの指定されたログプロバイダーアカウントのカスタムソースを削除します。  

```
aws securitylake delete-custom-log-source \
    --source-name "CustomSourceName"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[カスタムソースの削除](https://docs.aws.amazon.com/security-lake/latest/userguide/custom-sources.html#delete-custom-source)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[DeleteCustomLogSource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/delete-custom-log-source.html)」を参照してください。

### `delete-data-lake-organization-configuration`
<a name="securitylake_DeleteDataLakeOrganizationConfiguration_cli_2_topic"></a>

次のコード例は、`delete-data-lake-organization-configuration` を使用する方法を示しています。

**AWS CLI**  
**メンバーアカウントのソースの自動収集を停止するには**  
次の`delete-data-lake-organization-configuration`例では、組織に参加する新しいメンバーアカウントからの AWS Security Hub の検出結果の自動収集を停止します。このコマンドを実行できるのは、委任された Security Lake 管理者のみです。これにより、新しいメンバーアカウントからデータレイクにデータが自動的に提供されることがなくなります。  

```
aws securitylake delete-data-lake-organization-configuration \
    --auto-enable-new-account '[{"region":"us-east-1","sources":[{"sourceName":"SH_FINDINGS"}]}]'
```
このコマンドでは何も出力されません。  
詳細については、*「Amazon Security Lake ユーザーガイド*」の[AWS 「Organizations で複数のアカウントを管理する](https://docs.aws.amazon.com/securityhub/latest/userguide/multi-account-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDataLakeOrganizationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/delete-data-lake-organization-configuration.html)」を参照してください。

### `delete-data-lake`
<a name="securitylake_DeleteDataLake_cli_2_topic"></a>

次のコード例は、`delete-data-lake` を使用する方法を示しています。

**AWS CLI**  
**データレイクを無効にするには**  
次の の`delete-data-lake`例では、指定された AWS リージョンでデータレイクを無効にします。指定されたリージョンでは、ソースはデータレイクにデータを提供しなくなります。 AWS Organizations を利用する Security Lake デプロイの場合、組織内のアカウントの Security Lake を無効にすることができるのは、組織の委任 Security Lake 管理者のみです。  

```
aws securitylake delete-data-lake \
    --regions "ap-northeast-1" "eu-central-1"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Security Lake ユーザーガイド*の「[Disabling Amazon Security Lake](https://docs.aws.amazon.com/securityhub/latest/userguide/disable-security-lake.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDataLake](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/delete-data-lake.html)」を参照してください。

### `delete-subscriber-notification`
<a name="securitylake_DeleteSubscriberNotification_cli_2_topic"></a>

次のコード例は、`delete-subscriber-notification` を使用する方法を示しています。

**AWS CLI**  
**サブスクライバー通知を削除するには**  
次の `delete-subscriber-notification` の例は、特定の Security Lake サブスクライバーのサブスクライバー通知を削除する方法を示しています。  

```
aws securitylake delete-subscriber-notification \
    --subscriber-id "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
```
このコマンドでは何も出力されません。  
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[サブスクライバー管理](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubscriberNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/delete-subscriber-notification.html)」を参照してください。

### `delete-subscriber`
<a name="securitylake_DeleteSubscriber_cli_2_topic"></a>

次のコード例は、`delete-subscriber` を使用する方法を示しています。

**AWS CLI**  
**サブスクライバーを削除するには**  
次の `delete-subscriber` の例は、Security Lake からのデータをサブスクライバーに使用させたくない場合に、サブスクライバーを削除する方法を示します。  

```
aws securitylake delete-subscriber \
    --subscriber-id "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
```
このコマンドでは何も出力されません。  
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[サブスクライバー管理](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSubscriber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/delete-subscriber.html)」を参照してください。

### `get-data-lake-exception-subscription`
<a name="securitylake_GetDataLakeExceptionSubscription_cli_2_topic"></a>

次のコード例は、`get-data-lake-exception-subscription` を使用する方法を示しています。

**AWS CLI**  
**例外サブスクリプションの詳細を取得するには**  
次の `get-data-lake-exception-subscription` の例は、Security Lake 例外サブスクリプションの詳細情報を示しています。この例では、指定された AWS アカウントのユーザーに SMS 配信を通じてエラーが通知されます。例外メッセージは、指定された期間、アカウント内に残ります。例外サブスクリプションは、リクエスタの優先プロトコルを通じて、Security Lake ユーザーにエラーを通知します。  

```
aws securitylake get-data-lake-exception-subscription
```
出力:  

```
{
    "exceptionTimeToLive": 30,
    "notificationEndpoint": "123456789012",
    "subscriptionProtocol": "sms"
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[Troubleshooting data lake status](https://docs.aws.amazon.com/securityhub/latest/userguide/security-lake-troubleshoot.html#securitylake-data-lake-troubleshoot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDataLakeExceptionSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/get-data-lake-exception-subscription.html)」を参照してください。

### `get-data-lake-organization-configuration`
<a name="securitylake_GetDataLakeOrganizationConfiguration_cli_2_topic"></a>

次のコード例は、`get-data-lake-organization-configuration` を使用する方法を示しています。

**AWS CLI**  
**新しい組織アカウントの設定の詳細を取得するには**  
次の `get-data-lake-organization-configuration` の例では、Amazon Security Lake へのオンボーディング後に新しい組織アカウントが送信するソースログの詳細情報を取得します。  

```
aws securitylake get-data-lake-organization-configuration
```
出力:  

```
{
    "autoEnableNewAccount": [
        {
            "region": "us-east-1",
            "sources": [
                {
                    "sourceName": "VPC_FLOW",
                    "sourceVersion": "1.0"
                },
                {
                    "sourceName": "ROUTE53",
                    "sourceVersion": "1.0"
                },
                {
                    "sourceName": "SH_FINDINGS",
                    "sourceVersion": "1.0"
                }
            ]
        }
    ]
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*」の[AWS 「Organizations で複数のアカウントを管理する](https://docs.aws.amazon.com/security-lake/latest/userguide/multi-account-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDataLakeOrganizationConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/get-data-lake-organization-configuration.html)」を参照してください。

### `get-data-lake-sources`
<a name="securitylake_GetDataLakeSources_cli_2_topic"></a>

次のコード例は、`get-data-lake-sources` を使用する方法を示しています。

**AWS CLI**  
**ログ収集のステータスを取得するには**  
次の の`get-data-lake-sources`例では、現在の AWS リージョンで指定されたアカウントのログコレクションのスナップショットを取得します。アカウントでは Amazon Security Lake が有効になっています。  

```
aws securitylake get-data-lake-sources \
    --accounts "123456789012"
```
出力:  

```
{
    "dataLakeSources": [
        {
            "account": "123456789012",
            "sourceName": "SH_FINDINGS",
            "sourceStatuses": [
                {
                    "resource": "vpc-1234567890abcdef0",
                    "status": "COLLECTING"
                }
            ]
        },
        {
            "account": "123456789012",
            "sourceName": "VPC_FLOW",
            "sourceStatuses": [
                {
                    "resource": "vpc-1234567890abcdef0",
                    "status": "NOT_COLLECTING"
                }
            ]
        },
        {
            "account": "123456789012",
            "sourceName": "LAMBDA_EXECUTION",
            "sourceStatuses": [
                {
                    "resource": "vpc-1234567890abcdef0",
                    "status": "COLLECTING"
                }
            ]
        },
        {
            "account": "123456789012",
            "sourceName": "ROUTE53",
            "sourceStatuses": [
                {
                    "resource": "vpc-1234567890abcdef0",
                    "status": "COLLECTING"
                }
            ]
        },
        {
            "account": "123456789012",
            "sourceName": "CLOUD_TRAIL_MGMT",
            "sourceStatuses": [
                {
                    "resource": "vpc-1234567890abcdef0",
                    "status": "COLLECTING"
                }
            ]
        }
    ],
    "dataLakeArn": null
}
```
詳細については、*「Amazon Security Lake* [ユーザーガイド」の「 AWS のサービスからのデータ収集](https://docs.aws.amazon.com/security-lake/latest/userguide/internal-sources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDataLakeSources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/get-data-lake-sources.html)」を参照してください。

### `get-subscriber`
<a name="securitylake_GetSubscriber_cli_2_topic"></a>

次のコード例は、`get-subscriber` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション情報を取得するには**  
次の `get-subscriber` の例では、指定された Securiy Lake サブスクライバーのサブスクリプション情報を取得します。  

```
aws securitylake get-subscriber \
    --subscriber-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "subscriber": {
        "accessTypes": [
            "LAKEFORMATION"
        ],
        "createdAt": "2024-04-19T15:19:44.421803+00:00",
        "resourceShareArn": "arn:aws:ram:eu-west-2:123456789012:resource-share/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "resourceShareName": "LakeFormation-V3-TKJGBHCKTZ-123456789012",
        "sources": [
            {
                "awsLogSource": {
                    "sourceName": "LAMBDA_EXECUTION",
                    "sourceVersion": "1.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "EKS_AUDIT",
                    "sourceVersion": "2.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "ROUTE53",
                    "sourceVersion": "1.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "SH_FINDINGS",
                    "sourceVersion": "1.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "VPC_FLOW",
                    "sourceVersion": "1.0"
                }
            },
            {
                "customLogSource": {
                    "attributes": {
                        "crawlerArn": "arn:aws:glue:eu-west-2:123456789012:crawler/testCustom2",
                        "databaseArn": "arn:aws:glue:eu-west-2:123456789012:database/amazon_security_lake_glue_db_eu_west_2",
                        "tableArn": "arn:aws:glue:eu-west-2:123456789012:table/amazon_security_lake_table_eu_west_2_ext_testcustom2"
                    },
                    "provider": {
                        "location": "s3://aws-security-data-lake-eu-west-2-8ugsus4ztnsfpjbldwbgf4vge98av9/ext/testCustom2/",
                        "roleArn": "arn:aws:iam::123456789012:role/AmazonSecurityLake-Provider-testCustom2-eu-west-2"
                    },
                    "sourceName": "testCustom2"
                }
            },
            {
                "customLogSource": {
                    "attributes": {
                        "crawlerArn": "arn:aws:glue:eu-west-2:123456789012:crawler/TestCustom",
                        "databaseArn": "arn:aws:glue:eu-west-2:123456789012:database/amazon_security_lake_glue_db_eu_west_2",
                        "tableArn": "arn:aws:glue:eu-west-2:123456789012:table/amazon_security_lake_table_eu_west_2_ext_testcustom"
                    },
                    "provider": {
                        "location": "s3://aws-security-data-lake-eu-west-2-8ugsus4ztnsfpjbldwbgf4vge98av9/ext/TestCustom/",
                        "roleArn": "arn:aws:iam::123456789012:role/AmazonSecurityLake-Provider-TestCustom-eu-west-2"
                    },
                    "sourceName": "TestCustom"
                }
            }
        ],
        "subscriberArn": "arn:aws:securitylake:eu-west-2:123456789012:subscriber/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "subscriberId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "subscriberIdentity": {
            "externalId": "123456789012",
            "principal": "123456789012"
        },
        "subscriberName": "test",
        "subscriberStatus": "ACTIVE",
        "updatedAt": "2024-04-19T15:19:55.230588+00:00"
    }
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[サブスクライバー管理](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSubscriber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/get-subscriber.html)」を参照してください。

### `list-data-lake-exceptions`
<a name="securitylake_ListDataLakeExceptions_cli_2_topic"></a>

次のコード例は、`list-data-lake-exceptions` を使用する方法を示しています。

**AWS CLI**  
**データレイクに影響する問題を一覧表示するには**  
次の の`list-data-lake-exceptions`例では、指定された AWS リージョンで過去 14 日間にデータレイクに影響を与えている問題を一覧表示します。  

```
aws securitylake list-data-lake-exceptions \
    --regions "us-east-1" "eu-west-3"
```
出力:  

```
{
    "exceptions": [
        {
            "exception": "The account does not have the required role permissions. Update your role permissions to use the new data source version.",
            "region": "us-east-1",
            "timestamp": "2024-02-29T12:24:15.641725+00:00"
        },
        {
            "exception": "The account does not have the required role permissions. Update your role permissions to use the new data source version.",
            "region": "eu-west-3",
            "timestamp": "2024-02-29T12:24:15.641725+00:00"
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Amazon Security Lake のトラブルシューティング](https://docs.aws.amazon.com/security-lake/latest/userguide/security-lake-troubleshoot.html#securitylake-data-lake-troubleshoot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDataLakeExceptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/list-data-lake-exceptions.html)」を参照してください。

### `list-data-lakes`
<a name="securitylake_ListDataLakes_cli_2_topic"></a>

次のコード例は、`list-data-lakes` を使用する方法を示しています。

**AWS CLI**  
**Security Lake 設定オブジェクトを一覧表示するには**  
次の の`list-data-lakes`例では、指定された AWS リージョンの Amazon Security Lake 設定オブジェクトを一覧表示します。このコマンドを使用して、指定されたリージョンで Security Lake が有効になっているかどうかを判断できます。  

```
aws securitylake list-data-lakes \
    --regions "us-east-1"
```
出力:  

```
{
    "dataLakes": [
        {
            "createStatus": "COMPLETED",
            "dataLakeArn": "arn:aws:securitylake:us-east-1:123456789012:data-lake/default",
            "encryptionConfiguration": {
                "kmsKeyId": "S3_MANAGED_KEY"
            },
            "lifecycleConfiguration": {
                "expiration": {
                    "days": 365
                },
                "transitions": [
                    {
                        "days": 60,
                        "storageClass": "ONEZONE_IA"
                    }
                ]
            },
            "region": "us-east-1",
            "replicationConfiguration": {
                "regions": [
                    "ap-northeast-3"
                ],
                "roleArn": "arn:aws:securitylake:ap-northeast-3:123456789012:data-lake/default"
            },
            "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-1-1234567890abcdef0",
            "updateStatus": {
                "exception": {
                    "code": "software.amazon.awssdk.services.s3.model.S3Exception",
                    "reason": ""
                },
                "requestId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
                "status": "FAILED"
            }
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[リージョンステータスの確認](https://docs.aws.amazon.com/security-lake/latest/userguide/manage-regions.html#check-region-status)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDataLakes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/list-data-lakes.html)」を参照してください。

### `list-log-sources`
<a name="securitylake_ListLogSources_cli_2_topic"></a>

次のコード例は、`list-log-sources` を使用する方法を示しています。

**AWS CLI**  
**Amazon Security Lake ログソースを取得するには**  
次の `list-log-sources` の例では、指定されたアカウントの Amazon Security Lake ログソースを一覧表示します。  

```
aws securitylake list-log-sources \
    --accounts "123456789012"
```
出力:  

```
{
    "account": "123456789012",
    "region": "xy-region-1",
    "sources": [
        {
               "awsLogSource": {
                "sourceName": "VPC_FLOW",
                "sourceVersion": "2.0"
            }
        },
        {
            "awsLogSource": {
                "sourceName": "SH_FINDINGS",
                "sourceVersion": "2.0"
            }
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Source management in Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/source-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLogSources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/list-log-sources.html)」を参照してください。

### `list-subscribers`
<a name="securitylake_ListSubscribers_cli_2_topic"></a>

次のコード例は、`list-subscribers` を使用する方法を示しています。

**AWS CLI**  
**Amazon Security Lake サブスクライバーを取得するには**  
次の `list-subscribers` の例では、特定のアカウントのすべての Amazon Security Lake サブスクライバーを一覧表示します。  

```
aws securitylake list-subscribers
```
出力:  

```
{
    "subscribers": [
        {
            "accessTypes": [
                "S3"
            ],
            "createdAt": "2024-06-04T15:02:28.921000+00:00",
            "roleArn": "arn:aws:iam::123456789012:role/AmazonSecurityLake-E1WG1ZNPRXT0D4",
            "s3BucketArn": "amzn-s3-demo-bucket--usw2-az1--x-s3",
            "sources": [
                {
                    "awsLogSource": {
                        "sourceName": "CLOUD_TRAIL_MGMT",
                        "sourceVersion": "2.0"
                    }
                },
                {
                    "awsLogSource": {
                        "sourceName": "LAMBDA_EXECUTION",
                        "sourceVersion": "1.0"
                    }
                },
                {
                    "customLogSource": {
                        "attributes": {
                            "crawlerArn": "arn:aws:glue:eu-west-2:123456789012:crawler/E1WG1ZNPRXT0D4",
                            "databaseArn": "arn:aws:glue:eu-west-2:123456789012:database/E1WG1ZNPRXT0D4",
                            "tableArn": "arn:aws:glue:eu-west-2:123456789012:table/E1WG1ZNPRXT0D4"
                        },
                        "provider": {
                            "location": "amzn-s3-demo-bucket--usw2-az1--x-s3",
                            "roleArn": "arn:aws:iam::123456789012:role/AmazonSecurityLake-E1WG1ZNPRXT0D4"
                        },
                        "sourceName": "testCustom2"
                    }
                }
            ],
            "subscriberArn": "arn:aws:securitylake:eu-west-2:123456789012:subscriber/E1WG1ZNPRXT0D4",
            "subscriberEndpoint": "arn:aws:sqs:eu-west-2:123456789012:AmazonSecurityLake-a1b2c3d4-5678-90ab-cdef-EXAMPLE11111-Main-Queue",
            "subscriberId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "subscriberIdentity": {
                "externalId": "ext123456789012",
                "principal": "123456789012"
            },
            "subscriberName": "Test",
            "subscriberStatus": "ACTIVE",
            "updatedAt": "2024-06-04T15:02:35.617000+00:00"
        }
    ]
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[サブスクライバー管理](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSubscribers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/list-subscribers.html)」を参照してください。

### `list-tags-for-resource`
<a name="securitylake_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のリソースのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された Amazon Security Lake サブスクライバーのタグを一覧表示します。この例で、所有者タグキーに関連するタグ値はありません。このオペレーションを使用して、他の既存の Security Lake リソースのタグを一覧表示することもできます。  

```
aws securitylake list-tags-for-resource \
    --resource-arn "arn:aws:securitylake:us-east-1:123456789012:subscriber/1234abcd-12ab-34cd-56ef-1234567890ab"
```
出力:  

```
{
    "tags": [
        {
            "key": "Environment",
            "value": "Cloud"
        },
        {
            "key": "CostCenter",
            "value": "12345"
        },
        {
            "key": "Owner",
            "value": ""
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Tagging Security Lake resources](https://docs.aws.amazon.com/security-lake/latest/userguide/tagging-resources.html#tags-retrieve)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/list-tags-for-resource.html)」を参照してください。

### `register-data-lake-delegated-administrator`
<a name="securitylake_RegisterDataLakeDelegatedAdministrator_cli_2_topic"></a>

次のコード例は、`register-data-lake-delegated-administrator` を使用する方法を示しています。

**AWS CLI**  
**委任された管理者を指定するには**  
次の の`register-data-lake-delegated-administrator`例では、指定された AWS アカウントを委任 Amazon Security Lake 管理者として指定します。  

```
aws securitylake register-data-lake-delegated-administrator \
    --account-id 123456789012
```
このコマンドでは何も出力されません。  
詳細については、*「Amazon Security Lake ユーザーガイド*」の[AWS 「Organizations で複数のアカウントを管理する](https://docs.aws.amazon.com/security-lake/latest/userguide/multi-account-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス」の「[RegisterDataLakeDelegatedAdministrator](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/register-data-lake-delegated-administrator.html)*」を参照してください。

### `tag-resource`
<a name="securitylake_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のリソースにタグを追加するには**  
次の`tag-resource`例では、既存のサブスクライバーリソースにタグを追加します。新しいリソースを作成して 1 つ以上のタグを追加する場合に、このオペレーションを使用しないでください。代わりに、作成するリソースのタイプに適した作成オペレーションを使用します。  

```
aws securitylake tag-resource \
    --resource-arn "arn:aws:securitylake:us-east-1:123456789012:subscriber/1234abcd-12ab-34cd-56ef-1234567890ab" \
    --tags key=Environment,value=Cloud
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Tagging Security Lake resources](https://docs.aws.amazon.com/security-lake/latest/userguide/tagging-resources.html#tags-retrieve)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="securitylake_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のリソースからタグを削除するには**  
次の`untag-resource`例では、既存のサブスクライバーリソースから指定されたタグを削除します。  

```
aws securitylake untag-resource \
    --resource-arn "arn:aws:securitylake:us-east-1:123456789012:subscriber/1234abcd-12ab-34cd-56ef-1234567890ab" \
    --tags Environment Owner
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Tagging Security Lake resources](https://docs.aws.amazon.com/security-lake/latest/userguide/tagging-resources.html#tags-retrieve)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/untag-resource.html)」を参照してください。

### `update-data-lake-exception-subscription`
<a name="securitylake_UpdateDataLakeExceptionSubscription_cli_2_topic"></a>

次のコード例は、`update-data-lake-exception-subscription` を使用する方法を示しています。

**AWS CLI**  
**Security Lake の例外の通知サブスクリプションを更新するには**  
次の `update-data-lake-exception-subscription` の例では、Security Lake の例外をユーザーに通知する通知サブスクリプションを更新します。  

```
aws securitylake update-data-lake-exception-subscription \
    --notification-endpoint "123456789012" \
    --exception-time-to-live 30 \
    --subscription-protocol "email"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Amazon Security Lake のトラブルシューティング](https://docs.aws.amazon.com/security-lake/latest/userguide/security-lake-troubleshoot.html#securitylake-data-lake-troubleshoot)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDataLakeExceptionSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/update-data-lake-exception-subscription.html)」を参照してください。

### `update-data-lake`
<a name="securitylake_UpdateDataLake_cli_2_topic"></a>

次のコード例は、`update-data-lake` を使用する方法を示しています。

**AWS CLI**  
**例 1: データレイク設定を更新するには**  
次の `update-data-lake` の例では、Amazon Security Lake データレイクの設定を更新します。このオペレーションを使用して、データ暗号化、ストレージ、ロールアップリージョンの設定を指定できます。  

```
aws securitylake update-data-lake \
    --configurations '[{"encryptionConfiguration": {"kmsKeyId":"S3_MANAGED_KEY"},"region":"us-east-1","lifecycleConfiguration": {"expiration":{"days":365},"transitions":[{"days":60,"storageClass":"ONEZONE_IA"}]}}, {"encryptionConfiguration": {"kmsKeyId":"S3_MANAGED_KEY"},"region":"us-east-2","lifecycleConfiguration": {"expiration":{"days":365},"transitions":[{"days":60,"storageClass":"ONEZONE_IA"}]}}]' \
    --meta-store-manager-role-arn "arn:aws:iam:us-east-1:123456789012:role/service-role/AmazonSecurityLakeMetaStoreManager"
```
出力:  

```
{
    "dataLakes": [
        {
            "createStatus": "COMPLETED",
            "dataLakeArn": "arn:aws:securitylake:us-east-1:522481757177:data-lake/default",
            "encryptionConfiguration": {
                "kmsKeyId": "S3_MANAGED_KEY"
            },
            "lifecycleConfiguration": {
                "expiration": {
                    "days": 365
                },
                "transitions": [
                    {
                        "days": 60,
                        "storageClass": "ONEZONE_IA"
                    }
                ]
            },
            "region": "us-east-1",
            "replicationConfiguration": {
                "regions": [
                    "ap-northeast-3"
                ],
                "roleArn": "arn:aws:securitylake:ap-northeast-3:522481757177:data-lake/default"
            },
            "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-1-gnevt6s8z7bzby8oi3uiaysbr8v2ml",
            "updateStatus": {
                "exception": {},
                "requestId": "f20a6450-d24a-4f87-a6be-1d4c075a59c2",
                "status": "INITIALIZED"
            }
        },
        {
            "createStatus": "COMPLETED",
            "dataLakeArn": "arn:aws:securitylake:us-east-2:522481757177:data-lake/default",
            "encryptionConfiguration": {
                "kmsKeyId": "S3_MANAGED_KEY"
            },
            "lifecycleConfiguration": {
                "expiration": {
                    "days": 365
                },
                "transitions": [
                    {
                        "days": 60,
                        "storageClass": "ONEZONE_IA"
                    }
                ]
            },
            "region": "us-east-2",
            "replicationConfiguration": {
                "regions": [
                    "ap-northeast-3"
                ],
                "roleArn": "arn:aws:securitylake:ap-northeast-3:522481757177:data-lake/default"
            },
            "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-2-cehuifzl5rwmhm6m62h7zhvtseogr9",
            "updateStatus": {
                "exception": {},
                "requestId": "f20a6450-d24a-4f87-a6be-1d4c075a59c2",
                "status": "INITIALIZED"
            }
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Getting started with Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/getting-started.html)」を参照してください。  
**例 2: 1 つのリージョンでデータレイクを設定するには**  
次の`create-data-lake`例では、単一の AWS リージョンで Amazon Security Lake を有効にし、データレイクを設定します。  

```
aws securitylake create-data-lake \
    --configurations '[{"encryptionConfiguration": {"kmsKeyId":"1234abcd-12ab-34cd-56ef-1234567890ab"},"region":"us-east-2","lifecycleConfiguration": {"expiration":{"days":500},"transitions":[{"days":30,"storageClass":"GLACIER"}]}}]' \
    --meta-store-manager-role-arn "arn:aws:iam:us-east-1:123456789012:role/service-role/AmazonSecurityLakeMetaStoreManager"
```
出力:  

```
{
    "dataLakes": [
        {
            "createStatus": "COMPLETED",
            "dataLakeArn": "arn:aws:securitylake:us-east-2:522481757177:data-lake/default",
            "encryptionConfiguration": {
                "kmsKeyId": "1234abcd-12ab-34cd-56ef-1234567890ab"
            },
            "lifecycleConfiguration": {
                "expiration": {
                    "days": 500
                },
                "transitions": [
                    {
                        "days": 30,
                        "storageClass": "GLACIER"
                    }
                ]
            },
            "region": "us-east-2",
            "replicationConfiguration": {
                "regions": [
                    "ap-northeast-3"
                ],
                "roleArn": "arn:aws:securitylake:ap-northeast-3:522481757177:data-lake/default"
            },
            "s3BucketArn": "arn:aws:s3:::aws-security-data-lake-us-east-2-cehuifzl5rwmhm6m62h7zhvtseogr9",
            "updateStatus": {
                "exception": {},
                "requestId": "77702a53-dcbf-493e-b8ef-518e362f3003",
                "status": "INITIALIZED"
            }
        }
    ]
}
```
詳細については、「*Amazon Security Lake ユーザーガイド*」の「[Getting started with Amazon Security Lake](https://docs.aws.amazon.com/security-lake/latest/userguide/getting-started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDataLake](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/update-data-lake.html)」を参照してください。

### `update-subscriber-notification`
<a name="securitylake_UpdateSubscriberNotification_cli_2_topic"></a>

次のコード例は、`update-subscriber-notification` を使用する方法を示しています。

**AWS CLI**  
**サブスクライバー通知を更新するには**  
次の `update-subscriber-notification` の例では、サブスクライバーの通知方法を更新する方法を示しています。  

```
aws securitylake update-subscriber-notification \
    --subscriber-id "12345ab8-1a34-1c34-1bd4-12345ab9012" \
    --configuration '{"httpsNotificationConfiguration": {"targetRoleArn":"arn:aws:iam::XXX:role/service-role/RoleName", "endpoint":"https://account-management.$3.$2.securitylake.aws.dev/v1/datalake"}}'
```
出力:  

```
{
    "subscriberEndpoint": [
        "https://account-management.$3.$2.securitylake.aws.dev/v1/datalake"
    ]
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[サブスクライバー管理](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSubscriberNotification](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/update-subscriber-notification.html)」を参照してください。

### `update-subscriber`
<a name="securitylake_UpdateSubscriber_cli_2_topic"></a>

次のコード例は、`update-subscriber` を使用する方法を示しています。

**AWS CLI**  
**Amazon Security Lake サブスクライバーを更新するには。**  
次の `update-subscriber` の例では、特定の Security Lake サブスクライバーのセキュリティレイクデータソースを更新します。  

```
aws securitylake update-subscriber \
    --subscriber-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "subscriber": {
        "accessTypes": [
            "LAKEFORMATION"
        ],
        "createdAt": "2024-04-19T15:19:44.421803+00:00",
        "resourceShareArn": "arn:aws:ram:eu-west-2:123456789012:resource-share/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "resourceShareName": "LakeFormation-V3-TKJGBHCKTZ-123456789012",
        "sources": [
            {
                "awsLogSource": {
                    "sourceName": "LAMBDA_EXECUTION",
                    "sourceVersion": "1.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "EKS_AUDIT",
                    "sourceVersion": "2.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "ROUTE53",
                    "sourceVersion": "1.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "SH_FINDINGS",
                    "sourceVersion": "1.0"
                }
            },
            {
                "awsLogSource": {
                    "sourceName": "VPC_FLOW",
                    "sourceVersion": "1.0"
                }
            },
            {
                "customLogSource": {
                    "attributes": {
                        "crawlerArn": "arn:aws:glue:eu-west-2:123456789012:crawler/E1WG1ZNPRXT0D4",
                        "databaseArn": "arn:aws:glue:eu-west-2:123456789012:database/E1WG1ZNPRXT0D4",
                        "tableArn": "arn:aws:glue:eu-west-2:123456789012:table/E1WG1ZNPRXT0D4"
                    },
                    "provider": {
                        "location": "amzn-s3-demo-bucket--usw2-az1--x-s3",
                        "roleArn": "arn:aws:iam::123456789012:role/AmazonSecurityLake-E1WG1ZNPRXT0D4"
                    },
                    "sourceName": "testCustom2"
                }
            }
        ],
        "subscriberArn": "arn:aws:securitylake:eu-west-2:123456789012:subscriber/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "subscriberId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "subscriberIdentity": {
            "externalId": "123456789012",
            "principal": "123456789012"
        },
        "subscriberName": "test",
        "subscriberStatus": "ACTIVE",
        "updatedAt": "2024-07-18T20:47:37.098000+00:00"
    }
}
```
詳細については、*「Amazon Security Lake ユーザーガイド*」の「[サブスクライバー管理](https://docs.aws.amazon.com/security-lake/latest/userguide/subscriber-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSubscriber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/securitylake/update-subscriber.html)」を参照してください。

# AWS Serverless Application Repository を使用した の例 AWS CLI
<a name="cli_2_serverlessapplicationrepository_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Serverless Application Repository。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `put-application-policy`
<a name="serverlessapplicationrepository_PutApplicationPolicy_cli_2_topic"></a>

次のコード例は、`put-application-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: アプリケーションを公開共有するには**  
次の `put-application-policy`はアプリケーションを公開しているため、誰でも AWS サーバーレスアプリケーションリポジトリでアプリケーションを検索してデプロイできます。  

```
aws serverlessrepo put-application-policy \
    --application-id arn:aws:serverlessrepo:us-east-1:123456789012:applications/my-test-application \
    --statements Principals='*',Actions=Deploy
```
出力:  

```
{
    "Statements": [
        {
            "Actions": [
                "Deploy"
            ],
            "Principals": [
                ""
            ],
            "StatementId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
        }
    ]
}
```
**例 2:** アプリケーションをプライベートに共有するには  
次の はアプリケーションをプライベートに`put-application-policy`共有するため、特定の AWS アカウントのみが AWS サーバーレスアプリケーションリポジトリでアプリケーションを検索してデプロイできます。  

```
aws serverlessrepo put-application-policy \
    --application-id arn:aws:serverlessrepo:us-east-1:123456789012:applications/my-test-application \
    --statements Principals=111111111111,222222222222,Actions=Deploy
```
出力:  

```
{
    "Statements": [
        {
            "Actions": [
                "Deploy"
            ],
            "Principals": [
                "111111111111",
                "222222222222"
            ],
            "StatementId": "a1b2c3d4-5678-90ab-cdef-11111EXAMPLE"
        }
    ]
}
```
詳細については、「*AWS Serverless Application Repository デベロッパーガイド*」の「[コンソールを介したアプリケーションの共有](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverlessrepo-how-to-publish.html#share-application)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutApplicationPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/serverlessrepo/put-application-policy.html)」を参照してください。

# を使用した Service Catalog の例 AWS CLI
<a name="cli_2_service-catalog_code_examples"></a>

次のコード例は、Service Catalog AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `accept-portfolio-share`
<a name="service-catalog_AcceptPortfolioShare_cli_2_topic"></a>

次のコード例は、`accept-portfolio-share` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオの共有を受け入れるには**  
次の `accept-portfolio-share` の例では、指定されたポートフォリオを共有するために別のユーザーが行ったオファーを受け入れます。  

```
aws servicecatalog accept-portfolio-share \
    --portfolio-id port-2s6wuabcdefghijk
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AcceptPortfolioShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/accept-portfolio-share.html)」を参照してください。

### `associate-principal-with-portfolio`
<a name="service-catalog_AssociatePrincipalWithPortfolio_cli_2_topic"></a>

次のコード例は、`associate-principal-with-portfolio` を使用する方法を示しています。

**AWS CLI**  
**プリンシパルをポートフォリオに関連付けるには**  
次の `associate-principal-with-portfolio` の例では、指定されたポートフォリオにユーザーを関連付けます。  

```
aws servicecatalog associate-principal-with-portfolio \
    --portfolio-id port-2s6abcdefwdh4 \
    --principal-arn arn:aws:iam::123456789012:user/usertest \
    --principal-type IAM
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociatePrincipalWithPortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/associate-principal-with-portfolio.html)」を参照してください。

### `associate-product-with-portfolio`
<a name="service-catalog_AssociateProductWithPortfolio_cli_2_topic"></a>

次のコード例は、`associate-product-with-portfolio` を使用する方法を示しています。

**AWS CLI**  
**製品をポートフォリオに関連付けるには**  
次の `associate-product-with-portfolio` の例では、特定の製品を指定されたポートフォリオに関連付けます。  

```
aws servicecatalog associate-product-with-portfolio
     --product-id prod-3p5abcdef3oyk
     --portfolio-id port-2s6abcdef5wdh4
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateProductWithPortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/associate-product-with-portfolio.html)」を参照してください。

### `associate-tag-option-with-resource`
<a name="service-catalog_AssociateTagOptionWithResource_cli_2_topic"></a>

次のコード例は、`associate-tag-option-with-resource` を使用する方法を示しています。

**AWS CLI**  
**TagOption をリソースに関連付けるには**  
次の `associate-tag-option-with-resource` の例では、指定された TagOption を指定されたリソースに関連付けます。  

```
aws servicecatalog associate-tag-option-with-resource \
    --resource-id port-2s6abcdq5wdh4 \
    --tag-option-id tag-p3abc2pkpz5qc
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateTagOptionWithResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/associate-tag-option-with-resource.html)」を参照してください。

### `copy-product`
<a name="service-catalog_CopyProduct_cli_2_topic"></a>

次のコード例は、`copy-product` を使用する方法を示しています。

**AWS CLI**  
**製品をコピーするには**  
次の `copy-product` の例では、JSON ファイルを使用してパラメータを渡すことで、指定された製品のコピーを作成します。  

```
aws servicecatalog copy-product --cli-input-json file://copy-product-input.json
```
`copy-product-input.json` の内容:  

```
{
    "SourceProductArn": "arn:aws:catalog:us-west-2:123456789012:product/prod-tcabcd3syn2xy",
    "TargetProductName": "copy-of-myproduct",
    "CopyOptions": [
        "CopyTags"
    ]
}
```
出力:  

```
{
    "CopyProductToken": "copyproduct-abc5defgjkdji"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CopyProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/copy-product.html)」を参照してください。

### `create-portfolio-share`
<a name="service-catalog_CreatePortfolioShare_cli_2_topic"></a>

次のコード例は、`create-portfolio-share` を使用する方法を示しています。

**AWS CLI**  
**アカウントとポートフォリオを共有するには**  
次の `create-portfolio-share` の例では、指定されたポートフォリオを指定されたアカウントと共有します。  

```
aws servicecatalog create-portfolio-share \
    --portfolio-id port-2s6abcdef5wdh4 \
    --account-id 794123456789
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePortfolioShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/create-portfolio-share.html)」を参照してください。

### `create-portfolio`
<a name="service-catalog_CreatePortfolio_cli_2_topic"></a>

次のコード例は、`create-portfolio` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオを作成するには**  
次の `create-portfolio` の例ではポートフォリオを作成します。  

```
aws servicecatalog create-portfolio  \
    --provider-name my-provider \
    --display-name my-portfolio
```
出力:  

```
{
    "PortfolioDetail": {
        "ProviderName": "my-provider",
        "DisplayName": "my-portfolio",
        "CreatedTime": 1571337221.555,
        "ARN": "arn:aws:catalog:us-east-2:123456789012:portfolio/port-2s6xmplq5wdh4",
        "Id": "port-2s6xmplq5wdh4"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/create-portfolio.html)」を参照してください。

### `create-product`
<a name="service-catalog_CreateProduct_cli_2_topic"></a>

次のコード例は、`create-product` を使用する方法を示しています。

**AWS CLI**  
**製品を作成するには**  
次の `create-product` の例では、JSON ファイルを使用してパラメータをを渡すことで、製品を作成します。  

```
aws servicecatalog create-product \
    --cli-input-json file://create-product-input.json
```
`create-product-input.json` の内容:  

```
{
    "AcceptLanguage": "en",
    "Name": "test-product",
    "Owner": "test-owner",
    "Description": "test-description",
    "Distributor": "test-distributor",
    "SupportDescription": "test-support",
    "SupportEmail": "test@amazon.com",
    "SupportUrl": "https://aws.amazon.com",
    "ProductType": "CLOUD_FORMATION_TEMPLATE",
    "Tags": [
        {
            "Key": "region",
            "Value": "us-east-1"
        }
    ],
    "ProvisioningArtifactParameters": {
        "Name": "test-version-name",
        "Description": "test-version-description",
        "Info": {
            "LoadTemplateFromURL": "https://s3-us-west-1.amazonaws.com/cloudformation-templates-us-west-1/my-cfn-template.template"
        },
        "Type": "CLOUD_FORMATION_TEMPLATE"
    }
}
```
出力:  

```
{
    "Tags": [
        {
            "Key": "region",
            "Value": "us-east-1"
        }
    ],
    "ProductViewDetail": {
        "CreatedTime": 1576025036.0,
        "ProductARN": "arn:aws:catalog:us-west-2:1234568542028:product/prod-3p5abcdef3oyk",
        "Status": "CREATED",
        "ProductViewSummary": {
            "Type": "CLOUD_FORMATION_TEMPLATE",
            "Distributor": "test-distributor",
            "SupportUrl": "https://aws.amazon.com",
            "SupportEmail": "test@amazon.com",
            "Id": "prodview-abcd42wvx45um",
            "SupportDescription": "test-support",
            "ShortDescription": "test-description",
            "Owner": "test-owner",
            "Name": "test-product2",
            "HasDefaultPath": false,
            "ProductId": "prod-3p5abcdef3oyk"
        }
    },
    "ProvisioningArtifactDetail": {
        "CreatedTime": 1576025036.0,
        "Active": true,
        "Id": "pa-pq3p5lil12a34",
        "Description": "test-version-description",
        "Name": "test-version-name",
        "Type": "CLOUD_FORMATION_TEMPLATE"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/create-product.html)」を参照してください。

### `create-provisioning-artifact`
<a name="service-catalog_CreateProvisioningArtifact_cli_2_topic"></a>

次のコード例は、`create-provisioning-artifact` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングアーティファクトを作成するには**  
次の `create-provisioning-artifact` の例では、JSON ファイルを使用してパラメータを渡すことで、プロビジョニングアーティファクトを作成します。  

```
aws servicecatalog create-provisioning-artifact \
   --cli-input-json file://create-provisioning-artifact-input.json
```
`create-provisioning-artifact-input.json` の内容:  

```
{
    "ProductId": "prod-nfi2abcdefghi",
    "Parameters": {
        "Name": "test-provisioning-artifact",
        "Description": "test description",
        "Info": {
            "LoadTemplateFromURL": "https://s3-us-west-1.amazonaws.com/cloudformation-templates-us-west-1/my-cfn-template.template"
        },
        "Type": "CLOUD_FORMATION_TEMPLATE"
    }
}
```
出力:  

```
{
    "Info": {
        "TemplateUrl": "https://s3-us-west-1.amazonaws.com/cloudformation-templates-us-west-1/my-cfn-template.template"
    },
    "Status": "CREATING",
    "ProvisioningArtifactDetail": {
        "Id": "pa-bb4abcdefwnaio",
        "Name": "test-provisioning-artifact",
        "Description": "test description",
        "Active": true,
        "Type": "CLOUD_FORMATION_TEMPLATE",
        "CreatedTime": 1576022545.0
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProvisioningArtifact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/create-provisioning-artifact.html)」を参照してください。

### `create-tag-option`
<a name="service-catalog_CreateTagOption_cli_2_topic"></a>

次のコード例は、`create-tag-option` を使用する方法を示しています。

**AWS CLI**  
**TagOption を作成するには**  
次の `create-tag-option` の例では、TagOption を作成します。  

```
aws servicecatalog create-tag-option
    --key 1234
    --value name
```
出力:  

```
{
    "TagOptionDetail": {
    "Id": "tag-iabcdn4fzjjms",
    "Value": "name",
    "Active": true,
    "Key": "1234"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTagOption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/create-tag-option.html)」を参照してください。

### `delete-portfolio-share`
<a name="service-catalog_DeletePortfolioShare_cli_2_topic"></a>

次のコード例は、`delete-portfolio-share` を使用する方法を示しています。

**AWS CLI**  
**アカウントとポートフォリオの共有を停止するには**  
次の `delete-portfolio-share` の例では、指定されたアカウントとポートフォリオの共有を停止します。  

```
aws servicecatalog delete-portfolio-share \
    --portfolio-id port-2s6abcdq5wdh4 \
    --account-id 123456789012
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePortfolioShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/delete-portfolio-share.html)」を参照してください。

### `delete-portfolio`
<a name="service-catalog_DeletePortfolio_cli_2_topic"></a>

次のコード例は、`delete-portfolio` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオを削除するには**  
次の `delete-portfolio` の例では、指定されたレポートフォリオを削除します。  

```
aws servicecatalog delete-portfolio \
    --id port-abcdlx4gox4do
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeletePortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/delete-portfolio.html)」を参照してください。

### `delete-product`
<a name="service-catalog_DeleteProduct_cli_2_topic"></a>

次のコード例は、`delete-product` を使用する方法を示しています。

**AWS CLI**  
**製品を削除するには**  
次の `delete-product` の例では、指定された製品を削除します。  

```
aws servicecatalog delete-product \
    --id prod-abcdcek6yhbxi
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/delete-product.html)」を参照してください。

### `delete-provisioning-artifact`
<a name="service-catalog_DeleteProvisioningArtifact_cli_2_topic"></a>

次のコード例は、`delete-provisioning-artifact` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングアーティファクトを削除するには**  
次の `delete-provisioning-artifact` の例では、指定されたプロビジョニングアーティファクトを削除します。  

```
aws servicecatalog delete-provisioning-artifact \
    --product-id prod-abc2uebuplcpw \
    --provisioning-artifact-id pa-pqabcddii7ouc
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteProvisioningArtifact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/delete-provisioning-artifact.html)」を参照してください。

### `delete-tag-option`
<a name="service-catalog_DeleteTagOption_cli_2_topic"></a>

次のコード例は、`delete-tag-option` を使用する方法を示しています。

**AWS CLI**  
**TagOption を削除するには**  
次の `delete-tag-option` の例では、指定された TagOption を削除します。  

```
aws servicecatalog delete-tag-option \
    --id tag-iabcdn4fzjjms
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTagOption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/delete-tag-option.html)」を参照してください。

### `describe-copy-product-status`
<a name="service-catalog_DescribeCopyProductStatus_cli_2_topic"></a>

次のコード例は、`describe-copy-product-status` を使用する方法を示しています。

**AWS CLI**  
**コピー製品オペレーションのステータスを記述するには**  
次の `describe-copy-product-status` の例では、指定された非同期コピー製品オペレーションの現在のステータスを表示します。  

```
aws servicecatalog describe-copy-product-status \
    --copy-product-token copyproduct-znn5tf5abcd3w
```
出力:  

```
{
    "CopyProductStatus": "SUCCEEDED",
    "TargetProductId": "prod-os6hog7abcdt2"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCopyProductStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/describe-copy-product-status.html)」を参照してください。

### `describe-portfolio`
<a name="service-catalog_DescribePortfolio_cli_2_topic"></a>

次のコード例は、`describe-portfolio` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオの説明を表示するには**  
次の `describe-portfolio` の例は、指定されたポートフォリオの詳細情報を表示します。  

```
aws servicecatalog describe-portfolio \
    --id port-2s6abcdq5wdh4
```
出力:  

```
{
    "TagOptions": [],
    "PortfolioDetail": {
        "ARN": "arn:aws:catalog:us-west-2:687558541234:portfolio/port-2s6abcdq5wdh4",
        "Id": "port-2s6wuzyq5wdh4",
        "CreatedTime": 1571337221.555,
        "DisplayName": "my-portfolio",
        "ProviderName": "my-provider"
    },
    "Tags": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/describe-portfolio.html)」を参照してください。

### `describe-product-as-admin`
<a name="service-catalog_DescribeProductAsAdmin_cli_2_topic"></a>

次のコード例は、`describe-product-as-admin` を使用する方法を示しています。

**AWS CLI**  
**管理者として製品の説明を表示するには**  
次の `describe-product-as-admin` の例では、管理者権限を使用して、指定された製品の詳細情報を表示します。  

```
aws servicecatalog describe-product-as-admin \
    --id prod-abcdcek6yhbxi
```
出力:  

```
{
    "TagOptions": [],
    "ProductViewDetail": {
        "ProductARN": "arn:aws:catalog:us-west-2:687558542028:product/prod-abcdcek6yhbxi",
        "ProductViewSummary": {
            "SupportEmail": "test@amazon.com",
            "Type": "CLOUD_FORMATION_TEMPLATE",
            "Distributor": "test-distributor",
            "ShortDescription": "test-description",
            "Owner": "test-owner",
            "Id": "prodview-wi3l2j4abc6vc",
            "SupportDescription": "test-support",
            "ProductId": "prod-abcdcek6yhbxi",
            "HasDefaultPath": false,
            "Name": "test-product3",
            "SupportUrl": "https://aws.amazon.com"
        },
        "CreatedTime": 1577136715.0,
        "Status": "CREATED"
    },
    "ProvisioningArtifactSummaries": [
        {
            "CreatedTime": 1577136715.0,
            "Description": "test-version-description",
            "ProvisioningArtifactMetadata": {
                "SourceProvisioningArtifactId": "pa-abcdxkkiv5fcm"
            },
            "Name": "test-version-name-3",
            "Id": "pa-abcdxkkiv5fcm"
        }
    ],
    "Tags": [
        {
            "Value": "iad",
            "Key": "region"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProductAsAdmin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/describe-product-as-admin.html)」を参照してください。

### `describe-provisioned-product`
<a name="service-catalog_DescribeProvisionedProduct_cli_2_topic"></a>

次のコード例は、`describe-provisioned-product` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニング済み製品の説明を表示するには**  
次の `describe-provisioned-product` の例では、プロビジョニング済み製品の詳細情報を表示します。  

```
aws servicecatalog describe-provisioned-product \
    --id pp-dpom27bm4abcd
```
出力:  

```
{
    "ProvisionedProductDetail": {
        "Status": "ERROR",
        "CreatedTime": 1577222793.358,
        "Arn": "arn:aws:servicecatalog:us-west-2:123456789012:stack/mytestppname3/pp-dpom27bm4abcd",
        "Id": "pp-dpom27bm4abcd",
        "StatusMessage": "AmazonCloudFormationException  Parameters: [KeyName] must have values (Service: AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: 5528602a-a9ef-427c-825c-f82c31b814f5)",
        "IdempotencyToken": "527c5358-2a1a-4b9e-b1b9-7293b0ddff42",
        "LastRecordId": "rec-tfuawdjovzxge",
        "Type": "CFN_STACK",
        "Name": "mytestppname3"
    },
    "CloudWatchDashboards": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProvisionedProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/describe-provisioned-product.html)」を参照してください。

### `describe-provisioning-artifact`
<a name="service-catalog_DescribeProvisioningArtifact_cli_2_topic"></a>

次のコード例は、`describe-provisioning-artifact` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングアーティファクトの説明を表示するには**  
次の `describe-provisioning-artifact` の例では、指定されたプロビジョニングアーティファクトの詳細情報を表示します。  

```
aws servicecatalog describe-provisioning-artifact \
    --provisioning-artifact-id pa-pcz347abcdcfm \
    --product-id prod-abcdfz3syn2rg
```
出力:  

```
{
    "Info": {
        "TemplateUrl": "https://awsdocs.s3.amazonaws.com/servicecatalog/myexampledevelopment-environment.template"
    },
    "ProvisioningArtifactDetail": {
        "Id": "pa-pcz347abcdcfm",
        "Active": true,
        "Type": "CLOUD_FORMATION_TEMPLATE",
        "Description": "updated description",
        "CreatedTime": 1562097906.0,
        "Name": "updated name"
    },
    "Status": "AVAILABLE"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProvisioningArtifact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/describe-provisioning-artifact.html)」を参照してください。

### `describe-tag-option`
<a name="service-catalog_DescribeTagOption_cli_2_topic"></a>

次のコード例は、`describe-tag-option` を使用する方法を示しています。

**AWS CLI**  
**TagOption の説明を表示するには**  
次の `describe-tag-option` の例では、指定された TagOption の詳細情報を表示します。  

```
aws servicecatalog describe-tag-option \
    --id tag-p3tej2abcd5qc
```
出力:  

```
{
    "TagOptionDetail": {
        "Active": true,
        "Id": "tag-p3tej2abcd5qc",
        "Value": "value-3",
        "Key": "1234"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTagOption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/describe-tag-option.html)」を参照してください。

### `disassociate-principal-from-portfolio`
<a name="service-catalog_DisassociatePrincipalFromPortfolio_cli_2_topic"></a>

次のコード例は、`disassociate-principal-from-portfolio` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオからプリンシパルの関連付けを解除するには**  
次の `disassociate-principal-from-portfolio` の例では、指定されたプリンシパルとポートフォリオの関連付けを解除します。  

```
aws servicecatalog disassociate-principal-from-portfolio \
    --portfolio-id port-2s6abcdq5wdh4 \
    --principal-arn arn:aws:iam::123456789012:group/myendusers
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociatePrincipalFromPortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/disassociate-principal-from-portfolio.html)」を参照してください。

### `disassociate-product-from-portfolio`
<a name="service-catalog_DisassociateProductFromPortfolio_cli_2_topic"></a>

次のコード例は、`disassociate-product-from-portfolio` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオから製品の関連付けを解除するには**  
次の `disassociate-product-from-portfolio` の例では、ポートフォリオから指定された製品の関連付けを解除します。  

```
aws servicecatalog disassociate-product-from-portfolio \
    --product-id prod-3p5abcdmu3oyk \
    --portfolio-id port-2s6abcdq5wdh4
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateProductFromPortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/disassociate-product-from-portfolio.html)」を参照してください。

### `disassociate-tag-option-from-resource`
<a name="service-catalog_DisassociateTagOptionFromResource_cli_2_topic"></a>

次のコード例は、`disassociate-tag-option-from-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースから TagOption の関連付けを解除するには**  
次の `disassociate-tag-option-from-resource` の例では、リソースから指定された `TagOption` の関連付けを解除します。  

```
aws servicecatalog disassociate-tag-option-from-resource \
     --resource-id port-2s6abcdq5wdh4 \
     --tag-option-id tag-p3abc2pkpz5qc
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateTagOptionFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/disassociate-tag-option-from-resource.html)」を参照してください。

### `list-accepted-portfolio-shares`
<a name="service-catalog_ListAcceptedPortfolioShares_cli_2_topic"></a>

次のコード例は、`list-accepted-portfolio-shares` を使用する方法を示しています。

**AWS CLI**  
**受け入れられたポートフォリオ共有を一覧表示するには**  
次の `list-accepted-portfolio-shares` の例では、デフォルトの Service Catalog ポートフォリオのみを含む、このアカウントで共有が受け入れられたすべてのポートフォリオを一覧表示します。  

```
aws servicecatalog list-accepted-portfolio-shares \
    --portfolio-share-type "AWS_SERVICECATALOG"
```
出力:  

```
{
    "PortfolioDetails": [
        {
            "ARN": "arn:aws:catalog:us-west-2:123456789012:portfolio/port-d2abcd5dpkuma",
            "Description": "AWS Service Catalog Reference blueprints for often-used AWS services such as EC2, S3, RDS, VPC and EMR.",
            "CreatedTime": 1574456190.687,
            "ProviderName": "AWS Service Catalog",
            "DisplayName": "Reference Architectures",
            "Id": "port-d2abcd5dpkuma"
        },
        {
            "ARN": "arn:aws:catalog:us-west-2:123456789012:portfolio/port-abcdefaua7zpu",
            "Description": "AWS well-architected blueprints for high reliability applications.",
            "CreatedTime": 1574461496.092,
            "ProviderName": "AWS Service Catalog",
            "DisplayName": "High Reliability Architectures",
            "Id": "port-abcdefaua7zpu"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAcceptedPortfolioShares](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-accepted-portfolio-shares.html)」を参照してください。

### `list-portfolio-access`
<a name="service-catalog_ListPortfolioAccess_cli_2_topic"></a>

次のコード例は、`list-portfolio-access` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオにアクセスできるアカウントを一覧表示するには**  
次の の`list-portfolio-access`例では、指定されたポートフォリオにアクセスできる AWS アカウントを一覧表示します。  

```
aws servicecatalog list-portfolio-access \
    --portfolio-id port-2s6abcdq5wdh4
```
出力:  

```
{
    "AccountIds": [
        "123456789012"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPortfolioAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-portfolio-access.html)」を参照してください。

### `list-portfolios-for-product`
<a name="service-catalog_ListPortfoliosForProduct_cli_2_topic"></a>

次のコード例は、`list-portfolios-for-product` を使用する方法を示しています。

**AWS CLI**  
**製品に関連付けられたポートフォリオを一覧表するには**  
次の `list-portfolios-for-product` の例では、指定された製品に関連付けられたポートフォリオを一覧表示します。  

```
aws servicecatalog list-portfolios-for-product \
    --product-id prod-abcdfz3syn2rg
```
出力:  

```
{
    "PortfolioDetails": [
        {
            "CreatedTime": 1571337221.555,
            "Id": "port-2s6abcdq5wdh4",
            "ARN": "arn:aws:catalog:us-west-2:123456789012:portfolio/port-2s6abcdq5wdh4",
            "DisplayName": "my-portfolio",
            "ProviderName": "my-provider"
        },
        {
            "CreatedTime": 1559665256.348,
            "Id": "port-5abcd3e5st4ei",
            "ARN": "arn:aws:catalog:us-west-2:123456789012:portfolio/port-5abcd3e5st4ei",
            "DisplayName": "test",
            "ProviderName": "provider-name"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPortfoliosForProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-portfolios-for-product.html)」を参照してください。

### `list-portfolios`
<a name="service-catalog_ListPortfolios_cli_2_topic"></a>

次のコード例は、`list-portfolios` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオを一覧表示するには**  
次の `list-portfolios` の例では、現在のリージョンの Service Catalog ポートフォリオを一覧表示します。  

```
aws servicecatalog list-portfolios
```
出力:  

```
{
    "PortfolioDetails": [
        {
           "CreatedTime": 1559665256.348,
           "ARN": "arn:aws:catalog:us-east-2:123456789012:portfolio/port-5pzcxmplst4ei",
           "DisplayName": "my-portfolio",
           "Id": "port-5pzcxmplst4ei",
           "ProviderName": "my-user"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPortfolios](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-portfolios.html)」を参照してください。

### `list-principals-for-portfolio`
<a name="service-catalog_ListPrincipalsForPortfolio_cli_2_topic"></a>

次のコード例は、`list-principals-for-portfolio` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオのすべてのプリンシパルを一覧表示するには**  
次の `list-principals-for-portfolio` の例では、指定されたポートフォリオのすべてのプリンシパルを一覧表示します。  

```
aws servicecatalog list-principals-for-portfolio \
    --portfolio-id port-2s6abcdq5wdh4
```
出力:  

```
{
    "Principals": [
        {
            "PrincipalARN": "arn:aws:iam::123456789012:user/usertest",
            "PrincipalType": "IAM"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPrincipalsForPortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-principals-for-portfolio.html)」を参照してください。

### `list-provisioning-artifacts`
<a name="service-catalog_ListProvisioningArtifacts_cli_2_topic"></a>

次のコード例は、`list-provisioning-artifacts` を使用する方法を示しています。

**AWS CLI**  
**製品のすべてのプロビジョニングアーティファクトを一覧表示するには**  
次の `list-provisioning-artifacts` の例では、指定された製品のすべてのプロビジョニングアーティファクトを一覧表示します。  

```
aws servicecatalog list-provisioning-artifacts \
    --product-id prod-nfi2abcdefgcpw
```
出力:  

```
{
    "ProvisioningArtifactDetails": [
        {
            "Id": "pa-abcdef54ipm6z",
            "Description": "test-version-description",
            "Type": "CLOUD_FORMATION_TEMPLATE",
            "CreatedTime": 1576021147.0,
            "Active": true,
            "Name": "test-version-name"
        },
        {
            "Id": "pa-bb4zyxwwnaio",
            "Description": "test description",
            "Type": "CLOUD_FORMATION_TEMPLATE",
            "CreatedTime": 1576022545.0,
            "Active": true,
            "Name": "test-provisioning-artifact-2"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProvisioningArtifacts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-provisioning-artifacts.html)」を参照してください。

### `list-resources-for-tag-option`
<a name="service-catalog_ListResourcesForTagOption_cli_2_topic"></a>

次のコード例は、`list-resources-for-tag-option` を使用する方法を示しています。

**AWS CLI**  
**TagOption に関連付けられたリソースを一覧表示するには**  
次の `list-resources-for-tag-option` の例では、指定された `TagOption` に関連付けられたリソースを一覧表示します。  

```
aws servicecatalog list-resources-for-tag-option \
    --tag-option-id tag-p3tej2abcd5qc
```
出力:  

```
{
    "ResourceDetails": [
        {
            "ARN": "arn:aws:catalog:us-west-2:123456789012:product/prod-abcdfz3syn2rg",
            "Name": "my product",
            "Description": "description",
            "CreatedTime": 1562097906.0,
            "Id": "prod-abcdfz3syn2rg"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourcesForTagOption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-resources-for-tag-option.html)」を参照してください。

### `list-tag-options`
<a name="service-catalog_ListTagOptions_cli_2_topic"></a>

次のコード例は、`list-tag-options` を使用する方法を示しています。

**AWS CLI**  
次の `list-tag-options` の例では、`TagOptions` のすべての値を一覧表示します。  

```
aws servicecatalog list-tag-options
```
出力:  

```
{
    "TagOptionDetails": [
        {
            "Value": "newvalue",
            "Active": true,
            "Id": "tag-iabcdn4fzjjms",
            "Key": "1234"
        },
        {
            "Value": "value1",
            "Active": true,
            "Id": "tag-e3abcdvmwvrzy",
            "Key": "key"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagOptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/list-tag-options.html)」を参照してください。

### `provision-product`
<a name="service-catalog_ProvisionProduct_cli_2_topic"></a>

次のコード例は、`provision-product` を使用する方法を示しています。

**AWS CLI**  
**製品をプロビジョニングするには**  
次の `provision-product` の例では、指定されたプロビジョニングアーティファクトを使用して、指定された製品をプロビジョニングします。  

```
aws servicecatalog provision-product \
    --product-id prod-abcdfz3syn2rg \
    --provisioning-artifact-id pa-abc347pcsccfm \
    --provisioned-product-name "mytestppname3"
```
出力:  

```
{
    "RecordDetail": {
        "RecordId": "rec-tfuawdabcdege",
        "CreatedTime": 1577222793.362,
        "ProvisionedProductId": "pp-abcd27bm4mldq",
        "PathId": "lpv2-abcdg3jp6t5k6",
        "RecordErrors": [],
        "ProductId": "prod-abcdfz3syn2rg",
        "UpdatedTime": 1577222793.362,
        "RecordType": "PROVISION_PRODUCT",
        "ProvisionedProductName": "mytestppname3",
        "ProvisioningArtifactId": "pa-pcz347abcdcfm",
        "RecordTags": [],
        "Status": "CREATED",
        "ProvisionedProductType": "CFN_STACK"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ProvisionProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/provision-product.html)」を参照してください。

### `reject-portfolio-share`
<a name="service-catalog_RejectPortfolioShare_cli_2_topic"></a>

次のコード例は、`reject-portfolio-share` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオの共有を拒否するには**  
次の `reject-portfolio-share` の例では、特定のポートフォリオのポートフォリオ共有を拒否します。  

```
aws servicecatalog reject-portfolio-share \
    --portfolio-id port-2s6wuabcdefghijk
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RejectPortfolioShare](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/reject-portfolio-share.html)」を参照してください。

### `scan-provisioned-products`
<a name="service-catalog_ScanProvisionedProducts_cli_2_topic"></a>

次のコード例は、`scan-provisioned-products` を使用する方法を示しています。

**AWS CLI**  
**使用可能なすべてのプロビジョニング済み製品を一覧表示するには**  
次の `scan-provisioned-products` の例では、使用可能なプロビジョニング済み製品を一覧表示します。  

```
aws servicecatalog scan-provisioned-products
```
出力:  

```
{
    "ProvisionedProducts": [
        {
            "Status": "ERROR",
            "Arn": "arn:aws:servicecatalog:us-west-2:123456789012:stack/mytestppname3/pp-abcd27bm4mldq",
            "StatusMessage": "AmazonCloudFormationException  Parameters: [KeyName] must have values (Service: AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: 5528602a-a9ef-427c-825c-f82c31b814f5)",
            "Id": "pp-abcd27bm4mldq",
            "Type": "CFN_STACK",
            "IdempotencyToken": "527c5358-2a1a-4b9e-b1b9-7293b0ddff42",
            "CreatedTime": 1577222793.358,
            "Name": "mytestppname3",
            "LastRecordId": "rec-tfuawdabcdxge"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ScanProvisionedProducts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/scan-provisioned-products.html)」を参照してください。

### `search-products-as-admin`
<a name="service-catalog_SearchProductsAsAdmin_cli_2_topic"></a>

次のコード例は、`search-products-as-admin` を使用する方法を示しています。

**AWS CLI**  
**管理者権限で製品を検索するには**  
次の `search-products-as-admin` の例では、ポートフォリオ ID をフィルターとして使用して、管理者権限で製品を検索します。  

```
aws servicecatalog search-products-as-admin \
    --portfolio-id port-5abcd3e5st4ei
```
出力:  

```
{
    "ProductViewDetails": [
        {
            "ProductViewSummary": {
                "Name": "my product",
                "Owner": "owner name",
                "Type": "CLOUD_FORMATION_TEMPLATE",
                "ProductId": "prod-abcdfz3syn2rg",
                "HasDefaultPath": false,
                "Id": "prodview-abcdmyuzv2dlu",
                "ShortDescription": "description"
            },
            "ProductARN": "arn:aws:catalog:us-west-2:123456789012:product/prod-abcdfz3syn2rg",
            "CreatedTime": 1562097906.0,
            "Status": "CREATED"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchProductsAsAdmin](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/search-products-as-admin.html)」を参照してください。

### `search-provisioned-products`
<a name="service-catalog_SearchProvisionedProducts_cli_2_topic"></a>

次のコード例は、`search-provisioned-products` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニング済み製品を検索するには**  
次の `search-provisioned-products` の例では、JSON ファイルを使用してパラメータを渡すことで、指定された製品 ID に一致するプロビジョニング済み製品を検索します。  

```
aws servicecatalog search-provisioned-products \
    --cli-input-json file://search-provisioned-products-input.json
```
`search-provisioned-products-input.json` の内容:  

```
{
    "Filters": {
        "SearchQuery": [
            "prod-tcjvfz3syn2rg"
        ]
    }
}
```
出力:  

```
{
    "ProvisionedProducts": [
        {
            "ProvisioningArtifactId": "pa-pcz347abcdcfm",
            "Name": "mytestppname3",
            "CreatedTime": 1577222793.358,
            "Id": "pp-abcd27bm4mldq",
            "Status": "ERROR",
            "UserArn": "arn:aws:iam::123456789012:user/cliuser",
            "StatusMessage": "AmazonCloudFormationException  Parameters: [KeyName] must have values (Service: AmazonCloudFormation; Status Code: 400; Error Code: ValidationError; Request ID: 5528602a-a9ef-427c-825c-f82c31b814f5)",
            "Arn": "arn:aws:servicecatalog:us-west-2:123456789012:stack/mytestppname3/pp-abcd27bm4mldq",
            "Tags": [
                {
                    "Value": "arn:aws:catalog:us-west-2:123456789012:product/prod-abcdfz3syn2rg",
                    "Key": "aws:servicecatalog:productArn"
                },
                {
                    "Value": "arn:aws:iam::123456789012:user/cliuser",
                    "Key": "aws:servicecatalog:provisioningPrincipalArn"
                },
                {
                    "Value": "value-3",
                    "Key": "1234"
                },
                {
                    "Value": "pa-pcz347abcdcfm",
                    "Key": "aws:servicecatalog:provisioningArtifactIdentifier"
                },
                {
                    "Value": "arn:aws:catalog:us-west-2:123456789012:portfolio/port-2s6abcdq5wdh4",
                    "Key": "aws:servicecatalog:portfolioArn"
                },
                {
                    "Value": "arn:aws:servicecatalog:us-west-2:123456789012:stack/mytestppname3/pp-abcd27bm4mldq",
                    "Key": "aws:servicecatalog:provisionedProductArn"
                }
            ],
            "IdempotencyToken": "527c5358-2a1a-4b9e-b1b9-7293b0ddff42",
            "UserArnSession": "arn:aws:iam::123456789012:user/cliuser",
            "Type": "CFN_STACK",
            "LastRecordId": "rec-tfuawdabcdxge",
            "ProductId": "prod-abcdfz3syn2rg"
        }
    ],
    "TotalResultsCount": 1
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SearchProvisionedProducts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/search-provisioned-products.html)」を参照してください。

### `update-portfolio`
<a name="service-catalog_UpdatePortfolio_cli_2_topic"></a>

次のコード例は、`update-portfolio` を使用する方法を示しています。

**AWS CLI**  
**ポートフォリオを更新するには**  
次の `update-portfolio` の例では、指定されたポートフォリオの名前を更新します。  

```
aws servicecatalog update-portfolio \
    --id port-5abcd3e5st4ei \
    --display-name "New portfolio name"
```
出力:  

```
{
    "PortfolioDetail": {
        "DisplayName": "New portfolio name",
        "ProviderName": "provider",
        "ARN": "arn:aws:catalog:us-west-2:123456789012:portfolio/port-5abcd3e5st4ei",
        "Id": "port-5abcd3e5st4ei",
        "CreatedTime": 1559665256.348
    },
    "Tags": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePortfolio](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/update-portfolio.html)」を参照してください。

### `update-product`
<a name="service-catalog_UpdateProduct_cli_2_topic"></a>

次のコード例は、`update-product` を使用する方法を示しています。

**AWS CLI**  
**製品を更新するには**  
次の `update-product` の例では、指定された製品の名前と所有者を更新します。  

```
aws servicecatalog update-product \
    --id prod-os6abc7drqlt2 \
    --name "New product name" \
    --owner "Updated product owner"
```
出力:  

```
{
    "Tags": [
        {
            "Value": "iad",
            "Key": "region"
        }
    ],
    "ProductViewDetail": {
        "ProductViewSummary": {
            "Owner": "Updated product owner",
            "ProductId": "prod-os6abc7drqlt2",
            "Distributor": "test-distributor",
            "SupportUrl": "https://aws.amazon.com",
            "Name": "New product name",
            "ShortDescription": "test-description",
            "HasDefaultPath": false,
            "Id": "prodview-6abcdgrfhvidy",
            "SupportDescription": "test-support",
            "SupportEmail": "test@amazon.com",
            "Type": "CLOUD_FORMATION_TEMPLATE"
        },
        "Status": "CREATED",
        "ProductARN": "arn:aws:catalog:us-west-2:123456789012:product/prod-os6abc7drqlt2",
        "CreatedTime": 1577136255.0
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateProduct](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/update-product.html)」を参照してください。

### `update-provisioning-artifact`
<a name="service-catalog_UpdateProvisioningArtifact_cli_2_topic"></a>

次のコード例は、`update-provisioning-artifact` を使用する方法を示しています。

**AWS CLI**  
**プロビジョニングアーティファクトを更新するには**  
次の `update-provisioning-artifact` の例では、JSON ファイルを使用してパラメータを渡すことで、指定されたプロビジョニングアーティファクトの名前と説明を更新します。  

```
aws servicecatalog update-provisioning-artifact \
    --cli-input-json file://update-provisioning-artifact-input.json
```
`update-provisioning-artifact-input.json` の内容:  

```
{
    "ProductId": "prod-abcdfz3syn2rg",
    "ProvisioningArtifactId": "pa-pcz347abcdcfm",
    "Name": "updated name",
    "Description": "updated description"
}
```
出力:  

```
{
    "Info": {
        "TemplateUrl": "https://awsdocs.s3.amazonaws.com/servicecatalog/myexampledevelopment-environment.template"
    },
    "Status": "AVAILABLE",
    "ProvisioningArtifactDetail": {
        "Active": true,
        "Description": "updated description",
        "Id": "pa-pcz347abcdcfm",
        "Name": "updated name",
        "Type": "CLOUD_FORMATION_TEMPLATE",
        "CreatedTime": 1562097906.0
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateProvisioningArtifact](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/update-provisioning-artifact.html)」を参照してください。

### `update-tag-option`
<a name="service-catalog_UpdateTagOption_cli_2_topic"></a>

次のコード例は、`update-tag-option` を使用する方法を示しています。

**AWS CLI**  
**TagOption を更新するには**  
次の `update-tag-option` の例では、指定された JSON ファイルを使用して `TagOption` の値を更新します。  

```
aws servicecatalog update-tag-option --cli-input-json file://update-tag-option-input.json
```
`update-tag-option-input.json` の内容:  

```
{
    "Id": "tag-iabcdn4fzjjms",
    "Value": "newvalue",
    "Active": true
}
```
出力:  

```
{
    "TagOptionDetail": {
        "Value": "newvalue",
        "Key": "1234",
        "Active": true,
        "Id": "tag-iabcdn4fzjjms"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateTagOption](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/servicecatalog/update-tag-option.html)」を参照してください。

# を使用した Service Quotas の例 AWS CLI
<a name="cli_2_service-quotas_code_examples"></a>

次のコード例は、Service Quotas AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-aws-default-service-quota`
<a name="service-quotas_GetAwsDefaultServiceQuota_cli_2_topic"></a>

次のコード例は、`get-aws-default-service-quota` を使用する方法を示しています。

**AWS CLI**  
**デフォルトのサービスクォータの説明を表示するには**  
次の `get-aws-default-service-quota` の例では、指定されたクォータの詳細情報を表示します。  

```
aws service-quotas get-aws-default-service-quota \
    --service-code ec2 \
    --quota-code L-1216C47A
```
出力:  

```
{
    "Quota": {
        "ServiceCode": "ec2",
        "ServiceName": "Amazon Elastic Compute Cloud (Amazon EC2)",
        "QuotaArn": "arn:aws:servicequotas:us-east-2::ec2/L-1216C47A",
        "QuotaCode": "L-1216C47A",
        "QuotaName": "Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances",
        "Value": 5.0,
        "Unit": "None",
        "Adjustable": true,
        "GlobalQuota": false,
        "UsageMetric": {
            "MetricNamespace": "AWS/Usage",
            "MetricName": "ResourceCount",
            "MetricDimensions": {
                "Class": "Standard/OnDemand",
                "Resource": "vCPU",
                "Service": "EC2",
                "Type": "Resource"
            },
            "MetricStatisticRecommendation": "Maximum"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAwsDefaultServiceQuota](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/get-aws-default-service-quota.html)」を参照してください。

### `get-requested-service-quota-change`
<a name="service-quotas_GetRequestedServiceQuotaChange_cli_2_topic"></a>

次のコード例は、`get-requested-service-quota-change` を使用する方法を示しています。

**AWS CLI**  
**サービスクォータ引き上げリクエストの説明を表示するには**  
次の `get-requested-service-quota-change` の例では、指定されたクォータ引き上げリクエストの説明を表示します。  

```
aws service-quotas get-requested-service-quota-change \
    --request-id d187537d15254312a9609aa51bbf7624u7W49tPO
```
出力:  

```
{
    "RequestedQuota": {
        "Id": "d187537d15254312a9609aa51bbf7624u7W49tPO",
        "CaseId": "6780195351",
        "ServiceCode": "ec2",
        "ServiceName": "Amazon Elastic Compute Cloud (Amazon EC2)",
        "QuotaCode": "L-20F13EBD",
        "QuotaName": "Running Dedicated c5n Hosts",
        "DesiredValue": 2.0,
        "Status": "CASE_OPENED",
        "Created": 1580446904.067,
        "LastUpdated": 1580446953.265,
        "Requester": "{\"accountId\":\"123456789012\",\"callerArn\":\"arn:aws:iam::123456789012:root\"}",
        "QuotaArn": "arn:aws:servicequotas:us-east-2:123456789012:ec2/L-20F13EBD",
        "GlobalQuota": false,
        "Unit": "None"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRequestedServiceQuotaChange](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/get-requested-service-quota-change.html)」を参照してください。

### `get-service-quota`
<a name="service-quotas_GetServiceQuota_cli_2_topic"></a>

次のコード例は、`get-service-quota` を使用する方法を示しています。

**AWS CLI**  
**サービスクォータの説明を表示するには**  
次の `get-service-quota` の例では、指定されたクォータの詳細情報を表示します。  

```
aws service-quotas get-service-quota \
    --service-code ec2 \
    --quota-code L-1216C47A
```
出力:  

```
{
    "Quota": {
        "ServiceCode": "ec2",
        "ServiceName": "Amazon Elastic Compute Cloud (Amazon EC2)",
        "QuotaArn": "arn:aws:servicequotas:us-east-2:123456789012:ec2/L-1216C47A",
        "QuotaCode": "L-1216C47A",
        "QuotaName": "Running On-Demand Standard (A, C, D, H, I, M, R, T, Z) instances",
        "Value": 1920.0,
        "Unit": "None",
        "Adjustable": true,
        "GlobalQuota": false,
        "UsageMetric": {
            "MetricNamespace": "AWS/Usage",
            "MetricName": "ResourceCount",
            "MetricDimensions": {
                "Class": "Standard/OnDemand",
                "Resource": "vCPU",
                "Service": "EC2",
                "Type": "Resource"
            },
            "MetricStatisticRecommendation": "Maximum"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceQuota](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/get-service-quota.html)」を参照してください。

### `list-aws-default-service-quotas`
<a name="service-quotas_ListAwsDefaultServiceQuotas_cli_2_topic"></a>

次のコード例は、`list-aws-default-service-quotas` を使用する方法を示しています。

**AWS CLI**  
**サービスのデフォルトのクォータを一覧表示するには**  
次の `list-aws-default-service-quotas` の例では、指定されたサービスのクォータのデフォルト値を一覧表示します。  

```
aws service-quotas list-aws-default-service-quotas \
    --service-code xray
```
出力:  

```
{
    "Quotas": [
        {
            "ServiceCode": "xray",
            "ServiceName": "AWS X-Ray",
            "QuotaArn": "arn:aws:servicequotas:us-west-2::xray/L-C6B6F05D",
            "QuotaCode": "L-C6B6F05D",
            "QuotaName": "Indexed annotations per trace",
            "Value": 50.0,
            "Unit": "None",
            "Adjustable": false,
            "GlobalQuota": false
        },
        {
            "ServiceCode": "xray",
            "ServiceName": "AWS X-Ray",
            "QuotaArn": "arn:aws:servicequotas:us-west-2::xray/L-D781C0FD",
            "QuotaCode": "L-D781C0FD",
            "QuotaName": "Segment document size",
            "Value": 64.0,
            "Unit": "Kilobytes",
            "Adjustable": false,
            "GlobalQuota": false
        },
        {
            "ServiceCode": "xray",
            "ServiceName": "AWS X-Ray",
            "QuotaArn": "arn:aws:servicequotas:us-west-2::xray/L-998BFF16",
            "QuotaCode": "L-998BFF16",
            "QuotaName": "Trace and service graph retention in days",
            "Value": 30.0,
            "Unit": "None",
            "Adjustable": false,
            "GlobalQuota": false
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAwsDefaultServiceQuotas](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/list-aws-default-service-quotas.html)」を参照してください。

### `list-requested-service-quota-change-history-by-quota`
<a name="service-quotas_ListRequestedServiceQuotaChangeHistoryByQuota_cli_2_topic"></a>

次のコード例は、`list-requested-service-quota-change-history-by-quota` を使用する方法を示しています。

**AWS CLI**  
**クォータ引き上げリクエストを一覧表示するには**  
次の `list-requested-service-quota-change-history-by-quota` の例では、指定されたクォータのクォータ引き上げリクエストを一覧示します。  

```
aws service-quotas list-requested-service-quota-change-history-by-quota \
    --service-code ec2 \
    --quota-code L-20F13EBD
```
出力:  

```
{
    "RequestedQuotas": [
        {
            "Id": "d187537d15254312a9609aa51bbf7624u7W49tPO",
            "CaseId": "6780195351",
            "ServiceCode": "ec2",
            "ServiceName": "Amazon Elastic Compute Cloud (Amazon EC2)",
            "QuotaCode": "L-20F13EBD",
            "QuotaName": "Running Dedicated c5n Hosts",
            "DesiredValue": 2.0,
            "Status": "CASE_OPENED",
            "Created": 1580446904.067,
            "LastUpdated": 1580446953.265,
            "Requester": "{\"accountId\":\"123456789012\",\"callerArn\":\"arn:aws:iam::123456789012:root\"}",
            "QuotaArn": "arn:aws:servicequotas:us-east-2:123456789012:ec2/L-20F13EBD",
            "GlobalQuota": false,
            "Unit": "None"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRequestedServiceQuotaChangeHistoryByQuota](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/list-requested-service-quota-change-history-by-quota.html)」を参照してください。

### `list-requested-service-quota-change-history`
<a name="service-quotas_ListRequestedServiceQuotaChangeHistory_cli_2_topic"></a>

次のコード例は、`list-requested-service-quota-change-history` を使用する方法を示しています。

**AWS CLI**  
**クォータ引き上げリクエストを一覧表示するには**  
次の `list-requested-service-quota-change-history` の例では、指定されたサービスのクォータ引き上げリクエストを一覧示します。  

```
aws service-quotas list-requested-service-quota-change-history \
    --service-code ec2
```
出力:  

```
{
    "RequestedQuotas": [
        {
            "Id": "d187537d15254312a9609aa51bbf7624u7W49tPO",
            "CaseId": "6780195351",
            "ServiceCode": "ec2",
            "ServiceName": "Amazon Elastic Compute Cloud (Amazon EC2)",
            "QuotaCode": "L-20F13EBD",
            "QuotaName": "Running Dedicated c5n Hosts",
            "DesiredValue": 2.0,
            "Status": "CASE_OPENED",
            "Created": 1580446904.067,
            "LastUpdated": 1580446953.265,
            "Requester": "{\"accountId\":\"123456789012\",\"callerArn\":\"arn:aws:iam::123456789012:root\"}",
            "QuotaArn": "arn:aws:servicequotas:us-east-2:123456789012:ec2/L-20F13EBD",
            "GlobalQuota": false,
            "Unit": "None"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRequestedServiceQuotaChangeHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/list-requested-service-quota-change-history.html)」を参照してください。

### `list-service-quotas`
<a name="service-quotas_ListServiceQuotas_cli_2_topic"></a>

次のコード例は、`list-service-quotas` を使用する方法を示しています。

**AWS CLI**  
**サービスのクォータを一覧表示するには**  
次の の`list-service-quotas`例では、 AWS CloudFormation のクォータの詳細を表示します。  

```
aws service-quotas list-service-quotas \
    --service-code cloudformation
```
出力:  

```
{
    "Quotas": [
        {
            "ServiceCode": "cloudformation",
            "ServiceName": "AWS CloudFormation",
            "QuotaArn": "arn:aws:servicequotas:us-east-2:123456789012:cloudformation/L-87D14FB7",
            "QuotaCode": "L-87D14FB7",
            "QuotaName": "Output count in CloudFormation template",
            "Value": 60.0,
            "Unit": "None",
            "Adjustable": false,
            "GlobalQuota": false
        },
        {
            "ServiceCode": "cloudformation",
            "ServiceName": "AWS CloudFormation",
            "QuotaArn": "arn:aws:servicequotas:us-east-2:123456789012:cloudformation/L-0485CB21",
            "QuotaCode": "L-0485CB21",
            "QuotaName": "Stack count",
            "Value": 200.0,
            "Unit": "None",
            "Adjustable": true,
            "GlobalQuota": false
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceQuotas](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/list-service-quotas.html)」を参照してください。

### `list-services`
<a name="service-quotas_ListServices_cli_2_topic"></a>

次のコード例は、`list-services` を使用する方法を示しています。

**AWS CLI**  
**使用可能なサービスを一覧表示するには**  
次のコマンドは、Service Quotas で使用可能なサービスを一覧表示します。  

```
aws service-quotas list-services
```
出力:  

```
{
    "Services": [
        {
            "ServiceCode": "AWSCloudMap",
            "ServiceName": "AWS Cloud Map"
        },
        {
            "ServiceCode": "access-analyzer",
            "ServiceName": "Access Analyzer"
        },
        {
            "ServiceCode": "acm",
            "ServiceName": "AWS Certificate Manager (ACM)"
        },

        ...truncated...

        {
            "ServiceCode": "xray",
            "ServiceName": "AWS X-Ray"
        }
    ]
}
```
`--query` パラメータを追加して、関心のある情報に表示を絞り込むことができます。次の例では、サービスコードのみを表示します。  

```
aws service-quotas list-services \
    --query Services[*].ServiceCode
```
出力:  

```
[
    "AWSCloudMap",
    "access-analyzer",
    "acm",
    "acm-pca",
    "amplify",
    "apigateway",
    "application-autoscaling",
        ...truncated...
    "xray"
]
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/list-services.html)」を参照してください。

### `request-service-quota-increase`
<a name="service-quotas_RequestServiceQuotaIncrease_cli_2_topic"></a>

次のコード例は、`request-service-quota-increase` を使用する方法を示しています。

**AWS CLI**  
**サービスクォータ引き上げをリクエストするには**  
次の `request-service-quota-increase` の例では、指定されたサービスクォータの引き上げをリクエストします。  

```
aws service-quotas request-service-quota-increase \
    --service-code ec2 \
    --quota-code L-20F13EBD \
    --desired-value 2
```
出力:  

```
{
    "RequestedQuota": {
        "Id": "d187537d15254312a9609aa51bbf7624u7W49tPO",
        "ServiceCode": "ec2",
        "ServiceName": "Amazon Elastic Compute Cloud (Amazon EC2)",
        "QuotaCode": "L-20F13EBD",
        "QuotaName": "Running Dedicated c5n Hosts",
        "DesiredValue": 2.0,
        "Status": "PENDING",
        "Created": 1580446904.067,
        "Requester": "{\"accountId\":\"123456789012\",\"callerArn\":\"arn:aws:iam::123456789012:root\"}",
        "QuotaArn": "arn:aws:servicequotas:us-east-2:123456789012:ec2/L-20F13EBD",
        "GlobalQuota": false,
        "Unit": "None"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RequestServiceQuotaIncrease](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/service-quotas/request-service-quota-increase.html)」を参照してください。

# を使用した Amazon SES の例 AWS CLI
<a name="cli_2_ses_code_examples"></a>

次のコード例は、Amazon SES AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `delete-identity`
<a name="ses_DeleteIdentity_cli_2_topic"></a>

次のコード例は、`delete-identity` を使用する方法を示しています。

**AWS CLI**  
**ID を削除するには**  
次の例では、`delete-identity` コマンドを使用して Amazon SES で検証された ID のリストから ID を削除します。  

```
aws ses delete-identity --identity user@example.com
```
検証済み ID の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES での E メールアドレスとドメインの検証」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/delete-identity.html)」を参照してください。

### `get-identity-dkim-attributes`
<a name="ses_GetIdentityDkimAttributes_cli_2_topic"></a>

次のコード例は、`get-identity-dkim-attributes` を使用する方法を示しています。

**AWS CLI**  
**ID のリストの Amazon SES Easy DKIM 属性を取得するには**  
次の例では、`get-identity-dkim-attributes` コマンドを使用して ID リストの Amazon SES Easy DKIM 属性を取得します。  

```
aws ses get-identity-dkim-attributes --identities "example.com" "user@example.com"
```
出力:  

```
{
   "DkimAttributes": {
       "example.com": {
           "DkimTokens": [
               "EXAMPLEjcs5xoyqytjsotsijas7236gr",
               "EXAMPLEjr76cvoc6mysspnioorxsn6ep",
               "EXAMPLEkbmkqkhlm2lyz77ppkulerm4k"
           ],
           "DkimEnabled": true,
           "DkimVerificationStatus": "Success"
       },
       "user@example.com": {
           "DkimEnabled": false,
           "DkimVerificationStatus": "NotStarted"
       }
   }
}
```
検証のために、送信したことがない ID を使用してこのコマンドを呼び出した場合、その ID は出力に表示されません。  
Easy DKIM の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Easy DKIM in Amazon SES」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIdentityDkimAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/get-identity-dkim-attributes.html)」を参照してください。

### `get-identity-notification-attributes`
<a name="ses_GetIdentityNotificationAttributes_cli_2_topic"></a>

次のコード例は、`get-identity-notification-attributes` を使用する方法を示しています。

**AWS CLI**  
**ID リストの Amazon SES 通知属性を取得するには**  
次の例では、`get-identity-notification-attributes` コマンドを使用して ID リストの Amazon SES 通知属性を取得します。  

```
aws ses get-identity-notification-attributes --identities "user1@example.com" "user2@example.com"
```
出力:  

```
{
   "NotificationAttributes": {
       "user1@example.com": {
           "ForwardingEnabled": false,
           "ComplaintTopic": "arn:aws:sns:us-east-1:EXAMPLE65304:MyTopic",
           "BounceTopic": "arn:aws:sns:us-east-1:EXAMPLE65304:MyTopic",
           "DeliveryTopic": "arn:aws:sns:us-east-1:EXAMPLE65304:MyTopic"
       },
       "user2@example.com": {
           "ForwardingEnabled": true
       }
   }
}
```
このコマンドは、E メールフィードバック転送のステータスと、該当する場合は、バウンス、苦情、配信通知が送信される Amazon SNS トピックの Amazon リソースネーム (ARN) を返します。  
検証のために、送信したことがない ID を使用してこのコマンドを呼び出した場合、その ID は出力に表示されません。  
通知の詳細については、「Amazon Simple Email Service デベロッパーガイド」の「*Amazon SES で通知を使用する*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIdentityNotificationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/get-identity-notification-attributes.html)」を参照してください。

### `get-identity-verification-attributes`
<a name="ses_GetIdentityVerificationAttributes_cli_2_topic"></a>

次のコード例は、`get-identity-verification-attributes` を使用する方法を示しています。

**AWS CLI**  
**ID リストの Amazon SES 検証ステータスを取得するには**  
次の例では、`get-identity-verification-attributes` コマンドを使用して ID リストの Amazon SES 検証ステータスを取得します。  

```
aws ses get-identity-verification-attributes --identities "user1@example.com" "user2@example.com"
```
出力:  

```
{
   "VerificationAttributes": {
       "user1@example.com": {
           "VerificationStatus": "Success"
       },
       "user2@example.com": {
           "VerificationStatus": "Pending"
       }
   }
}
```
検証のために、送信したことがない ID を使用してこのコマンドを呼び出した場合、その ID は出力に表示されません。  
検証済み ID の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES での E メールアドレスとドメインの検証」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIdentityVerificationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/get-identity-verification-attributes.html)」を参照してください。

### `get-send-quota`
<a name="ses_GetSendQuota_cli_2_topic"></a>

次のコード例は、`get-send-quota` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES 送信制限を取得するには**  
次の例では、`get-send-quota` コマンドを使用して Amazon SES の送信制限を返します。  

```
aws ses get-send-quota
```
出力:  

```
{
   "Max24HourSend": 200.0,
   "SentLast24Hours": 1.0,
   "MaxSendRate": 1.0
}
```
Max24HourSend は送信クォータで、24 時間あたりに送信できる E メールの最大数です。送信クォータには、期間の推移が反映されます。E メールを送信しようとするたびに、Amazon SES は直近 24 時間内に送信された E メールの件数をチェックします。送信済みのメールの合計数がクォータ未満であれば、送信リクエストは受理され、E メールが送信されます。  
SentLast24Hours は、過去 24 時間以内に送信した E メールの数です。  
MaxSendRate は、1 秒あたりに送信できる E メールの最大数です。  
送信制限は、メッセージ数ではなく、受取人数に基づいていることに注意してください。例えば、受取人数が 10 人である E メールは、送信クォータに対しては 10 通とカウントされます。  
詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES 送信制限の管理」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSendQuota](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/get-send-quota.html)」を参照してください。

### `get-send-statistics`
<a name="ses_GetSendStatistics_cli_2_topic"></a>

次のコード例は、`get-send-statistics` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES 統計の送信を取得するには**  
次の例では、`get-send-statistics` コマンドを使用して Amazon SES の統計の送信を返します。  

```
aws ses get-send-statistics
```
出力:  

```
{
   "SendDataPoints": [
       {
           "Complaints": 0,
           "Timestamp": "2013-06-12T19:32:00Z",
           "DeliveryAttempts": 2,
           "Bounces": 0,
           "Rejects": 0
       },
       {
           "Complaints": 0,
           "Timestamp": "2013-06-12T00:47:00Z",
           "DeliveryAttempts": 1,
           "Bounces": 0,
           "Rejects": 0
       }
   ]
}
```
結果は、送信アクティビティの最新の 2 週間を示すデータポイントのリストです。このリスト内の各データポイントには、15 分間隔の統計が含まれます。  
この例では、過去 2 週間にユーザーが送信した E メールが 15 分間隔で 2 件のみだったため、データポイントは 2 つしかありません。  
詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES 使用状況統計のモニタリング」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSendStatistics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/get-send-statistics.html)」を参照してください。

### `list-identities`
<a name="ses_ListIdentities_cli_2_topic"></a>

次の例は、`list-identities` を使用する方法を説明しています。

**AWS CLI**  
**特定の AWS アカウントのすべての ID (E メールアドレスとドメイン) を一覧表示するには**  
次の例では、`list-identities` コマンドを使用して、Amazon SES で検証のために送信されたすべての ID を一覧表示します。  

```
aws ses list-identities
```
出力:  

```
{
    "Identities": [
      "user@example.com",
      "example.com"
    ]
}
```
返されるリストには、検証ステータス (検証済み、検証保留中、失敗など) に関係なく、すべての ID が含まれます。  
この例では、identity-type パラメータを指定しなかったため、E メールアドレス*および*ドメインが返されます。  
検証の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES での E メールアドレスとドメインの検証」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIdentities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/list-identities.html)」を参照してください。

### `send-email`
<a name="ses_SendEmail_cli_2_topic"></a>

次のコード例は、`send-email` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES を使用してフォーマット済み E メールを送信するには**  
以下の例では、`send-email` コマンドを使用してフォーマットされた E メールを送信しています。  

```
aws ses send-email --from sender@example.com --destination file://destination.json --message file://message.json
```
出力:  

```
{
   "MessageId": "EXAMPLEf3a5efcd1-51adec81-d2a4-4e3f-9fe2-5d85c1b23783-000000"
}
```
送信先とメッセージは、現在のディレクトリで.json ファイルに保存される JSON データ構造です。これらのファイルは以下のとおりです。  
`destination.json`:  

```
{
  "ToAddresses":  ["recipient1@example.com", "recipient2@example.com"],
  "CcAddresses":  ["recipient3@example.com"],
  "BccAddresses": []
}
```
`message.json`:  

```
{
   "Subject": {
       "Data": "Test email sent using the AWS CLI",
       "Charset": "UTF-8"
   },
   "Body": {
       "Text": {
           "Data": "This is the message body in text format.",
           "Charset": "UTF-8"
       },
       "Html": {
           "Data": "This message body contains HTML formatting. It can, for example, contain links like this one: <a class=\"ulink\" href=\"http://docs.aws.amazon.com/ses/latest/DeveloperGuide\" target=\"_blank\">Amazon SES Developer Guide</a>.",
           "Charset": "UTF-8"
       }
   }
}
```
送信者と受信者の E メールアドレスを、使用したい E メールアドレスに置き換えます。送信者の E メールアドレスは、Amazon SES で検証される必要があることに注意してください。Amazon SES への本稼働アクセスが許可されるまでは、受信者が Amazon SES メールボックスシミュレーターでない限り、各受信者の E メールアドレスも検証する必要があります。検証の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES での E メールアドレスとドメインの検証」を参照してください。  
出力のメッセージ ID は、send-email の呼び出しが成功したことを示しています。  
E メールが届かない場合は、迷惑メールフォルダを確認してください。  
フォーマット済み E メールの送信の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES API を使用してフォーマット済み E メールを送信する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendEmail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/send-email.html)」を参照してください。

### `send-raw-email`
<a name="ses_SendRawEmail_cli_2_topic"></a>

次のコード例は、`send-raw-email` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES を使用して raw E メールを送信するには**  
以下の例では、`send-raw-email` コマンドを使用して TXT 添付ファイルを含む E メールを送信しています。  

```
aws ses send-raw-email --raw-message file://message.json
```
出力:  

```
{
   "MessageId": "EXAMPLEf3f73d99b-c63fb06f-d263-41f8-a0fb-d0dc67d56c07-000000"
}
```
raw メッセージは、現在のディレクトリで `message.json` という名前のファイルに保存される JSON データ構造です。以下の要素が含まれます。  

```
{
   "Data": "From: sender@example.com\nTo: recipient@example.com\nSubject: Test email sent using the AWS CLI (contains an attachment)\nMIME-Version: 1.0\nContent-type: Multipart/Mixed; boundary=\"NextPart\"\n\n--NextPart\nContent-Type: text/plain\n\nThis is the message body.\n\n--NextPart\nContent-Type: text/plain;\nContent-Disposition: attachment; filename=\"attachment.txt\"\n\nThis is the text in the attachment.\n\n--NextPart--"
}
```
おわかりのように、「Data」は attachment.txt という添付ファイルを含む、MIME 形式の raw E メールコンテンツ全体が含まれた 1 つの長い文字列です。  
sender@example.com と recipient@example.com は、使用するアドレスに置き換えてください。送信者の E メールアドレスは、Amazon SES で検証される必要があることに注意してください。Amazon SES への本稼働アクセスが許可されるまでは、受信者が Amazon SES メールボックスシミュレーターである場合を除き、受信者の E メールアドレスも検証する必要があります。検証の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES での E メールアドレスとドメインの検証」を参照してください。  
出力のメッセージ ID は、send-raw-email の呼び出しが成功したことを示しています。  
E メールが届かない場合は、迷惑メールフォルダを確認してください。  
raw E メールの送信の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Sending raw email using the Amazon SES API」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendRawEmail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/send-raw-email.html)」を参照してください。

### `set-identity-dkim-enabled`
<a name="ses_SetIdentityDkimEnabled_cli_2_topic"></a>

次のコード例は、`set-identity-dkim-enabled` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES 検証済み ID の Easy DKIM を有効または無効にするには**  
次の例では、`set-identity-dkim-enabled` コマンドを使用して検証済み E メールアドレスの DKIM を無効にします。  

```
aws ses set-identity-dkim-enabled --identity user@example.com --no-dkim-enabled
```
Easy DKIM の詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Easy DKIM in Amazon SES」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetIdentityDkimEnabled](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/set-identity-dkim-enabled.html)」を参照してください。

### `set-identity-feedback-forwarding-enabled`
<a name="ses_SetIdentityFeedbackForwardingEnabled_cli_2_topic"></a>

次のコード例は、`set-identity-feedback-forwarding-enabled` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES 検証済み ID のバウンスと苦情の E メールフィードバック転送を有効または無効にするには**  
次の例では、`set-identity-feedback-forwarding-enabled` コマンドを使用して、検証済みの E メールアドレスが E メールでバウンスと苦情の通知を受信できるようにします。  

```
aws ses set-identity-feedback-forwarding-enabled --identity user@example.com --forwarding-enabled
```
Amazon SNS または E メールフィードバック転送を介してバウンス通知と苦情通知を受け取る必要があるため、バウンス通知と苦情通知の両方の Amazon SNS トピックを選択した場合のみ、E メールフィードバック転送を無効にすることができます。  
通知の詳細については、「Amazon Simple Email Service デベロッパーガイド」の「*Amazon SES で通知を使用する*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetIdentityFeedbackForwardingEnabled](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/set-identity-feedback-forwarding-enabled.html)」を参照してください。

### `set-identity-notification-topic`
<a name="ses_SetIdentityNotificationTopic_cli_2_topic"></a>

次のコード例は、`set-identity-notification-topic` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES が検証済み ID のバウンス、苦情、配信通知を発行する Amazon SES トピックを設定するには**  
次の例では、`set-identity-notification-topic` コマンドを使用して、検証済みの E メールアドレスがバウンス通知を受信する Amazon SNS トピックを指定します。  

```
aws ses set-identity-notification-topic --identity user@example.com --notification-type Bounce --sns-topic arn:aws:sns:us-east-1:EXAMPLE65304:MyTopic
```
通知の詳細については、「Amazon Simple Email Service デベロッパーガイド」の「*Amazon SES で通知を使用する*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetIdentityNotificationTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/set-identity-notification-topic.html)」を参照してください。

### `verify-domain-dkim`
<a name="ses_VerifyDomainDkim_cli_2_topic"></a>

次のコード例は、`verify-domain-dkim` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES を使用した DKIM 署名の検証済みドメインの DKIM トークンを生成するには**  
次の例では、`verify-domain-dkim` コマンドを使用して、Amazon SES で検証されたドメインの DKIM トークンを生成します。  

```
aws ses verify-domain-dkim --domain example.com
```
出力:  

```
{
   "DkimTokens": [
       "EXAMPLEq76owjnks3lnluwg65scbemvw",
       "EXAMPLEi3dnsj67hstzaj673klariwx2",
       "EXAMPLEwfbtcukvimehexktmdtaz6naj"
   ]
}
```
DKIM を設定するには、返された DKIM トークンを使用して、Amazon SES がホストする DKIM パブリックキーを指す CNAME レコードでドメインの DNS 設定を更新する必要があります。詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Easy DKIM in Amazon SES」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyDomainDkim](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/verify-domain-dkim.html)」を参照してください。

### `verify-domain-identity`
<a name="ses_VerifyDomainIdentity_cli_2_topic"></a>

次のコード例は、`verify-domain-identity` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES でドメインを検証するには**  
以下の例では、`verify-domain-identity` コマンドを使用してドメインを認証しています。  

```
aws ses verify-domain-identity --domain example.com
```
出力:  

```
{
   "VerificationToken": "eoEmxw+YaYhb3h3iVJHuXMJXqeu1q1/wwmvjuEXAMPLE"
}
```
ドメイン検証を完了するには、返された検証トークンと共に、TXT レコードをドメインの DNS 設定に追加する必要があります。詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES でのドメインの検証」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyDomainIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/verify-domain-identity.html)」を参照してください。

### `verify-email-identity`
<a name="ses_VerifyEmailIdentity_cli_2_topic"></a>

次のコード例は、`verify-email-identity` を使用する方法を示しています。

**AWS CLI**  
**Amazon SES で E メールアドレスを検証するには**  
以下の例では、`verify-email-identity` コマンドを使用して E メールアドレスを認証しています。  

```
aws ses verify-email-identity --email-address user@example.com
```
Amazon SES を使用してメールを送信する前に、E メールの送信元となるアドレスまたはドメインを所有していることを証明するために、そのアドレスまたはドメインを検証する必要があります。まだ本稼働アクセス権を持っていない場合は、Amazon SES メールボックスシミュレーターから提供された E メールアドレスを除いて、すべての送信先の E メールアドレスも検証する必要があります。  
verify-email-identity が呼び出されると、その E メールアドレスに検証 E メールが届きます。ユーザーは、E メールのリンクをクリックして、検証プロセスを完了する必要があります。  
詳細については、「*Amazon Simple Email Service デベロッパーガイド*」の「Amazon SES での E メールアドレスの検証」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[VerifyEmailIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ses/verify-email-identity.html)」を参照してください。

# を使用した Shield の例 AWS CLI
<a name="cli_2_shield_code_examples"></a>

次のコード例は、Shield AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-drt-log-bucket`
<a name="shield_AssociateDrtLogBucket_cli_2_topic"></a>

次のコード例は、`associate-drt-log-bucket` を使用する方法を示しています。

**AWS CLI**  
**Amazon S3 バケットへのアクセス許可を DRT に付与するには**  
次の `associate-drt-log-bucket` の例では、DRT と指定された S3 バケットの間に関連付けを作成します。これにより、DRT はアカウントに代わってバケットにアクセスできるようになります。  

```
aws shield associate-drt-log-bucket \
    --log-bucket flow-logs-for-website-lb
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[DDoS 対応チームの承認](https://docs.aws.amazon.com/waf/latest/developerguide/authorize-DRT.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateDrtLogBucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/associate-drt-log-bucket.html)」を参照してください。

### `associate-drt-role`
<a name="shield_AssociateDrtRole_cli_2_topic"></a>

次のコード例は、`associate-drt-role` を使用する方法を示しています。

**AWS CLI**  
**お客様に代わって攻撃を軽減する権限を DRT に付与するには**  
次の `associate-drt-role` の例では、DRT と指定されたロールの間に関連付けを作成します。DRT は、ロールを使用してアカウントへのアクセスやアカウント管理をすることができます。  

```
aws shield associate-drt-role \
    --role-arn arn:aws:iam::123456789012:role/service-role/DrtRole
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[DDoS 対応チームの承認](https://docs.aws.amazon.com/waf/latest/developerguide/authorize-DRT.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateDrtRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/associate-drt-role.html)」を参照してください。

### `create-protection`
<a name="shield_CreateProtection_cli_2_topic"></a>

次の例は、`create-protection` を使用する方法を説明しています。

**AWS CLI**  
**1 つの AWS リソースに対して AWS Shield Advanced 保護を有効にするには**  
次の の`create-protection`例では、指定された AWS CloudFront ディストリビューションの Shield Advanced 保護を有効にします。  

```
aws shield create-protection \
    --name "Protection for CloudFront distribution" \
    --resource-arn arn:aws:cloudfront::123456789012:distribution/E198WC25FXOWY8
```
出力:  

```
{
    "ProtectionId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
}
```
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[保護するリソースの指定](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-choose-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/create-protection.html)」を参照してください。

### `create-subscription`
<a name="shield_CreateSubscription_cli_2_topic"></a>

次の例は、`create-subscription` を使用する方法を説明しています。

**AWS CLI**  
**アカウントの AWS Shield Advanced 保護を有効にするには**  
次の `create-subscription` の例では、アカウントの Shield Advanced 保護を有効にします。  

```
aws shield create-subscription
```
このコマンドでは何も出力されません。  
詳細については、[Shield Advanced デベロッパーガイド AWS の](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started-ddos.html)「Shield Advanced の開始方法」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/create-subscription.html)」を参照してください。

### `delete-protection`
<a name="shield_DeleteProtection_cli_2_topic"></a>

次の例は、`delete-protection` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースから AWS Shield Advanced 保護を削除するには**  
次の の`delete-protection`例では、指定された Shield Advanced AWS 保護を削除します。  

```
aws shield delete-protection \
    --protection-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
このコマンドでは何も出力されません。  
詳細については、[「Shield Advanced デベロッパーガイド AWS 」の AWS 「リソースからの](https://docs.aws.amazon.com/waf/latest/developerguide/remove-protection.html) Shield Advanced の削除」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/delete-protection.html)」を参照してください。

### `describe-attack`
<a name="shield_DescribeAttack_cli_2_topic"></a>

次のコード例は、`describe-attack` を使用する方法を示しています。

**AWS CLI**  
**攻撃の詳細な説明を取得するには**  
次の `describe-attack` の例では、指定された攻撃 ID を持つ DDoS 攻撃の詳細情報を表示します。`list-attacks` コマンドを実行すると、攻撃 ID を取得できます。  

```
aws shield describe-attack --attack-id a1b2c3d4-5678-90ab-cdef-EXAMPLE22222
```
出力:  

```
{
    "Attack": {
        "AttackId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "ResourceArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/testElb",
        "SubResources": [
            {
                "Type": "IP",
                "Id": "192.0.2.2",
                "AttackVectors": [
                    {
                        "VectorType": "SYN_FLOOD",
                        "VectorCounters": [
                            {
                                "Name": "SYN_FLOOD_BPS",
                                "Max": 982184.0,
                                "Average": 982184.0,
                                "Sum": 11786208.0,
                                "N": 12,
                                "Unit": "BPS"
                            }
                        ]
                    }
                ],
                "Counters": []
            },
            {
                "Type": "IP",
                "Id": "192.0.2.3",
                "AttackVectors": [
                    {
                        "VectorType": "SYN_FLOOD",
                        "VectorCounters": [
                            {
                                "Name": "SYN_FLOOD_BPS",
                                "Max": 982184.0,
                                "Average": 982184.0,
                                "Sum": 9821840.0,
                                "N": 10,
                                "Unit": "BPS"
                            }
                        ]
                    }
                ],
                "Counters": []
            },
            {
                "Type": "IP",
                "Id": "192.0.2.4",
                "AttackVectors": [
                    {
                        "VectorType": "SYN_FLOOD",
                        "VectorCounters": [
                            {
                                "Name": "SYN_FLOOD_BPS",
                                "Max": 982184.0,
                                "Average": 982184.0,
                                "Sum": 7857472.0,
                                "N": 8,
                                "Unit": "BPS"
                            }
                        ]
                    }
                ],
                "Counters": []
            },
            {
                "Type": "IP",
                "Id": "192.0.2.5",
                "AttackVectors": [
                    {
                        "VectorType": "SYN_FLOOD",
                        "VectorCounters": [
                            {
                                "Name": "SYN_FLOOD_BPS",
                                "Max": 982184.0,
                                "Average": 982184.0,
                                "Sum": 1964368.0,
                                "N": 2,
                                "Unit": "BPS"
                            }
                        ]
                    }
                ],
                "Counters": []
            },
            {
                "Type": "IP",
                "Id": "2001:DB8::bcde:4321:8765:0:0",
                "AttackVectors": [
                    {
                        "VectorType": "SYN_FLOOD",
                        "VectorCounters": [
                            {
                                "Name": "SYN_FLOOD_BPS",
                                "Max": 982184.0,
                                "Average": 982184.0,
                                "Sum": 1964368.0,
                                "N": 2,
                                "Unit": "BPS"
                            }
                        ]
                    }
                ],
                "Counters": []
            },
            {
                "Type": "IP",
                "Id": "192.0.2.6",
                "AttackVectors": [
                    {
                        "VectorType": "SYN_FLOOD",
                        "VectorCounters": [
                            {
                                "Name": "SYN_FLOOD_BPS",
                                "Max": 982184.0,
                                "Average": 982184.0,
                                "Sum": 1964368.0,
                                "N": 2,
                                "Unit": "BPS"
                            }
                        ]
                    }
                ],
                "Counters": []
            }
        ],
        "StartTime": 1576024927.457,
        "EndTime": 1576025647.457,
        "AttackCounters": [],
        "AttackProperties": [
            {
                "AttackLayer": "NETWORK",
                "AttackPropertyIdentifier": "SOURCE_IP_ADDRESS",
                "TopContributors": [
                    {
                        "Name": "198.51.100.5",
                        "Value": 2024475682
                    },
                    {
                        "Name": "198.51.100.8",
                        "Value": 1311380863
                    },
                    {
                        "Name": "203.0.113.4",
                        "Value": 900599855
                    },
                    {
                        "Name": "198.51.100.4",
                        "Value": 769417366
                    },
                    {
                        "Name": "203.1.113.13",
                        "Value": 757992847
                    }
                ],
                "Unit": "BYTES",
                "Total": 92773354841
            },
            {
                "AttackLayer": "NETWORK",
                "AttackPropertyIdentifier": "SOURCE_COUNTRY",
                "TopContributors": [
                    {
                        "Name": "United States",
                        "Value": 80938161764
                    },
                    {
                        "Name": "Brazil",
                        "Value": 9929864330
                    },
                    {
                        "Name": "Netherlands",
                        "Value": 1635009446
                    },
                    {
                        "Name": "Mexico",
                        "Value": 144832971
                    },
                    {
                        "Name": "Japan",
                        "Value": 45369000
                    }
                ],
                "Unit": "BYTES",
                "Total": 92773354841
            },
            {
                "AttackLayer": "NETWORK",
                "AttackPropertyIdentifier": "SOURCE_ASN",
                "TopContributors": [
                    {
                        "Name": "12345",
                        "Value": 74953625841
                    },
                    {
                        "Name": "12346",
                        "Value": 4440087595
                    },
                    {
                        "Name": "12347",
                        "Value": 1635009446
                    },
                    {
                        "Name": "12348",
                        "Value": 1221230000
                    },
                    {
                        "Name": "12349",
                        "Value": 1199425294
                    }
                ],
                "Unit": "BYTES",
                "Total": 92755479921
            }
        ],
        "Mitigations": []
    }
}
```
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[DDoS インシデントを確認する](https://docs.aws.amazon.com/waf/latest/developerguide/using-ddos-reports.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAttack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/describe-attack.html)」を参照してください。

### `describe-drt-access`
<a name="shield_DescribeDrtAccess_cli_2_topic"></a>

次のコード例は、`describe-drt-access` を使用する方法を示しています。

**AWS CLI**  
**DRT がお客様に代わって攻撃を軽減するために必要な許可の説明を取得するには**  
次の `describe-drt-access` の例では、DRT が持つロールと S3 バケット許可を取得し、お客様に代わって攻撃の可能性に対応できるようにします。  

```
aws shield describe-drt-access
```
出力:  

```
{
    "RoleArn": "arn:aws:iam::123456789012:role/service-role/DrtRole",
    "LogBucketList": [
        "flow-logs-for-website-lb"
    ]
}
```
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[DDoS 対応チームの承認](https://docs.aws.amazon.com/waf/latest/developerguide/authorize-DRT.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDrtAccess](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/describe-drt-access.html)」を参照してください。

### `describe-emergency-contact-settings`
<a name="shield_DescribeEmergencyContactSettings_cli_2_topic"></a>

次のコード例は、`describe-emergency-contact-settings` を使用する方法を示しています。

**AWS CLI**  
**DRT に登録されている緊急 E メールアドレスを取得するには**  
次の `describe-emergency-contact-settings` の例では、DRT に登録されているアカウントの E メールアドレスを取得します。これらは、疑わしい攻撃に応答しているときに DRT が問い合わせるアドレスです。  

```
aws shield describe-emergency-contact-settings
```
出力:  

```
{
    "EmergencyContactList": [
        {
            "EmailAddress": "ops@example.com"
        },
        {
            "EmailAddress": "ddos-notifications@example.com"
       }
    ]
}
```
詳細については、Shield *AWS Advanced デベロッパーガイド* AWS の「Shield の仕組み<https://docs.aws.amazon.com/waf/latest/developerguide/ddos-overview.html>」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEmergencyContactSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/describe-emergency-contact-settings.html)」を参照してください。

### `describe-protection`
<a name="shield_DescribeProtection_cli_2_topic"></a>

次の例は、`describe-protection` を使用する方法を説明しています。

**AWS CLI**  
**Shield Advanced AWS 保護の詳細を取得するには**  
次の `describe-protection` の例では、指定された ID を持つ Shield Advanced 保護の詳細情報を表示します。`list-protections` コマンドを実行すると、保護 ID を取得できます。  

```
aws shield describe-protection \
    --protection-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "Protection": {
        "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Name": "1.2.3.4",
        "ResourceArn": "arn:aws:ec2:us-west-2:123456789012:eip-allocation/eipalloc-0ac1537af40742a6d"
    }
}
```
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[保護するリソースの指定](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-choose-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeProtection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/describe-protection.html)」を参照してください。

### `describe-subscription`
<a name="shield_DescribeSubscription_cli_2_topic"></a>

次の例は、`describe-subscription` を使用する方法を説明しています。

**AWS CLI**  
**アカウントの AWS Shield Advanced 保護の詳細を取得するには**  
次の `describe-subscription` の例では、アカウントに提供される Shield Advanced 保護の詳細情報を表示します。  

```
aws shield describe-subscription
```
出力:  

```
{
    "Subscription": {
        "StartTime": 1534368978.0,
        "EndTime": 1597613778.0,
        "TimeCommitmentInSeconds": 63244800,
        "AutoRenew": "ENABLED",
        "Limits": [
            {
                "Type": "GLOBAL_ACCELERATOR",
                "Max": 1000
            },
            {
                "Type": "ROUTE53_HOSTED_ZONE",
                "Max": 1000
            },
            {
                "Type": "CF_DISTRIBUTION",
                "Max": 1000
            },
            {
                "Type": "ELB_LOAD_BALANCER",
                "Max": 1000
            },
            {
                "Type": "EC2_ELASTIC_IP_ALLOCATION",
                "Max": 1000
            }
        ]
    }
}
```
詳細については、[Shield Advanced デベロッパーガイド AWS の「Shield の仕組み](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-overview.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/describe-subscription.html)」を参照してください。

### `disassociate-drt-log-bucket`
<a name="shield_DisassociateDrtLogBucket_cli_2_topic"></a>

次のコード例は、`disassociate-drt-log-bucket` を使用する方法を示しています。

**AWS CLI**  
**DRT がお客様に代わって Amazon S3 バケットにアクセスする許可を削除するには**  
次の `disassociate-drt-log-bucket` の例では、DRT と指定された S3 バケットの間の関連付けを削除します。このコマンドが完了すると、DRT はアカウントに代わってバケットにアクセスすることができなくなります。  

```
aws shield disassociate-drt-log-bucket \
    --log-bucket flow-logs-for-website-lb
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[DDoS 対応チームの承認](https://docs.aws.amazon.com/waf/latest/developerguide/authorize-DRT.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateDrtLogBucket](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/disassociate-drt-log-bucket.html)」を参照してください。

### `disassociate-drt-role`
<a name="shield_DisassociateDrtRole_cli_2_topic"></a>

次のコード例は、`disassociate-drt-role` を使用する方法を示しています。

**AWS CLI**  
**お客様に代わって DRT が攻撃を軽減する権限を削除するには**  
次の `disassociate-drt-role` の例では、DRT とアカウントの間の関連付けを削除します。この呼び出し後、DRT はアカウントにアクセスしたり、アクセスを管理したりできなくなります。  

```
aws shield disassociate-drt-role
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[DDoS 対応チームの承認](https://docs.aws.amazon.com/waf/latest/developerguide/authorize-DRT.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateDrtRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/disassociate-drt-role.html)」を参照してください。

### `get-subscription-state`
<a name="shield_GetSubscriptionState_cli_2_topic"></a>

次の例は、`get-subscription-state` を使用する方法を説明しています。

**AWS CLI**  
**アカウントの Shield Advanced AWS サブスクリプションの現在の状態を取得するには**  
次の `get-subscription-state` の例では、アカウントの Shield Advanced 保護の状態を取得します。  

```
aws shield get-subscription-state
```
出力:  

```
{
    "SubscriptionState": "ACTIVE"
}
```
詳細については、[Shield Advanced デベロッパーガイド AWS の「Shield の仕組み](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-overview.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSubscriptionState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/get-subscription-state.html)」を参照してください。

### `list-attacks`
<a name="shield_ListAttacks_cli_2_topic"></a>

次の例は、`list-attacks` を使用する方法を説明しています。

**AWS CLI**  
** AWS Shield Advanced から攻撃の概要を取得するには**  
次の の`list-attacks`例では、指定された期間中の指定された AWS CloudFront ディストリビューションの攻撃の概要を取得します。応答には、攻撃の詳細情報を取得するために `describe-attack` コマンドに提供できる攻撃 ID が含まれます。  

```
aws shield list-attacks \
    --resource-arns arn:aws:cloudfront::12345678910:distribution/E1PXMP22ZVFAOR \
    --start-time FromInclusive=1529280000,ToExclusive=1529300000
```
出力:  

```
{
    "AttackSummaries": [
        {
            "AttackId": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "ResourceArn": "arn:aws:cloudfront::123456789012:distribution/E1PXMP22ZVFAOR",
            "StartTime": 1529280000.0,
            "EndTime": 1529449200.0,
            "AttackVectors": [
                {
                    "VectorType": "SYN_FLOOD"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[DDoS インシデントを確認する](https://docs.aws.amazon.com/waf/latest/developerguide/using-ddos-reports.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAttacks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/list-attacks.html)」を参照してください。

### `list-protections`
<a name="shield_ListProtections_cli_2_topic"></a>

次の例は、`list-protections` を使用する方法を説明しています。

**AWS CLI**  
** AWS Shield Advanced から保護の概要を取得するには**  
次の `list-protections` の例では、アカウントで有効になっている保護の概要を取得します。  

```
aws shield list-protections
```
出力:  

```
{
    "Protections": [
        {
            "Id": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Name": "Protection for CloudFront distribution",
            "ResourceArn": "arn:aws:cloudfront::123456789012:distribution/E198WC25FXOWY8"
        }
    ]
}
```
詳細については、「*AWS Shield Advanced デベロッパーガイド*」の「[保護するリソースの指定](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-choose-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListProtections](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/list-protections.html)」を参照してください。

### `update-emergency-contact-settings`
<a name="shield_UpdateEmergencyContactSettings_cli_2_topic"></a>

次のコード例は、`update-emergency-contact-settings` を使用する方法を示しています。

**AWS CLI**  
**DRT に登録される緊急 E メールアドレスを定義するには**  
次の `update-emergency-contact-settings` の例では、攻撃が疑われる場合に DRT が応答で問い合わせる 2 つの E メールアドレスを定義します。  

```
aws shield update-emergency-contact-settings \
        --emergency-contact-list EmailAddress=ops@example.com EmailAddress=ddos-notifications@example.com
```
このコマンドでは何も出力されません。  
詳細については、[Shield Advanced デベロッパーガイド AWS の「Shield の仕組み](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-overview.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateEmergencyContactSettings](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/update-emergency-contact-settings.html)」を参照してください。

### `update-subscription`
<a name="shield_UpdateSubscription_cli_2_topic"></a>

次の例は、`update-subscription` を使用する方法を説明しています。

**AWS CLI**  
**アカウントの Shield Advanced AWS サブスクリプションを変更するには**  
次の`update-subscription`例では、アカウントの AWS Shield Advanced サブスクリプションの自動更新を有効にします。  

```
aws shield update-subscription \
    --auto-renew ENABLED
```
このコマンドでは何も出力されません。  
詳細については、[Shield Advanced デベロッパーガイド AWS の「Shield の仕組み](https://docs.aws.amazon.com/waf/latest/developerguide/ddos-overview.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/shield/update-subscription.html)」を参照してください。

# を使用した署名者の例 AWS CLI
<a name="cli_2_signer_code_examples"></a>

次のコード例は、Signer AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `cancel-signing-profile`
<a name="signer_CancelSigningProfile_cli_2_topic"></a>

次のコード例は、`cancel-signing-profile` を使用する方法を示しています。

**AWS CLI**  
**署名プロファイルを削除するには**  
次の の`cancel-signing-profile`例では、 AWS Signer から既存の署名プロファイルを削除します。  

```
aws signer cancel-signing-profile \
    --profile-name MyProfile1
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelSigningProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/cancel-signing-profile.html)」を参照してください。

### `describe-signing-job`
<a name="signer_DescribeSigningJob_cli_2_topic"></a>

次のコード例は、`describe-signing-job` を使用する方法を示しています。

**AWS CLI**  
**署名ジョブの詳細を表示するには**  
次の `describe-signing-job` の例では、指定された署名ジョブの詳細情報を表示します。  

```
aws signer describe-signing-job \
    --job-id 2065c468-73e2-4385-a6c9-0123456789abc
```
出力:  

```
{
    "status": "Succeeded",
    "completedAt": 1568412037,
    "platformId": "AmazonFreeRTOS-Default",
    "signingMaterial": {
        "certificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/6a55389b-306b-4e8c-a95c-0123456789abc"
    },
    "statusReason": "Signing Succeeded",
    "jobId": "2065c468-73e2-4385-a6c9-0123456789abc",
    "source": {
        "s3": {
            "version": "PNyFaUTgsQh5ZdMCcoCe6pT1gOpgB_M4",
            "bucketName": "signer-source",
            "key": "MyCode.rb"
        }
    },
    "profileName": "MyProfile2",
    "signedObject": {
        "s3": {
            "bucketName": "signer-destination",
            "key": "signed-2065c468-73e2-4385-a6c9-0123456789abc"
        }
    },
    "requestedBy": "arn:aws:iam::123456789012:user/maria",
    "createdAt": 1568412036
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSigningJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/describe-signing-job.html)」を参照してください。

### `get-signing-platform`
<a name="signer_GetSigningPlatform_cli_2_topic"></a>

次のコード例は、`get-signing-platform` を使用する方法を示しています。

**AWS CLI**  
**署名プラットフォームの詳細を表示するには**  
次の `get-signing-platform` の例では、指定された署名プラットフォームの詳細情報を表示します。  

```
aws signer get-signing-platform \
    --platform-id AmazonFreeRTOS-TI-CC3220SF
```
出力:  

```
{
    "category": "AWS",
    "displayName": "Amazon FreeRTOS SHA1-RSA CC3220SF-Format",
    "target": "SHA1-RSA-TISHA1",
    "platformId": "AmazonFreeRTOS-TI-CC3220SF",
    "signingConfiguration": {
        "encryptionAlgorithmOptions": {
            "defaultValue": "RSA",
            "allowedValues": [
                "RSA"
            ]
        },
        "hashAlgorithmOptions": {
            "defaultValue": "SHA1",
            "allowedValues": [
                "SHA1"
            ]
        }
    },
    "maxSizeInMB": 16,
    "partner": "AmazonFreeRTOS",
    "signingImageFormat": {
        "defaultFormat": "JSONEmbedded",
        "supportedFormats": [
            "JSONEmbedded"
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSigningPlatform](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/get-signing-platform.html)」を参照してください。

### `get-signing-profile`
<a name="signer_GetSigningProfile_cli_2_topic"></a>

次のコード例は、`get-signing-profile` を使用する方法を示しています。

**AWS CLI**  
**署名プロファイルの詳細を表示するには**  
次の `get-signing-profile` の例では、指定された署名プロファイルの詳細情報を表示します。  

```
aws signer get-signing-profile \
    --profile-name MyProfile3
```
出力:  

```
{
    "platformId": "AmazonFreeRTOS-TI-CC3220SF",
    "profileName": "MyProfile3",
    "status": "Active",
    "signingMaterial": {
        "certificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/6a55389b-306b-4e8c-a95c-0123456789abc"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSigningProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/get-signing-profile.html)」を参照してください。

### `list-signing-jobs`
<a name="signer_ListSigningJobs_cli_2_topic"></a>

次のコード例は、`list-signing-jobs` を使用する方法を示しています。

**AWS CLI**  
**すべての署名ジョブを一覧表示するには**  
次の `list-signing-jobs` の例では、アカウントのすべて署名ジョブの詳細情報を表示します。  

```
aws signer list-signing-jobs
```
この例では、2 つのジョブが返され、1 つは成功し、1 つは失敗しています。  

```
{
    "jobs": [
        {
            "status": "Succeeded",
            "signingMaterial": {
                "certificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/6a55389b-306b-4e8c-a95c-0123456789abc"
            },
            "jobId": "2065c468-73e2-4385-a6c9-0123456789abc",
            "source": {
                "s3": {
                    "version": "PNyFaUTgsQh5ZdMCcoCe6pT1gOpgB_M4",
                    "bucketName": "signer-source",
                    "key": "MyCode.rb"
                }
            },
            "signedObject": {
                "s3": {
                    "bucketName": "signer-destination",
                    "key": "signed-2065c468-73e2-4385-a6c9-0123456789abc"
                }
            },
            "createdAt": 1568412036
        },
        {
            "status": "Failed",
            "source": {
                "s3": {
                    "version": "PNyFaUTgsQh5ZdMCcoCe6pT1gOpgB_M4",
                    "bucketName": "signer-source",
                    "key": "MyOtherCode.rb"
                }
            },
            "signingMaterial": {
                "certificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/6a55389b-306b-4e8c-a95c-0123456789abc"
            },
            "createdAt": 1568402690,
            "jobId": "74d9825e-22fc-4a0d-b962-0123456789abc"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSigningJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/list-signing-jobs.html)」を参照してください。

### `list-signing-platforms`
<a name="signer_ListSigningPlatforms_cli_2_topic"></a>

次のコード例は、`list-signing-platforms` を使用する方法を示しています。

**AWS CLI**  
**すべての署名プラットフォームを一覧表示するには**  
次の `list-signing-platforms` の例では、使用可能なすべての署名プラットフォームの詳細情報を表示します。  

```
aws signer list-signing-platforms
```
出力:  

```
{
    "platforms": [
        {
            "category": "AWS",
            "displayName": "AWS IoT Device Management SHA256-ECDSA ",
            "target": "SHA256-ECDSA",
            "platformId": "AWSIoTDeviceManagement-SHA256-ECDSA",
            "signingConfiguration": {
                "encryptionAlgorithmOptions": {
                    "defaultValue": "ECDSA",
                    "allowedValues": [
                        "ECDSA"
                    ]
                },
                "hashAlgorithmOptions": {
                    "defaultValue": "SHA256",
                    "allowedValues": [
                        "SHA256"
                    ]
                }
            },
            "maxSizeInMB": 2048,
            "partner": "AWSIoTDeviceManagement",
            "signingImageFormat": {
                "defaultFormat": "JSONDetached",
                "supportedFormats": [
                    "JSONDetached"
                ]
            }
        },
        {
            "category": "AWS",
            "displayName": "Amazon FreeRTOS SHA1-RSA CC3220SF-Format",
            "target": "SHA1-RSA-TISHA1",
            "platformId": "AmazonFreeRTOS-TI-CC3220SF",
            "signingConfiguration": {
                "encryptionAlgorithmOptions": {
                    "defaultValue": "RSA",
                    "allowedValues": [
                        "RSA"
                    ]
                },
                "hashAlgorithmOptions": {
                    "defaultValue": "SHA1",
                    "allowedValues": [
                        "SHA1"
                    ]
                }
            },
            "maxSizeInMB": 16,
            "partner": "AmazonFreeRTOS",
            "signingImageFormat": {
                "defaultFormat": "JSONEmbedded",
                "supportedFormats": [
                    "JSONEmbedded"
                ]
            }
        },
        {
            "category": "AWS",
            "displayName": "Amazon FreeRTOS SHA256-ECDSA",
            "target": "SHA256-ECDSA",
            "platformId": "AmazonFreeRTOS-Default",
            "signingConfiguration": {
                "encryptionAlgorithmOptions": {
                    "defaultValue": "ECDSA",
                    "allowedValues": [
                        "ECDSA"
                    ]
                },
                "hashAlgorithmOptions": {
                    "defaultValue": "SHA256",
                    "allowedValues": [
                        "SHA256"
                    ]
                }
            },
            "maxSizeInMB": 16,
            "partner": "AmazonFreeRTOS",
            "signingImageFormat": {
                "defaultFormat": "JSONEmbedded",
                "supportedFormats": [
                    "JSONEmbedded"
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSigningPlatforms](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/list-signing-platforms.html)」を参照してください。

### `list-signing-profiles`
<a name="signer_ListSigningProfiles_cli_2_topic"></a>

次のコード例は、`list-signing-profiles` を使用する方法を示しています。

**AWS CLI**  
**すべての署名プロファイルを一覧表示するには**  
次の `list-signing-profiles` の例では、アカウントのすべての署名プロファイルの詳細情報を表示します。  

```
aws signer list-signing-profiles
```
出力:  

```
{
    "profiles": [
        {
            "platformId": "AmazonFreeRTOS-TI-CC3220SF",
            "profileName": "MyProfile4",
            "status": "Active",
            "signingMaterial": {
                "certificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/6a55389b-306b-4e8c-a95c-0123456789abc"
            }
        },
        {
            "platformId": "AWSIoTDeviceManagement-SHA256-ECDSA",
            "profileName": "MyProfile5",
            "status": "Active",
            "signingMaterial": {
                "certificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/6a55389b-306b-4e8c-a95c-0123456789abc"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSigningProfiles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/list-signing-profiles.html)」を参照してください。

### `put-signing-profile`
<a name="signer_PutSigningProfile_cli_2_topic"></a>

次のコード例は、`put-signing-profile` を使用する方法を示しています。

**AWS CLI**  
**署名プロファイルを作成するには**  
次の `put-signing-profile` の例では、指定された証明書とプラットフォームを使用して署名プロファイルを作成します。  

```
aws signer put-signing-profile \
    --profile-name MyProfile6 \
    --signing-material certificateArn=arn:aws:acm:us-west-2:123456789012:certificate/6a55389b-306b-4e8c-a95c-0123456789abc \
    --platform AmazonFreeRTOS-TI-CC3220SF
```
出力:  

```
{
    "arn": "arn:aws:signer:us-west-2:123456789012:/signing-profiles/MyProfile6"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutSigningProfile](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/put-signing-profile.html)」を参照してください。

### `start-signing-job`
<a name="signer_StartSigningJob_cli_2_topic"></a>

次のコード例は、`start-signing-job` を使用する方法を示しています。

**AWS CLI**  
**署名ジョブを開始するには**  
次の `start-signing-job` の例では、指定されたソースで見つかったコードの署名ジョブを開始します。指定されたプロファイルを使用して署名を行い、署名されたコードを指定された宛先に配置します。  

```
aws signer start-signing-job \
    --source 's3={bucketName=signer-source,key=MyCode.rb,version=PNyFaUTgsQh5ZdMCcoCe6pT1gOpgB_M4}' \
    --destination 's3={bucketName=signer-destination,prefix=signed-}' \
    --profile-name MyProfile7
```
出力は署名ジョブの ID です。  

```
{
    "jobId": "2065c468-73e2-4385-a6c9-0123456789abc"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartSigningJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/signer/start-signing-job.html)」を参照してください。

# を使用した Snowball Edge の例 AWS CLI
<a name="cli_2_snowball_code_examples"></a>

次のコード例は、Snowball Edge AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-snowball-usage`
<a name="snowball_GetSnowballUsage_cli_2_topic"></a>

次のコード例は、`get-snowball-usage` を使用する方法を示しています。

**AWS CLI**  
**アカウントの Snowball サービス制限に関する情報を取得するには**  
次の `get-snowball-usage` の例では、アカウントの Snowball サービスの制限に関する情報の他、アカウントが使用中の Snowball の数も表示します。  

```
aws snowball get-snowball-usage
```
出力:  

```
{
    "SnowballLimit": 1,
    "SnowballsInUse": 0
}
```
詳細については、「*AWS Snowball デベロッパーガイド*」の「[AWS Snowball Edge の制限](https://docs.aws.amazon.com/snowball/latest/developer-guide/limits.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSnowballUsage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/snowball/get-snowball-usage.html)」を参照してください。

### `list-jobs`
<a name="snowball_ListJobs_cli_2_topic"></a>

次のコード例は、`list-jobs` を使用する方法を示しています。

**AWS CLI**  
**アカウント内の現在の Snowball ジョブを一覧表示するには**  
次の `list-jobs` の例では、`JobListEntry` オブジェクトの配列を表示します。この例では、1 つのジョブが一覧表示されています。  

```
aws snowball list-jobs
```
出力:  

```
{
    "JobListEntries": [
        {
            "CreationDate": 2016-09-27T14:50Z,
             "Description": "Important Photos 2016-08-11",
             "IsMaster": TRUE,
             "JobId": "ABCd1e324fe-022f-488e-a98b-3b0566063db1",
             "JobState": "Complete",
             "JobType": "IMPORT",
             "SnowballType": "EDGE"
        }
   ]
}
```
詳細については、[AWS Snowball デベロッパーガイドの「Snowball Edge デバイスのジョブ](https://docs.aws.amazon.com/snowball/latest/developer-guide/jobs.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/snowball/list-jobs.html)」を参照してください。

# を使用した Amazon SNS の例 AWS CLI
<a name="cli_2_sns_code_examples"></a>

次のコード例は、Amazon SNS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `add-permission`
<a name="sns_AddPermission_cli_2_topic"></a>

次のコード例は、`add-permission` を使用する方法を示しています。

**AWS CLI**  
**トピックにアクセス許可を追加するには**  
次の の`add-permission`例では、 AWS アカウント の指定されたトピックで `Publish`アクションを使用する`987654321098`アクセス許可を AWS アカウント に追加します`123456789012`。  

```
aws sns add-permission \
    --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --label Publish-Permission \
    --aws-account-id 987654321098 \
    --action-name Publish
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/add-permission.html)」を参照してください。

### `check-if-phone-number-is-opted-out`
<a name="sns_CheckIfPhoneNumberIsOptedOut_cli_2_topic"></a>

次のコード例は、`check-if-phone-number-is-opted-out` を使用する方法を示しています。

**AWS CLI**  
**電話番号での SMS メッセージのオプトアウトを確認するには**  
次の の`check-if-phone-number-is-opted-out`例では、指定された電話番号が現在の AWS アカウントからの SMS メッセージの受信をオプトアウトされているかどうかを確認します。  

```
aws sns check-if-phone-number-is-opted-out \
    --phone-number +1555550100
```
出力:  

```
{
    "isOptedOut": false
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CheckIfPhoneNumberIsOptedOut](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/check-if-phone-number-is-opted-out.html)」を参照してください。

### `confirm-subscription`
<a name="sns_ConfirmSubscription_cli_2_topic"></a>

次のコード例は、`confirm-subscription` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプションを確認するには**  
次の `confirm-subscription` コマンドは、`my-topic` という名前の SNS トピックをサブスクライブしたときに開始された確認プロセスを完了します。--token パラメータは、subscribe の呼び出しで指定した通知エンドポイントに送信される確認メッセージから取得されます。  

```
aws sns confirm-subscription \
    --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \
    --token 2336412f37fb687f5d51e6e241d7700ae02f7124d8268910b858cb4db727ceeb2474bb937929d3bdd7ce5d0cce19325d036bc858d3c217426bcafa9c501a2cace93b83f1dd3797627467553dc438a8c974119496fc3eff026eaa5d14472ded6f9a5c43aec62d83ef5f49109da7176391
```
出力:  

```
{
    "SubscriptionArn": "arn:aws:sns:us-west-2:123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ConfirmSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/confirm-subscription.html)」を参照してください。

### `create-platform-application`
<a name="sns_CreatePlatformApplication_cli_2_topic"></a>

次のコード例は、`create-platform-application` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションを作成するには**  
次の `create-platform-application` の例では、指定されたプラットフォーム認証情報を使用して Google Firebase プラットフォームアプリケーションを作成します。  

```
aws sns create-platform-application \
    --name MyApplication \
    --platform GCM \
    --attributes PlatformCredential=EXAMPLEabcd12345jklm67890stuv12345bcdef
```
出力:  

```
{
    "PlatformApplicationArn": "arn:aws:sns:us-west-2:123456789012:app/GCM/MyApplication"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePlatformApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/create-platform-application.html)」を参照してください。

### `create-topic`
<a name="sns_CreateTopic_cli_2_topic"></a>

次のコード例は、`create-topic` を使用する方法を示しています。

**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 での](https://docs.aws.amazon.com/cli/latest/userguide/cli-sqs-queue-sns-topic.html)コマンドラインインターフェイスの使用」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/create-topic.html)」を参照してください。

### `delete-endpoint`
<a name="sns_DeleteEndpoint_cli_2_topic"></a>

次のコード例は、`delete-endpoint` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションのエンドポイントを削除するには**  
次の `delete-endpoint` の例では、指定されたプラットフォームアプリケーションのエンドポイントを削除します。  

```
aws sns delete-endpoint \
    --endpoint-arn arn:aws:sns:us-west-2:123456789012:endpoint/GCM/MyApplication/12345678-abcd-9012-efgh-345678901234
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteEndpoint](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/delete-endpoint.html)」を参照してください。

### `delete-platform-application`
<a name="sns_DeletePlatformApplication_cli_2_topic"></a>

次のコード例は、`delete-platform-application` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションを削除するには**  
次の `delete-platform-application` の例では、指定されたプラットフォームアプリケーションを削除します。  

```
aws sns delete-platform-application \
    --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/ADM/MyApplication
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePlatformApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/delete-platform-application.html)」を参照してください。

### `delete-topic`
<a name="sns_DeleteTopic_cli_2_topic"></a>

次のコード例は、`delete-topic` を使用する方法を示しています。

**AWS CLI**  
**SNS トピックを削除するには**  
次の `delete-topic` の例では、指定した SNS トピックを削除します。  

```
aws sns delete-topic \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/delete-topic.html)」を参照してください。

### `get-endpoint-attributes`
<a name="sns_GetEndpointAttributes_cli_2_topic"></a>

次のコード例は、`get-endpoint-attributes` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションエンドポイント属性を一覧表示するには**  
次の `get-endpoint-attributes` の例では、指定されたプラットフォームアプリケーションのエンドポイントの属性を一覧表示します。  

```
aws sns get-endpoint-attributes \
    --endpoint-arn arn:aws:sns:us-west-2:123456789012:endpoint/GCM/MyApplication/12345678-abcd-9012-efgh-345678901234
```
出力:  

```
{
    "Attributes": {
        "Enabled": "true",
        "Token": "EXAMPLE12345..."
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEndpointAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/get-endpoint-attributes.html)」を参照してください。

### `get-platform-application-attributes`
<a name="sns_GetPlatformApplicationAttributes_cli_2_topic"></a>

次のコード例は、`get-platform-application-attributes` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションの属性を一覧表示するには**  
次の `get-platform-application-attributes` の例では、指定されたプラットフォームアプリケーションの属性を一覧表示します。  

```
aws sns get-platform-application-attributes \
    --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/MPNS/MyApplication
```
出力:  

```
{
    "Attributes": {
        "Enabled": "true",
        "SuccessFeedbackSampleRate": "100"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPlatformApplicationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/get-platform-application-attributes.html)」を参照してください。

### `get-sms-attributes`
<a name="sns_GetSMSAttributes_cli_2_topic"></a>

次のコード例は、`get-sms-attributes` を使用する方法を示しています。

**AWS CLI**  
**デフォルトの SMS メッセージ属性を一覧表示するには**  
次の `get-sms-attributes` の例では、SMS メッセージを送信するためのデフォルト属性を一覧表示しています。  

```
aws sns get-sms-attributes
```
出力:  

```
{
    "attributes": {
        "DefaultSenderID": "MyName"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSMSAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/get-sms-attributes.html)」を参照してください。

### `get-subscription-attributes`
<a name="sns_GetSubscriptionAttributes_cli_2_topic"></a>

次のコード例は、`get-subscription-attributes` を使用する方法を示しています。

**AWS CLI**  
**トピックのサブスクリプション属性を取得するには**  
次の `get-subscription-attributes` の例では、指定されたサブスクリプションの属性を表示します。`list-subscriptions` コマンドの出力から `subscription-arn` を取得できます。  

```
aws sns get-subscription-attributes \
    --subscription-arn "arn:aws:sns:us-west-2:123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f"
```
出力:  

```
{
    "Attributes": {
        "Endpoint": "my-email@example.com",
        "Protocol": "email",
        "RawMessageDelivery": "false",
        "ConfirmationWasAuthenticated": "false",
        "Owner": "123456789012",
        "SubscriptionArn": "arn:aws:sns:us-west-2:123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f",
        "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSubscriptionAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/get-subscription-attributes.html)」を参照してください。

### `get-topic-attributes`
<a name="sns_GetTopicAttributes_cli_2_topic"></a>

次のコード例は、`get-topic-attributes` を使用する方法を示しています。

**AWS CLI**  
**トピックの属性を取得するには**  
次の `get-topic-attributes` の例では、指定したトピックの属性を表示します。  

```
aws sns get-topic-attributes \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic"
```
出力:  

```
{
    "Attributes": {
        "SubscriptionsConfirmed": "1",
        "DisplayName": "my-topic",
        "SubscriptionsDeleted": "0",
        "EffectiveDeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}",
        "Owner": "123456789012",
        "Policy": "{\"Version\":\"2008-10-17\",\"Id\":\"__default_policy_ID\",\"Statement\":[{\"Sid\":\"__default_statement_ID\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"SNS:Subscribe\",\"SNS:ListSubscriptionsByTopic\",\"SNS:DeleteTopic\",\"SNS:GetTopicAttributes\",\"SNS:Publish\",\"SNS:RemovePermission\",\"SNS:AddPermission\",\"SNS:SetTopicAttributes\"],\"Resource\":\"arn:aws:sns:us-west-2:123456789012:my-topic\",\"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\":\"0123456789012\"}}}]}",
        "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic",
        "SubscriptionsPending": "0"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTopicAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/get-topic-attributes.html)」を参照してください。

### `list-endpoints-by-platform-application`
<a name="sns_ListEndpointsByPlatformApplication_cli_2_topic"></a>

次のコード例は、`list-endpoints-by-platform-application` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションのエンドポイントを一覧表示するには**  
次の `list-endpoints-by-platform-application` の例では、指定されたプラットフォームアプリケーションのエンドポイントとエンドポイント属性を一覧表示します。  

```
aws sns list-endpoints-by-platform-application \
    --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/GCM/MyApplication
```
出力:  

```
{
    "Endpoints": [
        {
            "Attributes": {
                "Token": "EXAMPLE12345...,
                "Enabled": "true"
            },
            "EndpointArn": "arn:aws:sns:us-west-2:123456789012:endpoint/GCM/MyApplication/12345678-abcd-9012-efgh-345678901234"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListEndpointsByPlatformApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/list-endpoints-by-platform-application.html)」を参照してください。

### `list-phone-numbers-opted-out`
<a name="sns_ListPhoneNumbersOptedOut_cli_2_topic"></a>

次のコード例は、`list-phone-numbers-opted-out` を使用する方法を示しています。

**AWS CLI**  
**SMS メッセージのオプトアウトを一覧表示するには**  
次の `list-phone-numbers-opted-out` の例では、SMS メッセージの受信をオプトアウトした電話番号を一覧表示しています。  

```
aws sns list-phone-numbers-opted-out
```
出力:  

```
{
    "phoneNumbers": [
        "+15555550100"
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPhoneNumbersOptedOut](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/list-phone-numbers-opted-out.html)」を参照してください。

### `list-platform-applications`
<a name="sns_ListPlatformApplications_cli_2_topic"></a>

次のコード例は、`list-platform-applications` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションを一覧表示するには**  
次の `list-platform-applications` の例では、ADM と MPNS のプラットフォームアプリケーションを一覧表示します。  

```
aws sns list-platform-applications
```
出力:  

```
{
    "PlatformApplications": [
        {
            "PlatformApplicationArn": "arn:aws:sns:us-west-2:123456789012:app/ADM/MyApplication",
            "Attributes": {
                "SuccessFeedbackSampleRate": "100",
                "Enabled": "true"
            }
        },
        {
            "PlatformApplicationArn": "arn:aws:sns:us-west-2:123456789012:app/MPNS/MyOtherApplication",
            "Attributes": {
                "SuccessFeedbackSampleRate": "100",
                "Enabled": "true"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPlatformApplications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/list-platform-applications.html)」を参照してください。

### `list-subscriptions-by-topic`
<a name="sns_ListSubscriptionsByTopic_cli_2_topic"></a>

次のコード例は、`list-subscriptions-by-topic` を使用する方法を示しています。

**AWS CLI**  
**トピックに関連付けられたサブスクリプションを一覧表示するには**  
次の `list-subscriptions-by-topic` の例では、指定されたトピックに関連付けられた SNS サブスクリプションのリストを取得します。  

```
aws sns list-subscriptions-by-topic \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic"
```
出力:  

```
{
    "Subscriptions": [
        {
            "Owner": "123456789012",
            "Endpoint": "my-email@example.com",
            "Protocol": "email",
            "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic",
            "SubscriptionArn": "arn:aws:sns:us-west-2:123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSubscriptionsByTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/list-subscriptions-by-topic.html)」を参照してください。

### `list-subscriptions`
<a name="sns_ListSubscriptions_cli_2_topic"></a>

次のコード例は、`list-subscriptions` を使用する方法を示しています。

**AWS CLI**  
**SNS サブスクリプションを一覧表示するには**  
次の の`list-subscriptions`例では、 AWS アカウントの SNS サブスクリプションのリストを表示します。  

```
aws sns list-subscriptions
```
出力:  

```
{
    "Subscriptions": [
        {
            "Owner": "123456789012",
            "Endpoint": "my-email@example.com",
            "Protocol": "email",
            "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic",
            "SubscriptionArn": "arn:aws:sns:us-west-2:123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListSubscriptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/list-subscriptions.html)」を参照してください。

### `list-tags-for-resource`
<a name="sns_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**トピックのタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、指定された Amazon SNS トピックのタグを一覧表示します。  

```
aws sns list-tags-for-resource \
    --resource-arn arn:aws:sns:us-west-2:123456789012:MyTopic
```
出力:  

```
{
    "Tags": [
        {
            "Key": "Team",
            "Value": "Alpha"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/list-tags-for-resource.html)」を参照してください。

### `list-topics`
<a name="sns_ListTopics_cli_2_topic"></a>

次のコード例は、`list-topics` を使用する方法を示しています。

**AWS CLI**  
**SNS トピックを一覧表示するには**  
次の の`list-topics`例では、 AWS アカウント内のすべての SNS トピックを一覧表示します。  

```
aws sns list-topics
```
出力:  

```
{
    "Topics": [
        {
            "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTopics](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/list-topics.html)」を参照してください。

### `opt-in-phone-number`
<a name="sns_OptInPhoneNumber_cli_2_topic"></a>

次のコード例は、`opt-in-phone-number` を使用する方法を示しています。

**AWS CLI**  
**SMS メッセージをオプトインするには**  
次の `opt-in-phone-number` の例では、指定された電話番号で SMS メッセージの受信をオプトインできるようにします。  

```
aws sns opt-in-phone-number \
    --phone-number +15555550100
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[OptInPhoneNumber](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/opt-in-phone-number.html)」を参照してください。

### `publish`
<a name="sns_Publish_cli_2_topic"></a>

次のコード例は、`publish` を使用する方法を示しています。

**AWS CLI**  
**例 1: トピックにメッセージを発行するには**  
次の `publish` の例では、指定した Amazon SNS トピックに指定した通知を公開します。メッセージはテキストファイルから取得されたもので、改行を含めることができます。  

```
aws sns publish \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \
    --message file://message.txt
```
`message.txt` の内容:  

```
Hello World
Second Line
```
出力:  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-111122223333"
}
```
**例 2: 電話番号に SMS メッセージを公開するには**  
次の `publish` の例では、`Hello world!` メッセージを電話番号 `+1-555-555-0100` に公開します。  

```
aws sns publish \
    --message "Hello world!" \
    --phone-number +1-555-555-0100
```
出力:  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-333322221111"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Publish](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/publish.html)」を参照してください。

### `put-data-protection-policy`
<a name="sns_PutDataProtectionPolicy_cli_2_topic"></a>

次のコード例は、`put-data-protection-policy` を使用する方法を示しています。

**AWS CLI**  
**データ保護ポリシーを設定するには**  
**例 1: パブリッシャーが CreditCardNumber を使用してメッセージをパブリッシュすることを拒否するには**  
次の `put-data-protection-policy` の例では、パブリッシャーによる CreditCardNumber を使用したメッセージのパブリッシュを拒否します。  

```
aws sns put-data-protection-policy \
    --resource-arn arn:aws:sns:us-east-1:123456789012:mytopic \
    --data-protection-policy "{\"Name\":\"data_protection_policy\",\"Description\":\"Example data protection policy\",\"Version\":\"2021-06-01\",\"Statement\":[{\"DataDirection\":\"Inbound\",\"Principal\":[\"*\"],\"DataIdentifier\":[\"arn:aws:dataprotection::aws:data-identifier/CreditCardNumber\"],\"Operation\":{\"Deny\":{}}}]}"
```
このコマンドでは何も出力されません。  
**例 2: ファイルからパラメータをロードするには**  
次の `put-data-protection-policy` では、ファイルからパラメータをロードします。  

```
aws sns put-data-protection-policy \
    --resource-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --data-protection-policy file://policy.json
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutDataProtectionPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/put-data-protection-policy.html)」を参照してください。

### `remove-permission`
<a name="sns_RemovePermission_cli_2_topic"></a>

次のコード例は、`remove-permission` を使用する方法を示しています。

**AWS CLI**  
**トピックからアクセス許可を削除するには**  
次の `remove-permission` の例では、指定されたトピックからアクセス許可 `Publish-Permission` を削除します。  

```
aws sns remove-permission \
    --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --label Publish-Permission
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemovePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/remove-permission.html)」を参照してください。

### `set-endpoint-attributes`
<a name="sns_SetEndpointAttributes_cli_2_topic"></a>

次のコード例は、`set-endpoint-attributes` を使用する方法を示しています。

**AWS CLI**  
**エンドポイント属性を設定するには**  
次の `set-endpoint-attributes` の例では、指定されたプラットフォームアプリケーションエンドポイントを無効にします。  

```
aws sns set-endpoint-attributes \
    --endpoint-arn arn:aws:sns:us-west-2:123456789012:endpoint/GCM/MyApplication/12345678-abcd-9012-efgh-345678901234 \
    --attributes Enabled=false
```
出力:  

```
{
    "Attributes": {
        "Enabled": "false",
        "Token": "EXAMPLE12345..."
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetEndpointAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-endpoint-attributes.html)」を参照してください。

### `set-platform-application-attributes`
<a name="sns_SetPlatformApplicationAttributes_cli_2_topic"></a>

次のコード例は、`set-platform-application-attributes` を使用する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションの属性を設定するには**  
次の `set-platform-application-attributes` の例では、指定されたプラットフォームアプリケーションの `EventDeliveryFailure` 属性を、指定された Amazon SNS トピックの ARN に設定します。  

```
aws sns set-platform-application-attributes \
    --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/GCM/MyApplication \
    --attributes EventDeliveryFailure=arn:aws:sns:us-west-2:123456789012:AnotherTopic
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetPlatformApplicationAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-platform-application-attributes.html)」を参照してください。

### `set-sms-attributes`
<a name="sns_SetSMSAttributes_cli_2_topic"></a>

次のコード例は、`set-sms-attributes` を使用する方法を示しています。

**AWS CLI**  
**SMS メッセージ属性を設定するには**  
次の `set-sms-attributes` の例では、SMS メッセージのデフォルトの送信者 ID を `MyName` に設定します。  

```
aws sns set-sms-attributes \
    --attributes DefaultSenderID=MyName
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetSMSAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-sms-attributes.html)」を参照してください。

### `set-subscription-attributes`
<a name="sns_SetSubscriptionAttributes_cli_2_topic"></a>

次のコード例は、`set-subscription-attributes` を使用する方法を示しています。

**AWS CLI**  
**サブスクリプション属性を設定するには**  
次の `set-subscription-attributes` の例では、`RawMessageDelivery` 属性を SQS サブスクリプションに設定します。  

```
aws sns set-subscription-attributes \
    --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \
    --attribute-name RawMessageDelivery \
    --attribute-value true
```
このコマンドでは何も出力されません。  
次の `set-subscription-attributes` の例では、`FilterPolicy` 属性を SQS サブスクリプションに設定します。  

```
aws sns set-subscription-attributes \
    --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \
    --attribute-name FilterPolicy \
    --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }"
```
このコマンドでは何も出力されません。  
次の `set-subscription-attributes` の例では、`FilterPolicy` 属性を SQS サブスクリプションから削除します。  

```
aws sns set-subscription-attributes \
    --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \
    --attribute-name FilterPolicy \
    --attribute-value "{}"
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetSubscriptionAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-subscription-attributes.html)」を参照してください。

### `set-topic-attributes`
<a name="sns_SetTopicAttributes_cli_2_topic"></a>

次のコード例は、`set-topic-attributes` を使用する方法を示しています。

**AWS CLI**  
**トピックの属性を設定するには**  
次の `set-topic-attributes` の例では、指定したトピックの `DisplayName` 属性を設定します。  

```
aws sns set-topic-attributes \
    --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --attribute-name DisplayName \
    --attribute-value MyTopicDisplayName
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SetTopicAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-topic-attributes.html)」を参照してください。

### `subscribe`
<a name="sns_Subscribe_cli_2_topic"></a>

次のコード例は、`subscribe` を使用する方法を示しています。

**AWS CLI**  
**トピックにサブスクライブするには**  
次の `subscribe` コマンドは、指定したトピックに E メールアドレスをサブスクライブします。  

```
aws sns subscribe \
    --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \
    --protocol email \
    --notification-endpoint my-email@example.com
```
出力:  

```
{
    "SubscriptionArn": "pending confirmation"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Subscribe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/subscribe.html)」を参照してください。

### `tag-resource`
<a name="sns_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**トピックにタグを追加するには**  
次の `tag-resource` の例では、指定した Amazon SNS トピックにメタデータタグを追加します。  

```
aws sns tag-resource \
    --resource-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --tags Key=Team,Value=Alpha
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/tag-resource.html)」を参照してください。

### `unsubscribe`
<a name="sns_Unsubscribe_cli_2_topic"></a>

次のコード例は、`unsubscribe` を使用する方法を示しています。

**AWS CLI**  
**トピックからサブスクライブを解除するには**  
次の `unsubscribe` の例では、指定したサブスクリプションをトピックから削除します。  

```
aws sns unsubscribe \
    --subscription-arn arn:aws:sns:us-west-2:0123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Unsubscribe](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/unsubscribe.html)」を参照してください。

### `untag-resource`
<a name="sns_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**トピックからタグを削除するには**  
次の `untag-resource` の例では、指定された Amazon SNS トピックから、指定されたキーを持つタグを削除します。  

```
aws sns untag-resource \
    --resource-arn arn:aws:sns:us-west-2:123456789012:MyTopic \
    --tag-keys Team
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/untag-resource.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### プッシュ通知のプラットフォームエンドポイントを作成します
<a name="sns_CreatePlatformEndpoint_cli_2_topic"></a>

次のコード例は、Amazon SNS プッシュ通知のプラットフォームエンドポイントを作成する方法を示しています。

**AWS CLI**  
**プラットフォームアプリケーションのエンドポイントを作成するには**  
次の `create-platform-endpoint` の例では、指定したトークンを使用して、指定したプラットフォームアプリケーションのエンドポイントを作成します。  

```
aws sns create-platform-endpoint \
    --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/GCM/MyApplication \
    --token EXAMPLE12345...
```
出力:  

```
{
      "EndpointArn": "arn:aws:sns:us-west-2:1234567890:endpoint/GCM/MyApplication/12345678-abcd-9012-efgh-345678901234"
}
```

# を使用した Amazon SQS の例 AWS CLI
<a name="cli_2_sqs_code_examples"></a>

次のコード例は、Amazon SQS AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-permission`
<a name="sqs_AddPermission_cli_2_topic"></a>

次のコード例は、`add-permission` を使用する方法を示しています。

**AWS CLI**  
**キューへのアクセス許可を追加するには**  
この例では、指定された AWS アカウントが指定されたキューにメッセージを送信できるようにします。  
コマンド:  

```
aws sqs add-permission --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --label SendMessagesFromMyQueue --aws-account-ids 12345EXAMPLE --actions SendMessage
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/add-permission.html)」を参照してください。

### `cancel-message-move-task`
<a name="sqs_CancelMessageMoveTask_cli_2_topic"></a>

次のコード例は、`cancel-message-move-task` を使用する方法を示しています。

**AWS CLI**  
**メッセージ移動タスクをキャンセルするには**  
次の `cancel-message-move-task` の例では、指定されたメッセージ移動タスクをキャンセルします。  

```
aws sqs cancel-message-move-task \
    --task-handle AQEB6nR4...HzlvZQ==
```
出力:  

```
{
    "ApproximateNumberOfMessagesMoved": 102
}
```
詳細については、「*デベロッパーガイド*」の「[Amazon SQS API permissions: Actions and resource reference](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-api-permissions-reference.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelMessageMoveTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/cancel-message-move-task.html)」を参照してください。

### `change-message-visibility-batch`
<a name="sqs_ChangeMessageVisibilityBatch_cli_2_topic"></a>

次のコード例は、`change-message-visibility-batch` を使用する方法を示しています。

**AWS CLI**  
**複数のメッセージの可視性タイムアウトをバッチで変更するには**  
この例では、2 件の指定されたメッセージの可視性タイムアウトを 10 時間 (10 時間 × 60 分 × 60 秒) に変更します。  
コマンド:  

```
aws sqs change-message-visibility-batch --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --entries file://change-message-visibility-batch.json
```
入力ファイル (change-message-visibility-batch.json):  

```
[
  {
    "Id": "FirstMessage",
        "ReceiptHandle": "AQEBhz2q...Jf3kaw==",
        "VisibilityTimeout": 36000
  },
  {
    "Id": "SecondMessage",
        "ReceiptHandle": "AQEBkTUH...HifSnw==",
        "VisibilityTimeout": 36000
  }
]
```
出力:  

```
{
  "Successful": [
    {
      "Id": "SecondMessage"
    },
    {
      "Id": "FirstMessage"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ChangeMessageVisibilityBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/change-message-visibility-batch.html)」を参照してください。

### `change-message-visibility`
<a name="sqs_ChangeMessageVisibility_cli_2_topic"></a>

次のコード例は、`change-message-visibility` を使用する方法を示しています。

**AWS CLI**  
**メッセージのタイムアウトの可視性を変更するには**  
この例は、指定されたメッセージのタイムアウトの可視性を 10 時間 (10 時間 × 60 分 × 60 秒) に変更します。  
コマンド:  

```
aws sqs change-message-visibility --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --receipt-handle AQEBTpyI...t6HyQg== --visibility-timeout 36000
```
出力:  

```
None.
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ChangeMessageVisibility](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/change-message-visibility.html)」を参照してください。**

### `create-queue`
<a name="sqs_CreateQueue_cli_2_topic"></a>

次のコード例は、`create-queue` を使用する方法を示しています。

**AWS CLI**  
**キューを作成するには**  
この例は、指定された名前のキューを作成して、メッセージの保持期間を 3 日間 (3 日 × 24 時間 × 60 分 × 60 秒) に設定します。またキューのデッドレターキューを、最大受信数 1,000 件のメッセージを含む指定されたキューに設定します。  
コマンド:  

```
aws sqs create-queue --queue-name MyQueue --attributes file://create-queue.json
```
入力ファイル (create-queue.json):  

```
{
  "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":\"1000\"}",
  "MessageRetentionPeriod": "259200"
}
```
出力:  

```
{
  "QueueUrl": "https://queue.amazonaws.com/80398EXAMPLE/MyQueue"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/create-queue.html)」を参照してください。**

### `delete-message-batch`
<a name="sqs_DeleteMessageBatch_cli_2_topic"></a>

次のコード例は、`delete-message-batch` を使用する方法を示しています。

**AWS CLI**  
**複数のメッセージを一括削除するには**  
この例は、指定されたメッセージを削除します。  
コマンド:  

```
aws sqs delete-message-batch --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --entries file://delete-message-batch.json
```
入力ファイル (delete-message-batch.json):  

```
[
  {
        "Id": "FirstMessage",
        "ReceiptHandle": "AQEB1mgl...Z4GuLw=="
  },
  {
    "Id": "SecondMessage",
        "ReceiptHandle": "AQEBLsYM...VQubAA=="
  }
]
```
出力:  

```
{
  "Successful": [
    {
      "Id": "FirstMessage"
    },
    {
      "Id": "SecondMessage"
    }
  ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteMessageBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/delete-message-batch.html)」を参照してください。**

### `delete-message`
<a name="sqs_DeleteMessage_cli_2_topic"></a>

次のコード例は、`delete-message` を使用する方法を示しています。

**AWS CLI**  
**単一のメッセージを削除するには**  
この例は、指定された単一のメッセージを削除します。  
コマンド:  

```
aws sqs delete-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --receipt-handle AQEBRXTo...q2doVA==
```
出力:  

```
None.
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/delete-message.html)」を参照してください。**

### `delete-queue`
<a name="sqs_DeleteQueue_cli_2_topic"></a>

次のコード例は、`delete-queue` を使用する方法を示しています。

**AWS CLI**  
**キューを削除するには**  
この例は、指定されたキューを削除します。  
コマンド:  

```
aws sqs delete-queue --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyNewerQueue
```
出力:  

```
None.
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[DeleteQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/delete-queue.html)」を参照してください。

### `get-queue-attributes`
<a name="sqs_GetQueueAttributes_cli_2_topic"></a>

次のコード例は、`get-queue-attributes` を使用する方法を示しています。

**AWS CLI**  
**キューの属性を取得するには**  
この例では、指定されたキューの属性をすべて取得します。  
コマンド:  

```
aws sqs get-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute-names All
```
出力:  

```
{
  "Attributes": {
    "ApproximateNumberOfMessagesNotVisible": "0",
    "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":1000}",
    "MessageRetentionPeriod": "345600",
    "ApproximateNumberOfMessagesDelayed": "0",
    "MaximumMessageSize": "262144",
    "CreatedTimestamp": "1442426968",
    "ApproximateNumberOfMessages": "0",
    "ReceiveMessageWaitTimeSeconds": "0",
    "DelaySeconds": "0",
    "VisibilityTimeout": "30",
    "LastModifiedTimestamp": "1442426968",
    "QueueArn": "arn:aws:sqs:us-east-1:80398EXAMPLE:MyNewQueue"
  }
}
```
この例は、指定されたキューの最大メッセージサイズと可視性タイムアウト属性のみを取得します。  
コマンド:  

```
aws sqs get-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyNewQueue --attribute-names MaximumMessageSize VisibilityTimeout
```
出力:  

```
{
  "Attributes": {
    "VisibilityTimeout": "30",
    "MaximumMessageSize": "262144"
  }
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetQueueAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/get-queue-attributes.html)」を参照してください。**

### `get-queue-url`
<a name="sqs_GetQueueUrl_cli_2_topic"></a>

次のコード例は、`get-queue-url` を使用する方法を示しています。

**AWS CLI**  
**キューの URL を取得するには**  
この例は、指定されたキューの URL を取得します。  
コマンド:  

```
aws sqs get-queue-url --queue-name MyQueue
```
出力:  

```
{
  "QueueUrl": "https://queue.amazonaws.com/80398EXAMPLE/MyQueue"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetQueueUrl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/get-queue-url.html)」を参照してください。**

### `list-dead-letter-source-queues`
<a name="sqs_ListDeadLetterSourceQueues_cli_2_topic"></a>

次のコード例は、`list-dead-letter-source-queues` を使用する方法を示しています。

**AWS CLI**  
**デッドレターソースキューを一覧表示するには**  
この例では、指定されたデッドレターソースキューに関連付けられているキューを一覧表示します。  
コマンド:  

```
aws sqs list-dead-letter-source-queues --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
出力:  

```
{
  "queueUrls": [
    "https://queue.amazonaws.com/80398EXAMPLE/MyQueue",
    "https://queue.amazonaws.com/80398EXAMPLE/MyOtherQueue"
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDeadLetterSourceQueues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/list-dead-letter-source-queues.html)」を参照してください。

### `list-message-move-tasks`
<a name="sqs_ListMessageMoveTasks_cli_2_topic"></a>

次のコード例は、`list-message-move-tasks` を使用する方法を示しています。

**AWS CLI**  
**メッセージ移動タスクを一覧表示するには**  
次の `list-message-move-tasks` の例では、指定されたキュー内の最新のメッセージ移動タスクを 2 件、一覧表示します。  

```
aws sqs list-message-move-tasks \
    --source-arn arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue \
    --max-results 2
```
出力:  

```
{
    "Results": [
        {
            "TaskHandle": "AQEB6nR4...HzlvZQ==",
            "Status": "RUNNING",
            "SourceArn": "arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue1",
            "DestinationArn": "arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue2",
            "MaxNumberOfMessagesPerSecond": 50,
            "ApproximateNumberOfMessagesMoved": 203,
            "ApproximateNumberOfMessagesToMove": 30,
            "StartedTimestamp": 1442428276921
         },

         {
            "Status": "COMPLETED",
            "SourceArn": "arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue1",
            "DestinationArn": "arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue2",
            "ApproximateNumberOfMessagesMoved": 29,
            "ApproximateNumberOfMessagesToMove": 0,
            "StartedTimestamp": 1342428272093
         }
    ]
}
```
詳細については、「*デベロッパーガイド*」の「[Amazon SQS API permissions: Actions and resource reference](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-api-permissions-reference.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMessageMoveTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/list-message-move-tasks.html)」を参照してください。

### `list-queue-tags`
<a name="sqs_ListQueueTags_cli_2_topic"></a>

次のコード例は、`list-queue-tags` を使用する方法を示しています。

**AWS CLI**  
**キューのすべてのコスト配分タグを一覧表示するには**  
次の `list-queue-tags` の例では、指定されたキューに関連付けられているすべてのコスト配分タグを表示します。  

```
aws sqs list-queue-tags \
    --queue-url https://sqs.us-west-2.amazonaws.com/123456789012/MyQueue
```
出力:  

```
{
    "Tags": {
        "Team": "Alpha"
    }
}
```
詳細については、「*Amazon Simple Queue Service 開発者ガイド*」の「[コスト配分タグの一覧表示](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-queue-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListQueueTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/list-queue-tags.html)」を参照してください。

### `list-queues`
<a name="sqs_ListQueues_cli_2_topic"></a>

次のコード例は、`list-queues` を使用する方法を示しています。

**AWS CLI**  
**キューを一覧表示するには**  
この例は、すべてのキューを一覧表示します。  
コマンド:  

```
aws sqs list-queues
```
出力:  

```
{
  "QueueUrls": [
    "https://queue.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue",
    "https://queue.amazonaws.com/80398EXAMPLE/MyQueue",
    "https://queue.amazonaws.com/80398EXAMPLE/MyOtherQueue",
    "https://queue.amazonaws.com/80398EXAMPLE/TestQueue1",
        "https://queue.amazonaws.com/80398EXAMPLE/TestQueue2"
  ]
}
```
この例は、「My」で始まるキューのみを一覧表示します。  
コマンド:  

```
aws sqs list-queues --queue-name-prefix My
```
出力:  

```
{
  "QueueUrls": [
    "https://queue.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue",
    "https://queue.amazonaws.com/80398EXAMPLE/MyQueue",
    "https://queue.amazonaws.com/80398EXAMPLE/MyOtherQueue"
  ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListQueues](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/list-queues.html)」を参照してください。**

### `purge-queue`
<a name="sqs_PurgeQueue_cli_2_topic"></a>

次のコード例は、`purge-queue` を使用する方法を示しています。

**AWS CLI**  
**キューをクリアするには**  
この例では、指定されたキューのすべてのメッセージを削除します。  
コマンド:  

```
aws sqs purge-queue --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyNewQueue
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PurgeQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/purge-queue.html)」を参照してください。

### `receive-message`
<a name="sqs_ReceiveMessage_cli_2_topic"></a>

次のコード例は、`receive-message` を使用する方法を示しています。

**AWS CLI**  
**メッセージを受信するには**  
この例は、最大 10 件のメッセージを受信し、使用可能なすべての属性を返します。  
コマンド:  

```
aws sqs receive-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute-names All --message-attribute-names All --max-number-of-messages 10
```
出力:  

```
{
  "Messages": [
    {
      "Body": "My first message.",
      "ReceiptHandle": "AQEBzbVv...fqNzFw==",
      "MD5OfBody": "1000f835...a35411fa",
      "MD5OfMessageAttributes": "9424c491...26bc3ae7",
      "MessageId": "d6790f8d-d575-4f01-bc51-40122EXAMPLE",
      "Attributes": {
        "ApproximateFirstReceiveTimestamp": "1442428276921",
        "SenderId": "AIDAIAZKMSNQ7TEXAMPLE",
        "ApproximateReceiveCount": "5",
        "SentTimestamp": "1442428276921"
      },
      "MessageAttributes": {
        "PostalCode": {
          "DataType": "String",
          "StringValue": "ABC123"
        },
        "City": {
          "DataType": "String",
          "StringValue": "Any City"
        }
      }
    }
  ]
}
```
この例は、次に受信可能なメッセージを受信し、PostalCode メッセージ属性に加えて、SenderId 属性と SentTimestamp 属性のみを返します。  
コマンド:  

```
aws sqs receive-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute-names SenderId SentTimestamp --message-attribute-names PostalCode
```
出力:  

```
{
  "Messages": [
    {
      "Body": "My first message.",
      "ReceiptHandle": "AQEB6nR4...HzlvZQ==",
      "MD5OfBody": "1000f835...a35411fa",
      "MD5OfMessageAttributes": "b8e89563...e088e74f",
      "MessageId": "d6790f8d-d575-4f01-bc51-40122EXAMPLE",
      "Attributes": {
        "SenderId": "AIDAIAZKMSNQ7TEXAMPLE",
        "SentTimestamp": "1442428276921"
      },
      "MessageAttributes": {
        "PostalCode": {
          "DataType": "String",
          "StringValue": "ABC123"
        }
      }
    }
  ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[ReceiveMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/receive-message.html)」を参照してください。

### `remove-permission`
<a name="sqs_RemovePermission_cli_2_topic"></a>

次のコード例は、`remove-permission` を使用する方法を示しています。

**AWS CLI**  
**アクセス許可を削除するには**  
この例では、指定されたキューから指定されたラベルを持つアクセス許可を削除します。  
コマンド:  

```
aws sqs remove-permission --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --label SendMessagesFromMyQueue
```
出力:  

```
None.
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemovePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/remove-permission.html)」を参照してください。

### `send-message-batch`
<a name="sqs_SendMessageBatch_cli_2_topic"></a>

次のコード例は、`send-message-batch` を使用する方法を示しています。

**AWS CLI**  
**複数のメッセージを一括送信するには**  
この例は、メッセージ本文、遅延期間、およびメッセージ属性を指定した 2 つのメッセージを指定されたキューに送信します。  
コマンド:  

```
aws sqs send-message-batch --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --entries file://send-message-batch.json
```
入力ファイル (send-message-batch.json):  

```
[
  {
    "Id": "FuelReport-0001-2015-09-16T140731Z",
        "MessageBody": "Fuel report for account 0001 on 2015-09-16 at 02:07:31 PM.",
        "DelaySeconds": 10,
        "MessageAttributes": {
          "SellerName": {
            "DataType": "String",
                "StringValue": "Example Store"
      },
          "City": {
        "DataType": "String",
        "StringValue": "Any City"
      },
          "Region": {
            "DataType": "String",
                "StringValue": "WA"
      },
          "PostalCode": {
            "DataType": "String",
                "StringValue": "99065"
          },
          "PricePerGallon": {
            "DataType": "Number",
                "StringValue": "1.99"
      }
        }
  },
  {
    "Id": "FuelReport-0002-2015-09-16T140930Z",
        "MessageBody": "Fuel report for account 0002 on 2015-09-16 at 02:09:30 PM.",
        "DelaySeconds": 10,
        "MessageAttributes": {
          "SellerName": {
            "DataType": "String",
                "StringValue": "Example Fuels"
      },
          "City": {
        "DataType": "String",
        "StringValue": "North Town"
      },
          "Region": {
            "DataType": "String",
                "StringValue": "WA"
      },
          "PostalCode": {
            "DataType": "String",
                "StringValue": "99123"
          },
          "PricePerGallon": {
            "DataType": "Number",
                "StringValue": "1.87"
      }
        }
  }
]
```
出力:  

```
{
  "Successful": [
    {
      "MD5OfMessageBody": "203c4a38...7943237e",
      "MD5OfMessageAttributes": "10809b55...baf283ef",
      "Id": "FuelReport-0001-2015-09-16T140731Z",
      "MessageId": "d175070c-d6b8-4101-861d-adeb3EXAMPLE"
    },
    {
      "MD5OfMessageBody": "2cf0159a...c1980595",
      "MD5OfMessageAttributes": "55623928...ae354a25",
      "Id": "FuelReport-0002-2015-09-16T140930Z",
      "MessageId": "f9b7d55d-0570-413e-b9c5-a9264EXAMPLE"
    }
  ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[SendMessageBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/send-message-batch.html)」を参照してください。

### `send-message`
<a name="sqs_SendMessage_cli_2_topic"></a>

次のコード例は、`send-message` を使用する方法を示しています。

**AWS CLI**  
**単一のメッセージを送信するには**  
この例は、指定された単一のメッセージ本文、遅延期間、メッセージ属性を含むメッセージを指定されたキューに送信します。  
コマンド:  

```
aws sqs send-message --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue --message-body "Information about the largest city in Any Region." --delay-seconds 10 --message-attributes file://send-message.json
```
入力ファイル (send-message.json):  

```
{
  "City": {
    "DataType": "String",
    "StringValue": "Any City"
  },
  "Greeting": {
    "DataType": "Binary",
    "BinaryValue": "Hello, World!"
  },
  "Population": {
    "DataType": "Number",
    "StringValue": "1250800"
  }
}
```
出力:  

```
{
  "MD5OfMessageBody": "51b0a325...39163aa0",
  "MD5OfMessageAttributes": "00484c68...59e48f06",
  "MessageId": "da68f62c-0c07-4bee-bf5f-7e856EXAMPLE"
}
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[SendMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/send-message.html)」を参照してください。

### `set-queue-attributes`
<a name="sqs_SetQueueAttributes_cli_2_topic"></a>

次のコード例は、`set-queue-attributes` を使用する方法を示しています。

**AWS CLI**  
**キューの属性を設定するには**  
この例は、指定されたキューの配信遅延時間を 10 秒、最大メッセージサイズを 128 KB (128 KB × 1,024 バイト)、メッセージ保持期間を 3 日間 (3 日 × 24 時間 × 60 分 × 60 秒)、受信メッセージ待機時間を 20 秒、デフォルトの可視性タイムアウトを 60 秒に設定します。また、この例では、指定されたデッドレターキューの最大受信数を 1,000 メッセージと関連付けます。  
コマンド:  

```
aws sqs set-queue-attributes --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyNewQueue --attributes file://set-queue-attributes.json
```
入力ファイル (set-queue-attributes.json):  

```
{
  "DelaySeconds": "10",
  "MaximumMessageSize": "131072",
  "MessageRetentionPeriod": "259200",
  "ReceiveMessageWaitTimeSeconds": "20",
  "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":\"1000\"}",
  "VisibilityTimeout": "60"
}
```
出力:  

```
None.
```
+  API の詳細については、AWS CLI コマンドリファレンス**の「[SetQueueAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/set-queue-attributes.html)」を参照してください。

### `start-message-move-task`
<a name="sqs_StartMessageMoveTask_cli_2_topic"></a>

次のコード例は、`start-message-move-task` を使用する方法を示しています。

**AWS CLI**  
*例 1: \$1メッセージ移動タスクを開始するには\$1*  
次の `start-message-move-task` の例では、メッセージ移動タスクを開始して、指定されたデッドレターキューからソースキューにメッセージをリドライブします。  

```
aws sqs start-message-move-task \
    --source-arn arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue
```
出力:  

```
{
    "TaskHandle": "AQEB6nR4...HzlvZQ=="
}
```
詳細については、「*ガイド名*」の「[トピックタイトル](https://link.to.the/topic/page)」を参照してください。  
*例 2: \$1最大速度でメッセージ移動タスクを開始するには\$1*  
次の `start-message-move-task` の例では、メッセージ移動タスクを開始して、指定されたデッドレターキューから指定された送信先キューに 1 秒あたり 50 件のメッセージという最大速度でメッセージをリドライブします。  

```
aws sqs start-message-move-task \
    --source-arn arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue1 \
    --destination-arn arn:aws:sqs:us-west-2:80398EXAMPLE:MyQueue2 \
    --max-number-of-messages-per-second 50
```
出力:  

```
{
    "TaskHandle": "AQEB6nR4...HzlvZQ=="
}
```
詳細については、「*デベロッパーガイド*」の「[Amazon SQS API permissions: Actions and resource reference](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-api-permissions-reference.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartMessageMoveTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/start-message-move-task.html)」を参照してください。

### `tag-queue`
<a name="sqs_TagQueue_cli_2_topic"></a>

次のコード例は、`tag-queue` を使用する方法を示しています。

**AWS CLI**  
**コスト配分タグをキューに追加するには**  
次の `tag-queue` の例では、指定された Amazon SQS キューにコスト配分タグを追加します。  

```
aws sqs tag-queue \
    --queue-url https://sqs.us-west-2.amazonaws.com/123456789012/MyQueue \
    --tags Priority=Highest
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Simple Queue Service 開発者ガイド*」の「[コスト配分タグの追加](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-queue-tags.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/tag-queue.html)」を参照してください。

### `untag-queue`
<a name="sqs_UntagQueue_cli_2_topic"></a>

次のコード例は、`untag-queue` を使用する方法を示しています。

**AWS CLI**  
**キューからコスト配分タグを削除するには**  
次の `untag-queue` の例では、指定された Amazon SQS キューからコスト配分タグを削除します。  

```
aws sqs untag-queue \
    --queue-url https://sqs.us-west-2.amazonaws.com/123456789012/MyQueue \
    --tag-keys "Priority"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Simple Queue Service 開発者ガイド*」の「[コスト配分タグの追加](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-queue-tags.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagQueue](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sqs/untag-queue.html)」を参照してください。

# を使用した Storage Gateway の例 AWS CLI
<a name="cli_2_storage-gateway_code_examples"></a>

次のコード例は、Storage Gateway AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `describe-gateway-information`
<a name="storage-gateway_DescribeGatewayInformation_cli_2_topic"></a>

次のコード例は、`describe-gateway-information` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイを記述するには**  
次の `describe-gateway-information` コマンドは、指定されたゲートウェイに関するメタデータを返します。記述するゲートウェイを指定するには、コマンドでゲートウェイの Amazon リソースネーム (ARN) を使用します。  
この例では、 アカウント `123456789012` の ID `sgw-12A3456B` を持つゲートウェイを指定します。  

```
aws storagegateway describe-gateway-information --gateway-arn "arn:aws:storagegateway:us-west-2:123456789012:gateway/sgw-12A3456B"
```
このコマンドは、名前、ネットワークインターフェイス、設定したタイムゾーン、および状態 (ゲートウェイが実行中かどうか) など、ゲートウェイに関するメタデータを含む JSON ブロックを出力します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGatewayInformation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/storagegateway/describe-gateway-information.html)」を参照してください。

### `list-file-shares`
<a name="storage-gateway_ListFileShares_cli_2_topic"></a>

次のコード例は、`list-file-shares` を使用する方法を示しています。

**AWS CLI**  
**ファイル共有を一覧表示するには**  
次の の`command-name`例では、 AWS アカウントで使用可能なウィジェットを一覧表示します。  

```
aws storagegateway list-file-shares \
    --gateway-arn arn:aws:storagegateway:us-east-1:209870788375:gateway/sgw-FB02E292
```
出力:  

```
{
    "FileShareInfoList": [
        {
            "FileShareType": "NFS",
            "FileShareARN": "arn:aws:storagegateway:us-east-1:111122223333:share/share-2FA12345",
            "FileShareId": "share-2FA12345",
            "FileShareStatus": "AVAILABLE",
            "GatewayARN": "arn:aws:storagegateway:us-east-1:111122223333:gateway/sgw-FB0AAAAA"
        }
    ],
    "Marker": null
}
```
詳細については、「*AWS Storage Gateway Service API Reference*」の「[ListFileShares](https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListFileShares.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListFileShares](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/storagegateway/list-file-shares.html)」を参照してください。

### `list-gateways`
<a name="storage-gateway_ListGateways_cli_2_topic"></a>

次のコード例は、`list-gateways` を使用する方法を示しています。

**AWS CLI**  
**アカウントのゲートウェイを一覧表示するには**  
次の `list-gateways` コマンドは、アカウントに定義されているすべてのゲートウェイを一覧表示します。  

```
aws storagegateway list-gateways
```
このコマンドは、ゲートウェイの Amazon リソースネーム (ARN) のリストを含む JSON ブロックを出力します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/storagegateway/list-gateways.html)」を参照してください。

### `list-volumes`
<a name="storage-gateway_ListVolumes_cli_2_topic"></a>

次のコード例は、`list-volumes` を使用する方法を示しています。

**AWS CLI**  
**ゲートウェイ用に設定されたボリュームを一覧表示するには**  
次の `list-volumes` コマンドは、指定されたゲートウェイ用に設定されたボリュームのリストを返します。記述するゲートウェイを指定するには、コマンドでゲートウェイの Amazon リソースネーム (ARN) を使用します。  
この例では、アカウント `123456789012` の ID `sgw-12A3456B` を持つゲートウェイを指定します。  

```
aws storagegateway list-volumes --gateway-arn "arn:aws:storagegateway:us-west-2:123456789012:gateway/sgw-12A3456B"
```
このコマンドは、各ボリュームのタイプと ARN を含むボリュームのリストである JSON ブロックを出力します。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVolumes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/storagegateway/list-volumes.html)」を参照してください。

### `refresh-cache`
<a name="storage-gateway_RefreshCache_cli_2_topic"></a>

次のコード例は、`refresh-cache` を使用する方法を示しています。

**AWS CLI**  
**ファイル共有キャッシュを更新するには**  
次の `refresh-cache` の例では、指定されたファイル共有のキャッシュを更新します。  

```
aws storagegateway refresh-cache \
    --file-share-arn arn:aws:storagegateway:us-east-1:111122223333:share/share-2FA12345
```
出力:  

```
{
    "FileShareARN": "arn:aws:storagegateway:us-east-1:111122223333:share/share-2FA12345",
    "NotificationId": "4954d4b1-abcd-ef01-1234-97950a7d3483"
}
```
詳細については、「*AWS Storage Gateway Service API Reference*」の「[ListFileShares](https://docs.aws.amazon.com/storagegateway/latest/APIReference/API_RefreshCache.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RefreshCache](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/storagegateway/refresh-cache.html)」を参照してください。

# AWS STS を使用した の例 AWS CLI
<a name="cli_2_sts_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `assume-role-with-saml`
<a name="sts_AssumeRoleWithSaml_cli_2_topic"></a>

次のコード例は、`assume-role-with-saml` を使用する方法を示しています。

**AWS CLI**  
**SAML で認証されたロールの短期認証情報を取得するには**  
次の `assume-role-with-saml` コマンドは、IAM ロール `TestSaml` のために短期間有効な認証情報のセットを取得します。この例のリクエストは、認証時に ID プロバイダーから提供された SAML アサーションを使用して認証されます。  

```
aws sts assume-role-with-saml \
    --role-arn arn:aws:iam::123456789012:role/TestSaml \
    --principal-arn arn:aws:iam::123456789012:saml-provider/SAML-test \
    --saml-assertion "VERYLONGENCODEDASSERTIONEXAMPLExzYW1sOkF1ZGllbmNlPmJsYW5rPC9zYW1sOkF1ZGllbmNlPjwvc2FtbDpBdWRpZW5jZVJlc3RyaWN0aW9uPjwvc2FtbDpDb25kaXRpb25zPjxzYW1sOlN1YmplY3Q+PHNhbWw6TmFtZUlEIEZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOm5hbWVpZC1mb3JtYXQ6dHJhbnNpZW50Ij5TYW1sRXhhbXBsZTwvc2FtbDpOYW1lSUQ+PHNhbWw6U3ViamVjdENvbmZpcm1hdGlvbiBNZXRob2Q9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpjbTpiZWFyZXIiPjxzYW1sOlN1YmplY3RDb25maXJtYXRpb25EYXRhIE5vdE9uT3JBZnRlcj0iMjAxOS0xMS0wMVQyMDoyNTowNS4xNDVaIiBSZWNpcGllbnQ9Imh0dHBzOi8vc2lnbmluLmF3cy5hbWF6b24uY29tL3NhbWwiLz48L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbj48L3NhbWw6U3ViamVjdD48c2FtbDpBdXRoblN0YXRlbWVudCBBdXRoPD94bWwgdmpSZXNwb25zZT4="
```
出力:  

```
{
    "Issuer": "https://integ.example.com/idp/shibboleth</Issuer",
    "AssumedRoleUser": {
        "Arn": "arn:aws:sts::123456789012:assumed-role/TestSaml",
        "AssumedRoleId": "ARO456EXAMPLE789:TestSaml"
    },
    "Credentials": {
        "AccessKeyId": "ASIAV3ZUEFP6EXAMPLE",
        "SecretAccessKey": "8P+SQvWIuLnKhh8d++jpw0nNmQRBZvNEXAMPLEKEY",
        "SessionToken": "IQoJb3JpZ2luX2VjEOz////////////////////wEXAMPLEtMSJHMEUCIDoKK3JH9uGQE1z0sINr5M4jk+Na8KHDcCYRVjJCZEvOAiEA3OvJGtw1EcViOleS2vhs8VdCKFJQWPQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==",
        "Expiration": "2019-11-01T20:26:47Z"
    },
    "Audience": "https://signin.aws.amazon.com/saml",
    "SubjectType": "transient",
    "PackedPolicySize": "6",
    "NameQualifier": "SbdGOnUkh1i4+EXAMPLExL/jEvs=",
    "Subject": "SamlExample"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[一時的なセキュリティ認証情報のリクエスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithsaml)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssumeRoleWithSaml](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role-with-saml.html)」を参照してください。

### `assume-role-with-web-identity`
<a name="sts_AssumeRoleWithWebIdentity_cli_2_topic"></a>

次のコード例は、`assume-role-with-web-identity` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ID (OAuth 2."0) で認証されたロールの短期認証情報を取得するには**  
次の `assume-role-with-web-identity` コマンドは、IAM ロール `app1` のために短期間有効な認証情報のセットを取得します。リクエストは、指定されたウェブ ID プロバイダーから提供されたウェブ ID トークンを使用して認証されます。ユーザーが実行できることをさらに制限するために、2 つの追加ポリシーがセッションに適用されます。返される認証情報は、生成されてから 1 時間後に失効します。  

```
aws sts assume-role-with-web-identity \
    --duration-seconds 3600 \
    --role-session-name "app1" \
    --provider-id "www.amazon.com" \
    --policy-arns "arn:aws:iam::123456789012:policy/q=webidentitydemopolicy1","arn:aws:iam::123456789012:policy/webidentitydemopolicy2" \
    --role-arn arn:aws:iam::123456789012:role/FederatedWebIdentityRole \
    --web-identity-token "Atza%7CIQEBLjAsAhRFiXuWpUXuRvQ9PZL3GMFcYevydwIUFAHZwXZXXXXXXXXJnrulxKDHwy87oGKPznh0D6bEQZTSCzyoCtL_8S07pLpr0zMbn6w1lfVZKNTBdDansFBmtGnIsIapjI6xKR02Yc_2bQ8LZbUXSGm6Ry6_BG7PrtLZtj_dfCTj92xNGed-CrKqjG7nPBjNIL016GGvuS5gSvPRUxWES3VYfm1wl7WTI7jn-Pcb6M-buCgHhFOzTQxod27L9CqnOLio7N3gZAGpsp6n1-AJBOCJckcyXe2c6uD0srOJeZlKUm2eTDVMf8IehDVI0r1QOnTV6KzzAI3OY87Vd_cVMQ"
```
出力:  

```
{
    "SubjectFromWebIdentityToken": "amzn1.account.AF6RHO7KZU5XRVQJGXK6HB56KR2A",
    "Audience": "client.5498841531868486423.1548@apps.example.com",
    "AssumedRoleUser": {
        "Arn": "arn:aws:sts::123456789012:assumed-role/FederatedWebIdentityRole/app1",
        "AssumedRoleId": "AROACLKWSDQRAOEXAMPLE:app1"
    },
    "Credentials": {
        "AccessKeyId": "AKIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY",
        "SessionToken": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE",
        "Expiration": "2020-05-19T18:06:10+00:00"
    },
    "Provider": "www.amazon.com"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[一時的なセキュリティ認証情報のリクエスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssumeRoleWithWebIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role-with-web-identity.html)」を参照してください。

### `assume-role`
<a name="sts_AssumeRole_cli_2_topic"></a>

次のコード例は、`assume-role` を使用する方法を示しています。

**AWS CLI**  
**ロールを引き受けるには**  
次の `assume-role` コマンドは、IAM ロール `s3-access-example` のために短期間有効な認証情報のセットを取得します。  

```
aws sts assume-role \
    --role-arn arn:aws:iam::123456789012:role/xaccounts3access \
    --role-session-name s3-access-example
```
出力:  

```
{
    "AssumedRoleUser": {
        "AssumedRoleId": "AROA3XFRBF535PLBIFPI4:s3-access-example",
        "Arn": "arn:aws:sts::123456789012:assumed-role/xaccounts3access/s3-access-example"
    },
    "Credentials": {
        "SecretAccessKey": "9drTJvcXLB89EXAMPLELB8923FB892xMFI",
        "SessionToken": "AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=",
        "Expiration": "2016-03-15T00:05:07Z",
        "AccessKeyId": "ASIAJEXAMPLEXEG2JICEA"
    }
}
```
コマンドの出力には、 AWSに対する認証に使用できるアクセスキー、シークレットキー、およびセッショントークンが含まれています。  
 AWS CLI を使用するには、ロールに関連付けられた名前付きプロファイルを設定できます。プロファイルを使用すると、CLI AWS は assume-role を呼び出し、認証情報を管理します。詳細については、「 [CLI ユーザーガイド」の「 CLI AWS で IAM ロール](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-role.html)を使用する」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssumeRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html)」を参照してください。

### `assume-root`
<a name="sts_AssumeRoot_cli_2_topic"></a>

次のコード例は、`assume-root` を使用する方法を示しています。

**AWS CLI**  
**特権セッションを起動するには**  
次の `assume-root` コマンドは、組織内のメンバーアカウントの誤設定された Amazon S3 バケットポリシーを削除するために使用できる短期認証情報のセットを取得します。  

```
aws sts assume-root \
    --duration-seconds 900 \
    --target-principal 111122223333 \
    --task-policy-arn arn=arn:aws:iam::aws:policy/root-task/S3UnlockBucketPolicy
```
出力:  

```
{
    "Credentials": {
        "SecretAccessKey": "9drTJvcXLB89EXAMPLELB8923FB892xMFI",
        "SessionToken": "AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=",
        "Expiration": "2024-11-15T00:05:07Z",
        "AccessKeyId": "ASIAJEXAMPLEXEG2JICEA"
    },
    "SourceIdentity": "Alice",
}
```
コマンドの出力には、メンバーアカウントで特権アクションを実行するために使用できるアクセスキー、シークレットキー、セッショントークンが含まれています。詳細については、*AWS IAM* [ユーザーガイドの AWS 「Organizations メンバーアカウントで特権タスクを実行する](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user-privileged-task.html)」を参照してください。  
+  API の詳細については、*AWS CLI コマンドリファレンス*の「[AssumeRoot](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-root.html)」を参照してください。

### `decode-authorization-message`
<a name="sts_DecodeAuthorizationMessage_cli_2_topic"></a>

次のコード例は、`decode-authorization-message` を使用する方法を示しています。

**AWS CLI**  
**リクエストへの応答として返されるエンコードされた認可メッセージをデコードするには**  
次の `decode-authorization-message` の例では、Amazon Web Services リクエストへの応答として返されるエンコードされたメッセージから、リクエストの承認ステータスに関する追加情報をデコードします。  

```
aws sts decode-authorization-message \
    --encoded-message EXAMPLEWodyRNrtlQARDip-eTA6i6DrlUhHhPQrLWB_lAbl5pAKxl9mPDLexYcGBreyIKQC1BGBIpBKr3dFDkwqeO7e2NMk5j_hmzAiChJN-8oy3EwiCjkUW5fdRNjcRvscGlUo_MhqHqHpR-Ojau7BMjOTWwOtHPhV_Zaz87yENdipr745EjQwRd5LaoL3vN8_5ZfA9UiBMKDgVh1gjqZJFUiQoubv78V1RbHNYnK44ElGKmUWYa020I1y6TNS9LXoNmc62GzkfGvoPGhD13br5tXEOo1rAm3vsPewRDFNkYL-4_1MWWezhRNEpqvXBDXLI9xEux7YYkRtjd45NJLFzZynBUubV8NHOevVuighd1Mvz3OiA-1_oPSe4TBtjfN9s7kjU1z70WpVbUgrLVp1xXTK1rf9Ea7t8shPd-3VzKhjS5tLrweFxNOKwV2GtT76B_fRp8HTYz-pOu3FZjwYStfvTb3GHs3-6rLribGO9jZOktkfE6vqxlFzLyeDr4P2ihC1wty9tArCvvGzIAUNmARQJ2VVWPxioqgoqCzMaDMZEO7wkku7QeakEVZdf00qlNLMmcaVZb1UPNqD-JWP5pwe_mAyqh0NLw-r1S56YC_90onj9A80sNrHlI-tIiNd7tgNTYzDuPQYD2FMDBnp82V9eVmYGtPp5NIeSpuf3fOHanFuBZgENxZQZ2dlH3xJGMTtYayzZrRXjiq_SfX9zeBbpCvrD-0AJK477RM84vmtCrsUpJgx-FaoPIb8LmmKVBLpIB0iFhU9sEHPqKHVPi6jdxXqKaZaFGvYVmVOiuQdNQKuyk0p067POFrZECLjjOtNPBOZCcuEKEXAMPLE
```
出力:  

```
{
    "DecodedMessage": "{\"allowed\":false,\"explicitDeny\":true,\"matchedStatements\":{\"items\":[{\"statementId\":\"VisualEditor0\",\"effect\":\"DENY\",\"principals\":{\"items\":[{\"value\":\"AROA123456789EXAMPLE\"}]},\"principalGroups\":{\"items\":[]},\"actions\":{\"items\":[{\"value\":\"ec2:RunInstances\"}]},\"resources\":{\"items\":[{\"value\":\"*\"}]},\"conditions\":{\"items\":[]}}]},\"failures\":{\"items\":[]},\"context\":{\"principal\":{\"id\":\"AROA123456789EXAMPLE:Ana\",\"arn\":\"arn:aws:sts::111122223333:assumed-role/Developer/Ana\"},\"action\":\"RunInstances\",\"resource\":\"arn:aws:ec2:us-east-1:111122223333:instance/*\",\"conditions\":{\"items\":[{\"key\":\"ec2:MetadataHttpPutResponseHopLimit\",\"values\":{\"items\":[{\"value\":\"2\"}]}},{\"key\":\"ec2:InstanceMarketType\",\"values\":{\"items\":[{\"value\":\"on-demand\"}]}},{\"key\":\"aws:Resource\",\"values\":{\"items\":[{\"value\":\"instance/*\"}]}},{\"key\":\"aws:Account\",\"values\":{\"items\":[{\"value\":\"111122223333\"}]}},{\"key\":\"ec2:AvailabilityZone\",\"values\":{\"items\":[{\"value\":\"us-east-1f\"}]}},{\"key\":\"ec2:ebsOptimized\",\"values\":{\"items\":[{\"value\":\"false\"}]}},{\"key\":\"ec2:IsLaunchTemplateResource\",\"values\":{\"items\":[{\"value\":\"false\"}]}},{\"key\":\"ec2:InstanceType\",\"values\":{\"items\":[{\"value\":\"t2.micro\"}]}},{\"key\":\"ec2:RootDeviceType\",\"values\":{\"items\":[{\"value\":\"ebs\"}]}},{\"key\":\"aws:Region\",\"values\":{\"items\":[{\"value\":\"us-east-1\"}]}},{\"key\":\"ec2:MetadataHttpEndpoint\",\"values\":{\"items\":[{\"value\":\"enabled\"}]}},{\"key\":\"aws:Service\",\"values\":{\"items\":[{\"value\":\"ec2\"}]}},{\"key\":\"ec2:InstanceID\",\"values\":{\"items\":[{\"value\":\"*\"}]}},{\"key\":\"ec2:MetadataHttpTokens\",\"values\":{\"items\":[{\"value\":\"required\"}]}},{\"key\":\"aws:Type\",\"values\":{\"items\":[{\"value\":\"instance\"}]}},{\"key\":\"ec2:Tenancy\",\"values\":{\"items\":[{\"value\":\"default\"}]}},{\"key\":\"ec2:Region\",\"values\":{\"items\":[{\"value\":\"us-east-1\"}]}},{\"key\":\"aws:ARN\",\"values\":{\"items\":[{\"value\":\"arn:aws:ec2:us-east-1:111122223333:instance/*\"}]}}]}}}"
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[ポリシーの評価論理](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DecodeAuthorizationMessage](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/decode-authorization-message.html)」を参照してください。

### `get-caller-identity`
<a name="sts_GetCallerIdentity_cli_2_topic"></a>

次のコード例は、`get-caller-identity` を使用する方法を示しています。

**AWS CLI**  
**現在の IAM ID の詳細を取得するには**  
次の `get-caller-identity` コマンドは、リクエストの認証に使用される IAM ID に関する情報を表示します。発信者は IAM ユーザーです。  

```
aws sts get-caller-identity
```
出力:  

```
{
    "UserId": "AIDASAMPLEUSERID",
    "Account": "123456789012",
    "Arn": "arn:aws:iam::123456789012:user/DevAdmin"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCallerIdentity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/get-caller-identity.html)」を参照してください。

### `get-federation-token`
<a name="sts_GetFederationToken_cli_2_topic"></a>

次のコード例は、`get-federation-token` を使用する方法を示しています。

**AWS CLI**  
**IAM ユーザーアクセスキー認証情報を使用して一時的なセキュリティ認証情報一式を返すには**  
次の `get-federation-token` の例では、ユーザーの一時的なセキュリティ認証情報一式 (アクセスキー ID、シークレットアクセスキー、セキュリティトークンで構成) を返します。IAM ユーザーの長期的なセキュリティ認証情報を使用して、`GetFederationToken` オペレーションを呼び出す必要があります。  

```
aws sts get-federation-token \
    --name Bob \
    --policy file://myfile.json \
    --policy-arns arn=arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess \
    --duration-seconds 900
```
`myfile.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "elasticloadbalancing:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "cloudwatch:ListMetrics",
                "cloudwatch:GetMetricStatistics",
                "cloudwatch:Describe*"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "autoscaling:Describe*",
            "Resource": "*"
        }
    ]
}
```
出力:  

```
{
    "Credentials": {
        "AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
        "SessionToken": "EXAMPLEpZ2luX2VjEGoaCXVzLXdlc3QtMiJIMEYCIQC/W9pL5ArQyDD5JwFL3/h5+WGopQ24GEXweNctwhi9sgIhAMkg+MZE35iWM8s4r5Lr25f9rSTVPFH98G42QQunWMTfKq0DCOP//////////wEQAxoMNDUyOTI1MTcwNTA3Igxuy3AOpuuoLsk3MJwqgQPg8QOd9HuoClUxq26wnc/nm+eZLjHDyGf2KUAHK2DuaS/nrGSEXAMPLE",
        "Expiration": "2023-12-20T02:06:07+00:00"
    },
    "FederatedUser": {
        "FederatedUserId": "111122223333:Bob",
        "Arn": "arn:aws:sts::111122223333:federated-user/Bob"
    },
    "PackedPolicySize": 36
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[一時的なセキュリティ認証情報のリクエスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFederationToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/get-federation-token.html)」を参照してください。

### `get-session-token`
<a name="sts_GetSessionToken_cli_2_topic"></a>

次のコード例は、`get-session-token` を使用する方法を示しています。

**AWS CLI**  
**IAM ID のために短期間有効な認証情報のセットを取得するには**  
次の `get-session-token` コマンドは、呼び出しを実行する IAM ID のために短期間有効な認証情報のセットを取得します。結果として得られる認証情報は、ポリシーによって多要素認証 (MFA) が必要とされるリクエストのために使用できます。認証情報は生成されてから 15 分後に失効します。  

```
aws sts get-session-token \
    --duration-seconds 900 \
    --serial-number "YourMFADeviceSerialNumber" \
    --token-code 123456
```
出力:  

```
{
    "Credentials": {
        "AccessKeyId": "ASIAIOSFODNN7EXAMPLE",
        "SecretAccessKey": "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY",
        "SessionToken": "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE",
        "Expiration": "2020-05-19T18:06:10+00:00"
    }
}
```
詳細については、「*AWS IAM ユーザーガイド*」の「[一時的なセキュリティ認証情報のリクエスト](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSessionToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/get-session-token.html)」を参照してください。

# サポート を使用した の例 AWS CLI
<a name="cli_2_support_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-attachments-to-set`
<a name="support_AddAttachmentsToSet_cli_2_topic"></a>

次のコード例は、`add-attachments-to-set` を使用する方法を示しています。

**AWS CLI**  
**セットに添付ファイルを追加するには**  
次の`add-attachments-to-set`例では、 AWS アカウントでサポートケースに指定できるイメージをセットに追加します。  

```
aws support add-attachments-to-set \
    --attachment-set-id "as-2f5a6faa2a4a1e600-mu-nk5xQlBr70-G1cUos5LZkd38KOAHZa9BMDVzNEXAMPLE" \
    --attachments fileName=troubleshoot-screenshot.png,data=base64-encoded-string
```
出力:  

```
{
    "attachmentSetId": "as-2f5a6faa2a4a1e600-mu-nk5xQlBr70-G1cUos5LZkd38KOAHZa9BMDVzNEXAMPLE",
    "expiryTime": "2020-05-14T17:04:40.790+0000"
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddAttachmentsToSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/add-attachments-to-set.html)」を参照してください。

### `add-communication-to-case`
<a name="support_AddCommunicationToCase_cli_2_topic"></a>

次のコード例は、`add-communication-to-case` を使用する方法を示しています。

**AWS CLI**  
**ケースに通信を追加するには**  
次の の`add-communication-to-case`例では、 AWS アカウントのサポートケースに通信を追加します。  

```
aws support add-communication-to-case \
    --case-id "case-12345678910-2013-c4c1d2bf33c5cf47" \
    --communication-body "I'm attaching a set of images to this case." \
    --cc-email-addresses "myemail@example.com" \
    --attachment-set-id "as-2f5a6faa2a4a1e600-mu-nk5xQlBr70-G1cUos5LZkd38KOAHZa9BMDVzNEXAMPLE"
```
出力:  

```
{
    "result": true
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddCommunicationToCase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/add-communication-to-case.html)」を参照してください。

### `create-case`
<a name="support_CreateCase_cli_2_topic"></a>

次のコード例は、`create-case` を使用する方法を示しています。

**AWS CLI**  
**ケースを作成する**  
次の の`create-case`例では、 AWS アカウントのサポートケースを作成します。  

```
aws support create-case \
    --category-code "using-aws" \
    --cc-email-addresses "myemail@example.com" \
    --communication-body "I want to learn more about an AWS service." \
    --issue-type "technical" \
    --language "en" \
    --service-code "general-info" \
    --severity-code "low" \
    --subject "Question about my account"
```
出力:  

```
{
    "caseId": "case-12345678910-2013-c4c1d2bf33c5cf47"
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCase](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/create-case.html)」を参照してください。

### `describe-attachment`
<a name="support_DescribeAttachment_cli_2_topic"></a>

次のコード例は、`describe-attachment` を使用する方法を示しています。

**AWS CLI**  
**添付ファイルについて説明する**  
次の `describe-attachment` の例では、指定された ID の添付ファイルに関する情報を返します。  

```
aws support describe-attachment \
    --attachment-id "attachment-KBnjRNrePd9D6Jx0-Mm00xZuDEaL2JAj_0-gJv9qqDooTipsz3V1Nb19rCfkZneeQeDPgp8X1iVJyHH7UuhZDdNeqGoduZsPrAhyMakqlc60-iJjL5HqyYGiT1FG8EXAMPLE"
```
出力:  

```
{
    "attachment": {
        "fileName": "troubleshoot-screenshot.png",
        "data": "base64-blob"
    }
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[describe-attachment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-attachment.html)」を参照してください。

### `describe-cases`
<a name="support_DescribeCases_cli_2_topic"></a>

次のコード例は、`describe-cases` を使用する方法を示しています。

**AWS CLI**  
**ケースについて説明する**  
次の の`describe-cases`例では、 AWS アカウントで指定されたサポートケースに関する情報を返します。  

```
aws support describe-cases \
    --display-id "1234567890" \
    --after-time "2020-03-23T21:31:47.774Z" \
    --include-resolved-cases \
    --language "en" \
    --no-include-communications \
    --max-item 1
```
出力:  

```
{
    "cases": [
        {
            "status": "resolved",
            "ccEmailAddresses": [],
            "timeCreated": "2020-03-23T21:31:47.774Z",
            "caseId": "case-12345678910-2013-c4c1d2bf33c5cf47",
            "severityCode": "low",
            "language": "en",
            "categoryCode": "using-aws",
            "serviceCode": "general-info",
            "submittedBy": "myemail@example.com",
            "displayId": "1234567890",
            "subject": "Question about my account"
        }
    ]
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファンレンス*」の「[DescribeCases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-cases.html)」を参照してください。

### `describe-communications`
<a name="support_DescribeCommunications_cli_2_topic"></a>

次のコード例は、`describe-communications` を使用する方法を示しています。

**AWS CLI**  
**ケースの最新のコミュニケーションについて説明する**  
次の の`describe-communications`例では、 AWS アカウントで指定されたサポートケースの最新通信を返します。  

```
aws support describe-communications \
    --case-id "case-12345678910-2013-c4c1d2bf33c5cf47" \
    --after-time "2020-03-23T21:31:47.774Z" \
    --max-item 1
```
出力:  

```
{
    "communications": [
        {
            "body": "I want to learn more about an AWS service.",
            "attachmentSet": [],
            "caseId": "case-12345678910-2013-c4c1d2bf33c5cf47",
            "timeCreated": "2020-05-12T23:12:35.000Z",
            "submittedBy": "Amazon Web Services"
        }
    ],
    "NextToken": "eyJuZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQEXAMPLE=="
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeCommunications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-communications.html)」を参照してください。

### `describe-services`
<a name="support_DescribeServices_cli_2_topic"></a>

次の例は、`describe-services` を使用する方法を説明しています。

**AWS CLI**  
** AWS サービスとサービスカテゴリを一覧表示するには**  
次の `describe-services` の例では、一般的な情報をリクエストするためのサービスカテゴリを一覧表示します。  

```
aws support describe-services \
    --service-code-list "general-info"
```
出力:  

```
{
    "services": [
        {
            "code": "general-info",
            "name": "General Info and Getting Started",
            "categories": [
                {
                    "code": "charges",
                    "name": "How Will I Be Charged?"
                },
                {
                    "code": "gdpr-queries",
                    "name": "Data Privacy Query"
                },
                {
                    "code": "reserved-instances",
                    "name": "Reserved Instances"
                },
                {
                    "code": "resource",
                    "name": "Where is my Resource?"
                },
                {
                    "code": "using-aws",
                    "name": "Using AWS & Services"
                },
                {
                    "code": "free-tier",
                    "name": "Free Tier"
                },
                {
                    "code": "security-and-compliance",
                    "name": "Security & Compliance"
                },
                {
                    "code": "account-structure",
                    "name": "Account Structure"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-services.html)」を参照してください。

### `describe-severity-levels`
<a name="support_DescribeSeverityLevels_cli_2_topic"></a>

次のコード例は、`describe-severity-levels` を使用する方法を示しています。

**AWS CLI**  
**利用可能な重要度レベルを一覧表示する**  
次の `describe-severity-levels` の例では、サポートケースの重要度レベルを一覧表示します。  

```
aws support describe-severity-levels
```
出力:  

```
{
    "severityLevels": [
        {
            "code": "low",
            "name": "Low"
        },
        {
            "code": "normal",
            "name": "Normal"
        },
        {
            "code": "high",
            "name": "High"
        },
        {
            "code": "urgent",
            "name": "Urgent"
        },
        {
            "code": "critical",
            "name": "Critical"
        }
    ]
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Choosing an initial support case severity level](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html#choosing-severity)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSeverityLevels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-severity-levels.html)」を参照してください。

### `describe-trusted-advisor-check-refresh-statuses`
<a name="support_DescribeTrustedAdvisorCheckRefreshStatuses_cli_2_topic"></a>

次の例は、`describe-trusted-advisor-check-refresh-statuses` を使用する方法を説明しています。

**AWS CLI**  
** AWS Trusted Advisor チェックの更新ステータスを一覧表示するには**  
次の `describe-trusted-advisor-check-refresh-statuses` の例では、Amazon S3 バケットのアクセス許可と IAM の使用という 2 つの Trusted Advisor チェックの更新ステータスを一覧表示します。  

```
aws support describe-trusted-advisor-check-refresh-statuses \
    --check-id "Pfx0RwqBli" "zXCkfM1nI3"
```
出力:  

```
{
    "statuses": [
        {
            "checkId": "Pfx0RwqBli",
            "status": "none",
            "millisUntilNextRefreshable": 0
        },
        {
            "checkId": "zXCkfM1nI3",
            "status": "none",
            "millisUntilNextRefreshable": 0
        }
    ]
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[AWS Trusted Advisor](https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrustedAdvisorCheckRefreshStatuses](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-trusted-advisor-check-refresh-statuses.html)」を参照してください。

### `describe-trusted-advisor-check-result`
<a name="support_DescribeTrustedAdvisorCheckResult_cli_2_topic"></a>

次の例は、`describe-trusted-advisor-check-result` を使用する方法を説明しています。

**AWS CLI**  
** AWS Trusted Advisorチェックの結果を一覧表示するには**  
次の `describe-trusted-advisor-check-result` の例では、IAM 使用チェックの結果を一覧表示します。  

```
aws support describe-trusted-advisor-check-result \
    --check-id "zXCkfM1nI3"
```
出力:  

```
{
    "result": {
        "checkId": "zXCkfM1nI3",
        "timestamp": "2020-05-13T21:38:05Z",
        "status": "ok",
        "resourcesSummary": {
            "resourcesProcessed": 1,
            "resourcesFlagged": 0,
            "resourcesIgnored": 0,
            "resourcesSuppressed": 0
        },
        "categorySpecificSummary": {
            "costOptimizing": {
                "estimatedMonthlySavings": 0.0,
                "estimatedPercentMonthlySavings": 0.0
            }
        },
        "flaggedResources": [
            {
                "status": "ok",
                "resourceId": "47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZEXAMPLE",
                "isSuppressed": false
            }
        ]
    }
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[AWS Trusted Advisor](https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrustedAdvisorCheckResult](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-trusted-advisor-check-result.html)」を参照してください。

### `describe-trusted-advisor-check-summaries`
<a name="support_DescribeTrustedAdvisorCheckSummaries_cli_2_topic"></a>

次の例は、`describe-trusted-advisor-check-summaries` を使用する方法を説明しています。

**AWS CLI**  
** AWS Trusted Advisor チェックの概要を一覧表示するには**  
次の `describe-trusted-advisor-check-summaries` の例では、Amazon S3 バケットのアクセス許可と IAM の使用という 2 つの Trusted Advisor チェックの結果を一覧表示します。  

```
aws support describe-trusted-advisor-check-summaries \
    --check-ids "Pfx0RwqBli" "zXCkfM1nI3"
```
出力:  

```
{
    "summaries": [
        {
            "checkId": "Pfx0RwqBli",
            "timestamp": "2020-05-13T21:38:12Z",
            "status": "ok",
            "hasFlaggedResources": true,
            "resourcesSummary": {
                "resourcesProcessed": 44,
                "resourcesFlagged": 0,
                "resourcesIgnored": 0,
                "resourcesSuppressed": 0
            },
            "categorySpecificSummary": {
                "costOptimizing": {
                    "estimatedMonthlySavings": 0.0,
                    "estimatedPercentMonthlySavings": 0.0
                }
            }
        },
        {
            "checkId": "zXCkfM1nI3",
            "timestamp": "2020-05-13T21:38:05Z",
            "status": "ok",
            "hasFlaggedResources": true,
            "resourcesSummary": {
                "resourcesProcessed": 1,
                "resourcesFlagged": 0,
                "resourcesIgnored": 0,
                "resourcesSuppressed": 0
            },
            "categorySpecificSummary": {
                "costOptimizing": {
                    "estimatedMonthlySavings": 0.0,
                    "estimatedPercentMonthlySavings": 0.0
                }
            }
        }
    ]
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[AWS Trusted Advisor](https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrustedAdvisorCheckSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-trusted-advisor-check-summaries.html)」を参照してください。

### `describe-trusted-advisor-checks`
<a name="support_DescribeTrustedAdvisorChecks_cli_2_topic"></a>

次の例は、`describe-trusted-advisor-checks` を使用する方法を説明しています。

**AWS CLI**  
** AWS Trusted Advisorチェックを一覧表示するには**  
次の の`describe-trusted-advisor-checks`例では、 AWS アカウントで利用可能な Trusted Advisor チェックを一覧表示します。この情報には、チェック名、ID、説明、カテゴリ、メタデータが含まれます。読みやすくするために、出力が短縮されることに注意してください。  

```
aws support describe-trusted-advisor-checks \
    --language "en"
```
出力:  

```
{
    "checks": [
        {
            "id": "zXCkfM1nI3",
            "name": "IAM Use",
            "description": "Checks for your use of AWS Identity and Access Management (IAM). You can use IAM to create users, groups, and roles in AWS, and you can use permissions to control access to AWS resources. \n<br>\n<br>\n<b>Alert Criteria</b><br>\nYellow: No IAM users have been created for this account.\n<br>\n<br>\n<b>Recommended Action</b><br>\nCreate one or more IAM users and groups in your account. You can then create additional users whose permissions are limited to perform specific tasks in your AWS environment. For more information, see <a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMGettingStarted.html\" target=\"_blank\">Getting Started</a>. \n<br><br>\n<b>Additional Resources</b><br>\n<a href=\"https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_Introduction.html\" target=\"_blank\">What Is IAM?</a>",
            "category": "security",
            "metadata": []
        }
    ]
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[AWS Trusted Advisor](https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTrustedAdvisorChecks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/describe-trusted-advisor-checks.html)」を参照してください。

### `refresh-trusted-advisor-check`
<a name="support_RefreshTrustedAdvisorCheck_cli_2_topic"></a>

次の例は、`refresh-trusted-advisor-check` を使用する方法を説明しています。

**AWS CLI**  
** AWS Trusted Advisor チェックを更新するには**  
次の の`refresh-trusted-advisor-check`例では、 AWS アカウントの Amazon S3 Bucket Permissions Trusted Advisor チェックを更新します。  

```
aws support refresh-trusted-advisor-check \
    --check-id "Pfx0RwqBli"
```
出力:  

```
{
    "status": {
        "checkId": "Pfx0RwqBli",
        "status": "enqueued",
        "millisUntilNextRefreshable": 3599992
    }
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[AWS Trusted Advisor](https://docs.aws.amazon.com/awssupport/latest/user/trusted-advisor.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RefreshTrustedAdvisorCheck](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/refresh-trusted-advisor-check.html)」を参照してください。

### `resolve-case`
<a name="support_ResolveCase_cli_2_topic"></a>

次のコード例は、`resolve-case` を使用する方法を示しています。

**AWS CLI**  
**サポートケースを解決する**  
次の の`resolve-case`例では、 AWS アカウントのサポートケースを解決します。  

```
aws support resolve-case \
    --case-id "case-12345678910-2013-c4c1d2bf33c5cf47"
```
出力:  

```
{
    "finalCaseStatus": "resolved",
    "initialCaseStatus": "work-in-progress"
}
```
詳細については、「*AWS サポートユーザーガイド*」の「[Creating support cases and case management](https://docs.aws.amazon.com/awssupport/latest/user/case-management.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[resolve-case](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/support/resolve-case.html)」を参照してください。

# を使用した Amazon SWF の例 AWS CLI
<a name="cli_2_swf_code_examples"></a>

次のコード例は、Amazon SWF AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `count-closed-workflow-executions`
<a name="swf_CountClosedWorkflowExecutions_cli_2_topic"></a>

次のコード例は、`count-closed-workflow-executions` を使用する方法を示しています。

**AWS CLI**  
**クローズドワークフロー実行数のカウント**  
`swf count-closed-workflow-executions` を使用して、特定のドメインのクローズドワークフロー実行数を取得できます。フィルターを指定して、特定の実行クラスをカウントできます。  
`--domain` および `--close-time-filter` または `--start-time-filter` のうち*いずれか*の引数は必須です。その他の引数はオプションです。  

```
aws swf count-closed-workflow-executions \
    --domain DataFrobtzz \
    --close-time-filter "{ \"latestDate\" : 1377129600, \"oldestDate\" : 1370044800 }"
```
出力:  

```
{
    "count": 2,
    "truncated": false
}
```
「切り捨てられた」が `true` の場合、「カウント」は Amazon SWF によって返される最大数を表します。それ以降の結果は切り捨てられます。  
返される結果の数を減らすには、次の操作を行います。  
`--close-time-filter` または `--start-time-filter` 値を変更して、検索する時間範囲を絞り込みます。これらはそれぞれ相互に排他的です。リクエストで指定できるのは*これらのうちの 1 つのみ*です。`--close-status-filter`、`--execution-filter`、`--tag-filter`または `--type-filter` 引数を使用して結果をさらにフィルタリングします。ただし、これらの引数も相互に排他的です。  
「*Amazon Simple Workflow Service API リファレンス*」の「[CountClosedWorkflowExecutions](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_CountClosedWorkflowExecutions.html)」も参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CountClosedWorkflowExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/count-closed-workflow-executions.html)」を参照してください。

### `count-open-workflow-executions`
<a name="swf_CountOpenWorkflowExecutions_cli_2_topic"></a>

次のコード例は、`count-open-workflow-executions` を使用する方法を示しています。

**AWS CLI**  
**オープンワークフロー実行数のカウント**  
`swf count-open-workflow-executions` を使用して、特定のドメインのオープンワークフロー実行数を取得できます。フィルターを指定して、特定の実行クラスをカウントできます。  
`--domain` および `--start-time-filter` 引数は必須です。その他の引数はオプションです。  

```
aws swf count-open-workflow-executions \
    --domain DataFrobtzz \
    --start-time-filter "{ \"latestDate\" : 1377129600, \"oldestDate\" : 1370044800 }"
```
出力:  

```
{
    "count": 4,
    "truncated": false
}
```
「切り捨てられた」が `true` の場合、「カウント」は Amazon SWF によって返される最大数を表します。それ以降の結果は切り捨てられます。  
返される結果の数を減らすには、次の操作を行います。  
`--start-time-filter` 値を変更して、検索する時間範囲を絞り込みます。`--close-status-filter`、`--execution-filter`、`--tag-filter` または `--type-filter` 引数を使用して、結果をさらにフィルタリングします。これらはそれぞれ相互に排他的です。リクエストで指定できるのは、*これらのうちの 1 つのみ*です。  
詳細については、「*Amazon Simple Workflow Service API リファレンス*」の「CountOpenWorkflowExecutions」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CountOpenWorkflowExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/count-open-workflow-executions.html)」を参照してください。

### `deprecate-domain`
<a name="swf_DeprecateDomain_cli_2_topic"></a>

次のコード例は、`deprecate-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインの廃止**  
ドメインを廃止するには、`swf deprecate-domain` を使用します(まだ表示できますが、新しいワークフロー実行の作成、またはタイプを登録することはできません)。これには、唯一の必須パラメータ `--name` があり、廃止するドメイン名を取得します。  

```
aws swf deprecate-domain \
    --name MyNeatNewDomain ""
```
`register-domain` と同様に、出力は返されません。ただし、登録したドメインを表示するために `list-domains` を使用する場合、ドメインが廃止され、返されたデータに表示されなくなります。  

```
aws swf list-domains \
    --registration-status REGISTERED
        {
            "domainInfos": [
                {
                    "status": "REGISTERED",
                    "name": "DataFrobotz"
                },
                {
                    "status": "REGISTERED",
                    "name": "erontest"
                }
            ]
        }
```
`list-domains` で `--registration-status DEPRECATED` を使用すると、廃止されたドメインが表示されます。  

```
aws swf list-domains \
    --registration-status DEPRECATED
        {
            "domainInfos": [
                {
                    "status": "DEPRECATED",
                    "name": "MyNeatNewDomain"
                }
            ]
        }
```
また、`describe-domain` を使用して、廃止されたドメインに関する情報を取得できます。  

```
aws swf describe-domain \
    --name MyNeatNewDomain
        {
            "domainInfo": {
                "status": "DEPRECATED",
                "name": "MyNeatNewDomain"
            },
            "configuration": {
                "workflowExecutionRetentionPeriodInDays": "0"
            }
        }
```
「*Amazon Simple Workflow Service API リファレンス*」の「[DeprecateDomain](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_DeprecateDomain.html)」も参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeprecateDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/deprecate-domain.html)」を参照してください。

### `describe-domain`
<a name="swf_DescribeDomain_cli_2_topic"></a>

次のコード例は、`describe-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインに関する情報の取得**  
特定のドメインに関する詳細情報を表示するには、`swf describe-domain` コマンドを使用します。`--name` という必須パラメータが 1 つあり、これは情報が必要なドメインの名前を取得します。  

```
aws swf describe-domain \
    --name DataFrobotz
        {
            "domainInfo": {
                "status": "REGISTERED",
                "name": "DataFrobotz"
            },
            "configuration": {
                "workflowExecutionRetentionPeriodInDays": "1"
            }
        }
```
また、`describe-domain` を使用して、廃止されたドメインに関する情報を取得できます。  

```
aws swf describe-domain \
    --name MyNeatNewDomain
        {
            "domainInfo": {
                "status": "DEPRECATED",
                "name": "MyNeatNewDomain"
            },
            "configuration": {
                "workflowExecutionRetentionPeriodInDays": "0"
            }
        }
```
「*Amazon Simple Workflow Service API リファレンス*」の「[DescribeDomain](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_DescribeDomain.html)」も参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/describe-domain.html)」を参照してください。

### `list-activity-types`
<a name="swf_ListActivityTypes_cli_2_topic"></a>

次のコード例は、`list-activity-types` を使用する方法を示しています。

**AWS CLI**  
**アクティビティタイプの一覧表示**  
ドメインのアクティビティタイプのリストを取得するには、`swf list-activity-types` を使用します。`--domain` および `--registration-status` 引数は必須です。  

```
aws swf list-activity-types \
    --domain DataFrobtzz \
    --registration-status REGISTERED
```
出力:  

```
{
    "typeInfos": [
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.451,
            "activityType": {
                "version": "1",
                "name": "confirm-user-email"
            },
            "description": "subscribe confirm-user-email activity"
        },
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.709,
            "activityType": {
                "version": "1",
                "name": "confirm-user-phone"
            },
            "description": "subscribe confirm-user-phone activity"
        },
        {
            "status": "REGISTERED",
            "creationDate": 1371454149.871,
            "activityType": {
                "version": "1",
                "name": "get-subscription-info"
            },
            "description": "subscribe get-subscription-info activity"
        },
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.909,
            "activityType": {
                "version": "1",
                "name": "send-subscription-success"
            },
            "description": "subscribe send-subscription-success activity"
        },
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.085,
            "activityType": {
                "version": "1",
                "name": "subscribe-user-sns"
            },
            "description": "subscribe subscribe-user-sns activity"
        }
    ]
}
```
`--name` 引数を使用して、特定の名前のアクティビティタイプのみを選択できます。  

```
aws swf list-activity-types \
    --domain DataFrobtzz \
    --registration-status REGISTERED \
    --name "send-subscription-success"
```
出力:  

```
{
    "typeInfos": [
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.909,
            "activityType": {
                "version": "1",
                "name": "send-subscription-success"
            },
            "description": "subscribe send-subscription-success activity"
        }
    ]
}
```
ページで結果を取得するには、`--maximum-page-size` 引数を設定します。結果のページに収まるよりも多くの結果が返された場合、「nextPageToken」が結果セットに返されます。  

```
aws swf list-activity-types \
    --domain DataFrobtzz \
    --registration-status REGISTERED \
    --maximum-page-size 2
```
出力:  

```
{
    "nextPageToken": "AAAAKgAAAAEAAAAAAAAAA1Gp1BelJq+PmHvAnDxJYbup8+0R4LVtbXLDl7QNY7C3OpHo9Sz06D/GuFz1OyC73umBQ1tOPJ/gC/aYpzDMqUIWIA1T9W0s2DryyZX4OC/6Lhk9/o5kdsuWMSBkHhgaZjgwp3WJINIFJFdaSMxY2vYAX7AtRtpcqJuBDDRE9RaRqDGYqIYUMltarkiqpSY1ZVveBasBvlvyUb/WGAaqehiDz7/JzLT/wWNNUMOd+Nhe",
    "typeInfos": [
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.451,
            "activityType": {
                "version": "1",
                "name": "confirm-user-email"
            },
            "description": "subscribe confirm-user-email activity"
        },
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.709,
            "activityType": {
                "version": "1",
                "name": "confirm-user-phone"
            },
            "description": "subscribe confirm-user-phone activity"
        }
    ]
}
```
nextPageToken 値を `--next-page-token` 引数の `list-activity-types` への次の呼び出しに渡し、結果の次のページを取得できます。  

```
aws swf list-activity-types \
    --domain DataFrobtzz \
    --registration-status REGISTERED \
    --maximum-page-size 2 \
    --next-page-token "AAAAKgAAAAEAAAAAAAAAA1Gp1BelJq+PmHvAnDxJYbup8+0R4LVtbXLDl7QNY7C3OpHo9Sz06D/GuFz1OyC73umBQ1tOPJ/gC/aYpzDMqUIWIA1T9W0s2DryyZX4OC/6Lhk9/o5kdsuWMSBkHhgaZjgwp3WJINIFJFdaSMxY2vYAX7AtRtpcqJuBDDRE9RaRqDGYqIYUMltarkiqpSY1ZVveBasBvlvyUb/WGAaqehiDz7/JzLT/wWNNUMOd+Nhe"
```
出力:  

```
{
    "nextPageToken": "AAAAKgAAAAEAAAAAAAAAAw+7LZ4GRZPzTqBHsp2wBxWB8m1sgLCclgCuq3J+h/m3+vOfFqtkcjLwV5cc4OjNAzTCuq/XcylPumGwkjbajtqpZpbqOcVNfjFxGoi0LB2Olbvv0krbUISBvlpFPmSWpDSZJsxg5UxCcweteSlFn1PNSZ/MoinBZo8OTkjMuzcsTuKOzH9wCaR8ITcALJ3SaqHU3pyIRS5hPmFA3OLIc8zaAepjlaujo6hntNSCruB4"
    "typeInfos": [
        {
            "status": "REGISTERED",
            "creationDate": 1371454149.871,
            "activityType": {
                "version": "1",
                "name": "get-subscription-info"
            },
            "description": "subscribe get-subscription-info activity"
        },
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.909,
            "activityType": {
                "version": "1",
                "name": "send-subscription-success"
            },
            "description": "subscribe send-subscription-success activity"
        }
    ]
}
```
返す結果がまだある場合は、「nextPageToken」と結果が返されます。取得する結果のページがそれ以上存在しない場合、「nextPageToken」が結果に返されることは*ありません*。  
`--reverse-order` 引数を使用して、返された結果の順序を逆にすることができます。これはページ分割された結果にも影響します。  

```
aws swf list-activity-types \
    --domain DataFrobtzz \
    --registration-status REGISTERED \
    --maximum-page-size 2 \
    --reverse-order
```
出力:  

```
{
    "nextPageToken": "AAAAKgAAAAEAAAAAAAAAAwXcpu5ePSyQkrC+8WMbmSrenuZC2ZkIXQYBPB/b9xIOVkj+bMEFhGj0KmmJ4rF7iddhjf7UMYCsfGkEn7mk+yMCgVc1JxDWmB0EH46bhcmcLmYNQihMDmUWocpr7To6/R7CLu0St1gkFayxOidJXErQW0zdNfQaIWAnF/cwioBbXlkz1fQzmDeU3M5oYGMPQIrUqkPq7pMEW0q0lK5eDN97NzFYdZZ/rlcLDWPZhUjY",
    "typeInfos": [
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.085,
            "activityType": {
                "version": "1",
                "name": "subscribe-user-sns"
            },
            "description": "subscribe subscribe-user-sns activity"
        },
        {
            "status": "REGISTERED",
            "creationDate": 1371454150.909,
            "activityType": {
                "version": "1",
                "name": "send-subscription-success"
            },
            "description": "subscribe send-subscription-success activity"
        }
    ]
}
```
「*Amazon Simple Workflow Service API リファレンス*」の「[ListActivityTypes](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_ListActivityTypes.html)」も参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListActivityTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/list-activity-types.html)」を参照してください。

### `list-domains`
<a name="swf_ListDomains_cli_2_topic"></a>

次のコード例は、`list-domains` を使用する方法を示しています。

**AWS CLI**  
**例 1: 登録済みドメインを一覧表示するには**  
次の `list-domains` コマンド例では、アカウントに登録した `REGISTERED` SWF ドメインを一覧表示します。  

```
aws swf list-domains \
    --registration-status REGISTERED
```
出力:  

```
{
  "domainInfos": [
    {
      "status": "REGISTERED",
      "name": "DataFrobotz"
    },
    {
      "status": "REGISTERED",
      "name": "erontest"
    }
  ]
}
```
詳細については、「*Amazon Simple Workflow Service API リファレンス*」の「[ListDomains](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_ListDomains.html)」を参照してください。  
**例 2: 非推奨にされたドメインを一覧表示するには**  
次の `list-domains` コマンド例では、アカウントに登録した `DEPRECATED` SWF ドメインを一覧表示します。非推奨にされたドメインは、新しいワークフローやアクティビティを登録することはできませんが、クエリすることはできます。  

```
aws swf list-domains \
    --registration-status DEPRECATED
```
出力:  

```
{
  "domainInfos": [
    {
      "status": "DEPRECATED",
      "name": "MyNeatNewDomain"
    }
  ]
}
```
詳細については、「*Amazon Simple Workflow Service API リファレンス*」の「[ListDomains](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_ListDomains.html)」を参照してください。  
**例 3: 登録済みドメインの最初のページを一覧表示するには**  
次の `list-domains` コマンド例では、`--maximum-page-size` オプションを使用してアカウントに登録した最初のページ `REGISTERED` SWF ドメインを一覧表示します。  

```
aws swf list-domains \
    --registration-status REGISTERED \
    --maximum-page-size 1
```
出力:  

```
{
    "domainInfos": [
        {
            "status": "REGISTERED",
            "name": "DataFrobotz"
        }
    ],
"nextPageToken": "AAAAKgAAAAEAAAAAAAAAA2QJKNtidVgd49TTeNwYcpD+QKT2ynuEbibcQWe2QKrslMGe63gpS0MgZGpcpoKttL4OCXRFn98Xif557it+wSZUsvUDtImjDLvguyuyyFdIZtvIxIKEOPm3k2r4OjAGaFsGOuVbrKljvla7wdU7FYH3OlkNCP8b7PBj9SBkUyGoiAghET74P93AuVIIkdKGtQ=="
}
```
詳細については、「*Amazon Simple Workflow Service API リファレンス*」の「[ListDomains](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_ListDomains.html)」を参照してください。  
**例 4: 登録済みドメインの指定された 1 ページを一覧表示するには**  
次の `list-domains` コマンド例では、`--maximum-page-size` オプションを使用してアカウントに登録した最初のページ `REGISTERED` SWF ドメインを一覧表示します。  
`nextPageToken` 引数で `--next-page-token` の値を指定して、もう一度呼び出しを行うと、別のページの結果を取得できます。  

```
aws swf list-domains \
    --registration-status REGISTERED \
    --maximum-page-size 1 \
    --next-page-token "AAAAKgAAAAEAAAAAAAAAA2QJKNtidVgd49TTeNwYcpD+QKT2ynuEbibcQWe2QKrslMGe63gpS0MgZGpcpoKttL4OCXRFn98Xif557it+wSZUsvUDtImjDLvguyuyyFdIZtvIxIKEOPm3k2r4OjAGaFsGOuVbrKljvla7wdU7FYH3OlkNCP8b7PBj9SBkUyGoiAghET74P93AuVIIkdKGtQ=="
```
出力:  

```
{
    "domainInfos": [
        {
            "status": "REGISTERED",
            "name": "erontest"
        }
    ]
}
```
取得する結果のページがそれ以上存在しない場合、`nextPageToken` が、結果に返されることはありません。  
詳細については、「*Amazon Simple Workflow Service API リファレンス*」の「[ListDomains](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_ListDomains.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDomains](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/list-domains.html)」を参照してください。

### `list-workflow-types`
<a name="swf_ListWorkflowTypes_cli_2_topic"></a>

次のコード例は、`list-workflow-types` を使用する方法を示しています。

**AWS CLI**  
**ワークフロータイプの一覧表示**  
ドメインのワークフロータイプのリストを取得するには、`swf list-workflow-types` を使用します。`--domain` および `--registration-status` 引数は必須です。以下に簡単な例を示します。  

```
aws swf list-workflow-types \
    --domain DataFrobtzz \
    --registration-status REGISTERED
```
出力:  

```
{
    "typeInfos": [
        {
            "status": "REGISTERED",
            "creationDate": 1371454149.598,
            "description": "DataFrobtzz subscribe workflow",
            "workflowType": {
                "version": "v3",
                "name": "subscribe"
            }
        }
    ]
}
```
`list-activity-types` と同様、`--name` 引数を使用して特定の名前のワークフロータイプのみを選択し、`--next-page-token` と連携しながら `--maximum-page-size` 引数を使用して結果をページングできます。結果が返される順序を逆にするには、`--reverse-order` を使用します。  
「*Amazon Simple Workflow Service API リファレンス*」の「[ListWorkflowTypes](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_ListWorkflowTypes.html)」も参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWorkflowTypes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/list-workflow-types.html)」を参照してください。

### `register-domain`
<a name="swf_RegisterDomain_cli_2_topic"></a>

次のコード例は、`register-domain` を使用する方法を示しています。

**AWS CLI**  
**ドメインの登録**  
CLI AWS を使用して新しいドメインを登録できます。`swf register-domain` コマンドを使用します。必須パラメータは 2 つあります。ドメイン名を指定する `--name` と、このドメインのワークフロー実行データを保持する日数 (最大 90 日間) を整数で指定する `--workflow-execution-retention-period-in-days` です (詳細については「SWF に関するよくある質問」<https://aws.amazon.com/swf/faqs/\$1retain\$1limit> を参照)。ワークフロー実行データは、指定した日数が経過した後は保持されません。  

```
aws swf register-domain \
    --name MyNeatNewDomain \
    --workflow-execution-retention-period-in-days 0
    ""
```
ドメインを登録すると何も返されませんが ("")、`swf list-domains` または `swf describe-domain` を使用して、新しいドメインを表示できます。  

```
aws swf list-domains \
    --registration-status REGISTERED
        {
            "domainInfos": [
                {
                    "status": "REGISTERED",
                    "name": "DataFrobotz"
                },
                {
                    "status": "REGISTERED",
                    "name": "MyNeatNewDomain"
                },
                {
                    "status": "REGISTERED",
                    "name": "erontest"
                }
            ]
        }
```
`swf describe-domain` を使用する:  

```
aws swf describe-domain --name MyNeatNewDomain
{
    "domainInfo": {
        "status": "REGISTERED",
        "name": "MyNeatNewDomain"
    },
    "configuration": {
        "workflowExecutionRetentionPeriodInDays": "0"
    }
}
```
「*Amazon Simple Workflow Service API リファレンス*」の「[RegisterDomain](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_RegisterDomain.html)」も参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterDomain](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/register-domain.html)」を参照してください。

### `register-workflow-type`
<a name="swf_RegisterWorkflowType_cli_2_topic"></a>

次のコード例は、`register-workflow-type` を使用する方法を示しています。

**AWS CLI**  
**ワークフロータイプを登録する**  
ワークフロータイプを CLI AWS に登録するには、 `swf register-workflow-type` コマンドを使用します。  

```
aws swf register-workflow-type \
    --domain DataFrobtzz \
    --name "MySimpleWorkflow" \
    --workflow-version "v1"
```
コマンドが成功した場合、出力は生成されません。  
エラーの場合 (例えば、同じワークフローを 2 回登録しようとしたり、存在しないドメインを指定しようとしたりした場合)、JSON でレスポンスを受け取ります。  

```
{
    "message": "WorkflowType=[name=MySimpleWorkflow, version=v1]",
    "__type": "com.amazonaws.swf.base.model#TypeAlreadyExistsFault"
}
```
`--domain`、`--name`、`--workflow-version` は必須です。ワークフローの説明、タイムアウト、子ワークフローポリシーを設定することもできます。  
詳細については、「*Amazon Simple Storage Service API リファレンス*」の「[RegisterWorkflowType](https://docs.aws.amazon.com/amazonswf/latest/apireference/API_RegisterWorkflowType.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterWorkflowType](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/swf/register-workflow-type.html)」を参照してください。

# を使用した Systems Manager の例 AWS CLI
<a name="cli_2_ssm_code_examples"></a>

次のコード例は、Systems Manager AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `add-tags-to-resource`
<a name="ssm_AddTagsToResource_cli_2_topic"></a>

次のコード例は、`add-tags-to-resource` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウにタグを追加するには**  
次の `add-tags-to-resource` の例では、指定されたメンテナンスウィンドウにタグを追加します。  

```
aws ssm add-tags-to-resource \
    --resource-type "MaintenanceWindow" \
    --resource-id "mw-03eb9db428EXAMPLE" \
    --tags "Key=Stack,Value=Production"
```
このコマンドでは何も出力されません。  
**例 2: パラメータにタグを追加するには**  
次の `add-tags-to-resource` の例では、指定されたパラメータに 2 つのタグを追加します。  

```
aws ssm add-tags-to-resource \
    --resource-type "Parameter" \
    --resource-id "My-Parameter" \
    --tags '[{"Key":"Region","Value":"East"},{"Key":"Environment", "Value":"Production"}]'
```
このコマンドでは何も出力されません。  
**例 3: SSM ドキュメントにタグを追加するには**  
次の `add-tags-to-resource` の例では、指定されたドキュメントにタグを追加します。  

```
aws ssm add-tags-to-resource \
    --resource-type "Document" \
    --resource-id "My-Document" \
    --tags "Key=Quarter,Value=Q322"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager リソースにタグを付ける](https://docs.aws.amazon.com/systems-manager/latest/userguide/tagging-resources.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[AddTagsToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/add-tags-to-resource.html)」を参照してください。

### `associate-ops-item-related-item`
<a name="ssm_AssociateOpsItemRelatedItem_cli_2_topic"></a>

次のコード例は、`associate-ops-item-related-item` を使用する方法を示しています。

**AWS CLI**  
**関連項目を関連付けるには**  
次の `associate-ops-item-related-item` の例では、関連項目を OpsItem に関連付けます。  

```
aws ssm associate-ops-item-related-item \
    --ops-item-id "oi-649fExample" \
    --association-type "RelatesTo" \
    --resource-type "AWS::SSMIncidents::IncidentRecord" \
    --resource-uri "arn:aws:ssm-incidents::111122223333:incident-record/Example-Response-Plan/c2bde883-f7d5-343a-b13a-bf5fe9ea689f"
```
出力:  

```
{
    "AssociationId": "61d7178d-a30d-4bc5-9b4e-a9e74EXAMPLE"
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[OpsCenter で Incident Manager インシデントを操作する](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-create-OpsItems-for-Incident-Manager.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateOpsItemRelatedItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/associate-ops-item-related-item.html)」を参照してください。

### `cancel-command`
<a name="ssm_CancelCommand_cli_2_topic"></a>

次のコード例は、`cancel-command` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのインスタンスのコマンドをキャンセルするには**  
次の `cancel-command` の例では、すべてのインスタンスで既に実行されている、指定されたコマンドのキャンセルを試みます。  

```
aws ssm cancel-command \
    --command-id "662add3d-5831-4a10-b64a-f2ff3EXAMPLE"
```
このコマンドでは何も出力されません。  
**例 2: 特定のインスタンスのコマンドをキャンセルするには**  
次の `cancel-command` の例では、指定されたインスタンスに対してのみ実行するコマンドのキャンセルを試みます。  

```
aws ssm cancel-command \
    --command-id "662add3d-5831-4a10-b64a-f2ff3EXAMPLE"
    --instance-ids "i-02573cafcfEXAMPLE"
```
このコマンドでは何も出力されません。  
詳細については、「AWS Systems Manager ユーザーガイド」の「[Systems Manager パラメータにタグをつける](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-su-tag.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelCommand](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/cancel-command.html)」を参照してください。

### `cancel-maintenance-window-execution`
<a name="ssm_CancelMaintenanceWindowExecution_cli_2_topic"></a>

次のコード例は、`cancel-maintenance-window-execution` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウの実行をキャンセルするには**  
この `cancel-maintenance-window-execution` の例では、既に進行中の指定されたメンテナンスウィンドウの実行を停止します。  

```
aws ssm cancel-maintenance-window-execution \
    --window-execution-id j2l8d5b5c-mw66-tk4d-r3g9-1d4d1EXAMPLE
```
出力:  

```
{
    "WindowExecutionId": "j2l8d5b5c-mw66-tk4d-r3g9-1d4d1EXAMPLE"
}
```
詳細については、[「Systems Manager ユーザーガイド」の「Systems Manager メンテナンスウィンドウチュートリアル (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-tutorials.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CancelMaintenanceWindowExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/cancel-maintenance-window-execution.html)」を参照してください。

### `create-activation`
<a name="ssm_CreateActivation_cli_2_topic"></a>

次のコード例は、`create-activation` を使用する方法を示しています。

**AWS CLI**  
**マネージドインスタンスのアクティベーションを作成するには**  
次の `create-activation` の例では、マネージドインスタンスのアクティベーションを作成します。  

```
aws ssm create-activation \
    --default-instance-name "HybridWebServers" \
    --iam-role "HybridWebServersRole" \
    --registration-limit 5
```
出力:  

```
{
    "ActivationId": "5743558d-563b-4457-8682-d16c3EXAMPLE",
    "ActivationCode": "dRmgnYaFv567vEXAMPLE"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[ステップ 4: ハイブリッド環境のマネージドインスタンスアクティベーションを作成する](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-managed-instance-activation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateActivation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-activation.html)」を参照してください。

### `create-association-batch`
<a name="ssm_CreateAssociationBatch_cli_2_topic"></a>

次のコード例は、`create-association-batch` を使用する方法を示しています。

**AWS CLI**  
**複数の関連付けを削除するには**  
この例では、設定ドキュメントを複数のインスタンスに関連付けます。出力では、成功したオペレーションと失敗したオペレーションのリストが返されます (該当する場合)。  
コマンド:  

```
aws ssm create-association-batch --entries "Name=AWS-UpdateSSMAgent,InstanceId=i-1234567890abcdef0" "Name=AWS-UpdateSSMAgent,InstanceId=i-9876543210abcdef0"
```
出力:  

```
{
  "Successful": [
      {
          "Name": "AWS-UpdateSSMAgent",
          "InstanceId": "i-1234567890abcdef0",
          "AssociationVersion": "1",
          "Date": 1550504725.007,
          "LastUpdateAssociationDate": 1550504725.007,
          "Status": {
              "Date": 1550504725.007,
              "Name": "Associated",
              "Message": "Associated with AWS-UpdateSSMAgent"
          },
          "Overview": {
              "Status": "Pending",
              "DetailedStatus": "Creating"
          },
          "DocumentVersion": "$DEFAULT",
          "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
          "Targets": [
              {
                  "Key": "InstanceIds",
                  "Values": [
                      "i-1234567890abcdef0"
                  ]
              }
          ]
      },
      {
          "Name": "AWS-UpdateSSMAgent",
          "InstanceId": "i-9876543210abcdef0",
          "AssociationVersion": "1",
          "Date": 1550504725.057,
          "LastUpdateAssociationDate": 1550504725.057,
          "Status": {
              "Date": 1550504725.057,
              "Name": "Associated",
              "Message": "Associated with AWS-UpdateSSMAgent"
          },
          "Overview": {
              "Status": "Pending",
              "DetailedStatus": "Creating"
          },
          "DocumentVersion": "$DEFAULT",
          "AssociationId": "9c9f7f20-5154-4fed-a83e-0123456789ab",
          "Targets": [
              {
                  "Key": "InstanceIds",
                  "Values": [
                      "i-9876543210abcdef0"
                  ]
              }
          ]
      }
  ],
  "Failed": []
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAssociationBatch](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-association-batch.html)」を参照してください。

### `create-association`
<a name="ssm_CreateAssociation_cli_2_topic"></a>

次のコード例は、`create-association` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンス ID を使用してドキュメントを関連付けるには**  
この例では、インスタンス ID を使用して、設定ドキュメントをインスタンスに関連付けます。  

```
aws ssm create-association \
    --instance-id "i-0cb2b964d3e14fd9f" \
    --name "AWS-UpdateSSMAgent"
```
出力:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487875500.33,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-0cb2b964d3e14fd9f",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487875500.33,
        "Date": 1487875500.33,
        "Targets": [
            {
                "Values": [
                    "i-0cb2b964d3e14fd9f"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
詳細については、「*AWS Systems Manager API リファレンス*」の「[CreateAssociation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html)」を参照してください。  
**例 2: ターゲットを使用してドキュメントを関連付けるには**  
この例では、ターゲットを使用して、設定ドキュメントをインスタンスに関連付けます。  

```
aws ssm create-association \
    --name "AWS-UpdateSSMAgent" \
    --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f"
```
出力:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487875500.33,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-0cb2b964d3e14fd9f",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487875500.33,
        "Date": 1487875500.33,
        "Targets": [
            {
                "Values": [
                    "i-0cb2b964d3e14fd9f"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
詳細については、「*AWS Systems Manager API リファレンス*」の「[CreateAssociation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html)」を参照してください。  
**例 3: 1 回だけ実行される関連付けを作成するには**  
この例では、指定された日付および時刻に 1 回だけ実行される新しい関連付けを作成します。過去または現在の日付で作成された関連付け (処理されるまで日付は過去のものです) は、ただちに実行されます。  

```
aws ssm create-association \
    --name "AWS-UpdateSSMAgent" \
    --targets "Key=instanceids,Values=i-0cb2b964d3e14fd9f" \
    --schedule-expression "at(2020-05-14T15:55:00)"  \
    --apply-only-at-cron-interval
```
出力:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487875500.33,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-0cb2b964d3e14fd9f",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "AssociationId": "b7c3266e-a544-44db-877e-b20d3a108189",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487875500.33,
        "Date": 1487875500.33,
        "Targets": [
            {
                "Values": [
                    "i-0cb2b964d3e14fd9f"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
詳細については、「*AWS Systems Manager API リファレンス*」の「[CreateAssociation](https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_CreateAssociation.html)」、または「*AWS Systems Manager ユーザーガイド*」の「[リファレンス: Systems Manager の Cron 式および rate 式](https://docs.aws.amazon.com/systems-manager/latest/userguide/reference-cron-and-rate-expressions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-association.html)」を参照してください。

### `create-document`
<a name="ssm_CreateDocument_cli_2_topic"></a>

次のコード例は、`create-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントを作成するには**  
次の `create-document` の例では、新しい Systems Manager ドキュメントを作成します。  

```
aws ssm create-document \
    --content file://exampleDocument.yml \
    --name "Example" \
    --document-type "Automation" \
    --document-format YAML
```
出力:  

```
{
    "DocumentDescription": {
        "Hash": "fc2410281f40779e694a8b95975d0f9f316da8a153daa94e3d9921102EXAMPLE",
        "HashType": "Sha256",
        "Name": "Example",
        "Owner": "29884EXAMPLE",
        "CreatedDate": 1583256349.452,
        "Status": "Creating",
        "DocumentVersion": "1",
        "Description": "Document Example",
        "Parameters": [
            {
                "Name": "AutomationAssumeRole",
                "Type": "String",
                "Description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.",
                "DefaultValue": ""
            },
            {
                "Name": "InstanceId",
                "Type": "String",
                "Description": "(Required) The ID of the Amazon EC2 instance.",
                "DefaultValue": ""
            }
        ],
        "PlatformTypes": [
            "Windows",
            "Linux"
        ],
        "DocumentType": "Automation",
        "SchemaVersion": "0.3",
        "LatestVersion": "1",
        "DefaultVersion": "1",
        "DocumentFormat": "YAML",
        "Tags": []
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[SSM ドキュメントコンテンツを作成する](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-document.html)」を参照してください。

### `create-maintenance-window`
<a name="ssm_CreateMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`create-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウを作成するには**  
次の `create-maintenance-window` の例では、5 分ごとに最大 2 時間 (必要に応じて) の新しいメンテナンスウィンドウを作成し、メンテナンスウィンドウの実行終了から 1 時間以内に新しいタスクが開始されないようにします。また、関連付けられていないターゲット (メンテナンスウィンドウに登録されていないインスタンス) を許可し、カスタムタグを使用することで、その作成者がチュートリアルで使用する意図があることを示します。  

```
aws ssm create-maintenance-window \
    --name "My-Tutorial-Maintenance-Window" \
    --schedule "rate(5 minutes)" \
    --duration 2 --cutoff 1 \
    --allow-unassociated-targets \
    --tags "Key=Purpose,Value=Tutorial"
```
出力:  

```
{
    "WindowId": "mw-0c50858d01EXAMPLE"
}
```
**例 2: 1 回だけ実行されるメンテナンスウィンドウを作成するには**  
次の `create-maintenance-window` の例では、指定した日付および時刻に 1 回だけ実行される新しいメンテナンスウィンドウを作成します。  

```
aws ssm create-maintenance-window \
    --name My-One-Time-Maintenance-Window \
    --schedule "at(2020-05-14T15:55:00)" \
    --duration 5 \
    --cutoff 2 \
    --allow-unassociated-targets \
    --tags "Key=Environment,Value=Production"
```
出力:  

```
{
    "WindowId": "mw-01234567890abcdef"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Maintenance Windows](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-maintenance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-maintenance-window.html)」を参照してください。

### `create-ops-item`
<a name="ssm_CreateOpsItem_cli_2_topic"></a>

次のコード例は、`create-ops-item` を使用する方法を示しています。

**AWS CLI**  
**OpsItems を作成するには**  
次の `create-ops-item` の例は、OperationalData の /aws/resources キーを使用して、Amazon DynamoDB 関連リソースで OpsItem を作成します。  

```
aws ssm create-ops-item \
    --title "EC2 instance disk full" \
    --description "Log clean up may have failed which caused the disk to be full" \
    --priority 2 \
    --source ec2 \
    --operational-data '{"/aws/resources":{"Value":"[{\"arn\": \"arn:aws:dynamodb:us-west-2:12345678:table/OpsItems\"}]","Type":"SearchableString"}}' \
    --notifications Arn="arn:aws:sns:us-west-2:12345678:TestUser"
```
出力:  

```
{
    "OpsItemId": "oi-1a2b3c4d5e6f"
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[OpsItems の作成](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-creating-OpsItems.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateOpsItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-ops-item.html)」を参照してください。

### `create-patch-baseline`
<a name="ssm_CreatePatchBaseline_cli_2_topic"></a>

次のコード例は、`create-patch-baseline` を使用する方法を示しています。

**AWS CLI**  
**例 1: 自動承認を設定したパッチベースラインを作成するには**  
次の `create-patch-baseline` の例では、Microsoft からリリースされてから 7 日後に本番環境のパッチを承認する Windows Server のパッチベースラインを作成します。  

```
aws ssm create-patch-baseline \
    --name "Windows-Production-Baseline-AutoApproval" \
    --operating-system "WINDOWS" \
    --approval-rules "PatchRules=[{PatchFilterGroup={PatchFilters=[{Key=MSRC_SEVERITY,Values=[Critical,Important,Moderate]},{Key=CLASSIFICATION,Values=[SecurityUpdates,Updates,UpdateRollups,CriticalUpdates]}]},ApproveAfterDays=7}]" \
    --description "Baseline containing all updates approved for Windows Server production systems"
```
出力:  

```
{
    "BaselineId": "pb-045f10b4f3EXAMPLE"
}
```
**例 2: 承認のカットオフ日を設定したパッチベースラインを作成するには**  
次の `create-patch-baseline` の例では、2020 年 7 月 7 日より前にリリースされた本番環境のすべてのパッチを承認する Windows Server のパッチベースラインを作成します。  

```
aws ssm create-patch-baseline \
    --name "Windows-Production-Baseline-AutoApproval" \
    --operating-system "WINDOWS" \
    --approval-rules "PatchRules=[{PatchFilterGroup={PatchFilters=[{Key=MSRC_SEVERITY,Values=[Critical,Important,Moderate]},{Key=CLASSIFICATION,Values=[SecurityUpdates,Updates,UpdateRollups,CriticalUpdates]}]},ApproveUntilDate=2020-07-07}]" \
    --description "Baseline containing all updates approved for Windows Server production systems"
```
出力:  

```
{
    "BaselineId": "pb-045f10b4f3EXAMPLE"
}
```
**例 3: 承認ルールを JSON ファイルに保存してパッチベースラインを作成するには**  
次の `create-patch-baseline` の例では、Amazon Linux 2017.09 のパッチベースラインを作成し、リリースされてから 7 日後に本番環境のパッチを承認し、パッチベースラインの承認ルールを指定し、パッチのカスタムリポジトリを指定します。  

```
aws ssm create-patch-baseline \
    --cli-input-json file://my-amazon-linux-approval-rules-and-repo.json
```
`my-amazon-linux-approval-rules-and-repo.json` の内容:  

```
{
    "Name": "Amazon-Linux-2017.09-Production-Baseline",
    "Description": "My approval rules patch baseline for Amazon Linux 2017.09 instances",
    "OperatingSystem": "AMAZON_LINUX",
    "Tags": [
        {
            "Key": "Environment",
            "Value": "Production"
        }
    ],
    "ApprovalRules": {
        "PatchRules": [
            {
                "ApproveAfterDays": 7,
                "EnableNonSecurity": true,
                "PatchFilterGroup": {
                    "PatchFilters": [
                        {
                            "Key": "SEVERITY",
                            "Values": [
                                "Important",
                                "Critical"
                            ]
                        },
                        {
                            "Key": "CLASSIFICATION",
                            "Values": [
                                "Security",
                                "Bugfix"
                            ]
                        },
                        {
                            "Key": "PRODUCT",
                            "Values": [
                                "AmazonLinux2017.09"
                            ]
                        }
                    ]
                }
            }
        ]
    },
    "Sources": [
        {
            "Name": "My-AL2017.09",
            "Products": [
                "AmazonLinux2017.09"
            ],
            "Configuration": "[amzn-main] \nname=amzn-main-Base\nmirrorlist=http://repo./$awsregion./$awsdomain//$releasever/main/mirror.list //nmirrorlist_expire=300//nmetadata_expire=300 \npriority=10 \nfailovermethod=priority \nfastestmirror_enabled=0 \ngpgcheck=1 \ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-amazon-ga \nenabled=1 \nretries=3 \ntimeout=5\nreport_instanceid=yes"
        }
    ]
}
```
**例 4: 承認するパッチと拒否するパッチを指定したパッチベースラインを作成するには**  
次の `create-patch-baseline` の例では、デフォルトの承認ルールの例外として、承認するパッチと拒否するパッチを明示的に指定します。  

```
aws ssm create-patch-baseline \
    --name "Amazon-Linux-2017.09-Alpha-Baseline" \
    --description "My custom approve/reject patch baseline for Amazon Linux 2017.09 instances" \
    --operating-system "AMAZON_LINUX" \
    --approved-patches "CVE-2018-1234567,example-pkg-EE-2018*.amzn1.noarch" \
    --approved-patches-compliance-level "HIGH" \
    --approved-patches-enable-non-security \
    --tags "Key=Environment,Value=Alpha"
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[カスタムパッチベースラインを作成する](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baseline-console.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-patch-baseline.html)」を参照してください。

### `create-resource-data-sync`
<a name="ssm_CreateResourceDataSync_cli_2_topic"></a>

次のコード例は、`create-resource-data-sync` を使用する方法を示しています。

**AWS CLI**  
**リソースデータの同期を作成するには**  
この例では、リソースデータの同期を作成します。コマンドが成功した場合、出力はありません。  
コマンド:  

```
aws ssm create-resource-data-sync --sync-name "ssm-resource-data-sync" --s3-destination "BucketName=ssm-bucket,Prefix=inventory,SyncFormat=JsonSerDe,Region=us-east-1"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResourceDataSync](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/create-resource-data-sync.html)」を参照してください。

### `delete-activation`
<a name="ssm_DeleteActivation_cli_2_topic"></a>

次のコード例は、`delete-activation` を使用する方法を示しています。

**AWS CLI**  
**マネージドインスタンスのアクティベーションを削除するには**  
次の `delete-activation` の例では、マネージドインスタンスのアクティベーションを削除します。  

```
aws ssm delete-activation \
    --activation-id "aa673477-d926-42c1-8757-1358cEXAMPLE"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「Systems Manager ユーザーガイド」の「ハイブリッド環境用の Systems Manager のセットアップ](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteActivation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-activation.html)」を参照してください。

### `delete-association`
<a name="ssm_DeleteAssociation_cli_2_topic"></a>

次のコード例は、`delete-association` を使用する方法を示しています。

**AWS CLI**  
**例 1: 関連付け ID を使用して関連付けを削除するには**  
次の `delete-association` の例では、指定された関連付け ID の関連付けを削除します。コマンドが成功した場合、出力はありません。  

```
aws ssm delete-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの編集と新しいバージョンの作成](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)」を参照してください。  
**例 2: 関連付けを削除するには**  
次の `delete-association` の例では、インスタンスとドキュメント間の関連付けを削除します。コマンドが成功した場合、出力はありません。  

```
aws ssm delete-association \
    --instance-id "i-1234567890abcdef0" \
    --name "AWS-UpdateSSMAgent"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager の関連付けの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-association.html)」を参照してください。

### `delete-document`
<a name="ssm_DeleteDocument_cli_2_topic"></a>

次のコード例は、`delete-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントを削除するには**  
次の `delete-document` の例では、Systems Manager ドキュメントを削除します。  

```
aws ssm delete-document \
    --name "Example"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[SSM ドキュメントコンテンツを作成する](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-document.html)」を参照してください。

### `delete-inventory`
<a name="ssm_DeleteInventory_cli_2_topic"></a>

次のコード例は、`delete-inventory` を使用する方法を示しています。

**AWS CLI**  
**カスタムインベントリタイプを削除するには**  
この例では、カスタムインベントリスキーマを削除します。  
コマンド:  

```
aws ssm delete-inventory --type-name "Custom:RackInfo" --schema-delete-option "DeleteSchema"
```
出力:  

```
{
  "DeletionId": "d72ac9e8-1f60-4d40-b1c6-bf8c78c68c4d",
  "TypeName": "Custom:RackInfo",
  "DeletionSummary": {
      "TotalCount": 1,
      "RemainingCount": 1,
      "SummaryItems": [
          {
              "Version": "1.0",
              "Count": 1,
              "RemainingCount": 1
          }
      ]
  }
}
```
**カスタムインベントリタイプを無効にするには**  
この例では、カスタムインベントリスキーマを無効にします。  
コマンド:  

```
aws ssm delete-inventory --type-name "Custom:RackInfo" --schema-delete-option "DisableSchema"
```
出力:  

```
{
  "DeletionId": "6961492a-8163-44ec-aa1e-923364dd0850",
  "TypeName": "Custom:RackInformation",
  "DeletionSummary": {
      "TotalCount": 0,
      "RemainingCount": 0,
      "SummaryItems": []
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteInventory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-inventory.html)」を参照してください。

### `delete-maintenance-window`
<a name="ssm_DeleteMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`delete-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウを削除するには**  
この `delete-maintenance-window` の例では、指定されたメンテナンスウィンドウを削除します。  

```
aws ssm delete-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9"
```
出力:  

```
{
    "WindowId":"mw-1a2b3c4d5e6f7g8h9"
}
```
詳細については、*AWS 「 Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウの削除 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-delete-mw.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-maintenance-window.html)」を参照してください。

### `delete-parameter`
<a name="ssm_DeleteParameter_cli_2_topic"></a>

次のコード例は、`delete-parameter` を使用する方法を示しています。

**AWS CLI**  
**パラメータを削除をするには**  
次の `delete-parameter` の例では、指定された単一のパラメータを削除します。  

```
aws ssm delete-parameter \
    --name "MyParameter"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store の使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteParameter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-parameter.html)」を参照してください。

### `delete-parameters`
<a name="ssm_DeleteParameters_cli_2_topic"></a>

次のコード例は、`delete-parameters` を使用する方法を示しています。

**AWS CLI**  
**パラメータのリストを削除するには**  
次の `delete-parameters` の例では、指定されたパラメータを削除します。  

```
aws ssm delete-parameters \
    --names "MyFirstParameter" "MySecondParameter" "MyInvalidParameterName"
```
出力:  

```
{
    "DeletedParameters": [
        "MyFirstParameter",
        "MySecondParameter"
    ],
    "InvalidParameters": [
        "MyInvalidParameterName"
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store の使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-parameters.html)」を参照してください。

### `delete-patch-baseline`
<a name="ssm_DeletePatchBaseline_cli_2_topic"></a>

次のコード例は、`delete-patch-baseline` を使用する方法を示しています。

**AWS CLI**  
**パッチベースラインを削除するには**  
次の `delete-patch-baseline` の例では、指定されたパッチベースラインを削除します。  

```
aws ssm delete-patch-baseline \
    --baseline-id "pb-045f10b4f382baeda"
```
出力:  

```
{
    "BaselineId": "pb-045f10b4f382baeda"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パッチベースラインの更新または削除 (コンソール)](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-baseline-update-or-delete.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-patch-baseline.html)」を参照してください。

### `delete-resource-data-sync`
<a name="ssm_DeleteResourceDataSync_cli_2_topic"></a>

次のコード例は、`delete-resource-data-sync` を使用する方法を示しています。

**AWS CLI**  
**リソースデータの同期を削除するには**  
この例では、リソースデータの同期を削除します。コマンドが成功した場合、出力はありません。  
コマンド:  

```
aws ssm delete-resource-data-sync --sync-name "ssm-resource-data-sync"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourceDataSync](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/delete-resource-data-sync.html)」を参照してください。

### `deregister-managed-instance`
<a name="ssm_DeregisterManagedInstance_cli_2_topic"></a>

次のコード例は、`deregister-managed-instance` を使用する方法を示しています。

**AWS CLI**  
**マネージドインスタンスを登録解除するには**  
次の `deregister-managed-instance` の例では、指定されたマネージドインスタンスを登録解除します。  

```
aws ssm deregister-managed-instance \
    --instance-id 'mi-08ab247cdfEXAMPLE'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[ハイブリッドおよびマルチクラウド環境でのマネージドノードの登録解除](https://docs.aws.amazon.com/systems-manager/latest/userguide/fleet-manager-deregister-hybrid-nodes.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterManagedInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-managed-instance.html)」を参照してください。

### `deregister-patch-baseline-for-patch-group`
<a name="ssm_DeregisterPatchBaselineForPatchGroup_cli_2_topic"></a>

次のコード例は、`deregister-patch-baseline-for-patch-group` を使用する方法を示しています。

**AWS CLI**  
**パッチグループをパッチベースラインから登録解除するには**  
次の `deregister-patch-baseline-for-patch-group` の例では、指定されたパッチグループを指定されたパッチベースラインから登録解除します。  

```
aws ssm deregister-patch-baseline-for-patch-group \
    --patch-group "Production" \
    --baseline-id "pb-0ca44a362fEXAMPLE"
```
出力:  

```
{
  "PatchGroup":"Production",
  "BaselineId":"pb-0ca44a362fEXAMPLE"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パッチベースラインにパッチグループを追加します](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterPatchBaselineForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-patch-baseline-for-patch-group.html)」を参照してください。

### `deregister-target-from-maintenance-window`
<a name="ssm_DeregisterTargetFromMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`deregister-target-from-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウからターゲットを削除するには**  
次の`deregister-target-from-maintenance-window` の例では、指定されたターゲットを指定されたメンテナンスウィンドウから削除します。  

```
aws ssm deregister-target-from-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --window-target-id "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
```
出力:  

```
{
    "WindowId":"mw-ab12cd34ef56gh78",
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウの更新 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTargetFromMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-target-from-maintenance-window.html)」を参照してください。

### `deregister-task-from-maintenance-window`
<a name="ssm_DeregisterTaskFromMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`deregister-task-from-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウからタスクを削除するには**  
次の `deregister-task-from-maintenance-window` 例では、指定されたタスクを指定されたメンテナンスウィンドウから削除します。  

```
aws ssm deregister-task-from-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --window-task-id "1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6c"
```
出力:  

```
{
    "WindowTaskId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d5e6c",
    "WindowId":"mw-ab12cd34ef56gh78"
}
```
詳細については、[「Systems Manager ユーザーガイド」の「Systems Manager メンテナンスウィンドウチュートリアル (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-tutorials.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTaskFromMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/deregister-task-from-maintenance-window.html)」を参照してください。

### `describe-activations`
<a name="ssm_DescribeActivations_cli_2_topic"></a>

次のコード例は、`describe-activations` を使用する方法を示しています。

**AWS CLI**  
**アクティベーションについて表示するには**  
次の の`describe-activations`例では、 AWS アカウントのアクティベーションの詳細を一覧表示します。  

```
aws ssm describe-activations
```
出力:  

```
{
    "ActivationList": [
        {
            "ActivationId": "5743558d-563b-4457-8682-d16c3EXAMPLE",
            "Description": "Example1",
            "IamRole": "HybridWebServersRole,
            "RegistrationLimit": 5,
            "RegistrationsCount": 5,
            "ExpirationDate": 1584316800.0,
            "Expired": false,
            "CreatedDate": 1581954699.792
        },
        {
            "ActivationId": "3ee0322b-f62d-40eb-b672-13ebfEXAMPLE",
            "Description": "Example2",
            "IamRole": "HybridDatabaseServersRole",
            "RegistrationLimit": 5,
            "RegistrationsCount": 5,
            "ExpirationDate": 1580515200.0,
            "Expired": true,
            "CreatedDate": 1578064132.002
        },
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[ステップ 4: ハイブリッド環境のマネージドインスタンスアクティベーションを作成する](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-managed-instance-activation.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeActivations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-activations.html)」を参照してください。

### `describe-association-execution-targets`
<a name="ssm_DescribeAssociationExecutionTargets_cli_2_topic"></a>

次のコード例は、`describe-association-execution-targets` を使用する方法を示しています。

**AWS CLI**  
**関連付けの実行の詳細情報を取得するには**  
次の `describe-association-execution-targets` の例では、指定された関連付けの実行を記述します。  

```
aws ssm describe-association-execution-targets \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --execution-id "7abb6378-a4a5-4f10-8312-0123456789ab"
```
出力:  

```
{
    "AssociationExecutionTargets": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
            "ResourceId": "i-1234567890abcdef0",
            "ResourceType": "ManagedInstance",
            "Status": "Success",
            "DetailedStatus": "Success",
            "LastExecutionDate": 1550505538.497,
            "OutputSource": {
                "OutputSourceId": "97fff367-fc5a-4299-aed8-0123456789ab",
                "OutputSourceType": "RunCommand"
            }
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの履歴の表示](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-history.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssociationExecutionTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-association-execution-targets.html)」を参照してください。

### `describe-association-executions`
<a name="ssm_DescribeAssociationExecutions_cli_2_topic"></a>

次のコード例は、`describe-association-executions` を使用する方法を示しています。

**AWS CLI**  
**例 1: 関連付けのすべての実行に関する詳細情報を取得するには**  
次の `describe-association-executions` の例では、指定された関連付けのすべての実行を記述します。  

```
aws ssm describe-association-executions \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
出力:  

```
{
    "AssociationExecutions": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "474925ef-1249-45a2-b93d-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505827.119,
            "ResourceCountByStatus": "{Success=1}"
        },
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505536.843,
            "ResourceCountByStatus": "{Success=1}"
        },
        ...
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの履歴の表示](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-history.html)」を参照してください。  
**例 2: 特定の日付および時刻より後における、関連付けのすべての実行の詳細情報を取得するには**  
次の `describe-association-executions` の例では、指定した日付および時刻より後における関連付けのすべての実行を記述します。  

```
aws ssm describe-association-executions \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --filters "Key=CreatedTime,Value=2019-02-18T16:00:00Z,Type=GREATER_THAN"
```
出力:  

```
{
    "AssociationExecutions": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "474925ef-1249-45a2-b93d-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505827.119,
            "ResourceCountByStatus": "{Success=1}"
        },
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
            "Status": "Success",
            "DetailedStatus": "Success",
            "CreatedTime": 1550505536.843,
            "ResourceCountByStatus": "{Success=1}"
        },
        ...
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの履歴の表示](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-history.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssociationExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-association-executions.html)」を参照してください。

### `describe-association`
<a name="ssm_DescribeAssociation_cli_2_topic"></a>

次のコード例は、`describe-association` を使用する方法を示しています。

**AWS CLI**  
**例 1: 関連付けの詳細情報を取得するには**  
次の `describe-association` の例では、指定された関連付け ID の関連付けを記述します。  

```
aws ssm describe-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
出力:  

```
{
    "AssociationDescription": {
        "Name": "AWS-GatherSoftwareInventory",
        "AssociationVersion": "1",
        "Date": 1534864780.995,
        "LastUpdateAssociationDate": 1543235759.81,
        "Overview": {
            "Status": "Success",
            "AssociationStatusAggregatedCount": {
                "Success": 2
            }
        },
        "DocumentVersion": "$DEFAULT",
        "Parameters": {
            "applications": [
                "Enabled"
            ],
            "awsComponents": [
                "Enabled"
            ],
            "customInventory": [
                "Enabled"
            ],
            "files": [
                ""
            ],
            "instanceDetailedInformation": [
                "Enabled"
            ],
            "networkConfig": [
                "Enabled"
            ],
            "services": [
                "Enabled"
            ],
            "windowsRegistry": [
                ""
            ],
            "windowsRoles": [
                "Enabled"
            ],
            "windowsUpdates": [
                "Enabled"
            ]
        },
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "InstanceIds",
                "Values": [
                    "*"
                ]
            }
        ],
        "ScheduleExpression": "rate(24 hours)",
        "LastExecutionDate": 1550501886.0,
        "LastSuccessfulExecutionDate": 1550501886.0,
        "AssociationName": "Inventory-Association"
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの編集と新しいバージョンの作成](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)」を参照してください。  
**例 2: 特定のインスタンスとドキュメントの関連付けの詳細情報を取得するには**  
次の `describe-association` の例では、インスタンスとドキュメントの関連付けを記述します。  

```
aws ssm describe-association \
    --instance-id "i-1234567890abcdef0" \
    --name "AWS-UpdateSSMAgent"
```
出力:  

```
{
    "AssociationDescription": {
        "Status": {
            "Date": 1487876122.564,
            "Message": "Associated with AWS-UpdateSSMAgent",
            "Name": "Associated"
        },
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-1234567890abcdef0",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Associated",
            "AssociationStatusAggregatedCount": {
                "Pending": 1
            }
        },
        "AssociationId": "d8617c07-2079-4c18-9847-1234567890ab",
        "DocumentVersion": "$DEFAULT",
        "LastUpdateAssociationDate": 1487876122.564,
        "Date": 1487876122.564,
        "Targets": [
            {
                "Values": [
                    "i-1234567890abcdef0"
                ],
                "Key": "InstanceIds"
            }
        ]
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの編集と新しいバージョンの作成](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-association.html)」を参照してください。

### `describe-automation-executions`
<a name="ssm_DescribeAutomationExecutions_cli_2_topic"></a>

次のコード例は、`describe-automation-executions` を使用する方法を示しています。

**AWS CLI**  
**オートメーションの実行を記述するには**  
次の `describe-automation-executions` の例では、オートメーションの実行の詳細情報を表示します。  

```
aws ssm describe-automation-executions \
    --filters Key=ExecutionId,Values=73c8eef8-f4ee-4a05-820c-e354fEXAMPLE
```
出力:  

```
{
    "AutomationExecutionMetadataList": [
        {
            "AutomationExecutionId": "73c8eef8-f4ee-4a05-820c-e354fEXAMPLE",
            "DocumentName": "AWS-StartEC2Instance",
            "DocumentVersion": "1",
            "AutomationExecutionStatus": "Success",
            "ExecutionStartTime": 1583737233.748,
            "ExecutionEndTime": 1583737234.719,
            "ExecutedBy": "arn:aws:sts::29884EXAMPLE:assumed-role/mw_service_role/OrchestrationService",
            "LogFile": "",
            "Outputs": {},
            "Mode": "Auto",
            "Targets": [],
            "ResolvedTargets": {
                "ParameterValues": [],
                "Truncated": false
            },
            "AutomationType": "Local"
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[シンプルなオートメーションを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAutomationExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-automation-executions.html)」を参照してください。

### `describe-automation-step-executions`
<a name="ssm_DescribeAutomationStepExecutions_cli_2_topic"></a>

次のコード例は、`describe-automation-step-executions` を使用する方法を示しています。

**AWS CLI**  
**例 1: オートメーションの実行におけるすべてのステップを表示するには**  
次の `describe-automation-step-executions` の例では、オートメーションの実行におけるステップの詳細情報を表示します。  

```
aws ssm describe-automation-step-executions \
    --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE
```
出力:  

```
{
    "StepExecutions": [
        {
            "StepName": "startInstances",
            "Action": "aws:changeInstanceState",
            "ExecutionStartTime": 1583737234.134,
            "ExecutionEndTime": 1583737234.672,
            "StepStatus": "Success",
            "Inputs": {
                "DesiredState": "\"running\"",
                "InstanceIds": "[\"i-0cb99161f6EXAMPLE\"]"
            },
            "Outputs": {
                "InstanceStates": [
                    "running"
                ]
            },
            "StepExecutionId": "95e70479-cf20-4d80-8018-7e4e2EXAMPLE",
            "OverriddenParameters": {}
        }
    ]
}
```
**例 2: オートメーションの実行における特定のステップを表示するには**  
次の `describe-automation-step-executions` の例では、オートメーションの実行における特定のステップの詳細情報を表示します。  

```
aws ssm describe-automation-step-executions \
    --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE \
    --filters Key=StepExecutionId,Values=95e70479-cf20-4d80-8018-7e4e2EXAMPLE
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[オートメーションをステップごとに実行する (コマンドライン)](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing-manually.html#automation-working-executing-manually-commandline)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAutomationStepExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-automation-step-executions.html)」を参照してください。

### `describe-available-patches`
<a name="ssm_DescribeAvailablePatches_cli_2_topic"></a>

次のコード例は、`describe-available-patches` を使用する方法を示しています。

**AWS CLI**  
**利用可能なパッチを取得するには**  
次の`describe-available-patches` の例では、Windows Server 2019 で利用でき、MSRC 重要度が「緊急」のすべてのパッチに関する詳細情報を取得します。  

```
aws ssm describe-available-patches \
    --filters "Key=PRODUCT,Values=WindowsServer2019" "Key=MSRC_SEVERITY,Values=Critical"
```
出力:  

```
{
    "Patches": [
        {
            "Id": "fe6bd8c2-3752-4c8b-ab3e-1a7ed08767ba",
            "ReleaseDate": 1544047205.0,
            "Title": "2018-11 Update for Windows Server 2019 for x64-based Systems (KB4470788)",
            "Description": "Install this update to resolve issues in Windows. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article for more information. After you install this item, you may have to restart your computer.",
            "ContentUrl": "https://support.microsoft.com/en-us/kb/4470788",
            "Vendor": "Microsoft",
            "ProductFamily": "Windows",
            "Product": "WindowsServer2019",
            "Classification": "SecurityUpdates",
            "MsrcSeverity": "Critical",
            "KbNumber": "KB4470788",
            "MsrcNumber": "",
            "Language": "All"
        },
        {
            "Id": "c96115e1-5587-4115-b851-22baa46a3f11",
            "ReleaseDate": 1549994410.0,
            "Title": "2019-02 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4487038)",
            "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.",
            "ContentUrl": "https://support.microsoft.com/en-us/kb/4487038",
            "Vendor": "Microsoft",
            "ProductFamily": "Windows",
            "Product": "WindowsServer2019",
            "Classification": "SecurityUpdates",
            "MsrcSeverity": "Critical",
            "KbNumber": "KB4487038",
            "MsrcNumber": "",
            "Language": "All"
        },
        ...
    ]
}
```
**特定のパッチの詳細情報を取得するには**  
次の `describe-available-patches` の例では、指定されたパッチの詳細情報を取得します。  

```
aws ssm describe-available-patches \
    --filters "Key=PATCH_ID,Values=KB4480979"
```
出力:  

```
{
    "Patches": [
        {
            "Id": "680861e3-fb75-432e-818e-d72e5f2be719",
            "ReleaseDate": 1546970408.0,
            "Title": "2019-01 Security Update for Adobe Flash Player for Windows Server 2016 for x64-based Systems (KB4480979)",
            "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.",
            "ContentUrl": "https://support.microsoft.com/en-us/kb/4480979",
            "Vendor": "Microsoft",
            "ProductFamily": "Windows",
            "Product": "WindowsServer2016",
            "Classification": "SecurityUpdates",
            "MsrcSeverity": "Critical",
            "KbNumber": "KB4480979",
            "MsrcNumber": "",
            "Language": "All"
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Patch Manager の動作の仕組み](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-how-it-works.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeAvailablePatches](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-available-patches.html)」を参照してください。

### `describe-document-permission`
<a name="ssm_DescribeDocumentPermission_cli_2_topic"></a>

次のコード例は、`describe-document-permission` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントのアクセス許可を表示するには**  
次の `describe-document-permission` の例では、パブリックに共有されている Systems Manager ドキュメントに関するアクセス許可の詳細情報を表示します。  

```
aws ssm describe-document-permission \
    --name "Example" \
    --permission-type "Share"
```
出力:  

```
{
    "AccountIds": [
        "all"
    ],
    "AccountSharingInfoList": [
        {
            "AccountId": "all",
            "SharedDocumentVersion": "$DEFAULT"
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[SSM ドキュメントの共有](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-how-to-share.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDocumentPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-document-permission.html)」を参照してください。

### `describe-document`
<a name="ssm_DescribeDocument_cli_2_topic"></a>

次のコード例は、`describe-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントの詳細情報を表示するには**  
次の の`describe-document`例では、 AWS アカウントの Systems Manager ドキュメントの詳細を表示します。  

```
aws ssm describe-document \
    --name "Example"
```
出力:  

```
{
    "Document": {
        "Hash": "fc2410281f40779e694a8b95975d0f9f316da8a153daa94e3d9921102EXAMPLE",
        "HashType": "Sha256",
        "Name": "Example",
        "Owner": "29884EXAMPLE",
        "CreatedDate": 1583257938.266,
        "Status": "Active",
        "DocumentVersion": "1",
        "Description": "Document Example",
        "Parameters": [
            {
                "Name": "AutomationAssumeRole",
                "Type": "String",
                "Description": "(Required) The ARN of the role that allows Automation to perform the actions on your behalf. If no role is specified, Systems Manager Automation uses your IAM permissions to execute this document.",
                "DefaultValue": ""
            },
            {
                "Name": "InstanceId",
                "Type": "String",
                "Description": "(Required) The ID of the Amazon EC2 instance.",
                "DefaultValue": ""
            }
        ],
        "PlatformTypes": [
            "Windows",
            "Linux"
        ],
        "DocumentType": "Automation",
        "SchemaVersion": "0.3",
        "LatestVersion": "1",
        "DefaultVersion": "1",
        "DocumentFormat": "YAML",
        "Tags": []
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[SSM ドキュメントコンテンツを作成する](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-document.html)」を参照してください。

### `describe-effective-instance-associations`
<a name="ssm_DescribeEffectiveInstanceAssociations_cli_2_topic"></a>

次のコード例は、`describe-effective-instance-associations` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの有効な関連付けの詳細情報を取得するには**  
次の `describe-effective-instance-associations` の例では、インスタンスの有効な関連付けに関する詳細情報を取得します。  
コマンド:  

```
aws ssm describe-effective-instance-associations --instance-id "i-1234567890abcdef0"
```
出力:  

```
{
    "Associations": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "InstanceId": "i-1234567890abcdef0",
            "Content": "{\n    \"schemaVersion\": \"1.2\",\n    \"description\": \"Update the Amazon SSM Agent to the latest version or specified version.\",\n    \"parameters\": {\n        \"version\": {\n            \"default\": \"\",\n            \"description\": \"(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agent will be updated to the latest version.\",\n            \"type\": \"String\"\n        },\n        \"allowDowngrade\": {\n            \"default\": \"false\",\n            \"description\": \"(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.\",\n            \"type\": \"String\",\n            \"allowedValues\": [\n                \"true\",\n                \"false\"\n            ]\n        }\n    },\n    \"runtimeConfig\": {\n        \"aws:updateSsmAgent\": {\n            \"properties\": [\n                {\n                \"agentName\": \"amazon-ssm-agent\",\n                \"source\": \"https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json\",\n                \"allowDowngrade\": \"{{ allowDowngrade }}\",\n                \"targetVersion\": \"{{ version }}\"\n                }\n            ]\n        }\n    }\n}\n",
            "AssociationVersion": "1"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEffectiveInstanceAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-effective-instance-associations.html)」を参照してください。

### `describe-effective-patches-for-patch-baseline`
<a name="ssm_DescribeEffectivePatchesForPatchBaseline_cli_2_topic"></a>

次のコード例は、`describe-effective-patches-for-patch-baseline` を使用する方法を示しています。

**AWS CLI**  
**例 1: カスタムパッチベースラインで定義されている、すべてのパッチを取得するには**  
次の の`describe-effective-patches-for-patch-baseline`例では、現在の AWS アカウントのカスタムパッチベースラインで定義されたパッチを返します。カスタムベースラインの場合、`--baseline-id` には ID のみが必要であることに注意してください。  

```
aws ssm describe-effective-patches-for-patch-baseline \
    --baseline-id "pb-08b654cf9b9681f04"
```
出力:  

```
{
    "EffectivePatches": [
        {
            "Patch": {
                "Id": "fe6bd8c2-3752-4c8b-ab3e-1a7ed08767ba",
                "ReleaseDate": 1544047205.0,
                "Title": "2018-11 Update for Windows Server 2019 for x64-based Systems (KB4470788)",
                "Description": "Install this update to resolve issues in Windows. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article for more information. After you install this item, you may have to restart your computer.",
                "ContentUrl": "https://support.microsoft.com/en-us/kb/4470788",
                "Vendor": "Microsoft",
                "ProductFamily": "Windows",
                "Product": "WindowsServer2019",
                "Classification": "SecurityUpdates",
                "MsrcSeverity": "Critical",
                "KbNumber": "KB4470788",
                "MsrcNumber": "",
                "Language": "All"
            },
            "PatchStatus": {
                "DeploymentStatus": "APPROVED",
                "ComplianceLevel": "CRITICAL",
                "ApprovalDate": 1544047205.0
            }
        },
        {
            "Patch": {
                "Id": "915a6b1a-f556-4d83-8f50-b2e75a9a7e58",
                "ReleaseDate": 1549994400.0,
                "Title": "2019-02 Cumulative Update for .NET Framework 3.5 and 4.7.2 for Windows Server 2019 for x64 (KB4483452)",
                "Description": "A security issue has been identified in a Microsoft software product that could affect your system. You can help protect your system by installing this update from Microsoft. For a complete listing of the issues that are included in this update, see the associated Microsoft Knowledge Base article. After you install this update, you may have to restart your system.",
                "ContentUrl": "https://support.microsoft.com/en-us/kb/4483452",
                "Vendor": "Microsoft",
                "ProductFamily": "Windows",
                "Product": "WindowsServer2019",
                "Classification": "SecurityUpdates",
                "MsrcSeverity": "Important",
                "KbNumber": "KB4483452",
                "MsrcNumber": "",
                "Language": "All"
            },
            "PatchStatus": {
                "DeploymentStatus": "APPROVED",
                "ComplianceLevel": "CRITICAL",
                "ApprovalDate": 1549994400.0
            }
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
**例 2: AWS マネージドパッチベースラインで定義されたすべてのパッチを取得するには**  
次の の`describe-effective-patches-for-patch-baseline`例では、 AWS マネージドパッチベースラインで定義されたパッチを返します。 AWS マネージドベースラインの場合、 には完全なベースライン ARN が必要です。 `--baseline-id`  

```
aws ssm describe-effective-patches-for-patch-baseline \
    --baseline-id "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-020d361a05defe4ed"
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[セキュリティに関連するパッチの選択方法](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-how-it-works-selection.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeEffectivePatchesForPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-effective-patches-for-patch-baseline.html)」を参照してください。

### `describe-instance-associations-status`
<a name="ssm_DescribeInstanceAssociationsStatus_cli_2_topic"></a>

次のコード例は、`describe-instance-associations-status` を使用する方法を示しています。

**AWS CLI**  
**インスタンスの関連付けのステータスを表示するには**  
この例では、インスタンスの関連付けの詳細情報を表示します。  
コマンド:  

```
aws ssm describe-instance-associations-status --instance-id "i-1234567890abcdef0"
```
出力:  

```
{
  "InstanceAssociationStatusInfos": [
      {
          "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
          "Name": "AWS-GatherSoftwareInventory",
          "DocumentVersion": "1",
          "AssociationVersion": "1",
          "InstanceId": "i-1234567890abcdef0",
          "ExecutionDate": 1550501886.0,
          "Status": "Success",
          "ExecutionSummary": "1 out of 1 plugin processed, 1 success, 0 failed, 0 timedout, 0 skipped. ",
          "AssociationName": "Inventory-Association"
      },
      {
          "AssociationId": "5c5a31f6-6dae-46f9-944c-0123456789ab",
          "Name": "AWS-UpdateSSMAgent",
          "DocumentVersion": "1",
          "AssociationVersion": "1",
          "InstanceId": "i-1234567890abcdef0",
          "ExecutionDate": 1550505828.548,
          "Status": "Success",
          "DetailedStatus": "Success",
          "AssociationName": "UpdateSSMAgent"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceAssociationsStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-associations-status.html)」を参照してください。

### `describe-instance-information`
<a name="ssm_DescribeInstanceInformation_cli_2_topic"></a>

次のコード例は、`describe-instance-information` を使用する方法を示しています。

**AWS CLI**  
**例 1: マネージドインスタンスの情報を表示するには**  
次の `describe-instance-information` の例では、各マネージドインスタンスの詳細情報を取得します。  

```
aws ssm describe-instance-information
```
**例 2: 特定のマネージドインスタンスに関する情報を表示するには**  
次の `describe-instance-information` の例では、マネージドインスタンス `i-028ea792daEXAMPLE` の詳細情報を表示します。  

```
aws ssm describe-instance-information \
    --filters "Key=InstanceIds,Values=i-028ea792daEXAMPLE"
```
**例 3: 特定のタグキーを持つマネージドインスタンスに関する情報を表示するには**  
次の `describe-instance-information` の例では、タグキー `DEV` を持つマネージドインスタンスの詳細情報を表示します。  

```
aws ssm describe-instance-information \
    --filters "Key=tag-key,Values=DEV"
```
出力:  

```
{
    "InstanceInformationList": [
        {
            "InstanceId": "i-028ea792daEXAMPLE",
            "PingStatus": "Online",
            "LastPingDateTime": 1582221233.421,
            "AgentVersion": "2.3.842.0",
            "IsLatestVersion": true,
            "PlatformType": "Linux",
            "PlatformName": "SLES",
            "PlatformVersion": "15.1",
            "ResourceType": "EC2Instance",
            "IPAddress": "192.0.2.0",
            "ComputerName": "ip-198.51.100.0.us-east-2.compute.internal",
            "AssociationStatus": "Success",
            "LastAssociationExecutionDate": 1582220806.0,
            "LastSuccessfulAssociationExecutionDate": 1582220806.0,
            "AssociationOverview": {
                "DetailedStatus": "Success",
                "InstanceAssociationStatusAggregatedCount": {
                    "Success": 2
                }
            }
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[マネージドインスタンス](https://docs.aws.amazon.com/systems-manager/latest/userguide/managed_instances.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstanceInformation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-information.html)」を参照してください。

### `describe-instance-patch-states-for-patch-group`
<a name="ssm_DescribeInstancePatchStatesForPatchGroup_cli_2_topic"></a>

次のコード例は、`describe-instance-patch-states-for-patch-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: パッチグループのインスタンスの状態を取得するには**  
次の`describe-instance-patch-states-for-patch-group` の例では、指定されたパッチグループにおけるインスタンスごとのパッチの概要状態に関する詳細情報を取得します。  

```
aws ssm describe-instance-patch-states-for-patch-group \
    --patch-group "Production"
```
出力:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-02573cafcfEXAMPLE",
            "PatchGroup": "Production",
            "BaselineId": "pb-0c10e65780EXAMPLE",
            "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE",
            "OwnerInformation": "",
            "InstalledCount": 32,
            "InstalledOtherCount": 1,
            "InstalledPendingRebootCount": 0,
            "InstalledRejectedCount": 0,
            "MissingCount": 2,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 2671,
            "NotApplicableCount": 400,
            "OperationStartTime": "2021-08-04T11:03:50.590000-07:00",
            "OperationEndTime": "2021-08-04T11:04:21.555000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 0
        },
        {
            "InstanceId": "i-0471e04240EXAMPLE",
            "PatchGroup": "Production",
            "BaselineId": "pb-09ca3fb51fEXAMPLE",
            "SnapshotId": "05d8ffb0-1bbe-4812-ba2d-d9b7bEXAMPLE",
            "OwnerInformation": "",
            "InstalledCount": 32,
            "InstalledOtherCount": 1,
            "InstalledPendingRebootCount": 0,
            "InstalledRejectedCount": 0,
            "MissingCount": 2,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 2671,
            "NotApplicableCount": 400,
            "OperationStartTime": "2021-08-04T22:06:20.340000-07:00",
            "OperationEndTime": "2021-08-04T22:07:11.220000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 0
        }
    ]
}
```
**例 2: パッチグループの欠落しているパッチが 5 個以上あるインスタンスの状態を取得するには**  
次の `describe-instance-patch-states-for-patch-group` の例では、指定されたパッチグループにおいて、欠落しているパッチが 5 個以上あるインスタンスのパッチの概要状態に関する詳細情報を取得します。  

```
aws ssm describe-instance-patch-states-for-patch-group \
    --filters Key=MissingCount,Type=GreaterThan,Values=5 \
    --patch-group "Production"
```
出力:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-02573cafcfEXAMPLE",
            "PatchGroup": "Production",
            "BaselineId": "pb-0c10e65780EXAMPLE",
            "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE",
            "OwnerInformation": "",
            "InstalledCount": 46,
            "InstalledOtherCount": 4,
            "InstalledPendingRebootCount": 1,
            "InstalledRejectedCount": 1,
            "MissingCount": 7,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 232,
            "NotApplicableCount": 654,
            "OperationStartTime": "2021-08-04T11:03:50.590000-07:00",
            "OperationEndTime": "2021-08-04T11:04:21.555000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 1
        }
    ]
}
```
**例 3: パッチグループにおいて、再起動が必要なインスタンスが 10 個未満のインスタンスの状態を取得するには**  
次の`describe-instance-patch-states-for-patch-group` の例では、指定されたパッチグループにおいて、再起動が必要なインスタンスが 10 個未満であるインスタンスのパッチの概要状態に関する詳細情報を取得します。  

```
aws ssm describe-instance-patch-states-for-patch-group \
    --filters Key=InstalledPendingRebootCount,Type=LessThan,Values=10 \
    --patch-group "Production"
```
出力:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-02573cafcfEXAMPLE",
            "BaselineId": "pb-0c10e65780EXAMPLE",
            "SnapshotId": "a3f5ff34-9bc4-4d2c-a665-4d1c1EXAMPLE",
            "PatchGroup": "Production",
            "OwnerInformation": "",
            "InstalledCount": 32,
            "InstalledOtherCount": 1,
            "InstalledPendingRebootCount": 4,
            "InstalledRejectedCount": 0,
            "MissingCount": 2,
            "FailedCount": 0,
            "UnreportedNotApplicableCount": 846,
            "NotApplicableCount": 212,
            "OperationStartTime": "2021-08-046T11:03:50.590000-07:00",
            "OperationEndTime": "2021-08-06T11:04:21.555000-07:00",
            "Operation": "Scan",
            "RebootOption": "NoReboot",
            "CriticalNonCompliantCount": 0,
            "SecurityNonCompliantCount": 1,
            "OtherNonCompliantCount": 0
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パッチコンプライアンス状態の値について](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance-states.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstancePatchStatesForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-patch-states-for-patch-group.html)」を参照してください。

### `describe-instance-patch-states`
<a name="ssm_DescribeInstancePatchStates_cli_2_topic"></a>

次のコード例は、`describe-instance-patch-states` を使用する方法を示しています。

**AWS CLI**  
**インスタンスのパッチの概要状態を取得するには**  
この `describe-instance-patch-states` の例では、インスタンスのパッチの概要状態を取得します。  

```
aws ssm describe-instance-patch-states \
    --instance-ids "i-1234567890abcdef0"
```
出力:  

```
{
    "InstancePatchStates": [
        {
            "InstanceId": "i-1234567890abcdef0",
            "PatchGroup": "my-patch-group",
            "BaselineId": "pb-0713accee01234567",
            "SnapshotId": "521c3536-930c-4aa9-950e-01234567abcd",
            "CriticalNonCompliantCount": 2,
            "SecurityNonCompliantCount": 2,
            "OtherNonCompliantCount": 1,
            "InstalledCount": 123,
            "InstalledOtherCount": 334,
            "InstalledPendingRebootCount": 0,
            "InstalledRejectedCount": 0,
            "MissingCount": 1,
            "FailedCount": 2,
            "UnreportedNotApplicableCount": 11,
            "NotApplicableCount": 2063,
            "OperationStartTime": "2021-05-03T11:00:56-07:00",
            "OperationEndTime": "2021-05-03T11:01:09-07:00",
            "Operation": "Scan",
            "LastNoRebootInstallOperationTime": "2020-06-14T12:17:41-07:00",
            "RebootOption": "RebootIfNeeded"
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パッチコンプライアンスについて](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstancePatchStates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-patch-states.html)」を参照してください。

### `describe-instance-patches`
<a name="ssm_DescribeInstancePatches_cli_2_topic"></a>

次のコード例は、`describe-instance-patches` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスのパッチ状態の詳細を取得するには**  
次の `describe-instance-patches` の例では、指定されたインスタンスのパッチに関する詳細情報を取得します。  

```
aws ssm describe-instance-patches \
    --instance-id "i-1234567890abcdef0"
```
出力:  

```
{
    "Patches": [
        {
            "Title": "2019-01 Security Update for Adobe Flash Player for Windows Server 2016 for x64-based Systems (KB4480979)",
            "KBId": "KB4480979",
            "Classification": "SecurityUpdates",
            "Severity": "Critical",
            "State": "Installed",
            "InstalledTime": "2019-01-09T00:00:00+00:00"
        },
        {
            "Title": "",
            "KBId": "KB4481031",
            "Classification": "",
            "Severity": "",
            "State": "InstalledOther",
            "InstalledTime": "2019-02-08T00:00:00+00:00"
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
**例 2: インスタンスで欠落しているパッチのリストを取得するには**  
次の`describe-instance-patches` の例では、指定されたインスタンスで欠落しているパッチに関する情報を取得します。  

```
aws ssm describe-instance-patches \
    --instance-id "i-1234567890abcdef0" \
    --filters Key=State,Values=Missing
```
出力:  

```
{
    "Patches": [
        {
            "Title": "Windows Malicious Software Removal Tool x64 - February 2019 (KB890830)",
            "KBId": "KB890830",
            "Classification": "UpdateRollups",
            "Severity": "Unspecified",
            "State": "Missing",
            "InstalledTime": "1970-01-01T00:00:00+00:00"
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
詳細については、「*AWS Systems Manager*」の「[パッチコンプライアンスの状態について](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance-states.html)」を参照してください。  
**例 3: インスタンスに対して、指定された InstalledTime よりも後にインストールされたパッチのリストを取得するには**  
次の`describe-instance-patches` の例では、`--filters` と `--query` を組み合わせて、指定されたインスタンスに対して、指定された時刻よりも後にインストールされたパッチに関する情報を取得します。  

```
aws ssm describe-instance-patches \
    --instance-id "i-1234567890abcdef0" \
    --filters Key=State,Values=Installed \
    --query "Patches[?InstalledTime >= `2023-01-01T16:00:00`]"
```
出力:  

```
{
    "Patches": [
        {
            "Title": "2023-03 Cumulative Update for Windows Server 2019 (1809) for x64-based Systems (KB5023702)",
            "KBId": "KB5023702",
            "Classification": "SecurityUpdates",
            "Severity": "Critical",
            "State": "Installed",
            "InstalledTime": "2023-03-16T11:00:00+00:00"
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInstancePatches](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-instance-patches.html)」を参照してください。

### `describe-inventory-deletions`
<a name="ssm_DescribeInventoryDeletions_cli_2_topic"></a>

次のコード例は、`describe-inventory-deletions` を使用する方法を示しています。

**AWS CLI**  
**インベントリの削除を取得するには**  
この例では、インベントリ削除オペレーションの詳細情報を取得します。  
コマンド:  

```
aws ssm describe-inventory-deletions
```
出力:  

```
{
  "InventoryDeletions": [
      {
          "DeletionId": "6961492a-8163-44ec-aa1e-01234567850",
          "TypeName": "Custom:RackInformation",
          "DeletionStartTime": 1550254911.0,
          "LastStatus": "InProgress",
          "LastStatusMessage": "The Delete is in progress",
          "DeletionSummary": {
              "TotalCount": 0,
              "RemainingCount": 0,
              "SummaryItems": []
          },
          "LastStatusUpdateTime": 1550254911.0
      },
      {
          "DeletionId": "d72ac9e8-1f60-4d40-b1c6-987654321c4d",
          "TypeName": "Custom:RackInfo",
          "DeletionStartTime": 1550254859.0,
          "LastStatus": "InProgress",
          "LastStatusMessage": "The Delete is in progress",
          "DeletionSummary": {
              "TotalCount": 1,
              "RemainingCount": 1,
              "SummaryItems": [
                  {
                      "Version": "1.0",
                      "Count": 1,
                      "RemainingCount": 1
                  }
              ]
          },
          "LastStatusUpdateTime": 1550254859.0
      }
  ]
}
```
**指定されたインベントリ削除の詳細を取得するには**  
この例では、指定されたインベントリ削除オペレーションの詳細情報を取得します。  
コマンド:  

```
aws ssm describe-inventory-deletions --deletion-id "d72ac9e8-1f60-4d40-b1c6-987654321c4d"
```
出力:  

```
{
  "InventoryDeletions": [
      {
          "DeletionId": "d72ac9e8-1f60-4d40-b1c6-987654321c4d",
          "TypeName": "Custom:RackInfo",
          "DeletionStartTime": 1550254859.0,
          "LastStatus": "InProgress",
          "LastStatusMessage": "The Delete is in progress",
          "DeletionSummary": {
              "TotalCount": 1,
              "RemainingCount": 1,
              "SummaryItems": [
                  {
                      "Version": "1.0",
                      "Count": 1,
                      "RemainingCount": 1
                  }
              ]
          },
          "LastStatusUpdateTime": 1550254859.0
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeInventoryDeletions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-inventory-deletions.html)」を参照してください。

### `describe-maintenance-window-execution-task-invocations`
<a name="ssm_DescribeMaintenanceWindowExecutionTaskInvocations_cli_2_topic"></a>

次のコード例は、`describe-maintenance-window-execution-task-invocations` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウのタスク実行で実行される、特定のタスク呼び出しを取得するには**  
次の `describe-maintenance-window-execution-task-invocations` の例では、指定されたメンテナンスウィンドウの実行の一部として実行される、指定したタスクの呼び出しを一覧表示します。  

```
aws ssm describe-maintenance-window-execution-task-invocations \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2a638355" \
    --task-id "ac0c6ae1-daa3-4a89-832e-d384503b6586"
```
出力:  

```
{
    "WindowExecutionTaskInvocationIdentities": [
        {
            "Status": "SUCCESS",
            "Parameters": "{\"documentName\":\"AWS-RunShellScript\",\"instanceIds\":[\"i-0000293ffd8c57862\"],\"parameters\":{\"commands\":[\"df\"]},\"maxConcurrency\":\"1\",\"maxErrors\":\"1\"}",
            "InvocationId": "e274b6e1-fe56-4e32-bd2a-8073c6381d8b",
            "StartTime": 1487692834.723,
            "EndTime": 1487692834.871,
            "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2a638355",
            "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d384503b6586"
        }
    ]
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「タスクとタスク実行に関する情報を表示する (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindowExecutionTaskInvocations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-execution-task-invocations.html)」を参照してください。

### `describe-maintenance-window-execution-tasks`
<a name="ssm_DescribeMaintenanceWindowExecutionTasks_cli_2_topic"></a>

次のコード例は、`describe-maintenance-window-execution-tasks` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウの実行に関連するすべてのタスクを一覧表示するには**  
次の `ssm describe-maintenance-window-execution-tasks` の例では、指定されたメンテナンスウィンドウの実行に関連するタスクを一覧表示します。  

```
aws ssm describe-maintenance-window-execution-tasks \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE"
```
出力:  

```
{
    "WindowExecutionTaskIdentities": [
        {
            "Status": "SUCCESS",
            "TaskArn": "AWS-RunShellScript",
            "StartTime": 1487692834.684,
            "TaskType": "RUN_COMMAND",
            "EndTime": 1487692835.005,
            "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE",
            "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE"
        }
    ]
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「タスクとタスク実行に関する情報の表示 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindowExecutionTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-execution-tasks.html)」を参照してください。

### `describe-maintenance-window-executions`
<a name="ssm_DescribeMaintenanceWindowExecutions_cli_2_topic"></a>

次のコード例は、`describe-maintenance-window-executions` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウにおけるすべての実行を一覧表示するには**  
次の `describe-maintenance-window-executions` の例では、指定されたメンテナンスウィンドウにおけるすべての実行を一覧表示します。  

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-ab12cd34eEXAMPLE"
```
出力:  

```
{
    "WindowExecutions": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowExecutionId": "6027b513-64fe-4cf0-be7d-1191aEXAMPLE",
            "Status": "IN_PROGRESS",
            "StartTime": "2021-08-04T11:00:00.000000-07:00"

        },
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowExecutionId": "ff75b750-4834-4377-8f61-b3cadEXAMPLE",
            "Status": "SUCCESS",
            "StartTime": "2021-08-03T11:00:00.000000-07:00",
            "EndTime": "2021-08-03T11:37:21.450000-07:00"
        },
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowExecutionId": "9fac7dd9-ff21-42a5-96ad-bbc4bEXAMPLE",
            "Status": "FAILED",
            "StatusDetails": "One or more tasks in the orchestration failed.",
            "StartTime": "2021-08-02T11:00:00.000000-07:00",
            "EndTime": "2021-08-02T11:22:36.190000-07:00"
        }
    ]
}
```
**例 2: メンテナンスウィンドウにおける指定された日付より前のすべての実行を一覧表示するには**  
次の `describe-maintenance-window-executions` の例では、指定されたメンテナンスウィンドウにおける指定された日付より前のすべての実行を一覧表示します。  

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=ExecutedBefore,Values=2021-08-03T00:00:00Z"
```
出力:  

```
{
    "WindowExecutions": [
        {
        "WindowId": "mw-ab12cd34eEXAMPLE",
        "WindowExecutionId": "9fac7dd9-ff21-42a5-96ad-bbc4bEXAMPLE",
        "Status": "FAILED",
        "StatusDetails": "One or more tasks in the orchestration failed.",
        "StartTime": "2021-08-02T11:00:00.000000-07:00",
        "EndTime": "2021-08-02T11:22:36.190000-07:00"
    }
    ]
}
```
**例 3: メンテナンスウィンドウにおける指定された日付より後のすべての実行を一覧表示するには**  
次の `describe-maintenance-window-executions` の例では、メンテナンスウィンドウにおける指定された日付より後のすべての実行を一覧表示します。  

```
aws ssm describe-maintenance-window-executions \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=ExecutedAfter,Values=2021-08-04T00:00:00Z"
```
出力:  

```
{
    "WindowExecutions": [
        {
        "WindowId": "mw-ab12cd34eEXAMPLE",
        "WindowExecutionId": "6027b513-64fe-4cf0-be7d-1191aEXAMPLE",
        "Status": "IN_PROGRESS",
        "StartTime": "2021-08-04T11:00:00.000000-07:00"
        }
    ]
}
```
詳細については、*AWS 「Systems* [Manager ユーザーガイド」の「タスクとタスク実行 (AWS CLI) に関する情報](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html)を表示する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindowExecutions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-executions.html)」を参照してください。

### `describe-maintenance-window-schedule`
<a name="ssm_DescribeMaintenanceWindowSchedule_cli_2_topic"></a>

次のコード例は、`describe-maintenance-window-schedule` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウの今後の実行を一覧表示するには**  
次の `describe-maintenance-window-schedule` の例では、指定されたメンテナンスウィンドウの今後の実行をすべて一覧表示します。  

```
aws ssm describe-maintenance-window-schedule \
    --window-id mw-ab12cd34eEXAMPLE
```
出力:  

```
{
    "ScheduledWindowExecutions": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2020-02-19T16:00Z"
        },
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "Name": "My-First-Maintenance-Window",
            "ExecutionTime": "2020-02-26T16:00Z"
        },
        ...
    ]
}
```
**例 2: 指定された日付より前のメンテナンスウィンドウの今後の実行をすべて一覧表示するには**  
次の `describe-maintenance-window-schedule` の例では、指定された日付より前に行われる指定されたメンテナンスウィンドウの今後の実行をすべて一覧表示します。  

```
aws ssm describe-maintenance-window-schedule \
    --window-id mw-0ecb1226dd7b2e9a6 \
    --filters "Key=ScheduledBefore,Values=2020-02-15T06:00:00Z"
```
**例 3: 指定された日付より後のメンテナンスウィンドウの今後の実行をすべて一覧表示するには**  
次の `describe-maintenance-window-schedule` の例では、指定された日付より後に行われる指定されたメンテナンスウィンドウの今後の実行をすべて一覧表示します。  

```
aws ssm describe-maintenance-window-schedule \
    --window-id mw-0ecb1226dd7b2e9a6 \
    --filters "Key=ScheduledAfter,Values=2020-02-15T06:00:00Z"
```
詳細については、*AWS 「 Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) に関する情報を表示する](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindowSchedule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-schedule.html)」を参照してください。

### `describe-maintenance-window-targets`
<a name="ssm_DescribeMaintenanceWindowTargets_cli_2_topic"></a>

次のコード例は、`describe-maintenance-window-targets` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウのすべてのターゲットを一覧表示するには**  
次の `describe-maintenance-window-targets` の例では、メンテナンスウィンドウのすべてのターゲットを一覧表示します。  

```
aws ssm describe-maintenance-window-targets \
    --window-id "mw-06cf17cbefEXAMPLE"
```
出力:  

```
{
    "Targets": [
        {
            "ResourceType": "INSTANCE",
            "OwnerInformation": "Single instance",
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "Targets": [
                {
                    "Values": [
                        "i-0000293ffdEXAMPLE"
                    ],
                    "Key": "InstanceIds"
                }
            ],
            "WindowTargetId": "350d44e6-28cc-44e2-951f-4b2c9EXAMPLE"
        },
        {
            "ResourceType": "INSTANCE",
            "OwnerInformation": "Two instances in a list",
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "Targets": [
                {
                    "Values": [
                        "i-0000293ffdEXAMPLE",
                        "i-0cb2b964d3EXAMPLE"
                    ],
                    "Key": "InstanceIds"
                }
            ],
            "WindowTargetId": "e078a987-2866-47be-bedd-d9cf4EXAMPLE"
        }
    ]
}
```
**例 2: 特定の所有者情報の値に一致するメンテナンスウィンドウのターゲットを一覧表示するには**  
この `describe-maintenance-window-targets` の例では、特定の値を持つメンテナンスウィンドウにおける、すべてのターゲットを一覧表示します。  

```
aws ssm describe-maintenance-window-targets \
    --window-id "mw-0ecb1226ddEXAMPLE" \
    --filters "Key=OwnerInformation,Values=CostCenter1"
```
出力:  

```
{
    "Targets": [
        {
            "WindowId": "mw-0ecb1226ddEXAMPLE",
            "WindowTargetId": "da89dcc3-7f9c-481d-ba2b-edcb7d0057f9",
            "ResourceType": "INSTANCE",
            "Targets": [
                {
                    "Key": "tag:Environment",
                    "Values": [
                        "Prod"
                    ]
                }
            ],
            "OwnerInformation": "CostCenter1",
            "Name": "ProdTarget1"
        }
    ]
}
```
詳細については、*AWS 「 Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) に関する情報を表示する](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindowTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-targets.html)」を参照してください。

### `describe-maintenance-window-tasks`
<a name="ssm_DescribeMaintenanceWindowTasks_cli_2_topic"></a>

次のコード例は、`describe-maintenance-window-tasks` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウのすべてのタスクを一覧表示するには**  
次の `describe-maintenance-window-tasks` の例では、指定されたメンテナンスウィンドウのすべてのタスクを一覧表示します。  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-06cf17cbefEXAMPLE"
```
出力:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "WindowTaskId": "018b31c3-2d77-4b9e-bd48-c91edEXAMPLE",
            "TaskArn": "AWS-RestartEC2Instance",
            "TaskParameters": {},
            "Type": "AUTOMATION",
            "Description": "Restarting EC2 Instance for maintenance",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "My-Automation-Example-Task",
            "Priority": 0,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ]
        },
        {
            "WindowId": "mw-06cf17cbefEXAMPLE",
            "WindowTaskId": "1943dee0-0a17-4978-9bf4-3cc2fEXAMPLE",
            "TaskArn": "AWS-DisableS3BucketPublicReadWrite",
            "TaskParameters": {},
            "Type": "AUTOMATION",
            "Description": "Automation task to disable read/write access on public S3 buckets",
            "MaxConcurrency": "10",
            "MaxErrors": "5",
            "Name": "My-Disable-S3-Public-Read-Write-Access-Automation-Task",
            "Priority": 0,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ]
        }
    ]
}
```
**例 2: AWS-RunPowerShellScript コマンドドキュメントを呼び出すメンテナンスウィンドウのすべてのタスクを一覧表示するには**  
次の `describe-maintenance-window-tasks` の例では、`AWS-RunPowerShellScript` コマンドドキュメントを呼び出す、指定されたメンテナンスウィンドウのタスクを一覧表示します。  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=TaskArn,Values=AWS-RunPowerShellScript"
```
出力:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE",
            "TaskArn": "AWS-RunPowerShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "MyTask"
        }
    ]
}
```
**例 3: メンテナンスウィンドウのタスクのうち、Priority が 3 のすべてのタスクを一覧表示するには**  
次の `describe-maintenance-window-tasks` の例では、指定されたメンテナンスウィンドウのタスクのうち、`Priority` が `3` であるすべてのタスクを一覧表示します。  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=Priority,Values=3"
```
出力:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE",
            "TaskArn": "AWS-RunPowerShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 3,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "MyRunCommandTask"
        },
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "ee45feff-ad65-4a6c-b478-5cab8EXAMPLE",
            "TaskArn": "AWS-RestartEC2Instance",
            "Type": "AUTOMATION",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 3,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "10",
            "MaxErrors": "5",
            "Name": "My-Automation-Task",
            "Description": "A description for my Automation task"
        }
    ]
}
```
**例 4: メンテナンスウィンドウのタスクのうち、Priority が 1 で Run Command を使用するすべてのタスクを一覧表示するには**  
この `describe-maintenance-window-tasks` の例では、指定されたメンテナンスウィンドウのタスクのうち、`Priority` が `1` で `Run Command` を使用するすべてのタスクを一覧表示します。  

```
aws ssm describe-maintenance-window-tasks \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --filters "Key=Priority,Values=1" "Key=TaskType,Values=RUN_COMMAND"
```
出力:  

```
{
    "Tasks": [
        {
            "WindowId": "mw-ab12cd34eEXAMPLE",
            "WindowTaskId": "0d36e6b4-3a4f-411e-adcb-3558eEXAMPLE",
            "TaskArn": "AWS-RunPowerShellScript",
            "Type": "RUN_COMMAND",
            "Targets": [
                {
                    "Key": "WindowTargetIds",
                    "Values": [
                        "da89dcc3-7f9c-481d-ba2b-edcb7EXAMPLE"
                    ]
                }
            ],
            "TaskParameters": {},
            "Priority": 1,
            "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Name": "MyRunCommandTask"
        }
    ]
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) に関する情報](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)を表示する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindowTasks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-window-tasks.html)」を参照してください。

### `describe-maintenance-windows-for-target`
<a name="ssm_DescribeMaintenanceWindowsForTarget_cli_2_topic"></a>

次のコード例は、`describe-maintenance-windows-for-target` を使用する方法を示しています。

**AWS CLI**  
**指定されたインスタンスに関連付けられているメンテナンスウィンドウをすべて一覧表示するには**  
次の `describe-maintenance-windows-for-target` の例では、指定されたインスタンスに関連付けられているターゲットまたはタスクのあるメンテナンスウィンドウを一覧表示します。  

```
aws ssm describe-maintenance-windows-for-target \
    --targets Key=InstanceIds,Values=i-1234567890EXAMPLE \
    --resource-type INSTANCE
```
出力:  

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-0c5ed765acEXAMPLE",
            "Name": "My-First-Maintenance-Window"
        }
    ]
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) に関する情報を表示する](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindowsForTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-windows-for-target.html)」を参照してください。

### `describe-maintenance-windows`
<a name="ssm_DescribeMaintenanceWindows_cli_2_topic"></a>

次のコード例は、`describe-maintenance-windows` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのメンテナンスウィンドウを一覧表示するには**  
次の の`describe-maintenance-windows`例では、現在のリージョンの AWS アカウント内のすべてのメンテナンスウィンドウを一覧表示します。  

```
aws ssm describe-maintenance-windows
```
出力:  

```
{
    "WindowIdentities": [
        {
            "WindowId": "mw-0ecb1226ddEXAMPLE",
            "Name": "MyMaintenanceWindow-1",
            "Enabled": true,
            "Duration": 2,
            "Cutoff": 1,
            "Schedule": "rate(180 minutes)",
            "NextExecutionTime": "2020-02-12T23:19:20.596Z"
        },
        {
            "WindowId": "mw-03eb9db428EXAMPLE",
            "Name": "MyMaintenanceWindow-2",
            "Enabled": true,
            "Duration": 3,
            "Cutoff": 1,
            "Schedule": "rate(7 days)",
            "NextExecutionTime": "2020-02-17T23:22:00.956Z"
        },
    ]
}
```
**例 2: すべての有効なメンテナンスウィンドウを一覧表示するには**  
次の `describe-maintenance-windows` の例では、すべての有効なメンテナンスウィンドウを一覧表示します。  

```
aws ssm describe-maintenance-windows \
    --filters "Key=Enabled,Values=true"
```
**例 3: 特定の名前に一致するメンテナンスウィンドウを一覧表示するには**  
この `describe-maintenance-windows` の例では、指定された名前を持つすべてのメンテナンスウィンドウを一覧表示します。  

```
aws ssm describe-maintenance-windows \
    --filters "Key=Name,Values=MyMaintenanceWindow"
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) に関する情報を表示する](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeMaintenanceWindows](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-maintenance-windows.html)」を参照してください。

### `describe-ops-items`
<a name="ssm_DescribeOpsItems_cli_2_topic"></a>

次のコード例は、`describe-ops-items` を使用する方法を示しています。

**AWS CLI**  
**OpsItems のセットを一覧表示するには**  
次の の`describe-ops-items`例では、 AWS アカウント内のすべての開いている OpsItems のリストを表示します。  

```
aws ssm describe-ops-items \
    --ops-item-filters "Key=Status,Values=Open,Operator=Equal"
```
出力:  

```
{
    "OpsItemSummaries": [
        {
            "CreatedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "CreatedTime": "2020-03-14T17:02:46.375000-07:00",
            "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "LastModifiedTime": "2020-03-14T17:02:46.375000-07:00",
            "Source": "SSM",
            "Status": "Open",
            "OpsItemId": "oi-7cfc5EXAMPLE",
            "Title": "SSM Maintenance Window execution failed",
            "OperationalData": {
                "/aws/dedup": {
                    "Value": "{\"dedupString\":\"SSMOpsItems-SSM-maintenance-window-execution-failed\"}",
                    "Type": "SearchableString"
                },
                "/aws/resources": {
                    "Value": "[{\"arn\":\"arn:aws:ssm:us-east-2:111222333444:maintenancewindow/mw-034093d322EXAMPLE\"}]",
                    "Type": "SearchableString"
                }
            },
            "Category": "Availability",
            "Severity": "3"
        },
        {
            "CreatedBy": "arn:aws:sts::1112223233444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "CreatedTime": "2020-02-26T11:43:15.426000-08:00",
            "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
            "LastModifiedTime": "2020-02-26T11:43:15.426000-08:00",
            "Source": "EC2",
            "Status": "Open",
            "OpsItemId": "oi-6f966EXAMPLE",
            "Title": "EC2 instance stopped",
            "OperationalData": {
                "/aws/automations": {
                    "Value": "[ { \"automationType\": \"AWS:SSM:Automation\", \"automationId\": \"AWS-RestartEC2Instance\" } ]",
                    "Type": "SearchableString"
                },
                "/aws/dedup": {
                    "Value": "{\"dedupString\":\"SSMOpsItems-EC2-instance-stopped\"}",
                    "Type": "SearchableString"
                },
                "/aws/resources": {
                    "Value": "[{\"arn\":\"arn:aws:ec2:us-east-2:111222333444:instance/i-0beccfbc02EXAMPLE\"}]",
                    "Type": "SearchableString"
                }
            },
            "Category": "Availability",
            "Severity": "3"
        }
    ]
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[OpsItems を管理する](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOpsItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-ops-items.html)」を参照してください。

### `describe-parameters`
<a name="ssm_DescribeParameters_cli_2_topic"></a>

次のコード例は、`describe-parameters` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのパラメータを一覧表示するには**  
次の の`describe-parameters`例では、現在の AWS アカウントとリージョンのすべてのパラメータを一覧表示します。  

```
aws ssm describe-parameters
```
出力:  

```
{
    "Parameters": [
        {
            "Name": "MySecureStringParameter",
            "Type": "SecureString",
            "KeyId": "alias/aws/ssm",
            "LastModifiedDate": 1582155479.205,
            "LastModifiedUser": "arn:aws:sts::111222333444:assumed-role/Admin/Richard-Roe-Managed",
            "Description": "This is a SecureString parameter",
            "Version": 2,
            "Tier": "Advanced",
            "Policies": [
                {
                    "PolicyText": "{\"Type\":\"Expiration\",\"Version\":\"1.0\",\"Attributes\":{\"Timestamp\":\"2020-07-07T22:30:00Z\"}}",
                    "PolicyType": "Expiration",
                    "PolicyStatus": "Pending"
                },
                {
                    "PolicyText": "{\"Type\":\"ExpirationNotification\",\"Version\":\"1.0\",\"Attributes\":{\"Before\":\"12\",\"Unit\":\"Hours\"}}",
                    "PolicyType": "ExpirationNotification",
                    "PolicyStatus": "Pending"
                }
            ]
        },
        {
            "Name": "MyStringListParameter",
            "Type": "StringList",
            "LastModifiedDate": 1582154764.222,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is a StringList parameter",
            "Version": 1,
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582154711.976,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Alejandro-Rosalez",
            "Description": "This is a String parameter",
            "Version": 1,
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "latestAmi",
            "Type": "String",
            "LastModifiedDate": 1580862415.521,
            "LastModifiedUser": "arn:aws:sts::111222333444:assumed-role/lambda-ssm-role/Automation-UpdateSSM-Param",
            "Version": 3,
            "Tier": "Standard",
            "Policies": []
        }
    ]
}
```
**例 2: 特定のメタデータに一致するすべてのパラメータを一覧表示するには**  
この `describe-parameters` の例は、フィルターに一致するすべてのパラメータを一覧表示します。  
aws ssm describe-parameters --filters "Key=Type,Values=StringList"  
出力:  

```
{
    "Parameters": [
        {
            "Name": "MyStringListParameter",
            "Type": "StringList",
            "LastModifiedDate": 1582154764.222,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is a StringList parameter",
            "Version": 1,
            "Tier": "Standard",
            "Policies": []
        }
    ]
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[Systems Manager のパラメータを検索する](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-search.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-parameters.html)」を参照してください。

### `describe-patch-baselines`
<a name="ssm_DescribePatchBaselines_cli_2_topic"></a>

次のコード例は、`describe-patch-baselines` を使用する方法を示しています。

**AWS CLI**  
**例 1: すべてのパッチベースラインを一覧表示するには**  
次の `describe-patch-baselines` 例は、現在のリージョン内におけるアカウントのすべてのパッチベースラインに関する詳細情報を取得します。  

```
aws ssm describe-patch-baselines
```
出力:  

```
{
    "BaselineIdentities": [
        {
            "BaselineName": "AWS-SuseDefaultPatchBaseline",
            "DefaultBaseline": true,
            "BaselineDescription": "Default Patch Baseline for Suse Provided by AWS.",
            "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-0123fdb36e334a3b2",
            "OperatingSystem": "SUSE"
        },
        {
            "BaselineName": "AWS-DefaultPatchBaseline",
            "DefaultBaseline": false,
            "BaselineDescription": "Default Patch Baseline Provided by AWS.",
            "BaselineId": "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-020d361a05defe4ed",
            "OperatingSystem": "WINDOWS"
        },
        ...
        {
            "BaselineName": "MyWindowsPatchBaseline",
            "DefaultBaseline": true,
            "BaselineDescription": "My patch baseline for EC2 instances for Windows Server",
            "BaselineId": "pb-0ad00e0dd7EXAMPLE",
            "OperatingSystem": "WINDOWS"
        }
    ]
}
```
**例 2: によって提供されるすべてのパッチベースラインを一覧表示するには AWS**  
次の の`describe-patch-baselines`例では、 が提供するすべてのパッチベースラインを一覧表示します AWS。  

```
aws ssm describe-patch-baselines \
    --filters "Key=OWNER,Values=[AWS]"
```
**例 3: 所有しているすべてのパッチベースラインを一覧表示するには**  
次の `describe-patch-baselines` の例では、現在のリージョンにおけるアカウントで作成されたすべてのカスタムパッチベースラインを一覧表示します。  

```
aws ssm describe-patch-baselines \
    --filters "Key=OWNER,Values=[Self]"
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[事前定義されたパッチベースラインおよびカスタムパッチベースライン](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baselines.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePatchBaselines](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-patch-baselines.html)」を参照してください。

### `describe-patch-group-state`
<a name="ssm_DescribePatchGroupState_cli_2_topic"></a>

次のコード例は、`describe-patch-group-state` を使用する方法を示しています。

**AWS CLI**  
**パッチグループの状態を取得するには**  
次の `describe-patch-group-state` の例では、パッチグループのパッチコンプライアンスの概要を取得します。  

```
aws ssm describe-patch-group-state \
    --patch-group "Production"
```
出力:  

```
{
    "Instances": 21,
    "InstancesWithCriticalNonCompliantPatches": 1,
    "InstancesWithFailedPatches": 2,
    "InstancesWithInstalledOtherPatches": 3,
    "InstancesWithInstalledPatches": 21,
    "InstancesWithInstalledPendingRebootPatches": 2,
    "InstancesWithInstalledRejectedPatches": 1,
    "InstancesWithMissingPatches": 3,
    "InstancesWithNotApplicablePatches": 4,
    "InstancesWithOtherNonCompliantPatches": 1,
    "InstancesWithSecurityNonCompliantPatches": 1,
    "InstancesWithUnreportedNotApplicablePatches": 2
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「パッチグループ」<https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-patchgroups.html> および「[パッチコンプライアンス状態の値について](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-compliance-states.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePatchGroupState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-patch-group-state.html)」を参照してください。

### `describe-patch-groups`
<a name="ssm_DescribePatchGroups_cli_2_topic"></a>

次のコード例は、`describe-patch-groups` を使用する方法を示しています。

**AWS CLI**  
**パッチグループの登録を表示するには**  
次の `describe-patch-groups` の例では、パッチグループの登録を一覧表示します。  

```
aws ssm describe-patch-groups
```
出力:  

```
{
    "Mappings": [
        {
            "PatchGroup": "Production",
            "BaselineIdentity": {
                "BaselineId": "pb-0123456789abcdef0",
                "BaselineName": "ProdPatching",
                "OperatingSystem": "WINDOWS",
                "BaselineDescription": "Patches for Production",
                "DefaultBaseline": false
            }
        },
        {
            "PatchGroup": "Development",
            "BaselineIdentity": {
                "BaselineId": "pb-0713accee01234567",
                "BaselineName": "DevPatching",
                "OperatingSystem": "WINDOWS",
                "BaselineDescription": "Patches for Development",
                "DefaultBaseline": true
            }
        },
        ...
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「パッチグループの作成 <https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-tagging.html>\$1\$1」および「[パッチベースラインにパッチグループを追加する](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePatchGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-patch-groups.html)」を参照してください。

### `describe-patch-properties`
<a name="ssm_DescribePatchProperties_cli_2_topic"></a>

次のコード例は、`describe-patch-properties` を使用する方法を示しています。

**AWS CLI**  
**Amazon Linux の利用可能なパッチを一覧表示するには**  
次の の`describe-patch-properties`例では、 AWS アカウントでパッチが利用可能な Amazon Linux 製品のリストを表示します。  

```
aws ssm describe-patch-properties \
    --operating-system AMAZON_LINUX \
    --property PRODUCT
```
出力:  

```
{
    "Properties": [
        {
            "Name": "AmazonLinux2012.03"
        },
        {
            "Name": "AmazonLinux2012.09"
        },
        {
            "Name": "AmazonLinux2013.03"
        },
        {
            "Name": "AmazonLinux2013.09"
        },
        {
            "Name": "AmazonLinux2014.03"
        },
        {
            "Name": "AmazonLinux2014.09"
        },
        {
            "Name": "AmazonLinux2015.03"
        },
        {
            "Name": "AmazonLinux2015.09"
        },
        {
            "Name": "AmazonLinux2016.03"
        },
        {
            "Name": "AmazonLinux2016.09"
        },
        {
            "Name": "AmazonLinux2017.03"
        },
        {
            "Name": "AmazonLinux2017.09"
        },
        {
            "Name": "AmazonLinux2018.03"
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パッチベースラインについて](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-baselines.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribePatchProperties](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-patch-properties.html)」を参照してください。

### `describe-sessions`
<a name="ssm_DescribeSessions_cli_2_topic"></a>

次のコード例は、`describe-sessions` を使用する方法を示しています。

**AWS CLI**  
**例 1: アクティブな Session Manager セッションをすべて一覧表示するには**  
この `describe-sessions` の例では、指定されたユーザーが過去 30 日間で最後に作成したアクティブなセッション (接続されたセッションと切断されたセッションの両方) のリストを取得します。このコマンドは、Session Manager を使用して開始されたターゲットへの接続の結果のみを返します。リモートデスクトップ接続や SSH など、他の方法で行われた接続は表示されません。  

```
aws ssm describe-sessions \
    --state "Active" \
    --filters "key=Owner,value=arn:aws:sts::123456789012:assumed-role/Administrator/Shirley-Rodriguez"
```
出力:  

```
{
    "Sessions": [
        {
            "SessionId": "John-07a16060613c408b5",
            "Target": "i-1234567890abcdef0",
            "Status": "Connected",
            "StartDate": 1550676938.352,
            "Owner": "arn:aws:sts::123456789012:assumed-role/Administrator/Shirley-Rodriguez",
            "OutputUrl": {}
        },
        {
            "SessionId": "John-01edf534b8b56e8eb",
            "Target": "i-9876543210abcdef0",
            "Status": "Connected",
            "StartDate": 1550676842.194,
            "Owner": "arn:aws:sts::123456789012:assumed-role/Administrator/Shirley-Rodriguez",
            "OutputUrl": {}
        }
    ]
}
```
**例 2: 終了した Session Manager セッションをすべて一覧表示するには**  
この `describe-sessions` の例では、すべてのユーザーについて、過去 30 日間で最後に終了したセッションのリストを取得します。  

```
aws ssm describe-sessions \
    --state "History"
```
出力:  

```
{
    "Sessions": [
        {
            "SessionId": "Mary-Major-0022b1eb2b0d9e3bd",
            "Target": "i-1234567890abcdef0",
            "Status": "Terminated",
            "StartDate": 1550520701.256,
            "EndDate": 1550521931.563,
            "Owner": "arn:aws:sts::123456789012:assumed-role/Administrator/Mary-Major"
        },
        {
            "SessionId": "Jane-Roe-0db53f487931ed9d4",
            "Target": "i-9876543210abcdef0",
            "Status": "Terminated",
            "StartDate": 1550161369.149,
            "EndDate": 1550162580.329,
            "Owner": "arn:aws:sts::123456789012:assumed-role/Administrator/Jane-Roe"
        },
        ...
    ],
    "NextToken": "--token string truncated--"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[セッション履歴を表示する](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-view-history.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeSessions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/describe-sessions.html)」を参照してください。

### `disassociate-ops-item-related-item`
<a name="ssm_DisassociateOpsItemRelatedItem_cli_2_topic"></a>

次のコード例は、`disassociate-ops-item-related-item` を使用する方法を示しています。

**AWS CLI**  
**関連項目の関連付けを削除するには**  
次の `disassociate-ops-item-related-item` の例では、OpsItem と関連項目の関連付けを削除します。  

```
aws ssm disassociate-ops-item-related-item \
    --ops-item-id "oi-f99f2EXAMPLE" \
    --association-id "e2036148-cccb-490e-ac2a-390e5EXAMPLE"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[OpsCenter で Incident Manager インシデントを操作する](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-create-OpsItems-for-Incident-Manager.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateOpsItemRelatedItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/disassociate-ops-item-related-item.html)」を参照してください。

### `get-automation-execution`
<a name="ssm_GetAutomationExecution_cli_2_topic"></a>

次のコード例は、`get-automation-execution` を使用する方法を示しています。

**AWS CLI**  
**オートメーションの実行に関する詳細情報を表示するには**  
次の `get-automation-execution` の例では、オートメーションの実行に関する詳細情報を表示します。  

```
aws ssm get-automation-execution \
    --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE
```
出力:  

```
{
    "AutomationExecution": {
        "AutomationExecutionId": "73c8eef8-f4ee-4a05-820c-e354fEXAMPLE",
        "DocumentName": "AWS-StartEC2Instance",
        "DocumentVersion": "1",
        "ExecutionStartTime": 1583737233.748,
        "ExecutionEndTime": 1583737234.719,
        "AutomationExecutionStatus": "Success",
        "StepExecutions": [
            {
                "StepName": "startInstances",
                "Action": "aws:changeInstanceState",
                "ExecutionStartTime": 1583737234.134,
                "ExecutionEndTime": 1583737234.672,
                "StepStatus": "Success",
                "Inputs": {
                    "DesiredState": "\"running\"",
                    "InstanceIds": "[\"i-0cb99161f6EXAMPLE\"]"
                },
                "Outputs": {
                    "InstanceStates": [
                        "running"
                    ]
                },
                "StepExecutionId": "95e70479-cf20-4d80-8018-7e4e2EXAMPLE",
                "OverriddenParameters": {}
            }
        ],
        "StepExecutionsTruncated": false,
        "Parameters": {
            "AutomationAssumeRole": [
                ""
            ],
            "InstanceId": [
                "i-0cb99161f6EXAMPLE"
            ]
        },
        "Outputs": {},
        "Mode": "Auto",
        "ExecutedBy": "arn:aws:sts::29884EXAMPLE:assumed-role/mw_service_role/OrchestrationService",
        "Targets": [],
        "ResolvedTargets": {
            "ParameterValues": [],
            "Truncated": false
        }
    }
}
```
詳細については、*AWS 「 Systems Manager ユーザーガイド*[」の「チュートリアル: Linux AMI (AWS CLI) にパッチ](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-walk-patch-linux-ami-cli.html)を適用する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAutomationExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-automation-execution.html)」を参照してください。

### `get-calendar-state`
<a name="ssm_GetCalendarState_cli_2_topic"></a>

次のコード例は、`get-calendar-state` を使用する方法を示しています。

**AWS CLI**  
**例 1: 変更カレンダーの現在の状態を取得するには**  
この `get-calendar-state` の例では、現在のカレンダーの状態を返します。この例では時刻を指定していないため、カレンダーの現在の状態が報告されます。  

```
aws ssm get-calendar-state \
    --calendar-names "MyCalendar"
```
出力:  

```
{
    "State": "OPEN",
    "AtTime": "2020-02-19T22:28:51Z",
    "NextTransitionTime": "2020-02-24T21:15:19Z"
}
```
**例 2: 指定された時刻に変更カレンダーの状態を取得するには**  
この `get-calendar-state` の例では、指定された時刻のカレンダーの状態を返します。  

```
aws ssm get-calendar-state \
    --calendar-names "MyCalendar" \
    --at-time "2020-07-19T21:15:19Z"
```
出力:  

```
{
    "State": "CLOSED",
    "AtTime": "2020-07-19T21:15:19Z"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Change Calendar の状態の取得](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-calendar-getstate.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCalendarState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-calendar-state.html)」を参照してください。

### `get-command-invocation`
<a name="ssm_GetCommandInvocation_cli_2_topic"></a>

次のコード例は、`get-command-invocation` を使用する方法を示しています。

**AWS CLI**  
**コマンド呼び出しの詳細情報を表示するには**  
次の `get-command-invocation` の例では、指定されたインスタンスにおける指定されたコマンドのすべての呼び出しを一覧表示します。  

```
aws ssm get-command-invocation \
    --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" \
    --instance-id "i-1234567890abcdef0"
```
出力:  

```
{
    "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678",
    "InstanceId": "i-1234567890abcdef0",
    "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
    "DocumentName": "AWS-UpdateSSMAgent",
    "DocumentVersion": "",
    "PluginName": "aws:updateSsmAgent",
    "ResponseCode": 0,
    "ExecutionStartDateTime": "2020-02-19T18:18:03.419Z",
    "ExecutionElapsedTime": "PT0.091S",
    "ExecutionEndDateTime": "2020-02-19T18:18:03.419Z",
    "Status": "Success",
    "StatusDetails": "Success",
    "StandardOutputContent": "Updating amazon-ssm-agent from 2.3.842.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\namazon-ssm-agent 2.3.842.0 has already been installed, update skipped\n",
    "StandardOutputUrl": "",
    "StandardErrorContent": "",
    "StandardErrorUrl": "",
    "CloudWatchOutputConfig": {
        "CloudWatchLogGroupName": "",
        "CloudWatchOutputEnabled": false
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[コマンドのステータスについて](https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetCommandInvocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-command-invocation.html)」を参照してください。

### `get-connection-status`
<a name="ssm_GetConnectionStatus_cli_2_topic"></a>

次のコード例は、`get-connection-status` を使用する方法を示しています。

**AWS CLI**  
**マネージドインスタンスの接続ステータスを表示するには**  
この `get-connection-status` の例では、指定されたマネージドインスタンスの接続ステータスを返します。  

```
aws ssm get-connection-status \
    --target i-1234567890abcdef0
```
出力:  

```
{
    "Target": "i-1234567890abcdef0",
    "Status": "connected"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetConnectionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-connection-status.html)」を参照してください。

### `get-default-patch-baseline`
<a name="ssm_GetDefaultPatchBaseline_cli_2_topic"></a>

次のコード例は、`get-default-patch-baseline` を使用する方法を示しています。

**AWS CLI**  
**例 1: デフォルトの Windows パッチベースラインを表示するには**  
次の `get-default-patch-baseline` の例では、Windows Server のデフォルトのパッチベースラインの詳細を取得します。  

```
aws ssm get-default-patch-baseline
```
出力:  

```
{
  "BaselineId": "pb-0713accee01612345",
  "OperatingSystem": "WINDOWS"
}
```
**例 2: デフォルトの Amazon Linux パッチベースラインを表示するには**  
次の `get-default-patch-baseline` の例では、Amazon Linux のデフォルトのパッチベースラインの詳細を取得します。  

```
aws ssm get-default-patch-baseline \
    --operating-system AMAZON_LINUX
```
出力:  

```
{
    "BaselineId": "pb-047c6eb9c8fc12345",
    "OperatingSystem": "AMAZON_LINUX"
}
```
詳細については、「事前定義されたパッチベースラインおよびカスタムパッチベースラインについて」<https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baselines.html> および「*AWS Systems Manager ユーザーガイド*」の「[既存のパッチベースラインをデフォルトとして設定する](https://docs.aws.amazon.com/systems-manager/latest/userguide/set-default-patch-baseline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDefaultPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-default-patch-baseline.html)」を参照してください。

### `get-deployable-patch-snapshot-for-instance`
<a name="ssm_GetDeployablePatchSnapshotForInstance_cli_2_topic"></a>

次のコード例は、`get-deployable-patch-snapshot-for-instance` を使用する方法を示しています。

**AWS CLI**  
**インスタンスが使用するパッチベースラインの現在のスナップショットを取得するには**  
次の `get-deployable-patch-snapshot-for-instance` の例では、インスタンスが使用する指定されたパッチベースラインの現在のスナップショットの詳細を取得します。このコマンドは、インスタンス認証情報を使用してインスタンスから実行する必要があります。インスタンス認証情報が使用されるようにするため、`aws configure` を実行し、インスタンスのリージョンのみを指定します。`Access Key` および `Secret Key` フィールドは空のままにします。  
ヒント: `uuidgen` を使用して `snapshot-id` を生成します。  

```
aws ssm get-deployable-patch-snapshot-for-instance \
    --instance-id "i-1234567890abcdef0" \
    --snapshot-id "521c3536-930c-4aa9-950e-01234567abcd"
```
出力:  

```
{
    "InstanceId": "i-1234567890abcdef0",
    "SnapshotId": "521c3536-930c-4aa9-950e-01234567abcd",
    "Product": "AmazonLinux2018.03",
    "SnapshotDownloadUrl": "https://patch-baseline-snapshot-us-east-1.s3.amazonaws.com/ed85194ef27214f5984f28b4d664d14f7313568fea7d4b6ac6c10ad1f729d7e7-773304212436/AMAZON_LINUX-521c3536-930c-4aa9-950e-01234567abcd?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20190215T164031Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=AKIAJ5C56P35AEBRX2QQ%2F20190215%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=efaaaf6e3878e77f48a6697e015efdbda9c426b09c5822055075c062f6ad2149"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パラメータ名: Snapshot ID](https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-manager-about-aws-runpatchbaseline.html#patch-manager-about-aws-runpatchbaseline-parameters-snapshot-id)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDeployablePatchSnapshotForInstance](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-deployable-patch-snapshot-for-instance.html)」を参照してください。

### `get-document`
<a name="ssm_GetDocument_cli_2_topic"></a>

次のコード例は、`get-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントコンテンツを取得するには**  
次の `get-document` の例では、Systems Manager ドキュメントのコンテンツを表示します。  

```
aws ssm get-document \
    --name "AWS-RunShellScript"
```
出力:  

```
{
    "Name": "AWS-RunShellScript",
    "DocumentVersion": "1",
    "Status": "Active",
    "Content": "{\n    \"schemaVersion\":\"1.2\",\n    \"description\":\"Run a shell script or specify the commands to run.\",\n    \"parameters\":{\n        \"commands\":{\n            \"type\":\"StringList\",\n            \"description\":\"(Required) Specify a shell script or a command to run.\",\n            \"minItems\":1,\n            \"displayType\":\"textarea\"\n        },\n        \"workingDirectory\":{\n            \"type\":\"String\",\n            \"default\":\"\",\n            \"description\":\"(Optional) The path to the working directory on your instance.\",\n            \"maxChars\":4096\n        },\n        \"executionTimeout\":{\n            \"type\":\"String\",\n            \"default\":\"3600\",\n            \"description\":\"(Optional) The time in seconds for a command to complete before it is considered to have failed. Default is 3600 (1 hour). Maximum is 172800 (48 hours).\",\n            \"allowedPattern\":\"([1-9][0-9]{0,4})|(1[0-6][0-9]{4})|(17[0-1][0-9]{3})|(172[0-7][0-9]{2})|(172800)\"\n        }\n    },\n    \"runtimeConfig\":{\n        \"aws:runShellScript\":{\n            \"properties\":[\n                {\n                    \"id\":\"0.aws:runShellScript\",\n                    \"runCommand\":\"{{ commands }}\",\n                    \"workingDirectory\":\"{{ workingDirectory }}\",\n                    \"timeoutSeconds\":\"{{ executionTimeout }}\"\n                }\n            ]\n        }\n    }\n}\n",
    "DocumentType": "Command",
    "DocumentFormat": "JSON"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[AWS Systems Manager ドキュメント](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-document.html)」を参照してください。

### `get-inventory-schema`
<a name="ssm_GetInventorySchema_cli_2_topic"></a>

次のコード例は、`get-inventory-schema` を使用する方法を示しています。

**AWS CLI**  
**インベントリスキーマを表示するには**  
この例では、アカウントのインベントリタイプ名のリストを返します。  
コマンド:  

```
aws ssm get-inventory-schema
```
出力:  

```
{
  "Schemas": [
      {
          "TypeName": "AWS:AWSComponent",
          "Version": "1.0",
          "Attributes": [
              {
                  "Name": "Name",
                  "DataType": "STRING"
              },
              {
                  "Name": "ApplicationType",
                  "DataType": "STRING"
              },
              {
                  "Name": "Publisher",
                  "DataType": "STRING"
              },
              {
                  "Name": "Version",
                  "DataType": "STRING"
              },
              {
                  "Name": "InstalledTime",
                  "DataType": "STRING"
              },
              {
                  "Name": "Architecture",
                  "DataType": "STRING"
              },
              {
                  "Name": "URL",
                  "DataType": "STRING"
              }
          ]
      },
      ...
  ],
  "NextToken": "--token string truncated--"
}
```
**特定のインベントリタイプのインベントリスキーマを表示するには**  
この例では、 AWS:AWSコンポーネントインベントリタイプのインベントリスキーマを返します。  
コマンド:  

```
aws ssm get-inventory-schema --type-name "AWS:AWSComponent"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInventorySchema](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-inventory-schema.html)」を参照してください。

### `get-inventory`
<a name="ssm_GetInventory_cli_2_topic"></a>

次のコード例は、`get-inventory` を使用する方法を示しています。

**AWS CLI**  
**インベントリを表示するには**  
この例では、インベントリのカスタムメタデータを取得します。  
コマンド:  

```
aws ssm get-inventory
```
出力:  

```
{
  "Entities": [
      {
          "Data": {
              "AWS:InstanceInformation": {
                  "Content": [
                      {
                          "ComputerName": "ip-172-31-44-222.us-west-2.compute.internal",
                          "InstanceId": "i-0cb2b964d3e14fd9f",
                          "IpAddress": "172.31.44.222",
                          "AgentType": "amazon-ssm-agent",
                          "ResourceType": "EC2Instance",
                          "AgentVersion": "2.0.672.0",
                          "PlatformVersion": "2016.09",
                          "PlatformName": "Amazon Linux AMI",
                          "PlatformType": "Linux"
                      }
                  ],
                  "TypeName": "AWS:InstanceInformation",
                  "SchemaVersion": "1.0",
                  "CaptureTime": "2017-02-20T18:03:58Z"
              }
          },
          "Id": "i-0cb2b964d3e14fd9f"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetInventory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-inventory.html)」を参照してください。

### `get-maintenance-window-execution-task-invocation`
<a name="ssm_GetMaintenanceWindowExecutionTaskInvocation_cli_2_topic"></a>

次のコード例は、`get-maintenance-window-execution-task-invocation` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウのタスク呼び出しに関する情報を取得するには**  
次の `get-maintenance-window-execution-task-invocation` の例では、指定されたメンテナンスウィンドウの実行の一部である指定されたタスク呼び出しに関する情報を一覧表示します。  

```
aws ssm get-maintenance-window-execution-task-invocation \
    --window-execution-id "bc494bfa-e63b-49f6-8ad1-aa9f2EXAMPLE" \
    --task-id "96f2ad59-97e3-461d-a63d-40c8aEXAMPLE" \
    --invocation-id "a5273e2c-d2c6-4880-b3e1-5e550EXAMPLE"
```
出力:  

```
{
    "Status": "SUCCESS",
    "Parameters": "{\"comment\":\"\",\"documentName\":\"AWS-RunPowerShellScript\",\"instanceIds\":[\"i-1234567890EXAMPLE\"],\"maxConcurrency\":\"1\",\"maxErrors\":\"1\",\"parameters\":{\"executionTimeout\":[\"3600\"],\"workingDirectory\":[\"\"],\"commands\":[\"echo Hello\"]},\"timeoutSeconds\":600}",
    "ExecutionId": "03b6baa0-5460-4e15-83f2-ea685EXAMPLE",
    "InvocationId": "a5273e2c-d2c6-4880-b3e1-5e550EXAMPLE",
    "StartTime": 1549998326.421,
    "TaskType": "RUN_COMMAND",
    "EndTime": 1550001931.784,
    "WindowExecutionId": "bc494bfa-e63b-49f6-8ad1-aa9f2EXAMPLE",
    "StatusDetails": "Failed",
    "TaskExecutionId": "96f2ad59-97e3-461d-a63d-40c8aEXAMPLE"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「タスクとタスク実行に関する情報を表示する (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMaintenanceWindowExecutionTaskInvocation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window-execution-task-invocation.html)」を参照してください。

### `get-maintenance-window-execution-task`
<a name="ssm_GetMaintenanceWindowExecutionTask_cli_2_topic"></a>

次のコード例は、`get-maintenance-window-execution-task` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウのタスクの実行に関する情報を取得するには**  
次の `get-maintenance-window-execution-task` の例では、指定されたメンテナンスウィンドウの実行の一部であるタスクに関する情報を一覧表示します。  

```
aws ssm get-maintenance-window-execution-task \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE" \
    --task-id "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE"
```
出力:  

```
{
    "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE",
    "TaskExecutionId": "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE",
    "TaskArn": "AWS-RunPatchBaseline",
    "ServiceRole": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
    "Type": "RUN_COMMAND",
    "TaskParameters": [
        {
            "BaselineOverride": {
                "Values": [
                    ""
                ]
            },
            "InstallOverrideList": {
                "Values": [
                    ""
                ]
            },
            "Operation": {
                "Values": [
                    "Scan"
                ]
            },
            "RebootOption": {
                "Values": [
                    "RebootIfNeeded"
                ]
            },
            "SnapshotId": {
                "Values": [
                    "{{ aws:ORCHESTRATION_ID }}"
                ]
            },
            "aws:InstanceId": {
                "Values": [
                    "i-02573cafcfEXAMPLE",
                    "i-0471e04240EXAMPLE",
                    "i-07782c72faEXAMPLE"
                ]
            }
        }
    ],
    "Priority": 1,
    "MaxConcurrency": "1",
    "MaxErrors": "3",
    "Status": "SUCCESS",
    "StartTime": "2021-08-04T11:45:35.088000-07:00",
    "EndTime": "2021-08-04T11:53:09.079000-07:00"
}
```
詳細については、*AWS 「Systems* [Manager ユーザーガイド」の「タスクとタスク実行 (AWS CLI) に関する情報](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html)を表示する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMaintenanceWindowExecutionTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window-execution-task.html)」を参照してください。

### `get-maintenance-window-execution`
<a name="ssm_GetMaintenanceWindowExecution_cli_2_topic"></a>

次のコード例は、`get-maintenance-window-execution` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウのタスクの実行に関する情報を取得するには**  
次の `get-maintenance-window-execution` の例では、指定されたメンテナンスウィンドウの一部として実行されるタスクに関する情報を一覧表示します。  

```
aws ssm get-maintenance-window-execution \
    --window-execution-id "518d5565-5969-4cca-8f0e-da3b2EXAMPLE"
```
出力:  

```
{
    "Status": "SUCCESS",
    "TaskIds": [
        "ac0c6ae1-daa3-4a89-832e-d3845EXAMPLE"
    ],
    "StartTime": 1487692834.595,
    "EndTime": 1487692835.051,
    "WindowExecutionId": "518d5565-5969-4cca-8f0e-da3b2EXAMPLE",
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「タスクとタスク実行に関する情報の表示 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-task-info.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMaintenanceWindowExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window-execution.html)」を参照してください。

### `get-maintenance-window-task`
<a name="ssm_GetMaintenanceWindowTask_cli_2_topic"></a>

次のコード例は、`get-maintenance-window-task` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウタスクに関する情報を取得するには**  
次の `get-maintenance-window-task` の例では、指定されたメンテナンスウィンドウタスクの詳細情報を取得します。  

```
aws ssm get-maintenance-window-task \
    --window-id mw-0c5ed765acEXAMPLE \
    --window-task-id 0e842a8d-2d44-4886-bb62-af8dcEXAMPLE
```
出力:  

```
{
    "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
    "MaxErrors": "1",
    "TaskArn": "AWS-RunPowerShellScript",
    "MaxConcurrency": "1",
    "WindowTaskId": "0e842a8d-2d44-4886-bb62-af8dcEXAMPLE",
    "TaskParameters": {},
    "Priority": 1,
    "TaskInvocationParameters": {
        "RunCommand": {
            "Comment": "",
            "TimeoutSeconds": 600,
            "Parameters": {
                "commands": [
                    "echo Hello"
                ],
                "executionTimeout": [
                    "3600"
                ],
                "workingDirectory": [
                    ""
                ]
            }
        }
    },
    "WindowId": "mw-0c5ed765acEXAMPLE",
    "TaskType": "RUN_COMMAND",
    "Targets": [
        {
            "Values": [
                "84c818da-b619-4d3d-9651-946f3EXAMPLE"
            ],
            "Key": "WindowTargetIds"
        }
    ],
    "Name": "ExampleTask"
}
```
詳細については、*AWS 「 Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) に関する情報を表示する](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMaintenanceWindowTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window-task.html)」を参照してください。

### `get-maintenance-window`
<a name="ssm_GetMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`get-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウに関する情報を取得するには**  
次の `get-maintenance-window` の例では、指定されたメンテナンスウィンドウの詳細情報を取得します。  

```
aws ssm get-maintenance-window \
    --window-id "mw-03eb9db428EXAMPLE"
```
出力:  

```
{
    "AllowUnassociatedTargets": true,
    "CreatedDate": 1515006912.957,
    "Cutoff": 1,
    "Duration": 6,
    "Enabled": true,
    "ModifiedDate": 2020-01-01T10:04:04.099Z,
    "Name": "My-Maintenance-Window",
    "Schedule": "rate(3 days)",
    "WindowId": "mw-03eb9db428EXAMPLE",
    "NextExecutionTime": "2020-02-25T00:08:15.099Z"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) に関する情報](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-describe.html)を表示する」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-maintenance-window.html)」を参照してください。

### `get-ops-item`
<a name="ssm_GetOpsItem_cli_2_topic"></a>

次のコード例は、`get-ops-item` を使用する方法を示しています。

**AWS CLI**  
**OpsItem に関する情報を表示するには**  
次の `get-ops-item` の例では、指定された OpsItem の詳細情報を表示します。  

```
aws ssm get-ops-item \
    --ops-item-id oi-0b725EXAMPLE
```
出力:  

```
{
    "OpsItem": {
        "CreatedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
        "CreatedTime": "2019-12-04T15:52:16.793000-08:00",
        "Description": "CloudWatch Event Rule SSMOpsItems-EC2-instance-terminated was triggered. Your EC2 instance has terminated. See below for more details.",
        "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
        "LastModifiedTime": "2019-12-04T15:52:16.793000-08:00",
        "Notifications": [],
        "RelatedOpsItems": [],
        "Status": "Open",
        "OpsItemId": "oi-0b725EXAMPLE",
        "Title": "EC2 instance terminated",
        "Source": "EC2",
        "OperationalData": {
            "/aws/automations": {
                "Value": "[ { \"automationType\": \"AWS:SSM:Automation\", \"automationId\": \"AWS-CreateManagedWindowsInstance\" }, { \"automationType\": \"AWS:SSM:Automation\", \"automationId\": \"AWS-CreateManagedLinuxInstance\" } ]",
                "Type": "SearchableString"
            },
            "/aws/dedup": {
                "Value": "{\"dedupString\":\"SSMOpsItems-EC2-instance-terminated\"}",
                "Type": "SearchableString"
            },
            "/aws/resources": {
                "Value": "[{\"arn\":\"arn:aws:ec2:us-east-2:111222333444:instance/i-05adec7e97EXAMPLE\"}]",
                "Type": "SearchableString"
            },
            "event-time": {
                "Value": "2019-12-04T23:52:16Z",
                "Type": "String"
            },
            "instance-state": {
                "Value": "terminated",
                "Type": "String"
            }
        },
        "Category": "Availability",
        "Severity": "4"
    }
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[OpsItems を管理する](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOpsItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-ops-item.html)」を参照してください。

### `get-ops-summary`
<a name="ssm_GetOpsSummary_cli_2_topic"></a>

次のコード例は、`get-ops-summary` を使用する方法を示しています。

**AWS CLI**  
**すべての OpsItems の概要を表示するには**  
次の の`get-ops-summary`例では、 AWS アカウント内のすべての OpsItems の概要を表示します。  

```
aws ssm get-ops-summary
```
出力:  

```
{
    "Entities": [
        {
            "Id": "oi-4309fEXAMPLE",
            "Data": {
                "AWS:OpsItem": {
                    "CaptureTime": "2020-02-26T18:58:32.918Z",
                    "Content": [
                        {
                            "AccountId": "111222333444",
                            "Category": "Availability",
                            "CreatedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
                            "CreatedTime": "2020-02-26T19:10:44.149Z",
                            "Description": "CloudWatch Event Rule SSMOpsItems-EC2-instance-terminated was triggered. Your EC2 instance has terminated. See below for more details.",
                            "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
                            "LastModifiedTime": "2020-02-26T19:10:44.149Z",
                            "Notifications": "",
                            "OperationalData": "{\"/aws/automations\":{\"type\":\"SearchableString\",\"value\":\"[ { \\\"automationType\\\": \\\"AWS:SSM:Automation\\\", \\\"automationId\\\": \\\"AWS-CreateManagedWindowsInstance\\\" }, { \\\"automationType\\\": \\\"AWS:SSM:Automation\\\", \\\"automationId\\\": \\\"AWS-CreateManagedLinuxInstance\\\" } ]\"},\"/aws/resources\":{\"type\":\"SearchableString\",\"value\":\"[{\\\"arn\\\":\\\"arn:aws:ec2:us-east-2:111222333444:instance/i-0acbd0800fEXAMPLE\\\"}]\"},\"/aws/dedup\":{\"type\":\"SearchableString\",\"value\":\"{\\\"dedupString\\\":\\\"SSMOpsItems-EC2-instance-terminated\\\"}\"}}",
                            "OpsItemId": "oi-4309fEXAMPLE",
                            "RelatedItems": "",
                            "Severity": "3",
                            "Source": "EC2",
                            "Status": "Open",
                            "Title": "EC2 instance terminated"
                        }
                    ]
                }
            }
        },
        {
            "Id": "oi-bb2a0e6a4541",
            "Data": {
                "AWS:OpsItem": {
                    "CaptureTime": "2019-11-26T19:20:06.161Z",
                    "Content": [
                        {
                            "AccountId": "111222333444",
                            "Category": "Availability",
                            "CreatedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
                            "CreatedTime": "2019-11-26T20:00:07.237Z",
                            "Description": "CloudWatch Event Rule SSMOpsItems-SSM-maintenance-window-execution-failed was triggered. Your SSM Maintenance Window execution has failed. See below for more details.",
                            "LastModifiedBy": "arn:aws:sts::111222333444:assumed-role/OpsItem-CWE-Role/fbf77cbe264a33509569f23e4EXAMPLE",
                            "LastModifiedTime": "2019-11-26T20:00:07.237Z",
                            "Notifications": "",
                            "OperationalData": "{\"/aws/resources\":{\"type\":\"SearchableString\",\"value\":\"[{\\\"arn\\\":\\\"arn:aws:ssm:us-east-2:111222333444:maintenancewindow/mw-0e83ba440dEXAMPLE\\\"}]\"},\"/aws/dedup\":{\"type\":\"SearchableString\",\"value\":\"{\\\"dedupString\\\":\\\"SSMOpsItems-SSM-maintenance-window-execution-failed\\\"}\"}}",
                            "OpsItemId": "oi-bb2a0EXAMPLE",
                            "RelatedItems": "",
                            "Severity": "3",
                            "Source": "SSM",
                            "Status": "Open",
                            "Title": "SSM Maintenance Window execution failed"
                        }
                    ]
                }
            }
        }
    ]
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[OpsItems を管理する](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOpsSummary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-ops-summary.html)」を参照してください。

### `get-parameter-history`
<a name="ssm_GetParameterHistory_cli_2_topic"></a>

次のコード例は、`get-parameter-history` を使用する方法を示しています。

**AWS CLI**  
**パラメータの値の履歴を取得するには**  
次の `get-parameter-history` の例では、指定されたパラメータの変更履歴を、値を含めて一覧表示します。  

```
aws ssm get-parameter-history \
    --name "MyStringParameter"
```
出力:  

```
{
    "Parameters": [
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582154711.976,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is the first version of my String parameter",
            "Value": "Veni",
            "Version": 1,
            "Labels": [],
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582156093.471,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is the second version of my String parameter",
            "Value": "Vidi",
            "Version": 2,
            "Labels": [],
            "Tier": "Standard",
            "Policies": []
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "LastModifiedDate": 1582156117.545,
            "LastModifiedUser": "arn:aws:iam::111222333444:user/Mary-Major",
            "Description": "This is the third version of my String parameter",
            "Value": "Vici",
            "Version": 3,
            "Labels": [],
            "Tier": "Standard",
            "Policies": []
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パラメータバージョンの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-versions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParameterHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-parameter-history.html)」を参照してください。

### `get-parameter`
<a name="ssm_GetParameter_cli_2_topic"></a>

次のコード例は、`get-parameter` を使用する方法を示しています。

**AWS CLI**  
**例 1: パラメータの値を表示する**  
次の `get-parameter` 例は、指定された単一のパラメータの値を一覧表示します。  

```
aws ssm get-parameter \
    --name "MyStringParameter"
```
出力:  

```
{
    "Parameter": {
        "Name": "MyStringParameter",
        "Type": "String",
        "Value": "Veni",
        "Version": 1,
        "LastModifiedDate": 1530018761.888,
        "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MyStringParameter"
        "DataType": "text"
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store の使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)」を参照してください。  
**例 2: SecureString パラメータの値を復号化する**  
次の `get-parameter` 例は、指定された `SecureString` パラメータの値を複合化します。  

```
aws ssm get-parameter \
    --name "MySecureStringParameter" \
    --with-decryption
```
出力:  

```
{
    "Parameter": {
        "Name": "MySecureStringParameter",
        "Type": "SecureString",
        "Value": "16679b88-310b-4895-a943-e0764EXAMPLE",
        "Version": 2,
        "LastModifiedDate": 1582155479.205,
        "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MySecureStringParameter"
        "DataType": "text"
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store の使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)」を参照してください。  
**例 3: ラベルを使用してパラメータの値を表示する**  
次の `get-parameter` 例は、特定のラベルを使用して、指定された単一のパラメータの値を一覧表示します。  

```
aws ssm get-parameter \
    --name "MyParameter:label"
```
出力:  

```
{
    "Parameter": {
        "Name": "MyParameter",
        "Type": "String",
        "Value": "parameter version 2",
        "Version": 2,
        "Selector": ":label",
        "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00",
        "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter",
        "DataType": "text"
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パラメータラベルの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)」を参照してください。  
**例 4: バージョンを使用してパラメータの値を表示する**  
次の `get-parameter` 例は、指定された単一のパラメータバージョンの値を一覧表示します。  

```
aws ssm get-parameter \
    --name "MyParameter:2"
```
出力:  

```
{
    "Parameter": {
        "Name": "MyParameter",
        "Type": "String",
        "Value": "parameter version 2",
        "Version": 2,
        "Selector": ":2",
        "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00",
        "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter",
        "DataType": "text"
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パラメータラベルの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParameter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-parameter.html)」を参照してください。

### `get-parameters-by-path`
<a name="ssm_GetParametersByPath_cli_2_topic"></a>

次のコード例は、`get-parameters-by-path` を使用する方法を示しています。

**AWS CLI**  
**指定されたパスのパラメータを一覧表示するには**  
次の `get-parameters-by-path` の例では、指定された階層内のパラメータを一覧表示します。  

```
aws ssm get-parameters-by-path \
    --path "/site/newyork/department/"
```
出力:  

```
{
    "Parameters": [
        {
            "Name": "/site/newyork/department/marketing",
            "Type": "String",
            "Value": "Floor 2",
            "Version": 1,
            "LastModifiedDate": 1530018761.888,
            "ARN": "arn:aws:ssm:us-east-1:111222333444:parameter/site/newyork/department/marketing"
        },
        {
            "Name": "/site/newyork/department/infotech",
            "Type": "String",
            "Value": "Floor 3",
            "Version": 1,
            "LastModifiedDate": 1530018823.429,
            "ARN": "arn:aws:ssm:us-east-1:111222333444:parameter/site/newyork/department/infotech"
        },
        ...
    ]
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[パラメータ階層の使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-hierarchies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParametersByPath](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-parameters-by-path.html)」を参照してください。

### `get-parameters`
<a name="ssm_GetParameters_cli_2_topic"></a>

次のコード例は、`get-parameters` を使用する方法を示しています。

**AWS CLI**  
**例 1: パラメータの値を一覧表示するには**  
次の `get-parameters` の例では、指定した 3 つのパラメータの値を一覧表示します。  

```
aws ssm get-parameters \
    --names "MyStringParameter" "MyStringListParameter" "MyInvalidParameterName"
```
出力:  

```
{
    "Parameters": [
        {
            "Name": "MyStringListParameter",
            "Type": "StringList",
            "Value": "alpha,beta,gamma",
            "Version": 1,
            "LastModifiedDate": 1582154764.222,
            "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MyStringListParameter"
            "DataType": "text"
        },
        {
            "Name": "MyStringParameter",
            "Type": "String",
            "Value": "Vici",
            "Version": 3,
            "LastModifiedDate": 1582156117.545,
            "ARN": "arn:aws:ssm:us-east-2:111222333444:parameter/MyStringParameter"
            "DataType": "text"
        }
    ],
    "InvalidParameters": [
        "MyInvalidParameterName"
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store の使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)」を参照してください。  
**例 2: ``--query`` オプションを使用して複数のパラメータの名前と値を一覧表示するには**  
次の `get-parameters` の例では、指定したパラメータの名前と値を一覧表示します。  

```
aws ssm get-parameters \
    --names MyStringParameter MyStringListParameter \
    --query "Parameters[*].{Name:Name,Value:Value}"
```
出力:  

```
[
    {
        "Name": "MyStringListParameter",
        "Value": "alpha,beta,gamma"
    },
    {
        "Name": "MyStringParameter",
        "Value": "Vidi"
    }
]
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store の使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-working-with.html)」を参照してください。  
**例 3: ラベルを使用してパラメータの値を表示する**  
次の `get-parameter` 例は、特定のラベルを使用して、指定された単一のパラメータの値を一覧表示します。  

```
aws ssm get-parameter \
    --name "MyParameter:label"
```
出力:  

```
{
    "Parameters": [
        {
            "Name": "MyLabelParameter",
            "Type": "String",
            "Value": "parameter by label",
            "Version": 1,
            "Selector": ":label",
            "LastModifiedDate": "2021-07-12T09:49:15.865000-07:00",
            "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/MyParameter",
            "DataType": "text"
        },
        {
            "Name": "MyVersionParameter",
            "Type": "String",
            "Value": "parameter by version",
            "Version": 2,
            "Selector": ":2",
            "LastModifiedDate": "2021-03-24T16:20:28.236000-07:00",
            "ARN": "arn:aws:ssm:us-west-2:786973925828:parameter/unlabel-param",
            "DataType": "text"
        }
    ],
    "InvalidParameters": []
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[パラメータラベルの操作](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetParameters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-parameters.html)」を参照してください。

### `get-patch-baseline-for-patch-group`
<a name="ssm_GetPatchBaselineForPatchGroup_cli_2_topic"></a>

次のコード例は、`get-patch-baseline-for-patch-group` を使用する方法を示しています。

**AWS CLI**  
**パッチグループのパッチベースラインを表示するには**  
次の `get-patch-baseline-for-patch-group` の例では、指定されたパッチグループのパッチベースラインに関する詳細を取得します。  

```
aws ssm get-patch-baseline-for-patch-group \
    --patch-group "DEV"
```
出力:  

```
{
    "PatchGroup": "DEV",
    "BaselineId": "pb-0123456789abcdef0",
    "OperatingSystem": "WINDOWS"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「パッチグループの作成 <https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-tagging.html>\$1\$1」および「[パッチベースラインにパッチグループを追加する](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPatchBaselineForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-patch-baseline-for-patch-group.html)」を参照してください。

### `get-patch-baseline`
<a name="ssm_GetPatchBaseline_cli_2_topic"></a>

次のコード例は、`get-patch-baseline` を使用する方法を示しています。

**AWS CLI**  
**パッチベースラインを表示するには**  
次の `get-patch-baseline` の例では、指定されたパッチベースラインの詳細を取得します。  

```
aws ssm get-patch-baseline \
    --baseline-id "pb-0123456789abcdef0"
```
出力:  

```
{
    "BaselineId": "pb-0123456789abcdef0",
    "Name": "WindowsPatching",
    "OperatingSystem": "WINDOWS",
    "GlobalFilters": {
        "PatchFilters": []
    },
    "ApprovalRules": {
        "PatchRules": [
            {
                "PatchFilterGroup": {
                    "PatchFilters": [
                        {
                            "Key": "PRODUCT",
                            "Values": [
                                "WindowsServer2016"
                            ]
                        }
                    ]
                },
                "ComplianceLevel": "CRITICAL",
                "ApproveAfterDays": 0,
                "EnableNonSecurity": false
            }
        ]
    },
    "ApprovedPatches": [],
    "ApprovedPatchesComplianceLevel": "UNSPECIFIED",
    "ApprovedPatchesEnableNonSecurity": false,
    "RejectedPatches": [],
    "RejectedPatchesAction": "ALLOW_AS_DEPENDENCY",
    "PatchGroups": [
        "QA",
        "DEV"
    ],
    "CreatedDate": 1550244180.465,
    "ModifiedDate": 1550244180.465,
    "Description": "Patches for Windows Servers",
    "Sources": []
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パッチベースラインについて](https://docs.aws.amazon.com/systems-manager/latest/userguide/about-patch-baselines.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-patch-baseline.html)」を参照してください。

### `get-service-setting`
<a name="ssm_GetServiceSetting_cli_2_topic"></a>

次のコード例は、`get-service-setting` を使用する方法を示しています。

**AWS CLI**  
**Parameter Store スループットのサービス設定を取得するには**  
次の `get-service-setting` の例では、指定されたリージョンの Parameter Store スループットの現在のサービス設定を取得します。  

```
aws ssm get-service-setting \
    --setting-id arn:aws:ssm:us-east-1:123456789012:servicesetting/ssm/parameter-store/high-throughput-enabled
```
出力:  

```
{
    "ServiceSetting": {
        "SettingId": "/ssm/parameter-store/high-throughput-enabled",
        "SettingValue": "false",
        "LastModifiedDate": 1555532818.578,
        "LastModifiedUser": "System",
        "ARN": "arn:aws:ssm:us-east-1:123456789012:servicesetting/ssm/parameter-store/high-throughput-enabled",
        "Status": "Default"
    }
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[Parameter Store スループットの引き上げ](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-throughput.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceSetting](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/get-service-setting.html)」を参照してください。

### `label-parameter-version`
<a name="ssm_LabelParameterVersion_cli_2_topic"></a>

次のコード例は、`label-parameter-version` を使用する方法を示しています。

**AWS CLI**  
**例 1: パラメータの最新バージョンにラベルを追加するには**  
次の `label-parameter-version` 例では、指定されたパラメータの最新バージョンにラベルを追加します。  

```
aws ssm label-parameter-version \
    --name "MyStringParameter" \
    --labels "ProductionReady"
```
出力:  

```
{
    "InvalidLabels": [],
    "ParameterVersion": 3
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パラメータラベルの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)」を参照してください。  
**例 2: 特定のバージョンのパラメータにラベルを追加するには**  
次の `label-parameter-version` の例では、指定されたバージョンのパラメータにラベルを追加します。  

```
aws ssm label-parameter-version \
    --name "MyStringParameter" \
    --labels "ProductionReady" \
    --parameter-version "2" --labels "DevelopmentReady"
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[パラメータラベルの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[LabelParameterVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/label-parameter-version.html)」を参照してください。

### `list-association-versions`
<a name="ssm_ListAssociationVersions_cli_2_topic"></a>

次のコード例は、`list-association-versions` を使用する方法を示しています。

**AWS CLI**  
**特定の関連付け ID のすべてのバージョンの関連付けを取得するには**  
次の `list-association-versions` の例では、指定された関連付けのすべてのバージョンを一覧表示します。  

```
aws ssm list-association-versions \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
出力:  

```
{
"AssociationVersions": [
        {
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "CreatedDate": 1550505536.726,
            "Name": "AWS-UpdateSSMAgent",
            "Parameters": {
                "allowDowngrade": [
                    "false"
                ],
                "version": [
                    ""
                ]
            },
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-1234567890abcdef0"
                    ]
                }
            ],
            "ScheduleExpression": "cron(0 00 12 ? * SUN *)",
            "AssociationName": "UpdateSSMAgent"
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager の関連付けの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssociationVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-association-versions.html)」を参照してください。

### `list-associations`
<a name="ssm_ListAssociations_cli_2_topic"></a>

次のコード例は、`list-associations` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定のインスタンスの関連付けを一覧表示するには**  
次の list-associations の例では、AssociationName、UpdateSSMAgent とのすべての関連付けを一覧表示します。  

```
aws ssm list-associations /
    --association-filter-list "key=AssociationName,value=UpdateSSMAgent"
```
出力:  

```
{
    "Associations": [
        {
            "Name": "AWS-UpdateSSMAgent",
            "InstanceId": "i-1234567890abcdef0",
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-016648b75dd622dab"
                    ]
                }
            ],
            "Overview": {
                "Status": "Pending",
                "DetailedStatus": "Associated",
                "AssociationStatusAggregatedCount": {
                    "Pending": 1
                }
            },
            "ScheduleExpression": "cron(0 00 12 ? * SUN *)",
            "AssociationName": "UpdateSSMAgent"
        }
    ]
}
```
詳細については、「* Systems Manager ユーザーガイド*」の「[Systems Manager の関連付けの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)」を参照してください。  
**例 2: 特定のドキュメントの関連付けを一覧表示するには**  
次の list-associations の例では、指定したドキュメントのすべての関連付けを一覧表示します。  

```
aws ssm list-associations /
    --association-filter-list "key=Name,value=AWS-UpdateSSMAgent"
```
出力:  

```
{
    "Associations": [
        {
            "Name": "AWS-UpdateSSMAgent",
            "InstanceId": "i-1234567890abcdef0",
            "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-1234567890abcdef0"
                    ]
                }
            ],
            "LastExecutionDate": 1550505828.548,
            "Overview": {
                "Status": "Success",
                "DetailedStatus": "Success",
                "AssociationStatusAggregatedCount": {
                    "Success": 1
                }
            },
            "ScheduleExpression": "cron(0 00 12 ? * SUN *)",
            "AssociationName": "UpdateSSMAgent"
        },
    {
            "Name": "AWS-UpdateSSMAgent",
            "InstanceId": "i-9876543210abcdef0",
            "AssociationId": "fbc07ef7-b985-4684-b82b-0123456789ab",
            "AssociationVersion": "1",
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-9876543210abcdef0"
                    ]
                }
            ],
            "LastExecutionDate": 1550507531.0,
            "Overview": {
                "Status": "Success",
                "AssociationStatusAggregatedCount": {
                    "Success": 1
                }
            }
        }
    ]
}
```
詳細については、「*Systems Manager ユーザーガイド*」の「[Systems Manager の関連付けの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-associations.html)」を参照してください。

### `list-command-invocations`
<a name="ssm_ListCommandInvocations_cli_2_topic"></a>

次のコード例は、`list-command-invocations` を使用する方法を示しています。

**AWS CLI**  
**特定のコマンドの呼び出しを一覧表示するには**  
次の `list-command-invocations` の例では、コマンドのすべての呼び出しを一覧表示します。  

```
aws ssm list-command-invocations \
    --command-id "ef7fdfd8-9b57-4151-a15c-db9a12345678" \
    --details
```
出力:  

```
{
    "CommandInvocations": [
        {
            "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678",
            "InstanceId": "i-02573cafcfEXAMPLE",
            "InstanceName": "",
            "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
            "DocumentName": "AWS-UpdateSSMAgent",
            "DocumentVersion": "",
            "RequestedDateTime": 1582136283.089,
            "Status": "Success",
            "StatusDetails": "Success",
            "StandardOutputUrl": "",
            "StandardErrorUrl": "",
            "CommandPlugins": [
                {
                    "Name": "aws:updateSsmAgent",
                    "Status": "Success",
                    "StatusDetails": "Success",
                    "ResponseCode": 0,
                    "ResponseStartDateTime": 1582136283.419,
                    "ResponseFinishDateTime": 1582136283.51,
                    "Output": "Updating amazon-ssm-agent from 2.3.842.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\namazon-ssm-agent 2.3.842.0 has already been installed, update skipped\n",
                    "StandardOutputUrl": "",
                    "StandardErrorUrl": "",
                    "OutputS3Region": "us-east-2",
                    "OutputS3BucketName": "",
                    "OutputS3KeyPrefix": ""
                }
            ],
            "ServiceRole": "",
            "NotificationConfig": {
                "NotificationArn": "",
                "NotificationEvents": [],
                "NotificationType": ""
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        },
        {
            "CommandId": "ef7fdfd8-9b57-4151-a15c-db9a12345678",
            "InstanceId": "i-0471e04240EXAMPLE",
            "InstanceName": "",
            "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
            "DocumentName": "AWS-UpdateSSMAgent",
            "DocumentVersion": "",
            "RequestedDateTime": 1582136283.02,
            "Status": "Success",
            "StatusDetails": "Success",
            "StandardOutputUrl": "",
            "StandardErrorUrl": "",
            "CommandPlugins": [
                {
                    "Name": "aws:updateSsmAgent",
                    "Status": "Success",
                    "StatusDetails": "Success",
                    "ResponseCode": 0,
                    "ResponseStartDateTime": 1582136283.812,
                    "ResponseFinishDateTime": 1582136295.031,
                    "Output": "Updating amazon-ssm-agent from 2.3.672.0 to latest\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/ssm-agent-manifest.json\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent-updater/2.3.842.0/amazon-ssm-agent-updater-snap-amd64.tar.gz\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.672.0/amazon-ssm-agent-snap-amd64.tar.gz\nSuccessfully downloaded https://s3.us-east-2.amazonaws.com/amazon-ssm-us-east-2/amazon-ssm-agent/2.3.842.0/amazon-ssm-agent-snap-amd64.tar.gz\nInitiating amazon-ssm-agent update to 2.3.842.0\namazon-ssm-agent updated successfully to 2.3.842.0",
                    "StandardOutputUrl": "",
                    "StandardErrorUrl": "",
                    "OutputS3Region": "us-east-2",
                    "OutputS3BucketName": "",
                    "OutputS3KeyPrefix": "8bee3135-398c-4d31-99b6-e42d2EXAMPLE/i-0471e04240EXAMPLE/awsupdateSsmAgent"
                }
            ],
            "ServiceRole": "",
            "NotificationConfig": {
                "NotificationArn": "",
                "NotificationEvents": [],
                "NotificationType": ""
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[コマンドのステータスについて](https://docs.aws.amazon.com/systems-manager/latest/userguide/monitor-commands.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCommandInvocations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-command-invocations.html)」を参照してください。

### `list-commands`
<a name="ssm_ListCommands_cli_2_topic"></a>

次のコード例は、`list-commands` を使用する方法を示しています。

**AWS CLI**  
**例 1: 特定のコマンドのステータスを取得するには**  
次の `list-commands` の例では、指定されたコマンドのステータスを取得して表示します。  

```
aws ssm list-commands \
    --command-id "0831e1a8-a1ac-4257-a1fd-c831bEXAMPLE"
```
**例 2: 特定の日付より後にリクエストされたコマンドのステータスを取得するには**  
次の `list-commands` の例では、指定した日付より後にリクエストされたコマンドの詳細を取得します。  

```
aws ssm list-commands \
    --filter "key=InvokedAfter,value=2020-02-01T00:00:00Z"
```
**例 3: AWS アカウントでリクエストされたすべてのコマンドを一覧表示するには**  
次の の`list-commands`例では、現在の AWS アカウントとリージョンのユーザーがリクエストしたすべてのコマンドを一覧表示します。  

```
aws ssm list-commands
```
出力:  

```
{
    "Commands": [
        {
            "CommandId": "8bee3135-398c-4d31-99b6-e42d2EXAMPLE",
            "DocumentName": "AWS-UpdateSSMAgent",
            "DocumentVersion": "",
            "Comment": "b48291dd-ba76-43e0-b9df-13e11ddaac26:6960febb-2907-4b59-8e1a-d6ce8EXAMPLE",
            "ExpiresAfter": "2020-02-19T11:28:02.500000-08:00",
            "Parameters": {},
            "InstanceIds": [
                "i-028ea792daEXAMPLE",
                "i-02feef8c46EXAMPLE",
                "i-038613f3f0EXAMPLE",
                "i-03a530a2d4EXAMPLE",
                "i-083b678d37EXAMPLE",
                "i-0dee81debaEXAMPLE"
            ],
            "Targets": [],
            "RequestedDateTime": "2020-02-19T10:18:02.500000-08:00",
            "Status": "Success",
            "StatusDetails": "Success",
            "OutputS3BucketName": "",
            "OutputS3KeyPrefix": "",
            "MaxConcurrency": "50",
            "MaxErrors": "100%",
            "TargetCount": 6,
            "CompletedCount": 6,
            "ErrorCount": 0,
            "DeliveryTimedOutCount": 0,
            "ServiceRole": "",
            "NotificationConfig": {
                "NotificationArn": "",
                "NotificationEvents": [],
                "NotificationType": ""
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
        {
            "CommandId": "e9ade581-c03d-476b-9b07-26667EXAMPLE",
            "DocumentName": "AWS-FindWindowsUpdates",
            "DocumentVersion": "1",
            "Comment": "",
            "ExpiresAfter": "2020-01-24T12:37:31.874000-08:00",
            "Parameters": {
                "KbArticleIds": [
                    ""
                ],
                "UpdateLevel": [
                    "All"
                ]
            },
            "InstanceIds": [],
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-00ec29b21eEXAMPLE",
                        "i-09911ddd90EXAMPLE"
                    ]
                }
            ],
            "RequestedDateTime": "2020-01-24T11:27:31.874000-08:00",
            "Status": "Success",
            "StatusDetails": "Success",
            "OutputS3BucketName": "my-us-east-2-bucket",
            "OutputS3KeyPrefix": "my-rc-output",
            "MaxConcurrency": "50",
            "MaxErrors": "0",
            "TargetCount": 2,
            "CompletedCount": 2,
            "ErrorCount": 0,
            "DeliveryTimedOutCount": 0,
            "ServiceRole": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "NotificationConfig": {
                "NotificationArn": "arn:aws:sns:us-east-2:111222333444:my-us-east-2-notification-arn",
                "NotificationEvents": [
                    "All"
                ],
                "NotificationType": "Invocation"
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
        {
            "CommandId": "d539b6c3-70e8-4853-80e5-0ce4fEXAMPLE",
            "DocumentName": "AWS-RunPatchBaseline",
            "DocumentVersion": "1",
            "Comment": "",
            "ExpiresAfter": "2020-01-24T12:21:04.350000-08:00",
            "Parameters": {
                "InstallOverrideList": [
                    ""
                ],
                "Operation": [
                    "Install"
                ],
                "RebootOption": [
                    "RebootIfNeeded"
                ],
                "SnapshotId": [
                    ""
                ]
            },
            "InstanceIds": [],
            "Targets": [
                {
                    "Key": "InstanceIds",
                    "Values": [
                        "i-00ec29b21eEXAMPLE",
                        "i-09911ddd90EXAMPLE"
                    ]
                }
            ],
            "RequestedDateTime": "2020-01-24T11:11:04.350000-08:00",
            "Status": "Success",
            "StatusDetails": "Success",
            "OutputS3BucketName": "my-us-east-2-bucket",
            "OutputS3KeyPrefix": "my-rc-output",
            "MaxConcurrency": "50",
            "MaxErrors": "0",
            "TargetCount": 2,
            "CompletedCount": 2,
            "ErrorCount": 0,
            "DeliveryTimedOutCount": 0,
            "ServiceRole": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
            "NotificationConfig": {
                "NotificationArn": "arn:aws:sns:us-east-2:111222333444:my-us-east-2-notification-arn",
                "NotificationEvents": [
                    "All"
                ],
                "NotificationType": "Invocation"
            },
            "CloudWatchOutputConfig": {
                "CloudWatchLogGroupName": "",
                "CloudWatchOutputEnabled": false
            }
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListCommands](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-commands.html)」を参照してください。

### `list-compliance-items`
<a name="ssm_ListComplianceItems_cli_2_topic"></a>

次のコード例は、`list-compliance-items` を使用する方法を示しています。

**AWS CLI**  
**特定のインスタンスのコンプライアンス項目を一覧表示するには**  
この例では、指定したインスタンスのすべてのコンプライアンス項目を一覧表示します。  
コマンド:  

```
aws ssm list-compliance-items --resource-ids "i-1234567890abcdef0" --resource-types "ManagedInstance"
```
出力:  

```
{
  "ComplianceItems": [
      {
          "ComplianceType": "Association",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-1234567890abcdef0",
          "Id": "8dfe3659-4309-493a-8755-0123456789ab",
          "Title": "",
          "Status": "COMPLIANT",
          "Severity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550408470.0
          },
          "Details": {
              "DocumentName": "AWS-GatherSoftwareInventory",
              "DocumentVersion": "1"
          }
      },
      {
          "ComplianceType": "Association",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-1234567890abcdef0",
          "Id": "e4c2ed6d-516f-41aa-aa2a-0123456789ab",
          "Title": "",
          "Status": "COMPLIANT",
          "Severity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550508475.0
          },
          "Details": {
              "DocumentName": "AWS-UpdateSSMAgent",
              "DocumentVersion": "1"
          }
      },
              ...
  ],
  "NextToken": "--token string truncated--"
}
```
**特定のインスタンスと関連付け ID のコンプライアンス項目を一覧表示するには**  
この例では、指定したインスタンスと関連付け ID のすべてのコンプライアンス項目を一覧表示します。  
コマンド:  

```
aws ssm list-compliance-items --resource-ids "i-1234567890abcdef0" --resource-types "ManagedInstance" --filters "Key=ComplianceType,Values=Association,Type=EQUAL" "Key=Id,Values=e4c2ed6d-516f-41aa-aa2a-0123456789ab,Type=EQUAL"
```
**特定の日時より後のインスタンスのコンプライアンス項目を一覧表示するには**  
この例では、指定した日時より後のインスタンスのすべてのコンプライアンス項目を一覧表示します。  
コマンド:  

```
aws ssm list-compliance-items --resource-ids "i-1234567890abcdef0" --resource-types "ManagedInstance" --filters "Key=ExecutionTime,Values=2019-02-18T16:00:00Z,Type=GREATER_THAN"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListComplianceItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-compliance-items.html)」を参照してください。

### `list-compliance-summaries`
<a name="ssm_ListComplianceSummaries_cli_2_topic"></a>

次のコード例は、`list-compliance-summaries` を使用する方法を示しています。

**AWS CLI**  
**すべてのコンプライアンスタイプのコンプライアンス概要を一覧表示するには**  
この例では、アカウント内のすべてのコンプライアンスタイプのコンプライアンス概要を一覧表示します。  
コマンド:  

```
aws ssm list-compliance-summaries
```
出力:  

```
{
  "ComplianceSummaryItems": [
      {
          "ComplianceType": "Association",
          "CompliantSummary": {
              "CompliantCount": 2,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 2
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 0,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      },
      {
          "ComplianceType": "Patch",
          "CompliantSummary": {
              "CompliantCount": 1,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 1
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 1,
              "SeveritySummary": {
                  "CriticalCount": 1,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      },
              ...
  ],
  "NextToken": "eyJOZXh0VG9rZW4iOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ=="
}
```
**特定のコンプライアンスタイプのコンプライアンス概要を一覧表示するには**  
この例では、パッチコンプライアンスタイプのコンプライアンス概要を一覧表示します。  
コマンド:  

```
aws ssm list-compliance-summaries --filters "Key=ComplianceType,Values=Patch,Type=EQUAL"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListComplianceSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-compliance-summaries.html)」を参照してください。

### `list-document-metadata-history`
<a name="ssm_ListDocumentMetadataHistory_cli_2_topic"></a>

次のコード例は、`list-document-metadata-history` を使用する方法を示しています。

**AWS CLI**  
**例: 変更テンプレートの承認履歴とステータスを表示するには**  
次の `list-document-metadata-history` の例では、指定された Change Manager 変更テンプレートの承認履歴を返します。  

```
aws ssm list-document-metadata-history \
    --name MyChangeManageTemplate \
    --metadata DocumentReviews
```
出力:  

```
{
    "Name": "MyChangeManagerTemplate",
    "DocumentVersion": "1",
    "Author": "arn:aws:iam::111222333444;:user/JohnDoe",
    "Metadata": {
        "ReviewerResponse": [
            {
                "CreateTime": "2021-07-30T11:58:28.025000-07:00",
                "UpdatedTime": "2021-07-30T12:01:19.274000-07:00",
                "ReviewStatus": "APPROVED",
                "Comment": [
                    {
                        "Type": "COMMENT",
                        "Content": "I approve this template version"
                    }
                ],
                "Reviewer": "arn:aws:iam::111222333444;:user/ShirleyRodriguez"
            },
            {
                "CreateTime": "2021-07-30T11:58:28.025000-07:00",
                "UpdatedTime": "2021-07-30T11:58:28.025000-07:00",
                "ReviewStatus": "PENDING"
            }
        ]
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[変更テンプレートの確認と、承認または拒否](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-templates-review.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDocumentMetadataHistory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-document-metadata-history.html)」を参照してください。

### `list-document-versions`
<a name="ssm_ListDocumentVersions_cli_2_topic"></a>

次のコード例は、`list-document-versions` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントバージョンを一覧表示するには**  
次の `list-document-versions` の例では、Systems Manager ドキュメントのすべてのバージョンを一覧表示します。  

```
aws ssm list-document-versions \
    --name "Example"
```
出力:  

```
{
    "DocumentVersions": [
        {
            "Name": "Example",
            "DocumentVersion": "1",
            "CreatedDate": 1583257938.266,
            "IsDefaultVersion": true,
            "DocumentFormat": "YAML",
            "Status": "Active"
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[ドキュメントバージョンパラメータを使用するコマンドの実行](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command-version.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*.」の「[ListDocumentVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-document-versions.html)」を参照してください。

### `list-documents`
<a name="ssm_ListDocuments_cli_2_topic"></a>

次のコード例は、`list-documents` を使用する方法を示しています。

**AWS CLI**  
**例 1: ドキュメントを一覧表示するには**  
次の `list-documents` の例では、カスタムタグでタグ付けされたリクエスト元のアカウントが所有するドキュメントを一覧表示します。  

```
aws ssm list-documents \
    --filters Key=Owner,Values=Self Key=tag:DocUse,Values=Testing
```
出力:  

```
{
    "DocumentIdentifiers": [
        {
            "Name": "Example",
            "Owner": "29884EXAMPLE",
            "PlatformTypes": [
                "Windows",
                "Linux"
            ],
            "DocumentVersion": "1",
            "DocumentType": "Automation",
            "SchemaVersion": "0.3",
            "DocumentFormat": "YAML",
            "Tags": [
                {
                    "Key": "DocUse",
                    "Value": "Testing"
                }
            ]
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[AWS Systems Manager ドキュメント](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html)」を参照してください。  
**例 2: 共有ドキュメントを一覧表示するには**  
次の の`list-documents`例では、 が所有していないプライベート共有ドキュメントを含む共有ドキュメントを一覧表示します AWS。  

```
aws ssm list-documents \
    --filters Key=Name,Values=sharedDocNamePrefix  Key=Owner,Values=Private
```
出力:  

```
{
    "DocumentIdentifiers": [
        {
            "Name": "Example",
            "Owner": "12345EXAMPLE",
            "PlatformTypes": [
                "Windows",
                "Linux"
            ],
            "DocumentVersion": "1",
            "DocumentType": "Command",
            "SchemaVersion": "0.3",
            "DocumentFormat": "YAML",
            "Tags": []
        }
    ]
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[AWS Systems Manager ドキュメント](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-ssm-docs.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListDocuments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-documents.html)」を参照してください。

### `list-inventory-entries`
<a name="ssm_ListInventoryEntries_cli_2_topic"></a>

次のコード例は、`list-inventory-entries` を使用する方法を示しています。

**AWS CLI**  
**例 1: インスタンスの特定のインベントリタイプのエントリを表示するには**  
次の の`list-inventory-entries`例では、特定のインスタンスの AWS:Application インベントリタイプのインベントリエントリを一覧表示します。  

```
aws ssm list-inventory-entries \
    --instance-id "i-1234567890abcdef0" \
    --type-name "AWS:Application"
```
出力:  

```
{
  "TypeName": "AWS:Application",
  "InstanceId": "i-1234567890abcdef0",
  "SchemaVersion": "1.1",
  "CaptureTime": "2019-02-15T12:17:55Z",
  "Entries": [
    {
      "Architecture": "i386",
      "Name": "Amazon SSM Agent",
      "PackageId": "{88a60be2-89a1-4df8-812a-80863c2a2b68}",
      "Publisher": "Amazon Web Services",
      "Version": "2.3.274.0"
    },
    {
      "Architecture": "x86_64",
      "InstalledTime": "2018-05-03T13:42:34Z",
      "Name": "AmazonCloudWatchAgent",
      "Publisher": "",
      "Version": "1.200442.0"
    }
  ]
}
```
**例 2: インスタンスに割り当てられたカスタムインベントリエントリを表示するには**  
次の `list-inventory-entries` の例では、インスタンスに割り当てられたカスタムインベントリエントリを一覧表示します。  

```
aws ssm list-inventory-entries \
    --instance-id "i-1234567890abcdef0" \
    --type-name "Custom:RackInfo"
```
出力:  

```
{
  "TypeName": "Custom:RackInfo",
  "InstanceId": "i-1234567890abcdef0",
  "SchemaVersion": "1.0",
  "CaptureTime": "2021-05-22T10:01:01Z",
  "Entries": [
    {
      "RackLocation": "Bay B/Row C/Rack D/Shelf E"
    }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListInventoryEntries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-inventory-entries.html)」を参照してください。

### `list-ops-item-related-items`
<a name="ssm_ListOpsItemRelatedItems_cli_2_topic"></a>

次のコード例は、`list-ops-item-related-items` を使用する方法を示しています。

**AWS CLI**  
**OpsItem の関連項目リソースを一覧表示するには**  
次の `list-ops-item-related-items` の例では、OpsItem の関連項目リソースを一覧表示します。  

```
aws ssm list-ops-item-related-items \
    --ops-item-id "oi-f99f2EXAMPLE"
```
出力:  

```
{
    "Summaries": [
        {
            "OpsItemId": "oi-f99f2EXAMPLE",
            "AssociationId": "e2036148-cccb-490e-ac2a-390e5EXAMPLE",
            "ResourceType": "AWS::SSMIncidents::IncidentRecord",
            "AssociationType": "IsParentOf",
            "ResourceUri": "arn:aws:ssm-incidents::111122223333:incident-record/example-response/64bd9b45-1d0e-2622-840d-03a87a1451fa",
            "CreatedBy": {
                "Arn": "arn:aws:sts::111122223333:assumed-role/AWSServiceRoleForIncidentManager/IncidentResponse"
            },
            "CreatedTime": "2021-08-11T18:47:14.994000+00:00",
            "LastModifiedBy": {
                "Arn": "arn:aws:sts::111122223333:assumed-role/AWSServiceRoleForIncidentManager/IncidentResponse"
            },
            "LastModifiedTime": "2021-08-11T18:47:14.994000+00:00"
        }
    ]
}
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[OpsCenter で Incident Manager インシデントを操作する](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-create-OpsItems-for-Incident-Manager.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOpsItemRelatedItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-ops-item-related-items.html)」を参照してください。

### `list-resource-compliance-summaries`
<a name="ssm_ListResourceComplianceSummaries_cli_2_topic"></a>

次のコード例は、`list-resource-compliance-summaries` を使用する方法を示しています。

**AWS CLI**  
**リソースレベルのコンプライアンス概要数を一覧表示するには**  
この例では、リソースレベルのコンプライアンス概要数を一覧表示します。  
コマンド:  

```
aws ssm list-resource-compliance-summaries
```
出力:  

```
{
  "ResourceComplianceSummaryItems": [
      {
          "ComplianceType": "Association",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-1234567890abcdef0",
          "Status": "COMPLIANT",
          "OverallSeverity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550509273.0
          },
          "CompliantSummary": {
              "CompliantCount": 2,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 2
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 0,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      },
      {
          "ComplianceType": "Patch",
          "ResourceType": "ManagedInstance",
          "ResourceId": "i-9876543210abcdef0",
          "Status": "COMPLIANT",
          "OverallSeverity": "UNSPECIFIED",
          "ExecutionSummary": {
              "ExecutionTime": 1550248550.0,
              "ExecutionId": "7abb6378-a4a5-4f10-8312-0123456789ab",
              "ExecutionType": "Command"
          },
          "CompliantSummary": {
              "CompliantCount": 397,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 397
              }
          },
          "NonCompliantSummary": {
              "NonCompliantCount": 0,
              "SeveritySummary": {
                  "CriticalCount": 0,
                  "HighCount": 0,
                  "MediumCount": 0,
                  "LowCount": 0,
                  "InformationalCount": 0,
                  "UnspecifiedCount": 0
              }
          }
      }
  ],
  "NextToken": "--token string truncated--"
}
```
**特定のコンプライアンスタイプのリソースレベルのコンプライアンス概要を一覧表示するには**  
この例では、パッチコンプライアンスタイプのリソースレベルのコンプライアンス概要を一覧表示します。  
コマンド:  

```
aws ssm list-resource-compliance-summaries --filters "Key=ComplianceType,Values=Patch,Type=EQUAL"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceComplianceSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-resource-compliance-summaries.html)」を参照してください。

### `list-resource-data-sync`
<a name="ssm_ListResourceDataSync_cli_2_topic"></a>

次のコード例は、`list-resource-data-sync` を使用する方法を示しています。

**AWS CLI**  
**リソースデータ同期設定を一覧表示するには**  
この例では、リソースデータ同期設定に関する情報を取得します。  

```
aws ssm list-resource-data-sync
```
出力:  

```
{
    "ResourceDataSyncItems": [
        {
            "SyncName": "MyResourceDataSync",
            "S3Destination": {
                "BucketName": "ssm-resource-data-sync",
                "SyncFormat": "JsonSerDe",
                "Region": "us-east-1"
            },
            "LastSyncTime": 1550261472.003,
            "LastSuccessfulSyncTime": 1550261472.003,
            "LastStatus": "Successful",
            "SyncCreatedTime": 1543235736.72,
            "LastSyncStatusMessage": "The sync was successfully completed"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceDataSync](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-resource-data-sync.html)」を参照してください。

### `list-tags-for-resource`
<a name="ssm_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**パッチベースラインに適用されたタグを一覧表示するには**  
次の `list-tags-for-resource` の例では、パッチベースラインのタグを一覧表示します。  

```
aws ssm list-tags-for-resource \
    --resource-type "PatchBaseline" \
    --resource-id "pb-0123456789abcdef0"
```
出力:  

```
{
    "TagList": [
        {
            "Key": "Environment",
            "Value": "Production"
        },
        {
            "Key": "Region",
            "Value": "EMEA"
        }
    ]
}
```
詳細については、[「 全般のリファレンス」の AWS 「リソースのタグ付け](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-tags-for-resource.html)」を参照してください。

### `modify-document-permission`
<a name="ssm_ModifyDocumentPermission_cli_2_topic"></a>

次のコード例は、`modify-document-permission` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントのアクセス許可を変更するには**  
次の `modify-document-permission` の例では、Systems Manager ドキュメントをパブリックで共有します。  

```
aws ssm modify-document-permission \
    --name "Example" \
    --permission-type "Share" \
    --account-ids-to-add "All"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[SSM ドキュメントの共有](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-how-to-share.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyDocumentPermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/modify-document-permission.html)」を参照してください。

### `put-compliance-items`
<a name="ssm_PutComplianceItems_cli_2_topic"></a>

次のコード例は、`put-compliance-items` を使用する方法を示しています。

**AWS CLI**  
**コンプライアンスタイプおよびコンプライアンスの詳細を指定されたインスタンスに登録するには**  
この例では、指定されたマネージドインスタンスにコンプライアンスタイプ `Custom:AVCheck` を登録します。コマンドが成功した場合、出力はありません。  
コマンド:  

```
aws ssm put-compliance-items --resource-id "i-1234567890abcdef0" --resource-type "ManagedInstance" --compliance-type "Custom:AVCheck" --execution-summary "ExecutionTime=2019-02-18T16:00:00Z" --items "Id=Version2.0,Title=ScanHost,Severity=CRITICAL,Status=COMPLIANT"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutComplianceItems](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/put-compliance-items.html)」を参照してください。

### `put-inventory`
<a name="ssm_PutInventory_cli_2_topic"></a>

次のコード例は、`put-inventory` を使用する方法を示しています。

**AWS CLI**  
**顧客のメタデータをインスタンスに割り当てるには**  
この例では、ラックの場所情報をインスタンスに割り当てます。コマンドが成功した場合、出力はありません。  
コマンド (Linux):  

```
aws ssm put-inventory --instance-id "i-016648b75dd622dab" --items '[{"TypeName": "Custom:RackInfo","SchemaVersion": "1.0","CaptureTime": "2019-01-22T10:01:01Z","Content":[{"RackLocation": "Bay B/Row C/Rack D/Shelf E"}]}]'
```
コマンド (Windows):  

```
aws ssm put-inventory --instance-id "i-016648b75dd622dab" --items "TypeName=Custom:RackInfo,SchemaVersion=1.0,CaptureTime=2019-01-22T10:01:01Z,Content=[{RackLocation='Bay B/Row C/Rack D/Shelf F'}]"
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutInventory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/put-inventory.html)」を参照してください。

### `put-parameter`
<a name="ssm_PutParameter_cli_2_topic"></a>

次のコード例は、`put-parameter` を使用する方法を示しています。

**AWS CLI**  
**例 1: パラメータ値を変更するには**  
次の `put-parameter` の例は、指定されたパラメータの値を変更します。  

```
aws ssm put-parameter \
    --name "MyStringParameter" \
    --type "String" \
    --value "Vici" \
    --overwrite
```
出力:  

```
{
    "Version": 2,
    "Tier": "Standard"
}
```
詳細については、[「Systems Manager ユーザーガイド」の「Systems Manager パラメータの作成 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html)」、「パラメータ階層の管理」、[「パラメータポリシーの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html)」を参照してください。 [https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) *AWS *  
**例 2: アドバンストパラメータを作成するには**  
次の `put-parameter` の例は、アドバンストパラメータを作成します。  

```
aws ssm put-parameter \
    --name "MyAdvancedParameter" \
    --description "This is an advanced parameter" \
    --value "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat [truncated]" \
    --type "String" \
    --tier Advanced
```
出力:  

```
{
    "Version": 1,
    "Tier": "Advanced"
}
```
詳細については、[「Systems Manager ユーザーガイド」の「Systems Manager パラメータの作成 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html)」、「パラメータ階層の管理」、[「パラメータポリシーの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html)」を参照してください。 [https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) *AWS *  
**例 3: スタンダードパラメータをアドバンストパラメータに変換するには**  
次の `put-parameter` の例は、既存のスタンダードパラメータをアドバンストパラメータに変換します。  

```
aws ssm put-parameter \
    --name "MyConvertedParameter" \
    --value "abc123" \
    --type "String" \
    --tier Advanced \
    --overwrite
```
出力:  

```
{
    "Version": 2,
    "Tier": "Advanced"
}
```
詳細については、[「Systems Manager ユーザーガイド」の「Systems Manager パラメータの作成 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html)」、「パラメータ階層の管理」、[「パラメータポリシーの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html)」を参照してください。 [https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) *AWS *  
**例 4: ポリシーがアタッチされたパラメータを作成するには**  
次の `put-parameter` の例は、パラメータポリシーがアタッチされたアドバンストパラメータを作成します。  

```
aws ssm put-parameter \
    --name "/Finance/Payroll/q2accesskey" \
    --value "P@sSwW)rd" \
    --type "SecureString" \
    --tier Advanced \
    --policies "[{\"Type\":\"Expiration\",\"Version\":\"1.0\",\"Attributes\":{\"Timestamp\":\"2020-06-30T00:00:00.000Z\"}},{\"Type\":\"ExpirationNotification\",\"Version\":\"1.0\",\"Attributes\":{\"Before\":\"5\",\"Unit\":\"Days\"}},{\"Type\":\"NoChangeNotification\",\"Version\":\"1.0\",\"Attributes\":{\"After\":\"60\",\"Unit\":\"Days\"}}]"
```
出力:  

```
{
    "Version": 1,
    "Tier": "Advanced"
}
```
詳細については、[「Systems Manager ユーザーガイド」の「Systems Manager パラメータの作成 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html)」、「パラメータ階層の管理」、[「パラメータポリシーの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html)」を参照してください。 [https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) *AWS *  
**例 5: 既存のパラメータにポリシーを追加するには**  
次の `put-parameter` の例は、ポリシーを既存のアドバンストパラメータにアタッチします。  

```
aws ssm put-parameter \
    --name "/Finance/Payroll/q2accesskey" \
    --value "N3wP@sSwW)rd" \
    --type "SecureString" \
    --tier Advanced \
    --policies "[{\"Type\":\"Expiration\",\"Version\":\"1.0\",\"Attributes\":{\"Timestamp\":\"2020-06-30T00:00:00.000Z\"}},{\"Type\":\"ExpirationNotification\",\"Version\":\"1.0\",\"Attributes\":{\"Before\":\"5\",\"Unit\":\"Days\"}},{\"Type\":\"NoChangeNotification\",\"Version\":\"1.0\",\"Attributes\":{\"After\":\"60\",\"Unit\":\"Days\"}}]"
    --overwrite
```
出力:  

```
{
    "Version": 2,
    "Tier": "Advanced"
}
```
詳細については、[「Systems Manager ユーザーガイド」の「Systems Manager パラメータの作成 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html)」、「パラメータ階層の管理」、[「パラメータポリシーの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-policies.html)」を参照してください。 [https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-advanced-parameters.html) *AWS *  
+  API の詳細については、AWS CLI コマンドリファレンスの「[PutParameter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/put-parameter.html)」を参照してください。**

### `register-default-patch-baseline`
<a name="ssm_RegisterDefaultPatchBaseline_cli_2_topic"></a>

次のコード例は、`register-default-patch-baseline` を使用する方法を示しています。

**AWS CLI**  
**デフォルトパッチベースラインを設定するには**  
次の `register-default-patch-baseline` の例では、指定したカスタムパッチベースラインを、サポートするオペレーティングシステムタイプのデフォルトのパッチベースラインとして登録します。  

```
aws ssm register-default-patch-baseline \
    --baseline-id "pb-abc123cf9bEXAMPLE"
```
出力:  

```
{
    "BaselineId":"pb-abc123cf9bEXAMPLE"
}
```
次の の`register-default-patch-baseline`例では、 AWS for CentOS が提供するデフォルトのパッチベースラインをデフォルトのパッチベースラインとして登録します。  

```
aws ssm register-default-patch-baseline \
    --baseline-id "arn:aws:ssm:us-east-2:733109147000:patchbaseline/pb-0574b43a65ea646ed"
```
出力:  

```
{
    "BaselineId":"pb-abc123cf9bEXAMPLE"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[事前定義されたパッチベースラインおよびカスタムパッチベースライン](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-baselines.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterDefaultPatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-default-patch-baseline.html)」を参照してください。

### `register-patch-baseline-for-patch-group`
<a name="ssm_RegisterPatchBaselineForPatchGroup_cli_2_topic"></a>

次のコード例は、`register-patch-baseline-for-patch-group` を使用する方法を示しています。

**AWS CLI**  
**パッチグループのパッチベースラインを登録するには**  
次の `register-patch-baseline-for-patch-group` の例では、パッチグループのパッチベースラインを登録します。  

```
aws ssm register-patch-baseline-for-patch-group \
    --baseline-id "pb-045f10b4f382baeda" \
    --patch-group "Production"
```
出力:  

```
{
    "BaselineId": "pb-045f10b4f382baeda",
    "PatchGroup": "Production"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「パッチグループの作成 <https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-tagging.html>\$1\$1」および「[パッチベースラインにパッチグループを追加する](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-patch-group-patchbaseline.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterPatchBaselineForPatchGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-patch-baseline-for-patch-group.html)」を参照してください。

### `register-target-with-maintenance-window`
<a name="ssm_RegisterTargetWithMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`register-target-with-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウに単一のターゲットを登録するには**  
次の `register-target-with-maintenance-window` の例では、インスタンスをメンテナンスウィンドウに登録します。  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --target "Key=InstanceIds,Values=i-0000293ffd8c57862" \
    --owner-information "Single instance" \
    --resource-type "INSTANCE"
```
出力:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**例 2: インスタンス ID を使用して、メンテナンスウィンドウに複数のターゲットを登録するには**  
次の `register-target-with-maintenance-window` の例では、インスタンス ID を指定して、2 つのインスタンスをメンテナンスウィンドウに登録します。  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-ab12cd34ef56gh78" \
    --target "Key=InstanceIds,Values=i-0000293ffd8c57862,i-0cb2b964d3e14fd9f" \
    --owner-information "Two instances in a list" \
    --resource-type "INSTANCE"
```
出力:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**例 3: リソースタグを使用してメンテナンスウィンドウにターゲットを登録するには**  
次の `register-target-with-maintenance-window` の例では、インスタンスに適用されたリソースタグを指定して、インスタンスをメンテナンスウィンドウに登録します。  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-06cf17cbefcb4bf4f" \
    --targets "Key=tag:Environment,Values=Prod" "Key=Role,Values=Web" \
    --owner-information "Production Web Servers" \
    --resource-type "INSTANCE"
```
出力:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**例 4: タグキーのグループを使用してターゲットを登録するには**  
次の `register-target-with-maintenance-window` の例では、キー値に関係なく、1 つまたは複数のタグキーが割り当てられているインスタンスをすべて登録します。  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "INSTANCE" \
    --target "Key=tag-key,Values=Name,Instance-Type,CostCenter"
```
出力:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
**例 5: リソースグループ名を使用してターゲットを登録するには**  
次の `register-target-with-maintenance-window` の例では、含まれるリソースタイプに関係なく、指定されたリソースグループを登録します。  

```
aws ssm register-target-with-maintenance-window \
    --window-id "mw-0c50858d01EXAMPLE" \
    --resource-type "RESOURCE_GROUP" \
    --target "Key=resource-groups:Name,Values=MyResourceGroup"
```
出力:  

```
{
    "WindowTargetId":"1a2b3c4d-1a2b-1a2b-1a2b-1a2b3c4d-1a2"
}
```
詳細については、*AWS Systems* [Manager ユーザーガイドの「メンテナンスウィンドウ (AWS CLI) でターゲットインスタンスを登録する](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-targets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTargetWithMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-target-with-maintenance-window.html)」を参照してください。

### `register-task-with-maintenance-window`
<a name="ssm_RegisterTaskWithMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`register-task-with-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウにオートメーションタスクを登録するには**  
次の `register-task-with-maintenance-window` の例では、インスタンスをターゲットとするメンテナンスウィンドウにオートメーションタスクを登録します。  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-082dcd7649EXAMPLE" \
    --targets Key=InstanceIds,Values=i-1234520122EXAMPLE \
    --task-arn AWS-RestartEC2Instance \
    --service-role-arn arn:aws:iam::111222333444:role/SSM --task-type AUTOMATION \
    --task-invocation-parameters "{\"Automation\":{\"DocumentVersion\":\"\$LATEST\",\"Parameters\":{\"InstanceId\":[\"{{RESOURCE_ID}}\"]}}}" \
    --priority 0 \
    --max-concurrency 1 \
    --max-errors 1 \
    --name "AutomationExample" \
    --description "Restarting EC2 Instance for maintenance"
```
出力:  

```
{
    "WindowTaskId":"11144444-5555-6666-7777-88888888"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「メンテナンスウィンドウ (AWS CLI) でタスクを登録する](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)」を参照してください。  
**例 2: メンテナンスウィンドウに Lambda タスクを登録するには**  
次の `register-task-with-maintenance-window` の例では、インスタンスをターゲットとするメンテナンスウィンドウに Lambda タスクを登録します。  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-082dcd7649dee04e4" \
    --targets Key=InstanceIds,Values=i-12344d305eEXAMPLE \
    --task-arn arn:aws:lambda:us-east-1:111222333444:function:SSMTestLAMBDA \
    --service-role-arn arn:aws:iam::111222333444:role/SSM \
    --task-type LAMBDA \
    --task-invocation-parameters '{"Lambda":{"Payload":"{\"InstanceId\":\"{{RESOURCE_ID}}\",\"targetType\":\"{{TARGET_TYPE}}\"}","Qualifier":"$LATEST"}}' \
    --priority 0 \
    --max-concurrency 10 \
    --max-errors 5 \
    --name "Lambda_Example" \
    --description "My Lambda Example"
```
出力:  

```
{
    "WindowTaskId":"22244444-5555-6666-7777-88888888"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウ (AWS CLI) でタスクを登録する](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)」を参照してください。  
**例 3: メンテナンスウィンドウに Run Command タスクを登録するには**  
次の `register-task-with-maintenance-window` の例では、インスタンスをターゲットとするメンテナンスウィンドウに Run Command タスクを登録します。  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-082dcd7649dee04e4" \
    --targets "Key=InstanceIds,Values=i-12344d305eEXAMPLE" \
    --service-role-arn "arn:aws:iam::111222333444:role/SSM" \
    --task-type "RUN_COMMAND" \
    --name "SSMInstallPowerShellModule" \
    --task-arn "AWS-InstallPowerShellModule" \
    --task-invocation-parameters "{\"RunCommand\":{\"Comment\":\"\",\"OutputS3BucketName\":\"runcommandlogs\",\"Parameters\":{\"commands\":[\"Get-Module -ListAvailable\"],\"executionTimeout\":[\"3600\"],\"source\":[\"https:\/\/gallery.technet.microsoft.com\/EZOut-33ae0fb7\/file\/110351\/1\/EZOut.zip\"],\"workingDirectory\":[\"\\\\\"]},\"TimeoutSeconds\":600}}" \
    --max-concurrency 1 \
    --max-errors 1 \
    --priority 10
```
出力:  

```
{
    "WindowTaskId":"33344444-5555-6666-7777-88888888"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウ (AWS CLI) でタスクを登録する](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)」を参照してください。  
**例 4: Step Functions タスクをメンテナンスウィンドウに登録するには**  
次の `register-task-with-maintenance-window` の例では、インスタンスをターゲットとするメンテナンスウィンドウに Step Functions タスクを登録します。  

```
aws ssm register-task-with-maintenance-window \
    --window-id "mw-1234d787d6EXAMPLE" \
    --targets Key=WindowTargetIds,Values=12347414-69c3-49f8-95b8-ed2dcEXAMPLE \
    --task-arn arn:aws:states:us-east-1:111222333444:stateMachine:SSMTestStateMachine \
    --service-role-arn arn:aws:iam::111222333444:role/MaintenanceWindows \
    --task-type STEP_FUNCTIONS \
    --task-invocation-parameters '{"StepFunctions":{"Input":"{\"InstanceId\":\"{{RESOURCE_ID}}\"}"}}' \
    --priority 0 \
    --max-concurrency 10 \
    --max-errors 5 \
    --name "Step_Functions_Example" \
    --description "My Step Functions Example"
```
出力:  

```
{
    "WindowTaskId":"44444444-5555-6666-7777-88888888"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウ (AWS CLI) でタスクを登録する](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)」を参照してください。  
**例 5: メンテナンスウィンドウのターゲット ID を使用してタスクを登録するには**  
次の `register-task-with-maintenance-window` の例では、メンテナンスウィンドウのターゲット ID を使用してタスクを登録します。メンテナンスウィンドウのターゲット ID は、`aws ssm register-target-with-maintenance-window` コマンドの出力に含まれていました。この情報は `aws ssm describe-maintenance-window-targets` コマンドの出力から取得することもできます。  

```
aws ssm register-task-with-maintenance-window \
    --targets "Key=WindowTargetIds,Values=350d44e6-28cc-44e2-951f-4b2c9EXAMPLE" \
    --task-arn "AWS-RunShellScript" \
    --service-role-arn "arn:aws:iam::111222333444:role/MaintenanceWindowsRole" \
    --window-id "mw-ab12cd34eEXAMPLE" \
    --task-type "RUN_COMMAND" \
    --task-parameters  "{\"commands\":{\"Values\":[\"df\"]}}" \
    --max-concurrency 1 \
    --max-errors 1 \
    --priority 10
```
出力:  

```
{
    "WindowTaskId":"33344444-5555-6666-7777-88888888"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウ (AWS CLI) でタスクを登録する](https://docs.aws.amazon.com/systems-manager/latest/userguide/mw-cli-tutorial-tasks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTaskWithMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/register-task-with-maintenance-window.html)」を参照してください。

### `remove-tags-from-resource`
<a name="ssm_RemoveTagsFromResource_cli_2_topic"></a>

次のコード例は、`remove-tags-from-resource` を使用する方法を示しています。

**AWS CLI**  
**パッチベースラインからタグを削除するには**  
次の `remove-tags-from-resource` の例では、パッチベースラインからタグが削除されます。  

```
aws ssm remove-tags-from-resource \
    --resource-type "PatchBaseline" \
    --resource-id "pb-0123456789abcdef0" \
    --tag-keys "Region"
```
このコマンドでは何も出力されません。  
詳細については、「 *AWS 全般のリファレンス*[」の AWS 「リソースのタグ付け](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveTagsFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/remove-tags-from-resource.html)」を参照してください。

### `reset-service-setting`
<a name="ssm_ResetServiceSetting_cli_2_topic"></a>

次のコード例は、`reset-service-setting` を使用する方法を示しています。

**AWS CLI**  
**Parameter Store スループットのサービス設定をリセットするには**  
次の `reset-service-setting` 例では、指定されたリージョンの Parameter Store スループットのサービス設定をリセットして、スループットの引き上げを使用しないようにします。  

```
aws ssm reset-service-setting \
    --setting-id arn:aws:ssm:us-east-1:123456789012:servicesetting/ssm/parameter-store/high-throughput-enabled
```
出力:  

```
{
    "ServiceSetting": {
        "SettingId": "/ssm/parameter-store/high-throughput-enabled",
        "SettingValue": "false",
        "LastModifiedDate": 1555532818.578,
        "LastModifiedUser": "System",
        "ARN": "arn:aws:ssm:us-east-1:123456789012:servicesetting/ssm/parameter-store/high-throughput-enabled",
        "Status": "Default"
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store スループットの引き上げ](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-throughput.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetServiceSetting](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/reset-service-setting.html)」を参照してください。

### `resume-session`
<a name="ssm_ResumeSession_cli_2_topic"></a>

次のコード例は、`resume-session` を使用する方法を示しています。

**AWS CLI**  
**Session Manager セッションを再開するには**  
この `resume-session` の例では、インスタンスが切断された後に、インスタンスとの Session Manager セッションを再開します。このインタラクティブなコマンドでは、呼び出しを実行するクライアントマシンに Session Manager プラグインがインストールされている必要があることに留意してください。  

```
aws ssm resume-session \
    --session-id Mary-Major-07a16060613c408b5
```
出力:  

```
{
    "SessionId": "Mary-Major-07a16060613c408b5",
    "TokenValue": "AAEAAVbTGsaOnyvcUoNGqifbv5r/8lgxuQljCuY8qVcvOnoBAAAAAFxtd3jIXAFUUXGTJ7zF/AWJPwDviOlF5p3dlAgrqVIVO6IEXhkHLz0/1gXKRKEME71E6TLOplLDJAMZ+kREejkZu4c5AxMkrQjMF+gtHP1bYJKTwtHQd1wjulPLexO8SHl7g5R/wekrj6WsDUpnEegFBfGftpAIz2GXQVfTJXKfkc5qepQ11C11DOIT2dozOqXgHwfQHfAKLErM5dWDZqKwyT1Z3iw7unQdm3p5qsbrugiOZ7CRANTE+ihfGa6MEJJ97Jmat/a2TspEnOjNn9Mvu5iwXIW2yCvWZrGUj+/QI5Xr7s1XJBEnSKR54o4fN0GV9RWl0RZsZm1m1ki0JJtiwwgZ",
    "StreamUrl": "wss://ssmmessages.us-east-2.amazonaws.com/v1/data-channel/Mary-Major-07a16060613c408b5?role=publish_subscribe"
}
```
詳細については、「Systems [Manager ユーザーガイド」の「 CLI AWS 用の Session Manager プラグインのインストール](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResumeSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/resume-session.html)」を参照してください。

### `send-automation-signal`
<a name="ssm_SendAutomationSignal_cli_2_topic"></a>

次のコード例は、`send-automation-signal` を使用する方法を示しています。

**AWS CLI**  
**オートメーション実行にシグナルを送信するには**  
次の `send-automation-signal` の例では、オートメーション実行に Approve シグナルを送信します。  

```
aws ssm send-automation-signal \
    --automation-execution-id 73c8eef8-f4ee-4a05-820c-e354fEXAMPLE \
    --signal-type "Approve"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[承認が必要なオートメーションを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing-approval.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendAutomationSignal](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/send-automation-signal.html)」を参照してください。

### `send-command`
<a name="ssm_SendCommand_cli_2_topic"></a>

次のコード例は、`send-command` を使用する方法を示しています。

**AWS CLI**  
**例 1: 1 つ以上のリモートインスタンスでコマンドを実行するには**  
次の `send-command` の例では、ターゲットインスタンスで `echo` コマンドを実行します。  

```
aws ssm send-command \
    --document-name "AWS-RunShellScript" \
    --parameters 'commands=["echo HelloWorld"]' \
    --targets "Key=instanceids,Values=i-1234567890abcdef0" \
    --comment "echo HelloWorld"
```
出力:  

```
{
    "Command": {
        "CommandId": "92853adf-ba41-4cd6-9a88-142d1EXAMPLE",
        "DocumentName": "AWS-RunShellScript",
        "DocumentVersion": "",
        "Comment": "echo HelloWorld",
        "ExpiresAfter": 1550181014.717,
        "Parameters": {
            "commands": [
                "echo HelloWorld"
            ]
        },
        "InstanceIds": [
            "i-0f00f008a2dcbefe2"
        ],
        "Targets": [],
        "RequestedDateTime": 1550173814.717,
        "Status": "Pending",
        "StatusDetails": "Pending",
        "OutputS3BucketName": "",
        "OutputS3KeyPrefix": "",
        "MaxConcurrency": "50",
        "MaxErrors": "0",
        "TargetCount": 1,
        "CompletedCount": 0,
        "ErrorCount": 0,
        "DeliveryTimedOutCount": 0,
        "ServiceRole": "",
        "NotificationConfig": {
            "NotificationArn": "",
            "NotificationEvents": [],
            "NotificationType": ""
        },
        "CloudWatchOutputConfig": {
            "CloudWatchLogGroupName": "",
            "CloudWatchOutputEnabled": false
        }
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 2: インスタンスの IP 情報を取得するには**  
次の `send-command` の例では、インスタンスに関する IP 情報を取得します。  

```
aws ssm send-command \
    --instance-ids "i-1234567890abcdef0" \
    --document-name "AWS-RunShellScript" \
    --comment "IP config" \
    --parameters "commands=ifconfig"
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 3: 特定のタグを持つインスタンスでコマンドを実行するには**  
次の `send-command` の例では、タグキー「ENV」と値「Dev」を持つインスタンスでコマンドを実行します。  

```
aws ssm send-command \
    --targets "Key=tag:ENV,Values=Dev" \
    --document-name "AWS-RunShellScript" \
    --parameters "commands=ifconfig"
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 4: SNS 通知を送信するコマンドを実行するには**  
次の `send-command` の例では、すべての通知イベントと `Command` 通知タイプの SNS 通知を送信するコマンドを実行します。  

```
aws ssm send-command \
    --instance-ids "i-1234567890abcdef0" \
    --document-name "AWS-RunShellScript" \
    --comment "IP config" \
    --parameters "commands=ifconfig" \
    --service-role-arn "arn:aws:iam::123456789012:role/SNS_Role" \
    --notification-config "NotificationArn=arn:aws:sns:us-east-1:123456789012:SNSTopicName,NotificationEvents=All,NotificationType=Command"
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 5: S3 と CloudWatch に出力するコマンドを実行するには**  
次の `send-command` の例では、コマンドの詳細を S3 バケットと CloudWatch Logs ロググループに出力するコマンドを実行します。  

```
aws ssm send-command \
    --instance-ids "i-1234567890abcdef0" \
    --document-name "AWS-RunShellScript" \
    --comment "IP config" \
    --parameters "commands=ifconfig" \
    --output-s3-bucket-name "s3-bucket-name" \
    --output-s3-key-prefix "runcommand" \
    --cloud-watch-output-config "CloudWatchOutputEnabled=true,CloudWatchLogGroupName=CWLGroupName"
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 6: タグが異なる複数のインスタンスでコマンドを実行するには**  
次の `send-command` の例では、2 つの異なるタグキーと値を持つインスタンスでコマンドを実行します。  

```
aws ssm send-command \
    --document-name "AWS-RunPowerShellScript" \
    --parameters commands=["echo helloWorld"] \
    --targets Key=tag:Env,Values=Dev Key=tag:Role,Values=WebServers
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 7: 同じタグキーを持つ複数のインスタンスをターゲットにするには**  
次の `send-command` の例では、タグキーは同じだが異なる値を持つインスタンスにコマンドを実行します。  

```
aws ssm send-command \
    --document-name "AWS-RunPowerShellScript" \
    --parameters commands=["echo helloWorld"] \
    --targets Key=tag:Env,Values=Dev,Test
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager Run Command を使用してコマンドを実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/run-command.html)」を参照してください。  
**例 8: 共有ドキュメントを使用するコマンドを実行するには**  
次の `send-command` の例では、ターゲットインスタンスで共有ドキュメントを実行します。  

```
aws ssm send-command \
    --document-name "arn:aws:ssm:us-east-1:123456789012:document/ExampleDocument" \
    --targets "Key=instanceids,Values=i-1234567890abcdef0"
```
出力例については、例 1 を参照してください。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[共有 SSM ドキュメントの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-using-shared.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[SendCommand](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/send-command.html)」を参照してください。

### `start-associations-once`
<a name="ssm_StartAssociationsOnce_cli_2_topic"></a>

次のコード例は、`start-associations-once` を使用する方法を示しています。

**AWS CLI**  
**関連付けをただちに 1 回のみ実行するには**  
次の `start-associations-once` の例では、指定された関連付けを 1 回のみただちに実行します。コマンドが成功した場合、出力はありません。  

```
aws ssm start-associations-once \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの履歴の表示](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-history.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartAssociationsOnce](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/start-associations-once.html)」を参照してください。

### `start-automation-execution`
<a name="ssm_StartAutomationExecution_cli_2_topic"></a>

次のコード例は、`start-automation-execution` を使用する方法を示しています。

**AWS CLI**  
**例 1: オートメーションドキュメントを実行するには**  
次の `start-automation-execution` の例では、オートメーションドキュメントを実行します。  

```
aws ssm start-automation-execution \
    --document-name "AWS-UpdateLinuxAmi" \
    --parameters "AutomationAssumeRole=arn:aws:iam::123456789012:role/SSMAutomationRole,SourceAmiId=ami-EXAMPLE,IamInstanceProfileName=EC2InstanceRole"
```
出力:  

```
{
  "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0a1b2EXAMPLE"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[オートメーションを手動で実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing-manually.html)」を参照してください。  
**例 2: 共有オートメーションドキュメントを実行するには**  
次の `start-automation-execution` の例では、共有オートメーションドキュメントを実行します。  

```
aws ssm start-automation-execution \
    --document-name "arn:aws:ssm:us-east-1:123456789012:document/ExampleDocument"
```
出力:  

```
{
  "AutomationExecutionId": "4105a4fc-f944-11e6-9d32-0a1b2EXAMPLE"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[共有 SSM ドキュメントの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-using-shared.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartAutomationExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/start-automation-execution.html)」を参照してください。

### `start-change-request-execution`
<a name="ssm_StartChangeRequestExecution_cli_2_topic"></a>

次のコード例は、`start-change-request-execution` を使用する方法を示しています。

**AWS CLI**  
**例 1: 変更リクエストを開始するには**  
次の `start-change-request-execution` の例では、最小限のオプションを指定して変更リクエストを開始します。  

```
aws ssm start-change-request-execution \
    --change-request-name MyChangeRequest \
    --document-name AWS-HelloWorldChangeTemplate \
    --runbooks '[{"DocumentName": "AWS-HelloWorld","Parameters": {"AutomationAssumeRole": ["arn:aws:iam:us-east-2:1112223233444:role/MyChangeManagerAssumeRole"]}}]' \
    --parameters Approver="JohnDoe",ApproverType="IamUser",ApproverSnsTopicArn="arn:aws:sns:us-east-2:1112223233444:MyNotificationTopic"
```
出力:  

```
{
  "AutomationExecutionId": "9d32a4fc-f944-11e6-4105-0a1b2EXAMPLE"
}
```
**例 2: 外部 JSON ファイルを使用して変更リクエストを開始するには**  
次の `start-automation-execution` の例では、JSON ファイルで指定された複数のオプションを使用して変更リクエストを開始します。  

```
aws ssm start-change-request-execution \
    --cli-input-json file://MyChangeRequest.json
```
`MyChangeRequest.json` の内容:  

```
{
    "ChangeRequestName": "MyChangeRequest",
    "DocumentName": "AWS-HelloWorldChangeTemplate",
    "DocumentVersion": "$DEFAULT",
    "ScheduledTime": "2021-12-30T03:00:00",
    "ScheduledEndTime": "2021-12-30T03:05:00",
    "Tags": [
        {
            "Key": "Purpose",
            "Value": "Testing"
        }
    ],
    "Parameters": {
        "Approver": [
            "JohnDoe"
        ],
        "ApproverType": [
            "IamUser"
        ],
        "ApproverSnsTopicArn": [
            "arn:aws:sns:us-east-2:111222333444;:MyNotificationTopic
        ]
    },
    "Runbooks": [
        {
            "DocumentName": "AWS-HelloWorld",
            "DocumentVersion": "1",
            "MaxConcurrency": "1",
            "MaxErrors": "1",
            "Parameters": {
                "AutomationAssumeRole": [
                    "arn:aws:iam::111222333444:role/MyChangeManagerAssumeRole"
                ]
            }
        }
    ],
    "ChangeDetails": "### Document Name: HelloWorldChangeTemplate\n\n## What does this document do?\nThis change template demonstrates the feature set available for creating change templates for Change Manager. This template starts a Runbook workflow for the Automation document called AWS-HelloWorld.\n\n## Input Parameters\n* ApproverSnsTopicArn: (Required) Amazon Simple Notification Service ARN for approvers.\n* Approver: (Required) The name of the approver to send this request to.\n* ApproverType: (Required) The type of reviewer.\n  * Allowed Values: IamUser, IamGroup, IamRole, SSOGroup, SSOUser\n\n## Output Parameters\nThis document has no outputs \n"
}
```
出力:  

```
{
  "AutomationExecutionId": "9d32a4fc-f944-11e6-4105-0a1b2EXAMPLE"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[変更リクエストの作成](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-requests-create.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartChangeRequestExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/start-change-request-execution.html)」を参照してください。

### `start-session`
<a name="ssm_StartSession_cli_2_topic"></a>

次のコード例は、`start-session` を使用する方法を示しています。

**AWS CLI**  
**例 1: Session Manager のセッションを開始するには**  
この `start-session` の例では、Session Manager のセッションのためにインスタンスとの接続を確立します。このインタラクティブなコマンドでは、呼び出しを実行するクライアントマシンに Session Manager プラグインがインストールされている必要があることに留意してください。  

```
aws ssm start-session \
    --target "i-1234567890abcdef0"
```
出力:  

```
Starting session with SessionId: Jane-Roe-07a16060613c408b5
```
**例 2: SSH を使用して Session Manager のセッションを開始するには**  
この `start-session` の例では、SSH を使用して Session Manager のセッションのためにインスタンスとの接続を確立します。このインタラクティブなコマンドでは、呼び出しを実行するクライアントマシンに Session Manager プラグインがインストールされている必要があり、コマンドは Linux の EC2 インスタンスの `ec2-user` など、インスタンスのデフォルトユーザーを使用することに留意してください。  

```
ssh -i /path/my-key-pair.pem ec2-user@i-02573cafcfEXAMPLE
```
出力:  

```
Starting session with SessionId: ec2-user-07a16060613c408b5
```
詳細については、「Systems Manager ユーザーガイド」の[「セッションの開始](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html)」および「CLI 用の Session Manager プラグインのインストール」を参照してください。 [AWS](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html) *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/start-session.html)」を参照してください。

### `stop-automation-execution`
<a name="ssm_StopAutomationExecution_cli_2_topic"></a>

次のコード例は、`stop-automation-execution` を使用する方法を示しています。

**AWS CLI**  
**オートメーションの実行を停止するには**  
次の `stop-automation-execution` の例では、オートメーションドキュメントを停止します。  

```
aws ssm stop-automation-execution
    --automation-execution-id "4105a4fc-f944-11e6-9d32-0a1b2EXAMPLE"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[オートメーションを手動で実行する](https://docs.aws.amazon.com/systems-manager/latest/userguide/automation-working-executing-manually.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopAutomationExecution](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/stop-automation-execution.html)」を参照してください。

### `terminate-session`
<a name="ssm_TerminateSession_cli_2_topic"></a>

次のコード例は、`terminate-session` を使用する方法を示しています。

**AWS CLI**  
**Session Manager セッションを終了するには**  
この `terminate-session` の例では、ユーザーの「Shirley-Rodriguez」によって作成されたセッションを完全に終了し、インスタンス上の Session Manager クライアントと SSM エージェントの間のデータ接続を閉じます。  

```
aws ssm terminate-session \
    --session-id "Shirley-Rodriguez-07a16060613c408b5"
```
出力:  

```
{
    "SessionId": "Shirley-Rodriguez-07a16060613c408b5"
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[セッションを終了する](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-end.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TerminateSession](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/terminate-session.html)」を参照してください。

### `unlabel-parameter-version`
<a name="ssm_UnlabelParameterVersion_cli_2_topic"></a>

次のコード例は、`unlabel-parameter-version` を使用する方法を示しています。

**AWS CLI**  
**パラメータラベルを削除するには**  
次の `unlabel-parameter-version` の例では、特定のパラメータバージョンから指定されたラベルを削除します。  

```
aws ssm unlabel-parameter-version \
    --name "parameterName" \
    --parameter-version "version" \
    --labels "label_1" "label_2" "label_3"
```
出力:  

```
{
    "RemovedLabels": [
        "label_1"
        "label_2"
        "label_3"
    ],
    "InvalidLabels": []
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*」の[「パラメータラベルの削除 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-labels.html#systems-manager-parameter-store-labels-cli-delete)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UnlabelParameterVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/unlabel-parameter-version.html)」を参照してください。

### `update-association-status`
<a name="ssm_UpdateAssociationStatus_cli_2_topic"></a>

次のコード例は、`update-association-status` を使用する方法を示しています。

**AWS CLI**  
**関連付けステータスを更新するには**  
次の `update-association-status` の例では、インスタンスとドキュメント間の関連付けの関連付けステータスを更新します。  

```
aws ssm update-association-status \
    --name "AWS-UpdateSSMAgent" \
    --instance-id "i-1234567890abcdef0" \
    --association-status "Date=1424421071.939,Name=Pending,Message=temp_status_change,AdditionalInfo=Additional-Config-Needed"
```
出力:  

```
{
    "AssociationDescription": {
        "Name": "AWS-UpdateSSMAgent",
        "InstanceId": "i-1234567890abcdef0",
        "AssociationVersion": "1",
        "Date": 1550507529.604,
        "LastUpdateAssociationDate": 1550507806.974,
        "Status": {
            "Date": 1424421071.0,
            "Name": "Pending",
            "Message": "temp_status_change",
            "AdditionalInfo": "Additional-Config-Needed"
        },
        "Overview": {
            "Status": "Success",
            "AssociationStatusAggregatedCount": {
                "Success": 1
            }
        },
        "DocumentVersion": "$DEFAULT",
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "InstanceIds",
                "Values": [
                    "i-1234567890abcdef0"
                ]
            }
        ],
        "LastExecutionDate": 1550507808.0,
        "LastSuccessfulExecutionDate": 1550507808.0
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Systems Manager の関連付けの使用](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-associations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAssociationStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-association-status.html)」を参照してください。

### `update-association`
<a name="ssm_UpdateAssociation_cli_2_topic"></a>

次のコード例は、`update-association` を使用する方法を示しています。

**AWS CLI**  
**例 1: ドキュメントの関連付けを更新するには**  
次の `update-association` の例では、新しいドキュメントバージョンとの関連付けを更新します。  

```
aws ssm update-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --document-version "\$LATEST"
```
出力:  

```
{
    "AssociationDescription": {
        "Name": "AWS-UpdateSSMAgent",
        "AssociationVersion": "2",
        "Date": 1550508093.293,
        "LastUpdateAssociationDate": 1550508106.596,
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "DocumentVersion": "$LATEST",
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "tag:Name",
                "Values": [
                    "Linux"
                ]
            }
        ],
        "LastExecutionDate": 1550508094.879,
        "LastSuccessfulExecutionDate": 1550508094.879
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの編集と新しいバージョンの作成](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)」を参照してください。  
**例 2: 関連付けのスケジュール式を更新するには**  
次の `update-association` の例では、指定された関連付けのスケジュール式を更新します。  

```
aws ssm update-association \
    --association-id "8dfe3659-4309-493a-8755-0123456789ab" \
    --schedule-expression "cron(0 0 0/4 1/1 * ? *)"
```
出力:  

```
{
    "AssociationDescription": {
        "Name": "AWS-HelloWorld",
        "AssociationVersion": "2",
        "Date": "2021-02-08T13:54:19.203000-08:00",
        "LastUpdateAssociationDate": "2021-06-29T11:51:07.933000-07:00",
        "Overview": {
            "Status": "Pending",
            "DetailedStatus": "Creating"
        },
        "DocumentVersion": "$DEFAULT",
        "AssociationId": "8dfe3659-4309-493a-8755-0123456789ab",
        "Targets": [
            {
                "Key": "aws:NoOpAutomationTag",
                "Values": [
                    "AWS-NoOpAutomationTarget-Value"
                ]
            }
        ],
        "ScheduleExpression": "cron(0 0 0/4 1/1 * ? *)",
        "LastExecutionDate": "2021-06-26T19:00:48.110000-07:00",
        "ApplyOnlyAtCronInterval": false
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[関連付けの編集と新しいバージョンの作成](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-state-assoc-edit.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-association.html)」を参照してください。

### `update-document-default-version`
<a name="ssm_UpdateDocumentDefaultVersion_cli_2_topic"></a>

次のコード例は、`update-document-default-version` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントのデフォルトバージョンを更新するには**  
次の `update-document-default-version` の例では、Systems Manager ドキュメントのデフォルトバージョンを更新します。  

```
aws ssm update-document-default-version \
    --name "Example" \
    --document-version "2"
```
出力:  

```
{
    "Description": {
        "Name": "Example",
        "DefaultVersion": "2"
    }
}
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[SSM ドキュメントコンテンツを書き込む](https://docs.aws.amazon.com/systems-manager/latest/userguide/create-ssm-doc.html#writing-ssm-doc-content)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDocumentDefaultVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-document-default-version.html)」を参照してください。

### `update-document-metadata`
<a name="ssm_UpdateDocumentMetadata_cli_2_topic"></a>

次のコード例は、`update-document-metadata` を使用する方法を示しています。

**AWS CLI**  
**例: 変更テンプレートの最新バージョンを承認するには**  
次の `update-document-metadata` は、レビューのために送信された変更テンプレートの最新バージョンを承認します。  

```
aws ssm update-document-metadata \
    --name MyChangeManagerTemplate \
    --document-reviews 'Action=Approve,Comment=[{Type=Comment,Content=Approved!}]'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[変更テンプレートの確認と、承認または拒否](https://docs.aws.amazon.com/systems-manager/latest/userguide/change-templates-review.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDocumentMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-document-metadata.html)」を参照してください。

### `update-document`
<a name="ssm_UpdateDocument_cli_2_topic"></a>

次のコード例は、`update-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントの新しいバージョンを作成するには**  
次の `update-document` の例では、Windows コンピュータでの実行時に、ドキュメントの新しいバージョンを作成します。`--document` で指定されるドキュメントは JSON 形式である必要があります。`file://` に続くコンテンツファイルのパスを参照する必要があることに注意してください。`--document-version` パラメータの先頭に `$` があるため、Windows では値を二重引用符で囲む必要があります。Linux、MacOS、または PowerShell プロンプトでは、値を一重引用符で囲む必要があります。  
**Windows のバージョン**:  

```
aws ssm update-document \
    --name "RunShellScript" \
    --content "file://RunShellScript.json" \
    --document-version "$LATEST"
```
**Linux/Mac バージョン**:  

```
aws ssm update-document \
    --name "RunShellScript" \
    --content "file://RunShellScript.json" \
    --document-version '$LATEST'
```
出力:  

```
{
  "DocumentDescription": {
      "Status": "Updating",
      "Hash": "f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b",
      "Name": "RunShellScript",
      "Parameters": [
          {
              "Type": "StringList",
              "Name": "commands",
              "Description": "(Required) Specify a shell script or a command to run."
          }
      ],
      "DocumentType": "Command",
      "PlatformTypes": [
          "Linux"
      ],
      "DocumentVersion": "2",
      "HashType": "Sha256",
      "CreatedDate": 1487899655.152,
      "Owner": "809632081692",
      "SchemaVersion": "2.0",
      "DefaultVersion": "1",
      "LatestVersion": "2",
      "Description": "Run an updated script"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-document.html)」を参照してください。

### `update-maintenance-window-target`
<a name="ssm_UpdateMaintenanceWindowTarget_cli_2_topic"></a>

次のコード例は、`update-maintenance-window-target` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウのターゲットを更新するには**  
次の `update-maintenance-window-target` の例では、メンテナンスウィンドウのターゲットの名前のみを更新します。  

```
aws ssm update-maintenance-window-target \
    --window-id "mw-0c5ed765acEXAMPLE" \
    --window-target-id "57e8344e-fe64-4023-8191-6bf05EXAMPLE" \
    --name "NewName" \
    --no-replace
```
出力:  

```
{
    "Description": "",
    "OwnerInformation": "",
    "WindowTargetId": "57e8344e-fe64-4023-8191-6bf05EXAMPLE",
    "WindowId": "mw-0c5ed765acEXAMPLE",
    "Targets": [
        {
            "Values": [
                "i-1234567890EXAMPLE"
            ],
            "Key": "InstanceIds"
        }
    ],
    "Name": "NewName"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウの更新 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMaintenanceWindowTarget](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-maintenance-window-target.html)」を参照してください。

### `update-maintenance-window-task`
<a name="ssm_UpdateMaintenanceWindowTask_cli_2_topic"></a>

次のコード例は、`update-maintenance-window-task` を使用する方法を示しています。

**AWS CLI**  
**メンテナンスウィンドウのタスクを更新するには**  
次の `update-maintenance-window-task` の例では、メンテナンスウィンドウのタスクのサービスロールを更新します。  

```
aws ssm update-maintenance-window-task \
    --window-id "mw-0c5ed765acEXAMPLE" \
    --window-task-id "23d3809e-9fbe-4ddf-b41a-b49d7EXAMPLE" \
    --service-role-arn "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM"
```
出力:  

```
{
    "ServiceRoleArn": "arn:aws:iam::111222333444:role/aws-service-role/ssm.amazonaws.com/AWSServiceRoleForAmazonSSM",
    "MaxErrors": "1",
    "TaskArn": "AWS-UpdateEC2Config",
    "MaxConcurrency": "1",
    "WindowTaskId": "23d3809e-9fbe-4ddf-b41a-b49d7EXAMPLE",
    "TaskParameters": {},
    "Priority": 1,
    "TaskInvocationParameters": {
        "RunCommand": {
            "TimeoutSeconds": 600,
            "Parameters": {
                "allowDowngrade": [
                    "false"
                ]
            }
        }
    },
    "WindowId": "mw-0c5ed765acEXAMPLE",
    "Description": "UpdateEC2Config",
    "Targets": [
        {
            "Values": [
                "57e8344e-fe64-4023-8191-6bf05EXAMPLE"
            ],
            "Key": "WindowTargetIds"
        }
    ],
    "Name": "UpdateEC2Config"
}
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウの更新 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMaintenanceWindowTask](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-maintenance-window-task.html)」を参照してください。

### `update-maintenance-window`
<a name="ssm_UpdateMaintenanceWindow_cli_2_topic"></a>

次のコード例は、`update-maintenance-window` を使用する方法を示しています。

**AWS CLI**  
**例 1: メンテナンスウィンドウを更新するには**  
次の `update-maintenance-window` の例では、メンテナンスウィンドウの名前を更新します。  

```
aws ssm update-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9" \
    --name "My-Renamed-MW"
```
出力:  

```
{
    "Cutoff": 1,
    "Name": "My-Renamed-MW",
    "Schedule": "cron(0 16 ? * TUE *)",
    "Enabled": true,
    "AllowUnassociatedTargets": true,
    "WindowId": "mw-1a2b3c4d5e6f7g8h9",
    "Duration": 4
}
```
**例 2: メンテナンスウィンドウを無効にするには**  
次の `update-maintenance-window` の例では、メンテナンスウィンドウを無効にします。  

```
aws ssm update-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9" \
    --no-enabled
```
**例 3: メンテナンスウィンドウを有効にするには**  
次の `update-maintenance-window` の例では、メンテナンスウィンドウを有効にします。  

```
aws ssm update-maintenance-window \
    --window-id "mw-1a2b3c4d5e6f7g8h9" \
    --enabled
```
詳細については、*AWS 「Systems Manager ユーザーガイド*[」の「メンテナンスウィンドウの更新 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/maintenance-windows-cli-tutorials-update.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMaintenanceWindow](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-maintenance-window.html)」を参照してください。

### `update-managed-instance-role`
<a name="ssm_UpdateManagedInstanceRole_cli_2_topic"></a>

次のコード例は、`update-managed-instance-role` を使用する方法を示しています。

**AWS CLI**  
**マネージドインスタンスの IAM ロールを更新するには**  
次の `update-managed-instance-role` の例では、マネージドインスタンスの IAM インスタンスプロファイルを更新します。  

```
aws ssm update-managed-instance-role \
    --instance-id "mi-08ab247cdfEXAMPLE" \
    --iam-role "ExampleRole"
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[ステップ 4: Systems Manager の IAM インスタンスプロファイルを作成する](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateManagedInstanceRole](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-managed-instance-role.html)」を参照してください。

### `update-ops-item`
<a name="ssm_UpdateOpsItem_cli_2_topic"></a>

次のコード例は、`update-ops-item` を使用する方法を示しています。

**AWS CLI**  
**OpsItem を更新するには**  
次の `update-ops-item` の例は、OpsItem の記述、優先度、カテゴリを更新します。さらに、このコマンドは、この OpsItem が編集または変更されたときに通知が送信される SNS トピックを指定します。  

```
aws ssm update-ops-item \
    --ops-item-id "oi-287b5EXAMPLE" \
    --description "Primary OpsItem for failover event 2020-01-01-fh398yf" \
    --priority 2 \
    --category "Security" \
    --notifications "Arn=arn:aws:sns:us-east-2:111222333444:my-us-east-2-topic"
```
出力:  

```
This command produces no output.
```
詳細については、「AWS Systems Manager ユーザーガイド」の「[OpsItems を管理する](https://docs.aws.amazon.com/systems-manager/latest/userguide/OpsCenter-working-with-OpsItems.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[UpdateOpsItem](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-ops-item.html)」を参照してください。

### `update-patch-baseline`
<a name="ssm_UpdatePatchBaseline_cli_2_topic"></a>

次のコード例は、`update-patch-baseline` を使用する方法を示しています。

**AWS CLI**  
**例 1: パッチベースラインを更新するには**  
次の `update-patch-baseline` の例では、指定された 2 つのパッチを拒否済み、1 つのパッチを承認済みとして、指定されたパッチベースラインに追加します。  

```
aws ssm update-patch-baseline \
        --baseline-id "pb-0123456789abcdef0" \
        --rejected-patches "KB2032276" "MS10-048" \
        --approved-patches "KB2124261"
```
出力:  

```
{
    "BaselineId": "pb-0123456789abcdef0",
    "Name": "WindowsPatching",
    "OperatingSystem": "WINDOWS",
    "GlobalFilters": {
        "PatchFilters": []
    },
    "ApprovalRules": {
        "PatchRules": [
            {
                "PatchFilterGroup": {
                    "PatchFilters": [
                        {
                            "Key": "PRODUCT",
                            "Values": [
                                "WindowsServer2016"
                            ]
                        }
                    ]
                },
                "ComplianceLevel": "CRITICAL",
                "ApproveAfterDays": 0,
                "EnableNonSecurity": false
            }
        ]
    },
    "ApprovedPatches": [
        "KB2124261"
    ],
    "ApprovedPatchesComplianceLevel": "UNSPECIFIED",
    "ApprovedPatchesEnableNonSecurity": false,
    "RejectedPatches": [
        "KB2032276",
        "MS10-048"
    ],
    "RejectedPatchesAction": "ALLOW_AS_DEPENDENCY",
    "CreatedDate": 1550244180.465,
    "ModifiedDate": 1550244180.465,
    "Description": "Patches for Windows Servers",
    "Sources": []
}
```
**例 2: パッチベースラインの名前を変更するには**  
次の `update-patch-baseline` の例では、指定されたパッチベースラインの名前を変更します。  

```
aws ssm update-patch-baseline \
    --baseline-id "pb-0713accee01234567" \
    --name "Windows-Server-2012-R2-Important-and-Critical-Security-Updates"
```
詳細については、「*AWS Systems Manager ユーザーガイド*」の「カスタムパッチベースラインの更新または削除 <https://docs.aws.amazon.com/systems-manager/latest/userguide/patch-baseline-update-or-delete.html>`\$1\$1」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePatchBaseline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-patch-baseline.html)」を参照してください。

### `update-resource-data-sync`
<a name="ssm_UpdateResourceDataSync_cli_2_topic"></a>

次のコード例は、`update-resource-data-sync` を使用する方法を示しています。

**AWS CLI**  
**リソースデータの同期を更新するには**  
次の `update-resource-data-sync` の例では、SyncFromSource リソースデータの同期を更新します。  

```
aws ssm update-resource-data-sync \
    --sync-name exampleSync \
    --sync-type SyncFromSource \
    --sync-source '{"SourceType":"SingleAccountMultiRegions", "SourceRegions":["us-east-1", "us-west-2"]}'
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[複数のアカウントおよびリージョンのデータを表示するように Systems Manager Explorer を設定する](https://docs.aws.amazon.com/systems-manager/latest/userguide/Explorer-resource-data-sync.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResourceDataSync](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-resource-data-sync.html)」を参照してください。

### `update-service-setting`
<a name="ssm_UpdateServiceSetting_cli_2_topic"></a>

次のコード例は、`update-service-setting` を使用する方法を示しています。

**AWS CLI**  
**Parameter Store スループットのサービス設定を更新するには**  
次の `update-service-setting` の例では、指定されたリージョンの Parameter Store スループットの現在のサービス設定を更新して、引き上げられたスループットを使用します。  

```
aws ssm update-service-setting \
    --setting-id arn:aws:ssm:us-east-1:123456789012:servicesetting/ssm/parameter-store/high-throughput-enabled \
    --setting-value true
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Systems Manager ユーザーガイド*」の「[Parameter Store スループットの引き上げ](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-store-throughput.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateServiceSetting](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/update-service-setting.html)」を参照してください。

# を使用した Amazon Textract の例 AWS CLI
<a name="cli_2_textract_code_examples"></a>

次のコード例は、Amazon Textract AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `analyze-document`
<a name="textract_AnalyzeDocument_cli_2_topic"></a>

次のコード例は、`analyze-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメント内のテキストを分析するには**  
次の `analyze-document` の例は、ドキュメント内のテキストを分析する方法を示しています。  
Linux/macOS:  

```
aws textract analyze-document \
    --document '{"S3Object":{"Bucket":"bucket","Name":"document"}}' \
    --feature-types '["TABLES","FORMS"]'
```
Windows:  

```
aws textract analyze-document \
    --document "{\"S3Object\":{\"Bucket\":\"bucket\",\"Name\":\"document\"}}" \
    --feature-types "[\"TABLES\",\"FORMS\"]" \
    --region region-name
```
出力:  

```
{
    "Blocks": [
        {
            "Geometry": {
                "BoundingBox": {
                    "Width": 1.0,
                    "Top": 0.0,
                    "Left": 0.0,
                    "Height": 1.0
                },
                "Polygon": [
                    {
                        "Y": 0.0,
                        "X": 0.0
                    },
                    {
                        "Y": 0.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 0.0
                    }
                ]
            },
            "Relationships": [
                {
                    "Type": "CHILD",
                    "Ids": [
                        "87586964-d50d-43e2-ace5-8a890657b9a0",
                        "a1e72126-21d9-44f4-a8d6-5c385f9002ba",
                        "e889d012-8a6b-4d2e-b7cd-7a8b327d876a"
                    ]
                }
            ],
            "BlockType": "PAGE",
            "Id": "c2227f12-b25d-4e1f-baea-1ee180d926b2"
        }
    ],
    "DocumentMetadata": {
        "Pages": 1
    }
}
```
詳細については、「Amazon Textract デベロッパーガイド」の「Amazon Textract を使用したドキュメントテキストの分析」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンス**の「[AnalyzeDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/textract/analyze-document.html)」を参照してください。

### `detect-document-text`
<a name="textract_DetectDocumentText_cli_2_topic"></a>

次のコード例は、`detect-document-text` を使用する方法を示しています。

**AWS CLI**  
**ドキュメント内のテキストを検出するには**  
次の `detect-document-text` の例は、ドキュメント内のテキストを検出する方法を示しています。  
Linux/macOS:  

```
aws textract detect-document-text \
    --document '{"S3Object":{"Bucket":"bucket","Name":"document"}}'
```
Windows:  

```
aws textract detect-document-text \
    --document "{\"S3Object\":{\"Bucket\":\"bucket\",\"Name\":\"document\"}}" \
    --region region-name
```
出力:  

```
{
    "Blocks": [
        {
            "Geometry": {
                "BoundingBox": {
                    "Width": 1.0,
                    "Top": 0.0,
                    "Left": 0.0,
                    "Height": 1.0
                },
                "Polygon": [
                    {
                        "Y": 0.0,
                        "X": 0.0
                    },
                    {
                        "Y": 0.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 0.0
                    }
                ]
            },
            "Relationships": [
                {
                    "Type": "CHILD",
                    "Ids": [
                        "896a9f10-9e70-4412-81ce-49ead73ed881",
                        "0da18623-dc4c-463d-a3d1-9ac050e9e720",
                        "167338d7-d38c-4760-91f1-79a8ec457bb2"
                    ]
                }
            ],
            "BlockType": "PAGE",
            "Id": "21f0535e-60d5-4bc7-adf2-c05dd851fa25"
        },
        {
            "Relationships": [
                {
                    "Type": "CHILD",
                    "Ids": [
                        "62490c26-37ea-49fa-8034-7a9ff9369c9c",
                        "1e4f3f21-05bd-4da9-ba10-15d01e66604c"
                    ]
                }
            ],
            "Confidence": 89.11581420898438,
            "Geometry": {
                "BoundingBox": {
                    "Width": 0.33642634749412537,
                    "Top": 0.17169663310050964,
                    "Left": 0.13885067403316498,
                    "Height": 0.49159330129623413
                },
                "Polygon": [
                    {
                        "Y": 0.17169663310050964,
                        "X": 0.13885067403316498
                    },
                    {
                        "Y": 0.17169663310050964,
                        "X": 0.47527703642845154
                    },
                    {
                        "Y": 0.6632899641990662,
                        "X": 0.47527703642845154
                    },
                    {
                        "Y": 0.6632899641990662,
                        "X": 0.13885067403316498
                    }
                ]
            },
            "Text": "He llo,",
            "BlockType": "LINE",
            "Id": "896a9f10-9e70-4412-81ce-49ead73ed881"
        },
        {
            "Relationships": [
                {
                    "Type": "CHILD",
                    "Ids": [
                        "19b28058-9516-4352-b929-64d7cef29daf"
                    ]
                }
            ],
            "Confidence": 85.5694351196289,
            "Geometry": {
                "BoundingBox": {
                    "Width": 0.33182239532470703,
                    "Top": 0.23131252825260162,
                    "Left": 0.5091826915740967,
                    "Height": 0.3766750991344452
                },
                "Polygon": [
                    {
                        "Y": 0.23131252825260162,
                        "X": 0.5091826915740967
                    },
                    {
                        "Y": 0.23131252825260162,
                        "X": 0.8410050868988037
                    },
                    {
                        "Y": 0.607987642288208,
                        "X": 0.8410050868988037
                    },
                    {
                        "Y": 0.607987642288208,
                        "X": 0.5091826915740967
                    }
                ]
            },
            "Text": "worlc",
            "BlockType": "LINE",
            "Id": "0da18623-dc4c-463d-a3d1-9ac050e9e720"
        }
    ],
    "DocumentMetadata": {
        "Pages": 1
    }
}
```
詳細については、「Amazon Textract デベロッパーガイド」の「ドキュメントのテキストの検出」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DetectDocumentText](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/textract/detect-document-text.html)」を参照してください。**

### `get-document-analysis`
<a name="textract_GetDocumentAnalysis_cli_2_topic"></a>

次のコード例は、`get-document-analysis` を使用する方法を示しています。

**AWS CLI**  
**複数ページのドキュメントの非同期テキスト分析の結果を取得するには**  
次の `get-document-analysis` の例は、複数ページのドキュメントの非同期テキスト分析の結果を取得します。  

```
aws textract get-document-analysis \
    --job-id df7cf32ebbd2a5de113535fcf4d921926a701b09b4e7d089f3aebadb41e0712b \
    --max-results 1000
```
出力:  

```
{
    "Blocks": [
        {
            "Geometry": {
                "BoundingBox": {
                    "Width": 1.0,
                    "Top": 0.0,
                    "Left": 0.0,
                    "Height": 1.0
                },
                "Polygon": [
                    {
                        "Y": 0.0,
                        "X": 0.0
                    },
                    {
                        "Y": 0.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 0.0
                    }
                ]
            },
            "Relationships": [
                {
                    "Type": "CHILD",
                    "Ids": [
                        "75966e64-81c2-4540-9649-d66ec341cd8f",
                        "bb099c24-8282-464c-a179-8a9fa0a057f0",
                        "5ebf522d-f9e4-4dc7-bfae-a288dc094595"
                    ]
                }
            ],
            "BlockType": "PAGE",
            "Id": "247c28ee-b63d-4aeb-9af0-5f7ea8ba109e",
            "Page": 1
        }
    ],
    "NextToken": "cY1W3eTFvoB0cH7YrKVudI4Gb0H8J0xAYLo8xI/JunCIPWCthaKQ+07n/ElyutsSy0+1VOImoTRmP1zw4P0RFtaeV9Bzhnfedpx1YqwB4xaGDA==",
    "DocumentMetadata": {
        "Pages": 1
    },
    "JobStatus": "SUCCEEDED"
}
```
詳細については、「Amazon Textract デベロッパーガイド」の「複数ページドキュメント内のテキストの検出または分析」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetDocumentAnalysis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/textract/get-document-analysis.html)」を参照してください。**

### `get-document-text-detection`
<a name="textract_GetDocumentTextDetection_cli_2_topic"></a>

次のコード例は、`get-document-text-detection` を使用する方法を示しています。

**AWS CLI**  
**複数ページのドキュメントの非同期テキスト検出の結果を取得するには**  
次の `get-document-text-detection` の例は、複数ページのドキュメントの非同期テキスト検出の結果を取得します。  

```
aws textract get-document-text-detection \
    --job-id 57849a3dc627d4df74123dca269d69f7b89329c870c65bb16c9fd63409d200b9 \
    --max-results 1000
```
Output  

```
{
    "Blocks": [
        {
            "Geometry": {
                "BoundingBox": {
                    "Width": 1.0,
                    "Top": 0.0,
                    "Left": 0.0,
                    "Height": 1.0
                },
                "Polygon": [
                    {
                        "Y": 0.0,
                        "X": 0.0
                    },
                    {
                        "Y": 0.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 1.0
                    },
                    {
                        "Y": 1.0,
                        "X": 0.0
                    }
                ]
            },
            "Relationships": [
                {
                    "Type": "CHILD",
                    "Ids": [
                        "1b926a34-0357-407b-ac8f-ec473160c6a9",
                        "0c35dc17-3605-4c9d-af1a-d9451059df51",
                        "dea3db8a-52c2-41c0-b50c-81f66f4aa758"
                    ]
                }
            ],
            "BlockType": "PAGE",
            "Id": "84671a5e-8c99-43be-a9d1-6838965da33e",
            "Page": 1
        }
    ],
    "NextToken": "GcqyoAJuZwujOT35EN4LCI3EUzMtiLq3nKyFFHvU5q1SaIdEBcSty+njNgoWwuMP/muqc96S4o5NzDqehhXvhkodMyVO5OJGyms5lsrCxibWJw==",
    "DocumentMetadata": {
        "Pages": 1
    },
    "JobStatus": "SUCCEEDED"
}
```
詳細については、「Amazon Textract デベロッパーガイド」の「複数ページドキュメント内のテキストの検出または分析」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDocumentTextDetection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/textract/get-document-text-detection.html)」を参照してください。

### `start-document-analysis`
<a name="textract_StartDocumentAnalysis_cli_2_topic"></a>

次のコード例は、`start-document-analysis` を使用する方法を示しています。

**AWS CLI**  
**複数ページのドキュメント内のテキストの分析を開始するには**  
次の `start-document-analysis` の例は、複数ページのドキュメントの非同期テキスト分析を開始する方法を示しています。  
Linux/macOS:  

```
aws textract start-document-analysis \
    --document-location '{"S3Object":{"Bucket":"bucket","Name":"document"}}' \
    --feature-types '["TABLES","FORMS"]' \
    --notification-channel "SNSTopicArn=arn:snsTopic,RoleArn=roleArn"
```
Windows:  

```
aws textract start-document-analysis \
    --document-location "{\"S3Object\":{\"Bucket\":\"bucket\",\"Name\":\"document\"}}" \
    --feature-types "[\"TABLES\", \"FORMS\"]" \
    --region region-name \
    --notification-channel "SNSTopicArn=arn:snsTopic,RoleArn=roleArn"
```
出力:  

```
{
    "JobId": "df7cf32ebbd2a5de113535fcf4d921926a701b09b4e7d089f3aebadb41e0712b"
}
```
詳細については、「Amazon Textract デベロッパーガイド」の「複数ページドキュメント内のテキストの検出または分析」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[StartDocumentAnalysis](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/textract/start-document-analysis.html)」を参照してください。**

### `start-document-text-detection`
<a name="textract_StartDocumentTextDetection_cli_2_topic"></a>

次のコード例は、`start-document-text-detection` を使用する方法を示しています。

**AWS CLI**  
**複数ページのドキュメント内のテキストの検出を開始するには**  
次の `start-document-text-detection` の例は、複数ページのドキュメントの非同期テキスト検出を開始する方法を示しています。  
Linux/macOS:  

```
aws textract start-document-text-detection \
        --document-location '{"S3Object":{"Bucket":"bucket","Name":"document"}}' \
        --notification-channel "SNSTopicArn=arn:snsTopic,RoleArn=roleARN"
```
Windows:  

```
aws textract start-document-text-detection \
    --document-location "{\"S3Object\":{\"Bucket\":\"bucket\",\"Name\":\"document\"}}" \
    --region region-name \
    --notification-channel "SNSTopicArn=arn:snsTopic,RoleArn=roleArn"
```
出力:  

```
{
    "JobId": "57849a3dc627d4df74123dca269d69f7b89329c870c65bb16c9fd63409d200b9"
}
```
詳細については、「Amazon Textract デベロッパーガイド」の「複数ページドキュメント内のテキストの検出または分析」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[StartDocumentTextDetection](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/textract/start-document-text-detection.html)」を参照してください。**

# を使用した Amazon Transcribe の例 AWS CLI
<a name="cli_2_transcribe_code_examples"></a>

次のコード例は、Amazon Transcribe AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-language-model`
<a name="transcribe_CreateLanguageModel_cli_2_topic"></a>

次のコード例は、`create-language-model` を使用する方法を示しています。

**AWS CLI**  
**例 1: トレーニングデータとチューニングデータの両方を使用してカスタム言語モデルを作成するには**  
次の `create-language-model` の例では、カスタム言語モデルを作成します。カスタム言語モデルを使用して、法律、ホスピタリティ、財務、保険などの分野の文字起こしパフォーマンスを向上させることができます。language-code には、有効な言語コードを入力します。base-model-name には、カスタム言語モデルで文字起こしする音声のサンプルレートに最適なベースモデルを指定します。model-name には、カスタム言語モデルを呼び出す名前を指定します。  

```
aws transcribe create-language-model \
    --language-code language-code \
    --base-model-name base-model-name \
    --model-name cli-clm-example \
    --input-data-config S3Uri="s3://amzn-s3-demo-bucket/Amazon-S3-Prefix-for-training-data",TuningDataS3Uri="s3://amzn-s3-demo-bucket/Amazon-S3-Prefix-for-tuning-data",DataAccessRoleArn="arn:aws:iam::AWS-account-number:role/IAM-role-with-permissions-to-create-a-custom-language-model"
```
出力:  

```
{
    "LanguageCode": "language-code",
    "BaseModelName": "base-model-name",
    "ModelName": "cli-clm-example",
    "InputDataConfig": {
        "S3Uri": "s3://amzn-s3-demo-bucket/Amazon-S3-Prefix/",
        "TuningDataS3Uri": "s3://amzn-s3-demo-bucket/Amazon-S3-Prefix/",
        "DataAccessRoleArn": "arn:aws:iam::AWS-account-number:role/IAM-role-with-permissions-create-a-custom-language-model"
    },
    "ModelStatus": "IN_PROGRESS"
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[カスタム言語モデルを使用したドメイン固有のトランスクリプション精度の向上](https://docs.aws.amazon.com/transcribe/latest/dg/custom-language-models.html)」を参照してください。**  
**例 2: トレーニングデータのみを使用してカスタム言語モデルを作成するには**  
次の `create-language-model` の例は、音声ファイルの文字起こしを行います。カスタム言語モデルを使用して、法律、ホスピタリティ、財務、保険などの分野の文字起こしパフォーマンスを向上させることができます。language-code には、有効な言語コードを入力します。base-model-name には、カスタム言語モデルで文字起こしする音声のサンプルレートに最適なベースモデルを指定します。model-name には、カスタム言語モデルを呼び出す名前を指定します。  

```
aws transcribe create-language-model \
    --language-code en-US \
    --base-model-name base-model-name \
    --model-name cli-clm-example \
    --input-data-config S3Uri="s3://amzn-s3-demo-bucket/Amazon-S3-Prefix-For-Training-Data",DataAccessRoleArn="arn:aws:iam::AWS-account-number:role/IAM-role-with-permissions-to-create-a-custom-language-model"
```
出力:  

```
{
    "LanguageCode": "en-US",
    "BaseModelName": "base-model-name",
    "ModelName": "cli-clm-example",
    "InputDataConfig": {
        "S3Uri": "s3://amzn-s3-demo-bucket/Amazon-S3-Prefix-For-Training-Data/",
        "DataAccessRoleArn": "arn:aws:iam::your-AWS-account-number:role/IAM-role-with-permissions-to-create-a-custom-language-model"
    },
    "ModelStatus": "IN_PROGRESS"
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[カスタム言語モデルを使用したドメイン固有のトランスクリプション精度の向上](https://docs.aws.amazon.com/transcribe/latest/dg/custom-language-models.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLanguageModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/create-language-model.html)」を参照してください。

### `create-medical-vocabulary`
<a name="transcribe_CreateMedicalVocabulary_cli_2_topic"></a>

次のコード例は、`create-medical-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**医学用語のカスタム語彙を作成するには**  
次の `create-medical-vocabulary` 例では、カスタム語彙を作成します。カスタム語彙を作成するには、より正確に書き起こすべき用語のすべてを含むテキストファイルを作成しておく必要があります。vocabulary-file-uri として、そのテキストファイルの Amazon Simple Storage Service (Amazon S3) URI を指定します。language-code として、カスタム語彙の言語に対応する言語コードを指定します。vocabulary-name として、カスタムボキャブラリーに付ける名前を指定します。  

```
aws transcribe create-medical-vocabulary \
    --vocabulary-name cli-medical-vocab-example \
    --language-code language-code \
    --vocabulary-file-uri https://amzn-s3-demo-bucket.AWS-Region.amazonaws.com/the-text-file-for-the-medical-custom-vocabulary.txt
```
出力:  

```
{
    "VocabularyName": "cli-medical-vocab-example",
    "LanguageCode": "language-code",
    "VocabularyState": "PENDING"
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[医療カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary-med.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateMedicalVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/create-medical-vocabulary.html)」を参照してください。

### `create-vocabulary-filter`
<a name="transcribe_CreateVocabularyFilter_cli_2_topic"></a>

次のコード例は、`create-vocabulary-filter` を使用する方法を示しています。

**AWS CLI**  
**語彙フィルターを作成するには**  
次の `create-vocabulary-filter` の例では、文字起こしには表示しない単語のリストを含むテキストファイルを使用する語彙フィルターを作成します。language-code には、カスタム語彙の言語に対応する言語コードを指定します。vocabulary-file-uri には、そのテキストファイルの Amazon Simple Storage Service (Amazon S3) URI を指定します。vocabulary-filter-name には、語彙フィルターの名前を指定します。  

```
aws transcribe create-vocabulary-filter \
    --language-code language-code \
    --vocabulary-filter-file-uri s3://amzn-s3-demo-bucket/vocabulary-filter.txt \
    --vocabulary-filter-name cli-vocabulary-filter-example
```
出力:  

```
{
    "VocabularyFilterName": "cli-vocabulary-filter-example",
    "LanguageCode": "language-code"
}
```
詳細については、「*Amazon Transcribe 開発者ガイド*」の「[不要な単語のフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/filter-unwanted-words.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateVocabularyFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/create-vocabulary-filter.html)」を参照してください。

### `create-vocabulary`
<a name="transcribe_CreateVocabulary_cli_2_topic"></a>

次のコード例は、`create-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**カスタム語彙を作成するには**  
次の `create-vocabulary` 例は、カスタム語彙を作成します。カスタム語彙を作成するには、より正確に書き起こすべき用語のすべてを含むテキストファイルを作成しておく必要があります。vocabulary-file-uri として、そのテキストファイルの Amazon Simple Storage Service (Amazon S3) URI を指定します。language-code として、カスタム語彙の言語に対応する言語コードを指定します。vocabulary-name として、カスタムボキャブラリーに付ける名前を指定します。  

```
aws transcribe create-vocabulary \
    --language-code language-code \
    --vocabulary-name cli-vocab-example \
    --vocabulary-file-uri s3://amzn-s3-demo-bucket/Amazon-S3-prefix/the-text-file-for-the-custom-vocabulary.txt
```
出力:  

```
{
    "VocabularyName": "cli-vocab-example",
    "LanguageCode": "language-code",
    "VocabularyState": "PENDING"
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。**  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/create-vocabulary.html)」を参照してください。**

### `delete-language-model`
<a name="transcribe_DeleteLanguageModel_cli_2_topic"></a>

次のコード例は、`delete-language-model` を使用する方法を示しています。

**AWS CLI**  
**カスタム言語モデルを削除するには**  
次の `delete-language-model` の例では、カスタム言語モデルを削除します。  

```
aws transcribe delete-language-model \
    --model-name model-name
```
このコマンドでは何も出力されません。  
詳細については、「Amazon Transcribe 開発者ガイド」の「[カスタム言語モデルを使用したドメイン固有のトランスクリプション精度の向上](https://docs.aws.amazon.com/transcribe/latest/dg/custom-language-models.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLanguageModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/delete-language-model.html)」を参照してください。

### `delete-medical-transcription-job`
<a name="transcribe_DeleteMedicalTranscriptionJob_cli_2_topic"></a>

次のコード例は、`delete-medical-transcription-job` を使用する方法を示しています。

**AWS CLI**  
**医療文字起こしジョブを削除するには**  
次の `delete-medical-transcription-job` の例は、医療文字起こしジョブを削除します。  

```
aws transcribe delete-medical-transcription-job \
    --medical-transcription-job-name medical-transcription-job-name
```
このコマンドでは何も出力されません。  
詳細については、「Amazon Transcribe デベロッパーガイド」の「[DeleteMedicalTranscriptionJob](https://docs.aws.amazon.com/transcribe/latest/dg/API_DeleteMedicalTranscriptionJob.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteMedicalTranscriptionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/delete-medical-transcription-job.html)」を参照してください。**

### `delete-medical-vocabulary`
<a name="transcribe_DeleteMedicalVocabulary_cli_2_topic"></a>

次のコード例は、`delete-medical-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**医療用語のカスタム語彙を削除するには**  
次の `delete-medical-vocabulary` の例は、医療用語のカスタム語彙を削除します。vocabulary-name には、カスタム語彙の名前を指定します。  

```
aws transcribe delete-vocabulary \
    --vocabulary-name medical-custom-vocabulary-name
```
このコマンドでは何も出力されません。  
詳細については、「Amazon Transcribe 開発者ガイド」の「[医療カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary-med.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMedicalVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/delete-medical-vocabulary.html)」を参照してください。

### `delete-transcription-job`
<a name="transcribe_DeleteTranscriptionJob_cli_2_topic"></a>

次のコード例は、`delete-transcription-job` を使用する方法を示しています。

**AWS CLI**  
**文字起こしジョブの 1 つを削除するには**  
次の `delete-transcription-job` 例では、トランスクリプションジョブの 1 つを削除します。  

```
aws transcribe delete-transcription-job \
    --transcription-job-name your-transcription-job
```
このコマンドでは何も出力されません。  
詳細については、「Amazon Transcribe デベロッパーガイド」の「[DeleteTranscriptionJob](https://docs.aws.amazon.com/transcribe/latest/dg/API_DeleteTranscriptionJob.html)」を参照してください。**  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteTranscriptionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/delete-transcription-job.html)」を参照してください。**

### `delete-vocabulary-filter`
<a name="transcribe_DeleteVocabularyFilter_cli_2_topic"></a>

次のコード例は、`delete-vocabulary-filter` を使用する方法を示しています。

**AWS CLI**  
**語彙フィルターを削除するには**  
次の `delete-vocabulary-filter` の例では、語彙フィルターを削除します。  

```
aws transcribe delete-vocabulary-filter \
    --vocabulary-filter-name vocabulary-filter-name
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Transcribe 開発者ガイド*」の「[不要な単語のフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/filter-unwanted-words.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteVocabularyFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/delete-vocabulary-filter.html)」を参照してください。

### `delete-vocabulary`
<a name="transcribe_DeleteVocabulary_cli_2_topic"></a>

次のコード例は、`delete-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**カスタム語彙を削除するには**  
次の `delete-vocabulary` の例は、カスタム語彙を削除します。  

```
aws transcribe delete-vocabulary \
    --vocabulary-name vocabulary-name
```
このコマンドでは何も出力されません。  
詳細については、「Amazon Transcribe デベロッパーガイド」の「[カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/delete-vocabulary.html)」を参照してください。**

### `describe-language-model`
<a name="transcribe_DescribeLanguageModel_cli_2_topic"></a>

次のコード例は、`describe-language-model` を使用する方法を示しています。

**AWS CLI**  
**特定のカスタム言語モデルに関する情報を取得するには**  
次の `describe-language-model` の例では、特定のカスタム言語モデルに関する情報を取得します。例えば、BaseModelName では、モデルが NarrowBand または WideBand モデルを使用してトレーニングされているかどうかを確認できます。NarrowBand ベースモデルを使用するカスタム言語モデルは、サンプルレートが 16 kHz 未満の音声を文字起こしできます。WideBand ベースモデルを使用する言語モデルは、16 kHz を超えるサンプルレートで音声を文字起こしできます。S3Uri パラメータは、トレーニングデータにアクセスしてカスタム言語モデルを作成するために使用した Amazon S3 プレフィックスを示します。  

```
aws transcribe describe-language-model \
    --model-name cli-clm-example
```
出力:  

```
{
    "LanguageModel": {
        "ModelName": "cli-clm-example",
        "CreateTime": "2020-09-25T17:57:38.504000+00:00",
        "LastModifiedTime": "2020-09-25T17:57:48.585000+00:00",
        "LanguageCode": "language-code",
        "BaseModelName": "base-model-name",
        "ModelStatus": "IN_PROGRESS",
        "UpgradeAvailability": false,
        "InputDataConfig": {
            "S3Uri": "s3://amzn-s3-demo-bucket/Amazon-S3-Prefix/",
            "TuningDataS3Uri": "s3://amzn-s3-demo-bucket/Amazon-S3-Prefix/",
            "DataAccessRoleArn": "arn:aws:iam::AWS-account-number:role/IAM-role-with-permissions-to-create-a-custom-language-model"
        }
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[カスタム言語モデルを使用したドメイン固有のトランスクリプション精度の向上](https://docs.aws.amazon.com/transcribe/latest/dg/custom-language-models.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeLanguageModel](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/describe-language-model.html)」を参照してください。

### `get-medical-transcription-job`
<a name="transcribe_GetMedicalTranscriptionJob_cli_2_topic"></a>

次のコード例は、`get-medical-transcription-job` を使用する方法を示しています。

**AWS CLI**  
**特定の医療用語の文字起こしジョブに関する情報を取得するには**  
次の `get-medical-transcription-job` の例では、特定の医療用語の文字起こしジョブに関する情報を取得します。文字起こし結果にアクセスするには、TranscriptFileUri パラメータを使用します。文字起こしジョブの追加機能を有効にしている場合、Settings オブジェクトで確認できます。専門分野パラメータは、プロバイダーの医療専門分野を示します。Type パラメータは、文字起こしジョブの音声が医療に関する会話かディクテーションかを示します。  

```
aws transcribe get-medical-transcription-job \
    --medical-transcription-job-name vocabulary-dictation-medical-transcription-job
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "vocabulary-dictation-medical-transcription-job",
        "TranscriptionJobStatus": "COMPLETED",
        "LanguageCode": "en-US",
        "MediaSampleRateHertz": 48000,
        "MediaFormat": "mp4",
        "Media": {
            "MediaFileUri": "s3://Amazon-S3-Prefix/your-audio-file.file-extension"
        },
        "Transcript": {
            "TranscriptFileUri": "https://s3.Region.amazonaws.com/Amazon-S3-Prefix/vocabulary-dictation-medical-transcription-job.json"
        },
        "StartTime": "2020-09-21T21:17:27.045000+00:00",
        "CreationTime": "2020-09-21T21:17:27.016000+00:00",
        "CompletionTime": "2020-09-21T21:17:59.561000+00:00",
        "Settings": {
            "ChannelIdentification": false,
            "ShowAlternatives": false,
            "VocabularyName": "cli-medical-vocab-example"
        },
        "Specialty": "PRIMARYCARE",
        "Type": "DICTATION"
    }
}
```
詳細については、「*Amazon Transcribe 開発者ガイド*」の「[バッチトランスクリプション](https://docs.aws.amazon.com/transcribe/latest/dg/batch-med-transcription.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMedicalTranscriptionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/get-medical-transcription-job.html)」を参照してください。

### `get-medical-vocabulary`
<a name="transcribe_GetMedicalVocabulary_cli_2_topic"></a>

次のコード例は、`get-medical-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**医療用語のカスタム語彙に関する情報を取得するには**  
次の `get-medical-vocabulary` の例では、医療用語のスタム語彙に関する情報を取得します。VocabularyState パラメータを使用して、語彙の処理状態を確認できます。READY の場合は、StartMedicalTranscriptionJob オペレーションで使用できます。  

```
aws transcribe get-medical-vocabulary \
    --vocabulary-name medical-vocab-example
```
出力:  

```
{
    "VocabularyName": "medical-vocab-example",
    "LanguageCode": "en-US",
    "VocabularyState": "READY",
    "LastModifiedTime": "2020-09-19T23:59:04.349000+00:00",
    "DownloadUri": "https://link-to-download-the-text-file-used-to-create-your-medical-custom-vocabulary"
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[医療カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMedicalVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/get-medical-vocabulary.html)」を参照してください。

### `get-transcription-job`
<a name="transcribe_GetTranscriptionJob_cli_2_topic"></a>

次のコード例は、`get-transcription-job` を使用する方法を示しています。

**AWS CLI**  
**特定の文字起こしジョブに関する情報を取得するには**  
次の `get-transcription-job` 例では、特定の文字起こしジョブに関する情報を取得します。文字起こし結果にアクセスするには、TranscriptFileUri パラメータを使用します。MediaFileUri パラメータを使用して、このジョブで書き起こした音声ファイルを確認します。Settings オブジェクトを使用して、文字起こしジョブで有効にしたオプション機能を確認できます。  

```
aws transcribe get-transcription-job \
    --transcription-job-name your-transcription-job
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "your-transcription-job",
        "TranscriptionJobStatus": "COMPLETED",
        "LanguageCode": "language-code",
        "MediaSampleRateHertz": 48000,
        "MediaFormat": "mp4",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.file-extension"
        },
        "Transcript": {
            "TranscriptFileUri": "https://Amazon-S3-file-location-of-transcription-output"
        },
        "StartTime": "2020-09-18T22:27:23.970000+00:00",
        "CreationTime": "2020-09-18T22:27:23.948000+00:00",
        "CompletionTime": "2020-09-18T22:28:21.197000+00:00",
        "Settings": {
            "ChannelIdentification": false,
            "ShowAlternatives": false
        },
        "IdentifyLanguage": true,
        "IdentifiedLanguageScore": 0.8672199249267578
    }
}
```
詳細については、*Amazon Transcribe デベロッパーガイド*[」の「開始方法 (AWS コマンドラインインターフェイス)](https://docs.aws.amazon.com/transcribe/latest/dg/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[GetTranscriptionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/get-transcription-job.html)」を参照してください。**

### `get-vocabulary-filter`
<a name="transcribe_GetVocabularyFilter_cli_2_topic"></a>

次のコード例は、`get-vocabulary-filter` を使用する方法を示しています。

**AWS CLI**  
**語彙フィルターに関する情報を取得するには**  
次の `get-vocabulary-filter` の例では、語彙フィルターに関する情報を取得します。DownloadUri パラメータを使用して、語彙フィルターの作成に使用した単語のリストを取得できます。  

```
aws transcribe get-vocabulary-filter \
    --vocabulary-filter-name testFilter
```
出力:  

```
{
    "VocabularyFilterName": "testFilter",
    "LanguageCode": "language-code",
    "LastModifiedTime": "2020-05-07T22:39:32.147000+00:00",
    "DownloadUri": "https://Amazon-S3-location-to-download-your-vocabulary-filter"
}
```
詳細については、「*Amazon Transcribe 開発者ガイド*」の「[不要な単語のフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVocabularyFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/get-vocabulary-filter.html)」を参照してください。

### `get-vocabulary`
<a name="transcribe_GetVocabulary_cli_2_topic"></a>

次のコード例は、`get-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**カスタム語彙に関する情報を取得するには**  
次の `get-vocabulary` 例では、以前に作成したカスタム語彙に関する情報を取得します。  

```
aws transcribe get-vocabulary \
    --vocabulary-name cli-vocab-1
```
出力:  

```
{
    "VocabularyName": "cli-vocab-1",
    "LanguageCode": "language-code",
    "VocabularyState": "READY",
    "LastModifiedTime": "2020-09-19T23:22:32.836000+00:00",
    "DownloadUri": "https://link-to-download-the-text-file-used-to-create-your-custom-vocabulary"
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/get-vocabulary.html)」を参照してください。

### `list-language-models`
<a name="transcribe_ListLanguageModels_cli_2_topic"></a>

次のコード例は、`list-language-models` を使用する方法を示しています。

**AWS CLI**  
**カスタム言語モデルを一覧表示するには**  
次の の`list-language-models`例では、 AWS アカウントとリージョンに関連付けられたカスタム言語モデルを一覧表示します。`S3Uri` および `TuningDataS3Uri` パラメータを使用して、トレーニングデータまたはチューニングデータとして使用した Amazon S3 プレフィックスを検索できます。BaseModelName は、NarrowBand モデルまたは WideBand モデルを使用してカスタム言語モデルを作成したかどうかを示します。NarrowBand ベースモデルを使用して、カスタム言語モデルでサンプルレートが 16 kHz 未満の音声を文字起こしできます。WideBand ベースモデルを使用して、カスタム言語モデルで 16 kHz 以上のオーディオを文字起こしできます。`ModelStatus` パラメータは、文字起こしジョブでカスタム言語モデルを使用できるかどうかを示します。値が COMPLETED の場合、文字起こしジョブで使用できます。  

```
aws transcribe list-language-models
```
出力:  

```
{
    "Models": [
        {
            "ModelName": "cli-clm-2",
            "CreateTime": "2020-09-25T17:57:38.504000+00:00",
            "LastModifiedTime": "2020-09-25T17:57:48.585000+00:00",
            "LanguageCode": "language-code",
            "BaseModelName": "WideBand",
            "ModelStatus": "IN_PROGRESS",
            "UpgradeAvailability": false,
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/clm-training-data/",
                "TuningDataS3Uri": "s3://amzn-s3-demo-bucket/clm-tuning-data/",
                "DataAccessRoleArn": "arn:aws:iam::AWS-account-number:role/IAM-role-used-to-create-the-custom-language-model"
            }
        },
        {
            "ModelName": "cli-clm-1",
            "CreateTime": "2020-09-25T17:16:01.835000+00:00",
            "LastModifiedTime": "2020-09-25T17:16:15.555000+00:00",
            "LanguageCode": "language-code",
            "BaseModelName": "WideBand",
            "ModelStatus": "IN_PROGRESS",
            "UpgradeAvailability": false,
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/clm-training-data/",
                "DataAccessRoleArn": "arn:aws:iam::AWS-account-number:role/IAM-role-used-to-create-the-custom-language-model"
            }
        },
        {
            "ModelName": "clm-console-1",
            "CreateTime": "2020-09-24T19:26:28.076000+00:00",
            "LastModifiedTime": "2020-09-25T04:25:22.271000+00:00",
            "LanguageCode": "language-code",
            "BaseModelName": "NarrowBand",
            "ModelStatus": "COMPLETED",
            "UpgradeAvailability": false,
            "InputDataConfig": {
                "S3Uri": "s3://amzn-s3-demo-bucket/clm-training-data/",
                "DataAccessRoleArn": "arn:aws:iam::AWS-account-number:role/IAM-role-used-to-create-the-custom-language-model"
            }
        }
    ]
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[カスタム言語モデルを使用したドメイン固有のトランスクリプション精度の向上](https://docs.aws.amazon.com/transcribe/latest/dg/custom-language-models.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLanguageModels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/list-language-models.html)」を参照してください。

### `list-medical-transcription-jobs`
<a name="transcribe_ListMedicalTranscriptionJobs_cli_2_topic"></a>

次のコード例は、`list-medical-transcription-jobs` を使用する方法を示しています。

**AWS CLI**  
**医療文字起こしジョブを一覧表示するには**  
次の の`list-medical-transcription-jobs`例では、 AWS アカウントとリージョンに関連付けられた医療文字起こしジョブを一覧表示します。特定の文字起こしジョブに関する詳細情報を取得するには、文字起こし出力の MedicalTranscriptionJobName パラメータの値をコピーし、その値を `get-medical-transcription-job` コマンドの `MedicalTranscriptionJobName` オプションに指定します。さらに他の文字起こしジョブを表示するには、NextToken パラメータの値をコピーし、再度 `list-medical-transcription-jobs` コマンドを実行して、その値を `--next-token` オプションに指定します。  

```
aws transcribe list-medical-transcription-jobs
```
出力:  

```
{
    "NextToken": "3/PblzkiGhzjER3KHuQt2fmbPLF7cDYafjFMEoGn44ON/gsuUSTIkGyanvRE6WMXFd/ZTEc2EZj+P9eii/z1O2FDYli6RLI0WoRX4RwMisVrh9G0Kie0Y8ikBCdtqlZB10Wa9McC+ebOl+LaDtZPC4u6ttoHLRlEfzqstHXSgapXg3tEBtm9piIaPB6MOM5BB6t86+qtmocTR/qrteHZBBudhTfbCwhsxaqujHiiUvFdm3BQbKKWIW06yV9b+4f38oD2lVIan+vfUs3gBYAl5VTDmXXzQPBQOHPjtwmFI+IWX15nSUjWuN3TUylHgPWzDaYT8qBtu0Z+3UG4V6b+K2CC0XszXg5rBq9hYgNzy4XoFh/6s5DoSnzq49Q9xHgHdT2yBADFmvFK7myZBsj75+2vQZOSVpWUPy3WT/32zFAcoELHR4unuWhXPwjbKU+mFYfUjtTZ8n/jq7aQEjQ42A+X/7K6JgOcdVPtEg8PlDr5kgYYG3q3OmYXX37U3FZuJmnTI63VtIXsNnOU5eGoYObtpk00Nq9UkzgSJxqj84ZD5n+S0EGy9ZUYBJRRcGeYUM3Q4DbSJfUwSAqcFdLIWZdp8qIREMQIBWy7BLwSdyqsQo2vRrd53hm5aWM7SVf6pPq6X/IXR5+1eUOOD8/coaTT4ES2DerbV6RkV4o0VT1d0SdVX/MmtkNG8nYj8PqU07w7988quh1ZP6D80veJS1q73tUUR9MjnGernW2tAnvnLNhdefBcD+sZVfYq3iBMFY7wTy1P1G6NqW9GrYDYoX3tTPWlD7phpbVSyKrh/PdYrps5UxnsGoA1b7L/FfAXDfUoGrGUB4N3JsPYXX9D++g+6gV1qBBs/WfF934aKqfD6UTggm/zV3GAOWiBpfvAZRvEb924i6yGHyMC7y54O1ZAwSBupmI+FFd13CaPO4kN1vJlth6aM5vUPXg4BpyUhtbRhwD/KxCvf9K0tLJGyL1A==",
    "MedicalTranscriptionJobSummaries": [
        {
            "MedicalTranscriptionJobName": "vocabulary-dictation-medical-transcription-job",
            "CreationTime": "2020-09-21T21:17:27.016000+00:00",
            "StartTime": "2020-09-21T21:17:27.045000+00:00",
            "CompletionTime": "2020-09-21T21:17:59.561000+00:00",
            "LanguageCode": "en-US",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "CUSTOMER_BUCKET",
            "Specialty": "PRIMARYCARE",
            "Type": "DICTATION"
        },
        {
            "MedicalTranscriptionJobName": "alternatives-dictation-medical-transcription-job",
            "CreationTime": "2020-09-21T21:01:14.569000+00:00",
            "StartTime": "2020-09-21T21:01:14.592000+00:00",
            "CompletionTime": "2020-09-21T21:01:43.606000+00:00",
            "LanguageCode": "en-US",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "CUSTOMER_BUCKET",
            "Specialty": "PRIMARYCARE",
            "Type": "DICTATION"
        },
        {
            "MedicalTranscriptionJobName": "alternatives-conversation-medical-transcription-job",
            "CreationTime": "2020-09-21T19:09:18.171000+00:00",
            "StartTime": "2020-09-21T19:09:18.199000+00:00",
            "CompletionTime": "2020-09-21T19:10:22.516000+00:00",
            "LanguageCode": "en-US",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "CUSTOMER_BUCKET",
            "Specialty": "PRIMARYCARE",
            "Type": "CONVERSATION"
        },
        {
            "MedicalTranscriptionJobName": "speaker-id-conversation-medical-transcription-job",
            "CreationTime": "2020-09-21T18:43:37.157000+00:00",
            "StartTime": "2020-09-21T18:43:37.265000+00:00",
            "CompletionTime": "2020-09-21T18:44:21.192000+00:00",
            "LanguageCode": "en-US",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "CUSTOMER_BUCKET",
            "Specialty": "PRIMARYCARE",
            "Type": "CONVERSATION"
        },
        {
            "MedicalTranscriptionJobName": "multichannel-conversation-medical-transcription-job",
            "CreationTime": "2020-09-20T23:46:44.053000+00:00",
            "StartTime": "2020-09-20T23:46:44.081000+00:00",
            "CompletionTime": "2020-09-20T23:47:35.851000+00:00",
            "LanguageCode": "en-US",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "CUSTOMER_BUCKET",
            "Specialty": "PRIMARYCARE",
            "Type": "CONVERSATION"
        }
    ]
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の https://docs.aws.amazon.com/transcribe/latest/dg/batch-med-transcription.html を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMedicalTranscriptionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/list-medical-transcription-jobs.html)」を参照してください。

### `list-medical-vocabularies`
<a name="transcribe_ListMedicalVocabularies_cli_2_topic"></a>

次のコード例は、`list-medical-vocabularies` を使用する方法を示しています。

**AWS CLI**  
**医療用語のカスタム語彙を一覧表示するには**  
次の の`list-medical-vocabularies`例では、 AWS アカウントとリージョンに関連付けられた医療カスタム語彙を一覧表示します。特定の文字起こしジョブに関する詳細情報を取得するには、文字起こし出力の `MedicalTranscriptionJobName` パラメータの値をコピーし、その値を `get-medical-transcription-job` コマンドの `MedicalTranscriptionJobName` オプションに指定します。さらに他の文字起こしジョブを表示するには、`NextToken` パラメータの値をコピーし、再度 `list-medical-transcription-jobs` コマンドを実行して、その値を `--next-token` オプションに指定します。  

```
aws transcribe list-medical-vocabularies
```
出力:  

```
{
    "Vocabularies": [
        {
            "VocabularyName": "cli-medical-vocab-2",
            "LanguageCode": "en-US",
            "LastModifiedTime": "2020-09-21T21:44:59.521000+00:00",
            "VocabularyState": "READY"
        },
        {
            "VocabularyName": "cli-medical-vocab-1",
            "LanguageCode": "en-US",
            "LastModifiedTime": "2020-09-19T23:59:04.349000+00:00",
            "VocabularyState": "READY"
        }
    ]
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[医療カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary-med.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMedicalVocabularies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/list-medical-vocabularies.html)」を参照してください。

### `list-transcription-jobs`
<a name="transcribe_ListTranscriptionJobs_cli_2_topic"></a>

次のコード例は、`list-transcription-jobs` を使用する方法を示しています。

**AWS CLI**  
**文字起こしジョブを一覧表示するには**  
次の の`list-transcription-jobs`例では、 AWS アカウントとリージョンに関連付けられた文字起こしジョブを一覧表示します。  

```
aws transcribe list-transcription-jobs
```
出力:  

```
{
    "NextToken": "NextToken",
    "TranscriptionJobSummaries": [
        {
            "TranscriptionJobName": "speak-id-job-1",
            "CreationTime": "2020-08-17T21:06:15.391000+00:00",
            "StartTime": "2020-08-17T21:06:15.416000+00:00",
            "CompletionTime": "2020-08-17T21:07:05.098000+00:00",
            "LanguageCode": "language-code",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "SERVICE_BUCKET"
        },
        {
            "TranscriptionJobName": "job-1",
            "CreationTime": "2020-08-17T20:50:24.207000+00:00",
            "StartTime": "2020-08-17T20:50:24.230000+00:00",
            "CompletionTime": "2020-08-17T20:52:18.737000+00:00",
            "LanguageCode": "language-code",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "SERVICE_BUCKET"
        },
        {
            "TranscriptionJobName": "sdk-test-job-4",
            "CreationTime": "2020-08-17T20:32:27.917000+00:00",
            "StartTime": "2020-08-17T20:32:27.956000+00:00",
            "CompletionTime": "2020-08-17T20:33:15.126000+00:00",
            "LanguageCode": "language-code",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "SERVICE_BUCKET"
        },
        {
            "TranscriptionJobName": "Diarization-speak-id",
            "CreationTime": "2020-08-10T22:10:09.066000+00:00",
            "StartTime": "2020-08-10T22:10:09.116000+00:00",
            "CompletionTime": "2020-08-10T22:26:48.172000+00:00",
            "LanguageCode": "language-code",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "SERVICE_BUCKET"
        },
        {
            "TranscriptionJobName": "your-transcription-job-name",
            "CreationTime": "2020-07-29T17:45:09.791000+00:00",
            "StartTime": "2020-07-29T17:45:09.826000+00:00",
            "CompletionTime": "2020-07-29T17:46:20.831000+00:00",
            "LanguageCode": "language-code",
            "TranscriptionJobStatus": "COMPLETED",
            "OutputLocationType": "SERVICE_BUCKET"
        }
    ]
}
```
詳細については、*Amazon Transcribe デベロッパーガイド*[」の「開始方法 (AWS コマンドラインインターフェイス)](https://docs.aws.amazon.com/transcribe/latest/dg/getting-started-cli.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTranscriptionJobs](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/list-transcription-jobs.html)」を参照してください。

### `list-vocabularies`
<a name="transcribe_ListVocabularies_cli_2_topic"></a>

次のコード例は、`list-vocabularies` を使用する方法を示しています。

**AWS CLI**  
**カスタム語彙を一覧表示するには**  
次の の`list-vocabularies`例では、 AWS アカウントとリージョンに関連付けられたカスタム語彙を一覧表示します。  

```
aws transcribe list-vocabularies
```
出力:  

```
{
    "NextToken": "NextToken",
    "Vocabularies": [
        {
            "VocabularyName": "ards-test-1",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-04-27T22:00:27.330000+00:00",
            "VocabularyState": "READY"
        },
        {
            "VocabularyName": "sample-test",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-04-24T23:04:11.044000+00:00",
            "VocabularyState": "READY"
        },
        {
            "VocabularyName": "CRLF-to-LF-test-3-1",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-04-24T22:12:22.277000+00:00",
            "VocabularyState": "READY"
        },
        {
            "VocabularyName": "CRLF-to-LF-test-2",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-04-24T21:53:50.455000+00:00",
            "VocabularyState": "READY"
        },
        {
            "VocabularyName": "CRLF-to-LF-1-1",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-04-24T21:39:33.356000+00:00",
            "VocabularyState": "READY"
        }
    ]
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVocabularies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/list-vocabularies.html)」を参照してください。

### `list-vocabulary-filters`
<a name="transcribe_ListVocabularyFilters_cli_2_topic"></a>

次のコード例は、`list-vocabulary-filters` を使用する方法を示しています。

**AWS CLI**  
**語彙フィルターを一覧表示するには**  
次の の`list-vocabulary-filters`例では、 AWS アカウントとリージョンに関連付けられた語彙フィルターを一覧表示します。  

```
aws transcribe list-vocabulary-filters
```
出力:  

```
{
    "NextToken": "NextToken": [
        {
            "VocabularyFilterName": "testFilter",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-05-07T22:39:32.147000+00:00"
        },
        {
            "VocabularyFilterName": "testFilter2",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-05-21T23:29:35.174000+00:00"
        },
        {
            "VocabularyFilterName": "filter2",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-05-08T20:18:26.426000+00:00"
        },
        {
            "VocabularyFilterName": "filter-review",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-06-03T18:52:30.448000+00:00"
        },
        {
            "VocabularyFilterName": "crlf-filt",
            "LanguageCode": "language-code",
            "LastModifiedTime": "2020-05-22T19:42:42.737000+00:00"
        }
    ]
}
```
詳細については、「*Amazon Transcribe 開発者ガイド*」の「[不要な単語のフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/filter-unwanted-words.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListVocabularyFilters](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/list-vocabulary-filters.html)」を参照してください。

### `start-medical-transcription-job`
<a name="transcribe_StartMedicalTranscriptionJob_cli_2_topic"></a>

次のコード例は、`start-medical-transcription-job` を使用する方法を示しています。

**AWS CLI**  
**例 1: オーディオファイルとして保存されている医療ディクテーションを文字起こしするには**  
次の `start-medical-transcription-job` の例は、オーディオファイルの文字起こしを行います。トランスクリプション出力の場所を `OutputBucketName` パラメータで指定します。  

```
aws transcribe start-medical-transcription-job \
    --cli-input-json file://myfile.json
```
`myfile.json` の内容:  

```
{
    "MedicalTranscriptionJobName": "simple-dictation-medical-transcription-job",
    "LanguageCode": "language-code",
    "Specialty": "PRIMARYCARE",
    "Type": "DICTATION",
    "OutputBucketName":"amzn-s3-demo-bucket",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
    }
}
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "simple-dictation-medical-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "StartTime": "2020-09-20T00:35:22.256000+00:00",
        "CreationTime": "2020-09-20T00:35:22.218000+00:00",
        "Specialty": "PRIMARYCARE",
        "Type": "DICTATION"
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[バッチトランスクリプションの概要](https://docs.aws.amazon.com/transcribe/latest/dg/batch-med-transcription.html)」を参照してください。**  
**例 2: オーディオファイルとして保存されている臨床医と患者の対話を文字起こしするには**  
次の `start-medical-transcription-job` 例では、臨床医と患者の対話を含むオーディオファイルの文字起こしを行います。文字起こしの出力の場所を OutputBucketName パラメータで指定します。  

```
aws transcribe start-medical-transcription-job \
    --cli-input-json file://mysecondfile.json
```
`mysecondfile.json` の内容:  

```
{
    "MedicalTranscriptionJobName": "simple-dictation-medical-transcription-job",
    "LanguageCode": "language-code",
    "Specialty": "PRIMARYCARE",
    "Type": "CONVERSATION",
    "OutputBucketName":"amzn-s3-demo-bucket",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
    }
}
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "simple-conversation-medical-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "StartTime": "2020-09-20T23:19:49.965000+00:00",
        "CreationTime": "2020-09-20T23:19:49.941000+00:00",
        "Specialty": "PRIMARYCARE",
        "Type": "CONVERSATION"
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[バッチトランスクリプションの概要](https://docs.aws.amazon.com/transcribe/latest/dg/batch-med-transcription.html)」を参照してください。**  
**例 3: 臨床医と患者の対話のマルチチャネルオーディオファイルを書き起こすには**  
次の `start-medical-transcription-job` 例では、オーディオオファイルの各チャネルの音声の文字起こしを行い、チャネル別の文字起こし結果を組み合わせて、単一の文字起こし出力にまとめます。文字起こしの出力の場所を `OutputBucketName` パラメータで指定します。  

```
aws transcribe start-medical-transcription-job \
    --cli-input-json file://mythirdfile.json
```
`mythirdfile.json` の内容:  

```
{
    "MedicalTranscriptionJobName": "multichannel-conversation-medical-transcription-job",
    "LanguageCode": "language-code",
    "Specialty": "PRIMARYCARE",
    "Type": "CONVERSATION",
    "OutputBucketName":"amzn-s3-demo-bucket",
        "Media": {
          "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "Settings":{
          "ChannelIdentification": true
        }
}
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "multichannel-conversation-medical-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "StartTime": "2020-09-20T23:46:44.081000+00:00",
        "CreationTime": "2020-09-20T23:46:44.053000+00:00",
        "Settings": {
            "ChannelIdentification": true
        },
        "Specialty": "PRIMARYCARE",
        "Type": "CONVERSATION"
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[チャネル識別](https://docs.aws.amazon.com/transcribe/latest/dg/how-channel-id-med.html)」を参照してください。**  
**例 4: 臨床医と患者の対話のオーディオファイルを文字起こしして、文字起こし出力の話者を特定するには**  
次の `start-medical-transcription-job` の例は、オーディオファイルを書き起こしして、文字起こし出力の各話者の発話にラベルを付けます。文字起こしの出力の場所を `OutputBucketName` パラメータで指定します。  

```
aws transcribe start-medical-transcription-job \
    --cli-input-json file://myfourthfile.json
```
`myfourthfile.json` の内容:  

```
{
    "MedicalTranscriptionJobName": "speaker-id-conversation-medical-transcription-job",
    "LanguageCode": "language-code",
    "Specialty": "PRIMARYCARE",
    "Type": "CONVERSATION",
    "OutputBucketName":"amzn-s3-demo-bucket",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
    "Settings":{
        "ShowSpeakerLabels": true,
        "MaxSpeakerLabels": 2
        }
}
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "speaker-id-conversation-medical-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "StartTime": "2020-09-21T18:43:37.265000+00:00",
        "CreationTime": "2020-09-21T18:43:37.157000+00:00",
        "Settings": {
            "ShowSpeakerLabels": true,
            "MaxSpeakerLabels": 2
        },
        "Specialty": "PRIMARYCARE",
        "Type": "CONVERSATION"
    }
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[話者の識別](https://docs.aws.amazon.com/transcribe/latest/dg/diarization-med.html)」を参照してください。**  
**例 5: オーディオファイルとして保存されている医療会話を、最大 2 つの代替文字起こし結果に文字起こしするには**  
次の `start-medical-transcription-job` の例は、単一のオーディオファイルから最大 2 つの代替文字起こし結果を作成します。文字起こし結果ごとに信頼度レベルが関連付けられます。デフォルトでは、Amazon Transcribe は、信頼度レベルが最も高い文字起こし結果を返します。Amazon Transcribe で他の信頼度レベルがより低いトランスクリプションを返すようにも指定できます。文字起こしの出力の場所を `OutputBucketName` パラメータで指定します。  

```
aws transcribe start-medical-transcription-job \
    --cli-input-json file://myfifthfile.json
```
`myfifthfile.json` の内容:  

```
{
    "MedicalTranscriptionJobName": "alternatives-conversation-medical-transcription-job",
    "LanguageCode": "language-code",
    "Specialty": "PRIMARYCARE",
    "Type": "CONVERSATION",
    "OutputBucketName":"amzn-s3-demo-bucket",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
    },
    "Settings":{
        "ShowAlternatives": true,
        "MaxAlternatives": 2
    }
}
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "alternatives-conversation-medical-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "StartTime": "2020-09-21T19:09:18.199000+00:00",
        "CreationTime": "2020-09-21T19:09:18.171000+00:00",
        "Settings": {
            "ShowAlternatives": true,
            "MaxAlternatives": 2
        },
        "Specialty": "PRIMARYCARE",
        "Type": "CONVERSATION"
    }
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[代替文字起こし](https://docs.aws.amazon.com/transcribe/latest/dg/how-alternatives-med.html)」を参照してください。**  
**例 6: 医療ディクテーションのオーディオファイルを、最大 2 つの代替文字起こし結果に文字起こしするには**  
次の `start-medical-transcription-job` の例は、オーディオファイルを文字起こしして、語彙フィルターを使用して不要な単語をマスクします。トランスクリプション出力の場所を OutputBucketName パラメータで指定します。  

```
aws transcribe start-medical-transcription-job \
    --cli-input-json file://mysixthfile.json
```
`mysixthfile.json` の内容:  

```
{
    "MedicalTranscriptionJobName": "alternatives-conversation-medical-transcription-job",
    "LanguageCode": "language-code",
    "Specialty": "PRIMARYCARE",
    "Type": "DICTATION",
    "OutputBucketName":"amzn-s3-demo-bucket",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
    },
    "Settings":{
          "ShowAlternatives": true,
          "MaxAlternatives": 2
    }
}
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "alternatives-dictation-medical-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "StartTime": "2020-09-21T21:01:14.592000+00:00",
        "CreationTime": "2020-09-21T21:01:14.569000+00:00",
        "Settings": {
            "ShowAlternatives": true,
            "MaxAlternatives": 2
        },
        "Specialty": "PRIMARYCARE",
        "Type": "DICTATION"
    }
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[代替文字起こし](https://docs.aws.amazon.com/transcribe/latest/dg/how-alternatives-med.html)」を参照してください。**  
**例 7: カスタムボ語彙を使用して、医療ディクテーションのオーディオファイルをより正確に書き起こすには**  
次の `start-medical-transcription-job` の例は、オーディオファイルを文字起こしして、以前に作成した医療カスタム語彙を使用して文字起こし結果の精度を高めます。文字起こしの出力の場所を `OutputBucketName` パラメータで指定します。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://myseventhfile.json
```
`mysixthfile.json` の内容:  

```
{
    "MedicalTranscriptionJobName": "vocabulary-dictation-medical-transcription-job",
    "LanguageCode": "language-code",
    "Specialty": "PRIMARYCARE",
    "Type": "DICTATION",
    "OutputBucketName":"amzn-s3-demo-bucket",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
    },
    "Settings":{
        "VocabularyName": "cli-medical-vocab-1"
    }
}
```
出力:  

```
{
    "MedicalTranscriptionJob": {
        "MedicalTranscriptionJobName": "vocabulary-dictation-medical-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.extension"
        },
        "StartTime": "2020-09-21T21:17:27.045000+00:00",
        "CreationTime": "2020-09-21T21:17:27.016000+00:00",
        "Settings": {
            "VocabularyName": "cli-medical-vocab-1"
        },
        "Specialty": "PRIMARYCARE",
        "Type": "DICTATION"
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[医療カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary-med.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartMedicalTranscriptionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/start-medical-transcription-job.html)」を参照してください。

### `start-transcription-job`
<a name="transcribe_StartTranscriptionJob_cli_2_topic"></a>

次のコード例は、`start-transcription-job` を使用する方法を示しています。

**AWS CLI**  
**例 1: オーディオファイルを文字起こしするには**  
次の `start-transcription-job` の例は、音声ファイルの文字起こしを行います。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://myfile.json
```
`myfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-simple-transcription-job",
    "LanguageCode": "the-language-of-your-transcription-job",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
    }
}
```
詳細については、*Amazon Transcribe デベロッパーガイド*[」の「開始方法 (AWS コマンドラインインターフェイス)](https://docs.aws.amazon.com/transcribe/latest/dg/getting-started-cli.html)」を参照してください。  
**例 2: マルチチャネルのオーディオファイルを文字起こしするには**  
次の `start-transcription-job` の例は、マルチチャネルのオーディオファイルの文字起こしを行います。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://mysecondfile.json
```
`mysecondfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-channelid-job",
    "LanguageCode": "the-language-of-your-transcription-job",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
    },
    "Settings":{
        "ChannelIdentification":true
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-channelid-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "the-language-of-your-transcription-job",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
        },
        "StartTime": "2020-09-17T16:07:56.817000+00:00",
        "CreationTime": "2020-09-17T16:07:56.784000+00:00",
        "Settings": {
            "ChannelIdentification": true
        }
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[マルチチャネル音声の書き起こし](https://docs.aws.amazon.com/transcribe/latest/dg/channel-id.html)」を参照してください。**  
**例 3: オーディオファイルを文字起こしして、複数の異なる話者を識別するには**  
次の `start-transcription-job` 例では、オーディオファイルを書き起こし、文字起こし出力の話者を識別します。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://mythirdfile.json
```
`mythirdfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-speakerid-job",
    "LanguageCode": "the-language-of-your-transcription-job",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
    },
    "Settings":{
    "ShowSpeakerLabels": true,
    "MaxSpeakerLabels": 2
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-speakerid-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "the-language-of-your-transcription-job",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
        },
        "StartTime": "2020-09-17T16:22:59.696000+00:00",
        "CreationTime": "2020-09-17T16:22:59.676000+00:00",
        "Settings": {
            "ShowSpeakerLabels": true,
            "MaxSpeakerLabels": 2
        }
    }
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[話者の識別](https://docs.aws.amazon.com/transcribe/latest/dg/diarization.html)」を参照してください。**  
**例 4: オーディオファイルを文字起こしして、文字起こし出力内の不要な単語をすべてマスクするには**  
次の `start-transcription-job` 例では、オーディオファイルを書き起こし、以前に作成した語彙フィルターを使用して不要な単語をマスクします。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://myfourthfile.json
```
`myfourthfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-filter-mask-job",
    "LanguageCode": "the-language-of-your-transcription-job",
    "Media": {
          "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
    },
    "Settings":{
        "VocabularyFilterName": "your-vocabulary-filter",
        "VocabularyFilterMethod": "mask"
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-filter-mask-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "the-language-of-your-transcription-job",
        "Media": {
            "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension"
        },
        "StartTime": "2020-09-18T16:36:18.568000+00:00",
        "CreationTime": "2020-09-18T16:36:18.547000+00:00",
        "Settings": {
            "VocabularyFilterName": "your-vocabulary-filter",
            "VocabularyFilterMethod": "mask"
        }
    }
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[トランスクリプションのフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/filter-transcriptions.html)」を参照してください。**  
**例 5: オーディオファイルを文字起こしし、文字起こし出力から不要な単語を削除するには**  
次の `start-transcription-job` 例では、オーディオファイルを書き起こし、以前に作成した語彙フィルターを使用して不要な単語をマスクします。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://myfifthfile.json
```
`myfifthfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-filter-remove-job",
    "LanguageCode": "the-language-of-your-transcription-job",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
    },
    "Settings":{
        "VocabularyFilterName": "your-vocabulary-filter",
        "VocabularyFilterMethod": "remove"
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-filter-remove-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "the-language-of-your-transcription-job",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
        },
        "StartTime": "2020-09-18T16:36:18.568000+00:00",
        "CreationTime": "2020-09-18T16:36:18.547000+00:00",
        "Settings": {
            "VocabularyFilterName": "your-vocabulary-filter",
            "VocabularyFilterMethod": "remove"
        }
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[トランスクリプションのフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/filter-transcriptions.html)」を参照してください。**  
**例 6: カスタム語彙を使用して、オーディオファイルをより正確に文字起こしするには**  
次の `start-transcription-job` 例では、オーディオファイルを書き起こし、以前に作成した語彙フィルターを使用して不要な単語をマスクします。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://mysixthfile.json
```
`mysixthfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-vocab-job",
    "LanguageCode": "the-language-of-your-transcription-job",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
    },
    "Settings":{
        "VocabularyName": "your-vocabulary"
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-vocab-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "the-language-of-your-transcription-job",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
        },
        "StartTime": "2020-09-18T16:36:18.568000+00:00",
        "CreationTime": "2020-09-18T16:36:18.547000+00:00",
        "Settings": {
            "VocabularyName": "your-vocabulary"
        }
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[トランスクリプションのフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/filter-transcriptions.html)」を参照してください。**  
**例 7: オーディオファイルの言語を識別して文字起こしするには**  
次の `start-transcription-job` 例では、オーディオファイルを書き起こし、以前に作成した語彙フィルターを使用して不要な単語をマスクします。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://myseventhfile.json
```
`myseventhfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-identify-language-transcription-job",
    "IdentifyLanguage": true,
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-identify-language-transcription-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/Amazon-S3-prefix/your-media-file-name.file-extension"
        },
        "StartTime": "2020-09-18T22:27:23.970000+00:00",
        "CreationTime": "2020-09-18T22:27:23.948000+00:00",
        "IdentifyLanguage": true
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[言語の特定](https://docs.aws.amazon.com/transcribe/latest/dg/auto-lang-id.html)」を参照してください。**  
**例 8: 個人を特定できる情報をマスクしてオーディオファイルを文字起こしするには**  
次の `start-transcription-job` の例は、オーディオファイルを文字起こしして、文字起こし出力内の個人を特定できる情報をマスクします。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://myeighthfile.json
```
`myeigthfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-redaction-job",
    "LanguageCode": "language-code",
    "Media": {
        "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension"
    },
    "ContentRedaction": {
        "RedactionOutput":"redacted",
        "RedactionType":"PII"
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-redaction-job",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension"
        },
        "StartTime": "2020-09-25T23:49:13.195000+00:00",
        "CreationTime": "2020-09-25T23:49:13.176000+00:00",
        "ContentRedaction": {
            "RedactionType": "PII",
            "RedactionOutput": "redacted"
        }
    }
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[コンテンツの自動マスキング](https://docs.aws.amazon.com/transcribe/latest/dg/content-redaction.html)」を参照してください。**  
**例 9: 個人を特定できる情報 (PII) をマスクしたトランスクリプトとマスクしていないトランスクリプトを生成するには**  
次の `start-transcription-job` の例は、オーディオファイルの 2 つの文字起こしを生成します。1 つでは個人を特定できる情報をマスクし、別の 1 つではマスクしません。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://myninthfile.json
```
`myninthfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-redaction-job-with-unredacted-transcript",
    "LanguageCode": "language-code",
    "Media": {
          "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension"
        },
    "ContentRedaction": {
        "RedactionOutput":"redacted_and_unredacted",
        "RedactionType":"PII"
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-redaction-job-with-unredacted-transcript",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://Amazon-S3-Prefix/your-media-file.file-extension"
        },
        "StartTime": "2020-09-25T23:59:47.677000+00:00",
        "CreationTime": "2020-09-25T23:59:47.653000+00:00",
        "ContentRedaction": {
            "RedactionType": "PII",
            "RedactionOutput": "redacted_and_unredacted"
        }
    }
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[自動コンテンツリダクション](https://docs.aws.amazon.com/transcribe/latest/dg/content-redaction.html)」を参照してください。**  
**例 10: 以前に作成したカスタム言語モデルを使用してオーディオファイルを文字起こしするには**  
次の `start-transcription-job` の例は、以前に作成したカスタム言語モデルを使用してオーディオファイルを文字起こしします。  

```
aws transcribe start-transcription-job \
    --cli-input-json file://mytenthfile.json
```
`mytenthfile.json` の内容:  

```
{
    "TranscriptionJobName": "cli-clm-2-job-1",
    "LanguageCode": "language-code",
    "Media": {
        "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.file-extension"
    },
    "ModelSettings": {
        "LanguageModelName":"cli-clm-2"
    }
}
```
出力:  

```
{
    "TranscriptionJob": {
        "TranscriptionJobName": "cli-clm-2-job-1",
        "TranscriptionJobStatus": "IN_PROGRESS",
        "LanguageCode": "language-code",
        "Media": {
            "MediaFileUri": "s3://amzn-s3-demo-bucket/your-audio-file.file-extension"
        },
        "StartTime": "2020-09-28T17:56:01.835000+00:00",
        "CreationTime": "2020-09-28T17:56:01.801000+00:00",
        "ModelSettings": {
            "LanguageModelName": "cli-clm-2"
        }
    }
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[カスタム言語モデルを使用したドメイン固有のトランスクリプション精度の向上](https://docs.aws.amazon.com/transcribe/latest/dg/custom-language-models.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartTranscriptionJob](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/start-transcription-job.html)」を参照してください。

### `update-medical-vocabulary`
<a name="transcribe_UpdateMedicalVocabulary_cli_2_topic"></a>

次のコード例は、`update-medical-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**医療用語のカスタム語彙を新しい用語で更新するには**  
次の`update-medical-vocabulary`例では、医療用語の語彙で使用される用語を新しい語彙に置き換えます。前提条件: 医療用語のカスタム語彙の用語を置き換えるには、新しい用語を含むファイルが必要です。  

```
aws transcribe update-medical-vocabulary \
    --vocabulary-file-uri s3://amzn-s3-demo-bucket/Amazon-S3-Prefix/medical-custom-vocabulary.txt \
    --vocabulary-name medical-custom-vocabulary \
    --language-code language
```
出力:  

```
{
    "VocabularyName": "medical-custom-vocabulary",
    "LanguageCode": "en-US",
    "VocabularyState": "PENDING"
}
```
詳細については、「Amazon Transcribe 開発者ガイド」の「[医療カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。**  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMedicalVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/update-medical-vocabulary.html)」を参照してください。

### `update-vocabulary-filter`
<a name="transcribe_UpdateVocabularyFilter_cli_2_topic"></a>

次のコード例は、`update-vocabulary-filter` を使用する方法を示しています。

**AWS CLI**  
**語彙フィルターの単語を置き換えるには**  
次の `update-vocabulary-filter` の例では、語彙フィルターの単語を新しい単語に置き換えます。前提条件: 語彙フィルターを新しい単語で更新するには、それらの単語をテキストファイルとして保存する必要があります。  

```
aws transcribe update-vocabulary-filter \
    --vocabulary-filter-file-uri s3://amzn-s3-demo-bucket/Amazon-S3-Prefix/your-text-file-to-update-your-vocabulary-filter.txt \
    --vocabulary-filter-name vocabulary-filter-name
```
出力:  

```
{
    "VocabularyFilterName": "vocabulary-filter-name",
    "LanguageCode": "language-code",
    "LastModifiedTime": "2020-09-23T18:40:35.139000+00:00"
}
```
詳細については、「*Amazon Transcribe 開発者ガイド*」の「[不要な単語のフィルタリング](https://docs.aws.amazon.com/transcribe/latest/dg/filter-unwanted-words.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateVocabularyFilter](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/update-vocabulary-filter.html)」を参照してください。

### `update-vocabulary`
<a name="transcribe_UpdateVocabulary_cli_2_topic"></a>

次のコード例は、`update-vocabulary` を使用する方法を示しています。

**AWS CLI**  
**カスタム語彙を新しい用語で更新するには**  
次の `update-vocabulary` の例は、カスタム語彙の作成に使用した用語を、指定した新しい用語で上書きします。前提条件: カスタム語彙の用語を置き換えるには、新しい用語を含むファイルが必要です。  

```
aws transcribe update-vocabulary \
    --vocabulary-file-uri s3://amzn-s3-demo-bucket/Amazon-S3-Prefix/custom-vocabulary.txt \
    --vocabulary-name custom-vocabulary \
    --language-code language-code
```
出力:  

```
{
    "VocabularyName": "custom-vocabulary",
    "LanguageCode": "language",
    "VocabularyState": "PENDING"
}
```
詳細については、「Amazon Transcribe デベロッパーガイド」の「[カスタムボキャブラリー](https://docs.aws.amazon.com/transcribe/latest/dg/how-vocabulary.html)」を参照してください。**  
+  API の詳細については、AWS CLI コマンドリファレンスの「[UpdateVocabulary](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/transcribe/update-vocabulary.html)」を参照してください。**

# を使用した Amazon Translate の例 AWS CLI
<a name="cli_2_translate_code_examples"></a>

次のコード例は、Amazon Translate AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `import-terminology`
<a name="translate_ImportTerminology_cli_2_topic"></a>

次のコード例は、`import-terminology` を使用する方法を示しています。

**AWS CLI**  
**ファイルからカスタム用語をインポートするには**  
次の `import-terminology` の例では、 `test-terminology.csv` ファイルから `MyTestTerminology` という用語を作成します。  

```
aws translate import-terminology \
    --name MyTestTerminology \
    --description "Creating a test terminology in AWS Translate" \
    --merge-strategy OVERWRITE \
    --data-file fileb://test-terminology.csv \
    --terminology-data Format=CSV
```
`test-terminology.csv` の内容:  
en,fr,es,zh Hello world\$1,Bonjour tout le monde\$1,Hola Mundo\$1,???? Amazon,Amazon,Amazon,Amazon  
出力:  

```
{
    "TerminologyProperties": {
        "SourceLanguageCode": "en",
        "Name": "MyTestTerminology",
        "TargetLanguageCodes": [
            "fr",
            "es",
            "zh"
        ],
        "SizeBytes": 97,
        "LastUpdatedAt": 1571089500.851,
        "CreatedAt": 1571089500.851,
        "TermCount": 6,
        "Arn": "arn:aws:translate:us-west-2:123456789012:terminology/MyTestTerminology/LATEST",
        "Description": "Creating a test terminology in AWS Translate"
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ImportTerminology](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/translate/import-terminology.html)」を参照してください。

# Trusted Advisor を使用した の例 AWS CLI
<a name="cli_2_trustedadvisor_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています Trusted Advisor。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-organization-recommendation`
<a name="trustedadvisor_GetOrganizationRecommendation_cli_2_topic"></a>

次のコード例は、`get-organization-recommendation` を使用する方法を示しています。

**AWS CLI**  
**組織のレコメンデーションを取得するには**  
次の `get-organization-recommendation` の例では、組織のレコメンデーションを識別子で取得します。  

```
aws trustedadvisor get-organization-recommendation \
    --organization-recommendation-identifier arn:aws:trustedadvisor:::organization-recommendation/9534ec9b-bf3a-44e8-8213-2ed68b39d9d5
```
出力:  

```
{
    "organizationRecommendation": {
        "arn": "arn:aws:trustedadvisor:::organization-recommendation/9534ec9b-bf3a-44e8-8213-2ed68b39d9d5",
        "name": "Lambda Runtime Deprecation Warning",
        "description": "One or more lambdas are using a deprecated runtime",
        "awsServices": [
            "lambda"
        ],
        "checkArn": "arn:aws:trustedadvisor:::check/L4dfs2Q4C5",
        "id": "9534ec9b-bf3a-44e8-8213-2ed68b39d9d5",
        "lifecycleStage": "resolved",
        "pillars": [
            "security"
        ],
        "resourcesAggregates": {
            "errorCount": 0,
            "okCount": 0,
            "warningCount": 0
        },
        "source": "ta_check",
        "status": "warning",
        "type": "priority"
    }
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetOrganizationRecommendation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/get-organization-recommendation.html)」を参照してください。

### `get-recommendation`
<a name="trustedadvisor_GetRecommendation_cli_2_topic"></a>

次のコード例は、`get-recommendation` を使用する方法を示しています。

**AWS CLI**  
**レコメンデーションを取得するには**  
次の `get-recommendation` の例では、レコメンデーションを識別子で取得します。  

```
aws trustedadvisor get-recommendation \
    --recommendation-identifier arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578
```
出力:  

```
{
    "recommendation": {
        "arn": "arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578",
        "name": "MFA Recommendation",
        "description": "Enable multi-factor authentication",
        "awsServices": [
            "iam"
        ],
        "checkArn": "arn:aws:trustedadvisor:::check/7DAFEmoDos",
        "id": "55fa4d2e-bbb7-491a-833b-5773e9589578",
        "lastUpdatedAt": "2023-11-01T15:57:58.673Z",
        "pillarSpecificAggregates": {
            "costOptimizing": {
                "estimatedMonthlySavings": 0.0,
                "estimatedPercentMonthlySavings": 0.0
            }
        },
        "pillars": [
            "security"
        ],
        "resourcesAggregates": {
            "errorCount": 1,
            "okCount": 0,
            "warningCount": 0
        },
        "source": "ta_check",
        "status": "error",
        "type": "standard"
    }
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRecommendation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/get-recommendation.html)」を参照してください。

### `list-checks`
<a name="trustedadvisor_ListChecks_cli_2_topic"></a>

次のコード例は、`list-checks` を使用する方法を示しています。

**AWS CLI**  
**Trusted Advisor チェックを一覧表示するには**  
次の `list-checks` の例では、すべての Trusted Advisor チェックを一覧表示します。  

```
aws trustedadvisor list-checks
```
出力:  

```
{
    "checkSummaries": [
        {
            "arn": "arn:aws:trustedadvisor:::check/1iG5NDGVre",
            "awsServices": [
                "EC2"
            ],
            "description": "Checks security groups for rules that allow unrestricted access to a resource. Unrestricted access increases opportunities for malicious activity (hacking, denial-of-service attacks, loss of data)",
            "id": "1iG5NDGVre",
            "metadata": {
                "0": "Region",
                "1": "Security Group Name",
                "2": "Security Group ID",
                "3": "Protocol",
                "4": "Port",
                "5": "Status",
                "6": "IP Range"
            },
            "name": "Security Groups - Unrestricted Access",
            "pillars": [
                "security"
            ],
            "source": "ta_check"
        },
        {
            "arn": "arn:aws:trustedadvisor:::check/1qazXsw23e",
            "awsServices": [
                "RDS"
            ],
            "description": "Checks your usage of RDS and provides recommendations on purchase of Reserved Instances to help reduce costs incurred from using RDS On-Demand. AWS generates these recommendations by analyzing your On-Demand usage for the past 30 days. We then simulate every combination of reservations in the generated category of usage in order to identify the best number of each type of Reserved Instance to purchase to maximize your savings. This check covers recommendations based on partial upfront payment option with 1-year or 3-year commitment. This check is not available to accounts linked in Consolidated Billing. Recommendations are only available for the Paying Account.",
            "id": "1qazXsw23e",
            "metadata": {
                "0": "Region",
                "1": "Family",
                "2": "Instance Type",
                "3": "License Model",
                "4": "Database Edition",
                "5": "Database Engine",
                "6": "Deployment Option",
                "7": "Recommended number of Reserved Instances to purchase",
                "8": "Expected Average Reserved Instance Utilization",
                "9": "Estimated Savings with Recommendation (monthly)"
                "10": "Upfront Cost of Reserved Instances",
                "11": "Estimated cost of Reserved Instances (monthly)",
                "12": "Estimated On-Demand Cost Post Recommended Reserved Instance Purchase (monthly)",
                "13": "Estimated Break Even (months)",
                "14": "Lookback Period (days)",
                "15": "Term (years)"
            },
            "name": "Amazon Relational Database Service (RDS) Reserved Instance Optimization",
            "pillars": [
                "cost_optimizing"
            ],
            "source": "ta_check"
        },
        {
            "arn": "arn:aws:trustedadvisor:::check/1qw23er45t",
            "awsServices": [
                "Redshift"
            ],
            "description": "Checks your usage of Redshift and provides recommendations on purchase of Reserved Nodes to help reduce costs incurred from using Redshift On-Demand. AWS generates these recommendations by analyzing your On-Demand usage for the past 30 days. We then simulate every combination of reservations in the generated category of usage in order to identify the best number of each type of Reserved Nodes to purchase to maximize your savings. This check covers recommendations based on partial upfront payment option with 1-year or 3-year commitment. This check is not available to accounts linked in Consolidated Billing. Recommendations are only available for the Paying Account.",
            "id": "1qw23er45t",
            "metadata": {
                "0": "Region",
                "1": "Family",
                "2": "Node Type",
                "3": "Recommended number of Reserved Nodes to purchase",
                "4": "Expected Average Reserved Node Utilization",
                "5": "Estimated Savings with Recommendation (monthly)",
                "6": "Upfront Cost of Reserved Nodes",
                "7": "Estimated cost of Reserved Nodes (monthly)",
                "8": "Estimated On-Demand Cost Post Recommended Reserved Nodes Purchase (monthly)",
                "9": "Estimated Break Even (months)",
                "10": "Lookback Period (days)",
                "11": "Term (years)",
            },
            "name": "Amazon Redshift Reserved Node Optimization",
            "pillars": [
                "cost_optimizing"
            ],
            "source": "ta_check"
        },
    ],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListChecks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/list-checks.html)」を参照してください。

### `list-organization-recommendation-accounts`
<a name="trustedadvisor_ListOrganizationRecommendationAccounts_cli_2_topic"></a>

次のコード例は、`list-organization-recommendation-accounts` を使用する方法を示しています。

**AWS CLI**  
**組織のレコメンデーションアカウントを一覧表示するには**  
次の `list-organization-recommendation-accounts` の例では、組織のレコメンデーションのすべてのアカウントレコメンデーションの概要を識別子別に一覧表示します。  

```
aws trustedadvisor list-organization-recommendation-accounts \
    --organization-recommendation-identifier arn:aws:trustedadvisor:::organization-recommendation/9534ec9b-bf3a-44e8-8213-2ed68b39d9d5
```
出力:  

```
{
    "accountRecommendationLifecycleSummaries": [{
        "accountId": "000000000000",
        "accountRecommendationArn": "arn:aws:trustedadvisor::000000000000:recommendation/9534ec9b-bf3a-44e8-8213-2ed68b39d9d5",
        "lifecycleStage": "resolved",
        "updateReason": "Resolved issue",
        "updateReasonCode": "valid_business_case",
        "lastUpdatedAt": "2023-01-17T18:25:44.552Z"
    }],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOrganizationRecommendationAccounts](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/list-organization-recommendation-accounts.html)」を参照してください。

### `list-organization-recommendation-resources`
<a name="trustedadvisor_ListOrganizationRecommendationResources_cli_2_topic"></a>

次のコード例は、`list-organization-recommendation-resources` を使用する方法を示しています。

**AWS CLI**  
**組織のレコメンデーションリソースを一覧表示するには**  
次の `list-organization-recommendation-resources` の例では、組織のレコメンデーションのすべてのリソースを識別子別に一覧表示します。  

```
aws trustedadvisor list-organization-recommendation-resources \
    --organization-recommendation-identifier arn:aws:trustedadvisor:::organization-recommendation/5a694939-2e54-45a2-ae72-730598fa89d0
```
出力:  

```
{
    "organizationRecommendationResourceSummaries": [
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation-resource/5a694939-2e54-45a2-ae72-730598fa89d0/bb38affc0ce0681d9a6cd13f30238ba03a8f63dfe7a379dc403c619119d86af",
            "awsResourceId": "database-1-instance-1",
            "id": "bb38affc0ce0681d9a6cd13f302383ba03a8f63dfe7a379dc403c619119d86af",
            "lastUpdatedAt": "2023-11-01T15:09:51.891Z",
            "metadata": {
                "0": "14",
                "1": "208.79999999999998",
                "2": "database-1-instance-1",
                "3": "db.r5.large",
                "4": "false",
                "5": "us-west-2",
                "6": "arn:aws:rds:us-west-2:000000000000:db:database-1-instance-1",
                "7": "1"
            },
            "recommendationArn": "arn:aws:trustedadvisor:::organization-recommendation/5a694939-2e54-45a2-ae72-730598fa89d0",
            "regionCode": "us-west-2",
            "status": "warning"
        },
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation-resource/5a694939-2e54-45a2-ae72-730598fa89d0/51fded4d7a3278818df9cfe344ff5762cec46c095a6763d1ba1ba53bd0e1b0e6",
            "awsResourceId": "database-1",
            "id": "51fded4d7a3278818df9cfe344ff5762cec46c095a6763d1ba1ba53bd0e1b0e6",
            "lastUpdatedAt": "2023-11-01T15:09:51.891Z",
            "metadata": {
                "0": "14",
                "1": "31.679999999999996",
                "2": "database-1",
                "3": "db.t3.small",
                "4": "false",
                "5": "us-west-2",
                "6": "arn:aws:rds:us-west-2:000000000000:db:database-1",
                "7": "20"
            },
            "recommendationArn": "arn:aws:trustedadvisor:::organization-recommendation/5a694939-2e54-45a2-ae72-730598fa89d0",
            "regionCode": "us-west-2",
            "status": "warning"
        },
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation-resource/5a694939-2e54-45a2-ae72-730598fa89d0/f4d01bd20f4cd5372062aafc8786c489e48f0ead7cdab121463bf9f89e40a36b",
            "awsResourceId": "database-2-instance-1-us-west-2a",
            "id": "f4d01bd20f4cd5372062aafc8786c489e48f0ead7cdab121463bf9f89e40a36b",
            "lastUpdatedAt": "2023-11-01T15:09:51.891Z",
            "metadata": {
                "0": "14",
                "1": "187.20000000000002",
                "2": "database-2-instance-1-us-west-2a",
                "3": "db.r6g.large",
                "4": "true",
                "5": "us-west-2",
                "6": "arn:aws:rds:us-west-2:000000000000:db:database-2-instance-1-us-west-2a",
                "7": "1"
            },
            "recommendationArn": "arn:aws:trustedadvisor:::organization-recommendation/5a694939-2e54-45a2-ae72-730598fa89d0",
            "regionCode": "us-west-2",
            "status": "warning"
        },
    ],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOrganizationRecommendationResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/list-organization-recommendation-resources.html)」を参照してください。

### `list-organization-recommendations`
<a name="trustedadvisor_ListOrganizationRecommendations_cli_2_topic"></a>

次のコード例は、`list-organization-recommendations` を使用する方法を示しています。

**AWS CLI**  
**例 1: 組織のレコメンデーションを一覧表示するには**  
次の `list-organization-recommendations` の例では、すべての組織のレコメンデーションを一覧表示し、フィルターは含まれません。  

```
aws trustedadvisor list-organization-recommendations
```
出力:  

```
{
    "organizationRecommendationSummaries": [
        {
            "arn": "arn:aws:trustedadvisor:::organization-recommendation/9534ec9b-bf3a-44e8-8213-2ed68b39d9d5",
            "name": "Lambda Runtime Deprecation Warning",
            "awsServices": [
                "lambda"
            ],
            "checkArn": "arn:aws:trustedadvisor:::check/L4dfs2Q4C5",
            "id": "9534ec9b-bf3a-44e8-8213-2ed68b39d9d5",
            "lifecycleStage": "resolved",
            "pillars": [
                "security"
            ],
            "resourcesAggregates": {
                "errorCount": 0,
                "okCount": 0,
                "warningCount": 0
            },
            "source": "ta_check",
            "status": "warning",
            "type": "priority"
        },
        {
            "arn": "arn:aws:trustedadvisor:::organization-recommendation/4ecff4d4-1bc1-4c99-a5b8-0fff9ee500d6",
            "name": "Lambda Runtime Deprecation Warning",
            "awsServices": [
                "lambda"
            ],
            "checkArn": "arn:aws:trustedadvisor:::check/L4dfs2Q4C5",
            "id": "4ecff4d4-1bc1-4c99-a5b8-0fff9ee500d6",
            "lifecycleStage": "resolved",
            "pillars": [
                "security"
            ],
            "resourcesAggregates": {
                "errorCount": 0,
                "okCount": 0,
                "warningCount": 0
            },
            "source": "ta_check",
            "status": "warning",
            "type": "priority"
        },
    ],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
**例 2: フィルターを使用して組織のレコメンデーションを一覧表示するには**  
次の `list-organization-recommendations` の例では、「セキュリティ」の柱の一部である 1 つの組織レコメンデーションの最大数をフィルタリングして返します。  

```
aws trustedadvisor list-organization-recommendations \
    --pillar security \
    --max-items 100
```
出力:  

```
{
    "organizationRecommendationSummaries": [{
        "arn": "arn:aws:trustedadvisor:::organization-recommendation/9534ec9b-bf3a-44e8-8213-2ed68b39d9d5",
        "name": "Lambda Runtime Deprecation Warning",
        "awsServices": [
            "lambda"
        ],
        "checkArn": "arn:aws:trustedadvisor:::check/L4dfs2Q4C5",
        "id": "9534ec9b-bf3a-44e8-8213-2ed68b39d9d5",
        "lifecycleStage": "resolved",
        "pillars": [
            "security"
        ],
        "resourcesAggregates": {
            "errorCount": 0,
            "okCount": 0,
            "warningCount": 0
        },
        "source": "ta_check",
        "status": "warning",
        "type": "priority"
    }],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
**例 3: ページ分割トークンを使用して組織のレコメンデーションを一覧表示するには**  
次の `list-organization-recommendations` の例では、前のリクエストから返された「nextToken」を使用して、組織のレコメンデーションの次のページを取得します。  

```
aws trustedadvisor list-organization-recommendations \
    --pillar security \
    --max-items 100 \
    --starting-token <next-token>
```
出力:  

```
{
    "organizationRecommendationSummaries": [{
        "arn": "arn:aws:trustedadvisor:::organization-recommendation/4ecff4d4-1bc1-4c99-a5b8-0fff9ee500d6",
        "name": "Lambda Runtime Deprecation Warning",
        "awsServices": [
            "lambda"
        ],
        "checkArn": "arn:aws:trustedadvisor:::check/L4dfs2Q4C5",
        "id": "4ecff4d4-1bc1-4c99-a5b8-0fff9ee500d6",
        "lifecycleStage": "resolved",
        "pillars": [
            "security"
        ],
        "resourcesAggregates": {
            "errorCount": 0,
            "okCount": 0,
            "warningCount": 0
        },
        "source": "ta_check",
        "status": "warning",
        "type": "priority"
    }]
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOrganizationRecommendations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/list-organization-recommendations.html)」を参照してください。

### `list-recommendation-resources`
<a name="trustedadvisor_ListRecommendationResources_cli_2_topic"></a>

次のコード例は、`list-recommendation-resources` を使用する方法を示しています。

**AWS CLI**  
**レコメンデーションリソースを一覧表示するには**  
次の `list-recommendation-resources` の例では、レコメンデーションのすべてのリソースを識別子別に一覧表示します。  

```
aws trustedadvisor list-recommendation-resources \
    --recommendation-identifier arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578
```
出力:  

```
{
    "recommendationResourceSummaries": [
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation-resource/55fa4d2e-bbb7-491a-833b-5773e9589578/18959a1f1973cff8e706e9d9bde28bba36cd602a6b2cb86c8b61252835236010",
            "id": "18959a1f1973cff8e706e9d9bde28bba36cd602a6b2cb86c8b61252835236010",
            "awsResourceId": "webcms-dev-01",
            "lastUpdatedAt": "2023-11-01T15:09:51.891Z",
            "metadata": {
                "0": "14",
                "1": "123.12000000000002",
                "2": "webcms-dev-01",
                "3": "db.m6i.large",
                "4": "false",
                "5": "us-east-1",
                "6": "arn:aws:rds:us-east-1:000000000000:db:webcms-dev-01",
                "7": "20"
            },
            "recommendationArn": "arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578",
            "regionCode": "us-east-1",
            "status": "warning"
        },
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation-resource/55fa4d2e-bbb7-491a-833b-5773e9589578/e6367ff500ac90db8e4adeb4892e39ee9c36bbf812dcbce4b9e4fefcec9eb63e",
            "id": "e6367ff500ac90db8e4adeb4892e39ee9c36bbf812dcbce4b9e4fefcec9eb63e",
            "awsResourceId": "aws-dev-db-stack-instance-1",
            "lastUpdatedAt": "2023-11-01T15:09:51.891Z",
            "metadata": {
                "0": "14",
                "1": "29.52",
                "2": "aws-dev-db-stack-instance-1",
                "3": "db.t2.small",
                "4": "false",
                "5": "us-east-1",
                "6": "arn:aws:rds:us-east-1:000000000000:db:aws-dev-db-stack-instance-1",
                "7": "1"
            },
            "recommendationArn": "arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578",
            "regionCode": "us-east-1",
            "status": "warning"
        },
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation-resource/55fa4d2e-bbb7-491a-833b-5773e9589578/31aa78ba050a5015d2d38cca7f5f1ce88f70857c4e1c3ad03f8f9fd95dad7459",
            "id": "31aa78ba050a5015d2d38cca7f5f1ce88f70857c4e1c3ad03f8f9fd95dad7459",
            "awsResourceId": "aws-awesome-apps-stack-db",
            "lastUpdatedAt": "2023-11-01T15:09:51.891Z",
            "metadata": {
                "0": "14",
                "1": "114.48000000000002",
                "2": "aws-awesome-apps-stack-db",
                "3": "db.m6g.large",
                "4": "false",
                "5": "us-east-1",
                "6": "arn:aws:rds:us-east-1:000000000000:db:aws-awesome-apps-stack-db",
                "7": "100"
            },
            "recommendationArn": "arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578",
            "regionCode": "us-east-1",
            "status": "warning"
        }
    ],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRecommendationResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/list-recommendation-resources.html)」を参照してください。

### `list-recommendations`
<a name="trustedadvisor_ListRecommendations_cli_2_topic"></a>

次のコード例は、`list-recommendations` を使用する方法を示しています。

**AWS CLI**  
**例 1: レコメンデーションを一覧表示するには**  
次の `list-recommendations` の例では、すべてのレコメンデーションを一覧表示し、フィルターは含まれません。  

```
aws trustedadvisor list-recommendations
```
出力:  

```
{
    "recommendationSummaries": [
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578",
            "name": "MFA Recommendation",
            "awsServices": [
                "iam"
            ],
            "checkArn": "arn:aws:trustedadvisor:::check/7DAFEmoDos",
            "id": "55fa4d2e-bbb7-491a-833b-5773e9589578",
            "lastUpdatedAt": "2023-11-01T15:57:58.673Z",
            "pillarSpecificAggregates": {
                "costOptimizing": {
                    "estimatedMonthlySavings": 0.0,
                    "estimatedPercentMonthlySavings": 0.0
                }
            },
            "pillars": [
                "security"
            ],
            "resourcesAggregates": {
                "errorCount": 1,
                "okCount": 0,
                "warningCount": 0
            },
            "source": "ta_check",
            "status": "error",
            "type": "standard"
        },
        {
            "arn": "arn:aws:trustedadvisor::000000000000:recommendation/8b602b6f-452d-4cb2-8a9e-c7650955d9cd",
            "name": "RDS clusters quota warning",
            "awsServices": [
                "rds"
            ],
            "checkArn": "arn:aws:trustedadvisor:::check/gjqMBn6pjz",
            "id": "8b602b6f-452d-4cb2-8a9e-c7650955d9cd",
            "lastUpdatedAt": "2023-11-01T15:58:17.397Z",
            "pillarSpecificAggregates": {
                "costOptimizing": {
                    "estimatedMonthlySavings": 0.0,
                    "estimatedPercentMonthlySavings": 0.0
                }
            },
            "pillars": [
                "service_limits"
            ],
            "resourcesAggregates": {
                "errorCount": 0,
                "okCount": 3,
                "warningCount": 6
            },
            "source": "ta_check",
            "status": "warning",
            "type": "standard"
        }
    ],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
**例 2: フィルターを使用してレコメンデーションを一覧表示するには**  
次の `list-recommendations` の例では、レコメンデーションを一覧表示し、フィルターが含まれています。  

```
aws trustedadvisor list-recommendations \
    --aws-service iam \
    --max-items 100
```
出力:  

```
{
    "recommendationSummaries": [{
        "arn": "arn:aws:trustedadvisor::000000000000:recommendation/55fa4d2e-bbb7-491a-833b-5773e9589578",
        "name": "MFA Recommendation",
        "awsServices": [
            "iam"
        ],
        "checkArn": "arn:aws:trustedadvisor:::check/7DAFEmoDos",
        "id": "55fa4d2e-bbb7-491a-833b-5773e9589578",
        "lastUpdatedAt": "2023-11-01T15:57:58.673Z",
        "pillarSpecificAggregates": {
            "costOptimizing": {
                "estimatedMonthlySavings": 0.0,
                "estimatedPercentMonthlySavings": 0.0
            }
        },
        "pillars": [
            "security"
        ],
        "resourcesAggregates": {
            "errorCount": 1,
            "okCount": 0,
            "warningCount": 0
        },
        "source": "ta_check",
        "status": "error",
        "type": "standard"
    }],
    "nextToken": "REDACTED"
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
**例 3: ページ分割トークンを使用してレコメンデーションを一覧表示するには**  
次の `list-recommendations` の例では、前のリクエストから返された「nextToken」を使用して、フィルタリングされたレコメンデーションの次のページを取得します。  

```
aws trustedadvisor list-recommendations \
    --aws-service rds \
    --max-items 100 \
    --starting-token <next-token>
```
出力:  

```
{
    "recommendationSummaries": [{
        "arn": "arn:aws:trustedadvisor::000000000000:recommendation/8b602b6f-452d-4cb2-8a9e-c7650955d9cd",
        "name": "RDS clusters quota warning",
        "awsServices": [
            "rds"
        ],
        "checkArn": "arn:aws:trustedadvisor:::check/gjqMBn6pjz",
        "id": "8b602b6f-452d-4cb2-8a9e-c7650955d9cd",
        "lastUpdatedAt": "2023-11-01T15:58:17.397Z",
        "pillarSpecificAggregates": {
            "costOptimizing": {
                "estimatedMonthlySavings": 0.0,
                "estimatedPercentMonthlySavings": 0.0
            }
        },
        "pillars": [
            "service_limits"
        ],
        "resourcesAggregates": {
            "errorCount": 0,
            "okCount": 3,
            "warningCount": 6
        },
        "source": "ta_check",
        "status": "warning",
        "type": "standard"
    }]
}
```
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRecommendations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/list-recommendations.html)」を参照してください。

### `update-organization-recommendation-lifecycle`
<a name="trustedadvisor_UpdateOrganizationRecommendationLifecycle_cli_2_topic"></a>

次のコード例は、`update-organization-recommendation-lifecycle` を使用する方法を示しています。

**AWS CLI**  
**組織のレコメンデーションライフサイクルを更新するには**  
次の `update-organization-recommendation-lifecycle` の例では、組織のレコメンデーションのライフサイクルを識別子で更新します。  

```
aws trustedadvisor update-organization-recommendation-lifecycle \
    --organization-recommendation-identifier arn:aws:trustedadvisor:::organization-recommendation/96b5e5ca-7930-444c-90c6-06d386128100 \
    --lifecycle-stage dismissed \
    --update-reason-code not_applicable
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateOrganizationRecommendationLifecycle](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/update-organization-recommendation-lifecycle.html)」を参照してください。

### `update-recommendation-lifecycle`
<a name="trustedadvisor_UpdateRecommendationLifecycle_cli_2_topic"></a>

次のコード例は、`update-recommendation-lifecycle` を使用する方法を示しています。

**AWS CLI**  
**レコメンデーションライフサイクルを更新するには**  
次の `update-recommendation-lifecycle` の例では、レコメンデーションのライフサイクルを識別子で更新します。  

```
aws trustedadvisor update-recommendation-lifecycle \
    --recommendation-identifier arn:aws:trustedadvisor::000000000000:recommendation/861c9c6e-f169-405a-8b59-537a8caccd7a \
    --lifecycle-stage resolved \
    --update-reason-code valid_business_case
```
このコマンドでは何も出力されません。  
詳細については、「*AWS Trusted Advisor ユーザーガイド*」の「[Trusted Advisor API の使用を開始する](https://docs.aws.amazon.com/awssupport/latest/user/get-started-with-aws-trusted-advisor-api.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRecommendationLifecycle](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/trustedadvisor/update-recommendation-lifecycle.html)」を参照してください。

# を使用した Verified Permissions の例 AWS CLI
<a name="cli_2_verifiedpermissions_code_examples"></a>

次のコード例は、Verified Permissions AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-identity-source`
<a name="verifiedpermissions_CreateIdentitySource_cli_2_topic"></a>

次のコード例は、`create-identity-source` を使用する方法を示しています。

**AWS CLI**  
**ID ソースを作成するには**  
次の `create-identity-source` の例では、指定された Amazon Cognito ユーザープールに保存されているアイデンティティを参照できる ID ソースを作成します。これらのアイデンティティは、Verified Permissions でタイプ `User` のエンティティとして使用できます。  

```
aws verifiedpermissions create-identity-source \
    --configuration file://config.txt \
    --principal-entity-type "User" \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`config.txt` の内容:  

```
{
    "cognitoUserPoolConfiguration": {
        "userPoolArn": "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_1a2b3c4d5",
        "clientIds":["a1b2c3d4e5f6g7h8i9j0kalbmc"]
    }
}
```
出力:  

```
{
    "createdDate": "2023-05-19T20:30:28.214829+00:00",
    "identitySourceId": "ISEXAMPLEabcdefg111111",
    "lastUpdatedDate": "2023-05-19T20:30:28.214829+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111"
}
```
詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/identity-providers.html)」の「*ID プロバイダでの Amazon Verified Permissions の使用*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIdentitySource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/create-identity-source.html)」を参照してください。

### `create-policy-store`
<a name="verifiedpermissions_CreatePolicyStore_cli_2_topic"></a>

次のコード例は、`create-policy-store` を使用する方法を示しています。

**AWS CLI**  
**ポリシーストアを作成するには**  
次の の`create-policy-store`例では、現在の AWS リージョンにポリシーストアを作成します。  

```
aws verifiedpermissions create-policy-store \
    --validation-settings "mode=STRICT"
```
出力:  

```
{
    "arn": "arn:aws:verifiedpermissions::123456789012:policy-store/PSEXAMPLEabcdefg111111",
    "createdDate": "2023-05-16T17:41:29.103459+00:00",
    "lastUpdatedDate": "2023-05-16T17:41:29.103459+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111"
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーストア](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/create-policy-store.html)」を参照してください。

### `create-policy-template`
<a name="verifiedpermissions_CreatePolicyTemplate_cli_2_topic"></a>

次のコード例は、`create-policy-template` を使用する方法を示しています。

**AWS CLI**  
**ポリシーテンプレートを作成するには**  
次の `create-policy-template` の例では、プリンシパルのプレースホルダーを含むステートメント付きのポリシーテンプレートを作成します。  

```
aws verifiedpermissions create-policy-template \
    --statement file://template1.txt \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`template1.txt` の内容:  

```
permit(
    principal in ?principal,
    action == Action::"view",
    resource == Photo::"VacationPhoto94.jpg"
);
```
出力:  

```
{
    "createdDate": "2023-06-12T20:47:42.804511+00:00",
    "lastUpdatedDate": "2023-06-12T20:47:42.804511+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "policyTemplateId": "PTEXAMPLEabcdefg111111"
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーテンプレート](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicyTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/create-policy-template.html)」を参照してください。

### `create-policy`
<a name="verifiedpermissions_CreatePolicy_cli_2_topic"></a>

次のコード例は、`create-policy` を使用する方法を示しています。

**AWS CLI**  
**例 1: 静的ポリシーを作成するには**  
次の `create-policy` の例では、プリンシパルとリソースの両方を指定するポリシースコープを持つ静的ポリシーを作成します。  

```
aws verifiedpermissions create-policy \
    --definition file://definition1.txt \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`definition1.txt` ファイルの内容。  

```
{
    "static": {
        "description":  "Grant everyone of janeFriends UserGroup access to the vacationFolder Album",
        "statement": "permit(principal in UserGroup::\"janeFriends\", action, resource in Album::\"vacationFolder\" );"
    }
}
```
出力:  

```
{
    "createdDate": "2023-06-12T20:33:37.382907+00:00",
    "lastUpdatedDate": "2023-06-12T20:33:37.382907+00:00",
    "policyId": "SPEXAMPLEabcdefg111111",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "policyType": "STATIC",
    "principal": {
        "entityId": "janeFriends",
        "entityType": "UserGroup"
    },
    "resource": {
        "entityId": "vacationFolder",
        "entityType": "Album"
    }
}
```
**例 2: リソースへのアクセスを全員に許可する静的ポリシーを作成するには**  
次の `create-policy` の例では、リソースのみを指定するポリシースコープを持つ静的ポリシーを作成します。  

```
aws verifiedpermissions create-policy \
    --definition file://definition2.txt \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`definition2.txt` ファイルの内容。  

```
{
    "static": {
        "description":  "Grant everyone access to the publicFolder Album",
        "statement": "permit(principal, action, resource in Album::\"publicFolder\");"
    }
}
```
出力:  

```
{
    "createdDate": "2023-06-12T20:39:44.975897+00:00",
    "lastUpdatedDate": "2023-06-12T20:39:44.975897+00:00",
    "policyId": "PbfR73F8oh5MMfr9uRtFDB",
    "policyStoreId": "PSEXAMPLEabcdefg222222",
    "policyType": "STATIC",
    "resource": {
        "entityId": "publicFolder",
        "entityType": "Album"
    }
}
```
**例 3: 指定されたテンプレートに関連付けられているテンプレートにリンクされたポリシーを作成するには**  
次の `create-policy` の例では、指定されたポリシーテンプレートを使用してテンプレートリンクポリシーを作成し、使用する指定されたプリンシパルを新しいテンプレートリンクポリシーに関連付けます。  

```
aws verifiedpermissions create-policy \
    --definition file://definition.txt \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`definition.txt` の内容:  

```
{
    "templateLinked": {
        "policyTemplateId": "PTEXAMPLEabcdefg111111",
        "principal": {
            "entityType": "User",
            "entityId": "alice"
        }
    }
}
```
出力:  

```
{
    "createdDate": "2023-06-12T20:49:51.490211+00:00",
    "lastUpdatedDate": "2023-06-12T20:49:51.490211+00:00",
    "policyId": "TPEXAMPLEabcdefg111111",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "policyType": "TEMPLATE_LINKED",
    "principal": {
        "entityId": "alice",
        "entityType": "User"
    },
    "resource": {
        "entityId": "VacationPhoto94.jpg",
        "entityType": "Photo"
    }
}
```
ポリシーに関する詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policies.html)」の「*Amazon Verified Permissions のポリシー*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/create-policy.html)」を参照してください。

### `delete-identity-source`
<a name="verifiedpermissions_DeleteIdentitySource_cli_2_topic"></a>

次のコード例は、`delete-identity-source` を使用する方法を示しています。

**AWS CLI**  
**ID ソースを削除するには**  
次の `delete-identity-source` の例では、指定された ID を持つ ID ソースを削除します。  

```
aws verifiedpermissions delete-identity-source \
    --identity-source-id ISEXAMPLEabcdefg111111 \
    --policy-store-id PSEXAMPLEabcdefg111111
```
このコマンドでは何も出力されません。  
詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/identity-providers.html)」の「*ID プロバイダでの Amazon Verified Permissions の使用*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIdentitySource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/delete-identity-source.html)」を参照してください。

### `delete-policy-store`
<a name="verifiedpermissions_DeletePolicyStore_cli_2_topic"></a>

次のコード例は、`delete-policy-store` を使用する方法を示しています。

**AWS CLI**  
**ポリシーストアを削除するには**  
次の `delete-policy-store` の例では、指定された ID を持つ名前付きポリシーストアを削除します。  

```
aws verifiedpermissions delete-policy-store \
    --policy-store-id PSEXAMPLEabcdefg111111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーストア](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/delete-policy-store.html)」を参照してください。

### `delete-policy-template`
<a name="verifiedpermissions_DeletePolicyTemplate_cli_2_topic"></a>

次のコード例は、`delete-policy-template` を使用する方法を示しています。

**AWS CLI**  
**ポリシーテンプレートを削除するには**  
次の `delete-policy-template` の例では、指定された ID を持つ名前付きポリシーテンプレートを削除します。  

```
aws verifiedpermissions delete-policy \
    --policy-template-id PTEXAMPLEabcdefg111111 \
    --policy-store-id PSEXAMPLEabcdefg111111
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーテンプレート](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicyTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/delete-policy-template.html)」を参照してください。

### `delete-policy`
<a name="verifiedpermissions_DeletePolicy_cli_2_topic"></a>

次のコード例は、`delete-policy` を使用する方法を示しています。

**AWS CLI**  
**静的ポリシーまたはテンプレートにリンクされたポリシーを削除するには**  
次の `delete-policy` の例では、指定された ID を持つポリシーを削除します。  

```
aws verifiedpermissions delete-policy \
    --policy-id SPEXAMPLEabcdefg111111 \
    --policy-store-id PSEXAMPLEabcdefg111111
```
このコマンドでは何も出力されません。  
ポリシーに関する詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policies.html)」の「*Amazon Verified Permissions のポリシー*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeletePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/delete-policy.html)」を参照してください。

### `get-identity-source`
<a name="verifiedpermissions_GetIdentitySource_cli_2_topic"></a>

次のコード例は、`get-identity-source` を使用する方法を示しています。

**AWS CLI**  
**ID ソースの詳細を取得するには**  
次の`get-identity-source`例では、指定された ID を持つ ID ソースの詳細を表示します。  

```
aws verifiedpermissions get-identity-source \
    --identity-source  ISEXAMPLEabcdefg111111 \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "createdDate": "2023-06-12T22:27:49.150035+00:00",
    "details": {
        "clientIds": [ "a1b2c3d4e5f6g7h8i9j0kalbmc" ],
        "discoveryUrl": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_1a2b3c4d5",
        "openIdIssuer": "COGNITO",
        "userPoolArn": "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_1a2b3c4d5"
    },
    "identitySourceId": "ISEXAMPLEabcdefg111111",
    "lastUpdatedDate": "2023-06-12T22:27:49.150035+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "principalEntityType": "User"
}
```
詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/identity-providers.html)」の「*ID プロバイダでの Amazon Verified Permissions の使用*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIdentitySource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/get-identity-source.html)」を参照してください。

### `get-policy-store`
<a name="verifiedpermissions_GetPolicyStore_cli_2_topic"></a>

次のコード例は、`get-policy-store` を使用する方法を示しています。

**AWS CLI**  
**ポリシーストアに関する詳細を取得するには**  
次の `get-policy-store` の例では、指定された ID を持つポリシーストアの詳細を表示します。  

```
aws verifiedpermissions get-policy-store \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "arn": "arn:aws:verifiedpermissions::123456789012:policy-store/PSEXAMPLEabcdefg111111",
    "createdDate": "2023-06-05T20:16:46.225598+00:00",
    "lastUpdatedDate": "2023-06-08T20:40:23.173691+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "validationSettings": { "mode": "OFF" }
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーストア](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/get-policy-store.html)」を参照してください。

### `get-policy-template`
<a name="verifiedpermissions_GetPolicyTemplate_cli_2_topic"></a>

次のコード例は、`get-policy-template` を使用する方法を示しています。

**AWS CLI**  
**ポリシーテンプレートの詳細を取得するには**  
次の `get-policy-template` の例では、指定された ID を持つポリシーテンプレートの詳細を表示します。  

```
aws verifiedpermissions get-policy-template \
    --policy-template-id  PTEXAMPLEabcdefg111111 \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "createdDate": "2023-06-12T20:47:42.804511+00:00",
    "lastUpdatedDate": "2023-06-12T20:47:42.804511+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "policyTemplateId": "PTEXAMPLEabcdefg111111",
    "statement": "permit(\n    principal in ?principal,\n    action == Action::\"view\",\n    resource == Photo::\"VacationPhoto94.jpg\"\n);"
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーテンプレート](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicyTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/get-policy-template.html)」を参照してください。

### `get-policy`
<a name="verifiedpermissions_GetPolicy_cli_2_topic"></a>

次のコード例は、`get-policy` を使用する方法を示しています。

**AWS CLI**  
**ポリシーに関する詳細を取得するには**  
次の `get-policy` の例では、指定された ID を持つポリシーの詳細を表示します。  

```
aws verifiedpermissions get-policy \
    --policy-id PSEXAMPLEabcdefg111111 \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "createdDate": "2023-06-12T20:33:37.382907+00:00",
    "definition": {
        "static": {
            "description": "Grant everyone of janeFriends UserGroup access to the vacationFolder Album",
            "statement": "permit(principal in UserGroup::\"janeFriends\", action, resource in Album::\"vacationFolder\" );"
        }
    },
    "lastUpdatedDate": "2023-06-12T20:33:37.382907+00:00",
    "policyId": "SPEXAMPLEabcdefg111111",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "policyType": "STATIC",
    "principal": {
        "entityId": "janeFriends",
        "entityType": "UserGroup"
    },
    "resource": {
        "entityId": "vacationFolder",
        "entityType": "Album"
    }
}
```
ポリシーに関する詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policies.html)」の「*Amazon Verified Permissions のポリシー*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/get-policy.html)」を参照してください。

### `get-schema`
<a name="verifiedpermissions_GetSchema_cli_2_topic"></a>

次のコード例は、`get-schema` を使用する方法を示しています。

**AWS CLI**  
**ポリシーストアでスキーマを取得するには**  
次の `get-schema` の例では、指定されたポリシーストアにスキーマの詳細を表示します。  

```
aws verifiedpermissions get-schema \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "schema": "{\"MySampleNamespace\":{\"entityTypes\":{\"Employee\":{\"shape\":{\"attributes\":{\"jobLevel\":{\"type\":\"Long\"},\"name\":{\"type\":\"String\"}},\"type\":\"Record\"}}},\"actions\":{\"remoteAccess\":{\"appliesTo\":{\"principalTypes\":[\"Employee\"]}}}}}",
    "createdDate": "2023-06-14T17:47:13.999885+00:00",
    "lastUpdatedDate": "2023-06-14T17:47:13.999885+00:00"
}
```
スキーマの詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[ポリシーストアスキーマ](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/schema.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSchema](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/get-schema.html)」を参照してください。

### `is-authorized-with-token`
<a name="verifiedpermissions_IsAuthorizedWithToken_cli_2_topic"></a>

次のコード例は、`is-authorized-with-token` を使用する方法を示しています。

**AWS CLI**  
**例 1: ユーザーリクエストの承認決定をリクエストするには (許可)**  
次の `is-authorized-with-token` の例では、Amazon Cognito によって認証されたユーザーの認証決定をリクエストします。リクエストは、アクセストークンではなく Cognito によって提供される ID トークンを使用します。この例では、指定された情報ストアは、プリンシパルをタイプ `CognitoUser` のエンティティとして返すように設定されています。  

```
aws verifiedpermissions is-authorized-with-token \
    --action actionId="View",actionType="Action" \
    --resource entityId="vacationPhoto94.jpg",entityType="Photo" \
    --policy-store-id PSEXAMPLEabcdefg111111 \
    --identity-token "AbCdE12345...long.string...54321EdCbA"
```
ポリシーストアには、指定された Cognito ユーザープールとアプリケーション ID からアイデンティティを受け入れる次のステートメントを含むポリシーが含まれています。  

```
permit(
    principal == CognitoUser::"us-east-1_1a2b3c4d5|a1b2c3d4e5f6g7h8i9j0kalbmc",
    action,
    resource == Photo::"VacationPhoto94.jpg"
);
```
出力:  

```
{
    "decision":"Allow",
    "determiningPolicies":[
        {
        "determiningPolicyId":"SPEXAMPLEabcdefg111111"
        }
    ],
    "errors":[]
}
```
Cognito ユーザープールからの ID の使用の詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[ID プロバイダーでの Amazon Verified Permissions の使用](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/identity-providers.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IsAuthorizedWithToken](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/is-authorized-with-token.html)」を参照してください。

### `is-authorized`
<a name="verifiedpermissions_IsAuthorized_cli_2_topic"></a>

次のコード例は、`is-authorized` を使用する方法を示しています。

**AWS CLI**  
**例 1: ユーザーリクエストの承認決定をリクエストするには (許可)**  
次の `is-authorized` の例では、`VacationPhoto94.jpg` というタイプ `Photo` のリソースにで `updatePhoto` オペレーションを実行する、`Alice` というタイプ `User` のプリンシパルの承認決定をリクエストします。  
レスポンスは、リクエストが 1 つのポリシーで許可されていることを示します。  

```
aws verifiedpermissions is-authorized \
    --principal entityType=User,entityId=alice \
    --action actionType=Action,actionId=view \
    --resource entityType=Photo,entityId=VactionPhoto94.jpg \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "decision": "ALLOW",
    "determiningPolicies": [
        {
            "policyId": "SPEXAMPLEabcdefg111111"
        }
    ],
    "errors": []
}
```
**例 2: ユーザーリクエストの承認決定をリクエストするには (拒否)**  
次の例は、プリンシパルが `User::"Bob"` である点を除いて、前の例と同じです。ポリシーストアには、そのユーザーに `Album::"alice_folder"` へのアクセスを許可するポリシーは含まれていません。  
出力は、`DeterminingPolicies` のリストが空であるため、`Deny` が暗黙的であったことを示します。  

```
aws verifiedpermissions create-policy \
    --definition file://definition2.txt \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "decision": "DENY",
    "determiningPolicies": [],
    "errors": []
}
```
詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[IsAuthorized](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/is-authorized.html)」を参照してください。

### `list-identity-sources`
<a name="verifiedpermissions_ListIdentitySources_cli_2_topic"></a>

次のコード例は、`list-identity-sources` を使用する方法を示しています。

**AWS CLI**  
**使用可能な ID ソースを一覧表示するには**  
次の `list-identity-sources` の例では、指定されたポリシーストア内のすべての ID ソースを一覧表示します。  

```
aws verifiedpermissions list-identity-sources \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "identitySources": [
        {
            "createdDate": "2023-06-12T22:27:49.150035+00:00",
            "details": {
                "clientIds": [ "a1b2c3d4e5f6g7h8i9j0kalbmc" ],
                "discoveryUrl": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_1a2b3c4d5",
                "openIdIssuer": "COGNITO",
                "userPoolArn": "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_1a2b3c4d5"
            },
            "identitySourceId": "ISEXAMPLEabcdefg111111",
            "lastUpdatedDate": "2023-06-12T22:27:49.150035+00:00",
            "policyStoreId": "PSEXAMPLEabcdefg111111",
            "principalEntityType": "User"
        }
    ]
}
```
詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/identity-providers.html)」の「*ID プロバイダでの Amazon Verified Permissions の使用*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIdentitySources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/list-identity-sources.html)」を参照してください。

### `list-policies`
<a name="verifiedpermissions_ListPolicies_cli_2_topic"></a>

次のコード例は、`list-policies` を使用する方法を示しています。

**AWS CLI**  
**使用可能なポリシーを一覧表示するには**  
次の `list-policies` の例では、指定されたポリシーストア内のすべてのポリシーを一覧表示します。  

```
aws verifiedpermissions list-policies \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "policies": [
        {
            "createdDate": "2023-06-12T20:33:37.382907+00:00",
            "definition": {
                "static": {
                    "description": "Grant everyone of janeFriends UserGroup access to the vacationFolder Album"
                }
            },
            "lastUpdatedDate": "2023-06-12T20:33:37.382907+00:00",
            "policyId": "SPEXAMPLEabcdefg111111",
            "policyStoreId": "PSEXAMPLEabcdefg111111",
            "policyType": "STATIC",
            "principal": {
                "entityId": "janeFriends",
                "entityType": "UserGroup"
            },
            "resource": {
                "entityId": "vacationFolder",
                "entityType": "Album"
            }
        },
        {
            "createdDate": "2023-06-12T20:39:44.975897+00:00",
            "definition": {
                "static": {
                    "description": "Grant everyone access to the publicFolder Album"
                }
            },
            "lastUpdatedDate": "2023-06-12T20:39:44.975897+00:00",
            "policyId": "SPEXAMPLEabcdefg222222",
            "policyStoreId": "PSEXAMPLEabcdefg111111",
            "policyType": "STATIC",
            "resource": {
                "entityId": "publicFolder",
                "entityType": "Album"
            }
        },
        {
            "createdDate": "2023-06-12T20:49:51.490211+00:00",
            "definition": {
                "templateLinked": {
                    "policyTemplateId": "PTEXAMPLEabcdefg111111"
                }
            },
            "lastUpdatedDate": "2023-06-12T20:49:51.490211+00:00",
            "policyId": "SPEXAMPLEabcdefg333333",
            "policyStoreId": "PSEXAMPLEabcdefg111111",
            "policyType": "TEMPLATE_LINKED",
            "principal": {
                "entityId": "alice",
                "entityType": "User"
            },
            "resource": {
                "entityId": "VacationPhoto94.jpg",
                "entityType": "Photo"
            }
        }
    ]
}
```
ポリシーに関する詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policies.html)」の「*Amazon Verified Permissions のポリシー*」を参照してください。  
+  API の詳細については、「AWS CLI Command Reference」の「[ListPolicies](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/list-policies.html)」を参照してください。**

### `list-policy-stores`
<a name="verifiedpermissions_ListPolicyStores_cli_2_topic"></a>

次のコード例は、`list-policy-stores` を使用する方法を示しています。

**AWS CLI**  
**使用可能なポリシーストアを一覧表示するには**  
次の の`list-policy-stores`例では、 AWS リージョン内のすべてのポリシーストアを一覧表示します。`create-policy-store` および `list-policy-stores` を除く検証済みアクセス許可のすべてのコマンドでは、操作するポリシーストアの ID を指定する必要があります。  

```
aws verifiedpermissions list-policy-stores
```
出力:  

```
{
    "policyStores": [
        {
            "arn": "arn:aws:verifiedpermissions::123456789012:policy-store/PSEXAMPLEabcdefg111111",
            "createdDate": "2023-06-05T20:16:46.225598+00:00",
            "policyStoreId": "PSEXAMPLEabcdefg111111"
        },
        {
            "arn": "arn:aws:verifiedpermissions::123456789012:policy-store/PSEXAMPLEabcdefg222222",
            "createdDate": "2023-06-08T18:09:37.364356+00:00",
            "policyStoreId": "PSEXAMPLEabcdefg222222"
        },
        {
            "arn": "arn:aws:verifiedpermissions::123456789012:policy-store/PSEXAMPLEabcdefg333333",
            "createdDate": "2023-06-08T18:09:46.920600+00:00",
            "policyStoreId": "PSEXAMPLEabcdefg333333"
        }
    ]
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーストア](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPolicyStores](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/list-policy-stores.html)」を参照してください。

### `list-policy-templates`
<a name="verifiedpermissions_ListPolicyTemplates_cli_2_topic"></a>

次のコード例は、`list-policy-templates` を使用する方法を示しています。

**AWS CLI**  
**使用可能なポリシーテンプレートを一覧表示するには**  
次の `list-policy-templates` の例では、指定されたポリシーストア内のすべてのポリシーテンプレートを一覧表示します。  

```
aws verifiedpermissions list-policy-templates \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "policyTemplates": [
        {
            "createdDate": "2023-06-12T20:47:42.804511+00:00",
            "lastUpdatedDate": "2023-06-12T20:47:42.804511+00:00",
            "policyStoreId": "PSEXAMPLEabcdefg111111",
            "policyTemplateId": "PTEXAMPLEabcdefg111111"
        }
    ]
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーテンプレート](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListPolicyTemplates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/list-policy-templates.html)」を参照してください。

### `put-schema`
<a name="verifiedpermissions_PutSchema_cli_2_topic"></a>

次のコード例は、`put-schema` を使用する方法を示しています。

**AWS CLI**  
**スキーマをポリシーストアに保存するには**  
次の `put-schema` の例では、指定されたポリシーストアでスキーマを作成または置き換えます。  
入力ファイルの `cedarJson` パラメータは、JSON オブジェクトの文字列表現を取得します。これには、最も外側の引用符ペア内に埋め込まれた引用符 (") が含まれます。そのためには、すべての埋め込み引用符にバックスラッシュ文字 ( " ) を付け、すべての行を改行のない単一のテキスト行に結合して、JSON を文字列に変換する必要があります。  
文字列の例は、読みやすくするためにここで複数の行にラップして表示できますが、 オペレーションではパラメータを 1 行の文字列として送信する必要があります。  
aws verifiedpermissions put-schema --definition file://schema.txt --policy-store-id PSEXAMPLEabcdefg111111  
`schema.txt` の内容:  

```
{
    "cedarJson": "{\"MySampleNamespace\": {\"actions\": {\"remoteAccess\": {
            \"appliesTo\": {\"principalTypes\": [\"Employee\"]}}},\"entityTypes\": {
            \"Employee\": {\"shape\": {\"attributes\": {\"jobLevel\": {\"type\":
            \"Long\"},\"name\": {\"type\": \"String\"}},\"type\": \"Record\"}}}}}"
}
```
出力:  

```
{
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "namespaces": [
        "MySampleNamespace"
    ],
    "createdDate": "2023-06-14T17:47:13.999885+00:00",
    "lastUpdatedDate": "2023-06-14T17:47:13.999885+00:00"
}
```
スキーマの詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[ポリシーストアスキーマ](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/schema.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutSchema](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/put-schema.html)」を参照してください。

### `update-identity-source`
<a name="verifiedpermissions_UpdateIdentitySource_cli_2_topic"></a>

次のコード例は、`update-identity-source` を使用する方法を示しています。

**AWS CLI**  
**ID ソースを更新するには**  
次の `update-identity-source` の例では、新しい Cognito ユーザープール設定を指定し、ID ソースによって返されるエンティティタイプを変更することで、指定された ID ソースを変更します。  

```
aws verifiedpermissions update-identity-source
    --identity-source-id ISEXAMPLEabcdefg111111 \
    --update-configuration file://config.txt \
    --principal-entity-type "Employee" \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`config.txt` の内容:  

```
{
        "cognitoUserPoolConfiguration": {
                "userPoolArn": "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_1a2b3c4d5",
                "clientIds":["a1b2c3d4e5f6g7h8i9j0kalbmc"]
        }
}
```
出力:  

```
{
    "createdDate": "2023-05-19T20:30:28.214829+00:00",
    "identitySourceId": "ISEXAMPLEabcdefg111111",
    "lastUpdatedDate": "2023-05-19T20:30:28.214829+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111"
}
```
詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/identity-providers.html)」の「*ID プロバイダでの Amazon Verified Permissions の使用*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIdentitySource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/update-identity-source.html)」を参照してください。

### `update-policy-store`
<a name="verifiedpermissions_UpdatePolicyStore_cli_2_topic"></a>

次のコード例は、`update-policy-store` を使用する方法を示しています。

**AWS CLI**  
**ポリシーストアを更新するには**  
次の `update-policy-store` の例では、検証設定を変更してポリシーストアを変更します。  

```
aws verifiedpermissions update-policy-store \
    --validation-settings "mode=STRICT" \
    --policy-store-id PSEXAMPLEabcdefg111111
```
出力:  

```
{
    "arn": "arn:aws:verifiedpermissions::123456789012:policy-store/PSEXAMPLEabcdefg111111",
    "createdDate": "2023-05-16T17:41:29.103459+00:00",
    "lastUpdatedDate": "2023-05-16T17:41:29.103459+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111"
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーストア](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-stores.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePolicyStore](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/update-policy-store.html)」を参照してください。

### `update-policy-template`
<a name="verifiedpermissions_UpdatePolicyTemplate_cli_2_topic"></a>

次のコード例は、`update-policy-template` を使用する方法を示しています。

**AWS CLI**  
**例 1: ポリシーテンプレートを更新するには**  
次の `update-policy-template` の例では、指定されたテンプレートにリンクされたポリシーを変更して、ポリシーステートメントを置き換えます。  

```
aws verifiedpermissions update-policy-template \
    --policy-template-id PTEXAMPLEabcdefg111111 \
    --statement file://template1.txt \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`template1.txt` ファイルの内容。  

```
permit(
    principal in ?principal,
    action == Action::"view",
    resource == Photo::"VacationPhoto94.jpg"
);
```
出力:  

```
{
    "createdDate": "2023-06-12T20:47:42.804511+00:00",
    "lastUpdatedDate": "2023-06-12T20:47:42.804511+00:00",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "policyTemplateId": "PTEXAMPLEabcdefg111111"
}
```
詳細については、「*Amazon Verified Permissions ユーザーガイド*」の「[Amazon Verified Permissions ポリシーテンプレート](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policy-templates.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePolicyTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/update-policy-template.html)」を参照してください。

### `update-policy`
<a name="verifiedpermissions_UpdatePolicy_cli_2_topic"></a>

次のコード例は、`update-policy` を使用する方法を示しています。

**AWS CLI**  
**静的ポリシーを更新するには**  
次の `update-policy` の例では、説明とステートメントを更新して既存の静的ポリシーを変更します。  

```
aws verifiedpermissions update-policy \
    --policy-id SPEXAMPLEabcdefg111111 \
    --definition file://updated-definition.txt \
    --policy-store-id PSEXAMPLEabcdefg111111
```
`statement` パラメータは、JSON オブジェクトの文字列表現を取得します。これには、最も外側の引用符ペア内に埋め込まれた引用符 (") が含まれます。そのためには、すべての埋め込み引用符にバックスラッシュ文字 ( " ) を付け、すべての行を改行のない単一のテキスト行に結合して、JSON を文字列に変換する必要があります。  
文字列の例は、読みやすくするために複数の行にラップして表示できますが、オペレーションではパラメータを 1 行の文字列として送信する必要があります。  
`updated-definition.txt` ファイルの内容。  

```
{
    "static": {
        "description": "Updated policy to grant janeFriends UserGroup access to the vacationFolder Album with view action only",
        "statement": "permit(principal in UserGroup::\"janeFriends\", action == Action::\"view\", resource in Album::\"vacationFolder\" );"
    }
}
```
出力:  

```
{
    "createdDate": "2023-06-12T20:33:37.382907+00:00",
    "lastUpdatedDate": "2023-06-12T20:33:37.382907+00:00",
    "policyId": "SPEXAMPLEabcdefg111111",
    "policyStoreId": "PSEXAMPLEabcdefg111111",
    "policyType": "STATIC",
    "principal": {
        "entityId": "janeFriends",
        "entityType": "UserGroup"
    },
    "resource": {
        "entityId": "vacationFolder",
        "entityType": "Album"
    }
}
```
ポリシーに関する詳細については、「[Amazon Verified Permissions ユーザーガイド](https://docs.aws.amazon.com/verifiedpermissions/latest/userguide/policies.html)」の「*Amazon Verified Permissions のポリシー*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/verifiedpermissions/update-policy.html)」を参照してください。

# を使用した VPC Lattice の例 AWS CLI
<a name="cli_2_vpc-lattice_code_examples"></a>

次のコード例は、VPC Lattice AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-listener`
<a name="vpc-lattice_CreateListener_cli_2_topic"></a>

次のコード例は、`create-listener` を使用する方法を示しています。

**AWS CLI**  
**リスナーを作成するには**  
次の `create-listener` の例では、トラフィックを指定された VPC Lattice ターゲットグループに転送するデフォルトルールを持つ HTTPS リスナーを作成します。  

```
aws vpc-lattice create-listener \
    --name my-service-listener \
    --protocol HTTPS \
    --port 443 \
    --service-identifier svc-0285b53b2eEXAMPLE \
    --default-action file://listener-config.json
```
`listener-config.json` の内容:  

```
{
    "forward": {
        "targetGroups": [
            {
                "targetGroupIdentifier": "tg-0eaa4b9ab4EXAMPLE"
            }
        ]
    }
}
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE/listener/listener-07cc7fb0abEXAMPLE",
    "defaultAction": {
        "forward": {
            "targetGroups": [
                {
                    "targetGroupIdentifier": "tg-0eaa4b9ab4EXAMPLE",
                    "weight": 100
                }
            ]
        }
    },
    "id": "listener-07cc7fb0abEXAMPLE",
    "name": "my-service-listener",
    "port": 443,
    "protocol": "HTTPS",
    "serviceArn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE",
    "serviceId": "svc-0285b53b2eEXAMPLE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[リスナー](https://docs.aws.amazon.com/vpc-lattice/latest/ug/listeners.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-listener.html)」を参照してください。**

### `create-resource-configuration`
<a name="vpc-lattice_CreateResourceConfiguration_cli_2_topic"></a>

次のコード例は、`create-resource-configuration` を使用する方法を示しています。

**AWS CLI**  
**リソース構成を作成するには**  
次の `create-resource-configuration` の例では、単一の IPv4 アドレスを指定するリソース設定を作成します。  

```
aws vpc-lattice create-resource-configuration \
    --name my-resource-config \
    --type SINGLE \
    --resource-gateway-identifier rgw-0bba03f3d56060135 \
    --resource-configuration-definition 'ipResource={ipAddress=10.0.14.85}'
```
出力:  

```
{
    "allowAssociationToShareableServiceNetwork": true,
    "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-07129f3acded87625",
    "id": "rcfg-07129f3acded87625",
    "name": "my-resource-config",
    "portRanges": [
        "1-65535"
    ],
    "protocol": "TCP",
    "resourceConfigurationDefinition": {
        "ipResource": {
            "ipAddress": "10.0.14.85"
        }
    },
    "resourceGatewayId": "rgw-0bba03f3d56060135",
    "status": "ACTIVE",
    "type": "SINGLE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource configurations for VPC resources](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResourceConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-resource-configuration.html)」を参照してください。

### `create-resource-gateway`
<a name="vpc-lattice_CreateResourceGateway_cli_2_topic"></a>

次のコード例は、`create-resource-gateway` を使用する方法を示しています。

**AWS CLI**  
**リソースゲートウェイを作成するには**  
次の `create-resource-gateway` の例では、指定されたサブネットのリソースゲートウェイを作成します。  

```
aws vpc-lattice create-resource-gateway \
    --name my-resource-gateway \
    --vpc-identifier vpc-0bf4c2739bc05a69 \
    --subnet-ids subnet-08e8943905b63a683
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourcegateway/rgw-0bba03f3d56060135",
    "id": "rgw-0bba03f3d56060135",
    "ipAddressType": "IPV4",
    "name": "my-resource-gateway",
    "securityGroupIds": [
        "sg-087ffd596c5fe962c"
    ],
    "status": "ACTIVE",
    "subnetIds": [
        "subnet-08e8943905b63a683"
    ],
    "vpcIdentifier": "vpc-0bf4c2739bc05a694"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource gateways in VPC Lattice](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateResourceGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-resource-gateway.html)」を参照してください。

### `create-service-network-service-association`
<a name="vpc-lattice_CreateServiceNetworkServiceAssociation_cli_2_topic"></a>

次のコード例は、`create-service-network-service-association` を使用する方法を示しています。

**AWS CLI**  
**サービスの関連付けを作成するには**  
次の `create-service-network-service-association` の例では、指定されたサービスと指定されたサービスネットワークを関連付けます。  

```
aws vpc-lattice create-service-network-service-association \
    --service-identifier svc-0285b53b2eEXAMPLE \
    --service-network-identifier sn-080ec7dc93EXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetworkserviceassociation/snsa-0e16955a8cEXAMPLE",
    "createdBy": "123456789012",
    "dnsEntry": {
        "domainName": "my-lattice-service-0285b53b2eEXAMPLE.7d67968.vpc-lattice-svcs.us-east-2.on.aws",
        "hostedZoneId": "Z09127221KTH2CEXAMPLE"
    },
    "id": "snsa-0e16955a8cEXAMPLE",
    "status": "CREATE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービス関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-service-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateServiceNetworkServiceAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-service-network-service-association.html)」を参照してください。

### `create-service-network-vpc-association`
<a name="vpc-lattice_CreateServiceNetworkVpcAssociation_cli_2_topic"></a>

次のコード例は、`create-service-network-vpc-association` を使用する方法を示しています。

**AWS CLI**  
**VPC の関連付けを作成するには**  
次の `create-service-network-vpc-association` の例では、指定された vpc を指定されたサービスネットワークに関連付けます。指定されたセキュリティグループは、VPC 内のどのリソースがサービスネットワークとそのサービスにアクセスできるかを制御します。  

```
aws vpc-lattice create-service-network-vpc-association \
    --vpc-identifier vpc-0a1b2c3d4eEXAMPLE \
    --service-network-identifier sn-080ec7dc93EXAMPLE \
    --security-group-ids sg-0aee16bc6cEXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetworkvpcassociation/snva-0821fc8631EXAMPLE",
    "createdBy": "123456789012",
    "id": "snva-0821fc8631EXAMPLE",
    "securityGroupIds": [
        "sg-0aee16bc6cEXAMPLE"
    ],
    "status": "CREATE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[VPC の関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-vpc-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateServiceNetworkVpcAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-service-network-vpc-association.html)」を参照してください。

### `create-service-network`
<a name="vpc-lattice_CreateServiceNetwork_cli_2_topic"></a>

次のコード例は、`create-service-network` を使用する方法を示しています。

**AWS CLI**  
**サービスネットワークを作成するには**  
次の `create-service-network` の例では、指定された名前のサービスネットワークを作成します。  

```
aws vpc-lattice create-service-network \
    --name my-service-network
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetwork/sn-080ec7dc93EXAMPLE",
    "authType": "NONE",
    "id": "sn-080ec7dc93EXAMPLE",
    "name": "my-service-network"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービスネットワーク](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-networks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateServiceNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-service-network.html)」を参照してください。

### `create-service`
<a name="vpc-lattice_CreateService_cli_2_topic"></a>

次のコード例は、`create-service` を使用する方法を示しています。

**AWS CLI**  
**サービスを作成するには**  
次の `create-service` の例では、指定された名前のサービスを作成します。  

```
aws vpc-lattice create-service \
    --name my-lattice-service
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE",
    "authType": "NONE",
    "dnsEntry": {
        "domainName": "my-lattice-service-0285b53b2eEXAMPLE.1a2b3c4.vpc-lattice-svcs.us-east-2.on.aws",
        "hostedZoneId": "Z09127221KTH2CEXAMPLE"
    },
    "id": "svc-0285b53b2eEXAMPLE",
    "name": "my-lattice-service",
    "status": "CREATE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[VPC Lattice のサービス](https://docs.aws.amazon.com/vpc-lattice/latest/ug/services.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-service.html)」を参照してください。**

### `create-target-group`
<a name="vpc-lattice_CreateTargetGroup_cli_2_topic"></a>

次のコード例は、`create-target-group` を使用する方法を示しています。

**AWS CLI**  
**例 1: INSTANCE タイプのターゲットグループを作成するには**  
次の `create-target-group` の例では、指定された名前、タイプ、および設定を持つターゲットグループを作成します。  

```
aws vpc-lattice create-target-group \
    --name my-lattice-target-group-instance \
    --type INSTANCE \
    --config file://tg-config.json
```
`tg-config.json` の内容:  

```
{
    "port": 443,
    "protocol": "HTTPS",
    "protocolVersion": "HTTP1",
    "vpcIdentifier": "vpc-f1663d9868EXAMPLE"
}
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:targetgroup/tg-0eaa4b9ab4EXAMPLE",
    "config": {
        "healthCheck": {
            "enabled": true,
            "healthCheckIntervalSeconds": 30,
            "healthCheckTimeoutSeconds": 5,
            "healthyThresholdCount": 5,
            "matcher": {
                "httpCode": "200"
            },
            "path": "/",
            "protocol": "HTTPS",
            "protocolVersion": "HTTP1",
            "unhealthyThresholdCount": 2
        },
        "port": 443,
        "protocol": "HTTPS",
        "protocolVersion": "HTTP1",
        "vpcIdentifier": "vpc-f1663d9868EXAMPLE"
    },
    "id": "tg-0eaa4b9ab4EXAMPLE",
    "name": "my-lattice-target-group-instance",
    "status": "CREATE_IN_PROGRESS",
    "type": "INSTANCE"
}
```
**例 2: IP タイプのターゲットグループを作成するには**  
次の `create-target-group` の例では、指定された名前、タイプ、および設定を持つターゲットグループを作成します。  

```
aws vpc-lattice create-target-group \
    --name my-lattice-target-group-ip \
    --type IP \
    --config file://tg-config.json
```
`tg-config.json` の内容:  

```
{
    "ipAddressType": "IPV4",
    "port": 443,
    "protocol": "HTTPS",
    "protocolVersion": "HTTP1",
    "vpcIdentifier": "vpc-f1663d9868EXAMPLE"
}
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:targetgroup/tg-0eaa4b9ab4EXAMPLE",
    "config": {
        "healthCheck": {
            "enabled": true,
            "healthCheckIntervalSeconds": 30,
            "healthCheckTimeoutSeconds": 5,
            "healthyThresholdCount": 5,
            "matcher": {
                "httpCode": "200"
            },
            "path": "/",
            "protocol": "HTTPS",
            "protocolVersion": "HTTP1",
            "unhealthyThresholdCount": 2
        },
        "ipAddressType": "IPV4",
        "port": 443,
        "protocol": "HTTPS",
        "protocolVersion": "HTTP1",
        "vpcIdentifier": "vpc-f1663d9868EXAMPLE"
    },
    "id": "tg-0eaa4b9ab4EXAMPLE",
    "name": "my-lattice-target-group-ip",
    "status": "CREATE_IN_PROGRESS",
    "type": "IP"
}
```
**例 3: LAMBDA タイプのターゲットグループを作成するには**  
次の `create-target-group` の例では、指定された名前、タイプ、および設定を持つターゲットグループを作成します。  

```
aws vpc-lattice create-target-group \
    --name my-lattice-target-group-lambda \
    --type LAMBDA
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:targetgroup/tg-0eaa4b9ab4EXAMPLE",
    "id": "tg-0eaa4b9ab4EXAMPLE",
    "name": "my-lattice-target-group-lambda",
    "status": "CREATE_IN_PROGRESS",
    "type": "LAMBDA"
}
```
**例 4: ALB タイプのターゲットグループを作成するには**  
次の `create-target-group` の例では、指定された名前、タイプ、および設定を持つターゲットグループを作成します。  

```
aws vpc-lattice create-target-group \
    --name my-lattice-target-group-alb \
    --type ALB \
    --config file://tg-config.json
```
`tg-config.json` の内容:  

```
{
    "port": 443,
    "protocol": "HTTPS",
    "protocolVersion": "HTTP1",
    "vpcIdentifier": "vpc-f1663d9868EXAMPLE"
}
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:targetgroup/tg-0eaa4b9ab4EXAMPLE",
    "config": {
        "port": 443,
        "protocol": "HTTPS",
        "protocolVersion": "HTTP1",
        "vpcIdentifier": "vpc-f1663d9868EXAMPLE"
    },
    "id": "tg-0eaa4b9ab4EXAMPLE",
    "name": "my-lattice-target-group-alb",
    "status": "CREATE_IN_PROGRESS",
    "type": "ALB"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ターゲットグループ](https://docs.aws.amazon.com/vpc-lattice/latest/ug/target-groups.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateTargetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/create-target-group.html)」を参照してください。**

### `delete-auth-policy`
<a name="vpc-lattice_DeleteAuthPolicy_cli_2_topic"></a>

次のコード例は、`delete-auth-policy` を使用する方法を示しています。

**AWS CLI**  
**認証ポリシーを削除するには**  
以下の `delete-auth-policy` の例では、指定されたサービスのポリシーを削除します。  

```
aws vpc-lattice delete-auth-policy \
    --resource-identifier svc-0285b53b2eEXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[認証ポリシー](https://docs.aws.amazon.com/vpc-lattice/latest/ug/auth-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAuthPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-auth-policy.html)」を参照してください。

### `delete-listener`
<a name="vpc-lattice_DeleteListener_cli_2_topic"></a>

次のコード例は、`delete-listener` を使用する方法を示しています。

**AWS CLI**  
**リスナーを削除するには**  
以下の `delete-listener` 例は、指定されたリスナーを削除します。  

```
aws vpc-lattice delete-listener \
    --listener-identifier listener-07cc7fb0abEXAMPLE \
    --service-identifier svc-0285b53b2eEXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[リスナー](https://docs.aws.amazon.com/vpc-lattice/latest/ug/listeners.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-listener.html)」を参照してください。

### `delete-resource-configuration`
<a name="vpc-lattice_DeleteResourceConfiguration_cli_2_topic"></a>

次のコード例は、`delete-resource-configuration` を使用する方法を示しています。

**AWS CLI**  
**リソース構成を削除するには**  
次の `delete-resource-configuration` の例では、指定されたリソース構成を削除します。  

```
aws vpc-lattice delete-resource-configuration \
    --resource-configuration-identifier rcfg-07129f3acded87625
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource gateways in VPC Lattice](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourceConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-resource-configuration.html)」を参照してください。

### `delete-resource-gateway`
<a name="vpc-lattice_DeleteResourceGateway_cli_2_topic"></a>

次のコード例は、`delete-resource-gateway` を使用する方法を示しています。

**AWS CLI**  
**リソースゲートウェイを削除するには**  
次の `delete-resource-gateway` の例では、指定されたリソースゲートウェイを削除します。  

```
aws vpc-lattice delete-resource-gateway \
    --resource-gateway-identifier rgw-0bba03f3d56060135
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourcegateway/rgw-0bba03f3d56060135",
    "id": "rgw-0bba03f3d56060135",
    "name": "my-resource-gateway",
    "status": "DELETE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource gateways in VPC Lattice](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResourceGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-resource-gateway.html)」を参照してください。

### `delete-service-network-service-association`
<a name="vpc-lattice_DeleteServiceNetworkServiceAssociation_cli_2_topic"></a>

次のコード例は、`delete-service-network-service-association` を使用する方法を示しています。

**AWS CLI**  
**サービスの関連付けを削除するには**  
次の `delete-service-network-service-association` の例では、指定されたサービス関連付けの関連付けを解除します。  

```
aws vpc-lattice delete-service-network-service-association \
    --service-network-service-association-identifier snsa-031fabb4d8EXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetworkserviceassociation/snsa-031fabb4d8EXAMPLE",
    "id": "snsa-031fabb4d8EXAMPLE",
    "status": "DELETE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービス関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-service-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceNetworkServiceAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-service-network-service-association.html)」を参照してください。

### `delete-service-network-vpc-association`
<a name="vpc-lattice_DeleteServiceNetworkVpcAssociation_cli_2_topic"></a>

次のコード例は、`delete-service-network-vpc-association` を使用する方法を示しています。

**AWS CLI**  
**VPC の関連付けを削除するには**  
次の `delete-service-network-vpc-association` の例では、指定された VPC 関連付けの関連付けを解除します。  

```
aws vpc-lattice delete-service-network-vpc-association \
    --service-network-vpc-association-identifier snva-0821fc8631EXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetworkvpcassociation/snva-0821fc8631EXAMPLE",
    "id": "snva-0821fc8631EXAMPLE",
    "status": "DELETE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[VPC の関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-vpc-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceNetworkVpcAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-service-network-vpc-association.html)」を参照してください。

### `delete-service-network`
<a name="vpc-lattice_DeleteServiceNetwork_cli_2_topic"></a>

次のコード例は、`delete-service-network` を使用する方法を示しています。

**AWS CLI**  
**サービスネットワークを削除するには**  
以下の `delete-service-network` の例では、指定されたサービスネットワークを削除します。  

```
aws vpc-lattice delete-service-network \
    --service-network-identifier sn-080ec7dc93EXAMPLE
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービスネットワーク](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-networks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteServiceNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-service-network.html)」を参照してください。

### `delete-service`
<a name="vpc-lattice_DeleteService_cli_2_topic"></a>

次のコード例は、`delete-service` を使用する方法を示しています。

**AWS CLI**  
**サービスを削除する方法**  
次の `delete-service` の例では、指定されたサービスを削除します。  

```
aws vpc-lattice delete-service \
    --service-identifier svc-0285b53b2eEXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-west-2:123456789012:service/svc-0285b53b2eEXAMPLE",
    "id": "svc-0285b53b2eEXAMPLE",
    "name": "my-lattice-service",
    "status": "DELETE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[VPC Lattice のサービス](https://docs.aws.amazon.com/vpc-lattice/latest/ug/services.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-service.html)」を参照してください。

### `delete-target-group`
<a name="vpc-lattice_DeleteTargetGroup_cli_2_topic"></a>

次のコード例は、`delete-target-group` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループを削除するには**  
次の `delete-target-group` の例は、指定されたターゲットグループを削除します。  

```
aws vpc-lattice delete-target-group \
    --target-group-identifier tg-0eaa4b9ab4EXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:targetgroup/tg-0eaa4b9ab4EXAMPLE",
    "id": "tg-0eaa4b9ab4EXAMPLE",
    "status": "DELETE_IN_PROGRESS"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ターゲットグループ](https://docs.aws.amazon.com/vpc-lattice/latest/ug/target-groups.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteTargetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/delete-target-group.html)」を参照してください。**

### `deregister-targets`
<a name="vpc-lattice_DeregisterTargets_cli_2_topic"></a>

次のコード例は、`deregister-targets` を使用する方法を示しています。

**AWS CLI**  
**ターゲットの登録を解除するには**  
次の `deregister-targets` の例では、指定されたターゲットグループを指定されたターゲットグループから削除します。  

```
aws vpc-lattice deregister-targets \
    --targets i-07dd579bc5EXAMPLE \
    --target-group-identifier tg-0eaa4b9ab4EXAMPLE
```
出力:  

```
{
    "successful": [
        {
            "id": "i-07dd579bc5EXAMPLE",
            "port": 443
        }
    ],
    "unsuccessful": []
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ターゲットの登録](https://docs.aws.amazon.com/vpc-lattice/latest/ug/register-targets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/deregister-targets.html)」を参照してください。

### `get-auth-policy`
<a name="vpc-lattice_GetAuthPolicy_cli_2_topic"></a>

次のコード例は、`get-auth-policy` を使用する方法を示しています。

**AWS CLI**  
**認証ポリシーに関する情報を取得するには**  
以下の `get-auth-policy` の例では、指定されたサービスの認証ポリシーに関する情報を取得します。  

```
aws vpc-lattice get-auth-policy \
    --resource-identifier svc-0285b53b2eEXAMPLE
```
出力:  

```
{
    "createdAt": "2023-06-07T03:51:20.266Z",
    "lastUpdatedAt": "2023-06-07T04:39:27.082Z",
    "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:role/my-clients\"},\"Action\":\"vpc-lattice-svcs:Invoke\",\"Resource\":\"arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE\"}]}",
    "state": "Active"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[認証ポリシー](https://docs.aws.amazon.com/vpc-lattice/latest/ug/auth-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAuthPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-auth-policy.html)」を参照してください。

### `get-listener`
<a name="vpc-lattice_GetListener_cli_2_topic"></a>

次のコード例は、`get-listener` を使用する方法を示しています。

**AWS CLI**  
**サービスリスナーに関する情報を取得するには**  
以下の `get-listener` の例では、指定されたサービスの指定されたリスナーに関する情報を取得します。  

```
aws vpc-lattice get-listener \
    --listener-identifier listener-0ccf55918cEXAMPLE \
    --service-identifier svc-0285b53b2eEXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE/listener/listener-0ccf55918cEXAMPLE",
    "createdAt": "2023-05-07T05:08:45.192Z",
    "defaultAction": {
        "forward": {
            "targetGroups": [
                {
                    "targetGroupIdentifier": "tg-0ff213abb6EXAMPLE",
                    "weight": 1
                }
            ]
        }
    },
    "id": "listener-0ccf55918cEXAMPLE",
    "lastUpdatedAt": "2023-05-07T05:08:45.192Z",
    "name": "http-80",
    "port": 80,
    "protocol": "HTTP",
    "serviceArn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE",
    "serviceId": "svc-0285b53b2eEXAMPLE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ルーティングを定義する](https://docs.aws.amazon.com/vpc-lattice/latest/ug/services.html#define-routing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetListener](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-listener.html)」を参照してください。

### `get-resource-configuration`
<a name="vpc-lattice_GetResourceConfiguration_cli_2_topic"></a>

次のコード例は、`get-resource-configuration` を使用する方法を示しています。

**AWS CLI**  
**リソース構成に関する情報を取得するには**  
次の `get-resource-configuration` の例では、指定されたリソース構成に関する情報を取得します。  

```
aws vpc-lattice get-resource-configuration \
    --resource-configuration-identifier rcfg-07129f3acded87625
```
出力:  

```
{
    "allowAssociationToShareableServiceNetwork": true,
    "amazonManaged": false,
    "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-07129f3acded87625",
    "createdAt": "2025-02-01T00:57:35.871000+00:00",
    "id": "rcfg-07129f3acded87625",
    "lastUpdatedAt": "2025-02-01T00:57:46.874000+00:00",
    "name": "my-resource-config",
    "portRanges": [
        "1-65535"
    ],
    "protocol": "TCP",
    "resourceConfigurationDefinition": {
        "ipResource": {
            "ipAddress": "10.0.14.85"
        }
    },
    "resourceGatewayId": "rgw-0bba03f3d56060135",
    "status": "ACTIVE",
    "type": "SINGLE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource gateways in VPC Lattice](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-resource-configuration.html)」を参照してください。

### `get-resource-gateway`
<a name="vpc-lattice_GetResourceGateway_cli_2_topic"></a>

次のコード例は、`get-resource-gateway` を使用する方法を示しています。

**AWS CLI**  
**リソースゲートウェイに関する情報を取得するには**  
次の `get-resource-gateway` の例では、指定されたリソースゲートウェイに関する情報を取得します。  

```
aws vpc-lattice get-resource-gateway \
    --resource-gateway-identifier rgw-0bba03f3d56060135
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourcegateway/rgw-0bba03f3d56060135",
    "createdAt": "2025-02-01T00:57:33.241000+00:00",
    "id": "rgw-0bba03f3d56060135",
    "ipAddressType": "IPV4",
    "lastUpdatedAt": "2025-02-01T00:57:44.351000+00:00",
    "name": "my-resource-gateway",
    "securityGroupIds": [
        "sg-087ffd596c5fe962c"
    ],
    "status": "ACTIVE",
    "subnetIds": [
        "subnet-08e8943905b63a683"
    ],
    "vpcId": "vpc-0bf4c2739bc05a694"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource gateways in VPC Lattice](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetResourceGateway](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-resource-gateway.html)」を参照してください。

### `get-service-network-service-association`
<a name="vpc-lattice_GetServiceNetworkServiceAssociation_cli_2_topic"></a>

次のコード例は、`get-service-network-service-association` を使用する方法を示しています。

**AWS CLI**  
**サービス関連付けに関する情報を取得するには**  
次の `get-service-network-service-association` の例では、指定されたサービス関連付けに関する情報を取得します。  

```
aws vpc-lattice get-service-network-service-association \
    --service-network-service-association-identifier snsa-031fabb4d8EXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetworkserviceassociation/snsa-031fabb4d8EXAMPLE",
    "createdAt": "2023-05-05T21:48:16.076Z",
    "createdBy": "123456789012",
    "dnsEntry": {
        "domainName": "my-lattice-service-0285b53b2eEXAMPLE.7d67968.vpc-lattice-svcs.us-east-2.on.aws",
        "hostedZoneId": "Z09127221KTH2CEXAMPLE"
    },
    "id": "snsa-031fabb4d8EXAMPLE",
    "serviceArn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE",
    "serviceId": "svc-0285b53b2eEXAMPLE",
    "serviceName": "my-lattice-service",
    "serviceNetworkArn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetwork/sn-080ec7dc93EXAMPLE",
    "serviceNetworkId": "sn-080ec7dc93EXAMPLE",
    "serviceNetworkName": "my-service-network",
    "status": "ACTIVE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービス関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-service-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceNetworkServiceAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-service-network-service-association.html)」を参照してください。

### `get-service-network-vpc-association`
<a name="vpc-lattice_GetServiceNetworkVpcAssociation_cli_2_topic"></a>

次のコード例は、`get-service-network-vpc-association` を使用する方法を示しています。

**AWS CLI**  
**VPC 関連付けに関する情報を取得するには**  
次の `get-service-network-vpc-association` の例では、指定された VPC 関連付けに関する情報を取得します。  

```
aws vpc-lattice get-service-network-vpc-association \
    --service-network-vpc-association-identifier snva-0821fc8631EXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetworkvpcassociation/snva-0821fc8631EXAMPLE",
    "createdAt": "2023-06-06T23:41:08.421Z",
    "createdBy": "123456789012",
    "id": "snva-0c5dcb60d6EXAMPLE",
    "lastUpdatedAt": "2023-06-06T23:41:08.421Z",
    "securityGroupIds": [
        "sg-0aee16bc6cEXAMPLE"
    ],
    "serviceNetworkArn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetwork/sn-080ec7dc93EXAMPLE",
    "serviceNetworkId": "sn-080ec7dc93EXAMPLE",
    "serviceNetworkName": "my-service-network",
    "status": "ACTIVE",
    "vpcId": "vpc-0a1b2c3d4eEXAMPLE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[VPC の関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-vpc-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceNetworkVpcAssociation](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-service-network-vpc-association.html)」を参照してください。

### `get-service-network`
<a name="vpc-lattice_GetServiceNetwork_cli_2_topic"></a>

次のコード例は、`get-service-network` を使用する方法を示しています。

**AWS CLI**  
**サービスネットワークに関する情報を取得するには**  
次の `get-service-network` の例では、指定されたサービスネットワークに関する情報を取得します。  

```
aws vpc-lattice get-service-network \
    --service-network-identifier sn-080ec7dc93EXAMPLE
```
出力:  

```
{
   "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetwork/sn-080ec7dc93EXAMPLE",
   "authType": "AWS_IAM",
   "createdAt": "2023-05-05T15:26:08.417Z",
   "id": "sn-080ec7dc93EXAMPLE",
   "lastUpdatedAt": "2023-05-05T15:26:08.417Z",
   "name": "my-service-network",
   "numberOfAssociatedServices": 2,
   "numberOfAssociatedVPCs": 3
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービスネットワーク](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-networks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceNetwork](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-service-network.html)」を参照してください。

### `get-service`
<a name="vpc-lattice_GetService_cli_2_topic"></a>

次のコード例は、`get-service` を使用する方法を示しています。

**AWS CLI**  
**サービスに関する情報を取得するには**  
次の `get-service` の例では、指定されたサービスに関する情報を取得します。  

```
aws vpc-lattice get-service \
    --service-identifier svc-0285b53b2eEXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE",
    "authType": "AWS_IAM",
    "createdAt": "2023-05-05T21:35:29.339Z",
    "dnsEntry": {
        "domainName": "my-lattice-service-0285b53b2eEXAMPLE.7d67968.vpc-lattice-svcs.us-east-2.on.aws",
        "hostedZoneId": "Z09127221KTH2CFUOHIZH"
    },
    "id": "svc-0285b53b2eEXAMPLE",
    "lastUpdatedAt": "2023-05-05T21:35:29.339Z",
    "name": "my-lattice-service",
    "status": "ACTIVE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービス](https://docs.aws.amazon.com/vpc-lattice/latest/ug/services.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetService](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-service.html)」を参照してください。

### `get-target-group`
<a name="vpc-lattice_GetTargetGroup_cli_2_topic"></a>

次のコード例は、`get-target-group` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループに関する情報を取得するには**  
次の `get-target-group` の例では、ターゲットタイプが `INSTANCE` の指定されたターゲットグループに関する情報を取得します。  

```
aws vpc-lattice get-target-group \
    --target-group-identifier tg-0eaa4b9ab4EXAMPLE
```
出力:  

```
{
    "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:targetgroup/tg-0eaa4b9ab4EXAMPLE",
    "config": {
        "healthCheck": {
            "enabled": true,
            "healthCheckIntervalSeconds": 30,
            "healthCheckTimeoutSeconds": 5,
            "healthyThresholdCount": 5,
            "matcher": {
                "httpCode": "200"
            },
            "path": "/",
            "protocol": "HTTPS",
            "protocolVersion": "HTTP1",
            "unhealthyThresholdCount": 2
        },
        "port": 443,
        "protocol": "HTTPS",
        "protocolVersion": "HTTP1",
        "vpcIdentifier": "vpc-f1663d9868EXAMPLE"
    },
    "createdAt": "2023-05-06T04:41:04.122Z",
    "id": "tg-0eaa4b9ab4EXAMPLE",
    "lastUpdatedAt": "2023-05-06T04:41:04.122Z",
    "name": "my-target-group",
    "serviceArns": [
        "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE"
    ],
    "status": "ACTIVE",
    "type": "INSTANCE"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ターゲットグループ](https://docs.aws.amazon.com/vpc-lattice/latest/ug/target-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTargetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/get-target-group.html)」を参照してください。

### `list-listeners`
<a name="vpc-lattice_ListListeners_cli_2_topic"></a>

次のコード例は、`list-listeners` を使用する方法を示しています。

**AWS CLI**  
**サービスリスナーを一覧表示するには**  
次の `list-listeners` 例では、指定されたサービスのリスナーを一覧表示します。  

```
aws vpc-lattice list-listeners \
    --service-identifier svc-0285b53b2eEXAMPLE
```
出力:  

```
{
    "items": [
        {
            "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE/listener/listener-0ccf55918cEXAMPLE",
            "createdAt": "2023-05-07T05:08:45.192Z",
            "id": "listener-0ccf55918cEXAMPLE",
            "lastUpdatedAt": "2023-05-07T05:08:45.192Z",
            "name": "http-80",
            "port": 80,
            "protocol": "HTTP"
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ルーティングを定義する](https://docs.aws.amazon.com/vpc-lattice/latest/ug/services.html#define-routing)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListListeners](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-listeners.html)」を参照してください。

### `list-resource-configurations`
<a name="vpc-lattice_ListResourceConfigurations_cli_2_topic"></a>

次のコード例は、`list-resource-configurations` を使用する方法を示しています。

**AWS CLI**  
**リソース構成を一覧表示するには**  
次の `list-resource-configurations` の例では、リソース構成を一覧表示します。  

```
aws vpc-lattice list-resource-configurations
```
出力:  

```
{
    "items": [
        {
            "amazonManaged": false,
            "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-07129f3acded87625",
            "createdAt": "2025-02-01T00:57:35.871000+00:00",
            "id": "rcfg-07129f3acded87625",
            "lastUpdatedAt": "2025-02-01T00:57:46.874000+00:00",
            "name": "my-resource-config",
            "resourceGatewayId": "rgw-0bba03f3d56060135",
            "status": "ACTIVE",
            "type": "SINGLE"
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource configurations](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-configuration.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-resource-configurations.html)」を参照してください。

### `list-resource-endpoint-associations`
<a name="vpc-lattice_ListResourceEndpointAssociations_cli_2_topic"></a>

次のコード例は、`list-resource-endpoint-associations` を使用する方法を示しています。

**AWS CLI**  
**VPC エンドポイントの関連付けを一覧表示するには**  
次の `list-resource-endpoint-associations` の例では、指定されたリソース構成に関連付けられている VPC エンドポイントを一覧表示します。  

```
aws vpc-lattice list-resource-endpoint-associations \
    --resource-configuration-identifier rcfg-07129f3acded87625
```
出力:  

```
{
    "items": [
        {
            "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceendpointassociation/rea-0956a7435baf89326",
            "createdAt": "2025-02-01T00:57:38.998000+00:00",
            "id": "rea-0956a7435baf89326",
            "resourceConfigurationArn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-07129f3acded87625",
            "resourceConfigurationId": "rcfg-07129f3acded87625",
            "vpcEndpointId": "vpce-019b90d6f16d4f958",
            "vpcEndpointOwner": "123456789012"
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Manage associations for a VPC Lattice resource configuration](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-configuration-associations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceEndpointAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-resource-endpoint-associations.html)」を参照してください。

### `list-resource-gateways`
<a name="vpc-lattice_ListResourceGateways_cli_2_topic"></a>

次のコード例は、`list-resource-gateways` を使用する方法を示しています。

**AWS CLI**  
**リソースゲートウェイを一覧表示するには**  
次の `list-resource-gateways` の例では、リソースゲートウェイを一覧表示します。  

```
aws vpc-lattice list-resource-gateways
```
出力:  

```
{
    "items": [
        {
            "arn": "arn:aws:vpc-lattice:us-east-1:123456789012:resourcegateway/rgw-0bba03f3d56060135",
            "createdAt": "2025-02-01T00:57:33.241000+00:00",
            "id": "rgw-0bba03f3d56060135",
            "ipAddressType": "IPV4",
            "lastUpdatedAt": "2025-02-01T00:57:44.351000+00:00",
            "name": "my-resource-gateway",
            "seurityGroupIds": [
                "sg-087ffd596c5fe962c"
            ],
            "status": "ACTIVE",
            "subnetIds": [
                "subnet-08e8943905b63a683"
            ],
            "vpcIdentifier": "vpc-0bf4c2739bc05a694"
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Resource gateways in VPC Lattice](https://docs.aws.amazon.com/vpc-lattice/latest/ug/resource-gateway.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceGateways](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-resource-gateways.html)」を参照してください。

### `list-service-network-service-associations`
<a name="vpc-lattice_ListServiceNetworkServiceAssociations_cli_2_topic"></a>

次のコード例は、`list-service-network-service-associations` を使用する方法を示しています。

**AWS CLI**  
**サービス関連付けを一覧表示するには**  
次の `list-service-network-service-associations` の例では、指定されたサービスネットワークのサービス関連付けを一覧表示します。`--query` オプションは、出力をサービス関連付け ID にスコープします。  

```
aws vpc-lattice list-service-network-service-associations \
    --service-network-identifier sn-080ec7dc93EXAMPLE \
    --query items[*].id
```
出力:  

```
[
    "snsa-031fabb4d8EXAMPLE",
    "snsa-0e16955a8cEXAMPLE"
]
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービス関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-service-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceNetworkServiceAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-service-network-service-associations.html)」を参照してください。

### `list-service-network-vpc-associations`
<a name="vpc-lattice_ListServiceNetworkVpcAssociations_cli_2_topic"></a>

次のコード例は、`list-service-network-vpc-associations` を使用する方法を示しています。

**AWS CLI**  
**VPC の関連付けを一覧表示するには**  
次の `list-service-network-vpc-associations` の例では、指定されたサービスネットワークの VPC 関連付けを一覧表示します。`--query` オプションは、出力を VPC 関連付けの ID にスコープします。  

```
aws vpc-lattice list-service-network-vpc-associations \
    --service-network-identifier sn-080ec7dc93EXAMPLE \
    --query items[*].id
```
出力:  

```
[
    "snva-0821fc8631EXAMPLE",
    "snva-0c5dcb60d6EXAMPLE"
]
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[VPC の関連付けの管理](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html#service-network-vpc-associations)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceNetworkVpcAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-service-network-vpc-associations.html)」を参照してください。

### `list-service-network-vpc-endpoint-associations`
<a name="vpc-lattice_ListServiceNetworkVpcEndpointAssociations_cli_2_topic"></a>

次のコード例は、`list-service-network-vpc-endpoint-associations` を使用する方法を示しています。

**AWS CLI**  
**VPC エンドポイントの関連付けを一覧表示するには**  
次の `list-service-network-vpc-endpoint-associations` の例では、指定されたサービスネットワークに関連付けられた VPC エンドポイントを一覧表示します。  

```
aws vpc-lattice list-service-network-vpc-endpoint-associations \
    --service-network-identifier sn-0808d1748faee0c1e
```
出力:  

```
{
    "items": [
        {
            "createdAt": "2025-02-01T01:21:36.667000+00:00",
            "serviceNetworkArn": "arn:aws:vpc-lattice:us-east-1:123456789012:servicenetwork/sn-0808d1748faee0c1e",
            "state": "ACTIVE",
            "vpcEndpointId": "vpce-0cc199f605eaeace7",
            "vpcEndpointOwnerId": "123456789012"
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[Manage the associations for a VPC Lattice service network](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-network-associations.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceNetworkVpcEndpointAssociations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-service-network-vpc-endpoint-associations.html)」を参照してください。

### `list-service-networks`
<a name="vpc-lattice_ListServiceNetworks_cli_2_topic"></a>

次のコード例は、`list-service-networks` を使用する方法を示しています。

**AWS CLI**  
**サービスネットワークを一覧表示するには**  
次の `list-service-networks` の例では、呼び出し元のアカウントを所有または共有しているサービスネットワークを一覧表示します。`--query` オプションは、結果をサービスネットワークの Amazon リソースネーム (ARN) にスコープします。  

```
aws vpc-lattice list-service-networks \
    --query items[*].arn
```
出力:  

```
[
    "arn:aws:vpc-lattice:us-east-2:123456789012:servicenetwork/sn-080ec7dc93EXAMPLE",
    "arn:aws:vpc-lattice:us-east-2:111122223333:servicenetwork/sn-0ec4d436cfEXAMPLE"
]
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービスネットワーク](https://docs.aws.amazon.com/vpc-lattice/latest/ug/service-networks.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListServiceNetworks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-service-networks.html)」を参照してください。

### `list-services`
<a name="vpc-lattice_ListServices_cli_2_topic"></a>

次のコード例は、`list-services` を使用する方法を示しています。

**AWS CLI**  
**サービスを一覧表示するには**  
次の `list-services` の例では、呼び出し元のアカウントを所有または共有しているサービスを一覧表示します。`--query` オプションは、結果をサービスの Amazon リソースネーム (ARN) にスコープします。  

```
aws vpc-lattice list-services \
    --query items[*].arn
```
出力:  

```
[
    "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE",
    "arn:aws:vpc-lattice:us-east-2:111122223333:service/svc-0b8ac96550EXAMPLE"
]
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[サービス](https://docs.aws.amazon.com/vpc-lattice/latest/ug/services.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListServices](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-services.html)」を参照してください。**

### `list-target-groups`
<a name="vpc-lattice_ListTargetGroups_cli_2_topic"></a>

次のコード例は、`list-target-groups` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループを一覧表示するには**  
次の `list-target-groups` の例では、ターゲットタイプが `LAMBDA` のターゲットグループを一覧表示します。  

```
aws vpc-lattice list-target-groups \
    --target-group-type LAMBDA
```
出力:  

```
{
    "items": [
        {
            "arn": "arn:aws:vpc-lattice:us-east-2:123456789012:targetgroup/tg-045c1b7d9dEXAMPLE",
            "createdAt": "2023-05-06T05:22:16.637Z",
            "id": "tg-045c1b7d9dEXAMPLE",
            "lastUpdatedAt": "2023-05-06T05:22:16.637Z",
            "name": "my-target-group-lam",
            "serviceArns": [
                "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE"
            ],
            "status": "ACTIVE",
            "type": "LAMBDA"
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ターゲットグループ](https://docs.aws.amazon.com/vpc-lattice/latest/ug/target-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTargetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-target-groups.html)」を参照してください。

### `list-targets`
<a name="vpc-lattice_ListTargets_cli_2_topic"></a>

次のコード例は、`list-targets` を使用する方法を示しています。

**AWS CLI**  
**ターゲットグループのターゲットを一覧表示するには**  
次の `list-targets` の例は、指定されたターゲットグループのターゲットを表示します。  

```
aws vpc-lattice list-targets \
    --target-group-identifier tg-0eaa4b9ab4EXAMPLE
```
出力:  

```
{
    "items": [
        {
            "id": "i-07dd579bc5EXAMPLE",
            "port": 443,
            "status": "HEALTHY"
        },
        {
            "id": "i-047b3c9078EXAMPLE",
            "port": 443,
            "reasonCode": "HealthCheckFailed",
            "status": "UNHEALTHY"
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ターゲットグループ](https://docs.aws.amazon.com/vpc-lattice/latest/ug/target-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/list-targets.html)」を参照してください。

### `put-auth-policy`
<a name="vpc-lattice_PutAuthPolicy_cli_2_topic"></a>

次のコード例は、`put-auth-policy` を使用する方法を示しています。

**AWS CLI**  
**サービスの認証ポリシーを作成するには**  
次の `put-auth-policy` の例では、指定された IAM ロールを使用する認証されたプリンシパルからのリクエストへのアクセスを許可します。リソースは、ポリシーがアタッチされているサービスの ARN です。  

```
aws vpc-lattice put-auth-policy \
    --resource-identifier svc-0285b53b2eEXAMPLE \
    --policy file://auth-policy.json
```
`auth-policy.json` の内容:  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::123456789012:role/my-clients"
            },
            "Action": "vpc-lattice-svcs:Invoke",
            "Resource": "arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE"
        }
    ]
}
```
出力:  

```
{
    "policy": "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:role/my-clients\"},\"Action\":\"vpc-lattice-svcs:Invoke\",\"Resource\":\"arn:aws:vpc-lattice:us-east-2:123456789012:service/svc-0285b53b2eEXAMPLE\"}]}",
    "state": "Active"
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[認証ポリシー](https://docs.aws.amazon.com/vpc-lattice/latest/ug/auth-policies.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAuthPolicy](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/put-auth-policy.html)」を参照してください。

### `register-targets`
<a name="vpc-lattice_RegisterTargets_cli_2_topic"></a>

次のコード例は、`register-targets` を使用する方法を示しています。

**AWS CLI**  
**ターゲットを登録するには**  
次の `register-targets` の例では、指定されたターゲットグループに指定されたターゲットを登録します。  

```
aws vpc-lattice register-targets \
    --targets id=i-047b3c9078EXAMPLE id=i-07dd579bc5EXAMPLE \
    --target-group-identifier tg-0eaa4b9ab4EXAMPLE
```
出力:  

```
{
    "successful": [
        {
            "id": "i-07dd579bc5EXAMPLE",
            "port": 443
        }
    ],
    "unsuccessful": [
        {
            "failureCode": "UnsupportedTarget",
            "failureMessage": "Instance targets must be in the same VPC as their target group",
            "id": "i-047b3c9078EXAMPLE",
            "port": 443
        }
    ]
}
```
詳細については、「*Amazon VPC Lattice ユーザーガイド*」の「[ターゲットの登録](https://docs.aws.amazon.com/vpc-lattice/latest/ug/register-targets.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/vpc-lattice/register-targets.html)」を参照してください。

# AWS WAF Classic を使用した の例 AWS CLI
<a name="cli_2_waf_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS WAF Classic。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `put-logging-configuration`
<a name="waf_PutLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`put-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**指定された Kinesis Firehose ストリーム ARN を使用してウェブ ACL ARN のログ記録設定を作成するには**  
次の `put-logging-configuration` の例は、CloudFront を使用した WAF のログ記録設定を示しています。  

```
aws waf put-logging-configuration \
    --logging-configuration ResourceArn=arn:aws:waf::123456789012:webacl/3bffd3ed-fa2e-445e-869f-a6a7cf153fd3,LogDestinationConfigs=arn:aws:firehose:us-east-1:123456789012:deliverystream/aws-waf-logs-firehose-stream,RedactedFields=[]
```
出力:  

```
{
    "LoggingConfiguration": {
        "ResourceArn": "arn:aws:waf::123456789012:webacl/3bffd3ed-fa2e-445e-869f-a6a7cf153fd3",
        "LogDestinationConfigs": [
            "arn:aws:firehose:us-east-1:123456789012:deliverystream/aws-waf-logs-firehose-stream"
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/put-logging-configuration.html)」を参照してください。

### `update-byte-match-set`
<a name="waf_UpdateByteMatchSet_cli_2_topic"></a>

次のコード例は、`update-byte-match-set` を使用する方法を示しています。

**AWS CLI**  
**バイト一致セットを更新するには**  
次の `update-byte-match-set` コマンドは、ByteMatchSet の ByteMatchTuple オブジェクト (フィルター) を削除します。  

```
aws waf update-byte-match-set --byte-match-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates Action="DELETE",ByteMatchTuple={FieldToMatch={Type="HEADER",Data="referer"},TargetString="badrefer1",TextTransformation="NONE",PositionalConstraint="CONTAINS"}
```
詳細については、「*AWS WAF デベロッパーガイド*」の「文字列一致条件の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateByteMatchSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/update-byte-match-set.html)」を参照してください。

### `update-ip-set`
<a name="waf_UpdateIpSet_cli_2_topic"></a>

次のコード例は、`update-ip-set` を使用する方法を示しています。

**AWS CLI**  
**IP セットを更新するには**  
次の `update-ip-set` コマンドは、IPv4 アドレスを使用して IPSet を更新し、IPv6 アドレスを削除します:  

```
aws waf update-ip-set --ip-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates Action="INSERT",IPSetDescriptor={Type="IPV4",Value="12.34.56.78/16"},Action="DELETE",IPSetDescriptor={Type="IPV6",Value="1111:0000:0000:0000:0000:0000:0000:0111/128"}
```
または、JSON ファイルを使用して入力を指定できます。例えば、次のようになります。  

```
aws waf update-ip-set --ip-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1  --updates file://change.json
```
JSON ファイルの内容は次のとおりです。  

```
[
{
"Action": "INSERT",
"IPSetDescriptor":
{
"Type": "IPV4",
"Value": "12.34.56.78/16"
}
},
{
"Action": "DELETE",
"IPSetDescriptor":
{
"Type": "IPV6",
"Value": "1111:0000:0000:0000:0000:0000:0000:0111/128"
}
}
]
```
詳細については、「*AWS WAF デベロッパーガイド*」の「IP 一致条件の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/update-ip-set.html)」を参照してください。

### `update-rule`
<a name="waf_UpdateRule_cli_2_topic"></a>

次のコード例は、`update-rule` を使用する方法を示しています。

**AWS CLI**  
**ルールを更新するには**  
次の `update-rule` コマンドは、ルール内の Predicate オブジェクトを削除します。  

```
aws waf update-rule --rule-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates Action="DELETE",Predicate={Negated=false,Type="ByteMatch",DataId="MyByteMatchSetID"}
```
詳細については、「*AWS WAF デベロッパーガイド*」の「ルールの使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/update-rule.html)」を参照してください。

### `update-size-constraint-set`
<a name="waf_UpdateSizeConstraintSet_cli_2_topic"></a>

次のコード例は、`update-size-constraint-set` を使用する方法を示しています。

**AWS CLI**  
**サイズ制約セットを更新するには**  
次の `update-size-constraint-set` コマンドは、サイズ制約セット内の SizeConstraint オブジェクト (フィルター) を削除します。  

```
aws waf update-size-constraint-set --size-constraint-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates Action="DELETE",SizeConstraint={FieldToMatch={Type="QUERY_STRING"},TextTransformation="NONE",ComparisonOperator="GT",Size=0}
```
詳細については、「*AWS WAF デベロッパーガイド*」の「サイズ制約条件の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSizeConstraintSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/update-size-constraint-set.html)」を参照してください。

### `update-sql-injection-match-set`
<a name="waf_UpdateSqlInjectionMatchSet_cli_2_topic"></a>

次のコード例は、`update-sql-injection-match-set` を使用する方法を示しています。

**AWS CLI**  
**SQL インジェクションマッチセットを更新するには**  
次の `update-sql-injection-match-set` コマンドは、SQL インジェクション一致セット内の SqlInjectionMatchTuple オブジェクト (フィルター) を削除します。  

```
aws waf update-sql-injection-match-set --sql-injection-match-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates Action="DELETE",SqlInjectionMatchTuple={FieldToMatch={Type="QUERY_STRING"},TextTransformation="URL_DECODE"}
```
詳細については、「*AWS WAF デベロッパーガイド*」の「SQL インジェクション一致条件の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSqlInjectionMatchSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/update-sql-injection-match-set.html)」を参照してください。

### `update-web-acl`
<a name="waf_UpdateWebAcl_cli_2_topic"></a>

次のコード例は、`update-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL を更新するには**  
次の `update-web-acl` コマンドは、WebACL 内の `ActivatedRule` オブジェクトを削除します。  
aws waf update-web-acl --web-acl-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates Action="DELETE",ActivatedRule='\$1Priority=1,RuleId="WAFRule-1-Example",Action=\$1Type="ALLOW"\$1,Type="REGULAR"\$1'  
出力:  

```
{
    "ChangeToken": "12cs345-67cd-890b-1cd2-c3a4567d89f1"
}
```
詳細については、[ACLs の使用](https://docs.aws.amazon.com/waf/latest/developerguide/classic-web-acl-working-with.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/update-web-acl.html)」を参照してください。

### `update-xss-match-set`
<a name="waf_UpdateXssMatchSet_cli_2_topic"></a>

次のコード例は、`update-xss-match-set` を使用する方法を示しています。

**AWS CLI**  
**XSSMatchSet を更新するには**  
次の `update-xss-match-set` コマンドは、XssMatchSet の XssMatchTuple オブジェクト (フィルター) を削除します。  

```
aws waf update-xss-match-set --xss-match-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates Action="DELETE",XssMatchTuple={FieldToMatch={Type="QUERY_STRING"},TextTransformation="URL_DECODE"}
```
詳細については、「*AWS WAF デベロッパーガイド*」の「クロスサイトスクリプト一致条件の使用」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateXssMatchSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/update-xss-match-set.html)」を参照してください。

# AWS WAF Classic Regional を使用した の例 AWS CLI
<a name="cli_2_waf-regional_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS WAF Classic Regional。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-web-acl`
<a name="waf-regional_AssociateWebAcl_cli_2_topic"></a>

次のコード例は、`associate-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL をリソースに関連付けるには**  
次の `associate-web-acl` のコマンドは、web-acl-id で指定されたウェブ ACL を resource-arn で指定されたリソースに関連付けます。リソース ARN は、Application Load Balancer または API Gateway を参照できます。  

```
aws waf-regional associate-web-acl \
    --web-acl-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --resource-arn 12cs345-67cd-890b-1cd2-c3a4567d89f1
```
詳細については、「*AWS WAF デベロッパーガイド*」の「[Web ACL の使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-working-with.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/associate-web-acl.html)」を参照してください。

### `put-logging-configuration`
<a name="waf-regional_PutLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`put-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**指定された Kinesis Firehose ストリーム ARN を使用してウェブ ACL ARN のログ記録設定を作成するには**  
次の `put-logging-configuration` の例は、リージョン `us-east-1` の ALB/APIGateway を使用した WAF のログ記録設定を示しています。  

```
aws waf-regional put-logging-configuration \
    --logging-configuration ResourceArn=arn:aws:waf-regional:us-east-1:123456789012:webacl/3bffd3ed-fa2e-445e-869f-a6a7cf153fd3,LogDestinationConfigs=arn:aws:firehose:us-east-1:123456789012:deliverystream/aws-waf-logs-firehose-stream,RedactedFields=[] \
    --region us-east-1
```
出力:  

```
{
    "LoggingConfiguration": {
        "ResourceArn": "arn:aws:waf-regional:us-east-1:123456789012:webacl/3bffd3ed-fa2e-445e-869f-a6a7cf153fd3",
        "LogDestinationConfigs": [
            "arn:aws:firehose:us-east-1:123456789012:deliverystream/aws-waf-logs-firehose-stream"
        ]
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/put-logging-configuration.html)」を参照してください。

### `update-byte-match-set`
<a name="waf-regional_UpdateByteMatchSet_cli_2_topic"></a>

次のコード例は、`update-byte-match-set` を使用する方法を示しています。

**AWS CLI**  
**バイト一致セットを更新するには**  
次の `update-byte-match-set` コマンドは、`ByteMatchSet` 内の `ByteMatchTuple` オブジェクト (フィルター) を削除します。`updates` 値には二重引用符が埋め込まれているため、値を単一引用符で囲む必要があります。  

```
aws waf-regional update-byte-match-set \
    --byte-match-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 \
    --updates 'Action="DELETE",ByteMatchTuple={FieldToMatch={Type="HEADER",Data="referer"},TargetString="badrefer1",TextTransformation="NONE",PositionalConstraint="CONTAINS"}'
```
詳細については、「*AWS WAF デベロッパーガイド*」の「[文字列一致条件の使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-string-conditions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateByteMatchSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/update-byte-match-set.html)」を参照してください。

### `update-ip-set`
<a name="waf-regional_UpdateIpSet_cli_2_topic"></a>

次のコード例は、`update-ip-set` を使用する方法を示しています。

**AWS CLI**  
**IP セットを更新するには**  
次の `update-ip-set` コマンドは、IPv4 アドレスを使用して IPSet を更新し、IPv6 アドレスを削除します。`get-change-token` コマンドを実行して、`change-token` の値を取得します。更新の値には二重引用符が埋め込まれているため、値を単一引用符で囲む必要があります。  

```
aws waf update-ip-set \
    --ip-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 \
    --updates 'Action="INSERT",IPSetDescriptor={Type="IPV4",Value="12.34.56.78/16"},Action="DELETE",IPSetDescriptor={Type="IPV6",Value="1111:0000:0000:0000:0000:0000:0000:0111/128"}'
```
または、JSON ファイルを使用して入力を指定できます。例えば、次のようになります。  

```
aws waf-regional update-ip-set \
    --ip-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1  \
    --updates file://change.json
```
`change.json` の内容  

```
[
    {
        "Action": "INSERT",
        "IPSetDescriptor":
        {
            "Type": "IPV4",
            "Value": "12.34.56.78/16"
        }
    },
    {
        "Action": "DELETE",
        "IPSetDescriptor":
        {
            "Type": "IPV6",
            "Value": "1111:0000:0000:0000:0000:0000:0000:0111/128"
        }
    }
]
```
詳細については、「*AWS WAF デベロッパーガイド*」の「[IP 一致条件の使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-ip-conditions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/update-ip-set.html)」を参照してください。

### `update-rule`
<a name="waf-regional_UpdateRule_cli_2_topic"></a>

次のコード例は、`update-rule` を使用する方法を示しています。

**AWS CLI**  
**ルールを更新するには**  
次の `update-rule` コマンドは、ルール内の `Predicate` オブジェクトを削除します。`updates` 値には二重引用符が埋め込まれているため、値全体を単一引用符で囲む必要があります。  

```
aws waf-regional update-rule \
    --rule-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 \
    --updates 'Action="DELETE",Predicate={Negated=false,Type="ByteMatch",DataId="MyByteMatchSetID"}'
```
詳細については、「*AWS WAF デベロッパーガイド*」の「[ルールの使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/update-rule.html)」を参照してください。

### `update-size-constraint-set`
<a name="waf-regional_UpdateSizeConstraintSet_cli_2_topic"></a>

次のコード例は、`update-size-constraint-set` を使用する方法を示しています。

**AWS CLI**  
**サイズ制約セットを更新するには**  
次の `update-size-constraint-set` コマンドは、サイズ制約セット内の SizeConstraint ` オブジェクト (フィルター) を削除します。`updates` 値には埋め込み二重引用符が含まれているため、値全体を単一引用符で囲む必要があります。  

```
aws waf-regional update-size-constraint-set \
    --size-constraint-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 \
    --updates 'Action="DELETE",SizeConstraint={FieldToMatch={Type="QUERY_STRING"},TextTransformation="NONE",ComparisonOperator="GT",Size=0}'
```
詳細については、「*AWS WAF デベロッパーガイド*」の「[サイズ制約条件の使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-size-conditions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSizeConstraintSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/update-size-constraint-set.html)」を参照してください。

### `update-sql-injection-match-set`
<a name="waf-regional_UpdateSqlInjectionMatchSet_cli_2_topic"></a>

次のコード例は、`update-sql-injection-match-set` を使用する方法を示しています。

**AWS CLI**  
**SQL インジェクションマッチセットを更新するには**  
次の `update-sql-injection-match-set` コマンドは、SQL インジェクション一致セット内の `SqlInjectionMatchTuple` オブジェクト (フィルター) を削除します。`updates` 値には二重引用符が埋め込まれているため、値全体を一重引用符で囲む必要があります。:  
aws waf-regional update-sql-injection-match-set --sql-injection-match-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 --updates 'Action="DELETE",SqlInjectionMatchTuple=\$1FieldToMatch=\$1Type="QUERY\$1STRING"\$1,TextTransformation="URL\$1DECODE"\$1'  
詳細については、「*AWS WAF デベロッパーガイド*」の「[SQL インジェクション一致条件の使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-sql-conditions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSqlInjectionMatchSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/update-sql-injection-match-set.html)」を参照してください。

### `update-web-acl`
<a name="waf-regional_UpdateWebAcl_cli_2_topic"></a>

次のコード例は、`update-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL を更新するには**  
次の `update-web-acl` コマンドは、WebACL 内の `ActivatedRule` オブジェクトを削除します。`updates` 値には二重引用符が埋め込まれているため、値全体を一重引用符で囲む必要があります。  

```
aws waf-regional update-web-acl \
    --web-acl-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 \
    --updates Action="DELETE",ActivatedRule='{Priority=1,RuleId="WAFRule-1-Example",Action={Type="ALLOW"},Type="ALLOW"}'
```
詳細については、「*AWS WAF デベロッパーガイド*」の「[Web ACL の使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-working-with.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/update-web-acl.html)」を参照してください。

### `update-xss-match-set`
<a name="waf-regional_UpdateXssMatchSet_cli_2_topic"></a>

次のコード例は、`update-xss-match-set` を使用する方法を示しています。

**AWS CLI**  
**XSSMatchSet を更新するには**  
次の `update-xss-match-set` コマンドは、`XssMatchSet` 内の `XssMatchTuple` オブジェクト (フィルター) を削除します。`updates` 値には埋め込み二重引用符が含まれているため、値全体を単一引用符で囲む必要があります。  

```
aws waf-regional update-xss-match-set \
    --xss-match-set-id a123fae4-b567-8e90-1234-5ab67ac8ca90 \
    --change-token 12cs345-67cd-890b-1cd2-c3a4567d89f1 \
    --updates 'Action="DELETE",XssMatchTuple={FieldToMatch={Type="QUERY_STRING"},TextTransformation="URL_DECODE"}'
```
詳細については、「*AWS WAF デベロッパーガイド*」の「[クロスサイトスクリプト一致条件の使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-xss-conditions.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateXssMatchSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/update-xss-match-set.html)」を参照してください。

# AWS WAFV2 を使用した の例 AWS CLI
<a name="cli_2_wafv2_code_examples"></a>

次のコード例は、 AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS WAFV2。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-web-acl`
<a name="wafv2_AssociateWebAcl_cli_2_topic"></a>

次の例は、`associate-web-acl` を使用する方法を説明しています。

**AWS CLI**  
**ウェブ ACL をリージョン AWS リソースに関連付けるには**  
次の `associate-web-acl` の例では、指定されたウェブ ACL を Application Load Balancer に関連付けます。  

```
aws wafv2 associate-web-acl \
    --web-acl-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test-cli/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --resource-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/waf-cli-alb/1ea17125f8b25a2a \
    --region us-west-2
```
このコマンドでは何も出力されません。  
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「ウェブ ACL と AWS リソースの関連付けまたは関連付け解除](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-associating-aws-resource.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/associate-web-acl.html)」を参照してください。

### `check-capacity`
<a name="wafv2_CheckCapacity_cli_2_topic"></a>

次のコード例は、`check-capacity` を使用する方法を示しています。

**AWS CLI**  
**一連のルールで使用されるキャパシティを取得するには**  
次の `check-capacity` は、レートベースのルールステートメントを含むルールセットと、ネストされたルールを含む AND ルールステートメントの容量要件を取得します。  

```
aws wafv2 check-capacity \
    --scope REGIONAL \
    --rules file://waf-rule-list.json \
    --region us-west-2
```
ファイル://waf-rule-list.json の内容:  

```
[
    {
        "Name":"basic-rule",
        "Priority":0,
        "Statement":{
            "AndStatement":{
                "Statements":[
                    {
                        "ByteMatchStatement":{
                            "SearchString":"example.com",
                            "FieldToMatch":{
                                "SingleHeader":{
                                    "Name":"host"
                                }
                            },
                            "TextTransformations":[
                                {
                                    "Priority":0,
                                    "Type":"LOWERCASE"
                                }
                            ],
                            "PositionalConstraint":"EXACTLY"
                        }
                    },
                    {
                        "GeoMatchStatement":{
                            "CountryCodes":[
                                "US",
                                "IN"
                            ]
                        }
                    }
                ]
            }
        },
        "Action":{
            "Allow":{

            }
        },
        "VisibilityConfig":{
            "SampledRequestsEnabled":true,
            "CloudWatchMetricsEnabled":true,
            "MetricName":"basic-rule"
        }
    },
    {
        "Name":"rate-rule",
        "Priority":1,
        "Statement":{
            "RateBasedStatement":{
                "Limit":1000,
                "AggregateKeyType":"IP"
            }
        },
        "Action":{
            "Block":{

            }
        },
        "VisibilityConfig":{
            "SampledRequestsEnabled":true,
            "CloudWatchMetricsEnabled":true,
            "MetricName":"rate-rule"
        }
    }
]
```
出力:  

```
{
    "Capacity":15
}
```
詳細については、[AWS 「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「WAF ウェブ ACL キャパシティユニット (WCU)](https://docs.aws.amazon.com/waf/latest/developerguide/how-aws-waf-works.html#aws-waf-capacity-units)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CheckCapacity](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/check-capacity.html)」を参照してください。

### `create-ip-set`
<a name="wafv2_CreateIpSet_cli_2_topic"></a>

次のコード例は、`create-ip-set` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL とルールグループで使用する IP セットを作成するには**  
次の `create-ip-set` コマンドは、単一のアドレス範囲仕様を持つ IP セットを作成します。  

```
aws wafv2 create-ip-set \
    --name testip \
    --scope REGIONAL \
    --ip-address-version IPV4 \
    --addresses 198.51.100.0/16
```
出力:  

```
{
    "Summary":{
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/ipset/testip/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Description":"",
        "Name":"testip",
        "LockToken":"447e55ac-0000-0000-0000-86b67c17f8b5",
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/create-ip-set.html)」を参照してください。

### `create-regex-pattern-set`
<a name="wafv2_CreateRegexPatternSet_cli_2_topic"></a>

次のコード例は、`create-regex-pattern-set` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL とルールグループで使用する正規表現パターンセットを作成するには**  
次の `create-regex-pattern-set` コマンドは、2 つの正規表現パターンを指定して正規表現パターンセットを作成します。  

```
aws wafv2 create-regex-pattern-set \
    --name regexPatterSet01 \
    --scope REGIONAL \
    --description 'Test web-acl' \
    --regular-expression-list '[{"RegexString": "/[0-9]*/"},{"RegexString": "/[a-z]*/"}]'
```
出力:  

```
{
    "Summary":{
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/regexpatternset/regexPatterSet01/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Description":"Test web-acl",
        "Name":"regexPatterSet01",
        "LockToken":"0bc01e21-03c9-4b98-9433-6229cbf1ef1c",
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRegexPatternSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/create-regex-pattern-set.html)」を参照してください。

### `create-rule-group`
<a name="wafv2_CreateRuleGroup_cli_2_topic"></a>

次のコード例は、`create-rule-group` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL で使用するカスタムルールグループを作成するには**  
次の `create-rule-group` コマンドは、リージョンで使用するカスタムルールグループを作成します。グループのルールステートメントは、JSON 形式のファイルで提供されます。  

```
aws wafv2 create-rule-group \
    --name "TestRuleGroup" \
    --scope REGIONAL \
    --capacity 250 \
    --rules file://waf-rule.json \
    --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=TestRuleGroupMetrics \
    --region us-west-2
```
file://waf-rule.json の内容:  

```
[
    {
        "Name":"basic-rule",
        "Priority":0,
        "Statement":{
            "AndStatement":{
                "Statements":[
                    {
                        "ByteMatchStatement":{
                            "SearchString":"example.com",
                            "FieldToMatch":{
                                "SingleHeader":{
                                    "Name":"host"
                                }
                            },
                            "TextTransformations":[
                                {
                                    "Priority":0,
                                    "Type":"LOWERCASE"
                                }
                            ],
                            "PositionalConstraint":"EXACTLY"
                        }
                    },
                    {
                        "GeoMatchStatement":{
                            "CountryCodes":[
                                "US",
                                "IN"
                            ]
                        }
                    }
                ]
            }
        },
        "Action":{
            "Allow":{

            }
        },
        "VisibilityConfig":{
            "SampledRequestsEnabled":true,
            "CloudWatchMetricsEnabled":true,
            "MetricName":"basic-rule"
        }
    }
]
```
出力:  

```
{
    "Summary":{
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/rulegroup/TestRuleGroup/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Description":"",
        "Name":"TestRuleGroup",
        "LockToken":"7b3bcec2-374e-4c5a-b2b9-563bf47249f0",
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、 AWS Shield Advanced デベロッパーガイド*」の「[Managing Your Own Rule Groups](https://docs.aws.amazon.com/waf/latest/developerguide/waf-user-created-rule-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/create-rule-group.html)」を参照してください。

### `create-web-acl`
<a name="wafv2_CreateWebAcl_cli_2_topic"></a>

次のコード例は、`create-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL を作成するには**  
次の `create-web-acl` コマンドは、リージョンで使用するウェブ ACL を作成します。ウェブ ACL のルールステートメントは、JSON 形式のファイルで提供されます。  

```
aws wafv2 create-web-acl \
    --name TestWebAcl \
    --scope REGIONAL \
    --default-action Allow={} \
    --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=TestWebAclMetrics \
    --rules file://waf-rule.json \
    --region us-west-2
```
file://waf-rule.json の内容:  

```
[
    {
        "Name":"basic-rule",
        "Priority":0,
        "Statement":{
            "AndStatement":{
                "Statements":[
                    {
                        "ByteMatchStatement":{
                            "SearchString":"example.com",
                            "FieldToMatch":{
                                "SingleHeader":{
                                    "Name":"host"
                                }
                            },
                            "TextTransformations":[
                                {
                                    "Priority":0,
                                    "Type":"LOWERCASE"
                                }
                            ],
                            "PositionalConstraint":"EXACTLY"
                        }
                    },
                    {
                        "GeoMatchStatement":{
                            "CountryCodes":[
                                "US",
                                "IN"
                            ]
                        }
                    }
                ]
            }
        },
        "Action":{
            "Allow":{

            }
        },
        "VisibilityConfig":{
            "SampledRequestsEnabled":true,
            "CloudWatchMetricsEnabled":true,
            "MetricName":"basic-rule"
        }
    }
]
```
出力:  

```
{
    "Summary":{
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/TestWebAcl/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Description":"",
        "Name":"TestWebAcl",
        "LockToken":"2294b3a1-eb60-4aa0-a86f-a3ae04329de9",
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    }
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「 AWS *[Managing and Using a Web Access Control List (Web ACL)](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/create-web-acl.html)」を参照してください。

### `delete-ip-set`
<a name="wafv2_DeleteIpSet_cli_2_topic"></a>

次のコード例は、`delete-ip-set` を使用する方法を示しています。

**AWS CLI**  
**IP セットを削除するには**  
以下の `delete-ip-set` は指定した IP セットを削除します。この呼び出しには、呼び出しから取得できる ID、`list-ip-sets`、および呼び出しから取得できるロックトークン、`list-ip-sets` と `get-ip-set` が必要です。  

```
aws wafv2 delete-ip-set \
    --name test1 \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --lock-token 46851772-db6f-459d-9385-49428812e357
```
このコマンドでは何も出力されません。  
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/delete-ip-set.html)」を参照してください。

### `delete-logging-configuration`
<a name="wafv2_DeleteLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`delete-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL でログ記録を無効にするには**  
次の `delete-logging-configuration` は、指定されたウェブ ACL からログ記録設定を削除します。  

```
aws wafv2 delete-logging-configuration \
    --resource-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced デベロッパーガイド AWS *」の[「ウェブ ACL トラフィック情報のログ記録](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/delete-logging-configuration.html)」を参照してください。

### `delete-regex-pattern-set`
<a name="wafv2_DeleteRegexPatternSet_cli_2_topic"></a>

次のコード例は、`delete-regex-pattern-set` を使用する方法を示しています。

**AWS CLI**  
**正規表現パターンセットを削除するには**  
次の `delete-regex-pattern-set` は、指定された正規表現パターンセットの設定を更新します。この呼び出しには、呼び出しから取得できる ID、`list-regex-pattern-sets`、および呼び出し `list-regex-pattern-sets` または呼び出し `get-regex-pattern-set` から取得できるロックトークンが必要です。  

```
aws wafv2 delete-regex-pattern-set \
    --name regexPatterSet01 \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --lock-token 0bc01e21-03c9-4b98-9433-6229cbf1ef1c
```
このコマンドでは何も出力されません。  
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRegexPatternSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/delete-regex-pattern-set.html)」を参照してください。

### `delete-rule-group`
<a name="wafv2_DeleteRuleGroup_cli_2_topic"></a>

次のコード例は、`delete-rule-group` を使用する方法を示しています。

**AWS CLI**  
**カスタムルールグループを削除するには**  
次の `delete-rule-group` は、指定されたカスタムルールグループを削除します。この呼び出しには、呼び出しから取得できる ID、`list-rule-groups`、および呼び出し `list-rule-groups` または呼び出し `get-rule-group` から取得できるロックトークンが必要です。  

```
aws wafv2 delete-rule-group \
    --name TestRuleGroup \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --lock-token 7b3bcec2-0000-0000-0000-563bf47249f0
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 WAF、 AWS Firewall Manager、 AWS Shield Advanced デベロッパーガイド*」の「[Managing Your Own Rule Groups](https://docs.aws.amazon.com/waf/latest/developerguide/waf-user-created-rule-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/delete-rule-group.html)」を参照してください。

### `delete-web-acl`
<a name="wafv2_DeleteWebAcl_cli_2_topic"></a>

次のコード例は、`delete-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL を削除するには**  
次の `delete-web-acl` は、アカウントから指定されたウェブ ACL を削除します。ウェブ ACL は、リソースに関連付けられていない場合にのみ削除できます。この呼び出しには、呼び出しから取得できる ID、`list-web-acls`、および呼び出し `list-web-acls` または呼び出し `get-web-acl` から取得できるロックトークンが必要です。  

```
aws wafv2 delete-web-acl \
    --name test \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --lock-token ebab4ed2-155e-4c9a-9efb-e4c45665b1f5
```
このコマンドでは何も出力されません。  
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced デベロッパーガイド AWS *[」の「ウェブアクセスコントロールリスト (ウェブ ACL) の管理と使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/delete-web-acl.html)」を参照してください。

### `describe-managed-rule-group`
<a name="wafv2_DescribeManagedRuleGroup_cli_2_topic"></a>

次のコード例は、`describe-managed-rule-group` を使用する方法を示しています。

**AWS CLI**  
**マネージドルールグループの説明を取得するには**  
次の は、 AWS マネージドルールグループの説明`describe-managed-rule-group`を取得します。  

```
aws wafv2 describe-managed-rule-group \
    --vendor-name AWS \
    --name AWSManagedRulesCommonRuleSet \
    --scope REGIONAL
```
出力:  

```
{
    "Capacity": 700,
    "Rules": [
        {
            "Name": "NoUserAgent_HEADER",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "UserAgent_BadBots_HEADER",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "SizeRestrictions_QUERYSTRING",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "SizeRestrictions_Cookie_HEADER",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "SizeRestrictions_BODY",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "SizeRestrictions_URIPATH",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "EC2MetaDataSSRF_BODY",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "EC2MetaDataSSRF_COOKIE",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "EC2MetaDataSSRF_URIPATH",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "EC2MetaDataSSRF_QUERYARGUMENTS",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "GenericLFI_QUERYARGUMENTS",
            "Action": {
                "Block": {}
            }
        },
        {
            }
            "Name": "GenericLFI_URIPATH",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "GenericLFI_BODY",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "RestrictedExtensions_URIPATH",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "RestrictedExtensions_QUERYARGUMENTS",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "GenericRFI_QUERYARGUMENTS",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "GenericRFI_BODY",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "GenericRFI_URIPATH",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "CrossSiteScripting_COOKIE",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "CrossSiteScripting_QUERYARGUMENTS",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "CrossSiteScripting_BODY",
            "Action": {
                "Block": {}
            }
        },
        {
            "Name": "CrossSiteScripting_URIPATH",
            "Action": {
                "Block": {}
            }
        }
    ]
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced AWS デベロッパーガイド*」の[「マネージドルールグループ](https://docs.aws.amazon.com/waf/latest/developerguide/waf-managed-rule-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeManagedRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/describe-managed-rule-group.html)」を参照してください。

### `disassociate-web-acl`
<a name="wafv2_DisassociateWebAcl_cli_2_topic"></a>

次の例は、`disassociate-web-acl` を使用する方法を説明しています。

**AWS CLI**  
**リージョン AWS リソースからウェブ ACL の関連付けを解除するには**  
次の `disassociate-web-acl` の例では、指定された Application Load Balancer から既存のウェブ ACL 関連付けを削除します。  

```
aws wafv2 disassociate-web-acl \
    --resource-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/waf-cli-alb/1ea17125f8b25a2a \
    --region us-west-2
```
このコマンドでは何も出力されません。  
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「ウェブ ACL と AWS リソースの関連付けまたは関連付け解除](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-associating-aws-resource.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/disassociate-web-acl.html)」を参照してください。

### `get-ip-set`
<a name="wafv2_GetIpSet_cli_2_topic"></a>

次のコード例は、`get-ip-set` を使用する方法を示しています。

**AWS CLI**  
**特定の IP セットを取得するには**  
次の `get-ip-set` は、指定された名前、スコープ、および ID を持つ IP セットを取得します。コマンド `create-ip-set` と `list-ip-sets` から IP セットの ID を取得できます。  

```
aws wafv2 get-ip-set \
    --name testip \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "IPSet":{
        "Description":"",
        "Name":"testip",
        "IPAddressVersion":"IPV4",
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE1111",
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/ipset/testip/a1b2c3d4-5678-90ab-cdef-EXAMPLE1111",
        "Addresses":[
            "192.0.2.0/16"
        ]
    },
    "LockToken":"447e55ac-2396-4c6d-b9f9-86b67c17f8b5"
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-ip-set.html)」を参照してください。

### `get-logging-configuration`
<a name="wafv2_GetLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`get-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL のログ記録設定を取得するには**  
次の `get-logging-configuration` は、指定されたウェブ ACL のログ記録設定を取得します。  

```
aws wafv2 get-logging-configuration \
    --resource-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222 \
    --region us-west-2
```
出力:  

```
{
    "LoggingConfiguration":{
        "ResourceArn":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
        "RedactedFields":[
            {
                "Method":{

                }
            }
        ],
        "LogDestinationConfigs":[
            "arn:aws:firehose:us-west-2:123456789012:deliverystream/aws-waf-logs-custom-transformation"
        ]
    }
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced デベロッパーガイド AWS *」の[「ウェブ ACL トラフィック情報のログ記録](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-logging-configuration.html)」を参照してください。

### `get-rate-based-statement-managed-keys`
<a name="wafv2_GetRateBasedStatementManagedKeys_cli_2_topic"></a>

次のコード例は、`get-rate-based-statement-managed-keys` を使用する方法を示しています。

**AWS CLI**  
**レートベースのルールでブロックされている IP アドレスのリストを取得するには**  
次の `get-rate-based-statement-managed-keys` は、リージョンアプリケーションに使用されているレートベースのルールによって現在ブロックされている IP アドレスを取得します。  

```
aws wafv2 get-rate-based-statement-managed-keys \
    --scope REGIONAL \
    --web-acl-name testwebacl2 \
    --web-acl-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --rule-name ratebasedtest
```
出力:  

```
{
    "ManagedKeysIPV4":{
        "IPAddressVersion":"IPV4",
        "Addresses":[
            "198.51.100.0/32"
        ]
    },
    "ManagedKeysIPV6":{
        "IPAddressVersion":"IPV6",
        "Addresses":[

        ]
    }
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced AWS デベロッパーガイド*」の[「レートベースのルールステートメント](https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-type-rate-based.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRateBasedStatementManagedKeys](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-rate-based-statement-managed-keys.html)」を参照してください。

### `get-regex-pattern-set`
<a name="wafv2_GetRegexPatternSet_cli_2_topic"></a>

次のコード例は、`get-regex-pattern-set` を使用する方法を示しています。

**AWS CLI**  
**特定の正規表現パターンセットを取得するには**  
次の `get-regex-pattern-set` は、指定された名前、スコープ、リージョン、および ID を持つ正規表現パターンセットを取得します。コマンド `create-regex-pattern-set` と `list-regex-pattern-sets` から正規表現パターンセットの ID を取得できます。  

```
aws wafv2 get-regex-pattern-set \
    --name regexPatterSet01 \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --region us-west-2
```
出力:  

```
{
    "RegexPatternSet":{
        "Description":"Test web-acl",
        "RegularExpressionList":[
            {
                "RegexString":"/[0-9]*/"
            },
            {
                "RegexString":"/[a-z]*/"
            }
        ],
        "Name":"regexPatterSet01",
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/regexpatternset/regexPatterSet01/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
    },
    "LockToken":"c8abf33f-b6fc-46ae-846e-42f994d57b29"
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRegexPatternSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-regex-pattern-set.html)」を参照してください。

### `get-rule-group`
<a name="wafv2_GetRuleGroup_cli_2_topic"></a>

次のコード例は、`get-rule-group` を使用する方法を示しています。

**AWS CLI**  
**特定のカスタムルールグループを取得するには**  
次の `get-rule-group` は、指定された名前、スコープ、および ID を持つカスタムルールグループを取得します。コマンド `create-rule-group` と `list-rule-groups` からルールグループの ID を取得できます。  

```
aws wafv2 get-rule-group \
    --name ff \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "RuleGroup":{
        "Capacity":1,
        "Description":"",
        "Rules":[
            {
                "Priority":0,
                "Action":{
                    "Block":{

                    }
                },
                "VisibilityConfig":{
                    "SampledRequestsEnabled":true,
                    "CloudWatchMetricsEnabled":true,
                    "MetricName":"jj"
                },
                "Name":"jj",
                "Statement":{
                    "SizeConstraintStatement":{
                        "ComparisonOperator":"LE",
                        "TextTransformations":[
                            {
                                "Priority":0,
                                "Type":"NONE"
                            }
                        ],
                        "FieldToMatch":{
                            "UriPath":{

                            }
                        },
                        "Size":7
                    }
                }
            }
        ],
        "VisibilityConfig":{
            "SampledRequestsEnabled":true,
            "CloudWatchMetricsEnabled":true,
            "MetricName":"ff"
        },
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/rulegroup/ff/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Name":"ff"
    },
    "LockToken":"485458c9-1830-4234-af31-ec4d52ced1b3"
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、 AWS Shield Advanced デベロッパーガイド*」の「[Managing Your Own Rule Groups](https://docs.aws.amazon.com/waf/latest/developerguide/waf-user-created-rule-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-rule-group.html)」を参照してください。

### `get-sampled-requests`
<a name="wafv2_GetSampledRequests_cli_2_topic"></a>

次のコード例は、`get-sampled-requests` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL のウェブリクエストのサンプルを取得するには**  
次の `get-sampled-requests` は、指定されたウェブ ACL、ルールメトリクス、時間枠のサンプルされたウェブリクエストを取得します。  

```
aws wafv2 get-sampled-requests \
    --web-acl-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test-cli/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --rule-metric-name AWS-AWSManagedRulesSQLiRuleSet \
    --scope=REGIONAL \
    --time-window StartTime=2020-02-12T20:00Z,EndTime=2020-02-12T21:10Z \
    --max-items 100
```
出力:  

```
{
    "TimeWindow": {
    "EndTime": 1581541800.0,
    "StartTime": 1581537600.0
    },
    "SampledRequests": [
        {
            "Action": "BLOCK",
            "Timestamp": 1581541799.564,
            "RuleNameWithinRuleGroup": "AWS#AWSManagedRulesSQLiRuleSet#SQLi_BODY",
            "Request": {
                "Country": "US",
                "URI": "/",
                "Headers": [
                    {
                        "Name": "Host",
                        "Value": "alb-test-1EXAMPLE1.us-east-1.elb.amazonaws.com"
                    },
                    {
                        "Name": "Content-Length",
                        "Value": "7456"
                    },
                    {
                        "Name": "User-Agent",
                        "Value": "curl/7.53.1"
                    },
                    {
                        "Name": "Accept",
                        "Value": "/"
                    },
                    {
                        "Name": "Content-Type",
                        "Value": "application/x-www-form-urlencoded"
                    }
                ],
                "ClientIP": "198.51.100.08",
                "Method": "POST",
                "HTTPVersion": "HTTP/1.1"
            },
            "Weight": 1
        },
        {
            "Action": "BLOCK",
            "Timestamp": 1581541799.988,
            "RuleNameWithinRuleGroup": "AWS#AWSManagedRulesSQLiRuleSet#SQLi_BODY",
            "Request": {
                "Country": "US",
                "URI": "/",
                "Headers": [
                    {
                        "Name": "Host",
                        "Value": "alb-test-1EXAMPLE1.us-east-1.elb.amazonaws.com"
                    },
                    {
                        "Name": "Content-Length",
                        "Value": "7456"
                    },
                    {
                        "Name": "User-Agent",
                        "Value": "curl/7.53.1"
                    },
                    {
                        "Name": "Accept",
                        "Value": "/"
                    },
                    {
                        "Name": "Content-Type",
                        "Value": "application/x-www-form-urlencoded"
                    }
                ],
                "ClientIP": "198.51.100.08",
                "Method": "POST",
                "HTTPVersion": "HTTP/1.1"
            },
            "Weight": 3
        },
        {
            "Action": "BLOCK",
            "Timestamp": 1581541799.846,
            "RuleNameWithinRuleGroup": "AWS#AWSManagedRulesSQLiRuleSet#SQLi_BODY",
            "Request": {
                "Country": "US",
                "URI": "/",
                "Headers": [
                    {
                        "Name": "Host",
                        "Value": "alb-test-1EXAMPLE1.us-east-1.elb.amazonaws.com"
                    },
                    {
                        "Name": "Content-Length",
                        "Value": "7456"
                    },
                    {
                        "Name": "User-Agent",
                        "Value": "curl/7.53.1"
                    },
                    {
                        "Name": "Accept",
                        "Value": "/"
                    },
                    {
                        "Name": "Content-Type",
                        "Value": "application/x-www-form-urlencoded"
                    }
                ],
                "ClientIP": "198.51.100.08",
                "Method": "POST",
                "HTTPVersion": "HTTP/1.1"
            },
            "Weight": 1
        },
        {
            "Action": "BLOCK",
            "Timestamp": 1581541799.4,
            "RuleNameWithinRuleGroup": "AWS#AWSManagedRulesSQLiRuleSet#SQLi_BODY",
            "Request": {
                "Country": "US",
                "URI": "/",
                "Headers": [
                    {
                        "Name": "Host",
                        "Value": "alb-test-1EXAMPLE1.us-east-1.elb.amazonaws.com"
                    },
                    {
                        "Name": "Content-Length",
                        "Value": "7456"
                    },
                    {
                        "Name": "User-Agent",
                        "Value": "curl/7.53.1"
                    },
                    {
                        "Name": "Accept",
                        "Value": "/"
                    },
                    {
                        "Name": "Content-Type",
                        "Value": "application/x-www-form-urlencoded"
                    }
                ],
                "ClientIP": "198.51.100.08",
                "Method": "POST",
                "HTTPVersion": "HTTP/1.1"
            },
            "Weight": 1
        }
    ],
    "PopulationSize": 4
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「ウェブリクエストのサンプルの表示](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-testing.html#web-acl-testing-view-sample)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSampledRequests](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-sampled-requests.html)」を参照してください。

### `get-web-acl-for-resource`
<a name="wafv2_GetWebAclForResource_cli_2_topic"></a>

次の例は、`get-web-acl-for-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS リソースに関連付けられているウェブ ACL を取得するには**  
次の `get-web-acl-for-resource` は、指定されたリソースに関連付けられているウェブ ACL の JSON を取得します。  

```
aws wafv2 get-web-acl-for-resource \
    --resource-arn arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/waf-cli-alb/1ea17125f8b25a2a
```
出力:  

```
{
    "WebACL":{
        "Capacity":3,
        "Description":"",
        "Rules":[
            {
                "Priority":1,
                "Action":{
                    "Block":{

                    }
                },
                "VisibilityConfig":{
                    "SampledRequestsEnabled":true,
                    "CloudWatchMetricsEnabled":true,
                    "MetricName":"testrule01"
                },
                "Name":"testrule01",
                "Statement":{
                    "AndStatement":{
                        "Statements":[
                            {
                                "ByteMatchStatement":{
                                    "PositionalConstraint":"EXACTLY",
                                    "TextTransformations":[
                                        {
                                            "Priority":0,
                                            "Type":"NONE"
                                        }
                                    ],
                                    "SearchString":"dGVzdHN0cmluZw==",
                                    "FieldToMatch":{
                                        "UriPath":{

                                        }
                                    }
                                }
                            },
                            {
                                "SizeConstraintStatement":{
                                    "ComparisonOperator":"EQ",
                                    "TextTransformations":[
                                        {
                                            "Priority":0,
                                            "Type":"NONE"
                                        }
                                    ],
                                    "FieldToMatch":{
                                        "QueryString":{

                                       }
                                    },
                                    "Size":0
                                }
                            }
                        ]
                    }
                }
            }
        ],
        "VisibilityConfig":{
            "SampledRequestsEnabled":true,
            "CloudWatchMetricsEnabled":true,
            "MetricName":"test01"
        },
        "DefaultAction":{
            "Allow":{

            }
        },
        "Id":"9a1b2c3d4-5678-90ab-cdef-EXAMPLE11111  ",
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test01/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111  ",
        "Name":"test01"
    }
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「ウェブ ACL と AWS リソースの関連付けまたは関連付け解除](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-associating-aws-resource.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWebAclForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-web-acl-for-resource.html)」を参照してください。

### `get-web-acl`
<a name="wafv2_GetWebAcl_cli_2_topic"></a>

次のコード例は、`get-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL を取得するには**  
次の `get-web-acl` は、指定された名前、スコープ、および ID を持つウェブ ACL を取得します。コマンド `create-web-acl` と `list-web-acls` からウェブ ACL の ID を取得できます。  

```
aws wafv2 get-web-acl \
    --name test01 \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "WebACL":{
        "Capacity":3,
        "Description":"",
        "Rules":[
            {
                "Priority":1,
                "Action":{
                    "Block":{

                    }
                },
                "VisibilityConfig":{
                   "SampledRequestsEnabled":true,
                    "CloudWatchMetricsEnabled":true,
                    "MetricName":"testrule01"
                },
                "Name":"testrule01",
                "Statement":{
                    "AndStatement":{
                        "Statements":[
                            {
                                "ByteMatchStatement":{
                                    "PositionalConstraint":"EXACTLY",
                                    "TextTransformations":[
                                        {
                                            "Priority":0,
                                            "Type":"NONE"
                                        }
                                    ],
                                    "SearchString":"dGVzdHN0cmluZw==",
                                    "FieldToMatch":{
                                        "UriPath":{

                                        }
                                    }
                                }
                            },
                            {
                                "SizeConstraintStatement":{
                                    "ComparisonOperator":"EQ",
                                    "TextTransformations":[
                                        {
                                            "Priority":0,
                                            "Type":"NONE"
                                        }
                                    ],
                                    "FieldToMatch":{
                                        "QueryString":{

                                        }
                                    },
                                    "Size":0
                                }
                            }
                        ]
                    }
                }
            }
        ],
        "VisibilityConfig":{
            "SampledRequestsEnabled":true,
            "CloudWatchMetricsEnabled":true,
            "MetricName":"test01"
        },
        "DefaultAction":{
            "Allow":{

            }
        },
        "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test01/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "Name":"test01"
    },
    "LockToken":"e3db7e2c-d58b-4ee6-8346-6aec5511c6fb"
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、 AWS Shield Advanced Developer Guide*」の「[Managing and Using a Web Access Control List (Web ACL)](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/get-web-acl.html)」を参照してください。

### `list-available-managed-rule-groups`
<a name="wafv2_ListAvailableManagedRuleGroups_cli_2_topic"></a>

次のコード例は、`list-available-managed-rule-groups` を使用する方法を示しています。

**AWS CLI**  
**マネージドルールグループを取得するには**  
次の `list-available-managed-rule-groups` は、ウェブ ACL で使用できるマネージドルールグループすべてのリストを返します。  

```
aws wafv2 list-available-managed-rule-groups \
    --scope REGIONAL
```
出力:  

```
 {
    "ManagedRuleGroups": [
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesCommonRuleSet",
            "Description": "Contains rules that are generally applicable to web applications. This provides protection against exploitation of a wide range of vulnerabilities, including those described in OWASP publications and common Common Vulnerabilities and Exposures (CVE)."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesAdminProtectionRuleSet",
            "Description": "Contains rules that allow you to block external access to exposed admin pages. This may be useful if you are running third-party software or would like to reduce the risk of a malicious actor gaining administrative access to your application."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesKnownBadInputsRuleSet",
            "Description": "Contains rules that allow you to block request patterns that are known to be invalid and are associated with exploitation or discovery of vulnerabilities. This can help reduce the risk of a malicious actor discovering a vulnerable application."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesSQLiRuleSet",
            "Description": "Contains rules that allow you to block request patterns associated with exploitation of SQL databases, like SQL injection attacks. This can help prevent remote injection of unauthorized queries."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesLinuxRuleSet",
            "Description": "Contains rules that block request patterns associated with exploitation of vulnerabilities specific to Linux, including LFI attacks. This can help prevent attacks that expose file contents or execute code for which the attacker should not have had access."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesUnixRuleSet",
            "Description": "Contains rules that block request patterns associated with exploiting vulnerabilities specific to POSIX/POSIX-like OS, including LFI attacks. This can help prevent attacks that expose file contents or execute code for which access should not been allowed."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesWindowsRuleSet",
            "Description": "Contains rules that block request patterns associated with exploiting vulnerabilities specific to Windows, (e.g., PowerShell commands). This can help prevent exploits that allow attacker to run unauthorized commands or execute malicious code."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesPHPRuleSet",
            "Description": "Contains rules that block request patterns associated with exploiting vulnerabilities specific to the use of the PHP, including injection of unsafe PHP functions. This can help prevent exploits that allow an attacker to remotely execute code or commands."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesWordPressRuleSet",
            "Description": "The WordPress Applications group contains rules that block request patterns associated with the exploitation of vulnerabilities specific to WordPress sites."
        },
        {
            "VendorName": "AWS",
            "Name": "AWSManagedRulesAmazonIpReputationList",
            "Description": "This group contains rules that are based on Amazon threat intelligence. This is useful if you would like to block sources associated with bots or other threats."
        }
    ]
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced AWS デベロッパーガイド*」の[「マネージドルールグループ](https://docs.aws.amazon.com/waf/latest/developerguide/waf-managed-rule-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAvailableManagedRuleGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-available-managed-rule-groups.html)」を参照してください。

### `list-ip-sets`
<a name="wafv2_ListIpSets_cli_2_topic"></a>

次のコード例は、`list-ip-sets` を使用する方法を示しています。

**AWS CLI**  
**IP セットのリストを取得するには**  
次の `list-ip-sets` は、リージョンスコープを持つアカウントのすべての IP セットを取得します。  

```
aws wafv2 list-ip-sets \
    --scope REGIONAL
```
出力:  

```
{
    "IPSets":[
        {
            "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/ipset/testip/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Description":"",
            "Name":"testip",
            "LockToken":"0674c84b-0304-47fe-8728-c6bff46af8fc",
            "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111  "
        }
    ],
    "NextMarker":"testip"
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListIpSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-ip-sets.html)」を参照してください。

### `list-logging-configurations`
<a name="wafv2_ListLoggingConfigurations_cli_2_topic"></a>

次のコード例は、`list-logging-configurations` を使用する方法を示しています。

**AWS CLI**  
**リージョンのすべてのログ記録設定のリストを取得するには**  
次の `list-logging-configurations` は、`us-west-2` リージョンでリージョンでの使用がスコープされているウェブ ACL のすべてのログ記録設定を取得します。  

```
aws wafv2 list-logging-configurations \
    --scope REGIONAL \
    --region us-west-2
```
出力:  

```
{
    "LoggingConfigurations":[
        {
            "ResourceArn":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test-2/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "RedactedFields":[
                {
                    "QueryString":{

                    }
                }
            ],
            "LogDestinationConfigs":[
                "arn:aws:firehose:us-west-2:123456789012:deliverystream/aws-waf-logs-test"
            ]
        },
        {
            "ResourceArn":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "RedactedFields":[
                {
                    "Method":{

                    }
                }
            ],
            "LogDestinationConfigs":[
                "arn:aws:firehose:us-west-2:123456789012:deliverystream/aws-waf-logs-custom-transformation"
            ]
        }
    ]
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced デベロッパーガイド AWS *」の[「ウェブ ACL トラフィック情報のログ記録](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListLoggingConfigurations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-logging-configurations.html)」を参照してください。

### `list-regex-pattern-sets`
<a name="wafv2_ListRegexPatternSets_cli_2_topic"></a>

次のコード例は、`list-regex-pattern-sets` を使用する方法を示しています。

**AWS CLI**  
**正規表現パターンセットのリストを取得するには**  
次の `list-regex-pattern-sets` は、リージョン `us-west-2` で定義されているアカウントのすべての正規表現パターンセットを取得します。  

```
aws wafv2 list-regex-pattern-sets \
--scope REGIONAL \
--region us-west-2
```
出力:  

```
{
    "NextMarker":"regexPatterSet01",
    "RegexPatternSets":[
        {
            "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/regexpatternset/regexPatterSet01/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Description":"Test web-acl",
            "Name":"regexPatterSet01",
            "LockToken":"f17743f7-0000-0000-0000-19a8b93bfb01",
            "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        }
    ]
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRegexPatternSets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-regex-pattern-sets.html)」を参照してください。

### `list-resources-for-web-acl`
<a name="wafv2_ListResourcesForWebAcl_cli_2_topic"></a>

次のコード例は、`list-resources-for-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL に関連付けられたリソースを取得するには**  
次の `list-resources-for-web-acl` は、`us-west-2` リージョン内の指定されたウェブ ACL に現在関連付けられている API Gateway REST API リソースを取得します。  

```
aws wafv2 list-resources-for-web-acl \
    --web-acl-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/TestWebAcl/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --resource-type API_GATEWAY \
    --region us-west-2
```
出力:  

```
{
    "ResourceArns": [
        "arn:aws:apigateway:us-west-2::/restapis/EXAMPLE111/stages/testing"
    ]
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「ウェブ ACL と AWS リソースの関連付けまたは関連付け解除](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-associating-aws-resource.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourcesForWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-resources-for-web-acl.html)」を参照してください。

### `list-rule-groups`
<a name="wafv2_ListRuleGroups_cli_2_topic"></a>

次のコード例は、`list-rule-groups` を使用する方法を示しています。

**AWS CLI**  
**カスタムルールグループのリストを取得するには**  
次の `list-rule-groups` は、指定されたスコープとリージョンの場所のアカウントに定義されているすべてのカスタムルールグループを取得します。  

```
aws wafv2 list-rule-groups \
    --scope REGIONAL \
    --region us-west-2
```
出力:  

```
{
    "RuleGroups":[
        {
            "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/rulegroup/TestRuleGroup/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Description":"",
            "Name":"TestRuleGroup",
            "LockToken":"1eb5ec48-0000-0000-0000-ee9b906c541e",
            "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        },
        {
            "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/rulegroup/test/a1b2c3d4-5678-90ab-cdef-EXAMPLE22222",
            "Description":"",
            "Name":"test",
            "LockToken":"b0f4583e-998b-4880-9069-3fbe45738b43",
            "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE22222"
        }
    ],
    "NextMarker":"test"
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、 AWS Shield Advanced デベロッパーガイド*」の「[Managing Your Own Rule Groups](https://docs.aws.amazon.com/waf/latest/developerguide/waf-user-created-rule-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListRuleGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-rule-groups.html)」を参照してください。

### `list-tags-for-resource`
<a name="wafv2_ListTagsForResource_cli_2_topic"></a>

次の例は、`list-tags-for-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS WAF リソースのすべてのタグを取得するには**  
次の `list-tags-for-resource` は、指定されたウェブ ACL のすべてのタグキーと値のペアのリストを取得します。  

```
aws wafv2 list-tags-for-resource \
    --resource-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/testwebacl2/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
```
出力:  

```
{
    "NextMarker":"",
    "TagInfoForResource":{
        "ResourceARN":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/testwebacl2/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "TagList":[

        ]
    }
}
```
詳細については、[AWS 「 WAF](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started.html)、*AWS AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「WAF AWS *の開始方法」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-tags-for-resource.html)」を参照してください。

### `list-web-acls`
<a name="wafv2_ListWebAcls_cli_2_topic"></a>

次のコード例は、`list-web-acls` を使用する方法を示しています。

**AWS CLI**  
**スコープのウェブ ACL を取得するには**  
次の `list-web-acls` は、指定されたスコープのアカウントに定義されているすべてのウェブ ACL を取得します。  

```
aws wafv2 list-web-acls \
    --scope REGIONAL
```
出力:  

```
{
    "NextMarker":"Testt",
    "WebACLs":[
        {
            "ARN":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/Testt/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
            "Description":"sssss",
            "Name":"Testt",
            "LockToken":"7f36cb30-74ef-4cff-8cd4-a77e1aba1746",
            "Id":"a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
        }
    ]
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced デベロッパーガイド AWS *[」の「ウェブアクセスコントロールリスト (ウェブ ACL) の管理と使用](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListWebAcls](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/list-web-acls.html)」を参照してください。

### `put-logging-configuration`
<a name="wafv2_PutLoggingConfiguration_cli_2_topic"></a>

次のコード例は、`put-logging-configuration` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL にログ記録設定を追加するには**  
次の `put-logging-configuration` は、Amazon Kinesis Data Firehose ログ記録設定 `aws-waf-logs-custom-transformation` を指定されたウェブ ACL に追加します(ログから編集されるフィールドはありません)。  

```
aws wafv2 put-logging-configuration \
    --logging-configuration ResourceArn=arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test-cli/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111,LogDestinationConfigs=arn:aws:firehose:us-west-2:123456789012:deliverystream/aws-waf-logs-custom-transformation \
            --region us-west-2
```
出力:  

```
{
    "LoggingConfiguration":{
        "ResourceArn":"arn:aws:wafv2:us-west-2:123456789012:regional/webacl/test-cli/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
        "LogDestinationConfigs":[
            "arn:aws:firehose:us-west-2:123456789012:deliverystream/aws-waf-logs-custom-transformation"
        ]
    }
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、Shield Advanced デベロッパーガイド AWS *」の[「ウェブ ACL トラフィック情報のログ記録](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutLoggingConfiguration](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/put-logging-configuration.html)」を参照してください。

### `tag-resource`
<a name="wafv2_TagResource_cli_2_topic"></a>

次の例は、`tag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS WAF リソースにタグを追加するには**  
次の `tag-resource` の例では、指定されたウェブ ACL に「`Name`」のキーと「`AWSWAF`」の値セットを持つタグを追加します。  

```
aws wafv2 tag-resource \
    --resource-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/apiGatewayWebAcl/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --tags Key=Name,Value=AWSWAF
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 WAF](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started.html)、*AWS AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「WAF AWS *の開始方法」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="wafv2_UntagResource_cli_2_topic"></a>

次の例は、`untag-resource` を使用する方法を説明しています。

**AWS CLI**  
** AWS WAF リソースからタグを削除するには**  
次の `untag-resource` の例では、キー名 `KeyName` を持つタグを指定されたウェブ ACL から削除します。  

```
aws wafv2 untag-resource \
    --resource-arn arn:aws:wafv2:us-west-2:123456789012:regional/webacl/apiGatewayWebAcl/a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --tag-keys "KeyName"
```
このコマンドでは何も出力されません。  
詳細については、[AWS 「 WAF](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started.html)、*AWS AWS Firewall Manager、Shield Advanced デベロッパーガイド」の「WAF AWS *の開始方法」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/untag-resource.html)」を参照してください。

### `update-ip-set`
<a name="wafv2_UpdateIpSet_cli_2_topic"></a>

次のコード例は、`update-ip-set` を使用する方法を示しています。

**AWS CLI**  
**既存の IP セットの設定を変更するには**  
次の `update-ip-set` は、指定された IP セットの設定を更新します。この呼び出しには、呼び出しから取得できる ID、`list-ip-sets`、および呼び出しから取得できるロックトークン、`list-ip-sets` と `get-ip-set` が必要です。この呼び出しは、後続の更新に使用できるロックトークンも返します。  

```
aws wafv2 update-ip-set \
    --name testip \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --addresses 198.51.100.0/16 \
    --lock-token 447e55ac-2396-4c6d-b9f9-86b67c17f8b5
```
出力:  

```
{
    "NextLockToken": "0674c84b-0304-47fe-8728-c6bff46af8fc"
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateIpSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/update-ip-set.html)」を参照してください。

### `update-regex-pattern-set`
<a name="wafv2_UpdateRegexPatternSet_cli_2_topic"></a>

次のコード例は、`update-regex-pattern-set` を使用する方法を示しています。

**AWS CLI**  
**既存の正規表現パターンセットの設定を変更するには**  
次の `update-regex-pattern-set` は、指定された正規表現パターンセットの設定を更新します。この呼び出しには、呼び出しから取得できる ID、`list-regex-pattern-sets`、および呼び出しから取得できるロックトークン、`list-regex-pattern-sets` と `get-regex-pattern-set` が必要です。この呼び出しは、後続の更新に使用できるロックトークンも返します。  

```
aws wafv2 update-regex-pattern-set \
    --name ExampleRegex \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --regular-expression-list RegexString="^.+$"  \
    --lock-token ed207e9c-82e9-4a77-aadd-81e6173ab7eb
```
出力:  

```
{
    "NextLockToken": "12ebc73e-fa68-417d-a9b8-2bdd761a4fa5"
}
```
詳細については、[「 WAF、Firewall Manager、Shield Advanced デベロッパーガイド」の「IP セットと正規表現パターンセット](https://docs.aws.amazon.com/waf/latest/developerguide/waf-referenced-set-managing.html)」を参照してください。 *AWS AWS AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRegexPatternSet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/update-regex-pattern-set.html)」を参照してください。

### `update-rule-group`
<a name="wafv2_UpdateRuleGroup_cli_2_topic"></a>

次のコード例は、`update-rule-group` を使用する方法を示しています。

**AWS CLI**  
**カスタムルールグループを更新するには**  
次の `update-rule-group` は、既存のカスタムルールグループの可視性設定を変更します。この呼び出しには、呼び出しから取得できる ID、`list-rule-groups`、および呼び出しから取得できるロックトークン、`list-rule-groups` と `get-rule-group` が必要です。この呼び出しは、後続の更新に使用できるロックトークンも返します。  

```
aws wafv2 update-rule-group \
    --name TestRuleGroup \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --lock-token 7b3bcec2-0000-0000-0000-563bf47249f0 \
    --visibility-config SampledRequestsEnabled=false,CloudWatchMetricsEnabled=false,MetricName=TestMetricsForRuleGroup \
    --region us-west-2
```
出力:  

```
{
    "NextLockToken": "1eb5ec48-0000-0000-0000-ee9b906c541e"
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、 AWS Shield Advanced デベロッパーガイド*」の「[Managing Your Own Rule Groups](https://docs.aws.amazon.com/waf/latest/developerguide/waf-user-created-rule-groups.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateRuleGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/update-rule-group.html)」を参照してください。

### `update-web-acl`
<a name="wafv2_UpdateWebAcl_cli_2_topic"></a>

次のコード例は、`update-web-acl` を使用する方法を示しています。

**AWS CLI**  
**ウェブ ACL を更新するには**  
次の `update-web-acl` は、既存のウェブ ACL の設定を変更します。この呼び出しには、呼び出しから取得できる ID、`list-web-acls`、および呼び出し `get-web-acl` から取得できるロックトークンおよびその他の設定が必要です。この呼び出しは、後続の更新に使用できるロックトークンも返します。  

```
aws wafv2 update-web-acl \
    --name TestWebAcl \
    --scope REGIONAL \
    --id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 \
    --lock-token 2294b3a1-0000-0000-0000-a3ae04329de9 \
    --default-action Block={} \
    --visibility-config SampledRequestsEnabled=false,CloudWatchMetricsEnabled=false,MetricName=NewMetricTestWebAcl \
    --rules file://waf-rule.json \
    --region us-west-2
```
出力:  

```
{
    "NextLockToken": "714a0cfb-0000-0000-0000-2959c8b9a684"
}
```
詳細については、*AWS 「 WAF、 AWS Firewall Manager、 AWS Shield Advanced Developer Guide*」の「[Managing and Using a Web Access Control List (Web ACL)](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateWebAcl](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/wafv2/update-web-acl.html)」を参照してください。

# を使用した WorkDocs の例 AWS CLI
<a name="cli_2_workdocs_code_examples"></a>

次のコード例は、WorkDocs AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `abort-document-version-upload`
<a name="workdocs_AbortDocumentVersionUpload_cli_2_topic"></a>

次のコード例は、`abort-document-version-upload` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントバージョンのアップロードを停止するには**  
この例では、以前に開始されたドキュメントバージョンのアップロードを停止します。  
コマンド:  

```
aws workdocs abort-document-version-upload --document-id feaba64d4efdf271c2521b60a2a44a8f057e84beaabbe22f01267313209835f2 --version-id 1536773972914-ddb67663e782e7ce8455ebc962217cf9f9e47b5a9a702e5c84dcccd417da9313
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンスの*」の「[AbortDocumentVersionUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/abort-document-version-upload.html)」を参照してください。

### `activate-user`
<a name="workdocs_ActivateUser_cli_2_topic"></a>

次のコード例は、`activate-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーをアクティブ化するには**  
この例では、非アクティブなユーザーをアクティブ化します。  
コマンド:  

```
aws workdocs activate-user --user-id "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c"
```
出力:  

```
{
  "User": {
      "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
      "Username": "exampleUser",
      "EmailAddress": "exampleUser@site.awsapps.com",
      "GivenName": "Example",
      "Surname": "User",
      "OrganizationId": "d-926726012c",
      "RootFolderId": "75f67c183aa1217409ac87576a45c03a5df5e6d8c51c35c01669970538e86cd0",
      "RecycleBinFolderId": "642b7dd3e60b14204534f3df7b1959e01b5d170f8c2707f410e40a8149120a57",
      "Status": "ACTIVE",
      "Type": "MINIMALUSER",
      "CreatedTimestamp": 1521226107.747,
      "ModifiedTimestamp": 1525297406.462,
      "Storage": {
          "StorageUtilizedInBytes": 0,
          "StorageRule": {
              "StorageAllocatedInBytes": 0,
              "StorageType": "QUOTA"
          }
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ActivateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/activate-user.html)」を参照してください。

### `add-resource-permissions`
<a name="workdocs_AddResourcePermissions_cli_2_topic"></a>

次のコード例は、`add-resource-permissions` を使用する方法を示しています。

**AWS CLI**  
**リソースのアクセス許可を追加するには**  
この例では、指定されたプリンシパルのリソースにアクセス許可を追加します。  
コマンド:  

```
aws workdocs add-resource-permissions --resource-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65 --principals Id=anonymous,Type=ANONYMOUS,Role=VIEWER
```
出力:  

```
{
  "ShareResults": [
      {
          "PrincipalId": "anonymous",
          "Role": "VIEWER",
          "Status": "SUCCESS",
          "ShareId": "d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65",
          "StatusMessage": ""
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AddResourcePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/add-resource-permissions.html)」を参照してください。

### `create-comment`
<a name="workdocs_CreateComment_cli_2_topic"></a>

次のコード例は、`create-comment` を使用する方法を示しています。

**AWS CLI**  
**新しいコメントを追加するには**  
この例では、指定されたドキュメントバージョンに新しいコメントを追加します。  
コマンド:  

```
aws workdocs create-comment --document-id 15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3 --version-id 1521672507741-9f7df0ea5dd0b121c4f3564a0c7c0b4da95cd12c635d3c442af337a88e297920 --text "This is a comment."
```
出力:  

```
{
  "Comment": {
      "CommentId": "1534799058197-c7f5c84de9115875bbca93e0367bbebac609541d461636b760849b88b1609dd5",
      "ThreadId": "1534799058197-c7f5c84de9115875bbca93e0367bbebac609541d461636b760849b88b1609dd5",
      "Text": "This is a comment.",
      "Contributor": {
          "Id": "arn:aws:iam::123456789123:user/exampleUser",
          "Username": "exampleUser",
          "GivenName": "Example",
          "Surname": "User",
          "Status": "ACTIVE"
      },
      "CreatedTimestamp": 1534799058.197,
      "Status": "PUBLISHED",
      "Visibility": "PUBLIC"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateComment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/create-comment.html)」を参照してください。

### `create-custom-metadata`
<a name="workdocs_CreateCustomMetadata_cli_2_topic"></a>

次のコード例は、`create-custom-metadata` を使用する方法を示しています。

**AWS CLI**  
**カスタムメタデータを作成するには**  
この例では、指定されたドキュメントのカスタムメタデータを作成します。  
コマンド:  

```
aws workdocs create-custom-metadata --resource-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65 --custom-metadata KeyName1=example,KeyName2=example2
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateCustomMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/create-custom-metadata.html)」を参照してください。

### `create-folder`
<a name="workdocs_CreateFolder_cli_2_topic"></a>

次のコード例は、`create-folder` を使用する方法を示しています。

**AWS CLI**  
**フォルダを作成するには**  
この例では、フォルダを作成します。  
コマンド:  

```
aws workdocs create-folder --name documents --parent-folder-id 1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678
```
出力:  

```
{
  "Metadata": {
      "Id": "50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08",
      "Name": "documents",
      "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
      "ParentFolderId": "1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678",
      "CreatedTimestamp": 1534450467.622,
      "ModifiedTimestamp": 1534450467.622,
      "ResourceState": "ACTIVE",
      "Signature": "",
      "Size": 0,
      "LatestVersionSize": 0
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateFolder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/create-folder.html)」を参照してください。

### `create-labels`
<a name="workdocs_CreateLabels_cli_2_topic"></a>

次のコード例は、`create-labels` を使用する方法を示しています。

**AWS CLI**  
**ラベルを作成するには**  
この例では、ドキュメントの一連のラベルを作成します。  
コマンド:  

```
aws workdocs create-labels --resource-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65 --labels "documents" "examples" "my_documents"
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateLabels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/create-labels.html)」を参照してください。

### `create-notification-subscription`
<a name="workdocs_CreateNotificationSubscription_cli_2_topic"></a>

次のコード例は、`create-notification-subscription` を使用する方法を示しています。

**AWS CLI**  
**通知サブスクリプションを作成するには**  
次の `create-notification-subscription` の例では、指定された Amazon WorkDocs 組織の通知サブスクリプションを設定します。  

```
aws workdocs create-notification-subscription \
    --organization-id d-123456789c \
    --protocol HTTPS \
    --subscription-type ALL \
    --notification-endpoint "https://example.com/example"
```
出力:  

```
{
    "Subscription": {
        "SubscriptionId": "123ab4c5-678d-901e-f23g-45h6789j0123",
        "EndPoint": "https://example.com/example",
        "Protocol": "HTTPS"
    }
}
```
詳細については、「*Amazon WorkDocs デベロッパーガイド*」の「[通知のサブスクライブ](https://docs.aws.amazon.com/workdocs/latest/developerguide/subscribe-notifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateNotificationSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/create-notification-subscription.html)」を参照してください。

### `create-user`
<a name="workdocs_CreateUser_cli_2_topic"></a>

次のコード例は、`create-user` を使用する方法を示しています。

**AWS CLI**  
**新しいユーザーを作成するには**  
この例では、Simple AD ディレクトリまたは Microsoft AD ディレクトリに新しいユーザーを作成します。  
コマンド:  

```
aws workdocs create-user --organization-id d-926726012c --username exampleUser2 --email-address exampleUser2@site.awsapps.com --given-name example2Name --surname example2Surname --password examplePa$$w0rd
```
出力:  

```
{
  "User": {
      "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
      "Username": "exampleUser2",
      "EmailAddress": "exampleUser2@site.awsapps.com",
      "GivenName": "example2Name",
      "Surname": "example2Surname",
      "OrganizationId": "d-926726012c",
      "RootFolderId": "35b886cb17198cbd547655e58b025dff0cf34aaed638be52009567e23dc67390",
      "RecycleBinFolderId": "9858c3e9ed4c2460dde9aadb4c69fde998070dd46e5e985bd08ec6169ea249ff",
      "Status": "ACTIVE",
      "Type": "MINIMALUSER",
      "CreatedTimestamp": 1535478836.584,
      "ModifiedTimestamp": 1535478836.584,
      "Storage": {
          "StorageUtilizedInBytes": 0,
          "StorageRule": {
              "StorageAllocatedInBytes": 0,
              "StorageType": "QUOTA"
          }
      }
  }
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/create-user.html)」を参照してください。

### `deactivate-user`
<a name="workdocs_DeactivateUser_cli_2_topic"></a>

次のコード例は、`deactivate-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを非アクティブ化するには**  
この例では、アクティブなユーザーを非アクティブ化します。  
コマンド:  

```
aws workdocs deactivate-user --user-id "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c"
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeactivateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/deactivate-user.html)」を参照してください。

### `delete-comment`
<a name="workdocs_DeleteComment_cli_2_topic"></a>

次のコード例は、`delete-comment` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントのバージョンから指定されたコメントを削除するには**  
この例では、指定されたドキュメントバージョンから指定されたコメントを削除します。  
コマンド:  

```
aws workdocs delete-comment --document-id 15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3 --version-id 1521672507741-9f7df0ea5dd0b121c4f3564a0c7c0b4da95cd12c635d3c442af337a88e297920 --comment-id 1534799058197-c7f5c84de9115875bbca93e0367bbebac609541d461636b760849b88b1609dd5
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteComment](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-comment.html)」を参照してください。

### `delete-custom-metadata`
<a name="workdocs_DeleteCustomMetadata_cli_2_topic"></a>

次のコード例は、`delete-custom-metadata` を使用する方法を示しています。

**AWS CLI**  
**リソースからカスタムメタデータを削除するには**  
この例では、指定されたリソースからすべてのカスタムメタデータを削除します。  
コマンド:  

```
aws workdocs delete-custom-metadata --resource-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65 --delete-all
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteCustomMetadata](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-custom-metadata.html)」を参照してください。

### `delete-document`
<a name="workdocs_DeleteDocument_cli_2_topic"></a>

次のコード例は、`delete-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントを削除するには**  
この例は、指定されたドキュメントを削除します。  
コマンド:  

```
aws workdocs delete-document --document-id b83ed5e5b167b65ef69de9d597627ff1a0d4f07a45e67f1fab7d26b54427de0a
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-document.html)」を参照してください。

### `delete-folder-contents`
<a name="workdocs_DeleteFolderContents_cli_2_topic"></a>

次のコード例は、`delete-folder-contents` を使用する方法を示しています。

**AWS CLI**  
**フォルダの内容を削除するには**  
この例は、指定したフォルダの内容を削除します。  
コマンド:  

```
aws workdocs delete-folder-contents --folder-id 26fa8aa4ba2071447c194f7b150b07149dbdb9e1c8a301872dcd93a4735ce65d
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFolderContents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-folder-contents.html)」を参照してください。

### `delete-folder`
<a name="workdocs_DeleteFolder_cli_2_topic"></a>

次のコード例は、`delete-folder` を使用する方法を示しています。

**AWS CLI**  
**フォルダを削除するには**  
この例は、指定されたフォルダを削除します。  
コマンド:  

```
aws workdocs delete-folder --folder-id 26fa8aa4ba2071447c194f7b150b07149dbdb9e1c8a301872dcd93a4735ce65d
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteFolder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-folder.html)」を参照してください。

### `delete-labels`
<a name="workdocs_DeleteLabels_cli_2_topic"></a>

次のコード例は、`delete-labels` を使用する方法を示しています。

**AWS CLI**  
**ラベルを削除するには**  
この例では、ドキュメントから指定されたラベルを削除します。  
コマンド:  

```
aws workdocs delete-labels --resource-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65 --labels "documents" "examples"
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteLabels](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-labels.html)」を参照してください。

### `delete-notification-subscription`
<a name="workdocs_DeleteNotificationSubscription_cli_2_topic"></a>

次のコード例は、`delete-notification-subscription` を使用する方法を示しています。

**AWS CLI**  
**通知サブスクリプションを削除するには**  
次の `delete-notification-subscription` の例では、指定した通知サブスクリプションを削除します。  

```
aws workdocs delete-notification-subscription \
    --subscription-id 123ab4c5-678d-901e-f23g-45h6789j0123 \
    --organization-id d-123456789c
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkDocs デベロッパーガイド*」の「[通知のサブスクライブ](https://docs.aws.amazon.com/workdocs/latest/developerguide/subscribe-notifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteNotificationSubscription](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-notification-subscription.html)」を参照してください。

### `delete-user`
<a name="workdocs_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
この例では、ユーザーを削除します。  
コマンド:  

```
aws workdocs delete-user --user-id "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c"
```
出力:  

```
None
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/delete-user.html)」を参照してください。

### `describe-activities`
<a name="workdocs_DescribeActivities_cli_2_topic"></a>

次のコード例は、`describe-activities` を使用する方法を示しています。

**AWS CLI**  
**ユーザーアクティビティのリストを取得するには**  
この例では、指定された組織の最新のユーザーアクティビティのリストを返します。最新の 2 つのアクティビティには制限が設定されています。  
コマンド:  

```
aws workdocs describe-activities --organization-id d-926726012c --limit 2
```
出力:  

```
{
  "UserActivities": [
      {
          "Type": "DOCUMENT_VERSION_DOWNLOADED",
          "TimeStamp": 1534800122.17,
          "Initiator": {
              "Id": "arn:aws:iam::123456789123:user/exampleUser"
          },
          "ResourceMetadata": {
              "Type": "document",
              "Name": "updatedDoc",
              "Id": "15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3",
              "Owner": {
                  "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
                  "GivenName": "exampleName",
                  "Surname": "exampleSurname"
              }
          }
      },
      {
          "Type": "DOCUMENT_VERSION_VIEWED",
          "TimeStamp": 1534799079.207,
          "Initiator": {
              "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
              "GivenName": "exampleName",
              "Surname": "exampleSurname"
          },
          "ResourceMetadata": {
              "Type": "document",
              "Name": "updatedDoc",
              "Id": "15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3",
              "Owner": {
                  "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
                  "GivenName": "exampleName",
                  "Surname": "exampleSurname"
              }
          }
      }
  ],
  "Marker": "DnF1ZXJ5VGhlbkZldGNoAgAAAAAAAAS7FmlTaU1OdlFTU1h1UU00VVFIbDlRWHcAAAAAAAAJTRY3bWh5eUgzaVF1ZXN2RUE5Wm8tTTdR"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeActivities](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-activities.html)」を参照してください。

### `describe-comments`
<a name="workdocs_DescribeComments_cli_2_topic"></a>

次のコード例は、`describe-comments` を使用する方法を示しています。

**AWS CLI**  
**指定されたドキュメントバージョンのすべてのコメントを一覧表示するには**  
この例では、指定されたドキュメントバージョンのすべてのコメントを一覧表示します。  
コマンド:  

```
aws workdocs describe-comments --document-id 15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3 --version-id 1521672507741-9f7df0ea5dd0b121c4f3564a0c7c0b4da95cd12c635d3c442af337a88e297920
```
出力:  

```
{
  "Comments": [
      {
          "CommentId": "1534799058197-c7f5c84de9115875bbca93e0367bbebac609541d461636b760849b88b1609dd5",
          "ThreadId": "1534799058197-c7f5c84de9115875bbca93e0367bbebac609541d461636b760849b88b1609dd5",
          "Text": "This is a comment.",
          "Contributor": {
              "Username": "arn:aws:iam::123456789123:user/exampleUser",
              "Type": "USER"
          },
          "CreatedTimestamp": 1534799058.197,
          "Status": "PUBLISHED",
          "Visibility": "PUBLIC"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeComments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-comments.html)」を参照してください。

### `describe-document-versions`
<a name="workdocs_DescribeDocumentVersions_cli_2_topic"></a>

次のコード例は、`describe-document-versions` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントのバージョンを取得するには**  
この例では、初期化されたバージョンやソースドキュメントの URL など、指定されたドキュメントのドキュメントバージョンを取得します。  
コマンド:  

```
aws workdocs describe-document-versions --document-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65 --fields SOURCE
```
出力:  

```
{
  "DocumentVersions": [
      {
          "Id": "1534452029587-15e129dfc187505c407588df255be83de2920d733859f1d2762411d22a83e3ef",
          "Name": "exampleDoc.docx",
          "ContentType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "Size": 13922,
          "Signature": "1a23456b78901c23d4ef56gh7EXAMPLE",
          "Status": "ACTIVE",
          "CreatedTimestamp": 1534452029.587,
          "ModifiedTimestamp": 1534452029.849,
          "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
          "Source": {
              "ORIGINAL": "https://gb-us-west-2-prod-doc-source.s3.us-west-2.amazonaws.com/d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65/1534452029587-15e129dfc187505c407588df255be83de2920d733859f1d2762411d22a83e3ef?response-content-disposition=attachment%3B%20filename%2A%3DUTF-8%27%27exampleDoc29.docx&X-Amz-Algorithm=AWS1-ABCD-EFG234&X-Amz-Date=20180816T204149Z&X-Amz-SignedHeaders=host&X-Amz-Expires=900&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20180816%2Fus-west-2%2Fs3%2Faws1_request&X-Amz-Signature=01Ab2c34d567e8f90123g456hi78j901k2345678l901234mno56pqr78EXAMPLE"
          }
      },
      {
          "Id": "1529005196082-bb75fa19abc287699cb07147f75816dce43a53a10f28dc001bf61ef2fab01c59",
          "Name": "exampleDoc.pdf",
          "ContentType": "application/pdf",
          "Size": 425916,
          "Signature": "1a23456b78901c23d4ef56gh7EXAMPLE",
          "Status": "ACTIVE",
          "CreatedTimestamp": 1529005196.082,
          "ModifiedTimestamp": 1529005196.796,
          "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
          "Source": {
              "ORIGINAL": "https://gb-us-west-2-prod-doc-source.s3.us-west-2.amazonaws.com/d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65/1529005196082-bb75fa19abc287699cb07147f75816dce43a53a10f28dc001bf61ef2fab01c59?response-content-disposition=attachment%3B%20filename%2A%3DUTF-8%27%27exampleDoc29.pdf&X-Amz-Algorithm=AWS1-ABCD-EFG234&X-Amz-Date=20180816T204149Z&X-Amz-SignedHeaders=host&X-Amz-Expires=900&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20180816%2Fus-west-2%2Fs3%2Faws1_request&X-Amz-Signature=01Ab2c34d567e8f90123g456hi78j901k2345678l901234mno56pqr78EXAMPLE"
          }
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeDocumentVersions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-document-versions.html)」を参照してください。

### `describe-folder-contents`
<a name="workdocs_DescribeFolderContents_cli_2_topic"></a>

次のコード例は、`describe-folder-contents` を使用する方法を示しています。

**AWS CLI**  
**フォルダの内容を説明するには**  
この例では、ドキュメントやサブフォルダなど、指定されたフォルダのすべてのアクティブなコンテンツを日付順に昇順でソートします。  
コマンド:  

```
aws workdocs describe-folder-contents --folder-id 1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678 --sort DATE --order ASCENDING --type ALL
```
出力:  

```
{
  "Folders": [
      {
          "Id": "50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08",
          "Name": "testing",
          "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
          "ParentFolderId": "1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678",
          "CreatedTimestamp": 1534450467.622,
          "ModifiedTimestamp": 1534451113.504,
          "ResourceState": "ACTIVE",
          "Signature": "1a23456b78901c23d4ef56gh7EXAMPLE",
          "Size": 23019,
          "LatestVersionSize": 11537
      }
  ],
  "Documents": [
      {
          "Id": "d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65",
          "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
          "ParentFolderId": "1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678",
          "CreatedTimestamp": 1529005196.082,
          "ModifiedTimestamp": 1534452483.01,
          "LatestVersionMetadata": {
              "Id": "1534452029587-15e129dfc187505c407588df255be83de2920d733859f1d2762411d22a83e3ef",
              "Name": "exampleDoc.docx",
              "ContentType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
              "Size": 13922,
              "Signature": "1a23456b78901c23d4ef56gh7EXAMPLE",
              "Status": "ACTIVE",
              "CreatedTimestamp": 1534452029.587,
              "ModifiedTimestamp": 1534452029.587,
              "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c"
          },
          "ResourceState": "ACTIVE"
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeFolderContents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-folder-contents.html)」を参照してください。

### `describe-groups`
<a name="workdocs_DescribeGroups_cli_2_topic"></a>

次のコード例は、`describe-groups` を使用する方法を示しています。

**AWS CLI**  
**グループのリストを取得するには**  
次の `describe-groups` の例では、指定された Amazon WorkDocs 組織に関連付けられているグループを一覧表示します。  

```
aws workdocs describe-groups \
    --search-query "e" \
    --organization-id d-123456789c
```
出力:  

```
{
    "Groups": [
        {
            "Id": "S-1-1-11-1122222222-2222233333-3333334444-4444&d-123456789c",
            "Name": "Example Group 1"
        },
        {
            "Id": "S-1-1-11-1122222222-2222233333-3333334444-5555&d-123456789c",
            "Name": "Example Group 2"
        }
    ]
}
```
Amazon WorkDocs の詳細については、*Amazon WorkDocs 管理ガイド*の「[ Amazon WorkDocs の開始方法](https://docs.aws.amazon.com/workdocs/latest/adminguide/getting_started.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-groups.html)」を参照してください。

### `describe-notification-subscriptions`
<a name="workdocs_DescribeNotificationSubscriptions_cli_2_topic"></a>

次のコード例は、`describe-notification-subscriptions` を使用する方法を示しています。

**AWS CLI**  
**通知サブスクリプションのリストを取得するには**  
次の `describe-notification-subscriptions` の例では、指定された Amazon WorkDocs 組織の通知サブスクリプションを取得します。  

```
aws workdocs describe-notification-subscriptions \
    --organization-id d-123456789c
```
出力:  

```
{
    "Subscriptions": [
        {
            "SubscriptionId": "123ab4c5-678d-901e-f23g-45h6789j0123",
            "EndPoint": "https://example.com/example",
            "Protocol": "HTTPS"
        }
    ]
}
```
詳細については、「*Amazon WorkDocs デベロッパーガイド*」の「[通知のサブスクライブ](https://docs.aws.amazon.com/workdocs/latest/developerguide/subscribe-notifications.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeNotificationSubscriptions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-notification-subscriptions.html)」を参照してください。

### `describe-resource-permissions`
<a name="workdocs_DescribeResourcePermissions_cli_2_topic"></a>

次のコード例は、`describe-resource-permissions` を使用する方法を示しています。

**AWS CLI**  
**​リソースのアクセス許可のリストを取得するには**  
この例では、指定されたリソース (ドキュメントまたはフォルダ) のアクセス許可のリストを返します。  
コマンド:  

```
aws workdocs describe-resource-permissions --resource-id 15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3
```
出力:  

```
{
  "Principals": [
      {
          "Id": "anonymous",
          "Type": "ANONYMOUS",
          "Roles": [
              {
                  "Role": "VIEWER",
                  "Type": "DIRECT"
              }
          ]
      },
      {
          "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
          "Type": "USER",
          "Roles": [
              {
                  "Role": "OWNER",
                  "Type": "DIRECT"
              }
          ]
      },
      {
          "Id": "d-926726012c",
          "Type": "ORGANIZATION",
          "Roles": [
              {
                  "Role": "VIEWER",
                  "Type": "INHERITED"
              }
          ]
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeResourcePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-resource-permissions.html)」を参照してください。

### `describe-users`
<a name="workdocs_DescribeUsers_cli_2_topic"></a>

次のコード例は、`describe-users` を使用する方法を示しています。

**AWS CLI**  
**指定されたユーザーの詳細を取得するには**  
この例では、指定された組織内のすべてのユーザーの詳細を取得します。  
コマンド:  

```
aws workdocs describe-users --organization-id d-926726012c
```
出力:  

```
{
  "Users": [
      {
          "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
          "Username": "example1User",
          "OrganizationId": "d-926726012c",
          "RootFolderId": "3c0e3f849dd20a9771d937b9bbcc97e18796150ae56c26d64a4fa0320a2dedc9",
          "RecycleBinFolderId": "c277f4c4d647be1f5147b3184ffa96e1e2bf708278b696cacba68ba13b91f4fe",
          "Status": "INACTIVE",
          "Type": "USER",
          "CreatedTimestamp": 1535478999.452,
          "ModifiedTimestamp": 1535478999.452
      },
      {
          "Id": "S-1-1-11-1111111111-2222222222-3333333333-4444&d-926726012c",
          "Username": "example2User",
          "EmailAddress": "example2User@site.awsapps.com",
          "GivenName": "example2Name",
          "Surname": "example2Surname",
          "OrganizationId": "d-926726012c",
          "RootFolderId": "35b886cb17198cbd547655e58b025dff0cf34aaed638be52009567e23dc67390",
          "RecycleBinFolderId": "9858c3e9ed4c2460dde9aadb4c69fde998070dd46e5e985bd08ec6169ea249ff",
          "Status": "ACTIVE",
          "Type": "MINIMALUSER",
          "CreatedTimestamp": 1535478836.584,
          "ModifiedTimestamp": 1535478836.584
      }
  ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/describe-users.html)」を参照してください。

### `get-document-path`
<a name="workdocs_GetDocumentPath_cli_2_topic"></a>

次のコード例は、`get-document-path` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントのパス情報を取得するには**  
この例では、指定されたドキュメントのパス情報 (ルートフォルダからの階層) を取得し、親フォルダの名前を含めます。  
コマンド:  

```
aws workdocs get-document-path --document-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65 --fields NAME
```
出力:  

```
{
  "Path": {
      "Components": [
          {
              "Id": "a43d29cbb8e7c4d25cfee8b803a504b0dc63e760b55ad0c611c6b87691eb6ff3",
              "Name": "/"
          },
          {
              "Id": "1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678",
              "Name": "Top Level Folder"
          },
          {
              "Id": "d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65",
              "Name": "exampleDoc.docx"
          }
      ]
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDocumentPath](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/get-document-path.html)」を参照してください。

### `get-document-version`
<a name="workdocs_GetDocumentVersion_cli_2_topic"></a>

次のコード例は、`get-document-version` を使用する方法を示しています。

**AWS CLI**  
**指定されたドキュメントのバージョンのメタデータを取得するには**  
この例では、ソース URL やカスタムメタデータなど、指定されたドキュメントのバージョンメタデータを取得します。  
コマンド:  

```
aws workdocs get-document-version --document-id 15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3 --version-id 1521672507741-9f7df0ea5dd0b121c4f3564a0c7c0b4da95cd12c635d3c442af337a88e297920 --fields SOURCE --include-custom-metadata
```
出力:  

```
{
  "Metadata": {
      "Id": "1521672507741-9f7df0ea5dd0b121c4f3564a0c7c0b4da95cd12c635d3c442af337a88e297920",
      "Name": "exampleDoc",
      "ContentType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "Size": 11537,
      "Signature": "1a23456b78901c23d4ef56gh7EXAMPLE",
      "Status": "ACTIVE",
      "CreatedTimestamp": 1521672507.741,
      "ModifiedTimestamp": 1534451113.504,
      "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
      "Source": {
          "ORIGINAL": "https://gb-us-west-2-prod-doc-source.s3.us-west-2.amazonaws.com/15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3/1521672507741-9f7df0ea5dd0b121c4f3564a0c7c0b4da95cd12c635d3c442af337a88e297920?response-content-disposition=attachment%3B%20filename%2A%3DUTF-8%27%27exampleDoc&X-Amz-Algorithm=AWS1-ABCD-EFG234&X-Amz-Date=20180820T212202Z&X-Amz-SignedHeaders=host&X-Amz-Expires=900&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20180820%2Fus-west-2%2Fs3%2Faws1_request&X-Amz-Signature=01Ab2c34d567e8f90123g456hi78j901k2345678l901234mno56pqr78EXAMPLE"
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDocumentVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/get-document-version.html)」を参照してください。

### `get-document`
<a name="workdocs_GetDocument_cli_2_topic"></a>

次のコード例は、`get-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントの詳細を取得するには**  
この例では、指定されたドキュメントの詳細を取得します。  
コマンド:  

```
aws workdocs get-document --document-id d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65
```
出力:  

```
{
  "Metadata": {
      "Id": "d90d93c1fe44bad0c8471e973ebaab339090401a95e777cffa58e977d2983b65",
      "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
      "ParentFolderId": "1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678",
      "CreatedTimestamp": 1529005196.082,
      "ModifiedTimestamp": 1534452483.01,
      "LatestVersionMetadata": {
          "Id": "1534452029587-15e129dfc187505c407588df255be83de2920d733859f1d2762411d22a83e3ef",
          "Name": "exampleDoc.docx",
          "ContentType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
          "Size": 13922,
          "Signature": "1a23456b78901c23d4ef56gh7EXAMPLE",
          "Status": "ACTIVE",
          "CreatedTimestamp": 1534452029.587,
          "ModifiedTimestamp": 1534452029.587,
          "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c"
      },
      "ResourceState": "ACTIVE"
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/get-document.html)」を参照してください。

### `get-folder-path`
<a name="workdocs_GetFolderPath_cli_2_topic"></a>

次のコード例は、`get-folder-path` を使用する方法を示しています。

**AWS CLI**  
**フォルダのパス情報を取得するには**  
この例では、指定されたフォルダのパス情報 (ルートフォルダからの階層) を取得し、親フォルダの名前を含めます。  
コマンド:  

```
aws workdocs get-folder-path --folder-id 50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08 --fields NAME
```
出力:  

```
{
  "Path": {
      "Components": [
          {
              "Id": "a43d29cbb8e7c4d25cfee8b803a504b0dc63e760b55ad0c611c6b87691eb6ff3",
              "Name": "/"
          },
          {
              "Id": "1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678",
              "Name": "Top Level Folder"
          },
          {
              "Id": "50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08",
              "Name": "Sublevel Folder"
          }
      ]
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFolderPath](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/get-folder-path.html)」を参照してください。

### `get-folder`
<a name="workdocs_GetFolder_cli_2_topic"></a>

次のコード例は、`get-folder` を使用する方法を示しています。

**AWS CLI**  
**フォルダのメタデータを取得するには**  
この例は、指定されたフォルダのメタデータを取得します。  
コマンド:  

```
aws workdocs get-folder --folder-id 50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08
```
出力:  

```
{
  "Metadata": {
      "Id": "50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08",
      "Name": "exampleFolder",
      "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
      "ParentFolderId": "1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678",
      "CreatedTimestamp": 1534450467.622,
      "ModifiedTimestamp": 1534451113.504,
      "ResourceState": "ACTIVE",
      "Signature": "1a23456b78901c23d4ef56gh7EXAMPLE",
      "Size": 23019,
      "LatestVersionSize": 11537
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetFolder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/get-folder.html)」を参照してください。

### `get-resources`
<a name="workdocs_GetResources_cli_2_topic"></a>

次のコード例は、`get-resources` を使用する方法を示しています。

**AWS CLI**  
**共有リソースを取得するには**  
次の `get-resources` の例では、指定された Amazon WorkDocs ユーザーと共有されているリソースを取得します。  

```
aws workdocs get-resources \
    --user-id "S-1-1-11-1111111111-2222222222-3333333333-3333" \
    --collection-type SHARED_WITH_ME
```
出力:  

```
{
"Folders": [],
"Documents": []
}
```
詳細については、「*Amazon WorkDocs ユーザーガイド*」の「[ファイルおよびフォルダの共有](https://docs.aws.amazon.com/workdocs/latest/userguide/share-docs.html)」を参照してください。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[GetResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/get-resources.html)」を参照してください。**

### `initiate-document-version-upload`
<a name="workdocs_InitiateDocumentVersionUpload_cli_2_topic"></a>

次のコード例は、`initiate-document-version-upload` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントバージョンのアップロードを開始するには**  
次の `initiate-document-upload` の例は、新しいドキュメントオブジェクトとバージョンオブジェクトを作成します。  

```
aws workdocs initiate-document-version-upload \
    --name exampledocname \
    --parent-folder-id eacd546d952531c633452ed67cac23161aa0d5df2e8061223a59e8f67e7b6189
```
出力:  

```
{
    "Metadata": {
        "Id": "feaba64d4efdf271c2521b60a2a44a8f057e84beaabbe22f01267313209835f2",
        "CreatorId": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
        "ParentFolderId": "eacd546d952531c633452ed67cac23161aa0d5df2e8061223a59e8f67e7b6189",
        "CreatedTimestamp": 1536773972.914,
        "ModifiedTimestamp": 1536773972.914,
        "LatestVersionMetadata": {
            "Id": "1536773972914-ddb67663e782e7ce8455ebc962217cf9f9e47b5a9a702e5c84dcccd417da9313",
            "Name": "exampledocname",
            "ContentType": "application/octet-stream",
            "Size": 0,
            "Status": "INITIALIZED",
            "CreatedTimestamp": 1536773972.914,
            "ModifiedTimestamp": 1536773972.914,
            "CreatorId": "arn:aws:iam::123456789123:user/EXAMPLE"
        },
        "ResourceState": "ACTIVE"
    },
    "UploadMetadata": {
        "UploadUrl": "https://gb-us-west-2-prod-doc-source.s3.us-west-2.amazonaws.com/feaba64d4efdf271c2521b60a2a44a8f057e84beaabbe22f01267313209835f2/1536773972914-ddb67663e782e7ce8455ebc962217cf9f9e47b5a9a702e5c84dcccd417da9313?X-Amz-Algorithm=AWS1-ABCD-EFG234&X-Amz-Date=20180912T173932Z&X-Amz-SignedHeaders=content-type%3Bhost%3Bx-amz-server-side-encryption&X-Amz-Expires=899&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20180912%2Fus-west-2%2Fs3%2Faws1_request&X-Amz-Signature=01Ab2c34d567e8f90123g456hi78j901k2345678l901234mno56pqr78EXAMPLE",
        "SignedHeaders": {
            "Content-Type": "application/octet-stream",
            "x-amz-server-side-encryption": "ABC123"
        }
    }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[InitiateDocumentVersionUpload](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/initiate-document-version-upload.html)」を参照してください。

### `remove-all-resource-permissions`
<a name="workdocs_RemoveAllResourcePermissions_cli_2_topic"></a>

次のコード例は、`remove-all-resource-permissions` を使用する方法を示しています。

**AWS CLI**  
**指定されたリソースからすべてのアクセス許可を削除するには**  
この例は、指定されたリソースからすべてのアクセス許可を削除します。  
コマンド:  

```
aws workdocs remove-all-resource-permissions --resource-id 1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveAllResourcePermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/remove-all-resource-permissions.html)」を参照してください。

### `remove-resource-permission`
<a name="workdocs_RemoveResourcePermission_cli_2_topic"></a>

次のコード例は、`remove-resource-permission` を使用する方法を示しています。

**AWS CLI**  
**リソースからアクセス許可を削除するには**  
この例は、指定されたプリンシパルのリソースからすべてのアクセス許可を削除します。  
コマンド:  

```
aws workdocs remove-resource-permission --resource-id 1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678 --principal-id anonymous
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RemoveResourcePermission](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/remove-resource-permission.html)」を参照してください。

### `update-document-version`
<a name="workdocs_UpdateDocumentVersion_cli_2_topic"></a>

次のコード例は、`update-document-version` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントバージョンのステータスをアクティブに変更するには**  
この例は、ドキュメントバージョンのステータスを「アクティブ」に変更します。  
コマンド:  

```
aws workdocs update-document-version --document-id 15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3 --version-id 1521672507741-9f7df0ea5dd0b121c4f3564a0c7c0b4da95cd12c635d3c442af337a88e297920 --version-status ACTIVE
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDocumentVersion](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/update-document-version.html)」を参照してください。

### `update-document`
<a name="workdocs_UpdateDocument_cli_2_topic"></a>

次のコード例は、`update-document` を使用する方法を示しています。

**AWS CLI**  
**ドキュメントを更新するには**  
この例では、ドキュメントの名前と親フォルダを更新します。  
コマンド:  

```
aws workdocs update-document --document-id 15df51e0335cfcc6a2e4de9dd8be9f22ee40545ad9176f54758dcf903be982d3 --name updatedDoc --parent-folder-id 50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateDocument](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/update-document.html)」を参照してください。

### `update-folder`
<a name="workdocs_UpdateFolder_cli_2_topic"></a>

次のコード例は、`update-folder` を使用する方法を示しています。

**AWS CLI**  
**フォルダを作成するには**  
この例では、フォルダの名前と親フォルダを更新します。  
コマンド:  

```
aws workdocs update-folder --folder-id 50893c0af679524d1a0e0651130ed6d073e1a05f95bd12c42dcde5d35634ed08 --name exampleFolder1 --parent-folder-id 1ece93e5fe75315c7407c4967918b4fd9da87ddb2a588e67b7fdaf4a98fde678
```
出力:  

```
None
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateFolder](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/update-folder.html)」を参照してください。

### `update-user`
<a name="workdocs_UpdateUser_cli_2_topic"></a>

次のコード例は、`update-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを更新するには**  
この例では、指定されたユーザーのタイムゾーンを更新します。  
コマンド:  

```
aws workdocs update-user --user-id "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c" --time-zone-id "America/Los_Angeles"
```
出力:  

```
{
  "User": {
      "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333&d-926726012c",
      "Username": "exampleUser",
      "EmailAddress": "exampleUser@site.awsapps.com",
      "GivenName": "Example",
      "Surname": "User",
      "OrganizationId": "d-926726012c",
      "RootFolderId": "c5eceb5e1a2d1d460c9d1af8330ae117fc8d39bb1d3ed6acd0992d5ff192d986",
      "RecycleBinFolderId": "6ca20102926ad15f04b1d248d6d6e44f2449944eda5c758f9a1e9df6a6b7fa66",
      "Status": "ACTIVE",
      "Type": "USER",
      "TimeZoneId": "America/Los_Angeles",
      "Storage": {
          "StorageUtilizedInBytes": 0,
          "StorageRule": {
              "StorageAllocatedInBytes": 53687091200,
              "StorageType": "QUOTA"
          }
      }
  }
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workdocs/update-user.html)」を参照してください。

# を使用した Amazon WorkMail の例 AWS CLI
<a name="cli_2_workmail_code_examples"></a>

次のコード例は、Amazon WorkMail AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `associate-delegate-to-resource`
<a name="workmail_AssociateDelegateToResource_cli_2_topic"></a>

次のコード例は、`associate-delegate-to-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースに委任を追加するには**  
次の `associate-delegate-to-resource` コマンドは、リソースに委任を追加します。  

```
aws workmail associate-delegate-to-resource \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --resource-id r-68bf2d3b1c0244aab7264c24b9217443 \
    --entity-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateDelegateToResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/associate-delegate-to-resource.html)」を参照してください。

### `associate-member-to-group`
<a name="workmail_AssociateMemberToGroup_cli_2_topic"></a>

次のコード例は、`associate-member-to-group` を使用する方法を示しています。

**AWS CLI**  
**メンバーをグループに追加するには**  
次の `associate-member-to-group` コマンドは、指定されたメンバーをグループに追加します。  

```
aws workmail associate-member-to-group \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --group-id S-1-1-11-1122222222-2222233333-3333334444-4444 \
    --member-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[AssociateMemberToGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/associate-member-to-group.html)」を参照してください。

### `create-alias`
<a name="workmail_CreateAlias_cli_2_topic"></a>

次のコード例は、`create-alias` を使用する方法を示しています。

**AWS CLI**  
**エイリアスを作成するには**  
次の `create-alias` コマンドは、指定されたエンティティ (ユーザーまたはグループ) のエイリアスを作成します。  

```
aws workmail create-alias \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1122222222-2222233333-3333334444-4444 \
    --alias exampleAlias@site.awsapps.com
```
このコマンドでは何も出力されません。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/create-alias.html)」を参照してください。**

### `create-group`
<a name="workmail_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**新しいグループを作成するには**  
次の `create-group` コマンドを実行して、指定された組織に新しいグループを作成します。  

```
aws workmail create-group \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --name exampleGroup1
```
出力:  

```
{
    "GroupId": "S-1-1-11-1122222222-2222233333-3333334444-4444"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/create-group.html)」を参照してください。

### `create-resource`
<a name="workmail_CreateResource_cli_2_topic"></a>

次のコード例は、`create-resource` を使用する方法を示しています。

**AWS CLI**  
**新しいリソースを作成するには**  
次の `create-resource` コマンドを実行して、指定された組織に新しいリソース (会議室) を作成します。  

```
aws workmail create-resource \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --name exampleRoom1 \
    --type ROOM
```
出力:  

```
{
    "ResourceId": "r-7afe0efbade843a58cdc10251fce992c"
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[CreateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/create-resource.html)」を参照してください。**

### `create-user`
<a name="workmail_CreateUser_cli_2_topic"></a>

次のコード例は、`create-user` を使用する方法を示しています。

**AWS CLI**  
**新しいユーザーを作成するには**  
次の `create-user` コマンドは、新しいユーザーを作成します。  

```
aws workmail create-user \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --name exampleName \
    --display-name exampleDisplayName \
    --password examplePa$$w0rd
```
出力:  

```
{
    "UserId": "S-1-1-11-1111111111-2222222222-3333333333-3333"
}
```
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/create-user.html)」を参照してください。

### `delete-access-control-rule`
<a name="workmail_DeleteAccessControlRule_cli_2_topic"></a>

次のコード例は、`delete-access-control-rule` を使用する方法を示しています。

**AWS CLI**  
**アクセスコントロールルールを削除するには**  
次の `delete-access-control-rule` の例では、指定された Amazon WorkMail 組織から指定されたアクセスコントロールルールを削除します。  

```
aws workmail delete-access-control-rule \
    --organization-id m-n1pq2345678r901st2u3vx45x6789yza \
    --name "myRule"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkMail 管理ガイド*」の「[アクセスコントロールルールの使用](https://docs.aws.amazon.com/workmail/latest/adminguide/access-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteAccessControlRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/delete-access-control-rule.html)」を参照してください。

### `delete-alias`
<a name="workmail_DeleteAlias_cli_2_topic"></a>

次のコード例は、`delete-alias` を使用する方法を示しています。

**AWS CLI**  
**エイリアスを削除するには**  
次の `delete-alias` コマンドは、指定されたエンティティ (ユーザーまたはグループ) のエイリアスを削除します。  

```
aws workmail delete-alias \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1122222222-2222233333-3333334444-4444 \
    --alias exampleAlias@site.awsapps.com
```
このコマンドでは何も出力されません。  
+  API の詳細については、AWS CLI コマンドリファレンスの「[DeleteAlias](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/delete-alias.html)」を参照してください。**

### `delete-group`
<a name="workmail_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**既存のグループを削除するには**  
次の `delete-group` コマンドは、Amazon WorkMail から既存のグループを削除します。  

```
aws workmail delete-group \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --group-id S-1-1-11-1122222222-2222233333-3333334444-4444
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/delete-group.html)」を参照してください。

### `delete-mailbox-permissions`
<a name="workmail_DeleteMailboxPermissions_cli_2_topic"></a>

次のコード例は、`delete-mailbox-permissions` を使用する方法を示しています。

**AWS CLI**  
**メールボックスのアクセス許可を削除するには**  
次の `delete-mailbox-permissions` コマンドは、以前にユーザーまたはグループに付与されたメールボックスのアクセス許可を削除します。エンティティはメールボックスを所有するユーザーを表し、被付与者はアクセス許可を削除するユーザーまたはグループを表します。  

```
aws workmail delete-mailbox-permissions \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1122222222-2222233333-3333334444-4444 \
    --grantee-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteMailboxPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/delete-mailbox-permissions.html)」を参照してください。

### `delete-resource`
<a name="workmail_DeleteResource_cli_2_topic"></a>

次のコード例は、`delete-resource` を使用する方法を示しています。

**AWS CLI**  
**既存のリソースを削除するには**  
次の `delete-resource` コマンドは、Amazon WorkMail から既存のリソースを削除します。  

```
aws workmail delete-resource \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --resource-id r-7afe0efbade843a58cdc10251fce992c
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/delete-resource.html)」を参照してください。

### `delete-user`
<a name="workmail_DeleteUser_cli_2_topic"></a>

次のコード例は、`delete-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザーを削除するには**  
次の `delete-user` コマンドは、Amazon WorkMail および後続のすべてのシステムから指定されたユーザーを削除します。  

```
aws workmail delete-user \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --user-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
このコマンドでは何も出力されません。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[DeleteUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/delete-user.html)」を参照してください。

### `deregister-from-work-mail`
<a name="workmail_DeregisterFromWorkMail_cli_2_topic"></a>

次のコード例は、`deregister-from-work-mail` を使用する方法を示しています。

**AWS CLI**  
**既存のエンティティを無効にするには**  
次の `deregister-from-work-mail` コマンドは、既存のエンティティ (ユーザー、グループ、またはリソース) が Amazon WorkMail を使用できないようにします。  

```
aws workmail deregister-from-work-mail \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterFromWorkMail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/deregister-from-work-mail.html)」を参照してください。

### `describe-group`
<a name="workmail_DescribeGroup_cli_2_topic"></a>

次のコード例は、`describe-group` を使用する方法を示しています。

**AWS CLI**  
**グループの情報を取得するには**  
次の `describe-group` コマンドは、指定されたグループに関する情報を取得します。  

```
aws workmail describe-group \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --group-id S-1-1-11-1122222222-2222233333-3333334444-4444
```
出力:  

```
{
    "GroupId": "S-1-1-11-1122222222-2222233333-3333334444-4444",
    "Name": "exampleGroup1",
    "State": "ENABLED"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/describe-group.html)」を参照してください。

### `describe-organization`
<a name="workmail_DescribeOrganization_cli_2_topic"></a>

次のコード例は、`describe-organization` を使用する方法を示しています。

**AWS CLI**  
**組織の情報を取得するには**  
次の `describe-organization` コマンドは、指定された Amazon WorkMail 組織の情報を取得します。  

```
aws workmail describe-organization \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27
```
出力:  

```
{
    "OrganizationId": "m-d281d0a2fd824be5b6cd3d3ce909fd27",
    "Alias": "alias",
    "State": "Active",
    "DirectoryId": "d-926726012c",
    "DirectoryType": "VpcDirectory",
    "DefaultMailDomain": "site.awsapps.com",
    "CompletedDate": 1522693605.468,
    "ARN": "arn:aws:workmail:us-west-2:111122223333:organization/m-n1pq2345678r901st2u3vx45x6789yza"
}
```
詳細については、「*Amazon WorkMail 管理ガイド*」の「[Working with Organizations](https://docs.aws.amazon.com/workmail/latest/adminguide/organizations_overview.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeOrganization](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/describe-organization.html)」を参照してください。

### `describe-resource`
<a name="workmail_DescribeResource_cli_2_topic"></a>

次のコード例は、`describe-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースの情報を取得するには**  
次の `describe-resource` コマンドは、指定されたリソースに関する情報を取得します。  

```
aws workmail describe-resource \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --resource-id r-7afe0efbade843a58cdc10251fce992c
```
出力:  

```
{
    "ResourceId": "r-7afe0efbade843a58cdc10251fce992c",
    "Name": "exampleRoom1",
    "Type": "ROOM",
    "BookingOptions": {
        "AutoAcceptRequests": true,
        "AutoDeclineRecurringRequests": false,
        "AutoDeclineConflictingRequests": true
    },
    "State": "ENABLED"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/describe-resource.html)」を参照してください。

### `describe-user`
<a name="workmail_DescribeUser_cli_2_topic"></a>

次のコード例は、`describe-user` を使用する方法を示しています。

**AWS CLI**  
**ユーザー情報を取得するには**  
次の `describe-user` コマンドは、指定されたユーザーに関する情報を取得します。  

```
aws workmail describe-user \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --user-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
出力:  

```
{
    "UserId": "S-1-1-11-1111111111-2222222222-3333333333-3333",
    "Name": "exampleUser1",
    "Email": "exampleUser1@site.awsapps.com",
    "DisplayName": "",
    "State": "ENABLED",
    "UserRole": "USER",
    "EnabledDate": 1532459261.827
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeUser](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/describe-user.html)」を参照してください。

### `disassociate-delegate-from-resource`
<a name="workmail_DisassociateDelegateFromResource_cli_2_topic"></a>

次のコード例は、`disassociate-delegate-from-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースからタグを削除するには**  
次の `disassociate-delegate-from-resource` コマンドは、リソースから指定されたメンバーを削除します。  

```
ws workmail disassociate-delegate-from-resource \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --resource-id r-68bf2d3b1c0244aab7264c24b9217443 \
    --entity-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateDelegateFromResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/disassociate-delegate-from-resource.html)」を参照してください。

### `disassociate-member-from-group`
<a name="workmail_DisassociateMemberFromGroup_cli_2_topic"></a>

次のコード例は、`disassociate-member-from-group` を使用する方法を示しています。

**AWS CLI**  
**グループからメンバーを削除するには**  
次の `disassociate-member-from-group` コマンドは、グループから指定されたメンバーを削除します。  

```
aws workmail disassociate-member-from-group \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --group-id S-1-1-11-1122222222-2222233333-3333334444-4444 \
    --member-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DisassociateMemberFromGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/disassociate-member-from-group.html)」を参照してください。

### `get-access-control-effect`
<a name="workmail_GetAccessControlEffect_cli_2_topic"></a>

次のコード例は、`get-access-control-effect` を使用する方法を示しています。

**AWS CLI**  
**アクセスコントロールルールの効果を得るには**  
次の `get-access-control-effect` 例では、指定された IP アドレス、アクセスプロトコルアクション、およびユーザー ID に対する、指定された Amazon WorkMail 組織のアクセスコントロールルールの効果を取得します。  

```
aws workmail get-access-control-effect \
    --organization-id m-n1pq2345678r901st2u3vx45x6789yza \
    --ip-address "192.0.2.0" \
    --action "WindowsOutlook" \
    --user-id "S-1-1-11-1111111111-2222222222-3333333333-3333"
```
出力:  

```
{
    "Effect": "DENY",
    "MatchedRules": [
        "myRule"
    ]
}
```
詳細については、「*Amazon WorkMail 管理ガイド*」の「[アクセスコントロールルールの使用](https://docs.aws.amazon.com/workmail/latest/adminguide/access-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetAccessControlEffect](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/get-access-control-effect.html)」を参照してください。

### `get-mailbox-details`
<a name="workmail_GetMailboxDetails_cli_2_topic"></a>

次のコード例は、`get-mailbox-details` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのメールボックスの詳細を取得するには**  
次の `get-mailbox-details` コマンドは、指定されたユーザーのメールボックスの詳細を取得します。  

```
aws workmail get-mailbox-details \
    --organization-id m-n1pq2345678r901st2u3vx45x6789yza \
    --user-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
出力:  

```
{
    "MailboxQuota": 51200,
    "MailboxSize": 0.03890800476074219
}
```
詳細については、「*Amazon WorkMail 管理者ガイド*」の「[ユーザーアカウントの管理](https://docs.aws.amazon.com/workmail/latest/adminguide/manage-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetMailboxDetails](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/get-mailbox-details.html)」を参照してください。

### `list-access-control-rules`
<a name="workmail_ListAccessControlRules_cli_2_topic"></a>

次のコード例は、`list-access-control-rules` を使用する方法を示しています。

**AWS CLI**  
**アクセスコントロールルールを一覧表示するには**  
次の `list-access-control-rules` の例では、指定された Amazon WorkMail 組織のアクセスコントロールルールを一覧表示します。  

```
aws workmail list-access-control-rules \
    --organization-id m-n1pq2345678r901st2u3vx45x6789yza
```
出力:  

```
{
    "Rules": [
        {
            "Name": "default",
            "Effect": "ALLOW",
            "Description": "Default WorkMail Rule",
            "DateCreated": 0.0,
            "DateModified": 0.0
        },
        {
            "Name": "myRule",
            "Effect": "DENY",
            "Description": "my rule",
            "UserIds": [
            "S-1-1-11-1111111111-2222222222-3333333333-3333"
            ],
            "DateCreated": 1581635628.0,
            "DateModified": 1581635628.0
        }
    ]
}
```
詳細については、「*Amazon WorkMail 管理ガイド*」の「[アクセスコントロールルールの使用](https://docs.aws.amazon.com/workmail/latest/adminguide/access-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListAccessControlRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-access-control-rules.html)」を参照してください。

### `list-aliases`
<a name="workmail_ListAliases_cli_2_topic"></a>

次のコード例は、`list-aliases` を使用する方法を示しています。

**AWS CLI**  
**メンバーのエイリアスを一覧表示するには**  
次の `list-aliases` コマンドは、指定されたメンバー (ユーザーまたはグループ) のエイリアスを一覧表示します。  

```
aws workmail list-aliases \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
出力:  

```
{
    "Aliases": [
        "exampleAlias@site.awsapps.com",
        "exampleAlias1@site.awsapps.com"
    ]
}
```
+  API の詳細については、AWS CLI コマンドリファレンスの「[ListAliases](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-aliases.html)」を参照してください。**

### `list-group-members`
<a name="workmail_ListGroupMembers_cli_2_topic"></a>

次のコード例は、`list-group-members` を使用する方法を示しています。

**AWS CLI**  
**グループメンバーを一覧表示するには**  
次の `list-group-members` コマンドは、指定されたグループのメンバーを一覧表示します。  

```
aws workmail list-group-members \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --group-id S-1-1-11-1122222222-2222233333-3333334444-4444
```
出力:  

```
{
    "Members": [
        {
            "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333",
            "Name": "exampleUser1",
            "Type": "USER",
            "State": "ENABLED",
            "EnabledDate": 1532459261.827
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroupMembers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-group-members.html)」を参照してください。

### `list-groups`
<a name="workmail_ListGroups_cli_2_topic"></a>

次のコード例は、`list-groups` を使用する方法を示しています。

**AWS CLI**  
**グループのリストを取得するには**  
次の `list-groups` コマンドは、指定された組織内のグループの概要を取得します。  

```
aws workmail list-groups \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27
```
出力:  

```
{
    "Groups": [
        {
            "Id": "S-1-1-11-1122222222-2222233333-3333334444-4444",
            "Name": "exampleGroup1",
            "State": "DISABLED"
        },
        {
            "Id": "S-4-4-44-1122222222-2222233333-3333334444-4444",
            "Name": "exampleGroup2",
            "State": "ENABLED"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-groups.html)」を参照してください。

### `list-mailbox-permissions`
<a name="workmail_ListMailboxPermissions_cli_2_topic"></a>

次のコード例は、`list-mailbox-permissions` を使用する方法を示しています。

**AWS CLI**  
**メールボックスのアクセス許可を取得するには**  
次の `list-mailbox-permissions` コマンドは、指定されたエンティティのメールボックスに関連付けられたメールボックスのアクセス許可を取得します。  

```
aws workmail list-mailbox-permissions \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1111111111-2222222222-3333333333-3333
```
出力:  

```
{
    "Permissions": [
        {
            "GranteeId": "S-1-1-11-1122222222-2222233333-3333334444-4444",
            "GranteeType": "USER",
            "PermissionValues": [
                "FULL_ACCESS"
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListMailboxPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-mailbox-permissions.html)」を参照してください。

### `list-organizations`
<a name="workmail_ListOrganizations_cli_2_topic"></a>

次のコード例は、`list-organizations` を使用する方法を示しています。

**AWS CLI**  
**Organizations のリストを取得するには**  
次の `list-organizations` コマンドは、お客様の組織の概要を取得します。  

```
aws workmail list-organizations
```
出力:  

```
{
    "OrganizationSummaries": [
        {
            "OrganizationId": "m-d281d0a2fd824be5b6cd3d3ce909fd27",
            "Alias": "exampleAlias",
            "State": "Active"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListOrganizations](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-organizations.html)」を参照してください。

### `list-resource-delegates`
<a name="workmail_ListResourceDelegates_cli_2_topic"></a>

次のコード例は、`list-resource-delegates` を使用する方法を示しています。

**AWS CLI**  
**リソースの委任を一覧表示するには**  
次の `list-resource-delegates` コマンドは、指定されたリソースに関連付けられている委任を取得します。  

```
aws workmail list-resource-delegates \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --resource-id r-68bf2d3b1c0244aab7264c24b9217443
```
出力:  

```
{
    "Delegates": [
        {
            "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333",
            "Type": "USER"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResourceDelegates](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-resource-delegates.html)」を参照してください。

### `list-resources`
<a name="workmail_ListResources_cli_2_topic"></a>

次のコード例は、`list-resources` を使用する方法を示しています。

**AWS CLI**  
**リソースのリストを取得するには**  
次の `list-resources` コマンドは、指定された組織のリソースの概要を取得します。  

```
aws workmail list-resources \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27
```
出力:  

```
{
    "Resources": [
        {
            "Id": "r-7afe0efbade843a58cdc10251fce992c",
            "Name": "exampleRoom1",
            "Type": "ROOM",
            "State": "ENABLED"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-resources.html)」を参照してください。

### `list-tags-for-resource`
<a name="workmail_ListTagsForResource_cli_2_topic"></a>

次のコード例は、`list-tags-for-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを一覧表示するには**  
次の `list-tags-for-resource` 例では、指定された Amazon WorkMail 組織のタグを一覧表示します。  

```
aws workmail list-tags-for-resource \
    --resource-arn arn:aws:workmail:us-west-2:111122223333:organization/m-n1pq2345678r901st2u3vx45x6789yza
```
出力:  

```
{
    "Tags": [
        {
            "Key": "priority",
            "Value": "1"
        }
    ]
}
```
詳細については、「*Amazon WorkMail 管理者ガイド*」の「[組織のタグ付け](https://docs.aws.amazon.com/workmail/latest/adminguide/org-tag.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[ListTagsForResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-tags-for-resource.html)」を参照してください。

### `list-users`
<a name="workmail_ListUsers_cli_2_topic"></a>

次のコード例は、`list-users` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのリストを取得するには**  
次の `list-users` コマンドは、指定された組織内のユーザーの概要を取得します。  

```
aws workmail list-users \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27
```
出力:  

```
{
    "Users": [
        {
            "Id": "S-1-1-11-1111111111-2222222222-3333333333-3333",
            "Email": "exampleUser1@site.awsapps.com",
            "Name": "exampleUser1",
            "State": "ENABLED",
            "UserRole": "USER",
            "EnabledDate": 1532459261.827
        },
        {
            "Id": "S-1-1-11-1122222222-2222233333-3333334444-4444",
            "Name": "exampleGuestUser",
            "State": "DISABLED",
            "UserRole": "SYSTEM_USER"
        }
    ]
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ListUsers](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-users.html)」を参照してください。

### `put-access-control-rule`
<a name="workmail_PutAccessControlRule_cli_2_topic"></a>

次のコード例は、`put-access-control-rule` を使用する方法を示しています。

**AWS CLI**  
新しいアクセスコントロールルールを配置するには  
次の `put-access-control-rule` の例では、指定された Amazon WorkMail 組織への指定されたユーザーアクセスを拒否します。  

```
aws workmail put-access-control-rule \
    --name "myRule" \
    --effect "DENY" \
    --description "my rule" \
    --user-ids "S-1-1-11-1111111111-2222222222-3333333333-3333" \
    --organization-id m-n1pq2345678r901st2u3vx45x6789yza
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkMail 管理ガイド*」の「[アクセスコントロールルールの使用](https://docs.aws.amazon.com/workmail/latest/adminguide/access-rules.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutAccessControlRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/put-access-control-rule.html)」を参照してください。

### `put-mailbox-permissions`
<a name="workmail_PutMailboxPermissions_cli_2_topic"></a>

次のコード例は、`put-mailbox-permissions` を使用する方法を示しています。

**AWS CLI**  
**メールボックスのアクセス許可を設定するには**  
次の `put-mailbox-permissions` コマンドは、指定された被付与者 (ユーザーまたはグループ) にフルアクセス許可を設定します。エンティティはメールボックスの所有者を表します。  

```
aws workmail put-mailbox-permissions \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1111111111-2222222222-3333333333-3333 \
    --grantee-id S-1-1-11-1122222222-2222233333-3333334444-4444 \
    --permission-values FULL_ACCESS
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutMailboxPermissions](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/put-mailbox-permissions.html)」を参照してください。

### `register-to-work-mail`
<a name="workmail_RegisterToWorkMail_cli_2_topic"></a>

次のコード例は、`register-to-work-mail` を使用する方法を示しています。

**AWS CLI**  
**既存のエンティティまたは無効化されたエンティティを登録するには**  
次の `register-to-work-mail` コマンドは、指定された既存のエンティティ (ユーザー、グループ、またはリソース) が Amazon WorkMail を使用できるようにします。  

```
aws workmail register-to-work-mail \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1122222222-2222233333-3333334444-4444 \
    --email exampleGroup1@site.awsapps.com
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterToWorkMail](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/register-to-work-mail.html)」を参照してください。

### `reset-password`
<a name="workmail_ResetPassword_cli_2_topic"></a>

次のコード例は、`reset-password` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのパスワードをリセットするには**  
次の `reset-password` コマンドは、指定されたユーザーのパスワードをリセットします。  

```
aws workmail reset-password \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --user-id S-1-1-11-1111111111-2222222222-3333333333-3333 \
    --password examplePa$$w0rd
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ResetPassword](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/reset-password.html)」を参照してください。

### `tag-resource`
<a name="workmail_TagResource_cli_2_topic"></a>

次のコード例は、`tag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースにタグを適用するには**  
次の `tag-resource` の例では、キー「priority」と値「1」のタグを指定された Amazon WorkMail 組織に適用します。  

```
aws workmail tag-resource \
    --resource-arn arn:aws:workmail:us-west-2:111122223333:organization/m-n1pq2345678r901st2u3vx45x6789yza \
    --tags "Key=priority,Value=1"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkMail 管理者ガイド*」の「[組織のタグ付け](https://docs.aws.amazon.com/workmail/latest/adminguide/org-tag.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/tag-resource.html)」を参照してください。

### `untag-resource`
<a name="workmail_UntagResource_cli_2_topic"></a>

次のコード例は、`untag-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースのタグを削除するには**  
次の `untag-resource` の例では、指定された Amazon WorkMail 組織から指定されたタグを削除します。  

```
aws workmail untag-resource \
    --resource-arn arn:aws:workmail:us-west-2:111122223333:organization/m-n1pq2345678r901st2u3vx45x6789yza \
    --tag-keys "priority"
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkMail 管理者ガイド*」の「[組織のタグ付け](https://docs.aws.amazon.com/workmail/latest/adminguide/org-tag.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[UntagResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/untag-resource.html)」を参照してください。

### `update-mailbox-quota`
<a name="workmail_UpdateMailboxQuota_cli_2_topic"></a>

次のコード例は、`update-mailbox-quota` を使用する方法を示しています。

**AWS CLI**  
**ユーザーのメールボックスクォータを更新するには**  
次の `update-mailbox-quota` コマンドは、指定されたユーザーのメールボックスクォータを変更します。  

```
aws workmail update-mailbox-quota \
    --organization-id m-n1pq2345678r901st2u3vx45x6789yza \
    --user-id S-1-1-11-1111111111-2222222222-3333333333-3333 \
    --mailbox-quota 40000
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkMail 管理者ガイド*」の「[ユーザーアカウントの管理](https://docs.aws.amazon.com/workmail/latest/adminguide/manage-users.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateMailboxQuota](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/update-mailbox-quota.html)」を参照してください。

### `update-primary-email-address`
<a name="workmail_UpdatePrimaryEmailAddress_cli_2_topic"></a>

次のコード例は、`update-primary-email-address` を使用する方法を示しています。

**AWS CLI**  
**プライマリ E メールアドレスを更新するには**  
次の `update-primary-email-address` コマンドは、指定されたエンティティ (ユーザー、グループ、またはリソース) のプライマリ E メールアドレスを更新します。  

```
aws workmail update-primary-email-address \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --entity-id S-1-1-11-1111111111-2222222222-3333333333-3333 \
    --email exampleUser2@site.awsapps.com
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdatePrimaryEmailAddress](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/update-primary-email-address.html)」を参照してください。

### `update-resource`
<a name="workmail_UpdateResource_cli_2_topic"></a>

次のコード例は、`update-resource` を使用する方法を示しています。

**AWS CLI**  
**リソースを更新するには**  
次の `update-resource` コマンドは、指定されたリソースの名前を更新します。  

```
aws workmail update-resource \
    --organization-id m-d281d0a2fd824be5b6cd3d3ce909fd27 \
    --resource-id r-7afe0efbade843a58cdc10251fce992c \
    --name exampleRoom2
```
このコマンドでは何も出力されません。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/update-resource.html)」を参照してください。

# を使用した Amazon WorkMail メッセージフローの例 AWS CLI
<a name="cli_2_workmailmessageflow_code_examples"></a>

次のコード例は、Amazon WorkMail メッセージフロー AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `get-raw-message-content`
<a name="workmailmessageflow_GetRawMessageContent_cli_2_topic"></a>

次のコード例は、`get-raw-message-content` を使用する方法を示しています。

**AWS CLI**  
**E メールメッセージの raw コンテンツを取得するには**  
次の `get-raw-message-content` の例では、転送中の E メールメッセージの未加工コンテンツを取得し、`test` という名前のテキストファイルに送信します。  

```
aws workmailmessageflow get-raw-message-content \
    --message-id a1b2cd34-ef5g-6h7j-kl8m-npq9012345rs \
    test
```
コマンド実行後の `test` ファイルの内容:  

```
Subject: Hello World
From: =?UTF-8?Q?marymajor_marymajor?= <marymajor@example.com>
To: =?UTF-8?Q?mateojackson=40example=2Enet?= <mateojackson@example.net>
Date: Thu, 7 Nov 2019 19:22:46 +0000
Mime-Version: 1.0
Content-Type: multipart/alternative;
 boundary="=_EXAMPLE+"
References: <mail.1ab23c45.5de6.7f890g123hj45678@storage.wm.amazon.com>
X-Priority: 3 (Normal)
X-Mailer: Amazon WorkMail
Thread-Index: EXAMPLE
Thread-Topic: Hello World
Message-Id: <mail.1ab23c45.5de6.7f890g123hj45678@storage.wm.amazon.com>

This is a multi-part message in MIME format. Your mail reader does not
understand MIME message format.
--=_EXAMPLE+
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit

hello world


--=_EXAMPLE+
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable

<!DOCTYPE HTML><html>
<head>
<meta name=3D"Generator" content=3D"Amazon WorkMail v3.0-4510">
<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf-8">=

<title>testing</title>
</head>
<body>
<p style=3D"margin: 0px; font-family: Arial, Tahoma, Helvetica, sans-seri=
f; font-size: small;">hello world</p>
</body>
</html>
--=_EXAMPLE+--
```
詳細については、[「Amazon WorkMail 管理者ガイド」の AWS 「Lambda を使用したメッセージコンテンツの取得](https://docs.aws.amazon.com/workmail/latest/adminguide/lambda-content.html)」を参照してください。 *Amazon WorkMail *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetRawMessageContent](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmailmessageflow/get-raw-message-content.html)」を参照してください。

# を使用した WorkSpaces の例 AWS CLI
<a name="cli_2_workspaces_code_examples"></a>

次のコード例は、WorkSpaces AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `create-tags`
<a name="workspaces_CreateTags_cli_2_topic"></a>

次のコード例は、`create-tags` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace にタグを追加するには**  
次の `create-tags` の例では、指定された WorkSpace に指定されたタグを追加します。  

```
aws workspaces create-tags \
    --resource-id ws-dk1xzr417 \
    --tags Key=Department,Value=Finance
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkSpaces 管理ガイド*」の「[WorkSpaces リソースのタグ付け](https://docs.aws.amazon.com/workspaces/latest/adminguide/tag-workspaces-resources.html)」を参照してください。  
+  API の詳細については、「AWS CLI コマンドリファレンス」の「[CreateTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/create-tags.html)」を参照してください。

### `create-workspaces`
<a name="workspaces_CreateWorkspaces_cli_2_topic"></a>

次のコード例は、`create-workspaces` を使用する方法を示しています。

**AWS CLI**  
**例 1: AlwaysOn WorkSpace を作成するには**  
次の `create-workspaces` の例では、指定されたディレクトリとバンドルを使用して、指定されたユーザーの AlwaysOn WorkSpace を作成します。  

```
aws workspaces create-workspaces \
    --workspaces DirectoryId=d-926722edaf,UserName=Mateo,BundleId=wsb-0zsvgp8fc
```
出力:  

```
{
    "FailedRequests": [],
    "PendingRequests": [
        {
            "WorkspaceId": "ws-kcqms853t",
            "DirectoryId": "d-926722edaf",
            "UserName": "Mateo",
            "State": "PENDING",
            "BundleId": "wsb-0zsvgp8fc"
        }
    ]
}
```
**例 2: AutoStop WorkSpace を作成するには**  
次の `create-workspaces` の例では、指定されたディレクトリとバンドルを使用して、指定されたユーザーの AutoStop WorkSpace を作成します。  

```
aws workspaces create-workspaces \
    --workspaces DirectoryId=d-926722edaf,UserName=Mary,BundleId=wsb-0zsvgp8fc,WorkspaceProperties={RunningMode=AUTO_STOP}
```
出力:  

```
{
    "FailedRequests": [],
    "PendingRequests": [
        {
            "WorkspaceId": "ws-dk1xzr417",
            "DirectoryId": "d-926722edaf",
            "UserName": "Mary",
            "State": "PENDING",
            "BundleId": "wsb-0zsvgp8fc"
        }
    ]
}
```
**例 3: ユーザーデカップリング WorkSpace を作成するには**  
次の `create-workspaces` の例では、ユーザー名を に設定し`[UNDEFINED]`、WorkSpace 名、ディレクトリ ID、バンドル ID を指定して、ユーザーが分離した WorkSpace を作成します。  

```
aws workspaces create-workspaces \
    --workspaces DirectoryId=d-926722edaf,UserName='"[UNDEFINED]"',WorkspaceName=MaryWorkspace1,BundleId=wsb-0zsvgp8fc,WorkspaceProperties={RunningMode=ALWAYS_ON}
```
出力:  

```
{
    "FailedRequests": [],
    "PendingRequests": [
        {
            "WorkspaceId": "ws-abcd1234",
            "DirectoryId": "d-926722edaf",
            "UserName": "[UNDEFINED]",
            "State": "PENDING",
            "BundleId": "wsb-0zsvgp8fc",
            "WorkspaceName": "MaryWorkspace1"
        }
    ]
}
```
詳細については、「*Amazon WorkSpaces 管理ガイド*」の「[仮想デスクトップの起動](https://docs.aws.amazon.com/workspaces/latest/adminguide/launch-workspaces-tutorials.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/create-workspaces.html)」を参照してください。

### `delete-tags`
<a name="workspaces_DeleteTags_cli_2_topic"></a>

次のコード例は、`delete-tags` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace からタグを削除するには**  
次の `delete-tags` の例では、指定された WorkSpace から指定されたタグを削除します。  

```
aws workspaces delete-tags \
    --resource-id ws-dk1xzr417 \
    --tag-keys Department
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkSpaces 管理ガイド*」の「[WorkSpaces リソースのタグ付け](https://docs.aws.amazon.com/workspaces/latest/adminguide/tag-workspaces-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/delete-tags.html)」を参照してください。

### `deregister-workspace-directory`
<a name="workspaces_DeregisterWorkspaceDirectory_cli_2_topic"></a>

次のコード例は、`deregister-workspace-directory` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリの登録を解除するには**  
次の `deregister-workspace-directory` の例では、指定されたディレクトリを登録解除します。  

```
aws workspaces deregister-workspace-directory \
    --directory-id d-926722edaf
```
このコマンドでは何も出力されません。  
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/register-deregister-directory.html)」の「*WorkSpaces でディレクトリを登録する*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeregisterWorkspaceDirectory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/deregister-workspace-directory.html)」を参照してください。

### `describe-tags`
<a name="workspaces_DescribeTags_cli_2_topic"></a>

次のコード例は、`describe-tags` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace のタグを記述するには**  
次の `describe-tags` の例では、指定した WorkSpace のタグについて説明します。  

```
aws workspaces describe-tags \
    --resource-id ws-dk1xzr417
```
出力:  

```
{
    "TagList": [
        {
            "Key": "Department",
            "Value": "Finance"
        }
    ]
}
```
詳細については、「*Amazon WorkSpaces 管理ガイド*」の「[WorkSpaces リソースのタグ付け](https://docs.aws.amazon.com/workspaces/latest/adminguide/tag-workspaces-resources.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeTags](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-tags.html)」を参照してください。

### `describe-workspace-bundles`
<a name="workspaces_DescribeWorkspaceBundles_cli_2_topic"></a>

次のコード例は、`describe-workspace-bundles` を使用する方法を示しています。

**AWS CLI**  
**Amazon が提供するバンドルを一覧表示するには**  
次の `describe-workspace-bundles` の例では、Amazon が提供するバンドルの名前と ID を、テーブル形式で名前でソートして一覧表示します。  

```
aws workspaces describe-workspace-bundles \
    --owner AMAZON \
    --query "Bundles[*].[Name, BundleId]"
```
出力:  

```
[
    [
        "Standard with Amazon Linux 2",
        "wsb-clj85qzj1"
    ],
    [
        "Performance with Windows 10 (Server 2016 based)",
        "wsb-gm4d5tx2v"
    ],
    [
        "PowerPro with Windows 7",
        "wsb-1pzkp0bx4"
    ],
    [
        "Power with Amazon Linux 2",
        "wsb-2bs6k5lgn"
    ],
    [
        "Graphics with Windows 10 (Server 2019 based)",
        "wsb-03gyjnfyy"
    ],
    ...
]
```
詳細については、「*Amazon WorkSpaces 管理ガイド*」の「[WorkSpaces バンドルとイメージ](https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces-bundles.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeWorkspaceBundles](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspace-bundles.html)」を参照してください。

### `describe-workspace-directories`
<a name="workspaces_DescribeWorkspaceDirectories_cli_2_topic"></a>

次のコード例は、`describe-workspace-directories` を使用する方法を示しています。

**AWS CLI**  
**登録済みディレクトリを記述するには**  
次の `describe-workspace-directories` の例では、指定された登録ディレクトリについて説明します。  

```
aws workspaces describe-workspace-directories \
    --directory-ids d-926722edaf
```
出力:  

```
{
    "Directories": [
        {
            "DirectoryId": "d-926722edaf",
            "Alias": "d-926722edaf",
            "DirectoryName": "example.com",
            "RegistrationCode": "WSpdx+9RJ8JT",
            "SubnetIds": [
                "subnet-9d19c4c6",
                "subnet-500d5819"
            ],
            "DnsIpAddresses": [
                "172.16.1.140",
                "172.16.0.30"
            ],
            "CustomerUserName": "Administrator",
            "IamRoleId": "arn:aws:iam::123456789012:role/workspaces_DefaultRole",
            "DirectoryType": "SIMPLE_AD",
            "WorkspaceSecurityGroupId": "sg-0d89e927e5645d7c5",
            "State": "REGISTERED",
            "WorkspaceCreationProperties": {
                "EnableInternetAccess": false,
                "UserEnabledAsLocalAdministrator": true,
                "EnableMaintenanceMode": true
            },
            "WorkspaceAccessProperties": {
                "DeviceTypeWindows": "ALLOW",
                "DeviceTypeOsx": "ALLOW",
                "DeviceTypeWeb": "DENY",
                "DeviceTypeIos": "ALLOW",
                "DeviceTypeAndroid": "ALLOW",
                "DeviceTypeChromeOs": "ALLOW",
                "DeviceTypeZeroClient": "ALLOW",
                "DeviceTypeLinux": "DENY"
            },
            "Tenancy": "SHARED",
            "SelfservicePermissions": {
                "RestartWorkspace": "ENABLED",
                "IncreaseVolumeSize": "DISABLED",
                "ChangeComputeType": "DISABLED",
                "SwitchRunningMode": "DISABLED",
                "RebuildWorkspace": "DISABLED"
            }
        }
    ]
}
```
詳細については、「*Amazon WorkSpaces 管理ガイド*」の「[Manage directories for WorkSpaces Personal](https://docs.aws.amazon.com/workspaces/latest/adminguide/manage-workspaces-directory.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeWorkspaceDirectories](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspace-directories.html)」を参照してください。

### `describe-workspaces-connection-status`
<a name="workspaces_DescribeWorkspacesConnectionStatus_cli_2_topic"></a>

次のコード例は、`describe-workspaces-connection-status` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace の接続ステータスの説明を表示するには**  
次の `describe-workspaces-connection-status` の例では、指定した WorkSpace の接続ステータスについて説明します。  

```
aws workspaces describe-workspaces-connection-status \
    --workspace-ids ws-dk1xzr417
```
出力:  

```
{
    "WorkspacesConnectionStatus": [
        {
            "WorkspaceId": "ws-dk1xzr417",
            "ConnectionState": "CONNECTED",
            "ConnectionStateCheckTimestamp": 1662526214.744
        }
    ]
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/administer-workspaces.html)」の「*Amazon WorkSpaces の管理*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeWorkspacesConnectionStatus](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspaces-connection-status.html)」を参照してください。

### `describe-workspaces`
<a name="workspaces_DescribeWorkspaces_cli_2_topic"></a>

次のコード例は、`describe-workspaces` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace を記述するには**  
次の `describe-workspaces` の例では、指定した WorkSpace について説明します。  

```
aws workspaces describe-workspaces \
    --workspace-ids ws-dk1xzr417
```
出力:  

```
{
    "Workspaces": [
        {
            "WorkspaceId": "ws-dk1xzr417",
            "DirectoryId": "d-926722edaf",
            "UserName": "Mary",
            "IpAddress": "172.16.0.175",
            "State": "STOPPED",
            "BundleId": "wsb-0zsvgp8fc",
            "SubnetId": "subnet-500d5819",
            "ComputerName": "WSAMZN-RBSLTTD9",
            "WorkspaceProperties": {
                "RunningMode": "AUTO_STOP",
                "RunningModeAutoStopTimeoutInMinutes": 60,
                "RootVolumeSizeGib": 80,
                "UserVolumeSizeGib": 10,
                "ComputeTypeName": "VALUE"
            },
            "ModificationStates": []
        }
    ]
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/administer-workspaces.html)」の「*Amazon WorkSpaces の管理*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DescribeWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/describe-workspaces.html)」を参照してください。

### `migrate-workspace`
<a name="workspaces_MigrateWorkspace_cli_2_topic"></a>

次のコード例は、`migrate-workspace` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace を移行するには**  
次の `migrate-workspace` の例では、指定された WorkSpace を指定されたバンドルに移行します。  

```
aws workspaces migrate-workspace \
    --source-workspace-id ws-dk1xzr417 \
    --bundle-id wsb-j4dky1gs4
```
出力:  

```
{
    "SourceWorkspaceId": "ws-dk1xzr417",
    "TargetWorkspaceId": "ws-x5h1lbkp5"
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/migrate-workspaces.html)」の「*WorkSpaces の移行*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[MigrateWorkspace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/migrate-workspace.html)」を参照してください。

### `modify-workspace-creation-properties`
<a name="workspaces_ModifyWorkspaceCreationProperties_cli_2_topic"></a>

次のコード例は、`modify-workspace-creation-properties` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリの WorkSpace 作成プロパティを変更するには**  
次の `modify-workspace-creation-properties` の例では、指定されたディレクトリの `EnableInternetAccess` プロパティを有効にします。これにより、 ディレクトリ用に作成された WorkSpaces のパブリック IP アドレスを自動的に割り当てることができます。  

```
aws workspaces modify-workspace-creation-properties \
    --resource-id d-926722edaf \
    --workspace-creation-properties EnableInternetAccess=true
```
このコマンドでは何も出力されません。  
詳細については、「*Amazon WorkSpaces 管理ガイド*」の「[WorkSpaces のディレクトリ詳細を更新する](https://docs.aws.amazon.com/workspaces/latest/adminguide/update-directory-details.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyWorkspaceCreationProperties](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/modify-workspace-creation-properties.html)」を参照してください。

### `modify-workspace-properties`
<a name="workspaces_ModifyWorkspaceProperties_cli_2_topic"></a>

次のコード例は、`modify-workspace-properties` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace の実行モードを変更するには**  
次の `modify-workspace-properties` の例では、指定された WorkSpace の実行モードを `AUTO_STOP` に設定します。  

```
aws workspaces modify-workspace-properties \
    --workspace-id ws-dk1xzr417 \
    --workspace-properties RunningMode=AUTO_STOP
```
このコマンドでは何も出力されません。  
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/modify-workspaces.html)」の「*WorkSpaces の変更*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyWorkspaceProperties](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/modify-workspace-properties.html)」を参照してください。

### `modify-workspace-state`
<a name="workspaces_ModifyWorkspaceState_cli_2_topic"></a>

次のコード例は、`modify-workspace-state` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace の状態を変更するには**  
次の `modify-workspace-state` の例では、指定された WorkSpace の状態を `ADMIN_MAINTENANCE` に設定します。  

```
aws workspaces modify-workspace-state \
    --workspace-id ws-dk1xzr417 \
    --workspace-state ADMIN_MAINTENANCE
```
このコマンドでは何も出力されません。  
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/workspace-maintenance.html)」の「*WorkSpaces のメンテナンス*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[ModifyWorkspaceState](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/modify-workspace-state.html)」を参照してください。

### `reboot-workspaces`
<a name="workspaces_RebootWorkspaces_cli_2_topic"></a>

次のコード例は、`reboot-workspaces` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace を再起動するには**  
次の `reboot-workspaces` の例では、指定された WorkSpace を再起動します。  

```
aws workspaces reboot-workspaces \
    --reboot-workspace-requests ws-dk1xzr417
```
出力:  

```
{
    "FailedRequests": []
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/reboot-workspaces.html)」の「*WorkSpaces の再起動*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebootWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/reboot-workspaces.html)」を参照してください。

### `rebuild-workspaces`
<a name="workspaces_RebuildWorkspaces_cli_2_topic"></a>

次のコード例は、`rebuild-workspaces` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace を再構築するには**  
次の `rebuild-workspaces` の例では、指定された WorkSpace を再構築します。  

```
aws workspaces rebuild-workspaces \
    --rebuild-workspace-requests ws-dk1xzr417
```
出力:  

```
{
    "FailedRequests": []
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/rebuild-workspace.html)」の「*WorkSpaces の再構築*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RebuildWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/rebuild-workspaces.html)」を参照してください。

### `register-workspace-directory`
<a name="workspaces_RegisterWorkspaceDirectory_cli_2_topic"></a>

次のコード例は、`register-workspace-directory` を使用する方法を示しています。

**AWS CLI**  
**ディレクトリを登録するには**  
次の `register-workspace-directory` の例では、Amazon WorkSpaces で使用する指定されたディレクトリを登録します。  

```
aws workspaces register-workspace-directory \
    --directory-id d-926722edaf
```
このコマンドでは何も出力されません。  
詳細については、「Amazon [ WorkSpaces 管理ガイド」の「既存の AWS Directory Service ディレクトリを WorkSpaces Personal に登録](https://docs.aws.amazon.com/workspaces/latest/adminguide/register-deregister-directory.html)する」を参照してください。 *Amazon WorkSpaces *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RegisterWorkspaceDirectory](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/register-workspace-directory.html)」を参照してください。

### `restore-workspace`
<a name="workspaces_RestoreWorkspace_cli_2_topic"></a>

次のコード例は、`restore-workspace` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace を復元するには**  
次の `restore-workspace` の例では、指定された WorkSpace を復元します。  

```
aws workspaces restore-workspace \
    --workspace-id ws-dk1xzr417
```
このコマンドでは何も出力されません。  
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/restore-workspace.html)」の「*WorkSpaces の復元*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[RestoreWorkspace](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/restore-workspace.html)」を参照してください。

### `start-workspaces`
<a name="workspaces_StartWorkspaces_cli_2_topic"></a>

次のコード例は、`start-workspaces` を使用する方法を示しています。

**AWS CLI**  
**AutoStop WorkSpace を開始するには**  
次の `start-workspaces` の例では、指定された WorkSpace を開始します。WorkSpace には `AutoStop` の実行モードが必要です。  

```
aws workspaces start-workspaces \
    --start-workspace-requests WorkspaceId=ws-dk1xzr417
```
出力:  

```
{
    "FailedRequests": []
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/running-mode.html#stop-start-workspace)」の「*AutoStop WorkSpace を停止/開始する*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StartWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/start-workspaces.html)」を参照してください。

### `stop-workspaces`
<a name="workspaces_StopWorkspaces_cli_2_topic"></a>

次のコード例は、`stop-workspaces` を使用する方法を示しています。

**AWS CLI**  
**AutoStop WorkSpace を停止するには**  
次の `stop-workspaces` の例では、指定された WorkSpace を停止しています。WorkSpace には `AutoStop` の実行モードが必要です。  

```
aws workspaces stop-workspaces \
    --stop-workspace-requests WorkspaceId=ws-dk1xzr417
```
出力:  

```
{
    "FailedRequests": []
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/running-mode.html#stop-start-workspace)」の「*AutoStop WorkSpace を停止/開始する*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[StopWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/stop-workspaces.html)」を参照してください。

### `terminate-workspaces`
<a name="workspaces_TerminateWorkspaces_cli_2_topic"></a>

次のコード例は、`terminate-workspaces` を使用する方法を示しています。

**AWS CLI**  
**WorkSpace を終了するには**  
次の `terminate-workspaces` の例では、指定されたワークスペースを終了します。  

```
aws workspaces terminate-workspaces \
    --terminate-workspace-requests ws-dk1xzr417
```
出力:  

```
{
    "FailedRequests": []
}
```
詳細については、「[Amazon WorkSpaces 管理ガイド](https://docs.aws.amazon.com/workspaces/latest/adminguide/delete-workspaces.html)」の「*WorkSpaces の削除*」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[TerminateWorkspaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workspaces/terminate-workspaces.html)」を参照してください。

# を使用した X-Ray の例 AWS CLI
<a name="cli_2_xray_code_examples"></a>

次のコード例は、X-Ray AWS Command Line Interface で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `batch-traces-get`
<a name="xray_BatchTracesGet_cli_2_topic"></a>

次のコード例は、`batch-traces-get` を使用する方法を示しています。

**AWS CLI**  
**トレースのリストを取得するには**  
次の `batch-get-traces` の例では、ID で指定されたトレースのリストを取得します。トレース全体には、同一のトレース ID を使用して取得されるすべてのセグメントドキュメントからコンパイルされた、各セグメントのドキュメントが含まれます。  

```
aws xray batch-get-traces \
    --trace-ids 1-5d82881a-0a9126e92a73e971eed891b9
```
出力:  

```
{
    "Traces": [
        {
            "Id": "1-5d82881a-0a9126e92a73e971eed891b9",
            "Duration": 0.232,
            "Segments": [
                {
                    "Id": "54aff5735b12dd28",
                    "Document": "{\"id\":\"54aff5735b12dd28\",\"name\":\"Scorekeep\",\"start_time\":1.568835610432E9,\"end_time\":1.568835610664E9,\"http\":{\"request\":{\"url\":\"http://scorekeep-env-1.m4fg2pfzpv.us-east-2.elasticbeanstalk.com/api/user\",\"method\":\"POST\",\"user_agent\":\"curl/7.59.0\",\"client_ip\":\"52.95.4.28\",\"x_forwarded_for\":true},\"response\":{\"status\":200}},\"aws\":{\"elastic_beanstalk\":{\"version_label\":\"Sample Application-1\",\"deployment_id\":3,\"environment_name\":\"Scorekeep-env-1\"},\"ec2\":{\"availability_zone\":\"us-east-2b\",\"instance_id\":\"i-0e3cf4d2de0f3f37a\"},\"xray\":{\"sdk_version\":\"1.1.0\",\"sdk\":\"X-Ray for Java\"}},\"service\":{\"runtime\":\"OpenJDK 64-Bit Server VM\",\"runtime_version\":\"1.8.0_222\"},\"trace_id\":\"1-5d82881a-0a9126e92a73e971eed891b9\",\"origin\":\"AWS::ElasticBeanstalk::Environment\",\"subsegments\":[{\"id\":\"2d6900034ccfe558\",\"name\":\"DynamoDB\",\"start_time\":1.568835610658E9,\"end_time\":1.568835610664E9,\"http\":{\"response\":{\"status\":200,\"content_length\":61}},\"aws\":{\"table_name\":\"scorekeep-user\",\"operation\":\"UpdateItem\",\"request_id\":\"TPEIDNDUROMLPOV17U4A79555NVV4KQNSO5AEMVJF66Q9ASUAAJG\",\"resource_names\":[\"scorekeep-user\"]},\"namespace\":\"aws\"}]}"
                },
                {
                    "Id": "0f278b6334c34e6b",
                    "Document": "{\"id\":\"0f278b6334c34e6b\",\"name\":\"DynamoDB\",\"start_time\":1.568835610658E9,\"end_time\":1.568835610664E9,\"parent_id\":\"2d6900034ccfe558\",\"inferred\":true,\"http\":{\"response\":{\"status\":200,\"content_length\":61}},\"aws\":{\"table_name\":\"scorekeep-user\",\"operation\":\"UpdateItem\",\"request_id\":\"TPEIDNDUROMLPOV17U4A79555NVV4KQNSO5AEMVJF66Q9ASUAAJG\",\"resource_names\":[\"scorekeep-user\"]},\"trace_id\":\"1-5d82881a-0a9126e92a73e971eed891b9\",\"origin\":\"AWS::DynamoDB::Table\"}"
                }
            ]
        }
    ],
    "UnprocessedTraceIds": []
}
```
詳細については、[AWS 「X-Ray デベロッパーガイド」の「 CLI AWS での X-Ray API](https://docs.aws.amazon.com/xray/latest/devguide/xray-api-tutorial.html) の使用」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[BatchTracesGet](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/batch-traces-get.html)」を参照してください。

### `create-group`
<a name="xray_CreateGroup_cli_2_topic"></a>

次のコード例は、`create-group` を使用する方法を示しています。

**AWS CLI**  
**グループを作成するには**  
次の `create-group` の例では、`AdminGroup` という名前のグループリソースが作成されます。グループは、障害またはエラーの原因となる特定のサービスに関連するセグメントとしてグループの条件を定義するフィルター式を取得します。  

```
aws xray create-group \
   --group-name "AdminGroup" \
   --filter-expression "service(\"mydomain.com\") {fault OR error}"
```
出力:  

```
{
    "GroupName": "AdminGroup",
    "GroupARN": "arn:aws:xray:us-west-2:123456789012:group/AdminGroup/123456789",
    "FilterExpression": "service(\"mydomain.com\") {fault OR error}"
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/create-group.html)」を参照してください。

### `create-sampling-rule`
<a name="xray_CreateSamplingRule_cli_2_topic"></a>

次のコード例は、`create-sampling-rule` を使用する方法を示しています。

**AWS CLI**  
**サンプリングルールを作成するには**  
次の `create-sampling-rule` の例は、実装されたアプリケーションのサンプリング動作を制御するルールを作成します。ルールは JSON ファイルによって提供されます。ルールを作成するには、サンプリングルールフィールドの大部分が必要です。  

```
aws xray create-sampling-rule \
    --cli-input-json file://9000-base-scorekeep.json
```
`9000-base-scorekeep.json` の内容:  

```
{
    "SamplingRule": {
        "RuleName": "base-scorekeep",
        "ResourceARN": "*",
        "Priority": 9000,
        "FixedRate": 0.1,
        "ReservoirSize": 5,
        "ServiceName": "Scorekeep",
        "ServiceType": "*",
        "Host": "*",
        "HTTPMethod": "*",
        "URLPath": "*",
        "Version": 1
    }
}
```
出力:  

```
{
    "SamplingRuleRecord": {
        "SamplingRule": {
            "RuleName": "base-scorekeep",
            "RuleARN": "arn:aws:xray:us-west-2:123456789012:sampling-rule/base-scorekeep",
            "ResourceARN": "*",
            "Priority": 9000,
            "FixedRate": 0.1,
            "ReservoirSize": 5,
            "ServiceName": "Scorekeep",
            "ServiceType": "*",
            "Host": "*",
            "HTTPMethod": "*",
            "URLPath": "*",
            "Version": 1,
            "Attributes": {}
        },
        "CreatedAt": 1530574410.0,
        "ModifiedAt": 1530574410.0
    }
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[CreateSamplingRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/create-sampling-rule.html)」を参照してください。

### `delete-group`
<a name="xray_DeleteGroup_cli_2_topic"></a>

次のコード例は、`delete-group` を使用する方法を示しています。

**AWS CLI**  
**グループを削除するには**  
次の `delete-group` の例では、指定されたグループリソースを削除します。  

```
aws xray delete-group \
    --group-name "AdminGroup" \
    --group-arn "arn:aws:xray:us-east-2:123456789012:group/AdminGroup/123456789"
```
このコマンドでは何も出力されません。  
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/delete-group.html)」を参照してください。

### `delete-sampling-rule`
<a name="xray_DeleteSamplingRule_cli_2_topic"></a>

次のコード例は、`delete-sampling-rule` を使用する方法を示しています。

**AWS CLI**  
**サンプリングルールを削除するには**  
次の `delete-sampling-rule` の例は、指定されたサンプリングルールを削除します。グループ名またはグループ ARN を使用して、グループを指定できます。  

```
aws xray delete-sampling-rule \
    --rule-name polling-scorekeep
```
出力:  

```
{
    "SamplingRuleRecord": {
        "SamplingRule": {
            "RuleName": "polling-scorekeep",
            "RuleARN": "arn:aws:xray:us-west-2:123456789012:sampling-rule/polling-scorekeep",
            "ResourceARN": "*",
            "Priority": 5000,
            "FixedRate": 0.003,
            "ReservoirSize": 0,
            "ServiceName": "Scorekeep",
            "ServiceType": "*",
            "Host": "*",
            "HTTPMethod": "GET",
            "URLPath": "/api/state/*",
            "Version": 1,
            "Attributes": {}
        },
        "CreatedAt": 1530574399.0,
        "ModifiedAt": 1530574399.0
    }
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[DeleteSamplingRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/delete-sampling-rule.html)」を参照してください。

### `get-encryption-config`
<a name="xray_GetEncryptionConfig_cli_2_topic"></a>

次のコード例は、`get-encryption-config` を使用する方法を示しています。

**AWS CLI**  
**暗号化設定を取得するには**  
次の の`get-encryption-config`例では、 AWS X-Ray データの現在の暗号化設定を取得します。  

```
aws xray get-encryption-config
```
出力:  

```
{
    "EncryptionConfig": {
        "KeyId": "ae4aa6d49-a4d8-9df9-a475-4ff6d7898456",
        "Status": "ACTIVE",
        "Type": "NONE"
    }
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetEncryptionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/get-encryption-config.html)」を参照してください。

### `get-group`
<a name="xray_GetGroup_cli_2_topic"></a>

次のコード例は、`get-group` を使用する方法を示しています。

**AWS CLI**  
**グループを取得するには**  
次の `get-group` の例では、指定したグループリソースに関する詳細を表示します。詳細には、グループ名、グループ ARN、そのグループの条件を定義するフィルター式が含まれます。グループは ARN によって取得することもできます。  

```
aws xray get-group \
    --group-name "AdminGroup"
```
出力:  

```
{
    "Group": [
        {
            "GroupName": "AdminGroup",
            "GroupARN": "arn:aws:xray:us-west-2:123456789012:group/AdminGroup/123456789",
            "FilterExpression": "service(\"mydomain.com\") {fault OR error}"
        }
    ]
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/get-group.html)」を参照してください。

### `get-groups`
<a name="xray_GetGroups_cli_2_topic"></a>

次のコード例は、`get-groups` を使用する方法を示しています。

**AWS CLI**  
**すべてのグループを取得するには**  
次の例では、すべてのアクティブなグループの詳細を表示します。  

```
aws xray get-groups
```
出力:  

```
{
    "Groups": [
        {
            "GroupName": "AdminGroup",
            "GroupARN": "arn:aws:xray:us-west-2:123456789012:group/AdminGroup/123456789",
            "FilterExpression": "service(\"example.com\") {fault OR error}"
        },
        {
            "GroupName": "SDETGroup",
            "GroupARN": "arn:aws:xray:us-west-2:123456789012:group/SDETGroup/987654321",
            "FilterExpression": "responsetime > 2"
        }
    ]
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetGroups](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/get-groups.html)」を参照してください。

### `get-sampling-rules`
<a name="xray_GetSamplingRules_cli_2_topic"></a>

次のコード例は、`get-sampling-rules` を使用する方法を示しています。

**AWS CLI**  
**すべてのサンプリングルールを取得するには**  
次の `get-sampling-rules` の例では、使用可能なすべてのサンプリングルールの詳細を表示します。  

```
aws xray get-sampling-rules
```
出力:  

```
{
    "SamplingRuleRecords": [
        {
            "SamplingRule": {
                "RuleName": "Default",
                "RuleARN": "arn:aws:xray:us-east-1::sampling-rule/Default",
                "ResourceARN": "*",
                "Priority": 10000,
                "FixedRate": 0.01,
                "ReservoirSize": 0,
                "ServiceName": "*",
                "ServiceType": "*",
                "Host": "*",
                "HTTPMethod": "*",
                "URLPath": "*",
                "Version": 1,
                "Attributes": {}
            },
            "CreatedAt": 0.0,
            "ModifiedAt": 1530558121.0
        },
        {
            "SamplingRule": {
                "RuleName": "base-scorekeep",
                "RuleARN": "arn:aws:xray:us-east-1::sampling-rule/base-scorekeep",
                "ResourceARN": "*",
                "Priority": 9000,
                "FixedRate": 0.1,
                "ReservoirSize": 2,
                "ServiceName": "Scorekeep",
                "ServiceType": "*",
                "Host": "*",
                "HTTPMethod": "*",
                "URLPath": "*",
                "Version": 1,
                "Attributes": {}
            },
            "CreatedAt": 1530573954.0,
            "ModifiedAt": 1530920505.0
        },
        {
            "SamplingRule": {
                "RuleName": "polling-scorekeep",
                "RuleARN": "arn:aws:xray:us-east-1::sampling-rule/polling-scorekeep",
                "ResourceARN": "*",
                "Priority": 5000,
                "FixedRate": 0.003,
                "ReservoirSize": 0,
                "ServiceName": "Scorekeep",
                "ServiceType": "*",
                "Host": "*",
                "HTTPMethod": "GET",
                "URLPath": "/api/state/*",
                "Version": 1,
                "Attributes": {}
            },
            "CreatedAt": 1530918163.0,
            "ModifiedAt": 1530918163.0
        }
    ]
}
```
詳細については、「*AWS X-Ray デベロッパーガイド*」の「[X-Ray API でのサンプリングルールの使用](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-sampling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSamplingRules](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/get-sampling-rules.html)」を参照してください。

### `get-sampling-targets`
<a name="xray_GetSamplingTargets_cli_2_topic"></a>

次のコード例は、`get-sampling-targets` を使用する方法を示しています。

**AWS CLI**  
**サンプリングクォータをリクエストするには**  
次の `get-sampling-targets` の例は、サービスがリクエストのサンプリングに使用しているルールのサンプリングクォータをリクエストします。 AWS X-Ray からのレスポンスには、リザーバから借りる代わりに使用できるクォータが含まれています。  

```
aws xray get-sampling-targets \
    --sampling-statistics-documents '[ { "RuleName": "base-scorekeep", "ClientID": "ABCDEF1234567890ABCDEF10", "Timestamp": "2018-07-07T00:20:06, "RequestCount": 110, "SampledCount": 20, "BorrowCount": 10 }, { "RuleName": "polling-scorekeep", 31, "BorrowCount": 0 } ]'
```
出力:  

```
{
    "SamplingTargetDocuments": [
        {
            "RuleName": "base-scorekeep",
            "FixedRate": 0.1,
            "ReservoirQuota": 2,
            "ReservoirQuotaTTL": 1530923107.0,
            "Interval": 10
        },
        {
            "RuleName": "polling-scorekeep",
            "FixedRate": 0.003,
            "ReservoirQuota": 0,
            "ReservoirQuotaTTL": 1530923107.0,
            "Interval": 10
        }
    ],
    "LastRuleModification": 1530920505.0,
    "UnprocessedStatistics": []
}
```
詳細については、「*AWS X-Ray デベロッパーガイド*」の「[X-Ray API でのサンプリングルールの使用](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-sampling.html)」を参照してください。  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetSamplingTargets](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/get-sampling-targets.html)」を参照してください。

### `get-service-graph`
<a name="xray_GetServiceGraph_cli_2_topic"></a>

次のコード例は、`get-service-graph` を使用する方法を示しています。

**AWS CLI**  
**サービスグラフを取得するには**  
次の例では、受信リクエストを処理するサービス、および結果として呼び出すダウンストリームサービスを説明する、指定された期間内にドキュメントを表示します。  

```
aws xray get-service-graph \
    --start-time 1568835392.0
    --end-time 1568835446.0
```
出力:  

```
{
    "Services": [
        {
            "ReferenceId": 0,
            "Name": "Scorekeep",
            "Names": [
                "Scorekeep"
            ],
            "Root": true,
            "Type": "AWS::ElasticBeanstalk::Environment",
            "State": "active",
            "StartTime": 1568835392.0,
            "EndTime": 1568835446.0,
            "Edges": [
                {
                    "ReferenceId": 1,
                    "StartTime": 1568835392.0,
                    "EndTime": 1568835446.0,
                    "SummaryStatistics": {
                        "OkCount": 14,
                        "ErrorStatistics": {
                            "ThrottleCount": 0,
                            "OtherCount": 0,
                            "TotalCount": 0
                        },
                        "FaultStatistics": {
                            "OtherCount": 0,
                            "TotalCount": 0
                        },
                        "TotalCount": 14,
                        "TotalResponseTime": 0.13
                    },
                    "ResponseTimeHistogram": [
                        {
                            "Value": 0.008,
                            "Count": 1
                        },
                        {
                            "Value": 0.005,
                            "Count": 7
                        },
                        {
                            "Value": 0.009,
                            "Count": 1
                        },
                        {
                            "Value": 0.021,
                            "Count": 1
                        },
                        {
                            "Value": 0.038,
                            "Count": 1
                        },
                        {
                            "Value": 0.007,
                            "Count": 1
                        },
                        {
                            "Value": 0.006,
                            "Count": 2
                        }
                    ],
                    "Aliases": []
                },

                ... TRUNCATED FOR BREVITY ...

            ]
        }
    ],
    "StartTime": 1568835392.0,
    "EndTime": 1568835446.0,
    "ContainsOldGroupVersions": false
}
```
詳細については、[AWS 「X-Ray デベロッパーガイド」の「 CLI AWS での X-Ray API](https://docs.aws.amazon.com/xray/latest/devguide/xray-api-tutorial.html) の使用」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetServiceGraph](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/get-service-graph.html)」を参照してください。

### `get-trace-summaries`
<a name="xray_GetTraceSummaries_cli_2_topic"></a>

次のコード例は、`get-trace-summaries` を使用する方法を示しています。

**AWS CLI**  
**トレースの概要を取得するには**  
次の `get-trace-summaries` の例では、指定された時間枠内で使用可能なトレースの ID とメタデータを取得します。  

```
aws xray get-trace-summaries \
    --start-time 1568835392.0 \
    --end-time 1568835446.0
```
出力:  

```
[
    "http://scorekeep-env-1.123456789.us-east-2.elasticbeanstalk.com/api/move/VSAE93HF/GSSD2NTB/DP0PCC09",
    "http://scorekeep-env-1.123456789.us-east-2.elasticbeanstalk.com/api/move/GCQ2B35P/FREELDFT/4LRE643M",
    "http://scorekeep-env-1.123456789.us-east-2.elasticbeanstalk.com/api/game/VSAE93HF/GSSD2NTB/starttime/1568835513",
    "http://scorekeep-env-1.123456789.us-east-2.elasticbeanstalk.com/api/move/4MQNA5NN/L99KK2RF/null"
]
```
詳細については、[AWS 「X-Ray デベロッパーガイド」の「 CLI AWS での X-Ray API](https://docs.aws.amazon.com/xray/latest/devguide/xray-api-tutorial.html) の使用」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[GetTraceSummaries](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/get-trace-summaries.html)」を参照してください。

### `put-encryption-config`
<a name="xray_PutEncryptionConfig_cli_2_topic"></a>

次のコード例は、`put-encryption-config` を使用する方法を示しています。

**AWS CLI**  
**暗号化設定を更新するには**  
次の `put-encryption-config``example updates the encryption configuration for AWS X-Ray data to use the default AWS managed KMS key ``aws/xray`。  

```
aws xray put-encryption-config \
    --type KMS \
    --key-id alias/aws/xray
```
出力:  

```
{
    "EncryptionConfig": {
        "KeyId": "arn:aws:kms:us-west-2:123456789012:key/c234g4e8-39e9-4gb0-84e2-b0ea215cbba5",
        "Status": "UPDATING",
        "Type": "KMS"
    }
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutEncryptionConfig](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/put-encryption-config.html)」を参照してください。

### `put-trace-segments`
<a name="xray_PutTraceSegments_cli_2_topic"></a>

次のコード例は、`put-trace-segments` を使用する方法を示しています。

**AWS CLI**  
**セグメントをアップロードするには**  
次の の`put-trace-segments`例では、セグメントドキュメントを AWS X-Ray にアップロードします。セグメントドキュメントは、JSON セグメントドキュメントのリストとして消費されます。  

```
aws xray put-trace-segments \
    --trace-segment-documents "{\"id\":\"20312a0e2b8809f4\",\"name\":\"DynamoDB\",\"trace_id\":\"1-5832862d-a43aafded3334a971fe312db\",\"start_time\":1.479706157195E9,\"end_time\":1.479706157202E9,\"parent_id\":\"79736b962fe3239e\",\"http\":{\"response\":{\"content_length\":60,\"status\":200}},\"inferred\":true,\"aws\":{\"consistent_read\":false,\"table_name\":\"scorekeep-session-xray\",\"operation\":\"GetItem\",\"request_id\":\"SCAU23OM6M8FO38UASGC7785ARVV4KQNSO5AEMVJF66Q9ASUAAJG\",\"resource_names\":[\"scorekeep-session-xray\"]},\"origin\":\"AWS::DynamoDB::Table\"}"
```
出力:  

```
{
    "UnprocessedTraceSegments": []
}
```
詳細については、[AWS 「X-Ray デベロッパーガイド」の「X-Ray へのトレースデータの送信](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-sendingdata.html#xray-api-segments)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[PutTraceSegments](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/put-trace-segments.html)」を参照してください。

### `update-group`
<a name="xray_UpdateGroup_cli_2_topic"></a>

次のコード例は、`update-group` を使用する方法を示しています。

**AWS CLI**  
**グループを更新するには**  
次の `update-group` の例では、`AdminGroup` という名前のグループへのトレースを受け入れる基準を更新します。グループ名またはグループ ARN を使用して、目的のグループを指定できます。  

```
aws xray update-group \
    --group-name "AdminGroup" \
    --group-arn "arn:aws:xray:us-west-2:123456789012:group/AdminGroup/123456789" \
    --filter-expression "service(\"mydomain.com\") {fault}"
```
出力:  

```
{
    "GroupName": "AdminGroup",
    "GroupARN": "arn:aws:xray:us-east-2:123456789012:group/AdminGroup/123456789",
    "FilterExpression": "service(\"mydomain.com\") {fault}"
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateGroup](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/update-group.html)」を参照してください。

### `update-sampling-rule`
<a name="xray_UpdateSamplingRule_cli_2_topic"></a>

次のコード例は、`update-sampling-rule` を使用する方法を示しています。

**AWS CLI**  
**サンプリングルールを更新するには**  
次の `update-sampling-rule` の例では、サンプリングルールの設定を変更します。ルールは JSON ファイルから消費されます。更新されるフィールドのみが必要です。  

```
aws xray update-sampling-rule \
   --cli-input-json file://1000-default.json
```
`1000-default.json` の内容:  

```
{
    "SamplingRuleUpdate": {
        "RuleName": "Default",
        "FixedRate": 0.01,
        "ReservoirSize": 0
    }
}
```
出力:  

```
{
    "SamplingRuleRecords": [
        {
            "SamplingRule": {
                "RuleName": "Default",
                "RuleARN": "arn:aws:xray:us-west-2:123456789012:sampling-rule/Default",
                "ResourceARN": "*",
                "Priority": 10000,
                "FixedRate": 0.01,
                "ReservoirSize": 0,
                "ServiceName": "*",
                "ServiceType": "*",
                "Host": "*",
                "HTTPMethod": "*",
                "URLPath": "*",
                "Version": 1,
                "Attributes": {}
            },
            "CreatedAt": 0.0,
            "ModifiedAt": 1529959993.0
        }
   ]
}
```
詳細については、X-[Ray デベロッパーガイドの AWS 「X-Ray API を使用したサンプリング、グループ、暗号化の設定](https://docs.aws.amazon.com/en_pv/xray/latest/devguide/xray-api-configuration.html#xray-api-configuration-sampling)」を参照してください。 *AWS *  
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[UpdateSamplingRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/xray/update-sampling-rule.html)」を参照してください。

# SDK for Go V2 のコード例
<a name="go_2_code_examples"></a>

次のコード例は、 で AWS SDK for Go V2 を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for Go V2 デベロッパーガイド ](https://aws.github.io/aws-sdk-go-v2/docs/) ** – Go の使用に関する詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23go)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [API ゲートウェイ](go_2_api-gateway_code_examples.md)
+ [Aurora](go_2_aurora_code_examples.md)
+ [Amazon Bedrock](go_2_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](go_2_bedrock-runtime_code_examples.md)
+ [CloudFormation](go_2_cloudformation_code_examples.md)
+ [CloudWatch Logs](go_2_cloudwatch-logs_code_examples.md)
+ [Amazon Cognito ID プロバイダー](go_2_cognito-identity-provider_code_examples.md)
+ [Amazon DocumentDB](go_2_docdb_code_examples.md)
+ [DynamoDB](go_2_dynamodb_code_examples.md)
+ [IAM](go_2_iam_code_examples.md)
+ [Kinesis](go_2_kinesis_code_examples.md)
+ [Lambda](go_2_lambda_code_examples.md)
+ [Amazon MSK](go_2_kafka_code_examples.md)
+ [パートナーセントラル](go_2_partnercentral-selling_code_examples.md)
+ [Amazon RDS](go_2_rds_code_examples.md)
+ [Amazon Redshift](go_2_redshift_code_examples.md)
+ [Amazon S3](go_2_s3_code_examples.md)
+ [Amazon SNS](go_2_sns_code_examples.md)
+ [Amazon SQS](go_2_sqs_code_examples.md)

# SDK for Go V2 を使用した API Gateway の例
<a name="go_2_api-gateway_code_examples"></a>

次のコード例は、API Gateway で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*AWS コミュニティへの貢献*は、複数のチームによって作成され、維持されている例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_go_2_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Go V2**  
 Go SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-go-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Go V2 を使用した Aurora の例
<a name="go_2_aurora_code_examples"></a>

次のコード例は、Aurora で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Aurora
<a name="aurora_Hello_go_2_topic"></a>

次のコード例は、Aurora の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/rds"
)

// main uses the AWS SDK for Go V2 to create an Amazon Aurora client and list up to 20
// DB clusters in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	auroraClient := rds.NewFromConfig(sdkConfig)
	const maxClusters = 20
	fmt.Printf("Let's list up to %v DB clusters.\n", maxClusters)
	output, err := auroraClient.DescribeDBClusters(
		ctx, &rds.DescribeDBClustersInput{MaxRecords: aws.Int32(maxClusters)})
	if err != nil {
		fmt.Printf("Couldn't list DB clusters: %v\n", err)
		return
	}
	if len(output.DBClusters) == 0 {
		fmt.Println("No DB clusters found.")
	} else {
		for _, cluster := range output.DBClusters {
			fmt.Printf("DB cluster %v has database %v.\n", *cluster.DBClusterIdentifier,
				*cluster.DatabaseName)
		}
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBClusters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="aurora_Scenario_GetStartedClusters_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム Aurora DB クラスターパラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用する DB クラスターを作成する
+ データベースを含む DB インスタンスを作成します。
+ DB クラスターのスナップショットを作成して、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"aurora/actions"
	"context"
	"fmt"
	"log"
	"slices"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/google/uuid"
)

// GetStartedClusters is an interactive example that shows you how to use the AWS SDK for Go
// with Amazon Aurora to do the following:
//
// 1. Create a custom DB cluster parameter group and set parameter values.
// 2. Create an Aurora DB cluster that is configured to use the parameter group.
// 3. Create a DB instance in the DB cluster that contains a database.
// 4. Take a snapshot of the DB cluster.
// 5. Delete the DB instance, DB cluster, and parameter group.
type GetStartedClusters struct {
	sdkConfig  aws.Config
	dbClusters actions.DbClusters
	questioner demotools.IQuestioner
	helper     IScenarioHelper
	isTestRun  bool
}

// NewGetStartedClusters constructs a GetStartedClusters instance from a configuration.
// It uses the specified config to get an Amazon Relational Database Service (Amazon RDS)
// client and create wrappers for the actions used in the scenario.
func NewGetStartedClusters(sdkConfig aws.Config, questioner demotools.IQuestioner,
	helper IScenarioHelper) GetStartedClusters {
	auroraClient := rds.NewFromConfig(sdkConfig)
	return GetStartedClusters{
		sdkConfig:  sdkConfig,
		dbClusters: actions.DbClusters{AuroraClient: auroraClient},
		questioner: questioner,
		helper:     helper,
	}
}

// Run runs the interactive scenario.
func (scenario GetStartedClusters) Run(ctx context.Context, dbEngine string, parameterGroupName string,
	clusterName string, dbName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon Aurora DB Cluster demo.")
	log.Println(strings.Repeat("-", 88))

	parameterGroup := scenario.CreateParameterGroup(ctx, dbEngine, parameterGroupName)
	scenario.SetUserParameters(ctx, parameterGroupName)
	cluster := scenario.CreateCluster(ctx, clusterName, dbEngine, dbName, parameterGroup)
	scenario.helper.Pause(5)
	dbInstance := scenario.CreateInstance(ctx, cluster)
	scenario.DisplayConnection(cluster)
	scenario.CreateSnapshot(ctx, clusterName)
	scenario.Cleanup(ctx, dbInstance, cluster, parameterGroup)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}

// CreateParameterGroup shows how to get available engine versions for a specified
// database engine and create a DB cluster parameter group that is compatible with a
// selected engine family.
func (scenario GetStartedClusters) CreateParameterGroup(ctx context.Context, dbEngine string,
	parameterGroupName string) *types.DBClusterParameterGroup {

	log.Printf("Checking for an existing DB cluster parameter group named %v.\n",
		parameterGroupName)
	parameterGroup, err := scenario.dbClusters.GetParameterGroup(ctx, parameterGroupName)
	if err != nil {
		panic(err)
	}
	if parameterGroup == nil {
		log.Printf("Getting available database engine versions for %v.\n", dbEngine)
		engineVersions, err := scenario.dbClusters.GetEngineVersions(ctx, dbEngine, "")
		if err != nil {
			panic(err)
		}

		familySet := map[string]struct{}{}
		for _, family := range engineVersions {
			familySet[*family.DBParameterGroupFamily] = struct{}{}
		}
		var families []string
		for family := range familySet {
			families = append(families, family)
		}
		sort.Strings(families)
		familyIndex := scenario.questioner.AskChoice("Which family do you want to use?\n", families)
		log.Println("Creating a DB cluster parameter group.")
		_, err = scenario.dbClusters.CreateParameterGroup(
			ctx, parameterGroupName, families[familyIndex], "Example parameter group.")
		if err != nil {
			panic(err)
		}
		parameterGroup, err = scenario.dbClusters.GetParameterGroup(ctx, parameterGroupName)
		if err != nil {
			panic(err)
		}
	}
	log.Printf("Parameter group %v:\n", *parameterGroup.DBParameterGroupFamily)
	log.Printf("\tName: %v\n", *parameterGroup.DBClusterParameterGroupName)
	log.Printf("\tARN: %v\n", *parameterGroup.DBClusterParameterGroupArn)
	log.Printf("\tFamily: %v\n", *parameterGroup.DBParameterGroupFamily)
	log.Printf("\tDescription: %v\n", *parameterGroup.Description)
	log.Println(strings.Repeat("-", 88))
	return parameterGroup

}

// SetUserParameters shows how to get the parameters contained in a custom parameter
// group and update some of the parameter values in the group.
func (scenario GetStartedClusters) SetUserParameters(ctx context.Context, parameterGroupName string) {
	log.Println("Let's set some parameter values in your parameter group.")
	dbParameters, err := scenario.dbClusters.GetParameters(ctx, parameterGroupName, "")
	if err != nil {
		panic(err)
	}
	var updateParams []types.Parameter
	for _, dbParam := range dbParameters {
		if strings.HasPrefix(*dbParam.ParameterName, "auto_increment") &&
			*dbParam.IsModifiable && *dbParam.DataType == "integer" {
			log.Printf("The %v parameter is described as:\n\t%v",
				*dbParam.ParameterName, *dbParam.Description)
			rangeSplit := strings.Split(*dbParam.AllowedValues, "-")
			lower, _ := strconv.Atoi(rangeSplit[0])
			upper, _ := strconv.Atoi(rangeSplit[1])
			newValue := scenario.questioner.AskInt(
				fmt.Sprintf("Enter a value between %v and %v:", lower, upper),
				demotools.InIntRange{Lower: lower, Upper: upper})
			dbParam.ParameterValue = aws.String(strconv.Itoa(newValue))
			updateParams = append(updateParams, dbParam)
		}
	}
	err = scenario.dbClusters.UpdateParameters(ctx, parameterGroupName, updateParams)
	if err != nil {
		panic(err)
	}
	log.Println("You can get a list of parameters you've set by specifying a source of 'user'.")
	userParameters, err := scenario.dbClusters.GetParameters(ctx, parameterGroupName, "user")
	if err != nil {
		panic(err)
	}
	log.Println("Here are the parameters you've set:")
	for _, param := range userParameters {
		log.Printf("\t%v: %v\n", *param.ParameterName, *param.ParameterValue)
	}
	log.Println(strings.Repeat("-", 88))
}

// CreateCluster shows how to create an Aurora DB cluster that contains a database
// of a specified type. The database is also configured to use a custom DB cluster
// parameter group.
func (scenario GetStartedClusters) CreateCluster(ctx context.Context, clusterName string, dbEngine string,
	dbName string, parameterGroup *types.DBClusterParameterGroup) *types.DBCluster {

	log.Println("Checking for an existing DB cluster.")
	cluster, err := scenario.dbClusters.GetDbCluster(ctx, clusterName)
	if err != nil {
		panic(err)
	}
	if cluster == nil {
		adminUsername := scenario.questioner.Ask(
			"Enter an administrator user name for the database: ", demotools.NotEmpty{})
		adminPassword := scenario.questioner.Ask(
			"Enter a password for the administrator (at least 8 characters): ", demotools.NotEmpty{})
		engineVersions, err := scenario.dbClusters.GetEngineVersions(ctx, dbEngine, *parameterGroup.DBParameterGroupFamily)
		if err != nil {
			panic(err)
		}
		var engineChoices []string
		for _, engine := range engineVersions {
			engineChoices = append(engineChoices, *engine.EngineVersion)
		}
		log.Println("The available engines for your parameter group are:")
		engineIndex := scenario.questioner.AskChoice("Which engine do you want to use?\n", engineChoices)
		log.Printf("Creating DB cluster %v and database %v.\n", clusterName, dbName)
		log.Printf("The DB cluster is configured to use\nyour custom parameter group %v\n",
			*parameterGroup.DBClusterParameterGroupName)
		log.Printf("and selected engine %v.\n", engineChoices[engineIndex])
		log.Println("This typically takes several minutes.")
		cluster, err = scenario.dbClusters.CreateDbCluster(
			ctx, clusterName, *parameterGroup.DBClusterParameterGroupName, dbName, dbEngine,
			engineChoices[engineIndex], adminUsername, adminPassword)
		if err != nil {
			panic(err)
		}
		for *cluster.Status != "available" {
			scenario.helper.Pause(30)
			cluster, err = scenario.dbClusters.GetDbCluster(ctx, clusterName)
			if err != nil {
				panic(err)
			}
			log.Println("Cluster created and available.")
		}
	}
	log.Println("Cluster data:")
	log.Printf("\tDBClusterIdentifier: %v\n", *cluster.DBClusterIdentifier)
	log.Printf("\tARN: %v\n", *cluster.DBClusterArn)
	log.Printf("\tStatus: %v\n", *cluster.Status)
	log.Printf("\tEngine: %v\n", *cluster.Engine)
	log.Printf("\tEngine version: %v\n", *cluster.EngineVersion)
	log.Printf("\tDBClusterParameterGroup: %v\n", *cluster.DBClusterParameterGroup)
	log.Printf("\tEngineMode: %v\n", *cluster.EngineMode)
	log.Println(strings.Repeat("-", 88))
	return cluster
}

// CreateInstance shows how to create a DB instance in an existing Aurora DB cluster.
// A new DB cluster contains no DB instances, so you must add one. The first DB instance
// that is added to a DB cluster defaults to a read-write DB instance.
func (scenario GetStartedClusters) CreateInstance(ctx context.Context, cluster *types.DBCluster) *types.DBInstance {
	log.Println("Checking for an existing database instance.")
	dbInstance, err := scenario.dbClusters.GetInstance(ctx, *cluster.DBClusterIdentifier)
	if err != nil {
		panic(err)
	}
	if dbInstance == nil {
		log.Println("Let's create a database instance in your DB cluster.")
		log.Println("First, choose a DB instance type:")
		instOpts, err := scenario.dbClusters.GetOrderableInstances(
			ctx, *cluster.Engine, *cluster.EngineVersion)
		if err != nil {
			panic(err)
		}
		var instChoices []string
		for _, opt := range instOpts {
			instChoices = append(instChoices, *opt.DBInstanceClass)
		}
		slices.Sort(instChoices)
		instChoices = slices.Compact(instChoices)
		instIndex := scenario.questioner.AskChoice(
			"Which DB instance class do you want to use?\n", instChoices)
		log.Println("Creating a database instance. This typically takes several minutes.")
		dbInstance, err = scenario.dbClusters.CreateInstanceInCluster(
			ctx, *cluster.DBClusterIdentifier, *cluster.DBClusterIdentifier, *cluster.Engine,
			instChoices[instIndex])
		if err != nil {
			panic(err)
		}
		for *dbInstance.DBInstanceStatus != "available" {
			scenario.helper.Pause(30)
			dbInstance, err = scenario.dbClusters.GetInstance(ctx, *cluster.DBClusterIdentifier)
			if err != nil {
				panic(err)
			}
		}
	}
	log.Println("Instance data:")
	log.Printf("\tDBInstanceIdentifier: %v\n", *dbInstance.DBInstanceIdentifier)
	log.Printf("\tARN: %v\n", *dbInstance.DBInstanceArn)
	log.Printf("\tStatus: %v\n", *dbInstance.DBInstanceStatus)
	log.Printf("\tEngine: %v\n", *dbInstance.Engine)
	log.Printf("\tEngine version: %v\n", *dbInstance.EngineVersion)
	log.Println(strings.Repeat("-", 88))
	return dbInstance
}

// DisplayConnection displays connection information about an Aurora DB cluster and tips
// on how to connect to it.
func (scenario GetStartedClusters) DisplayConnection(cluster *types.DBCluster) {
	log.Println(
		"You can now connect to your database using your favorite MySql client.\n" +
			"One way to connect is by using the 'mysql' shell on an Amazon EC2 instance\n" +
			"that is running in the same VPC as your database cluster. Pass the endpoint,\n" +
			"port, and administrator user name to 'mysql' and enter your password\n" +
			"when prompted:")
	log.Printf("\n\tmysql -h %v -P %v -u %v -p\n",
		*cluster.Endpoint, *cluster.Port, *cluster.MasterUsername)
	log.Println("For more information, see the User Guide for Aurora:\n" +
		"\thttps://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_GettingStartedAurora.CreatingConnecting.Aurora.html#CHAP_GettingStartedAurora.Aurora.Connect")
	log.Println(strings.Repeat("-", 88))
}

// CreateSnapshot shows how to create a DB cluster snapshot and wait until it's available.
func (scenario GetStartedClusters) CreateSnapshot(ctx context.Context, clusterName string) {
	if scenario.questioner.AskBool(
		"Do you want to create a snapshot of your DB cluster (y/n)? ", "y") {
		snapshotId := fmt.Sprintf("%v-%v", clusterName, scenario.helper.UniqueId())
		log.Printf("Creating a snapshot named %v. This typically takes a few minutes.\n", snapshotId)
		snapshot, err := scenario.dbClusters.CreateClusterSnapshot(ctx, clusterName, snapshotId)
		if err != nil {
			panic(err)
		}
		for *snapshot.Status != "available" {
			scenario.helper.Pause(30)
			snapshot, err = scenario.dbClusters.GetClusterSnapshot(ctx, snapshotId)
			if err != nil {
				panic(err)
			}
		}
		log.Println("Snapshot data:")
		log.Printf("\tDBClusterSnapshotIdentifier: %v\n", *snapshot.DBClusterSnapshotIdentifier)
		log.Printf("\tARN: %v\n", *snapshot.DBClusterSnapshotArn)
		log.Printf("\tStatus: %v\n", *snapshot.Status)
		log.Printf("\tEngine: %v\n", *snapshot.Engine)
		log.Printf("\tEngine version: %v\n", *snapshot.EngineVersion)
		log.Printf("\tDBClusterIdentifier: %v\n", *snapshot.DBClusterIdentifier)
		log.Printf("\tSnapshotCreateTime: %v\n", *snapshot.SnapshotCreateTime)
		log.Println(strings.Repeat("-", 88))
	}
}

// Cleanup shows how to clean up a DB instance, DB cluster, and DB cluster parameter group.
// Before the DB cluster parameter group can be deleted, all associated DB instances and
// DB clusters must first be deleted.
func (scenario GetStartedClusters) Cleanup(ctx context.Context, dbInstance *types.DBInstance, cluster *types.DBCluster,
	parameterGroup *types.DBClusterParameterGroup) {

	if scenario.questioner.AskBool(
		"\nDo you want to delete the database instance, DB cluster, and parameter group (y/n)? ", "y") {
		log.Printf("Deleting database instance %v.\n", *dbInstance.DBInstanceIdentifier)
		err := scenario.dbClusters.DeleteInstance(ctx, *dbInstance.DBInstanceIdentifier)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleting database cluster %v.\n", *cluster.DBClusterIdentifier)
		err = scenario.dbClusters.DeleteDbCluster(ctx, *cluster.DBClusterIdentifier)
		if err != nil {
			panic(err)
		}
		log.Println(
			"Waiting for the DB instance and DB cluster to delete. This typically takes several minutes.")
		for dbInstance != nil || cluster != nil {
			scenario.helper.Pause(30)
			if dbInstance != nil {
				dbInstance, err = scenario.dbClusters.GetInstance(ctx, *dbInstance.DBInstanceIdentifier)
				if err != nil {
					panic(err)
				}
			}
			if cluster != nil {
				cluster, err = scenario.dbClusters.GetDbCluster(ctx, *cluster.DBClusterIdentifier)
				if err != nil {
					panic(err)
				}
			}
		}
		log.Printf("Deleting parameter group %v.", *parameterGroup.DBClusterParameterGroupName)
		err = scenario.dbClusters.DeleteParameterGroup(ctx, *parameterGroup.DBClusterParameterGroupName)
		if err != nil {
			panic(err)
		}
	}
}

// IScenarioHelper abstracts the function from a scenario so that it
// can be mocked for unit testing.
type IScenarioHelper interface {
	Pause(secs int)
	UniqueId() string
}
type ScenarioHelper struct{}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	time.Sleep(time.Duration(secs) * time.Second)
}

// UniqueId returns a new UUID.
func (helper ScenarioHelper) UniqueId() string {
	return uuid.New().String()
}
```
Aurora アクションを管理するためにシナリオによって呼び出される関数を定義します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}


// GetParameterGroup gets a DB cluster parameter group by name.
func (clusters *DbClusters) GetParameterGroup(ctx context.Context, parameterGroupName string) (
	*types.DBClusterParameterGroup, error) {
	output, err := clusters.AuroraClient.DescribeDBClusterParameterGroups(
		ctx, &rds.DescribeDBClusterParameterGroupsInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		var notFoundError *types.DBParameterGroupNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("Parameter group %v does not exist.\n", parameterGroupName)
			err = nil
		} else {
			log.Printf("Error getting parameter group %v: %v\n", parameterGroupName, err)
		}
		return nil, err
	} else {
		return &output.DBClusterParameterGroups[0], err
	}
}


// CreateParameterGroup creates a DB cluster parameter group that is based on the specified
// parameter group family.
func (clusters *DbClusters) CreateParameterGroup(
	ctx context.Context, parameterGroupName string, parameterGroupFamily string, description string) (
	*types.DBClusterParameterGroup, error) {

	output, err := clusters.AuroraClient.CreateDBClusterParameterGroup(ctx,
		&rds.CreateDBClusterParameterGroupInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
			DBParameterGroupFamily:      aws.String(parameterGroupFamily),
			Description:                 aws.String(description),
		})
	if err != nil {
		log.Printf("Couldn't create parameter group %v: %v\n", parameterGroupName, err)
		return nil, err
	} else {
		return output.DBClusterParameterGroup, err
	}
}



// DeleteParameterGroup deletes the named DB cluster parameter group.
func (clusters *DbClusters) DeleteParameterGroup(ctx context.Context, parameterGroupName string) error {
	_, err := clusters.AuroraClient.DeleteDBClusterParameterGroup(ctx,
		&rds.DeleteDBClusterParameterGroupInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		log.Printf("Couldn't delete parameter group %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}



// GetParameters gets the parameters that are contained in a DB cluster parameter group.
func (clusters *DbClusters) GetParameters(ctx context.Context, parameterGroupName string, source string) (
	[]types.Parameter, error) {

	var output *rds.DescribeDBClusterParametersOutput
	var params []types.Parameter
	var err error
	parameterPaginator := rds.NewDescribeDBClusterParametersPaginator(clusters.AuroraClient,
		&rds.DescribeDBClusterParametersInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
			Source:                      aws.String(source),
		})
	for parameterPaginator.HasMorePages() {
		output, err = parameterPaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get paramaeters for %v: %v\n", parameterGroupName, err)
			break
		} else {
			params = append(params, output.Parameters...)
		}
	}
	return params, err
}



// UpdateParameters updates parameters in a named DB cluster parameter group.
func (clusters *DbClusters) UpdateParameters(ctx context.Context, parameterGroupName string, params []types.Parameter) error {
	_, err := clusters.AuroraClient.ModifyDBClusterParameterGroup(ctx,
		&rds.ModifyDBClusterParameterGroupInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
			Parameters:                  params,
		})
	if err != nil {
		log.Printf("Couldn't update parameters in %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}



// GetDbCluster gets data about an Aurora DB cluster.
func (clusters *DbClusters) GetDbCluster(ctx context.Context, clusterName string) (*types.DBCluster, error) {
	output, err := clusters.AuroraClient.DescribeDBClusters(ctx,
		&rds.DescribeDBClustersInput{
			DBClusterIdentifier: aws.String(clusterName),
		})
	if err != nil {
		var notFoundError *types.DBClusterNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("DB cluster %v does not exist.\n", clusterName)
			err = nil
		} else {
			log.Printf("Couldn't get DB cluster %v: %v\n", clusterName, err)
		}
		return nil, err
	} else {
		return &output.DBClusters[0], err
	}
}



// CreateDbCluster creates a DB cluster that is configured to use the specified parameter group.
// The newly created DB cluster contains a database that uses the specified engine and
// engine version.
func (clusters *DbClusters) CreateDbCluster(ctx context.Context, clusterName string, parameterGroupName string,
	dbName string, dbEngine string, dbEngineVersion string, adminName string, adminPassword string) (
	*types.DBCluster, error) {

	output, err := clusters.AuroraClient.CreateDBCluster(ctx, &rds.CreateDBClusterInput{
		DBClusterIdentifier:         aws.String(clusterName),
		Engine:                      aws.String(dbEngine),
		DBClusterParameterGroupName: aws.String(parameterGroupName),
		DatabaseName:                aws.String(dbName),
		EngineVersion:               aws.String(dbEngineVersion),
		MasterUserPassword:          aws.String(adminPassword),
		MasterUsername:              aws.String(adminName),
	})
	if err != nil {
		log.Printf("Couldn't create DB cluster %v: %v\n", clusterName, err)
		return nil, err
	} else {
		return output.DBCluster, err
	}
}



// DeleteDbCluster deletes a DB cluster without keeping a final snapshot.
func (clusters *DbClusters) DeleteDbCluster(ctx context.Context, clusterName string) error {
	_, err := clusters.AuroraClient.DeleteDBCluster(ctx, &rds.DeleteDBClusterInput{
		DBClusterIdentifier: aws.String(clusterName),
		SkipFinalSnapshot:   aws.Bool(true),
	})
	if err != nil {
		log.Printf("Couldn't delete DB cluster %v: %v\n", clusterName, err)
		return err
	} else {
		return nil
	}
}



// CreateClusterSnapshot creates a snapshot of a DB cluster.
func (clusters *DbClusters) CreateClusterSnapshot(ctx context.Context, clusterName string, snapshotName string) (
	*types.DBClusterSnapshot, error) {
	output, err := clusters.AuroraClient.CreateDBClusterSnapshot(ctx, &rds.CreateDBClusterSnapshotInput{
		DBClusterIdentifier:         aws.String(clusterName),
		DBClusterSnapshotIdentifier: aws.String(snapshotName),
	})
	if err != nil {
		log.Printf("Couldn't create snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return output.DBClusterSnapshot, nil
	}
}



// GetClusterSnapshot gets a DB cluster snapshot.
func (clusters *DbClusters) GetClusterSnapshot(ctx context.Context, snapshotName string) (*types.DBClusterSnapshot, error) {
	output, err := clusters.AuroraClient.DescribeDBClusterSnapshots(ctx,
		&rds.DescribeDBClusterSnapshotsInput{
			DBClusterSnapshotIdentifier: aws.String(snapshotName),
		})
	if err != nil {
		log.Printf("Couldn't get snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return &output.DBClusterSnapshots[0], nil
	}
}



// CreateInstanceInCluster creates a database instance in an existing DB cluster. The first database that is
// created defaults to a read-write DB instance.
func (clusters *DbClusters) CreateInstanceInCluster(ctx context.Context, clusterName string, instanceName string,
	dbEngine string, dbInstanceClass string) (*types.DBInstance, error) {
	output, err := clusters.AuroraClient.CreateDBInstance(ctx, &rds.CreateDBInstanceInput{
		DBInstanceIdentifier: aws.String(instanceName),
		DBClusterIdentifier:  aws.String(clusterName),
		Engine:               aws.String(dbEngine),
		DBInstanceClass:      aws.String(dbInstanceClass),
	})
	if err != nil {
		log.Printf("Couldn't create instance %v: %v\n", instanceName, err)
		return nil, err
	} else {
		return output.DBInstance, nil
	}
}



// GetInstance gets data about a DB instance.
func (clusters *DbClusters) GetInstance(ctx context.Context, instanceName string) (
	*types.DBInstance, error) {
	output, err := clusters.AuroraClient.DescribeDBInstances(ctx,
		&rds.DescribeDBInstancesInput{
			DBInstanceIdentifier: aws.String(instanceName),
		})
	if err != nil {
		var notFoundError *types.DBInstanceNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("DB instance %v does not exist.\n", instanceName)
			err = nil
		} else {
			log.Printf("Couldn't get instance %v: %v\n", instanceName, err)
		}
		return nil, err
	} else {
		return &output.DBInstances[0], nil
	}
}



// DeleteInstance deletes a DB instance.
func (clusters *DbClusters) DeleteInstance(ctx context.Context, instanceName string) error {
	_, err := clusters.AuroraClient.DeleteDBInstance(ctx, &rds.DeleteDBInstanceInput{
		DBInstanceIdentifier:   aws.String(instanceName),
		SkipFinalSnapshot:      aws.Bool(true),
		DeleteAutomatedBackups: aws.Bool(true),
	})
	if err != nil {
		log.Printf("Couldn't delete instance %v: %v\n", instanceName, err)
		return err
	} else {
		return nil
	}
}



// GetEngineVersions gets database engine versions that are available for the specified engine
// and parameter group family.
func (clusters *DbClusters) GetEngineVersions(ctx context.Context, engine string, parameterGroupFamily string) (
	[]types.DBEngineVersion, error) {
	output, err := clusters.AuroraClient.DescribeDBEngineVersions(ctx,
		&rds.DescribeDBEngineVersionsInput{
			Engine:                 aws.String(engine),
			DBParameterGroupFamily: aws.String(parameterGroupFamily),
		})
	if err != nil {
		log.Printf("Couldn't get engine versions for %v: %v\n", engine, err)
		return nil, err
	} else {
		return output.DBEngineVersions, nil
	}
}



// GetOrderableInstances uses a paginator to get DB instance options that can be used to create DB instances that are
// compatible with a set of specifications.
func (clusters *DbClusters) GetOrderableInstances(ctx context.Context, engine string, engineVersion string) (
	[]types.OrderableDBInstanceOption, error) {

	var output *rds.DescribeOrderableDBInstanceOptionsOutput
	var instances []types.OrderableDBInstanceOption
	var err error
	orderablePaginator := rds.NewDescribeOrderableDBInstanceOptionsPaginator(clusters.AuroraClient,
		&rds.DescribeOrderableDBInstanceOptionsInput{
			Engine:        aws.String(engine),
			EngineVersion: aws.String(engineVersion),
		})
	for orderablePaginator.HasMorePages() {
		output, err = orderablePaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get orderable DB instances: %v\n", err)
			break
		} else {
			instances = append(instances, output.OrderableDBInstanceOptions...)
		}
	}
	return instances, err
}
```
+ API の詳細については、「AWS SDK for Go API リファレンス**」の以下のトピックを参照してください。
  + [CreateDBCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBCluster)
  + [CreateDBClusterParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBClusterParameterGroup)
  + [CreateDBClusterSnapshot](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBClusterSnapshot)
  + [CreateDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBInstance)
  + [DeleteDBCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBCluster)
  + [DeleteDBClusterParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBClusterParameterGroup)
  + [DeleteDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBInstance)
  + [DescribeDBClusterParameterGroups](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusterParameterGroups)
  + [DescribeDBClusterParameters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusterParameters)
  + [DescribeDBClusterSnapshots](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusterSnapshots)
  + [DescribeDBClusters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusters)
  + [DescribeDBEngineVersions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBEngineVersions)
  + [DescribeDBInstances](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBInstances)
  + [DescribeOrderableDBInstanceOptions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeOrderableDBInstanceOptions)
  + [ModifyDBClusterParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.ModifyDBClusterParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="aurora_CreateDBCluster_go_2_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// CreateDbCluster creates a DB cluster that is configured to use the specified parameter group.
// The newly created DB cluster contains a database that uses the specified engine and
// engine version.
func (clusters *DbClusters) CreateDbCluster(ctx context.Context, clusterName string, parameterGroupName string,
	dbName string, dbEngine string, dbEngineVersion string, adminName string, adminPassword string) (
	*types.DBCluster, error) {

	output, err := clusters.AuroraClient.CreateDBCluster(ctx, &rds.CreateDBClusterInput{
		DBClusterIdentifier:         aws.String(clusterName),
		Engine:                      aws.String(dbEngine),
		DBClusterParameterGroupName: aws.String(parameterGroupName),
		DatabaseName:                aws.String(dbName),
		EngineVersion:               aws.String(dbEngineVersion),
		MasterUserPassword:          aws.String(adminPassword),
		MasterUsername:              aws.String(adminName),
	})
	if err != nil {
		log.Printf("Couldn't create DB cluster %v: %v\n", clusterName, err)
		return nil, err
	} else {
		return output.DBCluster, err
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateDBCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBCluster)」を参照してください。

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_go_2_topic"></a>

次のコード例は、`CreateDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// CreateParameterGroup creates a DB cluster parameter group that is based on the specified
// parameter group family.
func (clusters *DbClusters) CreateParameterGroup(
	ctx context.Context, parameterGroupName string, parameterGroupFamily string, description string) (
	*types.DBClusterParameterGroup, error) {

	output, err := clusters.AuroraClient.CreateDBClusterParameterGroup(ctx,
		&rds.CreateDBClusterParameterGroupInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
			DBParameterGroupFamily:      aws.String(parameterGroupFamily),
			Description:                 aws.String(description),
		})
	if err != nil {
		log.Printf("Couldn't create parameter group %v: %v\n", parameterGroupName, err)
		return nil, err
	} else {
		return output.DBClusterParameterGroup, err
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateDBClusterParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBClusterParameterGroup)」を参照してください。

### `CreateDBClusterSnapshot`
<a name="aurora_CreateDBClusterSnapshot_go_2_topic"></a>

次のコード例は、`CreateDBClusterSnapshot` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// CreateClusterSnapshot creates a snapshot of a DB cluster.
func (clusters *DbClusters) CreateClusterSnapshot(ctx context.Context, clusterName string, snapshotName string) (
	*types.DBClusterSnapshot, error) {
	output, err := clusters.AuroraClient.CreateDBClusterSnapshot(ctx, &rds.CreateDBClusterSnapshotInput{
		DBClusterIdentifier:         aws.String(clusterName),
		DBClusterSnapshotIdentifier: aws.String(snapshotName),
	})
	if err != nil {
		log.Printf("Couldn't create snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return output.DBClusterSnapshot, nil
	}
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[CreateDBClusterSnapshot](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBClusterSnapshot)」を参照してください。

### `CreateDBInstance`
<a name="aurora_CreateDBInstance_go_2_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// CreateInstanceInCluster creates a database instance in an existing DB cluster. The first database that is
// created defaults to a read-write DB instance.
func (clusters *DbClusters) CreateInstanceInCluster(ctx context.Context, clusterName string, instanceName string,
	dbEngine string, dbInstanceClass string) (*types.DBInstance, error) {
	output, err := clusters.AuroraClient.CreateDBInstance(ctx, &rds.CreateDBInstanceInput{
		DBInstanceIdentifier: aws.String(instanceName),
		DBClusterIdentifier:  aws.String(clusterName),
		Engine:               aws.String(dbEngine),
		DBInstanceClass:      aws.String(dbInstanceClass),
	})
	if err != nil {
		log.Printf("Couldn't create instance %v: %v\n", instanceName, err)
		return nil, err
	} else {
		return output.DBInstance, nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBInstance)」を参照してください。

### `DeleteDBCluster`
<a name="aurora_DeleteDBCluster_go_2_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// DeleteDbCluster deletes a DB cluster without keeping a final snapshot.
func (clusters *DbClusters) DeleteDbCluster(ctx context.Context, clusterName string) error {
	_, err := clusters.AuroraClient.DeleteDBCluster(ctx, &rds.DeleteDBClusterInput{
		DBClusterIdentifier: aws.String(clusterName),
		SkipFinalSnapshot:   aws.Bool(true),
	})
	if err != nil {
		log.Printf("Couldn't delete DB cluster %v: %v\n", clusterName, err)
		return err
	} else {
		return nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteDBCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBCluster)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_go_2_topic"></a>

次のコード例は、`DeleteDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// DeleteParameterGroup deletes the named DB cluster parameter group.
func (clusters *DbClusters) DeleteParameterGroup(ctx context.Context, parameterGroupName string) error {
	_, err := clusters.AuroraClient.DeleteDBClusterParameterGroup(ctx,
		&rds.DeleteDBClusterParameterGroupInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		log.Printf("Couldn't delete parameter group %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteDBClusterParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBClusterParameterGroup)」を参照してください。

### `DeleteDBInstance`
<a name="aurora_DeleteDBInstance_go_2_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// DeleteInstance deletes a DB instance.
func (clusters *DbClusters) DeleteInstance(ctx context.Context, instanceName string) error {
	_, err := clusters.AuroraClient.DeleteDBInstance(ctx, &rds.DeleteDBInstanceInput{
		DBInstanceIdentifier:   aws.String(instanceName),
		SkipFinalSnapshot:      aws.Bool(true),
		DeleteAutomatedBackups: aws.Bool(true),
	})
	if err != nil {
		log.Printf("Couldn't delete instance %v: %v\n", instanceName, err)
		return err
	} else {
		return nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBInstance)」を参照してください。

### `DescribeDBClusterParameterGroups`
<a name="aurora_DescribeDBClusterParameterGroups_go_2_topic"></a>

次のコード例は、`DescribeDBClusterParameterGroups` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// GetParameterGroup gets a DB cluster parameter group by name.
func (clusters *DbClusters) GetParameterGroup(ctx context.Context, parameterGroupName string) (
	*types.DBClusterParameterGroup, error) {
	output, err := clusters.AuroraClient.DescribeDBClusterParameterGroups(
		ctx, &rds.DescribeDBClusterParameterGroupsInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		var notFoundError *types.DBParameterGroupNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("Parameter group %v does not exist.\n", parameterGroupName)
			err = nil
		} else {
			log.Printf("Error getting parameter group %v: %v\n", parameterGroupName, err)
		}
		return nil, err
	} else {
		return &output.DBClusterParameterGroups[0], err
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBClusterParameterGroups](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusterParameterGroups)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_go_2_topic"></a>

次のコード例は、`DescribeDBClusterParameters` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// GetParameters gets the parameters that are contained in a DB cluster parameter group.
func (clusters *DbClusters) GetParameters(ctx context.Context, parameterGroupName string, source string) (
	[]types.Parameter, error) {

	var output *rds.DescribeDBClusterParametersOutput
	var params []types.Parameter
	var err error
	parameterPaginator := rds.NewDescribeDBClusterParametersPaginator(clusters.AuroraClient,
		&rds.DescribeDBClusterParametersInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
			Source:                      aws.String(source),
		})
	for parameterPaginator.HasMorePages() {
		output, err = parameterPaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get paramaeters for %v: %v\n", parameterGroupName, err)
			break
		} else {
			params = append(params, output.Parameters...)
		}
	}
	return params, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBClusterParameters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusterParameters)」を参照してください。

### `DescribeDBClusterSnapshots`
<a name="aurora_DescribeDBClusterSnapshots_go_2_topic"></a>

次のコード例は、`DescribeDBClusterSnapshots` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// GetClusterSnapshot gets a DB cluster snapshot.
func (clusters *DbClusters) GetClusterSnapshot(ctx context.Context, snapshotName string) (*types.DBClusterSnapshot, error) {
	output, err := clusters.AuroraClient.DescribeDBClusterSnapshots(ctx,
		&rds.DescribeDBClusterSnapshotsInput{
			DBClusterSnapshotIdentifier: aws.String(snapshotName),
		})
	if err != nil {
		log.Printf("Couldn't get snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return &output.DBClusterSnapshots[0], nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBClusterSnapshots](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusterSnapshots)」を参照してください。

### `DescribeDBClusters`
<a name="aurora_DescribeDBClusters_go_2_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// GetDbCluster gets data about an Aurora DB cluster.
func (clusters *DbClusters) GetDbCluster(ctx context.Context, clusterName string) (*types.DBCluster, error) {
	output, err := clusters.AuroraClient.DescribeDBClusters(ctx,
		&rds.DescribeDBClustersInput{
			DBClusterIdentifier: aws.String(clusterName),
		})
	if err != nil {
		var notFoundError *types.DBClusterNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("DB cluster %v does not exist.\n", clusterName)
			err = nil
		} else {
			log.Printf("Couldn't get DB cluster %v: %v\n", clusterName, err)
		}
		return nil, err
	} else {
		return &output.DBClusters[0], err
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBClusters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBClusters)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_go_2_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// GetEngineVersions gets database engine versions that are available for the specified engine
// and parameter group family.
func (clusters *DbClusters) GetEngineVersions(ctx context.Context, engine string, parameterGroupFamily string) (
	[]types.DBEngineVersion, error) {
	output, err := clusters.AuroraClient.DescribeDBEngineVersions(ctx,
		&rds.DescribeDBEngineVersionsInput{
			Engine:                 aws.String(engine),
			DBParameterGroupFamily: aws.String(parameterGroupFamily),
		})
	if err != nil {
		log.Printf("Couldn't get engine versions for %v: %v\n", engine, err)
		return nil, err
	} else {
		return output.DBEngineVersions, nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBEngineVersions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="aurora_DescribeDBInstances_go_2_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// GetInstance gets data about a DB instance.
func (clusters *DbClusters) GetInstance(ctx context.Context, instanceName string) (
	*types.DBInstance, error) {
	output, err := clusters.AuroraClient.DescribeDBInstances(ctx,
		&rds.DescribeDBInstancesInput{
			DBInstanceIdentifier: aws.String(instanceName),
		})
	if err != nil {
		var notFoundError *types.DBInstanceNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("DB instance %v does not exist.\n", instanceName)
			err = nil
		} else {
			log.Printf("Couldn't get instance %v: %v\n", instanceName, err)
		}
		return nil, err
	} else {
		return &output.DBInstances[0], nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBInstances](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBInstances)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="aurora_DescribeOrderableDBInstanceOptions_go_2_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// GetOrderableInstances uses a paginator to get DB instance options that can be used to create DB instances that are
// compatible with a set of specifications.
func (clusters *DbClusters) GetOrderableInstances(ctx context.Context, engine string, engineVersion string) (
	[]types.OrderableDBInstanceOption, error) {

	var output *rds.DescribeOrderableDBInstanceOptionsOutput
	var instances []types.OrderableDBInstanceOption
	var err error
	orderablePaginator := rds.NewDescribeOrderableDBInstanceOptionsPaginator(clusters.AuroraClient,
		&rds.DescribeOrderableDBInstanceOptionsInput{
			Engine:        aws.String(engine),
			EngineVersion: aws.String(engineVersion),
		})
	for orderablePaginator.HasMorePages() {
		output, err = orderablePaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get orderable DB instances: %v\n", err)
			break
		} else {
			instances = append(instances, output.OrderableDBInstanceOptions...)
		}
	}
	return instances, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_go_2_topic"></a>

次のコード例は、`ModifyDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/aurora#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbClusters struct {
	AuroraClient *rds.Client
}



// UpdateParameters updates parameters in a named DB cluster parameter group.
func (clusters *DbClusters) UpdateParameters(ctx context.Context, parameterGroupName string, params []types.Parameter) error {
	_, err := clusters.AuroraClient.ModifyDBClusterParameterGroup(ctx,
		&rds.ModifyDBClusterParameterGroupInput{
			DBClusterParameterGroupName: aws.String(parameterGroupName),
			Parameters:                  params,
		})
	if err != nil {
		log.Printf("Couldn't update parameters in %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[ModifyDBClusterParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.ModifyDBClusterParameterGroup)」を参照してください。

# SDK for Go V2 を使用する Amazon Bedrock の例
<a name="go_2_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Bedrock
<a name="bedrock_Hello_go_2_topic"></a>

次のコード例は、Amazon Bedrock の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/bedrock"
)

const region = "us-east-1"

// main uses the AWS SDK for Go (v2) to create an Amazon Bedrock client and
// list the available foundation models in your account and the chosen region.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx, config.WithRegion(region))
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	bedrockClient := bedrock.NewFromConfig(sdkConfig)
	result, err := bedrockClient.ListFoundationModels(ctx, &bedrock.ListFoundationModelsInput{})
	if err != nil {
		fmt.Printf("Couldn't list foundation models. Here's why: %v\n", err)
		return
	}
	if len(result.ModelSummaries) == 0 {
		fmt.Println("There are no foundation models.")
	}
	for _, modelSummary := range result.ModelSummaries {
		fmt.Println(*modelSummary.ModelId)
	}
}
```
+  API の詳細については、「AWS SDK for Go API リファレンス**」の「[ListFoundationModels](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrock#Client.ListFoundationModels)」を参照してください。

## アクション
<a name="actions"></a>

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_go_2_topic"></a>

次のコード例は、`ListFoundationModels` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock#code-examples)での設定と実行の方法を確認してください。
利用可能な Bedrock 基盤モデルを一覧表示します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/bedrock"
	"github.com/aws/aws-sdk-go-v2/service/bedrock/types"
)

// FoundationModelWrapper encapsulates Amazon Bedrock actions used in the examples.
// It contains a Bedrock service client that is used to perform foundation model actions.
type FoundationModelWrapper struct {
	BedrockClient *bedrock.Client
}



// ListPolicies lists Bedrock foundation models that you can use.
func (wrapper FoundationModelWrapper) ListFoundationModels(ctx context.Context) ([]types.FoundationModelSummary, error) {

	var models []types.FoundationModelSummary

	result, err := wrapper.BedrockClient.ListFoundationModels(ctx, &bedrock.ListFoundationModelsInput{})

	if err != nil {
		log.Printf("Couldn't list foundation models. Here's why: %v\n", err)
	} else {
		models = result.ModelSummaries
	}
	return models, err
}
```
+  API の詳細については、「AWS SDK for Go API リファレンス**」の「[ListFoundationModels](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrock#Client.ListFoundationModels)」を参照してください。

# SDK for Go V2 を使用した Amazon Bedrock ランタイムの例
<a name="go_2_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイムで AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [シナリオ](#scenarios)
+ [Amazon Titan Image Generator](#amazon_titan_image_generator)
+ [Anthropic Claude](#anthropic_claude)

## はじめに
<a name="get_started"></a>

### Hello Amazon Bedrock
<a name="bedrock-runtime_Hello_go_2_topic"></a>

次のコード例は、Amazon Bedrock の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
)

// Each model provider defines their own individual request and response formats.
// For the format, ranges, and default values for the different models, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html

type ClaudeRequest struct {
	Prompt            string `json:"prompt"`
	MaxTokensToSample int    `json:"max_tokens_to_sample"`
	// Omitting optional request parameters
}

type ClaudeResponse struct {
	Completion string `json:"completion"`
}

// main uses the AWS SDK for Go (v2) to create an Amazon Bedrock Runtime client
// and invokes Anthropic Claude 2 inside your account and the chosen region.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {

	region := flag.String("region", "us-east-1", "The AWS region")
	flag.Parse()

	fmt.Printf("Using AWS region: %s\n", *region)

	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx, config.WithRegion(*region))
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}

	client := bedrockruntime.NewFromConfig(sdkConfig)

	modelId := "anthropic.claude-v2"

	prompt := "Hello, how are you today?"

	// Anthropic Claude requires you to enclose the prompt as follows:
	prefix := "Human: "
	postfix := "\n\nAssistant:"
	wrappedPrompt := prefix + prompt + postfix

	request := ClaudeRequest{
		Prompt:            wrappedPrompt,
		MaxTokensToSample: 200,
	}

	body, err := json.Marshal(request)
	if err != nil {
		log.Panicln("Couldn't marshal the request: ", err)
	}

	result, err := client.InvokeModel(ctx, &bedrockruntime.InvokeModelInput{
		ModelId:     aws.String(modelId),
		ContentType: aws.String("application/json"),
		Body:        body,
	})

	if err != nil {
		errMsg := err.Error()
		if strings.Contains(errMsg, "no such host") {
			fmt.Printf("Error: The Bedrock service is not available in the selected region. Please double-check the service availability for your region at https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/.\n")
		} else if strings.Contains(errMsg, "Could not resolve the foundation model") {
			fmt.Printf("Error: Could not resolve the foundation model from model identifier: \"%v\". Please verify that the requested model exists and is accessible within the specified region.\n", modelId)
		} else {
			fmt.Printf("Error: Couldn't invoke Anthropic Claude. Here's why: %v\n", err)
		}
		os.Exit(1)
	}

	var response ClaudeResponse

	err = json.Unmarshal(result.Body, &response)

	if err != nil {
		log.Fatal("failed to unmarshal", err)
	}
	fmt.Println("Prompt:\n", prompt)
	fmt.Println("Response from Anthropic Claude:\n", response.Completion)
}
```
+  API の詳細については、「**AWS SDK for Go API リファレンス」の「[InvokeModel](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrockruntime#Client.InvokeModel)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Bedrock で複数の基盤モデルを呼び出す
<a name="bedrock-runtime_Scenario_InvokeModels_go_2_topic"></a>

次のコード例は、Amazon Bedrock でさまざまな大規模言語モデル (LLM) にプロンプトを準備して送信する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で複数の基盤モデルを呼び出します。  

```
import (
	"context"
	"encoding/base64"
	"fmt"
	"log"
	"math/rand"
	"os"
	"path/filepath"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/bedrock-runtime/actions"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// InvokeModelsScenario demonstrates how to use the Amazon Bedrock Runtime client
// to invoke various foundation models for text and image generation
//
// 1. Generate text with Anthropic Claude 2
// 2. Generate text with Meta Llama 2 Chat
// 3. Generate text and asynchronously process the response stream with Anthropic Claude 2
// 4. Generate an image with the Amazon Titan image generation model
type InvokeModelsScenario struct {
	sdkConfig             aws.Config
	invokeModelWrapper    actions.InvokeModelWrapper
	responseStreamWrapper actions.InvokeModelWithResponseStreamWrapper
	questioner            demotools.IQuestioner
}

// NewInvokeModelsScenario constructs an InvokeModelsScenario instance from a configuration.
// It uses the specified config to get a Bedrock Runtime client and create wrappers for the
// actions used in the scenario.
func NewInvokeModelsScenario(sdkConfig aws.Config, questioner demotools.IQuestioner) InvokeModelsScenario {
	client := bedrockruntime.NewFromConfig(sdkConfig)
	return InvokeModelsScenario{
		sdkConfig:             sdkConfig,
		invokeModelWrapper:    actions.InvokeModelWrapper{BedrockRuntimeClient: client},
		responseStreamWrapper: actions.InvokeModelWithResponseStreamWrapper{BedrockRuntimeClient: client},
		questioner:            questioner,
	}
}

// Runs the interactive scenario.
func (scenario InvokeModelsScenario) Run(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong with the demo: %v\n", r)
		}
	}()

	log.Println(strings.Repeat("=", 77))
	log.Println("Welcome to the Amazon Bedrock Runtime model invocation demo.")
	log.Println(strings.Repeat("=", 77))

	log.Printf("First, let's invoke a few large-language models using the synchronous client:\n\n")

	text2textPrompt := "In one paragraph, who are you?"

	log.Println(strings.Repeat("-", 77))
	log.Printf("Invoking Claude with prompt: %v\n", text2textPrompt)
	scenario.InvokeClaude(ctx, text2textPrompt)

	log.Println(strings.Repeat("=", 77))
	log.Printf("Now, let's invoke Claude with the asynchronous client and process the response stream:\n\n")

	log.Println(strings.Repeat("-", 77))
	log.Printf("Invoking Claude with prompt: %v\n", text2textPrompt)
	scenario.InvokeWithResponseStream(ctx, text2textPrompt)

	log.Println(strings.Repeat("=", 77))
	log.Printf("Now, let's create an image with the Amazon Titan image generation model:\n\n")

	text2ImagePrompt := "stylized picture of a cute old steampunk robot"
	seed := rand.Int63n(2147483648)

	log.Println(strings.Repeat("-", 77))
	log.Printf("Invoking Amazon Titan with prompt: %v\n", text2ImagePrompt)
	scenario.InvokeTitanImage(ctx, text2ImagePrompt, seed)

	log.Println(strings.Repeat("=", 77))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("=", 77))
}

func (scenario InvokeModelsScenario) InvokeClaude(ctx context.Context, prompt string) {
	completion, err := scenario.invokeModelWrapper.InvokeClaude(ctx, prompt)
	if err != nil {
		panic(err)
	}
	log.Printf("\nClaude     : %v\n", strings.TrimSpace(completion))
}

func (scenario InvokeModelsScenario) InvokeWithResponseStream(ctx context.Context, prompt string) {
	log.Println("\nClaude with response stream:")
	_, err := scenario.responseStreamWrapper.InvokeModelWithResponseStream(ctx, prompt)
	if err != nil {
		panic(err)
	}
	log.Println()
}

func (scenario InvokeModelsScenario) InvokeTitanImage(ctx context.Context, prompt string, seed int64) {
	base64ImageData, err := scenario.invokeModelWrapper.InvokeTitanImage(ctx, prompt, seed)
	if err != nil {
		panic(err)
	}
	imagePath := saveImage(base64ImageData, "amazon.titan-image-generator-v2")
	fmt.Printf("The generated image has been saved to %s\n", imagePath)
}
```
+ API の詳細については、「AWS SDK for Go API リファレンス**」の以下のトピックを参照してください。
  + [InvokeModel](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrockruntime#Client.InvokeModel)
  + [InvokeModelWithResponseStream](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrockruntime#Client.InvokeModelWithResponseStream)

## Amazon Titan Image Generator
<a name="amazon_titan_image_generator"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_TitanImageGenerator_go_2_topic"></a>

次のコード例は、Amazon Bedrock で Amazon Titan Image を呼び出して画像を生成する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Titan Image Generator を使用して画像を作成します。  

```
import (
	"context"
	"encoding/json"
	"log"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
)

// InvokeModelWrapper encapsulates Amazon Bedrock actions used in the examples.
// It contains a Bedrock Runtime client that is used to invoke foundation models.
type InvokeModelWrapper struct {
	BedrockRuntimeClient *bedrockruntime.Client
}



type TitanImageRequest struct {
	TaskType              string                `json:"taskType"`
	TextToImageParams     TextToImageParams     `json:"textToImageParams"`
	ImageGenerationConfig ImageGenerationConfig `json:"imageGenerationConfig"`
}
type TextToImageParams struct {
	Text string `json:"text"`
}
type ImageGenerationConfig struct {
	NumberOfImages int     `json:"numberOfImages"`
	Quality        string  `json:"quality"`
	CfgScale       float64 `json:"cfgScale"`
	Height         int     `json:"height"`
	Width          int     `json:"width"`
	Seed           int64   `json:"seed"`
}

type TitanImageResponse struct {
	Images []string `json:"images"`
}

// Invokes the Titan Image model to create an image using the input provided
// in the request body.
func (wrapper InvokeModelWrapper) InvokeTitanImage(ctx context.Context, prompt string, seed int64) (string, error) {
	modelId := "amazon.titan-image-generator-v2:0"

	body, err := json.Marshal(TitanImageRequest{
		TaskType: "TEXT_IMAGE",
		TextToImageParams: TextToImageParams{
			Text: prompt,
		},
		ImageGenerationConfig: ImageGenerationConfig{
			NumberOfImages: 1,
			Quality:        "standard",
			CfgScale:       8.0,
			Height:         512,
			Width:          512,
			Seed:           seed,
		},
	})

	if err != nil {
		log.Fatal("failed to marshal", err)
	}

	output, err := wrapper.BedrockRuntimeClient.InvokeModel(ctx, &bedrockruntime.InvokeModelInput{
		ModelId:     aws.String(modelId),
		ContentType: aws.String("application/json"),
		Body:        body,
	})

	if err != nil {
		ProcessError(err, modelId)
	}

	var response TitanImageResponse
	if err := json.Unmarshal(output.Body, &response); err != nil {
		log.Fatal("failed to unmarshal", err)
	}

	base64ImageData := response.Images[0]

	return base64ImageData, nil

}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[InvokeModel](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrockruntime#Client.InvokeModel)」を参照してください。

## Anthropic Claude
<a name="anthropic_claude"></a>

### Converse
<a name="bedrock-runtime_Converse_AnthropicClaude_go_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。  

```
import (
	"context"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types"
)

// ConverseWrapper encapsulates Amazon Bedrock actions used in the examples.
// It contains a Bedrock Runtime client that is used to invoke Bedrock.
type ConverseWrapper struct {
	BedrockRuntimeClient *bedrockruntime.Client
}



func (wrapper ConverseWrapper) ConverseClaude(ctx context.Context, prompt string) (string, error) {
	var content = types.ContentBlockMemberText{
		Value: prompt,
	}
	var message = types.Message{
		Content: []types.ContentBlock{&content},
		Role:    "user",
	}
	modelId := "anthropic.claude-3-haiku-20240307-v1:0"
	var converseInput = bedrockruntime.ConverseInput{
		ModelId:  aws.String(modelId),
		Messages: []types.Message{message},
	}
	response, err := wrapper.BedrockRuntimeClient.Converse(ctx, &converseInput)
	if err != nil {
		ProcessError(err, modelId)
	}

	responseText, _ := response.Output.(*types.ConverseOutputMemberMessage)
	responseContentBlock := responseText.Value.Content[0]
	text, _ := responseContentBlock.(*types.ContentBlockMemberText)
	return text.Value, nil

}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[Converse](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrockruntime#Client.Converse)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AnthropicClaude_go_2_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Anthropic Claude 2 基盤モデルを呼び出して、テキストを生成します。  

```
import (
	"context"
	"encoding/json"
	"log"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
)

// InvokeModelWrapper encapsulates Amazon Bedrock actions used in the examples.
// It contains a Bedrock Runtime client that is used to invoke foundation models.
type InvokeModelWrapper struct {
	BedrockRuntimeClient *bedrockruntime.Client
}



// Each model provider has their own individual request and response formats.
// For the format, ranges, and default values for Anthropic Claude, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html

type ClaudeRequest struct {
	Prompt            string   `json:"prompt"`
	MaxTokensToSample int      `json:"max_tokens_to_sample"`
	Temperature       float64  `json:"temperature,omitempty"`
	StopSequences     []string `json:"stop_sequences,omitempty"`
}

type ClaudeResponse struct {
	Completion string `json:"completion"`
}

// Invokes Anthropic Claude on Amazon Bedrock to run an inference using the input
// provided in the request body.
func (wrapper InvokeModelWrapper) InvokeClaude(ctx context.Context, prompt string) (string, error) {
	modelId := "anthropic.claude-v2"

	// Anthropic Claude requires enclosing the prompt as follows:
	enclosedPrompt := "Human: " + prompt + "\n\nAssistant:"

	body, err := json.Marshal(ClaudeRequest{
		Prompt:            enclosedPrompt,
		MaxTokensToSample: 200,
		Temperature:       0.5,
		StopSequences:     []string{"\n\nHuman:"},
	})

	if err != nil {
		log.Fatal("failed to marshal", err)
	}

	output, err := wrapper.BedrockRuntimeClient.InvokeModel(ctx, &bedrockruntime.InvokeModelInput{
		ModelId:     aws.String(modelId),
		ContentType: aws.String("application/json"),
		Body:        body,
	})

	if err != nil {
		ProcessError(err, modelId)
	}

	var response ClaudeResponse
	if err := json.Unmarshal(output.Body, &response); err != nil {
		log.Fatal("failed to unmarshal", err)
	}

	return response.Completion, nil
}
```
+  API の詳細については、「**AWS SDK for Go API リファレンス」の「[InvokeModel](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrockruntime#Client.InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_AnthropicClaude_go_2_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime"
	"github.com/aws/aws-sdk-go-v2/service/bedrockruntime/types"
)

// InvokeModelWithResponseStreamWrapper encapsulates Amazon Bedrock actions used in the examples.
// It contains a Bedrock Runtime client that is used to invoke foundation models.
type InvokeModelWithResponseStreamWrapper struct {
	BedrockRuntimeClient *bedrockruntime.Client
}



// Each model provider defines their own individual request and response formats.
// For the format, ranges, and default values for the different models, refer to:
// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html

type Request struct {
	Prompt            string  `json:"prompt"`
	MaxTokensToSample int     `json:"max_tokens_to_sample"`
	Temperature       float64 `json:"temperature,omitempty"`
}

type Response struct {
	Completion string `json:"completion"`
}

// Invokes Anthropic Claude on Amazon Bedrock to run an inference and asynchronously
// process the response stream.

func (wrapper InvokeModelWithResponseStreamWrapper) InvokeModelWithResponseStream(ctx context.Context, prompt string) (string, error) {

	modelId := "anthropic.claude-v2"

	// Anthropic Claude requires you to enclose the prompt as follows:
	prefix := "Human: "
	postfix := "\n\nAssistant:"
	prompt = prefix + prompt + postfix

	request := ClaudeRequest{
		Prompt:            prompt,
		MaxTokensToSample: 200,
		Temperature:       0.5,
		StopSequences:     []string{"\n\nHuman:"},
	}

	body, err := json.Marshal(request)
	if err != nil {
		log.Panicln("Couldn't marshal the request: ", err)
	}

	output, err := wrapper.BedrockRuntimeClient.InvokeModelWithResponseStream(ctx, &bedrockruntime.InvokeModelWithResponseStreamInput{
		Body:        body,
		ModelId:     aws.String(modelId),
		ContentType: aws.String("application/json"),
	})

	if err != nil {
		errMsg := err.Error()
		if strings.Contains(errMsg, "no such host") {
			log.Printf("The Bedrock service is not available in the selected region. Please double-check the service availability for your region at https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/.\n")
		} else if strings.Contains(errMsg, "Could not resolve the foundation model") {
			log.Printf("Could not resolve the foundation model from model identifier: \"%v\". Please verify that the requested model exists and is accessible within the specified region.\n", modelId)
		} else {
			log.Printf("Couldn't invoke Anthropic Claude. Here's why: %v\n", err)
		}
	}

	resp, err := processStreamingOutput(ctx, output, func(ctx context.Context, part []byte) error {
		fmt.Print(string(part))
		return nil
	})

	if err != nil {
		log.Fatal("streaming output processing error: ", err)
	}

	return resp.Completion, nil

}

type StreamingOutputHandler func(ctx context.Context, part []byte) error

func processStreamingOutput(ctx context.Context, output *bedrockruntime.InvokeModelWithResponseStreamOutput, handler StreamingOutputHandler) (Response, error) {

	var combinedResult string
	resp := Response{}

	for event := range output.GetStream().Events() {
		switch v := event.(type) {
		case *types.ResponseStreamMemberChunk:

			//fmt.Println("payload", string(v.Value.Bytes))

			var resp Response
			err := json.NewDecoder(bytes.NewReader(v.Value.Bytes)).Decode(&resp)
			if err != nil {
				return resp, err
			}

			err = handler(ctx, []byte(resp.Completion))
			if err != nil {
				return resp, err
			}

			combinedResult += resp.Completion

		case *types.UnknownUnionMember:
			fmt.Println("unknown tag:", v.Tag)

		default:
			fmt.Println("union is nil or unknown type")
		}
	}

	resp.Completion = combinedResult

	return resp, nil
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[InvokeModelWithResponseStream](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/bedrockruntime#Client.InvokeModelWithResponseStream)」を参照してください。

# CloudFormation SDK for Go V2 を使用した の例
<a name="go_2_cloudformation_code_examples"></a>

次のコード例は、 で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています CloudFormation。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeStacks`
<a name="cloudformation_DescribeStacks_go_2_topic"></a>

次のコード例は、`DescribeStacks` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[DescribeStacks](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cloudformation#Client.DescribeStacks)」を参照してください。

# SDK for Go V2 を使用した CloudWatch Logs のコード例
<a name="go_2_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `StartLiveTail`
<a name="cloudwatch-logs_StartLiveTail_go_2_topic"></a>

次のコード例は、`StartLiveTail` を使用する方法を示しています。

**SDK for Go V2**  
必要なファイルを含めます。  

```
import (
	"context"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
)
```
Live Tail セッションのイベントを処理します。  

```
func handleEventStreamAsync(stream *cloudwatchlogs.StartLiveTailEventStream) {
	eventsChan := stream.Events()
	for {
		event := <-eventsChan
		switch e := event.(type) {
		case *types.StartLiveTailResponseStreamMemberSessionStart:
			log.Println("Received SessionStart event")
		case *types.StartLiveTailResponseStreamMemberSessionUpdate:
			for _, logEvent := range e.Value.SessionResults {
				log.Println(*logEvent.Message)
			}
		default:
			// Handle on-stream exceptions
			if err := stream.Err(); err != nil {
				log.Fatalf("Error occured during streaming: %v", err)
			} else if event == nil {
				log.Println("Stream is Closed")
				return
			} else {
				log.Fatalf("Unknown event type: %T", e)
			}
		}
	}
}
```
Live Tail セッションを開始します。  

```
	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		panic("configuration error, " + err.Error())
	}
	client := cloudwatchlogs.NewFromConfig(cfg)

	request := &cloudwatchlogs.StartLiveTailInput{
		LogGroupIdentifiers:   logGroupIdentifiers,
		LogStreamNames:        logStreamNames,
		LogEventFilterPattern: logEventFilterPattern,
	}

	response, err := client.StartLiveTail(context.TODO(), request)
	// Handle pre-stream Exceptions
	if err != nil {
		log.Fatalf("Failed to start streaming: %v", err)
	}

	// Start a Goroutine to handle events over stream
	stream := response.GetStream()
	go handleEventStreamAsync(stream)
```
一定時間が経過したら Live Tail セッションを停止します。  

```
	// Close the stream (which ends the session) after a timeout
	time.Sleep(10 * time.Second)
	stream.Close()
	log.Println("Event stream closed")
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[StartLiveTail](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs#Client.StartLiveTail)」を参照してください。

# SDK for Go V2 を使用する Amazon Cognito ID プロバイダーの例
<a name="go_2_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Cognito
<a name="cognito-identity-provider_Hello_go_2_topic"></a>

次のコード例は、Amazon Cognito の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

// main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service
// (Amazon SNS) client and list the topics in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	cognitoClient := cognitoidentityprovider.NewFromConfig(sdkConfig)
	fmt.Println("Let's list the user pools for your account.")
	var pools []types.UserPoolDescriptionType
	paginator := cognitoidentityprovider.NewListUserPoolsPaginator(
		cognitoClient, &cognitoidentityprovider.ListUserPoolsInput{MaxResults: aws.Int32(10)})
	for paginator.HasMorePages() {
		output, err := paginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get user pools. Here's why: %v\n", err)
		} else {
			pools = append(pools, output.UserPools...)
		}
	}
	if len(pools) == 0 {
		fmt.Println("You don't have any user pools!")
	} else {
		for _, pool := range pools {
			fmt.Printf("\t%v: %v\n", *pool.Name, *pool.Id)
		}
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListUserPools](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ListUserPools)」を参照してください。

## アクション
<a name="actions"></a>

### `AdminCreateUser`
<a name="cognito-identity-provider_AdminCreateUser_go_2_topic"></a>

次のコード例は、`AdminCreateUser` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// AdminCreateUser uses administrator credentials to add a user to a user pool. This method leaves the user
// in a state that requires they enter a new password next time they sign in.
func (actor CognitoActions) AdminCreateUser(ctx context.Context, userPoolId string, userName string, userEmail string) error {
	_, err := actor.CognitoClient.AdminCreateUser(ctx, &cognitoidentityprovider.AdminCreateUserInput{
		UserPoolId:     aws.String(userPoolId),
		Username:       aws.String(userName),
		MessageAction:  types.MessageActionTypeSuppress,
		UserAttributes: []types.AttributeType{{Name: aws.String("email"), Value: aws.String(userEmail)}},
	})
	if err != nil {
		var userExists *types.UsernameExistsException
		if errors.As(err, &userExists) {
			log.Printf("User %v already exists in the user pool.", userName)
			err = nil
		} else {
			log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[AdminCreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.AdminCreateUser)」を参照してください。

### `AdminSetUserPassword`
<a name="cognito-identity-provider_AdminSetUserPassword_go_2_topic"></a>

次のコード例は、`AdminSetUserPassword` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[AdminSetUserPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.AdminSetUserPassword)」を参照してください。

### `ConfirmForgotPassword`
<a name="cognito-identity-provider_ConfirmForgotPassword_go_2_topic"></a>

次のコード例は、`ConfirmForgotPassword` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// ConfirmForgotPassword confirms a user with a confirmation code and a new password.
func (actor CognitoActions) ConfirmForgotPassword(ctx context.Context, clientId string, code string, userName string, password string) error {
	_, err := actor.CognitoClient.ConfirmForgotPassword(ctx, &cognitoidentityprovider.ConfirmForgotPasswordInput{
		ClientId:         aws.String(clientId),
		ConfirmationCode: aws.String(code),
		Password:         aws.String(password),
		Username:         aws.String(userName),
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't confirm user %v. Here's why: %v", userName, err)
		}
	}
	return err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ConfirmForgotPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ConfirmForgotPassword)」を参照してください。

### `DeleteUser`
<a name="cognito-identity-provider_DeleteUser_go_2_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// DeleteUser removes a user from the user pool.
func (actor CognitoActions) DeleteUser(ctx context.Context, userAccessToken string) error {
	_, err := actor.CognitoClient.DeleteUser(ctx, &cognitoidentityprovider.DeleteUserInput{
		AccessToken: aws.String(userAccessToken),
	})
	if err != nil {
		log.Printf("Couldn't delete user. Here's why: %v\n", err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.DeleteUser)」を参照してください。

### `ForgotPassword`
<a name="cognito-identity-provider_ForgotPassword_go_2_topic"></a>

次のコード例は、`ForgotPassword` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// ForgotPassword starts a password recovery flow for a user. This flow typically sends a confirmation code
// to the user's configured notification destination, such as email.
func (actor CognitoActions) ForgotPassword(ctx context.Context, clientId string, userName string) (*types.CodeDeliveryDetailsType, error) {
	output, err := actor.CognitoClient.ForgotPassword(ctx, &cognitoidentityprovider.ForgotPasswordInput{
		ClientId: aws.String(clientId),
		Username: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't start password reset for user '%v'. Here;s why: %v\n", userName, err)
	}
	return output.CodeDeliveryDetails, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ForgotPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ForgotPassword)」を参照してください。

### `InitiateAuth`
<a name="cognito-identity-provider_InitiateAuth_go_2_topic"></a>

次のコード例は、`InitiateAuth` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// SignIn signs in a user to Amazon Cognito using a username and password authentication flow.
func (actor CognitoActions) SignIn(ctx context.Context, clientId string, userName string, password string) (*types.AuthenticationResultType, error) {
	var authResult *types.AuthenticationResultType
	output, err := actor.CognitoClient.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
		AuthFlow:       "USER_PASSWORD_AUTH",
		ClientId:       aws.String(clientId),
		AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password},
	})
	if err != nil {
		var resetRequired *types.PasswordResetRequiredException
		if errors.As(err, &resetRequired) {
			log.Println(*resetRequired.Message)
		} else {
			log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err)
		}
	} else {
		authResult = output.AuthenticationResult
	}
	return authResult, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[InitiateAuth](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.InitiateAuth)」を参照してください。

### `ListUserPools`
<a name="cognito-identity-provider_ListUserPools_go_2_topic"></a>

次のコード例は、`ListUserPools` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

// main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service
// (Amazon SNS) client and list the topics in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	cognitoClient := cognitoidentityprovider.NewFromConfig(sdkConfig)
	fmt.Println("Let's list the user pools for your account.")
	var pools []types.UserPoolDescriptionType
	paginator := cognitoidentityprovider.NewListUserPoolsPaginator(
		cognitoClient, &cognitoidentityprovider.ListUserPoolsInput{MaxResults: aws.Int32(10)})
	for paginator.HasMorePages() {
		output, err := paginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get user pools. Here's why: %v\n", err)
		} else {
			pools = append(pools, output.UserPools...)
		}
	}
	if len(pools) == 0 {
		fmt.Println("You don't have any user pools!")
	} else {
		for _, pool := range pools {
			fmt.Printf("\t%v: %v\n", *pool.Name, *pool.Id)
		}
	}
}
```
+  API の詳細については*AWS SDK for Go API リファレンス*の「[ListUserPools](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ListUserPools)」を参照してください。

### `SignUp`
<a name="cognito-identity-provider_SignUp_go_2_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// SignUp signs up a user with Amazon Cognito.
func (actor CognitoActions) SignUp(ctx context.Context, clientId string, userName string, password string, userEmail string) (bool, error) {
	confirmed := false
	output, err := actor.CognitoClient.SignUp(ctx, &cognitoidentityprovider.SignUpInput{
		ClientId: aws.String(clientId),
		Password: aws.String(password),
		Username: aws.String(userName),
		UserAttributes: []types.AttributeType{
			{Name: aws.String("email"), Value: aws.String(userEmail)},
		},
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err)
		}
	} else {
		confirmed = output.UserConfirmed
	}
	return confirmed, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[SignUp](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.SignUp)」を参照してください。

### `UpdateUserPool`
<a name="cognito-identity-provider_UpdateUserPool_go_2_topic"></a>

次のコード例は、`UpdateUserPool` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/cognito#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// Trigger and TriggerInfo define typed data for updating an Amazon Cognito trigger.
type Trigger int

const (
	PreSignUp Trigger = iota
	UserMigration
	PostAuthentication
)

type TriggerInfo struct {
	Trigger    Trigger
	HandlerArn *string
}

// UpdateTriggers adds or removes Lambda triggers for a user pool. When a trigger is specified with a `nil` value,
// it is removed from the user pool.
func (actor CognitoActions) UpdateTriggers(ctx context.Context, userPoolId string, triggers ...TriggerInfo) error {
	output, err := actor.CognitoClient.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{
		UserPoolId: aws.String(userPoolId),
	})
	if err != nil {
		log.Printf("Couldn't get info about user pool %v. Here's why: %v\n", userPoolId, err)
		return err
	}
	lambdaConfig := output.UserPool.LambdaConfig
	for _, trigger := range triggers {
		switch trigger.Trigger {
		case PreSignUp:
			lambdaConfig.PreSignUp = trigger.HandlerArn
		case UserMigration:
			lambdaConfig.UserMigration = trigger.HandlerArn
		case PostAuthentication:
			lambdaConfig.PostAuthentication = trigger.HandlerArn
		}
	}
	_, err = actor.CognitoClient.UpdateUserPool(ctx, &cognitoidentityprovider.UpdateUserPoolInput{
		UserPoolId:   aws.String(userPoolId),
		LambdaConfig: lambdaConfig,
	})
	if err != nil {
		log.Printf("Couldn't update user pool %v. Here's why: %v\n", userPoolId, err)
	}
	return err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[UpdateUserPool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.UpdateUserPool)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Lambda 関数を使用して登録済みのユーザーを自動的に確認する
<a name="cross_CognitoAutoConfirmUser_go_2_topic"></a>

次のコード例は、Lambda 関数を使用して登録済みの Amazon Cognito ユーザーを自動的に確認する方法を示しています。
+ `PreSignUp` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ Amazon Cognito でユーザーをサインアップする
+ Lambda 関数は DynamoDB テーブルをスキャンし、登録済みのユーザーを自動的に確認します。
+ 新しいユーザーとしてサインインし、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"errors"
	"log"
	"strings"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// AutoConfirm separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type AutoConfirm struct {
	helper       IScenarioHelper
	questioner   demotools.IQuestioner
	resources    Resources
	cognitoActor *actions.CognitoActions
}

// NewAutoConfirm constructs a new auto confirm runner.
func NewAutoConfirm(sdkConfig aws.Config, questioner demotools.IQuestioner, helper IScenarioHelper) AutoConfirm {
	scenario := AutoConfirm{
		helper:       helper,
		questioner:   questioner,
		resources:    Resources{},
		cognitoActor: &actions.CognitoActions{CognitoClient: cognitoidentityprovider.NewFromConfig(sdkConfig)},
	}
	scenario.resources.init(scenario.cognitoActor, questioner)
	return scenario
}

// AddPreSignUpTrigger adds a Lambda handler as an invocation target for the PreSignUp trigger.
func (runner *AutoConfirm) AddPreSignUpTrigger(ctx context.Context, userPoolId string, functionArn string) {
	log.Printf("Let's add a Lambda function to handle the PreSignUp trigger from Cognito.\n" +
		"This trigger happens when a user signs up, and lets your function take action before the main Cognito\n" +
		"sign up processing occurs.\n")
	err := runner.cognitoActor.UpdateTriggers(
		ctx, userPoolId,
		actions.TriggerInfo{Trigger: actions.PreSignUp, HandlerArn: aws.String(functionArn)})
	if err != nil {
		panic(err)
	}
	log.Printf("Lambda function %v added to user pool %v to handle the PreSignUp trigger.\n",
		functionArn, userPoolId)
}

// SignUpUser signs up a user from the known user table with a password you specify.
func (runner *AutoConfirm) SignUpUser(ctx context.Context, clientId string, usersTable string) (string, string) {
	log.Println("Let's sign up a user to your Cognito user pool. When the user's email matches an email in the\n" +
		"DynamoDB known users table, it is automatically verified and the user is confirmed.")

	knownUsers, err := runner.helper.GetKnownUsers(ctx, usersTable)
	if err != nil {
		panic(err)
	}
	userChoice := runner.questioner.AskChoice("Which user do you want to use?\n", knownUsers.UserNameList())
	user := knownUsers.Users[userChoice]

	var signedUp bool
	var userConfirmed bool
	password := runner.questioner.AskPassword("Enter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.\n"+
		"(the password will not display as you type):", 8)
	for !signedUp {
		log.Printf("Signing up user '%v' with email '%v' to Cognito.\n", user.UserName, user.UserEmail)
		userConfirmed, err = runner.cognitoActor.SignUp(ctx, clientId, user.UserName, password, user.UserEmail)
		if err != nil {
			var invalidPassword *types.InvalidPasswordException
			if errors.As(err, &invalidPassword) {
				password = runner.questioner.AskPassword("Enter another password:", 8)
			} else {
				panic(err)
			}
		} else {
			signedUp = true
		}
	}
	log.Printf("User %v signed up, confirmed = %v.\n", user.UserName, userConfirmed)

	log.Println(strings.Repeat("-", 88))

	return user.UserName, password
}

// SignInUser signs in a user.
func (runner *AutoConfirm) SignInUser(ctx context.Context, clientId string, userName string, password string) string {
	runner.questioner.Ask("Press Enter when you're ready to continue.")
	log.Printf("Let's sign in as %v...\n", userName)
	authResult, err := runner.cognitoActor.SignIn(ctx, clientId, userName, password)
	if err != nil {
		panic(err)
	}
	log.Printf("Successfully signed in. Your access token starts with: %v...\n", (*authResult.AccessToken)[:10])
	log.Println(strings.Repeat("-", 88))
	return *authResult.AccessToken
}

// Run runs the scenario.
func (runner *AutoConfirm) Run(ctx context.Context, stackName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			runner.resources.Cleanup(ctx)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome\n")

	log.Println(strings.Repeat("-", 88))

	stackOutputs, err := runner.helper.GetStackOutputs(ctx, stackName)
	if err != nil {
		panic(err)
	}
	runner.resources.userPoolId = stackOutputs["UserPoolId"]
	runner.helper.PopulateUserTable(ctx, stackOutputs["TableName"])

	runner.AddPreSignUpTrigger(ctx, stackOutputs["UserPoolId"], stackOutputs["AutoConfirmFunctionArn"])
	runner.resources.triggers = append(runner.resources.triggers, actions.PreSignUp)
	userName, password := runner.SignUpUser(ctx, stackOutputs["UserPoolClientId"], stackOutputs["TableName"])
	runner.helper.ListRecentLogEvents(ctx, stackOutputs["AutoConfirmFunction"])
	runner.resources.userAccessTokens = append(runner.resources.userAccessTokens,
		runner.SignInUser(ctx, stackOutputs["UserPoolClientId"], userName, password))

	runner.resources.Cleanup(ctx)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
Lambda 関数を使用して `PreSignUp` トリガーを処理します。  

```
import (
	"context"
	"log"
	"os"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	dynamodbtypes "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

const TABLE_NAME = "TABLE_NAME"

// UserInfo defines structured user data that can be marshalled to a DynamoDB format.
type UserInfo struct {
	UserName  string `dynamodbav:"UserName"`
	UserEmail string `dynamodbav:"UserEmail"`
}

// GetKey marshals the user email value to a DynamoDB key format.
func (user UserInfo) GetKey() map[string]dynamodbtypes.AttributeValue {
	userEmail, err := attributevalue.Marshal(user.UserEmail)
	if err != nil {
		panic(err)
	}
	return map[string]dynamodbtypes.AttributeValue{"UserEmail": userEmail}
}

type handler struct {
	dynamoClient *dynamodb.Client
}

// HandleRequest handles the PreSignUp event by looking up a user in an Amazon DynamoDB table and
// specifying whether they should be confirmed and verified.
func (h *handler) HandleRequest(ctx context.Context, event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) {
	log.Printf("Received presignup from %v for user '%v'", event.TriggerSource, event.UserName)
	if event.TriggerSource != "PreSignUp_SignUp" {
		// Other trigger sources, such as PreSignUp_AdminInitiateAuth, ignore the response from this handler.
		return event, nil
	}
	tableName := os.Getenv(TABLE_NAME)
	user := UserInfo{
		UserEmail: event.Request.UserAttributes["email"],
	}
	log.Printf("Looking up email %v in table %v.\n", user.UserEmail, tableName)
	output, err := h.dynamoClient.GetItem(ctx, &dynamodb.GetItemInput{
		Key:       user.GetKey(),
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Error looking up email %v.\n", user.UserEmail)
		return event, err
	}
	if output.Item == nil {
		log.Printf("Email %v not found. Email verification is required.\n", user.UserEmail)
		return event, err
	}

	err = attributevalue.UnmarshalMap(output.Item, &user)
	if err != nil {
		log.Printf("Couldn't unmarshal DynamoDB item. Here's why: %v\n", err)
		return event, err
	}

	if user.UserName != event.UserName {
		log.Printf("UserEmail %v found, but stored UserName '%v' does not match supplied UserName '%v'. Verification is required.\n",
			user.UserEmail, user.UserName, event.UserName)
	} else {
		log.Printf("UserEmail %v found with matching UserName %v. User is confirmed.\n", user.UserEmail, user.UserName)
		event.Response.AutoConfirmUser = true
		event.Response.AutoVerifyEmail = true
	}

	return event, err
}

func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Panicln(err)
	}
	h := handler{
		dynamoClient: dynamodb.NewFromConfig(sdkConfig),
	}
	lambda.Start(h.HandleRequest)
}
```
一般的なタスクを実行する構造体を作成します。  

```
import (
	"context"
	"log"
	"strings"
	"time"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// IScenarioHelper defines common functions used by the workflows in this example.
type IScenarioHelper interface {
	Pause(secs int)
	GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error)
	PopulateUserTable(ctx context.Context, tableName string)
	GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error)
	AddKnownUser(ctx context.Context, tableName string, user actions.User)
	ListRecentLogEvents(ctx context.Context, functionName string)
}

// ScenarioHelper contains AWS wrapper structs used by the workflows in this example.
type ScenarioHelper struct {
	questioner  demotools.IQuestioner
	dynamoActor *actions.DynamoActions
	cfnActor    *actions.CloudFormationActions
	cwlActor    *actions.CloudWatchLogsActions
	isTestRun   bool
}

// NewScenarioHelper constructs a new scenario helper.
func NewScenarioHelper(sdkConfig aws.Config, questioner demotools.IQuestioner) ScenarioHelper {
	scenario := ScenarioHelper{
		questioner:  questioner,
		dynamoActor: &actions.DynamoActions{DynamoClient: dynamodb.NewFromConfig(sdkConfig)},
		cfnActor:    &actions.CloudFormationActions{CfnClient: cloudformation.NewFromConfig(sdkConfig)},
		cwlActor:    &actions.CloudWatchLogsActions{CwlClient: cloudwatchlogs.NewFromConfig(sdkConfig)},
	}
	return scenario
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	if !helper.isTestRun {
		time.Sleep(time.Duration(secs) * time.Second)
	}
}

// GetStackOutputs gets the outputs from the specified CloudFormation stack in a structured format.
func (helper ScenarioHelper) GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error) {
	return helper.cfnActor.GetOutputs(ctx, stackName), nil
}

// PopulateUserTable fills the known user table with example data.
func (helper ScenarioHelper) PopulateUserTable(ctx context.Context, tableName string) {
	log.Printf("First, let's add some users to the DynamoDB %v table we'll use for this example.\n", tableName)
	err := helper.dynamoActor.PopulateTable(ctx, tableName)
	if err != nil {
		panic(err)
	}
}

// GetKnownUsers gets the users from the known users table in a structured format.
func (helper ScenarioHelper) GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error) {
	knownUsers, err := helper.dynamoActor.Scan(ctx, tableName)
	if err != nil {
		log.Printf("Couldn't get known users from table %v. Here's why: %v\n", tableName, err)
	}
	return knownUsers, err
}

// AddKnownUser adds a user to the known users table.
func (helper ScenarioHelper) AddKnownUser(ctx context.Context, tableName string, user actions.User) {
	log.Printf("Adding user '%v' with email '%v' to the DynamoDB known users table...\n",
		user.UserName, user.UserEmail)
	err := helper.dynamoActor.AddUser(ctx, tableName, user)
	if err != nil {
		panic(err)
	}
}

// ListRecentLogEvents gets the most recent log stream and events for the specified Lambda function and displays them.
func (helper ScenarioHelper) ListRecentLogEvents(ctx context.Context, functionName string) {
	log.Println("Waiting a few seconds to let Lambda write to CloudWatch Logs...")
	helper.Pause(10)
	log.Println("Okay, let's check the logs to find what's happened recently with your Lambda function.")
	logStream, err := helper.cwlActor.GetLatestLogStream(ctx, functionName)
	if err != nil {
		panic(err)
	}
	log.Printf("Getting some recent events from log stream %v\n", *logStream.LogStreamName)
	events, err := helper.cwlActor.GetLogEvents(ctx, functionName, *logStream.LogStreamName, 10)
	if err != nil {
		panic(err)
	}
	for _, event := range events {
		log.Printf("\t%v", *event.Message)
	}
	log.Println(strings.Repeat("-", 88))
}
```
Amazon Cognito アクションをラップする構造体を作成します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// Trigger and TriggerInfo define typed data for updating an Amazon Cognito trigger.
type Trigger int

const (
	PreSignUp Trigger = iota
	UserMigration
	PostAuthentication
)

type TriggerInfo struct {
	Trigger    Trigger
	HandlerArn *string
}

// UpdateTriggers adds or removes Lambda triggers for a user pool. When a trigger is specified with a `nil` value,
// it is removed from the user pool.
func (actor CognitoActions) UpdateTriggers(ctx context.Context, userPoolId string, triggers ...TriggerInfo) error {
	output, err := actor.CognitoClient.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{
		UserPoolId: aws.String(userPoolId),
	})
	if err != nil {
		log.Printf("Couldn't get info about user pool %v. Here's why: %v\n", userPoolId, err)
		return err
	}
	lambdaConfig := output.UserPool.LambdaConfig
	for _, trigger := range triggers {
		switch trigger.Trigger {
		case PreSignUp:
			lambdaConfig.PreSignUp = trigger.HandlerArn
		case UserMigration:
			lambdaConfig.UserMigration = trigger.HandlerArn
		case PostAuthentication:
			lambdaConfig.PostAuthentication = trigger.HandlerArn
		}
	}
	_, err = actor.CognitoClient.UpdateUserPool(ctx, &cognitoidentityprovider.UpdateUserPoolInput{
		UserPoolId:   aws.String(userPoolId),
		LambdaConfig: lambdaConfig,
	})
	if err != nil {
		log.Printf("Couldn't update user pool %v. Here's why: %v\n", userPoolId, err)
	}
	return err
}



// SignUp signs up a user with Amazon Cognito.
func (actor CognitoActions) SignUp(ctx context.Context, clientId string, userName string, password string, userEmail string) (bool, error) {
	confirmed := false
	output, err := actor.CognitoClient.SignUp(ctx, &cognitoidentityprovider.SignUpInput{
		ClientId: aws.String(clientId),
		Password: aws.String(password),
		Username: aws.String(userName),
		UserAttributes: []types.AttributeType{
			{Name: aws.String("email"), Value: aws.String(userEmail)},
		},
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err)
		}
	} else {
		confirmed = output.UserConfirmed
	}
	return confirmed, err
}



// SignIn signs in a user to Amazon Cognito using a username and password authentication flow.
func (actor CognitoActions) SignIn(ctx context.Context, clientId string, userName string, password string) (*types.AuthenticationResultType, error) {
	var authResult *types.AuthenticationResultType
	output, err := actor.CognitoClient.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
		AuthFlow:       "USER_PASSWORD_AUTH",
		ClientId:       aws.String(clientId),
		AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password},
	})
	if err != nil {
		var resetRequired *types.PasswordResetRequiredException
		if errors.As(err, &resetRequired) {
			log.Println(*resetRequired.Message)
		} else {
			log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err)
		}
	} else {
		authResult = output.AuthenticationResult
	}
	return authResult, err
}



// ForgotPassword starts a password recovery flow for a user. This flow typically sends a confirmation code
// to the user's configured notification destination, such as email.
func (actor CognitoActions) ForgotPassword(ctx context.Context, clientId string, userName string) (*types.CodeDeliveryDetailsType, error) {
	output, err := actor.CognitoClient.ForgotPassword(ctx, &cognitoidentityprovider.ForgotPasswordInput{
		ClientId: aws.String(clientId),
		Username: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't start password reset for user '%v'. Here;s why: %v\n", userName, err)
	}
	return output.CodeDeliveryDetails, err
}



// ConfirmForgotPassword confirms a user with a confirmation code and a new password.
func (actor CognitoActions) ConfirmForgotPassword(ctx context.Context, clientId string, code string, userName string, password string) error {
	_, err := actor.CognitoClient.ConfirmForgotPassword(ctx, &cognitoidentityprovider.ConfirmForgotPasswordInput{
		ClientId:         aws.String(clientId),
		ConfirmationCode: aws.String(code),
		Password:         aws.String(password),
		Username:         aws.String(userName),
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't confirm user %v. Here's why: %v", userName, err)
		}
	}
	return err
}



// DeleteUser removes a user from the user pool.
func (actor CognitoActions) DeleteUser(ctx context.Context, userAccessToken string) error {
	_, err := actor.CognitoClient.DeleteUser(ctx, &cognitoidentityprovider.DeleteUserInput{
		AccessToken: aws.String(userAccessToken),
	})
	if err != nil {
		log.Printf("Couldn't delete user. Here's why: %v\n", err)
	}
	return err
}



// AdminCreateUser uses administrator credentials to add a user to a user pool. This method leaves the user
// in a state that requires they enter a new password next time they sign in.
func (actor CognitoActions) AdminCreateUser(ctx context.Context, userPoolId string, userName string, userEmail string) error {
	_, err := actor.CognitoClient.AdminCreateUser(ctx, &cognitoidentityprovider.AdminCreateUserInput{
		UserPoolId:     aws.String(userPoolId),
		Username:       aws.String(userName),
		MessageAction:  types.MessageActionTypeSuppress,
		UserAttributes: []types.AttributeType{{Name: aws.String("email"), Value: aws.String(userEmail)}},
	})
	if err != nil {
		var userExists *types.UsernameExistsException
		if errors.As(err, &userExists) {
			log.Printf("User %v already exists in the user pool.", userName)
			err = nil
		} else {
			log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
DynamoDB アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type DynamoActions struct {
	DynamoClient *dynamodb.Client
}

// User defines structured user data.
type User struct {
	UserName  string
	UserEmail string
	LastLogin *LoginInfo `dynamodbav:",omitempty"`
}

// LoginInfo defines structured custom login data.
type LoginInfo struct {
	UserPoolId string
	ClientId   string
	Time       string
}

// UserList defines a list of users.
type UserList struct {
	Users []User
}

// UserNameList returns the usernames contained in a UserList as a list of strings.
func (users *UserList) UserNameList() []string {
	names := make([]string, len(users.Users))
	for i := 0; i < len(users.Users); i++ {
		names[i] = users.Users[i].UserName
	}
	return names
}

// PopulateTable adds a set of test users to the table.
func (actor DynamoActions) PopulateTable(ctx context.Context, tableName string) error {
	var err error
	var item map[string]types.AttributeValue
	var writeReqs []types.WriteRequest
	for i := 1; i < 4; i++ {
		item, err = attributevalue.MarshalMap(User{UserName: fmt.Sprintf("test_user_%v", i), UserEmail: fmt.Sprintf("test_email_%v@example.com", i)})
		if err != nil {
			log.Printf("Couldn't marshall user into DynamoDB format. Here's why: %v\n", err)
			return err
		}
		writeReqs = append(writeReqs, types.WriteRequest{PutRequest: &types.PutRequest{Item: item}})
	}
	_, err = actor.DynamoClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
		RequestItems: map[string][]types.WriteRequest{tableName: writeReqs},
	})
	if err != nil {
		log.Printf("Couldn't populate table %v with users. Here's why: %v\n", tableName, err)
	}
	return err
}

// Scan scans the table for all items.
func (actor DynamoActions) Scan(ctx context.Context, tableName string) (UserList, error) {
	var userList UserList
	output, err := actor.DynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't scan table %v for items. Here's why: %v\n", tableName, err)
	} else {
		err = attributevalue.UnmarshalListOfMaps(output.Items, &userList.Users)
		if err != nil {
			log.Printf("Couldn't unmarshal items into users. Here's why: %v\n", err)
		}
	}
	return userList, err
}

// AddUser adds a user item to a table.
func (actor DynamoActions) AddUser(ctx context.Context, tableName string, user User) error {
	userItem, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshall user to item. Here's why: %v\n", err)
	}
	_, err = actor.DynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
		Item:      userItem,
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't put item in table %v. Here's why: %v", tableName, err)
	}
	return err
}
```
CloudWatch Logs アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
)

type CloudWatchLogsActions struct {
	CwlClient *cloudwatchlogs.Client
}

// GetLatestLogStream gets the most recent log stream for a Lambda function.
func (actor CloudWatchLogsActions) GetLatestLogStream(ctx context.Context, functionName string) (types.LogStream, error) {
	var logStream types.LogStream
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
		Descending:   aws.Bool(true),
		Limit:        aws.Int32(1),
		LogGroupName: aws.String(logGroupName),
		OrderBy:      types.OrderByLastEventTime,
	})
	if err != nil {
		log.Printf("Couldn't get log streams for log group %v. Here's why: %v\n", logGroupName, err)
	} else {
		logStream = output.LogStreams[0]
	}
	return logStream, err
}

// GetLogEvents gets the most recent eventCount events from the specified log stream.
func (actor CloudWatchLogsActions) GetLogEvents(ctx context.Context, functionName string, logStreamName string, eventCount int32) (
	[]types.OutputLogEvent, error) {
	var events []types.OutputLogEvent
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.GetLogEvents(ctx, &cloudwatchlogs.GetLogEventsInput{
		LogStreamName: aws.String(logStreamName),
		Limit:         aws.Int32(eventCount),
		LogGroupName:  aws.String(logGroupName),
	})
	if err != nil {
		log.Printf("Couldn't get log event for log stream %v. Here's why: %v\n", logStreamName, err)
	} else {
		events = output.Events
	}
	return events, err
}
```
 CloudFormation アクションをラップする構造体を作成します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"log"
	"user_pools_and_lambda_triggers/actions"

	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	userPoolId       string
	userAccessTokens []string
	triggers         []actions.Trigger

	cognitoActor *actions.CognitoActions
	questioner   demotools.IQuestioner
}

func (resources *Resources) init(cognitoActor *actions.CognitoActions, questioner demotools.IQuestioner) {
	resources.userAccessTokens = []string{}
	resources.triggers = []actions.Trigger{}
	resources.cognitoActor = cognitoActor
	resources.questioner = questioner
}

// Cleanup deletes all AWS resources created during an example.
func (resources *Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong during cleanup.\n%v\n", r)
			log.Println("Use the AWS Management Console to remove any remaining resources \n" +
				"that were created for this scenario.")
		}
	}()

	wantDelete := resources.questioner.AskBool("Do you want to remove all of the AWS resources that were created "+
		"during this demo (y/n)?", "y")
	if wantDelete {
		for _, accessToken := range resources.userAccessTokens {
			err := resources.cognitoActor.DeleteUser(ctx, accessToken)
			if err != nil {
				log.Println("Couldn't delete user during cleanup.")
				panic(err)
			}
			log.Println("Deleted user.")
		}
		triggerList := make([]actions.TriggerInfo, len(resources.triggers))
		for i := 0; i < len(resources.triggers); i++ {
			triggerList[i] = actions.TriggerInfo{Trigger: resources.triggers[i], HandlerArn: nil}
		}
		err := resources.cognitoActor.UpdateTriggers(ctx, resources.userPoolId, triggerList...)
		if err != nil {
			log.Println("Couldn't update Cognito triggers during cleanup.")
			panic(err)
		}
		log.Println("Removed Cognito triggers from user pool.")
	} else {
		log.Println("Be sure to remove resources when you're done with them to avoid unexpected charges!")
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.DeleteUser)
  + [InitiateAuth](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.InitiateAuth)
  + [SignUp](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.SignUp)
  + [UpdateUserPool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.UpdateUserPool)

### Lambda 関数を使用して登録済みのユーザーを自動的に移行する
<a name="cross_CognitoAutoMigrateUser_go_2_topic"></a>

次のコード例は、Lambda 関数を使用して登録済みの Amazon Cognito ユーザーを自動的に移行する方法を示しています。
+ `MigrateUser` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ ユーザープールにないユーザー名と E メールで Amazon Cognito にサインインします。
+ Lambda 関数は DynamoDB テーブルをスキャンし、登録済みのユーザーをユーザープールに自動的に移行します。
+ パスワードを忘れた場合のフローを実行して、移行したユーザーのパスワードをリセットします。
+ 新しいユーザーとしてサインインし、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"errors"
	"fmt"
	"log"
	"strings"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// MigrateUser separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type MigrateUser struct {
	helper       IScenarioHelper
	questioner   demotools.IQuestioner
	resources    Resources
	cognitoActor *actions.CognitoActions
}

// NewMigrateUser constructs a new migrate user runner.
func NewMigrateUser(sdkConfig aws.Config, questioner demotools.IQuestioner, helper IScenarioHelper) MigrateUser {
	scenario := MigrateUser{
		helper:       helper,
		questioner:   questioner,
		resources:    Resources{},
		cognitoActor: &actions.CognitoActions{CognitoClient: cognitoidentityprovider.NewFromConfig(sdkConfig)},
	}
	scenario.resources.init(scenario.cognitoActor, questioner)
	return scenario
}

// AddMigrateUserTrigger adds a Lambda handler as an invocation target for the MigrateUser trigger.
func (runner *MigrateUser) AddMigrateUserTrigger(ctx context.Context, userPoolId string, functionArn string) {
	log.Printf("Let's add a Lambda function to handle the MigrateUser trigger from Cognito.\n" +
		"This trigger happens when an unknown user signs in, and lets your function take action before Cognito\n" +
		"rejects the user.\n\n")
	err := runner.cognitoActor.UpdateTriggers(
		ctx, userPoolId,
		actions.TriggerInfo{Trigger: actions.UserMigration, HandlerArn: aws.String(functionArn)})
	if err != nil {
		panic(err)
	}
	log.Printf("Lambda function %v added to user pool %v to handle the MigrateUser trigger.\n",
		functionArn, userPoolId)

	log.Println(strings.Repeat("-", 88))
}

// SignInUser adds a new user to the known users table and signs that user in to Amazon Cognito.
func (runner *MigrateUser) SignInUser(ctx context.Context, usersTable string, clientId string) (bool, actions.User) {
	log.Println("Let's sign in a user to your Cognito user pool. When the username and email matches an entry in the\n" +
		"DynamoDB known users table, the email is automatically verified and the user is migrated to the Cognito user pool.")

	user := actions.User{}
	user.UserName = runner.questioner.Ask("\nEnter a username:")
	user.UserEmail = runner.questioner.Ask("\nEnter an email that you own. This email will be used to confirm user migration\n" +
		"during this example:")

	runner.helper.AddKnownUser(ctx, usersTable, user)

	var err error
	var resetRequired *types.PasswordResetRequiredException
	var authResult *types.AuthenticationResultType
	signedIn := false
	for !signedIn && resetRequired == nil {
		log.Printf("Signing in to Cognito as user '%v'. The expected result is a PasswordResetRequiredException.\n\n", user.UserName)
		authResult, err = runner.cognitoActor.SignIn(ctx, clientId, user.UserName, "_")
		if err != nil {
			if errors.As(err, &resetRequired) {
				log.Printf("\nUser '%v' is not in the Cognito user pool but was found in the DynamoDB known users table.\n"+
					"User migration is started and a password reset is required.", user.UserName)
			} else {
				panic(err)
			}
		} else {
			log.Printf("User '%v' successfully signed in. This is unexpected and probably means you have not\n"+
				"cleaned up a previous run of this scenario, so the user exist in the Cognito user pool.\n"+
				"You can continue this example and select to clean up resources, or manually remove\n"+
				"the user from your user pool and try again.", user.UserName)
			runner.resources.userAccessTokens = append(runner.resources.userAccessTokens, *authResult.AccessToken)
			signedIn = true
		}
	}

	log.Println(strings.Repeat("-", 88))
	return resetRequired != nil, user
}

// ResetPassword starts a password recovery flow.
func (runner *MigrateUser) ResetPassword(ctx context.Context, clientId string, user actions.User) {
	wantCode := runner.questioner.AskBool(fmt.Sprintf("In order to migrate the user to Cognito, you must be able to receive a confirmation\n"+
		"code by email at %v. Do you want to send a code (y/n)?", user.UserEmail), "y")
	if !wantCode {
		log.Println("To complete this example and successfully migrate a user to Cognito, you must enter an email\n" +
			"you own that can receive a confirmation code.")
		return
	}
	codeDelivery, err := runner.cognitoActor.ForgotPassword(ctx, clientId, user.UserName)
	if err != nil {
		panic(err)
	}
	log.Printf("\nA confirmation code has been sent to %v.", *codeDelivery.Destination)
	code := runner.questioner.Ask("Check your email and enter it here:")

	confirmed := false
	password := runner.questioner.AskPassword("\nEnter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.\n"+
		"(the password will not display as you type):", 8)
	for !confirmed {
		log.Printf("\nConfirming password reset for user '%v'.\n", user.UserName)
		err = runner.cognitoActor.ConfirmForgotPassword(ctx, clientId, code, user.UserName, password)
		if err != nil {
			var invalidPassword *types.InvalidPasswordException
			if errors.As(err, &invalidPassword) {
				password = runner.questioner.AskPassword("\nEnter another password:", 8)
			} else {
				panic(err)
			}
		} else {
			confirmed = true
		}
	}
	log.Printf("User '%v' successfully confirmed and migrated.\n", user.UserName)
	log.Println("Signing in with your username and password...")
	authResult, err := runner.cognitoActor.SignIn(ctx, clientId, user.UserName, password)
	if err != nil {
		panic(err)
	}
	log.Printf("Successfully signed in. Your access token starts with: %v...\n", (*authResult.AccessToken)[:10])
	runner.resources.userAccessTokens = append(runner.resources.userAccessTokens, *authResult.AccessToken)

	log.Println(strings.Repeat("-", 88))
}

// Run runs the scenario.
func (runner *MigrateUser) Run(ctx context.Context, stackName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			runner.resources.Cleanup(ctx)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome\n")

	log.Println(strings.Repeat("-", 88))

	stackOutputs, err := runner.helper.GetStackOutputs(ctx, stackName)
	if err != nil {
		panic(err)
	}
	runner.resources.userPoolId = stackOutputs["UserPoolId"]

	runner.AddMigrateUserTrigger(ctx, stackOutputs["UserPoolId"], stackOutputs["MigrateUserFunctionArn"])
	runner.resources.triggers = append(runner.resources.triggers, actions.UserMigration)
	resetNeeded, user := runner.SignInUser(ctx, stackOutputs["TableName"], stackOutputs["UserPoolClientId"])
	if resetNeeded {
		runner.helper.ListRecentLogEvents(ctx, stackOutputs["MigrateUserFunction"])
		runner.ResetPassword(ctx, stackOutputs["UserPoolClientId"], user)
	}

	runner.resources.Cleanup(ctx)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
Lambda 関数を使用して `MigrateUser` トリガーを処理します。  

```
import (
	"context"
	"log"
	"os"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
)

const TABLE_NAME = "TABLE_NAME"

// UserInfo defines structured user data that can be marshalled to a DynamoDB format.
type UserInfo struct {
	UserName  string `dynamodbav:"UserName"`
	UserEmail string `dynamodbav:"UserEmail"`
}

type handler struct {
	dynamoClient *dynamodb.Client
}

// HandleRequest handles the MigrateUser event by looking up a user in an Amazon DynamoDB table and
// specifying whether they should be migrated to the user pool.
func (h *handler) HandleRequest(ctx context.Context, event events.CognitoEventUserPoolsMigrateUser) (events.CognitoEventUserPoolsMigrateUser, error) {
	log.Printf("Received migrate trigger from %v for user '%v'", event.TriggerSource, event.UserName)
	if event.TriggerSource != "UserMigration_Authentication" {
		return event, nil
	}
	tableName := os.Getenv(TABLE_NAME)
	user := UserInfo{
		UserName: event.UserName,
	}
	log.Printf("Looking up user '%v' in table %v.\n", user.UserName, tableName)
	filterEx := expression.Name("UserName").Equal(expression.Value(user.UserName))
	expr, err := expression.NewBuilder().WithFilter(filterEx).Build()
	if err != nil {
		log.Printf("Error building expression to query for user '%v'.\n", user.UserName)
		return event, err
	}
	output, err := h.dynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName:                 aws.String(tableName),
		FilterExpression:          expr.Filter(),
		ExpressionAttributeNames:  expr.Names(),
		ExpressionAttributeValues: expr.Values(),
	})
	if err != nil {
		log.Printf("Error looking up user '%v'.\n", user.UserName)
		return event, err
	}
	if len(output.Items) == 0 {
		log.Printf("User '%v' not found, not migrating user.\n", user.UserName)
		return event, err
	}

	var users []UserInfo
	err = attributevalue.UnmarshalListOfMaps(output.Items, &users)
	if err != nil {
		log.Printf("Couldn't unmarshal DynamoDB items. Here's why: %v\n", err)
		return event, err
	}

	user = users[0]
	log.Printf("UserName '%v' found with email %v. User is migrated and must reset password.\n", user.UserName, user.UserEmail)
	event.CognitoEventUserPoolsMigrateUserResponse.UserAttributes = map[string]string{
		"email":          user.UserEmail,
		"email_verified": "true", // email_verified is required for the forgot password flow.
	}
	event.CognitoEventUserPoolsMigrateUserResponse.FinalUserStatus = "RESET_REQUIRED"
	event.CognitoEventUserPoolsMigrateUserResponse.MessageAction = "SUPPRESS"

	return event, err
}

func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Panicln(err)
	}
	h := handler{
		dynamoClient: dynamodb.NewFromConfig(sdkConfig),
	}
	lambda.Start(h.HandleRequest)
}
```
一般的なタスクを実行する構造体を作成します。  

```
import (
	"context"
	"log"
	"strings"
	"time"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// IScenarioHelper defines common functions used by the workflows in this example.
type IScenarioHelper interface {
	Pause(secs int)
	GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error)
	PopulateUserTable(ctx context.Context, tableName string)
	GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error)
	AddKnownUser(ctx context.Context, tableName string, user actions.User)
	ListRecentLogEvents(ctx context.Context, functionName string)
}

// ScenarioHelper contains AWS wrapper structs used by the workflows in this example.
type ScenarioHelper struct {
	questioner  demotools.IQuestioner
	dynamoActor *actions.DynamoActions
	cfnActor    *actions.CloudFormationActions
	cwlActor    *actions.CloudWatchLogsActions
	isTestRun   bool
}

// NewScenarioHelper constructs a new scenario helper.
func NewScenarioHelper(sdkConfig aws.Config, questioner demotools.IQuestioner) ScenarioHelper {
	scenario := ScenarioHelper{
		questioner:  questioner,
		dynamoActor: &actions.DynamoActions{DynamoClient: dynamodb.NewFromConfig(sdkConfig)},
		cfnActor:    &actions.CloudFormationActions{CfnClient: cloudformation.NewFromConfig(sdkConfig)},
		cwlActor:    &actions.CloudWatchLogsActions{CwlClient: cloudwatchlogs.NewFromConfig(sdkConfig)},
	}
	return scenario
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	if !helper.isTestRun {
		time.Sleep(time.Duration(secs) * time.Second)
	}
}

// GetStackOutputs gets the outputs from the specified CloudFormation stack in a structured format.
func (helper ScenarioHelper) GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error) {
	return helper.cfnActor.GetOutputs(ctx, stackName), nil
}

// PopulateUserTable fills the known user table with example data.
func (helper ScenarioHelper) PopulateUserTable(ctx context.Context, tableName string) {
	log.Printf("First, let's add some users to the DynamoDB %v table we'll use for this example.\n", tableName)
	err := helper.dynamoActor.PopulateTable(ctx, tableName)
	if err != nil {
		panic(err)
	}
}

// GetKnownUsers gets the users from the known users table in a structured format.
func (helper ScenarioHelper) GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error) {
	knownUsers, err := helper.dynamoActor.Scan(ctx, tableName)
	if err != nil {
		log.Printf("Couldn't get known users from table %v. Here's why: %v\n", tableName, err)
	}
	return knownUsers, err
}

// AddKnownUser adds a user to the known users table.
func (helper ScenarioHelper) AddKnownUser(ctx context.Context, tableName string, user actions.User) {
	log.Printf("Adding user '%v' with email '%v' to the DynamoDB known users table...\n",
		user.UserName, user.UserEmail)
	err := helper.dynamoActor.AddUser(ctx, tableName, user)
	if err != nil {
		panic(err)
	}
}

// ListRecentLogEvents gets the most recent log stream and events for the specified Lambda function and displays them.
func (helper ScenarioHelper) ListRecentLogEvents(ctx context.Context, functionName string) {
	log.Println("Waiting a few seconds to let Lambda write to CloudWatch Logs...")
	helper.Pause(10)
	log.Println("Okay, let's check the logs to find what's happened recently with your Lambda function.")
	logStream, err := helper.cwlActor.GetLatestLogStream(ctx, functionName)
	if err != nil {
		panic(err)
	}
	log.Printf("Getting some recent events from log stream %v\n", *logStream.LogStreamName)
	events, err := helper.cwlActor.GetLogEvents(ctx, functionName, *logStream.LogStreamName, 10)
	if err != nil {
		panic(err)
	}
	for _, event := range events {
		log.Printf("\t%v", *event.Message)
	}
	log.Println(strings.Repeat("-", 88))
}
```
Amazon Cognito アクションをラップする構造体を作成します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// Trigger and TriggerInfo define typed data for updating an Amazon Cognito trigger.
type Trigger int

const (
	PreSignUp Trigger = iota
	UserMigration
	PostAuthentication
)

type TriggerInfo struct {
	Trigger    Trigger
	HandlerArn *string
}

// UpdateTriggers adds or removes Lambda triggers for a user pool. When a trigger is specified with a `nil` value,
// it is removed from the user pool.
func (actor CognitoActions) UpdateTriggers(ctx context.Context, userPoolId string, triggers ...TriggerInfo) error {
	output, err := actor.CognitoClient.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{
		UserPoolId: aws.String(userPoolId),
	})
	if err != nil {
		log.Printf("Couldn't get info about user pool %v. Here's why: %v\n", userPoolId, err)
		return err
	}
	lambdaConfig := output.UserPool.LambdaConfig
	for _, trigger := range triggers {
		switch trigger.Trigger {
		case PreSignUp:
			lambdaConfig.PreSignUp = trigger.HandlerArn
		case UserMigration:
			lambdaConfig.UserMigration = trigger.HandlerArn
		case PostAuthentication:
			lambdaConfig.PostAuthentication = trigger.HandlerArn
		}
	}
	_, err = actor.CognitoClient.UpdateUserPool(ctx, &cognitoidentityprovider.UpdateUserPoolInput{
		UserPoolId:   aws.String(userPoolId),
		LambdaConfig: lambdaConfig,
	})
	if err != nil {
		log.Printf("Couldn't update user pool %v. Here's why: %v\n", userPoolId, err)
	}
	return err
}



// SignUp signs up a user with Amazon Cognito.
func (actor CognitoActions) SignUp(ctx context.Context, clientId string, userName string, password string, userEmail string) (bool, error) {
	confirmed := false
	output, err := actor.CognitoClient.SignUp(ctx, &cognitoidentityprovider.SignUpInput{
		ClientId: aws.String(clientId),
		Password: aws.String(password),
		Username: aws.String(userName),
		UserAttributes: []types.AttributeType{
			{Name: aws.String("email"), Value: aws.String(userEmail)},
		},
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err)
		}
	} else {
		confirmed = output.UserConfirmed
	}
	return confirmed, err
}



// SignIn signs in a user to Amazon Cognito using a username and password authentication flow.
func (actor CognitoActions) SignIn(ctx context.Context, clientId string, userName string, password string) (*types.AuthenticationResultType, error) {
	var authResult *types.AuthenticationResultType
	output, err := actor.CognitoClient.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
		AuthFlow:       "USER_PASSWORD_AUTH",
		ClientId:       aws.String(clientId),
		AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password},
	})
	if err != nil {
		var resetRequired *types.PasswordResetRequiredException
		if errors.As(err, &resetRequired) {
			log.Println(*resetRequired.Message)
		} else {
			log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err)
		}
	} else {
		authResult = output.AuthenticationResult
	}
	return authResult, err
}



// ForgotPassword starts a password recovery flow for a user. This flow typically sends a confirmation code
// to the user's configured notification destination, such as email.
func (actor CognitoActions) ForgotPassword(ctx context.Context, clientId string, userName string) (*types.CodeDeliveryDetailsType, error) {
	output, err := actor.CognitoClient.ForgotPassword(ctx, &cognitoidentityprovider.ForgotPasswordInput{
		ClientId: aws.String(clientId),
		Username: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't start password reset for user '%v'. Here;s why: %v\n", userName, err)
	}
	return output.CodeDeliveryDetails, err
}



// ConfirmForgotPassword confirms a user with a confirmation code and a new password.
func (actor CognitoActions) ConfirmForgotPassword(ctx context.Context, clientId string, code string, userName string, password string) error {
	_, err := actor.CognitoClient.ConfirmForgotPassword(ctx, &cognitoidentityprovider.ConfirmForgotPasswordInput{
		ClientId:         aws.String(clientId),
		ConfirmationCode: aws.String(code),
		Password:         aws.String(password),
		Username:         aws.String(userName),
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't confirm user %v. Here's why: %v", userName, err)
		}
	}
	return err
}



// DeleteUser removes a user from the user pool.
func (actor CognitoActions) DeleteUser(ctx context.Context, userAccessToken string) error {
	_, err := actor.CognitoClient.DeleteUser(ctx, &cognitoidentityprovider.DeleteUserInput{
		AccessToken: aws.String(userAccessToken),
	})
	if err != nil {
		log.Printf("Couldn't delete user. Here's why: %v\n", err)
	}
	return err
}



// AdminCreateUser uses administrator credentials to add a user to a user pool. This method leaves the user
// in a state that requires they enter a new password next time they sign in.
func (actor CognitoActions) AdminCreateUser(ctx context.Context, userPoolId string, userName string, userEmail string) error {
	_, err := actor.CognitoClient.AdminCreateUser(ctx, &cognitoidentityprovider.AdminCreateUserInput{
		UserPoolId:     aws.String(userPoolId),
		Username:       aws.String(userName),
		MessageAction:  types.MessageActionTypeSuppress,
		UserAttributes: []types.AttributeType{{Name: aws.String("email"), Value: aws.String(userEmail)}},
	})
	if err != nil {
		var userExists *types.UsernameExistsException
		if errors.As(err, &userExists) {
			log.Printf("User %v already exists in the user pool.", userName)
			err = nil
		} else {
			log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
DynamoDB アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type DynamoActions struct {
	DynamoClient *dynamodb.Client
}

// User defines structured user data.
type User struct {
	UserName  string
	UserEmail string
	LastLogin *LoginInfo `dynamodbav:",omitempty"`
}

// LoginInfo defines structured custom login data.
type LoginInfo struct {
	UserPoolId string
	ClientId   string
	Time       string
}

// UserList defines a list of users.
type UserList struct {
	Users []User
}

// UserNameList returns the usernames contained in a UserList as a list of strings.
func (users *UserList) UserNameList() []string {
	names := make([]string, len(users.Users))
	for i := 0; i < len(users.Users); i++ {
		names[i] = users.Users[i].UserName
	}
	return names
}

// PopulateTable adds a set of test users to the table.
func (actor DynamoActions) PopulateTable(ctx context.Context, tableName string) error {
	var err error
	var item map[string]types.AttributeValue
	var writeReqs []types.WriteRequest
	for i := 1; i < 4; i++ {
		item, err = attributevalue.MarshalMap(User{UserName: fmt.Sprintf("test_user_%v", i), UserEmail: fmt.Sprintf("test_email_%v@example.com", i)})
		if err != nil {
			log.Printf("Couldn't marshall user into DynamoDB format. Here's why: %v\n", err)
			return err
		}
		writeReqs = append(writeReqs, types.WriteRequest{PutRequest: &types.PutRequest{Item: item}})
	}
	_, err = actor.DynamoClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
		RequestItems: map[string][]types.WriteRequest{tableName: writeReqs},
	})
	if err != nil {
		log.Printf("Couldn't populate table %v with users. Here's why: %v\n", tableName, err)
	}
	return err
}

// Scan scans the table for all items.
func (actor DynamoActions) Scan(ctx context.Context, tableName string) (UserList, error) {
	var userList UserList
	output, err := actor.DynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't scan table %v for items. Here's why: %v\n", tableName, err)
	} else {
		err = attributevalue.UnmarshalListOfMaps(output.Items, &userList.Users)
		if err != nil {
			log.Printf("Couldn't unmarshal items into users. Here's why: %v\n", err)
		}
	}
	return userList, err
}

// AddUser adds a user item to a table.
func (actor DynamoActions) AddUser(ctx context.Context, tableName string, user User) error {
	userItem, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshall user to item. Here's why: %v\n", err)
	}
	_, err = actor.DynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
		Item:      userItem,
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't put item in table %v. Here's why: %v", tableName, err)
	}
	return err
}
```
CloudWatch Logs アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
)

type CloudWatchLogsActions struct {
	CwlClient *cloudwatchlogs.Client
}

// GetLatestLogStream gets the most recent log stream for a Lambda function.
func (actor CloudWatchLogsActions) GetLatestLogStream(ctx context.Context, functionName string) (types.LogStream, error) {
	var logStream types.LogStream
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
		Descending:   aws.Bool(true),
		Limit:        aws.Int32(1),
		LogGroupName: aws.String(logGroupName),
		OrderBy:      types.OrderByLastEventTime,
	})
	if err != nil {
		log.Printf("Couldn't get log streams for log group %v. Here's why: %v\n", logGroupName, err)
	} else {
		logStream = output.LogStreams[0]
	}
	return logStream, err
}

// GetLogEvents gets the most recent eventCount events from the specified log stream.
func (actor CloudWatchLogsActions) GetLogEvents(ctx context.Context, functionName string, logStreamName string, eventCount int32) (
	[]types.OutputLogEvent, error) {
	var events []types.OutputLogEvent
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.GetLogEvents(ctx, &cloudwatchlogs.GetLogEventsInput{
		LogStreamName: aws.String(logStreamName),
		Limit:         aws.Int32(eventCount),
		LogGroupName:  aws.String(logGroupName),
	})
	if err != nil {
		log.Printf("Couldn't get log event for log stream %v. Here's why: %v\n", logStreamName, err)
	} else {
		events = output.Events
	}
	return events, err
}
```
 CloudFormation アクションをラップする構造体を作成します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"log"
	"user_pools_and_lambda_triggers/actions"

	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	userPoolId       string
	userAccessTokens []string
	triggers         []actions.Trigger

	cognitoActor *actions.CognitoActions
	questioner   demotools.IQuestioner
}

func (resources *Resources) init(cognitoActor *actions.CognitoActions, questioner demotools.IQuestioner) {
	resources.userAccessTokens = []string{}
	resources.triggers = []actions.Trigger{}
	resources.cognitoActor = cognitoActor
	resources.questioner = questioner
}

// Cleanup deletes all AWS resources created during an example.
func (resources *Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong during cleanup.\n%v\n", r)
			log.Println("Use the AWS Management Console to remove any remaining resources \n" +
				"that were created for this scenario.")
		}
	}()

	wantDelete := resources.questioner.AskBool("Do you want to remove all of the AWS resources that were created "+
		"during this demo (y/n)?", "y")
	if wantDelete {
		for _, accessToken := range resources.userAccessTokens {
			err := resources.cognitoActor.DeleteUser(ctx, accessToken)
			if err != nil {
				log.Println("Couldn't delete user during cleanup.")
				panic(err)
			}
			log.Println("Deleted user.")
		}
		triggerList := make([]actions.TriggerInfo, len(resources.triggers))
		for i := 0; i < len(resources.triggers); i++ {
			triggerList[i] = actions.TriggerInfo{Trigger: resources.triggers[i], HandlerArn: nil}
		}
		err := resources.cognitoActor.UpdateTriggers(ctx, resources.userPoolId, triggerList...)
		if err != nil {
			log.Println("Couldn't update Cognito triggers during cleanup.")
			panic(err)
		}
		log.Println("Removed Cognito triggers from user pool.")
	} else {
		log.Println("Be sure to remove resources when you're done with them to avoid unexpected charges!")
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [ConfirmForgotPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ConfirmForgotPassword)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.DeleteUser)
  + [ForgotPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ForgotPassword)
  + [InitiateAuth](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.InitiateAuth)
  + [SignUp](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.SignUp)
  + [UpdateUserPool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.UpdateUserPool)

### Amazon Cognito ユーザー認証後に Lambda 関数を使用してカスタムアクティビティデータを書き込む
<a name="cross_CognitoCustomActivityLog_go_2_topic"></a>

次のコード例は、Amazon Cognito ユーザー認証後に Lambda 関数を使用してカスタムアクティビティデータを書き込む方法を示しています。
+ 管理者関数を使用して、ユーザーをユーザープールに追加します。
+ `PostAuthentication` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ 新しいユーザーを Amazon Cognito にサインインします。
+ Lambda 関数は、カスタム情報を CloudWatch Logs と DynamoDB テーブルに書き込みます。
+ DynamoDB テーブルからカスタムデータを取得して表示し、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"errors"
	"log"
	"strings"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// ActivityLog separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type ActivityLog struct {
	helper       IScenarioHelper
	questioner   demotools.IQuestioner
	resources    Resources
	cognitoActor *actions.CognitoActions
}

// NewActivityLog constructs a new activity log runner.
func NewActivityLog(sdkConfig aws.Config, questioner demotools.IQuestioner, helper IScenarioHelper) ActivityLog {
	scenario := ActivityLog{
		helper:       helper,
		questioner:   questioner,
		resources:    Resources{},
		cognitoActor: &actions.CognitoActions{CognitoClient: cognitoidentityprovider.NewFromConfig(sdkConfig)},
	}
	scenario.resources.init(scenario.cognitoActor, questioner)
	return scenario
}

// AddUserToPool selects a user from the known users table and uses administrator credentials to add the user to the user pool.
func (runner *ActivityLog) AddUserToPool(ctx context.Context, userPoolId string, tableName string) (string, string) {
	log.Println("To facilitate this example, let's add a user to the user pool using administrator privileges.")
	users, err := runner.helper.GetKnownUsers(ctx, tableName)
	if err != nil {
		panic(err)
	}
	user := users.Users[0]
	log.Printf("Adding known user %v to the user pool.\n", user.UserName)
	err = runner.cognitoActor.AdminCreateUser(ctx, userPoolId, user.UserName, user.UserEmail)
	if err != nil {
		panic(err)
	}
	pwSet := false
	password := runner.questioner.AskPassword("\nEnter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.\n"+
		"(the password will not display as you type):", 8)
	for !pwSet {
		log.Printf("\nSetting password for user '%v'.\n", user.UserName)
		err = runner.cognitoActor.AdminSetUserPassword(ctx, userPoolId, user.UserName, password)
		if err != nil {
			var invalidPassword *types.InvalidPasswordException
			if errors.As(err, &invalidPassword) {
				password = runner.questioner.AskPassword("\nEnter another password:", 8)
			} else {
				panic(err)
			}
		} else {
			pwSet = true
		}
	}

	log.Println(strings.Repeat("-", 88))

	return user.UserName, password
}

// AddActivityLogTrigger adds a Lambda handler as an invocation target for the PostAuthentication trigger.
func (runner *ActivityLog) AddActivityLogTrigger(ctx context.Context, userPoolId string, activityLogArn string) {
	log.Println("Let's add a Lambda function to handle the PostAuthentication trigger from Cognito.\n" +
		"This trigger happens after a user is authenticated, and lets your function take action, such as logging\n" +
		"the outcome.")
	err := runner.cognitoActor.UpdateTriggers(
		ctx, userPoolId,
		actions.TriggerInfo{Trigger: actions.PostAuthentication, HandlerArn: aws.String(activityLogArn)})
	if err != nil {
		panic(err)
	}
	runner.resources.triggers = append(runner.resources.triggers, actions.PostAuthentication)
	log.Printf("Lambda function %v added to user pool %v to handle PostAuthentication Cognito trigger.\n",
		activityLogArn, userPoolId)

	log.Println(strings.Repeat("-", 88))
}

// SignInUser signs in as the specified user.
func (runner *ActivityLog) SignInUser(ctx context.Context, clientId string, userName string, password string) {
	log.Printf("Now we'll sign in user %v and check the results in the logs and the DynamoDB table.", userName)
	runner.questioner.Ask("Press Enter when you're ready.")
	authResult, err := runner.cognitoActor.SignIn(ctx, clientId, userName, password)
	if err != nil {
		panic(err)
	}
	log.Println("Sign in successful.",
		"The PostAuthentication Lambda handler writes custom information to CloudWatch Logs.")

	runner.resources.userAccessTokens = append(runner.resources.userAccessTokens, *authResult.AccessToken)
}

// GetKnownUserLastLogin gets the login info for a user from the Amazon DynamoDB table and displays it.
func (runner *ActivityLog) GetKnownUserLastLogin(ctx context.Context, tableName string, userName string) {
	log.Println("The PostAuthentication handler also writes login data to the DynamoDB table.")
	runner.questioner.Ask("Press Enter when you're ready to continue.")
	users, err := runner.helper.GetKnownUsers(ctx, tableName)
	if err != nil {
		panic(err)
	}
	for _, user := range users.Users {
		if user.UserName == userName {
			log.Println("The last login info for the user in the known users table is:")
			log.Printf("\t%+v", *user.LastLogin)
		}
	}
	log.Println(strings.Repeat("-", 88))
}

// Run runs the scenario.
func (runner *ActivityLog) Run(ctx context.Context, stackName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			runner.resources.Cleanup(ctx)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome\n")

	log.Println(strings.Repeat("-", 88))

	stackOutputs, err := runner.helper.GetStackOutputs(ctx, stackName)
	if err != nil {
		panic(err)
	}
	runner.resources.userPoolId = stackOutputs["UserPoolId"]
	runner.helper.PopulateUserTable(ctx, stackOutputs["TableName"])
	userName, password := runner.AddUserToPool(ctx, stackOutputs["UserPoolId"], stackOutputs["TableName"])

	runner.AddActivityLogTrigger(ctx, stackOutputs["UserPoolId"], stackOutputs["ActivityLogFunctionArn"])
	runner.SignInUser(ctx, stackOutputs["UserPoolClientId"], userName, password)
	runner.helper.ListRecentLogEvents(ctx, stackOutputs["ActivityLogFunction"])
	runner.GetKnownUserLastLogin(ctx, stackOutputs["TableName"], userName)

	runner.resources.Cleanup(ctx)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
Lambda 関数を使用して `PostAuthentication` トリガーを処理します。  

```
import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	dynamodbtypes "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

const TABLE_NAME = "TABLE_NAME"

// LoginInfo defines structured login data that can be marshalled to a DynamoDB format.
type LoginInfo struct {
	UserPoolId string `dynamodbav:"UserPoolId"`
	ClientId   string `dynamodbav:"ClientId"`
	Time       string `dynamodbav:"Time"`
}

// UserInfo defines structured user data that can be marshalled to a DynamoDB format.
type UserInfo struct {
	UserName  string    `dynamodbav:"UserName"`
	UserEmail string    `dynamodbav:"UserEmail"`
	LastLogin LoginInfo `dynamodbav:"LastLogin"`
}

// GetKey marshals the user email value to a DynamoDB key format.
func (user UserInfo) GetKey() map[string]dynamodbtypes.AttributeValue {
	userEmail, err := attributevalue.Marshal(user.UserEmail)
	if err != nil {
		panic(err)
	}
	return map[string]dynamodbtypes.AttributeValue{"UserEmail": userEmail}
}

type handler struct {
	dynamoClient *dynamodb.Client
}

// HandleRequest handles the PostAuthentication event by writing custom data to the logs and
// to an Amazon DynamoDB table.
func (h *handler) HandleRequest(ctx context.Context, event events.CognitoEventUserPoolsPostAuthentication) (events.CognitoEventUserPoolsPostAuthentication, error) {
	log.Printf("Received post authentication trigger from %v for user '%v'", event.TriggerSource, event.UserName)
	tableName := os.Getenv(TABLE_NAME)
	user := UserInfo{
		UserName:  event.UserName,
		UserEmail: event.Request.UserAttributes["email"],
		LastLogin: LoginInfo{
			UserPoolId: event.UserPoolID,
			ClientId:   event.CallerContext.ClientID,
			Time:       time.Now().Format(time.UnixDate),
		},
	}
	// Write to CloudWatch Logs.
	fmt.Printf("%#v", user)

	// Also write to an external system. This examples uses DynamoDB to demonstrate.
	userMap, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshal to DynamoDB map. Here's why: %v\n", err)
	} else if len(userMap) == 0 {
		log.Printf("User info marshaled to an empty map.")
	} else {
		_, err := h.dynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
			Item:      userMap,
			TableName: aws.String(tableName),
		})
		if err != nil {
			log.Printf("Couldn't write to DynamoDB. Here's why: %v\n", err)
		} else {
			log.Printf("Wrote user info to DynamoDB table %v.\n", tableName)
		}
	}

	return event, nil
}

func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Panicln(err)
	}
	h := handler{
		dynamoClient: dynamodb.NewFromConfig(sdkConfig),
	}
	lambda.Start(h.HandleRequest)
}
```
一般的なタスクを実行する構造体を作成します。  

```
import (
	"context"
	"log"
	"strings"
	"time"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// IScenarioHelper defines common functions used by the workflows in this example.
type IScenarioHelper interface {
	Pause(secs int)
	GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error)
	PopulateUserTable(ctx context.Context, tableName string)
	GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error)
	AddKnownUser(ctx context.Context, tableName string, user actions.User)
	ListRecentLogEvents(ctx context.Context, functionName string)
}

// ScenarioHelper contains AWS wrapper structs used by the workflows in this example.
type ScenarioHelper struct {
	questioner  demotools.IQuestioner
	dynamoActor *actions.DynamoActions
	cfnActor    *actions.CloudFormationActions
	cwlActor    *actions.CloudWatchLogsActions
	isTestRun   bool
}

// NewScenarioHelper constructs a new scenario helper.
func NewScenarioHelper(sdkConfig aws.Config, questioner demotools.IQuestioner) ScenarioHelper {
	scenario := ScenarioHelper{
		questioner:  questioner,
		dynamoActor: &actions.DynamoActions{DynamoClient: dynamodb.NewFromConfig(sdkConfig)},
		cfnActor:    &actions.CloudFormationActions{CfnClient: cloudformation.NewFromConfig(sdkConfig)},
		cwlActor:    &actions.CloudWatchLogsActions{CwlClient: cloudwatchlogs.NewFromConfig(sdkConfig)},
	}
	return scenario
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	if !helper.isTestRun {
		time.Sleep(time.Duration(secs) * time.Second)
	}
}

// GetStackOutputs gets the outputs from the specified CloudFormation stack in a structured format.
func (helper ScenarioHelper) GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error) {
	return helper.cfnActor.GetOutputs(ctx, stackName), nil
}

// PopulateUserTable fills the known user table with example data.
func (helper ScenarioHelper) PopulateUserTable(ctx context.Context, tableName string) {
	log.Printf("First, let's add some users to the DynamoDB %v table we'll use for this example.\n", tableName)
	err := helper.dynamoActor.PopulateTable(ctx, tableName)
	if err != nil {
		panic(err)
	}
}

// GetKnownUsers gets the users from the known users table in a structured format.
func (helper ScenarioHelper) GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error) {
	knownUsers, err := helper.dynamoActor.Scan(ctx, tableName)
	if err != nil {
		log.Printf("Couldn't get known users from table %v. Here's why: %v\n", tableName, err)
	}
	return knownUsers, err
}

// AddKnownUser adds a user to the known users table.
func (helper ScenarioHelper) AddKnownUser(ctx context.Context, tableName string, user actions.User) {
	log.Printf("Adding user '%v' with email '%v' to the DynamoDB known users table...\n",
		user.UserName, user.UserEmail)
	err := helper.dynamoActor.AddUser(ctx, tableName, user)
	if err != nil {
		panic(err)
	}
}

// ListRecentLogEvents gets the most recent log stream and events for the specified Lambda function and displays them.
func (helper ScenarioHelper) ListRecentLogEvents(ctx context.Context, functionName string) {
	log.Println("Waiting a few seconds to let Lambda write to CloudWatch Logs...")
	helper.Pause(10)
	log.Println("Okay, let's check the logs to find what's happened recently with your Lambda function.")
	logStream, err := helper.cwlActor.GetLatestLogStream(ctx, functionName)
	if err != nil {
		panic(err)
	}
	log.Printf("Getting some recent events from log stream %v\n", *logStream.LogStreamName)
	events, err := helper.cwlActor.GetLogEvents(ctx, functionName, *logStream.LogStreamName, 10)
	if err != nil {
		panic(err)
	}
	for _, event := range events {
		log.Printf("\t%v", *event.Message)
	}
	log.Println(strings.Repeat("-", 88))
}
```
Amazon Cognito アクションをラップする構造体を作成します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// Trigger and TriggerInfo define typed data for updating an Amazon Cognito trigger.
type Trigger int

const (
	PreSignUp Trigger = iota
	UserMigration
	PostAuthentication
)

type TriggerInfo struct {
	Trigger    Trigger
	HandlerArn *string
}

// UpdateTriggers adds or removes Lambda triggers for a user pool. When a trigger is specified with a `nil` value,
// it is removed from the user pool.
func (actor CognitoActions) UpdateTriggers(ctx context.Context, userPoolId string, triggers ...TriggerInfo) error {
	output, err := actor.CognitoClient.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{
		UserPoolId: aws.String(userPoolId),
	})
	if err != nil {
		log.Printf("Couldn't get info about user pool %v. Here's why: %v\n", userPoolId, err)
		return err
	}
	lambdaConfig := output.UserPool.LambdaConfig
	for _, trigger := range triggers {
		switch trigger.Trigger {
		case PreSignUp:
			lambdaConfig.PreSignUp = trigger.HandlerArn
		case UserMigration:
			lambdaConfig.UserMigration = trigger.HandlerArn
		case PostAuthentication:
			lambdaConfig.PostAuthentication = trigger.HandlerArn
		}
	}
	_, err = actor.CognitoClient.UpdateUserPool(ctx, &cognitoidentityprovider.UpdateUserPoolInput{
		UserPoolId:   aws.String(userPoolId),
		LambdaConfig: lambdaConfig,
	})
	if err != nil {
		log.Printf("Couldn't update user pool %v. Here's why: %v\n", userPoolId, err)
	}
	return err
}



// SignUp signs up a user with Amazon Cognito.
func (actor CognitoActions) SignUp(ctx context.Context, clientId string, userName string, password string, userEmail string) (bool, error) {
	confirmed := false
	output, err := actor.CognitoClient.SignUp(ctx, &cognitoidentityprovider.SignUpInput{
		ClientId: aws.String(clientId),
		Password: aws.String(password),
		Username: aws.String(userName),
		UserAttributes: []types.AttributeType{
			{Name: aws.String("email"), Value: aws.String(userEmail)},
		},
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err)
		}
	} else {
		confirmed = output.UserConfirmed
	}
	return confirmed, err
}



// SignIn signs in a user to Amazon Cognito using a username and password authentication flow.
func (actor CognitoActions) SignIn(ctx context.Context, clientId string, userName string, password string) (*types.AuthenticationResultType, error) {
	var authResult *types.AuthenticationResultType
	output, err := actor.CognitoClient.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
		AuthFlow:       "USER_PASSWORD_AUTH",
		ClientId:       aws.String(clientId),
		AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password},
	})
	if err != nil {
		var resetRequired *types.PasswordResetRequiredException
		if errors.As(err, &resetRequired) {
			log.Println(*resetRequired.Message)
		} else {
			log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err)
		}
	} else {
		authResult = output.AuthenticationResult
	}
	return authResult, err
}



// ForgotPassword starts a password recovery flow for a user. This flow typically sends a confirmation code
// to the user's configured notification destination, such as email.
func (actor CognitoActions) ForgotPassword(ctx context.Context, clientId string, userName string) (*types.CodeDeliveryDetailsType, error) {
	output, err := actor.CognitoClient.ForgotPassword(ctx, &cognitoidentityprovider.ForgotPasswordInput{
		ClientId: aws.String(clientId),
		Username: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't start password reset for user '%v'. Here;s why: %v\n", userName, err)
	}
	return output.CodeDeliveryDetails, err
}



// ConfirmForgotPassword confirms a user with a confirmation code and a new password.
func (actor CognitoActions) ConfirmForgotPassword(ctx context.Context, clientId string, code string, userName string, password string) error {
	_, err := actor.CognitoClient.ConfirmForgotPassword(ctx, &cognitoidentityprovider.ConfirmForgotPasswordInput{
		ClientId:         aws.String(clientId),
		ConfirmationCode: aws.String(code),
		Password:         aws.String(password),
		Username:         aws.String(userName),
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't confirm user %v. Here's why: %v", userName, err)
		}
	}
	return err
}



// DeleteUser removes a user from the user pool.
func (actor CognitoActions) DeleteUser(ctx context.Context, userAccessToken string) error {
	_, err := actor.CognitoClient.DeleteUser(ctx, &cognitoidentityprovider.DeleteUserInput{
		AccessToken: aws.String(userAccessToken),
	})
	if err != nil {
		log.Printf("Couldn't delete user. Here's why: %v\n", err)
	}
	return err
}



// AdminCreateUser uses administrator credentials to add a user to a user pool. This method leaves the user
// in a state that requires they enter a new password next time they sign in.
func (actor CognitoActions) AdminCreateUser(ctx context.Context, userPoolId string, userName string, userEmail string) error {
	_, err := actor.CognitoClient.AdminCreateUser(ctx, &cognitoidentityprovider.AdminCreateUserInput{
		UserPoolId:     aws.String(userPoolId),
		Username:       aws.String(userName),
		MessageAction:  types.MessageActionTypeSuppress,
		UserAttributes: []types.AttributeType{{Name: aws.String("email"), Value: aws.String(userEmail)}},
	})
	if err != nil {
		var userExists *types.UsernameExistsException
		if errors.As(err, &userExists) {
			log.Printf("User %v already exists in the user pool.", userName)
			err = nil
		} else {
			log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
DynamoDB アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type DynamoActions struct {
	DynamoClient *dynamodb.Client
}

// User defines structured user data.
type User struct {
	UserName  string
	UserEmail string
	LastLogin *LoginInfo `dynamodbav:",omitempty"`
}

// LoginInfo defines structured custom login data.
type LoginInfo struct {
	UserPoolId string
	ClientId   string
	Time       string
}

// UserList defines a list of users.
type UserList struct {
	Users []User
}

// UserNameList returns the usernames contained in a UserList as a list of strings.
func (users *UserList) UserNameList() []string {
	names := make([]string, len(users.Users))
	for i := 0; i < len(users.Users); i++ {
		names[i] = users.Users[i].UserName
	}
	return names
}

// PopulateTable adds a set of test users to the table.
func (actor DynamoActions) PopulateTable(ctx context.Context, tableName string) error {
	var err error
	var item map[string]types.AttributeValue
	var writeReqs []types.WriteRequest
	for i := 1; i < 4; i++ {
		item, err = attributevalue.MarshalMap(User{UserName: fmt.Sprintf("test_user_%v", i), UserEmail: fmt.Sprintf("test_email_%v@example.com", i)})
		if err != nil {
			log.Printf("Couldn't marshall user into DynamoDB format. Here's why: %v\n", err)
			return err
		}
		writeReqs = append(writeReqs, types.WriteRequest{PutRequest: &types.PutRequest{Item: item}})
	}
	_, err = actor.DynamoClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
		RequestItems: map[string][]types.WriteRequest{tableName: writeReqs},
	})
	if err != nil {
		log.Printf("Couldn't populate table %v with users. Here's why: %v\n", tableName, err)
	}
	return err
}

// Scan scans the table for all items.
func (actor DynamoActions) Scan(ctx context.Context, tableName string) (UserList, error) {
	var userList UserList
	output, err := actor.DynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't scan table %v for items. Here's why: %v\n", tableName, err)
	} else {
		err = attributevalue.UnmarshalListOfMaps(output.Items, &userList.Users)
		if err != nil {
			log.Printf("Couldn't unmarshal items into users. Here's why: %v\n", err)
		}
	}
	return userList, err
}

// AddUser adds a user item to a table.
func (actor DynamoActions) AddUser(ctx context.Context, tableName string, user User) error {
	userItem, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshall user to item. Here's why: %v\n", err)
	}
	_, err = actor.DynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
		Item:      userItem,
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't put item in table %v. Here's why: %v", tableName, err)
	}
	return err
}
```
CloudWatch Logs アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
)

type CloudWatchLogsActions struct {
	CwlClient *cloudwatchlogs.Client
}

// GetLatestLogStream gets the most recent log stream for a Lambda function.
func (actor CloudWatchLogsActions) GetLatestLogStream(ctx context.Context, functionName string) (types.LogStream, error) {
	var logStream types.LogStream
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
		Descending:   aws.Bool(true),
		Limit:        aws.Int32(1),
		LogGroupName: aws.String(logGroupName),
		OrderBy:      types.OrderByLastEventTime,
	})
	if err != nil {
		log.Printf("Couldn't get log streams for log group %v. Here's why: %v\n", logGroupName, err)
	} else {
		logStream = output.LogStreams[0]
	}
	return logStream, err
}

// GetLogEvents gets the most recent eventCount events from the specified log stream.
func (actor CloudWatchLogsActions) GetLogEvents(ctx context.Context, functionName string, logStreamName string, eventCount int32) (
	[]types.OutputLogEvent, error) {
	var events []types.OutputLogEvent
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.GetLogEvents(ctx, &cloudwatchlogs.GetLogEventsInput{
		LogStreamName: aws.String(logStreamName),
		Limit:         aws.Int32(eventCount),
		LogGroupName:  aws.String(logGroupName),
	})
	if err != nil {
		log.Printf("Couldn't get log event for log stream %v. Here's why: %v\n", logStreamName, err)
	} else {
		events = output.Events
	}
	return events, err
}
```
 CloudFormation アクションをラップする構造体を作成します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"log"
	"user_pools_and_lambda_triggers/actions"

	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	userPoolId       string
	userAccessTokens []string
	triggers         []actions.Trigger

	cognitoActor *actions.CognitoActions
	questioner   demotools.IQuestioner
}

func (resources *Resources) init(cognitoActor *actions.CognitoActions, questioner demotools.IQuestioner) {
	resources.userAccessTokens = []string{}
	resources.triggers = []actions.Trigger{}
	resources.cognitoActor = cognitoActor
	resources.questioner = questioner
}

// Cleanup deletes all AWS resources created during an example.
func (resources *Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong during cleanup.\n%v\n", r)
			log.Println("Use the AWS Management Console to remove any remaining resources \n" +
				"that were created for this scenario.")
		}
	}()

	wantDelete := resources.questioner.AskBool("Do you want to remove all of the AWS resources that were created "+
		"during this demo (y/n)?", "y")
	if wantDelete {
		for _, accessToken := range resources.userAccessTokens {
			err := resources.cognitoActor.DeleteUser(ctx, accessToken)
			if err != nil {
				log.Println("Couldn't delete user during cleanup.")
				panic(err)
			}
			log.Println("Deleted user.")
		}
		triggerList := make([]actions.TriggerInfo, len(resources.triggers))
		for i := 0; i < len(resources.triggers); i++ {
			triggerList[i] = actions.TriggerInfo{Trigger: resources.triggers[i], HandlerArn: nil}
		}
		err := resources.cognitoActor.UpdateTriggers(ctx, resources.userPoolId, triggerList...)
		if err != nil {
			log.Println("Couldn't update Cognito triggers during cleanup.")
			panic(err)
		}
		log.Println("Removed Cognito triggers from user pool.")
	} else {
		log.Println("Be sure to remove resources when you're done with them to avoid unexpected charges!")
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [AdminCreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.AdminCreateUser)
  + [AdminSetUserPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.AdminSetUserPassword)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.DeleteUser)
  + [InitiateAuth](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.InitiateAuth)
  + [UpdateUserPool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.UpdateUserPool)

# SDK for Go V2 を使用した Amazon DocumentDB の例
<a name="go_2_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_go_2_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/aws/aws-lambda-go/lambda"
)

type Event struct {
	Events []Record `json:"events"`
}

type Record struct {
	Event struct {
		OperationType string `json:"operationType"`
		NS            struct {
			DB   string `json:"db"`
			Coll string `json:"coll"`
		} `json:"ns"`
		FullDocument interface{} `json:"fullDocument"`
	} `json:"event"`
}

func main() {
	lambda.Start(handler)
}

func handler(ctx context.Context, event Event) (string, error) {
	fmt.Println("Loading function")
	for _, record := range event.Events {
		logDocumentDBEvent(record)
	}

	return "OK", nil
}

func logDocumentDBEvent(record Record) {
	fmt.Printf("Operation type: %s\n", record.Event.OperationType)
	fmt.Printf("db: %s\n", record.Event.NS.DB)
	fmt.Printf("collection: %s\n", record.Event.NS.Coll)
	docBytes, _ := json.MarshalIndent(record.Event.FullDocument, "", "  ")
	fmt.Printf("Full document: %s\n", string(docBytes))
}
```

# SDK for Go V2 を使用した DynamoDB の例
<a name="go_2_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームによって作成され、維持されている例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。
対話型シナリオを実行してテーブルを作成し、そのテーブルに対してアクションを実行します。  

```
import (
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/dynamodb/actions"
)

// RunMovieScenario is an interactive example that shows you how to use the AWS SDK for Go
// to create and use an Amazon DynamoDB table that stores data about movies.
//
//  1. Create a table that can hold movie data.
//  2. Put, get, and update a single movie in the table.
//  3. Write movie data to the table from a sample JSON file.
//  4. Query for movies that were released in a given year.
//  5. Scan for movies that were released in a range of years.
//  6. Delete a movie from the table.
//  7. Delete the table.
//
// This example creates a DynamoDB service client from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// It uses a questioner from the `demotools` package to get input during the example.
// This package can be found in the ..\..\demotools folder of this repo.
//
// The specified movie sampler is used to get sample data from a URL that is loaded
// into the named table.
func RunMovieScenario(
	ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner, tableName string,
	movieSampler actions.IMovieSampler) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("Something went wrong with the demo.")
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon DynamoDB getting started demo.")
	log.Println(strings.Repeat("-", 88))

	tableBasics := actions.TableBasics{TableName: tableName,
		DynamoDbClient: dynamodb.NewFromConfig(sdkConfig)}

	exists, err := tableBasics.TableExists(ctx)
	if err != nil {
		panic(err)
	}
	if !exists {
		log.Printf("Creating table %v...\n", tableName)
		_, err = tableBasics.CreateMovieTable(ctx)
		if err != nil {
			panic(err)
		} else {
			log.Printf("Created table %v.\n", tableName)
		}
	} else {
		log.Printf("Table %v already exists.\n", tableName)
	}

	var customMovie actions.Movie
	customMovie.Title = questioner.Ask("Enter a movie title to add to the table:",
		demotools.NotEmpty{})
	customMovie.Year = questioner.AskInt("What year was it released?",
		demotools.NotEmpty{}, demotools.InIntRange{Lower: 1900, Upper: 2030})
	customMovie.Info = map[string]interface{}{}
	customMovie.Info["rating"] = questioner.AskFloat64(
		"Enter a rating between 1 and 10:",
		demotools.NotEmpty{}, demotools.InFloatRange{Lower: 1, Upper: 10})
	customMovie.Info["plot"] = questioner.Ask("What's the plot? ",
		demotools.NotEmpty{})
	err = tableBasics.AddMovie(ctx, customMovie)
	if err == nil {
		log.Printf("Added %v to the movie table.\n", customMovie.Title)
	}
	log.Println(strings.Repeat("-", 88))

	log.Printf("Let's update your movie. You previously rated it %v.\n", customMovie.Info["rating"])
	customMovie.Info["rating"] = questioner.AskFloat64(
		"What new rating would you give it?",
		demotools.NotEmpty{}, demotools.InFloatRange{Lower: 1, Upper: 10})
	log.Printf("You summarized the plot as '%v'.\n", customMovie.Info["plot"])
	customMovie.Info["plot"] = questioner.Ask("What would you say now?",
		demotools.NotEmpty{})
	attributes, err := tableBasics.UpdateMovie(ctx, customMovie)
	if err == nil {
		log.Printf("Updated %v with new values.\n", customMovie.Title)
		for _, attVal := range attributes {
			for valKey, val := range attVal {
				log.Printf("\t%v: %v\n", valKey, val)
			}
		}
	}
	log.Println(strings.Repeat("-", 88))

	log.Printf("Getting movie data from %v and adding 250 movies to the table...\n",
		movieSampler.GetURL())
	movies := movieSampler.GetSampleMovies()
	written, err := tableBasics.AddMovieBatch(ctx, movies, 250)
	if err != nil {
		panic(err)
	} else {
		log.Printf("Added %v movies to the table.\n", written)
	}

	show := 10
	if show > written {
		show = written
	}
	log.Printf("The first %v movies in the table are:", show)
	for index, movie := range movies[:show] {
		log.Printf("\t%v. %v\n", index+1, movie.Title)
	}
	movieIndex := questioner.AskInt(
		"Enter the number of a movie to get info about it: ",
		demotools.InIntRange{Lower: 1, Upper: show},
	)
	movie, err := tableBasics.GetMovie(ctx, movies[movieIndex-1].Title, movies[movieIndex-1].Year)
	if err == nil {
		log.Println(movie)
	}
	log.Println(strings.Repeat("-", 88))

	log.Println("Let's get a list of movies released in a given year.")
	releaseYear := questioner.AskInt("Enter a year between 1972 and 2018: ",
		demotools.InIntRange{Lower: 1972, Upper: 2018},
	)
	releases, err := tableBasics.Query(ctx, releaseYear)
	if err == nil {
		if len(releases) == 0 {
			log.Printf("I couldn't find any movies released in %v!\n", releaseYear)
		} else {
			for _, movie = range releases {
				log.Println(movie)
			}
		}
	}
	log.Println(strings.Repeat("-", 88))

	log.Println("Now let's scan for movies released in a range of years.")
	startYear := questioner.AskInt("Enter a year: ",
		demotools.InIntRange{Lower: 1972, Upper: 2018})
	endYear := questioner.AskInt("Enter another year: ",
		demotools.InIntRange{Lower: 1972, Upper: 2018})
	releases, err = tableBasics.Scan(ctx, startYear, endYear)
	if err == nil {
		if len(releases) == 0 {
			log.Printf("I couldn't find any movies released between %v and %v!\n", startYear, endYear)
		} else {
			log.Printf("Found %v movies. In this list, the plot is <nil> because "+
				"we used a projection expression when scanning for items to return only "+
				"the title, year, and rating.\n", len(releases))
			for _, movie = range releases {
				log.Println(movie)
			}
		}
	}
	log.Println(strings.Repeat("-", 88))

	var tables []string
	if questioner.AskBool("Do you want to list all of your tables? (y/n) ", "y") {
		tables, err = tableBasics.ListTables(ctx)
		if err == nil {
			log.Printf("Found %v tables:", len(tables))
			for _, table := range tables {
				log.Printf("\t%v", table)
			}
		}
	}
	log.Println(strings.Repeat("-", 88))

	log.Printf("Let's remove your movie '%v'.\n", customMovie.Title)
	if questioner.AskBool("Do you want to delete it from the table? (y/n) ", "y") {
		err = tableBasics.DeleteMovie(ctx, customMovie)
	}
	if err == nil {
		log.Printf("Deleted %v.\n", customMovie.Title)
	}

	if questioner.AskBool("Delete the table, too? (y/n)", "y") {
		err = tableBasics.DeleteTable(ctx)
	} else {
		log.Println("Don't forget to delete the table when you're done or you might " +
			"incur charges on your account.")
	}
	if err == nil {
		log.Printf("Deleted table %v.\n", tableBasics.TableName)
	}

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
DynamoDB アクションを呼び出す構造体およびメソッドを作成します。  

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// TableExists determines whether a DynamoDB table exists.
func (basics TableBasics) TableExists(ctx context.Context) (bool, error) {
	exists := true
	_, err := basics.DynamoDbClient.DescribeTable(
		ctx, &dynamodb.DescribeTableInput{TableName: aws.String(basics.TableName)},
	)
	if err != nil {
		var notFoundEx *types.ResourceNotFoundException
		if errors.As(err, &notFoundEx) {
			log.Printf("Table %v does not exist.\n", basics.TableName)
			err = nil
		} else {
			log.Printf("Couldn't determine existence of table %v. Here's why: %v\n", basics.TableName, err)
		}
		exists = false
	}
	return exists, err
}



// CreateMovieTable creates a DynamoDB table with a composite primary key defined as
// a string sort key named `title`, and a numeric partition key named `year`.
// This function uses NewTableExistsWaiter to wait for the table to be created by
// DynamoDB before it returns.
func (basics TableBasics) CreateMovieTable(ctx context.Context) (*types.TableDescription, error) {
	var tableDesc *types.TableDescription
	table, err := basics.DynamoDbClient.CreateTable(ctx, &dynamodb.CreateTableInput{
		AttributeDefinitions: []types.AttributeDefinition{{
			AttributeName: aws.String("year"),
			AttributeType: types.ScalarAttributeTypeN,
		}, {
			AttributeName: aws.String("title"),
			AttributeType: types.ScalarAttributeTypeS,
		}},
		KeySchema: []types.KeySchemaElement{{
			AttributeName: aws.String("year"),
			KeyType:       types.KeyTypeHash,
		}, {
			AttributeName: aws.String("title"),
			KeyType:       types.KeyTypeRange,
		}},
		TableName:   aws.String(basics.TableName),
		BillingMode: types.BillingModePayPerRequest,
	})
	if err != nil {
		log.Printf("Couldn't create table %v. Here's why: %v\n", basics.TableName, err)
	} else {
		waiter := dynamodb.NewTableExistsWaiter(basics.DynamoDbClient)
		err = waiter.Wait(ctx, &dynamodb.DescribeTableInput{
			TableName: aws.String(basics.TableName)}, 5*time.Minute)
		if err != nil {
			log.Printf("Wait for table exists failed. Here's why: %v\n", err)
		}
		tableDesc = table.TableDescription
		log.Printf("Ccreating table test")
	}
	return tableDesc, err
}



// ListTables lists the DynamoDB table names for the current account.
func (basics TableBasics) ListTables(ctx context.Context) ([]string, error) {
	var tableNames []string
	var output *dynamodb.ListTablesOutput
	var err error
	tablePaginator := dynamodb.NewListTablesPaginator(basics.DynamoDbClient, &dynamodb.ListTablesInput{})
	for tablePaginator.HasMorePages() {
		output, err = tablePaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't list tables. Here's why: %v\n", err)
			break
		} else {
			tableNames = append(tableNames, output.TableNames...)
		}
	}
	return tableNames, err
}



// AddMovie adds a movie the DynamoDB table.
func (basics TableBasics) AddMovie(ctx context.Context, movie Movie) error {
	item, err := attributevalue.MarshalMap(movie)
	if err != nil {
		panic(err)
	}
	_, err = basics.DynamoDbClient.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(basics.TableName), Item: item,
	})
	if err != nil {
		log.Printf("Couldn't add item to table. Here's why: %v\n", err)
	}
	return err
}



// UpdateMovie updates the rating and plot of a movie that already exists in the
// DynamoDB table. This function uses the `expression` package to build the update
// expression.
func (basics TableBasics) UpdateMovie(ctx context.Context, movie Movie) (map[string]map[string]interface{}, error) {
	var err error
	var response *dynamodb.UpdateItemOutput
	var attributeMap map[string]map[string]interface{}
	update := expression.Set(expression.Name("info.rating"), expression.Value(movie.Info["rating"]))
	update.Set(expression.Name("info.plot"), expression.Value(movie.Info["plot"]))
	expr, err := expression.NewBuilder().WithUpdate(update).Build()
	if err != nil {
		log.Printf("Couldn't build expression for update. Here's why: %v\n", err)
	} else {
		response, err = basics.DynamoDbClient.UpdateItem(ctx, &dynamodb.UpdateItemInput{
			TableName:                 aws.String(basics.TableName),
			Key:                       movie.GetKey(),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			UpdateExpression:          expr.Update(),
			ReturnValues:              types.ReturnValueUpdatedNew,
		})
		if err != nil {
			log.Printf("Couldn't update movie %v. Here's why: %v\n", movie.Title, err)
		} else {
			err = attributevalue.UnmarshalMap(response.Attributes, &attributeMap)
			if err != nil {
				log.Printf("Couldn't unmarshall update response. Here's why: %v\n", err)
			}
		}
	}
	return attributeMap, err
}



// AddMovieBatch adds a slice of movies to the DynamoDB table. The function sends
// batches of 25 movies to DynamoDB until all movies are added or it reaches the
// specified maximum.
func (basics TableBasics) AddMovieBatch(ctx context.Context, movies []Movie, maxMovies int) (int, error) {
	var err error
	var item map[string]types.AttributeValue
	written := 0
	batchSize := 25 // DynamoDB allows a maximum batch size of 25 items.
	start := 0
	end := start + batchSize
	for start < maxMovies && start < len(movies) {
		var writeReqs []types.WriteRequest
		if end > len(movies) {
			end = len(movies)
		}
		for _, movie := range movies[start:end] {
			item, err = attributevalue.MarshalMap(movie)
			if err != nil {
				log.Printf("Couldn't marshal movie %v for batch writing. Here's why: %v\n", movie.Title, err)
			} else {
				writeReqs = append(
					writeReqs,
					types.WriteRequest{PutRequest: &types.PutRequest{Item: item}},
				)
			}
		}
		_, err = basics.DynamoDbClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
			RequestItems: map[string][]types.WriteRequest{basics.TableName: writeReqs}})
		if err != nil {
			log.Printf("Couldn't add a batch of movies to %v. Here's why: %v\n", basics.TableName, err)
		} else {
			written += len(writeReqs)
		}
		start = end
		end += batchSize
	}

	return written, err
}



// GetMovie gets movie data from the DynamoDB table by using the primary composite key
// made of title and year.
func (basics TableBasics) GetMovie(ctx context.Context, title string, year int) (Movie, error) {
	movie := Movie{Title: title, Year: year}
	response, err := basics.DynamoDbClient.GetItem(ctx, &dynamodb.GetItemInput{
		Key: movie.GetKey(), TableName: aws.String(basics.TableName),
	})
	if err != nil {
		log.Printf("Couldn't get info about %v. Here's why: %v\n", title, err)
	} else {
		err = attributevalue.UnmarshalMap(response.Item, &movie)
		if err != nil {
			log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
		}
	}
	return movie, err
}



// Query gets all movies in the DynamoDB table that were released in the specified year.
// The function uses the `expression` package to build the key condition expression
// that is used in the query.
func (basics TableBasics) Query(ctx context.Context, releaseYear int) ([]Movie, error) {
	var err error
	var response *dynamodb.QueryOutput
	var movies []Movie
	keyEx := expression.Key("year").Equal(expression.Value(releaseYear))
	expr, err := expression.NewBuilder().WithKeyCondition(keyEx).Build()
	if err != nil {
		log.Printf("Couldn't build expression for query. Here's why: %v\n", err)
	} else {
		queryPaginator := dynamodb.NewQueryPaginator(basics.DynamoDbClient, &dynamodb.QueryInput{
			TableName:                 aws.String(basics.TableName),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			KeyConditionExpression:    expr.KeyCondition(),
		})
		for queryPaginator.HasMorePages() {
			response, err = queryPaginator.NextPage(ctx)
			if err != nil {
				log.Printf("Couldn't query for movies released in %v. Here's why: %v\n", releaseYear, err)
				break
			} else {
				var moviePage []Movie
				err = attributevalue.UnmarshalListOfMaps(response.Items, &moviePage)
				if err != nil {
					log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
					break
				} else {
					movies = append(movies, moviePage...)
				}
			}
		}
	}
	return movies, err
}



// Scan gets all movies in the DynamoDB table that were released in a range of years
// and projects them to return a reduced set of fields.
// The function uses the `expression` package to build the filter and projection
// expressions.
func (basics TableBasics) Scan(ctx context.Context, startYear int, endYear int) ([]Movie, error) {
	var movies []Movie
	var err error
	var response *dynamodb.ScanOutput
	filtEx := expression.Name("year").Between(expression.Value(startYear), expression.Value(endYear))
	projEx := expression.NamesList(
		expression.Name("year"), expression.Name("title"), expression.Name("info.rating"))
	expr, err := expression.NewBuilder().WithFilter(filtEx).WithProjection(projEx).Build()
	if err != nil {
		log.Printf("Couldn't build expressions for scan. Here's why: %v\n", err)
	} else {
		scanPaginator := dynamodb.NewScanPaginator(basics.DynamoDbClient, &dynamodb.ScanInput{
			TableName:                 aws.String(basics.TableName),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			FilterExpression:          expr.Filter(),
			ProjectionExpression:      expr.Projection(),
		})
		for scanPaginator.HasMorePages() {
			response, err = scanPaginator.NextPage(ctx)
			if err != nil {
				log.Printf("Couldn't scan for movies released between %v and %v. Here's why: %v\n",
					startYear, endYear, err)
				break
			} else {
				var moviePage []Movie
				err = attributevalue.UnmarshalListOfMaps(response.Items, &moviePage)
				if err != nil {
					log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
					break
				} else {
					movies = append(movies, moviePage...)
				}
			}
		}
	}
	return movies, err
}



// DeleteMovie removes a movie from the DynamoDB table.
func (basics TableBasics) DeleteMovie(ctx context.Context, movie Movie) error {
	_, err := basics.DynamoDbClient.DeleteItem(ctx, &dynamodb.DeleteItemInput{
		TableName: aws.String(basics.TableName), Key: movie.GetKey(),
	})
	if err != nil {
		log.Printf("Couldn't delete %v from the table. Here's why: %v\n", movie.Title, err)
	}
	return err
}



// DeleteTable deletes the DynamoDB table and all of its data.
func (basics TableBasics) DeleteTable(ctx context.Context) error {
	_, err := basics.DynamoDbClient.DeleteTable(ctx, &dynamodb.DeleteTableInput{
		TableName: aws.String(basics.TableName)})
	if err != nil {
		log.Printf("Couldn't delete table %v. Here's why: %v\n", basics.TableName, err)
	}
	return err
}
```
+ API の詳細については、「AWS SDK for Go API リファレンス**」の以下のトピックを参照してください。
  + [BatchWriteItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.BatchWriteItem)
  + [CreateTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.CreateTable)
  + [DeleteItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteItem)
  + [DeleteTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteTable)
  + [DescribeTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DescribeTable)
  + [GetItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.GetItem)
  + [PutItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.PutItem)
  + [Query](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Query)
  + [Scan](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Scan)
  + [UpdateItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.UpdateItem)

## アクション
<a name="actions"></a>

### `BatchExecuteStatement`
<a name="dynamodb_BatchExecuteStatement_go_2_topic"></a>

次のコード例は、`BatchExecuteStatement` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例の関数レシーバー構造体を定義します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// PartiQLRunner encapsulates the Amazon DynamoDB service actions used in the
// PartiQL examples. It contains a DynamoDB service client that is used to act on the
// specified table.
type PartiQLRunner struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}
```
INSERT ステートメントのバッチを使用して項目を追加します。  

```
// AddMovieBatch runs a batch of PartiQL INSERT statements to add multiple movies to the
// DynamoDB table.
func (runner PartiQLRunner) AddMovieBatch(ctx context.Context, movies []Movie) error {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year, movie.Info})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(fmt.Sprintf(
				"INSERT INTO \"%v\" VALUE {'title': ?, 'year': ?, 'info': ?}", runner.TableName)),
			Parameters: params,
		}
	}

	_, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	if err != nil {
		log.Printf("Couldn't insert a batch of items with PartiQL. Here's why: %v\n", err)
	}
	return err
}
```
SELECT ステートメントのバッチを使用して項目を取得します。  

```
// GetMovieBatch runs a batch of PartiQL SELECT statements to get multiple movies from
// the DynamoDB table by title and year.
func (runner PartiQLRunner) GetMovieBatch(ctx context.Context, movies []Movie) ([]Movie, error) {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(
				fmt.Sprintf("SELECT * FROM \"%v\" WHERE title=? AND year=?", runner.TableName)),
			Parameters: params,
		}
	}

	output, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	var outMovies []Movie
	if err != nil {
		log.Printf("Couldn't get a batch of items with PartiQL. Here's why: %v\n", err)
	} else {
		for _, response := range output.Responses {
			var movie Movie
			err = attributevalue.UnmarshalMap(response.Item, &movie)
			if err != nil {
				log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
			} else {
				outMovies = append(outMovies, movie)
			}
		}
	}
	return outMovies, err
}
```
UPDATE ステートメントのバッチを使用して項目を更新します。  

```
// UpdateMovieBatch runs a batch of PartiQL UPDATE statements to update the rating of
// multiple movies that already exist in the DynamoDB table.
func (runner PartiQLRunner) UpdateMovieBatch(ctx context.Context, movies []Movie, ratings []float64) error {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{ratings[index], movie.Title, movie.Year})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(
				fmt.Sprintf("UPDATE \"%v\" SET info.rating=? WHERE title=? AND year=?", runner.TableName)),
			Parameters: params,
		}
	}

	_, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	if err != nil {
		log.Printf("Couldn't update the batch of movies. Here's why: %v\n", err)
	}
	return err
}
```
DELETE ステートメントのバッチを使用して項目を削除します。  

```
// DeleteMovieBatch runs a batch of PartiQL DELETE statements to remove multiple movies
// from the DynamoDB table.
func (runner PartiQLRunner) DeleteMovieBatch(ctx context.Context, movies []Movie) error {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(
				fmt.Sprintf("DELETE FROM \"%v\" WHERE title=? AND year=?", runner.TableName)),
			Parameters: params,
		}
	}

	_, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	if err != nil {
		log.Printf("Couldn't delete the batch of movies. Here's why: %v\n", err)
	}
	return err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[BatchExecuteStatement](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.BatchExecuteStatement)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_go_2_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// AddMovieBatch adds a slice of movies to the DynamoDB table. The function sends
// batches of 25 movies to DynamoDB until all movies are added or it reaches the
// specified maximum.
func (basics TableBasics) AddMovieBatch(ctx context.Context, movies []Movie, maxMovies int) (int, error) {
	var err error
	var item map[string]types.AttributeValue
	written := 0
	batchSize := 25 // DynamoDB allows a maximum batch size of 25 items.
	start := 0
	end := start + batchSize
	for start < maxMovies && start < len(movies) {
		var writeReqs []types.WriteRequest
		if end > len(movies) {
			end = len(movies)
		}
		for _, movie := range movies[start:end] {
			item, err = attributevalue.MarshalMap(movie)
			if err != nil {
				log.Printf("Couldn't marshal movie %v for batch writing. Here's why: %v\n", movie.Title, err)
			} else {
				writeReqs = append(
					writeReqs,
					types.WriteRequest{PutRequest: &types.PutRequest{Item: item}},
				)
			}
		}
		_, err = basics.DynamoDbClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
			RequestItems: map[string][]types.WriteRequest{basics.TableName: writeReqs}})
		if err != nil {
			log.Printf("Couldn't add a batch of movies to %v. Here's why: %v\n", basics.TableName, err)
		} else {
			written += len(writeReqs)
		}
		start = end
		end += batchSize
	}

	return written, err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[BatchWriteItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.BatchWriteItem)」を参照してください。

### `CreateTable`
<a name="dynamodb_CreateTable_go_2_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// CreateMovieTable creates a DynamoDB table with a composite primary key defined as
// a string sort key named `title`, and a numeric partition key named `year`.
// This function uses NewTableExistsWaiter to wait for the table to be created by
// DynamoDB before it returns.
func (basics TableBasics) CreateMovieTable(ctx context.Context) (*types.TableDescription, error) {
	var tableDesc *types.TableDescription
	table, err := basics.DynamoDbClient.CreateTable(ctx, &dynamodb.CreateTableInput{
		AttributeDefinitions: []types.AttributeDefinition{{
			AttributeName: aws.String("year"),
			AttributeType: types.ScalarAttributeTypeN,
		}, {
			AttributeName: aws.String("title"),
			AttributeType: types.ScalarAttributeTypeS,
		}},
		KeySchema: []types.KeySchemaElement{{
			AttributeName: aws.String("year"),
			KeyType:       types.KeyTypeHash,
		}, {
			AttributeName: aws.String("title"),
			KeyType:       types.KeyTypeRange,
		}},
		TableName:   aws.String(basics.TableName),
		BillingMode: types.BillingModePayPerRequest,
	})
	if err != nil {
		log.Printf("Couldn't create table %v. Here's why: %v\n", basics.TableName, err)
	} else {
		waiter := dynamodb.NewTableExistsWaiter(basics.DynamoDbClient)
		err = waiter.Wait(ctx, &dynamodb.DescribeTableInput{
			TableName: aws.String(basics.TableName)}, 5*time.Minute)
		if err != nil {
			log.Printf("Wait for table exists failed. Here's why: %v\n", err)
		}
		tableDesc = table.TableDescription
		log.Printf("Ccreating table test")
	}
	return tableDesc, err
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの**「[CreateTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_go_2_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// DeleteMovie removes a movie from the DynamoDB table.
func (basics TableBasics) DeleteMovie(ctx context.Context, movie Movie) error {
	_, err := basics.DynamoDbClient.DeleteItem(ctx, &dynamodb.DeleteItemInput{
		TableName: aws.String(basics.TableName), Key: movie.GetKey(),
	})
	if err != nil {
		log.Printf("Couldn't delete %v from the table. Here's why: %v\n", movie.Title, err)
	}
	return err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*のの「[DeleteItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteItem)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_go_2_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// DeleteTable deletes the DynamoDB table and all of its data.
func (basics TableBasics) DeleteTable(ctx context.Context) error {
	_, err := basics.DynamoDbClient.DeleteTable(ctx, &dynamodb.DeleteTableInput{
		TableName: aws.String(basics.TableName)})
	if err != nil {
		log.Printf("Couldn't delete table %v. Here's why: %v\n", basics.TableName, err)
	}
	return err
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの**「[DeleteTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DeleteTable)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_go_2_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// TableExists determines whether a DynamoDB table exists.
func (basics TableBasics) TableExists(ctx context.Context) (bool, error) {
	exists := true
	_, err := basics.DynamoDbClient.DescribeTable(
		ctx, &dynamodb.DescribeTableInput{TableName: aws.String(basics.TableName)},
	)
	if err != nil {
		var notFoundEx *types.ResourceNotFoundException
		if errors.As(err, &notFoundEx) {
			log.Printf("Table %v does not exist.\n", basics.TableName)
			err = nil
		} else {
			log.Printf("Couldn't determine existence of table %v. Here's why: %v\n", basics.TableName, err)
		}
		exists = false
	}
	return exists, err
}
```
+  API の詳細については、**AWS SDK for Go API リファレンスの「[DescribeTable](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.DescribeTable)」を参照してください。

### `ExecuteStatement`
<a name="dynamodb_ExecuteStatement_go_2_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例の関数レシーバー構造体を定義します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// PartiQLRunner encapsulates the Amazon DynamoDB service actions used in the
// PartiQL examples. It contains a DynamoDB service client that is used to act on the
// specified table.
type PartiQLRunner struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}
```
INSERT ステートメントを使用して項目を追加します。  

```
// AddMovie runs a PartiQL INSERT statement to add a movie to the DynamoDB table.
func (runner PartiQLRunner) AddMovie(ctx context.Context, movie Movie) error {
	params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year, movie.Info})
	if err != nil {
		panic(err)
	}
	_, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("INSERT INTO \"%v\" VALUE {'title': ?, 'year': ?, 'info': ?}",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't insert an item with PartiQL. Here's why: %v\n", err)
	}
	return err
}
```
SELECT ステートメントを使用して項目を取得します。  

```
// GetMovie runs a PartiQL SELECT statement to get a movie from the DynamoDB table by
// title and year.
func (runner PartiQLRunner) GetMovie(ctx context.Context, title string, year int) (Movie, error) {
	var movie Movie
	params, err := attributevalue.MarshalList([]interface{}{title, year})
	if err != nil {
		panic(err)
	}
	response, err := runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("SELECT * FROM \"%v\" WHERE title=? AND year=?",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't get info about %v. Here's why: %v\n", title, err)
	} else {
		err = attributevalue.UnmarshalMap(response.Items[0], &movie)
		if err != nil {
			log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
		}
	}
	return movie, err
}
```
SELECT ステートメントを使用して、項目のリストを取得し、結果を射影します。  

```
// GetAllMovies runs a PartiQL SELECT statement to get all movies from the DynamoDB table.
// pageSize is not typically required and is used to show how to paginate the results.
// The results are projected to return only the title and rating of each movie.
func (runner PartiQLRunner) GetAllMovies(ctx context.Context, pageSize int32) ([]map[string]interface{}, error) {
	var output []map[string]interface{}
	var response *dynamodb.ExecuteStatementOutput
	var err error
	var nextToken *string
	for moreData := true; moreData; {
		response, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
			Statement: aws.String(
				fmt.Sprintf("SELECT title, info.rating FROM \"%v\"", runner.TableName)),
			Limit:     aws.Int32(pageSize),
			NextToken: nextToken,
		})
		if err != nil {
			log.Printf("Couldn't get movies. Here's why: %v\n", err)
			moreData = false
		} else {
			var pageOutput []map[string]interface{}
			err = attributevalue.UnmarshalListOfMaps(response.Items, &pageOutput)
			if err != nil {
				log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
			} else {
				log.Printf("Got a page of length %v.\n", len(response.Items))
				output = append(output, pageOutput...)
			}
			nextToken = response.NextToken
			moreData = nextToken != nil
		}
	}
	return output, err
}
```
UPDATE ステートメントを使用して項目を更新します。  

```
// UpdateMovie runs a PartiQL UPDATE statement to update the rating of a movie that
// already exists in the DynamoDB table.
func (runner PartiQLRunner) UpdateMovie(ctx context.Context, movie Movie, rating float64) error {
	params, err := attributevalue.MarshalList([]interface{}{rating, movie.Title, movie.Year})
	if err != nil {
		panic(err)
	}
	_, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("UPDATE \"%v\" SET info.rating=? WHERE title=? AND year=?",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't update movie %v. Here's why: %v\n", movie.Title, err)
	}
	return err
}
```
DELETE ステートメントを使用して項目を削除します。  

```
// DeleteMovie runs a PartiQL DELETE statement to remove a movie from the DynamoDB table.
func (runner PartiQLRunner) DeleteMovie(ctx context.Context, movie Movie) error {
	params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year})
	if err != nil {
		panic(err)
	}
	_, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("DELETE FROM \"%v\" WHERE title=? AND year=?",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't delete %v from the table. Here's why: %v\n", movie.Title, err)
	}
	return err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ExecuteStatement](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.ExecuteStatement)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_go_2_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// GetMovie gets movie data from the DynamoDB table by using the primary composite key
// made of title and year.
func (basics TableBasics) GetMovie(ctx context.Context, title string, year int) (Movie, error) {
	movie := Movie{Title: title, Year: year}
	response, err := basics.DynamoDbClient.GetItem(ctx, &dynamodb.GetItemInput{
		Key: movie.GetKey(), TableName: aws.String(basics.TableName),
	})
	if err != nil {
		log.Printf("Couldn't get info about %v. Here's why: %v\n", title, err)
	} else {
		err = attributevalue.UnmarshalMap(response.Item, &movie)
		if err != nil {
			log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
		}
	}
	return movie, err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[GetItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.GetItem)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_go_2_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// ListTables lists the DynamoDB table names for the current account.
func (basics TableBasics) ListTables(ctx context.Context) ([]string, error) {
	var tableNames []string
	var output *dynamodb.ListTablesOutput
	var err error
	tablePaginator := dynamodb.NewListTablesPaginator(basics.DynamoDbClient, &dynamodb.ListTablesInput{})
	for tablePaginator.HasMorePages() {
		output, err = tablePaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't list tables. Here's why: %v\n", err)
			break
		} else {
			tableNames = append(tableNames, output.TableNames...)
		}
	}
	return tableNames, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListTables](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_go_2_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// AddMovie adds a movie the DynamoDB table.
func (basics TableBasics) AddMovie(ctx context.Context, movie Movie) error {
	item, err := attributevalue.MarshalMap(movie)
	if err != nil {
		panic(err)
	}
	_, err = basics.DynamoDbClient.PutItem(ctx, &dynamodb.PutItemInput{
		TableName: aws.String(basics.TableName), Item: item,
	})
	if err != nil {
		log.Printf("Couldn't add item to table. Here's why: %v\n", err)
	}
	return err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[PutItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.PutItem)」を参照してください。

### `Query`
<a name="dynamodb_Query_go_2_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// Query gets all movies in the DynamoDB table that were released in the specified year.
// The function uses the `expression` package to build the key condition expression
// that is used in the query.
func (basics TableBasics) Query(ctx context.Context, releaseYear int) ([]Movie, error) {
	var err error
	var response *dynamodb.QueryOutput
	var movies []Movie
	keyEx := expression.Key("year").Equal(expression.Value(releaseYear))
	expr, err := expression.NewBuilder().WithKeyCondition(keyEx).Build()
	if err != nil {
		log.Printf("Couldn't build expression for query. Here's why: %v\n", err)
	} else {
		queryPaginator := dynamodb.NewQueryPaginator(basics.DynamoDbClient, &dynamodb.QueryInput{
			TableName:                 aws.String(basics.TableName),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			KeyConditionExpression:    expr.KeyCondition(),
		})
		for queryPaginator.HasMorePages() {
			response, err = queryPaginator.NextPage(ctx)
			if err != nil {
				log.Printf("Couldn't query for movies released in %v. Here's why: %v\n", releaseYear, err)
				break
			} else {
				var moviePage []Movie
				err = attributevalue.UnmarshalListOfMaps(response.Items, &moviePage)
				if err != nil {
					log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
					break
				} else {
					movies = append(movies, moviePage...)
				}
			}
		}
	}
	return movies, err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[Query](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Query)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_go_2_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// Scan gets all movies in the DynamoDB table that were released in a range of years
// and projects them to return a reduced set of fields.
// The function uses the `expression` package to build the filter and projection
// expressions.
func (basics TableBasics) Scan(ctx context.Context, startYear int, endYear int) ([]Movie, error) {
	var movies []Movie
	var err error
	var response *dynamodb.ScanOutput
	filtEx := expression.Name("year").Between(expression.Value(startYear), expression.Value(endYear))
	projEx := expression.NamesList(
		expression.Name("year"), expression.Name("title"), expression.Name("info.rating"))
	expr, err := expression.NewBuilder().WithFilter(filtEx).WithProjection(projEx).Build()
	if err != nil {
		log.Printf("Couldn't build expressions for scan. Here's why: %v\n", err)
	} else {
		scanPaginator := dynamodb.NewScanPaginator(basics.DynamoDbClient, &dynamodb.ScanInput{
			TableName:                 aws.String(basics.TableName),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			FilterExpression:          expr.Filter(),
			ProjectionExpression:      expr.Projection(),
		})
		for scanPaginator.HasMorePages() {
			response, err = scanPaginator.NextPage(ctx)
			if err != nil {
				log.Printf("Couldn't scan for movies released between %v and %v. Here's why: %v\n",
					startYear, endYear, err)
				break
			} else {
				var moviePage []Movie
				err = attributevalue.UnmarshalListOfMaps(response.Items, &moviePage)
				if err != nil {
					log.Printf("Couldn't unmarshal query response. Here's why: %v\n", err)
					break
				} else {
					movies = append(movies, moviePage...)
				}
			}
		}
	}
	return movies, err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[Scan](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.Scan)」を参照してください。

### `UpdateItem`
<a name="dynamodb_UpdateItem_go_2_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// TableBasics encapsulates the Amazon DynamoDB service actions used in the examples.
// It contains a DynamoDB service client that is used to act on the specified table.
type TableBasics struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// UpdateMovie updates the rating and plot of a movie that already exists in the
// DynamoDB table. This function uses the `expression` package to build the update
// expression.
func (basics TableBasics) UpdateMovie(ctx context.Context, movie Movie) (map[string]map[string]interface{}, error) {
	var err error
	var response *dynamodb.UpdateItemOutput
	var attributeMap map[string]map[string]interface{}
	update := expression.Set(expression.Name("info.rating"), expression.Value(movie.Info["rating"]))
	update.Set(expression.Name("info.plot"), expression.Value(movie.Info["plot"]))
	expr, err := expression.NewBuilder().WithUpdate(update).Build()
	if err != nil {
		log.Printf("Couldn't build expression for update. Here's why: %v\n", err)
	} else {
		response, err = basics.DynamoDbClient.UpdateItem(ctx, &dynamodb.UpdateItemInput{
			TableName:                 aws.String(basics.TableName),
			Key:                       movie.GetKey(),
			ExpressionAttributeNames:  expr.Names(),
			ExpressionAttributeValues: expr.Values(),
			UpdateExpression:          expr.Update(),
			ReturnValues:              types.ReturnValueUpdatedNew,
		})
		if err != nil {
			log.Printf("Couldn't update movie %v. Here's why: %v\n", movie.Title, err)
		} else {
			err = attributevalue.UnmarshalMap(response.Attributes, &attributeMap)
			if err != nil {
				log.Printf("Couldn't unmarshall update response. Here's why: %v\n", err)
			}
		}
	}
	return attributeMap, err
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[UpdateItem](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.UpdateItem)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_go_2_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルを作成し、PartiQL クエリのバッチを実行するシナリオを実行します。  

```
import (
	"context"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/dynamodb/actions"
)

// RunPartiQLBatchScenario shows you how to use the AWS SDK for Go
// to run batches of PartiQL statements to query a table that stores data about movies.
//
//   - Use batches of PartiQL statements to add, get, update, and delete data for
//     individual movies.
//
// This example creates an Amazon DynamoDB service client from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// This example creates and deletes a DynamoDB table to use during the scenario.
func RunPartiQLBatchScenario(ctx context.Context, sdkConfig aws.Config, tableName string) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("Something went wrong with the demo.")
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon DynamoDB PartiQL batch demo.")
	log.Println(strings.Repeat("-", 88))

	tableBasics := actions.TableBasics{
		DynamoDbClient: dynamodb.NewFromConfig(sdkConfig),
		TableName:      tableName,
	}
	runner := actions.PartiQLRunner{
		DynamoDbClient: dynamodb.NewFromConfig(sdkConfig),
		TableName:      tableName,
	}

	exists, err := tableBasics.TableExists(ctx)
	if err != nil {
		panic(err)
	}
	if !exists {
		log.Printf("Creating table %v...\n", tableName)
		_, err = tableBasics.CreateMovieTable(ctx)
		if err != nil {
			panic(err)
		} else {
			log.Printf("Created table %v.\n", tableName)
		}
	} else {
		log.Printf("Table %v already exists.\n", tableName)
	}
	log.Println(strings.Repeat("-", 88))

	currentYear, _, _ := time.Now().Date()
	customMovies := []actions.Movie{{
		Title: "House PartiQL",
		Year:  currentYear - 5,
		Info: map[string]interface{}{
			"plot":   "Wacky high jinks result from querying a mysterious database.",
			"rating": 8.5}}, {
		Title: "House PartiQL 2",
		Year:  currentYear - 3,
		Info: map[string]interface{}{
			"plot":   "Moderate high jinks result from querying another mysterious database.",
			"rating": 6.5}}, {
		Title: "House PartiQL 3",
		Year:  currentYear - 1,
		Info: map[string]interface{}{
			"plot":   "Tepid high jinks result from querying yet another mysterious database.",
			"rating": 2.5},
	},
	}

	log.Printf("Inserting a batch of movies into table '%v'.\n", tableName)
	err = runner.AddMovieBatch(ctx, customMovies)
	if err == nil {
		log.Printf("Added %v movies to the table.\n", len(customMovies))
	}
	log.Println(strings.Repeat("-", 88))

	log.Println("Getting data for a batch of movies.")
	movies, err := runner.GetMovieBatch(ctx, customMovies)
	if err == nil {
		for _, movie := range movies {
			log.Println(movie)
		}
	}
	log.Println(strings.Repeat("-", 88))

	newRatings := []float64{7.7, 4.4, 1.1}
	log.Println("Updating a batch of movies with new ratings.")
	err = runner.UpdateMovieBatch(ctx, customMovies, newRatings)
	if err == nil {
		log.Printf("Updated %v movies with new ratings.\n", len(customMovies))
	}
	log.Println(strings.Repeat("-", 88))

	log.Println("Getting projected data from the table to verify our update.")
	log.Println("Using a page size of 2 to demonstrate paging.")
	projections, err := runner.GetAllMovies(ctx, 2)
	if err == nil {
		log.Println("All movies:")
		for _, projection := range projections {
			log.Println(projection)
		}
	}
	log.Println(strings.Repeat("-", 88))

	log.Println("Deleting a batch of movies.")
	err = runner.DeleteMovieBatch(ctx, customMovies)
	if err == nil {
		log.Printf("Deleted %v movies.\n", len(customMovies))
	}

	err = tableBasics.DeleteTable(ctx)
	if err == nil {
		log.Printf("Deleted table %v.\n", tableBasics.TableName)
	}

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
PartiQL ステートメントを実行する struct およびメソッドを作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// PartiQLRunner encapsulates the Amazon DynamoDB service actions used in the
// PartiQL examples. It contains a DynamoDB service client that is used to act on the
// specified table.
type PartiQLRunner struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// AddMovieBatch runs a batch of PartiQL INSERT statements to add multiple movies to the
// DynamoDB table.
func (runner PartiQLRunner) AddMovieBatch(ctx context.Context, movies []Movie) error {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year, movie.Info})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(fmt.Sprintf(
				"INSERT INTO \"%v\" VALUE {'title': ?, 'year': ?, 'info': ?}", runner.TableName)),
			Parameters: params,
		}
	}

	_, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	if err != nil {
		log.Printf("Couldn't insert a batch of items with PartiQL. Here's why: %v\n", err)
	}
	return err
}



// GetMovieBatch runs a batch of PartiQL SELECT statements to get multiple movies from
// the DynamoDB table by title and year.
func (runner PartiQLRunner) GetMovieBatch(ctx context.Context, movies []Movie) ([]Movie, error) {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(
				fmt.Sprintf("SELECT * FROM \"%v\" WHERE title=? AND year=?", runner.TableName)),
			Parameters: params,
		}
	}

	output, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	var outMovies []Movie
	if err != nil {
		log.Printf("Couldn't get a batch of items with PartiQL. Here's why: %v\n", err)
	} else {
		for _, response := range output.Responses {
			var movie Movie
			err = attributevalue.UnmarshalMap(response.Item, &movie)
			if err != nil {
				log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
			} else {
				outMovies = append(outMovies, movie)
			}
		}
	}
	return outMovies, err
}



// GetAllMovies runs a PartiQL SELECT statement to get all movies from the DynamoDB table.
// pageSize is not typically required and is used to show how to paginate the results.
// The results are projected to return only the title and rating of each movie.
func (runner PartiQLRunner) GetAllMovies(ctx context.Context, pageSize int32) ([]map[string]interface{}, error) {
	var output []map[string]interface{}
	var response *dynamodb.ExecuteStatementOutput
	var err error
	var nextToken *string
	for moreData := true; moreData; {
		response, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
			Statement: aws.String(
				fmt.Sprintf("SELECT title, info.rating FROM \"%v\"", runner.TableName)),
			Limit:     aws.Int32(pageSize),
			NextToken: nextToken,
		})
		if err != nil {
			log.Printf("Couldn't get movies. Here's why: %v\n", err)
			moreData = false
		} else {
			var pageOutput []map[string]interface{}
			err = attributevalue.UnmarshalListOfMaps(response.Items, &pageOutput)
			if err != nil {
				log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
			} else {
				log.Printf("Got a page of length %v.\n", len(response.Items))
				output = append(output, pageOutput...)
			}
			nextToken = response.NextToken
			moreData = nextToken != nil
		}
	}
	return output, err
}



// UpdateMovieBatch runs a batch of PartiQL UPDATE statements to update the rating of
// multiple movies that already exist in the DynamoDB table.
func (runner PartiQLRunner) UpdateMovieBatch(ctx context.Context, movies []Movie, ratings []float64) error {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{ratings[index], movie.Title, movie.Year})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(
				fmt.Sprintf("UPDATE \"%v\" SET info.rating=? WHERE title=? AND year=?", runner.TableName)),
			Parameters: params,
		}
	}

	_, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	if err != nil {
		log.Printf("Couldn't update the batch of movies. Here's why: %v\n", err)
	}
	return err
}



// DeleteMovieBatch runs a batch of PartiQL DELETE statements to remove multiple movies
// from the DynamoDB table.
func (runner PartiQLRunner) DeleteMovieBatch(ctx context.Context, movies []Movie) error {
	statementRequests := make([]types.BatchStatementRequest, len(movies))
	for index, movie := range movies {
		params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year})
		if err != nil {
			panic(err)
		}
		statementRequests[index] = types.BatchStatementRequest{
			Statement: aws.String(
				fmt.Sprintf("DELETE FROM \"%v\" WHERE title=? AND year=?", runner.TableName)),
			Parameters: params,
		}
	}

	_, err := runner.DynamoDbClient.BatchExecuteStatement(ctx, &dynamodb.BatchExecuteStatementInput{
		Statements: statementRequests,
	})
	if err != nil {
		log.Printf("Couldn't delete the batch of movies. Here's why: %v\n", err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[BatchExecuteStatement](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.BatchExecuteStatement)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_go_2_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルを作成し、PartiQL クエリを実行するシナリオを実行します。  

```
import (
	"context"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/dynamodb/actions"
)

// RunPartiQLSingleScenario shows you how to use the AWS SDK for Go
// to use PartiQL to query a table that stores data about movies.
//
// * Use PartiQL statements to add, get, update, and delete data for individual movies.
//
// This example creates an Amazon DynamoDB service client from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// This example creates and deletes a DynamoDB table to use during the scenario.
func RunPartiQLSingleScenario(ctx context.Context, sdkConfig aws.Config, tableName string) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("Something went wrong with the demo.")
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon DynamoDB PartiQL single action demo.")
	log.Println(strings.Repeat("-", 88))

	tableBasics := actions.TableBasics{
		DynamoDbClient: dynamodb.NewFromConfig(sdkConfig),
		TableName:      tableName,
	}
	runner := actions.PartiQLRunner{
		DynamoDbClient: dynamodb.NewFromConfig(sdkConfig),
		TableName:      tableName,
	}

	exists, err := tableBasics.TableExists(ctx)
	if err != nil {
		panic(err)
	}
	if !exists {
		log.Printf("Creating table %v...\n", tableName)
		_, err = tableBasics.CreateMovieTable(ctx)
		if err != nil {
			panic(err)
		} else {
			log.Printf("Created table %v.\n", tableName)
		}
	} else {
		log.Printf("Table %v already exists.\n", tableName)
	}
	log.Println(strings.Repeat("-", 88))

	currentYear, _, _ := time.Now().Date()
	customMovie := actions.Movie{
		Title: "24 Hour PartiQL People",
		Year:  currentYear,
		Info: map[string]interface{}{
			"plot":   "A group of data developers discover a new query language they can't stop using.",
			"rating": 9.9,
		},
	}

	log.Printf("Inserting movie '%v' released in %v.", customMovie.Title, customMovie.Year)
	err = runner.AddMovie(ctx, customMovie)
	if err == nil {
		log.Printf("Added %v to the movie table.\n", customMovie.Title)
	}
	log.Println(strings.Repeat("-", 88))

	log.Printf("Getting data for movie '%v' released in %v.", customMovie.Title, customMovie.Year)
	movie, err := runner.GetMovie(ctx, customMovie.Title, customMovie.Year)
	if err == nil {
		log.Println(movie)
	}
	log.Println(strings.Repeat("-", 88))

	newRating := 6.6
	log.Printf("Updating movie '%v' with a rating of %v.", customMovie.Title, newRating)
	err = runner.UpdateMovie(ctx, customMovie, newRating)
	if err == nil {
		log.Printf("Updated %v with a new rating.\n", customMovie.Title)
	}
	log.Println(strings.Repeat("-", 88))

	log.Printf("Getting data again to verify the update.")
	movie, err = runner.GetMovie(ctx, customMovie.Title, customMovie.Year)
	if err == nil {
		log.Println(movie)
	}
	log.Println(strings.Repeat("-", 88))

	log.Printf("Deleting movie '%v'.\n", customMovie.Title)
	err = runner.DeleteMovie(ctx, customMovie)
	if err == nil {
		log.Printf("Deleted %v.\n", customMovie.Title)
	}

	err = tableBasics.DeleteTable(ctx)
	if err == nil {
		log.Printf("Deleted table %v.\n", tableBasics.TableName)
	}

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
この例で使用している Movie struct を定義します。  

```
import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"

	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// Movie encapsulates data about a movie. Title and Year are the composite primary key
// of the movie in Amazon DynamoDB. Title is the sort key, Year is the partition key,
// and Info is additional data.
type Movie struct {
	Title string                 `dynamodbav:"title"`
	Year  int                    `dynamodbav:"year"`
	Info  map[string]interface{} `dynamodbav:"info"`
}

// GetKey returns the composite primary key of the movie in a format that can be
// sent to DynamoDB.
func (movie Movie) GetKey() map[string]types.AttributeValue {
	title, err := attributevalue.Marshal(movie.Title)
	if err != nil {
		panic(err)
	}
	year, err := attributevalue.Marshal(movie.Year)
	if err != nil {
		panic(err)
	}
	return map[string]types.AttributeValue{"title": title, "year": year}
}

// String returns the title, year, rating, and plot of a movie, formatted for the example.
func (movie Movie) String() string {
	return fmt.Sprintf("%v\n\tReleased: %v\n\tRating: %v\n\tPlot: %v\n",
		movie.Title, movie.Year, movie.Info["rating"], movie.Info["plot"])
}
```
PartiQL ステートメントを実行する struct およびメソッドを作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// PartiQLRunner encapsulates the Amazon DynamoDB service actions used in the
// PartiQL examples. It contains a DynamoDB service client that is used to act on the
// specified table.
type PartiQLRunner struct {
	DynamoDbClient *dynamodb.Client
	TableName      string
}



// AddMovie runs a PartiQL INSERT statement to add a movie to the DynamoDB table.
func (runner PartiQLRunner) AddMovie(ctx context.Context, movie Movie) error {
	params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year, movie.Info})
	if err != nil {
		panic(err)
	}
	_, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("INSERT INTO \"%v\" VALUE {'title': ?, 'year': ?, 'info': ?}",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't insert an item with PartiQL. Here's why: %v\n", err)
	}
	return err
}



// GetMovie runs a PartiQL SELECT statement to get a movie from the DynamoDB table by
// title and year.
func (runner PartiQLRunner) GetMovie(ctx context.Context, title string, year int) (Movie, error) {
	var movie Movie
	params, err := attributevalue.MarshalList([]interface{}{title, year})
	if err != nil {
		panic(err)
	}
	response, err := runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("SELECT * FROM \"%v\" WHERE title=? AND year=?",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't get info about %v. Here's why: %v\n", title, err)
	} else {
		err = attributevalue.UnmarshalMap(response.Items[0], &movie)
		if err != nil {
			log.Printf("Couldn't unmarshal response. Here's why: %v\n", err)
		}
	}
	return movie, err
}



// UpdateMovie runs a PartiQL UPDATE statement to update the rating of a movie that
// already exists in the DynamoDB table.
func (runner PartiQLRunner) UpdateMovie(ctx context.Context, movie Movie, rating float64) error {
	params, err := attributevalue.MarshalList([]interface{}{rating, movie.Title, movie.Year})
	if err != nil {
		panic(err)
	}
	_, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("UPDATE \"%v\" SET info.rating=? WHERE title=? AND year=?",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't update movie %v. Here's why: %v\n", movie.Title, err)
	}
	return err
}



// DeleteMovie runs a PartiQL DELETE statement to remove a movie from the DynamoDB table.
func (runner PartiQLRunner) DeleteMovie(ctx context.Context, movie Movie) error {
	params, err := attributevalue.MarshalList([]interface{}{movie.Title, movie.Year})
	if err != nil {
		panic(err)
	}
	_, err = runner.DynamoDbClient.ExecuteStatement(ctx, &dynamodb.ExecuteStatementInput{
		Statement: aws.String(
			fmt.Sprintf("DELETE FROM \"%v\" WHERE title=? AND year=?",
				runner.TableName)),
		Parameters: params,
	})
	if err != nil {
		log.Printf("Couldn't delete %v from the table. Here's why: %v\n", movie.Title, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ExecuteStatement](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/dynamodb#Client.ExecuteStatement)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_go_2_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で DynamoDB イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-lambda-go/events"
	"fmt"
)

func HandleRequest(ctx context.Context, event events.DynamoDBEvent) (*string, error) {
	if len(event.Records) == 0 {
		return nil, fmt.Errorf("received empty event")
	}

	for _, record := range event.Records {
	 	LogDynamoDBRecord(record)
	}

	message := fmt.Sprintf("Records processed: %d", len(event.Records))
	return &message, nil
}

func main() {
	lambda.Start(HandleRequest)
}

func LogDynamoDBRecord(record events.DynamoDBEventRecord){
	fmt.Println(record.EventID)
	fmt.Println(record.EventName)
	fmt.Printf("%+v\n", record.Change)
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_go_2_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

type BatchItemFailure struct {
	ItemIdentifier string `json:"ItemIdentifier"`
}

type BatchResult struct {
	BatchItemFailures []BatchItemFailure `json:"BatchItemFailures"`
}

func HandleRequest(ctx context.Context, event events.DynamoDBEvent) (*BatchResult, error) {
	var batchItemFailures []BatchItemFailure
	curRecordSequenceNumber := ""

	for _, record := range event.Records {
		// Process your record
		curRecordSequenceNumber = record.Change.SequenceNumber
	}

	if curRecordSequenceNumber != "" {
		batchItemFailures = append(batchItemFailures, BatchItemFailure{ItemIdentifier: curRecordSequenceNumber})
	}
	
	batchResult := BatchResult{
		BatchItemFailures: batchItemFailures,
	}

	return &batchResult, nil
}

func main() {
	lambda.Start(HandleRequest)
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_go_2_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Go V2**  
 Go SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-go-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# Go V2 を使用した IAM の例
<a name="go_2_iam_code_examples"></a>

次のコード例は、IAM で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_go_2_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/iam"
)

// main uses the AWS SDK for Go (v2) to create an AWS Identity and Access Management (IAM)
// client and list up to 10 policies in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	iamClient := iam.NewFromConfig(sdkConfig)
	const maxPols = 10
	fmt.Printf("Let's list up to %v policies for your account.\n", maxPols)
	result, err := iamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPols),
	})
	if err != nil {
		fmt.Printf("Couldn't list policies for your account. Here's why: %v\n", err)
		return
	}
	if len(result.Policies) == 0 {
		fmt.Println("You don't have any policies!")
	} else {
		for _, policy := range result.Policies {
			fmt.Printf("\t%v\n", *policy.PolicyName)
		}
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListPolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListPolicies)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_go_2_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブのシナリオを実行します。  

```
import (
	"context"
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/credentials"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/sts"
	"github.com/aws/smithy-go"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/iam/actions"
)

// AssumeRoleScenario shows you how to use the AWS Identity and Access Management (IAM)
// service to perform the following actions:
//
//  1. Create a user who has no permissions.
//  2. Create a role that grants permission to list Amazon Simple Storage Service
//     (Amazon S3) buckets for the account.
//  3. Add a policy to let the user assume the role.
//  4. Try and fail to list buckets without permissions.
//  5. Assume the role and list S3 buckets using temporary credentials.
//  6. Delete the policy, role, and user.
type AssumeRoleScenario struct {
	sdkConfig      aws.Config
	accountWrapper actions.AccountWrapper
	policyWrapper  actions.PolicyWrapper
	roleWrapper    actions.RoleWrapper
	userWrapper    actions.UserWrapper
	questioner     demotools.IQuestioner
	helper         IScenarioHelper
	isTestRun      bool
}

// NewAssumeRoleScenario constructs an AssumeRoleScenario instance from a configuration.
// It uses the specified config to get an IAM client and create wrappers for the actions
// used in the scenario.
func NewAssumeRoleScenario(sdkConfig aws.Config, questioner demotools.IQuestioner,
	helper IScenarioHelper) AssumeRoleScenario {
	iamClient := iam.NewFromConfig(sdkConfig)
	return AssumeRoleScenario{
		sdkConfig:      sdkConfig,
		accountWrapper: actions.AccountWrapper{IamClient: iamClient},
		policyWrapper:  actions.PolicyWrapper{IamClient: iamClient},
		roleWrapper:    actions.RoleWrapper{IamClient: iamClient},
		userWrapper:    actions.UserWrapper{IamClient: iamClient},
		questioner:     questioner,
		helper:         helper,
	}
}

// addTestOptions appends the API options specified in the original configuration to
// another configuration. This is used to attach the middleware stubber to clients
// that are constructed during the scenario, which is needed for unit testing.
func (scenario AssumeRoleScenario) addTestOptions(scenarioConfig *aws.Config) {
	if scenario.isTestRun {
		scenarioConfig.APIOptions = append(scenarioConfig.APIOptions, scenario.sdkConfig.APIOptions...)
	}
}

// Run runs the interactive scenario.
func (scenario AssumeRoleScenario) Run(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong with the demo.\n")
			log.Println(r)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the AWS Identity and Access Management (IAM) assume role demo.")
	log.Println(strings.Repeat("-", 88))

	user := scenario.CreateUser(ctx)
	accessKey := scenario.CreateAccessKey(ctx, user)
	role := scenario.CreateRoleAndPolicies(ctx, user)
	noPermsConfig := scenario.ListBucketsWithoutPermissions(ctx, accessKey)
	scenario.ListBucketsWithAssumedRole(ctx, noPermsConfig, role)
	scenario.Cleanup(ctx, user, role)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}

// CreateUser creates a new IAM user. This user has no permissions.
func (scenario AssumeRoleScenario) CreateUser(ctx context.Context) *types.User {
	log.Println("Let's create an example user with no permissions.")
	userName := scenario.questioner.Ask("Enter a name for the example user:", demotools.NotEmpty{})
	user, err := scenario.userWrapper.GetUser(ctx, userName)
	if err != nil {
		panic(err)
	}
	if user == nil {
		user, err = scenario.userWrapper.CreateUser(ctx, userName)
		if err != nil {
			panic(err)
		}
		log.Printf("Created user %v.\n", *user.UserName)
	} else {
		log.Printf("User %v already exists.\n", *user.UserName)
	}
	log.Println(strings.Repeat("-", 88))
	return user
}

// CreateAccessKey creates an access key for the user.
func (scenario AssumeRoleScenario) CreateAccessKey(ctx context.Context, user *types.User) *types.AccessKey {
	accessKey, err := scenario.userWrapper.CreateAccessKeyPair(ctx, *user.UserName)
	if err != nil {
		panic(err)
	}
	log.Printf("Created access key %v for your user.", *accessKey.AccessKeyId)
	log.Println("Waiting a few seconds for your user to be ready...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return accessKey
}

// CreateRoleAndPolicies creates a policy that grants permission to list S3 buckets for
// the current account and attaches the policy to a newly created role. It also adds an
// inline policy to the specified user that grants the user permission to assume the role.
func (scenario AssumeRoleScenario) CreateRoleAndPolicies(ctx context.Context, user *types.User) *types.Role {
	log.Println("Let's create a role and policy that grant permission to list S3 buckets.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	listBucketsRole, err := scenario.roleWrapper.CreateRole(ctx, scenario.helper.GetName(), *user.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created role %v.\n", *listBucketsRole.RoleName)
	listBucketsPolicy, err := scenario.policyWrapper.CreatePolicy(
		ctx, scenario.helper.GetName(), []string{"s3:ListAllMyBuckets"}, "arn:aws:s3:::*")
	if err != nil {
		panic(err)
	}
	log.Printf("Created policy %v.\n", *listBucketsPolicy.PolicyName)
	err = scenario.roleWrapper.AttachRolePolicy(ctx, *listBucketsPolicy.Arn, *listBucketsRole.RoleName)
	if err != nil {
		panic(err)
	}
	log.Printf("Attached policy %v to role %v.\n", *listBucketsPolicy.PolicyName,
		*listBucketsRole.RoleName)
	err = scenario.userWrapper.CreateUserPolicy(ctx, *user.UserName, scenario.helper.GetName(),
		[]string{"sts:AssumeRole"}, *listBucketsRole.Arn)
	if err != nil {
		panic(err)
	}
	log.Printf("Created an inline policy for user %v that lets the user assume the role.\n",
		*user.UserName)
	log.Println("Let's give AWS a few seconds to propagate these new resources and connections...")
	scenario.helper.Pause(10)
	log.Println(strings.Repeat("-", 88))
	return listBucketsRole
}

// ListBucketsWithoutPermissions creates an Amazon S3 client from the user's access key
// credentials and tries to list buckets for the account. Because the user does not have
// permission to perform this action, the action fails.
func (scenario AssumeRoleScenario) ListBucketsWithoutPermissions(ctx context.Context, accessKey *types.AccessKey) *aws.Config {
	log.Println("Let's try to list buckets without permissions. This should return an AccessDenied error.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	noPermsConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*accessKey.AccessKeyId, *accessKey.SecretAccessKey, ""),
		))
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&noPermsConfig)

	s3Client := s3.NewFromConfig(noPermsConfig)
	_, err = s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		// The SDK for Go does not model the AccessDenied error, so check ErrorCode directly.
		var ae smithy.APIError
		if errors.As(err, &ae) {
			switch ae.ErrorCode() {
			case "AccessDenied":
				log.Println("Got AccessDenied error, which is the expected result because\n" +
					"the ListBuckets call was made without permissions.")
			default:
				log.Println("Expected AccessDenied, got something else.")
				panic(err)
			}
		}
	} else {
		log.Println("Expected AccessDenied error when calling ListBuckets without permissions,\n" +
			"but the call succeeded. Continuing the example anyway...")
	}
	log.Println(strings.Repeat("-", 88))
	return &noPermsConfig
}

// ListBucketsWithAssumedRole performs the following actions:
//
//  1. Creates an AWS Security Token Service (AWS STS) client from the config created from
//     the user's access key credentials.
//  2. Gets temporary credentials by assuming the role that grants permission to list the
//     buckets.
//  3. Creates an Amazon S3 client from the temporary credentials.
//  4. Lists buckets for the account. Because the temporary credentials are generated by
//     assuming the role that grants permission, the action succeeds.
func (scenario AssumeRoleScenario) ListBucketsWithAssumedRole(ctx context.Context, noPermsConfig *aws.Config, role *types.Role) {
	log.Println("Let's assume the role that grants permission to list buckets and try again.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	stsClient := sts.NewFromConfig(*noPermsConfig)
	tempCredentials, err := stsClient.AssumeRole(ctx, &sts.AssumeRoleInput{
		RoleArn:         role.Arn,
		RoleSessionName: aws.String("AssumeRoleExampleSession"),
		DurationSeconds: aws.Int32(900),
	})
	if err != nil {
		log.Printf("Couldn't assume role %v.\n", *role.RoleName)
		panic(err)
	}
	log.Printf("Assumed role %v, got temporary credentials.\n", *role.RoleName)
	assumeRoleConfig, err := config.LoadDefaultConfig(ctx,
		config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(
			*tempCredentials.Credentials.AccessKeyId,
			*tempCredentials.Credentials.SecretAccessKey,
			*tempCredentials.Credentials.SessionToken),
		),
	)
	if err != nil {
		panic(err)
	}

	// Add test options if this is a test run. This is needed only for testing purposes.
	scenario.addTestOptions(&assumeRoleConfig)

	s3Client := s3.NewFromConfig(assumeRoleConfig)
	result, err := s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		log.Println("Couldn't list buckets with assumed role credentials.")
		panic(err)
	}
	log.Println("Successfully called ListBuckets with assumed role credentials, \n" +
		"here are some of them:")
	for i := 0; i < len(result.Buckets) && i < 5; i++ {
		log.Printf("\t%v\n", *result.Buckets[i].Name)
	}
	log.Println(strings.Repeat("-", 88))
}

// Cleanup deletes all resources created for the scenario.
func (scenario AssumeRoleScenario) Cleanup(ctx context.Context, user *types.User, role *types.Role) {
	if scenario.questioner.AskBool(
		"Do you want to delete the resources created for this example? (y/n)", "y",
	) {
		policies, err := scenario.roleWrapper.ListAttachedRolePolicies(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		for _, policy := range policies {
			err = scenario.roleWrapper.DetachRolePolicy(ctx, *role.RoleName, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			err = scenario.policyWrapper.DeletePolicy(ctx, *policy.PolicyArn)
			if err != nil {
				panic(err)
			}
			log.Printf("Detached policy %v from role %v and deleted the policy.\n",
				*policy.PolicyName, *role.RoleName)
		}
		err = scenario.roleWrapper.DeleteRole(ctx, *role.RoleName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted role %v.\n", *role.RoleName)

		userPols, err := scenario.userWrapper.ListUserPolicies(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, userPol := range userPols {
			err = scenario.userWrapper.DeleteUserPolicy(ctx, *user.UserName, userPol)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted policy %v from user %v.\n", userPol, *user.UserName)
		}
		keys, err := scenario.userWrapper.ListAccessKeys(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		for _, key := range keys {
			err = scenario.userWrapper.DeleteAccessKey(ctx, *user.UserName, *key.AccessKeyId)
			if err != nil {
				panic(err)
			}
			log.Printf("Deleted access key %v from user %v.\n", *key.AccessKeyId, *user.UserName)
		}
		err = scenario.userWrapper.DeleteUser(ctx, *user.UserName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleted user %v.\n", *user.UserName)
		log.Println(strings.Repeat("-", 88))
	}

}

// IScenarioHelper abstracts input and wait functions from a scenario so that they
// can be mocked for unit testing.
type IScenarioHelper interface {
	GetName() string
	Pause(secs int)
}

const rMax = 100000

type ScenarioHelper struct {
	Prefix string
	Random *rand.Rand
}

// GetName returns a unique name formed of a prefix and a random number.
func (helper *ScenarioHelper) GetName() string {
	return fmt.Sprintf("%v%v", helper.Prefix, helper.Random.Intn(rMax))
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	time.Sleep(time.Duration(secs) * time.Second)
}
```
アカウントアクションをラップする構造体を定義します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// GetAccountPasswordPolicy gets the account password policy for the current account.
// If no policy has been set, a NoSuchEntityException is error is returned.
func (wrapper AccountWrapper) GetAccountPasswordPolicy(ctx context.Context) (*types.PasswordPolicy, error) {
	var pwPolicy *types.PasswordPolicy
	result, err := wrapper.IamClient.GetAccountPasswordPolicy(ctx,
		&iam.GetAccountPasswordPolicyInput{})
	if err != nil {
		log.Printf("Couldn't get account password policy. Here's why: %v\n", err)
	} else {
		pwPolicy = result.PasswordPolicy
	}
	return pwPolicy, err
}



// ListSAMLProviders gets the SAML providers for the account.
func (wrapper AccountWrapper) ListSAMLProviders(ctx context.Context) ([]types.SAMLProviderListEntry, error) {
	var providers []types.SAMLProviderListEntry
	result, err := wrapper.IamClient.ListSAMLProviders(ctx, &iam.ListSAMLProvidersInput{})
	if err != nil {
		log.Printf("Couldn't list SAML providers. Here's why: %v\n", err)
	} else {
		providers = result.SAMLProviderList
	}
	return providers, err
}
```
ポリシーアクションをラップする構造体を定義します。  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// ListPolicies gets up to maxPolicies policies.
func (wrapper PolicyWrapper) ListPolicies(ctx context.Context, maxPolicies int32) ([]types.Policy, error) {
	var policies []types.Policy
	result, err := wrapper.IamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPolicies),
	})
	if err != nil {
		log.Printf("Couldn't list policies. Here's why: %v\n", err)
	} else {
		policies = result.Policies
	}
	return policies, err
}



// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    []string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
}

// CreatePolicy creates a policy that grants a list of actions to the specified resource.
// 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 PolicyWrapper) CreatePolicy(ctx context.Context, policyName string, actions []string,
	resourceArn string) (*types.Policy, error) {
	var policy *types.Policy
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(resourceArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", resourceArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreatePolicy(ctx, &iam.CreatePolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
	})
	if err != nil {
		log.Printf("Couldn't create policy %v. Here's why: %v\n", policyName, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// GetPolicy gets data about a policy.
func (wrapper PolicyWrapper) GetPolicy(ctx context.Context, policyArn string) (*types.Policy, error) {
	var policy *types.Policy
	result, err := wrapper.IamClient.GetPolicy(ctx, &iam.GetPolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't get policy %v. Here's why: %v\n", policyArn, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}



// DeletePolicy deletes a policy.
func (wrapper PolicyWrapper) DeletePolicy(ctx context.Context, policyArn string) error {
	_, err := wrapper.IamClient.DeletePolicy(ctx, &iam.DeletePolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't delete policy %v. Here's why: %v\n", policyArn, err)
	}
	return err
}
```
ロールアクションをラップする構造体を定義します。  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// ListRoles gets up to maxRoles roles.
func (wrapper RoleWrapper) ListRoles(ctx context.Context, maxRoles int32) ([]types.Role, error) {
	var roles []types.Role
	result, err := wrapper.IamClient.ListRoles(ctx,
		&iam.ListRolesInput{MaxItems: aws.Int32(maxRoles)},
	)
	if err != nil {
		log.Printf("Couldn't list roles. Here's why: %v\n", err)
	} else {
		roles = result.Roles
	}
	return roles, err
}



// 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(ctx context.Context, 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(ctx, &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
}



// GetRole gets data about a role.
func (wrapper RoleWrapper) GetRole(ctx context.Context, roleName string) (*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.GetRole(ctx,
		&iam.GetRoleInput{RoleName: aws.String(roleName)})
	if err != nil {
		log.Printf("Couldn't get role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// CreateServiceLinkedRole creates a service-linked role that is owned by the specified service.
func (wrapper RoleWrapper) CreateServiceLinkedRole(ctx context.Context, serviceName string, description string) (
	*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.CreateServiceLinkedRole(ctx, &iam.CreateServiceLinkedRoleInput{
		AWSServiceName: aws.String(serviceName),
		Description:    aws.String(description),
	})
	if err != nil {
		log.Printf("Couldn't create service-linked role %v. Here's why: %v\n", serviceName, err)
	} else {
		role = result.Role
	}
	return role, err
}



// DeleteServiceLinkedRole deletes a service-linked role.
func (wrapper RoleWrapper) DeleteServiceLinkedRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteServiceLinkedRole(ctx, &iam.DeleteServiceLinkedRoleInput{
		RoleName: aws.String(roleName)},
	)
	if err != nil {
		log.Printf("Couldn't delete service-linked role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// AttachRolePolicy attaches a policy to a role.
func (wrapper RoleWrapper) AttachRolePolicy(ctx context.Context, policyArn string, roleName string) error {
	_, err := wrapper.IamClient.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't attach policy %v to role %v. Here's why: %v\n", policyArn, roleName, err)
	}
	return err
}



// ListAttachedRolePolicies lists the policies that are attached to the specified role.
func (wrapper RoleWrapper) ListAttachedRolePolicies(ctx context.Context, roleName string) ([]types.AttachedPolicy, error) {
	var policies []types.AttachedPolicy
	result, err := wrapper.IamClient.ListAttachedRolePolicies(ctx, &iam.ListAttachedRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list attached policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.AttachedPolicies
	}
	return policies, err
}



// DetachRolePolicy detaches a policy from a role.
func (wrapper RoleWrapper) DetachRolePolicy(ctx context.Context, roleName string, policyArn string) error {
	_, err := wrapper.IamClient.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't detach policy from role %v. Here's why: %v\n", roleName, err)
	}
	return err
}



// ListRolePolicies lists the inline policies for a role.
func (wrapper RoleWrapper) ListRolePolicies(ctx context.Context, roleName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListRolePolicies(ctx, &iam.ListRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteRole deletes a role. All attached policies must be detached before a
// role can be deleted.
func (wrapper RoleWrapper) DeleteRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteRole(ctx, &iam.DeleteRoleInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't delete role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
ユーザーアクションをラップする構造体を定義します。  

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUsers gets up to maxUsers number of users.
func (wrapper UserWrapper) ListUsers(ctx context.Context, maxUsers int32) ([]types.User, error) {
	var users []types.User
	result, err := wrapper.IamClient.ListUsers(ctx, &iam.ListUsersInput{
		MaxItems: aws.Int32(maxUsers),
	})
	if err != nil {
		log.Printf("Couldn't list users. Here's why: %v\n", err)
	} else {
		users = result.Users
	}
	return users, err
}



// GetUser gets data about a user.
func (wrapper UserWrapper) GetUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.GetUser(ctx, &iam.GetUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NoSuchEntityException:
				log.Printf("User %v does not exist.\n", userName)
				err = nil
			default:
				log.Printf("Couldn't get user %v. Here's why: %v\n", userName, err)
			}
		}
	} else {
		user = result.User
	}
	return user, err
}



// CreateUser creates a new user with the specified name.
func (wrapper UserWrapper) CreateUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.CreateUser(ctx, &iam.CreateUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
	} else {
		user = result.User
	}
	return user, err
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// 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 UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// ListUserPolicies lists the inline policies for the specified user.
func (wrapper UserWrapper) ListUserPolicies(ctx context.Context, userName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListUserPolicies(ctx, &iam.ListUserPoliciesInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for user %v. Here's why: %v\n", userName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}



// DeleteUserPolicy deletes an inline policy from a user.
func (wrapper UserWrapper) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
	_, err := wrapper.IamClient.DeleteUserPolicy(ctx, &iam.DeleteUserPolicyInput{
		PolicyName: aws.String(policyName),
		UserName:   aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete policy from user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// DeleteUser deletes a user.
func (wrapper UserWrapper) DeleteUser(ctx context.Context, userName string) error {
	_, err := wrapper.IamClient.DeleteUser(ctx, &iam.DeleteUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete user %v. Here's why: %v\n", userName, err)
	}
	return err
}



// CreateAccessKeyPair creates an access key for a user. The returned access key contains
// the ID and secret credentials needed to use the key.
func (wrapper UserWrapper) CreateAccessKeyPair(ctx context.Context, userName string) (*types.AccessKey, error) {
	var key *types.AccessKey
	result, err := wrapper.IamClient.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{
		UserName: aws.String(userName)})
	if err != nil {
		log.Printf("Couldn't create access key pair for user %v. Here's why: %v\n", userName, err)
	} else {
		key = result.AccessKey
	}
	return key, err
}



// DeleteAccessKey deletes an access key from a user.
func (wrapper UserWrapper) DeleteAccessKey(ctx context.Context, userName string, keyId string) error {
	_, err := wrapper.IamClient.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{
		AccessKeyId: aws.String(keyId),
		UserName:    aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete access key %v. Here's why: %v\n", keyId, err)
	}
	return err
}



// ListAccessKeys lists the access keys for the specified user.
func (wrapper UserWrapper) ListAccessKeys(ctx context.Context, userName string) ([]types.AccessKeyMetadata, error) {
	var keys []types.AccessKeyMetadata
	result, err := wrapper.IamClient.ListAccessKeys(ctx, &iam.ListAccessKeysInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list access keys for user %v. Here's why: %v\n", userName, err)
	} else {
		keys = result.AccessKeyMetadata
	}
	return keys, err
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.AttachRolePolicy)
  + [CreateAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateAccessKey)
  + [CreatePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreatePolicy)
  + [CreateRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)
  + [CreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateUser)
  + [DeleteAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteAccessKey)
  + [DeletePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeletePolicy)
  + [DeleteRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteRole)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUser)
  + [DeleteUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUserPolicy)
  + [DetachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DetachRolePolicy)
  + [PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_go_2_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// AttachRolePolicy attaches a policy to a role.
func (wrapper RoleWrapper) AttachRolePolicy(ctx context.Context, policyArn string, roleName string) error {
	_, err := wrapper.IamClient.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't attach policy %v to role %v. Here's why: %v\n", policyArn, roleName, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[AttachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.AttachRolePolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_go_2_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// CreateAccessKeyPair creates an access key for a user. The returned access key contains
// the ID and secret credentials needed to use the key.
func (wrapper UserWrapper) CreateAccessKeyPair(ctx context.Context, userName string) (*types.AccessKey, error) {
	var key *types.AccessKey
	result, err := wrapper.IamClient.CreateAccessKey(ctx, &iam.CreateAccessKeyInput{
		UserName: aws.String(userName)})
	if err != nil {
		log.Printf("Couldn't create access key pair for user %v. Here's why: %v\n", userName, err)
	} else {
		key = result.AccessKey
	}
	return key, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateAccessKey)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_go_2_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    []string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
}

// CreatePolicy creates a policy that grants a list of actions to the specified resource.
// 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 PolicyWrapper) CreatePolicy(ctx context.Context, policyName string, actions []string,
	resourceArn string) (*types.Policy, error) {
	var policy *types.Policy
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(resourceArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", resourceArn, err)
		return nil, err
	}
	result, err := wrapper.IamClient.CreatePolicy(ctx, &iam.CreatePolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
	})
	if err != nil {
		log.Printf("Couldn't create policy %v. Here's why: %v\n", policyName, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreatePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreatePolicy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_go_2_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// 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(ctx context.Context, 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(ctx, &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](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateRole)」を参照してください。**

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_go_2_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// CreateServiceLinkedRole creates a service-linked role that is owned by the specified service.
func (wrapper RoleWrapper) CreateServiceLinkedRole(ctx context.Context, serviceName string, description string) (
	*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.CreateServiceLinkedRole(ctx, &iam.CreateServiceLinkedRoleInput{
		AWSServiceName: aws.String(serviceName),
		Description:    aws.String(description),
	})
	if err != nil {
		log.Printf("Couldn't create service-linked role %v. Here's why: %v\n", serviceName, err)
	} else {
		role = result.Role
	}
	return role, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[CreateServiceLinkedRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateServiceLinkedRole)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_go_2_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// CreateUser creates a new user with the specified name.
func (wrapper UserWrapper) CreateUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.CreateUser(ctx, &iam.CreateUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
	} else {
		user = result.User
	}
	return user, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_go_2_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// DeleteAccessKey deletes an access key from a user.
func (wrapper UserWrapper) DeleteAccessKey(ctx context.Context, userName string, keyId string) error {
	_, err := wrapper.IamClient.DeleteAccessKey(ctx, &iam.DeleteAccessKeyInput{
		AccessKeyId: aws.String(keyId),
		UserName:    aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete access key %v. Here's why: %v\n", keyId, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteAccessKey](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteAccessKey)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_go_2_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// DeletePolicy deletes a policy.
func (wrapper PolicyWrapper) DeletePolicy(ctx context.Context, policyArn string) error {
	_, err := wrapper.IamClient.DeletePolicy(ctx, &iam.DeletePolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't delete policy %v. Here's why: %v\n", policyArn, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeletePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeletePolicy)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_go_2_topic"></a>

次のコード例は、`DeleteRole` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// DeleteRole deletes a role. All attached policies must be detached before a
// role can be deleted.
func (wrapper RoleWrapper) DeleteRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteRole(ctx, &iam.DeleteRoleInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't delete role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[DeleteRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteRole)」を参照してください。

### `DeleteServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_go_2_topic"></a>

次のコード例は、`DeleteServiceLinkedRole` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// DeleteServiceLinkedRole deletes a service-linked role.
func (wrapper RoleWrapper) DeleteServiceLinkedRole(ctx context.Context, roleName string) error {
	_, err := wrapper.IamClient.DeleteServiceLinkedRole(ctx, &iam.DeleteServiceLinkedRoleInput{
		RoleName: aws.String(roleName)},
	)
	if err != nil {
		log.Printf("Couldn't delete service-linked role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteServiceLinkedRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteServiceLinkedRole)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_go_2_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// DeleteUser deletes a user.
func (wrapper UserWrapper) DeleteUser(ctx context.Context, userName string) error {
	_, err := wrapper.IamClient.DeleteUser(ctx, &iam.DeleteUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUser)」を参照してください。

### `DeleteUserPolicy`
<a name="iam_DeleteUserPolicy_go_2_topic"></a>

次のコード例は、`DeleteUserPolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// DeleteUserPolicy deletes an inline policy from a user.
func (wrapper UserWrapper) DeleteUserPolicy(ctx context.Context, userName string, policyName string) error {
	_, err := wrapper.IamClient.DeleteUserPolicy(ctx, &iam.DeleteUserPolicyInput{
		PolicyName: aws.String(policyName),
		UserName:   aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't delete policy from user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DeleteUserPolicy)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_go_2_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// DetachRolePolicy detaches a policy from a role.
func (wrapper RoleWrapper) DetachRolePolicy(ctx context.Context, roleName string, policyArn string) error {
	_, err := wrapper.IamClient.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{
		PolicyArn: aws.String(policyArn),
		RoleName:  aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't detach policy from role %v. Here's why: %v\n", roleName, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DetachRolePolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.DetachRolePolicy)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_go_2_topic"></a>

次のコード例は、`GetAccountPasswordPolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// GetAccountPasswordPolicy gets the account password policy for the current account.
// If no policy has been set, a NoSuchEntityException is error is returned.
func (wrapper AccountWrapper) GetAccountPasswordPolicy(ctx context.Context) (*types.PasswordPolicy, error) {
	var pwPolicy *types.PasswordPolicy
	result, err := wrapper.IamClient.GetAccountPasswordPolicy(ctx,
		&iam.GetAccountPasswordPolicyInput{})
	if err != nil {
		log.Printf("Couldn't get account password policy. Here's why: %v\n", err)
	} else {
		pwPolicy = result.PasswordPolicy
	}
	return pwPolicy, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[GetAccountPasswordPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetAccountPasswordPolicy)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_go_2_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// GetPolicy gets data about a policy.
func (wrapper PolicyWrapper) GetPolicy(ctx context.Context, policyArn string) (*types.Policy, error) {
	var policy *types.Policy
	result, err := wrapper.IamClient.GetPolicy(ctx, &iam.GetPolicyInput{
		PolicyArn: aws.String(policyArn),
	})
	if err != nil {
		log.Printf("Couldn't get policy %v. Here's why: %v\n", policyArn, err)
	} else {
		policy = result.Policy
	}
	return policy, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[GetPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetPolicy)」を参照してください。

### `GetRole`
<a name="iam_GetRole_go_2_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// GetRole gets data about a role.
func (wrapper RoleWrapper) GetRole(ctx context.Context, roleName string) (*types.Role, error) {
	var role *types.Role
	result, err := wrapper.IamClient.GetRole(ctx,
		&iam.GetRoleInput{RoleName: aws.String(roleName)})
	if err != nil {
		log.Printf("Couldn't get role %v. Here's why: %v\n", roleName, err)
	} else {
		role = result.Role
	}
	return role, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[GetRole](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetRole)」を参照してください。

### `GetUser`
<a name="iam_GetUser_go_2_topic"></a>

次のコード例は、`GetUser` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// GetUser gets data about a user.
func (wrapper UserWrapper) GetUser(ctx context.Context, userName string) (*types.User, error) {
	var user *types.User
	result, err := wrapper.IamClient.GetUser(ctx, &iam.GetUserInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NoSuchEntityException:
				log.Printf("User %v does not exist.\n", userName)
				err = nil
			default:
				log.Printf("Couldn't get user %v. Here's why: %v\n", userName, err)
			}
		}
	} else {
		user = result.User
	}
	return user, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[GetUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.GetUser)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_go_2_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListAccessKeys lists the access keys for the specified user.
func (wrapper UserWrapper) ListAccessKeys(ctx context.Context, userName string) ([]types.AccessKeyMetadata, error) {
	var keys []types.AccessKeyMetadata
	result, err := wrapper.IamClient.ListAccessKeys(ctx, &iam.ListAccessKeysInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list access keys for user %v. Here's why: %v\n", userName, err)
	} else {
		keys = result.AccessKeyMetadata
	}
	return keys, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListAccessKeys](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListAccessKeys)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_go_2_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// ListAttachedRolePolicies lists the policies that are attached to the specified role.
func (wrapper RoleWrapper) ListAttachedRolePolicies(ctx context.Context, roleName string) ([]types.AttachedPolicy, error) {
	var policies []types.AttachedPolicy
	result, err := wrapper.IamClient.ListAttachedRolePolicies(ctx, &iam.ListAttachedRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list attached policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.AttachedPolicies
	}
	return policies, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ListAttachedRolePolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListAttachedRolePolicies)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_go_2_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// GroupWrapper encapsulates AWS Identity and Access Management (IAM) group actions
// used in the examples.
// It contains an IAM service client that is used to perform group actions.
type GroupWrapper struct {
	IamClient *iam.Client
}



// ListGroups lists up to maxGroups number of groups.
func (wrapper GroupWrapper) ListGroups(ctx context.Context, maxGroups int32) ([]types.Group, error) {
	var groups []types.Group
	result, err := wrapper.IamClient.ListGroups(ctx, &iam.ListGroupsInput{
		MaxItems: aws.Int32(maxGroups),
	})
	if err != nil {
		log.Printf("Couldn't list groups. Here's why: %v\n", err)
	} else {
		groups = result.Groups
	}
	return groups, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ListGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListGroups)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_go_2_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions
// used in the examples.
// It contains an IAM service client that is used to perform policy actions.
type PolicyWrapper struct {
	IamClient *iam.Client
}



// ListPolicies gets up to maxPolicies policies.
func (wrapper PolicyWrapper) ListPolicies(ctx context.Context, maxPolicies int32) ([]types.Policy, error) {
	var policies []types.Policy
	result, err := wrapper.IamClient.ListPolicies(ctx, &iam.ListPoliciesInput{
		MaxItems: aws.Int32(maxPolicies),
	})
	if err != nil {
		log.Printf("Couldn't list policies. Here's why: %v\n", err)
	} else {
		policies = result.Policies
	}
	return policies, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListPolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListPolicies)」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_go_2_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// ListRolePolicies lists the inline policies for a role.
func (wrapper RoleWrapper) ListRolePolicies(ctx context.Context, roleName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListRolePolicies(ctx, &iam.ListRolePoliciesInput{
		RoleName: aws.String(roleName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for role %v. Here's why: %v\n", roleName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ListRolePolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListRolePolicies)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_go_2_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

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



// ListRoles gets up to maxRoles roles.
func (wrapper RoleWrapper) ListRoles(ctx context.Context, maxRoles int32) ([]types.Role, error) {
	var roles []types.Role
	result, err := wrapper.IamClient.ListRoles(ctx,
		&iam.ListRolesInput{MaxItems: aws.Int32(maxRoles)},
	)
	if err != nil {
		log.Printf("Couldn't list roles. Here's why: %v\n", err)
	} else {
		roles = result.Roles
	}
	return roles, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ListRoles](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListRoles)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_go_2_topic"></a>

次のコード例は、`ListSAMLProviders` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
)

// AccountWrapper encapsulates AWS Identity and Access Management (IAM) account actions
// used in the examples.
// It contains an IAM service client that is used to perform account actions.
type AccountWrapper struct {
	IamClient *iam.Client
}



// ListSAMLProviders gets the SAML providers for the account.
func (wrapper AccountWrapper) ListSAMLProviders(ctx context.Context) ([]types.SAMLProviderListEntry, error) {
	var providers []types.SAMLProviderListEntry
	result, err := wrapper.IamClient.ListSAMLProviders(ctx, &iam.ListSAMLProvidersInput{})
	if err != nil {
		log.Printf("Couldn't list SAML providers. Here's why: %v\n", err)
	} else {
		providers = result.SAMLProviderList
	}
	return providers, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ListSAMLProviders](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListSAMLProviders)」を参照してください。

### `ListUserPolicies`
<a name="iam_ListUserPolicies_go_2_topic"></a>

次のコード例は、`ListUserPolicies` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUserPolicies lists the inline policies for the specified user.
func (wrapper UserWrapper) ListUserPolicies(ctx context.Context, userName string) ([]string, error) {
	var policies []string
	result, err := wrapper.IamClient.ListUserPolicies(ctx, &iam.ListUserPoliciesInput{
		UserName: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't list policies for user %v. Here's why: %v\n", userName, err)
	} else {
		policies = result.PolicyNames
	}
	return policies, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ListUserPolicies](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListUserPolicies)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_go_2_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// ListUsers gets up to maxUsers number of users.
func (wrapper UserWrapper) ListUsers(ctx context.Context, maxUsers int32) ([]types.User, error) {
	var users []types.User
	result, err := wrapper.IamClient.ListUsers(ctx, &iam.ListUsersInput{
		MaxItems: aws.Int32(maxUsers),
	})
	if err != nil {
		log.Printf("Couldn't list users. Here's why: %v\n", err)
	} else {
		users = result.Users
	}
	return users, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListUsers](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.ListUsers)」を参照してください。

### `PutUserPolicy`
<a name="iam_PutUserPolicy_go_2_topic"></a>

次のコード例は、`PutUserPolicy` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/iam#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	"github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/smithy-go"
)

// UserWrapper encapsulates user actions used in the examples.
// It contains an IAM service client that is used to perform user actions.
type UserWrapper struct {
	IamClient *iam.Client
}



// CreateUserPolicy adds an inline policy to a user. This example creates a policy that
// grants a list of actions on a specified role.
// 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 UserWrapper) CreateUserPolicy(ctx context.Context, userName string, policyName string, actions []string,
	roleArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:   "Allow",
			Action:   actions,
			Resource: aws.String(roleArn),
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document for %v. Here's why: %v\n", roleArn, err)
		return err
	}
	_, err = wrapper.IamClient.PutUserPolicy(ctx, &iam.PutUserPolicyInput{
		PolicyDocument: aws.String(string(policyBytes)),
		PolicyName:     aws.String(policyName),
		UserName:       aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't create policy for user %v. Here's why: %v\n", userName, err)
	}
	return err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[PutUserPolicy](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/iam#Client.PutUserPolicy)」を参照してください。

# SDK for Go V2 を使用した Kinesis の例
<a name="go_2_kinesis_code_examples"></a>

次のコード例は、Kinesis で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_go_2_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"log"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, kinesisEvent events.KinesisEvent) error {
	if len(kinesisEvent.Records) == 0 {
		log.Printf("empty Kinesis event received")
		return nil
	}

	for _, record := range kinesisEvent.Records {
		log.Printf("processed Kinesis event with EventId: %v", record.EventID)
		recordDataBytes := record.Kinesis.Data
		recordDataText := string(recordDataBytes)
		log.Printf("record data: %v", recordDataText)
		// TODO: Do interesting work based on the new data
	}
	log.Printf("successfully processed %v records", len(kinesisEvent.Records))
	return nil
}

func main() {
	lambda.Start(handler)
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_go_2_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"fmt"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, kinesisEvent events.KinesisEvent) (map[string]interface{}, error) {
	batchItemFailures := []map[string]interface{}{}

	for _, record := range kinesisEvent.Records {
		curRecordSequenceNumber := ""

		// Process your record
		if /* Your record processing condition here */ {
			curRecordSequenceNumber = record.Kinesis.SequenceNumber
		}

		// Add a condition to check if the record processing failed
		if curRecordSequenceNumber != "" {
			batchItemFailures = append(batchItemFailures, map[string]interface{}{"itemIdentifier": curRecordSequenceNumber})
		}
	}

	kinesisBatchResponse := map[string]interface{}{
		"batchItemFailures": batchItemFailures,
	}
	return kinesisBatchResponse, nil
}

func main() {
	lambda.Start(handler)
}
```

# SDK for Go V2 を使用した Lambda の例
<a name="go_2_lambda_code_examples"></a>

次のコード例は、Lambda で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームによって作成され、維持されている例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## はじめに
<a name="get_started"></a>

### Hello Lambda
<a name="lambda_Hello_go_2_topic"></a>

次のコード例は、Lambda の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
)

// main uses the AWS SDK for Go (v2) to create an AWS Lambda client and list up to 10
// functions in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	lambdaClient := lambda.NewFromConfig(sdkConfig)

	maxItems := 10
	fmt.Printf("Let's list up to %v functions for your account.\n", maxItems)
	result, err := lambdaClient.ListFunctions(ctx, &lambda.ListFunctionsInput{
		MaxItems: aws.Int32(int32(maxItems)),
	})
	if err != nil {
		fmt.Printf("Couldn't list functions for your account. Here's why: %v\n", err)
		return
	}
	if len(result.Functions) == 0 {
		fmt.Println("You don't have any functions!")
	} else {
		for _, function := range result.Functions {
			fmt.Printf("\t%v\n", *function.FunctionName)
		}
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListFunctions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.ListFunctions)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。
Lambda 関数の開始方法を示すインタラクティブなシナリオを作成します。  

```
import (
	"archive/zip"
	"bytes"
	"context"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/iam"
	iamtypes "github.com/aws/aws-sdk-go-v2/service/iam/types"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/lambda/actions"
)

// GetStartedFunctionsScenario shows you how to use AWS Lambda to perform the following
// actions:
//
//  1. Create an AWS Identity and Access Management (IAM) role and Lambda function, then upload handler code.
//  2. Invoke the function with a single parameter and get results.
//  3. Update the function code and configure with an environment variable.
//  4. Invoke the function with new parameters and get results. Display the returned execution log.
//  5. List the functions for your account, then clean up resources.
type GetStartedFunctionsScenario struct {
	sdkConfig       aws.Config
	functionWrapper actions.FunctionWrapper
	questioner      demotools.IQuestioner
	helper          IScenarioHelper
	isTestRun       bool
}

// NewGetStartedFunctionsScenario constructs a GetStartedFunctionsScenario instance from a configuration.
// It uses the specified config to get a Lambda client and create wrappers for the actions
// used in the scenario.
func NewGetStartedFunctionsScenario(sdkConfig aws.Config, questioner demotools.IQuestioner,
	helper IScenarioHelper) GetStartedFunctionsScenario {
	lambdaClient := lambda.NewFromConfig(sdkConfig)
	return GetStartedFunctionsScenario{
		sdkConfig:       sdkConfig,
		functionWrapper: actions.FunctionWrapper{LambdaClient: lambdaClient},
		questioner:      questioner,
		helper:          helper,
	}
}

// Run runs the interactive scenario.
func (scenario GetStartedFunctionsScenario) Run(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong with the demo.\n")
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the AWS Lambda get started with functions demo.")
	log.Println(strings.Repeat("-", 88))

	role := scenario.GetOrCreateRole(ctx)
	funcName := scenario.CreateFunction(ctx, role)
	scenario.InvokeIncrement(ctx, funcName)
	scenario.UpdateFunction(ctx, funcName)
	scenario.InvokeCalculator(ctx, funcName)
	scenario.ListFunctions(ctx)
	scenario.Cleanup(ctx, role, funcName)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}

// GetOrCreateRole checks whether the specified role exists and returns it if it does.
// Otherwise, a role is created that specifies Lambda as a trusted principal.
// The AWSLambdaBasicExecutionRole managed policy is attached to the role and the role
// is returned.
func (scenario GetStartedFunctionsScenario) GetOrCreateRole(ctx context.Context) *iamtypes.Role {
	var role *iamtypes.Role
	iamClient := iam.NewFromConfig(scenario.sdkConfig)
	log.Println("First, we need an IAM role that Lambda can assume.")
	roleName := scenario.questioner.Ask("Enter a name for the role:", demotools.NotEmpty{})
	getOutput, err := iamClient.GetRole(ctx, &iam.GetRoleInput{
		RoleName: aws.String(roleName)})
	if err != nil {
		var noSuch *iamtypes.NoSuchEntityException
		if errors.As(err, &noSuch) {
			log.Printf("Role %v doesn't exist. Creating it....\n", roleName)
		} else {
			log.Panicf("Couldn't check whether role %v exists. Here's why: %v\n",
				roleName, err)
		}
	} else {
		role = getOutput.Role
		log.Printf("Found role %v.\n", *role.RoleName)
	}
	if role == nil {
		trustPolicy := PolicyDocument{
			Version: "2012-10-17",
			Statement: []PolicyStatement{{
				Effect:    "Allow",
				Principal: map[string]string{"Service": "lambda.amazonaws.com"},
				Action:    []string{"sts:AssumeRole"},
			}},
		}
		policyArn := "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
		createOutput, err := iamClient.CreateRole(ctx, &iam.CreateRoleInput{
			AssumeRolePolicyDocument: aws.String(trustPolicy.String()),
			RoleName:                 aws.String(roleName),
		})
		if err != nil {
			log.Panicf("Couldn't create role %v. Here's why: %v\n", roleName, err)
		}
		role = createOutput.Role
		_, err = iamClient.AttachRolePolicy(ctx, &iam.AttachRolePolicyInput{
			PolicyArn: aws.String(policyArn),
			RoleName:  aws.String(roleName),
		})
		if err != nil {
			log.Panicf("Couldn't attach a policy to role %v. Here's why: %v\n", roleName, err)
		}
		log.Printf("Created role %v.\n", *role.RoleName)
		log.Println("Let's give AWS a few seconds to propagate resources...")
		scenario.helper.Pause(10)
	}
	log.Println(strings.Repeat("-", 88))
	return role
}

// CreateFunction creates a Lambda function and uploads a handler written in Python.
// The code for the Python handler is packaged as a []byte in .zip format.
func (scenario GetStartedFunctionsScenario) CreateFunction(ctx context.Context, role *iamtypes.Role) string {
	log.Println("Let's create a function that increments a number.\n" +
		"The function uses the 'lambda_handler_basic.py' script found in the \n" +
		"'handlers' directory of this project.")
	funcName := scenario.questioner.Ask("Enter a name for the Lambda function:", demotools.NotEmpty{})
	zipPackage := scenario.helper.CreateDeploymentPackage("lambda_handler_basic.py", fmt.Sprintf("%v.py", funcName))
	log.Printf("Creating function %v and waiting for it to be ready.", funcName)
	funcState := scenario.functionWrapper.CreateFunction(ctx, funcName, fmt.Sprintf("%v.lambda_handler", funcName),
		role.Arn, zipPackage)
	log.Printf("Your function is %v.", funcState)
	log.Println(strings.Repeat("-", 88))
	return funcName
}

// InvokeIncrement invokes a Lambda function that increments a number. The function
// parameters are contained in a Go struct that is used to serialize the parameters to
// a JSON payload that is passed to the function.
// The result payload is deserialized into a Go struct that contains an int value.
func (scenario GetStartedFunctionsScenario) InvokeIncrement(ctx context.Context, funcName string) {
	parameters := actions.IncrementParameters{Action: "increment"}
	log.Println("Let's invoke our function. This function increments a number.")
	parameters.Number = scenario.questioner.AskInt("Enter a number to increment:", demotools.NotEmpty{})
	log.Printf("Invoking %v with %v...\n", funcName, parameters.Number)
	invokeOutput := scenario.functionWrapper.Invoke(ctx, funcName, parameters, false)
	var payload actions.LambdaResultInt
	err := json.Unmarshal(invokeOutput.Payload, &payload)
	if err != nil {
		log.Panicf("Couldn't unmarshal payload from invoking %v. Here's why: %v\n",
			funcName, err)
	}
	log.Printf("Invoking %v with %v returned %v.\n", funcName, parameters.Number, payload)
	log.Println(strings.Repeat("-", 88))
}

// UpdateFunction updates the code for a Lambda function by uploading a simple arithmetic
// calculator written in Python. The code for the Python handler is packaged as a
// []byte in .zip format.
// After the code is updated, the configuration is also updated with a new log
// level that instructs the handler to log additional information.
func (scenario GetStartedFunctionsScenario) UpdateFunction(ctx context.Context, funcName string) {
	log.Println("Let's update the function to an arithmetic calculator.\n" +
		"The function uses the 'lambda_handler_calculator.py' script found in the \n" +
		"'handlers' directory of this project.")
	scenario.questioner.Ask("Press Enter when you're ready.")
	log.Println("Creating deployment package...")
	zipPackage := scenario.helper.CreateDeploymentPackage("lambda_handler_calculator.py",
		fmt.Sprintf("%v.py", funcName))
	log.Println("...and updating the Lambda function and waiting for it to be ready.")
	funcState := scenario.functionWrapper.UpdateFunctionCode(ctx, funcName, zipPackage)
	log.Printf("Updated function %v. Its current state is %v.", funcName, funcState)
	log.Println("This function uses an environment variable to control logging level.")
	log.Println("Let's set it to DEBUG to get the most logging.")
	scenario.functionWrapper.UpdateFunctionConfiguration(ctx, funcName,
		map[string]string{"LOG_LEVEL": "DEBUG"})
	log.Println(strings.Repeat("-", 88))
}

// InvokeCalculator invokes the Lambda calculator function. The parameters are stored in a
// Go struct that is used to serialize the parameters to a JSON payload. That payload is then passed
// to the function.
// The result payload is deserialized to a Go struct that stores the result as either an
// int or float32, depending on the kind of operation that was specified.
func (scenario GetStartedFunctionsScenario) InvokeCalculator(ctx context.Context, funcName string) {
	wantInvoke := true
	choices := []string{"plus", "minus", "times", "divided-by"}
	for wantInvoke {
		choice := scenario.questioner.AskChoice("Select an arithmetic operation:\n", choices)
		x := scenario.questioner.AskInt("Enter a value for x:", demotools.NotEmpty{})
		y := scenario.questioner.AskInt("Enter a value for y:", demotools.NotEmpty{})
		log.Printf("Invoking %v %v %v...", x, choices[choice], y)
		calcParameters := actions.CalculatorParameters{
			Action: choices[choice],
			X:      x,
			Y:      y,
		}
		invokeOutput := scenario.functionWrapper.Invoke(ctx, funcName, calcParameters, true)
		var payload any
		if choice == 3 { // divide-by results in a float.
			payload = actions.LambdaResultFloat{}
		} else {
			payload = actions.LambdaResultInt{}
		}
		err := json.Unmarshal(invokeOutput.Payload, &payload)
		if err != nil {
			log.Panicf("Couldn't unmarshal payload from invoking %v. Here's why: %v\n",
				funcName, err)
		}
		log.Printf("Invoking %v with %v %v %v returned %v.\n", funcName,
			calcParameters.X, calcParameters.Action, calcParameters.Y, payload)
		scenario.questioner.Ask("Press Enter to see the logs from the call.")
		logRes, err := base64.StdEncoding.DecodeString(*invokeOutput.LogResult)
		if err != nil {
			log.Panicf("Couldn't decode log result. Here's why: %v\n", err)
		}
		log.Println(string(logRes))
		wantInvoke = scenario.questioner.AskBool("Do you want to calculate again? (y/n)", "y")
	}
	log.Println(strings.Repeat("-", 88))
}

// ListFunctions lists up to the specified number of functions for your account.
func (scenario GetStartedFunctionsScenario) ListFunctions(ctx context.Context) {
	count := scenario.questioner.AskInt(
		"Let's list functions for your account. How many do you want to see?", demotools.NotEmpty{})
	functions := scenario.functionWrapper.ListFunctions(ctx, count)
	log.Printf("Found %v functions:", len(functions))
	for _, function := range functions {
		log.Printf("\t%v", *function.FunctionName)
	}
	log.Println(strings.Repeat("-", 88))
}

// Cleanup removes the IAM and Lambda resources created by the example.
func (scenario GetStartedFunctionsScenario) Cleanup(ctx context.Context, role *iamtypes.Role, funcName string) {
	if scenario.questioner.AskBool("Do you want to clean up resources created for this example? (y/n)",
		"y") {
		iamClient := iam.NewFromConfig(scenario.sdkConfig)
		policiesOutput, err := iamClient.ListAttachedRolePolicies(ctx,
			&iam.ListAttachedRolePoliciesInput{RoleName: role.RoleName})
		if err != nil {
			log.Panicf("Couldn't get policies attached to role %v. Here's why: %v\n",
				*role.RoleName, err)
		}
		for _, policy := range policiesOutput.AttachedPolicies {
			_, err = iamClient.DetachRolePolicy(ctx, &iam.DetachRolePolicyInput{
				PolicyArn: policy.PolicyArn, RoleName: role.RoleName,
			})
			if err != nil {
				log.Panicf("Couldn't detach policy %v from role %v. Here's why: %v\n",
					*policy.PolicyArn, *role.RoleName, err)
			}
		}
		_, err = iamClient.DeleteRole(ctx, &iam.DeleteRoleInput{RoleName: role.RoleName})
		if err != nil {
			log.Panicf("Couldn't delete role %v. Here's why: %v\n", *role.RoleName, err)
		}
		log.Printf("Deleted role %v.\n", *role.RoleName)

		scenario.functionWrapper.DeleteFunction(ctx, funcName)
		log.Printf("Deleted function %v.\n", funcName)
	} else {
		log.Println("Okay. Don't forget to delete the resources when you're done with them.")
	}
}

// IScenarioHelper abstracts I/O and wait functions from a scenario so that they
// can be mocked for unit testing.
type IScenarioHelper interface {
	Pause(secs int)
	CreateDeploymentPackage(sourceFile string, destinationFile string) *bytes.Buffer
}

// ScenarioHelper lets the caller specify the path to Lambda handler functions.
type ScenarioHelper struct {
	HandlerPath string
}

// Pause waits for the specified number of seconds.
func (helper *ScenarioHelper) Pause(secs int) {
	time.Sleep(time.Duration(secs) * time.Second)
}

// CreateDeploymentPackage creates an AWS Lambda deployment package from a source file. The
// deployment package is stored in .zip format in a bytes.Buffer. The buffer can be
// used to pass a []byte to Lambda when creating the function.
// The specified destinationFile is the name to give the file when it's deployed to Lambda.
func (helper *ScenarioHelper) CreateDeploymentPackage(sourceFile string, destinationFile string) *bytes.Buffer {
	var err error
	buffer := &bytes.Buffer{}
	writer := zip.NewWriter(buffer)
	zFile, err := writer.Create(destinationFile)
	if err != nil {
		log.Panicf("Couldn't create destination archive %v. Here's why: %v\n", destinationFile, err)
	}
	sourceBody, err := os.ReadFile(fmt.Sprintf("%v/%v", helper.HandlerPath, sourceFile))
	if err != nil {
		log.Panicf("Couldn't read handler source file %v. Here's why: %v\n",
			sourceFile, err)
	} else {
		_, err = zFile.Write(sourceBody)
		if err != nil {
			log.Panicf("Couldn't write handler %v to zip archive. Here's why: %v\n",
				sourceFile, err)
		}
	}
	err = writer.Close()
	if err != nil {
		log.Panicf("Couldn't close zip writer. Here's why: %v\n", err)
	}
	return buffer
}
```
個別の Lambda アクションをラップする構造体を作成します。  

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}


// GetFunction gets data about the Lambda function specified by functionName.
func (wrapper FunctionWrapper) GetFunction(ctx context.Context, functionName string) types.State {
	var state types.State
	funcOutput, err := wrapper.LambdaClient.GetFunction(ctx, &lambda.GetFunctionInput{
		FunctionName: aws.String(functionName),
	})
	if err != nil {
		log.Panicf("Couldn't get function %v. Here's why: %v\n", functionName, err)
	} else {
		state = funcOutput.Configuration.State
	}
	return state
}



// CreateFunction creates a new Lambda function from code contained in the zipPackage
// buffer. The specified handlerName must match the name of the file and function
// contained in the uploaded code. The role specified by iamRoleArn is assumed by
// Lambda and grants specific permissions.
// When the function already exists, types.StateActive is returned.
// When the function is created, a lambda.FunctionActiveV2Waiter is used to wait until the
// function is active.
func (wrapper FunctionWrapper) CreateFunction(ctx context.Context, functionName string, handlerName string,
	iamRoleArn *string, zipPackage *bytes.Buffer) types.State {
	var state types.State
	_, err := wrapper.LambdaClient.CreateFunction(ctx, &lambda.CreateFunctionInput{
		Code:         &types.FunctionCode{ZipFile: zipPackage.Bytes()},
		FunctionName: aws.String(functionName),
		Role:         iamRoleArn,
		Handler:      aws.String(handlerName),
		Publish:      true,
		Runtime:      types.RuntimePython39,
	})
	if err != nil {
		var resConflict *types.ResourceConflictException
		if errors.As(err, &resConflict) {
			log.Printf("Function %v already exists.\n", functionName)
			state = types.StateActive
		} else {
			log.Panicf("Couldn't create function %v. Here's why: %v\n", functionName, err)
		}
	} else {
		waiter := lambda.NewFunctionActiveV2Waiter(wrapper.LambdaClient)
		funcOutput, err := waiter.WaitForOutput(ctx, &lambda.GetFunctionInput{
			FunctionName: aws.String(functionName)}, 1*time.Minute)
		if err != nil {
			log.Panicf("Couldn't wait for function %v to be active. Here's why: %v\n", functionName, err)
		} else {
			state = funcOutput.Configuration.State
		}
	}
	return state
}



// UpdateFunctionCode updates the code for the Lambda function specified by functionName.
// The existing code for the Lambda function is entirely replaced by the code in the
// zipPackage buffer. After the update action is called, a lambda.FunctionUpdatedV2Waiter
// is used to wait until the update is successful.
func (wrapper FunctionWrapper) UpdateFunctionCode(ctx context.Context, functionName string, zipPackage *bytes.Buffer) types.State {
	var state types.State
	_, err := wrapper.LambdaClient.UpdateFunctionCode(ctx, &lambda.UpdateFunctionCodeInput{
		FunctionName: aws.String(functionName), ZipFile: zipPackage.Bytes(),
	})
	if err != nil {
		log.Panicf("Couldn't update code for function %v. Here's why: %v\n", functionName, err)
	} else {
		waiter := lambda.NewFunctionUpdatedV2Waiter(wrapper.LambdaClient)
		funcOutput, err := waiter.WaitForOutput(ctx, &lambda.GetFunctionInput{
			FunctionName: aws.String(functionName)}, 1*time.Minute)
		if err != nil {
			log.Panicf("Couldn't wait for function %v to be active. Here's why: %v\n", functionName, err)
		} else {
			state = funcOutput.Configuration.State
		}
	}
	return state
}



// UpdateFunctionConfiguration updates a map of environment variables configured for
// the Lambda function specified by functionName.
func (wrapper FunctionWrapper) UpdateFunctionConfiguration(ctx context.Context, functionName string, envVars map[string]string) {
	_, err := wrapper.LambdaClient.UpdateFunctionConfiguration(ctx, &lambda.UpdateFunctionConfigurationInput{
		FunctionName: aws.String(functionName),
		Environment:  &types.Environment{Variables: envVars},
	})
	if err != nil {
		log.Panicf("Couldn't update configuration for %v. Here's why: %v", functionName, err)
	}
}



// ListFunctions lists up to maxItems functions for the account. This function uses a
// lambda.ListFunctionsPaginator to paginate the results.
func (wrapper FunctionWrapper) ListFunctions(ctx context.Context, maxItems int) []types.FunctionConfiguration {
	var functions []types.FunctionConfiguration
	paginator := lambda.NewListFunctionsPaginator(wrapper.LambdaClient, &lambda.ListFunctionsInput{
		MaxItems: aws.Int32(int32(maxItems)),
	})
	for paginator.HasMorePages() && len(functions) < maxItems {
		pageOutput, err := paginator.NextPage(ctx)
		if err != nil {
			log.Panicf("Couldn't list functions for your account. Here's why: %v\n", err)
		}
		functions = append(functions, pageOutput.Functions...)
	}
	return functions
}



// DeleteFunction deletes the Lambda function specified by functionName.
func (wrapper FunctionWrapper) DeleteFunction(ctx context.Context, functionName string) {
	_, err := wrapper.LambdaClient.DeleteFunction(ctx, &lambda.DeleteFunctionInput{
		FunctionName: aws.String(functionName),
	})
	if err != nil {
		log.Panicf("Couldn't delete function %v. Here's why: %v\n", functionName, err)
	}
}



// Invoke invokes the Lambda function specified by functionName, passing the parameters
// as a JSON payload. When getLog is true, types.LogTypeTail is specified, which tells
// Lambda to include the last few log lines in the returned result.
func (wrapper FunctionWrapper) Invoke(ctx context.Context, functionName string, parameters any, getLog bool) *lambda.InvokeOutput {
	logType := types.LogTypeNone
	if getLog {
		logType = types.LogTypeTail
	}
	payload, err := json.Marshal(parameters)
	if err != nil {
		log.Panicf("Couldn't marshal parameters to JSON. Here's why %v\n", err)
	}
	invokeOutput, err := wrapper.LambdaClient.Invoke(ctx, &lambda.InvokeInput{
		FunctionName: aws.String(functionName),
		LogType:      logType,
		Payload:      payload,
	})
	if err != nil {
		log.Panicf("Couldn't invoke function %v. Here's why: %v\n", functionName, err)
	}
	return invokeOutput
}



// IncrementParameters is used to serialize parameters to the increment Lambda handler.
type IncrementParameters struct {
	Action string `json:"action"`
	Number int    `json:"number"`
}

// CalculatorParameters is used to serialize parameters to the calculator Lambda handler.
type CalculatorParameters struct {
	Action string `json:"action"`
	X      int    `json:"x"`
	Y      int    `json:"y"`
}

// LambdaResultInt is used to deserialize an int result from a Lambda handler.
type LambdaResultInt struct {
	Result int `json:"result"`
}

// LambdaResultFloat is used to deserialize a float32 result from a Lambda handler.
type LambdaResultFloat struct {
	Result float32 `json:"result"`
}
```
数値をインクリメントする Lambda ハンドラーを定義します。  

```
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    """
    Accepts an action and a single number, performs the specified action on the number,
    and returns the result. The only allowable action is 'increment'.

    :param event: The event dict that contains the parameters sent when the function
                  is invoked.
    :param context: The context in which the function is called.
    :return: The result of the action.
    """
    result = None
    action = event.get("action")
    if action == "increment":
        result = event.get("number", 0) + 1
        logger.info("Calculated result of %s", result)
    else:
        logger.error("%s is not a valid action.", action)

    response = {"result": result}
    return response
```
算術演算を実行する 2 番目の Lambda ハンドラーを定義します。  

```
import logging
import os


logger = logging.getLogger()

# Define a list of Python lambda functions that are called by this AWS Lambda function.
ACTIONS = {
    "plus": lambda x, y: x + y,
    "minus": lambda x, y: x - y,
    "times": lambda x, y: x * y,
    "divided-by": lambda x, y: x / y,
}


def lambda_handler(event, context):
    """
    Accepts an action and two numbers, performs the specified action on the numbers,
    and returns the result.

    :param event: The event dict that contains the parameters sent when the function
                  is invoked.
    :param context: The context in which the function is called.
    :return: The result of the specified action.
    """
    # Set the log level based on a variable configured in the Lambda environment.
    logger.setLevel(os.environ.get("LOG_LEVEL", logging.INFO))
    logger.debug("Event: %s", event)

    action = event.get("action")
    func = ACTIONS.get(action)
    x = event.get("x")
    y = event.get("y")
    result = None
    try:
        if func is not None and x is not None and y is not None:
            result = func(x, y)
            logger.info("%s %s %s is %s", x, action, y, result)
        else:
            logger.error("I can't calculate %s %s %s.", x, action, y)
    except ZeroDivisionError:
        logger.warning("I can't divide %s by 0!", x)

    response = {"result": result}
    return response
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.CreateFunction)
  + [DeleteFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.DeleteFunction)
  + [GetFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.GetFunction)
  + [Invoke](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.Invoke)
  + [ListFunctions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.ListFunctions)
  + [UpdateFunctionCode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.UpdateFunctionCode)
  + [UpdateFunctionConfiguration](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.UpdateFunctionConfiguration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_go_2_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}



// CreateFunction creates a new Lambda function from code contained in the zipPackage
// buffer. The specified handlerName must match the name of the file and function
// contained in the uploaded code. The role specified by iamRoleArn is assumed by
// Lambda and grants specific permissions.
// When the function already exists, types.StateActive is returned.
// When the function is created, a lambda.FunctionActiveV2Waiter is used to wait until the
// function is active.
func (wrapper FunctionWrapper) CreateFunction(ctx context.Context, functionName string, handlerName string,
	iamRoleArn *string, zipPackage *bytes.Buffer) types.State {
	var state types.State
	_, err := wrapper.LambdaClient.CreateFunction(ctx, &lambda.CreateFunctionInput{
		Code:         &types.FunctionCode{ZipFile: zipPackage.Bytes()},
		FunctionName: aws.String(functionName),
		Role:         iamRoleArn,
		Handler:      aws.String(handlerName),
		Publish:      true,
		Runtime:      types.RuntimePython39,
	})
	if err != nil {
		var resConflict *types.ResourceConflictException
		if errors.As(err, &resConflict) {
			log.Printf("Function %v already exists.\n", functionName)
			state = types.StateActive
		} else {
			log.Panicf("Couldn't create function %v. Here's why: %v\n", functionName, err)
		}
	} else {
		waiter := lambda.NewFunctionActiveV2Waiter(wrapper.LambdaClient)
		funcOutput, err := waiter.WaitForOutput(ctx, &lambda.GetFunctionInput{
			FunctionName: aws.String(functionName)}, 1*time.Minute)
		if err != nil {
			log.Panicf("Couldn't wait for function %v to be active. Here's why: %v\n", functionName, err)
		} else {
			state = funcOutput.Configuration.State
		}
	}
	return state
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの「[CreateFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.CreateFunction)」を参照してください。**

### `DeleteFunction`
<a name="lambda_DeleteFunction_go_2_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}



// DeleteFunction deletes the Lambda function specified by functionName.
func (wrapper FunctionWrapper) DeleteFunction(ctx context.Context, functionName string) {
	_, err := wrapper.LambdaClient.DeleteFunction(ctx, &lambda.DeleteFunctionInput{
		FunctionName: aws.String(functionName),
	})
	if err != nil {
		log.Panicf("Couldn't delete function %v. Here's why: %v\n", functionName, err)
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.DeleteFunction)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_go_2_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}



// GetFunction gets data about the Lambda function specified by functionName.
func (wrapper FunctionWrapper) GetFunction(ctx context.Context, functionName string) types.State {
	var state types.State
	funcOutput, err := wrapper.LambdaClient.GetFunction(ctx, &lambda.GetFunctionInput{
		FunctionName: aws.String(functionName),
	})
	if err != nil {
		log.Panicf("Couldn't get function %v. Here's why: %v\n", functionName, err)
	} else {
		state = funcOutput.Configuration.State
	}
	return state
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[GetFunction](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.GetFunction)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_go_2_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}



// Invoke invokes the Lambda function specified by functionName, passing the parameters
// as a JSON payload. When getLog is true, types.LogTypeTail is specified, which tells
// Lambda to include the last few log lines in the returned result.
func (wrapper FunctionWrapper) Invoke(ctx context.Context, functionName string, parameters any, getLog bool) *lambda.InvokeOutput {
	logType := types.LogTypeNone
	if getLog {
		logType = types.LogTypeTail
	}
	payload, err := json.Marshal(parameters)
	if err != nil {
		log.Panicf("Couldn't marshal parameters to JSON. Here's why %v\n", err)
	}
	invokeOutput, err := wrapper.LambdaClient.Invoke(ctx, &lambda.InvokeInput{
		FunctionName: aws.String(functionName),
		LogType:      logType,
		Payload:      payload,
	})
	if err != nil {
		log.Panicf("Couldn't invoke function %v. Here's why: %v\n", functionName, err)
	}
	return invokeOutput
}
```
+  API の詳細については、**AWS SDK for Go API リファレンスの「[Invoke](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.Invoke)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_go_2_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}



// ListFunctions lists up to maxItems functions for the account. This function uses a
// lambda.ListFunctionsPaginator to paginate the results.
func (wrapper FunctionWrapper) ListFunctions(ctx context.Context, maxItems int) []types.FunctionConfiguration {
	var functions []types.FunctionConfiguration
	paginator := lambda.NewListFunctionsPaginator(wrapper.LambdaClient, &lambda.ListFunctionsInput{
		MaxItems: aws.Int32(int32(maxItems)),
	})
	for paginator.HasMorePages() && len(functions) < maxItems {
		pageOutput, err := paginator.NextPage(ctx)
		if err != nil {
			log.Panicf("Couldn't list functions for your account. Here's why: %v\n", err)
		}
		functions = append(functions, pageOutput.Functions...)
	}
	return functions
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListFunctions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.ListFunctions)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_go_2_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}



// UpdateFunctionCode updates the code for the Lambda function specified by functionName.
// The existing code for the Lambda function is entirely replaced by the code in the
// zipPackage buffer. After the update action is called, a lambda.FunctionUpdatedV2Waiter
// is used to wait until the update is successful.
func (wrapper FunctionWrapper) UpdateFunctionCode(ctx context.Context, functionName string, zipPackage *bytes.Buffer) types.State {
	var state types.State
	_, err := wrapper.LambdaClient.UpdateFunctionCode(ctx, &lambda.UpdateFunctionCodeInput{
		FunctionName: aws.String(functionName), ZipFile: zipPackage.Bytes(),
	})
	if err != nil {
		log.Panicf("Couldn't update code for function %v. Here's why: %v\n", functionName, err)
	} else {
		waiter := lambda.NewFunctionUpdatedV2Waiter(wrapper.LambdaClient)
		funcOutput, err := waiter.WaitForOutput(ctx, &lambda.GetFunctionInput{
			FunctionName: aws.String(functionName)}, 1*time.Minute)
		if err != nil {
			log.Panicf("Couldn't wait for function %v to be active. Here's why: %v\n", functionName, err)
		} else {
			state = funcOutput.Configuration.State
		}
	}
	return state
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[UpdateFunctionCode](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.UpdateFunctionCode)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_go_2_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/lambda#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/lambda"
	"github.com/aws/aws-sdk-go-v2/service/lambda/types"
)

// FunctionWrapper encapsulates function actions used in the examples.
// It contains an AWS Lambda service client that is used to perform user actions.
type FunctionWrapper struct {
	LambdaClient *lambda.Client
}



// UpdateFunctionConfiguration updates a map of environment variables configured for
// the Lambda function specified by functionName.
func (wrapper FunctionWrapper) UpdateFunctionConfiguration(ctx context.Context, functionName string, envVars map[string]string) {
	_, err := wrapper.LambdaClient.UpdateFunctionConfiguration(ctx, &lambda.UpdateFunctionConfigurationInput{
		FunctionName: aws.String(functionName),
		Environment:  &types.Environment{Variables: envVars},
	})
	if err != nil {
		log.Panicf("Couldn't update configuration for %v. Here's why: %v", functionName, err)
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[UpdateFunctionConfiguration](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/lambda#Client.UpdateFunctionConfiguration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Lambda 関数を使用して登録済みのユーザーを自動的に確認する
<a name="cross_CognitoAutoConfirmUser_go_2_topic"></a>

次のコード例は、Lambda 関数を使用して登録済みの Amazon Cognito ユーザーを自動的に確認する方法を示しています。
+ `PreSignUp` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ Amazon Cognito でユーザーをサインアップする
+ Lambda 関数は DynamoDB テーブルをスキャンし、登録済みのユーザーを自動的に確認します。
+ 新しいユーザーとしてサインインし、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"errors"
	"log"
	"strings"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// AutoConfirm separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type AutoConfirm struct {
	helper       IScenarioHelper
	questioner   demotools.IQuestioner
	resources    Resources
	cognitoActor *actions.CognitoActions
}

// NewAutoConfirm constructs a new auto confirm runner.
func NewAutoConfirm(sdkConfig aws.Config, questioner demotools.IQuestioner, helper IScenarioHelper) AutoConfirm {
	scenario := AutoConfirm{
		helper:       helper,
		questioner:   questioner,
		resources:    Resources{},
		cognitoActor: &actions.CognitoActions{CognitoClient: cognitoidentityprovider.NewFromConfig(sdkConfig)},
	}
	scenario.resources.init(scenario.cognitoActor, questioner)
	return scenario
}

// AddPreSignUpTrigger adds a Lambda handler as an invocation target for the PreSignUp trigger.
func (runner *AutoConfirm) AddPreSignUpTrigger(ctx context.Context, userPoolId string, functionArn string) {
	log.Printf("Let's add a Lambda function to handle the PreSignUp trigger from Cognito.\n" +
		"This trigger happens when a user signs up, and lets your function take action before the main Cognito\n" +
		"sign up processing occurs.\n")
	err := runner.cognitoActor.UpdateTriggers(
		ctx, userPoolId,
		actions.TriggerInfo{Trigger: actions.PreSignUp, HandlerArn: aws.String(functionArn)})
	if err != nil {
		panic(err)
	}
	log.Printf("Lambda function %v added to user pool %v to handle the PreSignUp trigger.\n",
		functionArn, userPoolId)
}

// SignUpUser signs up a user from the known user table with a password you specify.
func (runner *AutoConfirm) SignUpUser(ctx context.Context, clientId string, usersTable string) (string, string) {
	log.Println("Let's sign up a user to your Cognito user pool. When the user's email matches an email in the\n" +
		"DynamoDB known users table, it is automatically verified and the user is confirmed.")

	knownUsers, err := runner.helper.GetKnownUsers(ctx, usersTable)
	if err != nil {
		panic(err)
	}
	userChoice := runner.questioner.AskChoice("Which user do you want to use?\n", knownUsers.UserNameList())
	user := knownUsers.Users[userChoice]

	var signedUp bool
	var userConfirmed bool
	password := runner.questioner.AskPassword("Enter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.\n"+
		"(the password will not display as you type):", 8)
	for !signedUp {
		log.Printf("Signing up user '%v' with email '%v' to Cognito.\n", user.UserName, user.UserEmail)
		userConfirmed, err = runner.cognitoActor.SignUp(ctx, clientId, user.UserName, password, user.UserEmail)
		if err != nil {
			var invalidPassword *types.InvalidPasswordException
			if errors.As(err, &invalidPassword) {
				password = runner.questioner.AskPassword("Enter another password:", 8)
			} else {
				panic(err)
			}
		} else {
			signedUp = true
		}
	}
	log.Printf("User %v signed up, confirmed = %v.\n", user.UserName, userConfirmed)

	log.Println(strings.Repeat("-", 88))

	return user.UserName, password
}

// SignInUser signs in a user.
func (runner *AutoConfirm) SignInUser(ctx context.Context, clientId string, userName string, password string) string {
	runner.questioner.Ask("Press Enter when you're ready to continue.")
	log.Printf("Let's sign in as %v...\n", userName)
	authResult, err := runner.cognitoActor.SignIn(ctx, clientId, userName, password)
	if err != nil {
		panic(err)
	}
	log.Printf("Successfully signed in. Your access token starts with: %v...\n", (*authResult.AccessToken)[:10])
	log.Println(strings.Repeat("-", 88))
	return *authResult.AccessToken
}

// Run runs the scenario.
func (runner *AutoConfirm) Run(ctx context.Context, stackName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			runner.resources.Cleanup(ctx)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome\n")

	log.Println(strings.Repeat("-", 88))

	stackOutputs, err := runner.helper.GetStackOutputs(ctx, stackName)
	if err != nil {
		panic(err)
	}
	runner.resources.userPoolId = stackOutputs["UserPoolId"]
	runner.helper.PopulateUserTable(ctx, stackOutputs["TableName"])

	runner.AddPreSignUpTrigger(ctx, stackOutputs["UserPoolId"], stackOutputs["AutoConfirmFunctionArn"])
	runner.resources.triggers = append(runner.resources.triggers, actions.PreSignUp)
	userName, password := runner.SignUpUser(ctx, stackOutputs["UserPoolClientId"], stackOutputs["TableName"])
	runner.helper.ListRecentLogEvents(ctx, stackOutputs["AutoConfirmFunction"])
	runner.resources.userAccessTokens = append(runner.resources.userAccessTokens,
		runner.SignInUser(ctx, stackOutputs["UserPoolClientId"], userName, password))

	runner.resources.Cleanup(ctx)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
Lambda 関数を使用して `PreSignUp` トリガーを処理します。  

```
import (
	"context"
	"log"
	"os"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	dynamodbtypes "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

const TABLE_NAME = "TABLE_NAME"

// UserInfo defines structured user data that can be marshalled to a DynamoDB format.
type UserInfo struct {
	UserName  string `dynamodbav:"UserName"`
	UserEmail string `dynamodbav:"UserEmail"`
}

// GetKey marshals the user email value to a DynamoDB key format.
func (user UserInfo) GetKey() map[string]dynamodbtypes.AttributeValue {
	userEmail, err := attributevalue.Marshal(user.UserEmail)
	if err != nil {
		panic(err)
	}
	return map[string]dynamodbtypes.AttributeValue{"UserEmail": userEmail}
}

type handler struct {
	dynamoClient *dynamodb.Client
}

// HandleRequest handles the PreSignUp event by looking up a user in an Amazon DynamoDB table and
// specifying whether they should be confirmed and verified.
func (h *handler) HandleRequest(ctx context.Context, event events.CognitoEventUserPoolsPreSignup) (events.CognitoEventUserPoolsPreSignup, error) {
	log.Printf("Received presignup from %v for user '%v'", event.TriggerSource, event.UserName)
	if event.TriggerSource != "PreSignUp_SignUp" {
		// Other trigger sources, such as PreSignUp_AdminInitiateAuth, ignore the response from this handler.
		return event, nil
	}
	tableName := os.Getenv(TABLE_NAME)
	user := UserInfo{
		UserEmail: event.Request.UserAttributes["email"],
	}
	log.Printf("Looking up email %v in table %v.\n", user.UserEmail, tableName)
	output, err := h.dynamoClient.GetItem(ctx, &dynamodb.GetItemInput{
		Key:       user.GetKey(),
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Error looking up email %v.\n", user.UserEmail)
		return event, err
	}
	if output.Item == nil {
		log.Printf("Email %v not found. Email verification is required.\n", user.UserEmail)
		return event, err
	}

	err = attributevalue.UnmarshalMap(output.Item, &user)
	if err != nil {
		log.Printf("Couldn't unmarshal DynamoDB item. Here's why: %v\n", err)
		return event, err
	}

	if user.UserName != event.UserName {
		log.Printf("UserEmail %v found, but stored UserName '%v' does not match supplied UserName '%v'. Verification is required.\n",
			user.UserEmail, user.UserName, event.UserName)
	} else {
		log.Printf("UserEmail %v found with matching UserName %v. User is confirmed.\n", user.UserEmail, user.UserName)
		event.Response.AutoConfirmUser = true
		event.Response.AutoVerifyEmail = true
	}

	return event, err
}

func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Panicln(err)
	}
	h := handler{
		dynamoClient: dynamodb.NewFromConfig(sdkConfig),
	}
	lambda.Start(h.HandleRequest)
}
```
一般的なタスクを実行する構造体を作成します。  

```
import (
	"context"
	"log"
	"strings"
	"time"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// IScenarioHelper defines common functions used by the workflows in this example.
type IScenarioHelper interface {
	Pause(secs int)
	GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error)
	PopulateUserTable(ctx context.Context, tableName string)
	GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error)
	AddKnownUser(ctx context.Context, tableName string, user actions.User)
	ListRecentLogEvents(ctx context.Context, functionName string)
}

// ScenarioHelper contains AWS wrapper structs used by the workflows in this example.
type ScenarioHelper struct {
	questioner  demotools.IQuestioner
	dynamoActor *actions.DynamoActions
	cfnActor    *actions.CloudFormationActions
	cwlActor    *actions.CloudWatchLogsActions
	isTestRun   bool
}

// NewScenarioHelper constructs a new scenario helper.
func NewScenarioHelper(sdkConfig aws.Config, questioner demotools.IQuestioner) ScenarioHelper {
	scenario := ScenarioHelper{
		questioner:  questioner,
		dynamoActor: &actions.DynamoActions{DynamoClient: dynamodb.NewFromConfig(sdkConfig)},
		cfnActor:    &actions.CloudFormationActions{CfnClient: cloudformation.NewFromConfig(sdkConfig)},
		cwlActor:    &actions.CloudWatchLogsActions{CwlClient: cloudwatchlogs.NewFromConfig(sdkConfig)},
	}
	return scenario
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	if !helper.isTestRun {
		time.Sleep(time.Duration(secs) * time.Second)
	}
}

// GetStackOutputs gets the outputs from the specified CloudFormation stack in a structured format.
func (helper ScenarioHelper) GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error) {
	return helper.cfnActor.GetOutputs(ctx, stackName), nil
}

// PopulateUserTable fills the known user table with example data.
func (helper ScenarioHelper) PopulateUserTable(ctx context.Context, tableName string) {
	log.Printf("First, let's add some users to the DynamoDB %v table we'll use for this example.\n", tableName)
	err := helper.dynamoActor.PopulateTable(ctx, tableName)
	if err != nil {
		panic(err)
	}
}

// GetKnownUsers gets the users from the known users table in a structured format.
func (helper ScenarioHelper) GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error) {
	knownUsers, err := helper.dynamoActor.Scan(ctx, tableName)
	if err != nil {
		log.Printf("Couldn't get known users from table %v. Here's why: %v\n", tableName, err)
	}
	return knownUsers, err
}

// AddKnownUser adds a user to the known users table.
func (helper ScenarioHelper) AddKnownUser(ctx context.Context, tableName string, user actions.User) {
	log.Printf("Adding user '%v' with email '%v' to the DynamoDB known users table...\n",
		user.UserName, user.UserEmail)
	err := helper.dynamoActor.AddUser(ctx, tableName, user)
	if err != nil {
		panic(err)
	}
}

// ListRecentLogEvents gets the most recent log stream and events for the specified Lambda function and displays them.
func (helper ScenarioHelper) ListRecentLogEvents(ctx context.Context, functionName string) {
	log.Println("Waiting a few seconds to let Lambda write to CloudWatch Logs...")
	helper.Pause(10)
	log.Println("Okay, let's check the logs to find what's happened recently with your Lambda function.")
	logStream, err := helper.cwlActor.GetLatestLogStream(ctx, functionName)
	if err != nil {
		panic(err)
	}
	log.Printf("Getting some recent events from log stream %v\n", *logStream.LogStreamName)
	events, err := helper.cwlActor.GetLogEvents(ctx, functionName, *logStream.LogStreamName, 10)
	if err != nil {
		panic(err)
	}
	for _, event := range events {
		log.Printf("\t%v", *event.Message)
	}
	log.Println(strings.Repeat("-", 88))
}
```
Amazon Cognito アクションをラップする構造体を作成します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// Trigger and TriggerInfo define typed data for updating an Amazon Cognito trigger.
type Trigger int

const (
	PreSignUp Trigger = iota
	UserMigration
	PostAuthentication
)

type TriggerInfo struct {
	Trigger    Trigger
	HandlerArn *string
}

// UpdateTriggers adds or removes Lambda triggers for a user pool. When a trigger is specified with a `nil` value,
// it is removed from the user pool.
func (actor CognitoActions) UpdateTriggers(ctx context.Context, userPoolId string, triggers ...TriggerInfo) error {
	output, err := actor.CognitoClient.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{
		UserPoolId: aws.String(userPoolId),
	})
	if err != nil {
		log.Printf("Couldn't get info about user pool %v. Here's why: %v\n", userPoolId, err)
		return err
	}
	lambdaConfig := output.UserPool.LambdaConfig
	for _, trigger := range triggers {
		switch trigger.Trigger {
		case PreSignUp:
			lambdaConfig.PreSignUp = trigger.HandlerArn
		case UserMigration:
			lambdaConfig.UserMigration = trigger.HandlerArn
		case PostAuthentication:
			lambdaConfig.PostAuthentication = trigger.HandlerArn
		}
	}
	_, err = actor.CognitoClient.UpdateUserPool(ctx, &cognitoidentityprovider.UpdateUserPoolInput{
		UserPoolId:   aws.String(userPoolId),
		LambdaConfig: lambdaConfig,
	})
	if err != nil {
		log.Printf("Couldn't update user pool %v. Here's why: %v\n", userPoolId, err)
	}
	return err
}



// SignUp signs up a user with Amazon Cognito.
func (actor CognitoActions) SignUp(ctx context.Context, clientId string, userName string, password string, userEmail string) (bool, error) {
	confirmed := false
	output, err := actor.CognitoClient.SignUp(ctx, &cognitoidentityprovider.SignUpInput{
		ClientId: aws.String(clientId),
		Password: aws.String(password),
		Username: aws.String(userName),
		UserAttributes: []types.AttributeType{
			{Name: aws.String("email"), Value: aws.String(userEmail)},
		},
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err)
		}
	} else {
		confirmed = output.UserConfirmed
	}
	return confirmed, err
}



// SignIn signs in a user to Amazon Cognito using a username and password authentication flow.
func (actor CognitoActions) SignIn(ctx context.Context, clientId string, userName string, password string) (*types.AuthenticationResultType, error) {
	var authResult *types.AuthenticationResultType
	output, err := actor.CognitoClient.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
		AuthFlow:       "USER_PASSWORD_AUTH",
		ClientId:       aws.String(clientId),
		AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password},
	})
	if err != nil {
		var resetRequired *types.PasswordResetRequiredException
		if errors.As(err, &resetRequired) {
			log.Println(*resetRequired.Message)
		} else {
			log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err)
		}
	} else {
		authResult = output.AuthenticationResult
	}
	return authResult, err
}



// ForgotPassword starts a password recovery flow for a user. This flow typically sends a confirmation code
// to the user's configured notification destination, such as email.
func (actor CognitoActions) ForgotPassword(ctx context.Context, clientId string, userName string) (*types.CodeDeliveryDetailsType, error) {
	output, err := actor.CognitoClient.ForgotPassword(ctx, &cognitoidentityprovider.ForgotPasswordInput{
		ClientId: aws.String(clientId),
		Username: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't start password reset for user '%v'. Here;s why: %v\n", userName, err)
	}
	return output.CodeDeliveryDetails, err
}



// ConfirmForgotPassword confirms a user with a confirmation code and a new password.
func (actor CognitoActions) ConfirmForgotPassword(ctx context.Context, clientId string, code string, userName string, password string) error {
	_, err := actor.CognitoClient.ConfirmForgotPassword(ctx, &cognitoidentityprovider.ConfirmForgotPasswordInput{
		ClientId:         aws.String(clientId),
		ConfirmationCode: aws.String(code),
		Password:         aws.String(password),
		Username:         aws.String(userName),
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't confirm user %v. Here's why: %v", userName, err)
		}
	}
	return err
}



// DeleteUser removes a user from the user pool.
func (actor CognitoActions) DeleteUser(ctx context.Context, userAccessToken string) error {
	_, err := actor.CognitoClient.DeleteUser(ctx, &cognitoidentityprovider.DeleteUserInput{
		AccessToken: aws.String(userAccessToken),
	})
	if err != nil {
		log.Printf("Couldn't delete user. Here's why: %v\n", err)
	}
	return err
}



// AdminCreateUser uses administrator credentials to add a user to a user pool. This method leaves the user
// in a state that requires they enter a new password next time they sign in.
func (actor CognitoActions) AdminCreateUser(ctx context.Context, userPoolId string, userName string, userEmail string) error {
	_, err := actor.CognitoClient.AdminCreateUser(ctx, &cognitoidentityprovider.AdminCreateUserInput{
		UserPoolId:     aws.String(userPoolId),
		Username:       aws.String(userName),
		MessageAction:  types.MessageActionTypeSuppress,
		UserAttributes: []types.AttributeType{{Name: aws.String("email"), Value: aws.String(userEmail)}},
	})
	if err != nil {
		var userExists *types.UsernameExistsException
		if errors.As(err, &userExists) {
			log.Printf("User %v already exists in the user pool.", userName)
			err = nil
		} else {
			log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
DynamoDB アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type DynamoActions struct {
	DynamoClient *dynamodb.Client
}

// User defines structured user data.
type User struct {
	UserName  string
	UserEmail string
	LastLogin *LoginInfo `dynamodbav:",omitempty"`
}

// LoginInfo defines structured custom login data.
type LoginInfo struct {
	UserPoolId string
	ClientId   string
	Time       string
}

// UserList defines a list of users.
type UserList struct {
	Users []User
}

// UserNameList returns the usernames contained in a UserList as a list of strings.
func (users *UserList) UserNameList() []string {
	names := make([]string, len(users.Users))
	for i := 0; i < len(users.Users); i++ {
		names[i] = users.Users[i].UserName
	}
	return names
}

// PopulateTable adds a set of test users to the table.
func (actor DynamoActions) PopulateTable(ctx context.Context, tableName string) error {
	var err error
	var item map[string]types.AttributeValue
	var writeReqs []types.WriteRequest
	for i := 1; i < 4; i++ {
		item, err = attributevalue.MarshalMap(User{UserName: fmt.Sprintf("test_user_%v", i), UserEmail: fmt.Sprintf("test_email_%v@example.com", i)})
		if err != nil {
			log.Printf("Couldn't marshall user into DynamoDB format. Here's why: %v\n", err)
			return err
		}
		writeReqs = append(writeReqs, types.WriteRequest{PutRequest: &types.PutRequest{Item: item}})
	}
	_, err = actor.DynamoClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
		RequestItems: map[string][]types.WriteRequest{tableName: writeReqs},
	})
	if err != nil {
		log.Printf("Couldn't populate table %v with users. Here's why: %v\n", tableName, err)
	}
	return err
}

// Scan scans the table for all items.
func (actor DynamoActions) Scan(ctx context.Context, tableName string) (UserList, error) {
	var userList UserList
	output, err := actor.DynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't scan table %v for items. Here's why: %v\n", tableName, err)
	} else {
		err = attributevalue.UnmarshalListOfMaps(output.Items, &userList.Users)
		if err != nil {
			log.Printf("Couldn't unmarshal items into users. Here's why: %v\n", err)
		}
	}
	return userList, err
}

// AddUser adds a user item to a table.
func (actor DynamoActions) AddUser(ctx context.Context, tableName string, user User) error {
	userItem, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshall user to item. Here's why: %v\n", err)
	}
	_, err = actor.DynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
		Item:      userItem,
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't put item in table %v. Here's why: %v", tableName, err)
	}
	return err
}
```
CloudWatch Logs アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
)

type CloudWatchLogsActions struct {
	CwlClient *cloudwatchlogs.Client
}

// GetLatestLogStream gets the most recent log stream for a Lambda function.
func (actor CloudWatchLogsActions) GetLatestLogStream(ctx context.Context, functionName string) (types.LogStream, error) {
	var logStream types.LogStream
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
		Descending:   aws.Bool(true),
		Limit:        aws.Int32(1),
		LogGroupName: aws.String(logGroupName),
		OrderBy:      types.OrderByLastEventTime,
	})
	if err != nil {
		log.Printf("Couldn't get log streams for log group %v. Here's why: %v\n", logGroupName, err)
	} else {
		logStream = output.LogStreams[0]
	}
	return logStream, err
}

// GetLogEvents gets the most recent eventCount events from the specified log stream.
func (actor CloudWatchLogsActions) GetLogEvents(ctx context.Context, functionName string, logStreamName string, eventCount int32) (
	[]types.OutputLogEvent, error) {
	var events []types.OutputLogEvent
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.GetLogEvents(ctx, &cloudwatchlogs.GetLogEventsInput{
		LogStreamName: aws.String(logStreamName),
		Limit:         aws.Int32(eventCount),
		LogGroupName:  aws.String(logGroupName),
	})
	if err != nil {
		log.Printf("Couldn't get log event for log stream %v. Here's why: %v\n", logStreamName, err)
	} else {
		events = output.Events
	}
	return events, err
}
```
 CloudFormation アクションをラップする構造体を作成します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"log"
	"user_pools_and_lambda_triggers/actions"

	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	userPoolId       string
	userAccessTokens []string
	triggers         []actions.Trigger

	cognitoActor *actions.CognitoActions
	questioner   demotools.IQuestioner
}

func (resources *Resources) init(cognitoActor *actions.CognitoActions, questioner demotools.IQuestioner) {
	resources.userAccessTokens = []string{}
	resources.triggers = []actions.Trigger{}
	resources.cognitoActor = cognitoActor
	resources.questioner = questioner
}

// Cleanup deletes all AWS resources created during an example.
func (resources *Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong during cleanup.\n%v\n", r)
			log.Println("Use the AWS Management Console to remove any remaining resources \n" +
				"that were created for this scenario.")
		}
	}()

	wantDelete := resources.questioner.AskBool("Do you want to remove all of the AWS resources that were created "+
		"during this demo (y/n)?", "y")
	if wantDelete {
		for _, accessToken := range resources.userAccessTokens {
			err := resources.cognitoActor.DeleteUser(ctx, accessToken)
			if err != nil {
				log.Println("Couldn't delete user during cleanup.")
				panic(err)
			}
			log.Println("Deleted user.")
		}
		triggerList := make([]actions.TriggerInfo, len(resources.triggers))
		for i := 0; i < len(resources.triggers); i++ {
			triggerList[i] = actions.TriggerInfo{Trigger: resources.triggers[i], HandlerArn: nil}
		}
		err := resources.cognitoActor.UpdateTriggers(ctx, resources.userPoolId, triggerList...)
		if err != nil {
			log.Println("Couldn't update Cognito triggers during cleanup.")
			panic(err)
		}
		log.Println("Removed Cognito triggers from user pool.")
	} else {
		log.Println("Be sure to remove resources when you're done with them to avoid unexpected charges!")
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.DeleteUser)
  + [InitiateAuth](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.InitiateAuth)
  + [SignUp](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.SignUp)
  + [UpdateUserPool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.UpdateUserPool)

### Lambda 関数を使用して登録済みのユーザーを自動的に移行する
<a name="cross_CognitoAutoMigrateUser_go_2_topic"></a>

次のコード例は、Lambda 関数を使用して登録済みの Amazon Cognito ユーザーを自動的に移行する方法を示しています。
+ `MigrateUser` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ ユーザープールにないユーザー名と E メールで Amazon Cognito にサインインします。
+ Lambda 関数は DynamoDB テーブルをスキャンし、登録済みのユーザーをユーザープールに自動的に移行します。
+ パスワードを忘れた場合のフローを実行して、移行したユーザーのパスワードをリセットします。
+ 新しいユーザーとしてサインインし、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"errors"
	"fmt"
	"log"
	"strings"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// MigrateUser separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type MigrateUser struct {
	helper       IScenarioHelper
	questioner   demotools.IQuestioner
	resources    Resources
	cognitoActor *actions.CognitoActions
}

// NewMigrateUser constructs a new migrate user runner.
func NewMigrateUser(sdkConfig aws.Config, questioner demotools.IQuestioner, helper IScenarioHelper) MigrateUser {
	scenario := MigrateUser{
		helper:       helper,
		questioner:   questioner,
		resources:    Resources{},
		cognitoActor: &actions.CognitoActions{CognitoClient: cognitoidentityprovider.NewFromConfig(sdkConfig)},
	}
	scenario.resources.init(scenario.cognitoActor, questioner)
	return scenario
}

// AddMigrateUserTrigger adds a Lambda handler as an invocation target for the MigrateUser trigger.
func (runner *MigrateUser) AddMigrateUserTrigger(ctx context.Context, userPoolId string, functionArn string) {
	log.Printf("Let's add a Lambda function to handle the MigrateUser trigger from Cognito.\n" +
		"This trigger happens when an unknown user signs in, and lets your function take action before Cognito\n" +
		"rejects the user.\n\n")
	err := runner.cognitoActor.UpdateTriggers(
		ctx, userPoolId,
		actions.TriggerInfo{Trigger: actions.UserMigration, HandlerArn: aws.String(functionArn)})
	if err != nil {
		panic(err)
	}
	log.Printf("Lambda function %v added to user pool %v to handle the MigrateUser trigger.\n",
		functionArn, userPoolId)

	log.Println(strings.Repeat("-", 88))
}

// SignInUser adds a new user to the known users table and signs that user in to Amazon Cognito.
func (runner *MigrateUser) SignInUser(ctx context.Context, usersTable string, clientId string) (bool, actions.User) {
	log.Println("Let's sign in a user to your Cognito user pool. When the username and email matches an entry in the\n" +
		"DynamoDB known users table, the email is automatically verified and the user is migrated to the Cognito user pool.")

	user := actions.User{}
	user.UserName = runner.questioner.Ask("\nEnter a username:")
	user.UserEmail = runner.questioner.Ask("\nEnter an email that you own. This email will be used to confirm user migration\n" +
		"during this example:")

	runner.helper.AddKnownUser(ctx, usersTable, user)

	var err error
	var resetRequired *types.PasswordResetRequiredException
	var authResult *types.AuthenticationResultType
	signedIn := false
	for !signedIn && resetRequired == nil {
		log.Printf("Signing in to Cognito as user '%v'. The expected result is a PasswordResetRequiredException.\n\n", user.UserName)
		authResult, err = runner.cognitoActor.SignIn(ctx, clientId, user.UserName, "_")
		if err != nil {
			if errors.As(err, &resetRequired) {
				log.Printf("\nUser '%v' is not in the Cognito user pool but was found in the DynamoDB known users table.\n"+
					"User migration is started and a password reset is required.", user.UserName)
			} else {
				panic(err)
			}
		} else {
			log.Printf("User '%v' successfully signed in. This is unexpected and probably means you have not\n"+
				"cleaned up a previous run of this scenario, so the user exist in the Cognito user pool.\n"+
				"You can continue this example and select to clean up resources, or manually remove\n"+
				"the user from your user pool and try again.", user.UserName)
			runner.resources.userAccessTokens = append(runner.resources.userAccessTokens, *authResult.AccessToken)
			signedIn = true
		}
	}

	log.Println(strings.Repeat("-", 88))
	return resetRequired != nil, user
}

// ResetPassword starts a password recovery flow.
func (runner *MigrateUser) ResetPassword(ctx context.Context, clientId string, user actions.User) {
	wantCode := runner.questioner.AskBool(fmt.Sprintf("In order to migrate the user to Cognito, you must be able to receive a confirmation\n"+
		"code by email at %v. Do you want to send a code (y/n)?", user.UserEmail), "y")
	if !wantCode {
		log.Println("To complete this example and successfully migrate a user to Cognito, you must enter an email\n" +
			"you own that can receive a confirmation code.")
		return
	}
	codeDelivery, err := runner.cognitoActor.ForgotPassword(ctx, clientId, user.UserName)
	if err != nil {
		panic(err)
	}
	log.Printf("\nA confirmation code has been sent to %v.", *codeDelivery.Destination)
	code := runner.questioner.Ask("Check your email and enter it here:")

	confirmed := false
	password := runner.questioner.AskPassword("\nEnter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.\n"+
		"(the password will not display as you type):", 8)
	for !confirmed {
		log.Printf("\nConfirming password reset for user '%v'.\n", user.UserName)
		err = runner.cognitoActor.ConfirmForgotPassword(ctx, clientId, code, user.UserName, password)
		if err != nil {
			var invalidPassword *types.InvalidPasswordException
			if errors.As(err, &invalidPassword) {
				password = runner.questioner.AskPassword("\nEnter another password:", 8)
			} else {
				panic(err)
			}
		} else {
			confirmed = true
		}
	}
	log.Printf("User '%v' successfully confirmed and migrated.\n", user.UserName)
	log.Println("Signing in with your username and password...")
	authResult, err := runner.cognitoActor.SignIn(ctx, clientId, user.UserName, password)
	if err != nil {
		panic(err)
	}
	log.Printf("Successfully signed in. Your access token starts with: %v...\n", (*authResult.AccessToken)[:10])
	runner.resources.userAccessTokens = append(runner.resources.userAccessTokens, *authResult.AccessToken)

	log.Println(strings.Repeat("-", 88))
}

// Run runs the scenario.
func (runner *MigrateUser) Run(ctx context.Context, stackName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			runner.resources.Cleanup(ctx)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome\n")

	log.Println(strings.Repeat("-", 88))

	stackOutputs, err := runner.helper.GetStackOutputs(ctx, stackName)
	if err != nil {
		panic(err)
	}
	runner.resources.userPoolId = stackOutputs["UserPoolId"]

	runner.AddMigrateUserTrigger(ctx, stackOutputs["UserPoolId"], stackOutputs["MigrateUserFunctionArn"])
	runner.resources.triggers = append(runner.resources.triggers, actions.UserMigration)
	resetNeeded, user := runner.SignInUser(ctx, stackOutputs["TableName"], stackOutputs["UserPoolClientId"])
	if resetNeeded {
		runner.helper.ListRecentLogEvents(ctx, stackOutputs["MigrateUserFunction"])
		runner.ResetPassword(ctx, stackOutputs["UserPoolClientId"], user)
	}

	runner.resources.Cleanup(ctx)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
Lambda 関数を使用して `MigrateUser` トリガーを処理します。  

```
import (
	"context"
	"log"
	"os"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
)

const TABLE_NAME = "TABLE_NAME"

// UserInfo defines structured user data that can be marshalled to a DynamoDB format.
type UserInfo struct {
	UserName  string `dynamodbav:"UserName"`
	UserEmail string `dynamodbav:"UserEmail"`
}

type handler struct {
	dynamoClient *dynamodb.Client
}

// HandleRequest handles the MigrateUser event by looking up a user in an Amazon DynamoDB table and
// specifying whether they should be migrated to the user pool.
func (h *handler) HandleRequest(ctx context.Context, event events.CognitoEventUserPoolsMigrateUser) (events.CognitoEventUserPoolsMigrateUser, error) {
	log.Printf("Received migrate trigger from %v for user '%v'", event.TriggerSource, event.UserName)
	if event.TriggerSource != "UserMigration_Authentication" {
		return event, nil
	}
	tableName := os.Getenv(TABLE_NAME)
	user := UserInfo{
		UserName: event.UserName,
	}
	log.Printf("Looking up user '%v' in table %v.\n", user.UserName, tableName)
	filterEx := expression.Name("UserName").Equal(expression.Value(user.UserName))
	expr, err := expression.NewBuilder().WithFilter(filterEx).Build()
	if err != nil {
		log.Printf("Error building expression to query for user '%v'.\n", user.UserName)
		return event, err
	}
	output, err := h.dynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName:                 aws.String(tableName),
		FilterExpression:          expr.Filter(),
		ExpressionAttributeNames:  expr.Names(),
		ExpressionAttributeValues: expr.Values(),
	})
	if err != nil {
		log.Printf("Error looking up user '%v'.\n", user.UserName)
		return event, err
	}
	if len(output.Items) == 0 {
		log.Printf("User '%v' not found, not migrating user.\n", user.UserName)
		return event, err
	}

	var users []UserInfo
	err = attributevalue.UnmarshalListOfMaps(output.Items, &users)
	if err != nil {
		log.Printf("Couldn't unmarshal DynamoDB items. Here's why: %v\n", err)
		return event, err
	}

	user = users[0]
	log.Printf("UserName '%v' found with email %v. User is migrated and must reset password.\n", user.UserName, user.UserEmail)
	event.CognitoEventUserPoolsMigrateUserResponse.UserAttributes = map[string]string{
		"email":          user.UserEmail,
		"email_verified": "true", // email_verified is required for the forgot password flow.
	}
	event.CognitoEventUserPoolsMigrateUserResponse.FinalUserStatus = "RESET_REQUIRED"
	event.CognitoEventUserPoolsMigrateUserResponse.MessageAction = "SUPPRESS"

	return event, err
}

func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Panicln(err)
	}
	h := handler{
		dynamoClient: dynamodb.NewFromConfig(sdkConfig),
	}
	lambda.Start(h.HandleRequest)
}
```
一般的なタスクを実行する構造体を作成します。  

```
import (
	"context"
	"log"
	"strings"
	"time"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// IScenarioHelper defines common functions used by the workflows in this example.
type IScenarioHelper interface {
	Pause(secs int)
	GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error)
	PopulateUserTable(ctx context.Context, tableName string)
	GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error)
	AddKnownUser(ctx context.Context, tableName string, user actions.User)
	ListRecentLogEvents(ctx context.Context, functionName string)
}

// ScenarioHelper contains AWS wrapper structs used by the workflows in this example.
type ScenarioHelper struct {
	questioner  demotools.IQuestioner
	dynamoActor *actions.DynamoActions
	cfnActor    *actions.CloudFormationActions
	cwlActor    *actions.CloudWatchLogsActions
	isTestRun   bool
}

// NewScenarioHelper constructs a new scenario helper.
func NewScenarioHelper(sdkConfig aws.Config, questioner demotools.IQuestioner) ScenarioHelper {
	scenario := ScenarioHelper{
		questioner:  questioner,
		dynamoActor: &actions.DynamoActions{DynamoClient: dynamodb.NewFromConfig(sdkConfig)},
		cfnActor:    &actions.CloudFormationActions{CfnClient: cloudformation.NewFromConfig(sdkConfig)},
		cwlActor:    &actions.CloudWatchLogsActions{CwlClient: cloudwatchlogs.NewFromConfig(sdkConfig)},
	}
	return scenario
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	if !helper.isTestRun {
		time.Sleep(time.Duration(secs) * time.Second)
	}
}

// GetStackOutputs gets the outputs from the specified CloudFormation stack in a structured format.
func (helper ScenarioHelper) GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error) {
	return helper.cfnActor.GetOutputs(ctx, stackName), nil
}

// PopulateUserTable fills the known user table with example data.
func (helper ScenarioHelper) PopulateUserTable(ctx context.Context, tableName string) {
	log.Printf("First, let's add some users to the DynamoDB %v table we'll use for this example.\n", tableName)
	err := helper.dynamoActor.PopulateTable(ctx, tableName)
	if err != nil {
		panic(err)
	}
}

// GetKnownUsers gets the users from the known users table in a structured format.
func (helper ScenarioHelper) GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error) {
	knownUsers, err := helper.dynamoActor.Scan(ctx, tableName)
	if err != nil {
		log.Printf("Couldn't get known users from table %v. Here's why: %v\n", tableName, err)
	}
	return knownUsers, err
}

// AddKnownUser adds a user to the known users table.
func (helper ScenarioHelper) AddKnownUser(ctx context.Context, tableName string, user actions.User) {
	log.Printf("Adding user '%v' with email '%v' to the DynamoDB known users table...\n",
		user.UserName, user.UserEmail)
	err := helper.dynamoActor.AddUser(ctx, tableName, user)
	if err != nil {
		panic(err)
	}
}

// ListRecentLogEvents gets the most recent log stream and events for the specified Lambda function and displays them.
func (helper ScenarioHelper) ListRecentLogEvents(ctx context.Context, functionName string) {
	log.Println("Waiting a few seconds to let Lambda write to CloudWatch Logs...")
	helper.Pause(10)
	log.Println("Okay, let's check the logs to find what's happened recently with your Lambda function.")
	logStream, err := helper.cwlActor.GetLatestLogStream(ctx, functionName)
	if err != nil {
		panic(err)
	}
	log.Printf("Getting some recent events from log stream %v\n", *logStream.LogStreamName)
	events, err := helper.cwlActor.GetLogEvents(ctx, functionName, *logStream.LogStreamName, 10)
	if err != nil {
		panic(err)
	}
	for _, event := range events {
		log.Printf("\t%v", *event.Message)
	}
	log.Println(strings.Repeat("-", 88))
}
```
Amazon Cognito アクションをラップする構造体を作成します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// Trigger and TriggerInfo define typed data for updating an Amazon Cognito trigger.
type Trigger int

const (
	PreSignUp Trigger = iota
	UserMigration
	PostAuthentication
)

type TriggerInfo struct {
	Trigger    Trigger
	HandlerArn *string
}

// UpdateTriggers adds or removes Lambda triggers for a user pool. When a trigger is specified with a `nil` value,
// it is removed from the user pool.
func (actor CognitoActions) UpdateTriggers(ctx context.Context, userPoolId string, triggers ...TriggerInfo) error {
	output, err := actor.CognitoClient.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{
		UserPoolId: aws.String(userPoolId),
	})
	if err != nil {
		log.Printf("Couldn't get info about user pool %v. Here's why: %v\n", userPoolId, err)
		return err
	}
	lambdaConfig := output.UserPool.LambdaConfig
	for _, trigger := range triggers {
		switch trigger.Trigger {
		case PreSignUp:
			lambdaConfig.PreSignUp = trigger.HandlerArn
		case UserMigration:
			lambdaConfig.UserMigration = trigger.HandlerArn
		case PostAuthentication:
			lambdaConfig.PostAuthentication = trigger.HandlerArn
		}
	}
	_, err = actor.CognitoClient.UpdateUserPool(ctx, &cognitoidentityprovider.UpdateUserPoolInput{
		UserPoolId:   aws.String(userPoolId),
		LambdaConfig: lambdaConfig,
	})
	if err != nil {
		log.Printf("Couldn't update user pool %v. Here's why: %v\n", userPoolId, err)
	}
	return err
}



// SignUp signs up a user with Amazon Cognito.
func (actor CognitoActions) SignUp(ctx context.Context, clientId string, userName string, password string, userEmail string) (bool, error) {
	confirmed := false
	output, err := actor.CognitoClient.SignUp(ctx, &cognitoidentityprovider.SignUpInput{
		ClientId: aws.String(clientId),
		Password: aws.String(password),
		Username: aws.String(userName),
		UserAttributes: []types.AttributeType{
			{Name: aws.String("email"), Value: aws.String(userEmail)},
		},
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err)
		}
	} else {
		confirmed = output.UserConfirmed
	}
	return confirmed, err
}



// SignIn signs in a user to Amazon Cognito using a username and password authentication flow.
func (actor CognitoActions) SignIn(ctx context.Context, clientId string, userName string, password string) (*types.AuthenticationResultType, error) {
	var authResult *types.AuthenticationResultType
	output, err := actor.CognitoClient.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
		AuthFlow:       "USER_PASSWORD_AUTH",
		ClientId:       aws.String(clientId),
		AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password},
	})
	if err != nil {
		var resetRequired *types.PasswordResetRequiredException
		if errors.As(err, &resetRequired) {
			log.Println(*resetRequired.Message)
		} else {
			log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err)
		}
	} else {
		authResult = output.AuthenticationResult
	}
	return authResult, err
}



// ForgotPassword starts a password recovery flow for a user. This flow typically sends a confirmation code
// to the user's configured notification destination, such as email.
func (actor CognitoActions) ForgotPassword(ctx context.Context, clientId string, userName string) (*types.CodeDeliveryDetailsType, error) {
	output, err := actor.CognitoClient.ForgotPassword(ctx, &cognitoidentityprovider.ForgotPasswordInput{
		ClientId: aws.String(clientId),
		Username: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't start password reset for user '%v'. Here;s why: %v\n", userName, err)
	}
	return output.CodeDeliveryDetails, err
}



// ConfirmForgotPassword confirms a user with a confirmation code and a new password.
func (actor CognitoActions) ConfirmForgotPassword(ctx context.Context, clientId string, code string, userName string, password string) error {
	_, err := actor.CognitoClient.ConfirmForgotPassword(ctx, &cognitoidentityprovider.ConfirmForgotPasswordInput{
		ClientId:         aws.String(clientId),
		ConfirmationCode: aws.String(code),
		Password:         aws.String(password),
		Username:         aws.String(userName),
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't confirm user %v. Here's why: %v", userName, err)
		}
	}
	return err
}



// DeleteUser removes a user from the user pool.
func (actor CognitoActions) DeleteUser(ctx context.Context, userAccessToken string) error {
	_, err := actor.CognitoClient.DeleteUser(ctx, &cognitoidentityprovider.DeleteUserInput{
		AccessToken: aws.String(userAccessToken),
	})
	if err != nil {
		log.Printf("Couldn't delete user. Here's why: %v\n", err)
	}
	return err
}



// AdminCreateUser uses administrator credentials to add a user to a user pool. This method leaves the user
// in a state that requires they enter a new password next time they sign in.
func (actor CognitoActions) AdminCreateUser(ctx context.Context, userPoolId string, userName string, userEmail string) error {
	_, err := actor.CognitoClient.AdminCreateUser(ctx, &cognitoidentityprovider.AdminCreateUserInput{
		UserPoolId:     aws.String(userPoolId),
		Username:       aws.String(userName),
		MessageAction:  types.MessageActionTypeSuppress,
		UserAttributes: []types.AttributeType{{Name: aws.String("email"), Value: aws.String(userEmail)}},
	})
	if err != nil {
		var userExists *types.UsernameExistsException
		if errors.As(err, &userExists) {
			log.Printf("User %v already exists in the user pool.", userName)
			err = nil
		} else {
			log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
DynamoDB アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type DynamoActions struct {
	DynamoClient *dynamodb.Client
}

// User defines structured user data.
type User struct {
	UserName  string
	UserEmail string
	LastLogin *LoginInfo `dynamodbav:",omitempty"`
}

// LoginInfo defines structured custom login data.
type LoginInfo struct {
	UserPoolId string
	ClientId   string
	Time       string
}

// UserList defines a list of users.
type UserList struct {
	Users []User
}

// UserNameList returns the usernames contained in a UserList as a list of strings.
func (users *UserList) UserNameList() []string {
	names := make([]string, len(users.Users))
	for i := 0; i < len(users.Users); i++ {
		names[i] = users.Users[i].UserName
	}
	return names
}

// PopulateTable adds a set of test users to the table.
func (actor DynamoActions) PopulateTable(ctx context.Context, tableName string) error {
	var err error
	var item map[string]types.AttributeValue
	var writeReqs []types.WriteRequest
	for i := 1; i < 4; i++ {
		item, err = attributevalue.MarshalMap(User{UserName: fmt.Sprintf("test_user_%v", i), UserEmail: fmt.Sprintf("test_email_%v@example.com", i)})
		if err != nil {
			log.Printf("Couldn't marshall user into DynamoDB format. Here's why: %v\n", err)
			return err
		}
		writeReqs = append(writeReqs, types.WriteRequest{PutRequest: &types.PutRequest{Item: item}})
	}
	_, err = actor.DynamoClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
		RequestItems: map[string][]types.WriteRequest{tableName: writeReqs},
	})
	if err != nil {
		log.Printf("Couldn't populate table %v with users. Here's why: %v\n", tableName, err)
	}
	return err
}

// Scan scans the table for all items.
func (actor DynamoActions) Scan(ctx context.Context, tableName string) (UserList, error) {
	var userList UserList
	output, err := actor.DynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't scan table %v for items. Here's why: %v\n", tableName, err)
	} else {
		err = attributevalue.UnmarshalListOfMaps(output.Items, &userList.Users)
		if err != nil {
			log.Printf("Couldn't unmarshal items into users. Here's why: %v\n", err)
		}
	}
	return userList, err
}

// AddUser adds a user item to a table.
func (actor DynamoActions) AddUser(ctx context.Context, tableName string, user User) error {
	userItem, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshall user to item. Here's why: %v\n", err)
	}
	_, err = actor.DynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
		Item:      userItem,
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't put item in table %v. Here's why: %v", tableName, err)
	}
	return err
}
```
CloudWatch Logs アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
)

type CloudWatchLogsActions struct {
	CwlClient *cloudwatchlogs.Client
}

// GetLatestLogStream gets the most recent log stream for a Lambda function.
func (actor CloudWatchLogsActions) GetLatestLogStream(ctx context.Context, functionName string) (types.LogStream, error) {
	var logStream types.LogStream
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
		Descending:   aws.Bool(true),
		Limit:        aws.Int32(1),
		LogGroupName: aws.String(logGroupName),
		OrderBy:      types.OrderByLastEventTime,
	})
	if err != nil {
		log.Printf("Couldn't get log streams for log group %v. Here's why: %v\n", logGroupName, err)
	} else {
		logStream = output.LogStreams[0]
	}
	return logStream, err
}

// GetLogEvents gets the most recent eventCount events from the specified log stream.
func (actor CloudWatchLogsActions) GetLogEvents(ctx context.Context, functionName string, logStreamName string, eventCount int32) (
	[]types.OutputLogEvent, error) {
	var events []types.OutputLogEvent
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.GetLogEvents(ctx, &cloudwatchlogs.GetLogEventsInput{
		LogStreamName: aws.String(logStreamName),
		Limit:         aws.Int32(eventCount),
		LogGroupName:  aws.String(logGroupName),
	})
	if err != nil {
		log.Printf("Couldn't get log event for log stream %v. Here's why: %v\n", logStreamName, err)
	} else {
		events = output.Events
	}
	return events, err
}
```
 CloudFormation アクションをラップする構造体を作成します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"log"
	"user_pools_and_lambda_triggers/actions"

	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	userPoolId       string
	userAccessTokens []string
	triggers         []actions.Trigger

	cognitoActor *actions.CognitoActions
	questioner   demotools.IQuestioner
}

func (resources *Resources) init(cognitoActor *actions.CognitoActions, questioner demotools.IQuestioner) {
	resources.userAccessTokens = []string{}
	resources.triggers = []actions.Trigger{}
	resources.cognitoActor = cognitoActor
	resources.questioner = questioner
}

// Cleanup deletes all AWS resources created during an example.
func (resources *Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong during cleanup.\n%v\n", r)
			log.Println("Use the AWS Management Console to remove any remaining resources \n" +
				"that were created for this scenario.")
		}
	}()

	wantDelete := resources.questioner.AskBool("Do you want to remove all of the AWS resources that were created "+
		"during this demo (y/n)?", "y")
	if wantDelete {
		for _, accessToken := range resources.userAccessTokens {
			err := resources.cognitoActor.DeleteUser(ctx, accessToken)
			if err != nil {
				log.Println("Couldn't delete user during cleanup.")
				panic(err)
			}
			log.Println("Deleted user.")
		}
		triggerList := make([]actions.TriggerInfo, len(resources.triggers))
		for i := 0; i < len(resources.triggers); i++ {
			triggerList[i] = actions.TriggerInfo{Trigger: resources.triggers[i], HandlerArn: nil}
		}
		err := resources.cognitoActor.UpdateTriggers(ctx, resources.userPoolId, triggerList...)
		if err != nil {
			log.Println("Couldn't update Cognito triggers during cleanup.")
			panic(err)
		}
		log.Println("Removed Cognito triggers from user pool.")
	} else {
		log.Println("Be sure to remove resources when you're done with them to avoid unexpected charges!")
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [ConfirmForgotPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ConfirmForgotPassword)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.DeleteUser)
  + [ForgotPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.ForgotPassword)
  + [InitiateAuth](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.InitiateAuth)
  + [SignUp](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.SignUp)
  + [UpdateUserPool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.UpdateUserPool)

### Amazon Cognito ユーザー認証後に Lambda 関数を使用してカスタムアクティビティデータを書き込む
<a name="cross_CognitoCustomActivityLog_go_2_topic"></a>

次のコード例は、Amazon Cognito ユーザー認証後に Lambda 関数を使用してカスタムアクティビティデータを書き込む方法を示しています。
+ 管理者関数を使用して、ユーザーをユーザープールに追加します。
+ `PostAuthentication` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ 新しいユーザーを Amazon Cognito にサインインします。
+ Lambda 関数は、カスタム情報を CloudWatch Logs と DynamoDB テーブルに書き込みます。
+ DynamoDB テーブルからカスタムデータを取得して表示し、リソースをクリーンアップします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"errors"
	"log"
	"strings"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// ActivityLog separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type ActivityLog struct {
	helper       IScenarioHelper
	questioner   demotools.IQuestioner
	resources    Resources
	cognitoActor *actions.CognitoActions
}

// NewActivityLog constructs a new activity log runner.
func NewActivityLog(sdkConfig aws.Config, questioner demotools.IQuestioner, helper IScenarioHelper) ActivityLog {
	scenario := ActivityLog{
		helper:       helper,
		questioner:   questioner,
		resources:    Resources{},
		cognitoActor: &actions.CognitoActions{CognitoClient: cognitoidentityprovider.NewFromConfig(sdkConfig)},
	}
	scenario.resources.init(scenario.cognitoActor, questioner)
	return scenario
}

// AddUserToPool selects a user from the known users table and uses administrator credentials to add the user to the user pool.
func (runner *ActivityLog) AddUserToPool(ctx context.Context, userPoolId string, tableName string) (string, string) {
	log.Println("To facilitate this example, let's add a user to the user pool using administrator privileges.")
	users, err := runner.helper.GetKnownUsers(ctx, tableName)
	if err != nil {
		panic(err)
	}
	user := users.Users[0]
	log.Printf("Adding known user %v to the user pool.\n", user.UserName)
	err = runner.cognitoActor.AdminCreateUser(ctx, userPoolId, user.UserName, user.UserEmail)
	if err != nil {
		panic(err)
	}
	pwSet := false
	password := runner.questioner.AskPassword("\nEnter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.\n"+
		"(the password will not display as you type):", 8)
	for !pwSet {
		log.Printf("\nSetting password for user '%v'.\n", user.UserName)
		err = runner.cognitoActor.AdminSetUserPassword(ctx, userPoolId, user.UserName, password)
		if err != nil {
			var invalidPassword *types.InvalidPasswordException
			if errors.As(err, &invalidPassword) {
				password = runner.questioner.AskPassword("\nEnter another password:", 8)
			} else {
				panic(err)
			}
		} else {
			pwSet = true
		}
	}

	log.Println(strings.Repeat("-", 88))

	return user.UserName, password
}

// AddActivityLogTrigger adds a Lambda handler as an invocation target for the PostAuthentication trigger.
func (runner *ActivityLog) AddActivityLogTrigger(ctx context.Context, userPoolId string, activityLogArn string) {
	log.Println("Let's add a Lambda function to handle the PostAuthentication trigger from Cognito.\n" +
		"This trigger happens after a user is authenticated, and lets your function take action, such as logging\n" +
		"the outcome.")
	err := runner.cognitoActor.UpdateTriggers(
		ctx, userPoolId,
		actions.TriggerInfo{Trigger: actions.PostAuthentication, HandlerArn: aws.String(activityLogArn)})
	if err != nil {
		panic(err)
	}
	runner.resources.triggers = append(runner.resources.triggers, actions.PostAuthentication)
	log.Printf("Lambda function %v added to user pool %v to handle PostAuthentication Cognito trigger.\n",
		activityLogArn, userPoolId)

	log.Println(strings.Repeat("-", 88))
}

// SignInUser signs in as the specified user.
func (runner *ActivityLog) SignInUser(ctx context.Context, clientId string, userName string, password string) {
	log.Printf("Now we'll sign in user %v and check the results in the logs and the DynamoDB table.", userName)
	runner.questioner.Ask("Press Enter when you're ready.")
	authResult, err := runner.cognitoActor.SignIn(ctx, clientId, userName, password)
	if err != nil {
		panic(err)
	}
	log.Println("Sign in successful.",
		"The PostAuthentication Lambda handler writes custom information to CloudWatch Logs.")

	runner.resources.userAccessTokens = append(runner.resources.userAccessTokens, *authResult.AccessToken)
}

// GetKnownUserLastLogin gets the login info for a user from the Amazon DynamoDB table and displays it.
func (runner *ActivityLog) GetKnownUserLastLogin(ctx context.Context, tableName string, userName string) {
	log.Println("The PostAuthentication handler also writes login data to the DynamoDB table.")
	runner.questioner.Ask("Press Enter when you're ready to continue.")
	users, err := runner.helper.GetKnownUsers(ctx, tableName)
	if err != nil {
		panic(err)
	}
	for _, user := range users.Users {
		if user.UserName == userName {
			log.Println("The last login info for the user in the known users table is:")
			log.Printf("\t%+v", *user.LastLogin)
		}
	}
	log.Println(strings.Repeat("-", 88))
}

// Run runs the scenario.
func (runner *ActivityLog) Run(ctx context.Context, stackName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			runner.resources.Cleanup(ctx)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome\n")

	log.Println(strings.Repeat("-", 88))

	stackOutputs, err := runner.helper.GetStackOutputs(ctx, stackName)
	if err != nil {
		panic(err)
	}
	runner.resources.userPoolId = stackOutputs["UserPoolId"]
	runner.helper.PopulateUserTable(ctx, stackOutputs["TableName"])
	userName, password := runner.AddUserToPool(ctx, stackOutputs["UserPoolId"], stackOutputs["TableName"])

	runner.AddActivityLogTrigger(ctx, stackOutputs["UserPoolId"], stackOutputs["ActivityLogFunctionArn"])
	runner.SignInUser(ctx, stackOutputs["UserPoolClientId"], userName, password)
	runner.helper.ListRecentLogEvents(ctx, stackOutputs["ActivityLogFunction"])
	runner.GetKnownUserLastLogin(ctx, stackOutputs["TableName"], userName)

	runner.resources.Cleanup(ctx)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
Lambda 関数を使用して `PostAuthentication` トリガーを処理します。  

```
import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	dynamodbtypes "github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

const TABLE_NAME = "TABLE_NAME"

// LoginInfo defines structured login data that can be marshalled to a DynamoDB format.
type LoginInfo struct {
	UserPoolId string `dynamodbav:"UserPoolId"`
	ClientId   string `dynamodbav:"ClientId"`
	Time       string `dynamodbav:"Time"`
}

// UserInfo defines structured user data that can be marshalled to a DynamoDB format.
type UserInfo struct {
	UserName  string    `dynamodbav:"UserName"`
	UserEmail string    `dynamodbav:"UserEmail"`
	LastLogin LoginInfo `dynamodbav:"LastLogin"`
}

// GetKey marshals the user email value to a DynamoDB key format.
func (user UserInfo) GetKey() map[string]dynamodbtypes.AttributeValue {
	userEmail, err := attributevalue.Marshal(user.UserEmail)
	if err != nil {
		panic(err)
	}
	return map[string]dynamodbtypes.AttributeValue{"UserEmail": userEmail}
}

type handler struct {
	dynamoClient *dynamodb.Client
}

// HandleRequest handles the PostAuthentication event by writing custom data to the logs and
// to an Amazon DynamoDB table.
func (h *handler) HandleRequest(ctx context.Context, event events.CognitoEventUserPoolsPostAuthentication) (events.CognitoEventUserPoolsPostAuthentication, error) {
	log.Printf("Received post authentication trigger from %v for user '%v'", event.TriggerSource, event.UserName)
	tableName := os.Getenv(TABLE_NAME)
	user := UserInfo{
		UserName:  event.UserName,
		UserEmail: event.Request.UserAttributes["email"],
		LastLogin: LoginInfo{
			UserPoolId: event.UserPoolID,
			ClientId:   event.CallerContext.ClientID,
			Time:       time.Now().Format(time.UnixDate),
		},
	}
	// Write to CloudWatch Logs.
	fmt.Printf("%#v", user)

	// Also write to an external system. This examples uses DynamoDB to demonstrate.
	userMap, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshal to DynamoDB map. Here's why: %v\n", err)
	} else if len(userMap) == 0 {
		log.Printf("User info marshaled to an empty map.")
	} else {
		_, err := h.dynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
			Item:      userMap,
			TableName: aws.String(tableName),
		})
		if err != nil {
			log.Printf("Couldn't write to DynamoDB. Here's why: %v\n", err)
		} else {
			log.Printf("Wrote user info to DynamoDB table %v.\n", tableName)
		}
	}

	return event, nil
}

func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Panicln(err)
	}
	h := handler{
		dynamoClient: dynamodb.NewFromConfig(sdkConfig),
	}
	lambda.Start(h.HandleRequest)
}
```
一般的なタスクを実行する構造体を作成します。  

```
import (
	"context"
	"log"
	"strings"
	"time"
	"user_pools_and_lambda_triggers/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// IScenarioHelper defines common functions used by the workflows in this example.
type IScenarioHelper interface {
	Pause(secs int)
	GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error)
	PopulateUserTable(ctx context.Context, tableName string)
	GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error)
	AddKnownUser(ctx context.Context, tableName string, user actions.User)
	ListRecentLogEvents(ctx context.Context, functionName string)
}

// ScenarioHelper contains AWS wrapper structs used by the workflows in this example.
type ScenarioHelper struct {
	questioner  demotools.IQuestioner
	dynamoActor *actions.DynamoActions
	cfnActor    *actions.CloudFormationActions
	cwlActor    *actions.CloudWatchLogsActions
	isTestRun   bool
}

// NewScenarioHelper constructs a new scenario helper.
func NewScenarioHelper(sdkConfig aws.Config, questioner demotools.IQuestioner) ScenarioHelper {
	scenario := ScenarioHelper{
		questioner:  questioner,
		dynamoActor: &actions.DynamoActions{DynamoClient: dynamodb.NewFromConfig(sdkConfig)},
		cfnActor:    &actions.CloudFormationActions{CfnClient: cloudformation.NewFromConfig(sdkConfig)},
		cwlActor:    &actions.CloudWatchLogsActions{CwlClient: cloudwatchlogs.NewFromConfig(sdkConfig)},
	}
	return scenario
}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	if !helper.isTestRun {
		time.Sleep(time.Duration(secs) * time.Second)
	}
}

// GetStackOutputs gets the outputs from the specified CloudFormation stack in a structured format.
func (helper ScenarioHelper) GetStackOutputs(ctx context.Context, stackName string) (actions.StackOutputs, error) {
	return helper.cfnActor.GetOutputs(ctx, stackName), nil
}

// PopulateUserTable fills the known user table with example data.
func (helper ScenarioHelper) PopulateUserTable(ctx context.Context, tableName string) {
	log.Printf("First, let's add some users to the DynamoDB %v table we'll use for this example.\n", tableName)
	err := helper.dynamoActor.PopulateTable(ctx, tableName)
	if err != nil {
		panic(err)
	}
}

// GetKnownUsers gets the users from the known users table in a structured format.
func (helper ScenarioHelper) GetKnownUsers(ctx context.Context, tableName string) (actions.UserList, error) {
	knownUsers, err := helper.dynamoActor.Scan(ctx, tableName)
	if err != nil {
		log.Printf("Couldn't get known users from table %v. Here's why: %v\n", tableName, err)
	}
	return knownUsers, err
}

// AddKnownUser adds a user to the known users table.
func (helper ScenarioHelper) AddKnownUser(ctx context.Context, tableName string, user actions.User) {
	log.Printf("Adding user '%v' with email '%v' to the DynamoDB known users table...\n",
		user.UserName, user.UserEmail)
	err := helper.dynamoActor.AddUser(ctx, tableName, user)
	if err != nil {
		panic(err)
	}
}

// ListRecentLogEvents gets the most recent log stream and events for the specified Lambda function and displays them.
func (helper ScenarioHelper) ListRecentLogEvents(ctx context.Context, functionName string) {
	log.Println("Waiting a few seconds to let Lambda write to CloudWatch Logs...")
	helper.Pause(10)
	log.Println("Okay, let's check the logs to find what's happened recently with your Lambda function.")
	logStream, err := helper.cwlActor.GetLatestLogStream(ctx, functionName)
	if err != nil {
		panic(err)
	}
	log.Printf("Getting some recent events from log stream %v\n", *logStream.LogStreamName)
	events, err := helper.cwlActor.GetLogEvents(ctx, functionName, *logStream.LogStreamName, 10)
	if err != nil {
		panic(err)
	}
	for _, event := range events {
		log.Printf("\t%v", *event.Message)
	}
	log.Println(strings.Repeat("-", 88))
}
```
Amazon Cognito アクションをラップする構造体を作成します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
	"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

type CognitoActions struct {
	CognitoClient *cognitoidentityprovider.Client
}



// Trigger and TriggerInfo define typed data for updating an Amazon Cognito trigger.
type Trigger int

const (
	PreSignUp Trigger = iota
	UserMigration
	PostAuthentication
)

type TriggerInfo struct {
	Trigger    Trigger
	HandlerArn *string
}

// UpdateTriggers adds or removes Lambda triggers for a user pool. When a trigger is specified with a `nil` value,
// it is removed from the user pool.
func (actor CognitoActions) UpdateTriggers(ctx context.Context, userPoolId string, triggers ...TriggerInfo) error {
	output, err := actor.CognitoClient.DescribeUserPool(ctx, &cognitoidentityprovider.DescribeUserPoolInput{
		UserPoolId: aws.String(userPoolId),
	})
	if err != nil {
		log.Printf("Couldn't get info about user pool %v. Here's why: %v\n", userPoolId, err)
		return err
	}
	lambdaConfig := output.UserPool.LambdaConfig
	for _, trigger := range triggers {
		switch trigger.Trigger {
		case PreSignUp:
			lambdaConfig.PreSignUp = trigger.HandlerArn
		case UserMigration:
			lambdaConfig.UserMigration = trigger.HandlerArn
		case PostAuthentication:
			lambdaConfig.PostAuthentication = trigger.HandlerArn
		}
	}
	_, err = actor.CognitoClient.UpdateUserPool(ctx, &cognitoidentityprovider.UpdateUserPoolInput{
		UserPoolId:   aws.String(userPoolId),
		LambdaConfig: lambdaConfig,
	})
	if err != nil {
		log.Printf("Couldn't update user pool %v. Here's why: %v\n", userPoolId, err)
	}
	return err
}



// SignUp signs up a user with Amazon Cognito.
func (actor CognitoActions) SignUp(ctx context.Context, clientId string, userName string, password string, userEmail string) (bool, error) {
	confirmed := false
	output, err := actor.CognitoClient.SignUp(ctx, &cognitoidentityprovider.SignUpInput{
		ClientId: aws.String(clientId),
		Password: aws.String(password),
		Username: aws.String(userName),
		UserAttributes: []types.AttributeType{
			{Name: aws.String("email"), Value: aws.String(userEmail)},
		},
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't sign up user %v. Here's why: %v\n", userName, err)
		}
	} else {
		confirmed = output.UserConfirmed
	}
	return confirmed, err
}



// SignIn signs in a user to Amazon Cognito using a username and password authentication flow.
func (actor CognitoActions) SignIn(ctx context.Context, clientId string, userName string, password string) (*types.AuthenticationResultType, error) {
	var authResult *types.AuthenticationResultType
	output, err := actor.CognitoClient.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
		AuthFlow:       "USER_PASSWORD_AUTH",
		ClientId:       aws.String(clientId),
		AuthParameters: map[string]string{"USERNAME": userName, "PASSWORD": password},
	})
	if err != nil {
		var resetRequired *types.PasswordResetRequiredException
		if errors.As(err, &resetRequired) {
			log.Println(*resetRequired.Message)
		} else {
			log.Printf("Couldn't sign in user %v. Here's why: %v\n", userName, err)
		}
	} else {
		authResult = output.AuthenticationResult
	}
	return authResult, err
}



// ForgotPassword starts a password recovery flow for a user. This flow typically sends a confirmation code
// to the user's configured notification destination, such as email.
func (actor CognitoActions) ForgotPassword(ctx context.Context, clientId string, userName string) (*types.CodeDeliveryDetailsType, error) {
	output, err := actor.CognitoClient.ForgotPassword(ctx, &cognitoidentityprovider.ForgotPasswordInput{
		ClientId: aws.String(clientId),
		Username: aws.String(userName),
	})
	if err != nil {
		log.Printf("Couldn't start password reset for user '%v'. Here;s why: %v\n", userName, err)
	}
	return output.CodeDeliveryDetails, err
}



// ConfirmForgotPassword confirms a user with a confirmation code and a new password.
func (actor CognitoActions) ConfirmForgotPassword(ctx context.Context, clientId string, code string, userName string, password string) error {
	_, err := actor.CognitoClient.ConfirmForgotPassword(ctx, &cognitoidentityprovider.ConfirmForgotPasswordInput{
		ClientId:         aws.String(clientId),
		ConfirmationCode: aws.String(code),
		Password:         aws.String(password),
		Username:         aws.String(userName),
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't confirm user %v. Here's why: %v", userName, err)
		}
	}
	return err
}



// DeleteUser removes a user from the user pool.
func (actor CognitoActions) DeleteUser(ctx context.Context, userAccessToken string) error {
	_, err := actor.CognitoClient.DeleteUser(ctx, &cognitoidentityprovider.DeleteUserInput{
		AccessToken: aws.String(userAccessToken),
	})
	if err != nil {
		log.Printf("Couldn't delete user. Here's why: %v\n", err)
	}
	return err
}



// AdminCreateUser uses administrator credentials to add a user to a user pool. This method leaves the user
// in a state that requires they enter a new password next time they sign in.
func (actor CognitoActions) AdminCreateUser(ctx context.Context, userPoolId string, userName string, userEmail string) error {
	_, err := actor.CognitoClient.AdminCreateUser(ctx, &cognitoidentityprovider.AdminCreateUserInput{
		UserPoolId:     aws.String(userPoolId),
		Username:       aws.String(userName),
		MessageAction:  types.MessageActionTypeSuppress,
		UserAttributes: []types.AttributeType{{Name: aws.String("email"), Value: aws.String(userEmail)}},
	})
	if err != nil {
		var userExists *types.UsernameExistsException
		if errors.As(err, &userExists) {
			log.Printf("User %v already exists in the user pool.", userName)
			err = nil
		} else {
			log.Printf("Couldn't create user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}



// AdminSetUserPassword uses administrator credentials to set a password for a user without requiring a
// temporary password.
func (actor CognitoActions) AdminSetUserPassword(ctx context.Context, userPoolId string, userName string, password string) error {
	_, err := actor.CognitoClient.AdminSetUserPassword(ctx, &cognitoidentityprovider.AdminSetUserPasswordInput{
		Password:   aws.String(password),
		UserPoolId: aws.String(userPoolId),
		Username:   aws.String(userName),
		Permanent:  true,
	})
	if err != nil {
		var invalidPassword *types.InvalidPasswordException
		if errors.As(err, &invalidPassword) {
			log.Println(*invalidPassword.Message)
		} else {
			log.Printf("Couldn't set password for user %v. Here's why: %v\n", userName, err)
		}
	}
	return err
}
```
DynamoDB アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/dynamodb/attributevalue"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
)

// DynamoActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type DynamoActions struct {
	DynamoClient *dynamodb.Client
}

// User defines structured user data.
type User struct {
	UserName  string
	UserEmail string
	LastLogin *LoginInfo `dynamodbav:",omitempty"`
}

// LoginInfo defines structured custom login data.
type LoginInfo struct {
	UserPoolId string
	ClientId   string
	Time       string
}

// UserList defines a list of users.
type UserList struct {
	Users []User
}

// UserNameList returns the usernames contained in a UserList as a list of strings.
func (users *UserList) UserNameList() []string {
	names := make([]string, len(users.Users))
	for i := 0; i < len(users.Users); i++ {
		names[i] = users.Users[i].UserName
	}
	return names
}

// PopulateTable adds a set of test users to the table.
func (actor DynamoActions) PopulateTable(ctx context.Context, tableName string) error {
	var err error
	var item map[string]types.AttributeValue
	var writeReqs []types.WriteRequest
	for i := 1; i < 4; i++ {
		item, err = attributevalue.MarshalMap(User{UserName: fmt.Sprintf("test_user_%v", i), UserEmail: fmt.Sprintf("test_email_%v@example.com", i)})
		if err != nil {
			log.Printf("Couldn't marshall user into DynamoDB format. Here's why: %v\n", err)
			return err
		}
		writeReqs = append(writeReqs, types.WriteRequest{PutRequest: &types.PutRequest{Item: item}})
	}
	_, err = actor.DynamoClient.BatchWriteItem(ctx, &dynamodb.BatchWriteItemInput{
		RequestItems: map[string][]types.WriteRequest{tableName: writeReqs},
	})
	if err != nil {
		log.Printf("Couldn't populate table %v with users. Here's why: %v\n", tableName, err)
	}
	return err
}

// Scan scans the table for all items.
func (actor DynamoActions) Scan(ctx context.Context, tableName string) (UserList, error) {
	var userList UserList
	output, err := actor.DynamoClient.Scan(ctx, &dynamodb.ScanInput{
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't scan table %v for items. Here's why: %v\n", tableName, err)
	} else {
		err = attributevalue.UnmarshalListOfMaps(output.Items, &userList.Users)
		if err != nil {
			log.Printf("Couldn't unmarshal items into users. Here's why: %v\n", err)
		}
	}
	return userList, err
}

// AddUser adds a user item to a table.
func (actor DynamoActions) AddUser(ctx context.Context, tableName string, user User) error {
	userItem, err := attributevalue.MarshalMap(user)
	if err != nil {
		log.Printf("Couldn't marshall user to item. Here's why: %v\n", err)
	}
	_, err = actor.DynamoClient.PutItem(ctx, &dynamodb.PutItemInput{
		Item:      userItem,
		TableName: aws.String(tableName),
	})
	if err != nil {
		log.Printf("Couldn't put item in table %v. Here's why: %v", tableName, err)
	}
	return err
}
```
CloudWatch Logs アクションをラップする構造体を作成します。  

```
import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
	"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
)

type CloudWatchLogsActions struct {
	CwlClient *cloudwatchlogs.Client
}

// GetLatestLogStream gets the most recent log stream for a Lambda function.
func (actor CloudWatchLogsActions) GetLatestLogStream(ctx context.Context, functionName string) (types.LogStream, error) {
	var logStream types.LogStream
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
		Descending:   aws.Bool(true),
		Limit:        aws.Int32(1),
		LogGroupName: aws.String(logGroupName),
		OrderBy:      types.OrderByLastEventTime,
	})
	if err != nil {
		log.Printf("Couldn't get log streams for log group %v. Here's why: %v\n", logGroupName, err)
	} else {
		logStream = output.LogStreams[0]
	}
	return logStream, err
}

// GetLogEvents gets the most recent eventCount events from the specified log stream.
func (actor CloudWatchLogsActions) GetLogEvents(ctx context.Context, functionName string, logStreamName string, eventCount int32) (
	[]types.OutputLogEvent, error) {
	var events []types.OutputLogEvent
	logGroupName := fmt.Sprintf("/aws/lambda/%s", functionName)
	output, err := actor.CwlClient.GetLogEvents(ctx, &cloudwatchlogs.GetLogEventsInput{
		LogStreamName: aws.String(logStreamName),
		Limit:         aws.Int32(eventCount),
		LogGroupName:  aws.String(logGroupName),
	})
	if err != nil {
		log.Printf("Couldn't get log event for log stream %v. Here's why: %v\n", logStreamName, err)
	} else {
		events = output.Events
	}
	return events, err
}
```
 CloudFormation アクションをラップする構造体を作成します。  

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"log"
	"user_pools_and_lambda_triggers/actions"

	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	userPoolId       string
	userAccessTokens []string
	triggers         []actions.Trigger

	cognitoActor *actions.CognitoActions
	questioner   demotools.IQuestioner
}

func (resources *Resources) init(cognitoActor *actions.CognitoActions, questioner demotools.IQuestioner) {
	resources.userAccessTokens = []string{}
	resources.triggers = []actions.Trigger{}
	resources.cognitoActor = cognitoActor
	resources.questioner = questioner
}

// Cleanup deletes all AWS resources created during an example.
func (resources *Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong during cleanup.\n%v\n", r)
			log.Println("Use the AWS Management Console to remove any remaining resources \n" +
				"that were created for this scenario.")
		}
	}()

	wantDelete := resources.questioner.AskBool("Do you want to remove all of the AWS resources that were created "+
		"during this demo (y/n)?", "y")
	if wantDelete {
		for _, accessToken := range resources.userAccessTokens {
			err := resources.cognitoActor.DeleteUser(ctx, accessToken)
			if err != nil {
				log.Println("Couldn't delete user during cleanup.")
				panic(err)
			}
			log.Println("Deleted user.")
		}
		triggerList := make([]actions.TriggerInfo, len(resources.triggers))
		for i := 0; i < len(resources.triggers); i++ {
			triggerList[i] = actions.TriggerInfo{Trigger: resources.triggers[i], HandlerArn: nil}
		}
		err := resources.cognitoActor.UpdateTriggers(ctx, resources.userPoolId, triggerList...)
		if err != nil {
			log.Println("Couldn't update Cognito triggers during cleanup.")
			panic(err)
		}
		log.Println("Removed Cognito triggers from user pool.")
	} else {
		log.Println("Be sure to remove resources when you're done with them to avoid unexpected charges!")
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [AdminCreateUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.AdminCreateUser)
  + [AdminSetUserPassword](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.AdminSetUserPassword)
  + [DeleteUser](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.DeleteUser)
  + [InitiateAuth](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.InitiateAuth)
  + [UpdateUserPool](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider#Client.UpdateUserPool)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_go_2_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
/*
Golang v2 code here.
*/

package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"os"

	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/rds/auth"
	_ "github.com/go-sql-driver/mysql"
)

type MyEvent struct {
	Name string `json:"name"`
}

func HandleRequest(event *MyEvent) (map[string]interface{}, error) {

	var dbName string = os.Getenv("DatabaseName")
	var dbUser string = os.Getenv("DatabaseUser")
	var dbHost string = os.Getenv("DBHost") // Add hostname without https
	var dbPort int = os.Getenv("Port")      // Add port number
	var dbEndpoint string = fmt.Sprintf("%s:%d", dbHost, dbPort)
	var region string = os.Getenv("AWS_REGION")

	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		panic("configuration error: " + err.Error())
	}

	authenticationToken, err := auth.BuildAuthToken(
		context.TODO(), dbEndpoint, region, dbUser, cfg.Credentials)
	if err != nil {
		panic("failed to create authentication token: " + err.Error())
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true&allowCleartextPasswords=true",
		dbUser, authenticationToken, dbEndpoint, dbName,
	)

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}

	defer db.Close()

	var sum int
	err = db.QueryRow("SELECT ?+? AS sum", 3, 2).Scan(&sum)
	if err != nil {
		panic(err)
	}
	s := fmt.Sprint(sum)
	message := fmt.Sprintf("The selected sum is: %s", s)

	messageBytes, err := json.Marshal(message)
	if err != nil {
		return nil, err
	}

	messageString := string(messageBytes)
	return map[string]interface{}{
		"statusCode": 200,
		"headers":    map[string]string{"Content-Type": "application/json"},
		"body":       messageString,
	}, nil
}

func main() {
	lambda.Start(HandleRequest)
}
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_go_2_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"log"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, kinesisEvent events.KinesisEvent) error {
	if len(kinesisEvent.Records) == 0 {
		log.Printf("empty Kinesis event received")
		return nil
	}

	for _, record := range kinesisEvent.Records {
		log.Printf("processed Kinesis event with EventId: %v", record.EventID)
		recordDataBytes := record.Kinesis.Data
		recordDataText := string(recordDataBytes)
		log.Printf("record data: %v", recordDataText)
		// TODO: Do interesting work based on the new data
	}
	log.Printf("successfully processed %v records", len(kinesisEvent.Records))
	return nil
}

func main() {
	lambda.Start(handler)
}
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_go_2_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で DynamoDB イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-lambda-go/events"
	"fmt"
)

func HandleRequest(ctx context.Context, event events.DynamoDBEvent) (*string, error) {
	if len(event.Records) == 0 {
		return nil, fmt.Errorf("received empty event")
	}

	for _, record := range event.Records {
	 	LogDynamoDBRecord(record)
	}

	message := fmt.Sprintf("Records processed: %d", len(event.Records))
	return &message, nil
}

func main() {
	lambda.Start(HandleRequest)
}

func LogDynamoDBRecord(record events.DynamoDBEventRecord){
	fmt.Println(record.EventID)
	fmt.Println(record.EventName)
	fmt.Printf("%+v\n", record.Change)
}
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_go_2_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/aws/aws-lambda-go/lambda"
)

type Event struct {
	Events []Record `json:"events"`
}

type Record struct {
	Event struct {
		OperationType string `json:"operationType"`
		NS            struct {
			DB   string `json:"db"`
			Coll string `json:"coll"`
		} `json:"ns"`
		FullDocument interface{} `json:"fullDocument"`
	} `json:"event"`
}

func main() {
	lambda.Start(handler)
}

func handler(ctx context.Context, event Event) (string, error) {
	fmt.Println("Loading function")
	for _, record := range event.Events {
		logDocumentDBEvent(record)
	}

	return "OK", nil
}

func logDocumentDBEvent(record Record) {
	fmt.Printf("Operation type: %s\n", record.Event.OperationType)
	fmt.Printf("db: %s\n", record.Event.NS.DB)
	fmt.Printf("collection: %s\n", record.Event.NS.Coll)
	docBytes, _ := json.MarshalIndent(record.Event.FullDocument, "", "  ")
	fmt.Printf("Full document: %s\n", string(docBytes))
}
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_go_2_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での Amazon MSK イベントの消費。  

```
package main

import (
	"encoding/base64"
	"fmt"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(event events.KafkaEvent) {
	for key, records := range event.Records {
		fmt.Println("Key:", key)

		for _, record := range records {
			fmt.Println("Record:", record)

			decodedValue, _ := base64.StdEncoding.DecodeString(record.Value)
			message := string(decodedValue)
			fmt.Println("Message:", message)
		}
	}
}

func main() {
	lambda.Start(handler)
}
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_go_2_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Go を使用して Lambda で S3 イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"log"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

func handler(ctx context.Context, s3Event events.S3Event) error {
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Printf("failed to load default config: %s", err)
		return err
	}
	s3Client := s3.NewFromConfig(sdkConfig)

	for _, record := range s3Event.Records {
		bucket := record.S3.Bucket.Name
		key := record.S3.Object.URLDecodedKey
		headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput{
			Bucket: &bucket,
			Key:    &key,
		})
		if err != nil {
			log.Printf("error getting head of object %s/%s: %s", bucket, key, err)
			return err
		}
		log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType)
	}

	return nil
}

func main() {
	lambda.Start(handler)
}
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_go_2_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で SNS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, snsEvent events.SNSEvent) {
	for _, record := range snsEvent.Records {
		processMessage(record)
	}
	fmt.Println("done")
}

func processMessage(record events.SNSEventRecord) {
	message := record.SNS.Message
	fmt.Printf("Processed message: %s\n", message)
	// TODO: Process your record here
}

func main() {
	lambda.Start(handler)
}
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_go_2_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package integration_sqs_to_lambda

import (
	"fmt"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(event events.SQSEvent) error {
	for _, record := range event.Records {
		err := processMessage(record)
		if err != nil {
			return err
		}
	}
	fmt.Println("done")
	return nil
}

func processMessage(record events.SQSMessage) error {
	fmt.Printf("Processed message %s\n", record.Body)
	// TODO: Do interesting work based on the new message
	return nil
}

func main() {
	lambda.Start(handler)
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_go_2_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"fmt"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, kinesisEvent events.KinesisEvent) (map[string]interface{}, error) {
	batchItemFailures := []map[string]interface{}{}

	for _, record := range kinesisEvent.Records {
		curRecordSequenceNumber := ""

		// Process your record
		if /* Your record processing condition here */ {
			curRecordSequenceNumber = record.Kinesis.SequenceNumber
		}

		// Add a condition to check if the record processing failed
		if curRecordSequenceNumber != "" {
			batchItemFailures = append(batchItemFailures, map[string]interface{}{"itemIdentifier": curRecordSequenceNumber})
		}
	}

	kinesisBatchResponse := map[string]interface{}{
		"batchItemFailures": batchItemFailures,
	}
	return kinesisBatchResponse, nil
}

func main() {
	lambda.Start(handler)
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_go_2_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

type BatchItemFailure struct {
	ItemIdentifier string `json:"ItemIdentifier"`
}

type BatchResult struct {
	BatchItemFailures []BatchItemFailure `json:"BatchItemFailures"`
}

func HandleRequest(ctx context.Context, event events.DynamoDBEvent) (*BatchResult, error) {
	var batchItemFailures []BatchItemFailure
	curRecordSequenceNumber := ""

	for _, record := range event.Records {
		// Process your record
		curRecordSequenceNumber = record.Change.SequenceNumber
	}

	if curRecordSequenceNumber != "" {
		batchItemFailures = append(batchItemFailures, BatchItemFailure{ItemIdentifier: curRecordSequenceNumber})
	}
	
	batchResult := BatchResult{
		BatchItemFailures: batchItemFailures,
	}

	return &batchResult, nil
}

func main() {
	lambda.Start(HandleRequest)
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_go_2_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"fmt"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, sqsEvent events.SQSEvent) (map[string]interface{}, error) {
	batchItemFailures := []map[string]interface{}{}

	for _, message := range sqsEvent.Records {
		if len(message.Body) > 0 {
			// Your message processing condition here
			fmt.Printf("Successfully processed message: %s\n", message.Body)
		} else {
			// Message processing failed
			fmt.Printf("Failed to process message %s\n", message.MessageId)
			batchItemFailures = append(batchItemFailures, map[string]interface{}{"itemIdentifier": message.MessageId})
		}
	}

	sqsBatchResponse := map[string]interface{}{
		"batchItemFailures": batchItemFailures,
	}
	return sqsBatchResponse, nil
}

func main() {
	lambda.Start(handler)
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_go_2_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Go V2**  
 Go SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-go-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Go V2 を使用した Amazon MSK の例
<a name="go_2_kafka_code_examples"></a>

次のコード例は、Amazon MSK で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_go_2_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での Amazon MSK イベントの消費。  

```
package main

import (
	"encoding/base64"
	"fmt"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(event events.KafkaEvent) {
	for key, records := range event.Records {
		fmt.Println("Key:", key)

		for _, record := range records {
			fmt.Println("Record:", record)

			decodedValue, _ := base64.StdEncoding.DecodeString(record.Value)
			message := string(decodedValue)
			fmt.Println("Message:", message)
		}
	}
}

func main() {
	lambda.Start(handler)
}
```

# SDK for Go V2 を使用したパートナーセントラルのコード例
<a name="go_2_partnercentral-selling_code_examples"></a>

次のコード例は、 Partner Central で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetOpportunity`
<a name="partnercentral-selling_GetOpportunity_go_2_topic"></a>

次のコード例は、`GetOpportunity` を使用する方法を示しています。

**SDK for Go V2**  
オポチュニティを取得します。  

```
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/partnercentralselling"
)

func main() {
	config, err := config.LoadDefaultConfig(context.TODO())

	if err != nil {
		log.Fatal(err)
	}

	config.Region = "us-east-1"

	client := partnercentralselling.NewFromConfig(config)

	output, err := client.GetOpportunity(context.TODO(), &partnercentralselling.GetOpportunityInput{
		Identifier: aws.String("O1111111"),
		Catalog:    aws.String("AWS"),
	})

	if err != nil {
		log.Fatal(err)
	}
	log.Println("printing opportuniy...\n")

	jsonOutput, err := json.MarshalIndent(output, "", "    ")

	fmt.Println(string(jsonOutput))
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[GetOpportunity](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/partnercentralselling#Client.GetOpportunity)」を参照してください。

### `ListOpportunities`
<a name="partnercentral-selling_ListOpportunities_go_2_topic"></a>

次のコード例は、`ListOpportunities` を使用する方法を示しています。

**SDK for Go V2**  
オポチュニティを一覧表示します。  

```
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/partnercentralselling"
)

func main() {
	config, err := config.LoadDefaultConfig(context.TODO())

	if err != nil {
		log.Fatal(err)
	}

	config.Region = "us-east-1"

	client := partnercentralselling.NewFromConfig(config)

	output, err := client.ListOpportunities(context.TODO(), &partnercentralselling.ListOpportunitiesInput{
		MaxResults: aws.Int32(2),
		Catalog:    aws.String("AWS"),
	})

	if err != nil {
		log.Fatal(err)
	}

	jsonOutput, err := json.MarshalIndent(output, "", "    ")
	fmt.Println(string(jsonOutput))
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListOpportunities](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/partnercentralselling#Client.ListOpportunities)」を参照してください。

# SDK for Go V2 を使用した Amazon RDS の例
<a name="go_2_rds_code_examples"></a>

次のコード例は、Amazon RDS で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon RDS
<a name="rds_Hello_go_2_topic"></a>

次のコード例は、Amazon RDS の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/rds"
)

// main uses the AWS SDK for Go V2 to create an Amazon Relational Database Service (Amazon RDS)
// client and list up to 20 DB instances in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	rdsClient := rds.NewFromConfig(sdkConfig)
	const maxInstances = 20
	fmt.Printf("Let's list up to %v DB instances.\n", maxInstances)
	output, err := rdsClient.DescribeDBInstances(ctx,
		&rds.DescribeDBInstancesInput{MaxRecords: aws.Int32(maxInstances)})
	if err != nil {
		fmt.Printf("Couldn't list DB instances: %v\n", err)
		return
	}
	if len(output.DBInstances) == 0 {
		fmt.Println("No DB instances found.")
	} else {
		for _, instance := range output.DBInstances {
			fmt.Printf("DB instance %v has database %v.\n", *instance.DBInstanceIdentifier,
				*instance.DBName)
		}
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBInstances](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBInstances)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="rds_Scenario_GetStartedInstances_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム DB パラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用するように設定した DB インスタンスを作成します。DB インスタンスにはデータベースも含まれています。
+ インスタンスのスナップショットを取得します。
+ インスタンスとパラメータグループを削除します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"fmt"
	"log"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/rds/actions"
	"github.com/google/uuid"
)

// GetStartedInstances is an interactive example that shows you how to use the AWS SDK for Go
// with Amazon Relation Database Service (Amazon RDS) to do the following:
//
//  1. Create a custom DB parameter group and set parameter values.
//  2. Create a DB instance that is configured to use the parameter group. The DB instance
//     also contains a database.
//  3. Take a snapshot of the DB instance.
//  4. Delete the DB instance and parameter group.
type GetStartedInstances struct {
	sdkConfig  aws.Config
	instances  actions.DbInstances
	questioner demotools.IQuestioner
	helper     IScenarioHelper
	isTestRun  bool
}

// NewGetStartedInstances constructs a GetStartedInstances instance from a configuration.
// It uses the specified config to get an Amazon RDS
// client and create wrappers for the actions used in the scenario.
func NewGetStartedInstances(sdkConfig aws.Config, questioner demotools.IQuestioner,
	helper IScenarioHelper) GetStartedInstances {
	rdsClient := rds.NewFromConfig(sdkConfig)
	return GetStartedInstances{
		sdkConfig:  sdkConfig,
		instances:  actions.DbInstances{RdsClient: rdsClient},
		questioner: questioner,
		helper:     helper,
	}
}

// Run runs the interactive scenario.
func (scenario GetStartedInstances) Run(ctx context.Context, dbEngine string, parameterGroupName string,
	instanceName string, dbName string) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon Relational Database Service (Amazon RDS) DB Instance demo.")
	log.Println(strings.Repeat("-", 88))

	parameterGroup := scenario.CreateParameterGroup(ctx, dbEngine, parameterGroupName)
	scenario.SetUserParameters(ctx, parameterGroupName)
	instance := scenario.CreateInstance(ctx, instanceName, dbEngine, dbName, parameterGroup)
	scenario.DisplayConnection(instance)
	scenario.CreateSnapshot(ctx, instance)
	scenario.Cleanup(ctx, instance, parameterGroup)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}

// CreateParameterGroup shows how to get available engine versions for a specified
// database engine and create a DB parameter group that is compatible with a
// selected engine family.
func (scenario GetStartedInstances) CreateParameterGroup(ctx context.Context, dbEngine string,
	parameterGroupName string) *types.DBParameterGroup {

	log.Printf("Checking for an existing DB parameter group named %v.\n",
		parameterGroupName)
	parameterGroup, err := scenario.instances.GetParameterGroup(ctx, parameterGroupName)
	if err != nil {
		panic(err)
	}
	if parameterGroup == nil {
		log.Printf("Getting available database engine versions for %v.\n", dbEngine)
		engineVersions, err := scenario.instances.GetEngineVersions(ctx, dbEngine, "")
		if err != nil {
			panic(err)
		}

		familySet := map[string]struct{}{}
		for _, family := range engineVersions {
			familySet[*family.DBParameterGroupFamily] = struct{}{}
		}
		var families []string
		for family := range familySet {
			families = append(families, family)
		}
		sort.Strings(families)
		familyIndex := scenario.questioner.AskChoice("Which family do you want to use?\n", families)
		log.Println("Creating a DB parameter group.")
		_, err = scenario.instances.CreateParameterGroup(
			ctx, parameterGroupName, families[familyIndex], "Example parameter group.")
		if err != nil {
			panic(err)
		}
		parameterGroup, err = scenario.instances.GetParameterGroup(ctx, parameterGroupName)
		if err != nil {
			panic(err)
		}
	}
	log.Printf("Parameter group %v:\n", *parameterGroup.DBParameterGroupFamily)
	log.Printf("\tName: %v\n", *parameterGroup.DBParameterGroupName)
	log.Printf("\tARN: %v\n", *parameterGroup.DBParameterGroupArn)
	log.Printf("\tFamily: %v\n", *parameterGroup.DBParameterGroupFamily)
	log.Printf("\tDescription: %v\n", *parameterGroup.Description)
	log.Println(strings.Repeat("-", 88))
	return parameterGroup
}

// SetUserParameters shows how to get the parameters contained in a custom parameter
// group and update some of the parameter values in the group.
func (scenario GetStartedInstances) SetUserParameters(ctx context.Context, parameterGroupName string) {
	log.Println("Let's set some parameter values in your parameter group.")
	dbParameters, err := scenario.instances.GetParameters(ctx, parameterGroupName, "")
	if err != nil {
		panic(err)
	}
	var updateParams []types.Parameter
	for _, dbParam := range dbParameters {
		if strings.HasPrefix(*dbParam.ParameterName, "auto_increment") &&
			*dbParam.IsModifiable && *dbParam.DataType == "integer" {
			log.Printf("The %v parameter is described as:\n\t%v",
				*dbParam.ParameterName, *dbParam.Description)
			rangeSplit := strings.Split(*dbParam.AllowedValues, "-")
			lower, _ := strconv.Atoi(rangeSplit[0])
			upper, _ := strconv.Atoi(rangeSplit[1])
			newValue := scenario.questioner.AskInt(
				fmt.Sprintf("Enter a value between %v and %v:", lower, upper),
				demotools.InIntRange{Lower: lower, Upper: upper})
			dbParam.ParameterValue = aws.String(strconv.Itoa(newValue))
			updateParams = append(updateParams, dbParam)
		}
	}
	err = scenario.instances.UpdateParameters(ctx, parameterGroupName, updateParams)
	if err != nil {
		panic(err)
	}
	log.Println("To get a list of parameters that you set previously, specify a source of 'user'.")
	userParameters, err := scenario.instances.GetParameters(ctx, parameterGroupName, "user")
	if err != nil {
		panic(err)
	}
	log.Println("Here are the parameters you set:")
	for _, param := range userParameters {
		log.Printf("\t%v: %v\n", *param.ParameterName, *param.ParameterValue)
	}
	log.Println(strings.Repeat("-", 88))
}

// CreateInstance shows how to create a DB instance that contains a database of a
// specified type. The database is also configured to use a custom DB parameter group.
func (scenario GetStartedInstances) CreateInstance(ctx context.Context, instanceName string, dbEngine string,
	dbName string, parameterGroup *types.DBParameterGroup) *types.DBInstance {

	log.Println("Checking for an existing DB instance.")
	instance, err := scenario.instances.GetInstance(ctx, instanceName)
	if err != nil {
		panic(err)
	}
	if instance == nil {
		adminUsername := scenario.questioner.Ask(
			"Enter an administrator username for the database: ", demotools.NotEmpty{})
		adminPassword := scenario.questioner.AskPassword(
			"Enter a password for the administrator (at least 8 characters): ", 7)
		engineVersions, err := scenario.instances.GetEngineVersions(ctx, dbEngine,
			*parameterGroup.DBParameterGroupFamily)
		if err != nil {
			panic(err)
		}
		var engineChoices []string
		for _, engine := range engineVersions {
			engineChoices = append(engineChoices, *engine.EngineVersion)
		}
		engineIndex := scenario.questioner.AskChoice(
			"The available engines for your parameter group are:\n", engineChoices)
		engineSelection := engineVersions[engineIndex]
		instOpts, err := scenario.instances.GetOrderableInstances(ctx, *engineSelection.Engine,
			*engineSelection.EngineVersion)
		if err != nil {
			panic(err)
		}
		optSet := map[string]struct{}{}
		for _, opt := range instOpts {
			if strings.Contains(*opt.DBInstanceClass, "micro") {
				optSet[*opt.DBInstanceClass] = struct{}{}
			}
		}
		var optChoices []string
		for opt := range optSet {
			optChoices = append(optChoices, opt)
		}
		sort.Strings(optChoices)
		optIndex := scenario.questioner.AskChoice(
			"The available micro DB instance classes for your database engine are:\n", optChoices)
		storageType := "standard"
		allocatedStorage := int32(5)
		log.Printf("Creating a DB instance named %v and database %v.\n"+
			"The DB instance is configured to use your custom parameter group %v,\n"+
			"selected engine %v,\n"+
			"selected DB instance class %v,"+
			"and %v GiB of %v storage.\n"+
			"This typically takes several minutes.",
			instanceName, dbName, *parameterGroup.DBParameterGroupName, *engineSelection.EngineVersion,
			optChoices[optIndex], allocatedStorage, storageType)
		instance, err = scenario.instances.CreateInstance(
			ctx, instanceName, dbName, *engineSelection.Engine, *engineSelection.EngineVersion,
			*parameterGroup.DBParameterGroupName, optChoices[optIndex], storageType,
			allocatedStorage, adminUsername, adminPassword)
		if err != nil {
			panic(err)
		}
		for *instance.DBInstanceStatus != "available" {
			scenario.helper.Pause(30)
			instance, err = scenario.instances.GetInstance(ctx, instanceName)
			if err != nil {
				panic(err)
			}
		}
		log.Println("Instance created and available.")
	}
	log.Println("Instance data:")
	log.Printf("\tDBInstanceIdentifier: %v\n", *instance.DBInstanceIdentifier)
	log.Printf("\tARN: %v\n", *instance.DBInstanceArn)
	log.Printf("\tStatus: %v\n", *instance.DBInstanceStatus)
	log.Printf("\tEngine: %v\n", *instance.Engine)
	log.Printf("\tEngine version: %v\n", *instance.EngineVersion)
	log.Println(strings.Repeat("-", 88))
	return instance
}

// DisplayConnection displays connection information about a DB instance and tips
// on how to connect to it.
func (scenario GetStartedInstances) DisplayConnection(instance *types.DBInstance) {
	log.Println(
		"You can now connect to your database by using your favorite MySQL client.\n" +
			"One way to connect is by using the 'mysql' shell on an Amazon EC2 instance\n" +
			"that is running in the same VPC as your DB instance. Pass the endpoint,\n" +
			"port, and administrator username to 'mysql'. Then, enter your password\n" +
			"when prompted:")
	log.Printf("\n\tmysql -h %v -P %v -u %v -p\n",
		*instance.Endpoint.Address, instance.Endpoint.Port, *instance.MasterUsername)
	log.Println("For more information, see the User Guide for RDS:\n" +
		"\thttps://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html#CHAP_GettingStarted.Connecting.MySQL")
	log.Println(strings.Repeat("-", 88))
}

// CreateSnapshot shows how to create a DB instance snapshot and wait until it's available.
func (scenario GetStartedInstances) CreateSnapshot(ctx context.Context, instance *types.DBInstance) {
	if scenario.questioner.AskBool(
		"Do you want to create a snapshot of your DB instance (y/n)? ", "y") {
		snapshotId := fmt.Sprintf("%v-%v", *instance.DBInstanceIdentifier, scenario.helper.UniqueId())
		log.Printf("Creating a snapshot named %v. This typically takes a few minutes.\n", snapshotId)
		snapshot, err := scenario.instances.CreateSnapshot(ctx, *instance.DBInstanceIdentifier, snapshotId)
		if err != nil {
			panic(err)
		}
		for *snapshot.Status != "available" {
			scenario.helper.Pause(30)
			snapshot, err = scenario.instances.GetSnapshot(ctx, snapshotId)
			if err != nil {
				panic(err)
			}
		}
		log.Println("Snapshot data:")
		log.Printf("\tDBSnapshotIdentifier: %v\n", *snapshot.DBSnapshotIdentifier)
		log.Printf("\tARN: %v\n", *snapshot.DBSnapshotArn)
		log.Printf("\tStatus: %v\n", *snapshot.Status)
		log.Printf("\tEngine: %v\n", *snapshot.Engine)
		log.Printf("\tEngine version: %v\n", *snapshot.EngineVersion)
		log.Printf("\tDBInstanceIdentifier: %v\n", *snapshot.DBInstanceIdentifier)
		log.Printf("\tSnapshotCreateTime: %v\n", *snapshot.SnapshotCreateTime)
		log.Println(strings.Repeat("-", 88))
	}
}

// Cleanup shows how to clean up a DB instance and DB parameter group.
// Before the DB parameter group can be deleted, all associated DB instances must first be deleted.
func (scenario GetStartedInstances) Cleanup(
	ctx context.Context, instance *types.DBInstance, parameterGroup *types.DBParameterGroup) {

	if scenario.questioner.AskBool(
		"\nDo you want to delete the database instance and parameter group (y/n)? ", "y") {
		log.Printf("Deleting database instance %v.\n", *instance.DBInstanceIdentifier)
		err := scenario.instances.DeleteInstance(ctx, *instance.DBInstanceIdentifier)
		if err != nil {
			panic(err)
		}
		log.Println(
			"Waiting for the DB instance to delete. This typically takes several minutes.")
		for instance != nil {
			scenario.helper.Pause(30)
			instance, err = scenario.instances.GetInstance(ctx, *instance.DBInstanceIdentifier)
			if err != nil {
				panic(err)
			}
		}
		log.Printf("Deleting parameter group %v.", *parameterGroup.DBParameterGroupName)
		err = scenario.instances.DeleteParameterGroup(ctx, *parameterGroup.DBParameterGroupName)
		if err != nil {
			panic(err)
		}
	}
}

// IScenarioHelper abstracts the function from a scenario so that it
// can be mocked for unit testing.
type IScenarioHelper interface {
	Pause(secs int)
	UniqueId() string
}
type ScenarioHelper struct{}

// Pause waits for the specified number of seconds.
func (helper ScenarioHelper) Pause(secs int) {
	time.Sleep(time.Duration(secs) * time.Second)
}

// UniqueId returns a new UUID.
func (helper ScenarioHelper) UniqueId() string {
	return uuid.New().String()
}
```
Amazon RDS アクションを管理するためにシナリオによって呼び出される関数を定義します。  

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}


// GetParameterGroup gets a DB parameter group by name.
func (instances *DbInstances) GetParameterGroup(ctx context.Context, parameterGroupName string) (
	*types.DBParameterGroup, error) {
	output, err := instances.RdsClient.DescribeDBParameterGroups(
		ctx, &rds.DescribeDBParameterGroupsInput{
			DBParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		var notFoundError *types.DBParameterGroupNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("Parameter group %v does not exist.\n", parameterGroupName)
			err = nil
		} else {
			log.Printf("Error getting parameter group %v: %v\n", parameterGroupName, err)
		}
		return nil, err
	} else {
		return &output.DBParameterGroups[0], err
	}
}



// CreateParameterGroup creates a DB parameter group that is based on the specified
// parameter group family.
func (instances *DbInstances) CreateParameterGroup(
	ctx context.Context, parameterGroupName string, parameterGroupFamily string, description string) (
	*types.DBParameterGroup, error) {

	output, err := instances.RdsClient.CreateDBParameterGroup(ctx,
		&rds.CreateDBParameterGroupInput{
			DBParameterGroupName:   aws.String(parameterGroupName),
			DBParameterGroupFamily: aws.String(parameterGroupFamily),
			Description:            aws.String(description),
		})
	if err != nil {
		log.Printf("Couldn't create parameter group %v: %v\n", parameterGroupName, err)
		return nil, err
	} else {
		return output.DBParameterGroup, err
	}
}



// DeleteParameterGroup deletes the named DB parameter group.
func (instances *DbInstances) DeleteParameterGroup(ctx context.Context, parameterGroupName string) error {
	_, err := instances.RdsClient.DeleteDBParameterGroup(ctx,
		&rds.DeleteDBParameterGroupInput{
			DBParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		log.Printf("Couldn't delete parameter group %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}



// GetParameters gets the parameters that are contained in a DB parameter group.
func (instances *DbInstances) GetParameters(ctx context.Context, parameterGroupName string, source string) (
	[]types.Parameter, error) {

	var output *rds.DescribeDBParametersOutput
	var params []types.Parameter
	var err error
	parameterPaginator := rds.NewDescribeDBParametersPaginator(instances.RdsClient,
		&rds.DescribeDBParametersInput{
			DBParameterGroupName: aws.String(parameterGroupName),
			Source:               aws.String(source),
		})
	for parameterPaginator.HasMorePages() {
		output, err = parameterPaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get parameters for %v: %v\n", parameterGroupName, err)
			break
		} else {
			params = append(params, output.Parameters...)
		}
	}
	return params, err
}



// UpdateParameters updates parameters in a named DB parameter group.
func (instances *DbInstances) UpdateParameters(ctx context.Context, parameterGroupName string, params []types.Parameter) error {
	_, err := instances.RdsClient.ModifyDBParameterGroup(ctx,
		&rds.ModifyDBParameterGroupInput{
			DBParameterGroupName: aws.String(parameterGroupName),
			Parameters:           params,
		})
	if err != nil {
		log.Printf("Couldn't update parameters in %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}



// CreateSnapshot creates a snapshot of a DB instance.
func (instances *DbInstances) CreateSnapshot(ctx context.Context, instanceName string, snapshotName string) (
	*types.DBSnapshot, error) {
	output, err := instances.RdsClient.CreateDBSnapshot(ctx, &rds.CreateDBSnapshotInput{
		DBInstanceIdentifier: aws.String(instanceName),
		DBSnapshotIdentifier: aws.String(snapshotName),
	})
	if err != nil {
		log.Printf("Couldn't create snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return output.DBSnapshot, nil
	}
}



// GetSnapshot gets a DB instance snapshot.
func (instances *DbInstances) GetSnapshot(ctx context.Context, snapshotName string) (*types.DBSnapshot, error) {
	output, err := instances.RdsClient.DescribeDBSnapshots(ctx,
		&rds.DescribeDBSnapshotsInput{
			DBSnapshotIdentifier: aws.String(snapshotName),
		})
	if err != nil {
		log.Printf("Couldn't get snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return &output.DBSnapshots[0], nil
	}
}



// CreateInstance creates a DB instance.
func (instances *DbInstances) CreateInstance(ctx context.Context, instanceName string, dbName string,
	dbEngine string, dbEngineVersion string, parameterGroupName string, dbInstanceClass string,
	storageType string, allocatedStorage int32, adminName string, adminPassword string) (
	*types.DBInstance, error) {
	output, err := instances.RdsClient.CreateDBInstance(ctx, &rds.CreateDBInstanceInput{
		DBInstanceIdentifier: aws.String(instanceName),
		DBName:               aws.String(dbName),
		DBParameterGroupName: aws.String(parameterGroupName),
		Engine:               aws.String(dbEngine),
		EngineVersion:        aws.String(dbEngineVersion),
		DBInstanceClass:      aws.String(dbInstanceClass),
		StorageType:          aws.String(storageType),
		AllocatedStorage:     aws.Int32(allocatedStorage),
		MasterUsername:       aws.String(adminName),
		MasterUserPassword:   aws.String(adminPassword),
	})
	if err != nil {
		log.Printf("Couldn't create instance %v: %v\n", instanceName, err)
		return nil, err
	} else {
		return output.DBInstance, nil
	}
}



// GetInstance gets data about a DB instance.
func (instances *DbInstances) GetInstance(ctx context.Context, instanceName string) (
	*types.DBInstance, error) {
	output, err := instances.RdsClient.DescribeDBInstances(ctx,
		&rds.DescribeDBInstancesInput{
			DBInstanceIdentifier: aws.String(instanceName),
		})
	if err != nil {
		var notFoundError *types.DBInstanceNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("DB instance %v does not exist.\n", instanceName)
			err = nil
		} else {
			log.Printf("Couldn't get instance %v: %v\n", instanceName, err)
		}
		return nil, err
	} else {
		return &output.DBInstances[0], nil
	}
}



// DeleteInstance deletes a DB instance.
func (instances *DbInstances) DeleteInstance(ctx context.Context, instanceName string) error {
	_, err := instances.RdsClient.DeleteDBInstance(ctx, &rds.DeleteDBInstanceInput{
		DBInstanceIdentifier:   aws.String(instanceName),
		SkipFinalSnapshot:      aws.Bool(true),
		DeleteAutomatedBackups: aws.Bool(true),
	})
	if err != nil {
		log.Printf("Couldn't delete instance %v: %v\n", instanceName, err)
		return err
	} else {
		return nil
	}
}



// GetEngineVersions gets database engine versions that are available for the specified engine
// and parameter group family.
func (instances *DbInstances) GetEngineVersions(ctx context.Context, engine string, parameterGroupFamily string) (
	[]types.DBEngineVersion, error) {
	output, err := instances.RdsClient.DescribeDBEngineVersions(ctx,
		&rds.DescribeDBEngineVersionsInput{
			Engine:                 aws.String(engine),
			DBParameterGroupFamily: aws.String(parameterGroupFamily),
		})
	if err != nil {
		log.Printf("Couldn't get engine versions for %v: %v\n", engine, err)
		return nil, err
	} else {
		return output.DBEngineVersions, nil
	}
}



// GetOrderableInstances uses a paginator to get DB instance options that can be used to create DB instances that are
// compatible with a set of specifications.
func (instances *DbInstances) GetOrderableInstances(ctx context.Context, engine string, engineVersion string) (
	[]types.OrderableDBInstanceOption, error) {

	var output *rds.DescribeOrderableDBInstanceOptionsOutput
	var instanceOptions []types.OrderableDBInstanceOption
	var err error
	orderablePaginator := rds.NewDescribeOrderableDBInstanceOptionsPaginator(instances.RdsClient,
		&rds.DescribeOrderableDBInstanceOptionsInput{
			Engine:        aws.String(engine),
			EngineVersion: aws.String(engineVersion),
		})
	for orderablePaginator.HasMorePages() {
		output, err = orderablePaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get orderable DB instance options: %v\n", err)
			break
		} else {
			instanceOptions = append(instanceOptions, output.OrderableDBInstanceOptions...)
		}
	}
	return instanceOptions, err
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBInstance)
  + [CreateDBParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBParameterGroup)
  + [CreateDBSnapshot](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBSnapshot)
  + [DeleteDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBInstance)
  + [DeleteDBParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBParameterGroup)
  + [DescribeDBEngineVersions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBEngineVersions)
  + [DescribeDBInstances](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBInstances)
  + [DescribeDBParameterGroups](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBParameterGroups)
  + [DescribeDBParameters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBParameters)
  + [DescribeDBSnapshots](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBSnapshots)
  + [DescribeOrderableDBInstanceOptions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeOrderableDBInstanceOptions)
  + [ModifyDBParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.ModifyDBParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_go_2_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// CreateInstance creates a DB instance.
func (instances *DbInstances) CreateInstance(ctx context.Context, instanceName string, dbName string,
	dbEngine string, dbEngineVersion string, parameterGroupName string, dbInstanceClass string,
	storageType string, allocatedStorage int32, adminName string, adminPassword string) (
	*types.DBInstance, error) {
	output, err := instances.RdsClient.CreateDBInstance(ctx, &rds.CreateDBInstanceInput{
		DBInstanceIdentifier: aws.String(instanceName),
		DBName:               aws.String(dbName),
		DBParameterGroupName: aws.String(parameterGroupName),
		Engine:               aws.String(dbEngine),
		EngineVersion:        aws.String(dbEngineVersion),
		DBInstanceClass:      aws.String(dbInstanceClass),
		StorageType:          aws.String(storageType),
		AllocatedStorage:     aws.Int32(allocatedStorage),
		MasterUsername:       aws.String(adminName),
		MasterUserPassword:   aws.String(adminPassword),
	})
	if err != nil {
		log.Printf("Couldn't create instance %v: %v\n", instanceName, err)
		return nil, err
	} else {
		return output.DBInstance, nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBInstance)」を参照してください。

### `CreateDBParameterGroup`
<a name="rds_CreateDBParameterGroup_go_2_topic"></a>

次のコード例は、`CreateDBParameterGroup` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// CreateParameterGroup creates a DB parameter group that is based on the specified
// parameter group family.
func (instances *DbInstances) CreateParameterGroup(
	ctx context.Context, parameterGroupName string, parameterGroupFamily string, description string) (
	*types.DBParameterGroup, error) {

	output, err := instances.RdsClient.CreateDBParameterGroup(ctx,
		&rds.CreateDBParameterGroupInput{
			DBParameterGroupName:   aws.String(parameterGroupName),
			DBParameterGroupFamily: aws.String(parameterGroupFamily),
			Description:            aws.String(description),
		})
	if err != nil {
		log.Printf("Couldn't create parameter group %v: %v\n", parameterGroupName, err)
		return nil, err
	} else {
		return output.DBParameterGroup, err
	}
}
```
+  詳細については、**「AWS SDK for Go API リファレンス」の「[CreateDBParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBParameterGroup)」を参照してください。

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_go_2_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// CreateSnapshot creates a snapshot of a DB instance.
func (instances *DbInstances) CreateSnapshot(ctx context.Context, instanceName string, snapshotName string) (
	*types.DBSnapshot, error) {
	output, err := instances.RdsClient.CreateDBSnapshot(ctx, &rds.CreateDBSnapshotInput{
		DBInstanceIdentifier: aws.String(instanceName),
		DBSnapshotIdentifier: aws.String(snapshotName),
	})
	if err != nil {
		log.Printf("Couldn't create snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return output.DBSnapshot, nil
	}
}
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[CreateDBSnapshot](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.CreateDBSnapshot)」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_go_2_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// DeleteInstance deletes a DB instance.
func (instances *DbInstances) DeleteInstance(ctx context.Context, instanceName string) error {
	_, err := instances.RdsClient.DeleteDBInstance(ctx, &rds.DeleteDBInstanceInput{
		DBInstanceIdentifier:   aws.String(instanceName),
		SkipFinalSnapshot:      aws.Bool(true),
		DeleteAutomatedBackups: aws.Bool(true),
	})
	if err != nil {
		log.Printf("Couldn't delete instance %v: %v\n", instanceName, err)
		return err
	} else {
		return nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteDBInstance](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBInstance)」を参照してください。

### `DeleteDBParameterGroup`
<a name="rds_DeleteDBParameterGroup_go_2_topic"></a>

次のコード例は、`DeleteDBParameterGroup` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// DeleteParameterGroup deletes the named DB parameter group.
func (instances *DbInstances) DeleteParameterGroup(ctx context.Context, parameterGroupName string) error {
	_, err := instances.RdsClient.DeleteDBParameterGroup(ctx,
		&rds.DeleteDBParameterGroupInput{
			DBParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		log.Printf("Couldn't delete parameter group %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}
```
+  詳細については、**「AWS SDK for Go API リファレンス」の「[DeleteDBParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DeleteDBParameterGroup)」を参照してください。

### `DescribeDBEngineVersions`
<a name="rds_DescribeDBEngineVersions_go_2_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// GetEngineVersions gets database engine versions that are available for the specified engine
// and parameter group family.
func (instances *DbInstances) GetEngineVersions(ctx context.Context, engine string, parameterGroupFamily string) (
	[]types.DBEngineVersion, error) {
	output, err := instances.RdsClient.DescribeDBEngineVersions(ctx,
		&rds.DescribeDBEngineVersionsInput{
			Engine:                 aws.String(engine),
			DBParameterGroupFamily: aws.String(parameterGroupFamily),
		})
	if err != nil {
		log.Printf("Couldn't get engine versions for %v: %v\n", engine, err)
		return nil, err
	} else {
		return output.DBEngineVersions, nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBEngineVersions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_go_2_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// GetInstance gets data about a DB instance.
func (instances *DbInstances) GetInstance(ctx context.Context, instanceName string) (
	*types.DBInstance, error) {
	output, err := instances.RdsClient.DescribeDBInstances(ctx,
		&rds.DescribeDBInstancesInput{
			DBInstanceIdentifier: aws.String(instanceName),
		})
	if err != nil {
		var notFoundError *types.DBInstanceNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("DB instance %v does not exist.\n", instanceName)
			err = nil
		} else {
			log.Printf("Couldn't get instance %v: %v\n", instanceName, err)
		}
		return nil, err
	} else {
		return &output.DBInstances[0], nil
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeDBInstances](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBInstances)」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_go_2_topic"></a>

次のコード例は、`DescribeDBParameterGroups` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// GetParameterGroup gets a DB parameter group by name.
func (instances *DbInstances) GetParameterGroup(ctx context.Context, parameterGroupName string) (
	*types.DBParameterGroup, error) {
	output, err := instances.RdsClient.DescribeDBParameterGroups(
		ctx, &rds.DescribeDBParameterGroupsInput{
			DBParameterGroupName: aws.String(parameterGroupName),
		})
	if err != nil {
		var notFoundError *types.DBParameterGroupNotFoundFault
		if errors.As(err, &notFoundError) {
			log.Printf("Parameter group %v does not exist.\n", parameterGroupName)
			err = nil
		} else {
			log.Printf("Error getting parameter group %v: %v\n", parameterGroupName, err)
		}
		return nil, err
	} else {
		return &output.DBParameterGroups[0], err
	}
}
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[DescribeDBParameterGroups](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBParameterGroups)」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_go_2_topic"></a>

次のコード例は、`DescribeDBParameters` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// GetParameters gets the parameters that are contained in a DB parameter group.
func (instances *DbInstances) GetParameters(ctx context.Context, parameterGroupName string, source string) (
	[]types.Parameter, error) {

	var output *rds.DescribeDBParametersOutput
	var params []types.Parameter
	var err error
	parameterPaginator := rds.NewDescribeDBParametersPaginator(instances.RdsClient,
		&rds.DescribeDBParametersInput{
			DBParameterGroupName: aws.String(parameterGroupName),
			Source:               aws.String(source),
		})
	for parameterPaginator.HasMorePages() {
		output, err = parameterPaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get parameters for %v: %v\n", parameterGroupName, err)
			break
		} else {
			params = append(params, output.Parameters...)
		}
	}
	return params, err
}
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[DescribeDBParameters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBParameters)」を参照してください。

### `DescribeDBSnapshots`
<a name="rds_DescribeDBSnapshots_go_2_topic"></a>

次のコード例は、`DescribeDBSnapshots` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// GetSnapshot gets a DB instance snapshot.
func (instances *DbInstances) GetSnapshot(ctx context.Context, snapshotName string) (*types.DBSnapshot, error) {
	output, err := instances.RdsClient.DescribeDBSnapshots(ctx,
		&rds.DescribeDBSnapshotsInput{
			DBSnapshotIdentifier: aws.String(snapshotName),
		})
	if err != nil {
		log.Printf("Couldn't get snapshot %v: %v\n", snapshotName, err)
		return nil, err
	} else {
		return &output.DBSnapshots[0], nil
	}
}
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[DescribeDBSnapshots](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeDBSnapshots)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="rds_DescribeOrderableDBInstanceOptions_go_2_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// GetOrderableInstances uses a paginator to get DB instance options that can be used to create DB instances that are
// compatible with a set of specifications.
func (instances *DbInstances) GetOrderableInstances(ctx context.Context, engine string, engineVersion string) (
	[]types.OrderableDBInstanceOption, error) {

	var output *rds.DescribeOrderableDBInstanceOptionsOutput
	var instanceOptions []types.OrderableDBInstanceOption
	var err error
	orderablePaginator := rds.NewDescribeOrderableDBInstanceOptionsPaginator(instances.RdsClient,
		&rds.DescribeOrderableDBInstanceOptionsInput{
			Engine:        aws.String(engine),
			EngineVersion: aws.String(engineVersion),
		})
	for orderablePaginator.HasMorePages() {
		output, err = orderablePaginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get orderable DB instance options: %v\n", err)
			break
		} else {
			instanceOptions = append(instanceOptions, output.OrderableDBInstanceOptions...)
		}
	}
	return instanceOptions, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBParameterGroup`
<a name="rds_ModifyDBParameterGroup_go_2_topic"></a>

次のコード例は、`ModifyDBParameterGroup` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/rds#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/rds"
	"github.com/aws/aws-sdk-go-v2/service/rds/types"
)

type DbInstances struct {
	RdsClient *rds.Client
}



// UpdateParameters updates parameters in a named DB parameter group.
func (instances *DbInstances) UpdateParameters(ctx context.Context, parameterGroupName string, params []types.Parameter) error {
	_, err := instances.RdsClient.ModifyDBParameterGroup(ctx,
		&rds.ModifyDBParameterGroupInput{
			DBParameterGroupName: aws.String(parameterGroupName),
			Parameters:           params,
		})
	if err != nil {
		log.Printf("Couldn't update parameters in %v: %v\n", parameterGroupName, err)
		return err
	} else {
		return nil
	}
}
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[ModifyDBParameterGroup](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/rds#Client.ModifyDBParameterGroup)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_go_2_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
/*
Golang v2 code here.
*/

package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
	"os"

	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/feature/rds/auth"
	_ "github.com/go-sql-driver/mysql"
)

type MyEvent struct {
	Name string `json:"name"`
}

func HandleRequest(event *MyEvent) (map[string]interface{}, error) {

	var dbName string = os.Getenv("DatabaseName")
	var dbUser string = os.Getenv("DatabaseUser")
	var dbHost string = os.Getenv("DBHost") // Add hostname without https
	var dbPort int = os.Getenv("Port")      // Add port number
	var dbEndpoint string = fmt.Sprintf("%s:%d", dbHost, dbPort)
	var region string = os.Getenv("AWS_REGION")

	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		panic("configuration error: " + err.Error())
	}

	authenticationToken, err := auth.BuildAuthToken(
		context.TODO(), dbEndpoint, region, dbUser, cfg.Credentials)
	if err != nil {
		panic("failed to create authentication token: " + err.Error())
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true&allowCleartextPasswords=true",
		dbUser, authenticationToken, dbEndpoint, dbName,
	)

	db, err := sql.Open("mysql", dsn)
	if err != nil {
		panic(err)
	}

	defer db.Close()

	var sum int
	err = db.QueryRow("SELECT ?+? AS sum", 3, 2).Scan(&sum)
	if err != nil {
		panic(err)
	}
	s := fmt.Sprint(sum)
	message := fmt.Sprintf("The selected sum is: %s", s)

	messageBytes, err := json.Marshal(message)
	if err != nil {
		return nil, err
	}

	messageString := string(messageBytes)
	return map[string]interface{}{
		"statusCode": 200,
		"headers":    map[string]string{"Content-Type": "application/json"},
		"body":       messageString,
	}, nil
}

func main() {
	lambda.Start(HandleRequest)
}
```

# SDK for Go V2 を使用した Amazon Redshift の例
<a name="go_2_redshift_code_examples"></a>

次のコード例は、Amazon Redshift で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Redshift
<a name="redshift_Hello_go_2_topic"></a>

次のコード例は、Amazon Redshift の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/redshift#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/redshift"
)

// main uses the AWS SDK for Go V2 to create a Redshift client
// and list up to 10 clusters in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	redshiftClient := redshift.NewFromConfig(sdkConfig)
	count := 20
	fmt.Printf("Let's list up to %v clusters for your account.\n", count)
	result, err := redshiftClient.DescribeClusters(ctx, &redshift.DescribeClustersInput{
		MaxRecords: aws.Int32(int32(count)),
	})
	if err != nil {
		fmt.Printf("Couldn't list clusters for your account. Here's why: %v\n", err)
		return
	}
	if len(result.Clusters) == 0 {
		fmt.Println("You don't have any clusters!")
		return
	}
	for _, cluster := range result.Clusters {
		fmt.Printf("\t%v : %v\n", *cluster.ClusterIdentifier, *cluster.ClusterStatus)
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeClusters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.DescribeClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="redshift_Scenario_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Redshift クラスターを作成します。
+ クラスター内のデータベースを一覧表示します。
+ Movies という名前のテーブルを作成します。
+ Movies テーブルにデータを入力します。
+ Movies テーブルに対して年に基づくクエリを実行します。
+ Redshift クラスターを変更します。
+ Amazon Redshift クラスターを削除します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/redshift#code-examples)での設定と実行の方法を確認してください。

```
package scenarios

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"math/rand"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	redshift_types "github.com/aws/aws-sdk-go-v2/service/redshift/types"
	redshiftdata_types "github.com/aws/aws-sdk-go-v2/service/redshiftdata/types"
	"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/redshift/actions"

	"github.com/aws/aws-sdk-go-v2/service/redshift"
	"github.com/aws/aws-sdk-go-v2/service/redshiftdata"
)

// IScenarioHelper abstracts input and wait functions from a scenario so that they
// can be mocked for unit testing.
type IScenarioHelper interface {
	GetName() string
}

const rMax = 100000

type ScenarioHelper struct {
	Prefix string
	Random *rand.Rand
}

// GetName returns a unique name formed of a prefix and a random number.
func (helper ScenarioHelper) GetName() string {
	return fmt.Sprintf("%v%v", helper.Prefix, helper.Random.Intn(rMax))
}

// RedshiftBasicsScenario separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type RedshiftBasicsScenario struct {
	sdkConfig         aws.Config
	helper            IScenarioHelper
	questioner        demotools.IQuestioner
	pauser            demotools.IPausable
	filesystem        demotools.IFileSystem
	redshiftActor     *actions.RedshiftActions
	redshiftDataActor *actions.RedshiftDataActions
	secretsmanager    *SecretsManager
}

// SecretsManager is used to retrieve username and password information from a secure service.
type SecretsManager struct {
	SecretsManagerClient *secretsmanager.Client
}

// RedshiftBasics constructs a new Redshift Basics runner.
func RedshiftBasics(sdkConfig aws.Config, questioner demotools.IQuestioner, pauser demotools.IPausable, filesystem demotools.IFileSystem, helper IScenarioHelper) RedshiftBasicsScenario {
	scenario := RedshiftBasicsScenario{
		sdkConfig:         sdkConfig,
		helper:            helper,
		questioner:        questioner,
		pauser:            pauser,
		filesystem:        filesystem,
		secretsmanager:    &SecretsManager{SecretsManagerClient: secretsmanager.NewFromConfig(sdkConfig)},
		redshiftActor:     &actions.RedshiftActions{RedshiftClient: redshift.NewFromConfig(sdkConfig)},
		redshiftDataActor: &actions.RedshiftDataActions{RedshiftDataClient: redshiftdata.NewFromConfig(sdkConfig)},
	}
	return scenario
}


// Movie makes it easier to use Movie objects given in json format.
type Movie struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Year  int    `json:"year"`
}


// User makes it easier to get the User data back from SecretsManager and use it later.
type User struct {
	Username string `json:"userName"`
	Password string `json:"userPassword"`
}

// Run runs the RedshiftBasics interactive example that shows you how to use Amazon
// Redshift and how to interact with its common endpoints.
//
// 0. Retrieve username and password information to access Redshift.
// 1. Create a cluster.
// 2. Wait for the cluster to become available.
// 3. List the available databases in the region.
// 4. Create a table named "Movies" in the "dev" database.
// 5. Populate the movies table from the "movies.json" file.
// 6. Query the movies table by year.
// 7. Modify the cluster's maintenance window.
// 8. Optionally clean up all resources created during this demo.
//
// This example creates an Amazon Redshift service client from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// It uses a questioner from the `demotools` package to get input during the example.
// This package can be found in the ..\..\demotools folder of this repo.
func (runner *RedshiftBasicsScenario) Run(ctx context.Context) {

	user := User{}
	secretId := "s3express/basics/secrets"
	clusterId := "demo-cluster-1"
	maintenanceWindow := "wed:07:30-wed:08:00"
	databaseName := "dev"
	tableName := "Movies"
	fileName := "Movies.json"
	nodeType := "ra3.xlplus"
	clusterType := "single-node"

	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			_, isMock := runner.questioner.(*demotools.MockQuestioner)
			if isMock || runner.questioner.AskBool("Do you want to see the full error message (y/n)?", "y") {
				log.Println(r)
			}
			runner.cleanUpResources(ctx, clusterId, databaseName, tableName, user.Username, runner.questioner)
		}
	}()

	// Retrieve the userName and userPassword from SecretsManager
	output, err := runner.secretsmanager.SecretsManagerClient.GetSecretValue(ctx, &secretsmanager.GetSecretValueInput{
		SecretId: aws.String(secretId),
	})
	if err != nil {
		log.Printf("There was a problem getting the secret value: %s", err)
		log.Printf("Please make sure to create a secret named 's3express/basics/secrets' with keys of 'userName' and 'userPassword'.")
		panic(err)
	}

	err = json.Unmarshal([]byte(*output.SecretString), &user)
	if err != nil {
		log.Printf("There was a problem parsing the secret value from JSON: %s", err)
		panic(err)
	}

	// Create the Redshift cluster
	_, err = runner.redshiftActor.CreateCluster(ctx, clusterId, user.Username, user.Password, nodeType, clusterType, true)
	if err != nil {
		var clusterAlreadyExistsFault *redshift_types.ClusterAlreadyExistsFault
		if errors.As(err, &clusterAlreadyExistsFault) {
			log.Println("Cluster already exists. Continuing.")
		} else {
			log.Println("Error creating cluster.")
			panic(err)
		}
	}

	// Wait for the cluster to become available
	waiter := redshift.NewClusterAvailableWaiter(runner.redshiftActor.RedshiftClient)
	err = waiter.Wait(ctx, &redshift.DescribeClustersInput{
		ClusterIdentifier: aws.String(clusterId),
	}, 5*time.Minute)
	if err != nil {
		log.Println("An error occurred waiting for the cluster.")
		panic(err)
	}

	// Get some info about the cluster
	describeOutput, err := runner.redshiftActor.DescribeClusters(ctx, clusterId)
	if err != nil {
		log.Println("Something went wrong trying to get information about the cluster.")
		panic(err)
	}
	log.Println("Here's some information about the cluster.")
	log.Printf("The cluster's status is %s", *describeOutput.Clusters[0].ClusterStatus)
	log.Printf("The cluster was created at %s", *describeOutput.Clusters[0].ClusterCreateTime)

	// List databases
	log.Println("List databases in", clusterId)
	runner.questioner.Ask("Press Enter to continue...")
	err = runner.redshiftDataActor.ListDatabases(ctx, clusterId, databaseName, user.Username)
	if err != nil {
		log.Printf("Failed to list databases: %v\n", err)
		panic(err)
	}

	// Create the "Movies" table
	log.Println("Now you will create a table named " + tableName + ".")
	runner.questioner.Ask("Press Enter to continue...")
	err = nil
	result, err := runner.redshiftDataActor.CreateTable(ctx, clusterId, databaseName, tableName, user.Username, runner.pauser, []string{"title VARCHAR(256)", "year INT"})
	if err != nil {
		log.Printf("Failed to create table: %v\n", err)
		panic(err)
	}

	describeInput := redshiftdata.DescribeStatementInput{
		Id: result.Id,
	}
	query := actions.RedshiftQuery{
		Context: ctx,
		Input:   describeInput,
		Result:  result,
	}
	err = runner.redshiftDataActor.WaitForQueryStatus(query, runner.pauser, true)
	if err != nil {
		log.Printf("Failed to execute query: %v\n", err)
		panic(err)
	}
	log.Printf("Successfully executed query\n")

	// Populate the "Movies" table
	runner.PopulateMoviesTable(ctx, clusterId, databaseName, tableName, user.Username, fileName)

	// Query the "Movies" table by year
	log.Println("Query the Movies table by year.")
	year := runner.questioner.AskInt(
		fmt.Sprintf("Enter a value between %v and %v:", 2012, 2014),
		demotools.InIntRange{Lower: 2012, Upper: 2014})
	runner.QueryMoviesByYear(ctx, clusterId, databaseName, tableName, user.Username, year)

	// Modify the cluster's maintenance window
	runner.redshiftActor.ModifyCluster(ctx, clusterId, maintenanceWindow)

	// Delete the Redshift cluster if confirmed
	runner.cleanUpResources(ctx, clusterId, databaseName, tableName, user.Username, runner.questioner)

	log.Println("Thanks for watching!")
}

// cleanUpResources asks the user if they would like to delete each resource created during the scenario, from most
// impactful to least impactful. If any choice to delete is made, further deletion attempts are skipped.
func (runner *RedshiftBasicsScenario) cleanUpResources(ctx context.Context, clusterId string, databaseName string, tableName string, userName string, questioner demotools.IQuestioner) {
	deleted := false
	var err error = nil
	if questioner.AskBool("Do you want to delete the entire cluster? This will clean up all resources. (y/n)", "y") {
		deleted, err = runner.redshiftActor.DeleteCluster(ctx, clusterId)
		if err != nil {
			log.Printf("Error deleting cluster: %v", err)
		}
	}
	if !deleted && questioner.AskBool("Do you want to delete the dev table? This will clean up all inserted records but keep your cluster intact. (y/n)", "y") {
		deleted, err = runner.redshiftDataActor.DeleteTable(ctx, clusterId, databaseName, tableName, userName)
		if err != nil {
			log.Printf("Error deleting movies table: %v", err)
		}
	}
	if !deleted && questioner.AskBool("Do you want to delete all rows in the Movies table? This will clean up all inserted records but keep your cluster and table intact. (y/n)", "y") {
		deleted, err = runner.redshiftDataActor.DeleteDataRows(ctx, clusterId, databaseName, tableName, userName, runner.pauser)
		if err != nil {
			log.Printf("Error deleting data rows: %v", err)
		}
	}
	if !deleted {
		log.Print("Please manually delete any unwanted resources.")
	}
}


// loadMoviesFromJSON takes the <fileName> file and populates a slice of Movie objects.
func (runner *RedshiftBasicsScenario) loadMoviesFromJSON(fileName string, filesystem demotools.IFileSystem) ([]Movie, error) {
	file, err := filesystem.OpenFile("../../resources/sample_files/" + fileName)
	if err != nil {
		return nil, err
	}
	defer filesystem.CloseFile(file)

	var movies []Movie
	err = json.NewDecoder(file).Decode(&movies)
	if err != nil {
		return nil, err
	}

	return movies, nil
}



// PopulateMoviesTable reads data from the <fileName> file and inserts records into the "Movies" table.
func (runner *RedshiftBasicsScenario) PopulateMoviesTable(ctx context.Context, clusterId string, databaseName string, tableName string, userName string, fileName string) {
	log.Println("Populate the " + tableName + " table using the " + fileName + " file.")
	numRecords := runner.questioner.AskInt(
		fmt.Sprintf("Enter a value between %v and %v:", 10, 100),
		demotools.InIntRange{Lower: 10, Upper: 100})

	movies, err := runner.loadMoviesFromJSON(fileName, runner.filesystem)
	if err != nil {
		log.Printf("Failed to load movies from JSON: %v\n", err)
		panic(err)
	}

	var sqlStatements []string

	for i, movie := range movies {
		if i >= numRecords {
			break
		}

		sqlStatement := fmt.Sprintf(`INSERT INTO %s (title, year) VALUES ('%s', %d);`,
			tableName,
			strings.Replace(movie.Title, "'", "''", -1), // Double any single quotes to escape them
			movie.Year)

		sqlStatements = append(sqlStatements, sqlStatement)
	}

	input := &redshiftdata.BatchExecuteStatementInput{
		ClusterIdentifier: aws.String(clusterId),
		Database:          aws.String(databaseName),
		DbUser:            aws.String(userName),
		Sqls:              sqlStatements,
	}

	result, err := runner.redshiftDataActor.ExecuteBatchStatement(ctx, *input)
	if err != nil {
		log.Printf("Failed to execute batch statement: %v\n", err)
		panic(err)
	}

	describeInput := redshiftdata.DescribeStatementInput{
		Id: result.Id,
	}

	query := actions.RedshiftQuery{
		Context: ctx,
		Result:  result,
		Input:   describeInput,
	}
	err = runner.redshiftDataActor.WaitForQueryStatus(query, runner.pauser, true)
	if err != nil {
		log.Printf("Failed to execute batch insert query: %v\n", err)
		return
	}
	log.Printf("Successfully executed batch statement\n")

	log.Printf("%d records were added to the Movies table.\n", numRecords)
}



// QueryMoviesByYear retrieves only movies from the "Movies" table which match the given year.
func (runner *RedshiftBasicsScenario) QueryMoviesByYear(ctx context.Context, clusterId string, databaseName string, tableName string, userName string, year int) {

	sqlStatement := fmt.Sprintf(`SELECT title FROM %s WHERE year = %d;`, tableName, year)

	input := &redshiftdata.ExecuteStatementInput{
		ClusterIdentifier: aws.String(clusterId),
		Database:          aws.String(databaseName),
		DbUser:            aws.String(userName),
		Sql:               aws.String(sqlStatement),
	}

	result, err := runner.redshiftDataActor.ExecuteStatement(ctx, *input)
	if err != nil {
		log.Printf("Failed to query movies: %v\n", err)
		panic(err)
	}

	log.Println("The identifier of the statement is ", *result.Id)

	describeInput := redshiftdata.DescribeStatementInput{
		Id: result.Id,
	}

	query := actions.RedshiftQuery{
		Context: ctx,
		Input:   describeInput,
		Result:  result,
	}
	err = runner.redshiftDataActor.WaitForQueryStatus(query, runner.pauser, true)
	if err != nil {
		log.Printf("Failed to execute query: %v\n", err)
		panic(err)
	}
	log.Printf("Successfully executed query\n")

	getResultOutput, err := runner.redshiftDataActor.GetStatementResult(ctx, *result.Id)
	if err != nil {
		log.Printf("Failed to query movies: %v\n", err)
		panic(err)
	}
	for _, row := range getResultOutput.Records {
		for _, col := range row {
			title, ok := col.(*redshiftdata_types.FieldMemberStringValue)
			if !ok {
				log.Println("Failed to parse the field")
			} else {
				log.Printf("The Movie title field is %s\n", title.Value)
			}
		}
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [CreateCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.CreateCluster)
  + [DescribeClusters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.DescribeClusters)
  + [DescribeStatement](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.DescribeStatement)
  + [ExecuteStatement](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.ExecuteStatement)
  + [GetStatementResult](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.GetStatementResult)
  + [ListDatabasesPaginator](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.ListDatabasesPaginator)
  + [ModifyCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.ModifyCluster)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="redshift_CreateCluster_go_2_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/redshift#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/redshift"
	"github.com/aws/aws-sdk-go-v2/service/redshift/types"
)



// RedshiftActions wraps Redshift service actions.
type RedshiftActions struct {
	RedshiftClient *redshift.Client
}



// CreateCluster sends a request to create a cluster with the given clusterId using the provided credentials.
func (actor RedshiftActions) CreateCluster(ctx context.Context, clusterId string, userName string, userPassword string, nodeType string, clusterType string, publiclyAccessible bool) (*redshift.CreateClusterOutput, error) {
	// Create a new Redshift cluster
	input := &redshift.CreateClusterInput{
		ClusterIdentifier:  aws.String(clusterId),
		MasterUserPassword: aws.String(userPassword),
		MasterUsername:     aws.String(userName),
		NodeType:           aws.String(nodeType),
		ClusterType:        aws.String(clusterType),
		PubliclyAccessible: aws.Bool(publiclyAccessible),
	}
	var opErr *types.ClusterAlreadyExistsFault
	output, err := actor.RedshiftClient.CreateCluster(ctx, input)
	if err != nil && errors.As(err, &opErr) {
		log.Println("Cluster already exists")
		return nil, nil
	} else if err != nil {
		log.Printf("Failed to create Redshift cluster: %v\n", err)
		return nil, err
	}

	log.Printf("Created cluster %s\n", *output.Cluster.ClusterIdentifier)
	return output, nil
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.CreateCluster)」を参照してください。

### `DeleteCluster`
<a name="redshift_DeleteCluster_go_2_topic"></a>

次のコード例は、`DeleteCluster` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/redshift#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/redshift"
	"github.com/aws/aws-sdk-go-v2/service/redshift/types"
)



// RedshiftActions wraps Redshift service actions.
type RedshiftActions struct {
	RedshiftClient *redshift.Client
}



// DeleteCluster deletes the given cluster.
func (actor RedshiftActions) DeleteCluster(ctx context.Context, clusterId string) (bool, error) {
	input := redshift.DeleteClusterInput{
		ClusterIdentifier:        aws.String(clusterId),
		SkipFinalClusterSnapshot: aws.Bool(true),
	}
	_, err := actor.RedshiftClient.DeleteCluster(ctx, &input)
	var opErr *types.ClusterNotFoundFault
	if err != nil && errors.As(err, &opErr) {
		log.Println("Cluster was not found. Where could it be?")
		return false, err
	} else if err != nil {
		log.Printf("Failed to delete Redshift cluster: %v\n", err)
		return false, err
	}
	waiter := redshift.NewClusterDeletedWaiter(actor.RedshiftClient)
	err = waiter.Wait(ctx, &redshift.DescribeClustersInput{
		ClusterIdentifier: aws.String(clusterId),
	}, 5*time.Minute)
	if err != nil {
		log.Printf("Wait time exceeded for deleting cluster, continuing: %v\n", err)
	}
	log.Printf("The cluster %s was deleted\n", clusterId)
	return true, nil
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.DeleteCluster)」を参照してください。

### `DescribeClusters`
<a name="redshift_DescribeClusters_go_2_topic"></a>

次のコード例は、`DescribeClusters` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/redshift#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/redshift"
	"github.com/aws/aws-sdk-go-v2/service/redshift/types"
)



// RedshiftActions wraps Redshift service actions.
type RedshiftActions struct {
	RedshiftClient *redshift.Client
}



// DescribeClusters returns information about the given cluster.
func (actor RedshiftActions) DescribeClusters(ctx context.Context, clusterId string) (*redshift.DescribeClustersOutput, error) {
	input, err := actor.RedshiftClient.DescribeClusters(ctx, &redshift.DescribeClustersInput{
		ClusterIdentifier: aws.String(clusterId),
	})
	var opErr *types.AccessToClusterDeniedFault
	if errors.As(err, &opErr) {
		println("Access to cluster denied.")
		panic(err)
	} else if err != nil {
		println("Failed to describe Redshift clusters.")
		return nil, err
	}
	return input, nil
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DescribeClusters](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.DescribeClusters)」を参照してください。

### `ModifyCluster`
<a name="redshift_ModifyCluster_go_2_topic"></a>

次のコード例は、`ModifyCluster` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/redshift#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"errors"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/redshift"
	"github.com/aws/aws-sdk-go-v2/service/redshift/types"
)



// RedshiftActions wraps Redshift service actions.
type RedshiftActions struct {
	RedshiftClient *redshift.Client
}



// ModifyCluster sets the preferred maintenance window for the given cluster.
func (actor RedshiftActions) ModifyCluster(ctx context.Context, clusterId string, maintenanceWindow string) *redshift.ModifyClusterOutput {
	// Modify the cluster's maintenance window
	input := &redshift.ModifyClusterInput{
		ClusterIdentifier:          aws.String(clusterId),
		PreferredMaintenanceWindow: aws.String(maintenanceWindow),
	}

	var opErr *types.InvalidClusterStateFault
	output, err := actor.RedshiftClient.ModifyCluster(ctx, input)
	if err != nil && errors.As(err, &opErr) {
		log.Println("Cluster is in an invalid state.")
		panic(err)
	} else if err != nil {
		log.Printf("Failed to modify Redshift cluster: %v\n", err)
		panic(err)
	}

	log.Printf("The cluster was successfully modified and now has %s as the maintenance window\n", *output.Cluster.PreferredMaintenanceWindow)
	return output
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ModifyCluster](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/redshift#Client.ModifyCluster)」を参照してください。

# SDK for Go V2 を使用した Amazon S3 の例
<a name="go_2_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_go_2_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/smithy-go"
)

// main uses the AWS SDK for Go V2 to create an Amazon Simple Storage Service
// (Amazon S3) client and list up to 10 buckets in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	s3Client := s3.NewFromConfig(sdkConfig)
	count := 10
	fmt.Printf("Let's list up to %v buckets for your account.\n", count)
	result, err := s3Client.ListBuckets(ctx, &s3.ListBucketsInput{})
	if err != nil {
		var ae smithy.APIError
		if errors.As(err, &ae) && ae.ErrorCode() == "AccessDenied" {
			fmt.Println("You don't have permission to list buckets for this account.")
		} else {
			fmt.Printf("Couldn't list buckets for your account. Here's why: %v\n", err)
		}
		return
	}
	if len(result.Buckets) == 0 {
		fmt.Println("You don't have any buckets!")
	} else {
		if count > len(result.Buckets) {
			count = len(result.Buckets)
		}
		for _, bucket := range result.Buckets[:count] {
			fmt.Printf("\t%v\n", *bucket.Name)
		}
	}
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの「[ListBuckets](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.ListBuckets)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。
シナリオで使用されるバケットアクションとオブジェクトアクションをラップする構造体を定義します。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// ListBuckets lists the buckets in the current account.
func (basics BucketBasics) ListBuckets(ctx context.Context) ([]types.Bucket, error) {
	var err error
	var output *s3.ListBucketsOutput
	var buckets []types.Bucket
	bucketPaginator := s3.NewListBucketsPaginator(basics.S3Client, &s3.ListBucketsInput{})
	for bucketPaginator.HasMorePages() {
		output, err = bucketPaginator.NextPage(ctx)
		if err != nil {
			var apiErr smithy.APIError
			if errors.As(err, &apiErr) && apiErr.ErrorCode() == "AccessDenied" {
				fmt.Println("You don't have permission to list buckets for this account.")
				err = apiErr
			} else {
				log.Printf("Couldn't list buckets for your account. Here's why: %v\n", err)
			}
			break
		} else {
			buckets = append(buckets, output.Buckets...)
		}
	}
	return buckets, err
}



// BucketExists checks whether a bucket exists in the current account.
func (basics BucketBasics) BucketExists(ctx context.Context, bucketName string) (bool, error) {
	_, err := basics.S3Client.HeadBucket(ctx, &s3.HeadBucketInput{
		Bucket: aws.String(bucketName),
	})
	exists := true
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NotFound:
				log.Printf("Bucket %v is available.\n", bucketName)
				exists = false
				err = nil
			default:
				log.Printf("Either you don't have access to bucket %v or another error occurred. "+
					"Here's what happened: %v\n", bucketName, err)
			}
		}
	} else {
		log.Printf("Bucket %v exists and you already own it.", bucketName)
	}

	return exists, err
}



// CreateBucket creates a bucket with the specified name in the specified Region.
func (basics BucketBasics) CreateBucket(ctx context.Context, name string, region string) error {
	_, err := basics.S3Client.CreateBucket(ctx, &s3.CreateBucketInput{
		Bucket: aws.String(name),
		CreateBucketConfiguration: &types.CreateBucketConfiguration{
			LocationConstraint: types.BucketLocationConstraint(region),
		},
	})
	if err != nil {
		var owned *types.BucketAlreadyOwnedByYou
		var exists *types.BucketAlreadyExists
		if errors.As(err, &owned) {
			log.Printf("You already own bucket %s.\n", name)
			err = owned
		} else if errors.As(err, &exists) {
			log.Printf("Bucket %s already exists.\n", name)
			err = exists
		}
	} else {
		err = s3.NewBucketExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(name)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to exist.\n", name)
		}
	}
	return err
}



// UploadFile reads from a file and puts the data into an object in a bucket.
func (basics BucketBasics) UploadFile(ctx context.Context, bucketName string, objectKey string, fileName string) error {
	file, err := os.Open(fileName)
	if err != nil {
		log.Printf("Couldn't open file %v to upload. Here's why: %v\n", fileName, err)
	} else {
		defer file.Close()
		_, err = basics.S3Client.PutObject(ctx, &s3.PutObjectInput{
			Bucket: aws.String(bucketName),
			Key:    aws.String(objectKey),
			Body:   file,
		})
		if err != nil {
			var apiErr smithy.APIError
			if errors.As(err, &apiErr) && apiErr.ErrorCode() == "EntityTooLarge" {
				log.Printf("Error while uploading object to %s. The object is too large.\n"+
					"To upload objects larger than 5GB, use the S3 console (160GB max)\n"+
					"or the multipart upload API (5TB max).", bucketName)
			} else {
				log.Printf("Couldn't upload file %v to %v:%v. Here's why: %v\n",
					fileName, bucketName, objectKey, err)
			}
		} else {
			err = s3.NewObjectExistsWaiter(basics.S3Client).Wait(
				ctx, &s3.HeadObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectKey)}, time.Minute)
			if err != nil {
				log.Printf("Failed attempt to wait for object %s to exist.\n", objectKey)
			}
		}
	}
	return err
}



// UploadLargeObject uses an upload manager to upload data to an object in a bucket.
// The upload manager breaks large data into parts and uploads the parts concurrently.
func (basics BucketBasics) UploadLargeObject(ctx context.Context, bucketName string, objectKey string, largeObject []byte) error {
	largeBuffer := bytes.NewReader(largeObject)
	var partMiBs int64 = 10
	uploader := manager.NewUploader(basics.S3Client, func(u *manager.Uploader) {
		u.PartSize = partMiBs * 1024 * 1024
	})
	_, err := uploader.Upload(ctx, &s3.PutObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
		Body:   largeBuffer,
	})
	if err != nil {
		var apiErr smithy.APIError
		if errors.As(err, &apiErr) && apiErr.ErrorCode() == "EntityTooLarge" {
			log.Printf("Error while uploading object to %s. The object is too large.\n"+
				"The maximum size for a multipart upload is 5TB.", bucketName)
		} else {
			log.Printf("Couldn't upload large object to %v:%v. Here's why: %v\n",
				bucketName, objectKey, err)
		}
	} else {
		err = s3.NewObjectExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectKey)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s to exist.\n", objectKey)
		}
	}

	return err
}



// DownloadFile gets an object from a bucket and stores it in a local file.
func (basics BucketBasics) DownloadFile(ctx context.Context, bucketName string, objectKey string, fileName string) error {
	result, err := basics.S3Client.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	})
	if err != nil {
		var noKey *types.NoSuchKey
		if errors.As(err, &noKey) {
			log.Printf("Can't get object %s from bucket %s. No such key exists.\n", objectKey, bucketName)
			err = noKey
		} else {
			log.Printf("Couldn't get object %v:%v. Here's why: %v\n", bucketName, objectKey, err)
		}
		return err
	}
	defer result.Body.Close()
	file, err := os.Create(fileName)
	if err != nil {
		log.Printf("Couldn't create file %v. Here's why: %v\n", fileName, err)
		return err
	}
	defer file.Close()
	body, err := io.ReadAll(result.Body)
	if err != nil {
		log.Printf("Couldn't read object body from %v. Here's why: %v\n", objectKey, err)
	}
	_, err = file.Write(body)
	return err
}



// DownloadLargeObject uses a download manager to download an object from a bucket.
// The download manager gets the data in parts and writes them to a buffer until all of
// the data has been downloaded.
func (basics BucketBasics) DownloadLargeObject(ctx context.Context, bucketName string, objectKey string) ([]byte, error) {
	var partMiBs int64 = 10
	downloader := manager.NewDownloader(basics.S3Client, func(d *manager.Downloader) {
		d.PartSize = partMiBs * 1024 * 1024
	})
	buffer := manager.NewWriteAtBuffer([]byte{})
	_, err := downloader.Download(ctx, buffer, &s3.GetObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	})
	if err != nil {
		log.Printf("Couldn't download large object from %v:%v. Here's why: %v\n",
			bucketName, objectKey, err)
	}
	return buffer.Bytes(), err
}



// CopyToFolder copies an object in a bucket to a subfolder in the same bucket.
func (basics BucketBasics) CopyToFolder(ctx context.Context, bucketName string, objectKey string, folderName string) error {
	objectDest := fmt.Sprintf("%v/%v", folderName, objectKey)
	_, err := basics.S3Client.CopyObject(ctx, &s3.CopyObjectInput{
		Bucket:     aws.String(bucketName),
		CopySource: aws.String(fmt.Sprintf("%v/%v", bucketName, objectKey)),
		Key:        aws.String(objectDest),
	})
	if err != nil {
		var notActive *types.ObjectNotInActiveTierError
		if errors.As(err, &notActive) {
			log.Printf("Couldn't copy object %s from %s because the object isn't in the active tier.\n",
				objectKey, bucketName)
			err = notActive
		}
	} else {
		err = s3.NewObjectExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectDest)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s to exist.\n", objectDest)
		}
	}
	return err
}



// CopyToBucket copies an object in a bucket to another bucket.
func (basics BucketBasics) CopyToBucket(ctx context.Context, sourceBucket string, destinationBucket string, objectKey string) error {
	_, err := basics.S3Client.CopyObject(ctx, &s3.CopyObjectInput{
		Bucket:     aws.String(destinationBucket),
		CopySource: aws.String(fmt.Sprintf("%v/%v", sourceBucket, objectKey)),
		Key:        aws.String(objectKey),
	})
	if err != nil {
		var notActive *types.ObjectNotInActiveTierError
		if errors.As(err, &notActive) {
			log.Printf("Couldn't copy object %s from %s because the object isn't in the active tier.\n",
				objectKey, sourceBucket)
			err = notActive
		}
	} else {
		err = s3.NewObjectExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadObjectInput{Bucket: aws.String(destinationBucket), Key: aws.String(objectKey)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s to exist.\n", objectKey)
		}
	}
	return err
}



// ListObjects lists the objects in a bucket.
func (basics BucketBasics) ListObjects(ctx context.Context, bucketName string) ([]types.Object, error) {
	var err error
	var output *s3.ListObjectsV2Output
	input := &s3.ListObjectsV2Input{
		Bucket: aws.String(bucketName),
	}
	var objects []types.Object
	objectPaginator := s3.NewListObjectsV2Paginator(basics.S3Client, input)
	for objectPaginator.HasMorePages() {
		output, err = objectPaginator.NextPage(ctx)
		if err != nil {
			var noBucket *types.NoSuchBucket
			if errors.As(err, &noBucket) {
				log.Printf("Bucket %s does not exist.\n", bucketName)
				err = noBucket
			}
			break
		} else {
			objects = append(objects, output.Contents...)
		}
	}
	return objects, err
}



// DeleteObjects deletes a list of objects from a bucket.
func (basics BucketBasics) DeleteObjects(ctx context.Context, bucketName string, objectKeys []string) error {
	var objectIds []types.ObjectIdentifier
	for _, key := range objectKeys {
		objectIds = append(objectIds, types.ObjectIdentifier{Key: aws.String(key)})
	}
	output, err := basics.S3Client.DeleteObjects(ctx, &s3.DeleteObjectsInput{
		Bucket: aws.String(bucketName),
		Delete: &types.Delete{Objects: objectIds, Quiet: aws.Bool(true)},
	})
	if err != nil || len(output.Errors) > 0 {
		log.Printf("Error deleting objects from bucket %s.\n", bucketName)
		if err != nil {
			var noBucket *types.NoSuchBucket
			if errors.As(err, &noBucket) {
				log.Printf("Bucket %s does not exist.\n", bucketName)
				err = noBucket
			}
		} else if len(output.Errors) > 0 {
			for _, outErr := range output.Errors {
				log.Printf("%s: %s\n", *outErr.Key, *outErr.Message)
			}
			err = fmt.Errorf("%s", *output.Errors[0].Message)
		}
	} else {
		for _, delObjs := range output.Deleted {
			err = s3.NewObjectNotExistsWaiter(basics.S3Client).Wait(
				ctx, &s3.HeadObjectInput{Bucket: aws.String(bucketName), Key: delObjs.Key}, time.Minute)
			if err != nil {
				log.Printf("Failed attempt to wait for object %s to be deleted.\n", *delObjs.Key)
			} else {
				log.Printf("Deleted %s.\n", *delObjs.Key)
			}
		}
	}
	return err
}



// DeleteBucket deletes a bucket. The bucket must be empty or an error is returned.
func (basics BucketBasics) DeleteBucket(ctx context.Context, bucketName string) error {
	_, err := basics.S3Client.DeleteBucket(ctx, &s3.DeleteBucketInput{
		Bucket: aws.String(bucketName)})
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucketName)
			err = noBucket
		} else {
			log.Printf("Couldn't delete bucket %v. Here's why: %v\n", bucketName, err)
		}
	} else {
		err = s3.NewBucketNotExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(bucketName)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to be deleted.\n", bucketName)
		} else {
			log.Printf("Deleted %s.\n", bucketName)
		}
	}
	return err
}
```
S3 バケットとオブジェクトの操作方法を示すインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/s3/actions"
)

// RunGetStartedScenario is an interactive example that shows you how to use Amazon
// Simple Storage Service (Amazon S3) to create an S3 bucket and use it to store objects.
//
// 1. Create a bucket.
// 2. Upload a local file to the bucket.
// 3. Download an object to a local file.
// 4. Copy an object to a different folder in the bucket.
// 5. List objects in the bucket.
// 6. Delete all objects in the bucket.
// 7. Delete the bucket.
//
// This example creates an Amazon S3 service client from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// It uses a questioner from the `demotools` package to get input during the example.
// This package can be found in the ..\..\demotools folder of this repo.
func RunGetStartedScenario(ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			_, isMock := questioner.(*demotools.MockQuestioner)
			if isMock || questioner.AskBool("Do you want to see the full error message (y/n)?", "y") {
				log.Println(r)
			}
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon S3 getting started demo.")
	log.Println(strings.Repeat("-", 88))

	s3Client := s3.NewFromConfig(sdkConfig)
	bucketBasics := actions.BucketBasics{S3Client: s3Client}

	count := 10
	log.Printf("Let's list up to %v buckets for your account:", count)
	buckets, err := bucketBasics.ListBuckets(ctx)
	if err != nil {
		panic(err)
	}
	if len(buckets) == 0 {
		log.Println("You don't have any buckets!")
	} else {
		if count > len(buckets) {
			count = len(buckets)
		}
		for _, bucket := range buckets[:count] {
			log.Printf("\t%v\n", *bucket.Name)
		}
	}

	bucketName := questioner.Ask("Let's create a bucket. Enter a name for your bucket:",
		demotools.NotEmpty{})
	bucketExists, err := bucketBasics.BucketExists(ctx, bucketName)
	if err != nil {
		panic(err)
	}
	if !bucketExists {
		err = bucketBasics.CreateBucket(ctx, bucketName, sdkConfig.Region)
		if err != nil {
			panic(err)
		} else {
			log.Println("Bucket created.")
		}
	}
	log.Println(strings.Repeat("-", 88))

	fmt.Println("Let's upload a file to your bucket.")
	smallFile := questioner.Ask("Enter the path to a file you want to upload:",
		demotools.NotEmpty{})
	const smallKey = "doc-example-key"
	err = bucketBasics.UploadFile(ctx, bucketName, smallKey, smallFile)
	if err != nil {
		panic(err)
	}
	log.Printf("Uploaded %v as %v.\n", smallFile, smallKey)
	log.Println(strings.Repeat("-", 88))

	log.Printf("Let's download %v to a file.", smallKey)
	downloadFileName := questioner.Ask("Enter a name for the downloaded file:", demotools.NotEmpty{})
	err = bucketBasics.DownloadFile(ctx, bucketName, smallKey, downloadFileName)
	if err != nil {
		panic(err)
	}
	log.Printf("File %v downloaded.", downloadFileName)
	log.Println(strings.Repeat("-", 88))

	log.Printf("Let's copy %v to a folder in the same bucket.", smallKey)
	folderName := questioner.Ask("Enter a folder name: ", demotools.NotEmpty{})
	err = bucketBasics.CopyToFolder(ctx, bucketName, smallKey, folderName)
	if err != nil {
		panic(err)
	}
	log.Printf("Copied %v to %v/%v.\n", smallKey, folderName, smallKey)
	log.Println(strings.Repeat("-", 88))

	log.Println("Let's list the objects in your bucket.")
	questioner.Ask("Press Enter when you're ready.")
	objects, err := bucketBasics.ListObjects(ctx, bucketName)
	if err != nil {
		panic(err)
	}
	log.Printf("Found %v objects.\n", len(objects))
	var objKeys []string
	for _, object := range objects {
		objKeys = append(objKeys, *object.Key)
		log.Printf("\t%v\n", *object.Key)
	}
	log.Println(strings.Repeat("-", 88))

	if questioner.AskBool("Do you want to delete your bucket and all of its "+
		"contents? (y/n)", "y") {
		log.Println("Deleting objects.")
		err = bucketBasics.DeleteObjects(ctx, bucketName, objKeys)
		if err != nil {
			panic(err)
		}
		log.Println("Deleting bucket.")
		err = bucketBasics.DeleteBucket(ctx, bucketName)
		if err != nil {
			panic(err)
		}
		log.Printf("Deleting downloaded file %v.\n", downloadFileName)
		err = os.Remove(downloadFileName)
		if err != nil {
			panic(err)
		}
	} else {
		log.Println("Okay. Don't forget to delete objects from your bucket to avoid charges.")
	}
	log.Println(strings.Repeat("-", 88))

	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.CopyObject)
  + [CreateBucket](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.CreateBucket)
  + [DeleteBucket](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.DeleteBucket)
  + [DeleteObjects](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.DeleteObjects)
  + [GetObject](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObject)
  + [ListObjectsV2](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.ListObjectsV2)
  + [PutObject](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObject)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_go_2_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// CopyToBucket copies an object in a bucket to another bucket.
func (basics BucketBasics) CopyToBucket(ctx context.Context, sourceBucket string, destinationBucket string, objectKey string) error {
	_, err := basics.S3Client.CopyObject(ctx, &s3.CopyObjectInput{
		Bucket:     aws.String(destinationBucket),
		CopySource: aws.String(fmt.Sprintf("%v/%v", sourceBucket, objectKey)),
		Key:        aws.String(objectKey),
	})
	if err != nil {
		var notActive *types.ObjectNotInActiveTierError
		if errors.As(err, &notActive) {
			log.Printf("Couldn't copy object %s from %s because the object isn't in the active tier.\n",
				objectKey, sourceBucket)
			err = notActive
		}
	} else {
		err = s3.NewObjectExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadObjectInput{Bucket: aws.String(destinationBucket), Key: aws.String(objectKey)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s to exist.\n", objectKey)
		}
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CopyObject](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.CopyObject)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_go_2_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。
デフォルト設定を使用してバケットを作成します。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// 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(ctx context.Context, name string, region string) error {
	_, err := basics.S3Client.CreateBucket(ctx, &s3.CreateBucketInput{
		Bucket: aws.String(name),
		CreateBucketConfiguration: &types.CreateBucketConfiguration{
			LocationConstraint: types.BucketLocationConstraint(region),
		},
	})
	if err != nil {
		var owned *types.BucketAlreadyOwnedByYou
		var exists *types.BucketAlreadyExists
		if errors.As(err, &owned) {
			log.Printf("You already own bucket %s.\n", name)
			err = owned
		} else if errors.As(err, &exists) {
			log.Printf("Bucket %s already exists.\n", name)
			err = exists
		}
	} else {
		err = s3.NewBucketExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(name)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to exist.\n", name)
		}
	}
	return err
}
```
オブジェクトロックを使用してバケットを作成し、作成が完了するまで待ちます。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// CreateBucketWithLock creates a new S3 bucket with optional object locking enabled
// and waits for the bucket to exist before returning.
func (actor S3Actions) CreateBucketWithLock(ctx context.Context, bucket string, region string, enableObjectLock bool) (string, error) {
	input := &s3.CreateBucketInput{
		Bucket: aws.String(bucket),
		CreateBucketConfiguration: &types.CreateBucketConfiguration{
			LocationConstraint: types.BucketLocationConstraint(region),
		},
	}

	if enableObjectLock {
		input.ObjectLockEnabledForBucket = aws.Bool(true)
	}

	_, err := actor.S3Client.CreateBucket(ctx, input)
	if err != nil {
		var owned *types.BucketAlreadyOwnedByYou
		var exists *types.BucketAlreadyExists
		if errors.As(err, &owned) {
			log.Printf("You already own bucket %s.\n", bucket)
			err = owned
		} else if errors.As(err, &exists) {
			log.Printf("Bucket %s already exists.\n", bucket)
			err = exists
		}
	} else {
		err = s3.NewBucketExistsWaiter(actor.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(bucket)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to exist.\n", bucket)
		}
	}

	return bucket, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[CreateBucket](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.CreateBucket)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_go_2_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// DeleteBucket deletes a bucket. The bucket must be empty or an error is returned.
func (basics BucketBasics) DeleteBucket(ctx context.Context, bucketName string) error {
	_, err := basics.S3Client.DeleteBucket(ctx, &s3.DeleteBucketInput{
		Bucket: aws.String(bucketName)})
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucketName)
			err = noBucket
		} else {
			log.Printf("Couldn't delete bucket %v. Here's why: %v\n", bucketName, err)
		}
	} else {
		err = s3.NewBucketNotExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(bucketName)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to be deleted.\n", bucketName)
		} else {
			log.Printf("Deleted %s.\n", bucketName)
		}
	}
	return err
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの「[DeleteBucket](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.DeleteBucket)」を参照してください。**

### `DeleteObject`
<a name="s3_DeleteObject_go_2_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// DeleteObject deletes an object from a bucket.
func (actor S3Actions) DeleteObject(ctx context.Context, bucket string, key string, versionId string, bypassGovernance bool) (bool, error) {
	deleted := false
	input := &s3.DeleteObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
	}
	if versionId != "" {
		input.VersionId = aws.String(versionId)
	}
	if bypassGovernance {
		input.BypassGovernanceRetention = aws.Bool(true)
	}
	_, err := actor.S3Client.DeleteObject(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in %s.\n", key, bucket)
			err = noKey
		} else if errors.As(err, &apiErr) {
			switch apiErr.ErrorCode() {
			case "AccessDenied":
				log.Printf("Access denied: cannot delete object %s from %s.\n", key, bucket)
				err = nil
			case "InvalidArgument":
				if bypassGovernance {
					log.Printf("You cannot specify bypass governance on a bucket without lock enabled.")
					err = nil
				}
			}
		}
	} else {
		err = s3.NewObjectNotExistsWaiter(actor.S3Client).Wait(
			ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s in bucket %s to be deleted.\n", key, bucket)
		} else {
			deleted = true
		}
	}
	return deleted, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteObject](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_go_2_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// DeleteObjects deletes a list of objects from a bucket.
func (actor S3Actions) DeleteObjects(ctx context.Context, bucket string, objects []types.ObjectIdentifier, bypassGovernance bool) error {
	if len(objects) == 0 {
		return nil
	}

	input := s3.DeleteObjectsInput{
		Bucket: aws.String(bucket),
		Delete: &types.Delete{
			Objects: objects,
			Quiet:   aws.Bool(true),
		},
	}
	if bypassGovernance {
		input.BypassGovernanceRetention = aws.Bool(true)
	}
	delOut, err := actor.S3Client.DeleteObjects(ctx, &input)
	if err != nil || len(delOut.Errors) > 0 {
		log.Printf("Error deleting objects from bucket %s.\n", bucket)
		if err != nil {
			var noBucket *types.NoSuchBucket
			if errors.As(err, &noBucket) {
				log.Printf("Bucket %s does not exist.\n", bucket)
				err = noBucket
			}
		} else if len(delOut.Errors) > 0 {
			for _, outErr := range delOut.Errors {
				log.Printf("%s: %s\n", *outErr.Key, *outErr.Message)
			}
			err = fmt.Errorf("%s", *delOut.Errors[0].Message)
		}
	} else {
		for _, delObjs := range delOut.Deleted {
			err = s3.NewObjectNotExistsWaiter(actor.S3Client).Wait(
				ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: delObjs.Key}, time.Minute)
			if err != nil {
				log.Printf("Failed attempt to wait for object %s to be deleted.\n", *delObjs.Key)
			} else {
				log.Printf("Deleted %s.\n", *delObjs.Key)
			}
		}
	}
	return err
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの「[DeleteObjects](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.DeleteObjects)」を参照してください。**

### `GetObject`
<a name="s3_GetObject_go_2_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// DownloadFile gets an object from a bucket and stores it in a local file.
func (basics BucketBasics) DownloadFile(ctx context.Context, bucketName string, objectKey string, fileName string) error {
	result, err := basics.S3Client.GetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	})
	if err != nil {
		var noKey *types.NoSuchKey
		if errors.As(err, &noKey) {
			log.Printf("Can't get object %s from bucket %s. No such key exists.\n", objectKey, bucketName)
			err = noKey
		} else {
			log.Printf("Couldn't get object %v:%v. Here's why: %v\n", bucketName, objectKey, err)
		}
		return err
	}
	defer result.Body.Close()
	file, err := os.Create(fileName)
	if err != nil {
		log.Printf("Couldn't create file %v. Here's why: %v\n", fileName, err)
		return err
	}
	defer file.Close()
	body, err := io.ReadAll(result.Body)
	if err != nil {
		log.Printf("Couldn't read object body from %v. Here's why: %v\n", objectKey, err)
	}
	_, err = file.Write(body)
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[GetObject](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObject)」を参照してください。

### `GetObjectLegalHold`
<a name="s3_GetObjectLegalHold_go_2_topic"></a>

次のコード例は、`GetObjectLegalHold` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// GetObjectLegalHold retrieves the legal hold status for an S3 object.
func (actor S3Actions) GetObjectLegalHold(ctx context.Context, bucket string, key string, versionId string) (*types.ObjectLockLegalHoldStatus, error) {
	var status *types.ObjectLockLegalHoldStatus
	input := &s3.GetObjectLegalHoldInput{
		Bucket:    aws.String(bucket),
		Key:       aws.String(key),
		VersionId: aws.String(versionId),
	}

	output, err := actor.S3Client.GetObjectLegalHold(ctx, input)
	if err != nil {
		var noSuchKeyErr *types.NoSuchKey
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noSuchKeyErr) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noSuchKeyErr
		} else if errors.As(err, &apiErr) {
			switch apiErr.ErrorCode() {
			case "NoSuchObjectLockConfiguration":
				log.Printf("Object %s does not have an object lock configuration.\n", key)
				err = nil
			case "InvalidRequest":
				log.Printf("Bucket %s does not have an object lock configuration.\n", bucket)
				err = nil
			}
		}
	} else {
		status = &output.LegalHold.Status
	}

	return status, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[GetObjectLegalHold](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObjectLegalHold)」を参照してください。

### `GetObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_go_2_topic"></a>

次のコード例は、`GetObjectLockConfiguration` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// GetObjectLockConfiguration retrieves the object lock configuration for an S3 bucket.
func (actor S3Actions) GetObjectLockConfiguration(ctx context.Context, bucket string) (*types.ObjectLockConfiguration, error) {
	var lockConfig *types.ObjectLockConfiguration
	input := &s3.GetObjectLockConfigurationInput{
		Bucket: aws.String(bucket),
	}

	output, err := actor.S3Client.GetObjectLockConfiguration(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		} else if errors.As(err, &apiErr) && apiErr.ErrorCode() == "ObjectLockConfigurationNotFoundError" {
			log.Printf("Bucket %s does not have an object lock configuration.\n", bucket)
			err = nil
		}
	} else {
		lockConfig = output.ObjectLockConfiguration
	}

	return lockConfig, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[GetObjectLockConfiguration](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObjectLockConfiguration)」を参照してください。

### `GetObjectRetention`
<a name="s3_GetObjectRetention_go_2_topic"></a>

次のコード例は、`GetObjectRetention` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// GetObjectRetention retrieves the object retention configuration for an S3 object.
func (actor S3Actions) GetObjectRetention(ctx context.Context, bucket string, key string) (*types.ObjectLockRetention, error) {
	var retention *types.ObjectLockRetention
	input := &s3.GetObjectRetentionInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
	}

	output, err := actor.S3Client.GetObjectRetention(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noKey
		} else if errors.As(err, &apiErr) {
			switch apiErr.ErrorCode() {
			case "NoSuchObjectLockConfiguration":
				err = nil
			case "InvalidRequest":
				log.Printf("Bucket %s does not have locking enabled.", bucket)
				err = nil
			}
		}
	} else {
		retention = output.Retention
	}

	return retention, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[GetObjectRetention](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObjectRetention)」を参照してください。

### `HeadBucket`
<a name="s3_HeadBucket_go_2_topic"></a>

次のコード例は、`HeadBucket` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// BucketExists checks whether a bucket exists in the current account.
func (basics BucketBasics) BucketExists(ctx context.Context, bucketName string) (bool, error) {
	_, err := basics.S3Client.HeadBucket(ctx, &s3.HeadBucketInput{
		Bucket: aws.String(bucketName),
	})
	exists := true
	if err != nil {
		var apiError smithy.APIError
		if errors.As(err, &apiError) {
			switch apiError.(type) {
			case *types.NotFound:
				log.Printf("Bucket %v is available.\n", bucketName)
				exists = false
				err = nil
			default:
				log.Printf("Either you don't have access to bucket %v or another error occurred. "+
					"Here's what happened: %v\n", bucketName, err)
			}
		}
	} else {
		log.Printf("Bucket %v exists and you already own it.", bucketName)
	}

	return exists, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[HeadBucket](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.HeadBucket)」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_go_2_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// ListBuckets lists the buckets in the current account.
func (basics BucketBasics) ListBuckets(ctx context.Context) ([]types.Bucket, error) {
	var err error
	var output *s3.ListBucketsOutput
	var buckets []types.Bucket
	bucketPaginator := s3.NewListBucketsPaginator(basics.S3Client, &s3.ListBucketsInput{})
	for bucketPaginator.HasMorePages() {
		output, err = bucketPaginator.NextPage(ctx)
		if err != nil {
			var apiErr smithy.APIError
			if errors.As(err, &apiErr) && apiErr.ErrorCode() == "AccessDenied" {
				fmt.Println("You don't have permission to list buckets for this account.")
				err = apiErr
			} else {
				log.Printf("Couldn't list buckets for your account. Here's why: %v\n", err)
			}
			break
		} else {
			buckets = append(buckets, output.Buckets...)
		}
	}
	return buckets, err
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの「[ListBuckets](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.ListBuckets)」を参照してください。**

### `ListObjectVersions`
<a name="s3_ListObjectVersions_go_2_topic"></a>

次のコード例は、`ListObjectVersions` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// ListObjectVersions lists all versions of all objects in a bucket.
func (actor S3Actions) ListObjectVersions(ctx context.Context, bucket string) ([]types.ObjectVersion, error) {
	var err error
	var output *s3.ListObjectVersionsOutput
	var versions []types.ObjectVersion
	input := &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)}
	versionPaginator := s3.NewListObjectVersionsPaginator(actor.S3Client, input)
	for versionPaginator.HasMorePages() {
		output, err = versionPaginator.NextPage(ctx)
		if err != nil {
			var noBucket *types.NoSuchBucket
			if errors.As(err, &noBucket) {
				log.Printf("Bucket %s does not exist.\n", bucket)
				err = noBucket
			}
			break
		} else {
			versions = append(versions, output.Versions...)
		}
	}
	return versions, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[ListObjectVersions](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.ListObjectVersions)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_go_2_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// ListObjects lists the objects in a bucket.
func (basics BucketBasics) ListObjects(ctx context.Context, bucketName string) ([]types.Object, error) {
	var err error
	var output *s3.ListObjectsV2Output
	input := &s3.ListObjectsV2Input{
		Bucket: aws.String(bucketName),
	}
	var objects []types.Object
	objectPaginator := s3.NewListObjectsV2Paginator(basics.S3Client, input)
	for objectPaginator.HasMorePages() {
		output, err = objectPaginator.NextPage(ctx)
		if err != nil {
			var noBucket *types.NoSuchBucket
			if errors.As(err, &noBucket) {
				log.Printf("Bucket %s does not exist.\n", bucketName)
				err = noBucket
			}
			break
		} else {
			objects = append(objects, output.Contents...)
		}
	}
	return objects, err
}
```
+  API の詳細については、AWS SDK for Go API リファレンスの「[ListObjectsV2](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.ListObjectsV2)」を参照してください。**

### `PutObject`
<a name="s3_PutObject_go_2_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。
低レベル API を使用してオブジェクトをバケットに配置します。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// UploadFile reads from a file and puts the data into an object in a bucket.
func (basics BucketBasics) UploadFile(ctx context.Context, bucketName string, objectKey string, fileName string) error {
	file, err := os.Open(fileName)
	if err != nil {
		log.Printf("Couldn't open file %v to upload. Here's why: %v\n", fileName, err)
	} else {
		defer file.Close()
		_, err = basics.S3Client.PutObject(ctx, &s3.PutObjectInput{
			Bucket: aws.String(bucketName),
			Key:    aws.String(objectKey),
			Body:   file,
		})
		if err != nil {
			var apiErr smithy.APIError
			if errors.As(err, &apiErr) && apiErr.ErrorCode() == "EntityTooLarge" {
				log.Printf("Error while uploading object to %s. The object is too large.\n"+
					"To upload objects larger than 5GB, use the S3 console (160GB max)\n"+
					"or the multipart upload API (5TB max).", bucketName)
			} else {
				log.Printf("Couldn't upload file %v to %v:%v. Here's why: %v\n",
					fileName, bucketName, objectKey, err)
			}
		} else {
			err = s3.NewObjectExistsWaiter(basics.S3Client).Wait(
				ctx, &s3.HeadObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectKey)}, time.Minute)
			if err != nil {
				log.Printf("Failed attempt to wait for object %s to exist.\n", objectKey)
			}
		}
	}
	return err
}
```
Transfer Manager を使用してオブジェクトをバケットにアップロードします。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// UploadObject uses the S3 upload manager to upload an object to a bucket.
func (actor S3Actions) UploadObject(ctx context.Context, bucket string, key string, contents string) (string, error) {
	var outKey string
	input := &s3.PutObjectInput{
		Bucket:            aws.String(bucket),
		Key:               aws.String(key),
		Body:              bytes.NewReader([]byte(contents)),
		ChecksumAlgorithm: types.ChecksumAlgorithmSha256,
	}
	output, err := actor.S3Manager.Upload(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
	} else {
		err := s3.NewObjectExistsWaiter(actor.S3Client).Wait(ctx, &s3.HeadObjectInput{
			Bucket: aws.String(bucket),
			Key:    aws.String(key),
		}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s to exist in %s.\n", key, bucket)
		} else {
			outKey = *output.Key
		}
	}
	return outKey, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[PutObject](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObject)」を参照してください。

### `PutObjectLegalHold`
<a name="s3_PutObjectLegalHold_go_2_topic"></a>

次のコード例は、`PutObjectLegalHold` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// PutObjectLegalHold sets the legal hold configuration for an S3 object.
func (actor S3Actions) PutObjectLegalHold(ctx context.Context, bucket string, key string, versionId string, legalHoldStatus types.ObjectLockLegalHoldStatus) error {
	input := &s3.PutObjectLegalHoldInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
		LegalHold: &types.ObjectLockLegalHold{
			Status: legalHoldStatus,
		},
	}
	if versionId != "" {
		input.VersionId = aws.String(versionId)
	}

	_, err := actor.S3Client.PutObjectLegalHold(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noKey
		}
	}

	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[PutObjectLegalHold](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObjectLegalHold)」を参照してください。

### `PutObjectLockConfiguration`
<a name="s3_PutObjectLockConfiguration_go_2_topic"></a>

次のコード例は、`PutObjectLockConfiguration` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。
バケットのオブジェクトロック設定を指定します。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// EnableObjectLockOnBucket enables object locking on an existing bucket.
func (actor S3Actions) EnableObjectLockOnBucket(ctx context.Context, bucket string) error {
	// Versioning must be enabled on the bucket before object locking is enabled.
	verInput := &s3.PutBucketVersioningInput{
		Bucket: aws.String(bucket),
		VersioningConfiguration: &types.VersioningConfiguration{
			MFADelete: types.MFADeleteDisabled,
			Status:    types.BucketVersioningStatusEnabled,
		},
	}
	_, err := actor.S3Client.PutBucketVersioning(ctx, verInput)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
		return err
	}

	input := &s3.PutObjectLockConfigurationInput{
		Bucket: aws.String(bucket),
		ObjectLockConfiguration: &types.ObjectLockConfiguration{
			ObjectLockEnabled: types.ObjectLockEnabledEnabled,
		},
	}
	_, err = actor.S3Client.PutObjectLockConfiguration(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
	}

	return err
}
```
バケットのデフォルトの保存期間を設定します。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// ModifyDefaultBucketRetention modifies the default retention period of an existing bucket.
func (actor S3Actions) ModifyDefaultBucketRetention(
	ctx context.Context, bucket string, lockMode types.ObjectLockEnabled, retentionPeriod int32, retentionMode types.ObjectLockRetentionMode) error {

	input := &s3.PutObjectLockConfigurationInput{
		Bucket: aws.String(bucket),
		ObjectLockConfiguration: &types.ObjectLockConfiguration{
			ObjectLockEnabled: lockMode,
			Rule: &types.ObjectLockRule{
				DefaultRetention: &types.DefaultRetention{
					Days: aws.Int32(retentionPeriod),
					Mode: retentionMode,
				},
			},
		},
	}
	_, err := actor.S3Client.PutObjectLockConfiguration(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
	}

	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[PutObjectLockConfiguration](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObjectLockConfiguration)」を参照してください。

### `PutObjectRetention`
<a name="s3_PutObjectRetention_go_2_topic"></a>

次のコード例は、`PutObjectRetention` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// PutObjectRetention sets the object retention configuration for an S3 object.
func (actor S3Actions) PutObjectRetention(ctx context.Context, bucket string, key string, retentionMode types.ObjectLockRetentionMode, retentionPeriodDays int32) error {
	input := &s3.PutObjectRetentionInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
		Retention: &types.ObjectLockRetention{
			Mode:            retentionMode,
			RetainUntilDate: aws.Time(time.Now().AddDate(0, 0, int(retentionPeriodDays))),
		},
		BypassGovernanceRetention: aws.Bool(true),
	}

	_, err := actor.S3Client.PutObjectRetention(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noKey
		}
	}

	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[PutObjectRetention](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObjectRetention)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_go_2_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。
S3 署名アクションをラップする関数を作成します。  

```
import (
	"context"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

// Presigner encapsulates the Amazon Simple Storage Service (Amazon S3) presign actions
// used in the examples.
// It contains PresignClient, a client that is used to presign requests to Amazon S3.
// Presigned requests contain temporary credentials and can be made from any HTTP client.
type Presigner struct {
	PresignClient *s3.PresignClient
}



// GetObject makes a presigned request that can be used to get an object from a bucket.
// The presigned request is valid for the specified number of seconds.
func (presigner Presigner) GetObject(
	ctx context.Context, bucketName string, objectKey string, lifetimeSecs int64) (*v4.PresignedHTTPRequest, error) {
	request, err := presigner.PresignClient.PresignGetObject(ctx, &s3.GetObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	}, func(opts *s3.PresignOptions) {
		opts.Expires = time.Duration(lifetimeSecs * int64(time.Second))
	})
	if err != nil {
		log.Printf("Couldn't get a presigned request to get %v:%v. Here's why: %v\n",
			bucketName, objectKey, err)
	}
	return request, err
}



// PutObject makes a presigned request that can be used to put an object in a bucket.
// The presigned request is valid for the specified number of seconds.
func (presigner Presigner) PutObject(
	ctx context.Context, bucketName string, objectKey string, lifetimeSecs int64) (*v4.PresignedHTTPRequest, error) {
	request, err := presigner.PresignClient.PresignPutObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	}, func(opts *s3.PresignOptions) {
		opts.Expires = time.Duration(lifetimeSecs * int64(time.Second))
	})
	if err != nil {
		log.Printf("Couldn't get a presigned request to put %v:%v. Here's why: %v\n",
			bucketName, objectKey, err)
	}
	return request, err
}



// DeleteObject makes a presigned request that can be used to delete an object from a bucket.
func (presigner Presigner) DeleteObject(ctx context.Context, bucketName string, objectKey string) (*v4.PresignedHTTPRequest, error) {
	request, err := presigner.PresignClient.PresignDeleteObject(ctx, &s3.DeleteObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	})
	if err != nil {
		log.Printf("Couldn't get a presigned request to delete object %v. Here's why: %v\n", objectKey, err)
	}
	return request, err
}



func (presigner Presigner) PresignPostObject(ctx context.Context, bucketName string, objectKey string, lifetimeSecs int64) (*s3.PresignedPostRequest, error) {
	request, err := presigner.PresignClient.PresignPostObject(ctx, &s3.PutObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	}, func(options *s3.PresignPostOptions) {
		options.Expires = time.Duration(lifetimeSecs) * time.Second
	})
	if err != nil {
		log.Printf("Couldn't get a presigned post request to put %v:%v. Here's why: %v\n", bucketName, objectKey, err)
	}
	return request, nil
}
```
署名付き URL を生成して使用し、S3 オブジェクトをアップロード、ダウンロード、削除するインタラクティブな例を実行します。  

```
import (
	"bytes"
	"context"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/s3/actions"
)



// RunPresigningScenario is an interactive example that shows you how to get presigned
// HTTP requests that you can use to move data into and out of Amazon Simple Storage
// Service (Amazon S3). The presigned requests contain temporary credentials and can
// be used by an HTTP client.
//
// 1. Get a presigned request to put an object in a bucket.
// 2. Use the net/http package to use the presigned request to upload a local file to the bucket.
// 3. Get a presigned request to get an object from a bucket.
// 4. Use the net/http package to use the presigned request to download the object to a local file.
// 5. Get a presigned request to delete an object from a bucket.
// 6. Use the net/http package to use the presigned request to delete the object.
//
// This example creates an Amazon S3 presign client from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// It uses a questioner from the `demotools` package to get input during the example.
// This package can be found in the ..\..\demotools folder of this repo.
//
// It uses an IHttpRequester interface to abstract HTTP requests so they can be mocked
// during testing.
func RunPresigningScenario(ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner, httpRequester IHttpRequester) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			_, isMock := questioner.(*demotools.MockQuestioner)
			if isMock || questioner.AskBool("Do you want to see the full error message (y/n)?", "y") {
				log.Println(r)
			}
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon S3 presigning demo.")
	log.Println(strings.Repeat("-", 88))

	s3Client := s3.NewFromConfig(sdkConfig)
	bucketBasics := actions.BucketBasics{S3Client: s3Client}
	presignClient := s3.NewPresignClient(s3Client)
	presigner := actions.Presigner{PresignClient: presignClient}

	bucketName := questioner.Ask("We'll need a bucket. Enter a name for a bucket "+
		"you own or one you want to create:", demotools.NotEmpty{})
	bucketExists, err := bucketBasics.BucketExists(ctx, bucketName)
	if err != nil {
		panic(err)
	}
	if !bucketExists {
		err = bucketBasics.CreateBucket(ctx, bucketName, sdkConfig.Region)
		if err != nil {
			panic(err)
		} else {
			log.Println("Bucket created.")
		}
	}
	log.Println(strings.Repeat("-", 88))

	log.Printf("Let's presign a request to upload a file to your bucket.")
	uploadFilename := questioner.Ask("Enter the path to a file you want to upload:",
		demotools.NotEmpty{})
	uploadKey := questioner.Ask("What would you like to name the uploaded object?",
		demotools.NotEmpty{})
	uploadFile, err := os.Open(uploadFilename)
	if err != nil {
		panic(err)
	}
	defer uploadFile.Close()
	presignedPutRequest, err := presigner.PutObject(ctx, bucketName, uploadKey, 60)
	if err != nil {
		panic(err)
	}
	log.Printf("Got a presigned %v request to URL:\n\t%v\n", presignedPutRequest.Method,
		presignedPutRequest.URL)
	log.Println("Using net/http to send the request...")
	info, err := uploadFile.Stat()
	if err != nil {
		panic(err)
	}
	putResponse, err := httpRequester.Put(presignedPutRequest.URL, info.Size(), uploadFile)
	if err != nil {
		panic(err)
	}
	log.Printf("%v object %v with presigned URL returned %v.", presignedPutRequest.Method,
		uploadKey, putResponse.StatusCode)
	log.Println(strings.Repeat("-", 88))

	log.Printf("Let's presign a request to download the object.")
	questioner.Ask("Press Enter when you're ready.")
	presignedGetRequest, err := presigner.GetObject(ctx, bucketName, uploadKey, 60)
	if err != nil {
		panic(err)
	}
	log.Printf("Got a presigned %v request to URL:\n\t%v\n", presignedGetRequest.Method,
		presignedGetRequest.URL)
	log.Println("Using net/http to send the request...")
	getResponse, err := httpRequester.Get(presignedGetRequest.URL)
	if err != nil {
		panic(err)
	}
	log.Printf("%v object %v with presigned URL returned %v.", presignedGetRequest.Method,
		uploadKey, getResponse.StatusCode)
	defer getResponse.Body.Close()
	downloadBody, err := io.ReadAll(getResponse.Body)
	if err != nil {
		panic(err)
	}
	log.Printf("Downloaded %v bytes. Here are the first 100 of them:\n", len(downloadBody))
	log.Println(strings.Repeat("-", 88))
	log.Println(string(downloadBody[:100]))
	log.Println(strings.Repeat("-", 88))

	log.Println("Now we'll create a new request to put the same object using a presigned post request")
	questioner.Ask("Press Enter when you're ready.")
	presignPostRequest, err := presigner.PresignPostObject(ctx, bucketName, uploadKey, 60)
	if err != nil {
		panic(err)
	}
	log.Printf("Got a presigned post request to url %v with values %v\n", presignPostRequest.URL, presignPostRequest.Values)
	log.Println("Using net/http multipart to send the request...")
	uploadFile, err = os.Open(uploadFilename)
	if err != nil {
		panic(err)
	}
	defer uploadFile.Close()
	multiPartResponse, err := sendMultipartRequest(presignPostRequest.URL, presignPostRequest.Values, uploadFile, uploadKey, httpRequester)
	if err != nil {
		panic(err)
	}
	log.Printf("Presign post object %v with presigned URL returned %v.", uploadKey, multiPartResponse.StatusCode)

	log.Println("Let's presign a request to delete the object.")
	questioner.Ask("Press Enter when you're ready.")
	presignedDelRequest, err := presigner.DeleteObject(ctx, bucketName, uploadKey)
	if err != nil {
		panic(err)
	}
	log.Printf("Got a presigned %v request to URL:\n\t%v\n", presignedDelRequest.Method,
		presignedDelRequest.URL)
	log.Println("Using net/http to send the request...")
	delResponse, err := httpRequester.Delete(presignedDelRequest.URL)
	if err != nil {
		panic(err)
	}
	log.Printf("%v object %v with presigned URL returned %v.\n", presignedDelRequest.Method,
		uploadKey, delResponse.StatusCode)
	log.Println(strings.Repeat("-", 88))

	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
この例で HTTP リクエストを行うために使用する HTTP リクエストラッパーを定義します。  

```
// IHttpRequester abstracts HTTP requests into an interface so it can be mocked during
// unit testing.
type IHttpRequester interface {
	Get(url string) (resp *http.Response, err error)
	Post(url, contentType string, body io.Reader) (resp *http.Response, err error)
	Put(url string, contentLength int64, body io.Reader) (resp *http.Response, err error)
	Delete(url string) (resp *http.Response, err error)
}

// HttpRequester uses the net/http package to make HTTP requests during the scenario.
type HttpRequester struct{}

func (httpReq HttpRequester) Get(url string) (resp *http.Response, err error) {
	return http.Get(url)
}
func (httpReq HttpRequester) Post(url, contentType string, body io.Reader) (resp *http.Response, err error) {
	postRequest, err := http.NewRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	postRequest.Header.Set("Content-Type", contentType)
	return http.DefaultClient.Do(postRequest)
}

func (httpReq HttpRequester) Put(url string, contentLength int64, body io.Reader) (resp *http.Response, err error) {
	putRequest, err := http.NewRequest("PUT", url, body)
	if err != nil {
		return nil, err
	}
	putRequest.ContentLength = contentLength
	return http.DefaultClient.Do(putRequest)
}
func (httpReq HttpRequester) Delete(url string) (resp *http.Response, err error) {
	delRequest, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return nil, err
	}
	return http.DefaultClient.Do(delRequest)
}
```

### Amazon S3 オブジェクトをロックする
<a name="s3_Scenario_ObjectLock_go_2_topic"></a>

次のコード例は、S3 オブジェクトロック機能を操作する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/s3_object_lock#code-examples)での設定と実行の方法を確認してください。
Amazon S3 オブジェクトロック機能を示すインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"fmt"
	"log"
	"strings"

	"s3_object_lock/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// ObjectLockScenario contains the steps to run the S3 Object Lock workflow.
type ObjectLockScenario struct {
	questioner demotools.IQuestioner
	resources  Resources
	s3Actions  *actions.S3Actions
	sdkConfig  aws.Config
}

// NewObjectLockScenario constructs a new ObjectLockScenario instance.
func NewObjectLockScenario(sdkConfig aws.Config, questioner demotools.IQuestioner) ObjectLockScenario {
	scenario := ObjectLockScenario{
		questioner: questioner,
		resources:  Resources{},
		s3Actions:  &actions.S3Actions{S3Client: s3.NewFromConfig(sdkConfig)},
		sdkConfig:  sdkConfig,
	}
	scenario.s3Actions.S3Manager = manager.NewUploader(scenario.s3Actions.S3Client)
	scenario.resources.init(scenario.s3Actions, questioner)
	return scenario
}

type nameLocked struct {
	name   string
	locked bool
}

var createInfo = []nameLocked{
	{"standard-bucket", false},
	{"lock-bucket", true},
	{"retention-bucket", false},
}

// CreateBuckets creates the S3 buckets required for the workflow.
func (scenario *ObjectLockScenario) CreateBuckets(ctx context.Context) {
	log.Println("Let's create some S3 buckets to use for this workflow.")
	success := false
	for !success {
		prefix := scenario.questioner.Ask(
			"This example creates three buckets. Enter a prefix to name your buckets (remember bucket names must be globally unique):")

		for _, info := range createInfo {
			log.Println(fmt.Sprintf("%s.%s", prefix, info.name))
			bucketName, err := scenario.s3Actions.CreateBucketWithLock(ctx, fmt.Sprintf("%s.%s", prefix, info.name), scenario.sdkConfig.Region, info.locked)
			if err != nil {
				switch err.(type) {
				case *types.BucketAlreadyExists, *types.BucketAlreadyOwnedByYou:
					log.Printf("Couldn't create bucket %s.\n", bucketName)
				default:
					panic(err)
				}
				break
			}
			scenario.resources.demoBuckets[info.name] = &DemoBucket{
				name:       bucketName,
				objectKeys: []string{},
			}
			log.Printf("Created bucket %s.\n", bucketName)
		}

		if len(scenario.resources.demoBuckets) < len(createInfo) {
			scenario.resources.deleteBuckets(ctx)
		} else {
			success = true
		}
	}

	log.Println("S3 buckets created.")
	log.Println(strings.Repeat("-", 88))
}

// EnableLockOnBucket enables object locking on an existing bucket.
func (scenario *ObjectLockScenario) EnableLockOnBucket(ctx context.Context) {
	log.Println("\nA bucket can be configured to use object locking.")
	scenario.questioner.Ask("Press Enter to continue.")

	var err error
	bucket := scenario.resources.demoBuckets["retention-bucket"]
	err = scenario.s3Actions.EnableObjectLockOnBucket(ctx, bucket.name)
	if err != nil {
		switch err.(type) {
		case *types.NoSuchBucket:
			log.Printf("Couldn't enable object locking on bucket %s.\n", bucket.name)
		default:
			panic(err)
		}
	} else {
		log.Printf("Object locking enabled on bucket %s.", bucket.name)
	}

	log.Println(strings.Repeat("-", 88))
}

// SetDefaultRetentionPolicy sets a default retention governance policy on a bucket.
func (scenario *ObjectLockScenario) SetDefaultRetentionPolicy(ctx context.Context) {
	log.Println("\nA bucket can be configured to use object locking with a default retention period.")

	bucket := scenario.resources.demoBuckets["retention-bucket"]
	retentionPeriod := scenario.questioner.AskInt("Enter the default retention period in days: ")
	err := scenario.s3Actions.ModifyDefaultBucketRetention(ctx, bucket.name, types.ObjectLockEnabledEnabled, int32(retentionPeriod), types.ObjectLockRetentionModeGovernance)
	if err != nil {
		switch err.(type) {
		case *types.NoSuchBucket:
			log.Printf("Couldn't configure a default retention period on bucket %s.\n", bucket.name)
		default:
			panic(err)
		}
	} else {
		log.Printf("Default retention policy set on bucket %s with %d day retention period.", bucket.name, retentionPeriod)
		bucket.retentionEnabled = true
	}

	log.Println(strings.Repeat("-", 88))
}

// UploadTestObjects uploads test objects to the S3 buckets.
func (scenario *ObjectLockScenario) UploadTestObjects(ctx context.Context) {
	log.Println("Uploading test objects to S3 buckets.")

	for _, info := range createInfo {
		bucket := scenario.resources.demoBuckets[info.name]
		for i := 0; i < 2; i++ {
			key, err := scenario.s3Actions.UploadObject(ctx, bucket.name, fmt.Sprintf("example-%d", i),
				fmt.Sprintf("Example object content #%d in bucket %s.", i, bucket.name))
			if err != nil {
				switch err.(type) {
				case *types.NoSuchBucket:
					log.Printf("Couldn't upload %s to bucket %s.\n", key, bucket.name)
				default:
					panic(err)
				}
			} else {
				log.Printf("Uploaded %s to bucket %s.\n", key, bucket.name)
				bucket.objectKeys = append(bucket.objectKeys, key)
			}
		}
	}

	scenario.questioner.Ask("Test objects uploaded. Press Enter to continue.")
	log.Println(strings.Repeat("-", 88))
}

// SetObjectLockConfigurations sets object lock configurations on the test objects.
func (scenario *ObjectLockScenario) SetObjectLockConfigurations(ctx context.Context) {
	log.Println("Now let's set object lock configurations on individual objects.")

	buckets := []*DemoBucket{scenario.resources.demoBuckets["lock-bucket"], scenario.resources.demoBuckets["retention-bucket"]}
	for _, bucket := range buckets {
		for index, objKey := range bucket.objectKeys {
			switch index {
			case 0:
				if scenario.questioner.AskBool(fmt.Sprintf("\nDo you want to add a legal hold to %s in %s (y/n)? ", objKey, bucket.name), "y") {
					err := scenario.s3Actions.PutObjectLegalHold(ctx, bucket.name, objKey, "", types.ObjectLockLegalHoldStatusOn)
					if err != nil {
						switch err.(type) {
						case *types.NoSuchKey:
							log.Printf("Couldn't set legal hold on %s.\n", objKey)
						default:
							panic(err)
						}
					} else {
						log.Printf("Legal hold set on %s.\n", objKey)
					}
				}
			case 1:
				q := fmt.Sprintf("\nDo you want to add a 1 day Governance retention period to %s in %s?\n"+
					"Reminder: Only a user with the s3:BypassGovernanceRetention permission is able to delete this object\n"+
					"or its bucket until the retention period has expired. (y/n) ", objKey, bucket.name)
				if scenario.questioner.AskBool(q, "y") {
					err := scenario.s3Actions.PutObjectRetention(ctx, bucket.name, objKey, types.ObjectLockRetentionModeGovernance, 1)
					if err != nil {
						switch err.(type) {
						case *types.NoSuchKey:
							log.Printf("Couldn't set retention period on %s in %s.\n", objKey, bucket.name)
						default:
							panic(err)
						}
					} else {
						log.Printf("Retention period set to 1 for %s.", objKey)
						bucket.retentionEnabled = true
					}
				}
			}
		}
	}
	log.Println(strings.Repeat("-", 88))
}

const (
	ListAll = iota
	DeleteObject
	DeleteRetentionObject
	OverwriteObject
	ViewRetention
	ViewLegalHold
	Finish
)

// InteractWithObjects allows the user to interact with the objects and test the object lock configurations.
func (scenario *ObjectLockScenario) InteractWithObjects(ctx context.Context) {
	log.Println("Now you can interact with the objects to explore the object lock configurations.")
	interactiveChoices := []string{
		"List all objects and buckets.",
		"Attempt to delete an object.",
		"Attempt to delete an object with retention period bypass.",
		"Attempt to overwrite a file.",
		"View the retention settings for an object.",
		"View the legal hold settings for an object.",
		"Finish the workflow."}

	choice := ListAll
	for choice != Finish {
		objList := scenario.GetAllObjects(ctx)
		objChoices := scenario.makeObjectChoiceList(objList)
		choice = scenario.questioner.AskChoice("Choose an action from the menu:\n", interactiveChoices)
		switch choice {
		case ListAll:
			log.Println("The current objects in the example buckets are:")
			for _, objChoice := range objChoices {
				log.Println("\t", objChoice)
			}
		case DeleteObject, DeleteRetentionObject:
			objChoice := scenario.questioner.AskChoice("Enter the number of the object to delete:\n", objChoices)
			obj := objList[objChoice]
			deleted, err := scenario.s3Actions.DeleteObject(ctx, obj.bucket, obj.key, obj.versionId, choice == DeleteRetentionObject)
			if err != nil {
				switch err.(type) {
				case *types.NoSuchKey:
					log.Println("Nothing to delete.")
				default:
					panic(err)
				}
			} else if deleted {
				log.Printf("Object %s deleted.\n", obj.key)
			}
		case OverwriteObject:
			objChoice := scenario.questioner.AskChoice("Enter the number of the object to overwrite:\n", objChoices)
			obj := objList[objChoice]
			_, err := scenario.s3Actions.UploadObject(ctx, obj.bucket, obj.key, fmt.Sprintf("New content in object %s.", obj.key))
			if err != nil {
				switch err.(type) {
				case *types.NoSuchBucket:
					log.Println("Couldn't upload to nonexistent bucket.")
				default:
					panic(err)
				}
			} else {
				log.Printf("Uploaded new content to object %s.\n", obj.key)
			}
		case ViewRetention:
			objChoice := scenario.questioner.AskChoice("Enter the number of the object to view:\n", objChoices)
			obj := objList[objChoice]
			retention, err := scenario.s3Actions.GetObjectRetention(ctx, obj.bucket, obj.key)
			if err != nil {
				switch err.(type) {
				case *types.NoSuchKey:
					log.Printf("Can't get retention configuration for %s.\n", obj.key)
				default:
					panic(err)
				}
			} else if retention != nil {
				log.Printf("Object %s has retention mode %s until %v.\n", obj.key, retention.Mode, retention.RetainUntilDate)
			} else {
				log.Printf("Object %s does not have object retention configured.\n", obj.key)
			}
		case ViewLegalHold:
			objChoice := scenario.questioner.AskChoice("Enter the number of the object to view:\n", objChoices)
			obj := objList[objChoice]
			legalHold, err := scenario.s3Actions.GetObjectLegalHold(ctx, obj.bucket, obj.key, obj.versionId)
			if err != nil {
				switch err.(type) {
				case *types.NoSuchKey:
					log.Printf("Can't get legal hold configuration for %s.\n", obj.key)
				default:
					panic(err)
				}
			} else if legalHold != nil {
				log.Printf("Object %s has legal hold %v.", obj.key, *legalHold)
			} else {
				log.Printf("Object %s does not have legal hold configured.", obj.key)
			}
		case Finish:
			log.Println("Let's clean up.")
		}
		log.Println(strings.Repeat("-", 88))
	}
}

type BucketKeyVersionId struct {
	bucket    string
	key       string
	versionId string
}

// GetAllObjects gets the object versions in the example S3 buckets and returns them in a flattened list.
func (scenario *ObjectLockScenario) GetAllObjects(ctx context.Context) []BucketKeyVersionId {
	var objectList []BucketKeyVersionId
	for _, info := range createInfo {
		bucket := scenario.resources.demoBuckets[info.name]
		versions, err := scenario.s3Actions.ListObjectVersions(ctx, bucket.name)
		if err != nil {
			switch err.(type) {
			case *types.NoSuchBucket:
				log.Printf("Couldn't get object versions for %s.\n", bucket.name)
			default:
				panic(err)
			}
		} else {
			for _, version := range versions {
				objectList = append(objectList,
					BucketKeyVersionId{bucket: bucket.name, key: *version.Key, versionId: *version.VersionId})
			}
		}
	}
	return objectList
}

// makeObjectChoiceList makes the object version list into a list of strings that are displayed
// as choices.
func (scenario *ObjectLockScenario) makeObjectChoiceList(bucketObjects []BucketKeyVersionId) []string {
	choices := make([]string, len(bucketObjects))
	for i := 0; i < len(bucketObjects); i++ {
		choices[i] = fmt.Sprintf("%s in %s with VersionId %s.",
			bucketObjects[i].key, bucketObjects[i].bucket, bucketObjects[i].versionId)
	}
	return choices
}

// Run runs the S3 Object Lock scenario.
func (scenario *ObjectLockScenario) Run(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			_, isMock := scenario.questioner.(*demotools.MockQuestioner)
			if isMock || scenario.questioner.AskBool("Do you want to see the full error message (y/n)?", "y") {
				log.Println(r)
			}
			scenario.resources.Cleanup(ctx)
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon S3 Object Lock Feature Scenario.")
	log.Println(strings.Repeat("-", 88))

	scenario.CreateBuckets(ctx)
	scenario.EnableLockOnBucket(ctx)
	scenario.SetDefaultRetentionPolicy(ctx)
	scenario.UploadTestObjects(ctx)
	scenario.SetObjectLockConfigurations(ctx)
	scenario.InteractWithObjects(ctx)

	scenario.resources.Cleanup(ctx)

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
この例で使用されている S3 アクションをラップする構造体を定義します。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

// S3Actions wraps S3 service actions.
type S3Actions struct {
	S3Client  *s3.Client
	S3Manager *manager.Uploader
}



// CreateBucketWithLock creates a new S3 bucket with optional object locking enabled
// and waits for the bucket to exist before returning.
func (actor S3Actions) CreateBucketWithLock(ctx context.Context, bucket string, region string, enableObjectLock bool) (string, error) {
	input := &s3.CreateBucketInput{
		Bucket: aws.String(bucket),
		CreateBucketConfiguration: &types.CreateBucketConfiguration{
			LocationConstraint: types.BucketLocationConstraint(region),
		},
	}

	if enableObjectLock {
		input.ObjectLockEnabledForBucket = aws.Bool(true)
	}

	_, err := actor.S3Client.CreateBucket(ctx, input)
	if err != nil {
		var owned *types.BucketAlreadyOwnedByYou
		var exists *types.BucketAlreadyExists
		if errors.As(err, &owned) {
			log.Printf("You already own bucket %s.\n", bucket)
			err = owned
		} else if errors.As(err, &exists) {
			log.Printf("Bucket %s already exists.\n", bucket)
			err = exists
		}
	} else {
		err = s3.NewBucketExistsWaiter(actor.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(bucket)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to exist.\n", bucket)
		}
	}

	return bucket, err
}



// GetObjectLegalHold retrieves the legal hold status for an S3 object.
func (actor S3Actions) GetObjectLegalHold(ctx context.Context, bucket string, key string, versionId string) (*types.ObjectLockLegalHoldStatus, error) {
	var status *types.ObjectLockLegalHoldStatus
	input := &s3.GetObjectLegalHoldInput{
		Bucket:    aws.String(bucket),
		Key:       aws.String(key),
		VersionId: aws.String(versionId),
	}

	output, err := actor.S3Client.GetObjectLegalHold(ctx, input)
	if err != nil {
		var noSuchKeyErr *types.NoSuchKey
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noSuchKeyErr) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noSuchKeyErr
		} else if errors.As(err, &apiErr) {
			switch apiErr.ErrorCode() {
			case "NoSuchObjectLockConfiguration":
				log.Printf("Object %s does not have an object lock configuration.\n", key)
				err = nil
			case "InvalidRequest":
				log.Printf("Bucket %s does not have an object lock configuration.\n", bucket)
				err = nil
			}
		}
	} else {
		status = &output.LegalHold.Status
	}

	return status, err
}



// GetObjectLockConfiguration retrieves the object lock configuration for an S3 bucket.
func (actor S3Actions) GetObjectLockConfiguration(ctx context.Context, bucket string) (*types.ObjectLockConfiguration, error) {
	var lockConfig *types.ObjectLockConfiguration
	input := &s3.GetObjectLockConfigurationInput{
		Bucket: aws.String(bucket),
	}

	output, err := actor.S3Client.GetObjectLockConfiguration(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		} else if errors.As(err, &apiErr) && apiErr.ErrorCode() == "ObjectLockConfigurationNotFoundError" {
			log.Printf("Bucket %s does not have an object lock configuration.\n", bucket)
			err = nil
		}
	} else {
		lockConfig = output.ObjectLockConfiguration
	}

	return lockConfig, err
}



// GetObjectRetention retrieves the object retention configuration for an S3 object.
func (actor S3Actions) GetObjectRetention(ctx context.Context, bucket string, key string) (*types.ObjectLockRetention, error) {
	var retention *types.ObjectLockRetention
	input := &s3.GetObjectRetentionInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
	}

	output, err := actor.S3Client.GetObjectRetention(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noKey
		} else if errors.As(err, &apiErr) {
			switch apiErr.ErrorCode() {
			case "NoSuchObjectLockConfiguration":
				err = nil
			case "InvalidRequest":
				log.Printf("Bucket %s does not have locking enabled.", bucket)
				err = nil
			}
		}
	} else {
		retention = output.Retention
	}

	return retention, err
}



// PutObjectLegalHold sets the legal hold configuration for an S3 object.
func (actor S3Actions) PutObjectLegalHold(ctx context.Context, bucket string, key string, versionId string, legalHoldStatus types.ObjectLockLegalHoldStatus) error {
	input := &s3.PutObjectLegalHoldInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
		LegalHold: &types.ObjectLockLegalHold{
			Status: legalHoldStatus,
		},
	}
	if versionId != "" {
		input.VersionId = aws.String(versionId)
	}

	_, err := actor.S3Client.PutObjectLegalHold(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noKey
		}
	}

	return err
}



// ModifyDefaultBucketRetention modifies the default retention period of an existing bucket.
func (actor S3Actions) ModifyDefaultBucketRetention(
	ctx context.Context, bucket string, lockMode types.ObjectLockEnabled, retentionPeriod int32, retentionMode types.ObjectLockRetentionMode) error {

	input := &s3.PutObjectLockConfigurationInput{
		Bucket: aws.String(bucket),
		ObjectLockConfiguration: &types.ObjectLockConfiguration{
			ObjectLockEnabled: lockMode,
			Rule: &types.ObjectLockRule{
				DefaultRetention: &types.DefaultRetention{
					Days: aws.Int32(retentionPeriod),
					Mode: retentionMode,
				},
			},
		},
	}
	_, err := actor.S3Client.PutObjectLockConfiguration(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
	}

	return err
}



// EnableObjectLockOnBucket enables object locking on an existing bucket.
func (actor S3Actions) EnableObjectLockOnBucket(ctx context.Context, bucket string) error {
	// Versioning must be enabled on the bucket before object locking is enabled.
	verInput := &s3.PutBucketVersioningInput{
		Bucket: aws.String(bucket),
		VersioningConfiguration: &types.VersioningConfiguration{
			MFADelete: types.MFADeleteDisabled,
			Status:    types.BucketVersioningStatusEnabled,
		},
	}
	_, err := actor.S3Client.PutBucketVersioning(ctx, verInput)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
		return err
	}

	input := &s3.PutObjectLockConfigurationInput{
		Bucket: aws.String(bucket),
		ObjectLockConfiguration: &types.ObjectLockConfiguration{
			ObjectLockEnabled: types.ObjectLockEnabledEnabled,
		},
	}
	_, err = actor.S3Client.PutObjectLockConfiguration(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
	}

	return err
}



// PutObjectRetention sets the object retention configuration for an S3 object.
func (actor S3Actions) PutObjectRetention(ctx context.Context, bucket string, key string, retentionMode types.ObjectLockRetentionMode, retentionPeriodDays int32) error {
	input := &s3.PutObjectRetentionInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
		Retention: &types.ObjectLockRetention{
			Mode:            retentionMode,
			RetainUntilDate: aws.Time(time.Now().AddDate(0, 0, int(retentionPeriodDays))),
		},
		BypassGovernanceRetention: aws.Bool(true),
	}

	_, err := actor.S3Client.PutObjectRetention(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in bucket %s.\n", key, bucket)
			err = noKey
		}
	}

	return err
}



// UploadObject uses the S3 upload manager to upload an object to a bucket.
func (actor S3Actions) UploadObject(ctx context.Context, bucket string, key string, contents string) (string, error) {
	var outKey string
	input := &s3.PutObjectInput{
		Bucket:            aws.String(bucket),
		Key:               aws.String(key),
		Body:              bytes.NewReader([]byte(contents)),
		ChecksumAlgorithm: types.ChecksumAlgorithmSha256,
	}
	output, err := actor.S3Manager.Upload(ctx, input)
	if err != nil {
		var noBucket *types.NoSuchBucket
		if errors.As(err, &noBucket) {
			log.Printf("Bucket %s does not exist.\n", bucket)
			err = noBucket
		}
	} else {
		err := s3.NewObjectExistsWaiter(actor.S3Client).Wait(ctx, &s3.HeadObjectInput{
			Bucket: aws.String(bucket),
			Key:    aws.String(key),
		}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s to exist in %s.\n", key, bucket)
		} else {
			outKey = *output.Key
		}
	}
	return outKey, err
}



// ListObjectVersions lists all versions of all objects in a bucket.
func (actor S3Actions) ListObjectVersions(ctx context.Context, bucket string) ([]types.ObjectVersion, error) {
	var err error
	var output *s3.ListObjectVersionsOutput
	var versions []types.ObjectVersion
	input := &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)}
	versionPaginator := s3.NewListObjectVersionsPaginator(actor.S3Client, input)
	for versionPaginator.HasMorePages() {
		output, err = versionPaginator.NextPage(ctx)
		if err != nil {
			var noBucket *types.NoSuchBucket
			if errors.As(err, &noBucket) {
				log.Printf("Bucket %s does not exist.\n", bucket)
				err = noBucket
			}
			break
		} else {
			versions = append(versions, output.Versions...)
		}
	}
	return versions, err
}



// DeleteObject deletes an object from a bucket.
func (actor S3Actions) DeleteObject(ctx context.Context, bucket string, key string, versionId string, bypassGovernance bool) (bool, error) {
	deleted := false
	input := &s3.DeleteObjectInput{
		Bucket: aws.String(bucket),
		Key:    aws.String(key),
	}
	if versionId != "" {
		input.VersionId = aws.String(versionId)
	}
	if bypassGovernance {
		input.BypassGovernanceRetention = aws.Bool(true)
	}
	_, err := actor.S3Client.DeleteObject(ctx, input)
	if err != nil {
		var noKey *types.NoSuchKey
		var apiErr *smithy.GenericAPIError
		if errors.As(err, &noKey) {
			log.Printf("Object %s does not exist in %s.\n", key, bucket)
			err = noKey
		} else if errors.As(err, &apiErr) {
			switch apiErr.ErrorCode() {
			case "AccessDenied":
				log.Printf("Access denied: cannot delete object %s from %s.\n", key, bucket)
				err = nil
			case "InvalidArgument":
				if bypassGovernance {
					log.Printf("You cannot specify bypass governance on a bucket without lock enabled.")
					err = nil
				}
			}
		}
	} else {
		err = s3.NewObjectNotExistsWaiter(actor.S3Client).Wait(
			ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s in bucket %s to be deleted.\n", key, bucket)
		} else {
			deleted = true
		}
	}
	return deleted, err
}



// DeleteObjects deletes a list of objects from a bucket.
func (actor S3Actions) DeleteObjects(ctx context.Context, bucket string, objects []types.ObjectIdentifier, bypassGovernance bool) error {
	if len(objects) == 0 {
		return nil
	}

	input := s3.DeleteObjectsInput{
		Bucket: aws.String(bucket),
		Delete: &types.Delete{
			Objects: objects,
			Quiet:   aws.Bool(true),
		},
	}
	if bypassGovernance {
		input.BypassGovernanceRetention = aws.Bool(true)
	}
	delOut, err := actor.S3Client.DeleteObjects(ctx, &input)
	if err != nil || len(delOut.Errors) > 0 {
		log.Printf("Error deleting objects from bucket %s.\n", bucket)
		if err != nil {
			var noBucket *types.NoSuchBucket
			if errors.As(err, &noBucket) {
				log.Printf("Bucket %s does not exist.\n", bucket)
				err = noBucket
			}
		} else if len(delOut.Errors) > 0 {
			for _, outErr := range delOut.Errors {
				log.Printf("%s: %s\n", *outErr.Key, *outErr.Message)
			}
			err = fmt.Errorf("%s", *delOut.Errors[0].Message)
		}
	} else {
		for _, delObjs := range delOut.Deleted {
			err = s3.NewObjectNotExistsWaiter(actor.S3Client).Wait(
				ctx, &s3.HeadObjectInput{Bucket: aws.String(bucket), Key: delObjs.Key}, time.Minute)
			if err != nil {
				log.Printf("Failed attempt to wait for object %s to be deleted.\n", *delObjs.Key)
			} else {
				log.Printf("Deleted %s.\n", *delObjs.Key)
			}
		}
	}
	return err
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"log"
	"s3_object_lock/actions"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

// DemoBucket contains metadata for buckets used in this example.
type DemoBucket struct {
	name             string
	retentionEnabled bool
	objectKeys       []string
}

// Resources keeps track of AWS resources created during the ObjectLockScenario and handles
// cleanup when the scenario finishes.
type Resources struct {
	demoBuckets map[string]*DemoBucket

	s3Actions  *actions.S3Actions
	questioner demotools.IQuestioner
}

// init initializes objects in the Resources struct.
func (resources *Resources) init(s3Actions *actions.S3Actions, questioner demotools.IQuestioner) {
	resources.s3Actions = s3Actions
	resources.questioner = questioner
	resources.demoBuckets = map[string]*DemoBucket{}
}

// Cleanup deletes all AWS resources created during the ObjectLockScenario.
func (resources *Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf("Something went wrong during cleanup.\n%v\n", r)
			log.Println("Use the AWS Management Console to remove any remaining resources " +
				"that were created for this scenario.")
		}
	}()

	wantDelete := resources.questioner.AskBool("Do you want to remove all of the AWS resources that were created "+
		"during this demo (y/n)?", "y")
	if !wantDelete {
		log.Println("Be sure to remove resources when you're done with them to avoid unexpected charges!")
		return
	}

	log.Println("Removing objects from S3 buckets and deleting buckets...")
	resources.deleteBuckets(ctx)
	//resources.deleteRetentionObjects(resources.retentionBucket, resources.retentionObjects)

	log.Println("Cleanup complete.")
}

// deleteBuckets empties and then deletes all buckets created during the ObjectLockScenario.
func (resources *Resources) deleteBuckets(ctx context.Context) {
	for _, info := range createInfo {
		bucket := resources.demoBuckets[info.name]
		resources.deleteObjects(ctx, bucket)
		_, err := resources.s3Actions.S3Client.DeleteBucket(ctx, &s3.DeleteBucketInput{
			Bucket: aws.String(bucket.name),
		})
		if err != nil {
			panic(err)
		}
	}
	for _, info := range createInfo {
		bucket := resources.demoBuckets[info.name]
		err := s3.NewBucketNotExistsWaiter(resources.s3Actions.S3Client).Wait(
			ctx, &s3.HeadBucketInput{Bucket: aws.String(bucket.name)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for bucket %s to be deleted.\n", bucket.name)
		} else {
			log.Printf("Deleted %s.\n", bucket.name)
		}
	}
	resources.demoBuckets = map[string]*DemoBucket{}
}

// deleteObjects deletes all objects in the specified bucket.
func (resources *Resources) deleteObjects(ctx context.Context, bucket *DemoBucket) {
	lockConfig, err := resources.s3Actions.GetObjectLockConfiguration(ctx, bucket.name)
	if err != nil {
		panic(err)
	}
	versions, err := resources.s3Actions.ListObjectVersions(ctx, bucket.name)
	if err != nil {
		switch err.(type) {
		case *types.NoSuchBucket:
			log.Printf("No objects to get from %s.\n", bucket.name)
		default:
			panic(err)
		}
	}
	delObjects := make([]types.ObjectIdentifier, len(versions))
	for i, version := range versions {
		if lockConfig != nil && lockConfig.ObjectLockEnabled == types.ObjectLockEnabledEnabled {
			status, err := resources.s3Actions.GetObjectLegalHold(ctx, bucket.name, *version.Key, *version.VersionId)
			if err != nil {
				switch err.(type) {
				case *types.NoSuchKey:
					log.Printf("Couldn't determine legal hold status for %s in %s.\n", *version.Key, bucket.name)
				default:
					panic(err)
				}
			} else if status != nil && *status == types.ObjectLockLegalHoldStatusOn {
				err = resources.s3Actions.PutObjectLegalHold(ctx, bucket.name, *version.Key, *version.VersionId, types.ObjectLockLegalHoldStatusOff)
				if err != nil {
					switch err.(type) {
					case *types.NoSuchKey:
						log.Printf("Couldn't turn off legal hold for %s in %s.\n", *version.Key, bucket.name)
					default:
						panic(err)
					}
				}
			}
		}
		delObjects[i] = types.ObjectIdentifier{Key: version.Key, VersionId: version.VersionId}
	}
	err = resources.s3Actions.DeleteObjects(ctx, bucket.name, delObjects, bucket.retentionEnabled)
	if err != nil {
		switch err.(type) {
		case *types.NoSuchBucket:
			log.Println("Nothing to delete.")
		default:
			panic(err)
		}
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [GetObjectLegalHold](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObjectLegalHold)
  + [GetObjectLockConfiguration](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObjectLockConfiguration)
  + [GetObjectRetention](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.GetObjectRetention)
  + [PutObjectLegalHold](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObjectLegalHold)
  + [PutObjectLockConfiguration](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObjectLockConfiguration)
  + [PutObjectRetention](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/s3#Client.PutObjectRetention)

### 大きなファイルをアップロードまたはダウンロードする
<a name="s3_Scenario_UsingLargeFiles_go_2_topic"></a>

次のコード例は、Amazon S3 との間で大きなファイルをアップロードまたはダウンロードする方法を示しています。

詳細については、「[マルチパートアップロードを使用したオブジェクトのアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-upload-object.html)」を参照してください。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/s3#code-examples)での設定と実行の方法を確認してください。
アップロードマネージャーとダウンロードマネージャーを使用してデータを分割し、同時に転送する関数を作成します。  

```
import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/aws/aws-sdk-go-v2/service/s3/types"
	"github.com/aws/smithy-go"
)

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



// UploadLargeObject uses an upload manager to upload data to an object in a bucket.
// The upload manager breaks large data into parts and uploads the parts concurrently.
func (basics BucketBasics) UploadLargeObject(ctx context.Context, bucketName string, objectKey string, largeObject []byte) error {
	largeBuffer := bytes.NewReader(largeObject)
	var partMiBs int64 = 10
	uploader := manager.NewUploader(basics.S3Client, func(u *manager.Uploader) {
		u.PartSize = partMiBs * 1024 * 1024
	})
	_, err := uploader.Upload(ctx, &s3.PutObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
		Body:   largeBuffer,
	})
	if err != nil {
		var apiErr smithy.APIError
		if errors.As(err, &apiErr) && apiErr.ErrorCode() == "EntityTooLarge" {
			log.Printf("Error while uploading object to %s. The object is too large.\n"+
				"The maximum size for a multipart upload is 5TB.", bucketName)
		} else {
			log.Printf("Couldn't upload large object to %v:%v. Here's why: %v\n",
				bucketName, objectKey, err)
		}
	} else {
		err = s3.NewObjectExistsWaiter(basics.S3Client).Wait(
			ctx, &s3.HeadObjectInput{Bucket: aws.String(bucketName), Key: aws.String(objectKey)}, time.Minute)
		if err != nil {
			log.Printf("Failed attempt to wait for object %s to exist.\n", objectKey)
		}
	}

	return err
}



// DownloadLargeObject uses a download manager to download an object from a bucket.
// The download manager gets the data in parts and writes them to a buffer until all of
// the data has been downloaded.
func (basics BucketBasics) DownloadLargeObject(ctx context.Context, bucketName string, objectKey string) ([]byte, error) {
	var partMiBs int64 = 10
	downloader := manager.NewDownloader(basics.S3Client, func(d *manager.Downloader) {
		d.PartSize = partMiBs * 1024 * 1024
	})
	buffer := manager.NewWriteAtBuffer([]byte{})
	_, err := downloader.Download(ctx, buffer, &s3.GetObjectInput{
		Bucket: aws.String(bucketName),
		Key:    aws.String(objectKey),
	})
	if err != nil {
		log.Printf("Couldn't download large object from %v:%v. Here's why: %v\n",
			bucketName, objectKey, err)
	}
	return buffer.Bytes(), err
}
```
アップロードマネージャーとダウンロードマネージャーをコンテキストで使用する方法を示すインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"crypto/rand"
	"log"
	"strings"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/s3/actions"
)

// RunLargeObjectScenario is an interactive example that shows you how to use Amazon
// Simple Storage Service (Amazon S3) to upload and download large objects.
//
// 1. Create a bucket.
// 3. Upload a large object to the bucket by using an upload manager.
// 5. Download a large object by using a download manager.
// 8. Delete all objects in the bucket.
// 9. Delete the bucket.
//
// This example creates an Amazon S3 service client from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// It uses a questioner from the `demotools` package to get input during the example.
// This package can be found in the ..\..\demotools folder of this repo.
func RunLargeObjectScenario(ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.")
			_, isMock := questioner.(*demotools.MockQuestioner)
			if isMock || questioner.AskBool("Do you want to see the full error message (y/n)?", "y") {
				log.Println(r)
			}
		}
	}()

	log.Println(strings.Repeat("-", 88))
	log.Println("Welcome to the Amazon S3 large object demo.")
	log.Println(strings.Repeat("-", 88))

	s3Client := s3.NewFromConfig(sdkConfig)
	bucketBasics := actions.BucketBasics{S3Client: s3Client}

	bucketName := questioner.Ask("Let's create a bucket. Enter a name for your bucket:",
		demotools.NotEmpty{})
	bucketExists, err := bucketBasics.BucketExists(ctx, bucketName)
	if err != nil {
		panic(err)
	}
	if !bucketExists {
		err = bucketBasics.CreateBucket(ctx, bucketName, sdkConfig.Region)
		if err != nil {
			panic(err)
		} else {
			log.Println("Bucket created.")
		}
	}
	log.Println(strings.Repeat("-", 88))

	mibs := 30
	log.Printf("Let's create a slice of %v MiB of random bytes and upload it to your bucket. ", mibs)
	questioner.Ask("Press Enter when you're ready.")
	largeBytes := make([]byte, 1024*1024*mibs)
	_, _ = rand.Read(largeBytes)
	largeKey := "doc-example-large"
	log.Println("Uploading...")
	err = bucketBasics.UploadLargeObject(ctx, bucketName, largeKey, largeBytes)
	if err != nil {
		panic(err)
	}
	log.Printf("Uploaded %v MiB object as %v", mibs, largeKey)
	log.Println(strings.Repeat("-", 88))

	log.Printf("Let's download the %v MiB object.", mibs)
	questioner.Ask("Press Enter when you're ready.")
	log.Println("Downloading...")
	largeDownload, err := bucketBasics.DownloadLargeObject(ctx, bucketName, largeKey)
	if err != nil {
		panic(err)
	}
	log.Printf("Downloaded %v bytes.", len(largeDownload))
	log.Println(strings.Repeat("-", 88))

	if questioner.AskBool("Do you want to delete your bucket and all of its "+
		"contents? (y/n)", "y") {
		log.Println("Deleting object.")
		err = bucketBasics.DeleteObjects(ctx, bucketName, []string{largeKey})
		if err != nil {
			panic(err)
		}
		log.Println("Deleting bucket.")
		err = bucketBasics.DeleteBucket(ctx, bucketName)
		if err != nil {
			panic(err)
		}
	} else {
		log.Println("Okay. Don't forget to delete objects from your bucket to avoid charges.")
	}
	log.Println(strings.Repeat("-", 88))

	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_go_2_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Go を使用して Lambda で S3 イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"log"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
)

func handler(ctx context.Context, s3Event events.S3Event) error {
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		log.Printf("failed to load default config: %s", err)
		return err
	}
	s3Client := s3.NewFromConfig(sdkConfig)

	for _, record := range s3Event.Records {
		bucket := record.S3.Bucket.Name
		key := record.S3.Object.URLDecodedKey
		headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput{
			Bucket: &bucket,
			Key:    &key,
		})
		if err != nil {
			log.Printf("error getting head of object %s/%s: %s", bucket, key, err)
			return err
		}
		log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType)
	}

	return nil
}

func main() {
	lambda.Start(handler)
}
```

# SDK for Go V2 を使用した Amazon SNS の例
<a name="go_2_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SNS
<a name="sns_Hello_go_2_topic"></a>

次のコード例は、Amazon SNS の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/sns#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service
// (Amazon SNS) client and list the topics in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	snsClient := sns.NewFromConfig(sdkConfig)
	fmt.Println("Let's list the topics for your account.")
	var topics []types.Topic
	paginator := sns.NewListTopicsPaginator(snsClient, &sns.ListTopicsInput{})
	for paginator.HasMorePages() {
		output, err := paginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get topics. Here's why: %v\n", err)
			break
		} else {
			topics = append(topics, output.Topics...)
		}
	}
	if len(topics) == 0 {
		fmt.Println("You don't have any topics!")
	} else {
		for _, topic := range topics {
			fmt.Printf("\t%v\n", *topic.TopicArn)
		}
	}
}
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[ListTopics](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.ListTopics)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_go_2_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// 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(ctx context.Context, 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(ctx, &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](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.CreateTopic)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_go_2_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
	SnsClient *sns.Client
}



// DeleteTopic delete an Amazon SNS topic.
func (actor SnsActions) DeleteTopic(ctx context.Context, topicArn string) error {
	_, err := actor.SnsClient.DeleteTopic(ctx, &sns.DeleteTopicInput{
		TopicArn: aws.String(topicArn)})
	if err != nil {
		log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.DeleteTopic)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_go_2_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/sns#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service
// (Amazon SNS) client and list the topics in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	snsClient := sns.NewFromConfig(sdkConfig)
	fmt.Println("Let's list the topics for your account.")
	var topics []types.Topic
	paginator := sns.NewListTopicsPaginator(snsClient, &sns.ListTopicsInput{})
	for paginator.HasMorePages() {
		output, err := paginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get topics. Here's why: %v\n", err)
			break
		} else {
			topics = append(topics, output.Topics...)
		}
	}
	if len(topics) == 0 {
		fmt.Println("You don't have any topics!")
	} else {
		for _, topic := range topics {
			fmt.Printf("\t%v\n", *topic.TopicArn)
		}
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListTopics](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.ListTopics)」を参照してください。

### `Publish`
<a name="sns_Publish_go_2_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
	SnsClient *sns.Client
}



// Publish publishes a message to an Amazon SNS topic. The message is then sent to all
// subscribers. When the topic is a FIFO topic, the message must also contain a group ID
// and, when ID-based deduplication is used, a deduplication ID. An optional key-value
// filter attribute can be specified so that the message can be filtered according to
// a filter policy.
func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error {
	publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)}
	if groupId != "" {
		publishInput.MessageGroupId = aws.String(groupId)
	}
	if dedupId != "" {
		publishInput.MessageDeduplicationId = aws.String(dedupId)
	}
	if filterKey != "" && filterValue != "" {
		publishInput.MessageAttributes = map[string]types.MessageAttributeValue{
			filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)},
		}
	}
	_, err := actor.SnsClient.Publish(ctx, &publishInput)
	if err != nil {
		log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[Publish](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Publish)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_go_2_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。
オプションのフィルターでトピックにキューをサブスクライブします。  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
	SnsClient *sns.Client
}



// SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an
// Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy
// so that messages are only sent to the queue when the message has the specified attributes.
func (actor SnsActions) SubscribeQueue(ctx context.Context, topicArn string, queueArn string, filterMap map[string][]string) (string, error) {
	var subscriptionArn string
	var attributes map[string]string
	if filterMap != nil {
		filterBytes, err := json.Marshal(filterMap)
		if err != nil {
			log.Printf("Couldn't create filter policy, here's why: %v\n", err)
			return "", err
		}
		attributes = map[string]string{"FilterPolicy": string(filterBytes)}
	}
	output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{
		Protocol:              aws.String("sqs"),
		TopicArn:              aws.String(topicArn),
		Attributes:            attributes,
		Endpoint:              aws.String(queueArn),
		ReturnSubscriptionArn: true,
	})
	if err != nil {
		log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n",
			queueArn, topicArn, err)
	} else {
		subscriptionArn = *output.SubscriptionArn
	}

	return subscriptionArn, err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[Subscribe](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Subscribe)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"
	"topics_and_queues/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

const FIFO_SUFFIX = ".fifo"
const TONE_KEY = "tone"

var ToneChoices = []string{"cheerful", "funny", "serious", "sincere"}

// MessageBody is used to deserialize the body of a message from a JSON string.
type MessageBody struct {
	Message string
}

// ScenarioRunner separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type ScenarioRunner struct {
	questioner demotools.IQuestioner
	snsActor   *actions.SnsActions
	sqsActor   *actions.SqsActions
}

func (runner ScenarioRunner) CreateTopic(ctx context.Context) (string, string, bool, bool) {
	log.Println("SNS topics can be configured as FIFO (First-In-First-Out) or standard.\n" +
		"FIFO topics deliver messages in order and support deduplication and message filtering.")
	isFifoTopic := runner.questioner.AskBool("\nWould you like to work with FIFO topics? (y/n) ", "y")

	contentBasedDeduplication := false
	if isFifoTopic {
		log.Println(strings.Repeat("-", 88))
		log.Println("Because you have chosen a FIFO topic, deduplication is supported.\n" +
			"Deduplication IDs are either set in the message or are automatically generated\n" +
			"from content using a hash function. If a message is successfully published to\n" +
			"an SNS FIFO topic, any message published and determined to have the same\n" +
			"deduplication ID, within the five-minute deduplication interval, is accepted\n" +
			"but not delivered. For more information about deduplication, see:\n" +
			"\thttps://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.")
		contentBasedDeduplication = runner.questioner.AskBool(
			"\nDo you want to use content-based deduplication instead of entering a deduplication ID? (y/n) ", "y")
	}
	log.Println(strings.Repeat("-", 88))

	topicName := runner.questioner.Ask("Enter a name for your SNS topic. ")
	if isFifoTopic {
		topicName = fmt.Sprintf("%v%v", topicName, FIFO_SUFFIX)
		log.Printf("Because you have selected a FIFO topic, '%v' must be appended to\n"+
			"the topic name.", FIFO_SUFFIX)
	}

	topicArn, err := runner.snsActor.CreateTopic(ctx, topicName, isFifoTopic, contentBasedDeduplication)
	if err != nil {
		panic(err)
	}
	log.Printf("Your new topic with the name '%v' and Amazon Resource Name (ARN) \n"+
		"'%v' has been created.", topicName, topicArn)

	return topicName, topicArn, isFifoTopic, contentBasedDeduplication
}

func (runner ScenarioRunner) CreateQueue(ctx context.Context, ordinal string, isFifoTopic bool) (string, string) {
	queueName := runner.questioner.Ask(fmt.Sprintf("Enter a name for the %v SQS queue. ", ordinal))
	if isFifoTopic {
		queueName = fmt.Sprintf("%v%v", queueName, FIFO_SUFFIX)
		if ordinal == "first" {
			log.Printf("Because you are creating a FIFO SQS queue, '%v' must "+
				"be appended to the queue name.\n", FIFO_SUFFIX)
		}
	}
	queueUrl, err := runner.sqsActor.CreateQueue(ctx, queueName, isFifoTopic)
	if err != nil {
		panic(err)
	}
	log.Printf("Your new SQS queue with the name '%v' and the queue URL "+
		"'%v' has been created.", queueName, queueUrl)

	return queueName, queueUrl
}

func (runner ScenarioRunner) SubscribeQueueToTopic(
	ctx context.Context, queueName string, queueUrl string, topicName string, topicArn string, ordinal string,
	isFifoTopic bool) (string, bool) {

	queueArn, err := runner.sqsActor.GetQueueArn(ctx, queueUrl)
	if err != nil {
		panic(err)
	}
	log.Printf("The ARN of your queue is: %v.\n", queueArn)

	err = runner.sqsActor.AttachSendMessagePolicy(ctx, queueUrl, queueArn, topicArn)
	if err != nil {
		panic(err)
	}
	log.Println("Attached an IAM policy to the queue so the SNS topic can send " +
		"messages to it.")
	log.Println(strings.Repeat("-", 88))

	var filterPolicy map[string][]string
	if isFifoTopic {
		if ordinal == "first" {
			log.Println("Subscriptions to a FIFO topic can have filters.\n" +
				"If you add a filter to this subscription, then only the filtered messages\n" +
				"will be received in the queue.\n" +
				"For information about message filtering, see\n" +
				"\thttps://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n" +
				"For this example, you can filter messages by a \"tone\" attribute.")
		}

		wantFiltering := runner.questioner.AskBool(
			fmt.Sprintf("Do you want to filter messages that are sent to \"%v\"\n"+
				"from the %v topic? (y/n) ", queueName, topicName), "y")
		if wantFiltering {
			log.Println("You can filter messages by one or more of the following \"tone\" attributes.")

			var toneSelections []string
			askAboutTones := true
			for askAboutTones {
				toneIndex := runner.questioner.AskChoice(
					"Enter the number of the tone you want to filter by:\n", ToneChoices)
				toneSelections = append(toneSelections, ToneChoices[toneIndex])
				askAboutTones = runner.questioner.AskBool("Do you want to add another tone to the filter? (y/n) ", "y")
			}
			log.Printf("Your subscription will be filtered to only pass the following tones: %v\n", toneSelections)
			filterPolicy = map[string][]string{TONE_KEY: toneSelections}
		}
	}

	subscriptionArn, err := runner.snsActor.SubscribeQueue(ctx, topicArn, queueArn, filterPolicy)
	if err != nil {
		panic(err)
	}
	log.Printf("The queue %v is now subscribed to the topic %v with the subscription ARN %v.\n",
		queueName, topicName, subscriptionArn)

	return subscriptionArn, filterPolicy != nil
}

func (runner ScenarioRunner) PublishMessages(ctx context.Context, topicArn string, isFifoTopic bool, contentBasedDeduplication bool, usingFilters bool) {
	var message string
	var groupId string
	var dedupId string
	var toneSelection string
	publishMore := true
	for publishMore {
		groupId = ""
		dedupId = ""
		toneSelection = ""
		message = runner.questioner.Ask("Enter a message to publish: ")
		if isFifoTopic {
			log.Println("Because you are using a FIFO topic, you must set a message group ID.\n" +
				"All messages within the same group will be received in the order they were published.")
			groupId = runner.questioner.Ask("Enter a message group ID: ")
			if !contentBasedDeduplication {
				log.Println("Because you are not using content-based deduplication,\n" +
					"you must enter a deduplication ID.")
				dedupId = runner.questioner.Ask("Enter a deduplication ID: ")
			}
		}
		if usingFilters {
			if runner.questioner.AskBool("Add a tone attribute so this message can be filtered? (y/n) ", "y") {
				toneIndex := runner.questioner.AskChoice(
					"Enter the number of the tone you want to filter by:\n", ToneChoices)
				toneSelection = ToneChoices[toneIndex]
			}
		}

		err := runner.snsActor.Publish(ctx, topicArn, message, groupId, dedupId, TONE_KEY, toneSelection)
		if err != nil {
			panic(err)
		}
		log.Println(("Your message was published."))

		publishMore = runner.questioner.AskBool("Do you want to publish another messsage? (y/n) ", "y")
	}
}

func (runner ScenarioRunner) PollForMessages(ctx context.Context, queueUrls []string) {
	log.Println("Polling queues for messages...")
	for _, queueUrl := range queueUrls {
		var messages []types.Message
		for {
			currentMsgs, err := runner.sqsActor.GetMessages(ctx, queueUrl, 10, 1)
			if err != nil {
				panic(err)
			}
			if len(currentMsgs) == 0 {
				break
			}
			messages = append(messages, currentMsgs...)
		}
		if len(messages) == 0 {
			log.Printf("No messages were received by queue %v.\n", queueUrl)
		} else if len(messages) == 1 {
			log.Printf("One message was received by queue %v:\n", queueUrl)

		} else {
			log.Printf("%v messages were received by queue %v:\n", len(messages), queueUrl)
		}
		for msgIndex, message := range messages {
			messageBody := MessageBody{}
			err := json.Unmarshal([]byte(*message.Body), &messageBody)
			if err != nil {
				panic(err)
			}
			log.Printf("Message %v: %v\n", msgIndex+1, messageBody.Message)
		}

		if len(messages) > 0 {
			log.Printf("Deleting %v messages from queue %v.\n", len(messages), queueUrl)
			err := runner.sqsActor.DeleteMessages(ctx, queueUrl, messages)
			if err != nil {
				panic(err)
			}
		}
	}
}

// RunTopicsAndQueuesScenario is an interactive example that shows you how to use the
// AWS SDK for Go to create and use Amazon SNS topics and Amazon SQS queues.
//
// 1. Create a topic (FIFO or non-FIFO).
// 2. Subscribe several queues to the topic with an option to apply a filter.
// 3. Publish messages to the topic.
// 4. Poll the queues for messages received.
// 5. Delete the topic and the queues.
//
// This example creates service clients from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// It uses a questioner from the `demotools` package to get input during the example.
// This package can be found in the ..\..\demotools folder of this repo.
func RunTopicsAndQueuesScenario(
	ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner) {
	resources := Resources{}
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.\n" +
				"Cleaning up any resources that were created...")
			resources.Cleanup(ctx)
		}
	}()
	queueCount := 2

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome to messaging with topics and queues.\n\n"+
		"In this scenario, you will create an SNS topic and subscribe %v SQS queues to the\n"+
		"topic. You can select from several options for configuring the topic and the\n"+
		"subscriptions for the queues. You can then post to the topic and see the results\n"+
		"in the queues.\n", queueCount)

	log.Println(strings.Repeat("-", 88))

	runner := ScenarioRunner{
		questioner: questioner,
		snsActor:   &actions.SnsActions{SnsClient: sns.NewFromConfig(sdkConfig)},
		sqsActor:   &actions.SqsActions{SqsClient: sqs.NewFromConfig(sdkConfig)},
	}
	resources.snsActor = runner.snsActor
	resources.sqsActor = runner.sqsActor

	topicName, topicArn, isFifoTopic, contentBasedDeduplication := runner.CreateTopic(ctx)
	resources.topicArn = topicArn
	log.Println(strings.Repeat("-", 88))

	log.Printf("Now you will create %v SQS queues and subscribe them to the topic.\n", queueCount)
	ordinals := []string{"first", "next"}
	usingFilters := false
	for _, ordinal := range ordinals {
		queueName, queueUrl := runner.CreateQueue(ctx, ordinal, isFifoTopic)
		resources.queueUrls = append(resources.queueUrls, queueUrl)

		_, filtering := runner.SubscribeQueueToTopic(ctx, queueName, queueUrl, topicName, topicArn, ordinal, isFifoTopic)
		usingFilters = usingFilters || filtering
	}

	log.Println(strings.Repeat("-", 88))
	runner.PublishMessages(ctx, topicArn, isFifoTopic, contentBasedDeduplication, usingFilters)
	log.Println(strings.Repeat("-", 88))
	runner.PollForMessages(ctx, resources.queueUrls)

	log.Println(strings.Repeat("-", 88))

	wantCleanup := questioner.AskBool("Do you want to remove all AWS resources created for this scenario? (y/n) ", "y")
	if wantCleanup {
		log.Println("Cleaning up resources...")
		resources.Cleanup(ctx)
	}

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
この例で使用されている Amazon SNS アクションをラップする構造体を定義します。  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// 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(ctx context.Context, 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(ctx, &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
}



// DeleteTopic delete an Amazon SNS topic.
func (actor SnsActions) DeleteTopic(ctx context.Context, topicArn string) error {
	_, err := actor.SnsClient.DeleteTopic(ctx, &sns.DeleteTopicInput{
		TopicArn: aws.String(topicArn)})
	if err != nil {
		log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err)
	}
	return err
}



// SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an
// Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy
// so that messages are only sent to the queue when the message has the specified attributes.
func (actor SnsActions) SubscribeQueue(ctx context.Context, topicArn string, queueArn string, filterMap map[string][]string) (string, error) {
	var subscriptionArn string
	var attributes map[string]string
	if filterMap != nil {
		filterBytes, err := json.Marshal(filterMap)
		if err != nil {
			log.Printf("Couldn't create filter policy, here's why: %v\n", err)
			return "", err
		}
		attributes = map[string]string{"FilterPolicy": string(filterBytes)}
	}
	output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{
		Protocol:              aws.String("sqs"),
		TopicArn:              aws.String(topicArn),
		Attributes:            attributes,
		Endpoint:              aws.String(queueArn),
		ReturnSubscriptionArn: true,
	})
	if err != nil {
		log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n",
			queueArn, topicArn, err)
	} else {
		subscriptionArn = *output.SubscriptionArn
	}

	return subscriptionArn, err
}



// Publish publishes a message to an Amazon SNS topic. The message is then sent to all
// subscribers. When the topic is a FIFO topic, the message must also contain a group ID
// and, when ID-based deduplication is used, a deduplication ID. An optional key-value
// filter attribute can be specified so that the message can be filtered according to
// a filter policy.
func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error {
	publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)}
	if groupId != "" {
		publishInput.MessageGroupId = aws.String(groupId)
	}
	if dedupId != "" {
		publishInput.MessageDeduplicationId = aws.String(dedupId)
	}
	if filterKey != "" && filterValue != "" {
		publishInput.MessageAttributes = map[string]types.MessageAttributeValue{
			filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)},
		}
	}
	_, err := actor.SnsClient.Publish(ctx, &publishInput)
	if err != nil {
		log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err)
	}
	return err
}
```
この例で使用されている Amazon SQS アクションをラップする構造体を定義します。  

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// CreateQueue creates an Amazon SQS queue with the specified name. You can specify
// whether the queue is created as a FIFO queue.
func (actor SqsActions) CreateQueue(ctx context.Context, queueName string, isFifoQueue bool) (string, error) {
	var queueUrl string
	queueAttributes := map[string]string{}
	if isFifoQueue {
		queueAttributes["FifoQueue"] = "true"
	}
	queue, err := actor.SqsClient.CreateQueue(ctx, &sqs.CreateQueueInput{
		QueueName:  aws.String(queueName),
		Attributes: queueAttributes,
	})
	if err != nil {
		log.Printf("Couldn't create queue %v. Here's why: %v\n", queueName, err)
	} else {
		queueUrl = *queue.QueueUrl
	}

	return queueUrl, err
}



// GetQueueArn uses the GetQueueAttributes action to get the Amazon Resource Name (ARN)
// of an Amazon SQS queue.
func (actor SqsActions) GetQueueArn(ctx context.Context, queueUrl string) (string, error) {
	var queueArn string
	arnAttributeName := types.QueueAttributeNameQueueArn
	attribute, err := actor.SqsClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{
		QueueUrl:       aws.String(queueUrl),
		AttributeNames: []types.QueueAttributeName{arnAttributeName},
	})
	if err != nil {
		log.Printf("Couldn't get ARN for queue %v. Here's why: %v\n", queueUrl, err)
	} else {
		queueArn = attribute.Attributes[string(arnAttributeName)]
	}
	return queueArn, err
}



// AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an
// Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the
// queue.
func (actor SqsActions) AttachSendMessagePolicy(ctx context.Context, queueUrl string, queueArn string, topicArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:    "Allow",
			Action:    "sqs:SendMessage",
			Principal: map[string]string{"Service": "sns.amazonaws.com"},
			Resource:  aws.String(queueArn),
			Condition: PolicyCondition{"ArnEquals": map[string]string{"aws:SourceArn": topicArn}},
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document. Here's why: %v\n", err)
		return err
	}
	_, err = actor.SqsClient.SetQueueAttributes(ctx, &sqs.SetQueueAttributesInput{
		Attributes: map[string]string{
			string(types.QueueAttributeNamePolicy): string(policyBytes),
		},
		QueueUrl: aws.String(queueUrl),
	})
	if err != nil {
		log.Printf("Couldn't set send message policy on queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}

// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
	Condition PolicyCondition   `json:",omitempty"`
}

// PolicyCondition defines a condition in a policy.
type PolicyCondition map[string]map[string]string



// GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue.
func (actor SqsActions) GetMessages(ctx context.Context, queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) {
	var messages []types.Message
	result, err := actor.SqsClient.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
		QueueUrl:            aws.String(queueUrl),
		MaxNumberOfMessages: maxMessages,
		WaitTimeSeconds:     waitTime,
	})
	if err != nil {
		log.Printf("Couldn't get messages from queue %v. Here's why: %v\n", queueUrl, err)
	} else {
		messages = result.Messages
	}
	return messages, err
}



// DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from
// an Amazon SQS queue.
func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error {
	entries := make([]types.DeleteMessageBatchRequestEntry, len(messages))
	for msgIndex := range messages {
		entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex))
		entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle
	}
	_, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{
		Entries:  entries,
		QueueUrl: aws.String(queueUrl),
	})
	if err != nil {
		log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}



// DeleteQueue deletes an Amazon SQS queue.
func (actor SqsActions) DeleteQueue(ctx context.Context, queueUrl string) error {
	_, err := actor.SqsClient.DeleteQueue(ctx, &sqs.DeleteQueueInput{
		QueueUrl: aws.String(queueUrl)})
	if err != nil {
		log.Printf("Couldn't delete queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"fmt"
	"log"
	"topics_and_queues/actions"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	topicArn  string
	queueUrls []string
	snsActor  *actions.SnsActions
	sqsActor  *actions.SqsActions
}

// Cleanup deletes all AWS resources created during an example.
func (resources Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Something went wrong during cleanup. Use the AWS Management Console\n" +
				"to remove any remaining resources that were created for this scenario.")
		}
	}()

	var err error
	if resources.topicArn != "" {
		log.Printf("Deleting topic %v.\n", resources.topicArn)
		err = resources.snsActor.DeleteTopic(ctx, resources.topicArn)
		if err != nil {
			panic(err)
		}
	}

	for _, queueUrl := range resources.queueUrls {
		log.Printf("Deleting queue %v.\n", queueUrl)
		err = resources.sqsActor.DeleteQueue(ctx, queueUrl)
		if err != nil {
			panic(err)
		}
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.CreateQueue)
  + [CreateTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.CreateTopic)
  + [DeleteMessageBatch](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.DeleteMessageBatch)
  + [DeleteQueue](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.DeleteQueue)
  + [DeleteTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.DeleteTopic)
  + [GetQueueAttributes](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.GetQueueAttributes)
  + [Publish](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Publish)
  + [ReceiveMessage](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.ReceiveMessage)
  + [SetQueueAttributes](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.SetQueueAttributes)
  + [Subscribe](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Subscribe)
  + [Unsubscribe](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Unsubscribe)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_go_2_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用して Lambda で SNS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"fmt"

	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, snsEvent events.SNSEvent) {
	for _, record := range snsEvent.Records {
		processMessage(record)
	}
	fmt.Println("done")
}

func processMessage(record events.SNSEventRecord) {
	message := record.SNS.Message
	fmt.Printf("Processed message: %s\n", message)
	// TODO: Process your record here
}

func main() {
	lambda.Start(handler)
}
```

# SDK for Go V2 を使用した Amazon SQS の例
<a name="go_2_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS SDK for Go V2 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SQS
<a name="sqs_Hello_go_2_topic"></a>

次のコード例は、Amazon SQS の使用を開始する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/sqs#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
)

// main uses the AWS SDK for Go V2 to create an Amazon Simple Queue Service
// (Amazon SQS) client and list the queues in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	sqsClient := sqs.NewFromConfig(sdkConfig)
	fmt.Println("Let's list the queues for your account.")
	var queueUrls []string
	paginator := sqs.NewListQueuesPaginator(sqsClient, &sqs.ListQueuesInput{})
	for paginator.HasMorePages() {
		output, err := paginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get queues. Here's why: %v\n", err)
			break
		} else {
			queueUrls = append(queueUrls, output.QueueUrls...)
		}
	}
	if len(queueUrls) == 0 {
		fmt.Println("You don't have any queues!")
	} else {
		for _, queueUrl := range queueUrls {
			fmt.Printf("\t%v\n", queueUrl)
		}
	}
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[ListQueues](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.ListQueues)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateQueue`
<a name="sqs_CreateQueue_go_2_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// CreateQueue creates an Amazon SQS queue with the specified name. You can specify
// whether the queue is created as a FIFO queue.
func (actor SqsActions) CreateQueue(ctx context.Context, queueName string, isFifoQueue bool) (string, error) {
	var queueUrl string
	queueAttributes := map[string]string{}
	if isFifoQueue {
		queueAttributes["FifoQueue"] = "true"
	}
	queue, err := actor.SqsClient.CreateQueue(ctx, &sqs.CreateQueueInput{
		QueueName:  aws.String(queueName),
		Attributes: queueAttributes,
	})
	if err != nil {
		log.Printf("Couldn't create queue %v. Here's why: %v\n", queueName, err)
	} else {
		queueUrl = *queue.QueueUrl
	}

	return queueUrl, err
}
```
+  API の詳細については、**AWS SDK for Go API リファレンスの「[CreateQueue](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.CreateQueue)」を参照してください。

### `DeleteMessageBatch`
<a name="sqs_DeleteMessageBatch_go_2_topic"></a>

次のコード例は、`DeleteMessageBatch` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from
// an Amazon SQS queue.
func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error {
	entries := make([]types.DeleteMessageBatchRequestEntry, len(messages))
	for msgIndex := range messages {
		entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex))
		entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle
	}
	_, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{
		Entries:  entries,
		QueueUrl: aws.String(queueUrl),
	})
	if err != nil {
		log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[DeleteMessageBatch](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.DeleteMessageBatch)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_go_2_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// DeleteQueue deletes an Amazon SQS queue.
func (actor SqsActions) DeleteQueue(ctx context.Context, queueUrl string) error {
	_, err := actor.SqsClient.DeleteQueue(ctx, &sqs.DeleteQueueInput{
		QueueUrl: aws.String(queueUrl)})
	if err != nil {
		log.Printf("Couldn't delete queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}
```
+  API の詳細については、**AWS SDK for Go API リファレンスの「[DeleteQueue](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.DeleteQueue)」を参照してください。

### `GetQueueAttributes`
<a name="sqs_GetQueueAttributes_go_2_topic"></a>

次のコード例は、`GetQueueAttributes` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// GetQueueArn uses the GetQueueAttributes action to get the Amazon Resource Name (ARN)
// of an Amazon SQS queue.
func (actor SqsActions) GetQueueArn(ctx context.Context, queueUrl string) (string, error) {
	var queueArn string
	arnAttributeName := types.QueueAttributeNameQueueArn
	attribute, err := actor.SqsClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{
		QueueUrl:       aws.String(queueUrl),
		AttributeNames: []types.QueueAttributeName{arnAttributeName},
	})
	if err != nil {
		log.Printf("Couldn't get ARN for queue %v. Here's why: %v\n", queueUrl, err)
	} else {
		queueArn = attribute.Attributes[string(arnAttributeName)]
	}
	return queueArn, err
}
```
+  API の詳細については、「*AWS SDK for Go API リファレンス*」の「[GetQueueAttributes](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.GetQueueAttributes)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_go_2_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/sqs#code-examples)での設定と実行の方法を確認してください。

```
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
)

// main uses the AWS SDK for Go V2 to create an Amazon Simple Queue Service
// (Amazon SQS) client and list the queues in your account.
// This example uses the default settings specified in your shared credentials
// and config files.
func main() {
	ctx := context.Background()
	sdkConfig, err := config.LoadDefaultConfig(ctx)
	if err != nil {
		fmt.Println("Couldn't load default configuration. Have you set up your AWS account?")
		fmt.Println(err)
		return
	}
	sqsClient := sqs.NewFromConfig(sdkConfig)
	fmt.Println("Let's list the queues for your account.")
	var queueUrls []string
	paginator := sqs.NewListQueuesPaginator(sqsClient, &sqs.ListQueuesInput{})
	for paginator.HasMorePages() {
		output, err := paginator.NextPage(ctx)
		if err != nil {
			log.Printf("Couldn't get queues. Here's why: %v\n", err)
			break
		} else {
			queueUrls = append(queueUrls, output.QueueUrls...)
		}
	}
	if len(queueUrls) == 0 {
		fmt.Println("You don't have any queues!")
	} else {
		for _, queueUrl := range queueUrls {
			fmt.Printf("\t%v\n", queueUrl)
		}
	}
}
```
+  API の詳細については、**AWS SDK for Go API リファレンスの「[ListQueues](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.ListQueues)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_go_2_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue.
func (actor SqsActions) GetMessages(ctx context.Context, queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) {
	var messages []types.Message
	result, err := actor.SqsClient.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
		QueueUrl:            aws.String(queueUrl),
		MaxNumberOfMessages: maxMessages,
		WaitTimeSeconds:     waitTime,
	})
	if err != nil {
		log.Printf("Couldn't get messages from queue %v. Here's why: %v\n", queueUrl, err)
	} else {
		messages = result.Messages
	}
	return messages, err
}
```
+  API の詳細については、**AWS SDK for Go API リファレンスの「[ReceiveMessage](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.ReceiveMessage)」を参照してください。

### `SetQueueAttributes`
<a name="sqs_SetQueueAttributes_go_2_topic"></a>

次のコード例は、`SetQueueAttributes` を使用する方法を示しています。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an
// Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the
// queue.
func (actor SqsActions) AttachSendMessagePolicy(ctx context.Context, queueUrl string, queueArn string, topicArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:    "Allow",
			Action:    "sqs:SendMessage",
			Principal: map[string]string{"Service": "sns.amazonaws.com"},
			Resource:  aws.String(queueArn),
			Condition: PolicyCondition{"ArnEquals": map[string]string{"aws:SourceArn": topicArn}},
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document. Here's why: %v\n", err)
		return err
	}
	_, err = actor.SqsClient.SetQueueAttributes(ctx, &sqs.SetQueueAttributesInput{
		Attributes: map[string]string{
			string(types.QueueAttributeNamePolicy): string(policyBytes),
		},
		QueueUrl: aws.String(queueUrl),
	})
	if err != nil {
		log.Printf("Couldn't set send message policy on queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}

// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
	Condition PolicyCondition   `json:",omitempty"`
}

// PolicyCondition defines a condition in a policy.
type PolicyCondition map[string]map[string]string
```
+  API の詳細については、**「AWS SDK for Go API リファレンス」の「[SetQueueAttributes](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.SetQueueAttributes)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_go_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"strings"
	"topics_and_queues/actions"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools"
)

const FIFO_SUFFIX = ".fifo"
const TONE_KEY = "tone"

var ToneChoices = []string{"cheerful", "funny", "serious", "sincere"}

// MessageBody is used to deserialize the body of a message from a JSON string.
type MessageBody struct {
	Message string
}

// ScenarioRunner separates the steps of this scenario into individual functions so that
// they are simpler to read and understand.
type ScenarioRunner struct {
	questioner demotools.IQuestioner
	snsActor   *actions.SnsActions
	sqsActor   *actions.SqsActions
}

func (runner ScenarioRunner) CreateTopic(ctx context.Context) (string, string, bool, bool) {
	log.Println("SNS topics can be configured as FIFO (First-In-First-Out) or standard.\n" +
		"FIFO topics deliver messages in order and support deduplication and message filtering.")
	isFifoTopic := runner.questioner.AskBool("\nWould you like to work with FIFO topics? (y/n) ", "y")

	contentBasedDeduplication := false
	if isFifoTopic {
		log.Println(strings.Repeat("-", 88))
		log.Println("Because you have chosen a FIFO topic, deduplication is supported.\n" +
			"Deduplication IDs are either set in the message or are automatically generated\n" +
			"from content using a hash function. If a message is successfully published to\n" +
			"an SNS FIFO topic, any message published and determined to have the same\n" +
			"deduplication ID, within the five-minute deduplication interval, is accepted\n" +
			"but not delivered. For more information about deduplication, see:\n" +
			"\thttps://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.")
		contentBasedDeduplication = runner.questioner.AskBool(
			"\nDo you want to use content-based deduplication instead of entering a deduplication ID? (y/n) ", "y")
	}
	log.Println(strings.Repeat("-", 88))

	topicName := runner.questioner.Ask("Enter a name for your SNS topic. ")
	if isFifoTopic {
		topicName = fmt.Sprintf("%v%v", topicName, FIFO_SUFFIX)
		log.Printf("Because you have selected a FIFO topic, '%v' must be appended to\n"+
			"the topic name.", FIFO_SUFFIX)
	}

	topicArn, err := runner.snsActor.CreateTopic(ctx, topicName, isFifoTopic, contentBasedDeduplication)
	if err != nil {
		panic(err)
	}
	log.Printf("Your new topic with the name '%v' and Amazon Resource Name (ARN) \n"+
		"'%v' has been created.", topicName, topicArn)

	return topicName, topicArn, isFifoTopic, contentBasedDeduplication
}

func (runner ScenarioRunner) CreateQueue(ctx context.Context, ordinal string, isFifoTopic bool) (string, string) {
	queueName := runner.questioner.Ask(fmt.Sprintf("Enter a name for the %v SQS queue. ", ordinal))
	if isFifoTopic {
		queueName = fmt.Sprintf("%v%v", queueName, FIFO_SUFFIX)
		if ordinal == "first" {
			log.Printf("Because you are creating a FIFO SQS queue, '%v' must "+
				"be appended to the queue name.\n", FIFO_SUFFIX)
		}
	}
	queueUrl, err := runner.sqsActor.CreateQueue(ctx, queueName, isFifoTopic)
	if err != nil {
		panic(err)
	}
	log.Printf("Your new SQS queue with the name '%v' and the queue URL "+
		"'%v' has been created.", queueName, queueUrl)

	return queueName, queueUrl
}

func (runner ScenarioRunner) SubscribeQueueToTopic(
	ctx context.Context, queueName string, queueUrl string, topicName string, topicArn string, ordinal string,
	isFifoTopic bool) (string, bool) {

	queueArn, err := runner.sqsActor.GetQueueArn(ctx, queueUrl)
	if err != nil {
		panic(err)
	}
	log.Printf("The ARN of your queue is: %v.\n", queueArn)

	err = runner.sqsActor.AttachSendMessagePolicy(ctx, queueUrl, queueArn, topicArn)
	if err != nil {
		panic(err)
	}
	log.Println("Attached an IAM policy to the queue so the SNS topic can send " +
		"messages to it.")
	log.Println(strings.Repeat("-", 88))

	var filterPolicy map[string][]string
	if isFifoTopic {
		if ordinal == "first" {
			log.Println("Subscriptions to a FIFO topic can have filters.\n" +
				"If you add a filter to this subscription, then only the filtered messages\n" +
				"will be received in the queue.\n" +
				"For information about message filtering, see\n" +
				"\thttps://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n" +
				"For this example, you can filter messages by a \"tone\" attribute.")
		}

		wantFiltering := runner.questioner.AskBool(
			fmt.Sprintf("Do you want to filter messages that are sent to \"%v\"\n"+
				"from the %v topic? (y/n) ", queueName, topicName), "y")
		if wantFiltering {
			log.Println("You can filter messages by one or more of the following \"tone\" attributes.")

			var toneSelections []string
			askAboutTones := true
			for askAboutTones {
				toneIndex := runner.questioner.AskChoice(
					"Enter the number of the tone you want to filter by:\n", ToneChoices)
				toneSelections = append(toneSelections, ToneChoices[toneIndex])
				askAboutTones = runner.questioner.AskBool("Do you want to add another tone to the filter? (y/n) ", "y")
			}
			log.Printf("Your subscription will be filtered to only pass the following tones: %v\n", toneSelections)
			filterPolicy = map[string][]string{TONE_KEY: toneSelections}
		}
	}

	subscriptionArn, err := runner.snsActor.SubscribeQueue(ctx, topicArn, queueArn, filterPolicy)
	if err != nil {
		panic(err)
	}
	log.Printf("The queue %v is now subscribed to the topic %v with the subscription ARN %v.\n",
		queueName, topicName, subscriptionArn)

	return subscriptionArn, filterPolicy != nil
}

func (runner ScenarioRunner) PublishMessages(ctx context.Context, topicArn string, isFifoTopic bool, contentBasedDeduplication bool, usingFilters bool) {
	var message string
	var groupId string
	var dedupId string
	var toneSelection string
	publishMore := true
	for publishMore {
		groupId = ""
		dedupId = ""
		toneSelection = ""
		message = runner.questioner.Ask("Enter a message to publish: ")
		if isFifoTopic {
			log.Println("Because you are using a FIFO topic, you must set a message group ID.\n" +
				"All messages within the same group will be received in the order they were published.")
			groupId = runner.questioner.Ask("Enter a message group ID: ")
			if !contentBasedDeduplication {
				log.Println("Because you are not using content-based deduplication,\n" +
					"you must enter a deduplication ID.")
				dedupId = runner.questioner.Ask("Enter a deduplication ID: ")
			}
		}
		if usingFilters {
			if runner.questioner.AskBool("Add a tone attribute so this message can be filtered? (y/n) ", "y") {
				toneIndex := runner.questioner.AskChoice(
					"Enter the number of the tone you want to filter by:\n", ToneChoices)
				toneSelection = ToneChoices[toneIndex]
			}
		}

		err := runner.snsActor.Publish(ctx, topicArn, message, groupId, dedupId, TONE_KEY, toneSelection)
		if err != nil {
			panic(err)
		}
		log.Println(("Your message was published."))

		publishMore = runner.questioner.AskBool("Do you want to publish another messsage? (y/n) ", "y")
	}
}

func (runner ScenarioRunner) PollForMessages(ctx context.Context, queueUrls []string) {
	log.Println("Polling queues for messages...")
	for _, queueUrl := range queueUrls {
		var messages []types.Message
		for {
			currentMsgs, err := runner.sqsActor.GetMessages(ctx, queueUrl, 10, 1)
			if err != nil {
				panic(err)
			}
			if len(currentMsgs) == 0 {
				break
			}
			messages = append(messages, currentMsgs...)
		}
		if len(messages) == 0 {
			log.Printf("No messages were received by queue %v.\n", queueUrl)
		} else if len(messages) == 1 {
			log.Printf("One message was received by queue %v:\n", queueUrl)

		} else {
			log.Printf("%v messages were received by queue %v:\n", len(messages), queueUrl)
		}
		for msgIndex, message := range messages {
			messageBody := MessageBody{}
			err := json.Unmarshal([]byte(*message.Body), &messageBody)
			if err != nil {
				panic(err)
			}
			log.Printf("Message %v: %v\n", msgIndex+1, messageBody.Message)
		}

		if len(messages) > 0 {
			log.Printf("Deleting %v messages from queue %v.\n", len(messages), queueUrl)
			err := runner.sqsActor.DeleteMessages(ctx, queueUrl, messages)
			if err != nil {
				panic(err)
			}
		}
	}
}

// RunTopicsAndQueuesScenario is an interactive example that shows you how to use the
// AWS SDK for Go to create and use Amazon SNS topics and Amazon SQS queues.
//
// 1. Create a topic (FIFO or non-FIFO).
// 2. Subscribe several queues to the topic with an option to apply a filter.
// 3. Publish messages to the topic.
// 4. Poll the queues for messages received.
// 5. Delete the topic and the queues.
//
// This example creates service clients from the specified sdkConfig so that
// you can replace it with a mocked or stubbed config for unit testing.
//
// It uses a questioner from the `demotools` package to get input during the example.
// This package can be found in the ..\..\demotools folder of this repo.
func RunTopicsAndQueuesScenario(
	ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner) {
	resources := Resources{}
	defer func() {
		if r := recover(); r != nil {
			log.Println("Something went wrong with the demo.\n" +
				"Cleaning up any resources that were created...")
			resources.Cleanup(ctx)
		}
	}()
	queueCount := 2

	log.Println(strings.Repeat("-", 88))
	log.Printf("Welcome to messaging with topics and queues.\n\n"+
		"In this scenario, you will create an SNS topic and subscribe %v SQS queues to the\n"+
		"topic. You can select from several options for configuring the topic and the\n"+
		"subscriptions for the queues. You can then post to the topic and see the results\n"+
		"in the queues.\n", queueCount)

	log.Println(strings.Repeat("-", 88))

	runner := ScenarioRunner{
		questioner: questioner,
		snsActor:   &actions.SnsActions{SnsClient: sns.NewFromConfig(sdkConfig)},
		sqsActor:   &actions.SqsActions{SqsClient: sqs.NewFromConfig(sdkConfig)},
	}
	resources.snsActor = runner.snsActor
	resources.sqsActor = runner.sqsActor

	topicName, topicArn, isFifoTopic, contentBasedDeduplication := runner.CreateTopic(ctx)
	resources.topicArn = topicArn
	log.Println(strings.Repeat("-", 88))

	log.Printf("Now you will create %v SQS queues and subscribe them to the topic.\n", queueCount)
	ordinals := []string{"first", "next"}
	usingFilters := false
	for _, ordinal := range ordinals {
		queueName, queueUrl := runner.CreateQueue(ctx, ordinal, isFifoTopic)
		resources.queueUrls = append(resources.queueUrls, queueUrl)

		_, filtering := runner.SubscribeQueueToTopic(ctx, queueName, queueUrl, topicName, topicArn, ordinal, isFifoTopic)
		usingFilters = usingFilters || filtering
	}

	log.Println(strings.Repeat("-", 88))
	runner.PublishMessages(ctx, topicArn, isFifoTopic, contentBasedDeduplication, usingFilters)
	log.Println(strings.Repeat("-", 88))
	runner.PollForMessages(ctx, resources.queueUrls)

	log.Println(strings.Repeat("-", 88))

	wantCleanup := questioner.AskBool("Do you want to remove all AWS resources created for this scenario? (y/n) ", "y")
	if wantCleanup {
		log.Println("Cleaning up resources...")
		resources.Cleanup(ctx)
	}

	log.Println(strings.Repeat("-", 88))
	log.Println("Thanks for watching!")
	log.Println(strings.Repeat("-", 88))
}
```
この例で使用されている Amazon SNS アクションをラップする構造体を定義します。  

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// 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(ctx context.Context, 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(ctx, &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
}



// DeleteTopic delete an Amazon SNS topic.
func (actor SnsActions) DeleteTopic(ctx context.Context, topicArn string) error {
	_, err := actor.SnsClient.DeleteTopic(ctx, &sns.DeleteTopicInput{
		TopicArn: aws.String(topicArn)})
	if err != nil {
		log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err)
	}
	return err
}



// SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an
// Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy
// so that messages are only sent to the queue when the message has the specified attributes.
func (actor SnsActions) SubscribeQueue(ctx context.Context, topicArn string, queueArn string, filterMap map[string][]string) (string, error) {
	var subscriptionArn string
	var attributes map[string]string
	if filterMap != nil {
		filterBytes, err := json.Marshal(filterMap)
		if err != nil {
			log.Printf("Couldn't create filter policy, here's why: %v\n", err)
			return "", err
		}
		attributes = map[string]string{"FilterPolicy": string(filterBytes)}
	}
	output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{
		Protocol:              aws.String("sqs"),
		TopicArn:              aws.String(topicArn),
		Attributes:            attributes,
		Endpoint:              aws.String(queueArn),
		ReturnSubscriptionArn: true,
	})
	if err != nil {
		log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n",
			queueArn, topicArn, err)
	} else {
		subscriptionArn = *output.SubscriptionArn
	}

	return subscriptionArn, err
}



// Publish publishes a message to an Amazon SNS topic. The message is then sent to all
// subscribers. When the topic is a FIFO topic, the message must also contain a group ID
// and, when ID-based deduplication is used, a deduplication ID. An optional key-value
// filter attribute can be specified so that the message can be filtered according to
// a filter policy.
func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error {
	publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)}
	if groupId != "" {
		publishInput.MessageGroupId = aws.String(groupId)
	}
	if dedupId != "" {
		publishInput.MessageDeduplicationId = aws.String(dedupId)
	}
	if filterKey != "" && filterValue != "" {
		publishInput.MessageAttributes = map[string]types.MessageAttributeValue{
			filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)},
		}
	}
	_, err := actor.SnsClient.Publish(ctx, &publishInput)
	if err != nil {
		log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err)
	}
	return err
}
```
この例で使用されている Amazon SQS アクションをラップする構造体を定義します。  

```
import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sqs"
	"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)

// SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions
// used in the examples.
type SqsActions struct {
	SqsClient *sqs.Client
}



// CreateQueue creates an Amazon SQS queue with the specified name. You can specify
// whether the queue is created as a FIFO queue.
func (actor SqsActions) CreateQueue(ctx context.Context, queueName string, isFifoQueue bool) (string, error) {
	var queueUrl string
	queueAttributes := map[string]string{}
	if isFifoQueue {
		queueAttributes["FifoQueue"] = "true"
	}
	queue, err := actor.SqsClient.CreateQueue(ctx, &sqs.CreateQueueInput{
		QueueName:  aws.String(queueName),
		Attributes: queueAttributes,
	})
	if err != nil {
		log.Printf("Couldn't create queue %v. Here's why: %v\n", queueName, err)
	} else {
		queueUrl = *queue.QueueUrl
	}

	return queueUrl, err
}



// GetQueueArn uses the GetQueueAttributes action to get the Amazon Resource Name (ARN)
// of an Amazon SQS queue.
func (actor SqsActions) GetQueueArn(ctx context.Context, queueUrl string) (string, error) {
	var queueArn string
	arnAttributeName := types.QueueAttributeNameQueueArn
	attribute, err := actor.SqsClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{
		QueueUrl:       aws.String(queueUrl),
		AttributeNames: []types.QueueAttributeName{arnAttributeName},
	})
	if err != nil {
		log.Printf("Couldn't get ARN for queue %v. Here's why: %v\n", queueUrl, err)
	} else {
		queueArn = attribute.Attributes[string(arnAttributeName)]
	}
	return queueArn, err
}



// AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an
// Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the
// queue.
func (actor SqsActions) AttachSendMessagePolicy(ctx context.Context, queueUrl string, queueArn string, topicArn string) error {
	policyDoc := PolicyDocument{
		Version: "2012-10-17",
		Statement: []PolicyStatement{{
			Effect:    "Allow",
			Action:    "sqs:SendMessage",
			Principal: map[string]string{"Service": "sns.amazonaws.com"},
			Resource:  aws.String(queueArn),
			Condition: PolicyCondition{"ArnEquals": map[string]string{"aws:SourceArn": topicArn}},
		}},
	}
	policyBytes, err := json.Marshal(policyDoc)
	if err != nil {
		log.Printf("Couldn't create policy document. Here's why: %v\n", err)
		return err
	}
	_, err = actor.SqsClient.SetQueueAttributes(ctx, &sqs.SetQueueAttributesInput{
		Attributes: map[string]string{
			string(types.QueueAttributeNamePolicy): string(policyBytes),
		},
		QueueUrl: aws.String(queueUrl),
	})
	if err != nil {
		log.Printf("Couldn't set send message policy on queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}

// PolicyDocument defines a policy document as a Go struct that can be serialized
// to JSON.
type PolicyDocument struct {
	Version   string
	Statement []PolicyStatement
}

// PolicyStatement defines a statement in a policy document.
type PolicyStatement struct {
	Effect    string
	Action    string
	Principal map[string]string `json:",omitempty"`
	Resource  *string           `json:",omitempty"`
	Condition PolicyCondition   `json:",omitempty"`
}

// PolicyCondition defines a condition in a policy.
type PolicyCondition map[string]map[string]string



// GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue.
func (actor SqsActions) GetMessages(ctx context.Context, queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) {
	var messages []types.Message
	result, err := actor.SqsClient.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
		QueueUrl:            aws.String(queueUrl),
		MaxNumberOfMessages: maxMessages,
		WaitTimeSeconds:     waitTime,
	})
	if err != nil {
		log.Printf("Couldn't get messages from queue %v. Here's why: %v\n", queueUrl, err)
	} else {
		messages = result.Messages
	}
	return messages, err
}



// DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from
// an Amazon SQS queue.
func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error {
	entries := make([]types.DeleteMessageBatchRequestEntry, len(messages))
	for msgIndex := range messages {
		entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex))
		entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle
	}
	_, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{
		Entries:  entries,
		QueueUrl: aws.String(queueUrl),
	})
	if err != nil {
		log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}



// DeleteQueue deletes an Amazon SQS queue.
func (actor SqsActions) DeleteQueue(ctx context.Context, queueUrl string) error {
	_, err := actor.SqsClient.DeleteQueue(ctx, &sqs.DeleteQueueInput{
		QueueUrl: aws.String(queueUrl)})
	if err != nil {
		log.Printf("Couldn't delete queue %v. Here's why: %v\n", queueUrl, err)
	}
	return err
}
```
リソースをクリーンアップします。  

```
import (
	"context"
	"fmt"
	"log"
	"topics_and_queues/actions"
)

// Resources keeps track of AWS resources created during an example and handles
// cleanup when the example finishes.
type Resources struct {
	topicArn  string
	queueUrls []string
	snsActor  *actions.SnsActions
	sqsActor  *actions.SqsActions
}

// Cleanup deletes all AWS resources created during an example.
func (resources Resources) Cleanup(ctx context.Context) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Something went wrong during cleanup. Use the AWS Management Console\n" +
				"to remove any remaining resources that were created for this scenario.")
		}
	}()

	var err error
	if resources.topicArn != "" {
		log.Printf("Deleting topic %v.\n", resources.topicArn)
		err = resources.snsActor.DeleteTopic(ctx, resources.topicArn)
		if err != nil {
			panic(err)
		}
	}

	for _, queueUrl := range resources.queueUrls {
		log.Printf("Deleting queue %v.\n", queueUrl)
		err = resources.sqsActor.DeleteQueue(ctx, queueUrl)
		if err != nil {
			panic(err)
		}
	}
}
```
+ API の詳細については、「*AWS SDK for Go API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.CreateQueue)
  + [CreateTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.CreateTopic)
  + [DeleteMessageBatch](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.DeleteMessageBatch)
  + [DeleteQueue](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.DeleteQueue)
  + [DeleteTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.DeleteTopic)
  + [GetQueueAttributes](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.GetQueueAttributes)
  + [Publish](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Publish)
  + [ReceiveMessage](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.ReceiveMessage)
  + [SetQueueAttributes](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sqs#Client.SetQueueAttributes)
  + [Subscribe](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Subscribe)
  + [Unsubscribe](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Unsubscribe)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_go_2_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package integration_sqs_to_lambda

import (
	"fmt"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(event events.SQSEvent) error {
	for _, record := range event.Records {
		err := processMessage(record)
		if err != nil {
			return err
		}
	}
	fmt.Println("done")
	return nil
}

func processMessage(record events.SQSMessage) error {
	fmt.Printf("Processed message %s\n", record.Body)
	// TODO: Do interesting work based on the new message
	return nil
}

func main() {
	lambda.Start(handler)
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_go_2_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Go を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package main

import (
	"context"
	"fmt"
	"github.com/aws/aws-lambda-go/events"
	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, sqsEvent events.SQSEvent) (map[string]interface{}, error) {
	batchItemFailures := []map[string]interface{}{}

	for _, message := range sqsEvent.Records {
		if len(message.Body) > 0 {
			// Your message processing condition here
			fmt.Printf("Successfully processed message: %s\n", message.Body)
		} else {
			// Message processing failed
			fmt.Printf("Failed to process message %s\n", message.MessageId)
			batchItemFailures = append(batchItemFailures, map[string]interface{}{"itemIdentifier": message.MessageId})
		}
	}

	sqsBatchResponse := map[string]interface{}{
		"batchItemFailures": batchItemFailures,
	}
	return sqsBatchResponse, nil
}

func main() {
	lambda.Start(handler)
}
```

# SDK for JavaScript (v2) のコード例
<a name="javascript_2_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v2) を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for JavaScript (v2) デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/welcome.html) ** – で JavaScript を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23javascript)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [CloudWatch](javascript_2_cloudwatch_code_examples.md)
+ [CloudWatch Events](javascript_2_cloudwatch-events_code_examples.md)
+ [CloudWatch Logs](javascript_2_cloudwatch-logs_code_examples.md)
+ [DynamoDB](javascript_2_dynamodb_code_examples.md)
+ [AWS Entity Resolution](javascript_2_entityresolution_code_examples.md)
+ [EventBridge](javascript_2_eventbridge_code_examples.md)
+ [Amazon Glacier](javascript_2_glacier_code_examples.md)
+ [IAM](javascript_2_iam_code_examples.md)
+ [Lambda](javascript_2_lambda_code_examples.md)
+ [Amazon Pinpoint](javascript_2_pinpoint_code_examples.md)
+ [Amazon Pinpoint SMS および音声 API](javascript_2_pinpoint-sms-voice_code_examples.md)
+ [Amazon SNS](javascript_2_sns_code_examples.md)
+ [Amazon SQS](javascript_2_sqs_code_examples.md)
+ [AWS STS](javascript_2_sts_code_examples.md)

# SDK for JavaScript (v2) を使用した CloudWatch の例
<a name="javascript_2_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_javascript_2_topic"></a>

次のコード例は、`DeleteAlarms` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  AlarmNames: ["Web_Server_CPU_Utilization"],
};

cw.deleteAlarms(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html#cloudwatch-examples-creating-alarms-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteAlarms](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/DeleteAlarms)」を参照してください。

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_javascript_2_topic"></a>

次のコード例は、`DescribeAlarmsForMetric` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

cw.describeAlarms({ StateValue: "INSUFFICIENT_DATA" }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    // List the names of all current alarms in the console
    data.MetricAlarms.forEach(function (item, index, array) {
      console.log(item.AlarmName);
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html#cloudwatch-examples-creating-alarms-describing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/DescribeAlarmsForMetric)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_javascript_2_topic"></a>

次のコード例は、`DisableAlarmActions` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

cw.disableAlarmActions(
  { AlarmNames: ["Web_Server_CPU_Utilization"] },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-using-alarm-actions.html#cloudwatch-examples-using-alarm-actions-disabling)」を参照してください。
+  API 詳細については、*AWS SDK for JavaScript API リファレンス*の「[DisableAlarmActions](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/DisableAlarmActions)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_javascript_2_topic"></a>

次のコード例は、`EnableAlarmActions` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  AlarmName: "Web_Server_CPU_Utilization",
  ComparisonOperator: "GreaterThanThreshold",
  EvaluationPeriods: 1,
  MetricName: "CPUUtilization",
  Namespace: "AWS/EC2",
  Period: 60,
  Statistic: "Average",
  Threshold: 70.0,
  ActionsEnabled: true,
  AlarmActions: ["ACTION_ARN"],
  AlarmDescription: "Alarm when server CPU exceeds 70%",
  Dimensions: [
    {
      Name: "InstanceId",
      Value: "INSTANCE_ID",
    },
  ],
  Unit: "Percent",
};

cw.putMetricAlarm(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Alarm action added", data);
    var paramsEnableAlarmAction = {
      AlarmNames: [params.AlarmName],
    };
    cw.enableAlarmActions(paramsEnableAlarmAction, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Alarm action enabled", data);
      }
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-using-alarm-actions.html#cloudwatch-examples-using-alarm-actions-enabling)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[EnableAlarmActions](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/EnableAlarmActions)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_javascript_2_topic"></a>

次のコード例は、`ListMetrics` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  Dimensions: [
    {
      Name: "LogGroupName" /* required */,
    },
  ],
  MetricName: "IncomingLogEvents",
  Namespace: "AWS/Logs",
};

cw.listMetrics(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Metrics", JSON.stringify(data.Metrics));
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-getting-metrics.html#cloudwatch-examples-getting-metrics-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListMetrics](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/ListMetrics)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_javascript_2_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

var params = {
  AlarmName: "Web_Server_CPU_Utilization",
  ComparisonOperator: "GreaterThanThreshold",
  EvaluationPeriods: 1,
  MetricName: "CPUUtilization",
  Namespace: "AWS/EC2",
  Period: 60,
  Statistic: "Average",
  Threshold: 70.0,
  ActionsEnabled: false,
  AlarmDescription: "Alarm when server CPU exceeds 70%",
  Dimensions: [
    {
      Name: "InstanceId",
      Value: "INSTANCE_ID",
    },
  ],
  Unit: "Percent",
};

cw.putMetricAlarm(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html#cloudwatch-examples-creating-alarms-putmetricalarm)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutMetricAlarm](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/PutMetricAlarm)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_javascript_2_topic"></a>

次のコード例は、`PutMetricData` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatch service object
var cw = new AWS.CloudWatch({ apiVersion: "2010-08-01" });

// Create parameters JSON for putMetricData
var params = {
  MetricData: [
    {
      MetricName: "PAGES_VISITED",
      Dimensions: [
        {
          Name: "UNIQUE_PAGES",
          Value: "URLS",
        },
      ],
      Unit: "None",
      Value: 1.0,
    },
  ],
  Namespace: "SITE/TRAFFIC",
};

cw.putMetricData(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", JSON.stringify(data));
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-getting-metrics.html#cloudwatch-examples-getting-metrics-publishing-custom)」を参照してください。
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[PutMetricData](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/PutMetricData)」を参照してください。

# SDK for JavaScript (v2) を使用した CloudWatch Events の例
<a name="javascript_2_cloudwatch-events_code_examples"></a>

次のコード例は、CloudWatch Events で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="cloudwatch-events_PutEvents_javascript_2_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch-events#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Entries: [
    {
      Detail: '{ "key1": "value1", "key2": "value2" }',
      DetailType: "appRequestSubmitted",
      Resources: ["RESOURCE_ARN"],
      Source: "com.company.app",
    },
  ],
};

cwevents.putEvents(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Entries);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html#cloudwatch-examples-sending-events-putevents)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/PutEvents)」を参照してください。

### `PutRule`
<a name="cloudwatch-events_PutRule_javascript_2_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch-events#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Name: "DEMO_EVENT",
  RoleArn: "IAM_ROLE_ARN",
  ScheduleExpression: "rate(5 minutes)",
  State: "ENABLED",
};

cwevents.putRule(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.RuleArn);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html#cloudwatch-examples-sending-events-rules)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutRule](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/PutRule)」を参照してください。

### `PutTargets`
<a name="cloudwatch-events_PutTargets_javascript_2_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch-events#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var cwevents = new AWS.CloudWatchEvents({ apiVersion: "2015-10-07" });

var params = {
  Rule: "DEMO_EVENT",
  Targets: [
    {
      Arn: "LAMBDA_FUNCTION_ARN",
      Id: "myCloudWatchEventsTarget",
    },
  ],
};

cwevents.putTargets(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-sending-events.html#cloudwatch-examples-sending-events-targets)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/monitoring-2010-08-01/PutTargets)」を参照してください。

# SDK for JavaScript (v2) を使用した CloudWatch Logs の例
<a name="javascript_2_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteSubscriptionFilter`
<a name="cloudwatch-logs_DeleteSubscriptionFilter_javascript_2_topic"></a>

次のコード例は、`DeleteSubscriptionFilter` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the CloudWatchLogs service object
var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" });

var params = {
  filterName: "FILTER",
  logGroupName: "LOG_GROUP",
};

cwl.deleteSubscriptionFilter(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html#cloudwatch-examples-subscriptions-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteSubscriptionFilter](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/logs-2014-03-28/DeleteSubscriptionFilter)」を参照してください。

### `DescribeSubscriptionFilters`
<a name="cloudwatch-logs_DescribeSubscriptionFilters_javascript_2_topic"></a>

次のコード例は、`DescribeSubscriptionFilters` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the CloudWatchLogs service object
var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" });

var params = {
  logGroupName: "GROUP_NAME",
  limit: 5,
};

cwl.describeSubscriptionFilters(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.subscriptionFilters);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html#cloudwatch-examples-subscriptions-describing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeSubscriptionFilters](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/logs-2014-03-28/DescribeSubscriptionFilters)」を参照してください。

### `PutSubscriptionFilter`
<a name="cloudwatch-logs_PutSubscriptionFilter_javascript_2_topic"></a>

次のコード例は、`PutSubscriptionFilter` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the CloudWatchLogs service object
var cwl = new AWS.CloudWatchLogs({ apiVersion: "2014-03-28" });

var params = {
  destinationArn: "LAMBDA_FUNCTION_ARN",
  filterName: "FILTER_NAME",
  filterPattern: "ERROR",
  logGroupName: "LOG_GROUP",
};

cwl.putSubscriptionFilter(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-subscriptions.html#cloudwatch-examples-subscriptions-creating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutSubscriptionFilter](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/logs-2014-03-28/PutSubscriptionFilter)」を参照してください。

# SDK for JavaScript (v2) を使用した DynamoDB の例
<a name="javascript_2_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_javascript_2_topic"></a>

次のコード例は、`BatchGetItem` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  RequestItems: {
    TABLE_NAME: {
      Keys: [
        { KEY_NAME: { N: "KEY_VALUE_1" } },
        { KEY_NAME: { N: "KEY_VALUE_2" } },
        { KEY_NAME: { N: "KEY_VALUE_3" } },
      ],
      ProjectionExpression: "KEY_NAME, ATTRIBUTE",
    },
  },
};

ddb.batchGetItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    data.Responses.TABLE_NAME.forEach(function (element, index, array) {
      console.log(element);
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write-batch.html#dynamodb-example-table-read-write-batch-reading)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[BatchGetItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/BatchGetItem)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_javascript_2_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  RequestItems: {
    TABLE_NAME: [
      {
        PutRequest: {
          Item: {
            KEY: { N: "KEY_VALUE" },
            ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" },
            ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            KEY: { N: "KEY_VALUE" },
            ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" },
            ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" },
          },
        },
      },
    ],
  },
};

ddb.batchWriteItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write-batch.html#dynamodb-example-table-read-write-batch-writing)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[BatchWriteItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。**

### `CreateTable`
<a name="dynamodb_CreateTable_javascript_2_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  AttributeDefinitions: [
    {
      AttributeName: "CUSTOMER_ID",
      AttributeType: "N",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      AttributeType: "S",
    },
  ],
  KeySchema: [
    {
      AttributeName: "CUSTOMER_ID",
      KeyType: "HASH",
    },
    {
      AttributeName: "CUSTOMER_NAME",
      KeyType: "RANGE",
    },
  ],
  ProvisionedThroughput: {
    ReadCapacityUnits: 1,
    WriteCapacityUnits: 1,
  },
  TableName: "CUSTOMER_LIST",
  StreamSpecification: {
    StreamEnabled: false,
  },
};

// Call DynamoDB to create the table
ddb.createTable(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Table Created", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_javascript_2_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルから項目を削除します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "TABLE",
  Key: {
    KEY_NAME: { N: "VALUE" },
  },
};

// Call DynamoDB to delete the item from the table
ddb.deleteItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
DynamoDB ドキュメントクライアントを使用して、テーブルから項目を削除します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  Key: {
    HASH_KEY: VALUE,
  },
  TableName: "TABLE",
};

docClient.delete(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html#dynamodb-example-table-read-write-deleting-an-item)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DeleteItem)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_javascript_2_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: process.argv[2],
};

// Call DynamoDB to delete the specified table
ddb.deleteTable(params, function (err, data) {
  if (err && err.code === "ResourceNotFoundException") {
    console.log("Error: Table not found");
  } else if (err && err.code === "ResourceInUseException") {
    console.log("Error: Table in use");
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-deleting-a-table)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_javascript_2_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: process.argv[2],
};

// Call DynamoDB to retrieve the selected table descriptions
ddb.describeTable(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Table.KeySchema);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-describing-a-table)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeTable](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/DescribeTable)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_javascript_2_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルから項目を取得します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "TABLE",
  Key: {
    KEY_NAME: { N: "001" },
  },
  ProjectionExpression: "ATTRIBUTE_NAME",
};

// Call DynamoDB to read the item from the table
ddb.getItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Item);
  }
});
```
DynamoDB ドキュメントクライアントを使用して、テーブルから項目を取得します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  TableName: "EPISODES_TABLE",
  Key: { KEY_NAME: VALUE },
};

docClient.get(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Item);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-dynamodb-utilities.html#dynamodb-example-document-client-get)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/GetItem)」を参照してください。**

### `ListTables`
<a name="dynamodb_ListTables_javascript_2_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

// Call DynamoDB to retrieve the list of tables
ddb.listTables({ Limit: 10 }, function (err, data) {
  if (err) {
    console.log("Error", err.code);
  } else {
    console.log("Table names are ", data.TableNames);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-listing-tables)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListTables](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_javascript_2_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルに項目を配置します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

var params = {
  TableName: "CUSTOMER_LIST",
  Item: {
    CUSTOMER_ID: { N: "001" },
    CUSTOMER_NAME: { S: "Richard Roe" },
  },
};

// Call DynamoDB to add the item to the table
ddb.putItem(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
DynamoDB ドキュメントクライアントを使用して、テーブルに項目を配置します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  TableName: "TABLE",
  Item: {
    HASHKEY: VALUE,
    ATTRIBUTE_1: "STRING_VALUE",
    ATTRIBUTE_2: VALUE_2,
  },
};

docClient.put(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-table-read-write.html#dynamodb-example-table-read-write-writing-an-item)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/PutItem)」を参照してください。**

### `Query`
<a name="dynamodb_Query_javascript_2_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

var params = {
  ExpressionAttributeValues: {
    ":s": 2,
    ":e": 9,
    ":topic": "PHRASE",
  },
  KeyConditionExpression: "Season = :s and Episode > :e",
  FilterExpression: "contains (Subtitle, :topic)",
  TableName: "EPISODES_TABLE",
};

docClient.query(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Items);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/Query)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_javascript_2_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js.
var AWS = require("aws-sdk");
// Set the AWS Region.
AWS.config.update({ region: "REGION" });

// Create DynamoDB service object.
var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" });

const params = {
  // Specify which items in the results are returned.
  FilterExpression: "Subtitle = :topic AND Season = :s AND Episode = :e",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: "SubTitle2" },
    ":s": { N: 1 },
    ":e": { N: 2 },
  },
  // Set the projection expression, which are the attributes that you want.
  ProjectionExpression: "Season, Episode, Title, Subtitle",
  TableName: "EPISODES_TABLE",
};

ddb.scan(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
    data.Items.forEach(function (element, index, array) {
      console.log(
        "printing",
        element.Title.S + " (" + element.Subtitle.S + ")"
      );
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-scanning)」を参照してください。
+  API の詳細については、[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/dynamodb-2012-08-10/Scan)の「*Scan*」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ブラウザからの Lambda 関数の呼び出し
<a name="cross_LambdaForBrowser_javascript_2_topic"></a>

次のコード例は、ブラウザから AWS Lambda 関数を呼び出す方法を示しています。

**SDK for JavaScript (v2)**  
 AWS Lambda 関数を使用して Amazon DynamoDB テーブルをユーザー選択で更新するブラウザベースのアプリケーションを作成できます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/lambda/lambda-for-browser) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda

# AWS Entity Resolution SDK for JavaScript (v2) を使用した例
<a name="javascript_2_entityresolution_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Entity Resolution。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="entityresolution_Scenario_javascript_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ スキーママッピングを作成します。
+  AWS Entity Resolution ワークフローを作成します。
+ ワークフローの照合ジョブを開始します。
+ 照合ジョブの詳細を取得します。
+ スキーママッピングを取得します。
+ すべてのスキーママッピングを一覧表示します。
+ スキーママッピングリソースにタグを付けます。
+  AWS Entity Resolution アセットを削除します。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。
 AWS Entity Resolution 機能を示すインタラクティブなシナリオを実行します。  

```
import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import {
  CloudFormationClient,
  CreateStackCommand,
  DeleteStackCommand,
  DescribeStacksCommand,
  waitUntilStackExists,
  waitUntilStackCreateComplete,
} from "@aws-sdk/client-cloudformation";
import {
  EntityResolutionClient,
  CreateSchemaMappingCommand,
  CreateMatchingWorkflowCommand,
  GetMatchingJobCommand,
  StartMatchingJobCommand,
  GetSchemaMappingCommand,
  ListSchemaMappingsCommand,
  TagResourceCommand,
  DeleteMatchingWorkflowCommand,
  DeleteSchemaMappingCommand,
  ConflictException,
  ValidationException,
} from "@aws-sdk/client-entityresolution";
import {
  DeleteObjectsCommand,
  DeleteBucketCommand,
  PutObjectCommand,
  S3Client,
  ListObjectsCommand,
} from "@aws-sdk/client-s3";
import { wait } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { readFile } from "node:fs/promises";
import { parseArgs } from "node:util";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const stackName = `${data.inputs.entityResolutionStack}`;

/*The inputs for this example can be edited in the ../input.json.*/
import data from "../inputs.json" with { type: "json" };
const skipWhenErrors = (state) => state.errors.length > 0;
/**
 * Used repeatedly to have the user press enter.
 * @type {ScenarioInput}
 */
/* v8 ignore next 3 */
const pressEnter = new ScenarioInput("continue", "Press Enter to continue", {
  type: "input",
  verbose: "false",
  skipWhen: skipWhenErrors,
});

const region = "eu-west-1";

const entityResolutionClient = new EntityResolutionClient({ region: region });
const cloudFormationClient = new CloudFormationClient({ region: region });
const s3Client = new S3Client({ region: region });

const greet = new ScenarioOutput(
  "greet",
  "AWS Entity Resolution is a fully-managed machine learning service provided by " +
    "Amazon Web Services (AWS) that helps organizations extract, link, and " +
    "organize information from multiple data sources. It leverages natural " +
    "language processing and deep learning models to identify and resolve " +
    "entities, such as people, places, organizations, and products, " +
    "across structured and unstructured data.\n" +
    "\n" +
    "With Entity Resolution, customers can build robust data integration " +
    "pipelines to combine and reconcile data from multiple systems, databases, " +
    "and documents. The service can handle ambiguous, incomplete, or conflicting " +
    "information, and provide a unified view of entities and their relationships. " +
    "This can be particularly valuable in applications such as customer 360, " +
    "fraud detection, supply chain management, and knowledge management, where " +
    "accurate entity identification is crucial.\n" +
    "\n" +
    "The `EntityResolutionAsyncClient` interface in the AWS SDK for Java 2.x " +
    "provides a set of methods to programmatically interact with the AWS Entity " +
    "Resolution service. This allows developers to automate the entity extraction, " +
    "linking, and deduplication process as part of their data processing workflows. " +
    "With Entity Resolution, organizations can unlock the value of their data, " +
    "improve decision-making, and enhance customer experiences by having a reliable, " +
    "comprehensive view of their key entities.",

  { header: true },
);
const displayBuildCloudFormationStack = new ScenarioOutput(
  "displayBuildCloudFormationStack",
  "To prepare the AWS resources needed for this scenario application, the next step uploads " +
    "a CloudFormation template whose resulting stack creates the following resources:\n" +
    "- An AWS Glue Data Catalog table \n" +
    "- An AWS IAM role \n" +
    "- An AWS S3 bucket \n" +
    "- An AWS Entity Resolution Schema \n" +
    "It can take a couple minutes for the Stack to finish creating the resources.",
);

const sdkBuildCloudFormationStack = new ScenarioAction(
  "sdkBuildCloudFormationStack",
  async (/** @type {State} */ state) => {
    try {
      const data = readFileSync(
        `${__dirname}/../../../../resources/cfn/entity-resolution-basics/entity-resolution-basics-template.yml`,
        "utf8",
      );
      await cloudFormationClient.send(
        new CreateStackCommand({
          StackName: stackName,
          TemplateBody: data,
          Capabilities: ["CAPABILITY_IAM"],
        }),
      );
      await waitUntilStackExists(
        { client: cloudFormationClient },
        { StackName: stackName },
      );
      await waitUntilStackCreateComplete(
        { client: cloudFormationClient },
        { StackName: stackName },
      );
      const stack = await cloudFormationClient.send(
        new DescribeStacksCommand({
          StackName: stackName,
        }),
      );

      state.entityResolutionRole = stack.Stacks[0].Outputs[1];
      state.jsonGlueTable = stack.Stacks[0].Outputs[2];
      state.CSVGlueTable = stack.Stacks[0].Outputs[3];
      state.glueDataBucket = stack.Stacks[0].Outputs[0];
      state.stackName = stack.StackName;
      console.log(state.glueDataBucket);
      console.log(
        `The  ARN of the EntityResolution Role is ${state.entityResolutionRole.OutputValue}`,
      );
      console.log(
        `The ARN of the Json Glue Table is ${state.jsonGlueTable.OutputValue}`,
      );
      console.log(
        `The ARN of the CSV Glue Table is ${state.CSVGlueTable.OutputValue}`,
      );
      console.log(
        `The name of the Glue Data Bucket is ${state.glueDataBucket.OutputValue}\n`,
      );
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
    try {
      console.log(
        `Uploading the following JSON in ../data.json to the ${state.glueDataBucket.OutputValue} S3 bucket...`,
      );
      const bucketName = state.glueDataBucket.OutputValue;

      const putObjectParams = {
        Bucket: bucketName,
        Key: "jsonData/data.json",
        Body: await readFileSync(
          `${__dirname}/../../../../javascriptv3/example_code/entityresolution/data.json`,
        ),
      };
      const command = new PutObjectCommand(putObjectParams);
      const response = await s3Client.send(command);
      console.log(
        `../data.json file data uploaded to the ${state.glueDataBucket.OutputValue} S3 bucket.\n`,
      );
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
    try {
      console.log(
        `Uploading the CSV data in ../data.csv to the ${state.glueDataBucket.OutputValue} S3 bucket...`,
      );

      const bucketName = state.glueDataBucket.OutputValue;
      const putObjectParams = {
        Bucket: bucketName,
        Key: "csvData/data.csv",
        Body: await readFileSync(
          `${__dirname}/../../../../javascriptv3/example_code/entityresolution/data.csv`,
        ),
      };
      const command = new PutObjectCommand(putObjectParams);
      const response = await s3Client.send(command);
      console.log(
        `../data.csv file data uploaded to the ${state.glueDataBucket.OutputValue} S3 bucket.`,
      );
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
  },
);

const displayCreateSchemaMapping = new ScenarioOutput(
  "displayCreateSchemaMapping",
  "1. Create Schema Mapping" +
    "Entity Resolution schema mapping aligns and integrates data from " +
    "multiple sources by identifying and matching corresponding entities " +
    "like customers or products. It unifies schemas, resolves conflicts, " +
    "and uses machine learning to link related entities, enabling a " +
    "consolidated, accurate view for improved data quality and decision-making." +
    "\n" +
    "In this example, the schema mapping lines up with the fields in the JSON and CSV objects. That is, " +
    " it contains these fields: id, name, and email. ",
);

const sdkCreateSchemaMapping = new ScenarioAction(
  "sdkCreateSchemaMapping",
  async (/** @type {State} */ state) => {
    const createSchemaMappingParamsJson = {
      schemaName: `${data.inputs.schemaNameJson}`,
      mappedInputFields: [
        {
          fieldName: "id",
          type: "UNIQUE_ID",
        },
        {
          fieldName: "name",
          type: "NAME",
        },
        {
          fieldName: "email",
          type: "EMAIL_ADDRESS",
        },
      ],
    };
    const createSchemaMappingParamsCSV = {
      schemaName: `${data.inputs.schemaNameCSV}`,
      mappedInputFields: [
        {
          fieldName: "id",
          type: "UNIQUE_ID",
        },
        {
          fieldName: "name",
          type: "NAME",
        },
        {
          fieldName: "email",
          type: "EMAIL_ADDRESS",
        },
        {
          fieldName: "phone",
          type: "PROVIDER_ID",
          subType: "STRING",
        },
      ],
    };
    try {
      const command = new CreateSchemaMappingCommand(
        createSchemaMappingParamsJson,
      );
      const response = await entityResolutionClient.send(command);
      state.schemaNameJson = response.schemaName;
      state.schemaArn = response.schemaArn;
      state.idOutputAttribute = response.mappedInputFields[0].fieldName;
      state.nameOutputAttribute = response.mappedInputFields[1].fieldName;
      state.emailOutputAttribute = response.mappedInputFields[2].fieldName;

      console.log("The JSON schema mapping name is ", state.schemaNameJson);
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `The schema mapping already exists: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
    try {
      const command = new CreateSchemaMappingCommand(
        createSchemaMappingParamsCSV,
      );
      const response = await entityResolutionClient.send(command);
      state.schemaNameCSV = response.schemaName;
      state.phoneOutputAttribute = response.mappedInputFields[3].fieldName;
      console.log("The CSV schema mapping name is ", state.schemaNameCSV);
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `An unexpected error occurred while creating the geofence collection: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
  },
);
const displayCreateMatchingWorkflow = new ScenarioOutput(
  "displayCreateMatchingWorkflow",
  "2. Create an AWS Entity Resolution Workflow. " +
    "An Entity Resolution matching workflow identifies and links records " +
    "across datasets that represent the same real-world entity, such as " +
    "customers or products. Using techniques like schema mapping, " +
    "data profiling, and machine learning algorithms, " +
    "it evaluates attributes like names or emails to detect duplicates " +
    "or relationships, even with variations or inconsistencies. " +
    "The workflow outputs consolidated, de-duplicated data." +
    "\n" +
    "We will use the machine learning-based matching technique.",
);

const sdkCreateMatchingWorkflow = new ScenarioAction(
  "sdkCreateMatchingWorkflow",
  async (/** @type {State} */ state) => {
    const createMatchingWorkflowParams = {
      roleArn: `${state.entityResolutionRole.OutputValue}`,
      workflowName: `${data.inputs.workflowName}`,
      description: "Created by using the AWS SDK for JavaScript (v3).",
      inputSourceConfig: [
        {
          inputSourceARN: `${state.jsonGlueTable.OutputValue}`,
          schemaName: `${data.inputs.schemaNameJson}`,
          applyNormalization: false,
        },
        {
          inputSourceARN: `${state.CSVGlueTable.OutputValue}`,
          schemaName: `${data.inputs.schemaNameCSV}`,
          applyNormalization: false,
        },
      ],
      outputSourceConfig: [
        {
          outputS3Path: `s3://${state.glueDataBucket.OutputValue}/eroutput`,
          output: [
            {
              name: state.idOutputAttribute,
            },
            {
              name: state.nameOutputAttribute,
            },
            {
              name: state.emailOutputAttribute,
            },
            {
              name: state.phoneOutputAttribute,
            },
          ],
          applyNormalization: false,
        },
      ],
      resolutionTechniques: { resolutionType: "ML_MATCHING" },
    };
    try {
      const command = new CreateMatchingWorkflowCommand(
        createMatchingWorkflowParams,
      );
      const response = await entityResolutionClient.send(command);
      state.workflowArn = response.workflowArn;
      console.log(
        `Workflow created successfully.\n The workflow ARN is: ${response.workflowArn}`,
      );
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `The matching workflow already exists: ${caught.message} \n Exiting program.`,
        );
        return;
      }
      if (caught instanceof ValidationException) {
        console.error(
          `There was a validation exception: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
  },
);
const displayMatchingJobOfWorkflow = new ScenarioOutput(
  "displayMatchingJobOfWorkflow",
  "3. Start the matching job of the workflow",
);

const sdkMatchingJobOfWorkflow = new ScenarioAction(
  "sdk",
  async (/** @type {State} */ state) => {
    const matchingJobOfWorkflowParams = {
      workflowName: `${data.inputs.workflowName}`,
    };
    try {
      const command = new StartMatchingJobCommand(matchingJobOfWorkflowParams);
      const response = await entityResolutionClient.send(command);
      state.jobID = response.jobId;
      console.log(`Job ID: ${state.jobID} \n
The matching job was successfully started.`);
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `The matching workflow already exists: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
  },
);

const displayGetDetailsforJob = new ScenarioOutput(
  "displayGetDetailsforJob",
  `4. While the matching job is running, let's look at other API methods. First, let's get details for the job `,
);

const sdkGetDetailsforJob = new ScenarioAction(
  "sdkGetDetailsforJob",
  async (/** @type {State} */ state) => {
    const getDetailsforJobParams = {
      workflowName: `${data.inputs.workflowName}`,
      jobId: `${state.jobID}`,
    };
    try {
      const command = new GetMatchingJobCommand(getDetailsforJobParams);
      const response = await entityResolutionClient.send(command);
      state.Status = response.status;
      state.response = response;
      console.log(`Job status: ${state.Status} `);
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
  },
);

const displayGetSchemaMappingJson = new ScenarioOutput(
  "displayGetSchemaMappingJson",
  "5. Get the schema mapping for the JSON data.",
);

const sdkGetSchemaMappingJson = new ScenarioAction(
  "sdkGetSchemaMappingJson",
  async (/** @type {State} */ state) => {
    const getSchemaMappingJsonParams = {
      schemaName: `${data.inputs.schemaNameJson}`,
    };
    try {
      const command = new GetSchemaMappingCommand(getSchemaMappingJsonParams);
      const response = await entityResolutionClient.send(command);
      console.log("Schema·mapping·ARN·is:·", response.schemaArn);
      const resultMappings = response.mappedInputFields;
      const noOfResultMappings = resultMappings.length;
      for (let i = 0; i < noOfResultMappings; i++) {
        console.log(
          `Attribute name: ${resultMappings[i].fieldName} `,
          `Attribute type: ${resultMappings[i].type}`,
        );
      }
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
  },
);

const displayListSchemaMappings = new ScenarioOutput(
  "displayListSchemaMappings",
  "6. List Schema Mappings.",
);

const sdkListSchemaMappings = new ScenarioAction(
  "sdkListSchemaMappings",
  async (/** @type {State} */ state) => {
    try {
      const command = new ListSchemaMappingsCommand({});
      const response = await entityResolutionClient.send(command);
      const noOfSchemas = response.schemaList.length;
      for (let i = 0; i < noOfSchemas; i++) {
        console.log(
          `Schema Mapping Name: ${response.schemaList[i].schemaName} `,
        );
      }
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
  },
);

const displayTagTheJsonSchema = new ScenarioOutput(
  "display",
  "7. Tag the resource. \n" +
    "Tags can help you organize and categorize your Entity Resolution resources. " +
    "You can also use them to scope user permissions by granting a user permission " +
    "to access or change only resources with certain tag values. " +
    "In Entity Resolution, SchemaMapping and MatchingWorkflow can be tagged. For this example, " +
    "the SchemaMapping is tagged.",
);

const sdkTagTheJsonSchema = new ScenarioAction(
  "sdkGetSchemaMappingJson",
  async (/** @type {State} */ state) => {
    const tagResourceCommandParams = {
      resourceArn: state.schemaArn,
      tags: {
        tag1: "tag1Value",
        tag2: "tag2Value",
      },
    };
    try {
      const command = new TagResourceCommand(tagResourceCommandParams);
      const response = await entityResolutionClient.send(command);
      console.log("Successfully tagged the resource.");
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
  },
);

const displayGetJobInfo = new ScenarioOutput(
  "displayGetJobInfo",
  "8. View the results of the AWS Entity Resolution Workflow.\n " +
    "Please perform this task manually in the AWS Management Console. ",
);

const displayDeleteResources = new ScenarioOutput(
  "displayDeleteResources",
  "9. Delete the resources \n" +
    "You cannot delete a workflow that is in a running state. So this will take ~30 minutes.\n" +
    "If you don't want to delete the resources, simply exit this application.",
);

const sdkDeleteResources = new ScenarioAction(
  "sdkDeleteResources",
  async (/** @type {State} */ state) => {
    console.log(
      "You selected to delete the resources. This will take about 30 minutes.",
    );
    await wait(1800);
    const bucketName = state.glueDataBucket.OutputValue;
    try {
      const emptyBucket = async ({ bucketName }) => {
        const listObjectsCommand = new ListObjectsCommand({
          Bucket: bucketName,
        });
        const { Contents } = await s3Client.send(listObjectsCommand);
        const keys = Contents.map((c) => c.Key);

        const deleteObjectsCommand = new DeleteObjectsCommand({
          Bucket: bucketName,
          Delete: { Objects: keys.map((key) => ({ Key: key })) },
        });
        await s3Client.send(deleteObjectsCommand);
        console.log(`Bucket ${bucketName} emptied successfully.\n`);
      };
      await emptyBucket({ bucketName });
    } catch (error) {
      console.log("error ", error);
    }
    try {
      const deleteBucket = async ({ bucketName }) => {
        const command = new DeleteBucketCommand({ Bucket: bucketName });
        await s3Client.send(command);
        console.log(`Bucket ${bucketName} deleted successfully.\n`);
      };
      await deleteBucket({ bucketName });
    } catch (error) {
      console.log("error ", error);
    }
    try {
      console.log(
        "Now we will delete the CloudFormation stack, which deletes the resources that were created at the beginning of the scenario.",
      );
      const deleteStackParams = { StackName: `${state.stackName}` };
      const command = new DeleteStackCommand(deleteStackParams);
      const response = await cloudFormationClient.send(command);
      console.log("CloudFormation stack deleted successfully.");
    } catch (error) {
      console.log("error ", error);
    }
    try {
      const deleteWorkflowParams = {
        workflowName: `${data.inputs.workflowName}`,
      };
      const command = new DeleteMatchingWorkflowCommand(deleteWorkflowParams);
      const response = await entityResolutionClient.send(command);
      console.log("Workflow deleted successfully!");
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `Job associated with workflow ${data.inputs.workflowName} is still running, so can't be deleted. 
          Neither can schemas ${data.inputs.schemaNameJson} and ${data.inputs.schemaNameCSV} associated with it. Please confirm this workflow is finished in the AWS Management Console, then delete it manually.`,
        );
        throw caught;
      }
    }
    try {
      const deleteJSONschemaMapping = {
        schemaName: `${data.inputs.schemaNameJson}`,
      };
      const command = new DeleteSchemaMappingCommand(deleteJSONschemaMapping);
      const response = await entityResolutionClient.send(command);
      console.log("Schema mapping deleted successfully. ");
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `The schema ${data.inputs.schemaNameJson} can't be deleted because it is associated with workflow
           ${data.inputs.workflowName}, which is still running. Please confirm this workflow is finished in the AWS Management Console, then delete it manually.`,
        );
        throw caught;
      }
    }
    try {
      const deleteCSVschemaMapping = {
        schemaName: `${data.inputs.schemaNameCSV}`,
      };
      const command = new DeleteSchemaMappingCommand(deleteCSVschemaMapping);
      const response = await entityResolutionClient.send(command);
      console.log("Schema mapping deleted successfully.");
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `The schema ${data.inputs.schemaNameCSV} can't be deleted because it is associated with workflow ${data.inputs.workflowName}, which is still running. Please confirm this workflow is finished in the AWS Management Console, then delete it manually.`,
        );
        throw caught;
      }
    }
  },
  {
    skipWhen: (/** @type {State} */ state) =>
      state.confirmDeleteResources === "",
  },
);

const goodbye = new ScenarioOutput(
  "goodbye",
  "Thank you for checking out the Amazon Location Service Use demo. We hope you " +
    "learned something new, or got some inspiration for your own apps today!" +
    " For more Amazon Location Services examples in different programming languages, have a look at: " +
    "https://docs.aws.amazon.com/code-library/latest/ug/location_code_examples.html",
);

const myScenario = new Scenario("Entity Resolution Basics Scenario", [
  greet,
  pressEnter,
  displayBuildCloudFormationStack,
  sdkBuildCloudFormationStack,
  pressEnter,
  displayCreateSchemaMapping,
  sdkCreateSchemaMapping,
  pressEnter,
  displayCreateMatchingWorkflow,
  sdkCreateMatchingWorkflow,
  pressEnter,
  displayMatchingJobOfWorkflow,
  sdkMatchingJobOfWorkflow,
  pressEnter,
  displayGetDetailsforJob,
  sdkGetDetailsforJob,
  pressEnter,
  displayGetSchemaMappingJson,
  sdkGetSchemaMappingJson,
  pressEnter,
  displayListSchemaMappings,
  sdkListSchemaMappings,
  pressEnter,
  displayTagTheJsonSchema,
  sdkTagTheJsonSchema,
  pressEnter,
  displayGetJobInfo,
  pressEnter,
  displayDeleteResources,
  pressEnter,
  sdkDeleteResources,
  pressEnter,
  goodbye,
]);

/** @type {{ stepHandlerOptions: StepHandlerOptions }} */
export const main = async (stepHandlerOptions) => {
  await myScenario.run(stepHandlerOptions);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      yes: {
        type: "boolean",
        short: "y",
      },
    },
  });
  main({ confirmAll: values.yes });
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CreateMatchingWorkflow](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/CreateMatchingWorkflow)
  + [CreateSchemaMapping](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/CreateSchemaMapping)
  + [DeleteMatchingWorkflow](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/DeleteMatchingWorkflow)
  + [DeleteSchemaMapping](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/DeleteSchemaMapping)
  + [GetMatchingJob](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/GetMatchingJob)
  + [GetSchemaMapping](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/GetSchemaMapping)
  + [ListMatchingWorkflows](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/ListMatchingWorkflows)
  + [ListSchemaMappings](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/ListSchemaMappings)
  + [StartMatchingJob](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/StartMatchingJob)
  + [TagResource](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/entityresolution-2018-05-10/TagResource)

# SDK for JavaScript (v2) を使用した EventBridge の例
<a name="javascript_2_eventbridge_code_examples"></a>

次のコード例は、EventBridge で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="eventbridge_PutEvents_javascript_2_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" });

var params = {
  Entries: [
    {
      Detail: '{ "key1": "value1", "key2": "value2" }',
      DetailType: "appRequestSubmitted",
      Resources: ["RESOURCE_ARN"],
      Source: "com.company.app",
    },
  ],
};

ebevents.putEvents(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Entries);
  }
});
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/eventbridge-2015-10-07/PutEvents)」を参照してください。

### `PutRule`
<a name="eventbridge_PutRule_javascript_2_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" });

var params = {
  Name: "DEMO_EVENT",
  RoleArn: "IAM_ROLE_ARN",
  ScheduleExpression: "rate(5 minutes)",
  State: "ENABLED",
};

ebevents.putRule(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.RuleArn);
  }
});
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutRule](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/eventbridge-2015-10-07/PutRule)」を参照してください。

### `PutTargets`
<a name="eventbridge_PutTargets_javascript_2_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create CloudWatchEvents service object
var ebevents = new AWS.EventBridge({ apiVersion: "2015-10-07" });

var params = {
  Rule: "DEMO_EVENT",
  Targets: [
    {
      Arn: "LAMBDA_FUNCTION_ARN",
      Id: "myEventBridgeTarget",
    },
  ],
};

ebevents.putTargets(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/eventbridge-2015-10-07/PutTargets)」を参照してください。

# SDK for JavaScript (v2) を使用した Amazon Glacier の例
<a name="javascript_2_glacier_code_examples"></a>

次のコード例は、Amazon Glacier で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateVault`
<a name="glacier_CreateVault_javascript_2_topic"></a>

次のコード例は、`CreateVault` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
// Load the SDK for JavaScript
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create a new service object
var glacier = new AWS.Glacier({ apiVersion: "2012-06-01" });
// Call Glacier to create the vault
glacier.createVault({ vaultName: "YOUR_VAULT_NAME" }, function (err) {
  if (!err) {
    console.log("Created vault!");
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/glacier-example-creating-a-vault.html)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateVault](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/glacier-2012-06-01/CreateVault)」を参照してください。

### `UploadArchive`
<a name="glacier_UploadArchive_javascript_2_topic"></a>

次のコード例は、`UploadArchive` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
// Load the SDK for JavaScript
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create a new service object and buffer
var glacier = new AWS.Glacier({ apiVersion: "2012-06-01" });
buffer = Buffer.alloc(2.5 * 1024 * 1024); // 2.5MB buffer

var params = { vaultName: "YOUR_VAULT_NAME", body: buffer };
// Call Glacier to upload the archive.
glacier.uploadArchive(params, function (err, data) {
  if (err) {
    console.log("Error uploading archive!", err);
  } else {
    console.log("Archive ID", data.archiveId);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/glacier-example-uploadrchive.html)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UploadArchive](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/glacier-2012-06-01/UploadArchive)」を参照してください。

### `UploadMultipartPart`
<a name="glacier_UploadMultipartPart_javascript_2_topic"></a>

次のコード例は、`UploadMultipartPart` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/glacier#code-examples)での設定と実行の方法を確認してください。
Buffer オブジェクトの 1 メガバイトのチャンクのマルチパートアップロードを作成します。  

```
// Create a new service object and some supporting variables
var glacier = new AWS.Glacier({ apiVersion: "2012-06-01" }),
  vaultName = "YOUR_VAULT_NAME",
  buffer = new Buffer(2.5 * 1024 * 1024), // 2.5MB buffer
  partSize = 1024 * 1024, // 1MB chunks,
  numPartsLeft = Math.ceil(buffer.length / partSize),
  startTime = new Date(),
  params = { vaultName: vaultName, partSize: partSize.toString() };

// Compute the complete SHA-256 tree hash so we can pass it
// to completeMultipartUpload request at the end
var treeHash = glacier.computeChecksums(buffer).treeHash;

// Initiate the multipart upload
console.log("Initiating upload to", vaultName);
// Call Glacier to initiate the upload.
glacier.initiateMultipartUpload(params, function (mpErr, multipart) {
  if (mpErr) {
    console.log("Error!", mpErr.stack);
    return;
  }
  console.log("Got upload ID", multipart.uploadId);

  // Grab each partSize chunk and upload it as a part
  for (var i = 0; i < buffer.length; i += partSize) {
    var end = Math.min(i + partSize, buffer.length),
      partParams = {
        vaultName: vaultName,
        uploadId: multipart.uploadId,
        range: "bytes " + i + "-" + (end - 1) + "/*",
        body: buffer.slice(i, end),
      };

    // Send a single part
    console.log("Uploading part", i, "=", partParams.range);
    glacier.uploadMultipartPart(partParams, function (multiErr, mData) {
      if (multiErr) return;
      console.log("Completed part", this.request.params.range);
      if (--numPartsLeft > 0) return; // complete only when all parts uploaded

      var doneParams = {
        vaultName: vaultName,
        uploadId: multipart.uploadId,
        archiveSize: buffer.length.toString(),
        checksum: treeHash, // the computed tree hash
      };

      console.log("Completing upload...");
      glacier.completeMultipartUpload(doneParams, function (err, data) {
        if (err) {
          console.log("An error occurred while uploading the archive");
          console.log(err);
        } else {
          var delta = (new Date() - startTime) / 1000;
          console.log("Completed upload in", delta, "seconds");
          console.log("Archive ID:", data.archiveId);
          console.log("Checksum:  ", data.checksum);
        }
      });
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/glacier-example-multipart-upload.html)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[UploadMultipartPart](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/glacier-2012-06-01/UploadMultipartPart)」を参照してください。

# SDK for JavaScript (v2) を使用した IAM の例
<a name="javascript_2_iam_code_examples"></a>

次のコード例は、IAM で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_javascript_2_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var paramsRoleList = {
  RoleName: process.argv[2],
};

iam.listAttachedRolePolicies(paramsRoleList, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var myRolePolicies = data.AttachedPolicies;
    myRolePolicies.forEach(function (val, index, array) {
      if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") {
        console.log(
          "AmazonDynamoDBFullAccess is already attached to this role."
        );
        process.exit();
      }
    });
    var params = {
      PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",
      RoleName: process.argv[2],
    };
    iam.attachRolePolicy(params, function (err, data) {
      if (err) {
        console.log("Unable to attach policy to role", err);
      } else {
        console.log("Role attached successfully");
      }
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-attaching-role-policy)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AttachRolePolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/AttachRolePolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_javascript_2_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.createAccessKey({ UserName: "IAM_USER_NAME" }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.AccessKey);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-creating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateAccessKey](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreateAccessKey)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_javascript_2_topic"></a>

次のコード例は、`CreateAccountAlias` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.createAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-creating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateAccountAlias](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreateAccountAlias)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_javascript_2_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var myManagedPolicy = {
  Version: "2012-10-17",
  Statement: [
    {
      Effect: "Allow",
      Action: "logs:CreateLogGroup",
      Resource: "RESOURCE_ARN",
    },
    {
      Effect: "Allow",
      Action: [
        "dynamodb:DeleteItem",
        "dynamodb:GetItem",
        "dynamodb:PutItem",
        "dynamodb:Scan",
        "dynamodb:UpdateItem",
      ],
      Resource: "RESOURCE_ARN",
    },
  ],
};

var params = {
  PolicyDocument: JSON.stringify(myManagedPolicy),
  PolicyName: "myDynamoDBPolicy",
};

iam.createPolicy(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-creating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_javascript_2_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
};

iam.getUser(params, function (err, data) {
  if (err && err.code === "NoSuchEntity") {
    iam.createUser(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data);
      }
    });
  } else {
    console.log(
      "User " + process.argv[2] + " already exists",
      data.User.UserId
    );
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-creating-users)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_javascript_2_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  AccessKeyId: "ACCESS_KEY_ID",
  UserName: "USER_NAME",
};

iam.deleteAccessKey(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteAccessKey](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteAccessKey)」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_javascript_2_topic"></a>

次のコード例は、`DeleteAccountAlias` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.deleteAccountAlias({ AccountAlias: process.argv[2] }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteAccountAlias](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteAccountAlias)」を参照してください。

### `DeleteServerCertificate`
<a name="iam_DeleteServerCertificate_javascript_2_topic"></a>

次のコード例は、`DeleteServerCertificate` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.deleteServerCertificate(
  { ServerCertificateName: "CERTIFICATE_NAME" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteServerCertificate](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteServerCertificate)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_javascript_2_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
};

iam.getUser(params, function (err, data) {
  if (err && err.code === "NoSuchEntity") {
    console.log("User " + process.argv[2] + " does not exist.");
  } else {
    iam.deleteUser(params, function (err, data) {
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data);
      }
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-deleting-users)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DeleteUser)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_javascript_2_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var paramsRoleList = {
  RoleName: process.argv[2],
};

iam.listAttachedRolePolicies(paramsRoleList, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var myRolePolicies = data.AttachedPolicies;
    myRolePolicies.forEach(function (val, index, array) {
      if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") {
        var params = {
          PolicyArn: "arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess",
          RoleName: process.argv[2],
        };
        iam.detachRolePolicy(params, function (err, data) {
          if (err) {
            console.log("Unable to detach policy from role", err);
          } else {
            console.log("Policy detached from role successfully");
            process.exit();
          }
        });
      }
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-detaching-role-policy)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DetachRolePolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/DetachRolePolicy)」を参照してください。

### `GetAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_javascript_2_topic"></a>

次のコード例は、`GetAccessKeyLastUsed` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.getAccessKeyLastUsed(
  { AccessKeyId: "ACCESS_KEY_ID" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data.AccessKeyLastUsed);
    }
  }
);
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-last-used)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetAccessKeyLastUsed](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/GetAccessKeyLastUsed)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_javascript_2_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  PolicyArn: "arn:aws:iam::aws:policy/AWSLambdaExecute",
};

iam.getPolicy(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.Policy.Description);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-policies.html#iam-examples-policies-getting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetPolicy](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/GetPolicy)」を参照してください。

### `GetServerCertificate`
<a name="iam_GetServerCertificate_javascript_2_topic"></a>

次のコード例は、`GetServerCertificate` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.getServerCertificate(
  { ServerCertificateName: "CERTIFICATE_NAME" },
  function (err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("Success", data);
    }
  }
);
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-getting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetServerCertificate](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/GetServerCertificate)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_javascript_2_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  MaxItems: 5,
  UserName: "IAM_USER_NAME",
};

iam.listAccessKeys(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iiam-examples-managing-access-keys-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListAccessKeys](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListAccessKeys)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_javascript_2_topic"></a>

次のコード例は、`ListAccountAliases` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.listAccountAliases({ MaxItems: 10 }, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListAccountAliases](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListAccountAliases)」を参照してください。

### `ListServerCertificates`
<a name="iam_ListServerCertificates_javascript_2_topic"></a>

次のコード例は、`ListServerCertificates` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

iam.listServerCertificates({}, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListServerCertificates](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListServerCertificates)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_javascript_2_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  MaxItems: 10,
};

iam.listUsers(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    var users = data.Users || [];
    users.forEach(function (user) {
      console.log("User " + user.UserName + " created", user.CreateDate);
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-listing-users)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/ListUsers)」を参照してください。

### `UpdateAccessKey`
<a name="iam_UpdateAccessKey_javascript_2_topic"></a>

次のコード例は、`UpdateAccessKey` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  AccessKeyId: "ACCESS_KEY_ID",
  Status: "Active",
  UserName: "USER_NAME",
};

iam.updateAccessKey(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-updating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の[UpdateAccessKey](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/UpdateAccessKey)」を参照してください。

### `UpdateServerCertificate`
<a name="iam_UpdateServerCertificate_javascript_2_topic"></a>

次のコード例は、`UpdateServerCertificate` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  ServerCertificateName: "CERTIFICATE_NAME",
  NewServerCertificateName: "NEW_CERTIFICATE_NAME",
};

iam.updateServerCertificate(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-updating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateServerCertificate](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/UpdateServerCertificate)」を参照してください。

### `UpdateUser`
<a name="iam_UpdateUser_javascript_2_topic"></a>

次のコード例は、`UpdateUser` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the IAM service object
var iam = new AWS.IAM({ apiVersion: "2010-05-08" });

var params = {
  UserName: process.argv[2],
  NewUserName: process.argv[3],
};

iam.updateUser(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-updating-users)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateUser](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/iam-2010-05-08/UpdateUser)」を参照してください。

# SDK for JavaScript (v2) を使用した Lambda 例
<a name="javascript_2_lambda_code_examples"></a>

次のコード例は、Lambda で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### ブラウザからの Lambda 関数の呼び出し
<a name="cross_LambdaForBrowser_javascript_2_topic"></a>

次のコード例は、ブラウザから AWS Lambda 関数を呼び出す方法を示しています。

**SDK for JavaScript (v2)**  
 AWS Lambda 関数を使用して Amazon DynamoDB テーブルをユーザー選択で更新するブラウザベースのアプリケーションを作成できます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/lambda/lambda-for-browser) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda

# SDK for JavaScript (v2) を使用した Amazon Pinpoint の例
<a name="javascript_2_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendMessages`
<a name="pinpoint_SendMessages_javascript_2_topic"></a>

次のコード例は、`SendMessages` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
E メールメッセージを送信します。  

```
"use strict";

const AWS = require("aws-sdk");

// The AWS Region that you want to use to send the email. For a list of
// AWS Regions where the Amazon Pinpoint API is available, see
// https://docs.aws.amazon.com/pinpoint/latest/apireference/
const aws_region = "us-west-2";

// The "From" address. This address has to be verified in Amazon Pinpoint
// in the region that you use to send email.
const senderAddress = "sender@example.com";

// The address on the "To" line. If your Amazon Pinpoint account is in
// the sandbox, this address also has to be verified.
var toAddress = "recipient@example.com";

// The Amazon Pinpoint project/application ID to use when you send this message.
// Make sure that the SMS channel is enabled for the project or application
// that you choose.
const appId = "ce796be37f32f178af652b26eexample";

// The subject line of the email.
var subject = "Amazon Pinpoint (AWS SDK for JavaScript in Node.js)";

// The email body for recipients with non-HTML email clients.
var body_text = `Amazon Pinpoint Test (SDK for JavaScript in Node.js)
----------------------------------------------------
This email was sent with Amazon Pinpoint using the AWS SDK for JavaScript in Node.js.
For more information, see https:\/\/aws.amazon.com/sdk-for-node-js/`;

// The body of the email for recipients whose email clients support HTML content.
var body_html = `<html>
<head></head>
<body>
  <h1>Amazon Pinpoint Test (SDK for JavaScript in Node.js)</h1>
  <p>This email was sent with
    <a href='https://aws.amazon.com/pinpoint/'>the Amazon Pinpoint API</a> using the
    <a href='https://aws.amazon.com/sdk-for-node-js/'>
      AWS SDK for JavaScript in Node.js</a>.</p>
</body>
</html>`;

// The character encoding the you want to use for the subject line and
// message body of the email.
var charset = "UTF-8";

// Specify that you're using a shared credentials file.
var credentials = new AWS.SharedIniFileCredentials({ profile: "default" });
AWS.config.credentials = credentials;

// Specify the region.
AWS.config.update({ region: aws_region });

//Create a new Pinpoint object.
var pinpoint = new AWS.Pinpoint();

// Specify the parameters to pass to the API.
var params = {
  ApplicationId: appId,
  MessageRequest: {
    Addresses: {
      [toAddress]: {
        ChannelType: "EMAIL",
      },
    },
    MessageConfiguration: {
      EmailMessage: {
        FromAddress: senderAddress,
        SimpleEmail: {
          Subject: {
            Charset: charset,
            Data: subject,
          },
          HtmlPart: {
            Charset: charset,
            Data: body_html,
          },
          TextPart: {
            Charset: charset,
            Data: body_text,
          },
        },
      },
    },
  },
};

//Try to send the email.
pinpoint.sendMessages(params, function (err, data) {
  // If something goes wrong, print an error message.
  if (err) {
    console.log(err.message);
  } else {
    console.log(
      "Email sent! Message ID: ",
      data["MessageResponse"]["Result"][toAddress]["MessageId"]
    );
  }
});
```
SMS メッセージを送信します。  

```
"use strict";

var AWS = require("aws-sdk");

// The AWS Region that you want to use to send the message. For a list of
// AWS Regions where the Amazon Pinpoint API is available, see
// https://docs.aws.amazon.com/pinpoint/latest/apireference/.
var aws_region = "us-east-1";

// The phone number or short code to send the message from. The phone number
// or short code that you specify has to be associated with your Amazon Pinpoint
// account. For best results, specify long codes in E.164 format.
var originationNumber = "+12065550199";

// The recipient's phone number.  For best results, you should specify the
// phone number in E.164 format.
var destinationNumber = "+14255550142";

// The content of the SMS message.
var message =
  "This message was sent through Amazon Pinpoint " +
  "using the AWS SDK for JavaScript in Node.js. Reply STOP to " +
  "opt out.";

// The Amazon Pinpoint project/application ID to use when you send this message.
// Make sure that the SMS channel is enabled for the project or application
// that you choose.
var applicationId = "ce796be37f32f178af652b26eexample";

// The type of SMS message that you want to send. If you plan to send
// time-sensitive content, specify TRANSACTIONAL. If you plan to send
// marketing-related content, specify PROMOTIONAL.
var messageType = "TRANSACTIONAL";

// The registered keyword associated with the originating short code.
var registeredKeyword = "myKeyword";

// The sender ID to use when sending the message. Support for sender ID
// varies by country or region. For more information, see
// https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html
var senderId = "MySenderID";

// Specify that you're using a shared credentials file, and optionally specify
// the profile that you want to use.
var credentials = new AWS.SharedIniFileCredentials({ profile: "default" });
AWS.config.credentials = credentials;

// Specify the region.
AWS.config.update({ region: aws_region });

//Create a new Pinpoint object.
var pinpoint = new AWS.Pinpoint();

// Specify the parameters to pass to the API.
var params = {
  ApplicationId: applicationId,
  MessageRequest: {
    Addresses: {
      [destinationNumber]: {
        ChannelType: "SMS",
      },
    },
    MessageConfiguration: {
      SMSMessage: {
        Body: message,
        Keyword: registeredKeyword,
        MessageType: messageType,
        OriginationNumber: originationNumber,
        SenderId: senderId,
      },
    },
  },
};

//Try to send the message.
pinpoint.sendMessages(params, function (err, data) {
  // If something goes wrong, print an error message.
  if (err) {
    console.log(err.message);
    // Otherwise, show the unique ID for the message.
  } else {
    console.log(
      "Message sent! " +
        data["MessageResponse"]["Result"][destinationNumber]["StatusMessage"]
    );
  }
});
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SendMessage](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/pinpoint-2016-12-01/SendMessages)」を参照してください。

# SDK for JavaScript (v2) を使用した Amazon Pinpoint SMS および音声 API の例
<a name="javascript_2_pinpoint-sms-voice_code_examples"></a>

次のコード例は、Amazon Pinpoint SMS および音声 API で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendVoiceMessage`
<a name="pinpoint-sms-voice_SendVoiceMessage_javascript_2_topic"></a>

次のコード例は、`SendVoiceMessage` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/pinpoint-sms-voice#code-examples)での設定と実行の方法を確認してください。

```
"use strict";

var AWS = require("aws-sdk");

// The AWS Region that you want to use to send the voice message. For a list of
// AWS Regions where the Amazon Pinpoint SMS and Voice API is available, see
// https://docs.aws.amazon.com/pinpoint-sms-voice/latest/APIReference/
var aws_region = "us-east-1";

// The phone number that the message is sent from. The phone number that you
// specify has to be associated with your Amazon Pinpoint account. For best results, you
// should specify the phone number in E.164 format.
var originationNumber = "+12065550110";

// The recipient's phone number. For best results, you should specify the phone
// number in E.164 format.
var destinationNumber = "+12065550142";

// The language to use when sending the message. For a list of supported
// languages, see https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html
var languageCode = "en-US";

// The Amazon Polly voice that you want to use to send the message. For a list
// of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
var voiceId = "Matthew";

// The content of the message. This example uses SSML to customize and control
// certain aspects of the message, such as the volume or the speech rate.
// The message can't contain any line breaks.
var ssmlMessage =
  "<speak>" +
  "This is a test message sent from <emphasis>Amazon Pinpoint</emphasis> " +
  "using the <break strength='weak'/>AWS SDK for JavaScript in Node.js. " +
  "<amazon:effect phonation='soft'>Thank you for listening." +
  "</amazon:effect>" +
  "</speak>";

// The phone number that you want to appear on the recipient's device. The phone
// number that you specify has to be associated with your Amazon Pinpoint account.
var callerId = "+12065550199";

// The configuration set that you want to use to send the message.
var configurationSet = "ConfigSet";

// Specify that you're using a shared credentials file, and optionally specify
// the profile that you want to use.
var credentials = new AWS.SharedIniFileCredentials({ profile: "default" });
AWS.config.credentials = credentials;

// Specify the region.
AWS.config.update({ region: aws_region });

//Create a new Pinpoint object.
var pinpointsmsvoice = new AWS.PinpointSMSVoice();

var params = {
  CallerId: callerId,
  ConfigurationSetName: configurationSet,
  Content: {
    SSMLMessage: {
      LanguageCode: languageCode,
      Text: ssmlMessage,
      VoiceId: voiceId,
    },
  },
  DestinationPhoneNumber: destinationNumber,
  OriginationPhoneNumber: originationNumber,
};

//Try to send the message.
pinpointsmsvoice.sendVoiceMessage(params, function (err, data) {
  // If something goes wrong, print an error message.
  if (err) {
    console.log(err.message);
    // Otherwise, show the unique ID for the message.
  } else {
    console.log("Message sent! Message ID: " + data["MessageId"]);
  }
});
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[SendVoiceMessage](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/pinpoint-sms-voice-2018-09-05/SendVoiceMessage)」を参照してください。

# SDK for JavaScript (v2) を使用した Amazon SNS の例
<a name="javascript_2_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_javascript_2_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sns#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set region
AWS.config.update({ region: "REGION" });

// Create promise and SNS service object
var getTopicAttribsPromise = new AWS.SNS({ apiVersion: "2010-03-31" })
  .getTopicAttributes({ TopicArn: "TOPIC_ARN" })
  .promise();

// Handle promise's fulfilled/rejected states
getTopicAttribsPromise
  .then(function (data) {
    console.log(data);
  })
  .catch(function (err) {
    console.error(err, err.stack);
  });
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topicsgetttopicattributes)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetTopicAttributes](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sns-2010-03-31/GetTopicAttributes)」を参照してください。

# SDK for JavaScript (v2) を使用した Amazon SQS の例
<a name="javascript_2_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ChangeMessageVisibility`
<a name="sqs_ChangeMessageVisibility_javascript_2_topic"></a>

次のコード例は、`ChangeMessageVisibility` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS メッセージを受信し、可視性タイムアウトを変更します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region to us-west-2
AWS.config.update({ region: "us-west-2" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var queueURL = "https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME";

var params = {
  AttributeNames: ["SentTimestamp"],
  MaxNumberOfMessages: 1,
  MessageAttributeNames: ["All"],
  QueueUrl: queueURL,
};

sqs.receiveMessage(params, function (err, data) {
  if (err) {
    console.log("Receive Error", err);
  } else {
    // Make sure we have a message
    if (data.Messages != null) {
      var visibilityParams = {
        QueueUrl: queueURL,
        ReceiptHandle: data.Messages[0].ReceiptHandle,
        VisibilityTimeout: 20, // 20 second timeout
      };
      sqs.changeMessageVisibility(visibilityParams, function (err, data) {
        if (err) {
          console.log("Delete Error", err);
        } else {
          console.log("Timeout Changed", data);
        }
      });
    } else {
      console.log("No messages to change");
    }
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-managing-visibility-timeout.html#sqs-examples-managing-visibility-timeout-setting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ChangeMessageVisibility](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/ChangeMessageVisibility)」を参照してください。

### `CreateQueue`
<a name="sqs_CreateQueue_javascript_2_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS 標準キューを作成します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueName: "SQS_QUEUE_NAME",
  Attributes: {
    DelaySeconds: "60",
    MessageRetentionPeriod: "86400",
  },
};

sqs.createQueue(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrl);
  }
});
```
メッセージが到着するまで待機する Amazon SQS キューを作成します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueName: "SQS_QUEUE_NAME",
  Attributes: {
    ReceiveMessageWaitTimeSeconds: "20",
  },
};

sqs.createQueue(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrl);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-create-queue)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateQueue](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/CreateQueue)」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_javascript_2_topic"></a>

次のコード例は、`DeleteMessage` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS メッセージを受信および削除します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var queueURL = "SQS_QUEUE_URL";

var params = {
  AttributeNames: ["SentTimestamp"],
  MaxNumberOfMessages: 10,
  MessageAttributeNames: ["All"],
  QueueUrl: queueURL,
  VisibilityTimeout: 20,
  WaitTimeSeconds: 0,
};

sqs.receiveMessage(params, function (err, data) {
  if (err) {
    console.log("Receive Error", err);
  } else if (data.Messages) {
    var deleteParams = {
      QueueUrl: queueURL,
      ReceiptHandle: data.Messages[0].ReceiptHandle,
    };
    sqs.deleteMessage(deleteParams, function (err, data) {
      if (err) {
        console.log("Delete Error", err);
      } else {
        console.log("Message Deleted", data);
      }
    });
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-send-receive-messages.html#sqs-examples-send-receive-messages-receiving)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteMessage](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/DeleteMessage)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_javascript_2_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューを削除します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueUrl: "SQS_QUEUE_URL",
};

sqs.deleteQueue(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-delete-queue)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteQueue](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/DeleteQueue)」を参照してください。

### `GetQueueUrl`
<a name="sqs_GetQueueUrl_javascript_2_topic"></a>

次のコード例は、`GetQueueUrl` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューの URL を取得します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  QueueName: "SQS_QUEUE_NAME",
};

sqs.getQueueUrl(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrl);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-get-queue-url)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetQueueUrl](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/GetQueueUrl)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_javascript_2_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューを一覧表示します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {};

sqs.listQueues(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.QueueUrls);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-listing-queues)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListQueues](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/ListQueues)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_javascript_2_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
ロングポーリングサポートを使用して Amazon SQS キューからメッセージを受信します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create the SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var queueURL = "SQS_QUEUE_URL";

var params = {
  AttributeNames: ["SentTimestamp"],
  MaxNumberOfMessages: 1,
  MessageAttributeNames: ["All"],
  QueueUrl: queueURL,
  WaitTimeSeconds: 20,
};

sqs.receiveMessage(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-enable-long-polling.html#sqs-examples-enable-long-polling-on-receive-message)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ReceiveMessage](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/ReceiveMessage)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_javascript_2_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューにメッセージを送信します。  

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create an SQS service object
var sqs = new AWS.SQS({ apiVersion: "2012-11-05" });

var params = {
  // Remove DelaySeconds parameter and value for FIFO queues
  DelaySeconds: 10,
  MessageAttributes: {
    Title: {
      DataType: "String",
      StringValue: "The Whistler",
    },
    Author: {
      DataType: "String",
      StringValue: "John Grisham",
    },
    WeeksOn: {
      DataType: "Number",
      StringValue: "6",
    },
  },
  MessageBody:
    "Information about current NY Times fiction bestseller for week of 12/11/2016.",
  // MessageDeduplicationId: "TheWhistler",  // Required for FIFO queues
  // MessageGroupId: "Group1",  // Required for FIFO queues
  QueueUrl: "SQS_QUEUE_URL",
};

sqs.sendMessage(params, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else {
    console.log("Success", data.MessageId);
  }
});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sqs-examples-send-receive-messages.html#sqs-examples-send-receive-messages-sending)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SendMessage](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sqs-2012-11-05/SendMessage)」を参照してください。

# AWS STS SDK for JavaScript (v2) を使用した例
<a name="javascript_2_sts_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v2) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_javascript_2_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for JavaScript (v2)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascript/example_code/sts#code-examples)での設定と実行の方法を確認してください。

```
// Load the AWS SDK for Node.js
const AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

var roleToAssume = {
  RoleArn: "arn:aws:iam::123456789012:role/RoleName",
  RoleSessionName: "session1",
  DurationSeconds: 900,
};
var roleCreds;

// Create the STS service object
var sts = new AWS.STS({ apiVersion: "2011-06-15" });

//Assume Role
sts.assumeRole(roleToAssume, function (err, data) {
  if (err) console.log(err, err.stack);
  else {
    roleCreds = {
      accessKeyId: data.Credentials.AccessKeyId,
      secretAccessKey: data.Credentials.SecretAccessKey,
      sessionToken: data.Credentials.SessionToken,
    };
    stsGetCallerIdentity(roleCreds);
  }
});

//Get Arn of current identity
function stsGetCallerIdentity(creds) {
  var stsParams = { credentials: creds };
  // Create STS service object
  var sts = new AWS.STS(stsParams);

  sts.getCallerIdentity({}, function (err, data) {
    if (err) {
      console.log(err, err.stack);
    } else {
      console.log(data.Arn);
    }
  });
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AssumeRole](https://docs.aws.amazon.com/goto/AWSJavaScriptSDK/sts-2011-06-15/AssumeRole)」を参照してください。

# SDK for JavaScript (v3) のコード例
<a name="javascript_3_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v3) を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for JavaScript (v3) デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html) ** – での JavaScript の使用に関する詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23javascript)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [API ゲートウェイ](javascript_3_api-gateway_code_examples.md)
+ [Aurora](javascript_3_aurora_code_examples.md)
+ [Auto Scaling](javascript_3_auto-scaling_code_examples.md)
+ [Amazon Bedrock](javascript_3_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](javascript_3_bedrock-runtime_code_examples.md)
+ [Amazon Bedrock エージェント](javascript_3_bedrock-agent_code_examples.md)
+ [Amazon Bedrock エージェントランタイム](javascript_3_bedrock-agent-runtime_code_examples.md)
+ [CloudWatch](javascript_3_cloudwatch_code_examples.md)
+ [CloudWatch Events](javascript_3_cloudwatch-events_code_examples.md)
+ [CloudWatch Logs](javascript_3_cloudwatch-logs_code_examples.md)
+ [CodeBuild](javascript_3_codebuild_code_examples.md)
+ [Amazon Cognito ID](javascript_3_cognito-identity_code_examples.md)
+ [Amazon Cognito ID プロバイダー](javascript_3_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](javascript_3_comprehend_code_examples.md)
+ [Amazon DocumentDB](javascript_3_docdb_code_examples.md)
+ [DynamoDB](javascript_3_dynamodb_code_examples.md)
+ [Amazon EC2](javascript_3_ec2_code_examples.md)
+ [Elastic Load Balancing - バージョン 2](javascript_3_elastic-load-balancing-v2_code_examples.md)
+ [AWS Entity Resolution](javascript_3_entityresolution_code_examples.md)
+ [EventBridge](javascript_3_eventbridge_code_examples.md)
+ [Amazon Glacier](javascript_3_glacier_code_examples.md)
+ [AWS Glue](javascript_3_glue_code_examples.md)
+ [HealthImaging](javascript_3_medical-imaging_code_examples.md)
+ [IAM](javascript_3_iam_code_examples.md)
+ [AWS IoT SiteWise](javascript_3_iotsitewise_code_examples.md)
+ [Kinesis](javascript_3_kinesis_code_examples.md)
+ [Lambda](javascript_3_lambda_code_examples.md)
+ [Amazon Lex](javascript_3_lex_code_examples.md)
+ [Amazon Location](javascript_3_location_code_examples.md)
+ [Amazon MSK](javascript_3_kafka_code_examples.md)
+ [Amazon Personalize](javascript_3_personalize_code_examples.md)
+ [Amazon Personalize Events](javascript_3_personalize-events_code_examples.md)
+ [Amazon Personalize Runtime](javascript_3_personalize-runtime_code_examples.md)
+ [Amazon Pinpoint](javascript_3_pinpoint_code_examples.md)
+ [Amazon Polly](javascript_3_polly_code_examples.md)
+ [Amazon RDS](javascript_3_rds_code_examples.md)
+ [Amazon RDS データサービス](javascript_3_rds-data_code_examples.md)
+ [Amazon Redshift](javascript_3_redshift_code_examples.md)
+ [Amazon Rekognition](javascript_3_rekognition_code_examples.md)
+ [Amazon S3](javascript_3_s3_code_examples.md)
+ [SageMaker AI](javascript_3_sagemaker_code_examples.md)
+ [Secrets Manager](javascript_3_secrets-manager_code_examples.md)
+ [Amazon SES](javascript_3_ses_code_examples.md)
+ [Amazon SNS](javascript_3_sns_code_examples.md)
+ [Amazon SQS](javascript_3_sqs_code_examples.md)
+ [ステップ関数](javascript_3_sfn_code_examples.md)
+ [AWS STS](javascript_3_sts_code_examples.md)
+ [サポート](javascript_3_support_code_examples.md)
+ [Systems Manager](javascript_3_ssm_code_examples.md)
+ [Amazon Textract](javascript_3_textract_code_examples.md)
+ [Amazon Transcribe](javascript_3_transcribe_code_examples.md)
+ [Amazon Translate](javascript_3_translate_code_examples.md)

# SDK for JavaScript (v3) を使用した API Gateway の例
<a name="javascript_3_api-gateway_code_examples"></a>

次のコード例は、API Gateway で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_javascript_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for JavaScript (v3)**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo-asset-manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_javascript_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 Lambda JavaScript ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-api-gateway) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

# SDK for JavaScript (v3) を使用した Aurora の例
<a name="javascript_3_aurora_code_examples"></a>

次のコード例は、Aurora で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_javascript_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScript (v3) を使用して Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して Express Node.js バックエンドと対話します。  
+ React.js ウェブアプリケーションを と統合します AWS のサービス。
+ Aurora テーブルの項目を一覧表示、追加、更新します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/aurora-serverless-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for JavaScript (v3) を使用した自動スケーリングの例
<a name="javascript_3_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AttachLoadBalancerTargetGroups`
<a name="auto-scaling_AttachLoadBalancerTargetGroups_javascript_3_topic"></a>

次のコード例は、`AttachLoadBalancerTargetGroups` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const client = new AutoScalingClient({});
    await client.send(
      new AttachLoadBalancerTargetGroupsCommand({
        AutoScalingGroupName: NAMES.autoScalingGroupName,
        TargetGroupARNs: [state.targetGroupArn],
      }),
    );
```
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/AttachLoadBalancerTargetGroupsCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_javascript_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
#!/usr/bin/env node
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import {
  Scenario,
  parseScenarioArgs,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

/**
 * The workflow steps are split into three stages:
 *   - deploy
 *   - demo
 *   - destroy
 *
 * Each of these stages has a corresponding file prefixed with steps-*.
 */
import { deploySteps } from "./steps-deploy.js";
import { demoSteps } from "./steps-demo.js";
import { destroySteps } from "./steps-destroy.js";

/**
 * The context is passed to every scenario. Scenario steps
 * will modify the context.
 */
const context = {};

/**
 * Three Scenarios are created for the workflow. A Scenario is an orchestration class
 * that simplifies running a series of steps.
 */
export const scenarios = {
  // Deploys all resources necessary for the workflow.
  deploy: new Scenario("Resilient Workflow - Deploy", deploySteps, context),
  // Demonstrates how a fragile web service can be made more resilient.
  demo: new Scenario("Resilient Workflow - Demo", demoSteps, context),
  // Destroys the resources created for the workflow.
  destroy: new Scenario("Resilient Workflow - Destroy", destroySteps, context),
};

// Call function if run directly
import { fileURLToPath } from "node:url";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  parseScenarioArgs(scenarios, {
    name: "Resilient Workflow",
    synopsis:
      "node index.js --scenario <deploy | demo | destroy> [-h|--help] [-y|--yes] [-v|--verbose]",
    description: "Deploy and interact with scalable EC2 instances.",
  });
}
```
すべてのリソースをデプロイするための手順を作成します。  

```
import { join } from "node:path";
import { readFileSync, writeFileSync } from "node:fs";
import axios from "axios";

import {
  BatchWriteItemCommand,
  CreateTableCommand,
  DynamoDBClient,
  waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  CreateKeyPairCommand,
  CreateLaunchTemplateCommand,
  DescribeAvailabilityZonesCommand,
  DescribeVpcsCommand,
  DescribeSubnetsCommand,
  DescribeSecurityGroupsCommand,
  AuthorizeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  AttachRolePolicyCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";
import {
  CreateAutoScalingGroupCommand,
  AutoScalingClient,
  AttachLoadBalancerTargetGroupsCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  CreateListenerCommand,
  CreateLoadBalancerCommand,
  CreateTargetGroupCommand,
  ElasticLoadBalancingV2Client,
  waitUntilLoadBalancerAvailable,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { saveState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH, ROOT } from "./constants.js";
import { initParamsSteps } from "./steps-reset-params.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const deploySteps = [
  new ScenarioOutput("introduction", MESSAGES.introduction, { header: true }),
  new ScenarioInput("confirmDeployment", MESSAGES.confirmDeployment, {
    type: "confirm",
  }),
  new ScenarioAction(
    "handleConfirmDeployment",
    (c) => c.confirmDeployment === false && process.exit(),
  ),
  new ScenarioOutput(
    "creatingTable",
    MESSAGES.creatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("createTable", async () => {
    const client = new DynamoDBClient({});
    await client.send(
      new CreateTableCommand({
        TableName: NAMES.tableName,
        ProvisionedThroughput: {
          ReadCapacityUnits: 5,
          WriteCapacityUnits: 5,
        },
        AttributeDefinitions: [
          {
            AttributeName: "MediaType",
            AttributeType: "S",
          },
          {
            AttributeName: "ItemId",
            AttributeType: "N",
          },
        ],
        KeySchema: [
          {
            AttributeName: "MediaType",
            KeyType: "HASH",
          },
          {
            AttributeName: "ItemId",
            KeyType: "RANGE",
          },
        ],
      }),
    );
    await waitUntilTableExists({ client }, { TableName: NAMES.tableName });
  }),
  new ScenarioOutput(
    "createdTable",
    MESSAGES.createdTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "populatingTable",
    MESSAGES.populatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("populateTable", () => {
    const client = new DynamoDBClient({});
    /**
     * @type {{ default: import("@aws-sdk/client-dynamodb").PutRequest['Item'][] }}
     */
    const recommendations = JSON.parse(
      readFileSync(join(RESOURCES_PATH, "recommendations.json")),
    );

    return client.send(
      new BatchWriteItemCommand({
        RequestItems: {
          [NAMES.tableName]: recommendations.map((item) => ({
            PutRequest: { Item: item },
          })),
        },
      }),
    );
  }),
  new ScenarioOutput(
    "populatedTable",
    MESSAGES.populatedTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "creatingKeyPair",
    MESSAGES.creatingKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioAction("createKeyPair", async () => {
    const client = new EC2Client({});
    const { KeyMaterial } = await client.send(
      new CreateKeyPairCommand({
        KeyName: NAMES.keyPairName,
      }),
    );

    writeFileSync(`${NAMES.keyPairName}.pem`, KeyMaterial, { mode: 0o600 });
  }),
  new ScenarioOutput(
    "createdKeyPair",
    MESSAGES.createdKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioOutput(
    "creatingInstancePolicy",
    MESSAGES.creatingInstancePolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    ),
  ),
  new ScenarioAction("createInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const {
      Policy: { Arn },
    } = await client.send(
      new CreatePolicyCommand({
        PolicyName: NAMES.instancePolicyName,
        PolicyDocument: readFileSync(
          join(RESOURCES_PATH, "instance_policy.json"),
        ),
      }),
    );
    state.instancePolicyArn = Arn;
  }),
  new ScenarioOutput("createdInstancePolicy", (state) =>
    MESSAGES.createdInstancePolicy
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_POLICY_ARN}", state.instancePolicyArn),
  ),
  new ScenarioOutput(
    "creatingInstanceRole",
    MESSAGES.creatingInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioAction("createInstanceRole", () => {
    const client = new IAMClient({});
    return client.send(
      new CreateRoleCommand({
        RoleName: NAMES.instanceRoleName,
        AssumeRolePolicyDocument: readFileSync(
          join(ROOT, "assume-role-policy.json"),
        ),
      }),
    );
  }),
  new ScenarioOutput(
    "createdInstanceRole",
    MESSAGES.createdInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioOutput(
    "attachingPolicyToRole",
    MESSAGES.attachingPolicyToRole
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName)
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName),
  ),
  new ScenarioAction("attachPolicyToRole", async (state) => {
    const client = new IAMClient({});
    await client.send(
      new AttachRolePolicyCommand({
        RoleName: NAMES.instanceRoleName,
        PolicyArn: state.instancePolicyArn,
      }),
    );
  }),
  new ScenarioOutput(
    "attachedPolicyToRole",
    MESSAGES.attachedPolicyToRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioOutput(
    "creatingInstanceProfile",
    MESSAGES.creatingInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    ),
  ),
  new ScenarioAction("createInstanceProfile", async (state) => {
    const client = new IAMClient({});
    const {
      InstanceProfile: { Arn },
    } = await client.send(
      new CreateInstanceProfileCommand({
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
    state.instanceProfileArn = Arn;

    await waitUntilInstanceProfileExists(
      { client },
      { InstanceProfileName: NAMES.instanceProfileName },
    );
  }),
  new ScenarioOutput("createdInstanceProfile", (state) =>
    MESSAGES.createdInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_PROFILE_ARN}", state.instanceProfileArn),
  ),
  new ScenarioOutput(
    "addingRoleToInstanceProfile",
    MESSAGES.addingRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioAction("addRoleToInstanceProfile", () => {
    const client = new IAMClient({});
    return client.send(
      new AddRoleToInstanceProfileCommand({
        RoleName: NAMES.instanceRoleName,
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
  }),
  new ScenarioOutput(
    "addedRoleToInstanceProfile",
    MESSAGES.addedRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  ...initParamsSteps,
  new ScenarioOutput("creatingLaunchTemplate", MESSAGES.creatingLaunchTemplate),
  new ScenarioAction("createLaunchTemplate", async () => {
    const ssmClient = new SSMClient({});
    const { Parameter } = await ssmClient.send(
      new GetParameterCommand({
        Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
      }),
    );
    const ec2Client = new EC2Client({});
    await ec2Client.send(
      new CreateLaunchTemplateCommand({
        LaunchTemplateName: NAMES.launchTemplateName,
        LaunchTemplateData: {
          InstanceType: "t3.micro",
          ImageId: Parameter.Value,
          IamInstanceProfile: { Name: NAMES.instanceProfileName },
          UserData: readFileSync(
            join(RESOURCES_PATH, "server_startup_script.sh"),
          ).toString("base64"),
          KeyName: NAMES.keyPairName,
        },
      }),
    );
  }),
  new ScenarioOutput(
    "createdLaunchTemplate",
    MESSAGES.createdLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    ),
  ),
  new ScenarioOutput(
    "creatingAutoScalingGroup",
    MESSAGES.creatingAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    ),
  ),
  new ScenarioAction("createAutoScalingGroup", async (state) => {
    const ec2Client = new EC2Client({});
    const { AvailabilityZones } = await ec2Client.send(
      new DescribeAvailabilityZonesCommand({}),
    );
    state.availabilityZoneNames = AvailabilityZones.map((az) => az.ZoneName);
    const autoScalingClient = new AutoScalingClient({});
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new CreateAutoScalingGroupCommand({
          AvailabilityZones: state.availabilityZoneNames,
          AutoScalingGroupName: NAMES.autoScalingGroupName,
          LaunchTemplate: {
            LaunchTemplateName: NAMES.launchTemplateName,
            Version: "$Default",
          },
          MinSize: 3,
          MaxSize: 3,
        }),
      ),
    );
  }),
  new ScenarioOutput(
    "createdAutoScalingGroup",
    /**
     * @param {{ availabilityZoneNames: string[] }} state
     */
    (state) =>
      MESSAGES.createdAutoScalingGroup
        .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName)
        .replace(
          "${AVAILABILITY_ZONE_NAMES}",
          state.availabilityZoneNames.join(", "),
        ),
  ),
  new ScenarioInput("confirmContinue", MESSAGES.confirmContinue, {
    type: "confirm",
  }),
  new ScenarioOutput("loadBalancer", MESSAGES.loadBalancer),
  new ScenarioOutput("gettingVpc", MESSAGES.gettingVpc),
  new ScenarioAction("getVpc", async (state) => {
    const client = new EC2Client({});
    const { Vpcs } = await client.send(
      new DescribeVpcsCommand({
        Filters: [{ Name: "is-default", Values: ["true"] }],
      }),
    );
    state.defaultVpc = Vpcs[0].VpcId;
  }),
  new ScenarioOutput("gotVpc", (state) =>
    MESSAGES.gotVpc.replace("${VPC_ID}", state.defaultVpc),
  ),
  new ScenarioOutput("gettingSubnets", MESSAGES.gettingSubnets),
  new ScenarioAction("getSubnets", async (state) => {
    const client = new EC2Client({});
    const { Subnets } = await client.send(
      new DescribeSubnetsCommand({
        Filters: [
          { Name: "vpc-id", Values: [state.defaultVpc] },
          { Name: "availability-zone", Values: state.availabilityZoneNames },
          { Name: "default-for-az", Values: ["true"] },
        ],
      }),
    );
    state.subnets = Subnets.map((subnet) => subnet.SubnetId);
  }),
  new ScenarioOutput(
    "gotSubnets",
    /**
     * @param {{ subnets: string[] }} state
     */
    (state) =>
      MESSAGES.gotSubnets.replace("${SUBNETS}", state.subnets.join(", ")),
  ),
  new ScenarioOutput(
    "creatingLoadBalancerTargetGroup",
    MESSAGES.creatingLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioAction("createLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { TargetGroups } = await client.send(
      new CreateTargetGroupCommand({
        Name: NAMES.loadBalancerTargetGroupName,
        Protocol: "HTTP",
        Port: 80,
        HealthCheckPath: "/healthcheck",
        HealthCheckIntervalSeconds: 10,
        HealthCheckTimeoutSeconds: 5,
        HealthyThresholdCount: 2,
        UnhealthyThresholdCount: 2,
        VpcId: state.defaultVpc,
      }),
    );
    const targetGroup = TargetGroups[0];
    state.targetGroupArn = targetGroup.TargetGroupArn;
    state.targetGroupProtocol = targetGroup.Protocol;
    state.targetGroupPort = targetGroup.Port;
  }),
  new ScenarioOutput(
    "createdLoadBalancerTargetGroup",
    MESSAGES.createdLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioOutput(
    "creatingLoadBalancer",
    MESSAGES.creatingLoadBalancer.replace("${LB_NAME}", NAMES.loadBalancerName),
  ),
  new ScenarioAction("createLoadBalancer", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { LoadBalancers } = await client.send(
      new CreateLoadBalancerCommand({
        Name: NAMES.loadBalancerName,
        Subnets: state.subnets,
      }),
    );
    state.loadBalancerDns = LoadBalancers[0].DNSName;
    state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn;
    await waitUntilLoadBalancerAvailable(
      { client },
      { Names: [NAMES.loadBalancerName] },
    );
  }),
  new ScenarioOutput("createdLoadBalancer", (state) =>
    MESSAGES.createdLoadBalancer
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioOutput(
    "creatingListener",
    MESSAGES.creatingLoadBalancerListener
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName),
  ),
  new ScenarioAction("createListener", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { Listeners } = await client.send(
      new CreateListenerCommand({
        LoadBalancerArn: state.loadBalancerArn,
        Protocol: state.targetGroupProtocol,
        Port: state.targetGroupPort,
        DefaultActions: [
          { Type: "forward", TargetGroupArn: state.targetGroupArn },
        ],
      }),
    );
    const listener = Listeners[0];
    state.loadBalancerListenerArn = listener.ListenerArn;
  }),
  new ScenarioOutput("createdListener", (state) =>
    MESSAGES.createdLoadBalancerListener.replace(
      "${LB_LISTENER_ARN}",
      state.loadBalancerListenerArn,
    ),
  ),
  new ScenarioOutput(
    "attachingLoadBalancerTargetGroup",
    MESSAGES.attachingLoadBalancerTargetGroup
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName)
      .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName),
  ),
  new ScenarioAction("attachLoadBalancerTargetGroup", async (state) => {
    const client = new AutoScalingClient({});
    await client.send(
      new AttachLoadBalancerTargetGroupsCommand({
        AutoScalingGroupName: NAMES.autoScalingGroupName,
        TargetGroupARNs: [state.targetGroupArn],
      }),
    );
  }),
  new ScenarioOutput(
    "attachedLoadBalancerTargetGroup",
    MESSAGES.attachedLoadBalancerTargetGroup,
  ),
  new ScenarioOutput("verifyingInboundPort", MESSAGES.verifyingInboundPort),
  new ScenarioAction(
    "verifyInboundPort",
    /**
     *
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup}} state
     */
    async (state) => {
      const client = new EC2Client({});
      const { SecurityGroups } = await client.send(
        new DescribeSecurityGroupsCommand({
          Filters: [{ Name: "group-name", Values: ["default"] }],
        }),
      );
      if (!SecurityGroups) {
        state.verifyInboundPortError = new Error(MESSAGES.noSecurityGroups);
      }
      state.defaultSecurityGroup = SecurityGroups[0];

      /**
       * @type {string}
       */
      const ipResponse = (await axios.get("http://checkip.amazonaws.com")).data;
      state.myIp = ipResponse.trim();
      const myIpRules = state.defaultSecurityGroup.IpPermissions.filter(
        ({ IpRanges }) =>
          IpRanges.some(
            ({ CidrIp }) =>
              CidrIp.startsWith(state.myIp) || CidrIp === "0.0.0.0/0",
          ),
      )
        .filter(({ IpProtocol }) => IpProtocol === "tcp")
        .filter(({ FromPort }) => FromPort === 80);

      state.myIpRules = myIpRules;
    },
  ),
  new ScenarioOutput(
    "verifiedInboundPort",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return MESSAGES.foundIpRules.replace(
          "${IP_RULES}",
          JSON.stringify(state.myIpRules, null, 2),
        );
      }
      return MESSAGES.noIpRules;
    },
  ),
  new ScenarioInput(
    "shouldAddInboundRule",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return false;
      }
      return MESSAGES.noIpRules;
    },
    { type: "confirm" },
  ),
  new ScenarioAction(
    "addInboundRule",
    /**
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup }} state
     */
    async (state) => {
      if (!state.shouldAddInboundRule) {
        return;
      }

      const client = new EC2Client({});
      await client.send(
        new AuthorizeSecurityGroupIngressCommand({
          GroupId: state.defaultSecurityGroup.GroupId,
          CidrIp: `${state.myIp}/32`,
          FromPort: 80,
          ToPort: 80,
          IpProtocol: "tcp",
        }),
      );
    },
  ),
  new ScenarioOutput("addedInboundRule", (state) => {
    if (state.shouldAddInboundRule) {
      return MESSAGES.addedInboundRule.replace("${IP_ADDRESS}", state.myIp);
    }
    return false;
  }),
  new ScenarioOutput("verifyingEndpoint", (state) =>
    MESSAGES.verifyingEndpoint.replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioAction("verifyEndpoint", async (state) => {
    try {
      const response = await retry({ intervalInMs: 2000, maxRetries: 30 }, () =>
        axios.get(`http://${state.loadBalancerDns}`),
      );
      state.endpointResponse = JSON.stringify(response.data, null, 2);
    } catch (e) {
      state.verifyEndpointError = e;
    }
  }),
  new ScenarioOutput("verifiedEndpoint", (state) => {
    if (state.verifyEndpointError) {
      console.error(state.verifyEndpointError);
    } else {
      return MESSAGES.verifiedEndpoint.replace(
        "${ENDPOINT_RESPONSE}",
        state.endpointResponse,
      );
    }
  }),
  saveState,
];
```
デモを実行するための手順を作成します。  

```
import { readFileSync } from "node:fs";
import { join } from "node:path";

import axios from "axios";

import {
  DescribeTargetGroupsCommand,
  DescribeTargetHealthCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";
import {
  DescribeInstanceInformationCommand,
  PutParameterCommand,
  SSMClient,
  SendCommandCommand,
} from "@aws-sdk/client-ssm";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DescribeAutoScalingGroupsCommand,
  TerminateInstanceInAutoScalingGroupCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  DescribeIamInstanceProfileAssociationsCommand,
  EC2Client,
  RebootInstancesCommand,
  ReplaceIamInstanceProfileAssociationCommand,
} from "@aws-sdk/client-ec2";

import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

const getRecommendation = new ScenarioAction(
  "getRecommendation",
  async (state) => {
    const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
    if (loadBalancer) {
      state.loadBalancerDnsName = loadBalancer.DNSName;
      try {
        state.recommendation = (
          await axios.get(`http://${state.loadBalancerDnsName}`)
        ).data;
      } catch (e) {
        state.recommendation = e instanceof Error ? e.message : e;
      }
    } else {
      throw new Error(MESSAGES.demoFindLoadBalancerError);
    }
  },
);

const getRecommendationResult = new ScenarioOutput(
  "getRecommendationResult",
  (state) =>
    `Recommendation:\n${JSON.stringify(state.recommendation, null, 2)}`,
  { preformatted: true },
);

const getHealthCheck = new ScenarioAction("getHealthCheck", async (state) => {
  const client = new ElasticLoadBalancingV2Client({});
  const { TargetGroups } = await client.send(
    new DescribeTargetGroupsCommand({
      Names: [NAMES.loadBalancerTargetGroupName],
    }),
  );

  const { TargetHealthDescriptions } = await client.send(
    new DescribeTargetHealthCommand({
      TargetGroupArn: TargetGroups[0].TargetGroupArn,
    }),
  );
  state.targetHealthDescriptions = TargetHealthDescriptions;
});

const getHealthCheckResult = new ScenarioOutput(
  "getHealthCheckResult",
  /**
   * @param {{ targetHealthDescriptions: import('@aws-sdk/client-elastic-load-balancing-v2').TargetHealthDescription[]}} state
   */
  (state) => {
    const status = state.targetHealthDescriptions
      .map((th) => `${th.Target.Id}: ${th.TargetHealth.State}`)
      .join("\n");
    return `Health check:\n${status}`;
  },
  { preformatted: true },
);

const loadBalancerLoop = new ScenarioAction(
  "loadBalancerLoop",
  getRecommendation.action,
  {
    whileConfig: {
      whileFn: ({ loadBalancerCheck }) => loadBalancerCheck,
      input: new ScenarioInput(
        "loadBalancerCheck",
        MESSAGES.demoLoadBalancerCheck,
        {
          type: "confirm",
        },
      ),
      output: getRecommendationResult,
    },
  },
);

const healthCheckLoop = new ScenarioAction(
  "healthCheckLoop",
  getHealthCheck.action,
  {
    whileConfig: {
      whileFn: ({ healthCheck }) => healthCheck,
      input: new ScenarioInput("healthCheck", MESSAGES.demoHealthCheck, {
        type: "confirm",
      }),
      output: getHealthCheckResult,
    },
  },
);

const statusSteps = [
  getRecommendation,
  getRecommendationResult,
  getHealthCheck,
  getHealthCheckResult,
];

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const demoSteps = [
  new ScenarioOutput("header", MESSAGES.demoHeader, { header: true }),
  new ScenarioOutput("sanityCheck", MESSAGES.demoSanityCheck),
  ...statusSteps,
  new ScenarioInput(
    "brokenDependencyConfirmation",
    MESSAGES.demoBrokenDependencyConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("brokenDependency", async (state) => {
    if (!state.brokenDependencyConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      state.badTableName = `fake-table-${Date.now()}`;
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmTableNameKey,
          Value: state.badTableName,
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testBrokenDependency", (state) =>
    MESSAGES.demoTestBrokenDependency.replace(
      "${TABLE_NAME}",
      state.badTableName,
    ),
  ),
  ...statusSteps,
  new ScenarioInput(
    "staticResponseConfirmation",
    MESSAGES.demoStaticResponseConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("staticResponse", async (state) => {
    if (!state.staticResponseConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmFailureResponseKey,
          Value: "static",
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testStaticResponse", MESSAGES.demoTestStaticResponse),
  ...statusSteps,
  new ScenarioInput(
    "badCredentialsConfirmation",
    MESSAGES.demoBadCredentialsConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("badCredentialsExit", (state) => {
    if (!state.badCredentialsConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("fixDynamoDBName", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioAction(
    "badCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-auto-scaling').Instance }} state
     */
    async (state) => {
      await createSsmOnlyInstanceProfile();
      const autoScalingClient = new AutoScalingClient({});
      const { AutoScalingGroups } = await autoScalingClient.send(
        new DescribeAutoScalingGroupsCommand({
          AutoScalingGroupNames: [NAMES.autoScalingGroupName],
        }),
      );
      state.targetInstance = AutoScalingGroups[0].Instances[0];
      const ec2Client = new EC2Client({});
      const { IamInstanceProfileAssociations } = await ec2Client.send(
        new DescribeIamInstanceProfileAssociationsCommand({
          Filters: [
            { Name: "instance-id", Values: [state.targetInstance.InstanceId] },
          ],
        }),
      );
      state.instanceProfileAssociationId =
        IamInstanceProfileAssociations[0].AssociationId;
      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        ec2Client.send(
          new ReplaceIamInstanceProfileAssociationCommand({
            AssociationId: state.instanceProfileAssociationId,
            IamInstanceProfile: { Name: NAMES.ssmOnlyInstanceProfileName },
          }),
        ),
      );

      await ec2Client.send(
        new RebootInstancesCommand({
          InstanceIds: [state.targetInstance.InstanceId],
        }),
      );

      const ssmClient = new SSMClient({});
      await retry({ intervalInMs: 20000, maxRetries: 15 }, async () => {
        const { InstanceInformationList } = await ssmClient.send(
          new DescribeInstanceInformationCommand({}),
        );

        const instance = InstanceInformationList.find(
          (info) => info.InstanceId === state.targetInstance.InstanceId,
        );

        if (!instance) {
          throw new Error("Instance not found.");
        }
      });

      await ssmClient.send(
        new SendCommandCommand({
          InstanceIds: [state.targetInstance.InstanceId],
          DocumentName: "AWS-RunShellScript",
          Parameters: { commands: ["cd / && sudo python3 server.py 80"] },
        }),
      );
    },
  ),
  new ScenarioOutput(
    "testBadCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation}} state
     */
    (state) =>
      MESSAGES.demoTestBadCredentials.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
  ),
  loadBalancerLoop,
  new ScenarioInput(
    "deepHealthCheckConfirmation",
    MESSAGES.demoDeepHealthCheckConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("deepHealthCheckExit", (state) => {
    if (!state.deepHealthCheckConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("deepHealthCheck", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmHealthCheckKey,
        Value: "deep",
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testDeepHealthCheck", MESSAGES.demoTestDeepHealthCheck),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "killInstanceConfirmation",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    (state) =>
      MESSAGES.demoKillInstanceConfirmation.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
    { type: "confirm" },
  ),
  new ScenarioAction("killInstanceExit", (state) => {
    if (!state.killInstanceConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction(
    "killInstance",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    async (state) => {
      const client = new AutoScalingClient({});
      await client.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: state.targetInstance.InstanceId,
          ShouldDecrementDesiredCapacity: false,
        }),
      );
    },
  ),
  new ScenarioOutput("testKillInstance", MESSAGES.demoTestKillInstance),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput("failOpenConfirmation", MESSAGES.demoFailOpenConfirmation, {
    type: "confirm",
  }),
  new ScenarioAction("failOpenExit", (state) => {
    if (!state.failOpenConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("failOpen", () => {
    const client = new SSMClient({});
    return client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: `fake-table-${Date.now()}`,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testFailOpen", MESSAGES.demoFailOpenTest),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "resetTableConfirmation",
    MESSAGES.demoResetTableConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("resetTableExit", (state) => {
    if (!state.resetTableConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("resetTable", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testResetTable", MESSAGES.demoTestResetTable),
  healthCheckLoop,
  loadBalancerLoop,
];

async function createSsmOnlyInstanceProfile() {
  const iamClient = new IAMClient({});
  const { Policy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyName: NAMES.ssmOnlyPolicyName,
      PolicyDocument: readFileSync(
        join(RESOURCES_PATH, "ssm_only_policy.json"),
      ),
    }),
  );
  await iamClient.send(
    new CreateRoleCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      AssumeRolePolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Principal: { Service: "ec2.amazonaws.com" },
            Action: "sts:AssumeRole",
          },
        ],
      }),
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: Policy.Arn,
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
    }),
  );
  const { InstanceProfile } = await iamClient.send(
    new CreateInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
    }),
  );
  await waitUntilInstanceProfileExists(
    { client: iamClient },
    { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName },
  );
  await iamClient.send(
    new AddRoleToInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
      RoleName: NAMES.ssmOnlyRoleName,
    }),
  );

  return InstanceProfile;
}
```
すべてのリソースを破棄するための手順を作成します。  

```
import { unlinkSync } from "node:fs";

import { DynamoDBClient, DeleteTableCommand } from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  DeleteKeyPairCommand,
  DeleteLaunchTemplateCommand,
  RevokeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  DeleteInstanceProfileCommand,
  RemoveRoleFromInstanceProfileCommand,
  DeletePolicyCommand,
  DeleteRoleCommand,
  DetachRolePolicyCommand,
  paginateListPolicies,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DeleteAutoScalingGroupCommand,
  TerminateInstanceInAutoScalingGroupCommand,
  UpdateAutoScalingGroupCommand,
  paginateDescribeAutoScalingGroups,
} from "@aws-sdk/client-auto-scaling";
import {
  DeleteLoadBalancerCommand,
  DeleteTargetGroupCommand,
  DescribeTargetGroupsCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { loadState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const destroySteps = [
  loadState,
  new ScenarioInput("destroy", MESSAGES.destroy, { type: "confirm" }),
  new ScenarioAction(
    "abort",
    (state) => state.destroy === false && process.exit(),
  ),
  new ScenarioAction("deleteTable", async (c) => {
    try {
      const client = new DynamoDBClient({});
      await client.send(new DeleteTableCommand({ TableName: NAMES.tableName }));
    } catch (e) {
      c.deleteTableError = e;
    }
  }),
  new ScenarioOutput("deleteTableResult", (state) => {
    if (state.deleteTableError) {
      console.error(state.deleteTableError);
      return MESSAGES.deleteTableError.replace(
        "${TABLE_NAME}",
        NAMES.tableName,
      );
    }
    return MESSAGES.deletedTable.replace("${TABLE_NAME}", NAMES.tableName);
  }),
  new ScenarioAction("deleteKeyPair", async (state) => {
    try {
      const client = new EC2Client({});
      await client.send(
        new DeleteKeyPairCommand({ KeyName: NAMES.keyPairName }),
      );
      unlinkSync(`${NAMES.keyPairName}.pem`);
    } catch (e) {
      state.deleteKeyPairError = e;
    }
  }),
  new ScenarioOutput("deleteKeyPairResult", (state) => {
    if (state.deleteKeyPairError) {
      console.error(state.deleteKeyPairError);
      return MESSAGES.deleteKeyPairError.replace(
        "${KEY_PAIR_NAME}",
        NAMES.keyPairName,
      );
    }
    return MESSAGES.deletedKeyPair.replace(
      "${KEY_PAIR_NAME}",
      NAMES.keyPairName,
    );
  }),
  new ScenarioAction("detachPolicyFromRole", async (state) => {
    try {
      const client = new IAMClient({});
      const policy = await findPolicy(NAMES.instancePolicyName);

      if (!policy) {
        state.detachPolicyFromRoleError = new Error(
          `Policy ${NAMES.instancePolicyName} not found.`,
        );
      } else {
        await client.send(
          new DetachRolePolicyCommand({
            RoleName: NAMES.instanceRoleName,
            PolicyArn: policy.Arn,
          }),
        );
      }
    } catch (e) {
      state.detachPolicyFromRoleError = e;
    }
  }),
  new ScenarioOutput("detachedPolicyFromRole", (state) => {
    if (state.detachPolicyFromRoleError) {
      console.error(state.detachPolicyFromRoleError);
      return MESSAGES.detachPolicyFromRoleError
        .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.detachedPolicyFromRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const policy = await findPolicy(NAMES.instancePolicyName);

    if (!policy) {
      state.deletePolicyError = new Error(
        `Policy ${NAMES.instancePolicyName} not found.`,
      );
    } else {
      return client.send(
        new DeletePolicyCommand({
          PolicyArn: policy.Arn,
        }),
      );
    }
  }),
  new ScenarioOutput("deletePolicyResult", (state) => {
    if (state.deletePolicyError) {
      console.error(state.deletePolicyError);
      return MESSAGES.deletePolicyError.replace(
        "${INSTANCE_POLICY_NAME}",
        NAMES.instancePolicyName,
      );
    }
    return MESSAGES.deletedPolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    );
  }),
  new ScenarioAction("removeRoleFromInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          RoleName: NAMES.instanceRoleName,
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.removeRoleFromInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("removeRoleFromInstanceProfileResult", (state) => {
    if (state.removeRoleFromInstanceProfile) {
      console.error(state.removeRoleFromInstanceProfileError);
      return MESSAGES.removeRoleFromInstanceProfileError
        .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.removedRoleFromInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstanceRole", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteRoleCommand({
          RoleName: NAMES.instanceRoleName,
        }),
      );
    } catch (e) {
      state.deleteInstanceRoleError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceRoleResult", (state) => {
    if (state.deleteInstanceRoleError) {
      console.error(state.deleteInstanceRoleError);
      return MESSAGES.deleteInstanceRoleError.replace(
        "${INSTANCE_ROLE_NAME}",
        NAMES.instanceRoleName,
      );
    }
    return MESSAGES.deletedInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    );
  }),
  new ScenarioAction("deleteInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceProfileResult", (state) => {
    if (state.deleteInstanceProfileError) {
      console.error(state.deleteInstanceProfileError);
      return MESSAGES.deleteInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.instanceProfileName,
      );
    }
    return MESSAGES.deletedInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    );
  }),
  new ScenarioAction("deleteAutoScalingGroup", async (state) => {
    try {
      await terminateGroupInstances(NAMES.autoScalingGroupName);
      await retry({ intervalInMs: 60000, maxRetries: 60 }, async () => {
        await deleteAutoScalingGroup(NAMES.autoScalingGroupName);
      });
    } catch (e) {
      state.deleteAutoScalingGroupError = e;
    }
  }),
  new ScenarioOutput("deleteAutoScalingGroupResult", (state) => {
    if (state.deleteAutoScalingGroupError) {
      console.error(state.deleteAutoScalingGroupError);
      return MESSAGES.deleteAutoScalingGroupError.replace(
        "${AUTO_SCALING_GROUP_NAME}",
        NAMES.autoScalingGroupName,
      );
    }
    return MESSAGES.deletedAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    );
  }),
  new ScenarioAction("deleteLaunchTemplate", async (state) => {
    const client = new EC2Client({});
    try {
      await client.send(
        new DeleteLaunchTemplateCommand({
          LaunchTemplateName: NAMES.launchTemplateName,
        }),
      );
    } catch (e) {
      state.deleteLaunchTemplateError = e;
    }
  }),
  new ScenarioOutput("deleteLaunchTemplateResult", (state) => {
    if (state.deleteLaunchTemplateError) {
      console.error(state.deleteLaunchTemplateError);
      return MESSAGES.deleteLaunchTemplateError.replace(
        "${LAUNCH_TEMPLATE_NAME}",
        NAMES.launchTemplateName,
      );
    }
    return MESSAGES.deletedLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    );
  }),
  new ScenarioAction("deleteLoadBalancer", async (state) => {
    try {
      const client = new ElasticLoadBalancingV2Client({});
      const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
      await client.send(
        new DeleteLoadBalancerCommand({
          LoadBalancerArn: loadBalancer.LoadBalancerArn,
        }),
      );
      await retry({ intervalInMs: 1000, maxRetries: 60 }, async () => {
        const lb = await findLoadBalancer(NAMES.loadBalancerName);
        if (lb) {
          throw new Error("Load balancer still exists.");
        }
      });
    } catch (e) {
      state.deleteLoadBalancerError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerResult", (state) => {
    if (state.deleteLoadBalancerError) {
      console.error(state.deleteLoadBalancerError);
      return MESSAGES.deleteLoadBalancerError.replace(
        "${LB_NAME}",
        NAMES.loadBalancerName,
      );
    }
    return MESSAGES.deletedLoadBalancer.replace(
      "${LB_NAME}",
      NAMES.loadBalancerName,
    );
  }),
  new ScenarioAction("deleteLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    try {
      const { TargetGroups } = await client.send(
        new DescribeTargetGroupsCommand({
          Names: [NAMES.loadBalancerTargetGroupName],
        }),
      );

      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        client.send(
          new DeleteTargetGroupCommand({
            TargetGroupArn: TargetGroups[0].TargetGroupArn,
          }),
        ),
      );
    } catch (e) {
      state.deleteLoadBalancerTargetGroupError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerTargetGroupResult", (state) => {
    if (state.deleteLoadBalancerTargetGroupError) {
      console.error(state.deleteLoadBalancerTargetGroupError);
      return MESSAGES.deleteLoadBalancerTargetGroupError.replace(
        "${TARGET_GROUP_NAME}",
        NAMES.loadBalancerTargetGroupName,
      );
    }
    return MESSAGES.deletedLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    );
  }),
  new ScenarioAction("detachSsmOnlyRoleFromProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyRoleFromProfileError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyRoleFromProfileResult", (state) => {
    if (state.detachSsmOnlyRoleFromProfileError) {
      console.error(state.detachSsmOnlyRoleFromProfileError);
      return MESSAGES.detachSsmOnlyRoleFromProfileError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
    }
    return MESSAGES.detachedSsmOnlyRoleFromProfile
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
  }),
  new ScenarioAction("detachSsmOnlyCustomRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyCustomRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyCustomRolePolicyResult", (state) => {
    if (state.detachSsmOnlyCustomRolePolicyError) {
      console.error(state.detachSsmOnlyCustomRolePolicyError);
      return MESSAGES.detachSsmOnlyCustomRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
    }
    return MESSAGES.detachedSsmOnlyCustomRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
  }),
  new ScenarioAction("detachSsmOnlyAWSRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
        }),
      );
    } catch (e) {
      state.detachSsmOnlyAWSRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyAWSRolePolicyResult", (state) => {
    if (state.detachSsmOnlyAWSRolePolicyError) {
      console.error(state.detachSsmOnlyAWSRolePolicyError);
      return MESSAGES.detachSsmOnlyAWSRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
    }
    return MESSAGES.detachedSsmOnlyAWSRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
  }),
  new ScenarioAction("deleteSsmOnlyInstanceProfile", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyInstanceProfileResult", (state) => {
    if (state.deleteSsmOnlyInstanceProfileError) {
      console.error(state.deleteSsmOnlyInstanceProfileError);
      return MESSAGES.deleteSsmOnlyInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.ssmOnlyInstanceProfileName,
      );
    }
    return MESSAGES.deletedSsmOnlyInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.ssmOnlyInstanceProfileName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyPolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DeletePolicyCommand({
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyPolicyError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyPolicyResult", (state) => {
    if (state.deleteSsmOnlyPolicyError) {
      console.error(state.deleteSsmOnlyPolicyError);
      return MESSAGES.deleteSsmOnlyPolicyError.replace(
        "${POLICY_NAME}",
        NAMES.ssmOnlyPolicyName,
      );
    }
    return MESSAGES.deletedSsmOnlyPolicy.replace(
      "${POLICY_NAME}",
      NAMES.ssmOnlyPolicyName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyRole", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteRoleCommand({
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyRoleError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyRoleResult", (state) => {
    if (state.deleteSsmOnlyRoleError) {
      console.error(state.deleteSsmOnlyRoleError);
      return MESSAGES.deleteSsmOnlyRoleError.replace(
        "${ROLE_NAME}",
        NAMES.ssmOnlyRoleName,
      );
    }
    return MESSAGES.deletedSsmOnlyRole.replace(
      "${ROLE_NAME}",
      NAMES.ssmOnlyRoleName,
    );
  }),
  new ScenarioAction(
    "revokeSecurityGroupIngress",
    async (
      /** @type {{ myIp: string, defaultSecurityGroup: { GroupId: string } }} */ state,
    ) => {
      const ec2Client = new EC2Client({});

      try {
        await ec2Client.send(
          new RevokeSecurityGroupIngressCommand({
            GroupId: state.defaultSecurityGroup.GroupId,
            CidrIp: `${state.myIp}/32`,
            FromPort: 80,
            ToPort: 80,
            IpProtocol: "tcp",
          }),
        );
      } catch (e) {
        state.revokeSecurityGroupIngressError = e;
      }
    },
  ),
  new ScenarioOutput("revokeSecurityGroupIngressResult", (state) => {
    if (state.revokeSecurityGroupIngressError) {
      console.error(state.revokeSecurityGroupIngressError);
      return MESSAGES.revokeSecurityGroupIngressError.replace(
        "${IP}",
        state.myIp,
      );
    }
    return MESSAGES.revokedSecurityGroupIngress.replace("${IP}", state.myIp);
  }),
];

/**
 * @param {string} policyName
 */
async function findPolicy(policyName) {
  const client = new IAMClient({});
  const paginatedPolicies = paginateListPolicies({ client }, {});
  for await (const page of paginatedPolicies) {
    const policy = page.Policies.find((p) => p.PolicyName === policyName);
    if (policy) {
      return policy;
    }
  }
}

/**
 * @param {string} groupName
 */
async function deleteAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  try {
    await client.send(
      new DeleteAutoScalingGroupCommand({
        AutoScalingGroupName: groupName,
      }),
    );
  } catch (err) {
    if (!(err instanceof Error)) {
      throw err;
    }
    console.log(err.name);
    throw err;
  }
}

/**
 * @param {string} groupName
 */
async function terminateGroupInstances(groupName) {
  const autoScalingClient = new AutoScalingClient({});
  const group = await findAutoScalingGroup(groupName);
  await autoScalingClient.send(
    new UpdateAutoScalingGroupCommand({
      AutoScalingGroupName: group.AutoScalingGroupName,
      MinSize: 0,
    }),
  );
  for (const i of group.Instances) {
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: i.InstanceId,
          ShouldDecrementDesiredCapacity: true,
        }),
      ),
    );
  }
}

async function findAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  const paginatedGroups = paginateDescribeAutoScalingGroups({ client }, {});
  for await (const page of paginatedGroups) {
    const group = page.AutoScalingGroups.find(
      (g) => g.AutoScalingGroupName === groupName,
    );
    if (group) {
      return group;
    }
  }
  throw new Error(`Auto scaling group ${groupName} not found.`);
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/AttachLoadBalancerTargetGroupsCommand)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/CreateAutoScalingGroupCommand)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateInstanceProfileCommand)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateLaunchTemplateCommand)
  + [CreateListener](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateListenerCommand)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateLoadBalancerCommand)
  + [CreateTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateTargetGroupCommand)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DeleteAutoScalingGroupCommand)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteInstanceProfileCommand)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteLaunchTemplateCommand)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteLoadBalancerCommand)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteTargetGroupCommand)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DescribeAutoScalingGroupsCommand)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeAvailabilityZonesCommand)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeIamInstanceProfileAssociationsCommand)
  + [DescribeInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstancesCommand)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeLoadBalancersCommand)
  + [DescribeSubnets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSubnetsCommand)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetGroupsCommand)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetHealthCommand)
  + [DescribeVpcs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeVpcsCommand)
  + [RebootInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RebootInstancesCommand)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReplaceIamInstanceProfileAssociationCommand)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/TerminateInstanceInAutoScalingGroupCommand)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/UpdateAutoScalingGroupCommand)

# SDK for JavaScript (v3) を使用した Amazon Bedrock の例
<a name="javascript_3_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Bedrock
<a name="bedrock_Hello_javascript_3_topic"></a>

次のコード例は、Amazon Bedrock の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";

import {
  BedrockClient,
  ListFoundationModelsCommand,
} from "@aws-sdk/client-bedrock";

const REGION = "us-east-1";
const client = new BedrockClient({ region: REGION });

export const main = async () => {
  const command = new ListFoundationModelsCommand({});

  const response = await client.send(command);
  const models = response.modelSummaries;

  console.log("Listing the available Bedrock foundation models:");

  for (const model of models) {
    console.log("=".repeat(42));
    console.log(` Model: ${model.modelId}`);
    console.log("-".repeat(42));
    console.log(` Name: ${model.modelName}`);
    console.log(` Provider: ${model.providerName}`);
    console.log(` Model ARN: ${model.modelArn}`);
    console.log(` Input modalities: ${model.inputModalities}`);
    console.log(` Output modalities: ${model.outputModalities}`);
    console.log(` Supported customizations: ${model.customizationsSupported}`);
    console.log(` Supported inference types: ${model.inferenceTypesSupported}`);
    console.log(` Lifecycle status: ${model.modelLifecycle.status}`);
    console.log(`${"=".repeat(42)}\n`);
  }

  const active = models.filter(
    (m) => m.modelLifecycle.status === "ACTIVE",
  ).length;
  const legacy = models.filter(
    (m) => m.modelLifecycle.status === "LEGACY",
  ).length;

  console.log(
    `There are ${active} active and ${legacy} legacy foundation models in ${REGION}.`,
  );

  return response;
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  await main();
}
```
+  API の詳細については、「AWS SDK for JavaScript API リファレンス**」の「[ListFoundationModels](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock/command/ListFoundationModelsCommand)」を参照してください。

## アクション
<a name="actions"></a>

### `GetFoundationModel`
<a name="bedrock_GetFoundationModel_javascript_3_topic"></a>

次のコード例は、`GetFoundationModel` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。
基盤モデルに関する詳細を取得します。  

```
import { fileURLToPath } from "node:url";

import {
  BedrockClient,
  GetFoundationModelCommand,
} from "@aws-sdk/client-bedrock";

/**
 * Get details about an Amazon Bedrock foundation model.
 *
 * @return {FoundationModelDetails} - The list of available bedrock foundation models.
 */
export const getFoundationModel = async () => {
  const client = new BedrockClient();

  const command = new GetFoundationModelCommand({
    modelIdentifier: "amazon.titan-embed-text-v1",
  });

  const response = await client.send(command);

  return response.modelDetails;
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const model = await getFoundationModel();
  console.log(model);
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetFoundationModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock/command/GetFoundationModelCommand)」を参照してください。

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_javascript_3_topic"></a>

次のコード例は、`ListFoundationModels` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。
使用可能な基盤モデルを一覧表示します。  

```
import { fileURLToPath } from "node:url";

import {
  BedrockClient,
  ListFoundationModelsCommand,
} from "@aws-sdk/client-bedrock";

/**
 * List the available Amazon Bedrock foundation models.
 *
 * @return {FoundationModelSummary[]} - The list of available bedrock foundation models.
 */
export const listFoundationModels = async () => {
  const client = new BedrockClient();

  const input = {
    // byProvider: 'STRING_VALUE',
    // byCustomizationType: 'FINE_TUNING' || 'CONTINUED_PRE_TRAINING',
    // byOutputModality: 'TEXT' || 'IMAGE' || 'EMBEDDING',
    // byInferenceType: 'ON_DEMAND' || 'PROVISIONED',
  };

  const command = new ListFoundationModelsCommand(input);

  const response = await client.send(command);

  return response.modelSummaries;
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const models = await listFoundationModels();
  console.log(models);
}
```
+  API の詳細については、「AWS SDK for JavaScript API リファレンス**」の「[ListFoundationModels](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock/command/ListFoundationModelsCommand)」を参照してください。

# SDK for JavaScript (v3) を使用する Amazon Bedrock ランタイムの例
<a name="javascript_3_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイムで AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [シナリオ](#scenarios)
+ [Amazon Nova](#amazon_nova)
+ [Amazon Nova Canvas](#amazon_nova_canvas)
+ [Anthropic Claude](#anthropic_claude)
+ [Cohere Command](#cohere_command)
+ [Meta Llama](#meta_llama)
+ [Mistral AI](#mistral_ai)

## はじめに
<a name="get_started"></a>

### Hello Amazon Bedrock
<a name="bedrock-runtime_Hello_javascript_3_topic"></a>

次のコード例は、Amazon Bedrock の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。

```
/**
 * @typedef {Object} Content
 * @property {string} text
 *
 * @typedef {Object} Usage
 * @property {number} input_tokens
 * @property {number} output_tokens
 *
 * @typedef {Object} ResponseBody
 * @property {Content[]} content
 * @property {Usage} usage
 */

import { fileURLToPath } from "node:url";
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";

const AWS_REGION = "us-east-1";

const MODEL_ID = "anthropic.claude-3-haiku-20240307-v1:0";
const PROMPT = "Hi. In a short paragraph, explain what you can do.";

const hello = async () => {
  console.log("=".repeat(35));
  console.log("Welcome to the Amazon Bedrock demo!");
  console.log("=".repeat(35));

  console.log("Model: Anthropic Claude 3 Haiku");
  console.log(`Prompt: ${PROMPT}\n`);
  console.log("Invoking model...\n");

  // Create a new Bedrock Runtime client instance.
  const client = new BedrockRuntimeClient({ region: AWS_REGION });

  // Prepare the payload for the model.
  const payload = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: 1000,
    messages: [{ role: "user", content: [{ type: "text", text: PROMPT }] }],
  };

  // Invoke Claude with the payload and wait for the response.
  const apiResponse = await client.send(
    new InvokeModelCommand({
      contentType: "application/json",
      body: JSON.stringify(payload),
      modelId: MODEL_ID,
    }),
  );

  // Decode and return the response(s)
  const decodedResponseBody = new TextDecoder().decode(apiResponse.body);
  /** @type {ResponseBody} */
  const responseBody = JSON.parse(decodedResponseBody);
  const responses = responseBody.content;

  if (responses.length === 1) {
    console.log(`Response: ${responses[0].text}`);
  } else {
    console.log("Haiku returned multiple responses:");
    console.log(responses);
  }

  console.log(`\nNumber of input tokens:   ${responseBody.usage.input_tokens}`);
  console.log(`Number of output tokens: ${responseBody.usage.output_tokens}`);
};

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  await hello();
}
```
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[InvokeModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Bedrock で複数の基盤モデルを呼び出す
<a name="bedrock-runtime_Scenario_InvokeModels_javascript_3_topic"></a>

次のコード例は、Amazon Bedrock でさまざまな大規模言語モデル (LLM) にプロンプトを準備して送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { FoundationModels } from "../config/foundation_models.js";

/**
 * @typedef {Object} ModelConfig
 * @property {Function} module
 * @property {Function} invoker
 * @property {string} modelId
 * @property {string} modelName
 */

const greeting = new ScenarioOutput(
  "greeting",
  "Welcome to the Amazon Bedrock Runtime client demo!",
  { header: true },
);

const selectModel = new ScenarioInput("model", "First, select a model:", {
  type: "select",
  choices: Object.values(FoundationModels).map((model) => ({
    name: model.modelName,
    value: model,
  })),
});

const enterPrompt = new ScenarioInput("prompt", "Now, enter your prompt:", {
  type: "input",
});

const printDetails = new ScenarioOutput(
  "print details",
  /**
   * @param {{ model: ModelConfig, prompt: string }} c
   */
  (c) => console.log(`Invoking ${c.model.modelName} with '${c.prompt}'...`),
);

const invokeModel = new ScenarioAction(
  "invoke model",
  /**
   * @param {{ model: ModelConfig, prompt: string, response: string }} c
   */
  async (c) => {
    const modelModule = await c.model.module();
    const invoker = c.model.invoker(modelModule);
    c.response = await invoker(c.prompt, c.model.modelId);
  },
);

const printResponse = new ScenarioOutput(
  "print response",
  /**
   * @param {{ response: string }} c
   */
  (c) => c.response,
);

const scenario = new Scenario("Amazon Bedrock Runtime Demo", [
  greeting,
  selectModel,
  enterPrompt,
  printDetails,
  invokeModel,
  printResponse,
]);

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  scenario.run();
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [InvokeModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelCommand)
  + [InvokeModelWithResponseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelWithResponseStreamCommand)

### Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUse_javascript_3_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime/scenarios/converse_tool_scenario#code-examples)での設定と実行の方法を確認してください。
シナリオフローのプライマリ実行。このシナリオはユーザー、Amazon Bedrock Converse API、気象ツールの間の会話を調整します。  

```
/* Before running this JavaScript code example, set up your development environment, including your credentials.
This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user
input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.*/

import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import {
  BedrockRuntimeClient,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

import { parseArgs } from "node:util";
import { fileURLToPath } from "node:url";
import data from "./questions.json" with { type: "json" };
import toolConfig from "./tool_config.json" with { type: "json" };

const __filename = fileURLToPath(import.meta.url);

const systemPrompt = [
  {
    text:
      "You are a weather assistant that provides current weather data for user-specified locations using only\n" +
      "the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.\n" +
      "If the user provides coordinates, infer the approximate location and refer to it in your response.\n" +
      "To use the tool, you strictly apply the provided tool specification.\n" +
      "If the user specifies a state, country, or region, infer the locations of cities within that state.\n" +
      "\n" +
      "- Explain your step-by-step process, and give brief updates before each step.\n" +
      "- Only use the Weather_Tool for data. Never guess or make up information. \n" +
      "- Repeat the tool use for subsequent requests if necessary.\n" +
      "- If the tool errors, apologize, explain weather is unavailable, and suggest other options.\n" +
      "- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use\n" +
      "  emojis where appropriate.\n" +
      "- Only respond to weather queries. Remind off-topic users of your purpose. \n" +
      "- Never claim to search online, access external data, or use tools besides Weather_Tool.\n" +
      "- Complete the entire process until you have all required data before sending the complete response.",
  },
];
const tools_config = toolConfig;

/// Starts the conversation with the user and handles the interaction with Bedrock.
async function askQuestion(userMessage) {
  // The maximum number of recursive calls allowed in the tool use function.
  // This helps prevent infinite loops and potential performance issues.
  const max_recursions = 5;
  const messages = [
    {
      role: "user",
      content: [{ text: userMessage }],
    },
  ];
  try {
    const response = await SendConversationtoBedrock(messages);
    await ProcessModelResponseAsync(response, messages, max_recursions);
  } catch (error) {
    console.log("error ", error);
  }
}

// Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response.
// param "messages" - The conversation history including the next message to send.
// return - The response from Amazon Bedrock.
async function SendConversationtoBedrock(messages) {
  const bedRockRuntimeClient = new BedrockRuntimeClient({
    region: "us-east-1",
  });
  try {
    const modelId = "amazon.nova-lite-v1:0";
    const response = await bedRockRuntimeClient.send(
      new ConverseCommand({
        modelId: modelId,
        messages: messages,
        system: systemPrompt,
        toolConfig: tools_config,
      }),
    );
    return response;
  } catch (caught) {
    if (caught.name === "ModelNotReady") {
      console.log(
        "`${caught.name}` - Model not ready, please wait and try again.",
      );
      throw caught;
    }
    if (caught.name === "BedrockRuntimeException") {
      console.log(
        '`${caught.name}` - "Error occurred while sending Converse request.',
      );
      throw caught;
    }
  }
}

// Processes the response received via Amazon Bedrock and performs the necessary actions based on the stop reason.
// param "response" - The model's response returned via Amazon Bedrock.
// param "messages" - The conversation history.
// param "max_recursions" - The maximum number of recursive calls allowed.
async function ProcessModelResponseAsync(response, messages, max_recursions) {
  if (max_recursions <= 0) {
    await HandleToolUseAsync(response, messages);
  }
  if (response.stopReason === "tool_use") {
    await HandleToolUseAsync(response, messages, max_recursions - 1);
  }
  if (response.stopReason === "end_turn") {
    const messageToPrint = response.output.message.content[0].text;
    console.log(messageToPrint.replace(/<[^>]+>/g, ""));
  }
}
// Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock.
// The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing.
// param "response" - the model's response containing the tool use request.
// param "messages" - the conversation history.
// param "max_recursions" - The maximum number of recursive calls allowed.
async function HandleToolUseAsync(response, messages, max_recursions) {
  const toolResultFinal = [];
  try {
    const output_message = response.output.message;
    messages.push(output_message);
    const toolRequests = output_message.content;
    const toolMessage = toolRequests[0].text;
    console.log(toolMessage.replace(/<[^>]+>/g, ""));
    for (const toolRequest of toolRequests) {
      if (Object.hasOwn(toolRequest, "toolUse")) {
        const toolUse = toolRequest.toolUse;
        const latitude = toolUse.input.latitude;
        const longitude = toolUse.input.longitude;
        const toolUseID = toolUse.toolUseId;
        console.log(
          `Requesting tool ${toolUse.name}, Tool use id ${toolUseID}`,
        );
        if (toolUse.name === "Weather_Tool") {
          try {
            const current_weather = await callWeatherTool(
              longitude,
              latitude,
            ).then((current_weather) => current_weather);
            const currentWeather = current_weather;
            const toolResult = {
              toolResult: {
                toolUseId: toolUseID,
                content: [{ json: currentWeather }],
              },
            };
            toolResultFinal.push(toolResult);
          } catch (err) {
            console.log("An error occurred. ", err);
          }
        }
      }
    }

    const toolResultMessage = {
      role: "user",
      content: toolResultFinal,
    };
    messages.push(toolResultMessage);
    // Send the conversation to Amazon Bedrock
    await ProcessModelResponseAsync(
      await SendConversationtoBedrock(messages),
      messages,
    );
  } catch (error) {
    console.log("An error occurred. ", error);
  }
}
// Call the Weathertool.
// param = longitude of location
// param = latitude of location
async function callWeatherTool(longitude, latitude) {
  // Open-Meteo API endpoint
  const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true`;

  // Fetch the weather data.
  return fetch(apiUrl)
    .then((response) => {
      return response.json().then((current_weather) => {
        return current_weather;
      });
    })
    .catch((error) => {
      console.error("Error fetching weather data:", error);
    });
}
/**
 * Used repeatedly to have the user press enter.
 * @type {ScenarioInput}
 */
const pressEnter = new ScenarioInput("continue", "Press Enter to continue", {
  type: "input",
  default: "",
});

const greet = new ScenarioOutput(
  "greet",
  "Welcome to the Amazon Bedrock Tool Use demo! \n" +
    "This assistant provides current weather information for user-specified locations. " +
    "You can ask for weather details by providing the location name or coordinates." +
    "Weather information will be provided using a custom Tool and open-meteo API." +
    "For the purposes of this example, we'll use in order the questions in ./questions.json :\n" +
    "What's the weather like in Seattle? " +
    "What's the best kind of cat? " +
    "Where is the warmest city in Washington State right now? " +
    "What's the warmest city in California right now?\n" +
    "To exit the program, simply type 'x' and press Enter.\n" +
    "Have fun and experiment with the app by editing the questions in ./questions.json! " +
    "P.S.: You're not limited to single locations, or even to using English! ",

  { header: true },
);
const displayAskQuestion1 = new ScenarioOutput(
  "displayAskQuestion1",
  "Press enter to ask question number 1 (default is 'What's the weather like in Seattle?')",
);

const askQuestion1 = new ScenarioAction(
  "askQuestion1",
  async (/** @type {State} */ state) => {
    const userMessage1 = data.questions["question-1"];
    await askQuestion(userMessage1);
  },
);

const displayAskQuestion2 = new ScenarioOutput(
  "displayAskQuestion2",
  "Press enter to ask question number 2 (default is 'What's the best kind of cat?')",
);

const askQuestion2 = new ScenarioAction(
  "askQuestion2",
  async (/** @type {State} */ state) => {
    const userMessage2 = data.questions["question-2"];
    await askQuestion(userMessage2);
  },
);
const displayAskQuestion3 = new ScenarioOutput(
  "displayAskQuestion3",
  "Press enter to ask question number 3 (default is 'Where is the warmest city in Washington State right now?')",
);

const askQuestion3 = new ScenarioAction(
  "askQuestion3",
  async (/** @type {State} */ state) => {
    const userMessage3 = data.questions["question-3"];
    await askQuestion(userMessage3);
  },
);

const displayAskQuestion4 = new ScenarioOutput(
  "displayAskQuestion4",
  "Press enter to ask question number 4 (default is 'What's the warmest city in California right now?')",
);

const askQuestion4 = new ScenarioAction(
  "askQuestion4",
  async (/** @type {State} */ state) => {
    const userMessage4 = data.questions["question-4"];
    await askQuestion(userMessage4);
  },
);

const goodbye = new ScenarioOutput(
  "goodbye",
  "Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you\n" +
    "learned something new, or got some inspiration for your own apps today!\n" +
    "For more Bedrock examples in different programming languages, have a look at:\n" +
    "https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html",
);

const myScenario = new Scenario("Converse Tool Scenario", [
  greet,
  pressEnter,
  displayAskQuestion1,
  askQuestion1,
  pressEnter,
  displayAskQuestion2,
  askQuestion2,
  pressEnter,
  displayAskQuestion3,
  askQuestion3,
  pressEnter,
  displayAskQuestion4,
  askQuestion4,
  pressEnter,
  goodbye,
]);

/** @type {{ stepHandlerOptions: StepHandlerOptions }} */
export const main = async (stepHandlerOptions) => {
  await myScenario.run(stepHandlerOptions);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      yes: {
        type: "boolean",
        short: "y",
      },
    },
  });
  main({ confirmAll: values.yes });
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Converse](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseCommand)」を参照してください。

## Amazon Nova
<a name="amazon_nova"></a>

### Converse
<a name="bedrock-runtime_Converse_AmazonNovaText_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
// This example demonstrates how to use the Amazon Nova foundation models to generate text.
// It shows how to:
// - Set up the Amazon Bedrock runtime client
// - Create a message
// - Configure and send a request
// - Process the response

import {
  BedrockRuntimeClient,
  ConversationRole,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Step 1: Create the Amazon Bedrock runtime client
// Credentials will be automatically loaded from the environment.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Step 2: Specify which model to use:
// Available Amazon Nova models and their characteristics:
// - Amazon Nova Micro: Text-only model optimized for lowest latency and cost
// - Amazon Nova Lite:  Fast, low-cost multimodal model for image, video, and text
// - Amazon Nova Pro:   Advanced multimodal model balancing accuracy, speed, and cost
//
// For the most current model IDs, see:
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
const modelId = "amazon.nova-lite-v1:0";

// Step 3: Create the message
// The message includes the text prompt and specifies that it comes from the user
const inputText =
  "Describe the purpose of a 'hello world' program in one line.";
const message = {
  content: [{ text: inputText }],
  role: ConversationRole.USER,
};

// Step 4: Configure the request
// Optional parameters to control the model's response:
// - maxTokens: maximum number of tokens to generate
// - temperature: randomness (max: 1.0, default: 0.7)
//   OR
// - topP: diversity of word choice (max: 1.0, default: 0.9)
// Note: Use either temperature OR topP, but not both
const request = {
  modelId,
  messages: [message],
  inferenceConfig: {
    maxTokens: 500, // The maximum response length
    temperature: 0.5, // Using temperature for randomness control
    //topP: 0.9,        // Alternative: use topP instead of temperature
  },
};

// Step 5: Send and process the request
// - Send the request to the model
// - Extract and return the generated text from the response
try {
  const response = await client.send(new ConverseCommand(request));
  console.log(response.output.message.content[0].text);
} catch (error) {
  console.error(`ERROR: Can't invoke '${modelId}'. Reason: ${error.message}`);
  throw error;
}
```
ツール設定を含む Bedrock の Converse API を使用して Amazon Nova にメッセージの会話を送信します。  

```
// This example demonstrates how to send a conversation of messages to Amazon Nova using Bedrock's Converse API with a tool configuration.
// It shows how to:
// - 1. Set up the Amazon Bedrock runtime client
// - 2. Define the parameters required enable Amazon Bedrock to use a tool when formulating its response (model ID, user input, system prompt, and the tool spec)
// - 3. Send the request to Amazon Bedrock, and returns the response.
// - 4. Add the tool response to the conversation, and send it back to Amazon Bedrock.
// - 5. Publish the response.

import {
  BedrockRuntimeClient,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Step 1: Create the Amazon Bedrock runtime client

// Credentials will be automatically loaded from the environment
const bedRockRuntimeClient = new BedrockRuntimeClient({
  region: "us-east-1",
});

// Step 2. Define the parameters required enable Amazon Bedrock to use a tool when formulating its response.

// The Bedrock Model ID.
const modelId = "amazon.nova-lite-v1:0";

// The system prompt to help Amazon Bedrock craft it's response.
const system_prompt = [
  {
    text:
      "You are a music expert that provides the most popular song played on a radio station, using only the\n" +
      "the top_song tool, which he call sign for the radio station for which you want the most popular song. " +
      "Example calls signs are WZPZ and WKRP. \n" +
      "- Only use the top_song tool. Never guess or make up information. \n" +
      "- If the tool errors, apologize, explain weather is unavailable, and suggest other options.\n" +
      "- Only respond to queries about the most popular song played on a radio station\n" +
      "Remind off-topic users of your purpose. \n" +
      "- Never claim to search online, access external data, or use tools besides the top_song tool.\n",
  },
];
//  The user's question.
const message = [
  {
    role: "user",
    content: [{ text: "What is the most popular song on WZPZ?" }],
  },
];
// The tool specification. In this case, it uses an example schema for
// a tool that gets the most popular song played on a radio station.
const tool_config = {
  tools: [
    {
      toolSpec: {
        name: "top_song",
        description: "Get the most popular song played on a radio station.",
        inputSchema: {
          json: {
            type: "object",
            properties: {
              sign: {
                type: "string",
                description:
                  "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP.",
              },
            },
            required: ["sign"],
          },
        },
      },
    },
  ],
};

// Helper function to return the song and artist from top_song tool.
async function get_top_song(call_sign) {
  try {
    if (call_sign === "WZPZ") {
      const song = "Elemental Hotel";
      const artist = "8 Storey Hike";
      return { song, artist };
    }
  } catch (error) {
    console.log(`${error.message}`);
  }
}

// 3. Send the request to Amazon Bedrock, and returns the response.
export async function SendConversationtoBedrock(
  modelId,
  message,
  system_prompt,
  tool_config,
) {
  try {
    const response = await bedRockRuntimeClient.send(
      new ConverseCommand({
        modelId: modelId,
        messages: message,
        system: system_prompt,
        toolConfig: tool_config,
      }),
    );
    if (response.stopReason === "tool_use") {
      const toolResultFinal = [];
      try {
        const output_message = response.output.message;
        message.push(output_message);
        const toolRequests = output_message.content;
        const toolMessage = toolRequests[0].text;
        console.log(toolMessage.replace(/<[^>]+>/g, ""));
        for (const toolRequest of toolRequests) {
          if (Object.hasOwn(toolRequest, "toolUse")) {
            const toolUse = toolRequest.toolUse;
            const sign = toolUse.input.sign;
            const toolUseID = toolUse.toolUseId;
            console.log(
              `Requesting tool ${toolUse.name}, Tool use id ${toolUseID}`,
            );
            if (toolUse.name === "top_song") {
              const toolResult = [];
              try {
                const top_song = await get_top_song(toolUse.input.sign).then(
                  (top_song) => top_song,
                );
                const toolResult = {
                  toolResult: {
                    toolUseId: toolUseID,
                    content: [
                      {
                        json: { song: top_song.song, artist: top_song.artist },
                      },
                    ],
                  },
                };
                toolResultFinal.push(toolResult);
              } catch (err) {
                const toolResult = {
                  toolUseId: toolUseID,
                  content: [{ json: { text: err.message } }],
                  status: "error",
                };
              }
            }
          }
        }
        const toolResultMessage = {
          role: "user",
          content: toolResultFinal,
        };
        // Step 4. Add the tool response to the conversation, and send it back to Amazon Bedrock.

        message.push(toolResultMessage);
        await SendConversationtoBedrock(
          modelId,
          message,
          system_prompt,
          tool_config,
        );
      } catch (caught) {
        console.error(`${caught.message}`);
        throw caught;
      }
    }

    // 4. Publish the response.
    if (response.stopReason === "end_turn") {
      const finalMessage = response.output.message.content[0].text;
      const messageToPrint = finalMessage.replace(/<[^>]+>/g);
      console.log(messageToPrint.replace(/<[^>]+>/g));
      return messageToPrint;
    }
  } catch (caught) {
    if (caught.name === "ModelNotReady") {
      console.log(
        `${caught.name} - Model not ready, please wait and try again.`,
      );
      throw caught;
    }
    if (caught.name === "BedrockRuntimeException") {
      console.log(
        `${caught.name} - Error occurred while sending Converse request`,
      );
      throw caught;
    }
  }
}
await SendConversationtoBedrock(modelId, message, system_prompt, tool_config);
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Converse](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseCommand)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AmazonNovaText_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// This example demonstrates how to use the Amazon Nova foundation models
// to generate streaming text responses.
// It shows how to:
// - Set up the Amazon Bedrock runtime client
// - Create a message
// - Configure a streaming request
// - Process the streaming response

import {
  BedrockRuntimeClient,
  ConversationRole,
  ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Step 1: Create the Amazon Bedrock runtime client
// Credentials will be automatically loaded from the environment
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Step 2: Specify which model to use
// Available Amazon Nova models and their characteristics:
// - Amazon Nova Micro: Text-only model optimized for lowest latency and cost
// - Amazon Nova Lite:  Fast, low-cost multimodal model for image, video, and text
// - Amazon Nova Pro:   Advanced multimodal model balancing accuracy, speed, and cost
//
// For the most current model IDs, see:
// https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
const modelId = "amazon.nova-lite-v1:0";

// Step 3: Create the message
// The message includes the text prompt and specifies that it comes from the user
const inputText =
  "Describe the purpose of a 'hello world' program in one paragraph";
const message = {
  content: [{ text: inputText }],
  role: ConversationRole.USER,
};

// Step 4: Configure the streaming request
// Optional parameters to control the model's response:
// - maxTokens: maximum number of tokens to generate
// - temperature: randomness (max: 1.0, default: 0.7)
//   OR
// - topP: diversity of word choice (max: 1.0, default: 0.9)
// Note: Use either temperature OR topP, but not both
const request = {
  modelId,
  messages: [message],
  inferenceConfig: {
    maxTokens: 500, // The maximum response length
    temperature: 0.5, // Using temperature for randomness control
    //topP: 0.9,        // Alternative: use topP instead of temperature
  },
};

// Step 5: Send and process the streaming request
// - Send the request to the model
// - Process each chunk of the streaming response
try {
  const response = await client.send(new ConverseStreamCommand(request));

  for await (const chunk of response.stream) {
    if (chunk.contentBlockDelta) {
      // Print each text chunk as it arrives
      process.stdout.write(chunk.contentBlockDelta.delta?.text || "");
    }
  }
} catch (error) {
  console.error(`ERROR: Can't invoke '${modelId}'. Reason: ${error.message}`);
  process.exitCode = 1;
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseStreamCommand)」を参照してください。

### シナリオ: Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUseDemo_AmazonNova_javascript_3_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime/scenarios/converse_tool_scenario#code-examples)での設定と実行の方法を確認してください。
シナリオフローのプライマリ実行。このシナリオはユーザー、Amazon Bedrock Converse API、気象ツールの間の会話を調整します。  

```
/* Before running this JavaScript code example, set up your development environment, including your credentials.
This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user
input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.*/

import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import {
  BedrockRuntimeClient,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

import { parseArgs } from "node:util";
import { fileURLToPath } from "node:url";
import data from "./questions.json" with { type: "json" };
import toolConfig from "./tool_config.json" with { type: "json" };

const __filename = fileURLToPath(import.meta.url);

const systemPrompt = [
  {
    text:
      "You are a weather assistant that provides current weather data for user-specified locations using only\n" +
      "the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.\n" +
      "If the user provides coordinates, infer the approximate location and refer to it in your response.\n" +
      "To use the tool, you strictly apply the provided tool specification.\n" +
      "If the user specifies a state, country, or region, infer the locations of cities within that state.\n" +
      "\n" +
      "- Explain your step-by-step process, and give brief updates before each step.\n" +
      "- Only use the Weather_Tool for data. Never guess or make up information. \n" +
      "- Repeat the tool use for subsequent requests if necessary.\n" +
      "- If the tool errors, apologize, explain weather is unavailable, and suggest other options.\n" +
      "- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use\n" +
      "  emojis where appropriate.\n" +
      "- Only respond to weather queries. Remind off-topic users of your purpose. \n" +
      "- Never claim to search online, access external data, or use tools besides Weather_Tool.\n" +
      "- Complete the entire process until you have all required data before sending the complete response.",
  },
];
const tools_config = toolConfig;

/// Starts the conversation with the user and handles the interaction with Bedrock.
async function askQuestion(userMessage) {
  // The maximum number of recursive calls allowed in the tool use function.
  // This helps prevent infinite loops and potential performance issues.
  const max_recursions = 5;
  const messages = [
    {
      role: "user",
      content: [{ text: userMessage }],
    },
  ];
  try {
    const response = await SendConversationtoBedrock(messages);
    await ProcessModelResponseAsync(response, messages, max_recursions);
  } catch (error) {
    console.log("error ", error);
  }
}

// Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response.
// param "messages" - The conversation history including the next message to send.
// return - The response from Amazon Bedrock.
async function SendConversationtoBedrock(messages) {
  const bedRockRuntimeClient = new BedrockRuntimeClient({
    region: "us-east-1",
  });
  try {
    const modelId = "amazon.nova-lite-v1:0";
    const response = await bedRockRuntimeClient.send(
      new ConverseCommand({
        modelId: modelId,
        messages: messages,
        system: systemPrompt,
        toolConfig: tools_config,
      }),
    );
    return response;
  } catch (caught) {
    if (caught.name === "ModelNotReady") {
      console.log(
        "`${caught.name}` - Model not ready, please wait and try again.",
      );
      throw caught;
    }
    if (caught.name === "BedrockRuntimeException") {
      console.log(
        '`${caught.name}` - "Error occurred while sending Converse request.',
      );
      throw caught;
    }
  }
}

// Processes the response received via Amazon Bedrock and performs the necessary actions based on the stop reason.
// param "response" - The model's response returned via Amazon Bedrock.
// param "messages" - The conversation history.
// param "max_recursions" - The maximum number of recursive calls allowed.
async function ProcessModelResponseAsync(response, messages, max_recursions) {
  if (max_recursions <= 0) {
    await HandleToolUseAsync(response, messages);
  }
  if (response.stopReason === "tool_use") {
    await HandleToolUseAsync(response, messages, max_recursions - 1);
  }
  if (response.stopReason === "end_turn") {
    const messageToPrint = response.output.message.content[0].text;
    console.log(messageToPrint.replace(/<[^>]+>/g, ""));
  }
}
// Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock.
// The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing.
// param "response" - the model's response containing the tool use request.
// param "messages" - the conversation history.
// param "max_recursions" - The maximum number of recursive calls allowed.
async function HandleToolUseAsync(response, messages, max_recursions) {
  const toolResultFinal = [];
  try {
    const output_message = response.output.message;
    messages.push(output_message);
    const toolRequests = output_message.content;
    const toolMessage = toolRequests[0].text;
    console.log(toolMessage.replace(/<[^>]+>/g, ""));
    for (const toolRequest of toolRequests) {
      if (Object.hasOwn(toolRequest, "toolUse")) {
        const toolUse = toolRequest.toolUse;
        const latitude = toolUse.input.latitude;
        const longitude = toolUse.input.longitude;
        const toolUseID = toolUse.toolUseId;
        console.log(
          `Requesting tool ${toolUse.name}, Tool use id ${toolUseID}`,
        );
        if (toolUse.name === "Weather_Tool") {
          try {
            const current_weather = await callWeatherTool(
              longitude,
              latitude,
            ).then((current_weather) => current_weather);
            const currentWeather = current_weather;
            const toolResult = {
              toolResult: {
                toolUseId: toolUseID,
                content: [{ json: currentWeather }],
              },
            };
            toolResultFinal.push(toolResult);
          } catch (err) {
            console.log("An error occurred. ", err);
          }
        }
      }
    }

    const toolResultMessage = {
      role: "user",
      content: toolResultFinal,
    };
    messages.push(toolResultMessage);
    // Send the conversation to Amazon Bedrock
    await ProcessModelResponseAsync(
      await SendConversationtoBedrock(messages),
      messages,
    );
  } catch (error) {
    console.log("An error occurred. ", error);
  }
}
// Call the Weathertool.
// param = longitude of location
// param = latitude of location
async function callWeatherTool(longitude, latitude) {
  // Open-Meteo API endpoint
  const apiUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&current_weather=true`;

  // Fetch the weather data.
  return fetch(apiUrl)
    .then((response) => {
      return response.json().then((current_weather) => {
        return current_weather;
      });
    })
    .catch((error) => {
      console.error("Error fetching weather data:", error);
    });
}
/**
 * Used repeatedly to have the user press enter.
 * @type {ScenarioInput}
 */
const pressEnter = new ScenarioInput("continue", "Press Enter to continue", {
  type: "input",
  default: "",
});

const greet = new ScenarioOutput(
  "greet",
  "Welcome to the Amazon Bedrock Tool Use demo! \n" +
    "This assistant provides current weather information for user-specified locations. " +
    "You can ask for weather details by providing the location name or coordinates." +
    "Weather information will be provided using a custom Tool and open-meteo API." +
    "For the purposes of this example, we'll use in order the questions in ./questions.json :\n" +
    "What's the weather like in Seattle? " +
    "What's the best kind of cat? " +
    "Where is the warmest city in Washington State right now? " +
    "What's the warmest city in California right now?\n" +
    "To exit the program, simply type 'x' and press Enter.\n" +
    "Have fun and experiment with the app by editing the questions in ./questions.json! " +
    "P.S.: You're not limited to single locations, or even to using English! ",

  { header: true },
);
const displayAskQuestion1 = new ScenarioOutput(
  "displayAskQuestion1",
  "Press enter to ask question number 1 (default is 'What's the weather like in Seattle?')",
);

const askQuestion1 = new ScenarioAction(
  "askQuestion1",
  async (/** @type {State} */ state) => {
    const userMessage1 = data.questions["question-1"];
    await askQuestion(userMessage1);
  },
);

const displayAskQuestion2 = new ScenarioOutput(
  "displayAskQuestion2",
  "Press enter to ask question number 2 (default is 'What's the best kind of cat?')",
);

const askQuestion2 = new ScenarioAction(
  "askQuestion2",
  async (/** @type {State} */ state) => {
    const userMessage2 = data.questions["question-2"];
    await askQuestion(userMessage2);
  },
);
const displayAskQuestion3 = new ScenarioOutput(
  "displayAskQuestion3",
  "Press enter to ask question number 3 (default is 'Where is the warmest city in Washington State right now?')",
);

const askQuestion3 = new ScenarioAction(
  "askQuestion3",
  async (/** @type {State} */ state) => {
    const userMessage3 = data.questions["question-3"];
    await askQuestion(userMessage3);
  },
);

const displayAskQuestion4 = new ScenarioOutput(
  "displayAskQuestion4",
  "Press enter to ask question number 4 (default is 'What's the warmest city in California right now?')",
);

const askQuestion4 = new ScenarioAction(
  "askQuestion4",
  async (/** @type {State} */ state) => {
    const userMessage4 = data.questions["question-4"];
    await askQuestion(userMessage4);
  },
);

const goodbye = new ScenarioOutput(
  "goodbye",
  "Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you\n" +
    "learned something new, or got some inspiration for your own apps today!\n" +
    "For more Bedrock examples in different programming languages, have a look at:\n" +
    "https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html",
);

const myScenario = new Scenario("Converse Tool Scenario", [
  greet,
  pressEnter,
  displayAskQuestion1,
  askQuestion1,
  pressEnter,
  displayAskQuestion2,
  askQuestion2,
  pressEnter,
  displayAskQuestion3,
  askQuestion3,
  pressEnter,
  displayAskQuestion4,
  askQuestion4,
  pressEnter,
  goodbye,
]);

/** @type {{ stepHandlerOptions: StepHandlerOptions }} */
export const main = async (stepHandlerOptions) => {
  await myScenario.run(stepHandlerOptions);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      yes: {
        type: "boolean",
        short: "y",
      },
    },
  });
  main({ confirmAll: values.yes });
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Converse](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseCommand)」を参照してください。

## Amazon Nova Canvas
<a name="amazon_nova_canvas"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AmazonNovaImageGeneration_javascript_3_topic"></a>

以下のコード例は、Amazon Bedrock で Amazon Nova Canvas を呼び出して画像を生成する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Nova Canvas で画像を作成します。  

```
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { saveImage } from "../../utils/image-creation.js";
import { fileURLToPath } from "node:url";

/**
 * This example demonstrates how to use Amazon Nova Canvas to generate images.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Configure the image generation parameters
 * - Send a request to generate an image
 * - Process the response and handle the generated image
 *
 * @returns {Promise<string>} Base64-encoded image data
 */
export const invokeModel = async () => {
  // Step 1: Create the Amazon Bedrock runtime client
  // Credentials will be automatically loaded from the environment
  const client = new BedrockRuntimeClient({ region: "us-east-1" });

  // Step 2: Specify which model to use
  // For the latest available models, see:
  // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
  const modelId = "amazon.nova-canvas-v1:0";

  // Step 3: Configure the request payload
  // First, set the main parameters:
  // - prompt: Text description of the image to generate
  // - seed: Random number for reproducible generation (0 to 858,993,459)
  const prompt = "A stylized picture of a cute old steampunk robot";
  const seed = Math.floor(Math.random() * 858993460);

  // Then, create the payload using the following structure:
  // - taskType: TEXT_IMAGE (specifies text-to-image generation)
  // - textToImageParams: Contains the text prompt
  // - imageGenerationConfig: Contains optional generation settings (seed, quality, etc.)
  // For a list of available request parameters, see:
  // https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html
  const payload = {
    taskType: "TEXT_IMAGE",
    textToImageParams: {
      text: prompt,
    },
    imageGenerationConfig: {
      seed,
      quality: "standard",
    },
  };

  // Step 4: Send and process the request
  // - Embed the payload in a request object
  // - Send the request to the model
  // - Extract and return the generated image data from the response
  try {
    const request = {
      modelId,
      body: JSON.stringify(payload),
    };
    const response = await client.send(new InvokeModelCommand(request));

    const decodedResponseBody = new TextDecoder().decode(response.body);
    // The response includes an array of base64-encoded PNG images
    /** @type {{images: string[]}} */
    const responseBody = JSON.parse(decodedResponseBody);
    return responseBody.images[0]; // Base64-encoded image data
  } catch (error) {
    console.error(`ERROR: Can't invoke '${modelId}'. Reason: ${error.message}`);
    throw error;
  }
};

// If run directly, execute the example and save the generated image
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  console.log("Generating image. This may take a few seconds...");
  invokeModel()
    .then(async (imageData) => {
      const imagePath = await saveImage(imageData, "nova-canvas");
      // Example path: javascriptv3/example_code/bedrock-runtime/output/nova-canvas/image-01.png
      console.log(`Image saved to: ${imagePath}`);
    })
    .catch((error) => {
      console.error("Execution failed:", error);
      process.exitCode = 1;
    });
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelCommand)」を参照してください。

## Anthropic Claude
<a name="anthropic_claude"></a>

### Converse
<a name="bedrock-runtime_Converse_AnthropicClaude_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。  

```
// Use the Conversation API to send a text message to Anthropic Claude.

import {
  BedrockRuntimeClient,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Claude 3 Haiku.
const modelId = "anthropic.claude-3-haiku-20240307-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the response text.
  const responseText = response.output.message.content[0].text;
  console.log(responseText);
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Converse](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseCommand)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AnthropicClaude_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Conversation API to send a text message to Anthropic Claude.

import {
  BedrockRuntimeClient,
  ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Claude 3 Haiku.
const modelId = "anthropic.claude-3-haiku-20240307-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseStreamCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the streamed response text in real-time.
  for await (const item of response.stream) {
    if (item.contentBlockDelta) {
      process.stdout.write(item.contentBlockDelta.delta?.text);
    }
  }
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseStreamCommand)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AnthropicClaude_javascript_3_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
import { fileURLToPath } from "node:url";

import { FoundationModels } from "../../config/foundation_models.js";
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
  InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

/**
 * @typedef {Object} ResponseContent
 * @property {string} text
 *
 * @typedef {Object} MessagesResponseBody
 * @property {ResponseContent[]} content
 *
 * @typedef {Object} Delta
 * @property {string} text
 *
 * @typedef {Object} Message
 * @property {string} role
 *
 * @typedef {Object} Chunk
 * @property {string} type
 * @property {Delta} delta
 * @property {Message} message
 */

/**
 * Invokes Anthropic Claude 3 using the Messages API.
 *
 * To learn more about the Anthropic Messages API, go to:
 * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
 *
 * @param {string} prompt - The input text prompt for the model to complete.
 * @param {string} [modelId] - The ID of the model to use. Defaults to "anthropic.claude-3-haiku-20240307-v1:0".
 */
export const invokeModel = async (
  prompt,
  modelId = "anthropic.claude-3-haiku-20240307-v1:0",
) => {
  // Create a new Bedrock Runtime client instance.
  const client = new BedrockRuntimeClient({ region: "us-east-1" });

  // Prepare the payload for the model.
  const payload = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: 1000,
    messages: [
      {
        role: "user",
        content: [{ type: "text", text: prompt }],
      },
    ],
  };

  // Invoke Claude with the payload and wait for the response.
  const command = new InvokeModelCommand({
    contentType: "application/json",
    body: JSON.stringify(payload),
    modelId,
  });
  const apiResponse = await client.send(command);

  // Decode and return the response(s)
  const decodedResponseBody = new TextDecoder().decode(apiResponse.body);
  /** @type {MessagesResponseBody} */
  const responseBody = JSON.parse(decodedResponseBody);
  return responseBody.content[0].text;
};

/**
 * Invokes Anthropic Claude 3 and processes the response stream.
 *
 * To learn more about the Anthropic Messages API, go to:
 * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
 *
 * @param {string} prompt - The input text prompt for the model to complete.
 * @param {string} [modelId] - The ID of the model to use. Defaults to "anthropic.claude-3-haiku-20240307-v1:0".
 */
export const invokeModelWithResponseStream = async (
  prompt,
  modelId = "anthropic.claude-3-haiku-20240307-v1:0",
) => {
  // Create a new Bedrock Runtime client instance.
  const client = new BedrockRuntimeClient({ region: "us-east-1" });

  // Prepare the payload for the model.
  const payload = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: 1000,
    messages: [
      {
        role: "user",
        content: [{ type: "text", text: prompt }],
      },
    ],
  };

  // Invoke Claude with the payload and wait for the API to respond.
  const command = new InvokeModelWithResponseStreamCommand({
    contentType: "application/json",
    body: JSON.stringify(payload),
    modelId,
  });
  const apiResponse = await client.send(command);

  let completeMessage = "";

  // Decode and process the response stream
  for await (const item of apiResponse.body) {
    /** @type Chunk */
    const chunk = JSON.parse(new TextDecoder().decode(item.chunk.bytes));
    const chunk_type = chunk.type;

    if (chunk_type === "content_block_delta") {
      const text = chunk.delta.text;
      completeMessage = completeMessage + text;
      process.stdout.write(text);
    }
  }

  // Return the final response
  return completeMessage;
};

// Invoke the function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const prompt = 'Write a paragraph starting with: "Once upon a time..."';
  const modelId = FoundationModels.CLAUDE_3_HAIKU.modelId;
  console.log(`Prompt: ${prompt}`);
  console.log(`Model ID: ${modelId}`);

  try {
    console.log("-".repeat(53));
    const response = await invokeModel(prompt, modelId);
    console.log(`\n${"-".repeat(53)}`);
    console.log("Final structured response:");
    console.log(response);
  } catch (err) {
    console.log(`\n${err}`);
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelCommand)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_AnthropicClaude_javascript_3_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
import { fileURLToPath } from "node:url";

import { FoundationModels } from "../../config/foundation_models.js";
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
  InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

/**
 * @typedef {Object} ResponseContent
 * @property {string} text
 *
 * @typedef {Object} MessagesResponseBody
 * @property {ResponseContent[]} content
 *
 * @typedef {Object} Delta
 * @property {string} text
 *
 * @typedef {Object} Message
 * @property {string} role
 *
 * @typedef {Object} Chunk
 * @property {string} type
 * @property {Delta} delta
 * @property {Message} message
 */

/**
 * Invokes Anthropic Claude 3 using the Messages API.
 *
 * To learn more about the Anthropic Messages API, go to:
 * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
 *
 * @param {string} prompt - The input text prompt for the model to complete.
 * @param {string} [modelId] - The ID of the model to use. Defaults to "anthropic.claude-3-haiku-20240307-v1:0".
 */
export const invokeModel = async (
  prompt,
  modelId = "anthropic.claude-3-haiku-20240307-v1:0",
) => {
  // Create a new Bedrock Runtime client instance.
  const client = new BedrockRuntimeClient({ region: "us-east-1" });

  // Prepare the payload for the model.
  const payload = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: 1000,
    messages: [
      {
        role: "user",
        content: [{ type: "text", text: prompt }],
      },
    ],
  };

  // Invoke Claude with the payload and wait for the response.
  const command = new InvokeModelCommand({
    contentType: "application/json",
    body: JSON.stringify(payload),
    modelId,
  });
  const apiResponse = await client.send(command);

  // Decode and return the response(s)
  const decodedResponseBody = new TextDecoder().decode(apiResponse.body);
  /** @type {MessagesResponseBody} */
  const responseBody = JSON.parse(decodedResponseBody);
  return responseBody.content[0].text;
};

/**
 * Invokes Anthropic Claude 3 and processes the response stream.
 *
 * To learn more about the Anthropic Messages API, go to:
 * https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
 *
 * @param {string} prompt - The input text prompt for the model to complete.
 * @param {string} [modelId] - The ID of the model to use. Defaults to "anthropic.claude-3-haiku-20240307-v1:0".
 */
export const invokeModelWithResponseStream = async (
  prompt,
  modelId = "anthropic.claude-3-haiku-20240307-v1:0",
) => {
  // Create a new Bedrock Runtime client instance.
  const client = new BedrockRuntimeClient({ region: "us-east-1" });

  // Prepare the payload for the model.
  const payload = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: 1000,
    messages: [
      {
        role: "user",
        content: [{ type: "text", text: prompt }],
      },
    ],
  };

  // Invoke Claude with the payload and wait for the API to respond.
  const command = new InvokeModelWithResponseStreamCommand({
    contentType: "application/json",
    body: JSON.stringify(payload),
    modelId,
  });
  const apiResponse = await client.send(command);

  let completeMessage = "";

  // Decode and process the response stream
  for await (const item of apiResponse.body) {
    /** @type Chunk */
    const chunk = JSON.parse(new TextDecoder().decode(item.chunk.bytes));
    const chunk_type = chunk.type;

    if (chunk_type === "content_block_delta") {
      const text = chunk.delta.text;
      completeMessage = completeMessage + text;
      process.stdout.write(text);
    }
  }

  // Return the final response
  return completeMessage;
};

// Invoke the function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const prompt = 'Write a paragraph starting with: "Once upon a time..."';
  const modelId = FoundationModels.CLAUDE_3_HAIKU.modelId;
  console.log(`Prompt: ${prompt}`);
  console.log(`Model ID: ${modelId}`);

  try {
    console.log("-".repeat(53));
    const response = await invokeModel(prompt, modelId);
    console.log(`\n${"-".repeat(53)}`);
    console.log("Final structured response:");
    console.log(response);
  } catch (err) {
    console.log(`\n${err}`);
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelWithResponseStreamCommand)」を参照してください。

## Cohere Command
<a name="cohere_command"></a>

### Converse
<a name="bedrock-runtime_Converse_CohereCommand_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信します。  

```
// Use the Conversation API to send a text message to Cohere Command.

import {
  BedrockRuntimeClient,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Command R.
const modelId = "cohere.command-r-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the response text.
  const responseText = response.output.message.content[0].text;
  console.log(responseText);
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Converse](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseCommand)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_CohereCommand_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Conversation API to send a text message to Cohere Command.

import {
  BedrockRuntimeClient,
  ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Command R.
const modelId = "cohere.command-r-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseStreamCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the streamed response text in real-time.
  for await (const item of response.stream) {
    if (item.contentBlockDelta) {
      process.stdout.write(item.contentBlockDelta.delta?.text);
    }
  }
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ConverseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseStreamCommand)」を参照してください。

## Meta Llama
<a name="meta_llama"></a>

### Converse
<a name="bedrock-runtime_Converse_MetaLlama_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信します。  

```
// Use the Conversation API to send a text message to Meta Llama.

import {
  BedrockRuntimeClient,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Llama 3 8b Instruct.
const modelId = "meta.llama3-8b-instruct-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the response text.
  const responseText = response.output.message.content[0].text;
  console.log(responseText);
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Converse](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseCommand)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_MetaLlama_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Conversation API to send a text message to Meta Llama.

import {
  BedrockRuntimeClient,
  ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Llama 3 8b Instruct.
const modelId = "meta.llama3-8b-instruct-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseStreamCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the streamed response text in real-time.
  for await (const item of response.stream) {
    if (item.contentBlockDelta) {
      process.stdout.write(item.contentBlockDelta.delta?.text);
    }
  }
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseStreamCommand)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MetaLlama3_javascript_3_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Send a prompt to Meta Llama 3 and print the response.

import {
  BedrockRuntimeClient,
  InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region of your choice.
const client = new BedrockRuntimeClient({ region: "us-west-2" });

// Set the model ID, e.g., Llama 3 70B Instruct.
const modelId = "meta.llama3-70b-instruct-v1:0";

// Define the user message to send.
const userMessage =
  "Describe the purpose of a 'hello world' program in one sentence.";

// Embed the message in Llama 3's prompt format.
const prompt = `
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
${userMessage}
<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
`;

// Format the request payload using the model's native structure.
const request = {
  prompt,
  // Optional inference parameters:
  max_gen_len: 512,
  temperature: 0.5,
  top_p: 0.9,
};

// Encode and send the request.
const response = await client.send(
  new InvokeModelCommand({
    contentType: "application/json",
    body: JSON.stringify(request),
    modelId,
  }),
);

// Decode the native response body.
/** @type {{ generation: string }} */
const nativeResponse = JSON.parse(new TextDecoder().decode(response.body));

// Extract and print the generated text.
const responseText = nativeResponse.generation;
console.log(responseText);

// Learn more about the Llama 3 prompt format at:
// https://llama.meta.com/docs/model-cards-and-prompt-formats/meta-llama-3/#special-tokens-used-with-meta-llama-3
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelCommand)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_MetaLlama3_javascript_3_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Send a prompt to Meta Llama 3 and print the response stream in real-time.

import {
  BedrockRuntimeClient,
  InvokeModelWithResponseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region of your choice.
const client = new BedrockRuntimeClient({ region: "us-west-2" });

// Set the model ID, e.g., Llama 3 70B Instruct.
const modelId = "meta.llama3-70b-instruct-v1:0";

// Define the user message to send.
const userMessage =
  "Describe the purpose of a 'hello world' program in one sentence.";

// Embed the message in Llama 3's prompt format.
const prompt = `
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
${userMessage}
<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
`;

// Format the request payload using the model's native structure.
const request = {
  prompt,
  // Optional inference parameters:
  max_gen_len: 512,
  temperature: 0.5,
  top_p: 0.9,
};

// Encode and send the request.
const responseStream = await client.send(
  new InvokeModelWithResponseStreamCommand({
    contentType: "application/json",
    body: JSON.stringify(request),
    modelId,
  }),
);

// Extract and print the response stream in real-time.
for await (const event of responseStream.body) {
  /** @type {{ generation: string }} */
  const chunk = JSON.parse(new TextDecoder().decode(event.chunk.bytes));
  if (chunk.generation) {
    process.stdout.write(chunk.generation);
  }
}

// Learn more about the Llama 3 prompt format at:
// https://llama.meta.com/docs/model-cards-and-prompt-formats/meta-llama-3/#special-tokens-used-with-meta-llama-3
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelWithResponseStreamCommand)」を参照してください。

## Mistral AI
<a name="mistral_ai"></a>

### Converse
<a name="bedrock-runtime_Converse_Mistral_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信します。  

```
// Use the Conversation API to send a text message to Mistral.

import {
  BedrockRuntimeClient,
  ConverseCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Mistral Large.
const modelId = "mistral.mistral-large-2402-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the response text.
  const responseText = response.output.message.content[0].text;
  console.log(responseText);
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Converse](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseCommand)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_Mistral_javascript_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Conversation API to send a text message to Mistral.

import {
  BedrockRuntimeClient,
  ConverseStreamCommand,
} from "@aws-sdk/client-bedrock-runtime";

// Create a Bedrock Runtime client in the AWS Region you want to use.
const client = new BedrockRuntimeClient({ region: "us-east-1" });

// Set the model ID, e.g., Mistral Large.
const modelId = "mistral.mistral-large-2402-v1:0";

// Start a conversation with the user message.
const userMessage =
  "Describe the purpose of a 'hello world' program in one line.";
const conversation = [
  {
    role: "user",
    content: [{ text: userMessage }],
  },
];

// Create a command with the model ID, the message, and a basic configuration.
const command = new ConverseStreamCommand({
  modelId,
  messages: conversation,
  inferenceConfig: { maxTokens: 512, temperature: 0.5, topP: 0.9 },
});

try {
  // Send the command to the model and wait for the response
  const response = await client.send(command);

  // Extract and print the streamed response text in real-time.
  for await (const item of response.stream) {
    if (item.contentBlockDelta) {
      process.stdout.write(item.contentBlockDelta.delta?.text);
    }
  }
} catch (err) {
  console.log(`ERROR: Can't invoke '${modelId}'. Reason: ${err}`);
  process.exit(1);
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/ConverseStreamCommand)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MistralAi_javascript_3_topic"></a>

次のコード例は、Invoke Model API を使用して Mistral モデルにテキストメッセージを送信する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
import { fileURLToPath } from "node:url";

import { FoundationModels } from "../../config/foundation_models.js";
import {
  BedrockRuntimeClient,
  InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";

/**
 * @typedef {Object} Output
 * @property {string} text
 *
 * @typedef {Object} ResponseBody
 * @property {Output[]} outputs
 */

/**
 * Invokes a Mistral 7B Instruct model.
 *
 * @param {string} prompt - The input text prompt for the model to complete.
 * @param {string} [modelId] - The ID of the model to use. Defaults to "mistral.mistral-7b-instruct-v0:2".
 */
export const invokeModel = async (
  prompt,
  modelId = "mistral.mistral-7b-instruct-v0:2",
) => {
  // Create a new Bedrock Runtime client instance.
  const client = new BedrockRuntimeClient({ region: "us-east-1" });

  // Mistral instruct models provide optimal results when embedding
  // the prompt into the following template:
  const instruction = `<s>[INST] ${prompt} [/INST]`;

  // Prepare the payload.
  const payload = {
    prompt: instruction,
    max_tokens: 500,
    temperature: 0.5,
  };

  // Invoke the model with the payload and wait for the response.
  const command = new InvokeModelCommand({
    contentType: "application/json",
    body: JSON.stringify(payload),
    modelId,
  });
  const apiResponse = await client.send(command);

  // Decode and return the response.
  const decodedResponseBody = new TextDecoder().decode(apiResponse.body);
  /** @type {ResponseBody} */
  const responseBody = JSON.parse(decodedResponseBody);
  return responseBody.outputs[0].text;
};

// Invoke the function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const prompt =
    'Complete the following in one sentence: "Once upon a time..."';
  const modelId = FoundationModels.MISTRAL_7B.modelId;
  console.log(`Prompt: ${prompt}`);
  console.log(`Model ID: ${modelId}`);

  try {
    console.log("-".repeat(53));
    const response = await invokeModel(prompt, modelId);
    console.log(response);
  } catch (err) {
    console.log(err);
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-runtime/command/InvokeModelCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon Bedrock エージェントの例
<a name="javascript_3_bedrock-agent_code_examples"></a>

次のコード例は、Amazon Bedrock エージェントで AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Amazon Bedrock エージェントの始め方
<a name="bedrock-agent_Hello_javascript_3_topic"></a>

次のコード例は、Amazon Bedrock エージェントの使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";

import {
  BedrockAgentClient,
  GetAgentCommand,
  paginateListAgents,
} from "@aws-sdk/client-bedrock-agent";

/**
 * @typedef {Object} AgentSummary
 */

/**
 * A simple scenario to demonstrate basic setup and interaction with the Bedrock Agents Client.
 *
 * This function first initializes the Amazon Bedrock Agents client for a specific region.
 * It then retrieves a list of existing agents using the streamlined paginator approach.
 * For each agent found, it retrieves detailed information using a command object.
 *
 * Demonstrates:
 * - Use of the Bedrock Agents client to initialize and communicate with the AWS service.
 * - Listing resources in a paginated response pattern.
 * - Accessing an individual resource using a command object.
 *
 * @returns {Promise<void>} A promise that resolves when the function has completed execution.
 */
export const main = async () => {
  const region = "us-east-1";

  console.log("=".repeat(68));

  console.log(`Initializing Amazon Bedrock Agents client for ${region}...`);
  const client = new BedrockAgentClient({ region });

  console.log("Retrieving the list of existing agents...");
  const paginatorConfig = { client };
  const pages = paginateListAgents(paginatorConfig, {});

  /** @type {AgentSummary[]} */
  const agentSummaries = [];
  for await (const page of pages) {
    agentSummaries.push(...page.agentSummaries);
  }

  console.log(`Found ${agentSummaries.length} agents in ${region}.`);

  if (agentSummaries.length > 0) {
    for (const agentSummary of agentSummaries) {
      const agentId = agentSummary.agentId;
      console.log("=".repeat(68));
      console.log(`Retrieving agent with ID: ${agentId}:`);
      console.log("-".repeat(68));

      const command = new GetAgentCommand({ agentId });
      const response = await client.send(command);
      const agent = response.agent;

      console.log(` Name: ${agent.agentName}`);
      console.log(` Status: ${agent.agentStatus}`);
      console.log(` ARN: ${agent.agentArn}`);
      console.log(` Foundation model: ${agent.foundationModel}`);
    }
  }
  console.log("=".repeat(68));
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  await main();
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [GetAgent](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent/command/GetAgentCommand)
  + [ListAgents](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent/command/ListAgentsCommand)

## アクション
<a name="actions"></a>

### `CreateAgent`
<a name="bedrock-agent_CreateAgent_javascript_3_topic"></a>

次のコード例は、`CreateAgent` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
 エージェントを作成します。  

```
import { fileURLToPath } from "node:url";
import { checkForPlaceholders } from "../lib/utils.js";

import {
  BedrockAgentClient,
  CreateAgentCommand,
} from "@aws-sdk/client-bedrock-agent";

/**
 * Creates an Amazon Bedrock Agent.
 *
 * @param {string} agentName - A name for the agent that you create.
 * @param {string} foundationModel - The foundation model to be used by the agent you create.
 * @param {string} agentResourceRoleArn - The ARN of the IAM role with permissions required by the agent.
 * @param {string} [region='us-east-1'] - The AWS region in use.
 * @returns {Promise<import("@aws-sdk/client-bedrock-agent").Agent>} An object containing details of the created agent.
 */
export const createAgent = async (
  agentName,
  foundationModel,
  agentResourceRoleArn,
  region = "us-east-1",
) => {
  const client = new BedrockAgentClient({ region });

  const command = new CreateAgentCommand({
    agentName,
    foundationModel,
    agentResourceRoleArn,
  });
  const response = await client.send(command);

  return response.agent;
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  // Replace the placeholders for agentName and accountId, and roleName with a unique name for the new agent,
  // the id of your AWS account, and the name of an existing execution role that the agent can use inside your account.
  // For foundationModel, specify the desired model. Ensure to remove the brackets '[]' before adding your data.

  // A string (max 100 chars) that can include letters, numbers, dashes '-', and underscores '_'.
  const agentName = "[your-bedrock-agent-name]";

  // Your AWS account id.
  const accountId = "[123456789012]";

  // The name of the agent's execution role. It must be prefixed by `AmazonBedrockExecutionRoleForAgents_`.
  const roleName = "[AmazonBedrockExecutionRoleForAgents_your-role-name]";

  // The ARN for the agent's execution role.
  // Follow the ARN format: 'arn:aws:iam::account-id:role/role-name'
  const roleArn = `arn:aws:iam::${accountId}:role/${roleName}`;

  // Specify the model for the agent. Change if a different model is preferred.
  const foundationModel = "anthropic.claude-v2";

  // Check for unresolved placeholders in agentName and roleArn.
  checkForPlaceholders([agentName, roleArn]);

  console.log("Creating a new agent...");

  const agent = await createAgent(agentName, foundationModel, roleArn);
  console.log(agent);
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateAgent](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent/command/CreateAgentCommand)」を参照してください。

### `DeleteAgent`
<a name="bedrock-agent_DeleteAgent_javascript_3_topic"></a>

次のコード例は、`DeleteAgent` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントを削除します。  

```
import { fileURLToPath } from "node:url";
import { checkForPlaceholders } from "../lib/utils.js";

import {
  BedrockAgentClient,
  DeleteAgentCommand,
} from "@aws-sdk/client-bedrock-agent";

/**
 * Deletes an Amazon Bedrock Agent.
 *
 * @param {string} agentId - The unique identifier of the agent to delete.
 * @param {string} [region='us-east-1'] - The AWS region in use.
 * @returns {Promise<import("@aws-sdk/client-bedrock-agent").DeleteAgentCommandOutput>} An object containing the agent id, the status, and some additional metadata.
 */
export const deleteAgent = (agentId, region = "us-east-1") => {
  const client = new BedrockAgentClient({ region });
  const command = new DeleteAgentCommand({ agentId });
  return client.send(command);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  // Replace the placeholders for agentId with an existing agent's id.
  // Ensure to remove the brackets (`[]`) before adding your data.

  // The agentId must be an alphanumeric string with exactly 10 characters.
  const agentId = "[ABC123DE45]";

  // Check for unresolved placeholders in agentId.
  checkForPlaceholders([agentId]);

  console.log(`Deleting agent with ID ${agentId}...`);

  const response = await deleteAgent(agentId);
  console.log(response);
}
```
+  API の詳細については、「[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent/command/DeleteAgentCommand)」の「*DeleteAgent*」を参照してください。

### `GetAgent`
<a name="bedrock-agent_GetAgent_javascript_3_topic"></a>

次のコード例は、`GetAgent` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントを取得します。  

```
import { fileURLToPath } from "node:url";
import { checkForPlaceholders } from "../lib/utils.js";

import {
  BedrockAgentClient,
  GetAgentCommand,
} from "@aws-sdk/client-bedrock-agent";

/**
 * Retrieves the details of an Amazon Bedrock Agent.
 *
 * @param {string} agentId - The unique identifier of the agent.
 * @param {string} [region='us-east-1'] - The AWS region in use.
 * @returns {Promise<import("@aws-sdk/client-bedrock-agent").Agent>} An object containing the agent details.
 */
export const getAgent = async (agentId, region = "us-east-1") => {
  const client = new BedrockAgentClient({ region });

  const command = new GetAgentCommand({ agentId });
  const response = await client.send(command);
  return response.agent;
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  // Replace the placeholders for agentId with an existing agent's id.
  // Ensure to remove the brackets '[]' before adding your data.

  // The agentId must be an alphanumeric string with exactly 10 characters.
  const agentId = "[ABC123DE45]";

  // Check for unresolved placeholders in agentId.
  checkForPlaceholders([agentId]);

  console.log(`Retrieving agent with ID ${agentId}...`);

  const agent = await getAgent(agentId);
  console.log(agent);
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetAgent](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent/command/GetAgentCommand)」を参照してください。

### `ListAgentActionGroups`
<a name="bedrock-agent_ListAgentActionGroups_javascript_3_topic"></a>

次のコード例は、`ListAgentActionGroups` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントのアクショングループを一覧表示します。  

```
import { fileURLToPath } from "node:url";
import { checkForPlaceholders } from "../lib/utils.js";

import {
  BedrockAgentClient,
  ListAgentActionGroupsCommand,
  paginateListAgentActionGroups,
} from "@aws-sdk/client-bedrock-agent";

/**
 * Retrieves a list of Action Groups of an agent utilizing the paginator function.
 *
 * This function leverages a paginator, which abstracts the complexity of pagination, providing
 * a straightforward way to handle paginated results inside a `for await...of` loop.
 *
 * @param {string} agentId - The unique identifier of the agent.
 * @param {string} agentVersion - The version of the agent.
 * @param {string} [region='us-east-1'] - The AWS region in use.
 * @returns {Promise<ActionGroupSummary[]>} An array of action group summaries.
 */
export const listAgentActionGroupsWithPaginator = async (
  agentId,
  agentVersion,
  region = "us-east-1",
) => {
  const client = new BedrockAgentClient({ region });

  // Create a paginator configuration
  const paginatorConfig = {
    client,
    pageSize: 10, // optional, added for demonstration purposes
  };

  const params = { agentId, agentVersion };

  const pages = paginateListAgentActionGroups(paginatorConfig, params);

  // Paginate until there are no more results
  const actionGroupSummaries = [];
  for await (const page of pages) {
    actionGroupSummaries.push(...page.actionGroupSummaries);
  }

  return actionGroupSummaries;
};

/**
 * Retrieves a list of Action Groups of an agent utilizing the ListAgentActionGroupsCommand.
 *
 * This function demonstrates the manual approach, sending a command to the client and processing the response.
 * Pagination must manually be managed. For a simplified approach that abstracts away pagination logic, see
 * the `listAgentActionGroupsWithPaginator()` example below.
 *
 * @param {string} agentId - The unique identifier of the agent.
 * @param {string} agentVersion - The version of the agent.
 * @param {string} [region='us-east-1'] - The AWS region in use.
 * @returns {Promise<ActionGroupSummary[]>} An array of action group summaries.
 */
export const listAgentActionGroupsWithCommandObject = async (
  agentId,
  agentVersion,
  region = "us-east-1",
) => {
  const client = new BedrockAgentClient({ region });

  let nextToken;
  const actionGroupSummaries = [];
  do {
    const command = new ListAgentActionGroupsCommand({
      agentId,
      agentVersion,
      nextToken,
      maxResults: 10, // optional, added for demonstration purposes
    });

    /** @type {{actionGroupSummaries: ActionGroupSummary[], nextToken?: string}} */
    const response = await client.send(command);

    for (const actionGroup of response.actionGroupSummaries || []) {
      actionGroupSummaries.push(actionGroup);
    }

    nextToken = response.nextToken;
  } while (nextToken);

  return actionGroupSummaries;
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  // Replace the placeholders for agentId and agentVersion with an existing agent's id and version.
  // Ensure to remove the brackets '[]' before adding your data.

  // The agentId must be an alphanumeric string with exactly 10 characters.
  const agentId = "[ABC123DE45]";

  // A string either containing `DRAFT` or a number with 1-5 digits (e.g., '123' or 'DRAFT').
  const agentVersion = "[DRAFT]";

  // Check for unresolved placeholders in agentId and agentVersion.
  checkForPlaceholders([agentId, agentVersion]);

  console.log("=".repeat(68));
  console.log(
    "Listing agent action groups using ListAgentActionGroupsCommand:",
  );

  for (const actionGroup of await listAgentActionGroupsWithCommandObject(
    agentId,
    agentVersion,
  )) {
    console.log(actionGroup);
  }

  console.log("=".repeat(68));
  console.log(
    "Listing agent action groups using the paginateListAgents function:",
  );
  for (const actionGroup of await listAgentActionGroupsWithPaginator(
    agentId,
    agentVersion,
  )) {
    console.log(actionGroup);
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListAgentActionGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent/command/ListAgentActionGroupsCommand)」を参照してください。

### `ListAgents`
<a name="bedrock-agent_ListAgents_javascript_3_topic"></a>

次のコード例は、`ListAgents` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
アカウントに属するエージェントを一覧表示します。  

```
import { fileURLToPath } from "node:url";

import {
  BedrockAgentClient,
  ListAgentsCommand,
  paginateListAgents,
} from "@aws-sdk/client-bedrock-agent";

/**
 * Retrieves a list of available Amazon Bedrock agents utilizing the paginator function.
 *
 * This function leverages a paginator, which abstracts the complexity of pagination, providing
 * a straightforward way to handle paginated results inside a `for await...of` loop.
 *
 * @param {string} [region='us-east-1'] - The AWS region in use.
 * @returns {Promise<AgentSummary[]>} An array of agent summaries.
 */
export const listAgentsWithPaginator = async (region = "us-east-1") => {
  const client = new BedrockAgentClient({ region });

  const paginatorConfig = {
    client,
    pageSize: 10, // optional, added for demonstration purposes
  };

  const pages = paginateListAgents(paginatorConfig, {});

  // Paginate until there are no more results
  const agentSummaries = [];
  for await (const page of pages) {
    agentSummaries.push(...page.agentSummaries);
  }

  return agentSummaries;
};

/**
 * Retrieves a list of available Amazon Bedrock agents utilizing the ListAgentsCommand.
 *
 * This function demonstrates the manual approach, sending a command to the client and processing the response.
 * Pagination must manually be managed. For a simplified approach that abstracts away pagination logic, see
 * the `listAgentsWithPaginator()` example below.
 *
 * @param {string} [region='us-east-1'] - The AWS region in use.
 * @returns {Promise<AgentSummary[]>} An array of agent summaries.
 */
export const listAgentsWithCommandObject = async (region = "us-east-1") => {
  const client = new BedrockAgentClient({ region });

  let nextToken;
  const agentSummaries = [];
  do {
    const command = new ListAgentsCommand({
      nextToken,
      maxResults: 10, // optional, added for demonstration purposes
    });

    /** @type {{agentSummaries: AgentSummary[], nextToken?: string}} */
    const paginatedResponse = await client.send(command);

    agentSummaries.push(...(paginatedResponse.agentSummaries || []));

    nextToken = paginatedResponse.nextToken;
  } while (nextToken);

  return agentSummaries;
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  console.log("=".repeat(68));
  console.log("Listing agents using ListAgentsCommand:");
  for (const agent of await listAgentsWithCommandObject()) {
    console.log(agent);
  }

  console.log("=".repeat(68));
  console.log("Listing agents using the paginateListAgents function:");
  for (const agent of await listAgentsWithPaginator()) {
    console.log(agent);
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListAgents](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent/command/ListAgentsCommand)」を参照してください。

# SDK for JavaScript (v3) を使用する Amazon Bedrock エージェントランタイムの例
<a name="javascript_3_bedrock-agent-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock エージェントランタイムで AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `InvokeAgent`
<a name="bedrock-agent-runtime_InvokeAgent_javascript_3_topic"></a>

次のコード例は、`InvokeAgent` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent-runtime#code-examples)での設定と実行の方法を確認してください。

```
import {
  BedrockAgentRuntimeClient,
  InvokeAgentCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";

/**
 * @typedef {Object} ResponseBody
 * @property {string} completion
 */

/**
 * Invokes a Bedrock agent to run an inference using the input
 * provided in the request body.
 *
 * @param {string} prompt - The prompt that you want the Agent to complete.
 * @param {string} sessionId - An arbitrary identifier for the session.
 */
export const invokeBedrockAgent = async (prompt, sessionId) => {
  const client = new BedrockAgentRuntimeClient({ region: "us-east-1" });
  // const client = new BedrockAgentRuntimeClient({
  //   region: "us-east-1",
  //   credentials: {
  //     accessKeyId: "accessKeyId", // permission to invoke agent
  //     secretAccessKey: "accessKeySecret",
  //   },
  // });

  const agentId = "AJBHXXILZN";
  const agentAliasId = "AVKP1ITZAA";

  const command = new InvokeAgentCommand({
    agentId,
    agentAliasId,
    sessionId,
    inputText: prompt,
  });

  try {
    let completion = "";
    const response = await client.send(command);

    if (response.completion === undefined) {
      throw new Error("Completion is undefined");
    }

    for await (const chunkEvent of response.completion) {
      const chunk = chunkEvent.chunk;
      console.log(chunk);
      const decodedResponse = new TextDecoder("utf-8").decode(chunk.bytes);
      completion += decodedResponse;
    }

    return { sessionId: sessionId, completion };
  } catch (err) {
    console.error(err);
  }
};

// Call function if run directly
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const result = await invokeBedrockAgent("I need help.", "123");
  console.log(result);
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[InvokeAgent](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent-runtime/command/InvokeAgentCommand)」を参照してください。

### `InvokeFlow`
<a name="bedrock-agent-runtime_InvokeFlow_javascript_3_topic"></a>

次のコード例は、`InvokeFlow` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/bedrock-agent-runtime#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";

import {
  BedrockAgentRuntimeClient,
  InvokeFlowCommand,
} from "@aws-sdk/client-bedrock-agent-runtime";

/**
 * Invokes an alias of a flow to run the inputs that you specify and return
 * the output of each node as a stream.
 *
 * @param {{
 *  flowIdentifier: string,
 *  flowAliasIdentifier: string,
 *  prompt?: string,
 *  region?: string
 * }} options
 * @returns {Promise<import("@aws-sdk/client-bedrock-agent").FlowNodeOutput>} An object containing information about the output from flow invocation.
 */
export const invokeBedrockFlow = async ({
  flowIdentifier,
  flowAliasIdentifier,
  prompt = "Hi, how are you?",
  region = "us-east-1",
}) => {
  const client = new BedrockAgentRuntimeClient({ region });

  const command = new InvokeFlowCommand({
    flowIdentifier,
    flowAliasIdentifier,
    inputs: [
      {
        content: {
          document: prompt,
        },
        nodeName: "FlowInputNode",
        nodeOutputName: "document",
      },
    ],
  });

  let flowResponse = {};
  const response = await client.send(command);

  for await (const chunkEvent of response.responseStream) {
    const { flowOutputEvent, flowCompletionEvent } = chunkEvent;

    if (flowOutputEvent) {
      flowResponse = { ...flowResponse, ...flowOutputEvent };
      console.log("Flow output event:", flowOutputEvent);
    } else if (flowCompletionEvent) {
      flowResponse = { ...flowResponse, ...flowCompletionEvent };
      console.log("Flow completion event:", flowCompletionEvent);
    }
  }

  return flowResponse;
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    flowIdentifier: {
      type: "string",
      required: true,
    },
    flowAliasIdentifier: {
      type: "string",
      required: true,
    },
    prompt: {
      type: "string",
    },
    region: {
      type: "string",
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    invokeBedrockFlow(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[InvokeFlow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/bedrock-agent-runtime/command/InvokeFlowCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した CloudWatch の例
<a name="javascript_3_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_javascript_3_topic"></a>

次のコード例は、`DeleteAlarms` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { DeleteAlarmsCommand } from "@aws-sdk/client-cloudwatch";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new DeleteAlarmsCommand({
    AlarmNames: [process.env.CLOUDWATCH_ALARM_NAME], // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm.
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch";

export const client = new CloudWatchClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-creating-alarms.html#cloudwatch-examples-creating-alarms-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteAlarms](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch/command/DeleteAlarmsCommand)」を参照してください。

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_javascript_3_topic"></a>

次のコード例は、`DescribeAlarmsForMetric` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { DescribeAlarmsCommand } from "@aws-sdk/client-cloudwatch";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new DescribeAlarmsCommand({
    AlarmNames: [process.env.CLOUDWATCH_ALARM_NAME], // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm.
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch";

export const client = new CloudWatchClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html#cloudwatch-examples-creating-alarms-describing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch/command/DescribeAlarmsForMetricCommand)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_javascript_3_topic"></a>

次のコード例は、`DisableAlarmActions` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { DisableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new DisableAlarmActionsCommand({
    AlarmNames: process.env.CLOUDWATCH_ALARM_NAME, // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm.
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch";

export const client = new CloudWatchClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-using-alarm-actions.html#cloudwatch-examples-using-alarm-actions-disabling)」を参照してください。
+  API 詳細については、*AWS SDK for JavaScript API リファレンス*の「[DisableAlarmActions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch/command/DisableAlarmActionsCommand)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_javascript_3_topic"></a>

次のコード例は、`EnableAlarmActions` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { EnableAlarmActionsCommand } from "@aws-sdk/client-cloudwatch";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new EnableAlarmActionsCommand({
    AlarmNames: [process.env.CLOUDWATCH_ALARM_NAME], // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm.
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch";

export const client = new CloudWatchClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-using-alarm-actions.html#cloudwatch-examples-using-alarm-actions-enabling)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[EnableAlarmActions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch/command/EnableAlarmActionsCommand)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_javascript_3_topic"></a>

次のコード例は、`ListMetrics` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import {
  CloudWatchServiceException,
  ListMetricsCommand,
} from "@aws-sdk/client-cloudwatch";
import { client } from "../libs/client.js";

export const main = async () => {
  // Use the AWS console to see available namespaces and metric names. Custom metrics can also be created.
  // https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/viewing_metrics_with_cloudwatch.html
  const command = new ListMetricsCommand({
    Dimensions: [
      {
        Name: "LogGroupName",
      },
    ],
    MetricName: "IncomingLogEvents",
    Namespace: "AWS/Logs",
  });

  try {
    const response = await client.send(command);
    console.log(`Metrics count: ${response.Metrics?.length}`);
    return response;
  } catch (caught) {
    if (caught instanceof CloudWatchServiceException) {
      console.error(`Error from CloudWatch. ${caught.name}: ${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch";

export const client = new CloudWatchClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-getting-metrics.html#cloudwatch-examples-getting-metrics-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListMetrics](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch/command/ListMetricsCommand)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_javascript_3_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { PutMetricAlarmCommand } from "@aws-sdk/client-cloudwatch";
import { client } from "../libs/client.js";

const run = async () => {
  // This alarm triggers when CPUUtilization exceeds 70% for one minute.
  const command = new PutMetricAlarmCommand({
    AlarmName: process.env.CLOUDWATCH_ALARM_NAME, // Set the value of CLOUDWATCH_ALARM_NAME to the name of an existing alarm.
    ComparisonOperator: "GreaterThanThreshold",
    EvaluationPeriods: 1,
    MetricName: "CPUUtilization",
    Namespace: "AWS/EC2",
    Period: 60,
    Statistic: "Average",
    Threshold: 70.0,
    ActionsEnabled: false,
    AlarmDescription: "Alarm when server CPU exceeds 70%",
    Dimensions: [
      {
        Name: "InstanceId",
        Value: process.env.EC2_INSTANCE_ID, // Set the value of EC_INSTANCE_ID to the Id of an existing Amazon EC2 instance.
      },
    ],
    Unit: "Percent",
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch";

export const client = new CloudWatchClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/cloudwatch-examples-creating-alarms.html#cloudwatch-examples-creating-alarms-putmetricalarm)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutMetricAlarm](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch/command/PutMetricAlarmCommand)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_javascript_3_topic"></a>

次のコード例は、`PutMetricData` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { PutMetricDataCommand } from "@aws-sdk/client-cloudwatch";
import { client } from "../libs/client.js";

const run = async () => {
  // See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricData.html#API_PutMetricData_RequestParameters
  // and https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/publishingMetrics.html
  // for more information about the parameters in this command.
  const command = new PutMetricDataCommand({
    MetricData: [
      {
        MetricName: "PAGES_VISITED",
        Dimensions: [
          {
            Name: "UNIQUE_PAGES",
            Value: "URLS",
          },
        ],
        Unit: "None",
        Value: 1.0,
      },
    ],
    Namespace: "SITE/TRAFFIC",
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchClient } from "@aws-sdk/client-cloudwatch";

export const client = new CloudWatchClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-getting-metrics.html#cloudwatch-examples-getting-metrics-publishing-custom)」を参照してください。
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[PutMetricData](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch/command/PutMetricDataCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した CloudWatch Events の例
<a name="javascript_3_cloudwatch-events_code_examples"></a>

次のコード例は、CloudWatch Events で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="cloudwatch-events_PutEvents_javascript_3_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-events#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { PutEventsCommand } from "@aws-sdk/client-cloudwatch-events";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new PutEventsCommand({
    // The list of events to send to Amazon CloudWatch Events.
    Entries: [
      {
        // The name of the application or service that is sending the event.
        Source: "my.app",

        // The name of the event that is being sent.
        DetailType: "My Custom Event",

        // The data that is sent with the event.
        Detail: JSON.stringify({ timeOfEvent: new Date().toISOString() }),
      },
    ],
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchEventsClient } from "@aws-sdk/client-cloudwatch-events";

export const client = new CloudWatchEventsClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-sending-events.html#cloudwatch-examples-sending-events-putevents)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-events/command/PutEventsCommand)」を参照してください。

### `PutRule`
<a name="cloudwatch-events_PutRule_javascript_3_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-events#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { PutRuleCommand } from "@aws-sdk/client-cloudwatch-events";
import { client } from "../libs/client.js";

const run = async () => {
  // Request parameters for PutRule.
  // https://docs.aws.amazon.com/eventbridge/latest/APIReference/API_PutRule.html#API_PutRule_RequestParameters
  const command = new PutRuleCommand({
    Name: process.env.CLOUDWATCH_EVENTS_RULE,

    // The event pattern for the rule.
    //  Example: {"source": ["my.app"]}
    EventPattern: process.env.CLOUDWATCH_EVENTS_RULE_PATTERN,

    // The state of the rule. Valid values: ENABLED, DISABLED
    State: "ENABLED",
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchEventsClient } from "@aws-sdk/client-cloudwatch-events";

export const client = new CloudWatchEventsClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-sending-events.html#cloudwatch-examples-sending-events-rules)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutRule](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-events/command/PutRuleCommand)」を参照してください。

### `PutTargets`
<a name="cloudwatch-events_PutTargets_javascript_3_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-events#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { PutTargetsCommand } from "@aws-sdk/client-cloudwatch-events";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new PutTargetsCommand({
    // The name of the Amazon CloudWatch Events rule.
    Rule: process.env.CLOUDWATCH_EVENTS_RULE,

    // The targets to add to the rule.
    Targets: [
      {
        Arn: process.env.CLOUDWATCH_EVENTS_TARGET_ARN,
        // The ID of the target. Choose a unique ID for each target.
        Id: process.env.CLOUDWATCH_EVENTS_TARGET_ID,
      },
    ],
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { CloudWatchEventsClient } from "@aws-sdk/client-cloudwatch-events";

export const client = new CloudWatchEventsClient({});
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cloudwatch-examples-sending-events.html#cloudwatch-examples-sending-events-targets)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-events/command/PutTargetsCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した CloudWatch Logs の例
<a name="javascript_3_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateLogGroup`
<a name="cloudwatch-logs_CreateLogGroup_javascript_3_topic"></a>

次のコード例は、`CreateLogGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import { CreateLogGroupCommand } from "@aws-sdk/client-cloudwatch-logs";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new CreateLogGroupCommand({
    // The name of the log group.
    logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP,
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateLogGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/CreateLogGroupCommand)」を参照してください。

### `DeleteLogGroup`
<a name="cloudwatch-logs_DeleteLogGroup_javascript_3_topic"></a>

次のコード例は、`DeleteLogGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteLogGroupCommand } from "@aws-sdk/client-cloudwatch-logs";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new DeleteLogGroupCommand({
    // The name of the log group.
    logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP,
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteLogGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/DeleteLogGroupCommand)」を参照してください。

### `DeleteSubscriptionFilter`
<a name="cloudwatch-logs_DeleteSubscriptionFilter_javascript_3_topic"></a>

次のコード例は、`DeleteSubscriptionFilter` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteSubscriptionFilterCommand } from "@aws-sdk/client-cloudwatch-logs";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new DeleteSubscriptionFilterCommand({
    // The name of the filter.
    filterName: process.env.CLOUDWATCH_LOGS_FILTER_NAME,
    // The name of the log group.
    logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP,
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteSubscriptionFilter](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/DeleteSubscriptionFilterCommand)」を参照してください。

### `DescribeLogGroups`
<a name="cloudwatch-logs_DescribeLogGroups_javascript_3_topic"></a>

次のコード例は、`DescribeLogGroups` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import {
  paginateDescribeLogGroups,
  CloudWatchLogsClient,
} from "@aws-sdk/client-cloudwatch-logs";

const client = new CloudWatchLogsClient({});

export const main = async () => {
  const paginatedLogGroups = paginateDescribeLogGroups({ client }, {});
  const logGroups = [];

  for await (const page of paginatedLogGroups) {
    if (page.logGroups?.every((lg) => !!lg)) {
      logGroups.push(...page.logGroups);
    }
  }

  console.log(logGroups);
  return logGroups;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeLogGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/DescribeLogGroupsCommand)」を参照してください。

### `DescribeSubscriptionFilters`
<a name="cloudwatch-logs_DescribeSubscriptionFilters_javascript_3_topic"></a>

次のコード例は、`DescribeSubscriptionFilters` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeSubscriptionFiltersCommand } from "@aws-sdk/client-cloudwatch-logs";
import { client } from "../libs/client.js";

const run = async () => {
  // This will return a list of all subscription filters in your account
  // matching the log group name.
  const command = new DescribeSubscriptionFiltersCommand({
    logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP,
    limit: 1,
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeSubscriptionFilters](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/DescribeSubscriptionFiltersCommand)」を参照してください。

### `GetQueryResults`
<a name="cloudwatch-logs_GetQueryResults_javascript_3_topic"></a>

次のコード例は、`GetQueryResults` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
  /**
   * Simple wrapper for the GetQueryResultsCommand.
   * @param {string} queryId
   */
  _getQueryResults(queryId) {
    return this.client.send(new GetQueryResultsCommand({ queryId }));
  }
```
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[GetQueryResults](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/GetQueryResultsCommand)」を参照してください。

### `PutSubscriptionFilter`
<a name="cloudwatch-logs_PutSubscriptionFilter_javascript_3_topic"></a>

次のコード例は、`PutSubscriptionFilter` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import { PutSubscriptionFilterCommand } from "@aws-sdk/client-cloudwatch-logs";
import { client } from "../libs/client.js";

const run = async () => {
  const command = new PutSubscriptionFilterCommand({
    // An ARN of a same-account Kinesis stream, Kinesis Firehose
    // delivery stream, or Lambda function.
    // https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html
    destinationArn: process.env.CLOUDWATCH_LOGS_DESTINATION_ARN,

    // A name for the filter.
    filterName: process.env.CLOUDWATCH_LOGS_FILTER_NAME,

    // A filter pattern for subscribing to a filtered stream of log events.
    // https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html
    filterPattern: process.env.CLOUDWATCH_LOGS_FILTER_PATTERN,

    // The name of the log group. Messages in this group matching the filter pattern
    // will be sent to the destination ARN.
    logGroupName: process.env.CLOUDWATCH_LOGS_LOG_GROUP,
  });

  try {
    return await client.send(command);
  } catch (err) {
    console.error(err);
  }
};

export default run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutSubscriptionFilter](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/PutSubscriptionFilterCommand)」を参照してください。

### `StartLiveTail`
<a name="cloudwatch-logs_StartLiveTail_javascript_3_topic"></a>

次のコード例は、`StartLiveTail` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
必要なファイルを含めます。  

```
import { CloudWatchLogsClient, StartLiveTailCommand } from "@aws-sdk/client-cloudwatch-logs";
```
Live Tail セッションのイベントを処理します。  

```
async function handleResponseAsync(response) {
    try {
      for await (const event of response.responseStream) {
        if (event.sessionStart !== undefined) {
          console.log(event.sessionStart);
        } else if (event.sessionUpdate !== undefined) {
          for (const logEvent of event.sessionUpdate.sessionResults) {
            const timestamp = logEvent.timestamp;
            const date = new Date(timestamp);
            console.log("[" + date + "] " + logEvent.message);
          } 
        } else {
            console.error("Unknown event type");
        }
      }
    } catch (err) {  
        // On-stream exceptions are captured here
        console.error(err)
    }
}
```
Live Tail セッションを開始します。  

```
    const client = new CloudWatchLogsClient();

    const command = new StartLiveTailCommand({
        logGroupIdentifiers: logGroupIdentifiers,
        logStreamNames: logStreamNames,
        logEventFilterPattern: filterPattern
    });
    try{
        const response = await client.send(command);
        handleResponseAsync(response);
    } catch (err){
        // Pre-stream exceptions are captured here
        console.log(err);
    }
```
一定時間が経過したら Live Tail セッションを停止します。  

```
    /* Set a timeout to close the client. This will stop the Live Tail session. */
    setTimeout(function() {
        console.log("Client timeout");
        client.destroy();
      }, 10000);
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[StartLiveTail](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/StartLiveTailCommand)」を参照してください。

### `StartQuery`
<a name="cloudwatch-logs_StartQuery_javascript_3_topic"></a>

次のコード例は、`StartQuery` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
  /**
   * Wrapper for the StartQueryCommand. Uses a static query string
   * for consistency.
   * @param {[Date, Date]} dateRange
   * @param {number} maxLogs
   * @returns {Promise<{ queryId: string }>}
   */
  async _startQuery([startDate, endDate], maxLogs = 10000) {
    try {
      return await this.client.send(
        new StartQueryCommand({
          logGroupNames: this.logGroupNames,
          queryString: "fields @timestamp, @message | sort @timestamp asc",
          startTime: startDate.valueOf(),
          endTime: endDate.valueOf(),
          limit: maxLogs,
        }),
      );
    } catch (err) {
      /** @type {string} */
      const message = err.message;
      if (message.startsWith("Query's end date and time")) {
        // This error indicates that the query's start or end date occur
        // before the log group was created.
        throw new DateOutOfBoundsError(message);
      }

      throw err;
    }
  }
```
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[StartQuery](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/StartQueryCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 大規模なクエリを実行する
<a name="cloudwatch-logs_Scenario_BigQuery_javascript_3_topic"></a>

次のコード例は、CloudWatch Logs を使用して 10,000 を超えるレコードをクエリする方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cloudwatch-logs/scenarios/large-query#code-examples)での設定と実行の方法を確認してください。
これはエントリポイントです。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { CloudWatchLogsClient } from "@aws-sdk/client-cloudwatch-logs";
import { CloudWatchQuery } from "./cloud-watch-query.js";

console.log("Starting a recursive query...");

if (!process.env.QUERY_START_DATE || !process.env.QUERY_END_DATE) {
  throw new Error(
    "QUERY_START_DATE and QUERY_END_DATE environment variables are required.",
  );
}

const cloudWatchQuery = new CloudWatchQuery(new CloudWatchLogsClient({}), {
  logGroupNames: ["/workflows/cloudwatch-logs/large-query"],
  dateRange: [
    new Date(Number.parseInt(process.env.QUERY_START_DATE)),
    new Date(Number.parseInt(process.env.QUERY_END_DATE)),
  ],
});

await cloudWatchQuery.run();

console.log(
  `Queries finished in ${cloudWatchQuery.secondsElapsed} seconds.\nTotal logs found: ${cloudWatchQuery.results.length}`,
);
```
これは、必要に応じてクエリを複数のステップに分割するクラスです。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
  StartQueryCommand,
  GetQueryResultsCommand,
} from "@aws-sdk/client-cloudwatch-logs";
import { splitDateRange } from "@aws-doc-sdk-examples/lib/utils/util-date.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

class DateOutOfBoundsError extends Error {}

export class CloudWatchQuery {
  /**
   * Run a query for all CloudWatch Logs within a certain date range.
   * CloudWatch logs return a max of 10,000 results. This class
   * performs a binary search across all of the logs in the provided
   * date range if a query returns the maximum number of results.
   *
   * @param {import('@aws-sdk/client-cloudwatch-logs').CloudWatchLogsClient} client
   * @param {{ logGroupNames: string[], dateRange: [Date, Date], queryConfig: { limit: number } }} config
   */
  constructor(client, { logGroupNames, dateRange, queryConfig }) {
    this.client = client;
    /**
     * All log groups are queried.
     */
    this.logGroupNames = logGroupNames;

    /**
     * The inclusive date range that is queried.
     */
    this.dateRange = dateRange;

    /**
     * CloudWatch Logs never returns more than 10,000 logs.
     */
    this.limit = queryConfig?.limit ?? 10000;

    /**
     * @type {import("@aws-sdk/client-cloudwatch-logs").ResultField[][]}
     */
    this.results = [];
  }

  /**
   * Run the query.
   */
  async run() {
    this.secondsElapsed = 0;
    const start = new Date();
    this.results = await this._largeQuery(this.dateRange);
    const end = new Date();
    this.secondsElapsed = (end - start) / 1000;
    return this.results;
  }

  /**
   * Recursively query for logs.
   * @param {[Date, Date]} dateRange
   * @returns {Promise<import("@aws-sdk/client-cloudwatch-logs").ResultField[][]>}
   */
  async _largeQuery(dateRange) {
    const logs = await this._query(dateRange, this.limit);

    console.log(
      `Query date range: ${dateRange
        .map((d) => d.toISOString())
        .join(" to ")}. Found ${logs.length} logs.`,
    );

    if (logs.length < this.limit) {
      return logs;
    }

    const lastLogDate = this._getLastLogDate(logs);
    const offsetLastLogDate = new Date(lastLogDate);
    offsetLastLogDate.setMilliseconds(lastLogDate.getMilliseconds() + 1);
    const subDateRange = [offsetLastLogDate, dateRange[1]];
    const [r1, r2] = splitDateRange(subDateRange);
    const results = await Promise.all([
      this._largeQuery(r1),
      this._largeQuery(r2),
    ]);
    return [logs, ...results].flat();
  }

  /**
   * Find the most recent log in a list of logs.
   * @param {import("@aws-sdk/client-cloudwatch-logs").ResultField[][]} logs
   */
  _getLastLogDate(logs) {
    const timestamps = logs
      .map(
        (log) =>
          log.find((fieldMeta) => fieldMeta.field === "@timestamp")?.value,
      )
      .filter((t) => !!t)
      .map((t) => `${t}Z`)
      .sort();

    if (!timestamps.length) {
      throw new Error("No timestamp found in logs.");
    }

    return new Date(timestamps[timestamps.length - 1]);
  }

  /**
   * Simple wrapper for the GetQueryResultsCommand.
   * @param {string} queryId
   */
  _getQueryResults(queryId) {
    return this.client.send(new GetQueryResultsCommand({ queryId }));
  }

  /**
   * Starts a query and waits for it to complete.
   * @param {[Date, Date]} dateRange
   * @param {number} maxLogs
   */
  async _query(dateRange, maxLogs) {
    try {
      const { queryId } = await this._startQuery(dateRange, maxLogs);
      const { results } = await this._waitUntilQueryDone(queryId);
      return results ?? [];
    } catch (err) {
      /**
       * This error is thrown when StartQuery returns an error indicating
       * that the query's start or end date occur before the log group was
       * created.
       */
      if (err instanceof DateOutOfBoundsError) {
        return [];
      }
      throw err;
    }
  }

  /**
   * Wrapper for the StartQueryCommand. Uses a static query string
   * for consistency.
   * @param {[Date, Date]} dateRange
   * @param {number} maxLogs
   * @returns {Promise<{ queryId: string }>}
   */
  async _startQuery([startDate, endDate], maxLogs = 10000) {
    try {
      return await this.client.send(
        new StartQueryCommand({
          logGroupNames: this.logGroupNames,
          queryString: "fields @timestamp, @message | sort @timestamp asc",
          startTime: startDate.valueOf(),
          endTime: endDate.valueOf(),
          limit: maxLogs,
        }),
      );
    } catch (err) {
      /** @type {string} */
      const message = err.message;
      if (message.startsWith("Query's end date and time")) {
        // This error indicates that the query's start or end date occur
        // before the log group was created.
        throw new DateOutOfBoundsError(message);
      }

      throw err;
    }
  }

  /**
   * Call GetQueryResultsCommand until the query is done.
   * @param {string} queryId
   */
  _waitUntilQueryDone(queryId) {
    const getResults = async () => {
      const results = await this._getQueryResults(queryId);
      const queryDone = [
        "Complete",
        "Failed",
        "Cancelled",
        "Timeout",
        "Unknown",
      ].includes(results.status);

      return { queryDone, results };
    };

    return retry(
      { intervalInMs: 1000, maxRetries: 60, quiet: true },
      async () => {
        const { queryDone, results } = await getResults();
        if (!queryDone) {
          throw new Error("Query not done.");
        }

        return results;
      },
    );
  }
}
```
+ API の詳細については、「AWS SDK for JavaScript API リファレンス**」の以下のトピックを参照してください。
  + [GetQueryResults](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/GetQueryResultsCommand)
  + [StartQuery](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cloudwatch-logs/command/StartQueryCommand)

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_javascript_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda JavaScript ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

# SDK for JavaScript (v3) を使用した CodeBuild の例
<a name="javascript_3_codebuild_code_examples"></a>

次のコード例は、CodeBuild で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateProject`
<a name="codebuild_CreateProject_javascript_3_topic"></a>

次のコード例は、`CreateProject` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/codebuild#code-examples)での設定と実行の方法を確認してください。
プロジェクトを作成します。  

```
import {
  ArtifactsType,
  CodeBuildClient,
  ComputeType,
  CreateProjectCommand,
  EnvironmentType,
  SourceType,
} from "@aws-sdk/client-codebuild";

// Create the AWS CodeBuild project.
export const createProject = async (
  projectName = "MyCodeBuilder",
  roleArn = "arn:aws:iam::xxxxxxxxxxxx:role/CodeBuildAdmin",
  buildOutputBucket = "xxxx",
  githubUrl = "https://...",
) => {
  const codeBuildClient = new CodeBuildClient({});

  const response = await codeBuildClient.send(
    new CreateProjectCommand({
      artifacts: {
        // The destination of the build artifacts.
        type: ArtifactsType.S3,
        location: buildOutputBucket,
      },
      // Information about the build environment. The combination of "computeType" and "type" determines the
      // requirements for the environment such as CPU, memory, and disk space.
      environment: {
        // Build environment compute types.
        // https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html
        computeType: ComputeType.BUILD_GENERAL1_SMALL,
        // Docker image identifier.
        // See https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-available.html
        image: "aws/codebuild/standard:7.0",
        // Build environment type.
        type: EnvironmentType.LINUX_CONTAINER,
      },
      name: projectName,
      // A role ARN with permission to create a CodeBuild project, write to the artifact location, and write CloudWatch logs.
      serviceRole: roleArn,
      source: {
        // The type of repository that contains the source code to be built.
        type: SourceType.GITHUB,
        // The location of the repository that contains the source code to be built.
        location: githubUrl,
      },
    }),
  );
  console.log(response);
  //   {
  //     '$metadata': {
  //       httpStatusCode: 200,
  //       requestId: 'b428b244-777b-49a6-a48d-5dffedced8e7',
  //       extendedRequestId: undefined,
  //       cfId: undefined,
  //       attempts: 1,
  //       totalRetryDelay: 0
  //     },
  //     project: {
  //       arn: 'arn:aws:codebuild:us-east-1:xxxxxxxxxxxx:project/MyCodeBuilder',
  //       artifacts: {
  //         encryptionDisabled: false,
  //         location: 'xxxxxx-xxxxxxx-xxxxxx',
  //         name: 'MyCodeBuilder',
  //         namespaceType: 'NONE',
  //         packaging: 'NONE',
  //         type: 'S3'
  //       },
  //       badge: { badgeEnabled: false },
  //       cache: { type: 'NO_CACHE' },
  //       created: 2023-08-18T14:46:48.979Z,
  //       encryptionKey: 'arn:aws:kms:us-east-1:xxxxxxxxxxxx:alias/aws/s3',
  //       environment: {
  //         computeType: 'BUILD_GENERAL1_SMALL',
  //         environmentVariables: [],
  //         image: 'aws/codebuild/standard:7.0',
  //         imagePullCredentialsType: 'CODEBUILD',
  //         privilegedMode: false,
  //         type: 'LINUX_CONTAINER'
  //       },
  //       lastModified: 2023-08-18T14:46:48.979Z,
  //       name: 'MyCodeBuilder',
  //       projectVisibility: 'PRIVATE',
  //       queuedTimeoutInMinutes: 480,
  //       serviceRole: 'arn:aws:iam::xxxxxxxxxxxx:role/CodeBuildAdmin',
  //       source: {
  //         insecureSsl: false,
  //         location: 'https://...',
  //         reportBuildStatus: false,
  //         type: 'GITHUB'
  //       },
  //       timeoutInMinutes: 60
  //     }
  //   }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/codebuild/)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateProject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/codebuild/command/CreateProjectCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon Cognito ID の例
<a name="javascript_3_cognito-identity_code_examples"></a>

次のコード例は、Amazon Cognito Identity で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_javascript_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for JavaScript (v3)**  
 を使用して、Amazon Textract を使用してドキュメントイメージからデータを抽出し、インタラクティブなウェブページに表示する React アプリケーション AWS SDK for JavaScript を構築する方法を示します。この例はウェブブラウザで実行され、認証情報に認証された Amazon Cognito ID が必要です。Amazon Simple Storage Service (Amazon S3) をストレージに使用し、通知のために、Amazon Simple Notification Service (Amazon SNS) トピックにサブスクライブした Amazon Simple Queue Service (Amazon SQS) キューをポーリングします。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/textract-react) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

# SDK for JavaScript (v3) を使用した Amazon Cognito ID プロバイダーの例
<a name="javascript_3_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Cognito
<a name="cognito-identity-provider_Hello_javascript_3_topic"></a>

次のコード例は、Amazon Cognito の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import {
  paginateListUserPools,
  CognitoIdentityProviderClient,
} from "@aws-sdk/client-cognito-identity-provider";

const client = new CognitoIdentityProviderClient({});

export const helloCognito = async () => {
  const paginator = paginateListUserPools({ client }, {});

  const userPoolNames = [];

  for await (const page of paginator) {
    const names = page.UserPools.map((pool) => pool.Name);
    userPoolNames.push(...names);
  }

  console.log("User pool names: ");
  console.log(userPoolNames.join("\n"));
  return userPoolNames;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListUserPools](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ListUserPoolsCommand)」を参照してください。

## アクション
<a name="actions"></a>

### `AdminGetUser`
<a name="cognito-identity-provider_AdminGetUser_javascript_3_topic"></a>

次のコード例は、`AdminGetUser` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider/#code-examples)での設定と実行の方法を確認してください。

```
const adminGetUser = ({ userPoolId, username }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new AdminGetUserCommand({
    UserPoolId: userPoolId,
    Username: username,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AdminGetUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AdminGetUserCommand)」を参照してください。

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_javascript_3_topic"></a>

次のコード例は、`AdminInitiateAuth` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider/#code-examples)での設定と実行の方法を確認してください。

```
const adminInitiateAuth = ({ clientId, userPoolId, username, password }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new AdminInitiateAuthCommand({
    ClientId: clientId,
    UserPoolId: userPoolId,
    AuthFlow: AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
    AuthParameters: { USERNAME: username, PASSWORD: password },
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AdminInitiateAuth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AdminInitiateAuthCommand)」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_javascript_3_topic"></a>

次のコード例は、`AdminRespondToAuthChallenge` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const adminRespondToAuthChallenge = ({
  userPoolId,
  clientId,
  username,
  totp,
  session,
}) => {
  const client = new CognitoIdentityProviderClient({});
  const command = new AdminRespondToAuthChallengeCommand({
    ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA,
    ChallengeResponses: {
      SOFTWARE_TOKEN_MFA_CODE: totp,
      USERNAME: username,
    },
    ClientId: clientId,
    UserPoolId: userPoolId,
    Session: session,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AdminRespondToAuthChallengeCommand)」を参照してください。

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_javascript_3_topic"></a>

次のコード例は、`AssociateSoftwareToken` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const associateSoftwareToken = (session) => {
  const client = new CognitoIdentityProviderClient({});
  const command = new AssociateSoftwareTokenCommand({
    Session: session,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AssociateSoftwareToken](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AssociateSoftwareTokenCommand)」を参照してください。

### `ConfirmDevice`
<a name="cognito-identity-provider_ConfirmDevice_javascript_3_topic"></a>

次のコード例は、`ConfirmDevice` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const confirmDevice = ({ deviceKey, accessToken, passwordVerifier, salt }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new ConfirmDeviceCommand({
    DeviceKey: deviceKey,
    AccessToken: accessToken,
    DeviceSecretVerifierConfig: {
      PasswordVerifier: passwordVerifier,
      Salt: salt,
    },
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ConfirmDevice](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ConfirmDeviceCommand)」を参照してください。

### `ConfirmSignUp`
<a name="cognito-identity-provider_ConfirmSignUp_javascript_3_topic"></a>

次のコード例は、`ConfirmSignUp` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const confirmSignUp = ({ clientId, username, code }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new ConfirmSignUpCommand({
    ClientId: clientId,
    Username: username,
    ConfirmationCode: code,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ConfirmSignUp](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ConfirmSignUpCommand)」を参照してください。

### `DeleteUser`
<a name="cognito-identity-provider_DeleteUser_javascript_3_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-pools-triggers#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Delete the signed-in user. Useful for allowing a user to delete their
 * own profile.
 * @param {{ region: string, accessToken: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").DeleteUserCommandOutput | null, unknown]>}
 */
export const deleteUser = async ({ region, accessToken }) => {
  try {
    const client = new CognitoIdentityProviderClient({ region });
    const response = await client.send(
      new DeleteUserCommand({ AccessToken: accessToken }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/DeleteUserCommand)」を参照してください。

### `InitiateAuth`
<a name="cognito-identity-provider_InitiateAuth_javascript_3_topic"></a>

次のコード例は、`InitiateAuth` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const initiateAuth = ({ username, password, clientId }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new InitiateAuthCommand({
    AuthFlow: AuthFlowType.USER_PASSWORD_AUTH,
    AuthParameters: {
      USERNAME: username,
      PASSWORD: password,
    },
    ClientId: clientId,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[InitiateAuth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/InitiateAuthCommand)」を参照してください。

### `ListUsers`
<a name="cognito-identity-provider_ListUsers_javascript_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const listUsers = ({ userPoolId }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new ListUsersCommand({
    UserPoolId: userPoolId,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ListUsersCommand)」を参照してください。

### `ResendConfirmationCode`
<a name="cognito-identity-provider_ResendConfirmationCode_javascript_3_topic"></a>

次のコード例は、`ResendConfirmationCode` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const resendConfirmationCode = ({ clientId, username }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new ResendConfirmationCodeCommand({
    ClientId: clientId,
    Username: username,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ResendConfirmationCode](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ResendConfirmationCodeCommand)」を参照してください。

### `RespondToAuthChallenge`
<a name="cognito-identity-provider_RespondToAuthChallenge_javascript_3_topic"></a>

次のコード例は、`RespondToAuthChallenge` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const respondToAuthChallenge = ({
  clientId,
  username,
  session,
  userPoolId,
  code,
}) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new RespondToAuthChallengeCommand({
    ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA,
    ChallengeResponses: {
      SOFTWARE_TOKEN_MFA_CODE: code,
      USERNAME: username,
    },
    ClientId: clientId,
    UserPoolId: userPoolId,
    Session: session,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[RespondToAuthChallenge](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/RespondToAuthChallengeCommand)」を参照してください。

### `SignUp`
<a name="cognito-identity-provider_SignUp_javascript_3_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const signUp = ({ clientId, username, password, email }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new SignUpCommand({
    ClientId: clientId,
    Username: username,
    Password: password,
    UserAttributes: [{ Name: "email", Value: email }],
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SignUp](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/SignUpCommand)」を参照してください。

### `UpdateUserPool`
<a name="cognito-identity-provider_UpdateUserPool_javascript_3_topic"></a>

次のコード例は、`UpdateUserPool` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-pools-triggers#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Connect a Lambda function to the PreSignUp trigger for a Cognito user pool
 * @param {{ region: string, userPoolId: string, handlerArn: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").UpdateUserPoolCommandOutput | null, unknown]>}
 */
export const addPreSignUpHandler = async ({
  region,
  userPoolId,
  handlerArn,
}) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({
      region,
    });

    const command = new UpdateUserPoolCommand({
      UserPoolId: userPoolId,
      LambdaConfig: {
        PreSignUp: handlerArn,
      },
    });

    const response = await cognitoClient.send(command);
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[UpdateUserPool](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/UpdateUserPoolCommand)」を参照してください。

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_javascript_3_topic"></a>

次のコード例は、`VerifySoftwareToken` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
const verifySoftwareToken = (totp) => {
  const client = new CognitoIdentityProviderClient({});

  // The 'Session' is provided in the response to 'AssociateSoftwareToken'.
  const session = process.env.SESSION;

  if (!session) {
    throw new Error(
      "Missing a valid Session. Did you run 'admin-initiate-auth'?",
    );
  }

  const command = new VerifySoftwareTokenCommand({
    Session: session,
    UserCode: totp,
  });

  return client.send(command);
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[VerifySoftwareToken](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/VerifySoftwareTokenCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Lambda 関数を使用して登録済みのユーザーを自動的に確認する
<a name="cross_CognitoAutoConfirmUser_javascript_3_topic"></a>

次のコード例は、Lambda 関数を使用して登録済みの Amazon Cognito ユーザーを自動的に確認する方法を示しています。
+ `PreSignUp` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ Amazon Cognito でユーザーをサインアップする
+ Lambda 関数は DynamoDB テーブルをスキャンし、登録済みのユーザーを自動的に確認します。
+ 新しいユーザーとしてサインインし、リソースをクリーンアップします。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-pools-triggers#code-examples)での設定と実行の方法を確認してください。
インタラクティブな「シナリオ」実行を設定します。JavaScript (v3) の例では、シナリオランナーを共有して、複雑な例を効率化します。完全なソースコードは GitHub にあります。  

```
import { AutoConfirm } from "./scenario-auto-confirm.js";

/**
 * The context is passed to every scenario. Scenario steps
 * will modify the context.
 */
const context = {
  errors: [],
  users: [
    {
      UserName: "test_user_1",
      UserEmail: "test_email_1@example.com",
    },
    {
      UserName: "test_user_2",
      UserEmail: "test_email_2@example.com",
    },
    {
      UserName: "test_user_3",
      UserEmail: "test_email_3@example.com",
    },
  ],
};

/**
 * Three Scenarios are created for the workflow. A Scenario is an orchestration class
 * that simplifies running a series of steps.
 */
export const scenarios = {
  // Demonstrate automatically confirming known users in a database.
  "auto-confirm": AutoConfirm(context),
};

// Call function if run directly
import { fileURLToPath } from "node:url";
import { parseScenarioArgs } from "@aws-doc-sdk-examples/lib/scenario/index.js";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  parseScenarioArgs(scenarios, {
    name: "Cognito user pools and triggers",
    description:
      "Demonstrate how to use the AWS SDKs to customize Amazon Cognito authentication behavior.",
  });
}
```
このシナリオでは、既知のユーザーを自動確認する方法を示します。サンプルのステップをオーケストレーションします。  

```
import { wait } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";

import {
  getStackOutputs,
  logCleanUpReminder,
  promptForStackName,
  promptForStackRegion,
  skipWhenErrors,
} from "./steps-common.js";
import { populateTable } from "./actions/dynamodb-actions.js";
import {
  addPreSignUpHandler,
  deleteUser,
  getUser,
  signIn,
  signUpUser,
} from "./actions/cognito-actions.js";
import {
  getLatestLogStreamForLambda,
  getLogEvents,
} from "./actions/cloudwatch-logs-actions.js";

/**
 * @typedef {{
 *   errors: Error[],
 *   password: string,
 *   users: { UserName: string, UserEmail: string }[],
 *   selectedUser?: string,
 *   stackName?: string,
 *   stackRegion?: string,
 *   token?: string,
 *   confirmDeleteSignedInUser?: boolean,
 *   TableName?: string,
 *   UserPoolClientId?: string,
 *   UserPoolId?: string,
 *   UserPoolArn?: string,
 *   AutoConfirmHandlerArn?: string,
 *   AutoConfirmHandlerName?: string
 * }} State
 */

const greeting = new ScenarioOutput(
  "greeting",
  (/** @type {State} */ state) => `This demo will populate some users into the \
database created as part of the "${state.stackName}" stack. \
Then the AutoConfirmHandler will be linked to the PreSignUp \
trigger from Cognito. Finally, you will choose a user to sign up.`,
  { skipWhen: skipWhenErrors },
);

const logPopulatingUsers = new ScenarioOutput(
  "logPopulatingUsers",
  "Populating the DynamoDB table with some users.",
  { skipWhenErrors: skipWhenErrors },
);

const logPopulatingUsersComplete = new ScenarioOutput(
  "logPopulatingUsersComplete",
  "Done populating users.",
  { skipWhen: skipWhenErrors },
);

const populateUsers = new ScenarioAction(
  "populateUsers",
  async (/** @type {State} */ state) => {
    const [_, err] = await populateTable({
      region: state.stackRegion,
      tableName: state.TableName,
      items: state.users,
    });
    if (err) {
      state.errors.push(err);
    }
  },
  {
    skipWhen: skipWhenErrors,
  },
);

const logSetupSignUpTrigger = new ScenarioOutput(
  "logSetupSignUpTrigger",
  "Setting up the PreSignUp trigger for the Cognito User Pool.",
  { skipWhen: skipWhenErrors },
);

const setupSignUpTrigger = new ScenarioAction(
  "setupSignUpTrigger",
  async (/** @type {State} */ state) => {
    const [_, err] = await addPreSignUpHandler({
      region: state.stackRegion,
      userPoolId: state.UserPoolId,
      handlerArn: state.AutoConfirmHandlerArn,
    });
    if (err) {
      state.errors.push(err);
    }
  },
  {
    skipWhen: skipWhenErrors,
  },
);

const logSetupSignUpTriggerComplete = new ScenarioOutput(
  "logSetupSignUpTriggerComplete",
  (
    /** @type {State} */ state,
  ) => `The lambda function "${state.AutoConfirmHandlerName}" \
has been configured as the PreSignUp trigger handler for the user pool "${state.UserPoolId}".`,
  { skipWhen: skipWhenErrors },
);

const selectUser = new ScenarioInput(
  "selectedUser",
  "Select a user to sign up.",
  {
    type: "select",
    choices: (/** @type {State} */ state) => state.users.map((u) => u.UserName),
    skipWhen: skipWhenErrors,
    default: (/** @type {State} */ state) => state.users[0].UserName,
  },
);

const checkIfUserAlreadyExists = new ScenarioAction(
  "checkIfUserAlreadyExists",
  async (/** @type {State} */ state) => {
    const [user, err] = await getUser({
      region: state.stackRegion,
      userPoolId: state.UserPoolId,
      username: state.selectedUser,
    });

    if (err?.name === "UserNotFoundException") {
      // Do nothing. We're not expecting the user to exist before
      // sign up is complete.
      return;
    }

    if (err) {
      state.errors.push(err);
      return;
    }

    if (user) {
      state.errors.push(
        new Error(
          `The user "${state.selectedUser}" already exists in the user pool "${state.UserPoolId}".`,
        ),
      );
    }
  },
  {
    skipWhen: skipWhenErrors,
  },
);

const createPassword = new ScenarioInput(
  "password",
  "Enter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.",
  { type: "password", skipWhen: skipWhenErrors, default: "Abcd1234!" },
);

const logSignUpExistingUser = new ScenarioOutput(
  "logSignUpExistingUser",
  (/** @type {State} */ state) => `Signing up user "${state.selectedUser}".`,
  { skipWhen: skipWhenErrors },
);

const signUpExistingUser = new ScenarioAction(
  "signUpExistingUser",
  async (/** @type {State} */ state) => {
    const signUp = (password) =>
      signUpUser({
        region: state.stackRegion,
        userPoolClientId: state.UserPoolClientId,
        username: state.selectedUser,
        email: state.users.find((u) => u.UserName === state.selectedUser)
          .UserEmail,
        password,
      });

    let [_, err] = await signUp(state.password);

    while (err?.name === "InvalidPasswordException") {
      console.warn("The password you entered was invalid.");
      await createPassword.handle(state);
      [_, err] = await signUp(state.password);
    }

    if (err) {
      state.errors.push(err);
    }
  },
  { skipWhen: skipWhenErrors },
);

const logSignUpExistingUserComplete = new ScenarioOutput(
  "logSignUpExistingUserComplete",
  (/** @type {State} */ state) =>
    `"${state.selectedUser} was signed up successfully.`,
  { skipWhen: skipWhenErrors },
);

const logLambdaLogs = new ScenarioAction(
  "logLambdaLogs",
  async (/** @type {State} */ state) => {
    console.log(
      "Waiting a few seconds to let Lambda write to CloudWatch Logs...\n",
    );
    await wait(10);

    const [logStream, logStreamErr] = await getLatestLogStreamForLambda({
      functionName: state.AutoConfirmHandlerName,
      region: state.stackRegion,
    });
    if (logStreamErr) {
      state.errors.push(logStreamErr);
      return;
    }

    console.log(
      `Getting some recent events from log stream "${logStream.logStreamName}"`,
    );
    const [logEvents, logEventsErr] = await getLogEvents({
      functionName: state.AutoConfirmHandlerName,
      region: state.stackRegion,
      eventCount: 10,
      logStreamName: logStream.logStreamName,
    });
    if (logEventsErr) {
      state.errors.push(logEventsErr);
      return;
    }

    console.log(logEvents.map((ev) => `\t${ev.message}`).join(""));
  },
  { skipWhen: skipWhenErrors },
);

const logSignInUser = new ScenarioOutput(
  "logSignInUser",
  (/** @type {State} */ state) => `Let's sign in as ${state.selectedUser}`,
  { skipWhen: skipWhenErrors },
);

const signInUser = new ScenarioAction(
  "signInUser",
  async (/** @type {State} */ state) => {
    const [response, err] = await signIn({
      region: state.stackRegion,
      clientId: state.UserPoolClientId,
      username: state.selectedUser,
      password: state.password,
    });

    if (err?.name === "PasswordResetRequiredException") {
      state.errors.push(new Error("Please reset your password."));
      return;
    }

    if (err) {
      state.errors.push(err);
      return;
    }

    state.token = response?.AuthenticationResult?.AccessToken;
  },
  { skipWhen: skipWhenErrors },
);

const logSignInUserComplete = new ScenarioOutput(
  "logSignInUserComplete",
  (/** @type {State} */ state) =>
    `Successfully signed in. Your access token starts with: ${state.token.slice(0, 11)}`,
  { skipWhen: skipWhenErrors },
);

const confirmDeleteSignedInUser = new ScenarioInput(
  "confirmDeleteSignedInUser",
  "Do you want to delete the currently signed in user?",
  { type: "confirm", skipWhen: skipWhenErrors },
);

const deleteSignedInUser = new ScenarioAction(
  "deleteSignedInUser",
  async (/** @type {State} */ state) => {
    const [_, err] = await deleteUser({
      region: state.stackRegion,
      accessToken: state.token,
    });

    if (err) {
      state.errors.push(err);
    }
  },
  {
    skipWhen: (/** @type {State} */ state) =>
      skipWhenErrors(state) || !state.confirmDeleteSignedInUser,
  },
);

const logErrors = new ScenarioOutput(
  "logErrors",
  (/** @type {State}*/ state) => {
    const errorList = state.errors
      .map((err) => ` - ${err.name}: ${err.message}`)
      .join("\n");
    return `Scenario errors found:\n${errorList}`;
  },
  {
    // Don't log errors when there aren't any!
    skipWhen: (/** @type {State} */ state) => state.errors.length === 0,
  },
);

export const AutoConfirm = (context) =>
  new Scenario(
    "AutoConfirm",
    [
      promptForStackName,
      promptForStackRegion,
      getStackOutputs,
      greeting,
      logPopulatingUsers,
      populateUsers,
      logPopulatingUsersComplete,
      logSetupSignUpTrigger,
      setupSignUpTrigger,
      logSetupSignUpTriggerComplete,
      selectUser,
      checkIfUserAlreadyExists,
      createPassword,
      logSignUpExistingUser,
      signUpExistingUser,
      logSignUpExistingUserComplete,
      logLambdaLogs,
      logSignInUser,
      signInUser,
      logSignInUserComplete,
      confirmDeleteSignedInUser,
      deleteSignedInUser,
      logCleanUpReminder,
      logErrors,
    ],
    context,
  );
```
これらは、他のシナリオと共有されるステップです。  

```
import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";
import { getCfnOutputs } from "@aws-doc-sdk-examples/lib/sdk/cfn-outputs.js";

export const skipWhenErrors = (state) => state.errors.length > 0;

export const getStackOutputs = new ScenarioAction(
  "getStackOutputs",
  async (state) => {
    if (!state.stackName || !state.stackRegion) {
      state.errors.push(
        new Error(
          "No stack name or region provided. The stack name and \
region are required to fetch CFN outputs relevant to this example.",
        ),
      );
      return;
    }

    const outputs = await getCfnOutputs(state.stackName, state.stackRegion);
    Object.assign(state, outputs);
  },
);

export const promptForStackName = new ScenarioInput(
  "stackName",
  "Enter the name of the stack you deployed earlier.",
  { type: "input", default: "PoolsAndTriggersStack" },
);

export const promptForStackRegion = new ScenarioInput(
  "stackRegion",
  "Enter the region of the stack you deployed earlier.",
  { type: "input", default: "us-east-1" },
);

export const logCleanUpReminder = new ScenarioOutput(
  "logCleanUpReminder",
  "All done. Remember to run 'cdk destroy' to teardown the stack.",
  { skipWhen: skipWhenErrors },
);
```
Lambda 関数を使用する `PreSignUp` トリガーのハンドラー。  

```
import type { PreSignUpTriggerEvent, Handler } from "aws-lambda";
import type { UserRepository } from "./user-repository";
import { DynamoDBUserRepository } from "./user-repository";

export class PreSignUpHandler {
  private userRepository: UserRepository;

  constructor(userRepository: UserRepository) {
    this.userRepository = userRepository;
  }

  private isPreSignUpTriggerSource(event: PreSignUpTriggerEvent): boolean {
    return event.triggerSource === "PreSignUp_SignUp";
  }

  private getEventUserEmail(event: PreSignUpTriggerEvent): string {
    return event.request.userAttributes.email;
  }

  async handlePreSignUpTriggerEvent(
    event: PreSignUpTriggerEvent,
  ): Promise<PreSignUpTriggerEvent> {
    console.log(
      `Received presignup from ${event.triggerSource} for user '${event.userName}'`,
    );

    if (!this.isPreSignUpTriggerSource(event)) {
      return event;
    }

    const eventEmail = this.getEventUserEmail(event);
    console.log(`Looking up email ${eventEmail}.`);
    const storedUserInfo =
      await this.userRepository.getUserInfoByEmail(eventEmail);

    if (!storedUserInfo) {
      console.log(
        `Email ${eventEmail} not found. Email verification is required.`,
      );
      return event;
    }

    if (storedUserInfo.UserName !== event.userName) {
      console.log(
        `UserEmail ${eventEmail} found, but stored UserName '${storedUserInfo.UserName}' does not match supplied UserName '${event.userName}'. Verification is required.`,
      );
    } else {
      console.log(
        `UserEmail ${eventEmail} found with matching UserName ${storedUserInfo.UserName}. User is confirmed.`,
      );
      event.response.autoConfirmUser = true;
      event.response.autoVerifyEmail = true;
    }
    return event;
  }
}

const createPreSignUpHandler = (): PreSignUpHandler => {
  const tableName = process.env.TABLE_NAME;
  if (!tableName) {
    throw new Error("TABLE_NAME environment variable is not set");
  }

  const userRepository = new DynamoDBUserRepository(tableName);
  return new PreSignUpHandler(userRepository);
};

export const handler: Handler = async (event: PreSignUpTriggerEvent) => {
  const preSignUpHandler = createPreSignUpHandler();
  return preSignUpHandler.handlePreSignUpTriggerEvent(event);
};
```
CloudWatch Logs アクションのモジュール。  

```
import {
  CloudWatchLogsClient,
  GetLogEventsCommand,
  OrderBy,
  paginateDescribeLogStreams,
} from "@aws-sdk/client-cloudwatch-logs";

/**
 * Get the latest log stream for a Lambda function.
 * @param {{ functionName: string, region: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cloudwatch-logs").LogStream | null, unknown]>}
 */
export const getLatestLogStreamForLambda = async ({ functionName, region }) => {
  try {
    const logGroupName = `/aws/lambda/${functionName}`;
    const cwlClient = new CloudWatchLogsClient({ region });
    const paginator = paginateDescribeLogStreams(
      { client: cwlClient },
      {
        descending: true,
        limit: 1,
        orderBy: OrderBy.LastEventTime,
        logGroupName,
      },
    );

    for await (const page of paginator) {
      return [page.logStreams[0], null];
    }
  } catch (err) {
    return [null, err];
  }
};

/**
 * Get the log events for a Lambda function's log stream.
 * @param {{
 *   functionName: string,
 *   logStreamName: string,
 *   eventCount: number,
 *   region: string
 * }} config
 * @returns {Promise<[import("@aws-sdk/client-cloudwatch-logs").OutputLogEvent[] | null, unknown]>}
 */
export const getLogEvents = async ({
  functionName,
  logStreamName,
  eventCount,
  region,
}) => {
  try {
    const cwlClient = new CloudWatchLogsClient({ region });
    const logGroupName = `/aws/lambda/${functionName}`;
    const response = await cwlClient.send(
      new GetLogEventsCommand({
        logStreamName: logStreamName,
        limit: eventCount,
        logGroupName: logGroupName,
      }),
    );

    return [response.events, null];
  } catch (err) {
    return [null, err];
  }
};
```
Amazon Cognito アクションのモジュール。  

```
import {
  AdminGetUserCommand,
  CognitoIdentityProviderClient,
  DeleteUserCommand,
  InitiateAuthCommand,
  SignUpCommand,
  UpdateUserPoolCommand,
} from "@aws-sdk/client-cognito-identity-provider";

/**
 * Connect a Lambda function to the PreSignUp trigger for a Cognito user pool
 * @param {{ region: string, userPoolId: string, handlerArn: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").UpdateUserPoolCommandOutput | null, unknown]>}
 */
export const addPreSignUpHandler = async ({
  region,
  userPoolId,
  handlerArn,
}) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({
      region,
    });

    const command = new UpdateUserPoolCommand({
      UserPoolId: userPoolId,
      LambdaConfig: {
        PreSignUp: handlerArn,
      },
    });

    const response = await cognitoClient.send(command);
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Attempt to register a user to a user pool with a given username and password.
 * @param {{
 *   region: string,
 *   userPoolClientId: string,
 *   username: string,
 *   email: string,
 *   password: string
 * }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").SignUpCommandOutput | null, unknown]>}
 */
export const signUpUser = async ({
  region,
  userPoolClientId,
  username,
  email,
  password,
}) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({
      region,
    });

    const response = await cognitoClient.send(
      new SignUpCommand({
        ClientId: userPoolClientId,
        Username: username,
        Password: password,
        UserAttributes: [{ Name: "email", Value: email }],
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Sign in a user to Amazon Cognito using a username and password authentication flow.
 * @param {{ region: string, clientId: string, username: string, password: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").InitiateAuthCommandOutput | null, unknown]>}
 */
export const signIn = async ({ region, clientId, username, password }) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({ region });
    const response = await cognitoClient.send(
      new InitiateAuthCommand({
        AuthFlow: "USER_PASSWORD_AUTH",
        ClientId: clientId,
        AuthParameters: { USERNAME: username, PASSWORD: password },
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Retrieve an existing user from a user pool.
 * @param {{ region: string, userPoolId: string, username: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").AdminGetUserCommandOutput | null, unknown]>}
 */
export const getUser = async ({ region, userPoolId, username }) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({ region });
    const response = await cognitoClient.send(
      new AdminGetUserCommand({
        UserPoolId: userPoolId,
        Username: username,
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Delete the signed-in user. Useful for allowing a user to delete their
 * own profile.
 * @param {{ region: string, accessToken: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").DeleteUserCommandOutput | null, unknown]>}
 */
export const deleteUser = async ({ region, accessToken }) => {
  try {
    const client = new CognitoIdentityProviderClient({ region });
    const response = await client.send(
      new DeleteUserCommand({ AccessToken: accessToken }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};
```
DynamoDB アクションのモジュール。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  BatchWriteCommand,
  DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";

/**
 * Populate a DynamoDB table with provide items.
 * @param {{ region: string, tableName: string, items: Record<string, unknown>[] }} config
 * @returns {Promise<[import("@aws-sdk/lib-dynamodb").BatchWriteCommandOutput | null, unknown]>}
 */
export const populateTable = async ({ region, tableName, items }) => {
  try {
    const ddbClient = new DynamoDBClient({ region });
    const docClient = DynamoDBDocumentClient.from(ddbClient);
    const response = await docClient.send(
      new BatchWriteCommand({
        RequestItems: {
          [tableName]: items.map((item) => ({
            PutRequest: {
              Item: item,
            },
          })),
        },
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/DeleteUserCommand)
  + [InitiateAuth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/InitiateAuthCommand)
  + [SignUp](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/SignUpCommand)
  + [UpdateUserPool](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/UpdateUserPoolCommand)

### MFA を必要とするユーザープールでユーザーをサインアップする
<a name="cognito-identity-provider_Scenario_SignUpUserWithMfa_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。
+ MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。
+ パスワードと MFA コードを使用してサインインします。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cognito-identity-provider/scenarios/basic#code-examples)での設定と実行の方法を確認してください。
最適なエクスペリエンスを得るには、GitHub リポジトリを複製してこの例を実行します。次のコードは、サンプルアプリケーション全体のサンプルを表しています。  

```
import { logger } from "@aws-doc-sdk-examples/lib/utils/util-log.js";
import { signUp } from "../../../actions/sign-up.js";
import { FILE_USER_POOLS } from "./constants.js";
import { getSecondValuesFromEntries } from "@aws-doc-sdk-examples/lib/utils/util-csv.js";

const validateClient = (clientId) => {
  if (!clientId) {
    throw new Error(
      `App client id is missing. Did you run 'create-user-pool'?`,
    );
  }
};

const validateUser = (username, password, email) => {
  if (!(username && password && email)) {
    throw new Error(
      `Username, password, and email must be provided as arguments to the 'sign-up' command.`,
    );
  }
};

const signUpHandler = async (commands) => {
  const [_, username, password, email] = commands;

  try {
    validateUser(username, password, email);
    /**
     * @type {string[]}
     */
    const values = getSecondValuesFromEntries(FILE_USER_POOLS);
    const clientId = values[0];
    validateClient(clientId);
    logger.log("Signing up.");
    await signUp({ clientId, username, password, email });
    logger.log(`Signed up. A confirmation email has been sent to: ${email}.`);
    logger.log(
      `Run 'confirm-sign-up ${username} <code>' to confirm your account.`,
    );
  } catch (err) {
    logger.error(err);
  }
};

export { signUpHandler };

const signUp = ({ clientId, username, password, email }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new SignUpCommand({
    ClientId: clientId,
    Username: username,
    Password: password,
    UserAttributes: [{ Name: "email", Value: email }],
  });

  return client.send(command);
};

import { logger } from "@aws-doc-sdk-examples/lib/utils/util-log.js";
import { confirmSignUp } from "../../../actions/confirm-sign-up.js";
import { FILE_USER_POOLS } from "./constants.js";
import { getSecondValuesFromEntries } from "@aws-doc-sdk-examples/lib/utils/util-csv.js";

const validateClient = (clientId) => {
  if (!clientId) {
    throw new Error(
      `App client id is missing. Did you run 'create-user-pool'?`,
    );
  }
};

const validateUser = (username) => {
  if (!username) {
    throw new Error(
      `Username name is missing. It must be provided as an argument to the 'confirm-sign-up' command.`,
    );
  }
};

const validateCode = (code) => {
  if (!code) {
    throw new Error(
      `Verification code is missing. It must be provided as an argument to the 'confirm-sign-up' command.`,
    );
  }
};

const confirmSignUpHandler = async (commands) => {
  const [_, username, code] = commands;

  try {
    validateUser(username);
    validateCode(code);
    /**
     * @type {string[]}
     */
    const values = getSecondValuesFromEntries(FILE_USER_POOLS);
    const clientId = values[0];
    validateClient(clientId);
    logger.log("Confirming user.");
    await confirmSignUp({ clientId, username, code });
    logger.log(
      `User confirmed. Run 'admin-initiate-auth ${username} <password>' to sign in.`,
    );
  } catch (err) {
    logger.error(err);
  }
};

export { confirmSignUpHandler };

const confirmSignUp = ({ clientId, username, code }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new ConfirmSignUpCommand({
    ClientId: clientId,
    Username: username,
    ConfirmationCode: code,
  });

  return client.send(command);
};

import qrcode from "qrcode-terminal";
import { logger } from "@aws-doc-sdk-examples/lib/utils/util-log.js";
import { adminInitiateAuth } from "../../../actions/admin-initiate-auth.js";
import { associateSoftwareToken } from "../../../actions/associate-software-token.js";
import { FILE_USER_POOLS } from "./constants.js";
import { getFirstEntry } from "@aws-doc-sdk-examples/lib/utils/util-csv.js";

const handleMfaSetup = async (session, username) => {
  const { SecretCode, Session } = await associateSoftwareToken(session);

  // Store the Session for use with 'VerifySoftwareToken'.
  process.env.SESSION = Session;

  console.log(
    "Scan this code in your preferred authenticator app, then run 'verify-software-token' to finish the setup.",
  );
  qrcode.generate(
    `otpauth://totp/${username}?secret=${SecretCode}`,
    { small: true },
    console.log,
  );
};

const handleSoftwareTokenMfa = (session) => {
  // Store the Session for use with 'AdminRespondToAuthChallenge'.
  process.env.SESSION = session;
};

const validateClient = (id) => {
  if (!id) {
    throw new Error(
      `User pool client id is missing. Did you run 'create-user-pool'?`,
    );
  }
};

const validateId = (id) => {
  if (!id) {
    throw new Error(`User pool id is missing. Did you run 'create-user-pool'?`);
  }
};

const validateUser = (username, password) => {
  if (!(username && password)) {
    throw new Error(
      `Username and password must be provided as arguments to the 'admin-initiate-auth' command.`,
    );
  }
};

const adminInitiateAuthHandler = async (commands) => {
  const [_, username, password] = commands;

  try {
    validateUser(username, password);

    const [userPoolId, clientId] = getFirstEntry(FILE_USER_POOLS);
    validateId(userPoolId);
    validateClient(clientId);

    logger.log("Signing in.");
    const { ChallengeName, Session } = await adminInitiateAuth({
      clientId,
      userPoolId,
      username,
      password,
    });

    if (ChallengeName === "MFA_SETUP") {
      logger.log("MFA setup is required.");
      return handleMfaSetup(Session, username);
    }

    if (ChallengeName === "SOFTWARE_TOKEN_MFA") {
      handleSoftwareTokenMfa(Session);
      logger.log(`Run 'admin-respond-to-auth-challenge ${username} <totp>'`);
    }
  } catch (err) {
    logger.error(err);
  }
};

export { adminInitiateAuthHandler };

const adminInitiateAuth = ({ clientId, userPoolId, username, password }) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new AdminInitiateAuthCommand({
    ClientId: clientId,
    UserPoolId: userPoolId,
    AuthFlow: AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
    AuthParameters: { USERNAME: username, PASSWORD: password },
  });

  return client.send(command);
};

import { logger } from "@aws-doc-sdk-examples/lib/utils/util-log.js";
import { adminRespondToAuthChallenge } from "../../../actions/admin-respond-to-auth-challenge.js";
import { getFirstEntry } from "@aws-doc-sdk-examples/lib/utils/util-csv.js";
import { FILE_USER_POOLS } from "./constants.js";

const verifyUsername = (username) => {
  if (!username) {
    throw new Error(
      `Username is missing. It must be provided as an argument to the 'admin-respond-to-auth-challenge' command.`,
    );
  }
};

const verifyTotp = (totp) => {
  if (!totp) {
    throw new Error(
      `Time-based one-time password (TOTP) is missing. It must be provided as an argument to the 'admin-respond-to-auth-challenge' command.`,
    );
  }
};

const storeAccessToken = (token) => {
  process.env.AccessToken = token;
};

const adminRespondToAuthChallengeHandler = async (commands) => {
  const [_, username, totp] = commands;

  try {
    verifyUsername(username);
    verifyTotp(totp);

    const [userPoolId, clientId] = getFirstEntry(FILE_USER_POOLS);
    const session = process.env.SESSION;

    const { AuthenticationResult } = await adminRespondToAuthChallenge({
      clientId,
      userPoolId,
      username,
      totp,
      session,
    });

    storeAccessToken(AuthenticationResult.AccessToken);

    logger.log("Successfully authenticated.");
  } catch (err) {
    logger.error(err);
  }
};

export { adminRespondToAuthChallengeHandler };

const respondToAuthChallenge = ({
  clientId,
  username,
  session,
  userPoolId,
  code,
}) => {
  const client = new CognitoIdentityProviderClient({});

  const command = new RespondToAuthChallengeCommand({
    ChallengeName: ChallengeNameType.SOFTWARE_TOKEN_MFA,
    ChallengeResponses: {
      SOFTWARE_TOKEN_MFA_CODE: code,
      USERNAME: username,
    },
    ClientId: clientId,
    UserPoolId: userPoolId,
    Session: session,
  });

  return client.send(command);
};

import { logger } from "@aws-doc-sdk-examples/lib/utils/util-log.js";
import { verifySoftwareToken } from "../../../actions/verify-software-token.js";

const validateTotp = (totp) => {
  if (!totp) {
    throw new Error(
      `Time-based one-time password (TOTP) must be provided to the 'validate-software-token' command.`,
    );
  }
};
const verifySoftwareTokenHandler = async (commands) => {
  const [_, totp] = commands;

  try {
    validateTotp(totp);

    logger.log("Verifying TOTP.");
    await verifySoftwareToken(totp);
    logger.log("TOTP Verified. Run 'admin-initiate-auth' again to sign-in.");
  } catch (err) {
    logger.error(err);
  }
};

export { verifySoftwareTokenHandler };

const verifySoftwareToken = (totp) => {
  const client = new CognitoIdentityProviderClient({});

  // The 'Session' is provided in the response to 'AssociateSoftwareToken'.
  const session = process.env.SESSION;

  if (!session) {
    throw new Error(
      "Missing a valid Session. Did you run 'admin-initiate-auth'?",
    );
  }

  const command = new VerifySoftwareTokenCommand({
    Session: session,
    UserCode: totp,
  });

  return client.send(command);
};
```
+ API の詳細については、「AWS SDK for JavaScript API リファレンス**」の以下のトピックを参照してください。
  + [AdminGetUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AdminGetUserCommand)
  + [AdminInitiateAuth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AdminInitiateAuthCommand)
  + [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AdminRespondToAuthChallengeCommand)
  + [AssociateSoftwareToken](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/AssociateSoftwareTokenCommand)
  + [ConfirmDevice](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ConfirmDeviceCommand)
  + [ConfirmSignUp](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ConfirmSignUpCommand)
  + [InitiateAuth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/InitiateAuthCommand)
  + [ListUsers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ListUsersCommand)
  + [ResendConfirmationCode](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/ResendConfirmationCodeCommand)
  + [RespondToAuthChallenge](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/RespondToAuthChallengeCommand)
  + [SignUp](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/SignUpCommand)
  + [VerifySoftwareToken](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/VerifySoftwareTokenCommand)

# SDK for JavaScript (v3) を使用する Amazon Comprehend の例
<a name="javascript_3_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Transcribe ストリーミングアプリケーションを構築する
<a name="cross_TranscriptionStreamingApp_javascript_3_topic"></a>

次のコード例は、ライブ音声をリアルタイムで記録、転写、翻訳し、結果を E メールで送信するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 Amazon Transcribe を使用して、ライブ音声をリアルタイムで記録、転写、翻訳し、Amazon Simple Email Service (Amazon SES) を使用して結果を E メールで送信するアプリケーションを構築する方法について説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/transcribe-streaming-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SES
+ Amazon Transcribe
+ Amazon Translate

### Amazon Lex チャットボットを構築する
<a name="cross_LexChatbotLanguages_javascript_3_topic"></a>

次のコード例は、ウェブサイトの訪問者を引き付けるチャットボットの作成方法を示しています。

**SDK for JavaScript (v3)**  
 Amazon Lex API を使用して、ウェブアプリケーション内にチャットボットを作成し、Web サイトの訪問者と交流する方法を説明します。  
 完全なソースコードとセットアップと実行の手順については、 デ AWS SDK for JavaScript ベロッパーガイドの[Amazon Lexチャットボットの構築](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html)」の完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon Lex
+ Amazon Translate

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_javascript_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for JavaScript (v3)**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer) のプロジェクトを参照してください。次の抜粋は、 AWS SDK for JavaScript が Lambda 関数内でどのように使用されるかを示しています。  

```
import {
  ComprehendClient,
  DetectDominantLanguageCommand,
  DetectSentimentCommand,
} from "@aws-sdk/client-comprehend";

/**
 * Determine the language and sentiment of the extracted text.
 *
 * @param {{ source_text: string}} extractTextOutput
 */
export const handler = async (extractTextOutput) => {
  const comprehendClient = new ComprehendClient({});

  const detectDominantLanguageCommand = new DetectDominantLanguageCommand({
    Text: extractTextOutput.source_text,
  });

  // The source language is required for sentiment analysis and
  // translation in the next step.
  const { Languages } = await comprehendClient.send(
    detectDominantLanguageCommand,
  );

  const languageCode = Languages[0].LanguageCode;

  const detectSentimentCommand = new DetectSentimentCommand({
    Text: extractTextOutput.source_text,
    LanguageCode: languageCode,
  });

  const { Sentiment } = await comprehendClient.send(detectSentimentCommand);

  return {
    sentiment: Sentiment,
    language_code: languageCode,
  };
};
```

```
import {
  DetectDocumentTextCommand,
  TextractClient,
} from "@aws-sdk/client-textract";

/**
 * Fetch the S3 object from the event and analyze it using Amazon Textract.
 *
 * @param {import("@types/aws-lambda").EventBridgeEvent<"Object Created">} eventBridgeS3Event
 */
export const handler = async (eventBridgeS3Event) => {
  const textractClient = new TextractClient();

  const detectDocumentTextCommand = new DetectDocumentTextCommand({
    Document: {
      S3Object: {
        Bucket: eventBridgeS3Event.bucket,
        Name: eventBridgeS3Event.object,
      },
    },
  });

  // Textract returns a list of blocks. A block can be a line, a page, word, etc.
  // Each block also contains geometry of the detected text.
  // For more information on the Block type, see https://docs.aws.amazon.com/textract/latest/dg/API_Block.html.
  const { Blocks } = await textractClient.send(detectDocumentTextCommand);

  // For the purpose of this example, we are only interested in words.
  const extractedWords = Blocks.filter((b) => b.BlockType === "WORD").map(
    (b) => b.Text,
  );

  return extractedWords.join(" ");
};
```

```
import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly";
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

/**
 * Synthesize an audio file from text.
 *
 * @param {{ bucket: string, translated_text: string, object: string}} sourceDestinationConfig
 */
export const handler = async (sourceDestinationConfig) => {
  const pollyClient = new PollyClient({});

  const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
    Engine: "neural",
    Text: sourceDestinationConfig.translated_text,
    VoiceId: "Ruth",
    OutputFormat: "mp3",
  });

  const { AudioStream } = await pollyClient.send(synthesizeSpeechCommand);

  const audioKey = `${sourceDestinationConfig.object}.mp3`;

  // Store the audio file in S3.
  const s3Client = new S3Client();
  const upload = new Upload({
    client: s3Client,
    params: {
      Bucket: sourceDestinationConfig.bucket,
      Key: audioKey,
      Body: AudioStream,
      ContentType: "audio/mp3",
    },
  });

  await upload.done();
  return audioKey;
};
```

```
import {
  TranslateClient,
  TranslateTextCommand,
} from "@aws-sdk/client-translate";

/**
 * Translate the extracted text to English.
 *
 * @param {{ extracted_text: string, source_language_code: string}} textAndSourceLanguage
 */
export const handler = async (textAndSourceLanguage) => {
  const translateClient = new TranslateClient({});

  const translateCommand = new TranslateTextCommand({
    SourceLanguageCode: textAndSourceLanguage.source_language_code,
    TargetLanguageCode: "en",
    Text: textAndSourceLanguage.extracted_text,
  });

  const { TranslatedText } = await translateClient.send(translateCommand);

  return { translated_text: TranslatedText };
};
```

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for JavaScript (v3) を使用した Amazon DocumentDB の例
<a name="javascript_3_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_javascript_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での Amazon DocumentDB イベントの消費。  

```
console.log('Loading function');
exports.handler = async (event, context) => {
    event.events.forEach(record => {
        logDocumentDBEvent(record);
    });
    return 'OK';
};

const logDocumentDBEvent = (record) => {
    console.log('Operation type: ' + record.event.operationType);
    console.log('db: ' + record.event.ns.db);
    console.log('collection: ' + record.event.ns.coll);
    console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2));
};
```
TypeScript を使用した Lambda での Amazon DocumentDB イベントの消費  

```
import { DocumentDBEventRecord, DocumentDBEventSubscriptionContext } from 'aws-lambda';

console.log('Loading function');

export const handler = async (
  event: DocumentDBEventSubscriptionContext,
  context: any
): Promise<string> => {
  event.events.forEach((record: DocumentDBEventRecord) => {
    logDocumentDBEvent(record);
  });
  return 'OK';
};

const logDocumentDBEvent = (record: DocumentDBEventRecord): void => {
  console.log('Operation type: ' + record.event.operationType);
  console.log('db: ' + record.event.ns.db);
  console.log('collection: ' + record.event.ns.coll);
  console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2));
};
```

# SDK for JavaScript (v3) を使用した DynamoDB の例
<a name="javascript_3_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello DynamoDB
<a name="dynamodb_Hello_javascript_3_topic"></a>

次のコード例は、DynamoDB の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
での DynamoDB の使用の詳細については AWS SDK for JavaScript、[JavaScript を使用した DynamoDB のプログラミング](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/programming-with-javascript.html)」を参照してください。  

```
import { ListTablesCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new ListTablesCommand({});

  const response = await client.send(command);
  console.log(response.TableNames.join("\n"));
  return response;
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[ListTables](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ListTablesCommand)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import { readFileSync } from "node:fs";
import {
  BillingMode,
  CreateTableCommand,
  DeleteTableCommand,
  DynamoDBClient,
  waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";

/**
 * This module is a convenience library. It abstracts Amazon DynamoDB's data type
 * descriptors (such as S, N, B, and BOOL) by marshalling JavaScript objects into
 * AttributeValue shapes.
 */
import {
  BatchWriteCommand,
  DeleteCommand,
  DynamoDBDocumentClient,
  GetCommand,
  PutCommand,
  UpdateCommand,
  paginateQuery,
  paginateScan,
} from "@aws-sdk/lib-dynamodb";

// These modules are local to our GitHub repository. We recommend cloning
// the project from GitHub if you want to run this example.
// For more information, see https://github.com/awsdocs/aws-doc-sdk-examples.
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import { chunkArray } from "@aws-doc-sdk-examples/lib/utils/util-array.js";

const dirname = dirnameFromMetaUrl(import.meta.url);
const tableName = getUniqueName("Movies");
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

const log = (msg) => console.log(`[SCENARIO] ${msg}`);

export const main = async () => {
  /**
   * Create a table.
   */

  const createTableCommand = new CreateTableCommand({
    TableName: tableName,
    // This example performs a large write to the database.
    // Set the billing mode to PAY_PER_REQUEST to
    // avoid throttling the large write.
    BillingMode: BillingMode.PAY_PER_REQUEST,
    // Define the attributes that are necessary for the key schema.
    AttributeDefinitions: [
      {
        AttributeName: "year",
        // 'N' is a data type descriptor that represents a number type.
        // For a list of all data type descriptors, see the following link.
        // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors
        AttributeType: "N",
      },
      { AttributeName: "title", AttributeType: "S" },
    ],
    // The KeySchema defines the primary key. The primary key can be
    // a partition key, or a combination of a partition key and a sort key.
    // Key schema design is important. For more info, see
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html
    KeySchema: [
      // The way your data is accessed determines how you structure your keys.
      // The movies table will be queried for movies by year. It makes sense
      // to make year our partition (HASH) key.
      { AttributeName: "year", KeyType: "HASH" },
      { AttributeName: "title", KeyType: "RANGE" },
    ],
  });

  log("Creating a table.");
  const createTableResponse = await client.send(createTableCommand);
  log(`Table created: ${JSON.stringify(createTableResponse.TableDescription)}`);

  // This polls with DescribeTableCommand until the requested table is 'ACTIVE'.
  // You can't write to a table before it's active.
  log("Waiting for the table to be active.");
  await waitUntilTableExists({ client }, { TableName: tableName });
  log("Table active.");

  /**
   * Add a movie to the table.
   */

  log("Adding a single movie to the table.");
  // PutCommand is the first example usage of 'lib-dynamodb'.
  const putCommand = new PutCommand({
    TableName: tableName,
    Item: {
      // In 'client-dynamodb', the AttributeValue would be required (`year: { N: 1981 }`)
      // 'lib-dynamodb' simplifies the usage ( `year: 1981` )
      year: 1981,
      // The preceding KeySchema defines 'title' as our sort (RANGE) key, so 'title'
      // is required.
      title: "The Evil Dead",
      // Every other attribute is optional.
      info: {
        genres: ["Horror"],
      },
    },
  });
  await docClient.send(putCommand);
  log("The movie was added.");

  /**
   * Get a movie from the table.
   */

  log("Getting a single movie from the table.");
  const getCommand = new GetCommand({
    TableName: tableName,
    // Requires the complete primary key. For the movies table, the primary key
    // is only the id (partition key).
    Key: {
      year: 1981,
      title: "The Evil Dead",
    },
    // Set this to make sure that recent writes are reflected.
    // For more information, see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html.
    ConsistentRead: true,
  });
  const getResponse = await docClient.send(getCommand);
  log(`Got the movie: ${JSON.stringify(getResponse.Item)}`);

  /**
   * Update a movie in the table.
   */

  log("Updating a single movie in the table.");
  const updateCommand = new UpdateCommand({
    TableName: tableName,
    Key: { year: 1981, title: "The Evil Dead" },
    // This update expression appends "Comedy" to the list of genres.
    // For more information on update expressions, see
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html
    UpdateExpression: "set #i.#g = list_append(#i.#g, :vals)",
    ExpressionAttributeNames: { "#i": "info", "#g": "genres" },
    ExpressionAttributeValues: {
      ":vals": ["Comedy"],
    },
    ReturnValues: "ALL_NEW",
  });
  const updateResponse = await docClient.send(updateCommand);
  log(`Movie updated: ${JSON.stringify(updateResponse.Attributes)}`);

  /**
   * Delete a movie from the table.
   */

  log("Deleting a single movie from the table.");
  const deleteCommand = new DeleteCommand({
    TableName: tableName,
    Key: { year: 1981, title: "The Evil Dead" },
  });
  await docClient.send(deleteCommand);
  log("Movie deleted.");

  /**
   * Upload a batch of movies.
   */

  log("Adding movies from local JSON file.");
  const file = readFileSync(
    `${dirname}../../../../resources/sample_files/movies.json`,
  );
  const movies = JSON.parse(file.toString());
  // chunkArray is a local convenience function. It takes an array and returns
  // a generator function. The generator function yields every N items.
  const movieChunks = chunkArray(movies, 25);
  // For every chunk of 25 movies, make one BatchWrite request.
  for (const chunk of movieChunks) {
    const putRequests = chunk.map((movie) => ({
      PutRequest: {
        Item: movie,
      },
    }));

    const command = new BatchWriteCommand({
      RequestItems: {
        [tableName]: putRequests,
      },
    });

    await docClient.send(command);
  }
  log("Movies added.");

  /**
   * Query for movies by year.
   */

  log("Querying for all movies from 1981.");
  const paginatedQuery = paginateQuery(
    { client: docClient },
    {
      TableName: tableName,
      //For more information about query expressions, see
      // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.KeyConditionExpressions
      KeyConditionExpression: "#y = :y",
      // 'year' is a reserved word in DynamoDB. Indicate that it's an attribute
      // name by using an expression attribute name.
      ExpressionAttributeNames: { "#y": "year" },
      ExpressionAttributeValues: { ":y": 1981 },
      ConsistentRead: true,
    },
  );
  /**
   * @type { Record<string, any>[] };
   */
  const movies1981 = [];
  for await (const page of paginatedQuery) {
    movies1981.push(...page.Items);
  }
  log(`Movies: ${movies1981.map((m) => m.title).join(", ")}`);

  /**
   * Scan the table for movies between 1980 and 1990.
   */

  log("Scan for movies released between 1980 and 1990");
  // A 'Scan' operation always reads every item in the table. If your design requires
  // the use of 'Scan', consider indexing your table or changing your design.
  // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-query-scan.html
  const paginatedScan = paginateScan(
    { client: docClient },
    {
      TableName: tableName,
      // Scan uses a filter expression instead of a key condition expression. Scan will
      // read the entire table and then apply the filter.
      FilterExpression: "#y between :y1 and :y2",
      ExpressionAttributeNames: { "#y": "year" },
      ExpressionAttributeValues: { ":y1": 1980, ":y2": 1990 },
      ConsistentRead: true,
    },
  );
  /**
   * @type { Record<string, any>[] };
   */
  const movies1980to1990 = [];
  for await (const page of paginatedScan) {
    movies1980to1990.push(...page.Items);
  }
  log(
    `Movies: ${movies1980to1990
      .map((m) => `${m.title} (${m.year})`)
      .join(", ")}`,
  );

  /**
   * Delete the table.
   */

  const deleteTableCommand = new DeleteTableCommand({ TableName: tableName });
  log(`Deleting table ${tableName}.`);
  await client.send(deleteTableCommand);
  log("Table deleted.");
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchWriteItemCommand)
  + [CreateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand)
  + [DeleteItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteItemCommand)
  + [DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteTableCommand)
  + [DescribeTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DescribeTableCommand)
  + [GetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/GetItemCommand)
  + [PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)
  + [Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)
  + [Scan](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ScanCommand)
  + [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)

## アクション
<a name="actions"></a>

### `BatchExecuteStatement`
<a name="dynamodb_BatchExecuteStatement_javascript_3_topic"></a>

次のコード例は、`BatchExecuteStatement` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
PartiQL を使用して項目のバッチを作成します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  DynamoDBDocumentClient,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const breakfastFoods = ["Eggs", "Bacon", "Sausage"];
  const command = new BatchExecuteStatementCommand({
    Statements: breakfastFoods.map((food) => ({
      Statement: `INSERT INTO BreakfastFoods value {'Name':?}`,
      Parameters: [food],
    })),
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
PartiQL を使用して項目のバッチを取得します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  DynamoDBDocumentClient,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new BatchExecuteStatementCommand({
    Statements: [
      {
        Statement: "SELECT * FROM PepperMeasurements WHERE Unit=?",
        Parameters: ["Teaspoons"],
        ConsistentRead: true,
      },
      {
        Statement: "SELECT * FROM PepperMeasurements WHERE Unit=?",
        Parameters: ["Grams"],
        ConsistentRead: true,
      },
    ],
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
PartiQL を使用して項目のバッチを更新します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  DynamoDBDocumentClient,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const eggUpdates = [
    ["duck", "fried"],
    ["chicken", "omelette"],
  ];
  const command = new BatchExecuteStatementCommand({
    Statements: eggUpdates.map((change) => ({
      Statement: "UPDATE Eggs SET Style=? where Variety=?",
      Parameters: [change[1], change[0]],
    })),
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
PartiQL を使用して項目のバッチを削除します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  DynamoDBDocumentClient,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new BatchExecuteStatementCommand({
    Statements: [
      {
        Statement: "DELETE FROM Flavors where Name=?",
        Parameters: ["Grape"],
      },
      {
        Statement: "DELETE FROM Flavors where Name=?",
        Parameters: ["Strawberry"],
      },
    ],
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[BatchExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchExecuteStatementCommand)」を参照してください。

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_javascript_3_topic"></a>

次のコード例は、`BatchGetItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[BatchGet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/BatchGetCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { BatchGetCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new BatchGetCommand({
    // Each key in this object is the name of a table. This example refers
    // to a Books table.
    RequestItems: {
      Books: {
        // Each entry in Keys is an object that specifies a primary key.
        Keys: [
          {
            Title: "How to AWS",
          },
          {
            Title: "DynamoDB for DBAs",
          },
        ],
        // Only return the "Title" and "PageCount" attributes.
        ProjectionExpression: "Title, PageCount",
      },
    },
  });

  const response = await docClient.send(command);
  console.log(response.Responses.Books);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-table-read-write-batch.html#dynamodb-example-table-read-write-batch-reading)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[BatchGetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchGetItemCommand)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_javascript_3_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[BatchWrite](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/BatchWriteCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  BatchWriteCommand,
  DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";
import { readFileSync } from "node:fs";

// These modules are local to our GitHub repository. We recommend cloning
// the project from GitHub if you want to run this example.
// For more information, see https://github.com/awsdocs/aws-doc-sdk-examples.
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import { chunkArray } from "@aws-doc-sdk-examples/lib/utils/util-array.js";

const dirname = dirnameFromMetaUrl(import.meta.url);

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const file = readFileSync(
    `${dirname}../../../../../resources/sample_files/movies.json`,
  );

  const movies = JSON.parse(file.toString());

  // chunkArray is a local convenience function. It takes an array and returns
  // a generator function. The generator function yields every N items.
  const movieChunks = chunkArray(movies, 25);

  // For every chunk of 25 movies, make one BatchWrite request.
  for (const chunk of movieChunks) {
    const putRequests = chunk.map((movie) => ({
      PutRequest: {
        Item: movie,
      },
    }));

    const command = new BatchWriteCommand({
      RequestItems: {
        // An existing table is required. A composite key of 'title' and 'year' is recommended
        // to account for duplicate titles.
        BatchWriteMoviesTable: putRequests,
      },
    });

    await docClient.send(command);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[BatchWriteItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchWriteItemCommand)」を参照してください。

### `CreateTable`
<a name="dynamodb_CreateTable_javascript_3_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import { CreateTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new CreateTableCommand({
    TableName: "EspressoDrinks",
    // For more information about data types,
    // see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes and
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors
    AttributeDefinitions: [
      {
        AttributeName: "DrinkName",
        AttributeType: "S",
      },
    ],
    KeySchema: [
      {
        AttributeName: "DrinkName",
        KeyType: "HASH",
      },
    ],
    BillingMode: "PAY_PER_REQUEST",
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-creating-a-table)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_javascript_3_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[DeleteCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/DeleteCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, DeleteCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new DeleteCommand({
    TableName: "Sodas",
    Key: {
      Flavor: "Cola",
    },
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-table-read-write.html#dynamodb-example-table-read-write-deleting-an-item)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteItemCommand)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_javascript_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new DeleteTableCommand({
    TableName: "DecafCoffees",
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteTableCommand)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_javascript_3_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new DescribeTableCommand({
    TableName: "Pastries",
  });

  const response = await client.send(command);
  console.log(`TABLE NAME: ${response.Table.TableName}`);
  console.log(`TABLE ITEM COUNT: ${response.Table.ItemCount}`);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-describing-a-table)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DescribeTableCommand)」を参照してください。

### `DescribeTimeToLive`
<a name="dynamodb_DescribeTimeToLive_javascript_3_topic"></a>

次のコード例は、`DescribeTimeToLive` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScriptを使用して既存の DynamoDB テーブルの TTL 設定を記述します。  

```
import { DynamoDBClient, DescribeTimeToLiveCommand } from "@aws-sdk/client-dynamodb";

export const describeTTL = async (tableName, region) => {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    try {
        const ttlDescription = await client.send(new DescribeTimeToLiveCommand({ TableName: tableName }));

        if (ttlDescription.TimeToLiveDescription.TimeToLiveStatus === 'ENABLED') {
            console.log("TTL is enabled for table %s.", tableName);
        } else {
            console.log("TTL is not enabled for table %s.", tableName);
        }

        return ttlDescription;
    } catch (e) {
        console.error(`Error describing table: ${e}`);
        throw e;
    }
}

// Example usage (commented out for testing)
// describeTTL('your-table-name', 'us-east-1');
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeTimeToLive](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DescribeTimeToLiveCommand)」を参照してください。

### `ExecuteStatement`
<a name="dynamodb_ExecuteStatement_javascript_3_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
PartiQL を使用して項目を作成します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  ExecuteStatementCommand,
  DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new ExecuteStatementCommand({
    Statement: `INSERT INTO Flowers value {'Name':?}`,
    Parameters: ["Rose"],
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
PartiQL を使用して項目を取得します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  ExecuteStatementCommand,
  DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new ExecuteStatementCommand({
    Statement: "SELECT * FROM CloudTypes WHERE IsStorm=?",
    Parameters: [false],
    ConsistentRead: true,
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
PartiQL を使用して項目を更新します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  ExecuteStatementCommand,
  DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new ExecuteStatementCommand({
    Statement: "UPDATE EyeColors SET IsRecessive=? where Color=?",
    Parameters: [true, "blue"],
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
PartiQL を使用して項目を削除します。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import {
  ExecuteStatementCommand,
  DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new ExecuteStatementCommand({
    Statement: "DELETE FROM PaintColors where Name=?",
    Parameters: ["Purple"],
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の[ExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ExecuteStatementCommand)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_javascript_3_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[GetCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/GetCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new GetCommand({
    TableName: "AngryAnimals",
    Key: {
      CommonName: "Shoebill",
    },
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/GetItemCommand)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_javascript_3_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import { ListTablesCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({});

export const main = async () => {
  const command = new ListTablesCommand({});

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-examples-using-tables.html#dynamodb-examples-using-tables-listing-tables)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListTables](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ListTablesCommand)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_javascript_3_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[PutCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/PutCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { PutCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new PutCommand({
    TableName: "HappyAnimals",
    Item: {
      CommonName: "Shiba Inu",
    },
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)」を参照してください。

### `Query`
<a name="dynamodb_Query_javascript_3_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[QueryCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/QueryCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { QueryCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new QueryCommand({
    TableName: "CoffeeCrop",
    KeyConditionExpression:
      "OriginCountry = :originCountry AND RoastDate > :roastDate",
    ExpressionAttributeValues: {
      ":originCountry": "Ethiopia",
      ":roastDate": "2023-05-01",
    },
    ConsistentRead: true,
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/dynamodb-example-query-scan.html#dynamodb-example-table-query-scan-querying)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_javascript_3_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[ScanCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/ScanCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, ScanCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new ScanCommand({
    ProjectionExpression: "#Name, Color, AvgLifeSpan",
    ExpressionAttributeNames: { "#Name": "Name" },
    TableName: "Birds",
  });

  const response = await docClient.send(command);
  for (const bird of response.Items) {
    console.log(`${bird.Name} - (${bird.Color}, ${bird.AvgLifeSpan})`);
  }
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Scan](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ScanCommand)」を参照してください。

### `UpdateItem`
<a name="dynamodb_UpdateItem_javascript_3_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「[UpdateCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-lib-dynamodb/Class/UpdateCommand/)」を参照してください。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

export const main = async () => {
  const command = new UpdateCommand({
    TableName: "Dogs",
    Key: {
      Breed: "Labrador",
    },
    UpdateExpression: "set Color = :color",
    ExpressionAttributeValues: {
      ":color": "black",
    },
    ReturnValues: "ALL_NEW",
  });

  const response = await docClient.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### `UpdateTimeToLive`
<a name="dynamodb_UpdateTimeToLive_javascript_3_topic"></a>

次のコード例は、`UpdateTimeToLive` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
既存の DynamoDB テーブルの TTL を有効にします。  

```
import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb";

export const enableTTL = async (tableName, ttlAttribute, region = 'us-east-1') => {

    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const params = {
        TableName: tableName,
        TimeToLiveSpecification: {
            Enabled: true,
            AttributeName: ttlAttribute
        }
    };

    try {
        const response = await client.send(new UpdateTimeToLiveCommand(params));
        if (response.$metadata.httpStatusCode === 200) {
            console.log(`TTL enabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`);
        } else {
            console.log(`Failed to enable TTL for table ${tableName}, response object: ${response}`);
        }
        return response;
    } catch (e) {
        console.error(`Error enabling TTL: ${e}`);
        throw e;
    }
};

// Example usage (commented out for testing)
// enableTTL('ExampleTable', 'exampleTtlAttribute');
```
既存の DynamoDB テーブルの TTL を無効にします。  

```
import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb";

export const disableTTL = async (tableName, ttlAttribute, region = 'us-east-1') => {

    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const params = {
        TableName: tableName,
        TimeToLiveSpecification: {
            Enabled: false,
            AttributeName: ttlAttribute
        }
    };

    try {
        const response = await client.send(new UpdateTimeToLiveCommand(params));
        if (response.$metadata.httpStatusCode === 200) {
            console.log(`TTL disabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`);
        } else {
            console.log(`Failed to disable TTL for table ${tableName}, response object: ${response}`);
        }
        return response;
    } catch (e) {
        console.error(`Error disabling TTL: ${e}`);
        throw e;
    }
};

// Example usage (commented out for testing)
// disableTTL('ExampleTable', 'exampleTtlAttribute');
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateTimeToLive](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateTimeToLiveCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DynamoDB テーブルにデータを送信するアプリケーションを構築する
<a name="cross_SubmitDataApp_javascript_3_topic"></a>

次のコード例は、Amazon DynamoDB テーブルにデータを送信し、ユーザーがテーブルを更新したときに通知するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 この例では、ユーザーが Amazon DynamoDB テーブルにデータを送信し、Amazon Simple Notification Service (Amazon SNS) を使用して管理者にテキストメッセージを送信できるようにするアプリを構築する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/submit-data-app) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-submitting-data.html)でも使用できます。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SNS

### 複数の値を 1 つの属性と比較する
<a name="dynamodb_Scenario_CompareMultipleValues_javascript_3_topic"></a>

次のコード例は、DynamoDB で複数の値を 1 つの属性と比較する方法を示しています。
+ IN 演算子を使用して、複数の値を 1 つの属性と比較します。
+ IN 演算子を複数の OR 条件と比較します。
+ IN の使用によるパフォーマンスと式の複雑さのメリットを理解します。

**SDK for JavaScript (v3)**  
を使用して、複数の値を単一の属性と比較します AWS SDK for JavaScript。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  ScanCommand, 
  QueryCommand 
} = require("@aws-sdk/lib-dynamodb");

/**
 * Query or scan a DynamoDB table to find items where an attribute matches any value from a list.
 * 
 * This function demonstrates the use of the IN operator to compare a single attribute
 * against multiple possible values, which is more efficient than using multiple OR conditions.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} attributeName - The name of the attribute to compare against the values list
 * @param {Array} valuesList - List of values to compare the attribute against
 * @param {string} [partitionKeyName] - Optional name of the partition key attribute for query operations
 * @param {string} [partitionKeyValue] - Optional value of the partition key to query
 * @returns {Promise<Object>} - The response from DynamoDB containing the matching items
 */
async function compareMultipleValues(
  config,
  tableName,
  attributeName,
  valuesList,
  partitionKeyName,
  partitionKeyValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Create the filter expression using the IN operator
  const filterExpression = `${attributeName} IN (${valuesList.map((_, index) => `:val${index}`).join(', ')})`;
  
  // Create expression attribute values for the values list
  const expressionAttributeValues = valuesList.reduce((acc, val, index) => {
    acc[`:val${index}`] = val;
    return acc;
  }, {});
  
  // If partition key is provided, perform a query operation
  if (partitionKeyName && partitionKeyValue) {
    const keyCondition = `${partitionKeyName} = :partitionKey`;
    expressionAttributeValues[':partitionKey'] = partitionKeyValue;
    
    // Initialize array to collect all items
    let allItems = [];
    let lastEvaluatedKey;
    
    // Use pagination to get all results
    do {
      const params = {
        TableName: tableName,
        KeyConditionExpression: keyCondition,
        FilterExpression: filterExpression,
        ExpressionAttributeValues: expressionAttributeValues
      };
      
      // Add ExclusiveStartKey if we have a lastEvaluatedKey from a previous query
      if (lastEvaluatedKey) {
        params.ExclusiveStartKey = lastEvaluatedKey;
      }
      
      const response = await docClient.send(new QueryCommand(params));
      
      // Add the items from this page to our collection
      if (response.Items && response.Items.length > 0) {
        allItems = [...allItems, ...response.Items];
      }
      
      // Get the key for the next page of results
      lastEvaluatedKey = response.LastEvaluatedKey;
    } while (lastEvaluatedKey);
    
    // Return the complete result
    return {
      Items: allItems,
      Count: allItems.length
    };
  } else {
    // Otherwise, perform a scan operation
    // Initialize array to collect all items
    let allItems = [];
    let lastEvaluatedKey;
    
    // Use pagination to get all results
    do {
      const params = {
        TableName: tableName,
        FilterExpression: filterExpression,
        ExpressionAttributeValues: expressionAttributeValues
      };
      
      // Add ExclusiveStartKey if we have a lastEvaluatedKey from a previous scan
      if (lastEvaluatedKey) {
        params.ExclusiveStartKey = lastEvaluatedKey;
      }
      
      const response = await docClient.send(new ScanCommand(params));
      
      // Add the items from this page to our collection
      if (response.Items && response.Items.length > 0) {
        allItems = [...allItems, ...response.Items];
      }
      
      // Get the key for the next page of results
      lastEvaluatedKey = response.LastEvaluatedKey;
    } while (lastEvaluatedKey);
    
    // Return the complete result
    return {
      Items: allItems,
      Count: allItems.length
    };
  }
}

/**
 * Alternative implementation using multiple OR conditions instead of the IN operator.
 * 
 * This function is provided for comparison to show why using the IN operator is preferable.
 * With many values, this approach becomes verbose and less efficient.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} attributeName - The name of the attribute to compare against the values list
 * @param {Array} valuesList - List of values to compare the attribute against
 * @param {string} [partitionKeyName] - Optional name of the partition key attribute for query operations
 * @param {string} [partitionKeyValue] - Optional value of the partition key to query
 * @returns {Promise<Object>} - The response from DynamoDB containing the matching items
 */
async function compareWithOrConditions(
  config,
  tableName,
  attributeName,
  valuesList,
  partitionKeyName,
  partitionKeyValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // If no values provided, return empty result
  if (!valuesList || valuesList.length === 0) {
    return {
      Items: [],
      Count: 0
    };
  }
  
  // Create the filter expression using multiple OR conditions
  const filterConditions = valuesList.map((_, index) => `${attributeName} = :val${index}`);
  const filterExpression = filterConditions.join(' OR ');
  
  // Create expression attribute values for the values list
  const expressionAttributeValues = valuesList.reduce((acc, val, index) => {
    acc[`:val${index}`] = val;
    return acc;
  }, {});
  
  // If partition key is provided, perform a query operation
  if (partitionKeyName && partitionKeyValue) {
    const keyCondition = `${partitionKeyName} = :partitionKey`;
    expressionAttributeValues[':partitionKey'] = partitionKeyValue;
    
    // Initialize array to collect all items
    let allItems = [];
    let lastEvaluatedKey;
    
    // Use pagination to get all results
    do {
      const params = {
        TableName: tableName,
        KeyConditionExpression: keyCondition,
        FilterExpression: filterExpression,
        ExpressionAttributeValues: expressionAttributeValues
      };
      
      // Add ExclusiveStartKey if we have a lastEvaluatedKey from a previous query
      if (lastEvaluatedKey) {
        params.ExclusiveStartKey = lastEvaluatedKey;
      }
      
      const response = await docClient.send(new QueryCommand(params));
      
      // Add the items from this page to our collection
      if (response.Items && response.Items.length > 0) {
        allItems = [...allItems, ...response.Items];
      }
      
      // Get the key for the next page of results
      lastEvaluatedKey = response.LastEvaluatedKey;
    } while (lastEvaluatedKey);
    
    // Return the complete result
    return {
      Items: allItems,
      Count: allItems.length
    };
  } else {
    // Otherwise, perform a scan operation
    // Initialize array to collect all items
    let allItems = [];
    let lastEvaluatedKey;
    
    // Use pagination to get all results
    do {
      const params = {
        TableName: tableName,
        FilterExpression: filterExpression,
        ExpressionAttributeValues: expressionAttributeValues
      };
      
      // Add ExclusiveStartKey if we have a lastEvaluatedKey from a previous scan
      if (lastEvaluatedKey) {
        params.ExclusiveStartKey = lastEvaluatedKey;
      }
      
      const response = await docClient.send(new ScanCommand(params));
      
      // Add the items from this page to our collection
      if (response.Items && response.Items.length > 0) {
        allItems = [...allItems, ...response.Items];
      }
      
      // Get the key for the next page of results
      lastEvaluatedKey = response.LastEvaluatedKey;
    } while (lastEvaluatedKey);
    
    // Return the complete result
    return {
      Items: allItems,
      Count: allItems.length
    };
  }
}
```
複数の値と を比較する使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to use the compareMultipleValues function.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "Products";
  const attributeName = "Category";
  const valuesList = ["Electronics", "Computers", "Accessories"];
  
  console.log(`Searching for products in any of these categories: ${valuesList.join(', ')}`);
  
  try {
    // Using the IN operator (recommended approach)
    console.log("\nApproach 1: Using the IN operator");
    const response = await compareMultipleValues(
      config,
      tableName,
      attributeName,
      valuesList
    );
    
    console.log(`Found ${response.Count} products in the specified categories`);
    
    // Using multiple OR conditions (alternative approach)
    console.log("\nApproach 2: Using multiple OR conditions");
    const response2 = await compareWithOrConditions(
      config,
      tableName,
      attributeName,
      valuesList
    );
    
    console.log(`Found ${response2.Count} products in the specified categories`);
    
    // Example with a query operation
    console.log("\nQuerying a specific manufacturer's products in multiple categories");
    const partitionKeyName = "Manufacturer";
    const partitionKeyValue = "Acme";
    
    const response3 = await compareMultipleValues(
      config,
      tableName,
      attributeName,
      valuesList,
      partitionKeyName,
      partitionKeyValue
    );
    
    console.log(`Found ${response3.Count} Acme products in the specified categories`);
    
    // Explain the benefits of using the IN operator
    console.log("\nBenefits of using the IN operator:");
    console.log("1. More concise expression compared to multiple OR conditions");
    console.log("2. Better readability and maintainability");
    console.log("3. Potentially better performance with large value lists");
    console.log("4. Simpler code that's less prone to errors");
    console.log("5. Easier to modify when adding or removing values");
    
  } catch (error) {
    console.error("Error:", error);
  }
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)
  + [Scan](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ScanCommand)

### 項目の TTL を条件付きで更新する
<a name="dynamodb_UpdateItemConditionalTTL_javascript_3_topic"></a>

以下のコード例は、項目の TTL を条件付きで更新する方法を示しています。

**SDK for JavaScript (v3)**  
条件を指定して、テーブル内の既存の DynamoDB 項目の TTL を更新します。  

```
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";

export const updateItemConditional = async (tableName, partitionKey, sortKey, region = 'us-east-1', newAttribute = 'default-value') => {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const currentTime = Math.floor(Date.now() / 1000);

    const params = {
        TableName: tableName,
        Key: marshall({
            artist: partitionKey,
            album: sortKey
        }),
        UpdateExpression: "SET newAttribute = :newAttribute",
        ConditionExpression: "expireAt > :expiration",
        ExpressionAttributeValues: marshall({
            ':newAttribute': newAttribute,
            ':expiration': currentTime
        }),
        ReturnValues: "ALL_NEW"
    };

    try {
        const response = await client.send(new UpdateItemCommand(params));
        const responseData = unmarshall(response.Attributes);
        console.log("Item updated successfully: ", responseData);
        return responseData;
    } catch (error) {
        if (error.name === "ConditionalCheckFailedException") {
            console.log("Condition check failed: Item's 'expireAt' is expired.");
        } else {
            console.error("Error updating item: ", error);
        }
        throw error;
    }
};

// Example usage (commented out for testing)
// updateItemConditional('your-table-name', 'your-partition-key-value', 'your-sort-key-value');
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### 式演算子をカウントする
<a name="dynamodb_Scenario_ExpressionOperatorCounting_javascript_3_topic"></a>

次のコード例は、DynamoDB で式演算子をカウントする方法を示しています。
+ DynamoDB の演算子の制限数が 300 であることを理解します。
+ 複雑な式での演算子をカウントする。
+ 式を最適化して制限内に収まるようにします。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScriptを使用して式演算子のカウントをデモンストレーションします。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  QueryCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Create a complex filter expression with a specified number of conditions.
 * 
 * This function demonstrates how to generate a complex expression with
 * a specific number of operators to test the 300 operator limit.
 * 
 * @param {number} conditionsCount - Number of conditions to include
 * @param {boolean} useAnd - Whether to use AND (true) or OR (false) between conditions
 * @returns {Object} - Object containing the filter expression and attribute values
 */
function createComplexFilterExpression(conditionsCount, useAnd = true) {
  // Initialize the expression parts and attribute values
  const conditions = [];
  const expressionAttributeValues = {};
  
  // Generate the specified number of conditions
  for (let i = 0; i < conditionsCount; i++) {
    // Alternate between different comparison operators for variety
    let condition;
    const valueKey = `:val${i}`;
    
    switch (i % 5) {
      case 0:
        condition = `attribute${i} = ${valueKey}`;
        expressionAttributeValues[valueKey] = `value${i}`;
        break;
      case 1:
        condition = `attribute${i} > ${valueKey}`;
        expressionAttributeValues[valueKey] = i;
        break;
      case 2:
        condition = `attribute${i} < ${valueKey}`;
        expressionAttributeValues[valueKey] = i * 10;
        break;
      case 3:
        condition = `contains(attribute${i}, ${valueKey})`;
        expressionAttributeValues[valueKey] = `substring${i}`;
        break;
      case 4:
        condition = `attribute_exists(attribute${i})`;
        break;
    }
    
    conditions.push(condition);
  }
  
  // Join the conditions with AND or OR
  const operator = useAnd ? " AND " : " OR ";
  const filterExpression = conditions.join(operator);
  
  // Calculate the operator count
  // Each condition has 1 operator (=, >, <, contains, attribute_exists)
  // Each AND or OR between conditions is 1 operator
  const operatorCount = conditionsCount + (conditionsCount > 0 ? conditionsCount - 1 : 0);
  
  return {
    filterExpression,
    expressionAttributeValues,
    operatorCount
  };
}

/**
 * Create a complex update expression with a specified number of operations.
 * 
 * This function demonstrates how to generate a complex update expression with
 * a specific number of operators to test the 300 operator limit.
 * 
 * @param {number} operationsCount - Number of operations to include
 * @returns {Object} - Object containing the update expression and attribute values
 */
function createComplexUpdateExpression(operationsCount) {
  // Initialize the expression parts and attribute values
  const setOperations = [];
  const expressionAttributeValues = {};
  
  // Generate the specified number of SET operations
  for (let i = 0; i < operationsCount; i++) {
    // Alternate between different types of SET operations
    let operation;
    const valueKey = `:val${i}`;
    
    switch (i % 3) {
      case 0:
        // Simple assignment (1 operator: =)
        operation = `attribute${i} = ${valueKey}`;
        expressionAttributeValues[valueKey] = `value${i}`;
        break;
      case 1:
        // Addition (2 operators: = and +)
        operation = `attribute${i} = attribute${i} + ${valueKey}`;
        expressionAttributeValues[valueKey] = i;
        break;
      case 2:
        // Conditional assignment with if_not_exists (2 operators: = and if_not_exists)
        operation = `attribute${i} = if_not_exists(attribute${i}, ${valueKey})`;
        expressionAttributeValues[valueKey] = i * 10;
        break;
    }
    
    setOperations.push(operation);
  }
  
  // Create the update expression
  const updateExpression = `SET ${setOperations.join(", ")}`;
  
  // Calculate the operator count
  // Each operation has 1-2 operators as noted above
  let operatorCount = 0;
  for (let i = 0; i < operationsCount; i++) {
    operatorCount += (i % 3 === 0) ? 1 : 2;
  }
  
  return {
    updateExpression,
    expressionAttributeValues,
    operatorCount
  };
}

/**
 * Test the operator limit by attempting an operation with a complex expression.
 * 
 * This function demonstrates what happens when an expression approaches or
 * exceeds the 300 operator limit.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {number} operatorCount - Target number of operators to include
 * @returns {Promise<Object>} - Result of the operation attempt
 */
async function testOperatorLimit(
  config,
  tableName,
  key,
  operatorCount
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Create a complex update expression with the specified operator count
  const { updateExpression, expressionAttributeValues, operatorCount: actualCount } = 
    createComplexUpdateExpression(Math.ceil(operatorCount / 1.5)); // Adjust to get close to target count
  
  console.log(`Generated update expression with approximately ${actualCount} operators`);
  
  // Define the update parameters
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: updateExpression,
    ExpressionAttributeValues: expressionAttributeValues,
    ReturnValues: "UPDATED_NEW"
  };
  
  try {
    // Attempt the update operation
    const response = await docClient.send(new UpdateCommand(params));
    return {
      success: true,
      message: `Operation succeeded with ${actualCount} operators`,
      data: response
    };
  } catch (error) {
    // Check if the error is due to exceeding the operator limit
    if (error.name === "ValidationException" && 
        error.message.includes("too many operators")) {
      return {
        success: false,
        message: `Operation failed: ${error.message}`,
        operatorCount: actualCount
      };
    }
    
    // Return other errors
    return {
      success: false,
      message: `Operation failed: ${error.message}`,
      error
    };
  }
}

/**
 * Break down a complex expression into multiple simpler operations.
 * 
 * This function demonstrates how to handle expressions that would exceed
 * the 300 operator limit by breaking them into multiple operations.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {number} totalOperations - Total number of operations to perform
 * @returns {Promise<Object>} - Result of the operations
 */
async function breakDownComplexExpression(
  config,
  tableName,
  key,
  totalOperations
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Calculate how many operations we can safely include in each batch
  // Using 150 as a conservative limit (well below 300)
  const operationsPerBatch = 100;
  const batchCount = Math.ceil(totalOperations / operationsPerBatch);
  
  console.log(`Breaking down ${totalOperations} operations into ${batchCount} batches`);
  
  const results = [];
  
  // Process each batch
  for (let batch = 0; batch < batchCount; batch++) {
    // Calculate the operations for this batch
    const batchStart = batch * operationsPerBatch;
    const batchEnd = Math.min(batchStart + operationsPerBatch, totalOperations);
    const batchSize = batchEnd - batchStart;
    
    console.log(`Processing batch ${batch + 1}/${batchCount} with ${batchSize} operations`);
    
    // Create an update expression for this batch
    const { updateExpression, expressionAttributeValues, operatorCount } = 
      createComplexUpdateExpression(batchSize);
    
    // Define the update parameters
    const params = {
      TableName: tableName,
      Key: key,
      UpdateExpression: updateExpression,
      ExpressionAttributeValues: expressionAttributeValues,
      ReturnValues: "UPDATED_NEW"
    };
    
    try {
      // Perform the update operation for this batch
      const response = await docClient.send(new UpdateCommand(params));
      
      results.push({
        batch: batch + 1,
        success: true,
        operatorCount,
        attributes: response.Attributes
      });
    } catch (error) {
      results.push({
        batch: batch + 1,
        success: false,
        operatorCount,
        error: error.message
      });
      
      // Stop processing if an error occurs
      break;
    }
  }
  
  return {
    totalBatches: batchCount,
    results
  };
}

/**
 * Count operators in a DynamoDB expression based on the rules in the documentation.
 * 
 * This function demonstrates how operators are counted according to the
 * DynamoDB documentation.
 * 
 * @param {string} expression - The DynamoDB expression to analyze
 * @returns {Object} - Breakdown of operator counts
 */
function countOperatorsInExpression(expression) {
  // Initialize counters for different operator types
  const counts = {
    comparisonOperators: 0,
    logicalOperators: 0,
    functions: 0,
    arithmeticOperators: 0,
    specialOperators: 0,
    total: 0
  };
  
  // Count comparison operators (=, <>, <, <=, >, >=)
  const comparisonRegex = /[^<>]=[^=]|<>|<=|>=|[^<]>[^=]|[^>]<[^=]/g;
  const comparisonMatches = expression.match(comparisonRegex) || [];
  counts.comparisonOperators = comparisonMatches.length;
  
  // Count logical operators (AND, OR, NOT)
  const andMatches = expression.match(/\bAND\b/g) || [];
  const orMatches = expression.match(/\bOR\b/g) || [];
  const notMatches = expression.match(/\bNOT\b/g) || [];
  counts.logicalOperators = andMatches.length + orMatches.length + notMatches.length;
  
  // Count functions (attribute_exists, attribute_not_exists, attribute_type, begins_with, contains, size)
  const functionRegex = /\b(attribute_exists|attribute_not_exists|attribute_type|begins_with|contains|size|if_not_exists)\(/g;
  const functionMatches = expression.match(functionRegex) || [];
  counts.functions = functionMatches.length;
  
  // Count arithmetic operators (+ and -)
  const arithmeticMatches = expression.match(/[a-zA-Z0-9_)\]]\s*[\+\-]\s*[a-zA-Z0-9_(:]/g) || [];
  counts.arithmeticOperators = arithmeticMatches.length;
  
  // Count special operators (BETWEEN, IN)
  const betweenMatches = expression.match(/\bBETWEEN\b/g) || [];
  const inMatches = expression.match(/\bIN\b/g) || [];
  counts.specialOperators = betweenMatches.length + inMatches.length;
  
  // Add extra operators for BETWEEN (each BETWEEN includes an AND)
  counts.logicalOperators += betweenMatches.length;
  
  // Calculate total
  counts.total = counts.comparisonOperators + 
                 counts.logicalOperators + 
                 counts.functions + 
                 counts.arithmeticOperators + 
                 counts.specialOperators;
  
  return counts;
}
```
でカウントする式演算子の使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to work with expression operator counting.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "Products";
  const key = { ProductId: "P12345" };
  
  console.log("Demonstrating DynamoDB expression operator counting and the 300 operator limit");
  
  try {
    // Example 1: Analyze a simple expression
    console.log("\nExample 1: Analyzing a simple expression");
    const simpleExpression = "Price = :price AND Rating > :rating AND Category IN (:cat1, :cat2, :cat3)";
    const simpleCount = countOperatorsInExpression(simpleExpression);
    
    console.log(`Expression: ${simpleExpression}`);
    console.log("Operator count breakdown:");
    console.log(`- Comparison operators: ${simpleCount.comparisonOperators}`);
    console.log(`- Logical operators: ${simpleCount.logicalOperators}`);
    console.log(`- Functions: ${simpleCount.functions}`);
    console.log(`- Arithmetic operators: ${simpleCount.arithmeticOperators}`);
    console.log(`- Special operators: ${simpleCount.specialOperators}`);
    console.log(`- Total operators: ${simpleCount.total}`);
    
    // Example 2: Analyze a complex expression
    console.log("\nExample 2: Analyzing a complex expression");
    const complexExpression = 
      "(attribute_exists(Category) AND Size BETWEEN :min AND :max) OR " +
      "(Price > :price AND contains(Description, :keyword) AND " +
      "(Rating >= :minRating OR Reviews > :minReviews))";
    const complexCount = countOperatorsInExpression(complexExpression);
    
    console.log(`Expression: ${complexExpression}`);
    console.log("Operator count breakdown:");
    console.log(`- Comparison operators: ${complexCount.comparisonOperators}`);
    console.log(`- Logical operators: ${complexCount.logicalOperators}`);
    console.log(`- Functions: ${complexCount.functions}`);
    console.log(`- Arithmetic operators: ${complexCount.arithmeticOperators}`);
    console.log(`- Special operators: ${complexCount.specialOperators}`);
    console.log(`- Total operators: ${complexCount.total}`);
    
    // Example 3: Test approaching the operator limit
    console.log("\nExample 3: Testing an expression approaching the operator limit");
    const approachingLimit = await testOperatorLimit(config, tableName, key, 290);
    console.log(approachingLimit.message);
    
    // Example 4: Test exceeding the operator limit
    console.log("\nExample 4: Testing an expression exceeding the operator limit");
    const exceedingLimit = await testOperatorLimit(config, tableName, key, 310);
    console.log(exceedingLimit.message);
    
    // Example 5: Breaking down a complex expression
    console.log("\nExample 5: Breaking down a complex expression into multiple operations");
    const breakdownResult = await breakDownComplexExpression(config, tableName, key, 500);
    console.log(`Processed ${breakdownResult.results.length} of ${breakdownResult.totalBatches} batches`);
    
    // Explain the operator counting rules
    console.log("\nKey points about DynamoDB expression operator counting:");
    console.log("1. The maximum number of operators in any expression is 300");
    console.log("2. Each comparison operator (=, <>, <, <=, >, >=) counts as 1 operator");
    console.log("3. Each logical operator (AND, OR, NOT) counts as 1 operator");
    console.log("4. Each function call (attribute_exists, contains, etc.) counts as 1 operator");
    console.log("5. Each arithmetic operator (+ or -) counts as 1 operator");
    console.log("6. BETWEEN counts as 2 operators (BETWEEN itself and the AND within it)");
    console.log("7. IN counts as 1 operator regardless of the number of values");
    console.log("8. Parentheses for grouping and attribute paths don't count as operators");
    console.log("9. When you exceed the limit, the error always reports '301 operators'");
    console.log("10. For complex operations, break them into multiple smaller operations");
    
  } catch (error) {
    console.error("Error:", error);
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_javascript_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for JavaScript (v3)**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo-asset-manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### ウォームスループットを有効にしたテーブルを作成する
<a name="dynamodb_CreateTableWarmThroughput_javascript_3_topic"></a>

次のコード例は、ウォームスループットを有効にしたテーブルを作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScriptを使用してウォームスループット設定を含む DynamoDB テーブルを作成します。  

```
import { DynamoDBClient, CreateTableCommand } from "@aws-sdk/client-dynamodb";

export async function createDynamoDBTableWithWarmThroughput(
  tableName,
  partitionKey,
  sortKey,
  miscKeyAttr,
  nonKeyAttr,
  tableProvisionedReadUnits,
  tableProvisionedWriteUnits,
  tableWarmReads,
  tableWarmWrites,
  indexName,
  indexProvisionedReadUnits,
  indexProvisionedWriteUnits,
  indexWarmReads,
  indexWarmWrites,
  region = "us-east-1"
) {
  try {
    const ddbClient = new DynamoDBClient({ region: region });
    const command = new CreateTableCommand({
      TableName: tableName,
      AttributeDefinitions: [
          { AttributeName: partitionKey, AttributeType: "S" },
          { AttributeName: sortKey, AttributeType: "S" },
          { AttributeName: miscKeyAttr, AttributeType: "N" },
      ],
      KeySchema: [
          { AttributeName: partitionKey, KeyType: "HASH" },
          { AttributeName: sortKey, KeyType: "RANGE" },
      ],
      ProvisionedThroughput: {
          ReadCapacityUnits: tableProvisionedReadUnits,
          WriteCapacityUnits: tableProvisionedWriteUnits,
      },
      WarmThroughput: {
          ReadUnitsPerSecond: tableWarmReads,
          WriteUnitsPerSecond: tableWarmWrites,
      },
      GlobalSecondaryIndexes: [
          {
            IndexName: indexName,
            KeySchema: [
                { AttributeName: sortKey, KeyType: "HASH" },
                { AttributeName: miscKeyAttr, KeyType: "RANGE" },
            ],
            Projection: {
                ProjectionType: "INCLUDE",
                NonKeyAttributes: [nonKeyAttr],
            },
            ProvisionedThroughput: {
                ReadCapacityUnits: indexProvisionedReadUnits,
                WriteCapacityUnits: indexProvisionedWriteUnits,
            },
            WarmThroughput: {
                ReadUnitsPerSecond: indexWarmReads,
                WriteUnitsPerSecond: indexWarmWrites,
            },
          },
      ],
    });
    const response = await ddbClient.send(command);
    console.log(response);
    return response;
  } catch (error) {
    console.error(`Error creating table: ${error}`);
    throw error;
  }
}

// Example usage (commented out for testing)
/*
createDynamoDBTableWithWarmThroughput(
  'example-table',
  'pk',
  'sk',
  'gsiKey',
  'data',
  10, 10, 5, 5,
  'example-index',
  5, 5, 2, 2
);
*/
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/CreateTableCommand)」を参照してください。

### TTL を含む項目を作成する
<a name="dynamodb_PutItemTTL_javascript_3_topic"></a>

次のコード例は、TTL を含む項目の作成方法を示しています。

**SDK for JavaScript (v3)**  

```
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";

export function createDynamoDBItem(table_name, region, partition_key, sort_key) {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    // Get the current time in epoch second format
    const current_time = Math.floor(new Date().getTime() / 1000);

    // Calculate the expireAt time (90 days from now) in epoch second format
    const expire_at = Math.floor((new Date().getTime() + 90 * 24 * 60 * 60 * 1000) / 1000);

    // Create DynamoDB item
    const item = {
        'partitionKey': {'S': partition_key},
        'sortKey': {'S': sort_key},
        'createdAt': {'N': current_time.toString()},
        'expireAt': {'N': expire_at.toString()}
    };

    const putItemCommand = new PutItemCommand({
        TableName: table_name,
        Item: item,
        ProvisionedThroughput: {
            ReadCapacityUnits: 1,
            WriteCapacityUnits: 1,
        },
    });

    client.send(putItemCommand, function(err, data) {
        if (err) {
            console.log("Exception encountered when creating item %s, here's what happened: ", data, err);
            throw err;
        } else {
            console.log("Item created successfully: %s.", data);
            return data;
        }
    });
}

// Example usage (commented out for testing)
// createDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)」を参照してください。

### PartiQL DELETE を使用してデータを削除する
<a name="dynamodb_PartiQLDelete_javascript_3_topic"></a>

次のコード例は、PartiQL DELETE ステートメントを使用してデータを削除する方法を示しています。

**SDK for JavaScript (v3)**  
PartiQL DELETE ステートメントを使用して、DynamoDB テーブルから項目を削除します AWS SDK for JavaScript。  

```
/**
 * This example demonstrates how to delete items from a DynamoDB table using PartiQL.
 * It shows different ways to delete documents with various index types.
 */
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  DynamoDBDocumentClient,
  ExecuteStatementCommand,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

/**
 * Delete a single item by its partition key using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @returns The response from the ExecuteStatementCommand
 */
export const deleteItemByPartitionKey = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `DELETE FROM "${tableName}" WHERE ${partitionKeyName} = ?`,
    Parameters: [partitionKeyValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item deleted successfully");
    return data;
  } catch (err) {
    console.error("Error deleting item:", err);
    throw err;
  }
};

/**
 * Delete an item by its composite key (partition key + sort key) using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @param sortKeyName - The name of the sort key attribute
 * @param sortKeyValue - The value of the sort key
 * @returns The response from the ExecuteStatementCommand
 */
export const deleteItemByCompositeKey = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number,
  sortKeyName: string,
  sortKeyValue: string | number
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `DELETE FROM "${tableName}" WHERE ${partitionKeyName} = ? AND ${sortKeyName} = ?`,
    Parameters: [partitionKeyValue, sortKeyValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item deleted successfully");
    return data;
  } catch (err) {
    console.error("Error deleting item:", err);
    throw err;
  }
};

/**
 * Delete an item with a condition to ensure the delete only happens if a condition is met.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @param conditionAttribute - The attribute to check in the condition
 * @param conditionValue - The value to compare against in the condition
 * @returns The response from the ExecuteStatementCommand
 */
export const deleteItemWithCondition = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number,
  conditionAttribute: string,
  conditionValue: any
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `DELETE FROM "${tableName}" WHERE ${partitionKeyName} = ? AND ${conditionAttribute} = ?`,
    Parameters: [partitionKeyValue, conditionValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item deleted with condition successfully");
    return data;
  } catch (err) {
    console.error("Error deleting item with condition:", err);
    throw err;
  }
};

/**
 * Batch delete multiple items using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param keys - Array of objects containing key information
 * @returns The response from the BatchExecuteStatementCommand
 */
export const batchDeleteItems = async (
  tableName: string,
  keys: Array<{
    partitionKeyName: string;
    partitionKeyValue: string | number;
    sortKeyName?: string;
    sortKeyValue?: string | number;
  }>
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  // Create statements for each delete
  const statements = keys.map((key) => {
    if (key.sortKeyName && key.sortKeyValue !== undefined) {
      return {
        Statement: `DELETE FROM "${tableName}" WHERE ${key.partitionKeyName} = ? AND ${key.sortKeyName} = ?`,
        Parameters: [key.partitionKeyValue, key.sortKeyValue],
      };
    } else {
      return {
        Statement: `DELETE FROM "${tableName}" WHERE ${key.partitionKeyName} = ?`,
        Parameters: [key.partitionKeyValue],
      };
    }
  });

  const params = {
    Statements: statements,
  };

  try {
    const data = await docClient.send(new BatchExecuteStatementCommand(params));
    console.log("Items batch deleted successfully");
    return data;
  } catch (err) {
    console.error("Error batch deleting items:", err);
    throw err;
  }
};

/**
 * Delete multiple items that match a filter condition.
 * Note: This performs a scan operation which can be expensive on large tables.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param filterAttribute - The attribute to filter on
 * @param filterValue - The value to filter by
 * @returns The response from the ExecuteStatementCommand
 */
export const deleteItemsByFilter = async (
  tableName: string,
  filterAttribute: string,
  filterValue: any
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `DELETE FROM "${tableName}" WHERE ${filterAttribute} = ?`,
    Parameters: [filterValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Items deleted by filter successfully");
    return data;
  } catch (err) {
    console.error("Error deleting items by filter:", err);
    throw err;
  }
};

/**
 * Example usage showing how to delete items with different index types
 */
export const deleteExamples = async () => {
  // Delete an item by partition key (simple primary key)
  await deleteItemByPartitionKey("UsersTable", "userId", "user123");

  // Delete an item by composite key (partition key + sort key)
  await deleteItemByCompositeKey(
    "OrdersTable",
    "orderId",
    "order456",
    "productId",
    "prod789"
  );

  // Delete with a condition
  await deleteItemWithCondition(
    "UsersTable",
    "userId",
    "user789",
    "userStatus",
    "inactive"
  );

  // Batch delete multiple items
  await batchDeleteItems("UsersTable", [
    { partitionKeyName: "userId", partitionKeyValue: "user234" },
    { partitionKeyName: "userId", partitionKeyValue: "user345" },
  ]);

  // Batch delete items with composite keys
  await batchDeleteItems("OrdersTable", [
    {
      partitionKeyName: "orderId",
      partitionKeyValue: "order567",
      sortKeyName: "productId",
      sortKeyValue: "prod123",
    },
    {
      partitionKeyName: "orderId",
      partitionKeyValue: "order678",
      sortKeyName: "productId",
      sortKeyValue: "prod456",
    },
  ]);

  // Delete items by filter (use with caution)
  await deleteItemsByFilter("UsersTable", "userStatus", "deleted");
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [BatchExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchExecuteStatementCommand)
  + [ExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ExecuteStatementCommand)

### PartiQL INSERT を使用してデータを挿入する
<a name="dynamodb_PartiQLInsert_javascript_3_topic"></a>

次のコード例は、PartiQL INSERT ステートメントを使用してデータを挿入する方法を示しています。

**SDK for JavaScript (v3)**  
PartiQL INSERT ステートメントを使用して、DynamoDB テーブルに項目を挿入します AWS SDK for JavaScript。  

```
/**
 * This example demonstrates how to insert items into a DynamoDB table using PartiQL.
 * It shows different ways to insert documents with various index types.
 */
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  DynamoDBDocumentClient,
  ExecuteStatementCommand,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

/**
 * Insert a single item into a DynamoDB table using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param item - The item to insert
 * @returns The response from the ExecuteStatementCommand
 */
export const insertItem = async (tableName: string, item: Record<string, any>) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  // Convert the item to a string representation for PartiQL
  const itemString = JSON.stringify(item).replace(/"([^"]+)":/g, '$1:');

  const params = {
    Statement: `INSERT INTO "${tableName}" VALUE ${itemString}`,
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item inserted successfully");
    return data;
  } catch (err) {
    console.error("Error inserting item:", err);
    throw err;
  }
};

/**
 * Insert multiple items into a DynamoDB table using PartiQL batch operation.
 * This is more efficient than inserting items one by one.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param items - Array of items to insert
 * @returns The response from the BatchExecuteStatementCommand
 */
export const batchInsertItems = async (tableName: string, items: Record<string, any>[]) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  // Create statements for each item
  const statements = items.map((item) => {
    const itemString = JSON.stringify(item).replace(/"([^"]+)":/g, '$1:');
    return {
      Statement: `INSERT INTO "${tableName}" VALUE ${itemString}`,
    };
  });

  const params = {
    Statements: statements,
  };

  try {
    const data = await docClient.send(new BatchExecuteStatementCommand(params));
    console.log("Items inserted successfully");
    return data;
  } catch (err) {
    console.error("Error batch inserting items:", err);
    throw err;
  }
};

/**
 * Insert an item with a condition to prevent overwriting existing items.
 * This is useful for ensuring you don't accidentally overwrite data.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param item - The item to insert
 * @param partitionKeyName - The name of the partition key attribute
 * @returns The response from the ExecuteStatementCommand
 */
export const insertItemWithCondition = async (
  tableName: string,
  item: Record<string, any>,
  partitionKeyName: string
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const itemString = JSON.stringify(item).replace(/"([^"]+)":/g, '$1:');
  const partitionKeyValue = JSON.stringify(item[partitionKeyName]);

  const params = {
    Statement: `INSERT INTO "${tableName}" VALUE ${itemString} WHERE attribute_not_exists(${partitionKeyName})`,
    Parameters: [{ S: partitionKeyValue }],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item inserted with condition successfully");
    return data;
  } catch (err) {
    console.error("Error inserting item with condition:", err);
    throw err;
  }
};

/**
 * Example usage showing how to insert items with different index types
 */
export const insertExamples = async () => {
  // Example table with a simple primary key (just partition key)
  const simpleKeyItem = {
    userId: "user123",
    name: "John Doe",
    email: "john@example.com",
  };
  await insertItem("UsersTable", simpleKeyItem);

  // Example table with composite key (partition key + sort key)
  const compositeKeyItem = {
    orderId: "order456",
    productId: "prod789",
    quantity: 2,
    price: 29.99,
  };
  await insertItem("OrdersTable", compositeKeyItem);

  // Example with Global Secondary Index (GSI)
  // The GSI might be on the email attribute
  const gsiItem = {
    userId: "user789",
    email: "jane@example.com",
    name: "Jane Smith",
    userType: "premium",  // This could be part of a GSI
  };
  await insertItem("UsersTable", gsiItem);

  // Example with Local Secondary Index (LSI)
  // LSI uses the same partition key but different sort key
  const lsiItem = {
    orderId: "order567",  // Partition key
    productId: "prod123", // Sort key for the table
    orderDate: "2023-11-15", // Potential sort key for an LSI
    quantity: 1,
    price: 19.99,
  };
  await insertItem("OrdersTable", lsiItem);

  // Batch insert example with multiple items
  const batchItems = [
    {
      userId: "user234",
      name: "Alice Johnson",
      email: "alice@example.com",
    },
    {
      userId: "user345",
      name: "Bob Williams",
      email: "bob@example.com",
    },
  ];
  await batchInsertItems("UsersTable", batchItems);
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [BatchExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchExecuteStatementCommand)
  + [ExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ExecuteStatementCommand)

### ブラウザからの Lambda 関数の呼び出し
<a name="cross_LambdaForBrowser_javascript_3_topic"></a>

次のコード例は、ブラウザから AWS Lambda 関数を呼び出す方法を示しています。

**SDK for JavaScript (v3)**  
 AWS Lambda 関数を使用して Amazon DynamoDB テーブルをユーザー選択で更新するブラウザベースのアプリケーションを作成できます。このアプリは v3 AWS SDK for JavaScript を使用します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-for-browser) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda

### 高度なクエリオペレーションを実行する
<a name="dynamodb_Scenario_AdvancedQueryTechniques_javascript_3_topic"></a>

次のコード例は、DynamoDB で高度なクエリオペレーションを実行する方法を示しています。
+ さまざまなフィルタリングと条件の手法を使用してテーブルをクエリします。
+ 大きな結果セットのページ分割を実装します。
+ 代替アクセスパターンにはグローバルセカンダリインデックスを使用します。
+ アプリケーション要件に基づいて整合性コントロールを適用します。

**SDK for JavaScript (v3)**  
を使用した強力な整合性のある読み取りによるクエリ AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table with configurable read consistency
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {boolean} useConsistentRead - Whether to use strongly consistent reads
 * @returns {Promise<Object>} - The query response
 */
async function queryWithConsistentRead(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  useConsistentRead = false
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "#pk = :pkValue",
      ExpressionAttributeNames: {
        "#pk": partitionKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue }
      },
      ConsistentRead: useConsistentRead
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with consistent read: ${error}`);
    throw error;
  }
}
```
でグローバルセカンダリインデックスを使用してクエリを実行します AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table using the primary key
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} userId - The user ID to query by (partition key)
 * @returns {Promise<Object>} - The query response
 */
async function queryTable(
  config,
  tableName,
  userId
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input for the base table
    const input = {
      TableName: tableName,
      KeyConditionExpression: "user_id = :userId",
      ExpressionAttributeValues: {
        ":userId": { S: userId }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying table: ${error}`);
    throw error;
  }
}

/**
 * Queries a DynamoDB Global Secondary Index (GSI)
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} indexName - The name of the GSI to query
 * @param {string} gameId - The game ID to query by (GSI partition key)
 * @returns {Promise<Object>} - The query response
 */
async function queryGSI(
  config,
  tableName,
  indexName,
  gameId
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input for the GSI
    const input = {
      TableName: tableName,
      IndexName: indexName,
      KeyConditionExpression: "game_id = :gameId",
      ExpressionAttributeValues: {
        ":gameId": { S: gameId }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying GSI: ${error}`);
    throw error;
  }
}
```
を使用してページ分割でクエリを実行します AWS SDK for JavaScript。  

```
/**
 * Example demonstrating how to handle large query result sets in DynamoDB using pagination
 * 
 * This example shows:
 * - How to use pagination to handle large result sets
 * - How to use LastEvaluatedKey to retrieve the next page of results
 * - How to construct subsequent query requests using ExclusiveStartKey
 */
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table with pagination to handle large result sets
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {number} pageSize - Number of items per page
 * @returns {Promise<Array>} - All items from the query
 */
async function queryWithPagination(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  pageSize = 25
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);
    
    // Initialize variables for pagination
    let lastEvaluatedKey = undefined;
    const allItems = [];
    let pageCount = 0;
    
    // Loop until all pages are retrieved
    do {
      // Construct the query input
      const input = {
        TableName: tableName,
        KeyConditionExpression: "#pk = :pkValue",
        Limit: pageSize,
        ExpressionAttributeNames: {
          "#pk": partitionKeyName
        },
        ExpressionAttributeValues: {
          ":pkValue": { S: partitionKeyValue }
        }
      };
      
      // Add ExclusiveStartKey if we have a LastEvaluatedKey from a previous query
      if (lastEvaluatedKey) {
        input.ExclusiveStartKey = lastEvaluatedKey;
      }
      
      // Execute the query
      const command = new QueryCommand(input);
      const response = await client.send(command);
      
      // Process the current page of results
      pageCount++;
      console.log(`Processing page ${pageCount} with ${response.Items.length} items`);
      
      // Add the items from this page to our collection
      if (response.Items && response.Items.length > 0) {
        allItems.push(...response.Items);
      }
      
      // Get the LastEvaluatedKey for the next page
      lastEvaluatedKey = response.LastEvaluatedKey;
      
    } while (lastEvaluatedKey); // Continue until there are no more pages
    
    console.log(`Query complete. Retrieved ${allItems.length} items in ${pageCount} pages.`);
    return allItems;
  } catch (error) {
    console.error(`Error querying with pagination: ${error}`);
    throw error;
  }
}

/**
 * Example usage:
 * 
 * // Query all items in the "AWS DynamoDB" forum with pagination
 * const allItems = await queryWithPagination(
 *   { region: "us-west-2" },
 *   "ForumThreads",
 *   "ForumName",
 *   "AWS DynamoDB",
 *   25 // 25 items per page
 * );
 * 
 * console.log(`Total items retrieved: ${allItems.length}`);
 * 
 * // Notes on pagination:
 * // - LastEvaluatedKey contains the primary key of the last evaluated item
 * // - When LastEvaluatedKey is undefined/null, there are no more items to retrieve
 * // - ExclusiveStartKey tells DynamoDB where to start the next page
 * // - Pagination helps manage memory usage for large result sets
 * // - Each page requires a separate network request to DynamoDB
 */

module.exports = { queryWithPagination };
```
を使用して複雑なフィルターでクエリを実行します AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table with a complex filter expression
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {number|string} minViews - Minimum number of views for filtering
 * @param {number|string} minReplies - Minimum number of replies for filtering
 * @param {string} requiredTag - Tag that must be present in the item's tags set
 * @returns {Promise<Object>} - The query response
 */
async function queryWithComplexFilter(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  minViews,
  minReplies,
  requiredTag
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "#pk = :pkValue",
      FilterExpression: "views >= :minViews AND replies >= :minReplies AND contains(tags, :tag)",
      ExpressionAttributeNames: {
        "#pk": partitionKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue },
        ":minViews": { N: minViews.toString() },
        ":minReplies": { N: minReplies.toString() },
        ":tag": { S: requiredTag }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with complex filter: ${error}`);
    throw error;
  }
}
```
を使用して動的に構築されたフィルター式でクエリを実行します AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

async function queryWithDynamicFilter(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  sortKeyName,
  sortKeyValue,
  filterParams = {}
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Initialize filter expression components
    let filterExpressions = [];
    const expressionAttributeValues = {
      ":pkValue": { S: partitionKeyValue },
      ":skValue": { S: sortKeyValue }
    };
    const expressionAttributeNames = {
      "#pk": partitionKeyName,
      "#sk": sortKeyName
    };

    // Add status filter if provided
    if (filterParams.status) {
      filterExpressions.push("status = :status");
      expressionAttributeValues[":status"] = { S: filterParams.status };
    }

    // Add minimum views filter if provided
    if (filterParams.minViews !== undefined) {
      filterExpressions.push("views >= :minViews");
      expressionAttributeValues[":minViews"] = { N: filterParams.minViews.toString() };
    }

    // Add author filter if provided
    if (filterParams.author) {
      filterExpressions.push("author = :author");
      expressionAttributeValues[":author"] = { S: filterParams.author };
    }

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "#pk = :pkValue AND #sk = :skValue"
    };

    // Add filter expression if any filters were provided
    if (filterExpressions.length > 0) {
      input.FilterExpression = filterExpressions.join(" AND ");
    }

    // Add expression attribute names and values
    input.ExpressionAttributeNames = expressionAttributeNames;
    input.ExpressionAttributeValues = expressionAttributeValues;

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with dynamic filter: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### リストオペレーションを実行する
<a name="dynamodb_Scenario_ListOperations_javascript_3_topic"></a>

次のコード例は、DynamoDB でリストオペレーションを実行する方法を示しています。
+ リスト属性に要素を追加します。
+ リスト属性から要素を削除します。
+ インデックスでリスト内の特定の要素を更新します。
+ リスト追加関数およびリストインデックス関数を使用します。

**SDK for JavaScript (v3)**  
を使用してリストオペレーションをデモンストレーションします AWS SDK for JavaScript。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  GetCommand,
  PutCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Append elements to a list attribute.
 * 
 * This function demonstrates how to use the list_append function to add elements
 * to the end of a list.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} listName - The name of the list attribute
 * @param {Array} values - The values to append to the list
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function appendToList(
  config,
  tableName,
  key,
  listName,
  values
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using list_append
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${listName} = list_append(if_not_exists(${listName}, :empty_list), :values)`,
    ExpressionAttributeValues: {
      ":empty_list": [],
      ":values": values
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Prepend elements to a list attribute.
 * 
 * This function demonstrates how to use the list_append function to add elements
 * to the beginning of a list.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} listName - The name of the list attribute
 * @param {Array} values - The values to prepend to the list
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function prependToList(
  config,
  tableName,
  key,
  listName,
  values
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using list_append
  // Note: To prepend, we put the new values first in the list_append function
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${listName} = list_append(:values, if_not_exists(${listName}, :empty_list))`,
    ExpressionAttributeValues: {
      ":empty_list": [],
      ":values": values
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Update a specific element in a list by index.
 * 
 * This function demonstrates how to update a specific element in a list
 * using the index notation.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} listName - The name of the list attribute
 * @param {number} index - The index of the element to update
 * @param {any} value - The new value for the element
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateListElement(
  config,
  tableName,
  key,
  listName,
  index,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using index notation
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${listName}[${index}] = :value`,
    ExpressionAttributeValues: {
      ":value": value
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Remove an element from a list by index.
 * 
 * This function demonstrates how to remove a specific element from a list
 * using the REMOVE action with index notation.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} listName - The name of the list attribute
 * @param {number} index - The index of the element to remove
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function removeListElement(
  config,
  tableName,
  key,
  listName,
  index
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using REMOVE with index notation
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `REMOVE ${listName}[${index}]`,
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Concatenate two lists.
 * 
 * This function demonstrates how to concatenate two lists using the list_append function.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} listName1 - The name of the first list attribute
 * @param {string} listName2 - The name of the second list attribute
 * @param {string} resultListName - The name of the attribute to store the concatenated list
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function concatenateLists(
  config,
  tableName,
  key,
  listName1,
  listName2,
  resultListName
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using list_append
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${resultListName} = list_append(if_not_exists(${listName1}, :empty_list), if_not_exists(${listName2}, :empty_list))`,
    ExpressionAttributeValues: {
      ":empty_list": []
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Create a nested list structure.
 * 
 * This function demonstrates how to create and work with nested lists.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} listName - The name of the list attribute
 * @param {Array} nestedLists - An array of arrays to create a nested list structure
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function createNestedList(
  config,
  tableName,
  key,
  listName,
  nestedLists
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters to create a nested list
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${listName} = :nested_lists`,
    ExpressionAttributeValues: {
      ":nested_lists": nestedLists
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Update an element in a nested list.
 * 
 * This function demonstrates how to update an element in a nested list
 * using multiple index notations.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} listName - The name of the list attribute
 * @param {number} outerIndex - The index in the outer list
 * @param {number} innerIndex - The index in the inner list
 * @param {any} value - The new value for the element
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateNestedListElement(
  config,
  tableName,
  key,
  listName,
  outerIndex,
  innerIndex,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using multiple index notations
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${listName}[${outerIndex}][${innerIndex}] = :value`,
    ExpressionAttributeValues: {
      ":value": value
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Get the current value of an item.
 * 
 * Helper function to retrieve the current value of an item.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to get
 * @returns {Promise<Object|null>} - The item or null if not found
 */
async function getItem(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the get parameters
  const params = {
    TableName: tableName,
    Key: key
  };
  
  // Perform the get operation
  const response = await docClient.send(new GetCommand(params));
  
  // Return the item if it exists, otherwise null
  return response.Item || null;
}
```
でのリストオペレーションの使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to work with lists in DynamoDB.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "UserProfiles";
  const key = { UserId: "U12345" };
  
  console.log("Demonstrating list operations in DynamoDB");
  
  try {
    // Example 1: Append elements to a list
    console.log("\nExample 1: Appending elements to a list");
    const response1 = await appendToList(
      config,
      tableName,
      key,
      "RecentSearches",
      ["laptop", "headphones", "monitor"]
    );
    
    console.log("Appended to list:", response1.Attributes);
    
    // Example 2: Prepend elements to a list
    console.log("\nExample 2: Prepending elements to a list");
    const response2 = await prependToList(
      config,
      tableName,
      key,
      "RecentSearches",
      ["keyboard", "mouse"]
    );
    
    console.log("Prepended to list:", response2.Attributes);
    
    // Get the current state of the item
    let currentItem = await getItem(config, tableName, key);
    console.log("\nCurrent state of RecentSearches:", currentItem?.RecentSearches);
    
    // Example 3: Update a specific element in a list
    console.log("\nExample 3: Updating a specific element in a list");
    const response3 = await updateListElement(
      config,
      tableName,
      key,
      "RecentSearches",
      0, // Update the first element
      "mechanical keyboard" // New value
    );
    
    console.log("Updated list element:", response3.Attributes);
    
    // Example 4: Remove an element from a list
    console.log("\nExample 4: Removing an element from a list");
    const response4 = await removeListElement(
      config,
      tableName,
      key,
      "RecentSearches",
      2 // Remove the third element
    );
    
    console.log("List after removing element:", response4.Attributes);
    
    // Example 5: Create and concatenate lists
    console.log("\nExample 5: Creating and concatenating lists");
    
    // First, create two separate lists
    await updateWithMultipleActions(
      config,
      tableName,
      key,
      "SET WishList = :wishlist, SavedItems = :saveditems",
      null,
      {
        ":wishlist": ["gaming laptop", "wireless earbuds"],
        ":saveditems": ["smartphone", "tablet"]
      }
    );
    
    // Then, concatenate them
    const response5 = await concatenateLists(
      config,
      tableName,
      key,
      "WishList",
      "SavedItems",
      "AllItems"
    );
    
    console.log("Concatenated lists:", response5.Attributes);
    
    // Example 6: Create a nested list structure
    console.log("\nExample 6: Creating a nested list structure");
    const response6 = await createNestedList(
      config,
      tableName,
      key,
      "Categories",
      [
        ["Electronics", "Computers", "Accessories"],
        ["Books", "Magazines", "E-books"],
        ["Clothing", "Shoes", "Watches"]
      ]
    );
    
    console.log("Created nested list:", response6.Attributes);
    
    // Example 7: Update an element in a nested list
    console.log("\nExample 7: Updating an element in a nested list");
    const response7 = await updateNestedListElement(
      config,
      tableName,
      key,
      "Categories",
      0, // First inner list
      1, // Second element in that list
      "Laptops" // New value
    );
    
    console.log("Updated nested list element:", response7.Attributes);
    
    // Get the final state of the item
    currentItem = await getItem(config, tableName, key);
    console.log("\nFinal state of the item:", JSON.stringify(currentItem, null, 2));
    
    // Explain list operations
    console.log("\nKey points about list operations in DynamoDB:");
    console.log("1. Use list_append to add elements to a list");
    console.log("2. To append elements, use list_append(existingList, newElements)");
    console.log("3. To prepend elements, use list_append(newElements, existingList)");
    console.log("4. Use if_not_exists to handle cases where the list might not exist yet");
    console.log("5. Use index notation (list[0]) to access or update specific elements");
    console.log("6. Use REMOVE with index notation to remove elements from a list");
    console.log("7. Lists can contain elements of different types");
    console.log("8. Lists can be nested (lists of lists)");
    console.log("9. Use multiple index notations (list[0][1]) to access nested list elements");
    
  } catch (error) {
    console.error("Error:", error);
  }
}

/**
 * Helper function for the examples.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} updateExpression - The update expression
 * @param {Object} expressionAttributeNames - Expression attribute name placeholders
 * @param {Object} expressionAttributeValues - Expression attribute value placeholders
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateWithMultipleActions(
  config,
  tableName,
  key,
  updateExpression,
  expressionAttributeNames,
  expressionAttributeValues
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Prepare the update parameters
  const updateParams = {
    TableName: tableName,
    Key: key,
    UpdateExpression: updateExpression,
    ReturnValues: "UPDATED_NEW"
  };
  
  // Add expression attribute names if provided
  if (expressionAttributeNames) {
    updateParams.ExpressionAttributeNames = expressionAttributeNames;
  }
  
  // Add expression attribute values if provided
  if (expressionAttributeValues) {
    updateParams.ExpressionAttributeValues = expressionAttributeValues;
  }
  
  // Execute the update
  const response = await docClient.send(new UpdateCommand(updateParams));
  
  return response;
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### マップオペレーションを実行する
<a name="dynamodb_Scenario_MapOperations_javascript_3_topic"></a>

次のコード例は、DynamoDB でマップオペレーションを実行する方法を示しています。
+ マップ構造にネストされた属性を追加および更新します。
+ マップから特定のフィールドを削除します。
+ 深くネストされたマップ属性を操作します。

**SDK for JavaScript (v3)**  
を使用してマップオペレーションをデモンストレーションします AWS SDK for JavaScript。  

```
/**
 * Example of updating map attributes in DynamoDB.
 * 
 * This module demonstrates how to update map attributes that may not exist,
 * how to update nested attributes, and how to handle various map update scenarios.
 */

const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  GetCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Update a map attribute safely, handling the case where the map might not exist.
 * 
 * This function demonstrates using the if_not_exists function to safely update
 * a map attribute that might not exist yet.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} mapName - The name of the map attribute
 * @param {string} mapKey - The key within the map to update
 * @param {any} value - The value to set
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateMapAttributeSafe(
  config,
  tableName,
  key,
  mapName,
  mapKey,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using SET with if_not_exists
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${mapName}.${mapKey} = :value`,
    ExpressionAttributeValues: {
      ":value": value
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  try {
    // Perform the update operation
    const response = await docClient.send(new UpdateCommand(params));
    return response;
  } catch (error) {
    // If the error is because the map doesn't exist, create it
    if (error.name === "ValidationException" && 
        error.message.includes("The document path provided in the update expression is invalid")) {
      
      // Create the map with the specified key-value pair
      const createParams = {
        TableName: tableName,
        Key: key,
        UpdateExpression: `SET ${mapName} = :map`,
        ExpressionAttributeValues: {
          ":map": { [mapKey]: value }
        },
        ReturnValues: "UPDATED_NEW"
      };
      
      return await docClient.send(new UpdateCommand(createParams));
    }
    
    // Re-throw other errors
    throw error;
  }
}

/**
 * Update a map attribute using the if_not_exists function.
 * 
 * This function demonstrates a more elegant approach using if_not_exists
 * to handle the case where the map doesn't exist yet.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} mapName - The name of the map attribute
 * @param {string} mapKey - The key within the map to update
 * @param {any} value - The value to set
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateMapAttributeWithIfNotExists(
  config,
  tableName,
  key,
  mapName,
  mapKey,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using SET with if_not_exists
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${mapName} = if_not_exists(${mapName}, :emptyMap), ${mapName}.${mapKey} = :value`,
    ExpressionAttributeValues: {
      ":emptyMap": {},
      ":value": value
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Add a value to a deeply nested map, creating parent maps if they don't exist.
 * 
 * This function demonstrates how to update a deeply nested attribute,
 * creating any parent maps that don't exist along the way.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string[]} path - The path to the nested attribute as an array of keys
 * @param {any} value - The value to set
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function addToNestedMap(
  config,
  tableName,
  key,
  path,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Build the update expression and expression attribute values
  let updateExpression = "SET";
  const expressionAttributeValues = {};
  
  // For each level in the path, create a map if it doesn't exist
  for (let i = 0; i < path.length; i++) {
    const currentPath = path.slice(0, i + 1).join(".");
    const parentPath = i > 0 ? path.slice(0, i).join(".") : null;
    
    if (parentPath) {
      updateExpression += ` ${parentPath} = if_not_exists(${parentPath}, :emptyMap${i}),`;
      expressionAttributeValues[`:emptyMap${i}`] = {};
    }
  }
  
  // Set the final value
  const fullPath = path.join(".");
  updateExpression += ` ${fullPath} = :value`;
  expressionAttributeValues[":value"] = value;
  
  // Define the update parameters
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: updateExpression,
    ExpressionAttributeValues: expressionAttributeValues,
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Update multiple fields in a map attribute in a single operation.
 * 
 * This function demonstrates how to update multiple fields in a map
 * in a single DynamoDB operation.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} mapName - The name of the map attribute
 * @param {Object} updates - Object containing key-value pairs to update
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateMultipleMapFields(
  config,
  tableName,
  key,
  mapName,
  updates
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Build the update expression and expression attribute values
  let updateExpression = `SET ${mapName} = if_not_exists(${mapName}, :emptyMap)`;
  const expressionAttributeValues = {
    ":emptyMap": {}
  };
  
  // Add each update to the expression
  Object.entries(updates).forEach(([field, value], index) => {
    updateExpression += `, ${mapName}.${field} = :val${index}`;
    expressionAttributeValues[`:val${index}`] = value;
  });
  
  // Define the update parameters
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: updateExpression,
    ExpressionAttributeValues: expressionAttributeValues,
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Get the current value of an item.
 * 
 * Helper function to retrieve the current value of an item.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to get
 * @returns {Promise<Object|null>} - The item or null if not found
 */
async function getItem(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the get parameters
  const params = {
    TableName: tableName,
    Key: key
  };
  
  // Perform the get operation
  const response = await docClient.send(new GetCommand(params));
  
  // Return the item if it exists, otherwise null
  return response.Item || null;
}

/**
 * Example of how to use the map attribute update functions.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "Users";
  const key = { UserId: "U12345" };
  
  console.log("Demonstrating different approaches to update map attributes in DynamoDB");
  
  try {
    // Example 1: Update a map attribute that might not exist (two-step approach)
    console.log("\nExample 1: Updating a map attribute that might not exist (two-step approach)");
    const response1 = await updateMapAttributeSafe(
      config,
      tableName,
      key,
      "Preferences",
      "Theme",
      "Dark"
    );
    
    console.log("Updated preferences:", response1.Attributes);
    
    // Example 2: Update a map attribute using if_not_exists (elegant approach)
    console.log("\nExample 2: Updating a map attribute using if_not_exists (elegant approach)");
    const response2 = await updateMapAttributeWithIfNotExists(
      config,
      tableName,
      key,
      "Settings",
      "NotificationsEnabled",
      true
    );
    
    console.log("Updated settings:", response2.Attributes);
    
    // Example 3: Update a deeply nested attribute
    console.log("\nExample 3: Updating a deeply nested attribute");
    const response3 = await addToNestedMap(
      config,
      tableName,
      key,
      ["Profile", "Address", "City"],
      "Seattle"
    );
    
    console.log("Updated nested attribute:", response3.Attributes);
    
    // Example 4: Update multiple fields in a map
    console.log("\nExample 4: Updating multiple fields in a map");
    const response4 = await updateMultipleMapFields(
      config,
      tableName,
      key,
      "ContactInfo",
      {
        Email: "user@example.com",
        Phone: "555-123-4567",
        PreferredContact: "Email"
      }
    );
    
    console.log("Updated multiple fields:", response4.Attributes);
    
    // Get the final state of the item
    console.log("\nFinal state of the item:");
    const item = await getItem(config, tableName, key);
    console.log(JSON.stringify(item, null, 2));
    
    // Explain the benefits of different approaches
    console.log("\nKey points about updating map attributes:");
    console.log("1. Use if_not_exists to handle maps that might not exist");
    console.log("2. Multiple updates can be combined in a single operation");
    console.log("3. Deeply nested attributes require creating parent maps");
    console.log("4. DynamoDB expressions are atomic - the entire update succeeds or fails");
    console.log("5. Using a single operation is more efficient than multiple separate updates");
    
  } catch (error) {
    console.error("Error:", error);
  }
}

// Export the functions
module.exports = {
  updateMapAttributeSafe,
  updateMapAttributeWithIfNotExists,
  addToNestedMap,
  updateMultipleMapFields,
  getItem,
  exampleUsage
};

// Run the example if this file is executed directly
if (require.main === module) {
  exampleUsage();
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### セットオペレーションを実行する
<a name="dynamodb_Scenario_SetOperations_javascript_3_topic"></a>

次のコード例は、DynamoDB でセットオペレーションを実行する方法を示しています。
+ セット属性に要素を追加します。
+ セット属性から要素を削除します。
+ セットで ADD および DELETE オペレーションを使用します。

**SDK for JavaScript (v3)**  
を使用してセットオペレーションをデモンストレーションします AWS SDK for JavaScript。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  GetCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Add elements to a set attribute.
 * 
 * This function demonstrates using the ADD operation to add elements to a set.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} setName - The name of the set attribute
 * @param {Array} values - The values to add to the set
 * @param {string} setType - The type of set ('string', 'number', or 'binary')
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function addToSet(
  config,
  tableName,
  key,
  setName,
  values,
  setType = 'string'
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Create the appropriate set type
  let setValues;
  if (setType === 'string') {
    setValues = new Set(values.map(String));
  } else if (setType === 'number') {
    setValues = new Set(values.map(Number));
  } else if (setType === 'binary') {
    setValues = new Set(values);
  } else {
    throw new Error(`Unsupported set type: ${setType}`);
  }
  
  // Define the update parameters using ADD
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `ADD ${setName} :values`,
    ExpressionAttributeValues: {
      ":values": setValues
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Remove elements from a set attribute.
 * 
 * This function demonstrates using the DELETE operation to remove elements from a set.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} setName - The name of the set attribute
 * @param {Array} values - The values to remove from the set
 * @param {string} setType - The type of set ('string', 'number', or 'binary')
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function removeFromSet(
  config,
  tableName,
  key,
  setName,
  values,
  setType = 'string'
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Create the appropriate set type
  let setValues;
  if (setType === 'string') {
    setValues = new Set(values.map(String));
  } else if (setType === 'number') {
    setValues = new Set(values.map(Number));
  } else if (setType === 'binary') {
    setValues = new Set(values);
  } else {
    throw new Error(`Unsupported set type: ${setType}`);
  }
  
  // Define the update parameters using DELETE
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `DELETE ${setName} :values`,
    ExpressionAttributeValues: {
      ":values": setValues
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Create a new set attribute with initial values.
 * 
 * This function demonstrates using the SET operation to create a new set attribute.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} setName - The name of the set attribute
 * @param {Array} values - The initial values for the set
 * @param {string} setType - The type of set ('string', 'number', or 'binary')
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function createSet(
  config,
  tableName,
  key,
  setName,
  values,
  setType = 'string'
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Create the appropriate set type
  let setValues;
  if (setType === 'string') {
    setValues = new Set(values.map(String));
  } else if (setType === 'number') {
    setValues = new Set(values.map(Number));
  } else if (setType === 'binary') {
    setValues = new Set(values);
  } else {
    throw new Error(`Unsupported set type: ${setType}`);
  }
  
  // Define the update parameters using SET
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${setName} = :values`,
    ExpressionAttributeValues: {
      ":values": setValues
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Replace an entire set attribute with a new set of values.
 * 
 * This function demonstrates using the SET operation to replace an entire set.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} setName - The name of the set attribute
 * @param {Array} values - The new values for the set
 * @param {string} setType - The type of set ('string', 'number', or 'binary')
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function replaceSet(
  config,
  tableName,
  key,
  setName,
  values,
  setType = 'string'
) {
  // This is the same as createSet, but included for clarity of intent
  return await createSet(config, tableName, key, setName, values, setType);
}

/**
 * Remove the last element from a set and handle the empty set case.
 * 
 * This function demonstrates what happens when you delete the last element of a set.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} setName - The name of the set attribute
 * @returns {Promise<Object>} - The result of the operation
 */
async function removeLastElementFromSet(
  config,
  tableName,
  key,
  setName
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // First, get the current item to check the set
  const currentItem = await getItem(config, tableName, key);
  
  // Check if the set exists and has elements
  if (!currentItem || !currentItem[setName] || currentItem[setName].size === 0) {
    return {
      success: false,
      message: "Set doesn't exist or is already empty",
      item: currentItem
    };
  }
  
  // Get the set values
  const setValues = Array.from(currentItem[setName]);
  
  // If there's only one element left, remove the attribute entirely
  if (setValues.length === 1) {
    // Define the update parameters to remove the attribute
    const params = {
      TableName: tableName,
      Key: key,
      UpdateExpression: `REMOVE ${setName}`,
      ReturnValues: "UPDATED_NEW"
    };
    
    // Perform the update operation
    await docClient.send(new UpdateCommand(params));
    
    return {
      success: true,
      message: "Last element removed, attribute has been deleted",
      removedValue: setValues[0]
    };
  } else {
    // Otherwise, remove just the last element
    // Create a set with just the last element
    const lastElement = setValues[setValues.length - 1];
    const setType = typeof lastElement === 'number' ? 'number' : 'string';
    
    // Remove the last element
    const response = await removeFromSet(
      config,
      tableName,
      key,
      setName,
      [lastElement],
      setType
    );
    
    return {
      success: true,
      message: "Last element removed, set still contains elements",
      removedValue: lastElement,
      remainingSet: response.Attributes[setName]
    };
  }
}

/**
 * Get the current value of an item.
 * 
 * Helper function to retrieve the current value of an item.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to get
 * @returns {Promise<Object|null>} - The item or null if not found
 */
async function getItem(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the get parameters
  const params = {
    TableName: tableName,
    Key: key
  };
  
  // Perform the get operation
  const response = await docClient.send(new GetCommand(params));
  
  // Return the item if it exists, otherwise null
  return response.Item || null;
}
```
でのセットオペレーションの使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to work with sets in DynamoDB.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "Users";
  const key = { UserId: "U12345" };
  
  console.log("Demonstrating set operations in DynamoDB");
  
  try {
    // Example 1: Create a string set
    console.log("\nExample 1: Creating a string set");
    const response1 = await createSet(
      config,
      tableName,
      key,
      "Interests",
      ["Reading", "Hiking", "Cooking"],
      "string"
    );
    
    console.log("Created set:", response1.Attributes);
    
    // Example 2: Add elements to a set
    console.log("\nExample 2: Adding elements to a set");
    const response2 = await addToSet(
      config,
      tableName,
      key,
      "Interests",
      ["Photography", "Travel"],
      "string"
    );
    
    console.log("Updated set after adding elements:", response2.Attributes);
    
    // Example 3: Remove elements from a set
    console.log("\nExample 3: Removing elements from a set");
    const response3 = await removeFromSet(
      config,
      tableName,
      key,
      "Interests",
      ["Cooking"],
      "string"
    );
    
    console.log("Updated set after removing elements:", response3.Attributes);
    
    // Example 4: Create a number set
    console.log("\nExample 4: Creating a number set");
    const response4 = await createSet(
      config,
      tableName,
      key,
      "FavoriteNumbers",
      [7, 42, 99],
      "number"
    );
    
    console.log("Created number set:", response4.Attributes);
    
    // Example 5: Replace an entire set
    console.log("\nExample 5: Replacing an entire set");
    const response5 = await replaceSet(
      config,
      tableName,
      key,
      "Interests",
      ["Gaming", "Movies", "Music"],
      "string"
    );
    
    console.log("Replaced set:", response5.Attributes);
    
    // Example 6: Remove the last element from a set
    console.log("\nExample 6: Removing the last element from a set");
    
    // First, create a set with just one element
    await createSet(
      config,
      tableName,
      { UserId: "U67890" },
      "Tags",
      ["LastTag"],
      "string"
    );
    
    // Then, remove the last element
    const response6 = await removeLastElementFromSet(
      config,
      tableName,
      { UserId: "U67890" },
      "Tags"
    );
    
    console.log(response6.message);
    console.log("Removed value:", response6.removedValue);
    
    // Get the final state of the items
    console.log("\nFinal state of the items:");
    const item1 = await getItem(config, tableName, key);
    console.log("User U12345:", JSON.stringify(item1, null, 2));
    
    const item2 = await getItem(config, tableName, { UserId: "U67890" });
    console.log("User U67890:", JSON.stringify(item2, null, 2));
    
    // Explain set operations
    console.log("\nKey points about set operations in DynamoDB:");
    console.log("1. Use ADD to add elements to a set (duplicates are automatically removed)");
    console.log("2. Use DELETE to remove elements from a set");
    console.log("3. Use SET to create a new set or replace an existing one");
    console.log("4. DynamoDB supports three types of sets: string sets, number sets, and binary sets");
    console.log("5. When you delete the last element from a set, the attribute remains as an empty set");
    console.log("6. To remove an empty set, use the REMOVE operation");
    console.log("7. Sets automatically maintain unique values (no duplicates)");
    console.log("8. You cannot mix data types within a set");
    
  } catch (error) {
    console.error("Error:", error);
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_javascript_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
PartiQL ステートメントのバッチを実行します。  

```
import {
  BillingMode,
  CreateTableCommand,
  DeleteTableCommand,
  DescribeTableCommand,
  DynamoDBClient,
  waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";
import {
  DynamoDBDocumentClient,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";
import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

const log = (msg) => console.log(`[SCENARIO] ${msg}`);
const tableName = "Cities";

export const main = async (confirmAll = false) => {
  /**
   * Delete table if it exists.
   */
  try {
    await client.send(new DescribeTableCommand({ TableName: tableName }));
    // If no error was thrown, the table exists.
    const input = new ScenarioInput(
      "deleteTable",
      `A table named ${tableName} already exists. If you choose not to delete
this table, the scenario cannot continue. Delete it?`,
      { type: "confirm", confirmAll },
    );
    const deleteTable = await input.handle({}, { confirmAll });
    if (deleteTable) {
      await client.send(new DeleteTableCommand({ tableName }));
    } else {
      console.warn(
        "Scenario could not run. Either delete ${tableName} or provide a unique table name.",
      );
      return;
    }
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "ResourceNotFoundException"
    ) {
      // Do nothing. This means the table is not there.
    } else {
      throw caught;
    }
  }

  /**
   * Create a table.
   */

  log("Creating a table.");
  const createTableCommand = new CreateTableCommand({
    TableName: tableName,
    // This example performs a large write to the database.
    // Set the billing mode to PAY_PER_REQUEST to
    // avoid throttling the large write.
    BillingMode: BillingMode.PAY_PER_REQUEST,
    // Define the attributes that are necessary for the key schema.
    AttributeDefinitions: [
      {
        AttributeName: "name",
        // 'S' is a data type descriptor that represents a number type.
        // For a list of all data type descriptors, see the following link.
        // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors
        AttributeType: "S",
      },
    ],
    // The KeySchema defines the primary key. The primary key can be
    // a partition key, or a combination of a partition key and a sort key.
    // Key schema design is important. For more info, see
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html
    KeySchema: [{ AttributeName: "name", KeyType: "HASH" }],
  });
  await client.send(createTableCommand);
  log(`Table created: ${tableName}.`);

  /**
   * Wait until the table is active.
   */

  // This polls with DescribeTableCommand until the requested table is 'ACTIVE'.
  // You can't write to a table before it's active.
  log("Waiting for the table to be active.");
  await waitUntilTableExists({ client }, { TableName: tableName });
  log("Table active.");

  /**
   * Insert items.
   */

  log("Inserting cities into the table.");
  const addItemsStatementCommand = new BatchExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html
    Statements: [
      {
        Statement: `INSERT INTO ${tableName} value {'name':?, 'population':?}`,
        Parameters: ["Alachua", 10712],
      },
      {
        Statement: `INSERT INTO ${tableName} value {'name':?, 'population':?}`,
        Parameters: ["High Springs", 6415],
      },
    ],
  });
  await docClient.send(addItemsStatementCommand);
  log("Cities inserted.");

  /**
   * Select items.
   */

  log("Selecting cities from the table.");
  const selectItemsStatementCommand = new BatchExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html
    Statements: [
      {
        Statement: `SELECT * FROM ${tableName} WHERE name=?`,
        Parameters: ["Alachua"],
      },
      {
        Statement: `SELECT * FROM ${tableName} WHERE name=?`,
        Parameters: ["High Springs"],
      },
    ],
  });
  const selectItemResponse = await docClient.send(selectItemsStatementCommand);
  log(
    `Got cities: ${selectItemResponse.Responses.map(
      (r) => `${r.Item.name} (${r.Item.population})`,
    ).join(", ")}`,
  );

  /**
   * Update items.
   */

  log("Modifying the populations.");
  const updateItemStatementCommand = new BatchExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html
    Statements: [
      {
        Statement: `UPDATE ${tableName} SET population=? WHERE name=?`,
        Parameters: [10, "Alachua"],
      },
      {
        Statement: `UPDATE ${tableName} SET population=? WHERE name=?`,
        Parameters: [5, "High Springs"],
      },
    ],
  });
  await docClient.send(updateItemStatementCommand);
  log("Updated cities.");

  /**
   * Delete the items.
   */

  log("Deleting the cities.");
  const deleteItemStatementCommand = new BatchExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.delete.html
    Statements: [
      {
        Statement: `DELETE FROM ${tableName} WHERE name=?`,
        Parameters: ["Alachua"],
      },
      {
        Statement: `DELETE FROM ${tableName} WHERE name=?`,
        Parameters: ["High Springs"],
      },
    ],
  });
  await docClient.send(deleteItemStatementCommand);
  log("Cities deleted.");

  /**
   * Delete the table.
   */

  log("Deleting the table.");
  const deleteTableCommand = new DeleteTableCommand({ TableName: tableName });
  await client.send(deleteTableCommand);
  log("Table deleted.");
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[BatchExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchExecuteStatementCommand)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_javascript_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
単一の PartiQL ステートメントを実行します。  

```
import {
  BillingMode,
  CreateTableCommand,
  DeleteTableCommand,
  DescribeTableCommand,
  DynamoDBClient,
  waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";
import {
  DynamoDBDocumentClient,
  ExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";
import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario";

const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

const log = (msg) => console.log(`[SCENARIO] ${msg}`);
const tableName = "SingleOriginCoffees";

export const main = async (confirmAll = false) => {
  /**
   * Delete table if it exists.
   */
  try {
    await client.send(new DescribeTableCommand({ TableName: tableName }));
    // If no error was thrown, the table exists.
    const input = new ScenarioInput(
      "deleteTable",
      `A table named ${tableName} already exists. If you choose not to delete
this table, the scenario cannot continue. Delete it?`,
      { type: "confirm", confirmAll },
    );
    const deleteTable = await input.handle({});
    if (deleteTable) {
      await client.send(new DeleteTableCommand({ tableName }));
    } else {
      console.warn(
        "Scenario could not run. Either delete ${tableName} or provide a unique table name.",
      );
      return;
    }
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "ResourceNotFoundException"
    ) {
      // Do nothing. This means the table is not there.
    } else {
      throw caught;
    }
  }

  /**
   * Create a table.
   */

  log("Creating a table.");
  const createTableCommand = new CreateTableCommand({
    TableName: tableName,
    // This example performs a large write to the database.
    // Set the billing mode to PAY_PER_REQUEST to
    // avoid throttling the large write.
    BillingMode: BillingMode.PAY_PER_REQUEST,
    // Define the attributes that are necessary for the key schema.
    AttributeDefinitions: [
      {
        AttributeName: "varietal",
        // 'S' is a data type descriptor that represents a number type.
        // For a list of all data type descriptors, see the following link.
        // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors
        AttributeType: "S",
      },
    ],
    // The KeySchema defines the primary key. The primary key can be
    // a partition key, or a combination of a partition key and a sort key.
    // Key schema design is important. For more info, see
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html
    KeySchema: [{ AttributeName: "varietal", KeyType: "HASH" }],
  });
  await client.send(createTableCommand);
  log(`Table created: ${tableName}.`);

  /**
   * Wait until the table is active.
   */

  // This polls with DescribeTableCommand until the requested table is 'ACTIVE'.
  // You can't write to a table before it's active.
  log("Waiting for the table to be active.");
  await waitUntilTableExists({ client }, { TableName: tableName });
  log("Table active.");

  /**
   * Insert an item.
   */

  log("Inserting a coffee into the table.");
  const addItemStatementCommand = new ExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html
    Statement: `INSERT INTO ${tableName} value {'varietal':?, 'profile':?}`,
    Parameters: ["arabica", ["chocolate", "floral"]],
  });
  await client.send(addItemStatementCommand);
  log("Coffee inserted.");

  /**
   * Select an item.
   */

  log("Selecting the coffee from the table.");
  const selectItemStatementCommand = new ExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html
    Statement: `SELECT * FROM ${tableName} WHERE varietal=?`,
    Parameters: ["arabica"],
  });
  const selectItemResponse = await docClient.send(selectItemStatementCommand);
  log(`Got coffee: ${JSON.stringify(selectItemResponse.Items[0])}`);

  /**
   * Update the item.
   */

  log("Add a flavor profile to the coffee.");
  const updateItemStatementCommand = new ExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html
    Statement: `UPDATE ${tableName} SET profile=list_append(profile, ?) WHERE varietal=?`,
    Parameters: [["fruity"], "arabica"],
  });
  await client.send(updateItemStatementCommand);
  log("Updated coffee");

  /**
   * Delete the item.
   */

  log("Deleting the coffee.");
  const deleteItemStatementCommand = new ExecuteStatementCommand({
    // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.delete.html
    Statement: `DELETE FROM ${tableName} WHERE varietal=?`,
    Parameters: ["arabica"],
  });
  await docClient.send(deleteItemStatementCommand);
  log("Coffee deleted.");

  /**
   * Delete the table.
   */

  log("Deleting the table.");
  const deleteTableCommand = new DeleteTableCommand({ TableName: tableName });
  await client.send(deleteTableCommand);
  log("Table deleted.");
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ExecuteStatementCommand)」を参照してください。

### グローバルセカンダリインデックスを使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithGlobalSecondaryIndex_javascript_3_topic"></a>

以下のコード例は、グローバルセカンダリインデックスを使用してテーブルをクエリする方法を示しています。
+ プライマリキーを使用して DynamoDB テーブルをクエリします。
+ 代替アクセスパターンのグローバルセカンダリインデックス (GSI) をクエリします。
+ テーブルクエリと GSI クエリを比較します。

**SDK for JavaScript (v3)**  
でプライマリキーを使用して DynamoDB テーブルをクエリします AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table using the primary key
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} userId - The user ID to query by (partition key)
 * @returns {Promise<Object>} - The query response
 */
async function queryTable(
  config,
  tableName,
  userId
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input for the base table
    const input = {
      TableName: tableName,
      KeyConditionExpression: "user_id = :userId",
      ExpressionAttributeValues: {
        ":userId": { S: userId }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying table: ${error}`);
    throw error;
  }
}
```
を使用して DynamoDB グローバルセカンダリインデックス (GSI) をクエリします AWS SDK for JavaScript。  

```
/**
 * Queries a DynamoDB Global Secondary Index (GSI)
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} indexName - The name of the GSI to query
 * @param {string} gameId - The game ID to query by (GSI partition key)
 * @returns {Promise<Object>} - The query response
 */
async function queryGSI(
  config,
  tableName,
  indexName,
  gameId
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input for the GSI
    const input = {
      TableName: tableName,
      IndexName: indexName,
      KeyConditionExpression: "game_id = :gameId",
      ExpressionAttributeValues: {
        ":gameId": { S: gameId }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying GSI: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### begins\$1with 条件を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithBeginsWithCondition_javascript_3_topic"></a>

以下のコード例は、begins\$1with 条件を使用してテーブルをクエリする方法を示しています。
+ キー条件式で begins\$1with 関数を使用します。
+ ソートキーのプレフィックスパターンに基づいて項目をフィルタリングします。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScriptでソートキーの begins\$1with 条件を使用して DynamoDB テーブルをクエリします。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table for items where the sort key begins with a specific prefix
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {string} sortKeyName - The name of the sort key
 * @param {string} prefix - The prefix to match at the beginning of the sort key
 * @returns {Promise<Object>} - The query response
 */
async function queryWithBeginsWith(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  sortKeyName,
  prefix
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "#pk = :pkValue AND begins_with(#sk, :prefix)",
      ExpressionAttributeNames: {
        "#pk": partitionKeyName,
        "#sk": sortKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue },
        ":prefix": { S: prefix }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with begins_with: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### 日付範囲を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithDateRange_javascript_3_topic"></a>

以下のコード例は、ソートキーの日付範囲を使用してテーブルをクエリする方法を示しています。
+ 特定の日付範囲内の項目をクエリします。
+ 日付形式のソートキーで比較演算子を使用します。

**SDK for JavaScript (v3)**  
を使用して、日付範囲内の項目について DynamoDB テーブルをクエリします AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table for items within a specific date range on the sort key
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {string} sortKeyName - The name of the sort key (must be a date/time attribute)
 * @param {Date} startDate - The start date for the range query
 * @param {Date} endDate - The end date for the range query
 * @returns {Promise<Object>} - The query response
 */
async function queryByDateRangeOnSortKey(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  sortKeyName,
  startDate,
  endDate
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Format dates as ISO strings for DynamoDB
    const formattedStartDate = startDate.toISOString();
    const formattedEndDate = endDate.toISOString();

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: '#pk = :pkValue AND #sk BETWEEN :startDate AND :endDate',
      ExpressionAttributeNames: {
        "#pk": partitionKeyName,
        "#sk": sortKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue },
        ":startDate": { S: formattedStartDate },
        ":endDate": { S: formattedEndDate }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying by date range on sort key: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### 複雑なフィルター式を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithComplexFilter_javascript_3_topic"></a>

次のコード例は、複雑なフィルター式を使用してテーブルをクエリする方法を示しています。
+ 複雑なフィルター式をクエリ結果に適用します。
+ 論理演算子を使用して複数の条件を組み合わせます。
+ キー以外の属性に基づいて項目をフィルタリングします。

**SDK for JavaScript (v3)**  
を使用して、複雑なフィルター式で DynamoDB テーブルをクエリします AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table with a complex filter expression
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {number|string} minViews - Minimum number of views for filtering
 * @param {number|string} minReplies - Minimum number of replies for filtering
 * @param {string} requiredTag - Tag that must be present in the item's tags set
 * @returns {Promise<Object>} - The query response
 */
async function queryWithComplexFilter(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  minViews,
  minReplies,
  requiredTag
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "#pk = :pkValue",
      FilterExpression: "views >= :minViews AND replies >= :minReplies AND contains(tags, :tag)",
      ExpressionAttributeNames: {
        "#pk": partitionKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue },
        ":minViews": { N: minViews.toString() },
        ":minReplies": { N: minReplies.toString() },
        ":tag": { S: requiredTag }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with complex filter: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### 動的フィルター式を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithDynamicFilter_javascript_3_topic"></a>

以下のコード例は、動的フィルター式を使用してテーブルをクエリする方法を示しています。
+ ランタイムにフィルター式を動的に構築します。
+ ユーザー入力またはアプリケーション状態に基づいてフィルター条件を構築します。
+ 条件付きでフィルター条件を追加または削除します。

**SDK for JavaScript (v3)**  
を使用して動的に構築されたフィルター式を使用して DynamoDB テーブルをクエリします AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

async function queryWithDynamicFilter(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  sortKeyName,
  sortKeyValue,
  filterParams = {}
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Initialize filter expression components
    let filterExpressions = [];
    const expressionAttributeValues = {
      ":pkValue": { S: partitionKeyValue },
      ":skValue": { S: sortKeyValue }
    };
    const expressionAttributeNames = {
      "#pk": partitionKeyName,
      "#sk": sortKeyName
    };

    // Add status filter if provided
    if (filterParams.status) {
      filterExpressions.push("status = :status");
      expressionAttributeValues[":status"] = { S: filterParams.status };
    }

    // Add minimum views filter if provided
    if (filterParams.minViews !== undefined) {
      filterExpressions.push("views >= :minViews");
      expressionAttributeValues[":minViews"] = { N: filterParams.minViews.toString() };
    }

    // Add author filter if provided
    if (filterParams.author) {
      filterExpressions.push("author = :author");
      expressionAttributeValues[":author"] = { S: filterParams.author };
    }

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "#pk = :pkValue AND #sk = :skValue"
    };

    // Add filter expression if any filters were provided
    if (filterExpressions.length > 0) {
      input.FilterExpression = filterExpressions.join(" AND ");
    }

    // Add expression attribute names and values
    input.ExpressionAttributeNames = expressionAttributeNames;
    input.ExpressionAttributeValues = expressionAttributeValues;

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with dynamic filter: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### ネストされた属性を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithNestedAttributes_javascript_3_topic"></a>

以下のコード例は、ネストされた属性を使用してテーブルをクエリする方法を示しています。
+ DynamoDB 項目のネストされた属性を使用してアクセスおよびフィルタリングします。
+ ネストされた要素を参照するには、ドキュメントパス式を使用します。

**SDK for JavaScript (v3)**  
を使用して、ネストされた属性を持つ DynamoDB テーブルをクエリします AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table filtering on a nested attribute
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} productId - The product ID to query by (partition key)
 * @param {string} category - The category to filter by (nested attribute)
 * @returns {Promise<Object>} - The query response
 */
async function queryWithNestedAttribute(
  config,
  tableName,
  productId,
  category
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "product_id = :productId",
      FilterExpression: "details.category = :category",
      ExpressionAttributeValues: {
        ":productId": { S: productId },
        ":category": { S: category }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with nested attribute: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### ページ分割を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithPagination_javascript_3_topic"></a>

以下のコード例は、ページ分割を使用してテーブルをクエリする方法を示しています。
+ DynamoDB クエリ結果のページ分割を実装します。
+ LastEvaluatedKey を使用して後続のページを取得します。
+ Limit パラメータを使用して、ページあたりの項目数を制御します。

**SDK for JavaScript (v3)**  
を使用してページ分割で DynamoDB テーブルをクエリします AWS SDK for JavaScript。  

```
/**
 * Example demonstrating how to handle large query result sets in DynamoDB using pagination
 * 
 * This example shows:
 * - How to use pagination to handle large result sets
 * - How to use LastEvaluatedKey to retrieve the next page of results
 * - How to construct subsequent query requests using ExclusiveStartKey
 */
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table with pagination to handle large result sets
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {number} pageSize - Number of items per page
 * @returns {Promise<Array>} - All items from the query
 */
async function queryWithPagination(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  pageSize = 25
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);
    
    // Initialize variables for pagination
    let lastEvaluatedKey = undefined;
    const allItems = [];
    let pageCount = 0;
    
    // Loop until all pages are retrieved
    do {
      // Construct the query input
      const input = {
        TableName: tableName,
        KeyConditionExpression: "#pk = :pkValue",
        Limit: pageSize,
        ExpressionAttributeNames: {
          "#pk": partitionKeyName
        },
        ExpressionAttributeValues: {
          ":pkValue": { S: partitionKeyValue }
        }
      };
      
      // Add ExclusiveStartKey if we have a LastEvaluatedKey from a previous query
      if (lastEvaluatedKey) {
        input.ExclusiveStartKey = lastEvaluatedKey;
      }
      
      // Execute the query
      const command = new QueryCommand(input);
      const response = await client.send(command);
      
      // Process the current page of results
      pageCount++;
      console.log(`Processing page ${pageCount} with ${response.Items.length} items`);
      
      // Add the items from this page to our collection
      if (response.Items && response.Items.length > 0) {
        allItems.push(...response.Items);
      }
      
      // Get the LastEvaluatedKey for the next page
      lastEvaluatedKey = response.LastEvaluatedKey;
      
    } while (lastEvaluatedKey); // Continue until there are no more pages
    
    console.log(`Query complete. Retrieved ${allItems.length} items in ${pageCount} pages.`);
    return allItems;
  } catch (error) {
    console.error(`Error querying with pagination: ${error}`);
    throw error;
  }
}

/**
 * Example usage:
 * 
 * // Query all items in the "AWS DynamoDB" forum with pagination
 * const allItems = await queryWithPagination(
 *   { region: "us-west-2" },
 *   "ForumThreads",
 *   "ForumName",
 *   "AWS DynamoDB",
 *   25 // 25 items per page
 * );
 * 
 * console.log(`Total items retrieved: ${allItems.length}`);
 * 
 * // Notes on pagination:
 * // - LastEvaluatedKey contains the primary key of the last evaluated item
 * // - When LastEvaluatedKey is undefined/null, there are no more items to retrieve
 * // - ExclusiveStartKey tells DynamoDB where to start the next page
 * // - Pagination helps manage memory usage for large result sets
 * // - Each page requires a separate network request to DynamoDB
 */

module.exports = { queryWithPagination };
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### 強力な整合性のある読み込みを使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithStronglyConsistentReads_javascript_3_topic"></a>

次のコード例は、強力な整合性のある読み込みを使用してテーブルをクエリする方法を示しています。
+ DynamoDB クエリの整合性レベルを設定します。
+ 強力な整合性のある読み込みを使用して最新のデータを取得します。
+ 結果整合性と強力な整合性のトレードオフを理解します。

**SDK for JavaScript (v3)**  
を使用して、設定可能な読み取り整合性で DynamoDB テーブルをクエリします AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table with configurable read consistency
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {boolean} useConsistentRead - Whether to use strongly consistent reads
 * @returns {Promise<Object>} - The query response
 */
async function queryWithConsistentRead(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  useConsistentRead = false
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: "#pk = :pkValue",
      ExpressionAttributeNames: {
        "#pk": partitionKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue }
      },
      ConsistentRead: useConsistentRead
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying with consistent read: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### PartiQL SELECT を使用してデータをクエリする
<a name="dynamodb_PartiQLSelect_javascript_3_topic"></a>

次のコード例は、PartiQL SELECT ステートメントを使用してデータをクエリする方法を示しています。

**SDK for JavaScript (v3)**  
PartiQL SELECT ステートメントを使用して、DynamoDB テーブルから項目をクエリします AWS SDK for JavaScript。  

```
/**
 * This example demonstrates how to query items from a DynamoDB table using PartiQL.
 * It shows different ways to select data with various index types.
 */
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  DynamoDBDocumentClient,
  ExecuteStatementCommand,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

/**
 * Select all items from a DynamoDB table using PartiQL.
 * Note: This should be used with caution on large tables.
 * 
 * @param tableName - The name of the DynamoDB table
 * @returns The response from the ExecuteStatementCommand
 */
export const selectAllItems = async (tableName: string) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `SELECT * FROM "${tableName}"`,
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Items retrieved successfully");
    return data;
  } catch (err) {
    console.error("Error retrieving items:", err);
    throw err;
  }
};

/**
 * Select an item by its primary key using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @returns The response from the ExecuteStatementCommand
 */
export const selectItemByPartitionKey = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `SELECT * FROM "${tableName}" WHERE ${partitionKeyName} = ?`,
    Parameters: [partitionKeyValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item retrieved successfully");
    return data;
  } catch (err) {
    console.error("Error retrieving item:", err);
    throw err;
  }
};

/**
 * Select an item by its composite key (partition key + sort key) using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @param sortKeyName - The name of the sort key attribute
 * @param sortKeyValue - The value of the sort key
 * @returns The response from the ExecuteStatementCommand
 */
export const selectItemByCompositeKey = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number,
  sortKeyName: string,
  sortKeyValue: string | number
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `SELECT * FROM "${tableName}" WHERE ${partitionKeyName} = ? AND ${sortKeyName} = ?`,
    Parameters: [partitionKeyValue, sortKeyValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item retrieved successfully");
    return data;
  } catch (err) {
    console.error("Error retrieving item:", err);
    throw err;
  }
};

/**
 * Select items using a filter condition with PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param filterAttribute - The attribute to filter on
 * @param filterValue - The value to filter by
 * @returns The response from the ExecuteStatementCommand
 */
export const selectItemsWithFilter = async (
  tableName: string,
  filterAttribute: string,
  filterValue: string | number
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `SELECT * FROM "${tableName}" WHERE ${filterAttribute} = ?`,
    Parameters: [filterValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Items retrieved successfully");
    return data;
  } catch (err) {
    console.error("Error retrieving items:", err);
    throw err;
  }
};

/**
 * Select items using a begins_with function for prefix matching.
 * This is useful for querying hierarchical data.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param attributeName - The attribute to check for prefix
 * @param prefix - The prefix to match
 * @returns The response from the ExecuteStatementCommand
 */
export const selectItemsByPrefix = async (
  tableName: string,
  attributeName: string,
  prefix: string
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `SELECT * FROM "${tableName}" WHERE begins_with(${attributeName}, ?)`,
    Parameters: [prefix],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Items retrieved successfully");
    return data;
  } catch (err) {
    console.error("Error retrieving items:", err);
    throw err;
  }
};

/**
 * Select items using a between condition for range queries.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param attributeName - The attribute to check for range
 * @param startValue - The start value of the range
 * @param endValue - The end value of the range
 * @returns The response from the ExecuteStatementCommand
 */
export const selectItemsByRange = async (
  tableName: string,
  attributeName: string,
  startValue: number | string,
  endValue: number | string
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `SELECT * FROM "${tableName}" WHERE ${attributeName} BETWEEN ? AND ?`,
    Parameters: [startValue, endValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Items retrieved successfully");
    return data;
  } catch (err) {
    console.error("Error retrieving items:", err);
    throw err;
  }
};

/**
 * Example usage showing how to select items with different index types
 */
export const selectExamples = async () => {
  // Select all items from a table (use with caution on large tables)
  await selectAllItems("UsersTable");

  // Select by partition key (simple primary key)
  await selectItemByPartitionKey("UsersTable", "userId", "user123");

  // Select by composite key (partition key + sort key)
  await selectItemByCompositeKey("OrdersTable", "orderId", "order456", "productId", "prod789");

  // Select with a filter condition (can use any attribute)
  await selectItemsWithFilter("UsersTable", "userType", "premium");

  // Select items with a prefix (useful for hierarchical data)
  await selectItemsByPrefix("ProductsTable", "category", "electronics");

  // Select items within a range (useful for numeric or date ranges)
  await selectItemsByRange("OrdersTable", "orderDate", "2023-01-01", "2023-12-31");
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [BatchExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchExecuteStatementCommand)
  + [ExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ExecuteStatementCommand)

### TTL 項目のクエリ
<a name="dynamodb_QueryFilteredTTL_javascript_3_topic"></a>

以下のコード例は、TTL 項目のクエリの開始方法を示しています。

**SDK for JavaScript (v3)**  
を使用して DynamoDB テーブルに TTL 項目を収集するためにフィルタリングされた式をクエリします AWS SDK for JavaScript。  

```
import { DynamoDBClient, QueryCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";

export const queryFiltered = async (tableName, primaryKey, region = 'us-east-1') => {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const currentTime = Math.floor(Date.now() / 1000);

    const params = {
        TableName: tableName,
        KeyConditionExpression: "#pk = :pk",
        FilterExpression: "#ea > :ea",
        ExpressionAttributeNames: {
            "#pk": "primaryKey",
            "#ea": "expireAt"
        },
        ExpressionAttributeValues: marshall({
            ":pk": primaryKey,
            ":ea": currentTime
        })
    };

    try {
        const { Items } = await client.send(new QueryCommand(params));
        Items.forEach(item => {
            console.log(unmarshall(item))
        });
        return Items;
    } catch (err) {
        console.error(`Error querying items: ${err}`);
        throw err;
    }
}

// Example usage (commented out for testing)
// queryFiltered('your-table-name', 'your-partition-key-value');
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### 日付と時刻のパターンを使用してテーブルをクエリする
<a name="dynamodb_Scenario_DateTimeQueries_javascript_3_topic"></a>

次のコード例は、日付と時刻のパターンを使用してテーブルをクエリする方法を示しています。
+ DynamoDB に日付/時刻値を保存してクエリします。
+ ソートキーを使用して日付範囲クエリを実装します。
+ 有効なクエリを行うために日付文字列をフォーマットします。

**SDK for JavaScript (v3)**  
でソートキーの日付範囲を使用してクエリを実行します AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table for items within a specific date range on the sort key
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {string} sortKeyName - The name of the sort key (must be a date/time attribute)
 * @param {Date} startDate - The start date for the range query
 * @param {Date} endDate - The end date for the range query
 * @returns {Promise<Object>} - The query response
 */
async function queryByDateRangeOnSortKey(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  sortKeyName,
  startDate,
  endDate
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Format dates as ISO strings for DynamoDB
    const formattedStartDate = startDate.toISOString();
    const formattedEndDate = endDate.toISOString();

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: '#pk = :pkValue AND #sk BETWEEN :startDate AND :endDate',
      ExpressionAttributeNames: {
        "#pk": partitionKeyName,
        "#sk": sortKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue },
        ":startDate": { S: formattedStartDate },
        ":endDate": { S: formattedEndDate }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying by date range on sort key: ${error}`);
    throw error;
  }
}
```
で日時変数を使用してクエリを実行します AWS SDK for JavaScript。  

```
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

/**
 * Queries a DynamoDB table for items within a specific date range
 * 
 * @param {Object} config - AWS SDK configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key
 * @param {string} partitionKeyValue - The value of the partition key
 * @param {string} dateKeyName - The name of the date attribute to filter on
 * @param {Date} startDate - The start date for the range query
 * @param {Date} endDate - The end date for the range query
 * @returns {Promise<Object>} - The query response
 */
async function queryByDateRange(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  dateKeyName,
  startDate,
  endDate
) {
  try {
    // Create DynamoDB client
    const client = new DynamoDBClient(config);

    // Format dates as ISO strings for DynamoDB
    const formattedStartDate = startDate.toISOString();
    const formattedEndDate = endDate.toISOString();

    // Construct the query input
    const input = {
      TableName: tableName,
      KeyConditionExpression: `#pk = :pkValue AND #dateAttr BETWEEN :startDate AND :endDate`,
      ExpressionAttributeNames: {
        "#pk": partitionKeyName,
        "#dateAttr": dateKeyName
      },
      ExpressionAttributeValues: {
        ":pkValue": { S: partitionKeyValue },
        ":startDate": { S: formattedStartDate },
        ":endDate": { S: formattedEndDate }
      }
    };

    // Execute the query
    const command = new QueryCommand(input);
    return await client.send(command);
  } catch (error) {
    console.error(`Error querying by date range: ${error}`);
    throw error;
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Query](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)」を参照してください。

### 式順序の更新を理解する
<a name="dynamodb_Scenario_UpdateExpressionOrder_javascript_3_topic"></a>

次のコード例は、式順序の更新を理解する方法を示しています。
+ DynamoDB が更新式を処理する方法について説明します。
+ 更新式のオペレーションの順序を理解します。
+ 式の評価を理解することで、予期しない結果を回避できます。

**SDK for JavaScript (v3)**  
を使用して式の更新順序をデモンストレーションします AWS SDK for JavaScript。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  GetCommand,
  PutCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Update an item with multiple actions in a single update expression.
 * 
 * This function demonstrates how to use multiple actions in a single update expression
 * and how DynamoDB processes these actions.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The primary key of the item to update
 * @param {string} updateExpression - The update expression with multiple actions
 * @param {Object} [expressionAttributeNames] - Expression attribute name placeholders
 * @param {Object} [expressionAttributeValues] - Expression attribute value placeholders
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateWithMultipleActions(
  config,
  tableName,
  key,
  updateExpression,
  expressionAttributeNames,
  expressionAttributeValues
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Prepare the update parameters
  const updateParams = {
    TableName: tableName,
    Key: key,
    UpdateExpression: updateExpression,
    ReturnValues: "UPDATED_NEW"
  };
  
  // Add expression attribute names if provided
  if (expressionAttributeNames) {
    updateParams.ExpressionAttributeNames = expressionAttributeNames;
  }
  
  // Add expression attribute values if provided
  if (expressionAttributeValues) {
    updateParams.ExpressionAttributeValues = expressionAttributeValues;
  }
  
  // Execute the update
  const response = await docClient.send(new UpdateCommand(updateParams));
  
  return response;
}

/**
 * Demonstrate that variables hold copies of existing values before modifications.
 * 
 * This function creates an item with initial values, then updates it with an expression
 * that uses the values of attributes before they are modified in the same expression.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The primary key of the item to create and update
 * @returns {Promise<Object>} - A dictionary containing the results of the demonstration
 */
async function demonstrateValueCopying(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Step 1: Create an item with initial values
  const initialItem = { ...key, a: 1, b: 2, c: 3 };
  
  await docClient.send(new PutCommand({
    TableName: tableName,
    Item: initialItem
  }));
  
  // Step 2: Get the item to verify initial state
  const responseBefore = await docClient.send(new GetCommand({
    TableName: tableName,
    Key: key
  }));
  
  const itemBefore = responseBefore.Item || {};
  
  // Step 3: Update the item with an expression that uses values before they are modified
  // This expression removes 'a', then sets 'b' to the value of 'a', and 'c' to the value of 'b'
  const updateResponse = await docClient.send(new UpdateCommand({
    TableName: tableName,
    Key: key,
    UpdateExpression: "REMOVE a SET b = a, c = b",
    ReturnValues: "UPDATED_NEW"
  }));
  
  // Step 4: Get the item to verify final state
  const responseAfter = await docClient.send(new GetCommand({
    TableName: tableName,
    Key: key
  }));
  
  const itemAfter = responseAfter.Item || {};
  
  // Return the results
  return {
    initialState: itemBefore,
    updateResponse: updateResponse,
    finalState: itemAfter
  };
}

/**
 * Demonstrate the order in which different action types are processed.
 * 
 * This function creates an item with initial values, then updates it with an expression
 * that includes multiple action types (SET, REMOVE, ADD, DELETE) to show the order
 * in which they are processed.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The primary key of the item to create and update
 * @returns {Promise<Object>} - A dictionary containing the results of the demonstration
 */
async function demonstrateActionOrder(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Step 1: Create an item with initial values
  const initialItem = {
    ...key,
    counter: 10,
    set_attr: new Set(["A", "B", "C"]),
    to_remove: "This will be removed",
    to_modify: "Original value"
  };
  
  await docClient.send(new PutCommand({
    TableName: tableName,
    Item: initialItem
  }));
  
  // Step 2: Get the item to verify initial state
  const responseBefore = await docClient.send(new GetCommand({
    TableName: tableName,
    Key: key
  }));
  
  const itemBefore = responseBefore.Item || {};
  
  // Step 3: Update the item with multiple action types
  // The actions will be processed in this order: REMOVE, SET, ADD, DELETE
  const updateResponse = await docClient.send(new UpdateCommand({
    TableName: tableName,
    Key: key,
    UpdateExpression: "REMOVE to_remove SET to_modify = :new_value ADD counter :increment DELETE set_attr :elements",
    ExpressionAttributeValues: {
      ":new_value": "Updated value",
      ":increment": 5,
      ":elements": new Set(["B"])
    },
    ReturnValues: "UPDATED_NEW"
  }));
  
  // Step 4: Get the item to verify final state
  const responseAfter = await docClient.send(new GetCommand({
    TableName: tableName,
    Key: key
  }));
  
  const itemAfter = responseAfter.Item || {};
  
  // Return the results
  return {
    initialState: itemBefore,
    updateResponse: updateResponse,
    finalState: itemAfter
  };
}

/**
 * Update multiple attributes with a single SET action.
 * 
 * This function demonstrates how to update multiple attributes in a single SET action,
 * which is more efficient than using multiple separate update operations.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The primary key of the item to update
 * @param {Object} attributes - The attributes to update and their new values
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateWithMultipleSetActions(
  config,
  tableName,
  key,
  attributes
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Build the update expression and expression attribute values
  let updateExpression = "SET ";
  const expressionAttributeValues = {};
  
  // Add each attribute to the update expression
  Object.entries(attributes).forEach(([attrName, attrValue], index) => {
    const valuePlaceholder = `:val${index}`;
    
    if (index > 0) {
      updateExpression += ", ";
    }
    updateExpression += `${attrName} = ${valuePlaceholder}`;
    
    expressionAttributeValues[valuePlaceholder] = attrValue;
  });
  
  // Execute the update
  const response = await docClient.send(new UpdateCommand({
    TableName: tableName,
    Key: key,
    UpdateExpression: updateExpression,
    ExpressionAttributeValues: expressionAttributeValues,
    ReturnValues: "UPDATED_NEW"
  }));
  
  return response;
}

/**
 * Update an attribute with a value from another attribute or a default value.
 * 
 * This function demonstrates how to use if_not_exists to conditionally copy a value
 * from one attribute to another, or use a default value if the source doesn't exist.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The primary key of the item to update
 * @param {string} sourceAttribute - The attribute to copy the value from
 * @param {string} targetAttribute - The attribute to update
 * @param {any} defaultValue - The default value to use if the source attribute doesn't exist
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateWithConditionalValueCopying(
  config,
  tableName,
  key,
  sourceAttribute,
  targetAttribute,
  defaultValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Use if_not_exists to conditionally copy the value
  const response = await docClient.send(new UpdateCommand({
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${targetAttribute} = if_not_exists(${sourceAttribute}, :default)`,
    ExpressionAttributeValues: {
      ":default": defaultValue
    },
    ReturnValues: "UPDATED_NEW"
  }));
  
  return response;
}

/**
 * Demonstrate complex update expressions with multiple operations on the same attribute.
 * 
 * This function shows how DynamoDB processes multiple operations on the same attribute
 * in a single update expression.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The primary key of the item to create and update
 * @returns {Promise<Object>} - A dictionary containing the results of the demonstration
 */
async function demonstrateMultipleOperationsOnSameAttribute(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Step 1: Create an item with initial values
  const initialItem = {
    ...key,
    counter: 10,
    list_attr: [1, 2, 3],
    map_attr: {
      nested1: "value1",
      nested2: "value2"
    }
  };
  
  await docClient.send(new PutCommand({
    TableName: tableName,
    Item: initialItem
  }));
  
  // Step 2: Get the item to verify initial state
  const responseBefore = await docClient.send(new GetCommand({
    TableName: tableName,
    Key: key
  }));
  
  const itemBefore = responseBefore.Item || {};
  
  // Step 3: Update the item with multiple operations on the same attributes
  const updateResponse = await docClient.send(new UpdateCommand({
    TableName: tableName,
    Key: key,
    UpdateExpression: `
      SET counter = counter + :inc1,
          counter = counter + :inc2,
          map_attr.nested1 = :new_val1,
          map_attr.nested3 = :new_val3,
          list_attr[0] = list_attr[1],
          list_attr[1] = list_attr[2]
    `,
    ExpressionAttributeValues: {
      ":inc1": 5,
      ":inc2": 3,
      ":new_val1": "updated_value1",
      ":new_val3": "new_value3"
    },
    ReturnValues: "UPDATED_NEW"
  }));
  
  // Step 4: Get the item to verify final state
  const responseAfter = await docClient.send(new GetCommand({
    TableName: tableName,
    Key: key
  }));
  
  const itemAfter = responseAfter.Item || {};
  
  // Return the results
  return {
    initialState: itemBefore,
    updateResponse: updateResponse,
    finalState: itemAfter
  };
}
```
を使用した式の更新順序の使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to use update expression order of operations in DynamoDB.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "OrderProcessing";
  
  console.log("Demonstrating update expression order of operations in DynamoDB");
  
  try {
    // Example 1: Demonstrating value copying in update expressions
    console.log("\nExample 1: Demonstrating value copying in update expressions");
    const results1 = await demonstrateValueCopying(
      config,
      tableName,
      { OrderId: "order123" }
    );
    
    console.log("Initial state:", JSON.stringify(results1.initialState, null, 2));
    console.log("Update response:", JSON.stringify(results1.updateResponse, null, 2));
    console.log("Final state:", JSON.stringify(results1.finalState, null, 2));
    
    console.log("\nExplanation:");
    console.log("1. The initial state had a=1, b=2, c=3");
    console.log("2. The update expression 'REMOVE a SET b = a, c = b' did the following:");
    console.log("   - Copied the value of 'a' (which was 1) to be used for 'b'");
    console.log("   - Copied the value of 'b' (which was 2) to be used for 'c'");
    console.log("   - Removed the attribute 'a'");
    console.log("3. The final state has b=1, c=2, and 'a' is removed");
    console.log("4. This demonstrates that DynamoDB uses the values of attributes as they were BEFORE any modifications");
    
    // Example 2: Demonstrating the order of different action types
    console.log("\nExample 2: Demonstrating the order of different action types");
    const results2 = await demonstrateActionOrder(
      config,
      tableName,
      { OrderId: "order456" }
    );
    
    console.log("Initial state:", JSON.stringify(results2.initialState, null, 2));
    console.log("Update response:", JSON.stringify(results2.updateResponse, null, 2));
    console.log("Final state:", JSON.stringify(results2.finalState, null, 2));
    
    console.log("\nExplanation:");
    console.log("1. The update expression contained multiple action types: REMOVE, SET, ADD, DELETE");
    console.log("2. DynamoDB processes these actions in this order: REMOVE, SET, ADD, DELETE");
    console.log("3. First, 'to_remove' was removed");
    console.log("4. Then, 'to_modify' was set to a new value");
    console.log("5. Next, 'counter' was incremented by 5");
    console.log("6. Finally, 'B' was removed from the set attribute");
    
    // Example 3: Updating multiple attributes in a single SET action
    console.log("\nExample 3: Updating multiple attributes in a single SET action");
    const response3 = await updateWithMultipleSetActions(
      config,
      tableName,
      { OrderId: "order789" },
      {
        Status: "Shipped",
        ShippingDate: "2025-05-28",
        TrackingNumber: "1Z999AA10123456784"
      }
    );
    
    console.log("Multiple attributes updated successfully:", JSON.stringify(response3.Attributes, null, 2));
    
    // Example 4: Conditional value copying with if_not_exists
    console.log("\nExample 4: Conditional value copying with if_not_exists");
    const response4 = await updateWithConditionalValueCopying(
      config,
      tableName,
      { OrderId: "order101" },
      "PreferredShippingMethod",
      "ShippingMethod",
      "Standard"
    );
    
    console.log("Conditional value copying result:", JSON.stringify(response4.Attributes, null, 2));
    
    // Example 5: Multiple operations on the same attribute
    console.log("\nExample 5: Multiple operations on the same attribute");
    const results5 = await demonstrateMultipleOperationsOnSameAttribute(
      config,
      tableName,
      { OrderId: "order202" }
    );
    
    console.log("Initial state:", JSON.stringify(results5.initialState, null, 2));
    console.log("Update response:", JSON.stringify(results5.updateResponse, null, 2));
    console.log("Final state:", JSON.stringify(results5.finalState, null, 2));
    
    console.log("\nExplanation:");
    console.log("1. The counter was incremented twice (first by 5, then by 3) for a total of +8");
    console.log("2. The map attribute had one value updated and a new nested attribute added");
    console.log("3. The list attribute had values shifted (value at index 1 moved to index 0, value at index 2 moved to index 1)");
    console.log("4. All operations within the SET action are processed from left to right");
    
    // Key points about update expression order of operations
    console.log("\nKey Points About Update Expression Order of Operations:");
    console.log("1. Variables in expressions hold copies of attribute values as they existed BEFORE any modifications");
    console.log("2. Multiple actions in an update expression are processed in this order: REMOVE, SET, ADD, DELETE");
    console.log("3. Within each action type, operations are processed from left to right");
    console.log("4. You can reference the same attribute multiple times in an expression");
    console.log("5. You can use if_not_exists() to conditionally set values based on attribute existence");
    console.log("6. Using a single update expression with multiple actions is more efficient than multiple separate updates");
    console.log("7. The update expression is atomic - either all actions succeed or none do");
    
  } catch (error) {
    console.error("Error:", error);
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### テーブルのウォームスループット設定を更新する
<a name="dynamodb_UpdateTableWarmThroughput_javascript_3_topic"></a>

次のコード例は、テーブルのウォームスループット設定を更新する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScriptを使用して既存の DynamoDB テーブルのウォームスループット設定を更新します。  

```
import { DynamoDBClient, UpdateTableCommand } from "@aws-sdk/client-dynamodb";

export async function updateDynamoDBTableWarmThroughput(
  tableName,
  tableReadUnits,
  tableWriteUnits,
  gsiName,
  gsiReadUnits,
  gsiWriteUnits,
  region = "us-east-1"
) {
  try {
    const ddbClient = new DynamoDBClient({ region: region });

    // Construct the update table request
    const updateTableRequest = {
      TableName: tableName,
      GlobalSecondaryIndexUpdates: [
        {
            Update: {
                IndexName: gsiName,
                WarmThroughput: {
                    ReadUnitsPerSecond: gsiReadUnits,
                    WriteUnitsPerSecond: gsiWriteUnits,
                },
            },
        },
      ],
      WarmThroughput: {
          ReadUnitsPerSecond: tableReadUnits,
          WriteUnitsPerSecond: tableWriteUnits,
      },
    };

    const command = new UpdateTableCommand(updateTableRequest);
    const response = await ddbClient.send(command);
    console.log(`Table updated successfully! Response: ${JSON.stringify(response)}`);
    return response;
  } catch (error) {
    console.error(`Error updating table: ${error}`);
    throw error;
  }
}

// Example usage (commented out for testing)
/*
updateDynamoDBTableWarmThroughput(
  'example-table',
  5, 5,
  'example-index',
  2, 2
);
*/
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateTableCommand)」を参照してください。

### 項目の TTL を更新する
<a name="dynamodb_UpdateItemTTL_javascript_3_topic"></a>

以下のコード例は、項目の TTL の更新方法を示しています。

**SDK for JavaScript (v3)**  

```
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";

export const updateItem = async (tableName, partitionKey, sortKey, region = 'us-east-1') => {
    const client = new DynamoDBClient({
        region: region,
        endpoint: `https://dynamodb.${region}.amazonaws.com`
    });

    const currentTime = Math.floor(Date.now() / 1000);
    const expireAt = Math.floor((Date.now() + 90 * 24 * 60 * 60 * 1000) / 1000);

    const params = {
        TableName: tableName,
        Key: marshall({
            partitionKey: partitionKey,
            sortKey: sortKey
        }),
        UpdateExpression: "SET updatedAt = :c, expireAt = :e",
        ExpressionAttributeValues: marshall({
            ":c": currentTime,
            ":e": expireAt
        }),
    };

    try {
        const data = await client.send(new UpdateItemCommand(params));
        const responseData = unmarshall(data.Attributes);
        console.log("Item updated successfully: %s", responseData);
        return responseData;
    } catch (err) {
        console.error("Error updating item:", err);
        throw err;
    }
}

// Example usage (commented out for testing)
// updateItem('your-table-name', 'your-partition-key-value', 'your-sort-key-value');
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### PartiQL UPDATE を使用してデータを更新する
<a name="dynamodb_PartiQLUpdate_javascript_3_topic"></a>

次のコード例は、PartiQL UPDATE ステートメントを使用してデータを更新する方法を示しています。

**SDK for JavaScript (v3)**  
PartiQL UPDATE ステートメントを使用して DynamoDB テーブルの項目を更新します AWS SDK for JavaScript。  

```
/**
 * This example demonstrates how to update items in a DynamoDB table using PartiQL.
 * It shows different ways to update documents with various index types.
 */
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  DynamoDBDocumentClient,
  ExecuteStatementCommand,
  BatchExecuteStatementCommand,
} from "@aws-sdk/lib-dynamodb";

/**
 * Update a single attribute of an item using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @param attributeName - The name of the attribute to update
 * @param attributeValue - The new value for the attribute
 * @returns The response from the ExecuteStatementCommand
 */
export const updateSingleAttribute = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number,
  attributeName: string,
  attributeValue: any
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `UPDATE "${tableName}" SET ${attributeName} = ? WHERE ${partitionKeyName} = ?`,
    Parameters: [attributeValue, partitionKeyValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item updated successfully");
    return data;
  } catch (err) {
    console.error("Error updating item:", err);
    throw err;
  }
};

/**
 * Update multiple attributes of an item using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @param attributeUpdates - Object containing attribute names and their new values
 * @returns The response from the ExecuteStatementCommand
 */
export const updateMultipleAttributes = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number,
  attributeUpdates: Record<string, any>
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  // Create SET clause for each attribute
  const setClause = Object.keys(attributeUpdates)
    .map((attr, index) => `${attr} = ?`)
    .join(", ");

  // Create parameters array with attribute values followed by the partition key value
  const parameters = [...Object.values(attributeUpdates), partitionKeyValue];

  const params = {
    Statement: `UPDATE "${tableName}" SET ${setClause} WHERE ${partitionKeyName} = ?`,
    Parameters: parameters,
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item updated successfully");
    return data;
  } catch (err) {
    console.error("Error updating item:", err);
    throw err;
  }
};

/**
 * Update an item identified by a composite key (partition key + sort key) using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @param sortKeyName - The name of the sort key attribute
 * @param sortKeyValue - The value of the sort key
 * @param attributeName - The name of the attribute to update
 * @param attributeValue - The new value for the attribute
 * @returns The response from the ExecuteStatementCommand
 */
export const updateItemWithCompositeKey = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number,
  sortKeyName: string,
  sortKeyValue: string | number,
  attributeName: string,
  attributeValue: any
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `UPDATE "${tableName}" SET ${attributeName} = ? WHERE ${partitionKeyName} = ? AND ${sortKeyName} = ?`,
    Parameters: [attributeValue, partitionKeyValue, sortKeyValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item updated successfully");
    return data;
  } catch (err) {
    console.error("Error updating item:", err);
    throw err;
  }
};

/**
 * Update an item with a condition to ensure the update only happens if a condition is met.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param partitionKeyName - The name of the partition key attribute
 * @param partitionKeyValue - The value of the partition key
 * @param attributeName - The name of the attribute to update
 * @param attributeValue - The new value for the attribute
 * @param conditionAttribute - The attribute to check in the condition
 * @param conditionValue - The value to compare against in the condition
 * @returns The response from the ExecuteStatementCommand
 */
export const updateItemWithCondition = async (
  tableName: string,
  partitionKeyName: string,
  partitionKeyValue: string | number,
  attributeName: string,
  attributeValue: any,
  conditionAttribute: string,
  conditionValue: any
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  const params = {
    Statement: `UPDATE "${tableName}" SET ${attributeName} = ? WHERE ${partitionKeyName} = ? AND ${conditionAttribute} = ?`,
    Parameters: [attributeValue, partitionKeyValue, conditionValue],
  };

  try {
    const data = await docClient.send(new ExecuteStatementCommand(params));
    console.log("Item updated with condition successfully");
    return data;
  } catch (err) {
    console.error("Error updating item with condition:", err);
    throw err;
  }
};

/**
 * Batch update multiple items using PartiQL.
 * 
 * @param tableName - The name of the DynamoDB table
 * @param updates - Array of objects containing key and update information
 * @returns The response from the BatchExecuteStatementCommand
 */
export const batchUpdateItems = async (
  tableName: string,
  updates: Array<{
    partitionKeyName: string;
    partitionKeyValue: string | number;
    attributeName: string;
    attributeValue: any;
  }>
) => {
  const client = new DynamoDBClient({});
  const docClient = DynamoDBDocumentClient.from(client);

  // Create statements for each update
  const statements = updates.map((update) => {
    return {
      Statement: `UPDATE "${tableName}" SET ${update.attributeName} = ? WHERE ${update.partitionKeyName} = ?`,
      Parameters: [update.attributeValue, update.partitionKeyValue],
    };
  });

  const params = {
    Statements: statements,
  };

  try {
    const data = await docClient.send(new BatchExecuteStatementCommand(params));
    console.log("Items batch updated successfully");
    return data;
  } catch (err) {
    console.error("Error batch updating items:", err);
    throw err;
  }
};

/**
 * Example usage showing how to update items with different index types
 */
export const updateExamples = async () => {
  // Update a single attribute using a simple primary key
  await updateSingleAttribute("UsersTable", "userId", "user123", "email", "newemail@example.com");

  // Update multiple attributes at once
  await updateMultipleAttributes("UsersTable", "userId", "user123", {
    email: "newemail@example.com",
    name: "John Smith",
    lastLogin: new Date().toISOString(),
  });

  // Update an item with a composite key (partition key + sort key)
  await updateItemWithCompositeKey(
    "OrdersTable",
    "orderId",
    "order456",
    "productId",
    "prod789",
    "quantity",
    5
  );

  // Update with a condition
  await updateItemWithCondition(
    "UsersTable",
    "userId",
    "user123",
    "userStatus",
    "active",
    "userType",
    "premium"
  );

  // Batch update multiple items
  await batchUpdateItems("UsersTable", [
    {
      partitionKeyName: "userId",
      partitionKeyValue: "user123",
      attributeName: "lastLogin",
      attributeValue: new Date().toISOString(),
    },
    {
      partitionKeyName: "userId",
      partitionKeyValue: "user456",
      attributeName: "lastLogin",
      attributeValue: new Date().toISOString(),
    },
  ]);
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [BatchExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/BatchExecuteStatementCommand)
  + [ExecuteStatement](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/ExecuteStatementCommand)

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_javascript_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 Lambda JavaScript ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-api-gateway) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### アトミックカウンタオペレーションを使用する
<a name="dynamodb_Scenario_AtomicCounterOperations_javascript_3_topic"></a>

次のコード例は、DynamoDB でアトミックカウンタオペレーションを使用する方法を示しています。
+ ADD および SET オペレーションを使用してカウンタをアトミックに増分します。
+ 存在しない可能性のあるカウンターを安全に増分します。
+ カウンターオペレーションに楽観的ロックを実装します。

**SDK for JavaScript (v3)**  
を使用してアトミックカウンターオペレーションをデモンストレーションします AWS SDK for JavaScript。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  GetCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Increment a counter using the ADD operation.
 * 
 * This function demonstrates using the ADD operation for atomic increments.
 * The ADD operation is atomic and is the recommended way to increment counters.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} counterName - The name of the counter attribute
 * @param {number} incrementValue - The value to increment by
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function incrementCounterWithAdd(
  config,
  tableName,
  key,
  counterName,
  incrementValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using ADD
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `ADD ${counterName} :increment`,
    ExpressionAttributeValues: {
      ":increment": incrementValue
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Increment a counter using the SET operation with an expression.
 * 
 * This function demonstrates using the SET operation with an expression for increments.
 * While this approach works, it's less idiomatic for simple increments than using ADD.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} counterName - The name of the counter attribute
 * @param {number} incrementValue - The value to increment by
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function incrementCounterWithSet(
  config,
  tableName,
  key,
  counterName,
  incrementValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using SET with an expression
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${counterName} = ${counterName} + :increment`,
    ExpressionAttributeValues: {
      ":increment": incrementValue
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Increment a counter safely, handling the case where the counter might not exist.
 * 
 * This function demonstrates using the if_not_exists function with SET to safely
 * increment a counter that might not exist yet.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} counterName - The name of the counter attribute
 * @param {number} incrementValue - The value to increment by
 * @param {number} defaultValue - The default value if the counter doesn't exist
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function incrementCounterSafely(
  config,
  tableName,
  key,
  counterName,
  incrementValue,
  defaultValue = 0
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using SET with if_not_exists
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${counterName} = if_not_exists(${counterName}, :default) + :increment`,
    ExpressionAttributeValues: {
      ":increment": incrementValue,
      ":default": defaultValue
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Increment a counter with optimistic locking to prevent race conditions.
 * 
 * This function demonstrates using a condition expression to implement optimistic
 * locking, which prevents race conditions when multiple processes try to update
 * the same counter.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} counterName - The name of the counter attribute
 * @param {number} incrementValue - The value to increment by
 * @param {number} expectedValue - The expected current value of the counter
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function incrementCounterWithLocking(
  config,
  tableName,
  key,
  counterName,
  incrementValue,
  expectedValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters with a condition expression
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${counterName} = ${counterName} + :increment`,
    ConditionExpression: `${counterName} = :expected`,
    ExpressionAttributeValues: {
      ":increment": incrementValue,
      ":expected": expectedValue
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  try {
    // Perform the update operation
    const response = await docClient.send(new UpdateCommand(params));
    return {
      success: true,
      data: response
    };
  } catch (error) {
    // Check if the error is due to the condition check failing
    if (error.name === "ConditionalCheckFailedException") {
      return {
        success: false,
        error: "Optimistic locking failed: the counter value has changed"
      };
    }
    // Re-throw other errors
    throw error;
  }
}

/**
 * Get the current value of a counter.
 * 
 * Helper function to retrieve the current value of a counter attribute.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to get
 * @param {string} counterName - The name of the counter attribute
 * @returns {Promise<number|null>} - The current counter value or null if not found
 */
async function getCounterValue(
  config,
  tableName,
  key,
  counterName
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the get parameters
  const params = {
    TableName: tableName,
    Key: key
  };
  
  // Perform the get operation
  const response = await docClient.send(new GetCommand(params));
  
  // Return the counter value if it exists, otherwise null
  return response.Item && counterName in response.Item
    ? response.Item[counterName]
    : null;
}
```
でのアトミックカウンターオペレーションの使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to use the atomic counter operations.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "Products";
  const key = { ProductId: "P12345" };
  const counterName = "ViewCount";
  const incrementValue = 1;
  
  console.log("Demonstrating different approaches to increment counters in DynamoDB");
  
  try {
    // Example 1: Using ADD operation (recommended for simple increments)
    console.log("\nExample 1: Incrementing counter with ADD operation");
    const response1 = await incrementCounterWithAdd(
      config,
      tableName,
      key,
      counterName,
      incrementValue
    );
    
    console.log(`Counter incremented to: ${response1.Attributes[counterName]}`);
    
    // Example 2: Using SET operation with an expression
    console.log("\nExample 2: Incrementing counter with SET operation");
    const response2 = await incrementCounterWithSet(
      config,
      tableName,
      key,
      counterName,
      incrementValue
    );
    
    console.log(`Counter incremented to: ${response2.Attributes[counterName]}`);
    
    // Example 3: Safely incrementing a counter that might not exist
    console.log("\nExample 3: Safely incrementing counter that might not exist");
    const newKey = { ProductId: "P67890" };
    const response3 = await incrementCounterSafely(
      config,
      tableName,
      newKey,
      counterName,
      incrementValue,
      0
    );
    
    console.log(`Counter initialized and incremented to: ${response3.Attributes[counterName]}`);
    
    // Example 4: Incrementing with optimistic locking
    console.log("\nExample 4: Incrementing with optimistic locking");
    
    // First, get the current counter value
    const currentValue = await getCounterValue(config, tableName, key, counterName);
    console.log(`Current counter value: ${currentValue}`);
    
    // Then, try to increment with optimistic locking
    const response4 = await incrementCounterWithLocking(
      config,
      tableName,
      key,
      counterName,
      incrementValue,
      currentValue
    );
    
    if (response4.success) {
      console.log(`Counter successfully incremented to: ${response4.data.Attributes[counterName]}`);
    } else {
      console.log(response4.error);
    }
    
    // Explain the differences between ADD and SET
    console.log("\nKey differences between ADD and SET for counter operations:");
    console.log("1. ADD is more concise and idiomatic for simple increments");
    console.log("2. SET with expressions is more flexible for complex operations");
    console.log("3. Both operations are atomic and safe for concurrent updates");
    console.log("4. SET with if_not_exists is required when the attribute might not exist");
    console.log("5. Optimistic locking can be added to either approach for additional safety");
    
  } catch (error) {
    console.error("Error:", error);
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)」を参照してください。

### 条件付きオペレーションを使用する
<a name="dynamodb_Scenario_ConditionalOperations_javascript_3_topic"></a>

次のコード例は、DynamoDB で条件付きオペレーションを使用する方法を示しています。
+ データの上書きを防ぐため、条件付き書き込みを実装します。
+ 条件式を使用してビジネスルールを適用します。
+ 条件付きチェックの失敗を適切に処理します。

**SDK for JavaScript (v3)**  
を使用して条件付きオペレーションをデモンストレーションします AWS SDK for JavaScript。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  DeleteCommand,
  GetCommand,
  PutCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Perform a conditional update operation.
 * 
 * This function demonstrates how to update an item only if a condition is met.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} conditionAttribute - The attribute to check in the condition
 * @param {any} conditionValue - The value to compare against
 * @param {string} updateAttribute - The attribute to update
 * @param {any} updateValue - The new value to set
 * @returns {Promise<Object>} - Result of the operation
 */
async function conditionalUpdate(
  config,
  tableName,
  key,
  conditionAttribute,
  conditionValue,
  updateAttribute,
  updateValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters with a condition expression
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${updateAttribute} = :value`,
    ConditionExpression: `${conditionAttribute} = :condition`,
    ExpressionAttributeValues: {
      ":value": updateValue,
      ":condition": conditionValue
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  try {
    // Perform the update operation
    const response = await docClient.send(new UpdateCommand(params));
    
    return {
      success: true,
      message: "Condition was met and update was performed",
      updatedAttributes: response.Attributes
    };
  } catch (error) {
    // Check if the error is due to the condition check failing
    if (error.name === "ConditionalCheckFailedException") {
      return {
        success: false,
        message: "Condition was not met, update was not performed",
        error: "ConditionalCheckFailedException"
      };
    }
    
    // Re-throw other errors
    throw error;
  }
}

/**
 * Perform a conditional delete operation.
 * 
 * This function demonstrates how to delete an item only if a condition is met.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to delete
 * @param {string} conditionAttribute - The attribute to check in the condition
 * @param {any} conditionValue - The value to compare against
 * @returns {Promise<Object>} - Result of the operation
 */
async function conditionalDelete(
  config,
  tableName,
  key,
  conditionAttribute,
  conditionValue
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the delete parameters with a condition expression
  const params = {
    TableName: tableName,
    Key: key,
    ConditionExpression: `${conditionAttribute} = :condition`,
    ExpressionAttributeValues: {
      ":condition": conditionValue
    },
    ReturnValues: "ALL_OLD"
  };
  
  try {
    // Perform the delete operation
    const response = await docClient.send(new DeleteCommand(params));
    
    return {
      success: true,
      message: "Condition was met and item was deleted",
      deletedItem: response.Attributes
    };
  } catch (error) {
    // Check if the error is due to the condition check failing
    if (error.name === "ConditionalCheckFailedException") {
      return {
        success: false,
        message: "Condition was not met, item was not deleted",
        error: "ConditionalCheckFailedException"
      };
    }
    
    // Re-throw other errors
    throw error;
  }
}

/**
 * Implement optimistic locking with a version number.
 * 
 * This function demonstrates how to use a version number for optimistic locking
 * to prevent race conditions when multiple processes update the same item.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {Object} updates - The attributes to update
 * @param {number} expectedVersion - The expected current version number
 * @returns {Promise<Object>} - Result of the operation
 */
async function updateWithOptimisticLocking(
  config,
  tableName,
  key,
  updates,
  expectedVersion
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Build the update expression
  const updateExpressions = [];
  const expressionAttributeValues = {
    ":expectedVersion": expectedVersion,
    ":newVersion": expectedVersion + 1
  };
  
  // Add each update to the expression
  Object.entries(updates).forEach(([attribute, value], index) => {
    updateExpressions.push(`${attribute} = :val${index}`);
    expressionAttributeValues[`:val${index}`] = value;
  });
  
  // Add the version update
  updateExpressions.push("version = :newVersion");
  
  // Define the update parameters with a condition expression
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${updateExpressions.join(", ")}`,
    ConditionExpression: "version = :expectedVersion",
    ExpressionAttributeValues: expressionAttributeValues,
    ReturnValues: "UPDATED_NEW"
  };
  
  try {
    // Perform the update operation
    const response = await docClient.send(new UpdateCommand(params));
    
    return {
      success: true,
      message: "Update succeeded with optimistic locking",
      newVersion: expectedVersion + 1,
      updatedAttributes: response.Attributes
    };
  } catch (error) {
    // Check if the error is due to the condition check failing
    if (error.name === "ConditionalCheckFailedException") {
      return {
        success: false,
        message: "Optimistic locking failed: the item was modified by another process",
        error: "ConditionalCheckFailedException"
      };
    }
    
    // Re-throw other errors
    throw error;
  }
}

/**
 * Implement a conditional write that creates an item only if it doesn't exist.
 * 
 * This function demonstrates how to use attribute_not_exists to create an item
 * only if it doesn't already exist (similar to an "INSERT IF NOT EXISTS" operation).
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} item - The item to create
 * @returns {Promise<Object>} - Result of the operation
 */
async function createIfNotExists(
  config,
  tableName,
  item
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Extract the primary key attributes
  const keyAttributes = Object.keys(item).filter(attr => 
    attr === "id" || attr === "ID" || attr === "Id" || 
    attr.endsWith("Id") || attr.endsWith("ID") || 
    attr.endsWith("Key")
  );
  
  if (keyAttributes.length === 0) {
    throw new Error("Could not determine primary key attributes");
  }
  
  // Create a condition expression that checks if the item doesn't exist
  const conditionExpression = `attribute_not_exists(${keyAttributes[0]})`;
  
  // Define the put parameters with a condition expression
  const params = {
    TableName: tableName,
    Item: item,
    ConditionExpression: conditionExpression
  };
  
  try {
    // Perform the put operation
    await docClient.send(new PutCommand(params));
    
    return {
      success: true,
      message: "Item was created because it didn't exist",
      item
    };
  } catch (error) {
    // Check if the error is due to the condition check failing
    if (error.name === "ConditionalCheckFailedException") {
      return {
        success: false,
        message: "Item already exists, creation was skipped",
        error: "ConditionalCheckFailedException"
      };
    }
    
    // Re-throw other errors
    throw error;
  }
}

/**
 * Get the current value of an item.
 * 
 * Helper function to retrieve the current value of an item.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to get
 * @returns {Promise<Object|null>} - The item or null if not found
 */
async function getItem(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the get parameters
  const params = {
    TableName: tableName,
    Key: key
  };
  
  // Perform the get operation
  const response = await docClient.send(new GetCommand(params));
  
  // Return the item if it exists, otherwise null
  return response.Item || null;
}
```
での条件付きオペレーションの使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to use conditional operations.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "Products";
  const key = { ProductId: "P12345" };
  
  console.log("Demonstrating conditional operations in DynamoDB");
  
  try {
    // Example 1: Conditional update based on attribute value
    console.log("\nExample 1: Conditional update based on attribute value");
    const updateResult = await conditionalUpdate(
      config,
      tableName,
      key,
      "Category",
      "Electronics",
      "Price",
      299.99
    );
    
    console.log(`Result: ${updateResult.message}`);
    if (updateResult.success) {
      console.log("Updated attributes:", updateResult.updatedAttributes);
    }
    
    // Example 2: Conditional delete based on attribute value
    console.log("\nExample 2: Conditional delete based on attribute value");
    const deleteResult = await conditionalDelete(
      config,
      tableName,
      key,
      "InStock",
      false
    );
    
    console.log(`Result: ${deleteResult.message}`);
    if (deleteResult.success) {
      console.log("Deleted item:", deleteResult.deletedItem);
    }
    
    // Example 3: Optimistic locking with version number
    console.log("\nExample 3: Optimistic locking with version number");
    
    // First, get the current item to check its version
    const currentItem = await getItem(config, tableName, { ProductId: "P67890" });
    const currentVersion = currentItem ? (currentItem.version || 0) : 0;
    
    console.log(`Current version: ${currentVersion}`);
    
    // Then, update with optimistic locking
    const lockingResult = await updateWithOptimisticLocking(
      config,
      tableName,
      { ProductId: "P67890" },
      {
        Name: "Updated Product Name",
        Description: "This is an updated description"
      },
      currentVersion
    );
    
    console.log(`Result: ${lockingResult.message}`);
    if (lockingResult.success) {
      console.log(`New version: ${lockingResult.newVersion}`);
      console.log("Updated attributes:", lockingResult.updatedAttributes);
    }
    
    // Example 4: Create item only if it doesn't exist
    console.log("\nExample 4: Create item only if it doesn't exist");
    const createResult = await createIfNotExists(
      config,
      tableName,
      {
        ProductId: "P99999",
        Name: "New Product",
        Category: "Accessories",
        Price: 19.99,
        InStock: true
      }
    );
    
    console.log(`Result: ${createResult.message}`);
    if (createResult.success) {
      console.log("Created item:", createResult.item);
    }
    
    // Explain conditional operations
    console.log("\nKey points about conditional operations:");
    console.log("1. Conditional operations only succeed if the condition is met");
    console.log("2. ConditionalCheckFailedException indicates the condition wasn't met");
    console.log("3. Optimistic locking prevents race conditions in concurrent updates");
    console.log("4. attribute_exists and attribute_not_exists are useful for checking if attributes are present");
    console.log("5. Conditional operations are atomic - they either succeed completely or fail completely");
    console.log("6. You can use any valid comparison operators and functions in condition expressions");
    console.log("7. Conditional operations don't consume write capacity if the condition fails");
    
  } catch (error) {
    console.error("Error:", error);
  }
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [DeleteItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/DeleteItemCommand)
  + [PutItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/PutItemCommand)
  + [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)

### 式の属性名を使用する
<a name="dynamodb_Scenario_ExpressionAttributeNames_javascript_3_topic"></a>

次のコード例は、DynamoDB で式の属性名を使用する方法を示しています。
+ DynamoDB 式で予約語を操作します。
+ 式の属性名のプレースホルダーを使用します。
+ 属性名の特殊文字を処理します。

**SDK for JavaScript (v3)**  
を使用して式の属性名をデモンストレーションします AWS SDK for JavaScript。  

```
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { 
  DynamoDBDocumentClient, 
  UpdateCommand,
  GetCommand,
  QueryCommand,
  ScanCommand
} = require("@aws-sdk/lib-dynamodb");

/**
 * Update an attribute that is a reserved word in DynamoDB.
 * 
 * This function demonstrates how to use expression attribute names to update
 * attributes that are reserved words in DynamoDB.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} reservedWordAttribute - The reserved word attribute to update
 * @param {any} value - The value to set
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateReservedWordAttribute(
  config,
  tableName,
  key,
  reservedWordAttribute,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using expression attribute names
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: "SET #attr = :value",
    ExpressionAttributeNames: {
      "#attr": reservedWordAttribute
    },
    ExpressionAttributeValues: {
      ":value": value
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Update an attribute that contains special characters.
 * 
 * This function demonstrates how to use expression attribute names to update
 * attributes that contain special characters.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string} specialCharAttribute - The attribute with special characters to update
 * @param {any} value - The value to set
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateSpecialCharacterAttribute(
  config,
  tableName,
  key,
  specialCharAttribute,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the update parameters using expression attribute names
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: "SET #attr = :value",
    ExpressionAttributeNames: {
      "#attr": specialCharAttribute
    },
    ExpressionAttributeValues: {
      ":value": value
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Query items using an attribute that is a reserved word.
 * 
 * This function demonstrates how to use expression attribute names in a query
 * when the attribute is a reserved word.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {string} partitionKeyName - The name of the partition key attribute
 * @param {any} partitionKeyValue - The value of the partition key
 * @param {string} reservedWordAttribute - The reserved word attribute to filter on
 * @param {any} value - The value to compare against
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function queryWithReservedWordAttribute(
  config,
  tableName,
  partitionKeyName,
  partitionKeyValue,
  reservedWordAttribute,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the query parameters using expression attribute names
  const params = {
    TableName: tableName,
    KeyConditionExpression: "#pkName = :pkValue",
    FilterExpression: "#attr = :value",
    ExpressionAttributeNames: {
      "#pkName": partitionKeyName,
      "#attr": reservedWordAttribute
    },
    ExpressionAttributeValues: {
      ":pkValue": partitionKeyValue,
      ":value": value
    }
  };
  
  // Perform the query operation
  const response = await docClient.send(new QueryCommand(params));
  
  return response;
}

/**
 * Update a nested attribute with a path that contains reserved words.
 * 
 * This function demonstrates how to use expression attribute names to update
 * nested attributes where the path contains reserved words.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to update
 * @param {string[]} attributePath - The path to the nested attribute as an array
 * @param {any} value - The value to set
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function updateNestedReservedWordAttribute(
  config,
  tableName,
  key,
  attributePath,
  value
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Create expression attribute names for each part of the path
  const expressionAttributeNames = {};
  for (let i = 0; i < attributePath.length; i++) {
    expressionAttributeNames[`#attr${i}`] = attributePath[i];
  }
  
  // Build the attribute path using the expression attribute names
  const attributePathExpression = attributePath
    .map((_, i) => `#attr${i}`)
    .join(".");
  
  // Define the update parameters
  const params = {
    TableName: tableName,
    Key: key,
    UpdateExpression: `SET ${attributePathExpression} = :value`,
    ExpressionAttributeNames: expressionAttributeNames,
    ExpressionAttributeValues: {
      ":value": value
    },
    ReturnValues: "UPDATED_NEW"
  };
  
  // Perform the update operation
  const response = await docClient.send(new UpdateCommand(params));
  
  return response;
}

/**
 * Scan a table with multiple attribute name placeholders.
 * 
 * This function demonstrates how to use multiple expression attribute names
 * in a complex filter expression.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} filters - Object mapping attribute names to filter values
 * @returns {Promise<Object>} - The response from DynamoDB
 */
async function scanWithMultipleAttributeNames(
  config,
  tableName,
  filters
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Create expression attribute names and values
  const expressionAttributeNames = {};
  const expressionAttributeValues = {};
  const filterConditions = [];
  
  // Build the filter expression
  Object.entries(filters).forEach(([attrName, value], index) => {
    const nameKey = `#attr${index}`;
    const valueKey = `:val${index}`;
    
    expressionAttributeNames[nameKey] = attrName;
    expressionAttributeValues[valueKey] = value;
    filterConditions.push(`${nameKey} = ${valueKey}`);
  });
  
  // Join the filter conditions with AND
  const filterExpression = filterConditions.join(" AND ");
  
  // Define the scan parameters
  const params = {
    TableName: tableName,
    FilterExpression: filterExpression,
    ExpressionAttributeNames: expressionAttributeNames,
    ExpressionAttributeValues: expressionAttributeValues
  };
  
  // Perform the scan operation
  const response = await docClient.send(new ScanCommand(params));
  
  return response;
}

/**
 * Get the current value of an item.
 * 
 * Helper function to retrieve the current value of an item.
 * 
 * @param {Object} config - AWS configuration object
 * @param {string} tableName - The name of the DynamoDB table
 * @param {Object} key - The key of the item to get
 * @returns {Promise<Object|null>} - The item or null if not found
 */
async function getItem(
  config,
  tableName,
  key
) {
  // Initialize the DynamoDB client
  const client = new DynamoDBClient(config);
  const docClient = DynamoDBDocumentClient.from(client);
  
  // Define the get parameters
  const params = {
    TableName: tableName,
    Key: key
  };
  
  // Perform the get operation
  const response = await docClient.send(new GetCommand(params));
  
  // Return the item if it exists, otherwise null
  return response.Item || null;
}
```
を使用した式の属性名の使用例 AWS SDK for JavaScript。  

```
/**
 * Example of how to use expression attribute names.
 */
async function exampleUsage() {
  // Example parameters
  const config = { region: "us-west-2" };
  const tableName = "Products";
  const key = { ProductId: "P12345" };
  
  console.log("Demonstrating expression attribute names in DynamoDB");
  
  try {
    // Example 1: Update an attribute that is a reserved word
    console.log("\nExample 1: Updating an attribute that is a reserved word");
    const response1 = await updateReservedWordAttribute(
      config,
      tableName,
      key,
      "Size", // "SIZE" is a reserved word in DynamoDB
      "Large"
    );
    
    console.log("Updated attribute:", response1.Attributes);
    
    // Example 2: Update an attribute with special characters
    console.log("\nExample 2: Updating an attribute with special characters");
    const response2 = await updateSpecialCharacterAttribute(
      config,
      tableName,
      key,
      "Product-Type", // Contains a hyphen, which is a special character
      "Electronics"
    );
    
    console.log("Updated attribute:", response2.Attributes);
    
    // Example 3: Query with a reserved word attribute
    console.log("\nExample 3: Querying with a reserved word attribute");
    const response3 = await queryWithReservedWordAttribute(
      config,
      tableName,
      "Category",
      "Electronics",
      "Count", // "COUNT" is a reserved word in DynamoDB
      10
    );
    
    console.log(`Found ${response3.Items.length} items`);
    
    // Example 4: Update a nested attribute with reserved words in the path
    console.log("\nExample 4: Updating a nested attribute with reserved words in the path");
    const response4 = await updateNestedReservedWordAttribute(
      config,
      tableName,
      key,
      ["Dimensions", "Size", "Height"], // "SIZE" is a reserved word
      30
    );
    
    console.log("Updated nested attribute:", response4.Attributes);
    
    // Example 5: Scan with multiple attribute name placeholders
    console.log("\nExample 5: Scanning with multiple attribute name placeholders");
    const response5 = await scanWithMultipleAttributeNames(
      config,
      tableName,
      {
        "Size": "Large",
        "Count": 10,
        "Product-Type": "Electronics"
      }
    );
    
    console.log(`Found ${response5.Items.length} items`);
    
    // Get the final state of the item
    console.log("\nFinal state of the item:");
    const item = await getItem(config, tableName, key);
    console.log(JSON.stringify(item, null, 2));
    
    // Show some common reserved words
    console.log("\nSome common DynamoDB reserved words:");
    const commonReservedWords = [
      "ABORT", "ABSOLUTE", "ACTION", "ADD", "ALL", "ALTER", "AND", "ANY", "AS",
      "ASC", "BETWEEN", "BY", "CASE", "CAST", "COLUMN", "CONNECT", "COUNT",
      "CREATE", "CURRENT", "DATE", "DELETE", "DESC", "DROP", "ELSE", "EXISTS",
      "FOR", "FROM", "GRANT", "GROUP", "HAVING", "IN", "INDEX", "INSERT", "INTO",
      "IS", "JOIN", "KEY", "LEVEL", "LIKE", "LIMIT", "LOCAL", "MAX", "MIN", "NAME",
      "NOT", "NULL", "OF", "ON", "OR", "ORDER", "OUTER", "REPLACE", "RETURN",
      "SELECT", "SET", "SIZE", "TABLE", "THEN", "TO", "UPDATE", "USER", "VALUES",
      "VIEW", "WHERE"
    ];
    console.log(commonReservedWords.join(", "));
    
    // Explain expression attribute names
    console.log("\nKey points about expression attribute names:");
    console.log("1. Use expression attribute names (#name) for reserved words");
    console.log("2. Use expression attribute names for attributes with special characters");
    console.log("3. Special characters include: spaces, hyphens, dots, and other non-alphanumeric characters");
    console.log("4. Expression attribute names are required for nested attributes with reserved words");
    console.log("5. You can use multiple expression attribute names in a single expression");
    console.log("6. Expression attribute names are case-sensitive");
    console.log("7. Expression attribute names are only used in expressions, not in the actual data");
    
  } catch (error) {
    console.error("Error:", error);
  }
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [クエリ](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/QueryCommand)
  + [UpdateItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/dynamodb/command/UpdateItemCommand)

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_javascript_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda JavaScript ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_javascript_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での DynamoDB イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
    console.log(JSON.stringify(event, null, 2));
    event.Records.forEach(record => {
        logDynamoDBRecord(record);
    });
};

const logDynamoDBRecord = (record) => {
    console.log(record.eventID);
    console.log(record.eventName);
    console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`);
};
```
TypeScript を使用した Lambda での DynamoDB イベントの消費。  

```
export const handler = async (event, context) => {
    console.log(JSON.stringify(event, null, 2));
    event.Records.forEach(record => {
        logDynamoDBRecord(record);
    });
}
const logDynamoDBRecord = (record) => {
    console.log(record.eventID);
    console.log(record.eventName);
    console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`);
};
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_javascript_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
export const handler = async (event) => {
  const records = event.Records;
  let curRecordSequenceNumber = "";

  for (const record of records) {
    try {
      // Process your record
      curRecordSequenceNumber = record.dynamodb.SequenceNumber;
    } catch (e) {
      // Return failed record's sequence number
      return { batchItemFailures: [{ itemIdentifier: curRecordSequenceNumber }] };
    }
  }

  return { batchItemFailures: [] };
};
```
TypeScript を使用して Lambda で DynamoDB のバッチアイテム失敗をレポートする。  

```
import {
  DynamoDBBatchResponse,
  DynamoDBBatchItemFailure,
  DynamoDBStreamEvent,
} from "aws-lambda";

export const handler = async (
  event: DynamoDBStreamEvent
): Promise<DynamoDBBatchResponse> => {
  const batchItemFailures: DynamoDBBatchItemFailure[] = [];
  let curRecordSequenceNumber;

  for (const record of event.Records) {
    curRecordSequenceNumber = record.dynamodb?.SequenceNumber;

    if (curRecordSequenceNumber) {
      batchItemFailures.push({
        itemIdentifier: curRecordSequenceNumber,
      });
    }
  }

  return { batchItemFailures: batchItemFailures };
};
```

# SDK for JavaScript (v3) を使用した Amazon EC2 の例
<a name="javascript_3_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_javascript_3_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2";

// Call DescribeSecurityGroups and display the result.
export const main = async () => {
  const client = new EC2Client();
  try {
    const { SecurityGroups } = await client.send(
      new DescribeSecurityGroupsCommand({}),
    );

    const securityGroupList = SecurityGroups.slice(0, 9)
      .map((sg) => ` • ${sg.GroupId}: ${sg.GroupName}`)
      .join("\n");

    console.log(
      "Hello, Amazon EC2! Let's list up to 10 of your security groups:",
    );
    console.log(securityGroupList);
  } catch (err) {
    console.error(err);
  }
};

// Call function if run directly.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSecurityGroupsCommand)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
このファイルには、EC2 で使用される一般的なアクションのリストが含まれています。これらの手順は、インタラクティブな例を簡単に実行できるようにするシナリオフレームワークを使って構成されています。完全なコンテキストについては、GitHub リポジトリを参照してください。  

```
import { tmpdir } from "node:os";
import { writeFile, mkdtemp, rm } from "node:fs/promises";
import { join } from "node:path";
import { get } from "node:http";

import {
  AllocateAddressCommand,
  AssociateAddressCommand,
  AuthorizeSecurityGroupIngressCommand,
  CreateKeyPairCommand,
  CreateSecurityGroupCommand,
  DeleteKeyPairCommand,
  DeleteSecurityGroupCommand,
  DisassociateAddressCommand,
  paginateDescribeImages,
  paginateDescribeInstances,
  paginateDescribeInstanceTypes,
  ReleaseAddressCommand,
  RunInstancesCommand,
  StartInstancesCommand,
  StopInstancesCommand,
  TerminateInstancesCommand,
  waitUntilInstanceStatusOk,
  waitUntilInstanceStopped,
  waitUntilInstanceTerminated,
} from "@aws-sdk/client-ec2";

import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

import { paginateGetParametersByPath, SSMClient } from "@aws-sdk/client-ssm";

/**
 * @typedef {{
 *   ec2Client: import('@aws-sdk/client-ec2').EC2Client,
 *   errors: Error[],
 *   keyPairId?: string,
 *   tmpDirectory?: string,
 *   securityGroupId?: string,
 *   ipAddress?: string,
 *   images?: import('@aws-sdk/client-ec2').Image[],
 *   image?: import('@aws-sdk/client-ec2').Image,
 *   instanceTypes?: import('@aws-sdk/client-ec2').InstanceTypeInfo[],
 *   instanceId?: string,
 *   instanceIpAddress?: string,
 *   allocationId?: string,
 *   allocatedIpAddress?: string,
 *   associationId?: string,
 * }} State
 */

/**
 * A skip function provided to the `skipWhen` of a Step when you want
 * to ignore that step if any errors have occurred.
 * @param {State} state
 */
const skipWhenErrors = (state) => state.errors.length > 0;

const MAX_WAITER_TIME_IN_SECONDS = 60 * 8;

export const confirm = new ScenarioInput("confirmContinue", "Continue?", {
  type: "confirm",
  skipWhen: skipWhenErrors,
});

export const exitOnNoConfirm = new ScenarioAction(
  "exitOnConfirmContinueFalse",
  (/** @type { { earlyExit: boolean } & Record<string, any>} */ state) => {
    if (!state[confirm.name]) {
      state.earlyExit = true;
    }
  },
  {
    skipWhen: skipWhenErrors,
  },
);

export const greeting = new ScenarioOutput(
  "greeting",
  `

Welcome to the Amazon EC2 basic usage scenario.

Before you launch an instances, you'll need to provide a few things:
 - A key pair - This is for SSH access to your EC2 instance. You only need to provide the name.
 - A security group - This is used for configuring access to your instance. Again, only the name is needed.
 - An IP address - Your public IP address will be fetched.
 - An Amazon Machine Image (AMI)
 - A compatible instance type`,
  { header: true, preformatted: true, skipWhen: skipWhenErrors },
);

export const provideKeyPairName = new ScenarioInput(
  "keyPairName",
  "Provide a name for a new key pair.",
  { type: "input", default: "ec2-example-key-pair", skipWhen: skipWhenErrors },
);

export const createKeyPair = new ScenarioAction(
  "createKeyPair",
  async (/** @type {State} */ state) => {
    try {
      // Create a key pair in Amazon EC2.
      const { KeyMaterial, KeyPairId } = await state.ec2Client.send(
        // A unique name for the key pair. Up to 255 ASCII characters.
        new CreateKeyPairCommand({ KeyName: state[provideKeyPairName.name] }),
      );

      state.keyPairId = KeyPairId;

      // Save the private key in a temporary location.
      state.tmpDirectory = await mkdtemp(join(tmpdir(), "ec2-scenario-tmp"));
      await writeFile(
        `${state.tmpDirectory}/${state[provideKeyPairName.name]}.pem`,
        KeyMaterial,
        {
          mode: 0o400,
        },
      );
    } catch (caught) {
      if (
        caught instanceof Error &&
        caught.name === "InvalidKeyPair.Duplicate"
      ) {
        caught.message = `${caught.message}. Try another key name.`;
      }

      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const logKeyPair = new ScenarioOutput(
  "logKeyPair",
  (/** @type {State} */ state) =>
    `Created the key pair ${state[provideKeyPairName.name]}.`,
  { skipWhen: skipWhenErrors },
);

export const confirmDeleteKeyPair = new ScenarioInput(
  "confirmDeleteKeyPair",
  "Do you want to delete the key pair?",
  {
    type: "confirm",
    // Don't do anything when a key pair was never created.
    skipWhen: (/** @type {State} */ state) => !state.keyPairId,
  },
);

export const maybeDeleteKeyPair = new ScenarioAction(
  "deleteKeyPair",
  async (/** @type {State} */ state) => {
    try {
      // Delete a key pair by name from EC2
      await state.ec2Client.send(
        new DeleteKeyPairCommand({ KeyName: state[provideKeyPairName.name] }),
      );
    } catch (caught) {
      if (
        caught instanceof Error &&
        // Occurs when a required parameter (e.g. KeyName) is undefined.
        caught.name === "MissingParameter"
      ) {
        caught.message = `${caught.message}. Did you provide the required value?`;
      }
      state.errors.push(caught);
    }
  },
  {
    // Don't do anything when there's no key pair to delete or the user chooses
    // to keep it.
    skipWhen: (/** @type {State} */ state) =>
      !state.keyPairId || !state[confirmDeleteKeyPair.name],
  },
);

export const provideSecurityGroupName = new ScenarioInput(
  "securityGroupName",
  "Provide a name for a new security group.",
  { type: "input", default: "ec2-scenario-sg", skipWhen: skipWhenErrors },
);

export const createSecurityGroup = new ScenarioAction(
  "createSecurityGroup",
  async (/** @type {State} */ state) => {
    try {
      // Create a new security group that will be used to configure ingress/egress for
      // an EC2 instance.
      const { GroupId } = await state.ec2Client.send(
        new CreateSecurityGroupCommand({
          GroupName: state[provideSecurityGroupName.name],
          Description: "A security group for the Amazon EC2 example.",
        }),
      );
      state.securityGroupId = GroupId;
    } catch (caught) {
      if (caught instanceof Error && caught.name === "InvalidGroup.Duplicate") {
        caught.message = `${caught.message}. Please provide a different name for your security group.`;
      }

      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const logSecurityGroup = new ScenarioOutput(
  "logSecurityGroup",
  (/** @type {State} */ state) =>
    `Created the security group ${state.securityGroupId}.`,
  { skipWhen: skipWhenErrors },
);

export const confirmDeleteSecurityGroup = new ScenarioInput(
  "confirmDeleteSecurityGroup",
  "Do you want to delete the security group?",
  {
    type: "confirm",
    // Don't do anything when a security group was never created.
    skipWhen: (/** @type {State} */ state) => !state.securityGroupId,
  },
);

export const maybeDeleteSecurityGroup = new ScenarioAction(
  "deleteSecurityGroup",
  async (/** @type {State} */ state) => {
    try {
      // Delete the security group if the 'skipWhen' condition below is not met.
      await state.ec2Client.send(
        new DeleteSecurityGroupCommand({
          GroupId: state.securityGroupId,
        }),
      );
    } catch (caught) {
      if (
        caught instanceof Error &&
        caught.name === "InvalidGroupId.Malformed"
      ) {
        caught.message = `${caught.message}. Please provide a valid GroupId.`;
      }
      state.errors.push(caught);
    }
  },
  {
    // Don't do anything when there's no security group to delete
    // or the user chooses to keep it.
    skipWhen: (/** @type {State} */ state) =>
      !state.securityGroupId || !state[confirmDeleteSecurityGroup.name],
  },
);

export const authorizeSecurityGroupIngress = new ScenarioAction(
  "authorizeSecurity",
  async (/** @type {State} */ state) => {
    try {
      // Get the public IP address of the machine running this example.
      const ipAddress = await new Promise((res, rej) => {
        get("http://checkip.amazonaws.com", (response) => {
          let data = "";
          response.on("data", (chunk) => {
            data += chunk;
          });
          response.on("end", () => res(data.trim()));
        }).on("error", (err) => {
          rej(err);
        });
      });
      state.ipAddress = ipAddress;
      // Allow ingress from the IP address above to the security group.
      // This will allow you to SSH into the EC2 instance.
      const command = new AuthorizeSecurityGroupIngressCommand({
        GroupId: state.securityGroupId,
        IpPermissions: [
          {
            IpProtocol: "tcp",
            FromPort: 22,
            ToPort: 22,
            IpRanges: [{ CidrIp: `${ipAddress}/32` }],
          },
        ],
      });

      await state.ec2Client.send(command);
    } catch (caught) {
      if (
        caught instanceof Error &&
        caught.name === "InvalidGroupId.Malformed"
      ) {
        caught.message = `${caught.message}. Please provide a valid GroupId.`;
      }

      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const logSecurityGroupIngress = new ScenarioOutput(
  "logSecurityGroupIngress",
  (/** @type {State} */ state) =>
    `Allowed SSH access from your public IP: ${state.ipAddress}.`,
  { skipWhen: skipWhenErrors },
);

export const getImages = new ScenarioAction(
  "images",
  async (/** @type {State} */ state) => {
    const AMIs = [];
    // Some AWS services publish information about common artifacts as AWS Systems Manager (SSM)
    // public parameters. For example, the Amazon Elastic Compute Cloud (Amazon EC2)
    // service publishes information about Amazon Machine Images (AMIs) as public parameters.

    // Create the paginator for getting images. Actions that return multiple pages of
    // results have paginators to simplify those calls.
    const getParametersByPathPaginator = paginateGetParametersByPath(
      {
        // Not storing this client in state since it's only used once.
        client: new SSMClient({}),
      },
      {
        // The path to the public list of the latest amazon-linux instances.
        Path: "/aws/service/ami-amazon-linux-latest",
      },
    );

    try {
      for await (const page of getParametersByPathPaginator) {
        for (const param of page.Parameters) {
          // Filter by Amazon Linux 2
          if (param.Name.includes("amzn2")) {
            AMIs.push(param.Value);
          }
        }
      }
    } catch (caught) {
      if (caught instanceof Error && caught.name === "InvalidFilterValue") {
        caught.message = `${caught.message} Please provide a valid filter value for paginateGetParametersByPath.`;
      }
      state.errors.push(caught);
      return;
    }

    const imageDetails = [];
    const describeImagesPaginator = paginateDescribeImages(
      { client: state.ec2Client },
      // The images found from the call to SSM.
      { ImageIds: AMIs },
    );

    try {
      // Get more details for the images found above.
      for await (const page of describeImagesPaginator) {
        imageDetails.push(...(page.Images || []));
      }

      // Store the image details for later use.
      state.images = imageDetails;
    } catch (caught) {
      if (caught instanceof Error && caught.name === "InvalidAMIID.NotFound") {
        caught.message = `${caught.message}. Please provide a valid image id.`;
      }

      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const provideImage = new ScenarioInput(
  "image",
  "Select one of the following images.",
  {
    type: "select",
    choices: (/** @type { State } */ state) =>
      state.images.map((image) => ({
        name: `${image.Description}`,
        value: image,
      })),
    default: (/** @type { State } */ state) => state.images[0],
    skipWhen: skipWhenErrors,
  },
);

export const getCompatibleInstanceTypes = new ScenarioAction(
  "getCompatibleInstanceTypes",
  async (/** @type {State} */ state) => {
    // Get more details about instance types that match the architecture of
    // the provided image.
    const paginator = paginateDescribeInstanceTypes(
      { client: state.ec2Client, pageSize: 25 },
      {
        Filters: [
          {
            Name: "processor-info.supported-architecture",
            // The value selected from provideImage()
            Values: [state.image.Architecture],
          },
          // Filter for smaller, less expensive, types.
          { Name: "instance-type", Values: ["*.micro", "*.small"] },
        ],
      },
    );

    const instanceTypes = [];

    try {
      for await (const page of paginator) {
        if (page.InstanceTypes.length) {
          instanceTypes.push(...(page.InstanceTypes || []));
        }
      }

      if (!instanceTypes.length) {
        state.errors.push(
          "No instance types matched the instance type filters.",
        );
      }
    } catch (caught) {
      if (caught instanceof Error && caught.name === "InvalidParameterValue") {
        caught.message = `${caught.message}. Please check the provided values and try again.`;
      }

      state.errors.push(caught);
    }

    state.instanceTypes = instanceTypes;
  },
  { skipWhen: skipWhenErrors },
);

export const provideInstanceType = new ScenarioInput(
  "instanceType",
  "Select an instance type.",
  {
    choices: (/** @type {State} */ state) =>
      state.instanceTypes.map((instanceType) => ({
        name: `${instanceType.InstanceType} - Memory:${instanceType.MemoryInfo.SizeInMiB}`,
        value: instanceType.InstanceType,
      })),
    type: "select",
    default: (/** @type {State} */ state) =>
      state.instanceTypes[0].InstanceType,
    skipWhen: skipWhenErrors,
  },
);

export const runInstance = new ScenarioAction(
  "runInstance",
  async (/** @type { State } */ state) => {
    const { Instances } = await state.ec2Client.send(
      new RunInstancesCommand({
        KeyName: state[provideKeyPairName.name],
        SecurityGroupIds: [state.securityGroupId],
        ImageId: state.image.ImageId,
        InstanceType: state[provideInstanceType.name],
        // Availability Zones have capacity limitations that may impact your ability to launch instances.
        // The `RunInstances` operation will only succeed if it can allocate at least the `MinCount` of instances.
        // However, EC2 will attempt to launch up to the `MaxCount` of instances, even if the full request cannot be satisfied.
        // If you need a specific number of instances, use `MinCount` and `MaxCount` set to the same value.
        // If you want to launch up to a certain number of instances, use `MaxCount` and let EC2 provision as many as possible.
        // If you require a minimum number of instances, but do not want to exceed a maximum, use both `MinCount` and `MaxCount`.
        MinCount: 1,
        MaxCount: 1,
      }),
    );

    state.instanceId = Instances[0].InstanceId;

    try {
      // Poll `DescribeInstanceStatus` until status is "ok".
      await waitUntilInstanceStatusOk(
        {
          client: state.ec2Client,
          maxWaitTime: MAX_WAITER_TIME_IN_SECONDS,
        },
        { InstanceIds: [Instances[0].InstanceId] },
      );
    } catch (caught) {
      if (caught instanceof Error && caught.name === "TimeoutError") {
        caught.message = `${caught.message}. Try increasing the maxWaitTime in the waiter.`;
      }

      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const logRunInstance = new ScenarioOutput(
  "logRunInstance",
  "The next step is to run your EC2 instance for the first time. This can take a few minutes.",
  { header: true, skipWhen: skipWhenErrors },
);

export const describeInstance = new ScenarioAction(
  "describeInstance",
  async (/** @type { State } */ state) => {
    /** @type { import("@aws-sdk/client-ec2").Instance[] } */
    const instances = [];

    try {
      const paginator = paginateDescribeInstances(
        {
          client: state.ec2Client,
        },
        {
          // Only get our created instance.
          InstanceIds: [state.instanceId],
        },
      );

      for await (const page of paginator) {
        for (const reservation of page.Reservations) {
          instances.push(...reservation.Instances);
        }
      }
      if (instances.length !== 1) {
        throw new Error(`Instance ${state.instanceId} not found.`);
      }

      // The only info we need is the IP address for SSH purposes.
      state.instanceIpAddress = instances[0].PublicIpAddress;
    } catch (caught) {
      if (caught instanceof Error && caught.name === "InvalidParameterValue") {
        caught.message = `${caught.message}. Please check provided values and try again.`;
      }

      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const logSSHConnectionInfo = new ScenarioOutput(
  "logSSHConnectionInfo",
  (/** @type { State } */ state) =>
    `You can now SSH into your instance using the following command:
ssh -i ${state.tmpDirectory}/${state[provideKeyPairName.name]}.pem ec2-user@${state.instanceIpAddress}`,
  { preformatted: true, skipWhen: skipWhenErrors },
);

export const logStopInstance = new ScenarioOutput(
  "logStopInstance",
  "Stopping your EC2 instance.",
  { skipWhen: skipWhenErrors },
);

export const stopInstance = new ScenarioAction(
  "stopInstance",
  async (/** @type { State } */ state) => {
    try {
      await state.ec2Client.send(
        new StopInstancesCommand({
          InstanceIds: [state.instanceId],
        }),
      );

      await waitUntilInstanceStopped(
        {
          client: state.ec2Client,
          maxWaitTime: MAX_WAITER_TIME_IN_SECONDS,
        },
        { InstanceIds: [state.instanceId] },
      );
    } catch (caught) {
      if (caught instanceof Error && caught.name === "TimeoutError") {
        caught.message = `${caught.message}. Try increasing the maxWaitTime in the waiter.`;
      }

      state.errors.push(caught);
    }
  },
  // Don't try to stop an instance that doesn't exist.
  { skipWhen: (/** @type { State } */ state) => !state.instanceId },
);

export const logIpAddressBehavior = new ScenarioOutput(
  "logIpAddressBehavior",
  [
    "When you run an instance, by default it's assigned an IP address.",
    "That IP address is not static. It will change every time the instance is restarted.",
    "The next step is to stop and restart your instance to demonstrate this behavior.",
  ].join(" "),
  { header: true, skipWhen: skipWhenErrors },
);

export const logStartInstance = new ScenarioOutput(
  "logStartInstance",
  (/** @type { State } */ state) => `Starting instance ${state.instanceId}`,
  { skipWhen: skipWhenErrors },
);

export const startInstance = new ScenarioAction(
  "startInstance",
  async (/** @type { State } */ state) => {
    try {
      await state.ec2Client.send(
        new StartInstancesCommand({
          InstanceIds: [state.instanceId],
        }),
      );

      await waitUntilInstanceStatusOk(
        {
          client: state.ec2Client,
          maxWaitTime: MAX_WAITER_TIME_IN_SECONDS,
        },
        { InstanceIds: [state.instanceId] },
      );
    } catch (caught) {
      if (caught instanceof Error && caught.name === "TimeoutError") {
        caught.message = `${caught.message}. Try increasing the maxWaitTime in the waiter.`;
      }

      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const logIpAllocation = new ScenarioOutput(
  "logIpAllocation",
  [
    "It is possible to have a static IP address.",
    "To demonstrate this, an IP will be allocated and associated to your EC2 instance.",
  ].join(" "),
  { header: true, skipWhen: skipWhenErrors },
);

export const allocateIp = new ScenarioAction(
  "allocateIp",
  async (/** @type { State } */ state) => {
    try {
      // An Elastic IP address is allocated to your AWS account, and is yours until you release it.
      const { AllocationId, PublicIp } = await state.ec2Client.send(
        new AllocateAddressCommand({}),
      );
      state.allocationId = AllocationId;
      state.allocatedIpAddress = PublicIp;
    } catch (caught) {
      if (caught instanceof Error && caught.name === "MissingParameter") {
        caught.message = `${caught.message}. Did you provide these values?`;
      }
      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const associateIp = new ScenarioAction(
  "associateIp",
  async (/** @type { State } */ state) => {
    try {
      // Associate an allocated IP address to an EC2 instance. An IP address can be allocated
      // with the AllocateAddress action.
      const { AssociationId } = await state.ec2Client.send(
        new AssociateAddressCommand({
          AllocationId: state.allocationId,
          InstanceId: state.instanceId,
        }),
      );
      state.associationId = AssociationId;
      // Update the IP address that is being tracked to match
      // the one just associated.
      state.instanceIpAddress = state.allocatedIpAddress;
    } catch (caught) {
      if (
        caught instanceof Error &&
        caught.name === "InvalidAllocationID.NotFound"
      ) {
        caught.message = `${caught.message}. Did you provide the ID of a valid Elastic IP address AllocationId?`;
      }
      state.errors.push(caught);
    }
  },
  { skipWhen: skipWhenErrors },
);

export const logStaticIpProof = new ScenarioOutput(
  "logStaticIpProof",
  "The IP address should remain the same even after stopping and starting the instance.",
  { header: true, skipWhen: skipWhenErrors },
);

export const logCleanUp = new ScenarioOutput(
  "logCleanUp",
  "That's it! You can choose to clean up the resources now, or clean them up on your own later.",
  { header: true, skipWhen: skipWhenErrors },
);

export const confirmDisassociateAddress = new ScenarioInput(
  "confirmDisassociateAddress",
  "Do you want to disassociate and release the static IP address created earlier?",
  {
    type: "confirm",
    skipWhen: (/** @type { State } */ state) => !state.associationId,
  },
);

export const maybeDisassociateAddress = new ScenarioAction(
  "maybeDisassociateAddress",
  async (/** @type { State } */ state) => {
    try {
      await state.ec2Client.send(
        new DisassociateAddressCommand({
          AssociationId: state.associationId,
        }),
      );
    } catch (caught) {
      if (
        caught instanceof Error &&
        caught.name === "InvalidAssociationID.NotFound"
      ) {
        caught.message = `${caught.message}. Please provide a valid association ID.`;
      }
      state.errors.push(caught);
    }
  },
  {
    skipWhen: (/** @type { State } */ state) =>
      !state[confirmDisassociateAddress.name] || !state.associationId,
  },
);

export const maybeReleaseAddress = new ScenarioAction(
  "maybeReleaseAddress",
  async (/** @type { State } */ state) => {
    try {
      await state.ec2Client.send(
        new ReleaseAddressCommand({
          AllocationId: state.allocationId,
        }),
      );
    } catch (caught) {
      if (
        caught instanceof Error &&
        caught.name === "InvalidAllocationID.NotFound"
      ) {
        caught.message = `${caught.message}. Please provide a valid AllocationID.`;
      }
      state.errors.push(caught);
    }
  },
  {
    skipWhen: (/** @type { State } */ state) =>
      !state[confirmDisassociateAddress.name] || !state.allocationId,
  },
);

export const confirmTerminateInstance = new ScenarioInput(
  "confirmTerminateInstance",
  "Do you want to terminate the instance?",
  // Don't do anything when an instance was never run.
  {
    skipWhen: (/** @type { State } */ state) => !state.instanceId,
    type: "confirm",
  },
);

export const maybeTerminateInstance = new ScenarioAction(
  "terminateInstance",
  async (/** @type { State } */ state) => {
    try {
      await state.ec2Client.send(
        new TerminateInstancesCommand({
          InstanceIds: [state.instanceId],
        }),
      );
      await waitUntilInstanceTerminated(
        { client: state.ec2Client },
        { InstanceIds: [state.instanceId] },
      );
    } catch (caught) {
      if (caught instanceof Error && caught.name === "TimeoutError") {
        caught.message = `${caught.message}. Try increasing the maxWaitTime in the waiter.`;
      }

      state.errors.push(caught);
    }
  },
  {
    // Don't do anything when there's no instance to terminate or the
    // use chooses not to terminate.
    skipWhen: (/** @type { State } */ state) =>
      !state.instanceId || !state[confirmTerminateInstance.name],
  },
);

export const deleteTemporaryDirectory = new ScenarioAction(
  "deleteTemporaryDirectory",
  async (/** @type { State } */ state) => {
    try {
      await rm(state.tmpDirectory, { recursive: true });
    } catch (caught) {
      state.errors.push(caught);
    }
  },
);

export const logErrors = new ScenarioOutput(
  "logErrors",
  (/** @type {State}*/ state) => {
    const errorList = state.errors
      .map((err) => ` - ${err.name}: ${err.message}`)
      .join("\n");
    return `Scenario errors found:\n${errorList}`;
  },
  {
    preformatted: true,
    header: true,
    // Don't log errors when there aren't any!
    skipWhen: (/** @type {State} */ state) => state.errors.length === 0,
  },
);
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AllocateAddressCommand)
  + [AssociateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AssociateAddressCommand)
  + [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AuthorizeSecurityGroupIngressCommand)
  + [CreateKeyPair](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateKeyPairCommand)
  + [CreateSecurityGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateSecurityGroupCommand)
  + [DeleteKeyPair](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteKeyPairCommand)
  + [DeleteSecurityGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteSecurityGroupCommand)
  + [DescribeImages](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeImagesCommand)
  + [DescribeInstanceTypes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstanceTypesCommand)
  + [DescribeInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstancesCommand)
  + [DescribeKeyPairs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeKeyPairsCommand)
  + [DescribeSecurityGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSecurityGroupsCommand)
  + [DisassociateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DisassociateAddressCommand)
  + [ReleaseAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReleaseAddressCommand)
  + [RunInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RunInstancesCommand)
  + [StartInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/StartInstancesCommand)
  + [StopInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/StopInstancesCommand)
  + [TerminateInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/TerminateInstancesCommand)
  + [UnmonitorInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/UnmonitorInstancesCommand)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_javascript_3_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { AllocateAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Allocates an Elastic IP address to your AWS account.
 */
export const main = async () => {
  const client = new EC2Client({});
  const command = new AllocateAddressCommand({});

  try {
    const { AllocationId, PublicIp } = await client.send(command);
    console.log("A new IP address has been allocated to your account:");
    console.log(`ID: ${AllocationId} Public IP: ${PublicIp}`);
    console.log(
      "You can view your IP addresses in the AWS Management Console for Amazon EC2. Look under Network & Security > Elastic IPs",
    );
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide these values?`);
    } else {
      throw caught;
    }
  }
};
import { fileURLToPath } from "node:url";
// Call function if run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[AllocateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AllocateAddressCommand)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_javascript_3_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { AssociateAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Associates an Elastic IP address, or carrier IP address (for instances that are in subnets in Wavelength Zones)
 * with an instance or a network interface.
 * @param {{ instanceId: string, allocationId: string }} options
 */
export const main = async ({ instanceId, allocationId }) => {
  const client = new EC2Client({});
  const command = new AssociateAddressCommand({
    // You need to allocate an Elastic IP address before associating it with an instance.
    // You can do that with the AllocateAddressCommand.
    AllocationId: allocationId,
    // You need to create an EC2 instance before an IP address can be associated with it.
    // You can do that with the RunInstancesCommand.
    InstanceId: instanceId,
  });

  try {
    const { AssociationId } = await client.send(command);
    console.log(
      `Address with allocation ID ${allocationId} is now associated with instance ${instanceId}.`,
      `The association ID is ${AssociationId}.`,
    );
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAllocationID.NotFound"
    ) {
      console.warn(
        `${caught.message}. Did you provide the ID of a valid Elastic IP address AllocationId?`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[AssociateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AssociateAddressCommand)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_javascript_3_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import {
  AuthorizeSecurityGroupIngressCommand,
  EC2Client,
} from "@aws-sdk/client-ec2";

/**
 * Adds the specified inbound (ingress) rules to a security group.
 * @param {{ groupId: string, ipAddress: string }} options
 */
export const main = async ({ groupId, ipAddress }) => {
  const client = new EC2Client({});
  const command = new AuthorizeSecurityGroupIngressCommand({
    // Use a group ID from the AWS console or
    // the DescribeSecurityGroupsCommand.
    GroupId: groupId,
    IpPermissions: [
      {
        IpProtocol: "tcp",
        FromPort: 22,
        ToPort: 22,
        // The IP address to authorize.
        // For more information on this notation, see
        // https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation
        IpRanges: [{ CidrIp: `${ipAddress}/32` }],
      },
    ],
  });

  try {
    const { SecurityGroupRules } = await client.send(command);
    console.log(JSON.stringify(SecurityGroupRules, null, 2));
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") {
      console.warn(`${caught.message}. Please provide a valid GroupId.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/AuthorizeSecurityGroupIngressCommand)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_javascript_3_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { CreateKeyPairCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Creates an ED25519 or 2048-bit RSA key pair with the specified name and in the specified PEM or PPK format.
 * Amazon EC2 stores the public key and displays the private key for you to save to a file.
 * @param {{ keyName: string }} options
 */
export const main = async ({ keyName }) => {
  const client = new EC2Client({});
  const command = new CreateKeyPairCommand({
    KeyName: keyName,
  });

  try {
    const { KeyMaterial, KeyName } = await client.send(command);
    console.log(KeyName);
    console.log(KeyMaterial);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidKeyPair.Duplicate") {
      console.warn(`${caught.message}. Try another key name.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[CreateKeyPair](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateKeyPairCommand)」を参照してください。

### `CreateLaunchTemplate`
<a name="ec2_CreateLaunchTemplate_javascript_3_topic"></a>

次のコード例は、`CreateLaunchTemplate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const ssmClient = new SSMClient({});
    const { Parameter } = await ssmClient.send(
      new GetParameterCommand({
        Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
      }),
    );
    const ec2Client = new EC2Client({});
    await ec2Client.send(
      new CreateLaunchTemplateCommand({
        LaunchTemplateName: NAMES.launchTemplateName,
        LaunchTemplateData: {
          InstanceType: "t3.micro",
          ImageId: Parameter.Value,
          IamInstanceProfile: { Name: NAMES.instanceProfileName },
          UserData: readFileSync(
            join(RESOURCES_PATH, "server_startup_script.sh"),
          ).toString("base64"),
          KeyName: NAMES.keyPairName,
        },
      }),
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateLaunchTemplateCommand)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_javascript_3_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { CreateSecurityGroupCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Creates a security group.
 * @param {{ groupName: string, description: string }} options
 */
export const main = async ({ groupName, description }) => {
  const client = new EC2Client({});
  const command = new CreateSecurityGroupCommand({
    // Up to 255 characters in length. Cannot start with sg-.
    GroupName: groupName,
    // Up to 255 characters in length.
    Description: description,
  });

  try {
    const { GroupId } = await client.send(command);
    console.log(GroupId);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[CreateSecurityGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateSecurityGroupCommand)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_javascript_3_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteKeyPairCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Deletes the specified key pair, by removing the public key from Amazon EC2.
 * @param {{ keyName: string }} options
 */
export const main = async ({ keyName }) => {
  const client = new EC2Client({});
  const command = new DeleteKeyPairCommand({
    KeyName: keyName,
  });

  try {
    await client.send(command);
    console.log("Successfully deleted key pair.");
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide the required value?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteKeyPair](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteKeyPairCommand)」を参照してください。

### `DeleteLaunchTemplate`
<a name="ec2_DeleteLaunchTemplate_javascript_3_topic"></a>

次のコード例は、`DeleteLaunchTemplate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
      await client.send(
        new DeleteLaunchTemplateCommand({
          LaunchTemplateName: NAMES.launchTemplateName,
        }),
      );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteLaunchTemplateCommand)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_javascript_3_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteSecurityGroupCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Deletes a security group.
 * @param {{ groupId: string }} options
 */
export const main = async ({ groupId }) => {
  const client = new EC2Client({});
  const command = new DeleteSecurityGroupCommand({
    GroupId: groupId,
  });

  try {
    await client.send(command);
    console.log("Security group deleted successfully.");
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") {
      console.warn(`${caught.message}. Please provide a valid GroupId.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteSecurityGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteSecurityGroupCommand)」を参照してください。

### `DescribeAddresses`
<a name="ec2_DescribeAddresses_javascript_3_topic"></a>

次のコード例は、`DescribeAddresses` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeAddressesCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Describes the specified Elastic IP addresses or all of your Elastic IP addresses.
 * @param {{ allocationId: string }} options
 */
export const main = async ({ allocationId }) => {
  const client = new EC2Client({});
  const command = new DescribeAddressesCommand({
    // You can omit this property to show all addresses.
    AllocationIds: [allocationId],
  });

  try {
    const { Addresses } = await client.send(command);
    const addressList = Addresses.map((address) => ` • ${address.PublicIp}`);
    console.log("Elastic IP addresses:");
    console.log(addressList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAllocationID.NotFound"
    ) {
      console.warn(`${caught.message}. Please provide a valid AllocationId.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeAddresses](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeAddressesCommand)」を参照してください。

### `DescribeIamInstanceProfileAssociations`
<a name="ec2_DescribeIamInstanceProfileAssociations_javascript_3_topic"></a>

次のコード例は、`DescribeIamInstanceProfileAssociations` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
      const ec2Client = new EC2Client({});
      const { IamInstanceProfileAssociations } = await ec2Client.send(
        new DescribeIamInstanceProfileAssociationsCommand({
          Filters: [
            { Name: "instance-id", Values: [state.targetInstance.InstanceId] },
          ],
        }),
      );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeIamInstanceProfileAssociationsCommand)」を参照してください。

### `DescribeImages`
<a name="ec2_DescribeImages_javascript_3_topic"></a>

次のコード例は、`DescribeImages` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, paginateDescribeImages } from "@aws-sdk/client-ec2";

/**
 * Describes the specified images (AMIs, AKIs, and ARIs) available to you or all of the images available to you.
 * @param {{ architecture: string, pageSize: number }} options
 */
export const main = async ({ architecture, pageSize }) => {
  pageSize = Number.parseInt(pageSize);
  const client = new EC2Client({});

  // The paginate function is a wrapper around the base command.
  const paginator = paginateDescribeImages(
    // Without limiting the page size, this call can take a long time. pageSize is just sugar for
    // the MaxResults property in the base command.
    { client, pageSize },
    {
      // There are almost 70,000 images available. Be specific with your filtering
      // to increase efficiency.
      // See https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-ec2/interfaces/describeimagescommandinput.html#filters
      Filters: [{ Name: "architecture", Values: [architecture] }],
    },
  );

  /**
   * @type {import('@aws-sdk/client-ec2').Image[]}
   */
  const images = [];
  let recordsScanned = 0;

  try {
    for await (const page of paginator) {
      recordsScanned += pageSize;
      if (page.Images.length) {
        images.push(...page.Images);
        break;
      }
      console.log(
        `No matching image found yet. Searched ${recordsScanned} records.`,
      );
    }

    if (images.length) {
      console.log(
        `Found ${images.length} images:\n\n${images.map((image) => image.Name).join("\n")}\n`,
      );
    } else {
      console.log(
        `No matching images found. Searched ${recordsScanned} records.\n`,
      );
    }

    return images;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}`);
      return [];
    }
    throw caught;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeImages](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeImagesCommand)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_javascript_3_topic"></a>

次のコード例は、`DescribeInstanceTypes` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, paginateDescribeInstanceTypes } from "@aws-sdk/client-ec2";

/**
 * Describes the specified instance types. By default, all instance types for the
 * current Region are described. Alternatively, you can filter the results.
 * @param {{ pageSize: string, supportedArch: string[], freeTier: boolean }} options
 */
export const main = async ({ pageSize, supportedArch, freeTier }) => {
  pageSize = Number.parseInt(pageSize);
  const client = new EC2Client({});

  // The paginate function is a wrapper around the underlying command.
  const paginator = paginateDescribeInstanceTypes(
    // Without limiting the page size, this call can take a long time. pageSize is just sugar for
    // the MaxResults property in the underlying command.
    { client, pageSize },
    {
      Filters: [
        {
          Name: "processor-info.supported-architecture",
          Values: supportedArch,
        },
        { Name: "free-tier-eligible", Values: [freeTier ? "true" : "false"] },
      ],
    },
  );

  try {
    /**
     * @type {import('@aws-sdk/client-ec2').InstanceTypeInfo[]}
     */
    const instanceTypes = [];

    for await (const page of paginator) {
      if (page.InstanceTypes.length) {
        instanceTypes.push(...page.InstanceTypes);

        // When we have at least 1 result, we can stop.
        if (instanceTypes.length >= 1) {
          break;
        }
      }
    }
    console.log(
      `Memory size in MiB for matching instance types:\n\n${instanceTypes.map((it) => `${it.InstanceType}: ${it.MemoryInfo.SizeInMiB} MiB`).join("\n")}`,
    );
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}`);
      return [];
    }
    throw caught;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeInstanceTypes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstanceTypesCommand)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_javascript_3_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, paginateDescribeInstances } from "@aws-sdk/client-ec2";

/**
 * List all of your EC2 instances running with the provided architecture that
 * were launched in the past month.
 * @param {{ pageSize: string, architectures: string[] }} options
 */
export const main = async ({ pageSize, architectures }) => {
  pageSize = Number.parseInt(pageSize);
  const client = new EC2Client({});
  const d = new Date();
  const year = d.getFullYear();
  const month = `0${d.getMonth() + 1}`.slice(-2);
  const launchTimePattern = `${year}-${month}-*`;

  const paginator = paginateDescribeInstances(
    {
      client,
      pageSize,
    },
    {
      Filters: [
        { Name: "architecture", Values: architectures },
        { Name: "instance-state-name", Values: ["running"] },
        {
          Name: "launch-time",
          Values: [launchTimePattern],
        },
      ],
    },
  );

  try {
    /**
     * @type {import('@aws-sdk/client-ec2').Instance[]}
     */
    const instanceList = [];
    for await (const page of paginator) {
      const { Reservations } = page;
      for (const reservation of Reservations) {
        instanceList.push(...reservation.Instances);
      }
    }
    console.log(
      `Running instances launched this month:\n\n${instanceList.map((instance) => instance.InstanceId).join("\n")}`,
    );
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[DescribeInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstancesCommand)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_javascript_3_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeKeyPairsCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * List all key pairs in the current AWS account.
 * @param {{ dryRun: boolean }}
 */
export const main = async ({ dryRun }) => {
  const client = new EC2Client({});
  const command = new DescribeKeyPairsCommand({ DryRun: dryRun });

  try {
    const { KeyPairs } = await client.send(command);
    const keyPairList = KeyPairs.map(
      (kp) => ` • ${kp.KeyPairId}: ${kp.KeyName}`,
    ).join("\n");
    console.log("The following key pairs were found in your account:");
    console.log(keyPairList);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "DryRunOperation") {
      console.log(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeKeyPairs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeKeyPairsCommand)」を参照してください。

### `DescribeRegions`
<a name="ec2_DescribeRegions_javascript_3_topic"></a>

次のコード例は、`DescribeRegions` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeRegionsCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * List all available AWS regions.
 * @param {{ regionNames: string[], includeOptInRegions: boolean }} options
 */
export const main = async ({ regionNames, includeOptInRegions }) => {
  const client = new EC2Client({});
  const command = new DescribeRegionsCommand({
    // By default this command will not show regions that require you to opt-in.
    // When AllRegions is true, even the regions that require opt-in will be returned.
    AllRegions: includeOptInRegions,
    // You can omit the Filters property if you want to get all regions.
    Filters: regionNames?.length
      ? [
          {
            Name: "region-name",
            // You can specify multiple values for a filter.
            // You can also use '*' as a wildcard. This will return all
            // of the regions that start with `us-east-`.
            Values: regionNames,
          },
        ]
      : undefined,
  });

  try {
    const { Regions } = await client.send(command);
    const regionsList = Regions.map((reg) => ` • ${reg.RegionName}`);
    console.log("Found regions:");
    console.log(regionsList.join("\n"));
  } catch (caught) {
    if (caught instanceof Error && caught.name === "DryRunOperation") {
      console.log(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[DescribeRegions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeRegionsCommand)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_javascript_3_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeSecurityGroupsCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Describes the specified security groups or all of your security groups.
 * @param {{ groupIds: string[] }} options
 */
export const main = async ({ groupIds = [] }) => {
  const client = new EC2Client({});
  const command = new DescribeSecurityGroupsCommand({
    GroupIds: groupIds,
  });

  try {
    const { SecurityGroups } = await client.send(command);
    const sgList = SecurityGroups.map(
      (sg) => `• ${sg.GroupName} (${sg.GroupId}): ${sg.Description}`,
    ).join("\n");
    if (sgList.length) {
      console.log(`Security groups:\n${sgList}`);
    } else {
      console.log("No security groups found.");
    }
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") {
      console.warn(`${caught.message}. Please provide a valid GroupId.`);
    } else if (
      caught instanceof Error &&
      caught.name === "InvalidGroup.NotFound"
    ) {
      console.warn(caught.message);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSecurityGroupsCommand)」を参照してください。

### `DescribeSubnets`
<a name="ec2_DescribeSubnets_javascript_3_topic"></a>

次のコード例は、`DescribeSubnets` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const client = new EC2Client({});
    const { Subnets } = await client.send(
      new DescribeSubnetsCommand({
        Filters: [
          { Name: "vpc-id", Values: [state.defaultVpc] },
          { Name: "availability-zone", Values: state.availabilityZoneNames },
          { Name: "default-for-az", Values: ["true"] },
        ],
      }),
    );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeSubnets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSubnetsCommand)」を参照してください。

### `DescribeVpcs`
<a name="ec2_DescribeVpcs_javascript_3_topic"></a>

次のコード例は、`DescribeVpcs` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const client = new EC2Client({});
    const { Vpcs } = await client.send(
      new DescribeVpcsCommand({
        Filters: [{ Name: "is-default", Values: ["true"] }],
      }),
    );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeVpcs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeVpcsCommand)」を参照してください。

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_javascript_3_topic"></a>

次のコード例は、`DisassociateAddress` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { DisassociateAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Disassociate an Elastic IP address from an instance.
 * @param {{ associationId: string }} options
 */
export const main = async ({ associationId }) => {
  const client = new EC2Client({});
  const command = new DisassociateAddressCommand({
    // You can also use PublicIp, but that is for EC2 classic which is being retired.
    AssociationId: associationId,
  });

  try {
    await client.send(command);
    console.log("Successfully disassociated address");
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAssociationID.NotFound"
    ) {
      console.warn(`${caught.message}.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DisassociateAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DisassociateAddressCommand)」を参照してください。

### `MonitorInstances`
<a name="ec2_MonitorInstances_javascript_3_topic"></a>

次のコード例は、`MonitorInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, MonitorInstancesCommand } from "@aws-sdk/client-ec2";

/**
 * Turn on detailed monitoring for the selected instance.
 * By default, metrics are sent to Amazon CloudWatch every 5 minutes.
 * For a cost you can enable detailed monitoring which sends metrics every minute.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new MonitorInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { InstanceMonitorings } = await client.send(command);
    const instancesBeingMonitored = InstanceMonitorings.map(
      (im) =>
        ` • Detailed monitoring state for ${im.InstanceId} is ${im.Monitoring.State}.`,
    );
    console.log("Monitoring status:");
    console.log(instancesBeingMonitored.join("\n"));
  } catch (caught) {
    if (caught instanceof Error && caught.name === "InvalidParameterValue") {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[MonitorInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/MonitorInstancesCommand)」を参照してください。

### `RebootInstances`
<a name="ec2_RebootInstances_javascript_3_topic"></a>

次のコード例は、`RebootInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, RebootInstancesCommand } from "@aws-sdk/client-ec2";

/**
 * Requests a reboot of the specified instances. This operation is asynchronous;
 * it only queues a request to reboot the specified instances.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new RebootInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    await client.send(command);
    console.log("Instance rebooted successfully.");
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(
        `${caught.message}. Please provide the InstanceId of a valid instance to reboot.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[RebootInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RebootInstancesCommand)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_javascript_3_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { ReleaseAddressCommand, EC2Client } from "@aws-sdk/client-ec2";

/**
 * Release an Elastic IP address.
 * @param {{ allocationId: string }} options
 */
export const main = async ({ allocationId }) => {
  const client = new EC2Client({});
  const command = new ReleaseAddressCommand({
    // You can also use PublicIp, but that is for EC2 classic which is being retired.
    AllocationId: allocationId,
  });

  try {
    await client.send(command);
    console.log("Successfully released address.");
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidAllocationID.NotFound"
    ) {
      console.warn(`${caught.message}. Please provide a valid AllocationID.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[ReleaseAddress](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReleaseAddressCommand)」を参照してください。

### `ReplaceIamInstanceProfileAssociation`
<a name="ec2_ReplaceIamInstanceProfileAssociation_javascript_3_topic"></a>

次のコード例は、`ReplaceIamInstanceProfileAssociation` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        ec2Client.send(
          new ReplaceIamInstanceProfileAssociationCommand({
            AssociationId: state.instanceProfileAssociationId,
            IamInstanceProfile: { Name: NAMES.ssmOnlyInstanceProfileName },
          }),
        ),
      );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReplaceIamInstanceProfileAssociationCommand)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_javascript_3_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, RunInstancesCommand } from "@aws-sdk/client-ec2";

/**
 * Create new EC2 instances.
 * @param {{
 *  keyName: string,
 *  securityGroupIds: string[],
 *  imageId: string,
 *  instanceType: import('@aws-sdk/client-ec2')._InstanceType,
 *  minCount?: number,
 *  maxCount?: number }} options
 */
export const main = async ({
  keyName,
  securityGroupIds,
  imageId,
  instanceType,
  minCount = "1",
  maxCount = "1",
}) => {
  const client = new EC2Client({});
  minCount = Number.parseInt(minCount);
  maxCount = Number.parseInt(maxCount);
  const command = new RunInstancesCommand({
    // Your key pair name.
    KeyName: keyName,
    // Your security group.
    SecurityGroupIds: securityGroupIds,
    // An Amazon Machine Image (AMI). There are multiple ways to search for AMIs. For more information, see:
    // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html
    ImageId: imageId,
    // An instance type describing the resources provided to your instance. There are multiple
    // ways to search for instance types. For more information see:
    // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-discovery.html
    InstanceType: instanceType,
    // Availability Zones have capacity limitations that may impact your ability to launch instances.
    // The `RunInstances` operation will only succeed if it can allocate at least the `MinCount` of instances.
    // However, EC2 will attempt to launch up to the `MaxCount` of instances, even if the full request cannot be satisfied.
    // If you need a specific number of instances, use `MinCount` and `MaxCount` set to the same value.
    // If you want to launch up to a certain number of instances, use `MaxCount` and let EC2 provision as many as possible.
    // If you require a minimum number of instances, but do not want to exceed a maximum, use both `MinCount` and `MaxCount`.
    MinCount: minCount,
    MaxCount: maxCount,
  });

  try {
    const { Instances } = await client.send(command);
    const instanceList = Instances.map(
      (instance) => `• ${instance.InstanceId}`,
    ).join("\n");
    console.log(`Launched instances:\n${instanceList}`);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceCountExceeded") {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[RunInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RunInstancesCommand)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_javascript_3_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, StartInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Starts an Amazon EBS-backed instance that you've previously stopped.
 * @param {{ instanceIds }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new StartInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { StartingInstances } = await client.send(command);
    const instanceIdList = StartingInstances.map(
      (instance) => ` • ${instance.InstanceId}`,
    );
    console.log("Starting instances:");
    console.log(instanceIdList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[StartInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/StartInstancesCommand)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_javascript_3_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, StopInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Stop one or more EC2 instances.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new StopInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { StoppingInstances } = await client.send(command);
    const instanceIdList = StoppingInstances.map(
      (instance) => ` • ${instance.InstanceId}`,
    );
    console.log("Stopping instances:");
    console.log(instanceIdList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[StopInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/StopInstancesCommand)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_javascript_3_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, TerminateInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Terminate one or more EC2 instances.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new TerminateInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { TerminatingInstances } = await client.send(command);
    const instanceList = TerminatingInstances.map(
      (instance) => ` • ${instance.InstanceId}`,
    );
    console.log("Terminating instances:");
    console.log(instanceList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[TerminateInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/TerminateInstancesCommand)」を参照してください。

### `UnmonitorInstances`
<a name="ec2_UnmonitorInstances_javascript_3_topic"></a>

次のコード例は、`UnmonitorInstances` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import { EC2Client, UnmonitorInstancesCommand } from "@aws-sdk/client-ec2";
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

/**
 * Turn off detailed monitoring for the selected instance.
 * @param {{ instanceIds: string[] }} options
 */
export const main = async ({ instanceIds }) => {
  const client = new EC2Client({});
  const command = new UnmonitorInstancesCommand({
    InstanceIds: instanceIds,
  });

  try {
    const { InstanceMonitorings } = await client.send(command);
    const instanceMonitoringsList = InstanceMonitorings.map(
      (im) =>
        ` • Detailed monitoring state for ${im.InstanceId} is ${im.Monitoring.State}.`,
    );
    console.log("Monitoring status:");
    console.log(instanceMonitoringsList.join("\n"));
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInstanceID.NotFound"
    ) {
      console.warn(`${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UnmonitorInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/UnmonitorInstancesCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_javascript_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
#!/usr/bin/env node
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import {
  Scenario,
  parseScenarioArgs,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

/**
 * The workflow steps are split into three stages:
 *   - deploy
 *   - demo
 *   - destroy
 *
 * Each of these stages has a corresponding file prefixed with steps-*.
 */
import { deploySteps } from "./steps-deploy.js";
import { demoSteps } from "./steps-demo.js";
import { destroySteps } from "./steps-destroy.js";

/**
 * The context is passed to every scenario. Scenario steps
 * will modify the context.
 */
const context = {};

/**
 * Three Scenarios are created for the workflow. A Scenario is an orchestration class
 * that simplifies running a series of steps.
 */
export const scenarios = {
  // Deploys all resources necessary for the workflow.
  deploy: new Scenario("Resilient Workflow - Deploy", deploySteps, context),
  // Demonstrates how a fragile web service can be made more resilient.
  demo: new Scenario("Resilient Workflow - Demo", demoSteps, context),
  // Destroys the resources created for the workflow.
  destroy: new Scenario("Resilient Workflow - Destroy", destroySteps, context),
};

// Call function if run directly
import { fileURLToPath } from "node:url";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  parseScenarioArgs(scenarios, {
    name: "Resilient Workflow",
    synopsis:
      "node index.js --scenario <deploy | demo | destroy> [-h|--help] [-y|--yes] [-v|--verbose]",
    description: "Deploy and interact with scalable EC2 instances.",
  });
}
```
すべてのリソースをデプロイするための手順を作成します。  

```
import { join } from "node:path";
import { readFileSync, writeFileSync } from "node:fs";
import axios from "axios";

import {
  BatchWriteItemCommand,
  CreateTableCommand,
  DynamoDBClient,
  waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  CreateKeyPairCommand,
  CreateLaunchTemplateCommand,
  DescribeAvailabilityZonesCommand,
  DescribeVpcsCommand,
  DescribeSubnetsCommand,
  DescribeSecurityGroupsCommand,
  AuthorizeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  AttachRolePolicyCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";
import {
  CreateAutoScalingGroupCommand,
  AutoScalingClient,
  AttachLoadBalancerTargetGroupsCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  CreateListenerCommand,
  CreateLoadBalancerCommand,
  CreateTargetGroupCommand,
  ElasticLoadBalancingV2Client,
  waitUntilLoadBalancerAvailable,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { saveState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH, ROOT } from "./constants.js";
import { initParamsSteps } from "./steps-reset-params.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const deploySteps = [
  new ScenarioOutput("introduction", MESSAGES.introduction, { header: true }),
  new ScenarioInput("confirmDeployment", MESSAGES.confirmDeployment, {
    type: "confirm",
  }),
  new ScenarioAction(
    "handleConfirmDeployment",
    (c) => c.confirmDeployment === false && process.exit(),
  ),
  new ScenarioOutput(
    "creatingTable",
    MESSAGES.creatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("createTable", async () => {
    const client = new DynamoDBClient({});
    await client.send(
      new CreateTableCommand({
        TableName: NAMES.tableName,
        ProvisionedThroughput: {
          ReadCapacityUnits: 5,
          WriteCapacityUnits: 5,
        },
        AttributeDefinitions: [
          {
            AttributeName: "MediaType",
            AttributeType: "S",
          },
          {
            AttributeName: "ItemId",
            AttributeType: "N",
          },
        ],
        KeySchema: [
          {
            AttributeName: "MediaType",
            KeyType: "HASH",
          },
          {
            AttributeName: "ItemId",
            KeyType: "RANGE",
          },
        ],
      }),
    );
    await waitUntilTableExists({ client }, { TableName: NAMES.tableName });
  }),
  new ScenarioOutput(
    "createdTable",
    MESSAGES.createdTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "populatingTable",
    MESSAGES.populatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("populateTable", () => {
    const client = new DynamoDBClient({});
    /**
     * @type {{ default: import("@aws-sdk/client-dynamodb").PutRequest['Item'][] }}
     */
    const recommendations = JSON.parse(
      readFileSync(join(RESOURCES_PATH, "recommendations.json")),
    );

    return client.send(
      new BatchWriteItemCommand({
        RequestItems: {
          [NAMES.tableName]: recommendations.map((item) => ({
            PutRequest: { Item: item },
          })),
        },
      }),
    );
  }),
  new ScenarioOutput(
    "populatedTable",
    MESSAGES.populatedTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "creatingKeyPair",
    MESSAGES.creatingKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioAction("createKeyPair", async () => {
    const client = new EC2Client({});
    const { KeyMaterial } = await client.send(
      new CreateKeyPairCommand({
        KeyName: NAMES.keyPairName,
      }),
    );

    writeFileSync(`${NAMES.keyPairName}.pem`, KeyMaterial, { mode: 0o600 });
  }),
  new ScenarioOutput(
    "createdKeyPair",
    MESSAGES.createdKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioOutput(
    "creatingInstancePolicy",
    MESSAGES.creatingInstancePolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    ),
  ),
  new ScenarioAction("createInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const {
      Policy: { Arn },
    } = await client.send(
      new CreatePolicyCommand({
        PolicyName: NAMES.instancePolicyName,
        PolicyDocument: readFileSync(
          join(RESOURCES_PATH, "instance_policy.json"),
        ),
      }),
    );
    state.instancePolicyArn = Arn;
  }),
  new ScenarioOutput("createdInstancePolicy", (state) =>
    MESSAGES.createdInstancePolicy
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_POLICY_ARN}", state.instancePolicyArn),
  ),
  new ScenarioOutput(
    "creatingInstanceRole",
    MESSAGES.creatingInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioAction("createInstanceRole", () => {
    const client = new IAMClient({});
    return client.send(
      new CreateRoleCommand({
        RoleName: NAMES.instanceRoleName,
        AssumeRolePolicyDocument: readFileSync(
          join(ROOT, "assume-role-policy.json"),
        ),
      }),
    );
  }),
  new ScenarioOutput(
    "createdInstanceRole",
    MESSAGES.createdInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioOutput(
    "attachingPolicyToRole",
    MESSAGES.attachingPolicyToRole
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName)
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName),
  ),
  new ScenarioAction("attachPolicyToRole", async (state) => {
    const client = new IAMClient({});
    await client.send(
      new AttachRolePolicyCommand({
        RoleName: NAMES.instanceRoleName,
        PolicyArn: state.instancePolicyArn,
      }),
    );
  }),
  new ScenarioOutput(
    "attachedPolicyToRole",
    MESSAGES.attachedPolicyToRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioOutput(
    "creatingInstanceProfile",
    MESSAGES.creatingInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    ),
  ),
  new ScenarioAction("createInstanceProfile", async (state) => {
    const client = new IAMClient({});
    const {
      InstanceProfile: { Arn },
    } = await client.send(
      new CreateInstanceProfileCommand({
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
    state.instanceProfileArn = Arn;

    await waitUntilInstanceProfileExists(
      { client },
      { InstanceProfileName: NAMES.instanceProfileName },
    );
  }),
  new ScenarioOutput("createdInstanceProfile", (state) =>
    MESSAGES.createdInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_PROFILE_ARN}", state.instanceProfileArn),
  ),
  new ScenarioOutput(
    "addingRoleToInstanceProfile",
    MESSAGES.addingRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioAction("addRoleToInstanceProfile", () => {
    const client = new IAMClient({});
    return client.send(
      new AddRoleToInstanceProfileCommand({
        RoleName: NAMES.instanceRoleName,
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
  }),
  new ScenarioOutput(
    "addedRoleToInstanceProfile",
    MESSAGES.addedRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  ...initParamsSteps,
  new ScenarioOutput("creatingLaunchTemplate", MESSAGES.creatingLaunchTemplate),
  new ScenarioAction("createLaunchTemplate", async () => {
    const ssmClient = new SSMClient({});
    const { Parameter } = await ssmClient.send(
      new GetParameterCommand({
        Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
      }),
    );
    const ec2Client = new EC2Client({});
    await ec2Client.send(
      new CreateLaunchTemplateCommand({
        LaunchTemplateName: NAMES.launchTemplateName,
        LaunchTemplateData: {
          InstanceType: "t3.micro",
          ImageId: Parameter.Value,
          IamInstanceProfile: { Name: NAMES.instanceProfileName },
          UserData: readFileSync(
            join(RESOURCES_PATH, "server_startup_script.sh"),
          ).toString("base64"),
          KeyName: NAMES.keyPairName,
        },
      }),
    );
  }),
  new ScenarioOutput(
    "createdLaunchTemplate",
    MESSAGES.createdLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    ),
  ),
  new ScenarioOutput(
    "creatingAutoScalingGroup",
    MESSAGES.creatingAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    ),
  ),
  new ScenarioAction("createAutoScalingGroup", async (state) => {
    const ec2Client = new EC2Client({});
    const { AvailabilityZones } = await ec2Client.send(
      new DescribeAvailabilityZonesCommand({}),
    );
    state.availabilityZoneNames = AvailabilityZones.map((az) => az.ZoneName);
    const autoScalingClient = new AutoScalingClient({});
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new CreateAutoScalingGroupCommand({
          AvailabilityZones: state.availabilityZoneNames,
          AutoScalingGroupName: NAMES.autoScalingGroupName,
          LaunchTemplate: {
            LaunchTemplateName: NAMES.launchTemplateName,
            Version: "$Default",
          },
          MinSize: 3,
          MaxSize: 3,
        }),
      ),
    );
  }),
  new ScenarioOutput(
    "createdAutoScalingGroup",
    /**
     * @param {{ availabilityZoneNames: string[] }} state
     */
    (state) =>
      MESSAGES.createdAutoScalingGroup
        .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName)
        .replace(
          "${AVAILABILITY_ZONE_NAMES}",
          state.availabilityZoneNames.join(", "),
        ),
  ),
  new ScenarioInput("confirmContinue", MESSAGES.confirmContinue, {
    type: "confirm",
  }),
  new ScenarioOutput("loadBalancer", MESSAGES.loadBalancer),
  new ScenarioOutput("gettingVpc", MESSAGES.gettingVpc),
  new ScenarioAction("getVpc", async (state) => {
    const client = new EC2Client({});
    const { Vpcs } = await client.send(
      new DescribeVpcsCommand({
        Filters: [{ Name: "is-default", Values: ["true"] }],
      }),
    );
    state.defaultVpc = Vpcs[0].VpcId;
  }),
  new ScenarioOutput("gotVpc", (state) =>
    MESSAGES.gotVpc.replace("${VPC_ID}", state.defaultVpc),
  ),
  new ScenarioOutput("gettingSubnets", MESSAGES.gettingSubnets),
  new ScenarioAction("getSubnets", async (state) => {
    const client = new EC2Client({});
    const { Subnets } = await client.send(
      new DescribeSubnetsCommand({
        Filters: [
          { Name: "vpc-id", Values: [state.defaultVpc] },
          { Name: "availability-zone", Values: state.availabilityZoneNames },
          { Name: "default-for-az", Values: ["true"] },
        ],
      }),
    );
    state.subnets = Subnets.map((subnet) => subnet.SubnetId);
  }),
  new ScenarioOutput(
    "gotSubnets",
    /**
     * @param {{ subnets: string[] }} state
     */
    (state) =>
      MESSAGES.gotSubnets.replace("${SUBNETS}", state.subnets.join(", ")),
  ),
  new ScenarioOutput(
    "creatingLoadBalancerTargetGroup",
    MESSAGES.creatingLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioAction("createLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { TargetGroups } = await client.send(
      new CreateTargetGroupCommand({
        Name: NAMES.loadBalancerTargetGroupName,
        Protocol: "HTTP",
        Port: 80,
        HealthCheckPath: "/healthcheck",
        HealthCheckIntervalSeconds: 10,
        HealthCheckTimeoutSeconds: 5,
        HealthyThresholdCount: 2,
        UnhealthyThresholdCount: 2,
        VpcId: state.defaultVpc,
      }),
    );
    const targetGroup = TargetGroups[0];
    state.targetGroupArn = targetGroup.TargetGroupArn;
    state.targetGroupProtocol = targetGroup.Protocol;
    state.targetGroupPort = targetGroup.Port;
  }),
  new ScenarioOutput(
    "createdLoadBalancerTargetGroup",
    MESSAGES.createdLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioOutput(
    "creatingLoadBalancer",
    MESSAGES.creatingLoadBalancer.replace("${LB_NAME}", NAMES.loadBalancerName),
  ),
  new ScenarioAction("createLoadBalancer", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { LoadBalancers } = await client.send(
      new CreateLoadBalancerCommand({
        Name: NAMES.loadBalancerName,
        Subnets: state.subnets,
      }),
    );
    state.loadBalancerDns = LoadBalancers[0].DNSName;
    state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn;
    await waitUntilLoadBalancerAvailable(
      { client },
      { Names: [NAMES.loadBalancerName] },
    );
  }),
  new ScenarioOutput("createdLoadBalancer", (state) =>
    MESSAGES.createdLoadBalancer
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioOutput(
    "creatingListener",
    MESSAGES.creatingLoadBalancerListener
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName),
  ),
  new ScenarioAction("createListener", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { Listeners } = await client.send(
      new CreateListenerCommand({
        LoadBalancerArn: state.loadBalancerArn,
        Protocol: state.targetGroupProtocol,
        Port: state.targetGroupPort,
        DefaultActions: [
          { Type: "forward", TargetGroupArn: state.targetGroupArn },
        ],
      }),
    );
    const listener = Listeners[0];
    state.loadBalancerListenerArn = listener.ListenerArn;
  }),
  new ScenarioOutput("createdListener", (state) =>
    MESSAGES.createdLoadBalancerListener.replace(
      "${LB_LISTENER_ARN}",
      state.loadBalancerListenerArn,
    ),
  ),
  new ScenarioOutput(
    "attachingLoadBalancerTargetGroup",
    MESSAGES.attachingLoadBalancerTargetGroup
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName)
      .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName),
  ),
  new ScenarioAction("attachLoadBalancerTargetGroup", async (state) => {
    const client = new AutoScalingClient({});
    await client.send(
      new AttachLoadBalancerTargetGroupsCommand({
        AutoScalingGroupName: NAMES.autoScalingGroupName,
        TargetGroupARNs: [state.targetGroupArn],
      }),
    );
  }),
  new ScenarioOutput(
    "attachedLoadBalancerTargetGroup",
    MESSAGES.attachedLoadBalancerTargetGroup,
  ),
  new ScenarioOutput("verifyingInboundPort", MESSAGES.verifyingInboundPort),
  new ScenarioAction(
    "verifyInboundPort",
    /**
     *
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup}} state
     */
    async (state) => {
      const client = new EC2Client({});
      const { SecurityGroups } = await client.send(
        new DescribeSecurityGroupsCommand({
          Filters: [{ Name: "group-name", Values: ["default"] }],
        }),
      );
      if (!SecurityGroups) {
        state.verifyInboundPortError = new Error(MESSAGES.noSecurityGroups);
      }
      state.defaultSecurityGroup = SecurityGroups[0];

      /**
       * @type {string}
       */
      const ipResponse = (await axios.get("http://checkip.amazonaws.com")).data;
      state.myIp = ipResponse.trim();
      const myIpRules = state.defaultSecurityGroup.IpPermissions.filter(
        ({ IpRanges }) =>
          IpRanges.some(
            ({ CidrIp }) =>
              CidrIp.startsWith(state.myIp) || CidrIp === "0.0.0.0/0",
          ),
      )
        .filter(({ IpProtocol }) => IpProtocol === "tcp")
        .filter(({ FromPort }) => FromPort === 80);

      state.myIpRules = myIpRules;
    },
  ),
  new ScenarioOutput(
    "verifiedInboundPort",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return MESSAGES.foundIpRules.replace(
          "${IP_RULES}",
          JSON.stringify(state.myIpRules, null, 2),
        );
      }
      return MESSAGES.noIpRules;
    },
  ),
  new ScenarioInput(
    "shouldAddInboundRule",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return false;
      }
      return MESSAGES.noIpRules;
    },
    { type: "confirm" },
  ),
  new ScenarioAction(
    "addInboundRule",
    /**
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup }} state
     */
    async (state) => {
      if (!state.shouldAddInboundRule) {
        return;
      }

      const client = new EC2Client({});
      await client.send(
        new AuthorizeSecurityGroupIngressCommand({
          GroupId: state.defaultSecurityGroup.GroupId,
          CidrIp: `${state.myIp}/32`,
          FromPort: 80,
          ToPort: 80,
          IpProtocol: "tcp",
        }),
      );
    },
  ),
  new ScenarioOutput("addedInboundRule", (state) => {
    if (state.shouldAddInboundRule) {
      return MESSAGES.addedInboundRule.replace("${IP_ADDRESS}", state.myIp);
    }
    return false;
  }),
  new ScenarioOutput("verifyingEndpoint", (state) =>
    MESSAGES.verifyingEndpoint.replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioAction("verifyEndpoint", async (state) => {
    try {
      const response = await retry({ intervalInMs: 2000, maxRetries: 30 }, () =>
        axios.get(`http://${state.loadBalancerDns}`),
      );
      state.endpointResponse = JSON.stringify(response.data, null, 2);
    } catch (e) {
      state.verifyEndpointError = e;
    }
  }),
  new ScenarioOutput("verifiedEndpoint", (state) => {
    if (state.verifyEndpointError) {
      console.error(state.verifyEndpointError);
    } else {
      return MESSAGES.verifiedEndpoint.replace(
        "${ENDPOINT_RESPONSE}",
        state.endpointResponse,
      );
    }
  }),
  saveState,
];
```
デモを実行するための手順を作成します。  

```
import { readFileSync } from "node:fs";
import { join } from "node:path";

import axios from "axios";

import {
  DescribeTargetGroupsCommand,
  DescribeTargetHealthCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";
import {
  DescribeInstanceInformationCommand,
  PutParameterCommand,
  SSMClient,
  SendCommandCommand,
} from "@aws-sdk/client-ssm";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DescribeAutoScalingGroupsCommand,
  TerminateInstanceInAutoScalingGroupCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  DescribeIamInstanceProfileAssociationsCommand,
  EC2Client,
  RebootInstancesCommand,
  ReplaceIamInstanceProfileAssociationCommand,
} from "@aws-sdk/client-ec2";

import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

const getRecommendation = new ScenarioAction(
  "getRecommendation",
  async (state) => {
    const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
    if (loadBalancer) {
      state.loadBalancerDnsName = loadBalancer.DNSName;
      try {
        state.recommendation = (
          await axios.get(`http://${state.loadBalancerDnsName}`)
        ).data;
      } catch (e) {
        state.recommendation = e instanceof Error ? e.message : e;
      }
    } else {
      throw new Error(MESSAGES.demoFindLoadBalancerError);
    }
  },
);

const getRecommendationResult = new ScenarioOutput(
  "getRecommendationResult",
  (state) =>
    `Recommendation:\n${JSON.stringify(state.recommendation, null, 2)}`,
  { preformatted: true },
);

const getHealthCheck = new ScenarioAction("getHealthCheck", async (state) => {
  const client = new ElasticLoadBalancingV2Client({});
  const { TargetGroups } = await client.send(
    new DescribeTargetGroupsCommand({
      Names: [NAMES.loadBalancerTargetGroupName],
    }),
  );

  const { TargetHealthDescriptions } = await client.send(
    new DescribeTargetHealthCommand({
      TargetGroupArn: TargetGroups[0].TargetGroupArn,
    }),
  );
  state.targetHealthDescriptions = TargetHealthDescriptions;
});

const getHealthCheckResult = new ScenarioOutput(
  "getHealthCheckResult",
  /**
   * @param {{ targetHealthDescriptions: import('@aws-sdk/client-elastic-load-balancing-v2').TargetHealthDescription[]}} state
   */
  (state) => {
    const status = state.targetHealthDescriptions
      .map((th) => `${th.Target.Id}: ${th.TargetHealth.State}`)
      .join("\n");
    return `Health check:\n${status}`;
  },
  { preformatted: true },
);

const loadBalancerLoop = new ScenarioAction(
  "loadBalancerLoop",
  getRecommendation.action,
  {
    whileConfig: {
      whileFn: ({ loadBalancerCheck }) => loadBalancerCheck,
      input: new ScenarioInput(
        "loadBalancerCheck",
        MESSAGES.demoLoadBalancerCheck,
        {
          type: "confirm",
        },
      ),
      output: getRecommendationResult,
    },
  },
);

const healthCheckLoop = new ScenarioAction(
  "healthCheckLoop",
  getHealthCheck.action,
  {
    whileConfig: {
      whileFn: ({ healthCheck }) => healthCheck,
      input: new ScenarioInput("healthCheck", MESSAGES.demoHealthCheck, {
        type: "confirm",
      }),
      output: getHealthCheckResult,
    },
  },
);

const statusSteps = [
  getRecommendation,
  getRecommendationResult,
  getHealthCheck,
  getHealthCheckResult,
];

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const demoSteps = [
  new ScenarioOutput("header", MESSAGES.demoHeader, { header: true }),
  new ScenarioOutput("sanityCheck", MESSAGES.demoSanityCheck),
  ...statusSteps,
  new ScenarioInput(
    "brokenDependencyConfirmation",
    MESSAGES.demoBrokenDependencyConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("brokenDependency", async (state) => {
    if (!state.brokenDependencyConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      state.badTableName = `fake-table-${Date.now()}`;
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmTableNameKey,
          Value: state.badTableName,
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testBrokenDependency", (state) =>
    MESSAGES.demoTestBrokenDependency.replace(
      "${TABLE_NAME}",
      state.badTableName,
    ),
  ),
  ...statusSteps,
  new ScenarioInput(
    "staticResponseConfirmation",
    MESSAGES.demoStaticResponseConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("staticResponse", async (state) => {
    if (!state.staticResponseConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmFailureResponseKey,
          Value: "static",
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testStaticResponse", MESSAGES.demoTestStaticResponse),
  ...statusSteps,
  new ScenarioInput(
    "badCredentialsConfirmation",
    MESSAGES.demoBadCredentialsConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("badCredentialsExit", (state) => {
    if (!state.badCredentialsConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("fixDynamoDBName", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioAction(
    "badCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-auto-scaling').Instance }} state
     */
    async (state) => {
      await createSsmOnlyInstanceProfile();
      const autoScalingClient = new AutoScalingClient({});
      const { AutoScalingGroups } = await autoScalingClient.send(
        new DescribeAutoScalingGroupsCommand({
          AutoScalingGroupNames: [NAMES.autoScalingGroupName],
        }),
      );
      state.targetInstance = AutoScalingGroups[0].Instances[0];
      const ec2Client = new EC2Client({});
      const { IamInstanceProfileAssociations } = await ec2Client.send(
        new DescribeIamInstanceProfileAssociationsCommand({
          Filters: [
            { Name: "instance-id", Values: [state.targetInstance.InstanceId] },
          ],
        }),
      );
      state.instanceProfileAssociationId =
        IamInstanceProfileAssociations[0].AssociationId;
      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        ec2Client.send(
          new ReplaceIamInstanceProfileAssociationCommand({
            AssociationId: state.instanceProfileAssociationId,
            IamInstanceProfile: { Name: NAMES.ssmOnlyInstanceProfileName },
          }),
        ),
      );

      await ec2Client.send(
        new RebootInstancesCommand({
          InstanceIds: [state.targetInstance.InstanceId],
        }),
      );

      const ssmClient = new SSMClient({});
      await retry({ intervalInMs: 20000, maxRetries: 15 }, async () => {
        const { InstanceInformationList } = await ssmClient.send(
          new DescribeInstanceInformationCommand({}),
        );

        const instance = InstanceInformationList.find(
          (info) => info.InstanceId === state.targetInstance.InstanceId,
        );

        if (!instance) {
          throw new Error("Instance not found.");
        }
      });

      await ssmClient.send(
        new SendCommandCommand({
          InstanceIds: [state.targetInstance.InstanceId],
          DocumentName: "AWS-RunShellScript",
          Parameters: { commands: ["cd / && sudo python3 server.py 80"] },
        }),
      );
    },
  ),
  new ScenarioOutput(
    "testBadCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation}} state
     */
    (state) =>
      MESSAGES.demoTestBadCredentials.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
  ),
  loadBalancerLoop,
  new ScenarioInput(
    "deepHealthCheckConfirmation",
    MESSAGES.demoDeepHealthCheckConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("deepHealthCheckExit", (state) => {
    if (!state.deepHealthCheckConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("deepHealthCheck", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmHealthCheckKey,
        Value: "deep",
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testDeepHealthCheck", MESSAGES.demoTestDeepHealthCheck),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "killInstanceConfirmation",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    (state) =>
      MESSAGES.demoKillInstanceConfirmation.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
    { type: "confirm" },
  ),
  new ScenarioAction("killInstanceExit", (state) => {
    if (!state.killInstanceConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction(
    "killInstance",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    async (state) => {
      const client = new AutoScalingClient({});
      await client.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: state.targetInstance.InstanceId,
          ShouldDecrementDesiredCapacity: false,
        }),
      );
    },
  ),
  new ScenarioOutput("testKillInstance", MESSAGES.demoTestKillInstance),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput("failOpenConfirmation", MESSAGES.demoFailOpenConfirmation, {
    type: "confirm",
  }),
  new ScenarioAction("failOpenExit", (state) => {
    if (!state.failOpenConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("failOpen", () => {
    const client = new SSMClient({});
    return client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: `fake-table-${Date.now()}`,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testFailOpen", MESSAGES.demoFailOpenTest),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "resetTableConfirmation",
    MESSAGES.demoResetTableConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("resetTableExit", (state) => {
    if (!state.resetTableConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("resetTable", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testResetTable", MESSAGES.demoTestResetTable),
  healthCheckLoop,
  loadBalancerLoop,
];

async function createSsmOnlyInstanceProfile() {
  const iamClient = new IAMClient({});
  const { Policy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyName: NAMES.ssmOnlyPolicyName,
      PolicyDocument: readFileSync(
        join(RESOURCES_PATH, "ssm_only_policy.json"),
      ),
    }),
  );
  await iamClient.send(
    new CreateRoleCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      AssumeRolePolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Principal: { Service: "ec2.amazonaws.com" },
            Action: "sts:AssumeRole",
          },
        ],
      }),
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: Policy.Arn,
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
    }),
  );
  const { InstanceProfile } = await iamClient.send(
    new CreateInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
    }),
  );
  await waitUntilInstanceProfileExists(
    { client: iamClient },
    { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName },
  );
  await iamClient.send(
    new AddRoleToInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
      RoleName: NAMES.ssmOnlyRoleName,
    }),
  );

  return InstanceProfile;
}
```
すべてのリソースを破棄するための手順を作成します。  

```
import { unlinkSync } from "node:fs";

import { DynamoDBClient, DeleteTableCommand } from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  DeleteKeyPairCommand,
  DeleteLaunchTemplateCommand,
  RevokeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  DeleteInstanceProfileCommand,
  RemoveRoleFromInstanceProfileCommand,
  DeletePolicyCommand,
  DeleteRoleCommand,
  DetachRolePolicyCommand,
  paginateListPolicies,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DeleteAutoScalingGroupCommand,
  TerminateInstanceInAutoScalingGroupCommand,
  UpdateAutoScalingGroupCommand,
  paginateDescribeAutoScalingGroups,
} from "@aws-sdk/client-auto-scaling";
import {
  DeleteLoadBalancerCommand,
  DeleteTargetGroupCommand,
  DescribeTargetGroupsCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { loadState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const destroySteps = [
  loadState,
  new ScenarioInput("destroy", MESSAGES.destroy, { type: "confirm" }),
  new ScenarioAction(
    "abort",
    (state) => state.destroy === false && process.exit(),
  ),
  new ScenarioAction("deleteTable", async (c) => {
    try {
      const client = new DynamoDBClient({});
      await client.send(new DeleteTableCommand({ TableName: NAMES.tableName }));
    } catch (e) {
      c.deleteTableError = e;
    }
  }),
  new ScenarioOutput("deleteTableResult", (state) => {
    if (state.deleteTableError) {
      console.error(state.deleteTableError);
      return MESSAGES.deleteTableError.replace(
        "${TABLE_NAME}",
        NAMES.tableName,
      );
    }
    return MESSAGES.deletedTable.replace("${TABLE_NAME}", NAMES.tableName);
  }),
  new ScenarioAction("deleteKeyPair", async (state) => {
    try {
      const client = new EC2Client({});
      await client.send(
        new DeleteKeyPairCommand({ KeyName: NAMES.keyPairName }),
      );
      unlinkSync(`${NAMES.keyPairName}.pem`);
    } catch (e) {
      state.deleteKeyPairError = e;
    }
  }),
  new ScenarioOutput("deleteKeyPairResult", (state) => {
    if (state.deleteKeyPairError) {
      console.error(state.deleteKeyPairError);
      return MESSAGES.deleteKeyPairError.replace(
        "${KEY_PAIR_NAME}",
        NAMES.keyPairName,
      );
    }
    return MESSAGES.deletedKeyPair.replace(
      "${KEY_PAIR_NAME}",
      NAMES.keyPairName,
    );
  }),
  new ScenarioAction("detachPolicyFromRole", async (state) => {
    try {
      const client = new IAMClient({});
      const policy = await findPolicy(NAMES.instancePolicyName);

      if (!policy) {
        state.detachPolicyFromRoleError = new Error(
          `Policy ${NAMES.instancePolicyName} not found.`,
        );
      } else {
        await client.send(
          new DetachRolePolicyCommand({
            RoleName: NAMES.instanceRoleName,
            PolicyArn: policy.Arn,
          }),
        );
      }
    } catch (e) {
      state.detachPolicyFromRoleError = e;
    }
  }),
  new ScenarioOutput("detachedPolicyFromRole", (state) => {
    if (state.detachPolicyFromRoleError) {
      console.error(state.detachPolicyFromRoleError);
      return MESSAGES.detachPolicyFromRoleError
        .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.detachedPolicyFromRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const policy = await findPolicy(NAMES.instancePolicyName);

    if (!policy) {
      state.deletePolicyError = new Error(
        `Policy ${NAMES.instancePolicyName} not found.`,
      );
    } else {
      return client.send(
        new DeletePolicyCommand({
          PolicyArn: policy.Arn,
        }),
      );
    }
  }),
  new ScenarioOutput("deletePolicyResult", (state) => {
    if (state.deletePolicyError) {
      console.error(state.deletePolicyError);
      return MESSAGES.deletePolicyError.replace(
        "${INSTANCE_POLICY_NAME}",
        NAMES.instancePolicyName,
      );
    }
    return MESSAGES.deletedPolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    );
  }),
  new ScenarioAction("removeRoleFromInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          RoleName: NAMES.instanceRoleName,
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.removeRoleFromInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("removeRoleFromInstanceProfileResult", (state) => {
    if (state.removeRoleFromInstanceProfile) {
      console.error(state.removeRoleFromInstanceProfileError);
      return MESSAGES.removeRoleFromInstanceProfileError
        .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.removedRoleFromInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstanceRole", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteRoleCommand({
          RoleName: NAMES.instanceRoleName,
        }),
      );
    } catch (e) {
      state.deleteInstanceRoleError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceRoleResult", (state) => {
    if (state.deleteInstanceRoleError) {
      console.error(state.deleteInstanceRoleError);
      return MESSAGES.deleteInstanceRoleError.replace(
        "${INSTANCE_ROLE_NAME}",
        NAMES.instanceRoleName,
      );
    }
    return MESSAGES.deletedInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    );
  }),
  new ScenarioAction("deleteInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceProfileResult", (state) => {
    if (state.deleteInstanceProfileError) {
      console.error(state.deleteInstanceProfileError);
      return MESSAGES.deleteInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.instanceProfileName,
      );
    }
    return MESSAGES.deletedInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    );
  }),
  new ScenarioAction("deleteAutoScalingGroup", async (state) => {
    try {
      await terminateGroupInstances(NAMES.autoScalingGroupName);
      await retry({ intervalInMs: 60000, maxRetries: 60 }, async () => {
        await deleteAutoScalingGroup(NAMES.autoScalingGroupName);
      });
    } catch (e) {
      state.deleteAutoScalingGroupError = e;
    }
  }),
  new ScenarioOutput("deleteAutoScalingGroupResult", (state) => {
    if (state.deleteAutoScalingGroupError) {
      console.error(state.deleteAutoScalingGroupError);
      return MESSAGES.deleteAutoScalingGroupError.replace(
        "${AUTO_SCALING_GROUP_NAME}",
        NAMES.autoScalingGroupName,
      );
    }
    return MESSAGES.deletedAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    );
  }),
  new ScenarioAction("deleteLaunchTemplate", async (state) => {
    const client = new EC2Client({});
    try {
      await client.send(
        new DeleteLaunchTemplateCommand({
          LaunchTemplateName: NAMES.launchTemplateName,
        }),
      );
    } catch (e) {
      state.deleteLaunchTemplateError = e;
    }
  }),
  new ScenarioOutput("deleteLaunchTemplateResult", (state) => {
    if (state.deleteLaunchTemplateError) {
      console.error(state.deleteLaunchTemplateError);
      return MESSAGES.deleteLaunchTemplateError.replace(
        "${LAUNCH_TEMPLATE_NAME}",
        NAMES.launchTemplateName,
      );
    }
    return MESSAGES.deletedLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    );
  }),
  new ScenarioAction("deleteLoadBalancer", async (state) => {
    try {
      const client = new ElasticLoadBalancingV2Client({});
      const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
      await client.send(
        new DeleteLoadBalancerCommand({
          LoadBalancerArn: loadBalancer.LoadBalancerArn,
        }),
      );
      await retry({ intervalInMs: 1000, maxRetries: 60 }, async () => {
        const lb = await findLoadBalancer(NAMES.loadBalancerName);
        if (lb) {
          throw new Error("Load balancer still exists.");
        }
      });
    } catch (e) {
      state.deleteLoadBalancerError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerResult", (state) => {
    if (state.deleteLoadBalancerError) {
      console.error(state.deleteLoadBalancerError);
      return MESSAGES.deleteLoadBalancerError.replace(
        "${LB_NAME}",
        NAMES.loadBalancerName,
      );
    }
    return MESSAGES.deletedLoadBalancer.replace(
      "${LB_NAME}",
      NAMES.loadBalancerName,
    );
  }),
  new ScenarioAction("deleteLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    try {
      const { TargetGroups } = await client.send(
        new DescribeTargetGroupsCommand({
          Names: [NAMES.loadBalancerTargetGroupName],
        }),
      );

      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        client.send(
          new DeleteTargetGroupCommand({
            TargetGroupArn: TargetGroups[0].TargetGroupArn,
          }),
        ),
      );
    } catch (e) {
      state.deleteLoadBalancerTargetGroupError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerTargetGroupResult", (state) => {
    if (state.deleteLoadBalancerTargetGroupError) {
      console.error(state.deleteLoadBalancerTargetGroupError);
      return MESSAGES.deleteLoadBalancerTargetGroupError.replace(
        "${TARGET_GROUP_NAME}",
        NAMES.loadBalancerTargetGroupName,
      );
    }
    return MESSAGES.deletedLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    );
  }),
  new ScenarioAction("detachSsmOnlyRoleFromProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyRoleFromProfileError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyRoleFromProfileResult", (state) => {
    if (state.detachSsmOnlyRoleFromProfileError) {
      console.error(state.detachSsmOnlyRoleFromProfileError);
      return MESSAGES.detachSsmOnlyRoleFromProfileError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
    }
    return MESSAGES.detachedSsmOnlyRoleFromProfile
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
  }),
  new ScenarioAction("detachSsmOnlyCustomRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyCustomRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyCustomRolePolicyResult", (state) => {
    if (state.detachSsmOnlyCustomRolePolicyError) {
      console.error(state.detachSsmOnlyCustomRolePolicyError);
      return MESSAGES.detachSsmOnlyCustomRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
    }
    return MESSAGES.detachedSsmOnlyCustomRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
  }),
  new ScenarioAction("detachSsmOnlyAWSRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
        }),
      );
    } catch (e) {
      state.detachSsmOnlyAWSRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyAWSRolePolicyResult", (state) => {
    if (state.detachSsmOnlyAWSRolePolicyError) {
      console.error(state.detachSsmOnlyAWSRolePolicyError);
      return MESSAGES.detachSsmOnlyAWSRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
    }
    return MESSAGES.detachedSsmOnlyAWSRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
  }),
  new ScenarioAction("deleteSsmOnlyInstanceProfile", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyInstanceProfileResult", (state) => {
    if (state.deleteSsmOnlyInstanceProfileError) {
      console.error(state.deleteSsmOnlyInstanceProfileError);
      return MESSAGES.deleteSsmOnlyInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.ssmOnlyInstanceProfileName,
      );
    }
    return MESSAGES.deletedSsmOnlyInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.ssmOnlyInstanceProfileName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyPolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DeletePolicyCommand({
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyPolicyError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyPolicyResult", (state) => {
    if (state.deleteSsmOnlyPolicyError) {
      console.error(state.deleteSsmOnlyPolicyError);
      return MESSAGES.deleteSsmOnlyPolicyError.replace(
        "${POLICY_NAME}",
        NAMES.ssmOnlyPolicyName,
      );
    }
    return MESSAGES.deletedSsmOnlyPolicy.replace(
      "${POLICY_NAME}",
      NAMES.ssmOnlyPolicyName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyRole", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteRoleCommand({
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyRoleError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyRoleResult", (state) => {
    if (state.deleteSsmOnlyRoleError) {
      console.error(state.deleteSsmOnlyRoleError);
      return MESSAGES.deleteSsmOnlyRoleError.replace(
        "${ROLE_NAME}",
        NAMES.ssmOnlyRoleName,
      );
    }
    return MESSAGES.deletedSsmOnlyRole.replace(
      "${ROLE_NAME}",
      NAMES.ssmOnlyRoleName,
    );
  }),
  new ScenarioAction(
    "revokeSecurityGroupIngress",
    async (
      /** @type {{ myIp: string, defaultSecurityGroup: { GroupId: string } }} */ state,
    ) => {
      const ec2Client = new EC2Client({});

      try {
        await ec2Client.send(
          new RevokeSecurityGroupIngressCommand({
            GroupId: state.defaultSecurityGroup.GroupId,
            CidrIp: `${state.myIp}/32`,
            FromPort: 80,
            ToPort: 80,
            IpProtocol: "tcp",
          }),
        );
      } catch (e) {
        state.revokeSecurityGroupIngressError = e;
      }
    },
  ),
  new ScenarioOutput("revokeSecurityGroupIngressResult", (state) => {
    if (state.revokeSecurityGroupIngressError) {
      console.error(state.revokeSecurityGroupIngressError);
      return MESSAGES.revokeSecurityGroupIngressError.replace(
        "${IP}",
        state.myIp,
      );
    }
    return MESSAGES.revokedSecurityGroupIngress.replace("${IP}", state.myIp);
  }),
];

/**
 * @param {string} policyName
 */
async function findPolicy(policyName) {
  const client = new IAMClient({});
  const paginatedPolicies = paginateListPolicies({ client }, {});
  for await (const page of paginatedPolicies) {
    const policy = page.Policies.find((p) => p.PolicyName === policyName);
    if (policy) {
      return policy;
    }
  }
}

/**
 * @param {string} groupName
 */
async function deleteAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  try {
    await client.send(
      new DeleteAutoScalingGroupCommand({
        AutoScalingGroupName: groupName,
      }),
    );
  } catch (err) {
    if (!(err instanceof Error)) {
      throw err;
    }
    console.log(err.name);
    throw err;
  }
}

/**
 * @param {string} groupName
 */
async function terminateGroupInstances(groupName) {
  const autoScalingClient = new AutoScalingClient({});
  const group = await findAutoScalingGroup(groupName);
  await autoScalingClient.send(
    new UpdateAutoScalingGroupCommand({
      AutoScalingGroupName: group.AutoScalingGroupName,
      MinSize: 0,
    }),
  );
  for (const i of group.Instances) {
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: i.InstanceId,
          ShouldDecrementDesiredCapacity: true,
        }),
      ),
    );
  }
}

async function findAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  const paginatedGroups = paginateDescribeAutoScalingGroups({ client }, {});
  for await (const page of paginatedGroups) {
    const group = page.AutoScalingGroups.find(
      (g) => g.AutoScalingGroupName === groupName,
    );
    if (group) {
      return group;
    }
  }
  throw new Error(`Auto scaling group ${groupName} not found.`);
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/AttachLoadBalancerTargetGroupsCommand)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/CreateAutoScalingGroupCommand)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateInstanceProfileCommand)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateLaunchTemplateCommand)
  + [CreateListener](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateListenerCommand)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateLoadBalancerCommand)
  + [CreateTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateTargetGroupCommand)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DeleteAutoScalingGroupCommand)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteInstanceProfileCommand)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteLaunchTemplateCommand)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteLoadBalancerCommand)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteTargetGroupCommand)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DescribeAutoScalingGroupsCommand)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeAvailabilityZonesCommand)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeIamInstanceProfileAssociationsCommand)
  + [DescribeInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstancesCommand)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeLoadBalancersCommand)
  + [DescribeSubnets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSubnetsCommand)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetGroupsCommand)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetHealthCommand)
  + [DescribeVpcs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeVpcsCommand)
  + [RebootInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RebootInstancesCommand)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReplaceIamInstanceProfileAssociationCommand)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/TerminateInstanceInAutoScalingGroupCommand)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/UpdateAutoScalingGroupCommand)

# SDK for JavaScript (v3) を使用した Elastic Load Balancing - バージョン 2 の例
<a name="javascript_3_elastic-load-balancing-v2_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 2 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Elastic Load Balancing
<a name="elastic-load-balancing-v2_Hello_javascript_3_topic"></a>

次のコード例は、Elastic Load Balancing の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/elastic-load-balancing-v2#code-examples)での設定と実行の方法を確認してください。

```
import {
  ElasticLoadBalancingV2Client,
  DescribeLoadBalancersCommand,
} from "@aws-sdk/client-elastic-load-balancing-v2";

export async function main() {
  const client = new ElasticLoadBalancingV2Client({});
  const { LoadBalancers } = await client.send(
    new DescribeLoadBalancersCommand({}),
  );
  const loadBalancersList = LoadBalancers.map(
    (lb) => `• ${lb.LoadBalancerName}: ${lb.DNSName}`,
  ).join("\n");
  console.log(
    "Hello, Elastic Load Balancing! Let's list some of your load balancers:\n",
    loadBalancersList,
  );
}

// Call function if run directly
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeLoadBalancers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeLoadBalancersCommand)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateListener`
<a name="elastic-load-balancing-v2_CreateListener_javascript_3_topic"></a>

次のコード例は、`CreateListener` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const client = new ElasticLoadBalancingV2Client({});
    const { Listeners } = await client.send(
      new CreateListenerCommand({
        LoadBalancerArn: state.loadBalancerArn,
        Protocol: state.targetGroupProtocol,
        Port: state.targetGroupPort,
        DefaultActions: [
          { Type: "forward", TargetGroupArn: state.targetGroupArn },
        ],
      }),
    );
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateListener](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateListenerCommand)」を参照してください。

### `CreateLoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_javascript_3_topic"></a>

次のコード例は、`CreateLoadBalancer` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const client = new ElasticLoadBalancingV2Client({});
    const { LoadBalancers } = await client.send(
      new CreateLoadBalancerCommand({
        Name: NAMES.loadBalancerName,
        Subnets: state.subnets,
      }),
    );
    state.loadBalancerDns = LoadBalancers[0].DNSName;
    state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn;
    await waitUntilLoadBalancerAvailable(
      { client },
      { Names: [NAMES.loadBalancerName] },
    );
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateLoadBalancerCommand)」を参照してください。

### `CreateTargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_javascript_3_topic"></a>

次のコード例は、`CreateTargetGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const client = new ElasticLoadBalancingV2Client({});
    const { TargetGroups } = await client.send(
      new CreateTargetGroupCommand({
        Name: NAMES.loadBalancerTargetGroupName,
        Protocol: "HTTP",
        Port: 80,
        HealthCheckPath: "/healthcheck",
        HealthCheckIntervalSeconds: 10,
        HealthCheckTimeoutSeconds: 5,
        HealthyThresholdCount: 2,
        UnhealthyThresholdCount: 2,
        VpcId: state.defaultVpc,
      }),
    );
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateTargetGroupCommand)」を参照してください。

### `DeleteLoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_javascript_3_topic"></a>

次のコード例は、`DeleteLoadBalancer` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
      const client = new ElasticLoadBalancingV2Client({});
      const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
      await client.send(
        new DeleteLoadBalancerCommand({
          LoadBalancerArn: loadBalancer.LoadBalancerArn,
        }),
      );
      await retry({ intervalInMs: 1000, maxRetries: 60 }, async () => {
        const lb = await findLoadBalancer(NAMES.loadBalancerName);
        if (lb) {
          throw new Error("Load balancer still exists.");
        }
      });
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteLoadBalancerCommand)」を参照してください。

### `DeleteTargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_javascript_3_topic"></a>

次のコード例は、`DeleteTargetGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
    const client = new ElasticLoadBalancingV2Client({});
    try {
      const { TargetGroups } = await client.send(
        new DescribeTargetGroupsCommand({
          Names: [NAMES.loadBalancerTargetGroupName],
        }),
      );

      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        client.send(
          new DeleteTargetGroupCommand({
            TargetGroupArn: TargetGroups[0].TargetGroupArn,
          }),
        ),
      );
    } catch (e) {
      state.deleteLoadBalancerTargetGroupError = e;
    }
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteTargetGroupCommand)」を参照してください。

### `DescribeLoadBalancers`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_javascript_3_topic"></a>

次のコード例は、`DescribeLoadBalancers` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/elastic-load-balancing-v2#code-examples)での設定と実行の方法を確認してください。

```
import {
  ElasticLoadBalancingV2Client,
  DescribeLoadBalancersCommand,
} from "@aws-sdk/client-elastic-load-balancing-v2";

export async function main() {
  const client = new ElasticLoadBalancingV2Client({});
  const { LoadBalancers } = await client.send(
    new DescribeLoadBalancersCommand({}),
  );
  const loadBalancersList = LoadBalancers.map(
    (lb) => `• ${lb.LoadBalancerName}: ${lb.DNSName}`,
  ).join("\n");
  console.log(
    "Hello, Elastic Load Balancing! Let's list some of your load balancers:\n",
    loadBalancersList,
  );
}

// Call function if run directly
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeLoadBalancers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeLoadBalancersCommand)」を参照してください。

### `DescribeTargetGroups`
<a name="elastic-load-balancing-v2_DescribeTargetGroups_javascript_3_topic"></a>

次のコード例は、`DescribeTargetGroups` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/elastic-load-balancing-v2#code-examples)での設定と実行の方法を確認してください。

```
  const client = new ElasticLoadBalancingV2Client({});
  const { TargetGroups } = await client.send(
    new DescribeTargetGroupsCommand({
      Names: [NAMES.loadBalancerTargetGroupName],
    }),
  );
```
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[DescribeTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetGroupsCommand)」を参照してください。

### `DescribeTargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_javascript_3_topic"></a>

次のコード例は、`DescribeTargetHealth` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
  const { TargetHealthDescriptions } = await client.send(
    new DescribeTargetHealthCommand({
      TargetGroupArn: TargetGroups[0].TargetGroupArn,
    }),
  );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeTargetHealth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetHealthCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_javascript_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
#!/usr/bin/env node
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import {
  Scenario,
  parseScenarioArgs,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

/**
 * The workflow steps are split into three stages:
 *   - deploy
 *   - demo
 *   - destroy
 *
 * Each of these stages has a corresponding file prefixed with steps-*.
 */
import { deploySteps } from "./steps-deploy.js";
import { demoSteps } from "./steps-demo.js";
import { destroySteps } from "./steps-destroy.js";

/**
 * The context is passed to every scenario. Scenario steps
 * will modify the context.
 */
const context = {};

/**
 * Three Scenarios are created for the workflow. A Scenario is an orchestration class
 * that simplifies running a series of steps.
 */
export const scenarios = {
  // Deploys all resources necessary for the workflow.
  deploy: new Scenario("Resilient Workflow - Deploy", deploySteps, context),
  // Demonstrates how a fragile web service can be made more resilient.
  demo: new Scenario("Resilient Workflow - Demo", demoSteps, context),
  // Destroys the resources created for the workflow.
  destroy: new Scenario("Resilient Workflow - Destroy", destroySteps, context),
};

// Call function if run directly
import { fileURLToPath } from "node:url";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  parseScenarioArgs(scenarios, {
    name: "Resilient Workflow",
    synopsis:
      "node index.js --scenario <deploy | demo | destroy> [-h|--help] [-y|--yes] [-v|--verbose]",
    description: "Deploy and interact with scalable EC2 instances.",
  });
}
```
すべてのリソースをデプロイするための手順を作成します。  

```
import { join } from "node:path";
import { readFileSync, writeFileSync } from "node:fs";
import axios from "axios";

import {
  BatchWriteItemCommand,
  CreateTableCommand,
  DynamoDBClient,
  waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  CreateKeyPairCommand,
  CreateLaunchTemplateCommand,
  DescribeAvailabilityZonesCommand,
  DescribeVpcsCommand,
  DescribeSubnetsCommand,
  DescribeSecurityGroupsCommand,
  AuthorizeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  AttachRolePolicyCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";
import {
  CreateAutoScalingGroupCommand,
  AutoScalingClient,
  AttachLoadBalancerTargetGroupsCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  CreateListenerCommand,
  CreateLoadBalancerCommand,
  CreateTargetGroupCommand,
  ElasticLoadBalancingV2Client,
  waitUntilLoadBalancerAvailable,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { saveState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH, ROOT } from "./constants.js";
import { initParamsSteps } from "./steps-reset-params.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const deploySteps = [
  new ScenarioOutput("introduction", MESSAGES.introduction, { header: true }),
  new ScenarioInput("confirmDeployment", MESSAGES.confirmDeployment, {
    type: "confirm",
  }),
  new ScenarioAction(
    "handleConfirmDeployment",
    (c) => c.confirmDeployment === false && process.exit(),
  ),
  new ScenarioOutput(
    "creatingTable",
    MESSAGES.creatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("createTable", async () => {
    const client = new DynamoDBClient({});
    await client.send(
      new CreateTableCommand({
        TableName: NAMES.tableName,
        ProvisionedThroughput: {
          ReadCapacityUnits: 5,
          WriteCapacityUnits: 5,
        },
        AttributeDefinitions: [
          {
            AttributeName: "MediaType",
            AttributeType: "S",
          },
          {
            AttributeName: "ItemId",
            AttributeType: "N",
          },
        ],
        KeySchema: [
          {
            AttributeName: "MediaType",
            KeyType: "HASH",
          },
          {
            AttributeName: "ItemId",
            KeyType: "RANGE",
          },
        ],
      }),
    );
    await waitUntilTableExists({ client }, { TableName: NAMES.tableName });
  }),
  new ScenarioOutput(
    "createdTable",
    MESSAGES.createdTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "populatingTable",
    MESSAGES.populatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("populateTable", () => {
    const client = new DynamoDBClient({});
    /**
     * @type {{ default: import("@aws-sdk/client-dynamodb").PutRequest['Item'][] }}
     */
    const recommendations = JSON.parse(
      readFileSync(join(RESOURCES_PATH, "recommendations.json")),
    );

    return client.send(
      new BatchWriteItemCommand({
        RequestItems: {
          [NAMES.tableName]: recommendations.map((item) => ({
            PutRequest: { Item: item },
          })),
        },
      }),
    );
  }),
  new ScenarioOutput(
    "populatedTable",
    MESSAGES.populatedTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "creatingKeyPair",
    MESSAGES.creatingKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioAction("createKeyPair", async () => {
    const client = new EC2Client({});
    const { KeyMaterial } = await client.send(
      new CreateKeyPairCommand({
        KeyName: NAMES.keyPairName,
      }),
    );

    writeFileSync(`${NAMES.keyPairName}.pem`, KeyMaterial, { mode: 0o600 });
  }),
  new ScenarioOutput(
    "createdKeyPair",
    MESSAGES.createdKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioOutput(
    "creatingInstancePolicy",
    MESSAGES.creatingInstancePolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    ),
  ),
  new ScenarioAction("createInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const {
      Policy: { Arn },
    } = await client.send(
      new CreatePolicyCommand({
        PolicyName: NAMES.instancePolicyName,
        PolicyDocument: readFileSync(
          join(RESOURCES_PATH, "instance_policy.json"),
        ),
      }),
    );
    state.instancePolicyArn = Arn;
  }),
  new ScenarioOutput("createdInstancePolicy", (state) =>
    MESSAGES.createdInstancePolicy
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_POLICY_ARN}", state.instancePolicyArn),
  ),
  new ScenarioOutput(
    "creatingInstanceRole",
    MESSAGES.creatingInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioAction("createInstanceRole", () => {
    const client = new IAMClient({});
    return client.send(
      new CreateRoleCommand({
        RoleName: NAMES.instanceRoleName,
        AssumeRolePolicyDocument: readFileSync(
          join(ROOT, "assume-role-policy.json"),
        ),
      }),
    );
  }),
  new ScenarioOutput(
    "createdInstanceRole",
    MESSAGES.createdInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioOutput(
    "attachingPolicyToRole",
    MESSAGES.attachingPolicyToRole
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName)
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName),
  ),
  new ScenarioAction("attachPolicyToRole", async (state) => {
    const client = new IAMClient({});
    await client.send(
      new AttachRolePolicyCommand({
        RoleName: NAMES.instanceRoleName,
        PolicyArn: state.instancePolicyArn,
      }),
    );
  }),
  new ScenarioOutput(
    "attachedPolicyToRole",
    MESSAGES.attachedPolicyToRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioOutput(
    "creatingInstanceProfile",
    MESSAGES.creatingInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    ),
  ),
  new ScenarioAction("createInstanceProfile", async (state) => {
    const client = new IAMClient({});
    const {
      InstanceProfile: { Arn },
    } = await client.send(
      new CreateInstanceProfileCommand({
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
    state.instanceProfileArn = Arn;

    await waitUntilInstanceProfileExists(
      { client },
      { InstanceProfileName: NAMES.instanceProfileName },
    );
  }),
  new ScenarioOutput("createdInstanceProfile", (state) =>
    MESSAGES.createdInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_PROFILE_ARN}", state.instanceProfileArn),
  ),
  new ScenarioOutput(
    "addingRoleToInstanceProfile",
    MESSAGES.addingRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioAction("addRoleToInstanceProfile", () => {
    const client = new IAMClient({});
    return client.send(
      new AddRoleToInstanceProfileCommand({
        RoleName: NAMES.instanceRoleName,
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
  }),
  new ScenarioOutput(
    "addedRoleToInstanceProfile",
    MESSAGES.addedRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  ...initParamsSteps,
  new ScenarioOutput("creatingLaunchTemplate", MESSAGES.creatingLaunchTemplate),
  new ScenarioAction("createLaunchTemplate", async () => {
    const ssmClient = new SSMClient({});
    const { Parameter } = await ssmClient.send(
      new GetParameterCommand({
        Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
      }),
    );
    const ec2Client = new EC2Client({});
    await ec2Client.send(
      new CreateLaunchTemplateCommand({
        LaunchTemplateName: NAMES.launchTemplateName,
        LaunchTemplateData: {
          InstanceType: "t3.micro",
          ImageId: Parameter.Value,
          IamInstanceProfile: { Name: NAMES.instanceProfileName },
          UserData: readFileSync(
            join(RESOURCES_PATH, "server_startup_script.sh"),
          ).toString("base64"),
          KeyName: NAMES.keyPairName,
        },
      }),
    );
  }),
  new ScenarioOutput(
    "createdLaunchTemplate",
    MESSAGES.createdLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    ),
  ),
  new ScenarioOutput(
    "creatingAutoScalingGroup",
    MESSAGES.creatingAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    ),
  ),
  new ScenarioAction("createAutoScalingGroup", async (state) => {
    const ec2Client = new EC2Client({});
    const { AvailabilityZones } = await ec2Client.send(
      new DescribeAvailabilityZonesCommand({}),
    );
    state.availabilityZoneNames = AvailabilityZones.map((az) => az.ZoneName);
    const autoScalingClient = new AutoScalingClient({});
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new CreateAutoScalingGroupCommand({
          AvailabilityZones: state.availabilityZoneNames,
          AutoScalingGroupName: NAMES.autoScalingGroupName,
          LaunchTemplate: {
            LaunchTemplateName: NAMES.launchTemplateName,
            Version: "$Default",
          },
          MinSize: 3,
          MaxSize: 3,
        }),
      ),
    );
  }),
  new ScenarioOutput(
    "createdAutoScalingGroup",
    /**
     * @param {{ availabilityZoneNames: string[] }} state
     */
    (state) =>
      MESSAGES.createdAutoScalingGroup
        .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName)
        .replace(
          "${AVAILABILITY_ZONE_NAMES}",
          state.availabilityZoneNames.join(", "),
        ),
  ),
  new ScenarioInput("confirmContinue", MESSAGES.confirmContinue, {
    type: "confirm",
  }),
  new ScenarioOutput("loadBalancer", MESSAGES.loadBalancer),
  new ScenarioOutput("gettingVpc", MESSAGES.gettingVpc),
  new ScenarioAction("getVpc", async (state) => {
    const client = new EC2Client({});
    const { Vpcs } = await client.send(
      new DescribeVpcsCommand({
        Filters: [{ Name: "is-default", Values: ["true"] }],
      }),
    );
    state.defaultVpc = Vpcs[0].VpcId;
  }),
  new ScenarioOutput("gotVpc", (state) =>
    MESSAGES.gotVpc.replace("${VPC_ID}", state.defaultVpc),
  ),
  new ScenarioOutput("gettingSubnets", MESSAGES.gettingSubnets),
  new ScenarioAction("getSubnets", async (state) => {
    const client = new EC2Client({});
    const { Subnets } = await client.send(
      new DescribeSubnetsCommand({
        Filters: [
          { Name: "vpc-id", Values: [state.defaultVpc] },
          { Name: "availability-zone", Values: state.availabilityZoneNames },
          { Name: "default-for-az", Values: ["true"] },
        ],
      }),
    );
    state.subnets = Subnets.map((subnet) => subnet.SubnetId);
  }),
  new ScenarioOutput(
    "gotSubnets",
    /**
     * @param {{ subnets: string[] }} state
     */
    (state) =>
      MESSAGES.gotSubnets.replace("${SUBNETS}", state.subnets.join(", ")),
  ),
  new ScenarioOutput(
    "creatingLoadBalancerTargetGroup",
    MESSAGES.creatingLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioAction("createLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { TargetGroups } = await client.send(
      new CreateTargetGroupCommand({
        Name: NAMES.loadBalancerTargetGroupName,
        Protocol: "HTTP",
        Port: 80,
        HealthCheckPath: "/healthcheck",
        HealthCheckIntervalSeconds: 10,
        HealthCheckTimeoutSeconds: 5,
        HealthyThresholdCount: 2,
        UnhealthyThresholdCount: 2,
        VpcId: state.defaultVpc,
      }),
    );
    const targetGroup = TargetGroups[0];
    state.targetGroupArn = targetGroup.TargetGroupArn;
    state.targetGroupProtocol = targetGroup.Protocol;
    state.targetGroupPort = targetGroup.Port;
  }),
  new ScenarioOutput(
    "createdLoadBalancerTargetGroup",
    MESSAGES.createdLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioOutput(
    "creatingLoadBalancer",
    MESSAGES.creatingLoadBalancer.replace("${LB_NAME}", NAMES.loadBalancerName),
  ),
  new ScenarioAction("createLoadBalancer", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { LoadBalancers } = await client.send(
      new CreateLoadBalancerCommand({
        Name: NAMES.loadBalancerName,
        Subnets: state.subnets,
      }),
    );
    state.loadBalancerDns = LoadBalancers[0].DNSName;
    state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn;
    await waitUntilLoadBalancerAvailable(
      { client },
      { Names: [NAMES.loadBalancerName] },
    );
  }),
  new ScenarioOutput("createdLoadBalancer", (state) =>
    MESSAGES.createdLoadBalancer
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioOutput(
    "creatingListener",
    MESSAGES.creatingLoadBalancerListener
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName),
  ),
  new ScenarioAction("createListener", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { Listeners } = await client.send(
      new CreateListenerCommand({
        LoadBalancerArn: state.loadBalancerArn,
        Protocol: state.targetGroupProtocol,
        Port: state.targetGroupPort,
        DefaultActions: [
          { Type: "forward", TargetGroupArn: state.targetGroupArn },
        ],
      }),
    );
    const listener = Listeners[0];
    state.loadBalancerListenerArn = listener.ListenerArn;
  }),
  new ScenarioOutput("createdListener", (state) =>
    MESSAGES.createdLoadBalancerListener.replace(
      "${LB_LISTENER_ARN}",
      state.loadBalancerListenerArn,
    ),
  ),
  new ScenarioOutput(
    "attachingLoadBalancerTargetGroup",
    MESSAGES.attachingLoadBalancerTargetGroup
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName)
      .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName),
  ),
  new ScenarioAction("attachLoadBalancerTargetGroup", async (state) => {
    const client = new AutoScalingClient({});
    await client.send(
      new AttachLoadBalancerTargetGroupsCommand({
        AutoScalingGroupName: NAMES.autoScalingGroupName,
        TargetGroupARNs: [state.targetGroupArn],
      }),
    );
  }),
  new ScenarioOutput(
    "attachedLoadBalancerTargetGroup",
    MESSAGES.attachedLoadBalancerTargetGroup,
  ),
  new ScenarioOutput("verifyingInboundPort", MESSAGES.verifyingInboundPort),
  new ScenarioAction(
    "verifyInboundPort",
    /**
     *
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup}} state
     */
    async (state) => {
      const client = new EC2Client({});
      const { SecurityGroups } = await client.send(
        new DescribeSecurityGroupsCommand({
          Filters: [{ Name: "group-name", Values: ["default"] }],
        }),
      );
      if (!SecurityGroups) {
        state.verifyInboundPortError = new Error(MESSAGES.noSecurityGroups);
      }
      state.defaultSecurityGroup = SecurityGroups[0];

      /**
       * @type {string}
       */
      const ipResponse = (await axios.get("http://checkip.amazonaws.com")).data;
      state.myIp = ipResponse.trim();
      const myIpRules = state.defaultSecurityGroup.IpPermissions.filter(
        ({ IpRanges }) =>
          IpRanges.some(
            ({ CidrIp }) =>
              CidrIp.startsWith(state.myIp) || CidrIp === "0.0.0.0/0",
          ),
      )
        .filter(({ IpProtocol }) => IpProtocol === "tcp")
        .filter(({ FromPort }) => FromPort === 80);

      state.myIpRules = myIpRules;
    },
  ),
  new ScenarioOutput(
    "verifiedInboundPort",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return MESSAGES.foundIpRules.replace(
          "${IP_RULES}",
          JSON.stringify(state.myIpRules, null, 2),
        );
      }
      return MESSAGES.noIpRules;
    },
  ),
  new ScenarioInput(
    "shouldAddInboundRule",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return false;
      }
      return MESSAGES.noIpRules;
    },
    { type: "confirm" },
  ),
  new ScenarioAction(
    "addInboundRule",
    /**
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup }} state
     */
    async (state) => {
      if (!state.shouldAddInboundRule) {
        return;
      }

      const client = new EC2Client({});
      await client.send(
        new AuthorizeSecurityGroupIngressCommand({
          GroupId: state.defaultSecurityGroup.GroupId,
          CidrIp: `${state.myIp}/32`,
          FromPort: 80,
          ToPort: 80,
          IpProtocol: "tcp",
        }),
      );
    },
  ),
  new ScenarioOutput("addedInboundRule", (state) => {
    if (state.shouldAddInboundRule) {
      return MESSAGES.addedInboundRule.replace("${IP_ADDRESS}", state.myIp);
    }
    return false;
  }),
  new ScenarioOutput("verifyingEndpoint", (state) =>
    MESSAGES.verifyingEndpoint.replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioAction("verifyEndpoint", async (state) => {
    try {
      const response = await retry({ intervalInMs: 2000, maxRetries: 30 }, () =>
        axios.get(`http://${state.loadBalancerDns}`),
      );
      state.endpointResponse = JSON.stringify(response.data, null, 2);
    } catch (e) {
      state.verifyEndpointError = e;
    }
  }),
  new ScenarioOutput("verifiedEndpoint", (state) => {
    if (state.verifyEndpointError) {
      console.error(state.verifyEndpointError);
    } else {
      return MESSAGES.verifiedEndpoint.replace(
        "${ENDPOINT_RESPONSE}",
        state.endpointResponse,
      );
    }
  }),
  saveState,
];
```
デモを実行するための手順を作成します。  

```
import { readFileSync } from "node:fs";
import { join } from "node:path";

import axios from "axios";

import {
  DescribeTargetGroupsCommand,
  DescribeTargetHealthCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";
import {
  DescribeInstanceInformationCommand,
  PutParameterCommand,
  SSMClient,
  SendCommandCommand,
} from "@aws-sdk/client-ssm";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DescribeAutoScalingGroupsCommand,
  TerminateInstanceInAutoScalingGroupCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  DescribeIamInstanceProfileAssociationsCommand,
  EC2Client,
  RebootInstancesCommand,
  ReplaceIamInstanceProfileAssociationCommand,
} from "@aws-sdk/client-ec2";

import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

const getRecommendation = new ScenarioAction(
  "getRecommendation",
  async (state) => {
    const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
    if (loadBalancer) {
      state.loadBalancerDnsName = loadBalancer.DNSName;
      try {
        state.recommendation = (
          await axios.get(`http://${state.loadBalancerDnsName}`)
        ).data;
      } catch (e) {
        state.recommendation = e instanceof Error ? e.message : e;
      }
    } else {
      throw new Error(MESSAGES.demoFindLoadBalancerError);
    }
  },
);

const getRecommendationResult = new ScenarioOutput(
  "getRecommendationResult",
  (state) =>
    `Recommendation:\n${JSON.stringify(state.recommendation, null, 2)}`,
  { preformatted: true },
);

const getHealthCheck = new ScenarioAction("getHealthCheck", async (state) => {
  const client = new ElasticLoadBalancingV2Client({});
  const { TargetGroups } = await client.send(
    new DescribeTargetGroupsCommand({
      Names: [NAMES.loadBalancerTargetGroupName],
    }),
  );

  const { TargetHealthDescriptions } = await client.send(
    new DescribeTargetHealthCommand({
      TargetGroupArn: TargetGroups[0].TargetGroupArn,
    }),
  );
  state.targetHealthDescriptions = TargetHealthDescriptions;
});

const getHealthCheckResult = new ScenarioOutput(
  "getHealthCheckResult",
  /**
   * @param {{ targetHealthDescriptions: import('@aws-sdk/client-elastic-load-balancing-v2').TargetHealthDescription[]}} state
   */
  (state) => {
    const status = state.targetHealthDescriptions
      .map((th) => `${th.Target.Id}: ${th.TargetHealth.State}`)
      .join("\n");
    return `Health check:\n${status}`;
  },
  { preformatted: true },
);

const loadBalancerLoop = new ScenarioAction(
  "loadBalancerLoop",
  getRecommendation.action,
  {
    whileConfig: {
      whileFn: ({ loadBalancerCheck }) => loadBalancerCheck,
      input: new ScenarioInput(
        "loadBalancerCheck",
        MESSAGES.demoLoadBalancerCheck,
        {
          type: "confirm",
        },
      ),
      output: getRecommendationResult,
    },
  },
);

const healthCheckLoop = new ScenarioAction(
  "healthCheckLoop",
  getHealthCheck.action,
  {
    whileConfig: {
      whileFn: ({ healthCheck }) => healthCheck,
      input: new ScenarioInput("healthCheck", MESSAGES.demoHealthCheck, {
        type: "confirm",
      }),
      output: getHealthCheckResult,
    },
  },
);

const statusSteps = [
  getRecommendation,
  getRecommendationResult,
  getHealthCheck,
  getHealthCheckResult,
];

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const demoSteps = [
  new ScenarioOutput("header", MESSAGES.demoHeader, { header: true }),
  new ScenarioOutput("sanityCheck", MESSAGES.demoSanityCheck),
  ...statusSteps,
  new ScenarioInput(
    "brokenDependencyConfirmation",
    MESSAGES.demoBrokenDependencyConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("brokenDependency", async (state) => {
    if (!state.brokenDependencyConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      state.badTableName = `fake-table-${Date.now()}`;
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmTableNameKey,
          Value: state.badTableName,
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testBrokenDependency", (state) =>
    MESSAGES.demoTestBrokenDependency.replace(
      "${TABLE_NAME}",
      state.badTableName,
    ),
  ),
  ...statusSteps,
  new ScenarioInput(
    "staticResponseConfirmation",
    MESSAGES.demoStaticResponseConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("staticResponse", async (state) => {
    if (!state.staticResponseConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmFailureResponseKey,
          Value: "static",
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testStaticResponse", MESSAGES.demoTestStaticResponse),
  ...statusSteps,
  new ScenarioInput(
    "badCredentialsConfirmation",
    MESSAGES.demoBadCredentialsConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("badCredentialsExit", (state) => {
    if (!state.badCredentialsConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("fixDynamoDBName", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioAction(
    "badCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-auto-scaling').Instance }} state
     */
    async (state) => {
      await createSsmOnlyInstanceProfile();
      const autoScalingClient = new AutoScalingClient({});
      const { AutoScalingGroups } = await autoScalingClient.send(
        new DescribeAutoScalingGroupsCommand({
          AutoScalingGroupNames: [NAMES.autoScalingGroupName],
        }),
      );
      state.targetInstance = AutoScalingGroups[0].Instances[0];
      const ec2Client = new EC2Client({});
      const { IamInstanceProfileAssociations } = await ec2Client.send(
        new DescribeIamInstanceProfileAssociationsCommand({
          Filters: [
            { Name: "instance-id", Values: [state.targetInstance.InstanceId] },
          ],
        }),
      );
      state.instanceProfileAssociationId =
        IamInstanceProfileAssociations[0].AssociationId;
      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        ec2Client.send(
          new ReplaceIamInstanceProfileAssociationCommand({
            AssociationId: state.instanceProfileAssociationId,
            IamInstanceProfile: { Name: NAMES.ssmOnlyInstanceProfileName },
          }),
        ),
      );

      await ec2Client.send(
        new RebootInstancesCommand({
          InstanceIds: [state.targetInstance.InstanceId],
        }),
      );

      const ssmClient = new SSMClient({});
      await retry({ intervalInMs: 20000, maxRetries: 15 }, async () => {
        const { InstanceInformationList } = await ssmClient.send(
          new DescribeInstanceInformationCommand({}),
        );

        const instance = InstanceInformationList.find(
          (info) => info.InstanceId === state.targetInstance.InstanceId,
        );

        if (!instance) {
          throw new Error("Instance not found.");
        }
      });

      await ssmClient.send(
        new SendCommandCommand({
          InstanceIds: [state.targetInstance.InstanceId],
          DocumentName: "AWS-RunShellScript",
          Parameters: { commands: ["cd / && sudo python3 server.py 80"] },
        }),
      );
    },
  ),
  new ScenarioOutput(
    "testBadCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation}} state
     */
    (state) =>
      MESSAGES.demoTestBadCredentials.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
  ),
  loadBalancerLoop,
  new ScenarioInput(
    "deepHealthCheckConfirmation",
    MESSAGES.demoDeepHealthCheckConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("deepHealthCheckExit", (state) => {
    if (!state.deepHealthCheckConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("deepHealthCheck", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmHealthCheckKey,
        Value: "deep",
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testDeepHealthCheck", MESSAGES.demoTestDeepHealthCheck),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "killInstanceConfirmation",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    (state) =>
      MESSAGES.demoKillInstanceConfirmation.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
    { type: "confirm" },
  ),
  new ScenarioAction("killInstanceExit", (state) => {
    if (!state.killInstanceConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction(
    "killInstance",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    async (state) => {
      const client = new AutoScalingClient({});
      await client.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: state.targetInstance.InstanceId,
          ShouldDecrementDesiredCapacity: false,
        }),
      );
    },
  ),
  new ScenarioOutput("testKillInstance", MESSAGES.demoTestKillInstance),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput("failOpenConfirmation", MESSAGES.demoFailOpenConfirmation, {
    type: "confirm",
  }),
  new ScenarioAction("failOpenExit", (state) => {
    if (!state.failOpenConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("failOpen", () => {
    const client = new SSMClient({});
    return client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: `fake-table-${Date.now()}`,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testFailOpen", MESSAGES.demoFailOpenTest),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "resetTableConfirmation",
    MESSAGES.demoResetTableConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("resetTableExit", (state) => {
    if (!state.resetTableConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("resetTable", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testResetTable", MESSAGES.demoTestResetTable),
  healthCheckLoop,
  loadBalancerLoop,
];

async function createSsmOnlyInstanceProfile() {
  const iamClient = new IAMClient({});
  const { Policy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyName: NAMES.ssmOnlyPolicyName,
      PolicyDocument: readFileSync(
        join(RESOURCES_PATH, "ssm_only_policy.json"),
      ),
    }),
  );
  await iamClient.send(
    new CreateRoleCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      AssumeRolePolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Principal: { Service: "ec2.amazonaws.com" },
            Action: "sts:AssumeRole",
          },
        ],
      }),
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: Policy.Arn,
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
    }),
  );
  const { InstanceProfile } = await iamClient.send(
    new CreateInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
    }),
  );
  await waitUntilInstanceProfileExists(
    { client: iamClient },
    { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName },
  );
  await iamClient.send(
    new AddRoleToInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
      RoleName: NAMES.ssmOnlyRoleName,
    }),
  );

  return InstanceProfile;
}
```
すべてのリソースを破棄するための手順を作成します。  

```
import { unlinkSync } from "node:fs";

import { DynamoDBClient, DeleteTableCommand } from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  DeleteKeyPairCommand,
  DeleteLaunchTemplateCommand,
  RevokeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  DeleteInstanceProfileCommand,
  RemoveRoleFromInstanceProfileCommand,
  DeletePolicyCommand,
  DeleteRoleCommand,
  DetachRolePolicyCommand,
  paginateListPolicies,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DeleteAutoScalingGroupCommand,
  TerminateInstanceInAutoScalingGroupCommand,
  UpdateAutoScalingGroupCommand,
  paginateDescribeAutoScalingGroups,
} from "@aws-sdk/client-auto-scaling";
import {
  DeleteLoadBalancerCommand,
  DeleteTargetGroupCommand,
  DescribeTargetGroupsCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { loadState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const destroySteps = [
  loadState,
  new ScenarioInput("destroy", MESSAGES.destroy, { type: "confirm" }),
  new ScenarioAction(
    "abort",
    (state) => state.destroy === false && process.exit(),
  ),
  new ScenarioAction("deleteTable", async (c) => {
    try {
      const client = new DynamoDBClient({});
      await client.send(new DeleteTableCommand({ TableName: NAMES.tableName }));
    } catch (e) {
      c.deleteTableError = e;
    }
  }),
  new ScenarioOutput("deleteTableResult", (state) => {
    if (state.deleteTableError) {
      console.error(state.deleteTableError);
      return MESSAGES.deleteTableError.replace(
        "${TABLE_NAME}",
        NAMES.tableName,
      );
    }
    return MESSAGES.deletedTable.replace("${TABLE_NAME}", NAMES.tableName);
  }),
  new ScenarioAction("deleteKeyPair", async (state) => {
    try {
      const client = new EC2Client({});
      await client.send(
        new DeleteKeyPairCommand({ KeyName: NAMES.keyPairName }),
      );
      unlinkSync(`${NAMES.keyPairName}.pem`);
    } catch (e) {
      state.deleteKeyPairError = e;
    }
  }),
  new ScenarioOutput("deleteKeyPairResult", (state) => {
    if (state.deleteKeyPairError) {
      console.error(state.deleteKeyPairError);
      return MESSAGES.deleteKeyPairError.replace(
        "${KEY_PAIR_NAME}",
        NAMES.keyPairName,
      );
    }
    return MESSAGES.deletedKeyPair.replace(
      "${KEY_PAIR_NAME}",
      NAMES.keyPairName,
    );
  }),
  new ScenarioAction("detachPolicyFromRole", async (state) => {
    try {
      const client = new IAMClient({});
      const policy = await findPolicy(NAMES.instancePolicyName);

      if (!policy) {
        state.detachPolicyFromRoleError = new Error(
          `Policy ${NAMES.instancePolicyName} not found.`,
        );
      } else {
        await client.send(
          new DetachRolePolicyCommand({
            RoleName: NAMES.instanceRoleName,
            PolicyArn: policy.Arn,
          }),
        );
      }
    } catch (e) {
      state.detachPolicyFromRoleError = e;
    }
  }),
  new ScenarioOutput("detachedPolicyFromRole", (state) => {
    if (state.detachPolicyFromRoleError) {
      console.error(state.detachPolicyFromRoleError);
      return MESSAGES.detachPolicyFromRoleError
        .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.detachedPolicyFromRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const policy = await findPolicy(NAMES.instancePolicyName);

    if (!policy) {
      state.deletePolicyError = new Error(
        `Policy ${NAMES.instancePolicyName} not found.`,
      );
    } else {
      return client.send(
        new DeletePolicyCommand({
          PolicyArn: policy.Arn,
        }),
      );
    }
  }),
  new ScenarioOutput("deletePolicyResult", (state) => {
    if (state.deletePolicyError) {
      console.error(state.deletePolicyError);
      return MESSAGES.deletePolicyError.replace(
        "${INSTANCE_POLICY_NAME}",
        NAMES.instancePolicyName,
      );
    }
    return MESSAGES.deletedPolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    );
  }),
  new ScenarioAction("removeRoleFromInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          RoleName: NAMES.instanceRoleName,
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.removeRoleFromInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("removeRoleFromInstanceProfileResult", (state) => {
    if (state.removeRoleFromInstanceProfile) {
      console.error(state.removeRoleFromInstanceProfileError);
      return MESSAGES.removeRoleFromInstanceProfileError
        .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.removedRoleFromInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstanceRole", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteRoleCommand({
          RoleName: NAMES.instanceRoleName,
        }),
      );
    } catch (e) {
      state.deleteInstanceRoleError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceRoleResult", (state) => {
    if (state.deleteInstanceRoleError) {
      console.error(state.deleteInstanceRoleError);
      return MESSAGES.deleteInstanceRoleError.replace(
        "${INSTANCE_ROLE_NAME}",
        NAMES.instanceRoleName,
      );
    }
    return MESSAGES.deletedInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    );
  }),
  new ScenarioAction("deleteInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceProfileResult", (state) => {
    if (state.deleteInstanceProfileError) {
      console.error(state.deleteInstanceProfileError);
      return MESSAGES.deleteInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.instanceProfileName,
      );
    }
    return MESSAGES.deletedInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    );
  }),
  new ScenarioAction("deleteAutoScalingGroup", async (state) => {
    try {
      await terminateGroupInstances(NAMES.autoScalingGroupName);
      await retry({ intervalInMs: 60000, maxRetries: 60 }, async () => {
        await deleteAutoScalingGroup(NAMES.autoScalingGroupName);
      });
    } catch (e) {
      state.deleteAutoScalingGroupError = e;
    }
  }),
  new ScenarioOutput("deleteAutoScalingGroupResult", (state) => {
    if (state.deleteAutoScalingGroupError) {
      console.error(state.deleteAutoScalingGroupError);
      return MESSAGES.deleteAutoScalingGroupError.replace(
        "${AUTO_SCALING_GROUP_NAME}",
        NAMES.autoScalingGroupName,
      );
    }
    return MESSAGES.deletedAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    );
  }),
  new ScenarioAction("deleteLaunchTemplate", async (state) => {
    const client = new EC2Client({});
    try {
      await client.send(
        new DeleteLaunchTemplateCommand({
          LaunchTemplateName: NAMES.launchTemplateName,
        }),
      );
    } catch (e) {
      state.deleteLaunchTemplateError = e;
    }
  }),
  new ScenarioOutput("deleteLaunchTemplateResult", (state) => {
    if (state.deleteLaunchTemplateError) {
      console.error(state.deleteLaunchTemplateError);
      return MESSAGES.deleteLaunchTemplateError.replace(
        "${LAUNCH_TEMPLATE_NAME}",
        NAMES.launchTemplateName,
      );
    }
    return MESSAGES.deletedLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    );
  }),
  new ScenarioAction("deleteLoadBalancer", async (state) => {
    try {
      const client = new ElasticLoadBalancingV2Client({});
      const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
      await client.send(
        new DeleteLoadBalancerCommand({
          LoadBalancerArn: loadBalancer.LoadBalancerArn,
        }),
      );
      await retry({ intervalInMs: 1000, maxRetries: 60 }, async () => {
        const lb = await findLoadBalancer(NAMES.loadBalancerName);
        if (lb) {
          throw new Error("Load balancer still exists.");
        }
      });
    } catch (e) {
      state.deleteLoadBalancerError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerResult", (state) => {
    if (state.deleteLoadBalancerError) {
      console.error(state.deleteLoadBalancerError);
      return MESSAGES.deleteLoadBalancerError.replace(
        "${LB_NAME}",
        NAMES.loadBalancerName,
      );
    }
    return MESSAGES.deletedLoadBalancer.replace(
      "${LB_NAME}",
      NAMES.loadBalancerName,
    );
  }),
  new ScenarioAction("deleteLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    try {
      const { TargetGroups } = await client.send(
        new DescribeTargetGroupsCommand({
          Names: [NAMES.loadBalancerTargetGroupName],
        }),
      );

      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        client.send(
          new DeleteTargetGroupCommand({
            TargetGroupArn: TargetGroups[0].TargetGroupArn,
          }),
        ),
      );
    } catch (e) {
      state.deleteLoadBalancerTargetGroupError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerTargetGroupResult", (state) => {
    if (state.deleteLoadBalancerTargetGroupError) {
      console.error(state.deleteLoadBalancerTargetGroupError);
      return MESSAGES.deleteLoadBalancerTargetGroupError.replace(
        "${TARGET_GROUP_NAME}",
        NAMES.loadBalancerTargetGroupName,
      );
    }
    return MESSAGES.deletedLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    );
  }),
  new ScenarioAction("detachSsmOnlyRoleFromProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyRoleFromProfileError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyRoleFromProfileResult", (state) => {
    if (state.detachSsmOnlyRoleFromProfileError) {
      console.error(state.detachSsmOnlyRoleFromProfileError);
      return MESSAGES.detachSsmOnlyRoleFromProfileError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
    }
    return MESSAGES.detachedSsmOnlyRoleFromProfile
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
  }),
  new ScenarioAction("detachSsmOnlyCustomRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyCustomRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyCustomRolePolicyResult", (state) => {
    if (state.detachSsmOnlyCustomRolePolicyError) {
      console.error(state.detachSsmOnlyCustomRolePolicyError);
      return MESSAGES.detachSsmOnlyCustomRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
    }
    return MESSAGES.detachedSsmOnlyCustomRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
  }),
  new ScenarioAction("detachSsmOnlyAWSRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
        }),
      );
    } catch (e) {
      state.detachSsmOnlyAWSRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyAWSRolePolicyResult", (state) => {
    if (state.detachSsmOnlyAWSRolePolicyError) {
      console.error(state.detachSsmOnlyAWSRolePolicyError);
      return MESSAGES.detachSsmOnlyAWSRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
    }
    return MESSAGES.detachedSsmOnlyAWSRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
  }),
  new ScenarioAction("deleteSsmOnlyInstanceProfile", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyInstanceProfileResult", (state) => {
    if (state.deleteSsmOnlyInstanceProfileError) {
      console.error(state.deleteSsmOnlyInstanceProfileError);
      return MESSAGES.deleteSsmOnlyInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.ssmOnlyInstanceProfileName,
      );
    }
    return MESSAGES.deletedSsmOnlyInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.ssmOnlyInstanceProfileName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyPolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DeletePolicyCommand({
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyPolicyError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyPolicyResult", (state) => {
    if (state.deleteSsmOnlyPolicyError) {
      console.error(state.deleteSsmOnlyPolicyError);
      return MESSAGES.deleteSsmOnlyPolicyError.replace(
        "${POLICY_NAME}",
        NAMES.ssmOnlyPolicyName,
      );
    }
    return MESSAGES.deletedSsmOnlyPolicy.replace(
      "${POLICY_NAME}",
      NAMES.ssmOnlyPolicyName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyRole", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteRoleCommand({
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyRoleError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyRoleResult", (state) => {
    if (state.deleteSsmOnlyRoleError) {
      console.error(state.deleteSsmOnlyRoleError);
      return MESSAGES.deleteSsmOnlyRoleError.replace(
        "${ROLE_NAME}",
        NAMES.ssmOnlyRoleName,
      );
    }
    return MESSAGES.deletedSsmOnlyRole.replace(
      "${ROLE_NAME}",
      NAMES.ssmOnlyRoleName,
    );
  }),
  new ScenarioAction(
    "revokeSecurityGroupIngress",
    async (
      /** @type {{ myIp: string, defaultSecurityGroup: { GroupId: string } }} */ state,
    ) => {
      const ec2Client = new EC2Client({});

      try {
        await ec2Client.send(
          new RevokeSecurityGroupIngressCommand({
            GroupId: state.defaultSecurityGroup.GroupId,
            CidrIp: `${state.myIp}/32`,
            FromPort: 80,
            ToPort: 80,
            IpProtocol: "tcp",
          }),
        );
      } catch (e) {
        state.revokeSecurityGroupIngressError = e;
      }
    },
  ),
  new ScenarioOutput("revokeSecurityGroupIngressResult", (state) => {
    if (state.revokeSecurityGroupIngressError) {
      console.error(state.revokeSecurityGroupIngressError);
      return MESSAGES.revokeSecurityGroupIngressError.replace(
        "${IP}",
        state.myIp,
      );
    }
    return MESSAGES.revokedSecurityGroupIngress.replace("${IP}", state.myIp);
  }),
];

/**
 * @param {string} policyName
 */
async function findPolicy(policyName) {
  const client = new IAMClient({});
  const paginatedPolicies = paginateListPolicies({ client }, {});
  for await (const page of paginatedPolicies) {
    const policy = page.Policies.find((p) => p.PolicyName === policyName);
    if (policy) {
      return policy;
    }
  }
}

/**
 * @param {string} groupName
 */
async function deleteAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  try {
    await client.send(
      new DeleteAutoScalingGroupCommand({
        AutoScalingGroupName: groupName,
      }),
    );
  } catch (err) {
    if (!(err instanceof Error)) {
      throw err;
    }
    console.log(err.name);
    throw err;
  }
}

/**
 * @param {string} groupName
 */
async function terminateGroupInstances(groupName) {
  const autoScalingClient = new AutoScalingClient({});
  const group = await findAutoScalingGroup(groupName);
  await autoScalingClient.send(
    new UpdateAutoScalingGroupCommand({
      AutoScalingGroupName: group.AutoScalingGroupName,
      MinSize: 0,
    }),
  );
  for (const i of group.Instances) {
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: i.InstanceId,
          ShouldDecrementDesiredCapacity: true,
        }),
      ),
    );
  }
}

async function findAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  const paginatedGroups = paginateDescribeAutoScalingGroups({ client }, {});
  for await (const page of paginatedGroups) {
    const group = page.AutoScalingGroups.find(
      (g) => g.AutoScalingGroupName === groupName,
    );
    if (group) {
      return group;
    }
  }
  throw new Error(`Auto scaling group ${groupName} not found.`);
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/AttachLoadBalancerTargetGroupsCommand)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/CreateAutoScalingGroupCommand)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateInstanceProfileCommand)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateLaunchTemplateCommand)
  + [CreateListener](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateListenerCommand)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateLoadBalancerCommand)
  + [CreateTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateTargetGroupCommand)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DeleteAutoScalingGroupCommand)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteInstanceProfileCommand)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteLaunchTemplateCommand)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteLoadBalancerCommand)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteTargetGroupCommand)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DescribeAutoScalingGroupsCommand)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeAvailabilityZonesCommand)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeIamInstanceProfileAssociationsCommand)
  + [DescribeInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstancesCommand)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeLoadBalancersCommand)
  + [DescribeSubnets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSubnetsCommand)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetGroupsCommand)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetHealthCommand)
  + [DescribeVpcs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeVpcsCommand)
  + [RebootInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RebootInstancesCommand)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReplaceIamInstanceProfileAssociationCommand)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/TerminateInstanceInAutoScalingGroupCommand)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/UpdateAutoScalingGroupCommand)

# AWS Entity Resolution SDK for JavaScript (v3) を使用した例
<a name="javascript_3_entityresolution_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Entity Resolution。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Entity Resolutionは
<a name="entityresolution_Hello_javascript_3_topic"></a>

次のコード例は、 AWS Entity Resolutionの使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  EntityResolutionClient,
  ListMatchingWorkflowsCommand,
} from "@aws-sdk/client-entityresolution";

export const main = async () => {
  const region = "eu-west-1";
  const erClient = new EntityResolutionClient({ region: region });
  try {
    const command = new ListMatchingWorkflowsCommand({});
    const response = await erClient.send(command);
    const workflowSummaries = response.workflowSummaries;
    for (const workflowSummary of workflowSummaries) {
      console.log(`Attribute name: ${workflowSummaries[0].workflowName} `);
    }
    if (workflowSummaries.length === 0) {
      console.log("No matching workflows found.");
    }
  } catch (error) {
    console.error(
      `An error occurred in listing the workflow summaries: ${error.message} \n Exiting program.`,
    );
    return;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListMatchingWorkflows](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/ListMatchingWorkflowsCommand)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateMatchingWorkflow`
<a name="entityresolution_CreateMatchingWorkflow_javascript_3_topic"></a>

次のコード例は、`CreateMatchingWorkflow` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  CreateMatchingWorkflowCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  const createMatchingWorkflowParams = {
    roleArn: `${data.inputs.roleArn}`,
    workflowName: `${data.inputs.workflowName}`,
    description: "Created by using the AWS SDK for JavaScript (v3).",
    inputSourceConfig: [
      {
        inputSourceARN: `${data.inputs.JSONinputSourceARN}`,
        schemaName: `${data.inputs.schemaNameJson}`,
        applyNormalization: false,
      },
      {
        inputSourceARN: `${data.inputs.CSVinputSourceARN}`,
        schemaName: `${data.inputs.schemaNameCSV}`,
        applyNormalization: false,
      },
    ],
    outputSourceConfig: [
      {
        outputS3Path: `s3://${data.inputs.myBucketName}/eroutput`,
        output: [
          {
            name: "id",
          },
          {
            name: "name",
          },
          {
            name: "email",
          },
          {
            name: "phone",
          },
        ],
        applyNormalization: false,
      },
    ],
    resolutionTechniques: { resolutionType: "ML_MATCHING" },
  };
  try {
    const command = new CreateMatchingWorkflowCommand(
      createMatchingWorkflowParams,
    );
    const response = await erClient.send(command);

    console.log(
      `Workflow created successfully.\n The workflow ARN is: ${response.workflowArn}`,
    );
  } catch (caught) {
    console.error(caught.message);
    throw caught;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateMatchingWorkflow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/CreateMatchingWorkflowCommand)」を参照してください。

### `CreateSchemaMapping`
<a name="entityresolution_CreateSchemaMapping_javascript_3_topic"></a>

次のコード例は、`CreateSchemaMapping` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  CreateSchemaMappingCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  const createSchemaMappingParamsJson = {
    schemaName: `${data.inputs.schemaNameJson}`,
    mappedInputFields: [
      {
        fieldName: "id",
        type: "UNIQUE_ID",
      },
      {
        fieldName: "name",
        type: "NAME",
      },
      {
        fieldName: "email",
        type: "EMAIL_ADDRESS",
      },
    ],
  };
  const createSchemaMappingParamsCSV = {
    schemaName: `${data.inputs.schemaNameCSV}`,
    mappedInputFields: [
      {
        fieldName: "id",
        type: "UNIQUE_ID",
      },
      {
        fieldName: "name",
        type: "NAME",
      },
      {
        fieldName: "email",
        type: "EMAIL_ADDRESS",
      },
      {
        fieldName: "phone",
        type: "PROVIDER_ID",
        subType: "STRING",
      },
    ],
  };
  try {
    const command = new CreateSchemaMappingCommand(
      createSchemaMappingParamsJson,
    );
    const response = await erClient.send(command);
    console.log("The JSON schema mapping name is ", response.schemaName);
  } catch (error) {
    console.log("error ", error.message);
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateSchemaMapping](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/CreateSchemaMappingCommand)」を参照してください。

### `DeleteMatchingWorkflow`
<a name="entityresolution_DeleteMatchingWorkflow_javascript_3_topic"></a>

次のコード例は、`DeleteMatchingWorkflow` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  DeleteMatchingWorkflowCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  try {
    const deleteWorkflowParams = {
      workflowName: `${data.inputs.workflowName}`,
    };
    const command = new DeleteMatchingWorkflowCommand(deleteWorkflowParams);
    const response = await erClient.send(command);
    console.log("Workflow deleted successfully!", response);
  } catch (error) {
    console.log("error ", error);
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteMatchingWorkflow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/DeleteMatchingWorkflowCommand)」を参照してください。

### `DeleteSchemaMapping`
<a name="entityresolution_DeleteSchemaMapping_javascript_3_topic"></a>

次のコード例は、`DeleteSchemaMapping` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  DeleteSchemaMappingCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  const deleteSchemaMapping = {
    schemaName: `${data.inputs.schemaNameJson}`,
  };
  try {
    const command = new DeleteSchemaMappingCommand(deleteSchemaMapping);
    const response = await erClient.send(command);
    console.log("Schema mapping deleted successfully. ", response);
  } catch (error) {
    console.log("error ", error);
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteSchemaMapping](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/DeleteSchemaMappingCommand)」を参照してください。

### `GetMatchingJob`
<a name="entityresolution_GetMatchingJob_javascript_3_topic"></a>

次のコード例は、`GetMatchingJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  GetMatchingJobCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  async function getInfo() {
    const getJobInfoParams = {
      workflowName: `${data.inputs.workflowName}`,
      jobId: `${data.inputs.jobId}`,
    };
    try {
      const command = new GetMatchingJobCommand(getJobInfoParams);
      const response = await erClient.send(command);
      console.log(`Job status: ${response.status}`);
    } catch (error) {
      console.log("error ", error.message);
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetMatchingJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/GetMatchingJobCommand)」を参照してください。

### `GetSchemaMapping`
<a name="entityresolution_GetSchemaMapping_javascript_3_topic"></a>

次のコード例は、`GetSchemaMapping` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  GetSchemaMappingCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  const getSchemaMappingJsonParams = {
    schemaName: `${data.inputs.schemaNameJson}`,
  };
  try {
    const command = new GetSchemaMappingCommand(getSchemaMappingJsonParams);
    const response = await erClient.send(command);
    console.log(response);
    console.log(
      `Schema mapping for the JSON data:\n ${response.mappedInputFields[0]}`,
    );
    console.log("Schema mapping ARN is: ", response.schemaArn);
  } catch (caught) {
    console.error(caught.message);
    throw caught;
  }
};
```
+  API の詳細については、「[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/GetSchemaMappingCommand)」の「*GetSchemaMapping*」を参照してください。

### `ListSchemaMappings`
<a name="entityresolution_ListSchemaMappings_javascript_3_topic"></a>

次のコード例は、`ListSchemaMappings` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  ListSchemaMappingsCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  async function getInfo() {
    const listSchemaMappingsParams = {
      workflowName: `${data.inputs.workflowName}`,
      jobId: `${data.inputs.jobId}`,
    };
    try {
      const command = new ListSchemaMappingsCommand(listSchemaMappingsParams);
      const response = await erClient.send(command);
      const noOfSchemas = response.schemaList.length;
      for (let i = 0; i < noOfSchemas; i++) {
        console.log(
          `Schema Mapping Name: ${response.schemaList[i].schemaName} `,
        );
      }
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
  }
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListSchemaMappings](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/ListSchemaMappingsCommand)」を参照してください。

### `StartMatchingJob`
<a name="entityresolution_StartMatchingJob_javascript_3_topic"></a>

次のコード例は、`StartMatchingJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";
import {
  StartMatchingJobCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  const matchingJobOfWorkflowParams = {
    workflowName: `${data.inputs.workflowName}`,
  };
  try {
    const command = new StartMatchingJobCommand(matchingJobOfWorkflowParams);
    const response = await erClient.send(command);
    console.log(`Job ID: ${response.jobID} \n
The matching job was successfully started.`);
  } catch (caught) {
    console.error(caught.message);
    throw caught;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[StartMatchingJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/StartMatchingJobCommand)」を参照してください。

### `TagResource`
<a name="entityresolution_TagResource_javascript_3_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
//The default inputs for this demo are read from the ../inputs.json.

import { fileURLToPath } from "node:url";

import {
  TagResourceCommand,
  EntityResolutionClient,
} from "@aws-sdk/client-entityresolution";
import data from "../inputs.json" with { type: "json" };

const region = "eu-west-1";
const erClient = new EntityResolutionClient({ region: region });

export const main = async () => {
  const tagResourceCommandParams = {
    resourceArn: `${data.inputs.schemaArn}`,
    tags: {
      tag1: "tag1Value",
      tag2: "tag2Value",
    },
  };
  try {
    const command = new TagResourceCommand(tagResourceCommandParams);
    const response = await erClient.send(command);
    console.log("Successfully tagged the resource.");
  } catch (caught) {
    console.error(caught.message);
    throw caught;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[TagResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/entityresolution/command/TagResourceCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した EventBridge の例
<a name="javascript_3_eventbridge_code_examples"></a>

次のコード例は、EventBridge で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="eventbridge_PutEvents_javascript_3_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import {
  EventBridgeClient,
  PutEventsCommand,
} from "@aws-sdk/client-eventbridge";

export const putEvents = async (
  source = "eventbridge.integration.test",
  detailType = "greeting",
  resources = [],
) => {
  const client = new EventBridgeClient({});

  const response = await client.send(
    new PutEventsCommand({
      Entries: [
        {
          Detail: JSON.stringify({ greeting: "Hello there." }),
          DetailType: detailType,
          Resources: resources,
          Source: source,
        },
      ],
    }),
  );

  console.log("PutEvents response:");
  console.log(response);
  // PutEvents response:
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '3d0df73d-dcea-4a23-ae0d-f5556a3ac109',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Entries: [ { EventId: '51620841-5af4-6402-d9bc-b77734991eb5' } ],
  //   FailedEntryCount: 0
  // }

  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/eventbridge/command/PutEventsCommand)」を参照してください。

### `PutRule`
<a name="eventbridge_PutRule_javascript_3_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import { EventBridgeClient, PutRuleCommand } from "@aws-sdk/client-eventbridge";

export const putRule = async (
  ruleName = "some-rule",
  source = "some-source",
) => {
  const client = new EventBridgeClient({});

  const response = await client.send(
    new PutRuleCommand({
      Name: ruleName,
      EventPattern: JSON.stringify({ source: [source] }),
      State: "ENABLED",
      EventBusName: "default",
    }),
  );

  console.log("PutRule response:");
  console.log(response);
  // PutRule response:
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'd7292ced-1544-421b-842f-596326bc7072',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   RuleArn: 'arn:aws:events:us-east-1:xxxxxxxxxxxx:rule/EventBridgeTestRule-1696280037720'
  // }
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutRule](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/eventbridge/command/PutRuleCommand)」を参照してください。

### `PutTargets`
<a name="eventbridge_PutTargets_javascript_3_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。  

```
import {
  EventBridgeClient,
  PutTargetsCommand,
} from "@aws-sdk/client-eventbridge";

export const putTarget = async (
  existingRuleName = "some-rule",
  targetArn = "arn:aws:lambda:us-east-1:000000000000:function:test-func",
  uniqueId = Date.now().toString(),
) => {
  const client = new EventBridgeClient({});
  const response = await client.send(
    new PutTargetsCommand({
      Rule: existingRuleName,
      Targets: [
        {
          Arn: targetArn,
          Id: uniqueId,
        },
      ],
    }),
  );

  console.log("PutTargets response:");
  console.log(response);
  // PutTargets response:
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'f5b23b9a-2c17-45c1-ad5c-f926c3692e3d',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   FailedEntries: [],
  //   FailedEntryCount: 0
  // }

  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/eventbridge/command/PutTargetsCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_javascript_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda JavaScript ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

# SDK for JavaScript (v3) を使用した Amazon Glacier の例
<a name="javascript_3_glacier_code_examples"></a>

次のコード例は、Amazon Glacier で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateVault`
<a name="glacier_CreateVault_javascript_3_topic"></a>

次のコード例は、`CreateVault` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glacier#code-examples)での設定と実行の方法を確認してください。
クライアントを作成する  

```
const { GlacierClient } = require("@aws-sdk/client-glacier");
// Set the AWS Region.
const REGION = "REGION";
//Set the Redshift Service Object
const glacierClient = new GlacierClient({ region: REGION });
export { glacierClient };
```
ボールトを作成します。  

```
// Load the SDK for JavaScript
import { CreateVaultCommand } from "@aws-sdk/client-glacier";
import { glacierClient } from "./libs/glacierClient.js";

// Set the parameters
const vaultname = "VAULT_NAME"; // VAULT_NAME
const params = { vaultName: vaultname };

const run = async () => {
  try {
    const data = await glacierClient.send(new CreateVaultCommand(params));
    console.log("Success, vault created!");
    return data; // For unit tests.
  } catch (err) {
    console.log("Error");
  }
};
run();
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/glacier-example-creating-a-vault.html)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateVault](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glacier/command/CreateVaultCommand)」を参照してください。

### `UploadArchive`
<a name="glacier_UploadArchive_javascript_3_topic"></a>

次のコード例は、`UploadArchive` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glacier#code-examples)での設定と実行の方法を確認してください。
クライアントの作成  

```
const { GlacierClient } = require("@aws-sdk/client-glacier");
// Set the AWS Region.
const REGION = "REGION";
//Set the Redshift Service Object
const glacierClient = new GlacierClient({ region: REGION });
export { glacierClient };
```
アーカイブをアップロードします。  

```
// Load the SDK for JavaScript
import { UploadArchiveCommand } from "@aws-sdk/client-glacier";
import { glacierClient } from "./libs/glacierClient.js";

// Set the parameters
const vaultname = "VAULT_NAME"; // VAULT_NAME

// Create a new service object and buffer
const buffer = new Buffer.alloc(2.5 * 1024 * 1024); // 2.5MB buffer
const params = { vaultName: vaultname, body: buffer };

const run = async () => {
  try {
    const data = await glacierClient.send(new UploadArchiveCommand(params));
    console.log("Archive ID", data.archiveId);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error uploading archive!", err);
  }
};
run();
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/glacier-example-uploadarchive.html)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UploadArchive](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glacier/command/UploadArchiveCommand)」を参照してください。

# AWS Glue SDK for JavaScript (v3) を使用した例
<a name="javascript_3_glue_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Glueは
<a name="glue_Hello_javascript_3_topic"></a>

次のコード例は、 AWS Glueの使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import { ListJobsCommand, GlueClient } from "@aws-sdk/client-glue";

const client = new GlueClient({});

export const main = async () => {
  const command = new ListJobsCommand({});

  const { JobNames } = await client.send(command);
  const formattedJobNames = JobNames.join("\n");
  console.log("Job names: ");
  console.log(formattedJobNames);
  return JobNames;
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/ListJobsCommand)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。
パブリックの Amazon Simple Storage Service (Amazon S3) バケットをクロールし、検出した CSV 形式データを記述するメタデータデータベースを生成するクローラーを作成して実行します。  

```
const createCrawler = (name, role, dbName, tablePrefix, s3TargetPath) => {
  const client = new GlueClient({});

  const command = new CreateCrawlerCommand({
    Name: name,
    Role: role,
    DatabaseName: dbName,
    TablePrefix: tablePrefix,
    Targets: {
      S3Targets: [{ Path: s3TargetPath }],
    },
  });

  return client.send(command);
};

const getCrawler = (name) => {
  const client = new GlueClient({});

  const command = new GetCrawlerCommand({
    Name: name,
  });

  return client.send(command);
};

const startCrawler = (name) => {
  const client = new GlueClient({});

  const command = new StartCrawlerCommand({
    Name: name,
  });

  return client.send(command);
};

const crawlerExists = async ({ getCrawler }, crawlerName) => {
  try {
    await getCrawler(crawlerName);
    return true;
  } catch {
    return false;
  }
};

/**
 * @param {{ createCrawler: import('../../../actions/create-crawler.js').createCrawler}} actions
 */
const makeCreateCrawlerStep = (actions) => async (context) => {
  if (await crawlerExists(actions, process.env.CRAWLER_NAME)) {
    log("Crawler already exists. Skipping creation.");
  } else {
    await actions.createCrawler(
      process.env.CRAWLER_NAME,
      process.env.ROLE_NAME,
      process.env.DATABASE_NAME,
      process.env.TABLE_PREFIX,
      process.env.S3_TARGET_PATH,
    );

    log("Crawler created successfully.", { type: "success" });
  }

  return { ...context };
};

/**
 * @param {(name: string) => Promise<import('@aws-sdk/client-glue').GetCrawlerCommandOutput>} getCrawler
 * @param {string} crawlerName
 */
const waitForCrawler = async (getCrawler, crawlerName) => {
  const waitTimeInSeconds = 30;
  const { Crawler } = await getCrawler(crawlerName);

  if (!Crawler) {
    throw new Error(`Crawler with name ${crawlerName} not found.`);
  }

  if (Crawler.State === "READY") {
    return;
  }

  log(`Crawler is ${Crawler.State}. Waiting ${waitTimeInSeconds} seconds...`);
  await wait(waitTimeInSeconds);
  return waitForCrawler(getCrawler, crawlerName);
};

const makeStartCrawlerStep =
  ({ startCrawler, getCrawler }) =>
  async (context) => {
    log("Starting crawler.");
    await startCrawler(process.env.CRAWLER_NAME);
    log("Crawler started.", { type: "success" });

    log("Waiting for crawler to finish running. This can take a while.");
    await waitForCrawler(getCrawler, process.env.CRAWLER_NAME);
    log("Crawler ready.", { type: "success" });

    return { ...context };
  };
```
のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。  

```
const getDatabase = (name) => {
  const client = new GlueClient({});

  const command = new GetDatabaseCommand({
    Name: name,
  });

  return client.send(command);
};

const getTables = (databaseName) => {
  const client = new GlueClient({});

  const command = new GetTablesCommand({
    DatabaseName: databaseName,
  });

  return client.send(command);
};

const makeGetDatabaseStep =
  ({ getDatabase }) =>
  async (context) => {
    const {
      Database: { Name },
    } = await getDatabase(process.env.DATABASE_NAME);
    log(`Database: ${Name}`);
    return { ...context };
  };

/**
 * @param {{ getTables: () => Promise<import('@aws-sdk/client-glue').GetTablesCommandOutput}} config
 */
const makeGetTablesStep =
  ({ getTables }) =>
  async (context) => {
    const { TableList } = await getTables(process.env.DATABASE_NAME);
    log("Tables:");
    log(TableList.map((table) => `  • ${table.Name}\n`));
    return { ...context };
  };
```
ソース Amazon S3 バケットから CSV 形式データを抽出し、フィールドを削除して名前を変更することで変換し、JSON 形式の出力を別の Amazon S3 バケットにロードするジョブを作成して実行します。  

```
const createJob = (name, role, scriptBucketName, scriptKey) => {
  const client = new GlueClient({});

  const command = new CreateJobCommand({
    Name: name,
    Role: role,
    Command: {
      Name: "glueetl",
      PythonVersion: "3",
      ScriptLocation: `s3://${scriptBucketName}/${scriptKey}`,
    },
    GlueVersion: "3.0",
  });

  return client.send(command);
};

const startJobRun = (jobName, dbName, tableName, bucketName) => {
  const client = new GlueClient({});

  const command = new StartJobRunCommand({
    JobName: jobName,
    Arguments: {
      "--input_database": dbName,
      "--input_table": tableName,
      "--output_bucket_url": `s3://${bucketName}/`,
    },
  });

  return client.send(command);
};

const makeCreateJobStep =
  ({ createJob }) =>
  async (context) => {
    log("Creating Job.");
    await createJob(
      process.env.JOB_NAME,
      process.env.ROLE_NAME,
      process.env.BUCKET_NAME,
      process.env.PYTHON_SCRIPT_KEY,
    );
    log("Job created.", { type: "success" });

    return { ...context };
  };

/**
 * @param {(name: string, runId: string) => Promise<import('@aws-sdk/client-glue').GetJobRunCommandOutput> }  getJobRun
 * @param {string} jobName
 * @param {string} jobRunId
 */
const waitForJobRun = async (getJobRun, jobName, jobRunId) => {
  const waitTimeInSeconds = 30;
  const { JobRun } = await getJobRun(jobName, jobRunId);

  if (!JobRun) {
    throw new Error(`Job run with id ${jobRunId} not found.`);
  }

  switch (JobRun.JobRunState) {
    case "FAILED":
    case "TIMEOUT":
    case "STOPPED":
    case "ERROR":
      throw new Error(
        `Job ${JobRun.JobRunState}. Error: ${JobRun.ErrorMessage}`,
      );
    case "SUCCEEDED":
      return;
    default:
      break;
  }

  log(
    `Job ${JobRun.JobRunState}. Waiting ${waitTimeInSeconds} more seconds...`,
  );
  await wait(waitTimeInSeconds);
  return waitForJobRun(getJobRun, jobName, jobRunId);
};

/**
 * @param {{ prompter: { prompt: () => Promise<{ shouldOpen: boolean }>} }} context
 */
const promptToOpen = async (context) => {
  const { shouldOpen } = await context.prompter.prompt({
    name: "shouldOpen",
    type: "confirm",
    message: "Open the output bucket in your browser?",
  });

  if (shouldOpen) {
    return open(
      `https://s3.console.aws.amazon.com/s3/buckets/${process.env.BUCKET_NAME} to view the output.`,
    );
  }
};

const makeStartJobRunStep =
  ({ startJobRun, getJobRun }) =>
  async (context) => {
    log("Starting job.");
    const { JobRunId } = await startJobRun(
      process.env.JOB_NAME,
      process.env.DATABASE_NAME,
      process.env.TABLE_NAME,
      process.env.BUCKET_NAME,
    );
    log("Job started.", { type: "success" });

    log("Waiting for job to finish running. This can take a while.");
    await waitForJobRun(getJobRun, process.env.JOB_NAME, JobRunId);
    log("Job run succeeded.", { type: "success" });

    await promptToOpen(context);

    return { ...context };
  };
```
ジョブ実行に関する情報を一覧表示し、変換されたデータの一部を表示します。  

```
const getJobRuns = (jobName) => {
  const client = new GlueClient({});
  const command = new GetJobRunsCommand({
    JobName: jobName,
  });

  return client.send(command);
};

const getJobRun = (jobName, jobRunId) => {
  const client = new GlueClient({});
  const command = new GetJobRunCommand({
    JobName: jobName,
    RunId: jobRunId,
  });

  return client.send(command);
};

/**
 * @typedef {{ prompter: { prompt: () => Promise<{jobName: string}> } }} Context
 */

/**
 * @typedef {() => Promise<import('@aws-sdk/client-glue').GetJobRunCommandOutput>} getJobRun
 */

/**
 * @typedef {() => Promise<import('@aws-sdk/client-glue').GetJobRunsCommandOutput} getJobRuns
 */

/**
 *
 * @param {getJobRun} getJobRun
 * @param {string} jobName
 * @param {string} jobRunId
 */
const logJobRunDetails = async (getJobRun, jobName, jobRunId) => {
  const { JobRun } = await getJobRun(jobName, jobRunId);
  log(JobRun, { type: "object" });
};

/**
 *
 * @param {{getJobRuns: getJobRuns, getJobRun: getJobRun }} funcs
 */
const makePickJobRunStep =
  ({ getJobRuns, getJobRun }) =>
  async (/** @type { Context } */ context) => {
    if (context.selectedJobName) {
      const { JobRuns } = await getJobRuns(context.selectedJobName);

      const { jobRunId } = await context.prompter.prompt({
        name: "jobRunId",
        type: "list",
        message: "Select a job run to see details.",
        choices: JobRuns.map((run) => run.Id),
      });

      logJobRunDetails(getJobRun, context.selectedJobName, jobRunId);
    }

    return { ...context };
  };
```
デモによって作成されたすべてのリソースを削除します。  

```
const deleteJob = (jobName) => {
  const client = new GlueClient({});

  const command = new DeleteJobCommand({
    JobName: jobName,
  });

  return client.send(command);
};

const deleteTable = (databaseName, tableName) => {
  const client = new GlueClient({});

  const command = new DeleteTableCommand({
    DatabaseName: databaseName,
    Name: tableName,
  });

  return client.send(command);
};

const deleteDatabase = (databaseName) => {
  const client = new GlueClient({});

  const command = new DeleteDatabaseCommand({
    Name: databaseName,
  });

  return client.send(command);
};

const deleteCrawler = (crawlerName) => {
  const client = new GlueClient({});

  const command = new DeleteCrawlerCommand({
    Name: crawlerName,
  });

  return client.send(command);
};

/**
 *
 * @param {import('../../../actions/delete-job.js').deleteJob} deleteJobFn
 * @param {string[]} jobNames
 * @param {{ prompter: { prompt: () => Promise<any> }}} context
 */
const handleDeleteJobs = async (deleteJobFn, jobNames, context) => {
  /**
   * @type {{ selectedJobNames: string[] }}
   */
  const { selectedJobNames } = await context.prompter.prompt({
    name: "selectedJobNames",
    type: "checkbox",
    message: "Let's clean up jobs. Select jobs to delete.",
    choices: jobNames,
  });

  if (selectedJobNames.length === 0) {
    log("No jobs selected.");
  } else {
    log("Deleting jobs.");
    await Promise.all(
      selectedJobNames.map((n) => deleteJobFn(n).catch(console.error)),
    );
    log("Jobs deleted.", { type: "success" });
  }
};

/**
 * @param {{
 *   listJobs: import('../../../actions/list-jobs.js').listJobs,
 *   deleteJob: import('../../../actions/delete-job.js').deleteJob
 * }} config
 */
const makeCleanUpJobsStep =
  ({ listJobs, deleteJob }) =>
  async (context) => {
    const { JobNames } = await listJobs();
    if (JobNames.length > 0) {
      await handleDeleteJobs(deleteJob, JobNames, context);
    }

    return { ...context };
  };

/**
 * @param {import('../../../actions/delete-table.js').deleteTable} deleteTable
 * @param {string} databaseName
 * @param {string[]} tableNames
 */
const deleteTables = (deleteTable, databaseName, tableNames) =>
  Promise.all(
    tableNames.map((tableName) =>
      deleteTable(databaseName, tableName).catch(console.error),
    ),
  );

/**
 * @param {{
 *  getTables: import('../../../actions/get-tables.js').getTables,
 *  deleteTable: import('../../../actions/delete-table.js').deleteTable
 * }} config
 */
const makeCleanUpTablesStep =
  ({ getTables, deleteTable }) =>
  /**
   * @param {{ prompter: { prompt: () => Promise<any>}}} context
   */
  async (context) => {
    const { TableList } = await getTables(process.env.DATABASE_NAME).catch(
      () => ({ TableList: null }),
    );

    if (TableList && TableList.length > 0) {
      /**
       * @type {{ tableNames: string[] }}
       */
      const { tableNames } = await context.prompter.prompt({
        name: "tableNames",
        type: "checkbox",
        message: "Let's clean up tables. Select tables to delete.",
        choices: TableList.map((t) => t.Name),
      });

      if (tableNames.length === 0) {
        log("No tables selected.");
      } else {
        log("Deleting tables.");
        await deleteTables(deleteTable, process.env.DATABASE_NAME, tableNames);
        log("Tables deleted.", { type: "success" });
      }
    }

    return { ...context };
  };

/**
 * @param {import('../../../actions/delete-database.js').deleteDatabase} deleteDatabase
 * @param {string[]} databaseNames
 */
const deleteDatabases = (deleteDatabase, databaseNames) =>
  Promise.all(
    databaseNames.map((dbName) => deleteDatabase(dbName).catch(console.error)),
  );

/**
 * @param {{
 *   getDatabases: import('../../../actions/get-databases.js').getDatabases
 *   deleteDatabase: import('../../../actions/delete-database.js').deleteDatabase
 * }} config
 */
const makeCleanUpDatabasesStep =
  ({ getDatabases, deleteDatabase }) =>
  /**
   * @param {{ prompter: { prompt: () => Promise<any>}} context
   */
  async (context) => {
    const { DatabaseList } = await getDatabases();

    if (DatabaseList.length > 0) {
      /** @type {{ dbNames: string[] }} */
      const { dbNames } = await context.prompter.prompt({
        name: "dbNames",
        type: "checkbox",
        message: "Let's clean up databases. Select databases to delete.",
        choices: DatabaseList.map((db) => db.Name),
      });

      if (dbNames.length === 0) {
        log("No databases selected.");
      } else {
        log("Deleting databases.");
        await deleteDatabases(deleteDatabase, dbNames);
        log("Databases deleted.", { type: "success" });
      }
    }

    return { ...context };
  };

const cleanUpCrawlerStep = async (context) => {
  log("Deleting crawler.");

  try {
    await deleteCrawler(process.env.CRAWLER_NAME);
    log("Crawler deleted.", { type: "success" });
  } catch (err) {
    if (err.name === "EntityNotFoundException") {
      log("Crawler is already deleted.");
    } else {
      throw err;
    }
  }

  return { ...context };
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/CreateCrawlerCommand)
  + [CreateJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/CreateJobCommand)
  + [DeleteCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteCrawlerCommand)
  + [DeleteDatabase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteDatabaseCommand)
  + [DeleteJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteJobCommand)
  + [DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteTableCommand)
  + [GetCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetCrawlerCommand)
  + [GetDatabase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetDatabaseCommand)
  + [GetDatabases](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetDatabasesCommand)
  + [GetJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetJobCommand)
  + [GetJobRun](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetJobRunCommand)
  + [GetJobRuns](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetJobRunsCommand)
  + [GetTables](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetTablesCommand)
  + [ListJobs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/ListJobsCommand)
  + [StartCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/StartCrawlerCommand)
  + [StartJobRun](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/StartJobRunCommand)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_javascript_3_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const createCrawler = (name, role, dbName, tablePrefix, s3TargetPath) => {
  const client = new GlueClient({});

  const command = new CreateCrawlerCommand({
    Name: name,
    Role: role,
    DatabaseName: dbName,
    TablePrefix: tablePrefix,
    Targets: {
      S3Targets: [{ Path: s3TargetPath }],
    },
  });

  return client.send(command);
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[CreateCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/CreateCrawlerCommand)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_javascript_3_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const createJob = (name, role, scriptBucketName, scriptKey) => {
  const client = new GlueClient({});

  const command = new CreateJobCommand({
    Name: name,
    Role: role,
    Command: {
      Name: "glueetl",
      PythonVersion: "3",
      ScriptLocation: `s3://${scriptBucketName}/${scriptKey}`,
    },
    GlueVersion: "3.0",
  });

  return client.send(command);
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[CreateJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/CreateJobCommand)」を参照してください。**

### `DeleteCrawler`
<a name="glue_DeleteCrawler_javascript_3_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const deleteCrawler = (crawlerName) => {
  const client = new GlueClient({});

  const command = new DeleteCrawlerCommand({
    Name: crawlerName,
  });

  return client.send(command);
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[DeleteCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteCrawlerCommand)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_javascript_3_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const deleteDatabase = (databaseName) => {
  const client = new GlueClient({});

  const command = new DeleteDatabaseCommand({
    Name: databaseName,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteDatabase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteDatabaseCommand)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_javascript_3_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const deleteJob = (jobName) => {
  const client = new GlueClient({});

  const command = new DeleteJobCommand({
    JobName: jobName,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteJobCommand)」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_javascript_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const deleteTable = (databaseName, tableName) => {
  const client = new GlueClient({});

  const command = new DeleteTableCommand({
    DatabaseName: databaseName,
    Name: tableName,
  });

  return client.send(command);
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/DeleteTableCommand)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_javascript_3_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const getCrawler = (name) => {
  const client = new GlueClient({});

  const command = new GetCrawlerCommand({
    Name: name,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetCrawlerCommand)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_javascript_3_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const getDatabase = (name) => {
  const client = new GlueClient({});

  const command = new GetDatabaseCommand({
    Name: name,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetDatabase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetDatabaseCommand)」を参照してください。

### `GetDatabases`
<a name="glue_GetDatabases_javascript_3_topic"></a>

次のコード例は、`GetDatabases` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const getDatabases = () => {
  const client = new GlueClient({});

  const command = new GetDatabasesCommand({});

  return client.send(command);
};
```
+  API の詳細については、「AWS SDK for JavaScript API リファレンス」の「[GetDatabases](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetDatabasesCommand)」を参照してください。

### `GetJob`
<a name="glue_GetJob_javascript_3_topic"></a>

次のコード例は、`GetJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const getJob = (jobName) => {
  const client = new GlueClient({});

  const command = new GetJobCommand({
    JobName: jobName,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetJobCommand)」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_javascript_3_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const getJobRun = (jobName, jobRunId) => {
  const client = new GlueClient({});
  const command = new GetJobRunCommand({
    JobName: jobName,
    RunId: jobRunId,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetJobRun](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetJobRunCommand)」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_javascript_3_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const getJobRuns = (jobName) => {
  const client = new GlueClient({});
  const command = new GetJobRunsCommand({
    JobName: jobName,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetJobRuns](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetJobRunsCommand)」を参照してください。

### `GetTables`
<a name="glue_GetTables_javascript_3_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const getTables = (databaseName) => {
  const client = new GlueClient({});

  const command = new GetTablesCommand({
    DatabaseName: databaseName,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetTables](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/GetTablesCommand)」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_javascript_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const listJobs = () => {
  const client = new GlueClient({});

  const command = new ListJobsCommand({});

  return client.send(command);
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/ListJobsCommand)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_javascript_3_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const startCrawler = (name) => {
  const client = new GlueClient({});

  const command = new StartCrawlerCommand({
    Name: name,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[StartCrawler](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/StartCrawlerCommand)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_javascript_3_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
const startJobRun = (jobName, dbName, tableName, bucketName) => {
  const client = new GlueClient({});

  const command = new StartJobRunCommand({
    JobName: jobName,
    Arguments: {
      "--input_database": dbName,
      "--input_table": tableName,
      "--output_bucket_url": `s3://${bucketName}/`,
    },
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[StartJobRun](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/glue/command/StartJobRunCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した HealthImaging の例
<a name="javascript_3_medical-imaging_code_examples"></a>

次のコード例は、HealthImaging で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello HealthImaging
<a name="medical-imaging_Hello_javascript_3_topic"></a>

次のコード例は、HealthImaging の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  

```
import {
  ListDatastoresCommand,
  MedicalImagingClient,
} from "@aws-sdk/client-medical-imaging";

// When no region or credentials are provided, the SDK will use the
// region and credentials from the local AWS config.
const client = new MedicalImagingClient({});

export const helloMedicalImaging = async () => {
  const command = new ListDatastoresCommand({});

  const { datastoreSummaries } = await client.send(command);
  console.log("Datastores: ");
  console.log(datastoreSummaries.map((item) => item.datastoreName).join("\n"));
  return datastoreSummaries;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListDatastores](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/ListDatastoresCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

## アクション
<a name="actions"></a>

### `CopyImageSet`
<a name="medical-imaging_CopyImageSet_javascript_3_topic"></a>

次のコード例は、`CopyImageSet` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
イメージセットをコピーするためのユーティリティ関数。  

```
import { CopyImageSetCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The ID of the data store.
 * @param {string} imageSetId - The source image set ID.
 * @param {string} sourceVersionId - The source version ID.
 * @param {string} destinationImageSetId - The optional ID of the destination image set.
 * @param {string} destinationVersionId - The optional version ID of the destination image set.
 * @param {boolean} force - Force the copy action.
 * @param {[string]} copySubsets - A subset of instance IDs to copy.
 */
export const copyImageSet = async (
  datastoreId = "xxxxxxxxxxx",
  imageSetId = "xxxxxxxxxxxx",
  sourceVersionId = "1",
  destinationImageSetId = "",
  destinationVersionId = "",
  force = false,
  copySubsets = [],
) => {
  try {
    const params = {
      datastoreId: datastoreId,
      sourceImageSetId: imageSetId,
      copyImageSetInformation: {
        sourceImageSet: { latestVersionId: sourceVersionId },
      },
      force: force,
    };
    if (destinationImageSetId !== "" && destinationVersionId !== "") {
      params.copyImageSetInformation.destinationImageSet = {
        imageSetId: destinationImageSetId,
        latestVersionId: destinationVersionId,
      };
    }

    if (copySubsets.length > 0) {
      let copySubsetsJson;
      copySubsetsJson = {
        SchemaVersion: 1.1,
        Study: {
          Series: {
            imageSetId: {
              Instances: {},
            },
          },
        },
      };

      for (let i = 0; i < copySubsets.length; i++) {
        copySubsetsJson.Study.Series.imageSetId.Instances[copySubsets[i]] = {};
      }

      params.copyImageSetInformation.dicomCopies = copySubsetsJson;
    }

    const response = await medicalImagingClient.send(
      new CopyImageSetCommand(params),
    );
    console.log(response);
    // {
    //     '$metadata': {
    //         httpStatusCode: 200,
    //         requestId: 'd9b219ce-cc48-4a44-a5b2-c5c3068f1ee8',
    //         extendedRequestId: undefined,
    //         cfId: undefined,
    //         attempts: 1,
    //         totalRetryDelay: 0
    //      },
    //       datastoreId: 'xxxxxxxxxxxxxx',
    //       destinationImageSetProperties: {
    //             createdAt: 2023-09-27T19:46:21.824Z,
    //             imageSetArn: 'arn:aws:medical-imaging:us-east-1:xxxxxxxxxxx:datastore/xxxxxxxxxxxxx/imageset/xxxxxxxxxxxxxxxxxxx',
    //             imageSetId: 'xxxxxxxxxxxxxxx',
    //             imageSetState: 'LOCKED',
    //             imageSetWorkflowStatus: 'COPYING',
    //             latestVersionId: '1',
    //             updatedAt: 2023-09-27T19:46:21.824Z
    //       },
    //       sourceImageSetProperties: {
    //             createdAt: 2023-09-22T14:49:26.427Z,
    //             imageSetArn: 'arn:aws:medical-imaging:us-east-1:xxxxxxxxxxx:datastore/xxxxxxxxxxxxx/imageset/xxxxxxxxxxxxxxxx',
    //             imageSetId: 'xxxxxxxxxxxxxxxx',
    //             imageSetState: 'LOCKED',
    //             imageSetWorkflowStatus: 'COPYING_WITH_READ_ONLY_ACCESS',
    //             latestVersionId: '4',
    //             updatedAt: 2023-09-27T19:46:21.824Z
    //      }
    // }
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
コピー先を指定せずにイメージセットをコピーします。  

```
  await copyImageSet(
    "12345678901234567890123456789012",
    "12345678901234567890123456789012",
    "1",
  );
```
コピー先を指定してイメージセットをコピーします。  

```
  await copyImageSet(
    "12345678901234567890123456789012",
    "12345678901234567890123456789012",
    "1",
    "12345678901234567890123456789012",
    "1",
    false,
  );
```
イメージセットのサブセットを送信先にコピーし、コピーを強制します。  

```
  await copyImageSet(
    "12345678901234567890123456789012",
    "12345678901234567890123456789012",
    "1",
    "12345678901234567890123456789012",
    "1",
    true,
    ["12345678901234567890123456789012", "11223344556677889900112233445566"],
  );
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の[CopyImageSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/CopyImageSetCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `CreateDatastore`
<a name="medical-imaging_CreateDatastore_javascript_3_topic"></a>

次のコード例は、`CreateDatastore` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { CreateDatastoreCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreName - The name of the data store to create.
 */
export const createDatastore = async (datastoreName = "DATASTORE_NAME") => {
  const response = await medicalImagingClient.send(
    new CreateDatastoreCommand({ datastoreName: datastoreName }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //       httpStatusCode: 200,
  //       requestId: 'a71cd65f-2382-49bf-b682-f9209d8d399b',
  //       extendedRequestId: undefined,
  //       cfId: undefined,
  //       attempts: 1,
  //       totalRetryDelay: 0
  //    },
  //    datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //    datastoreStatus: 'CREATING'
  // }
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateDatastore](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/CreateDatastoreCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `DeleteDatastore`
<a name="medical-imaging_DeleteDatastore_javascript_3_topic"></a>

次のコード例は、`DeleteDatastore` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { DeleteDatastoreCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The ID of the data store to delete.
 */
export const deleteDatastore = async (datastoreId = "DATASTORE_ID") => {
  const response = await medicalImagingClient.send(
    new DeleteDatastoreCommand({ datastoreId }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //           httpStatusCode: 200,
  //           requestId: 'f5beb409-678d-48c9-9173-9a001ee1ebb1',
  //           extendedRequestId: undefined,
  //           cfId: undefined,
  //           attempts: 1,
  //           totalRetryDelay: 0
  //        },
  //     datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //     datastoreStatus: 'DELETING'
  // }

  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteDatastore](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/DeleteDatastoreCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `DeleteImageSet`
<a name="medical-imaging_DeleteImageSet_javascript_3_topic"></a>

次のコード例は、`DeleteImageSet` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { DeleteImageSetCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The data store ID.
 * @param {string} imageSetId - The image set ID.
 */
export const deleteImageSet = async (
  datastoreId = "xxxxxxxxxxxxxxxx",
  imageSetId = "xxxxxxxxxxxxxxxx",
) => {
  const response = await medicalImagingClient.send(
    new DeleteImageSetCommand({
      datastoreId: datastoreId,
      imageSetId: imageSetId,
    }),
  );
  console.log(response);
  // {
  //    '$metadata': {
  //         httpStatusCode: 200,
  //         requestId: '6267bbd2-eaa5-4a50-8ee8-8fddf535cf73',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //     },
  //     datastoreId: 'xxxxxxxxxxxxxxxx',
  //     imageSetId: 'xxxxxxxxxxxxxxx',
  //     imageSetState: 'LOCKED',
  //     imageSetWorkflowStatus: 'DELETING'
  // }
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteImageSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/DeleteImageSetCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetDICOMImportJob`
<a name="medical-imaging_GetDICOMImportJob_javascript_3_topic"></a>

次のコード例は、`GetDICOMImportJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { GetDICOMImportJobCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The ID of the data store.
 * @param {string} jobId - The ID of the import job.
 */
export const getDICOMImportJob = async (
  datastoreId = "xxxxxxxxxxxxxxxxxxxx",
  jobId = "xxxxxxxxxxxxxxxxxxxx",
) => {
  const response = await medicalImagingClient.send(
    new GetDICOMImportJobCommand({ datastoreId: datastoreId, jobId: jobId }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //     httpStatusCode: 200,
  //         requestId: 'a2637936-78ea-44e7-98b8-7a87d95dfaee',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  // },
  //     jobProperties: {
  //         dataAccessRoleArn: 'arn:aws:iam::xxxxxxxxxxxx:role/dicom_import',
  //             datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
  //             endedAt: 2023-09-19T17:29:21.753Z,
  //             inputS3Uri: 's3://healthimaging-source/CTStudy/',
  //             jobId: ''xxxxxxxxxxxxxxxxxxxxxxxxx'',
  //             jobName: 'job_1',
  //             jobStatus: 'COMPLETED',
  //             outputS3Uri: 's3://health-imaging-dest/ouput_ct/'xxxxxxxxxxxxxxxxxxxxxxxxx'-DicomImport-'xxxxxxxxxxxxxxxxxxxxxxxxx'/',
  //             submittedAt: 2023-09-19T17:27:25.143Z
  //     }
  // }

  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetDICOMImportJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetDICOMImportJobCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetDatastore`
<a name="medical-imaging_GetDatastore_javascript_3_topic"></a>

次のコード例は、`GetDatastore` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { GetDatastoreCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreID - The ID of the data store.
 */
export const getDatastore = async (datastoreID = "DATASTORE_ID") => {
  const response = await medicalImagingClient.send(
    new GetDatastoreCommand({ datastoreId: datastoreID }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //       httpStatusCode: 200,
  //       requestId: '55ea7d2e-222c-4a6a-871e-4f591f40cadb',
  //       extendedRequestId: undefined,
  //       cfId: undefined,
  //       attempts: 1,
  //       totalRetryDelay: 0
  //    },
  //   datastoreProperties: {
  //        createdAt: 2023-08-04T18:50:36.239Z,
  //         datastoreArn: 'arn:aws:medical-imaging:us-east-1:xxxxxxxxx:datastore/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //         datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //         datastoreName: 'my_datastore',
  //         datastoreStatus: 'ACTIVE',
  //         updatedAt: 2023-08-04T18:50:36.239Z
  //   }
  // }
  return response.datastoreProperties;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetDatastore](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetDatastoreCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageFrame`
<a name="medical-imaging_GetImageFrame_javascript_3_topic"></a>

次のコード例は、`GetImageFrame` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { GetImageFrameCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} imageFrameFileName - The name of the file for the HTJ2K-encoded image frame.
 * @param {string} datastoreID - The data store's ID.
 * @param {string} imageSetID - The image set's ID.
 * @param {string} imageFrameID - The image frame's ID.
 */
export const getImageFrame = async (
  imageFrameFileName = "image.jph",
  datastoreID = "DATASTORE_ID",
  imageSetID = "IMAGE_SET_ID",
  imageFrameID = "IMAGE_FRAME_ID",
) => {
  const response = await medicalImagingClient.send(
    new GetImageFrameCommand({
      datastoreId: datastoreID,
      imageSetId: imageSetID,
      imageFrameInformation: { imageFrameId: imageFrameID },
    }),
  );
  const buffer = await response.imageFrameBlob.transformToByteArray();
  writeFileSync(imageFrameFileName, buffer);

  console.log(response);
  // {
  //     '$metadata': {
  //         httpStatusCode: 200,
  //         requestId: 'e4ab42a5-25a3-4377-873f-374ecf4380e1',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //     },
  //     contentType: 'application/octet-stream',
  //     imageFrameBlob: <ref *1> IncomingMessage {}
  // }
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetImageFrame](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetImageFrameCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageSet`
<a name="medical-imaging_GetImageSet_javascript_3_topic"></a>

次のコード例は、`GetImageSet` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { GetImageSetCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The ID of the data store.
 * @param {string} imageSetId - The ID of the image set.
 * @param {string} imageSetVersion - The optional version of the image set.
 *
 */
export const getImageSet = async (
  datastoreId = "xxxxxxxxxxxxxxx",
  imageSetId = "xxxxxxxxxxxxxxx",
  imageSetVersion = "",
) => {
  const params = { datastoreId: datastoreId, imageSetId: imageSetId };
  if (imageSetVersion !== "") {
    params.imageSetVersion = imageSetVersion;
  }
  const response = await medicalImagingClient.send(
    new GetImageSetCommand(params),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //     httpStatusCode: 200,
  //         requestId: '0615c161-410d-4d06-9d8c-6e1241bb0a5a',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  // },
  //     createdAt: 2023-09-22T14:49:26.427Z,
  //     datastoreId: 'xxxxxxxxxxxxxxx',
  //     imageSetArn: 'arn:aws:medical-imaging:us-east-1:xxxxxxxxxx:datastore/xxxxxxxxxxxxxxxxxxxx/imageset/xxxxxxxxxxxxxxxxxxxx',
  //     imageSetId: 'xxxxxxxxxxxxxxx',
  //     imageSetState: 'ACTIVE',
  //     imageSetWorkflowStatus: 'CREATED',
  //     updatedAt: 2023-09-22T14:49:26.427Z,
  //     versionId: '1'
  // }

  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetImageSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetImageSetCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageSetMetadata`
<a name="medical-imaging_GetImageSetMetadata_javascript_3_topic"></a>

次のコード例は、`GetImageSetMetadata` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
イメージセットのメタデータを取得するためのユーティリティ関数。  

```
import { GetImageSetMetadataCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";
import { writeFileSync } from "node:fs";

/**
 * @param {string} metadataFileName - The name of the file for the gzipped metadata.
 * @param {string} datastoreId - The ID of the data store.
 * @param {string} imagesetId - The ID of the image set.
 * @param {string} versionID - The optional version ID of the image set.
 */
export const getImageSetMetadata = async (
  metadataFileName = "metadata.json.gzip",
  datastoreId = "xxxxxxxxxxxxxx",
  imagesetId = "xxxxxxxxxxxxxx",
  versionID = "",
) => {
  const params = { datastoreId: datastoreId, imageSetId: imagesetId };

  if (versionID) {
    params.versionID = versionID;
  }

  const response = await medicalImagingClient.send(
    new GetImageSetMetadataCommand(params),
  );
  const buffer = await response.imageSetMetadataBlob.transformToByteArray();
  writeFileSync(metadataFileName, buffer);

  console.log(response);
  // {
  //     '$metadata': {
  //     httpStatusCode: 200,
  //         requestId: '5219b274-30ff-4986-8cab-48753de3a599',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  // },
  //     contentType: 'application/json',
  //     contentEncoding: 'gzip',
  //     imageSetMetadataBlob: <ref *1> IncomingMessage {}
  // }

  return response;
};
```
イメージセットのメタデータをバージョンなしで取得します。  

```
  try {
    await getImageSetMetadata(
      "metadata.json.gzip",
      "12345678901234567890123456789012",
      "12345678901234567890123456789012",
    );
  } catch (err) {
    console.log("Error", err);
  }
```
イメージセットのメタデータをバージョン付きで取得します。  

```
  try {
    await getImageSetMetadata(
      "metadata2.json.gzip",
      "12345678901234567890123456789012",
      "12345678901234567890123456789012",
      "1",
    );
  } catch (err) {
    console.log("Error", err);
  }
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetImageSetMetadata](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetImageSetMetadataCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListDICOMImportJobs`
<a name="medical-imaging_ListDICOMImportJobs_javascript_3_topic"></a>

次のコード例は、`ListDICOMImportJobs` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { paginateListDICOMImportJobs } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The ID of the data store.
 */
export const listDICOMImportJobs = async (
  datastoreId = "xxxxxxxxxxxxxxxxxx",
) => {
  const paginatorConfig = {
    client: medicalImagingClient,
    pageSize: 50,
  };

  const commandParams = { datastoreId: datastoreId };
  const paginator = paginateListDICOMImportJobs(paginatorConfig, commandParams);

  const jobSummaries = [];
  for await (const page of paginator) {
    // Each page contains a list of `jobSummaries`. The list is truncated if is larger than `pageSize`.
    jobSummaries.push(...page.jobSummaries);
    console.log(page);
  }
  // {
  //     '$metadata': {
  //     httpStatusCode: 200,
  //         requestId: '3c20c66e-0797-446a-a1d8-91b742fd15a0',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  // },
  //     jobSummaries: [
  //         {
  //             dataAccessRoleArn: 'arn:aws:iam::xxxxxxxxxxxx:role/dicom_import',
  //             datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
  //             endedAt: 2023-09-22T14:49:51.351Z,
  //             jobId: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
  //             jobName: 'test-1',
  //             jobStatus: 'COMPLETED',
  //             submittedAt: 2023-09-22T14:48:45.767Z
  // }
  // ]}

  return jobSummaries;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListDICOMImportJobs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/ListDICOMImportJobsCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListDatastores`
<a name="medical-imaging_ListDatastores_javascript_3_topic"></a>

次のコード例は、`ListDatastores` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { paginateListDatastores } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

export const listDatastores = async () => {
  const paginatorConfig = {
    client: medicalImagingClient,
    pageSize: 50,
  };

  const commandParams = {};
  const paginator = paginateListDatastores(paginatorConfig, commandParams);

  /**
   * @type {import("@aws-sdk/client-medical-imaging").DatastoreSummary[]}
   */
  const datastoreSummaries = [];
  for await (const page of paginator) {
    // Each page contains a list of `jobSummaries`. The list is truncated if is larger than `pageSize`.
    datastoreSummaries.push(...page.datastoreSummaries);
    console.log(page);
  }
  // {
  //   '$metadata': {
  //       httpStatusCode: 200,
  //       requestId: '6aa99231-d9c2-4716-a46e-edb830116fa3',
  //       extendedRequestId: undefined,
  //       cfId: undefined,
  //       attempts: 1,
  //       totalRetryDelay: 0
  //   },
  //   datastoreSummaries: [
  //     {
  //       createdAt: 2023-08-04T18:49:54.429Z,
  //       datastoreArn: 'arn:aws:medical-imaging:us-east-1:xxxxxxxxx:datastore/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //       datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //       datastoreName: 'my_datastore',
  //       datastoreStatus: 'ACTIVE',
  //       updatedAt: 2023-08-04T18:49:54.429Z
  //     }
  //     ...
  //   ]
  // }

  return datastoreSummaries;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListDatastores](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/ListDatastoresCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListImageSetVersions`
<a name="medical-imaging_ListImageSetVersions_javascript_3_topic"></a>

次のコード例は、`ListImageSetVersions` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { paginateListImageSetVersions } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The ID of the data store.
 * @param {string} imageSetId - The ID of the image set.
 */
export const listImageSetVersions = async (
  datastoreId = "xxxxxxxxxxxx",
  imageSetId = "xxxxxxxxxxxx",
) => {
  const paginatorConfig = {
    client: medicalImagingClient,
    pageSize: 50,
  };

  const commandParams = { datastoreId, imageSetId };
  const paginator = paginateListImageSetVersions(
    paginatorConfig,
    commandParams,
  );

  const imageSetPropertiesList = [];
  for await (const page of paginator) {
    // Each page contains a list of `jobSummaries`. The list is truncated if is larger than `pageSize`.
    imageSetPropertiesList.push(...page.imageSetPropertiesList);
    console.log(page);
  }
  // {
  //     '$metadata': {
  //         httpStatusCode: 200,
  //         requestId: '74590b37-a002-4827-83f2-3c590279c742',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //     },
  //     imageSetPropertiesList: [
  //         {
  //             ImageSetWorkflowStatus: 'CREATED',
  //             createdAt: 2023-09-22T14:49:26.427Z,
  //             imageSetId: 'xxxxxxxxxxxxxxxxxxxxxxx',
  //             imageSetState: 'ACTIVE',
  //             versionId: '1'
  //         }]
  // }
  return imageSetPropertiesList;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListImageSetVersions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/ListImageSetVersionsCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListTagsForResource`
<a name="medical-imaging_ListTagsForResource_javascript_3_topic"></a>

次のコード例は、`ListTagsForResource` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { ListTagsForResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 */
export const listTagsForResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:abc:datastore/def/imageset/ghi",
) => {
  const response = await medicalImagingClient.send(
    new ListTagsForResourceCommand({ resourceArn: resourceArn }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //         httpStatusCode: 200,
  //         requestId: '008fc6d3-abec-4870-a155-20fa3631e645',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //     },
  //     tags: { Deployment: 'Development' }
  // }

  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListTagsForResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/ListTagsForResourceCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `SearchImageSets`
<a name="medical-imaging_SearchImageSets_javascript_3_topic"></a>

次のコード例は、`SearchImageSets` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
画像セットを検索するためのユーティリティ関数。  

```
import { paginateSearchImageSets } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The data store's ID.
 * @param { import('@aws-sdk/client-medical-imaging').SearchFilter[] } filters - The search criteria filters.
 * @param { import('@aws-sdk/client-medical-imaging').Sort } sort - The search criteria sort.
 */
export const searchImageSets = async (
  datastoreId = "xxxxxxxx",
  searchCriteria = {},
) => {
  const paginatorConfig = {
    client: medicalImagingClient,
    pageSize: 50,
  };

  const commandParams = {
    datastoreId: datastoreId,
    searchCriteria: searchCriteria,
  };

  const paginator = paginateSearchImageSets(paginatorConfig, commandParams);

  const imageSetsMetadataSummaries = [];
  for await (const page of paginator) {
    // Each page contains a list of `jobSummaries`. The list is truncated if is larger than `pageSize`.
    imageSetsMetadataSummaries.push(...page.imageSetsMetadataSummaries);
    console.log(page);
  }
  // {
  //     '$metadata': {
  //         httpStatusCode: 200,
  //         requestId: 'f009ea9c-84ca-4749-b5b6-7164f00a5ada',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //     },
  //     imageSetsMetadataSummaries: [
  //         {
  //             DICOMTags: [Object],
  //             createdAt: "2023-09-19T16:59:40.551Z",
  //             imageSetId: '7f75e1b5c0f40eac2b24cf712f485f50',
  //             updatedAt: "2023-09-19T16:59:40.551Z",
  //             version: 1
  //         }]
  // }

  return imageSetsMetadataSummaries;
};
```
ユースケース \$11: EQUAL 演算子。  

```
  const datastoreId = "12345678901234567890123456789012";

  try {
    const searchCriteria = {
      filters: [
        {
          values: [{ DICOMPatientId: "1234567" }],
          operator: "EQUAL",
        },
      ],
    };

    await searchImageSets(datastoreId, searchCriteria);
  } catch (err) {
    console.error(err);
  }
```
ユースケース \$12: DICOMStudyDate と DICOMStudyTime を使用する BETWEEN 演算子。  

```
  const datastoreId = "12345678901234567890123456789012";

  try {
    const searchCriteria = {
      filters: [
        {
          values: [
            {
              DICOMStudyDateAndTime: {
                DICOMStudyDate: "19900101",
                DICOMStudyTime: "000000",
              },
            },
            {
              DICOMStudyDateAndTime: {
                DICOMStudyDate: "20230901",
                DICOMStudyTime: "000000",
              },
            },
          ],
          operator: "BETWEEN",
        },
      ],
    };

    await searchImageSets(datastoreId, searchCriteria);
  } catch (err) {
    console.error(err);
  }
```
ユースケース \$13: createdAt を使用する BETWEEN 演算子。タイムスタディは以前に永続化されています。  

```
  const datastoreId = "12345678901234567890123456789012";

  try {
    const searchCriteria = {
      filters: [
        {
          values: [
            { createdAt: new Date("1985-04-12T23:20:50.52Z") },
            { createdAt: new Date() },
          ],
          operator: "BETWEEN",
        },
      ],
    };

    await searchImageSets(datastoreId, searchCriteria);
  } catch (err) {
    console.error(err);
  }
```
ユースケース 4: DICOMSeriesInstanceUID で EQUAL 演算子を使用し、updatedAt で BETWEEN 演算子を使用して、updatedAt フィールドで ASC 順序にレスポンスをソートします。  

```
  const datastoreId = "12345678901234567890123456789012";

  try {
    const searchCriteria = {
      filters: [
        {
          values: [
            { updatedAt: new Date("1985-04-12T23:20:50.52Z") },
            { updatedAt: new Date() },
          ],
          operator: "BETWEEN",
        },
        {
          values: [
            {
              DICOMSeriesInstanceUID:
                "1.1.123.123456.1.12.1.1234567890.1234.12345678.123",
            },
          ],
          operator: "EQUAL",
        },
      ],
      sort: {
        sortOrder: "ASC",
        sortField: "updatedAt",
      },
    };

    await searchImageSets(datastoreId, searchCriteria);
  } catch (err) {
    console.error(err);
  }
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SearchImageSets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/SearchImageSetsCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `StartDICOMImportJob`
<a name="medical-imaging_StartDICOMImportJob_javascript_3_topic"></a>

次のコード例は、`StartDICOMImportJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { StartDICOMImportJobCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} jobName - The name of the import job.
 * @param {string} datastoreId - The ID of the data store.
 * @param {string} dataAccessRoleArn - The Amazon Resource Name (ARN) of the role that grants permission.
 * @param {string} inputS3Uri - The URI of the S3 bucket containing the input files.
 * @param {string} outputS3Uri - The URI of the S3 bucket where the output files are stored.
 */
export const startDicomImportJob = async (
  jobName = "test-1",
  datastoreId = "12345678901234567890123456789012",
  dataAccessRoleArn = "arn:aws:iam::xxxxxxxxxxxx:role/ImportJobDataAccessRole",
  inputS3Uri = "s3://medical-imaging-dicom-input/dicom_input/",
  outputS3Uri = "s3://medical-imaging-output/job_output/",
) => {
  const response = await medicalImagingClient.send(
    new StartDICOMImportJobCommand({
      jobName: jobName,
      datastoreId: datastoreId,
      dataAccessRoleArn: dataAccessRoleArn,
      inputS3Uri: inputS3Uri,
      outputS3Uri: outputS3Uri,
    }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //     httpStatusCode: 200,
  //         requestId: '6e81d191-d46b-4e48-a08a-cdcc7e11eb79',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  // },
  //     datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //     jobId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
  //     jobStatus: 'SUBMITTED',
  //     submittedAt: 2023-09-22T14:48:45.767Z
  // }
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[StartDICOMImportJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/StartDICOMImportJobCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `TagResource`
<a name="medical-imaging_TagResource_javascript_3_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { TagResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 * @param {Record<string,string>} tags - The tags to add to the resource as JSON.
 *                     - For example: {"Deployment" : "Development"}
 */
export const tagResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:xxxxxx:datastore/xxxxx/imageset/xxx",
  tags = {},
) => {
  const response = await medicalImagingClient.send(
    new TagResourceCommand({ resourceArn: resourceArn, tags: tags }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //        httpStatusCode: 204,
  //         requestId: '8a6de9a3-ec8e-47ef-8643-473518b19d45',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //    }
  // }

  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[TagResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/TagResourceCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `UntagResource`
<a name="medical-imaging_UntagResource_javascript_3_topic"></a>

次のコード例は、`UntagResource` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { UntagResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 * @param {string[]} tagKeys - The keys of the tags to remove.
 */
export const untagResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:xxxxxx:datastore/xxxxx/imageset/xxx",
  tagKeys = [],
) => {
  const response = await medicalImagingClient.send(
    new UntagResourceCommand({ resourceArn: resourceArn, tagKeys: tagKeys }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //        httpStatusCode: 204,
  //         requestId: '8a6de9a3-ec8e-47ef-8643-473518b19d45',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //    }
  // }

  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[UntagResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/UntagResourceCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `UpdateImageSetMetadata`
<a name="medical-imaging_UpdateImageSetMetadata_javascript_3_topic"></a>

次のコード例は、`UpdateImageSetMetadata` を使用する方法を示しています。

**SDK for JavaScript (v3)**  

```
import { UpdateImageSetMetadataCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} datastoreId - The ID of the HealthImaging data store.
 * @param {string} imageSetId - The ID of the HealthImaging image set.
 * @param {string} latestVersionId - The ID of the HealthImaging image set version.
 * @param {{}} updateMetadata - The metadata to update.
 * @param {boolean} force - Force the update.
 */
export const updateImageSetMetadata = async (
  datastoreId = "xxxxxxxxxx",
  imageSetId = "xxxxxxxxxx",
  latestVersionId = "1",
  updateMetadata = "{}",
  force = false,
) => {
  try {
    const response = await medicalImagingClient.send(
      new UpdateImageSetMetadataCommand({
        datastoreId: datastoreId,
        imageSetId: imageSetId,
        latestVersionId: latestVersionId,
        updateImageSetMetadataUpdates: updateMetadata,
        force: force,
      }),
    );
    console.log(response);
    // {
    //     '$metadata': {
    //     httpStatusCode: 200,
    //         requestId: '7966e869-e311-4bff-92ec-56a61d3003ea',
    //         extendedRequestId: undefined,
    //         cfId: undefined,
    //         attempts: 1,
    //         totalRetryDelay: 0
    // },
    //     createdAt: 2023-09-22T14:49:26.427Z,
    //     datastoreId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    //     imageSetId: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
    //     imageSetState: 'LOCKED',
    //     imageSetWorkflowStatus: 'UPDATING',
    //     latestVersionId: '4',
    //     updatedAt: 2023-09-27T19:41:43.494Z
    // }
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
ユースケース 1: 属性を挿入または更新し、強制的に更新します。  

```
    const insertAttributes = JSON.stringify({
      SchemaVersion: 1.1,
      Study: {
        DICOM: {
          StudyDescription: "CT CHEST",
        },
      },
    });

    const updateMetadata = {
      DICOMUpdates: {
        updatableAttributes: new TextEncoder().encode(insertAttributes),
      },
    };

    await updateImageSetMetadata(
      datastoreID,
      imageSetID,
      versionID,
      updateMetadata,
      true,
    );
```
ユースケース 2: 属性を削除します。  

```
    // Attribute key and value must match the existing attribute.
    const remove_attribute = JSON.stringify({
      SchemaVersion: 1.1,
      Study: {
        DICOM: {
          StudyDescription: "CT CHEST",
        },
      },
    });

    const updateMetadata = {
      DICOMUpdates: {
        removableAttributes: new TextEncoder().encode(remove_attribute),
      },
    };

    await updateImageSetMetadata(
      datastoreID,
      imageSetID,
      versionID,
      updateMetadata,
    );
```
ユースケース 3: インスタンスを削除します。  

```
    const remove_instance = JSON.stringify({
      SchemaVersion: 1.1,
      Study: {
        Series: {
          "1.1.1.1.1.1.12345.123456789012.123.12345678901234.1": {
            Instances: {
              "1.1.1.1.1.1.12345.123456789012.123.12345678901234.1": {},
            },
          },
        },
      },
    });

    const updateMetadata = {
      DICOMUpdates: {
        removableAttributes: new TextEncoder().encode(remove_instance),
      },
    };

    await updateImageSetMetadata(
      datastoreID,
      imageSetID,
      versionID,
      updateMetadata,
    );
```
ユースケース 4: 以前のバージョンに戻します。  

```
    const updateMetadata = {
      revertToVersionId: "1",
    };

    await updateImageSetMetadata(
      datastoreID,
      imageSetID,
      versionID,
      updateMetadata,
    );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[UpdateImageSetMetadata](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/UpdateImageSetMetadataCommand)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

## シナリオ
<a name="scenarios"></a>

### 画像セットと画像フレームを使い始める
<a name="medical-imaging_Scenario_ImageSetsAndFrames_javascript_3_topic"></a>

次のコード例は、HealthImaging で DICOM ファイルをインポートし、画像フレームをダウンロードする方法を示しています。

実装はコマンドラインアプリケーションとして構造化されています。
+ DICOM インポート用にリソースをセットアップします。
+ DICOM ファイルをデータストアへのインポート。
+ インポートジョブの画像セット ID の取得。
+ インポートジョブの画像フレーム ID の取得。
+ イメージフレームをダウンロード、デコード、および検証します。
+ リソースをクリーンアップします。

**SDK for JavaScript (v3)**  
ステップをオーケストレーションします (index.js)。  

```
import {
  parseScenarioArgs,
  Scenario,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import {
  saveState,
  loadState,
} from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";

import {
  createStack,
  deployStack,
  getAccountId,
  getDatastoreName,
  getStackName,
  outputState,
  waitForStackCreation,
} from "./deploy-steps.js";
import {
  doCopy,
  selectDataset,
  copyDataset,
  outputCopiedObjects,
} from "./dataset-steps.js";
import {
  doImport,
  outputImportJobStatus,
  startDICOMImport,
  waitForImportJobCompletion,
} from "./import-steps.js";
import {
  getManifestFile,
  outputImageSetIds,
  parseManifestFile,
} from "./image-set-steps.js";
import {
  getImageSetMetadata,
  outputImageFrameIds,
} from "./image-frame-steps.js";
import { decodeAndVerifyImages, doVerify } from "./verify-steps.js";
import {
  confirmCleanup,
  deleteImageSets,
  deleteStack,
} from "./clean-up-steps.js";

const context = {};

const scenarios = {
  deploy: new Scenario(
    "Deploy Resources",
    [
      deployStack,
      getStackName,
      getDatastoreName,
      getAccountId,
      createStack,
      waitForStackCreation,
      outputState,
      saveState,
    ],
    context,
  ),
  demo: new Scenario(
    "Run Demo",
    [
      loadState,
      doCopy,
      selectDataset,
      copyDataset,
      outputCopiedObjects,
      doImport,
      startDICOMImport,
      waitForImportJobCompletion,
      outputImportJobStatus,
      getManifestFile,
      parseManifestFile,
      outputImageSetIds,
      getImageSetMetadata,
      outputImageFrameIds,
      doVerify,
      decodeAndVerifyImages,
      saveState,
    ],
    context,
  ),
  destroy: new Scenario(
    "Clean Up Resources",
    [loadState, confirmCleanup, deleteImageSets, deleteStack],
    context,
  ),
};

// Call function if run directly
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  parseScenarioArgs(scenarios, {
    name: "Health Imaging Workflow",
    description:
      "Work with DICOM images using an AWS Health Imaging data store.",
    synopsis:
      "node index.js --scenario <deploy | demo | destroy> [-h|--help] [-y|--yes] [-v|--verbose]",
  });
}
```
リソースをデプロイします (deploy-steps.js)。  

```
import fs from "node:fs/promises";
import path from "node:path";

import {
  CloudFormationClient,
  CreateStackCommand,
  DescribeStacksCommand,
} from "@aws-sdk/client-cloudformation";
import { STSClient, GetCallerIdentityCommand } from "@aws-sdk/client-sts";

import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

const cfnClient = new CloudFormationClient({});
const stsClient = new STSClient({});

const __dirname = path.dirname(new URL(import.meta.url).pathname);
const cfnTemplatePath = path.join(
  __dirname,
  "../../../../../scenarios/features/healthimaging_image_sets/resources/cfn_template.yaml",
);

export const deployStack = new ScenarioInput(
  "deployStack",
  "Do you want to deploy the CloudFormation stack?",
  { type: "confirm" },
);

export const getStackName = new ScenarioInput(
  "getStackName",
  "Enter a name for the CloudFormation stack:",
  { type: "input", skipWhen: (/** @type {{}} */ state) => !state.deployStack },
);

export const getDatastoreName = new ScenarioInput(
  "getDatastoreName",
  "Enter a name for the HealthImaging datastore:",
  { type: "input", skipWhen: (/** @type {{}} */ state) => !state.deployStack },
);

export const getAccountId = new ScenarioAction(
  "getAccountId",
  async (/** @type {{}} */ state) => {
    const command = new GetCallerIdentityCommand({});
    const response = await stsClient.send(command);
    state.accountId = response.Account;
  },
  {
    skipWhen: (/** @type {{}} */ state) => !state.deployStack,
  },
);

export const createStack = new ScenarioAction(
  "createStack",
  async (/** @type {{}} */ state) => {
    const stackName = state.getStackName;
    const datastoreName = state.getDatastoreName;
    const accountId = state.accountId;

    const command = new CreateStackCommand({
      StackName: stackName,
      TemplateBody: await fs.readFile(cfnTemplatePath, "utf8"),
      Capabilities: ["CAPABILITY_IAM"],
      Parameters: [
        {
          ParameterKey: "datastoreName",
          ParameterValue: datastoreName,
        },
        {
          ParameterKey: "userAccountID",
          ParameterValue: accountId,
        },
      ],
    });

    const response = await cfnClient.send(command);
    state.stackId = response.StackId;
  },
  { skipWhen: (/** @type {{}} */ state) => !state.deployStack },
);

export const waitForStackCreation = new ScenarioAction(
  "waitForStackCreation",
  async (/** @type {{}} */ state) => {
    const command = new DescribeStacksCommand({
      StackName: state.stackId,
    });

    await retry({ intervalInMs: 10000, maxRetries: 60 }, async () => {
      const response = await cfnClient.send(command);
      const stack = response.Stacks?.find(
        (s) => s.StackName === state.getStackName,
      );
      if (!stack || stack.StackStatus === "CREATE_IN_PROGRESS") {
        throw new Error("Stack creation is still in progress");
      }
      if (stack.StackStatus === "CREATE_COMPLETE") {
        state.stackOutputs = stack.Outputs?.reduce((acc, output) => {
          acc[output.OutputKey] = output.OutputValue;
          return acc;
        }, {});
      } else {
        throw new Error(
          `Stack creation failed with status: ${stack.StackStatus}`,
        );
      }
    });
  },
  {
    skipWhen: (/** @type {{}} */ state) => !state.deployStack,
  },
);

export const outputState = new ScenarioOutput(
  "outputState",
  (/** @type {{}} */ state) => {
    /**
     * @type {{ stackOutputs: { DatastoreID: string, BucketName: string, RoleArn: string }}}
     */
    const { stackOutputs } = state;
    return `Stack creation completed. Output values:
Datastore ID: ${stackOutputs?.DatastoreID}
Bucket Name: ${stackOutputs?.BucketName}
Role ARN: ${stackOutputs?.RoleArn}
    `;
  },
  { skipWhen: (/** @type {{}} */ state) => !state.deployStack },
);
```
DICOM ファイルをコピーします (dataset-steps.js)。  

```
import {
  S3Client,
  CopyObjectCommand,
  ListObjectsV2Command,
} from "@aws-sdk/client-s3";

import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

const s3Client = new S3Client({});

const datasetOptions = [
  {
    name: "CT of chest (2 images)",
    value: "00029d25-fb18-4d42-aaa5-a0897d1ac8f7",
  },
  {
    name: "CT of pelvis (57 images)",
    value: "00025d30-ef8f-4135-a35a-d83eff264fc1",
  },
  {
    name: "MRI of head (192 images)",
    value: "0002d261-8a5d-4e63-8e2e-0cbfac87b904",
  },
  {
    name: "MRI of breast (92 images)",
    value: "0002dd07-0b7f-4a68-a655-44461ca34096",
  },
];

/**
 * @typedef {{ stackOutputs: {
 *   BucketName: string,
 *   DatastoreID: string,
 *   doCopy: boolean
 * }}} State
 */

export const selectDataset = new ScenarioInput(
  "selectDataset",
  (state) => {
    if (!state.doCopy) {
      process.exit(0);
    }
    return "Select a DICOM dataset to import:";
  },
  {
    type: "select",
    choices: datasetOptions,
  },
);

export const doCopy = new ScenarioInput(
  "doCopy",
  "Do you want to copy images from the public dataset into your bucket?",
  {
    type: "confirm",
  },
);

export const copyDataset = new ScenarioAction(
  "copyDataset",
  async (/** @type { State } */ state) => {
    const inputBucket = state.stackOutputs.BucketName;
    const inputPrefix = "input/";
    const selectedDatasetId = state.selectDataset;

    const sourceBucket = "idc-open-data";
    const sourcePrefix = `${selectedDatasetId}`;

    const listObjectsCommand = new ListObjectsV2Command({
      Bucket: sourceBucket,
      Prefix: sourcePrefix,
    });

    const objects = await s3Client.send(listObjectsCommand);

    const copyPromises = objects.Contents.map((object) => {
      const sourceKey = object.Key;
      const destinationKey = `${inputPrefix}${sourceKey
        .split("/")
        .slice(1)
        .join("/")}`;

      const copyCommand = new CopyObjectCommand({
        Bucket: inputBucket,
        CopySource: `/${sourceBucket}/${sourceKey}`,
        Key: destinationKey,
      });

      return s3Client.send(copyCommand);
    });

    const results = await Promise.all(copyPromises);
    state.copiedObjects = results.length;
  },
);

export const outputCopiedObjects = new ScenarioOutput(
  "outputCopiedObjects",
  (state) => `${state.copiedObjects} DICOM files were copied.`,
);
```
データストアへのインポートを開始します (import-steps.js)。  

```
import {
  MedicalImagingClient,
  StartDICOMImportJobCommand,
  GetDICOMImportJobCommand,
} from "@aws-sdk/client-medical-imaging";

import {
  ScenarioAction,
  ScenarioOutput,
  ScenarioInput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

/**
 * @typedef {{ stackOutputs: {
 *   BucketName: string,
 *   DatastoreID: string,
 *   RoleArn: string
 * }}} State
 */

export const doImport = new ScenarioInput(
  "doImport",
  "Do you want to import DICOM images into your datastore?",
  {
    type: "confirm",
    default: true,
  },
);

export const startDICOMImport = new ScenarioAction(
  "startDICOMImport",
  async (/** @type {State} */ state) => {
    if (!state.doImport) {
      process.exit(0);
    }
    const medicalImagingClient = new MedicalImagingClient({});
    const inputS3Uri = `s3://${state.stackOutputs.BucketName}/input/`;
    const outputS3Uri = `s3://${state.stackOutputs.BucketName}/output/`;

    const command = new StartDICOMImportJobCommand({
      dataAccessRoleArn: state.stackOutputs.RoleArn,
      datastoreId: state.stackOutputs.DatastoreID,
      inputS3Uri,
      outputS3Uri,
    });

    const response = await medicalImagingClient.send(command);
    state.importJobId = response.jobId;
  },
);

export const waitForImportJobCompletion = new ScenarioAction(
  "waitForImportJobCompletion",
  async (/** @type {State} */ state) => {
    const medicalImagingClient = new MedicalImagingClient({});
    const command = new GetDICOMImportJobCommand({
      datastoreId: state.stackOutputs.DatastoreID,
      jobId: state.importJobId,
    });

    await retry({ intervalInMs: 10000, maxRetries: 60 }, async () => {
      const response = await medicalImagingClient.send(command);
      const jobStatus = response.jobProperties?.jobStatus;
      if (!jobStatus || jobStatus === "IN_PROGRESS") {
        throw new Error("Import job is still in progress");
      }
      if (jobStatus === "COMPLETED") {
        state.importJobOutputS3Uri = response.jobProperties.outputS3Uri;
      } else {
        throw new Error(`Import job failed with status: ${jobStatus}`);
      }
    });
  },
);

export const outputImportJobStatus = new ScenarioOutput(
  "outputImportJobStatus",
  (state) =>
    `DICOM import job completed. Output location: ${state.importJobOutputS3Uri}`,
);
```
画像セット ID を取得します (image-set-steps.js - )。  

```
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";

import {
  ScenarioAction,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

/**
 * @typedef {{ stackOutputs: {
 *   BucketName: string,
 *   DatastoreID: string,
 *   RoleArn: string
 * }, importJobId: string,
 * importJobOutputS3Uri: string,
 * imageSetIds: string[],
 * manifestContent: { jobSummary: { imageSetsSummary: { imageSetId: string }[] } }
 * }} State
 */

const s3Client = new S3Client({});

export const getManifestFile = new ScenarioAction(
  "getManifestFile",
  async (/** @type {State} */ state) => {
    const bucket = state.stackOutputs.BucketName;
    const prefix = `output/${state.stackOutputs.DatastoreID}-DicomImport-${state.importJobId}/`;
    const key = `${prefix}job-output-manifest.json`;

    const command = new GetObjectCommand({
      Bucket: bucket,
      Key: key,
    });

    const response = await s3Client.send(command);
    const manifestContent = await response.Body.transformToString();
    state.manifestContent = JSON.parse(manifestContent);
  },
);

export const parseManifestFile = new ScenarioAction(
  "parseManifestFile",
  (/** @type {State} */ state) => {
    const imageSetIds =
      state.manifestContent.jobSummary.imageSetsSummary.reduce((ids, next) => {
        return Object.assign({}, ids, {
          [next.imageSetId]: next.imageSetId,
        });
      }, {});
    state.imageSetIds = Object.keys(imageSetIds);
  },
);

export const outputImageSetIds = new ScenarioOutput(
  "outputImageSetIds",
  (/** @type {State} */ state) =>
    `The image sets created by this import job are: \n${state.imageSetIds
      .map((id) => `Image set: ${id}`)
      .join("\n")}`,
);
```
画像フレーム ID を取得します (image-frame-steps.js)。  

```
import {
  MedicalImagingClient,
  GetImageSetMetadataCommand,
} from "@aws-sdk/client-medical-imaging";
import { gunzip } from "node:zlib";
import { promisify } from "node:util";

import {
  ScenarioAction,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

const gunzipAsync = promisify(gunzip);

/**
 * @typedef {Object} DICOMValueRepresentation
 * @property {string} name
 * @property {string} type
 * @property {string} value
 */

/**
 * @typedef {Object} ImageFrameInformation
 * @property {string} ID
 * @property {Array<{ Checksum: number, Height: number, Width: number }>} PixelDataChecksumFromBaseToFullResolution
 * @property {number} MinPixelValue
 * @property {number} MaxPixelValue
 * @property {number} FrameSizeInBytes
 */

/**
 * @typedef {Object} DICOMMetadata
 * @property {Object} DICOM
 * @property {DICOMValueRepresentation[]} DICOMVRs
 * @property {ImageFrameInformation[]} ImageFrames
 */

/**
 * @typedef {Object} Series
 * @property {{ [key: string]: DICOMMetadata }} Instances
 */

/**
 * @typedef {Object} Study
 * @property {Object} DICOM
 * @property {Series[]} Series
 */

/**
 * @typedef {Object} Patient
 * @property {Object} DICOM
 */

/**
 * @typedef {{
 *  SchemaVersion: string,
 *  DatastoreID: string,
 *  ImageSetID: string,
 *  Patient: Patient,
 *  Study: Study
 * }} ImageSetMetadata
 */

/**
 * @typedef {{ stackOutputs: {
 *   BucketName: string,
 *   DatastoreID: string,
 *   RoleArn: string
 * }, imageSetIds: string[] }} State
 */

const medicalImagingClient = new MedicalImagingClient({});

export const getImageSetMetadata = new ScenarioAction(
  "getImageSetMetadata",
  async (/** @type {State} */ state) => {
    const outputMetadata = [];

    for (const imageSetId of state.imageSetIds) {
      const command = new GetImageSetMetadataCommand({
        datastoreId: state.stackOutputs.DatastoreID,
        imageSetId,
      });

      const response = await medicalImagingClient.send(command);
      const compressedMetadataBlob =
        await response.imageSetMetadataBlob.transformToByteArray();
      const decompressedMetadata = await gunzipAsync(compressedMetadataBlob);
      const imageSetMetadata = JSON.parse(decompressedMetadata.toString());

      outputMetadata.push(imageSetMetadata);
    }

    state.imageSetMetadata = outputMetadata;
  },
);

export const outputImageFrameIds = new ScenarioOutput(
  "outputImageFrameIds",
  (/** @type {State & { imageSetMetadata: ImageSetMetadata[] }} */ state) => {
    let output = "";

    for (const metadata of state.imageSetMetadata) {
      const imageSetId = metadata.ImageSetID;
      /** @type {DICOMMetadata[]} */
      const instances = Object.values(metadata.Study.Series).flatMap(
        (series) => {
          return Object.values(series.Instances);
        },
      );
      const imageFrameIds = instances.flatMap((instance) =>
        instance.ImageFrames.map((frame) => frame.ID),
      );

      output += `Image set ID: ${imageSetId}\nImage frame IDs:\n${imageFrameIds.join(
        "\n",
      )}\n\n`;
    }

    return output;
  },
);
```
画像フレームを確認します (verify-steps.js)。[AWS HealthImaging Pixel データ検証](https://github.com/aws-samples/aws-healthimaging-samples/tree/main/pixel-data-verification)ライブラリが検証に使用されました。  

```
import { spawn } from "node:child_process";

import {
  ScenarioAction,
  ScenarioInput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

/**
 * @typedef {Object} DICOMValueRepresentation
 * @property {string} name
 * @property {string} type
 * @property {string} value
 */

/**
 * @typedef {Object} ImageFrameInformation
 * @property {string} ID
 * @property {Array<{ Checksum: number, Height: number, Width: number }>} PixelDataChecksumFromBaseToFullResolution
 * @property {number} MinPixelValue
 * @property {number} MaxPixelValue
 * @property {number} FrameSizeInBytes
 */

/**
 * @typedef {Object} DICOMMetadata
 * @property {Object} DICOM
 * @property {DICOMValueRepresentation[]} DICOMVRs
 * @property {ImageFrameInformation[]} ImageFrames
 */

/**
 * @typedef {Object} Series
 * @property {{ [key: string]: DICOMMetadata }} Instances
 */

/**
 * @typedef {Object} Study
 * @property {Object} DICOM
 * @property {Series[]} Series
 */

/**
 * @typedef {Object} Patient
 * @property {Object} DICOM
 */

/**
 * @typedef {{
 *  SchemaVersion: string,
 *  DatastoreID: string,
 *  ImageSetID: string,
 *  Patient: Patient,
 *  Study: Study
 * }} ImageSetMetadata
 */

/**
 * @typedef {{ stackOutputs: {
 *   BucketName: string,
 *   DatastoreID: string,
 *   RoleArn: string
 * }, imageSetMetadata: ImageSetMetadata[] }} State
 */

export const doVerify = new ScenarioInput(
  "doVerify",
  "Do you want to verify the imported images?",
  {
    type: "confirm",
    default: true,
  },
);

export const decodeAndVerifyImages = new ScenarioAction(
  "decodeAndVerifyImages",
  async (/** @type {State} */ state) => {
    if (!state.doVerify) {
      process.exit(0);
    }
    const verificationTool = "./pixel-data-verification/index.js";

    for (const metadata of state.imageSetMetadata) {
      const datastoreId = state.stackOutputs.DatastoreID;
      const imageSetId = metadata.ImageSetID;

      for (const [seriesInstanceUid, series] of Object.entries(
        metadata.Study.Series,
      )) {
        for (const [sopInstanceUid, _] of Object.entries(series.Instances)) {
          console.log(
            `Verifying image set ${imageSetId} with series ${seriesInstanceUid} and sop ${sopInstanceUid}`,
          );
          const child = spawn(
            "node",
            [
              verificationTool,
              datastoreId,
              imageSetId,
              seriesInstanceUid,
              sopInstanceUid,
            ],
            { stdio: "inherit" },
          );

          await new Promise((resolve, reject) => {
            child.on("exit", (code) => {
              if (code === 0) {
                resolve();
              } else {
                reject(
                  new Error(
                    `Verification tool exited with code ${code} for image set ${imageSetId}`,
                  ),
                );
              }
            });
          });
        }
      }
    }
  },
);
```
リソースを破壊します (clean-up-steps.js)。  

```
import {
  CloudFormationClient,
  DeleteStackCommand,
} from "@aws-sdk/client-cloudformation";
import {
  MedicalImagingClient,
  DeleteImageSetCommand,
} from "@aws-sdk/client-medical-imaging";

import {
  ScenarioAction,
  ScenarioInput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

/**
 * @typedef {Object} DICOMValueRepresentation
 * @property {string} name
 * @property {string} type
 * @property {string} value
 */

/**
 * @typedef {Object} ImageFrameInformation
 * @property {string} ID
 * @property {Array<{ Checksum: number, Height: number, Width: number }>} PixelDataChecksumFromBaseToFullResolution
 * @property {number} MinPixelValue
 * @property {number} MaxPixelValue
 * @property {number} FrameSizeInBytes
 */

/**
 * @typedef {Object} DICOMMetadata
 * @property {Object} DICOM
 * @property {DICOMValueRepresentation[]} DICOMVRs
 * @property {ImageFrameInformation[]} ImageFrames
 */

/**
 * @typedef {Object} Series
 * @property {{ [key: string]: DICOMMetadata }} Instances
 */

/**
 * @typedef {Object} Study
 * @property {Object} DICOM
 * @property {Series[]} Series
 */

/**
 * @typedef {Object} Patient
 * @property {Object} DICOM
 */

/**
 * @typedef {{
 *  SchemaVersion: string,
 *  DatastoreID: string,
 *  ImageSetID: string,
 *  Patient: Patient,
 *  Study: Study
 * }} ImageSetMetadata
 */

/**
 * @typedef {{ stackOutputs: {
 *   BucketName: string,
 *   DatastoreID: string,
 *   RoleArn: string
 * }, imageSetMetadata: ImageSetMetadata[] }} State
 */

const cfnClient = new CloudFormationClient({});
const medicalImagingClient = new MedicalImagingClient({});

export const confirmCleanup = new ScenarioInput(
  "confirmCleanup",
  "Do you want to delete the created resources?",
  { type: "confirm" },
);

export const deleteImageSets = new ScenarioAction(
  "deleteImageSets",
  async (/** @type {State} */ state) => {
    const datastoreId = state.stackOutputs.DatastoreID;

    for (const metadata of state.imageSetMetadata) {
      const command = new DeleteImageSetCommand({
        datastoreId,
        imageSetId: metadata.ImageSetID,
      });

      try {
        await medicalImagingClient.send(command);
        console.log(`Successfully deleted image set ${metadata.ImageSetID}`);
      } catch (e) {
        if (e instanceof Error) {
          if (e.name === "ConflictException") {
            console.log(`Image set ${metadata.ImageSetID} already deleted`);
          }
        }
      }
    }
  },
  {
    skipWhen: (/** @type {{}} */ state) => !state.confirmCleanup,
  },
);

export const deleteStack = new ScenarioAction(
  "deleteStack",
  async (/** @type {State} */ state) => {
    const stackName = state.getStackName;

    const command = new DeleteStackCommand({
      StackName: stackName,
    });

    await cfnClient.send(command);
    console.log(`Stack ${stackName} deletion initiated`);
  },
  {
    skipWhen: (/** @type {{}} */ state) => !state.confirmCleanup,
  },
);
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [DeleteImageSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/DeleteImageSetCommand)
  + [GetDICOMImportJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetDICOMImportJobCommand)
  + [GetImageFrame](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetImageFrameCommand)
  + [GetImageSetMetadata](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/GetImageSetMetadataCommand)
  + [SearchImageSets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/SearchImageSetsCommand)
  + [StartDICOMImportJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/StartDICOMImportJobCommand)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### データストアにタグを付ける
<a name="medical-imaging_Scenario_TaggingDataStores_javascript_3_topic"></a>

次のコード例は、HealthImaging データストアにタグを付ける方法を示しています。

**SDK for JavaScript (v3)**  
データストアにタグを付けるには  

```
  try {
    const datastoreArn =
      "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012";
    const tags = {
      Deployment: "Development",
    };
    await tagResource(datastoreArn, tags);
  } catch (e) {
    console.log(e);
  }
```
リソースにタグを付けるためのユーティリティ関数。  

```
import { TagResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 * @param {Record<string,string>} tags - The tags to add to the resource as JSON.
 *                     - For example: {"Deployment" : "Development"}
 */
export const tagResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:xxxxxx:datastore/xxxxx/imageset/xxx",
  tags = {},
) => {
  const response = await medicalImagingClient.send(
    new TagResourceCommand({ resourceArn: resourceArn, tags: tags }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //        httpStatusCode: 204,
  //         requestId: '8a6de9a3-ec8e-47ef-8643-473518b19d45',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //    }
  // }

  return response;
};
```
データストアのタグを一覧表示します。  

```
  try {
    const datastoreArn =
      "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012";
    const { tags } = await listTagsForResource(datastoreArn);
    console.log(tags);
  } catch (e) {
    console.log(e);
  }
```
リソースのタグを一覧表示するユーティリティ関数。  

```
import { ListTagsForResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 */
export const listTagsForResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:abc:datastore/def/imageset/ghi",
) => {
  const response = await medicalImagingClient.send(
    new ListTagsForResourceCommand({ resourceArn: resourceArn }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //         httpStatusCode: 200,
  //         requestId: '008fc6d3-abec-4870-a155-20fa3631e645',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //     },
  //     tags: { Deployment: 'Development' }
  // }

  return response;
};
```
データストアのタグを解除するには  

```
  try {
    const datastoreArn =
      "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012";
    const keys = ["Deployment"];
    await untagResource(datastoreArn, keys);
  } catch (e) {
    console.log(e);
  }
```
リソースのタグを解除するユーティリティ関数。  

```
import { UntagResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 * @param {string[]} tagKeys - The keys of the tags to remove.
 */
export const untagResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:xxxxxx:datastore/xxxxx/imageset/xxx",
  tagKeys = [],
) => {
  const response = await medicalImagingClient.send(
    new UntagResourceCommand({ resourceArn: resourceArn, tagKeys: tagKeys }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //        httpStatusCode: 204,
  //         requestId: '8a6de9a3-ec8e-47ef-8643-473518b19d45',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //    }
  // }

  return response;
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [ListTagsForResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/ListTagsForResourceCommand)
  + [TagResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/TagResourceCommand)
  + [UntagResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/UntagResourceCommand)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### イメージセットにタグを付ける
<a name="medical-imaging_Scenario_TaggingImageSets_javascript_3_topic"></a>

次のコード例は、HealthImaging イメージセットにタグを付ける方法を示しています。

**SDK for JavaScript (v3)**  
イメージセットにタグを付けるには  

```
  try {
    const imagesetArn =
      "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012";
    const tags = {
      Deployment: "Development",
    };
    await tagResource(imagesetArn, tags);
  } catch (e) {
    console.log(e);
  }
```
リソースにタグを付けるためのユーティリティ関数。  

```
import { TagResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 * @param {Record<string,string>} tags - The tags to add to the resource as JSON.
 *                     - For example: {"Deployment" : "Development"}
 */
export const tagResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:xxxxxx:datastore/xxxxx/imageset/xxx",
  tags = {},
) => {
  const response = await medicalImagingClient.send(
    new TagResourceCommand({ resourceArn: resourceArn, tags: tags }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //        httpStatusCode: 204,
  //         requestId: '8a6de9a3-ec8e-47ef-8643-473518b19d45',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //    }
  // }

  return response;
};
```
イメージセットのタグを一覧表示します。  

```
  try {
    const imagesetArn =
      "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012";
    const { tags } = await listTagsForResource(imagesetArn);
    console.log(tags);
  } catch (e) {
    console.log(e);
  }
```
リソースのタグを一覧表示するユーティリティ関数。  

```
import { ListTagsForResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 */
export const listTagsForResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:abc:datastore/def/imageset/ghi",
) => {
  const response = await medicalImagingClient.send(
    new ListTagsForResourceCommand({ resourceArn: resourceArn }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //         httpStatusCode: 200,
  //         requestId: '008fc6d3-abec-4870-a155-20fa3631e645',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //     },
  //     tags: { Deployment: 'Development' }
  // }

  return response;
};
```
イメージセットのタグを解除します。  

```
  try {
    const imagesetArn =
      "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012";
    const keys = ["Deployment"];
    await untagResource(imagesetArn, keys);
  } catch (e) {
    console.log(e);
  }
```
リソースのタグを解除するユーティリティ関数。  

```
import { UntagResourceCommand } from "@aws-sdk/client-medical-imaging";
import { medicalImagingClient } from "../libs/medicalImagingClient.js";

/**
 * @param {string} resourceArn - The Amazon Resource Name (ARN) for the data store or image set.
 * @param {string[]} tagKeys - The keys of the tags to remove.
 */
export const untagResource = async (
  resourceArn = "arn:aws:medical-imaging:us-east-1:xxxxxx:datastore/xxxxx/imageset/xxx",
  tagKeys = [],
) => {
  const response = await medicalImagingClient.send(
    new UntagResourceCommand({ resourceArn: resourceArn, tagKeys: tagKeys }),
  );
  console.log(response);
  // {
  //     '$metadata': {
  //        httpStatusCode: 204,
  //         requestId: '8a6de9a3-ec8e-47ef-8643-473518b19d45',
  //         extendedRequestId: undefined,
  //         cfId: undefined,
  //         attempts: 1,
  //         totalRetryDelay: 0
  //    }
  // }

  return response;
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [ListTagsForResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/ListTagsForResourceCommand)
  + [TagResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/TagResourceCommand)
  + [UntagResource](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/medical-imaging/command/UntagResourceCommand)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

# SDK for JavaScript (v3) を使用した IAM の例
<a name="javascript_3_iam_code_examples"></a>

次のコード例は、IAM で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_javascript_3_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { IAMClient, paginateListPolicies } from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const listLocalPolicies = async () => {
  /**
   * In v3, the clients expose paginateOperationName APIs that are written using async generators so that you can use async iterators in a for await..of loop.
   * https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators
   */
  const paginator = paginateListPolicies(
    { client, pageSize: 10 },
    // List only customer managed policies.
    { Scope: "Local" },
  );

  console.log("IAM policies defined in your account:");
  let policyCount = 0;
  for await (const page of paginator) {
    if (page.Policies) {
      for (const policy of page.Policies) {
        console.log(`${policy.PolicyName}`);
        policyCount++;
      }
    }
  }
  console.log(`Found ${policyCount} policies.`);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListPoliciesCommand)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_javascript_3_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーと、Amazon S3 バケットを一覧表示するアクセス権限を付与するロールを作成します。ユーザーには、ロールの引き受けのみ権限があります。ロールを引き受けた後、一時的な認証情報を使用してアカウントのバケットを一覧表示します。  

```
import {
  CreateUserCommand,
  GetUserCommand,
  CreateAccessKeyCommand,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  DeleteAccessKeyCommand,
  DeleteUserCommand,
  DeleteRoleCommand,
  DeletePolicyCommand,
  DetachRolePolicyCommand,
  IAMClient,
} from "@aws-sdk/client-iam";
import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3";
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario/index.js";

// Set the parameters.
const iamClient = new IAMClient({});
const userName = "iam_basic_test_username";
const policyName = "iam_basic_test_policy";
const roleName = "iam_basic_test_role";

/**
 * Create a new IAM user. If the user already exists, give
 * the option to delete and re-create it.
 * @param {string} name
 */
export const createUser = async (name, confirmAll = false) => {
  try {
    const { User } = await iamClient.send(
      new GetUserCommand({ UserName: name }),
    );
    const input = new ScenarioInput(
      "deleteUser",
      "Do you want to delete and remake this user?",
      { type: "confirm" },
    );
    const deleteUser = await input.handle({}, { confirmAll });
    // If the user exists, and you want to delete it, delete the user
    // and then create it again.
    if (deleteUser) {
      await iamClient.send(new DeleteUserCommand({ UserName: User.UserName }));
      await iamClient.send(new CreateUserCommand({ UserName: name }));
    } else {
      console.warn(
        `${name} already exists. The scenario may not work as expected.`,
      );
      return User;
    }
  } catch (caught) {
    // If there is no user by that name, create one.
    if (caught instanceof Error && caught.name === "NoSuchEntityException") {
      const { User } = await iamClient.send(
        new CreateUserCommand({ UserName: name }),
      );
      return User;
    }
    throw caught;
  }
};

export const main = async (confirmAll = false) => {
  // Create a user. The user has no permissions by default.
  const User = await createUser(userName, confirmAll);

  if (!User) {
    throw new Error("User not created");
  }

  // Create an access key. This key is used to authenticate the new user to
  // Amazon Simple Storage Service (Amazon S3) and AWS Security Token Service (AWS STS).
  // It's not best practice to use access keys. For more information, see https://aws.amazon.com/iam/resources/best-practices/.
  const createAccessKeyResponse = await iamClient.send(
    new CreateAccessKeyCommand({ UserName: userName }),
  );

  if (
    !createAccessKeyResponse.AccessKey?.AccessKeyId ||
    !createAccessKeyResponse.AccessKey?.SecretAccessKey
  ) {
    throw new Error("Access key not created");
  }

  const {
    AccessKey: { AccessKeyId, SecretAccessKey },
  } = createAccessKeyResponse;

  let s3Client = new S3Client({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the list buckets operation until it succeeds. InvalidAccessKeyId is
  // thrown while the user and access keys are still stabilizing.
  await retry({ intervalInMs: 1000, maxRetries: 300 }, async () => {
    try {
      return await listBuckets(s3Client);
    } catch (err) {
      if (err instanceof Error && err.name === "InvalidAccessKeyId") {
        throw err;
      }
    }
  });

  // Retry the create role operation until it succeeds. A MalformedPolicyDocument error
  // is thrown while the user and access keys are still stabilizing.
  const { Role } = await retry(
    {
      intervalInMs: 2000,
      maxRetries: 60,
    },
    () =>
      iamClient.send(
        new CreateRoleCommand({
          AssumeRolePolicyDocument: JSON.stringify({
            Version: "2012-10-17",
            Statement: [
              {
                Effect: "Allow",
                Principal: {
                  // Allow the previously created user to assume this role.
                  AWS: User.Arn,
                },
                Action: "sts:AssumeRole",
              },
            ],
          }),
          RoleName: roleName,
        }),
      ),
  );

  if (!Role) {
    throw new Error("Role not created");
  }

  // Create a policy that allows the user to list S3 buckets.
  const { Policy: listBucketPolicy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Action: ["s3:ListAllMyBuckets"],
            Resource: "*",
          },
        ],
      }),
      PolicyName: policyName,
    }),
  );

  if (!listBucketPolicy) {
    throw new Error("Policy not created");
  }

  // Attach the policy granting the 's3:ListAllMyBuckets' action to the role.
  await iamClient.send(
    new AttachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  // Assume the role.
  const stsClient = new STSClient({
    credentials: {
      accessKeyId: AccessKeyId,
      secretAccessKey: SecretAccessKey,
    },
  });

  // Retry the assume role operation until it succeeds.
  const { Credentials } = await retry(
    { intervalInMs: 2000, maxRetries: 60 },
    () =>
      stsClient.send(
        new AssumeRoleCommand({
          RoleArn: Role.Arn,
          RoleSessionName: `iamBasicScenarioSession-${Math.floor(
            Math.random() * 1000000,
          )}`,
          DurationSeconds: 900,
        }),
      ),
  );

  if (!Credentials?.AccessKeyId || !Credentials?.SecretAccessKey) {
    throw new Error("Credentials not created");
  }

  s3Client = new S3Client({
    credentials: {
      accessKeyId: Credentials.AccessKeyId,
      secretAccessKey: Credentials.SecretAccessKey,
      sessionToken: Credentials.SessionToken,
    },
  });

  // List the S3 buckets again.
  // Retry the list buckets operation until it succeeds. AccessDenied might
  // be thrown while the role policy is still stabilizing.
  await retry({ intervalInMs: 2000, maxRetries: 120 }, () =>
    listBuckets(s3Client),
  );

  // Clean up.
  await iamClient.send(
    new DetachRolePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeletePolicyCommand({
      PolicyArn: listBucketPolicy.Arn,
    }),
  );

  await iamClient.send(
    new DeleteRoleCommand({
      RoleName: Role.RoleName,
    }),
  );

  await iamClient.send(
    new DeleteAccessKeyCommand({
      UserName: userName,
      AccessKeyId,
    }),
  );

  await iamClient.send(
    new DeleteUserCommand({
      UserName: userName,
    }),
  );
};

/**
 *
 * @param {S3Client} s3Client
 */
const listBuckets = async (s3Client) => {
  const { Buckets } = await s3Client.send(new ListBucketsCommand({}));

  if (!Buckets) {
    throw new Error("Buckets not listed");
  }

  console.log(Buckets.map((bucket) => bucket.Name).join("\n"));
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/AttachRolePolicyCommand)
  + [CreateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccessKeyCommand)
  + [CreatePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreatePolicyCommand)
  + [CreateRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)
  + [CreateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateUserCommand)
  + [DeleteAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccessKeyCommand)
  + [DeletePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeletePolicyCommand)
  + [DeleteRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRoleCommand)
  + [DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserCommand)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserPolicyCommand)
  + [DetachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DetachRolePolicyCommand)
  + [PutUserPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/PutUserPolicyCommand)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_javascript_3_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ポリシーをアタッチします。  

```
import { AttachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 * @param {string} roleName
 */
export const attachRolePolicy = (policyArn, roleName) => {
  const command = new AttachRolePolicyCommand({
    PolicyArn: policyArn,
    RoleName: roleName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-attaching-role-policy)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AttachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/AttachRolePolicyCommand)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_javascript_3_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アクセスキーを作成します。  

```
import { CreateAccessKeyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} userName
 */
export const createAccessKey = (userName) => {
  const command = new CreateAccessKeyCommand({ UserName: userName });
  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-creating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccessKeyCommand)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_javascript_3_topic"></a>

次のコード例は、`CreateAccountAlias` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アカウントエイリアスを作成します。  

```
import { CreateAccountAliasCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} alias - A unique name for the account alias.
 * @returns
 */
export const createAccountAlias = (alias) => {
  const command = new CreateAccountAliasCommand({
    AccountAlias: alias,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-creating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateAccountAlias](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateAccountAliasCommand)」を参照してください。

### `CreateGroup`
<a name="iam_CreateGroup_javascript_3_topic"></a>

次のコード例は、`CreateGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { CreateGroupCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} groupName
 */
export const createGroup = async (groupName) => {
  const command = new CreateGroupCommand({ GroupName: groupName });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateGroupCommand)」を参照してください。

### `CreateInstanceProfile`
<a name="iam_CreateInstanceProfile_javascript_3_topic"></a>

次のコード例は、`CreateInstanceProfile` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
  const { InstanceProfile } = await iamClient.send(
    new CreateInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
    }),
  );
  await waitUntilInstanceProfileExists(
    { client: iamClient },
    { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName },
  );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateInstanceProfileCommand)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_javascript_3_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ポリシーを作成します。  

```
import { CreatePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyName
 */
export const createPolicy = (policyName) => {
  const command = new CreatePolicyCommand({
    PolicyDocument: JSON.stringify({
      Version: "2012-10-17",
      Statement: [
        {
          Effect: "Allow",
          Action: "*",
          Resource: "*",
        },
      ],
    }),
    PolicyName: policyName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-creating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreatePolicyCommand)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_javascript_3_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ロールを作成します。  

```
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](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateRoleCommand)」を参照してください。

### `CreateSAMLProvider`
<a name="iam_CreateSAMLProvider_javascript_3_topic"></a>

次のコード例は、`CreateSAMLProvider` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { CreateSAMLProviderCommand, IAMClient } from "@aws-sdk/client-iam";
import { readFileSync } from "node:fs";
import * as path from "node:path";
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";

const client = new IAMClient({});

/**
 * This sample document was generated using Auth0.
 * For more information on generating this document, see https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html#samlstep1.
 */
const sampleMetadataDocument = readFileSync(
  path.join(
    dirnameFromMetaUrl(import.meta.url),
    "../../../../resources/sample_files/sample_saml_metadata.xml",
  ),
);

/**
 *
 * @param {*} providerName
 * @returns
 */
export const createSAMLProvider = async (providerName) => {
  const command = new CreateSAMLProviderCommand({
    Name: providerName,
    SAMLMetadataDocument: sampleMetadataDocument.toString(),
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateSAMLProvider](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateSAMLProviderCommand)」を参照してください。

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_javascript_3_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
サービスにリンクされたロールを作成します。  

```
import {
  CreateServiceLinkedRoleCommand,
  GetRoleCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} serviceName
 */
export const createServiceLinkedRole = async (serviceName) => {
  const command = new CreateServiceLinkedRoleCommand({
    // For a list of AWS services that support service-linked roles,
    // see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html.
    //
    // For a list of AWS service endpoints, see https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html.
    AWSServiceName: serviceName,
  });
  try {
    const response = await client.send(command);
    console.log(response);
    return response;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "InvalidInputException" &&
      caught.message.includes(
        "Service role name AWSServiceRoleForElasticBeanstalk has been taken in this account",
      )
    ) {
      console.warn(caught.message);
      return client.send(
        new GetRoleCommand({ RoleName: "AWSServiceRoleForElasticBeanstalk" }),
      );
    }
    throw caught;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateServiceLinkedRoleCommand)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_javascript_3_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ユーザーを作成します。  

```
import { CreateUserCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} name
 */
export const createUser = (name) => {
  const command = new CreateUserCommand({ UserName: name });
  return client.send(command);
};
```
+  詳細については、「AWS SDK for JavaScript デベロッパーガイド」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateUserCommand)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_javascript_3_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アクセスキーを削除します  

```
import { DeleteAccessKeyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} userName
 * @param {string} accessKeyId
 */
export const deleteAccessKey = (userName, accessKeyId) => {
  const command = new DeleteAccessKeyCommand({
    AccessKeyId: accessKeyId,
    UserName: userName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccessKeyCommand)」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_javascript_3_topic"></a>

次のコード例は、`DeleteAccountAlias` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アカウントエイリアスを削除します。  

```
import { DeleteAccountAliasCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} alias
 */
export const deleteAccountAlias = (alias) => {
  const command = new DeleteAccountAliasCommand({ AccountAlias: alias });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteAccountAlias](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteAccountAliasCommand)」を参照してください。

### `DeleteGroup`
<a name="iam_DeleteGroup_javascript_3_topic"></a>

次のコード例は、`DeleteGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteGroupCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} groupName
 */
export const deleteGroup = async (groupName) => {
  const command = new DeleteGroupCommand({
    GroupName: groupName,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、「AWS SDK for JavaScript API リファレンス」の「[DeleteGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteGroupCommand)」を参照してください。

### `DeleteInstanceProfile`
<a name="iam_DeleteInstanceProfile_javascript_3_topic"></a>

次のコード例は、`DeleteInstanceProfile` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。

```
      const client = new IAMClient({});
      await client.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteInstanceProfileCommand)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_javascript_3_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam/#code-examples)での設定と実行の方法を確認してください。
ポリシーを削除します。  

```
import { DeletePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 */
export const deletePolicy = (policyArn) => {
  const command = new DeletePolicyCommand({ PolicyArn: policyArn });
  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeletePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeletePolicyCommand)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_javascript_3_topic"></a>

次のコード例は、`DeleteRole` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ロールを削除します。  

```
import { DeleteRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const deleteRole = (roleName) => {
  const command = new DeleteRoleCommand({ RoleName: roleName });
  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRoleCommand)」を参照してください。

### `DeleteRolePolicy`
<a name="iam_DeleteRolePolicy_javascript_3_topic"></a>

次のコード例は、`DeleteRolePolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 * @param {string} policyName
 */
export const deleteRolePolicy = (roleName, policyName) => {
  const command = new DeleteRolePolicyCommand({
    RoleName: roleName,
    PolicyName: policyName,
  });
  return client.send(command);
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteRolePolicyCommand)」を参照してください。

### `DeleteSAMLProvider`
<a name="iam_DeleteSAMLProvider_javascript_3_topic"></a>

次のコード例は、`DeleteSAMLProvider` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteSAMLProviderCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} providerArn
 * @returns
 */
export const deleteSAMLProvider = async (providerArn) => {
  const command = new DeleteSAMLProviderCommand({
    SAMLProviderArn: providerArn,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteSAMLProvider](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteSAMLProviderCommand)」を参照してください。

### `DeleteServerCertificate`
<a name="iam_DeleteServerCertificate_javascript_3_topic"></a>

次のコード例は、`DeleteServerCertificate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
サーバー証明書を削除します。  

```
import { DeleteServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} certName
 */
export const deleteServerCertificate = (certName) => {
  const command = new DeleteServerCertificateCommand({
    ServerCertificateName: certName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-deleting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteServerCertificateCommand)」を参照してください。

### `DeleteServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_javascript_3_topic"></a>

次のコード例は、`DeleteServiceLinkedRole` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteServiceLinkedRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const deleteServiceLinkedRole = (roleName) => {
  const command = new DeleteServiceLinkedRoleCommand({ RoleName: roleName });
  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteServiceLinkedRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteServiceLinkedRoleCommand)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_javascript_3_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ユーザーを削除します。  

```
import { DeleteUserCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} name
 */
export const deleteUser = (name) => {
  const command = new DeleteUserCommand({ UserName: name });
  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-deleting-users)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteUserCommand)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_javascript_3_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ポリシーをデタッチします。  

```
import { DetachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 * @param {string} roleName
 */
export const detachRolePolicy = (policyArn, roleName) => {
  const command = new DetachRolePolicyCommand({
    PolicyArn: policyArn,
    RoleName: roleName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-detaching-role-policy)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DetachRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DetachRolePolicyCommand)」を参照してください。

### `GetAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_javascript_3_topic"></a>

次のコード例は、`GetAccessKeyLastUsed` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アクセスキーを取得します。  

```
import { GetAccessKeyLastUsedCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} accessKeyId
 */
export const getAccessKeyLastUsed = async (accessKeyId) => {
  const command = new GetAccessKeyLastUsedCommand({
    AccessKeyId: accessKeyId,
  });

  const response = await client.send(command);

  if (response.AccessKeyLastUsed?.LastUsedDate) {
    console.log(`
    ${accessKeyId} was last used by ${response.UserName} via 
    the ${response.AccessKeyLastUsed.ServiceName} service on
    ${response.AccessKeyLastUsed.LastUsedDate.toISOString()}
    `);
  }

  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-last-used)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetAccessKeyLastUsed](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetAccessKeyLastUsedCommand)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_javascript_3_topic"></a>

次のコード例は、`GetAccountPasswordPolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アカウントのパスワードポリシーを取得します。  

```
import {
  GetAccountPasswordPolicyCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const getAccountPasswordPolicy = async () => {
  const command = new GetAccountPasswordPolicyCommand({});

  const response = await client.send(command);
  console.log(response.PasswordPolicy);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetAccountPasswordPolicyCommand)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_javascript_3_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ポリシーを取得します。  

```
import { GetPolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 */
export const getPolicy = (policyArn) => {
  const command = new GetPolicyCommand({
    PolicyArn: policyArn,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-policies.html#iam-examples-policies-getting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetPolicyCommand)」を参照してください。

### `GetRole`
<a name="iam_GetRole_javascript_3_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ロールを取得します。  

```
import { GetRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const getRole = (roleName) => {
  const command = new GetRoleCommand({
    RoleName: roleName,
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetRoleCommand)」を参照してください。

### `GetServerCertificate`
<a name="iam_GetServerCertificate_javascript_3_topic"></a>

次のコード例は、`GetServerCertificate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
サーバー証明書を取得します。  

```
import { GetServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} certName
 * @returns
 */
export const getServerCertificate = async (certName) => {
  const command = new GetServerCertificateCommand({
    ServerCertificateName: certName,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-getting)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetServerCertificateCommand)」を参照してください。

### `GetServiceLinkedRoleDeletionStatus`
<a name="iam_GetServiceLinkedRoleDeletionStatus_javascript_3_topic"></a>

次のコード例は、`GetServiceLinkedRoleDeletionStatus` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import {
  GetServiceLinkedRoleDeletionStatusCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} deletionTaskId
 */
export const getServiceLinkedRoleDeletionStatus = (deletionTaskId) => {
  const command = new GetServiceLinkedRoleDeletionStatusCommand({
    DeletionTaskId: deletionTaskId,
  });

  return client.send(command);
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetServiceLinkedRoleDeletionStatus](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/GetServiceLinkedRoleDeletionStatusCommand)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_javascript_3_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アクセスキーを一覧表示します。  

```
import { ListAccessKeysCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 * @param {string} userName
 */
export async function* listAccessKeys(userName) {
  const command = new ListAccessKeysCommand({
    MaxItems: 5,
    UserName: userName,
  });

  /**
   * @type {import("@aws-sdk/client-iam").ListAccessKeysCommandOutput | undefined}
   */
  let response = await client.send(command);

  while (response?.AccessKeyMetadata?.length) {
    for (const key of response.AccessKeyMetadata) {
      yield key;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListAccessKeysCommand({
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListAccessKeys](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListAccessKeysCommand)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_javascript_3_topic"></a>

次のコード例は、`ListAccountAliases` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アカウントエイリアスを一覧表示します。  

```
import { ListAccountAliasesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 */
export async function* listAccountAliases() {
  const command = new ListAccountAliasesCommand({ MaxItems: 5 });

  let response = await client.send(command);

  while (response.AccountAliases?.length) {
    for (const alias of response.AccountAliases) {
      yield alias;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListAccountAliasesCommand({
          Marker: response.Marker,
          MaxItems: 5,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-account-aliases.html#iam-examples-account-aliases-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListAccountAliases](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListAccountAliasesCommand)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_javascript_3_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ロールにアタッチされたポリシーを一覧表示します。  

```
import {
  ListAttachedRolePoliciesCommand,
  IAMClient,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 * @param {string} roleName
 */
export async function* listAttachedRolePolicies(roleName) {
  const command = new ListAttachedRolePoliciesCommand({
    RoleName: roleName,
  });

  let response = await client.send(command);

  while (response.AttachedPolicies?.length) {
    for (const policy of response.AttachedPolicies) {
      yield policy;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListAttachedRolePoliciesCommand({
          RoleName: roleName,
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListAttachedRolePoliciesCommand)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_javascript_3_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
グループを一覧表示します。  

```
import { ListGroupsCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 */
export async function* listGroups() {
  const command = new ListGroupsCommand({
    MaxItems: 10,
  });

  let response = await client.send(command);

  while (response.Groups?.length) {
    for (const group of response.Groups) {
      yield group;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListGroupsCommand({
          Marker: response.Marker,
          MaxItems: 10,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListGroupsCommand)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_javascript_3_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ポリシーを一覧表示します。  

```
import { ListPoliciesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 */
export async function* listPolicies() {
  const command = new ListPoliciesCommand({
    MaxItems: 10,
    OnlyAttached: false,
    // List only the customer managed policies in your Amazon Web Services account.
    Scope: "Local",
  });

  let response = await client.send(command);

  while (response.Policies?.length) {
    for (const policy of response.Policies) {
      yield policy;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListPoliciesCommand({
          Marker: response.Marker,
          MaxItems: 10,
          OnlyAttached: false,
          Scope: "Local",
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListPoliciesCommand)」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_javascript_3_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ポリシーを一覧表示します。  

```
import { ListRolePoliciesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 * @param {string} roleName
 */
export async function* listRolePolicies(roleName) {
  const command = new ListRolePoliciesCommand({
    RoleName: roleName,
    MaxItems: 10,
  });

  let response = await client.send(command);

  while (response.PolicyNames?.length) {
    for (const policyName of response.PolicyNames) {
      yield policyName;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListRolePoliciesCommand({
          RoleName: roleName,
          MaxItems: 10,
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListRolePolicies](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListRolePoliciesCommand)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_javascript_3_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ロールを一覧表示します。  

```
import { ListRolesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 */
export async function* listRoles() {
  const command = new ListRolesCommand({
    MaxItems: 10,
  });

  /**
   * @type {import("@aws-sdk/client-iam").ListRolesCommandOutput | undefined}
   */
  let response = await client.send(command);

  while (response?.Roles?.length) {
    for (const role of response.Roles) {
      yield role;
    }

    if (response.IsTruncated) {
      response = await client.send(
        new ListRolesCommand({
          Marker: response.Marker,
        }),
      );
    } else {
      break;
    }
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListRoles](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListRolesCommand)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_javascript_3_topic"></a>

次のコード例は、`ListSAMLProviders` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
SAML プロバイダーを一覧表示します。  

```
import { ListSAMLProvidersCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const listSamlProviders = async () => {
  const command = new ListSAMLProvidersCommand({});

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListSAMLProviders](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListSAMLProvidersCommand)」を参照してください。

### `ListServerCertificates`
<a name="iam_ListServerCertificates_javascript_3_topic"></a>

次のコード例は、`ListServerCertificates` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
証明書を一覧表示します。  

```
import { ListServerCertificatesCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 * A generator function that handles paginated results.
 * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this.
 *
 */
export async function* listServerCertificates() {
  const command = new ListServerCertificatesCommand({});
  let response = await client.send(command);

  while (response.ServerCertificateMetadataList?.length) {
    for await (const cert of response.ServerCertificateMetadataList) {
      yield cert;
    }

    if (response.IsTruncated) {
      response = await client.send(new ListServerCertificatesCommand({}));
    } else {
      break;
    }
  }
}
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-listing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListServerCertificates](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListServerCertificatesCommand)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_javascript_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ユーザーを一覧表示します。  

```
import { ListUsersCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

export const listUsers = async () => {
  const command = new ListUsersCommand({ MaxItems: 10 });

  const response = await client.send(command);

  for (const { UserName, CreateDate } of response.Users) {
    console.log(`${UserName} created on: ${CreateDate}`);
  }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-listing-users)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/ListUsersCommand)」を参照してください。

### `PutRolePolicy`
<a name="iam_PutRolePolicy_javascript_3_topic"></a>

次のコード例は、`PutRolePolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { PutRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const examplePolicyDocument = JSON.stringify({
  Version: "2012-10-17",
  Statement: [
    {
      Sid: "VisualEditor0",
      Effect: "Allow",
      Action: [
        "s3:ListBucketMultipartUploads",
        "s3:ListBucketVersions",
        "s3:ListBucket",
        "s3:ListMultipartUploadParts",
      ],
      Resource: "arn:aws:s3:::amzn-s3-demo-bucket",
    },
    {
      Sid: "VisualEditor1",
      Effect: "Allow",
      Action: [
        "s3:ListStorageLensConfigurations",
        "s3:ListAccessPointsForObjectLambda",
        "s3:ListAllMyBuckets",
        "s3:ListAccessPoints",
        "s3:ListJobs",
        "s3:ListMultiRegionAccessPoints",
      ],
      Resource: "*",
    },
  ],
});

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 * @param {string} policyName
 * @param {string} policyDocument
 */
export const putRolePolicy = async (roleName, policyName, policyDocument) => {
  const command = new PutRolePolicyCommand({
    RoleName: roleName,
    PolicyName: policyName,
    PolicyDocument: policyDocument,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutRolePolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/PutRolePolicyCommand)」を参照してください。

### `UpdateAccessKey`
<a name="iam_UpdateAccessKey_javascript_3_topic"></a>

次のコード例は、`UpdateAccessKey` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アクセスキーを更新します。  

```
import {
  UpdateAccessKeyCommand,
  IAMClient,
  StatusType,
} from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} userName
 * @param {string} accessKeyId
 */
export const updateAccessKey = (userName, accessKeyId) => {
  const command = new UpdateAccessKeyCommand({
    AccessKeyId: accessKeyId,
    Status: StatusType.Inactive,
    UserName: userName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-access-keys.html#iam-examples-managing-access-keys-updating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の[UpdateAccessKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UpdateAccessKeyCommand)」を参照してください。

### `UpdateServerCertificate`
<a name="iam_UpdateServerCertificate_javascript_3_topic"></a>

次のコード例は、`UpdateServerCertificate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
サーバー証明書を更新します。  

```
import { UpdateServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} currentName
 * @param {string} newName
 */
export const updateServerCertificate = (currentName, newName) => {
  const command = new UpdateServerCertificateCommand({
    ServerCertificateName: currentName,
    NewServerCertificateName: newName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-server-certificates.html#iam-examples-server-certificates-updating)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UpdateServerCertificateCommand)」を参照してください。

### `UpdateUser`
<a name="iam_UpdateUser_javascript_3_topic"></a>

次のコード例は、`UpdateUser` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。
ユーザーを更新します。  

```
import { UpdateUserCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} currentUserName
 * @param {string} newUserName
 */
export const updateUser = (currentUserName, newUserName) => {
  const command = new UpdateUserCommand({
    UserName: currentUserName,
    NewUserName: newUserName,
  });

  return client.send(command);
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/iam-examples-managing-users.html#iam-examples-managing-users-updating-users)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[UpdateUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UpdateUserCommand)」を参照してください。

### `UploadServerCertificate`
<a name="iam_UploadServerCertificate_javascript_3_topic"></a>

次のコード例は、`UploadServerCertificate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import { UploadServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";
import { readFileSync } from "node:fs";
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import * as path from "node:path";

const client = new IAMClient({});

const certMessage = `Generate a certificate and key with the following command, or the equivalent for your system.

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
-keyout example.key -out example.crt -subj "/CN=example.com" \
-addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1"
`;

const getCertAndKey = () => {
  try {
    const cert = readFileSync(
      path.join(dirnameFromMetaUrl(import.meta.url), "./example.crt"),
    );
    const key = readFileSync(
      path.join(dirnameFromMetaUrl(import.meta.url), "./example.key"),
    );
    return { cert, key };
  } catch (err) {
    if (err.code === "ENOENT") {
      throw new Error(
        `Certificate and/or private key not found. ${certMessage}`,
      );
    }

    throw err;
  }
};

/**
 *
 * @param {string} certificateName
 */
export const uploadServerCertificate = (certificateName) => {
  const { cert, key } = getCertAndKey();
  const command = new UploadServerCertificateCommand({
    ServerCertificateName: certificateName,
    CertificateBody: cert.toString(),
    PrivateKey: key.toString(),
  });

  return client.send(command);
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[UploadServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UploadServerCertificateCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_javascript_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-resilient-service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
#!/usr/bin/env node
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

import {
  Scenario,
  parseScenarioArgs,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

/**
 * The workflow steps are split into three stages:
 *   - deploy
 *   - demo
 *   - destroy
 *
 * Each of these stages has a corresponding file prefixed with steps-*.
 */
import { deploySteps } from "./steps-deploy.js";
import { demoSteps } from "./steps-demo.js";
import { destroySteps } from "./steps-destroy.js";

/**
 * The context is passed to every scenario. Scenario steps
 * will modify the context.
 */
const context = {};

/**
 * Three Scenarios are created for the workflow. A Scenario is an orchestration class
 * that simplifies running a series of steps.
 */
export const scenarios = {
  // Deploys all resources necessary for the workflow.
  deploy: new Scenario("Resilient Workflow - Deploy", deploySteps, context),
  // Demonstrates how a fragile web service can be made more resilient.
  demo: new Scenario("Resilient Workflow - Demo", demoSteps, context),
  // Destroys the resources created for the workflow.
  destroy: new Scenario("Resilient Workflow - Destroy", destroySteps, context),
};

// Call function if run directly
import { fileURLToPath } from "node:url";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  parseScenarioArgs(scenarios, {
    name: "Resilient Workflow",
    synopsis:
      "node index.js --scenario <deploy | demo | destroy> [-h|--help] [-y|--yes] [-v|--verbose]",
    description: "Deploy and interact with scalable EC2 instances.",
  });
}
```
すべてのリソースをデプロイするための手順を作成します。  

```
import { join } from "node:path";
import { readFileSync, writeFileSync } from "node:fs";
import axios from "axios";

import {
  BatchWriteItemCommand,
  CreateTableCommand,
  DynamoDBClient,
  waitUntilTableExists,
} from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  CreateKeyPairCommand,
  CreateLaunchTemplateCommand,
  DescribeAvailabilityZonesCommand,
  DescribeVpcsCommand,
  DescribeSubnetsCommand,
  DescribeSecurityGroupsCommand,
  AuthorizeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  AttachRolePolicyCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import { SSMClient, GetParameterCommand } from "@aws-sdk/client-ssm";
import {
  CreateAutoScalingGroupCommand,
  AutoScalingClient,
  AttachLoadBalancerTargetGroupsCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  CreateListenerCommand,
  CreateLoadBalancerCommand,
  CreateTargetGroupCommand,
  ElasticLoadBalancingV2Client,
  waitUntilLoadBalancerAvailable,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { saveState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH, ROOT } from "./constants.js";
import { initParamsSteps } from "./steps-reset-params.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const deploySteps = [
  new ScenarioOutput("introduction", MESSAGES.introduction, { header: true }),
  new ScenarioInput("confirmDeployment", MESSAGES.confirmDeployment, {
    type: "confirm",
  }),
  new ScenarioAction(
    "handleConfirmDeployment",
    (c) => c.confirmDeployment === false && process.exit(),
  ),
  new ScenarioOutput(
    "creatingTable",
    MESSAGES.creatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("createTable", async () => {
    const client = new DynamoDBClient({});
    await client.send(
      new CreateTableCommand({
        TableName: NAMES.tableName,
        ProvisionedThroughput: {
          ReadCapacityUnits: 5,
          WriteCapacityUnits: 5,
        },
        AttributeDefinitions: [
          {
            AttributeName: "MediaType",
            AttributeType: "S",
          },
          {
            AttributeName: "ItemId",
            AttributeType: "N",
          },
        ],
        KeySchema: [
          {
            AttributeName: "MediaType",
            KeyType: "HASH",
          },
          {
            AttributeName: "ItemId",
            KeyType: "RANGE",
          },
        ],
      }),
    );
    await waitUntilTableExists({ client }, { TableName: NAMES.tableName });
  }),
  new ScenarioOutput(
    "createdTable",
    MESSAGES.createdTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "populatingTable",
    MESSAGES.populatingTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioAction("populateTable", () => {
    const client = new DynamoDBClient({});
    /**
     * @type {{ default: import("@aws-sdk/client-dynamodb").PutRequest['Item'][] }}
     */
    const recommendations = JSON.parse(
      readFileSync(join(RESOURCES_PATH, "recommendations.json")),
    );

    return client.send(
      new BatchWriteItemCommand({
        RequestItems: {
          [NAMES.tableName]: recommendations.map((item) => ({
            PutRequest: { Item: item },
          })),
        },
      }),
    );
  }),
  new ScenarioOutput(
    "populatedTable",
    MESSAGES.populatedTable.replace("${TABLE_NAME}", NAMES.tableName),
  ),
  new ScenarioOutput(
    "creatingKeyPair",
    MESSAGES.creatingKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioAction("createKeyPair", async () => {
    const client = new EC2Client({});
    const { KeyMaterial } = await client.send(
      new CreateKeyPairCommand({
        KeyName: NAMES.keyPairName,
      }),
    );

    writeFileSync(`${NAMES.keyPairName}.pem`, KeyMaterial, { mode: 0o600 });
  }),
  new ScenarioOutput(
    "createdKeyPair",
    MESSAGES.createdKeyPair.replace("${KEY_PAIR_NAME}", NAMES.keyPairName),
  ),
  new ScenarioOutput(
    "creatingInstancePolicy",
    MESSAGES.creatingInstancePolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    ),
  ),
  new ScenarioAction("createInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const {
      Policy: { Arn },
    } = await client.send(
      new CreatePolicyCommand({
        PolicyName: NAMES.instancePolicyName,
        PolicyDocument: readFileSync(
          join(RESOURCES_PATH, "instance_policy.json"),
        ),
      }),
    );
    state.instancePolicyArn = Arn;
  }),
  new ScenarioOutput("createdInstancePolicy", (state) =>
    MESSAGES.createdInstancePolicy
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_POLICY_ARN}", state.instancePolicyArn),
  ),
  new ScenarioOutput(
    "creatingInstanceRole",
    MESSAGES.creatingInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioAction("createInstanceRole", () => {
    const client = new IAMClient({});
    return client.send(
      new CreateRoleCommand({
        RoleName: NAMES.instanceRoleName,
        AssumeRolePolicyDocument: readFileSync(
          join(ROOT, "assume-role-policy.json"),
        ),
      }),
    );
  }),
  new ScenarioOutput(
    "createdInstanceRole",
    MESSAGES.createdInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    ),
  ),
  new ScenarioOutput(
    "attachingPolicyToRole",
    MESSAGES.attachingPolicyToRole
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName)
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName),
  ),
  new ScenarioAction("attachPolicyToRole", async (state) => {
    const client = new IAMClient({});
    await client.send(
      new AttachRolePolicyCommand({
        RoleName: NAMES.instanceRoleName,
        PolicyArn: state.instancePolicyArn,
      }),
    );
  }),
  new ScenarioOutput(
    "attachedPolicyToRole",
    MESSAGES.attachedPolicyToRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioOutput(
    "creatingInstanceProfile",
    MESSAGES.creatingInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    ),
  ),
  new ScenarioAction("createInstanceProfile", async (state) => {
    const client = new IAMClient({});
    const {
      InstanceProfile: { Arn },
    } = await client.send(
      new CreateInstanceProfileCommand({
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
    state.instanceProfileArn = Arn;

    await waitUntilInstanceProfileExists(
      { client },
      { InstanceProfileName: NAMES.instanceProfileName },
    );
  }),
  new ScenarioOutput("createdInstanceProfile", (state) =>
    MESSAGES.createdInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_PROFILE_ARN}", state.instanceProfileArn),
  ),
  new ScenarioOutput(
    "addingRoleToInstanceProfile",
    MESSAGES.addingRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  new ScenarioAction("addRoleToInstanceProfile", () => {
    const client = new IAMClient({});
    return client.send(
      new AddRoleToInstanceProfileCommand({
        RoleName: NAMES.instanceRoleName,
        InstanceProfileName: NAMES.instanceProfileName,
      }),
    );
  }),
  new ScenarioOutput(
    "addedRoleToInstanceProfile",
    MESSAGES.addedRoleToInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName),
  ),
  ...initParamsSteps,
  new ScenarioOutput("creatingLaunchTemplate", MESSAGES.creatingLaunchTemplate),
  new ScenarioAction("createLaunchTemplate", async () => {
    const ssmClient = new SSMClient({});
    const { Parameter } = await ssmClient.send(
      new GetParameterCommand({
        Name: "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
      }),
    );
    const ec2Client = new EC2Client({});
    await ec2Client.send(
      new CreateLaunchTemplateCommand({
        LaunchTemplateName: NAMES.launchTemplateName,
        LaunchTemplateData: {
          InstanceType: "t3.micro",
          ImageId: Parameter.Value,
          IamInstanceProfile: { Name: NAMES.instanceProfileName },
          UserData: readFileSync(
            join(RESOURCES_PATH, "server_startup_script.sh"),
          ).toString("base64"),
          KeyName: NAMES.keyPairName,
        },
      }),
    );
  }),
  new ScenarioOutput(
    "createdLaunchTemplate",
    MESSAGES.createdLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    ),
  ),
  new ScenarioOutput(
    "creatingAutoScalingGroup",
    MESSAGES.creatingAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    ),
  ),
  new ScenarioAction("createAutoScalingGroup", async (state) => {
    const ec2Client = new EC2Client({});
    const { AvailabilityZones } = await ec2Client.send(
      new DescribeAvailabilityZonesCommand({}),
    );
    state.availabilityZoneNames = AvailabilityZones.map((az) => az.ZoneName);
    const autoScalingClient = new AutoScalingClient({});
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new CreateAutoScalingGroupCommand({
          AvailabilityZones: state.availabilityZoneNames,
          AutoScalingGroupName: NAMES.autoScalingGroupName,
          LaunchTemplate: {
            LaunchTemplateName: NAMES.launchTemplateName,
            Version: "$Default",
          },
          MinSize: 3,
          MaxSize: 3,
        }),
      ),
    );
  }),
  new ScenarioOutput(
    "createdAutoScalingGroup",
    /**
     * @param {{ availabilityZoneNames: string[] }} state
     */
    (state) =>
      MESSAGES.createdAutoScalingGroup
        .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName)
        .replace(
          "${AVAILABILITY_ZONE_NAMES}",
          state.availabilityZoneNames.join(", "),
        ),
  ),
  new ScenarioInput("confirmContinue", MESSAGES.confirmContinue, {
    type: "confirm",
  }),
  new ScenarioOutput("loadBalancer", MESSAGES.loadBalancer),
  new ScenarioOutput("gettingVpc", MESSAGES.gettingVpc),
  new ScenarioAction("getVpc", async (state) => {
    const client = new EC2Client({});
    const { Vpcs } = await client.send(
      new DescribeVpcsCommand({
        Filters: [{ Name: "is-default", Values: ["true"] }],
      }),
    );
    state.defaultVpc = Vpcs[0].VpcId;
  }),
  new ScenarioOutput("gotVpc", (state) =>
    MESSAGES.gotVpc.replace("${VPC_ID}", state.defaultVpc),
  ),
  new ScenarioOutput("gettingSubnets", MESSAGES.gettingSubnets),
  new ScenarioAction("getSubnets", async (state) => {
    const client = new EC2Client({});
    const { Subnets } = await client.send(
      new DescribeSubnetsCommand({
        Filters: [
          { Name: "vpc-id", Values: [state.defaultVpc] },
          { Name: "availability-zone", Values: state.availabilityZoneNames },
          { Name: "default-for-az", Values: ["true"] },
        ],
      }),
    );
    state.subnets = Subnets.map((subnet) => subnet.SubnetId);
  }),
  new ScenarioOutput(
    "gotSubnets",
    /**
     * @param {{ subnets: string[] }} state
     */
    (state) =>
      MESSAGES.gotSubnets.replace("${SUBNETS}", state.subnets.join(", ")),
  ),
  new ScenarioOutput(
    "creatingLoadBalancerTargetGroup",
    MESSAGES.creatingLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioAction("createLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { TargetGroups } = await client.send(
      new CreateTargetGroupCommand({
        Name: NAMES.loadBalancerTargetGroupName,
        Protocol: "HTTP",
        Port: 80,
        HealthCheckPath: "/healthcheck",
        HealthCheckIntervalSeconds: 10,
        HealthCheckTimeoutSeconds: 5,
        HealthyThresholdCount: 2,
        UnhealthyThresholdCount: 2,
        VpcId: state.defaultVpc,
      }),
    );
    const targetGroup = TargetGroups[0];
    state.targetGroupArn = targetGroup.TargetGroupArn;
    state.targetGroupProtocol = targetGroup.Protocol;
    state.targetGroupPort = targetGroup.Port;
  }),
  new ScenarioOutput(
    "createdLoadBalancerTargetGroup",
    MESSAGES.createdLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    ),
  ),
  new ScenarioOutput(
    "creatingLoadBalancer",
    MESSAGES.creatingLoadBalancer.replace("${LB_NAME}", NAMES.loadBalancerName),
  ),
  new ScenarioAction("createLoadBalancer", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { LoadBalancers } = await client.send(
      new CreateLoadBalancerCommand({
        Name: NAMES.loadBalancerName,
        Subnets: state.subnets,
      }),
    );
    state.loadBalancerDns = LoadBalancers[0].DNSName;
    state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn;
    await waitUntilLoadBalancerAvailable(
      { client },
      { Names: [NAMES.loadBalancerName] },
    );
  }),
  new ScenarioOutput("createdLoadBalancer", (state) =>
    MESSAGES.createdLoadBalancer
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioOutput(
    "creatingListener",
    MESSAGES.creatingLoadBalancerListener
      .replace("${LB_NAME}", NAMES.loadBalancerName)
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName),
  ),
  new ScenarioAction("createListener", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    const { Listeners } = await client.send(
      new CreateListenerCommand({
        LoadBalancerArn: state.loadBalancerArn,
        Protocol: state.targetGroupProtocol,
        Port: state.targetGroupPort,
        DefaultActions: [
          { Type: "forward", TargetGroupArn: state.targetGroupArn },
        ],
      }),
    );
    const listener = Listeners[0];
    state.loadBalancerListenerArn = listener.ListenerArn;
  }),
  new ScenarioOutput("createdListener", (state) =>
    MESSAGES.createdLoadBalancerListener.replace(
      "${LB_LISTENER_ARN}",
      state.loadBalancerListenerArn,
    ),
  ),
  new ScenarioOutput(
    "attachingLoadBalancerTargetGroup",
    MESSAGES.attachingLoadBalancerTargetGroup
      .replace("${TARGET_GROUP_NAME}", NAMES.loadBalancerTargetGroupName)
      .replace("${AUTO_SCALING_GROUP_NAME}", NAMES.autoScalingGroupName),
  ),
  new ScenarioAction("attachLoadBalancerTargetGroup", async (state) => {
    const client = new AutoScalingClient({});
    await client.send(
      new AttachLoadBalancerTargetGroupsCommand({
        AutoScalingGroupName: NAMES.autoScalingGroupName,
        TargetGroupARNs: [state.targetGroupArn],
      }),
    );
  }),
  new ScenarioOutput(
    "attachedLoadBalancerTargetGroup",
    MESSAGES.attachedLoadBalancerTargetGroup,
  ),
  new ScenarioOutput("verifyingInboundPort", MESSAGES.verifyingInboundPort),
  new ScenarioAction(
    "verifyInboundPort",
    /**
     *
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup}} state
     */
    async (state) => {
      const client = new EC2Client({});
      const { SecurityGroups } = await client.send(
        new DescribeSecurityGroupsCommand({
          Filters: [{ Name: "group-name", Values: ["default"] }],
        }),
      );
      if (!SecurityGroups) {
        state.verifyInboundPortError = new Error(MESSAGES.noSecurityGroups);
      }
      state.defaultSecurityGroup = SecurityGroups[0];

      /**
       * @type {string}
       */
      const ipResponse = (await axios.get("http://checkip.amazonaws.com")).data;
      state.myIp = ipResponse.trim();
      const myIpRules = state.defaultSecurityGroup.IpPermissions.filter(
        ({ IpRanges }) =>
          IpRanges.some(
            ({ CidrIp }) =>
              CidrIp.startsWith(state.myIp) || CidrIp === "0.0.0.0/0",
          ),
      )
        .filter(({ IpProtocol }) => IpProtocol === "tcp")
        .filter(({ FromPort }) => FromPort === 80);

      state.myIpRules = myIpRules;
    },
  ),
  new ScenarioOutput(
    "verifiedInboundPort",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return MESSAGES.foundIpRules.replace(
          "${IP_RULES}",
          JSON.stringify(state.myIpRules, null, 2),
        );
      }
      return MESSAGES.noIpRules;
    },
  ),
  new ScenarioInput(
    "shouldAddInboundRule",
    /**
     * @param {{ myIpRules: any[] }} state
     */
    (state) => {
      if (state.myIpRules.length > 0) {
        return false;
      }
      return MESSAGES.noIpRules;
    },
    { type: "confirm" },
  ),
  new ScenarioAction(
    "addInboundRule",
    /**
     * @param {{ defaultSecurityGroup: import('@aws-sdk/client-ec2').SecurityGroup }} state
     */
    async (state) => {
      if (!state.shouldAddInboundRule) {
        return;
      }

      const client = new EC2Client({});
      await client.send(
        new AuthorizeSecurityGroupIngressCommand({
          GroupId: state.defaultSecurityGroup.GroupId,
          CidrIp: `${state.myIp}/32`,
          FromPort: 80,
          ToPort: 80,
          IpProtocol: "tcp",
        }),
      );
    },
  ),
  new ScenarioOutput("addedInboundRule", (state) => {
    if (state.shouldAddInboundRule) {
      return MESSAGES.addedInboundRule.replace("${IP_ADDRESS}", state.myIp);
    }
    return false;
  }),
  new ScenarioOutput("verifyingEndpoint", (state) =>
    MESSAGES.verifyingEndpoint.replace("${DNS_NAME}", state.loadBalancerDns),
  ),
  new ScenarioAction("verifyEndpoint", async (state) => {
    try {
      const response = await retry({ intervalInMs: 2000, maxRetries: 30 }, () =>
        axios.get(`http://${state.loadBalancerDns}`),
      );
      state.endpointResponse = JSON.stringify(response.data, null, 2);
    } catch (e) {
      state.verifyEndpointError = e;
    }
  }),
  new ScenarioOutput("verifiedEndpoint", (state) => {
    if (state.verifyEndpointError) {
      console.error(state.verifyEndpointError);
    } else {
      return MESSAGES.verifiedEndpoint.replace(
        "${ENDPOINT_RESPONSE}",
        state.endpointResponse,
      );
    }
  }),
  saveState,
];
```
デモを実行するための手順を作成します。  

```
import { readFileSync } from "node:fs";
import { join } from "node:path";

import axios from "axios";

import {
  DescribeTargetGroupsCommand,
  DescribeTargetHealthCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";
import {
  DescribeInstanceInformationCommand,
  PutParameterCommand,
  SSMClient,
  SendCommandCommand,
} from "@aws-sdk/client-ssm";
import {
  IAMClient,
  CreatePolicyCommand,
  CreateRoleCommand,
  AttachRolePolicyCommand,
  CreateInstanceProfileCommand,
  AddRoleToInstanceProfileCommand,
  waitUntilInstanceProfileExists,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DescribeAutoScalingGroupsCommand,
  TerminateInstanceInAutoScalingGroupCommand,
} from "@aws-sdk/client-auto-scaling";
import {
  DescribeIamInstanceProfileAssociationsCommand,
  EC2Client,
  RebootInstancesCommand,
  ReplaceIamInstanceProfileAssociationCommand,
} from "@aws-sdk/client-ec2";

import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES, RESOURCES_PATH } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

const getRecommendation = new ScenarioAction(
  "getRecommendation",
  async (state) => {
    const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
    if (loadBalancer) {
      state.loadBalancerDnsName = loadBalancer.DNSName;
      try {
        state.recommendation = (
          await axios.get(`http://${state.loadBalancerDnsName}`)
        ).data;
      } catch (e) {
        state.recommendation = e instanceof Error ? e.message : e;
      }
    } else {
      throw new Error(MESSAGES.demoFindLoadBalancerError);
    }
  },
);

const getRecommendationResult = new ScenarioOutput(
  "getRecommendationResult",
  (state) =>
    `Recommendation:\n${JSON.stringify(state.recommendation, null, 2)}`,
  { preformatted: true },
);

const getHealthCheck = new ScenarioAction("getHealthCheck", async (state) => {
  const client = new ElasticLoadBalancingV2Client({});
  const { TargetGroups } = await client.send(
    new DescribeTargetGroupsCommand({
      Names: [NAMES.loadBalancerTargetGroupName],
    }),
  );

  const { TargetHealthDescriptions } = await client.send(
    new DescribeTargetHealthCommand({
      TargetGroupArn: TargetGroups[0].TargetGroupArn,
    }),
  );
  state.targetHealthDescriptions = TargetHealthDescriptions;
});

const getHealthCheckResult = new ScenarioOutput(
  "getHealthCheckResult",
  /**
   * @param {{ targetHealthDescriptions: import('@aws-sdk/client-elastic-load-balancing-v2').TargetHealthDescription[]}} state
   */
  (state) => {
    const status = state.targetHealthDescriptions
      .map((th) => `${th.Target.Id}: ${th.TargetHealth.State}`)
      .join("\n");
    return `Health check:\n${status}`;
  },
  { preformatted: true },
);

const loadBalancerLoop = new ScenarioAction(
  "loadBalancerLoop",
  getRecommendation.action,
  {
    whileConfig: {
      whileFn: ({ loadBalancerCheck }) => loadBalancerCheck,
      input: new ScenarioInput(
        "loadBalancerCheck",
        MESSAGES.demoLoadBalancerCheck,
        {
          type: "confirm",
        },
      ),
      output: getRecommendationResult,
    },
  },
);

const healthCheckLoop = new ScenarioAction(
  "healthCheckLoop",
  getHealthCheck.action,
  {
    whileConfig: {
      whileFn: ({ healthCheck }) => healthCheck,
      input: new ScenarioInput("healthCheck", MESSAGES.demoHealthCheck, {
        type: "confirm",
      }),
      output: getHealthCheckResult,
    },
  },
);

const statusSteps = [
  getRecommendation,
  getRecommendationResult,
  getHealthCheck,
  getHealthCheckResult,
];

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const demoSteps = [
  new ScenarioOutput("header", MESSAGES.demoHeader, { header: true }),
  new ScenarioOutput("sanityCheck", MESSAGES.demoSanityCheck),
  ...statusSteps,
  new ScenarioInput(
    "brokenDependencyConfirmation",
    MESSAGES.demoBrokenDependencyConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("brokenDependency", async (state) => {
    if (!state.brokenDependencyConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      state.badTableName = `fake-table-${Date.now()}`;
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmTableNameKey,
          Value: state.badTableName,
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testBrokenDependency", (state) =>
    MESSAGES.demoTestBrokenDependency.replace(
      "${TABLE_NAME}",
      state.badTableName,
    ),
  ),
  ...statusSteps,
  new ScenarioInput(
    "staticResponseConfirmation",
    MESSAGES.demoStaticResponseConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("staticResponse", async (state) => {
    if (!state.staticResponseConfirmation) {
      process.exit();
    } else {
      const client = new SSMClient({});
      await client.send(
        new PutParameterCommand({
          Name: NAMES.ssmFailureResponseKey,
          Value: "static",
          Overwrite: true,
          Type: "String",
        }),
      );
    }
  }),
  new ScenarioOutput("testStaticResponse", MESSAGES.demoTestStaticResponse),
  ...statusSteps,
  new ScenarioInput(
    "badCredentialsConfirmation",
    MESSAGES.demoBadCredentialsConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("badCredentialsExit", (state) => {
    if (!state.badCredentialsConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("fixDynamoDBName", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioAction(
    "badCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-auto-scaling').Instance }} state
     */
    async (state) => {
      await createSsmOnlyInstanceProfile();
      const autoScalingClient = new AutoScalingClient({});
      const { AutoScalingGroups } = await autoScalingClient.send(
        new DescribeAutoScalingGroupsCommand({
          AutoScalingGroupNames: [NAMES.autoScalingGroupName],
        }),
      );
      state.targetInstance = AutoScalingGroups[0].Instances[0];
      const ec2Client = new EC2Client({});
      const { IamInstanceProfileAssociations } = await ec2Client.send(
        new DescribeIamInstanceProfileAssociationsCommand({
          Filters: [
            { Name: "instance-id", Values: [state.targetInstance.InstanceId] },
          ],
        }),
      );
      state.instanceProfileAssociationId =
        IamInstanceProfileAssociations[0].AssociationId;
      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        ec2Client.send(
          new ReplaceIamInstanceProfileAssociationCommand({
            AssociationId: state.instanceProfileAssociationId,
            IamInstanceProfile: { Name: NAMES.ssmOnlyInstanceProfileName },
          }),
        ),
      );

      await ec2Client.send(
        new RebootInstancesCommand({
          InstanceIds: [state.targetInstance.InstanceId],
        }),
      );

      const ssmClient = new SSMClient({});
      await retry({ intervalInMs: 20000, maxRetries: 15 }, async () => {
        const { InstanceInformationList } = await ssmClient.send(
          new DescribeInstanceInformationCommand({}),
        );

        const instance = InstanceInformationList.find(
          (info) => info.InstanceId === state.targetInstance.InstanceId,
        );

        if (!instance) {
          throw new Error("Instance not found.");
        }
      });

      await ssmClient.send(
        new SendCommandCommand({
          InstanceIds: [state.targetInstance.InstanceId],
          DocumentName: "AWS-RunShellScript",
          Parameters: { commands: ["cd / && sudo python3 server.py 80"] },
        }),
      );
    },
  ),
  new ScenarioOutput(
    "testBadCredentials",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation}} state
     */
    (state) =>
      MESSAGES.demoTestBadCredentials.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
  ),
  loadBalancerLoop,
  new ScenarioInput(
    "deepHealthCheckConfirmation",
    MESSAGES.demoDeepHealthCheckConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("deepHealthCheckExit", (state) => {
    if (!state.deepHealthCheckConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("deepHealthCheck", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmHealthCheckKey,
        Value: "deep",
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testDeepHealthCheck", MESSAGES.demoTestDeepHealthCheck),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "killInstanceConfirmation",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    (state) =>
      MESSAGES.demoKillInstanceConfirmation.replace(
        "${INSTANCE_ID}",
        state.targetInstance.InstanceId,
      ),
    { type: "confirm" },
  ),
  new ScenarioAction("killInstanceExit", (state) => {
    if (!state.killInstanceConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction(
    "killInstance",
    /**
     * @param {{ targetInstance: import('@aws-sdk/client-ssm').InstanceInformation }} state
     */
    async (state) => {
      const client = new AutoScalingClient({});
      await client.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: state.targetInstance.InstanceId,
          ShouldDecrementDesiredCapacity: false,
        }),
      );
    },
  ),
  new ScenarioOutput("testKillInstance", MESSAGES.demoTestKillInstance),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput("failOpenConfirmation", MESSAGES.demoFailOpenConfirmation, {
    type: "confirm",
  }),
  new ScenarioAction("failOpenExit", (state) => {
    if (!state.failOpenConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("failOpen", () => {
    const client = new SSMClient({});
    return client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: `fake-table-${Date.now()}`,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testFailOpen", MESSAGES.demoFailOpenTest),
  healthCheckLoop,
  loadBalancerLoop,
  new ScenarioInput(
    "resetTableConfirmation",
    MESSAGES.demoResetTableConfirmation,
    { type: "confirm" },
  ),
  new ScenarioAction("resetTableExit", (state) => {
    if (!state.resetTableConfirmation) {
      process.exit();
    }
  }),
  new ScenarioAction("resetTable", async () => {
    const client = new SSMClient({});
    await client.send(
      new PutParameterCommand({
        Name: NAMES.ssmTableNameKey,
        Value: NAMES.tableName,
        Overwrite: true,
        Type: "String",
      }),
    );
  }),
  new ScenarioOutput("testResetTable", MESSAGES.demoTestResetTable),
  healthCheckLoop,
  loadBalancerLoop,
];

async function createSsmOnlyInstanceProfile() {
  const iamClient = new IAMClient({});
  const { Policy } = await iamClient.send(
    new CreatePolicyCommand({
      PolicyName: NAMES.ssmOnlyPolicyName,
      PolicyDocument: readFileSync(
        join(RESOURCES_PATH, "ssm_only_policy.json"),
      ),
    }),
  );
  await iamClient.send(
    new CreateRoleCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      AssumeRolePolicyDocument: JSON.stringify({
        Version: "2012-10-17",
        Statement: [
          {
            Effect: "Allow",
            Principal: { Service: "ec2.amazonaws.com" },
            Action: "sts:AssumeRole",
          },
        ],
      }),
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: Policy.Arn,
    }),
  );
  await iamClient.send(
    new AttachRolePolicyCommand({
      RoleName: NAMES.ssmOnlyRoleName,
      PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
    }),
  );
  const { InstanceProfile } = await iamClient.send(
    new CreateInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
    }),
  );
  await waitUntilInstanceProfileExists(
    { client: iamClient },
    { InstanceProfileName: NAMES.ssmOnlyInstanceProfileName },
  );
  await iamClient.send(
    new AddRoleToInstanceProfileCommand({
      InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
      RoleName: NAMES.ssmOnlyRoleName,
    }),
  );

  return InstanceProfile;
}
```
すべてのリソースを破棄するための手順を作成します。  

```
import { unlinkSync } from "node:fs";

import { DynamoDBClient, DeleteTableCommand } from "@aws-sdk/client-dynamodb";
import {
  EC2Client,
  DeleteKeyPairCommand,
  DeleteLaunchTemplateCommand,
  RevokeSecurityGroupIngressCommand,
} from "@aws-sdk/client-ec2";
import {
  IAMClient,
  DeleteInstanceProfileCommand,
  RemoveRoleFromInstanceProfileCommand,
  DeletePolicyCommand,
  DeleteRoleCommand,
  DetachRolePolicyCommand,
  paginateListPolicies,
} from "@aws-sdk/client-iam";
import {
  AutoScalingClient,
  DeleteAutoScalingGroupCommand,
  TerminateInstanceInAutoScalingGroupCommand,
  UpdateAutoScalingGroupCommand,
  paginateDescribeAutoScalingGroups,
} from "@aws-sdk/client-auto-scaling";
import {
  DeleteLoadBalancerCommand,
  DeleteTargetGroupCommand,
  DescribeTargetGroupsCommand,
  ElasticLoadBalancingV2Client,
} from "@aws-sdk/client-elastic-load-balancing-v2";

import {
  ScenarioOutput,
  ScenarioInput,
  ScenarioAction,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { loadState } from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

import { MESSAGES, NAMES } from "./constants.js";
import { findLoadBalancer } from "./shared.js";

/**
 * @type {import('@aws-doc-sdk-examples/lib/scenario.js').Step[]}
 */
export const destroySteps = [
  loadState,
  new ScenarioInput("destroy", MESSAGES.destroy, { type: "confirm" }),
  new ScenarioAction(
    "abort",
    (state) => state.destroy === false && process.exit(),
  ),
  new ScenarioAction("deleteTable", async (c) => {
    try {
      const client = new DynamoDBClient({});
      await client.send(new DeleteTableCommand({ TableName: NAMES.tableName }));
    } catch (e) {
      c.deleteTableError = e;
    }
  }),
  new ScenarioOutput("deleteTableResult", (state) => {
    if (state.deleteTableError) {
      console.error(state.deleteTableError);
      return MESSAGES.deleteTableError.replace(
        "${TABLE_NAME}",
        NAMES.tableName,
      );
    }
    return MESSAGES.deletedTable.replace("${TABLE_NAME}", NAMES.tableName);
  }),
  new ScenarioAction("deleteKeyPair", async (state) => {
    try {
      const client = new EC2Client({});
      await client.send(
        new DeleteKeyPairCommand({ KeyName: NAMES.keyPairName }),
      );
      unlinkSync(`${NAMES.keyPairName}.pem`);
    } catch (e) {
      state.deleteKeyPairError = e;
    }
  }),
  new ScenarioOutput("deleteKeyPairResult", (state) => {
    if (state.deleteKeyPairError) {
      console.error(state.deleteKeyPairError);
      return MESSAGES.deleteKeyPairError.replace(
        "${KEY_PAIR_NAME}",
        NAMES.keyPairName,
      );
    }
    return MESSAGES.deletedKeyPair.replace(
      "${KEY_PAIR_NAME}",
      NAMES.keyPairName,
    );
  }),
  new ScenarioAction("detachPolicyFromRole", async (state) => {
    try {
      const client = new IAMClient({});
      const policy = await findPolicy(NAMES.instancePolicyName);

      if (!policy) {
        state.detachPolicyFromRoleError = new Error(
          `Policy ${NAMES.instancePolicyName} not found.`,
        );
      } else {
        await client.send(
          new DetachRolePolicyCommand({
            RoleName: NAMES.instanceRoleName,
            PolicyArn: policy.Arn,
          }),
        );
      }
    } catch (e) {
      state.detachPolicyFromRoleError = e;
    }
  }),
  new ScenarioOutput("detachedPolicyFromRole", (state) => {
    if (state.detachPolicyFromRoleError) {
      console.error(state.detachPolicyFromRoleError);
      return MESSAGES.detachPolicyFromRoleError
        .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.detachedPolicyFromRole
      .replace("${INSTANCE_POLICY_NAME}", NAMES.instancePolicyName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstancePolicy", async (state) => {
    const client = new IAMClient({});
    const policy = await findPolicy(NAMES.instancePolicyName);

    if (!policy) {
      state.deletePolicyError = new Error(
        `Policy ${NAMES.instancePolicyName} not found.`,
      );
    } else {
      return client.send(
        new DeletePolicyCommand({
          PolicyArn: policy.Arn,
        }),
      );
    }
  }),
  new ScenarioOutput("deletePolicyResult", (state) => {
    if (state.deletePolicyError) {
      console.error(state.deletePolicyError);
      return MESSAGES.deletePolicyError.replace(
        "${INSTANCE_POLICY_NAME}",
        NAMES.instancePolicyName,
      );
    }
    return MESSAGES.deletedPolicy.replace(
      "${INSTANCE_POLICY_NAME}",
      NAMES.instancePolicyName,
    );
  }),
  new ScenarioAction("removeRoleFromInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          RoleName: NAMES.instanceRoleName,
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.removeRoleFromInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("removeRoleFromInstanceProfileResult", (state) => {
    if (state.removeRoleFromInstanceProfile) {
      console.error(state.removeRoleFromInstanceProfileError);
      return MESSAGES.removeRoleFromInstanceProfileError
        .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
        .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
    }
    return MESSAGES.removedRoleFromInstanceProfile
      .replace("${INSTANCE_PROFILE_NAME}", NAMES.instanceProfileName)
      .replace("${INSTANCE_ROLE_NAME}", NAMES.instanceRoleName);
  }),
  new ScenarioAction("deleteInstanceRole", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteRoleCommand({
          RoleName: NAMES.instanceRoleName,
        }),
      );
    } catch (e) {
      state.deleteInstanceRoleError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceRoleResult", (state) => {
    if (state.deleteInstanceRoleError) {
      console.error(state.deleteInstanceRoleError);
      return MESSAGES.deleteInstanceRoleError.replace(
        "${INSTANCE_ROLE_NAME}",
        NAMES.instanceRoleName,
      );
    }
    return MESSAGES.deletedInstanceRole.replace(
      "${INSTANCE_ROLE_NAME}",
      NAMES.instanceRoleName,
    );
  }),
  new ScenarioAction("deleteInstanceProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.instanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteInstanceProfileResult", (state) => {
    if (state.deleteInstanceProfileError) {
      console.error(state.deleteInstanceProfileError);
      return MESSAGES.deleteInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.instanceProfileName,
      );
    }
    return MESSAGES.deletedInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.instanceProfileName,
    );
  }),
  new ScenarioAction("deleteAutoScalingGroup", async (state) => {
    try {
      await terminateGroupInstances(NAMES.autoScalingGroupName);
      await retry({ intervalInMs: 60000, maxRetries: 60 }, async () => {
        await deleteAutoScalingGroup(NAMES.autoScalingGroupName);
      });
    } catch (e) {
      state.deleteAutoScalingGroupError = e;
    }
  }),
  new ScenarioOutput("deleteAutoScalingGroupResult", (state) => {
    if (state.deleteAutoScalingGroupError) {
      console.error(state.deleteAutoScalingGroupError);
      return MESSAGES.deleteAutoScalingGroupError.replace(
        "${AUTO_SCALING_GROUP_NAME}",
        NAMES.autoScalingGroupName,
      );
    }
    return MESSAGES.deletedAutoScalingGroup.replace(
      "${AUTO_SCALING_GROUP_NAME}",
      NAMES.autoScalingGroupName,
    );
  }),
  new ScenarioAction("deleteLaunchTemplate", async (state) => {
    const client = new EC2Client({});
    try {
      await client.send(
        new DeleteLaunchTemplateCommand({
          LaunchTemplateName: NAMES.launchTemplateName,
        }),
      );
    } catch (e) {
      state.deleteLaunchTemplateError = e;
    }
  }),
  new ScenarioOutput("deleteLaunchTemplateResult", (state) => {
    if (state.deleteLaunchTemplateError) {
      console.error(state.deleteLaunchTemplateError);
      return MESSAGES.deleteLaunchTemplateError.replace(
        "${LAUNCH_TEMPLATE_NAME}",
        NAMES.launchTemplateName,
      );
    }
    return MESSAGES.deletedLaunchTemplate.replace(
      "${LAUNCH_TEMPLATE_NAME}",
      NAMES.launchTemplateName,
    );
  }),
  new ScenarioAction("deleteLoadBalancer", async (state) => {
    try {
      const client = new ElasticLoadBalancingV2Client({});
      const loadBalancer = await findLoadBalancer(NAMES.loadBalancerName);
      await client.send(
        new DeleteLoadBalancerCommand({
          LoadBalancerArn: loadBalancer.LoadBalancerArn,
        }),
      );
      await retry({ intervalInMs: 1000, maxRetries: 60 }, async () => {
        const lb = await findLoadBalancer(NAMES.loadBalancerName);
        if (lb) {
          throw new Error("Load balancer still exists.");
        }
      });
    } catch (e) {
      state.deleteLoadBalancerError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerResult", (state) => {
    if (state.deleteLoadBalancerError) {
      console.error(state.deleteLoadBalancerError);
      return MESSAGES.deleteLoadBalancerError.replace(
        "${LB_NAME}",
        NAMES.loadBalancerName,
      );
    }
    return MESSAGES.deletedLoadBalancer.replace(
      "${LB_NAME}",
      NAMES.loadBalancerName,
    );
  }),
  new ScenarioAction("deleteLoadBalancerTargetGroup", async (state) => {
    const client = new ElasticLoadBalancingV2Client({});
    try {
      const { TargetGroups } = await client.send(
        new DescribeTargetGroupsCommand({
          Names: [NAMES.loadBalancerTargetGroupName],
        }),
      );

      await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
        client.send(
          new DeleteTargetGroupCommand({
            TargetGroupArn: TargetGroups[0].TargetGroupArn,
          }),
        ),
      );
    } catch (e) {
      state.deleteLoadBalancerTargetGroupError = e;
    }
  }),
  new ScenarioOutput("deleteLoadBalancerTargetGroupResult", (state) => {
    if (state.deleteLoadBalancerTargetGroupError) {
      console.error(state.deleteLoadBalancerTargetGroupError);
      return MESSAGES.deleteLoadBalancerTargetGroupError.replace(
        "${TARGET_GROUP_NAME}",
        NAMES.loadBalancerTargetGroupName,
      );
    }
    return MESSAGES.deletedLoadBalancerTargetGroup.replace(
      "${TARGET_GROUP_NAME}",
      NAMES.loadBalancerTargetGroupName,
    );
  }),
  new ScenarioAction("detachSsmOnlyRoleFromProfile", async (state) => {
    try {
      const client = new IAMClient({});
      await client.send(
        new RemoveRoleFromInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyRoleFromProfileError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyRoleFromProfileResult", (state) => {
    if (state.detachSsmOnlyRoleFromProfileError) {
      console.error(state.detachSsmOnlyRoleFromProfileError);
      return MESSAGES.detachSsmOnlyRoleFromProfileError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
    }
    return MESSAGES.detachedSsmOnlyRoleFromProfile
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${PROFILE_NAME}", NAMES.ssmOnlyInstanceProfileName);
  }),
  new ScenarioAction("detachSsmOnlyCustomRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.detachSsmOnlyCustomRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyCustomRolePolicyResult", (state) => {
    if (state.detachSsmOnlyCustomRolePolicyError) {
      console.error(state.detachSsmOnlyCustomRolePolicyError);
      return MESSAGES.detachSsmOnlyCustomRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
    }
    return MESSAGES.detachedSsmOnlyCustomRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", NAMES.ssmOnlyPolicyName);
  }),
  new ScenarioAction("detachSsmOnlyAWSRolePolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: NAMES.ssmOnlyRoleName,
          PolicyArn: "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore",
        }),
      );
    } catch (e) {
      state.detachSsmOnlyAWSRolePolicyError = e;
    }
  }),
  new ScenarioOutput("detachSsmOnlyAWSRolePolicyResult", (state) => {
    if (state.detachSsmOnlyAWSRolePolicyError) {
      console.error(state.detachSsmOnlyAWSRolePolicyError);
      return MESSAGES.detachSsmOnlyAWSRolePolicyError
        .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
        .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
    }
    return MESSAGES.detachedSsmOnlyAWSRolePolicy
      .replace("${ROLE_NAME}", NAMES.ssmOnlyRoleName)
      .replace("${POLICY_NAME}", "AmazonSSMManagedInstanceCore");
  }),
  new ScenarioAction("deleteSsmOnlyInstanceProfile", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteInstanceProfileCommand({
          InstanceProfileName: NAMES.ssmOnlyInstanceProfileName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyInstanceProfileError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyInstanceProfileResult", (state) => {
    if (state.deleteSsmOnlyInstanceProfileError) {
      console.error(state.deleteSsmOnlyInstanceProfileError);
      return MESSAGES.deleteSsmOnlyInstanceProfileError.replace(
        "${INSTANCE_PROFILE_NAME}",
        NAMES.ssmOnlyInstanceProfileName,
      );
    }
    return MESSAGES.deletedSsmOnlyInstanceProfile.replace(
      "${INSTANCE_PROFILE_NAME}",
      NAMES.ssmOnlyInstanceProfileName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyPolicy", async (state) => {
    try {
      const iamClient = new IAMClient({});
      const ssmOnlyPolicy = await findPolicy(NAMES.ssmOnlyPolicyName);
      await iamClient.send(
        new DeletePolicyCommand({
          PolicyArn: ssmOnlyPolicy.Arn,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyPolicyError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyPolicyResult", (state) => {
    if (state.deleteSsmOnlyPolicyError) {
      console.error(state.deleteSsmOnlyPolicyError);
      return MESSAGES.deleteSsmOnlyPolicyError.replace(
        "${POLICY_NAME}",
        NAMES.ssmOnlyPolicyName,
      );
    }
    return MESSAGES.deletedSsmOnlyPolicy.replace(
      "${POLICY_NAME}",
      NAMES.ssmOnlyPolicyName,
    );
  }),
  new ScenarioAction("deleteSsmOnlyRole", async (state) => {
    try {
      const iamClient = new IAMClient({});
      await iamClient.send(
        new DeleteRoleCommand({
          RoleName: NAMES.ssmOnlyRoleName,
        }),
      );
    } catch (e) {
      state.deleteSsmOnlyRoleError = e;
    }
  }),
  new ScenarioOutput("deleteSsmOnlyRoleResult", (state) => {
    if (state.deleteSsmOnlyRoleError) {
      console.error(state.deleteSsmOnlyRoleError);
      return MESSAGES.deleteSsmOnlyRoleError.replace(
        "${ROLE_NAME}",
        NAMES.ssmOnlyRoleName,
      );
    }
    return MESSAGES.deletedSsmOnlyRole.replace(
      "${ROLE_NAME}",
      NAMES.ssmOnlyRoleName,
    );
  }),
  new ScenarioAction(
    "revokeSecurityGroupIngress",
    async (
      /** @type {{ myIp: string, defaultSecurityGroup: { GroupId: string } }} */ state,
    ) => {
      const ec2Client = new EC2Client({});

      try {
        await ec2Client.send(
          new RevokeSecurityGroupIngressCommand({
            GroupId: state.defaultSecurityGroup.GroupId,
            CidrIp: `${state.myIp}/32`,
            FromPort: 80,
            ToPort: 80,
            IpProtocol: "tcp",
          }),
        );
      } catch (e) {
        state.revokeSecurityGroupIngressError = e;
      }
    },
  ),
  new ScenarioOutput("revokeSecurityGroupIngressResult", (state) => {
    if (state.revokeSecurityGroupIngressError) {
      console.error(state.revokeSecurityGroupIngressError);
      return MESSAGES.revokeSecurityGroupIngressError.replace(
        "${IP}",
        state.myIp,
      );
    }
    return MESSAGES.revokedSecurityGroupIngress.replace("${IP}", state.myIp);
  }),
];

/**
 * @param {string} policyName
 */
async function findPolicy(policyName) {
  const client = new IAMClient({});
  const paginatedPolicies = paginateListPolicies({ client }, {});
  for await (const page of paginatedPolicies) {
    const policy = page.Policies.find((p) => p.PolicyName === policyName);
    if (policy) {
      return policy;
    }
  }
}

/**
 * @param {string} groupName
 */
async function deleteAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  try {
    await client.send(
      new DeleteAutoScalingGroupCommand({
        AutoScalingGroupName: groupName,
      }),
    );
  } catch (err) {
    if (!(err instanceof Error)) {
      throw err;
    }
    console.log(err.name);
    throw err;
  }
}

/**
 * @param {string} groupName
 */
async function terminateGroupInstances(groupName) {
  const autoScalingClient = new AutoScalingClient({});
  const group = await findAutoScalingGroup(groupName);
  await autoScalingClient.send(
    new UpdateAutoScalingGroupCommand({
      AutoScalingGroupName: group.AutoScalingGroupName,
      MinSize: 0,
    }),
  );
  for (const i of group.Instances) {
    await retry({ intervalInMs: 1000, maxRetries: 30 }, () =>
      autoScalingClient.send(
        new TerminateInstanceInAutoScalingGroupCommand({
          InstanceId: i.InstanceId,
          ShouldDecrementDesiredCapacity: true,
        }),
      ),
    );
  }
}

async function findAutoScalingGroup(groupName) {
  const client = new AutoScalingClient({});
  const paginatedGroups = paginateDescribeAutoScalingGroups({ client }, {});
  for await (const page of paginatedGroups) {
    const group = page.AutoScalingGroups.find(
      (g) => g.AutoScalingGroupName === groupName,
    );
    if (group) {
      return group;
    }
  }
  throw new Error(`Auto scaling group ${groupName} not found.`);
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/AttachLoadBalancerTargetGroupsCommand)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/CreateAutoScalingGroupCommand)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/CreateInstanceProfileCommand)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/CreateLaunchTemplateCommand)
  + [CreateListener](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateListenerCommand)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateLoadBalancerCommand)
  + [CreateTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/CreateTargetGroupCommand)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DeleteAutoScalingGroupCommand)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/DeleteInstanceProfileCommand)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DeleteLaunchTemplateCommand)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteLoadBalancerCommand)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DeleteTargetGroupCommand)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/DescribeAutoScalingGroupsCommand)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeAvailabilityZonesCommand)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeIamInstanceProfileAssociationsCommand)
  + [DescribeInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeInstancesCommand)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeLoadBalancersCommand)
  + [DescribeSubnets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeSubnetsCommand)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetGroupsCommand)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/elastic-load-balancing-v2/command/DescribeTargetHealthCommand)
  + [DescribeVpcs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/DescribeVpcsCommand)
  + [RebootInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/RebootInstancesCommand)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ec2/command/ReplaceIamInstanceProfileAssociationCommand)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/TerminateInstanceInAutoScalingGroupCommand)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/auto-scaling/command/UpdateAutoScalingGroupCommand)

# AWS IoT SiteWise SDK for JavaScript (v3) を使用した例
<a name="javascript_3_iotsitewise_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT SiteWise。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoT SiteWiseは
<a name="iotsitewise_Hello_javascript_3_topic"></a>

次のコード例は、 AWS IoT SiteWiseの使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  paginateListAssetModels,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";

// Call ListDocuments and display the result.
export const main = async () => {
  const client = new IoTSiteWiseClient();
  const listAssetModelsPaginated = [];
  console.log(
    "Hello, AWS Systems Manager! Let's list some of your documents:\n",
  );
  try {
    // The paginate function is a wrapper around the base command.
    const paginator = paginateListAssetModels({ client }, { maxResults: 5 });
    for await (const page of paginator) {
      listAssetModelsPaginated.push(...page.assetModelSummaries);
    }
  } catch (caught) {
    console.error(`There was a problem saying hello: ${caught.message}`);
    throw caught;
  }
  for (const { name, creationDate } of listAssetModelsPaginated) {
    console.log(`${name} - ${creationDate}`);
  }
};

// Call function if run directly.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API の詳細については、「[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/ListAssetModelsCommand)」の「*ListAssetModels*」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iotsitewise_Scenario_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT SiteWise アセットモデルを作成します。
+  AWS IoT SiteWise アセットを作成します。
+ プロパティ ID 値を取得します。
+  AWS IoT SiteWise アセットにデータを送信します。
+ Asset AWS IoT SiteWise プロパティの値を取得します。
+  AWS IoT SiteWise ポータルを作成します。
+  AWS IoT SiteWise ゲートウェイを作成します。
+  AWS IoT SiteWise ゲートウェイを記述します。
+  AWS IoT SiteWise アセットを削除します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
  //} from "@aws-doc-sdk-examples/lib/scenario/index.js";
} from "../../libs/scenario/index.js";
import {
  IoTSiteWiseClient,
  CreateAssetModelCommand,
  CreateAssetCommand,
  ListAssetModelPropertiesCommand,
  BatchPutAssetPropertyValueCommand,
  GetAssetPropertyValueCommand,
  CreatePortalCommand,
  DescribePortalCommand,
  CreateGatewayCommand,
  DescribeGatewayCommand,
  DeletePortalCommand,
  DeleteGatewayCommand,
  DeleteAssetCommand,
  DeleteAssetModelCommand,
  DescribeAssetModelCommand,
} from "@aws-sdk/client-iotsitewise";
import {
  CloudFormationClient,
  CreateStackCommand,
  DeleteStackCommand,
  DescribeStacksCommand,
  waitUntilStackExists,
  waitUntilStackCreateComplete,
  waitUntilStackDeleteComplete,
} from "@aws-sdk/client-cloudformation";
import { wait } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import { parseArgs } from "node:util";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const stackName = "SiteWiseBasicsStack";

/**
 * @typedef {{
 *   iotSiteWiseClient: import('@aws-sdk/client-iotsitewise').IotSiteWiseClient,
 *   cloudFormationClient: import('@aws-sdk/client-cloudformation').CloudFormationClient,
 *   stackName,
 *   stack,
 *   askToDeleteResources: true,
 *   asset: {assetName: "MyAsset1"},
 *   assetModel: {assetModelName: "MyAssetModel1"},
 *   portal: {portalName: "MyPortal1"},
 *   gateway: {gatewayName: "MyGateway1"},
 *   propertyIds: [],
 *   contactEmail: "user@mydomain.com",
 *   thing: "MyThing1",
 *   sampleData: { temperature: 23.5, humidity: 65.0}
 * }} State
 */

/**
 * Used repeatedly to have the user press enter.
 * @type {ScenarioInput}
 */
const pressEnter = new ScenarioInput("continue", "Press Enter to continue", {
  type: "confirm",
});

const greet = new ScenarioOutput(
  "greet",
  `AWS IoT SiteWise is a fully managed industrial software-as-a-service (SaaS) that makes it easy to collect, store, organize, and monitor data from industrial equipment and processes. It is designed to help industrial and manufacturing organizations collect data from their equipment and processes, and use that data to make informed decisions about their operations.
One of the key features of AWS IoT SiteWise is its ability to connect to a wide range of industrial equipment and systems, including programmable logic controllers (PLCs), sensors, and other industrial devices. It can collect data from these devices and organize it into a unified data model, making it easier to analyze and gain insights from the data. AWS IoT SiteWise also provides tools for visualizing the data, setting up alarms and alerts, and generating reports.
Another key feature of AWS IoT SiteWise is its ability to scale to handle large volumes of data. It can collect and store data from thousands of devices and process millions of data points per second, making it suitable for large-scale industrial operations. Additionally, AWS IoT SiteWise is designed to be secure and compliant, with features like role-based access controls, data encryption, and integration with other AWS services for additional security and compliance features.

Let's get started...`,
  { header: true },
);

const displayBuildCloudFormationStack = new ScenarioOutput(
  "displayBuildCloudFormationStack",
  "This scenario uses AWS CloudFormation to create an IAM role that is required for this scenario. The stack will now be deployed.",
);

const sdkBuildCloudFormationStack = new ScenarioAction(
  "sdkBuildCloudFormationStack",
  async (/** @type {State} */ state) => {
    try {
      const data = readFileSync(
        `${__dirname}/../../../../resources/cfn/iotsitewise_basics/SitewiseRoles-template.yml`,
        "utf8",
      );
      await state.cloudFormationClient.send(
        new CreateStackCommand({
          StackName: stackName,
          TemplateBody: data,
          Capabilities: ["CAPABILITY_IAM"],
        }),
      );
      await waitUntilStackExists(
        { client: state.cloudFormationClient },
        { StackName: stackName },
      );
      await waitUntilStackCreateComplete(
        { client: state.cloudFormationClient },
        { StackName: stackName },
      );
      const stack = await state.cloudFormationClient.send(
        new DescribeStacksCommand({
          StackName: stackName,
        }),
      );
      state.stack = stack.Stacks[0].Outputs[0];
      console.log(`The ARN of the IAM role is ${state.stack.OutputValue}`);
    } catch (caught) {
      console.error(caught.message);
      throw caught;
    }
  },
);

const displayCreateAWSSiteWiseAssetModel = new ScenarioOutput(
  "displayCreateAWSSiteWiseAssetModel",
  `1. Create an AWS SiteWise Asset Model
An AWS IoT SiteWise Asset Model is a way to represent the physical assets, such as equipment, processes, and systems, that exist in an industrial environment. This model provides a structured and hierarchical representation of these assets, allowing users to define the relationships and properties of each asset.
         
This scenario creates two asset model properties: temperature and humidity.`,
);

const sdkCreateAWSSiteWiseAssetModel = new ScenarioAction(
  "sdkCreateAWSSiteWiseAssetModel",
  async (/** @type {State} */ state) => {
    let assetModelResponse;
    try {
      assetModelResponse = await state.iotSiteWiseClient.send(
        new CreateAssetModelCommand({
          assetModelName: state.assetModel.assetModelName,
          assetModelProperties: [
            {
              name: "Temperature",
              dataType: "DOUBLE",
              type: {
                measurement: {},
              },
            },
            {
              name: "Humidity",
              dataType: "DOUBLE",
              type: {
                measurement: {},
              },
            },
          ],
        }),
      );
      state.assetModel.assetModelId = assetModelResponse.assetModelId;
      console.log(
        `Asset Model successfully created. Asset Model ID: ${state.assetModel.assetModelId}`,
      );
    } catch (caught) {
      if (caught.name === "ResourceAlreadyExistsException") {
        console.log(
          `The Asset Model ${state.assetModel.assetModelName} already exists.`,
        );
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displayCreateAWSIoTSiteWiseAssetModel = new ScenarioOutput(
  "displayCreateAWSIoTSiteWiseAssetModel",
  `2. Create an AWS IoT SiteWise Asset
The IoT SiteWise model that we just created defines the structure and metadata for your physical assets. Now we create an asset from the asset model.

Let's wait 30 seconds for the asset to be ready.`,
);

const waitThirtySeconds = new ScenarioAction("waitThirtySeconds", async () => {
  await wait(30); // wait 30 seconds
  console.log("Time's up! Let's check the asset's status.");
});

const sdkCreateAWSIoTSiteWiseAssetModel = new ScenarioAction(
  "sdkCreateAWSIoTSiteWiseAssetModel",
  async (/** @type {State} */ state) => {
    try {
      const assetResponse = await state.iotSiteWiseClient.send(
        new CreateAssetCommand({
          assetModelId: state.assetModel.assetModelId,
          assetName: state.asset.assetName,
        }),
      );
      state.asset.assetId = assetResponse.assetId;
      console.log(`Asset created with ID: ${state.asset.assetId}`);
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(
          `The Asset ${state.assetModel.assetModelName} was not found.`,
        );
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displayRetrievePropertyId = new ScenarioOutput(
  "displayRetrievePropertyId",
  `3. Retrieve the property ID values

To send data to an asset, we need to get the property ID values. In this scenario, we access the temperature and humidity property ID values.`,
);

const sdkRetrievePropertyId = new ScenarioAction(
  "sdkRetrievePropertyId",
  async (state) => {
    try {
      const retrieveResponse = await state.iotSiteWiseClient.send(
        new ListAssetModelPropertiesCommand({
          assetModelId: state.assetModel.assetModelId,
        }),
      );
      for (const retrieveResponseKey in retrieveResponse.assetModelPropertySummaries) {
        if (
          retrieveResponse.assetModelPropertySummaries[retrieveResponseKey]
            .name === "Humidity"
        ) {
          state.propertyIds.Humidity =
            retrieveResponse.assetModelPropertySummaries[
              retrieveResponseKey
            ].id;
        }
        if (
          retrieveResponse.assetModelPropertySummaries[retrieveResponseKey]
            .name === "Temperature"
        ) {
          state.propertyIds.Temperature =
            retrieveResponse.assetModelPropertySummaries[
              retrieveResponseKey
            ].id;
        }
      }
      console.log(`The Humidity propertyId is ${state.propertyIds.Humidity}`);
      console.log(
        `The Temperature propertyId is ${state.propertyIds.Temperature}`,
      );
    } catch (caught) {
      if (caught.name === "IoTSiteWiseException") {
        console.log(
          `There was a problem retrieving the properties: ${caught.message}`,
        );
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displaySendDataToIoTSiteWiseAsset = new ScenarioOutput(
  "displaySendDataToIoTSiteWiseAsset",
  `4. Send data to an AWS IoT SiteWise Asset

By sending data to an IoT SiteWise Asset, you can aggregate data from multiple sources, normalize the data into a standard format, and store it in a centralized location. This makes it easier to analyze and gain insights from the data.

In this example, we generate sample temperature and humidity data and send it to the AWS IoT SiteWise asset.`,
);

const sdkSendDataToIoTSiteWiseAsset = new ScenarioAction(
  "sdkSendDataToIoTSiteWiseAsset",
  async (state) => {
    try {
      const sendResponse = await state.iotSiteWiseClient.send(
        new BatchPutAssetPropertyValueCommand({
          entries: [
            {
              entryId: "entry-3",
              assetId: state.asset.assetId,
              propertyId: state.propertyIds.Humidity,
              propertyValues: [
                {
                  value: {
                    doubleValue: state.sampleData.humidity,
                  },
                  timestamp: {
                    timeInSeconds: Math.floor(Date.now() / 1000),
                  },
                },
              ],
            },
            {
              entryId: "entry-4",
              assetId: state.asset.assetId,
              propertyId: state.propertyIds.Temperature,
              propertyValues: [
                {
                  value: {
                    doubleValue: state.sampleData.temperature,
                  },
                  timestamp: {
                    timeInSeconds: Math.floor(Date.now() / 1000),
                  },
                },
              ],
            },
          ],
        }),
      );
      console.log("The data was sent successfully.");
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(`The Asset ${state.asset.assetName} was not found.`);
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displayRetrieveValueOfIoTSiteWiseAsset = new ScenarioOutput(
  "displayRetrieveValueOfIoTSiteWiseAsset",
  `5. Retrieve the value of the IoT SiteWise Asset property

IoT SiteWise is an AWS service that allows you to collect, process, and analyze industrial data from connected equipment and sensors. One of the key benefits of reading an IoT SiteWise property is the ability to gain valuable insights from your industrial data.`,
);

const sdkRetrieveValueOfIoTSiteWiseAsset = new ScenarioAction(
  "sdkRetrieveValueOfIoTSiteWiseAsset",
  async (/** @type {State} */ state) => {
    try {
      const temperatureResponse = await state.iotSiteWiseClient.send(
        new GetAssetPropertyValueCommand({
          assetId: state.asset.assetId,
          propertyId: state.propertyIds.Temperature,
        }),
      );
      const humidityResponse = await state.iotSiteWiseClient.send(
        new GetAssetPropertyValueCommand({
          assetId: state.asset.assetId,
          propertyId: state.propertyIds.Humidity,
        }),
      );
      console.log(
        `The property value for Temperature is ${temperatureResponse.propertyValue.value.doubleValue}`,
      );
      console.log(
        `The property value for Humidity is ${humidityResponse.propertyValue.value.doubleValue}`,
      );
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(`The Asset ${state.asset.assetName} was not found.`);
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displayCreateIoTSiteWisePortal = new ScenarioOutput(
  "displayCreateIoTSiteWisePortal",
  `6. Create an IoT SiteWise Portal

An IoT SiteWise Portal allows you to aggregate data from multiple industrial sources, such as sensors, equipment, and control systems, into a centralized platform.`,
);

const sdkCreateIoTSiteWisePortal = new ScenarioAction(
  "sdkCreateIoTSiteWisePortal",
  async (/** @type {State} */ state) => {
    try {
      const createPortalResponse = await state.iotSiteWiseClient.send(
        new CreatePortalCommand({
          portalName: state.portal.portalName,
          portalContactEmail: state.contactEmail,
          roleArn: state.stack.OutputValue,
        }),
      );
      state.portal = { ...state.portal, ...createPortalResponse };
      await wait(5); // Allow the portal to properly propagate.
      console.log(
        `Portal created successfully. Portal ID ${createPortalResponse.portalId}`,
      );
    } catch (caught) {
      if (caught.name === "IoTSiteWiseException") {
        console.log(
          `There was a problem creating the Portal: ${caught.message}.`,
        );
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displayDescribePortal = new ScenarioOutput(
  "displayDescribePortal",
  `7. Describe the Portal

In this step, we get a description of the portal and display the portal URL.`,
);

const sdkDescribePortal = new ScenarioAction(
  "sdkDescribePortal",
  async (/** @type {State} */ state) => {
    try {
      const describePortalResponse = await state.iotSiteWiseClient.send(
        new DescribePortalCommand({
          portalId: state.portal.portalId,
        }),
      );
      console.log(`Portal URL: ${describePortalResponse.portalStartUrl}`);
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(`The Portal ${state.portal.portalName} was not found.`);
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displayCreateIoTSiteWiseGateway = new ScenarioOutput(
  "displayCreateIoTSiteWiseGateway",
  `8. Create an IoT SiteWise Gateway

IoT SiteWise Gateway serves as the bridge between industrial equipment, sensors, and the cloud-based IoT SiteWise service. It is responsible for securely collecting, processing, and transmitting data from various industrial assets to the IoT SiteWise platform, enabling real-time monitoring, analysis, and optimization of industrial operations.`,
);

const sdkCreateIoTSiteWiseGateway = new ScenarioAction(
  "sdkCreateIoTSiteWiseGateway",
  async (/** @type {State} */ state) => {
    try {
      const createGatewayResponse = await state.iotSiteWiseClient.send(
        new CreateGatewayCommand({
          gatewayName: state.gateway.gatewayName,
          gatewayPlatform: {
            greengrassV2: {
              coreDeviceThingName: state.thing,
            },
          },
        }),
      );
      console.log(
        `Gateway creation completed successfully. ID is ${createGatewayResponse.gatewayId}`,
      );
      state.gateway.gatewayId = createGatewayResponse.gatewayId;
    } catch (caught) {
      if (caught.name === "IoTSiteWiseException") {
        console.log(
          `There was a problem creating the gateway: ${caught.message}.`,
        );
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const displayDescribeIoTSiteWiseGateway = new ScenarioOutput(
  "displayDescribeIoTSiteWiseGateway",
  "9. Describe the IoT SiteWise Gateway",
);

const sdkDescribeIoTSiteWiseGateway = new ScenarioAction(
  "sdkDescribeIoTSiteWiseGateway",
  async (/** @type {State} */ state) => {
    try {
      const describeGatewayResponse = await state.iotSiteWiseClient.send(
        new DescribeGatewayCommand({
          gatewayId: state.gateway.gatewayId,
        }),
      );
      console.log("Gateway creation completed successfully.");
      console.log(`Gateway Name: ${describeGatewayResponse.gatewayName}`);
      console.log(`Gateway ARN: ${describeGatewayResponse.gatewayArn}`);
      console.log(
        `Gateway Platform: ${Object.keys(describeGatewayResponse.gatewayPlatform)}`,
      );
      console.log(
        `Gateway Creation Date: ${describeGatewayResponse.creationDate}`,
      );
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(`The Gateway ${state.gateway.gatewayId} was not found.`);
        throw caught;
      }
      console.error(`${caught.message}`);
      throw caught;
    }
  },
);

const askToDeleteResources = new ScenarioInput(
  "askToDeleteResources",
  `10. Delete the AWS IoT SiteWise Assets
  
Before you can delete the Asset Model, you must delete the assets.`,
  { type: "confirm" },
);

const displayConfirmDeleteResources = new ScenarioAction(
  "displayConfirmDeleteResources",
  async (/** @type {State} */ state) => {
    if (state.askToDeleteResources) {
      return "You selected to delete the SiteWise assets.";
    }
    return "The resources will not be deleted. Please delete them manually to avoid charges.";
  },
);

const sdkDeleteResources = new ScenarioAction(
  "sdkDeleteResources",
  async (/** @type {State} */ state) => {
    await wait(10); // Give the portal status time to catch up.
    try {
      await state.iotSiteWiseClient.send(
        new DeletePortalCommand({
          portalId: state.portal.portalId,
        }),
      );
      console.log(
        `Portal ${state.portal.portalName} was deleted successfully.`,
      );
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(`The Portal ${state.portal.portalName} was not found.`);
      } else {
        console.log(`When trying to delete the portal: ${caught.message}`);
      }
    }

    try {
      await state.iotSiteWiseClient.send(
        new DeleteGatewayCommand({
          gatewayId: state.gateway.gatewayId,
        }),
      );
      console.log(
        `Gateway ${state.gateway.gatewayName} was deleted successfully.`,
      );
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(`The Gateway ${state.gateway.gatewayId} was not found.`);
      } else {
        console.log(`When trying to delete the gateway: ${caught.message}`);
      }
    }

    try {
      await state.iotSiteWiseClient.send(
        new DeleteAssetCommand({
          assetId: state.asset.assetId,
        }),
      );
      await wait(5); // Allow the delete to finish.
      console.log(`Asset ${state.asset.assetName} was deleted successfully.`);
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(`The Asset ${state.asset.assetName} was not found.`);
      } else {
        console.log(`When deleting the asset: ${caught.message}`);
      }
    }

    await wait(30); // Allow asset deletion to finish.
    try {
      await state.iotSiteWiseClient.send(
        new DeleteAssetModelCommand({
          assetModelId: state.assetModel.assetModelId,
        }),
      );
      console.log(
        `Asset Model ${state.assetModel.assetModelName} was deleted successfully.`,
      );
    } catch (caught) {
      if (caught.name === "ResourceNotFoundException") {
        console.log(
          `The Asset Model ${state.assetModel.assetModelName} was not found.`,
        );
      } else {
        console.log(`When deleting the asset model: ${caught.message}`);
      }
    }

    try {
      await state.cloudFormationClient.send(
        new DeleteStackCommand({
          StackName: stackName,
        }),
      );
      await waitUntilStackDeleteComplete(
        { client: state.cloudFormationClient },
        { StackName: stackName },
      );
      console.log("The stack was deleted successfully.");
    } catch (caught) {
      console.log(
        `${caught.message}. The stack was NOT deleted. Please clean up the resources manually.`,
      );
    }
  },
  { skipWhen: (/** @type {{}} */ state) => !state.askToDeleteResources },
);

const goodbye = new ScenarioOutput(
  "goodbye",
  "This concludes the IoT Sitewise Basics scenario for the AWS Javascript SDK v3. Thank you!",
);

const myScenario = new Scenario(
  "IoTSiteWise Basics",
  [
    greet,
    pressEnter,
    displayBuildCloudFormationStack,
    sdkBuildCloudFormationStack,
    pressEnter,
    displayCreateAWSSiteWiseAssetModel,
    sdkCreateAWSSiteWiseAssetModel,
    displayCreateAWSIoTSiteWiseAssetModel,
    pressEnter,
    waitThirtySeconds,
    sdkCreateAWSIoTSiteWiseAssetModel,
    pressEnter,
    displayRetrievePropertyId,
    sdkRetrievePropertyId,
    pressEnter,
    displaySendDataToIoTSiteWiseAsset,
    sdkSendDataToIoTSiteWiseAsset,
    pressEnter,
    displayRetrieveValueOfIoTSiteWiseAsset,
    sdkRetrieveValueOfIoTSiteWiseAsset,
    pressEnter,
    displayCreateIoTSiteWisePortal,
    sdkCreateIoTSiteWisePortal,
    pressEnter,
    displayDescribePortal,
    sdkDescribePortal,
    pressEnter,
    displayCreateIoTSiteWiseGateway,
    sdkCreateIoTSiteWiseGateway,
    pressEnter,
    displayDescribeIoTSiteWiseGateway,
    sdkDescribeIoTSiteWiseGateway,
    pressEnter,
    askToDeleteResources,
    displayConfirmDeleteResources,
    sdkDeleteResources,
    goodbye,
  ],
  {
    iotSiteWiseClient: new IoTSiteWiseClient({}),
    cloudFormationClient: new CloudFormationClient({}),
    asset: { assetName: "MyAsset1" },
    assetModel: { assetModelName: "MyAssetModel1" },
    portal: { portalName: "MyPortal1" },
    gateway: { gatewayName: "MyGateway1" },
    propertyIds: [],
    contactEmail: "user@mydomain.com",
    thing: "MyThing1",
    sampleData: { temperature: 23.5, humidity: 65.0 },
  },
);

/** @type {{ stepHandlerOptions: StepHandlerOptions }} */
export const main = async (stepHandlerOptions) => {
  await myScenario.run(stepHandlerOptions);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      yes: {
        type: "boolean",
        short: "y",
      },
    },
  });
  main({ confirmAll: values.yes });
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [BatchPutAssetPropertyValue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/BatchPutAssetPropertyValueCommand)
  + [CreateAsset](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/CreateAssetCommand)
  + [CreateAssetModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/CreateAssetModelCommand)
  + [CreateGateway](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/CreateGatewayCommand)
  + [DeleteAsset](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DeleteAssetCommand)
  + [DeleteAssetModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DeleteAssetModelCommand)
  + [DeleteGateway](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DeleteGatewayCommand)
  + [DescribeAssetModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DescribeAssetModelCommand)
  + [DescribeGateway](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DescribeGatewayCommand)
  + [GetAssetPropertyValue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/GetAssetPropertyValueCommand)
  + [ListAssetModelProperties](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/ListAssetModelPropertiesCommand)
  + [ListAssetModels](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/ListAssetModelsCommand)

## アクション
<a name="actions"></a>

### `BatchPutAssetPropertyValue`
<a name="iotsitewise_BatchPutAssetPropertyValue_javascript_3_topic"></a>

次のコード例は、`BatchPutAssetPropertyValue` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  BatchPutAssetPropertyValueCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Batch put asset property values.
 * @param {{ entries : array }}
 */
export const main = async ({ entries }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const result = await client.send(
      new BatchPutAssetPropertyValueCommand({
        entries: entries,
      }),
    );
    console.log("Asset properties batch put successfully.");
    return result;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(`${caught.message}. A resource could not be found.`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[BatchPutAssetPropertyValue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/BatchPutAssetPropertyValueCommand)」を参照してください。

### `CreateAsset`
<a name="iotsitewise_CreateAsset_javascript_3_topic"></a>

次のコード例は、`CreateAsset` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  CreateAssetCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Create an Asset.
 * @param {{ assetName : string, assetModelId: string }}
 */
export const main = async ({ assetName, assetModelId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const result = await client.send(
      new CreateAssetCommand({
        assetName: assetName, // The name to give the Asset.
        assetModelId: assetModelId, // The ID of the asset model from which to create the asset.
      }),
    );
    console.log("Asset created successfully.");
    return result;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(
        `${caught.message}. The asset model could not be found. Please check the asset model id.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateAsset](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/CreateAssetCommand)」を参照してください。

### `CreateAssetModel`
<a name="iotsitewise_CreateAssetModel_javascript_3_topic"></a>

次のコード例は、`CreateAssetModel` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  CreateAssetModelCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Create an Asset Model.
 * @param {{ assetName : string, assetModelId: string }}
 */
export const main = async ({ assetModelName, assetModelId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const result = await client.send(
      new CreateAssetModelCommand({
        assetModelName: assetModelName, // The name to give the Asset Model.
      }),
    );
    console.log("Asset model created successfully.");
    return result;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "IoTSiteWiseError") {
      console.warn(
        `${caught.message}. There was a problem creating the asset model.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/CreateAssetModelCommand)」の「*CreateAssetModel*」を参照してください。

### `CreateGateway`
<a name="iotsitewise_CreateGateway_javascript_3_topic"></a>

次のコード例は、`CreateGateway` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  CreateGatewayCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Create a Gateway.
 * @param {{  }}
 */
export const main = async ({ gatewayName }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const result = await client.send(
      new CreateGatewayCommand({
        gatewayName: gatewayName, // The name to give the created Gateway.
      }),
    );
    console.log("Gateway created successfully.");
    return result;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "IoTSiteWiseError") {
      console.warn(
        `${caught.message}. There was a problem creating the Gateway.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateGateway](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/CreateGatewayCommand)」を参照してください。

### `DeleteAsset`
<a name="iotsitewise_DeleteAsset_javascript_3_topic"></a>

次の例は、`DeleteAsset` を使用する方法を説明しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  DeleteAssetCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Delete an asset.
 * @param {{ assetId : string }}
 */
export const main = async ({ assetId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    await client.send(
      new DeleteAssetCommand({
        assetId: assetId, // The model id to delete.
      }),
    );
    console.log("Asset deleted successfully.");
    return { assetDeleted: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(
        `${caught.message}. There was a problem deleting the asset.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DeleteAssetCommand)」の「*DeleteAsset*」を参照してください。

### `DeleteAssetModel`
<a name="iotsitewise_DeleteAssetModel_javascript_3_topic"></a>

次のコード例は、`DeleteAssetModel` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  DeleteAssetModelCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Delete an asset model.
 * @param {{ assetModelId : string }}
 */
export const main = async ({ assetModelId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    await client.send(
      new DeleteAssetModelCommand({
        assetModelId: assetModelId, // The model id to delete.
      }),
    );
    console.log("Asset model deleted successfully.");
    return { assetModelDeleted: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(
        `${caught.message}. There was a problem deleting the asset model.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DeleteAssetModelCommand)」の「*DeleteAssetModel*」を参照してください。

### `DeleteGateway`
<a name="iotsitewise_DeleteGateway_javascript_3_topic"></a>

次のコード例は、`DeleteGateway` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  DeleteGatewayCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Create an SSM document.
 * @param {{ content: string, name: string, documentType?: DocumentType }}
 */
export const main = async ({ gatewayId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    await client.send(
      new DeleteGatewayCommand({
        gatewayId: gatewayId, // The ID of the Gateway to describe.
      }),
    );
    console.log("Gateway deleted successfully.");
    return { gatewayDeleted: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(
        `${caught.message}. The Gateway could not be found. Please check the Gateway Id.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteGateway](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DeleteGatewayCommand)」を参照してください。

### `DescribeAssetModel`
<a name="iotsitewise_DescribeAssetModel_javascript_3_topic"></a>

次の例は、`DescribeAssetModel` を使用する方法を説明しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  DescribeAssetModelCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Describe an asset model.
 * @param {{ assetModelId : string }}
 */
export const main = async ({ assetModelId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const { assetModelDescription } = await client.send(
      new DescribeAssetModelCommand({
        assetModelId: assetModelId, // The ID of the Gateway to describe.
      }),
    );
    console.log("Asset model information retrieved successfully.");
    return { assetModelDescription: assetModelDescription };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(
        `${caught.message}. The asset model could not be found. Please check the asset model id.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeAssetModel](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DescribeAssetModelCommand)」を参照してください。

### `DescribeGateway`
<a name="iotsitewise_DescribeGateway_javascript_3_topic"></a>

次のコード例は、`DescribeGateway` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  DescribeGatewayCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Create an SSM document.
 * @param {{ content: string, name: string, documentType?: DocumentType }}
 */
export const main = async ({ gatewayId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const { gatewayDescription } = await client.send(
      new DescribeGatewayCommand({
        gatewayId: gatewayId, // The ID of the Gateway to describe.
      }),
    );
    console.log("Gateway information retrieved successfully.");
    return { gatewayDescription: gatewayDescription };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(
        `${caught.message}. The Gateway could not be found. Please check the Gateway Id.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeGateway](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/DescribeGatewayCommand)」を参照してください。

### `GetAssetPropertyValue`
<a name="iotsitewise_GetAssetPropertyValue_javascript_3_topic"></a>

次の例は、`GetAssetPropertyValue` を使用する方法を説明しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  GetAssetPropertyValueCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * Describe an asset property value.
 * @param {{ entryId : string }}
 */
export const main = async ({ entryId }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const result = await client.send(
      new GetAssetPropertyValueCommand({
        entryId: entryId, // The ID of the Gateway to describe.
      }),
    );
    console.log("Asset property information retrieved successfully.");
    return result;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ResourceNotFound") {
      console.warn(
        `${caught.message}. The asset property entry could not be found. Please check the entry id.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetAssetPropertyValue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/GetAssetPropertyValueCommand)」を参照してください。

### `ListAssetModels`
<a name="iotsitewise_ListAssetModels_javascript_3_topic"></a>

次のコード例は、`ListAssetModels` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import {
  ListAssetModelsCommand,
  IoTSiteWiseClient,
} from "@aws-sdk/client-iotsitewise";
import { parseArgs } from "node:util";

/**
 * List asset models.
 * @param {{ assetModelTypes : array }}
 */
export const main = async ({ assetModelTypes = [] }) => {
  const client = new IoTSiteWiseClient({});
  try {
    const result = await client.send(
      new ListAssetModelsCommand({
        assetModelTypes: assetModelTypes, // The model types to list
      }),
    );
    console.log("Asset model types retrieved successfully.");
    return result;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "IoTSiteWiseError") {
      console.warn(
        `${caught.message}. There was a problem listing the asset model types.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「[AWS SDK for JavaScript API リファレンス](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iotsitewise/command/ListAssetModelsCommand)」の「*ListAssetModels*」を参照してください。

# SDK for JavaScript (v3) を使用した Kinesis の例
<a name="javascript_3_kinesis_code_examples"></a>

次のコード例は、Kinesis で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `PutRecords`
<a name="kinesis_PutRecords_javascript_3_topic"></a>

次のコード例は、`PutRecords` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import { PutRecordsCommand, KinesisClient } from "@aws-sdk/client-kinesis";

/**
 * Put multiple records into a Kinesis stream.
 * @param {{ streamArn: string }} config
 */
export const main = async ({ streamArn }) => {
  const client = new KinesisClient({});
  try {
    await client.send(
      new PutRecordsCommand({
        StreamARN: streamArn,
        Records: [
          {
            Data: new Uint8Array(),
            /**
             * Determines which shard in the stream the data record is assigned to.
             * Partition keys are Unicode strings with a maximum length limit of 256
             * characters for each key. Amazon Kinesis Data Streams uses the partition
             * key as input to a hash function that maps the partition key and
             * associated data to a specific shard.
             */
            PartitionKey: "TEST_KEY",
          },
          {
            Data: new Uint8Array(),
            PartitionKey: "TEST_KEY",
          },
        ],
      }),
    );
  } catch (caught) {
    if (caught instanceof Error) {
      //
    } else {
      throw caught;
    }
  }
};

// Call function if run directly.
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const options = {
    streamArn: {
      type: "string",
      description: "The ARN of the stream.",
    },
  };

  const { values } = parseArgs({ options });
  main(values);
}
```
+  API の詳細については、「**AWS SDK for JavaScript API リファレンス」の「[PutRecords](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/kinesis/command/PutRecordsCommand)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_javascript_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const record of event.Records) {
    try {
      console.log(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      console.log(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      console.error(`An error occurred ${err}`);
      throw err;
    }
  }
  console.log(`Successfully processed ${event.Records.length} records.`);
};

async function getRecordDataAsync(payload) {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```
TypeScript を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
  KinesisStreamEvent,
  Context,
  KinesisStreamHandler,
  KinesisStreamRecordPayload,
} from "aws-lambda";
import { Buffer } from "buffer";
import { Logger } from "@aws-lambda-powertools/logger";

const logger = new Logger({
  logLevel: "INFO",
  serviceName: "kinesis-stream-handler-sample",
});

export const functionHandler: KinesisStreamHandler = async (
  event: KinesisStreamEvent,
  context: Context
): Promise<void> => {
  for (const record of event.Records) {
    try {
      logger.info(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      logger.info(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      logger.error(`An error occurred ${err}`);
      throw err;
    }
    logger.info(`Successfully processed ${event.Records.length} records.`);
  }
};

async function getRecordDataAsync(
  payload: KinesisStreamRecordPayload
): Promise<string> {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_javascript_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Javascript を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const record of event.Records) {
    try {
      console.log(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      console.log(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      console.error(`An error occurred ${err}`);
      /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
      return {
        batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }],
      };
    }
  }
  console.log(`Successfully processed ${event.Records.length} records.`);
  return { batchItemFailures: [] };
};

async function getRecordDataAsync(payload) {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```
TypeScript を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
  KinesisStreamEvent,
  Context,
  KinesisStreamHandler,
  KinesisStreamRecordPayload,
  KinesisStreamBatchResponse,
} from "aws-lambda";
import { Buffer } from "buffer";
import { Logger } from "@aws-lambda-powertools/logger";

const logger = new Logger({
  logLevel: "INFO",
  serviceName: "kinesis-stream-handler-sample",
});

export const functionHandler: KinesisStreamHandler = async (
  event: KinesisStreamEvent,
  context: Context
): Promise<KinesisStreamBatchResponse> => {
  for (const record of event.Records) {
    try {
      logger.info(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      logger.info(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      logger.error(`An error occurred ${err}`);
      /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
      return {
        batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }],
      };
    }
  }
  logger.info(`Successfully processed ${event.Records.length} records.`);
  return { batchItemFailures: [] };
};

async function getRecordDataAsync(
  payload: KinesisStreamRecordPayload
): Promise<string> {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```

# SDK for JavaScript (v3) を使用した Lambda の例
<a name="javascript_3_lambda_code_examples"></a>

次のコード例は、Lambda で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Lambda
<a name="lambda_Hello_javascript_3_topic"></a>

次のコード例は、Lambda の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
import { LambdaClient, paginateListFunctions } from "@aws-sdk/client-lambda";

const client = new LambdaClient({});

export const helloLambda = async () => {
  const paginator = paginateListFunctions({ client }, {});
  const functions = [];

  for await (const page of paginator) {
    const funcNames = page.Functions.map((f) => f.FunctionName);
    functions.push(...funcNames);
  }

  console.log("Functions:");
  console.log(functions.join("\n"));
  return functions;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/ListFunctionsCommand)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda/scenarios/basic#code-examples)での設定と実行の方法を確認してください。
ログに書き込むアクセス許可を Lambda に付与する AWS Identity and Access Management (IAM) ロールを作成します。  

```
    logger.log(`Creating role (${NAME_ROLE_LAMBDA})...`);
    const response = await createRole(NAME_ROLE_LAMBDA);

import { AttachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} policyArn
 * @param {string} roleName
 */
export const attachRolePolicy = (policyArn, roleName) => {
  const command = new AttachRolePolicyCommand({
    PolicyArn: policyArn,
    RoleName: roleName,
  });

  return client.send(command);
};
```
Lambda 関数を作成し、ハンドラーコードをアップロードします。  

```
const createFunction = async (funcName, roleArn) => {
  const client = new LambdaClient({});
  const code = await readFile(`${dirname}../functions/${funcName}.zip`);

  const command = new CreateFunctionCommand({
    Code: { ZipFile: code },
    FunctionName: funcName,
    Role: roleArn,
    Architectures: [Architecture.arm64],
    Handler: "index.handler", // Required when sending a .zip file
    PackageType: PackageType.Zip, // Required when sending a .zip file
    Runtime: Runtime.nodejs16x, // Required when sending a .zip file
  });

  return client.send(command);
};
```
1 つのパラメーターで関数を呼び出して、結果を取得します。  

```
const invoke = async (funcName, payload) => {
  const client = new LambdaClient({});
  const command = new InvokeCommand({
    FunctionName: funcName,
    Payload: JSON.stringify(payload),
    LogType: LogType.Tail,
  });

  const { Payload, LogResult } = await client.send(command);
  const result = Buffer.from(Payload).toString();
  const logs = Buffer.from(LogResult, "base64").toString();
  return { logs, result };
};
```
関数コードを更新し、Lambda 環境を環境可変で設定します。  

```
const updateFunctionCode = async (funcName, newFunc) => {
  const client = new LambdaClient({});
  const code = await readFile(`${dirname}../functions/${newFunc}.zip`);
  const command = new UpdateFunctionCodeCommand({
    ZipFile: code,
    FunctionName: funcName,
    Architectures: [Architecture.arm64],
    Handler: "index.handler", // Required when sending a .zip file
    PackageType: PackageType.Zip, // Required when sending a .zip file
    Runtime: Runtime.nodejs16x, // Required when sending a .zip file
  });

  return client.send(command);
};

const updateFunctionConfiguration = (funcName) => {
  const client = new LambdaClient({});
  const config = readFileSync(`${dirname}../functions/config.json`).toString();
  const command = new UpdateFunctionConfigurationCommand({
    ...JSON.parse(config),
    FunctionName: funcName,
  });
  const result = client.send(command);
  waitForFunctionUpdated({ FunctionName: funcName });
  return result;
};
```
アカウントの関数を一覧表示します。  

```
const listFunctions = () => {
  const client = new LambdaClient({});
  const command = new ListFunctionsCommand({});

  return client.send(command);
};
```
IAM ロールと Lambda 関数を削除します。  

```
import { DeleteRoleCommand, IAMClient } from "@aws-sdk/client-iam";

const client = new IAMClient({});

/**
 *
 * @param {string} roleName
 */
export const deleteRole = (roleName) => {
  const command = new DeleteRoleCommand({ RoleName: roleName });
  return client.send(command);
};

/**
 * @param {string} funcName
 */
const deleteFunction = (funcName) => {
  const client = new LambdaClient({});
  const command = new DeleteFunctionCommand({ FunctionName: funcName });
  return client.send(command);
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/CreateFunctionCommand)
  + [DeleteFunction](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/DeleteFunctionCommand)
  + [GetFunction](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/GetFunctionCommand)
  + [Invoke](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/InvokeCommand)
  + [ListFunctions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/ListFunctionsCommand)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/UpdateFunctionCodeCommand)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/UpdateFunctionConfigurationCommand)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_javascript_3_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
const createFunction = async (funcName, roleArn) => {
  const client = new LambdaClient({});
  const code = await readFile(`${dirname}../functions/${funcName}.zip`);

  const command = new CreateFunctionCommand({
    Code: { ZipFile: code },
    FunctionName: funcName,
    Role: roleArn,
    Architectures: [Architecture.arm64],
    Handler: "index.handler", // Required when sending a .zip file
    PackageType: PackageType.Zip, // Required when sending a .zip file
    Runtime: Runtime.nodejs16x, // Required when sending a .zip file
  });

  return client.send(command);
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[CreateFunction](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/CreateFunctionCommand)」を参照してください。**

### `DeleteFunction`
<a name="lambda_DeleteFunction_javascript_3_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
/**
 * @param {string} funcName
 */
const deleteFunction = (funcName) => {
  const client = new LambdaClient({});
  const command = new DeleteFunctionCommand({ FunctionName: funcName });
  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteFunction](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/DeleteFunctionCommand)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_javascript_3_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
const getFunction = (funcName) => {
  const client = new LambdaClient({});
  const command = new GetFunctionCommand({ FunctionName: funcName });
  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetFunction](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/GetFunctionCommand)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_javascript_3_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
const invoke = async (funcName, payload) => {
  const client = new LambdaClient({});
  const command = new InvokeCommand({
    FunctionName: funcName,
    Payload: JSON.stringify(payload),
    LogType: LogType.Tail,
  });

  const { Payload, LogResult } = await client.send(command);
  const result = Buffer.from(Payload).toString();
  const logs = Buffer.from(LogResult, "base64").toString();
  return { logs, result };
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[Invoke](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/InvokeCommand)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_javascript_3_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
const listFunctions = () => {
  const client = new LambdaClient({});
  const command = new ListFunctionsCommand({});

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/ListFunctionsCommand)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_javascript_3_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
const updateFunctionCode = async (funcName, newFunc) => {
  const client = new LambdaClient({});
  const code = await readFile(`${dirname}../functions/${newFunc}.zip`);
  const command = new UpdateFunctionCodeCommand({
    ZipFile: code,
    FunctionName: funcName,
    Architectures: [Architecture.arm64],
    Handler: "index.handler", // Required when sending a .zip file
    PackageType: PackageType.Zip, // Required when sending a .zip file
    Runtime: Runtime.nodejs16x, // Required when sending a .zip file
  });

  return client.send(command);
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateFunctionCode](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/UpdateFunctionCodeCommand)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_javascript_3_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
const updateFunctionConfiguration = (funcName) => {
  const client = new LambdaClient({});
  const config = readFileSync(`${dirname}../functions/config.json`).toString();
  const command = new UpdateFunctionConfigurationCommand({
    ...JSON.parse(config),
    FunctionName: funcName,
  });
  const result = client.send(command);
  waitForFunctionUpdated({ FunctionName: funcName });
  return result;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/lambda/command/UpdateFunctionConfigurationCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Lambda 関数を使用して登録済みのユーザーを自動的に確認する
<a name="cross_CognitoAutoConfirmUser_javascript_3_topic"></a>

次のコード例は、Lambda 関数を使用して登録済みの Amazon Cognito ユーザーを自動的に確認する方法を示しています。
+ `PreSignUp` トリガーの Lambda 関数を呼び出すようにユーザープールを設定します。
+ Amazon Cognito でユーザーをサインアップする
+ Lambda 関数は DynamoDB テーブルをスキャンし、登録済みのユーザーを自動的に確認します。
+ 新しいユーザーとしてサインインし、リソースをクリーンアップします。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-pools-triggers#code-examples)での設定と実行の方法を確認してください。
インタラクティブな「シナリオ」実行を設定します。JavaScript (v3) の例では、シナリオランナーを共有して、複雑な例を効率化します。完全なソースコードは GitHub にあります。  

```
import { AutoConfirm } from "./scenario-auto-confirm.js";

/**
 * The context is passed to every scenario. Scenario steps
 * will modify the context.
 */
const context = {
  errors: [],
  users: [
    {
      UserName: "test_user_1",
      UserEmail: "test_email_1@example.com",
    },
    {
      UserName: "test_user_2",
      UserEmail: "test_email_2@example.com",
    },
    {
      UserName: "test_user_3",
      UserEmail: "test_email_3@example.com",
    },
  ],
};

/**
 * Three Scenarios are created for the workflow. A Scenario is an orchestration class
 * that simplifies running a series of steps.
 */
export const scenarios = {
  // Demonstrate automatically confirming known users in a database.
  "auto-confirm": AutoConfirm(context),
};

// Call function if run directly
import { fileURLToPath } from "node:url";
import { parseScenarioArgs } from "@aws-doc-sdk-examples/lib/scenario/index.js";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  parseScenarioArgs(scenarios, {
    name: "Cognito user pools and triggers",
    description:
      "Demonstrate how to use the AWS SDKs to customize Amazon Cognito authentication behavior.",
  });
}
```
このシナリオでは、既知のユーザーを自動確認する方法を示します。サンプルのステップをオーケストレーションします。  

```
import { wait } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";

import {
  getStackOutputs,
  logCleanUpReminder,
  promptForStackName,
  promptForStackRegion,
  skipWhenErrors,
} from "./steps-common.js";
import { populateTable } from "./actions/dynamodb-actions.js";
import {
  addPreSignUpHandler,
  deleteUser,
  getUser,
  signIn,
  signUpUser,
} from "./actions/cognito-actions.js";
import {
  getLatestLogStreamForLambda,
  getLogEvents,
} from "./actions/cloudwatch-logs-actions.js";

/**
 * @typedef {{
 *   errors: Error[],
 *   password: string,
 *   users: { UserName: string, UserEmail: string }[],
 *   selectedUser?: string,
 *   stackName?: string,
 *   stackRegion?: string,
 *   token?: string,
 *   confirmDeleteSignedInUser?: boolean,
 *   TableName?: string,
 *   UserPoolClientId?: string,
 *   UserPoolId?: string,
 *   UserPoolArn?: string,
 *   AutoConfirmHandlerArn?: string,
 *   AutoConfirmHandlerName?: string
 * }} State
 */

const greeting = new ScenarioOutput(
  "greeting",
  (/** @type {State} */ state) => `This demo will populate some users into the \
database created as part of the "${state.stackName}" stack. \
Then the AutoConfirmHandler will be linked to the PreSignUp \
trigger from Cognito. Finally, you will choose a user to sign up.`,
  { skipWhen: skipWhenErrors },
);

const logPopulatingUsers = new ScenarioOutput(
  "logPopulatingUsers",
  "Populating the DynamoDB table with some users.",
  { skipWhenErrors: skipWhenErrors },
);

const logPopulatingUsersComplete = new ScenarioOutput(
  "logPopulatingUsersComplete",
  "Done populating users.",
  { skipWhen: skipWhenErrors },
);

const populateUsers = new ScenarioAction(
  "populateUsers",
  async (/** @type {State} */ state) => {
    const [_, err] = await populateTable({
      region: state.stackRegion,
      tableName: state.TableName,
      items: state.users,
    });
    if (err) {
      state.errors.push(err);
    }
  },
  {
    skipWhen: skipWhenErrors,
  },
);

const logSetupSignUpTrigger = new ScenarioOutput(
  "logSetupSignUpTrigger",
  "Setting up the PreSignUp trigger for the Cognito User Pool.",
  { skipWhen: skipWhenErrors },
);

const setupSignUpTrigger = new ScenarioAction(
  "setupSignUpTrigger",
  async (/** @type {State} */ state) => {
    const [_, err] = await addPreSignUpHandler({
      region: state.stackRegion,
      userPoolId: state.UserPoolId,
      handlerArn: state.AutoConfirmHandlerArn,
    });
    if (err) {
      state.errors.push(err);
    }
  },
  {
    skipWhen: skipWhenErrors,
  },
);

const logSetupSignUpTriggerComplete = new ScenarioOutput(
  "logSetupSignUpTriggerComplete",
  (
    /** @type {State} */ state,
  ) => `The lambda function "${state.AutoConfirmHandlerName}" \
has been configured as the PreSignUp trigger handler for the user pool "${state.UserPoolId}".`,
  { skipWhen: skipWhenErrors },
);

const selectUser = new ScenarioInput(
  "selectedUser",
  "Select a user to sign up.",
  {
    type: "select",
    choices: (/** @type {State} */ state) => state.users.map((u) => u.UserName),
    skipWhen: skipWhenErrors,
    default: (/** @type {State} */ state) => state.users[0].UserName,
  },
);

const checkIfUserAlreadyExists = new ScenarioAction(
  "checkIfUserAlreadyExists",
  async (/** @type {State} */ state) => {
    const [user, err] = await getUser({
      region: state.stackRegion,
      userPoolId: state.UserPoolId,
      username: state.selectedUser,
    });

    if (err?.name === "UserNotFoundException") {
      // Do nothing. We're not expecting the user to exist before
      // sign up is complete.
      return;
    }

    if (err) {
      state.errors.push(err);
      return;
    }

    if (user) {
      state.errors.push(
        new Error(
          `The user "${state.selectedUser}" already exists in the user pool "${state.UserPoolId}".`,
        ),
      );
    }
  },
  {
    skipWhen: skipWhenErrors,
  },
);

const createPassword = new ScenarioInput(
  "password",
  "Enter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.",
  { type: "password", skipWhen: skipWhenErrors, default: "Abcd1234!" },
);

const logSignUpExistingUser = new ScenarioOutput(
  "logSignUpExistingUser",
  (/** @type {State} */ state) => `Signing up user "${state.selectedUser}".`,
  { skipWhen: skipWhenErrors },
);

const signUpExistingUser = new ScenarioAction(
  "signUpExistingUser",
  async (/** @type {State} */ state) => {
    const signUp = (password) =>
      signUpUser({
        region: state.stackRegion,
        userPoolClientId: state.UserPoolClientId,
        username: state.selectedUser,
        email: state.users.find((u) => u.UserName === state.selectedUser)
          .UserEmail,
        password,
      });

    let [_, err] = await signUp(state.password);

    while (err?.name === "InvalidPasswordException") {
      console.warn("The password you entered was invalid.");
      await createPassword.handle(state);
      [_, err] = await signUp(state.password);
    }

    if (err) {
      state.errors.push(err);
    }
  },
  { skipWhen: skipWhenErrors },
);

const logSignUpExistingUserComplete = new ScenarioOutput(
  "logSignUpExistingUserComplete",
  (/** @type {State} */ state) =>
    `"${state.selectedUser} was signed up successfully.`,
  { skipWhen: skipWhenErrors },
);

const logLambdaLogs = new ScenarioAction(
  "logLambdaLogs",
  async (/** @type {State} */ state) => {
    console.log(
      "Waiting a few seconds to let Lambda write to CloudWatch Logs...\n",
    );
    await wait(10);

    const [logStream, logStreamErr] = await getLatestLogStreamForLambda({
      functionName: state.AutoConfirmHandlerName,
      region: state.stackRegion,
    });
    if (logStreamErr) {
      state.errors.push(logStreamErr);
      return;
    }

    console.log(
      `Getting some recent events from log stream "${logStream.logStreamName}"`,
    );
    const [logEvents, logEventsErr] = await getLogEvents({
      functionName: state.AutoConfirmHandlerName,
      region: state.stackRegion,
      eventCount: 10,
      logStreamName: logStream.logStreamName,
    });
    if (logEventsErr) {
      state.errors.push(logEventsErr);
      return;
    }

    console.log(logEvents.map((ev) => `\t${ev.message}`).join(""));
  },
  { skipWhen: skipWhenErrors },
);

const logSignInUser = new ScenarioOutput(
  "logSignInUser",
  (/** @type {State} */ state) => `Let's sign in as ${state.selectedUser}`,
  { skipWhen: skipWhenErrors },
);

const signInUser = new ScenarioAction(
  "signInUser",
  async (/** @type {State} */ state) => {
    const [response, err] = await signIn({
      region: state.stackRegion,
      clientId: state.UserPoolClientId,
      username: state.selectedUser,
      password: state.password,
    });

    if (err?.name === "PasswordResetRequiredException") {
      state.errors.push(new Error("Please reset your password."));
      return;
    }

    if (err) {
      state.errors.push(err);
      return;
    }

    state.token = response?.AuthenticationResult?.AccessToken;
  },
  { skipWhen: skipWhenErrors },
);

const logSignInUserComplete = new ScenarioOutput(
  "logSignInUserComplete",
  (/** @type {State} */ state) =>
    `Successfully signed in. Your access token starts with: ${state.token.slice(0, 11)}`,
  { skipWhen: skipWhenErrors },
);

const confirmDeleteSignedInUser = new ScenarioInput(
  "confirmDeleteSignedInUser",
  "Do you want to delete the currently signed in user?",
  { type: "confirm", skipWhen: skipWhenErrors },
);

const deleteSignedInUser = new ScenarioAction(
  "deleteSignedInUser",
  async (/** @type {State} */ state) => {
    const [_, err] = await deleteUser({
      region: state.stackRegion,
      accessToken: state.token,
    });

    if (err) {
      state.errors.push(err);
    }
  },
  {
    skipWhen: (/** @type {State} */ state) =>
      skipWhenErrors(state) || !state.confirmDeleteSignedInUser,
  },
);

const logErrors = new ScenarioOutput(
  "logErrors",
  (/** @type {State}*/ state) => {
    const errorList = state.errors
      .map((err) => ` - ${err.name}: ${err.message}`)
      .join("\n");
    return `Scenario errors found:\n${errorList}`;
  },
  {
    // Don't log errors when there aren't any!
    skipWhen: (/** @type {State} */ state) => state.errors.length === 0,
  },
);

export const AutoConfirm = (context) =>
  new Scenario(
    "AutoConfirm",
    [
      promptForStackName,
      promptForStackRegion,
      getStackOutputs,
      greeting,
      logPopulatingUsers,
      populateUsers,
      logPopulatingUsersComplete,
      logSetupSignUpTrigger,
      setupSignUpTrigger,
      logSetupSignUpTriggerComplete,
      selectUser,
      checkIfUserAlreadyExists,
      createPassword,
      logSignUpExistingUser,
      signUpExistingUser,
      logSignUpExistingUserComplete,
      logLambdaLogs,
      logSignInUser,
      signInUser,
      logSignInUserComplete,
      confirmDeleteSignedInUser,
      deleteSignedInUser,
      logCleanUpReminder,
      logErrors,
    ],
    context,
  );
```
これらは、他のシナリオと共有されるステップです。  

```
import {
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/scenario.js";
import { getCfnOutputs } from "@aws-doc-sdk-examples/lib/sdk/cfn-outputs.js";

export const skipWhenErrors = (state) => state.errors.length > 0;

export const getStackOutputs = new ScenarioAction(
  "getStackOutputs",
  async (state) => {
    if (!state.stackName || !state.stackRegion) {
      state.errors.push(
        new Error(
          "No stack name or region provided. The stack name and \
region are required to fetch CFN outputs relevant to this example.",
        ),
      );
      return;
    }

    const outputs = await getCfnOutputs(state.stackName, state.stackRegion);
    Object.assign(state, outputs);
  },
);

export const promptForStackName = new ScenarioInput(
  "stackName",
  "Enter the name of the stack you deployed earlier.",
  { type: "input", default: "PoolsAndTriggersStack" },
);

export const promptForStackRegion = new ScenarioInput(
  "stackRegion",
  "Enter the region of the stack you deployed earlier.",
  { type: "input", default: "us-east-1" },
);

export const logCleanUpReminder = new ScenarioOutput(
  "logCleanUpReminder",
  "All done. Remember to run 'cdk destroy' to teardown the stack.",
  { skipWhen: skipWhenErrors },
);
```
Lambda 関数を使用する `PreSignUp` トリガーのハンドラー。  

```
import type { PreSignUpTriggerEvent, Handler } from "aws-lambda";
import type { UserRepository } from "./user-repository";
import { DynamoDBUserRepository } from "./user-repository";

export class PreSignUpHandler {
  private userRepository: UserRepository;

  constructor(userRepository: UserRepository) {
    this.userRepository = userRepository;
  }

  private isPreSignUpTriggerSource(event: PreSignUpTriggerEvent): boolean {
    return event.triggerSource === "PreSignUp_SignUp";
  }

  private getEventUserEmail(event: PreSignUpTriggerEvent): string {
    return event.request.userAttributes.email;
  }

  async handlePreSignUpTriggerEvent(
    event: PreSignUpTriggerEvent,
  ): Promise<PreSignUpTriggerEvent> {
    console.log(
      `Received presignup from ${event.triggerSource} for user '${event.userName}'`,
    );

    if (!this.isPreSignUpTriggerSource(event)) {
      return event;
    }

    const eventEmail = this.getEventUserEmail(event);
    console.log(`Looking up email ${eventEmail}.`);
    const storedUserInfo =
      await this.userRepository.getUserInfoByEmail(eventEmail);

    if (!storedUserInfo) {
      console.log(
        `Email ${eventEmail} not found. Email verification is required.`,
      );
      return event;
    }

    if (storedUserInfo.UserName !== event.userName) {
      console.log(
        `UserEmail ${eventEmail} found, but stored UserName '${storedUserInfo.UserName}' does not match supplied UserName '${event.userName}'. Verification is required.`,
      );
    } else {
      console.log(
        `UserEmail ${eventEmail} found with matching UserName ${storedUserInfo.UserName}. User is confirmed.`,
      );
      event.response.autoConfirmUser = true;
      event.response.autoVerifyEmail = true;
    }
    return event;
  }
}

const createPreSignUpHandler = (): PreSignUpHandler => {
  const tableName = process.env.TABLE_NAME;
  if (!tableName) {
    throw new Error("TABLE_NAME environment variable is not set");
  }

  const userRepository = new DynamoDBUserRepository(tableName);
  return new PreSignUpHandler(userRepository);
};

export const handler: Handler = async (event: PreSignUpTriggerEvent) => {
  const preSignUpHandler = createPreSignUpHandler();
  return preSignUpHandler.handlePreSignUpTriggerEvent(event);
};
```
CloudWatch Logs アクションのモジュール。  

```
import {
  CloudWatchLogsClient,
  GetLogEventsCommand,
  OrderBy,
  paginateDescribeLogStreams,
} from "@aws-sdk/client-cloudwatch-logs";

/**
 * Get the latest log stream for a Lambda function.
 * @param {{ functionName: string, region: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cloudwatch-logs").LogStream | null, unknown]>}
 */
export const getLatestLogStreamForLambda = async ({ functionName, region }) => {
  try {
    const logGroupName = `/aws/lambda/${functionName}`;
    const cwlClient = new CloudWatchLogsClient({ region });
    const paginator = paginateDescribeLogStreams(
      { client: cwlClient },
      {
        descending: true,
        limit: 1,
        orderBy: OrderBy.LastEventTime,
        logGroupName,
      },
    );

    for await (const page of paginator) {
      return [page.logStreams[0], null];
    }
  } catch (err) {
    return [null, err];
  }
};

/**
 * Get the log events for a Lambda function's log stream.
 * @param {{
 *   functionName: string,
 *   logStreamName: string,
 *   eventCount: number,
 *   region: string
 * }} config
 * @returns {Promise<[import("@aws-sdk/client-cloudwatch-logs").OutputLogEvent[] | null, unknown]>}
 */
export const getLogEvents = async ({
  functionName,
  logStreamName,
  eventCount,
  region,
}) => {
  try {
    const cwlClient = new CloudWatchLogsClient({ region });
    const logGroupName = `/aws/lambda/${functionName}`;
    const response = await cwlClient.send(
      new GetLogEventsCommand({
        logStreamName: logStreamName,
        limit: eventCount,
        logGroupName: logGroupName,
      }),
    );

    return [response.events, null];
  } catch (err) {
    return [null, err];
  }
};
```
Amazon Cognito アクションのモジュール。  

```
import {
  AdminGetUserCommand,
  CognitoIdentityProviderClient,
  DeleteUserCommand,
  InitiateAuthCommand,
  SignUpCommand,
  UpdateUserPoolCommand,
} from "@aws-sdk/client-cognito-identity-provider";

/**
 * Connect a Lambda function to the PreSignUp trigger for a Cognito user pool
 * @param {{ region: string, userPoolId: string, handlerArn: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").UpdateUserPoolCommandOutput | null, unknown]>}
 */
export const addPreSignUpHandler = async ({
  region,
  userPoolId,
  handlerArn,
}) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({
      region,
    });

    const command = new UpdateUserPoolCommand({
      UserPoolId: userPoolId,
      LambdaConfig: {
        PreSignUp: handlerArn,
      },
    });

    const response = await cognitoClient.send(command);
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Attempt to register a user to a user pool with a given username and password.
 * @param {{
 *   region: string,
 *   userPoolClientId: string,
 *   username: string,
 *   email: string,
 *   password: string
 * }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").SignUpCommandOutput | null, unknown]>}
 */
export const signUpUser = async ({
  region,
  userPoolClientId,
  username,
  email,
  password,
}) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({
      region,
    });

    const response = await cognitoClient.send(
      new SignUpCommand({
        ClientId: userPoolClientId,
        Username: username,
        Password: password,
        UserAttributes: [{ Name: "email", Value: email }],
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Sign in a user to Amazon Cognito using a username and password authentication flow.
 * @param {{ region: string, clientId: string, username: string, password: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").InitiateAuthCommandOutput | null, unknown]>}
 */
export const signIn = async ({ region, clientId, username, password }) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({ region });
    const response = await cognitoClient.send(
      new InitiateAuthCommand({
        AuthFlow: "USER_PASSWORD_AUTH",
        ClientId: clientId,
        AuthParameters: { USERNAME: username, PASSWORD: password },
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Retrieve an existing user from a user pool.
 * @param {{ region: string, userPoolId: string, username: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").AdminGetUserCommandOutput | null, unknown]>}
 */
export const getUser = async ({ region, userPoolId, username }) => {
  try {
    const cognitoClient = new CognitoIdentityProviderClient({ region });
    const response = await cognitoClient.send(
      new AdminGetUserCommand({
        UserPoolId: userPoolId,
        Username: username,
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};

/**
 * Delete the signed-in user. Useful for allowing a user to delete their
 * own profile.
 * @param {{ region: string, accessToken: string }} config
 * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").DeleteUserCommandOutput | null, unknown]>}
 */
export const deleteUser = async ({ region, accessToken }) => {
  try {
    const client = new CognitoIdentityProviderClient({ region });
    const response = await client.send(
      new DeleteUserCommand({ AccessToken: accessToken }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};
```
DynamoDB アクションのモジュール。  

```
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import {
  BatchWriteCommand,
  DynamoDBDocumentClient,
} from "@aws-sdk/lib-dynamodb";

/**
 * Populate a DynamoDB table with provide items.
 * @param {{ region: string, tableName: string, items: Record<string, unknown>[] }} config
 * @returns {Promise<[import("@aws-sdk/lib-dynamodb").BatchWriteCommandOutput | null, unknown]>}
 */
export const populateTable = async ({ region, tableName, items }) => {
  try {
    const ddbClient = new DynamoDBClient({ region });
    const docClient = DynamoDBDocumentClient.from(ddbClient);
    const response = await docClient.send(
      new BatchWriteCommand({
        RequestItems: {
          [tableName]: items.map((item) => ({
            PutRequest: {
              Item: item,
            },
          })),
        },
      }),
    );
    return [response, null];
  } catch (err) {
    return [null, err];
  }
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [DeleteUser](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/DeleteUserCommand)
  + [InitiateAuth](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/InitiateAuthCommand)
  + [SignUp](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/SignUpCommand)
  + [UpdateUserPool](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/cognito-identity-provider/command/UpdateUserPoolCommand)

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_javascript_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for JavaScript (v3)**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo-asset-manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_javascript_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for JavaScript (v3)**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer) のプロジェクトを参照してください。次の抜粋は、 AWS SDK for JavaScript が Lambda 関数内でどのように使用されるかを示しています。  

```
import {
  ComprehendClient,
  DetectDominantLanguageCommand,
  DetectSentimentCommand,
} from "@aws-sdk/client-comprehend";

/**
 * Determine the language and sentiment of the extracted text.
 *
 * @param {{ source_text: string}} extractTextOutput
 */
export const handler = async (extractTextOutput) => {
  const comprehendClient = new ComprehendClient({});

  const detectDominantLanguageCommand = new DetectDominantLanguageCommand({
    Text: extractTextOutput.source_text,
  });

  // The source language is required for sentiment analysis and
  // translation in the next step.
  const { Languages } = await comprehendClient.send(
    detectDominantLanguageCommand,
  );

  const languageCode = Languages[0].LanguageCode;

  const detectSentimentCommand = new DetectSentimentCommand({
    Text: extractTextOutput.source_text,
    LanguageCode: languageCode,
  });

  const { Sentiment } = await comprehendClient.send(detectSentimentCommand);

  return {
    sentiment: Sentiment,
    language_code: languageCode,
  };
};
```

```
import {
  DetectDocumentTextCommand,
  TextractClient,
} from "@aws-sdk/client-textract";

/**
 * Fetch the S3 object from the event and analyze it using Amazon Textract.
 *
 * @param {import("@types/aws-lambda").EventBridgeEvent<"Object Created">} eventBridgeS3Event
 */
export const handler = async (eventBridgeS3Event) => {
  const textractClient = new TextractClient();

  const detectDocumentTextCommand = new DetectDocumentTextCommand({
    Document: {
      S3Object: {
        Bucket: eventBridgeS3Event.bucket,
        Name: eventBridgeS3Event.object,
      },
    },
  });

  // Textract returns a list of blocks. A block can be a line, a page, word, etc.
  // Each block also contains geometry of the detected text.
  // For more information on the Block type, see https://docs.aws.amazon.com/textract/latest/dg/API_Block.html.
  const { Blocks } = await textractClient.send(detectDocumentTextCommand);

  // For the purpose of this example, we are only interested in words.
  const extractedWords = Blocks.filter((b) => b.BlockType === "WORD").map(
    (b) => b.Text,
  );

  return extractedWords.join(" ");
};
```

```
import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly";
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

/**
 * Synthesize an audio file from text.
 *
 * @param {{ bucket: string, translated_text: string, object: string}} sourceDestinationConfig
 */
export const handler = async (sourceDestinationConfig) => {
  const pollyClient = new PollyClient({});

  const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
    Engine: "neural",
    Text: sourceDestinationConfig.translated_text,
    VoiceId: "Ruth",
    OutputFormat: "mp3",
  });

  const { AudioStream } = await pollyClient.send(synthesizeSpeechCommand);

  const audioKey = `${sourceDestinationConfig.object}.mp3`;

  // Store the audio file in S3.
  const s3Client = new S3Client();
  const upload = new Upload({
    client: s3Client,
    params: {
      Bucket: sourceDestinationConfig.bucket,
      Key: audioKey,
      Body: AudioStream,
      ContentType: "audio/mp3",
    },
  });

  await upload.done();
  return audioKey;
};
```

```
import {
  TranslateClient,
  TranslateTextCommand,
} from "@aws-sdk/client-translate";

/**
 * Translate the extracted text to English.
 *
 * @param {{ extracted_text: string, source_language_code: string}} textAndSourceLanguage
 */
export const handler = async (textAndSourceLanguage) => {
  const translateClient = new TranslateClient({});

  const translateCommand = new TranslateTextCommand({
    SourceLanguageCode: textAndSourceLanguage.source_language_code,
    TargetLanguageCode: "en",
    Text: textAndSourceLanguage.extracted_text,
  });

  const { TranslatedText } = await translateClient.send(translateCommand);

  return { translated_text: TranslatedText };
};
```

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

### ブラウザからの Lambda 関数の呼び出し
<a name="cross_LambdaForBrowser_javascript_3_topic"></a>

次のコード例は、ブラウザから AWS Lambda 関数を呼び出す方法を示しています。

**SDK for JavaScript (v3)**  
 AWS Lambda 関数を使用して Amazon DynamoDB テーブルをユーザー選択で更新するブラウザベースのアプリケーションを作成できます。このアプリは v3 AWS SDK for JavaScript を使用します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-for-browser) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_javascript_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 Lambda JavaScript ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-api-gateway) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_javascript_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda JavaScript ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_javascript_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/* 
Node.js code here.
*/
// ES6+ example
import { Signer } from "@aws-sdk/rds-signer";
import mysql from 'mysql2/promise';

async function createAuthToken() {
  // Define connection authentication parameters
  const dbinfo = {

    hostname: process.env.ProxyHostName,
    port: process.env.Port,
    username: process.env.DBUserName,
    region: process.env.AWS_REGION,

  }

  // Create RDS Signer object
  const signer = new Signer(dbinfo);

  // Request authorization token from RDS, specifying the username
  const token = await signer.getAuthToken();
  return token;
}

async function dbOps() {

  // Obtain auth token
  const token = await createAuthToken();
  // Define connection configuration
  let connectionConfig = {
    host: process.env.ProxyHostName,
    user: process.env.DBUserName,
    password: token,
    database: process.env.DBName,
    ssl: 'Amazon RDS'
  }
  // Create the connection to the DB
  const conn = await mysql.createConnection(connectionConfig);
  // Obtain the result of the query
  const [res,] = await conn.execute('select ?+? as sum', [3, 2]);
  return res;

}

export const handler = async (event) => {
  // Execute database flow
  const result = await dbOps();
  // Return result
  return {
    statusCode: 200,
    body: JSON.stringify("The selected sum is: " + result[0].sum)
  }
};
```
TypeScript を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
import { Signer } from "@aws-sdk/rds-signer";
import mysql from 'mysql2/promise';

// RDS settings
// Using '!' (non-null assertion operator) to tell the TypeScript compiler that the DB settings are not null or undefined,
const proxy_host_name = process.env.PROXY_HOST_NAME!
const port = parseInt(process.env.PORT!)
const db_name = process.env.DB_NAME!
const db_user_name = process.env.DB_USER_NAME!
const aws_region = process.env.AWS_REGION!


async function createAuthToken(): Promise<string> {

    // Create RDS Signer object
    const signer = new Signer({
        hostname: proxy_host_name,
        port: port,
        region: aws_region,
        username: db_user_name
    });

    // Request authorization token from RDS, specifying the username
    const token = await signer.getAuthToken();
    return token;
}

async function dbOps(): Promise<mysql.QueryResult | undefined> {
    try {
        // Obtain auth token
        const token = await createAuthToken();
        const conn = await mysql.createConnection({
            host: proxy_host_name,
            user: db_user_name,
            password: token,
            database: db_name,
            ssl: 'Amazon RDS' // Ensure you have the CA bundle for SSL connection
        });
        const [rows, fields] = await conn.execute('SELECT ? + ? AS sum', [3, 2]);
        console.log('result:', rows);
        return rows;
    }
    catch (err) {
        console.log(err);
    }
}

export const lambdaHandler = async (event: any): Promise<{ statusCode: number; body: string }> => {
    // Execute database flow
    const result = await dbOps();

    // Return error is result is undefined
    if (result == undefined)
        return {
            statusCode: 500,
            body: JSON.stringify(`Error with connection to DB host`)
        }

    // Return result
    return {
        statusCode: 200,
        body: JSON.stringify(`The selected sum is: ${result[0].sum}`)
    };
};
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_javascript_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const record of event.Records) {
    try {
      console.log(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      console.log(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      console.error(`An error occurred ${err}`);
      throw err;
    }
  }
  console.log(`Successfully processed ${event.Records.length} records.`);
};

async function getRecordDataAsync(payload) {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```
TypeScript を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
  KinesisStreamEvent,
  Context,
  KinesisStreamHandler,
  KinesisStreamRecordPayload,
} from "aws-lambda";
import { Buffer } from "buffer";
import { Logger } from "@aws-lambda-powertools/logger";

const logger = new Logger({
  logLevel: "INFO",
  serviceName: "kinesis-stream-handler-sample",
});

export const functionHandler: KinesisStreamHandler = async (
  event: KinesisStreamEvent,
  context: Context
): Promise<void> => {
  for (const record of event.Records) {
    try {
      logger.info(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      logger.info(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      logger.error(`An error occurred ${err}`);
      throw err;
    }
    logger.info(`Successfully processed ${event.Records.length} records.`);
  }
};

async function getRecordDataAsync(
  payload: KinesisStreamRecordPayload
): Promise<string> {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_javascript_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での DynamoDB イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
    console.log(JSON.stringify(event, null, 2));
    event.Records.forEach(record => {
        logDynamoDBRecord(record);
    });
};

const logDynamoDBRecord = (record) => {
    console.log(record.eventID);
    console.log(record.eventName);
    console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`);
};
```
TypeScript を使用した Lambda での DynamoDB イベントの消費。  

```
export const handler = async (event, context) => {
    console.log(JSON.stringify(event, null, 2));
    event.Records.forEach(record => {
        logDynamoDBRecord(record);
    });
}
const logDynamoDBRecord = (record) => {
    console.log(record.eventID);
    console.log(record.eventName);
    console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`);
};
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_javascript_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での Amazon DocumentDB イベントの消費。  

```
console.log('Loading function');
exports.handler = async (event, context) => {
    event.events.forEach(record => {
        logDocumentDBEvent(record);
    });
    return 'OK';
};

const logDocumentDBEvent = (record) => {
    console.log('Operation type: ' + record.event.operationType);
    console.log('db: ' + record.event.ns.db);
    console.log('collection: ' + record.event.ns.coll);
    console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2));
};
```
TypeScript を使用した Lambda での Amazon DocumentDB イベントの消費  

```
import { DocumentDBEventRecord, DocumentDBEventSubscriptionContext } from 'aws-lambda';

console.log('Loading function');

export const handler = async (
  event: DocumentDBEventSubscriptionContext,
  context: any
): Promise<string> => {
  event.events.forEach((record: DocumentDBEventRecord) => {
    logDocumentDBEvent(record);
  });
  return 'OK';
};

const logDocumentDBEvent = (record: DocumentDBEventRecord): void => {
  console.log('Operation type: ' + record.event.operationType);
  console.log('db: ' + record.event.ns.db);
  console.log('collection: ' + record.event.ns.coll);
  console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2));
};
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_javascript_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での Amazon MSK イベントの消費。  

```
exports.handler = async (event) => {
    // Iterate through keys
    for (let key in event.records) {
      console.log('Key: ', key)
      // Iterate through records
      event.records[key].map((record) => {
        console.log('Record: ', record)
        // Decode base64
        const msg = Buffer.from(record.value, 'base64').toString()
        console.log('Message:', msg)
      }) 
    }
}
```
TypeScript を使用した Lambda での Amazon MSK イベントの消費。  

```
import { MSKEvent, Context } from "aws-lambda";
import { Buffer } from "buffer";
import { Logger } from "@aws-lambda-powertools/logger";

const logger = new Logger({
  logLevel: "INFO",
  serviceName: "msk-handler-sample",
});

export const handler = async (
  event: MSKEvent,
  context: Context
): Promise<void> => {
  for (const [topic, topicRecords] of Object.entries(event.records)) {
    logger.info(`Processing key: ${topic}`);

    // Process each record in the partition
    for (const record of topicRecords) {
      try {
        // Decode the message value from base64
        const decodedMessage = Buffer.from(record.value, 'base64').toString();

        logger.info({
          message: decodedMessage
        });
      }
      catch (error) {
        logger.error('Error processing event', { error });
        throw error;
      }
    };
  }
}
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_javascript_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
JavaScript を使用した Lambda での S3 イベントの消費。  

```
import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3";

const client = new S3Client();

export const handler = async (event, context) => {

    // Get the object from the event and show its content type
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));

    try {
        const { ContentType } = await client.send(new HeadObjectCommand({
            Bucket: bucket,
            Key: key,
        }));

        console.log('CONTENT TYPE:', ContentType);
        return ContentType;

    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);
    }
};
```
TypeScript を使用した Lambda での S3 イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { S3Event } from 'aws-lambda';
import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({ region: process.env.AWS_REGION });

export const handler = async (event: S3Event): Promise<string | undefined> => {
  // Get the object from the event and show its content type
  const bucket = event.Records[0].s3.bucket.name;
  const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  const params = {
    Bucket: bucket,
    Key: key,
  };
  try {
    const { ContentType } = await s3.send(new HeadObjectCommand(params));
    console.log('CONTENT TYPE:', ContentType);
    return ContentType;
  } catch (err) {
    console.log(err);
    const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
    console.log(message);
    throw new Error(message);
  }
};
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_javascript_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-sns-to-lambda)リポジトリで完全な例を検索し、設定および実行する方法を確認してください。
JavaScript を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const record of event.Records) {
    await processMessageAsync(record);
  }
  console.info("done");
};

async function processMessageAsync(record) {
  try {
    const message = JSON.stringify(record.Sns.Message);
    console.log(`Processed message ${message}`);
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```
TypeScript を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { SNSEvent, Context, SNSHandler, SNSEventRecord } from "aws-lambda";

export const functionHandler: SNSHandler = async (
  event: SNSEvent,
  context: Context
): Promise<void> => {
  for (const record of event.Records) {
    await processMessageAsync(record);
  }
  console.info("done");
};

async function processMessageAsync(record: SNSEventRecord): Promise<any> {
  try {
    const message: string = JSON.stringify(record.Sns.Message);
    console.log(`Processed message ${message}`);
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_javascript_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const message of event.Records) {
    await processMessageAsync(message);
  }
  console.info("done");
};

async function processMessageAsync(message) {
  try {
    console.log(`Processed message ${message.body}`);
    // TODO: Do interesting work based on the new message
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```
TypeScript を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { SQSEvent, Context, SQSHandler, SQSRecord } from "aws-lambda";

export const functionHandler: SQSHandler = async (
  event: SQSEvent,
  context: Context
): Promise<void> => {
  for (const message of event.Records) {
    await processMessageAsync(message);
  }
  console.info("done");
};

async function processMessageAsync(message: SQSRecord): Promise<any> {
  try {
    console.log(`Processed message ${message.body}`);
    // TODO: Do interesting work based on the new message
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_javascript_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Javascript を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const record of event.Records) {
    try {
      console.log(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      console.log(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      console.error(`An error occurred ${err}`);
      /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
      return {
        batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }],
      };
    }
  }
  console.log(`Successfully processed ${event.Records.length} records.`);
  return { batchItemFailures: [] };
};

async function getRecordDataAsync(payload) {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```
TypeScript を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import {
  KinesisStreamEvent,
  Context,
  KinesisStreamHandler,
  KinesisStreamRecordPayload,
  KinesisStreamBatchResponse,
} from "aws-lambda";
import { Buffer } from "buffer";
import { Logger } from "@aws-lambda-powertools/logger";

const logger = new Logger({
  logLevel: "INFO",
  serviceName: "kinesis-stream-handler-sample",
});

export const functionHandler: KinesisStreamHandler = async (
  event: KinesisStreamEvent,
  context: Context
): Promise<KinesisStreamBatchResponse> => {
  for (const record of event.Records) {
    try {
      logger.info(`Processed Kinesis Event - EventID: ${record.eventID}`);
      const recordData = await getRecordDataAsync(record.kinesis);
      logger.info(`Record Data: ${recordData}`);
      // TODO: Do interesting work based on the new data
    } catch (err) {
      logger.error(`An error occurred ${err}`);
      /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
      return {
        batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }],
      };
    }
  }
  logger.info(`Successfully processed ${event.Records.length} records.`);
  return { batchItemFailures: [] };
};

async function getRecordDataAsync(
  payload: KinesisStreamRecordPayload
): Promise<string> {
  var data = Buffer.from(payload.data, "base64").toString("utf-8");
  await Promise.resolve(1); //Placeholder for actual async work
  return data;
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_javascript_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
export const handler = async (event) => {
  const records = event.Records;
  let curRecordSequenceNumber = "";

  for (const record of records) {
    try {
      // Process your record
      curRecordSequenceNumber = record.dynamodb.SequenceNumber;
    } catch (e) {
      // Return failed record's sequence number
      return { batchItemFailures: [{ itemIdentifier: curRecordSequenceNumber }] };
    }
  }

  return { batchItemFailures: [] };
};
```
TypeScript を使用して Lambda で DynamoDB のバッチアイテム失敗をレポートする。  

```
import {
  DynamoDBBatchResponse,
  DynamoDBBatchItemFailure,
  DynamoDBStreamEvent,
} from "aws-lambda";

export const handler = async (
  event: DynamoDBStreamEvent
): Promise<DynamoDBBatchResponse> => {
  const batchItemFailures: DynamoDBBatchItemFailure[] = [];
  let curRecordSequenceNumber;

  for (const record of event.Records) {
    curRecordSequenceNumber = record.dynamodb?.SequenceNumber;

    if (curRecordSequenceNumber) {
      batchItemFailures.push({
        itemIdentifier: curRecordSequenceNumber,
      });
    }
  }

  return { batchItemFailures: batchItemFailures };
};
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_javascript_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Node.js 20.x Lambda runtime, AWS SDK for Javascript V3
export const handler = async (event, context) => {
    const batchItemFailures = [];
    for (const record of event.Records) {
        try {
            await processMessageAsync(record, context);
        } catch (error) {
            batchItemFailures.push({ itemIdentifier: record.messageId });
        }
    }
    return { batchItemFailures };
};

async function processMessageAsync(record, context) {
    if (record.body && record.body.includes("error")) {
        throw new Error("There is an error in the SQS Message.");
    }
    console.log(`Processed message: ${record.body}`);
}
```
TypeScript を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { SQSEvent, SQSBatchResponse, Context, SQSBatchItemFailure, SQSRecord } from 'aws-lambda';

export const handler = async (event: SQSEvent, context: Context): Promise<SQSBatchResponse> => {
    const batchItemFailures: SQSBatchItemFailure[] = [];

    for (const record of event.Records) {
        try {
            await processMessageAsync(record);
        } catch (error) {
            batchItemFailures.push({ itemIdentifier: record.messageId });
        }
    }

    return {batchItemFailures: batchItemFailures};
};

async function processMessageAsync(record: SQSRecord): Promise<void> {
    if (record.body && record.body.includes("error")) {
        throw new Error('There is an error in the SQS Message.');
    }
    console.log(`Processed message ${record.body}`);
}
```

# SDK for JavaScript (v3) を使用した Amazon Lex の例
<a name="javascript_3_lex_code_examples"></a>

次のコード例は、Amazon Lex で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Lex チャットボットを構築する
<a name="cross_LexChatbotLanguages_javascript_3_topic"></a>

次のコード例は、ウェブサイトの訪問者を引き付けるチャットボットの作成方法を示しています。

**SDK for JavaScript (v3)**  
 Amazon Lex API を使用して、ウェブアプリケーション内にチャットボットを作成し、Web サイトの訪問者と交流する方法を説明します。  
 完全なソースコードとセットアップと実行の手順については、 デ AWS SDK for JavaScript ベロッパーガイドの[Amazon Lexチャットボットの構築](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html)」の完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon Lex
+ Amazon Translate

# SDK for JavaScript (v3) を使用した Amazon Location の例
<a name="javascript_3_location_code_examples"></a>

次のコード例は、Amazon Location で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Location
<a name="location_Hello_javascript_3_topic"></a>

次のコード例は、Amazon Location Service の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  LocationClient,
  ListGeofenceCollectionsCommand,
} from "@aws-sdk/client-location";

/**
 * Lists geofences from a specified geofence collection asynchronously.
 */
export const main = async () => {
  const region = "eu-west-1";
  const locationClient = new LocationClient({ region: region });
  const listGeofenceCollParams = {
    MaxResults: 100,
  };
  try {
    const command = new ListGeofenceCollectionsCommand(listGeofenceCollParams);
    const response = await locationClient.send(command);
    const geofenceEntries = response.Entries;
    if (geofenceEntries.length === 0) {
      console.log("No Geofences were found in the collection.");
    } else {
      for (const geofenceEntry of geofenceEntries) {
        console.log(`Geofence ID: ${geofenceEntry.CollectionName}`);
      }
    }
  } catch (error) {
    console.error(
      `A validation error occurred while creating geofence: ${error} \n Exiting program.`,
    );
    return;
  }
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [ListGeofenceCollections](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/ListGeofenceCollectionsCommand)
  + [ListGeofences](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/ListGeofencesCommand)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="location_Scenario_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Location マップを作成します。
+ Amazon Location API キーを作成します。
+ マップ URL を表示します。
+ ジオフェンスコレクションを作成します。
+ ジオフェンスジオメトリを保存します。
+ トラッカーリソースを作成します。
+ デバイスの位置を更新します。
+ 指定されたデバイスの最新の位置更新を取得します。
+ ルート計算ツールを作成します。
+ シアトルとバンクーバー間の距離を決定します。
+ Amazon Location の上位レベルの API を使用します。
+ Amazon Location アセットを削除します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/scenarios#code-examples)での設定と実行の方法を確認してください。

```
/*
Before running this JavaScript code example, set up your development environment, including your credentials.
This demo illustrates how to use the AWS SDK for JavaScript (v3) to work with Amazon Location Service.

For more information, see the following documentation topic:

https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started.html
*/

import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";

import {
  CreateMapCommand,
  CreateGeofenceCollectionCommand,
  PutGeofenceCommand,
  CreateTrackerCommand,
  BatchUpdateDevicePositionCommand,
  GetDevicePositionCommand,
  CreateRouteCalculatorCommand,
  CalculateRouteCommand,
  LocationClient,
  ConflictException,
  ResourceNotFoundException,
  DeleteGeofenceCollectionCommand,
  DeleteRouteCalculatorCommand,
  DeleteTrackerCommand,
  DeleteMapCommand,
} from "@aws-sdk/client-location";

import {
  GeoPlacesClient,
  ReverseGeocodeCommand,
  SearchNearbyCommand,
  SearchTextCommand,
  GetPlaceCommand,
  ValidationException,
} from "@aws-sdk/client-geo-places";

import { parseArgs } from "node:util";
import { fileURLToPath } from "node:url";

/*The inputs for this example can be edited in the ./input.json.*/
import data from "./inputs.json" with { type: "json" };

/**
 * Used repeatedly to have the user press enter.
 * @type {ScenarioInput}
 */
/* v8 ignore next 3 */
const pressEnter = new ScenarioInput("continue", "Press Enter to continue", {
  type: "confirm",
  verbose: "false",
});

const pressEnterConfirm = new ScenarioInput(
  "confirm",
  "Press Enter to continue",
  {
    type: "confirm",
    verbose: "false",
  },
);

const region = "eu-west-1";

const locationClient = new LocationClient({ region: region });

const greet = new ScenarioOutput(
  "greet",
  "Welcome to the Amazon Location Use demo! \n" +
    "AWS Location Service is a fully managed service offered by Amazon Web Services (AWS) that " +
    "provides location-based services for developers. This service simplifies " +
    "the integration of location-based features into applications, making it " +
    "Maps: The service provides access to high-quality maps, satellite imagery, " +
    "and geospatial data from various providers, allowing developers to " +
    "easily embed maps into their applications:\n" +
    "Tracking: The Location Service enables real-time tracking of mobile devices, " +
    "assets, or other entities, allowing developers to build applications " +
    "that can monitor the location of people, vehicles, or other objects.\n" +
    "Geocoding: The service provides the ability to convert addresses or " +
    "location names into geographic coordinates (latitude and longitude), " +
    "and vice versa, enabling developers to integrate location-based search " +
    "and routing functionality into their applications. " +
    "Please define values ./inputs.json for each user-defined variable used in this app. Otherwise the default is used:\n" +
    "- mapName: The name of the map to be create (default is 'AWSMap').\n" +
    "- keyName: The name of the API key to create (default is ' AWSApiKey')\n" +
    "- collectionName: The name of the geofence collection (default is 'AWSLocationCollection')\n" +
    "- geoId: The geographic identifier used for the geofence or map (default is 'geoId')\n" +
    "- trackerName: The name of the tracker (default is 'geoTracker')\n" +
    "- calculatorName: The name of the route calculator (default is 'AWSRouteCalc')\n" +
    "- deviceId: The ID of the device (default is 'iPhone-112356')",

  { header: true },
);
const displayCreateAMap = new ScenarioOutput(
  "displayCreateAMap",
  "1. Create a map\n" +
    "An AWS Location map can enhance the user experience of your " +
    " application by providing accurate and personalized location-based " +
    " features. For example, you could use the geocoding capabilities to " +
    " allow users to search for and locate businesses, landmarks, or " +
    " other points of interest within a specific region.",
);

const sdkCreateAMap = new ScenarioAction(
  "sdkCreateAMap",
  async (/** @type {State} */ state) => {
    const createMapParams = {
      MapName: `${data.inputs.mapName}`,
      Configuration: { style: "VectorEsriNavigation" },
    };
    try {
      const command = new CreateMapCommand(createMapParams);
      const response = await locationClient.send(command);
      state.MapName = response.MapName;
      console.log("Map created. Map ARN is: ", state.MapName);
    } catch (error) {
      console.error("Error creating map: ", error);
      throw error;
    }
  },
);

const displayMapUrl = new ScenarioOutput(
  "displayMapUrl",
  "2. Display Map URL\n" +
    "When you embed a map in a web app or website, the API key is " +
    "included in the map tile URL to authenticate requests. You can " +
    "restrict API keys to specific AWS Location operations (e.g., only " +
    "maps, not geocoding). API keys can expire, ensuring temporary " +
    "access control.\n" +
    "In order to get the MAP URL you need to create and get the API Key value. " +
    "You can create and get the key value using the AWS Management Console under " +
    "Location Services. These operations cannot be completed using the " +
    "AWS SDK. For more information about getting the key value, see " +
    "the AWS Location Documentation.",
);

const sdkDisplayMapUrl = new ScenarioAction(
  "sdkDisplayMapUrl",
  async (/** @type {State} */ state) => {
    const mapURL = `https://maps.geo.aws.amazon.com/maps/v0/maps/${state.MapName}/tiles/{z}/{x}/{y}?key=API_KEY_VALUE`;
    state.mapURL = mapURL;
    console.log(
      `Replace \'API_KEY_VALUE\' in the following URL with the value for the API key you create and get from the AWS Management Console under Location Services. This is then the Map URL you can embed this URL in your Web app:\n 
${state.mapURL}`,
    );
  },
);
const displayCreateGeoFenceColl = new ScenarioOutput(
  "displayCreateGeoFenceColl",
  "3. Create a geofence collection, which manages and stores geofences.",
);

const sdkCreateGeoFenceColl = new ScenarioAction(
  "sdkCreateGeoFenceColl",
  async (/** @type {State} */ state) => {
    // Creates a new geofence collection.
    const geoFenceCollParams = {
      CollectionName: `${data.inputs.collectionName}`,
    };
    try {
      const command = new CreateGeofenceCollectionCommand(geoFenceCollParams);
      const response = await locationClient.send(command);
      state.CollectionName = response.CollectionName;
      console.log(
        `The geofence collection was successfully created: ${state.CollectionName}`,
      );
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `An unexpected error occurred while creating the geofence collection: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
  },
);
const displayStoreGeometry = new ScenarioOutput(
  "displayStoreGeometry",
  "4. Store a geofence geometry in a given geofence collection. " +
    "An AWS Location geofence is a virtual boundary that defines a geographic area " +
    "on a map. It is a useful feature for tracking the location of " +
    "assets or monitoring the movement of objects within a specific region. " +
    "To define a geofence, you need to specify the coordinates of a " +
    "polygon that represents the area of interest. The polygon must be " +
    "defined in a counter-clockwise direction, meaning that the points of " +
    "the polygon must be listed in a counter-clockwise order. " +
    "This is a requirement for the AWS Location service to correctly " +
    "interpret the geofence and ensure that the location data is " +
    "accurately processed within the defined area.",
);

const sdkStoreGeometry = new ScenarioAction(
  "sdkStoreGeometry",
  async (/** @type {State} */ state) => {
    const geoFenceGeoParams = {
      CollectionName: `${data.inputs.collectionName}`,
      GeofenceId: `${data.inputs.geoId}`,
      Geometry: {
        Polygon: [
          [
            [-122.3381, 47.6101],
            [-122.3281, 47.6101],
            [-122.3281, 47.6201],
            [-122.3381, 47.6201],
            [-122.3381, 47.6101],
          ],
        ],
      },
    };
    try {
      const command = new PutGeofenceCommand(geoFenceGeoParams);
      const response = await locationClient.send(command);
      state.GeoFencId = response.GeofenceId;
      console.log("GeoFence created. GeoFence ID is: ", state.GeoFencId);
    } catch (caught) {
      if (caught instanceof ValidationException) {
        console.error(
          `A validation error occurred while creating geofence: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
  },
);
const displayCreateTracker = new ScenarioOutput(
  "displayCreateTracker",
  "5. Create a tracker resource which lets you retrieve current and historical location of devices.",
);

const sdkCreateTracker = new ScenarioAction(
  "sdkCreateTracker",
  async (/** @type {State} */ state) => {
    //Creates a new tracker resource in your AWS account, which you can use to track the location of devices.
    const createTrackerParams = {
      TrackerName: `${data.inputs.trackerName}`,
      Description: "Created using the JavaScript V3 SDK",
      PositionFiltering: "TimeBased",
    };
    try {
      const command = new CreateTrackerCommand(createTrackerParams);
      const response = await locationClient.send(command);
      state.trackerName = response.TrackerName;
      console.log("Tracker created. Tracker name is : ", state.trackerName);
    } catch (caught) {
      if (caught instanceof ResourceNotFoundException) {
        console.error(
          `A validation error occurred while creating geofence: ${caught.message} \n Exiting program.`,
        );
      } else {
        `An unexpected error error occurred: ${caught.message} \n Exiting program.`;
      }
      return;
    }
  },
);
const displayUpdatePosition = new ScenarioOutput(
  "displayUpdatePosition",
  "6. Update the position of a device in the location tracking system." +
    "The AWS Location Service does not enforce a strict format for deviceId, but it must:\n " +
    "- Be a string (case-sensitive).\n" +
    "- Be 1–100 characters long.\n" +
    "- Contain only: Alphanumeric characters (A-Z, a-z, 0-9); Underscores (_); Hyphens (-); and be the same ID used when sending and retrieving positions.",
);

const sdkUpdatePosition = new ScenarioAction(
  "sdkUpdatePosition",
  async (/** @type {State} */ state) => {
    // Updates the position of a device in the location tracking system.

    const updateDevicePosParams = {
      TrackerName: `${data.inputs.trackerName}`,
      Updates: [
        {
          DeviceId: `${data.inputs.deviceId}`,
          SampleTime: new Date(),
          Position: [-122.4194, 37.7749],
        },
      ],
    };
    try {
      const command = new BatchUpdateDevicePositionCommand(
        updateDevicePosParams,
      );
      const response = await locationClient.send(command);
      console.log(
        `Device with id ${data.inputs.deviceId} was successfully updated in the location tracking system. `,
      );
    } catch (caught) {
      if (caught instanceof ResourceNotFoundException) {
        console.error(
          `A validation error occurred while updating the device: ${caught.message} \n Exiting program.`,
        );
      }
    }
  },
);
const displayRetrievePosition = new ScenarioOutput(
  "displayRetrievePosition",
  "7. Retrieve the most recent position update for a specified device.",
);

const sdkRetrievePosition = new ScenarioAction(
  "sdkRetrievePosition",
  async (/** @type {State} */ state) => {
    const devicePositionParams = {
      TrackerName: `${data.inputs.trackerName}`,
      DeviceId: `${data.inputs.deviceId}`,
    };
    try {
      const command = new GetDevicePositionCommand(devicePositionParams);
      const response = await locationClient.send(command);
      state.position = response.Position;
      console.log("Successfully fetched device position: : ", state.position);
    } catch (caught) {
      if (caught instanceof ResourceNotFoundException) {
        console.error(
          `"The resource was not found: ${caught.message} \n Exiting program.`,
        );
      } else {
        `An unexpected error error occurred: ${caught.message} \n Exiting program.`;
      }
      return;
    }
  },
);
const displayCreateRouteCalc = new ScenarioOutput(
  "displayCreateRouteCalc",
  "8. Create a route calculator.",
);

const sdkCreateRouteCalc = new ScenarioAction(
  "sdkCreateRouteCalc",
  async (/** @type {State} */ state) => {
    const routeCalcParams = {
      CalculatorName: `${data.inputs.calculatorName}`,
      DataSource: "Esri",
    };
    try {
      // Creates a new route calculator with the specified name and data source.
      const command = new CreateRouteCalculatorCommand(routeCalcParams);
      const response = await locationClient.send(command);
      state.CalculatorName = response.CalculatorName;
      console.log(
        "Route calculator created successfully. Calculator name is: ",
        state.CalculatorName,
      );
    } catch (caught) {
      if (caught instanceof ConflictException) {
        console.error(
          `An conflict occurred: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
  },
);
const displayDetermineDist = new ScenarioOutput(
  "displayDetermineDist",
  "9. Determine the distance between Seattle and Vancouver using the route calculator.",
);

const sdkDetermineDist = new ScenarioAction(
  "sdkDetermineDist",
  async (/** @type {State} */ state) => {
    // Calculates the distance between two locations asynchronously.
    const determineDist = {
      CalculatorName: `${data.inputs.calculatorName}`,
      DeparturePosition: [-122.3321, 47.6062],
      DestinationPosition: [-123.1216, 49.2827],
      TravelMode: "Car",
      DistanceUnit: "Kilometers",
    };
    try {
      const command = new CalculateRouteCommand(determineDist);
      const response = await locationClient.send(command);

      console.log(
        "Successfully calculated route. The distance in kilometers is : ",
        response.Summary.Distance,
      );
    } catch (caught) {
      if (caught instanceof ResourceNotFoundException) {
        console.error(
          `Failed to calculate route: ${caught.message} \n Exiting program.`,
        );
      }
      return;
    }
  },
);
const displayUseGeoPlacesClient = new ScenarioOutput(
  "displayUseGeoPlacesClient",
  "10. Use the GeoPlacesAsyncClient to perform additional operations. " +
    "This scenario will show use of the GeoPlacesClient that enables" +
    "location search and geocoding capabilities for your applications. " +
    "We are going to use this client to perform these AWS Location tasks: \n" +
    " - Reverse Geocoding (reverseGeocode): Converts geographic coordinates into addresses.\n " +
    " - Place Search (searchText): Finds places based on search queries.\n " +
    " - Nearby Search (searchNearby): Finds places near a specific location.\n " +
    "First we will perform a Reverse Geocoding operation",
);

const sdkUseGeoPlacesClient = new ScenarioAction(
  "sdkUseGeoPlacesClient",
  async (/** @type {State} */ state) => {
    const geoPlacesClient = new GeoPlacesClient({ region: region });

    const reverseGeoCodeParams = {
      QueryPosition: [-122.4194, 37.7749],
    };
    const searchTextParams = {
      QueryText: "coffee shop",
      BiasPosition: [-122.4194, 37.7749], //San Fransisco
    };
    const searchNearbyParams = {
      QueryPosition: [-122.4194, 37.7749],
      QueryRadius: Number("1000"),
    };
    try {
      /*   Performs reverse geocoding using the AWS Geo Places API.
     Reverse geocoding is the process of converting geographic coordinates (latitude and longitude) to a human-readable address.
     This method uses the latitude and longitude of San Francisco as the input, and prints the resulting address.*/

      console.log("Use latitude 37.7749 and longitude -122.4194.");
      const command = new ReverseGeocodeCommand(reverseGeoCodeParams);
      const response = await geoPlacesClient.send(command);
      console.log(
        "Successfully calculated route. The distance in kilometers is : ",
        response.ResultItems[0].Distance,
      );
    } catch (caught) {
      if (caught instanceof ValidationException) {
        console.error(
          `An conflict occurred: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
    try {
      console.log(
        "Now we are going to perform a text search using coffee shop",
      );

      /*Searches for a place using the provided search query and prints the detailed information of the first result.
  @param searchTextParams the search query to be used for the place search (ex, coffee shop)*/

      const command = new SearchTextCommand(searchTextParams);
      const response = await geoPlacesClient.send(command);
      const placeId = response.ResultItems[0].PlaceId.toString();
      const getPlaceCommand = new GetPlaceCommand({
        PlaceId: placeId,
      });
      const getPlaceResponse = await geoPlacesClient.send(getPlaceCommand);
      console.log(
        `Detailed Place Information: \n Name and address: ${getPlaceResponse.Address.Label}`,
      );

      const foodTypes = getPlaceResponse.FoodTypes;
      if (foodTypes.length) {
        console.log("Food Types: ");
        for (const foodType of foodTypes) {
          console.log("- ", foodType.LocalizedName);
        }
      } else {
        console.log("No food types available.");
      }
    } catch (caught) {
      if (caught instanceof ValidationException) {
        console.error(
          `An conflict occurred: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
    try {
      console.log("\nNow we are going to perform a nearby search.");
      const command = new SearchNearbyCommand(searchNearbyParams);
      const response = await geoPlacesClient.send(command);
      const resultItems = response.ResultItems;
      console.log("\nSuccessfully performed nearby search.");
      for (const resultItem of resultItems) {
        console.log("Name and address: ", resultItem.Address.Label);
        console.log("Distance: ", resultItem.Distance);
      }
    } catch (caught) {
      if (caught instanceof ValidationException) {
        console.error(
          `An conflict occurred: ${caught.message} \n Exiting program.`,
        );
        return;
      }
    }
  },
);

const displayDeleteResources = new ScenarioOutput(
  "displayDeleteResources",
  "11. Delete the AWS Location Services resources. " +
    "Would you like to delete the AWS Location Services resources? (y/n)",
);

const sdkDeleteResources = new ScenarioAction(
  "sdkDeleteResources",
  async (/** @type {State} */ state) => {
    const deleteGeofenceCollParams = {
      CollectionName: `${state.CollectionName}`,
    };
    const deleteRouteCalculatorParams = {
      CalculatorName: `${state.CalculatorName}`,
    };
    const deleteTrackerParams = { TrackerName: `${state.trackerName}` };
    const deleteMapParams = { MapName: `${state.MapName}` };
    try {
      const command = new DeleteMapCommand(deleteMapParams);
      const response = await locationClient.send(command);
      console.log("Map deleted.");
    } catch (error) {
      console.log("Error deleting map: ", error);
    }
    try {
      const command = new DeleteGeofenceCollectionCommand(
        deleteGeofenceCollParams,
      );
      const response = await locationClient.send(command);
      console.log("Geofence collection deleted.");
    } catch (error) {
      console.log("Error deleting geofence collection: ", error);
    }
    try {
      const command = new DeleteRouteCalculatorCommand(
        deleteRouteCalculatorParams,
      );
      const response = await locationClient.send(command);
      console.log("Route calculator deleted.");
    } catch (error) {
      console.log("Error deleting route calculator: ", error);
    }
    try {
      const command = new DeleteTrackerCommand(deleteTrackerParams);
      const response = await locationClient.send(command);
      console.log("Tracker deleted.");
    } catch (error) {
      console.log("Error deleting tracker: ", error);
    }
  },
);

const goodbye = new ScenarioOutput(
  "goodbye",
  "Thank you for checking out the Amazon Location Service Use demo. We hope you " +
    "learned something new, or got some inspiration for your own apps today!" +
    " For more Amazon Location Services examples in different programming languages, have a look at: " +
    "https://docs.aws.amazon.com/code-library/latest/ug/location_code_examples.html",
);

const myScenario = new Scenario("Location Services Scenario", [
  greet,
  pressEnter,
  displayCreateAMap,
  sdkCreateAMap,
  pressEnter,
  displayMapUrl,
  sdkDisplayMapUrl,
  pressEnter,
  displayCreateGeoFenceColl,
  sdkCreateGeoFenceColl,
  pressEnter,
  displayStoreGeometry,
  sdkStoreGeometry,
  pressEnter,
  displayCreateTracker,
  sdkCreateTracker,
  pressEnter,
  displayUpdatePosition,
  sdkUpdatePosition,
  pressEnter,
  displayRetrievePosition,
  sdkRetrievePosition,
  pressEnter,
  displayCreateRouteCalc,
  sdkCreateRouteCalc,
  pressEnter,
  displayDetermineDist,
  sdkDetermineDist,
  pressEnter,
  displayUseGeoPlacesClient,
  sdkUseGeoPlacesClient,
  pressEnter,
  displayDeleteResources,
  pressEnterConfirm,
  sdkDeleteResources,
  goodbye,
]);

/** @type {{ stepHandlerOptions: StepHandlerOptions }} */
export const main = async (stepHandlerOptions) => {
  await myScenario.run(stepHandlerOptions);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      yes: {
        type: "boolean",
        short: "y",
      },
    },
  });
  main({ confirmAll: values.yes });
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [BatchUpdateDevicePosition](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/BatchUpdateDevicePositionCommand)
  + [CalculateRoute](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CalculateRouteCommand)
  + [CreateGeofenceCollection](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateGeofenceCollectionCommand)
  + [CreateKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateKeyCommand)
  + [CreateMap](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateMapCommand)
  + [CreateRouteCalculator](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateRouteCalculatorCommand)
  + [CreateTracker](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateTrackerCommand)
  + [DeleteGeofenceCollection](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteGeofenceCollectionCommand)
  + [DeleteKey](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteKeyCommand)
  + [DeleteMap](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteMapCommand)
  + [DeleteRouteCalculator](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteRouteCalculatorCommand)
  + [DeleteTracker](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteTrackerCommand)
  + [GetDevicePosition](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/GetDevicePositionCommand)
  + [PutGeofence](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/PutGeofenceCommand)

## アクション
<a name="actions"></a>

### `BatchUpdateDevicePosition`
<a name="location_BatchUpdateDevicePosition_javascript_3_topic"></a>

次のコード例は、`BatchUpdateDevicePosition` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  BatchUpdateDevicePositionCommand,
  LocationClient,
  ResourceNotFoundException,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };
const region = "eu-west-1";
const locationClient = new LocationClient({ region: region });
const updateDevicePosParams = {
  TrackerName: `${data.inputs.trackerName}`,
  Updates: [
    {
      DeviceId: `${data.inputs.deviceId}`,
      SampleTime: new Date(),
      Position: [-122.4194, 37.7749],
    },
  ],
};
export const main = async () => {
  try {
    const command = new BatchUpdateDevicePositionCommand(updateDevicePosParams);
    const response = await locationClient.send(command);
    //console.log("response ", response.Errors[0].Error);

    console.log(
      `Device with id ${data.inputs.deviceId} was successfully updated in the location tracking system. `,
      response,
    );
  } catch (error) {
    console.log("error ", error);
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[BatchUpdateDevicePosition](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/BatchUpdateDevicePositionCommand)」を参照してください。

### `CalculateRoute`
<a name="location_CalculateRoute_javascript_3_topic"></a>

次のコード例は、`CalculateRoute` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  CalculateRouteCommand,
  ResourceNotFoundException,
  LocationClient,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";
const locationClient = new LocationClient({ region: region });

export const main = async () => {
  const routeCalcParams = {
    CalculatorName: `${data.inputs.calculatorName}`,
    DeparturePosition: [-122.3321, 47.6062],
    DestinationPosition: [-123.1216, 49.2827],
    TravelMode: "Car",
    DistanceUnit: "Kilometers",
  };
  try {
    const command = new CalculateRouteCommand(routeCalcParams);
    const response = await locationClient.send(command);

    console.log(
      "Successfully calculated route. The distance in kilometers is : ",
      response.Summary.Distance,
    );
  } catch (caught) {
    if (caught instanceof ResourceNotFoundException) {
      console.error(
        `An conflict occurred: ${caught.message} \n Exiting program.`,
      );
      return;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CalculateRoute](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CalculateRouteCommand)」を参照してください。

### `CreateGeofenceCollection`
<a name="location_CreateGeofenceCollection_javascript_3_topic"></a>

次のコード例は、`CreateGeofenceCollection` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  ConflictException,
  CreateGeofenceCollectionCommand,
  LocationClient,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const geoFenceCollParams = {
    CollectionName: `${data.inputs.collectionName}`,
  };
  const locationClient = new LocationClient({ region: region });
  try {
    const command = new CreateGeofenceCollectionCommand(geoFenceCollParams);
    const response = await locationClient.send(command);
    console.log(
      "Collection created. Collection name is: ",
      response.CollectionName,
    );
  } catch (caught) {
    if (caught instanceof ConflictException) {
      console.error("A conflict occurred. Exiting program.");
      return;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateGeofenceCollection](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateGeofenceCollectionCommand)」を参照してください。

### `CreateMap`
<a name="location_CreateMap_javascript_3_topic"></a>

次のコード例は、`CreateMap` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import { CreateMapCommand, LocationClient } from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const CreateMapCommandInput = {
    MapName: `${data.inputs.mapName}`,
    Configuration: { style: "VectorEsriNavigation" },
  };
  const locationClient = new LocationClient({ region: region });
  try {
    const command = new CreateMapCommand(CreateMapCommandInput);
    const response = await locationClient.send(command);
    console.log("Map created. Map ARN is : ", response.MapArn);
  } catch (error) {
    console.error("Error creating map: ", error);
    throw error;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateMap](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateMapCommand)」を参照してください。

### `CreateRouteCalculator`
<a name="location_CreateRouteCalculator_javascript_3_topic"></a>

次のコード例は、`CreateRouteCalculator` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  ConflictException,
  CreateRouteCalculatorCommand,
  LocationClient,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";
const locationClient = new LocationClient({ region: region });

export const main = async () => {
  const routeCalcParams = {
    CalculatorName: `${data.inputs.calculatorName}`,
    DataSource: "Esri",
  };
  try {
    const command = new CreateRouteCalculatorCommand(routeCalcParams);
    const response = await locationClient.send(command);

    console.log(
      "Route calculator created successfully. Calculator name is ",
      response.CalculatorName,
    );
  } catch (caught) {
    if (caught instanceof ConflictException) {
      console.error(
        `An conflict occurred: ${caught.message} \n Exiting program.`,
      );
      return;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateRouteCalculator](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateRouteCalculatorCommand)」を参照してください。

### `CreateTracker`
<a name="location_CreateTracker_javascript_3_topic"></a>

次のコード例は、`CreateTracker` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import { CreateTrackerCommand, LocationClient } from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const createTrackerParams = {
    TrackerName: `${data.inputs.trackerName}`,
  };
  const locationClient = new LocationClient({ region: region });
  try {
    const command = new CreateTrackerCommand(createTrackerParams);
    const response = await locationClient.send(command);
    //state.trackerName - response.TrackerName;
    console.log("Tracker created. Tracker name is : ", response.TrackerName);
  } catch (error) {
    console.error("Error creating map: ", error);
    throw error;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateTracker](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/CreateTrackerCommand)」を参照してください。

### `DeleteGeofenceCollection`
<a name="location_DeleteGeofenceCollection_javascript_3_topic"></a>

次のコード例は、`DeleteGeofenceCollection` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  DeleteGeofenceCollectionCommand,
  LocationClient,
  ResourceNotFoundException,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const deleteGeofenceCollParams = {
    CollectionName: `${data.inputs.collectionName}`,
  };
  const locationClient = new LocationClient({ region: region });
  try {
    const command = new DeleteGeofenceCollectionCommand(
      deleteGeofenceCollParams,
    );
    const response = await locationClient.send(command);
    console.log("Collection deleted.");
  } catch (caught) {
    if (caught instanceof ResourceNotFoundException) {
      console.error(
        `${data.inputs.collectionName} Geofence collection not found.`,
      );
      return;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteGeofenceCollection](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteGeofenceCollectionCommand)」を参照してください。

### `DeleteMap`
<a name="location_DeleteMap_javascript_3_topic"></a>

次のコード例は、`DeleteMap` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  DeleteMapCommand,
  LocationClient,
  ResourceNotFoundException,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const deleteMapParams = {
    MapName: `${data.inputs.mapName}`,
  };
  try {
    const locationClient = new LocationClient({ region: region });
    const command = new DeleteMapCommand(deleteMapParams);
    const response = await locationClient.send(command);
    console.log("Map deleted.");
  } catch (caught) {
    if (caught instanceof ResourceNotFoundException) {
      console.error(`${data.inputs.mapName} map not found.`);
      return;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteMap](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteMapCommand)」を参照してください。

### `DeleteRouteCalculator`
<a name="location_DeleteRouteCalculator_javascript_3_topic"></a>

次のコード例は、`DeleteRouteCalculator` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  DeleteRouteCalculatorCommand,
  LocationClient,
  ResourceNotFoundException,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const deleteRouteCalculatorParams = {
    CalculatorName: `${data.inputs.calculatorName}`,
  };
  try {
    const locationClient = new LocationClient({ region: region });
    const command = new DeleteRouteCalculatorCommand(
      deleteRouteCalculatorParams,
    );
    const response = await locationClient.send(command);
    console.log("Route calculator deleted.");
  } catch (caught) {
    if (caught instanceof ResourceNotFoundException) {
      console.error(
        `${data.inputs.calculatorName} route calculator not found.`,
      );
      return;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteRouteCalculator](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteRouteCalculatorCommand)」を参照してください。

### `DeleteTracker`
<a name="location_DeleteTracker_javascript_3_topic"></a>

次のコード例は、`DeleteTracker` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  DeleteTrackerCommand,
  LocationClient,
  ResourceNotFoundException,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const deleteTrackerParams = {
    TrackerName: `${data.inputs.trackerName}`,
  };
  try {
    const locationClient = new LocationClient({ region: region });
    const command = new DeleteTrackerCommand(deleteTrackerParams);
    const response = await locationClient.send(command);
    console.log("Tracker deleted.");
  } catch (caught) {
    if (caught instanceof ResourceNotFoundException) {
      console.error(`${data.inputs.trackerName} tracker not found.`);
      return;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteTracker](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/DeleteTrackerCommand)」を参照してください。

### `GetDevicePosition`
<a name="location_GetDevicePosition_javascript_3_topic"></a>

次のコード例は、`GetDevicePosition` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  GetDevicePositionCommand,
  LocationClient,
  ResourceNotFoundException,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";

export const main = async () => {
  const locationClient = new LocationClient({ region: region });
  const deviceId = `${data.inputs.deviceId}`;
  const trackerName = `${data.inputs.trackerName}`;

  const devicePositionParams = {
    DeviceId: deviceId,
    TrackerName: trackerName,
  };
  try {
    const command = new GetDevicePositionCommand(devicePositionParams);
    const response = await locationClient.send(command);
    //state.position = response.position;
    console.log("Successfully fetched device position: ", response);
  } catch (error) {
    console.log("Error ", error);
    /*  if (caught instanceof ResourceNotFoundException) {
      console.error(
        `"The resource was not found: ${caught.message} \n Exiting program.`,
      );
    } else {
      `An unexpected error error occurred: ${caught.message} \n Exiting program.`;
    }
    return;*/
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetDevicePosition](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/GetDevicePositionCommand)」を参照してください。

### `PutGeofence`
<a name="location_PutGeofence_javascript_3_topic"></a>

次のコード例は、`PutGeofence` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/location/actions#code-examples)での設定と実行の方法を確認してください。

```
import { fileURLToPath } from "node:url";
import {
  PutGeofenceCommand,
  LocationClient,
  ValidationException,
} from "@aws-sdk/client-location";
import data from "./inputs.json" with { type: "json" };

const region = "eu-west-1";
const locationClient = new LocationClient({ region: region });
export const main = async () => {
  const geoFenceGeoParams = {
    CollectionName: `${data.inputs.collectionName}`,
    GeofenceId: `${data.inputs.geoId}`,
    Geometry: {
      Polygon: [
        [
          [-122.3381, 47.6101],
          [-122.3281, 47.6101],
          [-122.3281, 47.6201],
          [-122.3381, 47.6201],
          [-122.3381, 47.6101],
        ],
      ],
    },
  };
  try {
    const command = new PutGeofenceCommand(geoFenceGeoParams);
    const response = await locationClient.send(command);
    console.log("GeoFence created. GeoFence ID is: ", response.GeofenceId);
  } catch (error) {
    console.error(
      `A validation error occurred while creating geofence: ${error} \n Exiting program.`,
    );
    return;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[PutGeofence](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/location/command/PutGeofenceCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon MSK の例
<a name="javascript_3_kafka_code_examples"></a>

次のコード例は、Amazon MSK で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_javascript_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での Amazon MSK イベントの消費。  

```
exports.handler = async (event) => {
    // Iterate through keys
    for (let key in event.records) {
      console.log('Key: ', key)
      // Iterate through records
      event.records[key].map((record) => {
        console.log('Record: ', record)
        // Decode base64
        const msg = Buffer.from(record.value, 'base64').toString()
        console.log('Message:', msg)
      }) 
    }
}
```
TypeScript を使用した Lambda での Amazon MSK イベントの消費。  

```
import { MSKEvent, Context } from "aws-lambda";
import { Buffer } from "buffer";
import { Logger } from "@aws-lambda-powertools/logger";

const logger = new Logger({
  logLevel: "INFO",
  serviceName: "msk-handler-sample",
});

export const handler = async (
  event: MSKEvent,
  context: Context
): Promise<void> => {
  for (const [topic, topicRecords] of Object.entries(event.records)) {
    logger.info(`Processing key: ${topic}`);

    // Process each record in the partition
    for (const record of topicRecords) {
      try {
        // Decode the message value from base64
        const decodedMessage = Buffer.from(record.value, 'base64').toString();

        logger.info({
          message: decodedMessage
        });
      }
      catch (error) {
        logger.error('Error processing event', { error });
        throw error;
      }
    };
  }
}
```

# SDK for JavaScript (v3) を使用した Amazon Personalize の例
<a name="javascript_3_personalize_code_examples"></a>

次のコード例は、Amazon Personalize で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateBatchInferenceJob`
<a name="personalize_CreateBatchInferenceJob_javascript_3_topic"></a>

次のコード例は、`CreateBatchInferenceJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateBatchInferenceJobCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the batch inference job's parameters.

export const createBatchInferenceJobParam = {
  jobName: "JOB_NAME",
  jobInput: {
    s3DataSource: {
      path: "INPUT_PATH",
    },
  },
  jobOutput: {
    s3DataDestination: {
      path: "OUTPUT_PATH",
    },
  },
  roleArn: "ROLE_ARN",
  solutionVersionArn: "SOLUTION_VERSION_ARN",
  numResults: 20,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateBatchInferenceJobCommand(createBatchInferenceJobParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateBatchInferenceJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateBatchInferenceJobCommand)」を参照してください。

### `CreateBatchSegmentJob`
<a name="personalize_CreateBatchSegmentJob_javascript_3_topic"></a>

次のコード例は、`CreateBatchSegmentJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateBatchSegmentJobCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the batch segment job's parameters.

export const createBatchSegmentJobParam = {
  jobName: "NAME",
  jobInput: {
    s3DataSource: {
      path: "INPUT_PATH",
    },
  },
  jobOutput: {
    s3DataDestination: {
      path: "OUTPUT_PATH",
    },
  },
  roleArn: "ROLE_ARN",
  solutionVersionArn: "SOLUTION_VERSION_ARN",
  numResults: 20,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateBatchSegmentJobCommand(createBatchSegmentJobParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[CreateBatchSegmentJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateBatchSegmentJobCommand)」を参照してください。

### `CreateCampaign`
<a name="personalize_CreateCampaign_javascript_3_topic"></a>

次のコード例は、`CreateCampaign` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.

import { CreateCampaignCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the campaign's parameters.
export const createCampaignParam = {
  solutionVersionArn: "SOLUTION_VERSION_ARN" /* required */,
  name: "NAME" /* required */,
  minProvisionedTPS: 1 /* optional integer */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateCampaignCommand(createCampaignParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateCampaign](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateCampaignCommand) 」を参照してください。

### `CreateDataset`
<a name="personalize_CreateDataset_javascript_3_topic"></a>

次のコード例は、`CreateDataset` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateDatasetCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the dataset's parameters.
export const createDatasetParam = {
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
  datasetType: "DATASET_TYPE" /* required */,
  name: "NAME" /* required */,
  schemaArn: "SCHEMA_ARN" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateDatasetCommand(createDatasetParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateDataset](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateDatasetCommand)」を参照してください。

### `CreateDatasetExportJob`
<a name="personalize_CreateDatasetExportJob_javascript_3_topic"></a>

次のコード例は、`CreateDatasetExportJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateDatasetExportJobCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the export job parameters.
export const datasetExportJobParam = {
  datasetArn: "DATASET_ARN" /* required */,
  jobOutput: {
    s3DataDestination: {
      path: "S3_DESTINATION_PATH" /* required */,
      //kmsKeyArn: 'ARN'  /* include if your bucket uses AWS KMS for encryption
    },
  },
  jobName: "NAME" /* required */,
  roleArn: "ROLE_ARN" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateDatasetExportJobCommand(datasetExportJobParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*のの「[CreateDatasetExportJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateDatasetExportJobCommand)」を参照してください。

### `CreateDatasetGroup`
<a name="personalize_CreateDatasetGroup_javascript_3_topic"></a>

次のコード例は、`CreateDatasetGroup` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.

import { CreateDatasetGroupCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the dataset group parameters.
export const createDatasetGroupParam = {
  name: "NAME" /* required */,
};

export const run = async (createDatasetGroupParam) => {
  try {
    const response = await personalizeClient.send(
      new CreateDatasetGroupCommand(createDatasetGroupParam),
    );
    console.log("Success", response);
    return "Run successfully"; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run(createDatasetGroupParam);
```
ドメインデータセットグループを作成します。  

```
// Get service clients module and commands using ES6 syntax.
import { CreateDatasetGroupCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the domain dataset group parameters.
export const domainDatasetGroupParams = {
  name: "NAME" /* required */,
  domain:
    "DOMAIN" /* required for a domain dsg, specify ECOMMERCE or VIDEO_ON_DEMAND */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateDatasetGroupCommand(domainDatasetGroupParams),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateDatasetGroup](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateDatasetGroupCommand)」を参照してください。

### `CreateDatasetImportJob`
<a name="personalize_CreateDatasetImportJob_javascript_3_topic"></a>

次のコード例は、`CreateDatasetImportJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateDatasetImportJobCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the dataset import job parameters.
export const datasetImportJobParam = {
  datasetArn: "DATASET_ARN" /* required */,
  dataSource: {
    /* required */
    dataLocation: "S3_PATH",
  },
  jobName: "NAME" /* required */,
  roleArn: "ROLE_ARN" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateDatasetImportJobCommand(datasetImportJobParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateDatasetImportJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateDatasetImportJobCommand)」を参照してください。

### `CreateEventTracker`
<a name="personalize_CreateEventTracker_javascript_3_topic"></a>

次のコード例は、`CreateEventTracker` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateEventTrackerCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the event tracker's parameters.
export const createEventTrackerParam = {
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
  name: "NAME" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateEventTrackerCommand(createEventTrackerParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateEventTracker](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateEventTrackerCommand)」を参照してください。

### `CreateFilter`
<a name="personalize_CreateFilter_javascript_3_topic"></a>

次のコード例は、`CreateFilter` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateFilterCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the filter's parameters.
export const createFilterParam = {
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
  name: "NAME" /* required */,
  filterExpression: "FILTER_EXPRESSION" /*required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateFilterCommand(createFilterParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateFilter](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateFilterCommand)」を参照してください。

### `CreateRecommender`
<a name="personalize_CreateRecommender_javascript_3_topic"></a>

次のコード例は、`CreateRecommender` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateRecommenderCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the recommender's parameters.
export const createRecommenderParam = {
  name: "NAME" /* required */,
  recipeArn: "RECIPE_ARN" /* required */,
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateRecommenderCommand(createRecommenderParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateRecommender](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateRecommenderCommand)」を参照してください。

### `CreateSchema`
<a name="personalize_CreateSchema_javascript_3_topic"></a>

次のコード例は、`CreateSchema` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateSchemaCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

import fs from "node:fs";

const schemaFilePath = "SCHEMA_PATH";
let mySchema = "";

try {
  mySchema = fs.readFileSync(schemaFilePath).toString();
} catch (err) {
  mySchema = "TEST"; // For unit tests.
}
// Set the schema parameters.
export const createSchemaParam = {
  name: "NAME" /* required */,
  schema: mySchema /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateSchemaCommand(createSchemaParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
ドメインでスキーマを作成します。  

```
// Get service clients module and commands using ES6 syntax.
import { CreateSchemaCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";

// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

import fs from "node:fs";

const schemaFilePath = "SCHEMA_PATH";
let mySchema = "";

try {
  mySchema = fs.readFileSync(schemaFilePath).toString();
} catch (err) {
  mySchema = "TEST"; // for unit tests.
}

// Set the domain schema parameters.
export const createDomainSchemaParam = {
  name: "NAME" /* required */,
  schema: mySchema /* required */,
  domain:
    "DOMAIN" /* required for a domain dataset group, specify ECOMMERCE or VIDEO_ON_DEMAND */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateSchemaCommand(createDomainSchemaParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateSchema](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateSchemaCommand)」を参照してください。

### `CreateSolution`
<a name="personalize_CreateSolution_javascript_3_topic"></a>

次のコード例は、`CreateSolution` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateSolutionCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the solution parameters.
export const createSolutionParam = {
  datasetGroupArn: "DATASET_GROUP_ARN" /* required */,
  recipeArn: "RECIPE_ARN" /* required */,
  name: "NAME" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateSolutionCommand(createSolutionParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateSolution](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateSolutionCommand)」を参照してください。

### `CreateSolutionVersion`
<a name="personalize_CreateSolutionVersion_javascript_3_topic"></a>

次のコード例は、`CreateSolutionVersion` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { CreateSolutionVersionCommand } from "@aws-sdk/client-personalize";
import { personalizeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeClient = new PersonalizeClient({ region: "REGION"});

// Set the solution version parameters.
export const solutionVersionParam = {
  solutionArn: "SOLUTION_ARN" /* required */,
};

export const run = async () => {
  try {
    const response = await personalizeClient.send(
      new CreateSolutionVersionCommand(solutionVersionParam),
    );
    console.log("Success", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[CreateSolutionVersion](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize/command/CreateSolutionVersionCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon Personalize Events の例
<a name="javascript_3_personalize-events_code_examples"></a>

次のコード例は、Amazon Personalize Events で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="personalize-events_PutEvents_javascript_3_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { PutEventsCommand } from "@aws-sdk/client-personalize-events";
import { personalizeEventsClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeEventsClient = new PersonalizeEventsClient({ region: "REGION"});

// Convert your UNIX timestamp to a Date.
const sentAtDate = new Date(1613443801 * 1000); // 1613443801 is a testing value. Replace it with your sentAt timestamp in UNIX format.

// Set put events parameters.
const putEventsParam = {
  eventList: [
    /* required */
    {
      eventType: "EVENT_TYPE" /* required */,
      sentAt: sentAtDate /* required, must be a Date with js */,
      eventId: "EVENT_ID" /* optional */,
      itemId: "ITEM_ID" /* optional */,
    },
  ],
  sessionId: "SESSION_ID" /* required */,
  trackingId: "TRACKING_ID" /* required */,
  userId: "USER_ID" /* required */,
};
export const run = async () => {
  try {
    const response = await personalizeEventsClient.send(
      new PutEventsCommand(putEventsParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize-events/command/PutEventsCommand)」を参照してください。

### `PutItems`
<a name="personalize-events_PutItems_javascript_3_topic"></a>

次のコード例は、`PutItems` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { PutItemsCommand } from "@aws-sdk/client-personalize-events";
import { personalizeEventsClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeEventsClient = new PersonalizeEventsClient({ region: "REGION"});

// Set the put items parameters. For string properties and values, use the \ character to escape quotes.
const putItemsParam = {
  datasetArn: "DATASET_ARN" /* required */,
  items: [
    /* required */
    {
      itemId: "ITEM_ID" /*  required */,
      properties:
        '{"PROPERTY1_NAME": "PROPERTY1_VALUE", "PROPERTY2_NAME": "PROPERTY2_VALUE", "PROPERTY3_NAME": "PROPERTY3_VALUE"}' /* optional */,
    },
  ],
};
export const run = async () => {
  try {
    const response = await personalizeEventsClient.send(
      new PutItemsCommand(putItemsParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[PutItems](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize-events/command/PutItemsCommand)」を参照してください。

### `PutUsers`
<a name="personalize-events_PutUsers_javascript_3_topic"></a>

次のコード例は、`PutUsers` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { PutUsersCommand } from "@aws-sdk/client-personalize-events";
import { personalizeEventsClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeEventsClient = new PersonalizeEventsClient({ region: "REGION"});

// Set the put users parameters. For string properties and values, use the \ character to escape quotes.
const putUsersParam = {
  datasetArn: "DATASET_ARN",
  users: [
    {
      userId: "USER_ID",
      properties: '{"PROPERTY1_NAME": "PROPERTY1_VALUE"}',
    },
  ],
};
export const run = async () => {
  try {
    const response = await personalizeEventsClient.send(
      new PutUsersCommand(putUsersParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[PutUsers](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize-events/command/PutUsersCommand)」を参照してください。

# SDK for JavaScript (v3) による Amazon Personalize Runtime の例
<a name="javascript_3_personalize-runtime_code_examples"></a>

次のコード例は、Amazon Personalize ランタイムで AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetPersonalizedRanking`
<a name="personalize-runtime_GetPersonalizedRanking_javascript_3_topic"></a>

次のコード例は、`GetPersonalizedRanking` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { GetPersonalizedRankingCommand } from "@aws-sdk/client-personalize-runtime";
import { personalizeRuntimeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"});

// Set the ranking request parameters.
export const getPersonalizedRankingParam = {
  campaignArn: "CAMPAIGN_ARN" /* required */,
  userId: "USER_ID" /* required */,
  inputList: ["ITEM_ID_1", "ITEM_ID_2", "ITEM_ID_3", "ITEM_ID_4"],
};

export const run = async () => {
  try {
    const response = await personalizeRuntimeClient.send(
      new GetPersonalizedRankingCommand(getPersonalizedRankingParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetPersonalizedRanking](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize-runtime/command/GetPersonalizedRankingCommand)」を参照してください。

### `GetRecommendations`
<a name="personalize-runtime_GetRecommendations_javascript_3_topic"></a>

次のコード例は、`GetRecommendations` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
// Get service clients module and commands using ES6 syntax.
import { GetRecommendationsCommand } from "@aws-sdk/client-personalize-runtime";

import { personalizeRuntimeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"});

// Set the recommendation request parameters.
export const getRecommendationsParam = {
  campaignArn: "CAMPAIGN_ARN" /* required */,
  userId: "USER_ID" /* required */,
  numResults: 15 /* optional */,
};

export const run = async () => {
  try {
    const response = await personalizeRuntimeClient.send(
      new GetRecommendationsCommand(getRecommendationsParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
フィルターを使用してレコメンデーションを取得します (カスタムデータセットグループ)。  

```
// Get service clients module and commands using ES6 syntax.
import { GetRecommendationsCommand } from "@aws-sdk/client-personalize-runtime";
import { personalizeRuntimeClient } from "./libs/personalizeClients.js";
// Or, create the client here.
// const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"});

// Set the recommendation request parameters.
export const getRecommendationsParam = {
  recommenderArn: "RECOMMENDER_ARN" /* required */,
  userId: "USER_ID" /* required */,
  numResults: 15 /* optional */,
};

export const run = async () => {
  try {
    const response = await personalizeRuntimeClient.send(
      new GetRecommendationsCommand(getRecommendationsParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
ドメインデータセットグループで作成されたレコメンダーから、フィルタリングされたレコメンデーションを取得します。  

```
// Get service clients module and commands using ES6 syntax.
import { GetRecommendationsCommand } from "@aws-sdk/client-personalize-runtime";
import { personalizeRuntimeClient } from "./libs/personalizeClients.js";
// Or, create the client here:
// const personalizeRuntimeClient = new PersonalizeRuntimeClient({ region: "REGION"});

// Set recommendation request parameters.
export const getRecommendationsParam = {
  campaignArn: "CAMPAIGN_ARN" /* required */,
  userId: "USER_ID" /* required */,
  numResults: 15 /* optional */,
  filterArn: "FILTER_ARN" /* required to filter recommendations */,
  filterValues: {
    PROPERTY:
      '"VALUE"' /* Only required if your filter has a placeholder parameter */,
  },
};

export const run = async () => {
  try {
    const response = await personalizeRuntimeClient.send(
      new GetRecommendationsCommand(getRecommendationsParam),
    );
    console.log("Success!", response);
    return response; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[GetRecommendations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/personalize-runtime/command/GetRecommendationsCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon Pinpoint の例
<a name="javascript_3_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendMessages`
<a name="pinpoint_SendMessages_javascript_3_topic"></a>

次のコード例は、`SendMessages` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
import { PinpointClient } from "@aws-sdk/client-pinpoint";
// Set the AWS Region.
const REGION = "us-east-1";
export const pinClient = new PinpointClient({ region: REGION });
```
E メールメッセージを送信します。  

```
// Import required AWS SDK clients and commands for Node.js
import { SendMessagesCommand } from "@aws-sdk/client-pinpoint";
import { pinClient } from "./libs/pinClient.js";

// The FromAddress must be verified in SES.
const fromAddress = "FROM_ADDRESS";
const toAddress = "TO_ADDRESS";
const projectId = "PINPOINT_PROJECT_ID";

// The subject line of the email.
const subject = "Amazon Pinpoint Test (AWS SDK for JavaScript in Node.js)";

// The email body for recipients with non-HTML email clients.
const body_text = `Amazon Pinpoint Test (SDK for JavaScript in Node.js)
----------------------------------------------------
This email was sent with Amazon Pinpoint using the AWS SDK for JavaScript in Node.js.
For more information, see https://aws.amazon.com/sdk-for-node-js/`;

// The body of the email for recipients whose email clients support HTML content.
const body_html = `<html>
<head></head>
<body>
  <h1>Amazon Pinpoint Test (SDK for JavaScript in Node.js)</h1>
  <p>This email was sent with
    <a href='https://aws.amazon.com/pinpoint/'>the Amazon Pinpoint Email API</a> using the
    <a href='https://aws.amazon.com/sdk-for-node-js/'>
      AWS SDK for JavaScript in Node.js</a>.</p>
</body>
</html>`;

// The character encoding for the subject line and message body of the email.
const charset = "UTF-8";

const params = {
  ApplicationId: projectId,
  MessageRequest: {
    Addresses: {
      [toAddress]: {
        ChannelType: "EMAIL",
      },
    },
    MessageConfiguration: {
      EmailMessage: {
        FromAddress: fromAddress,
        SimpleEmail: {
          Subject: {
            Charset: charset,
            Data: subject,
          },
          HtmlPart: {
            Charset: charset,
            Data: body_html,
          },
          TextPart: {
            Charset: charset,
            Data: body_text,
          },
        },
      },
    },
  },
};

const run = async () => {
  try {
    const { MessageResponse } = await pinClient.send(
      new SendMessagesCommand(params),
    );

    if (!MessageResponse) {
      throw new Error("No message response.");
    }

    if (!MessageResponse.Result) {
      throw new Error("No message result.");
    }

    const recipientResult = MessageResponse.Result[toAddress];

    if (recipientResult.StatusCode !== 200) {
      throw new Error(recipientResult.StatusMessage);
    }
    console.log(recipientResult.MessageId);
  } catch (err) {
    console.log(err.message);
  }
};

run();
```
SMS メッセージを送信します。  

```
// Import required AWS SDK clients and commands for Node.js
import { SendMessagesCommand } from "@aws-sdk/client-pinpoint";
import { pinClient } from "./libs/pinClient.js";

/* The phone number or short code to send the message from. The phone number
 or short code that you specify has to be associated with your Amazon Pinpoint
account. For best results, specify long codes in E.164 format. */
const originationNumber = "SENDER_NUMBER"; //e.g., +1XXXXXXXXXX

// The recipient's phone number.  For best results, you should specify the phone number in E.164 format.
const destinationNumber = "RECEIVER_NUMBER"; //e.g., +1XXXXXXXXXX

// The content of the SMS message.
const message =
  "This message was sent through Amazon Pinpoint " +
  "using the AWS SDK for JavaScript in Node.js. Reply STOP to " +
  "opt out.";

/*The Amazon Pinpoint project/application ID to use when you send this message.
Make sure that the SMS channel is enabled for the project or application
that you choose.*/
const projectId = "PINPOINT_PROJECT_ID"; //e.g., XXXXXXXX66e4e9986478cXXXXXXXXX

/* The type of SMS message that you want to send. If you plan to send
time-sensitive content, specify TRANSACTIONAL. If you plan to send
marketing-related content, specify PROMOTIONAL.*/
const messageType = "TRANSACTIONAL";

// The registered keyword associated with the originating short code.
const registeredKeyword = "myKeyword";

/* The sender ID to use when sending the message. Support for sender ID
// varies by country or region. For more information, see
https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html.*/

const senderId = "MySenderID";

// Specify the parameters to pass to the API.
const params = {
  ApplicationId: projectId,
  MessageRequest: {
    Addresses: {
      [destinationNumber]: {
        ChannelType: "SMS",
      },
    },
    MessageConfiguration: {
      SMSMessage: {
        Body: message,
        Keyword: registeredKeyword,
        MessageType: messageType,
        OriginationNumber: originationNumber,
        SenderId: senderId,
      },
    },
  },
};

const run = async () => {
  try {
    const data = await pinClient.send(new SendMessagesCommand(params));
    console.log(
      `Message sent! ${data.MessageResponse.Result[destinationNumber].StatusMessage}`,
    );
  } catch (err) {
    console.log(err);
  }
};
run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SendMessage](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/pinpoint/command/SendMessagesCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon Polly の例
<a name="javascript_3_polly_code_examples"></a>

次のコード例は、Amazon Polly で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_javascript_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for JavaScript (v3)**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer) のプロジェクトを参照してください。次の抜粋は、 AWS SDK for JavaScript が Lambda 関数内でどのように使用されるかを示しています。  

```
import {
  ComprehendClient,
  DetectDominantLanguageCommand,
  DetectSentimentCommand,
} from "@aws-sdk/client-comprehend";

/**
 * Determine the language and sentiment of the extracted text.
 *
 * @param {{ source_text: string}} extractTextOutput
 */
export const handler = async (extractTextOutput) => {
  const comprehendClient = new ComprehendClient({});

  const detectDominantLanguageCommand = new DetectDominantLanguageCommand({
    Text: extractTextOutput.source_text,
  });

  // The source language is required for sentiment analysis and
  // translation in the next step.
  const { Languages } = await comprehendClient.send(
    detectDominantLanguageCommand,
  );

  const languageCode = Languages[0].LanguageCode;

  const detectSentimentCommand = new DetectSentimentCommand({
    Text: extractTextOutput.source_text,
    LanguageCode: languageCode,
  });

  const { Sentiment } = await comprehendClient.send(detectSentimentCommand);

  return {
    sentiment: Sentiment,
    language_code: languageCode,
  };
};
```

```
import {
  DetectDocumentTextCommand,
  TextractClient,
} from "@aws-sdk/client-textract";

/**
 * Fetch the S3 object from the event and analyze it using Amazon Textract.
 *
 * @param {import("@types/aws-lambda").EventBridgeEvent<"Object Created">} eventBridgeS3Event
 */
export const handler = async (eventBridgeS3Event) => {
  const textractClient = new TextractClient();

  const detectDocumentTextCommand = new DetectDocumentTextCommand({
    Document: {
      S3Object: {
        Bucket: eventBridgeS3Event.bucket,
        Name: eventBridgeS3Event.object,
      },
    },
  });

  // Textract returns a list of blocks. A block can be a line, a page, word, etc.
  // Each block also contains geometry of the detected text.
  // For more information on the Block type, see https://docs.aws.amazon.com/textract/latest/dg/API_Block.html.
  const { Blocks } = await textractClient.send(detectDocumentTextCommand);

  // For the purpose of this example, we are only interested in words.
  const extractedWords = Blocks.filter((b) => b.BlockType === "WORD").map(
    (b) => b.Text,
  );

  return extractedWords.join(" ");
};
```

```
import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly";
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

/**
 * Synthesize an audio file from text.
 *
 * @param {{ bucket: string, translated_text: string, object: string}} sourceDestinationConfig
 */
export const handler = async (sourceDestinationConfig) => {
  const pollyClient = new PollyClient({});

  const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
    Engine: "neural",
    Text: sourceDestinationConfig.translated_text,
    VoiceId: "Ruth",
    OutputFormat: "mp3",
  });

  const { AudioStream } = await pollyClient.send(synthesizeSpeechCommand);

  const audioKey = `${sourceDestinationConfig.object}.mp3`;

  // Store the audio file in S3.
  const s3Client = new S3Client();
  const upload = new Upload({
    client: s3Client,
    params: {
      Bucket: sourceDestinationConfig.bucket,
      Key: audioKey,
      Body: AudioStream,
      ContentType: "audio/mp3",
    },
  });

  await upload.done();
  return audioKey;
};
```

```
import {
  TranslateClient,
  TranslateTextCommand,
} from "@aws-sdk/client-translate";

/**
 * Translate the extracted text to English.
 *
 * @param {{ extracted_text: string, source_language_code: string}} textAndSourceLanguage
 */
export const handler = async (textAndSourceLanguage) => {
  const translateClient = new TranslateClient({});

  const translateCommand = new TranslateTextCommand({
    SourceLanguageCode: textAndSourceLanguage.source_language_code,
    TargetLanguageCode: "en",
    Text: textAndSourceLanguage.extracted_text,
  });

  const { TranslatedText } = await translateClient.send(translateCommand);

  return { translated_text: TranslatedText };
};
```

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for JavaScript (v3) を使用した Amazon RDS の例
<a name="javascript_3_rds_code_examples"></a>

次のコード例は、Amazon RDS で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_javascript_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScript (v3) を使用して Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して Express Node.js バックエンドと対話します。  
+ React.js ウェブアプリケーションを と統合します AWS のサービス。
+ Aurora テーブルの項目を一覧表示、追加、更新します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/aurora-serverless-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_javascript_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/* 
Node.js code here.
*/
// ES6+ example
import { Signer } from "@aws-sdk/rds-signer";
import mysql from 'mysql2/promise';

async function createAuthToken() {
  // Define connection authentication parameters
  const dbinfo = {

    hostname: process.env.ProxyHostName,
    port: process.env.Port,
    username: process.env.DBUserName,
    region: process.env.AWS_REGION,

  }

  // Create RDS Signer object
  const signer = new Signer(dbinfo);

  // Request authorization token from RDS, specifying the username
  const token = await signer.getAuthToken();
  return token;
}

async function dbOps() {

  // Obtain auth token
  const token = await createAuthToken();
  // Define connection configuration
  let connectionConfig = {
    host: process.env.ProxyHostName,
    user: process.env.DBUserName,
    password: token,
    database: process.env.DBName,
    ssl: 'Amazon RDS'
  }
  // Create the connection to the DB
  const conn = await mysql.createConnection(connectionConfig);
  // Obtain the result of the query
  const [res,] = await conn.execute('select ?+? as sum', [3, 2]);
  return res;

}

export const handler = async (event) => {
  // Execute database flow
  const result = await dbOps();
  // Return result
  return {
    statusCode: 200,
    body: JSON.stringify("The selected sum is: " + result[0].sum)
  }
};
```
TypeScript を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
import { Signer } from "@aws-sdk/rds-signer";
import mysql from 'mysql2/promise';

// RDS settings
// Using '!' (non-null assertion operator) to tell the TypeScript compiler that the DB settings are not null or undefined,
const proxy_host_name = process.env.PROXY_HOST_NAME!
const port = parseInt(process.env.PORT!)
const db_name = process.env.DB_NAME!
const db_user_name = process.env.DB_USER_NAME!
const aws_region = process.env.AWS_REGION!


async function createAuthToken(): Promise<string> {

    // Create RDS Signer object
    const signer = new Signer({
        hostname: proxy_host_name,
        port: port,
        region: aws_region,
        username: db_user_name
    });

    // Request authorization token from RDS, specifying the username
    const token = await signer.getAuthToken();
    return token;
}

async function dbOps(): Promise<mysql.QueryResult | undefined> {
    try {
        // Obtain auth token
        const token = await createAuthToken();
        const conn = await mysql.createConnection({
            host: proxy_host_name,
            user: db_user_name,
            password: token,
            database: db_name,
            ssl: 'Amazon RDS' // Ensure you have the CA bundle for SSL connection
        });
        const [rows, fields] = await conn.execute('SELECT ? + ? AS sum', [3, 2]);
        console.log('result:', rows);
        return rows;
    }
    catch (err) {
        console.log(err);
    }
}

export const lambdaHandler = async (event: any): Promise<{ statusCode: number; body: string }> => {
    // Execute database flow
    const result = await dbOps();

    // Return error is result is undefined
    if (result == undefined)
        return {
            statusCode: 500,
            body: JSON.stringify(`Error with connection to DB host`)
        }

    // Return result
    return {
        statusCode: 200,
        body: JSON.stringify(`The selected sum is: ${result[0].sum}`)
    };
};
```

# SDK for JavaScript (v3) を使用した Amazon RDS Data Service の例
<a name="javascript_3_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_javascript_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScript (v3) を使用して Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して Express Node.js バックエンドと対話します。  
+ React.js ウェブアプリケーションを と統合します AWS のサービス。
+ Aurora テーブルの項目を一覧表示、追加、更新します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/aurora-serverless-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for JavaScript (v3) を使用した Amazon Redshift の例
<a name="javascript_3_redshift_code_examples"></a>

次のコード例は、Amazon Redshift で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="redshift_CreateCluster_javascript_3_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { RedshiftClient } from "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION";
//Set the Redshift Service Object
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```
クラスターを作成します。  

```
// Import required AWS SDK clients and commands for Node.js
import { CreateClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME", // Required
  NodeType: "NODE_TYPE", //Required
  MasterUsername: "MASTER_USER_NAME", // Required - must be lowercase
  MasterUserPassword: "MASTER_USER_PASSWORD", // Required - must contain at least one uppercase letter, and one number
  ClusterType: "CLUSTER_TYPE", // Required
  IAMRoleARN: "IAM_ROLE_ARN", // Optional - the ARN of an IAM role with permissions your cluster needs to access other AWS services on your behalf, such as Amazon S3.
  ClusterSubnetGroupName: "CLUSTER_SUBNET_GROUPNAME", //Optional - the name of a cluster subnet group to be associated with this cluster. Defaults to 'default' if not specified.
  DBName: "DATABASE_NAME", // Optional - defaults to 'dev' if not specified
  Port: "PORT_NUMBER", // Optional - defaults to '5439' if not specified
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new CreateClusterCommand(params));
    console.log(
      `Cluster ${data.Cluster.ClusterIdentifier} successfully created`,
    );
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateCluster](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/redshift/command/CreateClusterCommand)」を参照してください。

### `DeleteCluster`
<a name="redshift_DeleteCluster_javascript_3_topic"></a>

次のコード例は、`DeleteCluster` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { RedshiftClient } from "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION";
//Set the Redshift Service Object
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```
クラスターを作成します。  

```
// Import required AWS SDK clients and commands for Node.js
import { DeleteClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME",
  SkipFinalClusterSnapshot: false,
  FinalClusterSnapshotIdentifier: "CLUSTER_SNAPSHOT_ID",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new DeleteClusterCommand(params));
    console.log("Success, cluster deleted. ", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteCluster](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/redshift/command/DeleteClusterCommand)」を参照してください。

### `DescribeClusters`
<a name="redshift_DescribeClusters_javascript_3_topic"></a>

次のコード例は、`DescribeClusters` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { RedshiftClient } from "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION";
//Set the Redshift Service Object
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```
クラスターを記述します。  

```
// Import required AWS SDK clients and commands for Node.js
import { DescribeClustersCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new DescribeClustersCommand(params));
    console.log("Success", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeClusters](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/redshift/command/DescribeClustersCommand)」を参照してください。

### `ModifyCluster`
<a name="redshift_ModifyCluster_javascript_3_topic"></a>

次のコード例は、`ModifyCluster` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { RedshiftClient } from "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION";
//Set the Redshift Service Object
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```
クラスターを変更します。  

```
// Import required AWS SDK clients and commands for Node.js
import { ModifyClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

// Set the parameters
const params = {
  ClusterIdentifier: "CLUSTER_NAME",
  MasterUserPassword: "NEW_MASTER_USER_PASSWORD",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new ModifyClusterCommand(params));
    console.log("Success was modified.", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ModifyCluster](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/redshift/command/ModifyClusterCommand)」を参照してください。

# SDK for JavaScript (v3) を使用する Amazon Rekognition の例
<a name="javascript_3_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_javascript_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for JavaScript (v3)**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo-asset-manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_javascript_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 で Amazon Rekognition を使用して、Amazon Rekognition を使用して Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内のオブジェクトをカテゴリ別に識別するアプリケーション AWS SDK for JavaScript を作成する方法を示します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
以下ではその方法を説明しています。  
+ Amazon Cognito を使用して認証されていないユーザーを作成します。
+ Amazon Rekognition を使用して、オブジェクトのイメージを分析します。
+ Amazon SES の E メールアドレスを検証します。
+ Amazon SES を使用して、E メール通知を送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo_analyzer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

# SDK for JavaScript (v3) を使用した Amazon S3 の例
<a name="javascript_3_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_javascript_3_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import {
  paginateListBuckets,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * List the S3 buckets in your configured AWS account.
 */
export const helloS3 = async () => {
  // When no region or credentials are provided, the SDK will use the
  // region and credentials from the local AWS config.
  const client = new S3Client({});

  try {
    /**
     * @type { import("@aws-sdk/client-s3").Bucket[] }
     */
    const buckets = [];

    for await (const page of paginateListBuckets({ client }, {})) {
      buckets.push(...page.Buckets);
    }
    console.log("Buckets: ");
    console.log(buckets.map((bucket) => bucket.Name).join("\n"));
    return buckets;
  } catch (caught) {
    // ListBuckets does not throw any modeled errors. Any error caught
    // here will be something generic like `AccessDenied`.
    if (caught instanceof S3ServiceException) {
      console.error(`${caught.name}: ${caught.message}`);
    } else {
      // Something besides S3 failed.
      throw caught;
    }
  }
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/ListBucketsCommand)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
まず、必要なモジュールをすべてインポートします。  

```
// Used to check if currently running file is this file.
import { fileURLToPath } from "node:url";
import { readdirSync, readFileSync, writeFileSync } from "node:fs";

// Local helper utils.
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js";
import { wrapText } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

import {
  S3Client,
  CreateBucketCommand,
  PutObjectCommand,
  ListObjectsCommand,
  CopyObjectCommand,
  GetObjectCommand,
  DeleteObjectsCommand,
  DeleteBucketCommand,
} from "@aws-sdk/client-s3";
```
前述のインポートでは、いくつかのヘルパーユーティリティを参照しています。これらのユーティリティは、このセクションの冒頭でリンクされている GitHub リポジトリのローカルにあります。参考までに、これらのユーティリティの以下の実装を参照してください。  

```
export const dirnameFromMetaUrl = (metaUrl) =>
  fileURLToPath(new URL(".", metaUrl));

import { select, input, confirm, checkbox, password } from "@inquirer/prompts";

export class Prompter {
  /**
   * @param {{ message: string, choices: { name: string, value: string }[]}} options
   */
  select(options) {
    return select(options);
  }

  /**
   * @param {{ message: string }} options
   */
  input(options) {
    return input(options);
  }

  /**
   * @param {{ message: string }} options
   */
  password(options) {
    return password({ ...options, mask: true });
  }

  /**
   * @param {string} prompt
   */
  checkContinue = async (prompt = "") => {
    const prefix = prompt && `${prompt} `;
    const ok = await this.confirm({
      message: `${prefix}Continue?`,
    });
    if (!ok) throw new Error("Exiting...");
  };

  /**
   * @param {{ message: string }} options
   */
  confirm(options) {
    return confirm(options);
  }

  /**
   * @param {{ message: string, choices: { name: string, value: string }[]}} options
   */
  checkbox(options) {
    return checkbox(options);
  }
}

export const wrapText = (text, char = "=") => {
  const rule = char.repeat(80);
  return `${rule}\n    ${text}\n${rule}\n`;
};
```
オブジェクトは「バケット」に保存されます。新しいバケットを作成する関数を定義しましょう。  

```
export const createBucket = async () => {
  const bucketName = await prompter.input({
    message: "Enter a bucket name. Bucket names must be globally unique:",
  });
  const command = new CreateBucketCommand({ Bucket: bucketName });
  await s3Client.send(command);
  console.log("Bucket created successfully.\n");
  return bucketName;
};
```
バケットには「オブジェクト」が含まれています。この関数は、ディレクトリの内容をバケットにオブジェクトとしてアップロードします。  

```
export const uploadFilesToBucket = async ({ bucketName, folderPath }) => {
  console.log(`Uploading files from ${folderPath}\n`);
  const keys = readdirSync(folderPath);
  const files = keys.map((key) => {
    const filePath = `${folderPath}/${key}`;
    const fileContent = readFileSync(filePath);
    return {
      Key: key,
      Body: fileContent,
    };
  });

  for (const file of files) {
    await s3Client.send(
      new PutObjectCommand({
        Bucket: bucketName,
        Body: file.Body,
        Key: file.Key,
      }),
    );
    console.log(`${file.Key} uploaded successfully.`);
  }
};
```
オブジェクトをアップロードしたら、正しくアップロードされたことを確認します。そのためには ListObjects を使用できます。ここでは 'Key' プロパティを使用しますが、レスポンスには他にも便利なプロパティがあります。  

```
export const listFilesInBucket = async ({ bucketName }) => {
  const command = new ListObjectsCommand({ Bucket: bucketName });
  const { Contents } = await s3Client.send(command);
  const contentsList = Contents.map((c) => ` • ${c.Key}`).join("\n");
  console.log("\nHere's a list of files in the bucket:");
  console.log(`${contentsList}\n`);
};
```
バケットから別のバケットにオブジェクトをコピーしたい場合があります。そのためには、CopyObject コマンドを使用してください。  

```
export const copyFileFromBucket = async ({ destinationBucket }) => {
  const proceed = await prompter.confirm({
    message: "Would you like to copy an object from another bucket?",
  });

  if (!proceed) {
    return;
  }
  const copy = async () => {
    try {
      const sourceBucket = await prompter.input({
        message: "Enter source bucket name:",
      });
      const sourceKey = await prompter.input({
        message: "Enter source key:",
      });
      const destinationKey = await prompter.input({
        message: "Enter destination key:",
      });

      const command = new CopyObjectCommand({
        Bucket: destinationBucket,
        CopySource: `${sourceBucket}/${sourceKey}`,
        Key: destinationKey,
      });
      await s3Client.send(command);
      await copyFileFromBucket({ destinationBucket });
    } catch (err) {
      console.error("Copy error.");
      console.error(err);
      const retryAnswer = await prompter.confirm({ message: "Try again?" });
      if (retryAnswer) {
        await copy();
      }
    }
  };
  await copy();
};
```
バケットから複数のオブジェクトを取得するための SDK メソッドはありません。代わりに、ダウンロードして繰り返し処理するオブジェクトのリストを作成します。  

```
export const downloadFilesFromBucket = async ({ bucketName }) => {
  const { Contents } = await s3Client.send(
    new ListObjectsCommand({ Bucket: bucketName }),
  );
  const path = await prompter.input({
    message: "Enter destination path for files:",
  });

  for (const content of Contents) {
    const obj = await s3Client.send(
      new GetObjectCommand({ Bucket: bucketName, Key: content.Key }),
    );
    writeFileSync(
      `${path}/${content.Key}`,
      await obj.Body.transformToByteArray(),
    );
  }
  console.log("Files downloaded successfully.\n");
};
```
では、リソースをクリーンアップしましょう。バケットを削除するには、そのバケットを空にしておく必要があります。これら 2 つの関数はバケットを空にして削除します。  

```
export const emptyBucket = async ({ bucketName }) => {
  const listObjectsCommand = new ListObjectsCommand({ Bucket: bucketName });
  const { Contents } = await s3Client.send(listObjectsCommand);
  const keys = Contents.map((c) => c.Key);

  const deleteObjectsCommand = new DeleteObjectsCommand({
    Bucket: bucketName,
    Delete: { Objects: keys.map((key) => ({ Key: key })) },
  });
  await s3Client.send(deleteObjectsCommand);
  console.log(`${bucketName} emptied successfully.\n`);
};

export const deleteBucket = async ({ bucketName }) => {
  const command = new DeleteBucketCommand({ Bucket: bucketName });
  await s3Client.send(command);
  console.log(`${bucketName} deleted successfully.\n`);
};
```
「main」関数はすべてをまとめます。このファイルを直接実行すると、main 関数が呼び出されます。  

```
const main = async () => {
  const OBJECT_DIRECTORY = `${dirnameFromMetaUrl(
    import.meta.url,
  )}../../../../resources/sample_files/.sample_media`;

  try {
    console.log(wrapText("Welcome to the Amazon S3 getting started example."));
    console.log("Let's create a bucket.");
    const bucketName = await createBucket();
    await prompter.confirm({ message: continueMessage });

    console.log(wrapText("File upload."));
    console.log(
      "I have some default files ready to go. You can edit the source code to provide your own.",
    );
    await uploadFilesToBucket({
      bucketName,
      folderPath: OBJECT_DIRECTORY,
    });

    await listFilesInBucket({ bucketName });
    await prompter.confirm({ message: continueMessage });

    console.log(wrapText("Copy files."));
    await copyFileFromBucket({ destinationBucket: bucketName });
    await listFilesInBucket({ bucketName });
    await prompter.confirm({ message: continueMessage });

    console.log(wrapText("Download files."));
    await downloadFilesFromBucket({ bucketName });

    console.log(wrapText("Clean up."));
    await emptyBucket({ bucketName });
    await deleteBucket({ bucketName });
  } catch (err) {
    console.error(err);
  }
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/CopyObjectCommand)
  + [CreateBucket](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/CreateBucketCommand)
  + [DeleteBucket](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteBucketCommand)
  + [DeleteObjects](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteObjectsCommand)
  + [GetObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectCommand)
  + [ListObjectsV2](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/ListObjectsV2Command)
  + [PutObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectCommand)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_javascript_3_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトをコピーします。  

```
import {
  S3Client,
  CopyObjectCommand,
  ObjectNotInActiveTierError,
  waitUntilObjectExists,
} from "@aws-sdk/client-s3";

/**
 * Copy an S3 object from one bucket to another.
 *
 * @param {{
 *   sourceBucket: string,
 *   sourceKey: string,
 *   destinationBucket: string,
 *   destinationKey: string }} config
 */
export const main = async ({
  sourceBucket,
  sourceKey,
  destinationBucket,
  destinationKey,
}) => {
  const client = new S3Client({});

  try {
    await client.send(
      new CopyObjectCommand({
        CopySource: `${sourceBucket}/${sourceKey}`,
        Bucket: destinationBucket,
        Key: destinationKey,
      }),
    );
    await waitUntilObjectExists(
      { client },
      { Bucket: destinationBucket, Key: destinationKey },
    );
    console.log(
      `Successfully copied ${sourceBucket}/${sourceKey} to ${destinationBucket}/${destinationKey}`,
    );
  } catch (caught) {
    if (caught instanceof ObjectNotInActiveTierError) {
      console.error(
        `Could not copy ${sourceKey} from ${sourceBucket}. Object is not in the active tier.`,
      );
    } else {
      throw caught;
    }
  }
};
```
ETag が指定されたものと一致しないことを条件にオブジェクトをコピーします。  

```
import {
  CopyObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

// Optionally edit the default key name of the copied object in 'object_name.json'
import data from "../scenarios/conditional-requests/object_name.json" assert {
  type: "json",
};

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ sourceBucketName: string, sourceKeyName: string, destinationBucketName: string, eTag: string }}
 */
export const main = async ({
  sourceBucketName,
  sourceKeyName,
  destinationBucketName,
  eTag,
}) => {
  const client = new S3Client({});
  const name = data.name;
  try {
    const response = await client.send(
      new CopyObjectCommand({
        CopySource: `${sourceBucketName}/${sourceKeyName}`,
        Bucket: destinationBucketName,
        Key: `${name}${sourceKeyName}`,
        CopySourceIfMatch: eTag,
      }),
    );
    console.log("Successfully copied object to bucket.");
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while copying object "${sourceKeyName}" from "${sourceBucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Unable to copy object "${sourceKeyName}" to bucket "${sourceBucketName}":  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    sourceBucketName: {
      type: "string",
      required: true,
    },
    sourceKeyName: {
      type: "string",
      required: true,
    },
    destinationBucketName: {
      type: "string",
      required: true,
    },
    eTag: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
ETag が指定されたものと一致しないことを条件にオブジェクトをコピーします。  

```
import {
  CopyObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

// Optionally edit the default key name of the copied object in 'object_name.json'
import data from "../scenarios/conditional-requests/object_name.json" assert {
  type: "json",
};

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ sourceBucketName: string, sourceKeyName: string, destinationBucketName: string, eTag: string }}
 */
export const main = async ({
  sourceBucketName,
  sourceKeyName,
  destinationBucketName,
  eTag,
}) => {
  const client = new S3Client({});
  const name = data.name;

  try {
    const response = await client.send(
      new CopyObjectCommand({
        CopySource: `${sourceBucketName}/${sourceKeyName}`,
        Bucket: destinationBucketName,
        Key: `${name}${sourceKeyName}`,
        CopySourceIfNoneMatch: eTag,
      }),
    );
    console.log("Successfully copied object to bucket.");
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while copying object "${sourceKeyName}" from "${sourceBucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Unable to copy object "${sourceKeyName}" to bucket "${sourceBucketName}":  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    sourceBucketName: {
      type: "string",
      required: true,
    },
    sourceKeyName: {
      type: "string",
      required: true,
    },
    destinationBucketName: {
      type: "string",
      required: true,
    },
    eTag: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
特定の期間内に作成または変更されたという条件に基づいて、オブジェクトをコピーします。  

```
import {
  CopyObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

// Optionally edit the default key name of the copied object in 'object_name.json'
import data from "../scenarios/conditional-requests/object_name.json" assert {
  type: "json",
};

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ sourceBucketName: string, sourceKeyName: string, destinationBucketName: string }}
 */
export const main = async ({
  sourceBucketName,
  sourceKeyName,
  destinationBucketName,
}) => {
  const date = new Date();
  date.setDate(date.getDate() - 1);

  const name = data.name;
  const client = new S3Client({});
  const copySource = `${sourceBucketName}/${sourceKeyName}`;
  const copiedKey = name + sourceKeyName;

  try {
    const response = await client.send(
      new CopyObjectCommand({
        CopySource: copySource,
        Bucket: destinationBucketName,
        Key: copiedKey,
        CopySourceIfModifiedSince: date,
      }),
    );
    console.log("Successfully copied object to bucket.");
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while copying object "${sourceKeyName}" from "${sourceBucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while copying object from ${sourceBucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    sourceBucketName: {
      type: "string",
      required: true,
    },
    sourceKeyName: {
      type: "string",
      required: true,
    },
    destinationBucketName: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
特定の期間内に作成または変更されていないという条件に基づいて、オブジェクトをコピーします。  

```
import {
  CopyObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

// Optionally edit the default key name of the copied object in 'object_name.json'
import data from "../scenarios/conditional-requests/object_name.json" assert {
  type: "json",
};

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ sourceBucketName: string, sourceKeyName: string, destinationBucketName: string }}
 */
export const main = async ({
  sourceBucketName,
  sourceKeyName,
  destinationBucketName,
}) => {
  const date = new Date();
  date.setDate(date.getDate() - 1);
  const client = new S3Client({});
  const name = data.name;
  const copiedKey = name + sourceKeyName;
  const copySource = `${sourceBucketName}/${sourceKeyName}`;

  try {
    const response = await client.send(
      new CopyObjectCommand({
        CopySource: copySource,
        Bucket: destinationBucketName,
        Key: copiedKey,
        CopySourceIfUnmodifiedSince: date,
      }),
    );
    console.log("Successfully copied object to bucket.");
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while copying object "${sourceKeyName}" from "${sourceBucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while copying object from ${sourceBucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    sourceBucketName: {
      type: "string",
      required: true,
    },
    sourceKeyName: {
      type: "string",
      required: true,
    },
    destinationBucketName: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[CopyObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/CopyObjectCommand)」を参照してください。**

### `CreateBucket`
<a name="s3_CreateBucket_javascript_3_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットを作成します。  

```
import {
  BucketAlreadyExists,
  BucketAlreadyOwnedByYou,
  CreateBucketCommand,
  S3Client,
  waitUntilBucketExists,
} from "@aws-sdk/client-s3";

/**
 * Create an Amazon S3 bucket.
 * @param {{ bucketName: string }} config
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    const { Location } = await client.send(
      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: bucketName,
      }),
    );
    await waitUntilBucketExists({ client }, { Bucket: bucketName });
    console.log(`Bucket created with location ${Location}`);
  } catch (caught) {
    if (caught instanceof BucketAlreadyExists) {
      console.error(
        `The bucket "${bucketName}" already exists in another AWS account. Bucket names must be globally unique.`,
      );
    }
    // WARNING: If you try to create a bucket in the North Virginia region,
    // and you already own a bucket in that region with the same name, this
    // error will not be thrown. Instead, the call will return successfully
    // and the ACL on that bucket will be reset.
    else if (caught instanceof BucketAlreadyOwnedByYou) {
      console.error(
        `The bucket "${bucketName}" already exists in this AWS account.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-new-bucket-2)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[CreateBucket](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/CreateBucketCommand)」を参照してください。**

### `DeleteBucket`
<a name="s3_DeleteBucket_javascript_3_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
 バケットを削除します。  

```
import {
  DeleteBucketCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Delete an Amazon S3 bucket.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});
  const command = new DeleteBucketCommand({
    Bucket: bucketName,
  });

  try {
    await client.send(command);
    console.log("Bucket was deleted.");
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while deleting bucket. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while deleting the bucket. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-deleting-buckets)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[DeleteBucket](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteBucketCommand)」を参照してください。**

### `DeleteBucketPolicy`
<a name="s3_DeleteBucketPolicy_javascript_3_topic"></a>

次のコード例は、`DeleteBucketPolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットポリシーを削除します。  

```
import {
  DeleteBucketPolicyCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Remove the policy from an Amazon S3 bucket.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    await client.send(
      new DeleteBucketPolicyCommand({
        Bucket: bucketName,
      }),
    );
    console.log(`Bucket policy deleted from "${bucketName}".`);
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while deleting policy from ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while deleting policy from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-bucket-policies.html#s3-example-bucket-policies-delete-policy)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteBucketPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteBucketPolicyCommand)」を参照してください。

### `DeleteBucketWebsite`
<a name="s3_DeleteBucketWebsite_javascript_3_topic"></a>

次のコード例は、`DeleteBucketWebsite` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットからウェブサイト設定を削除します。  

```
import {
  DeleteBucketWebsiteCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Remove the website configuration for a bucket.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    await client.send(
      new DeleteBucketWebsiteCommand({
        Bucket: bucketName,
      }),
    );
    // The response code will be successful for both removed configurations and
    // configurations that did not exist in the first place.
    console.log(
      `The bucket "${bucketName}" is not longer configured as a website, or it never was.`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while removing website configuration from ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while removing website configuration from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-static-web-host.html#s3-example-static-web-host-delete-website)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteBucketWebsite](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteBucketWebsiteCommand)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_javascript_3_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトを削除します。  

```
import {
  DeleteObjectCommand,
  S3Client,
  S3ServiceException,
  waitUntilObjectNotExists,
} from "@aws-sdk/client-s3";

/**
 * Delete one object from an Amazon S3 bucket.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const client = new S3Client({});

  try {
    await client.send(
      new DeleteObjectCommand({
        Bucket: bucketName,
        Key: key,
      }),
    );
    await waitUntilObjectNotExists(
      { client },
      { Bucket: bucketName, Key: key },
    );
    // A successful delete, or a delete for a non-existent object, both return
    // a 204 response code.
    console.log(
      `The object "${key}" from bucket "${bucketName}" was deleted, or it didn't exist.`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while deleting object from ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while deleting object from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteObjectCommand)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_javascript_3_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
複数のオブジェクトを削除します。  

```
import {
  DeleteObjectsCommand,
  S3Client,
  S3ServiceException,
  waitUntilObjectNotExists,
} from "@aws-sdk/client-s3";

/**
 * Delete multiple objects from an S3 bucket.
 * @param {{ bucketName: string, keys: string[] }}
 */
export const main = async ({ bucketName, keys }) => {
  const client = new S3Client({});

  try {
    const { Deleted } = await client.send(
      new DeleteObjectsCommand({
        Bucket: bucketName,
        Delete: {
          Objects: keys.map((k) => ({ Key: k })),
        },
      }),
    );
    for (const key in keys) {
      await waitUntilObjectNotExists(
        { client },
        { Bucket: bucketName, Key: key },
      );
    }
    console.log(
      `Successfully deleted ${Deleted.length} objects from S3 bucket. Deleted objects:`,
    );
    console.log(Deleted.map((d) => ` • ${d.Key}`).join("\n"));
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while deleting objects from ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while deleting objects from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteObjectsCommand)」を参照してください。**

### `GetBucketAcl`
<a name="s3_GetBucketAcl_javascript_3_topic"></a>

次のコード例は、`GetBucketAcl` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
ACL 許可を取得します。  

```
import {
  GetBucketAclCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Retrieves the Access Control List (ACL) for an S3 bucket.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    const response = await client.send(
      new GetBucketAclCommand({
        Bucket: bucketName,
      }),
    );
    console.log(`ACL for bucket "${bucketName}":`);
    console.log(JSON.stringify(response, null, 2));
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while getting ACL for ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting ACL for ${bucketName}. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-access-permissions.html#s3-example-access-permissions-get-acl)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetBucketAcl](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetBucketAclCommand)」を参照してください。

### `GetBucketCors`
<a name="s3_GetBucketCors_javascript_3_topic"></a>

次のコード例は、`GetBucketCors` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットの CORS ポリシーを取得します。  

```
import {
  GetBucketCorsCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Log the Cross-Origin Resource Sharing (CORS) configuration information
 * set for the bucket.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});
  const command = new GetBucketCorsCommand({
    Bucket: bucketName,
  });

  try {
    const { CORSRules } = await client.send(command);
    console.log(JSON.stringify(CORSRules));
    CORSRules.forEach((cr, i) => {
      console.log(
        `\nCORSRule ${i + 1}`,
        `\n${"-".repeat(10)}`,
        `\nAllowedHeaders: ${cr.AllowedHeaders}`,
        `\nAllowedMethods: ${cr.AllowedMethods}`,
        `\nAllowedOrigins: ${cr.AllowedOrigins}`,
        `\nExposeHeaders: ${cr.ExposeHeaders}`,
        `\nMaxAgeSeconds: ${cr.MaxAgeSeconds}`,
      );
    });
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while getting bucket CORS rules for ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting bucket CORS rules for ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-configuring-buckets.html#s3-example-configuring-buckets-get-cors)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[GetBucketCors](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetBucketCorsCommand)」を参照してください。**

### `GetBucketPolicy`
<a name="s3_GetBucketPolicy_javascript_3_topic"></a>

次のコード例は、`GetBucketPolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットポリシーを取得します。  

```
import {
  GetBucketPolicyCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Logs the policy for a specified bucket.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    const { Policy } = await client.send(
      new GetBucketPolicyCommand({
        Bucket: bucketName,
      }),
    );
    console.log(`Policy for "${bucketName}":\n${Policy}`);
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while getting policy from ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting policy from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-bucket-policies.html#s3-example-bucket-policies-get-policy)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetBucketPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetBucketPolicyCommand)」を参照してください。

### `GetBucketWebsite`
<a name="s3_GetBucketWebsite_javascript_3_topic"></a>

次のコード例は、`GetBucketWebsite` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
ウェブサイト設定を取得します。  

```
import {
  GetBucketWebsiteCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Log the website configuration for a bucket.
 * @param {{ bucketName }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    const response = await client.send(
      new GetBucketWebsiteCommand({
        Bucket: bucketName,
      }),
    );
    console.log(
      `Your bucket is set up to host a website with the following configuration:\n${JSON.stringify(response, null, 2)}`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchWebsiteConfiguration"
    ) {
      console.error(
        `Error from S3 while getting website configuration for ${bucketName}. The bucket isn't configured as a website.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting website configuration for ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetBucketWebsite](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetBucketWebsiteCommand)」を参照してください。

### `GetObject`
<a name="s3_GetObject_javascript_3_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトをダウンロードします。  

```
import {
  GetObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const client = new S3Client({});

  try {
    const response = await client.send(
      new GetObjectCommand({
        Bucket: bucketName,
        Key: key,
      }),
    );
    // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods.
    const str = await response.Body.transformToString();
    console.log(str);
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while getting object "${key}" from "${bucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
ETag が指定されたものと一致することを条件に、オブジェクトをダウンロードします。  

```
import {
  GetObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ bucketName: string, key: string, eTag: string }}
 */
export const main = async ({ bucketName, key, eTag }) => {
  const client = new S3Client({});

  try {
    const response = await client.send(
      new GetObjectCommand({
        Bucket: bucketName,
        Key: key,
        IfMatch: eTag,
      }),
    );
    // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods.
    const str = await response.Body.transformToString();
    console.log("Success. Here is text of the file:", str);
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while getting object "${key}" from "${bucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
    eTag: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
ETag が指定されたものと一致しないことを条件に、オブジェクトをダウンロードします。  

```
import {
  GetObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ bucketName: string, key: string, eTag: string }}
 */
export const main = async ({ bucketName, key, eTag }) => {
  const client = new S3Client({});

  try {
    const response = await client.send(
      new GetObjectCommand({
        Bucket: bucketName,
        Key: key,
        IfNoneMatch: eTag,
      }),
    );
    // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods.
    const str = await response.Body.transformToString();
    console.log("Success. Here is text of the file:", str);
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while getting object "${key}" from "${bucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object from ${bucketName}. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
    eTag: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
特定の期間に作成または変更されたことを条件に、オブジェクトをダウンロードします。  

```
import {
  GetObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const client = new S3Client({});
  const date = new Date();
  date.setDate(date.getDate() - 1);
  try {
    const response = await client.send(
      new GetObjectCommand({
        Bucket: bucketName,
        Key: key,
        IfModifiedSince: date,
      }),
    );
    // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods.
    const str = await response.Body.transformToString();
    console.log("Success. Here is text of the file:", str);
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while getting object "${key}" from "${bucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
特定の期間に作成または変更されていないことを条件に、オブジェクトをダウンロードします。  

```
import {
  GetObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const client = new S3Client({});
  const date = new Date();
  date.setDate(date.getDate() - 1);
  try {
    const response = await client.send(
      new GetObjectCommand({
        Bucket: bucketName,
        Key: key,
        IfUnmodifiedSince: date,
      }),
    );
    // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods.
    const str = await response.Body.transformToString();
    console.log("Success. Here is text of the file:", str);
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while getting object "${key}" from "${bucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-get-object)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[GetObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectCommand)」を参照してください。**

### `GetObjectLegalHold`
<a name="s3_GetObjectLegalHold_javascript_3_topic"></a>

次のコード例は、`GetObjectLegalHold` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import {
  GetObjectLegalHoldCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Get an object's current legal hold status.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const client = new S3Client({});

  try {
    const response = await client.send(
      new GetObjectLegalHoldCommand({
        Bucket: bucketName,
        Key: key,
        // Optionally, you can provide additional parameters
        // ExpectedBucketOwner: "<account ID that is expected to own the bucket>",
        // VersionId: "<the specific version id of the object to check>",
      }),
    );
    console.log(`Legal Hold Status: ${response.LegalHold.Status}`);
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while getting legal hold status for ${key} in ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting legal hold status for ${key} in ${bucketName} from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetObjectLegalHold](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectLegalHoldCommand)」を参照してください。

### `GetObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_javascript_3_topic"></a>

次のコード例は、`GetObjectLockConfiguration` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import {
  GetObjectLockConfigurationCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Gets the Object Lock configuration for a bucket.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    const { ObjectLockConfiguration } = await client.send(
      new GetObjectLockConfigurationCommand({
        Bucket: bucketName,
        // Optionally, you can provide additional parameters
        // ExpectedBucketOwner: "<account ID that is expected to own the bucket>",
      }),
    );
    console.log(
      `Object Lock Configuration:\n${JSON.stringify(ObjectLockConfiguration)}`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while getting object lock configuration for ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object lock configuration for ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetObjectLockConfiguration](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectLockConfigurationCommand)」を参照してください。

### `GetObjectRetention`
<a name="s3_GetObjectRetention_javascript_3_topic"></a>

次のコード例は、`GetObjectRetention` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import {
  GetObjectRetentionCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Log the "RetainUntilDate" for an object in an S3 bucket.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const client = new S3Client({});

  try {
    const { Retention } = await client.send(
      new GetObjectRetentionCommand({
        Bucket: bucketName,
        Key: key,
      }),
    );
    console.log(
      `${key} in ${bucketName} will be retained until ${Retention.RetainUntilDate}`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchObjectLockConfiguration"
    ) {
      console.warn(
        `The object "${key}" in the bucket "${bucketName}" does not have an ObjectLock configuration.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object retention settings for "${bucketName}".  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetObjectRetention](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectRetentionCommand)」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_javascript_3_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットを一覧表示します。  

```
import {
  paginateListBuckets,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * List the Amazon S3 buckets in your account.
 */
export const main = async () => {
  const client = new S3Client({});
  /** @type {?import('@aws-sdk/client-s3').Owner} */
  let Owner = null;

  /** @type {import('@aws-sdk/client-s3').Bucket[]} */
  const Buckets = [];

  try {
    const paginator = paginateListBuckets({ client }, {});

    for await (const page of paginator) {
      if (!Owner) {
        Owner = page.Owner;
      }

      Buckets.push(...page.Buckets);
    }

    console.log(
      `${Owner.DisplayName} owns ${Buckets.length} bucket${
        Buckets.length === 1 ? "" : "s"
      }:`,
    );
    console.log(`${Buckets.map((b) => ` • ${b.Name}`).join("\n")}`);
  } catch (caught) {
    if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while listing buckets.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-list-buckets)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/ListBucketsCommand)」を参照してください。**

### `ListObjectsV2`
<a name="s3_ListObjectsV2_javascript_3_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケット内のすべてのオブジェクトを一覧表示します。オブジェクトが複数ある場合は、IsTruncated と NextContinuationToken を使用してリスト全体を繰り返し処理します。  

```
import {
  S3Client,
  S3ServiceException,
  // This command supersedes the ListObjectsCommand and is the recommended way to list objects.
  paginateListObjectsV2,
} from "@aws-sdk/client-s3";

/**
 * Log all of the object keys in a bucket.
 * @param {{ bucketName: string, pageSize: string }}
 */
export const main = async ({ bucketName, pageSize }) => {
  const client = new S3Client({});
  /** @type {string[][]} */
  const objects = [];
  try {
    const paginator = paginateListObjectsV2(
      { client, /* Max items per page */ pageSize: Number.parseInt(pageSize) },
      { Bucket: bucketName },
    );

    for await (const page of paginator) {
      objects.push(page.Contents.map((o) => o.Key));
    }
    objects.forEach((objectList, pageNum) => {
      console.log(
        `Page ${pageNum + 1}\n------\n${objectList.map((o) => `• ${o}`).join("\n")}\n`,
      );
    });
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while listing objects for "${bucketName}". The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while listing objects for "${bucketName}".  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[ListObjectsV2](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/ListObjectsV2Command)」を参照してください。**

### `PutBucketAcl`
<a name="s3_PutBucketAcl_javascript_3_topic"></a>

次のコード例は、`PutBucketAcl` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケット ACL をプットします。  

```
import {
  PutBucketAclCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Grant read access to a user using their canonical AWS account ID.
 *
 * Most Amazon S3 use cases don't require the use of access control lists (ACLs).
 * We recommend that you disable ACLs, except in unusual circumstances where
 * you need to control access for each object individually. Consider a policy instead.
 * For more information see https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-policies.html.
 * @param {{ bucketName: string, granteeCanonicalUserId: string, ownerCanonicalUserId }}
 */
export const main = async ({
  bucketName,
  granteeCanonicalUserId,
  ownerCanonicalUserId,
}) => {
  const client = new S3Client({});
  const command = new PutBucketAclCommand({
    Bucket: bucketName,
    AccessControlPolicy: {
      Grants: [
        {
          Grantee: {
            // The canonical ID of the user. This ID is an obfuscated form of your AWS account number.
            // It's unique to Amazon S3 and can't be found elsewhere.
            // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/finding-canonical-user-id.html.
            ID: granteeCanonicalUserId,
            Type: "CanonicalUser",
          },
          // One of FULL_CONTROL | READ | WRITE | READ_ACP | WRITE_ACP
          // https://docs.aws.amazon.com/AmazonS3/latest/API/API_Grant.html#AmazonS3-Type-Grant-Permission
          Permission: "READ",
        },
      ],
      Owner: {
        ID: ownerCanonicalUserId,
      },
    },
  });

  try {
    await client.send(command);
    console.log(`Granted READ access to ${bucketName}`);
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while setting ACL for bucket ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while setting ACL for bucket ${bucketName}. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-access-permissions.html#s3-example-access-permissions-put-acl)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutBucketAcl](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutBucketAclCommand)」を参照してください。

### `PutBucketCors`
<a name="s3_PutBucketCors_javascript_3_topic"></a>

次のコード例は、`PutBucketCors` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
CORS ルールを追加します。  

```
import {
  PutBucketCorsCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Allows cross-origin requests to an S3 bucket by setting the CORS configuration.
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});

  try {
    await client.send(
      new PutBucketCorsCommand({
        Bucket: bucketName,
        CORSConfiguration: {
          CORSRules: [
            {
              // Allow all headers to be sent to this bucket.
              AllowedHeaders: ["*"],
              // Allow only GET and PUT methods to be sent to this bucket.
              AllowedMethods: ["GET", "PUT"],
              // Allow only requests from the specified origin.
              AllowedOrigins: ["https://www.example.com"],
              // Allow the entity tag (ETag) header to be returned in the response. The ETag header
              // The entity tag represents a specific version of the object. The ETag reflects
              // changes only to the contents of an object, not its metadata.
              ExposeHeaders: ["ETag"],
              // How long the requesting browser should cache the preflight response. After
              // this time, the preflight request will have to be made again.
              MaxAgeSeconds: 3600,
            },
          ],
        },
      }),
    );
    console.log(`Successfully set CORS rules for bucket: ${bucketName}`);
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while setting CORS rules for ${bucketName}. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while setting CORS rules for ${bucketName}. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-configuring-buckets.html#s3-example-configuring-buckets-put-cors)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[PutBucketCors](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutBucketCorsCommand)」を参照してください。**

### `PutBucketPolicy`
<a name="s3_PutBucketPolicy_javascript_3_topic"></a>

次のコード例は、`PutBucketPolicy` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
ポリシーを追加します。  

```
import {
  PutBucketPolicyCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Grant an IAM role GetObject access to all of the objects
 * in the provided bucket.
 * @param {{ bucketName: string, iamRoleArn: string }}
 */
export const main = async ({ bucketName, iamRoleArn }) => {
  const client = new S3Client({});
  const command = new PutBucketPolicyCommand({
    // This is a resource-based policy. For more information on resource-based policies,
    // see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_resource-based.
    Policy: JSON.stringify({
      Version: "2012-10-17",
      Statement: [
        {
          Effect: "Allow",
          Principal: {
            AWS: iamRoleArn,
          },
          Action: "s3:GetObject",
          Resource: `arn:aws:s3:::${bucketName}/*`,
        },
      ],
    }),
    // Apply the preceding policy to this bucket.
    Bucket: bucketName,
  });

  try {
    await client.send(command);
    console.log(
      `GetObject access to the bucket "${bucketName}" was granted to the provided IAM role.`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "MalformedPolicy"
    ) {
      console.error(
        `Error from S3 while setting the bucket policy for the bucket "${bucketName}". The policy was malformed.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while setting the bucket policy for the bucket "${bucketName}". ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-bucket-policies.html#s3-example-bucket-policies-set-policy)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[PutBucketPolicy](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutBucketPolicyCommand)」を参照してください。**

### `PutBucketWebsite`
<a name="s3_PutBucketWebsite_javascript_3_topic"></a>

次のコード例は、`PutBucketWebsite` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
ウェブサイト設定を設定します。  

```
import {
  PutBucketWebsiteCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Configure an Amazon S3 bucket to serve a static website.
 * Website access must also be granted separately. For more information
 * on setting the permissions for website access, see
 * https://docs.aws.amazon.com/AmazonS3/latest/userguide/WebsiteAccessPermissionsReqd.html.
 *
 * @param {{ bucketName: string }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});
  const command = new PutBucketWebsiteCommand({
    Bucket: bucketName,
    WebsiteConfiguration: {
      ErrorDocument: {
        // The object key name to use when a 4XX class error occurs.
        Key: "error.html",
      },
      IndexDocument: {
        // A suffix that is appended to a request when the request is
        // for a directory.
        Suffix: "index.html",
      },
    },
  });

  try {
    await client.send(command);
    console.log(
      `The bucket "${bucketName}" has been configured as a static website.`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while configuring the bucket "${bucketName}" as a static website. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while configuring the bucket "${bucketName}" as a static website. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-static-web-host.html#s3-example-static-web-host-set-website)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「*PutBucketWebsite*」を参照してください。[https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutBucketWebsiteCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutBucketWebsiteCommand)

### `PutObject`
<a name="s3_PutObject_javascript_3_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトをアップロードします。  

```
import { readFile } from "node:fs/promises";

import {
  PutObjectCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Upload a file to an S3 bucket.
 * @param {{ bucketName: string, key: string, filePath: string }}
 */
export const main = async ({ bucketName, key, filePath }) => {
  const client = new S3Client({});
  const command = new PutObjectCommand({
    Bucket: bucketName,
    Key: key,
    Body: await readFile(filePath),
  });

  try {
    const response = await client.send(command);
    console.log(response);
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "EntityTooLarge"
    ) {
      console.error(
        `Error from S3 while uploading object to ${bucketName}. \
The object was too large. To upload objects larger than 5GB, use the S3 console (160GB max) \
or the multipart upload API (5TB max).`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while uploading object to ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
ETag が指定されたものと一致することを条件にオブジェクトをアップロードします。  

```
import {
  GetObjectCommand,
  NoSuchKey,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Get a single object from a specified S3 bucket.
 * @param {{ bucketName: string, key: string, eTag: string }}
 */
export const main = async ({ bucketName, key, eTag }) => {
  const client = new S3Client({});

  try {
    const response = await client.send(
      new GetObjectCommand({
        Bucket: bucketName,
        Key: key,
        IfMatch: eTag,
      }),
    );
    // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods.
    const str = await response.Body.transformToString();
    console.log("Success. Here is text of the file:", str);
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(
        `Error from S3 while getting object "${key}" from "${bucketName}". No such key exists.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while getting object from ${bucketName}.  ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
    eTag: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-example-creating-buckets-new-bucket-2)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectCommand)」を参照してください。

### `PutObjectLegalHold`
<a name="s3_PutObjectLegalHold_javascript_3_topic"></a>

次のコード例は、`PutObjectLegalHold` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import {
  PutObjectLegalHoldCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Apply a legal hold configuration to the specified object.
 * @param {{ bucketName: string, objectKey: string, legalHoldStatus: "ON" | "OFF" }}
 */
export const main = async ({ bucketName, objectKey, legalHoldStatus }) => {
  if (!["OFF", "ON"].includes(legalHoldStatus.toUpperCase())) {
    throw new Error(
      "Invalid parameter. legalHoldStatus must be 'ON' or 'OFF'.",
    );
  }

  const client = new S3Client({});
  const command = new PutObjectLegalHoldCommand({
    Bucket: bucketName,
    Key: objectKey,
    LegalHold: {
      // Set the status to 'ON' to place a legal hold on the object.
      // Set the status to 'OFF' to remove the legal hold.
      Status: legalHoldStatus,
    },
  });

  try {
    await client.send(command);
    console.log(
      `Legal hold status set to "${legalHoldStatus}" for "${objectKey}" in "${bucketName}"`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while modifying legal hold status for "${objectKey}" in "${bucketName}". The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while modifying legal hold status for "${objectKey}" in "${bucketName}". ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    objectKey: {
      type: "string",
      required: true,
    },
    legalHoldStatus: {
      type: "string",
      default: "ON",
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutObjectLegalHold](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectLegalHoldCommand)」を参照してください。

### `PutObjectLockConfiguration`
<a name="s3_PutObjectLockConfiguration_javascript_3_topic"></a>

次のコード例は、`PutObjectLockConfiguration` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットのオブジェクトロック設定を指定します。  

```
import {
  PutObjectLockConfigurationCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Enable S3 Object Lock for an Amazon S3 bucket.
 * After you enable Object Lock on a bucket, you can't
 * disable Object Lock or suspend versioning for that bucket.
 * @param {{ bucketName: string, enabled: boolean }}
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});
  const command = new PutObjectLockConfigurationCommand({
    Bucket: bucketName,
    // The Object Lock configuration that you want to apply to the specified bucket.
    ObjectLockConfiguration: {
      ObjectLockEnabled: "Enabled",
    },
  });

  try {
    await client.send(command);
    console.log(`Object Lock for "${bucketName}" enabled.`);
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while modifying the object lock configuration for the bucket "${bucketName}". The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while modifying the object lock configuration for the bucket "${bucketName}". ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
バケットのデフォルトの保存期間を設定します。  

```
import {
  PutObjectLockConfigurationCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Change the default retention settings for an object in an Amazon S3 bucket.
 * @param {{ bucketName: string, retentionDays: string }}
 */
export const main = async ({ bucketName, retentionDays }) => {
  const client = new S3Client({});

  try {
    await client.send(
      new PutObjectLockConfigurationCommand({
        Bucket: bucketName,
        // The Object Lock configuration that you want to apply to the specified bucket.
        ObjectLockConfiguration: {
          ObjectLockEnabled: "Enabled",
          Rule: {
            // The default Object Lock retention mode and period that you want to apply
            // to new objects placed in the specified bucket. Bucket settings require
            // both a mode and a period. The period can be either Days or Years but
            // you must select one.
            DefaultRetention: {
              // In governance mode, users can't overwrite or delete an object version
              // or alter its lock settings unless they have special permissions. With
              // governance mode, you protect objects against being deleted by most users,
              // but you can still grant some users permission to alter the retention settings
              // or delete the objects if necessary.
              Mode: "GOVERNANCE",
              Days: Number.parseInt(retentionDays),
            },
          },
        },
      }),
    );
    console.log(
      `Set default retention mode to "GOVERNANCE" with a retention period of ${retentionDays} day(s).`,
    );
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while setting the default object retention for a bucket. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while setting the default object retention for a bucket. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    retentionDays: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutObjectLockConfiguration](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectLockConfigurationCommand)」を参照してください。

### `PutObjectRetention`
<a name="s3_PutObjectRetention_javascript_3_topic"></a>

次のコード例は、`PutObjectRetention` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import {
  PutObjectRetentionCommand,
  S3Client,
  S3ServiceException,
} from "@aws-sdk/client-s3";

/**
 * Place a 24-hour retention period on an object in an Amazon S3 bucket.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const client = new S3Client({});
  const command = new PutObjectRetentionCommand({
    Bucket: bucketName,
    Key: key,
    BypassGovernanceRetention: false,
    Retention: {
      // In governance mode, users can't overwrite or delete an object version
      // or alter its lock settings unless they have special permissions. With
      // governance mode, you protect objects against being deleted by most users,
      // but you can still grant some users permission to alter the retention settings
      // or delete the objects if necessary.
      Mode: "GOVERNANCE",
      RetainUntilDate: new Date(new Date().getTime() + 24 * 60 * 60 * 1000),
    },
  });

  try {
    await client.send(command);
    console.log("Object Retention settings updated.");
  } catch (caught) {
    if (
      caught instanceof S3ServiceException &&
      caught.name === "NoSuchBucket"
    ) {
      console.error(
        `Error from S3 while modifying the governance mode and retention period on an object. The bucket doesn't exist.`,
      );
    } else if (caught instanceof S3ServiceException) {
      console.error(
        `Error from S3 while modifying the governance mode and retention period on an object. ${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};

// Call function if run directly
import { parseArgs } from "node:util";
import {
  isMain,
  validateArgs,
} from "@aws-doc-sdk-examples/lib/utils/util-node.js";

const loadArgs = () => {
  const options = {
    bucketName: {
      type: "string",
      required: true,
    },
    key: {
      type: "string",
      required: true,
    },
  };
  const results = parseArgs({ options });
  const { errors } = validateArgs({ options }, results);
  return { errors, results };
};

if (isMain(import.meta.url)) {
  const { errors, results } = loadArgs();
  if (!errors) {
    main(results.values);
  } else {
    console.error(errors.join("\n"));
  }
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[PutObjectRetention](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectRetentionCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_javascript_3_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
署名付き URL を作成して、オブジェクトをバケットにアップロードします。  

```
import https from "node:https";

import { XMLParser } from "fast-xml-parser";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { fromIni } from "@aws-sdk/credential-providers";
import { HttpRequest } from "@smithy/protocol-http";
import {
  getSignedUrl,
  S3RequestPresigner,
} from "@aws-sdk/s3-request-presigner";
import { parseUrl } from "@smithy/url-parser";
import { formatUrl } from "@aws-sdk/util-format-url";
import { Hash } from "@smithy/hash-node";

const createPresignedUrlWithoutClient = async ({ region, bucket, key }) => {
  const url = parseUrl(`https://${bucket}.s3.${region}.amazonaws.com/${key}`);
  const presigner = new S3RequestPresigner({
    credentials: fromIni(),
    region,
    sha256: Hash.bind(null, "sha256"),
  });

  const signedUrlObject = await presigner.presign(
    new HttpRequest({ ...url, method: "PUT" }),
  );
  return formatUrl(signedUrlObject);
};

const createPresignedUrlWithClient = ({ region, bucket, key }) => {
  const client = new S3Client({ region });
  const command = new PutObjectCommand({ Bucket: bucket, Key: key });
  return getSignedUrl(client, command, { expiresIn: 3600 });
};

/**
 * Make a PUT request to the provided URL.
 *
 * @param {string} url
 * @param {string} data
 */
const put = (url, data) => {
  return new Promise((resolve, reject) => {
    const req = https.request(
      url,
      { method: "PUT", headers: { "Content-Length": new Blob([data]).size } },
      (res) => {
        let responseBody = "";
        res.on("data", (chunk) => {
          responseBody += chunk;
        });
        res.on("end", () => {
          const parser = new XMLParser();
          if (res.statusCode >= 200 && res.statusCode <= 299) {
            resolve(parser.parse(responseBody, true));
          } else {
            reject(parser.parse(responseBody, true));
          }
        });
      },
    );
    req.on("error", (err) => {
      reject(err);
    });
    req.write(data);
    req.end();
  });
};

/**
 * Create two presigned urls for uploading an object to an S3 bucket.
 * The first presigned URL is created with credentials from the shared INI file
 * in the current environment. The second presigned URL is created using an
 * existing S3Client instance that has already been provided with credentials.
 * @param {{ bucketName: string, key: string, region: string }}
 */
export const main = async ({ bucketName, key, region }) => {
  try {
    const noClientUrl = await createPresignedUrlWithoutClient({
      bucket: bucketName,
      key,
      region,
    });

    const clientUrl = await createPresignedUrlWithClient({
      bucket: bucketName,
      region,
      key,
    });

    // After you get the presigned URL, you can provide your own file
    // data. Refer to put() above.
    console.log("Calling PUT using presigned URL without client");
    await put(noClientUrl, "Hello World");

    console.log("Calling PUT using presigned URL with client");
    await put(clientUrl, "Hello World");

    console.log("\nDone. Check your S3 console.");
  } catch (caught) {
    if (caught instanceof Error && caught.name === "CredentialsProviderError") {
      console.error(
        `There was an error getting your credentials. Are your local credentials configured?\n${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
署名付き URL を作成して、オブジェクトをバケットからダウンロードします。  

```
import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { fromIni } from "@aws-sdk/credential-providers";
import { HttpRequest } from "@smithy/protocol-http";
import {
  getSignedUrl,
  S3RequestPresigner,
} from "@aws-sdk/s3-request-presigner";
import { parseUrl } from "@smithy/url-parser";
import { formatUrl } from "@aws-sdk/util-format-url";
import { Hash } from "@smithy/hash-node";

const createPresignedUrlWithoutClient = async ({ region, bucket, key }) => {
  const url = parseUrl(`https://${bucket}.s3.${region}.amazonaws.com/${key}`);
  const presigner = new S3RequestPresigner({
    credentials: fromIni(),
    region,
    sha256: Hash.bind(null, "sha256"),
  });

  const signedUrlObject = await presigner.presign(new HttpRequest(url));
  return formatUrl(signedUrlObject);
};

const createPresignedUrlWithClient = ({ region, bucket, key }) => {
  const client = new S3Client({ region });
  const command = new GetObjectCommand({ Bucket: bucket, Key: key });
  return getSignedUrl(client, command, { expiresIn: 3600 });
};

/**
 * Create two presigned urls for downloading an object from an S3 bucket.
 * The first presigned URL is created with credentials from the shared INI file
 * in the current environment. The second presigned URL is created using an
 * existing S3Client instance that has already been provided with credentials.
 * @param {{ bucketName: string, key: string, region: string }}
 */
export const main = async ({ bucketName, key, region }) => {
  try {
    const noClientUrl = await createPresignedUrlWithoutClient({
      bucket: bucketName,
      region,
      key,
    });

    const clientUrl = await createPresignedUrlWithClient({
      bucket: bucketName,
      region,
      key,
    });

    console.log("Presigned URL without client");
    console.log(noClientUrl);
    console.log("\n");

    console.log("Presigned URL with client");
    console.log(clientUrl);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "CredentialsProviderError") {
      console.error(
        `There was an error getting your credentials. Are your local credentials configured?\n${caught.name}: ${caught.message}`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html#s3-create-presigendurl)」を参照してください。

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_javascript_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for JavaScript (v3)**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo-asset-manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### Amazon S3 オブジェクトを一覧表示するウェブページの作成
<a name="s3_Scenario_ListObjectsWeb_javascript_3_topic"></a>

次のコード例は、ウェブページに Amazon S3 オブジェクトを一覧表示する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/web/s3/list-objects#code-examples)での設定と実行の方法を確認してください。
次のコードは、 AWS SDK を呼び出す関連する React コンポーネントです。このコンポーネントを含むアプリケーションの実行可能なバージョンは、前述の GitHub リンクにあります。  

```
import { useEffect, useState } from "react";
import {
  ListObjectsCommand,
  type ListObjectsCommandOutput,
  S3Client,
} from "@aws-sdk/client-s3";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers";
import "./App.css";

function App() {
  const [objects, setObjects] = useState<
    Required<ListObjectsCommandOutput>["Contents"]
  >([]);

  useEffect(() => {
    const client = new S3Client({
      region: "us-east-1",
      // Unless you have a public bucket, you'll need access to a private bucket.
      // One way to do this is to create an Amazon Cognito identity pool, attach a role to the pool,
      // and grant the role access to the 's3:GetObject' action.
      //
      // You'll also need to configure the CORS settings on the bucket to allow traffic from
      // this example site. Here's an example configuration that allows all origins. Don't
      // do this in production.
      //[
      //  {
      //    "AllowedHeaders": ["*"],
      //    "AllowedMethods": ["GET"],
      //    "AllowedOrigins": ["*"],
      //    "ExposeHeaders": [],
      //  },
      //]
      //
      credentials: fromCognitoIdentityPool({
        clientConfig: { region: "us-east-1" },
        identityPoolId: "<YOUR_IDENTITY_POOL_ID>",
      }),
    });
    const command = new ListObjectsCommand({ Bucket: "bucket-name" });
    client.send(command).then(({ Contents }) => setObjects(Contents || []));
  }, []);

  return (
    <div className="App">
      {objects.map((o) => (
        <div key={o.ETag}>{o.Key}</div>
      ))}
    </div>
  );
}

export default App;
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListObjects](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/ListObjectsCommand)」を参照してください。

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_javascript_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for JavaScript (v3)**  
 を使用して、Amazon Textract を使用してドキュメントイメージからデータを抽出し、インタラクティブなウェブページに表示する React アプリケーション AWS SDK for JavaScript を構築する方法を示します。この例はウェブブラウザで実行され、認証情報に認証された Amazon Cognito ID が必要です。Amazon Simple Storage Service (Amazon S3) をストレージに使用し、通知のために、Amazon Simple Notification Service (Amazon SNS) トピックにサブスクライブした Amazon Simple Queue Service (Amazon SQS) キューをポーリングします。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/textract-react) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### バケット内のすべてのオブジェクトを削除する
<a name="s3_Scenario_DeleteAllObjects_javascript_3_topic"></a>

次のコード例は、Amazon S3 バケットからすべてのオブジェクトを削除する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
Amazon S3 バケットからすべてのオブジェクトを削除します。  

```
import {
  DeleteObjectsCommand,
  paginateListObjectsV2,
  S3Client,
} from "@aws-sdk/client-s3";

/**
 *
 * @param {{ bucketName: string }} config
 */
export const main = async ({ bucketName }) => {
  const client = new S3Client({});
  try {
    console.log(`Deleting all objects in bucket: ${bucketName}`);

    const paginator = paginateListObjectsV2(
      { client },
      {
        Bucket: bucketName,
      },
    );

    const objectKeys = [];
    for await (const { Contents } of paginator) {
      objectKeys.push(...Contents.map((obj) => ({ Key: obj.Key })));
    }

    const deleteCommand = new DeleteObjectsCommand({
      Bucket: bucketName,
      Delete: { Objects: objectKeys },
    });

    await client.send(deleteCommand);

    console.log(`All objects deleted from bucket: ${bucketName}`);
  } catch (caught) {
    if (caught instanceof Error) {
      console.error(
        `Failed to empty ${bucketName}. ${caught.name}: ${caught.message}`,
      );
    }
  }
};

// Call function if run directly.
import { fileURLToPath } from "node:url";
import { parseArgs } from "node:util";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const options = {
    bucketName: {
      type: "string",
    },
  };

  const { values } = parseArgs({ options });
  main(values);
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [DeleteObjects](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/DeleteObjectsCommand)
  + [ListObjectsV2](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/ListObjectsV2Command)

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_javascript_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 で Amazon Rekognition を使用して、Amazon Rekognition を使用して Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内のオブジェクトをカテゴリ別に識別するアプリケーション AWS SDK for JavaScript を作成する方法を示します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
以下ではその方法を説明しています。  
+ Amazon Cognito を使用して認証されていないユーザーを作成します。
+ Amazon Rekognition を使用して、オブジェクトのイメージを分析します。
+ Amazon SES の E メールアドレスを検証します。
+ Amazon SES を使用して、E メール通知を送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo_analyzer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### Amazon S3 オブジェクトをロックする
<a name="s3_Scenario_ObjectLock_javascript_3_topic"></a>

次のコード例は、S3 オブジェクトロック機能を操作する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3/scenarios/object-locking#code-examples)での設定と実行の方法を確認してください。
シナリオのエントリポイント (index.js)。これにより、すべてのステップがオーケストレーションされます。GitHub にアクセスして、Scenario、ScenarioInput、ScenarioOutput、ScenarioAction の実装の詳細を確認します。  

```
import * as Scenarios from "@aws-doc-sdk-examples/lib/scenario/index.js";
import {
  exitOnFalse,
  loadState,
  saveState,
} from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";

import { welcome, welcomeContinue } from "./welcome.steps.js";
import {
  confirmCreateBuckets,
  confirmPopulateBuckets,
  confirmSetLegalHoldFileEnabled,
  confirmSetLegalHoldFileRetention,
  confirmSetRetentionPeriodFileEnabled,
  confirmSetRetentionPeriodFileRetention,
  confirmUpdateLockPolicy,
  confirmUpdateRetention,
  createBuckets,
  createBucketsAction,
  getBucketPrefix,
  populateBuckets,
  populateBucketsAction,
  setLegalHoldFileEnabledAction,
  setLegalHoldFileRetentionAction,
  setRetentionPeriodFileEnabledAction,
  setRetentionPeriodFileRetentionAction,
  updateLockPolicy,
  updateLockPolicyAction,
  updateRetention,
  updateRetentionAction,
} from "./setup.steps.js";

/**
 * @param {Scenarios} scenarios
 * @param {Record<string, any>} initialState
 */
export const getWorkflowStages = (scenarios, initialState = {}) => {
  const client = new S3Client({});

  return {
    deploy: new scenarios.Scenario(
      "S3 Object Locking - Deploy",
      [
        welcome(scenarios),
        welcomeContinue(scenarios),
        exitOnFalse(scenarios, "welcomeContinue"),
        getBucketPrefix(scenarios),
        createBuckets(scenarios),
        confirmCreateBuckets(scenarios),
        exitOnFalse(scenarios, "confirmCreateBuckets"),
        createBucketsAction(scenarios, client),
        updateRetention(scenarios),
        confirmUpdateRetention(scenarios),
        exitOnFalse(scenarios, "confirmUpdateRetention"),
        updateRetentionAction(scenarios, client),
        populateBuckets(scenarios),
        confirmPopulateBuckets(scenarios),
        exitOnFalse(scenarios, "confirmPopulateBuckets"),
        populateBucketsAction(scenarios, client),
        updateLockPolicy(scenarios),
        confirmUpdateLockPolicy(scenarios),
        exitOnFalse(scenarios, "confirmUpdateLockPolicy"),
        updateLockPolicyAction(scenarios, client),
        confirmSetLegalHoldFileEnabled(scenarios),
        setLegalHoldFileEnabledAction(scenarios, client),
        confirmSetRetentionPeriodFileEnabled(scenarios),
        setRetentionPeriodFileEnabledAction(scenarios, client),
        confirmSetLegalHoldFileRetention(scenarios),
        setLegalHoldFileRetentionAction(scenarios, client),
        confirmSetRetentionPeriodFileRetention(scenarios),
        setRetentionPeriodFileRetentionAction(scenarios, client),
        saveState,
      ],
      initialState,
    ),
    demo: new scenarios.Scenario(
      "S3 Object Locking - Demo",
      [loadState, replAction(scenarios, client)],
      initialState,
    ),
    clean: new scenarios.Scenario(
      "S3 Object Locking - Destroy",
      [
        loadState,
        confirmCleanup(scenarios),
        exitOnFalse(scenarios, "confirmCleanup"),
        cleanupAction(scenarios, client),
      ],
      initialState,
    ),
  };
};

// Call function if run directly
import { fileURLToPath } from "node:url";
import { S3Client } from "@aws-sdk/client-s3";
import { cleanupAction, confirmCleanup } from "./clean.steps.js";
import { replAction } from "./repl.steps.js";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const objectLockingScenarios = getWorkflowStages(Scenarios);
  Scenarios.parseScenarioArgs(objectLockingScenarios, {
    name: "Amazon S3 object locking workflow",
    description:
      "Work with Amazon Simple Storage Service (Amazon S3) object locking features.",
    synopsis:
      "node index.js --scenario <deploy | demo | clean> [-h|--help] [-y|--yes] [-v|--verbose]",
  });
}
```
ウェルカムメッセージをコンソールに出力します (welcome.steps.js)。  

```
/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @param {Scenarios} scenarios
 */
const welcome = (scenarios) =>
  new scenarios.ScenarioOutput(
    "welcome",
    "Welcome to the Amazon Simple Storage Service (S3) Object Locking Feature Scenario. For this workflow, we will use the AWS SDK for JavaScript to create several S3 buckets and files to demonstrate working with S3 locking features.",
    { header: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const welcomeContinue = (scenarios) =>
  new scenarios.ScenarioInput(
    "welcomeContinue",
    "Press Enter when you are ready to start.",
    { type: "confirm" },
  );

export { welcome, welcomeContinue };
```
バケット、オブジェクト、ファイル設定をデプロイします (setup.steps.js)。  

```
import {
  BucketVersioningStatus,
  ChecksumAlgorithm,
  CreateBucketCommand,
  MFADeleteStatus,
  PutBucketVersioningCommand,
  PutObjectCommand,
  PutObjectLockConfigurationCommand,
  PutObjectLegalHoldCommand,
  PutObjectRetentionCommand,
  ObjectLockLegalHoldStatus,
  ObjectLockRetentionMode,
  GetBucketVersioningCommand,
  BucketAlreadyExists,
  BucketAlreadyOwnedByYou,
  S3ServiceException,
  waitUntilBucketExists,
} from "@aws-sdk/client-s3";

import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @typedef {import("@aws-sdk/client-s3").S3Client} S3Client
 */

/**
 * @param {Scenarios} scenarios
 */
const getBucketPrefix = (scenarios) =>
  new scenarios.ScenarioInput(
    "bucketPrefix",
    "Provide a prefix that will be used for bucket creation.",
    { type: "input", default: "amzn-s3-demo-bucket" },
  );

/**
 * @param {Scenarios} scenarios
 */
const createBuckets = (scenarios) =>
  new scenarios.ScenarioOutput(
    "createBuckets",
    (state) => `The following buckets will be created:
         ${state.bucketPrefix}-no-lock with object lock False.
         ${state.bucketPrefix}-lock-enabled with object lock True.
         ${state.bucketPrefix}-retention-after-creation with object lock False.`,
    { preformatted: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const confirmCreateBuckets = (scenarios) =>
  new scenarios.ScenarioInput("confirmCreateBuckets", "Create the buckets?", {
    type: "confirm",
  });

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const createBucketsAction = (scenarios, client) =>
  new scenarios.ScenarioAction("createBucketsAction", async (state) => {
    const noLockBucketName = `${state.bucketPrefix}-no-lock`;
    const lockEnabledBucketName = `${state.bucketPrefix}-lock-enabled`;
    const retentionBucketName = `${state.bucketPrefix}-retention-after-creation`;

    try {
      await client.send(new CreateBucketCommand({ Bucket: noLockBucketName }));
      await waitUntilBucketExists({ client }, { Bucket: noLockBucketName });
      await client.send(
        new CreateBucketCommand({
          Bucket: lockEnabledBucketName,
          ObjectLockEnabledForBucket: true,
        }),
      );
      await waitUntilBucketExists(
        { client },
        { Bucket: lockEnabledBucketName },
      );
      await client.send(
        new CreateBucketCommand({ Bucket: retentionBucketName }),
      );
      await waitUntilBucketExists({ client }, { Bucket: retentionBucketName });

      state.noLockBucketName = noLockBucketName;
      state.lockEnabledBucketName = lockEnabledBucketName;
      state.retentionBucketName = retentionBucketName;
    } catch (caught) {
      if (
        caught instanceof BucketAlreadyExists ||
        caught instanceof BucketAlreadyOwnedByYou
      ) {
        console.error(`${caught.name}: ${caught.message}`);
        state.earlyExit = true;
      } else {
        throw caught;
      }
    }
  });

/**
 * @param {Scenarios} scenarios
 */
const populateBuckets = (scenarios) =>
  new scenarios.ScenarioOutput(
    "populateBuckets",
    (state) => `The following test files will be created:
         file0.txt in ${state.bucketPrefix}-no-lock.
         file1.txt in ${state.bucketPrefix}-no-lock.
         file0.txt in ${state.bucketPrefix}-lock-enabled.
         file1.txt in ${state.bucketPrefix}-lock-enabled.
         file0.txt in ${state.bucketPrefix}-retention-after-creation.
         file1.txt in ${state.bucketPrefix}-retention-after-creation.`,
    { preformatted: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const confirmPopulateBuckets = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmPopulateBuckets",
    "Populate the buckets?",
    { type: "confirm" },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const populateBucketsAction = (scenarios, client) =>
  new scenarios.ScenarioAction("populateBucketsAction", async (state) => {
    try {
      await client.send(
        new PutObjectCommand({
          Bucket: state.noLockBucketName,
          Key: "file0.txt",
          Body: "Content",
          ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
        }),
      );
      await client.send(
        new PutObjectCommand({
          Bucket: state.noLockBucketName,
          Key: "file1.txt",
          Body: "Content",
          ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
        }),
      );
      await client.send(
        new PutObjectCommand({
          Bucket: state.lockEnabledBucketName,
          Key: "file0.txt",
          Body: "Content",
          ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
        }),
      );
      await client.send(
        new PutObjectCommand({
          Bucket: state.lockEnabledBucketName,
          Key: "file1.txt",
          Body: "Content",
          ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
        }),
      );
      await client.send(
        new PutObjectCommand({
          Bucket: state.retentionBucketName,
          Key: "file0.txt",
          Body: "Content",
          ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
        }),
      );
      await client.send(
        new PutObjectCommand({
          Bucket: state.retentionBucketName,
          Key: "file1.txt",
          Body: "Content",
          ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
        }),
      );
    } catch (caught) {
      if (caught instanceof S3ServiceException) {
        console.error(
          `Error from S3 while uploading object.  ${caught.name}: ${caught.message}`,
        );
      } else {
        throw caught;
      }
    }
  });

/**
 * @param {Scenarios} scenarios
 */
const updateRetention = (scenarios) =>
  new scenarios.ScenarioOutput(
    "updateRetention",
    (state) => `A bucket can be configured to use object locking with a default retention period.
A default retention period will be configured for ${state.bucketPrefix}-retention-after-creation.`,
    { preformatted: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const confirmUpdateRetention = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmUpdateRetention",
    "Configure default retention period?",
    { type: "confirm" },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const updateRetentionAction = (scenarios, client) =>
  new scenarios.ScenarioAction("updateRetentionAction", async (state) => {
    await client.send(
      new PutBucketVersioningCommand({
        Bucket: state.retentionBucketName,
        VersioningConfiguration: {
          MFADelete: MFADeleteStatus.Disabled,
          Status: BucketVersioningStatus.Enabled,
        },
      }),
    );

    const getBucketVersioning = new GetBucketVersioningCommand({
      Bucket: state.retentionBucketName,
    });

    await retry({ intervalInMs: 500, maxRetries: 10 }, async () => {
      const { Status } = await client.send(getBucketVersioning);
      if (Status !== "Enabled") {
        throw new Error("Bucket versioning is not enabled.");
      }
    });

    await client.send(
      new PutObjectLockConfigurationCommand({
        Bucket: state.retentionBucketName,
        ObjectLockConfiguration: {
          ObjectLockEnabled: "Enabled",
          Rule: {
            DefaultRetention: {
              Mode: "GOVERNANCE",
              Years: 1,
            },
          },
        },
      }),
    );
  });

/**
 * @param {Scenarios} scenarios
 */
const updateLockPolicy = (scenarios) =>
  new scenarios.ScenarioOutput(
    "updateLockPolicy",
    (state) => `Object lock policies can also be added to existing buckets.
An object lock policy will be added to ${state.bucketPrefix}-lock-enabled.`,
    { preformatted: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const confirmUpdateLockPolicy = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmUpdateLockPolicy",
    "Add object lock policy?",
    { type: "confirm" },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const updateLockPolicyAction = (scenarios, client) =>
  new scenarios.ScenarioAction("updateLockPolicyAction", async (state) => {
    await client.send(
      new PutObjectLockConfigurationCommand({
        Bucket: state.lockEnabledBucketName,
        ObjectLockConfiguration: {
          ObjectLockEnabled: "Enabled",
        },
      }),
    );
  });

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const confirmSetLegalHoldFileEnabled = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmSetLegalHoldFileEnabled",
    (state) =>
      `Would you like to add a legal hold to file0.txt in ${state.lockEnabledBucketName}?`,
    {
      type: "confirm",
    },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const setLegalHoldFileEnabledAction = (scenarios, client) =>
  new scenarios.ScenarioAction(
    "setLegalHoldFileEnabledAction",
    async (state) => {
      await client.send(
        new PutObjectLegalHoldCommand({
          Bucket: state.lockEnabledBucketName,
          Key: "file0.txt",
          LegalHold: {
            Status: ObjectLockLegalHoldStatus.ON,
          },
        }),
      );
      console.log(
        `Modified legal hold for file0.txt in ${state.lockEnabledBucketName}.`,
      );
    },
    { skipWhen: (state) => !state.confirmSetLegalHoldFileEnabled },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const confirmSetRetentionPeriodFileEnabled = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmSetRetentionPeriodFileEnabled",
    (state) =>
      `Would you like to add a 1 day Governance retention period to file1.txt in ${state.lockEnabledBucketName}? 
Reminder: Only a user with the s3:BypassGovernanceRetention permission will be able to delete this file or its bucket until the retention period has expired.`,
    {
      type: "confirm",
    },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const setRetentionPeriodFileEnabledAction = (scenarios, client) =>
  new scenarios.ScenarioAction(
    "setRetentionPeriodFileEnabledAction",
    async (state) => {
      const retentionDate = new Date();
      retentionDate.setDate(retentionDate.getDate() + 1);
      await client.send(
        new PutObjectRetentionCommand({
          Bucket: state.lockEnabledBucketName,
          Key: "file1.txt",
          Retention: {
            Mode: ObjectLockRetentionMode.GOVERNANCE,
            RetainUntilDate: retentionDate,
          },
        }),
      );
      console.log(
        `Set retention for file1.txt in ${state.lockEnabledBucketName} until ${retentionDate.toISOString().split("T")[0]}.`,
      );
    },
    { skipWhen: (state) => !state.confirmSetRetentionPeriodFileEnabled },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const confirmSetLegalHoldFileRetention = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmSetLegalHoldFileRetention",
    (state) =>
      `Would you like to add a legal hold to file0.txt in ${state.retentionBucketName}?`,
    {
      type: "confirm",
    },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const setLegalHoldFileRetentionAction = (scenarios, client) =>
  new scenarios.ScenarioAction(
    "setLegalHoldFileRetentionAction",
    async (state) => {
      await client.send(
        new PutObjectLegalHoldCommand({
          Bucket: state.retentionBucketName,
          Key: "file0.txt",
          LegalHold: {
            Status: ObjectLockLegalHoldStatus.ON,
          },
        }),
      );
      console.log(
        `Modified legal hold for file0.txt in ${state.retentionBucketName}.`,
      );
    },
    { skipWhen: (state) => !state.confirmSetLegalHoldFileRetention },
  );

/**
 * @param {Scenarios} scenarios
 */
const confirmSetRetentionPeriodFileRetention = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmSetRetentionPeriodFileRetention",
    (state) =>
      `Would you like to add a 1 day Governance retention period to file1.txt in ${state.retentionBucketName}?
Reminder: Only a user with the s3:BypassGovernanceRetention permission will be able to delete this file or its bucket until the retention period has expired.`,
    {
      type: "confirm",
    },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const setRetentionPeriodFileRetentionAction = (scenarios, client) =>
  new scenarios.ScenarioAction(
    "setRetentionPeriodFileRetentionAction",
    async (state) => {
      const retentionDate = new Date();
      retentionDate.setDate(retentionDate.getDate() + 1);
      await client.send(
        new PutObjectRetentionCommand({
          Bucket: state.retentionBucketName,
          Key: "file1.txt",
          Retention: {
            Mode: ObjectLockRetentionMode.GOVERNANCE,
            RetainUntilDate: retentionDate,
          },
          BypassGovernanceRetention: true,
        }),
      );
      console.log(
        `Set retention for file1.txt in ${state.retentionBucketName} until ${retentionDate.toISOString().split("T")[0]}.`,
      );
    },
    { skipWhen: (state) => !state.confirmSetRetentionPeriodFileRetention },
  );

export {
  getBucketPrefix,
  createBuckets,
  confirmCreateBuckets,
  createBucketsAction,
  populateBuckets,
  confirmPopulateBuckets,
  populateBucketsAction,
  updateRetention,
  confirmUpdateRetention,
  updateRetentionAction,
  updateLockPolicy,
  confirmUpdateLockPolicy,
  updateLockPolicyAction,
  confirmSetLegalHoldFileEnabled,
  setLegalHoldFileEnabledAction,
  confirmSetRetentionPeriodFileEnabled,
  setRetentionPeriodFileEnabledAction,
  confirmSetLegalHoldFileRetention,
  setLegalHoldFileRetentionAction,
  confirmSetRetentionPeriodFileRetention,
  setRetentionPeriodFileRetentionAction,
};
```
バケット内のファイルを表示および削除します (repl.steps.js)。  

```
import {
  ChecksumAlgorithm,
  DeleteObjectCommand,
  GetObjectLegalHoldCommand,
  GetObjectLockConfigurationCommand,
  GetObjectRetentionCommand,
  ListObjectVersionsCommand,
  PutObjectCommand,
} from "@aws-sdk/client-s3";

/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @typedef {import("@aws-sdk/client-s3").S3Client} S3Client
 */

const choices = {
  EXIT: 0,
  LIST_ALL_FILES: 1,
  DELETE_FILE: 2,
  DELETE_FILE_WITH_RETENTION: 3,
  OVERWRITE_FILE: 4,
  VIEW_RETENTION_SETTINGS: 5,
  VIEW_LEGAL_HOLD_SETTINGS: 6,
};

/**
 * @param {Scenarios} scenarios
 */
const replInput = (scenarios) =>
  new scenarios.ScenarioInput(
    "replChoice",
    "Explore the S3 locking features by selecting one of the following choices",
    {
      type: "select",
      choices: [
        { name: "List all files in buckets", value: choices.LIST_ALL_FILES },
        { name: "Attempt to delete a file.", value: choices.DELETE_FILE },
        {
          name: "Attempt to delete a file with retention period bypass.",
          value: choices.DELETE_FILE_WITH_RETENTION,
        },
        { name: "Attempt to overwrite a file.", value: choices.OVERWRITE_FILE },
        {
          name: "View the object and bucket retention settings for a file.",
          value: choices.VIEW_RETENTION_SETTINGS,
        },
        {
          name: "View the legal hold settings for a file.",
          value: choices.VIEW_LEGAL_HOLD_SETTINGS,
        },
        { name: "Finish the workflow.", value: choices.EXIT },
      ],
    },
  );

/**
 * @param {S3Client} client
 * @param {string[]} buckets
 */
const getAllFiles = async (client, buckets) => {
  /** @type {{bucket: string, key: string, version: string}[]} */
  const files = [];
  for (const bucket of buckets) {
    const objectsResponse = await client.send(
      new ListObjectVersionsCommand({ Bucket: bucket }),
    );
    for (const version of objectsResponse.Versions || []) {
      const { Key, VersionId } = version;
      files.push({ bucket, key: Key, version: VersionId });
    }
  }

  return files;
};

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const replAction = (scenarios, client) =>
  new scenarios.ScenarioAction(
    "replAction",
    async (state) => {
      const files = await getAllFiles(client, [
        state.noLockBucketName,
        state.lockEnabledBucketName,
        state.retentionBucketName,
      ]);

      const fileInput = new scenarios.ScenarioInput(
        "selectedFile",
        "Select a file:",
        {
          type: "select",
          choices: files.map((file, index) => ({
            name: `${index + 1}: ${file.bucket}: ${file.key} (version: ${
              file.version
            })`,
            value: index,
          })),
        },
      );

      const { replChoice } = state;

      switch (replChoice) {
        case choices.LIST_ALL_FILES: {
          const files = await getAllFiles(client, [
            state.noLockBucketName,
            state.lockEnabledBucketName,
            state.retentionBucketName,
          ]);
          state.replOutput = files
            .map(
              (file) =>
                `${file.bucket}: ${file.key} (version: ${file.version})`,
            )
            .join("\n");
          break;
        }
        case choices.DELETE_FILE: {
          /** @type {number} */
          const fileToDelete = await fileInput.handle(state);
          const selectedFile = files[fileToDelete];
          try {
            await client.send(
              new DeleteObjectCommand({
                Bucket: selectedFile.bucket,
                Key: selectedFile.key,
                VersionId: selectedFile.version,
              }),
            );
            state.replOutput = `Deleted ${selectedFile.key} in ${selectedFile.bucket}.`;
          } catch (err) {
            state.replOutput = `Unable to delete object ${selectedFile.key} in bucket ${selectedFile.bucket}: ${err.message}`;
          }
          break;
        }
        case choices.DELETE_FILE_WITH_RETENTION: {
          /** @type {number} */
          const fileToDelete = await fileInput.handle(state);
          const selectedFile = files[fileToDelete];
          try {
            await client.send(
              new DeleteObjectCommand({
                Bucket: selectedFile.bucket,
                Key: selectedFile.key,
                VersionId: selectedFile.version,
                BypassGovernanceRetention: true,
              }),
            );
            state.replOutput = `Deleted ${selectedFile.key} in ${selectedFile.bucket}.`;
          } catch (err) {
            state.replOutput = `Unable to delete object ${selectedFile.key} in bucket ${selectedFile.bucket}: ${err.message}`;
          }
          break;
        }
        case choices.OVERWRITE_FILE: {
          /** @type {number} */
          const fileToOverwrite = await fileInput.handle(state);
          const selectedFile = files[fileToOverwrite];
          try {
            await client.send(
              new PutObjectCommand({
                Bucket: selectedFile.bucket,
                Key: selectedFile.key,
                Body: "New content",
                ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
              }),
            );
            state.replOutput = `Overwrote ${selectedFile.key} in ${selectedFile.bucket}.`;
          } catch (err) {
            state.replOutput = `Unable to overwrite object ${selectedFile.key} in bucket ${selectedFile.bucket}: ${err.message}`;
          }
          break;
        }
        case choices.VIEW_RETENTION_SETTINGS: {
          /** @type {number} */
          const fileToView = await fileInput.handle(state);
          const selectedFile = files[fileToView];
          try {
            const retention = await client.send(
              new GetObjectRetentionCommand({
                Bucket: selectedFile.bucket,
                Key: selectedFile.key,
                VersionId: selectedFile.version,
              }),
            );
            const bucketConfig = await client.send(
              new GetObjectLockConfigurationCommand({
                Bucket: selectedFile.bucket,
              }),
            );
            state.replOutput = `Object retention for ${selectedFile.key} in ${selectedFile.bucket}: ${retention.Retention?.Mode} until ${retention.Retention?.RetainUntilDate?.toISOString()}.
Bucket object lock config for ${selectedFile.bucket} in ${selectedFile.bucket}:
Enabled: ${bucketConfig.ObjectLockConfiguration?.ObjectLockEnabled}
Rule: ${JSON.stringify(bucketConfig.ObjectLockConfiguration?.Rule?.DefaultRetention)}`;
          } catch (err) {
            state.replOutput = `Unable to fetch object lock retention: '${err.message}'`;
          }
          break;
        }
        case choices.VIEW_LEGAL_HOLD_SETTINGS: {
          /** @type {number} */
          const fileToView = await fileInput.handle(state);
          const selectedFile = files[fileToView];
          try {
            const legalHold = await client.send(
              new GetObjectLegalHoldCommand({
                Bucket: selectedFile.bucket,
                Key: selectedFile.key,
                VersionId: selectedFile.version,
              }),
            );
            state.replOutput = `Object legal hold for ${selectedFile.key} in ${selectedFile.bucket}: Status: ${legalHold.LegalHold?.Status}`;
          } catch (err) {
            state.replOutput = `Unable to fetch legal hold: '${err.message}'`;
          }
          break;
        }
        default:
          throw new Error(`Invalid replChoice: ${replChoice}`);
      }
    },
    {
      whileConfig: {
        whileFn: ({ replChoice }) => replChoice !== choices.EXIT,
        input: replInput(scenarios),
        output: new scenarios.ScenarioOutput(
          "REPL output",
          (state) => state.replOutput,
          { preformatted: true },
        ),
      },
    },
  );

export { replInput, replAction, choices };
```
作成されたすべてのリソースを破棄します (clean.steps.js)。  

```
import {
  DeleteObjectCommand,
  DeleteBucketCommand,
  ListObjectVersionsCommand,
  GetObjectLegalHoldCommand,
  GetObjectRetentionCommand,
  PutObjectLegalHoldCommand,
} from "@aws-sdk/client-s3";

/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @typedef {import("@aws-sdk/client-s3").S3Client} S3Client
 */

/**
 * @param {Scenarios} scenarios
 */
const confirmCleanup = (scenarios) =>
  new scenarios.ScenarioInput("confirmCleanup", "Clean up resources?", {
    type: "confirm",
  });

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const cleanupAction = (scenarios, client) =>
  new scenarios.ScenarioAction("cleanupAction", async (state) => {
    const { noLockBucketName, lockEnabledBucketName, retentionBucketName } =
      state;

    const buckets = [
      noLockBucketName,
      lockEnabledBucketName,
      retentionBucketName,
    ];

    for (const bucket of buckets) {
      /** @type {import("@aws-sdk/client-s3").ListObjectVersionsCommandOutput} */
      let objectsResponse;

      try {
        objectsResponse = await client.send(
          new ListObjectVersionsCommand({
            Bucket: bucket,
          }),
        );
      } catch (e) {
        if (e instanceof Error && e.name === "NoSuchBucket") {
          console.log("Object's bucket has already been deleted.");
          continue;
        }
        throw e;
      }

      for (const version of objectsResponse.Versions || []) {
        const { Key, VersionId } = version;

        try {
          const legalHold = await client.send(
            new GetObjectLegalHoldCommand({
              Bucket: bucket,
              Key,
              VersionId,
            }),
          );

          if (legalHold.LegalHold?.Status === "ON") {
            await client.send(
              new PutObjectLegalHoldCommand({
                Bucket: bucket,
                Key,
                VersionId,
                LegalHold: {
                  Status: "OFF",
                },
              }),
            );
          }
        } catch (err) {
          console.log(
            `Unable to fetch legal hold for ${Key} in ${bucket}: '${err.message}'`,
          );
        }

        try {
          const retention = await client.send(
            new GetObjectRetentionCommand({
              Bucket: bucket,
              Key,
              VersionId,
            }),
          );

          if (retention.Retention?.Mode === "GOVERNANCE") {
            await client.send(
              new DeleteObjectCommand({
                Bucket: bucket,
                Key,
                VersionId,
                BypassGovernanceRetention: true,
              }),
            );
          }
        } catch (err) {
          console.log(
            `Unable to fetch object lock retention for ${Key} in ${bucket}: '${err.message}'`,
          );
        }

        await client.send(
          new DeleteObjectCommand({
            Bucket: bucket,
            Key,
            VersionId,
          }),
        );
      }

      await client.send(new DeleteBucketCommand({ Bucket: bucket }));
      console.log(`Delete for ${bucket} complete.`);
    }
  });

export { confirmCleanup, cleanupAction };
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [GetObjectLegalHold](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectLegalHoldCommand)
  + [GetObjectLockConfiguration](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectLockConfigurationCommand)
  + [GetObjectRetention](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectRetentionCommand)
  + [PutObjectLegalHold](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectLegalHoldCommand)
  + [PutObjectLockConfiguration](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectLockConfigurationCommand)
  + [PutObjectRetention](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectRetentionCommand)

### 条件付きリクエストの実行
<a name="s3_Scenario_ConditionalRequests_javascript_3_topic"></a>

次のコード例は、Amazon S3 リクエストに前提条件を追加する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3/scenarios/conditional-requests#code-examples)での設定と実行の方法を確認してください。
ワークフローのエントリポイント (index.js)。これにより、すべてのステップがオーケストレーションされます。GitHub にアクセスして、Scenario、ScenarioInput、ScenarioOutput、ScenarioAction の実装の詳細を確認します。  

```
import * as Scenarios from "@aws-doc-sdk-examples/lib/scenario/index.js";
import {
  exitOnFalse,
  loadState,
  saveState,
} from "@aws-doc-sdk-examples/lib/scenario/steps-common.js";

import { welcome, welcomeContinue } from "./welcome.steps.js";
import {
  confirmCreateBuckets,
  confirmPopulateBuckets,
  createBuckets,
  createBucketsAction,
  getBucketPrefix,
  populateBuckets,
  populateBucketsAction,
} from "./setup.steps.js";

/**
 * @param {Scenarios} scenarios
 * @param {Record<string, any>} initialState
 */
export const getWorkflowStages = (scenarios, initialState = {}) => {
  const client = new S3Client({});

  return {
    deploy: new scenarios.Scenario(
      "S3 Conditional Requests - Deploy",
      [
        welcome(scenarios),
        welcomeContinue(scenarios),
        exitOnFalse(scenarios, "welcomeContinue"),
        getBucketPrefix(scenarios),
        createBuckets(scenarios),
        confirmCreateBuckets(scenarios),
        exitOnFalse(scenarios, "confirmCreateBuckets"),
        createBucketsAction(scenarios, client),
        populateBuckets(scenarios),
        confirmPopulateBuckets(scenarios),
        exitOnFalse(scenarios, "confirmPopulateBuckets"),
        populateBucketsAction(scenarios, client),
        saveState,
      ],
      initialState,
    ),
    demo: new scenarios.Scenario(
      "S3 Conditional Requests - Demo",
      [loadState, welcome(scenarios), replAction(scenarios, client)],
      initialState,
    ),
    clean: new scenarios.Scenario(
      "S3 Conditional Requests - Destroy",
      [
        loadState,
        confirmCleanup(scenarios),
        exitOnFalse(scenarios, "confirmCleanup"),
        cleanupAction(scenarios, client),
      ],
      initialState,
    ),
  };
};

// Call function if run directly
import { fileURLToPath } from "node:url";
import { S3Client } from "@aws-sdk/client-s3";
import { cleanupAction, confirmCleanup } from "./clean.steps.js";
import { replAction } from "./repl.steps.js";

if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const objectLockingScenarios = getWorkflowStages(Scenarios);
  Scenarios.parseScenarioArgs(objectLockingScenarios, {
    name: "Amazon S3 object locking workflow",
    description:
      "Work with Amazon Simple Storage Service (Amazon S3) object locking features.",
    synopsis:
      "node index.js --scenario <deploy | demo | clean> [-h|--help] [-y|--yes] [-v|--verbose]",
  });
}
```
ウェルカムメッセージをコンソールに出力します (welcome.steps.js)。  

```
/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @param {Scenarios} scenarios
 */
const welcome = (scenarios) =>
  new scenarios.ScenarioOutput(
    "welcome",
    "This example demonstrates the use of conditional requests for S3 operations." +
      " You can use conditional requests to add preconditions to S3 read requests to return " +
      "or copy an object based on its Entity tag (ETag), or last modified date.You can use " +
      "a conditional write requests to prevent overwrites by ensuring there is no existing " +
      "object with the same key.\n" +
      "This example will enable you to perform conditional reads and writes that will succeed " +
      "or fail based on your selected options.\n" +
      "Sample buckets and a sample object will be created as part of the example.\n" +
      "Some steps require a key name prefix to be defined by the user. Before you begin, you can " +
      "optionally edit this prefix in ./object_name.json. If you do so, please reload the scenario before you begin.",
    { header: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const welcomeContinue = (scenarios) =>
  new scenarios.ScenarioInput(
    "welcomeContinue",
    "Press Enter when you are ready to start.",
    { type: "confirm" },
  );

export { welcome, welcomeContinue };
```
バケットとオブジェクトをデプロイします (setup.steps.js)。  

```
import {
  ChecksumAlgorithm,
  CreateBucketCommand,
  PutObjectCommand,
  BucketAlreadyExists,
  BucketAlreadyOwnedByYou,
  S3ServiceException,
  waitUntilBucketExists,
} from "@aws-sdk/client-s3";

/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @typedef {import("@aws-sdk/client-s3").S3Client} S3Client
 */

/**
 * @param {Scenarios} scenarios
 */
const getBucketPrefix = (scenarios) =>
  new scenarios.ScenarioInput(
    "bucketPrefix",
    "Provide a prefix that will be used for bucket creation.",
    { type: "input", default: "amzn-s3-demo-bucket" },
  );
/**
 * @param {Scenarios} scenarios
 */
const createBuckets = (scenarios) =>
  new scenarios.ScenarioOutput(
    "createBuckets",
    (state) => `The following buckets will be created:
         ${state.bucketPrefix}-source-bucket.
         ${state.bucketPrefix}-destination-bucket.`,
    { preformatted: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const confirmCreateBuckets = (scenarios) =>
  new scenarios.ScenarioInput("confirmCreateBuckets", "Create the buckets?", {
    type: "confirm",
  });

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const createBucketsAction = (scenarios, client) =>
  new scenarios.ScenarioAction("createBucketsAction", async (state) => {
    const sourceBucketName = `${state.bucketPrefix}-source-bucket`;
    const destinationBucketName = `${state.bucketPrefix}-destination-bucket`;

    try {
      await client.send(
        new CreateBucketCommand({
          Bucket: sourceBucketName,
        }),
      );
      await waitUntilBucketExists({ client }, { Bucket: sourceBucketName });
      await client.send(
        new CreateBucketCommand({
          Bucket: destinationBucketName,
        }),
      );
      await waitUntilBucketExists(
        { client },
        { Bucket: destinationBucketName },
      );

      state.sourceBucketName = sourceBucketName;
      state.destinationBucketName = destinationBucketName;
    } catch (caught) {
      if (
        caught instanceof BucketAlreadyExists ||
        caught instanceof BucketAlreadyOwnedByYou
      ) {
        console.error(`${caught.name}: ${caught.message}`);
        state.earlyExit = true;
      } else {
        throw caught;
      }
    }
  });

/**
 * @param {Scenarios} scenarios
 */
const populateBuckets = (scenarios) =>
  new scenarios.ScenarioOutput(
    "populateBuckets",
    (state) => `The following test files will be created:
         file01.txt in ${state.bucketPrefix}-source-bucket.`,
    { preformatted: true },
  );

/**
 * @param {Scenarios} scenarios
 */
const confirmPopulateBuckets = (scenarios) =>
  new scenarios.ScenarioInput(
    "confirmPopulateBuckets",
    "Populate the buckets?",
    { type: "confirm" },
  );

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const populateBucketsAction = (scenarios, client) =>
  new scenarios.ScenarioAction("populateBucketsAction", async (state) => {
    try {
      await client.send(
        new PutObjectCommand({
          Bucket: state.sourceBucketName,
          Key: "file01.txt",
          Body: "Content",
          ChecksumAlgorithm: ChecksumAlgorithm.SHA256,
        }),
      );
    } catch (caught) {
      if (caught instanceof S3ServiceException) {
        console.error(
          `Error from S3 while uploading object.  ${caught.name}: ${caught.message}`,
        );
      } else {
        throw caught;
      }
    }
  });

export {
  confirmCreateBuckets,
  confirmPopulateBuckets,
  createBuckets,
  createBucketsAction,
  getBucketPrefix,
  populateBuckets,
  populateBucketsAction,
};
```
S3 条件付きリクエストを使用してオブジェクトを取得、コピー、配置します (repl.steps.js)。  

```
import path from "node:path";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";

import {
  ListObjectVersionsCommand,
  GetObjectCommand,
  CopyObjectCommand,
  PutObjectCommand,
} from "@aws-sdk/client-s3";
import data from "./object_name.json" assert { type: "json" };
import { readFile } from "node:fs/promises";
import {
  ScenarioInput,
  Scenario,
  ScenarioAction,
  ScenarioOutput,
} from "../../../libs/scenario/index.js";

/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @typedef {import("@aws-sdk/client-s3").S3Client} S3Client
 */

const choices = {
  EXIT: 0,
  LIST_ALL_FILES: 1,
  CONDITIONAL_READ: 2,
  CONDITIONAL_COPY: 3,
  CONDITIONAL_WRITE: 4,
};

/**
 * @param {Scenarios} scenarios
 */
const replInput = (scenarios) =>
  new ScenarioInput(
    "replChoice",
    "Explore the S3 conditional request features by selecting one of the following choices",
    {
      type: "select",
      choices: [
        { name: "Print list of bucket items.", value: choices.LIST_ALL_FILES },
        {
          name: "Perform a conditional read.",
          value: choices.CONDITIONAL_READ,
        },
        {
          name: "Perform a conditional copy. These examples use the key name prefix defined in ./object_name.json.",
          value: choices.CONDITIONAL_COPY,
        },
        {
          name: "Perform a conditional write. This example use the sample file ./text02.txt.",
          value: choices.CONDITIONAL_WRITE,
        },
        { name: "Finish the workflow.", value: choices.EXIT },
      ],
    },
  );

/**
 * @param {S3Client} client
 * @param {string[]} buckets
 */
const getAllFiles = async (client, buckets) => {
  /** @type {{bucket: string, key: string, version: string}[]} */
  const files = [];
  for (const bucket of buckets) {
    const objectsResponse = await client.send(
      new ListObjectVersionsCommand({ Bucket: bucket }),
    );
    for (const version of objectsResponse.Versions || []) {
      const { Key } = version;
      files.push({ bucket, key: Key });
    }
  }
  return files;
};

/**
 * @param {S3Client} client
 * @param {string[]} buckets
 * @param {string} key
 */
const getEtag = async (client, bucket, key) => {
  const objectsResponse = await client.send(
    new GetObjectCommand({
      Bucket: bucket,
      Key: key,
    }),
  );
  return objectsResponse.ETag;
};

/**
 * @param {S3Client} client
 * @param {string[]} buckets
 */

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
export const replAction = (scenarios, client) =>
  new ScenarioAction(
    "replAction",
    async (state) => {
      const files = await getAllFiles(client, [
        state.sourceBucketName,
        state.destinationBucketName,
      ]);

      const fileInput = new scenarios.ScenarioInput(
        "selectedFile",
        "Select a file to use:",
        {
          type: "select",
          choices: files.map((file, index) => ({
            name: `${index + 1}: ${file.bucket}: ${file.key} (Etag: ${
              file.version
            })`,
            value: index,
          })),
        },
      );
      const condReadOptions = new scenarios.ScenarioInput(
        "selectOption",
        "Which conditional read action would you like to take?",
        {
          type: "select",
          choices: [
            "If-Match: using the object's ETag. This condition should succeed.",
            "If-None-Match: using the object's ETag. This condition should fail.",
            "If-Modified-Since: using yesterday's date. This condition should succeed.",
            "If-Unmodified-Since: using yesterday's date. This condition should fail.",
          ],
        },
      );
      const condCopyOptions = new scenarios.ScenarioInput(
        "selectOption",
        "Which conditional copy action would you like to take?",
        {
          type: "select",
          choices: [
            "If-Match: using the object's ETag. This condition should succeed.",
            "If-None-Match: using the object's ETag. This condition should fail.",
            "If-Modified-Since: using yesterday's date. This condition should succeed.",
            "If-Unmodified-Since: using yesterday's date. This condition should fail.",
          ],
        },
      );
      const condWriteOptions = new scenarios.ScenarioInput(
        "selectOption",
        "Which conditional write action would you like to take?",
        {
          type: "select",
          choices: [
            "IfNoneMatch condition on the object key: If the key is a duplicate, the write will fail.",
          ],
        },
      );

      const { replChoice } = state;

      switch (replChoice) {
        case choices.LIST_ALL_FILES: {
          const files = await getAllFiles(client, [
            state.sourceBucketName,
            state.destinationBucketName,
          ]);
          state.replOutput = files
            .map(
              (file) => `Items in bucket ${file.bucket}: object: ${file.key} `,
            )
            .join("\n");
          break;
        }
        case choices.CONDITIONAL_READ:
          {
            const selectedCondRead = await condReadOptions.handle(state);
            if (
              selectedCondRead ===
              "If-Match: using the object's ETag. This condition should succeed."
            ) {
              const bucket = state.sourceBucketName;
              const key = "file01.txt";
              const ETag = await getEtag(client, bucket, key);

              try {
                await client.send(
                  new GetObjectCommand({
                    Bucket: bucket,
                    Key: key,
                    IfMatch: ETag,
                  }),
                );
                state.replOutput = `${key} in bucket ${state.sourceBucketName} read because ETag provided matches the object's ETag.`;
              } catch (err) {
                state.replOutput = `Unable to read object ${key} in bucket ${state.sourceBucketName}: ${err.message}`;
              }
              break;
            }
            if (
              selectedCondRead ===
              "If-None-Match: using the object's ETag. This condition should fail."
            ) {
              const bucket = state.sourceBucketName;
              const key = "file01.txt";
              const ETag = await getEtag(client, bucket, key);

              try {
                await client.send(
                  new GetObjectCommand({
                    Bucket: bucket,
                    Key: key,
                    IfNoneMatch: ETag,
                  }),
                );
                state.replOutput = `${key} in ${state.sourceBucketName} was returned.`;
              } catch (err) {
                state.replOutput = `${key} in ${state.sourceBucketName} was not read: ${err.message}`;
              }
              break;
            }
            if (
              selectedCondRead ===
              "If-Modified-Since: using yesterday's date. This condition should succeed."
            ) {
              const date = new Date();
              date.setDate(date.getDate() - 1);

              const bucket = state.sourceBucketName;
              const key = "file01.txt";
              try {
                await client.send(
                  new GetObjectCommand({
                    Bucket: bucket,
                    Key: key,
                    IfModifiedSince: date,
                  }),
                );
                state.replOutput = `${key} in bucket ${state.sourceBucketName} read because it has been created or modified in the last 24 hours.`;
              } catch (err) {
                state.replOutput = `Unable to read object ${key} in bucket ${state.sourceBucketName}: ${err.message}`;
              }
              break;
            }
            if (
              selectedCondRead ===
              "If-Unmodified-Since: using yesterday's date. This condition should fail."
            ) {
              const bucket = state.sourceBucketName;
              const key = "file01.txt";

              const date = new Date();
              date.setDate(date.getDate() - 1);
              try {
                await client.send(
                  new GetObjectCommand({
                    Bucket: bucket,
                    Key: key,
                    IfUnmodifiedSince: date,
                  }),
                );
                state.replOutput = `${key} in ${state.sourceBucketName} was read.`;
              } catch (err) {
                state.replOutput = `${key} in ${state.sourceBucketName} was not read: ${err.message}`;
              }
              break;
            }
          }
          break;
        case choices.CONDITIONAL_COPY: {
          const selectedCondCopy = await condCopyOptions.handle(state);
          if (
            selectedCondCopy ===
            "If-Match: using the object's ETag. This condition should succeed."
          ) {
            const bucket = state.sourceBucketName;
            const key = "file01.txt";
            const ETag = await getEtag(client, bucket, key);

            const copySource = `${bucket}/${key}`;
            // Optionally edit the default key name prefix of the copied object in ./object_name.json.
            const name = data.name;
            const copiedKey = `${name}${key}`;
            try {
              await client.send(
                new CopyObjectCommand({
                  CopySource: copySource,
                  Bucket: state.destinationBucketName,
                  Key: copiedKey,
                  CopySourceIfMatch: ETag,
                }),
              );
              state.replOutput = `${key} copied as ${copiedKey} to bucket ${state.destinationBucketName} because ETag provided matches the object's ETag.`;
            } catch (err) {
              state.replOutput = `Unable to copy object ${key} as ${copiedKey} to bucket ${state.destinationBucketName}: ${err.message}`;
            }
            break;
          }
          if (
            selectedCondCopy ===
            "If-None-Match: using the object's ETag. This condition should fail."
          ) {
            const bucket = state.sourceBucketName;
            const key = "file01.txt";
            const ETag = await getEtag(client, bucket, key);
            const copySource = `${bucket}/${key}`;
            // Optionally edit the default key name prefix of the copied object in ./object_name.json.
            const name = data.name;
            const copiedKey = `${name}${key}`;

            try {
              await client.send(
                new CopyObjectCommand({
                  CopySource: copySource,
                  Bucket: state.destinationBucketName,
                  Key: copiedKey,
                  CopySourceIfNoneMatch: ETag,
                }),
              );
              state.replOutput = `${copiedKey} copied to bucket ${state.destinationBucketName}`;
            } catch (err) {
              state.replOutput = `Unable to copy object as ${key} as as ${copiedKey} to bucket ${state.destinationBucketName}: ${err.message}`;
            }
            break;
          }
          if (
            selectedCondCopy ===
            "If-Modified-Since: using yesterday's date. This condition should succeed."
          ) {
            const bucket = state.sourceBucketName;
            const key = "file01.txt";
            const copySource = `${bucket}/${key}`;
            // Optionally edit the default key name prefix of the copied object in ./object_name.json.
            const name = data.name;
            const copiedKey = `${name}${key}`;

            const date = new Date();
            date.setDate(date.getDate() - 1);

            try {
              await client.send(
                new CopyObjectCommand({
                  CopySource: copySource,
                  Bucket: state.destinationBucketName,
                  Key: copiedKey,
                  CopySourceIfModifiedSince: date,
                }),
              );
              state.replOutput = `${key} copied as ${copiedKey} to bucket ${state.destinationBucketName} because it has been created or modified in the last 24 hours.`;
            } catch (err) {
              state.replOutput = `Unable to copy object ${key} as ${copiedKey} to bucket ${state.destinationBucketName} : ${err.message}`;
            }
            break;
          }
          if (
            selectedCondCopy ===
            "If-Unmodified-Since: using yesterday's date. This condition should fail."
          ) {
            const bucket = state.sourceBucketName;
            const key = "file01.txt";
            const copySource = `${bucket}/${key}`;
            // Optionally edit the default key name prefix of the copied object in ./object_name.json.
            const name = data.name;
            const copiedKey = `${name}${key}`;

            const date = new Date();
            date.setDate(date.getDate() - 1);

            try {
              await client.send(
                new CopyObjectCommand({
                  CopySource: copySource,
                  Bucket: state.destinationBucketName,
                  Key: copiedKey,
                  CopySourceIfUnmodifiedSince: date,
                }),
              );
              state.replOutput = `${copiedKey} copied to bucket ${state.destinationBucketName} because it has not been created or modified in the last 24 hours.`;
            } catch (err) {
              state.replOutput = `Unable to copy object ${key} to bucket ${state.destinationBucketName}: ${err.message}`;
            }
          }
          break;
        }
        case choices.CONDITIONAL_WRITE:
          {
            const selectedCondWrite = await condWriteOptions.handle(state);
            if (
              selectedCondWrite ===
              "IfNoneMatch condition on the object key: If the key is a duplicate, the write will fail."
            ) {
              // Optionally edit the default key name prefix of the copied object in ./object_name.json.
              const key = "text02.txt";
              const __filename = fileURLToPath(import.meta.url);
              const __dirname = dirname(__filename);
              const filePath = path.join(__dirname, "text02.txt");
              try {
                await client.send(
                  new PutObjectCommand({
                    Bucket: `${state.destinationBucketName}`,
                    Key: `${key}`,
                    Body: await readFile(filePath),
                    IfNoneMatch: "*",
                  }),
                );
                state.replOutput = `${key} uploaded to bucket ${state.destinationBucketName} because the key is not a duplicate.`;
              } catch (err) {
                state.replOutput = `Unable to upload object to bucket ${state.destinationBucketName}:${err.message}`;
              }
              break;
            }
          }
          break;

        default:
          throw new Error(`Invalid replChoice: ${replChoice}`);
      }
    },
    {
      whileConfig: {
        whileFn: ({ replChoice }) => replChoice !== choices.EXIT,
        input: replInput(scenarios),
        output: new ScenarioOutput("REPL output", (state) => state.replOutput, {
          preformatted: true,
        }),
      },
    },
  );

export { replInput, choices };
```
作成されたすべてのリソースを破棄します (clean.steps.js)。  

```
import {
  DeleteObjectCommand,
  DeleteBucketCommand,
  ListObjectVersionsCommand,
} from "@aws-sdk/client-s3";

/**
 * @typedef {import("@aws-doc-sdk-examples/lib/scenario/index.js")} Scenarios
 */

/**
 * @typedef {import("@aws-sdk/client-s3").S3Client} S3Client
 */

/**
 * @param {Scenarios} scenarios
 */
const confirmCleanup = (scenarios) =>
  new scenarios.ScenarioInput("confirmCleanup", "Clean up resources?", {
    type: "confirm",
  });

/**
 * @param {Scenarios} scenarios
 * @param {S3Client} client
 */
const cleanupAction = (scenarios, client) =>
  new scenarios.ScenarioAction("cleanupAction", async (state) => {
    const { sourceBucketName, destinationBucketName } = state;
    const buckets = [sourceBucketName, destinationBucketName].filter((b) => b);

    for (const bucket of buckets) {
      try {
        let objectsResponse;
        objectsResponse = await client.send(
          new ListObjectVersionsCommand({
            Bucket: bucket,
          }),
        );
        for (const version of objectsResponse.Versions || []) {
          const { Key, VersionId } = version;
          try {
            await client.send(
              new DeleteObjectCommand({
                Bucket: bucket,
                Key,
                VersionId,
              }),
            );
          } catch (err) {
            console.log(`An error occurred: ${err.message} `);
          }
        }
      } catch (e) {
        if (e instanceof Error && e.name === "NoSuchBucket") {
          console.log("Objects and buckets have already been deleted.");
          continue;
        }
        throw e;
      }

      await client.send(new DeleteBucketCommand({ Bucket: bucket }));
      console.log(`Delete for ${bucket} complete.`);
    }
  });

export { confirmCleanup, cleanupAction };
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/CopyObjectCommand)
  + [GetObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/GetObjectCommand)
  + [PutObject](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/s3/command/PutObjectCommand)

### 大きなファイルをアップロードまたはダウンロードする
<a name="s3_Scenario_UsingLargeFiles_javascript_3_topic"></a>

次のコード例は、Amazon S3 との間で大きなファイルをアップロードまたはダウンロードする方法を示しています。

詳細については、「[マルチパートアップロードを使用したオブジェクトのアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-upload-object.html)」を参照してください。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/s3#code-examples)での設定と実行の方法を確認してください。
サイズの大きいファイルをアップロードします。  

```
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

import {
  ProgressBar,
  logger,
} from "@aws-doc-sdk-examples/lib/utils/util-log.js";

const twentyFiveMB = 25 * 1024 * 1024;

export const createString = (size = twentyFiveMB) => {
  return "x".repeat(size);
};

/**
 * Create a 25MB file and upload it in parts to the specified
 * Amazon S3 bucket.
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  const str = createString();
  const buffer = Buffer.from(str, "utf8");
  const progressBar = new ProgressBar({
    description: `Uploading "${key}" to "${bucketName}"`,
    barLength: 30,
  });

  try {
    const upload = new Upload({
      client: new S3Client({}),
      params: {
        Bucket: bucketName,
        Key: key,
        Body: buffer,
      },
    });

    upload.on("httpUploadProgress", ({ loaded, total }) => {
      progressBar.update({ current: loaded, total });
    });

    await upload.done();
  } catch (caught) {
    if (caught instanceof Error && caught.name === "AbortError") {
      logger.error(`Multipart upload was aborted. ${caught.message}`);
    } else {
      throw caught;
    }
  }
};
```
サイズの大きいファイルをダウンロードします。  

```
import { fileURLToPath } from "node:url";
import { GetObjectCommand, NoSuchKey, S3Client } from "@aws-sdk/client-s3";
import { createWriteStream, rmSync } from "node:fs";

const s3Client = new S3Client({});
const oneMB = 1024 * 1024;

export const getObjectRange = ({ bucket, key, start, end }) => {
  const command = new GetObjectCommand({
    Bucket: bucket,
    Key: key,
    Range: `bytes=${start}-${end}`,
  });

  return s3Client.send(command);
};

/**
 * @param {string | undefined} contentRange
 */
export const getRangeAndLength = (contentRange) => {
  const [range, length] = contentRange.split("/");
  const [start, end] = range.split("-");
  return {
    start: Number.parseInt(start),
    end: Number.parseInt(end),
    length: Number.parseInt(length),
  };
};

export const isComplete = ({ end, length }) => end === length - 1;

const downloadInChunks = async ({ bucket, key }) => {
  const writeStream = createWriteStream(
    fileURLToPath(new URL(`./${key}`, import.meta.url)),
  ).on("error", (err) => console.error(err));

  let rangeAndLength = { start: -1, end: -1, length: -1 };

  while (!isComplete(rangeAndLength)) {
    const { end } = rangeAndLength;
    const nextRange = { start: end + 1, end: end + oneMB };

    const { ContentRange, Body } = await getObjectRange({
      bucket,
      key,
      ...nextRange,
    });
    console.log(`Downloaded bytes ${nextRange.start} to ${nextRange.end}`);

    writeStream.write(await Body.transformToByteArray());
    rangeAndLength = getRangeAndLength(ContentRange);
  }
};

/**
 * Download a large object from and Amazon S3 bucket.
 *
 * When downloading a large file, you might want to break it down into
 * smaller pieces. Amazon S3 accepts a Range header to specify the start
 * and end of the byte range to be downloaded.
 *
 * @param {{ bucketName: string, key: string }}
 */
export const main = async ({ bucketName, key }) => {
  try {
    await downloadInChunks({
      bucket: bucketName,
      key: key,
    });
  } catch (caught) {
    if (caught instanceof NoSuchKey) {
      console.error(`Failed to download object. No such key "${key}".`);
      rmSync(key);
    }
  }
};
```

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_javascript_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
JavaScript を使用した Lambda での S3 イベントの消費。  

```
import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3";

const client = new S3Client();

export const handler = async (event, context) => {

    // Get the object from the event and show its content type
    const bucket = event.Records[0].s3.bucket.name;
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));

    try {
        const { ContentType } = await client.send(new HeadObjectCommand({
            Bucket: bucket,
            Key: key,
        }));

        console.log('CONTENT TYPE:', ContentType);
        return ContentType;

    } catch (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
        console.log(message);
        throw new Error(message);
    }
};
```
TypeScript を使用した Lambda での S3 イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { S3Event } from 'aws-lambda';
import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({ region: process.env.AWS_REGION });

export const handler = async (event: S3Event): Promise<string | undefined> => {
  // Get the object from the event and show its content type
  const bucket = event.Records[0].s3.bucket.name;
  const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  const params = {
    Bucket: bucket,
    Key: key,
  };
  try {
    const { ContentType } = await s3.send(new HeadObjectCommand(params));
    console.log('CONTENT TYPE:', ContentType);
    return ContentType;
  } catch (err) {
    console.log(err);
    const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
    console.log(message);
    throw new Error(message);
  }
};
```

# SDK for JavaScript (v3) を使用した SageMaker AI の例
<a name="javascript_3_sagemaker_code_examples"></a>

次のコード例は、SageMaker AI で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello SageMaker AI
<a name="sagemaker_Hello_javascript_3_topic"></a>

次のコード例は、SageMaker AI の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sagemaker#code-examples)での設定と実行の方法を確認してください。

```
import {
  SageMakerClient,
  ListNotebookInstancesCommand,
} from "@aws-sdk/client-sagemaker";

const client = new SageMakerClient({
  region: "us-west-2",
});

export const helloSagemaker = async () => {
  const command = new ListNotebookInstancesCommand({ MaxResults: 5 });

  const response = await client.send(command);
  console.log(
    "Hello Amazon SageMaker! Let's list some of your notebook instances:",
  );

  const instances = response.NotebookInstances || [];

  if (instances.length === 0) {
    console.log(
      "• No notebook instances found. Try creating one in the AWS Management Console or with the CreateNotebookInstanceCommand.",
    );
  } else {
    console.log(
      instances
        .map(
          (i) =>
            `• Instance: ${i.NotebookInstanceName}\n  Arn:${
              i.NotebookInstanceArn
            } \n  Creation Date: ${i.CreationTime.toISOString()}`,
        )
        .join("\n"),
    );
  }

  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListNotebookInstances](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/ListNotebookInstancesCommand)」を参照してください。

## アクション
<a name="actions"></a>

### `CreatePipeline`
<a name="sagemaker_CreatePipeline_javascript_3_topic"></a>

次のコード例は、`CreatePipeline` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sagemaker#code-examples)での設定と実行の方法を確認してください。
ローカルで提供される JSON 定義を使用して SageMaker AI パイプラインを作成する関数。  

```
/**
 * Create the Amazon SageMaker pipeline using a JSON pipeline definition. The definition
 * can also be provided as an Amazon S3 object using PipelineDefinitionS3Location.
 * @param {{roleArn: string, name: string, sagemakerClient: import('@aws-sdk/client-sagemaker').SageMakerClient}} props
 */
export async function createSagemakerPipeline({
  // Assumes an AWS IAM role has been created for this pipeline.
  roleArn,
  name,
  // Assumes an AWS Lambda function has been created for this pipeline.
  functionArn,
  sagemakerClient,
}) {
  const pipelineDefinition = readFileSync(
    // dirnameFromMetaUrl is a local utility function. You can find its implementation
    // on GitHub.
    `${dirnameFromMetaUrl(
      import.meta.url,
    )}../../../../../scenarios/features/sagemaker_pipelines/resources/GeoSpatialPipeline.json`,
  )
    .toString()
    .replace(/\*FUNCTION_ARN\*/g, functionArn);

  let arn = null;

  const createPipeline = () =>
    sagemakerClient.send(
      new CreatePipelineCommand({
        PipelineName: name,
        PipelineDefinition: pipelineDefinition,
        RoleArn: roleArn,
      }),
    );

  try {
    const { PipelineArn } = await createPipeline();
    arn = PipelineArn;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "ValidationException" &&
      caught.message.includes(
        "Pipeline names must be unique within an AWS account and region",
      )
    ) {
      const { PipelineArn } = await sagemakerClient.send(
        new DescribePipelineCommand({ PipelineName: name }),
      );
      arn = PipelineArn;
    } else {
      throw caught;
    }
  }

  return {
    arn,
    cleanUp: async () => {
      await sagemakerClient.send(
        new DeletePipelineCommand({ PipelineName: name }),
      );
    },
  };
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreatePipeline](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/CreatePipelineCommand)」を参照してください。

### `DeletePipeline`
<a name="sagemaker_DeletePipeline_javascript_3_topic"></a>

次のコード例は、`DeletePipeline` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sagemaker#code-examples)での設定と実行の方法を確認してください。
SageMaker AI パイプラインを削除するための構文。このコードは、より大きな関数の一部です。コンテキストの詳細については、「パイプラインの作成」または GitHub リポジトリを参照してください。  

```
      await sagemakerClient.send(
        new DeletePipelineCommand({ PipelineName: name }),
      );
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeletePipeline](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/DeletePipelineCommand)」を参照してください。

### `DescribePipelineExecution`
<a name="sagemaker_DescribePipelineExecution_javascript_3_topic"></a>

次のコード例は、`DescribePipelineExecution` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sagemaker#code-examples)での設定と実行の方法を確認してください。
SageMaker AI パイプラインの実行が成功、失敗、または停止するのを待ちます。  

```
/**
 * Poll the executing pipeline until the status is 'SUCCEEDED', 'STOPPED', or 'FAILED'.
 * @param {{ arn: string, sagemakerClient: import('@aws-sdk/client-sagemaker').SageMakerClient, wait: (ms: number) => Promise<void>}} props
 */
export async function waitForPipelineComplete({ arn, sagemakerClient, wait }) {
  const command = new DescribePipelineExecutionCommand({
    PipelineExecutionArn: arn,
  });

  let complete = false;
  const intervalInSeconds = 15;
  const COMPLETION_STATUSES = [
    PipelineExecutionStatus.FAILED,
    PipelineExecutionStatus.STOPPED,
    PipelineExecutionStatus.SUCCEEDED,
  ];

  do {
    const { PipelineExecutionStatus: status, FailureReason } =
      await sagemakerClient.send(command);

    complete = COMPLETION_STATUSES.includes(status);

    if (!complete) {
      console.log(
        `Pipeline is ${status}. Waiting ${intervalInSeconds} seconds before checking again.`,
      );
      await wait(intervalInSeconds);
    } else if (status === PipelineExecutionStatus.FAILED) {
      throw new Error(`Pipeline failed because: ${FailureReason}`);
    } else if (status === PipelineExecutionStatus.STOPPED) {
      throw new Error("Pipeline was forcefully stopped.");
    } else {
      console.log(`Pipeline execution ${status}.`);
    }
  } while (!complete);
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribePipelineExecution](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/DescribePipelineExecutionCommand)」を参照してください。

### `StartPipelineExecution`
<a name="sagemaker_StartPipelineExecution_javascript_3_topic"></a>

次のコード例は、`StartPipelineExecution` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sagemaker#code-examples)での設定と実行の方法を確認してください。
SageMaker AI パイプライン実行を開始します。  

```
/**
 * Start the execution of the Amazon SageMaker pipeline. Parameters that are
 * passed in are used in the AWS Lambda function.
 * @param {{
 *   name: string,
 *   sagemakerClient: import('@aws-sdk/client-sagemaker').SageMakerClient,
 *   roleArn: string,
 *   queueUrl: string,
 *   s3InputBucketName: string,
 * }} props
 */
export async function startPipelineExecution({
  sagemakerClient,
  name,
  bucketName,
  roleArn,
  queueUrl,
}) {
  /**
   * The Vector Enrichment Job requests CSV data. This configuration points to a CSV
   * file in an Amazon S3 bucket.
   * @type {import("@aws-sdk/client-sagemaker-geospatial").VectorEnrichmentJobInputConfig}
   */
  const inputConfig = {
    DataSourceConfig: {
      S3Data: {
        S3Uri: `s3://${bucketName}/input/sample_data.csv`,
      },
    },
    DocumentType: VectorEnrichmentJobDocumentType.CSV,
  };

  /**
   * The Vector Enrichment Job adds additional data to the source CSV. This configuration points
   * to an Amazon S3 prefix where the output will be stored.
   * @type {import("@aws-sdk/client-sagemaker-geospatial").ExportVectorEnrichmentJobOutputConfig}
   */
  const outputConfig = {
    S3Data: {
      S3Uri: `s3://${bucketName}/output/`,
    },
  };

  /**
   * This job will be a Reverse Geocoding Vector Enrichment Job. Reverse Geocoding requires
   * latitude and longitude values.
   * @type {import("@aws-sdk/client-sagemaker-geospatial").VectorEnrichmentJobConfig}
   */
  const jobConfig = {
    ReverseGeocodingConfig: {
      XAttributeName: "Longitude",
      YAttributeName: "Latitude",
    },
  };

  const { PipelineExecutionArn } = await sagemakerClient.send(
    new StartPipelineExecutionCommand({
      PipelineName: name,
      PipelineExecutionDisplayName: `${name}-example-execution`,
      PipelineParameters: [
        { Name: "parameter_execution_role", Value: roleArn },
        { Name: "parameter_queue_url", Value: queueUrl },
        {
          Name: "parameter_vej_input_config",
          Value: JSON.stringify(inputConfig),
        },
        {
          Name: "parameter_vej_export_config",
          Value: JSON.stringify(outputConfig),
        },
        {
          Name: "parameter_step_1_vej_config",
          Value: JSON.stringify(jobConfig),
        },
      ],
    }),
  );

  return {
    arn: PipelineExecutionArn,
  };
}
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[StartPipelineExecution](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/StartPipelineExecutionCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 地理空間ジョブとパイプラインの使用を開始する
<a name="sagemaker_Scenario_Pipelines_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パイプラインのリソースを設定します。
+ 地理空間ジョブを実行するパイプラインを設定します。
+ パイプラインの実行を開始します。
+ ジョブ実行のステータスをモニタリングします。
+ パイプラインの出力を表示します。
+ リソースをクリーンアップします。

詳細については、[「Community.aws で SDK を使用して SageMaker パイプラインを作成および実行する AWS SDKs](https://community.aws/posts/create-and-run-sagemaker-pipelines-using-aws-sdks)」を参照してください。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sagemaker#code-examples)での設定と実行の方法を確認してください。
以下のファイルの抜粋には、SageMaker AI クライアントを使用してパイプラインを管理する関数が含まれています。  

```
import { readFileSync } from "node:fs";

import {
  CreateRoleCommand,
  DeleteRoleCommand,
  CreatePolicyCommand,
  DeletePolicyCommand,
  AttachRolePolicyCommand,
  DetachRolePolicyCommand,
  GetRoleCommand,
  ListPoliciesCommand,
} from "@aws-sdk/client-iam";

import {
  PublishLayerVersionCommand,
  DeleteLayerVersionCommand,
  CreateFunctionCommand,
  Runtime,
  DeleteFunctionCommand,
  CreateEventSourceMappingCommand,
  DeleteEventSourceMappingCommand,
  GetFunctionCommand,
} from "@aws-sdk/client-lambda";

import {
  PutObjectCommand,
  CreateBucketCommand,
  DeleteBucketCommand,
  DeleteObjectCommand,
  GetObjectCommand,
  ListObjectsV2Command,
} from "@aws-sdk/client-s3";

import {
  CreatePipelineCommand,
  DeletePipelineCommand,
  DescribePipelineCommand,
  DescribePipelineExecutionCommand,
  PipelineExecutionStatus,
  StartPipelineExecutionCommand,
} from "@aws-sdk/client-sagemaker";

import { VectorEnrichmentJobDocumentType } from "@aws-sdk/client-sagemaker-geospatial";

import {
  CreateQueueCommand,
  DeleteQueueCommand,
  GetQueueAttributesCommand,
  GetQueueUrlCommand,
} from "@aws-sdk/client-sqs";

import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

/**
 * Create the AWS IAM role that will be assumed by AWS Lambda.
 * @param {{ name: string, iamClient: import('@aws-sdk/client-iam').IAMClient }} props
 */
export async function createLambdaExecutionRole({ name, iamClient }) {
  const createRole = () =>
    iamClient.send(
      new CreateRoleCommand({
        RoleName: name,
        AssumeRolePolicyDocument: JSON.stringify({
          Version: "2012-10-17",
          Statement: [
            {
              Effect: "Allow",
              Action: ["sts:AssumeRole"],
              Principal: { Service: ["lambda.amazonaws.com"] },
            },
          ],
        }),
      }),
    );

  let role = null;

  try {
    const { Role } = await createRole();
    role = Role;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "EntityAlreadyExistsException"
    ) {
      const { Role } = await iamClient.send(
        new GetRoleCommand({ RoleName: name }),
      );
      role = Role;
    } else {
      throw caught;
    }
  }

  return {
    arn: role.Arn,
    cleanUp: async () => {
      await iamClient.send(new DeleteRoleCommand({ RoleName: name }));
    },
  };
}

/**
 * Create an AWS IAM policy that will be attached to the AWS IAM role assumed by the AWS Lambda function.
 * The policy grants permission to work with Amazon SQS, Amazon CloudWatch, and Amazon SageMaker.
 * @param {{name: string, iamClient: import('@aws-sdk/client-iam').IAMClient, pipelineExecutionRoleArn: string}} props
 */
export async function createLambdaExecutionPolicy({
  name,
  iamClient,
  pipelineExecutionRoleArn,
}) {
  const policyConfig = {
    Version: "2012-10-17",
    Statement: [
      {
        Effect: "Allow",
        Action: [
          "sqs:ReceiveMessage",
          "sqs:DeleteMessage",
          "sqs:GetQueueAttributes",
          "logs:CreateLogGroup",
          "logs:CreateLogStream",
          "logs:PutLogEvents",
          "sagemaker-geospatial:StartVectorEnrichmentJob",
          "sagemaker-geospatial:GetVectorEnrichmentJob",
          "sagemaker:SendPipelineExecutionStepFailure",
          "sagemaker:SendPipelineExecutionStepSuccess",
          "sagemaker-geospatial:ExportVectorEnrichmentJob",
        ],
        Resource: "*",
      },
      {
        Effect: "Allow",
        // The AWS Lambda function needs permission to pass the pipeline execution role to
        // the StartVectorEnrichmentCommand. This restriction prevents an AWS Lambda function
        // from elevating privileges. For more information, see:
        // https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_passrole.html
        Action: ["iam:PassRole"],
        Resource: `${pipelineExecutionRoleArn}`,
        Condition: {
          StringEquals: {
            "iam:PassedToService": [
              "sagemaker.amazonaws.com",
              "sagemaker-geospatial.amazonaws.com",
            ],
          },
        },
      },
    ],
  };

  const createPolicy = () =>
    iamClient.send(
      new CreatePolicyCommand({
        PolicyDocument: JSON.stringify(policyConfig),
        PolicyName: name,
      }),
    );

  let policy = null;

  try {
    const { Policy } = await createPolicy();
    policy = Policy;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "EntityAlreadyExistsException"
    ) {
      const { Policies } = await iamClient.send(new ListPoliciesCommand({}));
      if (Policies) {
        policy = Policies.find((p) => p.PolicyName === name);
      } else {
        throw new Error("No policies found.");
      }
    } else {
      throw caught;
    }
  }

  return {
    arn: policy?.Arn,
    policyConfig,
    cleanUp: async () => {
      await iamClient.send(new DeletePolicyCommand({ PolicyArn: policy?.Arn }));
    },
  };
}

/**
 * Attach an AWS IAM policy to an AWS IAM role.
 * @param {{roleName: string, policyArn: string, iamClient: import('@aws-sdk/client-iam').IAMClient}} props
 */
export async function attachPolicy({ roleName, policyArn, iamClient }) {
  const attachPolicyCommand = new AttachRolePolicyCommand({
    RoleName: roleName,
    PolicyArn: policyArn,
  });

  await iamClient.send(attachPolicyCommand);
  return {
    cleanUp: async () => {
      await iamClient.send(
        new DetachRolePolicyCommand({
          RoleName: roleName,
          PolicyArn: policyArn,
        }),
      );
    },
  };
}

/**
 * Create an AWS Lambda layer that contains the Amazon SageMaker and Amazon SageMaker Geospatial clients
 * in the runtime. The default runtime supports v3.188.0 of the JavaScript SDK. The Amazon SageMaker
 * Geospatial client wasn't introduced until v3.221.0.
 * @param {{ name: string, lambdaClient: import('@aws-sdk/client-lambda').LambdaClient }} props
 */
export async function createLambdaLayer({ name, lambdaClient }) {
  const layerPath = `${dirnameFromMetaUrl(import.meta.url)}lambda/nodejs.zip`;
  const { LayerVersionArn, Version } = await lambdaClient.send(
    new PublishLayerVersionCommand({
      LayerName: name,
      Content: {
        ZipFile: Uint8Array.from(readFileSync(layerPath)),
      },
    }),
  );

  return {
    versionArn: LayerVersionArn,
    version: Version,
    cleanUp: async () => {
      await lambdaClient.send(
        new DeleteLayerVersionCommand({
          LayerName: name,
          VersionNumber: Version,
        }),
      );
    },
  };
}

/**
 * Deploy the AWS Lambda function that will be used to respond to Amazon SageMaker pipeline
 * execution steps.
 * @param {{roleArn: string, name: string, lambdaClient: import('@aws-sdk/client-lambda').LambdaClient, layerVersionArn: string}} props
 */
export async function createLambdaFunction({
  name,
  roleArn,
  lambdaClient,
  layerVersionArn,
}) {
  const lambdaPath = `${dirnameFromMetaUrl(
    import.meta.url,
  )}lambda/dist/index.mjs.zip`;

  // If a function of the same name already exists, return that
  // function's ARN instead. By default this is
  // "sagemaker-wkflw-lambda-function", so collisions are
  // unlikely.
  const createFunction = async () => {
    try {
      return await lambdaClient.send(
        new CreateFunctionCommand({
          Code: {
            ZipFile: Uint8Array.from(readFileSync(lambdaPath)),
          },
          Runtime: Runtime.nodejs18x,
          Handler: "index.handler",
          Layers: [layerVersionArn],
          FunctionName: name,
          Role: roleArn,
        }),
      );
    } catch (caught) {
      if (
        caught instanceof Error &&
        caught.name === "ResourceConflictException"
      ) {
        const { Configuration } = await lambdaClient.send(
          new GetFunctionCommand({ FunctionName: name }),
        );
        return Configuration;
      }
      throw caught;
    }
  };

  // Function creation fails if the Role is not ready. This retries
  // function creation until it succeeds or it times out.
  const { FunctionArn } = await retry(
    { intervalInMs: 1000, maxRetries: 60 },
    createFunction,
  );

  return {
    arn: FunctionArn,
    cleanUp: async () => {
      await lambdaClient.send(
        new DeleteFunctionCommand({ FunctionName: name }),
      );
    },
  };
}

/**
 * This uploads some sample coordinate data to an Amazon S3 bucket.
 * The Amazon SageMaker Geospatial vector enrichment job will take the simple Lat/Long
 * coordinates in this file and augment them with more detailed location data.
 * @param {{bucketName: string, s3Client: import('@aws-sdk/client-s3').S3Client}} props
 */
export async function uploadCSVDataToS3({ bucketName, s3Client }) {
  const s3Path = `${dirnameFromMetaUrl(
    import.meta.url,
  )}../../../../../scenarios/features/sagemaker_pipelines/resources/latlongtest.csv`;

  await s3Client.send(
    new PutObjectCommand({
      Bucket: bucketName,
      Key: "input/sample_data.csv",
      Body: readFileSync(s3Path),
    }),
  );
}

/**
 * Create the AWS IAM role that will be assumed by the Amazon SageMaker pipeline.
 * @param {{name: string, iamClient: import('@aws-sdk/client-iam').IAMClient, wait: (ms: number) => Promise<void>}} props
 */
export async function createSagemakerRole({ name, iamClient, wait }) {
  let role = null;

  const createRole = () =>
    iamClient.send(
      new CreateRoleCommand({
        RoleName: name,
        AssumeRolePolicyDocument: JSON.stringify({
          Version: "2012-10-17",
          Statement: [
            {
              Effect: "Allow",
              Action: ["sts:AssumeRole"],
              Principal: {
                Service: [
                  "sagemaker.amazonaws.com",
                  "sagemaker-geospatial.amazonaws.com",
                ],
              },
            },
          ],
        }),
      }),
    );

  try {
    const { Role } = await createRole();
    role = Role;
    // Wait for the role to be ready.
    await wait(10);
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "EntityAlreadyExistsException"
    ) {
      const { Role } = await iamClient.send(
        new GetRoleCommand({ RoleName: name }),
      );
      role = Role;
    } else {
      throw caught;
    }
  }

  return {
    arn: role.Arn,
    cleanUp: async () => {
      await iamClient.send(new DeleteRoleCommand({ RoleName: name }));
    },
  };
}

/**
 * Create the Amazon SageMaker execution policy. This policy grants permission to
 * invoke the AWS Lambda function, read/write to the Amazon S3 bucket, and send messages to
 * the Amazon SQS queue.
 * @param {{ name: string, sqsQueueArn: string, lambdaArn: string, iamClient: import('@aws-sdk/client-iam').IAMClient, s3BucketName: string}} props
 */
export async function createSagemakerExecutionPolicy({
  sqsQueueArn,
  lambdaArn,
  iamClient,
  name,
  s3BucketName,
}) {
  const policyConfig = {
    Version: "2012-10-17",
    Statement: [
      {
        Effect: "Allow",
        Action: ["lambda:InvokeFunction"],
        Resource: lambdaArn,
      },
      {
        Effect: "Allow",
        Action: ["s3:*"],
        Resource: [
          `arn:aws:s3:::${s3BucketName}`,
          `arn:aws:s3:::${s3BucketName}/*`,
        ],
      },
      {
        Effect: "Allow",
        Action: ["sqs:SendMessage"],
        Resource: sqsQueueArn,
      },
    ],
  };

  const createPolicy = () =>
    iamClient.send(
      new CreatePolicyCommand({
        PolicyDocument: JSON.stringify(policyConfig),
        PolicyName: name,
      }),
    );

  let policy = null;

  try {
    const { Policy } = await createPolicy();
    policy = Policy;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "EntityAlreadyExistsException"
    ) {
      const { Policies } = await iamClient.send(new ListPoliciesCommand({}));
      if (Policies) {
        policy = Policies.find((p) => p.PolicyName === name);
      } else {
        throw new Error("No policies found.");
      }
    } else {
      throw caught;
    }
  }

  return {
    arn: policy?.Arn,
    policyConfig,
    cleanUp: async () => {
      await iamClient.send(new DeletePolicyCommand({ PolicyArn: policy?.Arn }));
    },
  };
}

/**
 * Create the Amazon SageMaker pipeline using a JSON pipeline definition. The definition
 * can also be provided as an Amazon S3 object using PipelineDefinitionS3Location.
 * @param {{roleArn: string, name: string, sagemakerClient: import('@aws-sdk/client-sagemaker').SageMakerClient}} props
 */
export async function createSagemakerPipeline({
  // Assumes an AWS IAM role has been created for this pipeline.
  roleArn,
  name,
  // Assumes an AWS Lambda function has been created for this pipeline.
  functionArn,
  sagemakerClient,
}) {
  const pipelineDefinition = readFileSync(
    // dirnameFromMetaUrl is a local utility function. You can find its implementation
    // on GitHub.
    `${dirnameFromMetaUrl(
      import.meta.url,
    )}../../../../../scenarios/features/sagemaker_pipelines/resources/GeoSpatialPipeline.json`,
  )
    .toString()
    .replace(/\*FUNCTION_ARN\*/g, functionArn);

  let arn = null;

  const createPipeline = () =>
    sagemakerClient.send(
      new CreatePipelineCommand({
        PipelineName: name,
        PipelineDefinition: pipelineDefinition,
        RoleArn: roleArn,
      }),
    );

  try {
    const { PipelineArn } = await createPipeline();
    arn = PipelineArn;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "ValidationException" &&
      caught.message.includes(
        "Pipeline names must be unique within an AWS account and region",
      )
    ) {
      const { PipelineArn } = await sagemakerClient.send(
        new DescribePipelineCommand({ PipelineName: name }),
      );
      arn = PipelineArn;
    } else {
      throw caught;
    }
  }

  return {
    arn,
    cleanUp: async () => {
      await sagemakerClient.send(
        new DeletePipelineCommand({ PipelineName: name }),
      );
    },
  };
}

/**
 * Create an Amazon SQS queue. The Amazon SageMaker pipeline will send messages
 * to this queue that are then processed by the AWS Lambda function.
 * @param {{name: string, sqsClient: import('@aws-sdk/client-sqs').SQSClient}} props
 */
export async function createSQSQueue({ name, sqsClient }) {
  const createSqsQueue = () =>
    sqsClient.send(
      new CreateQueueCommand({
        QueueName: name,
        Attributes: {
          DelaySeconds: "5",
          ReceiveMessageWaitTimeSeconds: "5",
          VisibilityTimeout: "300",
        },
      }),
    );

  let queueUrl = null;
  try {
    const { QueueUrl } = await createSqsQueue();
    queueUrl = QueueUrl;
  } catch (caught) {
    if (caught instanceof Error && caught.name === "QueueNameExists") {
      const { QueueUrl } = await sqsClient.send(
        new GetQueueUrlCommand({ QueueName: name }),
      );
      queueUrl = QueueUrl;
    } else {
      throw caught;
    }
  }

  const { Attributes } = await retry(
    { intervalInMs: 1000, maxRetries: 60 },
    () =>
      sqsClient.send(
        new GetQueueAttributesCommand({
          QueueUrl: queueUrl,
          AttributeNames: ["QueueArn"],
        }),
      ),
  );

  return {
    queueUrl,
    queueArn: Attributes.QueueArn,
    cleanUp: async () => {
      await sqsClient.send(new DeleteQueueCommand({ QueueUrl: queueUrl }));
    },
  };
}

/**
 * Configure the AWS Lambda function to long poll for messages from the Amazon SQS
 * queue.
 * @param {{
 *   paginateListEventSourceMappings: () => Generator<import('@aws-sdk/client-lambda').ListEventSourceMappingsCommandOutput>,
 *   lambdaName: string,
 *   queueArn: string,
 *   lambdaClient: import('@aws-sdk/client-lambda').LambdaClient}} props
 */
export async function configureLambdaSQSEventSource({
  lambdaName,
  queueArn,
  lambdaClient,
  paginateListEventSourceMappings,
}) {
  let uuid = null;
  const createEvenSourceMapping = () =>
    lambdaClient.send(
      new CreateEventSourceMappingCommand({
        EventSourceArn: queueArn,
        FunctionName: lambdaName,
      }),
    );

  try {
    const { UUID } = await createEvenSourceMapping();
    uuid = UUID;
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "ResourceConflictException"
    ) {
      const paginator = paginateListEventSourceMappings(
        { client: lambdaClient },
        {},
      );
      /**
       * @type {import('@aws-sdk/client-lambda').EventSourceMappingConfiguration[]}
       */
      const eventSourceMappings = [];
      for await (const page of paginator) {
        eventSourceMappings.concat(page.EventSourceMappings || []);
      }

      const { Configuration } = await lambdaClient.send(
        new GetFunctionCommand({ FunctionName: lambdaName }),
      );

      uuid = eventSourceMappings.find(
        (mapping) =>
          mapping.EventSourceArn === queueArn &&
          mapping.FunctionArn === Configuration.FunctionArn,
      ).UUID;
    } else {
      throw caught;
    }
  }

  return {
    cleanUp: async () => {
      await lambdaClient.send(
        new DeleteEventSourceMappingCommand({
          UUID: uuid,
        }),
      );
    },
  };
}

/**
 * Create an Amazon S3 bucket that will store the simple coordinate file as input
 * and the output of the Amazon SageMaker Geospatial vector enrichment job.
 * @param {{
 *   s3Client: import('@aws-sdk/client-s3').S3Client,
 *   name: string,
 *   paginateListObjectsV2: () => Generator<import('@aws-sdk/client-s3').ListObjectsCommandOutput>
 * }} props
 */
export async function createS3Bucket({
  name,
  s3Client,
  paginateListObjectsV2,
}) {
  await s3Client.send(new CreateBucketCommand({ Bucket: name }));

  return {
    cleanUp: async () => {
      const paginator = paginateListObjectsV2(
        { client: s3Client },
        { Bucket: name },
      );
      for await (const page of paginator) {
        const objects = page.Contents;
        if (objects) {
          for (const object of objects) {
            await s3Client.send(
              new DeleteObjectCommand({ Bucket: name, Key: object.Key }),
            );
          }
        }
      }
      await s3Client.send(new DeleteBucketCommand({ Bucket: name }));
    },
  };
}

/**
 * Start the execution of the Amazon SageMaker pipeline. Parameters that are
 * passed in are used in the AWS Lambda function.
 * @param {{
 *   name: string,
 *   sagemakerClient: import('@aws-sdk/client-sagemaker').SageMakerClient,
 *   roleArn: string,
 *   queueUrl: string,
 *   s3InputBucketName: string,
 * }} props
 */
export async function startPipelineExecution({
  sagemakerClient,
  name,
  bucketName,
  roleArn,
  queueUrl,
}) {
  /**
   * The Vector Enrichment Job requests CSV data. This configuration points to a CSV
   * file in an Amazon S3 bucket.
   * @type {import("@aws-sdk/client-sagemaker-geospatial").VectorEnrichmentJobInputConfig}
   */
  const inputConfig = {
    DataSourceConfig: {
      S3Data: {
        S3Uri: `s3://${bucketName}/input/sample_data.csv`,
      },
    },
    DocumentType: VectorEnrichmentJobDocumentType.CSV,
  };

  /**
   * The Vector Enrichment Job adds additional data to the source CSV. This configuration points
   * to an Amazon S3 prefix where the output will be stored.
   * @type {import("@aws-sdk/client-sagemaker-geospatial").ExportVectorEnrichmentJobOutputConfig}
   */
  const outputConfig = {
    S3Data: {
      S3Uri: `s3://${bucketName}/output/`,
    },
  };

  /**
   * This job will be a Reverse Geocoding Vector Enrichment Job. Reverse Geocoding requires
   * latitude and longitude values.
   * @type {import("@aws-sdk/client-sagemaker-geospatial").VectorEnrichmentJobConfig}
   */
  const jobConfig = {
    ReverseGeocodingConfig: {
      XAttributeName: "Longitude",
      YAttributeName: "Latitude",
    },
  };

  const { PipelineExecutionArn } = await sagemakerClient.send(
    new StartPipelineExecutionCommand({
      PipelineName: name,
      PipelineExecutionDisplayName: `${name}-example-execution`,
      PipelineParameters: [
        { Name: "parameter_execution_role", Value: roleArn },
        { Name: "parameter_queue_url", Value: queueUrl },
        {
          Name: "parameter_vej_input_config",
          Value: JSON.stringify(inputConfig),
        },
        {
          Name: "parameter_vej_export_config",
          Value: JSON.stringify(outputConfig),
        },
        {
          Name: "parameter_step_1_vej_config",
          Value: JSON.stringify(jobConfig),
        },
      ],
    }),
  );

  return {
    arn: PipelineExecutionArn,
  };
}

/**
 * Poll the executing pipeline until the status is 'SUCCEEDED', 'STOPPED', or 'FAILED'.
 * @param {{ arn: string, sagemakerClient: import('@aws-sdk/client-sagemaker').SageMakerClient, wait: (ms: number) => Promise<void>}} props
 */
export async function waitForPipelineComplete({ arn, sagemakerClient, wait }) {
  const command = new DescribePipelineExecutionCommand({
    PipelineExecutionArn: arn,
  });

  let complete = false;
  const intervalInSeconds = 15;
  const COMPLETION_STATUSES = [
    PipelineExecutionStatus.FAILED,
    PipelineExecutionStatus.STOPPED,
    PipelineExecutionStatus.SUCCEEDED,
  ];

  do {
    const { PipelineExecutionStatus: status, FailureReason } =
      await sagemakerClient.send(command);

    complete = COMPLETION_STATUSES.includes(status);

    if (!complete) {
      console.log(
        `Pipeline is ${status}. Waiting ${intervalInSeconds} seconds before checking again.`,
      );
      await wait(intervalInSeconds);
    } else if (status === PipelineExecutionStatus.FAILED) {
      throw new Error(`Pipeline failed because: ${FailureReason}`);
    } else if (status === PipelineExecutionStatus.STOPPED) {
      throw new Error("Pipeline was forcefully stopped.");
    } else {
      console.log(`Pipeline execution ${status}.`);
    }
  } while (!complete);
}

/**
 * Return the string value of an Amazon S3 object.
 * @param {{ bucket: string, key: string, s3Client: import('@aws-sdk/client-s3').S3Client}} param0
 */
export async function getObject({ bucket, s3Client }) {
  const prefix = "output/";
  const { Contents } = await s3Client.send(
    new ListObjectsV2Command({ MaxKeys: 1, Bucket: bucket, Prefix: prefix }),
  );

  if (!Contents.length) {
    throw new Error("No objects found in bucket.");
  }

  // Find the CSV file.
  const outputObject = Contents.find((obj) => obj.Key.endsWith(".csv"));

  if (!outputObject) {
    throw new Error(`No CSV file found in bucket with the prefix "${prefix}".`);
  }

  const { Body } = await s3Client.send(
    new GetObjectCommand({
      Bucket: bucket,
      Key: outputObject.Key,
    }),
  );

  return Body.transformToString();
}
```
この関数は、上記のライブラリ関数により SageMaker AI パイプラインを設定して実行し、作成されたすべてのリソースを削除するファイルからの抜粋です。  

```
import { retry, wait } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import {
  attachPolicy,
  configureLambdaSQSEventSource,
  createLambdaExecutionPolicy,
  createLambdaExecutionRole,
  createLambdaFunction,
  createLambdaLayer,
  createS3Bucket,
  createSQSQueue,
  createSagemakerExecutionPolicy,
  createSagemakerPipeline,
  createSagemakerRole,
  getObject,
  startPipelineExecution,
  uploadCSVDataToS3,
  waitForPipelineComplete,
} from "./lib.js";
import { MESSAGES } from "./messages.js";

export class SageMakerPipelinesWkflw {
  names = {
    LAMBDA_EXECUTION_ROLE: "sagemaker-wkflw-lambda-execution-role",
    LAMBDA_EXECUTION_ROLE_POLICY:
      "sagemaker-wkflw-lambda-execution-role-policy",
    LAMBDA_FUNCTION: "sagemaker-wkflw-lambda-function",
    LAMBDA_LAYER: "sagemaker-wkflw-lambda-layer",
    SAGE_MAKER_EXECUTION_ROLE: "sagemaker-wkflw-pipeline-execution-role",
    SAGE_MAKER_EXECUTION_ROLE_POLICY:
      "sagemaker-wkflw-pipeline-execution-role-policy",
    SAGE_MAKER_PIPELINE: "sagemaker-wkflw-pipeline",
    SQS_QUEUE: "sagemaker-wkflw-sqs-queue",
    S3_BUCKET: `sagemaker-wkflw-s3-bucket-${Date.now()}`,
  };

  cleanUpFunctions = [];

  /**
   * @param {import("@aws-doc-sdk-examples/lib/prompter.js").Prompter} prompter
   * @param {import("@aws-doc-sdk-examples/lib/logger.js").Logger} logger
   * @param {{ IAM: import("@aws-sdk/client-iam").IAMClient, Lambda: import("@aws-sdk/client-lambda").LambdaClient, SageMaker: import("@aws-sdk/client-sagemaker").SageMakerClient, S3: import("@aws-sdk/client-s3").S3Client, SQS: import("@aws-sdk/client-sqs").SQSClient }} clients
   */
  constructor(prompter, logger, clients) {
    this.prompter = prompter;
    this.logger = logger;
    this.clients = clients;
  }

  async run() {
    try {
      await this.startWorkflow();
    } catch (err) {
      console.error(err);
      throw err;
    } finally {
      this.logger.logSeparator();
      const doCleanUp = await this.prompter.confirm({
        message: "Clean up resources?",
      });
      if (doCleanUp) {
        await this.cleanUp();
      }
    }
  }

  async cleanUp() {
    // Run all of the clean up functions. If any fail, we log the error and continue.
    // This ensures all clean up functions are run.
    for (let i = this.cleanUpFunctions.length - 1; i >= 0; i--) {
      await retry(
        { intervalInMs: 1000, maxRetries: 60, swallowError: true },
        this.cleanUpFunctions[i],
      );
    }
  }

  async startWorkflow() {
    this.logger.logSeparator(MESSAGES.greetingHeader);
    await this.logger.log(MESSAGES.greeting);

    this.logger.logSeparator();
    await this.logger.log(
      MESSAGES.creatingRole.replace(
        "${ROLE_NAME}",
        this.names.LAMBDA_EXECUTION_ROLE,
      ),
    );

    // Create an IAM role that will be assumed by the AWS Lambda function. This function
    // is triggered by Amazon SQS messages and calls SageMaker and SageMaker GeoSpatial actions.
    const { arn: lambdaExecutionRoleArn, cleanUp: lambdaExecutionRoleCleanUp } =
      await createLambdaExecutionRole({
        name: this.names.LAMBDA_EXECUTION_ROLE,
        iamClient: this.clients.IAM,
      });
    // Add a clean up step to a stack for every resource created.
    this.cleanUpFunctions.push(lambdaExecutionRoleCleanUp);

    await this.logger.log(
      MESSAGES.roleCreated.replace(
        "${ROLE_NAME}",
        this.names.LAMBDA_EXECUTION_ROLE,
      ),
    );

    this.logger.logSeparator();

    await this.logger.log(
      MESSAGES.creatingRole.replace(
        "${ROLE_NAME}",
        this.names.SAGE_MAKER_EXECUTION_ROLE,
      ),
    );

    // Create an IAM role that will be assumed by the SageMaker pipeline. The pipeline
    // sends messages to an Amazon SQS queue and puts/retrieves Amazon S3 objects.
    const {
      arn: pipelineExecutionRoleArn,
      cleanUp: pipelineExecutionRoleCleanUp,
    } = await createSagemakerRole({
      iamClient: this.clients.IAM,
      name: this.names.SAGE_MAKER_EXECUTION_ROLE,
      wait,
    });
    this.cleanUpFunctions.push(pipelineExecutionRoleCleanUp);

    await this.logger.log(
      MESSAGES.roleCreated.replace(
        "${ROLE_NAME}",
        this.names.SAGE_MAKER_EXECUTION_ROLE,
      ),
    );

    this.logger.logSeparator();

    // Create an IAM policy that allows the AWS Lambda function to invoke SageMaker APIs.
    const {
      arn: lambdaExecutionPolicyArn,
      policy: lambdaPolicy,
      cleanUp: lambdaExecutionPolicyCleanUp,
    } = await createLambdaExecutionPolicy({
      name: this.names.LAMBDA_EXECUTION_ROLE_POLICY,
      s3BucketName: this.names.S3_BUCKET,
      iamClient: this.clients.IAM,
      pipelineExecutionRoleArn,
    });
    this.cleanUpFunctions.push(lambdaExecutionPolicyCleanUp);

    console.log(JSON.stringify(lambdaPolicy, null, 2), "\n");

    await this.logger.log(
      MESSAGES.attachPolicy
        .replace("${POLICY_NAME}", this.names.LAMBDA_EXECUTION_ROLE_POLICY)
        .replace("${ROLE_NAME}", this.names.LAMBDA_EXECUTION_ROLE),
    );

    await this.prompter.checkContinue();

    // Attach the Lambda execution policy to the execution role.
    const { cleanUp: lambdaExecutionRolePolicyCleanUp } = await attachPolicy({
      roleName: this.names.LAMBDA_EXECUTION_ROLE,
      policyArn: lambdaExecutionPolicyArn,
      iamClient: this.clients.IAM,
    });
    this.cleanUpFunctions.push(lambdaExecutionRolePolicyCleanUp);

    await this.logger.log(MESSAGES.policyAttached);

    this.logger.logSeparator();

    // Create Lambda layer for SageMaker packages.
    const { versionArn: layerVersionArn, cleanUp: lambdaLayerCleanUp } =
      await createLambdaLayer({
        name: this.names.LAMBDA_LAYER,
        lambdaClient: this.clients.Lambda,
      });
    this.cleanUpFunctions.push(lambdaLayerCleanUp);

    await this.logger.log(
      MESSAGES.creatingFunction.replace(
        "${FUNCTION_NAME}",
        this.names.LAMBDA_FUNCTION,
      ),
    );

    // Create the Lambda function with the execution role.
    const { arn: lambdaArn, cleanUp: lambdaCleanUp } =
      await createLambdaFunction({
        roleArn: lambdaExecutionRoleArn,
        lambdaClient: this.clients.Lambda,
        name: this.names.LAMBDA_FUNCTION,
        layerVersionArn,
      });
    this.cleanUpFunctions.push(lambdaCleanUp);

    await this.logger.log(
      MESSAGES.functionCreated.replace(
        "${FUNCTION_NAME}",
        this.names.LAMBDA_FUNCTION,
      ),
    );

    this.logger.logSeparator();

    await this.logger.log(
      MESSAGES.creatingSQSQueue.replace("${QUEUE_NAME}", this.names.SQS_QUEUE),
    );

    // Create an SQS queue for the SageMaker pipeline.
    const {
      queueUrl,
      queueArn,
      cleanUp: queueCleanUp,
    } = await createSQSQueue({
      name: this.names.SQS_QUEUE,
      sqsClient: this.clients.SQS,
    });
    this.cleanUpFunctions.push(queueCleanUp);

    await this.logger.log(
      MESSAGES.sqsQueueCreated.replace("${QUEUE_NAME}", this.names.SQS_QUEUE),
    );

    this.logger.logSeparator();

    await this.logger.log(
      MESSAGES.configuringLambdaSQSEventSource
        .replace("${LAMBDA_NAME}", this.names.LAMBDA_FUNCTION)
        .replace("${QUEUE_NAME}", this.names.SQS_QUEUE),
    );

    // Configure the SQS queue as an event source for the Lambda.
    const { cleanUp: lambdaSQSEventSourceCleanUp } =
      await configureLambdaSQSEventSource({
        lambdaArn,
        lambdaName: this.names.LAMBDA_FUNCTION,
        queueArn,
        sqsClient: this.clients.SQS,
        lambdaClient: this.clients.Lambda,
      });
    this.cleanUpFunctions.push(lambdaSQSEventSourceCleanUp);

    await this.logger.log(
      MESSAGES.lambdaSQSEventSourceConfigured
        .replace("${LAMBDA_NAME}", this.names.LAMBDA_FUNCTION)
        .replace("${QUEUE_NAME}", this.names.SQS_QUEUE),
    );

    this.logger.logSeparator();

    // Create an IAM policy that allows the SageMaker pipeline to invoke AWS Lambda
    // and send messages to the Amazon SQS queue.
    const {
      arn: pipelineExecutionPolicyArn,
      policy: sagemakerPolicy,
      cleanUp: pipelineExecutionPolicyCleanUp,
    } = await createSagemakerExecutionPolicy({
      sqsQueueArn: queueArn,
      lambdaArn,
      iamClient: this.clients.IAM,
      name: this.names.SAGE_MAKER_EXECUTION_ROLE_POLICY,
      s3BucketName: this.names.S3_BUCKET,
    });
    this.cleanUpFunctions.push(pipelineExecutionPolicyCleanUp);

    console.log(JSON.stringify(sagemakerPolicy, null, 2));

    await this.logger.log(
      MESSAGES.attachPolicy
        .replace("${POLICY_NAME}", this.names.SAGE_MAKER_EXECUTION_ROLE_POLICY)
        .replace("${ROLE_NAME}", this.names.SAGE_MAKER_EXECUTION_ROLE),
    );

    await this.prompter.checkContinue();

    // Attach the SageMaker execution policy to the execution role.
    const { cleanUp: pipelineExecutionRolePolicyCleanUp } = await attachPolicy({
      roleName: this.names.SAGE_MAKER_EXECUTION_ROLE,
      policyArn: pipelineExecutionPolicyArn,
      iamClient: this.clients.IAM,
    });
    this.cleanUpFunctions.push(pipelineExecutionRolePolicyCleanUp);
    // Wait for the role to be ready. If the role is used immediately,
    // the pipeline will fail.
    await wait(5);

    await this.logger.log(MESSAGES.policyAttached);

    this.logger.logSeparator();

    await this.logger.log(
      MESSAGES.creatingPipeline.replace(
        "${PIPELINE_NAME}",
        this.names.SAGE_MAKER_PIPELINE,
      ),
    );

    // Create the SageMaker pipeline.
    const { cleanUp: pipelineCleanUp } = await createSagemakerPipeline({
      roleArn: pipelineExecutionRoleArn,
      functionArn: lambdaArn,
      sagemakerClient: this.clients.SageMaker,
      name: this.names.SAGE_MAKER_PIPELINE,
    });
    this.cleanUpFunctions.push(pipelineCleanUp);

    await this.logger.log(
      MESSAGES.pipelineCreated.replace(
        "${PIPELINE_NAME}",
        this.names.SAGE_MAKER_PIPELINE,
      ),
    );

    this.logger.logSeparator();

    await this.logger.log(
      MESSAGES.creatingS3Bucket.replace("${BUCKET_NAME}", this.names.S3_BUCKET),
    );

    // Create an S3 bucket for storing inputs and outputs.
    const { cleanUp: s3BucketCleanUp } = await createS3Bucket({
      name: this.names.S3_BUCKET,
      s3Client: this.clients.S3,
    });
    this.cleanUpFunctions.push(s3BucketCleanUp);

    await this.logger.log(
      MESSAGES.s3BucketCreated.replace("${BUCKET_NAME}", this.names.S3_BUCKET),
    );

    this.logger.logSeparator();

    await this.logger.log(
      MESSAGES.uploadingInputData.replace(
        "${BUCKET_NAME}",
        this.names.S3_BUCKET,
      ),
    );

    // Upload CSV Lat/Long data to S3.
    await uploadCSVDataToS3({
      bucketName: this.names.S3_BUCKET,
      s3Client: this.clients.S3,
    });

    await this.logger.log(MESSAGES.inputDataUploaded);

    this.logger.logSeparator();

    await this.prompter.checkContinue(MESSAGES.executePipeline);

    // Execute the SageMaker pipeline.
    const { arn: pipelineExecutionArn } = await startPipelineExecution({
      name: this.names.SAGE_MAKER_PIPELINE,
      sagemakerClient: this.clients.SageMaker,
      roleArn: pipelineExecutionRoleArn,
      bucketName: this.names.S3_BUCKET,
      queueUrl,
    });

    // Wait for the pipeline execution to finish.
    await waitForPipelineComplete({
      arn: pipelineExecutionArn,
      sagemakerClient: this.clients.SageMaker,
      wait,
    });

    this.logger.logSeparator();

    await this.logger.log(MESSAGES.outputDelay);

    // The getOutput function will throw an error if the output is not
    // found. The retry function will retry a failed function call once
    // ever 10 seconds for 2 minutes.
    const output = await retry({ intervalInMs: 10000, maxRetries: 12 }, () =>
      getObject({
        bucket: this.names.S3_BUCKET,
        s3Client: this.clients.S3,
      }),
    );

    this.logger.logSeparator();
    await this.logger.log(MESSAGES.outputDataRetrieved);
    console.log(output.split("\n").slice(0, 6).join("\n"));
  }
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CreatePipeline](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/CreatePipelineCommand)
  + [DeletePipeline](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/DeletePipelineCommand)
  + [DescribePipelineExecution](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/DescribePipelineExecutionCommand)
  + [StartPipelineExecution](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/StartPipelineExecutionCommand)
  + [UpdatePipeline](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sagemaker/command/UpdatePipelineCommand)

# SDK for JavaScript (v3) を使用した Secrets Manager の例
<a name="javascript_3_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_javascript_3_topic"></a>

次のコード例は、`GetSecretValue` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/secrets-manager#code-examples)での設定と実行の方法を確認してください。

```
import {
  GetSecretValueCommand,
  SecretsManagerClient,
} from "@aws-sdk/client-secrets-manager";

export const getSecretValue = async (secretName = "SECRET_NAME") => {
  const client = new SecretsManagerClient();
  const response = await client.send(
    new GetSecretValueCommand({
      SecretId: secretName,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '584eb612-f8b0-48c9-855e-6d246461b604',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   ARN: 'arn:aws:secretsmanager:us-east-1:xxxxxxxxxxxx:secret:binary-secret-3873048-xxxxxx',
  //   CreatedDate: 2023-08-08T19:29:51.294Z,
  //   Name: 'binary-secret-3873048',
  //   SecretBinary: Uint8Array(11) [
  //      98, 105, 110, 97, 114,
  //     121,  32, 100, 97, 116,
  //      97
  //   ],
  //   VersionId: '712083f4-0d26-415e-8044-16735142cd6a',
  //   VersionStages: [ 'AWSCURRENT' ]
  // }

  if (response.SecretString) {
    return response.SecretString;
  }

  if (response.SecretBinary) {
    return response.SecretBinary;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[GetSecretValue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/secrets-manager/command/GetSecretValueCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon SES の例
<a name="javascript_3_ses_code_examples"></a>

次のコード例は、Amazon SES で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateReceiptFilter`
<a name="ses_CreateReceiptFilter_javascript_3_topic"></a>

次のコード例は、`CreateReceiptFilter` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import {
  CreateReceiptFilterCommand,
  ReceiptFilterPolicy,
} from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

const createCreateReceiptFilterCommand = ({ policy, ipOrRange, name }) => {
  return new CreateReceiptFilterCommand({
    Filter: {
      IpFilter: {
        Cidr: ipOrRange, // string, either a single IP address (10.0.0.1) or an IP address range in CIDR notation (10.0.0.1/24)).
        Policy: policy, // enum ReceiptFilterPolicy, email traffic from the filtered addressesOptions.
      },
      /*
        The name of the IP address filter. Only ASCII letters, numbers, underscores, or dashes.
        Must be less than 64 characters and start and end with a letter or number.
       */
      Name: name,
    },
  });
};

const FILTER_NAME = getUniqueName("ReceiptFilter");

const run = async () => {
  const createReceiptFilterCommand = createCreateReceiptFilterCommand({
    policy: ReceiptFilterPolicy.Allow,
    ipOrRange: "10.0.0.1",
    name: FILTER_NAME,
  });

  try {
    return await sesClient.send(createReceiptFilterCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[CreateReceiptFilter](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/CreateReceiptFilterCommand)」を参照してください。

### `CreateReceiptRule`
<a name="ses_CreateReceiptRule_javascript_3_topic"></a>

次のコード例は、`CreateReceiptRule` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { CreateReceiptRuleCommand, TlsPolicy } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

const RULE_SET_NAME = getUniqueName("RuleSetName");
const RULE_NAME = getUniqueName("RuleName");
const S3_BUCKET_NAME = getUniqueName("S3BucketName");

const createS3ReceiptRuleCommand = ({
  bucketName,
  emailAddresses,
  name,
  ruleSet,
}) => {
  return new CreateReceiptRuleCommand({
    Rule: {
      Actions: [
        {
          S3Action: {
            BucketName: bucketName,
            ObjectKeyPrefix: "email",
          },
        },
      ],
      Recipients: emailAddresses,
      Enabled: true,
      Name: name,
      ScanEnabled: false,
      TlsPolicy: TlsPolicy.Optional,
    },
    RuleSetName: ruleSet, // Required
  });
};

const run = async () => {
  const s3ReceiptRuleCommand = createS3ReceiptRuleCommand({
    bucketName: S3_BUCKET_NAME,
    emailAddresses: ["email@example.com"],
    name: RULE_NAME,
    ruleSet: RULE_SET_NAME,
  });

  try {
    return await sesClient.send(s3ReceiptRuleCommand);
  } catch (err) {
    console.log("Failed to create S3 receipt rule.", err);
    throw err;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[CreateReceiptRule](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/CreateReceiptRuleCommand)」を参照してください。

### `CreateReceiptRuleSet`
<a name="ses_CreateReceiptRuleSet_javascript_3_topic"></a>

次のコード例は、`CreateReceiptRuleSet` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { CreateReceiptRuleSetCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

const RULE_SET_NAME = getUniqueName("RuleSetName");

const createCreateReceiptRuleSetCommand = (ruleSetName) => {
  return new CreateReceiptRuleSetCommand({ RuleSetName: ruleSetName });
};

const run = async () => {
  const createReceiptRuleSetCommand =
    createCreateReceiptRuleSetCommand(RULE_SET_NAME);

  try {
    return await sesClient.send(createReceiptRuleSetCommand);
  } catch (err) {
    console.log("Failed to create receipt rule set", err);
    return err;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[CreateReceiptRuleSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/CreateReceiptRuleSetCommand)」を参照してください。

### `CreateTemplate`
<a name="ses_CreateTemplate_javascript_3_topic"></a>

次のコード例は、`CreateTemplate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { CreateTemplateCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

const TEMPLATE_NAME = getUniqueName("TestTemplateName");

const createCreateTemplateCommand = () => {
  return new CreateTemplateCommand({
    /**
     * The template feature in Amazon SES is based on the Handlebars template system.
     */
    Template: {
      /**
       * The name of an existing template in Amazon SES.
       */
      TemplateName: TEMPLATE_NAME,
      HtmlPart: `
        <h1>Hello, {{contact.firstName}}!</h1>
        <p>
        Did you know Amazon has a mascot named Peccy?
        </p>
      `,
      SubjectPart: "Amazon Tip",
    },
  });
};

const run = async () => {
  const createTemplateCommand = createCreateTemplateCommand();

  try {
    return await sesClient.send(createTemplateCommand);
  } catch (err) {
    console.log("Failed to create template.", err);
    return err;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/CreateTemplateCommand)」を参照してください。

### `DeleteIdentity`
<a name="ses_DeleteIdentity_javascript_3_topic"></a>

次のコード例は、`DeleteIdentity` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteIdentityCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const IDENTITY_EMAIL = "fake@example.com";

const createDeleteIdentityCommand = (identityName) => {
  return new DeleteIdentityCommand({
    Identity: identityName,
  });
};

const run = async () => {
  const deleteIdentityCommand = createDeleteIdentityCommand(IDENTITY_EMAIL);

  try {
    return await sesClient.send(deleteIdentityCommand);
  } catch (err) {
    console.log("Failed to delete identity.", err);
    return err;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteIdentity](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/DeleteIdentityCommand)」を参照してください。

### `DeleteReceiptFilter`
<a name="ses_DeleteReceiptFilter_javascript_3_topic"></a>

次のコード例は、`DeleteReceiptFilter` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteReceiptFilterCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

const RECEIPT_FILTER_NAME = getUniqueName("ReceiptFilterName");

const createDeleteReceiptFilterCommand = (filterName) => {
  return new DeleteReceiptFilterCommand({ FilterName: filterName });
};

const run = async () => {
  const deleteReceiptFilterCommand =
    createDeleteReceiptFilterCommand(RECEIPT_FILTER_NAME);

  try {
    return await sesClient.send(deleteReceiptFilterCommand);
  } catch (err) {
    console.log("Error deleting receipt filter.", err);
    return err;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[DeleteReceiptFilter](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/DeleteReceiptFilterCommand)」を参照してください。

### `DeleteReceiptRule`
<a name="ses_DeleteReceiptRule_javascript_3_topic"></a>

次のコード例は、`DeleteReceiptRule` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteReceiptRuleCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const RULE_NAME = getUniqueName("RuleName");
const RULE_SET_NAME = getUniqueName("RuleSetName");

const createDeleteReceiptRuleCommand = () => {
  return new DeleteReceiptRuleCommand({
    RuleName: RULE_NAME,
    RuleSetName: RULE_SET_NAME,
  });
};

const run = async () => {
  const deleteReceiptRuleCommand = createDeleteReceiptRuleCommand();
  try {
    return await sesClient.send(deleteReceiptRuleCommand);
  } catch (err) {
    console.log("Failed to delete receipt rule.", err);
    return err;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[DeleteReceiptRule](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/DeleteReceiptRuleCommand)」を参照してください。

### `DeleteReceiptRuleSet`
<a name="ses_DeleteReceiptRuleSet_javascript_3_topic"></a>

次のコード例は、`DeleteReceiptRuleSet` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteReceiptRuleSetCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const RULE_SET_NAME = getUniqueName("RuleSetName");

const createDeleteReceiptRuleSetCommand = () => {
  return new DeleteReceiptRuleSetCommand({ RuleSetName: RULE_SET_NAME });
};

const run = async () => {
  const deleteReceiptRuleSetCommand = createDeleteReceiptRuleSetCommand();

  try {
    return await sesClient.send(deleteReceiptRuleSetCommand);
  } catch (err) {
    console.log("Failed to delete receipt rule set.", err);
    return err;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[DeleteReceiptRuleSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/DeleteReceiptRuleSetCommand)」を参照してください。

### `DeleteTemplate`
<a name="ses_DeleteTemplate_javascript_3_topic"></a>

次のコード例は、`DeleteTemplate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");

const createDeleteTemplateCommand = (templateName) =>
  new DeleteTemplateCommand({ TemplateName: templateName });

const run = async () => {
  const deleteTemplateCommand = createDeleteTemplateCommand(TEMPLATE_NAME);

  try {
    return await sesClient.send(deleteTemplateCommand);
  } catch (err) {
    console.log("Failed to delete template.", err);
    return err;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*のの「[DeleteTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/DeleteTemplateCommand)」を参照してください。

### `GetTemplate`
<a name="ses_GetTemplate_javascript_3_topic"></a>

次のコード例は、`GetTemplate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { GetTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");

const createGetTemplateCommand = (templateName) =>
  new GetTemplateCommand({ TemplateName: templateName });

const run = async () => {
  const getTemplateCommand = createGetTemplateCommand(TEMPLATE_NAME);

  try {
    return await sesClient.send(getTemplateCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[GetTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/GetTemplateCommand)」を参照してください。

### `ListIdentities`
<a name="ses_ListIdentities_javascript_3_topic"></a>

次のコード例は、`ListIdentities` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { ListIdentitiesCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createListIdentitiesCommand = () =>
  new ListIdentitiesCommand({ IdentityType: "EmailAddress", MaxItems: 10 });

const run = async () => {
  const listIdentitiesCommand = createListIdentitiesCommand();

  try {
    return await sesClient.send(listIdentitiesCommand);
  } catch (err) {
    console.log("Failed to list identities.", err);
    return err;
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[ListIdentities](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/ListIdentitiesCommand)」を参照してください。

### `ListReceiptFilters`
<a name="ses_ListReceiptFilters_javascript_3_topic"></a>

次のコード例は、`ListReceiptFilters` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { ListReceiptFiltersCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createListReceiptFiltersCommand = () => new ListReceiptFiltersCommand({});

const run = async () => {
  const listReceiptFiltersCommand = createListReceiptFiltersCommand();

  return await sesClient.send(listReceiptFiltersCommand);
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[ListReceiptFilters](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/ListReceiptFiltersCommand)」を参照してください。

### `ListTemplates`
<a name="ses_ListTemplates_javascript_3_topic"></a>

次のコード例は、`ListTemplates` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { ListTemplatesCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createListTemplatesCommand = (maxItems) =>
  new ListTemplatesCommand({ MaxItems: maxItems });

const run = async () => {
  const listTemplatesCommand = createListTemplatesCommand(10);

  try {
    return await sesClient.send(listTemplatesCommand);
  } catch (err) {
    console.log("Failed to list templates.", err);
    return err;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListTemplates](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/ListTemplatesCommand)」を参照してください。

### `SendBulkTemplatedEmail`
<a name="ses_SendBulkTemplatedEmail_javascript_3_topic"></a>

次のコード例は、`SendBulkTemplatedEmail` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { SendBulkTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL_1 = postfix(getUniqueName("Bilbo"), "@example.com");
const VERIFIED_EMAIL_2 = postfix(getUniqueName("Frodo"), "@example.com");

const USERS = [
  { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL_1 },
  { firstName: "Frodo", emailAddress: VERIFIED_EMAIL_2 },
];

/**
 *
 * @param { { emailAddress: string, firstName: string }[] } users
 * @param { string } templateName the name of an existing template in SES
 * @returns { SendBulkTemplatedEmailCommand }
 */
const createBulkReminderEmailCommand = (users, templateName) => {
  return new SendBulkTemplatedEmailCommand({
    /**
     * Each 'Destination' uses a corresponding set of replacement data. We can map each user
     * to a 'Destination' and provide user specific replacement data to create personalized emails.
     *
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{name}},</h1><p>Don't forget about the party gifts!</p>
     * Destination 1: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     * Destination 2: <h1>Hello Frodo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destinations: users.map((user) => ({
      Destination: { ToAddresses: [user.emailAddress] },
      ReplacementTemplateData: JSON.stringify({ name: user.firstName }),
    })),
    DefaultTemplateData: JSON.stringify({ name: "Shireling" }),
    Source: VERIFIED_EMAIL_1,
    Template: templateName,
  });
};

const run = async () => {
  const sendBulkTemplateEmailCommand = createBulkReminderEmailCommand(
    USERS,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendBulkTemplateEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[SendBulkTemplatedEmail](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/SendBulkTemplatedEmailCommand)」を参照してください。

### `SendEmail`
<a name="ses_SendEmail_javascript_3_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { SendEmailCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createSendEmailCommand = (toAddress, fromAddress) => {
  return new SendEmailCommand({
    Destination: {
      /* required */
      CcAddresses: [
        /* more items */
      ],
      ToAddresses: [
        toAddress,
        /* more To-email addresses */
      ],
    },
    Message: {
      /* required */
      Body: {
        /* required */
        Html: {
          Charset: "UTF-8",
          Data: "HTML_FORMAT_BODY",
        },
        Text: {
          Charset: "UTF-8",
          Data: "TEXT_FORMAT_BODY",
        },
      },
      Subject: {
        Charset: "UTF-8",
        Data: "EMAIL_SUBJECT",
      },
    },
    Source: fromAddress,
    ReplyToAddresses: [
      /* more items */
    ],
  });
};

const run = async () => {
  const sendEmailCommand = createSendEmailCommand(
    "recipient@example.com",
    "sender@example.com",
  );

  try {
    return await sesClient.send(sendEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[SendEmail](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/SendEmailCommand)」を参照してください。

### `SendRawEmail`
<a name="ses_SendRawEmail_javascript_3_topic"></a>

次のコード例は、`SendRawEmail` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。
[nodemailer](https://nodemailer.com/transports/ses) を使用して、添付ファイル付きの E メールを送信します。  

```
import sesClientModule from "@aws-sdk/client-ses";
/**
 * nodemailer wraps the SES SDK and calls SendRawEmail. Use this for more advanced
 * functionality like adding attachments to your email.
 *
 * https://nodemailer.com/transports/ses
 */
import nodemailer from "nodemailer";

/**
 * @param {string} from An Amazon SES verified email address.
 * @param {*} to An Amazon SES verified email address.
 */
export const sendEmailWithAttachments = (
  from = "from@example.com",
  to = "to@example.com",
) => {
  const ses = new sesClientModule.SESClient({});
  const transporter = nodemailer.createTransport({
    SES: { ses, aws: sesClientModule },
  });

  return new Promise((resolve, reject) => {
    transporter.sendMail(
      {
        from,
        to,
        subject: "Hello World",
        text: "Greetings from Amazon SES!",
        attachments: [{ content: "Hello World!", filename: "hello.txt" }],
      },
      (err, info) => {
        if (err) {
          reject(err);
        } else {
          resolve(info);
        }
      },
    );
  });
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[SendRawEmail](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/SendRawEmailCommand)」を参照してください。

### `SendTemplatedEmail`
<a name="ses_SendTemplatedEmail_javascript_3_topic"></a>

次のコード例は、`SendTemplatedEmail` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { SendTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL = postfix(getUniqueName("Bilbo"), "@example.com");

const USER = { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL };

/**
 *
 * @param { { emailAddress: string, firstName: string } } user
 * @param { string } templateName - The name of an existing template in Amazon SES.
 * @returns { SendTemplatedEmailCommand }
 */
const createReminderEmailCommand = (user, templateName) => {
  return new SendTemplatedEmailCommand({
    /**
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{contact.firstName}},</h1><p>Don't forget about the party gifts!</p>
     * Destination: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destination: { ToAddresses: [user.emailAddress] },
    TemplateData: JSON.stringify({ contact: { firstName: user.firstName } }),
    Source: VERIFIED_EMAIL,
    Template: templateName,
  });
};

const run = async () => {
  const sendReminderEmailCommand = createReminderEmailCommand(
    USER,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendReminderEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[SendTemplatedEmail](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/SendTemplatedEmailCommand)」を参照してください。

### `UpdateTemplate`
<a name="ses_UpdateTemplate_javascript_3_topic"></a>

次のコード例は、`UpdateTemplate` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { UpdateTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");
const HTML_PART = "<h1>Hello, World!</h1>";

const createUpdateTemplateCommand = () => {
  return new UpdateTemplateCommand({
    Template: {
      TemplateName: TEMPLATE_NAME,
      HtmlPart: HTML_PART,
      SubjectPart: "Example",
      TextPart: "Updated template text.",
    },
  });
};

const run = async () => {
  const updateTemplateCommand = createUpdateTemplateCommand();

  try {
    return await sesClient.send(updateTemplateCommand);
  } catch (err) {
    console.log("Failed to update template.", err);
    return err;
  }
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[UpdateTemplate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/UpdateTemplateCommand)」を参照してください。

### `VerifyDomainIdentity`
<a name="ses_VerifyDomainIdentity_javascript_3_topic"></a>

次のコード例は、`VerifyDomainIdentity` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import { VerifyDomainIdentityCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * You must have access to the domain's DNS settings to complete the
 * domain verification process.
 */
const DOMAIN_NAME = postfix(getUniqueName("Domain"), ".example.com");

const createVerifyDomainIdentityCommand = () => {
  return new VerifyDomainIdentityCommand({ Domain: DOMAIN_NAME });
};

const run = async () => {
  const VerifyDomainIdentityCommand = createVerifyDomainIdentityCommand();

  try {
    return await sesClient.send(VerifyDomainIdentityCommand);
  } catch (err) {
    console.log("Failed to verify domain.", err);
    return err;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[VerifyDomainIdentity](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/VerifyDomainIdentityCommand)」を参照してください。

### `VerifyEmailIdentity`
<a name="ses_VerifyEmailIdentity_javascript_3_topic"></a>

次のコード例は、`VerifyEmailIdentity` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
// Import required AWS SDK clients and commands for Node.js
import { VerifyEmailIdentityCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const EMAIL_ADDRESS = "name@example.com";

const createVerifyEmailIdentityCommand = (emailAddress) => {
  return new VerifyEmailIdentityCommand({ EmailAddress: emailAddress });
};

const run = async () => {
  const verifyEmailIdentityCommand =
    createVerifyEmailIdentityCommand(EMAIL_ADDRESS);
  try {
    return await sesClient.send(verifyEmailIdentityCommand);
  } catch (err) {
    console.log("Failed to verify email identity.", err);
    return err;
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[VerifyEmailIdentity](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ses/command/VerifyEmailIdentityCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Transcribe ストリーミングアプリケーションを構築する
<a name="cross_TranscriptionStreamingApp_javascript_3_topic"></a>

次のコード例は、ライブ音声をリアルタイムで記録、転写、翻訳し、結果を E メールで送信するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 Amazon Transcribe を使用して、ライブ音声をリアルタイムで記録、転写、翻訳し、Amazon Simple Email Service (Amazon SES) を使用して結果を E メールで送信するアプリケーションを構築する方法について説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/transcribe-streaming-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SES
+ Amazon Transcribe
+ Amazon Translate

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_javascript_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS SDK for JavaScript (v3) を使用して Amazon Aurora データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して Express Node.js バックエンドと対話します。  
+ React.js ウェブアプリケーションを と統合します AWS のサービス。
+ Aurora テーブルの項目を一覧表示、追加、更新します。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/aurora-serverless-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_javascript_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 で Amazon Rekognition を使用して、Amazon Rekognition を使用して Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内のオブジェクトをカテゴリ別に識別するアプリケーション AWS SDK for JavaScript を作成する方法を示します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
以下ではその方法を説明しています。  
+ Amazon Cognito を使用して認証されていないユーザーを作成します。
+ Amazon Rekognition を使用して、オブジェクトのイメージを分析します。
+ Amazon SES の E メールアドレスを検証します。
+ Amazon SES を使用して、E メール通知を送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo_analyzer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

# SDK for JavaScript (v3) を使用した Amazon SNS の例
<a name="javascript_3_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SNS
<a name="sns_Hello_javascript_3_topic"></a>

次のコード例は、Amazon SNS の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
SNS クライアントを初期化し、アカウントのトピックを一覧表示します。  

```
import { SNSClient, paginateListTopics } from "@aws-sdk/client-sns";

export const helloSns = async () => {
  // The configuration object (`{}`) is required. If the region and credentials
  // are omitted, the SDK uses your local configuration if it exists.
  const client = new SNSClient({});

  // You can also use `ListTopicsCommand`, but to use that command you must
  // handle the pagination yourself. You can do that by sending the `ListTopicsCommand`
  // with the `NextToken` parameter from the previous request.
  const paginatedTopics = paginateListTopics({ client }, {});
  const topics = [];

  for await (const page of paginatedTopics) {
    if (page.Topics?.length) {
      topics.push(...page.Topics);
    }
  }

  const suffix = topics.length === 1 ? "" : "s";

  console.log(
    `Hello, Amazon SNS! You have ${topics.length} topic${suffix} in your account.`,
  );
  console.log(topics.map((t) => `  * ${t.TopicArn}`).join("\n"));
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[ListTopics](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/ListTopicsCommand)」を参照してください。

## アクション
<a name="actions"></a>

### `CheckIfPhoneNumberIsOptedOut`
<a name="sns_CheckIfPhoneNumberIsOptedOut_javascript_3_topic"></a>

次のコード例は、`CheckIfPhoneNumberIsOptedOut` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns";

import { snsClient } from "../libs/snsClient.js";

export const checkIfPhoneNumberIsOptedOut = async (
  phoneNumber = "5555555555",
) => {
  const command = new CheckIfPhoneNumberIsOptedOutCommand({
    phoneNumber,
  });

  const response = await snsClient.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   isOptedOut: false
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-sending-sms.html#sending-sms-checkifphonenumberisoptedout)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CheckIfPhoneNumberIsOptedOut](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CheckIfPhoneNumberIsOptedOutCommand)」を参照してください。

### `ConfirmSubscription`
<a name="sns_ConfirmSubscription_javascript_3_topic"></a>

次のコード例は、`ConfirmSubscription` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { ConfirmSubscriptionCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} token - This token is sent the subscriber. Only subscribers
 *                         that are not AWS services (HTTP/S, email) need to be confirmed.
 * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription.
 */
export const confirmSubscription = async (
  token = "TOKEN",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    // A subscription only needs to be confirmed if the endpoint type is
    // HTTP/S, email, or in another AWS account.
    new ConfirmSubscriptionCommand({
      Token: token,
      TopicArn: topicArn,
      // If this is true, the subscriber cannot unsubscribe while unauthenticated.
      AuthenticateOnUnsubscribe: "false",
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '4bb5bce9-805a-5517-8333-e1d2cface90b',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-sending-sms.html#sending-sms-getattributes)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ConfirmSubscription](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/ConfirmSubscriptionCommand)」を参照してください。

### `CreateTopic`
<a name="sns_CreateTopic_javascript_3_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-createtopic)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの**「[CreateTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_javascript_3_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { DeleteTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic to delete.
 */
export const deleteTopic = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new DeleteTopicCommand({ TopicArn: topicArn }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'a10e2886-5a8f-5114-af36-75bd39498332',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-deletetopic)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/DeleteTopicCommand)」を参照してください。

### `GetSMSAttributes`
<a name="sns_GetSMSAttributes_javascript_3_topic"></a>

次のコード例は、`GetSMSAttributes` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { GetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const getSmsAttributes = async () => {
  const response = await snsClient.send(
    // If you have not modified the account-level mobile settings of SNS,
    // the DefaultSMSType is undefined. For this example, it was set to
    // Transactional.
    new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   attributes: { DefaultSMSType: 'Transactional' }
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-subscribing-unubscribing-topics.html#sns-confirm-subscription-email)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetSMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/GetSMSAttributesCommand)」を参照してください。

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_javascript_3_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { GetTopicAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic to retrieve attributes for.
 */
export const getTopicAttributes = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new GetTopicAttributesCommand({
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '36b6a24e-5473-5d4e-ac32-ff72d9a73d94',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Attributes: {
  //     Policy: '{...}',
  //     Owner: 'xxxxxxxxxxxx',
  //     SubscriptionsPending: '1',
  //     TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic',
  //     TracingConfig: 'PassThrough',
  //     EffectiveDeliveryPolicy: '{"http":{"defaultHealthyRetryPolicy":{"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0,"numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false,"defaultRequestPolicy":{"headerContentType":"text/plain; charset=UTF-8"}}}',
  //     SubscriptionsConfirmed: '0',
  //     DisplayName: '',
  //     SubscriptionsDeleted: '1'
  //   }
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topicsgetttopicattributes)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetTopicAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/GetTopicAttributesCommand)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_javascript_3_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { ListSubscriptionsByTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic for which you wish to list subscriptions.
 */
export const listSubscriptionsByTopic = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new ListSubscriptionsByTopicCommand({ TopicArn: topicArn }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '0934fedf-0c4b-572e-9ed2-a3e38fadb0c8',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Subscriptions: [
  //     {
  //       SubscriptionArn: 'PendingConfirmation',
  //       Owner: '901487484989',
  //       Protocol: 'email',
  //       Endpoint: 'corepyle@amazon.com',
  //       TopicArn: 'arn:aws:sns:us-east-1:901487484989:mytopic'
  //     }
  //   ]
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topicsgetttopicattributes)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[ListSubscriptions](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/ListSubscriptionsCommand)」を参照してください。**

### `ListTopics`
<a name="sns_ListTopics_javascript_3_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { ListTopicsCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const listTopics = async () => {
  const response = await snsClient.send(new ListTopicsCommand({}));
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '936bc5ad-83ca-53c2-b0b7-9891167b909e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Topics: [ { TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic' } ]
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-listtopics)」を参照してください。
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[ListTopics](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/ListTopicsCommand)」を参照してください。

### `Publish`
<a name="sns_Publish_javascript_3_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {string} topicArn - The ARN of the topic to which you would like to publish.
 */
export const publish = async (
  message = "Hello from SNS!",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```
グループ、重複、属性のオプションを指定してトピックにメッセージを発行します。  

```
  async publishMessages() {
    const message = await this.prompter.input({
      message: MESSAGES.publishMessagePrompt,
    });

    let groupId;
    let deduplicationId;
    let choices;

    if (this.isFifo) {
      await this.logger.log(MESSAGES.groupIdNotice);
      groupId = await this.prompter.input({
        message: MESSAGES.groupIdPrompt,
      });

      if (this.autoDedup === false) {
        await this.logger.log(MESSAGES.deduplicationIdNotice);
        deduplicationId = await this.prompter.input({
          message: MESSAGES.deduplicationIdPrompt,
        });
      }

      choices = await this.prompter.checkbox({
        message: MESSAGES.messageAttributesPrompt,
        choices: toneChoices,
      });
    }

    await this.snsClient.send(
      new PublishCommand({
        TopicArn: this.topicArn,
        Message: message,
        ...(groupId
          ? {
              MessageGroupId: groupId,
            }
          : {}),
        ...(deduplicationId
          ? {
              MessageDeduplicationId: deduplicationId,
            }
          : {}),
        ...(choices
          ? {
              MessageAttributes: {
                tone: {
                  DataType: "String.Array",
                  StringValue: JSON.stringify(choices),
                },
              },
            }
          : {}),
      }),
    );

    const publishAnother = await this.prompter.confirm({
      message: MESSAGES.publishAnother,
    });

    if (publishAnother) {
      await this.publishMessages();
    }
  }
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-publishing-messages.html)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[Publish](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/PublishCommand)」を参照してください。**

### `SetSMSAttributes`
<a name="sns_SetSMSAttributes_javascript_3_topic"></a>

次のコード例は、`SetSMSAttributes` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { SetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {"Transactional" | "Promotional"} defaultSmsType
 */
export const setSmsType = async (defaultSmsType = "Transactional") => {
  const response = await snsClient.send(
    new SetSMSAttributesCommand({
      attributes: {
        // Promotional – (Default) Noncritical messages, such as marketing messages.
        // Transactional – Critical messages that support customer transactions,
        // such as one-time passcodes for multi-factor authentication.
        DefaultSMSType: defaultSmsType,
      },
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '1885b977-2d7e-535e-8214-e44be727e265',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-sending-sms.html#sending-sms-setattributes)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SetSMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/SetSMSAttributesCommand)」を参照してください。

### `SetTopicAttributes`
<a name="sns_SetTopicAttributes_javascript_3_topic"></a>

次のコード例は、`SetTopicAttributes` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { SetTopicAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const setTopicAttributes = async (
  topicArn = "TOPIC_ARN",
  attributeName = "DisplayName",
  attributeValue = "Test Topic",
) => {
  const response = await snsClient.send(
    new SetTopicAttributesCommand({
      AttributeName: attributeName,
      AttributeValue: attributeValue,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topicsstttopicattributes)」を参照してください。
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[SetTopicAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/SetTopicAttributesCommand)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_javascript_3_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { SubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription.
 * @param {string} emailAddress - The email address that is subscribed to the topic.
 */
export const subscribeEmail = async (
  topicArn = "TOPIC_ARN",
  emailAddress = "usern@me.com",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "email",
      TopicArn: topicArn,
      Endpoint: emailAddress,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
};
```
モバイルアプリケーションをトピックにサブスクライブします。  

```
import { SubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to.
 * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created
 *                            when an application registers for notifications.
 */
export const subscribeApp = async (
  topicArn = "TOPIC_ARN",
  endpoint = "ENDPOINT",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "application",
      TopicArn: topicArn,
      Endpoint: endpoint,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
  return response;
};
```
Lambda 関数をトピックにサブスクライブします。  

```
import { SubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to.
 * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function.
 */
export const subscribeLambda = async (
  topicArn = "TOPIC_ARN",
  endpoint = "ENDPOINT",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "lambda",
      TopicArn: topicArn,
      Endpoint: endpoint,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
  return response;
};
```
SQS キューをトピックにサブスクライブします。  

```
import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns";

const client = new SNSClient({});

export const subscribeQueue = async (
  topicArn = "TOPIC_ARN",
  queueArn = "QUEUE_ARN",
) => {
  const command = new SubscribeCommand({
    TopicArn: topicArn,
    Protocol: "sqs",
    Endpoint: queueArn,
  });

  const response = await client.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```
トピックにフィルターでサブスクライブします。  

```
import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns";

const client = new SNSClient({});

export const subscribeQueueFiltered = async (
  topicArn = "TOPIC_ARN",
  queueArn = "QUEUE_ARN",
) => {
  const command = new SubscribeCommand({
    TopicArn: topicArn,
    Protocol: "sqs",
    Endpoint: queueArn,
    Attributes: {
      // This subscription will only receive messages with the 'event' attribute set to 'order_placed'.
      FilterPolicyScope: "MessageAttributes",
      FilterPolicy: JSON.stringify({
        event: ["order_placed"],
      }),
    },
  });

  const response = await client.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-subscribing-email)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[Subscribe](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/SubscribeCommand)」を参照してください。**

### `Unsubscribe`
<a name="sns_Unsubscribe_javascript_3_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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 { UnsubscribeCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} subscriptionArn - The ARN of the subscription to cancel.
 */
const unsubscribe = async (
  subscriptionArn = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
) => {
  const response = await snsClient.send(
    new UnsubscribeCommand({
      SubscriptionArn: subscriptionArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '0178259a-9204-507c-b620-78a7570a44c6',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-unsubscribing)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[Unsubscribe](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/UnsubscribeCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DynamoDB テーブルにデータを送信するアプリケーションを構築する
<a name="cross_SubmitDataApp_javascript_3_topic"></a>

次のコード例は、Amazon DynamoDB テーブルにデータを送信し、ユーザーがテーブルを更新したときに通知するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 この例では、ユーザーが Amazon DynamoDB テーブルにデータを送信し、Amazon Simple Notification Service (Amazon SNS) を使用して管理者にテキストメッセージを送信できるようにするアプリを構築する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/submit-data-app) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/cross-service-example-submitting-data.html)でも使用できます。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SNS

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_javascript_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for JavaScript (v3)**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/photo-asset-manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_javascript_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for JavaScript (v3)**  
 を使用して、Amazon Textract を使用してドキュメントイメージからデータを抽出し、インタラクティブなウェブページに表示する React アプリケーション AWS SDK for JavaScript を構築する方法を示します。この例はウェブブラウザで実行され、認証情報に認証された Amazon Cognito ID が必要です。Amazon Simple Storage Service (Amazon S3) をストレージに使用し、通知のために、Amazon Simple Notification Service (Amazon SNS) トピックにサブスクライブした Amazon Simple Queue Service (Amazon SQS) キューをポーリングします。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/textract-react) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-topics-queues#code-examples)での設定と実行の方法を確認してください。
これがこのシナリオのエントリーポイントです。  

```
import { SNSClient } from "@aws-sdk/client-sns";
import { SQSClient } from "@aws-sdk/client-sqs";

import { TopicsQueuesWkflw } from "./TopicsQueuesWkflw.js";
import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js";

export const startSnsWorkflow = () => {
  const snsClient = new SNSClient({});
  const sqsClient = new SQSClient({});
  const prompter = new Prompter();
  const logger = console;

  const wkflw = new TopicsQueuesWkflw(snsClient, sqsClient, prompter, logger);

  wkflw.start();
};
```
上記のコードにより必要な依存関係が提供され、シナリオが開始されます。次のセクションには、この例の大部分が含まれています。  

```
const toneChoices = [
  { name: "cheerful", value: "cheerful" },
  { name: "funny", value: "funny" },
  { name: "serious", value: "serious" },
  { name: "sincere", value: "sincere" },
];

export class TopicsQueuesWkflw {
  // SNS topic is configured as First-In-First-Out
  isFifo = true;

  // Automatic content-based deduplication is enabled.
  autoDedup = false;

  snsClient;
  sqsClient;
  topicName;
  topicArn;
  subscriptionArns = [];
  /**
   * @type {{ queueName: string, queueArn: string, queueUrl: string, policy?: string }[]}
   */
  queues = [];
  prompter;

  /**
   * @param {import('@aws-sdk/client-sns').SNSClient} snsClient
   * @param {import('@aws-sdk/client-sqs').SQSClient} sqsClient
   * @param {import('../../libs/prompter.js').Prompter} prompter
   * @param {import('../../libs/logger.js').Logger} logger
   */
  constructor(snsClient, sqsClient, prompter, logger) {
    this.snsClient = snsClient;
    this.sqsClient = sqsClient;
    this.prompter = prompter;
    this.logger = logger;
  }

  async welcome() {
    await this.logger.log(MESSAGES.description);
  }

  async confirmFifo() {
    await this.logger.log(MESSAGES.snsFifoDescription);
    this.isFifo = await this.prompter.confirm({
      message: MESSAGES.snsFifoPrompt,
    });

    if (this.isFifo) {
      this.logger.logSeparator(MESSAGES.headerDedup);
      await this.logger.log(MESSAGES.deduplicationNotice);
      await this.logger.log(MESSAGES.deduplicationDescription);
      this.autoDedup = await this.prompter.confirm({
        message: MESSAGES.deduplicationPrompt,
      });
    }
  }

  async createTopic() {
    await this.logger.log(MESSAGES.creatingTopics);
    this.topicName = await this.prompter.input({
      message: MESSAGES.topicNamePrompt,
    });
    if (this.isFifo) {
      this.topicName += ".fifo";
      this.logger.logSeparator(MESSAGES.headerFifoNaming);
      await this.logger.log(MESSAGES.appendFifoNotice);
    }

    const response = await this.snsClient.send(
      new CreateTopicCommand({
        Name: this.topicName,
        Attributes: {
          FifoTopic: this.isFifo ? "true" : "false",
          ...(this.autoDedup ? { ContentBasedDeduplication: "true" } : {}),
        },
      }),
    );

    this.topicArn = response.TopicArn;

    await this.logger.log(
      MESSAGES.topicCreatedNotice
        .replace("${TOPIC_NAME}", this.topicName)
        .replace("${TOPIC_ARN}", this.topicArn),
    );
  }

  async createQueues() {
    await this.logger.log(MESSAGES.createQueuesNotice);
    // Increase this number to add more queues.
    const maxQueues = 2;

    for (let i = 0; i < maxQueues; i++) {
      await this.logger.log(MESSAGES.queueCount.replace("${COUNT}", i + 1));
      let queueName = await this.prompter.input({
        message: MESSAGES.queueNamePrompt.replace(
          "${EXAMPLE_NAME}",
          i === 0 ? "good-news" : "bad-news",
        ),
      });

      if (this.isFifo) {
        queueName += ".fifo";
        await this.logger.log(MESSAGES.appendFifoNotice);
      }

      const response = await this.sqsClient.send(
        new CreateQueueCommand({
          QueueName: queueName,
          Attributes: { ...(this.isFifo ? { FifoQueue: "true" } : {}) },
        }),
      );

      const { Attributes } = await this.sqsClient.send(
        new GetQueueAttributesCommand({
          QueueUrl: response.QueueUrl,
          AttributeNames: ["QueueArn"],
        }),
      );

      this.queues.push({
        queueName,
        queueArn: Attributes.QueueArn,
        queueUrl: response.QueueUrl,
      });

      await this.logger.log(
        MESSAGES.queueCreatedNotice
          .replace("${QUEUE_NAME}", queueName)
          .replace("${QUEUE_URL}", response.QueueUrl)
          .replace("${QUEUE_ARN}", Attributes.QueueArn),
      );
    }
  }

  async attachQueueIamPolicies() {
    for (const [index, queue] of this.queues.entries()) {
      const policy = JSON.stringify(
        {
          Statement: [
            {
              Effect: "Allow",
              Principal: {
                Service: "sns.amazonaws.com",
              },
              Action: "sqs:SendMessage",
              Resource: queue.queueArn,
              Condition: {
                ArnEquals: {
                  "aws:SourceArn": this.topicArn,
                },
              },
            },
          ],
        },
        null,
        2,
      );

      if (index !== 0) {
        this.logger.logSeparator();
      }

      await this.logger.log(MESSAGES.attachPolicyNotice);
      console.log(policy);
      const addPolicy = await this.prompter.confirm({
        message: MESSAGES.addPolicyConfirmation.replace(
          "${QUEUE_NAME}",
          queue.queueName,
        ),
      });

      if (addPolicy) {
        await this.sqsClient.send(
          new SetQueueAttributesCommand({
            QueueUrl: queue.queueUrl,
            Attributes: {
              Policy: policy,
            },
          }),
        );
        queue.policy = policy;
      } else {
        await this.logger.log(
          MESSAGES.policyNotAttachedNotice.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
        );
      }
    }
  }

  async subscribeQueuesToTopic() {
    for (const [index, queue] of this.queues.entries()) {
      /**
       * @type {import('@aws-sdk/client-sns').SubscribeCommandInput}
       */
      const subscribeParams = {
        TopicArn: this.topicArn,
        Protocol: "sqs",
        Endpoint: queue.queueArn,
      };
      let tones = [];

      if (this.isFifo) {
        if (index === 0) {
          await this.logger.log(MESSAGES.fifoFilterNotice);
        }
        tones = await this.prompter.checkbox({
          message: MESSAGES.fifoFilterSelect.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
          choices: toneChoices,
        });

        if (tones.length) {
          subscribeParams.Attributes = {
            FilterPolicyScope: "MessageAttributes",
            FilterPolicy: JSON.stringify({
              tone: tones,
            }),
          };
        }
      }

      const { SubscriptionArn } = await this.snsClient.send(
        new SubscribeCommand(subscribeParams),
      );

      this.subscriptionArns.push(SubscriptionArn);

      await this.logger.log(
        MESSAGES.queueSubscribedNotice
          .replace("${QUEUE_NAME}", queue.queueName)
          .replace("${TOPIC_NAME}", this.topicName)
          .replace("${TONES}", tones.length ? tones.join(", ") : "none"),
      );
    }
  }

  async publishMessages() {
    const message = await this.prompter.input({
      message: MESSAGES.publishMessagePrompt,
    });

    let groupId;
    let deduplicationId;
    let choices;

    if (this.isFifo) {
      await this.logger.log(MESSAGES.groupIdNotice);
      groupId = await this.prompter.input({
        message: MESSAGES.groupIdPrompt,
      });

      if (this.autoDedup === false) {
        await this.logger.log(MESSAGES.deduplicationIdNotice);
        deduplicationId = await this.prompter.input({
          message: MESSAGES.deduplicationIdPrompt,
        });
      }

      choices = await this.prompter.checkbox({
        message: MESSAGES.messageAttributesPrompt,
        choices: toneChoices,
      });
    }

    await this.snsClient.send(
      new PublishCommand({
        TopicArn: this.topicArn,
        Message: message,
        ...(groupId
          ? {
              MessageGroupId: groupId,
            }
          : {}),
        ...(deduplicationId
          ? {
              MessageDeduplicationId: deduplicationId,
            }
          : {}),
        ...(choices
          ? {
              MessageAttributes: {
                tone: {
                  DataType: "String.Array",
                  StringValue: JSON.stringify(choices),
                },
              },
            }
          : {}),
      }),
    );

    const publishAnother = await this.prompter.confirm({
      message: MESSAGES.publishAnother,
    });

    if (publishAnother) {
      await this.publishMessages();
    }
  }

  async receiveAndDeleteMessages() {
    for (const queue of this.queues) {
      const { Messages } = await this.sqsClient.send(
        new ReceiveMessageCommand({
          QueueUrl: queue.queueUrl,
        }),
      );

      if (Messages) {
        await this.logger.log(
          MESSAGES.messagesReceivedNotice.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
        );
        console.log(Messages);

        await this.sqsClient.send(
          new DeleteMessageBatchCommand({
            QueueUrl: queue.queueUrl,
            Entries: Messages.map((message) => ({
              Id: message.MessageId,
              ReceiptHandle: message.ReceiptHandle,
            })),
          }),
        );
      } else {
        await this.logger.log(
          MESSAGES.noMessagesReceivedNotice.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
        );
      }
    }

    const deleteAndPoll = await this.prompter.confirm({
      message: MESSAGES.deleteAndPollConfirmation,
    });

    if (deleteAndPoll) {
      await this.receiveAndDeleteMessages();
    }
  }

  async destroyResources() {
    for (const subscriptionArn of this.subscriptionArns) {
      await this.snsClient.send(
        new UnsubscribeCommand({ SubscriptionArn: subscriptionArn }),
      );
    }

    for (const queue of this.queues) {
      await this.sqsClient.send(
        new DeleteQueueCommand({ QueueUrl: queue.queueUrl }),
      );
    }

    if (this.topicArn) {
      await this.snsClient.send(
        new DeleteTopicCommand({ TopicArn: this.topicArn }),
      );
    }
  }

  async start() {
    console.clear();

    try {
      this.logger.logSeparator(MESSAGES.headerWelcome);
      await this.welcome();
      this.logger.logSeparator(MESSAGES.headerFifo);
      await this.confirmFifo();
      this.logger.logSeparator(MESSAGES.headerCreateTopic);
      await this.createTopic();
      this.logger.logSeparator(MESSAGES.headerCreateQueues);
      await this.createQueues();
      this.logger.logSeparator(MESSAGES.headerAttachPolicy);
      await this.attachQueueIamPolicies();
      this.logger.logSeparator(MESSAGES.headerSubscribeQueues);
      await this.subscribeQueuesToTopic();
      this.logger.logSeparator(MESSAGES.headerPublishMessage);
      await this.publishMessages();
      this.logger.logSeparator(MESSAGES.headerReceiveMessages);
      await this.receiveAndDeleteMessages();
    } catch (err) {
      console.error(err);
    } finally {
      await this.destroyResources();
    }
  }
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/CreateQueueCommand)
  + [CreateTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/DeleteMessageBatchCommand)
  + [DeleteQueue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/DeleteQueueCommand)
  + [DeleteTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/DeleteTopicCommand)
  + [GetQueueAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/GetQueueAttributesCommand)
  + [Publish](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/PublishCommand)
  + [ReceiveMessage](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/ReceiveMessageCommand)
  + [SetQueueAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/SetQueueAttributesCommand)
  + [Subscribe](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/SubscribeCommand)
  + [Unsubscribe](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/UnsubscribeCommand)

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_javascript_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 Lambda JavaScript ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-api-gateway) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/api-gateway-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_javascript_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for JavaScript (v3)**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda JavaScript ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events) で完全な例を参照してください。  
この例は、[AWS SDK for JavaScript v3 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html)でも使用できます。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_javascript_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-sns-to-lambda)リポジトリで完全な例を検索し、設定および実行する方法を確認してください。
JavaScript を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const record of event.Records) {
    await processMessageAsync(record);
  }
  console.info("done");
};

async function processMessageAsync(record) {
  try {
    const message = JSON.stringify(record.Sns.Message);
    console.log(`Processed message ${message}`);
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```
TypeScript を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { SNSEvent, Context, SNSHandler, SNSEventRecord } from "aws-lambda";

export const functionHandler: SNSHandler = async (
  event: SNSEvent,
  context: Context
): Promise<void> => {
  for (const record of event.Records) {
    await processMessageAsync(record);
  }
  console.info("done");
};

async function processMessageAsync(record: SNSEventRecord): Promise<any> {
  try {
    const message: string = JSON.stringify(record.Sns.Message);
    console.log(`Processed message ${message}`);
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```

# SDK for JavaScript (v3) を使用した Amazon SQS の例
<a name="javascript_3_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SQS
<a name="sqs_Hello_javascript_3_topic"></a>

次のコード例は、Amazon SQS の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS クライアントを初期化し、キューを一覧表示します。  

```
import { SQSClient, paginateListQueues } from "@aws-sdk/client-sqs";

export const helloSqs = async () => {
  // The configuration object (`{}`) is required. If the region and credentials
  // are omitted, the SDK uses your local configuration if it exists.
  const client = new SQSClient({});

  // You can also use `ListQueuesCommand`, but to use that command you must
  // handle the pagination yourself. You can do that by sending the `ListQueuesCommand`
  // with the `NextToken` parameter from the previous request.
  const paginatedQueues = paginateListQueues({ client }, {});
  const queues = [];

  for await (const page of paginatedQueues) {
    if (page.QueueUrls?.length) {
      queues.push(...page.QueueUrls);
    }
  }

  const suffix = queues.length === 1 ? "" : "s";

  console.log(
    `Hello, Amazon SQS! You have ${queues.length} queue${suffix} in your account.`,
  );
  console.log(queues.map((t) => `  * ${t}`).join("\n"));
};
```
+  API の詳細については、**「AWS SDK for JavaScript API リファレンス」の「[ListQueues](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/ListQueuesCommand)」を参照してください。

## アクション
<a name="actions"></a>

### `ChangeMessageVisibility`
<a name="sqs_ChangeMessageVisibility_javascript_3_topic"></a>

次のコード例は、`ChangeMessageVisibility` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS メッセージを受信し、可視性タイムアウトを変更します。  

```
import {
  ReceiveMessageCommand,
  ChangeMessageVisibilityCommand,
  SQSClient,
} from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue_url";

const receiveMessage = (queueUrl) =>
  client.send(
    new ReceiveMessageCommand({
      AttributeNames: ["SentTimestamp"],
      MaxNumberOfMessages: 1,
      MessageAttributeNames: ["All"],
      QueueUrl: queueUrl,
      WaitTimeSeconds: 1,
    }),
  );

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const { Messages } = await receiveMessage(queueUrl);

  const response = await client.send(
    new ChangeMessageVisibilityCommand({
      QueueUrl: queueUrl,
      ReceiptHandle: Messages[0].ReceiptHandle,
      VisibilityTimeout: 20,
    }),
  );
  console.log(response);
  return response;
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[ChangeMessageVisibility](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/ChangeMessageVisibilityCommand)」を参照してください。

### `CreateQueue`
<a name="sqs_CreateQueue_javascript_3_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS 標準キューを作成します。  

```
import { CreateQueueCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_NAME = "test-queue";

export const main = async (sqsQueueName = SQS_QUEUE_NAME) => {
  const command = new CreateQueueCommand({
    QueueName: sqsQueueName,
    Attributes: {
      DelaySeconds: "60",
      MessageRetentionPeriod: "86400",
    },
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
ロングポーリングでキューを作成します。  

```
import { CreateQueueCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_NAME = "queue_name";

export const main = async (queueName = SQS_QUEUE_NAME) => {
  const response = await client.send(
    new CreateQueueCommand({
      QueueName: queueName,
      Attributes: {
        // When the wait time for the ReceiveMessage API action is greater than 0,
        // long polling is in effect. The maximum long polling wait time is 20
        // seconds. Long polling helps reduce the cost of using Amazon SQS by,
        // eliminating the number of empty responses and false empty responses.
        // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html
        ReceiveMessageWaitTimeSeconds: "20",
      },
    }),
  );
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-create-queue)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateQueue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/CreateQueueCommand)」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_javascript_3_topic"></a>

次のコード例は、`DeleteMessage` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS メッセージを受信および削除します。  

```
import {
  ReceiveMessageCommand,
  DeleteMessageCommand,
  SQSClient,
  DeleteMessageBatchCommand,
} from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue_url";

const receiveMessage = (queueUrl) =>
  client.send(
    new ReceiveMessageCommand({
      AttributeNames: ["SentTimestamp"],
      MaxNumberOfMessages: 10,
      MessageAttributeNames: ["All"],
      QueueUrl: queueUrl,
      WaitTimeSeconds: 20,
      VisibilityTimeout: 20,
    }),
  );

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const { Messages } = await receiveMessage(queueUrl);

  if (!Messages) {
    return;
  }

  if (Messages.length === 1) {
    console.log(Messages[0].Body);
    await client.send(
      new DeleteMessageCommand({
        QueueUrl: queueUrl,
        ReceiptHandle: Messages[0].ReceiptHandle,
      }),
    );
  } else {
    await client.send(
      new DeleteMessageBatchCommand({
        QueueUrl: queueUrl,
        Entries: Messages.map((message) => ({
          Id: message.MessageId,
          ReceiptHandle: message.ReceiptHandle,
        })),
      }),
    );
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteMessage](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/DeleteMessageCommand)」を参照してください。

### `DeleteMessageBatch`
<a name="sqs_DeleteMessageBatch_javascript_3_topic"></a>

次のコード例は、`DeleteMessageBatch` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import {
  ReceiveMessageCommand,
  DeleteMessageCommand,
  SQSClient,
  DeleteMessageBatchCommand,
} from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue_url";

const receiveMessage = (queueUrl) =>
  client.send(
    new ReceiveMessageCommand({
      AttributeNames: ["SentTimestamp"],
      MaxNumberOfMessages: 10,
      MessageAttributeNames: ["All"],
      QueueUrl: queueUrl,
      WaitTimeSeconds: 20,
      VisibilityTimeout: 20,
    }),
  );

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const { Messages } = await receiveMessage(queueUrl);

  if (!Messages) {
    return;
  }

  if (Messages.length === 1) {
    console.log(Messages[0].Body);
    await client.send(
      new DeleteMessageCommand({
        QueueUrl: queueUrl,
        ReceiptHandle: Messages[0].ReceiptHandle,
      }),
    );
  } else {
    await client.send(
      new DeleteMessageBatchCommand({
        QueueUrl: queueUrl,
        Entries: Messages.map((message) => ({
          Id: message.MessageId,
          ReceiptHandle: message.ReceiptHandle,
        })),
      }),
    );
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteMessageBatch](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/DeleteMessageBatchCommand)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_javascript_3_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューを削除します。  

```
import { DeleteQueueCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "test-queue-url";

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const command = new DeleteQueueCommand({ QueueUrl: queueUrl });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-delete-queue)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteQueue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/DeleteQueueCommand)」を参照してください。

### `GetQueueAttributes`
<a name="sqs_GetQueueAttributes_javascript_3_topic"></a>

次のコード例は、`GetQueueAttributes` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import { GetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue-url";

export const getQueueAttributes = async (queueUrl = SQS_QUEUE_URL) => {
  const command = new GetQueueAttributesCommand({
    QueueUrl: queueUrl,
    AttributeNames: ["DelaySeconds"],
  });

  const response = await client.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '747a1192-c334-5682-a508-4cd5e8dc4e79',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Attributes: { DelaySeconds: '1' }
  // }
  return response;
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[GetQueueAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/GetQueueAttributesCommand)」を参照してください。

### `GetQueueUrl`
<a name="sqs_GetQueueUrl_javascript_3_topic"></a>

次のコード例は、`GetQueueUrl` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューの URL を取得します。  

```
import { GetQueueUrlCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_NAME = "test-queue";

export const main = async (queueName = SQS_QUEUE_NAME) => {
  const command = new GetQueueUrlCommand({ QueueName: queueName });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-get-queue-url)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[GetQueueUrl](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/GetQueueUrlCommand)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_javascript_3_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューを一覧表示します。  

```
import { paginateListQueues, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});

export const main = async () => {
  const paginatedListQueues = paginateListQueues({ client }, {});

  /** @type {string[]} */
  const urls = [];
  for await (const page of paginatedListQueues) {
    const nextUrls = page.QueueUrls?.filter((qurl) => !!qurl) || [];
    urls.push(...nextUrls);
    for (const url of urls) {
      console.log(url);
    }
  }

  return urls;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sqs-examples-using-queues.html#sqs-examples-using-queues-listing-queues)」を参照してください。
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ListQueues](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/ListQueuesCommand)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_javascript_3_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューからメッセージを受信します。  

```
import {
  ReceiveMessageCommand,
  DeleteMessageCommand,
  SQSClient,
  DeleteMessageBatchCommand,
} from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue_url";

const receiveMessage = (queueUrl) =>
  client.send(
    new ReceiveMessageCommand({
      AttributeNames: ["SentTimestamp"],
      MaxNumberOfMessages: 10,
      MessageAttributeNames: ["All"],
      QueueUrl: queueUrl,
      WaitTimeSeconds: 20,
      VisibilityTimeout: 20,
    }),
  );

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const { Messages } = await receiveMessage(queueUrl);

  if (!Messages) {
    return;
  }

  if (Messages.length === 1) {
    console.log(Messages[0].Body);
    await client.send(
      new DeleteMessageCommand({
        QueueUrl: queueUrl,
        ReceiptHandle: Messages[0].ReceiptHandle,
      }),
    );
  } else {
    await client.send(
      new DeleteMessageBatchCommand({
        QueueUrl: queueUrl,
        Entries: Messages.map((message) => ({
          Id: message.MessageId,
          ReceiptHandle: message.ReceiptHandle,
        })),
      }),
    );
  }
};
```
ロングポーリングサポートを使用して Amazon SQS キューからメッセージを受信します。  

```
import { ReceiveMessageCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue-url";

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const command = new ReceiveMessageCommand({
    AttributeNames: ["SentTimestamp"],
    MaxNumberOfMessages: 1,
    MessageAttributeNames: ["All"],
    QueueUrl: queueUrl,
    // The duration (in seconds) for which the call waits for a message
    // to arrive in the queue before returning. If a message is available,
    // the call returns sooner than WaitTimeSeconds. If no messages are
    // available and the wait time expires, the call returns successfully
    // with an empty list of messages.
    // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html#API_ReceiveMessage_RequestSyntax
    WaitTimeSeconds: 20,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、**AWS SDK for JavaScript API リファレンスの「[ReceiveMessage](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/ReceiveMessageCommand)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_javascript_3_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューにメッセージを送信します。  

```
import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue_url";

export const main = async (sqsQueueUrl = SQS_QUEUE_URL) => {
  const command = new SendMessageCommand({
    QueueUrl: sqsQueueUrl,
    DelaySeconds: 10,
    MessageAttributes: {
      Title: {
        DataType: "String",
        StringValue: "The Whistler",
      },
      Author: {
        DataType: "String",
        StringValue: "John Grisham",
      },
      WeeksOn: {
        DataType: "Number",
        StringValue: "6",
      },
    },
    MessageBody:
      "Information about current NY Times fiction bestseller for week of 12/11/2016.",
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sqs-examples-send-receive-messages.html#sqs-examples-send-receive-messages-sending)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[SendMessage](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/SendMessageCommand)」を参照してください。**

### `SetQueueAttributes`
<a name="sqs_SetQueueAttributes_javascript_3_topic"></a>

次のコード例は、`SetQueueAttributes` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue-url";

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const command = new SetQueueAttributesCommand({
    QueueUrl: queueUrl,
    Attributes: {
      DelaySeconds: "1",
    },
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
ロングポーリングを使用するように Amazon SQS キューを設定します。  

```
import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue_url";

export const main = async (queueUrl = SQS_QUEUE_URL) => {
  const command = new SetQueueAttributesCommand({
    Attributes: {
      ReceiveMessageWaitTimeSeconds: "20",
    },
    QueueUrl: queueUrl,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
デッドレターキューを設定します。  

```
import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs";

const client = new SQSClient({});
const SQS_QUEUE_URL = "queue_url";
const DEAD_LETTER_QUEUE_ARN = "dead_letter_queue_arn";

export const main = async (
  queueUrl = SQS_QUEUE_URL,
  deadLetterQueueArn = DEAD_LETTER_QUEUE_ARN,
) => {
  const command = new SetQueueAttributesCommand({
    Attributes: {
      RedrivePolicy: JSON.stringify({
        // Amazon SQS supports dead-letter queues (DLQ), which other
        // queues (source queues) can target for messages that can't
        // be processed (consumed) successfully.
        // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html
        deadLetterTargetArn: deadLetterQueueArn,
        maxReceiveCount: "10",
      }),
    },
    QueueUrl: queueUrl,
  });

  const response = await client.send(command);
  console.log(response);
  return response;
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SetQueueAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/SetQueueAttributesCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_javascript_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for JavaScript (v3)**  
 を使用して、Amazon Textract を使用してドキュメントイメージからデータを抽出し、インタラクティブなウェブページに表示する React アプリケーション AWS SDK for JavaScript を構築する方法を示します。この例はウェブブラウザで実行され、認証情報に認証された Amazon Cognito ID が必要です。Amazon Simple Storage Service (Amazon S3) をストレージに使用し、通知のために、Amazon Simple Notification Service (Amazon SNS) トピックにサブスクライブした Amazon Simple Queue Service (Amazon SQS) キューをポーリングします。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/textract-react) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/wkflw-topics-queues#code-examples)での設定と実行の方法を確認してください。
これがこのシナリオのエントリーポイントです。  

```
import { SNSClient } from "@aws-sdk/client-sns";
import { SQSClient } from "@aws-sdk/client-sqs";

import { TopicsQueuesWkflw } from "./TopicsQueuesWkflw.js";
import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js";

export const startSnsWorkflow = () => {
  const snsClient = new SNSClient({});
  const sqsClient = new SQSClient({});
  const prompter = new Prompter();
  const logger = console;

  const wkflw = new TopicsQueuesWkflw(snsClient, sqsClient, prompter, logger);

  wkflw.start();
};
```
上記のコードにより必要な依存関係が提供され、シナリオが開始されます。次のセクションには、この例の大部分が含まれています。  

```
const toneChoices = [
  { name: "cheerful", value: "cheerful" },
  { name: "funny", value: "funny" },
  { name: "serious", value: "serious" },
  { name: "sincere", value: "sincere" },
];

export class TopicsQueuesWkflw {
  // SNS topic is configured as First-In-First-Out
  isFifo = true;

  // Automatic content-based deduplication is enabled.
  autoDedup = false;

  snsClient;
  sqsClient;
  topicName;
  topicArn;
  subscriptionArns = [];
  /**
   * @type {{ queueName: string, queueArn: string, queueUrl: string, policy?: string }[]}
   */
  queues = [];
  prompter;

  /**
   * @param {import('@aws-sdk/client-sns').SNSClient} snsClient
   * @param {import('@aws-sdk/client-sqs').SQSClient} sqsClient
   * @param {import('../../libs/prompter.js').Prompter} prompter
   * @param {import('../../libs/logger.js').Logger} logger
   */
  constructor(snsClient, sqsClient, prompter, logger) {
    this.snsClient = snsClient;
    this.sqsClient = sqsClient;
    this.prompter = prompter;
    this.logger = logger;
  }

  async welcome() {
    await this.logger.log(MESSAGES.description);
  }

  async confirmFifo() {
    await this.logger.log(MESSAGES.snsFifoDescription);
    this.isFifo = await this.prompter.confirm({
      message: MESSAGES.snsFifoPrompt,
    });

    if (this.isFifo) {
      this.logger.logSeparator(MESSAGES.headerDedup);
      await this.logger.log(MESSAGES.deduplicationNotice);
      await this.logger.log(MESSAGES.deduplicationDescription);
      this.autoDedup = await this.prompter.confirm({
        message: MESSAGES.deduplicationPrompt,
      });
    }
  }

  async createTopic() {
    await this.logger.log(MESSAGES.creatingTopics);
    this.topicName = await this.prompter.input({
      message: MESSAGES.topicNamePrompt,
    });
    if (this.isFifo) {
      this.topicName += ".fifo";
      this.logger.logSeparator(MESSAGES.headerFifoNaming);
      await this.logger.log(MESSAGES.appendFifoNotice);
    }

    const response = await this.snsClient.send(
      new CreateTopicCommand({
        Name: this.topicName,
        Attributes: {
          FifoTopic: this.isFifo ? "true" : "false",
          ...(this.autoDedup ? { ContentBasedDeduplication: "true" } : {}),
        },
      }),
    );

    this.topicArn = response.TopicArn;

    await this.logger.log(
      MESSAGES.topicCreatedNotice
        .replace("${TOPIC_NAME}", this.topicName)
        .replace("${TOPIC_ARN}", this.topicArn),
    );
  }

  async createQueues() {
    await this.logger.log(MESSAGES.createQueuesNotice);
    // Increase this number to add more queues.
    const maxQueues = 2;

    for (let i = 0; i < maxQueues; i++) {
      await this.logger.log(MESSAGES.queueCount.replace("${COUNT}", i + 1));
      let queueName = await this.prompter.input({
        message: MESSAGES.queueNamePrompt.replace(
          "${EXAMPLE_NAME}",
          i === 0 ? "good-news" : "bad-news",
        ),
      });

      if (this.isFifo) {
        queueName += ".fifo";
        await this.logger.log(MESSAGES.appendFifoNotice);
      }

      const response = await this.sqsClient.send(
        new CreateQueueCommand({
          QueueName: queueName,
          Attributes: { ...(this.isFifo ? { FifoQueue: "true" } : {}) },
        }),
      );

      const { Attributes } = await this.sqsClient.send(
        new GetQueueAttributesCommand({
          QueueUrl: response.QueueUrl,
          AttributeNames: ["QueueArn"],
        }),
      );

      this.queues.push({
        queueName,
        queueArn: Attributes.QueueArn,
        queueUrl: response.QueueUrl,
      });

      await this.logger.log(
        MESSAGES.queueCreatedNotice
          .replace("${QUEUE_NAME}", queueName)
          .replace("${QUEUE_URL}", response.QueueUrl)
          .replace("${QUEUE_ARN}", Attributes.QueueArn),
      );
    }
  }

  async attachQueueIamPolicies() {
    for (const [index, queue] of this.queues.entries()) {
      const policy = JSON.stringify(
        {
          Statement: [
            {
              Effect: "Allow",
              Principal: {
                Service: "sns.amazonaws.com",
              },
              Action: "sqs:SendMessage",
              Resource: queue.queueArn,
              Condition: {
                ArnEquals: {
                  "aws:SourceArn": this.topicArn,
                },
              },
            },
          ],
        },
        null,
        2,
      );

      if (index !== 0) {
        this.logger.logSeparator();
      }

      await this.logger.log(MESSAGES.attachPolicyNotice);
      console.log(policy);
      const addPolicy = await this.prompter.confirm({
        message: MESSAGES.addPolicyConfirmation.replace(
          "${QUEUE_NAME}",
          queue.queueName,
        ),
      });

      if (addPolicy) {
        await this.sqsClient.send(
          new SetQueueAttributesCommand({
            QueueUrl: queue.queueUrl,
            Attributes: {
              Policy: policy,
            },
          }),
        );
        queue.policy = policy;
      } else {
        await this.logger.log(
          MESSAGES.policyNotAttachedNotice.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
        );
      }
    }
  }

  async subscribeQueuesToTopic() {
    for (const [index, queue] of this.queues.entries()) {
      /**
       * @type {import('@aws-sdk/client-sns').SubscribeCommandInput}
       */
      const subscribeParams = {
        TopicArn: this.topicArn,
        Protocol: "sqs",
        Endpoint: queue.queueArn,
      };
      let tones = [];

      if (this.isFifo) {
        if (index === 0) {
          await this.logger.log(MESSAGES.fifoFilterNotice);
        }
        tones = await this.prompter.checkbox({
          message: MESSAGES.fifoFilterSelect.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
          choices: toneChoices,
        });

        if (tones.length) {
          subscribeParams.Attributes = {
            FilterPolicyScope: "MessageAttributes",
            FilterPolicy: JSON.stringify({
              tone: tones,
            }),
          };
        }
      }

      const { SubscriptionArn } = await this.snsClient.send(
        new SubscribeCommand(subscribeParams),
      );

      this.subscriptionArns.push(SubscriptionArn);

      await this.logger.log(
        MESSAGES.queueSubscribedNotice
          .replace("${QUEUE_NAME}", queue.queueName)
          .replace("${TOPIC_NAME}", this.topicName)
          .replace("${TONES}", tones.length ? tones.join(", ") : "none"),
      );
    }
  }

  async publishMessages() {
    const message = await this.prompter.input({
      message: MESSAGES.publishMessagePrompt,
    });

    let groupId;
    let deduplicationId;
    let choices;

    if (this.isFifo) {
      await this.logger.log(MESSAGES.groupIdNotice);
      groupId = await this.prompter.input({
        message: MESSAGES.groupIdPrompt,
      });

      if (this.autoDedup === false) {
        await this.logger.log(MESSAGES.deduplicationIdNotice);
        deduplicationId = await this.prompter.input({
          message: MESSAGES.deduplicationIdPrompt,
        });
      }

      choices = await this.prompter.checkbox({
        message: MESSAGES.messageAttributesPrompt,
        choices: toneChoices,
      });
    }

    await this.snsClient.send(
      new PublishCommand({
        TopicArn: this.topicArn,
        Message: message,
        ...(groupId
          ? {
              MessageGroupId: groupId,
            }
          : {}),
        ...(deduplicationId
          ? {
              MessageDeduplicationId: deduplicationId,
            }
          : {}),
        ...(choices
          ? {
              MessageAttributes: {
                tone: {
                  DataType: "String.Array",
                  StringValue: JSON.stringify(choices),
                },
              },
            }
          : {}),
      }),
    );

    const publishAnother = await this.prompter.confirm({
      message: MESSAGES.publishAnother,
    });

    if (publishAnother) {
      await this.publishMessages();
    }
  }

  async receiveAndDeleteMessages() {
    for (const queue of this.queues) {
      const { Messages } = await this.sqsClient.send(
        new ReceiveMessageCommand({
          QueueUrl: queue.queueUrl,
        }),
      );

      if (Messages) {
        await this.logger.log(
          MESSAGES.messagesReceivedNotice.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
        );
        console.log(Messages);

        await this.sqsClient.send(
          new DeleteMessageBatchCommand({
            QueueUrl: queue.queueUrl,
            Entries: Messages.map((message) => ({
              Id: message.MessageId,
              ReceiptHandle: message.ReceiptHandle,
            })),
          }),
        );
      } else {
        await this.logger.log(
          MESSAGES.noMessagesReceivedNotice.replace(
            "${QUEUE_NAME}",
            queue.queueName,
          ),
        );
      }
    }

    const deleteAndPoll = await this.prompter.confirm({
      message: MESSAGES.deleteAndPollConfirmation,
    });

    if (deleteAndPoll) {
      await this.receiveAndDeleteMessages();
    }
  }

  async destroyResources() {
    for (const subscriptionArn of this.subscriptionArns) {
      await this.snsClient.send(
        new UnsubscribeCommand({ SubscriptionArn: subscriptionArn }),
      );
    }

    for (const queue of this.queues) {
      await this.sqsClient.send(
        new DeleteQueueCommand({ QueueUrl: queue.queueUrl }),
      );
    }

    if (this.topicArn) {
      await this.snsClient.send(
        new DeleteTopicCommand({ TopicArn: this.topicArn }),
      );
    }
  }

  async start() {
    console.clear();

    try {
      this.logger.logSeparator(MESSAGES.headerWelcome);
      await this.welcome();
      this.logger.logSeparator(MESSAGES.headerFifo);
      await this.confirmFifo();
      this.logger.logSeparator(MESSAGES.headerCreateTopic);
      await this.createTopic();
      this.logger.logSeparator(MESSAGES.headerCreateQueues);
      await this.createQueues();
      this.logger.logSeparator(MESSAGES.headerAttachPolicy);
      await this.attachQueueIamPolicies();
      this.logger.logSeparator(MESSAGES.headerSubscribeQueues);
      await this.subscribeQueuesToTopic();
      this.logger.logSeparator(MESSAGES.headerPublishMessage);
      await this.publishMessages();
      this.logger.logSeparator(MESSAGES.headerReceiveMessages);
      await this.receiveAndDeleteMessages();
    } catch (err) {
      console.error(err);
    } finally {
      await this.destroyResources();
    }
  }
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/CreateQueueCommand)
  + [CreateTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/DeleteMessageBatchCommand)
  + [DeleteQueue](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/DeleteQueueCommand)
  + [DeleteTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/DeleteTopicCommand)
  + [GetQueueAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/GetQueueAttributesCommand)
  + [Publish](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/PublishCommand)
  + [ReceiveMessage](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/ReceiveMessageCommand)
  + [SetQueueAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sqs/command/SetQueueAttributesCommand)
  + [Subscribe](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/SubscribeCommand)
  + [Unsubscribe](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/UnsubscribeCommand)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_javascript_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/blob/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
exports.handler = async (event, context) => {
  for (const message of event.Records) {
    await processMessageAsync(message);
  }
  console.info("done");
};

async function processMessageAsync(message) {
  try {
    console.log(`Processed message ${message.body}`);
    // TODO: Do interesting work based on the new message
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```
TypeScript を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { SQSEvent, Context, SQSHandler, SQSRecord } from "aws-lambda";

export const functionHandler: SQSHandler = async (
  event: SQSEvent,
  context: Context
): Promise<void> => {
  for (const message of event.Records) {
    await processMessageAsync(message);
  }
  console.info("done");
};

async function processMessageAsync(message: SQSRecord): Promise<any> {
  try {
    console.log(`Processed message ${message.body}`);
    // TODO: Do interesting work based on the new message
    await Promise.resolve(1); //Placeholder for actual async work
  } catch (err) {
    console.error("An error occurred");
    throw err;
  }
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_javascript_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JavaScript を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Node.js 20.x Lambda runtime, AWS SDK for Javascript V3
export const handler = async (event, context) => {
    const batchItemFailures = [];
    for (const record of event.Records) {
        try {
            await processMessageAsync(record, context);
        } catch (error) {
            batchItemFailures.push({ itemIdentifier: record.messageId });
        }
    }
    return { batchItemFailures };
};

async function processMessageAsync(record, context) {
    if (record.body && record.body.includes("error")) {
        throw new Error("There is an error in the SQS Message.");
    }
    console.log(`Processed message: ${record.body}`);
}
```
TypeScript を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { SQSEvent, SQSBatchResponse, Context, SQSBatchItemFailure, SQSRecord } from 'aws-lambda';

export const handler = async (event: SQSEvent, context: Context): Promise<SQSBatchResponse> => {
    const batchItemFailures: SQSBatchItemFailure[] = [];

    for (const record of event.Records) {
        try {
            await processMessageAsync(record);
        } catch (error) {
            batchItemFailures.push({ itemIdentifier: record.messageId });
        }
    }

    return {batchItemFailures: batchItemFailures};
};

async function processMessageAsync(record: SQSRecord): Promise<void> {
    if (record.body && record.body.includes("error")) {
        throw new Error('There is an error in the SQS Message.');
    }
    console.log(`Processed message ${record.body}`);
}
```

# SDK for JavaScript (v3) を使用した Step Functions の例
<a name="javascript_3_sfn_code_examples"></a>

次のコード例は、Step Functions で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `StartExecution`
<a name="sfn_StartExecution_javascript_3_topic"></a>

次のコード例は、`StartExecution` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sfn#code-examples)での設定と実行の方法を確認してください。

```
import { SFNClient, StartExecutionCommand } from "@aws-sdk/client-sfn";

/**
 * @param {{ sfnClient: SFNClient, stateMachineArn: string }} config
 */
export async function startExecution({ sfnClient, stateMachineArn }) {
  const response = await sfnClient.send(
    new StartExecutionCommand({
      stateMachineArn,
    }),
  );
  console.log(response);
  // Example response:
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '202a9309-c16a-454b-adeb-c4d19afe3bf2',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   executionArn: 'arn:aws:states:us-east-1:000000000000:execution:MyStateMachine:aaaaaaaa-f787-49fb-a20c-1b61c64eafe6',
  //   startDate: 2024-01-04T15:54:08.362Z
  // }
  return response;
}

// Call function if run directly
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  startExecution({ sfnClient: new SFNClient({}), stateMachineArn: "ARN" });
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[StartExecution](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sfn/command/StartExecutionCommand)」を参照してください。

# AWS STS SDK for JavaScript (v3) を使用した例
<a name="javascript_3_sts_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_javascript_3_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sts#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { STSClient } from "@aws-sdk/client-sts";
// Set the AWS Region.
const REGION = "us-east-1";
// Create an AWS STS service client object.
export const client = new STSClient({ region: REGION });
```
IAM ロールを割り当てます。  

```
import { AssumeRoleCommand } from "@aws-sdk/client-sts";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Returns a set of temporary security credentials that you can use to
    // access Amazon Web Services resources that you might not normally
    // have access to.
    const command = new AssumeRoleCommand({
      // The Amazon Resource Name (ARN) of the role to assume.
      RoleArn: "ROLE_ARN",
      // An identifier for the assumed role session.
      RoleSessionName: "session1",
      // The duration, in seconds, of the role session. The value specified
      // can range from 900 seconds (15 minutes) up to the maximum session
      // duration set for the role.
      DurationSeconds: 900,
    });
    const response = await client.send(command);
    console.log(response);
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[AssumeRole](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sts/command/AssumeRoleCommand)」を参照してください。

# サポート SDK for JavaScript (v3) を使用した例
<a name="javascript_3_support_code_examples"></a>

次のコード例は、 で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち サポートは
<a name="support_Hello_javascript_3_topic"></a>

次のコード例は、 サポートの使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。
`main()` を呼び出してサンプルを実行します。  

```
import {
  DescribeServicesCommand,
  SupportClient,
} from "@aws-sdk/client-support";

// Change the value of 'region' to your preferred AWS Region.
const client = new SupportClient({ region: "us-east-1" });

const getServiceCount = async () => {
  try {
    const { services } = await client.send(new DescribeServicesCommand({}));
    return services.length;
  } catch (err) {
    if (err.name === "SubscriptionRequiredException") {
      throw new Error(
        "You must be subscribed to the AWS Support plan to use this feature.",
      );
    }
    throw err;
  }
};

export const main = async () => {
  try {
    const count = await getServiceCount();
    console.log(`Hello, AWS Support! There are ${count} services available.`);
  } catch (err) {
    console.error("Failed to get service count: ", err.message);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*のの「[DescribeServices](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeServicesCommand)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="support_Scenario_GetStartedSupportCases_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ケースの利用可能なサービスと重要度レベルを取得して表示します。
+ 選択したサービス、カテゴリ、重要度レベルを使用してサポートケースを作成する方法
+ 当日のオープンケースのリストを取得して表示する方法
+ 新しいケースに添付セットとコミュニケーションを追加する方法
+ ケースの新しい添付ファイルとコミュニケーションについて説明する方法
+ ケースを解決する方法
+ 当日の解決済みケースのリストを取得して表示します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。
ターミナルでインタラクティブシナリオを実行します。  

```
import {
  AddAttachmentsToSetCommand,
  AddCommunicationToCaseCommand,
  CreateCaseCommand,
  DescribeAttachmentCommand,
  DescribeCasesCommand,
  DescribeCommunicationsCommand,
  DescribeServicesCommand,
  DescribeSeverityLevelsCommand,
  ResolveCaseCommand,
  SupportClient,
} from "@aws-sdk/client-support";
import * as inquirer from "@inquirer/prompts";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";

const wrapText = (text, char = "=") => {
  const rule = char.repeat(80);
  return `${rule}\n    ${text}\n${rule}\n`;
};

const client = new SupportClient({ region: "us-east-1" });

// Verify that the account has a Support plan.
export const verifyAccount = async () => {
  const command = new DescribeServicesCommand({});

  try {
    await client.send(command);
  } catch (err) {
    if (err.name === "SubscriptionRequiredException") {
      throw new Error(
        "You must be subscribed to the AWS Support plan to use this feature.",
      );
    }
    throw err;
  }
};

/**
 * Select a service from the list returned from DescribeServices.
 */
export const getService = async () => {
  const { services } = await client.send(new DescribeServicesCommand({}));
  const selectedService = await inquirer.select({
    message:
      "Select a service. Your support case will be created for this service. The list of services is truncated for readability.",
    choices: services.slice(0, 10).map((s) => ({ name: s.name, value: s })),
  });
  return selectedService;
};

/**
 * @param {{ categories: import('@aws-sdk/client-support').Category[]}} service
 */
export const getCategory = async (service) => {
  const selectedCategory = await inquirer.select({
    message: "Select a category.",
    choices: service.categories.map((c) => ({ name: c.name, value: c })),
  });
  return selectedCategory;
};

// Get the available severity levels for the account.
export const getSeverityLevel = async () => {
  const command = new DescribeSeverityLevelsCommand({});
  const { severityLevels } = await client.send(command);
  const selectedSeverityLevel = await inquirer.select({
    message: "Select a severity level.",
    choices: severityLevels.map((s) => ({ name: s.name, value: s })),
  });
  return selectedSeverityLevel;
};

/**
 * Create a new support case
 * @param {{
 *  selectedService: import('@aws-sdk/client-support').Service
 *  selectedCategory: import('@aws-sdk/client-support').Category
 *  selectedSeverityLevel: import('@aws-sdk/client-support').SeverityLevel
 * }} selections
 * @returns
 */
export const createCase = async ({
  selectedService,
  selectedCategory,
  selectedSeverityLevel,
}) => {
  const command = new CreateCaseCommand({
    subject: "IGNORE: Test case",
    communicationBody: "This is a test. Please ignore.",
    serviceCode: selectedService.code,
    categoryCode: selectedCategory.code,
    severityCode: selectedSeverityLevel.code,
  });
  const { caseId } = await client.send(command);
  return caseId;
};

// Get a list of open support cases created today.
export const getTodaysOpenCases = async () => {
  const d = new Date();
  const startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  const command = new DescribeCasesCommand({
    includeCommunications: false,
    afterTime: startOfToday.toISOString(),
  });

  const { cases } = await client.send(command);

  if (cases.length === 0) {
    throw new Error(
      "Unexpected number of cases. Expected more than 0 open cases.",
    );
  }
  return cases;
};

// Create an attachment set.
export const createAttachmentSet = async () => {
  const command = new AddAttachmentsToSetCommand({
    attachments: [
      {
        fileName: "example.txt",
        data: new TextEncoder().encode("some example text"),
      },
    ],
  });
  const { attachmentSetId } = await client.send(command);
  return attachmentSetId;
};

export const linkAttachmentSetToCase = async (attachmentSetId, caseId) => {
  const command = new AddCommunicationToCaseCommand({
    attachmentSetId,
    caseId,
    communicationBody: "Adding attachment set to case.",
  });
  await client.send(command);
};

// Get all communications for a support case.
export const getCommunications = async (caseId) => {
  const command = new DescribeCommunicationsCommand({
    caseId,
  });
  const { communications } = await client.send(command);
  return communications;
};

/**
 * @param {import('@aws-sdk/client-support').Communication[]} communications
 */
export const getFirstAttachment = (communications) => {
  const firstCommWithAttachment = communications.find(
    (c) => c.attachmentSet.length > 0,
  );
  return firstCommWithAttachment?.attachmentSet[0].attachmentId;
};

// Get an attachment.
export const getAttachment = async (attachmentId) => {
  const command = new DescribeAttachmentCommand({
    attachmentId,
  });
  const { attachment } = await client.send(command);
  return attachment;
};

// Resolve the case matching the given case ID.
export const resolveCase = async (caseId) => {
  const shouldResolve = await inquirer.confirm({
    message: `Do you want to resolve ${caseId}?`,
  });

  if (shouldResolve) {
    const command = new ResolveCaseCommand({
      caseId: caseId,
    });

    await client.send(command);
    return true;
  }
  return false;
};

/**
 * Find a specific case in the list of provided cases by case ID.
 * If the case is not found, and the results are paginated, continue
 * paging through the results.
 * @param {{
 *   caseId: string,
 *   cases: import('@aws-sdk/client-support').CaseDetails[]
 *   nextToken: string
 * }} options
 * @returns
 */
export const findCase = async ({ caseId, cases, nextToken }) => {
  const foundCase = cases.find((c) => c.caseId === caseId);

  if (foundCase) {
    return foundCase;
  }

  if (nextToken) {
    const response = await client.send(
      new DescribeCasesCommand({
        nextToken,
        includeResolvedCases: true,
      }),
    );
    return findCase({
      caseId,
      cases: response.cases,
      nextToken: response.nextToken,
    });
  }

  throw new Error(`${caseId} not found.`);
};

// Get all cases created today.
export const getTodaysResolvedCases = async (caseIdToWaitFor) => {
  const d = new Date("2023-01-18");
  const startOfToday = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  const command = new DescribeCasesCommand({
    includeCommunications: false,
    afterTime: startOfToday.toISOString(),
    includeResolvedCases: true,
  });
  const { cases, nextToken } = await client.send(command);
  await findCase({ cases, caseId: caseIdToWaitFor, nextToken });
  return cases.filter((c) => c.status === "resolved");
};

const main = async () => {
  let caseId;
  try {
    console.log(wrapText("Welcome to the AWS Support basic usage scenario."));

    // Verify that the account is subscribed to support.
    await verifyAccount();

    // Provided a truncated list of services and prompt the user to select one.
    const selectedService = await getService();

    // Provided the categories for the selected service and prompt the user to select one.
    const selectedCategory = await getCategory(selectedService);

    // Provide the severity available severity levels for the account and prompt the user to select one.
    const selectedSeverityLevel = await getSeverityLevel();

    // Create a support case.
    console.log("\nCreating a support case.");
    caseId = await createCase({
      selectedService,
      selectedCategory,
      selectedSeverityLevel,
    });
    console.log(`Support case created: ${caseId}`);

    // Display a list of open support cases created today.
    const todaysOpenCases = await retry(
      { intervalInMs: 1000, maxRetries: 15 },
      getTodaysOpenCases,
    );
    console.log(
      `\nOpen support cases created today: ${todaysOpenCases.length}`,
    );
    console.log(todaysOpenCases.map((c) => `${c.caseId}`).join("\n"));

    // Create an attachment set.
    console.log("\nCreating an attachment set.");
    const attachmentSetId = await createAttachmentSet();
    console.log(`Attachment set created: ${attachmentSetId}`);

    // Add the attachment set to the support case.
    console.log(`\nAdding attachment set to ${caseId}`);
    await linkAttachmentSetToCase(attachmentSetId, caseId);
    console.log(`Attachment set added to ${caseId}`);

    // List the communications for a support case.
    console.log(`\nListing communications for ${caseId}`);
    const communications = await getCommunications(caseId);
    console.log(
      communications
        .map(
          (c) =>
            `Communication created on ${c.timeCreated}. Has ${c.attachmentSet.length} attachments.`,
        )
        .join("\n"),
    );

    // Describe the first attachment.
    console.log(`\nDescribing attachment ${attachmentSetId}`);
    const attachmentId = getFirstAttachment(communications);
    const attachment = await getAttachment(attachmentId);
    console.log(
      `Attachment is the file '${
        attachment.fileName
      }' with data: \n${new TextDecoder().decode(attachment.data)}`,
    );

    // Confirm that the support case should be resolved.
    const isResolved = await resolveCase(caseId);
    if (isResolved) {
      // List the resolved cases and include the one previously created.
      // Resolved cases can take a while to appear.
      console.log(
        "\nWaiting for case status to be marked as resolved. This can take some time.",
      );
      const resolvedCases = await retry(
        { intervalInMs: 20000, maxRetries: 15 },
        () => getTodaysResolvedCases(caseId),
      );
      console.log("Resolved cases:");
      console.log(resolvedCases.map((c) => c.caseId).join("\n"));
    }
  } catch (err) {
    console.error(err);
  }
};
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [AddAttachmentsToSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/AddAttachmentsToSetCommand)
  + [AddCommunicationToCase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/AddCommunicationToCaseCommand)
  + [CreateCase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/CreateCaseCommand)
  + [DescribeAttachment](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeAttachmentCommand)
  + [DescribeCases](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeCasesCommand)
  + [DescribeCommunications](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeCommunicationsCommand)
  + [DescribeServices](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeServicesCommand)
  + [DescribeSeverityLevels](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeSeverityLevelsCommand)
  + [ResolveCase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/ResolveCaseCommand)

## アクション
<a name="actions"></a>

### `AddAttachmentsToSet`
<a name="support_AddAttachmentsToSet_javascript_3_topic"></a>

次のコード例は、`AddAttachmentsToSet` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { AddAttachmentsToSetCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Create a new attachment set or add attachments to an existing set.
    // Provide an 'attachmentSetId' value to add attachments to an existing set.
    // Use AddCommunicationToCase or CreateCase to associate an attachment set with a support case.
    const response = await client.send(
      new AddAttachmentsToSetCommand({
        // You can add up to three attachments per set. The size limit is 5 MB per attachment.
        attachments: [
          {
            fileName: "example.txt",
            data: new TextEncoder().encode("some example text"),
          },
        ],
      }),
    );
    // Use this ID in AddCommunicationToCase or CreateCase.
    console.log(response.attachmentSetId);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AddAttachmentsToSet](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/AddAttachmentsToSetCommand)」を参照してください。

### `AddCommunicationToCase`
<a name="support_AddCommunicationToCase_javascript_3_topic"></a>

次のコード例は、`AddCommunicationToCase` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { AddCommunicationToCaseCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

export const main = async () => {
  let attachmentSetId;

  try {
    // Add a communication to a case.
    const response = await client.send(
      new AddCommunicationToCaseCommand({
        communicationBody: "Adding an attachment.",
        // Set value to an existing support case id.
        caseId: "CASE_ID",
        // Optional. Set value to an existing attachment set id to add attachments to the case.
        attachmentSetId,
      }),
    );
    console.log(response);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[AddCommunicationToCase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/AddCommunicationToCaseCommand)」を参照してください。

### `CreateCase`
<a name="support_CreateCase_javascript_3_topic"></a>

次のコード例は、`CreateCase` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { CreateCaseCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Create a new case and log the case id.
    // Important: This creates a real support case in your account.
    const response = await client.send(
      new CreateCaseCommand({
        // The subject line of the case.
        subject: "IGNORE: Test case",
        // Use DescribeServices to find available service codes for each service.
        serviceCode: "service-quicksight-end-user",
        // Use DescribeSecurityLevels to find available severity codes for your support plan.
        severityCode: "low",
        // Use DescribeServices to find available category codes for each service.
        categoryCode: "end-user-support",
        // The main description of the support case.
        communicationBody: "This is a test. Please ignore.",
      }),
    );
    console.log(response.caseId);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateCase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/CreateCaseCommand)」を参照してください。

### `DescribeAttachment`
<a name="support_DescribeAttachment_javascript_3_topic"></a>

次のコード例は、`DescribeAttachment` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeAttachmentCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Get the metadata and content of an attachment.
    const response = await client.send(
      new DescribeAttachmentCommand({
        // Set value to an existing attachment id.
        // Use DescribeCommunications or DescribeCases to find an attachment id.
        attachmentId: "ATTACHMENT_ID",
      }),
    );
    console.log(response.attachment?.fileName);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeAttachment](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeAttachmentCommand)」を参照してください。

### `DescribeCases`
<a name="support_DescribeCases_javascript_3_topic"></a>

次のコード例は、`DescribeCases` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeCasesCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Get all of the unresolved cases in your account.
    // Filter or expand results by providing parameters to the DescribeCasesCommand. Refer
    // to the TypeScript definition and the API doc for more information on possible parameters.
    // https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-support/interfaces/describecasescommandinput.html
    const response = await client.send(new DescribeCasesCommand({}));
    const caseIds = response.cases.map((supportCase) => supportCase.caseId);
    console.log(caseIds);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeCases](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeCasesCommand)」を参照してください。

### `DescribeCommunications`
<a name="support_DescribeCommunications_javascript_3_topic"></a>

次のコード例は、`DescribeCommunications` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeCommunicationsCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Get all communications for the support case.
    // Filter results by providing parameters to the DescribeCommunicationsCommand. Refer
    // to the TypeScript definition and the API doc for more information on possible parameters.
    // https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-support/interfaces/describecommunicationscommandinput.html
    const response = await client.send(
      new DescribeCommunicationsCommand({
        // Set value to an existing case id.
        caseId: "CASE_ID",
      }),
    );
    const text = response.communications.map((item) => item.body).join("\n");
    console.log(text);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeCommunications](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeCommunicationsCommand)」を参照してください。

### `DescribeSeverityLevels`
<a name="support_DescribeSeverityLevels_javascript_3_topic"></a>

次のコード例は、`DescribeSeverityLevels` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { DescribeSeverityLevelsCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

export const main = async () => {
  try {
    // Get the list of severity levels.
    // The available values depend on the support plan for the account.
    const response = await client.send(new DescribeSeverityLevelsCommand({}));
    console.log(response.severityLevels);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DescribeSeverityLevels](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/DescribeSeverityLevelsCommand)」を参照してください。

### `ResolveCase`
<a name="support_ResolveCase_javascript_3_topic"></a>

次のコード例は、`ResolveCase` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import { ResolveCaseCommand } from "@aws-sdk/client-support";

import { client } from "../libs/client.js";

const main = async () => {
  try {
    const response = await client.send(
      new ResolveCaseCommand({
        caseId: "CASE_ID",
      }),
    );

    console.log(response.finalCaseStatus);
    return response;
  } catch (err) {
    console.error(err);
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[ResolveCase](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/support/command/ResolveCaseCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Systems Manager の例
<a name="javascript_3_ssm_code_examples"></a>

次のコード例は、Systems Manager で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにちは、Systems Manager
<a name="ssm_Hello_javascript_3_topic"></a>

次のコード例は、Systems Manager の使用を開始する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { paginateListDocuments, SSMClient } from "@aws-sdk/client-ssm";

// Call ListDocuments and display the result.
export const main = async () => {
  const client = new SSMClient();
  const listDocumentsPaginated = [];
  console.log(
    "Hello, AWS Systems Manager! Let's list some of your documents:\n",
  );
  try {
    // The paginate function is a wrapper around the base command.
    const paginator = paginateListDocuments({ client }, { MaxResults: 5 });
    for await (const page of paginator) {
      listDocumentsPaginated.push(...page.DocumentIdentifiers);
    }
  } catch (caught) {
    console.error(`There was a problem saying hello: ${caught.message}`);
    throw caught;
  }

  for (const { Name, DocumentFormat, CreatedDate } of listDocumentsPaginated) {
    console.log(`${Name} - ${DocumentFormat} - ${CreatedDate}`);
  }
};

// Call function if run directly.
import { fileURLToPath } from "node:url";
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  main();
}
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListDocuments](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/ListDocumentsCommand)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ssm_Scenario_javascript_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ メンテナンスウィンドウを作成します。
+ メンテナンスウィンドウのスケジュールを変更します。
+ ドキュメントを作成します。
+ 指定された EC2 インスタンスにコマンドを送信します。
+ 新しい OpsItem を作成します。
+ OpsItem を更新して解決します。
+ メンテナンスウィンドウ、OpsItem、ドキュメントを削除します。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import {
  Scenario,
  ScenarioAction,
  ScenarioInput,
  ScenarioOutput,
} from "@aws-doc-sdk-examples/lib/scenario/index.js";
import { fileURLToPath } from "node:url";
import {
  CreateDocumentCommand,
  CreateMaintenanceWindowCommand,
  CreateOpsItemCommand,
  DeleteDocumentCommand,
  DeleteMaintenanceWindowCommand,
  DeleteOpsItemCommand,
  DescribeOpsItemsCommand,
  DocumentAlreadyExists,
  OpsItemStatus,
  waitUntilCommandExecuted,
  CancelCommandCommand,
  paginateListCommandInvocations,
  SendCommandCommand,
  UpdateMaintenanceWindowCommand,
  UpdateOpsItemCommand,
  SSMClient,
} from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * @typedef {{
 *   ssmClient: import('@aws-sdk/client-ssm').SSMClient,
 *   documentName?: string
 *   maintenanceWindow?: string
 *   winId?: int
 *   ec2InstanceId?: string
 *   requestedDateTime?: Date
 *   opsItemId?: string
 *   askToDeleteResources?: boolean
 * }} State
 */

const defaultMaintenanceWindow = "ssm-maintenance-window";
const defaultDocumentName = "ssmdocument";
// The timeout duration is highly dependent on the specific setup and environment necessary. This example handles only the most common error cases, and uses a much shorter duration than most productions systems would use.
const COMMAND_TIMEOUT_DURATION_SECONDS = 30; // 30 seconds

const pressEnter = new ScenarioInput("continue", "Press Enter to continue", {
  type: "confirm",
});

const greet = new ScenarioOutput(
  "greet",
  `Welcome to the AWS Systems Manager SDK Getting Started scenario.
    This program demonstrates how to interact with Systems Manager using the AWS SDK for JavaScript V3.
    Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution.
    The program's primary functions include creating a maintenance window, creating a document, sending a command to a document,
    listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting Systems Manager resources.
    Upon completion of the program, all AWS resources are cleaned up.
    Let's get started...`,
  { header: true },
);

const createMaintenanceWindow = new ScenarioOutput(
  "createMaintenanceWindow",
  "Step 1: Create a Systems Manager maintenance window.",
);

const getMaintenanceWindow = new ScenarioInput(
  "maintenanceWindow",
  "Please enter the maintenance window name:",
  { type: "input", default: defaultMaintenanceWindow },
);

export const sdkCreateMaintenanceWindow = new ScenarioAction(
  "sdkCreateMaintenanceWindow",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new CreateMaintenanceWindowCommand({
          Name: state.maintenanceWindow,
          Schedule: "cron(0 10 ? * MON-FRI *)", //The schedule of the maintenance window in the form of a cron or rate expression.
          Duration: 2, //The duration of the maintenance window in hours.
          Cutoff: 1, //The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution.
          AllowUnassociatedTargets: true, //Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
        }),
      );
      state.winId = response.WindowId;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while creating the maintenance window. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const modifyMaintenanceWindow = new ScenarioOutput(
  "modifyMaintenanceWindow",
  "Modify the maintenance window by changing the schedule.",
);

const sdkModifyMaintenanceWindow = new ScenarioAction(
  "sdkModifyMaintenanceWindow",
  async (/** @type {State} */ state) => {
    try {
      await state.ssmClient.send(
        new UpdateMaintenanceWindowCommand({
          WindowId: state.winId,
          Schedule: "cron(0 0 ? * MON *)",
        }),
      );
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while modifying the maintenance window. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const createSystemsManagerActions = new ScenarioOutput(
  "createSystemsManagerActions",
  "Create a document that defines the actions that Systems Manager performs on your EC2 instance.",
);

const getDocumentName = new ScenarioInput(
  "documentName",
  "Please enter the document: ",
  { type: "input", default: defaultDocumentName },
);

const sdkCreateSSMDoc = new ScenarioAction(
  "sdkCreateSSMDoc",
  async (/** @type {State} */ state) => {
    const contentData = `{
                "schemaVersion": "2.2",
                "description": "Run a simple shell command",
                "mainSteps": [
                    {
                        "action": "aws:runShellScript",
                        "name": "runEchoCommand",
                        "inputs": {
                          "runCommand": [
                            "echo 'Hello, world!'"
                          ]
                        }
                    }
                ]
            }`;
    try {
      await state.ssmClient.send(
        new CreateDocumentCommand({
          Content: contentData,
          Name: state.documentName,
          DocumentType: "Command",
        }),
      );
    } catch (caught) {
      console.log(`Exception type: (${typeof caught})`);
      if (caught instanceof DocumentAlreadyExists) {
        console.log("Document already exists. Continuing...\n");
      } else {
        console.error(caught.message);
        console.log(
          `An error occurred while creating the document. Please fix the error and try again. Error message: ${caught.message}`,
        );
        throw caught;
      }
    }
  },
);

const ec2HelloWorld = new ScenarioOutput(
  "ec2HelloWorld",
  `Now you have the option of running a command on an EC2 instance that echoes 'Hello, world!'. In order to run this command, you must provide the instance ID of a Linux EC2 instance. If you do not already have a running Linux EC2 instance in your account, you can create one using the AWS console. For information about creating an EC2 instance, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html.`,
);

const enterIdOrSkipEC2HelloWorld = new ScenarioInput(
  "enterIdOrSkipEC2HelloWorld",
  "Enter your EC2 InstanceId or press enter to skip this step: ",
  { type: "input", default: "" },
);

const sdkEC2HelloWorld = new ScenarioAction(
  "sdkEC2HelloWorld",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new SendCommandCommand({
          DocumentName: state.documentName,
          InstanceIds: [state.ec2InstanceId],
          TimeoutSeconds: COMMAND_TIMEOUT_DURATION_SECONDS,
        }),
      );
      state.CommandId = response.Command.CommandId;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while sending the command. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
  {
    skipWhen: (/** @type {State} */ state) =>
      state.enterIdOrSkipEC2HelloWorld === "",
  },
);

const sdkGetCommandTime = new ScenarioAction(
  "sdkGetCommandTime",
  async (/** @type {State} */ state) => {
    const listInvocationsPaginated = [];
    console.log(
      "Let's get the time when the specific command was sent to the specific managed node.",
    );

    console.log(
      `First, we'll wait for the command to finish executing. This may take up to ${COMMAND_TIMEOUT_DURATION_SECONDS} seconds.`,
    );
    const commandExecutedResult = waitUntilCommandExecuted(
      { client: state.ssmClient },
      {
        CommandId: state.CommandId,
        InstanceId: state.ec2InstanceId,
      },
    );
    // This is necessary because the TimeoutSeconds of SendCommandCommand is only for the delivery, not execution.
    try {
      await new Promise((_, reject) =>
        setTimeout(
          reject,
          COMMAND_TIMEOUT_DURATION_SECONDS * 1000,
          new Error("Command Timed Out"),
        ),
      );
    } catch (caught) {
      if (caught.message === "Command Timed Out") {
        commandExecutedResult.state = "TIMED_OUT";
      } else {
        throw caught;
      }
    }

    if (commandExecutedResult.state !== "SUCCESS") {
      console.log(
        `The command with id: ${state.CommandId} did not execute in the allotted time. Canceling command.`,
      );
      state.ssmClient.send(
        new CancelCommandCommand({
          CommandId: state.CommandId,
        }),
      );
      state.enterIdOrSkipEC2HelloWorld === "";
      return;
    }

    for await (const page of paginateListCommandInvocations(
      { client: state.ssmClient },
      { CommandId: state.CommandId },
    )) {
      listInvocationsPaginated.push(...page.CommandInvocations);
    }
    /**
     * @type {import('@aws-sdk/client-ssm').CommandInvocation}
     */
    const commandInvocation = listInvocationsPaginated.shift(); // Because the call was made with CommandId, there's only one result, so shift it off.
    state.requestedDateTime = commandInvocation.RequestedDateTime;

    console.log(
      `The command invocation happened at: ${state.requestedDateTime}.`,
    );
  },
  {
    skipWhen: (/** @type {State} */ state) =>
      state.enterIdOrSkipEC2HelloWorld === "",
  },
);

const createSSMOpsItem = new ScenarioOutput(
  "createSSMOpsItem",
  `Now we will create a Systems Manager OpsItem. An OpsItem is a feature provided by the Systems Manager service. It is a type of operational data item that allows you to manage and track various operational issues, events, or tasks within your AWS environment.
You can create OpsItems to track and manage operational issues as they arise. For example, you could create an OpsItem whenever your application detects a critical error or an anomaly in your infrastructure.`,
);

const sdkCreateSSMOpsItem = new ScenarioAction(
  "sdkCreateSSMOpsItem",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new CreateOpsItemCommand({
          Description: "Created by the System Manager Javascript API",
          Title: "Disk Space Alert",
          Source: "EC2",
          Category: "Performance",
          Severity: "2",
        }),
      );
      state.opsItemId = response.OpsItemId;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while creating the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const updateOpsItem = new ScenarioOutput(
  "updateOpsItem",
  (/** @type {State} */ state) =>
    `Now we will update the OpsItem: ${state.opsItemId}`,
);

const sdkUpdateOpsItem = new ScenarioAction(
  "sdkUpdateOpsItem",
  async (/** @type {State} */ state) => {
    try {
      const _response = await state.ssmClient.send(
        new UpdateOpsItemCommand({
          OpsItemId: state.opsItemId,
          Description: `An update to ${state.opsItemId}`,
        }),
      );
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while updating the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const getOpsItemStatus = new ScenarioOutput(
  "getOpsItemStatus",
  (/** @type {State} */ state) =>
    `Now we will get the status of the OpsItem: ${state.opsItemId}`,
);

const sdkOpsItemStatus = new ScenarioAction(
  "sdkGetOpsItemStatus",
  async (/** @type {State} */ state) => {
    try {
      const response = await state.ssmClient.send(
        new DescribeOpsItemsCommand({
          OpsItemId: state.opsItemId,
        }),
      );
      state.opsItemStatus = response.OpsItemStatus;
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while describing the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const resolveOpsItem = new ScenarioOutput(
  "resolveOpsItem",
  (/** @type {State} */ state) =>
    `Now we will resolve the OpsItem: ${state.opsItemId}`,
);

const sdkResolveOpsItem = new ScenarioAction(
  "sdkResolveOpsItem",
  async (/** @type {State} */ state) => {
    try {
      const _response = await state.ssmClient.send(
        new UpdateOpsItemCommand({
          OpsItemId: state.opsItemId,
          Status: OpsItemStatus.RESOLVED,
        }),
      );
    } catch (caught) {
      console.error(caught.message);
      console.log(
        `An error occurred while updating the ops item. Please fix the error and try again. Error message: ${caught.message}`,
      );
      throw caught;
    }
  },
);

const askToDeleteResources = new ScenarioInput(
  "askToDeleteResources",
  "Would you like to delete the Systems Manager resources created during this example run?",
  { type: "confirm" },
);

const confirmDeleteChoice = new ScenarioOutput(
  "confirmDeleteChoice",
  (/** @type {State} */ state) => {
    if (state.askToDeleteResources) {
      return "You chose to delete the resources.";
    }
    return "The Systems Manager resources will not be deleted. Please delete them manually to avoid charges.";
  },
);

export const sdkDeleteResources = new ScenarioAction(
  "sdkDeleteResources",
  async (/** @type {State} */ state) => {
    try {
      await state.ssmClient.send(
        new DeleteOpsItemCommand({
          OpsItemId: state.opsItemId,
        }),
      );
      console.log(`The ops item: ${state.opsItemId} was successfully deleted.`);
    } catch (caught) {
      console.log(
        `There was a problem deleting the ops item: ${state.opsItemId}. Please delete it manually. Error: ${caught.message}`,
      );
    }

    try {
      await state.ssmClient.send(
        new DeleteMaintenanceWindowCommand({
          Name: state.maintenanceWindow,
          WindowId: state.winId,
        }),
      );
      console.log(
        `The maintenance window: ${state.maintenanceWindow} was successfully deleted.`,
      );
    } catch (caught) {
      console.log(
        `There was a problem deleting the maintenance window: ${state.opsItemId}. Please delete it manually. Error: ${caught.message}`,
      );
    }

    try {
      await state.ssmClient.send(
        new DeleteDocumentCommand({
          Name: state.documentName,
        }),
      );
      console.log(
        `The document: ${state.documentName} was successfully deleted.`,
      );
    } catch (caught) {
      console.log(
        `There was a problem deleting the document: ${state.documentName}. Please delete it manually. Error: ${caught.message}`,
      );
    }
  },
  { skipWhen: (/** @type {{}} */ state) => !state.askToDeleteResources },
);

const goodbye = new ScenarioOutput(
  "goodbye",
  "This concludes the Systems Manager Basics scenario for the AWS Javascript SDK v3. Thank you!",
);

const myScenario = new Scenario(
  "SSM Basics",
  [
    greet,
    pressEnter,
    createMaintenanceWindow,
    getMaintenanceWindow,
    sdkCreateMaintenanceWindow,
    modifyMaintenanceWindow,
    pressEnter,
    sdkModifyMaintenanceWindow,
    createSystemsManagerActions,
    getDocumentName,
    sdkCreateSSMDoc,
    ec2HelloWorld,
    enterIdOrSkipEC2HelloWorld,
    sdkEC2HelloWorld,
    sdkGetCommandTime,
    pressEnter,
    createSSMOpsItem,
    pressEnter,
    sdkCreateSSMOpsItem,
    updateOpsItem,
    pressEnter,
    sdkUpdateOpsItem,
    getOpsItemStatus,
    pressEnter,
    sdkOpsItemStatus,
    resolveOpsItem,
    pressEnter,
    sdkResolveOpsItem,
    askToDeleteResources,
    confirmDeleteChoice,
    sdkDeleteResources,
    goodbye,
  ],
  { ssmClient: new SSMClient({}) },
);

/** @type {{ stepHandlerOptions: StepHandlerOptions }} */
export const main = async (stepHandlerOptions) => {
  await myScenario.run(stepHandlerOptions);
};

// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const { values } = parseArgs({
    options: {
      yes: {
        type: "boolean",
        short: "y",
      },
    },
  });
  main({ confirmAll: values.yes });
}
```
+ API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の以下のトピックを参照してください。
  + [CreateDocument](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateDocumentCommand)
  + [CreateMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateMaintenanceWindowCommand)
  + [CreateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateOpsItemCommand)
  + [DeleteMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DeleteMaintenanceWindowCommand)
  + [ListCommandInvocations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/ListCommandInvocationsCommand)
  + [SendCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/SendCommandCommand)
  + [UpdateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/UpdateOpsItemCommand)

## アクション
<a name="actions"></a>

### `CreateDocument`
<a name="ssm_CreateDocument_javascript_3_topic"></a>

次のコード例は、`CreateDocument` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { CreateDocumentCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Create an SSM document.
 * @param {{ content: string, name: string, documentType?: DocumentType }}
 */
export const main = async ({ content, name, documentType }) => {
  const client = new SSMClient({});
  try {
    const { documentDescription } = await client.send(
      new CreateDocumentCommand({
        Content: content, // The content for the new SSM document. The content must not exceed 64KB.
        Name: name,
        DocumentType: documentType, // Document format type can be JSON, YAML, or TEXT. The default format is JSON.
      }),
    );
    console.log("Document created successfully.");
    return { DocumentDescription: documentDescription };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "DocumentAlreadyExists") {
      console.warn(`${caught.message}. Did you provide a new document name?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateDocument](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateDocumentCommand)」を参照してください。

### `CreateMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_javascript_3_topic"></a>

次のコード例は、`CreateMaintenanceWindow` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { CreateMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Create an SSM maintenance window.
 * @param {{ name: string, allowUnassociatedTargets: boolean, duration: number, cutoff: number, schedule: string, description?: string }}
 */
export const main = async ({
  name,
  allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
  duration, // The duration of the maintenance window in hours.
  cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution.
  schedule, // The schedule of the maintenance window in the form of a cron or rate expression.
  description = undefined,
}) => {
  const client = new SSMClient({});

  try {
    const { windowId } = await client.send(
      new CreateMaintenanceWindowCommand({
        Name: name,
        Description: description,
        AllowUnassociatedTargets: allowUnassociatedTargets, // Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
        Duration: duration, // The duration of the maintenance window in hours.
        Cutoff: cutoff, // The number of hours before the end of the maintenance window that Amazon Web Services Systems Manager stops scheduling new tasks for execution.
        Schedule: schedule, // The schedule of the maintenance window in the form of a cron or rate expression.
      }),
    );
    console.log(`Maintenance window created with Id: ${windowId}`);
    return { WindowId: windowId };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide these values?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[CreateMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateMaintenanceWindowCommand)」を参照してください。**

### `CreateOpsItem`
<a name="ssm_CreateOpsItem_javascript_3_topic"></a>

次のコード例は、`CreateOpsItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { CreateOpsItemCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Create an SSM OpsItem.
 * @param {{ title: string, source: string, category?: string, severity?: string }}
 */
export const main = async ({
  title,
  source,
  category = undefined,
  severity = undefined,
}) => {
  const client = new SSMClient({});
  try {
    const { opsItemArn, opsItemId } = await client.send(
      new CreateOpsItemCommand({
        Title: title,
        Source: source, // The origin of the OpsItem, such as Amazon EC2 or Systems Manager.
        Category: category,
        Severity: severity,
      }),
    );
    console.log(`Ops item created with id: ${opsItemId}`);
    return { OpsItemArn: opsItemArn, OpsItemId: opsItemId };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide these values?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[CreateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/CreateOpsItemCommand)」を参照してください。

### `DeleteDocument`
<a name="ssm_DeleteDocument_javascript_3_topic"></a>

次のコード例は、`DeleteDocument` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteDocumentCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Delete an SSM document.
 * @param {{ documentName: string }}
 */
export const main = async ({ documentName }) => {
  const client = new SSMClient({});
  try {
    await client.send(new DeleteDocumentCommand({ Name: documentName }));
    console.log(`Document '${documentName}' deleted.`);
    return { Deleted: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide this value?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteDocument](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DeleteDocumentCommand)」を参照してください。

### `DeleteMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_javascript_3_topic"></a>

次のコード例は、`DeleteMaintenanceWindow` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { DeleteMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Delete an SSM maintenance window.
 * @param {{ windowId: string }}
 */
export const main = async ({ windowId }) => {
  const client = new SSMClient({});
  try {
    await client.send(
      new DeleteMaintenanceWindowCommand({ WindowId: windowId }),
    );
    console.log(`Maintenance window '${windowId}' deleted.`);
    return { Deleted: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide this value?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[DeleteMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DeleteMaintenanceWindowCommand)」を参照してください。

### `DescribeOpsItems`
<a name="ssm_DescribeOpsItems_javascript_3_topic"></a>

次のコード例は、`DescribeOpsItems` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import {
  OpsItemFilterOperator,
  OpsItemFilterKey,
  paginateDescribeOpsItems,
  SSMClient,
} from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Describe SSM OpsItems.
 * @param {{ opsItemId: string }}
 */
export const main = async ({ opsItemId }) => {
  const client = new SSMClient({});
  try {
    const describeOpsItemsPaginated = [];
    for await (const page of paginateDescribeOpsItems(
      { client },
      {
        OpsItemFilters: {
          Key: OpsItemFilterKey.OPSITEM_ID,
          Operator: OpsItemFilterOperator.EQUAL,
          Values: opsItemId,
        },
      },
    )) {
      describeOpsItemsPaginated.push(...page.OpsItemSummaries);
    }
    console.log("Here are the ops items:");
    console.log(describeOpsItemsPaginated);
    return { OpsItemSummaries: describeOpsItemsPaginated };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MissingParameter") {
      console.warn(`${caught.message}. Did you provide this value?`);
    }
    throw caught;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DescribeOpsItems](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/DescribeOpsItemsCommand)」を参照してください。

### `ListCommandInvocations`
<a name="ssm_ListCommandInvocations_javascript_3_topic"></a>

次のコード例は、`ListCommandInvocations` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { paginateListCommandInvocations, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * List SSM command invocations on an instance.
 * @param {{ instanceId: string }}
 */
export const main = async ({ instanceId }) => {
  const client = new SSMClient({});
  try {
    const listCommandInvocationsPaginated = [];
    // The paginate function is a wrapper around the base command.
    const paginator = paginateListCommandInvocations(
      { client },
      {
        InstanceId: instanceId,
      },
    );
    for await (const page of paginator) {
      listCommandInvocationsPaginated.push(...page.CommandInvocations);
    }
    console.log("Here is the list of command invocations:");
    console.log(listCommandInvocationsPaginated);
    return { CommandInvocations: listCommandInvocationsPaginated };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ValidationError") {
      console.warn(`${caught.message}. Did you provide a valid instance ID?`);
    }
    throw caught;
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListCommandInvocations](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/ListCommandInvocationsCommand)」を参照してください。

### `SendCommand`
<a name="ssm_SendCommand_javascript_3_topic"></a>

次のコード例は、`SendCommand` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { SendCommandCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Send an SSM command to a managed node.
 * @param {{ documentName: string }}
 */
export const main = async ({ documentName }) => {
  const client = new SSMClient({});
  try {
    await client.send(
      new SendCommandCommand({
        DocumentName: documentName,
      }),
    );
    console.log("Command sent successfully.");
    return { Success: true };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ValidationError") {
      console.warn(`${caught.message}. Did you provide a valid document name?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[SendCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/SendCommandCommand)」を参照してください。

### `UpdateMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_javascript_3_topic"></a>

次のコード例は、`UpdateMaintenanceWindow` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { UpdateMaintenanceWindowCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Update an SSM maintenance window.
 * @param {{ windowId: string, allowUnassociatedTargets?: boolean, duration?: number, enabled?: boolean, name?: string, schedule?: string }}
 */
export const main = async ({
  windowId,
  allowUnassociatedTargets = undefined, //Allow the maintenance window to run on managed nodes, even if you haven't registered those nodes as targets.
  duration = undefined, //The duration of the maintenance window in hours.
  enabled = undefined,
  name = undefined,
  schedule = undefined, //The schedule of the maintenance window in the form of a cron or rate expression.
}) => {
  const client = new SSMClient({});
  try {
    const { opsItemArn, opsItemId } = await client.send(
      new UpdateMaintenanceWindowCommand({
        WindowId: windowId,
        AllowUnassociatedTargets: allowUnassociatedTargets,
        Duration: duration,
        Enabled: enabled,
        Name: name,
        Schedule: schedule,
      }),
    );
    console.log("Maintenance window updated.");
    return { OpsItemArn: opsItemArn, OpsItemId: opsItemId };
  } catch (caught) {
    if (caught instanceof Error && caught.name === "ValidationError") {
      console.warn(`${caught.message}. Are these values correct?`);
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、*AWS SDK for JavaScript API リファレンス*の「[UpdateMaintenanceWindow](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/UpdateMaintenanceWindowCommand)」を参照してください。

### `UpdateOpsItem`
<a name="ssm_UpdateOpsItem_javascript_3_topic"></a>

次のコード例は、`UpdateOpsItem` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import { UpdateOpsItemCommand, SSMClient } from "@aws-sdk/client-ssm";
import { parseArgs } from "node:util";

/**
 * Update an SSM OpsItem.
 * @param {{ opsItemId: string, status?: OpsItemStatus }}
 */
export const main = async ({
  opsItemId,
  status = undefined, // The OpsItem status. Status can be Open, In Progress, or Resolved
}) => {
  const client = new SSMClient({});
  try {
    await client.send(
      new UpdateOpsItemCommand({
        OpsItemId: opsItemId,
        Status: status,
      }),
    );
    console.log("Ops item updated.");
    return { Success: true };
  } catch (caught) {
    if (
      caught instanceof Error &&
      caught.name === "OpsItemLimitExceededException"
    ) {
      console.warn(
        `Couldn't create ops item because you have exceeded your open OpsItem limit. ${caught.message}.`,
      );
    } else {
      throw caught;
    }
  }
};
```
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[UpdateOpsItem](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/ssm/command/UpdateOpsItemCommand)」を参照してください。

# SDK for JavaScript (v3) を使用した Amazon Textract の例
<a name="javascript_3_textract_code_examples"></a>

次のコード例は、Amazon Textract で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_javascript_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for JavaScript (v3)**  
 を使用して、Amazon Textract を使用してドキュメントイメージからデータを抽出し、インタラクティブなウェブページに表示する React アプリケーション AWS SDK for JavaScript を構築する方法を示します。この例はウェブブラウザで実行され、認証情報に認証された Amazon Cognito ID が必要です。Amazon Simple Storage Service (Amazon S3) をストレージに使用し、通知のために、Amazon Simple Notification Service (Amazon SNS) トピックにサブスクライブした Amazon Simple Queue Service (Amazon SQS) キューをポーリングします。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/textract-react) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_javascript_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for JavaScript (v3)**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer) のプロジェクトを参照してください。次の抜粋は、 AWS SDK for JavaScript が Lambda 関数内でどのように使用されるかを示しています。  

```
import {
  ComprehendClient,
  DetectDominantLanguageCommand,
  DetectSentimentCommand,
} from "@aws-sdk/client-comprehend";

/**
 * Determine the language and sentiment of the extracted text.
 *
 * @param {{ source_text: string}} extractTextOutput
 */
export const handler = async (extractTextOutput) => {
  const comprehendClient = new ComprehendClient({});

  const detectDominantLanguageCommand = new DetectDominantLanguageCommand({
    Text: extractTextOutput.source_text,
  });

  // The source language is required for sentiment analysis and
  // translation in the next step.
  const { Languages } = await comprehendClient.send(
    detectDominantLanguageCommand,
  );

  const languageCode = Languages[0].LanguageCode;

  const detectSentimentCommand = new DetectSentimentCommand({
    Text: extractTextOutput.source_text,
    LanguageCode: languageCode,
  });

  const { Sentiment } = await comprehendClient.send(detectSentimentCommand);

  return {
    sentiment: Sentiment,
    language_code: languageCode,
  };
};
```

```
import {
  DetectDocumentTextCommand,
  TextractClient,
} from "@aws-sdk/client-textract";

/**
 * Fetch the S3 object from the event and analyze it using Amazon Textract.
 *
 * @param {import("@types/aws-lambda").EventBridgeEvent<"Object Created">} eventBridgeS3Event
 */
export const handler = async (eventBridgeS3Event) => {
  const textractClient = new TextractClient();

  const detectDocumentTextCommand = new DetectDocumentTextCommand({
    Document: {
      S3Object: {
        Bucket: eventBridgeS3Event.bucket,
        Name: eventBridgeS3Event.object,
      },
    },
  });

  // Textract returns a list of blocks. A block can be a line, a page, word, etc.
  // Each block also contains geometry of the detected text.
  // For more information on the Block type, see https://docs.aws.amazon.com/textract/latest/dg/API_Block.html.
  const { Blocks } = await textractClient.send(detectDocumentTextCommand);

  // For the purpose of this example, we are only interested in words.
  const extractedWords = Blocks.filter((b) => b.BlockType === "WORD").map(
    (b) => b.Text,
  );

  return extractedWords.join(" ");
};
```

```
import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly";
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

/**
 * Synthesize an audio file from text.
 *
 * @param {{ bucket: string, translated_text: string, object: string}} sourceDestinationConfig
 */
export const handler = async (sourceDestinationConfig) => {
  const pollyClient = new PollyClient({});

  const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
    Engine: "neural",
    Text: sourceDestinationConfig.translated_text,
    VoiceId: "Ruth",
    OutputFormat: "mp3",
  });

  const { AudioStream } = await pollyClient.send(synthesizeSpeechCommand);

  const audioKey = `${sourceDestinationConfig.object}.mp3`;

  // Store the audio file in S3.
  const s3Client = new S3Client();
  const upload = new Upload({
    client: s3Client,
    params: {
      Bucket: sourceDestinationConfig.bucket,
      Key: audioKey,
      Body: AudioStream,
      ContentType: "audio/mp3",
    },
  });

  await upload.done();
  return audioKey;
};
```

```
import {
  TranslateClient,
  TranslateTextCommand,
} from "@aws-sdk/client-translate";

/**
 * Translate the extracted text to English.
 *
 * @param {{ extracted_text: string, source_language_code: string}} textAndSourceLanguage
 */
export const handler = async (textAndSourceLanguage) => {
  const translateClient = new TranslateClient({});

  const translateCommand = new TranslateTextCommand({
    SourceLanguageCode: textAndSourceLanguage.source_language_code,
    TargetLanguageCode: "en",
    Text: textAndSourceLanguage.extracted_text,
  });

  const { TranslatedText } = await translateClient.send(translateCommand);

  return { translated_text: TranslatedText };
};
```

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for JavaScript (v3) を使用した Amazon Transcribe の例
<a name="javascript_3_transcribe_code_examples"></a>

次のコード例は、Amazon Transcribe で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DeleteMedicalTranscriptionJob`
<a name="transcribe_DeleteMedicalTranscriptionJob_javascript_3_topic"></a>

次のコード例は、`DeleteMedicalTranscriptionJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```
医療分野の文字起こしジョブを削除します。  

```
// Import the required AWS SDK clients and commands for Node.js
import { DeleteMedicalTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  MedicalTranscriptionJobName: "MEDICAL_JOB_NAME", // For example, 'medical_transciption_demo'
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new DeleteMedicalTranscriptionJobCommand(params),
    );
    console.log("Success - deleted");
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-medical-examples-section.html#transcribe-delete-medical-job)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteMedicalTranscriptionJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/transcribe/command/DeleteMedicalTranscriptionJobCommand)」を参照してください。

### `DeleteTranscriptionJob`
<a name="transcribe_DeleteTranscriptionJob_javascript_3_topic"></a>

次のコード例は、`DeleteTranscriptionJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
文字起こしジョブを削除します。  

```
// Import the required AWS SDK clients and commands for Node.js
import { DeleteTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  TranscriptionJobName: "JOB_NAME", // Required. For example, 'transciption_demo'
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new DeleteTranscriptionJobCommand(params),
    );
    console.log("Success - deleted");
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
クライアントを作成します。  

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-examples-section.html#transcribe-delete-job)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[DeleteTranscriptionJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/transcribe/command/DeleteTranscriptionJobCommand)」を参照してください。

### `ListMedicalTranscriptionJobs`
<a name="transcribe_ListMedicalTranscriptionJobs_javascript_3_topic"></a>

次のコード例は、`ListMedicalTranscriptionJobs` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```
医療分野の文字起こしジョブを一覧表示します。  

```
// Import the required AWS SDK clients and commands for Node.js
import { StartMedicalTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  MedicalTranscriptionJobName: "MEDICAL_JOB_NAME", // Required
  OutputBucketName: "OUTPUT_BUCKET_NAME", // Required
  Specialty: "PRIMARYCARE", // Required. Possible values are 'PRIMARYCARE'
  Type: "JOB_TYPE", // Required. Possible values are 'CONVERSATION' and 'DICTATION'
  LanguageCode: "LANGUAGE_CODE", // For example, 'en-US'
  MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav'
  Media: {
    MediaFileUri: "SOURCE_FILE_LOCATION",
    // The S3 object location of the input media file. The URI must be in the same region
    // as the API endpoint that you are calling.For example,
    // "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav"
  },
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new StartMedicalTranscriptionJobCommand(params),
    );
    console.log("Success - put", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-medical-examples-section.html#transcribe-list-medical-jobs)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListMedicalTranscriptionJobs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/transcribe/command/ListMedicalTranscriptionJobsCommand)」を参照してください。

### `ListTranscriptionJobs`
<a name="transcribe_ListTranscriptionJobs_javascript_3_topic"></a>

次のコード例は、`ListTranscriptionJobs` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
文字起こしジョブを一覧表示します。  

```
// Import the required AWS SDK clients and commands for Node.js

import { ListTranscriptionJobsCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  JobNameContains: "KEYWORD", // Not required. Returns only transcription
  // job names containing this string
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new ListTranscriptionJobsCommand(params),
    );
    console.log("Success", data.TranscriptionJobSummaries);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
クライアントを作成します。  

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-examples-section.html#transcribe-list-jobs)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[ListTranscriptionJobs](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/transcribe/command/ListTranscriptionJobsCommand)」を参照してください。

### `StartMedicalTranscriptionJob`
<a name="transcribe_StartMedicalTranscriptionJob_javascript_3_topic"></a>

次のコード例は、`StartMedicalTranscriptionJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
クライアントを作成します。  

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```
医療分野の文字起こしジョブを開始します。  

```
// Import the required AWS SDK clients and commands for Node.js
import { StartMedicalTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  MedicalTranscriptionJobName: "MEDICAL_JOB_NAME", // Required
  OutputBucketName: "OUTPUT_BUCKET_NAME", // Required
  Specialty: "PRIMARYCARE", // Required. Possible values are 'PRIMARYCARE'
  Type: "JOB_TYPE", // Required. Possible values are 'CONVERSATION' and 'DICTATION'
  LanguageCode: "LANGUAGE_CODE", // For example, 'en-US'
  MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav'
  Media: {
    MediaFileUri: "SOURCE_FILE_LOCATION",
    // The S3 object location of the input media file. The URI must be in the same region
    // as the API endpoint that you are calling.For example,
    // "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav"
  },
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new StartMedicalTranscriptionJobCommand(params),
    );
    console.log("Success - put", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-medical-examples-section.html#transcribe-start-medical-transcription)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[StartMedicalTranscriptionJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/transcribe/command/StartMedicalTranscriptionJobCommand)」を参照してください。

### `StartTranscriptionJob`
<a name="transcribe_StartTranscriptionJob_javascript_3_topic"></a>

次のコード例は、`StartTranscriptionJob` を使用する方法を示しています。

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
文字起こしジョブを開始します。  

```
// Import the required AWS SDK clients and commands for Node.js
import { StartTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  TranscriptionJobName: "JOB_NAME",
  LanguageCode: "LANGUAGE_CODE", // For example, 'en-US'
  MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav'
  Media: {
    MediaFileUri: "SOURCE_LOCATION",
    // For example, "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav"
  },
  OutputBucketName: "OUTPUT_BUCKET_NAME",
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new StartTranscriptionJobCommand(params),
    );
    console.log("Success - put", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```
クライアントを作成します。  

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/transcribe-examples-section.html#transcribe-start-transcription)」を参照してください。
+  API の詳細については、「*AWS SDK for JavaScript API リファレンス*」の「[StartTranscriptionJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/transcribe/command/StartTranscriptionJobCommand)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Transcribe ストリーミングアプリケーションを構築する
<a name="cross_TranscriptionStreamingApp_javascript_3_topic"></a>

次のコード例は、ライブ音声をリアルタイムで記録、転写、翻訳し、結果を E メールで送信するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 Amazon Transcribe を使用して、ライブ音声をリアルタイムで記録、転写、翻訳し、Amazon Simple Email Service (Amazon SES) を使用して結果を E メールで送信するアプリケーションを構築する方法について説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/transcribe-streaming-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SES
+ Amazon Transcribe
+ Amazon Translate

# SDK for JavaScript (v3) を使用した Amazon Translate の例
<a name="javascript_3_translate_code_examples"></a>

次のコード例は、Amazon Translate で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Transcribe ストリーミングアプリケーションを構築する
<a name="cross_TranscriptionStreamingApp_javascript_3_topic"></a>

次のコード例は、ライブ音声をリアルタイムで記録、転写、翻訳し、結果を E メールで送信するアプリケーションを構築する方法を示しています。

**SDK for JavaScript (v3)**  
 Amazon Transcribe を使用して、ライブ音声をリアルタイムで記録、転写、翻訳し、Amazon Simple Email Service (Amazon SES) を使用して結果を E メールで送信するアプリケーションを構築する方法について説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/transcribe-streaming-app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SES
+ Amazon Transcribe
+ Amazon Translate

### Amazon Lex チャットボットを構築する
<a name="cross_LexChatbotLanguages_javascript_3_topic"></a>

次のコード例は、ウェブサイトの訪問者を引き付けるチャットボットの作成方法を示しています。

**SDK for JavaScript (v3)**  
 Amazon Lex API を使用して、ウェブアプリケーション内にチャットボットを作成し、Web サイトの訪問者と交流する方法を説明します。  
 完全なソースコードとセットアップと実行の手順については、 デ AWS SDK for JavaScript ベロッパーガイドの[Amazon Lexチャットボットの構築](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/lex-bot-example.html)」の完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon Lex
+ Amazon Translate

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_javascript_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for JavaScript (v3)**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/feedback-sentiment-analyzer) のプロジェクトを参照してください。次の抜粋は、 AWS SDK for JavaScript が Lambda 関数内でどのように使用されるかを示しています。  

```
import {
  ComprehendClient,
  DetectDominantLanguageCommand,
  DetectSentimentCommand,
} from "@aws-sdk/client-comprehend";

/**
 * Determine the language and sentiment of the extracted text.
 *
 * @param {{ source_text: string}} extractTextOutput
 */
export const handler = async (extractTextOutput) => {
  const comprehendClient = new ComprehendClient({});

  const detectDominantLanguageCommand = new DetectDominantLanguageCommand({
    Text: extractTextOutput.source_text,
  });

  // The source language is required for sentiment analysis and
  // translation in the next step.
  const { Languages } = await comprehendClient.send(
    detectDominantLanguageCommand,
  );

  const languageCode = Languages[0].LanguageCode;

  const detectSentimentCommand = new DetectSentimentCommand({
    Text: extractTextOutput.source_text,
    LanguageCode: languageCode,
  });

  const { Sentiment } = await comprehendClient.send(detectSentimentCommand);

  return {
    sentiment: Sentiment,
    language_code: languageCode,
  };
};
```

```
import {
  DetectDocumentTextCommand,
  TextractClient,
} from "@aws-sdk/client-textract";

/**
 * Fetch the S3 object from the event and analyze it using Amazon Textract.
 *
 * @param {import("@types/aws-lambda").EventBridgeEvent<"Object Created">} eventBridgeS3Event
 */
export const handler = async (eventBridgeS3Event) => {
  const textractClient = new TextractClient();

  const detectDocumentTextCommand = new DetectDocumentTextCommand({
    Document: {
      S3Object: {
        Bucket: eventBridgeS3Event.bucket,
        Name: eventBridgeS3Event.object,
      },
    },
  });

  // Textract returns a list of blocks. A block can be a line, a page, word, etc.
  // Each block also contains geometry of the detected text.
  // For more information on the Block type, see https://docs.aws.amazon.com/textract/latest/dg/API_Block.html.
  const { Blocks } = await textractClient.send(detectDocumentTextCommand);

  // For the purpose of this example, we are only interested in words.
  const extractedWords = Blocks.filter((b) => b.BlockType === "WORD").map(
    (b) => b.Text,
  );

  return extractedWords.join(" ");
};
```

```
import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly";
import { S3Client } from "@aws-sdk/client-s3";
import { Upload } from "@aws-sdk/lib-storage";

/**
 * Synthesize an audio file from text.
 *
 * @param {{ bucket: string, translated_text: string, object: string}} sourceDestinationConfig
 */
export const handler = async (sourceDestinationConfig) => {
  const pollyClient = new PollyClient({});

  const synthesizeSpeechCommand = new SynthesizeSpeechCommand({
    Engine: "neural",
    Text: sourceDestinationConfig.translated_text,
    VoiceId: "Ruth",
    OutputFormat: "mp3",
  });

  const { AudioStream } = await pollyClient.send(synthesizeSpeechCommand);

  const audioKey = `${sourceDestinationConfig.object}.mp3`;

  // Store the audio file in S3.
  const s3Client = new S3Client();
  const upload = new Upload({
    client: s3Client,
    params: {
      Bucket: sourceDestinationConfig.bucket,
      Key: audioKey,
      Body: AudioStream,
      ContentType: "audio/mp3",
    },
  });

  await upload.done();
  return audioKey;
};
```

```
import {
  TranslateClient,
  TranslateTextCommand,
} from "@aws-sdk/client-translate";

/**
 * Translate the extracted text to English.
 *
 * @param {{ extracted_text: string, source_language_code: string}} textAndSourceLanguage
 */
export const handler = async (textAndSourceLanguage) => {
  const translateClient = new TranslateClient({});

  const translateCommand = new TranslateTextCommand({
    SourceLanguageCode: textAndSourceLanguage.source_language_code,
    TargetLanguageCode: "en",
    Text: textAndSourceLanguage.extracted_text,
  });

  const { TranslatedText } = await translateClient.send(translateCommand);

  return { translated_text: TranslatedText };
};
```

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Java 2.x のコード例
<a name="java_2_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for Java 2.x デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/home.html) ** – で Java を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23java)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](java_2_acm_code_examples.md)
+ [API ゲートウェイ](java_2_api-gateway_code_examples.md)
+ [Application Auto Scaling](java_2_application-auto-scaling_code_examples.md)
+ [Application Recovery Controller](java_2_route53-recovery-cluster_code_examples.md)
+ [Aurora](java_2_aurora_code_examples.md)
+ [Auto Scaling](java_2_auto-scaling_code_examples.md)
+ [AWS Batch](java_2_batch_code_examples.md)
+ [Amazon Bedrock](java_2_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](java_2_bedrock-runtime_code_examples.md)
+ [CloudFront](java_2_cloudfront_code_examples.md)
+ [CloudWatch](java_2_cloudwatch_code_examples.md)
+ [CloudWatch Events](java_2_cloudwatch-events_code_examples.md)
+ [CloudWatch Logs](java_2_cloudwatch-logs_code_examples.md)
+ [Amazon Cognito ID](java_2_cognito-identity_code_examples.md)
+ [Amazon Cognito ID プロバイダー](java_2_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](java_2_comprehend_code_examples.md)
+ [AWS Control Tower](java_2_controltower_code_examples.md)
+ [Firehose](java_2_firehose_code_examples.md)
+ [Amazon DocumentDB](java_2_docdb_code_examples.md)
+ [DynamoDB](java_2_dynamodb_code_examples.md)
+ [Amazon EC2](java_2_ec2_code_examples.md)
+ [Amazon ECR](java_2_ecr_code_examples.md)
+ [Amazon ECS](java_2_ecs_code_examples.md)
+ [Elastic Load Balancing - バージョン 2](java_2_elastic-load-balancing-v2_code_examples.md)
+ [MediaStore](java_2_mediastore_code_examples.md)
+ [AWS Entity Resolution](java_2_entityresolution_code_examples.md)
+ [OpenSearch Service](java_2_opensearch_code_examples.md)
+ [EventBridge](java_2_eventbridge_code_examples.md)
+ [EventBridge スケジューラ](java_2_scheduler_code_examples.md)
+ [Forecast](java_2_forecast_code_examples.md)
+ [Amazon Glacier](java_2_glacier_code_examples.md)
+ [AWS Glue](java_2_glue_code_examples.md)
+ [HealthImaging](java_2_medical-imaging_code_examples.md)
+ [IAM](java_2_iam_code_examples.md)
+ [Amazon Inspector](java_2_inspector_code_examples.md)
+ [AWS IoT](java_2_iot_code_examples.md)
+ [AWS IoT data](java_2_iot-data-plane_code_examples.md)
+ [AWS IoT FleetWise](java_2_iotfleetwise_code_examples.md)
+ [AWS IoT SiteWise](java_2_iotsitewise_code_examples.md)
+ [Amazon Keyspaces](java_2_keyspaces_code_examples.md)
+ [Kinesis](java_2_kinesis_code_examples.md)
+ [AWS KMS](java_2_kms_code_examples.md)
+ [Lambda](java_2_lambda_code_examples.md)
+ [Amazon Lex](java_2_lex_code_examples.md)
+ [Amazon Location](java_2_location_code_examples.md)
+ [Location Service Places](java_2_geo-places_code_examples.md)
+ [AWS Marketplace カタログ API](java_2_marketplace-catalog_code_examples.md)
+ [AWS Marketplace 契約 API](java_2_marketplace-agreement_code_examples.md)
+ [MediaConvert](java_2_mediaconvert_code_examples.md)
+ [Migration Hub](java_2_migration-hub_code_examples.md)
+ [Amazon MSK](java_2_kafka_code_examples.md)
+ [Neptune](java_2_neptune_code_examples.md)
+ [パートナーセントラル](java_2_partnercentral-selling_code_examples.md)
+ [Amazon Personalize](java_2_personalize_code_examples.md)
+ [Amazon Personalize Events](java_2_personalize-events_code_examples.md)
+ [Amazon Personalize Runtime](java_2_personalize-runtime_code_examples.md)
+ [Amazon Pinpoint](java_2_pinpoint_code_examples.md)
+ [Amazon Pinpoint SMS および音声 API](java_2_pinpoint-sms-voice_code_examples.md)
+ [Amazon Polly](java_2_polly_code_examples.md)
+ [Amazon RDS](java_2_rds_code_examples.md)
+ [Amazon RDS データサービス](java_2_rds-data_code_examples.md)
+ [Amazon Redshift](java_2_redshift_code_examples.md)
+ [Amazon Rekognition](java_2_rekognition_code_examples.md)
+ [Route 53 ドメイン登録](java_2_route-53-domains_code_examples.md)
+ [Amazon S3](java_2_s3_code_examples.md)
+ [Amazon S3 Control](java_2_s3-control_code_examples.md)
+ [S3 ディレクトリバケット](java_2_s3-directory-buckets_code_examples.md)
+ [SageMaker AI](java_2_sagemaker_code_examples.md)
+ [Secrets Manager](java_2_secrets-manager_code_examples.md)
+ [Amazon SES](java_2_ses_code_examples.md)
+ [Amazon SES API v2](java_2_sesv2_code_examples.md)
+ [Amazon SNS](java_2_sns_code_examples.md)
+ [Amazon SQS](java_2_sqs_code_examples.md)
+ [ステップ関数](java_2_sfn_code_examples.md)
+ [AWS STS](java_2_sts_code_examples.md)
+ [サポート](java_2_support_code_examples.md)
+ [Systems Manager](java_2_ssm_code_examples.md)
+ [Amazon Textract](java_2_textract_code_examples.md)
+ [Amazon Transcribe](java_2_transcribe_code_examples.md)
+ [Amazon Transcribe ストリーミング](java_2_transcribe-streaming_code_examples.md)
+ [Amazon Translate](java_2_translate_code_examples.md)

# SDK for Java 2.x を使用した ACM の例
<a name="java_2_acm_code_examples"></a>

次のコード例は、ACM AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AddTagsToCertificate`
<a name="acm_AddTagsToCertificate_java_2_topic"></a>

次のコード例は、`AddTagsToCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class AddTagsToCertificate {

    public static void main(String[] args) {
        final String usage = """

            Usage:    <certArn>

            Where:
                certArn - the ARN of the certificate.
            """;
        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String certArn = args[0];
        addTags(certArn);
    }

    /**
     * Adds tags to a certificate in AWS Certificate Manager (ACM).
     *
     * @param certArn the Amazon Resource Name (ARN) of the certificate to add tags to
     */
    public static void addTags(String certArn) {
        AcmClient acmClient = AcmClient.create();
        List<Tag> expectedTags = List.of(Tag.builder().key("key").value("value").build());
        AddTagsToCertificateRequest addTagsToCertificateRequest = AddTagsToCertificateRequest.builder()
            .certificateArn(certArn)
            .tags(expectedTags)
            .build();

        try {
            acmClient.addTagsToCertificate(addTagsToCertificateRequest);
            System.out.println("Successfully added tags to a certificate");
        } catch (AcmException e) {
            System.out.println(e.getMessage());
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AddTagsToCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/AddTagsToCertificate)」を参照してください。

### `DeleteCertificate`
<a name="acm_DeleteCertificate_java_2_topic"></a>

次のコード例は、`DeleteCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DeleteCert {

    public static void main(String[] args) {
        final String usage = """

            Usage:    <certArn>

            Where:
                certArn - the ARN of the certificate.
            """;
        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String certArn = args[0];
        deleteCertificate(certArn);
    }

    /**
     * Deletes an SSL/TLS certificate from the AWS Certificate Manager (ACM).
     *
     * @param certArn the Amazon Resource Name (ARN) of the certificate to be deleted
     */
    public static void deleteCertificate( String certArn) {
        AcmClient acmClient = AcmClient.create();
        DeleteCertificateRequest request = DeleteCertificateRequest.builder()
            .certificateArn(certArn)
            .build();

        try {
            acmClient.deleteCertificate(request);
            System.out.println("The certificate was deleted");

        } catch (AcmException e) {
            System.out.println(e.getMessage());
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/DeleteCertificate)」を参照してください。

### `DescribeCertificate`
<a name="acm_DescribeCertificate_java_2_topic"></a>

次のコード例は、`DescribeCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class DescribeCert {

    public static void main(String[] args) {
        final String usage = """

            Usage:    <certArn>

            Where:
                certArn - the ARN of the certificate.
            """;
        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String certArn = args[0];
        describeCertificate(certArn);
    }

    /**
     * Describes the details of an SSL/TLS certificate.
     *
     * @param certArn the Amazon Resource Name (ARN) of the certificate to describe
     * @throws AcmException if an error occurs while describing the certificate
     */
    public static void describeCertificate(String certArn) {
        AcmClient acmClient = AcmClient.create();
        DescribeCertificateRequest req = DescribeCertificateRequest.builder()
            .certificateArn(certArn)
            .build();

        try {
            DescribeCertificateResponse response = acmClient.describeCertificate(req);

            // Print the certificate details.
            System.out.println("Certificate ARN: " + response.certificate().certificateArn());
            System.out.println("Domain Name: " + response.certificate().domainName());
            System.out.println("Issued By: " + response.certificate().issuer());
            System.out.println("Issued On: " + response.certificate().issuedAt());
            System.out.println("Status: " + response.certificate().status());
        } catch (AcmException e) {
            System.out.println(e.getMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/DescribeCertificate)」を参照してください。

### `ExportCertificate`
<a name="acm_ExportCertificate_java_2_topic"></a>

次のコード例は、`ExportCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class ExportCertificate {

    public static void main(String[] args) throws Exception {
        final String usage = """

            Usage:    <certArn>

            Where:
                certArn - the ARN of the certificate.
            """;
        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String certArn = args[0];
        exportCert(certArn);
    }

    /**
     * Exports an SSL/TLS certificate and its associated private key and certificate chain from AWS Certificate Manager (ACM).
     *
     * @param certArn The Amazon Resource Name (ARN) of the certificate that you want to export.
     * @throws IOException If an I/O error occurs while reading the private key passphrase file or exporting the certificate.
     */
    public static void exportCert(String certArn) throws IOException {
        AcmClient acmClient = AcmClient.create();

        // Initialize a file descriptor for the passphrase file.
        RandomAccessFile filePassphrase = null;
        ByteBuffer bufPassphrase = null;

        // Create a file stream for reading the private key passphrase.
        try {
            filePassphrase = new RandomAccessFile("C:\\AWS\\password.txt", "r");
        } catch (IllegalArgumentException | SecurityException | FileNotFoundException ex) {
            throw ex;
        }

        // Create a channel to map the file.
        FileChannel channelPassphrase = filePassphrase.getChannel();

        // Map the file to the buffer.
        try {
            bufPassphrase = channelPassphrase.map(FileChannel.MapMode.READ_ONLY, 0, channelPassphrase.size());
            channelPassphrase.close();
            filePassphrase.close();
        } catch (IOException ex) {
            throw ex;
        }

        // Create a request object.
        ExportCertificateRequest req = ExportCertificateRequest.builder()
            .certificateArn(certArn)
            .passphrase(SdkBytes.fromByteBuffer(bufPassphrase))
            .build();

        // Export the certificate.
        ExportCertificateResponse result = null;
        try {
            result = acmClient.exportCertificate(req);
        } catch (InvalidArnException | InvalidTagException | ResourceNotFoundException ex) {
            throw ex;
        }

        // Clear the buffer.
        bufPassphrase.clear();

        // Display the certificate and certificate chain.
        String certificate = result.certificate();
        System.out.println(certificate);

        String certificateChain = result.certificateChain();
        System.out.println(certificateChain);

        // This example retrieves but does not display the private key.
        String privateKey = result.privateKey();
        System.out.println("The example is complete");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の[ExportCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/ExportCertificate)」を参照してください。

### `ImportCertificate`
<a name="acm_ImportCertificate_java_2_topic"></a>

次のコード例は、`ImportCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class ImportCert {

    public static void main(String[] args) {
        final String usage = """
            Usage: <bucketName> <certificateKey> <privateKeyKey>
            
            Where:
                bucketName - The name of the S3 bucket containing the certificate and private key.
                certificateKey - The object key for the SSL/TLS certificate file in S3.
                privateKeyKey - The object key for the private key file in S3.
            """;

        if (args.length != 3) {
            System.out.println(usage);
            return;
        }

        String bucketName = args[0];
        String certificateKey = args[1];
        String privateKeyKey = args[2];

        String certificateArn = importCertificate(bucketName, certificateKey, privateKeyKey);
        System.out.println("Certificate imported with ARN: " + certificateArn);
    }

    /**
     * Imports an SSL/TLS certificate and private key from S3 into AWS Certificate Manager (ACM).
     *
     * @param bucketName     The name of the S3 bucket.
     * @param certificateKey The key for the SSL/TLS certificate file in S3.
     * @param privateKeyKey  The key for the private key file in S3.
     * @return The ARN of the imported certificate.
     */
    public static String importCertificate(String bucketName, String certificateKey, String privateKeyKey) {
        AcmClient acmClient = AcmClient.create();
        S3Client s3Client = S3Client.create();

        try {
            byte[] certificateBytes = downloadFileFromS3(s3Client, bucketName, certificateKey);
            byte[] privateKeyBytes = downloadFileFromS3(s3Client, bucketName, privateKeyKey);

            ImportCertificateRequest request = ImportCertificateRequest.builder()
                    .certificate(SdkBytes.fromByteBuffer(ByteBuffer.wrap(certificateBytes)))
                    .privateKey(SdkBytes.fromByteBuffer(ByteBuffer.wrap(privateKeyBytes)))
                    .build();

            ImportCertificateResponse response = acmClient.importCertificate(request);
            return response.certificateArn();

        } catch (IOException e) {
            System.err.println("Error downloading certificate or private key from S3: " + e.getMessage());
        } catch (S3Exception e) {
            System.err.println("S3 error: " + e.awsErrorDetails().errorMessage());
        }
        return "";
    }

    /**
     * Downloads a file from Amazon S3 and returns its contents as a byte array.
     *
     * @param s3Client   The S3 client.
     * @param bucketName The name of the S3 bucket.
     * @param objectKey  The key of the object in S3.
     * @return The file contents as a byte array.
     * @throws IOException If an I/O error occurs.
     */
    private static byte[] downloadFileFromS3(S3Client s3Client, String bucketName, String objectKey) throws IOException {
        GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .build();

        try (ResponseInputStream<GetObjectResponse> s3Object = s3Client.getObject(getObjectRequest);
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            IoUtils.copy(s3Object, byteArrayOutputStream);
            return byteArrayOutputStream.toByteArray();
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[ImportCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/ImportCertificate)」を参照してください。

### `ListCertificates`
<a name="acm_ListCertificates_java_2_topic"></a>

次のコード例は、`ListCertificates` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class ListCerts {
    public static void main(String[] args) {
        listCertificates();
    }

    /**
     * Lists all the certificates managed by AWS Certificate Manager (ACM) that have a status of "ISSUED".
     */
    public static void listCertificates() {
        AcmClient acmClient = AcmClient.create();
        try {
            ListCertificatesRequest listRequest = ListCertificatesRequest.builder()
                .certificateStatuses(CertificateStatus.ISSUED)
                .maxItems(100)
                .build();
            ListCertificatesIterable listResponse = acmClient.listCertificatesPaginator(listRequest);

            // Print the certificate details using streams
            listResponse.certificateSummaryList().stream()
                .forEach(certificate -> {
                    System.out.println("Certificate ARN: " + certificate.certificateArn());
                    System.out.println("Certificate Domain Name: " + certificate.domainName());
                    System.out.println("Certificate Status: " + certificate.statusAsString());
                    System.out.println("---");
                });

        } catch (AcmException e) {
            System.err.println(e.getMessage());
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンスの*「[ListCertificates](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/ListCertificates)」を参照してください。

### `ListTagsForCertificate`
<a name="acm_ListTagsForCertificate_java_2_topic"></a>

次のコード例は、`ListTagsForCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class ListCertTags {

    public static void main(String[] args) {

        final String usage = """

            Usage:    <certArn>

            Where:
                certArn - the ARN of the certificate.
            """;
        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String certArn = args[0];
        listCertTags(certArn);
    }

    /**
     * Lists the tags associated with an AWS Certificate Manager (ACM) certificate.
     *
     * @param certArn the Amazon Resource Name (ARN) of the ACM certificate
     */
    public static void listCertTags(String certArn) {
        AcmClient acmClient = AcmClient.create();

        ListTagsForCertificateRequest request = ListTagsForCertificateRequest.builder()
            .certificateArn(certArn)
            .build();

        ListTagsForCertificateResponse response = acmClient.listTagsForCertificate(request);
        List<Tag> tagList = response.tags();
        tagList.forEach(tag -> {
            System.out.println("Key: " + tag.key());
            System.out.println("Value: " + tag.value());
        });
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListTagsForCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/ListTagsForCertificate)」を参照してください。

### `RemoveTagsFromCertificate`
<a name="acm_RemoveTagsFromCertificate_java_2_topic"></a>

次のコード例は、`RemoveTagsFromCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class RemoveTagsFromCert {

    public static void main(String[] args) {
        final String usage = """

            Usage:    <certArn>

            Where:
                certArn - the ARN of the certificate.
            """;
        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String certArn = args[0];
        removeTags(certArn);
    }

    /**
     * Removes tags from an AWS Certificate Manager (ACM) certificate.
     *
     * @param certArn the Amazon Resource Name (ARN) of the certificate from which to remove tags
     */
    public static void removeTags(String certArn) {
        AcmClient acmClient = AcmClient.create();
        List<Tag> expectedTags = List.of(Tag.builder().key("key").value("value").build());
        RemoveTagsFromCertificateRequest req = RemoveTagsFromCertificateRequest.builder()
            .certificateArn(certArn)
            .tags(expectedTags)
            .build();

        try {
            acmClient.removeTagsFromCertificate(req);
            System.out.println("Successfully removed tags from the certificate");
        } catch (AcmException e) {
            System.err.println(e.getMessage());
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[RemoveTagsFromCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/RemoveTagsFromCertificate)」を参照してください。

### `RenewCertificate`
<a name="acm_RenewCertificate_java_2_topic"></a>

次のコード例は、`RenewCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class RenewCert {
    public static void main(String[] args) {
        final String usage = """

            Usage:    <certArn>

            Where:
                certArn - the ARN of the certificate.
            """;
        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String certArn = args[0];
        renewCertificate(certArn);
    }

    /**
     * Renews an existing SSL/TLS certificate in AWS Certificate Manager (ACM).
     *
     * @param certArn The Amazon Resource Name (ARN) of the certificate to be renewed.
     * @throws AcmException If there is an error renewing the certificate.
     */
    public static void renewCertificate(String certArn) {
        AcmClient acmClient = AcmClient.create();

        RenewCertificateRequest certificateRequest = RenewCertificateRequest.builder()
            .certificateArn(certArn)
            .build();

        try {
            acmClient.renewCertificate(certificateRequest);
            System.out.println("The certificate was renewed");
        } catch(AcmException e){
            System.out.println(e.getMessage());
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[RenewCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/RenewCertificate)」を参照してください。

### `RequestCertificate`
<a name="acm_RequestCertificate_java_2_topic"></a>

次のコード例は、`RequestCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class RequestCert {

    public static void main(String[] args) {
        requestCertificate();
    }

    /**
     * Requests a certificate from the AWS Certificate Manager (ACM) service.
     */
    public static void requestCertificate() {
        AcmClient acmClient = AcmClient.create();
        ArrayList<String> san = new ArrayList<>();
        san.add("www.example.com");

        RequestCertificateRequest req = RequestCertificateRequest.builder()
            .domainName("example.com")
            .idempotencyToken("1Aq25pTy")
            .subjectAlternativeNames(san)
            .build();

        try {
            RequestCertificateResponse response = acmClient.requestCertificate(req);
            System.out.println("Cert ARN IS " + response.certificateArn());
        } catch (AcmException e) {
            System.err.println(e.getMessage());
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[RequestCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/acm-2015-12-08/RequestCertificate)」を参照してください。

# SDK for Java 2.x を使用した API Gateway の例
<a name="java_2_api-gateway_code_examples"></a>

次のコード例は、 API Gateway AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## アクション
<a name="actions"></a>

### `CreateDeployment`
<a name="api-gateway_CreateDeployment_java_2_topic"></a>

次のコード例は、`CreateDeployment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/apigateway#code-examples)での設定と実行の方法を確認してください。

```
    public static String createNewDeployment(ApiGatewayClient apiGateway, String restApiId, String stageName) {

        try {
            CreateDeploymentRequest request = CreateDeploymentRequest.builder()
                    .restApiId(restApiId)
                    .description("Created using the AWS API Gateway Java API")
                    .stageName(stageName)
                    .build();

            CreateDeploymentResponse response = apiGateway.createDeployment(request);
            System.out.println("The id of the deployment is " + response.id());
            return response.id();

        } catch (ApiGatewayException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/apigateway-2015-07-09/CreateDeployment)」の「*CreateCollection*」を参照してください。

### `CreateRestApi`
<a name="api-gateway_CreateRestApi_java_2_topic"></a>

次のコード例は、`CreateRestApi` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/apigateway#code-examples)での設定と実行の方法を確認してください。

```
    public static String createAPI(ApiGatewayClient apiGateway, String restApiId, String restApiName) {

        try {
            CreateRestApiRequest request = CreateRestApiRequest.builder()
                    .cloneFrom(restApiId)
                    .description("Created using the Gateway Java API")
                    .name(restApiName)
                    .build();

            CreateRestApiResponse response = apiGateway.createRestApi(request);
            System.out.println("The id of the new api is " + response.id());
            return response.id();

        } catch (ApiGatewayException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateRestApi](https://docs.aws.amazon.com/goto/SdkForJavaV2/apigateway-2015-07-09/CreateRestApi)」を参照してください。

### `DeleteDeployment`
<a name="api-gateway_DeleteDeployment_java_2_topic"></a>

次のコード例は、`DeleteDeployment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/apigateway#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteSpecificDeployment(ApiGatewayClient apiGateway, String restApiId, String deploymentId) {

        try {
            DeleteDeploymentRequest request = DeleteDeploymentRequest.builder()
                    .restApiId(restApiId)
                    .deploymentId(deploymentId)
                    .build();

            apiGateway.deleteDeployment(request);
            System.out.println("Deployment was deleted");

        } catch (ApiGatewayException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteDeployment](https://docs.aws.amazon.com/goto/SdkForJavaV2/apigateway-2015-07-09/DeleteDeployment)」を参照してください。

### `DeleteRestApi`
<a name="api-gateway_DeleteRestApi_java_2_topic"></a>

次のコード例は、`DeleteRestApi` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/apigateway#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteAPI(ApiGatewayClient apiGateway, String restApiId) {

        try {
            DeleteRestApiRequest request = DeleteRestApiRequest.builder()
                    .restApiId(restApiId)
                    .build();

            apiGateway.deleteRestApi(request);
            System.out.println("The API was successfully deleted");

        } catch (ApiGatewayException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteRestApi](https://docs.aws.amazon.com/goto/SdkForJavaV2/apigateway-2015-07-09/DeleteRestApi)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_java_2_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Java 2.x**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_java_2_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 Lambda Java ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_apigateway) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_java_2_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Java 2.x**  
 Java SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-java-frameworks-samples) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Java 2.x を使用したアプリケーションの自動スケーリングの例
<a name="java_2_application-auto-scaling_code_examples"></a>

次のコード例は、Application Auto Scaling AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteScalingPolicy`
<a name="application-auto-scaling_DeleteScalingPolicy_java_2_topic"></a>

次のコード例は、`DeleteScalingPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/appautoscale#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException;
import software.amazon.awssdk.services.applicationautoscaling.model.DeleteScalingPolicyRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DeregisterScalableTargetRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension;
import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace;

/**
 * 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 DisableDynamoDBAutoscaling {
    public static void main(String[] args) {
        final String usage = """

            Usage:
               <tableId> <policyName>\s

            Where:
               tableId - The table Id value (for example, table/Music).\s
               policyName - The name of the policy (for example, $Music5-scaling-policy). 
        
            """;
        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        ApplicationAutoScalingClient appAutoScalingClient = ApplicationAutoScalingClient.builder()
            .region(Region.US_EAST_1)
            .build();

        ServiceNamespace ns = ServiceNamespace.DYNAMODB;
        ScalableDimension tableWCUs = ScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS;
        String tableId = args[0];
        String policyName = args[1];

        deletePolicy(appAutoScalingClient, policyName, tableWCUs, ns, tableId);
        verifyScalingPolicies(appAutoScalingClient, tableId, ns, tableWCUs);
        deregisterScalableTarget(appAutoScalingClient, tableId, ns, tableWCUs);
        verifyTarget(appAutoScalingClient, tableId, ns, tableWCUs);
    }

    public static void deletePolicy(ApplicationAutoScalingClient appAutoScalingClient, String policyName, ScalableDimension tableWCUs, ServiceNamespace ns, String tableId) {
        try {
            DeleteScalingPolicyRequest delSPRequest = DeleteScalingPolicyRequest.builder()
                .policyName(policyName)
                .scalableDimension(tableWCUs)
                .serviceNamespace(ns)
                .resourceId(tableId)
                .build();

            appAutoScalingClient.deleteScalingPolicy(delSPRequest);
            System.out.println(policyName +" was deleted successfully.");

        } catch (ApplicationAutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    // Verify that the scaling policy was deleted
    public static void verifyScalingPolicies(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        DescribeScalingPoliciesRequest dscRequest = DescribeScalingPoliciesRequest.builder()
            .scalableDimension(tableWCUs)
            .serviceNamespace(ns)
            .resourceId(tableId)
            .build();

        DescribeScalingPoliciesResponse response = appAutoScalingClient.describeScalingPolicies(dscRequest);
        System.out.println("DescribeScalableTargets result: ");
        System.out.println(response);
    }

    public static void deregisterScalableTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        try {
            DeregisterScalableTargetRequest targetRequest = DeregisterScalableTargetRequest.builder()
                .scalableDimension(tableWCUs)
                .serviceNamespace(ns)
                .resourceId(tableId)
                .build();

            appAutoScalingClient.deregisterScalableTarget(targetRequest);
            System.out.println("The scalable target was deregistered.");

        } catch (ApplicationAutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    public static void verifyTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        DescribeScalableTargetsRequest dscRequest = DescribeScalableTargetsRequest.builder()
            .scalableDimension(tableWCUs)
            .serviceNamespace(ns)
            .resourceIds(tableId)
            .build();

        DescribeScalableTargetsResponse response = appAutoScalingClient.describeScalableTargets(dscRequest);
        System.out.println("DescribeScalableTargets result: ");
        System.out.println(response);
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteScalingPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/application-autoscaling-2016-02-06/DeleteScalingPolicy)」を参照してください。

### `RegisterScalableTarget`
<a name="application-auto-scaling_RegisterScalableTarget_java_2_topic"></a>

次のコード例は、`RegisterScalableTarget` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/appautoscale#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.PolicyType;
import software.amazon.awssdk.services.applicationautoscaling.model.PredefinedMetricSpecification;
import software.amazon.awssdk.services.applicationautoscaling.model.PutScalingPolicyRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.RegisterScalableTargetRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalingPolicy;
import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension;
import software.amazon.awssdk.services.applicationautoscaling.model.MetricType;
import software.amazon.awssdk.services.applicationautoscaling.model.TargetTrackingScalingPolicyConfiguration;
import java.util.List;

/**
 * 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 EnableDynamoDBAutoscaling {
    public static void main(String[] args) {
        final String usage = """

            Usage:
               <tableId> <roleARN> <policyName>\s

            Where:
               tableId - The table Id value (for example, table/Music).
               roleARN - The ARN of the role that has ApplicationAutoScaling permissions.
               policyName - The name of the policy to create.
               
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        System.out.println("This example registers an Amazon DynamoDB table, which is the resource to scale.");
        String tableId = args[0];
        String roleARN = args[1];
        String policyName = args[2];
        ServiceNamespace ns = ServiceNamespace.DYNAMODB;
        ScalableDimension tableWCUs = ScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS;
        ApplicationAutoScalingClient appAutoScalingClient = ApplicationAutoScalingClient.builder()
            .region(Region.US_EAST_1)
            .build();

        registerScalableTarget(appAutoScalingClient, tableId, roleARN, ns, tableWCUs);
        verifyTarget(appAutoScalingClient, tableId, ns, tableWCUs);
        configureScalingPolicy(appAutoScalingClient, tableId, ns, tableWCUs, policyName);
    }

    public static void registerScalableTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, String roleARN, ServiceNamespace ns, ScalableDimension tableWCUs) {
        try {
            RegisterScalableTargetRequest targetRequest = RegisterScalableTargetRequest.builder()
                .serviceNamespace(ns)
                .scalableDimension(tableWCUs)
                .resourceId(tableId)
                .roleARN(roleARN)
                .minCapacity(5)
                .maxCapacity(10)
                .build();

            appAutoScalingClient.registerScalableTarget(targetRequest);
            System.out.println("You have registered " + tableId);

        } catch (ApplicationAutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    // Verify that the target was created.
    public static void verifyTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        DescribeScalableTargetsRequest dscRequest = DescribeScalableTargetsRequest.builder()
            .scalableDimension(tableWCUs)
            .serviceNamespace(ns)
            .resourceIds(tableId)
            .build();

        DescribeScalableTargetsResponse response = appAutoScalingClient.describeScalableTargets(dscRequest);
        System.out.println("DescribeScalableTargets result: ");
        System.out.println(response);
    }

    // Configure a scaling policy.
    public static void configureScalingPolicy(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs, String policyName) {
        // Check if the policy exists before creating a new one.
        DescribeScalingPoliciesResponse describeScalingPoliciesResponse = appAutoScalingClient.describeScalingPolicies(DescribeScalingPoliciesRequest.builder()
            .serviceNamespace(ns)
            .resourceId(tableId)
            .scalableDimension(tableWCUs)
            .build());

        if (!describeScalingPoliciesResponse.scalingPolicies().isEmpty()) {
            // If policies exist, consider updating an existing policy instead of creating a new one.
            System.out.println("Policy already exists. Consider updating it instead.");
            List<ScalingPolicy> polList = describeScalingPoliciesResponse.scalingPolicies();
            for (ScalingPolicy pol : polList) {
                System.out.println("Policy name:" +pol.policyName());
            }
        } else {
            // If no policies exist, proceed with creating a new policy.
            PredefinedMetricSpecification specification = PredefinedMetricSpecification.builder()
                .predefinedMetricType(MetricType.DYNAMO_DB_WRITE_CAPACITY_UTILIZATION)
                .build();

            TargetTrackingScalingPolicyConfiguration policyConfiguration = TargetTrackingScalingPolicyConfiguration.builder()
                .predefinedMetricSpecification(specification)
                .targetValue(50.0)
                .scaleInCooldown(60)
                .scaleOutCooldown(60)
                .build();

            PutScalingPolicyRequest putScalingPolicyRequest = PutScalingPolicyRequest.builder()
                .targetTrackingScalingPolicyConfiguration(policyConfiguration)
                .serviceNamespace(ns)
                .scalableDimension(tableWCUs)
                .resourceId(tableId)
                .policyName(policyName)
                .policyType(PolicyType.TARGET_TRACKING_SCALING)
                .build();

            try {
                appAutoScalingClient.putScalingPolicy(putScalingPolicyRequest);
                System.out.println("You have successfully created a scaling policy for an Application Auto Scaling scalable target");
            } catch (ApplicationAutoScalingException e) {
                System.err.println("Error: " + e.awsErrorDetails().errorMessage());
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[RegisterScalableTarget](https://docs.aws.amazon.com/goto/SdkForJavaV2/application-autoscaling-2016-02-06/RegisterScalableTarget)」を参照してください。

# SDK for Java 2.x を使用した Application Recovery Controller の例
<a name="java_2_route53-recovery-cluster_code_examples"></a>

次のコード例は、Application Recovery Controller AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetRoutingControlState`
<a name="route53-recovery-cluster_GetRoutingControlState_java_2_topic"></a>

次のコード例は、`GetRoutingControlState` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53recoverycluster#code-examples)での設定と実行の方法を確認してください。

```
    public static GetRoutingControlStateResponse getRoutingControlState(List<ClusterEndpoint> clusterEndpoints,
            String routingControlArn) {
        // As a best practice, we recommend choosing a random cluster endpoint to get or
        // set routing control states.
        // For more information, see
        // https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-practices.html#route53-arc-best-practices.regional
        Collections.shuffle(clusterEndpoints);
        for (ClusterEndpoint clusterEndpoint : clusterEndpoints) {
            try {
                System.out.println(clusterEndpoint);
                Route53RecoveryClusterClient client = Route53RecoveryClusterClient.builder()
                        .endpointOverride(URI.create(clusterEndpoint.endpoint()))
                        .region(Region.of(clusterEndpoint.region())).build();
                return client.getRoutingControlState(
                        GetRoutingControlStateRequest.builder()
                                .routingControlArn(routingControlArn).build());
            } catch (Exception exception) {
                System.out.println(exception);
            }
        }
        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetRoutingControlState](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53-recovery-cluster-2019-12-02/GetRoutingControlState)」を参照してください。

### `UpdateRoutingControlState`
<a name="route53-recovery-cluster_UpdateRoutingControlState_java_2_topic"></a>

次のコード例は、`UpdateRoutingControlState` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53recoverycluster#code-examples)での設定と実行の方法を確認してください。

```
    public static UpdateRoutingControlStateResponse updateRoutingControlState(List<ClusterEndpoint> clusterEndpoints,
            String routingControlArn,
            String routingControlState) {
        // As a best practice, we recommend choosing a random cluster endpoint to get or
        // set routing control states.
        // For more information, see
        // https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-practices.html#route53-arc-best-practices.regional
        Collections.shuffle(clusterEndpoints);
        for (ClusterEndpoint clusterEndpoint : clusterEndpoints) {
            try {
                System.out.println(clusterEndpoint);
                Route53RecoveryClusterClient client = Route53RecoveryClusterClient.builder()
                        .endpointOverride(URI.create(clusterEndpoint.endpoint()))
                        .region(Region.of(clusterEndpoint.region()))
                        .build();
                return client.updateRoutingControlState(
                        UpdateRoutingControlStateRequest.builder()
                                .routingControlArn(routingControlArn).routingControlState(routingControlState).build());
            } catch (Exception exception) {
                System.out.println(exception);
            }
        }
        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateRoutingControlState](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53-recovery-cluster-2019-12-02/UpdateRoutingControlState)」を参照してください。

# SDK for Java 2.x を使用した Aurora の例
<a name="java_2_aurora_code_examples"></a>

次のコード例は、Aurora AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Aurora
<a name="aurora_Hello_java_2_topic"></a>

次のコード例は、Aurora の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.paginators.DescribeDBClustersIterable;

public class DescribeDbClusters {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        describeClusters(rdsClient);
        rdsClient.close();
    }

    public static void describeClusters(RdsClient rdsClient) {
        DescribeDBClustersIterable clustersIterable = rdsClient.describeDBClustersPaginator();
        clustersIterable.stream()
                .flatMap(r -> r.dbClusters().stream())
                .forEach(cluster -> System.out
                        .println("Database name: " + cluster.databaseName() + " Arn = " + cluster.dbClusterArn()));
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="aurora_Scenario_GetStartedClusters_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム Aurora DB クラスターパラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用する DB クラスターを作成する
+ データベースを含む DB インスタンスを作成します。
+ DB クラスターのスナップショットを作成して、リソースをクリーンアップします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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
 *
 * This example requires an AWS Secrets Manager secret that contains the
 * database credentials. If you do not create a
 * secret, this example will not work. For details, see:
 *
 * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html
 *
 * This Java example performs the following tasks:
 *
 * 1. Gets available engine families for Amazon Aurora MySQL-Compatible Edition
 * by calling the DescribeDbEngineVersions(Engine='aurora-mysql') method.
 * 2. Selects an engine family and creates a custom DB cluster parameter group
 * by invoking the describeDBClusterParameters method.
 * 3. Gets the parameter groups by invoking the describeDBClusterParameterGroups
 * method.
 * 4. Gets parameters in the group by invoking the describeDBClusterParameters
 * method.
 * 5. Modifies the auto_increment_offset parameter by invoking the
 * modifyDbClusterParameterGroupRequest method.
 * 6. Gets and displays the updated parameters.
 * 7. Gets a list of allowed engine versions by invoking the
 * describeDbEngineVersions method.
 * 8. Creates an Aurora DB cluster database cluster that contains a MySQL
 * database.
 * 9. Waits for DB instance to be ready.
 * 10. Gets a list of instance classes available for the selected engine.
 * 11. Creates a database instance in the cluster.
 * 12. Waits for DB instance to be ready.
 * 13. Creates a snapshot.
 * 14. Waits for DB snapshot to be ready.
 * 15. Deletes the DB cluster.
 * 16. Deletes the DB cluster group.
 */
public class AuroraScenario {
    public static long sleepTime = 20;
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws InterruptedException {
        final String usage = "\n" +
                "Usage:\n" +
                "    <dbClusterGroupName> <dbParameterGroupFamily> <dbInstanceClusterIdentifier> <dbInstanceIdentifier> <dbName> <dbSnapshotIdentifier><secretName>"
                +
                "Where:\n" +
                "    dbClusterGroupName - The name of the DB cluster parameter group. \n" +
                "    dbParameterGroupFamily - The DB cluster parameter group family name (for example, aurora-mysql5.7). \n"
                +
                "    dbInstanceClusterIdentifier - The instance cluster identifier value.\n" +
                "    dbInstanceIdentifier - The database instance identifier.\n" +
                "    dbName - The database name.\n" +
                "    dbSnapshotIdentifier - The snapshot identifier.\n" +
                "    secretName - The name of the AWS Secrets Manager secret that contains the database credentials\"\n";
        ;

        if (args.length != 7) {
            System.out.println(usage);
            System.exit(1);
        }

        String dbClusterGroupName = args[0];
        String dbParameterGroupFamily = args[1];
        String dbInstanceClusterIdentifier = args[2];
        String dbInstanceIdentifier = args[3];
        String dbName = args[4];
        String dbSnapshotIdentifier = args[5];
        String secretName = args[6];

        // Retrieve the database credentials using AWS Secrets Manager.
        Gson gson = new Gson();
        User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class);
        String username = user.getUsername();
        String userPassword = user.getPassword();

        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon Aurora example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Return a list of the available DB engines");
        describeDBEngines(rdsClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Create a custom parameter group");
        createDBClusterParameterGroup(rdsClient, dbClusterGroupName, dbParameterGroupFamily);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Get the parameter group");
        describeDbClusterParameterGroups(rdsClient, dbClusterGroupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Get the parameters in the group");
        describeDbClusterParameters(rdsClient, dbClusterGroupName, 0);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Modify the auto_increment_offset parameter");
        modifyDBClusterParas(rdsClient, dbClusterGroupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Display the updated parameter value");
        describeDbClusterParameters(rdsClient, dbClusterGroupName, -1);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Get a list of allowed engine versions");
        getAllowedEngines(rdsClient, dbParameterGroupFamily);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Create an Aurora DB cluster database");
        String arnClusterVal = createDBCluster(rdsClient, dbClusterGroupName, dbName, dbInstanceClusterIdentifier,
                username, userPassword);
        System.out.println("The ARN of the cluster is " + arnClusterVal);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. Wait for DB instance to be ready");
        waitForInstanceReady(rdsClient, dbInstanceClusterIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Get a list of instance classes available for the selected engine");
        String instanceClass = getListInstanceClasses(rdsClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Create a database instance in the cluster.");
        String clusterDBARN = createDBInstanceCluster(rdsClient, dbInstanceIdentifier, dbInstanceClusterIdentifier,
                instanceClass);
        System.out.println("The ARN of the database is " + clusterDBARN);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("12. Wait for DB instance to be ready");
        waitDBInstanceReady(rdsClient, dbInstanceIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("13. Create a snapshot");
        createDBClusterSnapshot(rdsClient, dbInstanceClusterIdentifier, dbSnapshotIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("14. Wait for DB snapshot to be ready");
        waitForSnapshotReady(rdsClient, dbSnapshotIdentifier, dbInstanceClusterIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("14. Delete the DB instance");
        deleteDatabaseInstance(rdsClient, dbInstanceIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("15. Delete the DB cluster");
        deleteCluster(rdsClient, dbInstanceClusterIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("16. Delete the DB cluster group");
        deleteDBClusterGroup(rdsClient, dbClusterGroupName, clusterDBARN);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The Scenario has successfully completed.");
        System.out.println(DASHES);
        rdsClient.close();
    }

    private static SecretsManagerClient getSecretClient() {
        Region region = Region.US_WEST_2;
        return SecretsManagerClient.builder()
                .region(region)
                .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
                .build();
    }

    private static String getSecretValues(String secretName) {
        SecretsManagerClient secretClient = getSecretClient();
        GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                .secretId(secretName)
                .build();

        GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest);
        return valueResponse.secretString();
    }

    public static void deleteDBClusterGroup(RdsClient rdsClient, String dbClusterGroupName, String clusterDBARN)
            throws InterruptedException {
        try {
            boolean isDataDel = false;
            boolean didFind;
            String instanceARN;

            // Make sure that the database has been deleted.
            while (!isDataDel) {
                DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
                List<DBInstance> instanceList = response.dbInstances();
                int listSize = instanceList.size();
                didFind = false;
                int index = 1;
                for (DBInstance instance : instanceList) {
                    instanceARN = instance.dbInstanceArn();
                    if (instanceARN.compareTo(clusterDBARN) == 0) {
                        System.out.println(clusterDBARN + " still exists");
                        didFind = true;
                    }
                    if ((index == listSize) && (!didFind)) {
                        // Went through the entire list and did not find the database ARN.
                        isDataDel = true;
                    }
                    Thread.sleep(sleepTime * 1000);
                    index++;
                }
            }

            DeleteDbClusterParameterGroupRequest clusterParameterGroupRequest = DeleteDbClusterParameterGroupRequest
                    .builder()
                    .dbClusterParameterGroupName(dbClusterGroupName)
                    .build();

            rdsClient.deleteDBClusterParameterGroup(clusterParameterGroupRequest);
            System.out.println(dbClusterGroupName + " was deleted.");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void deleteCluster(RdsClient rdsClient, String dbInstanceClusterIdentifier) {
        try {
            DeleteDbClusterRequest deleteDbClusterRequest = DeleteDbClusterRequest.builder()
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .skipFinalSnapshot(true)
                    .build();

            rdsClient.deleteDBCluster(deleteDbClusterRequest);
            System.out.println(dbInstanceClusterIdentifier + " was deleted!");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) {
        try {
            DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .deleteAutomatedBackups(true)
                    .skipFinalSnapshot(true)
                    .build();

            DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest);
            System.out.println("The status of the database is " + response.dbInstance().dbInstanceStatus());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void waitForSnapshotReady(RdsClient rdsClient, String dbSnapshotIdentifier,
            String dbInstanceClusterIdentifier) {
        try {
            boolean snapshotReady = false;
            String snapshotReadyStr;
            System.out.println("Waiting for the snapshot to become available.");

            DescribeDbClusterSnapshotsRequest snapshotsRequest = DescribeDbClusterSnapshotsRequest.builder()
                    .dbClusterSnapshotIdentifier(dbSnapshotIdentifier)
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .build();

            while (!snapshotReady) {
                DescribeDbClusterSnapshotsResponse response = rdsClient.describeDBClusterSnapshots(snapshotsRequest);
                List<DBClusterSnapshot> snapshotList = response.dbClusterSnapshots();
                for (DBClusterSnapshot snapshot : snapshotList) {
                    snapshotReadyStr = snapshot.status();
                    if (snapshotReadyStr.contains("available")) {
                        snapshotReady = true;
                    } else {
                        System.out.println(".");
                        Thread.sleep(sleepTime * 5000);
                    }
                }
            }

            System.out.println("The Snapshot is available!");

        } catch (RdsException | InterruptedException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void createDBClusterSnapshot(RdsClient rdsClient, String dbInstanceClusterIdentifier,
            String dbSnapshotIdentifier) {
        try {
            CreateDbClusterSnapshotRequest snapshotRequest = CreateDbClusterSnapshotRequest.builder()
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .dbClusterSnapshotIdentifier(dbSnapshotIdentifier)
                    .build();

            CreateDbClusterSnapshotResponse response = rdsClient.createDBClusterSnapshot(snapshotRequest);
            System.out.println("The Snapshot ARN is " + response.dbClusterSnapshot().dbClusterSnapshotArn());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void waitDBInstanceReady(RdsClient rdsClient, String dbInstanceIdentifier) {
        boolean instanceReady = false;
        String instanceReadyStr;
        System.out.println("Waiting for instance to become available.");
        try {
            DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .build();

            String endpoint = "";
            while (!instanceReady) {
                DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest);
                List<DBInstance> instanceList = response.dbInstances();
                for (DBInstance instance : instanceList) {
                    instanceReadyStr = instance.dbInstanceStatus();
                    if (instanceReadyStr.contains("available")) {
                        endpoint = instance.endpoint().address();
                        instanceReady = true;
                    } else {
                        System.out.print(".");
                        Thread.sleep(sleepTime * 1000);
                    }
                }
            }
            System.out.println("Database instance is available! The connection endpoint is " + endpoint);

        } catch (RdsException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static String createDBInstanceCluster(RdsClient rdsClient,
            String dbInstanceIdentifier,
            String dbInstanceClusterIdentifier,
            String instanceClass) {
        try {
            CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .engine("aurora-mysql")
                    .dbInstanceClass(instanceClass)
                    .build();

            CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest);
            System.out.print("The status is " + response.dbInstance().dbInstanceStatus());
            return response.dbInstance().dbInstanceArn();

        } catch (RdsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }

    public static String getListInstanceClasses(RdsClient rdsClient) {
        try {
            DescribeOrderableDbInstanceOptionsRequest optionsRequest = DescribeOrderableDbInstanceOptionsRequest
                    .builder()
                    .engine("aurora-mysql")
                    .maxRecords(20)
                    .build();

            DescribeOrderableDbInstanceOptionsResponse response = rdsClient
                    .describeOrderableDBInstanceOptions(optionsRequest);
            List<OrderableDBInstanceOption> instanceOptions = response.orderableDBInstanceOptions();
            String instanceClass = "";
            for (OrderableDBInstanceOption instanceOption : instanceOptions) {
                instanceClass = instanceOption.dbInstanceClass();
                System.out.println("The instance class is " + instanceOption.dbInstanceClass());
                System.out.println("The engine version is " + instanceOption.engineVersion());
            }
            return instanceClass;

        } catch (RdsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }

    // Waits until the database instance is available.
    public static void waitForInstanceReady(RdsClient rdsClient, String dbClusterIdentifier) {
        boolean instanceReady = false;
        String instanceReadyStr;
        System.out.println("Waiting for instance to become available.");
        try {
            DescribeDbClustersRequest instanceRequest = DescribeDbClustersRequest.builder()
                    .dbClusterIdentifier(dbClusterIdentifier)
                    .build();

            while (!instanceReady) {
                DescribeDbClustersResponse response = rdsClient.describeDBClusters(instanceRequest);
                List<DBCluster> clusterList = response.dbClusters();
                for (DBCluster cluster : clusterList) {
                    instanceReadyStr = cluster.status();
                    if (instanceReadyStr.contains("available")) {
                        instanceReady = true;
                    } else {
                        System.out.print(".");
                        Thread.sleep(sleepTime * 1000);
                    }
                }
            }
            System.out.println("Database cluster is available!");

        } catch (RdsException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static String createDBCluster(RdsClient rdsClient, String dbParameterGroupFamily, String dbName,
            String dbClusterIdentifier, String userName, String password) {
        try {
            CreateDbClusterRequest clusterRequest = CreateDbClusterRequest.builder()
                    .databaseName(dbName)
                    .dbClusterIdentifier(dbClusterIdentifier)
                    .dbClusterParameterGroupName(dbParameterGroupFamily)
                    .engine("aurora-mysql")
                    .masterUsername(userName)
                    .masterUserPassword(password)
                    .build();

            CreateDbClusterResponse response = rdsClient.createDBCluster(clusterRequest);
            return response.dbCluster().dbClusterArn();

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }

    // Get a list of allowed engine versions.
    public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGroupFamily) {
        try {
            DescribeDbEngineVersionsRequest versionsRequest = DescribeDbEngineVersionsRequest.builder()
                    .dbParameterGroupFamily(dbParameterGroupFamily)
                    .engine("aurora-mysql")
                    .build();

            DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(versionsRequest);
            List<DBEngineVersion> dbEngines = response.dbEngineVersions();
            for (DBEngineVersion dbEngine : dbEngines) {
                System.out.println("The engine version is " + dbEngine.engineVersion());
                System.out.println("The engine description is " + dbEngine.dbEngineDescription());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Modify the auto_increment_offset parameter.
    public static void modifyDBClusterParas(RdsClient rdsClient, String dClusterGroupName) {
        try {
            Parameter parameter1 = Parameter.builder()
                    .parameterName("auto_increment_offset")
                    .applyMethod("immediate")
                    .parameterValue("5")
                    .build();

            List<Parameter> paraList = new ArrayList<>();
            paraList.add(parameter1);
            ModifyDbClusterParameterGroupRequest groupRequest = ModifyDbClusterParameterGroupRequest.builder()
                    .dbClusterParameterGroupName(dClusterGroupName)
                    .parameters(paraList)
                    .build();

            ModifyDbClusterParameterGroupResponse response = rdsClient.modifyDBClusterParameterGroup(groupRequest);
            System.out.println(
                    "The parameter group " + response.dbClusterParameterGroupName() + " was successfully modified");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void describeDbClusterParameters(RdsClient rdsClient, String dbCLusterGroupName, int flag) {
        try {
            DescribeDbClusterParametersRequest dbParameterGroupsRequest;
            if (flag == 0) {
                dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder()
                        .dbClusterParameterGroupName(dbCLusterGroupName)
                        .build();
            } else {
                dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder()
                        .dbClusterParameterGroupName(dbCLusterGroupName)
                        .source("user")
                        .build();
            }

            DescribeDbClusterParametersResponse response = rdsClient
                    .describeDBClusterParameters(dbParameterGroupsRequest);
            List<Parameter> dbParameters = response.parameters();
            String paraName;
            for (Parameter para : dbParameters) {
                // Only print out information about either auto_increment_offset or
                // auto_increment_increment.
                paraName = para.parameterName();
                if ((paraName.compareTo("auto_increment_offset") == 0)
                        || (paraName.compareTo("auto_increment_increment ") == 0)) {
                    System.out.println("*** The parameter name is  " + paraName);
                    System.out.println("*** The parameter value is  " + para.parameterValue());
                    System.out.println("*** The parameter data type is " + para.dataType());
                    System.out.println("*** The parameter description is " + para.description());
                    System.out.println("*** The parameter allowed values  is " + para.allowedValues());
                }
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void describeDbClusterParameterGroups(RdsClient rdsClient, String dbClusterGroupName) {
        try {
            DescribeDbClusterParameterGroupsRequest groupsRequest = DescribeDbClusterParameterGroupsRequest.builder()
                    .dbClusterParameterGroupName(dbClusterGroupName)
                    .maxRecords(20)
                    .build();

            List<DBClusterParameterGroup> groups = rdsClient.describeDBClusterParameterGroups(groupsRequest)
                    .dbClusterParameterGroups();
            for (DBClusterParameterGroup group : groups) {
                System.out.println("The group name is " + group.dbClusterParameterGroupName());
                System.out.println("The group ARN is " + group.dbClusterParameterGroupArn());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void createDBClusterParameterGroup(RdsClient rdsClient, String dbClusterGroupName,
            String dbParameterGroupFamily) {
        try {
            CreateDbClusterParameterGroupRequest groupRequest = CreateDbClusterParameterGroupRequest.builder()
                    .dbClusterParameterGroupName(dbClusterGroupName)
                    .dbParameterGroupFamily(dbParameterGroupFamily)
                    .description("Created by using the AWS SDK for Java")
                    .build();

            CreateDbClusterParameterGroupResponse response = rdsClient.createDBClusterParameterGroup(groupRequest);
            System.out.println("The group name is " + response.dbClusterParameterGroup().dbClusterParameterGroupName());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void describeDBEngines(RdsClient rdsClient) {
        try {
            DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder()
                    .engine("aurora-mysql")
                    .defaultOnly(true)
                    .maxRecords(20)
                    .build();

            DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest);
            List<DBEngineVersion> engines = response.dbEngineVersions();

            // Get all DBEngineVersion objects.
            for (DBEngineVersion engineOb : engines) {
                System.out.println("The name of the DB parameter group family for the database engine is "
                        + engineOb.dbParameterGroupFamily());
                System.out.println("The name of the database engine " + engineOb.engine());
                System.out.println("The version number of the database engine " + engineOb.engineVersion());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の以下のトピックを参照してください。
  + [CreateDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBCluster)
  + [CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBClusterParameterGroup)
  + [CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBClusterSnapshot)
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBInstance)
  + [DeleteDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBCluster)
  + [DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBClusterParameterGroup)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBInstance)
  + [DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusterParameterGroups)
  + [DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusterParameters)
  + [DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusterSnapshots)
  + [DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusters)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBInstances)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/ModifyDBClusterParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="aurora_CreateDBCluster_java_2_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static String createDBCluster(RdsClient rdsClient, String dbParameterGroupFamily, String dbName,
            String dbClusterIdentifier, String userName, String password) {
        try {
            CreateDbClusterRequest clusterRequest = CreateDbClusterRequest.builder()
                    .databaseName(dbName)
                    .dbClusterIdentifier(dbClusterIdentifier)
                    .dbClusterParameterGroupName(dbParameterGroupFamily)
                    .engine("aurora-mysql")
                    .masterUsername(userName)
                    .masterUserPassword(password)
                    .build();

            CreateDbClusterResponse response = rdsClient.createDBCluster(clusterRequest);
            return response.dbCluster().dbClusterArn();

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBCluster)」を参照してください。

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_java_2_topic"></a>

次のコード例は、`CreateDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void createDBClusterParameterGroup(RdsClient rdsClient, String dbClusterGroupName,
            String dbParameterGroupFamily) {
        try {
            CreateDbClusterParameterGroupRequest groupRequest = CreateDbClusterParameterGroupRequest.builder()
                    .dbClusterParameterGroupName(dbClusterGroupName)
                    .dbParameterGroupFamily(dbParameterGroupFamily)
                    .description("Created by using the AWS SDK for Java")
                    .build();

            CreateDbClusterParameterGroupResponse response = rdsClient.createDBClusterParameterGroup(groupRequest);
            System.out.println("The group name is " + response.dbClusterParameterGroup().dbClusterParameterGroupName());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBClusterParameterGroup)」を参照してください。

### `CreateDBClusterSnapshot`
<a name="aurora_CreateDBClusterSnapshot_java_2_topic"></a>

次のコード例は、`CreateDBClusterSnapshot` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void createDBClusterSnapshot(RdsClient rdsClient, String dbInstanceClusterIdentifier,
            String dbSnapshotIdentifier) {
        try {
            CreateDbClusterSnapshotRequest snapshotRequest = CreateDbClusterSnapshotRequest.builder()
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .dbClusterSnapshotIdentifier(dbSnapshotIdentifier)
                    .build();

            CreateDbClusterSnapshotResponse response = rdsClient.createDBClusterSnapshot(snapshotRequest);
            System.out.println("The Snapshot ARN is " + response.dbClusterSnapshot().dbClusterSnapshotArn());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBClusterSnapshot)」を参照してください。

### `CreateDBInstance`
<a name="aurora_CreateDBInstance_java_2_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static String createDBInstanceCluster(RdsClient rdsClient,
            String dbInstanceIdentifier,
            String dbInstanceClusterIdentifier,
            String instanceClass) {
        try {
            CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .engine("aurora-mysql")
                    .dbInstanceClass(instanceClass)
                    .build();

            CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest);
            System.out.print("The status is " + response.dbInstance().dbInstanceStatus());
            return response.dbInstance().dbInstanceArn();

        } catch (RdsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `DeleteDBCluster`
<a name="aurora_DeleteDBCluster_java_2_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteCluster(RdsClient rdsClient, String dbInstanceClusterIdentifier) {
        try {
            DeleteDbClusterRequest deleteDbClusterRequest = DeleteDbClusterRequest.builder()
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .skipFinalSnapshot(true)
                    .build();

            rdsClient.deleteDBCluster(deleteDbClusterRequest);
            System.out.println(dbInstanceClusterIdentifier + " was deleted!");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBCluster)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_java_2_topic"></a>

次のコード例は、`DeleteDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteDBClusterGroup(RdsClient rdsClient, String dbClusterGroupName, String clusterDBARN)
            throws InterruptedException {
        try {
            boolean isDataDel = false;
            boolean didFind;
            String instanceARN;

            // Make sure that the database has been deleted.
            while (!isDataDel) {
                DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
                List<DBInstance> instanceList = response.dbInstances();
                int listSize = instanceList.size();
                didFind = false;
                int index = 1;
                for (DBInstance instance : instanceList) {
                    instanceARN = instance.dbInstanceArn();
                    if (instanceARN.compareTo(clusterDBARN) == 0) {
                        System.out.println(clusterDBARN + " still exists");
                        didFind = true;
                    }
                    if ((index == listSize) && (!didFind)) {
                        // Went through the entire list and did not find the database ARN.
                        isDataDel = true;
                    }
                    Thread.sleep(sleepTime * 1000);
                    index++;
                }
            }

            DeleteDbClusterParameterGroupRequest clusterParameterGroupRequest = DeleteDbClusterParameterGroupRequest
                    .builder()
                    .dbClusterParameterGroupName(dbClusterGroupName)
                    .build();

            rdsClient.deleteDBClusterParameterGroup(clusterParameterGroupRequest);
            System.out.println(dbClusterGroupName + " was deleted.");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBClusterParameterGroup)」を参照してください。

### `DeleteDBInstance`
<a name="aurora_DeleteDBInstance_java_2_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) {
        try {
            DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .deleteAutomatedBackups(true)
                    .skipFinalSnapshot(true)
                    .build();

            DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest);
            System.out.println("The status of the database is " + response.dbInstance().dbInstanceStatus());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DescribeDBClusterParameterGroups`
<a name="aurora_DescribeDBClusterParameterGroups_java_2_topic"></a>

次のコード例は、`DescribeDBClusterParameterGroups` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDbClusterParameterGroups(RdsClient rdsClient, String dbClusterGroupName) {
        try {
            DescribeDbClusterParameterGroupsRequest groupsRequest = DescribeDbClusterParameterGroupsRequest.builder()
                    .dbClusterParameterGroupName(dbClusterGroupName)
                    .maxRecords(20)
                    .build();

            List<DBClusterParameterGroup> groups = rdsClient.describeDBClusterParameterGroups(groupsRequest)
                    .dbClusterParameterGroups();
            for (DBClusterParameterGroup group : groups) {
                System.out.println("The group name is " + group.dbClusterParameterGroupName());
                System.out.println("The group ARN is " + group.dbClusterParameterGroupArn());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusterParameterGroups)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_java_2_topic"></a>

次のコード例は、`DescribeDBClusterParameters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDbClusterParameters(RdsClient rdsClient, String dbCLusterGroupName, int flag) {
        try {
            DescribeDbClusterParametersRequest dbParameterGroupsRequest;
            if (flag == 0) {
                dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder()
                        .dbClusterParameterGroupName(dbCLusterGroupName)
                        .build();
            } else {
                dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder()
                        .dbClusterParameterGroupName(dbCLusterGroupName)
                        .source("user")
                        .build();
            }

            DescribeDbClusterParametersResponse response = rdsClient
                    .describeDBClusterParameters(dbParameterGroupsRequest);
            List<Parameter> dbParameters = response.parameters();
            String paraName;
            for (Parameter para : dbParameters) {
                // Only print out information about either auto_increment_offset or
                // auto_increment_increment.
                paraName = para.parameterName();
                if ((paraName.compareTo("auto_increment_offset") == 0)
                        || (paraName.compareTo("auto_increment_increment ") == 0)) {
                    System.out.println("*** The parameter name is  " + paraName);
                    System.out.println("*** The parameter value is  " + para.parameterValue());
                    System.out.println("*** The parameter data type is " + para.dataType());
                    System.out.println("*** The parameter description is " + para.description());
                    System.out.println("*** The parameter allowed values  is " + para.allowedValues());
                }
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusterParameters)」を参照してください。

### `DescribeDBClusterSnapshots`
<a name="aurora_DescribeDBClusterSnapshots_java_2_topic"></a>

次のコード例は、`DescribeDBClusterSnapshots` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void waitForSnapshotReady(RdsClient rdsClient, String dbSnapshotIdentifier,
            String dbInstanceClusterIdentifier) {
        try {
            boolean snapshotReady = false;
            String snapshotReadyStr;
            System.out.println("Waiting for the snapshot to become available.");

            DescribeDbClusterSnapshotsRequest snapshotsRequest = DescribeDbClusterSnapshotsRequest.builder()
                    .dbClusterSnapshotIdentifier(dbSnapshotIdentifier)
                    .dbClusterIdentifier(dbInstanceClusterIdentifier)
                    .build();

            while (!snapshotReady) {
                DescribeDbClusterSnapshotsResponse response = rdsClient.describeDBClusterSnapshots(snapshotsRequest);
                List<DBClusterSnapshot> snapshotList = response.dbClusterSnapshots();
                for (DBClusterSnapshot snapshot : snapshotList) {
                    snapshotReadyStr = snapshot.status();
                    if (snapshotReadyStr.contains("available")) {
                        snapshotReady = true;
                    } else {
                        System.out.println(".");
                        Thread.sleep(sleepTime * 5000);
                    }
                }
            }

            System.out.println("The Snapshot is available!");

        } catch (RdsException | InterruptedException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusterSnapshots)」を参照してください。

### `DescribeDBClusters`
<a name="aurora_DescribeDBClusters_java_2_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDbClusterParameters(RdsClient rdsClient, String dbCLusterGroupName, int flag) {
        try {
            DescribeDbClusterParametersRequest dbParameterGroupsRequest;
            if (flag == 0) {
                dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder()
                        .dbClusterParameterGroupName(dbCLusterGroupName)
                        .build();
            } else {
                dbParameterGroupsRequest = DescribeDbClusterParametersRequest.builder()
                        .dbClusterParameterGroupName(dbCLusterGroupName)
                        .source("user")
                        .build();
            }

            DescribeDbClusterParametersResponse response = rdsClient
                    .describeDBClusterParameters(dbParameterGroupsRequest);
            List<Parameter> dbParameters = response.parameters();
            String paraName;
            for (Parameter para : dbParameters) {
                // Only print out information about either auto_increment_offset or
                // auto_increment_increment.
                paraName = para.parameterName();
                if ((paraName.compareTo("auto_increment_offset") == 0)
                        || (paraName.compareTo("auto_increment_increment ") == 0)) {
                    System.out.println("*** The parameter name is  " + paraName);
                    System.out.println("*** The parameter value is  " + para.parameterValue());
                    System.out.println("*** The parameter data type is " + para.dataType());
                    System.out.println("*** The parameter description is " + para.description());
                    System.out.println("*** The parameter allowed values  is " + para.allowedValues());
                }
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBClusters)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_java_2_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDBEngines(RdsClient rdsClient) {
        try {
            DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder()
                    .engine("aurora-mysql")
                    .defaultOnly(true)
                    .maxRecords(20)
                    .build();

            DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest);
            List<DBEngineVersion> engines = response.dbEngineVersions();

            // Get all DBEngineVersion objects.
            for (DBEngineVersion engineOb : engines) {
                System.out.println("The name of the DB parameter group family for the database engine is "
                        + engineOb.dbParameterGroupFamily());
                System.out.println("The name of the database engine " + engineOb.engine());
                System.out.println("The version number of the database engine " + engineOb.engineVersion());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="aurora_DescribeDBInstances_java_2_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    // Waits until the database instance is available.
    public static void waitForInstanceReady(RdsClient rdsClient, String dbClusterIdentifier) {
        boolean instanceReady = false;
        String instanceReadyStr;
        System.out.println("Waiting for instance to become available.");
        try {
            DescribeDbClustersRequest instanceRequest = DescribeDbClustersRequest.builder()
                    .dbClusterIdentifier(dbClusterIdentifier)
                    .build();

            while (!instanceReady) {
                DescribeDbClustersResponse response = rdsClient.describeDBClusters(instanceRequest);
                List<DBCluster> clusterList = response.dbClusters();
                for (DBCluster cluster : clusterList) {
                    instanceReadyStr = cluster.status();
                    if (instanceReadyStr.contains("available")) {
                        instanceReady = true;
                    } else {
                        System.out.print(".");
                        Thread.sleep(sleepTime * 1000);
                    }
                }
            }
            System.out.println("Database cluster is available!");

        } catch (RdsException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="aurora_DescribeOrderableDBInstanceOptions_java_2_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDBEngines(RdsClient rdsClient) {
        try {
            DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder()
                    .engine("aurora-mysql")
                    .defaultOnly(true)
                    .maxRecords(20)
                    .build();

            DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest);
            List<DBEngineVersion> engines = response.dbEngineVersions();

            // Get all DBEngineVersion objects.
            for (DBEngineVersion engineOb : engines) {
                System.out.println("The name of the DB parameter group family for the database engine is "
                        + engineOb.dbParameterGroupFamily());
                System.out.println("The name of the database engine " + engineOb.engine());
                System.out.println("The version number of the database engine " + engineOb.engineVersion());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_java_2_topic"></a>

次のコード例は、`ModifyDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDbClusterParameterGroups(RdsClient rdsClient, String dbClusterGroupName) {
        try {
            DescribeDbClusterParameterGroupsRequest groupsRequest = DescribeDbClusterParameterGroupsRequest.builder()
                    .dbClusterParameterGroupName(dbClusterGroupName)
                    .maxRecords(20)
                    .build();

            List<DBClusterParameterGroup> groups = rdsClient.describeDBClusterParameterGroups(groupsRequest)
                    .dbClusterParameterGroups();
            for (DBClusterParameterGroup group : groups) {
                System.out.println("The group name is " + group.dbClusterParameterGroupName());
                System.out.println("The group ARN is " + group.dbClusterParameterGroupArn());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/ModifyDBClusterParameterGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_java_2_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_Spring_RDS_Rest) にある完全な例を参照してください。  
 完全なソースコードと JDBC API を使用する例のセットアップと実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_rds_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for Java 2.x を使用した Auto Scaling の例
<a name="java_2_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### こんにちは、Auto Scaling
<a name="auto-scaling_Hello_java_2_topic"></a>

次のコード例は、Auto Scaling の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;
import java.util.List;

/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DescribeAutoScalingGroups {
    public static void main(String[] args) throws InterruptedException {
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_EAST_1)
                .build();

        describeGroups(autoScalingClient);
    }

    public static void describeGroups(AutoScalingClient autoScalingClient) {
        DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups();
        List<AutoScalingGroup> groups = response.autoScalingGroups();
        groups.forEach(group -> {
            System.out.println("Group Name: " + group.autoScalingGroupName());
            System.out.println("Group ARN: " + group.autoScalingGroupARN());
        });
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="auto-scaling_Scenario_GroupsAndInstances_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 起動テンプレートとアベイラビリティーゾーンを使用して、Amazon EC2 Auto Scaling グループを作成し、実行中のインスタンスに関する情報を取得します。
+ Amazon CloudWatch メトリクスの収集を有効にします。
+ グループの希望するキャパシティを更新し、インスタンスが起動するのを待ちます。
+  グループ内の最も古いインスタンスを削除します。
+ ユーザーのリクエストやキャパシティの変更に応じて発生するスケーリングアクティビティを一覧表示します。
+ CloudWatch メトリクスの統計を取得して、リソースをクリーンアップします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * In addition, create a launch template. For more information, see the
 * following topic:
 *
 * https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-templates.html#create-launch-template
 *
 * This code example performs the following operations:
 * 1. Creates an Auto Scaling group using an AutoScalingWaiter.
 * 2. Gets a specific Auto Scaling group and returns an instance Id value.
 * 3. Describes Auto Scaling with the Id value.
 * 4. Enables metrics collection.
 * 5. Update an Auto Scaling group.
 * 6. Describes Account details.
 * 7. Describe account details"
 * 8. Updates an Auto Scaling group to use an additional instance.
 * 9. Gets the specific Auto Scaling group and gets the number of instances.
 * 10. List the scaling activities that have occurred for the group.
 * 11. Terminates an instance in the Auto Scaling group.
 * 12. Stops the metrics collection.
 * 13. Deletes the Auto Scaling group.
 */

public class AutoScalingScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final String ROLES_STACK = "MyCdkAutoScaleStack";
    public static void main(String[] args) throws InterruptedException {
        final String usage = """

                Usage:
                    <groupName>

                Where:
                    groupName - The name of the Auto Scaling group.
                """;

        String groupName = "MyAutoScalingGroup2";
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_WEST_2)
                .build();

        Ec2Client ec2 = Ec2Client.builder()
                .region(Region.US_WEST_2)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon EC2 Auto Scaling example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("First, we will create a launch template using a CloudFormation script");
        CloudFormationHelper.deployCloudFormationStack(ROLES_STACK);
        Map<String, String> stackOutputs = CloudFormationHelper.getStackOutputsAsync(ROLES_STACK).join();
        String launchTemplateName = stackOutputs.get("LaunchTemplateNameOutput");
        String vpcZoneId = getVPC(ec2);
        updateTemlate(ec2, launchTemplateName );
        System.out.println("The VPC zone id created by the CloudFormation stack is"+vpcZoneId);

        System.out.println("1. Create an Auto Scaling group named " + groupName);
        createAutoScalingGroup(autoScalingClient, ec2, groupName, launchTemplateName, vpcZoneId);

        System.out.println(
                "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned");
        Thread.sleep(60000);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Get Auto Scale group Id value");
        String instanceId = getSpecificAutoScalingGroups(autoScalingClient, groupName);
        if (instanceId.compareTo("") == 0) {
            System.out.println("Error - no instance Id value");
            System.exit(1);
        } else {
            System.out.println("The instance Id value is " + instanceId);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Describe Auto Scaling with the Id value " + instanceId);
        describeAutoScalingInstance(autoScalingClient, instanceId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Enable metrics collection " + instanceId);
        enableMetricsCollection(autoScalingClient, groupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Update an Auto Scaling group to update max size to 3");
        updateAutoScalingGroup(autoScalingClient, groupName, launchTemplateName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Describe Auto Scaling groups");
        describeAutoScalingGroups(autoScalingClient, groupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Describe account details");
        describeAccountLimits(autoScalingClient);
        System.out.println(
                "Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned");
        Thread.sleep(60000);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Set desired capacity to 2");
        setDesiredCapacity(autoScalingClient, groupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. Get the two instance Id values and state");
        getSpecificAutoScalingGroups(autoScalingClient, groupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. List the scaling activities that have occurred for the group");
        describeScalingActivities(autoScalingClient, groupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Terminate an instance in the Auto Scaling group");
        terminateInstanceInAutoScalingGroup(autoScalingClient, instanceId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("12. Stop the metrics collection");
        disableMetricsCollection(autoScalingClient, groupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("13. Delete the Auto Scaling group and cloud formation resources");
        CloudFormationHelper.destroyCloudFormationStack(ROLES_STACK);
        deleteAutoScalingGroup(autoScalingClient, groupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The Scenario has successfully completed.");
        System.out.println(DASHES);

        autoScalingClient.close();
    }

    public static String getVPC(Ec2Client ec2) {
        try {
            DescribeVpcsRequest request = DescribeVpcsRequest.builder()
                    .filters(f -> f.name("isDefault").values("true"))
                    .build();

            DescribeVpcsResponse response = ec2.describeVpcs(request);

            if (!response.vpcs().isEmpty()) {
                Vpc defaultVpc = response.vpcs().get(0);
                System.out.println("Default VPC ID: " + defaultVpc.vpcId());
                return defaultVpc.vpcId();
            } else {
                System.out.println("No default VPC found.");
                return null; // Return null if no default VPC is found
            }

        } catch (Ec2Exception e) {
            System.err.println("EC2 error: " + e.awsErrorDetails().errorMessage());
            return null; // Return null in case of an error
        }
    }


    public static void updateTemlate(Ec2Client ec2, String launchTemplateName ) {
        // Step 1: Create new launch template version
        String newAmiId = "ami-0025f0db847eb6254";
        RequestLaunchTemplateData launchTemplateData = RequestLaunchTemplateData.builder()
                .imageId(newAmiId)
                .build();

        CreateLaunchTemplateVersionRequest createVersionRequest = CreateLaunchTemplateVersionRequest.builder()
                .launchTemplateName(launchTemplateName)
                .versionDescription("Updated with valid AMI")
                .sourceVersion("1")
                .launchTemplateData(launchTemplateData)
                .build();

        CreateLaunchTemplateVersionResponse createResponse = ec2.createLaunchTemplateVersion(createVersionRequest);
        int newVersionNumber = createResponse.launchTemplateVersion().versionNumber().intValue();

        // Step 2: Modify default version
        ModifyLaunchTemplateRequest modifyRequest = ModifyLaunchTemplateRequest.builder()
                .launchTemplateName(launchTemplateName)
                .defaultVersion(String.valueOf(newVersionNumber))
                .build();

        ec2.modifyLaunchTemplate(modifyRequest);
        System.out.println("Updated launch template to version " + newVersionNumber + " with AMI " + newAmiId);
    }


    public static void describeScalingActivities(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DescribeScalingActivitiesRequest scalingActivitiesRequest = DescribeScalingActivitiesRequest.builder()
                    .autoScalingGroupName(groupName)
                    .maxRecords(10)
                    .build();

            DescribeScalingActivitiesResponse response = autoScalingClient
                    .describeScalingActivities(scalingActivitiesRequest);
            List<Activity> activities = response.activities();
            for (Activity activity : activities) {
                System.out.println("The activity Id is " + activity.activityId());
                System.out.println("The activity details are " + activity.details());
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void setDesiredCapacity(AutoScalingClient autoScalingClient, String groupName) {
        try {
            SetDesiredCapacityRequest capacityRequest = SetDesiredCapacityRequest.builder()
                    .autoScalingGroupName(groupName)
                    .desiredCapacity(2)
                    .build();

            autoScalingClient.setDesiredCapacity(capacityRequest);
            System.out.println("You have set the DesiredCapacity to 2");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void createAutoScalingGroup(AutoScalingClient autoScalingClient,
                                              Ec2Client ec2Client,
                                              String groupName,
                                              String launchTemplateName,
                                              String vpcId) {
        try {
            // Step 1: Get one subnet ID in the given VPC
            DescribeSubnetsRequest subnetRequest = DescribeSubnetsRequest.builder()
                    .filters(Filter.builder().name("vpc-id").values(vpcId).build())
                    .build();

            DescribeSubnetsResponse subnetResponse = ec2Client.describeSubnets(subnetRequest);

            if (subnetResponse.subnets().isEmpty()) {
                throw new RuntimeException("No subnets found in VPC: " + vpcId);
            }

            String subnetId = subnetResponse.subnets().get(0).subnetId(); // Use first subnet
            System.out.println("Using subnet: " + subnetId);

            // Step 2: Create launch template reference
            LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder()
                    .launchTemplateName(launchTemplateName)
                    .build();

            // Step 3: Create Auto Scaling group
            CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder()
                    .autoScalingGroupName(groupName)
                    .launchTemplate(templateSpecification)
                    .minSize(1)
                    .maxSize(1)
                    .vpcZoneIdentifier(subnetId)  // Correct: subnet ID, not VPC ID
                    .build();

            autoScalingClient.createAutoScalingGroup(request);

            // Step 4: Wait until group is created
            AutoScalingWaiter waiter = autoScalingClient.waiter();
            DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse =
                    waiter.waitUntilGroupExists(groupsRequest);

            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Auto Scaling Group created");

        } catch (Ec2Exception | AutoScalingException e) {
            System.err.println("Error: " + e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void describeAutoScalingInstance(AutoScalingClient autoScalingClient, String id) {
        try {
            DescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest = DescribeAutoScalingInstancesRequest
                    .builder()
                    .instanceIds(id)
                    .build();

            DescribeAutoScalingInstancesResponse response = autoScalingClient
                    .describeAutoScalingInstances(describeAutoScalingInstancesRequest);
            List<AutoScalingInstanceDetails> instances = response.autoScalingInstances();
            for (AutoScalingInstanceDetails instance : instances) {
                System.out.println("The instance lifecycle state is: " + instance.lifecycleState());
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void describeAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .maxRecords(10)
                    .build();

            DescribeAutoScalingGroupsResponse response = autoScalingClient.describeAutoScalingGroups(groupsRequest);
            List<AutoScalingGroup> groups = response.autoScalingGroups();
            for (AutoScalingGroup group : groups) {
                System.out.println("*** The service to use for the health checks: " + group.healthCheckType());
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static String getSpecificAutoScalingGroups(AutoScalingClient autoScalingClient, String groupName) {
        try {
            String instanceId = "";
            DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            DescribeAutoScalingGroupsResponse response = autoScalingClient
                    .describeAutoScalingGroups(scalingGroupsRequest);
            List<AutoScalingGroup> groups = response.autoScalingGroups();
            for (AutoScalingGroup group : groups) {
                System.out.println("The group name is " + group.autoScalingGroupName());
                System.out.println("The group ARN is " + group.autoScalingGroupARN());
                List<Instance> instances = group.instances();

                for (Instance instance : instances) {
                    instanceId = instance.instanceId();
                    System.out.println("The instance id is " + instanceId);
                    System.out.println("The lifecycle state is " + instance.lifecycleState());
                }
            }

            return instanceId;
        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void enableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) {
        try {
            EnableMetricsCollectionRequest collectionRequest = EnableMetricsCollectionRequest.builder()
                    .autoScalingGroupName(groupName)
                    .metrics("GroupMaxSize")
                    .granularity("1Minute")
                    .build();

            autoScalingClient.enableMetricsCollection(collectionRequest);
            System.out.println("The enable metrics collection operation was successful");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void disableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DisableMetricsCollectionRequest disableMetricsCollectionRequest = DisableMetricsCollectionRequest.builder()
                    .autoScalingGroupName(groupName)
                    .metrics("GroupMaxSize")
                    .build();

            autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest);
            System.out.println("The disable metrics collection operation was successful");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void describeAccountLimits(AutoScalingClient autoScalingClient) {
        try {
            DescribeAccountLimitsResponse response = autoScalingClient.describeAccountLimits();
            System.out.println("The max number of auto scaling groups is " + response.maxNumberOfAutoScalingGroups());
            System.out.println("The current number of auto scaling groups is " + response.numberOfAutoScalingGroups());

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName,
            String launchTemplateName) {
        try {
            AutoScalingWaiter waiter = autoScalingClient.waiter();
            LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder()
                    .launchTemplateName(launchTemplateName)
                    .build();

            UpdateAutoScalingGroupRequest groupRequest = UpdateAutoScalingGroupRequest.builder()
                    .maxSize(3)
                    .autoScalingGroupName(groupName)
                    .launchTemplate(templateSpecification)
                    .build();

            autoScalingClient.updateAutoScalingGroup(groupRequest);
            DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter
                    .waitUntilGroupInService(groupsRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("You successfully updated the auto scaling group  " + groupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId) {
        try {
            TerminateInstanceInAutoScalingGroupRequest request = TerminateInstanceInAutoScalingGroupRequest.builder()
                    .instanceId(instanceId)
                    .shouldDecrementDesiredCapacity(false)
                    .build();

            autoScalingClient.terminateInstanceInAutoScalingGroup(request);
            System.out.println("You have terminated instance " + instanceId);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder()
                    .autoScalingGroupName(groupName)
                    .forceDelete(true)
                    .build();

            autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest);
            System.out.println("You successfully deleted " + groupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の以下のトピックを参照してください。
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingInstances)
  + [DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeScalingActivities)
  + [DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DisableMetricsCollection)
  + [EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/EnableMetricsCollection)
  + [SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/SetDesiredCapacity)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/UpdateAutoScalingGroup)

## アクション
<a name="actions"></a>

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_java_2_topic"></a>

次のコード例は、`CreateAutoScalingGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
import software.amazon.awssdk.services.autoscaling.model.CreateAutoScalingGroupRequest;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;
import software.amazon.awssdk.services.autoscaling.model.LaunchTemplateSpecification;
import software.amazon.awssdk.services.autoscaling.waiters.AutoScalingWaiter;

/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CreateAutoScalingGroup {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <groupName> <launchTemplateName> <serviceLinkedRoleARN> <vpcZoneId>

                Where:
                    groupName - The name of the Auto Scaling group.
                    launchTemplateName - The name of the launch template.\s
                    vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created.
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String groupName = args[0];
        String launchTemplateName = args[1];
        String vpcZoneId = args[2];
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_EAST_1)
                .build();

        createAutoScalingGroup(autoScalingClient, groupName, launchTemplateName, vpcZoneId);
        autoScalingClient.close();
    }

    public static void createAutoScalingGroup(AutoScalingClient autoScalingClient,
            String groupName,
            String launchTemplateName,
            String vpcZoneId) {

        try {
            AutoScalingWaiter waiter = autoScalingClient.waiter();
            LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder()
                    .launchTemplateName(launchTemplateName)
                    .build();

            CreateAutoScalingGroupRequest request = CreateAutoScalingGroupRequest.builder()
                    .autoScalingGroupName(groupName)
                    .availabilityZones("us-east-1a")
                    .launchTemplate(templateSpecification)
                    .maxSize(1)
                    .minSize(1)
                    .vpcZoneIdentifier(vpcZoneId)
                    .build();

            autoScalingClient.createAutoScalingGroup(request);
            DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter
                    .waitUntilGroupExists(groupsRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Auto Scaling Group created");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_java_2_topic"></a>

次のコード例は、`DeleteAutoScalingGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
import software.amazon.awssdk.services.autoscaling.model.DeleteAutoScalingGroupRequest;

/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DeleteAutoScalingGroup {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <groupName>

                Where:
                    groupName - The name of the Auto Scaling group.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String groupName = args[0];
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_EAST_1)
                .build();

        deleteAutoScalingGroup(autoScalingClient, groupName);
        autoScalingClient.close();
    }

    public static void deleteAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder()
                    .autoScalingGroupName(groupName)
                    .forceDelete(true)
                    .build();

            autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest);
            System.out.println("You successfully deleted " + groupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_java_2_topic"></a>

次のコード例は、`DescribeAutoScalingGroups` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingGroup;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsResponse;
import software.amazon.awssdk.services.autoscaling.model.DescribeAutoScalingGroupsRequest;
import software.amazon.awssdk.services.autoscaling.model.Instance;
import java.util.List;

/**
 * Before running this SDK for Java (v2) code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DescribeAutoScalingInstances {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <groupName>

                Where:
                    groupName - The name of the Auto Scaling group.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String groupName = args[0];
        AutoScalingClient autoScalingClient = AutoScalingClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String instanceId = getAutoScaling(autoScalingClient, groupName);
        System.out.println(instanceId);
        autoScalingClient.close();
    }

    public static String getAutoScaling(AutoScalingClient autoScalingClient, String groupName) {
        try {
            String instanceId = "";
            DescribeAutoScalingGroupsRequest scalingGroupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            DescribeAutoScalingGroupsResponse response = autoScalingClient
                    .describeAutoScalingGroups(scalingGroupsRequest);
            List<AutoScalingGroup> groups = response.autoScalingGroups();
            for (AutoScalingGroup group : groups) {
                System.out.println("The group name is " + group.autoScalingGroupName());
                System.out.println("The group ARN is " + group.autoScalingGroupARN());

                List<Instance> instances = group.instances();
                for (Instance instance : instances) {
                    instanceId = instance.instanceId();
                }
            }
            return instanceId;
        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_java_2_topic"></a>

次のコード例は、`DescribeAutoScalingInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeAutoScalingInstance(AutoScalingClient autoScalingClient, String id) {
        try {
            DescribeAutoScalingInstancesRequest describeAutoScalingInstancesRequest = DescribeAutoScalingInstancesRequest
                    .builder()
                    .instanceIds(id)
                    .build();

            DescribeAutoScalingInstancesResponse response = autoScalingClient
                    .describeAutoScalingInstances(describeAutoScalingInstancesRequest);
            List<AutoScalingInstanceDetails> instances = response.autoScalingInstances();
            for (AutoScalingInstanceDetails instance : instances) {
                System.out.println("The instance lifecycle state is: " + instance.lifecycleState());
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_java_2_topic"></a>

次のコード例は、`DescribeScalingActivities` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeScalingActivities(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DescribeScalingActivitiesRequest scalingActivitiesRequest = DescribeScalingActivitiesRequest.builder()
                    .autoScalingGroupName(groupName)
                    .maxRecords(10)
                    .build();

            DescribeScalingActivitiesResponse response = autoScalingClient
                    .describeScalingActivities(scalingActivitiesRequest);
            List<Activity> activities = response.activities();
            for (Activity activity : activities) {
                System.out.println("The activity Id is " + activity.activityId());
                System.out.println("The activity details are " + activity.details());
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_java_2_topic"></a>

次のコード例は、`DisableMetricsCollection` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
    public static void disableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) {
        try {
            DisableMetricsCollectionRequest disableMetricsCollectionRequest = DisableMetricsCollectionRequest.builder()
                    .autoScalingGroupName(groupName)
                    .metrics("GroupMaxSize")
                    .build();

            autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest);
            System.out.println("The disable metrics collection operation was successful");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_java_2_topic"></a>

次のコード例は、`EnableMetricsCollection` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
    public static void enableMetricsCollection(AutoScalingClient autoScalingClient, String groupName) {
        try {
            EnableMetricsCollectionRequest collectionRequest = EnableMetricsCollectionRequest.builder()
                    .autoScalingGroupName(groupName)
                    .metrics("GroupMaxSize")
                    .granularity("1Minute")
                    .build();

            autoScalingClient.enableMetricsCollection(collectionRequest);
            System.out.println("The enable metrics collection operation was successful");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_java_2_topic"></a>

次のコード例は、`SetDesiredCapacity` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
    public static void setDesiredCapacity(AutoScalingClient autoScalingClient, String groupName) {
        try {
            SetDesiredCapacityRequest capacityRequest = SetDesiredCapacityRequest.builder()
                    .autoScalingGroupName(groupName)
                    .desiredCapacity(2)
                    .build();

            autoScalingClient.setDesiredCapacity(capacityRequest);
            System.out.println("You have set the DesiredCapacity to 2");

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_java_2_topic"></a>

次のコード例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
    public static void terminateInstanceInAutoScalingGroup(AutoScalingClient autoScalingClient, String instanceId) {
        try {
            TerminateInstanceInAutoScalingGroupRequest request = TerminateInstanceInAutoScalingGroupRequest.builder()
                    .instanceId(instanceId)
                    .shouldDecrementDesiredCapacity(false)
                    .build();

            autoScalingClient.terminateInstanceInAutoScalingGroup(request);
            System.out.println("You have terminated instance " + instanceId);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_java_2_topic"></a>

次のコード例は、`UpdateAutoScalingGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/autoscale#code-examples)での設定と実行の方法を確認してください。

```
    public static void updateAutoScalingGroup(AutoScalingClient autoScalingClient, String groupName,
            String launchTemplateName) {
        try {
            AutoScalingWaiter waiter = autoScalingClient.waiter();
            LaunchTemplateSpecification templateSpecification = LaunchTemplateSpecification.builder()
                    .launchTemplateName(launchTemplateName)
                    .build();

            UpdateAutoScalingGroupRequest groupRequest = UpdateAutoScalingGroupRequest.builder()
                    .maxSize(3)
                    .autoScalingGroupName(groupName)
                    .launchTemplate(templateSpecification)
                    .build();

            autoScalingClient.updateAutoScalingGroup(groupRequest);
            DescribeAutoScalingGroupsRequest groupsRequest = DescribeAutoScalingGroupsRequest.builder()
                    .autoScalingGroupNames(groupName)
                    .build();

            WaiterResponse<DescribeAutoScalingGroupsResponse> waiterResponse = waiter
                    .waitUntilGroupInService(groupsRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("You successfully updated the auto scaling group  " + groupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_java_2_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
public class Main {

    public static final String fileName = "C:\\AWS\\resworkflow\\recommendations.json"; // Modify file location.
    public static final String tableName = "doc-example-recommendation-service";
    public static final String startScript = "C:\\AWS\\resworkflow\\server_startup_script.sh"; // Modify file location.
    public static final String policyFile = "C:\\AWS\\resworkflow\\instance_policy.json"; // Modify file location.
    public static final String ssmJSON = "C:\\AWS\\resworkflow\\ssm_only_policy.json"; // Modify file location.
    public static final String failureResponse = "doc-example-resilient-architecture-failure-response";
    public static final String healthCheck = "doc-example-resilient-architecture-health-check";
    public static final String templateName = "doc-example-resilience-template";
    public static final String roleName = "doc-example-resilience-role";
    public static final String policyName = "doc-example-resilience-pol";
    public static final String profileName = "doc-example-resilience-prof";

    public static final String badCredsProfileName = "doc-example-resilience-prof-bc";

    public static final String targetGroupName = "doc-example-resilience-tg";
    public static final String autoScalingGroupName = "doc-example-resilience-group";
    public static final String lbName = "doc-example-resilience-lb";
    public static final String protocol = "HTTP";
    public static final int port = 80;

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner in = new Scanner(System.in);
        Database database = new Database();
        AutoScaler autoScaler = new AutoScaler();
        LoadBalancer loadBalancer = new LoadBalancer();

        System.out.println(DASHES);
        System.out.println("Welcome to the demonstration of How to Build and Manage a Resilient Service!");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("A - SETUP THE RESOURCES");
        System.out.println("Press Enter when you're ready to start deploying resources.");
        in.nextLine();
        deploy(loadBalancer);
        System.out.println(DASHES);
        System.out.println(DASHES);
        System.out.println("B - DEMO THE RESILIENCE FUNCTIONALITY");
        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        demo(loadBalancer);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("C - DELETE THE RESOURCES");
        System.out.println("""
                This concludes the demo of how to build and manage a resilient service.
                To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources
                that were created for this demo.
                """);

        System.out.println("\n Do you want to delete the resources (y/n)? ");
        String userInput = in.nextLine().trim().toLowerCase(); // Capture user input

        if (userInput.equals("y")) {
            // Delete resources here
            deleteResources(loadBalancer, autoScaler, database);
            System.out.println("Resources deleted.");
        } else {
            System.out.println("""
                    Okay, we'll leave the resources intact.
                    Don't forget to delete them when you're done with them or you might incur unexpected charges.
                    """);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The example has completed. ");
        System.out.println("\n Thanks for watching!");
        System.out.println(DASHES);
    }

    // Deletes the AWS resources used in this example.
    private static void deleteResources(LoadBalancer loadBalancer, AutoScaler autoScaler, Database database)
            throws IOException, InterruptedException {
        loadBalancer.deleteLoadBalancer(lbName);
        System.out.println("*** Wait 30 secs for resource to be deleted");
        TimeUnit.SECONDS.sleep(30);
        loadBalancer.deleteTargetGroup(targetGroupName);
        autoScaler.deleteAutoScaleGroup(autoScalingGroupName);
        autoScaler.deleteRolesPolicies(policyName, roleName, profileName);
        autoScaler.deleteTemplate(templateName);
        database.deleteTable(tableName);
    }

    private static void deploy(LoadBalancer loadBalancer) throws InterruptedException, IOException {
        Scanner in = new Scanner(System.in);
        System.out.println(
                """
                        For this demo, we'll use the AWS SDK for Java (v2) to create several AWS resources
                        to set up a load-balanced web service endpoint and explore some ways to make it resilient
                        against various kinds of failures.

                        Some of the resources create by this demo are:
                        \t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.
                        \t* An EC2 launch template that defines EC2 instances that each contain a Python web server.
                        \t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.
                        \t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.
                        """);

        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating and populating a DynamoDB table named " + tableName);
        Database database = new Database();
        database.createTable(tableName, fileName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an EC2 launch template that runs '{startup_script}' when an instance starts.
                This script starts a Python web server defined in the `server.py` script. The web server
                listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.
                For demo purposes, this server is run as the root user. In production, the best practice is to
                run a web server, such as Apache, with least-privileged credentials.

                The template also defines an IAM policy that each instance uses to assume a role that grants
                permissions to access the DynamoDB recommendation table and Systems Manager parameters
                that control the flow of the demo.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        templateCreator.createTemplate(policyFile, policyName, profileName, startScript, templateName, roleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(
                "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different Availability Zone.");
        System.out.println("*** Wait 30 secs for the VPC to be created");
        TimeUnit.SECONDS.sleep(30);
        AutoScaler autoScaler = new AutoScaler();
        String[] zones = autoScaler.createGroup(3, templateName, autoScalingGroupName);

        System.out.println("""
                At this point, you have EC2 instances created. Once each instance starts, it listens for
                HTTP requests. You can see these instances in the console or continue with the demo.
                Press Enter when you're ready to continue.
                """);

        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating variables that control the flow of the demo.");
        ParameterHelper paramHelper = new ParameterHelper();
        paramHelper.reset();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an Elastic Load Balancing target group and load balancer. The target group
                defines how the load balancer connects to instances. The load balancer provides a
                single endpoint where clients connect and dispatches requests to instances in the group.
                """);

        String vpcId = autoScaler.getDefaultVPC();
        List<Subnet> subnets = autoScaler.getSubnets(vpcId, zones);
        System.out.println("You have retrieved a list with " + subnets.size() + " subnets");
        String targetGroupArn = loadBalancer.createTargetGroup(protocol, port, vpcId, targetGroupName);
        String elbDnsName = loadBalancer.createLoadBalancer(subnets, targetGroupArn, lbName, port, protocol);
        autoScaler.attachLoadBalancerTargetGroup(autoScalingGroupName, targetGroupArn);
        System.out.println("Verifying access to the load balancer endpoint...");
        boolean wasSuccessul = loadBalancer.verifyLoadBalancerEndpoint(elbDnsName);
        if (!wasSuccessul) {
            System.out.println("Couldn't connect to the load balancer, verifying that the port is open...");
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // Create an HTTP GET request to "http://checkip.amazonaws.com"
            HttpGet httpGet = new HttpGet("http://checkip.amazonaws.com");
            try {
                // Execute the request and get the response
                HttpResponse response = httpClient.execute(httpGet);

                // Read the response content.
                String ipAddress = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8).trim();

                // Print the public IP address.
                System.out.println("Public IP Address: " + ipAddress);
                GroupInfo groupInfo = autoScaler.verifyInboundPort(vpcId, port, ipAddress);
                if (!groupInfo.isPortOpen()) {
                    System.out.println("""
                            For this example to work, the default security group for your default VPC must
                            allow access from this computer. You can either add it automatically from this
                            example or add it yourself using the AWS Management Console.
                            """);

                    System.out.println(
                            "Do you want to add a rule to security group " + groupInfo.getGroupName() + " to allow");
                    System.out.println("inbound traffic on port " + port + " from your computer's IP address (y/n) ");
                    String ans = in.nextLine();
                    if ("y".equalsIgnoreCase(ans)) {
                        autoScaler.openInboundPort(groupInfo.getGroupName(), String.valueOf(port), ipAddress);
                        System.out.println("Security group rule added.");
                    } else {
                        System.out.println("No security group rule added.");
                    }
                }

            } catch (AutoScalingException e) {
                e.printStackTrace();
            }
        } else if (wasSuccessul) {
            System.out.println("Your load balancer is ready. You can access it by browsing to:");
            System.out.println("\t http://" + elbDnsName);
        } else {
            System.out.println("Couldn't get a successful response from the load balancer endpoint. Troubleshoot by");
            System.out.println("manually verifying that your VPC and security group are configured correctly and that");
            System.out.println("you can successfully make a GET request to the load balancer.");
        }

        System.out.println("Press Enter when you're ready to continue with the demo.");
        in.nextLine();
    }

    // A method that controls the demo part of the Java program.
    public static void demo(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        ParameterHelper paramHelper = new ParameterHelper();
        System.out.println("Read the ssm_only_policy.json file");
        String ssmOnlyPolicy = readFileAsString(ssmJSON);

        System.out.println("Resetting parameters to starting values for demo.");
        paramHelper.reset();

        System.out.println(
                """
                         This part of the demonstration shows how to toggle different parts of the system
                         to create situations where the web service fails, and shows how using a resilient
                         architecture can keep the web service running in spite of these failures.

                         At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                         The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.
                         The table name is contained in a Systems Manager parameter named self.param_helper.table.
                         To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.
                        """);
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        System.out.println(
                """
                         \nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as
                         healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                        Instead of failing when the recommendation service fails, the web service can return a static response.
                        While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.
                        """);
        paramHelper.put(paramHelper.failureResponse, "static");

        System.out.println("""
                Now, sending a GET request to the load balancer endpoint returns a static response.
                The service still reports as healthy because health checks are still shallow.
                """);
        demoChoices(loadBalancer);

        System.out.println("Let's reinstate the recommendation service.");
        paramHelper.put(paramHelper.tableName, paramHelper.dyntable);

        System.out.println("""
                Let's also substitute bad credentials for one of the instances in the target group so that it can't
                access the DynamoDB recommendation table. We will get an instance id value.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        AutoScaler autoScaler = new AutoScaler();

        // Create a new instance profile based on badCredsProfileName.
        templateCreator.createInstanceProfile(policyFile, policyName, badCredsProfileName, roleName);
        String badInstanceId = autoScaler.getBadInstance(autoScalingGroupName);
        System.out.println("The bad instance id values used for this demo is " + badInstanceId);

        String profileAssociationId = autoScaler.getInstanceProfile(badInstanceId);
        System.out.println("The association Id value is " + profileAssociationId);
        System.out.println("Replacing the profile for instance " + badInstanceId
                + " with a profile that contains bad credentials");
        autoScaler.replaceInstanceProfile(badInstanceId, badCredsProfileName, profileAssociationId);

        System.out.println(
                """
                        Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,
                        depending on which instance is selected by the load balancer.
                        """);

        demoChoices(loadBalancer);

        System.out.println("""
                Let's implement a deep health check. For this demo, a deep health check tests whether
                the web service can access the DynamoDB table that it depends on for recommendations. Note that
                the deep health check is only for ELB routing and not for Auto Scaling instance health.
                This kind of deep health check is not recommended for Auto Scaling instance health, because it
                risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.
                """);

        System.out.println("""
                By implementing deep health checks, the load balancer can detect when one of the instances is failing
                and take that instance out of rotation.
                """);

        paramHelper.put(paramHelper.healthCheck, "deep");

        System.out.println("""
                Now, checking target health indicates that the instance with bad credentials
                is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy
                instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because
                the load balancer takes unhealthy instances out of its rotation.
                """);

        demoChoices(loadBalancer);

        System.out.println(
                """
                        Because the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy
                        instance is to terminate it and let the auto scaler start a new instance to replace it.
                        """);
        autoScaler.terminateInstance(badInstanceId);

        System.out.println("""
                Even while the instance is terminating and the new instance is starting, sending a GET
                request to the web service continues to get a successful recommendation response because
                the load balancer routes requests to the healthy instances. After the replacement instance
                starts and reports as healthy, it is included in the load balancing rotation.
                Note that terminating and replacing an instance typically takes several minutes, during which time you
                can see the changing health check status until the new instance is running and healthy.
                """);

        demoChoices(loadBalancer);
        System.out.println(
                "If the recommendation service fails now, deep health checks mean all instances report as unhealthy.");
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        demoChoices(loadBalancer);
        paramHelper.reset();
    }

    public static void demoChoices(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        String[] actions = {
                "Send a GET request to the load balancer endpoint.",
                "Check the health of load balancer targets.",
                "Go to the next part of the demo."
        };
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("-".repeat(88));
            System.out.println("See the current state of the service by selecting one of the following choices:");
            for (int i = 0; i < actions.length; i++) {
                System.out.println(i + ": " + actions[i]);
            }

            try {
                System.out.print("\nWhich action would you like to take? ");
                int choice = scanner.nextInt();
                System.out.println("-".repeat(88));

                switch (choice) {
                    case 0 -> {
                        System.out.println("Request:\n");
                        System.out.println("GET http://" + loadBalancer.getEndpoint(lbName));
                        CloseableHttpClient httpClient = HttpClients.createDefault();

                        // Create an HTTP GET request to the ELB.
                        HttpGet httpGet = new HttpGet("http://" + loadBalancer.getEndpoint(lbName));

                        // Execute the request and get the response.
                        HttpResponse response = httpClient.execute(httpGet);
                        int statusCode = response.getStatusLine().getStatusCode();
                        System.out.println("HTTP Status Code: " + statusCode);

                        // Display the JSON response
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        reader.close();

                        // Print the formatted JSON response.
                        System.out.println("Full Response:\n");
                        System.out.println(jsonResponse.toString());

                        // Close the HTTP client.
                        httpClient.close();

                    }
                    case 1 -> {
                        System.out.println("\nChecking the health of load balancer targets:\n");
                        List<TargetHealthDescription> health = loadBalancer.checkTargetHealth(targetGroupName);
                        for (TargetHealthDescription target : health) {
                            System.out.printf("\tTarget %s on port %d is %s%n", target.target().id(),
                                    target.target().port(), target.targetHealth().stateAsString());
                        }
                        System.out.println("""
                                Note that it can take a minute or two for the health check to update
                                after changes are made.
                                """);
                    }
                    case 2 -> {
                        System.out.println("\nOkay, let's move on.");
                        System.out.println("-".repeat(88));
                        return; // Exit the method when choice is 2
                    }
                    default -> System.out.println("You must choose a value between 0-2. Please select again.");
                }

            } catch (java.util.InputMismatchException e) {
                System.out.println("Invalid input. Please select again.");
                scanner.nextLine(); // Clear the input buffer.
            }
        }
    }

    public static String readFileAsString(String filePath) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        return new String(bytes);
    }
}
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
public class AutoScaler {

    private static Ec2Client ec2Client;
    private static AutoScalingClient autoScalingClient;
    private static IamClient iamClient;

    private static SsmClient ssmClient;

    private IamClient getIAMClient() {
        if (iamClient == null) {
            iamClient = IamClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return iamClient;
    }

    private SsmClient getSSMClient() {
        if (ssmClient == null) {
            ssmClient = SsmClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ssmClient;
    }

    private Ec2Client getEc2Client() {
        if (ec2Client == null) {
            ec2Client = Ec2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ec2Client;
    }

    private AutoScalingClient getAutoScalingClient() {
        if (autoScalingClient == null) {
            autoScalingClient = AutoScalingClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return autoScalingClient;
    }

    /**
     * Terminates and instances in an EC2 Auto Scaling group. After an instance is
     * terminated, it can no longer be accessed.
     */
    public void terminateInstance(String instanceId) {
        TerminateInstanceInAutoScalingGroupRequest terminateInstanceIRequest = TerminateInstanceInAutoScalingGroupRequest
                .builder()
                .instanceId(instanceId)
                .shouldDecrementDesiredCapacity(false)
                .build();

        getAutoScalingClient().terminateInstanceInAutoScalingGroup(terminateInstanceIRequest);
        System.out.format("Terminated instance %s.", instanceId);
    }

    /**
     * Replaces the profile associated with a running instance. After the profile is
     * replaced, the instance is rebooted to ensure that it uses the new profile.
     * When
     * the instance is ready, Systems Manager is used to restart the Python web
     * server.
     */
    public void replaceInstanceProfile(String instanceId, String newInstanceProfileName, String profileAssociationId)
            throws InterruptedException {
        // Create an IAM instance profile specification.
        software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification iamInstanceProfile = software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification
                .builder()
                .name(newInstanceProfileName) // Make sure 'newInstanceProfileName' is a valid IAM Instance Profile
                                              // name.
                .build();

        // Replace the IAM instance profile association for the EC2 instance.
        ReplaceIamInstanceProfileAssociationRequest replaceRequest = ReplaceIamInstanceProfileAssociationRequest
                .builder()
                .iamInstanceProfile(iamInstanceProfile)
                .associationId(profileAssociationId) // Make sure 'profileAssociationId' is a valid association ID.
                .build();

        try {
            getEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);
            // Handle the response as needed.
        } catch (Ec2Exception e) {
            // Handle exceptions, log, or report the error.
            System.err.println("Error: " + e.getMessage());
        }
        System.out.format("Replaced instance profile for association %s with profile %s.", profileAssociationId,
                newInstanceProfileName);
        TimeUnit.SECONDS.sleep(15);
        boolean instReady = false;
        int tries = 0;

        // Reboot after 60 seconds
        while (!instReady) {
            if (tries % 6 == 0) {
                getEc2Client().rebootInstances(RebootInstancesRequest.builder()
                        .instanceIds(instanceId)
                        .build());
                System.out.println("Rebooting instance " + instanceId + " and waiting for it to be ready.");
            }
            tries++;
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            DescribeInstanceInformationResponse informationResponse = getSSMClient().describeInstanceInformation();
            List<InstanceInformation> instanceInformationList = informationResponse.instanceInformationList();
            for (InstanceInformation info : instanceInformationList) {
                if (info.instanceId().equals(instanceId)) {
                    instReady = true;
                    break;
                }
            }
        }

        SendCommandRequest sendCommandRequest = SendCommandRequest.builder()
                .instanceIds(instanceId)
                .documentName("AWS-RunShellScript")
                .parameters(Collections.singletonMap("commands",
                        Collections.singletonList("cd / && sudo python3 server.py 80")))
                .build();

        getSSMClient().sendCommand(sendCommandRequest);
        System.out.println("Restarted the Python web server on instance " + instanceId + ".");
    }

    public void openInboundPort(String secGroupId, String port, String ipAddress) {
        AuthorizeSecurityGroupIngressRequest ingressRequest = AuthorizeSecurityGroupIngressRequest.builder()
                .groupName(secGroupId)
                .cidrIp(ipAddress)
                .fromPort(Integer.parseInt(port))
                .build();

        getEc2Client().authorizeSecurityGroupIngress(ingressRequest);
        System.out.format("Authorized ingress to %s on port %s from %s.", secGroupId, port, ipAddress);
    }

    /**
     * Detaches a role from an instance profile, detaches policies from the role,
     * and deletes all the resources.
     */
    public void deleteInstanceProfile(String roleName, String profileName) {
        try {
            software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest getInstanceProfileRequest = software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest
                    .builder()
                    .instanceProfileName(profileName)
                    .build();

            GetInstanceProfileResponse response = getIAMClient().getInstanceProfile(getInstanceProfileRequest);
            String name = response.instanceProfile().instanceProfileName();
            System.out.println(name);

            RemoveRoleFromInstanceProfileRequest profileRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .roleName(roleName)
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(profileRequest);
            DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .build();

            getIAMClient().deleteInstanceProfile(deleteInstanceProfileRequest);
            System.out.println("Deleted instance profile " + profileName);

            DeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            // List attached role policies.
            ListAttachedRolePoliciesResponse rolesResponse = getIAMClient()
                    .listAttachedRolePolicies(role -> role.roleName(roleName));
            List<AttachedPolicy> attachedPolicies = rolesResponse.attachedPolicies();
            for (AttachedPolicy attachedPolicy : attachedPolicies) {
                DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
                        .roleName(roleName)
                        .policyArn(attachedPolicy.policyArn())
                        .build();

                getIAMClient().detachRolePolicy(request);
                System.out.println("Detached and deleted policy " + attachedPolicy.policyName());
            }

            getIAMClient().deleteRole(deleteRoleRequest);
            System.out.println("Instance profile and role deleted.");

        } catch (IamException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public void deleteTemplate(String templateName) {
        getEc2Client().deleteLaunchTemplate(name -> name.launchTemplateName(templateName));
        System.out.format(templateName + " was deleted.");
    }

    public void deleteAutoScaleGroup(String groupName) {
        DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder()
                .autoScalingGroupName(groupName)
                .forceDelete(true)
                .build();

        getAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);
        System.out.println(groupName + " was deleted.");
    }

    /*
     * Verify the default security group of the specified VPC allows ingress from
     * this
     * computer. This can be done by allowing ingress from this computer's IP
     * address. In some situations, such as connecting from a corporate network, you
     * must instead specify a prefix list ID. You can also temporarily open the port
     * to
     * any IP address while running this example. If you do, be sure to remove
     * public
     * access when you're done.
     * 
     */
    public GroupInfo verifyInboundPort(String VPC, int port, String ipAddress) {
        boolean portIsOpen = false;
        GroupInfo groupInfo = new GroupInfo();
        try {
            Filter filter = Filter.builder()
                    .name("group-name")
                    .values("default")
                    .build();

            Filter filter1 = Filter.builder()
                    .name("vpc-id")
                    .values(VPC)
                    .build();

            DescribeSecurityGroupsRequest securityGroupsRequest = DescribeSecurityGroupsRequest.builder()
                    .filters(filter, filter1)
                    .build();

            DescribeSecurityGroupsResponse securityGroupsResponse = getEc2Client()
                    .describeSecurityGroups(securityGroupsRequest);
            String securityGroup = securityGroupsResponse.securityGroups().get(0).groupName();
            groupInfo.setGroupName(securityGroup);

            for (SecurityGroup secGroup : securityGroupsResponse.securityGroups()) {
                System.out.println("Found security group: " + secGroup.groupId());

                for (IpPermission ipPermission : secGroup.ipPermissions()) {
                    if (ipPermission.fromPort() == port) {
                        System.out.println("Found inbound rule: " + ipPermission);
                        for (IpRange ipRange : ipPermission.ipRanges()) {
                            String cidrIp = ipRange.cidrIp();
                            if (cidrIp.startsWith(ipAddress) || cidrIp.equals("0.0.0.0/0")) {
                                System.out.println(cidrIp + " is applicable");
                                portIsOpen = true;
                            }
                        }

                        if (!ipPermission.prefixListIds().isEmpty()) {
                            System.out.println("Prefix lList is applicable");
                            portIsOpen = true;
                        }

                        if (!portIsOpen) {
                            System.out
                                    .println("The inbound rule does not appear to be open to either this computer's IP,"
                                            + " all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                        } else {
                            break;
                        }
                    }
                }
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }

        groupInfo.setPortOpen(portIsOpen);
        return groupInfo;
    }

    /*
     * Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto
     * Scaling group.
     * The target group specifies how the load balancer forward requests to the
     * instances
     * in the group.
     */
    public void attachLoadBalancerTargetGroup(String asGroupName, String targetGroupARN) {
        try {
            AttachLoadBalancerTargetGroupsRequest targetGroupsRequest = AttachLoadBalancerTargetGroupsRequest.builder()
                    .autoScalingGroupName(asGroupName)
                    .targetGroupARNs(targetGroupARN)
                    .build();

            getAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);
            System.out.println("Attached load balancer to " + asGroupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Creates an EC2 Auto Scaling group with the specified size.
    public String[] createGroup(int groupSize, String templateName, String autoScalingGroupName) {

        // Get availability zones.
        software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest zonesRequest = software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest
                .builder()
                .build();

        DescribeAvailabilityZonesResponse zonesResponse = getEc2Client().describeAvailabilityZones(zonesRequest);
        List<String> availabilityZoneNames = zonesResponse.availabilityZones().stream()
                .map(software.amazon.awssdk.services.ec2.model.AvailabilityZone::zoneName)
                .collect(Collectors.toList());

        String availabilityZones = String.join(",", availabilityZoneNames);
        LaunchTemplateSpecification specification = LaunchTemplateSpecification.builder()
                .launchTemplateName(templateName)
                .version("$Default")
                .build();

        String[] zones = availabilityZones.split(",");
        CreateAutoScalingGroupRequest groupRequest = CreateAutoScalingGroupRequest.builder()
                .launchTemplate(specification)
                .availabilityZones(zones)
                .maxSize(groupSize)
                .minSize(groupSize)
                .autoScalingGroupName(autoScalingGroupName)
                .build();

        try {
            getAutoScalingClient().createAutoScalingGroup(groupRequest);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Created an EC2 Auto Scaling group named " + autoScalingGroupName);
        return zones;
    }

    public String getDefaultVPC() {
        // Define the filter.
        Filter defaultFilter = Filter.builder()
                .name("is-default")
                .values("true")
                .build();

        software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest request = software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest
                .builder()
                .filters(defaultFilter)
                .build();

        DescribeVpcsResponse response = getEc2Client().describeVpcs(request);
        return response.vpcs().get(0).vpcId();
    }

    // Gets the default subnets in a VPC for a specified list of Availability Zones.
    public List<Subnet> getSubnets(String vpcId, String[] availabilityZones) {
        List<Subnet> subnets = null;
        Filter vpcFilter = Filter.builder()
                .name("vpc-id")
                .values(vpcId)
                .build();

        Filter azFilter = Filter.builder()
                .name("availability-zone")
                .values(availabilityZones)
                .build();

        Filter defaultForAZ = Filter.builder()
                .name("default-for-az")
                .values("true")
                .build();

        DescribeSubnetsRequest request = DescribeSubnetsRequest.builder()
                .filters(vpcFilter, azFilter, defaultForAZ)
                .build();

        DescribeSubnetsResponse response = getEc2Client().describeSubnets(request);
        subnets = response.subnets();
        return subnets;
    }

    // Gets data about the instances in the EC2 Auto Scaling group.
    public String getBadInstance(String groupName) {
        DescribeAutoScalingGroupsRequest request = DescribeAutoScalingGroupsRequest.builder()
                .autoScalingGroupNames(groupName)
                .build();

        DescribeAutoScalingGroupsResponse response = getAutoScalingClient().describeAutoScalingGroups(request);
        AutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);
        List<String> instanceIds = autoScalingGroup.instances().stream()
                .map(instance -> instance.instanceId())
                .collect(Collectors.toList());

        String[] instanceIdArray = instanceIds.toArray(new String[0]);
        for (String instanceId : instanceIdArray) {
            System.out.println("Instance ID: " + instanceId);
            return instanceId;
        }
        return "";
    }

    // Gets data about the profile associated with an instance.
    public String getInstanceProfile(String instanceId) {
        Filter filter = Filter.builder()
                .name("instance-id")
                .values(instanceId)
                .build();

        DescribeIamInstanceProfileAssociationsRequest associationsRequest = DescribeIamInstanceProfileAssociationsRequest
                .builder()
                .filters(filter)
                .build();

        DescribeIamInstanceProfileAssociationsResponse response = getEc2Client()
                .describeIamInstanceProfileAssociations(associationsRequest);
        return response.iamInstanceProfileAssociations().get(0).associationId();
    }

    public void deleteRolesPolicies(String policyName, String roleName, String InstanceProfile) {
        ListPoliciesRequest listPoliciesRequest = ListPoliciesRequest.builder().build();
        ListPoliciesResponse listPoliciesResponse = getIAMClient().listPolicies(listPoliciesRequest);
        for (Policy policy : listPoliciesResponse.policies()) {
            if (policy.policyName().equals(policyName)) {
                // List the entities (users, groups, roles) that are attached to the policy.
                software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest listEntitiesRequest = software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest
                        .builder()
                        .policyArn(policy.arn())
                        .build();
                ListEntitiesForPolicyResponse listEntitiesResponse = iamClient
                        .listEntitiesForPolicy(listEntitiesRequest);
                if (!listEntitiesResponse.policyGroups().isEmpty() || !listEntitiesResponse.policyUsers().isEmpty()
                        || !listEntitiesResponse.policyRoles().isEmpty()) {
                    // Detach the policy from any entities it is attached to.
                    DetachRolePolicyRequest detachPolicyRequest = DetachRolePolicyRequest.builder()
                            .policyArn(policy.arn())
                            .roleName(roleName) // Specify the name of the IAM role
                            .build();

                    getIAMClient().detachRolePolicy(detachPolicyRequest);
                    System.out.println("Policy detached from entities.");
                }

                // Now, you can delete the policy.
                DeletePolicyRequest deletePolicyRequest = DeletePolicyRequest.builder()
                        .policyArn(policy.arn())
                        .build();

                getIAMClient().deletePolicy(deletePolicyRequest);
                System.out.println("Policy deleted successfully.");
                break;
            }
        }

        // List the roles associated with the instance profile
        ListInstanceProfilesForRoleRequest listRolesRequest = ListInstanceProfilesForRoleRequest.builder()
                .roleName(roleName)
                .build();

        // Detach the roles from the instance profile
        ListInstanceProfilesForRoleResponse listRolesResponse = iamClient.listInstanceProfilesForRole(listRolesRequest);
        for (software.amazon.awssdk.services.iam.model.InstanceProfile profile : listRolesResponse.instanceProfiles()) {
            RemoveRoleFromInstanceProfileRequest removeRoleRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(InstanceProfile)
                    .roleName(roleName) // Remove the extra dot here
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(removeRoleRequest);
            System.out.println("Role " + roleName + " removed from instance profile " + InstanceProfile);
        }

        // Delete the instance profile after removing all roles
        DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                .instanceProfileName(InstanceProfile)
                .build();

        getIAMClient().deleteInstanceProfile(r -> r.instanceProfileName(InstanceProfile));
        System.out.println(InstanceProfile + " Deleted");
        System.out.println("All roles and policies are deleted.");
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
public class LoadBalancer {
    public ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;

    public ElasticLoadBalancingV2Client getLoadBalancerClient() {
        if (elasticLoadBalancingV2Client == null) {
            elasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }

        return elasticLoadBalancingV2Client;
    }

    // Checks the health of the instances in the target group.
    public List<TargetHealthDescription> checkTargetHealth(String targetGroupName) {
        DescribeTargetGroupsRequest targetGroupsRequest = DescribeTargetGroupsRequest.builder()
                .names(targetGroupName)
                .build();

        DescribeTargetGroupsResponse tgResponse = getLoadBalancerClient().describeTargetGroups(targetGroupsRequest);

        DescribeTargetHealthRequest healthRequest = DescribeTargetHealthRequest.builder()
                .targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())
                .build();

        DescribeTargetHealthResponse healthResponse = getLoadBalancerClient().describeTargetHealth(healthRequest);
        return healthResponse.targetHealthDescriptions();
    }

    // Gets the HTTP endpoint of the load balancer.
    public String getEndpoint(String lbName) {
        DescribeLoadBalancersResponse res = getLoadBalancerClient()
                .describeLoadBalancers(describe -> describe.names(lbName));
        return res.loadBalancers().get(0).dnsName();
    }

    // Deletes a load balancer.
    public void deleteLoadBalancer(String lbName) {
        try {
            // Use a waiter to delete the Load Balancer.
            DescribeLoadBalancersResponse res = getLoadBalancerClient()
                    .describeLoadBalancers(describe -> describe.names(lbName));
            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())
                    .build();

            getLoadBalancerClient().deleteLoadBalancer(
                    builder -> builder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancersDeleted(request);
            waiterResponse.matched().response().ifPresent(System.out::println);

        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(lbName + " was deleted.");
    }

    // Deletes the target group.
    public void deleteTargetGroup(String targetGroupName) {
        try {
            DescribeTargetGroupsResponse res = getLoadBalancerClient()
                    .describeTargetGroups(describe -> describe.names(targetGroupName));
            getLoadBalancerClient()
                    .deleteTargetGroup(builder -> builder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));
        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(targetGroupName + " was deleted.");
    }

    // Verify this computer can successfully send a GET request to the load balancer
    // endpoint.
    public boolean verifyLoadBalancerEndpoint(String elbDnsName) throws IOException, InterruptedException {
        boolean success = false;
        int retries = 3;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // Create an HTTP GET request to the ELB.
        HttpGet httpGet = new HttpGet("http://" + elbDnsName);
        try {
            while ((!success) && (retries > 0)) {
                // Execute the request and get the response.
                HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);
                if (statusCode == 200) {
                    success = true;
                } else {
                    retries--;
                    System.out.println("Got connection error from load balancer endpoint, retrying...");
                    TimeUnit.SECONDS.sleep(15);
                }
            }

        } catch (org.apache.http.conn.HttpHostConnectException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Status.." + success);
        return success;
    }

    /*
     * Creates an Elastic Load Balancing target group. The target group specifies
     * how
     * the load balancer forward requests to instances in the group and how instance
     * health is checked.
     */
    public String createTargetGroup(String protocol, int port, String vpcId, String targetGroupName) {
        CreateTargetGroupRequest targetGroupRequest = CreateTargetGroupRequest.builder()
                .healthCheckPath("/healthcheck")
                .healthCheckTimeoutSeconds(5)
                .port(port)
                .vpcId(vpcId)
                .name(targetGroupName)
                .protocol(protocol)
                .build();

        CreateTargetGroupResponse targetGroupResponse = getLoadBalancerClient().createTargetGroup(targetGroupRequest);
        String targetGroupArn = targetGroupResponse.targetGroups().get(0).targetGroupArn();
        String targetGroup = targetGroupResponse.targetGroups().get(0).targetGroupName();
        System.out.println("The " + targetGroup + " was created with ARN" + targetGroupArn);
        return targetGroupArn;
    }

    /*
     * Creates an Elastic Load Balancing load balancer that uses the specified
     * subnets
     * and forwards requests to the specified target group.
     */
    public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port,
            String protocol) {
        try {
            List<String> subnetIdStrings = subnetIds.stream()
                    .map(Subnet::subnetId)
                    .collect(Collectors.toList());

            CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder()
                    .subnets(subnetIdStrings)
                    .name(lbName)
                    .scheme("internet-facing")
                    .build();

            // Create and wait for the load balancer to become available.
            CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest);
            String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();

            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(lbARN)
                    .build();

            System.out.println("Waiting for Load Balancer " + lbName + " to become available.");
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancerAvailable(request);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Load Balancer " + lbName + " is available.");

            // Get the DNS name (endpoint) of the load balancer.
            String lbDNSName = lsResponse.loadBalancers().get(0).dnsName();
            System.out.println("*** Load Balancer DNS Name: " + lbDNSName);

            // Create a listener for the load balance.
            Action action = Action.builder()
                    .targetGroupArn(targetGroupARN)
                    .type("forward")
                    .build();

            CreateListenerRequest listenerRequest = CreateListenerRequest.builder()
                    .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())
                    .defaultActions(action)
                    .port(port)
                    .protocol(protocol)
                    .build();

            getLoadBalancerClient().createListener(listenerRequest);
            System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group "
                    + targetGroupARN);

            // Return the load balancer DNS name.
            return lbDNSName;

        } catch (ElasticLoadBalancingV2Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
public class Database {

    private static DynamoDbClient dynamoDbClient;

    public static DynamoDbClient getDynamoDbClient() {
        if (dynamoDbClient == null) {
            dynamoDbClient = DynamoDbClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return dynamoDbClient;
    }

    // Checks to see if the Amazon DynamoDB table exists.
    private boolean doesTableExist(String tableName) {
        try {
            // Describe the table and catch any exceptions.
            DescribeTableRequest describeTableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            getDynamoDbClient().describeTable(describeTableRequest);
            System.out.println("Table '" + tableName + "' exists.");
            return true;

        } catch (ResourceNotFoundException e) {
            System.out.println("Table '" + tableName + "' does not exist.");
        } catch (DynamoDbException e) {
            System.err.println("Error checking table existence: " + e.getMessage());
        }
        return false;
    }

    /*
     * Creates a DynamoDB table to use a recommendation service. The table has a
     * hash key named 'MediaType' that defines the type of media recommended, such
     * as
     * Book or Movie, and a range key named 'ItemId' that, combined with the
     * MediaType,
     * forms a unique identifier for the recommended item.
     */
    public void createTable(String tableName, String fileName) throws IOException {
        // First check to see if the table exists.
        boolean doesExist = doesTableExist(tableName);
        if (!doesExist) {
            DynamoDbWaiter dbWaiter = getDynamoDbClient().waiter();
            CreateTableRequest createTableRequest = CreateTableRequest.builder()
                    .tableName(tableName)
                    .attributeDefinitions(
                            AttributeDefinition.builder()
                                    .attributeName("MediaType")
                                    .attributeType(ScalarAttributeType.S)
                                    .build(),
                            AttributeDefinition.builder()
                                    .attributeName("ItemId")
                                    .attributeType(ScalarAttributeType.N)
                                    .build())
                    .keySchema(
                            KeySchemaElement.builder()
                                    .attributeName("MediaType")
                                    .keyType(KeyType.HASH)
                                    .build(),
                            KeySchemaElement.builder()
                                    .attributeName("ItemId")
                                    .keyType(KeyType.RANGE)
                                    .build())
                    .provisionedThroughput(
                            ProvisionedThroughput.builder()
                                    .readCapacityUnits(5L)
                                    .writeCapacityUnits(5L)
                                    .build())
                    .build();

            getDynamoDbClient().createTable(createTableRequest);
            System.out.println("Creating table " + tableName + "...");

            // Wait until the Amazon DynamoDB table is created.
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Table " + tableName + " created.");

            // Add records to the table.
            populateTable(fileName, tableName);
        }
    }

    public void deleteTable(String tableName) {
        getDynamoDbClient().deleteTable(table -> table.tableName(tableName));
        System.out.println("Table " + tableName + " deleted.");
    }

    // Populates the table with data located in a JSON file using the DynamoDB
    // enhanced client.
    public void populateTable(String fileName, String tableName) throws IOException {
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(getDynamoDbClient())
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        File jsonFile = new File(fileName);
        JsonNode rootNode = objectMapper.readTree(jsonFile);

        DynamoDbTable<Recommendation> mappedTable = enhancedClient.table(tableName,
                TableSchema.fromBean(Recommendation.class));
        for (JsonNode currentNode : rootNode) {
            String mediaType = currentNode.path("MediaType").path("S").asText();
            int itemId = currentNode.path("ItemId").path("N").asInt();
            String title = currentNode.path("Title").path("S").asText();
            String creator = currentNode.path("Creator").path("S").asText();

            // Create a Recommendation object and set its properties.
            Recommendation rec = new Recommendation();
            rec.setMediaType(mediaType);
            rec.setItemId(itemId);
            rec.setTitle(title);
            rec.setCreator(creator);

            // Put the item into the DynamoDB table.
            mappedTable.putItem(rec); // Add the Recommendation to the list.
        }
        System.out.println("Added all records to the " + tableName);
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
public class ParameterHelper {

    String tableName = "doc-example-resilient-architecture-table";
    String dyntable = "doc-example-recommendation-service";
    String failureResponse = "doc-example-resilient-architecture-failure-response";
    String healthCheck = "doc-example-resilient-architecture-health-check";

    public void reset() {
        put(dyntable, tableName);
        put(failureResponse, "none");
        put(healthCheck, "shallow");
    }

    public void put(String name, String value) {
        SsmClient ssmClient = SsmClient.builder()
                .region(Region.US_EAST_1)
                .build();

        PutParameterRequest parameterRequest = PutParameterRequest.builder()
                .name(name)
                .value(value)
                .overwrite(true)
                .type("String")
                .build();

        ssmClient.putParameter(parameterRequest);
        System.out.printf("Setting demo parameter %s to '%s'.", name, value);
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# AWS Batch SDK for Java 2.x を使用した例
<a name="java_2_batch_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Batch。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Batchは
<a name="batch_Hello_java_2_topic"></a>

次のコード例は、 AWS Batchの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.batch.BatchAsyncClient;
import software.amazon.awssdk.services.batch.model.JobStatus;
import software.amazon.awssdk.services.batch.model.JobSummary;
import software.amazon.awssdk.services.batch.model.ListJobsRequest;
import software.amazon.awssdk.services.batch.paginators.ListJobsPublisher;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class HelloBatch {
    private static BatchAsyncClient batchClient;

    public static void main(String[] args) {
        List<JobSummary> jobs = listJobs("my-job-queue");
        jobs.forEach(job ->
            System.out.printf("Job ID: %s, Job Name: %s, Job Status: %s%n",
                job.jobId(), job.jobName(), job.status())
        );
    }

    public static List<JobSummary> listJobs(String jobQueue) {
        if (jobQueue == null || jobQueue.isEmpty()) {
            throw new IllegalArgumentException("Job queue cannot be null or empty");
        }

        ListJobsRequest listJobsRequest = ListJobsRequest.builder()
            .jobQueue(jobQueue)
            .jobStatus(JobStatus.SUCCEEDED)
            .build();

        List<JobSummary> jobSummaries = new ArrayList<>();
        ListJobsPublisher listJobsPaginator = getAsyncClient().listJobsPaginator(listJobsRequest);
        CompletableFuture<Void> future = listJobsPaginator.subscribe(response -> {
            jobSummaries.addAll(response.jobSummaryList());
        });

        future.join();
        return jobSummaries;
    }

    private static BatchAsyncClient getAsyncClient() {
        SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
            .maxConcurrency(100)  // Increase max concurrency to handle more simultaneous connections.
            .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
            .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
            .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
            .build();

        ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
            .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
            .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
            .retryPolicy(RetryPolicy.builder()  // Add a retry policy to handle transient errors.
                .numRetries(3)  // Number of retry attempts.
                .build())
            .build();

        if (batchClient == null) {
            batchClient = BatchAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return batchClient;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[listJobsPaginator](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/listJobsPaginator)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="batch_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS Batch コンピューティング環境を作成します。
+ コンピューティング環境のステータスを確認する。
+  AWS Batch ジョブキューとジョブ定義を設定します。
+ ジョブ定義を登録する。
+  AWS Batch ジョブを送信します。
+ ジョブキューに該当するジョブのリストを取得する。
+ ジョブのステータスを確認する。
+  AWS Batch リソースを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。
 AWS Batch 機能を示すインタラクティブなシナリオを実行します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.batch.model.BatchException;
import software.amazon.awssdk.services.batch.model.ClientException;
import software.amazon.awssdk.services.batch.model.CreateComputeEnvironmentResponse;
import software.amazon.awssdk.services.batch.model.JobSummary;
import software.amazon.awssdk.services.ec2.Ec2AsyncClient;
import software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsRequest;
import software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsResponse;
import software.amazon.awssdk.services.ec2.model.DescribeSubnetsRequest;
import software.amazon.awssdk.services.ec2.model.DescribeSubnetsResponse;
import software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest;
import software.amazon.awssdk.services.ec2.model.Filter;
import software.amazon.awssdk.services.ec2.model.SecurityGroup;
import software.amazon.awssdk.services.ec2.model.Subnet;
import software.amazon.awssdk.services.ec2.model.Vpc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

/**
 * 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
 *
 * NOTE
 * This scenario submits a job that pulls a Docker image named echo-text from Amazon ECR to Amazon Fargate.
 *
 * To place this Docker image on Amazon ECR, run the following Basics scenario.
 *
 * https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr
 *
 */
public class BatchScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    // Define two stacks used in this Basics Scenario.
    private static final String ROLES_STACK = "RolesStack";
    private static String defaultSubnet;
    private static String defaultSecurityGroup;

    private static final Logger logger = LoggerFactory.getLogger(BatchScenario.class);

    public static void main(String[] args) throws InterruptedException {

        BatchActions batchActions = new BatchActions();
        Scanner scanner = new Scanner(System.in);
        String computeEnvironmentName = "my-compute-environment";
        String jobQueueName = "my-job-queue";
        String jobDefinitionName = "my-job-definition";


        // See the NOTE in this Java code example (at start).
        String dockerImage = "dkr.ecr.us-east-1.amazonaws.com/echo-text:echo-text";

        logger.info("""
            AWS Batch is a fully managed batch processing service that dynamically provisions the required compute 
            resources for batch computing workloads. The Java V2 `BatchAsyncClient` allows 
            developers to automate the submission, monitoring, and management of batch jobs.
                        
            This scenario provides an example of setting up a compute environment, job queue and job definition, 
            and then submitting a job.
            
            This scenario submits a job that pulls a Docker image named echo-text from Amazon ECR to Amazon Fargate.
            
            To place this Docker image on Amazon ECR, run the following Basics scenario.
            
            https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr
            
            Let's get started...
                        
            You have two choices:
            
            1 - Run the entire program.
            2 - Delete an existing Compute Environment (created from a previous execution of 
            this program that did not complete).
            """);

        while (true) {
            String input = scanner.nextLine();
            if (input.trim().equalsIgnoreCase("1")) {
                logger.info("Continuing with the program...");
               // logger.info("");
                break;
            } else if (input.trim().equalsIgnoreCase("2")) {
                String jobQueueARN = String.valueOf(batchActions. describeJobQueueAsync(computeEnvironmentName));
                if (!jobQueueARN.isEmpty()) {
                    batchActions.disableJobQueueAsync(jobQueueARN);
                    countdown(1);
                    batchActions.deleteJobQueueAsync(jobQueueARN);
                }

                try {
                    batchActions.disableComputeEnvironmentAsync(computeEnvironmentName)
                        .exceptionally(ex -> {
                            logger.info("Disable compute environment failed: " + ex.getMessage());
                            return null;
                        })
                        .join();
                } catch (CompletionException ex) {
                    logger.info("Failed to disable compute environment: " + ex.getMessage());
                }
                countdown(2);
                batchActions.deleteComputeEnvironmentAsync(computeEnvironmentName).join();
                return;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
        System.out.println(DASHES);

        waitForInputToContinue(scanner);
        // Get an AWS Account id used to retrieve the docker image from Amazon ECR.
        // Create a single-element array to store the `accountId` value.
        String[] accId = new String[1];
        CompletableFuture<String> accountIdFuture = batchActions.getAccountId();
        accountIdFuture.thenAccept(accountId -> {
            logger.info("Account ID: " + accountId);
            accId[0] = accountId;
        }).join();

        dockerImage = accId[0]+"."+dockerImage;

        // Get a default subnet and default security associated with the default VPC.
        getSubnetSecurityGroup();

        logger.info("Use AWS CloudFormation to create two IAM roles that are required for this scenario.");
        CloudFormationHelper.deployCloudFormationStack(ROLES_STACK);

        Map<String, String> stackOutputs = CloudFormationHelper.getStackOutputs(ROLES_STACK);
        String batchIAMRole = stackOutputs.get("BatchRoleArn");
        String executionRoleARN = stackOutputs.get("EcsRoleArn");

        logger.info("The IAM role needed to interact with AWS Batch is "+batchIAMRole);
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("1. Create a Batch compute environment");
        logger.info("""
            A compute environment is a resource where you can run your batch jobs. 
            After creating a compute environment, you can define job queues and job definitions to submit jobs for 
            execution. 
            
            The benefit of creating a compute environment is it allows you to easily configure and manage the compute 
            resources that will be used to run your Batch jobs. By separating the compute environment from the job definitions,
            you can easily scale your compute resources up or down as needed, without having to modify your job definitions. 
            This makes it easier to manage your Batch workloads and ensures that your jobs have the necessary 
            compute resources to run efficiently.
            """);

        waitForInputToContinue(scanner);
        try {
            CompletableFuture<CreateComputeEnvironmentResponse> future = batchActions.createComputeEnvironmentAsync(computeEnvironmentName, batchIAMRole, defaultSubnet, defaultSecurityGroup);
            CreateComputeEnvironmentResponse response = future.join();
            logger.info("Compute Environment ARN: " + response.computeEnvironmentArn());
        } catch (RuntimeException rte) {
            Throwable cause = rte.getCause();
            if (cause instanceof ClientException batchExceptionEx) {
                String myErrorCode = batchExceptionEx.awsErrorDetails().errorMessage();
                if ("Object already exists".contains(myErrorCode)) {
                    logger.info("The compute environment '" + computeEnvironmentName + "' already exists. Moving on...");
                } else {
                    logger.info("Batch error occurred: {} (Code: {})", batchExceptionEx.getMessage(), batchExceptionEx.awsErrorDetails().errorCode());
                    return;
                }
            } else {
                    logger.info("An unexpected error occurred: {}", (cause != null ? cause.getMessage() : rte.getMessage()));
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. Check the status of the "+computeEnvironmentName +" Compute Environment.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<String> future = batchActions.checkComputeEnvironmentsStatus(computeEnvironmentName);
            String status = future.join();
            logger.info("Compute Environment Status: " + status);

        } catch (RuntimeException rte) {
            Throwable cause = rte.getCause();
            if (cause instanceof ClientException batchExceptionEx) {
                logger.info("Batch error occurred: {} (Code: {})", batchExceptionEx.getMessage(), batchExceptionEx.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: " + (cause != null ? cause.getMessage() : rte.getMessage()));
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("3. Create a job queue");
        logger.info("""
             A job queue is an essential component that helps manage the execution of your batch jobs. 
             It acts as a buffer, where jobs are placed and then scheduled for execution based on their 
             priority and the available resources in the compute environment. 
             """);
        waitForInputToContinue(scanner);

        String jobQueueArn = null;
        try {
            CompletableFuture<String> jobQueueFuture = batchActions.createJobQueueAsync(jobQueueName, computeEnvironmentName);
            jobQueueArn = jobQueueFuture.join();
            logger.info("Job Queue ARN: " + jobQueueArn);

        } catch (RuntimeException rte) {
            Throwable cause = rte.getCause();
            if (cause instanceof BatchException batchExceptionEx) {
                String myErrorCode = batchExceptionEx.awsErrorDetails().errorMessage();
                if ("Object already exists".contains(myErrorCode)) {
                    logger.info("The job queue '" + jobQueueName + "' already exists. Moving on...");
                    // Retrieve the ARN of the job queue.
                    CompletableFuture<String> jobQueueArnFuture = batchActions.getJobQueueARN(jobQueueName);
                    jobQueueArn = jobQueueArnFuture.join();
                    logger.info("Job Queue ARN: " + jobQueueArn);
                } else {
                    logger.info("Batch error occurred: {} (Code: {})", batchExceptionEx.getMessage(), batchExceptionEx.awsErrorDetails().errorCode());
                    return;
                }
            } else {
                logger.info("An unexpected error occurred: " + (cause != null ? cause.getMessage() : rte.getMessage()));
                return; // End the execution
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("4. Register a Job Definition.");
        logger.info("""
            Registering a job in AWS Batch using the Fargate launch type ensures that all
            necessary parameters, such as the execution role, command to run, and so on
            are specified and reused across multiple job submissions.
            
             The job definition pulls a Docker image from Amazon ECR and executes the Docker image.
            """);

        waitForInputToContinue(scanner);
        String jobARN;
        try {
            String platform = "";
            while (true) {
                logger.info("""
                    On which platform/CPU architecture combination did you build the Docker image?:
                    1. Windows       X86_64
                    2. Mac or Linux  ARM64
                    3. Mac or Linux  X86_64
                                
                    Please select 1, 2, or 3.
                    """);
                String platAns = scanner.nextLine().trim();
                if (platAns.equals("1")) {
                    platform = "X86_64";
                    break; // Exit loop since a valid option is selected
                } else if (platAns.equals("2")) {
                    platform = "ARM64";
                    break; // Exit loop since a valid option is selected
                } else if (platAns.equals("3")) {
                    platform = "X86_64";
                    break; // Exit loop since a valid option is selected
                } else {
                    System.out.println("Invalid input. Please select either 1 or 2.");
                }
            }

            jobARN = batchActions.registerJobDefinitionAsync(jobDefinitionName, executionRoleARN, dockerImage, platform)
                .exceptionally(ex -> {
                    System.err.println("Register job definition failed: " + ex.getMessage());
                    return null;
                })
                .join();
            if (jobARN != null) {
                logger.info("Job ARN: " + jobARN);
            }
        } catch (RuntimeException rte) {
            logger.error("A Batch exception occurred while registering the job: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
            return;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5. Submit an AWS Batch job from a job definition.");
        waitForInputToContinue(scanner);
        String jobId;
        try {
            jobId = batchActions.submitJobAsync(jobDefinitionName, jobQueueName, jobARN)
                .exceptionally(ex -> {
                    System.err.println("Submit job failed: " + ex.getMessage());
                    return null;
                })
                .join();

            logger.info("The job id is "+jobId);
            logger.info("Let's wait 2 minutes for the job to complete");
            countdown(2);

        } catch (RuntimeException rte) {
            logger.error("A Batch exception occurred while submitting the job: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        logger.info(DASHES);
        logger.info("6. Get a list of jobs applicable to the job queue.");

        waitForInputToContinue(scanner);
        try {
            List<JobSummary> jobs = batchActions.listJobsAsync(jobQueueName);
            jobs.forEach(job ->
                logger.info("Job ID: {}, Job Name: {}, Job Status: {}", job.jobId(), job.jobName(), job.status()));

        } catch (RuntimeException rte) {
            logger.info("A Batch exception occurred while submitting the job: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
            return;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Check the status of job "+jobId);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<String> future = batchActions.describeJobAsync(jobId);
            String jobStatus = future.join();
            logger.info("Job Status: " + jobStatus);

        } catch (RuntimeException rte) {
            logger.info("A Batch exception occurred while submitting the job: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
            return;
        }

        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        logger.info("8. Delete Batch resources");
        logger.info(
            """
            When deleting an AWS Batch compute environment, it does not happen instantaneously. 
            There is typically a delay, similar to some other AWS resources. 
            AWS Batch starts the deletion process.
            """);
        logger.info("Would you like to delete the AWS Batch resources such as the compute environment? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            logger.info("You selected to delete the AWS ECR resources.");
            logger.info("First, we will deregister the Job Definition.");
            waitForInputToContinue(scanner);
            try {
                batchActions.deregisterJobDefinitionAsync(jobARN)
                    .exceptionally(ex -> {
                        logger.info("Deregister job definition failed: " + ex.getMessage());
                        return null;
                    })
                    .join();
                logger.info(jobARN + " was deregistered");
            } catch (RuntimeException rte) {
                logger.error("A Batch exception occurred: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
                return;
            }

            logger.info("Second, we will disable and then delete the Job Queue.");
            waitForInputToContinue(scanner);
            try {
                batchActions.disableJobQueueAsync(jobQueueArn)
                    .exceptionally(ex -> {
                        logger.info("Disable job queue failed: " + ex.getMessage());
                        return null;
                    })
                    .join();
                logger.info(jobQueueArn + " was disabled");
            } catch (RuntimeException rte) {
                logger.info("A Batch exception occurred: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
                return;
            }

            batchActions.waitForJobQueueToBeDisabledAsync(jobQueueArn);
            try {
                CompletableFuture<Void> future = batchActions.waitForJobQueueToBeDisabledAsync(jobQueueArn);
                future.join();
                logger.info("Job queue is now disabled.");
            } catch (RuntimeException rte) {
                logger.info("A Batch exception occurred: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
                return;
            }

            waitForInputToContinue(scanner);
            try {
                batchActions.deleteJobQueueAsync(jobQueueArn);
                logger.info(jobQueueArn +" was deleted");
            } catch (RuntimeException rte) {
                logger.info("A Batch exception occurred: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
                return;
            }
            logger.info("Let's wait 2 minutes for the job queue to be deleted");
            countdown(2);
            waitForInputToContinue(scanner);

            logger.info("Third, we will delete the Compute Environment.");
            waitForInputToContinue(scanner);
            try {
                batchActions.disableComputeEnvironmentAsync(computeEnvironmentName)
                    .exceptionally(ex -> {
                        System.err.println("Disable compute environment failed: " + ex.getMessage());
                        return null;
                    })
                    .join();
                logger.info("Compute environment disabled") ;
            } catch (RuntimeException rte) {
                logger.info("A Batch exception occurred: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
                return;
            }

            batchActions.checkComputeEnvironmentsStatus(computeEnvironmentName).thenAccept(state -> {
                logger.info("Current State: " + state);
            }).join();

            logger.info("Lets wait 1 min for the compute environment to be deleted");
            countdown(1);

            try {
                batchActions.deleteComputeEnvironmentAsync(computeEnvironmentName).join();
                logger.info(computeEnvironmentName +" was deleted.");

            } catch (RuntimeException rte) {
                logger.info("A Batch exception occurred: {}", rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage());
                return;
            }
            waitForInputToContinue(scanner);
            CloudFormationHelper.destroyCloudFormationStack(ROLES_STACK);
        }

        logger.info(DASHES);
        logger.info("This concludes the AWS Batch SDK scenario");
        logger.info(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
    }

    public static void countdown(int minutes) throws InterruptedException {
        int seconds = 0;
        for (int i = minutes * 60 + seconds; i >= 0; i--) {
            int displayMinutes = i / 60;
            int displaySeconds = i % 60;
            System.out.print(String.format("\r%02d:%02d", displayMinutes, displaySeconds));
            Thread.sleep(1000); // Wait for 1 second
        }
        logger.info("Countdown complete!");
    }

    private static void getSubnetSecurityGroup() {
        try (Ec2AsyncClient ec2Client = Ec2AsyncClient.create()) {
            CompletableFuture<Vpc> defaultVpcFuture = ec2Client.describeVpcs(DescribeVpcsRequest.builder()
                            .filters(Filter.builder()
                                    .name("is-default")
                                    .values("true")
                                    .build())
                            .build())
                    .thenApply(response -> response.vpcs().stream()
                            .findFirst()
                            .orElseThrow(() -> new RuntimeException("Default VPC not found")));

            CompletableFuture<String> defaultSubnetFuture = defaultVpcFuture
                    .thenCompose(vpc -> ec2Client.describeSubnets(DescribeSubnetsRequest.builder()
                                    .filters(Filter.builder()
                                                    .name("vpc-id")
                                                    .values(vpc.vpcId())
                                                    .build(),
                                            Filter.builder()
                                                    .name("default-for-az")
                                                    .values("true")
                                                    .build())
                                    .build())
                            .thenApply(DescribeSubnetsResponse::subnets)
                            .thenApply(subnets -> subnets.stream()
                                    .findFirst()
                                    .map(Subnet::subnetId)
                                    .orElseThrow(() -> new RuntimeException("No default subnet found"))));

            CompletableFuture<String> defaultSecurityGroupFuture = defaultVpcFuture
                    .thenCompose(vpc -> ec2Client.describeSecurityGroups(DescribeSecurityGroupsRequest.builder()
                                    .filters(Filter.builder()
                                                    .name("group-name")
                                                    .values("default")
                                                    .build(),
                                            Filter.builder()
                                                    .name("vpc-id")
                                                    .values(vpc.vpcId())
                                                    .build())
                                    .build())
                            .thenApply(DescribeSecurityGroupsResponse::securityGroups)
                            .thenApply(securityGroups -> securityGroups.stream()
                                    .findFirst()
                                    .map(SecurityGroup::groupId)
                                    .orElseThrow(() -> new RuntimeException("No default security group found"))));

            defaultSubnet = defaultSubnetFuture.join();
            defaultSecurityGroup = defaultSecurityGroupFuture.join();
        }
    }
}
```
 AWS Batch SDK メソッドのラッパークラス。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.batch.BatchAsyncClient;
import software.amazon.awssdk.services.batch.BatchClient;
import software.amazon.awssdk.services.batch.model.AssignPublicIp;
import software.amazon.awssdk.services.batch.model.BatchException;
import software.amazon.awssdk.services.batch.model.CEState;
import software.amazon.awssdk.services.batch.model.CEType;
import software.amazon.awssdk.services.batch.model.CRType;
import software.amazon.awssdk.services.batch.model.ComputeEnvironmentOrder;
import software.amazon.awssdk.services.batch.model.ComputeResource;
import software.amazon.awssdk.services.batch.model.ContainerProperties;
import software.amazon.awssdk.services.batch.model.CreateComputeEnvironmentRequest;
import software.amazon.awssdk.services.batch.model.CreateComputeEnvironmentResponse;
import software.amazon.awssdk.services.batch.model.CreateJobQueueRequest;
import software.amazon.awssdk.services.batch.model.DeleteComputeEnvironmentRequest;
import software.amazon.awssdk.services.batch.model.DeleteComputeEnvironmentResponse;
import software.amazon.awssdk.services.batch.model.DeleteJobQueueRequest;
import software.amazon.awssdk.services.batch.model.DeleteJobQueueResponse;
import software.amazon.awssdk.services.batch.model.DeregisterJobDefinitionRequest;
import software.amazon.awssdk.services.batch.model.DeregisterJobDefinitionResponse;
import software.amazon.awssdk.services.batch.model.DescribeComputeEnvironmentsRequest;
import software.amazon.awssdk.services.batch.model.DescribeComputeEnvironmentsResponse;
import software.amazon.awssdk.services.batch.model.DescribeJobQueuesRequest;
import software.amazon.awssdk.services.batch.model.DescribeJobQueuesResponse;
import software.amazon.awssdk.services.batch.model.DescribeJobsRequest;
import software.amazon.awssdk.services.batch.model.DescribeJobsResponse;
import software.amazon.awssdk.services.batch.model.JQState;
import software.amazon.awssdk.services.batch.model.JobDefinitionType;
import software.amazon.awssdk.services.batch.model.JobDetail;
import software.amazon.awssdk.services.batch.model.JobQueueDetail;
import software.amazon.awssdk.services.batch.model.JobStatus;
import software.amazon.awssdk.services.batch.model.JobSummary;
import software.amazon.awssdk.services.batch.model.ListJobsRequest;
import software.amazon.awssdk.services.batch.model.RegisterJobDefinitionResponse;
import software.amazon.awssdk.services.batch.model.NetworkConfiguration;
import software.amazon.awssdk.services.batch.model.PlatformCapability;
import software.amazon.awssdk.services.batch.model.RegisterJobDefinitionRequest;
import software.amazon.awssdk.services.batch.model.ResourceRequirement;
import software.amazon.awssdk.services.batch.model.ResourceType;
import software.amazon.awssdk.services.batch.model.RuntimePlatform;
import software.amazon.awssdk.services.batch.model.SubmitJobRequest;
import software.amazon.awssdk.services.batch.model.CreateJobQueueResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.services.batch.model.SubmitJobResponse;
import software.amazon.awssdk.services.batch.model.UpdateComputeEnvironmentRequest;
import software.amazon.awssdk.services.batch.model.UpdateComputeEnvironmentResponse;
import software.amazon.awssdk.services.batch.model.UpdateJobQueueRequest;
import software.amazon.awssdk.services.batch.model.UpdateJobQueueResponse;
import software.amazon.awssdk.services.batch.paginators.ListJobsPublisher;
import software.amazon.awssdk.services.sts.StsAsyncClient;
import software.amazon.awssdk.services.sts.model.GetCallerIdentityResponse;

public class BatchActions {
    private static BatchAsyncClient batchClient;

    private static final Logger logger = LoggerFactory.getLogger(BatchActions.class);

    private static BatchAsyncClient getAsyncClient() {
        if (batchClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryPolicy(RetryPolicy.builder()
                    .numRetries(3)
                    .build())
                .build();

            batchClient = BatchAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return batchClient;
    }

    /**
     * Asynchronously creates a new compute environment in AWS Batch.
     *
     * @param computeEnvironmentName the name of the compute environment to create
     * @param batchIAMRole the IAM role to be used by the compute environment
     * @param subnet the subnet ID to be used for the compute environment
     * @param secGroup the security group ID to be used for the compute environment
     * @return a {@link CompletableFuture} representing the asynchronous operation, which will complete with the
     *         {@link CreateComputeEnvironmentResponse} when the compute environment has been created
     * @throws BatchException if there is an error creating the compute environment
     * @throws RuntimeException if there is an unexpected error during the operation
     */
    public CompletableFuture<CreateComputeEnvironmentResponse> createComputeEnvironmentAsync(
        String computeEnvironmentName, String batchIAMRole, String subnet, String secGroup) {
        CreateComputeEnvironmentRequest environmentRequest = CreateComputeEnvironmentRequest.builder()
            .computeEnvironmentName(computeEnvironmentName)
            .type(CEType.MANAGED)
            .state(CEState.ENABLED)
            .computeResources(ComputeResource.builder()
                .type(CRType.FARGATE)
                .maxvCpus(256)
                .subnets(Collections.singletonList(subnet))
                .securityGroupIds(Collections.singletonList(secGroup))
                .build())
            .serviceRole(batchIAMRole)
            .build();

        CompletableFuture<CreateComputeEnvironmentResponse> response = getAsyncClient().createComputeEnvironment(environmentRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
               String errorMessage = "Unexpected error occurred: " + ex.getMessage();
               throw new RuntimeException(errorMessage, ex);
            }
        });

        return response;
    }

    public CompletableFuture<DeleteComputeEnvironmentResponse> deleteComputeEnvironmentAsync(String computeEnvironmentName) {
        DeleteComputeEnvironmentRequest deleteComputeEnvironment = DeleteComputeEnvironmentRequest.builder()
            .computeEnvironment(computeEnvironmentName)
            .build();

        return getAsyncClient().deleteComputeEnvironment(deleteComputeEnvironment)
            .whenComplete((response, ex) -> {
                if (ex != null) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof BatchException) {
                        throw new RuntimeException(cause);
                    } else {
                        throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                    }
                }
            });
    }

    /**
     * Checks the status of the specified compute environment.
     *
     * @param computeEnvironmentName the name of the compute environment to check
     * @return a CompletableFuture containing the status of the compute environment, or "ERROR" if an exception occurs
     */
    public CompletableFuture<String> checkComputeEnvironmentsStatus(String computeEnvironmentName) {
        if (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {
            throw new IllegalArgumentException("Compute environment name cannot be null or empty");
        }

        DescribeComputeEnvironmentsRequest environmentsRequest = DescribeComputeEnvironmentsRequest.builder()
            .computeEnvironments(computeEnvironmentName)
            .build();

        CompletableFuture<DescribeComputeEnvironmentsResponse> response = getAsyncClient().describeComputeEnvironments(environmentsRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                throw new RuntimeException(errorMessage, ex);
            }
        });

        return response.thenApply(resp -> resp.computeEnvironments().stream()
            .map(env -> env.statusAsString())
            .findFirst()
            .orElse("UNKNOWN"));
    }

    /**
     * Creates a job queue asynchronously.
     *
     * @param jobQueueName the name of the job queue to create
     * @param computeEnvironmentName the name of the compute environment to associate with the job queue
     * @return a CompletableFuture that completes with the Amazon Resource Name (ARN) of the job queue
     */
    public CompletableFuture<String> createJobQueueAsync(String jobQueueName, String computeEnvironmentName) {
        if (jobQueueName == null || jobQueueName.isEmpty()) {
            throw new IllegalArgumentException("Job queue name cannot be null or empty");
        }
        if (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {
            throw new IllegalArgumentException("Compute environment name cannot be null or empty");
        }

        CreateJobQueueRequest request = CreateJobQueueRequest.builder()
            .jobQueueName(jobQueueName)
            .priority(1)
            .computeEnvironmentOrder(ComputeEnvironmentOrder.builder()
                .computeEnvironment(computeEnvironmentName)
                .order(1)
                .build())
            .build();

        CompletableFuture<CreateJobQueueResponse> response = getAsyncClient().createJobQueue(request);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                throw new RuntimeException(errorMessage, ex);
            }
        });

        return response.thenApply(CreateJobQueueResponse::jobQueueArn);
    }

    /**
     * Asynchronously lists the jobs in the specified job queue with the given job status.
     *
     * @param jobQueue the name of the job queue to list jobs from
     * @return a List<JobSummary> that contains the jobs that succeeded
     */
    public List<JobSummary> listJobsAsync(String jobQueue) {
        if (jobQueue == null || jobQueue.isEmpty()) {
            throw new IllegalArgumentException("Job queue cannot be null or empty");
        }

        ListJobsRequest listJobsRequest = ListJobsRequest.builder()
            .jobQueue(jobQueue)
            .jobStatus(JobStatus.SUCCEEDED)  // Filter jobs by status.
            .build();

        List<JobSummary> jobSummaries = new ArrayList<>();
        ListJobsPublisher listJobsPaginator = getAsyncClient().listJobsPaginator(listJobsRequest);
        CompletableFuture<Void> future = listJobsPaginator.subscribe(response -> {
            jobSummaries.addAll(response.jobSummaryList());
        });
        future.join();
        return jobSummaries;
    }

    /**
     * Registers a new job definition asynchronously in AWS Batch.
     * <p>
     * When using Fargate as the compute environment, it is crucial to set the
     * {@link NetworkConfiguration} with {@link AssignPublicIp#ENABLED} to
     * ensure proper networking configuration for the Fargate tasks. This
     * allows the tasks to communicate with external services, access the
     * internet, or communicate within a VPC.
     *
     * @param jobDefinitionName the name of the job definition to be registered
     * @param executionRoleARN the ARN (Amazon Resource Name) of the execution role
     *                         that provides permissions for the containers in the job
     * @param cpuArch a value of either X86_64 or ARM64 required for the service call
     * @return a CompletableFuture that completes with the ARN of the registered
     *         job definition upon successful execution, or completes exceptionally with
     *         an error if the registration fails
     */
    public CompletableFuture<String> registerJobDefinitionAsync(String jobDefinitionName, String executionRoleARN, String image, String cpuArch) {
        NetworkConfiguration networkConfiguration = NetworkConfiguration.builder()
                .assignPublicIp(AssignPublicIp.ENABLED)
                .build();

        ContainerProperties containerProperties = ContainerProperties.builder()
                .image(image)
                .executionRoleArn(executionRoleARN)
                .resourceRequirements(
                        Arrays.asList(
                                ResourceRequirement.builder()
                                        .type(ResourceType.VCPU)
                                        .value("1")
                                        .build(),
                                ResourceRequirement.builder()
                                        .type(ResourceType.MEMORY)
                                        .value("2048")
                                        .build()
                        )
                )
                .networkConfiguration(networkConfiguration)
               .runtimePlatform(b -> b
                        .cpuArchitecture(cpuArch)
                        .operatingSystemFamily("LINUX"))
                .build();

        RegisterJobDefinitionRequest request = RegisterJobDefinitionRequest.builder()
                .jobDefinitionName(jobDefinitionName)
                .type(JobDefinitionType.CONTAINER)
                .containerProperties(containerProperties)
                .platformCapabilities(PlatformCapability.FARGATE)
                .build();

        CompletableFuture<String> future = new CompletableFuture<>();
        getAsyncClient().registerJobDefinition(request)
                .thenApply(RegisterJobDefinitionResponse::jobDefinitionArn)
                .whenComplete((result, ex) -> {
                    if (ex != null) {
                        future.completeExceptionally(ex);
                    } else {
                        future.complete(result);
                    }
                });

        return future;
    }

    /**
     * Deregisters a job definition asynchronously.
     *
     * @param jobDefinition the name of the job definition to be deregistered
     * @return a CompletableFuture that completes when the job definition has been deregistered
     * or an exception has occurred
     */
    public CompletableFuture<DeregisterJobDefinitionResponse> deregisterJobDefinitionAsync(String jobDefinition) {
        DeregisterJobDefinitionRequest jobDefinitionRequest = DeregisterJobDefinitionRequest.builder()
            .jobDefinition(jobDefinition)
            .build();

        CompletableFuture<DeregisterJobDefinitionResponse> responseFuture = getAsyncClient().deregisterJobDefinition(jobDefinitionRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        });

        return responseFuture;
    }

    /**
     * Disables the specified job queue asynchronously.
     *
     * @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to be disabled
     * @return a {@link CompletableFuture} that completes when the job queue update operation is complete,
     *         or completes exceptionally if an error occurs during the operation
     */
    public CompletableFuture<Void> disableJobQueueAsync(String jobQueueArn) {
        UpdateJobQueueRequest updateRequest = UpdateJobQueueRequest.builder()
            .jobQueue(jobQueueArn)
            .state(JQState.DISABLED)
            .build();

        CompletableFuture<UpdateJobQueueResponse> responseFuture = getAsyncClient().updateJobQueue(updateRequest);
        return responseFuture.whenComplete((updateResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to update job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(updateResponse -> null);
    }

    /**
     * Deletes a Batch job queue asynchronously.
     *
     * @param jobQueueArn The Amazon Resource Name (ARN) of the job queue to delete.
     * @return A CompletableFuture that represents the asynchronous deletion of the job queue.
     *         The future completes when the job queue has been successfully deleted or if an error occurs.
     *         If successful, the future will be completed with a {@code Void} value.
     *         If an error occurs, the future will be completed exceptionally with the thrown exception.
     */
    public CompletableFuture<Void> deleteJobQueueAsync(String jobQueueArn) {
        DeleteJobQueueRequest deleteRequest = DeleteJobQueueRequest.builder()
            .jobQueue(jobQueueArn)
            .build();

        CompletableFuture<DeleteJobQueueResponse> responseFuture = getAsyncClient().deleteJobQueue(deleteRequest);
        return responseFuture.whenComplete((deleteResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(deleteResponse -> null);
    }

    /**
     * Asynchronously describes the job queue associated with the specified compute environment.
     *
     * @param computeEnvironmentName the name of the compute environment to find the associated job queue for
     * @return a {@link CompletableFuture} that, when completed, contains the job queue ARN associated with the specified compute environment
     * @throws RuntimeException if the job queue description fails
     */
    public CompletableFuture<String> describeJobQueueAsync(String computeEnvironmentName) {
        DescribeJobQueuesRequest describeJobQueuesRequest = DescribeJobQueuesRequest.builder()
            .build();

        CompletableFuture<DescribeJobQueuesResponse> responseFuture = getAsyncClient().describeJobQueues(describeJobQueuesRequest);
        return responseFuture.whenComplete((describeJobQueuesResponse, ex) -> {
            if (describeJobQueuesResponse != null) {
                String jobQueueARN;
                for (JobQueueDetail jobQueueDetail : describeJobQueuesResponse.jobQueues()) {
                    for (ComputeEnvironmentOrder computeEnvironmentOrder : jobQueueDetail.computeEnvironmentOrder()) {
                        String computeEnvironment = computeEnvironmentOrder.computeEnvironment();
                        String name = getComputeEnvironmentName(computeEnvironment);
                        if (name.equals(computeEnvironmentName)) {
                            jobQueueARN = jobQueueDetail.jobQueueArn();
                            logger.info("Job queue ARN associated with the compute environment: " + jobQueueARN);
                        }
                    }
                }
            } else {
                throw new RuntimeException("Failed to describe job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(describeJobQueuesResponse -> {
            String jobQueueARN = "";
            for (JobQueueDetail jobQueueDetail : describeJobQueuesResponse.jobQueues()) {
                for (ComputeEnvironmentOrder computeEnvironmentOrder : jobQueueDetail.computeEnvironmentOrder()) {
                    String computeEnvironment = computeEnvironmentOrder.computeEnvironment();
                    String name = getComputeEnvironmentName(computeEnvironment);
                    if (name.equals(computeEnvironmentName)) {
                        jobQueueARN = jobQueueDetail.jobQueueArn();
                    }
                }
            }
            return jobQueueARN;
        });
    }

    /**
     * Disables the specified compute environment asynchronously.
     *
     * @param computeEnvironmentName the name of the compute environment to disable
     * @return a CompletableFuture that completes when the compute environment is disabled
     */
    public CompletableFuture<UpdateComputeEnvironmentResponse> disableComputeEnvironmentAsync(String computeEnvironmentName) {
        UpdateComputeEnvironmentRequest updateRequest = UpdateComputeEnvironmentRequest.builder()
            .computeEnvironment(computeEnvironmentName)
            .state(CEState.DISABLED)
            .build();

        CompletableFuture<UpdateComputeEnvironmentResponse> responseFuture = getAsyncClient().updateComputeEnvironment(updateRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to disable compute environment: " + ex.getMessage(), ex);
            }
        });

        return responseFuture;
    }

    /**
     * Submits a job asynchronously to the AWS Batch service.
     *
     * @param jobDefinitionName the name of the job definition to use
     * @param jobQueueName the name of the job queue to submit the job to
     * @param jobARN the Amazon Resource Name (ARN) of the job definition
     * @return a CompletableFuture that, when completed, contains the job ID of the submitted job
     */
    public CompletableFuture<String> submitJobAsync(String jobDefinitionName, String jobQueueName, String jobARN) {
        SubmitJobRequest jobRequest = SubmitJobRequest.builder()
            .jobDefinition(jobARN)
            .jobName(jobDefinitionName)
            .jobQueue(jobQueueName)
            .build();

        CompletableFuture<SubmitJobResponse> responseFuture = getAsyncClient().submitJob(jobRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        });

        return responseFuture.thenApply(SubmitJobResponse::jobId);
    }

    /**
     * Asynchronously retrieves the status of a specific job.
     *
     * @param jobId the ID of the job to retrieve the status for
     * @return a CompletableFuture that completes with the job status
     */
    public CompletableFuture<String> describeJobAsync(String jobId) {
        DescribeJobsRequest describeJobsRequest = DescribeJobsRequest.builder()
            .jobs(jobId)
            .build();

        CompletableFuture<DescribeJobsResponse> responseFuture = getAsyncClient().describeJobs(describeJobsRequest);
        return responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        }).thenApply(response -> response.jobs().get(0).status().toString());
    }

    /**
     * Disables the specific job queue using the asynchronous Java client.
     *
     * @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to wait for
     * @return a {@link CompletableFuture} that completes when the job queue is disabled
     */
    public CompletableFuture<Void> waitForJobQueueToBeDisabledAsync(String jobQueueArn) {
        AtomicBoolean isDisabled = new AtomicBoolean(false);
        return CompletableFuture.runAsync(() -> {
            while (!isDisabled.get()) {
                DescribeJobQueuesRequest describeRequest = DescribeJobQueuesRequest.builder()
                    .jobQueues(jobQueueArn)
                    .build();

                CompletableFuture<DescribeJobQueuesResponse> responseFuture = getAsyncClient().describeJobQueues(describeRequest);
                responseFuture.whenComplete((describeResponse, ex) -> {
                    if (describeResponse != null) {
                        for (JobQueueDetail jobQueue : describeResponse.jobQueues()) {
                            if (jobQueue.jobQueueArn().equals(jobQueueArn) && jobQueue.state() == JQState.DISABLED) {
                                isDisabled.set(true);
                                break;
                            }
                        }
                    } else {
                        throw new RuntimeException("Error describing job queues", ex);
                    }
                }).join();

                if (!isDisabled.get()) {
                    try {
                        logger.info("Waiting for job queue to be disabled...");
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("Thread interrupted while waiting for job queue to be disabled", e);
                    }
                }
            }
        }).whenComplete((result, throwable) -> {
            if (throwable != null) {
                throw new RuntimeException("Error while waiting for job queue to be disabled", throwable);
            }
        });
    }

    public CompletableFuture<String> getJobQueueARN(String jobQueueName) {
        // Describe the job queue asynchronously
        CompletableFuture<DescribeJobQueuesResponse> describeJobQueuesFuture = batchClient.describeJobQueues(
            DescribeJobQueuesRequest.builder()
                .jobQueues(jobQueueName)
                .build()
        );

        // Handle the asynchronous response and return the Job Queue ARN in the CompletableFuture<String>
        CompletableFuture<String> jobQueueArnFuture = new CompletableFuture<>();
        describeJobQueuesFuture.whenComplete((response, error) -> {
            if (error != null) {
                if (error instanceof BatchException) {
                    logger.info("Batch error: " + ((BatchException) error).awsErrorDetails().errorMessage());
                } else {
                    logger.info("Error describing job queue: " + error.getMessage());
                }
                jobQueueArnFuture.completeExceptionally(new RuntimeException("Failed to retrieve Job Queue ARN", error));
            } else {
                if (response.jobQueues().isEmpty()) {
                    jobQueueArnFuture.completeExceptionally(new RuntimeException("Job queue not found: " + jobQueueName));
                } else {
                    // Assuming only one job queue is returned for the given name
                    String jobQueueArn = response.jobQueues().get(0).jobQueueArn();
                    jobQueueArnFuture.complete(jobQueueArn);
                }
            }
        });

        return jobQueueArnFuture;
    }

    private static String getComputeEnvironmentName(String computeEnvironment) {
        String[] parts = computeEnvironment.split("/");
        if (parts.length == 2) {
            return parts[1];
        }
        return null;
    }

    public CompletableFuture<String> getAccountId() {
        StsAsyncClient stsAsyncClient = StsAsyncClient.builder()
            .region(Region.US_EAST_1)
            .build();

        return stsAsyncClient.getCallerIdentity()
            .thenApply(GetCallerIdentityResponse::account);
    }


}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/CreateComputeEnvironment)
  + [CreateJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/CreateJobQueue)
  + [DeleteComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeleteComputeEnvironment)
  + [DeleteJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeleteJobQueue)
  + [DeregisterJobDefinition](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeregisterJobDefinition)
  + [DescribeComputeEnvironments](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeComputeEnvironments)
  + [DescribeJobQueues](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeJobQueues)
  + [DescribeJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeJobs)
  + [ListJobsPaginator](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/ListJobsPaginator)
  + [RegisterJobDefinition](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/RegisterJobDefinition)
  + [SubmitJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/SubmitJob)
  + [UpdateComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/UpdateComputeEnvironment)
  + [UpdateJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/UpdateJobQueue)

## アクション
<a name="actions"></a>

### `CreateComputeEnvironment`
<a name="batch_CreateComputeEnvironment_java_2_topic"></a>

次のコード例は、`CreateComputeEnvironment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously creates a new compute environment in AWS Batch.
     *
     * @param computeEnvironmentName the name of the compute environment to create
     * @param batchIAMRole the IAM role to be used by the compute environment
     * @param subnet the subnet ID to be used for the compute environment
     * @param secGroup the security group ID to be used for the compute environment
     * @return a {@link CompletableFuture} representing the asynchronous operation, which will complete with the
     *         {@link CreateComputeEnvironmentResponse} when the compute environment has been created
     * @throws BatchException if there is an error creating the compute environment
     * @throws RuntimeException if there is an unexpected error during the operation
     */
    public CompletableFuture<CreateComputeEnvironmentResponse> createComputeEnvironmentAsync(
        String computeEnvironmentName, String batchIAMRole, String subnet, String secGroup) {
        CreateComputeEnvironmentRequest environmentRequest = CreateComputeEnvironmentRequest.builder()
            .computeEnvironmentName(computeEnvironmentName)
            .type(CEType.MANAGED)
            .state(CEState.ENABLED)
            .computeResources(ComputeResource.builder()
                .type(CRType.FARGATE)
                .maxvCpus(256)
                .subnets(Collections.singletonList(subnet))
                .securityGroupIds(Collections.singletonList(secGroup))
                .build())
            .serviceRole(batchIAMRole)
            .build();

        CompletableFuture<CreateComputeEnvironmentResponse> response = getAsyncClient().createComputeEnvironment(environmentRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
               String errorMessage = "Unexpected error occurred: " + ex.getMessage();
               throw new RuntimeException(errorMessage, ex);
            }
        });

        return response;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/CreateComputeEnvironment)」を参照してください。

### `CreateJobQueue`
<a name="batch_CreateJobQueue_java_2_topic"></a>

次のコード例は、`CreateJobQueue` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a job queue asynchronously.
     *
     * @param jobQueueName the name of the job queue to create
     * @param computeEnvironmentName the name of the compute environment to associate with the job queue
     * @return a CompletableFuture that completes with the Amazon Resource Name (ARN) of the job queue
     */
    public CompletableFuture<String> createJobQueueAsync(String jobQueueName, String computeEnvironmentName) {
        if (jobQueueName == null || jobQueueName.isEmpty()) {
            throw new IllegalArgumentException("Job queue name cannot be null or empty");
        }
        if (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {
            throw new IllegalArgumentException("Compute environment name cannot be null or empty");
        }

        CreateJobQueueRequest request = CreateJobQueueRequest.builder()
            .jobQueueName(jobQueueName)
            .priority(1)
            .computeEnvironmentOrder(ComputeEnvironmentOrder.builder()
                .computeEnvironment(computeEnvironmentName)
                .order(1)
                .build())
            .build();

        CompletableFuture<CreateJobQueueResponse> response = getAsyncClient().createJobQueue(request);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                throw new RuntimeException(errorMessage, ex);
            }
        });

        return response.thenApply(CreateJobQueueResponse::jobQueueArn);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/CreateJobQueue)」を参照してください。

### `DeleteComputeEnvironment`
<a name="batch_DeleteComputeEnvironment_java_2_topic"></a>

次のコード例は、`DeleteComputeEnvironment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    public CompletableFuture<DeleteComputeEnvironmentResponse> deleteComputeEnvironmentAsync(String computeEnvironmentName) {
        DeleteComputeEnvironmentRequest deleteComputeEnvironment = DeleteComputeEnvironmentRequest.builder()
            .computeEnvironment(computeEnvironmentName)
            .build();

        return getAsyncClient().deleteComputeEnvironment(deleteComputeEnvironment)
            .whenComplete((response, ex) -> {
                if (ex != null) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof BatchException) {
                        throw new RuntimeException(cause);
                    } else {
                        throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                    }
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeleteComputeEnvironment)」を参照してください。

### `DeleteJobQueue`
<a name="batch_DeleteJobQueue_java_2_topic"></a>

次のコード例は、`DeleteJobQueue` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a Batch job queue asynchronously.
     *
     * @param jobQueueArn The Amazon Resource Name (ARN) of the job queue to delete.
     * @return A CompletableFuture that represents the asynchronous deletion of the job queue.
     *         The future completes when the job queue has been successfully deleted or if an error occurs.
     *         If successful, the future will be completed with a {@code Void} value.
     *         If an error occurs, the future will be completed exceptionally with the thrown exception.
     */
    public CompletableFuture<Void> deleteJobQueueAsync(String jobQueueArn) {
        DeleteJobQueueRequest deleteRequest = DeleteJobQueueRequest.builder()
            .jobQueue(jobQueueArn)
            .build();

        CompletableFuture<DeleteJobQueueResponse> responseFuture = getAsyncClient().deleteJobQueue(deleteRequest);
        return responseFuture.whenComplete((deleteResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(deleteResponse -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeleteJobQueue)」を参照してください。

### `DeregisterJobDefinition`
<a name="batch_DeregisterJobDefinition_java_2_topic"></a>

次のコード例は、`DeregisterJobDefinition` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deregisters a job definition asynchronously.
     *
     * @param jobDefinition the name of the job definition to be deregistered
     * @return a CompletableFuture that completes when the job definition has been deregistered
     * or an exception has occurred
     */
    public CompletableFuture<DeregisterJobDefinitionResponse> deregisterJobDefinitionAsync(String jobDefinition) {
        DeregisterJobDefinitionRequest jobDefinitionRequest = DeregisterJobDefinitionRequest.builder()
            .jobDefinition(jobDefinition)
            .build();

        CompletableFuture<DeregisterJobDefinitionResponse> responseFuture = getAsyncClient().deregisterJobDefinition(jobDefinitionRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        });

        return responseFuture;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeregisterJobDefinition](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DeregisterJobDefinition)」を参照してください。

### `DescribeComputeEnvironments`
<a name="batch_DescribeComputeEnvironments_java_2_topic"></a>

次のコード例は、`DescribeComputeEnvironments` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Checks the status of the specified compute environment.
     *
     * @param computeEnvironmentName the name of the compute environment to check
     * @return a CompletableFuture containing the status of the compute environment, or "ERROR" if an exception occurs
     */
    public CompletableFuture<String> checkComputeEnvironmentsStatus(String computeEnvironmentName) {
        if (computeEnvironmentName == null || computeEnvironmentName.isEmpty()) {
            throw new IllegalArgumentException("Compute environment name cannot be null or empty");
        }

        DescribeComputeEnvironmentsRequest environmentsRequest = DescribeComputeEnvironmentsRequest.builder()
            .computeEnvironments(computeEnvironmentName)
            .build();

        CompletableFuture<DescribeComputeEnvironmentsResponse> response = getAsyncClient().describeComputeEnvironments(environmentsRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                throw new RuntimeException(errorMessage, ex);
            }
        });

        return response.thenApply(resp -> resp.computeEnvironments().stream()
            .map(env -> env.statusAsString())
            .findFirst()
            .orElse("UNKNOWN"));
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeComputeEnvironments](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeComputeEnvironments)」を参照してください。

### `DescribeJobQueues`
<a name="batch_DescribeJobQueues_java_2_topic"></a>

次のコード例は、`DescribeJobQueues` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously describes the job queue associated with the specified compute environment.
     *
     * @param computeEnvironmentName the name of the compute environment to find the associated job queue for
     * @return a {@link CompletableFuture} that, when completed, contains the job queue ARN associated with the specified compute environment
     * @throws RuntimeException if the job queue description fails
     */
    public CompletableFuture<String> describeJobQueueAsync(String computeEnvironmentName) {
        DescribeJobQueuesRequest describeJobQueuesRequest = DescribeJobQueuesRequest.builder()
            .build();

        CompletableFuture<DescribeJobQueuesResponse> responseFuture = getAsyncClient().describeJobQueues(describeJobQueuesRequest);
        return responseFuture.whenComplete((describeJobQueuesResponse, ex) -> {
            if (describeJobQueuesResponse != null) {
                String jobQueueARN;
                for (JobQueueDetail jobQueueDetail : describeJobQueuesResponse.jobQueues()) {
                    for (ComputeEnvironmentOrder computeEnvironmentOrder : jobQueueDetail.computeEnvironmentOrder()) {
                        String computeEnvironment = computeEnvironmentOrder.computeEnvironment();
                        String name = getComputeEnvironmentName(computeEnvironment);
                        if (name.equals(computeEnvironmentName)) {
                            jobQueueARN = jobQueueDetail.jobQueueArn();
                            logger.info("Job queue ARN associated with the compute environment: " + jobQueueARN);
                        }
                    }
                }
            } else {
                throw new RuntimeException("Failed to describe job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(describeJobQueuesResponse -> {
            String jobQueueARN = "";
            for (JobQueueDetail jobQueueDetail : describeJobQueuesResponse.jobQueues()) {
                for (ComputeEnvironmentOrder computeEnvironmentOrder : jobQueueDetail.computeEnvironmentOrder()) {
                    String computeEnvironment = computeEnvironmentOrder.computeEnvironment();
                    String name = getComputeEnvironmentName(computeEnvironment);
                    if (name.equals(computeEnvironmentName)) {
                        jobQueueARN = jobQueueDetail.jobQueueArn();
                    }
                }
            }
            return jobQueueARN;
        });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeJobQueues](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeJobQueues)」を参照してください。

### `DescribeJobs`
<a name="batch_DescribeJobs_java_2_topic"></a>

次のコード例は、`DescribeJobs` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously retrieves the status of a specific job.
     *
     * @param jobId the ID of the job to retrieve the status for
     * @return a CompletableFuture that completes with the job status
     */
    public CompletableFuture<String> describeJobAsync(String jobId) {
        DescribeJobsRequest describeJobsRequest = DescribeJobsRequest.builder()
            .jobs(jobId)
            .build();

        CompletableFuture<DescribeJobsResponse> responseFuture = getAsyncClient().describeJobs(describeJobsRequest);
        return responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        }).thenApply(response -> response.jobs().get(0).status().toString());
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/DescribeJobs)」を参照してください。

### `ListJobsPaginator`
<a name="batch_ListJobsPaginator_java_2_topic"></a>

次のコード例は、`ListJobsPaginator` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously lists the jobs in the specified job queue with the given job status.
     *
     * @param jobQueue the name of the job queue to list jobs from
     * @return a List<JobSummary> that contains the jobs that succeeded
     */
    public List<JobSummary> listJobsAsync(String jobQueue) {
        if (jobQueue == null || jobQueue.isEmpty()) {
            throw new IllegalArgumentException("Job queue cannot be null or empty");
        }

        ListJobsRequest listJobsRequest = ListJobsRequest.builder()
            .jobQueue(jobQueue)
            .jobStatus(JobStatus.SUCCEEDED)  // Filter jobs by status.
            .build();

        List<JobSummary> jobSummaries = new ArrayList<>();
        ListJobsPublisher listJobsPaginator = getAsyncClient().listJobsPaginator(listJobsRequest);
        CompletableFuture<Void> future = listJobsPaginator.subscribe(response -> {
            jobSummaries.addAll(response.jobSummaryList());
        });
        future.join();
        return jobSummaries;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListJobsPaginator](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/ListJobsPaginator)」を参照してください。

### `RegisterJobDefinition`
<a name="batch_RegisterJobDefinition_java_2_topic"></a>

次のコード例は、`RegisterJobDefinition` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Registers a new job definition asynchronously in AWS Batch.
     * <p>
     * When using Fargate as the compute environment, it is crucial to set the
     * {@link NetworkConfiguration} with {@link AssignPublicIp#ENABLED} to
     * ensure proper networking configuration for the Fargate tasks. This
     * allows the tasks to communicate with external services, access the
     * internet, or communicate within a VPC.
     *
     * @param jobDefinitionName the name of the job definition to be registered
     * @param executionRoleARN the ARN (Amazon Resource Name) of the execution role
     *                         that provides permissions for the containers in the job
     * @param cpuArch a value of either X86_64 or ARM64 required for the service call
     * @return a CompletableFuture that completes with the ARN of the registered
     *         job definition upon successful execution, or completes exceptionally with
     *         an error if the registration fails
     */
    public CompletableFuture<String> registerJobDefinitionAsync(String jobDefinitionName, String executionRoleARN, String image, String cpuArch) {
        NetworkConfiguration networkConfiguration = NetworkConfiguration.builder()
                .assignPublicIp(AssignPublicIp.ENABLED)
                .build();

        ContainerProperties containerProperties = ContainerProperties.builder()
                .image(image)
                .executionRoleArn(executionRoleARN)
                .resourceRequirements(
                        Arrays.asList(
                                ResourceRequirement.builder()
                                        .type(ResourceType.VCPU)
                                        .value("1")
                                        .build(),
                                ResourceRequirement.builder()
                                        .type(ResourceType.MEMORY)
                                        .value("2048")
                                        .build()
                        )
                )
                .networkConfiguration(networkConfiguration)
               .runtimePlatform(b -> b
                        .cpuArchitecture(cpuArch)
                        .operatingSystemFamily("LINUX"))
                .build();

        RegisterJobDefinitionRequest request = RegisterJobDefinitionRequest.builder()
                .jobDefinitionName(jobDefinitionName)
                .type(JobDefinitionType.CONTAINER)
                .containerProperties(containerProperties)
                .platformCapabilities(PlatformCapability.FARGATE)
                .build();

        CompletableFuture<String> future = new CompletableFuture<>();
        getAsyncClient().registerJobDefinition(request)
                .thenApply(RegisterJobDefinitionResponse::jobDefinitionArn)
                .whenComplete((result, ex) -> {
                    if (ex != null) {
                        future.completeExceptionally(ex);
                    } else {
                        future.complete(result);
                    }
                });

        return future;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[RegisterJobDefinition](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/RegisterJobDefinition)」を参照してください。

### `SubmitJob`
<a name="batch_SubmitJob_java_2_topic"></a>

次のコード例は、`SubmitJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Submits a job asynchronously to the AWS Batch service.
     *
     * @param jobDefinitionName the name of the job definition to use
     * @param jobQueueName the name of the job queue to submit the job to
     * @param jobARN the Amazon Resource Name (ARN) of the job definition
     * @return a CompletableFuture that, when completed, contains the job ID of the submitted job
     */
    public CompletableFuture<String> submitJobAsync(String jobDefinitionName, String jobQueueName, String jobARN) {
        SubmitJobRequest jobRequest = SubmitJobRequest.builder()
            .jobDefinition(jobARN)
            .jobName(jobDefinitionName)
            .jobQueue(jobQueueName)
            .build();

        CompletableFuture<SubmitJobResponse> responseFuture = getAsyncClient().submitJob(jobRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Unexpected error occurred: " + ex.getMessage(), ex);
            }
        });

        return responseFuture.thenApply(SubmitJobResponse::jobId);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SubmitJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/SubmitJob)」を参照してください。

### `UpdateComputeEnvironment`
<a name="batch_UpdateComputeEnvironment_java_2_topic"></a>

次のコード例は、`UpdateComputeEnvironment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Disables the specified compute environment asynchronously.
     *
     * @param computeEnvironmentName the name of the compute environment to disable
     * @return a CompletableFuture that completes when the compute environment is disabled
     */
    public CompletableFuture<UpdateComputeEnvironmentResponse> disableComputeEnvironmentAsync(String computeEnvironmentName) {
        UpdateComputeEnvironmentRequest updateRequest = UpdateComputeEnvironmentRequest.builder()
            .computeEnvironment(computeEnvironmentName)
            .state(CEState.DISABLED)
            .build();

        CompletableFuture<UpdateComputeEnvironmentResponse> responseFuture = getAsyncClient().updateComputeEnvironment(updateRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to disable compute environment: " + ex.getMessage(), ex);
            }
        });

        return responseFuture;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateComputeEnvironment](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/UpdateComputeEnvironment)」を参照してください。

### `UpdateJobQueue`
<a name="batch_UpdateJobQueue_java_2_topic"></a>

次のコード例は、`UpdateJobQueue` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Disables the specified job queue asynchronously.
     *
     * @param jobQueueArn the Amazon Resource Name (ARN) of the job queue to be disabled
     * @return a {@link CompletableFuture} that completes when the job queue update operation is complete,
     *         or completes exceptionally if an error occurs during the operation
     */
    public CompletableFuture<Void> disableJobQueueAsync(String jobQueueArn) {
        UpdateJobQueueRequest updateRequest = UpdateJobQueueRequest.builder()
            .jobQueue(jobQueueArn)
            .state(JQState.DISABLED)
            .build();

        CompletableFuture<UpdateJobQueueResponse> responseFuture = getAsyncClient().updateJobQueue(updateRequest);
        return responseFuture.whenComplete((updateResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to update job queue: " + ex.getMessage(), ex);
            }
        }).thenApply(updateResponse -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateJobQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/batch-2016-08-10/UpdateJobQueue)」を参照してください。

# SDK for Java 2.x を使用する Amazon Bedrock の例
<a name="java_2_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetFoundationModel`
<a name="bedrock_GetFoundationModel_java_2_topic"></a>

次のコード例は、`GetFoundationModel` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。
同期 Amazon Bedrock クライアントを使用して、基盤モデルの詳細を取得します。  

```
    /**
     * Get details about an Amazon Bedrock foundation model.
     *
     * @param bedrockClient   The service client for accessing Amazon Bedrock.
     * @param modelIdentifier The model identifier.
     * @return An object containing the foundation model's details.
     */
    public static FoundationModelDetails getFoundationModel(BedrockClient bedrockClient, String modelIdentifier) {
        try {
            GetFoundationModelResponse response = bedrockClient.getFoundationModel(
                    r -> r.modelIdentifier(modelIdentifier)
            );

            FoundationModelDetails model = response.modelDetails();

            System.out.println(" Model ID:                     " + model.modelId());
            System.out.println(" Model ARN:                    " + model.modelArn());
            System.out.println(" Model Name:                   " + model.modelName());
            System.out.println(" Provider Name:                " + model.providerName());
            System.out.println(" Lifecycle status:             " + model.modelLifecycle().statusAsString());
            System.out.println(" Input modalities:             " + model.inputModalities());
            System.out.println(" Output modalities:            " + model.outputModalities());
            System.out.println(" Supported customizations:     " + model.customizationsSupported());
            System.out.println(" Supported inference types:    " + model.inferenceTypesSupported());
            System.out.println(" Response streaming supported: " + model.responseStreamingSupported());

            return model;

        } catch (ValidationException e) {
            throw new IllegalArgumentException(e.getMessage());
        } catch (SdkException e) {
            System.err.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }
```
非同期 Amazon Bedrock クライアントを使用して、基盤モデルの詳細を取得します。  

```
    /**
     * Get details about an Amazon Bedrock foundation model.
     *
     * @param bedrockClient   The async service client for accessing Amazon Bedrock.
     * @param modelIdentifier The model identifier.
     * @return An object containing the foundation model's details.
     */
    public static FoundationModelDetails getFoundationModel(BedrockAsyncClient bedrockClient, String modelIdentifier) {
        try {
            CompletableFuture<GetFoundationModelResponse> future = bedrockClient.getFoundationModel(
                    r -> r.modelIdentifier(modelIdentifier)
            );

            FoundationModelDetails model = future.get().modelDetails();

            System.out.println(" Model ID:                     " + model.modelId());
            System.out.println(" Model ARN:                    " + model.modelArn());
            System.out.println(" Model Name:                   " + model.modelName());
            System.out.println(" Provider Name:                " + model.providerName());
            System.out.println(" Lifecycle status:             " + model.modelLifecycle().statusAsString());
            System.out.println(" Input modalities:             " + model.inputModalities());
            System.out.println(" Output modalities:            " + model.outputModalities());
            System.out.println(" Supported customizations:     " + model.customizationsSupported());
            System.out.println(" Supported inference types:    " + model.inferenceTypesSupported());
            System.out.println(" Response streaming supported: " + model.responseStreamingSupported());

            return model;

        } catch (ExecutionException e) {
            if (e.getMessage().contains("ValidationException")) {
                throw new IllegalArgumentException(e.getMessage());
            } else {
                System.err.println(e.getMessage());
                throw new RuntimeException(e);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetFoundationModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-2023-04-20/GetFoundationModel)」を参照してください。

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_java_2_topic"></a>

次のコード例は、`ListFoundationModels` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。
同期 Amazon Bedrock クライアントを使用して、使用可能な Amazon Bedrock 基盤モデルを一覧表示します。  

```
    /**
     * Lists Amazon Bedrock foundation models that you can use.
     * You can filter the results with the request parameters.
     *
     * @param bedrockClient The service client for accessing Amazon Bedrock.
     * @return A list of objects containing the foundation models' details
     */
    public static List<FoundationModelSummary> listFoundationModels(BedrockClient bedrockClient) {

        try {
            ListFoundationModelsResponse response = bedrockClient.listFoundationModels(r -> {});

            List<FoundationModelSummary> models = response.modelSummaries();

            if (models.isEmpty()) {
                System.out.println("No available foundation models in " + region.toString());
            } else {
                for (FoundationModelSummary model : models) {
                    System.out.println("Model ID: " + model.modelId());
                    System.out.println("Provider: " + model.providerName());
                    System.out.println("Name:     " + model.modelName());
                    System.out.println();
                }
            }

            return models;

        } catch (SdkClientException e) {
            System.err.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }
```
非同期 Amazon Bedrock クライアントを使用して、使用可能な Amazon Bedrock 基盤モデルを一覧表示します。  

```
    /**
     * Lists Amazon Bedrock foundation models that you can use.
     * You can filter the results with the request parameters.
     *
     * @param bedrockClient The async service client for accessing Amazon Bedrock.
     * @return A list of objects containing the foundation models' details
     */
    public static List<FoundationModelSummary> listFoundationModels(BedrockAsyncClient bedrockClient) {
        try {
            CompletableFuture<ListFoundationModelsResponse> future = bedrockClient.listFoundationModels(r -> {});

            List<FoundationModelSummary> models = future.get().modelSummaries();

            if (models.isEmpty()) {
                System.out.println("No available foundation models in " + region.toString());
            } else {
                for (FoundationModelSummary model : models) {
                    System.out.println("Model ID: " + model.modelId());
                    System.out.println("Provider: " + model.providerName());
                    System.out.println("Name:     " + model.modelName());
                    System.out.println();
                }
            }

            return models;

        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println(e.getMessage());
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            System.err.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListFoundationModels](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-2023-04-20/ListFoundationModels)」を参照してください。

# SDK for Java 2.x を使用する Amazon Bedrock ランタイムの例
<a name="java_2_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイム AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)
+ [Amazon Nova](#amazon_nova)
+ [Amazon Nova Canvas](#amazon_nova_canvas)
+ [Amazon Titan Image Generator](#amazon_titan_image_generator)
+ [Amazon Titan Text Embeddings](#amazon_titan_text_embeddings)
+ [Anthropic Claude](#anthropic_claude)
+ [Cohere Command](#cohere_command)
+ [Meta Llama](#meta_llama)
+ [Mistral AI](#mistral_ai)
+ [Stable Diffusion](#stable_diffusion)

## シナリオ
<a name="scenarios"></a>

### Amazon Bedrock 基盤モデルとやりとりするためのプレイグラウンドアプリケーションを作成します。
<a name="cross_FMPlayground_java_2_topic"></a>

次のコード例は、さまざまな方法で Amazon Bedrock 基盤モデルと相互作用するプレイグラウンドを作成する方法を示しています。

**SDK for Java 2.x**  
 Java 基盤モデル (FM) プレイグラウンドは Spring Boot のサンプルアプリケーションで、Java で Amazon Bedrock を使用する方法を紹介しています。この例は、Java 開発者が Amazon Bedrock を使用して生成 AI 対応アプリケーションを構築する方法を示しています。次の 3 つのプレイグラウンドを使用して Amazon Bedrock 基盤モデルをテストしたり操作したりできます。  
+ テキストプレイグラウンド。
+ チャットプレイグラウンド。
+ イメージプレイグラウンド。
この例には、アクセスできる基盤モデルとその特性が一覧表示されています。ソースコードとデプロイ手順については、[GitHub](https://github.com/build-on-aws/java-fm-playground) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock ランタイム

### Amazon Bedrock を使用してテキストプロンプトからビデオを生成する
<a name="bedrock-runtime_Scenario_GenerateVideos_NovaReel_java_2_topic"></a>

次のコード例は、Amazon Bedrock と Nova-Reel モデルを使用してテキストプロンプトからビデオを生成する Spring Boot アプリの使用方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock と Nova-Reel を使用して、テキストプロンプトからビデオを生成します。  

```
import org.springframework.stereotype.Service;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.*;

import java.util.concurrent.CompletableFuture;

@Service
public class VideoGenerationService {

    public GenerateVideoResponse generateVideo(String prompt) {

        // add S3 bucket you want to store your generated videos
        String s3Bucket = "s3://mygeneratedvidoenovatest";


        //Create json request as an instance of Document class
        Document novaRequest = prepareDocument(prompt);

        // Create request
        StartAsyncInvokeRequest request = StartAsyncInvokeRequest.builder()
                .modelId("amazon.nova-reel-v1:0")
                .modelInput(novaRequest)
                .outputDataConfig(AsyncInvokeOutputDataConfig.builder()
                        .s3OutputDataConfig(AsyncInvokeS3OutputDataConfig.builder().s3Uri(s3Bucket).build())
                        .build())
                .build();

        try (BedrockRuntimeAsyncClient bedrockClient = getBedrockRuntimeAsyncClient()) {
            CompletableFuture<StartAsyncInvokeResponse> startAsyncInvokeResponseCompletableFuture = bedrockClient.startAsyncInvoke(request);

            //blocking operation to wait for the AWS API response
            StartAsyncInvokeResponse startAsyncInvokeResponse = startAsyncInvokeResponseCompletableFuture.get();
            System.out.println("invocation ARN: " + startAsyncInvokeResponse.invocationArn());

            GenerateVideoResponse response = new GenerateVideoResponse();
            response.setStatus("inProgress");
            response.setExecutionArn(startAsyncInvokeResponse.invocationArn());

            return response;
        } catch (Exception e) {
            System.out.println(e);
            throw new RuntimeException(e);
        }

    }

    public GenerateVideoResponse checkGenerationStatus(String invocationArn) {
        GenerateVideoResponse response = new GenerateVideoResponse();

        try (BedrockRuntimeAsyncClient bedrockClient = getBedrockRuntimeAsyncClient()) {
            //creating async request to fetch status by invocation Arn
            GetAsyncInvokeRequest asyncRequest = GetAsyncInvokeRequest.builder().invocationArn(invocationArn).build();

            CompletableFuture<GetAsyncInvokeResponse> asyncInvoke = bedrockClient.getAsyncInvoke(asyncRequest);

            //blocking operation to wait for the AWS API response
            GetAsyncInvokeResponse asyncInvokeResponse = asyncInvoke.get();
            System.out.println("Invocation status =" + asyncInvokeResponse.statusAsString());

            response.setExecutionArn(invocationArn);
            response.setStatus(asyncInvokeResponse.statusAsString());
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

    }

    private static BedrockRuntimeAsyncClient getBedrockRuntimeAsyncClient() {
        BedrockRuntimeAsyncClient bedrockClient = BedrockRuntimeAsyncClient.builder()
                .region(Region.US_EAST_1)
                .credentialsProvider(ProfileCredentialsProvider.create())
                .build();
        return bedrockClient;
    }

    private static Document prepareDocument(String prompt) {
        Document textToVideoParams = Document.mapBuilder()
                .putString("text", prompt)
                .build();

        Document videoGenerationConfig = Document.mapBuilder()
                .putNumber("durationSeconds", 6)
                .putNumber("fps", 24)
                .putString("dimension", "1280x720")
                .build();

        Document novaRequest = Document.mapBuilder()
                .putString("taskType", "TEXT_VIDEO")
                .putDocument("textToVideoParams", textToVideoParams)
                .putDocument("videoGenerationConfig", videoGenerationConfig)
                .build();
        return novaRequest;
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [GetAsyncInvoke](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/GetAsyncInvoke)
  + [StartAsyncInvoke](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/StartAsyncInvoke)

### Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUse_java_2_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
シナリオフローのプライマリ実行。このシナリオはユーザー、Amazon Bedrock Converse API、気象ツールの間の会話を調整します。  

```
/*
 This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
 The program interacts with a foundation model on Amazon Bedrock to provide weather information based on user
 input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.
 */
public class BedrockScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static String modelId = "amazon.nova-lite-v1:0";
    private static String defaultPrompt = "What is the weather like in Seattle?";
    private static WeatherTool weatherTool = new WeatherTool();

    // The maximum number of recursive calls allowed in the tool use function.
    // This helps prevent infinite loops and potential performance issues.
    private static int maxRecursions = 5;
    static BedrockActions bedrockActions = new BedrockActions();
    public static boolean interactive = true;

    private static final String systemPrompt = """
            You are a weather assistant that provides current weather data for user-specified locations using only
            the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
            If the user provides coordinates, infer the approximate location and refer to it in your response.
            To use the tool, you strictly apply the provided tool specification.
            
            - Explain your step-by-step process, and give brief updates before each step.
            - Only use the Weather_Tool for data. Never guess or make up information. 
            - Repeat the tool use for subsequent requests if necessary.
            - If the tool errors, apologize, explain weather is unavailable, and suggest other options.
            - Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
              emojis where appropriate.
            - Only respond to weather queries. Remind off-topic users of your purpose. 
            - Never claim to search online, access external data, or use tools besides Weather_Tool.
            - Complete the entire process until you have all required data before sending the complete response.
            """;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("""
                =================================================
                Welcome to the Amazon Bedrock Tool Use demo!
                =================================================
                
                This assistant provides current weather information for user-specified locations.
                You can ask for weather details by providing the location name or coordinates.
                
                Example queries:
                - What's the weather like in New York?
                - Current weather for latitude 40.70, longitude -74.01
                - Is it warmer in Rome or Barcelona today?
                
                To exit the program, simply type 'x' and press Enter.
                
                P.S.: You're not limited to single locations, or even to using English!
                Have fun and experiment with the app!
                """);
        System.out.println(DASHES);

        try {
            runConversation(scanner);

        } catch (Exception ex) {
            System.out.println("There was a problem running the scenario: " + ex.getMessage());
        }

        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("Amazon Bedrock Converse API with Tool Use Feature Scenario is complete.");
        System.out.println(DASHES);
    }

    /**
     * Starts the conversation with the user and handles the interaction with Bedrock.
     */
    private static List<Message> runConversation(Scanner scanner) {
        List<Message> conversation = new ArrayList<>();

        // Get the first user input
        String userInput = getUserInput("Your weather info request:", scanner);
        System.out.println(userInput);

        while (userInput != null) {
            ContentBlock block = ContentBlock.builder()
                    .text(userInput)
                    .build();

            List<ContentBlock> blockList = new ArrayList<>();
            blockList.add(block);

            Message message = Message.builder()
                    .role(ConversationRole.USER)
                    .content(blockList)
                    .build();

            conversation.add(message);

            // Send the conversation to Amazon Bedrock.
            ConverseResponse bedrockResponse = sendConversationToBedrock(conversation);

            // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0.
            processModelResponse(bedrockResponse, conversation, maxRecursions);

            // Repeat the loop until the user decides to exit the application.
            userInput = getUserInput("Your weather info request:", scanner);
        }
        printFooter();
        return conversation;
    }

    /**
     * Processes the response from the model and updates the conversation accordingly.
     *
     * @param modelResponse the response from the model
     * @param conversation  the ongoing conversation
     * @param maxRecursion  the maximum number of recursions allowed
     */
    private static void processModelResponse(ConverseResponse modelResponse, List<Message> conversation, int maxRecursion) {
        if (maxRecursion <= 0) {
            // Stop the process, the number of recursive calls could indicate an infinite loop
            System.out.println("\tWarning: Maximum number of recursions reached. Please try again.");
        }

        // Append the model's response to the ongoing conversation
        conversation.add(modelResponse.output().message());

        String modelResponseVal = modelResponse.stopReasonAsString();
        if (modelResponseVal.compareTo("tool_use") == 0) {
            // If the stop reason is "tool_use", forward everything to the tool use handler
            handleToolUse(modelResponse.output(), conversation, maxRecursion - 1);
        }

        if (modelResponseVal.compareTo("end_turn") == 0) {
            // If the stop reason is "end_turn", print the model's response text, and finish the process
            PrintModelResponse(modelResponse.output().message().content().get(0).text());
            if (!interactive) {
                defaultPrompt = "x";
            }
        }
    }

    /**
     * Handles the use of a tool by the model in a conversation.
     *
     * @param modelResponse the response from the model, which may include a tool use request
     * @param conversation  the current conversation, which will be updated with the tool use results
     * @param maxRecursion  the maximum number of recursive calls allowed to handle the model's response
     */
    private static void handleToolUse(ConverseOutput modelResponse, List<Message> conversation, int maxRecursion) {
        List<ContentBlock> toolResults = new ArrayList<>();

        // The model's response can consist of multiple content blocks
        for (ContentBlock contentBlock : modelResponse.message().content()) {
            if (contentBlock.text() != null && !contentBlock.text().isEmpty()) {
                // If the content block contains text, print it to the console
                PrintModelResponse(contentBlock.text());
            }

            if (contentBlock.toolUse() != null) {
                ToolResponse toolResponse = invokeTool(contentBlock.toolUse());

                // Add the tool use ID and the tool's response to the list of results
                List<ToolResultContentBlock> contentBlockList = new ArrayList<>();
                ToolResultContentBlock block = ToolResultContentBlock.builder()
                        .json(toolResponse.getContent())
                        .build();
                contentBlockList.add(block);

                ToolResultBlock toolResultBlock = ToolResultBlock.builder()
                        .toolUseId(toolResponse.getToolUseId())
                        .content(contentBlockList)
                        .build();

                ContentBlock contentBlock1 = ContentBlock.builder()
                        .toolResult(toolResultBlock)
                        .build();

                toolResults.add(contentBlock1);
            }
        }

        // Embed the tool results in a new user message
        Message message = Message.builder()
                .role(ConversationRole.USER)
                .content(toolResults)
                .build();

        // Append the new message to the ongoing conversation
        //conversation.add(message);
        conversation.add(message);

        // Send the conversation to Amazon Bedrock
        var response = sendConversationToBedrock(conversation);

        // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0
        processModelResponse(response, conversation, maxRecursion);
    }

    // Invokes the specified tool with the given payload and returns the tool's response.
    // If the requested tool does not exist, an error message is returned.
    private static ToolResponse invokeTool(ToolUseBlock payload) {
        String toolName = payload.name();

        if (Objects.equals(toolName, "Weather_Tool")) {
            Map<String, Document> inputData = payload.input().asMap();
            printToolUse(toolName, inputData);

            // Invoke the weather tool with the input data provided
            Document weatherResponse = weatherTool.fetchWeatherData(inputData.get("latitude").toString(), inputData.get("longitude").toString());

            ToolResponse toolResponse = new ToolResponse();
            toolResponse.setContent(weatherResponse);
            toolResponse.setToolUseId(payload.toolUseId());
            return toolResponse;
        } else {
            String errorMessage = "The requested tool with name " + toolName + " does not exist.";
            System.out.println(errorMessage);
            return null;
        }
    }

    public static void printToolUse(String toolName, Map<String, Document> inputData) {
        System.out.println("Invoking tool: " + toolName + " with input: " + inputData.get("latitude").toString() + ", " + inputData.get("longitude").toString() + "...");
    }

    private static void PrintModelResponse(String message) {
        System.out.println("\tThe model's response:\n");
        System.out.println(message);
        System.out.println("");
    }

    private static ConverseResponse sendConversationToBedrock(List<Message> conversation) {
        System.out.println("Calling Bedrock...");

        try {
            return bedrockActions.sendConverseRequestAsync(modelId, systemPrompt, conversation, weatherTool.getToolSpec());
        } catch (ModelNotReadyException ex) {
             System.err.println("Model is not ready. Please try again later: " + ex.getMessage());
            throw ex;
        } catch (BedrockRuntimeException ex) {
            System.err.println("Bedrock service error: " + ex.getMessage());
            throw ex;
        } catch (RuntimeException ex) {
            System.err.println("Unexpected error occurred: " + ex.getMessage());
            throw ex;
        }
    }

    private static ConverseResponse sendConversationToBedrockwithSpec(List<Message> conversation, ToolSpecification toolSpec) {
        System.out.println("Calling Bedrock...");

        // Send the conversation, system prompt, and tool configuration, and return the response
        return bedrockActions.sendConverseRequestAsync(modelId, systemPrompt, conversation, toolSpec);
    }

    public static String getUserInput(String prompt, Scanner scanner) {
        String userInput = defaultPrompt;
        if (interactive) {
            System.out.println("*".repeat(80));
            System.out.println(prompt + " (x to exit): \n\t");
            userInput = scanner.nextLine();
        }

        if (userInput == null || userInput.trim().isEmpty()) {
            return getUserInput("\tPlease enter your weather info request, e.g., the name of a city", scanner);
        }

        if (userInput.equalsIgnoreCase("x")) {
            return null;
        }

        return userInput;
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println("");
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }

    public static void printFooter() {
        System.out.println("""
                =================================================
                Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you
                learned something new, or got some inspiration for your own apps today!
                
                For more Bedrock examples in different programming languages, have a look at:
                https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html
                =================================================
                """);
    }
}
```
デモで使用される気象ツール。このファイルはツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
public class WeatherTool {

    private static final Logger logger = LoggerFactory.getLogger(WeatherTool.class);
    private static java.net.http.HttpClient httpClient = null;

    /**
     * Returns the JSON Schema specification for the Weather tool. The tool specification
     * defines the input schema and describes the tool's functionality.
     * For more information, see https://json-schema.org/understanding-json-schema/reference.
     *
     * @return The tool specification for the Weather tool.
     */
    public ToolSpecification getToolSpec() {
        Map<String, Document> latitudeMap = new HashMap<>();
        latitudeMap.put("type", Document.fromString("string"));
        latitudeMap.put("description", Document.fromString("Geographical WGS84 latitude of the location."));

        // Create the nested "longitude" object
        Map<String, Document> longitudeMap = new HashMap<>();
        longitudeMap.put("type", Document.fromString("string"));
        longitudeMap.put("description", Document.fromString("Geographical WGS84 longitude of the location."));

        // Create the "properties" object
        Map<String, Document> propertiesMap = new HashMap<>();
        propertiesMap.put("latitude", Document.fromMap(latitudeMap));
        propertiesMap.put("longitude", Document.fromMap(longitudeMap));

        // Create the "required" array
        List<Document> requiredList = new ArrayList<>();
        requiredList.add(Document.fromString("latitude"));
        requiredList.add(Document.fromString("longitude"));

        // Create the root object
        Map<String, Document> rootMap = new HashMap<>();
        rootMap.put("type", Document.fromString("object"));
        rootMap.put("properties", Document.fromMap(propertiesMap));
        rootMap.put("required", Document.fromList(requiredList));

        // Now create the Document representing the JSON schema
        Document document = Document.fromMap(rootMap);

        ToolSpecification specification = ToolSpecification.builder()
            .name("Weather_Tool")
            .description("Get the current weather for a given location, based on its WGS84 coordinates.")
            .inputSchema(ToolInputSchema.builder()
                .json(document)
                .build())
            .build();

        return specification;
    }

    /**
     * Fetches weather data for the given latitude and longitude.
     *
     * @param latitude  the latitude coordinate
     * @param longitude the longitude coordinate
     * @return a {@link CompletableFuture} containing the weather data as a JSON string
     */
    public Document fetchWeatherData(String latitude, String longitude) {
        HttpClient httpClient = HttpClient.newHttpClient();

        // Ensure no extra double quotes
        latitude = latitude.replace("\"", "");
        longitude = longitude.replace("\"", "");

        String endpoint = "https://api.open-meteo.com/v1/forecast";
        String url = String.format("%s?latitude=%s&longitude=%s&current_weather=True", endpoint, latitude, longitude);

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .build();

        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                String weatherJson = response.body();
                System.out.println(weatherJson);
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> rawMap = objectMapper.readValue(weatherJson, new TypeReference<Map<String, Object>>() {});
                Map<String, Document> documentMap = convertToDocumentMap(rawMap);


                Document weatherDocument = Document.fromMap(documentMap);
                System.out.println(weatherDocument);
                return weatherDocument;
            } else {
                throw new RuntimeException("Error fetching weather data: " + response.statusCode());
            }
        } catch (Exception e) {
            System.out.println("Error fetching weather data: " + e.getMessage());
            throw new RuntimeException("Error fetching weather data", e);
        }

    }

    private static Map<String, Document> convertToDocumentMap(Map<String, Object> inputMap) {
        Map<String, Document> result = new HashMap<>();
        for (Map.Entry<String, Object> entry : inputMap.entrySet()) {
            result.put(entry.getKey(), convertToDocument(entry.getValue()));
        }
        return result;
    }

    // Convert different types of Objects to Document
    private static Document convertToDocument(Object value) {
        if (value instanceof Map) {
            return Document.fromMap(convertToDocumentMap((Map<String, Object>) value));
        } else if (value instanceof Integer) {
            return Document.fromNumber(SdkNumber.fromInteger((Integer) value));
        } else if (value instanceof Double) {  //
            return Document.fromNumber(SdkNumber.fromDouble((Double) value));
        } else if (value instanceof Boolean) {
            return Document.fromBoolean((Boolean) value);
        } else if (value instanceof String) {
            return Document.fromString((String) value);
        }
        return Document.fromNull(); // Handle null values safely
    }
}
```
ツール設定を使用する Converse API アクション。  

```
    /**
     * Sends an asynchronous converse request to the AI model.
     *
     * @param modelId      the unique identifier of the AI model to be used for the converse request
     * @param systemPrompt the system prompt to be included in the converse request
     * @param conversation a list of messages representing the conversation history
     * @param toolSpec     the specification of the tool to be used in the converse request
     * @return the converse response received from the AI model
     */
    public ConverseResponse sendConverseRequestAsync(String modelId, String systemPrompt, List<Message> conversation, ToolSpecification toolSpec) {
        List<Tool> toolList = new ArrayList<>();
        Tool tool = Tool.builder()
            .toolSpec(toolSpec)
            .build();

        toolList.add(tool);

        ToolConfiguration configuration = ToolConfiguration.builder()
            .tools(toolList)
            .build();

        SystemContentBlock block = SystemContentBlock.builder()
            .text(systemPrompt)
            .build();

        ConverseRequest request = ConverseRequest.builder()
            .modelId(modelId)
            .system(block)
            .messages(conversation)
            .toolConfig(configuration)
            .build();

        try {
            ConverseResponse response = getClient().converse(request).join();
            return response;

        } catch (ModelNotReadyException ex) {
            throw new RuntimeException("Model is not ready: " + ex.getMessage(), ex);
        } catch (BedrockRuntimeException ex) {
            throw new RuntimeException("Failed to converse with Bedrock model: " + ex.getMessage(), ex);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Amazon Nova
<a name="amazon_nova"></a>

### Converse
<a name="bedrock-runtime_Converse_AmazonNovaText_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
非同期 Java クライアントを含む Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.*;

import java.util.concurrent.CompletableFuture;

/**
 * This example demonstrates how to use the Amazon Nova foundation models
 * with an asynchronous Amazon Bedrock runtime client to generate text.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Create a message
 * - Configure and send a request
 * - Process the response
 */
public class ConverseAsync {

    public static String converseAsync() {

        // Step 1: Create the Amazon Bedrock runtime client
        // The runtime client handles the communication with AI models on Amazon Bedrock
        BedrockRuntimeAsyncClient client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Step 2: Specify which model to use
        // Available Amazon Nova models and their characteristics:
        // - Amazon Nova Micro: Text-only model optimized for lowest latency and cost
        // - Amazon Nova Lite:  Fast, low-cost multimodal model for image, video, and text
        // - Amazon Nova Pro:   Advanced multimodal model balancing accuracy, speed, and cost
        //
        // For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        String modelId = "amazon.nova-lite-v1:0";

        // Step 3: Create the message
        // The message includes the text prompt and specifies that it comes from the user
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Step 4: Configure the request
        // Optional parameters to control the model's response:
        // - maxTokens: maximum number of tokens to generate
        // - temperature: randomness (max: 1.0, default: 0.7)
        //   OR
        // - topP: diversity of word choice (max: 1.0, default: 0.9)
        // Note: Use either temperature OR topP, but not both
        ConverseRequest request = ConverseRequest.builder()
                .modelId(modelId)
                .messages(message)
                .inferenceConfig(config -> config
                                .maxTokens(500)     // The maximum response length
                                .temperature(0.5F)  // Using temperature for randomness control
                        //.topP(0.9F)       // Alternative: use topP instead of temperature
                ).build();

        // Step 5: Send and process the request asynchronously
        // - Send the request to the model
        // - Extract and return the generated text from the response
        try {
            CompletableFuture<ConverseResponse> asyncResponse = client.converse(request);
            return asyncResponse.thenApply(
                    response -> response.output().message().content().get(0).text()
            ).get();

        } catch (Exception e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String response = converseAsync();
        System.out.println(response);
    }
}
```
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.*;

/**
 * This example demonstrates how to use the Amazon Nova foundation models
 * with a synchronous Amazon Bedrock runtime client to generate text.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Create a message
 * - Configure and send a request
 * - Process the response
 */
public class Converse {

    public static String converse() {

        // Step 1: Create the Amazon Bedrock runtime client
        // The runtime client handles the communication with AI models on Amazon Bedrock
        BedrockRuntimeClient client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Step 2: Specify which model to use
        // Available Amazon Nova models and their characteristics:
        // - Amazon Nova Micro: Text-only model optimized for lowest latency and cost
        // - Amazon Nova Lite:  Fast, low-cost multimodal model for image, video, and text
        // - Amazon Nova Pro:   Advanced multimodal model balancing accuracy, speed, and cost
        //
        // For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        String modelId = "amazon.nova-lite-v1:0";

        // Step 3: Create the message
        // The message includes the text prompt and specifies that it comes from the user
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Step 4: Configure the request
        // Optional parameters to control the model's response:
        // - maxTokens: maximum number of tokens to generate
        // - temperature: randomness (max: 1.0, default: 0.7)
        //   OR
        // - topP: diversity of word choice (max: 1.0, default: 0.9)
        // Note: Use either temperature OR topP, but not both
        ConverseRequest request = ConverseRequest.builder()
                .modelId(modelId)
                .messages(message)
                .inferenceConfig(config -> config
                                .maxTokens(500)     // The maximum response length
                                .temperature(0.5F)  // Using temperature for randomness control
                        //.topP(0.9F)       // Alternative: use topP instead of temperature
                ).build();

        // Step 5: Send and process the request
        // - Send the request to the model
        // - Extract and return the generated text from the response
        try {
            ConverseResponse response = client.converse(request);
            return response.output().message().content().get(0).text();

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String response = converse();
        System.out.println(response);
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AmazonNovaText_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.*;

import java.util.concurrent.ExecutionException;

/**
 * This example demonstrates how to use the Amazon Nova foundation models with an
 * asynchronous Amazon Bedrock runtime client to generate streaming text responses.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Create a message
 * - Configure a streaming request
 * - Set up a stream handler to process the response chunks
 * - Process the streaming response
 */
public class ConverseStream {

    public static void converseStream() {

        // Step 1: Create the Amazon Bedrock runtime client
        // The runtime client handles the communication with AI models on Amazon Bedrock
        BedrockRuntimeAsyncClient client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Step 2: Specify which model to use
        // Available Amazon Nova models and their characteristics:
        // - Amazon Nova Micro: Text-only model optimized for lowest latency and cost
        // - Amazon Nova Lite:  Fast, low-cost multimodal model for image, video, and text
        // - Amazon Nova Pro:   Advanced multimodal model balancing accuracy, speed, and cost
        //
        // For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        String modelId = "amazon.nova-lite-v1:0";

        // Step 3: Create the message
        // The message includes the text prompt and specifies that it comes from the user
        var inputText = "Describe the purpose of a 'hello world' program in one paragraph";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Step 4: Configure the request
        // Optional parameters to control the model's response:
        // - maxTokens: maximum number of tokens to generate
        // - temperature: randomness (max: 1.0, default: 0.7)
        //   OR
        // - topP: diversity of word choice (max: 1.0, default: 0.9)
        // Note: Use either temperature OR topP, but not both
        ConverseStreamRequest request = ConverseStreamRequest.builder()
                .modelId(modelId)
                .messages(message)
                .inferenceConfig(config -> config
                                .maxTokens(500)     // The maximum response length
                                .temperature(0.5F)  // Using temperature for randomness control
                        //.topP(0.9F)       // Alternative: use topP instead of temperature
                ).build();

        // Step 5: Set up the stream handler
        // The stream handler processes chunks of the response as they arrive
        // - onContentBlockDelta: Processes each text chunk
        // - onError: Handles any errors during streaming
        var streamHandler = ConverseStreamResponseHandler.builder()
                .subscriber(ConverseStreamResponseHandler.Visitor.builder()
                        .onContentBlockDelta(chunk -> {
                            System.out.print(chunk.delta().text());
                            System.out.flush();  // Ensure immediate output of each chunk
                        }).build())
                .onError(err -> System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage()))
                .build();

        // Step 6: Send the streaming request and process the response
        // - Send the request to the model
        // - Attach the handler to process response chunks as they arrive
        // - Handle any errors during streaming
        try {
            client.converseStream(request, streamHandler).get();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
        }
    }

    public static void main(String[] args) {
        converseStream();
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### シナリオ: Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUseDemo_AmazonNova_java_2_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
シナリオフローのプライマリ実行。このシナリオはユーザー、Amazon Bedrock Converse API、気象ツールの間の会話を調整します。  

```
/*
 This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
 The program interacts with a foundation model on Amazon Bedrock to provide weather information based on user
 input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.
 */
public class BedrockScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static String modelId = "amazon.nova-lite-v1:0";
    private static String defaultPrompt = "What is the weather like in Seattle?";
    private static WeatherTool weatherTool = new WeatherTool();

    // The maximum number of recursive calls allowed in the tool use function.
    // This helps prevent infinite loops and potential performance issues.
    private static int maxRecursions = 5;
    static BedrockActions bedrockActions = new BedrockActions();
    public static boolean interactive = true;

    private static final String systemPrompt = """
            You are a weather assistant that provides current weather data for user-specified locations using only
            the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
            If the user provides coordinates, infer the approximate location and refer to it in your response.
            To use the tool, you strictly apply the provided tool specification.
            
            - Explain your step-by-step process, and give brief updates before each step.
            - Only use the Weather_Tool for data. Never guess or make up information. 
            - Repeat the tool use for subsequent requests if necessary.
            - If the tool errors, apologize, explain weather is unavailable, and suggest other options.
            - Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
              emojis where appropriate.
            - Only respond to weather queries. Remind off-topic users of your purpose. 
            - Never claim to search online, access external data, or use tools besides Weather_Tool.
            - Complete the entire process until you have all required data before sending the complete response.
            """;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("""
                =================================================
                Welcome to the Amazon Bedrock Tool Use demo!
                =================================================
                
                This assistant provides current weather information for user-specified locations.
                You can ask for weather details by providing the location name or coordinates.
                
                Example queries:
                - What's the weather like in New York?
                - Current weather for latitude 40.70, longitude -74.01
                - Is it warmer in Rome or Barcelona today?
                
                To exit the program, simply type 'x' and press Enter.
                
                P.S.: You're not limited to single locations, or even to using English!
                Have fun and experiment with the app!
                """);
        System.out.println(DASHES);

        try {
            runConversation(scanner);

        } catch (Exception ex) {
            System.out.println("There was a problem running the scenario: " + ex.getMessage());
        }

        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("Amazon Bedrock Converse API with Tool Use Feature Scenario is complete.");
        System.out.println(DASHES);
    }

    /**
     * Starts the conversation with the user and handles the interaction with Bedrock.
     */
    private static List<Message> runConversation(Scanner scanner) {
        List<Message> conversation = new ArrayList<>();

        // Get the first user input
        String userInput = getUserInput("Your weather info request:", scanner);
        System.out.println(userInput);

        while (userInput != null) {
            ContentBlock block = ContentBlock.builder()
                    .text(userInput)
                    .build();

            List<ContentBlock> blockList = new ArrayList<>();
            blockList.add(block);

            Message message = Message.builder()
                    .role(ConversationRole.USER)
                    .content(blockList)
                    .build();

            conversation.add(message);

            // Send the conversation to Amazon Bedrock.
            ConverseResponse bedrockResponse = sendConversationToBedrock(conversation);

            // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0.
            processModelResponse(bedrockResponse, conversation, maxRecursions);

            // Repeat the loop until the user decides to exit the application.
            userInput = getUserInput("Your weather info request:", scanner);
        }
        printFooter();
        return conversation;
    }

    /**
     * Processes the response from the model and updates the conversation accordingly.
     *
     * @param modelResponse the response from the model
     * @param conversation  the ongoing conversation
     * @param maxRecursion  the maximum number of recursions allowed
     */
    private static void processModelResponse(ConverseResponse modelResponse, List<Message> conversation, int maxRecursion) {
        if (maxRecursion <= 0) {
            // Stop the process, the number of recursive calls could indicate an infinite loop
            System.out.println("\tWarning: Maximum number of recursions reached. Please try again.");
        }

        // Append the model's response to the ongoing conversation
        conversation.add(modelResponse.output().message());

        String modelResponseVal = modelResponse.stopReasonAsString();
        if (modelResponseVal.compareTo("tool_use") == 0) {
            // If the stop reason is "tool_use", forward everything to the tool use handler
            handleToolUse(modelResponse.output(), conversation, maxRecursion - 1);
        }

        if (modelResponseVal.compareTo("end_turn") == 0) {
            // If the stop reason is "end_turn", print the model's response text, and finish the process
            PrintModelResponse(modelResponse.output().message().content().get(0).text());
            if (!interactive) {
                defaultPrompt = "x";
            }
        }
    }

    /**
     * Handles the use of a tool by the model in a conversation.
     *
     * @param modelResponse the response from the model, which may include a tool use request
     * @param conversation  the current conversation, which will be updated with the tool use results
     * @param maxRecursion  the maximum number of recursive calls allowed to handle the model's response
     */
    private static void handleToolUse(ConverseOutput modelResponse, List<Message> conversation, int maxRecursion) {
        List<ContentBlock> toolResults = new ArrayList<>();

        // The model's response can consist of multiple content blocks
        for (ContentBlock contentBlock : modelResponse.message().content()) {
            if (contentBlock.text() != null && !contentBlock.text().isEmpty()) {
                // If the content block contains text, print it to the console
                PrintModelResponse(contentBlock.text());
            }

            if (contentBlock.toolUse() != null) {
                ToolResponse toolResponse = invokeTool(contentBlock.toolUse());

                // Add the tool use ID and the tool's response to the list of results
                List<ToolResultContentBlock> contentBlockList = new ArrayList<>();
                ToolResultContentBlock block = ToolResultContentBlock.builder()
                        .json(toolResponse.getContent())
                        .build();
                contentBlockList.add(block);

                ToolResultBlock toolResultBlock = ToolResultBlock.builder()
                        .toolUseId(toolResponse.getToolUseId())
                        .content(contentBlockList)
                        .build();

                ContentBlock contentBlock1 = ContentBlock.builder()
                        .toolResult(toolResultBlock)
                        .build();

                toolResults.add(contentBlock1);
            }
        }

        // Embed the tool results in a new user message
        Message message = Message.builder()
                .role(ConversationRole.USER)
                .content(toolResults)
                .build();

        // Append the new message to the ongoing conversation
        //conversation.add(message);
        conversation.add(message);

        // Send the conversation to Amazon Bedrock
        var response = sendConversationToBedrock(conversation);

        // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0
        processModelResponse(response, conversation, maxRecursion);
    }

    // Invokes the specified tool with the given payload and returns the tool's response.
    // If the requested tool does not exist, an error message is returned.
    private static ToolResponse invokeTool(ToolUseBlock payload) {
        String toolName = payload.name();

        if (Objects.equals(toolName, "Weather_Tool")) {
            Map<String, Document> inputData = payload.input().asMap();
            printToolUse(toolName, inputData);

            // Invoke the weather tool with the input data provided
            Document weatherResponse = weatherTool.fetchWeatherData(inputData.get("latitude").toString(), inputData.get("longitude").toString());

            ToolResponse toolResponse = new ToolResponse();
            toolResponse.setContent(weatherResponse);
            toolResponse.setToolUseId(payload.toolUseId());
            return toolResponse;
        } else {
            String errorMessage = "The requested tool with name " + toolName + " does not exist.";
            System.out.println(errorMessage);
            return null;
        }
    }

    public static void printToolUse(String toolName, Map<String, Document> inputData) {
        System.out.println("Invoking tool: " + toolName + " with input: " + inputData.get("latitude").toString() + ", " + inputData.get("longitude").toString() + "...");
    }

    private static void PrintModelResponse(String message) {
        System.out.println("\tThe model's response:\n");
        System.out.println(message);
        System.out.println("");
    }

    private static ConverseResponse sendConversationToBedrock(List<Message> conversation) {
        System.out.println("Calling Bedrock...");

        try {
            return bedrockActions.sendConverseRequestAsync(modelId, systemPrompt, conversation, weatherTool.getToolSpec());
        } catch (ModelNotReadyException ex) {
             System.err.println("Model is not ready. Please try again later: " + ex.getMessage());
            throw ex;
        } catch (BedrockRuntimeException ex) {
            System.err.println("Bedrock service error: " + ex.getMessage());
            throw ex;
        } catch (RuntimeException ex) {
            System.err.println("Unexpected error occurred: " + ex.getMessage());
            throw ex;
        }
    }

    private static ConverseResponse sendConversationToBedrockwithSpec(List<Message> conversation, ToolSpecification toolSpec) {
        System.out.println("Calling Bedrock...");

        // Send the conversation, system prompt, and tool configuration, and return the response
        return bedrockActions.sendConverseRequestAsync(modelId, systemPrompt, conversation, toolSpec);
    }

    public static String getUserInput(String prompt, Scanner scanner) {
        String userInput = defaultPrompt;
        if (interactive) {
            System.out.println("*".repeat(80));
            System.out.println(prompt + " (x to exit): \n\t");
            userInput = scanner.nextLine();
        }

        if (userInput == null || userInput.trim().isEmpty()) {
            return getUserInput("\tPlease enter your weather info request, e.g., the name of a city", scanner);
        }

        if (userInput.equalsIgnoreCase("x")) {
            return null;
        }

        return userInput;
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println("");
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }

    public static void printFooter() {
        System.out.println("""
                =================================================
                Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you
                learned something new, or got some inspiration for your own apps today!
                
                For more Bedrock examples in different programming languages, have a look at:
                https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html
                =================================================
                """);
    }
}
```
デモで使用される気象ツール。このファイルはツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
public class WeatherTool {

    private static final Logger logger = LoggerFactory.getLogger(WeatherTool.class);
    private static java.net.http.HttpClient httpClient = null;

    /**
     * Returns the JSON Schema specification for the Weather tool. The tool specification
     * defines the input schema and describes the tool's functionality.
     * For more information, see https://json-schema.org/understanding-json-schema/reference.
     *
     * @return The tool specification for the Weather tool.
     */
    public ToolSpecification getToolSpec() {
        Map<String, Document> latitudeMap = new HashMap<>();
        latitudeMap.put("type", Document.fromString("string"));
        latitudeMap.put("description", Document.fromString("Geographical WGS84 latitude of the location."));

        // Create the nested "longitude" object
        Map<String, Document> longitudeMap = new HashMap<>();
        longitudeMap.put("type", Document.fromString("string"));
        longitudeMap.put("description", Document.fromString("Geographical WGS84 longitude of the location."));

        // Create the "properties" object
        Map<String, Document> propertiesMap = new HashMap<>();
        propertiesMap.put("latitude", Document.fromMap(latitudeMap));
        propertiesMap.put("longitude", Document.fromMap(longitudeMap));

        // Create the "required" array
        List<Document> requiredList = new ArrayList<>();
        requiredList.add(Document.fromString("latitude"));
        requiredList.add(Document.fromString("longitude"));

        // Create the root object
        Map<String, Document> rootMap = new HashMap<>();
        rootMap.put("type", Document.fromString("object"));
        rootMap.put("properties", Document.fromMap(propertiesMap));
        rootMap.put("required", Document.fromList(requiredList));

        // Now create the Document representing the JSON schema
        Document document = Document.fromMap(rootMap);

        ToolSpecification specification = ToolSpecification.builder()
            .name("Weather_Tool")
            .description("Get the current weather for a given location, based on its WGS84 coordinates.")
            .inputSchema(ToolInputSchema.builder()
                .json(document)
                .build())
            .build();

        return specification;
    }

    /**
     * Fetches weather data for the given latitude and longitude.
     *
     * @param latitude  the latitude coordinate
     * @param longitude the longitude coordinate
     * @return a {@link CompletableFuture} containing the weather data as a JSON string
     */
    public Document fetchWeatherData(String latitude, String longitude) {
        HttpClient httpClient = HttpClient.newHttpClient();

        // Ensure no extra double quotes
        latitude = latitude.replace("\"", "");
        longitude = longitude.replace("\"", "");

        String endpoint = "https://api.open-meteo.com/v1/forecast";
        String url = String.format("%s?latitude=%s&longitude=%s&current_weather=True", endpoint, latitude, longitude);

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .build();

        try {
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            if (response.statusCode() == 200) {
                String weatherJson = response.body();
                System.out.println(weatherJson);
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> rawMap = objectMapper.readValue(weatherJson, new TypeReference<Map<String, Object>>() {});
                Map<String, Document> documentMap = convertToDocumentMap(rawMap);


                Document weatherDocument = Document.fromMap(documentMap);
                System.out.println(weatherDocument);
                return weatherDocument;
            } else {
                throw new RuntimeException("Error fetching weather data: " + response.statusCode());
            }
        } catch (Exception e) {
            System.out.println("Error fetching weather data: " + e.getMessage());
            throw new RuntimeException("Error fetching weather data", e);
        }

    }

    private static Map<String, Document> convertToDocumentMap(Map<String, Object> inputMap) {
        Map<String, Document> result = new HashMap<>();
        for (Map.Entry<String, Object> entry : inputMap.entrySet()) {
            result.put(entry.getKey(), convertToDocument(entry.getValue()));
        }
        return result;
    }

    // Convert different types of Objects to Document
    private static Document convertToDocument(Object value) {
        if (value instanceof Map) {
            return Document.fromMap(convertToDocumentMap((Map<String, Object>) value));
        } else if (value instanceof Integer) {
            return Document.fromNumber(SdkNumber.fromInteger((Integer) value));
        } else if (value instanceof Double) {  //
            return Document.fromNumber(SdkNumber.fromDouble((Double) value));
        } else if (value instanceof Boolean) {
            return Document.fromBoolean((Boolean) value);
        } else if (value instanceof String) {
            return Document.fromString((String) value);
        }
        return Document.fromNull(); // Handle null values safely
    }
}
```
ツール設定を使用する Converse API アクション。  

```
    /**
     * Sends an asynchronous converse request to the AI model.
     *
     * @param modelId      the unique identifier of the AI model to be used for the converse request
     * @param systemPrompt the system prompt to be included in the converse request
     * @param conversation a list of messages representing the conversation history
     * @param toolSpec     the specification of the tool to be used in the converse request
     * @return the converse response received from the AI model
     */
    public ConverseResponse sendConverseRequestAsync(String modelId, String systemPrompt, List<Message> conversation, ToolSpecification toolSpec) {
        List<Tool> toolList = new ArrayList<>();
        Tool tool = Tool.builder()
            .toolSpec(toolSpec)
            .build();

        toolList.add(tool);

        ToolConfiguration configuration = ToolConfiguration.builder()
            .tools(toolList)
            .build();

        SystemContentBlock block = SystemContentBlock.builder()
            .text(systemPrompt)
            .build();

        ConverseRequest request = ConverseRequest.builder()
            .modelId(modelId)
            .system(block)
            .messages(conversation)
            .toolConfig(configuration)
            .build();

        try {
            ConverseResponse response = getClient().converse(request).join();
            return response;

        } catch (ModelNotReadyException ex) {
            throw new RuntimeException("Model is not ready: " + ex.getMessage(), ex);
        } catch (BedrockRuntimeException ex) {
            throw new RuntimeException("Failed to converse with Bedrock model: " + ex.getMessage(), ex);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Amazon Nova Canvas
<a name="amazon_nova_canvas"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AmazonNovaImageGeneration_java_2_topic"></a>

以下のコード例は、Amazon Bedrock で Amazon Nova Canvas を呼び出して画像を生成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Nova Canvas で画像を作成します。  

```
import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelResponse;

import java.security.SecureRandom;
import java.util.Base64;

import static com.example.bedrockruntime.libs.ImageTools.displayImage;

/**
 * This example demonstrates how to use Amazon Nova Canvas to generate images.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Configure the image generation parameters
 * - Send a request to generate an image
 * - Process the response and handle the generated image
 */
public class InvokeModel {

    public static byte[] invokeModel() {

        // Step 1: Create the Amazon Bedrock runtime client
        // The runtime client handles the communication with AI models on Amazon Bedrock
        BedrockRuntimeClient client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Step 2: Specify which model to use
        // For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        String modelId = "amazon.nova-canvas-v1:0";

        // Step 3: Configure the generation parameters and create the request
        // First, set the main parameters:
        // - prompt: Text description of the image to generate
        // - seed: Random number for reproducible generation (0 to 858,993,459)
        String prompt = "A stylized picture of a cute old steampunk robot";
        int seed = new SecureRandom().nextInt(858_993_460);

        // Then, create the request using a template with the following structure:
        // - taskType: TEXT_IMAGE (specifies text-to-image generation)
        // - textToImageParams: Contains the text prompt
        // - imageGenerationConfig: Contains optional generation settings (seed, quality, etc.)
        // For a list of available request parameters, see:
        // https://docs.aws.amazon.com/nova/latest/userguide/image-gen-req-resp-structure.html
        String request = """
                {
                    "taskType": "TEXT_IMAGE",
                    "textToImageParams": {
                        "text": "{{prompt}}"
                    },
                    "imageGenerationConfig": {
                        "seed": {{seed}},
                        "quality": "standard"
                    }
                }"""
                .replace("{{prompt}}", prompt)
                .replace("{{seed}}", String.valueOf(seed));

        // Step 4: Send and process the request
        // - Send the request to the model using InvokeModelResponse
        // - Extract the Base64-encoded image from the JSON response
        // - Convert the encoded image to a byte array and return it
        try {
            InvokeModelResponse response = client.invokeModel(builder -> builder
                    .modelId(modelId)
                    .body(SdkBytes.fromUtf8String(request))
            );

            JSONObject responseBody = new JSONObject(response.body().asUtf8String());
            // Convert the Base64 string to byte array for better handling
            return Base64.getDecoder().decode(
                    new JSONPointer("/images/0").queryFrom(responseBody).toString()
            );

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s%n", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println("Generating image. This may take a few seconds...");
        byte[] imageData = invokeModel();
        displayImage(imageData);
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Amazon Titan Image Generator
<a name="amazon_titan_image_generator"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_TitanImageGenerator_java_2_topic"></a>

次のコード例は、Amazon Bedrock で Amazon Titan Image を呼び出して画像を生成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Titan Image Generator を使用して画像を作成します。  

```
// Create an image with the Amazon Titan Image Generator.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

import java.math.BigInteger;
import java.security.SecureRandom;

import static com.example.bedrockruntime.libs.ImageTools.displayImage;

public class InvokeModel {

    public static String invokeModel() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Titan Image G2.
        var modelId = "amazon.titan-image-generator-v2:0";

        // The InvokeModel API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html
        var nativeRequestTemplate = """
                {
                    "taskType": "TEXT_IMAGE",
                    "textToImageParams": { "text": "{{prompt}}" },
                    "imageGenerationConfig": { "seed": {{seed}} }
                }""";

        // Define the prompt for the image generation.
        var prompt = "A stylized picture of a cute old steampunk robot";

        // Get a random 31-bit seed for the image generation (max. 2,147,483,647).
        var seed = new BigInteger(31, new SecureRandom());

        // Embed the prompt and seed in the model's native request payload.
        var nativeRequest = nativeRequestTemplate
                .replace("{{prompt}}", prompt)
                .replace("{{seed}}", seed.toString());

        try {
            // Encode and send the request to the Bedrock Runtime.
            var response = client.invokeModel(request -> request
                    .body(SdkBytes.fromUtf8String(nativeRequest))
                    .modelId(modelId)
            );

            // Decode the response body.
            var responseBody = new JSONObject(response.body().asUtf8String());

            // Retrieve the generated image data from the model's response.
            var base64ImageData = new JSONPointer("/images/0").queryFrom(responseBody).toString();

            return base64ImageData;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println("Generating image. This may take a few seconds...");

        String base64ImageData = invokeModel();

        displayImage(base64ImageData);
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Amazon Titan Text Embeddings
<a name="amazon_titan_text_embeddings"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModelWithResponseStream_TitanTextEmbeddings_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 最初の埋め込みの作成を開始します。
+ ディメンションの数と正規化を設定する埋め込みを作成します (V2 のみ)。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Titan Text Embeddings V2 で最初の埋め込みを作成します。  

```
// Generate and print an embedding with Amazon Titan Text Embeddings.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

public class InvokeModel {

    public static String invokeModel() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Titan Text Embeddings V2.
        var modelId = "amazon.titan-embed-text-v2:0";

        // The InvokeModel API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-embed-text.html
        var nativeRequestTemplate = "{ \"inputText\": \"{{inputText}}\" }";

        // The text to convert into an embedding.
        var inputText = "Please recommend books with a theme similar to the movie 'Inception'.";

        // Embed the prompt in the model's native request payload.
        String nativeRequest = nativeRequestTemplate.replace("{{inputText}}", inputText);

        try {
            // Encode and send the request to the Bedrock Runtime.
            var response = client.invokeModel(request -> request
                    .body(SdkBytes.fromUtf8String(nativeRequest))
                    .modelId(modelId)
            );

            // Decode the response body.
            var responseBody = new JSONObject(response.body().asUtf8String());

            // Retrieve the generated text from the model's response.
            var text = new JSONPointer("/embedding").queryFrom(responseBody).toString();
            System.out.println(text);

            return text;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        invokeModel();
    }
}
```
ディメンションの数と正規化を設定する Titan Text Embeddings V2 を呼び出します。  

```
    /**
     * Invoke Amazon Titan Text Embeddings V2 with additional inference parameters.
     *
     * @param inputText  - The text to convert to an embedding.
     * @param dimensions - The number of dimensions the output embeddings should have.
     *                   Values accepted by the model: 256, 512, 1024.
     * @param normalize  - A flag indicating whether or not to normalize the output embeddings.
     * @return The {@link JSONObject} representing the model's response.
     */
    public static JSONObject invokeModel(String inputText, int dimensions, boolean normalize) {

        // Create a Bedrock Runtime client in the AWS Region of your choice.
        var client = BedrockRuntimeClient.builder()
                .region(Region.US_WEST_2)
                .build();

        // Set the model ID, e.g., Titan Embed Text v2.0.
        var modelId = "amazon.titan-embed-text-v2:0";

        // Create the request for the model.
        var nativeRequest = """
                {
                    "inputText": "%s",
                    "dimensions": %d,
                    "normalize": %b
                }
                """.formatted(inputText, dimensions, normalize);

        // Encode and send the request.
        var response = client.invokeModel(request -> {
            request.body(SdkBytes.fromUtf8String(nativeRequest));
            request.modelId(modelId);
        });

        // Decode the model's response.
        var modelResponse = new JSONObject(response.body().asUtf8String());

        // Extract and print the generated embedding and the input text token count.
        var embedding = modelResponse.getJSONArray("embedding");
        var inputTokenCount = modelResponse.getBigInteger("inputTextTokenCount");
        System.out.println("Embedding: " + embedding);
        System.out.println("\nInput token count: " + inputTokenCount);

        // Return the model's native response.
        return modelResponse;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Anthropic Claude
<a name="anthropic_claude"></a>

### Converse
<a name="bedrock-runtime_Converse_AnthropicClaude_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Anthropic Claude.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

public class Converse {

    public static String converse() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Claude 3 Haiku.
        var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();


        try {
            // Send the message with a basic inference configuration.
            ConverseResponse response = client.converse(request -> request
                    .modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)));

            // Retrieve the generated text from Bedrock's response object.
            var responseText = response.output().message().content().getFirst().text();
            System.out.println(responseText);

            return responseText;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        converse();
    }
}
```
Bedrock の Converse API と非同期 Java クライアントを使用して、Anthropic Claude にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Anthropic Claude
// with the async Java client.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ConverseAsync {

    public static String converseAsync() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Claude 3 Haiku.
        var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Send the message with a basic inference configuration.
        var request = client.converse(params -> params
                .modelId(modelId)
                .messages(message)
                .inferenceConfig(config -> config
                        .maxTokens(512)
                        .temperature(0.5F)
                        .topP(0.9F))
        );

        // Prepare a future object to handle the asynchronous response.
        CompletableFuture<String> future = new CompletableFuture<>();

        // Handle the response or error using the future object.
        request.whenComplete((response, error) -> {
            if (error == null) {
                // Extract the generated text from Bedrock's response object.
                String responseText = response.output().message().content().getFirst().text();
                future.complete(responseText);
            } else {
                future.completeExceptionally(error);
            }
        });

        try {
            // Wait for the future object to complete and retrieve the generated text.
            String responseText = future.get();
            System.out.println(responseText);

            return responseText;

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        converseAsync();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AnthropicClaude_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Anthropic Claude
// and print the response stream.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.ExecutionException;

public class ConverseStream {

    public static void main(String[] args) {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Claude 3 Haiku.
        var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Create a handler to extract and print the response text in real-time.
        var responseStreamHandler = ConverseStreamResponseHandler.builder()
                .subscriber(ConverseStreamResponseHandler.Visitor.builder()
                        .onContentBlockDelta(chunk -> {
                            String responseText = chunk.delta().text();
                            System.out.print(responseText);
                        }).build()
                ).onError(err ->
                        System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage())
                ).build();

        try {
            // Send the message with a basic inference configuration and attach the handler.
            client.converseStream(request -> request.modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)
                    ), responseStreamHandler).get();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AnthropicClaude_java_2_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Anthropic Claude.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

public class InvokeModel {

    public static String invokeModel() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Claude 3 Haiku.
        var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

        // The InvokeModel API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
        var nativeRequestTemplate = """
                {
                    "anthropic_version": "bedrock-2023-05-31",
                    "max_tokens": 512,
                    "temperature": 0.5,
                    "messages": [{
                        "role": "user",
                        "content": "{{prompt}}"
                    }]
                }""";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in the model's native request payload.
        String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt);

        try {
            // Encode and send the request to the Bedrock Runtime.
            var response = client.invokeModel(request -> request
                    .body(SdkBytes.fromUtf8String(nativeRequest))
                    .modelId(modelId)
            );

            // Decode the response body.
            var responseBody = new JSONObject(response.body().asUtf8String());

            // Retrieve the generated text from the model's response.
            var text = new JSONPointer("/content/0/text").queryFrom(responseBody).toString();
            System.out.println(text);

            return text;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        invokeModel();
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_AnthropicClaude_java_2_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Anthropic Claude
// and print the response stream.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;

import java.util.Objects;
import java.util.concurrent.ExecutionException;

import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;

public class InvokeModelWithResponseStream {

    public static String invokeModelWithResponseStream() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Claude 3 Haiku.
        var modelId = "anthropic.claude-3-haiku-20240307-v1:0";

        // The InvokeModelWithResponseStream API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
        var nativeRequestTemplate = """
                {
                    "anthropic_version": "bedrock-2023-05-31",
                    "max_tokens": 512,
                    "temperature": 0.5,
                    "messages": [{
                        "role": "user",
                        "content": "{{prompt}}"
                    }]
                }""";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in the model's native request payload.
        String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt);

        // Create a request with the model ID and the model's native request payload.
        var request = InvokeModelWithResponseStreamRequest.builder()
                .body(SdkBytes.fromUtf8String(nativeRequest))
                .modelId(modelId)
                .build();

        // Prepare a buffer to accumulate the generated response text.
        var completeResponseTextBuffer = new StringBuilder();

        // Prepare a handler to extract, accumulate, and print the response text in real-time.
        var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder()
                .subscriber(Visitor.builder().onChunk(chunk -> {
                    var response = new JSONObject(chunk.bytes().asUtf8String());

                    // Extract and print the text from the content blocks.
                    if (Objects.equals(response.getString("type"), "content_block_delta")) {
                        var text = new JSONPointer("/delta/text").queryFrom(response);
                        System.out.print(text);

                        // Append the text to the response text buffer.
                        completeResponseTextBuffer.append(text);
                    }
                }).build()).build();

        try {
            // Send the request and wait for the handler to process the response.
            client.invokeModelWithResponseStream(request, responseStreamHandler).get();

            // Return the complete response text.
            return completeResponseTextBuffer.toString();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        invokeModelWithResponseStream();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

### 推論
<a name="bedrock-runtime_Converse_AnthropicClaudeReasoning_java_2_topic"></a>

次のコード例は、Amazon Bedrock で Anthropic Claude 3.7 Sonnet の推論機能を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Anthropic Claude 3.7 Sonnet の推論機能を非同期 Bedrock ランタイムクライアントで使用します。  

```
import com.example.bedrockruntime.models.anthropicClaude.lib.ReasoningResponse;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.*;

import java.util.concurrent.CompletableFuture;

/**
 * This example demonstrates how to use Anthropic Claude 3.7 Sonnet's reasoning capability
 * with an asynchronous Amazon Bedrock runtime client.
 * It shows how to:
 * - Set up the Amazon Bedrock async runtime client
 * - Create a message
 * - Configure reasoning parameters
 * - Send an asynchronous request with reasoning enabled
 * - Process both the reasoning output and final response
 */
public class ReasoningAsync {

    public static ReasoningResponse reasoningAsync() {

        // Create the Amazon Bedrock runtime client
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Specify the model ID. For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        var modelId = "us.anthropic.claude-3-7-sonnet-20250219-v1:0";

        // Create the message with the user's prompt
        var prompt = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(prompt))
                .role(ConversationRole.USER)
                .build();

        // Configure reasoning parameters with a 2000 token budget
        Document reasoningConfig = Document.mapBuilder()
                .putDocument("thinking", Document.mapBuilder()
                        .putString("type", "enabled")
                        .putNumber("budget_tokens", 2000)
                        .build())
                .build();

        try {
            // Send message and reasoning configuration to the model
            CompletableFuture<ConverseResponse> asyncResponse = client.converse(request -> request
                    .additionalModelRequestFields(reasoningConfig)
                    .messages(message)
                    .modelId(modelId)
            );

            // Process the response asynchronously
            return asyncResponse.thenApply(response -> {

                        var content = response.output().message().content();
                        ReasoningContentBlock reasoning = null;
                        String text = null;

                        // Process each content block to find reasoning and response text
                        for (ContentBlock block : content) {
                            if (block.reasoningContent() != null) {
                                reasoning = block.reasoningContent();
                            } else if (block.text() != null) {
                                text = block.text();
                            }
                        }

                        return new ReasoningResponse(reasoning, text);
                    }
            ).get();

        } catch (Exception e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // Execute the example and display reasoning and final response
        ReasoningResponse response = reasoningAsync();
        System.out.println("\n<thinking>");
        System.out.println(response.reasoning().reasoningText());
        System.out.println("</thinking>\n");
        System.out.println(response.text());
    }
}
```
Anthropic Claude 3.7 Sonnet の推論機能を同期 Bedrock ランタイムクライアントで使用します。  

```
import com.example.bedrockruntime.models.anthropicClaude.lib.ReasoningResponse;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.*;

/**
 * This example demonstrates how to use Anthropic Claude 3.7 Sonnet's reasoning capability
 * with the synchronous Amazon Bedrock runtime client.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Create a message
 * - Configure reasoning parameters
 * - Send a request with reasoning enabled
 * - Process both the reasoning output and final response
 */
public class Reasoning {

    public static ReasoningResponse reasoning() {

        // Create the Amazon Bedrock runtime client
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Specify the model ID. For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        var modelId = "us.anthropic.claude-3-7-sonnet-20250219-v1:0";

        // Create the message with the user's prompt
        var prompt = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(prompt))
                .role(ConversationRole.USER)
                .build();

        // Configure reasoning parameters with a 2000 token budget
        Document reasoningConfig = Document.mapBuilder()
                .putDocument("thinking", Document.mapBuilder()
                        .putString("type", "enabled")
                        .putNumber("budget_tokens", 2000)
                        .build())
                .build();

        try {
            // Send message and reasoning configuration to the model
            ConverseResponse bedrockResponse = client.converse(request -> request
                    .additionalModelRequestFields(reasoningConfig)
                    .messages(message)
                    .modelId(modelId)
            );


            // Extract both reasoning and final response
            var content = bedrockResponse.output().message().content();
            ReasoningContentBlock reasoning = null;
            String text = null;

            // Process each content block to find reasoning and response text
            for (ContentBlock block : content) {
                if (block.reasoningContent() != null) {
                    reasoning = block.reasoningContent();
                } else if (block.text() != null) {
                    text = block.text();
                }
            }

            return new ReasoningResponse(reasoning, text);

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // Execute the example and display reasoning and final response
        ReasoningResponse response = reasoning();
        System.out.println("\n<thinking>");
        System.out.println(response.reasoning().reasoningText());
        System.out.println("</thinking>\n");
        System.out.println(response.text());
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ストリーミングレスポンスによる推論
<a name="bedrock-runtime_ConverseStream_AnthropicClaudeReasoning_java_2_topic"></a>

次のコード例は、Amazon Bedrock で Anthropic Claude 3.7 Sonnet の推論機能を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Anthropic Claude 3.7 Sonnet の推論機能を使用して、ストリーミングテキストレスポンスを生成します。  

```
import com.example.bedrockruntime.models.anthropicClaude.lib.ReasoningResponse;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.*;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;

/**
 * This example demonstrates how to use Anthropic Claude 3.7 Sonnet's reasoning
 * capability to generate streaming text responses.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Create a message
 * - Configure a streaming request
 * - Set up a stream handler to process the response chunks
 * - Process the streaming response
 */
public class ReasoningStream {

    public static ReasoningResponse reasoningStream() {

        // Create the Amazon Bedrock runtime client
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Specify the model ID. For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        var modelId = "us.anthropic.claude-3-7-sonnet-20250219-v1:0";

        // Create the message with the user's prompt
        var prompt = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(prompt))
                .role(ConversationRole.USER)
                .build();

        // Configure reasoning parameters with a 2000 token budget
        Document reasoningConfig = Document.mapBuilder()
                .putDocument("thinking", Document.mapBuilder()
                        .putString("type", "enabled")
                        .putNumber("budget_tokens", 2000)
                        .build())
                .build();

        // Configure the request with the message, model ID, and reasoning config
        ConverseStreamRequest request = ConverseStreamRequest.builder()
                .additionalModelRequestFields(reasoningConfig)
                .messages(message)
                .modelId(modelId)
                .build();

        StringBuilder reasoning = new StringBuilder();
        StringBuilder text = new StringBuilder();
        AtomicReference<ReasoningResponse> finalresponse = new AtomicReference<>();

        // Set up the stream handler to processes chunks of the response as they arrive
        var streamHandler = ConverseStreamResponseHandler.builder()
                .subscriber(ConverseStreamResponseHandler.Visitor.builder()
                        .onContentBlockDelta(chunk -> {
                            ContentBlockDelta delta = chunk.delta();
                            if (delta.reasoningContent() != null) {
                                if (reasoning.isEmpty()) {
                                    System.out.println("\n<thinking>");
                                }
                                if (delta.reasoningContent().text() != null) {
                                    System.out.print(delta.reasoningContent().text());
                                    reasoning.append(delta.reasoningContent().text());
                                }
                            } else if (delta.text() != null) {
                                if (text.isEmpty()) {
                                    System.out.println("\n</thinking>\n");
                                }
                                System.out.print(delta.text());
                                text.append(delta.text());
                            }
                            System.out.flush();  // Ensure immediate output of each chunk
                        }).build())
                .onComplete(() -> finalresponse.set(new ReasoningResponse(
                        ReasoningContentBlock.fromReasoningText(t -> t.text(reasoning.toString())),
                        text.toString()
                )))
                .onError(err -> System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage()))
                .build();

        // Step 6: Send the streaming request and process the response
        // - Send the request to the model
        // - Attach the handler to process response chunks as they arrive
        // - Handle any errors during streaming
        try {
            client.converseStream(request, streamHandler).get();
            return finalresponse.get();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
            throw new RuntimeException(e);
        } catch (Exception e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        reasoningStream();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Cohere Command
<a name="cohere_command"></a>

### Converse
<a name="bedrock-runtime_Converse_CohereCommand_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Cohere Command.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

public class Converse {

    public static String converse() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Command R.
        var modelId = "cohere.command-r-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();


        try {
            // Send the message with a basic inference configuration.
            ConverseResponse response = client.converse(request -> request
                    .modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)));

            // Retrieve the generated text from Bedrock's response object.
            var responseText = response.output().message().content().get(0).text();
            System.out.println(responseText);

            return responseText;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        converse();
    }
}
```
Bedrock の Converse API と非同期 Java クライアントを使用して Cohere Command にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Cohere Command
// with the async Java client.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ConverseAsync {

    public static String converseAsync() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Command R.
        var modelId = "cohere.command-r-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Send the message with a basic inference configuration.
        var request = client.converse(params -> params
                .modelId(modelId)
                .messages(message)
                .inferenceConfig(config -> config
                        .maxTokens(512)
                        .temperature(0.5F)
                        .topP(0.9F))
        );

        // Prepare a future object to handle the asynchronous response.
        CompletableFuture<String> future = new CompletableFuture<>();

        // Handle the response or error using the future object.
        request.whenComplete((response, error) -> {
            if (error == null) {
                // Extract the generated text from Bedrock's response object.
                String responseText = response.output().message().content().get(0).text();
                future.complete(responseText);
            } else {
                future.completeExceptionally(error);
            }
        });

        try {
            // Wait for the future object to complete and retrieve the generated text.
            String responseText = future.get();
            System.out.println(responseText);

            return responseText;

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        converseAsync();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_CohereCommand_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Cohere Command
// and print the response stream.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.ExecutionException;

public class ConverseStream {

    public static void main(String[] args) {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Command R.
        var modelId = "cohere.command-r-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Create a handler to extract and print the response text in real-time.
        var responseStreamHandler = ConverseStreamResponseHandler.builder()
                .subscriber(ConverseStreamResponseHandler.Visitor.builder()
                        .onContentBlockDelta(chunk -> {
                            String responseText = chunk.delta().text();
                            System.out.print(responseText);
                        }).build()
                ).onError(err ->
                        System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage())
                ).build();

        try {
            // Send the message with a basic inference configuration and attach the handler.
            client.converseStream(request -> request.modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)
                    ), responseStreamHandler).get();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### InvokeModel: コマンド R および R\$1
<a name="bedrock-runtime_InvokeModel_CohereCommandR_java_2_topic"></a>

次のコード例は、Invoke Model API を使用して Cohere Command R および R\$1 にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Cohere Command R.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

public class Command_R_InvokeModel {

    public static String invokeModel() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Command R.
        var modelId = "cohere.command-r-v1:0";

        // The InvokeModel API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html
        var nativeRequestTemplate = "{ \"message\": \"{{prompt}}\" }";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in the model's native request payload.
        String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt);

        try {
            // Encode and send the request to the Bedrock Runtime.
            var response = client.invokeModel(request -> request
                    .body(SdkBytes.fromUtf8String(nativeRequest))
                    .modelId(modelId)
            );

            // Decode the response body.
            var responseBody = new JSONObject(response.body().asUtf8String());

            // Retrieve the generated text from the model's response.
            var text = new JSONPointer("/text").queryFrom(responseBody).toString();
            System.out.println(text);

            return text;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        invokeModel();
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream: コマンド R および R\$1
<a name="bedrock-runtime_InvokeModelWithResponseStream_CohereCommandR_java_2_topic"></a>

次のコード例は、レスポンスストリームで Invoke Model API を使用して、Cohere Command にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Cohere Command R
// and print the response stream.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;

import java.util.concurrent.ExecutionException;

import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;

public class Command_R_InvokeModelWithResponseStream {

    public static String invokeModelWithResponseStream() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Command R.
        var modelId = "cohere.command-r-v1:0";

        // The InvokeModelWithResponseStream API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html
        var nativeRequestTemplate = "{ \"message\": \"{{prompt}}\" }";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in the model's native request payload.
        String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt);

        // Create a request with the model ID and the model's native request payload.
        var request = InvokeModelWithResponseStreamRequest.builder()
                .body(SdkBytes.fromUtf8String(nativeRequest))
                .modelId(modelId)
                .build();

        // Prepare a buffer to accumulate the generated response text.
        var completeResponseTextBuffer = new StringBuilder();

        // Prepare a handler to extract, accumulate, and print the response text in real-time.
        var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder()
                .subscriber(Visitor.builder().onChunk(chunk -> {
                    // Extract and print the text from the model's native response.
                    var response = new JSONObject(chunk.bytes().asUtf8String());
                    var text = new JSONPointer("/text").queryFrom(response);
                    System.out.print(text);

                    // Append the text to the response text buffer.
                    completeResponseTextBuffer.append(text);
                }).build()).build();

        try {
            // Send the request and wait for the handler to process the response.
            client.invokeModelWithResponseStream(request, responseStreamHandler).get();

            // Return the complete response text.
            return completeResponseTextBuffer.toString();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        invokeModelWithResponseStream();
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Meta Llama
<a name="meta_llama"></a>

### Converse
<a name="bedrock-runtime_Converse_MetaLlama_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Meta Llama.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

public class Converse {

    public static String converse() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Llama 3 8b Instruct.
        var modelId = "meta.llama3-8b-instruct-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();


        try {
            // Send the message with a basic inference configuration.
            ConverseResponse response = client.converse(request -> request
                    .modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)));

            // Retrieve the generated text from Bedrock's response object.
            var responseText = response.output().message().content().get(0).text();
            System.out.println(responseText);

            return responseText;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        converse();
    }
}
```
Bedrock の Converse API と非同期 Java クライアントを使用して Meta Llama にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Meta Llama
// with the async Java client.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ConverseAsync {

    public static String converseAsync() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Llama 3 8b Instruct.
        var modelId = "meta.llama3-8b-instruct-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Send the message with a basic inference configuration.
        var request = client.converse(params -> params
                .modelId(modelId)
                .messages(message)
                .inferenceConfig(config -> config
                        .maxTokens(512)
                        .temperature(0.5F)
                        .topP(0.9F))
        );

        // Prepare a future object to handle the asynchronous response.
        CompletableFuture<String> future = new CompletableFuture<>();

        // Handle the response or error using the future object.
        request.whenComplete((response, error) -> {
            if (error == null) {
                // Extract the generated text from Bedrock's response object.
                String responseText = response.output().message().content().get(0).text();
                future.complete(responseText);
            } else {
                future.completeExceptionally(error);
            }
        });

        try {
            // Wait for the future object to complete and retrieve the generated text.
            String responseText = future.get();
            System.out.println(responseText);

            return responseText;

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        converseAsync();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_MetaLlama_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Meta Llama
// and print the response stream.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.ExecutionException;

public class ConverseStream {

    public static void main(String[] args) {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Llama 3 8b Instruct.
        var modelId = "meta.llama3-8b-instruct-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Create a handler to extract and print the response text in real-time.
        var responseStreamHandler = ConverseStreamResponseHandler.builder()
                .subscriber(ConverseStreamResponseHandler.Visitor.builder()
                        .onContentBlockDelta(chunk -> {
                            String responseText = chunk.delta().text();
                            System.out.print(responseText);
                        }).build()
                ).onError(err ->
                        System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage())
                ).build();

        try {
            // Send the message with a basic inference configuration and attach the handler.
            client.converseStream(request -> request
                    .modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)
                    ), responseStreamHandler).get();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MetaLlama3_java_2_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Meta Llama 3.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

public class Llama3_InvokeModel {

    public static String invokeModel() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_WEST_2)
                .build();

        // Set the model ID, e.g., Llama 3 70b Instruct.
        var modelId = "meta.llama3-70b-instruct-v1:0";

        // The InvokeModel API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html
        var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in Llama 3's instruction format.
        var instruction = (
                "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\\n" +
                "{{prompt}} <|eot_id|>\\n" +
                "<|start_header_id|>assistant<|end_header_id|>\\n"
        ).replace("{{prompt}}", prompt);

        // Embed the instruction in the the native request payload.
        var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction);

        try {
            // Encode and send the request to the Bedrock Runtime.
            var response = client.invokeModel(request -> request
                    .body(SdkBytes.fromUtf8String(nativeRequest))
                    .modelId(modelId)
            );

            // Decode the response body.
            var responseBody = new JSONObject(response.body().asUtf8String());

            // Retrieve the generated text from the model's response.
            var text = new JSONPointer("/generation").queryFrom(responseBody).toString();
            System.out.println(text);

            return text;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        invokeModel();
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_MetaLlama3_java_2_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Meta Llama 3
// and print the response stream.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;

import java.util.concurrent.ExecutionException;

import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;

public class Llama3_InvokeModelWithResponseStream {

    public static String invokeModelWithResponseStream() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_WEST_2)
                .build();

        // Set the model ID, e.g., Llama 3 70b Instruct.
        var modelId = "meta.llama3-70b-instruct-v1:0";

        // The InvokeModelWithResponseStream API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-meta.html
        var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in Llama 3's instruction format.
        var instruction = (
                "<|begin_of_text|><|start_header_id|>user<|end_header_id|>\\n" +
                "{{prompt}} <|eot_id|>\\n" +
                "<|start_header_id|>assistant<|end_header_id|>\\n"
        ).replace("{{prompt}}", prompt);

        // Embed the instruction in the the native request payload.
        var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction);

        // Create a request with the model ID and the model's native request payload.
        var request = InvokeModelWithResponseStreamRequest.builder()
                .body(SdkBytes.fromUtf8String(nativeRequest))
                .modelId(modelId)
                .build();

        // Prepare a buffer to accumulate the generated response text.
        var completeResponseTextBuffer = new StringBuilder();

        // Prepare a handler to extract, accumulate, and print the response text in real-time.
        var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder()
                .subscriber(Visitor.builder().onChunk(chunk -> {
                    // Extract and print the text from the model's native response.
                    var response = new JSONObject(chunk.bytes().asUtf8String());
                    var text = new JSONPointer("/generation").queryFrom(response);
                    System.out.print(text);

                    // Append the text to the response text buffer.
                    completeResponseTextBuffer.append(text);
                }).build()).build();

        try {
            // Send the request and wait for the handler to process the response.
            client.invokeModelWithResponseStream(request, responseStreamHandler).get();

            // Return the complete response text.
            return completeResponseTextBuffer.toString();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        invokeModelWithResponseStream();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

## Mistral AI
<a name="mistral_ai"></a>

### Converse
<a name="bedrock-runtime_Converse_Mistral_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Mistral.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseResponse;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

public class Converse {

    public static String converse() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Mistral Large.
        var modelId = "mistral.mistral-large-2402-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();


        try {
            // Send the message with a basic inference configuration.
            ConverseResponse response = client.converse(request -> request
                    .modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)));

            // Retrieve the generated text from Bedrock's response object.
            var responseText = response.output().message().content().get(0).text();
            System.out.println(responseText);

            return responseText;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) {
        converse();
    }
}
```
Bedrock の Converse API と非同期 Java クライアントを使用して Mistral にテキストメッセージを送信します。  

```
// Use the Converse API to send a text message to Mistral
// with the async Java client.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class ConverseAsync {

    public static String converseAsync() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Mistral Large.
        var modelId = "mistral.mistral-large-2402-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Send the message with a basic inference configuration.
        var request = client.converse(params -> params
                .modelId(modelId)
                .messages(message)
                .inferenceConfig(config -> config
                        .maxTokens(512)
                        .temperature(0.5F)
                        .topP(0.9F))
        );

        // Prepare a future object to handle the asynchronous response.
        CompletableFuture<String> future = new CompletableFuture<>();

        // Handle the response or error using the future object.
        request.whenComplete((response, error) -> {
            if (error == null) {
                // Extract the generated text from Bedrock's response object.
                String responseText = response.output().message().content().get(0).text();
                future.complete(responseText);
            } else {
                future.completeExceptionally(error);
            }
        });

        try {
            // Wait for the future object to complete and retrieve the generated text.
            String responseText = future.get();
            System.out.println(responseText);

            return responseText;

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        converseAsync();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_Mistral_java_2_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the Converse API to send a text message to Mistral
// and print the response stream.

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.ContentBlock;
import software.amazon.awssdk.services.bedrockruntime.model.ConversationRole;
import software.amazon.awssdk.services.bedrockruntime.model.ConverseStreamResponseHandler;
import software.amazon.awssdk.services.bedrockruntime.model.Message;

import java.util.concurrent.ExecutionException;

public class ConverseStream {

    public static void main(String[] args) {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Mistral Large.
        var modelId = "mistral.mistral-large-2402-v1:0";

        // Create the input text and embed it in a message object with the user role.
        var inputText = "Describe the purpose of a 'hello world' program in one line.";
        var message = Message.builder()
                .content(ContentBlock.fromText(inputText))
                .role(ConversationRole.USER)
                .build();

        // Create a handler to extract and print the response text in real-time.
        var responseStreamHandler = ConverseStreamResponseHandler.builder()
                .subscriber(ConverseStreamResponseHandler.Visitor.builder()
                        .onContentBlockDelta(chunk -> {
                            String responseText = chunk.delta().text();
                            System.out.print(responseText);
                        }).build()
                ).onError(err ->
                        System.err.printf("Can't invoke '%s': %s", modelId, err.getMessage())
                ).build();

        try {
            // Send the message with a basic inference configuration and attach the handler.
            client.converseStream(request -> request.modelId(modelId)
                    .messages(message)
                    .inferenceConfig(config -> config
                            .maxTokens(512)
                            .temperature(0.5F)
                            .topP(0.9F)
                    ), responseStreamHandler).get();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MistralAi_java_2_topic"></a>

次のコード例は、Invoke Model API を使用して Mistral モデルにテキストメッセージを送信する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
// Use the native inference API to send a text message to Mistral.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

public class InvokeModel {

    public static String invokeModel() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Mistral Large.
        var modelId = "mistral.mistral-large-2402-v1:0";

        // The InvokeModel API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-mistral-text-completion.html
        var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in Mistral's instruction format.
        var instruction = "<s>[INST] {{prompt}} [/INST]\\n".replace("{{prompt}}", prompt);

        // Embed the instruction in the the native request payload.
        var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction);

        try {
            // Encode and send the request to the Bedrock Runtime.
            var response = client.invokeModel(request -> request
                    .body(SdkBytes.fromUtf8String(nativeRequest))
                    .modelId(modelId)
            );

            // Decode the response body.
            var responseBody = new JSONObject(response.body().asUtf8String());

            // Retrieve the generated text from the model's response.
            var text = new JSONPointer("/outputs/0/text").queryFrom(responseBody).toString();
            System.out.println(text);

            return text;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        invokeModel();
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_MistralAi_java_2_topic"></a>

次のコード例は、Invoke Model API を使用して Mistral AI モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// Use the native inference API to send a text message to Mistral
// and print the response stream.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeAsyncClient;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamRequest;
import software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler;

import java.util.concurrent.ExecutionException;

import static software.amazon.awssdk.services.bedrockruntime.model.InvokeModelWithResponseStreamResponseHandler.Visitor;

public class InvokeModelWithResponseStream {

    public static String invokeModelWithResponseStream() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeAsyncClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Mistral Large.
        var modelId = "mistral.mistral-large-2402-v1:0";

        // The InvokeModelWithResponseStream API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-mistral-text-completion.html
        var nativeRequestTemplate = "{ \"prompt\": \"{{instruction}}\" }";

        // Define the prompt for the model.
        var prompt = "Describe the purpose of a 'hello world' program in one line.";

        // Embed the prompt in Mistral's instruction format.
        var instruction = "<s>[INST] {{prompt}} [/INST]\\n".replace("{{prompt}}", prompt);

        // Embed the instruction in the the native request payload.
        var nativeRequest = nativeRequestTemplate.replace("{{instruction}}", instruction);

        // Create a request with the model ID and the model's native request payload.
        var request = InvokeModelWithResponseStreamRequest.builder()
                .body(SdkBytes.fromUtf8String(nativeRequest))
                .modelId(modelId)
                .build();

        // Prepare a buffer to accumulate the generated response text.
        var completeResponseTextBuffer = new StringBuilder();

        // Prepare a handler to extract, accumulate, and print the response text in real-time.
        var responseStreamHandler = InvokeModelWithResponseStreamResponseHandler.builder()
                .subscriber(Visitor.builder().onChunk(chunk -> {
                    // Extract and print the text from the model's native response.
                    var response = new JSONObject(chunk.bytes().asUtf8String());
                    var text = new JSONPointer("/outputs/0/text").queryFrom(response);
                    System.out.print(text);

                    // Append the text to the response text buffer.
                    completeResponseTextBuffer.append(text);
                }).build()).build();

        try {
            // Send the request and wait for the handler to process the response.
            client.invokeModelWithResponseStream(request, responseStreamHandler).get();

            // Return the complete response text.
            return completeResponseTextBuffer.toString();

        } catch (ExecutionException | InterruptedException e) {
            System.err.printf("Can't invoke '%s': %s", modelId, e.getCause().getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        invokeModelWithResponseStream();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

## Stable Diffusion
<a name="stable_diffusion"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_StableDiffusion_java_2_topic"></a>

次のコード例は、Amazon Bedrock で Stability.ai Stable Diffusion XL を呼び出して画像を生成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Stable Diffusion で画像を作成します。  

```
// Create an image with Stable Diffusion.

import org.json.JSONObject;
import org.json.JSONPointer;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient;

import java.math.BigInteger;
import java.security.SecureRandom;

import static com.example.bedrockruntime.libs.ImageTools.displayImage;

public class InvokeModel {

    public static String invokeModel() {

        // Create a Bedrock Runtime client in the AWS Region you want to use.
        // Replace the DefaultCredentialsProvider with your preferred credentials provider.
        var client = BedrockRuntimeClient.builder()
                .credentialsProvider(DefaultCredentialsProvider.create())
                .region(Region.US_EAST_1)
                .build();

        // Set the model ID, e.g., Stable Diffusion XL v1.
        var modelId = "stability.stable-diffusion-xl-v1";

        // The InvokeModel API uses the model's native payload.
        // Learn more about the available inference parameters and response fields at:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-diffusion-1-0-text-image.html
        var nativeRequestTemplate = """
                {
                    "text_prompts": [{ "text": "{{prompt}}" }],
                    "style_preset": "{{style}}",
                    "seed": {{seed}}
                }""";

        // Define the prompt for the image generation.
        var prompt = "A stylized picture of a cute old steampunk robot";

        // Get a random 32-bit seed for the image generation (max. 4,294,967,295).
        var seed = new BigInteger(31, new SecureRandom());

        // Choose a style preset.
        var style = "cinematic";

        // Embed the prompt, seed, and style in the model's native request payload.
        String nativeRequest = nativeRequestTemplate
                .replace("{{prompt}}", prompt)
                .replace("{{seed}}", seed.toString())
                .replace("{{style}}", style);

        try {
            // Encode and send the request to the Bedrock Runtime.
            var response = client.invokeModel(request -> request
                    .body(SdkBytes.fromUtf8String(nativeRequest))
                    .modelId(modelId)
            );

            // Decode the response body.
            var responseBody = new JSONObject(response.body().asUtf8String());

            // Retrieve the generated image data from the model's response.
            var base64ImageData = new JSONPointer("/artifacts/0/base64")
                    .queryFrom(responseBody)
                    .toString();

            return base64ImageData;

        } catch (SdkClientException e) {
            System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println("Generating image. This may take a few seconds...");

        String base64ImageData = invokeModel();

        displayImage(base64ImageData);
    }


}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

# SDK for Java 2.x を使用した CloudFront の例
<a name="java_2_cloudfront_code_examples"></a>

次のコード例は、CloudFront AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateDistribution`
<a name="cloudfront_CreateDistribution_java_2_topic"></a>

次のコード例は、`CreateDistribution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。
次の例では、Amazon Simple Storage Service (Amazon S3) バケットをコンテンツオリジンとして使用しています。  
コードは、ディストリビューションの作成後に [CloudFrontWaiter](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudfront/waiters/CloudFrontWaiter.html) を作成し、ディストリビューションがデプロイされるまで待ってからディストリビューションを返します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.internal.waiters.ResponseOrException;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse;
import software.amazon.awssdk.services.cloudfront.model.Distribution;
import software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;
import software.amazon.awssdk.services.cloudfront.model.ItemSelection;
import software.amazon.awssdk.services.cloudfront.model.Method;
import software.amazon.awssdk.services.cloudfront.model.ViewerProtocolPolicy;
import software.amazon.awssdk.services.cloudfront.waiters.CloudFrontWaiter;
import software.amazon.awssdk.services.s3.S3Client;

import java.time.Instant;

public class CreateDistribution {

        private static final Logger logger = LoggerFactory.getLogger(CreateDistribution.class);

        public static Distribution createDistribution(CloudFrontClient cloudFrontClient, S3Client s3Client,
                        final String bucketName, final String keyGroupId, final String originAccessControlId) {

                final String region = s3Client.headBucket(b -> b.bucket(bucketName)).sdkHttpResponse().headers()
                                .get("x-amz-bucket-region").get(0);
                final String originDomain = bucketName + ".s3." + region + ".amazonaws.com";
                String originId = originDomain; // Use the originDomain value for the originId.

                // The service API requires some deprecated methods, such as
                // DefaultCacheBehavior.Builder#minTTL and #forwardedValue.
                CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder
                                .distributionConfig(b1 -> b1
                                                .origins(b2 -> b2
                                                                .quantity(1)
                                                                .items(b3 -> b3
                                                                                .domainName(originDomain)
                                                                                .id(originId)
                                                                                .s3OriginConfig(builder4 -> builder4
                                                                                                .originAccessIdentity(
                                                                                                                ""))
                                                                                .originAccessControlId(
                                                                                                originAccessControlId)))
                                                .defaultCacheBehavior(b2 -> b2
                                                                .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL)
                                                                .targetOriginId(originId)
                                                                .minTTL(200L)
                                                                .forwardedValues(b5 -> b5
                                                                                .cookies(cp -> cp
                                                                                                .forward(ItemSelection.NONE))
                                                                                .queryString(true))
                                                                .trustedKeyGroups(b3 -> b3
                                                                                .quantity(1)
                                                                                .items(keyGroupId)
                                                                                .enabled(true))
                                                                .allowedMethods(b4 -> b4
                                                                                .quantity(2)
                                                                                .items(Method.HEAD, Method.GET)
                                                                                .cachedMethods(b5 -> b5
                                                                                                .quantity(2)
                                                                                                .items(Method.HEAD,
                                                                                                                Method.GET))))
                                                .cacheBehaviors(b -> b
                                                                .quantity(1)
                                                                .items(b2 -> b2
                                                                                .pathPattern("/index.html")
                                                                                .viewerProtocolPolicy(
                                                                                                ViewerProtocolPolicy.ALLOW_ALL)
                                                                                .targetOriginId(originId)
                                                                                .trustedKeyGroups(b3 -> b3
                                                                                                .quantity(1)
                                                                                                .items(keyGroupId)
                                                                                                .enabled(true))
                                                                                .minTTL(200L)
                                                                                .forwardedValues(b4 -> b4
                                                                                                .cookies(cp -> cp
                                                                                                                .forward(ItemSelection.NONE))
                                                                                                .queryString(true))
                                                                                .allowedMethods(b5 -> b5.quantity(2)
                                                                                                .items(Method.HEAD,
                                                                                                                Method.GET)
                                                                                                .cachedMethods(b6 -> b6
                                                                                                                .quantity(2)
                                                                                                                .items(Method.HEAD,
                                                                                                                                Method.GET)))))
                                                .enabled(true)
                                                .comment("Distribution built with java")
                                                .callerReference(Instant.now().toString())));

                final Distribution distribution = createDistResponse.distribution();
                logger.info("Distribution created. DomainName: [{}]  Id: [{}]", distribution.domainName(),
                                distribution.id());
                logger.info("Waiting for distribution to be deployed ...");
                try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) {
                        ResponseOrException<GetDistributionResponse> responseOrException = cfWaiter
                                        .waitUntilDistributionDeployed(builder -> builder.id(distribution.id()))
                                        .matched();
                        responseOrException.response()
                                        .orElseThrow(() -> new RuntimeException("Distribution not created"));
                        logger.info("Distribution deployed. DomainName: [{}]  Id: [{}]", distribution.domainName(),
                                        distribution.id());
                }
                return distribution;
        }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDistribution](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/CreateDistribution)」を参照してください。

### `CreateFunction`
<a name="cloudfront_CreateFunction_java_2_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CloudFrontException;
import software.amazon.awssdk.services.cloudfront.model.CreateFunctionRequest;
import software.amazon.awssdk.services.cloudfront.model.CreateFunctionResponse;
import software.amazon.awssdk.services.cloudfront.model.FunctionConfig;
import software.amazon.awssdk.services.cloudfront.model.FunctionRuntime;
import java.io.InputStream;

/**
 * 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 CreateFunction {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <functionName> <filePath>

                Where:
                    functionName - The name of the function to create.\s
                    filePath - The path to a file that contains the application logic for the function.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String functionName = args[0];
        String filePath = args[1];
        CloudFrontClient cloudFrontClient = CloudFrontClient.builder()
                .region(Region.AWS_GLOBAL)
                .build();

        String funArn = createNewFunction(cloudFrontClient, functionName, filePath);
        System.out.println("The function ARN is " + funArn);
        cloudFrontClient.close();
    }

    public static String createNewFunction(CloudFrontClient cloudFrontClient, String functionName, String filePath) {
        try {
            InputStream fileIs = CreateFunction.class.getClassLoader().getResourceAsStream(filePath);
            SdkBytes functionCode = SdkBytes.fromInputStream(fileIs);

            FunctionConfig config = FunctionConfig.builder()
                    .comment("Created by using the CloudFront Java API")
                    .runtime(FunctionRuntime.CLOUDFRONT_JS_1_0)
                    .build();

            CreateFunctionRequest functionRequest = CreateFunctionRequest.builder()
                    .name(functionName)
                    .functionCode(functionCode)
                    .functionConfig(config)
                    .build();

            CreateFunctionResponse response = cloudFrontClient.createFunction(functionRequest);
            return response.functionSummary().functionMetadata().functionARN();

        } catch (CloudFrontException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CreateFunction](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/CreateFunction)」を参照してください。**

### `CreateKeyGroup`
<a name="cloudfront_CreateKeyGroup_java_2_topic"></a>

次のコード例は、`CreateKeyGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。
キーグループには、署名付き URL または Cookie の検証に使用されるパブリックキーが少なくとも 1 つ必要です。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;

import java.util.UUID;

public class CreateKeyGroup {
    private static final Logger logger = LoggerFactory.getLogger(CreateKeyGroup.class);

    public static String createKeyGroup(CloudFrontClient cloudFrontClient, String publicKeyId) {
        String keyGroupId = cloudFrontClient.createKeyGroup(b -> b.keyGroupConfig(c -> c
                .items(publicKeyId)
                .name("JavaKeyGroup" + UUID.randomUUID())))
                .keyGroup().id();
        logger.info("KeyGroup created with ID: [{}]", keyGroupId);
        return keyGroupId;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateKeyGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/CreateKeyGroup)」を参照してください。

### `CreatePublicKey`
<a name="cloudfront_CreatePublicKey_java_2_topic"></a>

次のコード例は、`CreatePublicKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。
次のコード例では、パブリックキーを読み込んで Amazon CloudFront にアップロードします。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreatePublicKeyResponse;
import software.amazon.awssdk.utils.IoUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class CreatePublicKey {
    private static final Logger logger = LoggerFactory.getLogger(CreatePublicKey.class);

    public static String createPublicKey(CloudFrontClient cloudFrontClient, String publicKeyFileName) {
        try (InputStream is = CreatePublicKey.class.getClassLoader().getResourceAsStream(publicKeyFileName)) {
            String publicKeyString = IoUtils.toUtf8String(is);
            CreatePublicKeyResponse createPublicKeyResponse = cloudFrontClient
                    .createPublicKey(b -> b.publicKeyConfig(c -> c
                            .name("JavaCreatedPublicKey" + UUID.randomUUID())
                            .encodedKey(publicKeyString)
                            .callerReference(UUID.randomUUID().toString())));
            String createdPublicKeyId = createPublicKeyResponse.publicKey().id();
            logger.info("Public key created with id: [{}]", createdPublicKeyId);
            return createdPublicKeyId;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreatePublicKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/CreatePublicKey)」を参照してください。

### `DeleteDistribution`
<a name="cloudfront_DeleteDistribution_java_2_topic"></a>

次のコード例は、`DeleteDistribution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。
次のコード例では、配信を*無効状態*に更新し、ウェイターを使用して変更がデプロイされるのを待ってから、ディストリビューションを削除します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.internal.waiters.ResponseOrException;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.DeleteDistributionResponse;
import software.amazon.awssdk.services.cloudfront.model.DistributionConfig;
import software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;
import software.amazon.awssdk.services.cloudfront.waiters.CloudFrontWaiter;

public class DeleteDistribution {
        private static final Logger logger = LoggerFactory.getLogger(DeleteDistribution.class);

        public static void deleteDistribution(final CloudFrontClient cloudFrontClient, final String distributionId) {
                // First, disable the distribution by updating it.
                GetDistributionResponse response = cloudFrontClient.getDistribution(b -> b
                                .id(distributionId));
                String etag = response.eTag();
                DistributionConfig distConfig = response.distribution().distributionConfig();

                cloudFrontClient.updateDistribution(builder -> builder
                                .id(distributionId)
                                .distributionConfig(builder1 -> builder1
                                                .cacheBehaviors(distConfig.cacheBehaviors())
                                                .defaultCacheBehavior(distConfig.defaultCacheBehavior())
                                                .enabled(false)
                                                .origins(distConfig.origins())
                                                .comment(distConfig.comment())
                                                .callerReference(distConfig.callerReference())
                                                .defaultCacheBehavior(distConfig.defaultCacheBehavior())
                                                .priceClass(distConfig.priceClass())
                                                .aliases(distConfig.aliases())
                                                .logging(distConfig.logging())
                                                .defaultRootObject(distConfig.defaultRootObject())
                                                .customErrorResponses(distConfig.customErrorResponses())
                                                .httpVersion(distConfig.httpVersion())
                                                .isIPV6Enabled(distConfig.isIPV6Enabled())
                                                .restrictions(distConfig.restrictions())
                                                .viewerCertificate(distConfig.viewerCertificate())
                                                .webACLId(distConfig.webACLId())
                                                .originGroups(distConfig.originGroups()))
                                .ifMatch(etag));

                logger.info("Distribution [{}] is DISABLED, waiting for deployment before deleting ...",
                                distributionId);
                GetDistributionResponse distributionResponse;
                try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) {
                        ResponseOrException<GetDistributionResponse> responseOrException = cfWaiter
                                        .waitUntilDistributionDeployed(builder -> builder.id(distributionId)).matched();
                        distributionResponse = responseOrException.response()
                                        .orElseThrow(() -> new RuntimeException("Could not disable distribution"));
                }

                DeleteDistributionResponse deleteDistributionResponse = cloudFrontClient
                                .deleteDistribution(builder -> builder
                                                .id(distributionId)
                                                .ifMatch(distributionResponse.eTag()));
                if (deleteDistributionResponse.sdkHttpResponse().isSuccessful()) {
                        logger.info("Distribution [{}] DELETED", distributionId);
                }
        }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[DeleteDistribution](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/DeleteDistribution)」を参照してください。**

### `UpdateDistribution`
<a name="cloudfront_UpdateDistribution_java_2_topic"></a>

次のコード例は、`UpdateDistribution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.GetDistributionRequest;
import software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;
import software.amazon.awssdk.services.cloudfront.model.Distribution;
import software.amazon.awssdk.services.cloudfront.model.DistributionConfig;
import software.amazon.awssdk.services.cloudfront.model.UpdateDistributionRequest;
import software.amazon.awssdk.services.cloudfront.model.CloudFrontException;

/**
 * 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 ModifyDistribution {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <id>\s

                Where:
                    id - the id value of the distribution.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String id = args[0];
        CloudFrontClient cloudFrontClient = CloudFrontClient.builder()
                .region(Region.AWS_GLOBAL)
                .build();

        modDistribution(cloudFrontClient, id);
        cloudFrontClient.close();
    }

    public static void modDistribution(CloudFrontClient cloudFrontClient, String idVal) {
        try {
            // Get the Distribution to modify.
            GetDistributionRequest disRequest = GetDistributionRequest.builder()
                    .id(idVal)
                    .build();

            GetDistributionResponse response = cloudFrontClient.getDistribution(disRequest);
            Distribution disObject = response.distribution();
            DistributionConfig config = disObject.distributionConfig();

            // Create a new DistributionConfig object and add new values to comment and
            // aliases
            DistributionConfig config1 = DistributionConfig.builder()
                    .aliases(config.aliases()) // You can pass in new values here
                    .comment("New Comment")
                    .cacheBehaviors(config.cacheBehaviors())
                    .priceClass(config.priceClass())
                    .defaultCacheBehavior(config.defaultCacheBehavior())
                    .enabled(config.enabled())
                    .callerReference(config.callerReference())
                    .logging(config.logging())
                    .originGroups(config.originGroups())
                    .origins(config.origins())
                    .restrictions(config.restrictions())
                    .defaultRootObject(config.defaultRootObject())
                    .webACLId(config.webACLId())
                    .httpVersion(config.httpVersion())
                    .viewerCertificate(config.viewerCertificate())
                    .customErrorResponses(config.customErrorResponses())
                    .build();

            UpdateDistributionRequest updateDistributionRequest = UpdateDistributionRequest.builder()
                    .distributionConfig(config1)
                    .id(disObject.id())
                    .ifMatch(response.eTag())
                    .build();

            cloudFrontClient.updateDistribution(updateDistributionRequest);

        } catch (CloudFrontException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateDistribution](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/UpdateDistribution)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### マルチテナントディストリビューションとディストリビューションテナントを作成する
<a name="cloudfront_CreateSaasResources_java_2_topic"></a>

次のコード例は、さまざまな設定でマルチテナントディストリビューションおよびディストリビューションテナントを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。
次の例は、パラメータとワイルドカード証明書を使用してマルチテナントディストリビューションを作成する方法を示しています。  

```
import software.amazon.awssdk.core.internal.waiters.ResponseOrException;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.ConnectionMode;
import software.amazon.awssdk.services.cloudfront.model.CreateDistributionResponse;
import software.amazon.awssdk.services.cloudfront.model.Distribution;
import software.amazon.awssdk.services.cloudfront.model.GetDistributionResponse;
import software.amazon.awssdk.services.cloudfront.model.HttpVersion;
import software.amazon.awssdk.services.cloudfront.model.Method;
import software.amazon.awssdk.services.cloudfront.model.SSLSupportMethod;
import software.amazon.awssdk.services.cloudfront.model.ViewerProtocolPolicy;
import software.amazon.awssdk.services.cloudfront.waiters.CloudFrontWaiter;
import software.amazon.awssdk.services.s3.S3Client;

import java.time.Instant;

public class CreateMultiTenantDistribution {
    public static Distribution CreateMultiTenantDistributionWithCert(CloudFrontClient cloudFrontClient,
                                                                     S3Client s3Client,
                                                                     final String bucketName,
                                                                     final String certificateArn) {
        // fetch the origin info if necessary
        final String region = s3Client.headBucket(b -> b.bucket(bucketName)).sdkHttpResponse().headers()
                .get("x-amz-bucket-region").get(0);
        final String originDomain = bucketName + ".s3." + region + ".amazonaws.com";
        String originId = originDomain; // Use the originDomain value for the originId.

        CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder
                .distributionConfig(b1 -> b1
                        .httpVersion(HttpVersion.HTTP2)
                        .enabled(true)
                        .comment("Template Distribution with cert built with java")
                        .connectionMode(ConnectionMode.TENANT_ONLY)
                        .callerReference(Instant.now().toString())
                        .viewerCertificate(certBuilder -> certBuilder
                                .acmCertificateArn(certificateArn)
                                .sslSupportMethod(SSLSupportMethod.SNI_ONLY))
                        .origins(b2 -> b2
                                .quantity(1)
                                .items(b3 -> b3
                                        .domainName(originDomain)
                                        .id(originId)
                                        .originPath("/{{tenantName}}")
                                        .s3OriginConfig(builder4 -> builder4
                                                .originAccessIdentity(
                                                        ""))))
                        .tenantConfig(b5 -> b5
                                .parameterDefinitions(b6 -> b6
                                        .name("tenantName")
                                        .definition(b7 -> b7
                                                .stringSchema(b8 -> b8
                                                        .comment("tenantName value")
                                                        .defaultValue("root")
                                                        .required(false)))))
                        .defaultCacheBehavior(b2 -> b2
                                .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL)
                                .targetOriginId(originId)
                                .cachePolicyId("658327ea-f89d-4fab-a63d-7e88639e58f6") // CachingOptimized Policy
                                .allowedMethods(b4 -> b4
                                        .quantity(2)
                                        .items(Method.HEAD, Method.GET)))
                ));

        final Distribution distribution = createDistResponse.distribution();
        try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) {
            ResponseOrException<GetDistributionResponse> responseOrException = cfWaiter
                    .waitUntilDistributionDeployed(builder -> builder.id(distribution.id()))
                    .matched();
            responseOrException.response()
                    .orElseThrow(() -> new RuntimeException("Distribution not created"));
        }
        return distribution;
    }

    public static Distribution CreateMultiTenantDistributionNoCert(CloudFrontClient cloudFrontClient,
                                                             S3Client s3Client,
                                                             final String bucketName) {
        // fetch the origin info if necessary
        final String region = s3Client.headBucket(b -> b.bucket(bucketName)).sdkHttpResponse().headers()
                .get("x-amz-bucket-region").get(0);
        final String originDomain = bucketName + ".s3." + region + ".amazonaws.com";
        String originId = originDomain; // Use the originDomain value for the originId.

        CreateDistributionResponse createDistResponse = cloudFrontClient.createDistribution(builder -> builder
                .distributionConfig(b1 -> b1
                        .httpVersion(HttpVersion.HTTP2)
                        .enabled(true)
                        .comment("Template Distribution with cert built with java")
                        .connectionMode(ConnectionMode.TENANT_ONLY)
                        .callerReference(Instant.now().toString())
                        .origins(b2 -> b2
                                .quantity(1)
                                .items(b3 -> b3
                                        .domainName(originDomain)
                                        .id(originId)
                                        .originPath("/{{tenantName}}")
                                        .s3OriginConfig(builder4 -> builder4
                                                .originAccessIdentity(
                                                        ""))))
                        .tenantConfig(b5 -> b5
                                .parameterDefinitions(b6 -> b6
                                        .name("tenantName")
                                        .definition(b7 -> b7
                                                .stringSchema(b8 -> b8
                                                        .comment("tenantName value")
                                                        .defaultValue("root")
                                                        .required(false)))))
                        .defaultCacheBehavior(b2 -> b2
                                .viewerProtocolPolicy(ViewerProtocolPolicy.ALLOW_ALL)
                                .targetOriginId(originId)
                                .cachePolicyId("658327ea-f89d-4fab-a63d-7e88639e58f6") // CachingOptimized Policy
                                .allowedMethods(b4 -> b4
                                        .quantity(2)
                                        .items(Method.HEAD, Method.GET)))
                ));

        final Distribution distribution = createDistResponse.distribution();
        try (CloudFrontWaiter cfWaiter = CloudFrontWaiter.builder().client(cloudFrontClient).build()) {
            ResponseOrException<GetDistributionResponse> responseOrException = cfWaiter
                    .waitUntilDistributionDeployed(builder -> builder.id(distribution.id()))
                    .matched();
            responseOrException.response()
                    .orElseThrow(() -> new RuntimeException("Distribution not created"));
        }
        return distribution;
    }
}
```
次の例は、上記で宣言したパラメータの使用など、そのテンプレートに関連付けられたディストリビューションテナントを作成する方法を示しています。ドメインは既に親テンプレートでカバーされているため、ここで証明書情報を追加する必要がないことに注意してください。  

```
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse;
import software.amazon.awssdk.services.cloudfront.model.DistributionTenant;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.RRType;

import java.time.Instant;

public class CreateDistributionTenant {

    public static DistributionTenant createDistributionTenantNoCert(CloudFrontClient cloudFrontClient,
                                                                    Route53Client route53Client,
                                                                    String distributionId,
                                                                    String domain,
                                                                    String hostedZoneId) {
        CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder
                .distributionId(distributionId)
                .domains(b1 -> b1
                        .domain(domain))
                .parameters(b2 -> b2
                        .name("tenantName")
                        .value("myTenant"))
                .enabled(false)
                .name("no-cert-tenant")
        );

        final DistributionTenant distributionTenant = createResponse.distributionTenant();

        // Then update the Route53 hosted zone to point your domain at the distribution tenant
        // We fetch the RoutingEndpoint to point to via the default connection group that was created for your tenant
        final GetConnectionGroupResponse fetchedConnectionGroup = cloudFrontClient.getConnectionGroup(builder -> builder
                .identifier(distributionTenant.connectionGroupId()));

        route53Client.changeResourceRecordSets(builder -> builder
                .hostedZoneId(hostedZoneId)
                .changeBatch(b1 -> b1
                        .comment("ChangeBatch comment")
                        .changes(b2 -> b2
                                .resourceRecordSet(b3 -> b3
                                        .name(domain)
                                        .type("CNAME")
                                        .ttl(300L)
                                        .resourceRecords(b4 -> b4
                                                .value(fetchedConnectionGroup.connectionGroup().routingEndpoint())))
                                .action("CREATE"))
                ));
        return distributionTenant;
    }

}
```
ビューワーの証明書が親テンプレートから省略された場合は、代わりにそれに関連付けられたテナント (複数可) に証明書情報を追加する必要があります。次の例は、テナントの要なドメインをカバーする ACM 証明書 ARN を使用してこれを行う方法を示しています。  

```
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse;
import software.amazon.awssdk.services.cloudfront.model.DistributionTenant;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.RRType;

import java.time.Instant;

public class CreateDistributionTenant {

    public static DistributionTenant createDistributionTenantWithCert(CloudFrontClient cloudFrontClient,
                                                                      Route53Client route53Client,
                                                                      String distributionId,
                                                                      String domain,
                                                                      String hostedZoneId,
                                                                      String certificateArn) {
        CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder
                .distributionId(distributionId)
                .domains(b1 -> b1
                        .domain(domain))
                .enabled(false)
                .name("tenant-with-cert")
                .parameters(b2 -> b2
                        .name("tenantName")
                        .value("myTenant"))
                .customizations(b3 -> b3
                        .certificate(b4 -> b4
                                .arn(certificateArn))) // NOTE: Cert must be in Us-East-1 and cover the domain provided in this request

        );

        final DistributionTenant distributionTenant = createResponse.distributionTenant();

        // Then update the Route53 hosted zone to point your domain at the distribution tenant
        // We fetch the RoutingEndpoint to point to via the default connection group that was created for your tenant
        final GetConnectionGroupResponse fetchedConnectionGroup = cloudFrontClient.getConnectionGroup(builder -> builder
                .identifier(distributionTenant.connectionGroupId()));

        route53Client.changeResourceRecordSets(builder -> builder
                .hostedZoneId(hostedZoneId)
                .changeBatch(b1 -> b1
                        .comment("ChangeBatch comment")
                        .changes(b2 -> b2
                                .resourceRecordSet(b3 -> b3
                                        .name(domain)
                                        .type("CNAME")
                                        .ttl(300L)
                                        .resourceRecords(b4 -> b4
                                                .value(fetchedConnectionGroup.connectionGroup().routingEndpoint())))
                                .action("CREATE"))
                ));
        return distributionTenant;
    }

}
```
次の例は、CloudFront がホストするマネージド証明書リクエストでこれを行う方法を示しています。これは、ドメインへのトラフィックがまだない場合に最適です。この場合、RoutingEndpoint を生成する ConnectionGroup を作成します。次に、その RoutingEndpoint を使用して、ドメインの所有権を検証し、CloudFront を指す DNS レコードを作成します。その後、CloudFront はトークンを自動的に提供してドメインの所有権を検証し、マネージド証明書を作成します。  

```
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse;
import software.amazon.awssdk.services.cloudfront.model.DistributionTenant;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.RRType;

import java.time.Instant;

public class CreateDistributionTenant {

    public static DistributionTenant createDistributionTenantCfHosted(CloudFrontClient cloudFrontClient,
                                                                      Route53Client route53Client,
                                                                      String distributionId,
                                                                      String domain,
                                                                      String hostedZoneId) throws InterruptedException {
        CreateConnectionGroupResponse createConnectionGroupResponse = cloudFrontClient.createConnectionGroup(builder -> builder
                .ipv6Enabled(true)
                .name("cf-hosted-connection-group")
                .enabled(true));

        route53Client.changeResourceRecordSets(builder -> builder
                .hostedZoneId(hostedZoneId)
                .changeBatch(b1 -> b1
                        .comment("cf-hosted domain validation record")
                        .changes(b2 -> b2
                                .resourceRecordSet(b3 -> b3
                                        .name(domain)
                                        .type(RRType.CNAME)
                                        .ttl(300L)
                                        .resourceRecords(b4 -> b4
                                                .value(createConnectionGroupResponse.connectionGroup().routingEndpoint())))
                                .action("CREATE"))
                ));

        // Give the R53 record time to propagate, if it isn't being returned by servers yet, the following call will fail
        Thread.sleep(60000);

        CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder
                .distributionId(distributionId)
                .domains(b1 -> b1
                        .domain(domain))
                .connectionGroupId(createConnectionGroupResponse.connectionGroup().id())
                .enabled(false)
                .name("cf-hosted-tenant")
                .parameters(b2 -> b2
                        .name("tenantName")
                        .value("myTenant"))
                .managedCertificateRequest(b3 -> b3
                        .validationTokenHost(ValidationTokenHost.CLOUDFRONT)
                )
        );

        return createResponse.distributionTenant();
    }

}
```
次の例は、セルフホスト型マネージド証明書リクエストを使用してこれを行う方法を示しています。これは、ドメインへのトラフィックがあり、移行中のダウンタイムを許容できない場合に最適です。この例の最後に、テナントはドメインの検証と DNS 設定を待っている状態で作成されます。トラフィックを移行する準備ができたら、ステップ [こちら](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/managed-cloudfront-certificates.html\$1complete-domain-ownership) の手順に従ってセットアップを完了してください。  

```
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreateConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.CreateDistributionTenantResponse;
import software.amazon.awssdk.services.cloudfront.model.DistributionTenant;
import software.amazon.awssdk.services.cloudfront.model.GetConnectionGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.ValidationTokenHost;
import software.amazon.awssdk.services.route53.Route53Client;
import software.amazon.awssdk.services.route53.model.RRType;

import java.time.Instant;

public class CreateDistributionTenant {

    public static DistributionTenant createDistributionTenantSelfHosted(CloudFrontClient cloudFrontClient,
                                                                        String distributionId,
                                                                        String domain) {
        CreateDistributionTenantResponse createResponse = cloudFrontClient.createDistributionTenant(builder -> builder
                .distributionId(distributionId)
                .domains(b1 -> b1
                        .domain(domain))
                .parameters(b2 -> b2
                        .name("tenantName")
                        .value("myTenant"))
                .enabled(false)
                .name("self-hosted-tenant")
                .managedCertificateRequest(b3 -> b3
                        .validationTokenHost(ValidationTokenHost.SELF_HOSTED)
                        .primaryDomainName(domain)
                )
        );

        return createResponse.distributionTenant();
    }

}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateDistribution](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/CreateDistribution)
  + [CreateDistributionTenant](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/CreateDistributionTenant)

### 署名リソースを削除する
<a name="cloudfront_DeleteSigningResources_java_2_topic"></a>

次のコード例は、Amazon Simple Storage Service (Amazon S3) バケット内の制限付きコンテンツへのアクセス権を取得するために使用されるリソースを削除する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.DeleteKeyGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.DeleteOriginAccessControlResponse;
import software.amazon.awssdk.services.cloudfront.model.DeletePublicKeyResponse;
import software.amazon.awssdk.services.cloudfront.model.GetKeyGroupResponse;
import software.amazon.awssdk.services.cloudfront.model.GetOriginAccessControlResponse;
import software.amazon.awssdk.services.cloudfront.model.GetPublicKeyResponse;

public class DeleteSigningResources {
    private static final Logger logger = LoggerFactory.getLogger(DeleteSigningResources.class);

    public static void deleteOriginAccessControl(final CloudFrontClient cloudFrontClient,
            final String originAccessControlId) {
        GetOriginAccessControlResponse getResponse = cloudFrontClient
                .getOriginAccessControl(b -> b.id(originAccessControlId));
        DeleteOriginAccessControlResponse deleteResponse = cloudFrontClient.deleteOriginAccessControl(builder -> builder
                .id(originAccessControlId)
                .ifMatch(getResponse.eTag()));
        if (deleteResponse.sdkHttpResponse().isSuccessful()) {
            logger.info("Successfully deleted Origin Access Control [{}]", originAccessControlId);
        }
    }

    public static void deleteKeyGroup(final CloudFrontClient cloudFrontClient, final String keyGroupId) {

        GetKeyGroupResponse getResponse = cloudFrontClient.getKeyGroup(b -> b.id(keyGroupId));
        DeleteKeyGroupResponse deleteResponse = cloudFrontClient.deleteKeyGroup(builder -> builder
                .id(keyGroupId)
                .ifMatch(getResponse.eTag()));
        if (deleteResponse.sdkHttpResponse().isSuccessful()) {
            logger.info("Successfully deleted Key Group [{}]", keyGroupId);
        }
    }

    public static void deletePublicKey(final CloudFrontClient cloudFrontClient, final String publicKeyId) {
        GetPublicKeyResponse getResponse = cloudFrontClient.getPublicKey(b -> b.id(publicKeyId));

        DeletePublicKeyResponse deleteResponse = cloudFrontClient.deletePublicKey(builder -> builder
                .id(publicKeyId)
                .ifMatch(getResponse.eTag()));

        if (deleteResponse.sdkHttpResponse().isSuccessful()) {
            logger.info("Successfully deleted Public Key [{}]", publicKeyId);
        }
    }
}
```
+ API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の以下のトピックを参照してください。
  + [DeleteKeyGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/DeleteKeyGroup)
  + [DeleteOriginAccessControl](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/DeleteOriginAccessControl)
  + [DeletePublicKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/DeletePublicKey)

### URL および cookies に署名する
<a name="cloudfront_CloudFrontUtilities_java_2_topic"></a>

次のコード例は、制限付きリソースへのアクセスを許可する署名付き URL と Cookie を作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。
[CannedSignerRequest](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudfront/model/CannedSignerRequest.html) クラスを使用すると、既定*ポリシー*を使用して URL または Cookies に署名できます。  

```
import software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest;

import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class CreateCannedPolicyRequest {

    public static CannedSignerRequest createRequestForCannedPolicy(String distributionDomainName,
            String fileNameToUpload,
            String privateKeyFullPath, String publicKeyId) throws Exception {
        String protocol = "https";
        String resourcePath = "/" + fileNameToUpload;

        String cloudFrontUrl = new URL(protocol, distributionDomainName, resourcePath).toString();
        Instant expirationDate = Instant.now().plus(7, ChronoUnit.DAYS);
        Path path = Paths.get(privateKeyFullPath);

        return CannedSignerRequest.builder()
                .resourceUrl(cloudFrontUrl)
                .privateKey(path)
                .keyPairId(publicKeyId)
                .expirationDate(expirationDate)
                .build();
    }
}
```
[CustomSignerRequest](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudfront/model/CustomSignerRequest.html) クラスを使用すると、*カスタム*ポリシーを使用して URL や Cookie に署名できます。`activeDate` および `ipRange` はオプションのメソッドです。  

```
import software.amazon.awssdk.services.cloudfront.model.CustomSignerRequest;

import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class CreateCustomPolicyRequest {

    public static CustomSignerRequest createRequestForCustomPolicy(String distributionDomainName,
            String fileNameToUpload,
            String privateKeyFullPath, String publicKeyId) throws Exception {
        String protocol = "https";
        String resourcePath = "/" + fileNameToUpload;

        String cloudFrontUrl = new URL(protocol, distributionDomainName, resourcePath).toString();
        Instant expireDate = Instant.now().plus(7, ChronoUnit.DAYS);
        // URL will be accessible tomorrow using the signed URL.
        Instant activeDate = Instant.now().plus(1, ChronoUnit.DAYS);
        Path path = Paths.get(privateKeyFullPath);

        return CustomSignerRequest.builder()
                .resourceUrl(cloudFrontUrl)
                // .resourceUrlPattern("https://*.example.com/*")  // Optional.
                .privateKey(path)
                .keyPairId(publicKeyId)
                .expirationDate(expireDate)
                .activeDate(activeDate) // Optional.
                // .ipRange("192.168.0.1/24") // Optional.
                .build();
    }
}
```
次の例は、[CloudFrontUtilities](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/cloudfront/CloudFrontUtilities.html) クラスを使用して署名付き Cookies と URL を生成する方法を示しています。このコード例を GitHub を[表示](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/cloudfront/src/main/java/com/example/cloudfront/SigningUtilities.java)します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.cloudfront.CloudFrontUtilities;
import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCannedPolicy;
import software.amazon.awssdk.services.cloudfront.cookie.CookiesForCustomPolicy;
import software.amazon.awssdk.services.cloudfront.model.CannedSignerRequest;
import software.amazon.awssdk.services.cloudfront.model.CustomSignerRequest;
import software.amazon.awssdk.services.cloudfront.url.SignedUrl;

public class SigningUtilities {
    private static final Logger logger = LoggerFactory.getLogger(SigningUtilities.class);
    private static final CloudFrontUtilities cloudFrontUtilities = CloudFrontUtilities.create();

    public static SignedUrl signUrlForCannedPolicy(CannedSignerRequest cannedSignerRequest) {
        SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCannedPolicy(cannedSignerRequest);
        logger.info("Signed URL: [{}]", signedUrl.url());
        return signedUrl;
    }

    public static SignedUrl signUrlForCustomPolicy(CustomSignerRequest customSignerRequest) {
        SignedUrl signedUrl = cloudFrontUtilities.getSignedUrlWithCustomPolicy(customSignerRequest);
        logger.info("Signed URL: [{}]", signedUrl.url());
        return signedUrl;
    }

    public static CookiesForCannedPolicy getCookiesForCannedPolicy(CannedSignerRequest cannedSignerRequest) {
        CookiesForCannedPolicy cookiesForCannedPolicy = cloudFrontUtilities
                .getCookiesForCannedPolicy(cannedSignerRequest);
        logger.info("Cookie EXPIRES header [{}]", cookiesForCannedPolicy.expiresHeaderValue());
        logger.info("Cookie KEYPAIR header [{}]", cookiesForCannedPolicy.keyPairIdHeaderValue());
        logger.info("Cookie SIGNATURE header [{}]", cookiesForCannedPolicy.signatureHeaderValue());
        return cookiesForCannedPolicy;
    }

    public static CookiesForCustomPolicy getCookiesForCustomPolicy(CustomSignerRequest customSignerRequest) {
        CookiesForCustomPolicy cookiesForCustomPolicy = cloudFrontUtilities
                .getCookiesForCustomPolicy(customSignerRequest);
        logger.info("Cookie POLICY header [{}]", cookiesForCustomPolicy.policyHeaderValue());
        logger.info("Cookie KEYPAIR header [{}]", cookiesForCustomPolicy.keyPairIdHeaderValue());
        logger.info("Cookie SIGNATURE header [{}]", cookiesForCustomPolicy.signatureHeaderValue());
        return cookiesForCustomPolicy;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CloudFrontUtilities](https://docs.aws.amazon.com/goto/SdkForJavaV2/cloudfront-2020-05-31/CloudFrontUtilities)」を参照してください。

# SDK for Java 2.x を使用した CloudWatch の例
<a name="java_2_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello CloudWatch
<a name="cloudwatch_Hello_java_2_topic"></a>

次のコード例は、CloudWatch の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.ListMetricsRequest;
import software.amazon.awssdk.services.cloudwatch.paginators.ListMetricsIterable;

/**
 * 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 HelloService {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <namespace>\s

                Where:
                  namespace - The namespace to filter against (for example, AWS/EC2).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String namespace = args[0];
        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        listMets(cw, namespace);
        cw.close();
    }

    public static void listMets(CloudWatchClient cw, String namespace) {
        try {
            ListMetricsRequest request = ListMetricsRequest.builder()
                    .namespace(namespace)
                    .build();

            ListMetricsIterable listRes = cw.listMetricsPaginator(request);
            listRes.stream()
                    .flatMap(r -> r.metrics().stream())
                    .forEach(metrics -> System.out.println(" Retrieved metric is: " + metrics.metricName()));

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListMetrics](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/ListMetrics)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="cloudwatch_GetStartedMetricsDashboardsAlarms_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ CloudWatch の名前空間とメトリクスを一覧表示します。
+ メトリクスと予想請求額の統計の取得
+ ダッシュボードの作成と更新
+ メトリクスの作成とデータの追加
+ アラームの作成/トリガーとアラーム履歴の表示
+ 異常ディテクターの追加
+ メトリクス画像を取得し、リソースをクリーンアップします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
CloudWatch の機能を実証するインタラクティブなシナリオを実行します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.DashboardInvalidInputErrorException;
import software.amazon.awssdk.services.cloudwatch.model.DeleteAlarmsResponse;
import software.amazon.awssdk.services.cloudwatch.model.DeleteAnomalyDetectorResponse;
import software.amazon.awssdk.services.cloudwatch.model.DeleteDashboardsResponse;
import software.amazon.awssdk.services.cloudwatch.model.Dimension;
import software.amazon.awssdk.services.cloudwatch.model.GetMetricStatisticsResponse;
import software.amazon.awssdk.services.cloudwatch.model.LimitExceededException;
import software.amazon.awssdk.services.cloudwatch.model.PutDashboardResponse;
import software.amazon.awssdk.services.cloudwatch.model.PutMetricDataResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;

/**
 * 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
 *
 * To enable billing metrics and statistics for this example, make sure billing
 * alerts are enabled for your account:
 * https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics
 *
 * This Java code example performs the following tasks:
 *
 * 1. List available namespaces from Amazon CloudWatch.
 * 2. List available metrics within the selected Namespace.
 * 3. Get statistics for the selected metric over the last day.
 * 4. Get CloudWatch estimated billing for the last week.
 * 5. Create a new CloudWatch dashboard with metrics.
 * 6. List dashboards using a paginator.
 * 7. Create a new custom metric by adding data for it.
 * 8. Add the custom metric to the dashboard.
 * 9. Create an alarm for the custom metric.
 * 10. Describe current alarms.
 * 11. Get current data for the new custom metric.
 * 12. Push data into the custom metric to trigger the alarm.
 * 13. Check the alarm state using the action DescribeAlarmsForMetric.
 * 14. Get alarm history for the new alarm.
 * 15. Add an anomaly detector for the custom metric.
 * 16. Describe current anomaly detectors.
 * 17. Get a metric image for the custom metric.
 * 18. Clean up the Amazon CloudWatch resources.
 */
public class CloudWatchScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    static CloudWatchActions cwActions = new CloudWatchActions();

    private static final Logger logger = LoggerFactory.getLogger(CloudWatchScenario.class);
    static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) throws Throwable {

        final String usage = """

            Usage:
              <myDate> <costDateWeek> <dashboardName> <dashboardJson> <dashboardAdd> <settings> <metricImage> \s

            Where:
              myDate - The start date to use to get metric statistics. (For example, 2023-01-11T18:35:24.00Z.)\s
              costDateWeek - The start date to use to get AWS/Billing statistics. (For example, 2023-01-11T18:35:24.00Z.)\s
              dashboardName - The name of the dashboard to create.\s
              dashboardJson - The location of a JSON file to use to create a dashboard. (See jsonWidgets.json in javav2/example_code/cloudwatch.)\s
              dashboardAdd - The location of a JSON file to use to update a dashboard. (See CloudDashboard.json in javav2/example_code/cloudwatch.)\s
              settings - The location of a JSON file from which various values are read. (See settings.json in javav2/example_code/cloudwatch.)\s
              metricImage - The location of a BMP file that is used to create a graph.\s
            """;

        if (args.length != 7) {
            logger.info(usage);
            return;
        }
        String myDate = args[0];
        String costDateWeek = args[1];
        String dashboardName = args[2];
        String dashboardJson = args[3];
        String dashboardAdd = args[4];
        String settings = args[5];
        String metricImage = args[6];

        logger.info(DASHES);
        logger.info("Welcome to the Amazon CloudWatch Basics scenario.");
        logger.info("""
            Amazon CloudWatch is a comprehensive monitoring and observability service 
            provided by Amazon Web Services (AWS). It is designed to help you monitor your 
            AWS resources, applications, and services, as well as on-premises resources, 
            in real-time.
                        
            CloudWatch collects and tracks various types of data, including metrics, 
            logs, and events, from your AWS and on-premises resources. It allows you to set 
            alarms and automatically respond to changes in your environment, 
            enabling you to quickly identify and address issues before they impact your 
            applications or services. 
                        
            With CloudWatch, you can gain visibility into your entire infrastructure, from the cloud 
            to the edge, and use this information to make informed decisions and optimize your 
            resource utilization.
                        
            This scenario guides you through how to perform Amazon CloudWatch tasks by using the 
            AWS SDK for Java v2. Let's get started...
            """);
        waitForInputToContinue(scanner);

        try {
            runScenario(myDate, costDateWeek, dashboardName, dashboardJson, dashboardAdd, settings, metricImage);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
        logger.info(DASHES);
    }

    private static void runScenario(String myDate, String costDateWeek, String dashboardName, String dashboardJson, String dashboardAdd, String settings, String metricImage ) throws Throwable {
        Double dataPoint = Double.parseDouble("10.0");
        logger.info(DASHES);
        logger.info("""
        1. List at least five available unique namespaces from Amazon CloudWatch. 
        Select one from the list.
        """);
        String selectedNamespace;
        String selectedMetrics;
        int num;
        try {
            CompletableFuture<ArrayList<String>> future = cwActions.listNameSpacesAsync();
            ArrayList<String> list = future.join();
            for (int z = 0; z < 5; z++) {
                int index = z + 1;
                logger.info("    " + index + ". {}", list.get(z));
            }

            num = Integer.parseInt(scanner.nextLine());
            if (1 <= num && num <= 5) {
                selectedNamespace = list.get(num - 1);
            } else {
                logger.info("You did not select a valid option.");
                return;
            }
            logger.info("You selected {}", selectedNamespace);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. List available metrics within the selected namespace.");
        logger.info("""
            A metric is a measure of the performance or health of your AWS resources, 
            applications, or custom resources. Metrics are the basic building blocks of CloudWatch 
            and provide data points that represent a specific aspect of your system or application over time.
            
            Select a metric from the list.
            """);

        Dimension myDimension = null;
        try {
            CompletableFuture<ArrayList<String>> future = cwActions.listMetsAsync(selectedNamespace);
            ArrayList<String> metList = future.join();
            logger.info("Metrics successfully retrieved. Total metrics: {}", metList.size());
            for (int z = 0; z < 5; z++) {
                int index = z + 1;
                logger.info("    " + index + ". " + metList.get(z));
            }
            num = Integer.parseInt(scanner.nextLine());
            if (1 <= num && num <= 5) {
                selectedMetrics = metList.get(num - 1);
            } else {
                logger.info("You did not select a valid option.");
                return;
            }
            logger.info("You selected {}", selectedMetrics);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }

        try {
            myDimension = cwActions.getSpecificMetAsync(selectedNamespace).join();
            logger.info("Metric statistics successfully retrieved and displayed.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("3. Get statistics for the selected metric over the last day.");
        logger.info("""
            Statistics refer to the various mathematical calculations that can be performed on the 
            collected metrics to derive meaningful insights. Statistics provide a way to summarize and 
            analyze the data collected for a specific metric over a specified time period.
            """);
        waitForInputToContinue(scanner);
        String metricOption = "";
        ArrayList<String> statTypes = new ArrayList<>();
        statTypes.add("SampleCount");
        statTypes.add("Average");
        statTypes.add("Sum");
        statTypes.add("Minimum");
        statTypes.add("Maximum");

        for (int t = 0; t < 5; t++) {
            logger.info("    " + (t + 1) + ". {}", statTypes.get(t));
        }
        logger.info("Select a metric statistic by entering a number from the preceding list:");
        num = Integer.parseInt(scanner.nextLine());
        if (1 <= num && num <= 5) {
            metricOption = statTypes.get(num - 1);
        } else {
            logger.info("You did not select a valid option.");
            return;
        }
        logger.info("You selected " + metricOption);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<GetMetricStatisticsResponse> future = cwActions.getAndDisplayMetricStatisticsAsync(selectedNamespace, selectedMetrics, metricOption, myDate, myDimension);
            future.join();
            logger.info("Metric statistics retrieved successfully.");

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. Get CloudWatch estimated billing for the last week.");
        waitForInputToContinue(scanner);
         try {
            CompletableFuture<GetMetricStatisticsResponse> future = cwActions.getMetricStatisticsAsync(costDateWeek);
            future.join();

            logger.info("Metric statistics successfully retrieved and displayed.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
             throw cause;
         }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5. Create a new CloudWatch dashboard with metrics.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<PutDashboardResponse> future = cwActions.createDashboardWithMetricsAsync(dashboardName, dashboardJson);
            future.join();

        } catch (RuntimeException | IOException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof DashboardInvalidInputErrorException cwEx) {
                logger.info("Invalid CloudWatch data. Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("6. List dashboards using a paginator.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = cwActions.listDashboardsAsync();
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Create a new custom metric by adding data to it.");
        logger.info("""
            The primary benefit of using a custom metric in Amazon CloudWatch is the ability to 
            monitor and collect data that is specific to your application or infrastructure.
            """);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<PutMetricDataResponse> future = cwActions.createNewCustomMetricAsync(dataPoint);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("8. Add an additional metric to the dashboard.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<PutDashboardResponse> future = cwActions.addMetricToDashboardAsync(dashboardAdd, dashboardName);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof DashboardInvalidInputErrorException cwEx) {
                logger.info("Invalid CloudWatch data. Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("9. Create an alarm for the custom metric.");
        waitForInputToContinue(scanner);
        String alarmName = "" ;
        try {
            CompletableFuture<String> future = cwActions.createAlarmAsync(settings);
            alarmName = future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof LimitExceededException cwEx) {
                logger.info("The quota for alarms has been reached: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("10. Describe ten current alarms.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = cwActions.describeAlarmsAsync();
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("11. Get current data for new custom metric.");
        try {
            CompletableFuture<Void> future = cwActions.getCustomMetricDataAsync(settings);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("12. Push data into the custom metric to trigger the alarm.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<PutMetricDataResponse> future = cwActions.addMetricDataForAlarmAsync(settings);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("13. Check the alarm state using the action DescribeAlarmsForMetric.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = cwActions.checkForMetricAlarmAsync(settings);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("14. Get alarm history for the new alarm.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = cwActions.getAlarmHistoryAsync(settings, myDate);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("15. Add an anomaly detector for the custom metric.");
        logger.info("""
            An anomaly detector is a feature that automatically detects unusual patterns or deviations in your 
            monitored metrics. It uses machine learning algorithms to analyze the historical behavior 
            of your metrics and establish a baseline. 
            
            The anomaly detector then compares the current metric values against this baseline and 
            identifies any anomalies or outliers that may indicate potential issues or unexpected changes 
            in your system's performance or behavior. 
            
            """);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = cwActions.addAnomalyDetectorAsync(settings);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("16. Describe current anomaly detectors.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = cwActions.describeAnomalyDetectorsAsync(settings);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("17. Get a metric image for the custom metric.");
        try {
            CompletableFuture<Void> future = cwActions.downloadAndSaveMetricImageAsync(metricImage);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("18. Clean up the Amazon CloudWatch resources.");

        try {
            logger.info(". Delete the Dashboard.");
            waitForInputToContinue(scanner);
            CompletableFuture<DeleteDashboardsResponse> future = cwActions.deleteDashboardAsync(dashboardName);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }

        try {
            logger.info("Delete the alarm.");
            waitForInputToContinue(scanner);
            CompletableFuture<DeleteAlarmsResponse> future = cwActions.deleteCWAlarmAsync(alarmName);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }

        try {
            logger.info("Delete the anomaly detector.");
            waitForInputToContinue(scanner);
            CompletableFuture<DeleteAnomalyDetectorResponse> future = cwActions.deleteAnomalyDetectorAsync(settings);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof CloudWatchException cwEx) {
                logger.info("CloudWatch error occurred: Error message: {}, Error code {}", cwEx.getMessage(), cwEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("The Amazon CloudWatch example scenario is complete.");
        logger.info(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();
            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
CloudWatch SDK メソッドのラッパークラス。  

```
public class CloudWatchActions {

    private static CloudWatchAsyncClient cloudWatchAsyncClient;

    private static final Logger logger = LoggerFactory.getLogger(CloudWatchActions.class);

    /**
     * Retrieves an asynchronous CloudWatch client instance.
     *
     * <p>
     * This method ensures that the CloudWatch client is initialized with the following configurations:
     * <ul>
     *     <li>Maximum concurrency: 100</li>
     *     <li>Connection timeout: 60 seconds</li>
     *     <li>Read timeout: 60 seconds</li>
     *     <li>Write timeout: 60 seconds</li>
     *     <li>API call timeout: 2 minutes</li>
     *     <li>API call attempt timeout: 90 seconds</li>
     *     <li>Retry strategy: STANDARD</li>
     * </ul>
     * </p>
     *
     * @return the asynchronous CloudWatch client instance
     */
    private static CloudWatchAsyncClient getAsyncClient() {
        if (cloudWatchAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            cloudWatchAsyncClient = CloudWatchAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return cloudWatchAsyncClient;
    }

    /**
     * Deletes an Anomaly Detector.
     *
     * @param fileName the name of the file containing the Anomaly Detector configuration
     * @return a CompletableFuture that represents the asynchronous deletion of the Anomaly Detector
     */
    public CompletableFuture<DeleteAnomalyDetectorResponse> deleteAnomalyDetectorAsync(String fileName) {
        CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                return new ObjectMapper().readTree(parser); // Return the root node
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        return readFileFuture.thenCompose(rootNode -> {
            String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
            String customMetricName = rootNode.findValue("customMetricName").asText();

            SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder()
                .metricName(customMetricName)
                .namespace(customMetricNamespace)
                .stat("Maximum")
                .build();

            DeleteAnomalyDetectorRequest request = DeleteAnomalyDetectorRequest.builder()
                .singleMetricAnomalyDetector(singleMetricAnomalyDetector)
                .build();

            return getAsyncClient().deleteAnomalyDetector(request);
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Failed to delete the Anomaly Detector", exception);
            } else {
                logger.info("Successfully deleted the Anomaly Detector.");
            }
        });
    }

    /**
     * Deletes a CloudWatch alarm.
     *
     * @param alarmName the name of the alarm to be deleted
     * @return a {@link CompletableFuture} representing the asynchronous operation to delete the alarm
     * the {@link DeleteAlarmsResponse} is returned when the operation completes successfully,
     * or a {@link RuntimeException} is thrown if the operation fails
     */
    public CompletableFuture<DeleteAlarmsResponse> deleteCWAlarmAsync(String alarmName) {
        DeleteAlarmsRequest request = DeleteAlarmsRequest.builder()
            .alarmNames(alarmName)
            .build();

        return getAsyncClient().deleteAlarms(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to delete the alarm:{} " + alarmName, exception);
                } else {
                    logger.info("Successfully deleted alarm {} ", alarmName);
                }
            });
    }

    /**
     * Deletes the specified dashboard.
     *
     * @param dashboardName the name of the dashboard to be deleted
     * @return a {@link CompletableFuture} representing the asynchronous operation of deleting the dashboard
     * @throws RuntimeException if the dashboard deletion fails
     */
    public CompletableFuture<DeleteDashboardsResponse> deleteDashboardAsync(String dashboardName) {
        DeleteDashboardsRequest dashboardsRequest = DeleteDashboardsRequest.builder()
            .dashboardNames(dashboardName)
            .build();

        return getAsyncClient().deleteDashboards(dashboardsRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to delete the dashboard: " + dashboardName, exception);
                } else {
                    logger.info("{} was successfully deleted.", dashboardName);
                }
            });
    }


    /**
     * Retrieves and saves a custom metric image to a file.
     *
     * @param fileName the name of the file to save the metric image to
     * @return a {@link CompletableFuture} that completes when the image has been saved to the file
     */
    public CompletableFuture<Void> downloadAndSaveMetricImageAsync(String fileName) {
        logger.info("Getting Image data for custom metric.");
        String myJSON = """
              {
                  "title": "Example Metric Graph",
                  "view": "timeSeries",
                  "stacked ": false,
                  "period": 10,
                  "width": 1400,
                  "height": 600,
                  "metrics": [
                      [
                      "AWS/Billing",
                      "EstimatedCharges",
                      "Currency",
                      "USD"
                     ]
                  ]
              }
            """;

        GetMetricWidgetImageRequest imageRequest = GetMetricWidgetImageRequest.builder()
            .metricWidget(myJSON)
            .build();

        return getAsyncClient().getMetricWidgetImage(imageRequest)
            .thenCompose(response -> {
                SdkBytes sdkBytes = response.metricWidgetImage();
                byte[] bytes = sdkBytes.asByteArray();
                return CompletableFuture.runAsync(() -> {
                    try {
                        File outputFile = new File(fileName);
                        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                            outputStream.write(bytes);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("Failed to write image to file", e);
                    }
                });
            })
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Error getting and saving metric image", exception);
                } else {
                    logger.info("Image data saved successfully to {}", fileName);
                }
            });
    }


    /**
     * Describes the anomaly detectors based on the specified JSON file.
     *
     * @param fileName the name of the JSON file containing the custom metric namespace and name
     * @return a {@link CompletableFuture} that completes when the anomaly detectors have been described
     * @throws RuntimeException if there is a failure during the operation, such as when reading or parsing the JSON file,
     *                          or when describing the anomaly detectors
     */
    public CompletableFuture<Void> describeAnomalyDetectorsAsync(String fileName) {
        CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                return new ObjectMapper().readTree(parser);
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        return readFileFuture.thenCompose(rootNode -> {
            try {
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                DescribeAnomalyDetectorsRequest detectorsRequest = DescribeAnomalyDetectorsRequest.builder()
                    .maxResults(10)
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .build();

                return getAsyncClient().describeAnomalyDetectors(detectorsRequest).thenAccept(response -> {
                    List<AnomalyDetector> anomalyDetectorList = response.anomalyDetectors();
                    for (AnomalyDetector detector : anomalyDetectorList) {
                        logger.info("Metric name: {} ", detector.singleMetricAnomalyDetector().metricName());
                        logger.info("State: {} ", detector.stateValue());
                    }
                });
            } catch (RuntimeException e) {
                throw new RuntimeException("Failed to describe anomaly detectors", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error describing anomaly detectors", exception);
            }
        });
    }


    /**
     * Adds an anomaly detector for the given file.
     *
     * @param fileName the name of the file containing the anomaly detector configuration
     * @return a {@link CompletableFuture} that completes when the anomaly detector has been added
     */
    public CompletableFuture<Void> addAnomalyDetectorAsync(String fileName) {
        CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                return new ObjectMapper().readTree(parser); // Return the root node
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        return readFileFuture.thenCompose(rootNode -> {
            try {
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder()
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .stat("Maximum")
                    .build();

                PutAnomalyDetectorRequest anomalyDetectorRequest = PutAnomalyDetectorRequest.builder()
                    .singleMetricAnomalyDetector(singleMetricAnomalyDetector)
                    .build();

                return getAsyncClient().putAnomalyDetector(anomalyDetectorRequest).thenAccept(response -> {
                    logger.info("Added anomaly detector for metric {}", customMetricName);
                });
            } catch (Exception e) {
                throw new RuntimeException("Failed to create anomaly detector", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error adding anomaly detector", exception);
            }
        });
    }


    /**
     * Retrieves the alarm history for a given alarm name and date range.
     *
     * @param fileName the path to the JSON file containing the alarm name
     * @param date     the date to start the alarm history search (in the format "yyyy-MM-dd'T'HH:mm:ss'Z'")
     * @return a {@code CompletableFuture<Void>} that completes when the alarm history has been retrieved and processed
     */
    public CompletableFuture<Void> getAlarmHistoryAsync(String fileName, String date) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.findValue("exampleAlarmName").asText(); // Return alarmName from the JSON file
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        // Use the alarm name to describe alarm history with a paginator.
        return readFileFuture.thenCompose(alarmName -> {
            try {
                Instant start = Instant.parse(date);
                Instant endDate = Instant.now();
                DescribeAlarmHistoryRequest historyRequest = DescribeAlarmHistoryRequest.builder()
                    .startDate(start)
                    .endDate(endDate)
                    .alarmName(alarmName)
                    .historyItemType(HistoryItemType.ACTION)
                    .build();

                // Use the paginator to paginate through alarm history pages.
                DescribeAlarmHistoryPublisher historyPublisher = getAsyncClient().describeAlarmHistoryPaginator(historyRequest);
                CompletableFuture<Void> future = historyPublisher
                    .subscribe(response -> response.alarmHistoryItems().forEach(item -> {
                        logger.info("History summary: {}", item.historySummary());
                        logger.info("Timestamp: {}", item.timestamp());
                    }))
                    .whenComplete((result, exception) -> {
                        if (exception != null) {
                            logger.error("Error occurred while getting alarm history: " + exception.getMessage(), exception);
                        } else {
                            logger.info("Successfully retrieved all alarm history.");
                        }
                    });

                // Return the future to the calling code for further handling
                return future;
            } catch (Exception e) {
                throw new RuntimeException("Failed to process alarm history", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error completing alarm history processing", exception);
            }
        });
    }



    /**
     * Checks for a metric alarm in AWS CloudWatch.
     *
     * @param fileName the name of the file containing the JSON configuration for the custom metric
     * @return a {@link CompletableFuture} that completes when the check for the metric alarm is complete
     */
    public CompletableFuture<Void> checkForMetricAlarmAsync(String fileName) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.toString(); // Return JSON as a string for further processing
            } catch (IOException e) {
                throw new RuntimeException("Failed to read file", e);
            }
        });

        return readFileFuture.thenCompose(jsonContent -> {
            try {
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent);
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                DescribeAlarmsForMetricRequest metricRequest = DescribeAlarmsForMetricRequest.builder()
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .build();

                return checkForAlarmAsync(metricRequest, customMetricName, 10);

            } catch (IOException e) {
                throw new RuntimeException("Failed to parse JSON content", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error checking metric alarm", exception);
            }
        });
    }

    // Recursive method to check for the alarm.

    /**
     * Checks for the existence of an alarm asynchronously for the specified metric.
     *
     * @param metricRequest    the request to describe the alarms for the specified metric
     * @param customMetricName the name of the custom metric to check for an alarm
     * @param retries          the number of retries to perform if no alarm is found
     * @return a {@link CompletableFuture} that completes when an alarm is found or the maximum number of retries has been reached
     */
    private static CompletableFuture<Void> checkForAlarmAsync(DescribeAlarmsForMetricRequest metricRequest, String customMetricName, int retries) {
        if (retries == 0) {
            return CompletableFuture.completedFuture(null).thenRun(() ->
                logger.info("No Alarm state found for {} after 10 retries.", customMetricName)
            );
        }

        return (getAsyncClient().describeAlarmsForMetric(metricRequest).thenCompose(response -> {
            if (response.hasMetricAlarms()) {
                logger.info("Alarm state found for {}", customMetricName);
                return CompletableFuture.completedFuture(null); // Alarm found, complete the future
            } else {
                return CompletableFuture.runAsync(() -> {
                    try {
                        Thread.sleep(20000);
                        logger.info(".");
                    } catch (InterruptedException e) {
                        throw new RuntimeException("Interrupted while waiting to retry", e);
                    }
                }).thenCompose(v -> checkForAlarmAsync(metricRequest, customMetricName, retries - 1)); // Recursive call
            }
        }));
    }


    /**
     * Adds metric data for an alarm asynchronously.
     *
     * @param fileName the name of the JSON file containing the metric data
     * @return a CompletableFuture that asynchronously returns the PutMetricDataResponse
     */
    public CompletableFuture<PutMetricDataResponse> addMetricDataForAlarmAsync(String fileName) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.toString(); // Return JSON as a string for further processing
            } catch (IOException e) {
                throw new RuntimeException("Failed to read file", e);
            }
        });

        return readFileFuture.thenCompose(jsonContent -> {
            try {
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent);
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();
                Instant instant = Instant.now();

                // Create MetricDatum objects.
                MetricDatum datum1 = MetricDatum.builder()
                    .metricName(customMetricName)
                    .unit(StandardUnit.NONE)
                    .value(1001.00)
                    .timestamp(instant)
                    .build();

                MetricDatum datum2 = MetricDatum.builder()
                    .metricName(customMetricName)
                    .unit(StandardUnit.NONE)
                    .value(1002.00)
                    .timestamp(instant)
                    .build();

                List<MetricDatum> metricDataList = new ArrayList<>();
                metricDataList.add(datum1);
                metricDataList.add(datum2);

                // Build the PutMetricData request.
                PutMetricDataRequest request = PutMetricDataRequest.builder()
                    .namespace(customMetricNamespace)
                    .metricData(metricDataList)
                    .build();

                // Send the request asynchronously.
                return getAsyncClient().putMetricData(request);

            } catch (IOException e) {
                CompletableFuture<PutMetricDataResponse> failedFuture = new CompletableFuture<>();
                failedFuture.completeExceptionally(new RuntimeException("Failed to parse JSON content", e));
                return failedFuture;
            }
        }).whenComplete((response, exception) -> {
            if (exception != null) {
                logger.error("Failed to put metric data: " + exception.getMessage(), exception);
            } else {
                logger.info("Added metric values for metric.");
            }
        });
    }


    /**
     * Retrieves custom metric data from the AWS CloudWatch service.
     *
     * @param fileName the name of the file containing the custom metric information
     * @return a {@link CompletableFuture} that completes when the metric data has been retrieved
     */
    public CompletableFuture<Void> getCustomMetricDataAsync(String fileName) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                // Read values from the JSON file.
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.toString(); // Return JSON as a string for further processing
            } catch (IOException e) {
                throw new RuntimeException("Failed to read file", e);
            }
        });

        return readFileFuture.thenCompose(jsonContent -> {
            try {
                // Parse the JSON string to extract relevant values.
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent);
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                // Set the current time and date range for metric query.
                Instant nowDate = Instant.now();
                long hours = 1;
                long minutes = 30;
                Instant endTime = nowDate.plus(hours, ChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES);

                Metric met = Metric.builder()
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .build();

                MetricStat metStat = MetricStat.builder()
                    .stat("Maximum")
                    .period(60)  // Assuming period in seconds
                    .metric(met)
                    .build();

                MetricDataQuery dataQuery = MetricDataQuery.builder()
                    .metricStat(metStat)
                    .id("foo2")
                    .returnData(true)
                    .build();

                List<MetricDataQuery> dq = new ArrayList<>();
                dq.add(dataQuery);

                GetMetricDataRequest getMetricDataRequest = GetMetricDataRequest.builder()
                    .maxDatapoints(10)
                    .scanBy(ScanBy.TIMESTAMP_DESCENDING)
                    .startTime(nowDate)
                    .endTime(endTime)
                    .metricDataQueries(dq)
                    .build();

                // Call the async method for CloudWatch data retrieval.
                return getAsyncClient().getMetricData(getMetricDataRequest);

            } catch (IOException e) {
                throw new RuntimeException("Failed to parse JSON content", e);
            }
        }).thenAccept(response -> {
            List<MetricDataResult> data = response.metricDataResults();
            for (MetricDataResult item : data) {
                logger.info("The label is: {}", item.label());
                logger.info("The status code is: {}", item.statusCode().toString());
            }
        }).exceptionally(exception -> {
            throw new RuntimeException("Failed to get metric data", exception);
        });
    }


    /**
     * Describes the CloudWatch alarms of the 'METRIC_ALARM' type.
     *
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     * of describing the CloudWatch alarms. The future completes when the
     * operation is finished, either successfully or with an error.
     */
    public CompletableFuture<Void> describeAlarmsAsync() {
        List<AlarmType> typeList = new ArrayList<>();
        typeList.add(AlarmType.METRIC_ALARM);
        DescribeAlarmsRequest alarmsRequest = DescribeAlarmsRequest.builder()
            .alarmTypes(typeList)
            .maxRecords(10)
            .build();

        return getAsyncClient().describeAlarms(alarmsRequest)
            .thenAccept(response -> {
                List<MetricAlarm> alarmList = response.metricAlarms();
                for (MetricAlarm alarm : alarmList) {
                    logger.info("Alarm name: {}", alarm.alarmName());
                    logger.info("Alarm description: {} ", alarm.alarmDescription());
                }
            })
            .whenComplete((response, ex) -> {
                if (ex != null) {
                    logger.info("Failed to describe alarms: {}", ex.getMessage());
                } else {
                    logger.info("Successfully described alarms.");
                }
            });
    }

    /**
     * Creates an alarm based on the configuration provided in a JSON file.
     *
     * @param fileName the name of the JSON file containing the alarm configuration
     * @return a CompletableFuture that represents the asynchronous operation of creating the alarm
     * @throws RuntimeException if an exception occurs while reading the JSON file or creating the alarm
     */
    public CompletableFuture<String> createAlarmAsync(String fileName) {
        com.fasterxml.jackson.databind.JsonNode rootNode;
        try {
            JsonParser parser = new JsonFactory().createParser(new File(fileName));
            rootNode = new ObjectMapper().readTree(parser);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read the alarm configuration file", e);
        }

        // Extract values from the JSON node.
        String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
        String customMetricName = rootNode.findValue("customMetricName").asText();
        String alarmName = rootNode.findValue("exampleAlarmName").asText();
        String emailTopic = rootNode.findValue("emailTopic").asText();
        String accountId = rootNode.findValue("accountId").asText();
        String region = rootNode.findValue("region").asText();

        // Create a List for alarm actions.
        List<String> alarmActions = new ArrayList<>();
        alarmActions.add("arn:aws:sns:" + region + ":" + accountId + ":" + emailTopic);

        PutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder()
            .alarmActions(alarmActions)
            .alarmDescription("Example metric alarm")
            .alarmName(alarmName)
            .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD)
            .threshold(100.00)
            .metricName(customMetricName)
            .namespace(customMetricNamespace)
            .evaluationPeriods(1)
            .period(10)
            .statistic("Maximum")
            .datapointsToAlarm(1)
            .treatMissingData("ignore")
            .build();

        // Call the putMetricAlarm asynchronously and handle the result.
        return getAsyncClient().putMetricAlarm(alarmRequest)
            .handle((response, ex) -> {
                if (ex != null) {
                    logger.info("Failed to create alarm: {}", ex.getMessage());
                    throw new RuntimeException("Failed to create alarm", ex);
                } else {
                    logger.info("{} was successfully created!", alarmName);
                    return alarmName;
                }
            });
    }

    /**
     * Adds a metric to a dashboard asynchronously.
     *
     * @param fileName      the name of the file containing the dashboard content
     * @param dashboardName the name of the dashboard to be updated
     * @return a {@link CompletableFuture} representing the asynchronous operation, which will complete with a
     * {@link PutDashboardResponse} when the dashboard is successfully updated
     */
    public CompletableFuture<PutDashboardResponse> addMetricToDashboardAsync(String fileName, String dashboardName) {
        String dashboardBody;
        try {
            dashboardBody = readFileAsString(fileName);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read the dashboard file", e);
        }

        PutDashboardRequest dashboardRequest = PutDashboardRequest.builder()
            .dashboardName(dashboardName)
            .dashboardBody(dashboardBody)
            .build();

        return getAsyncClient().putDashboard(dashboardRequest)
            .handle((response, ex) -> {
                if (ex != null) {
                    logger.info("Failed to update dashboard: {}", ex.getMessage());
                    throw new RuntimeException("Error updating dashboard", ex);
                } else {
                    logger.info("{} was successfully updated.", dashboardName);
                    return response;
                }
            });
    }

    /**
     * Creates a new custom metric.
     *
     * @param dataPoint the data point to be added to the custom metric
     * @return a {@link CompletableFuture} representing the asynchronous operation of adding the custom metric
     */
    public CompletableFuture<PutMetricDataResponse> createNewCustomMetricAsync(Double dataPoint) {
        Dimension dimension = Dimension.builder()
            .name("UNIQUE_PAGES")
            .value("URLS")
            .build();

        // Set an Instant object for the current time in UTC.
        String time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT);
        Instant instant = Instant.parse(time);

        // Create the MetricDatum.
        MetricDatum datum = MetricDatum.builder()
            .metricName("PAGES_VISITED")
            .unit(StandardUnit.NONE)
            .value(dataPoint)
            .timestamp(instant)
            .dimensions(dimension)
            .build();

        PutMetricDataRequest request = PutMetricDataRequest.builder()
            .namespace("SITE/TRAFFIC")
            .metricData(datum)
            .build();

        return getAsyncClient().putMetricData(request)
            .whenComplete((response, ex) -> {
                if (ex != null) {
                    throw new RuntimeException("Error adding custom metric", ex);
                } else {
                    logger.info("Successfully added metric values for PAGES_VISITED.");
                }
            });
    }

    /**
     * Lists the available dashboards.
     *
     * @return a {@link CompletableFuture} that completes when the operation is finished.
     * The future will complete exceptionally if an error occurs while listing the dashboards.
     */
    public CompletableFuture<Void> listDashboardsAsync() {
        ListDashboardsRequest listDashboardsRequest = ListDashboardsRequest.builder().build();
        ListDashboardsPublisher paginator = getAsyncClient().listDashboardsPaginator(listDashboardsRequest);
        return paginator.subscribe(response -> {
            response.dashboardEntries().forEach(entry -> {
                logger.info("Dashboard name is: {} ", entry.dashboardName());
                logger.info("Dashboard ARN is: {} ", entry.dashboardArn());
            });
        }).exceptionally(ex -> {
            logger.info("Failed to list dashboards: {} ", ex.getMessage());
            throw new RuntimeException("Error occurred while listing dashboards", ex);
        });
    }


    /**
     * Creates a new dashboard with the specified name and metrics from the given file.
     *
     * @param dashboardName the name of the dashboard to be created
     * @param fileName      the name of the file containing the dashboard body
     * @return a {@link CompletableFuture} representing the asynchronous operation of creating the dashboard
     * @throws IOException if there is an error reading the dashboard body from the file
     */
    public CompletableFuture<PutDashboardResponse> createDashboardWithMetricsAsync(String dashboardName, String fileName) throws IOException {
        String dashboardBody = readFileAsString(fileName);
        PutDashboardRequest dashboardRequest = PutDashboardRequest.builder()
            .dashboardName(dashboardName)
            .dashboardBody(dashboardBody)
            .build();

        return getAsyncClient().putDashboard(dashboardRequest)
            .handle((response, ex) -> {
                if (ex != null) {
                    logger.info("Failed to create dashboard: {}", ex.getMessage());
                    throw new RuntimeException("Dashboard creation failed", ex);
                } else {
                    // Handle the normal response case
                    logger.info("{} was successfully created.", dashboardName);
                    List<DashboardValidationMessage> messages = response.dashboardValidationMessages();
                    if (messages.isEmpty()) {
                        logger.info("There are no messages in the new Dashboard.");
                    } else {
                        for (DashboardValidationMessage message : messages) {
                            logger.info("Message: {}", message.message());
                        }
                    }
                    return response; // Return the response for further use
                }
            });
    }


    /**
     * Retrieves the metric statistics for the "EstimatedCharges" metric in the "AWS/Billing" namespace.
     *
     * @param costDateWeek the start date for the metric statistics, in the format of an ISO-8601 date string (e.g., "2023-04-05")
     * @return a {@link CompletableFuture} that, when completed, contains the {@link GetMetricStatisticsResponse} with the retrieved metric statistics
     * @throws RuntimeException if the metric statistics cannot be retrieved successfully
     */
    public CompletableFuture<GetMetricStatisticsResponse> getMetricStatisticsAsync(String costDateWeek) {
        Instant start = Instant.parse(costDateWeek);
        Instant endDate = Instant.now();

        // Define dimension
        Dimension dimension = Dimension.builder()
            .name("Currency")
            .value("USD")
            .build();

        List<Dimension> dimensionList = new ArrayList<>();
        dimensionList.add(dimension);

        GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder()
            .metricName("EstimatedCharges")
            .namespace("AWS/Billing")
            .dimensions(dimensionList)
            .statistics(Statistic.MAXIMUM)
            .startTime(start)
            .endTime(endDate)
            .period(86400) // One day period
            .build();

        return getAsyncClient().getMetricStatistics(statisticsRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    List<Datapoint> data = response.datapoints();
                    if (!data.isEmpty()) {
                        for (Datapoint datapoint : data) {
                            logger.info("Timestamp: {} Maximum value: {})", datapoint.timestamp(), datapoint.maximum());
                        }
                    } else {
                        logger.info("The returned data list is empty");
                    }
                } else {
                    throw new RuntimeException("Failed to get metric statistics: " + exception.getMessage(), exception);
                }
            });
    }


    /**
     * Retrieves and displays metric statistics for the specified parameters.
     *
     * @param nameSpace    the namespace for the metric
     * @param metVal       the name of the metric
     * @param metricOption the statistic to retrieve for the metric (e.g., "Maximum", "Average")
     * @param date         the date for which to retrieve the metric statistics, in the format "yyyy-MM-dd'T'HH:mm:ss'Z'"
     * @param myDimension  the dimension(s) to filter the metric statistics by
     * @return a {@link CompletableFuture} that completes when the metric statistics have been retrieved and displayed
     */
    public CompletableFuture<GetMetricStatisticsResponse> getAndDisplayMetricStatisticsAsync(String nameSpace, String metVal,
                                                                                             String metricOption, String date, Dimension myDimension) {

        Instant start = Instant.parse(date);
        Instant endDate = Instant.now();

        // Building the request for metric statistics.
        GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder()
            .endTime(endDate)
            .startTime(start)
            .dimensions(myDimension)
            .metricName(metVal)
            .namespace(nameSpace)
            .period(86400) // 1 day period
            .statistics(Statistic.fromValue(metricOption))
            .build();

        return getAsyncClient().getMetricStatistics(statisticsRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    List<Datapoint> data = response.datapoints();
                    if (!data.isEmpty()) {
                        for (Datapoint datapoint : data) {
                            logger.info("Timestamp: {} Maximum value: {}", datapoint.timestamp(), datapoint.maximum());
                        }
                    } else {
                        logger.info("The returned data list is empty");
                    }
                } else {
                    logger.info("Failed to get metric statistics: {} ", exception.getMessage());
                }
            })
            .exceptionally(exception -> {
                throw new RuntimeException("Error while getting metric statistics: " + exception.getMessage(), exception);
            });
    }


    /**
     * Retrieves a list of metric names for the specified namespace.
     *
     * @param namespace the namespace for which to retrieve the metric names
     * @return a {@link CompletableFuture} that, when completed, contains an {@link ArrayList} of
     * the metric names in the specified namespace
     * @throws RuntimeException if an error occurs while listing the metrics
     */
    public CompletableFuture<ArrayList<String>> listMetsAsync(String namespace) {
        ListMetricsRequest request = ListMetricsRequest.builder()
            .namespace(namespace)
            .build();

        ListMetricsPublisher metricsPaginator = getAsyncClient().listMetricsPaginator(request);
        Set<String> metSet = new HashSet<>();
        CompletableFuture<Void> future = metricsPaginator.subscribe(response -> {
            response.metrics().forEach(metric -> {
                String metricName = metric.metricName();
                metSet.add(metricName);
            });
        });

        return future
            .thenApply(ignored -> new ArrayList<>(metSet))
            .exceptionally(exception -> {
                throw new RuntimeException("Failed to list metrics: " + exception.getMessage(), exception);
            });
    }

    /**
     * Lists the available namespaces for the current AWS account.
     *
     * @return a {@link CompletableFuture} that, when completed, contains an {@link ArrayList} of the available namespace names.
     * @throws RuntimeException if an error occurs while listing the namespaces.
     */
    public CompletableFuture<ArrayList<String>> listNameSpacesAsync() {
        ArrayList<String> nameSpaceList = new ArrayList<>();
        ListMetricsRequest request = ListMetricsRequest.builder().build();

        ListMetricsPublisher metricsPaginator = getAsyncClient().listMetricsPaginator(request);
        CompletableFuture<Void> future = metricsPaginator.subscribe(response -> {
            response.metrics().forEach(metric -> {
                String namespace = metric.namespace();
                if (!nameSpaceList.contains(namespace)) {
                    nameSpaceList.add(namespace);
                }
            });
        });

        return future
            .thenApply(ignored -> nameSpaceList)
            .exceptionally(exception -> {
                throw new RuntimeException("Failed to list namespaces: " + exception.getMessage(), exception);
            });
    }
    /**
     * Retrieves the specific metric asynchronously.
     *
     * @param namespace the namespace of the metric to retrieve
     * @return a CompletableFuture that completes with the first dimension of the first metric found in the specified namespace,
     * or throws a RuntimeException if an error occurs or no metrics or dimensions are found
     */
    public CompletableFuture<Dimension> getSpecificMetAsync(String namespace) {
        ListMetricsRequest request = ListMetricsRequest.builder()
            .namespace(namespace)
            .build();

        return getAsyncClient().listMetrics(request).handle((response, exception) -> {
            if (exception != null) {
                logger.info("Error occurred while listing metrics: {} ", exception.getMessage());
                throw new RuntimeException("Failed to retrieve specific metric dimension", exception);
            } else {
                List<Metric> myList = response.metrics();
                if (!myList.isEmpty()) {
                    Metric metric = myList.get(0);
                    if (!metric.dimensions().isEmpty()) {
                        return metric.dimensions().get(0); // Return the first dimension
                    }
                }
                throw new RuntimeException("No metrics or dimensions found");
            }
        });
    }

    public static String readFileAsString(String file) throws IOException {
        return new String(Files.readAllBytes(Paths.get(file)));
    }
}
```
+ API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の以下のトピックを参照してください。
  + [DeleteAlarms](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DeleteAlarms)
  + [DeleteAnomalyDetector](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DeleteAnomalyDetector)
  + [DeleteDashboards](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DeleteDashboards)
  + [DescribeAlarmHistory](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAlarmHistory)
  + [DescribeAlarms](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAlarms)
  + [DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAlarmsForMetric)
  + [DescribeAnomalyDetectors](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAnomalyDetectors)
  + [GetMetricData](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/GetMetricData)
  + [GetMetricStatistics](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/GetMetricStatistics)
  + [GetMetricWidgetImage](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/GetMetricWidgetImage)
  + [ListMetrics](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/ListMetrics)
  + [PutAnomalyDetector](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutAnomalyDetector)
  + [PutDashboard](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutDashboard)
  + [PutMetricAlarm](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutMetricAlarm)
  + [PutMetricData](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutMetricData)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_java_2_topic"></a>

次のコード例は、`DeleteAlarms` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a CloudWatch alarm.
     *
     * @param alarmName the name of the alarm to be deleted
     * @return a {@link CompletableFuture} representing the asynchronous operation to delete the alarm
     * the {@link DeleteAlarmsResponse} is returned when the operation completes successfully,
     * or a {@link RuntimeException} is thrown if the operation fails
     */
    public CompletableFuture<DeleteAlarmsResponse> deleteCWAlarmAsync(String alarmName) {
        DeleteAlarmsRequest request = DeleteAlarmsRequest.builder()
            .alarmNames(alarmName)
            .build();

        return getAsyncClient().deleteAlarms(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to delete the alarm:{} " + alarmName, exception);
                } else {
                    logger.info("Successfully deleted alarm {} ", alarmName);
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteAlarms](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DeleteAlarms)」を参照してください。

### `DeleteAnomalyDetector`
<a name="cloudwatch_DeleteAnomalyDetector_java_2_topic"></a>

次のコード例は、`DeleteAnomalyDetector` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an Anomaly Detector.
     *
     * @param fileName the name of the file containing the Anomaly Detector configuration
     * @return a CompletableFuture that represents the asynchronous deletion of the Anomaly Detector
     */
    public CompletableFuture<DeleteAnomalyDetectorResponse> deleteAnomalyDetectorAsync(String fileName) {
        CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                return new ObjectMapper().readTree(parser); // Return the root node
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        return readFileFuture.thenCompose(rootNode -> {
            String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
            String customMetricName = rootNode.findValue("customMetricName").asText();

            SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder()
                .metricName(customMetricName)
                .namespace(customMetricNamespace)
                .stat("Maximum")
                .build();

            DeleteAnomalyDetectorRequest request = DeleteAnomalyDetectorRequest.builder()
                .singleMetricAnomalyDetector(singleMetricAnomalyDetector)
                .build();

            return getAsyncClient().deleteAnomalyDetector(request);
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Failed to delete the Anomaly Detector", exception);
            } else {
                logger.info("Successfully deleted the Anomaly Detector.");
            }
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteAnomalyDetector](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DeleteAnomalyDetector)」を参照してください。

### `DeleteDashboards`
<a name="cloudwatch_DeleteDashboards_java_2_topic"></a>

次のコード例は、`DeleteDashboards` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes the specified dashboard.
     *
     * @param dashboardName the name of the dashboard to be deleted
     * @return a {@link CompletableFuture} representing the asynchronous operation of deleting the dashboard
     * @throws RuntimeException if the dashboard deletion fails
     */
    public CompletableFuture<DeleteDashboardsResponse> deleteDashboardAsync(String dashboardName) {
        DeleteDashboardsRequest dashboardsRequest = DeleteDashboardsRequest.builder()
            .dashboardNames(dashboardName)
            .build();

        return getAsyncClient().deleteDashboards(dashboardsRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to delete the dashboard: " + dashboardName, exception);
                } else {
                    logger.info("{} was successfully deleted.", dashboardName);
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDashboards](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DeleteDashboards)」を参照してください。

### `DescribeAlarmHistory`
<a name="cloudwatch_DescribeAlarmHistory_java_2_topic"></a>

次のコード例は、`DescribeAlarmHistory` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the alarm history for a given alarm name and date range.
     *
     * @param fileName the path to the JSON file containing the alarm name
     * @param date     the date to start the alarm history search (in the format "yyyy-MM-dd'T'HH:mm:ss'Z'")
     * @return a {@code CompletableFuture<Void>} that completes when the alarm history has been retrieved and processed
     */
    public CompletableFuture<Void> getAlarmHistoryAsync(String fileName, String date) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.findValue("exampleAlarmName").asText(); // Return alarmName from the JSON file
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        // Use the alarm name to describe alarm history with a paginator.
        return readFileFuture.thenCompose(alarmName -> {
            try {
                Instant start = Instant.parse(date);
                Instant endDate = Instant.now();
                DescribeAlarmHistoryRequest historyRequest = DescribeAlarmHistoryRequest.builder()
                    .startDate(start)
                    .endDate(endDate)
                    .alarmName(alarmName)
                    .historyItemType(HistoryItemType.ACTION)
                    .build();

                // Use the paginator to paginate through alarm history pages.
                DescribeAlarmHistoryPublisher historyPublisher = getAsyncClient().describeAlarmHistoryPaginator(historyRequest);
                CompletableFuture<Void> future = historyPublisher
                    .subscribe(response -> response.alarmHistoryItems().forEach(item -> {
                        logger.info("History summary: {}", item.historySummary());
                        logger.info("Timestamp: {}", item.timestamp());
                    }))
                    .whenComplete((result, exception) -> {
                        if (exception != null) {
                            logger.error("Error occurred while getting alarm history: " + exception.getMessage(), exception);
                        } else {
                            logger.info("Successfully retrieved all alarm history.");
                        }
                    });

                // Return the future to the calling code for further handling
                return future;
            } catch (Exception e) {
                throw new RuntimeException("Failed to process alarm history", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error completing alarm history processing", exception);
            }
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeAlarmHistory](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAlarmHistory)」を参照してください。

### `DescribeAlarms`
<a name="cloudwatch_DescribeAlarms_java_2_topic"></a>

次のコード例は、`DescribeAlarms` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Describes the CloudWatch alarms of the 'METRIC_ALARM' type.
     *
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     * of describing the CloudWatch alarms. The future completes when the
     * operation is finished, either successfully or with an error.
     */
    public CompletableFuture<Void> describeAlarmsAsync() {
        List<AlarmType> typeList = new ArrayList<>();
        typeList.add(AlarmType.METRIC_ALARM);
        DescribeAlarmsRequest alarmsRequest = DescribeAlarmsRequest.builder()
            .alarmTypes(typeList)
            .maxRecords(10)
            .build();

        return getAsyncClient().describeAlarms(alarmsRequest)
            .thenAccept(response -> {
                List<MetricAlarm> alarmList = response.metricAlarms();
                for (MetricAlarm alarm : alarmList) {
                    logger.info("Alarm name: {}", alarm.alarmName());
                    logger.info("Alarm description: {} ", alarm.alarmDescription());
                }
            })
            .whenComplete((response, ex) -> {
                if (ex != null) {
                    logger.info("Failed to describe alarms: {}", ex.getMessage());
                } else {
                    logger.info("Successfully described alarms.");
                }
            });
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DescribeAlarms](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAlarms)」を参照してください。**

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_java_2_topic"></a>

次のコード例は、`DescribeAlarmsForMetric` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Checks for a metric alarm in AWS CloudWatch.
     *
     * @param fileName the name of the file containing the JSON configuration for the custom metric
     * @return a {@link CompletableFuture} that completes when the check for the metric alarm is complete
     */
    public CompletableFuture<Void> checkForMetricAlarmAsync(String fileName) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.toString(); // Return JSON as a string for further processing
            } catch (IOException e) {
                throw new RuntimeException("Failed to read file", e);
            }
        });

        return readFileFuture.thenCompose(jsonContent -> {
            try {
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent);
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                DescribeAlarmsForMetricRequest metricRequest = DescribeAlarmsForMetricRequest.builder()
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .build();

                return checkForAlarmAsync(metricRequest, customMetricName, 10);

            } catch (IOException e) {
                throw new RuntimeException("Failed to parse JSON content", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error checking metric alarm", exception);
            }
        });
    }

    // Recursive method to check for the alarm.

    /**
     * Checks for the existence of an alarm asynchronously for the specified metric.
     *
     * @param metricRequest    the request to describe the alarms for the specified metric
     * @param customMetricName the name of the custom metric to check for an alarm
     * @param retries          the number of retries to perform if no alarm is found
     * @return a {@link CompletableFuture} that completes when an alarm is found or the maximum number of retries has been reached
     */
    private static CompletableFuture<Void> checkForAlarmAsync(DescribeAlarmsForMetricRequest metricRequest, String customMetricName, int retries) {
        if (retries == 0) {
            return CompletableFuture.completedFuture(null).thenRun(() ->
                logger.info("No Alarm state found for {} after 10 retries.", customMetricName)
            );
        }

        return (getAsyncClient().describeAlarmsForMetric(metricRequest).thenCompose(response -> {
            if (response.hasMetricAlarms()) {
                logger.info("Alarm state found for {}", customMetricName);
                return CompletableFuture.completedFuture(null); // Alarm found, complete the future
            } else {
                return CompletableFuture.runAsync(() -> {
                    try {
                        Thread.sleep(20000);
                        logger.info(".");
                    } catch (InterruptedException e) {
                        throw new RuntimeException("Interrupted while waiting to retry", e);
                    }
                }).thenCompose(v -> checkForAlarmAsync(metricRequest, customMetricName, retries - 1)); // Recursive call
            }
        }));
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAlarmsForMetric)」を参照してください。

### `DescribeAnomalyDetectors`
<a name="cloudwatch_DescribeAnomalyDetectors_java_2_topic"></a>

次のコード例は、`DescribeAnomalyDetectors` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Describes the anomaly detectors based on the specified JSON file.
     *
     * @param fileName the name of the JSON file containing the custom metric namespace and name
     * @return a {@link CompletableFuture} that completes when the anomaly detectors have been described
     * @throws RuntimeException if there is a failure during the operation, such as when reading or parsing the JSON file,
     *                          or when describing the anomaly detectors
     */
    public CompletableFuture<Void> describeAnomalyDetectorsAsync(String fileName) {
        CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                return new ObjectMapper().readTree(parser);
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        return readFileFuture.thenCompose(rootNode -> {
            try {
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                DescribeAnomalyDetectorsRequest detectorsRequest = DescribeAnomalyDetectorsRequest.builder()
                    .maxResults(10)
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .build();

                return getAsyncClient().describeAnomalyDetectors(detectorsRequest).thenAccept(response -> {
                    List<AnomalyDetector> anomalyDetectorList = response.anomalyDetectors();
                    for (AnomalyDetector detector : anomalyDetectorList) {
                        logger.info("Metric name: {} ", detector.singleMetricAnomalyDetector().metricName());
                        logger.info("State: {} ", detector.stateValue());
                    }
                });
            } catch (RuntimeException e) {
                throw new RuntimeException("Failed to describe anomaly detectors", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error describing anomaly detectors", exception);
            }
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeAnomalyDetectors](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DescribeAnomalyDetectors)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_java_2_topic"></a>

次のコード例は、`DisableAlarmActions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.DisableAlarmActionsRequest;

/**
 * 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 DisableAlarmActions {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <alarmName>

                Where:
                  alarmName - An alarm name to disable (for example, MyAlarm).
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String alarmName = args[0];
        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        disableActions(cw, alarmName);
        cw.close();
    }

    public static void disableActions(CloudWatchClient cw, String alarmName) {
        try {
            DisableAlarmActionsRequest request = DisableAlarmActionsRequest.builder()
                    .alarmNames(alarmName)
                    .build();

            cw.disableAlarmActions(request);
            System.out.printf("Successfully disabled actions on alarm %s", alarmName);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 詳細については、**AWS SDK for Java 2.x API リファレンスの「[DisableAlarmActions](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/DisableAlarmActions)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_java_2_topic"></a>

次のコード例は、`EnableAlarmActions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.CloudWatchClient;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatch.model.EnableAlarmActionsRequest;

/**
 * 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 EnableAlarmActions {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <alarmName>

                Where:
                  alarmName - An alarm name to enable (for example, MyAlarm).
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String alarm = args[0];
        Region region = Region.US_EAST_1;
        CloudWatchClient cw = CloudWatchClient.builder()
                .region(region)
                .build();

        enableActions(cw, alarm);
        cw.close();
    }

    public static void enableActions(CloudWatchClient cw, String alarm) {
        try {
            EnableAlarmActionsRequest request = EnableAlarmActionsRequest.builder()
                    .alarmNames(alarm)
                    .build();

            cw.enableAlarmActions(request);
            System.out.printf("Successfully enabled actions on alarm %s", alarm);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[EnableAlarmActions](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/EnableAlarmActions)」を参照してください。

### `GetMetricData`
<a name="cloudwatch_GetMetricData_java_2_topic"></a>

次のコード例は、`GetMetricData` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves custom metric data from the AWS CloudWatch service.
     *
     * @param fileName the name of the file containing the custom metric information
     * @return a {@link CompletableFuture} that completes when the metric data has been retrieved
     */
    public CompletableFuture<Void> getCustomMetricDataAsync(String fileName) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                // Read values from the JSON file.
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.toString(); // Return JSON as a string for further processing
            } catch (IOException e) {
                throw new RuntimeException("Failed to read file", e);
            }
        });

        return readFileFuture.thenCompose(jsonContent -> {
            try {
                // Parse the JSON string to extract relevant values.
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent);
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                // Set the current time and date range for metric query.
                Instant nowDate = Instant.now();
                long hours = 1;
                long minutes = 30;
                Instant endTime = nowDate.plus(hours, ChronoUnit.HOURS).plus(minutes, ChronoUnit.MINUTES);

                Metric met = Metric.builder()
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .build();

                MetricStat metStat = MetricStat.builder()
                    .stat("Maximum")
                    .period(60)  // Assuming period in seconds
                    .metric(met)
                    .build();

                MetricDataQuery dataQuery = MetricDataQuery.builder()
                    .metricStat(metStat)
                    .id("foo2")
                    .returnData(true)
                    .build();

                List<MetricDataQuery> dq = new ArrayList<>();
                dq.add(dataQuery);

                GetMetricDataRequest getMetricDataRequest = GetMetricDataRequest.builder()
                    .maxDatapoints(10)
                    .scanBy(ScanBy.TIMESTAMP_DESCENDING)
                    .startTime(nowDate)
                    .endTime(endTime)
                    .metricDataQueries(dq)
                    .build();

                // Call the async method for CloudWatch data retrieval.
                return getAsyncClient().getMetricData(getMetricDataRequest);

            } catch (IOException e) {
                throw new RuntimeException("Failed to parse JSON content", e);
            }
        }).thenAccept(response -> {
            List<MetricDataResult> data = response.metricDataResults();
            for (MetricDataResult item : data) {
                logger.info("The label is: {}", item.label());
                logger.info("The status code is: {}", item.statusCode().toString());
            }
        }).exceptionally(exception -> {
            throw new RuntimeException("Failed to get metric data", exception);
        });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetMetricData](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/GetMetricData)」を参照してください。

### `GetMetricStatistics`
<a name="cloudwatch_GetMetricStatistics_java_2_topic"></a>

次のコード例は、`GetMetricStatistics` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves and displays metric statistics for the specified parameters.
     *
     * @param nameSpace    the namespace for the metric
     * @param metVal       the name of the metric
     * @param metricOption the statistic to retrieve for the metric (e.g., "Maximum", "Average")
     * @param date         the date for which to retrieve the metric statistics, in the format "yyyy-MM-dd'T'HH:mm:ss'Z'"
     * @param myDimension  the dimension(s) to filter the metric statistics by
     * @return a {@link CompletableFuture} that completes when the metric statistics have been retrieved and displayed
     */
    public CompletableFuture<GetMetricStatisticsResponse> getAndDisplayMetricStatisticsAsync(String nameSpace, String metVal,
                                                                                             String metricOption, String date, Dimension myDimension) {

        Instant start = Instant.parse(date);
        Instant endDate = Instant.now();

        // Building the request for metric statistics.
        GetMetricStatisticsRequest statisticsRequest = GetMetricStatisticsRequest.builder()
            .endTime(endDate)
            .startTime(start)
            .dimensions(myDimension)
            .metricName(metVal)
            .namespace(nameSpace)
            .period(86400) // 1 day period
            .statistics(Statistic.fromValue(metricOption))
            .build();

        return getAsyncClient().getMetricStatistics(statisticsRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    List<Datapoint> data = response.datapoints();
                    if (!data.isEmpty()) {
                        for (Datapoint datapoint : data) {
                            logger.info("Timestamp: {} Maximum value: {}", datapoint.timestamp(), datapoint.maximum());
                        }
                    } else {
                        logger.info("The returned data list is empty");
                    }
                } else {
                    logger.info("Failed to get metric statistics: {} ", exception.getMessage());
                }
            })
            .exceptionally(exception -> {
                throw new RuntimeException("Error while getting metric statistics: " + exception.getMessage(), exception);
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetMetricStatistics](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/GetMetricStatistics)」を参照してください。

### `GetMetricWidgetImage`
<a name="cloudwatch_GetMetricWidgetImage_java_2_topic"></a>

次のコード例は、`GetMetricWidgetImage` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves and saves a custom metric image to a file.
     *
     * @param fileName the name of the file to save the metric image to
     * @return a {@link CompletableFuture} that completes when the image has been saved to the file
     */
    public CompletableFuture<Void> downloadAndSaveMetricImageAsync(String fileName) {
        logger.info("Getting Image data for custom metric.");
        String myJSON = """
              {
                  "title": "Example Metric Graph",
                  "view": "timeSeries",
                  "stacked ": false,
                  "period": 10,
                  "width": 1400,
                  "height": 600,
                  "metrics": [
                      [
                      "AWS/Billing",
                      "EstimatedCharges",
                      "Currency",
                      "USD"
                     ]
                  ]
              }
            """;

        GetMetricWidgetImageRequest imageRequest = GetMetricWidgetImageRequest.builder()
            .metricWidget(myJSON)
            .build();

        return getAsyncClient().getMetricWidgetImage(imageRequest)
            .thenCompose(response -> {
                SdkBytes sdkBytes = response.metricWidgetImage();
                byte[] bytes = sdkBytes.asByteArray();
                return CompletableFuture.runAsync(() -> {
                    try {
                        File outputFile = new File(fileName);
                        try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
                            outputStream.write(bytes);
                        }
                    } catch (IOException e) {
                        throw new RuntimeException("Failed to write image to file", e);
                    }
                });
            })
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Error getting and saving metric image", exception);
                } else {
                    logger.info("Image data saved successfully to {}", fileName);
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetMetricWidgetImage](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/GetMetricWidgetImage)」を参照してください。

### `ListDashboards`
<a name="cloudwatch_ListDashboards_java_2_topic"></a>

次のコード例は、`ListDashboards` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists the available dashboards.
     *
     * @return a {@link CompletableFuture} that completes when the operation is finished.
     * The future will complete exceptionally if an error occurs while listing the dashboards.
     */
    public CompletableFuture<Void> listDashboardsAsync() {
        ListDashboardsRequest listDashboardsRequest = ListDashboardsRequest.builder().build();
        ListDashboardsPublisher paginator = getAsyncClient().listDashboardsPaginator(listDashboardsRequest);
        return paginator.subscribe(response -> {
            response.dashboardEntries().forEach(entry -> {
                logger.info("Dashboard name is: {} ", entry.dashboardName());
                logger.info("Dashboard ARN is: {} ", entry.dashboardArn());
            });
        }).exceptionally(ex -> {
            logger.info("Failed to list dashboards: {} ", ex.getMessage());
            throw new RuntimeException("Error occurred while listing dashboards", ex);
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListDashboards](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/ListDashboards)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_java_2_topic"></a>

次のコード例は、`ListMetrics` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves a list of metric names for the specified namespace.
     *
     * @param namespace the namespace for which to retrieve the metric names
     * @return a {@link CompletableFuture} that, when completed, contains an {@link ArrayList} of
     * the metric names in the specified namespace
     * @throws RuntimeException if an error occurs while listing the metrics
     */
    public CompletableFuture<ArrayList<String>> listMetsAsync(String namespace) {
        ListMetricsRequest request = ListMetricsRequest.builder()
            .namespace(namespace)
            .build();

        ListMetricsPublisher metricsPaginator = getAsyncClient().listMetricsPaginator(request);
        Set<String> metSet = new HashSet<>();
        CompletableFuture<Void> future = metricsPaginator.subscribe(response -> {
            response.metrics().forEach(metric -> {
                String metricName = metric.metricName();
                metSet.add(metricName);
            });
        });

        return future
            .thenApply(ignored -> new ArrayList<>(metSet))
            .exceptionally(exception -> {
                throw new RuntimeException("Failed to list metrics: " + exception.getMessage(), exception);
            });
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[ListMetrics](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/ListMetrics)」を参照してください。

### `PutAnomalyDetector`
<a name="cloudwatch_PutAnomalyDetector_java_2_topic"></a>

次のコード例は、`PutAnomalyDetector` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Adds an anomaly detector for the given file.
     *
     * @param fileName the name of the file containing the anomaly detector configuration
     * @return a {@link CompletableFuture} that completes when the anomaly detector has been added
     */
    public CompletableFuture<Void> addAnomalyDetectorAsync(String fileName) {
        CompletableFuture<JsonNode> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                return new ObjectMapper().readTree(parser); // Return the root node
            } catch (IOException e) {
                throw new RuntimeException("Failed to read or parse the file", e);
            }
        });

        return readFileFuture.thenCompose(rootNode -> {
            try {
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();

                SingleMetricAnomalyDetector singleMetricAnomalyDetector = SingleMetricAnomalyDetector.builder()
                    .metricName(customMetricName)
                    .namespace(customMetricNamespace)
                    .stat("Maximum")
                    .build();

                PutAnomalyDetectorRequest anomalyDetectorRequest = PutAnomalyDetectorRequest.builder()
                    .singleMetricAnomalyDetector(singleMetricAnomalyDetector)
                    .build();

                return getAsyncClient().putAnomalyDetector(anomalyDetectorRequest).thenAccept(response -> {
                    logger.info("Added anomaly detector for metric {}", customMetricName);
                });
            } catch (Exception e) {
                throw new RuntimeException("Failed to create anomaly detector", e);
            }
        }).whenComplete((result, exception) -> {
            if (exception != null) {
                throw new RuntimeException("Error adding anomaly detector", exception);
            }
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutAnomalyDetector](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutAnomalyDetector)」を参照してください。

### `PutDashboard`
<a name="cloudwatch_PutDashboard_java_2_topic"></a>

次のコード例は、`PutDashboard` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new dashboard with the specified name and metrics from the given file.
     *
     * @param dashboardName the name of the dashboard to be created
     * @param fileName      the name of the file containing the dashboard body
     * @return a {@link CompletableFuture} representing the asynchronous operation of creating the dashboard
     * @throws IOException if there is an error reading the dashboard body from the file
     */
    public CompletableFuture<PutDashboardResponse> createDashboardWithMetricsAsync(String dashboardName, String fileName) throws IOException {
        String dashboardBody = readFileAsString(fileName);
        PutDashboardRequest dashboardRequest = PutDashboardRequest.builder()
            .dashboardName(dashboardName)
            .dashboardBody(dashboardBody)
            .build();

        return getAsyncClient().putDashboard(dashboardRequest)
            .handle((response, ex) -> {
                if (ex != null) {
                    logger.info("Failed to create dashboard: {}", ex.getMessage());
                    throw new RuntimeException("Dashboard creation failed", ex);
                } else {
                    // Handle the normal response case
                    logger.info("{} was successfully created.", dashboardName);
                    List<DashboardValidationMessage> messages = response.dashboardValidationMessages();
                    if (messages.isEmpty()) {
                        logger.info("There are no messages in the new Dashboard.");
                    } else {
                        for (DashboardValidationMessage message : messages) {
                            logger.info("Message: {}", message.message());
                        }
                    }
                    return response; // Return the response for further use
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutDashboard](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutDashboard)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_java_2_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an alarm based on the configuration provided in a JSON file.
     *
     * @param fileName the name of the JSON file containing the alarm configuration
     * @return a CompletableFuture that represents the asynchronous operation of creating the alarm
     * @throws RuntimeException if an exception occurs while reading the JSON file or creating the alarm
     */
    public CompletableFuture<String> createAlarmAsync(String fileName) {
        com.fasterxml.jackson.databind.JsonNode rootNode;
        try {
            JsonParser parser = new JsonFactory().createParser(new File(fileName));
            rootNode = new ObjectMapper().readTree(parser);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read the alarm configuration file", e);
        }

        // Extract values from the JSON node.
        String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
        String customMetricName = rootNode.findValue("customMetricName").asText();
        String alarmName = rootNode.findValue("exampleAlarmName").asText();
        String emailTopic = rootNode.findValue("emailTopic").asText();
        String accountId = rootNode.findValue("accountId").asText();
        String region = rootNode.findValue("region").asText();

        // Create a List for alarm actions.
        List<String> alarmActions = new ArrayList<>();
        alarmActions.add("arn:aws:sns:" + region + ":" + accountId + ":" + emailTopic);

        PutMetricAlarmRequest alarmRequest = PutMetricAlarmRequest.builder()
            .alarmActions(alarmActions)
            .alarmDescription("Example metric alarm")
            .alarmName(alarmName)
            .comparisonOperator(ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD)
            .threshold(100.00)
            .metricName(customMetricName)
            .namespace(customMetricNamespace)
            .evaluationPeriods(1)
            .period(10)
            .statistic("Maximum")
            .datapointsToAlarm(1)
            .treatMissingData("ignore")
            .build();

        // Call the putMetricAlarm asynchronously and handle the result.
        return getAsyncClient().putMetricAlarm(alarmRequest)
            .handle((response, ex) -> {
                if (ex != null) {
                    logger.info("Failed to create alarm: {}", ex.getMessage());
                    throw new RuntimeException("Failed to create alarm", ex);
                } else {
                    logger.info("{} was successfully created!", alarmName);
                    return alarmName;
                }
            });
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[PutMetricAlarm](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutMetricAlarm)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_java_2_topic"></a>

次のコード例は、`PutMetricData` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Adds metric data for an alarm asynchronously.
     *
     * @param fileName the name of the JSON file containing the metric data
     * @return a CompletableFuture that asynchronously returns the PutMetricDataResponse
     */
    public CompletableFuture<PutMetricDataResponse> addMetricDataForAlarmAsync(String fileName) {
        CompletableFuture<String> readFileFuture = CompletableFuture.supplyAsync(() -> {
            try {
                JsonParser parser = new JsonFactory().createParser(new File(fileName));
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
                return rootNode.toString(); // Return JSON as a string for further processing
            } catch (IOException e) {
                throw new RuntimeException("Failed to read file", e);
            }
        });

        return readFileFuture.thenCompose(jsonContent -> {
            try {
                com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(jsonContent);
                String customMetricNamespace = rootNode.findValue("customMetricNamespace").asText();
                String customMetricName = rootNode.findValue("customMetricName").asText();
                Instant instant = Instant.now();

                // Create MetricDatum objects.
                MetricDatum datum1 = MetricDatum.builder()
                    .metricName(customMetricName)
                    .unit(StandardUnit.NONE)
                    .value(1001.00)
                    .timestamp(instant)
                    .build();

                MetricDatum datum2 = MetricDatum.builder()
                    .metricName(customMetricName)
                    .unit(StandardUnit.NONE)
                    .value(1002.00)
                    .timestamp(instant)
                    .build();

                List<MetricDatum> metricDataList = new ArrayList<>();
                metricDataList.add(datum1);
                metricDataList.add(datum2);

                // Build the PutMetricData request.
                PutMetricDataRequest request = PutMetricDataRequest.builder()
                    .namespace(customMetricNamespace)
                    .metricData(metricDataList)
                    .build();

                // Send the request asynchronously.
                return getAsyncClient().putMetricData(request);

            } catch (IOException e) {
                CompletableFuture<PutMetricDataResponse> failedFuture = new CompletableFuture<>();
                failedFuture.completeExceptionally(new RuntimeException("Failed to parse JSON content", e));
                return failedFuture;
            }
        }).whenComplete((response, exception) -> {
            if (exception != null) {
                logger.error("Failed to put metric data: " + exception.getMessage(), exception);
            } else {
                logger.info("Added metric values for metric.");
            }
        });
    }
```
+  API の詳細については、「**AWS SDK for Java 2.x API リファレンス」の「[PutMetricData](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutMetricData)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DynamoDB のパフォーマンスのモニタリング
<a name="cross_MonitorDynamoDB_java_2_topic"></a>

次のコード例は、DynamoDB のパフォーマンスをモニタリングするように、アプリケーションを設定する方法を示しています。

**SDK for Java 2.x**  
 この例では、DynamoDB のパフォーマンスをモニタリングするように Java アプリケーションを設定する方法を示します。アプリケーションからメトリクスデータを CloudWatch に送信してパフォーマンスをモニタリングできます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/monitor_dynamodb) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch
+ DynamoDB

# SDK for Java 2.x を使用した CloudWatch Events の例
<a name="java_2_cloudwatch-events_code_examples"></a>

次のコード例は、CloudWatch Events AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="cloudwatch-events_PutEvents_java_2_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutEventsRequestEntry;

/**
 * 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 PutEvents {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                   <resourceArn>

                Where:
                   resourceArn - An Amazon Resource Name (ARN) related to the events.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String resourceArn = args[0];
        CloudWatchEventsClient cwe = CloudWatchEventsClient.builder()
                .build();

        putCWEvents(cwe, resourceArn);
        cwe.close();
    }

    public static void putCWEvents(CloudWatchEventsClient cwe, String resourceArn) {
        try {
            final String EVENT_DETAILS = "{ \"key1\": \"value1\", \"key2\": \"value2\" }";

            PutEventsRequestEntry requestEntry = PutEventsRequestEntry.builder()
                    .detail(EVENT_DETAILS)
                    .detailType("sampleSubmitted")
                    .resources(resourceArn)
                    .source("aws-sdk-java-cloudwatch-example")
                    .build();

            PutEventsRequest request = PutEventsRequest.builder()
                    .entries(requestEntry)
                    .build();

            cwe.putEvents(request);
            System.out.println("Successfully put CloudWatch event");

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutEvents)」を参照してください。

### `PutRule`
<a name="cloudwatch-events_PutRule_java_2_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.PutRuleResponse;
import software.amazon.awssdk.services.cloudwatchevents.model.RuleState;

/**
 * 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 PutRule {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <ruleName> roleArn>\s

                Where:
                  ruleName - A rule name (for example, myrule).
                  roleArn - A role ARN value (for example, arn:aws:iam::xxxxxx047983:user/MyUser).
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String ruleName = args[0];
        String roleArn = args[1];
        CloudWatchEventsClient cwe = CloudWatchEventsClient.builder()
                .build();

        putCWRule(cwe, ruleName, roleArn);
        cwe.close();
    }

    public static void putCWRule(CloudWatchEventsClient cwe, String ruleName, String roleArn) {
        try {
            PutRuleRequest request = PutRuleRequest.builder()
                    .name(ruleName)
                    .roleArn(roleArn)
                    .scheduleExpression("rate(5 minutes)")
                    .state(RuleState.ENABLED)
                    .build();

            PutRuleResponse response = cwe.putRule(request);
            System.out.printf(
                    "Successfully created CloudWatch events rule %s with arn %s",
                    roleArn, response.ruleArn());

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutRule)」を参照してください。

### `PutTargets`
<a name="cloudwatch-events_PutTargets_java_2_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchevents.CloudWatchEventsClient;
import software.amazon.awssdk.services.cloudwatchevents.model.PutTargetsRequest;
import software.amazon.awssdk.services.cloudwatchevents.model.Target;

/**
 * To run this Java V2 code example, ensure that you have setup 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 PutTargets {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <ruleName> <functionArn> <targetId>\s

                Where:
                  ruleName - A rule name (for example, myrule).
                  functionArn - An AWS Lambda function ARN (for example, arn:aws:lambda:us-west-2:xxxxxx047983:function:lamda1).
                  targetId - A target id value.
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String ruleName = args[0];
        String functionArn = args[1];
        String targetId = args[2];
        CloudWatchEventsClient cwe = CloudWatchEventsClient.builder()
                .build();

        putCWTargets(cwe, ruleName, functionArn, targetId);
        cwe.close();
    }

    public static void putCWTargets(CloudWatchEventsClient cwe, String ruleName, String functionArn, String targetId) {
        try {
            Target target = Target.builder()
                    .arn(functionArn)
                    .id(targetId)
                    .build();

            PutTargetsRequest request = PutTargetsRequest.builder()
                    .targets(target)
                    .rule(ruleName)
                    .build();

            cwe.putTargets(request);
            System.out.printf(
                    "Successfully created CloudWatch events target for rule %s",
                    ruleName);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/goto/SdkForJavaV2/monitoring-2010-08-01/PutTargets)」を参照してください。

# SDK for Java 2.x を使用した CloudWatch Logs
<a name="java_2_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DeleteSubscriptionFilter`
<a name="cloudwatch-logs_DeleteSubscriptionFilter_java_2_topic"></a>

次のコード例は、`DeleteSubscriptionFilter` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.DeleteSubscriptionFilterRequest;

/**
 * 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 DeleteSubscriptionFilter {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <filter> <logGroup>

                Where:
                  filter - The name of the subscription filter (for example, MyFilter).
                  logGroup - The name of the log group. (for example, testgroup).
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String filter = args[0];
        String logGroup = args[1];
        CloudWatchLogsClient logs = CloudWatchLogsClient.builder()
                .build();

        deleteSubFilter(logs, filter, logGroup);
        logs.close();
    }

    public static void deleteSubFilter(CloudWatchLogsClient logs, String filter, String logGroup) {
        try {
            DeleteSubscriptionFilterRequest request = DeleteSubscriptionFilterRequest.builder()
                    .filterName(filter)
                    .logGroupName(logGroup)
                    .build();

            logs.deleteSubscriptionFilter(request);
            System.out.printf("Successfully deleted CloudWatch logs subscription filter %s", filter);

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteSubscriptionFilter](https://docs.aws.amazon.com/goto/SdkForJavaV2/logs-2014-03-28/DeleteSubscriptionFilter)」を参照してください。

### `DescribeLogStreams`
<a name="cloudwatch-logs_DescribeLogStreams_java_2_topic"></a>

次のコード例は、`DescribeLogStreams` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。
指定されたプレフィックスに一致する、指定されたロググループ内のログストリームを検索します。  

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CloudWatchLogsSearch {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <logGroupName> <logStreamName> 

                Where:
                  logGroupName - The name of the log group (for example, WeathertopJavaContainerLogs).
                  logStreamName - The name of the log stream (for example, weathertop-java-stream).
                  pattern - the pattern to use (for example, INFO) 
                  
                """;

        if (args.length != 3) {
            System.out.print(usage);
            System.exit(1);
        }

        String logGroupName = args[0] ;
        String logStreamName = args[1] ;
        String pattern = args[2] ;

        CloudWatchLogsClient cwlClient = CloudWatchLogsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        searchLogStreamsAndFilterEvents(cwlClient, logGroupName, logStreamName, pattern);
    }

    /**
     * Searches for log streams with a specific prefix within a log group and filters log events based on a specified pattern.
     *
     * @param cwlClient       the CloudWatchLogsClient used to interact with AWS CloudWatch Logs
     * @param logGroupName    the name of the log group to search within
     * @param logStreamPrefix the prefix of the log streams to search for
     * @param pattern         the pattern to filter log events by
     */
    public static void searchLogStreamsAndFilterEvents(CloudWatchLogsClient cwlClient, String logGroupName, String logStreamPrefix, String pattern) {
        DescribeLogStreamsRequest describeLogStreamsRequest = DescribeLogStreamsRequest.builder()
                .logGroupName(logGroupName)
                .logStreamNamePrefix(logStreamPrefix)
                .build();

        DescribeLogStreamsResponse describeLogStreamsResponse = cwlClient.describeLogStreams(describeLogStreamsRequest);
        List<LogStream> logStreams = describeLogStreamsResponse.logStreams();

        for (LogStream logStream : logStreams) {
            String logStreamName = logStream.logStreamName();
            System.out.println("Searching in log stream: " + logStreamName);

            FilterLogEventsRequest filterLogEventsRequest = FilterLogEventsRequest.builder()
                    .logGroupName(logGroupName)
                    .logStreamNames(logStreamName)
                    .filterPattern(pattern)
                    .build();

            FilterLogEventsResponse filterLogEventsResponse = cwlClient.filterLogEvents(filterLogEventsRequest);

            for (FilteredLogEvent event : filterLogEventsResponse.events()) {
                System.out.println(event.message());
            }

            System.out.println("--------------------------------------------------"); // Separator for better readability
        }
    }
}
```
指定されたロググループ内の最新のログストリームに関するメタデータを出力します。  

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CloudWatchLogQuery {
    public static void main(final String[] args) {
        final String usage = """
                Usage:
                  <logGroupName>

                Where:
                  logGroupName - The name of the log group (for example, /aws/lambda/ChatAIHandler).
                """;

        if (args.length != 1) {
            System.out.print(usage);
            System.exit(1);
        }

        String logGroupName = "/aws/lambda/ChatAIHandler" ; //args[0];
        CloudWatchLogsClient logsClient = CloudWatchLogsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        describeMostRecentLogStream(logsClient, logGroupName);
    }

    /**
     * Describes and prints metadata about the most recent log stream in the specified log group.
     *
     * @param logsClient   the CloudWatchLogsClient used to interact with AWS CloudWatch Logs
     * @param logGroupName the name of the log group
     */
    public static void describeMostRecentLogStream(CloudWatchLogsClient logsClient, String logGroupName) {
        DescribeLogStreamsRequest streamsRequest = DescribeLogStreamsRequest.builder()
                .logGroupName(logGroupName)
                .orderBy(OrderBy.LAST_EVENT_TIME)
                .descending(true)
                .limit(1)
                .build();

        try {
            DescribeLogStreamsResponse streamsResponse = logsClient.describeLogStreams(streamsRequest);
            List<LogStream> logStreams = streamsResponse.logStreams();

            if (logStreams.isEmpty()) {
                System.out.println("No log streams found for log group: " + logGroupName);
                return;
            }

            LogStream stream = logStreams.get(0);
            System.out.println("Most Recent Log Stream:");
            System.out.println("  Name: " + stream.logStreamName());
            System.out.println("  ARN: " + stream.arn());
            System.out.println("  Creation Time: " + stream.creationTime());
            System.out.println("  First Event Time: " + stream.firstEventTimestamp());
            System.out.println("  Last Event Time: " + stream.lastEventTimestamp());
            System.out.println("  Stored Bytes: " + stream.storedBytes());
            System.out.println("  Upload Sequence Token: " + stream.uploadSequenceToken());

        } catch (CloudWatchLogsException e) {
            System.err.println("Failed to describe log stream: " + e.awsErrorDetails().errorMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeLogStreams](https://docs.aws.amazon.com/goto/SdkForJavaV2/logs-2014-03-28/DescribeLogStreams)」を参照してください。

### `DescribeSubscriptionFilters`
<a name="cloudwatch-logs_DescribeSubscriptionFilters_java_2_topic"></a>

次のコード例は、`DescribeSubscriptionFilters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeSubscriptionFiltersResponse;
import software.amazon.awssdk.services.cloudwatchlogs.model.SubscriptionFilter;

/**
 * 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 DescribeSubscriptionFilters {
    public static void main(String[] args) {

        final String usage = """

                Usage:
                  <logGroup>

                Where:
                  logGroup - A log group name (for example, myloggroup).
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String logGroup = args[0];
        CloudWatchLogsClient logs = CloudWatchLogsClient.builder()
                .credentialsProvider(ProfileCredentialsProvider.create())
                .build();

        describeFilters(logs, logGroup);
        logs.close();
    }

    public static void describeFilters(CloudWatchLogsClient logs, String logGroup) {
        try {
            boolean done = false;
            String newToken = null;

            while (!done) {
                DescribeSubscriptionFiltersResponse response;
                if (newToken == null) {
                    DescribeSubscriptionFiltersRequest request = DescribeSubscriptionFiltersRequest.builder()
                            .logGroupName(logGroup)
                            .limit(1).build();

                    response = logs.describeSubscriptionFilters(request);
                } else {
                    DescribeSubscriptionFiltersRequest request = DescribeSubscriptionFiltersRequest.builder()
                            .nextToken(newToken)
                            .logGroupName(logGroup)
                            .limit(1).build();
                    response = logs.describeSubscriptionFilters(request);
                }

                for (SubscriptionFilter filter : response.subscriptionFilters()) {
                    System.out.printf("Retrieved filter with name %s, " + "pattern %s " + "and destination arn %s",
                            filter.filterName(),
                            filter.filterPattern(),
                            filter.destinationArn());
                }

                if (response.nextToken() == null) {
                    done = true;
                } else {
                    newToken = response.nextToken();
                }
            }

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.printf("Done");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeSubscriptionFilters](https://docs.aws.amazon.com/goto/SdkForJavaV2/logs-2014-03-28/DescribeSubscriptionFilters)」を参照してください。

### `GetLogEvents`
<a name="cloudwatch-logs_GetLogEvents_java_2_topic"></a>

次のコード例は、`GetLogEvents` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatch.model.CloudWatchException;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.DescribeLogStreamsResponse;
import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.GetLogEventsResponse;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

/**
 * 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 GetLogEvents {

    public static void main(String[] args) {

        final String usage = """

                Usage:
                  <logGroupName> <logStreamName> 

                Where:
                  logGroupName - The name of the log group (for example, myloggroup).
                  logStreamName - The name of the log stream (for example, mystream).
                  
                """;

       // if (args.length != 2) {
       //     System.out.print(usage);
       //     System.exit(1);
//        }

        String logGroupName = "WeathertopJavaContainerLogs" ; //args[0];
        String logStreamName = "weathertop-java-stream" ; //args[1];

        Region region = Region.US_EAST_1 ;
        CloudWatchLogsClient cloudWatchLogsClient = CloudWatchLogsClient.builder()
                .region(region)
                .build();

        getCWLogEvents(cloudWatchLogsClient, logGroupName, logStreamName);
        cloudWatchLogsClient.close();
    }

    public static void getCWLogEvents(CloudWatchLogsClient cloudWatchLogsClient,
                                      String logGroupName,
                                      String logStreamPrefix) {
        try {
            // First, find the exact log stream name
            DescribeLogStreamsRequest describeRequest = DescribeLogStreamsRequest.builder()
                    .logGroupName(logGroupName)
                    .logStreamNamePrefix(logStreamPrefix)
                    .limit(1) // get the first matching stream
                    .build();

            DescribeLogStreamsResponse describeResponse = cloudWatchLogsClient.describeLogStreams(describeRequest);

            if (describeResponse.logStreams().isEmpty()) {
                System.out.println("No matching log streams found for prefix: " + logStreamPrefix);
                return;
            }

            String exactLogStreamName = describeResponse.logStreams().get(0).logStreamName();
            System.out.println("Using exact log stream: " + exactLogStreamName);

            long startTime = Instant.now().minus(7, ChronoUnit.DAYS).toEpochMilli();
            long endTime = Instant.now().toEpochMilli();

            GetLogEventsRequest getLogEventsRequest = GetLogEventsRequest.builder()
                    .logGroupName(logGroupName)
                    .logStreamName(exactLogStreamName) // <-- exact name, not prefix
                    .startTime(startTime)
                    .endTime(endTime)
                    .startFromHead(true)
                    .build();

            GetLogEventsResponse response = cloudWatchLogsClient.getLogEvents(getLogEventsRequest);

            if (response.events().isEmpty()) {
                System.out.println("No log events found in the past 7 days.");
            } else {
                response.events().forEach(e -> System.out.println(e.message()));
            }

        } catch (CloudWatchException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetLogEvents](https://docs.aws.amazon.com/goto/SdkForJavaV2/logs-2014-03-28/GetLogEvents)」を参照してください。

### `PutSubscriptionFilter`
<a name="cloudwatch-logs_PutSubscriptionFilter_java_2_topic"></a>

次のコード例は、`PutSubscriptionFilter` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException;
import software.amazon.awssdk.services.cloudwatchlogs.model.PutSubscriptionFilterRequest;

/**
 * Before running this code example, you need to grant permission to CloudWatch
 * Logs the right to execute your Lambda function.
 * To perform this task, you can use this CLI command:
 *
 * aws lambda add-permission --function-name "lamda1" --statement-id "lamda1"
 * --principal "logs.us-west-2.amazonaws.com" --action "lambda:InvokeFunction"
 * --source-arn "arn:aws:logs:us-west-2:111111111111:log-group:testgroup:*"
 * --source-account "111111111111"
 *
 * Make sure you replace the function name with your function name and replace
 * '111111111111' with your account details.
 * For more information, see "Subscription Filters with AWS Lambda" in the
 * Amazon CloudWatch Logs Guide.
 *
 *
 * Also, 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 PutSubscriptionFilter {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <filter> <pattern> <logGroup> <functionArn>\s

                Where:
                  filter - A filter name (for example, myfilter).
                  pattern - A filter pattern (for example, ERROR).
                  logGroup - A log group name (testgroup).
                  functionArn - An AWS Lambda function ARN (for example, arn:aws:lambda:us-west-2:111111111111:function:lambda1) .
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String filter = args[0];
        String pattern = args[1];
        String logGroup = args[2];
        String functionArn = args[3];
        Region region = Region.US_WEST_2;
        CloudWatchLogsClient cwl = CloudWatchLogsClient.builder()
                .region(region)
                .build();

        putSubFilters(cwl, filter, pattern, logGroup, functionArn);
        cwl.close();
    }

    public static void putSubFilters(CloudWatchLogsClient cwl,
            String filter,
            String pattern,
            String logGroup,
            String functionArn) {

        try {
            PutSubscriptionFilterRequest request = PutSubscriptionFilterRequest.builder()
                    .filterName(filter)
                    .filterPattern(pattern)
                    .logGroupName(logGroup)
                    .destinationArn(functionArn)
                    .build();

            cwl.putSubscriptionFilter(request);
            System.out.printf(
                    "Successfully created CloudWatch logs subscription filter %s",
                    filter);

        } catch (CloudWatchLogsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutSubscriptionFilter](https://docs.aws.amazon.com/goto/SdkForJavaV2/logs-2014-03-28/PutSubscriptionFilter)」を参照してください。

### `StartLiveTail`
<a name="cloudwatch-logs_StartLiveTail_java_2_topic"></a>

次のコード例は、`StartLiveTail` を使用する方法を示しています。

**SDK for Java 2.x**  
必要なファイルを含めます。  

```
import io.reactivex.FlowableSubscriber;
import io.reactivex.annotations.NonNull;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsAsyncClient;
import software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionLogEvent;
import software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionStart;
import software.amazon.awssdk.services.cloudwatchlogs.model.LiveTailSessionUpdate;
import software.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailRequest;
import software.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailResponseHandler;
import software.amazon.awssdk.services.cloudwatchlogs.model.CloudWatchLogsException;
import software.amazon.awssdk.services.cloudwatchlogs.model.StartLiveTailResponseStream;

import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
```
Live Tail セッションのイベントを処理します。  

```
    private static StartLiveTailResponseHandler getStartLiveTailResponseStreamHandler(
            AtomicReference<Subscription> subscriptionAtomicReference) {
        return StartLiveTailResponseHandler.builder()
            .onResponse(r -> System.out.println("Received initial response"))
            .onError(throwable -> {
                CloudWatchLogsException e = (CloudWatchLogsException) throwable.getCause();
                System.err.println(e.awsErrorDetails().errorMessage());
                System.exit(1);
            })
            .subscriber(() -> new FlowableSubscriber<>() {
                @Override
                public void onSubscribe(@NonNull Subscription s) {
                    subscriptionAtomicReference.set(s);
                    s.request(Long.MAX_VALUE);
                }

                @Override
                public void onNext(StartLiveTailResponseStream event) {
                    if (event instanceof LiveTailSessionStart) {
                        LiveTailSessionStart sessionStart = (LiveTailSessionStart) event;
                        System.out.println(sessionStart);
                    } else if (event instanceof LiveTailSessionUpdate) {
                        LiveTailSessionUpdate sessionUpdate = (LiveTailSessionUpdate) event;
                        List<LiveTailSessionLogEvent> logEvents = sessionUpdate.sessionResults();
                        logEvents.forEach(e -> {
                            long timestamp = e.timestamp();
                            Date date = new Date(timestamp);
                            System.out.println("[" + date + "] " + e.message());
                        });
                    } else {
                        throw CloudWatchLogsException.builder().message("Unknown event type").build();
                    }
                }

                @Override
                public void onError(Throwable throwable) {
                    System.out.println(throwable.getMessage());
                    System.exit(1);
                }

                @Override
                public void onComplete() {
                    System.out.println("Completed Streaming Session");
                }
            })
            .build();
    }
```
Live Tail セッションを開始します。  

```
        CloudWatchLogsAsyncClient cloudWatchLogsAsyncClient =
                CloudWatchLogsAsyncClient.builder()
                    .credentialsProvider(ProfileCredentialsProvider.create())
                    .build();

        StartLiveTailRequest request =
                StartLiveTailRequest.builder()
                    .logGroupIdentifiers(logGroupIdentifiers)
                    .logStreamNames(logStreamNames)
                    .logEventFilterPattern(logEventFilterPattern)
                    .build();

        /* Create a reference to store the subscription */ 
        final AtomicReference<Subscription> subscriptionAtomicReference = new AtomicReference<>(null);

        cloudWatchLogsAsyncClient.startLiveTail(request, getStartLiveTailResponseStreamHandler(subscriptionAtomicReference));
```
一定時間が経過したら Live Tail セッションを停止します。  

```
        /* Set a timeout for the session and cancel the subscription. This will:
         * 1). Close the stream
         * 2). Stop the Live Tail session
         */
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (subscriptionAtomicReference.get() != null) {
            subscriptionAtomicReference.get().cancel();
            System.out.println("Subscription to stream closed");
        }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[StartLiveTail](https://docs.aws.amazon.com/goto/SdkForJavaV2/logs-2014-03-28/StartLiveTail)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_java_2_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda Java ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_scheduled_events) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

# SDK for Java 2.x を使用した Amazon Cognito ID の例
<a name="java_2_cognito-identity_code_examples"></a>

次のコード例は、Amazon Cognito Identity AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateIdentityPool`
<a name="cognito-identity_CreateIdentityPool_java_2_topic"></a>

次のコード例は、`CreateIdentityPool` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;
import software.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolRequest;
import software.amazon.awssdk.services.cognitoidentity.model.CreateIdentityPoolResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;

/**
 * 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 CreateIdentityPool {
    public static void main(String[] args) {
        final String usage = """
                Usage:
                    <identityPoolName>\s

                Where:
                    identityPoolName - The name to give your identity pool.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String identityPoolName = args[0];
        CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String identityPoolId = createIdPool(cognitoClient, identityPoolName);
        System.out.println("Unity pool ID " + identityPoolId);
        cognitoClient.close();
    }

    public static String createIdPool(CognitoIdentityClient cognitoClient, String identityPoolName) {
        try {
            CreateIdentityPoolRequest poolRequest = CreateIdentityPoolRequest.builder()
                    .allowUnauthenticatedIdentities(false)
                    .identityPoolName(identityPoolName)
                    .build();

            CreateIdentityPoolResponse response = cognitoClient.createIdentityPool(poolRequest);
            return response.identityPoolId();

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateIdentityPool](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-identity-2014-06-30/CreateIdentityPool)」を参照してください。

### `DeleteIdentityPool`
<a name="cognito-identity_DeleteIdentityPool_java_2_topic"></a>

次のコード例は、`DeleteIdentityPool` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;
import software.amazon.awssdk.services.cognitoidentity.model.DeleteIdentityPoolRequest;

/**
 * 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 DeleteIdentityPool {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <identityPoolId>\s

                Where:
                    identityPoolId - The Id value of your identity pool.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String identityPoold = args[0];
        CognitoIdentityClient cognitoIdClient = CognitoIdentityClient.builder()
                .region(Region.US_EAST_1)
                .credentialsProvider(ProfileCredentialsProvider.create())
                .build();

        deleteIdPool(cognitoIdClient, identityPoold);
        cognitoIdClient.close();
    }

    public static void deleteIdPool(CognitoIdentityClient cognitoIdClient, String identityPoold) {
        try {

            DeleteIdentityPoolRequest identityPoolRequest = DeleteIdentityPoolRequest.builder()
                    .identityPoolId(identityPoold)
                    .build();

            cognitoIdClient.deleteIdentityPool(identityPoolRequest);
            System.out.println("Done");

        } catch (AwsServiceException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[DeleteIdentityPool](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-identity-2014-06-30/DeleteIdentityPool)」を参照してください。**

### `GetCredentialsForIdentity`
<a name="cognito-identity_GetCredentialsForIdentity_java_2_topic"></a>

次のコード例は、`GetCredentialsForIdentity` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;
import software.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityRequest;
import software.amazon.awssdk.services.cognitoidentity.model.GetCredentialsForIdentityResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;

/**
 * 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 GetIdentityCredentials {
    public static void main(String[] args) {

        final String usage = """

                Usage:
                    <identityId>\s

            Where:
                identityId - The Id of an existing identity in the format REGION:GUID.
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String identityId = args[0];
        CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder()
                .region(Region.US_EAST_1)
                .build();

        getCredsForIdentity(cognitoClient, identityId);
        cognitoClient.close();
    }

    public static void getCredsForIdentity(CognitoIdentityClient cognitoClient, String identityId) {
        try {
            GetCredentialsForIdentityRequest getCredentialsForIdentityRequest = GetCredentialsForIdentityRequest
                    .builder()
                    .identityId(identityId)
                    .build();

            GetCredentialsForIdentityResponse response = cognitoClient
                    .getCredentialsForIdentity(getCredentialsForIdentityRequest);
            System.out.println(
                    "Identity ID " + response.identityId() + ", Access key ID " + response.credentials().accessKeyId());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[GetCredentialsForIdentity](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-identity-2014-06-30/GetCredentialsForIdentity)」を参照してください。**

### `ListIdentityPools`
<a name="cognito-identity_ListIdentityPools_java_2_topic"></a>

次のコード例は、`ListIdentityPools` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentity.CognitoIdentityClient;
import software.amazon.awssdk.services.cognitoidentity.model.ListIdentityPoolsRequest;
import software.amazon.awssdk.services.cognitoidentity.model.ListIdentityPoolsResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;

/**
 * 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 ListIdentityPools {
    public static void main(String[] args) {
        CognitoIdentityClient cognitoClient = CognitoIdentityClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listIdPools(cognitoClient);
        cognitoClient.close();
    }

    public static void listIdPools(CognitoIdentityClient cognitoClient) {
        try {
            ListIdentityPoolsRequest poolsRequest = ListIdentityPoolsRequest.builder()
                    .maxResults(15)
                    .build();

            ListIdentityPoolsResponse response = cognitoClient.listIdentityPools(poolsRequest);
            response.identityPools().forEach(pool -> {
                System.out.println("Pool ID: " + pool.identityPoolId());
                System.out.println("Pool name: " + pool.identityPoolName());
            });

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListIdentityPools](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-identity-2014-06-30/ListIdentityPools)」を参照してください。

# SDK for Java 2.x を使用した Amazon Cognito ID プロバイダーの例
<a name="java_2_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダー AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Cognito
<a name="cognito-identity-provider_Hello_java_2_topic"></a>

次のコード例は、Amazon Cognito の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest;

/**
 * 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 ListUserPools {
    public static void main(String[] args) {
        CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listAllUserPools(cognitoClient);
        cognitoClient.close();
    }

    public static void listAllUserPools(CognitoIdentityProviderClient cognitoClient) {
        try {
            ListUserPoolsRequest request = ListUserPoolsRequest.builder()
                    .maxResults(10)
                    .build();

            ListUserPoolsResponse response = cognitoClient.listUserPools(request);
            response.userPools().forEach(userpool -> {
                System.out.println("User pool " + userpool.name() + ", User ID " + userpool.id());
            });

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListUserPools](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ListUserPools)」を参照してください。

## アクション
<a name="actions"></a>

### `AdminGetUser`
<a name="cognito-identity-provider_AdminGetUser_java_2_topic"></a>

次のコード例は、`AdminGetUser` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    public static void getAdminUser(CognitoIdentityProviderClient identityProviderClient, String userName,
            String poolId) {
        try {
            AdminGetUserRequest userRequest = AdminGetUserRequest.builder()
                    .username(userName)
                    .userPoolId(poolId)
                    .build();

            AdminGetUserResponse response = identityProviderClient.adminGetUser(userRequest);
            System.out.println("User status " + response.userStatusAsString());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AdminGetUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AdminGetUser)」を参照してください。

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_java_2_topic"></a>

次のコード例は、`AdminInitiateAuth` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    public static AdminInitiateAuthResponse initiateAuth(CognitoIdentityProviderClient identityProviderClient,
            String clientId, String userName, String password, String userPoolId) {
        try {
            Map<String, String> authParameters = new HashMap<>();
            authParameters.put("USERNAME", userName);
            authParameters.put("PASSWORD", password);

            AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder()
                    .clientId(clientId)
                    .userPoolId(userPoolId)
                    .authParameters(authParameters)
                    .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
                    .build();

            AdminInitiateAuthResponse response = identityProviderClient.adminInitiateAuth(authRequest);
            System.out.println("Result Challenge is : " + response.challengeName());
            return response;

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AdminInitiateAuth](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AdminInitiateAuth)」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_java_2_topic"></a>

次のコード例は、`AdminRespondToAuthChallenge` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    // Respond to an authentication challenge.
    public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient identityProviderClient,
            String userName, String clientId, String mfaCode, String session) {
        System.out.println("SOFTWARE_TOKEN_MFA challenge is generated");
        Map<String, String> challengeResponses = new HashMap<>();

        challengeResponses.put("USERNAME", userName);
        challengeResponses.put("SOFTWARE_TOKEN_MFA_CODE", mfaCode);

        AdminRespondToAuthChallengeRequest respondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest.builder()
                .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA)
                .clientId(clientId)
                .challengeResponses(challengeResponses)
                .session(session)
                .build();

        AdminRespondToAuthChallengeResponse respondToAuthChallengeResult = identityProviderClient
                .adminRespondToAuthChallenge(respondToAuthChallengeRequest);
        System.out.println("respondToAuthChallengeResult.getAuthenticationResult()"
                + respondToAuthChallengeResult.authenticationResult());
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)」を参照してください。

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_java_2_topic"></a>

次のコード例は、`AssociateSoftwareToken` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    public static String getSecretForAppMFA(CognitoIdentityProviderClient identityProviderClient, String session) {
        AssociateSoftwareTokenRequest softwareTokenRequest = AssociateSoftwareTokenRequest.builder()
                .session(session)
                .build();

        AssociateSoftwareTokenResponse tokenResponse = identityProviderClient
                .associateSoftwareToken(softwareTokenRequest);
        String secretCode = tokenResponse.secretCode();
        System.out.println("Enter this token into Google Authenticator");
        System.out.println(secretCode);
        return tokenResponse.session();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AssociateSoftwareToken](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AssociateSoftwareToken)」を参照してください。

### `ConfirmSignUp`
<a name="cognito-identity-provider_ConfirmSignUp_java_2_topic"></a>

次のコード例は、`ConfirmSignUp` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    public static void confirmSignUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String code,
            String userName) {
        try {
            ConfirmSignUpRequest signUpRequest = ConfirmSignUpRequest.builder()
                    .clientId(clientId)
                    .confirmationCode(code)
                    .username(userName)
                    .build();

            identityProviderClient.confirmSignUp(signUpRequest);
            System.out.println(userName + " was confirmed");

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ConfirmSignUp](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ConfirmSignUp)」を参照してください。

### `CreateUserPool`
<a name="cognito-identity-provider_CreateUserPool_java_2_topic"></a>

次のコード例は、`CreateUserPool` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolResponse;

/**
 * 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 CreateUserPool {
    public static void main(String[] args) {

        final String usage = """

                Usage:
                    <userPoolName>\s

                Where:
                    userPoolName - The name to give your user pool when it's created.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String userPoolName = args[0];
        CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String id = createPool(cognitoClient, userPoolName);
        System.out.println("User pool ID: " + id);
        cognitoClient.close();
    }

    public static String createPool(CognitoIdentityProviderClient cognitoClient, String userPoolName) {
        try {
            CreateUserPoolRequest request = CreateUserPoolRequest.builder()
                    .poolName(userPoolName)
                    .build();

            CreateUserPoolResponse response = cognitoClient.createUserPool(request);
            return response.userPool().id();

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[CreateUserPool](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/CreateUserPool)」を参照してください。**

### `CreateUserPoolClient`
<a name="cognito-identity-provider_CreateUserPoolClient_java_2_topic"></a>

次のコード例は、`CreateUserPoolClient` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CreateUserPoolClientResponse;

/**
 * A user pool client app is an application that authenticates with Amazon
 * Cognito user pools.
 * When you create a user pool, you can configure app clients that allow mobile
 * or web applications
 * to call API operations to authenticate users, manage user attributes and
 * profiles,
 * and implement sign-up and sign-in flows.
 *
 * 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 CreateUserPoolClient {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <clientName> <userPoolId>\s

                Where:
                    clientName - The name for the user pool client to create.
                    userPoolId - The ID for the user pool.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String clientName = args[0];
        String userPoolId = args[1];
        CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
                .region(Region.US_EAST_1)
                .build();

        createPoolClient(cognitoClient, clientName, userPoolId);
        cognitoClient.close();
    }

    public static void createPoolClient(CognitoIdentityProviderClient cognitoClient, String clientName,
            String userPoolId) {
        try {
            CreateUserPoolClientRequest request = CreateUserPoolClientRequest.builder()
                    .clientName(clientName)
                    .userPoolId(userPoolId)
                    .build();

            CreateUserPoolClientResponse response = cognitoClient.createUserPoolClient(request);
            System.out.println("User pool " + response.userPoolClient().clientName() + " created. ID: "
                    + response.userPoolClient().clientId());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[CreateUserPoolClient](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/CreateUserPoolClient)」を参照してください。**

### `ListUserPools`
<a name="cognito-identity-provider_ListUserPools_java_2_topic"></a>

次のコード例は、`ListUserPools` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUserPoolsRequest;

/**
 * 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 ListUserPools {
    public static void main(String[] args) {
        CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listAllUserPools(cognitoClient);
        cognitoClient.close();
    }

    public static void listAllUserPools(CognitoIdentityProviderClient cognitoClient) {
        try {
            ListUserPoolsRequest request = ListUserPoolsRequest.builder()
                    .maxResults(10)
                    .build();

            ListUserPoolsResponse response = cognitoClient.listUserPools(request);
            response.userPools().forEach(userpool -> {
                System.out.println("User pool " + userpool.name() + ", User ID " + userpool.id());
            });

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については*AWS SDK for Java 2.x API リファレンス*の「[ListUserPools](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ListUserPools)」を参照してください。

### `ListUsers`
<a name="cognito-identity-provider_ListUsers_java_2_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUsersRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ListUsersResponse;

/**
 * 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 ListUsers {
    public static void main(String[] args) {

        final String usage = """

                Usage:
                    <userPoolId>\s

                Where:
                    userPoolId - The ID given to your user pool when it's created.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String userPoolId = args[0];
        CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listAllUsers(cognitoClient, userPoolId);
        listUsersFilter(cognitoClient, userPoolId);
        cognitoClient.close();
    }

    public static void listAllUsers(CognitoIdentityProviderClient cognitoClient, String userPoolId) {
        try {
            ListUsersRequest usersRequest = ListUsersRequest.builder()
                    .userPoolId(userPoolId)
                    .build();

            ListUsersResponse response = cognitoClient.listUsers(usersRequest);
            response.users().forEach(user -> {
                System.out.println("User " + user.username() + " Status " + user.userStatus() + " Created "
                        + user.userCreateDate());
            });

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Shows how to list users by using a filter.
    public static void listUsersFilter(CognitoIdentityProviderClient cognitoClient, String userPoolId) {

        try {
            String filter = "email = \"tblue@noserver.com\"";
            ListUsersRequest usersRequest = ListUsersRequest.builder()
                    .userPoolId(userPoolId)
                    .filter(filter)
                    .build();

            ListUsersResponse response = cognitoClient.listUsers(usersRequest);
            response.users().forEach(user -> {
                System.out.println("User with filter applied " + user.username() + " Status " + user.userStatus()
                        + " Created " + user.userCreateDate());
            });

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ListUsers)」を参照してください。

### `ResendConfirmationCode`
<a name="cognito-identity-provider_ResendConfirmationCode_java_2_topic"></a>

次のコード例は、`ResendConfirmationCode` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    public static void resendConfirmationCode(CognitoIdentityProviderClient identityProviderClient, String clientId,
            String userName) {
        try {
            ResendConfirmationCodeRequest codeRequest = ResendConfirmationCodeRequest.builder()
                    .clientId(clientId)
                    .username(userName)
                    .build();

            ResendConfirmationCodeResponse response = identityProviderClient.resendConfirmationCode(codeRequest);
            System.out.println("Method of delivery is " + response.codeDeliveryDetails().deliveryMediumAsString());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ResendConfirmationCode](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ResendConfirmationCode)」を参照してください。

### `SignUp`
<a name="cognito-identity-provider_SignUp_java_2_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    public static void signUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName,
            String password, String email) {
        AttributeType userAttrs = AttributeType.builder()
                .name("email")
                .value(email)
                .build();

        List<AttributeType> userAttrsList = new ArrayList<>();
        userAttrsList.add(userAttrs);
        try {
            SignUpRequest signUpRequest = SignUpRequest.builder()
                    .userAttributes(userAttrsList)
                    .username(userName)
                    .clientId(clientId)
                    .password(password)
                    .build();

            identityProviderClient.signUp(signUpRequest);
            System.out.println("User has been signed up ");

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SignUp](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/SignUp)」を参照してください。

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_java_2_topic"></a>

次のコード例は、`VerifySoftwareToken` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
    // Verify the TOTP and register for MFA.
    public static void verifyTOTP(CognitoIdentityProviderClient identityProviderClient, String session, String code) {
        try {
            VerifySoftwareTokenRequest tokenRequest = VerifySoftwareTokenRequest.builder()
                    .userCode(code)
                    .session(session)
                    .build();

            VerifySoftwareTokenResponse verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest);
            System.out.println("The status of the token is " + verifyResponse.statusAsString());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[VerifySoftwareToken](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/VerifySoftwareToken)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### MFA を必要とするユーザープールでユーザーをサインアップする
<a name="cognito-identity-provider_Scenario_SignUpUserWithMfa_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。
+ MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。
+ パスワードと MFA コードを使用してサインインします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cognitoidentityprovider.CognitoIdentityProviderClient;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminGetUserResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminInitiateAuthResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminRespondToAuthChallengeRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AdminRespondToAuthChallengeResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AssociateSoftwareTokenRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AssociateSoftwareTokenResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AttributeType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.AuthFlowType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ChallengeNameType;
import software.amazon.awssdk.services.cognitoidentityprovider.model.CognitoIdentityProviderException;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ConfirmSignUpRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ResendConfirmationCodeRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.ResendConfirmationCodeResponse;
import software.amazon.awssdk.services.cognitoidentityprovider.model.SignUpRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.VerifySoftwareTokenRequest;
import software.amazon.awssdk.services.cognitoidentityprovider.model.VerifySoftwareTokenResponse;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * TIP: To set up the required user pool, run the AWS Cloud Development Kit (AWS
 * CDK) script provided in this GitHub repo at
 * resources/cdk/cognito_scenario_user_pool_with_mfa.
 *
 * This code example performs the following operations:
 *
 * 1. Invokes the signUp method to sign up a user.
 * 2. Invokes the adminGetUser method to get the user's confirmation status.
 * 3. Invokes the ResendConfirmationCode method if the user requested another
 * code.
 * 4. Invokes the confirmSignUp method.
 * 5. Invokes the AdminInitiateAuth to sign in. This results in being prompted
 * to set up TOTP (time-based one-time password). (The response is
 * “ChallengeName”: “MFA_SETUP”).
 * 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private
 * key. This can be used with Google Authenticator.
 * 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for
 * MFA.
 * 8. Invokes the AdminInitiateAuth to sign in again. This results in being
 * prompted to submit a TOTP (Response: “ChallengeName”: “SOFTWARE_TOKEN_MFA”).
 * 9. Invokes the AdminRespondToAuthChallenge to get back a token.
 */

public class CognitoMVP {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
        final String usage = """

                Usage:
                    <clientId> <poolId>

                Where:
                    clientId - The app client Id value that you can get from the AWS CDK script.
                    poolId - The pool Id that you can get from the AWS CDK script.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String clientId = args[0];
        String poolId = args[1];
        CognitoIdentityProviderClient identityProviderClient = CognitoIdentityProviderClient.builder()
                .region(Region.US_EAST_1)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon Cognito example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("*** Enter your user name");
        Scanner in = new Scanner(System.in);
        String userName = in.nextLine();

        System.out.println("*** Enter your password");
        String password = in.nextLine();

        System.out.println("*** Enter your email");
        String email = in.nextLine();

        System.out.println("1. Signing up " + userName);
        signUp(identityProviderClient, clientId, userName, password, email);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Getting " + userName + " in the user pool");
        getAdminUser(identityProviderClient, userName, poolId);

        System.out
                .println("*** Conformation code sent to " + userName + ". Would you like to send a new code? (Yes/No)");
        System.out.println(DASHES);

        System.out.println(DASHES);
        String ans = in.nextLine();

        if (ans.compareTo("Yes") == 0) {
            resendConfirmationCode(identityProviderClient, clientId, userName);
            System.out.println("3. Sending a new confirmation code");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Enter confirmation code that was emailed");
        String code = in.nextLine();
        confirmSignUp(identityProviderClient, clientId, code, userName);
        System.out.println("Rechecking the status of " + userName + " in the user pool");
        getAdminUser(identityProviderClient, userName, poolId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Invokes the initiateAuth to sign in");
        AdminInitiateAuthResponse authResponse = initiateAuth(identityProviderClient, clientId, userName, password,
                poolId);
        String mySession = authResponse.session();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Invokes the AssociateSoftwareToken method to generate a TOTP key");
        String newSession = getSecretForAppMFA(identityProviderClient, mySession);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("*** Enter the 6-digit code displayed in Google Authenticator");
        String myCode = in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Verify the TOTP and register for MFA");
        verifyTOTP(identityProviderClient, newSession, myCode);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Re-enter a 6-digit code displayed in Google Authenticator");
        String mfaCode = in.nextLine();
        AdminInitiateAuthResponse authResponse1 = initiateAuth(identityProviderClient, clientId, userName, password,
                poolId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9.  Invokes the AdminRespondToAuthChallenge");
        String session2 = authResponse1.session();
        adminRespondToAuthChallenge(identityProviderClient, userName, clientId, mfaCode, session2);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("All Amazon Cognito operations were successfully performed");
        System.out.println(DASHES);
    }

    // Respond to an authentication challenge.
    public static void adminRespondToAuthChallenge(CognitoIdentityProviderClient identityProviderClient,
            String userName, String clientId, String mfaCode, String session) {
        System.out.println("SOFTWARE_TOKEN_MFA challenge is generated");
        Map<String, String> challengeResponses = new HashMap<>();

        challengeResponses.put("USERNAME", userName);
        challengeResponses.put("SOFTWARE_TOKEN_MFA_CODE", mfaCode);

        AdminRespondToAuthChallengeRequest respondToAuthChallengeRequest = AdminRespondToAuthChallengeRequest.builder()
                .challengeName(ChallengeNameType.SOFTWARE_TOKEN_MFA)
                .clientId(clientId)
                .challengeResponses(challengeResponses)
                .session(session)
                .build();

        AdminRespondToAuthChallengeResponse respondToAuthChallengeResult = identityProviderClient
                .adminRespondToAuthChallenge(respondToAuthChallengeRequest);
        System.out.println("respondToAuthChallengeResult.getAuthenticationResult()"
                + respondToAuthChallengeResult.authenticationResult());
    }

    // Verify the TOTP and register for MFA.
    public static void verifyTOTP(CognitoIdentityProviderClient identityProviderClient, String session, String code) {
        try {
            VerifySoftwareTokenRequest tokenRequest = VerifySoftwareTokenRequest.builder()
                    .userCode(code)
                    .session(session)
                    .build();

            VerifySoftwareTokenResponse verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest);
            System.out.println("The status of the token is " + verifyResponse.statusAsString());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static AdminInitiateAuthResponse initiateAuth(CognitoIdentityProviderClient identityProviderClient,
            String clientId, String userName, String password, String userPoolId) {
        try {
            Map<String, String> authParameters = new HashMap<>();
            authParameters.put("USERNAME", userName);
            authParameters.put("PASSWORD", password);

            AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder()
                    .clientId(clientId)
                    .userPoolId(userPoolId)
                    .authParameters(authParameters)
                    .authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
                    .build();

            AdminInitiateAuthResponse response = identityProviderClient.adminInitiateAuth(authRequest);
            System.out.println("Result Challenge is : " + response.challengeName());
            return response;

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }

    public static String getSecretForAppMFA(CognitoIdentityProviderClient identityProviderClient, String session) {
        AssociateSoftwareTokenRequest softwareTokenRequest = AssociateSoftwareTokenRequest.builder()
                .session(session)
                .build();

        AssociateSoftwareTokenResponse tokenResponse = identityProviderClient
                .associateSoftwareToken(softwareTokenRequest);
        String secretCode = tokenResponse.secretCode();
        System.out.println("Enter this token into Google Authenticator");
        System.out.println(secretCode);
        return tokenResponse.session();
    }

    public static void confirmSignUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String code,
            String userName) {
        try {
            ConfirmSignUpRequest signUpRequest = ConfirmSignUpRequest.builder()
                    .clientId(clientId)
                    .confirmationCode(code)
                    .username(userName)
                    .build();

            identityProviderClient.confirmSignUp(signUpRequest);
            System.out.println(userName + " was confirmed");

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void resendConfirmationCode(CognitoIdentityProviderClient identityProviderClient, String clientId,
            String userName) {
        try {
            ResendConfirmationCodeRequest codeRequest = ResendConfirmationCodeRequest.builder()
                    .clientId(clientId)
                    .username(userName)
                    .build();

            ResendConfirmationCodeResponse response = identityProviderClient.resendConfirmationCode(codeRequest);
            System.out.println("Method of delivery is " + response.codeDeliveryDetails().deliveryMediumAsString());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void signUp(CognitoIdentityProviderClient identityProviderClient, String clientId, String userName,
            String password, String email) {
        AttributeType userAttrs = AttributeType.builder()
                .name("email")
                .value(email)
                .build();

        List<AttributeType> userAttrsList = new ArrayList<>();
        userAttrsList.add(userAttrs);
        try {
            SignUpRequest signUpRequest = SignUpRequest.builder()
                    .userAttributes(userAttrsList)
                    .username(userName)
                    .clientId(clientId)
                    .password(password)
                    .build();

            identityProviderClient.signUp(signUpRequest);
            System.out.println("User has been signed up ");

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void getAdminUser(CognitoIdentityProviderClient identityProviderClient, String userName,
            String poolId) {
        try {
            AdminGetUserRequest userRequest = AdminGetUserRequest.builder()
                    .username(userName)
                    .userPoolId(poolId)
                    .build();

            AdminGetUserResponse response = identityProviderClient.adminGetUser(userRequest);
            System.out.println("User status " + response.userStatusAsString());

        } catch (CognitoIdentityProviderException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の以下のトピックを参照してください。
  + [AdminGetUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AdminGetUser)
  + [AdminInitiateAuth](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AdminInitiateAuth)
  + [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)
  + [AssociateSoftwareToken](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/AssociateSoftwareToken)
  + [ConfirmDevice](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ConfirmDevice)
  + [ConfirmSignUp](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ConfirmSignUp)
  + [InitiateAuth](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/InitiateAuth)
  + [ListUsers](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ListUsers)
  + [ResendConfirmationCode](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/ResendConfirmationCode)
  + [RespondToAuthChallenge](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/RespondToAuthChallenge)
  + [SignUp](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/SignUp)
  + [VerifySoftwareToken](https://docs.aws.amazon.com/goto/SdkForJavaV2/cognito-idp-2016-04-18/VerifySoftwareToken)

# SDK for Java 2.x を使用する Amazon Comprehend の例
<a name="java_2_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateDocumentClassifier`
<a name="comprehend_CreateDocumentClassifier_java_2_topic"></a>

次のコード例は、`CreateDocumentClassifier` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.comprehend.ComprehendClient;
import software.amazon.awssdk.services.comprehend.model.ComprehendException;
import software.amazon.awssdk.services.comprehend.model.CreateDocumentClassifierRequest;
import software.amazon.awssdk.services.comprehend.model.CreateDocumentClassifierResponse;
import software.amazon.awssdk.services.comprehend.model.DocumentClassifierInputDataConfig;

/**
 * Before running this code example, you can setup the necessary resources, such
 * as the CSV file and IAM Roles, by following this document:
 * https://aws.amazon.com/blogs/machine-learning/building-a-custom-classifier-using-amazon-comprehend/
 *
 * Also, 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 DocumentClassifierDemo {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <dataAccessRoleArn> <s3Uri> <documentClassifierName>

                Where:
                  dataAccessRoleArn - The ARN value of the role used for this operation.
                  s3Uri - The Amazon S3 bucket that contains the CSV file.
                  documentClassifierName - The name of the document classifier.
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String dataAccessRoleArn = args[0];
        String s3Uri = args[1];
        String documentClassifierName = args[2];

        Region region = Region.US_EAST_1;
        ComprehendClient comClient = ComprehendClient.builder()
                .region(region)
                .build();

        createDocumentClassifier(comClient, dataAccessRoleArn, s3Uri, documentClassifierName);
        comClient.close();
    }

    public static void createDocumentClassifier(ComprehendClient comClient, String dataAccessRoleArn, String s3Uri,
            String documentClassifierName) {
        try {
            DocumentClassifierInputDataConfig config = DocumentClassifierInputDataConfig.builder()
                    .s3Uri(s3Uri)
                    .build();

            CreateDocumentClassifierRequest createDocumentClassifierRequest = CreateDocumentClassifierRequest.builder()
                    .documentClassifierName(documentClassifierName)
                    .dataAccessRoleArn(dataAccessRoleArn)
                    .languageCode("en")
                    .inputDataConfig(config)
                    .build();

            CreateDocumentClassifierResponse createDocumentClassifierResult = comClient
                    .createDocumentClassifier(createDocumentClassifierRequest);
            String documentClassifierArn = createDocumentClassifierResult.documentClassifierArn();
            System.out.println("Document Classifier ARN: " + documentClassifierArn);

        } catch (ComprehendException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDocumentClassifier](https://docs.aws.amazon.com/goto/SdkForJavaV2/comprehend-2017-11-27/CreateDocumentClassifier)」を参照してください。

### `DetectDominantLanguage`
<a name="comprehend_DetectDominantLanguage_java_2_topic"></a>

次のコード例は、`DetectDominantLanguage` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.comprehend.ComprehendClient;
import software.amazon.awssdk.services.comprehend.model.ComprehendException;
import software.amazon.awssdk.services.comprehend.model.DetectDominantLanguageRequest;
import software.amazon.awssdk.services.comprehend.model.DetectDominantLanguageResponse;
import software.amazon.awssdk.services.comprehend.model.DominantLanguage;
import java.util.List;

/**
 * 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 DetectLanguage {
    public static void main(String[] args) {
        // Specify French text - "It is raining today in Seattle".
        String text = "Il pleut aujourd'hui à Seattle";
        Region region = Region.US_EAST_1;

        ComprehendClient comClient = ComprehendClient.builder()
                .region(region)
                .build();

        System.out.println("Calling DetectDominantLanguage");
        detectTheDominantLanguage(comClient, text);
        comClient.close();
    }

    public static void detectTheDominantLanguage(ComprehendClient comClient, String text) {
        try {
            DetectDominantLanguageRequest request = DetectDominantLanguageRequest.builder()
                    .text(text)
                    .build();

            DetectDominantLanguageResponse resp = comClient.detectDominantLanguage(request);
            List<DominantLanguage> allLanList = resp.languages();
            for (DominantLanguage lang : allLanList) {
                System.out.println("Language is " + lang.languageCode());
            }

        } catch (ComprehendException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DetectDominantLanguage](https://docs.aws.amazon.com/goto/SdkForJavaV2/comprehend-2017-11-27/DetectDominantLanguage)」を参照してください。

### `DetectEntities`
<a name="comprehend_DetectEntities_java_2_topic"></a>

次のコード例は、`DetectEntities` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.comprehend.ComprehendClient;
import software.amazon.awssdk.services.comprehend.model.DetectEntitiesRequest;
import software.amazon.awssdk.services.comprehend.model.DetectEntitiesResponse;
import software.amazon.awssdk.services.comprehend.model.Entity;
import software.amazon.awssdk.services.comprehend.model.ComprehendException;
import java.util.List;

/**
 * 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 DetectEntities {
    public static void main(String[] args) {
        String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing.";
        Region region = Region.US_EAST_1;
        ComprehendClient comClient = ComprehendClient.builder()
                .region(region)
                .build();

        System.out.println("Calling DetectEntities");
        detectAllEntities(comClient, text);
        comClient.close();
    }

    public static void detectAllEntities(ComprehendClient comClient, String text) {
        try {
            DetectEntitiesRequest detectEntitiesRequest = DetectEntitiesRequest.builder()
                    .text(text)
                    .languageCode("en")
                    .build();

            DetectEntitiesResponse detectEntitiesResult = comClient.detectEntities(detectEntitiesRequest);
            List<Entity> entList = detectEntitiesResult.entities();
            for (Entity entity : entList) {
                System.out.println("Entity text is " + entity.text());
            }

        } catch (ComprehendException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DetectEntities](https://docs.aws.amazon.com/goto/SdkForJavaV2/comprehend-2017-11-27/DetectEntities)」を参照してください。

### `DetectKeyPhrases`
<a name="comprehend_DetectKeyPhrases_java_2_topic"></a>

次のコード例は、`DetectKeyPhrases` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.comprehend.ComprehendClient;
import software.amazon.awssdk.services.comprehend.model.DetectKeyPhrasesRequest;
import software.amazon.awssdk.services.comprehend.model.DetectKeyPhrasesResponse;
import software.amazon.awssdk.services.comprehend.model.KeyPhrase;
import software.amazon.awssdk.services.comprehend.model.ComprehendException;
import java.util.List;

/**
 * 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 DetectKeyPhrases {
    public static void main(String[] args) {
        String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing.";
        Region region = Region.US_EAST_1;
        ComprehendClient comClient = ComprehendClient.builder()
                .region(region)
                .build();

        System.out.println("Calling DetectKeyPhrases");
        detectAllKeyPhrases(comClient, text);
        comClient.close();
    }

    public static void detectAllKeyPhrases(ComprehendClient comClient, String text) {
        try {
            DetectKeyPhrasesRequest detectKeyPhrasesRequest = DetectKeyPhrasesRequest.builder()
                    .text(text)
                    .languageCode("en")
                    .build();

            DetectKeyPhrasesResponse detectKeyPhrasesResult = comClient.detectKeyPhrases(detectKeyPhrasesRequest);
            List<KeyPhrase> phraseList = detectKeyPhrasesResult.keyPhrases();
            for (KeyPhrase keyPhrase : phraseList) {
                System.out.println("Key phrase text is " + keyPhrase.text());
            }

        } catch (ComprehendException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DetectKeyPhrases](https://docs.aws.amazon.com/goto/SdkForJavaV2/comprehend-2017-11-27/DetectKeyPhrases)」を参照してください。

### `DetectSentiment`
<a name="comprehend_DetectSentiment_java_2_topic"></a>

次のコード例は、`DetectSentiment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.comprehend.ComprehendClient;
import software.amazon.awssdk.services.comprehend.model.ComprehendException;
import software.amazon.awssdk.services.comprehend.model.DetectSentimentRequest;
import software.amazon.awssdk.services.comprehend.model.DetectSentimentResponse;

/**
 * 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 DetectSentiment {
    public static void main(String[] args) {
        String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing.";
        Region region = Region.US_EAST_1;
        ComprehendClient comClient = ComprehendClient.builder()
                .region(region)
                .build();

        System.out.println("Calling DetectSentiment");
        detectSentiments(comClient, text);
        comClient.close();
    }

    public static void detectSentiments(ComprehendClient comClient, String text) {
        try {
            DetectSentimentRequest detectSentimentRequest = DetectSentimentRequest.builder()
                    .text(text)
                    .languageCode("en")
                    .build();

            DetectSentimentResponse detectSentimentResult = comClient.detectSentiment(detectSentimentRequest);
            System.out.println("The Neutral value is " + detectSentimentResult.sentimentScore().neutral());

        } catch (ComprehendException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DetectSentiment](https://docs.aws.amazon.com/goto/SdkForJavaV2/comprehend-2017-11-27/DetectSentiment)」を参照してください。

### `DetectSyntax`
<a name="comprehend_DetectSyntax_java_2_topic"></a>

次のコード例は、`DetectSyntax` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.comprehend.ComprehendClient;
import software.amazon.awssdk.services.comprehend.model.ComprehendException;
import software.amazon.awssdk.services.comprehend.model.DetectSyntaxRequest;
import software.amazon.awssdk.services.comprehend.model.DetectSyntaxResponse;
import software.amazon.awssdk.services.comprehend.model.SyntaxToken;
import java.util.List;

/**
 * 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 DetectSyntax {
    public static void main(String[] args) {
        String text = "Amazon.com, Inc. is located in Seattle, WA and was founded July 5th, 1994 by Jeff Bezos, allowing customers to buy everything from books to blenders. Seattle is north of Portland and south of Vancouver, BC. Other notable Seattle - based companies are Starbucks and Boeing.";
        Region region = Region.US_EAST_1;
        ComprehendClient comClient = ComprehendClient.builder()
                .region(region)
                .build();

        System.out.println("Calling DetectSyntax");
        detectAllSyntax(comClient, text);
        comClient.close();
    }

    public static void detectAllSyntax(ComprehendClient comClient, String text) {
        try {
            DetectSyntaxRequest detectSyntaxRequest = DetectSyntaxRequest.builder()
                    .text(text)
                    .languageCode("en")
                    .build();

            DetectSyntaxResponse detectSyntaxResult = comClient.detectSyntax(detectSyntaxRequest);
            List<SyntaxToken> syntaxTokens = detectSyntaxResult.syntaxTokens();
            for (SyntaxToken token : syntaxTokens) {
                System.out.println("Language is " + token.text());
                System.out.println("Part of speech is " + token.partOfSpeech().tagAsString());
            }

        } catch (ComprehendException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/comprehend-2017-11-27/DetectSyntax)」の「*DetectSyntax*」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Lex チャットボットを構築する
<a name="cross_LexChatbotLanguages_java_2_topic"></a>

次のコード例は、ウェブサイトの訪問者を引き付けるチャットボットの作成方法を示しています。

**SDK for Java 2.x**  
 Amazon Lex API を使用して、ウェブアプリケーション内にチャットボットを作成し、Web サイトの訪問者と交流する方法を説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lex_chatbot) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon Lex
+ Amazon Translate

### メッセージングアプリケーションを作成する
<a name="cross_SQSMessageApp_java_2_topic"></a>

次のコード例は、Amazon SQS を使用してメッセージングアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon SQS API を使用して、メッセージを送受信する Spring REST API を開発する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_message_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SQS

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_java_2_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Java 2.x**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_fsa_app) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# AWS Control Tower SDK for Java 2.x を使用した の例
<a name="java_2_controltower_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Control Tower。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Control Towerは
<a name="controltower_Hello_java_2_topic"></a>

次のコード例は、 AWS Control Towerの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
public class HelloControlTower {

    public static void main(String[] args) {
        try {
            ControlTowerClient controlTowerClient = ControlTowerClient.builder()
                .build() ;
            helloControlTower(controlTowerClient);
        } catch (ControlTowerException e) {
            System.out.println("Control Tower error occurred: " + e.awsErrorDetails().errorMessage());
        }
    }

    /**
     * Use the AWS SDK for Java (v2) to create an AWS Control Tower client
     * and list all available baselines.
     * This example uses the default settings specified in your shared credentials
     * and config files.
     *
     * @param controlTowerClient A ControlTowerClient object. This object wraps
     *                          the low-level AWS Control Tower service API.
     */
    public static void helloControlTower(ControlTowerClient controlTowerClient) {
        System.out.println("Hello, AWS Control Tower! Let's list available baselines:\n");
        
        ListBaselinesIterable paginator = controlTowerClient.listBaselinesPaginator(
                ListBaselinesRequest.builder().build());
        List<String> baselineNames = new ArrayList<>();
        
        try {
            paginator.stream()
                .flatMap(response -> response.baselines().stream())
                    .forEach(baseline -> baselineNames.add(baseline.name()));

            System.out.println(baselineNames.size() + " baseline(s) retrieved.");
            for (String baselineName : baselineNames) {
                System.out.println("\t" + baselineName);
            }

        } catch (ControlTowerException e) {
            if ("AccessDeniedException".equals(e.awsErrorDetails().errorCode())) {
                System.out.println("Access denied. Please ensure you have the necessary permissions.");
            } else {
                System.out.println("An error occurred: " + e.getMessage());
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListBaselines](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListBaselines)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="controltower_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ランディングゾーンを一覧表示します。
+ ベースラインを一覧表示、有効化、取得、リセット、無効化する。
+ コントロールを一覧表示、有効化、取得、無効化する。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。
 AWS Control Tower 機能を示すインタラクティブなシナリオを実行します。  

```
public class ControlTowerScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final Scanner scanner = new Scanner(in);

    private static OrganizationsClient orgClient;
    private static ControlCatalogClient catClient;

    private static String ouId = null;
    private static String ouArn = null;
    private static String landingZoneArn = null;
    private static boolean useLandingZone = false;

    private String stack = null;
    private String accountId = null;

    public static void main(String[] args) {

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS Control Tower basics scenario!");
        System.out.println(DASHES);

        try {
            runScenarioAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // -----------------------------
    // Utilities
    // -----------------------------
    private static boolean askYesNo(String msg) {
        System.out.println(msg);
        return scanner.nextLine().trim().toLowerCase().startsWith("y");
    }

    private static void runScenarioAsync() {
        try {
            ControlTowerActions actions = new ControlTowerActions();

            // -----------------------------
            // Step 1: Landing Zones
            // -----------------------------
            System.out.println(DASHES);
            System.out.println("""
        Some demo operations require the use of a landing zone.
        You can use an existing landing zone or opt out of these operations in the demo.
        For instructions on how to set up a landing zone,
        see https://docs.aws.amazon.com/controltower/latest/userguide/getting-started-from-console.html
        """);

            System.out.println("Step 1: Listing landing zones...");
            waitForInputToContinue(scanner);

            List<LandingZoneSummary> landingZones =
                    actions.listLandingZonesAsync().join();

            if (landingZones.isEmpty()) {
                System.out.println("No landing zones found. Landing-zone-dependent steps will be skipped.");
                useLandingZone = false;
                waitForInputToContinue(scanner);
            } else {
                System.out.println("\nAvailable Landing Zones:");
                for (int i = 0; i < landingZones.size(); i++) {
                    System.out.printf("%d) %s%n", i + 1, landingZones.get(i).arn());
                }

                if (askYesNo("Do you want to use the first landing zone in the list (" +
                        landingZones.get(0).arn() + ")? (y/n): ")) {
                    useLandingZone = true;
                    landingZoneArn = landingZones.get(0).arn();
                } else if (askYesNo("Do you want to use a different existing Landing Zone for this demo? (y/n): ")) {
                    useLandingZone = true;
                    System.out.println("Enter landing zone ARN: ");
                    landingZoneArn = scanner.nextLine().trim();
                } else {
                    System.out.println("Proceeding without a landing zone.");
                    useLandingZone = false;
                    waitForInputToContinue(scanner);
                }
            }

            // -----------------------------
            // Setup Organization + Sandbox OU
            // -----------------------------
            if (useLandingZone) {
                System.out.println("Using landing zone ARN: " + landingZoneArn);

                ControlTowerActions.OrgSetupResult result =
                        actions.setupOrganizationAsync().join();

                ouArn = result.sandboxOuArn();
                ouId  = result.sandboxOuArn();

                System.out.println("Organization ID: " + result.orgId());
                System.out.println("Using Sandbox OU ARN: " + ouArn);
            }

            // -----------------------------
            // Step 2: Baselines
            // -----------------------------
            System.out.println(DASHES);
            System.out.println("Step 2: Listing available baselines...");
            System.out.println("""
In this step, the program lists available AWS Control Tower baselines and may perform
baseline-related operations (enable, disable, reset) if requested.

NOTE:
AWS Control Tower enforces governance through baselines and mandatory controls
(guardrails). Mandatory controls are required for landing zone governance and may
restrict certain operations depending on the account, region, or organizational policy.

For more information, see:
- Types of baselines in AWS Control Tower:
  https://docs.aws.amazon.com/controltower/latest/userguide/types-of-baselines.html
- Mandatory controls (guardrails) in AWS Control Tower:
  https://docs.aws.amazon.com/controltower/latest/controlreference/mandatory-controls.html
- Baseline API examples:
  https://docs.aws.amazon.com/controltower/latest/userguide/baseline-api-examples.html
""");



            waitForInputToContinue(scanner);
            List<BaselineSummary> baselines =
                    actions.listBaselinesAsync().join();

            BaselineSummary controlTowerBaseline = null;
            for (BaselineSummary b : baselines) {
                System.out.println("Baseline: " + b.name());
                System.out.println("  ARN: " + b.arn());
                if ("AWSControlTowerBaseline".equals(b.name())) {
                    controlTowerBaseline = b;
                }
            }

            waitForInputToContinue(scanner);

            if (useLandingZone && controlTowerBaseline != null) {

                System.out.println("\nListing enabled baselines:");
                List<EnabledBaselineSummary> enabledBaselines =
                        actions.listEnabledBaselinesAsync().join();

                String enabledBaselineArn = null;
                for (EnabledBaselineSummary eb : enabledBaselines) {
                    System.out.println("Checking enabled baseline ARN: " + eb.arn());
                    if (eb.baselineIdentifier().equals(controlTowerBaseline.arn())) {
                        enabledBaselineArn = eb.arn(); // correct enabled ARN for this baseline
                        break; // stop after finding the matching one
                    }
                }

                if (enabledBaselineArn == null) {
                    System.out.println("No enabled baseline found for " + controlTowerBaseline.arn());
                } else {
                    System.out.println("Selected enabled baseline ARN for reset/disable: " + enabledBaselineArn);
                }


                // Enable the Baseline
                if (askYesNo("Do you want to enable the Control Tower Baseline? (y/n): ")) {
                    System.out.println("\nEnabling Control Tower Baseline...");

                    String baselineId = controlTowerBaseline.arn();
                    String enabledBaselineId =
                            actions.enableBaselineAsync(
                                    ouArn,                  // targetIdentifier → the OU or account ARN
                                    baselineId,             // baselineIdentifier → the Control Tower baseline ARN
                                    "5.0"                   // baselineVersion → version string
                            ).join();


                    System.out.println("Enabled baseline operation ID: " + enabledBaselineId);
                    if (enabledBaselineId == null) {
                       enabledBaselineId = enabledBaselineArn;
                    }

                    // Reset the Baseline
                    if (askYesNo("Do you want to reset the Control Tower Baseline? (y/n): ")) {
                        String operationId =
                                actions.resetEnabledBaselineAsync(enabledBaselineId).join();
                        System.out.println("Reset baseline operation ID: " + operationId);
                    }

                    if (askYesNo("Do you want to disable the Control Tower Baseline? (y/n): ")) {
                        String operationId =
                                actions.disableBaselineAsync(enabledBaselineId).join();
                        System.out.println("Disabled baseline operation ID: " + operationId);

                        System.out.println("Now we will re‑enable the baseline and wait 1 minute before making the call...");
                        try {
                            Thread.sleep(Duration.ofMinutes(1).toMillis());
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                            System.out.println("Wait interrupted");
                        }
                        String reEnabledBaselineId = actions.enableBaselineAsync(
                                ouArn,
                                baselineId,  // reuse baseline definition ARN
                                "5.0"
                        ).join();

                        System.out.println("Re-enabled baseline operation ID: " + reEnabledBaselineId);
                    }
                }
            }

            // -----------------------------
            // Step 3: Controls
            // -----------------------------
            System.out.println(DASHES);
            System.out.println("Step 3: Managing Controls:");
            waitForInputToContinue(scanner);

            List<ControlSummary> controls =
                    actions.listControlsAsync().join();

            System.out.println("\nListing first 5 available Controls:");
            for (int i = 0; i < Math.min(5, controls.size()); i++) {
                ControlSummary c = controls.get(i);
                System.out.println("%d. %s - %s".formatted(i + 1, c.name(), c.arn()));
            }

            if (useLandingZone) {
                waitForInputToContinue(scanner);

                List<EnabledControlSummary> enabledControls =
                        actions.listEnabledControlsAsync(ouArn).join();

                System.out.println("\nListing enabled controls:");
                for (int i = 0; i < enabledControls.size(); i++) {
                    System.out.println("%d. %s".formatted(i + 1, enabledControls.get(i).controlIdentifier()));
                }

                String controlArnToEnable = null;
                for (ControlSummary control : controls) {
                    boolean enabled = enabledControls.stream()
                            .anyMatch(ec -> ec.controlIdentifier().equals(control.arn()));
                    if (!enabled) {
                        controlArnToEnable = control.arn();
                        break;
                    }
                }

                waitForInputToContinue(scanner);
                if (controlArnToEnable != null &&
                        askYesNo("Do you want to enable the control " + controlArnToEnable + "? (y/n): ")) {

                    String operationId =
                            actions.enableControlAsync(controlArnToEnable, ouArn).join();

                    System.out.println("Enabled control with operation ID: " + operationId);
                }

                waitForInputToContinue(scanner);

                if (controlArnToEnable != null &&
                        askYesNo("Do you want to disable the control? (y/n): ")) {

                    String operationId =
                            actions.disableControlAsync(controlArnToEnable, ouArn).join();

                    System.out.println("Disable operation ID: " + operationId);
                }
            }
            System.out.println("\nThis concludes the example scenario.");
            System.out.println("Thanks for watching!");
            System.out.println(DASHES);

        } catch (CompletionException e) {
            Throwable cause = e.getCause() != null ? e.getCause() : e;
            System.out.println("Scenario failed: " + cause.getMessage());
            throw e; // bubble up for tests / callers
        } catch (Exception e) {
            System.out.println("Unexpected error running scenario: " + e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private static void waitForInputToContinue(Scanner sc) {
        System.out.println("\nEnter 'c' then <ENTER> to continue:");
        while (true) {
            String input = sc.nextLine();
            if ("c".equalsIgnoreCase(input.trim())) {
                System.out.println("Continuing...");
                break;
            }
        }
    }
}

public class ControlTowerActions {
    private static ControlCatalogAsyncClient controlCatalogAsyncClient;
    private static ControlTowerAsyncClient controlTowerAsyncClient;
    private static OrganizationsAsyncClient orgAsyncClient;

    private static OrganizationsAsyncClient getAsyncOrgClient() {
        if (orgAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                    .maxConcurrency(50)
                    .connectionTimeout(Duration.ofSeconds(60))
                    .readTimeout(Duration.ofSeconds(60))
                    .writeTimeout(Duration.ofSeconds(60))
                    .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                    .apiCallTimeout(Duration.ofMinutes(2))
                    .apiCallAttemptTimeout(Duration.ofSeconds(90))
                    .build();

            orgAsyncClient = OrganizationsAsyncClient.builder()
                    .httpClient(httpClient)
                    .overrideConfiguration(overrideConfig)
                    .build();
        }
        return orgAsyncClient;
    }

    private static ControlCatalogAsyncClient getAsyncCatClient() {
        if (controlCatalogAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                    .maxConcurrency(100)
                    .connectionTimeout(Duration.ofSeconds(60))
                    .readTimeout(Duration.ofSeconds(60))
                    .writeTimeout(Duration.ofSeconds(60))
                    .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                    .apiCallTimeout(Duration.ofMinutes(2))
                    .apiCallAttemptTimeout(Duration.ofSeconds(90))
                    .retryStrategy(RetryMode.STANDARD)
                    .build();

            controlCatalogAsyncClient = ControlCatalogAsyncClient.builder()
                    .httpClient(httpClient)
                    .overrideConfiguration(overrideConfig)
                    .build();
        }
        return controlCatalogAsyncClient;
    }

    private static ControlTowerAsyncClient getAsyncClient() {
        if (controlTowerAsyncClient == null) {

            SdkAsyncHttpClient httpClient =
                    AwsCrtAsyncHttpClient.builder()
                            .maxConcurrency(100)
                            .connectionTimeout(Duration.ofSeconds(60))
                            .build();

            ClientOverrideConfiguration overrideConfig =
                    ClientOverrideConfiguration.builder()
                            .apiCallTimeout(Duration.ofMinutes(2))
                            .apiCallAttemptTimeout(Duration.ofSeconds(90))
                            .retryStrategy(RetryMode.STANDARD)
                            .build();

            controlTowerAsyncClient =
                    ControlTowerAsyncClient.builder()
                            .httpClient(httpClient)
                            .overrideConfiguration(overrideConfig)
                            .build();
        }

        return controlTowerAsyncClient;
    }

    public record OrgSetupResult(String orgId, String sandboxOuArn) {
    }

    public CompletableFuture<OrgSetupResult> setupOrganizationAsync() {
        System.out.println("Starting organization setup…");

        OrganizationsAsyncClient client = getAsyncOrgClient();

        // Step 1: Describe or create organization
        CompletableFuture<Organization> orgFuture = client.describeOrganization()
                .thenApply(desc -> {
                    System.out.println("Organization exists: " + desc.organization().id());
                    return desc.organization();
                })
                .exceptionallyCompose(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
                    if (cause instanceof AwsServiceException awsEx &&
                            "AWSOrganizationsNotInUseException".equals(awsEx.awsErrorDetails().errorCode())) {
                        System.out.println("No organization found. Creating one…");
                        return client.createOrganization(CreateOrganizationRequest.builder()
                                        .featureSet(OrganizationFeatureSet.ALL)
                                        .build())
                                .thenApply(createResp -> {
                                    System.out.println("Created organization: {}" + createResp.organization().id());
                                    return createResp.organization();
                                });
                    }
                    return CompletableFuture.failedFuture(
                            new CompletionException("Failed to describe or create organization", cause)
                    );
                });

        // Step 2: Locate Sandbox OU
        return orgFuture.thenCompose(org -> {
            String orgId = org.id();
            System.out.println("Organization ID: {}" + orgId);

            return client.listRoots()
                    .thenCompose(rootsResp -> {
                        if (rootsResp.roots().isEmpty()) {
                            return CompletableFuture.failedFuture(
                                    new RuntimeException("No root found in organization")
                            );
                        }
                        String rootId = rootsResp.roots().get(0).id();

                        ListOrganizationalUnitsForParentRequest ouRequest =
                                ListOrganizationalUnitsForParentRequest.builder()
                                        .parentId(rootId)
                                        .build();

                        ListOrganizationalUnitsForParentPublisher paginator =
                                client.listOrganizationalUnitsForParentPaginator(ouRequest);

                        AtomicReference<String> sandboxOuArnRef = new AtomicReference<>();
                        return paginator.subscribe(page -> {
                                    for (OrganizationalUnit ou : page.organizationalUnits()) {
                                        if ("Sandbox".equals(ou.name())) {
                                            sandboxOuArnRef.set(ou.arn());
                                            System.out.println("Found Sandbox OU: " + ou.id());
                                            break;
                                        }
                                    }
                                })
                                .thenApply(v -> {
                                    String sandboxArn = sandboxOuArnRef.get();
                                    if (sandboxArn == null) {
                                        System.out.println("Sandbox OU not found.");
                                    }
                                    return new OrgSetupResult(orgId, sandboxArn);
                                });
                    });
        }).exceptionally(ex -> {
            Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
            System.out.println("Failed to setup organization: {}" + cause.getMessage());
            throw new CompletionException(cause);
        });
    }

    /**
     * Lists all landing zones using pagination to retrieve complete results.
     *
     * @return a list of all landing zones
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<LandingZoneSummary>> listLandingZonesAsync() {
        System.out.println("Starting list landing zones paginator…");

        ListLandingZonesRequest request = ListLandingZonesRequest.builder().build();
        ListLandingZonesPublisher paginator = getAsyncClient().listLandingZonesPaginator(request);
        List<LandingZoneSummary> landingZones = new ArrayList<>();

        return paginator.subscribe(response -> {
                    if (response.landingZones() != null && !response.landingZones().isEmpty()) {
                        response.landingZones().forEach(lz -> {
                            System.out.println("Landing zone ARN: " + lz.arn());
                            landingZones.add(lz);
                        });
                    } else {
                        System.out.println("Page contained no landing zones.");
                    }
                })
                .thenRun(() -> System.out.println("Successfully retrieved "+ landingZones.size() + " landing zones." ))
                .thenApply(v -> landingZones)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();
                        switch (errorCode) {
                            case "AccessDeniedException":
                                throw new CompletionException(
                                        "Access denied when listing landing zones: " + e.getMessage(), e);
                            default:
                                throw new CompletionException(
                                        "Error listing landing zones: " + e.getMessage(), e);
                        }
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing landing zones: " + cause.getMessage(), cause);
                    }

                    throw new CompletionException("Failed to list landing zones", cause);
                });
    }


    /**
     * Lists all available baselines using pagination to retrieve complete results.
     *
     * @return a list of all baselines
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<BaselineSummary>> listBaselinesAsync() {
        System.out.println("Starting list baselines paginator…");
        ListBaselinesRequest request = ListBaselinesRequest.builder().build();
        ListBaselinesPublisher paginator =
                getAsyncClient().listBaselinesPaginator(request);

        List<BaselineSummary> baselines = new ArrayList<>();
        return paginator.subscribe(response -> {
                    if (response.baselines() != null && !response.baselines().isEmpty()) {
                        response.baselines().forEach(baseline -> {
                            baselines.add(baseline);
                        });
                    } else {
                        System.out.println("Page contained no baselines.");
                    }
                })
                .thenRun(() ->
                        System.out.println("Successfully listed baselines. Total: " + baselines.size())
                )
                .thenApply(v -> baselines)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        if ("AccessDeniedException".equals(errorCode)) {
                            throw new CompletionException(
                                    "Access denied when listing baselines: %s".formatted(e.getMessage()),
                                    e
                            );
                        }

                        throw new CompletionException(
                                "Error listing baselines: %s".formatted(e.getMessage()),
                                e
                        );
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing baselines: %s".formatted(cause.getMessage()),
                                cause
                        );
                    }

                    throw new CompletionException("Failed to list baselines", cause);
                });
    }

    /**
     * Lists all enabled baselines using pagination to retrieve complete results.
     *
     * @return a list of all enabled baselines
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<EnabledBaselineSummary>> listEnabledBaselinesAsync() {
        System.out.println("Starting list enabled baselines paginator…");

        ListEnabledBaselinesRequest request =
                ListEnabledBaselinesRequest.builder().build();

        ListEnabledBaselinesPublisher paginator =
                getAsyncClient().listEnabledBaselinesPaginator(request);

        List<EnabledBaselineSummary> enabledBaselines = new ArrayList<>();
        return paginator.subscribe(response -> {
                    if (response.enabledBaselines() != null
                            && !response.enabledBaselines().isEmpty()) {

                        response.enabledBaselines().forEach(baseline -> {
                            enabledBaselines.add(baseline);
                        });
                    } else {
                        System.out.println("Page contained no enabled baselines.");
                    }
                })
                .thenRun(() ->
                        System.out.println(
                                "Successfully listed enabled baselines. Total: " +
                                        enabledBaselines.size()
                        )
                )
                .thenApply(v -> enabledBaselines)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        if ("AccessDeniedException".equals(errorCode)) {
                            throw new CompletionException(
                                    "Access denied when listing enabled baselines: %s".formatted(e.getMessage()), e);
                        }

                        throw new CompletionException(
                                "Error listing enabled baselines: %s"
                                        .formatted(e.getMessage()),
                                e
                        );
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing enabled baselines: %s"
                                        .formatted(cause.getMessage()),
                                cause
                        );
                    }

                    throw new CompletionException(
                            "Failed to list enabled baselines",
                            cause
                    );
                });
    }


    /**
     * Asynchronously enables a baseline for the specified target if not already enabled.
     *
     * @param targetIdentifier       The ARN of the target (OU or account).
     * @param baselineIdentifier     The baseline definition ARN to enable.
     * @param baselineVersion        The baseline version to enable.
     * @return A CompletableFuture containing the enabled baseline ARN, or null if already enabled.
     */
    public CompletableFuture<String> enableBaselineAsync(
            String targetIdentifier,
            String baselineIdentifier,
            String baselineVersion
    ) {
        EnableBaselineRequest request = EnableBaselineRequest.builder()
                .baselineIdentifier(baselineIdentifier)
                .baselineVersion(baselineVersion)
                .targetIdentifier(targetIdentifier)
                .build();

        return getAsyncClient().enableBaseline(request)
                .handle((resp, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ControlTowerException e) {
                            String code = e.awsErrorDetails() != null ? e.awsErrorDetails().errorCode() : "UNKNOWN";
                            String msg = e.awsErrorDetails() != null ? e.awsErrorDetails().errorMessage() : e.getMessage();

                            if ("ValidationException".equals(code) && msg.contains("already enabled")) {
                                System.out.println("Baseline is already enabled for this target → fetching ARN...");
                                return fetchEnabledBaselineArn(targetIdentifier, baselineIdentifier)
                                        .join(); // fetch existing ARN synchronously
                            }

                            throw new RuntimeException("Error enabling baseline: " + code + " - " + msg, e);
                        }

                        throw new RuntimeException("Unexpected error enabling baseline: " + cause.getMessage(), cause);
                    }

                    return resp;
                })
                .thenCompose(result -> {
                    if (result instanceof EnableBaselineResponse resp) {
                        String operationId = resp.operationIdentifier();
                        String enabledBaselineArn = resp.arn();
                        System.out.println("Baseline enable started. ARN: " + enabledBaselineArn
                                + ", operation ID: " + operationId);

                        // Inline polling
                        return CompletableFuture.supplyAsync(() -> {
                            while (true) {
                                GetBaselineOperationRequest opReq = GetBaselineOperationRequest.builder()
                                        .operationIdentifier(operationId)
                                        .build();

                                GetBaselineOperationResponse opResp = getAsyncClient().getBaselineOperation(opReq).join();
                                BaselineOperation op = opResp.baselineOperation();
                                BaselineOperationStatus status = op.status();
                                System.out.println("Operation " + operationId + " status: " + status);

                                if (status == BaselineOperationStatus.SUCCEEDED) {
                                    return enabledBaselineArn;
                                } else if (status == BaselineOperationStatus.FAILED) {
                                    String opId = op.operationIdentifier();
                                    String reason = op.statusMessage() != null ? op.statusMessage() : "No failure reason provided";
                                    throw new RuntimeException("Baseline operation failed (ID: " + opId + "), status: "
                                            + status + ", reason: " + reason);
                                }

                                try {
                                    Thread.sleep(Duration.ofSeconds(15).toMillis());
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt();
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                    } else if (result instanceof String existingArn) {
                        // Already enabled branch
                        return CompletableFuture.completedFuture(existingArn);
                    }

                    return CompletableFuture.completedFuture(null);
                });
    }


    /**
     * Fetches the ARN of an already-enabled baseline for the target asynchronously.
     */
    private CompletableFuture<String> fetchEnabledBaselineArn(String targetIdentifier, String baselineIdentifier) {
        return getAsyncClient().listEnabledBaselines(ListEnabledBaselinesRequest.builder().build())
                .thenApply(listResp -> {
                    for (EnabledBaselineSummary eb : listResp.enabledBaselines()) {
                        if (baselineIdentifier.equals(eb.baselineIdentifier())
                                && targetIdentifier.equals(eb.targetIdentifier())) {
                            return eb.arn();
                        }
                    }
                    return null; // not yet available
                });
    }


    /**
     * Disables a baseline for a specified target.
     *
     * @param enabledBaselineIdentifier the identifier of the enabled baseline to disable
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> disableBaselineAsync(String enabledBaselineIdentifier) {

        System.out.println("Starting disable of enabled baseline…");
        System.out.println("This operation will check the status every 15 seconds until it completes (SUCCEEDED or FAILED).");

        DisableBaselineRequest request = DisableBaselineRequest.builder()
                .enabledBaselineIdentifier(enabledBaselineIdentifier)
                .build();

        return getAsyncClient().disableBaseline(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Disable baseline operation ID: " + operationId);

                    // CompletableFuture that will be completed when operation finishes
                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    // Polling loop
                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getBaselineOperationAsync(operationId)
                                    .thenAccept(statusObj -> {
                                        String status = statusObj.toString(); // Convert enum/status to string for printing
                                        System.out.println("Current disable operation status: " + status + " → waiting for SUCCEEDED or FAILED...");

                                        if ("SUCCEEDED".equalsIgnoreCase(status) || "FAILED".equalsIgnoreCase(status)) {
                                            System.out.println("Disable operation finished with status: " + status);
                                            resultFuture.complete(operationId);
                                        } else {
                                            // Schedule next poll in 15 seconds
                                            CompletableFuture.delayedExecutor(15, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        System.out.println("Error checking baseline operation status: " + ex.getMessage());
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // Start first poll immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails() != null ? e.awsErrorDetails().errorCode() : "UNKNOWN";
                        String errorMessage = e.awsErrorDetails() != null ? e.awsErrorDetails().errorMessage() : e.getMessage();

                        System.out.println("ControlTowerException caught while disabling baseline: Code=" + errorCode + ", Message=" + errorMessage);
                        return null;
                    }

                    if (cause instanceof SdkException sdkEx) {
                        System.out.println("SDK exception caught while disabling baseline: " + sdkEx.getMessage());
                        return null;
                    }

                    System.out.println("Unexpected exception while disabling baseline: " + cause.getMessage());
                    return null;
                });
    }



    /**
     * Gets the status of a baseline operation.
     *
     * @param operationIdentifier the identifier of the operation
     * @return the operation status
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<BaselineOperationStatus> getBaselineOperationAsync(
            String operationIdentifier) {

        GetBaselineOperationRequest request = GetBaselineOperationRequest.builder()
                .operationIdentifier(operationIdentifier)
                .build();

        return getAsyncClient().getBaselineOperation(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null
                                ? exception.getCause()
                                : exception;

                        if (cause instanceof ControlTowerException e) {
                            String errorCode = e.awsErrorDetails().errorCode();

                            if ("ResourceNotFoundException".equals(errorCode)) {
                                throw new CompletionException(
                                        "Baseline operation not found: %s"
                                                .formatted(e.getMessage()),
                                        e
                                );
                            }

                            throw new CompletionException(
                                    "Error getting baseline operation status: %s"
                                            .formatted(e.getMessage()),
                                    e
                            );
                        }

                        if (cause instanceof SdkException) {
                            throw new CompletionException(
                                    "SDK error getting baseline operation status: %s"
                                            .formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException(
                                "Failed to get baseline operation status",
                                cause
                        );
                    }
                })
                .thenApply(response -> {
                    BaselineOperationStatus status =
                            response.baselineOperation().status();
                    return status;
                });
    }


    /**
     * Lists all enabled controls for a specific target using pagination.
     *
     * @param targetIdentifier the identifier of the target (e.g., OU ARN)
     * @return a list of enabled controls
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<EnabledControlSummary>> listEnabledControlsAsync(String targetIdentifier) {
        System.out.println("Starting list enabled controls paginator for target " + targetIdentifier);
        ListEnabledControlsRequest request = ListEnabledControlsRequest.builder()
                .targetIdentifier(targetIdentifier)
                .build();

        ListEnabledControlsPublisher paginator = getAsyncClient().listEnabledControlsPaginator(request);
        List<EnabledControlSummary> enabledControls = new ArrayList<>();

        // Subscribe to the paginator asynchronously
        return paginator.subscribe(response -> {
                    if (response.enabledControls() != null && !response.enabledControls().isEmpty()) {
                        response.enabledControls().forEach(control -> {
                            enabledControls.add(control);
                        });
                    } else {
                        System.out.println("Page contained no enabled controls.");
                    }
                })
                .thenRun(() -> System.out.println(
                        "Successfully retrieved "+enabledControls.size() +" enabled controls for target "+targetIdentifier
                ))
                .thenApply(v -> enabledControls)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        switch (errorCode) {
                            case "AccessDeniedException":
                                throw new CompletionException(
                                        "Access denied when listing enabled controls: %s".formatted(e.getMessage()), e);

                            case "ResourceNotFoundException":
                                if (e.getMessage() != null && e.getMessage().contains("not registered with AWS Control Tower")) {
                                    throw new CompletionException(
                                            "Control Tower must be enabled to work with controls", e);
                                }
                                throw new CompletionException(
                                        "Target not found when listing enabled controls: %s".formatted(e.getMessage()), e);

                            default:
                                throw new CompletionException(
                                        "Error listing enabled controls: %s".formatted(e.getMessage()), e);
                        }
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing enabled controls: %s".formatted(cause.getMessage()), cause);
                    }

                    throw new CompletionException("Failed to list enabled controls", cause);
                });
    }


    /**
     * Enables a control for a specified target.
     *
     * @param controlIdentifier the identifier of the control to enable
     * @param targetIdentifier  the identifier of the target (e.g., OU ARN)
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> enableControlAsync(
            String controlIdentifier,
            String targetIdentifier) {

        EnableControlRequest request = EnableControlRequest.builder()
                .controlIdentifier(controlIdentifier)
                .targetIdentifier(targetIdentifier)
                .build();

        return getAsyncClient().enableControl(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Enable control operation started. Operation ID: " + operationId);

                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getControlOperationAsync(operationId)
                                    .thenAccept(status -> {
                                        System.out.println("Control operation status: " + status);

                                        if (status == ControlOperationStatus.SUCCEEDED
                                                || status == ControlOperationStatus.FAILED) {
                                            resultFuture.complete(operationId);
                                        } else {
                                            // Poll again after 30 seconds
                                            CompletableFuture.delayedExecutor(30, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // Start polling immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();
                        String message = e.getMessage() != null ? e.getMessage() : "";

                        if ("ValidationException".equals(errorCode)
                                && message.contains("already enabled")) {
                            System.out.println("Control is already enabled for this target");
                            return null;
                        }

                        if ("ResourceNotFoundException".equals(errorCode)
                                && message.contains("not registered with AWS Control Tower")) {
                            System.out.println(
                                    "Control Tower must be enabled to work with controls.");
                            return null;
                        }

                        throw new CompletionException(
                                "Couldn't enable control: %s".formatted(message),
                                e
                        );
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error enabling control: %s"
                                        .formatted(cause.getMessage()),
                                cause
                        );
                    }

                    throw new CompletionException(
                            "Failed to enable control",
                            cause
                    );
                });
    }


    /**
     * Disables a control for a specified target.
     *
     * @param controlIdentifier the identifier of the control to disable
     * @param targetIdentifier  the identifier of the target (e.g., OU ARN)
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> disableControlAsync(
            String controlIdentifier,
            String targetIdentifier) {

        DisableControlRequest request = DisableControlRequest.builder()
                .controlIdentifier(controlIdentifier)
                .targetIdentifier(targetIdentifier)
                .build();

        return getAsyncClient().disableControl(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Disable control operation started. Operation ID: " + operationId);

                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getControlOperationAsync(operationId)
                                    .thenAccept(status -> {
                                        System.out.println("Control operation status: " + status);

                                        if (status == ControlOperationStatus.SUCCEEDED
                                                || status == ControlOperationStatus.FAILED) {
                                            resultFuture.complete(operationId);
                                        } else {
                                            // poll again after 30 seconds
                                            CompletableFuture.delayedExecutor(30, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // start polling immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        if ("ResourceNotFoundException".equals(errorCode)) {
                            // SPEC: notify user and continue
                            System.out.println("Control not found for disabling: " + e.getMessage());
                            return null;
                        }

                        throw new CompletionException(
                                "Error disabling control: " + e.getMessage(), e);
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error disabling control: " + cause.getMessage(), cause);
                    }

                    throw new CompletionException(
                            "Failed to disable control", cause);
                });
    }



    /**
     * Gets the status of a control operation.
     *
     * @param operationIdentifier the identifier of the operation
     * @return the operation status
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<ControlOperationStatus> getControlOperationAsync(
            String operationIdentifier) {

        GetControlOperationRequest request = GetControlOperationRequest.builder()
                .operationIdentifier(operationIdentifier)
                .build();

        return getAsyncClient().getControlOperation(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ControlTowerException e) {
                            String errorCode = e.awsErrorDetails().errorCode();

                            if ("ResourceNotFoundException".equals(errorCode)) {
                                throw new CompletionException(
                                        "Control operation not found: %s".formatted(e.getMessage()),
                                        e
                                );
                            }

                            throw new CompletionException(
                                    "Error getting control operation status: %s".formatted(e.getMessage()),
                                    e
                            );
                        }

                        if (cause instanceof SdkException) {
                            throw new CompletionException(
                                    "SDK error getting control operation status: %s".formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException("Failed to get control operation status", cause);
                    }
                })
                .thenApply(response -> response.controlOperation().status());
    }


    /**
     * Lists all controls in the Control Tower control catalog.
     *
     * @return a list of controls
     * @throws SdkException if a service-specific error occurs
     */
    public CompletableFuture<List<ControlSummary>> listControlsAsync() {
        System.out.println("Starting list controls paginator…");

        ListControlsRequest request = ListControlsRequest.builder().build();
        ListControlsPublisher paginator = getAsyncCatClient().listControlsPaginator(request);
        List<ControlSummary> controls = new ArrayList<>();

        return paginator.subscribe(response -> {
                    if (response.controls() != null && !response.controls().isEmpty()) {
                        response.controls().forEach(control -> {
                            controls.add(control);
                        });
                    } else {
                        System.out.println("Page contained no controls.");
                    }
                })
                .thenRun(() -> System.out.println("Successfully retrieved " + controls.size() +" controls."))
                .thenApply(v -> controls)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof SdkException sdkEx) {
                        if (sdkEx.getMessage() != null && sdkEx.getMessage().contains("AccessDeniedException")) {
                            throw new CompletionException(
                                    "Access denied when listing controls. Please ensure you have the necessary permissions.",
                                    sdkEx
                            );
                        } else {
                            throw new CompletionException(
                                    "SDK error listing controls: %s".formatted(sdkEx.getMessage()),
                                    sdkEx
                            );
                        }
                    }

                    throw new CompletionException("Failed to list controls", cause);
                });
    }

    /**
     * Resets an enabled baseline for a specific target.
     *
     * @param enabledBaselineIdentifier the identifier of the enabled baseline to reset
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> resetEnabledBaselineAsync(String enabledBaselineIdentifier) {

        System.out.println("Starting reset of enabled baseline…");
        System.out.println("This operation will check the status every 15 seconds until it completes (SUCCEEDED or FAILED).");

        ResetEnabledBaselineRequest request = ResetEnabledBaselineRequest.builder()
                .enabledBaselineIdentifier(enabledBaselineIdentifier)
                .build();

        return getAsyncClient().resetEnabledBaseline(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Reset enabled baseline operation ID: " + operationId);

                    // Polling loop
                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getBaselineOperationAsync(operationId)
                                    .thenAccept(statusObj -> {
                                        String status = statusObj.toString(); // Convert enum/status to string for printing
                                        System.out.println("Current baseline operation status: " + status + " → waiting for SUCCEEDED or FAILED...");

                                        if ("SUCCEEDED".equalsIgnoreCase(status) || "FAILED".equalsIgnoreCase(status)) {
                                            System.out.println("Baseline operation finished with status: " + status);
                                            resultFuture.complete(operationId);
                                        } else {
                                            // Schedule next poll in 15 seconds
                                            CompletableFuture.delayedExecutor(15, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        System.out.println("Error checking baseline operation status: " + ex.getMessage());
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // Start first poll immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails() != null ? e.awsErrorDetails().errorCode() : "UNKNOWN";
                        String errorMessage = e.awsErrorDetails() != null ? e.awsErrorDetails().errorMessage() : e.getMessage();

                        System.out.println("ControlTowerException caught: Code=" + errorCode + ", Message=" + errorMessage);
                        return null;
                    }

                    if (cause instanceof SdkException sdkEx) {
                        System.out.println("SDK exception caught: " + sdkEx.getMessage());
                        return null;
                    }

                    System.out.println("Unexpected exception resetting baseline: " + cause.getMessage());
                    return null;
                });
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateLandingZone](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/CreateLandingZone)
  + [DeleteLandingZone](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/DeleteLandingZone)
  + [DisableBaseline](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/DisableBaseline)
  + [DisableControl](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/DisableControl)
  + [EnableBaseline](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/EnableBaseline)
  + [EnableControl](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/EnableControl)
  + [GetControlOperation](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/GetControlOperation)
  + [GetLandingZoneOperation](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/GetLandingZoneOperation)
  + [ListBaselines](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListBaselines)
  + [ListEnabledBaselines](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListEnabledBaselines)
  + [ListEnabledControls](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListEnabledControls)
  + [ListLandingZones](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListLandingZones)
  + [ResetEnabledBaseline](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ResetEnabledBaseline)

## アクション
<a name="actions"></a>

### `DisableBaseline`
<a name="controltower_DisableBaseline_java_2_topic"></a>

次の例は、`DisableBaseline` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Disables a baseline for a specified target.
     *
     * @param enabledBaselineIdentifier the identifier of the enabled baseline to disable
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> disableBaselineAsync(String enabledBaselineIdentifier) {

        System.out.println("Starting disable of enabled baseline…");
        System.out.println("This operation will check the status every 15 seconds until it completes (SUCCEEDED or FAILED).");

        DisableBaselineRequest request = DisableBaselineRequest.builder()
                .enabledBaselineIdentifier(enabledBaselineIdentifier)
                .build();

        return getAsyncClient().disableBaseline(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Disable baseline operation ID: " + operationId);

                    // CompletableFuture that will be completed when operation finishes
                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    // Polling loop
                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getBaselineOperationAsync(operationId)
                                    .thenAccept(statusObj -> {
                                        String status = statusObj.toString(); // Convert enum/status to string for printing
                                        System.out.println("Current disable operation status: " + status + " → waiting for SUCCEEDED or FAILED...");

                                        if ("SUCCEEDED".equalsIgnoreCase(status) || "FAILED".equalsIgnoreCase(status)) {
                                            System.out.println("Disable operation finished with status: " + status);
                                            resultFuture.complete(operationId);
                                        } else {
                                            // Schedule next poll in 15 seconds
                                            CompletableFuture.delayedExecutor(15, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        System.out.println("Error checking baseline operation status: " + ex.getMessage());
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // Start first poll immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails() != null ? e.awsErrorDetails().errorCode() : "UNKNOWN";
                        String errorMessage = e.awsErrorDetails() != null ? e.awsErrorDetails().errorMessage() : e.getMessage();

                        System.out.println("ControlTowerException caught while disabling baseline: Code=" + errorCode + ", Message=" + errorMessage);
                        return null;
                    }

                    if (cause instanceof SdkException sdkEx) {
                        System.out.println("SDK exception caught while disabling baseline: " + sdkEx.getMessage());
                        return null;
                    }

                    System.out.println("Unexpected exception while disabling baseline: " + cause.getMessage());
                    return null;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DisableBaseline](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/DisableBaseline)」を参照してください。

### `DisableControl`
<a name="controltower_DisableControl_java_2_topic"></a>

次の例は、`DisableControl` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Disables a control for a specified target.
     *
     * @param controlIdentifier the identifier of the control to disable
     * @param targetIdentifier  the identifier of the target (e.g., OU ARN)
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> disableControlAsync(
            String controlIdentifier,
            String targetIdentifier) {

        DisableControlRequest request = DisableControlRequest.builder()
                .controlIdentifier(controlIdentifier)
                .targetIdentifier(targetIdentifier)
                .build();

        return getAsyncClient().disableControl(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Disable control operation started. Operation ID: " + operationId);

                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getControlOperationAsync(operationId)
                                    .thenAccept(status -> {
                                        System.out.println("Control operation status: " + status);

                                        if (status == ControlOperationStatus.SUCCEEDED
                                                || status == ControlOperationStatus.FAILED) {
                                            resultFuture.complete(operationId);
                                        } else {
                                            // poll again after 30 seconds
                                            CompletableFuture.delayedExecutor(30, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // start polling immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        if ("ResourceNotFoundException".equals(errorCode)) {
                            // SPEC: notify user and continue
                            System.out.println("Control not found for disabling: " + e.getMessage());
                            return null;
                        }

                        throw new CompletionException(
                                "Error disabling control: " + e.getMessage(), e);
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error disabling control: " + cause.getMessage(), cause);
                    }

                    throw new CompletionException(
                            "Failed to disable control", cause);
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DisableControl](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/DisableControl)」を参照してください。

### `EnableBaseline`
<a name="controltower_EnableBaseline_java_2_topic"></a>

次の例は、`EnableBaseline` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously enables a baseline for the specified target if not already enabled.
     *
     * @param targetIdentifier       The ARN of the target (OU or account).
     * @param baselineIdentifier     The baseline definition ARN to enable.
     * @param baselineVersion        The baseline version to enable.
     * @return A CompletableFuture containing the enabled baseline ARN, or null if already enabled.
     */
    public CompletableFuture<String> enableBaselineAsync(
            String targetIdentifier,
            String baselineIdentifier,
            String baselineVersion
    ) {
        EnableBaselineRequest request = EnableBaselineRequest.builder()
                .baselineIdentifier(baselineIdentifier)
                .baselineVersion(baselineVersion)
                .targetIdentifier(targetIdentifier)
                .build();

        return getAsyncClient().enableBaseline(request)
                .handle((resp, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ControlTowerException e) {
                            String code = e.awsErrorDetails() != null ? e.awsErrorDetails().errorCode() : "UNKNOWN";
                            String msg = e.awsErrorDetails() != null ? e.awsErrorDetails().errorMessage() : e.getMessage();

                            if ("ValidationException".equals(code) && msg.contains("already enabled")) {
                                System.out.println("Baseline is already enabled for this target → fetching ARN...");
                                return fetchEnabledBaselineArn(targetIdentifier, baselineIdentifier)
                                        .join(); // fetch existing ARN synchronously
                            }

                            throw new RuntimeException("Error enabling baseline: " + code + " - " + msg, e);
                        }

                        throw new RuntimeException("Unexpected error enabling baseline: " + cause.getMessage(), cause);
                    }

                    return resp;
                })
                .thenCompose(result -> {
                    if (result instanceof EnableBaselineResponse resp) {
                        String operationId = resp.operationIdentifier();
                        String enabledBaselineArn = resp.arn();
                        System.out.println("Baseline enable started. ARN: " + enabledBaselineArn
                                + ", operation ID: " + operationId);

                        // Inline polling
                        return CompletableFuture.supplyAsync(() -> {
                            while (true) {
                                GetBaselineOperationRequest opReq = GetBaselineOperationRequest.builder()
                                        .operationIdentifier(operationId)
                                        .build();

                                GetBaselineOperationResponse opResp = getAsyncClient().getBaselineOperation(opReq).join();
                                BaselineOperation op = opResp.baselineOperation();
                                BaselineOperationStatus status = op.status();
                                System.out.println("Operation " + operationId + " status: " + status);

                                if (status == BaselineOperationStatus.SUCCEEDED) {
                                    return enabledBaselineArn;
                                } else if (status == BaselineOperationStatus.FAILED) {
                                    String opId = op.operationIdentifier();
                                    String reason = op.statusMessage() != null ? op.statusMessage() : "No failure reason provided";
                                    throw new RuntimeException("Baseline operation failed (ID: " + opId + "), status: "
                                            + status + ", reason: " + reason);
                                }

                                try {
                                    Thread.sleep(Duration.ofSeconds(15).toMillis());
                                } catch (InterruptedException e) {
                                    Thread.currentThread().interrupt();
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                    } else if (result instanceof String existingArn) {
                        // Already enabled branch
                        return CompletableFuture.completedFuture(existingArn);
                    }

                    return CompletableFuture.completedFuture(null);
                });
    }


    /**
     * Fetches the ARN of an already-enabled baseline for the target asynchronously.
     */
    private CompletableFuture<String> fetchEnabledBaselineArn(String targetIdentifier, String baselineIdentifier) {
        return getAsyncClient().listEnabledBaselines(ListEnabledBaselinesRequest.builder().build())
                .thenApply(listResp -> {
                    for (EnabledBaselineSummary eb : listResp.enabledBaselines()) {
                        if (baselineIdentifier.equals(eb.baselineIdentifier())
                                && targetIdentifier.equals(eb.targetIdentifier())) {
                            return eb.arn();
                        }
                    }
                    return null; // not yet available
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[EnableBaseline](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/EnableBaseline)」を参照してください。

### `EnableControl`
<a name="controltower_EnableControl_java_2_topic"></a>

次の例は、`EnableControl` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Enables a control for a specified target.
     *
     * @param controlIdentifier the identifier of the control to enable
     * @param targetIdentifier  the identifier of the target (e.g., OU ARN)
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> enableControlAsync(
            String controlIdentifier,
            String targetIdentifier) {

        EnableControlRequest request = EnableControlRequest.builder()
                .controlIdentifier(controlIdentifier)
                .targetIdentifier(targetIdentifier)
                .build();

        return getAsyncClient().enableControl(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Enable control operation started. Operation ID: " + operationId);

                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getControlOperationAsync(operationId)
                                    .thenAccept(status -> {
                                        System.out.println("Control operation status: " + status);

                                        if (status == ControlOperationStatus.SUCCEEDED
                                                || status == ControlOperationStatus.FAILED) {
                                            resultFuture.complete(operationId);
                                        } else {
                                            // Poll again after 30 seconds
                                            CompletableFuture.delayedExecutor(30, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // Start polling immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();
                        String message = e.getMessage() != null ? e.getMessage() : "";

                        if ("ValidationException".equals(errorCode)
                                && message.contains("already enabled")) {
                            System.out.println("Control is already enabled for this target");
                            return null;
                        }

                        if ("ResourceNotFoundException".equals(errorCode)
                                && message.contains("not registered with AWS Control Tower")) {
                            System.out.println(
                                    "Control Tower must be enabled to work with controls.");
                            return null;
                        }

                        throw new CompletionException(
                                "Couldn't enable control: %s".formatted(message),
                                e
                        );
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error enabling control: %s"
                                        .formatted(cause.getMessage()),
                                cause
                        );
                    }

                    throw new CompletionException(
                            "Failed to enable control",
                            cause
                    );
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[EnableControl](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/EnableControl)」を参照してください。

### `GetBaselineOperation`
<a name="controltower_GetBaselineOperation_java_2_topic"></a>

次の例は、`GetBaselineOperation` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Gets the status of a baseline operation.
     *
     * @param operationIdentifier the identifier of the operation
     * @return the operation status
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<BaselineOperationStatus> getBaselineOperationAsync(
            String operationIdentifier) {

        GetBaselineOperationRequest request = GetBaselineOperationRequest.builder()
                .operationIdentifier(operationIdentifier)
                .build();

        return getAsyncClient().getBaselineOperation(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null
                                ? exception.getCause()
                                : exception;

                        if (cause instanceof ControlTowerException e) {
                            String errorCode = e.awsErrorDetails().errorCode();

                            if ("ResourceNotFoundException".equals(errorCode)) {
                                throw new CompletionException(
                                        "Baseline operation not found: %s"
                                                .formatted(e.getMessage()),
                                        e
                                );
                            }

                            throw new CompletionException(
                                    "Error getting baseline operation status: %s"
                                            .formatted(e.getMessage()),
                                    e
                            );
                        }

                        if (cause instanceof SdkException) {
                            throw new CompletionException(
                                    "SDK error getting baseline operation status: %s"
                                            .formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException(
                                "Failed to get baseline operation status",
                                cause
                        );
                    }
                })
                .thenApply(response -> {
                    BaselineOperationStatus status =
                            response.baselineOperation().status();
                    return status;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetBaselineOperation](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/GetBaselineOperation)」を参照してください。

### `GetControlOperation`
<a name="controltower_GetControlOperation_java_2_topic"></a>

次の例は、`GetControlOperation` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Gets the status of a control operation.
     *
     * @param operationIdentifier the identifier of the operation
     * @return the operation status
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<ControlOperationStatus> getControlOperationAsync(
            String operationIdentifier) {

        GetControlOperationRequest request = GetControlOperationRequest.builder()
                .operationIdentifier(operationIdentifier)
                .build();

        return getAsyncClient().getControlOperation(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ControlTowerException e) {
                            String errorCode = e.awsErrorDetails().errorCode();

                            if ("ResourceNotFoundException".equals(errorCode)) {
                                throw new CompletionException(
                                        "Control operation not found: %s".formatted(e.getMessage()),
                                        e
                                );
                            }

                            throw new CompletionException(
                                    "Error getting control operation status: %s".formatted(e.getMessage()),
                                    e
                            );
                        }

                        if (cause instanceof SdkException) {
                            throw new CompletionException(
                                    "SDK error getting control operation status: %s".formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException("Failed to get control operation status", cause);
                    }
                })
                .thenApply(response -> response.controlOperation().status());
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetControlOperation](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/GetControlOperation)」を参照してください。

### `ListBaselines`
<a name="controltower_ListBaselines_java_2_topic"></a>

次の例は、`ListBaselines` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists all available baselines using pagination to retrieve complete results.
     *
     * @return a list of all baselines
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<BaselineSummary>> listBaselinesAsync() {
        System.out.println("Starting list baselines paginator…");
        ListBaselinesRequest request = ListBaselinesRequest.builder().build();
        ListBaselinesPublisher paginator =
                getAsyncClient().listBaselinesPaginator(request);

        List<BaselineSummary> baselines = new ArrayList<>();
        return paginator.subscribe(response -> {
                    if (response.baselines() != null && !response.baselines().isEmpty()) {
                        response.baselines().forEach(baseline -> {
                            baselines.add(baseline);
                        });
                    } else {
                        System.out.println("Page contained no baselines.");
                    }
                })
                .thenRun(() ->
                        System.out.println("Successfully listed baselines. Total: " + baselines.size())
                )
                .thenApply(v -> baselines)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        if ("AccessDeniedException".equals(errorCode)) {
                            throw new CompletionException(
                                    "Access denied when listing baselines: %s".formatted(e.getMessage()),
                                    e
                            );
                        }

                        throw new CompletionException(
                                "Error listing baselines: %s".formatted(e.getMessage()),
                                e
                        );
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing baselines: %s".formatted(cause.getMessage()),
                                cause
                        );
                    }

                    throw new CompletionException("Failed to list baselines", cause);
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListBaselines](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListBaselines)」を参照してください。

### `ListEnabledBaselines`
<a name="controltower_ListEnabledBaselines_java_2_topic"></a>

次の例は、`ListEnabledBaselines` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists all enabled baselines using pagination to retrieve complete results.
     *
     * @return a list of all enabled baselines
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<EnabledBaselineSummary>> listEnabledBaselinesAsync() {
        System.out.println("Starting list enabled baselines paginator…");

        ListEnabledBaselinesRequest request =
                ListEnabledBaselinesRequest.builder().build();

        ListEnabledBaselinesPublisher paginator =
                getAsyncClient().listEnabledBaselinesPaginator(request);

        List<EnabledBaselineSummary> enabledBaselines = new ArrayList<>();
        return paginator.subscribe(response -> {
                    if (response.enabledBaselines() != null
                            && !response.enabledBaselines().isEmpty()) {

                        response.enabledBaselines().forEach(baseline -> {
                            enabledBaselines.add(baseline);
                        });
                    } else {
                        System.out.println("Page contained no enabled baselines.");
                    }
                })
                .thenRun(() ->
                        System.out.println(
                                "Successfully listed enabled baselines. Total: " +
                                        enabledBaselines.size()
                        )
                )
                .thenApply(v -> enabledBaselines)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        if ("AccessDeniedException".equals(errorCode)) {
                            throw new CompletionException(
                                    "Access denied when listing enabled baselines: %s".formatted(e.getMessage()), e);
                        }

                        throw new CompletionException(
                                "Error listing enabled baselines: %s"
                                        .formatted(e.getMessage()),
                                e
                        );
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing enabled baselines: %s"
                                        .formatted(cause.getMessage()),
                                cause
                        );
                    }

                    throw new CompletionException(
                            "Failed to list enabled baselines",
                            cause
                    );
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListEnabledBaselines](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListEnabledBaselines)」を参照してください。

### `ListEnabledControls`
<a name="controltower_ListEnabledControls_java_2_topic"></a>

次の例は、`ListEnabledControls` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists all enabled controls for a specific target using pagination.
     *
     * @param targetIdentifier the identifier of the target (e.g., OU ARN)
     * @return a list of enabled controls
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<EnabledControlSummary>> listEnabledControlsAsync(String targetIdentifier) {
        System.out.println("Starting list enabled controls paginator for target " + targetIdentifier);
        ListEnabledControlsRequest request = ListEnabledControlsRequest.builder()
                .targetIdentifier(targetIdentifier)
                .build();

        ListEnabledControlsPublisher paginator = getAsyncClient().listEnabledControlsPaginator(request);
        List<EnabledControlSummary> enabledControls = new ArrayList<>();

        // Subscribe to the paginator asynchronously
        return paginator.subscribe(response -> {
                    if (response.enabledControls() != null && !response.enabledControls().isEmpty()) {
                        response.enabledControls().forEach(control -> {
                            enabledControls.add(control);
                        });
                    } else {
                        System.out.println("Page contained no enabled controls.");
                    }
                })
                .thenRun(() -> System.out.println(
                        "Successfully retrieved "+enabledControls.size() +" enabled controls for target "+targetIdentifier
                ))
                .thenApply(v -> enabledControls)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();

                        switch (errorCode) {
                            case "AccessDeniedException":
                                throw new CompletionException(
                                        "Access denied when listing enabled controls: %s".formatted(e.getMessage()), e);

                            case "ResourceNotFoundException":
                                if (e.getMessage() != null && e.getMessage().contains("not registered with AWS Control Tower")) {
                                    throw new CompletionException(
                                            "Control Tower must be enabled to work with controls", e);
                                }
                                throw new CompletionException(
                                        "Target not found when listing enabled controls: %s".formatted(e.getMessage()), e);

                            default:
                                throw new CompletionException(
                                        "Error listing enabled controls: %s".formatted(e.getMessage()), e);
                        }
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing enabled controls: %s".formatted(cause.getMessage()), cause);
                    }

                    throw new CompletionException("Failed to list enabled controls", cause);
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListEnabledControls](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListEnabledControls)」を参照してください。

### `ListLandingZones`
<a name="controltower_ListLandingZones_java_2_topic"></a>

次の例は、`ListLandingZones` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists all landing zones using pagination to retrieve complete results.
     *
     * @return a list of all landing zones
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<List<LandingZoneSummary>> listLandingZonesAsync() {
        System.out.println("Starting list landing zones paginator…");

        ListLandingZonesRequest request = ListLandingZonesRequest.builder().build();
        ListLandingZonesPublisher paginator = getAsyncClient().listLandingZonesPaginator(request);
        List<LandingZoneSummary> landingZones = new ArrayList<>();

        return paginator.subscribe(response -> {
                    if (response.landingZones() != null && !response.landingZones().isEmpty()) {
                        response.landingZones().forEach(lz -> {
                            System.out.println("Landing zone ARN: " + lz.arn());
                            landingZones.add(lz);
                        });
                    } else {
                        System.out.println("Page contained no landing zones.");
                    }
                })
                .thenRun(() -> System.out.println("Successfully retrieved "+ landingZones.size() + " landing zones." ))
                .thenApply(v -> landingZones)
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails().errorCode();
                        switch (errorCode) {
                            case "AccessDeniedException":
                                throw new CompletionException(
                                        "Access denied when listing landing zones: " + e.getMessage(), e);
                            default:
                                throw new CompletionException(
                                        "Error listing landing zones: " + e.getMessage(), e);
                        }
                    }

                    if (cause instanceof SdkException) {
                        throw new CompletionException(
                                "SDK error listing landing zones: " + cause.getMessage(), cause);
                    }

                    throw new CompletionException("Failed to list landing zones", cause);
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListLandingZones](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ListLandingZones)」を参照してください。

### `ResetEnabledBaseline`
<a name="controltower_ResetEnabledBaseline_java_2_topic"></a>

次の例は、`ResetEnabledBaseline` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Resets an enabled baseline for a specific target.
     *
     * @param enabledBaselineIdentifier the identifier of the enabled baseline to reset
     * @return the operation identifier
     * @throws ControlTowerException if a service-specific error occurs
     * @throws SdkException          if an SDK error occurs
     */
    public CompletableFuture<String> resetEnabledBaselineAsync(String enabledBaselineIdentifier) {

        System.out.println("Starting reset of enabled baseline…");
        System.out.println("This operation will check the status every 15 seconds until it completes (SUCCEEDED or FAILED).");

        ResetEnabledBaselineRequest request = ResetEnabledBaselineRequest.builder()
                .enabledBaselineIdentifier(enabledBaselineIdentifier)
                .build();

        return getAsyncClient().resetEnabledBaseline(request)
                .thenCompose(response -> {
                    String operationId = response.operationIdentifier();
                    System.out.println("Reset enabled baseline operation ID: " + operationId);

                    // Polling loop
                    CompletableFuture<String> resultFuture = new CompletableFuture<>();

                    Runnable poller = new Runnable() {
                        @Override
                        public void run() {
                            getBaselineOperationAsync(operationId)
                                    .thenAccept(statusObj -> {
                                        String status = statusObj.toString(); // Convert enum/status to string for printing
                                        System.out.println("Current baseline operation status: " + status + " → waiting for SUCCEEDED or FAILED...");

                                        if ("SUCCEEDED".equalsIgnoreCase(status) || "FAILED".equalsIgnoreCase(status)) {
                                            System.out.println("Baseline operation finished with status: " + status);
                                            resultFuture.complete(operationId);
                                        } else {
                                            // Schedule next poll in 15 seconds
                                            CompletableFuture.delayedExecutor(15, TimeUnit.SECONDS)
                                                    .execute(this);
                                        }
                                    })
                                    .exceptionally(ex -> {
                                        System.out.println("Error checking baseline operation status: " + ex.getMessage());
                                        resultFuture.completeExceptionally(ex);
                                        return null;
                                    });
                        }
                    };

                    // Start first poll immediately
                    poller.run();

                    return resultFuture;
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ControlTowerException e) {
                        String errorCode = e.awsErrorDetails() != null ? e.awsErrorDetails().errorCode() : "UNKNOWN";
                        String errorMessage = e.awsErrorDetails() != null ? e.awsErrorDetails().errorMessage() : e.getMessage();

                        System.out.println("ControlTowerException caught: Code=" + errorCode + ", Message=" + errorMessage);
                        return null;
                    }

                    if (cause instanceof SdkException sdkEx) {
                        System.out.println("SDK exception caught: " + sdkEx.getMessage());
                        return null;
                    }

                    System.out.println("Unexpected exception resetting baseline: " + cause.getMessage());
                    return null;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ResetEnabledBaseline](https://docs.aws.amazon.com/goto/SdkForJavaV2/controltower-2018-05-10/ResetEnabledBaseline)」を参照してください。

# SDK for Java 2.x を使用した Firehose の例
<a name="java_2_firehose_code_examples"></a>

次のコード例は、Firehose AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `PutRecord`
<a name="firehose_PutRecord_java_2_topic"></a>

次のコード例は、`PutRecord` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/firehose#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Puts a record to the specified Amazon Kinesis Data Firehose delivery stream.
     *
     * @param record The record to be put to the delivery stream. The record must be a {@link Map} of String keys and Object values.
     * @param deliveryStreamName The name of the Amazon Kinesis Data Firehose delivery stream to which the record should be put.
     * @throws IllegalArgumentException if the input record or delivery stream name is null or empty.
     * @throws RuntimeException if there is an error putting the record to the delivery stream.
     */
    public static void putRecord(Map<String, Object> record, String deliveryStreamName) {
        if (record == null || deliveryStreamName == null || deliveryStreamName.isEmpty()) {
            throw new IllegalArgumentException("Invalid input: record or delivery stream name cannot be null/empty");
        }
        try {
            String jsonRecord = new ObjectMapper().writeValueAsString(record);
            Record firehoseRecord = Record.builder()
                .data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))
                .build();

            PutRecordRequest putRecordRequest = PutRecordRequest.builder()
                .deliveryStreamName(deliveryStreamName)
                .record(firehoseRecord)
                .build();

            getFirehoseClient().putRecord(putRecordRequest);
            System.out.println("Record sent: " + jsonRecord);
        } catch (Exception e) {
            throw new RuntimeException("Failed to put record: " + e.getMessage(), e);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutRecord](https://docs.aws.amazon.com/goto/SdkForJavaV2/firehose-2015-08-04/PutRecord)」を参照してください。

### `PutRecordBatch`
<a name="firehose_PutRecordBatch_java_2_topic"></a>

次のコード例は、`PutRecordBatch` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/firehose#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Puts a batch of records to an Amazon Kinesis Data Firehose delivery stream.
     *
     * @param records           a list of maps representing the records to be sent
     * @param batchSize         the maximum number of records to include in each batch
     * @param deliveryStreamName the name of the Kinesis Data Firehose delivery stream
     * @throws IllegalArgumentException if the input parameters are invalid (null or empty)
     * @throws RuntimeException         if there is an error putting the record batch
     */
    public static void putRecordBatch(List<Map<String, Object>> records, int batchSize, String deliveryStreamName) {
        if (records == null || records.isEmpty() || deliveryStreamName == null || deliveryStreamName.isEmpty()) {
            throw new IllegalArgumentException("Invalid input: records or delivery stream name cannot be null/empty");
        }
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            for (int i = 0; i < records.size(); i += batchSize) {
                List<Map<String, Object>> batch = records.subList(i, Math.min(i + batchSize, records.size()));

                List<Record> batchRecords = batch.stream().map(record -> {
                    try {
                        String jsonRecord = objectMapper.writeValueAsString(record);
                        return Record.builder()
                            .data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))
                            .build();
                    } catch (Exception e) {
                        throw new RuntimeException("Error creating Firehose record", e);
                    }
                }).collect(Collectors.toList());

                PutRecordBatchRequest request = PutRecordBatchRequest.builder()
                    .deliveryStreamName(deliveryStreamName)
                    .records(batchRecords)
                    .build();

                PutRecordBatchResponse response = getFirehoseClient().putRecordBatch(request);

                if (response.failedPutCount() > 0) {
                    response.requestResponses().stream()
                        .filter(r -> r.errorCode() != null)
                        .forEach(r -> System.err.println("Failed record: " + r.errorMessage()));
                }
                System.out.println("Batch sent with size: " + batchRecords.size());
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to put record batch: " + e.getMessage(), e);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutRecordBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/firehose-2015-08-04/PutRecordBatch)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Firehose にレコードを配置する
<a name="firehose_Scenario_PutRecords_java_2_topic"></a>

次のコード例は、Firehose を使用して個別レコードとバッチレコードを処理する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/firehose#code-examples)での設定と実行の方法を確認してください。
この例では、個別レコードとバッチレコードを Firehose に配置します。  

```
/**
 * Amazon Firehose Scenario example using Java V2 SDK.
 *
 * Demonstrates individual and batch record processing,
 * and monitoring Firehose delivery stream metrics.
 */
public class FirehoseScenario {

    private static FirehoseClient firehoseClient;
    private static CloudWatchClient cloudWatchClient;

    public static void main(String[] args) {
        final String usage = """
                Usage:
                    <deliveryStreamName>
                Where:
                    deliveryStreamName - The Firehose delivery stream name.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            return;
        }

        String deliveryStreamName = args[0];

        try {
            // Read and parse sample data.
            String jsonContent = readJsonFile("sample_records.json");
            ObjectMapper objectMapper = new ObjectMapper();
            List<Map<String, Object>> sampleData = objectMapper.readValue(jsonContent, new TypeReference<>() {});

            // Process individual records.
            System.out.println("Processing individual records...");
            sampleData.subList(0, 100).forEach(record -> {
                try {
                    putRecord(record, deliveryStreamName);
                } catch (Exception e) {
                    System.err.println("Error processing record: " + e.getMessage());
                }
            });

            // Monitor metrics.
            monitorMetrics(deliveryStreamName);

            // Process batch records.
            System.out.println("Processing batch records...");
            putRecordBatch(sampleData.subList(100, sampleData.size()), 500, deliveryStreamName);
            monitorMetrics(deliveryStreamName);

        } catch (Exception e) {
            System.err.println("Scenario failed: " + e.getMessage());
        } finally {
            closeClients();
        }
    }

    private static FirehoseClient getFirehoseClient() {
        if (firehoseClient == null) {
            firehoseClient = FirehoseClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return firehoseClient;
    }

    private static CloudWatchClient getCloudWatchClient() {
        if (cloudWatchClient == null) {
            cloudWatchClient = CloudWatchClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return cloudWatchClient;
    }

    /**
     * Puts a record to the specified Amazon Kinesis Data Firehose delivery stream.
     *
     * @param record The record to be put to the delivery stream. The record must be a {@link Map} of String keys and Object values.
     * @param deliveryStreamName The name of the Amazon Kinesis Data Firehose delivery stream to which the record should be put.
     * @throws IllegalArgumentException if the input record or delivery stream name is null or empty.
     * @throws RuntimeException if there is an error putting the record to the delivery stream.
     */
    public static void putRecord(Map<String, Object> record, String deliveryStreamName) {
        if (record == null || deliveryStreamName == null || deliveryStreamName.isEmpty()) {
            throw new IllegalArgumentException("Invalid input: record or delivery stream name cannot be null/empty");
        }
        try {
            String jsonRecord = new ObjectMapper().writeValueAsString(record);
            Record firehoseRecord = Record.builder()
                .data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))
                .build();

            PutRecordRequest putRecordRequest = PutRecordRequest.builder()
                .deliveryStreamName(deliveryStreamName)
                .record(firehoseRecord)
                .build();

            getFirehoseClient().putRecord(putRecordRequest);
            System.out.println("Record sent: " + jsonRecord);
        } catch (Exception e) {
            throw new RuntimeException("Failed to put record: " + e.getMessage(), e);
        }
    }


    /**
     * Puts a batch of records to an Amazon Kinesis Data Firehose delivery stream.
     *
     * @param records           a list of maps representing the records to be sent
     * @param batchSize         the maximum number of records to include in each batch
     * @param deliveryStreamName the name of the Kinesis Data Firehose delivery stream
     * @throws IllegalArgumentException if the input parameters are invalid (null or empty)
     * @throws RuntimeException         if there is an error putting the record batch
     */
    public static void putRecordBatch(List<Map<String, Object>> records, int batchSize, String deliveryStreamName) {
        if (records == null || records.isEmpty() || deliveryStreamName == null || deliveryStreamName.isEmpty()) {
            throw new IllegalArgumentException("Invalid input: records or delivery stream name cannot be null/empty");
        }
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            for (int i = 0; i < records.size(); i += batchSize) {
                List<Map<String, Object>> batch = records.subList(i, Math.min(i + batchSize, records.size()));

                List<Record> batchRecords = batch.stream().map(record -> {
                    try {
                        String jsonRecord = objectMapper.writeValueAsString(record);
                        return Record.builder()
                            .data(SdkBytes.fromByteArray(jsonRecord.getBytes(StandardCharsets.UTF_8)))
                            .build();
                    } catch (Exception e) {
                        throw new RuntimeException("Error creating Firehose record", e);
                    }
                }).collect(Collectors.toList());

                PutRecordBatchRequest request = PutRecordBatchRequest.builder()
                    .deliveryStreamName(deliveryStreamName)
                    .records(batchRecords)
                    .build();

                PutRecordBatchResponse response = getFirehoseClient().putRecordBatch(request);

                if (response.failedPutCount() > 0) {
                    response.requestResponses().stream()
                        .filter(r -> r.errorCode() != null)
                        .forEach(r -> System.err.println("Failed record: " + r.errorMessage()));
                }
                System.out.println("Batch sent with size: " + batchRecords.size());
            }
        } catch (Exception e) {
            throw new RuntimeException("Failed to put record batch: " + e.getMessage(), e);
        }
    }

    public static void monitorMetrics(String deliveryStreamName) {
        Instant endTime = Instant.now();
        Instant startTime = endTime.minusSeconds(600);

        List<String> metrics = List.of("IncomingBytes", "IncomingRecords", "FailedPutCount");
        metrics.forEach(metric -> monitorMetric(metric, startTime, endTime, deliveryStreamName));
    }

    private static void monitorMetric(String metricName, Instant startTime, Instant endTime, String deliveryStreamName) {
        try {
            GetMetricStatisticsRequest request = GetMetricStatisticsRequest.builder()
                .namespace("AWS/Firehose")
                .metricName(metricName)
                .dimensions(Dimension.builder().name("DeliveryStreamName").value(deliveryStreamName).build())
                .startTime(startTime)
                .endTime(endTime)
                .period(60)
                .statistics(Statistic.SUM)
                .build();

            GetMetricStatisticsResponse response = getCloudWatchClient().getMetricStatistics(request);
            double totalSum = response.datapoints().stream().mapToDouble(Datapoint::sum).sum();
            System.out.println(metricName + ": " + totalSum);
        } catch (Exception e) {
            System.err.println("Failed to monitor metric " + metricName + ": " + e.getMessage());
        }
    }

    public static String readJsonFile(String fileName) throws IOException {
        try (InputStream inputStream = FirehoseScenario.class.getResourceAsStream("/" + fileName);
             Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8)) {
            return scanner.useDelimiter("\\\\A").next();
        } catch (Exception e) {
            throw new RuntimeException("Error reading file: " + fileName, e);
        }
    }

    private static void closeClients() {
        try {
            if (firehoseClient != null) firehoseClient.close();
            if (cloudWatchClient != null) cloudWatchClient.close();
        } catch (Exception e) {
            System.err.println("Error closing clients: " + e.getMessage());
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [PutRecord](https://docs.aws.amazon.com/goto/SdkForJavaV2/firehose-2015-08-04/PutRecord)
  + [PutRecordBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/firehose-2015-08-04/PutRecordBatch)

# SDK for Java 2.x を使用する Amazon DocumentDB の例
<a name="java_2_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_java_2_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Amazon DocumentDB イベントの消費。  

```
import java.util.List;
import java.util.Map;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class Example implements RequestHandler<Map<String, Object>, String> {

    @SuppressWarnings("unchecked")
    @Override
    public String handleRequest(Map<String, Object> event, Context context) {
        List<Map<String, Object>> events = (List<Map<String, Object>>) event.get("events");
        for (Map<String, Object> record : events) {
            Map<String, Object> eventData = (Map<String, Object>) record.get("event");
            processEventData(eventData);
        }

        return "OK";
    }

    @SuppressWarnings("unchecked")
    private void processEventData(Map<String, Object> eventData) {
        String operationType = (String) eventData.get("operationType");
        System.out.println("operationType: %s".formatted(operationType));

        Map<String, Object> ns = (Map<String, Object>) eventData.get("ns");

        String db = (String) ns.get("db");
        System.out.println("db: %s".formatted(db));
        String coll = (String) ns.get("coll");
        System.out.println("coll: %s".formatted(coll));

        Map<String, Object> fullDocument = (Map<String, Object>) eventData.get("fullDocument");
        System.out.println("fullDocument: %s".formatted(fullDocument));
    }

}
```

# SDK for Java 2.x を使用した DynamoDB の例
<a name="java_2_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## はじめに
<a name="get_started"></a>

### Hello DynamoDB
<a name="dynamodb_Hello_java_2_topic"></a>

次のコード例は、DynamoDB の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;
import java.util.List;

/**
 * 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 ListTables {
    public static void main(String[] args) {
        System.out.println("Listing your Amazon DynamoDB tables:\n");
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();
        listAllTables(ddb);
        ddb.close();
    }

    public static void listAllTables(DynamoDbClient ddb) {
        boolean moreTables = true;
        String lastName = null;

        while (moreTables) {
            try {
                ListTablesResponse response = null;
                if (lastName == null) {
                    ListTablesRequest request = ListTablesRequest.builder().build();
                    response = ddb.listTables(request);
                } else {
                    ListTablesRequest request = ListTablesRequest.builder()
                            .exclusiveStartTableName(lastName).build();
                    response = ddb.listTables(request);
                }

                List<String> tableNames = response.tableNames();
                if (tableNames.size() > 0) {
                    for (String curName : tableNames) {
                        System.out.format("* %s\n", curName);
                    }
                } else {
                    System.out.println("No tables found!");
                    System.exit(0);
                }

                lastName = response.lastEvaluatedTableName();
                if (lastName == null) {
                    moreTables = false;
                }

            } catch (DynamoDbException e) {
                System.err.println(e.getMessage());
                System.exit(1);
            }
        }
        System.out.println("\nDone!");
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[ListTables](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/ListTables)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
DynamoDB テーブルを作成します。  

```
    // Create a table with a Sort key.
    public static void createTable(DynamoDbClient ddb, String tableName) {
        DynamoDbWaiter dbWaiter = ddb.waiter();
        ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>();

        // Define attributes.
        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("year")
            .attributeType("N")
            .build());

        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("title")
            .attributeType("S")
            .build());

        ArrayList<KeySchemaElement> tableKey = new ArrayList<>();
        KeySchemaElement key = KeySchemaElement.builder()
            .attributeName("year")
            .keyType(KeyType.HASH)
            .build();

        KeySchemaElement key2 = KeySchemaElement.builder()
            .attributeName("title")
            .keyType(KeyType.RANGE)
            .build();

        // Add KeySchemaElement objects to the list.
        tableKey.add(key);
        tableKey.add(key2);

        CreateTableRequest request = CreateTableRequest.builder()
            .keySchema(tableKey)
            .billingMode(BillingMode.PAY_PER_REQUEST) //  DynamoDB automatically scales based on traffic.
            .attributeDefinitions(attributeDefinitions)
            .tableName(tableName)
            .build();

        try {
            CreateTableResponse response = ddb.createTable(request);
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                .tableName(tableName)
                .build();

            // Wait until the Amazon DynamoDB table is created.
            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            String newTable = response.tableDescription().tableName();
            System.out.println("The " + newTable + " was successfully created.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
サンプルの JSON ファイルをダウンロードして抽出するヘルパー関数を作成します。  

```
    // Load data into the table.
    public static void loadData(DynamoDbClient ddb, String tableName, String fileName) throws IOException {
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
            .dynamoDbClient(ddb)
            .build();

        DynamoDbTable<Movies> mappedTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class));
        JsonParser parser = new JsonFactory().createParser(new File(fileName));
        com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
        Iterator<JsonNode> iter = rootNode.iterator();
        ObjectNode currentNode;
        int t = 0;
        while (iter.hasNext()) {
            // Only add 200 Movies to the table.
            if (t == 200)
                break;
            currentNode = (ObjectNode) iter.next();

            int year = currentNode.path("year").asInt();
            String title = currentNode.path("title").asText();
            String info = currentNode.path("info").toString();

            Movies movies = new Movies();
            movies.setYear(year);
            movies.setTitle(title);
            movies.setInfo(info);

            // Put the data into the Amazon DynamoDB Movie table.
            mappedTable.putItem(movies);
            t++;
        }
    }
```
テーブルから項目を取得します。  

```
    public static void getItem(DynamoDbClient ddb) {

        HashMap<String, AttributeValue> keyToGet = new HashMap<>();
        keyToGet.put("year", AttributeValue.builder()
            .n("1933")
            .build());

        keyToGet.put("title", AttributeValue.builder()
            .s("King Kong")
            .build());

        GetItemRequest request = GetItemRequest.builder()
            .key(keyToGet)
            .tableName("Movies")
            .build();

        try {
            Map<String, AttributeValue> returnedItem = ddb.getItem(request).item();

            if (returnedItem != null) {
                Set<String> keys = returnedItem.keySet();
                System.out.println("Amazon DynamoDB table attributes: \n");

                for (String key1 : keys) {
                    System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString());
                }
            } else {
                System.out.format("No item found with the key %s!\n", "year");
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
完全な例です。  

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 * <p>
 * This Java example performs these tasks:
 * <p>
 * 1. Creates the Amazon DynamoDB Movie table with partition and sort key.
 * 2. Puts data into the Amazon DynamoDB table from a JSON document using the
 * Enhanced client.
 * 3. Gets data from the Movie table.
 * 4. Adds a new item.
 * 5. Updates an item.
 * 6. Uses a Scan to query items using the Enhanced client.
 * 7. Queries all items where the year is 2013 using the Enhanced Client.
 * 8. Deletes the table.
 */

public class Scenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws IOException {
        String tableName = "Movies";
        String fileName = "../../../resources/sample_files/movies.json";
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
            .region(region)
            .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon DynamoDB example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(
            "1. Creating an Amazon DynamoDB table named Movies with a key named year and a sort key named title.");
        createTable(ddb, tableName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Loading data into the Amazon DynamoDB table.");
        loadData(ddb, tableName, fileName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Getting data from the Movie table.");
        getItem(ddb);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Putting a record into the Amazon DynamoDB table.");
        putRecord(ddb);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Updating a record.");
        updateTableItem(ddb, tableName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Scanning the Amazon DynamoDB table.");
        scanMovies(ddb, tableName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Querying the Movies released in 2013.");
        queryTable(ddb);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Deleting the Amazon DynamoDB table.");
        deleteDynamoDBTable(ddb, tableName);
        System.out.println(DASHES);

        ddb.close();
    }

    // Create a table with a Sort key.
    public static void createTable(DynamoDbClient ddb, String tableName) {
        DynamoDbWaiter dbWaiter = ddb.waiter();
        ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>();

        // Define attributes.
        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("year")
            .attributeType("N")
            .build());

        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("title")
            .attributeType("S")
            .build());

        ArrayList<KeySchemaElement> tableKey = new ArrayList<>();
        KeySchemaElement key = KeySchemaElement.builder()
            .attributeName("year")
            .keyType(KeyType.HASH)
            .build();

        KeySchemaElement key2 = KeySchemaElement.builder()
            .attributeName("title")
            .keyType(KeyType.RANGE)
            .build();

        // Add KeySchemaElement objects to the list.
        tableKey.add(key);
        tableKey.add(key2);

        CreateTableRequest request = CreateTableRequest.builder()
            .keySchema(tableKey)
            .billingMode(BillingMode.PAY_PER_REQUEST) //  DynamoDB automatically scales based on traffic.
            .attributeDefinitions(attributeDefinitions)
            .tableName(tableName)
            .build();

        try {
            CreateTableResponse response = ddb.createTable(request);
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                .tableName(tableName)
                .build();

            // Wait until the Amazon DynamoDB table is created.
            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            String newTable = response.tableDescription().tableName();
            System.out.println("The " + newTable + " was successfully created.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    // Query the table.
    public static void queryTable(DynamoDbClient ddb) {
        try {
            DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(ddb)
                .build();

            DynamoDbTable<Movies> custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class));
            QueryConditional queryConditional = QueryConditional
                .keyEqualTo(Key.builder()
                    .partitionValue(2013)
                    .build());

            // Get items in the table and write out the ID value.
            Iterator<Movies> results = custTable.query(queryConditional).items().iterator();
            String result = "";

            while (results.hasNext()) {
                Movies rec = results.next();
                System.out.println("The title of the movie is " + rec.getTitle());
                System.out.println("The movie information  is " + rec.getInfo());
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    // Scan the table.
    public static void scanMovies(DynamoDbClient ddb, String tableName) {
        System.out.println("******* Scanning all movies.\n");
        try {
            DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(ddb)
                .build();

            DynamoDbTable<Movies> custTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class));
            Iterator<Movies> results = custTable.scan().items().iterator();
            while (results.hasNext()) {
                Movies rec = results.next();
                System.out.println("The movie title is " + rec.getTitle());
                System.out.println("The movie year is " + rec.getYear());
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    // Load data into the table.
    public static void loadData(DynamoDbClient ddb, String tableName, String fileName) throws IOException {
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
            .dynamoDbClient(ddb)
            .build();

        DynamoDbTable<Movies> mappedTable = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class));
        JsonParser parser = new JsonFactory().createParser(new File(fileName));
        com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
        Iterator<JsonNode> iter = rootNode.iterator();
        ObjectNode currentNode;
        int t = 0;
        while (iter.hasNext()) {
            // Only add 200 Movies to the table.
            if (t == 200)
                break;
            currentNode = (ObjectNode) iter.next();

            int year = currentNode.path("year").asInt();
            String title = currentNode.path("title").asText();
            String info = currentNode.path("info").toString();

            Movies movies = new Movies();
            movies.setYear(year);
            movies.setTitle(title);
            movies.setInfo(info);

            // Put the data into the Amazon DynamoDB Movie table.
            mappedTable.putItem(movies);
            t++;
        }
    }

    // Update the record to include show only directors.
    public static void updateTableItem(DynamoDbClient ddb, String tableName) {
        HashMap<String, AttributeValue> itemKey = new HashMap<>();
        itemKey.put("year", AttributeValue.builder().n("1933").build());
        itemKey.put("title", AttributeValue.builder().s("King Kong").build());

        HashMap<String, AttributeValueUpdate> updatedValues = new HashMap<>();
        updatedValues.put("info", AttributeValueUpdate.builder()
            .value(AttributeValue.builder().s("{\"directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\"]")
                .build())
            .action(AttributeAction.PUT)
            .build());

        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(itemKey)
            .attributeUpdates(updatedValues)
            .build();

        try {
            ddb.updateItem(request);
        } catch (ResourceNotFoundException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }

        System.out.println("Item was updated!");
    }

    public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {
        DeleteTableRequest request = DeleteTableRequest.builder()
            .tableName(tableName)
            .build();

        try {
            ddb.deleteTable(request);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println(tableName + " was successfully deleted!");
    }

    public static void putRecord(DynamoDbClient ddb) {
        try {
            DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(ddb)
                .build();

            DynamoDbTable<Movies> table = enhancedClient.table("Movies", TableSchema.fromBean(Movies.class));

            // Populate the Table.
            Movies record = new Movies();
            record.setYear(2020);
            record.setTitle("My Movie2");
            record.setInfo("no info");
            table.putItem(record);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("Added a new movie to the table.");
    }

    public static void getItem(DynamoDbClient ddb) {

        HashMap<String, AttributeValue> keyToGet = new HashMap<>();
        keyToGet.put("year", AttributeValue.builder()
            .n("1933")
            .build());

        keyToGet.put("title", AttributeValue.builder()
            .s("King Kong")
            .build());

        GetItemRequest request = GetItemRequest.builder()
            .key(keyToGet)
            .tableName("Movies")
            .build();

        try {
            Map<String, AttributeValue> returnedItem = ddb.getItem(request).item();

            if (returnedItem != null) {
                Set<String> keys = returnedItem.keySet();
                System.out.println("Amazon DynamoDB table attributes: \n");

                for (String key1 : keys) {
                    System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString());
                }
            } else {
                System.out.format("No item found with the key %s!\n", "year");
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/BatchWriteItem)
  + [CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)
  + [DeleteItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteItem)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Scan)
  + [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)

## アクション
<a name="actions"></a>

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_java_2_topic"></a>

次のコード例は、`BatchGetItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
サービスクライアントを使用してバッチアイテムを取得する方法を示します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 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 BatchReadItems {
    public static void main(String[] args){
        final String usage = """

                Usage:
                    <tableName> 

                Where:
                    tableName - The Amazon DynamoDB table (for example, Music).\s
                """;

        String tableName = "Music";
        Region region = Region.US_EAST_1;
        DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
            .region(region)
            .build();

        getBatchItems(dynamoDbClient, tableName);
    }

    public static void getBatchItems(DynamoDbClient dynamoDbClient, String tableName) {
        // Define the primary key values for the items you want to retrieve.
        Map<String, AttributeValue> key1 = new HashMap<>();
        key1.put("Artist", AttributeValue.builder().s("Artist1").build());

        Map<String, AttributeValue> key2 = new HashMap<>();
        key2.put("Artist", AttributeValue.builder().s("Artist2").build());

        // Construct the batchGetItem request.
        Map<String, KeysAndAttributes> requestItems = new HashMap<>();
        requestItems.put(tableName, KeysAndAttributes.builder()
            .keys(List.of(key1, key2))
            .projectionExpression("Artist, SongTitle")
            .build());

        BatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder()
            .requestItems(requestItems)
            .build();

        // Make the batchGetItem request.
        BatchGetItemResponse batchGetItemResponse = dynamoDbClient.batchGetItem(batchGetItemRequest);

        // Extract and print the retrieved items.
        Map<String, List<Map<String, AttributeValue>>> responses = batchGetItemResponse.responses();
        if (responses.containsKey(tableName)) {
            List<Map<String, AttributeValue>> musicItems = responses.get(tableName);
            for (Map<String, AttributeValue> item : musicItems) {
                System.out.println("Artist: " + item.get("Artist").s() +
                    ", SongTitle: " + item.get("SongTitle").s());
            }
        } else {
            System.out.println("No items retrieved.");
        }
    }
}
```
サービスクライアントおよびページネーターを使用してバッチアイテムを取得する方法を示します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchGetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.KeysAndAttributes;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BatchGetItemsPaginator {

    public static void main(String[] args){
        final String usage = """

                Usage:
                    <tableName> 

                Where:
                    tableName - The Amazon DynamoDB table (for example, Music).\s
                """;

        String tableName = "Music";
        Region region = Region.US_EAST_1;
        DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
            .region(region)
            .build();

        getBatchItemsPaginator(dynamoDbClient, tableName) ;
    }

    public static void getBatchItemsPaginator(DynamoDbClient dynamoDbClient, String tableName) {
        // Define the primary key values for the items you want to retrieve.
        Map<String, AttributeValue> key1 = new HashMap<>();
        key1.put("Artist", AttributeValue.builder().s("Artist1").build());

        Map<String, AttributeValue> key2 = new HashMap<>();
        key2.put("Artist", AttributeValue.builder().s("Artist2").build());

        // Construct the batchGetItem request.
        Map<String, KeysAndAttributes> requestItems = new HashMap<>();
        requestItems.put(tableName, KeysAndAttributes.builder()
            .keys(List.of(key1, key2))
            .projectionExpression("Artist, SongTitle")
            .build());

        BatchGetItemRequest batchGetItemRequest = BatchGetItemRequest.builder()
            .requestItems(requestItems)
            .build();

        // Use batchGetItemPaginator for paginated requests.
        dynamoDbClient.batchGetItemPaginator(batchGetItemRequest).stream()
            .flatMap(response -> response.responses().getOrDefault(tableName, Collections.emptyList()).stream())
            .forEach(item -> {
                System.out.println("Artist: " + item.get("Artist").s() +
                    ", SongTitle: " + item.get("SongTitle").s());
            });
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[BatchGetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/BatchGetItem)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_java_2_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb/#code-examples)での設定と実行の方法を確認してください。
サービスクライアントを使用して、多数の項目をテーブルに挿入します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.BatchWriteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutRequest;
import software.amazon.awssdk.services.dynamodb.model.WriteRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 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 BatchWriteItems {
    public static void main(String[] args){
        final String usage = """

                Usage:
                    <tableName> 

                Where:
                    tableName - The Amazon DynamoDB table (for example, Music).\s
                """;

        String tableName = "Music";
        Region region = Region.US_EAST_1;
        DynamoDbClient dynamoDbClient = DynamoDbClient.builder()
            .region(region)
            .build();

        addBatchItems(dynamoDbClient, tableName);
    }

    public static void addBatchItems(DynamoDbClient dynamoDbClient, String tableName) {
        // Specify the updates you want to perform.
        List<WriteRequest> writeRequests = new ArrayList<>();

        // Set item 1.
        Map<String, AttributeValue> item1Attributes = new HashMap<>();
        item1Attributes.put("Artist", AttributeValue.builder().s("Artist1").build());
        item1Attributes.put("Rating", AttributeValue.builder().s("5").build());
        item1Attributes.put("Comments", AttributeValue.builder().s("Great song!").build());
        item1Attributes.put("SongTitle", AttributeValue.builder().s("SongTitle1").build());
        writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item1Attributes).build()).build());

        // Set item 2.
        Map<String, AttributeValue> item2Attributes = new HashMap<>();
        item2Attributes.put("Artist", AttributeValue.builder().s("Artist2").build());
        item2Attributes.put("Rating", AttributeValue.builder().s("4").build());
        item2Attributes.put("Comments", AttributeValue.builder().s("Nice melody.").build());
        item2Attributes.put("SongTitle", AttributeValue.builder().s("SongTitle2").build());
        writeRequests.add(WriteRequest.builder().putRequest(PutRequest.builder().item(item2Attributes).build()).build());

        try {
            // Create the BatchWriteItemRequest.
            BatchWriteItemRequest batchWriteItemRequest = BatchWriteItemRequest.builder()
                .requestItems(Map.of(tableName, writeRequests))
                .build();

            // Execute the BatchWriteItem operation.
            BatchWriteItemResponse batchWriteItemResponse = dynamoDbClient.batchWriteItem(batchWriteItemRequest);

            // Process the response.
            System.out.println("Batch write successful: " + batchWriteItemResponse);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
拡張クライアントを使用して、多数の項目をテーブルに挿入します。  

```
import com.example.dynamodb.Customer;
import com.example.dynamodb.Music;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.model.BatchWriteItemEnhancedRequest;
import software.amazon.awssdk.enhanced.dynamodb.model.WriteBatch;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/*
 * Before running this code example, create an Amazon DynamoDB table named Customer with these columns:
 *   - id - the id of the record that is the key
 *   - custName - the customer name
 *   - email - the email value
 *   - registrationDate - an instant value when the item was added to the table
 *
 * Also, ensure that you have 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 EnhancedBatchWriteItems {
        public static void main(String[] args) {
                Region region = Region.US_EAST_1;
                DynamoDbClient ddb = DynamoDbClient.builder()
                                .region(region)
                                .build();
                DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                                .dynamoDbClient(ddb)
                                .build();
                putBatchRecords(enhancedClient);
                ddb.close();
        }

        public static void putBatchRecords(DynamoDbEnhancedClient enhancedClient) {
                try {
                        DynamoDbTable<Customer> customerMappedTable = enhancedClient.table("Customer",
                                        TableSchema.fromBean(Customer.class));
                        DynamoDbTable<Music> musicMappedTable = enhancedClient.table("Music",
                                        TableSchema.fromBean(Music.class));
                        LocalDate localDate = LocalDate.parse("2020-04-07");
                        LocalDateTime localDateTime = localDate.atStartOfDay();
                        Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

                        Customer record2 = new Customer();
                        record2.setCustName("Fred Pink");
                        record2.setId("id110");
                        record2.setEmail("fredp@noserver.com");
                        record2.setRegistrationDate(instant);

                        Customer record3 = new Customer();
                        record3.setCustName("Susan Pink");
                        record3.setId("id120");
                        record3.setEmail("spink@noserver.com");
                        record3.setRegistrationDate(instant);

                        Customer record4 = new Customer();
                        record4.setCustName("Jerry orange");
                        record4.setId("id101");
                        record4.setEmail("jorange@noserver.com");
                        record4.setRegistrationDate(instant);

                        BatchWriteItemEnhancedRequest batchWriteItemEnhancedRequest = BatchWriteItemEnhancedRequest
                                        .builder()
                                        .writeBatches(
                                                        WriteBatch.builder(Customer.class) // add items to the Customer
                                                                                           // table
                                                                        .mappedTableResource(customerMappedTable)
                                                                        .addPutItem(builder -> builder.item(record2))
                                                                        .addPutItem(builder -> builder.item(record3))
                                                                        .addPutItem(builder -> builder.item(record4))
                                                                        .build(),
                                                        WriteBatch.builder(Music.class) // delete an item from the Music
                                                                                        // table
                                                                        .mappedTableResource(musicMappedTable)
                                                                        .addDeleteItem(builder -> builder.key(
                                                                                        Key.builder().partitionValue(
                                                                                                        "Famous Band")
                                                                                                        .build()))
                                                                        .build())
                                        .build();

                        // Add three items to the Customer table and delete one item from the Music
                        // table.
                        enhancedClient.batchWriteItem(batchWriteItemEnhancedRequest);
                        System.out.println("done");

                } catch (DynamoDbException e) {
                        System.err.println(e.getMessage());
                        System.exit(1);
                }
        }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。**

### `CreateTable`
<a name="dynamodb_CreateTable_java_2_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.BillingMode;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.OnDemandThroughput;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CreateTable {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <tableName> <key>

            Where:
                tableName - The Amazon DynamoDB table to create (for example, Music3).
                key - The key for the Amazon DynamoDB table (for example, Artist).
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        System.out.println("Creating an Amazon DynamoDB table " + tableName + " with a simple primary key: " + key);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
            .region(region)
            .build();

        String result = createTable(ddb, tableName, key);
        System.out.println("New table is " + result);
        ddb.close();
    }

    public static String createTable(DynamoDbClient ddb, String tableName, String key) {
        DynamoDbWaiter dbWaiter = ddb.waiter();
        CreateTableRequest request = CreateTableRequest.builder()
            .attributeDefinitions(AttributeDefinition.builder()
                .attributeName(key)
                .attributeType(ScalarAttributeType.S)
                .build())
            .keySchema(KeySchemaElement.builder()
                .attributeName(key)
                .keyType(KeyType.HASH)
                .build())
            .billingMode(BillingMode.PAY_PER_REQUEST) //  DynamoDB automatically scales based on traffic.
            .tableName(tableName)
            .build();

        String newTable;
        try {
            CreateTableResponse response = ddb.createTable(request);
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                .tableName(tableName)
                .build();

            // Wait until the Amazon DynamoDB table is created.
            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            newTable = response.tableDescription().tableName();
            return newTable;

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_java_2_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import java.util.HashMap;

/**
 * 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 DeleteItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyval>

                Where:
                    tableName - The Amazon DynamoDB table to delete the item from (for example, Music3).
                    key - The key used in the Amazon DynamoDB table (for example, Artist).\s
                    keyval - The key value that represents the item to delete (for example, Famous Band).
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        System.out.format("Deleting item \"%s\" from %s\n", keyVal, tableName);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        deleteDynamoDBItem(ddb, tableName, key, keyVal);
        ddb.close();
    }

    public static void deleteDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) {
        HashMap<String, AttributeValue> keyToGet = new HashMap<>();
        keyToGet.put(key, AttributeValue.builder()
                .s(keyVal)
                .build());

        DeleteItemRequest deleteReq = DeleteItemRequest.builder()
                .tableName(tableName)
                .key(keyToGet)
                .build();

        try {
            ddb.deleteItem(deleteReq);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DeleteItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteItem)」を参照してください。**

### `DeleteTable`
<a name="dynamodb_DeleteTable_java_2_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;

/**
 * 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 DeleteTable {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName>

                Where:
                    tableName - The Amazon DynamoDB table to delete (for example, Music3).

                **Warning** This program will delete the table that you specify!
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        System.out.format("Deleting the Amazon DynamoDB table %s...\n", tableName);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        deleteDynamoDBTable(ddb, tableName);
        ddb.close();
    }

    public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {
        DeleteTableRequest request = DeleteTableRequest.builder()
                .tableName(tableName)
                .build();

        try {
            ddb.deleteTable(request);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println(tableName + " was successfully deleted!");
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_java_2_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughputDescription;
import software.amazon.awssdk.services.dynamodb.model.TableDescription;
import java.util.List;

/**
 * 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 DescribeTable {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName>

                Where:
                    tableName - The Amazon DynamoDB table to get information about (for example, Music3).
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        System.out.format("Getting description for %s\n\n", tableName);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        describeDymamoDBTable(ddb, tableName);
        ddb.close();
    }

    public static void describeDymamoDBTable(DynamoDbClient ddb, String tableName) {
        DescribeTableRequest request = DescribeTableRequest.builder()
                .tableName(tableName)
                .build();

        try {
            TableDescription tableInfo = ddb.describeTable(request).table();
            if (tableInfo != null) {
                System.out.format("Table name  : %s\n", tableInfo.tableName());
                System.out.format("Table ARN   : %s\n", tableInfo.tableArn());
                System.out.format("Status      : %s\n", tableInfo.tableStatus());
                System.out.format("Item count  : %d\n", tableInfo.itemCount());
                System.out.format("Size (bytes): %d\n", tableInfo.tableSizeBytes());

                ProvisionedThroughputDescription throughputInfo = tableInfo.provisionedThroughput();
                System.out.println("Throughput");
                System.out.format("  Read Capacity : %d\n", throughputInfo.readCapacityUnits());
                System.out.format("  Write Capacity: %d\n", throughputInfo.writeCapacityUnits());

                List<AttributeDefinition> attributes = tableInfo.attributeDefinitions();
                System.out.println("Attributes");
                for (AttributeDefinition a : attributes) {
                    System.out.format("  %s (%s)\n", a.attributeName(), a.attributeType());
                }
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("\nDone!");
    }
}
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[DescribeTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DescribeTable)」を参照してください。

### `DescribeTimeToLive`
<a name="dynamodb_DescribeTimeToLive_java_2_topic"></a>

次のコード例は、`DescribeTimeToLive` を使用する方法を示しています。

**SDK for Java 2.x**  
 AWS SDK for Java 2.xを使用して既存の DynamoDB テーブルの TTL 設定を記述します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DescribeTimeToLiveRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTimeToLiveResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.logging.Level;
import java.util.logging.Logger;

    public DescribeTimeToLiveResponse describeTTL(final String tableName, final Region region) {
        final DescribeTimeToLiveRequest request =
            DescribeTimeToLiveRequest.builder().tableName(tableName).build();

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            return ddb.describeTimeToLive(request);
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeTimeToLive](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DescribeTimeToLive)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_java_2_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
DynamoDbClient を使用して、テーブルから項目を取得します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 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
 *
 * To get an item from an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client, see the EnhancedGetItem example.
 */
public class GetItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal>

                Where:
                    tableName - The Amazon DynamoDB table from which an item is retrieved (for example, Music3).\s
                    key - The key used in the Amazon DynamoDB table (for example, Artist).\s
                    keyval - The key value that represents the item to get (for example, Famous Band).
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        System.out.format("Retrieving item \"%s\" from \"%s\"\n", keyVal, tableName);
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        getDynamoDBItem(ddb, tableName, key, keyVal);
        ddb.close();
    }

    public static void getDynamoDBItem(DynamoDbClient ddb, String tableName, String key, String keyVal) {
        HashMap<String, AttributeValue> keyToGet = new HashMap<>();
        keyToGet.put(key, AttributeValue.builder()
                .s(keyVal)
                .build());

        GetItemRequest request = GetItemRequest.builder()
                .key(keyToGet)
                .tableName(tableName)
                .build();

        try {
            // If there is no matching item, GetItem does not return any data.
            Map<String, AttributeValue> returnedItem = ddb.getItem(request).item();
            if (returnedItem.isEmpty())
                System.out.format("No item found with the key %s!\n", key);
            else {
                Set<String> keys = returnedItem.keySet();
                System.out.println("Amazon DynamoDB table attributes: \n");
                for (String key1 : keys) {
                    System.out.format("%s: %s\n", key1, returnedItem.get(key1).toString());
                }
            }

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem)」を参照してください。**

### `ListTables`
<a name="dynamodb_ListTables_java_2_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ListTablesRequest;
import software.amazon.awssdk.services.dynamodb.model.ListTablesResponse;
import java.util.List;

/**
 * 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 ListTables {
    public static void main(String[] args) {
        System.out.println("Listing your Amazon DynamoDB tables:\n");
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();
        listAllTables(ddb);
        ddb.close();
    }

    public static void listAllTables(DynamoDbClient ddb) {
        boolean moreTables = true;
        String lastName = null;

        while (moreTables) {
            try {
                ListTablesResponse response = null;
                if (lastName == null) {
                    ListTablesRequest request = ListTablesRequest.builder().build();
                    response = ddb.listTables(request);
                } else {
                    ListTablesRequest request = ListTablesRequest.builder()
                            .exclusiveStartTableName(lastName).build();
                    response = ddb.listTables(request);
                }

                List<String> tableNames = response.tableNames();
                if (tableNames.size() > 0) {
                    for (String curName : tableNames) {
                        System.out.format("* %s\n", curName);
                    }
                } else {
                    System.out.println("No tables found!");
                    System.exit(0);
                }

                lastName = response.lastEvaluatedTableName();
                if (lastName == null) {
                    moreTables = false;
                }

            } catch (DynamoDbException e) {
                System.err.println(e.getMessage());
                System.exit(1);
            }
        }
        System.out.println("\nDone!");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListTables](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_java_2_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
[DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html) を使用してテーブルに項目を配置します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import java.util.HashMap;

/**
 * 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
 *
 * To place items into an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedPutItem example.
 */
public class PutItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal> <albumtitle> <albumtitleval> <awards> <awardsval> <Songtitle> <songtitleval>

                Where:
                    tableName - The Amazon DynamoDB table in which an item is placed (for example, Music3).
                    key - The key used in the Amazon DynamoDB table (for example, Artist).
                    keyval - The key value that represents the item to get (for example, Famous Band).
                    albumTitle - The Album title (for example, AlbumTitle).
                    AlbumTitleValue - The name of the album (for example, Songs About Life ).
                    Awards - The awards column (for example, Awards).
                    AwardVal - The value of the awards (for example, 10).
                    SongTitle - The song title (for example, SongTitle).
                    SongTitleVal - The value of the song title (for example, Happy Day).
                **Warning** This program will  place an item that you specify into a table!
                """;

        if (args.length != 9) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        String albumTitle = args[3];
        String albumTitleValue = args[4];
        String awards = args[5];
        String awardVal = args[6];
        String songTitle = args[7];
        String songTitleVal = args[8];

        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        putItemInTable(ddb, tableName, key, keyVal, albumTitle, albumTitleValue, awards, awardVal, songTitle,
                songTitleVal);
        System.out.println("Done!");
        ddb.close();
    }

    public static void putItemInTable(DynamoDbClient ddb,
            String tableName,
            String key,
            String keyVal,
            String albumTitle,
            String albumTitleValue,
            String awards,
            String awardVal,
            String songTitle,
            String songTitleVal) {

        HashMap<String, AttributeValue> itemValues = new HashMap<>();
        itemValues.put(key, AttributeValue.builder().s(keyVal).build());
        itemValues.put(songTitle, AttributeValue.builder().s(songTitleVal).build());
        itemValues.put(albumTitle, AttributeValue.builder().s(albumTitleValue).build());
        itemValues.put(awards, AttributeValue.builder().s(awardVal).build());

        PutItemRequest request = PutItemRequest.builder()
                .tableName(tableName)
                .item(itemValues)
                .build();

        try {
            PutItemResponse response = ddb.putItem(request);
            System.out.println(tableName + " was successfully updated. The request id is "
                    + response.responseMetadata().requestId());

        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            System.err.println("Be sure that it exists and that you've typed its name correctly!");
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)」を参照してください。**

### `Query`
<a name="dynamodb_Query_java_2_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
[DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html) を使用してテーブルに対してクエリを実行します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import java.util.HashMap;

/**
 * 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
 *
 * To query items from an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client. See the EnhancedQueryRecords example.
 */
public class Query {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <partitionKeyName> <partitionKeyVal>

                Where:
                    tableName - The Amazon DynamoDB table to put the item in (for example, Music3).
                    partitionKeyName - The partition key name of the Amazon DynamoDB table (for example, Artist).
                    partitionKeyVal - The value of the partition key that should match (for example, Famous Band).
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String partitionKeyName = args[1];
        String partitionKeyVal = args[2];

        // For more information about an alias, see:
        // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html
        String partitionAlias = "#a";

        System.out.format("Querying %s", tableName);
        System.out.println("");
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        int count = queryTable(ddb, tableName, partitionKeyName, partitionKeyVal, partitionAlias);
        System.out.println("There were " + count + "  record(s) returned");
        ddb.close();
    }

    public static int queryTable(DynamoDbClient ddb, String tableName, String partitionKeyName, String partitionKeyVal,
            String partitionAlias) {
        // Set up an alias for the partition key name in case it's a reserved word.
        HashMap<String, String> attrNameAlias = new HashMap<String, String>();
        attrNameAlias.put(partitionAlias, partitionKeyName);

        // Set up mapping of the partition name with the value.
        HashMap<String, AttributeValue> attrValues = new HashMap<>();
        attrValues.put(":" + partitionKeyName, AttributeValue.builder()
                .s(partitionKeyVal)
                .build());

        QueryRequest queryReq = QueryRequest.builder()
                .tableName(tableName)
                .keyConditionExpression(partitionAlias + " = :" + partitionKeyName)
                .expressionAttributeNames(attrNameAlias)
                .expressionAttributeValues(attrValues)
                .build();

        try {
            QueryResponse response = ddb.query(queryReq);
            return response.count();

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return -1;
    }
}
```
`DynamoDbClient` とセカンダリインデックスを使用してテーブルに対してクエリを実行します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 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
 *
 * Create the Movies table by running the Scenario example and loading the Movie
 * data from the JSON file. Next create a secondary
 * index for the Movies table that uses only the year column. Name the index
 * **year-index**. For more information, see:
 *
 * https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html
 */
public class QueryItemsUsingIndex {
    public static void main(String[] args) {
        String tableName = "Movies";
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        queryIndex(ddb, tableName);
        ddb.close();
    }

    public static void queryIndex(DynamoDbClient ddb, String tableName) {
        try {
            Map<String, String> expressionAttributesNames = new HashMap<>();
            expressionAttributesNames.put("#year", "year");
            Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
            expressionAttributeValues.put(":yearValue", AttributeValue.builder().n("2013").build());

            QueryRequest request = QueryRequest.builder()
                    .tableName(tableName)
                    .indexName("year-index")
                    .keyConditionExpression("#year = :yearValue")
                    .expressionAttributeNames(expressionAttributesNames)
                    .expressionAttributeValues(expressionAttributeValues)
                    .build();

            System.out.println("=== Movie Titles ===");
            QueryResponse response = ddb.query(request);
            response.items()
                    .forEach(movie -> System.out.println(movie.get("title").s()));

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。**

### `Scan`
<a name="dynamodb_Scan_java_2_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
[DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html) を使用して Amazon DynamoDB テーブルをスキャンします。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import java.util.Map;
import java.util.Set;

/**
 * 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
 *
 * To scan items from an Amazon DynamoDB table using the AWS SDK for Java V2,
 * its better practice to use the
 * Enhanced Client, See the EnhancedScanRecords example.
 */

public class DynamoDBScanItems {
    public static void main(String[] args) {

        final String usage = """

                Usage:
                    <tableName>

                Where:
                    tableName - The Amazon DynamoDB table to get information from (for example, Music3).
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        scanItems(ddb, tableName);
        ddb.close();
    }

    public static void scanItems(DynamoDbClient ddb, String tableName) {
        try {
            ScanRequest scanRequest = ScanRequest.builder()
                    .tableName(tableName)
                    .build();

            ScanResponse response = ddb.scan(scanRequest);
            for (Map<String, AttributeValue> item : response.items()) {
                Set<String> keys = item.keySet();
                for (String key : keys) {
                    System.out.println("The key name is " + key + "\n");
                    System.out.println("The value is " + item.get(key).s());
                }
            }

        } catch (DynamoDbException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[Scan](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Scan)」を参照してください。**

### `UpdateItem`
<a name="dynamodb_UpdateItem_java_2_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
[DynamoDbClient](https://docs.aws.amazon.com/sdk-for-java/latest/reference/software/amazon/awssdk/services/dynamodb/DynamoDbClient.html) を使用してテーブルで項目を更新します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.AttributeAction;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.AttributeValueUpdate;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import java.util.HashMap;

/**
 * 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
 *
 * To update an Amazon DynamoDB table using the AWS SDK for Java V2, its better
 * practice to use the
 * Enhanced Client, See the EnhancedModifyItem example.
 */
public class UpdateItem {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <tableName> <key> <keyVal> <name> <updateVal>

                Where:
                    tableName - The Amazon DynamoDB table (for example, Music3).
                    key - The name of the key in the table (for example, Artist).
                    keyVal - The value of the key (for example, Famous Band).
                    name - The name of the column where the value is updated (for example, Awards).
                    updateVal - The value used to update an item (for example, 14).
                 Example:
                    UpdateItem Music3 Artist Famous Band Awards 14
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String tableName = args[0];
        String key = args[1];
        String keyVal = args[2];
        String name = args[3];
        String updateVal = args[4];

        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();
        updateTableItem(ddb, tableName, key, keyVal, name, updateVal);
        ddb.close();
    }

    public static void updateTableItem(DynamoDbClient ddb,
            String tableName,
            String key,
            String keyVal,
            String name,
            String updateVal) {

        HashMap<String, AttributeValue> itemKey = new HashMap<>();
        itemKey.put(key, AttributeValue.builder()
                .s(keyVal)
                .build());

        HashMap<String, AttributeValueUpdate> updatedValues = new HashMap<>();
        updatedValues.put(name, AttributeValueUpdate.builder()
                .value(AttributeValue.builder().s(updateVal).build())
                .action(AttributeAction.PUT)
                .build());

        UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(itemKey)
                .attributeUpdates(updatedValues)
                .build();

        try {
            ddb.updateItem(request);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("The Amazon DynamoDB table was updated!");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### `UpdateTimeToLive`
<a name="dynamodb_UpdateTimeToLive_java_2_topic"></a>

次のコード例は、`UpdateTimeToLive` を使用する方法を示しています。

**SDK for Java 2.x**  
 AWS SDK for Java 2.xを使用して既存の DynamoDB テーブルの TTL を有効にします。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.TimeToLiveSpecification;
import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveResponse;

import java.util.logging.Level;
import java.util.logging.Logger;

    public UpdateTimeToLiveResponse enableTTL(final String tableName, final String attributeName, final Region region) {
        final TimeToLiveSpecification ttlSpec = TimeToLiveSpecification.builder()
            .attributeName(attributeName)
            .enabled(true)
            .build();

        final UpdateTimeToLiveRequest request = UpdateTimeToLiveRequest.builder()
            .tableName(tableName)
            .timeToLiveSpecification(ttlSpec)
            .build();

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            return ddb.updateTimeToLive(request);
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
```
 AWS SDK for Java 2.xを使用して既存の DynamoDB テーブルの TTL を無効にします。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.TimeToLiveSpecification;
import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateTimeToLiveResponse;

import java.util.logging.Level;
import java.util.logging.Logger;

    public UpdateTimeToLiveResponse disableTTL(
        final String tableName, final String attributeName, final Region region) {
        final TimeToLiveSpecification ttlSpec = TimeToLiveSpecification.builder()
            .attributeName(attributeName)
            .enabled(false)
            .build();

        final UpdateTimeToLiveRequest request = UpdateTimeToLiveRequest.builder()
            .tableName(tableName)
            .timeToLiveSpecification(ttlSpec)
            .build();

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            return ddb.updateTimeToLive(request);
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateTimeToLive](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateTimeToLive)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DynamoDB テーブルにデータを送信するアプリケーションを構築する
<a name="cross_SubmitDataApp_java_2_topic"></a>

次のコード例は、Amazon DynamoDB テーブルにデータを送信し、ユーザーがテーブルを更新したときに通知するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 Amazon DynamoDB Java API を使用してデータを送信し、Amazon Simple Notification Service Java API を使用してテキストメッセージを送信する動的ウェブアプリケーションを作成する方法について説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_first_project) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SNS

### 複数の値を 1 つの属性と比較する
<a name="dynamodb_Scenario_CompareMultipleValues_java_2_topic"></a>

次のコード例は、DynamoDB で複数の値を 1 つの属性と比較する方法を示しています。
+ IN 演算子を使用して、複数の値を 1 つの属性と比較します。
+ IN 演算子を複数の OR 条件と比較します。
+ IN の使用によるパフォーマンスと式の複雑さのメリットを理解します。

**SDK for Java 2.x**  
を使用して、複数の値を DynamoDB の 1 つの属性と比較します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

    /**
     * Queries a table using the IN operator to compare multiple values with a single attribute.
     *
     * <p>This method demonstrates how to use the IN operator in a filter expression
     * to match an attribute against multiple values.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param partitionKeyName The name of the partition key attribute
     * @param partitionKeyValue The value of the partition key to query
     * @param attributeName The name of the attribute to compare
     * @param valuesList List of values to compare against
     * @return The query response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static QueryResponse compareMultipleValues(
        DynamoDbClient dynamoDbClient,
        String tableName,
        String partitionKeyName,
        AttributeValue partitionKeyValue,
        String attributeName,
        List<AttributeValue> valuesList) {

        // Create expression attribute names
        Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put("#pkName", partitionKeyName);
        expressionAttributeNames.put("#attrName", attributeName);

        // Create expression attribute values
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(":pkValue", partitionKeyValue);

        // Add values for IN operator
        for (int i = 0; i < valuesList.size(); i++) {
            expressionAttributeValues.put(":val" + i, valuesList.get(i));
        }

        // Build the IN clause
        StringBuilder inClause = new StringBuilder();
        for (int i = 0; i < valuesList.size(); i++) {
            if (i > 0) {
                inClause.append(", ");
            }
            inClause.append(":val").append(i);
        }

        // Define the query parameters
        QueryRequest request = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression("#pkName = :pkValue")
            .filterExpression("#attrName IN (" + inClause.toString() + ")")
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        // Perform the query operation
        return dynamoDbClient.query(request);
    }

    /**
     * Queries a table using multiple OR conditions to compare multiple values with a single attribute.
     *
     * <p>This method demonstrates the alternative approach to using the IN operator,
     * by using multiple OR conditions.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param partitionKeyName The name of the partition key attribute
     * @param partitionKeyValue The value of the partition key to query
     * @param attributeName The name of the attribute to compare
     * @param valuesList List of values to compare against
     * @return The query response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static QueryResponse compareWithOrConditions(
        DynamoDbClient dynamoDbClient,
        String tableName,
        String partitionKeyName,
        AttributeValue partitionKeyValue,
        String attributeName,
        List<AttributeValue> valuesList) {

        // Create expression attribute names
        Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put("#pkName", partitionKeyName);
        expressionAttributeNames.put("#attrName", attributeName);

        // Create expression attribute values
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(":pkValue", partitionKeyValue);

        // Add values for OR conditions
        for (int i = 0; i < valuesList.size(); i++) {
            expressionAttributeValues.put(":val" + i, valuesList.get(i));
        }

        // Build the OR conditions
        StringBuilder orConditions = new StringBuilder();
        for (int i = 0; i < valuesList.size(); i++) {
            if (i > 0) {
                orConditions.append(" OR ");
            }
            orConditions.append("#attrName = :val").append(i);
        }

        // Define the query parameters
        QueryRequest request = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression("#pkName = :pkValue")
            .filterExpression(orConditions.toString())
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        // Perform the query operation
        return dynamoDbClient.query(request);
    }

    /**
     * Compares the performance of using the IN operator versus multiple OR conditions.
     *
     * <p>This method demonstrates the performance difference between using the IN operator
     * and using multiple OR conditions.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param partitionKeyName The name of the partition key attribute
     * @param partitionKeyValue The value of the partition key to query
     * @param attributeName The name of the attribute to compare
     * @param valuesList List of values to compare against
     * @return Map containing the performance comparison results
     */
    public static Map<String, Object> comparePerformance(
        DynamoDbClient dynamoDbClient,
        String tableName,
        String partitionKeyName,
        AttributeValue partitionKeyValue,
        String attributeName,
        List<AttributeValue> valuesList) {

        Map<String, Object> results = new HashMap<>();

        try {
            // Measure performance of IN operator
            long inStartTime = System.nanoTime();
            QueryResponse inResponse = compareMultipleValues(
                dynamoDbClient, tableName, partitionKeyName, partitionKeyValue, attributeName, valuesList);
            long inEndTime = System.nanoTime();
            long inDuration = inEndTime - inStartTime;

            // Measure performance of OR conditions
            long orStartTime = System.nanoTime();
            QueryResponse orResponse = compareWithOrConditions(
                dynamoDbClient, tableName, partitionKeyName, partitionKeyValue, attributeName, valuesList);
            long orEndTime = System.nanoTime();
            long orDuration = orEndTime - orStartTime;

            // Record results
            results.put("inOperatorDuration", inDuration);
            results.put("orConditionsDuration", orDuration);
            results.put("inOperatorItems", inResponse.count());
            results.put("orConditionsItems", orResponse.count());
            results.put("inOperatorExpression", "IN operator with " + valuesList.size() + " values");
            results.put("orConditionsExpression", valuesList.size() + " OR conditions");
            results.put("success", true);

        } catch (DynamoDbException e) {
            results.put("success", false);
            results.put("error", e.getMessage());
        }

        return results;
    }

    /**
     * Scans a table using the IN operator with a large number of values.
     *
     * <p>This method demonstrates how to use the IN operator with a large number of values,
     * which can help stay within the 300 operator limit.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param attributeName The name of the attribute to compare
     * @param valuesList List of values to compare against
     * @return The scan response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static ScanResponse scanWithLargeInClause(
        DynamoDbClient dynamoDbClient, String tableName, String attributeName, List<AttributeValue> valuesList) {

        // Create expression attribute names
        Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put("#attrName", attributeName);

        // Create expression attribute values
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();

        // Add values for IN operator
        for (int i = 0; i < valuesList.size(); i++) {
            expressionAttributeValues.put(":val" + i, valuesList.get(i));
        }

        // Build the IN clause
        StringBuilder inClause = new StringBuilder();
        for (int i = 0; i < valuesList.size(); i++) {
            if (i > 0) {
                inClause.append(", ");
            }
            inClause.append(":val").append(i);
        }

        // Define the scan parameters
        ScanRequest request = ScanRequest.builder()
            .tableName(tableName)
            .filterExpression("#attrName IN (" + inClause.toString() + ")")
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        // Perform the scan operation
        return dynamoDbClient.scan(request);
    }

    /**
     * Generates a list of sample values for testing.
     *
     * <p>Helper method to generate a list of sample values for testing.
     *
     * @param valueType The type of values to generate (string, number, or boolean)
     * @param count The number of values to generate
     * @return List of generated attribute values
     */
    public static List<AttributeValue> generateSampleValues(String valueType, int count) {
        List<AttributeValue> values = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            AttributeValue value;

            switch (valueType.toLowerCase(Locale.ROOT)) {
                case "string":
                    value = AttributeValue.builder().s("Value" + i).build();
                    break;
                case "number":
                    value = AttributeValue.builder().n(String.valueOf(i)).build();
                    break;
                case "boolean":
                    value = AttributeValue.builder().bool(i % 2 == 0).build();
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported value type: " + valueType);
            }

            values.add(value);
        }

        return values;
    }
```
複数の値と を比較する使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        System.out.println("Demonstrating how to compare multiple values with a single attribute in DynamoDB");

        try {
            // Example 1: Using the IN operator
            System.out.println("\nExample 1: Using the IN operator");
            List<AttributeValue> categories = List.of(
                AttributeValue.builder().s("Electronics").build(),
                AttributeValue.builder().s("Computers").build(),
                AttributeValue.builder().s("Accessories").build());

            QueryResponse inResponse = compareMultipleValues(
                dynamoDbClient,
                tableName,
                "Department",
                AttributeValue.builder().s("Retail").build(),
                "Category",
                categories);

            System.out.println("Found " + inResponse.count() + " items using IN operator");
            System.out.println("Items: " + inResponse.items());

            // Example 2: Using multiple OR conditions
            System.out.println("\nExample 2: Using multiple OR conditions");
            QueryResponse orResponse = compareWithOrConditions(
                dynamoDbClient,
                tableName,
                "Department",
                AttributeValue.builder().s("Retail").build(),
                "Category",
                categories);

            System.out.println("Found " + orResponse.count() + " items using OR conditions");
            System.out.println("Items: " + orResponse.items());

            // Example 3: Performance comparison
            System.out.println("\nExample 3: Performance comparison");
            Map<String, Object> perfComparison = comparePerformance(
                dynamoDbClient,
                tableName,
                "Department",
                AttributeValue.builder().s("Retail").build(),
                "Category",
                categories);

            if ((boolean) perfComparison.get("success")) {
                System.out.println("IN operator duration: " + perfComparison.get("inOperatorDuration") + " ns");
                System.out.println("OR conditions duration: " + perfComparison.get("orConditionsDuration") + " ns");
                System.out.println("IN operator found " + perfComparison.get("inOperatorItems") + " items");
                System.out.println("OR conditions found " + perfComparison.get("orConditionsItems") + " items");
                System.out.println("Expression complexity comparison:");
                System.out.println("  IN operator: " + perfComparison.get("inOperatorExpression"));
                System.out.println("  OR conditions: " + perfComparison.get("orConditionsExpression"));
            } else {
                System.out.println("Performance comparison failed: " + perfComparison.get("error"));
            }

            // Example 4: Using IN with a large number of values
            System.out.println("\nExample 4: Using IN with a large number of values");
            List<AttributeValue> productIds = generateSampleValues("string", 20);

            ScanResponse largeInResponse = scanWithLargeInClause(dynamoDbClient, tableName, "ProductId", productIds);

            System.out.println(
                "Found " + largeInResponse.count() + " items using IN with " + productIds.size() + " values");

            // Explain the benefits of using IN
            System.out.println("\nKey points about using the IN operator in DynamoDB:");
            System.out.println("1. The IN operator allows comparing a single attribute against multiple values");
            System.out.println("2. IN is more concise than using multiple OR conditions");
            System.out.println("3. IN counts as only 1 operator regardless of the number of values");
            System.out.println("4. Multiple OR conditions count as 1 operator per condition plus 1 per OR");
            System.out.println("5. Using IN helps stay within the 300 operator limit for complex expressions");
            System.out.println("6. IN can be used in filter expressions and condition expressions");
            System.out.println("7. The IN operator supports up to 100 comparison values");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Scan)

### 項目の TTL を条件付きで更新する
<a name="dynamodb_UpdateItemConditionalTTL_java_2_topic"></a>

以下のコード例は、項目の TTL を条件付きで更新する方法を示しています。

**SDK for Java 2.x**  
条件を指定して、テーブル内の既存の DynamoDB 項目の TTL を更新します。  

```
package com.amazon.samplelib.ttl;

import com.amazon.samplelib.CodeSampleUtils;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.Map;
import java.util.Optional;

/**
 * Updates an item in a DynamoDB table with TTL attributes using a conditional expression.
 * This class demonstrates how to conditionally update TTL expiration timestamps.
 */
public class UpdateTTLConditional {

    private static final String USAGE =
        """
            Usage:
                <tableName> <primaryKey> <sortKey> <region>
            Where:
                tableName - The Amazon DynamoDB table being queried.
                primaryKey - The name of the primary key. Also known as the hash or partition key.
                sortKey - The name of the sort key. Also known as the range attribute.
                region (optional) - The AWS region that the Amazon DynamoDB table is located in. (Default: us-east-1)
            """;
    private static final int DAYS_TO_EXPIRE = 90;
    private static final int SECONDS_PER_DAY = 24 * 60 * 60;
    private static final String PRIMARY_KEY_ATTR = "primaryKey";
    private static final String SORT_KEY_ATTR = "sortKey";
    private static final String UPDATED_AT_ATTR = "updatedAt";
    private static final String EXPIRE_AT_ATTR = "expireAt";
    private static final String UPDATE_EXPRESSION = "SET " + UPDATED_AT_ATTR + "=:c, " + EXPIRE_AT_ATTR + "=:e";
    private static final String CONDITION_EXPRESSION = "attribute_exists(" + PRIMARY_KEY_ATTR + ")";
    private static final String SUCCESS_MESSAGE = "%s UpdateItem operation with TTL successful.";
    private static final String CONDITION_FAILED_MESSAGE = "Condition check failed. Item does not exist.";
    private static final String TABLE_NOT_FOUND_ERROR = "Error: The Amazon DynamoDB table \"%s\" can't be found.";

    private final DynamoDbClient dynamoDbClient;

    /**
     * Constructs an UpdateTTLConditional with a default DynamoDB client.
     */
    public UpdateTTLConditional() {
        this.dynamoDbClient = null;
    }

    /**
     * Constructs an UpdateTTLConditional with the specified DynamoDB client.
     *
     * @param dynamoDbClient The DynamoDB client to use
     */
    public UpdateTTLConditional(final DynamoDbClient dynamoDbClient) {
        this.dynamoDbClient = dynamoDbClient;
    }

    /**
     * Main method to demonstrate conditionally updating an item with TTL.
     *
     * @param args Command line arguments
     */
    public static void main(final String[] args) {
        try {
            int result = new UpdateTTLConditional().processArgs(args);
            System.exit(result);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Process command line arguments and conditionally update an item with TTL.
     *
     * @param args Command line arguments
     * @return 0 if successful, non-zero otherwise
     * @throws ResourceNotFoundException If the table doesn't exist
     * @throws DynamoDbException If an error occurs during the operation
     * @throws IllegalArgumentException If arguments are invalid
     */
    public int processArgs(final String[] args) {
        // Argument validation (remove or replace this line when reusing this code)
        CodeSampleUtils.validateArgs(args, new int[] {3, 4}, USAGE);

        final String tableName = args[0];
        final String primaryKey = args[1];
        final String sortKey = args[2];
        final Region region = Optional.ofNullable(args.length > 3 ? args[3] : null)
            .map(Region::of)
            .orElse(Region.US_EAST_1);

        // Get current time in epoch second format
        final long currentTime = System.currentTimeMillis() / 1000;

        // Calculate expiration time 90 days from now in epoch second format
        final long expireDate = currentTime + (DAYS_TO_EXPIRE * SECONDS_PER_DAY);

        // Create the key map for the item to update
        final Map<String, AttributeValue> keyMap = Map.of(
            PRIMARY_KEY_ATTR, AttributeValue.builder().s(primaryKey).build(),
            SORT_KEY_ATTR, AttributeValue.builder().s(sortKey).build());

        // Create the expression attribute values
        final Map<String, AttributeValue> expressionAttributeValues = Map.of(
            ":c", AttributeValue.builder().n(String.valueOf(currentTime)).build(),
            ":e", AttributeValue.builder().n(String.valueOf(expireDate)).build());

        final UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(keyMap)
            .updateExpression(UPDATE_EXPRESSION)
            .conditionExpression(CONDITION_EXPRESSION)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            final UpdateItemResponse response = ddb.updateItem(request);
            System.out.println(String.format(SUCCESS_MESSAGE, tableName));
            return 0;
        } catch (ConditionalCheckFailedException e) {
            System.err.println(CONDITION_FAILED_MESSAGE);
            throw e;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### 式演算子をカウントする
<a name="dynamodb_Scenario_ExpressionOperatorCounting_java_2_topic"></a>

次のコード例は、DynamoDB で式演算子をカウントする方法を示しています。
+ DynamoDB の演算子の制限数が 300 であることを理解します。
+ 複雑な式での演算子をカウントする。
+ 式を最適化して制限内に収まるようにします。

**SDK for Java 2.x**  
 AWS SDK for Java 2.xを使用して式演算子のカウントをデモンストレーションします。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

    /**
     * Creates a complex filter expression with a specified number of conditions.
     *
     * <p>This method demonstrates how to generate a complex expression with
     * a specific number of operators to test the 300 operator limit.
     *
     * @param conditionsCount Number of conditions to include
     * @param useAnd Whether to use AND (true) or OR (false) between conditions
     * @return Map containing the filter expression, attribute values, and operator count
     */
    public static Map<String, Object> createComplexFilterExpression(int conditionsCount, boolean useAnd) {
        // Initialize the expression parts and attribute values
        StringBuilder filterExpression = new StringBuilder();
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();

        // Generate the specified number of conditions
        for (int i = 0; i < conditionsCount; i++) {
            // Add the operator between conditions (except for the first one)
            if (i > 0) {
                filterExpression.append(useAnd ? " AND " : " OR ");
            }

            // Alternate between different comparison operators for variety
            String valueKey = ":val" + i;

            switch (i % 5) {
                case 0:
                    filterExpression.append("attribute").append(i).append(" = ").append(valueKey);
                    expressionAttributeValues.put(
                        valueKey, AttributeValue.builder().s("value" + i).build());
                    break;
                case 1:
                    filterExpression.append("attribute").append(i).append(" > ").append(valueKey);
                    expressionAttributeValues.put(
                        valueKey, AttributeValue.builder().n(String.valueOf(i)).build());
                    break;
                case 2:
                    filterExpression.append("attribute").append(i).append(" < ").append(valueKey);
                    expressionAttributeValues.put(
                        valueKey,
                        AttributeValue.builder().n(String.valueOf(i * 10)).build());
                    break;
                case 3:
                    filterExpression
                        .append("contains(attribute")
                        .append(i)
                        .append(", ")
                        .append(valueKey)
                        .append(")");
                    expressionAttributeValues.put(
                        valueKey, AttributeValue.builder().s("substring" + i).build());
                    break;
                case 4:
                    filterExpression
                        .append("attribute_exists(attribute")
                        .append(i)
                        .append(")");
                    break;
                default:
                    // This case will never be reached, but added to satisfy checkstyle
                    break;
            }
        }

        // Calculate the operator count
        // Each condition has 1 operator (=, >, <, contains, attribute_exists)
        // Each AND or OR between conditions is 1 operator
        int operatorCount = conditionsCount + (conditionsCount > 0 ? conditionsCount - 1 : 0);

        // Create the result map
        Map<String, Object> result = new HashMap<>();
        result.put("filterExpression", filterExpression.toString());
        result.put("expressionAttributeValues", expressionAttributeValues);
        result.put("operatorCount", operatorCount);

        return result;
    }

    /**
     * Creates a complex update expression with a specified number of operations.
     *
     * <p>This method demonstrates how to generate a complex update expression with
     * a specific number of operators to test the 300 operator limit.
     *
     * @param operationsCount Number of operations to include
     * @return Map containing the update expression, attribute values, and operator count
     */
    public static Map<String, Object> createComplexUpdateExpression(int operationsCount) {
        // Initialize the expression parts and attribute values
        StringBuilder updateExpression = new StringBuilder("SET ");
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();

        // Generate the specified number of SET operations
        for (int i = 0; i < operationsCount; i++) {
            // Add comma between operations (except for the first one)
            if (i > 0) {
                updateExpression.append(", ");
            }

            // Alternate between different types of SET operations
            String valueKey = ":val" + i;

            switch (i % 3) {
                case 0:
                    // Simple assignment (1 operator: =)
                    updateExpression.append("attribute").append(i).append(" = ").append(valueKey);
                    expressionAttributeValues.put(
                        valueKey, AttributeValue.builder().s("value" + i).build());
                    break;
                case 1:
                    // Addition (2 operators: = and +)
                    updateExpression
                        .append("attribute")
                        .append(i)
                        .append(" = attribute")
                        .append(i)
                        .append(" + ")
                        .append(valueKey);
                    expressionAttributeValues.put(
                        valueKey, AttributeValue.builder().n(String.valueOf(i)).build());
                    break;
                case 2:
                    // Conditional assignment with if_not_exists (2 operators: = and if_not_exists)
                    updateExpression
                        .append("attribute")
                        .append(i)
                        .append(" = if_not_exists(attribute")
                        .append(i)
                        .append(", ")
                        .append(valueKey)
                        .append(")");
                    expressionAttributeValues.put(
                        valueKey,
                        AttributeValue.builder().n(String.valueOf(i * 10)).build());
                    break;
                default:
                    // This case will never be reached, but added to satisfy checkstyle
                    break;
            }
        }

        // Calculate the operator count
        // Each operation has 1-2 operators as noted above
        int operatorCount = 0;
        for (int i = 0; i < operationsCount; i++) {
            operatorCount += (i % 3 == 0) ? 1 : 2;
        }

        // Create the result map
        Map<String, Object> result = new HashMap<>();
        result.put("updateExpression", updateExpression.toString());
        result.put("expressionAttributeValues", expressionAttributeValues);
        result.put("operatorCount", operatorCount);

        return result;
    }

    /**
     * Test the operator limit by attempting an operation with a complex expression.
     *
     * <p>This method demonstrates what happens when an expression approaches or
     * exceeds the 300 operator limit.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param operatorCount Target number of operators to include
     * @return Map containing the result of the operation attempt
     */
    public static Map<String, Object> testOperatorLimit(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key, int operatorCount) {

        // Create a complex update expression with the specified operator count
        Map<String, Object> expressionData =
            createComplexUpdateExpression((int) Math.ceil(operatorCount / 1.5)); // Adjust to get close to target count

        String updateExpression = (String) expressionData.get("updateExpression");
        @SuppressWarnings("unchecked")
        Map<String, AttributeValue> expressionAttributeValues =
            (Map<String, AttributeValue>) expressionData.get("expressionAttributeValues");
        int actualCount = (int) expressionData.get("operatorCount");

        System.out.println("Generated update expression with approximately " + actualCount + " operators");

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression(updateExpression)
            .expressionAttributeValues(expressionAttributeValues)
            .returnValues("UPDATED_NEW")
            .build();

        try {
            // Attempt the update operation
            UpdateItemResponse response = dynamoDbClient.updateItem(request);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "Operation succeeded with " + actualCount + " operators");
            result.put("data", response);
            return result;

        } catch (DynamoDbException e) {
            // Check if the error is due to exceeding the operator limit
            if (e.getMessage().contains("too many operators")) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "Operation failed: " + e.getMessage());
                result.put("operatorCount", actualCount);
                return result;
            }

            // Return other errors
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "Operation failed: " + e.getMessage());
            result.put("error", e);
            return result;
        }
    }

    /**
     * Break down a complex expression into multiple simpler operations.
     *
     * <p>This method demonstrates how to handle expressions that would exceed
     * the 300 operator limit by breaking them into multiple operations.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param totalOperations Total number of operations to perform
     * @return Map containing the results of the operations
     */
    public static Map<String, Object> breakDownComplexExpression(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key, int totalOperations) {

        // Calculate how many operations we can safely include in each batch
        // Using 150 as a conservative limit (well below 300)
        final int operationsPerBatch = 100;
        final int batchCount = (int) Math.ceil((double) totalOperations / operationsPerBatch);

        System.out.println("Breaking down " + totalOperations + " operations into " + batchCount + " batches");

        Map<String, Object> results = new HashMap<>();
        results.put("totalBatches", batchCount);

        Map<Integer, Map<String, Object>> batchResults = new HashMap<>();

        // Process each batch
        for (int batch = 0; batch < batchCount; batch++) {
            // Calculate the operations for this batch
            int batchStart = batch * operationsPerBatch;
            int batchEnd = Math.min(batchStart + operationsPerBatch, totalOperations);
            int batchSize = batchEnd - batchStart;

            System.out.println(
                "Processing batch " + (batch + 1) + "/" + batchCount + " with " + batchSize + " operations");

            // Create an update expression for this batch
            Map<String, Object> expressionData = createComplexUpdateExpression(batchSize);

            String updateExpression = (String) expressionData.get("updateExpression");
            @SuppressWarnings("unchecked")
            Map<String, AttributeValue> expressionAttributeValues =
                (Map<String, AttributeValue>) expressionData.get("expressionAttributeValues");
            int operatorCount = (int) expressionData.get("operatorCount");

            // Define the update parameters
            UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression(updateExpression)
                .expressionAttributeValues(expressionAttributeValues)
                .returnValues("UPDATED_NEW")
                .build();

            try {
                // Perform the update operation for this batch
                UpdateItemResponse response = dynamoDbClient.updateItem(request);

                Map<String, Object> batchResult = new HashMap<>();
                batchResult.put("batch", batch + 1);
                batchResult.put("success", true);
                batchResult.put("operatorCount", operatorCount);
                batchResult.put("attributes", response.attributes());

                batchResults.put(batch, batchResult);

            } catch (DynamoDbException e) {
                Map<String, Object> batchResult = new HashMap<>();
                batchResult.put("batch", batch + 1);
                batchResult.put("success", false);
                batchResult.put("operatorCount", operatorCount);
                batchResult.put("error", e.getMessage());

                batchResults.put(batch, batchResult);

                // Continue with next batch instead of breaking
                continue;
            }
        }

        results.put("results", batchResults);
        return results;
    }

    /**
     * Count operators in a DynamoDB expression based on the rules in the documentation.
     *
     * <p>This method demonstrates how operators are counted according to the
     * DynamoDB documentation.
     *
     * @param expression The DynamoDB expression to analyze
     * @return Map containing the breakdown of operator counts
     */
    public static Map<String, Integer> countOperatorsInExpression(String expression) {
        // Initialize counters for different operator types
        Map<String, Integer> counts = new HashMap<>();
        counts.put("comparisonOperators", 0);
        counts.put("logicalOperators", 0);
        counts.put("functions", 0);
        counts.put("arithmeticOperators", 0);
        counts.put("specialOperators", 0);
        counts.put("total", 0);

        // Count comparison operators (=, <>, <, <=, >, >=)
        // This is a simplified approach and may not catch all cases
        int comparisonCount = 0;
        Pattern comparisonPattern = Pattern.compile("(=|<>|<=|>=|<|>)");
        Matcher comparisonMatcher = comparisonPattern.matcher(expression);
        while (comparisonMatcher.find()) {
            comparisonCount++;
        }
        counts.put("comparisonOperators", comparisonCount);

        // Count logical operators (AND, OR, NOT)
        int andCount = countOccurrences(expression, "\\bAND\\b");
        int orCount = countOccurrences(expression, "\\bOR\\b");
        int notCount = countOccurrences(expression, "\\bNOT\\b");
        counts.put("logicalOperators", andCount + orCount + notCount);

        // Count functions (attribute_exists, attribute_not_exists, attribute_type, begins_with, contains, size)
        int functionCount = countOccurrences(
            expression,
            "\\b(attribute_exists|attribute_not_exists|attribute_type|begins_with|contains|size|if_not_exists)\\(");
        counts.put("functions", functionCount);

        // Count arithmetic operators (+ and -)
        // This is a simplified approach and may not catch all cases
        int arithmeticCount = 0;
        Pattern arithmeticPattern = Pattern.compile("[a-zA-Z0-9_)\\]]\\s*[\\+\\-]\\s*[a-zA-Z0-9_:(]");
        Matcher arithmeticMatcher = arithmeticPattern.matcher(expression);
        while (arithmeticMatcher.find()) {
            arithmeticCount++;
        }
        counts.put("arithmeticOperators", arithmeticCount);

        // Count special operators (BETWEEN, IN)
        int betweenCount = countOccurrences(expression, "\\bBETWEEN\\b");
        int inCount = countOccurrences(expression, "\\bIN\\b");
        counts.put("specialOperators", betweenCount + inCount);

        // Add extra operators for BETWEEN (each BETWEEN includes an AND)
        int currentLogicalOps = counts.getOrDefault("logicalOperators", 0);
        counts.put("logicalOperators", currentLogicalOps + betweenCount);

        // Calculate total
        int total = counts.getOrDefault("comparisonOperators", 0)
            + counts.getOrDefault("logicalOperators", 0)
            + counts.getOrDefault("functions", 0)
            + counts.getOrDefault("arithmeticOperators", 0)
            + counts.getOrDefault("specialOperators", 0);
        counts.put("total", total);

        return counts;
    }

    /**
     * Helper method to count occurrences of a pattern in a string.
     *
     * @param text The text to search in
     * @param regex The regular expression pattern to search for
     * @return The number of occurrences
     */
    private static int countOccurrences(String text, String regex) {
        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(text);
        int count = 0;
        while (matcher.find()) {
            count++;
        }
        return count;
    }
```
でカウントする式演算子の使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating DynamoDB expression operator counting and the 300 operator limit");

        try {
            // Example 1: Analyze a simple expression
            System.out.println("\nExample 1: Analyzing a simple expression");
            String simpleExpression = "Price = :price AND Rating > :rating AND Category IN (:cat1, :cat2, :cat3)";
            Map<String, Integer> simpleCount = countOperatorsInExpression(simpleExpression);

            System.out.println("Expression: " + simpleExpression);
            System.out.println("Operator count breakdown:");
            System.out.println("- Comparison operators: " + simpleCount.get("comparisonOperators"));
            System.out.println("- Logical operators: " + simpleCount.get("logicalOperators"));
            System.out.println("- Functions: " + simpleCount.get("functions"));
            System.out.println("- Arithmetic operators: " + simpleCount.get("arithmeticOperators"));
            System.out.println("- Special operators: " + simpleCount.get("specialOperators"));
            System.out.println("- Total operators: " + simpleCount.get("total"));

            // Example 2: Analyze a complex expression
            System.out.println("\nExample 2: Analyzing a complex expression");
            String complexExpression = "(attribute_exists(Category) AND Size BETWEEN :min AND :max) OR "
                + "(Price > :price AND contains(Description, :keyword) AND "
                + "(Rating >= :minRating OR Reviews > :minReviews))";
            Map<String, Integer> complexCount = countOperatorsInExpression(complexExpression);

            System.out.println("Expression: " + complexExpression);
            System.out.println("Operator count breakdown:");
            System.out.println("- Comparison operators: " + complexCount.get("comparisonOperators"));
            System.out.println("- Logical operators: " + complexCount.get("logicalOperators"));
            System.out.println("- Functions: " + complexCount.get("functions"));
            System.out.println("- Arithmetic operators: " + complexCount.get("arithmeticOperators"));
            System.out.println("- Special operators: " + complexCount.get("specialOperators"));
            System.out.println("- Total operators: " + complexCount.get("total"));

            // Example 3: Test approaching the operator limit
            System.out.println("\nExample 3: Testing an expression approaching the operator limit");
            Map<String, Object> approachingLimit = testOperatorLimit(dynamoDbClient, tableName, key, 290);
            System.out.println(approachingLimit.get("message"));

            // Example 4: Test exceeding the operator limit
            System.out.println("\nExample 4: Testing an expression exceeding the operator limit");
            Map<String, Object> exceedingLimit = testOperatorLimit(dynamoDbClient, tableName, key, 310);
            System.out.println(exceedingLimit.get("message"));

            // Example 5: Breaking down a complex expression
            System.out.println("\nExample 5: Breaking down a complex expression into multiple operations");
            Map<String, Object> breakdownResult = breakDownComplexExpression(dynamoDbClient, tableName, key, 500);
            @SuppressWarnings("unchecked")
            Map<Integer, Map<String, Object>> results =
                (Map<Integer, Map<String, Object>>) breakdownResult.get("results");
            System.out.println(
                "Processed " + results.size() + " of " + breakdownResult.get("totalBatches") + " batches");

            // Explain the operator counting rules
            System.out.println("\nKey points about DynamoDB expression operator counting:");
            System.out.println("1. The maximum number of operators in any expression is 300");
            System.out.println("2. Each comparison operator (=, <>, <, <=, >, >=) counts as 1 operator");
            System.out.println("3. Each logical operator (AND, OR, NOT) counts as 1 operator");
            System.out.println("4. Each function call (attribute_exists, contains, etc.) counts as 1 operator");
            System.out.println("5. Each arithmetic operator (+ or -) counts as 1 operator");
            System.out.println("6. BETWEEN counts as 2 operators (BETWEEN itself and the AND within it)");
            System.out.println("7. IN counts as 1 operator regardless of the number of values");
            System.out.println("8. Parentheses for grouping and attribute paths don't count as operators");
            System.out.println("9. When you exceed the limit, the error always reports '301 operators'");
            System.out.println("10. For complex operations, break them into multiple smaller operations");

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_java_2_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Java 2.x**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### グローバルセカンダリインデックスを含むテーブルを作成する
<a name="dynamodb_CreateTableWithGlobalSecondaryIndex_java_2_topic"></a>

次のコード例は、グローバルセカンダリインデックスを含むテーブルの作成方法を示しています。

**SDK for Java 2.x**  
を使用して、グローバルセカンダリインデックスを含む DynamoDB テーブルを作成します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.Projection;
import software.amazon.awssdk.services.dynamodb.model.ProjectionType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    public void createTable() {
        try {
            // Attribute definitions
            final List<AttributeDefinition> attributeDefinitions = new ArrayList<>();
            attributeDefinitions.add(AttributeDefinition.builder()
                .attributeName(ISSUE_ID_ATTR)
                .attributeType(ScalarAttributeType.S)
                .build());
            attributeDefinitions.add(AttributeDefinition.builder()
                .attributeName(TITLE_ATTR)
                .attributeType(ScalarAttributeType.S)
                .build());
            attributeDefinitions.add(AttributeDefinition.builder()
                .attributeName(CREATE_DATE_ATTR)
                .attributeType(ScalarAttributeType.S)
                .build());
            attributeDefinitions.add(AttributeDefinition.builder()
                .attributeName(DUE_DATE_ATTR)
                .attributeType(ScalarAttributeType.S)
                .build());

            // Key schema for table
            final List<KeySchemaElement> tableKeySchema = new ArrayList<>();
            tableKeySchema.add(KeySchemaElement.builder()
                .attributeName(ISSUE_ID_ATTR)
                .keyType(KeyType.HASH)
                .build()); // Partition key
            tableKeySchema.add(KeySchemaElement.builder()
                .attributeName(TITLE_ATTR)
                .keyType(KeyType.RANGE)
                .build()); // Sort key

            // Initial provisioned throughput settings for the indexes
            final ProvisionedThroughput ptIndex = ProvisionedThroughput.builder()
                .readCapacityUnits(1L)
                .writeCapacityUnits(1L)
                .build();

            // CreateDateIndex
            final List<KeySchemaElement> createDateKeySchema = new ArrayList<>();
            createDateKeySchema.add(KeySchemaElement.builder()
                .attributeName(CREATE_DATE_ATTR)
                .keyType(KeyType.HASH)
                .build());
            createDateKeySchema.add(KeySchemaElement.builder()
                .attributeName(ISSUE_ID_ATTR)
                .keyType(KeyType.RANGE)
                .build());

            final Projection createDateProjection = Projection.builder()
                .projectionType(ProjectionType.INCLUDE)
                .nonKeyAttributes(DESCRIPTION_ATTR, STATUS_ATTR)
                .build();

            final GlobalSecondaryIndex createDateIndex = GlobalSecondaryIndex.builder()
                .indexName(CREATE_DATE_INDEX)
                .keySchema(createDateKeySchema)
                .projection(createDateProjection)
                .provisionedThroughput(ptIndex)
                .build();

            // TitleIndex
            final List<KeySchemaElement> titleKeySchema = new ArrayList<>();
            titleKeySchema.add(KeySchemaElement.builder()
                .attributeName(TITLE_ATTR)
                .keyType(KeyType.HASH)
                .build());
            titleKeySchema.add(KeySchemaElement.builder()
                .attributeName(ISSUE_ID_ATTR)
                .keyType(KeyType.RANGE)
                .build());

            final Projection titleProjection =
                Projection.builder().projectionType(ProjectionType.KEYS_ONLY).build();

            final GlobalSecondaryIndex titleIndex = GlobalSecondaryIndex.builder()
                .indexName(TITLE_INDEX)
                .keySchema(titleKeySchema)
                .projection(titleProjection)
                .provisionedThroughput(ptIndex)
                .build();

            // DueDateIndex
            final List<KeySchemaElement> dueDateKeySchema = new ArrayList<>();
            dueDateKeySchema.add(KeySchemaElement.builder()
                .attributeName(DUE_DATE_ATTR)
                .keyType(KeyType.HASH)
                .build());

            final Projection dueDateProjection =
                Projection.builder().projectionType(ProjectionType.ALL).build();

            final GlobalSecondaryIndex dueDateIndex = GlobalSecondaryIndex.builder()
                .indexName(DUE_DATE_INDEX)
                .keySchema(dueDateKeySchema)
                .projection(dueDateProjection)
                .provisionedThroughput(ptIndex)
                .build();

            final CreateTableRequest createTableRequest = CreateTableRequest.builder()
                .tableName(TABLE_NAME)
                .keySchema(tableKeySchema)
                .attributeDefinitions(attributeDefinitions)
                .globalSecondaryIndexes(createDateIndex, titleIndex, dueDateIndex)
                .provisionedThroughput(ProvisionedThroughput.builder()
                    .readCapacityUnits(1L)
                    .writeCapacityUnits(1L)
                    .build())
                .build();

            System.out.println("Creating table " + TABLE_NAME + "...");
            dynamoDbClient.createTable(createTableRequest);

            // Wait for table to become active
            System.out.println("Waiting for " + TABLE_NAME + " to become ACTIVE...");
            final DynamoDbWaiter waiter = dynamoDbClient.waiter();
            final DescribeTableRequest describeTableRequest =
                DescribeTableRequest.builder().tableName(TABLE_NAME).build();

            final WaiterResponse<DescribeTableResponse> waiterResponse =
                waiter.waitUntilTableExists(describeTableRequest);
            waiterResponse.matched().response().ifPresent(response -> System.out.println("Table is now ready for use"));

        } catch (DynamoDbException e) {
            System.err.println("Error creating table: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)」を参照してください。

### ウォームスループットを有効にしたテーブルを作成する
<a name="dynamodb_CreateTableWarmThroughput_java_2_topic"></a>

次のコード例は、ウォームスループットを有効にしたテーブルを作成する方法を示しています。

**SDK for Java 2.x**  
 AWS SDK for Java 2.xを使用してウォームスループット設定を含む DynamoDB テーブルを作成します。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndex;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.Projection;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.model.WarmThroughput;

    public static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond, final Long writeUnitsPerSecond) {
        return WarmThroughput.builder()
            .readUnitsPerSecond(readUnitsPerSecond)
            .writeUnitsPerSecond(writeUnitsPerSecond)
            .build();
    }

    /**
     * Builds a ProvisionedThroughput object with the specified read and write capacity units.
     *
     * @param readCapacityUnits The read capacity units
     * @param writeCapacityUnits The write capacity units
     * @return A configured ProvisionedThroughput object
     */
    public static ProvisionedThroughput buildProvisionedThroughput(
        final Long readCapacityUnits, final Long writeCapacityUnits) {
        return ProvisionedThroughput.builder()
            .readCapacityUnits(readCapacityUnits)
            .writeCapacityUnits(writeCapacityUnits)
            .build();
    }

    /**
     * Builds an AttributeDefinition with the specified name and type.
     *
     * @param attributeName The attribute name
     * @param scalarAttributeType The attribute type
     * @return A configured AttributeDefinition
     */
    private static AttributeDefinition buildAttributeDefinition(
        final String attributeName, final ScalarAttributeType scalarAttributeType) {
        return AttributeDefinition.builder()
            .attributeName(attributeName)
            .attributeType(scalarAttributeType)
            .build();
    }

    /**
     * Builds a KeySchemaElement with the specified name and key type.
     *
     * @param attributeName The attribute name
     * @param keyType The key type (HASH or RANGE)
     * @return A configured KeySchemaElement
     */
    private static KeySchemaElement buildKeySchemaElement(final String attributeName, final KeyType keyType) {
        return KeySchemaElement.builder()
            .attributeName(attributeName)
            .keyType(keyType)
            .build();
    }

    /**
     * Creates a DynamoDB table with the specified configuration including warm throughput settings.
     *
     * @param ddb The DynamoDB client
     * @param tableName The name of the table to create
     * @param partitionKey The partition key attribute name
     * @param sortKey The sort key attribute name
     * @param miscellaneousKeyAttribute Additional key attribute name for GSI
     * @param nonKeyAttribute Non-key attribute to include in GSI projection
     * @param tableReadCapacityUnits Read capacity units for the table
     * @param tableWriteCapacityUnits Write capacity units for the table
     * @param tableWarmReadUnitsPerSecond Warm read units per second for the table
     * @param tableWarmWriteUnitsPerSecond Warm write units per second for the table
     * @param globalSecondaryIndexName The name of the GSI to create
     * @param globalSecondaryIndexReadCapacityUnits Read capacity units for the GSI
     * @param globalSecondaryIndexWriteCapacityUnits Write capacity units for the GSI
     * @param globalSecondaryIndexWarmReadUnitsPerSecond Warm read units per second for the GSI
     * @param globalSecondaryIndexWarmWriteUnitsPerSecond Warm write units per second for the GSI
     */
    public static void createDynamoDBTable(
        final DynamoDbClient ddb,
        final String tableName,
        final String partitionKey,
        final String sortKey,
        final String miscellaneousKeyAttribute,
        final String nonKeyAttribute,
        final Long tableReadCapacityUnits,
        final Long tableWriteCapacityUnits,
        final Long tableWarmReadUnitsPerSecond,
        final Long tableWarmWriteUnitsPerSecond,
        final String globalSecondaryIndexName,
        final Long globalSecondaryIndexReadCapacityUnits,
        final Long globalSecondaryIndexWriteCapacityUnits,
        final Long globalSecondaryIndexWarmReadUnitsPerSecond,
        final Long globalSecondaryIndexWarmWriteUnitsPerSecond) {

        // Define the table attributes
        final AttributeDefinition partitionKeyAttribute = buildAttributeDefinition(partitionKey, ScalarAttributeType.S);
        final AttributeDefinition sortKeyAttribute = buildAttributeDefinition(sortKey, ScalarAttributeType.S);
        final AttributeDefinition miscellaneousKeyAttributeDefinition =
            buildAttributeDefinition(miscellaneousKeyAttribute, ScalarAttributeType.N);
        final AttributeDefinition[] attributeDefinitions = {
            partitionKeyAttribute, sortKeyAttribute, miscellaneousKeyAttributeDefinition
        };

        // Define the table key schema
        final KeySchemaElement partitionKeyElement = buildKeySchemaElement(partitionKey, KeyType.HASH);
        final KeySchemaElement sortKeyElement = buildKeySchemaElement(sortKey, KeyType.RANGE);
        final KeySchemaElement[] keySchema = {partitionKeyElement, sortKeyElement};

        // Define the provisioned throughput for the table
        final ProvisionedThroughput provisionedThroughput =
            buildProvisionedThroughput(tableReadCapacityUnits, tableWriteCapacityUnits);

        // Define the Global Secondary Index (GSI)
        final KeySchemaElement globalSecondaryIndexPartitionKeyElement = buildKeySchemaElement(sortKey, KeyType.HASH);
        final KeySchemaElement globalSecondaryIndexSortKeyElement =
            buildKeySchemaElement(miscellaneousKeyAttribute, KeyType.RANGE);
        final KeySchemaElement[] gsiKeySchema = {
            globalSecondaryIndexPartitionKeyElement, globalSecondaryIndexSortKeyElement
        };

        final Projection gsiProjection = Projection.builder()
            .projectionType(PROJECTION_TYPE_INCLUDE)
            .nonKeyAttributes(nonKeyAttribute)
            .build();

        final ProvisionedThroughput gsiProvisionedThroughput =
            buildProvisionedThroughput(globalSecondaryIndexReadCapacityUnits, globalSecondaryIndexWriteCapacityUnits);

        // Define the warm throughput for the Global Secondary Index (GSI)
        final WarmThroughput gsiWarmThroughput = buildWarmThroughput(
            globalSecondaryIndexWarmReadUnitsPerSecond, globalSecondaryIndexWarmWriteUnitsPerSecond);

        final GlobalSecondaryIndex globalSecondaryIndex = GlobalSecondaryIndex.builder()
            .indexName(globalSecondaryIndexName)
            .keySchema(gsiKeySchema)
            .projection(gsiProjection)
            .provisionedThroughput(gsiProvisionedThroughput)
            .warmThroughput(gsiWarmThroughput)
            .build();

        // Define the warm throughput for the table
        final WarmThroughput tableWarmThroughput =
            buildWarmThroughput(tableWarmReadUnitsPerSecond, tableWarmWriteUnitsPerSecond);

        final CreateTableRequest request = CreateTableRequest.builder()
            .tableName(tableName)
            .attributeDefinitions(attributeDefinitions)
            .keySchema(keySchema)
            .provisionedThroughput(provisionedThroughput)
            .globalSecondaryIndexes(globalSecondaryIndex)
            .warmThroughput(tableWarmThroughput)
            .build();

        final CreateTableResponse response = ddb.createTable(request);
        System.out.println(response);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)」を参照してください。

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_java_2_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon DynamoDB API を使用して、DynamoDB 作業データを追跡する動的ウェブアプリケーションを作成する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_dynamodb_web_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### TTL を含む項目を作成する
<a name="dynamodb_PutItemTTL_java_2_topic"></a>

次のコード例は、TTL を含む項目の作成方法を示しています。

**SDK for Java 2.x**  

```
package com.amazon.samplelib.ttl;

import com.amazon.samplelib.CodeSampleUtils;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.PutItemRequest;
import software.amazon.awssdk.services.dynamodb.model.PutItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Creates an item in a DynamoDB table with TTL attributes.
 * This class demonstrates how to add TTL expiration timestamps to DynamoDB items.
 */
public class CreateTTL {

    private static final String USAGE =
        """
            Usage:
                <tableName> <primaryKey> <sortKey> <region>
            Where:
                tableName - The Amazon DynamoDB table being queried.
                primaryKey - The name of the primary key. Also known as the hash or partition key.
                sortKey - The name of the sort key. Also known as the range attribute.
                region (optional) - The AWS region that the Amazon DynamoDB table is located in. (Default: us-east-1)
            """;
    private static final int DAYS_TO_EXPIRE = 90;
    private static final int SECONDS_PER_DAY = 24 * 60 * 60;
    private static final String PRIMARY_KEY_ATTR = "primaryKey";
    private static final String SORT_KEY_ATTR = "sortKey";
    private static final String CREATION_DATE_ATTR = "creationDate";
    private static final String EXPIRE_AT_ATTR = "expireAt";
    private static final String SUCCESS_MESSAGE = "%s PutItem operation with TTL successful.";
    private static final String TABLE_NOT_FOUND_ERROR = "Error: The Amazon DynamoDB table \"%s\" can't be found.";

    private final DynamoDbClient dynamoDbClient;

    /**
     * Constructs a CreateTTL instance with the specified DynamoDB client.
     *
     * @param dynamoDbClient The DynamoDB client to use
     */
    public CreateTTL(final DynamoDbClient dynamoDbClient) {
        this.dynamoDbClient = dynamoDbClient;
    }

    /**
     * Constructs a CreateTTL with a default DynamoDB client.
     */
    public CreateTTL() {
        this.dynamoDbClient = null;
    }

    /**
     * Main method to demonstrate creating an item with TTL.
     *
     * @param args Command line arguments
     */
    public static void main(final String[] args) {
        try {
            int result = new CreateTTL().processArgs(args);
            System.exit(result);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Process command line arguments and create an item with TTL.
     *
     * @param args Command line arguments
     * @return 0 if successful, non-zero otherwise
     * @throws ResourceNotFoundException If the table doesn't exist
     * @throws DynamoDbException If an error occurs during the operation
     * @throws IllegalArgumentException If arguments are invalid
     */
    public int processArgs(final String[] args) {
        // Argument validation (remove or replace this line when reusing this code)
        CodeSampleUtils.validateArgs(args, new int[] {3, 4}, USAGE);

        final String tableName = args[0];
        final String primaryKey = args[1];
        final String sortKey = args[2];
        final Region region = Optional.ofNullable(args.length > 3 ? args[3] : null)
            .map(Region::of)
            .orElse(Region.US_EAST_1);

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            final CreateTTL createTTL = new CreateTTL(ddb);
            createTTL.createItemWithTTL(tableName, primaryKey, sortKey);
            return 0;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * Creates an item in the specified table with TTL attributes.
     *
     * @param tableName The name of the table
     * @param primaryKeyValue The value for the primary key
     * @param sortKeyValue The value for the sort key
     * @return The response from the PutItem operation
     * @throws ResourceNotFoundException If the table doesn't exist
     * @throws DynamoDbException If an error occurs during the operation
     */
    public PutItemResponse createItemWithTTL(
        final String tableName, final String primaryKeyValue, final String sortKeyValue) {
        // Get current time in epoch second format
        final long createDate = System.currentTimeMillis() / 1000;

        // Calculate expiration time 90 days from now in epoch second format
        final long expireDate = createDate + (DAYS_TO_EXPIRE * SECONDS_PER_DAY);

        final Map<String, AttributeValue> itemMap = new HashMap<>();
        itemMap.put(
            PRIMARY_KEY_ATTR, AttributeValue.builder().s(primaryKeyValue).build());
        itemMap.put(SORT_KEY_ATTR, AttributeValue.builder().s(sortKeyValue).build());
        itemMap.put(
            CREATION_DATE_ATTR,
            AttributeValue.builder().n(String.valueOf(createDate)).build());
        itemMap.put(
            EXPIRE_AT_ATTR,
            AttributeValue.builder().n(String.valueOf(expireDate)).build());

        final PutItemRequest request =
            PutItemRequest.builder().tableName(tableName).item(itemMap).build();

        try {
            final PutItemResponse response = dynamoDbClient.putItem(request);
            System.out.println(String.format(SUCCESS_MESSAGE, tableName));
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)」を参照してください。**

### MRSC グローバルテーブルの作成と管理
<a name="dynamodb_Scenario_MRSCGlobalTables_java_2_topic"></a>

次のコード例は、マルチリージョンの強力な整合性 (MRSC) を備えた DynamoDB グローバルテーブルを作成および管理する方法を示しています。
+ マルチリージョンの強力な整合性を備えたテーブルを作成します。
+ MRSC 設定とレプリカのステータスを確認します。
+ 即時読み取りでリージョン間の強力な整合性をテストします。
+ MRSC 保証を使用して条件付き書き込みを実行します。
+ MRSC グローバルテーブルリソースをクリーンアップします。

**SDK for Java 2.x**  
を使用して、MRSC 変換の準備ができたリージョンテーブルを作成します AWS SDK for Java 2.x。  

```
    public static CreateTableResponse createRegionalTable(final DynamoDbClient dynamoDbClient, final String tableName) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }

        try {
            LOGGER.info("Creating regional table: " + tableName + " (must be empty for MRSC)");

            CreateTableRequest createTableRequest = CreateTableRequest.builder()
                .tableName(tableName)
                .attributeDefinitions(
                    AttributeDefinition.builder()
                        .attributeName("Artist")
                        .attributeType(ScalarAttributeType.S)
                        .build(),
                    AttributeDefinition.builder()
                        .attributeName("SongTitle")
                        .attributeType(ScalarAttributeType.S)
                        .build())
                .keySchema(
                    KeySchemaElement.builder()
                        .attributeName("Artist")
                        .keyType(KeyType.HASH)
                        .build(),
                    KeySchemaElement.builder()
                        .attributeName("SongTitle")
                        .keyType(KeyType.RANGE)
                        .build())
                .billingMode(BillingMode.PAY_PER_REQUEST)
                .build();

            CreateTableResponse response = dynamoDbClient.createTable(createTableRequest);
            LOGGER.info("Regional table creation initiated. Status: "
                + response.tableDescription().tableStatus());

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to create regional table: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Failed to create regional table: " + tableName)
                .cause(e)
                .build();
        }
    }
```
レプリカを使用してリージョンテーブルを MRSC に変換し、 を使用して監視します AWS SDK for Java 2.x。  

```
    public static UpdateTableResponse convertToMRSCWithWitness(
        final DynamoDbClient dynamoDbClient,
        final String tableName,
        final Region replicaRegion,
        final Region witnessRegion) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (replicaRegion == null) {
            throw new IllegalArgumentException("Replica region cannot be null");
        }
        if (witnessRegion == null) {
            throw new IllegalArgumentException("Witness region cannot be null");
        }

        try {
            LOGGER.info("Converting table to MRSC with replica in " + replicaRegion.id() + " and witness in "
                + witnessRegion.id());

            // Create replica update using ReplicationGroupUpdate
            ReplicationGroupUpdate replicaUpdate = ReplicationGroupUpdate.builder()
                .create(CreateReplicationGroupMemberAction.builder()
                    .regionName(replicaRegion.id())
                    .build())
                .build();

            // Create witness update
            GlobalTableWitnessGroupUpdate witnessUpdate = GlobalTableWitnessGroupUpdate.builder()
                .create(CreateGlobalTableWitnessGroupMemberAction.builder()
                    .regionName(witnessRegion.id())
                    .build())
                .build();

            UpdateTableRequest updateTableRequest = UpdateTableRequest.builder()
                .tableName(tableName)
                .replicaUpdates(List.of(replicaUpdate))
                .globalTableWitnessUpdates(List.of(witnessUpdate))
                .multiRegionConsistency(MultiRegionConsistency.STRONG)
                .build();

            UpdateTableResponse response = dynamoDbClient.updateTable(updateTableRequest);
            LOGGER.info("MRSC conversion initiated. Status: "
                + response.tableDescription().tableStatus());
            LOGGER.info("UpdateTableResponse full object: " + response);
            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to convert table to MRSC: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Failed to convert table to MRSC: " + tableName)
                .cause(e)
                .build();
        }
    }
```
を使用して MRSC グローバルテーブル設定を記述します AWS SDK for Java 2.x。  

```
    public static DescribeTableResponse describeMRSCTable(final DynamoDbClient dynamoDbClient, final String tableName) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }

        try {
            LOGGER.info("Describing MRSC global table: " + tableName);

            DescribeTableRequest request =
                DescribeTableRequest.builder().tableName(tableName).build();

            DescribeTableResponse response = dynamoDbClient.describeTable(request);

            LOGGER.info("Table status: " + response.table().tableStatus());
            LOGGER.info("Multi-region consistency: " + response.table().multiRegionConsistency());

            if (response.table().replicas() != null
                && !response.table().replicas().isEmpty()) {
                LOGGER.info("Number of replicas: " + response.table().replicas().size());
                response.table()
                    .replicas()
                    .forEach(replica -> LOGGER.info(
                        "Replica region: " + replica.regionName() + ", Status: " + replica.replicaStatus()));
            }

            if (response.table().globalTableWitnesses() != null
                && !response.table().globalTableWitnesses().isEmpty()) {
                LOGGER.info("Number of witnesses: "
                    + response.table().globalTableWitnesses().size());
                response.table()
                    .globalTableWitnesses()
                    .forEach(witness -> LOGGER.info(
                        "Witness region: " + witness.regionName() + ", Status: " + witness.witnessStatus()));
            }

            return response;

        } catch (ResourceNotFoundException e) {
            LOGGER.severe("Table not found: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Table not found: " + tableName)
                .cause(e)
                .build();
        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to describe table: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Failed to describe table: " + tableName)
                .cause(e)
                .build();
        }
    }
```
 AWS SDK for Java 2.xを使用して、MRSC の強力な整合性を検証するためのテスト項目を追加します。  

```
    public static PutItemResponse putTestItem(
        final DynamoDbClient dynamoDbClient,
        final String tableName,
        final String artist,
        final String songTitle,
        final String album,
        final String year) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (artist == null || artist.trim().isEmpty()) {
            throw new IllegalArgumentException("Artist cannot be null or empty");
        }
        if (songTitle == null || songTitle.trim().isEmpty()) {
            throw new IllegalArgumentException("Song title cannot be null or empty");
        }

        try {
            LOGGER.info("Adding test item to MRSC global table: " + tableName);

            Map<String, AttributeValue> item = new HashMap<>();
            item.put("Artist", AttributeValue.builder().s(artist).build());
            item.put("SongTitle", AttributeValue.builder().s(songTitle).build());

            if (album != null && !album.trim().isEmpty()) {
                item.put("Album", AttributeValue.builder().s(album).build());
            }
            if (year != null && !year.trim().isEmpty()) {
                item.put("Year", AttributeValue.builder().n(year).build());
            }

            PutItemRequest putItemRequest =
                PutItemRequest.builder().tableName(tableName).item(item).build();

            PutItemResponse response = dynamoDbClient.putItem(putItemRequest);
            LOGGER.info("Test item added successfully with strong consistency");

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to add test item to table: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Failed to add test item to table: " + tableName)
                .cause(e)
                .build();
        }
    }
```
を使用して、MRSC レプリカから一貫した読み取りを持つ項目を読み取ります AWS SDK for Java 2.x。  

```
    public static GetItemResponse getItemWithConsistentRead(
        final DynamoDbClient dynamoDbClient, final String tableName, final String artist, final String songTitle) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (artist == null || artist.trim().isEmpty()) {
            throw new IllegalArgumentException("Artist cannot be null or empty");
        }
        if (songTitle == null || songTitle.trim().isEmpty()) {
            throw new IllegalArgumentException("Song title cannot be null or empty");
        }

        try {
            LOGGER.info("Reading item from MRSC global table with consistent read: " + tableName);

            Map<String, AttributeValue> key = new HashMap<>();
            key.put("Artist", AttributeValue.builder().s(artist).build());
            key.put("SongTitle", AttributeValue.builder().s(songTitle).build());

            GetItemRequest getItemRequest = GetItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .consistentRead(true)
                .build();

            GetItemResponse response = dynamoDbClient.getItem(getItemRequest);

            if (response.hasItem()) {
                LOGGER.info("Item found with strong consistency - no wait time needed");
            } else {
                LOGGER.info("Item not found");
            }

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to read item from table: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Failed to read item from table: " + tableName)
                .cause(e)
                .build();
        }
    }
```
を使用して、MRSC 保証で条件付き更新を実行します AWS SDK for Java 2.x。  

```
    public static UpdateItemResponse performConditionalUpdate(
        final DynamoDbClient dynamoDbClient,
        final String tableName,
        final String artist,
        final String songTitle,
        final String rating) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (artist == null || artist.trim().isEmpty()) {
            throw new IllegalArgumentException("Artist cannot be null or empty");
        }
        if (songTitle == null || songTitle.trim().isEmpty()) {
            throw new IllegalArgumentException("Song title cannot be null or empty");
        }
        if (rating == null || rating.trim().isEmpty()) {
            throw new IllegalArgumentException("Rating cannot be null or empty");
        }

        try {
            LOGGER.info("Performing conditional update on MRSC global table: " + tableName);

            Map<String, AttributeValue> key = new HashMap<>();
            key.put("Artist", AttributeValue.builder().s(artist).build());
            key.put("SongTitle", AttributeValue.builder().s(songTitle).build());

            Map<String, String> expressionAttributeNames = new HashMap<>();
            expressionAttributeNames.put("#rating", "Rating");

            Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
            expressionAttributeValues.put(
                ":rating", AttributeValue.builder().n(rating).build());

            UpdateItemRequest updateItemRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET #rating = :rating")
                .conditionExpression("attribute_exists(Artist)")
                .expressionAttributeNames(expressionAttributeNames)
                .expressionAttributeValues(expressionAttributeValues)
                .build();

            UpdateItemResponse response = dynamoDbClient.updateItem(updateItemRequest);
            LOGGER.info("Conditional update successful - demonstrates strong consistency");

            return response;

        } catch (ConditionalCheckFailedException e) {
            LOGGER.warning("Conditional check failed: " + e.getMessage());
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to perform conditional update: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Failed to perform conditional update: " + tableName)
                .cause(e)
                .build();
        }
    }
```
を使用して MRSC レプリカと監視がアクティブになるまで待ちます AWS SDK for Java 2.x。  

```
    public static void waitForMRSCReplicasActive(
        final DynamoDbClient dynamoDbClient, final String tableName, final int maxWaitTimeSeconds)
        throws InterruptedException {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (maxWaitTimeSeconds <= 0) {
            throw new IllegalArgumentException("Max wait time must be positive");
        }

        try {
            LOGGER.info("Waiting for MRSC replicas and witnesses to become active: " + tableName);

            final long startTime = System.currentTimeMillis();
            final long maxWaitTimeMillis = maxWaitTimeSeconds * 1000L;
            int backoffSeconds = 5; // Start with 5 second intervals
            final int maxBackoffSeconds = 30; // Cap at 30 seconds

            while (System.currentTimeMillis() - startTime < maxWaitTimeMillis) {
                DescribeTableResponse response = describeMRSCTable(dynamoDbClient, tableName);

                boolean allActive = true;
                StringBuilder statusReport = new StringBuilder();

                if (response.table().multiRegionConsistency() == null
                    || !MultiRegionConsistency.STRONG
                        .toString()
                        .equals(response.table().multiRegionConsistency().toString())) {
                    allActive = false;
                    statusReport
                        .append("MultiRegionConsistency: ")
                        .append(response.table().multiRegionConsistency())
                        .append(" ");
                }
                if (response.table().replicas() == null
                    || response.table().replicas().isEmpty()) {
                    allActive = false;
                    statusReport.append("No replicas found. ");
                }
                if (response.table().globalTableWitnesses() == null
                    || response.table().globalTableWitnesses().isEmpty()) {
                    allActive = false;
                    statusReport.append("No witnesses found. ");
                }

                // Check table status
                if (!"ACTIVE".equals(response.table().tableStatus().toString())) {
                    allActive = false;
                    statusReport
                        .append("Table: ")
                        .append(response.table().tableStatus())
                        .append(" ");
                }

                // Check replica status
                if (response.table().replicas() != null) {
                    for (var replica : response.table().replicas()) {
                        if (!"ACTIVE".equals(replica.replicaStatus().toString())) {
                            allActive = false;
                            statusReport
                                .append("Replica(")
                                .append(replica.regionName())
                                .append("): ")
                                .append(replica.replicaStatus())
                                .append(" ");
                        }
                    }
                }

                // Check witness status
                if (response.table().globalTableWitnesses() != null) {
                    for (var witness : response.table().globalTableWitnesses()) {
                        if (!"ACTIVE".equals(witness.witnessStatus().toString())) {
                            allActive = false;
                            statusReport
                                .append("Witness(")
                                .append(witness.regionName())
                                .append("): ")
                                .append(witness.witnessStatus())
                                .append(" ");
                        }
                    }
                }

                if (allActive) {
                    LOGGER.info("All MRSC replicas and witnesses are now active: " + tableName);
                    return;
                }

                LOGGER.info("Waiting for MRSC components to become active. Status: " + statusReport.toString());
                LOGGER.info("Next check in " + backoffSeconds + " seconds...");

                tempWait(backoffSeconds);

                // Exponential backoff with cap
                backoffSeconds = Math.min(backoffSeconds * 2, maxBackoffSeconds);
            }

            throw DynamoDbException.builder()
                .message("Timeout waiting for MRSC replicas to become active after " + maxWaitTimeSeconds + " seconds")
                .build();

        } catch (DynamoDbException | InterruptedException e) {
            LOGGER.severe("Failed to wait for MRSC replicas to become active: " + tableName + " - " + e.getMessage());
            throw e;
        }
    }
```
を使用して MRSC レプリカと監視者をクリーンアップします AWS SDK for Java 2.x。  

```
    public static UpdateTableResponse cleanupMRSCReplicas(
        final DynamoDbClient dynamoDbClient,
        final String tableName,
        final Region replicaRegion,
        final Region witnessRegion) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (replicaRegion == null) {
            throw new IllegalArgumentException("Replica region cannot be null");
        }
        if (witnessRegion == null) {
            throw new IllegalArgumentException("Witness region cannot be null");
        }

        try {
            LOGGER.info("Cleaning up MRSC replicas and witnesses for table: " + tableName);

            // Remove replica using ReplicationGroupUpdate
            ReplicationGroupUpdate replicaUpdate = ReplicationGroupUpdate.builder()
                .delete(DeleteReplicationGroupMemberAction.builder()
                    .regionName(replicaRegion.id())
                    .build())
                .build();

            // Remove witness
            GlobalTableWitnessGroupUpdate witnessUpdate = GlobalTableWitnessGroupUpdate.builder()
                .delete(DeleteGlobalTableWitnessGroupMemberAction.builder()
                    .regionName(witnessRegion.id())
                    .build())
                .build();

            UpdateTableRequest updateTableRequest = UpdateTableRequest.builder()
                .tableName(tableName)
                .replicaUpdates(List.of(replicaUpdate))
                .globalTableWitnessUpdates(List.of(witnessUpdate))
                .build();

            UpdateTableResponse response = dynamoDbClient.updateTable(updateTableRequest);
            LOGGER.info("MRSC cleanup initiated - removing replica and witness. Response: " + response);

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to cleanup MRSC replicas: " + tableName + " - " + e.getMessage());
            throw DynamoDbException.builder()
                .message("Failed to cleanup MRSC replicas: " + tableName)
                .cause(e)
                .build();
        }
    }
```
を使用して MRSC ワークフローのデモンストレーションを完了します AWS SDK for Java 2.x。  

```
    public static void demonstrateCompleteMRSCWorkflow(
        final DynamoDbClient primaryClient,
        final DynamoDbClient replicaClient,
        final String tableName,
        final Region replicaRegion,
        final Region witnessRegion)
        throws InterruptedException {

        if (primaryClient == null) {
            throw new IllegalArgumentException("Primary DynamoDB client cannot be null");
        }
        if (replicaClient == null) {
            throw new IllegalArgumentException("Replica DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (replicaRegion == null) {
            throw new IllegalArgumentException("Replica region cannot be null");
        }
        if (witnessRegion == null) {
            throw new IllegalArgumentException("Witness region cannot be null");
        }

        try {
            LOGGER.info("=== Starting Complete MRSC Workflow Demonstration ===");

            // Step 1: Create an empty single-Region table
            LOGGER.info("Step 1: Creating empty single-Region table");
            createRegionalTable(primaryClient, tableName);

            // Use the existing GlobalTableOperations method for basic table waiting
            LOGGER.info("Intermediate step: Waiting for table [" + tableName + "] to become active before continuing");
            GlobalTableOperations.waitForTableActive(primaryClient, tableName);

            // Step 2: Convert to MRSC with replica and witness
            LOGGER.info("Step 2: Converting to MRSC with replica and witness");
            convertToMRSCWithWitness(primaryClient, tableName, replicaRegion, witnessRegion);

            // Wait for MRSC conversion to complete using MRSC-specific waiter
            LOGGER.info("Waiting for MRSC conversion to complete...");
            waitForMRSCReplicasActive(primaryClient, tableName);

            LOGGER.info("Intermediate step: Waiting for table [" + tableName + "] to become active before continuing");
            GlobalTableOperations.waitForTableActive(primaryClient, tableName);

            // Step 3: Verify MRSC configuration
            LOGGER.info("Step 3: Verifying MRSC configuration");
            describeMRSCTable(primaryClient, tableName);

            // Step 4: Test strong consistency with data operations
            LOGGER.info("Step 4: Testing strong consistency with data operations");

            // Add test item to primary region
            putTestItem(primaryClient, tableName, "The Beatles", "Hey Jude", "The Beatles 1967-1970", "1968");

            // Immediately read from replica region (no wait needed with MRSC)
            LOGGER.info("Reading from replica region immediately (strong consistency):");
            GetItemResponse getResponse =
                getItemWithConsistentRead(replicaClient, tableName, "The Beatles", "Hey Jude");

            if (getResponse.hasItem()) {
                LOGGER.info("✓ Strong consistency verified - item immediately available in replica region");
            } else {
                LOGGER.warning("✗ Item not found in replica region");
            }

            // Test conditional update from replica region
            LOGGER.info("Testing conditional update from replica region:");
            performConditionalUpdate(replicaClient, tableName, "The Beatles", "Hey Jude", "5");
            LOGGER.info("✓ Conditional update successful - demonstrates strong consistency");

            // Step 5: Cleanup
            LOGGER.info("Step 5: Cleaning up resources");
            cleanupMRSCReplicas(primaryClient, tableName, replicaRegion, witnessRegion);

            // Wait for cleanup to complete using basic table waiter
            LOGGER.info("Waiting for replica cleanup to complete...");
            GlobalTableOperations.waitForTableActive(primaryClient, tableName);

            // "Halt" until replica/witness cleanup is complete
            DescribeTableResponse cleanupVerification = describeMRSCTable(primaryClient, tableName);
            int backoffSeconds = 5; // Start with 5 second intervals
            while (cleanupVerification.table().multiRegionConsistency() != null) {
                LOGGER.info("Waiting additional time (" + backoffSeconds + " seconds) for MRSC cleanup to complete...");
                tempWait(backoffSeconds);

                // Exponential backoff with cap
                backoffSeconds = Math.min(backoffSeconds * 2, 30);
                cleanupVerification = describeMRSCTable(primaryClient, tableName);
            }

            // Delete the primary table
            deleteTable(primaryClient, tableName);

            LOGGER.info("=== MRSC Workflow Demonstration Complete ===");
            LOGGER.info("");
            LOGGER.info("Key benefits of Multi-Region Strong Consistency (MRSC):");
            LOGGER.info("- Immediate consistency across all regions (no eventual consistency delays)");
            LOGGER.info("- Simplified application logic (no need to handle eventual consistency)");
            LOGGER.info("- Support for conditional writes and transactions across regions");
            LOGGER.info("- Consistent read operations from any region without waiting");

        } catch (DynamoDbException | InterruptedException e) {
            LOGGER.severe("MRSC workflow failed: " + e.getMessage());
            throw e;
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)
  + [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)
  + [UpdateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateTable)

### MREC を示すグローバルテーブルの作成と管理
<a name="dynamodb_Scenario_GlobalTableOperations_java_2_topic"></a>

次のコード例は、複数のリージョンにまたがるレプリカを含む DynamoDB グローバルテーブルを作成して管理する方法を示しています。
+ グローバルセカンダリインデックスおよび DynamoDB Streams を含むテーブルを作成します。
+ 異なるリージョンにレプリカを追加して、グローバルテーブルを作成します。
+ グローバルテーブルからレプリカを削除します。
+ テスト項目を追加して、リージョン間のレプリケーションを検証します。
+ グローバルテーブル設定とレプリカのステータスについて説明します。

**SDK for Java 2.x**  
を使用して、グローバルセカンダリインデックスと DynamoDB ストリームを含むテーブルを作成します AWS SDK for Java 2.x。  

```
    public static CreateTableResponse createTableWithGSI(
        final DynamoDbClient dynamoDbClient, final String tableName, final String indexName) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (indexName == null || indexName.trim().isEmpty()) {
            throw new IllegalArgumentException("Index name cannot be null or empty");
        }

        try {
            LOGGER.info("Creating table: " + tableName + " with GSI: " + indexName);

            CreateTableRequest createTableRequest = CreateTableRequest.builder()
                .tableName(tableName)
                .attributeDefinitions(
                    AttributeDefinition.builder()
                        .attributeName("Artist")
                        .attributeType(ScalarAttributeType.S)
                        .build(),
                    AttributeDefinition.builder()
                        .attributeName("SongTitle")
                        .attributeType(ScalarAttributeType.S)
                        .build())
                .keySchema(
                    KeySchemaElement.builder()
                        .attributeName("Artist")
                        .keyType(KeyType.HASH)
                        .build(),
                    KeySchemaElement.builder()
                        .attributeName("SongTitle")
                        .keyType(KeyType.RANGE)
                        .build())
                .billingMode(BillingMode.PAY_PER_REQUEST)
                .globalSecondaryIndexes(GlobalSecondaryIndex.builder()
                    .indexName(indexName)
                    .keySchema(KeySchemaElement.builder()
                        .attributeName("SongTitle")
                        .keyType(KeyType.HASH)
                        .build())
                    .projection(
                        Projection.builder().projectionType(ProjectionType.ALL).build())
                    .build())
                .streamSpecification(StreamSpecification.builder()
                    .streamEnabled(true)
                    .streamViewType(StreamViewType.NEW_AND_OLD_IMAGES)
                    .build())
                .build();

            CreateTableResponse response = dynamoDbClient.createTable(createTableRequest);
            LOGGER.info("Table creation initiated. Status: "
                + response.tableDescription().tableStatus());

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to create table: " + tableName + " - " + e.getMessage());
            throw e;
        }
    }
```
を使用してテーブルがアクティブになるまで待ちます AWS SDK for Java 2.x。  

```
    public static void waitForTableActive(final DynamoDbClient dynamoDbClient, final String tableName) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }

        try {
            LOGGER.info("Waiting for table to become active: " + tableName);

            try (DynamoDbWaiter waiter =
                DynamoDbWaiter.builder().client(dynamoDbClient).build()) {
                DescribeTableRequest request =
                    DescribeTableRequest.builder().tableName(tableName).build();

                waiter.waitUntilTableExists(request);
                LOGGER.info("Table is now active: " + tableName);
            }

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to wait for table to become active: " + tableName + " - " + e.getMessage());
            throw e;
        }
    }
```
レプリカを追加して、 を使用してグローバルテーブルを作成または拡張します AWS SDK for Java 2.x。  

```
    public static UpdateTableResponse addReplica(
        final DynamoDbClient dynamoDbClient,
        final String tableName,
        final Region replicaRegion,
        final String indexName,
        final Long readCapacity) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (replicaRegion == null) {
            throw new IllegalArgumentException("Replica region cannot be null");
        }
        if (indexName == null || indexName.trim().isEmpty()) {
            throw new IllegalArgumentException("Index name cannot be null or empty");
        }
        if (readCapacity == null || readCapacity <= 0) {
            throw new IllegalArgumentException("Read capacity must be a positive number");
        }

        try {
            LOGGER.info("Adding replica in region: " + replicaRegion.id() + " for table: " + tableName);

            // Create a ReplicationGroupUpdate for adding a replica
            ReplicationGroupUpdate replicationGroupUpdate = ReplicationGroupUpdate.builder()
                .create(builder -> builder.regionName(replicaRegion.id())
                    .globalSecondaryIndexes(ReplicaGlobalSecondaryIndex.builder()
                        .indexName(indexName)
                        .provisionedThroughputOverride(ProvisionedThroughputOverride.builder()
                            .readCapacityUnits(readCapacity)
                            .build())
                        .build())
                    .build())
                .build();

            UpdateTableRequest updateTableRequest = UpdateTableRequest.builder()
                .tableName(tableName)
                .replicaUpdates(replicationGroupUpdate)
                .build();

            UpdateTableResponse response = dynamoDbClient.updateTable(updateTableRequest);
            LOGGER.info("Replica addition initiated in region: " + replicaRegion.id());

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to add replica in region: " + replicaRegion.id() + " - " + e.getMessage());
            throw e;
        }
    }
```
を使用してグローバルテーブルからレプリカを削除します AWS SDK for Java 2.x。  

```
    public static UpdateTableResponse removeReplica(
        final DynamoDbClient dynamoDbClient, final String tableName, final Region replicaRegion) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (replicaRegion == null) {
            throw new IllegalArgumentException("Replica region cannot be null");
        }

        try {
            LOGGER.info("Removing replica in region: " + replicaRegion.id() + " for table: " + tableName);

            // Create a ReplicationGroupUpdate for removing a replica
            ReplicationGroupUpdate replicationGroupUpdate = ReplicationGroupUpdate.builder()
                .delete(builder -> builder.regionName(replicaRegion.id()).build())
                .build();

            UpdateTableRequest updateTableRequest = UpdateTableRequest.builder()
                .tableName(tableName)
                .replicaUpdates(replicationGroupUpdate)
                .build();

            UpdateTableResponse response = dynamoDbClient.updateTable(updateTableRequest);
            LOGGER.info("Replica removal initiated in region: " + replicaRegion.id());

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to remove replica in region: " + replicaRegion.id() + " - " + e.getMessage());
            throw e;
        }
    }
```
テスト項目を追加して、 を使用してレプリケーションを検証します AWS SDK for Java 2.x。  

```
    public static PutItemResponse putTestItem(
        final DynamoDbClient dynamoDbClient, final String tableName, final String artist, final String songTitle) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }
        if (artist == null || artist.trim().isEmpty()) {
            throw new IllegalArgumentException("Artist cannot be null or empty");
        }
        if (songTitle == null || songTitle.trim().isEmpty()) {
            throw new IllegalArgumentException("Song title cannot be null or empty");
        }

        try {
            LOGGER.info("Adding test item to table: " + tableName);

            Map<String, software.amazon.awssdk.services.dynamodb.model.AttributeValue> item = new HashMap<>();
            item.put(
                "Artist",
                software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
                    .s(artist)
                    .build());
            item.put(
                "SongTitle",
                software.amazon.awssdk.services.dynamodb.model.AttributeValue.builder()
                    .s(songTitle)
                    .build());

            PutItemRequest putItemRequest =
                PutItemRequest.builder().tableName(tableName).item(item).build();

            PutItemResponse response = dynamoDbClient.putItem(putItemRequest);
            LOGGER.info("Test item added successfully");

            return response;

        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to add test item to table: " + tableName + " - " + e.getMessage());
            throw e;
        }
    }
```
を使用してグローバルテーブル設定とレプリカを記述します AWS SDK for Java 2.x。  

```
    public static DescribeTableResponse describeTable(final DynamoDbClient dynamoDbClient, final String tableName) {

        if (dynamoDbClient == null) {
            throw new IllegalArgumentException("DynamoDB client cannot be null");
        }
        if (tableName == null || tableName.trim().isEmpty()) {
            throw new IllegalArgumentException("Table name cannot be null or empty");
        }

        try {
            LOGGER.info("Describing table: " + tableName);

            DescribeTableRequest request =
                DescribeTableRequest.builder().tableName(tableName).build();

            DescribeTableResponse response = dynamoDbClient.describeTable(request);

            LOGGER.info("Table status: " + response.table().tableStatus());
            if (response.table().replicas() != null
                && !response.table().replicas().isEmpty()) {
                LOGGER.info("Number of replicas: " + response.table().replicas().size());
                response.table()
                    .replicas()
                    .forEach(replica -> LOGGER.info(
                        "Replica region: " + replica.regionName() + ", Status: " + replica.replicaStatus()));
            }

            return response;

        } catch (ResourceNotFoundException e) {
            LOGGER.severe("Table not found: " + tableName + " - " + e.getMessage());
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.severe("Failed to describe table: " + tableName + " - " + e.getMessage());
            throw e;
        }
    }
```
を使用したグローバルテーブルオペレーションの例を完成させます AWS SDK for Java 2.x。  

```
    public static void exampleUsage(final Region sourceRegion, final Region replicaRegion) {

        String tableName = "Music";
        String indexName = "SongTitleIndex";
        Long readCapacity = 15L;

        // Create DynamoDB client for the source region
        try (DynamoDbClient dynamoDbClient =
            DynamoDbClient.builder().region(sourceRegion).build()) {

            try {
                // Step 1: Create the initial table with GSI and streams
                LOGGER.info("Step 1: Creating table in source region: " + sourceRegion.id());
                createTableWithGSI(dynamoDbClient, tableName, indexName);

                // Step 2: Wait for table to become active
                LOGGER.info("Step 2: Waiting for table to become active");
                waitForTableActive(dynamoDbClient, tableName);

                // Step 3: Add replica in destination region
                LOGGER.info("Step 3: Adding replica in region: " + replicaRegion.id());
                addReplica(dynamoDbClient, tableName, replicaRegion, indexName, readCapacity);

                // Step 4: Wait a moment for replica creation to start
                Thread.sleep(5000);

                // Step 5: Describe table to view replica information
                LOGGER.info("Step 5: Describing table to view replicas");
                describeTable(dynamoDbClient, tableName);

                // Step 6: Add a test item to verify replication
                LOGGER.info("Step 6: Adding test item to verify replication");
                putTestItem(dynamoDbClient, tableName, "TestArtist", "TestSong");

                LOGGER.info("Global table setup completed successfully!");
                LOGGER.info("You can verify replication by checking the item in region: " + replicaRegion.id());

                // Step 7: Remove replica and clean up table
                LOGGER.info("Step 7: Removing replica from region: " + replicaRegion.id());
                removeReplica(dynamoDbClient, tableName, replicaRegion);
                DeleteTableResponse deleteTableResponse = dynamoDbClient.deleteTable(
                    DeleteTableRequest.builder().tableName(tableName).build());
                LOGGER.info("MREC global table demonstration completed successfully!");

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("Thread was interrupted", e);
            } catch (DynamoDbException e) {
                LOGGER.severe("DynamoDB operation failed: " + e.getMessage());
                throw e;
            }
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/CreateTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DescribeTable)
  + [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)
  + [UpdateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateTable)

### 画像内の PPE を検出する
<a name="cross_RekognitionPhotoAnalyzerPPE_java_2_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内の個人用防護具 (PPE) を検出するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 個人用保護具でイメージを検出する AWS Lambda 関数を作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_ppe) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### DynamoDB のパフォーマンスのモニタリング
<a name="cross_MonitorDynamoDB_java_2_topic"></a>

次のコード例は、DynamoDB のパフォーマンスをモニタリングするように、アプリケーションを設定する方法を示しています。

**SDK for Java 2.x**  
 この例では、DynamoDB のパフォーマンスをモニタリングするように Java アプリケーションを設定する方法を示します。アプリケーションからメトリクスデータを CloudWatch に送信してパフォーマンスをモニタリングできます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/monitor_dynamodb) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch
+ DynamoDB

### 高度なクエリオペレーションを実行する
<a name="dynamodb_Scenario_AdvancedQueryTechniques_java_2_topic"></a>

次のコード例は、DynamoDB で高度なクエリオペレーションを実行する方法を示しています。
+ さまざまなフィルタリングと条件の手法を使用してテーブルをクエリします。
+ 大きな結果セットのページ分割を実装します。
+ 代替アクセスパターンにはグローバルセカンダリインデックスを使用します。
+ アプリケーション要件に基づいて整合性コントロールを適用します。

**SDK for Java 2.x**  
を使用して、強力な整合性のある読み取りでクエリを実行します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithConsistentReads(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final boolean useConsistentRead) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .consistentRead(useConsistentRead)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            LOGGER.log(Level.INFO, "Query successful. Found {0} items", response.count());
            return response;
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", tableName);
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "Error querying with consistent reads", e);
            throw e;
        }
    }
```
を使用したグローバルセカンダリインデックスを使用したクエリ AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;

    public QueryResponse queryTable(
        final String tableName, final String partitionKeyName, final String partitionKeyValue) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            System.out.println("Query on base table successful. Found " + response.count() + " items");
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            throw new DynamoDbQueryException("Table not found: " + tableName, e);
        } catch (DynamoDbException e) {
            System.err.println("Error querying base table: " + e.getMessage());
            throw new DynamoDbQueryException("Failed to execute query on base table", e);
        }
    }

    /**
     * Queries a DynamoDB Global Secondary Index (GSI) by partition key.
     *
     * @param tableName         The name of the DynamoDB table
     * @param indexName         The name of the GSI
     * @param partitionKeyName  The name of the GSI partition key attribute
     * @param partitionKeyValue The value of the GSI partition key to query
     * @return The query response from DynamoDB
     * @throws ResourceNotFoundException if the table or index doesn't exist
     * @throws DynamoDbException if the query fails
     */
    public QueryResponse queryGlobalSecondaryIndex(
        final String tableName, final String indexName, final String partitionKeyName, final String partitionKeyValue) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Index name", indexName);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_IK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_IK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .indexName(indexName)
            .keyConditionExpression(GSI_KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            System.out.println("Query on GSI successful. Found " + response.count() + " items");
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format(
                "Error: The Amazon DynamoDB table \"%s\" or index \"%s\" can't be found.\n", tableName, indexName);
            throw new DynamoDbQueryException("Table or index not found: " + tableName + "/" + indexName, e);
        } catch (DynamoDbException e) {
            System.err.println("Error querying GSI: " + e.getMessage());
            throw new DynamoDbQueryException("Failed to execute query on GSI", e);
        }
    }
```
を使用してページ分割でクエリを実行します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    public List<Map<String, AttributeValue>> queryWithPagination(
        final String tableName, final String partitionKeyName, final String partitionKeyValue, final int pageSize) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validatePositiveInteger("Page size", pageSize);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .limit(pageSize);

        // List to store all items from all pages
        final List<Map<String, AttributeValue>> allItems = new ArrayList<>();

        // Map to store the last evaluated key for pagination
        Map<String, AttributeValue> lastEvaluatedKey = null;
        int pageNumber = 1;

        try {
            do {
                // If we have a last evaluated key, use it for the next page
                if (lastEvaluatedKey != null) {
                    queryRequestBuilder.exclusiveStartKey(lastEvaluatedKey);
                }

                // Execute the query
                final QueryResponse response = dynamoDbClient.query(queryRequestBuilder.build());

                // Process the current page of results
                final List<Map<String, AttributeValue>> pageItems = response.items();
                allItems.addAll(pageItems);

                // Get the last evaluated key for the next page
                lastEvaluatedKey = response.lastEvaluatedKey();
                if (lastEvaluatedKey != null && lastEvaluatedKey.isEmpty()) {
                    lastEvaluatedKey = null;
                }

                System.out.println("Page " + pageNumber + ": Retrieved " + pageItems.size() + " items (Running total: "
                    + allItems.size() + ")");

                pageNumber++;

            } while (lastEvaluatedKey != null);

            System.out.println("Query with pagination complete. Retrieved a total of " + allItems.size()
                + " items across " + (pageNumber - 1) + " pages");

            return allItems;
        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println("Error querying with pagination: " + e.getMessage());
            throw e;
        }
    }
```
を使用して複雑なフィルターでクエリを実行します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithComplexFilter(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String statusAttrName,
        final String activeStatus,
        final String pendingStatus,
        final String priceAttrName,
        final double minPrice,
        final double maxPrice,
        final String categoryAttrName) {

        // Validate parameters
        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Status attribute name", statusAttrName);
        CodeSampleUtils.validateStringParameter("Active status", activeStatus);
        CodeSampleUtils.validateStringParameter("Pending status", pendingStatus);
        CodeSampleUtils.validateStringParameter("Price attribute name", priceAttrName);
        CodeSampleUtils.validateStringParameter("Category attribute name", categoryAttrName);
        CodeSampleUtils.validateNumericRange("Minimum price", minPrice, 0.0, Double.MAX_VALUE);
        CodeSampleUtils.validateNumericRange("Maximum price", maxPrice, minPrice, Double.MAX_VALUE);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put("#pk", partitionKeyName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_STATUS, statusAttrName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PRICE, priceAttrName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_CATEGORY, categoryAttrName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            ":pkValue", AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_ACTIVE,
            AttributeValue.builder().s(activeStatus).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PENDING,
            AttributeValue.builder().s(pendingStatus).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_MIN_PRICE,
            AttributeValue.builder().n(String.valueOf(minPrice)).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_MAX_PRICE,
            AttributeValue.builder().n(String.valueOf(maxPrice)).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .filterExpression(FILTER_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        return dynamoDbClient.query(queryRequest);
    }
```
を使用して動的に構築されたフィルター式でクエリを実行します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;

    public static QueryResponse queryWithDynamicFilter(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final Map<String, Object> filterCriteria,
        final Region region,
        final DynamoDbClient dynamoDbClient) {

        validateParameters(tableName, partitionKeyName, partitionKeyValue, filterCriteria);

        DynamoDbClient ddbClient = dynamoDbClient;
        boolean shouldClose = false;

        try {
            if (ddbClient == null) {
                ddbClient = createClient(region);
                shouldClose = true;
            }

            final QueryWithDynamicFilter queryHelper = new QueryWithDynamicFilter(ddbClient);
            return queryHelper.queryWithDynamicFilter(tableName, partitionKeyName, partitionKeyValue, filterCriteria);
        } catch (ResourceNotFoundException e) {
            System.err.println("Table not found: " + tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println("Failed to execute dynamic filter query: " + e.getMessage());
            throw e;
        } catch (Exception e) {
            System.err.println("Unexpected error during query: " + e.getMessage());
            throw e;
        } finally {
            if (shouldClose && ddbClient != null) {
                ddbClient.close();
            }
        }
    }

    public static void main(String[] args) {
        final String usage =
            """
                Usage:
                    <tableName> <partitionKeyName> <partitionKeyValue> <filterAttrName> <filterAttrValue> [region]
                Where:
                    tableName - The Amazon DynamoDB table to query.
                    partitionKeyName - The name of the partition key attribute.
                    partitionKeyValue - The value of the partition key to query.
                    filterAttrName - The name of the attribute to filter on.
                    filterAttrValue - The value to filter by.
                    region (optional) - The AWS region where the table exists. (Default: us-east-1)
                """;

        if (args.length < 5) {
            System.out.println(usage);
            System.exit(1);
        }

        final String tableName = args[0];
        final String partitionKeyName = args[1];
        final String partitionKeyValue = args[2];
        final String filterAttrName = args[3];
        final String filterAttrValue = args[4];
        final Region region = args.length > 5 ? Region.of(args[5]) : Region.US_EAST_1;

        System.out.println("Querying items with dynamic filter: " + filterAttrName + " = " + filterAttrValue);

        try {
            // Using the builder pattern to create and execute the query
            final QueryResponse response = new DynamicFilterQueryBuilder()
                .withTableName(tableName)
                .withPartitionKeyName(partitionKeyName)
                .withPartitionKeyValue(partitionKeyValue)
                .withFilterCriterion(filterAttrName, filterAttrValue)
                .withRegion(region)
                .execute();

            // Process the results
            System.out.println("Found " + response.count() + " items:");
            response.items().forEach(item -> System.out.println(item));

            // Demonstrate multiple filter criteria
            System.out.println("\nNow querying with multiple filter criteria:");

            Map<String, Object> multipleFilters = new HashMap<>();
            multipleFilters.put(filterAttrName, filterAttrValue);
            multipleFilters.put("status", "active");

            final QueryResponse multiFilterResponse = new DynamicFilterQueryBuilder()
                .withTableName(tableName)
                .withPartitionKeyName(partitionKeyName)
                .withPartitionKeyValue(partitionKeyValue)
                .withFilterCriteria(multipleFilters)
                .withRegion(region)
                .execute();

            System.out.println("Found " + multiFilterResponse.count() + " items with multiple filters:");
            multiFilterResponse.items().forEach(item -> System.out.println(item));

        } catch (IllegalArgumentException e) {
            System.err.println("Invalid input: " + e.getMessage());
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            System.err.println("Table not found: " + tableName);
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println("DynamoDB error: " + e.getMessage());
            System.exit(1);
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            System.exit(1);
        }
    }
```
フィルター式を使用してクエリを実行し、 を使用して制限します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithFilterAndLimit(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String filterAttrName,
        final String filterAttrValue,
        final int limit) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Filter attribute name", filterAttrName);
        CodeSampleUtils.validateStringParameter("Filter attribute value", filterAttrValue);
        CodeSampleUtils.validatePositiveInteger("Limit", limit);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_FILTER, filterAttrName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_FILTER,
            AttributeValue.builder().s(filterAttrValue).build());

        // Create the filter expression
        final String filterExpression = "#filterAttr = :filterValue";

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .filterExpression(filterExpression)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .limit(limit)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            LOGGER.log(Level.INFO, "Query with filter and limit successful. Found {0} items", response.count());
            LOGGER.log(
                Level.INFO, "ScannedCount: {0} (total items evaluated before filtering)", response.scannedCount());
            return response;
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", tableName);
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "Error querying with filter and limit: {0}", e.getMessage());
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### リストオペレーションを実行する
<a name="dynamodb_Scenario_ListOperations_java_2_topic"></a>

次のコード例は、DynamoDB でリストオペレーションを実行する方法を示しています。
+ リスト属性に要素を追加します。
+ リスト属性から要素を削除します。
+ インデックスでリスト内の特定の要素を更新します。
+ リスト追加関数およびリストインデックス関数を使用します。

**SDK for Java 2.x**  
を使用してリストオペレーションをデモンストレーションします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    /**
     * Appends items to a list attribute.
     *
     * <p>This method demonstrates how to use the list_append function to add
     * items to the end of a list attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param listAttributeName The name of the list attribute
     * @param itemsToAppend The items to append to the list
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse appendToList(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String listAttributeName,
        List<AttributeValue> itemsToAppend) {

        // Create a list value from the items to append
        AttributeValue listValue = AttributeValue.builder().l(itemsToAppend).build();

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #attrName = list_append(if_not_exists(#attrName, :emptyList), :newItems)")
            .expressionAttributeNames(Map.of("#attrName", listAttributeName))
            .expressionAttributeValues(Map.of(
                ":newItems",
                listValue,
                ":emptyList",
                AttributeValue.builder().l(new ArrayList<AttributeValue>()).build()))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Prepends items to a list attribute.
     *
     * <p>This method demonstrates how to use the list_append function to add
     * items to the beginning of a list attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param listAttributeName The name of the list attribute
     * @param itemsToPrepend The items to prepend to the list
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse prependToList(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String listAttributeName,
        List<AttributeValue> itemsToPrepend) {

        // Create a list value from the items to prepend
        AttributeValue listValue = AttributeValue.builder().l(itemsToPrepend).build();

        // Define the update parameters
        // Note: To prepend, we put the new items first in the list_append function
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #attrName = list_append(:newItems, if_not_exists(#attrName, :emptyList))")
            .expressionAttributeNames(Map.of("#attrName", listAttributeName))
            .expressionAttributeValues(Map.of(
                ":newItems",
                listValue,
                ":emptyList",
                AttributeValue.builder().l(new ArrayList<AttributeValue>()).build()))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Updates a specific element in a list attribute.
     *
     * <p>This method demonstrates how to update a specific element in a list
     * by its index.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param listAttributeName The name of the list attribute
     * @param index The index of the element to update
     * @param newValue The new value for the element
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateListElement(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String listAttributeName,
        int index,
        AttributeValue newValue) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #attrName[" + index + "] = :newValue")
            .expressionAttributeNames(Map.of("#attrName", listAttributeName))
            .expressionAttributeValues(Map.of(":newValue", newValue))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Removes a specific element from a list attribute.
     *
     * <p>This method demonstrates how to remove a specific element from a list
     * by its index.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param listAttributeName The name of the list attribute
     * @param index The index of the element to remove
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse removeListElement(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String listAttributeName,
        int index) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("REMOVE #attrName[" + index + "]")
            .expressionAttributeNames(Map.of("#attrName", listAttributeName))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Gets the current value of a list attribute.
     *
     * <p>Helper method to retrieve the current value of a list attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to get
     * @param listAttributeName The name of the list attribute
     * @return The list attribute value or null if not found
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static List<AttributeValue> getListAttribute(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key, String listAttributeName) {

        // Define the get parameters
        GetItemRequest request = GetItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .projectionExpression(listAttributeName)
            .build();

        try {
            // Perform the get operation
            GetItemResponse response = dynamoDbClient.getItem(request);

            // Return the list attribute if it exists, otherwise null
            if (response.item() != null && response.item().containsKey(listAttributeName)) {
                return response.item().get(listAttributeName).l();
            }

            return null;
        } catch (DynamoDbException e) {
            throw DynamoDbException.builder()
                .message("Failed to get list attribute: " + e.getMessage())
                .cause(e)
                .build();
        }
    }
```
を使用したリストオペレーションの使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating list operations in DynamoDB");

        try {
            // Example 1: Append items to a list
            System.out.println("\nExample 1: Appending items to a list");
            List<AttributeValue> tagsToAppend = List.of(
                AttributeValue.builder().s("Electronics").build(),
                AttributeValue.builder().s("Gadget").build());

            UpdateItemResponse appendResponse = appendToList(dynamoDbClient, tableName, key, "Tags", tagsToAppend);

            System.out.println("Updated list attribute: " + appendResponse.attributes());

            // Example 2: Prepend items to a list
            System.out.println("\nExample 2: Prepending items to a list");
            List<AttributeValue> tagsToPrepend = List.of(
                AttributeValue.builder().s("Featured").build(),
                AttributeValue.builder().s("New").build());

            UpdateItemResponse prependResponse = prependToList(dynamoDbClient, tableName, key, "Tags", tagsToPrepend);

            System.out.println("Updated list attribute: " + prependResponse.attributes());

            // Example 3: Update a specific element in a list
            System.out.println("\nExample 3: Updating a specific element in a list");
            UpdateItemResponse updateResponse = updateListElement(
                dynamoDbClient,
                tableName,
                key,
                "Tags",
                0,
                AttributeValue.builder().s("BestSeller").build());

            System.out.println("Updated list attribute: " + updateResponse.attributes());

            // Example 4: Remove a specific element from a list
            System.out.println("\nExample 4: Removing a specific element from a list");
            UpdateItemResponse removeResponse = removeListElement(dynamoDbClient, tableName, key, "Tags", 1);

            System.out.println("Updated list attribute: " + removeResponse.attributes());

            // Example 5: Get the current value of a list attribute
            System.out.println("\nExample 5: Getting the current value of a list attribute");
            List<AttributeValue> currentList = getListAttribute(dynamoDbClient, tableName, key, "Tags");

            if (currentList != null) {
                System.out.println("Current list attribute:");
                for (int i = 0; i < currentList.size(); i++) {
                    System.out.println("  [" + i + "]: " + currentList.get(i).s());
                }
            } else {
                System.out.println("List attribute not found");
            }

            // Explain list operations
            System.out.println("\nKey points about DynamoDB list operations:");
            System.out.println("1. Lists are ordered collections of attributes");
            System.out.println("2. Use list_append to add items to a list");
            System.out.println("3. To append items, use list_append(existingList, newItems)");
            System.out.println("4. To prepend items, use list_append(newItems, existingList)");
            System.out.println("5. Use index notation (list[0]) to access or update specific elements");
            System.out.println("6. Use REMOVE to delete elements from a list");
            System.out.println("7. List indices are zero-based");
            System.out.println("8. Use if_not_exists to handle the case where the list doesn't exist yet");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### マップオペレーションを実行する
<a name="dynamodb_Scenario_MapOperations_java_2_topic"></a>

次のコード例は、DynamoDB でマップオペレーションを実行する方法を示しています。
+ マップ構造にネストされた属性を追加および更新します。
+ マップから特定のフィールドを削除します。
+ 深くネストされたマップ属性を操作します。

**SDK for Java 2.x**  
を使用してマップオペレーションをデモンストレーションします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

    /**
     * Updates a map attribute that may not exist.
     *
     * <p>This method demonstrates how to safely update a map attribute
     * by using if_not_exists to handle the case where the map doesn't exist yet.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param mapName The name of the map attribute
     * @param mapKey The key within the map to update
     * @param value The value to set
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateMapAttributeSafe(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String mapName,
        String mapKey,
        AttributeValue value) {

        // Create an empty map to use if the map doesn't exist
        Map<String, AttributeValue> emptyMap = new HashMap<>();
        AttributeValue emptyMapValue = AttributeValue.builder().m(emptyMap).build();

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #mapName = if_not_exists(#mapName, :emptyMap), #mapName.#mapKey = :value")
            .expressionAttributeNames(Map.of(
                "#mapName", mapName,
                "#mapKey", mapKey))
            .expressionAttributeValues(Map.of(
                ":value",
                value,
                ":emptyMap",
                AttributeValue.builder().m(new HashMap<>()).build()))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Adds an attribute to a nested map.
     *
     * <p>This method demonstrates how to update a nested attribute without
     * overwriting the entire map.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param path The path to the nested attribute as a list
     * @param value The value to set
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse addToNestedMap(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        List<String> path,
        AttributeValue value) {

        // Create expression attribute names for each part of the path
        Map<String, String> expressionAttributeNames = new HashMap<>();
        for (int i = 0; i < path.size(); i++) {
            expressionAttributeNames.put("#attr" + i, path.get(i));
        }

        // Build the attribute path using the expression attribute names
        StringBuilder attributePathExpression = new StringBuilder();
        for (int i = 0; i < path.size(); i++) {
            if (i > 0) {
                attributePathExpression.append(".");
            }
            attributePathExpression.append("#attr").append(i);
        }

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET " + attributePathExpression.toString() + " = :value")
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(Map.of(":value", value))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Removes an attribute from a map.
     *
     * <p>This method demonstrates how to remove a specific attribute from a map.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param mapName The name of the map attribute
     * @param mapKey The key within the map to remove
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse removeMapAttribute(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String mapName,
        String mapKey) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("REMOVE #mapName.#mapKey")
            .expressionAttributeNames(Map.of(
                "#mapName", mapName,
                "#mapKey", mapKey))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Creates a map with multiple attributes in a single operation.
     *
     * <p>This method demonstrates how to create a map with multiple attributes
     * in a single update operation.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param mapName The name of the map attribute
     * @param attributes The attributes to set in the map
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse createMapWithAttributes(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String mapName,
        Map<String, AttributeValue> attributes) {

        // Create a map value from the attributes
        AttributeValue mapValue = AttributeValue.builder().m(attributes).build();

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #mapName = :mapValue")
            .expressionAttributeNames(Map.of("#mapName", mapName))
            .expressionAttributeValues(Map.of(":mapValue", mapValue))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Gets the current value of a map attribute.
     *
     * <p>Helper method to retrieve the current value of a map attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to get
     * @param mapName The name of the map attribute
     * @return The map attribute value or null if not found
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static Map<String, AttributeValue> getMapAttribute(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key, String mapName) {

        // Define the get parameters
        GetItemRequest request = GetItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .projectionExpression(mapName)
            .build();

        try {
            // Perform the get operation
            GetItemResponse response = dynamoDbClient.getItem(request);

            // Return the map attribute if it exists, otherwise null
            if (response.item() != null && response.item().containsKey(mapName)) {
                return response.item().get(mapName).m();
            }

            return null;
        } catch (DynamoDbException e) {
            throw DynamoDbException.builder()
                .message("Failed to get map attribute: " + e.getMessage())
                .cause(e)
                .build();
        }
    }
```
でのマップオペレーションの使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating map operations in DynamoDB");

        try {
            // Example 1: Create a map with multiple attributes
            System.out.println("\nExample 1: Creating a map with multiple attributes");
            Map<String, AttributeValue> productDetails = new HashMap<>();
            productDetails.put("Color", AttributeValue.builder().s("Red").build());
            productDetails.put("Weight", AttributeValue.builder().n("2.5").build());
            productDetails.put(
                "Dimensions", AttributeValue.builder().s("10x20x5").build());

            UpdateItemResponse createResponse =
                createMapWithAttributes(dynamoDbClient, tableName, key, "Details", productDetails);

            System.out.println("Created map attribute: " + createResponse.attributes());

            // Example 2: Update a specific attribute in a map
            System.out.println("\nExample 2: Updating a specific attribute in a map");
            UpdateItemResponse updateResponse = updateMapAttributeSafe(
                dynamoDbClient,
                tableName,
                key,
                "Details",
                "Color",
                AttributeValue.builder().s("Blue").build());

            System.out.println("Updated map attribute: " + updateResponse.attributes());

            // Example 3: Add an attribute to a nested map
            System.out.println("\nExample 3: Adding an attribute to a nested map");
            UpdateItemResponse nestedResponse = addToNestedMap(
                dynamoDbClient,
                tableName,
                key,
                List.of("Specifications", "Technical", "Resolution"),
                AttributeValue.builder().s("1920x1080").build());

            System.out.println("Added to nested map: " + nestedResponse.attributes());

            // Example 4: Remove an attribute from a map
            System.out.println("\nExample 4: Removing an attribute from a map");
            UpdateItemResponse removeResponse =
                removeMapAttribute(dynamoDbClient, tableName, key, "Details", "Dimensions");

            System.out.println("Updated map after removal: " + removeResponse.attributes());

            // Example 5: Get the current value of a map attribute
            System.out.println("\nExample 5: Getting the current value of a map attribute");
            Map<String, AttributeValue> currentMap = getMapAttribute(dynamoDbClient, tableName, key, "Details");

            if (currentMap != null) {
                System.out.println("Current map attribute:");
                for (Map.Entry<String, AttributeValue> entry : currentMap.entrySet()) {
                    System.out.println("  " + entry.getKey() + ": " + entry.getValue());
                }
            } else {
                System.out.println("Map attribute not found");
            }

            // Explain map operations
            System.out.println("\nKey points about DynamoDB map operations:");
            System.out.println("1. Maps are unordered collections of name-value pairs");
            System.out.println("2. Use dot notation (map.key) to access or update specific attributes");
            System.out.println("3. You can update individual attributes without overwriting the entire map");
            System.out.println("4. Maps can be nested to create complex data structures");
            System.out.println("5. Use REMOVE to delete attributes from a map");
            System.out.println("6. You can create a map with multiple attributes in a single operation");
            System.out.println("7. Map keys are case-sensitive");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### セットオペレーションを実行する
<a name="dynamodb_Scenario_SetOperations_java_2_topic"></a>

次のコード例は、DynamoDB でセットオペレーションを実行する方法を示しています。
+ セット属性に要素を追加します。
+ セット属性から要素を削除します。
+ セットで ADD および DELETE オペレーションを使用します。

**SDK for Java 2.x**  
を使用してセットオペレーションをデモンストレーションします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

    /**
     * Adds values to a string set attribute.
     *
     * <p>This method demonstrates how to use the ADD operation to add values
     * to a string set attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param setAttributeName The name of the set attribute
     * @param valuesToAdd The values to add to the set
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse addToStringSet(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String setAttributeName,
        Set<String> valuesToAdd) {

        // Create a string set value from the values to add
        AttributeValue setValue = AttributeValue.builder().ss(valuesToAdd).build();

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("ADD #setAttr :valuesToAdd")
            .expressionAttributeNames(Map.of("#setAttr", setAttributeName))
            .expressionAttributeValues(Map.of(":valuesToAdd", setValue))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Adds values to a number set attribute.
     *
     * <p>This method demonstrates how to use the ADD operation to add values
     * to a number set attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param setAttributeName The name of the set attribute
     * @param valuesToAdd The values to add to the set
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse addToNumberSet(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String setAttributeName,
        Set<Number> valuesToAdd) {

        // Convert numbers to strings for DynamoDB
        Set<String> stringValues = new HashSet<>();
        for (Number value : valuesToAdd) {
            stringValues.add(value.toString());
        }

        // Create a number set value from the values to add
        AttributeValue setValue = AttributeValue.builder().ns(stringValues).build();

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("ADD #setAttr :valuesToAdd")
            .expressionAttributeNames(Map.of("#setAttr", setAttributeName))
            .expressionAttributeValues(Map.of(":valuesToAdd", setValue))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Removes values from a set attribute.
     *
     * <p>This method demonstrates how to use the DELETE operation to remove values
     * from a set attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param setAttributeName The name of the set attribute
     * @param valuesToRemove The values to remove from the set
     * @param isNumberSet Whether the set is a number set (true) or string set (false)
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse removeFromSet(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String setAttributeName,
        Set<?> valuesToRemove,
        boolean isNumberSet) {

        AttributeValue setValue;

        if (isNumberSet) {
            // Convert numbers to strings for DynamoDB
            Set<String> stringValues = new HashSet<>();
            for (Object value : valuesToRemove) {
                if (value instanceof Number) {
                    stringValues.add(value.toString());
                } else {
                    throw new IllegalArgumentException("Values must be numbers for a number set");
                }
            }

            setValue = AttributeValue.builder().ns(stringValues).build();
        } else {
            // Convert objects to strings for DynamoDB
            Set<String> stringValues = new HashSet<>();
            for (Object value : valuesToRemove) {
                stringValues.add(value.toString());
            }

            setValue = AttributeValue.builder().ss(stringValues).build();
        }

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("DELETE #setAttr :valuesToRemove")
            .expressionAttributeNames(Map.of("#setAttr", setAttributeName))
            .expressionAttributeValues(Map.of(":valuesToRemove", setValue))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Checks if a value exists in a set attribute.
     *
     * <p>This method demonstrates how to use the contains function to check
     * if a value exists in a set attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to check
     * @param setAttributeName The name of the set attribute
     * @param valueToCheck The value to check for
     * @return Map containing the result of the check
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static Map<String, Object> checkIfValueInSet(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String setAttributeName,
        String valueToCheck) {

        Map<String, Object> result = new HashMap<>();

        try {
            // Define the update parameters with a condition expression
            UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET #tempAttr = :tempVal")
                .conditionExpression("contains(#setAttr, :valueToCheck)")
                .expressionAttributeNames(Map.of("#setAttr", setAttributeName, "#tempAttr", "TempAttribute"))
                .expressionAttributeValues(Map.of(
                    ":valueToCheck", AttributeValue.builder().s(valueToCheck).build(),
                    ":tempVal", AttributeValue.builder().s("TempValue").build()))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            // Attempt the update operation
            dynamoDbClient.updateItem(request);

            // If we get here, the condition was met
            result.put("exists", true);
            result.put("message", "Value '" + valueToCheck + "' exists in the set");

            // Clean up the temporary attribute
            UpdateItemRequest cleanupRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("REMOVE #tempAttr")
                .expressionAttributeNames(Map.of("#tempAttr", "TempAttribute"))
                .build();

            dynamoDbClient.updateItem(cleanupRequest);

        } catch (DynamoDbException e) {
            if (e.getMessage().contains("ConditionalCheckFailed")) {
                // The condition was not met
                result.put("exists", false);
                result.put("message", "Value '" + valueToCheck + "' does not exist in the set");
            } else {
                // Some other error occurred
                result.put("exists", false);
                result.put("message", "Error checking set: " + e.getMessage());
                result.put("error", e.getClass().getSimpleName());
            }
        }

        return result;
    }

    /**
     * Creates a set with multiple values in a single operation.
     *
     * <p>This method demonstrates how to create a set with multiple values
     * in a single update operation.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param setAttributeName The name of the set attribute
     * @param setValues The values to include in the set
     * @param isNumberSet Whether to create a number set (true) or string set (false)
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse createSetWithValues(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String setAttributeName,
        Set<?> setValues,
        boolean isNumberSet) {

        AttributeValue setValue;

        if (isNumberSet) {
            // Convert numbers to strings for DynamoDB
            Set<String> stringValues = new HashSet<>();
            for (Object value : setValues) {
                if (value instanceof Number) {
                    stringValues.add(value.toString());
                } else {
                    throw new IllegalArgumentException("Values must be numbers for a number set");
                }
            }

            setValue = AttributeValue.builder().ns(stringValues).build();
        } else {
            // Convert objects to strings for DynamoDB
            Set<String> stringValues = new HashSet<>();
            for (Object value : setValues) {
                stringValues.add(value.toString());
            }

            setValue = AttributeValue.builder().ss(stringValues).build();
        }

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #setAttr = :setValue")
            .expressionAttributeNames(Map.of("#setAttr", setAttributeName))
            .expressionAttributeValues(Map.of(":setValue", setValue))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Gets the current value of a set attribute.
     *
     * <p>Helper method to retrieve the current value of a set attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to get
     * @param setAttributeName The name of the set attribute
     * @return The set attribute value or null if not found
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static AttributeValue getSetAttribute(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key, String setAttributeName) {

        // Define the get parameters
        GetItemRequest request = GetItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .projectionExpression(setAttributeName)
            .build();

        try {
            // Perform the get operation
            GetItemResponse response = dynamoDbClient.getItem(request);

            // Return the set attribute if it exists, otherwise null
            if (response.item() != null && response.item().containsKey(setAttributeName)) {
                return response.item().get(setAttributeName);
            }

            return null;
        } catch (DynamoDbException e) {
            throw DynamoDbException.builder()
                .message("Failed to get set attribute: " + e.getMessage())
                .cause(e)
                .build();
        }
    }
```
でのセットオペレーションの使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating set operations in DynamoDB");

        try {
            // Example 1: Create a string set with multiple values
            System.out.println("\nExample 1: Creating a string set with multiple values");
            Set<String> tags = new HashSet<>();
            tags.add("Electronics");
            tags.add("Gadget");
            tags.add("Smartphone");

            UpdateItemResponse createResponse = createSetWithValues(
                dynamoDbClient, tableName, key, "Tags", tags, false // Not a number set
                );

            System.out.println("Created set attribute: " + createResponse.attributes());

            // Example 2: Add values to a string set
            System.out.println("\nExample 2: Adding values to a string set");
            Set<String> additionalTags = new HashSet<>();
            additionalTags.add("Mobile");
            additionalTags.add("Wireless");

            UpdateItemResponse addResponse = addToStringSet(dynamoDbClient, tableName, key, "Tags", additionalTags);

            System.out.println("Updated set attribute: " + addResponse.attributes());

            // Example 3: Create a number set with multiple values
            System.out.println("\nExample 3: Creating a number set with multiple values");
            Set<Number> ratings = new HashSet<>();
            ratings.add(4);
            ratings.add(5);
            ratings.add(4.5);

            UpdateItemResponse createNumberSetResponse = createSetWithValues(
                dynamoDbClient, tableName, key, "Ratings", ratings, true // Is a number set
                );

            System.out.println("Created number set attribute: " + createNumberSetResponse.attributes());

            // Example 4: Add values to a number set
            System.out.println("\nExample 4: Adding values to a number set");
            Set<Number> additionalRatings = new HashSet<>();
            additionalRatings.add(3.5);
            additionalRatings.add(4.2);

            UpdateItemResponse addNumberResponse =
                addToNumberSet(dynamoDbClient, tableName, key, "Ratings", additionalRatings);

            System.out.println("Updated number set attribute: " + addNumberResponse.attributes());

            // Example 5: Remove values from a set
            System.out.println("\nExample 5: Removing values from a set");
            Set<String> tagsToRemove = new HashSet<>();
            tagsToRemove.add("Gadget");

            UpdateItemResponse removeResponse = removeFromSet(
                dynamoDbClient, tableName, key, "Tags", tagsToRemove, false // Not a number set
                );

            System.out.println("Updated set after removal: " + removeResponse.attributes());

            // Example 6: Check if a value exists in a set
            System.out.println("\nExample 6: Checking if a value exists in a set");
            Map<String, Object> checkResult = checkIfValueInSet(dynamoDbClient, tableName, key, "Tags", "Electronics");

            System.out.println("Check result: " + checkResult.get("message"));

            // Example 7: Get the current value of a set attribute
            System.out.println("\nExample 7: Getting the current value of a set attribute");
            AttributeValue currentStringSet = getSetAttribute(dynamoDbClient, tableName, key, "Tags");

            if (currentStringSet != null && currentStringSet.ss() != null) {
                System.out.println("Current string set values: " + currentStringSet.ss());
            } else {
                System.out.println("String set attribute not found");
            }

            AttributeValue currentNumberSet = getSetAttribute(dynamoDbClient, tableName, key, "Ratings");

            if (currentNumberSet != null && currentNumberSet.ns() != null) {
                System.out.println("Current number set values: " + currentNumberSet.ns());
            } else {
                System.out.println("Number set attribute not found");
            }

            // Explain set operations
            System.out.println("\nKey points about DynamoDB set operations:");
            System.out.println(
                "1. DynamoDB supports three set types: string sets (SS), number sets (NS), and binary sets (BS)");
            System.out.println("2. Sets can only contain elements of the same type");
            System.out.println("3. Use ADD to add elements to a set");
            System.out.println("4. Use DELETE to remove elements from a set");
            System.out.println("5. Sets automatically remove duplicate values");
            System.out.println("6. Sets are unordered collections");
            System.out.println("7. Use the contains function to check if a value exists in a set");
            System.out.println("8. You can create a set with multiple values in a single operation");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_java_2_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
public class ScenarioPartiQLBatch {
    public static void main(String[] args) throws IOException {
        String tableName = "MoviesPartiQBatch";
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
            .region(region)
            .build();

        System.out.println("Creating an Amazon DynamoDB table named " + tableName
            + " with a key named year and a sort key named title.");
        createTable(ddb, tableName);

        System.out.println("Adding multiple records into the " + tableName
            + " table using a batch command.");
        putRecordBatch(ddb);

        // Update multiple movies by using the BatchExecute statement.
        String title1 = "Star Wars";
        int year1 = 1977;
        String title2 = "Wizard of Oz";
        int year2 = 1939;

        System.out.println("Query two movies.");
        getBatch(ddb, tableName, title1, title2, year1, year2);

        System.out.println("Updating multiple records using a batch command.");
        updateTableItemBatch(ddb);

        System.out.println("Deleting multiple records using a batch command.");
        deleteItemBatch(ddb);

        System.out.println("Deleting the Amazon DynamoDB table.");
        deleteDynamoDBTable(ddb, tableName);
        ddb.close();
    }

    public static boolean getBatch(DynamoDbClient ddb, String tableName, String title1, String title2, int year1, int year2) {
        String getBatch = "SELECT * FROM " + tableName + " WHERE title = ? AND year = ?";

        List<BatchStatementRequest> statements = new ArrayList<>();
        statements.add(BatchStatementRequest.builder()
            .statement(getBatch)
            .parameters(AttributeValue.builder().s(title1).build(),
                AttributeValue.builder().n(String.valueOf(year1)).build())
            .build());
        statements.add(BatchStatementRequest.builder()
            .statement(getBatch)
            .parameters(AttributeValue.builder().s(title2).build(),
                AttributeValue.builder().n(String.valueOf(year2)).build())
            .build());

        BatchExecuteStatementRequest batchExecuteStatementRequest = BatchExecuteStatementRequest.builder()
            .statements(statements)
            .build();

        try {
            BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchExecuteStatementRequest);
            if (!response.responses().isEmpty()) {
                response.responses().forEach(r -> {
                    System.out.println(r.item().get("title") + "\\t" + r.item().get("year"));
                });
                return true;
            } else {
                System.out.println("Couldn't find either " + title1 + " or " + title2 + ".");
                return false;
            }
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            return false;
        }
    }

    public static void createTable(DynamoDbClient ddb, String tableName) {
        DynamoDbWaiter dbWaiter = ddb.waiter();
        ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>();

        // Define attributes.
        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("year")
            .attributeType("N")
            .build());

        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("title")
            .attributeType("S")
            .build());

        ArrayList<KeySchemaElement> tableKey = new ArrayList<>();
        KeySchemaElement key = KeySchemaElement.builder()
            .attributeName("year")
            .keyType(KeyType.HASH)
            .build();

        KeySchemaElement key2 = KeySchemaElement.builder()
            .attributeName("title")
            .keyType(KeyType.RANGE) // Sort
            .build();

        // Add KeySchemaElement objects to the list.
        tableKey.add(key);
        tableKey.add(key2);

        CreateTableRequest request = CreateTableRequest.builder()
            .keySchema(tableKey)
            .billingMode(BillingMode.PAY_PER_REQUEST) //  DynamoDB automatically scales based on traffic.
            .attributeDefinitions(attributeDefinitions)
            .tableName(tableName)
            .build();

        try {
            CreateTableResponse response = ddb.createTable(request);
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                .tableName(tableName)
                .build();

            // Wait until the Amazon DynamoDB table is created.
            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter
                .waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            String newTable = response.tableDescription().tableName();
            System.out.println("The " + newTable + " was successfully created.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void putRecordBatch(DynamoDbClient ddb) {
        String sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}";
        try {
            // Create three movies to add to the Amazon DynamoDB table.
            // Set data for Movie 1.
            List<AttributeValue> parameters = new ArrayList<>();

            AttributeValue att1 = AttributeValue.builder()
                .n("1977")
                .build();

            AttributeValue att2 = AttributeValue.builder()
                .s("Star Wars")
                .build();

            AttributeValue att3 = AttributeValue.builder()
                .s("No Information")
                .build();

            parameters.add(att1);
            parameters.add(att2);
            parameters.add(att3);

            BatchStatementRequest statementRequestMovie1 = BatchStatementRequest.builder()
                .statement(sqlStatement)
                .parameters(parameters)
                .build();

            // Set data for Movie 2.
            List<AttributeValue> parametersMovie2 = new ArrayList<>();
            AttributeValue attMovie2 = AttributeValue.builder()
                .n("1939")
                .build();

            AttributeValue attMovie2A = AttributeValue.builder()
                .s("Wizard of Oz")
                .build();

            AttributeValue attMovie2B = AttributeValue.builder()
                .s("No Information")
                .build();

            parametersMovie2.add(attMovie2);
            parametersMovie2.add(attMovie2A);
            parametersMovie2.add(attMovie2B);

            BatchStatementRequest statementRequestMovie2 = BatchStatementRequest.builder()
                .statement(sqlStatement)
                .parameters(parametersMovie2)
                .build();

            // Set data for Movie 3.
            List<AttributeValue> parametersMovie3 = new ArrayList<>();
            AttributeValue attMovie3 = AttributeValue.builder()
                .n(String.valueOf("2022"))
                .build();

            AttributeValue attMovie3A = AttributeValue.builder()
                .s("My Movie 3")
                .build();

            AttributeValue attMovie3B = AttributeValue.builder()
                .s("No Information")
                .build();

            parametersMovie3.add(attMovie3);
            parametersMovie3.add(attMovie3A);
            parametersMovie3.add(attMovie3B);

            BatchStatementRequest statementRequestMovie3 = BatchStatementRequest.builder()
                .statement(sqlStatement)
                .parameters(parametersMovie3)
                .build();

            // Add all three movies to the list.
            List<BatchStatementRequest> myBatchStatementList = new ArrayList<>();
            myBatchStatementList.add(statementRequestMovie1);
            myBatchStatementList.add(statementRequestMovie2);
            myBatchStatementList.add(statementRequestMovie3);

            BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder()
                .statements(myBatchStatementList)
                .build();

            BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest);
            System.out.println("ExecuteStatement successful: " + response.toString());
            System.out.println("Added new movies using a batch command.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void updateTableItemBatch(DynamoDbClient ddb) {
        String sqlStatement = "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?";
        List<AttributeValue> parametersRec1 = new ArrayList<>();

        // Update three records.
        AttributeValue att1 = AttributeValue.builder()
            .n(String.valueOf("2022"))
            .build();

        AttributeValue att2 = AttributeValue.builder()
            .s("My Movie 1")
            .build();

        parametersRec1.add(att1);
        parametersRec1.add(att2);

        BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder()
            .statement(sqlStatement)
            .parameters(parametersRec1)
            .build();

        // Update record 2.
        List<AttributeValue> parametersRec2 = new ArrayList<>();
        AttributeValue attRec2 = AttributeValue.builder()
            .n(String.valueOf("2022"))
            .build();

        AttributeValue attRec2a = AttributeValue.builder()
            .s("My Movie 2")
            .build();

        parametersRec2.add(attRec2);
        parametersRec2.add(attRec2a);
        BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder()
            .statement(sqlStatement)
            .parameters(parametersRec2)
            .build();

        // Update record 3.
        List<AttributeValue> parametersRec3 = new ArrayList<>();
        AttributeValue attRec3 = AttributeValue.builder()
            .n(String.valueOf("2022"))
            .build();

        AttributeValue attRec3a = AttributeValue.builder()
            .s("My Movie 3")
            .build();

        parametersRec3.add(attRec3);
        parametersRec3.add(attRec3a);
        BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder()
            .statement(sqlStatement)
            .parameters(parametersRec3)
            .build();

        // Add all three movies to the list.
        List<BatchStatementRequest> myBatchStatementList = new ArrayList<>();
        myBatchStatementList.add(statementRequestRec1);
        myBatchStatementList.add(statementRequestRec2);
        myBatchStatementList.add(statementRequestRec3);

        BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder()
            .statements(myBatchStatementList)
            .build();

        try {
            BatchExecuteStatementResponse response = ddb.batchExecuteStatement(batchRequest);
            System.out.println("ExecuteStatement successful: " + response.toString());
            System.out.println("Updated three movies using a batch command.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("Item was updated!");
    }

    public static void deleteItemBatch(DynamoDbClient ddb) {
        String sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?";
        List<AttributeValue> parametersRec1 = new ArrayList<>();

        // Specify three records to delete.
        AttributeValue att1 = AttributeValue.builder()
            .n(String.valueOf("2022"))
            .build();

        AttributeValue att2 = AttributeValue.builder()
            .s("My Movie 1")
            .build();

        parametersRec1.add(att1);
        parametersRec1.add(att2);

        BatchStatementRequest statementRequestRec1 = BatchStatementRequest.builder()
            .statement(sqlStatement)
            .parameters(parametersRec1)
            .build();

        // Specify record 2.
        List<AttributeValue> parametersRec2 = new ArrayList<>();
        AttributeValue attRec2 = AttributeValue.builder()
            .n(String.valueOf("2022"))
            .build();

        AttributeValue attRec2a = AttributeValue.builder()
            .s("My Movie 2")
            .build();

        parametersRec2.add(attRec2);
        parametersRec2.add(attRec2a);
        BatchStatementRequest statementRequestRec2 = BatchStatementRequest.builder()
            .statement(sqlStatement)
            .parameters(parametersRec2)
            .build();

        // Specify record 3.
        List<AttributeValue> parametersRec3 = new ArrayList<>();
        AttributeValue attRec3 = AttributeValue.builder()
            .n(String.valueOf("2022"))
            .build();

        AttributeValue attRec3a = AttributeValue.builder()
            .s("My Movie 3")
            .build();

        parametersRec3.add(attRec3);
        parametersRec3.add(attRec3a);

        BatchStatementRequest statementRequestRec3 = BatchStatementRequest.builder()
            .statement(sqlStatement)
            .parameters(parametersRec3)
            .build();

        // Add all three movies to the list.
        List<BatchStatementRequest> myBatchStatementList = new ArrayList<>();
        myBatchStatementList.add(statementRequestRec1);
        myBatchStatementList.add(statementRequestRec2);
        myBatchStatementList.add(statementRequestRec3);

        BatchExecuteStatementRequest batchRequest = BatchExecuteStatementRequest.builder()
            .statements(myBatchStatementList)
            .build();

        try {
            ddb.batchExecuteStatement(batchRequest);
            System.out.println("Deleted three movies using a batch command.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {
        DeleteTableRequest request = DeleteTableRequest.builder()
            .tableName(tableName)
            .build();

        try {
            ddb.deleteTable(request);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println(tableName + " was successfully deleted!");
    }

    private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement,
                                                                    List<AttributeValue> parameters) {
        ExecuteStatementRequest request = ExecuteStatementRequest.builder()
            .statement(statement)
            .parameters(parameters)
            .build();

        return ddb.executeStatement(request);
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」**の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_java_2_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
public class ScenarioPartiQ {
    public static void main(String[] args) throws IOException {
        String fileName = "../../../resources/sample_files/movies.json";
        String tableName = "MoviesPartiQ";
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
            .region(region)
            .build();

        System.out.println(
            "******* Creating an Amazon DynamoDB table named MoviesPartiQ with a key named year and a sort key named title.");
        createTable(ddb, tableName);

        System.out.println("Loading data into the MoviesPartiQ table.");
        loadData(ddb, fileName);

        System.out.println("Getting data from the MoviesPartiQ table.");
        getItem(ddb);

        System.out.println("Putting a record into the MoviesPartiQ table.");
        putRecord(ddb);

        System.out.println("Updating a record.");
        updateTableItem(ddb);

        System.out.println("Querying the movies released in 2013.");
        queryTable(ddb);

        System.out.println("Deleting the Amazon DynamoDB table.");
        deleteDynamoDBTable(ddb, tableName);
        ddb.close();
    }

    public static void createTable(DynamoDbClient ddb, String tableName) {
        DynamoDbWaiter dbWaiter = ddb.waiter();
        ArrayList<AttributeDefinition> attributeDefinitions = new ArrayList<>();

        // Define attributes.
        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("year")
            .attributeType("N")
            .build());

        attributeDefinitions.add(AttributeDefinition.builder()
            .attributeName("title")
            .attributeType("S")
            .build());

        ArrayList<KeySchemaElement> tableKey = new ArrayList<>();
        KeySchemaElement key = KeySchemaElement.builder()
            .attributeName("year")
            .keyType(KeyType.HASH)
            .build();

        KeySchemaElement key2 = KeySchemaElement.builder()
            .attributeName("title")
            .keyType(KeyType.RANGE) // Sort
            .build();

        // Add KeySchemaElement objects to the list.
        tableKey.add(key);
        tableKey.add(key2);

        CreateTableRequest request = CreateTableRequest.builder()
            .keySchema(tableKey)
            .billingMode(BillingMode.PAY_PER_REQUEST) //Scales based on traffic.
            .attributeDefinitions(attributeDefinitions)
            .tableName(tableName)
            .build();

        try {
            CreateTableResponse response = ddb.createTable(request);
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                .tableName(tableName)
                .build();

            // Wait until the Amazon DynamoDB table is created.
            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            String newTable = response.tableDescription().tableName();
            System.out.println("The " + newTable + " was successfully created.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    // Load data into the table.
    public static void loadData(DynamoDbClient ddb, String fileName) throws IOException {

        String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}";
        JsonParser parser = new JsonFactory().createParser(new File(fileName));
        com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
        Iterator<JsonNode> iter = rootNode.iterator();
        ObjectNode currentNode;
        int t = 0;
        List<AttributeValue> parameters = new ArrayList<>();
        while (iter.hasNext()) {

            // Add 200 movies to the table.
            if (t == 200)
                break;
            currentNode = (ObjectNode) iter.next();

            int year = currentNode.path("year").asInt();
            String title = currentNode.path("title").asText();
            String info = currentNode.path("info").toString();

            AttributeValue att1 = AttributeValue.builder()
                .n(String.valueOf(year))
                .build();

            AttributeValue att2 = AttributeValue.builder()
                .s(title)
                .build();

            AttributeValue att3 = AttributeValue.builder()
                .s(info)
                .build();

            parameters.add(att1);
            parameters.add(att2);
            parameters.add(att3);

            // Insert the movie into the Amazon DynamoDB table.
            executeStatementRequest(ddb, sqlStatement, parameters);
            System.out.println("Added Movie " + title);

            parameters.remove(att1);
            parameters.remove(att2);
            parameters.remove(att3);
            t++;
        }
    }

    public static void getItem(DynamoDbClient ddb) {

        String sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?";
        List<AttributeValue> parameters = new ArrayList<>();
        AttributeValue att1 = AttributeValue.builder()
            .n("2012")
            .build();

        AttributeValue att2 = AttributeValue.builder()
            .s("The Perks of Being a Wallflower")
            .build();

        parameters.add(att1);
        parameters.add(att2);

        try {
            ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters);
            System.out.println("ExecuteStatement successful: " + response.toString());

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void putRecord(DynamoDbClient ddb) {

        String sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}";
        try {
            List<AttributeValue> parameters = new ArrayList<>();

            AttributeValue att1 = AttributeValue.builder()
                .n(String.valueOf("2020"))
                .build();

            AttributeValue att2 = AttributeValue.builder()
                .s("My Movie")
                .build();

            AttributeValue att3 = AttributeValue.builder()
                .s("No Information")
                .build();

            parameters.add(att1);
            parameters.add(att2);
            parameters.add(att3);

            executeStatementRequest(ddb, sqlStatement, parameters);
            System.out.println("Added new movie.");

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void updateTableItem(DynamoDbClient ddb) {

        String sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?";
        List<AttributeValue> parameters = new ArrayList<>();
        AttributeValue att1 = AttributeValue.builder()
            .n(String.valueOf("2013"))
            .build();

        AttributeValue att2 = AttributeValue.builder()
            .s("The East")
            .build();

        parameters.add(att1);
        parameters.add(att2);

        try {
            executeStatementRequest(ddb, sqlStatement, parameters);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("Item was updated!");
    }

    // Query the table where the year is 2013.
    public static void queryTable(DynamoDbClient ddb) {
        String sqlStatement = "SELECT * FROM MoviesPartiQ where year = ? ORDER BY year";
        try {

            List<AttributeValue> parameters = new ArrayList<>();
            AttributeValue att1 = AttributeValue.builder()
                .n(String.valueOf("2013"))
                .build();
            parameters.add(att1);

            // Get items in the table and write out the ID value.
            ExecuteStatementResponse response = executeStatementRequest(ddb, sqlStatement, parameters);
            System.out.println("ExecuteStatement successful: " + response.toString());

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void deleteDynamoDBTable(DynamoDbClient ddb, String tableName) {

        DeleteTableRequest request = DeleteTableRequest.builder()
            .tableName(tableName)
            .build();

        try {
            ddb.deleteTable(request);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println(tableName + " was successfully deleted!");
    }

    private static ExecuteStatementResponse executeStatementRequest(DynamoDbClient ddb, String statement,
                                                                    List<AttributeValue> parameters) {
        ExecuteStatementRequest request = ExecuteStatementRequest.builder()
            .statement(statement)
            .parameters(parameters)
            .build();

        return ddb.executeStatement(request);
    }

    private static void processResults(ExecuteStatementResponse executeStatementResult) {
        System.out.println("ExecuteStatement successful: " + executeStatementResult.toString());
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### グローバルセカンダリインデックスを使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithGlobalSecondaryIndex_java_2_topic"></a>

以下のコード例は、グローバルセカンダリインデックスを使用してテーブルをクエリする方法を示しています。
+ プライマリキーを使用して DynamoDB テーブルをクエリします。
+ 代替アクセスパターンのグローバルセカンダリインデックス (GSI) をクエリします。
+ テーブルクエリと GSI クエリを比較します。

**SDK for Java 2.x**  
プライマリキーと グローバルセカンダリインデックス (GSI) を使用して DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;

    public QueryResponse queryTable(
        final String tableName, final String partitionKeyName, final String partitionKeyValue) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            System.out.println("Query on base table successful. Found " + response.count() + " items");
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            throw new DynamoDbQueryException("Table not found: " + tableName, e);
        } catch (DynamoDbException e) {
            System.err.println("Error querying base table: " + e.getMessage());
            throw new DynamoDbQueryException("Failed to execute query on base table", e);
        }
    }

    /**
     * Queries a DynamoDB Global Secondary Index (GSI) by partition key.
     *
     * @param tableName         The name of the DynamoDB table
     * @param indexName         The name of the GSI
     * @param partitionKeyName  The name of the GSI partition key attribute
     * @param partitionKeyValue The value of the GSI partition key to query
     * @return The query response from DynamoDB
     * @throws ResourceNotFoundException if the table or index doesn't exist
     * @throws DynamoDbException if the query fails
     */
    public QueryResponse queryGlobalSecondaryIndex(
        final String tableName, final String indexName, final String partitionKeyName, final String partitionKeyValue) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Index name", indexName);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_IK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_IK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .indexName(indexName)
            .keyConditionExpression(GSI_KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            System.out.println("Query on GSI successful. Found " + response.count() + " items");
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format(
                "Error: The Amazon DynamoDB table \"%s\" or index \"%s\" can't be found.\n", tableName, indexName);
            throw new DynamoDbQueryException("Table or index not found: " + tableName + "/" + indexName, e);
        } catch (DynamoDbException e) {
            System.err.println("Error querying GSI: " + e.getMessage());
            throw new DynamoDbQueryException("Failed to execute query on GSI", e);
        }
    }
```
テーブルの直接クエリと GSI のクエリを比較します AWS SDK for Java 2.x。  

```
    public static void main(String[] args) {
        final String usage =
            """
                Usage:
                    <tableName> <basePartitionKeyName> <basePartitionKeyValue> <gsiName> <gsiPartitionKeyName> <gsiPartitionKeyValue> [region]
                Where:
                    tableName - The Amazon DynamoDB table to query.
                    basePartitionKeyName - The name of the base table partition key attribute.
                    basePartitionKeyValue - The value of the base table partition key to query.
                    gsiName - The name of the Global Secondary Index.
                    gsiPartitionKeyName - The name of the GSI partition key attribute.
                    gsiPartitionKeyValue - The value of the GSI partition key to query.
                    region (optional) - The AWS region where the table exists. (Default: us-east-1)
                """;

        if (args.length < 6) {
            System.out.println(usage);
            System.exit(1);
        }

        final String tableName = args[0];
        final String basePartitionKeyName = args[1];
        final String basePartitionKeyValue = args[2];
        final String gsiName = args[3];
        final String gsiPartitionKeyName = args[4];
        final String gsiPartitionKeyValue = args[5];
        final Region region = args.length > 6 ? Region.of(args[6]) : Region.US_EAST_1;

        try (DynamoDbClient ddb = DynamoDbClient.builder().region(region).build()) {
            final QueryTableAndGSI queryHelper = new QueryTableAndGSI(ddb);

            // Query the base table
            System.out.println("Querying base table where " + basePartitionKeyName + " = " + basePartitionKeyValue);
            final QueryResponse tableResponse =
                queryHelper.queryTable(tableName, basePartitionKeyName, basePartitionKeyValue);

            System.out.println("Found " + tableResponse.count() + " items in base table:");
            tableResponse.items().forEach(item -> System.out.println(item));

            // Query the GSI
            System.out.println(
                "\nQuerying GSI '" + gsiName + "' where " + gsiPartitionKeyName + " = " + gsiPartitionKeyValue);
            final QueryResponse gsiResponse =
                queryHelper.queryGlobalSecondaryIndex(tableName, gsiName, gsiPartitionKeyName, gsiPartitionKeyValue);

            System.out.println("Found " + gsiResponse.count() + " items in GSI:");
            gsiResponse.items().forEach(item -> System.out.println(item));

            // Explain the differences between querying a table and a GSI
            System.out.println("\nKey differences between querying a table and a GSI:");
            System.out.println("1. When querying a GSI, you must specify the indexName parameter");
            System.out.println("2. GSIs may not contain all attributes from the base table (projection)");
            System.out.println("3. GSIs consume read capacity units from the GSI's capacity, not the base table's");
            System.out.println("4. GSIs may have eventually consistent data (cannot use ConsistentRead=true)");

        } catch (IllegalArgumentException e) {
            System.err.println("Invalid input: " + e.getMessage());
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            System.err.println("Table or index not found: " + e.getMessage());
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println("DynamoDB error: " + e.getMessage());
            System.exit(1);
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### begins\$1with 条件を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithBeginsWithCondition_java_2_topic"></a>

以下のコード例は、begins\$1with 条件を使用してテーブルをクエリする方法を示しています。
+ キー条件式で begins\$1with 関数を使用します。
+ ソートキーのプレフィックスパターンに基づいて項目をフィルタリングします。

**SDK for Java 2.x**  
 AWS SDK for Java 2.xでソートキーの begins\$1with 条件を使用して DynamoDB テーブルをクエリします。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithBeginsWithCondition(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String sortKeyName,
        final String sortKeyPrefix) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Sort key name", sortKeyName);
        CodeSampleUtils.validateStringParameter("Sort key prefix", sortKeyPrefix);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_SK, sortKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_SK_PREFIX,
            AttributeValue.builder().s(sortKeyPrefix).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            LOGGER.log(Level.INFO, "Query with begins_with condition successful. Found {0} items", response.count());
            return response;
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", tableName);
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "Error querying with begins_with condition", e);
            throw e;
        }
    }
```
 AWS SDK for Java 2.xでプレフィックス長が異なる begins\$1with の使用を示します。  

```
    public static void main(String[] args) {
        try {
            CodeSampleUtils.BeginsWithQueryConfig config = CodeSampleUtils.BeginsWithQueryConfig.fromArgs(args);
            LOGGER.log(Level.INFO, "Querying items where {0} = {1} and {2} begins with ''{3}''", new Object[] {
                config.getPartitionKeyName(),
                config.getPartitionKeyValue(),
                config.getSortKeyName(),
                config.getSortKeyPrefix()
            });

            // Using the builder pattern to create and execute the query
            final QueryResponse response = new BeginsWithQueryBuilder()
                .withTableName(config.getTableName())
                .withPartitionKeyName(config.getPartitionKeyName())
                .withPartitionKeyValue(config.getPartitionKeyValue())
                .withSortKeyName(config.getSortKeyName())
                .withSortKeyPrefix(config.getSortKeyPrefix())
                .withRegion(config.getRegion())
                .execute();

            // Process the results
            LOGGER.log(Level.INFO, "Found {0} items:", response.count());
            response.items().forEach(item -> LOGGER.info(item.toString()));

            // Demonstrate with a different prefix
            if (!config.getSortKeyPrefix().isEmpty()) {
                String shorterPrefix = config.getSortKeyPrefix()
                    .substring(0, Math.max(1, config.getSortKeyPrefix().length() / 2));
                LOGGER.log(Level.INFO, "\nNow querying with a shorter prefix: ''{0}''", shorterPrefix);

                final QueryResponse response2 = new BeginsWithQueryBuilder()
                    .withTableName(config.getTableName())
                    .withPartitionKeyName(config.getPartitionKeyName())
                    .withPartitionKeyValue(config.getPartitionKeyValue())
                    .withSortKeyName(config.getSortKeyName())
                    .withSortKeyPrefix(shorterPrefix)
                    .withRegion(config.getRegion())
                    .execute();

                LOGGER.log(Level.INFO, "Found {0} items with shorter prefix:", response2.count());
                response2.items().forEach(item -> LOGGER.info(item.toString()));
            }
        } catch (IllegalArgumentException e) {
            LOGGER.log(Level.SEVERE, "Invalid input: {0}", e.getMessage());
            printUsage();
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found", e);
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "DynamoDB error", e);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Unexpected error", e);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### 日付範囲を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithDateRange_java_2_topic"></a>

以下のコード例は、ソートキーの日付範囲を使用してテーブルをクエリする方法を示しています。
+ 特定の日付範囲内の項目をクエリします。
+ 日付形式のソートキーで比較演算子を使用します。

**SDK for Java 2.x**  
を使用して、日付範囲内の項目について DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithDateRange(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String dateKeyName,
        final LocalDate startDate,
        final LocalDate endDate) {

        // Focus on query logic, assuming parameters are valid
        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("Start date and end date cannot be null");
        }

        if (endDate.isBefore(startDate)) {
            throw new IllegalArgumentException("End date must be after start date");
        }

        // Format dates as ISO strings for DynamoDB (using just the date part)
        final String formattedStartDate = startDate.toString();
        final String formattedEndDate = endDate.toString();

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_SK, dateKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_START_DATE,
            AttributeValue.builder().s(formattedStartDate).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_END_DATE,
            AttributeValue.builder().s(formattedEndDate).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            LOGGER.log(Level.INFO, "Query by date range successful. Found {0} items", response.count());
            return response;
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", tableName);
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "Error querying by date range: {0}", e.getMessage());
            throw e;
        }
    }
```
日付範囲フィルタリングを使用して DynamoDB テーブルをクエリする方法を示します。  

```
    public static void main(String[] args) {
        final String usage =
            """
                Usage:
                    <tableName> <partitionKeyName> <partitionKeyValue> <dateKeyName> <startDate> <endDate> [region]
                Where:
                    tableName - The Amazon DynamoDB table to query.
                    partitionKeyName - The name of the partition key attribute.
                    partitionKeyValue - The value of the partition key to query.
                    dateKeyName - The name of the date attribute to filter on.
                    startDate - The start date for the range query (YYYY-MM-DD).
                    endDate - The end date for the range query (YYYY-MM-DD).
                    region (optional) - The AWS region where the table exists. (Default: us-east-1)
                """;

        if (args.length < 6) {
            System.out.println(usage);
            System.exit(1);
        }

        try {
            // Parse command line arguments into a config object
            CodeSampleUtils.DateRangeQueryConfig config = CodeSampleUtils.DateRangeQueryConfig.fromArgs(args);

            LOGGER.log(
                Level.INFO, "Querying items from {0} to {1}", new Object[] {config.getStartDate(), config.getEndDate()
                });

            // Using the builder pattern to create and execute the query
            final QueryResponse response = new DateRangeQueryBuilder()
                .withTableName(config.getTableName())
                .withPartitionKeyName(config.getPartitionKeyName())
                .withPartitionKeyValue(config.getPartitionKeyValue())
                .withDateKeyName(config.getDateKeyName())
                .withStartDate(config.getStartDate())
                .withEndDate(config.getEndDate())
                .withRegion(config.getRegion())
                .execute();

            // Process the results
            LOGGER.log(Level.INFO, "Found {0} items:", response.count());
            response.items().forEach(item -> {
                LOGGER.info(item.toString());

                // Extract and display the date attribute for clarity
                if (item.containsKey(config.getDateKeyName())) {
                    LOGGER.log(
                        Level.INFO,
                        "  Date attribute: {0}",
                        item.get(config.getDateKeyName()).s());
                }
            });

            // Demonstrate with a different date range
            LocalDate narrowerStartDate = config.getStartDate().plusDays(1);
            LocalDate narrowerEndDate = config.getEndDate().minusDays(1);

            if (!narrowerStartDate.isAfter(narrowerEndDate)) {
                LOGGER.log(Level.INFO, "\nNow querying with a narrower date range: {0} to {1}", new Object[] {
                    narrowerStartDate, narrowerEndDate
                });

                final QueryResponse response2 = new DateRangeQueryBuilder()
                    .withTableName(config.getTableName())
                    .withPartitionKeyName(config.getPartitionKeyName())
                    .withPartitionKeyValue(config.getPartitionKeyValue())
                    .withDateKeyName(config.getDateKeyName())
                    .withStartDate(narrowerStartDate)
                    .withEndDate(narrowerEndDate)
                    .withRegion(config.getRegion())
                    .execute();

                LOGGER.log(Level.INFO, "Found {0} items with narrower date range:", response2.count());
                response2.items().forEach(item -> LOGGER.info(item.toString()));
            }

            LOGGER.info("\nNote: When storing dates in DynamoDB:");
            LOGGER.info("1. Use ISO format (YYYY-MM-DD) for lexicographical ordering");
            LOGGER.info("2. Use the BETWEEN operator for inclusive date range queries");
            LOGGER.info("3. Consider using ISO-8601 format for timestamps with time components");

        } catch (IllegalArgumentException e) {
            LOGGER.log(Level.SEVERE, "Invalid input: {0}", e.getMessage());
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", e.getMessage());
            System.exit(1);
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "DynamoDB error: {0}", e.getMessage());
            System.exit(1);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Unexpected error: {0}", e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### 複雑なフィルター式を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithComplexFilter_java_2_topic"></a>

次のコード例は、複雑なフィルター式を使用してテーブルをクエリする方法を示しています。
+ 複雑なフィルター式をクエリ結果に適用します。
+ 論理演算子を使用して複数の条件を組み合わせます。
+ キー以外の属性に基づいて項目をフィルタリングします。

**SDK for Java 2.x**  
を使用して、複雑なフィルター式で DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithComplexFilter(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String statusAttrName,
        final String activeStatus,
        final String pendingStatus,
        final String priceAttrName,
        final double minPrice,
        final double maxPrice,
        final String categoryAttrName) {

        // Validate parameters
        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Status attribute name", statusAttrName);
        CodeSampleUtils.validateStringParameter("Active status", activeStatus);
        CodeSampleUtils.validateStringParameter("Pending status", pendingStatus);
        CodeSampleUtils.validateStringParameter("Price attribute name", priceAttrName);
        CodeSampleUtils.validateStringParameter("Category attribute name", categoryAttrName);
        CodeSampleUtils.validateNumericRange("Minimum price", minPrice, 0.0, Double.MAX_VALUE);
        CodeSampleUtils.validateNumericRange("Maximum price", maxPrice, minPrice, Double.MAX_VALUE);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put("#pk", partitionKeyName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_STATUS, statusAttrName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PRICE, priceAttrName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_CATEGORY, categoryAttrName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            ":pkValue", AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_ACTIVE,
            AttributeValue.builder().s(activeStatus).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PENDING,
            AttributeValue.builder().s(pendingStatus).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_MIN_PRICE,
            AttributeValue.builder().n(String.valueOf(minPrice)).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_MAX_PRICE,
            AttributeValue.builder().n(String.valueOf(maxPrice)).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .filterExpression(FILTER_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        return dynamoDbClient.query(queryRequest);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### 動的フィルター式を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithDynamicFilter_java_2_topic"></a>

以下のコード例は、動的フィルター式を使用してテーブルをクエリする方法を示しています。
+ ランタイムにフィルター式を動的に構築します。
+ ユーザー入力またはアプリケーション状態に基づいてフィルター条件を構築します。
+ 条件付きでフィルター条件を追加または削除します。

**SDK for Java 2.x**  
を使用して動的に構築されたフィルター式で DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;

    public static QueryResponse queryWithDynamicFilter(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final Map<String, Object> filterCriteria,
        final Region region,
        final DynamoDbClient dynamoDbClient) {

        validateParameters(tableName, partitionKeyName, partitionKeyValue, filterCriteria);

        DynamoDbClient ddbClient = dynamoDbClient;
        boolean shouldClose = false;

        try {
            if (ddbClient == null) {
                ddbClient = createClient(region);
                shouldClose = true;
            }

            final QueryWithDynamicFilter queryHelper = new QueryWithDynamicFilter(ddbClient);
            return queryHelper.queryWithDynamicFilter(tableName, partitionKeyName, partitionKeyValue, filterCriteria);
        } catch (ResourceNotFoundException e) {
            System.err.println("Table not found: " + tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println("Failed to execute dynamic filter query: " + e.getMessage());
            throw e;
        } catch (Exception e) {
            System.err.println("Unexpected error during query: " + e.getMessage());
            throw e;
        } finally {
            if (shouldClose && ddbClient != null) {
                ddbClient.close();
            }
        }
    }
```
で動的フィルター式を使用する方法を示します AWS SDK for Java 2.x。  

```
    public static void main(String[] args) {
        final String usage =
            """
                Usage:
                    <tableName> <partitionKeyName> <partitionKeyValue> <filterAttrName> <filterAttrValue> [region]
                Where:
                    tableName - The Amazon DynamoDB table to query.
                    partitionKeyName - The name of the partition key attribute.
                    partitionKeyValue - The value of the partition key to query.
                    filterAttrName - The name of the attribute to filter on.
                    filterAttrValue - The value to filter by.
                    region (optional) - The AWS region where the table exists. (Default: us-east-1)
                """;

        if (args.length < 5) {
            System.out.println(usage);
            System.exit(1);
        }

        final String tableName = args[0];
        final String partitionKeyName = args[1];
        final String partitionKeyValue = args[2];
        final String filterAttrName = args[3];
        final String filterAttrValue = args[4];
        final Region region = args.length > 5 ? Region.of(args[5]) : Region.US_EAST_1;

        System.out.println("Querying items with dynamic filter: " + filterAttrName + " = " + filterAttrValue);

        try {
            // Using the builder pattern to create and execute the query
            final QueryResponse response = new DynamicFilterQueryBuilder()
                .withTableName(tableName)
                .withPartitionKeyName(partitionKeyName)
                .withPartitionKeyValue(partitionKeyValue)
                .withFilterCriterion(filterAttrName, filterAttrValue)
                .withRegion(region)
                .execute();

            // Process the results
            System.out.println("Found " + response.count() + " items:");
            response.items().forEach(item -> System.out.println(item));

            // Demonstrate multiple filter criteria
            System.out.println("\nNow querying with multiple filter criteria:");

            Map<String, Object> multipleFilters = new HashMap<>();
            multipleFilters.put(filterAttrName, filterAttrValue);
            multipleFilters.put("status", "active");

            final QueryResponse multiFilterResponse = new DynamicFilterQueryBuilder()
                .withTableName(tableName)
                .withPartitionKeyName(partitionKeyName)
                .withPartitionKeyValue(partitionKeyValue)
                .withFilterCriteria(multipleFilters)
                .withRegion(region)
                .execute();

            System.out.println("Found " + multiFilterResponse.count() + " items with multiple filters:");
            multiFilterResponse.items().forEach(item -> System.out.println(item));

        } catch (IllegalArgumentException e) {
            System.err.println("Invalid input: " + e.getMessage());
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            System.err.println("Table not found: " + tableName);
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println("DynamoDB error: " + e.getMessage());
            System.exit(1);
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。**

### フィルター式と制限を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithFilterAndLimit_java_2_topic"></a>

以下のコード例は、フィルター式と制限を使用してテーブルをクエリする方法を示しています。
+ 評価対象項目を制限してクエリ結果にフィルター式を適用します。
+ フィルタリングされたクエリ結果に制限がどのように影響するかを理解します。
+ クエリで処理される項目の最大数を制御します。

**SDK for Java 2.x**  
を使用して、フィルター式と制限を使用して DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithFilterAndLimit(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String filterAttrName,
        final String filterAttrValue,
        final int limit) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Filter attribute name", filterAttrName);
        CodeSampleUtils.validateStringParameter("Filter attribute value", filterAttrValue);
        CodeSampleUtils.validatePositiveInteger("Limit", limit);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_FILTER, filterAttrName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_FILTER,
            AttributeValue.builder().s(filterAttrValue).build());

        // Create the filter expression
        final String filterExpression = "#filterAttr = :filterValue";

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .filterExpression(filterExpression)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .limit(limit)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            LOGGER.log(Level.INFO, "Query with filter and limit successful. Found {0} items", response.count());
            LOGGER.log(
                Level.INFO, "ScannedCount: {0} (total items evaluated before filtering)", response.scannedCount());
            return response;
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", tableName);
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "Error querying with filter and limit: {0}", e.getMessage());
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### ネストされた属性を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithNestedAttributes_java_2_topic"></a>

以下のコード例は、ネストされた属性を使用してテーブルをクエリする方法を示しています。
+ DynamoDB 項目のネストされた属性を使用してアクセスおよびフィルタリングします。
+ ネストされた要素を参照するには、ドキュメントパス式を使用します。

**SDK for Java 2.x**  
を使用して、ネストされた属性を持つ DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;

    public QueryResponse queryWithNestedAttributes(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String nestedPath,
        final String nestedAttr,
        final String nestedValue) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Nested path", nestedPath);
        CodeSampleUtils.validateStringParameter("Nested attribute", nestedAttr);
        CodeSampleUtils.validateStringParameter("Nested value", nestedValue);

        // Split the nested path into components
        final String[] pathComponents = nestedPath.split("\\.");

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);

        // Build the nested attribute reference using document path notation
        final StringBuilder nestedAttributeRef = new StringBuilder();
        for (int i = 0; i < pathComponents.length; i++) {
            final String aliasName = "#n" + i;
            expressionAttributeNames.put(aliasName, pathComponents[i]);

            if (i > 0) {
                nestedAttributeRef.append(".");
            }
            nestedAttributeRef.append(aliasName);
        }

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_NESTED,
            AttributeValue.builder().s(nestedValue).build());

        // Create the filter expression using the nested attribute reference
        final String filterExpression = nestedAttributeRef + " = :nestedValue";

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .filterExpression(filterExpression)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            System.out.println("Query with nested attribute filter successful. Found " + response.count() + " items");
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println("Error querying with nested attribute filter: " + e.getMessage());
            throw e;
        }
    }
```
ネストされた属性を使用して DynamoDB テーブルをクエリする方法を示します。  

```
    public static void main(String[] args) {
        final String usage =
            """
                Usage:
                    <tableName> <partitionKeyName> <partitionKeyValue> <nestedPath> <nestedAttr> <nestedValue> [region]
                Where:
                    tableName - The Amazon DynamoDB table to query.
                    partitionKeyName - The name of the partition key attribute.
                    partitionKeyValue - The value of the partition key to query.
                    nestedPath - The path to the nested map attribute (e.g., "address").
                    nestedAttr - The name of the nested attribute (e.g., "city").
                    nestedValue - The value to filter by (e.g., "Seattle").
                    region (optional) - The AWS region where the table exists. (Default: us-east-1)
                """;

        if (args.length < 6) {
            System.out.println(usage);
            System.exit(1);
        }

        final String tableName = args[0];
        final String partitionKeyName = args[1];
        final String partitionKeyValue = args[2];
        final String nestedPath = args[3];
        final String nestedAttr = args[4];
        final String nestedValue = args[5];
        final Region region = args.length > 6 ? Region.of(args[6]) : Region.US_EAST_1;

        System.out.println("Querying items where " + partitionKeyName + " = " + partitionKeyValue + " and " + nestedPath
            + "." + nestedAttr + " = " + nestedValue);

        try {
            // Using the builder pattern to create and execute the query
            final QueryResponse response = new NestedAttributeQueryBuilder()
                .withTableName(tableName)
                .withPartitionKeyName(partitionKeyName)
                .withPartitionKeyValue(partitionKeyValue)
                .withNestedPath(nestedPath)
                .withNestedAttribute(nestedAttr)
                .withNestedValue(nestedValue)
                .withRegion(region)
                .execute();

            // Process the results
            System.out.println("Found " + response.count() + " items:");
            response.items().forEach(item -> {
                System.out.println(item);

                // Extract and display the nested attribute for clarity
                if (item.containsKey(nestedPath) && item.get(nestedPath).hasM()) {
                    Map<String, AttributeValue> nestedMap = item.get(nestedPath).m();
                    if (nestedMap.containsKey(nestedAttr)) {
                        System.out.println("  Nested attribute " + nestedPath + "." + nestedAttr + ": "
                            + formatAttributeValue(nestedMap.get(nestedAttr)));
                    }
                }
            });

            System.out.println("\nNote: When working with nested attributes in DynamoDB:");
            System.out.println("1. Use dot notation in filter expressions to access nested attributes");
            System.out.println("2. Use expression attribute names for each component of the path");
            System.out.println("3. Check if the nested attribute exists before accessing it");

        } catch (IllegalArgumentException e) {
            System.err.println("Invalid input: " + e.getMessage());
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            System.err.println("Table not found: " + tableName);
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println("DynamoDB error: " + e.getMessage());
            System.exit(1);
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### ページ分割を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithPagination_java_2_topic"></a>

以下のコード例は、ページ分割を使用してテーブルをクエリする方法を示しています。
+ DynamoDB クエリ結果のページ分割を実装します。
+ LastEvaluatedKey を使用して後続のページを取得します。
+ Limit パラメータを使用して、ページあたりの項目数を制御します。

**SDK for Java 2.x**  
を使用してページ分割で DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    public List<Map<String, AttributeValue>> queryWithPagination(
        final String tableName, final String partitionKeyName, final String partitionKeyValue, final int pageSize) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validatePositiveInteger("Page size", pageSize);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        QueryRequest.Builder queryRequestBuilder = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .limit(pageSize);

        // List to store all items from all pages
        final List<Map<String, AttributeValue>> allItems = new ArrayList<>();

        // Map to store the last evaluated key for pagination
        Map<String, AttributeValue> lastEvaluatedKey = null;
        int pageNumber = 1;

        try {
            do {
                // If we have a last evaluated key, use it for the next page
                if (lastEvaluatedKey != null) {
                    queryRequestBuilder.exclusiveStartKey(lastEvaluatedKey);
                }

                // Execute the query
                final QueryResponse response = dynamoDbClient.query(queryRequestBuilder.build());

                // Process the current page of results
                final List<Map<String, AttributeValue>> pageItems = response.items();
                allItems.addAll(pageItems);

                // Get the last evaluated key for the next page
                lastEvaluatedKey = response.lastEvaluatedKey();
                if (lastEvaluatedKey != null && lastEvaluatedKey.isEmpty()) {
                    lastEvaluatedKey = null;
                }

                System.out.println("Page " + pageNumber + ": Retrieved " + pageItems.size() + " items (Running total: "
                    + allItems.size() + ")");

                pageNumber++;

            } while (lastEvaluatedKey != null);

            System.out.println("Query with pagination complete. Retrieved a total of " + allItems.size()
                + " items across " + (pageNumber - 1) + " pages");

            return allItems;
        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println("Error querying with pagination: " + e.getMessage());
            throw e;
        }
    }
```
ページ分割を使用して DynamoDB テーブルをクエリする方法を示します。  

```
    public static void main(String[] args) {
        final String usage =
            """
                Usage:
                    <tableName> <partitionKeyName> <partitionKeyValue> [pageSize] [region]
                Where:
                    tableName - The Amazon DynamoDB table to query.
                    partitionKeyName - The name of the partition key attribute.
                    partitionKeyValue - The value of the partition key to query.
                    pageSize (optional) - The maximum number of items to return per page. (Default: 10)
                    region (optional) - The AWS region where the table exists. (Default: us-east-1)
                """;

        if (args.length < 3) {
            System.out.println(usage);
            System.exit(1);
        }

        final String tableName = args[0];
        final String partitionKeyName = args[1];
        final String partitionKeyValue = args[2];
        final int pageSize = args.length > 3 ? Integer.parseInt(args[3]) : 10;
        final Region region = args.length > 4 ? Region.of(args[4]) : Region.US_EAST_1;

        System.out.println("Querying items with pagination (page size: " + pageSize + ")");

        try {
            // Using the builder pattern to create and execute the query
            final List<Map<String, AttributeValue>> allItems = new PaginationQueryBuilder()
                .withTableName(tableName)
                .withPartitionKeyName(partitionKeyName)
                .withPartitionKeyValue(partitionKeyValue)
                .withPageSize(pageSize)
                .withRegion(region)
                .executeWithPagination();

            // Process the results
            System.out.println("\nSummary: Retrieved a total of " + allItems.size() + " items");

            // Display the first few items as a sample
            final int sampleSize = Math.min(5, allItems.size());
            if (sampleSize > 0) {
                System.out.println("\nSample of retrieved items (first " + sampleSize + "):");
                for (int i = 0; i < sampleSize; i++) {
                    System.out.println(allItems.get(i));
                }

                if (allItems.size() > sampleSize) {
                    System.out.println("... and " + (allItems.size() - sampleSize) + " more items");
                }
            }
        } catch (IllegalArgumentException e) {
            System.err.println("Invalid input: " + e.getMessage());
            System.exit(1);
        } catch (ResourceNotFoundException e) {
            System.err.println("Table not found: " + tableName);
            System.exit(1);
        } catch (DynamoDbException e) {
            System.err.println("DynamoDB error: " + e.getMessage());
            System.exit(1);
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### 強力な整合性のある読み込みを使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithStronglyConsistentReads_java_2_topic"></a>

次のコード例は、強力な整合性のある読み込みを使用してテーブルをクエリする方法を示しています。
+ DynamoDB クエリの整合性レベルを設定します。
+ 強力な整合性のある読み込みを使用して最新のデータを取得します。
+ 結果整合性と強力な整合性のトレードオフを理解します。

**SDK for Java 2.x**  
を使用して、設定可能な読み取り整合性で DynamoDB テーブルをクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithConsistentReads(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final boolean useConsistentRead) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .consistentRead(useConsistentRead)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            LOGGER.log(Level.INFO, "Query successful. Found {0} items", response.count());
            return response;
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", tableName);
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "Error querying with consistent reads", e);
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。**

### TTL 項目のクエリ
<a name="dynamodb_QueryFilteredTTL_java_2_topic"></a>

次のコード例は、TTL 項目のクエリの開始方法を示しています。

**SDK for Java 2.x**  
を使用して DynamoDB テーブルで TTL 項目を収集するためにフィルタリングされた式をクエリします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.util.Map;
import java.util.Optional;

        final QueryRequest request = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .filterExpression(FILTER_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try (DynamoDbClient ddb = dynamoDbClient != null
            ? dynamoDbClient
            : DynamoDbClient.builder().region(region).build()) {
            final QueryResponse response = ddb.query(request);
            System.out.println("Query successful. Found " + response.count() + " items that have not expired yet.");

            // Print each item
            response.items().forEach(item -> {
                System.out.println("Item: " + item);
            });

            return 0;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### 日付と時刻のパターンを使用してテーブルをクエリする
<a name="dynamodb_Scenario_DateTimeQueries_java_2_topic"></a>

次のコード例は、日付と時刻のパターンを使用してテーブルをクエリする方法を示しています。
+ DynamoDB に日付/時刻値を保存してクエリします。
+ ソートキーを使用して日付範囲クエリを実装します。
+ 有効なクエリを行うために日付文字列をフォーマットします。

**SDK for Java 2.x**  
でソートキーの日付範囲を使用してクエリを実行します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

    public QueryResponse queryWithDateRange(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String dateKeyName,
        final LocalDate startDate,
        final LocalDate endDate) {

        // Focus on query logic, assuming parameters are valid
        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("Start date and end date cannot be null");
        }

        if (endDate.isBefore(startDate)) {
            throw new IllegalArgumentException("End date must be after start date");
        }

        // Format dates as ISO strings for DynamoDB (using just the date part)
        final String formattedStartDate = startDate.toString();
        final String formattedEndDate = endDate.toString();

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_SK, dateKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_START_DATE,
            AttributeValue.builder().s(formattedStartDate).build());
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_END_DATE,
            AttributeValue.builder().s(formattedEndDate).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            LOGGER.log(Level.INFO, "Query by date range successful. Found {0} items", response.count());
            return response;
        } catch (ResourceNotFoundException e) {
            LOGGER.log(Level.SEVERE, "Table not found: {0}", tableName);
            throw e;
        } catch (DynamoDbException e) {
            LOGGER.log(Level.SEVERE, "Error querying by date range: {0}", e.getMessage());
            throw e;
        }
    }
```
で日時変数を使用してクエリを実行します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

    public QueryResponse queryWithDateTime(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String dateKeyName,
        final String startDate,
        final String endDate) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateDateRangeParameters(dateKeyName, startDate, endDate);
        CodeSampleUtils.validateDateFormat("Start date", startDate);
        CodeSampleUtils.validateDateFormat("End date", endDate);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);
        expressionAttributeNames.put("#dateKey", dateKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            ":startDate", AttributeValue.builder().s(startDate).build());
        expressionAttributeValues.put(
            ":endDate", AttributeValue.builder().s(endDate).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            System.out.println("Query successful. Found " + response.count() + " items");
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println("Error querying with date range: " + e.getMessage());
            throw e;
        }
    }
```
 AWS SDK for Java 2.xで Unix エポックタイムスタンプの日付範囲内でクエリを実行します。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

    public QueryResponse queryWithDateTimeEpoch(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String dateKeyName,
        final long startEpoch,
        final long endEpoch) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Date key name", dateKeyName);
        CodeSampleUtils.validateEpochTimestamp("Start epoch", startEpoch);
        CodeSampleUtils.validateEpochTimestamp("End epoch", endEpoch);

        // Create expression attribute names for the column names
        final Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put(EXPRESSION_ATTRIBUTE_NAME_PK, partitionKeyName);
        expressionAttributeNames.put("#dateKey", dateKeyName);

        // Create expression attribute values for the column values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            EXPRESSION_ATTRIBUTE_VALUE_PK,
            AttributeValue.builder().s(partitionKeyValue).build());
        expressionAttributeValues.put(
            ":startDate", AttributeValue.builder().n(String.valueOf(startEpoch)).build());
        expressionAttributeValues.put(
            ":endDate", AttributeValue.builder().n(String.valueOf(endEpoch)).build());

        // Create the query request
        final QueryRequest queryRequest = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression(KEY_CONDITION_EXPRESSION)
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final QueryResponse response = dynamoDbClient.query(queryRequest);
            System.out.println("Query successful. Found " + response.count() + " items");
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println("Error querying with epoch timestamps: " + e.getMessage());
            throw e;
        }
    }
```
LocalDateTime オブジェクトを使用して日付範囲内でクエリを実行します AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;

    public QueryResponse queryWithDateTimeLocalDateTime(
        final String tableName,
        final String partitionKeyName,
        final String partitionKeyValue,
        final String dateKeyName,
        final LocalDateTime startDateTime,
        final LocalDateTime endDateTime) {

        CodeSampleUtils.validateTableParameters(tableName, partitionKeyName, partitionKeyValue);
        CodeSampleUtils.validateStringParameter("Date key name", dateKeyName);
        if (startDateTime == null || endDateTime == null) {
            throw new IllegalArgumentException("Start and end LocalDateTime must not be null");
        }

        // Convert LocalDateTime to ISO-8601 strings in UTC with the correct format
        final String startDate = startDateTime.atZone(ZoneOffset.UTC).format(DATE_TIME_FORMATTER);
        final String endDate = endDateTime.atZone(ZoneOffset.UTC).format(DATE_TIME_FORMATTER);

        return queryWithDateTime(tableName, partitionKeyName, partitionKeyValue, dateKeyName, startDate, endDate);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Query](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)」を参照してください。

### 式順序の更新を理解する
<a name="dynamodb_Scenario_UpdateExpressionOrder_java_2_topic"></a>

次のコード例は、式順序の更新を理解する方法を示しています。
+ DynamoDB が更新式を処理する方法について説明します。
+ 更新式のオペレーションの順序を理解します。
+ 式の評価を理解することで、予期しない結果を回避できます。

**SDK for Java 2.x**  
を使用して、式の更新順序をデモンストレーションします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.Map;

    /**
     * Demonstrates the effect of update expression order.
     *
     * <p>This method shows how the order of operations in an update expression
     * affects the result of the update.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @return Map containing the results of different update orders
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static Map<String, Object> demonstrateUpdateOrder(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key) {

        Map<String, Object> results = new HashMap<>();

        try {
            // Initialize the item with a counter
            UpdateItemRequest initRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET Counter = :zero, OldCounter = :zero")
                .expressionAttributeValues(
                    Map.of(":zero", AttributeValue.builder().n("0").build()))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            dynamoDbClient.updateItem(initRequest);

            // Example 1: SET first, then ADD
            UpdateItemRequest setFirstRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET Counter = :value ADD OldCounter :increment")
                .expressionAttributeValues(Map.of(
                    ":value", AttributeValue.builder().n("10").build(),
                    ":increment", AttributeValue.builder().n("5").build()))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            UpdateItemResponse setFirstResponse = dynamoDbClient.updateItem(setFirstRequest);
            results.put("setFirstResponse", setFirstResponse);

            // Reset the item
            dynamoDbClient.updateItem(initRequest);

            // Example 2: ADD first, then SET
            UpdateItemRequest addFirstRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("ADD Counter :increment SET OldCounter = :value")
                .expressionAttributeValues(Map.of(
                    ":value", AttributeValue.builder().n("10").build(),
                    ":increment", AttributeValue.builder().n("5").build()))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            UpdateItemResponse addFirstResponse = dynamoDbClient.updateItem(addFirstRequest);
            results.put("addFirstResponse", addFirstResponse);

            // Reset the item
            dynamoDbClient.updateItem(initRequest);

            // Example 3: SET with multiple attributes
            UpdateItemRequest multiSetRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET Counter = :value, OldCounter = Counter")
                .expressionAttributeValues(
                    Map.of(":value", AttributeValue.builder().n("10").build()))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            UpdateItemResponse multiSetResponse = dynamoDbClient.updateItem(multiSetRequest);
            results.put("multiSetResponse", multiSetResponse);

            // Reset the item
            dynamoDbClient.updateItem(initRequest);

            // Example 4: SET with expression using the same attribute
            UpdateItemRequest selfReferenceRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET Counter = Counter + :increment, OldCounter = Counter")
                .expressionAttributeValues(
                    Map.of(":increment", AttributeValue.builder().n("5").build()))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            UpdateItemResponse selfReferenceResponse = dynamoDbClient.updateItem(selfReferenceRequest);
            results.put("selfReferenceResponse", selfReferenceResponse);

            results.put("success", true);

        } catch (DynamoDbException e) {
            results.put("success", false);
            results.put("error", e.getMessage());
        }

        return results;
    }

    /**
     * Updates an item with SET first, then REMOVE.
     *
     * <p>This method demonstrates updating an item with SET operation first,
     * followed by a REMOVE operation.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param attributeToSet The attribute to set
     * @param setValue The value to set
     * @param attributeToRemove The attribute to remove
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateWithSetFirst(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String attributeToSet,
        AttributeValue setValue,
        String attributeToRemove) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #setAttr = :setValue REMOVE #removeAttr")
            .expressionAttributeNames(Map.of(
                "#setAttr", attributeToSet,
                "#removeAttr", attributeToRemove))
            .expressionAttributeValues(Map.of(":setValue", setValue))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        try {
            return dynamoDbClient.updateItem(request);
        } catch (DynamoDbException e) {
            throw DynamoDbException.builder()
                .message("Failed to update item with SET first: " + e.getMessage())
                .cause(e)
                .build();
        }
    }

    /**
     * Updates an item with REMOVE first, then SET.
     *
     * <p>This method demonstrates updating an item with REMOVE operation first,
     * followed by a SET operation.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param attributeToSet The attribute to set
     * @param setValue The value to set
     * @param attributeToRemove The attribute to remove
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateWithRemoveFirst(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String attributeToSet,
        AttributeValue setValue,
        String attributeToRemove) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("REMOVE #removeAttr SET #setAttr = :setValue")
            .expressionAttributeNames(Map.of(
                "#setAttr", attributeToSet,
                "#removeAttr", attributeToRemove))
            .expressionAttributeValues(Map.of(":setValue", setValue))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        try {
            return dynamoDbClient.updateItem(request);
        } catch (DynamoDbException e) {
            throw DynamoDbException.builder()
                .message("Failed to update item with REMOVE first: " + e.getMessage())
                .cause(e)
                .build();
        }
    }

    /**
     * Updates an item with all operation types in a specific order.
     *
     * <p>This method demonstrates using all operation types (SET, REMOVE, ADD, DELETE)
     * in a specific order in a single update expression.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateWithAllOperationTypes(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #stringAttr = :stringVal, #mapAttr.#nestedAttr = :nestedVal " + "REMOVE #oldAttr "
                + "ADD #counterAttr :increment "
                + "DELETE #stringSetAttr :stringSetVal")
            .expressionAttributeNames(Map.of(
                "#stringAttr", "StringAttribute",
                "#mapAttr", "MapAttribute",
                "#nestedAttr", "NestedAttribute",
                "#oldAttr", "OldAttribute",
                "#counterAttr", "CounterAttribute",
                "#stringSetAttr", "StringSetAttribute"))
            .expressionAttributeValues(Map.of(
                ":stringVal", AttributeValue.builder().s("New Value").build(),
                ":nestedVal", AttributeValue.builder().s("Nested Value").build(),
                ":increment", AttributeValue.builder().n("1").build(),
                ":stringSetVal", AttributeValue.builder().ss("Value1").build()))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        try {
            return dynamoDbClient.updateItem(request);
        } catch (DynamoDbException e) {
            throw DynamoDbException.builder()
                .message("Failed to update item with all operation types: " + e.getMessage())
                .cause(e)
                .build();
        }
    }

    /**
     * Gets the current state of an item.
     *
     * <p>Helper method to retrieve the current state of an item.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to get
     * @return The item or null if not found
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static Map<String, AttributeValue> getItem(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key) {

        // Define the get parameters
        GetItemRequest request =
            GetItemRequest.builder().tableName(tableName).key(key).build();

        // Perform the get operation
        try {
            GetItemResponse response = dynamoDbClient.getItem(request);

            // Return the item if it exists, otherwise null
            return response.item();
        } catch (DynamoDbException e) {
            throw DynamoDbException.builder()
                .message("Failed to get item: " + e.getMessage())
                .cause(e)
                .build();
        }
    }
```
での更新式の順序の使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating update expression order in DynamoDB");

        try {
            // Example 1: Demonstrate update order effects
            System.out.println("\nExample 1: Demonstrating update order effects");
            Map<String, Object> orderResults = demonstrateUpdateOrder(dynamoDbClient, tableName, key);

            if ((boolean) orderResults.get("success")) {
                System.out.println("SET first, then ADD:");
                System.out.println("  " + orderResults.get("setFirstResponse"));

                System.out.println("ADD first, then SET:");
                System.out.println("  " + orderResults.get("addFirstResponse"));

                System.out.println("SET with multiple attributes:");
                System.out.println("  " + orderResults.get("multiSetResponse"));

                System.out.println("SET with self-reference:");
                System.out.println("  " + orderResults.get("selfReferenceResponse"));
            } else {
                System.out.println("Error: " + orderResults.get("error"));
            }

            // Example 2: Update with SET first, then REMOVE
            System.out.println("\nExample 2: Update with SET first, then REMOVE");
            UpdateItemResponse setFirstResponse = updateWithSetFirst(
                dynamoDbClient,
                tableName,
                key,
                "Status",
                AttributeValue.builder().s("Active").build(),
                "OldStatus");

            System.out.println("Updated attributes: " + setFirstResponse.attributes());

            // Example 3: Update with REMOVE first, then SET
            System.out.println("\nExample 3: Update with REMOVE first, then SET");
            UpdateItemResponse removeFirstResponse = updateWithRemoveFirst(
                dynamoDbClient,
                tableName,
                key,
                "Status",
                AttributeValue.builder().s("Inactive").build(),
                "OldStatus");

            System.out.println("Updated attributes: " + removeFirstResponse.attributes());

            // Example 4: Update with all operation types
            System.out.println("\nExample 4: Update with all operation types");
            UpdateItemResponse allOpsResponse = updateWithAllOperationTypes(dynamoDbClient, tableName, key);

            System.out.println("Updated attributes: " + allOpsResponse.attributes());

            // Example 5: Get the current state of the item
            System.out.println("\nExample 5: Current state of the item");
            Map<String, AttributeValue> item = getItem(dynamoDbClient, tableName, key);

            if (item != null) {
                System.out.println("Item: " + item);
            } else {
                System.out.println("Item not found");
            }

            // Explain update expression order
            System.out.println("\nKey points about update expression order in DynamoDB:");
            System.out.println("1. Update expressions are processed in this order: SET, REMOVE, ADD, DELETE");
            System.out.println("2. Within each clause, operations are processed from left to right");
            System.out.println("3. SET operations use the item state before any updates in the expression");
            System.out.println("4. When an attribute is referenced multiple times, the first operation wins");
            System.out.println("5. To reference a new value, split the update into multiple operations");
            System.out.println("6. The order of clauses in the expression doesn't change the evaluation order");
            System.out.println("7. For complex updates, consider using multiple separate update operations");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### テーブルのウォームスループット設定を更新する
<a name="dynamodb_UpdateTableWarmThroughput_java_2_topic"></a>

次のコード例は、テーブルのウォームスループット設定を更新する方法を示しています。

**SDK for Java 2.x**  
 AWS SDK for Java 2.xを使用して既存の DynamoDB テーブルのウォームスループット設定を更新します。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GlobalSecondaryIndexUpdate;
import software.amazon.awssdk.services.dynamodb.model.UpdateGlobalSecondaryIndexAction;
import software.amazon.awssdk.services.dynamodb.model.UpdateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.WarmThroughput;

    public static WarmThroughput buildWarmThroughput(final Long readUnitsPerSecond, final Long writeUnitsPerSecond) {
        return WarmThroughput.builder()
            .readUnitsPerSecond(readUnitsPerSecond)
            .writeUnitsPerSecond(writeUnitsPerSecond)
            .build();
    }

    /**
     * Updates a DynamoDB table with warm throughput settings for both the table and a global secondary index.
     *
     * @param ddb The DynamoDB client
     * @param tableName The name of the table to update
     * @param tableReadUnitsPerSecond Read units per second for the table
     * @param tableWriteUnitsPerSecond Write units per second for the table
     * @param globalSecondaryIndexName The name of the global secondary index to update
     * @param globalSecondaryIndexReadUnitsPerSecond Read units per second for the GSI
     * @param globalSecondaryIndexWriteUnitsPerSecond Write units per second for the GSI
     */
    public static void updateDynamoDBTable(
        final DynamoDbClient ddb,
        final String tableName,
        final Long tableReadUnitsPerSecond,
        final Long tableWriteUnitsPerSecond,
        final String globalSecondaryIndexName,
        final Long globalSecondaryIndexReadUnitsPerSecond,
        final Long globalSecondaryIndexWriteUnitsPerSecond) {

        final WarmThroughput tableWarmThroughput =
            buildWarmThroughput(tableReadUnitsPerSecond, tableWriteUnitsPerSecond);
        final WarmThroughput gsiWarmThroughput =
            buildWarmThroughput(globalSecondaryIndexReadUnitsPerSecond, globalSecondaryIndexWriteUnitsPerSecond);

        final GlobalSecondaryIndexUpdate globalSecondaryIndexUpdate = GlobalSecondaryIndexUpdate.builder()
            .update(UpdateGlobalSecondaryIndexAction.builder()
                .indexName(globalSecondaryIndexName)
                .warmThroughput(gsiWarmThroughput)
                .build())
            .build();

        final UpdateTableRequest request = UpdateTableRequest.builder()
            .tableName(tableName)
            .globalSecondaryIndexUpdates(globalSecondaryIndexUpdate)
            .warmThroughput(tableWarmThroughput)
            .build();

        try {
            ddb.updateTable(request);
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }

        System.out.println(SUCCESS_MESSAGE);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateTable)」を参照してください。

### 項目の TTL を更新する
<a name="dynamodb_UpdateItemTTL_java_2_topic"></a>

次のコード例は、項目の TTL の更新方法を示しています。

**SDK for Java 2.x**  
テーブル内の既存の DynamoDB 項目の TTL を更新します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

    public UpdateItemResponse updateItemWithTTL(
        final String tableName, final String primaryKeyValue, final String sortKeyValue) {
        // Get current time in epoch second format
        final long currentTime = System.currentTimeMillis() / 1000;

        // Calculate expiration time 90 days from now in epoch second format
        final long expireDate = currentTime + (DAYS_TO_EXPIRE * SECONDS_PER_DAY);

        // Create the key map for the item to update
        final Map<String, AttributeValue> keyMap = new HashMap<>();
        keyMap.put(PRIMARY_KEY_ATTR, AttributeValue.builder().s(primaryKeyValue).build());
        keyMap.put(SORT_KEY_ATTR, AttributeValue.builder().s(sortKeyValue).build());

        // Create the expression attribute values
        final Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(
            ":c", AttributeValue.builder().n(String.valueOf(currentTime)).build());
        expressionAttributeValues.put(
            ":e", AttributeValue.builder().n(String.valueOf(expireDate)).build());

        final UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(keyMap)
            .updateExpression(UPDATE_EXPRESSION)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        try {
            final UpdateItemResponse response = dynamoDbClient.updateItem(request);
            System.out.println(String.format(SUCCESS_MESSAGE, tableName));
            return response;
        } catch (ResourceNotFoundException e) {
            System.err.format(TABLE_NOT_FOUND_ERROR, tableName);
            throw e;
        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_java_2_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 Lambda Java ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_apigateway) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### Step Functions を使用して Lambda 関数を呼び出す
<a name="cross_ServerlessWorkflows_java_2_topic"></a>

次のコード例は、 AWS Lambda 関数を順番に呼び出す AWS Step Functions ステートマシンを作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Step Functions と を使用して AWS サーバーレスワークフローを作成する方法を示します AWS SDK for Java 2.x。各ワークフローステップは、 AWS Lambda 関数を使用して実装されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_workflows_stepfunctions) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SES
+ ステップ関数

### アトミックカウンタオペレーションを使用する
<a name="dynamodb_Scenario_AtomicCounterOperations_java_2_topic"></a>

次のコード例は、DynamoDB でアトミックカウンタオペレーションを使用する方法を示しています。
+ ADD および SET オペレーションを使用してカウンタをアトミックに増分します。
+ 存在しない可能性のあるカウンターを安全に増分します。
+ カウンターオペレーションに楽観的ロックを実装します。

**SDK for Java 2.x**  
を使用してアトミックカウンターオペレーションをデモンストレーションします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.Map;

    /**
     * Increments a counter using the ADD operation.
     *
     * <p>This method demonstrates how to use the ADD operation to atomically
     * increment a counter attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param counterName The name of the counter attribute
     * @param incrementValue The value to increment by
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse incrementCounterWithAdd(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String counterName,
        int incrementValue) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("ADD #counterName :increment")
            .expressionAttributeNames(Map.of("#counterName", counterName))
            .expressionAttributeValues(Map.of(
                ":increment",
                AttributeValue.builder().n(String.valueOf(incrementValue)).build()))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Increments a counter using the SET operation.
     *
     * <p>This method demonstrates how to use the SET operation with an expression
     * to increment a counter attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param counterName The name of the counter attribute
     * @param incrementValue The value to increment by
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse incrementCounterWithSet(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String counterName,
        int incrementValue) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #counterName = #counterName + :increment")
            .expressionAttributeNames(Map.of("#counterName", counterName))
            .expressionAttributeValues(Map.of(
                ":increment",
                AttributeValue.builder().n(String.valueOf(incrementValue)).build()))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Increments a counter safely, handling the case where the counter doesn't exist yet.
     *
     * <p>This method demonstrates how to use if_not_exists to safely increment a counter
     * that may not exist yet.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param counterName The name of the counter attribute
     * @param incrementValue The value to increment by
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse incrementCounterSafely(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String counterName,
        int incrementValue) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #counterName = if_not_exists(#counterName, :zero) + :increment")
            .expressionAttributeNames(Map.of("#counterName", counterName))
            .expressionAttributeValues(Map.of(
                ":increment",
                    AttributeValue.builder().n(String.valueOf(incrementValue)).build(),
                ":zero", AttributeValue.builder().n("0").build()))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Decrements a counter safely, ensuring it doesn't go below zero.
     *
     * <p>This method demonstrates how to use a condition expression to safely
     * decrement a counter without going below zero.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param counterName The name of the counter attribute
     * @param decrementValue The value to decrement by
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation or if the counter would go below zero
     */
    public static UpdateItemResponse decrementCounterSafely(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String counterName,
        int decrementValue) {

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #counterName = #counterName - :decrement")
            .conditionExpression("#counterName >= :decrement")
            .expressionAttributeNames(Map.of("#counterName", counterName))
            .expressionAttributeValues(Map.of(
                ":decrement",
                AttributeValue.builder().n(String.valueOf(decrementValue)).build()))
            .returnValues(ReturnValue.UPDATED_NEW)
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Compares the ADD and SET approaches for incrementing counters.
     *
     * <p>This method demonstrates the differences between using ADD and SET
     * for incrementing counters in DynamoDB.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @return Map containing the comparison results
     */
    public static Map<String, Object> compareAddVsSet(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key) {

        Map<String, Object> results = new HashMap<>();

        try {
            // Reset counters to ensure a fair comparison
            UpdateItemRequest resetRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET AddCounter = :zero, SetCounter = :zero")
                .expressionAttributeValues(
                    Map.of(":zero", AttributeValue.builder().n("0").build()))
                .build();

            dynamoDbClient.updateItem(resetRequest);

            // Increment with ADD
            long addStartTime = System.nanoTime();
            UpdateItemResponse addResponse = incrementCounterWithAdd(dynamoDbClient, tableName, key, "AddCounter", 1);
            long addEndTime = System.nanoTime();
            long addDuration = addEndTime - addStartTime;

            // Increment with SET
            long setStartTime = System.nanoTime();
            UpdateItemResponse setResponse = incrementCounterWithSet(dynamoDbClient, tableName, key, "SetCounter", 1);
            long setEndTime = System.nanoTime();
            long setDuration = setEndTime - setStartTime;

            // Record results
            results.put("addResponse", addResponse);
            results.put("setResponse", setResponse);
            results.put("addDuration", addDuration);
            results.put("setDuration", setDuration);
            results.put("success", true);

        } catch (DynamoDbException e) {
            results.put("success", false);
            results.put("error", e.getMessage());
        }

        return results;
    }

    /**
     * Gets the current value of a counter attribute.
     *
     * <p>Helper method to retrieve the current value of a counter attribute.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to get
     * @param counterName The name of the counter attribute
     * @return The counter value or null if not found
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static Integer getCounterValue(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key, String counterName) {

        // Define the get parameters
        GetItemRequest request = GetItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .projectionExpression(counterName)
            .build();

        // Perform the get operation
        GetItemResponse response = dynamoDbClient.getItem(request);

        // Return the counter value if it exists, otherwise null
        if (response.item() != null && response.item().containsKey(counterName)) {
            return Integer.parseInt(response.item().get(counterName).n());
        }

        return null;
    }
```
でのアトミックカウンターオペレーションの使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating atomic counter operations in DynamoDB");

        try {
            // Example 1: Increment a counter using ADD
            System.out.println("\nExample 1: Incrementing a counter using ADD");
            UpdateItemResponse addResponse = incrementCounterWithAdd(dynamoDbClient, tableName, key, "ViewCount", 1);

            System.out.println("Updated counter: " + addResponse.attributes());

            // Example 2: Increment a counter using SET
            System.out.println("\nExample 2: Incrementing a counter using SET");
            UpdateItemResponse setResponse = incrementCounterWithSet(dynamoDbClient, tableName, key, "LikeCount", 1);

            System.out.println("Updated counter: " + setResponse.attributes());

            // Example 3: Increment a counter safely
            System.out.println("\nExample 3: Incrementing a counter safely");
            UpdateItemResponse safeResponse = incrementCounterSafely(dynamoDbClient, tableName, key, "ShareCount", 1);

            System.out.println("Updated counter: " + safeResponse.attributes());

            // Example 4: Decrement a counter safely
            System.out.println("\nExample 4: Decrementing a counter safely");
            try {
                UpdateItemResponse decrementResponse =
                    decrementCounterSafely(dynamoDbClient, tableName, key, "InventoryCount", 1);

                System.out.println("Updated counter: " + decrementResponse.attributes());
            } catch (DynamoDbException e) {
                if (e.getMessage().contains("ConditionalCheckFailed")) {
                    System.out.println("Cannot decrement counter below zero");
                } else {
                    throw e;
                }
            }

            // Example 5: Compare ADD vs SET
            System.out.println("\nExample 5: Comparing ADD vs SET");
            Map<String, Object> comparison = compareAddVsSet(dynamoDbClient, tableName, key);

            if ((boolean) comparison.get("success")) {
                System.out.println("ADD duration: " + comparison.get("addDuration") + " ns");
                System.out.println("SET duration: " + comparison.get("setDuration") + " ns");
                System.out.println("ADD response: " + comparison.get("addResponse"));
                System.out.println("SET response: " + comparison.get("setResponse"));
            } else {
                System.out.println("Comparison failed: " + comparison.get("error"));
            }

            // Explain atomic counter operations
            System.out.println("\nKey points about DynamoDB atomic counter operations:");
            System.out.println("1. Both ADD and SET can be used for atomic counters");
            System.out.println("2. ADD is more concise for simple increments");
            System.out.println("3. SET with an expression is more flexible for complex operations");
            System.out.println("4. Use if_not_exists to handle the case where the counter doesn't exist yet");
            System.out.println("5. Use condition expressions to prevent counters from going below zero");
            System.out.println("6. Atomic operations are guaranteed to be isolated from other writes");
            System.out.println("7. ADD can only be used with number and set data types");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### 条件付きオペレーションを使用する
<a name="dynamodb_Scenario_ConditionalOperations_java_2_topic"></a>

次のコード例は、DynamoDB で条件付きオペレーションを使用する方法を示しています。
+ データの上書きを防ぐため、条件付き書き込みを実装します。
+ 条件式を使用してビジネスルールを適用します。
+ 条件付きチェックの失敗を適切に処理します。

**SDK for Java 2.x**  
を使用して条件付きオペレーションをデモンストレーションします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.ConditionalCheckFailedException;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemRequest;
import software.amazon.awssdk.services.dynamodb.model.DeleteItemResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.GetItemRequest;
import software.amazon.awssdk.services.dynamodb.model.GetItemResponse;
import software.amazon.awssdk.services.dynamodb.model.ReturnValue;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.HashMap;
import java.util.Map;

    /**
     * Performs a conditional update on an item.
     *
     * <p>This method demonstrates how to use a condition expression to update an item
     * only if a specific condition is met.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param conditionAttribute The attribute to check in the condition
     * @param conditionValue The value to compare against
     * @param updateAttribute The attribute to update
     * @param updateValue The new value to set
     * @return Map containing the operation result and status
     */
    public static Map<String, Object> conditionalUpdate(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String conditionAttribute,
        AttributeValue conditionValue,
        String updateAttribute,
        AttributeValue updateValue) {

        Map<String, Object> result = new HashMap<>();

        try {
            // Define the update parameters
            UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET #updateAttr = :updateVal")
                .conditionExpression("#condAttr = :condVal")
                .expressionAttributeNames(Map.of(
                    "#condAttr", conditionAttribute,
                    "#updateAttr", updateAttribute))
                .expressionAttributeValues(Map.of(
                    ":condVal", conditionValue,
                    ":updateVal", updateValue))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            // Perform the update operation
            UpdateItemResponse response = dynamoDbClient.updateItem(request);

            // Record success result
            result.put("success", true);
            result.put("message", "Condition was met and update was performed");
            result.put("attributes", response.attributes());

        } catch (ConditionalCheckFailedException e) {
            // Record failure due to condition not being met
            result.put("success", false);
            result.put("message", "Condition was not met, update was not performed");
            result.put("error", "ConditionalCheckFailedException");

        } catch (DynamoDbException e) {
            // Record failure due to other errors
            result.put("success", false);
            result.put("message", "Error occurred: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
        }

        return result;
    }

    /**
     * Performs a conditional delete on an item.
     *
     * <p>This method demonstrates how to use a condition expression to delete an item
     * only if a specific condition is met.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to delete
     * @param conditionAttribute The attribute to check in the condition
     * @param conditionValue The value to compare against
     * @return Map containing the operation result and status
     */
    public static Map<String, Object> conditionalDelete(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String conditionAttribute,
        AttributeValue conditionValue) {

        Map<String, Object> result = new HashMap<>();

        try {
            // Define the delete parameters
            DeleteItemRequest request = DeleteItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .conditionExpression("#condAttr = :condVal")
                .expressionAttributeNames(Map.of("#condAttr", conditionAttribute))
                .expressionAttributeValues(Map.of(":condVal", conditionValue))
                .returnValues(ReturnValue.ALL_OLD)
                .build();

            // Perform the delete operation
            DeleteItemResponse response = dynamoDbClient.deleteItem(request);

            // Record success result
            result.put("success", true);
            result.put("message", "Condition was met and delete was performed");
            result.put("attributes", response.attributes());

        } catch (ConditionalCheckFailedException e) {
            // Record failure due to condition not being met
            result.put("success", false);
            result.put("message", "Condition was not met, delete was not performed");
            result.put("error", "ConditionalCheckFailedException");

        } catch (DynamoDbException e) {
            // Record failure due to other errors
            result.put("success", false);
            result.put("message", "Error occurred: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
        }

        return result;
    }

    /**
     * Demonstrates optimistic locking using a version attribute.
     *
     * <p>This method shows how to implement optimistic locking by using a version
     * attribute that is incremented with each update.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param versionAttribute The name of the version attribute
     * @return Map containing the operation result
     */
    public static Map<String, Object> optimisticLockingExample(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> key, String versionAttribute) {

        Map<String, Object> result = new HashMap<>();

        try {
            // Get the current version of the item
            GetItemRequest getRequest = GetItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .projectionExpression(versionAttribute)
                .build();

            GetItemResponse getResponse = dynamoDbClient.getItem(getRequest);

            // Check if the item exists
            if (getResponse.item() == null || !getResponse.item().containsKey(versionAttribute)) {
                // Item doesn't exist or doesn't have a version attribute
                // Initialize with version 1
                UpdateItemRequest initRequest = UpdateItemRequest.builder()
                    .tableName(tableName)
                    .key(key)
                    .updateExpression("SET #verAttr = :newVer, #dataAttr = :data")
                    .expressionAttributeNames(Map.of("#verAttr", versionAttribute, "#dataAttr", "Data"))
                    .expressionAttributeValues(Map.of(
                        ":newVer", AttributeValue.builder().n("1").build(),
                        ":data", AttributeValue.builder().s("Initial data").build()))
                    .returnValues(ReturnValue.UPDATED_NEW)
                    .build();

                UpdateItemResponse initResponse = dynamoDbClient.updateItem(initRequest);

                result.put("operation", "initialize");
                result.put("success", true);
                result.put("attributes", initResponse.attributes());

                return result;
            }

            // Get the current version number
            int currentVersion =
                Integer.parseInt(getResponse.item().get(versionAttribute).n());
            int newVersion = currentVersion + 1;

            // Update the item with a condition on the version
            UpdateItemRequest updateRequest = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET #verAttr = :newVer, #dataAttr = :newData")
                .conditionExpression("#verAttr = :curVer")
                .expressionAttributeNames(Map.of("#verAttr", versionAttribute, "#dataAttr", "Data"))
                .expressionAttributeValues(Map.of(
                    ":curVer",
                        AttributeValue.builder()
                            .n(String.valueOf(currentVersion))
                            .build(),
                    ":newVer",
                        AttributeValue.builder().n(String.valueOf(newVersion)).build(),
                    ":newData",
                        AttributeValue.builder()
                            .s("Updated data at version " + newVersion)
                            .build()))
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            UpdateItemResponse updateResponse = dynamoDbClient.updateItem(updateRequest);

            // Record success result
            result.put("operation", "update");
            result.put("success", true);
            result.put("oldVersion", currentVersion);
            result.put("newVersion", newVersion);
            result.put("attributes", updateResponse.attributes());

        } catch (ConditionalCheckFailedException e) {
            // Record failure due to version mismatch
            result.put("operation", "update");
            result.put("success", false);
            result.put("message", "Version mismatch, another process may have updated the item");
            result.put("error", "ConditionalCheckFailedException");

        } catch (DynamoDbException e) {
            // Record failure due to other errors
            result.put("operation", "update");
            result.put("success", false);
            result.put("message", "Error occurred: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
        }

        return result;
    }

    /**
     * Performs a conditional update with multiple conditions.
     *
     * <p>This method demonstrates how to use multiple conditions in a condition expression.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param conditions Map of attribute names to values for conditions
     * @param updateAttribute The attribute to update
     * @param updateValue The new value to set
     * @return Map containing the operation result and status
     */
    public static Map<String, Object> conditionalUpdateWithMultipleConditions(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        Map<String, AttributeValue> conditions,
        String updateAttribute,
        AttributeValue updateValue) {

        Map<String, Object> result = new HashMap<>();

        try {
            // Build the condition expression and attribute names/values
            StringBuilder conditionExpression = new StringBuilder();
            Map<String, String> expressionAttributeNames = new HashMap<>();
            Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();

            // Add update attribute
            expressionAttributeNames.put("#updateAttr", updateAttribute);
            expressionAttributeValues.put(":updateVal", updateValue);

            // Add conditions
            int i = 0;
            for (Map.Entry<String, AttributeValue> condition : conditions.entrySet()) {
                String attrName = condition.getKey();
                AttributeValue attrValue = condition.getValue();

                String nameKey = "#cond" + i;
                String valueKey = ":val" + i;

                expressionAttributeNames.put(nameKey, attrName);
                expressionAttributeValues.put(valueKey, attrValue);

                // Add AND between conditions (except for the first one)
                if (i > 0) {
                    conditionExpression.append(" AND ");
                }

                conditionExpression.append(nameKey).append(" = ").append(valueKey);
                i++;
            }

            // Define the update parameters
            UpdateItemRequest request = UpdateItemRequest.builder()
                .tableName(tableName)
                .key(key)
                .updateExpression("SET #updateAttr = :updateVal")
                .conditionExpression(conditionExpression.toString())
                .expressionAttributeNames(expressionAttributeNames)
                .expressionAttributeValues(expressionAttributeValues)
                .returnValues(ReturnValue.UPDATED_NEW)
                .build();

            // Perform the update operation
            UpdateItemResponse response = dynamoDbClient.updateItem(request);

            // Record success result
            result.put("success", true);
            result.put("message", "All conditions were met and update was performed");
            result.put("attributes", response.attributes());

        } catch (ConditionalCheckFailedException e) {
            // Record failure due to condition not being met
            result.put("success", false);
            result.put("message", "One or more conditions were not met, update was not performed");
            result.put("error", "ConditionalCheckFailedException");

        } catch (DynamoDbException e) {
            // Record failure due to other errors
            result.put("success", false);
            result.put("message", "Error occurred: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
        }

        return result;
    }
```
での条件付きオペレーションの使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating conditional operations in DynamoDB");

        try {
            // Example 1: Conditional update
            System.out.println("\nExample 1: Conditional update");
            Map<String, Object> updateResult = conditionalUpdate(
                dynamoDbClient,
                tableName,
                key,
                "InStock",
                AttributeValue.builder().bool(true).build(),
                "Status",
                AttributeValue.builder().s("Available").build());

            System.out.println("Update result: " + updateResult.get("message"));
            if ((boolean) updateResult.get("success")) {
                System.out.println("Updated attributes: " + updateResult.get("attributes"));
            }

            // Example 2: Conditional delete
            System.out.println("\nExample 2: Conditional delete");
            Map<String, Object> deleteResult = conditionalDelete(
                dynamoDbClient,
                tableName,
                key,
                "Status",
                AttributeValue.builder().s("Discontinued").build());

            System.out.println("Delete result: " + deleteResult.get("message"));
            if ((boolean) deleteResult.get("success")) {
                System.out.println("Deleted item: " + deleteResult.get("attributes"));
            }

            // Example 3: Optimistic locking
            System.out.println("\nExample 3: Optimistic locking");
            Map<String, Object> lockingResult = optimisticLockingExample(dynamoDbClient, tableName, key, "Version");

            System.out.println("Optimistic locking result:");
            System.out.println("  Operation: " + lockingResult.get("operation"));
            System.out.println("  Success: " + lockingResult.get("success"));
            if (lockingResult.get("operation").equals("update") && (boolean) lockingResult.get("success")) {
                System.out.println("  Old version: " + lockingResult.get("oldVersion"));
                System.out.println("  New version: " + lockingResult.get("newVersion"));
            }
            System.out.println("  Attributes: " + lockingResult.get("attributes"));

            // Example 4: Multiple conditions
            System.out.println("\nExample 4: Multiple conditions");
            Map<String, AttributeValue> conditions = new HashMap<>();
            conditions.put("Price", AttributeValue.builder().n("199.99").build());
            conditions.put("Category", AttributeValue.builder().s("Electronics").build());

            Map<String, Object> multiConditionResult = conditionalUpdateWithMultipleConditions(
                dynamoDbClient,
                tableName,
                key,
                conditions,
                "OnSale",
                AttributeValue.builder().bool(true).build());

            System.out.println("Multiple conditions result: " + multiConditionResult.get("message"));
            if ((boolean) multiConditionResult.get("success")) {
                System.out.println("Updated attributes: " + multiConditionResult.get("attributes"));
            }

            // Explain conditional operations
            System.out.println("\nKey points about DynamoDB conditional operations:");
            System.out.println("1. Conditional operations only succeed if the condition is met");
            System.out.println("2. ConditionalCheckFailedException is thrown when the condition fails");
            System.out.println("3. No changes are made to the item if the condition fails");
            System.out.println("4. Conditions can be used with update, delete, and put operations");
            System.out.println("5. Multiple conditions can be combined with AND and OR");
            System.out.println("6. Optimistic locking can be implemented using a version attribute");
            System.out.println(
                "7. Conditional operations consume the same amount of write capacity whether they succeed or fail");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [DeleteItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/DeleteItem)
  + [PutItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/PutItem)
  + [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)

### 式の属性名を使用する
<a name="dynamodb_Scenario_ExpressionAttributeNames_java_2_topic"></a>

次のコード例は、DynamoDB で式の属性名を使用する方法を示しています。
+ DynamoDB 式で予約語を操作します。
+ 式の属性名のプレースホルダーを使用します。
+ 属性名の特殊文字を処理します。

**SDK for Java 2.x**  
を使用して式の属性名をデモンストレーションします AWS SDK for Java 2.x。  

```
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.QueryRequest;
import software.amazon.awssdk.services.dynamodb.model.QueryResponse;
import software.amazon.awssdk.services.dynamodb.model.ScanRequest;
import software.amazon.awssdk.services.dynamodb.model.ScanResponse;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest;
import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

    /**
     * Updates an attribute that is a reserved word in DynamoDB.
     *
     * <p>This method demonstrates how to use expression attribute names to update
     * attributes that are reserved words in DynamoDB.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param reservedWordAttribute The reserved word attribute to update
     * @param value The value to set
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateReservedWordAttribute(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String reservedWordAttribute,
        AttributeValue value) {

        // Define the update parameters using expression attribute names
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #attr = :value")
            .expressionAttributeNames(Map.of("#attr", reservedWordAttribute))
            .expressionAttributeValues(Map.of(":value", value))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Updates an attribute that contains special characters.
     *
     * <p>This method demonstrates how to use expression attribute names to update
     * attributes that contain special characters.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param specialCharAttribute The attribute with special characters to update
     * @param value The value to set
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateSpecialCharacterAttribute(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        String specialCharAttribute,
        AttributeValue value) {

        // Define the update parameters using expression attribute names
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET #attr = :value")
            .expressionAttributeNames(Map.of("#attr", specialCharAttribute))
            .expressionAttributeValues(Map.of(":value", value))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Queries items using an attribute that is a reserved word.
     *
     * <p>This method demonstrates how to use expression attribute names in a query
     * when the attribute is a reserved word.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param partitionKeyName The name of the partition key attribute
     * @param partitionKeyValue The value of the partition key
     * @param reservedWordAttribute The reserved word attribute to filter on
     * @param value The value to compare against
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static QueryResponse queryWithReservedWordAttribute(
        DynamoDbClient dynamoDbClient,
        String tableName,
        String partitionKeyName,
        AttributeValue partitionKeyValue,
        String reservedWordAttribute,
        AttributeValue value) {

        // Define the query parameters using expression attribute names
        Map<String, String> expressionAttributeNames = new HashMap<>();
        expressionAttributeNames.put("#pkName", partitionKeyName);
        expressionAttributeNames.put("#attr", reservedWordAttribute);

        Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        expressionAttributeValues.put(":pkValue", partitionKeyValue);
        expressionAttributeValues.put(":value", value);

        QueryRequest request = QueryRequest.builder()
            .tableName(tableName)
            .keyConditionExpression("#pkName = :pkValue")
            .filterExpression("#attr = :value")
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        // Perform the query operation
        return dynamoDbClient.query(request);
    }

    /**
     * Updates a nested attribute with a path that contains reserved words.
     *
     * <p>This method demonstrates how to use expression attribute names to update
     * nested attributes where the path contains reserved words.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param key The key of the item to update
     * @param attributePath The path to the nested attribute as an array
     * @param value The value to set
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static UpdateItemResponse updateNestedReservedWordAttribute(
        DynamoDbClient dynamoDbClient,
        String tableName,
        Map<String, AttributeValue> key,
        List<String> attributePath,
        AttributeValue value) {

        // Create expression attribute names for each part of the path
        Map<String, String> expressionAttributeNames = new HashMap<>();
        for (int i = 0; i < attributePath.size(); i++) {
            expressionAttributeNames.put("#attr" + i, attributePath.get(i));
        }

        // Build the attribute path using the expression attribute names
        StringBuilder attributePathExpression = new StringBuilder();
        for (int i = 0; i < attributePath.size(); i++) {
            if (i > 0) {
                attributePathExpression.append(".");
            }
            attributePathExpression.append("#attr").append(i);
        }

        // Define the update parameters
        UpdateItemRequest request = UpdateItemRequest.builder()
            .tableName(tableName)
            .key(key)
            .updateExpression("SET " + attributePathExpression.toString() + " = :value")
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(Map.of(":value", value))
            .returnValues("UPDATED_NEW")
            .build();

        // Perform the update operation
        return dynamoDbClient.updateItem(request);
    }

    /**
     * Scans a table with multiple attribute name placeholders.
     *
     * <p>This method demonstrates how to use multiple expression attribute names
     * in a complex filter expression.
     *
     * @param dynamoDbClient The DynamoDB client
     * @param tableName The name of the DynamoDB table
     * @param filters Object mapping attribute names to filter values
     * @return The response from DynamoDB
     * @throws DynamoDbException if an error occurs during the operation
     */
    public static ScanResponse scanWithMultipleAttributeNames(
        DynamoDbClient dynamoDbClient, String tableName, Map<String, AttributeValue> filters) {

        // Create expression attribute names and values
        Map<String, String> expressionAttributeNames = new HashMap<>();
        Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
        StringBuilder filterExpression = new StringBuilder();

        // Build the filter expression
        int index = 0;
        for (Map.Entry<String, AttributeValue> entry : filters.entrySet()) {
            String attrName = entry.getKey();
            AttributeValue attrValue = entry.getValue();

            String nameKey = "#attr" + index;
            String valueKey = ":val" + index;

            expressionAttributeNames.put(nameKey, attrName);
            expressionAttributeValues.put(valueKey, attrValue);

            // Add AND between conditions (except for the first one)
            if (index > 0) {
                filterExpression.append(" AND ");
            }

            filterExpression.append(nameKey).append(" = ").append(valueKey);
            index++;
        }

        // Define the scan parameters
        ScanRequest request = ScanRequest.builder()
            .tableName(tableName)
            .filterExpression(filterExpression.toString())
            .expressionAttributeNames(expressionAttributeNames)
            .expressionAttributeValues(expressionAttributeValues)
            .build();

        // Perform the scan operation
        return dynamoDbClient.scan(request);
    }
```
を使用した式の属性名の使用例 AWS SDK for Java 2.x。  

```
    public static void exampleUsage(DynamoDbClient dynamoDbClient, String tableName) {
        // Example key
        Map<String, AttributeValue> key = new HashMap<>();
        key.put("ProductId", AttributeValue.builder().s("P12345").build());

        System.out.println("Demonstrating expression attribute names in DynamoDB");

        try {
            // Example 1: Update an attribute that is a reserved word
            System.out.println("\nExample 1: Updating an attribute that is a reserved word");
            UpdateItemResponse response1 = updateReservedWordAttribute(
                dynamoDbClient,
                tableName,
                key,
                "Size", // "SIZE" is a reserved word in DynamoDB
                AttributeValue.builder().s("Large").build());

            System.out.println("Updated attribute: " + response1.attributes());

            // Example 2: Update an attribute with special characters
            System.out.println("\nExample 2: Updating an attribute with special characters");
            UpdateItemResponse response2 = updateSpecialCharacterAttribute(
                dynamoDbClient,
                tableName,
                key,
                "Product-Type", // Contains a hyphen, which is a special character
                AttributeValue.builder().s("Electronics").build());

            System.out.println("Updated attribute: " + response2.attributes());

            // Example 3: Query with a reserved word attribute
            System.out.println("\nExample 3: Querying with a reserved word attribute");
            QueryResponse response3 = queryWithReservedWordAttribute(
                dynamoDbClient,
                tableName,
                "Category",
                AttributeValue.builder().s("Electronics").build(),
                "Count", // "COUNT" is a reserved word in DynamoDB
                AttributeValue.builder().n("10").build());

            System.out.println("Found " + response3.count() + " items");

            // Example 4: Update a nested attribute with reserved words in the path
            System.out.println("\nExample 4: Updating a nested attribute with reserved words in the path");
            UpdateItemResponse response4 = updateNestedReservedWordAttribute(
                dynamoDbClient,
                tableName,
                key,
                Arrays.asList("Dimensions", "Size", "Height"), // "SIZE" is a reserved word
                AttributeValue.builder().n("30").build());

            System.out.println("Updated nested attribute: " + response4.attributes());

            // Example 5: Scan with multiple attribute name placeholders
            System.out.println("\nExample 5: Scanning with multiple attribute name placeholders");
            Map<String, AttributeValue> filters = new HashMap<>();
            filters.put("Size", AttributeValue.builder().s("Large").build());
            filters.put("Count", AttributeValue.builder().n("10").build());
            filters.put(
                "Product-Type", AttributeValue.builder().s("Electronics").build());

            ScanResponse response5 = scanWithMultipleAttributeNames(dynamoDbClient, tableName, filters);

            System.out.println("Found " + response5.count() + " items");

            // Show some common reserved words
            System.out.println("\nSome common DynamoDB reserved words:");
            List<String> commonReservedWords = getDynamoDBReservedWords();
            System.out.println(String.join(", ", commonReservedWords));

            // Explain expression attribute names
            System.out.println("\nKey points about expression attribute names:");
            System.out.println("1. Use expression attribute names (#name) for reserved words");
            System.out.println("2. Use expression attribute names for attributes with special characters");
            System.out.println(
                "3. Special characters include: spaces, hyphens, dots, and other non-alphanumeric characters");
            System.out.println("4. Expression attribute names are required for nested attributes with reserved words");
            System.out.println("5. You can use multiple expression attribute names in a single expression");
            System.out.println("6. Expression attribute names are case-sensitive");
            System.out.println("7. Expression attribute names are only used in expressions, not in the actual data");

        } catch (DynamoDbException e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [クエリ](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/Query)
  + [UpdateItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/dynamodb-2012-08-10/UpdateItem)

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_java_2_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda Java ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_scheduled_events) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_java_2_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での DynamoDB イベントの消費。  

```
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class example implements RequestHandler<DynamodbEvent, Void> {

    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

    @Override
    public Void handleRequest(DynamodbEvent event, Context context) {
        System.out.println(GSON.toJson(event));
        event.getRecords().forEach(this::logDynamoDBRecord);
        return null;
    }

    private void logDynamoDBRecord(DynamodbStreamRecord record) {
        System.out.println(record.getEventID());
        System.out.println(record.getEventName());
        System.out.println("DynamoDB Record: " + GSON.toJson(record.getDynamodb()));
    }
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_java_2_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での DynamoDB のバッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse;
import com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord;

import java.util.ArrayList;
import java.util.List;

public class ProcessDynamodbRecords implements RequestHandler<DynamodbEvent, StreamsEventResponse> {

    @Override
    public StreamsEventResponse handleRequest(DynamodbEvent input, Context context) {

        List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>();
        String curRecordSequenceNumber = "";

        for (DynamodbEvent.DynamodbStreamRecord dynamodbStreamRecord : input.getRecords()) {
          try {
                //Process your record
                StreamRecord dynamodbRecord = dynamodbStreamRecord.getDynamodb();
                curRecordSequenceNumber = dynamodbRecord.getSequenceNumber();
                
            } catch (Exception e) {
                /* Since we are working with streams, we can return the failed item immediately.
                   Lambda will immediately begin to retry processing from this failed item onwards. */
                batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber));
                return new StreamsEventResponse(batchItemFailures);
            }
        }
       
       return new StreamsEventResponse();   
    }
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_java_2_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Java 2.x**  
 Java SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-java-frameworks-samples) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Java 2.x を使用する Amazon EC2 の例
<a name="java_2_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_java_2_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously describes the security groups for the specified group ID.
     *
     * @param groupName the name of the security group to describe
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     *         of describing the security groups. The future will complete with a
     *         {@link DescribeSecurityGroupsResponse} object that contains the
     *         security group information.
     */
    public CompletableFuture<String> describeSecurityGroupArnByNameAsync(String groupName) {
        DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder()
            .groupNames(groupName)
            .build();

        DescribeSecurityGroupsPublisher paginator = getAsyncClient().describeSecurityGroupsPaginator(request);
        AtomicReference<String> groupIdRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.securityGroups().stream()
                .filter(securityGroup -> securityGroup.groupName().equals(groupName))
                .findFirst()
                .ifPresent(securityGroup -> groupIdRef.set(securityGroup.groupId()));
        }).thenApply(v -> {
            String groupId = groupIdRef.get();
            if (groupId == null) {
                throw new RuntimeException("No security group found with the name: " + groupName);
            }
            return groupId;
        }).exceptionally(ex -> {
            logger.info("Failed to describe security group: " + ex.getMessage());
            throw new RuntimeException("Failed to describe security group", ex);
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトでシナリオを実行します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;
import software.amazon.awssdk.services.ec2.model.DeleteKeyPairResponse;
import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;
import software.amazon.awssdk.services.ec2.model.DisassociateAddressResponse;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.ReleaseAddressResponse;
import software.amazon.awssdk.services.ssm.model.GetParametersByPathResponse;
import software.amazon.awssdk.services.ssm.model.Parameter;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

/**
 * 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
 *
 * This Java example performs the following tasks:
 *
 * 1. Creates an RSA key pair and saves the private key data as a .pem file.
 * 2. Lists key pairs.
 * 3. Creates a security group for the default VPC.
 * 4. Displays security group information.
 * 5. Gets a list of Amazon Linux 2 AMIs and selects one.
 * 6. Gets additional information about the image.
 * 7. Gets a list of instance types that are compatible with the selected AMI’s
 * architecture.
 * 8. Creates an instance with the key pair, security group, AMI, and an
 * instance type.
 * 9. Displays information about the instance.
 * 10. Stops the instance and waits for it to stop.
 * 11. Starts the instance and waits for it to start.
 * 12. Allocates an Elastic IP address and associates it with the instance.
 * 13. Displays SSH connection info for the instance.
 * 14. Disassociates and deletes the Elastic IP address.
 * 15. Terminates the instance and waits for it to terminate.
 * 16. Deletes the security group.
 * 17. Deletes the key pair.
 */
public class EC2Scenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final Logger logger = LoggerFactory.getLogger(EC2Scenario.class);
    public static void main(String[] args) throws InterruptedException, UnknownHostException {

        logger.info("""
            Usage:
               <keyName> <fileName> <groupName> <groupDesc> 

            Where:
               keyName -  A key pair name (for example, TestKeyPair).\s
               fileName -  A file name where the key information is written to.\s
               groupName - The name of the security group.\s
               groupDesc - The description of the security group.\s
            """);

        Scanner scanner = new Scanner(System.in);
        EC2Actions ec2Actions = new EC2Actions();

        String keyName = "TestKeyPair7" ;
        String fileName = "ec2Key.pem";
        String groupName = "TestSecGroup7" ;
        String groupDesc = "Test Group" ;
        String vpcId = ec2Actions.describeFirstEC2VpcAsync().join().vpcId();
        InetAddress localAddress = InetAddress.getLocalHost();
        String myIpAddress = localAddress.getHostAddress();

        logger.info("""
            Amazon Elastic Compute Cloud (EC2) is a web service that provides secure, resizable compute 
            capacity in the cloud. It allows developers and organizations to easily launch and manage 
            virtual server instances, known as EC2 instances, to run their applications.
                        
            EC2 provides a wide range of instance types, each with different compute, memory, 
            and storage capabilities, to meet the diverse needs of various workloads. Developers 
            can choose the appropriate instance type based on their application's requirements, 
            such as high-performance computing, memory-intensive tasks, or GPU-accelerated workloads.
                        
            The `Ec2AsyncClient` interface in the AWS SDK for Java 2.x provides a set of methods to 
            programmatically interact with the Amazon EC2 service. This allows developers to 
            automate the provisioning, management, and monitoring of EC2 instances as part of their 
            application deployment pipelines. With EC2, teams can focus on building and deploying 
            their applications without having to worry about the underlying infrastructure 
            required to host and manage physical servers.
            
            This scenario walks you through how to perform key operations for this service.  
            Let's get started...
            """);

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("1. Create an RSA key pair and save the private key material as a .pem file.");
        logger.info("""
            An RSA key pair for Amazon EC2 is a security mechanism used to authenticate and secure 
            access to your EC2 instances. It consists of a public key and a private key, 
            which are generated as a pair.
            """);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<CreateKeyPairResponse> future = ec2Actions.createKeyPairAsync(keyName, fileName);
            CreateKeyPairResponse response = future.join();
            logger.info("Key Pair successfully created. Key Fingerprint: " + response.keyFingerprint());

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                if (ec2Ex.getMessage().contains("already exists")) {
                    // Key pair already exists.
                    logger.info("The key pair '" + keyName + "' already exists. Moving on...");
                } else {
                    logger.info("EC2 error occurred: Error message: {}, Error code {}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                    return;
                }
            } else {
                logger.info("An unexpected error occurred: " + (rt.getMessage()));
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. List key pairs.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<DescribeKeyPairsResponse> future = ec2Actions.describeKeysAsync();
            DescribeKeyPairsResponse keyPairsResponse = future.join();
            keyPairsResponse.keyPairs().forEach(keyPair -> logger.info(
                "Found key pair with name {} and fingerprint {}",
                keyPair.keyName(),
                keyPair.keyFingerprint()));

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Error message: {}, Error code {}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", (cause != null ? cause.getMessage() : rt.getMessage()));
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("3. Create a security group.");
        logger.info("""
            An AWS EC2 Security Group is a virtual firewall that controls the 
            inbound and outbound traffic to an EC2 instance. It acts as a first line 
            of defense for your EC2 instances, allowing you to specify the rules that 
            govern the network traffic entering and leaving your instances.
           """);
        waitForInputToContinue(scanner);
        String groupId = "";
        try {
            CompletableFuture<String> future = ec2Actions.createSecurityGroupAsync(groupName, groupDesc, vpcId, myIpAddress);
            future.join();
            logger.info("Created security group") ;

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                if (ec2Ex.awsErrorDetails().errorMessage().contains("already exists")) {
                    logger.info("The Security Group already exists. Moving on...");
                } else {
                    logger.error("An unexpected error occurred: {}", ec2Ex.awsErrorDetails().errorMessage());
                    return;
                }
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. Display security group information for the new security group.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<String> future = ec2Actions.describeSecurityGroupArnByNameAsync(groupName);
            groupId = future.join();
            logger.info("The security group Id is "+groupId);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                String errorCode = ec2Ex.awsErrorDetails().errorCode();
                if ("InvalidGroup.NotFound".equals(errorCode)) {
                    logger.info("Security group '{}' does not exist. Error Code: {}", groupName, errorCode);
                } else {
                    logger.info("EC2 error occurred: Message {}, Error Code: {}", ec2Ex.getMessage(), errorCode);
                }
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5. Get a list of Amazon Linux 2 AMIs and select one with amzn2 in the name.");
        logger.info("""
            An Amazon EC2 AMI (Amazon Machine Image) is a pre-configured virtual machine image that 
            serves as a template for launching EC2 instances. It contains all the necessary software and 
            configurations required to run an application or operating system on an EC2 instance.
            """);
        waitForInputToContinue(scanner);
        String instanceAMI="";
        try {
            CompletableFuture<GetParametersByPathResponse> future = ec2Actions.getParaValuesAsync();
            GetParametersByPathResponse pathResponse = future.join();
            List<Parameter> parameterList = pathResponse.parameters();
            for (Parameter para : parameterList) {
                if (filterName(para.name())) {
                    instanceAMI = para.value();
                    break;
                }
            }
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        logger.info("The AMI value with amzn2 is: {}", instanceAMI);
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("6. Get the (Amazon Machine Image) AMI value from the amzn2 image.");
        logger.info("""
           An AMI value represents a specific version of a virtual machine (VM) or server image.   
           It uniquely identifies a particular version of an EC2 instance, including its operating system, 
           pre-installed software, and any custom configurations. This allows you to consistently deploy the same 
           VM image across your infrastructure.
                        
            """);
        waitForInputToContinue(scanner);
        String amiValue;
        try {
            CompletableFuture<String> future = ec2Actions.describeImageAsync(instanceAMI);
            amiValue = future.join();

        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof Ec2Exception) {
                Ec2Exception ec2Ex = (Ec2Exception) cause;
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Retrieves an instance type available in the current AWS region.");
        waitForInputToContinue(scanner);
        String instanceType;
        try {
            CompletableFuture<String> future = ec2Actions.getInstanceTypesAsync();
            instanceType = future.join();
            if (!instanceType.isEmpty()) {
                logger.info("Found instance type: " + instanceType);
            } else {
                logger.info("Desired instance type not found.");
            }
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("8. Create an Amazon EC2 instance using the key pair, the instance type, the security group, and the EC2 AMI value.");
        logger.info("Once the EC2 instance is created, it is placed into a running state.");
        waitForInputToContinue(scanner);
        String newInstanceId;
        try {
            CompletableFuture<String> future = ec2Actions.runInstanceAsync(instanceType, keyName, groupName, amiValue);
            newInstanceId = future.join();
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception) {
                Ec2Exception ec2Ex = (Ec2Exception) cause;
                switch (ec2Ex.awsErrorDetails().errorCode()) {
                    case "InvalidParameterValue":
                        logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                        break;
                    case "InsufficientInstanceCapacity":
                        // Handle insufficient instance capacity.
                        logger.info("Insufficient instance capacity: {}, {}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                        break;
                    case "InvalidGroup.NotFound":
                        // Handle security group not found.
                        logger.info("Security group not found: {},{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                        break;
                    default:
                        logger.info("EC2 error occurred: {} (Code: {}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                        break;
                }
                return;
            } else {
                logger.info("An unexpected error occurred: {}", (cause != null ? cause.getMessage() : rt.getMessage()));
                return;
            }
        }
        logger.info("The instance Id is " + newInstanceId);
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("9. Display information about the running instance. ");

        waitForInputToContinue(scanner);
        String publicIp;
        try {
            CompletableFuture<String> future = ec2Actions.describeEC2InstancesAsync(newInstanceId);
            publicIp = future.join();
            logger.info("EC2 instance public IP {}", publicIp);
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }

        }
        logger.info("You can SSH to the instance using this command:");
        logger.info("ssh -i " + fileName + " ec2-user@" + publicIp);
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("10. Stop the instance using a waiter (this may take a few mins).");
        // Remove the 2nd one
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = ec2Actions.stopInstanceAsync(newInstanceId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("11. Start the instance using a waiter (this may take a few mins).");
        try {
            CompletableFuture<Void> future = ec2Actions.startInstanceAsync(newInstanceId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                // Handle EC2 exceptions.
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("12. Allocate an Elastic IP address and associate it with the instance.");
        logger.info("""
            An Elastic IP address is a static public IP address that you can associate with your EC2 instance.
            This allows you to have a fixed, predictable IP address that remains the same even if your instance 
            is stopped, terminated, or replaced. 
            This is particularly useful for applications or services that need to be accessed consistently from a 
            known IP address.
                        
            An EC2 Allocation ID (also known as a Reserved Instance Allocation ID) is a unique identifier associated with a Reserved Instance (RI) that you have purchased in AWS.
                       
            When you purchase a Reserved Instance, AWS assigns a unique Allocation ID to it. 
            This Allocation ID is used to track and identify the specific RI you have purchased, 
            and it is important for managing and monitoring your Reserved Instances.
                        
            """);

        waitForInputToContinue(scanner);
        String allocationId;
        try {
            CompletableFuture<String> future = ec2Actions.allocateAddressAsync();
            allocationId = future.join();
            logger.info("Successfully allocated address with ID: " +allocationId);
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        logger.info("The allocation Id value is " + allocationId);
        waitForInputToContinue(scanner);
        String associationId;
        try {
            CompletableFuture<String> future = ec2Actions.associateAddressAsync(newInstanceId, allocationId);
            associationId = future.join();
            logger.info("Successfully associated address with ID: " +associationId);
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("13. Describe the instance again. Note that the public IP address has changed");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<String> future = ec2Actions.describeEC2InstancesAsync(newInstanceId);
            publicIp = future.join();
            logger.info("EC2 instance public IP: " + publicIp);
            logger.info("You can SSH to the instance using this command:");
            logger.info("ssh -i " + fileName + " ec2-user@" + publicIp);
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("14. Disassociate and release the Elastic IP address.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<DisassociateAddressResponse> future = ec2Actions.disassociateAddressAsync(associationId);
            future.join();
            logger.info("Address successfully disassociated.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                // Handle EC2 exceptions.
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<ReleaseAddressResponse> future = ec2Actions.releaseEC2AddressAsync(allocationId);
            future.join(); // Wait for the operation to complete
            logger.info("Elastic IP address successfully released.");
        } catch (RuntimeException rte) {
            logger.info("An unexpected error occurred: {}", rte.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("15. Terminate the instance and use a waiter (this may take a few mins).");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Object> future = ec2Actions.terminateEC2Async(newInstanceId);
            future.join();
            logger.info("EC2 instance successfully terminated.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                // Handle EC2 exceptions.
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("16. Delete the security group.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = ec2Actions.deleteEC2SecGroupAsync(groupId);
            future.join();
            logger.info("Security group successfully deleted.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("17. Delete the key.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<DeleteKeyPairResponse> future = ec2Actions.deleteKeysAsync(keyName);
            future.join();
            logger.info("Successfully deleted key pair named " + keyName);
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof Ec2Exception ec2Ex) {
                logger.info("EC2 error occurred: Message {}, Error Code:{}", ec2Ex.getMessage(), ec2Ex.awsErrorDetails().errorCode());
                return;
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage());
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("You successfully completed the Amazon EC2 scenario.");
        logger.info(DASHES);
    }
    public static boolean filterName(String name) {
        String[] parts = name.split("/");
        String myValue = parts[4];
        return myValue.contains("amzn2");
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
EC2 アクションをラップするクラスを定義します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2AsyncClient;
import software.amazon.awssdk.services.ec2.model.AllocateAddressRequest;
import software.amazon.awssdk.services.ec2.model.AllocateAddressResponse;
import software.amazon.awssdk.services.ec2.model.AssociateAddressRequest;
import software.amazon.awssdk.services.ec2.model.AssociateAddressResponse;
import software.amazon.awssdk.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
import software.amazon.awssdk.services.ec2.model.CreateKeyPairRequest;
import software.amazon.awssdk.services.ec2.model.CreateKeyPairResponse;
import software.amazon.awssdk.services.ec2.model.CreateSecurityGroupRequest;
import software.amazon.awssdk.services.ec2.model.DeleteKeyPairRequest;
import software.amazon.awssdk.services.ec2.model.DeleteKeyPairResponse;
import software.amazon.awssdk.services.ec2.model.DeleteSecurityGroupRequest;
import software.amazon.awssdk.services.ec2.model.DeleteSecurityGroupResponse;
import software.amazon.awssdk.services.ec2.model.DescribeImagesRequest;
import software.amazon.awssdk.services.ec2.model.DescribeInstanceTypesRequest;
import software.amazon.awssdk.services.ec2.model.DescribeInstanceTypesResponse;
import software.amazon.awssdk.services.ec2.model.DescribeInstancesRequest;
import software.amazon.awssdk.services.ec2.model.DescribeKeyPairsResponse;
import software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsRequest;
import software.amazon.awssdk.services.ec2.model.DescribeSecurityGroupsResponse;
import software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest;
import software.amazon.awssdk.services.ec2.model.DisassociateAddressRequest;
import software.amazon.awssdk.services.ec2.model.DisassociateAddressResponse;
import software.amazon.awssdk.services.ec2.model.DomainType;
import software.amazon.awssdk.services.ec2.model.Ec2Exception;
import software.amazon.awssdk.services.ec2.model.Filter;
import software.amazon.awssdk.services.ec2.model.InstanceTypeInfo;
import software.amazon.awssdk.services.ec2.model.IpPermission;
import software.amazon.awssdk.services.ec2.model.IpRange;
import software.amazon.awssdk.services.ec2.model.ReleaseAddressRequest;
import software.amazon.awssdk.services.ec2.model.ReleaseAddressResponse;
import software.amazon.awssdk.services.ec2.model.RunInstancesRequest;
import software.amazon.awssdk.services.ec2.model.RunInstancesResponse;
import software.amazon.awssdk.services.ec2.model.StopInstancesRequest;
import software.amazon.awssdk.services.ec2.model.StartInstancesRequest;
import software.amazon.awssdk.services.ec2.model.TerminateInstancesRequest;
import software.amazon.awssdk.services.ec2.model.Vpc;
import software.amazon.awssdk.services.ec2.paginators.DescribeImagesPublisher;
import software.amazon.awssdk.services.ec2.paginators.DescribeInstancesPublisher;
import software.amazon.awssdk.services.ec2.paginators.DescribeSecurityGroupsPublisher;
import software.amazon.awssdk.services.ec2.paginators.DescribeVpcsPublisher;
import software.amazon.awssdk.services.ec2.waiters.Ec2AsyncWaiter;
import software.amazon.awssdk.services.ssm.SsmAsyncClient;
import software.amazon.awssdk.services.ssm.model.GetParametersByPathRequest;
import software.amazon.awssdk.services.ssm.model.GetParametersByPathResponse;
import software.amazon.awssdk.services.ec2.model.TerminateInstancesResponse;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.atomic.AtomicReference;

public class EC2Actions {
    private static final Logger logger = LoggerFactory.getLogger(EC2Actions.class);
    private static Ec2AsyncClient ec2AsyncClient;

    /**
     * Retrieves an asynchronous Amazon Elastic Container Registry (ECR) client.
     *
     * @return the configured ECR asynchronous client.
     */
    private static Ec2AsyncClient getAsyncClient() {
        if (ec2AsyncClient == null) {
            /*
            The `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java, version 2,
            and it is designed to provide a high-performance, asynchronous HTTP client for interacting with AWS services.
             It uses the Netty framework to handle the underlying network communication and the Java NIO API to
             provide a non-blocking, event-driven approach to HTTP requests and responses.
             */
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(50)  // Adjust as needed.
                .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
                .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
                .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
               .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
                .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
                .build();

            ec2AsyncClient = Ec2AsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return ec2AsyncClient;
    }

    /**
     * Deletes a key pair asynchronously.
     *
     * @param keyPair the name of the key pair to delete
     * @return a {@link CompletableFuture} that represents the result of the asynchronous operation.
     *         The {@link CompletableFuture} will complete with a {@link DeleteKeyPairResponse} object
     *         that provides the result of the key pair deletion operation.
     */
    public CompletableFuture<DeleteKeyPairResponse> deleteKeysAsync(String keyPair) {
        DeleteKeyPairRequest request = DeleteKeyPairRequest.builder()
            .keyName(keyPair)
            .build();

        // Initiate the asynchronous request to delete the key pair.
        CompletableFuture<DeleteKeyPairResponse> response = getAsyncClient().deleteKeyPair(request);
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete key pair: " + keyPair, ex);
            } else if (resp == null) {
                throw new RuntimeException("No response received for deleting key pair: " + keyPair);
            }
        });
    }

    /**
     * Deletes an EC2 security group asynchronously.
     *
     * @param groupId the ID of the security group to delete
     * @return a CompletableFuture that completes when the security group is deleted
     */
    public CompletableFuture<Void> deleteEC2SecGroupAsync(String groupId) {
        DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()
            .groupId(groupId)
            .build();

        CompletableFuture<DeleteSecurityGroupResponse> response = getAsyncClient().deleteSecurityGroup(request);
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete security group with Id " + groupId, ex);
            } else if (resp == null) {
                throw new RuntimeException("No response received for deleting security group with Id " + groupId);
            }
        }).thenApply(resp -> null);
    }

    /**
     * Terminates an EC2 instance asynchronously and waits for it to reach the terminated state.
     *
     * @param instanceId the ID of the EC2 instance to terminate
     * @return a {@link CompletableFuture} that completes when the instance has been terminated
     * @throws RuntimeException if there is no response from the AWS SDK or if there is a failure during the termination process
     */
    public CompletableFuture<Object> terminateEC2Async(String instanceId) {
        TerminateInstancesRequest terminateRequest = TerminateInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        CompletableFuture<TerminateInstancesResponse> responseFuture = getAsyncClient().terminateInstances(terminateRequest);
        return responseFuture.thenCompose(terminateResponse -> {
            if (terminateResponse == null) {
                throw new RuntimeException("No response received for terminating instance " + instanceId);
            }
            System.out.println("Going to terminate an EC2 instance and use a waiter to wait for it to be in terminated state");
            return getAsyncClient().waiter()
                .waitUntilInstanceTerminated(r -> r.instanceIds(instanceId))
                .thenApply(waiterResponse -> null);
        }).exceptionally(throwable -> {
            // Handle any exceptions that occurred during the async call
            throw new RuntimeException("Failed to terminate EC2 instance: " + throwable.getMessage(), throwable);
        });
    }

    /**
     * Releases an Elastic IP address asynchronously.
     *
     * @param allocId the allocation ID of the Elastic IP address to be released
     * @return a {@link CompletableFuture} representing the asynchronous operation of releasing the Elastic IP address
     */
    public CompletableFuture<ReleaseAddressResponse> releaseEC2AddressAsync(String allocId) {
        ReleaseAddressRequest request = ReleaseAddressRequest.builder()
            .allocationId(allocId)
            .build();

        CompletableFuture<ReleaseAddressResponse> response = getAsyncClient().releaseAddress(request);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to release Elastic IP address", ex);
            }
        });

        return response;
    }

    /**
     * Disassociates an Elastic IP address from an instance asynchronously.
     *
     * @param associationId The ID of the association you want to disassociate.
     * @return a {@link CompletableFuture} representing the asynchronous operation of disassociating the address. The
     *         {@link CompletableFuture} will complete with a {@link DisassociateAddressResponse} when the operation is
     *         finished.
     * @throws RuntimeException if the disassociation of the address fails.
     */
    public CompletableFuture<DisassociateAddressResponse> disassociateAddressAsync(String associationId) {
        Ec2AsyncClient ec2 = getAsyncClient();
        DisassociateAddressRequest addressRequest = DisassociateAddressRequest.builder()
            .associationId(associationId)
            .build();

        // Disassociate the address asynchronously.
        CompletableFuture<DisassociateAddressResponse> response = ec2.disassociateAddress(addressRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
               throw new RuntimeException("Failed to disassociate address", ex);
            }
        });

        return response;
    }

    /**
     * Associates an Elastic IP address with an EC2 instance asynchronously.
     *
     * @param instanceId    the ID of the EC2 instance to associate the Elastic IP address with
     * @param allocationId  the allocation ID of the Elastic IP address to associate
     * @return a {@link CompletableFuture} that completes with the association ID when the operation is successful,
     *         or throws a {@link RuntimeException} if the operation fails
     */
    public CompletableFuture<String> associateAddressAsync(String instanceId, String allocationId) {
        AssociateAddressRequest associateRequest = AssociateAddressRequest.builder()
            .instanceId(instanceId)
            .allocationId(allocationId)
            .build();

        CompletableFuture<AssociateAddressResponse> responseFuture = getAsyncClient().associateAddress(associateRequest);
        return responseFuture.thenApply(response -> {
            if (response.associationId() != null) {
                return response.associationId();
            } else {
                throw new RuntimeException("Association ID is null after associating address.");
            }
        }).whenComplete((result, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to associate address", ex);
            }
        });
    }

    /**
     * Allocates an Elastic IP address asynchronously in the VPC domain.
     *
     * @return a {@link CompletableFuture} containing the allocation ID of the allocated Elastic IP address
     */
    public CompletableFuture<String> allocateAddressAsync() {
        AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder()
            .domain(DomainType.VPC)
            .build();

        CompletableFuture<AllocateAddressResponse> responseFuture = getAsyncClient().allocateAddress(allocateRequest);
        return responseFuture.thenApply(AllocateAddressResponse::allocationId).whenComplete((result, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to allocate address", ex);
            }
        });
    }

    /**
     * Asynchronously describes the state of an EC2 instance.
     * The paginator helps you iterate over multiple pages of results.
     *
     * @param newInstanceId the ID of the EC2 instance to describe
     * @return a {@link CompletableFuture} that, when completed, contains a string describing the state of the EC2 instance
     */
    public CompletableFuture<String> describeEC2InstancesAsync(String newInstanceId) {
        DescribeInstancesRequest request = DescribeInstancesRequest.builder()
            .instanceIds(newInstanceId)
            .build();

        DescribeInstancesPublisher paginator = getAsyncClient().describeInstancesPaginator(request);
        AtomicReference<String> publicIpAddressRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.reservations().stream()
                .flatMap(reservation -> reservation.instances().stream())
                .filter(instance -> instance.instanceId().equals(newInstanceId))
                .findFirst()
                .ifPresent(instance -> publicIpAddressRef.set(instance.publicIpAddress()));
        }).thenApply(v -> {
            String publicIpAddress = publicIpAddressRef.get();
            if (publicIpAddress == null) {
                throw new RuntimeException("Instance with ID " + newInstanceId + " not found.");
            }
            return publicIpAddress;
        }).exceptionally(ex -> {
            logger.info("Failed to describe instances: " + ex.getMessage());
            throw new RuntimeException("Failed to describe instances", ex);
        });
    }

    /**
     * Runs an EC2 instance asynchronously.
     *
     * @param instanceType The instance type to use for the EC2 instance.
     * @param keyName The name of the key pair to associate with the EC2 instance.
     * @param groupName The name of the security group to associate with the EC2 instance.
     * @param amiId The ID of the Amazon Machine Image (AMI) to use for the EC2 instance.
     * @return A {@link CompletableFuture} that completes with the ID of the started EC2 instance.
     * @throws RuntimeException If there is an error running the EC2 instance.
     */
    public CompletableFuture<String> runInstanceAsync(String instanceType, String keyName, String groupName, String amiId) {
        RunInstancesRequest runRequest = RunInstancesRequest.builder()
            .instanceType(instanceType)
            .keyName(keyName)
            .securityGroups(groupName)
            .maxCount(1)
            .minCount(1)
            .imageId(amiId)
            .build();

        CompletableFuture<RunInstancesResponse> responseFuture = getAsyncClient().runInstances(runRequest);
        return responseFuture.thenCompose(response -> {
            String instanceIdVal = response.instances().get(0).instanceId();
            System.out.println("Going to start an EC2 instance and use a waiter to wait for it to be in running state");
            return getAsyncClient().waiter()
                .waitUntilInstanceExists(r -> r.instanceIds(instanceIdVal))
                .thenCompose(waitResponse -> getAsyncClient().waiter()
                    .waitUntilInstanceRunning(r -> r.instanceIds(instanceIdVal))
                    .thenApply(runningResponse -> instanceIdVal));
        }).exceptionally(throwable -> {
            // Handle any exceptions that occurred during the async call
            throw new RuntimeException("Failed to run EC2 instance: " + throwable.getMessage(), throwable);
        });
    }

    /**
     * Asynchronously retrieves the instance types available in the current AWS region.
     * <p>
     * This method uses the AWS SDK's asynchronous API to fetch the available instance types
     * and then processes the response. It logs the memory information, network information,
     * and instance type for each instance type returned. Additionally, it returns a
     * {@link CompletableFuture} that resolves to the instance type string for the "t2.2xlarge"
     * instance type, if it is found in the response. If the "t2.2xlarge" instance type is not
     * found, an empty string is returned.
     * </p>
     *
     * @return a {@link CompletableFuture} that resolves to the instance type string for the
     * "t2.2xlarge" instance type, or an empty string if the instance type is not found
     */
    public CompletableFuture<String> getInstanceTypesAsync() {
        DescribeInstanceTypesRequest typesRequest = DescribeInstanceTypesRequest.builder()
            .maxResults(10)
            .build();

        CompletableFuture<DescribeInstanceTypesResponse> response = getAsyncClient().describeInstanceTypes(typesRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                List<InstanceTypeInfo> instanceTypes = resp.instanceTypes();
                for (InstanceTypeInfo type : instanceTypes) {
                    logger.info("The memory information of this type is " + type.memoryInfo().sizeInMiB());
                    logger.info("Network information is " + type.networkInfo().toString());
                    logger.info("Instance type is " + type.instanceType().toString());
                }
            } else {
                throw (RuntimeException) ex;
            }
        });

        return response.thenApply(resp -> {
            for (InstanceTypeInfo type : resp.instanceTypes()) {
                String instanceType = type.instanceType().toString();
                if (instanceType.equals("t2.2xlarge")) {
                    return instanceType;
                }
            }
            return "";
        });
    }

    /**
     * Asynchronously describes an AWS EC2 image with the specified image ID.
     *
     * @param imageId the ID of the image to be described
     * @return a {@link CompletableFuture} that, when completed, contains the ID of the described image
     * @throws RuntimeException if no images are found with the provided image ID, or if an error occurs during the AWS API call
     */
    public CompletableFuture<String> describeImageAsync(String imageId) {
        DescribeImagesRequest imagesRequest = DescribeImagesRequest.builder()
            .imageIds(imageId)
            .build();

        AtomicReference<String> imageIdRef = new AtomicReference<>();
        DescribeImagesPublisher paginator = getAsyncClient().describeImagesPaginator(imagesRequest);
        return paginator.subscribe(response -> {
            response.images().stream()
                .filter(image -> image.imageId().equals(imageId))
                .findFirst()
                .ifPresent(image -> {
                    logger.info("The description of the image is " + image.description());
                    logger.info("The name of the image is " + image.name());
                    imageIdRef.set(image.imageId());
                });
        }).thenApply(v -> {
            String id = imageIdRef.get();
            if (id == null) {
                throw new RuntimeException("No images found with the provided image ID.");
            }
            return id;
        }).exceptionally(ex -> {
            logger.info("Failed to describe image: " + ex.getMessage());
            throw new RuntimeException("Failed to describe image", ex);
        });
    }

    /**
     * Retrieves the parameter values asynchronously using the AWS Systems Manager (SSM) API.
     *
     * @return a {@link CompletableFuture} that holds the response from the SSM API call to get parameters by path
     */
    public CompletableFuture<GetParametersByPathResponse> getParaValuesAsync() {
        SsmAsyncClient ssmClient = SsmAsyncClient.builder()
            .region(Region.US_EAST_1)
            .build();

        GetParametersByPathRequest parameterRequest = GetParametersByPathRequest.builder()
            .path("/aws/service/ami-amazon-linux-latest")
            .build();

        // Create a CompletableFuture to hold the final result.
        CompletableFuture<GetParametersByPathResponse> responseFuture = new CompletableFuture<>();
        ssmClient.getParametersByPath(parameterRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    responseFuture.completeExceptionally(new RuntimeException("Failed to get parameters by path", exception));
                } else {
                    responseFuture.complete(response);
                }
            });

        return responseFuture;
    }


    /**
     * Asynchronously describes the security groups for the specified group ID.
     *
     * @param groupName the name of the security group to describe
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     *         of describing the security groups. The future will complete with a
     *         {@link DescribeSecurityGroupsResponse} object that contains the
     *         security group information.
     */
    public CompletableFuture<String> describeSecurityGroupArnByNameAsync(String groupName) {
        DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder()
            .groupNames(groupName)
            .build();

        DescribeSecurityGroupsPublisher paginator = getAsyncClient().describeSecurityGroupsPaginator(request);
        AtomicReference<String> groupIdRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.securityGroups().stream()
                .filter(securityGroup -> securityGroup.groupName().equals(groupName))
                .findFirst()
                .ifPresent(securityGroup -> groupIdRef.set(securityGroup.groupId()));
        }).thenApply(v -> {
            String groupId = groupIdRef.get();
            if (groupId == null) {
                throw new RuntimeException("No security group found with the name: " + groupName);
            }
            return groupId;
        }).exceptionally(ex -> {
            logger.info("Failed to describe security group: " + ex.getMessage());
            throw new RuntimeException("Failed to describe security group", ex);
        });
    }

    /**
     * Creates a new security group asynchronously with the specified group name, description, and VPC ID. It also
     * authorizes inbound traffic on ports 80 and 22 from the specified IP address.
     *
     * @param groupName    the name of the security group to create
     * @param groupDesc    the description of the security group
     * @param vpcId        the ID of the VPC in which to create the security group
     * @param myIpAddress  the IP address from which to allow inbound traffic (e.g., "192.168.1.1/0" to allow traffic from
     *                     any IP address in the 192.168.1.0/24 subnet)
     * @return a CompletableFuture that, when completed, returns the ID of the created security group
     * @throws RuntimeException if there was a failure creating the security group or authorizing the inbound traffic
     */
    public CompletableFuture<String> createSecurityGroupAsync(String groupName, String groupDesc, String vpcId, String myIpAddress) {
        CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder()
            .groupName(groupName)
            .description(groupDesc)
            .vpcId(vpcId)
            .build();

        return getAsyncClient().createSecurityGroup(createRequest)
            .thenCompose(createResponse -> {
                String groupId = createResponse.groupId();
                IpRange ipRange = IpRange.builder()
                    .cidrIp(myIpAddress + "/32")
                    .build();

                IpPermission ipPerm = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(80)
                    .fromPort(80)
                    .ipRanges(ipRange)
                    .build();

                IpPermission ipPerm2 = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(22)
                    .fromPort(22)
                    .ipRanges(ipRange)
                    .build();

                AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder()
                    .groupName(groupName)
                    .ipPermissions(ipPerm, ipPerm2)
                    .build();

                return getAsyncClient().authorizeSecurityGroupIngress(authRequest)
                    .thenApply(authResponse -> groupId);
            })
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    if (exception instanceof CompletionException && exception.getCause() instanceof Ec2Exception) {
                        throw (Ec2Exception) exception.getCause();
                    } else {
                        throw new RuntimeException("Failed to create security group: " + exception.getMessage(), exception);
                    }
                }
            });
    }

    /**
     * Asynchronously describes the key pairs associated with the current AWS account.
     *
     * @return a {@link CompletableFuture} containing the {@link DescribeKeyPairsResponse} object, which provides
     * information about the key pairs.
     */
    public CompletableFuture<DescribeKeyPairsResponse> describeKeysAsync() {
        CompletableFuture<DescribeKeyPairsResponse> responseFuture = getAsyncClient().describeKeyPairs();
        responseFuture.whenComplete((response, exception) -> {
            if (exception != null) {
              throw new RuntimeException("Failed to describe key pairs: " + exception.getMessage(), exception);
            }
        });

        return responseFuture;
    }

    /**
     * Creates a new key pair asynchronously.
     *
     * @param keyName the name of the key pair to create
     * @param fileName the name of the file to write the key material to
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     *         of creating the key pair and writing the key material to a file
     */
    public CompletableFuture<CreateKeyPairResponse> createKeyPairAsync(String keyName, String fileName) {
        CreateKeyPairRequest request = CreateKeyPairRequest.builder()
            .keyName(keyName)
            .build();

        CompletableFuture<CreateKeyPairResponse> responseFuture = getAsyncClient().createKeyPair(request);
        responseFuture.whenComplete((response, exception) -> {
            if (response != null) {
                try {
                    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
                    writer.write(response.keyMaterial());
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException("Failed to write key material to file: " + e.getMessage(), e);
                }
            } else {
                throw new RuntimeException("Failed to create key pair: " + exception.getMessage(), exception);
            }
        });

        return responseFuture;
    }

    /**
     * Describes the first default VPC asynchronously and using a paginator.
     *
     * @return a {@link CompletableFuture} that, when completed, contains the first default VPC found.\
     */
    public CompletableFuture<Vpc> describeFirstEC2VpcAsync() {
        Filter myFilter = Filter.builder()
            .name("is-default")
            .values("true")
            .build();

        DescribeVpcsRequest request = DescribeVpcsRequest.builder()
            .filters(myFilter)
            .build();

        DescribeVpcsPublisher paginator = getAsyncClient().describeVpcsPaginator(request);
        AtomicReference<Vpc> vpcRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.vpcs().stream()
                .findFirst()
                .ifPresent(vpcRef::set);
        }).thenApply(v -> {
            Vpc vpc = vpcRef.get();
            if (vpc == null) {
                throw new RuntimeException("Default VPC not found");
            }
            return vpc;
        }).exceptionally(ex -> {
            logger.info("Failed to describe VPCs: " + ex.getMessage());
            throw new RuntimeException("Failed to describe VPCs", ex);
        });
    }

    /**
     * Stops the EC2 instance with the specified ID asynchronously and waits for the instance to stop.
     *
     * @param instanceId the ID of the EC2 instance to stop
     * @return a {@link CompletableFuture} that completes when the instance has been stopped, or exceptionally if an error occurs
     */
    public CompletableFuture<Void> stopInstanceAsync(String instanceId) {
        StopInstancesRequest stopRequest = StopInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        DescribeInstancesRequest describeRequest = DescribeInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        Ec2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()
            .client(getAsyncClient())
            .build();

        CompletableFuture<Void> resultFuture = new CompletableFuture<>();
        logger.info("Stopping instance " + instanceId + " and waiting for it to stop.");
        getAsyncClient().stopInstances(stopRequest)
            .thenCompose(response -> {
                if (response.stoppingInstances().isEmpty()) {
                    return CompletableFuture.failedFuture(new RuntimeException("No instances were stopped. Please check the instance ID: " + instanceId));
                }
                return ec2Waiter.waitUntilInstanceStopped(describeRequest);
            })
            .thenAccept(waiterResponse -> {
                logger.info("Successfully stopped instance " + instanceId);
                resultFuture.complete(null);
            })
            .exceptionally(throwable -> {
                logger.error("Failed to stop instance " + instanceId + ": " + throwable.getMessage(), throwable);
                resultFuture.completeExceptionally(new RuntimeException("Failed to stop instance: " + throwable.getMessage(), throwable));
                return null;
            });

        return resultFuture;
    }

    /**
     * Starts an Amazon EC2 instance asynchronously and waits until it is in the "running" state.
     *
     * @param instanceId the ID of the instance to start
     * @return a {@link CompletableFuture} that completes when the instance has been started and is in the "running" state, or exceptionally if an error occurs
     */
    public CompletableFuture<Void> startInstanceAsync(String instanceId) {
        StartInstancesRequest startRequest = StartInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        Ec2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()
            .client(getAsyncClient())
            .build();

        DescribeInstancesRequest describeRequest = DescribeInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        logger.info("Starting instance " + instanceId + " and waiting for it to run.");
        CompletableFuture<Void> resultFuture = new CompletableFuture<>();
        return getAsyncClient().startInstances(startRequest)
            .thenCompose(response ->
                ec2Waiter.waitUntilInstanceRunning(describeRequest)
            )
            .thenAccept(waiterResponse -> {
                logger.info("Successfully started instance " + instanceId);
                resultFuture.complete(null);
            })
            .exceptionally(throwable -> {
                resultFuture.completeExceptionally(new RuntimeException("Failed to start instance: " + throwable.getMessage(), throwable));
                return null;
            });
    }

}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AllocateAddress)
  + [AssociateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AssociateAddress)
  + [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AuthorizeSecurityGroupIngress)
  + [CreateKeyPair](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateKeyPair)
  + [CreateSecurityGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateSecurityGroup)
  + [DeleteKeyPair](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteKeyPair)
  + [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteSecurityGroup)
  + [DescribeImages](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeImages)
  + [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstanceTypes)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstances)
  + [DescribeKeyPairs](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeKeyPairs)
  + [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSecurityGroups)
  + [DisassociateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DisassociateAddress)
  + [ReleaseAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/ReleaseAddress)
  + [RunInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/RunInstances)
  + [StartInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/StartInstances)
  + [StopInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/StopInstances)
  + [TerminateInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/TerminateInstances)
  + [UnmonitorInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/UnmonitorInstances)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_java_2_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Allocates an Elastic IP address asynchronously in the VPC domain.
     *
     * @return a {@link CompletableFuture} containing the allocation ID of the allocated Elastic IP address
     */
    public CompletableFuture<String> allocateAddressAsync() {
        AllocateAddressRequest allocateRequest = AllocateAddressRequest.builder()
            .domain(DomainType.VPC)
            .build();

        CompletableFuture<AllocateAddressResponse> responseFuture = getAsyncClient().allocateAddress(allocateRequest);
        return responseFuture.thenApply(AllocateAddressResponse::allocationId).whenComplete((result, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to allocate address", ex);
            }
        });
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[AllocateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AllocateAddress)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_java_2_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Associates an Elastic IP address with an EC2 instance asynchronously.
     *
     * @param instanceId    the ID of the EC2 instance to associate the Elastic IP address with
     * @param allocationId  the allocation ID of the Elastic IP address to associate
     * @return a {@link CompletableFuture} that completes with the association ID when the operation is successful,
     *         or throws a {@link RuntimeException} if the operation fails
     */
    public CompletableFuture<String> associateAddressAsync(String instanceId, String allocationId) {
        AssociateAddressRequest associateRequest = AssociateAddressRequest.builder()
            .instanceId(instanceId)
            .allocationId(allocationId)
            .build();

        CompletableFuture<AssociateAddressResponse> responseFuture = getAsyncClient().associateAddress(associateRequest);
        return responseFuture.thenApply(response -> {
            if (response.associationId() != null) {
                return response.associationId();
            } else {
                throw new RuntimeException("Association ID is null after associating address.");
            }
        }).whenComplete((result, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to associate address", ex);
            }
        });
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[AssociateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AssociateAddress)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_java_2_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new security group asynchronously with the specified group name, description, and VPC ID. It also
     * authorizes inbound traffic on ports 80 and 22 from the specified IP address.
     *
     * @param groupName    the name of the security group to create
     * @param groupDesc    the description of the security group
     * @param vpcId        the ID of the VPC in which to create the security group
     * @param myIpAddress  the IP address from which to allow inbound traffic (e.g., "192.168.1.1/0" to allow traffic from
     *                     any IP address in the 192.168.1.0/24 subnet)
     * @return a CompletableFuture that, when completed, returns the ID of the created security group
     * @throws RuntimeException if there was a failure creating the security group or authorizing the inbound traffic
     */
    public CompletableFuture<String> createSecurityGroupAsync(String groupName, String groupDesc, String vpcId, String myIpAddress) {
        CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder()
            .groupName(groupName)
            .description(groupDesc)
            .vpcId(vpcId)
            .build();

        return getAsyncClient().createSecurityGroup(createRequest)
            .thenCompose(createResponse -> {
                String groupId = createResponse.groupId();
                IpRange ipRange = IpRange.builder()
                    .cidrIp(myIpAddress + "/32")
                    .build();

                IpPermission ipPerm = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(80)
                    .fromPort(80)
                    .ipRanges(ipRange)
                    .build();

                IpPermission ipPerm2 = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(22)
                    .fromPort(22)
                    .ipRanges(ipRange)
                    .build();

                AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder()
                    .groupName(groupName)
                    .ipPermissions(ipPerm, ipPerm2)
                    .build();

                return getAsyncClient().authorizeSecurityGroupIngress(authRequest)
                    .thenApply(authResponse -> groupId);
            })
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    if (exception instanceof CompletionException && exception.getCause() instanceof Ec2Exception) {
                        throw (Ec2Exception) exception.getCause();
                    } else {
                        throw new RuntimeException("Failed to create security group: " + exception.getMessage(), exception);
                    }
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/AuthorizeSecurityGroupIngress)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_java_2_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new key pair asynchronously.
     *
     * @param keyName the name of the key pair to create
     * @param fileName the name of the file to write the key material to
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     *         of creating the key pair and writing the key material to a file
     */
    public CompletableFuture<CreateKeyPairResponse> createKeyPairAsync(String keyName, String fileName) {
        CreateKeyPairRequest request = CreateKeyPairRequest.builder()
            .keyName(keyName)
            .build();

        CompletableFuture<CreateKeyPairResponse> responseFuture = getAsyncClient().createKeyPair(request);
        responseFuture.whenComplete((response, exception) -> {
            if (response != null) {
                try {
                    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
                    writer.write(response.keyMaterial());
                    writer.close();
                } catch (IOException e) {
                    throw new RuntimeException("Failed to write key material to file: " + e.getMessage(), e);
                }
            } else {
                throw new RuntimeException("Failed to create key pair: " + exception.getMessage(), exception);
            }
        });

        return responseFuture;
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[CreateKeyPair](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateKeyPair)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_java_2_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new security group asynchronously with the specified group name, description, and VPC ID. It also
     * authorizes inbound traffic on ports 80 and 22 from the specified IP address.
     *
     * @param groupName    the name of the security group to create
     * @param groupDesc    the description of the security group
     * @param vpcId        the ID of the VPC in which to create the security group
     * @param myIpAddress  the IP address from which to allow inbound traffic (e.g., "192.168.1.1/0" to allow traffic from
     *                     any IP address in the 192.168.1.0/24 subnet)
     * @return a CompletableFuture that, when completed, returns the ID of the created security group
     * @throws RuntimeException if there was a failure creating the security group or authorizing the inbound traffic
     */
    public CompletableFuture<String> createSecurityGroupAsync(String groupName, String groupDesc, String vpcId, String myIpAddress) {
        CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder()
            .groupName(groupName)
            .description(groupDesc)
            .vpcId(vpcId)
            .build();

        return getAsyncClient().createSecurityGroup(createRequest)
            .thenCompose(createResponse -> {
                String groupId = createResponse.groupId();
                IpRange ipRange = IpRange.builder()
                    .cidrIp(myIpAddress + "/32")
                    .build();

                IpPermission ipPerm = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(80)
                    .fromPort(80)
                    .ipRanges(ipRange)
                    .build();

                IpPermission ipPerm2 = IpPermission.builder()
                    .ipProtocol("tcp")
                    .toPort(22)
                    .fromPort(22)
                    .ipRanges(ipRange)
                    .build();

                AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder()
                    .groupName(groupName)
                    .ipPermissions(ipPerm, ipPerm2)
                    .build();

                return getAsyncClient().authorizeSecurityGroupIngress(authRequest)
                    .thenApply(authResponse -> groupId);
            })
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    if (exception instanceof CompletionException && exception.getCause() instanceof Ec2Exception) {
                        throw (Ec2Exception) exception.getCause();
                    } else {
                        throw new RuntimeException("Failed to create security group: " + exception.getMessage(), exception);
                    }
                }
            });
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[CreateSecurityGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateSecurityGroup)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_java_2_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a key pair asynchronously.
     *
     * @param keyPair the name of the key pair to delete
     * @return a {@link CompletableFuture} that represents the result of the asynchronous operation.
     *         The {@link CompletableFuture} will complete with a {@link DeleteKeyPairResponse} object
     *         that provides the result of the key pair deletion operation.
     */
    public CompletableFuture<DeleteKeyPairResponse> deleteKeysAsync(String keyPair) {
        DeleteKeyPairRequest request = DeleteKeyPairRequest.builder()
            .keyName(keyPair)
            .build();

        // Initiate the asynchronous request to delete the key pair.
        CompletableFuture<DeleteKeyPairResponse> response = getAsyncClient().deleteKeyPair(request);
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete key pair: " + keyPair, ex);
            } else if (resp == null) {
                throw new RuntimeException("No response received for deleting key pair: " + keyPair);
            }
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteKeyPair](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteKeyPair)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_java_2_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an EC2 security group asynchronously.
     *
     * @param groupId the ID of the security group to delete
     * @return a CompletableFuture that completes when the security group is deleted
     */
    public CompletableFuture<Void> deleteEC2SecGroupAsync(String groupId) {
        DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder()
            .groupId(groupId)
            .build();

        CompletableFuture<DeleteSecurityGroupResponse> response = getAsyncClient().deleteSecurityGroup(request);
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to delete security group with Id " + groupId, ex);
            } else if (resp == null) {
                throw new RuntimeException("No response received for deleting security group with Id " + groupId);
            }
        }).thenApply(resp -> null);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteSecurityGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteSecurityGroup)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_java_2_topic"></a>

次のコード例は、`DescribeInstanceTypes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously retrieves the instance types available in the current AWS region.
     * <p>
     * This method uses the AWS SDK's asynchronous API to fetch the available instance types
     * and then processes the response. It logs the memory information, network information,
     * and instance type for each instance type returned. Additionally, it returns a
     * {@link CompletableFuture} that resolves to the instance type string for the "t2.2xlarge"
     * instance type, if it is found in the response. If the "t2.2xlarge" instance type is not
     * found, an empty string is returned.
     * </p>
     *
     * @return a {@link CompletableFuture} that resolves to the instance type string for the
     * "t2.2xlarge" instance type, or an empty string if the instance type is not found
     */
    public CompletableFuture<String> getInstanceTypesAsync() {
        DescribeInstanceTypesRequest typesRequest = DescribeInstanceTypesRequest.builder()
            .maxResults(10)
            .build();

        CompletableFuture<DescribeInstanceTypesResponse> response = getAsyncClient().describeInstanceTypes(typesRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                List<InstanceTypeInfo> instanceTypes = resp.instanceTypes();
                for (InstanceTypeInfo type : instanceTypes) {
                    logger.info("The memory information of this type is " + type.memoryInfo().sizeInMiB());
                    logger.info("Network information is " + type.networkInfo().toString());
                    logger.info("Instance type is " + type.instanceType().toString());
                }
            } else {
                throw (RuntimeException) ex;
            }
        });

        return response.thenApply(resp -> {
            for (InstanceTypeInfo type : resp.instanceTypes()) {
                String instanceType = type.instanceType().toString();
                if (instanceType.equals("t2.2xlarge")) {
                    return instanceType;
                }
            }
            return "";
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeInstanceTypes](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstanceTypes)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_java_2_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously describes the state of an EC2 instance.
     * The paginator helps you iterate over multiple pages of results.
     *
     * @param newInstanceId the ID of the EC2 instance to describe
     * @return a {@link CompletableFuture} that, when completed, contains a string describing the state of the EC2 instance
     */
    public CompletableFuture<String> describeEC2InstancesAsync(String newInstanceId) {
        DescribeInstancesRequest request = DescribeInstancesRequest.builder()
            .instanceIds(newInstanceId)
            .build();

        DescribeInstancesPublisher paginator = getAsyncClient().describeInstancesPaginator(request);
        AtomicReference<String> publicIpAddressRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.reservations().stream()
                .flatMap(reservation -> reservation.instances().stream())
                .filter(instance -> instance.instanceId().equals(newInstanceId))
                .findFirst()
                .ifPresent(instance -> publicIpAddressRef.set(instance.publicIpAddress()));
        }).thenApply(v -> {
            String publicIpAddress = publicIpAddressRef.get();
            if (publicIpAddress == null) {
                throw new RuntimeException("Instance with ID " + newInstanceId + " not found.");
            }
            return publicIpAddress;
        }).exceptionally(ex -> {
            logger.info("Failed to describe instances: " + ex.getMessage());
            throw new RuntimeException("Failed to describe instances", ex);
        });
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[DescribeInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstances)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_java_2_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously describes the key pairs associated with the current AWS account.
     *
     * @return a {@link CompletableFuture} containing the {@link DescribeKeyPairsResponse} object, which provides
     * information about the key pairs.
     */
    public CompletableFuture<DescribeKeyPairsResponse> describeKeysAsync() {
        CompletableFuture<DescribeKeyPairsResponse> responseFuture = getAsyncClient().describeKeyPairs();
        responseFuture.whenComplete((response, exception) -> {
            if (exception != null) {
              throw new RuntimeException("Failed to describe key pairs: " + exception.getMessage(), exception);
            }
        });

        return responseFuture;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeKeyPairs](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeKeyPairs)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_java_2_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously describes the security groups for the specified group ID.
     *
     * @param groupName the name of the security group to describe
     * @return a {@link CompletableFuture} that represents the asynchronous operation
     *         of describing the security groups. The future will complete with a
     *         {@link DescribeSecurityGroupsResponse} object that contains the
     *         security group information.
     */
    public CompletableFuture<String> describeSecurityGroupArnByNameAsync(String groupName) {
        DescribeSecurityGroupsRequest request = DescribeSecurityGroupsRequest.builder()
            .groupNames(groupName)
            .build();

        DescribeSecurityGroupsPublisher paginator = getAsyncClient().describeSecurityGroupsPaginator(request);
        AtomicReference<String> groupIdRef = new AtomicReference<>();
        return paginator.subscribe(response -> {
            response.securityGroups().stream()
                .filter(securityGroup -> securityGroup.groupName().equals(groupName))
                .findFirst()
                .ifPresent(securityGroup -> groupIdRef.set(securityGroup.groupId()));
        }).thenApply(v -> {
            String groupId = groupIdRef.get();
            if (groupId == null) {
                throw new RuntimeException("No security group found with the name: " + groupName);
            }
            return groupId;
        }).exceptionally(ex -> {
            logger.info("Failed to describe security group: " + ex.getMessage());
            throw new RuntimeException("Failed to describe security group", ex);
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_java_2_topic"></a>

次のコード例は、`DisassociateAddress` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Disassociates an Elastic IP address from an instance asynchronously.
     *
     * @param associationId The ID of the association you want to disassociate.
     * @return a {@link CompletableFuture} representing the asynchronous operation of disassociating the address. The
     *         {@link CompletableFuture} will complete with a {@link DisassociateAddressResponse} when the operation is
     *         finished.
     * @throws RuntimeException if the disassociation of the address fails.
     */
    public CompletableFuture<DisassociateAddressResponse> disassociateAddressAsync(String associationId) {
        Ec2AsyncClient ec2 = getAsyncClient();
        DisassociateAddressRequest addressRequest = DisassociateAddressRequest.builder()
            .associationId(associationId)
            .build();

        // Disassociate the address asynchronously.
        CompletableFuture<DisassociateAddressResponse> response = ec2.disassociateAddress(addressRequest);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
               throw new RuntimeException("Failed to disassociate address", ex);
            }
        });

        return response;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DisassociateAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DisassociateAddress)」を参照してください。

### `GetPasswordData`
<a name="ec2_GetPasswordData_java_2_topic"></a>

次のコード例は、`GetPasswordData` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ec2.Ec2AsyncClient;
import software.amazon.awssdk.services.ec2.model.*;
import java.util.concurrent.CompletableFuture;

/**
 * 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 GetPasswordData {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                   <instanceId> 

                Where:
                   instanceId - An instance id value that you can obtain from the AWS Management Console.\s
             """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
        String instanceId = args[0];
        Ec2AsyncClient ec2AsyncClient = Ec2AsyncClient.builder()
            .region(Region.US_EAST_1)
            .build();

        try {
            CompletableFuture<Void> future = getPasswordDataAsync(ec2AsyncClient, instanceId);
            future.join();
        } catch (RuntimeException rte) {
            System.err.println("An exception occurred: " + (rte.getCause() != null ? rte.getCause().getMessage() : rte.getMessage()));
        }
    }

    /**
     * Fetches the password data for the specified EC2 instance asynchronously.
     *
     * @param ec2AsyncClient the EC2 asynchronous client to use for the request
     * @param instanceId instanceId the ID of the EC2 instance for which you want to fetch the password data
     * @return a {@link CompletableFuture} that completes when the password data has been fetched
     * @throws RuntimeException if there was a failure in fetching the password data
     */
    public static CompletableFuture<Void> getPasswordDataAsync(Ec2AsyncClient ec2AsyncClient, String instanceId) {
        GetPasswordDataRequest getPasswordDataRequest = GetPasswordDataRequest.builder()
            .instanceId(instanceId)
            .build();


        CompletableFuture<GetPasswordDataResponse> response = ec2AsyncClient.getPasswordData(getPasswordDataRequest);
        response.whenComplete((getPasswordDataResponse, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to get password data for instance: " + instanceId, ex);
            } else if (getPasswordDataResponse == null || getPasswordDataResponse.passwordData().isEmpty()) {
                throw new RuntimeException("No password data found for instance: " + instanceId);
            } else {
                String encryptedPasswordData = getPasswordDataResponse.passwordData();
                System.out.println("Encrypted Password Data: " + encryptedPasswordData);
            }
        });

        return response.thenApply(resp -> null);
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetPasswordData](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/GetPasswordData)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_java_2_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Releases an Elastic IP address asynchronously.
     *
     * @param allocId the allocation ID of the Elastic IP address to be released
     * @return a {@link CompletableFuture} representing the asynchronous operation of releasing the Elastic IP address
     */
    public CompletableFuture<ReleaseAddressResponse> releaseEC2AddressAsync(String allocId) {
        ReleaseAddressRequest request = ReleaseAddressRequest.builder()
            .allocationId(allocId)
            .build();

        CompletableFuture<ReleaseAddressResponse> response = getAsyncClient().releaseAddress(request);
        response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to release Elastic IP address", ex);
            }
        });

        return response;
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[ReleaseAddress](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/ReleaseAddress)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_java_2_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Runs an EC2 instance asynchronously.
     *
     * @param instanceType The instance type to use for the EC2 instance.
     * @param keyName The name of the key pair to associate with the EC2 instance.
     * @param groupName The name of the security group to associate with the EC2 instance.
     * @param amiId The ID of the Amazon Machine Image (AMI) to use for the EC2 instance.
     * @return A {@link CompletableFuture} that completes with the ID of the started EC2 instance.
     * @throws RuntimeException If there is an error running the EC2 instance.
     */
    public CompletableFuture<String> runInstanceAsync(String instanceType, String keyName, String groupName, String amiId) {
        RunInstancesRequest runRequest = RunInstancesRequest.builder()
            .instanceType(instanceType)
            .keyName(keyName)
            .securityGroups(groupName)
            .maxCount(1)
            .minCount(1)
            .imageId(amiId)
            .build();

        CompletableFuture<RunInstancesResponse> responseFuture = getAsyncClient().runInstances(runRequest);
        return responseFuture.thenCompose(response -> {
            String instanceIdVal = response.instances().get(0).instanceId();
            System.out.println("Going to start an EC2 instance and use a waiter to wait for it to be in running state");
            return getAsyncClient().waiter()
                .waitUntilInstanceExists(r -> r.instanceIds(instanceIdVal))
                .thenCompose(waitResponse -> getAsyncClient().waiter()
                    .waitUntilInstanceRunning(r -> r.instanceIds(instanceIdVal))
                    .thenApply(runningResponse -> instanceIdVal));
        }).exceptionally(throwable -> {
            // Handle any exceptions that occurred during the async call
            throw new RuntimeException("Failed to run EC2 instance: " + throwable.getMessage(), throwable);
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[RunInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/RunInstances)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_java_2_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Starts an Amazon EC2 instance asynchronously and waits until it is in the "running" state.
     *
     * @param instanceId the ID of the instance to start
     * @return a {@link CompletableFuture} that completes when the instance has been started and is in the "running" state, or exceptionally if an error occurs
     */
    public CompletableFuture<Void> startInstanceAsync(String instanceId) {
        StartInstancesRequest startRequest = StartInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        Ec2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()
            .client(getAsyncClient())
            .build();

        DescribeInstancesRequest describeRequest = DescribeInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        logger.info("Starting instance " + instanceId + " and waiting for it to run.");
        CompletableFuture<Void> resultFuture = new CompletableFuture<>();
        return getAsyncClient().startInstances(startRequest)
            .thenCompose(response ->
                ec2Waiter.waitUntilInstanceRunning(describeRequest)
            )
            .thenAccept(waiterResponse -> {
                logger.info("Successfully started instance " + instanceId);
                resultFuture.complete(null);
            })
            .exceptionally(throwable -> {
                resultFuture.completeExceptionally(new RuntimeException("Failed to start instance: " + throwable.getMessage(), throwable));
                return null;
            });
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[StartInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/StartInstances)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_java_2_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Stops the EC2 instance with the specified ID asynchronously and waits for the instance to stop.
     *
     * @param instanceId the ID of the EC2 instance to stop
     * @return a {@link CompletableFuture} that completes when the instance has been stopped, or exceptionally if an error occurs
     */
    public CompletableFuture<Void> stopInstanceAsync(String instanceId) {
        StopInstancesRequest stopRequest = StopInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        DescribeInstancesRequest describeRequest = DescribeInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        Ec2AsyncWaiter ec2Waiter = Ec2AsyncWaiter.builder()
            .client(getAsyncClient())
            .build();

        CompletableFuture<Void> resultFuture = new CompletableFuture<>();
        logger.info("Stopping instance " + instanceId + " and waiting for it to stop.");
        getAsyncClient().stopInstances(stopRequest)
            .thenCompose(response -> {
                if (response.stoppingInstances().isEmpty()) {
                    return CompletableFuture.failedFuture(new RuntimeException("No instances were stopped. Please check the instance ID: " + instanceId));
                }
                return ec2Waiter.waitUntilInstanceStopped(describeRequest);
            })
            .thenAccept(waiterResponse -> {
                logger.info("Successfully stopped instance " + instanceId);
                resultFuture.complete(null);
            })
            .exceptionally(throwable -> {
                logger.error("Failed to stop instance " + instanceId + ": " + throwable.getMessage(), throwable);
                resultFuture.completeExceptionally(new RuntimeException("Failed to stop instance: " + throwable.getMessage(), throwable));
                return null;
            });

        return resultFuture;
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[StopInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/StopInstances)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_java_2_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Terminates an EC2 instance asynchronously and waits for it to reach the terminated state.
     *
     * @param instanceId the ID of the EC2 instance to terminate
     * @return a {@link CompletableFuture} that completes when the instance has been terminated
     * @throws RuntimeException if there is no response from the AWS SDK or if there is a failure during the termination process
     */
    public CompletableFuture<Object> terminateEC2Async(String instanceId) {
        TerminateInstancesRequest terminateRequest = TerminateInstancesRequest.builder()
            .instanceIds(instanceId)
            .build();

        CompletableFuture<TerminateInstancesResponse> responseFuture = getAsyncClient().terminateInstances(terminateRequest);
        return responseFuture.thenCompose(terminateResponse -> {
            if (terminateResponse == null) {
                throw new RuntimeException("No response received for terminating instance " + instanceId);
            }
            System.out.println("Going to terminate an EC2 instance and use a waiter to wait for it to be in terminated state");
            return getAsyncClient().waiter()
                .waitUntilInstanceTerminated(r -> r.instanceIds(instanceId))
                .thenApply(waiterResponse -> null);
        }).exceptionally(throwable -> {
            // Handle any exceptions that occurred during the async call
            throw new RuntimeException("Failed to terminate EC2 instance: " + throwable.getMessage(), throwable);
        });
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[TerminateInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/TerminateInstances)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_java_2_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
public class Main {

    public static final String fileName = "C:\\AWS\\resworkflow\\recommendations.json"; // Modify file location.
    public static final String tableName = "doc-example-recommendation-service";
    public static final String startScript = "C:\\AWS\\resworkflow\\server_startup_script.sh"; // Modify file location.
    public static final String policyFile = "C:\\AWS\\resworkflow\\instance_policy.json"; // Modify file location.
    public static final String ssmJSON = "C:\\AWS\\resworkflow\\ssm_only_policy.json"; // Modify file location.
    public static final String failureResponse = "doc-example-resilient-architecture-failure-response";
    public static final String healthCheck = "doc-example-resilient-architecture-health-check";
    public static final String templateName = "doc-example-resilience-template";
    public static final String roleName = "doc-example-resilience-role";
    public static final String policyName = "doc-example-resilience-pol";
    public static final String profileName = "doc-example-resilience-prof";

    public static final String badCredsProfileName = "doc-example-resilience-prof-bc";

    public static final String targetGroupName = "doc-example-resilience-tg";
    public static final String autoScalingGroupName = "doc-example-resilience-group";
    public static final String lbName = "doc-example-resilience-lb";
    public static final String protocol = "HTTP";
    public static final int port = 80;

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner in = new Scanner(System.in);
        Database database = new Database();
        AutoScaler autoScaler = new AutoScaler();
        LoadBalancer loadBalancer = new LoadBalancer();

        System.out.println(DASHES);
        System.out.println("Welcome to the demonstration of How to Build and Manage a Resilient Service!");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("A - SETUP THE RESOURCES");
        System.out.println("Press Enter when you're ready to start deploying resources.");
        in.nextLine();
        deploy(loadBalancer);
        System.out.println(DASHES);
        System.out.println(DASHES);
        System.out.println("B - DEMO THE RESILIENCE FUNCTIONALITY");
        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        demo(loadBalancer);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("C - DELETE THE RESOURCES");
        System.out.println("""
                This concludes the demo of how to build and manage a resilient service.
                To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources
                that were created for this demo.
                """);

        System.out.println("\n Do you want to delete the resources (y/n)? ");
        String userInput = in.nextLine().trim().toLowerCase(); // Capture user input

        if (userInput.equals("y")) {
            // Delete resources here
            deleteResources(loadBalancer, autoScaler, database);
            System.out.println("Resources deleted.");
        } else {
            System.out.println("""
                    Okay, we'll leave the resources intact.
                    Don't forget to delete them when you're done with them or you might incur unexpected charges.
                    """);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The example has completed. ");
        System.out.println("\n Thanks for watching!");
        System.out.println(DASHES);
    }

    // Deletes the AWS resources used in this example.
    private static void deleteResources(LoadBalancer loadBalancer, AutoScaler autoScaler, Database database)
            throws IOException, InterruptedException {
        loadBalancer.deleteLoadBalancer(lbName);
        System.out.println("*** Wait 30 secs for resource to be deleted");
        TimeUnit.SECONDS.sleep(30);
        loadBalancer.deleteTargetGroup(targetGroupName);
        autoScaler.deleteAutoScaleGroup(autoScalingGroupName);
        autoScaler.deleteRolesPolicies(policyName, roleName, profileName);
        autoScaler.deleteTemplate(templateName);
        database.deleteTable(tableName);
    }

    private static void deploy(LoadBalancer loadBalancer) throws InterruptedException, IOException {
        Scanner in = new Scanner(System.in);
        System.out.println(
                """
                        For this demo, we'll use the AWS SDK for Java (v2) to create several AWS resources
                        to set up a load-balanced web service endpoint and explore some ways to make it resilient
                        against various kinds of failures.

                        Some of the resources create by this demo are:
                        \t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.
                        \t* An EC2 launch template that defines EC2 instances that each contain a Python web server.
                        \t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.
                        \t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.
                        """);

        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating and populating a DynamoDB table named " + tableName);
        Database database = new Database();
        database.createTable(tableName, fileName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an EC2 launch template that runs '{startup_script}' when an instance starts.
                This script starts a Python web server defined in the `server.py` script. The web server
                listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.
                For demo purposes, this server is run as the root user. In production, the best practice is to
                run a web server, such as Apache, with least-privileged credentials.

                The template also defines an IAM policy that each instance uses to assume a role that grants
                permissions to access the DynamoDB recommendation table and Systems Manager parameters
                that control the flow of the demo.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        templateCreator.createTemplate(policyFile, policyName, profileName, startScript, templateName, roleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(
                "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different Availability Zone.");
        System.out.println("*** Wait 30 secs for the VPC to be created");
        TimeUnit.SECONDS.sleep(30);
        AutoScaler autoScaler = new AutoScaler();
        String[] zones = autoScaler.createGroup(3, templateName, autoScalingGroupName);

        System.out.println("""
                At this point, you have EC2 instances created. Once each instance starts, it listens for
                HTTP requests. You can see these instances in the console or continue with the demo.
                Press Enter when you're ready to continue.
                """);

        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating variables that control the flow of the demo.");
        ParameterHelper paramHelper = new ParameterHelper();
        paramHelper.reset();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an Elastic Load Balancing target group and load balancer. The target group
                defines how the load balancer connects to instances. The load balancer provides a
                single endpoint where clients connect and dispatches requests to instances in the group.
                """);

        String vpcId = autoScaler.getDefaultVPC();
        List<Subnet> subnets = autoScaler.getSubnets(vpcId, zones);
        System.out.println("You have retrieved a list with " + subnets.size() + " subnets");
        String targetGroupArn = loadBalancer.createTargetGroup(protocol, port, vpcId, targetGroupName);
        String elbDnsName = loadBalancer.createLoadBalancer(subnets, targetGroupArn, lbName, port, protocol);
        autoScaler.attachLoadBalancerTargetGroup(autoScalingGroupName, targetGroupArn);
        System.out.println("Verifying access to the load balancer endpoint...");
        boolean wasSuccessul = loadBalancer.verifyLoadBalancerEndpoint(elbDnsName);
        if (!wasSuccessul) {
            System.out.println("Couldn't connect to the load balancer, verifying that the port is open...");
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // Create an HTTP GET request to "http://checkip.amazonaws.com"
            HttpGet httpGet = new HttpGet("http://checkip.amazonaws.com");
            try {
                // Execute the request and get the response
                HttpResponse response = httpClient.execute(httpGet);

                // Read the response content.
                String ipAddress = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8).trim();

                // Print the public IP address.
                System.out.println("Public IP Address: " + ipAddress);
                GroupInfo groupInfo = autoScaler.verifyInboundPort(vpcId, port, ipAddress);
                if (!groupInfo.isPortOpen()) {
                    System.out.println("""
                            For this example to work, the default security group for your default VPC must
                            allow access from this computer. You can either add it automatically from this
                            example or add it yourself using the AWS Management Console.
                            """);

                    System.out.println(
                            "Do you want to add a rule to security group " + groupInfo.getGroupName() + " to allow");
                    System.out.println("inbound traffic on port " + port + " from your computer's IP address (y/n) ");
                    String ans = in.nextLine();
                    if ("y".equalsIgnoreCase(ans)) {
                        autoScaler.openInboundPort(groupInfo.getGroupName(), String.valueOf(port), ipAddress);
                        System.out.println("Security group rule added.");
                    } else {
                        System.out.println("No security group rule added.");
                    }
                }

            } catch (AutoScalingException e) {
                e.printStackTrace();
            }
        } else if (wasSuccessul) {
            System.out.println("Your load balancer is ready. You can access it by browsing to:");
            System.out.println("\t http://" + elbDnsName);
        } else {
            System.out.println("Couldn't get a successful response from the load balancer endpoint. Troubleshoot by");
            System.out.println("manually verifying that your VPC and security group are configured correctly and that");
            System.out.println("you can successfully make a GET request to the load balancer.");
        }

        System.out.println("Press Enter when you're ready to continue with the demo.");
        in.nextLine();
    }

    // A method that controls the demo part of the Java program.
    public static void demo(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        ParameterHelper paramHelper = new ParameterHelper();
        System.out.println("Read the ssm_only_policy.json file");
        String ssmOnlyPolicy = readFileAsString(ssmJSON);

        System.out.println("Resetting parameters to starting values for demo.");
        paramHelper.reset();

        System.out.println(
                """
                         This part of the demonstration shows how to toggle different parts of the system
                         to create situations where the web service fails, and shows how using a resilient
                         architecture can keep the web service running in spite of these failures.

                         At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                         The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.
                         The table name is contained in a Systems Manager parameter named self.param_helper.table.
                         To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.
                        """);
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        System.out.println(
                """
                         \nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as
                         healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                        Instead of failing when the recommendation service fails, the web service can return a static response.
                        While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.
                        """);
        paramHelper.put(paramHelper.failureResponse, "static");

        System.out.println("""
                Now, sending a GET request to the load balancer endpoint returns a static response.
                The service still reports as healthy because health checks are still shallow.
                """);
        demoChoices(loadBalancer);

        System.out.println("Let's reinstate the recommendation service.");
        paramHelper.put(paramHelper.tableName, paramHelper.dyntable);

        System.out.println("""
                Let's also substitute bad credentials for one of the instances in the target group so that it can't
                access the DynamoDB recommendation table. We will get an instance id value.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        AutoScaler autoScaler = new AutoScaler();

        // Create a new instance profile based on badCredsProfileName.
        templateCreator.createInstanceProfile(policyFile, policyName, badCredsProfileName, roleName);
        String badInstanceId = autoScaler.getBadInstance(autoScalingGroupName);
        System.out.println("The bad instance id values used for this demo is " + badInstanceId);

        String profileAssociationId = autoScaler.getInstanceProfile(badInstanceId);
        System.out.println("The association Id value is " + profileAssociationId);
        System.out.println("Replacing the profile for instance " + badInstanceId
                + " with a profile that contains bad credentials");
        autoScaler.replaceInstanceProfile(badInstanceId, badCredsProfileName, profileAssociationId);

        System.out.println(
                """
                        Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,
                        depending on which instance is selected by the load balancer.
                        """);

        demoChoices(loadBalancer);

        System.out.println("""
                Let's implement a deep health check. For this demo, a deep health check tests whether
                the web service can access the DynamoDB table that it depends on for recommendations. Note that
                the deep health check is only for ELB routing and not for Auto Scaling instance health.
                This kind of deep health check is not recommended for Auto Scaling instance health, because it
                risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.
                """);

        System.out.println("""
                By implementing deep health checks, the load balancer can detect when one of the instances is failing
                and take that instance out of rotation.
                """);

        paramHelper.put(paramHelper.healthCheck, "deep");

        System.out.println("""
                Now, checking target health indicates that the instance with bad credentials
                is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy
                instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because
                the load balancer takes unhealthy instances out of its rotation.
                """);

        demoChoices(loadBalancer);

        System.out.println(
                """
                        Because the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy
                        instance is to terminate it and let the auto scaler start a new instance to replace it.
                        """);
        autoScaler.terminateInstance(badInstanceId);

        System.out.println("""
                Even while the instance is terminating and the new instance is starting, sending a GET
                request to the web service continues to get a successful recommendation response because
                the load balancer routes requests to the healthy instances. After the replacement instance
                starts and reports as healthy, it is included in the load balancing rotation.
                Note that terminating and replacing an instance typically takes several minutes, during which time you
                can see the changing health check status until the new instance is running and healthy.
                """);

        demoChoices(loadBalancer);
        System.out.println(
                "If the recommendation service fails now, deep health checks mean all instances report as unhealthy.");
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        demoChoices(loadBalancer);
        paramHelper.reset();
    }

    public static void demoChoices(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        String[] actions = {
                "Send a GET request to the load balancer endpoint.",
                "Check the health of load balancer targets.",
                "Go to the next part of the demo."
        };
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("-".repeat(88));
            System.out.println("See the current state of the service by selecting one of the following choices:");
            for (int i = 0; i < actions.length; i++) {
                System.out.println(i + ": " + actions[i]);
            }

            try {
                System.out.print("\nWhich action would you like to take? ");
                int choice = scanner.nextInt();
                System.out.println("-".repeat(88));

                switch (choice) {
                    case 0 -> {
                        System.out.println("Request:\n");
                        System.out.println("GET http://" + loadBalancer.getEndpoint(lbName));
                        CloseableHttpClient httpClient = HttpClients.createDefault();

                        // Create an HTTP GET request to the ELB.
                        HttpGet httpGet = new HttpGet("http://" + loadBalancer.getEndpoint(lbName));

                        // Execute the request and get the response.
                        HttpResponse response = httpClient.execute(httpGet);
                        int statusCode = response.getStatusLine().getStatusCode();
                        System.out.println("HTTP Status Code: " + statusCode);

                        // Display the JSON response
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        reader.close();

                        // Print the formatted JSON response.
                        System.out.println("Full Response:\n");
                        System.out.println(jsonResponse.toString());

                        // Close the HTTP client.
                        httpClient.close();

                    }
                    case 1 -> {
                        System.out.println("\nChecking the health of load balancer targets:\n");
                        List<TargetHealthDescription> health = loadBalancer.checkTargetHealth(targetGroupName);
                        for (TargetHealthDescription target : health) {
                            System.out.printf("\tTarget %s on port %d is %s%n", target.target().id(),
                                    target.target().port(), target.targetHealth().stateAsString());
                        }
                        System.out.println("""
                                Note that it can take a minute or two for the health check to update
                                after changes are made.
                                """);
                    }
                    case 2 -> {
                        System.out.println("\nOkay, let's move on.");
                        System.out.println("-".repeat(88));
                        return; // Exit the method when choice is 2
                    }
                    default -> System.out.println("You must choose a value between 0-2. Please select again.");
                }

            } catch (java.util.InputMismatchException e) {
                System.out.println("Invalid input. Please select again.");
                scanner.nextLine(); // Clear the input buffer.
            }
        }
    }

    public static String readFileAsString(String filePath) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        return new String(bytes);
    }
}
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
public class AutoScaler {

    private static Ec2Client ec2Client;
    private static AutoScalingClient autoScalingClient;
    private static IamClient iamClient;

    private static SsmClient ssmClient;

    private IamClient getIAMClient() {
        if (iamClient == null) {
            iamClient = IamClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return iamClient;
    }

    private SsmClient getSSMClient() {
        if (ssmClient == null) {
            ssmClient = SsmClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ssmClient;
    }

    private Ec2Client getEc2Client() {
        if (ec2Client == null) {
            ec2Client = Ec2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ec2Client;
    }

    private AutoScalingClient getAutoScalingClient() {
        if (autoScalingClient == null) {
            autoScalingClient = AutoScalingClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return autoScalingClient;
    }

    /**
     * Terminates and instances in an EC2 Auto Scaling group. After an instance is
     * terminated, it can no longer be accessed.
     */
    public void terminateInstance(String instanceId) {
        TerminateInstanceInAutoScalingGroupRequest terminateInstanceIRequest = TerminateInstanceInAutoScalingGroupRequest
                .builder()
                .instanceId(instanceId)
                .shouldDecrementDesiredCapacity(false)
                .build();

        getAutoScalingClient().terminateInstanceInAutoScalingGroup(terminateInstanceIRequest);
        System.out.format("Terminated instance %s.", instanceId);
    }

    /**
     * Replaces the profile associated with a running instance. After the profile is
     * replaced, the instance is rebooted to ensure that it uses the new profile.
     * When
     * the instance is ready, Systems Manager is used to restart the Python web
     * server.
     */
    public void replaceInstanceProfile(String instanceId, String newInstanceProfileName, String profileAssociationId)
            throws InterruptedException {
        // Create an IAM instance profile specification.
        software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification iamInstanceProfile = software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification
                .builder()
                .name(newInstanceProfileName) // Make sure 'newInstanceProfileName' is a valid IAM Instance Profile
                                              // name.
                .build();

        // Replace the IAM instance profile association for the EC2 instance.
        ReplaceIamInstanceProfileAssociationRequest replaceRequest = ReplaceIamInstanceProfileAssociationRequest
                .builder()
                .iamInstanceProfile(iamInstanceProfile)
                .associationId(profileAssociationId) // Make sure 'profileAssociationId' is a valid association ID.
                .build();

        try {
            getEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);
            // Handle the response as needed.
        } catch (Ec2Exception e) {
            // Handle exceptions, log, or report the error.
            System.err.println("Error: " + e.getMessage());
        }
        System.out.format("Replaced instance profile for association %s with profile %s.", profileAssociationId,
                newInstanceProfileName);
        TimeUnit.SECONDS.sleep(15);
        boolean instReady = false;
        int tries = 0;

        // Reboot after 60 seconds
        while (!instReady) {
            if (tries % 6 == 0) {
                getEc2Client().rebootInstances(RebootInstancesRequest.builder()
                        .instanceIds(instanceId)
                        .build());
                System.out.println("Rebooting instance " + instanceId + " and waiting for it to be ready.");
            }
            tries++;
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            DescribeInstanceInformationResponse informationResponse = getSSMClient().describeInstanceInformation();
            List<InstanceInformation> instanceInformationList = informationResponse.instanceInformationList();
            for (InstanceInformation info : instanceInformationList) {
                if (info.instanceId().equals(instanceId)) {
                    instReady = true;
                    break;
                }
            }
        }

        SendCommandRequest sendCommandRequest = SendCommandRequest.builder()
                .instanceIds(instanceId)
                .documentName("AWS-RunShellScript")
                .parameters(Collections.singletonMap("commands",
                        Collections.singletonList("cd / && sudo python3 server.py 80")))
                .build();

        getSSMClient().sendCommand(sendCommandRequest);
        System.out.println("Restarted the Python web server on instance " + instanceId + ".");
    }

    public void openInboundPort(String secGroupId, String port, String ipAddress) {
        AuthorizeSecurityGroupIngressRequest ingressRequest = AuthorizeSecurityGroupIngressRequest.builder()
                .groupName(secGroupId)
                .cidrIp(ipAddress)
                .fromPort(Integer.parseInt(port))
                .build();

        getEc2Client().authorizeSecurityGroupIngress(ingressRequest);
        System.out.format("Authorized ingress to %s on port %s from %s.", secGroupId, port, ipAddress);
    }

    /**
     * Detaches a role from an instance profile, detaches policies from the role,
     * and deletes all the resources.
     */
    public void deleteInstanceProfile(String roleName, String profileName) {
        try {
            software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest getInstanceProfileRequest = software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest
                    .builder()
                    .instanceProfileName(profileName)
                    .build();

            GetInstanceProfileResponse response = getIAMClient().getInstanceProfile(getInstanceProfileRequest);
            String name = response.instanceProfile().instanceProfileName();
            System.out.println(name);

            RemoveRoleFromInstanceProfileRequest profileRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .roleName(roleName)
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(profileRequest);
            DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .build();

            getIAMClient().deleteInstanceProfile(deleteInstanceProfileRequest);
            System.out.println("Deleted instance profile " + profileName);

            DeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            // List attached role policies.
            ListAttachedRolePoliciesResponse rolesResponse = getIAMClient()
                    .listAttachedRolePolicies(role -> role.roleName(roleName));
            List<AttachedPolicy> attachedPolicies = rolesResponse.attachedPolicies();
            for (AttachedPolicy attachedPolicy : attachedPolicies) {
                DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
                        .roleName(roleName)
                        .policyArn(attachedPolicy.policyArn())
                        .build();

                getIAMClient().detachRolePolicy(request);
                System.out.println("Detached and deleted policy " + attachedPolicy.policyName());
            }

            getIAMClient().deleteRole(deleteRoleRequest);
            System.out.println("Instance profile and role deleted.");

        } catch (IamException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public void deleteTemplate(String templateName) {
        getEc2Client().deleteLaunchTemplate(name -> name.launchTemplateName(templateName));
        System.out.format(templateName + " was deleted.");
    }

    public void deleteAutoScaleGroup(String groupName) {
        DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder()
                .autoScalingGroupName(groupName)
                .forceDelete(true)
                .build();

        getAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);
        System.out.println(groupName + " was deleted.");
    }

    /*
     * Verify the default security group of the specified VPC allows ingress from
     * this
     * computer. This can be done by allowing ingress from this computer's IP
     * address. In some situations, such as connecting from a corporate network, you
     * must instead specify a prefix list ID. You can also temporarily open the port
     * to
     * any IP address while running this example. If you do, be sure to remove
     * public
     * access when you're done.
     * 
     */
    public GroupInfo verifyInboundPort(String VPC, int port, String ipAddress) {
        boolean portIsOpen = false;
        GroupInfo groupInfo = new GroupInfo();
        try {
            Filter filter = Filter.builder()
                    .name("group-name")
                    .values("default")
                    .build();

            Filter filter1 = Filter.builder()
                    .name("vpc-id")
                    .values(VPC)
                    .build();

            DescribeSecurityGroupsRequest securityGroupsRequest = DescribeSecurityGroupsRequest.builder()
                    .filters(filter, filter1)
                    .build();

            DescribeSecurityGroupsResponse securityGroupsResponse = getEc2Client()
                    .describeSecurityGroups(securityGroupsRequest);
            String securityGroup = securityGroupsResponse.securityGroups().get(0).groupName();
            groupInfo.setGroupName(securityGroup);

            for (SecurityGroup secGroup : securityGroupsResponse.securityGroups()) {
                System.out.println("Found security group: " + secGroup.groupId());

                for (IpPermission ipPermission : secGroup.ipPermissions()) {
                    if (ipPermission.fromPort() == port) {
                        System.out.println("Found inbound rule: " + ipPermission);
                        for (IpRange ipRange : ipPermission.ipRanges()) {
                            String cidrIp = ipRange.cidrIp();
                            if (cidrIp.startsWith(ipAddress) || cidrIp.equals("0.0.0.0/0")) {
                                System.out.println(cidrIp + " is applicable");
                                portIsOpen = true;
                            }
                        }

                        if (!ipPermission.prefixListIds().isEmpty()) {
                            System.out.println("Prefix lList is applicable");
                            portIsOpen = true;
                        }

                        if (!portIsOpen) {
                            System.out
                                    .println("The inbound rule does not appear to be open to either this computer's IP,"
                                            + " all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                        } else {
                            break;
                        }
                    }
                }
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }

        groupInfo.setPortOpen(portIsOpen);
        return groupInfo;
    }

    /*
     * Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto
     * Scaling group.
     * The target group specifies how the load balancer forward requests to the
     * instances
     * in the group.
     */
    public void attachLoadBalancerTargetGroup(String asGroupName, String targetGroupARN) {
        try {
            AttachLoadBalancerTargetGroupsRequest targetGroupsRequest = AttachLoadBalancerTargetGroupsRequest.builder()
                    .autoScalingGroupName(asGroupName)
                    .targetGroupARNs(targetGroupARN)
                    .build();

            getAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);
            System.out.println("Attached load balancer to " + asGroupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Creates an EC2 Auto Scaling group with the specified size.
    public String[] createGroup(int groupSize, String templateName, String autoScalingGroupName) {

        // Get availability zones.
        software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest zonesRequest = software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest
                .builder()
                .build();

        DescribeAvailabilityZonesResponse zonesResponse = getEc2Client().describeAvailabilityZones(zonesRequest);
        List<String> availabilityZoneNames = zonesResponse.availabilityZones().stream()
                .map(software.amazon.awssdk.services.ec2.model.AvailabilityZone::zoneName)
                .collect(Collectors.toList());

        String availabilityZones = String.join(",", availabilityZoneNames);
        LaunchTemplateSpecification specification = LaunchTemplateSpecification.builder()
                .launchTemplateName(templateName)
                .version("$Default")
                .build();

        String[] zones = availabilityZones.split(",");
        CreateAutoScalingGroupRequest groupRequest = CreateAutoScalingGroupRequest.builder()
                .launchTemplate(specification)
                .availabilityZones(zones)
                .maxSize(groupSize)
                .minSize(groupSize)
                .autoScalingGroupName(autoScalingGroupName)
                .build();

        try {
            getAutoScalingClient().createAutoScalingGroup(groupRequest);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Created an EC2 Auto Scaling group named " + autoScalingGroupName);
        return zones;
    }

    public String getDefaultVPC() {
        // Define the filter.
        Filter defaultFilter = Filter.builder()
                .name("is-default")
                .values("true")
                .build();

        software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest request = software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest
                .builder()
                .filters(defaultFilter)
                .build();

        DescribeVpcsResponse response = getEc2Client().describeVpcs(request);
        return response.vpcs().get(0).vpcId();
    }

    // Gets the default subnets in a VPC for a specified list of Availability Zones.
    public List<Subnet> getSubnets(String vpcId, String[] availabilityZones) {
        List<Subnet> subnets = null;
        Filter vpcFilter = Filter.builder()
                .name("vpc-id")
                .values(vpcId)
                .build();

        Filter azFilter = Filter.builder()
                .name("availability-zone")
                .values(availabilityZones)
                .build();

        Filter defaultForAZ = Filter.builder()
                .name("default-for-az")
                .values("true")
                .build();

        DescribeSubnetsRequest request = DescribeSubnetsRequest.builder()
                .filters(vpcFilter, azFilter, defaultForAZ)
                .build();

        DescribeSubnetsResponse response = getEc2Client().describeSubnets(request);
        subnets = response.subnets();
        return subnets;
    }

    // Gets data about the instances in the EC2 Auto Scaling group.
    public String getBadInstance(String groupName) {
        DescribeAutoScalingGroupsRequest request = DescribeAutoScalingGroupsRequest.builder()
                .autoScalingGroupNames(groupName)
                .build();

        DescribeAutoScalingGroupsResponse response = getAutoScalingClient().describeAutoScalingGroups(request);
        AutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);
        List<String> instanceIds = autoScalingGroup.instances().stream()
                .map(instance -> instance.instanceId())
                .collect(Collectors.toList());

        String[] instanceIdArray = instanceIds.toArray(new String[0]);
        for (String instanceId : instanceIdArray) {
            System.out.println("Instance ID: " + instanceId);
            return instanceId;
        }
        return "";
    }

    // Gets data about the profile associated with an instance.
    public String getInstanceProfile(String instanceId) {
        Filter filter = Filter.builder()
                .name("instance-id")
                .values(instanceId)
                .build();

        DescribeIamInstanceProfileAssociationsRequest associationsRequest = DescribeIamInstanceProfileAssociationsRequest
                .builder()
                .filters(filter)
                .build();

        DescribeIamInstanceProfileAssociationsResponse response = getEc2Client()
                .describeIamInstanceProfileAssociations(associationsRequest);
        return response.iamInstanceProfileAssociations().get(0).associationId();
    }

    public void deleteRolesPolicies(String policyName, String roleName, String InstanceProfile) {
        ListPoliciesRequest listPoliciesRequest = ListPoliciesRequest.builder().build();
        ListPoliciesResponse listPoliciesResponse = getIAMClient().listPolicies(listPoliciesRequest);
        for (Policy policy : listPoliciesResponse.policies()) {
            if (policy.policyName().equals(policyName)) {
                // List the entities (users, groups, roles) that are attached to the policy.
                software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest listEntitiesRequest = software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest
                        .builder()
                        .policyArn(policy.arn())
                        .build();
                ListEntitiesForPolicyResponse listEntitiesResponse = iamClient
                        .listEntitiesForPolicy(listEntitiesRequest);
                if (!listEntitiesResponse.policyGroups().isEmpty() || !listEntitiesResponse.policyUsers().isEmpty()
                        || !listEntitiesResponse.policyRoles().isEmpty()) {
                    // Detach the policy from any entities it is attached to.
                    DetachRolePolicyRequest detachPolicyRequest = DetachRolePolicyRequest.builder()
                            .policyArn(policy.arn())
                            .roleName(roleName) // Specify the name of the IAM role
                            .build();

                    getIAMClient().detachRolePolicy(detachPolicyRequest);
                    System.out.println("Policy detached from entities.");
                }

                // Now, you can delete the policy.
                DeletePolicyRequest deletePolicyRequest = DeletePolicyRequest.builder()
                        .policyArn(policy.arn())
                        .build();

                getIAMClient().deletePolicy(deletePolicyRequest);
                System.out.println("Policy deleted successfully.");
                break;
            }
        }

        // List the roles associated with the instance profile
        ListInstanceProfilesForRoleRequest listRolesRequest = ListInstanceProfilesForRoleRequest.builder()
                .roleName(roleName)
                .build();

        // Detach the roles from the instance profile
        ListInstanceProfilesForRoleResponse listRolesResponse = iamClient.listInstanceProfilesForRole(listRolesRequest);
        for (software.amazon.awssdk.services.iam.model.InstanceProfile profile : listRolesResponse.instanceProfiles()) {
            RemoveRoleFromInstanceProfileRequest removeRoleRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(InstanceProfile)
                    .roleName(roleName) // Remove the extra dot here
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(removeRoleRequest);
            System.out.println("Role " + roleName + " removed from instance profile " + InstanceProfile);
        }

        // Delete the instance profile after removing all roles
        DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                .instanceProfileName(InstanceProfile)
                .build();

        getIAMClient().deleteInstanceProfile(r -> r.instanceProfileName(InstanceProfile));
        System.out.println(InstanceProfile + " Deleted");
        System.out.println("All roles and policies are deleted.");
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
public class LoadBalancer {
    public ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;

    public ElasticLoadBalancingV2Client getLoadBalancerClient() {
        if (elasticLoadBalancingV2Client == null) {
            elasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }

        return elasticLoadBalancingV2Client;
    }

    // Checks the health of the instances in the target group.
    public List<TargetHealthDescription> checkTargetHealth(String targetGroupName) {
        DescribeTargetGroupsRequest targetGroupsRequest = DescribeTargetGroupsRequest.builder()
                .names(targetGroupName)
                .build();

        DescribeTargetGroupsResponse tgResponse = getLoadBalancerClient().describeTargetGroups(targetGroupsRequest);

        DescribeTargetHealthRequest healthRequest = DescribeTargetHealthRequest.builder()
                .targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())
                .build();

        DescribeTargetHealthResponse healthResponse = getLoadBalancerClient().describeTargetHealth(healthRequest);
        return healthResponse.targetHealthDescriptions();
    }

    // Gets the HTTP endpoint of the load balancer.
    public String getEndpoint(String lbName) {
        DescribeLoadBalancersResponse res = getLoadBalancerClient()
                .describeLoadBalancers(describe -> describe.names(lbName));
        return res.loadBalancers().get(0).dnsName();
    }

    // Deletes a load balancer.
    public void deleteLoadBalancer(String lbName) {
        try {
            // Use a waiter to delete the Load Balancer.
            DescribeLoadBalancersResponse res = getLoadBalancerClient()
                    .describeLoadBalancers(describe -> describe.names(lbName));
            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())
                    .build();

            getLoadBalancerClient().deleteLoadBalancer(
                    builder -> builder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancersDeleted(request);
            waiterResponse.matched().response().ifPresent(System.out::println);

        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(lbName + " was deleted.");
    }

    // Deletes the target group.
    public void deleteTargetGroup(String targetGroupName) {
        try {
            DescribeTargetGroupsResponse res = getLoadBalancerClient()
                    .describeTargetGroups(describe -> describe.names(targetGroupName));
            getLoadBalancerClient()
                    .deleteTargetGroup(builder -> builder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));
        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(targetGroupName + " was deleted.");
    }

    // Verify this computer can successfully send a GET request to the load balancer
    // endpoint.
    public boolean verifyLoadBalancerEndpoint(String elbDnsName) throws IOException, InterruptedException {
        boolean success = false;
        int retries = 3;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // Create an HTTP GET request to the ELB.
        HttpGet httpGet = new HttpGet("http://" + elbDnsName);
        try {
            while ((!success) && (retries > 0)) {
                // Execute the request and get the response.
                HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);
                if (statusCode == 200) {
                    success = true;
                } else {
                    retries--;
                    System.out.println("Got connection error from load balancer endpoint, retrying...");
                    TimeUnit.SECONDS.sleep(15);
                }
            }

        } catch (org.apache.http.conn.HttpHostConnectException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Status.." + success);
        return success;
    }

    /*
     * Creates an Elastic Load Balancing target group. The target group specifies
     * how
     * the load balancer forward requests to instances in the group and how instance
     * health is checked.
     */
    public String createTargetGroup(String protocol, int port, String vpcId, String targetGroupName) {
        CreateTargetGroupRequest targetGroupRequest = CreateTargetGroupRequest.builder()
                .healthCheckPath("/healthcheck")
                .healthCheckTimeoutSeconds(5)
                .port(port)
                .vpcId(vpcId)
                .name(targetGroupName)
                .protocol(protocol)
                .build();

        CreateTargetGroupResponse targetGroupResponse = getLoadBalancerClient().createTargetGroup(targetGroupRequest);
        String targetGroupArn = targetGroupResponse.targetGroups().get(0).targetGroupArn();
        String targetGroup = targetGroupResponse.targetGroups().get(0).targetGroupName();
        System.out.println("The " + targetGroup + " was created with ARN" + targetGroupArn);
        return targetGroupArn;
    }

    /*
     * Creates an Elastic Load Balancing load balancer that uses the specified
     * subnets
     * and forwards requests to the specified target group.
     */
    public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port,
            String protocol) {
        try {
            List<String> subnetIdStrings = subnetIds.stream()
                    .map(Subnet::subnetId)
                    .collect(Collectors.toList());

            CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder()
                    .subnets(subnetIdStrings)
                    .name(lbName)
                    .scheme("internet-facing")
                    .build();

            // Create and wait for the load balancer to become available.
            CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest);
            String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();

            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(lbARN)
                    .build();

            System.out.println("Waiting for Load Balancer " + lbName + " to become available.");
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancerAvailable(request);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Load Balancer " + lbName + " is available.");

            // Get the DNS name (endpoint) of the load balancer.
            String lbDNSName = lsResponse.loadBalancers().get(0).dnsName();
            System.out.println("*** Load Balancer DNS Name: " + lbDNSName);

            // Create a listener for the load balance.
            Action action = Action.builder()
                    .targetGroupArn(targetGroupARN)
                    .type("forward")
                    .build();

            CreateListenerRequest listenerRequest = CreateListenerRequest.builder()
                    .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())
                    .defaultActions(action)
                    .port(port)
                    .protocol(protocol)
                    .build();

            getLoadBalancerClient().createListener(listenerRequest);
            System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group "
                    + targetGroupARN);

            // Return the load balancer DNS name.
            return lbDNSName;

        } catch (ElasticLoadBalancingV2Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
public class Database {

    private static DynamoDbClient dynamoDbClient;

    public static DynamoDbClient getDynamoDbClient() {
        if (dynamoDbClient == null) {
            dynamoDbClient = DynamoDbClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return dynamoDbClient;
    }

    // Checks to see if the Amazon DynamoDB table exists.
    private boolean doesTableExist(String tableName) {
        try {
            // Describe the table and catch any exceptions.
            DescribeTableRequest describeTableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            getDynamoDbClient().describeTable(describeTableRequest);
            System.out.println("Table '" + tableName + "' exists.");
            return true;

        } catch (ResourceNotFoundException e) {
            System.out.println("Table '" + tableName + "' does not exist.");
        } catch (DynamoDbException e) {
            System.err.println("Error checking table existence: " + e.getMessage());
        }
        return false;
    }

    /*
     * Creates a DynamoDB table to use a recommendation service. The table has a
     * hash key named 'MediaType' that defines the type of media recommended, such
     * as
     * Book or Movie, and a range key named 'ItemId' that, combined with the
     * MediaType,
     * forms a unique identifier for the recommended item.
     */
    public void createTable(String tableName, String fileName) throws IOException {
        // First check to see if the table exists.
        boolean doesExist = doesTableExist(tableName);
        if (!doesExist) {
            DynamoDbWaiter dbWaiter = getDynamoDbClient().waiter();
            CreateTableRequest createTableRequest = CreateTableRequest.builder()
                    .tableName(tableName)
                    .attributeDefinitions(
                            AttributeDefinition.builder()
                                    .attributeName("MediaType")
                                    .attributeType(ScalarAttributeType.S)
                                    .build(),
                            AttributeDefinition.builder()
                                    .attributeName("ItemId")
                                    .attributeType(ScalarAttributeType.N)
                                    .build())
                    .keySchema(
                            KeySchemaElement.builder()
                                    .attributeName("MediaType")
                                    .keyType(KeyType.HASH)
                                    .build(),
                            KeySchemaElement.builder()
                                    .attributeName("ItemId")
                                    .keyType(KeyType.RANGE)
                                    .build())
                    .provisionedThroughput(
                            ProvisionedThroughput.builder()
                                    .readCapacityUnits(5L)
                                    .writeCapacityUnits(5L)
                                    .build())
                    .build();

            getDynamoDbClient().createTable(createTableRequest);
            System.out.println("Creating table " + tableName + "...");

            // Wait until the Amazon DynamoDB table is created.
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Table " + tableName + " created.");

            // Add records to the table.
            populateTable(fileName, tableName);
        }
    }

    public void deleteTable(String tableName) {
        getDynamoDbClient().deleteTable(table -> table.tableName(tableName));
        System.out.println("Table " + tableName + " deleted.");
    }

    // Populates the table with data located in a JSON file using the DynamoDB
    // enhanced client.
    public void populateTable(String fileName, String tableName) throws IOException {
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(getDynamoDbClient())
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        File jsonFile = new File(fileName);
        JsonNode rootNode = objectMapper.readTree(jsonFile);

        DynamoDbTable<Recommendation> mappedTable = enhancedClient.table(tableName,
                TableSchema.fromBean(Recommendation.class));
        for (JsonNode currentNode : rootNode) {
            String mediaType = currentNode.path("MediaType").path("S").asText();
            int itemId = currentNode.path("ItemId").path("N").asInt();
            String title = currentNode.path("Title").path("S").asText();
            String creator = currentNode.path("Creator").path("S").asText();

            // Create a Recommendation object and set its properties.
            Recommendation rec = new Recommendation();
            rec.setMediaType(mediaType);
            rec.setItemId(itemId);
            rec.setTitle(title);
            rec.setCreator(creator);

            // Put the item into the DynamoDB table.
            mappedTable.putItem(rec); // Add the Recommendation to the list.
        }
        System.out.println("Added all records to the " + tableName);
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
public class ParameterHelper {

    String tableName = "doc-example-resilient-architecture-table";
    String dyntable = "doc-example-recommendation-service";
    String failureResponse = "doc-example-resilient-architecture-failure-response";
    String healthCheck = "doc-example-resilient-architecture-health-check";

    public void reset() {
        put(dyntable, tableName);
        put(failureResponse, "none");
        put(healthCheck, "shallow");
    }

    public void put(String name, String value) {
        SsmClient ssmClient = SsmClient.builder()
                .region(Region.US_EAST_1)
                .build();

        PutParameterRequest parameterRequest = PutParameterRequest.builder()
                .name(name)
                .value(value)
                .overwrite(true)
                .type("String")
                .build();

        ssmClient.putParameter(parameterRequest);
        System.out.printf("Setting demo parameter %s to '%s'.", name, value);
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# SDK for Java 2.x を使用する Amazon ECR の例
<a name="java_2_ecr_code_examples"></a>

次のコード例は、Amazon ECR AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon ECR
<a name="ecr_Hello_java_2_topic"></a>

次のコード例は、Amazon ECR の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecr.EcrClient;
import software.amazon.awssdk.services.ecr.model.EcrException;
import software.amazon.awssdk.services.ecr.model.ListImagesRequest;
import software.amazon.awssdk.services.ecr.paginators.ListImagesIterable;

public class HelloECR {

    public static void main(String[] args) {
        final String usage = """
            Usage:    <repositoryName> 

            Where:
               repositoryName - The name of the Amazon ECR repository. 
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String repoName = args[0];
        EcrClient ecrClient = EcrClient.builder()
            .region(Region.US_EAST_1)
            .build();

        listImageTags(ecrClient, repoName);
    }
    public static void listImageTags(EcrClient ecrClient, String repoName){
        ListImagesRequest listImagesPaginator = ListImagesRequest.builder()
            .repositoryName(repoName)
            .build();

        ListImagesIterable imagesIterable = ecrClient.listImagesPaginator(listImagesPaginator);
        imagesIterable.stream()
            .flatMap(r -> r.imageIds().stream())
            .forEach(image -> System.out.println("The docker image tag is: " +image.imageTag()));
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[listImages](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/listImages)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ecr_Scenario_RepositoryManagement_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon ECR リポジトリを作成します。
+ リポジトリポリシーを設定します。
+ リポジトリ URI を取得します。
+ Amazon ECR 認可トークンを取得します。
+ Amazon ECR リポジトリのライフサイクルポリシーを設定します。
+ Docker イメージを Amazon ECR リポジトリにプッシュします。
+ Amazon ECR リポジトリにイメージが存在しているか確認します。
+ アカウントの Amazon ECR リポジトリをリストし、その詳細を取得します。
+ Amazon ECR リポジトリを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。
Amazon ECR 機能を示すインタラクティブなシナリオを実行します。  

```
import software.amazon.awssdk.services.ecr.model.EcrException;
import software.amazon.awssdk.services.ecr.model.RepositoryPolicyNotFoundException;

import java.util.Scanner;

/**
 * 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
 *
 * This Java code example requires an IAM Role that has permissions to interact with the Amazon ECR service.
 *
 * To create an IAM role, see:
 *
 * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html
 *
 * This Java scenario example requires a local docker image named echo-text. Without a local image,
 * this Java program will not successfully run. For more information including how to create the local
 * image, see:
 *
 * /scenarios/basics/ecr/README
 *
 */
public class ECRScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    public static void main(String[] args) {
        final String usage = """
            Usage: <iamRoleARN> <accountId>

            Where:
               iamRoleARN - The IAM role ARN that has the necessary permissions to access and manage the Amazon ECR repository.
               accountId - Your AWS account number. 
            """;

        if (args.length != 2) {
            System.out.println(usage);
            return;
        }

        ECRActions ecrActions = new ECRActions();
        String iamRole = args[0];
        String accountId = args[1];
        String localImageName;

        Scanner scanner = new Scanner(System.in);
        System.out.println("""
             The Amazon Elastic Container Registry (ECR) is a fully-managed Docker container registry 
             service provided by AWS. It allows developers and organizations to securely 
             store, manage, and deploy Docker container images. 
             ECR provides a simple and scalable way to manage container images throughout their lifecycle, 
             from building and testing to production deployment.\s
                         
             The `EcrAsyncClient` interface in the AWS SDK for Java 2.x provides a set of methods to 
             programmatically interact with the Amazon ECR service. This allows developers to 
             automate the storage, retrieval, and management of container images as part of their application 
             deployment pipelines. With ECR, teams can focus on building and deploying their 
             applications without having to worry about the underlying infrastructure required to 
             host and manage a container registry.
             
            This scenario walks you through how to perform key operations for this service.  
            Let's get started...
                       
            You have two choices:
            1 - Run the entire program.
            2 - Delete an existing Amazon ECR repository named echo-text (created from a previous execution of 
            this program that did not complete).
            """);

        while (true) {
            String input = scanner.nextLine();
            if (input.trim().equalsIgnoreCase("1")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else if (input.trim().equalsIgnoreCase("2")) {
                String repoName = "echo-text";
                ecrActions.deleteECRRepository(repoName);
                return;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }

        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("""
           1. Create an ECR repository.
            
           The first task is to ensure we have a local Docker image named echo-text. 
           If this image exists, then an Amazon ECR repository is created. 
           
           An ECR repository is a private Docker container repository provided 
           by Amazon Web Services (AWS). It is a managed service that makes it easy 
           to store, manage, and deploy Docker container images.\s
           """ );

        // Ensure that a local docker image named echo-text exists.
        boolean doesExist = ecrActions.isEchoTextImagePresent();
        String repoName;
        if (!doesExist){
            System.out.println("The local image named echo-text does not exist");
            return;
        } else {
            localImageName = "echo-text";
            repoName = "echo-text";
        }

        try {
            String repoArn = ecrActions.createECRRepository(repoName);
            System.out.println("The ARN of the ECR repository is " + repoArn);

        } catch (IllegalArgumentException e) {
            System.err.println("Invalid repository name: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("An error occurred while creating the ECR repository: " + e.getMessage());
            e.printStackTrace();
            return;
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("""
        2. Set an ECR repository policy.
        
        Setting an ECR repository policy using the `setRepositoryPolicy` function is crucial for maintaining
        the security and integrity of your container images. The repository policy allows you to 
        define specific rules and restrictions for accessing and managing the images stored within your ECR 
        repository.    
        """);
        waitForInputToContinue(scanner);
        try {
            ecrActions.setRepoPolicy(repoName, iamRole);

        } catch (RepositoryPolicyNotFoundException e) {
            System.err.println("Invalid repository name: " + e.getMessage());
            return;
        } catch (EcrException e) {
            System.err.println("An ECR exception occurred: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("An error occurred while creating the ECR repository: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("""
        3. Display ECR repository policy.
       
        Now we will retrieve the ECR policy to ensure it was successfully set.   
        """);
        waitForInputToContinue(scanner);
        try {
            String policyText = ecrActions.getRepoPolicy(repoName);
            System.out.println("Policy Text:");
            System.out.println(policyText);

        } catch (EcrException e) {
            System.err.println("An ECR exception occurred: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("An error occurred while creating the ECR repository: " + e.getMessage());
            return;
        }

        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("""
        4. Retrieve an ECR authorization token.
       
        You need an authorization token to securely access and interact with the Amazon ECR registry. 
        The `getAuthorizationToken` method of the `EcrAsyncClient` is responsible for securely accessing 
        and interacting with an Amazon ECR repository. This operation is responsible for obtaining a 
        valid authorization token, which is required to authenticate your requests to the ECR service. 
        
        Without a valid authorization token, you would not be able to perform any operations on the 
        ECR repository, such as pushing, pulling, or managing your Docker images.    
        """);
        waitForInputToContinue(scanner);
        try {
             ecrActions.getAuthToken();

        } catch (EcrException e) {
            System.err.println("An ECR exception occurred: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("An error occurred while retrieving the authorization token: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("""
        5. Get the ECR Repository URI.
                    
        The URI  of an Amazon ECR repository is important. When you want to deploy a container image to 
        a container orchestration platform like Amazon Elastic Kubernetes Service (EKS) 
        or Amazon Elastic Container Service (ECS), you need to specify the full image URI, 
        which includes the ECR repository URI. This allows the container runtime to pull the 
        correct container image from the ECR repository.    
       """);
        waitForInputToContinue(scanner);

        try {
            ecrActions.getRepositoryURI(repoName);

        } catch (EcrException e) {
            System.err.println("An ECR exception occurred: " + e.getMessage());
            return;

        } catch (RuntimeException e) {
            System.err.println("An error occurred while retrieving the URI: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("""
            6. Set an ECR Lifecycle Policy.
                        
            An ECR Lifecycle Policy is used to manage the lifecycle of Docker images stored in your ECR repositories. 
            These policies allow you to automatically remove old or unused Docker images from your repositories, 
            freeing up storage space and reducing costs.    
                    
            This example policy helps to maintain the size and efficiency of the container registry
            by automatically removing older and potentially unused images, ensuring that the 
            storage is optimized and the registry remains up-to-date.
            """);
        waitForInputToContinue(scanner);
        try {
            ecrActions.setLifeCyclePolicy(repoName);

        } catch (RuntimeException e) {
            System.err.println("An error occurred while setting the lifecycle policy: " + e.getMessage());
            e.printStackTrace();
            return;
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("""
        7. Push a docker image to the Amazon ECR Repository.
            
        The `pushImageCmd()` method pushes a local Docker image to an Amazon ECR repository.
        It sets up the Docker client by connecting to the local Docker host using the default port.
        It then retrieves the authorization token for the ECR repository by making a call to the AWS SDK.
            
        The method uses the authorization token to create an `AuthConfig` object, which is used to authenticate
        the Docker client when pushing the image. Finally, the method tags the Docker image with the specified
        repository name and image tag, and then pushes the image to the ECR repository using the Docker client.
        If the push operation is successful, the method prints a message indicating that the image was pushed to ECR.
        """);
        waitForInputToContinue(scanner);

        try {
            ecrActions.pushDockerImage(repoName, localImageName);

        } catch (RuntimeException e) {
            System.err.println("An error occurred while pushing a local Docker image to Amazon ECR: " + e.getMessage());
            e.printStackTrace();
            return;
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("8. Verify if the image is in the ECR Repository.");
        waitForInputToContinue(scanner);
        try {
            ecrActions.verifyImage(repoName, localImageName);

        } catch (EcrException e) {
            System.err.println("An ECR exception occurred: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("An error occurred " + e.getMessage());
            e.printStackTrace();
            return;
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("9. As an optional step, you can interact with the image in Amazon ECR by using the CLI.");
        System.out.println("Would you like to view instructions on how to use the CLI to run the image? (y/n)");
        String ans = scanner.nextLine().trim();
        if (ans.equalsIgnoreCase("y")) {
            String instructions = """
            1. Authenticate with ECR - Before you can pull the image from Amazon ECR, you need to authenticate with the registry. You can do this using the AWS CLI:

                aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin %s.dkr.ecr.us-east-1.amazonaws.com

            2. Describe the image using this command:

               aws ecr describe-images --repository-name %s --image-ids imageTag=%s

            3. Run the Docker container and view the output using this command:

               docker run --rm %s.dkr.ecr.us-east-1.amazonaws.com/%s:%s
            """;

            instructions = String.format(instructions, accountId, repoName, localImageName, accountId, repoName, localImageName);
            System.out.println(instructions);
        }
        waitForInputToContinue(scanner);

        System.out.println(DASHES);
        System.out.println("10. Delete the ECR Repository.");
        System.out.println(
        """
        If the repository isn't empty, you must either delete the contents of the repository 
        or use the force option (used in this scenario) to delete the repository and have Amazon ECR delete all of its contents 
        on your behalf.
        """);
        System.out.println("Would you like to delete the Amazon ECR Repository? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            System.out.println("You selected to delete the AWS ECR resources.");

            try {
                ecrActions.deleteECRRepository(repoName);

            } catch (EcrException e) {
                System.err.println("An ECR exception occurred: " + e.getMessage());
                return;
            } catch (RuntimeException e) {
                System.err.println("An error occurred while deleting the Docker image: " + e.getMessage());
                e.printStackTrace();
                return;
            }
        }

        System.out.println(DASHES);
        System.out.println("This concludes the Amazon ECR SDK scenario");
        System.out.println(DASHES);
    }

   private static void waitForInputToContinue(Scanner scanner) {
       while (true) {
           System.out.println("");
           System.out.println("Enter 'c' followed by <ENTER> to continue:");
           String input = scanner.nextLine();

           if (input.trim().equalsIgnoreCase("c")) {
               System.out.println("Continuing with the program...");
               System.out.println("");
               break;
           } else {
               // Handle invalid input.
               System.out.println("Invalid input. Please try again.");
          }
       }
   }
}
```
Amazon ECR SDK メソッドのラッパークラス。  

```
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.exception.DockerClientException;
import com.github.dockerjava.api.model.AuthConfig;
import com.github.dockerjava.api.model.Image;
import com.github.dockerjava.core.DockerClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecr.EcrAsyncClient;
import software.amazon.awssdk.services.ecr.model.AuthorizationData;
import software.amazon.awssdk.services.ecr.model.CreateRepositoryRequest;
import software.amazon.awssdk.services.ecr.model.CreateRepositoryResponse;
import software.amazon.awssdk.services.ecr.model.DeleteRepositoryRequest;
import software.amazon.awssdk.services.ecr.model.DeleteRepositoryResponse;
import software.amazon.awssdk.services.ecr.model.DescribeImagesRequest;
import software.amazon.awssdk.services.ecr.model.DescribeImagesResponse;
import software.amazon.awssdk.services.ecr.model.DescribeRepositoriesRequest;
import software.amazon.awssdk.services.ecr.model.DescribeRepositoriesResponse;
import software.amazon.awssdk.services.ecr.model.EcrException;
import software.amazon.awssdk.services.ecr.model.GetAuthorizationTokenResponse;
import software.amazon.awssdk.services.ecr.model.GetRepositoryPolicyRequest;
import software.amazon.awssdk.services.ecr.model.GetRepositoryPolicyResponse;
import software.amazon.awssdk.services.ecr.model.ImageIdentifier;
import software.amazon.awssdk.services.ecr.model.Repository;
import software.amazon.awssdk.services.ecr.model.RepositoryPolicyNotFoundException;
import software.amazon.awssdk.services.ecr.model.SetRepositoryPolicyRequest;
import software.amazon.awssdk.services.ecr.model.SetRepositoryPolicyResponse;
import software.amazon.awssdk.services.ecr.model.StartLifecyclePolicyPreviewRequest;
import software.amazon.awssdk.services.ecr.model.StartLifecyclePolicyPreviewResponse;
import com.github.dockerjava.api.command.DockerCmdExecFactory;
import com.github.dockerjava.netty.NettyDockerCmdExecFactory;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

public class ECRActions {
    private static EcrAsyncClient ecrClient;

    private static DockerClient dockerClient;

    private static Logger logger = LoggerFactory.getLogger(ECRActions.class);

    /**
     * Creates an Amazon Elastic Container Registry (Amazon ECR) repository.
     *
     * @param repoName the name of the repository to create.
     * @return the Amazon Resource Name (ARN) of the created repository, or an empty string if the operation failed.
     * @throws IllegalArgumentException     If repository name is invalid.
     * @throws RuntimeException             if an error occurs while creating the repository.
     */
    public String createECRRepository(String repoName) {
        if (repoName == null || repoName.isEmpty()) {
            throw new IllegalArgumentException("Repository name cannot be null or empty");
        }

        CreateRepositoryRequest request = CreateRepositoryRequest.builder()
            .repositoryName(repoName)
            .build();

        CompletableFuture<CreateRepositoryResponse> response = getAsyncClient().createRepository(request);
        try {
            CreateRepositoryResponse result = response.join();
            if (result != null) {
                System.out.println("The " + repoName + " repository was created successfully.");
                return result.repository().repositoryArn();
            } else {
                throw new RuntimeException("Unexpected response type");
            }
        } catch (CompletionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof EcrException ex) {
                if ("RepositoryAlreadyExistsException".equals(ex.awsErrorDetails().errorCode())) {
                    System.out.println("The Amazon ECR repository already exists, moving on...");
                    DescribeRepositoriesRequest describeRequest = DescribeRepositoriesRequest.builder()
                        .repositoryNames(repoName)
                        .build();
                    DescribeRepositoriesResponse describeResponse = getAsyncClient().describeRepositories(describeRequest).join();
                    return describeResponse.repositories().get(0).repositoryArn();
                } else {
                    throw new RuntimeException(ex);
                }
            } else {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * Deletes an ECR (Elastic Container Registry) repository.
     *
     * @param repoName the name of the repository to delete.
     * @throws IllegalArgumentException if the repository name is null or empty.
     * @throws EcrException if there is an error deleting the repository.
     * @throws RuntimeException if an unexpected error occurs during the deletion process.
     */
    public void deleteECRRepository(String repoName) {
        if (repoName == null || repoName.isEmpty()) {
            throw new IllegalArgumentException("Repository name cannot be null or empty");
        }

        DeleteRepositoryRequest repositoryRequest = DeleteRepositoryRequest.builder()
            .force(true)
            .repositoryName(repoName)
            .build();

        CompletableFuture<DeleteRepositoryResponse> response = getAsyncClient().deleteRepository(repositoryRequest);
        response.whenComplete((deleteRepositoryResponse, ex) -> {
            if (deleteRepositoryResponse != null) {
                System.out.println("You have successfully deleted the " + repoName + " repository");
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof EcrException) {
                    throw (EcrException) cause;
                } else {
                    throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                }
            }
        });

        // Wait for the CompletableFuture to complete
        response.join();
    }



    private static DockerClient getDockerClient() {
        String osName = System.getProperty("os.name");
        if (osName.startsWith("Windows")) {
            // Make sure Docker Desktop is running.
            String dockerHost = "tcp://localhost:2375"; // Use the Docker Desktop default port.
            DockerCmdExecFactory dockerCmdExecFactory = new NettyDockerCmdExecFactory().withReadTimeout(20000).withConnectTimeout(20000);
            dockerClient = DockerClientBuilder.getInstance(dockerHost).withDockerCmdExecFactory(dockerCmdExecFactory).build();
        } else {
            dockerClient = DockerClientBuilder.getInstance().build();
        }
        return dockerClient;
    }

    /**
     * Retrieves an asynchronous Amazon Elastic Container Registry (ECR) client.
     *
     * @return the configured ECR asynchronous client.
     */
    private static EcrAsyncClient getAsyncClient() {

        /*
         The `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java, version 2,
         and it is designed to provide a high-performance, asynchronous HTTP client for interacting with AWS services.
         It uses the Netty framework to handle the underlying network communication and the Java NIO API to
         provide a non-blocking, event-driven approach to HTTP requests and responses.
         */
        SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
            .maxConcurrency(50)  // Adjust as needed.
            .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
            .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
            .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
            .build();

        ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
            .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
            .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
            .build();

        if (ecrClient == null) {
            ecrClient = EcrAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return ecrClient;
    }

    /**
     * Sets the lifecycle policy for the specified repository.
     *
     * @param repoName the name of the repository for which to set the lifecycle policy.
     */
    public void setLifeCyclePolicy(String repoName) {
        /*
           This policy helps to maintain the size and efficiency of the container registry
           by automatically removing older and potentially unused images,
           ensuring that the storage is optimized and the registry remains up-to-date.
         */
        String polText = """
             {
             "rules": [
                 {
                     "rulePriority": 1,
                     "description": "Expire images older than 14 days",
                     "selection": {
                         "tagStatus": "any",
                         "countType": "sinceImagePushed",
                         "countUnit": "days",
                         "countNumber": 14
                     },
                     "action": {
                         "type": "expire"
                     }
                 }
            ]
            }
            """;

        StartLifecyclePolicyPreviewRequest lifecyclePolicyPreviewRequest = StartLifecyclePolicyPreviewRequest.builder()
            .lifecyclePolicyText(polText)
            .repositoryName(repoName)
            .build();

        CompletableFuture<StartLifecyclePolicyPreviewResponse> response = getAsyncClient().startLifecyclePolicyPreview(lifecyclePolicyPreviewRequest);
        response.whenComplete((lifecyclePolicyPreviewResponse, ex) -> {
            if (lifecyclePolicyPreviewResponse != null) {
                System.out.println("Lifecycle policy preview started successfully.");
            } else {
                if (ex.getCause() instanceof EcrException) {
                    throw (EcrException) ex.getCause();
                } else {
                    String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                    throw new RuntimeException(errorMessage, ex);
                }
            }
        });
        // Wait for the CompletableFuture to complete.
        response.join();
    }

    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     * @throws EcrException             if there is an error retrieving the image information from Amazon ECR.
     * @throws CompletionException      if the asynchronous operation completes exceptionally.
     */
    public void verifyImage(String repositoryName, String imageTag) {
        DescribeImagesRequest request = DescribeImagesRequest.builder()
            .repositoryName(repositoryName)
            .imageIds(ImageIdentifier.builder().imageTag(imageTag).build())
            .build();

        CompletableFuture<DescribeImagesResponse> response = getAsyncClient().describeImages(request);
        response.whenComplete((describeImagesResponse, ex) -> {
            if (ex != null) {
                if (ex instanceof CompletionException) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof EcrException) {
                        throw (EcrException) cause;
                    } else {
                        throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                    }
                } else {
                    throw new RuntimeException("Unexpected error: " + ex.getCause());
                }
            } else if (describeImagesResponse != null && !describeImagesResponse.imageDetails().isEmpty()) {
                System.out.println("Image is present in the repository.");
            } else {
                System.out.println("Image is not present in the repository.");
            }
        });

        // Wait for the CompletableFuture to complete.
        response.join();
    }

    /**
     * Retrieves the repository URI for the specified repository name.
     *
     * @param repoName the name of the repository to retrieve the URI for.
     * @return the repository URI for the specified repository name.
     * @throws EcrException        if there is an error retrieving the repository information.
     * @throws CompletionException if the asynchronous operation completes exceptionally.
     */
    public void getRepositoryURI(String repoName) {
        DescribeRepositoriesRequest request = DescribeRepositoriesRequest.builder()
            .repositoryNames(repoName)
            .build();

        CompletableFuture<DescribeRepositoriesResponse> response = getAsyncClient().describeRepositories(request);
        response.whenComplete((describeRepositoriesResponse, ex) -> {
            if (ex != null) {
                Throwable cause = ex.getCause();
                if (cause instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                    String errorMessage = "Thread interrupted while waiting for asynchronous operation: " + cause.getMessage();
                    throw new RuntimeException(errorMessage, cause);
                } else if (cause instanceof EcrException) {
                    throw (EcrException) cause;
                } else {
                    String errorMessage = "Unexpected error: " + cause.getMessage();
                    throw new RuntimeException(errorMessage, cause);
                }
            } else {
                if (describeRepositoriesResponse != null) {
                    if (!describeRepositoriesResponse.repositories().isEmpty()) {
                        String repositoryUri = describeRepositoriesResponse.repositories().get(0).repositoryUri();
                        System.out.println("Repository URI found: " + repositoryUri);
                    } else {
                        System.out.println("No repositories found for the given name.");
                    }
                } else {
                    System.err.println("No response received from describeRepositories.");
                }
            }
        });
        response.join();
    }

    /**
     * Retrieves the authorization token for Amazon Elastic Container Registry (ECR).
     * This method makes an asynchronous call to the ECR client to retrieve the authorization token.
     * If the operation is successful, the method prints the token to the console.
     * If an exception occurs, the method handles the exception and prints the error message.
     *
     * @throws EcrException     if there is an error retrieving the authorization token from ECR.
     * @throws RuntimeException if there is an unexpected error during the operation.
     */
    public void getAuthToken() {
        CompletableFuture<GetAuthorizationTokenResponse> response = getAsyncClient().getAuthorizationToken();
        response.whenComplete((authorizationTokenResponse, ex) -> {
            if (authorizationTokenResponse != null) {
                AuthorizationData authorizationData = authorizationTokenResponse.authorizationData().get(0);
                String token = authorizationData.authorizationToken();
                if (!token.isEmpty()) {
                    System.out.println("The token was successfully retrieved.");
                }
            } else {
                if (ex.getCause() instanceof EcrException) {
                    throw (EcrException) ex.getCause();
                } else {
                    String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                    throw new RuntimeException(errorMessage, ex); // Rethrow the exception
                }
            }
        });
        response.join();
    }

    /**
     * Gets the repository policy for the specified repository.
     *
     * @param repoName the name of the repository.
     * @throws EcrException if an AWS error occurs while getting the repository policy.
     */
    public String getRepoPolicy(String repoName) {
        if (repoName == null || repoName.isEmpty()) {
            throw new IllegalArgumentException("Repository name cannot be null or empty");
        }

        GetRepositoryPolicyRequest getRepositoryPolicyRequest = GetRepositoryPolicyRequest.builder()
            .repositoryName(repoName)
            .build();

        CompletableFuture<GetRepositoryPolicyResponse> response = getAsyncClient().getRepositoryPolicy(getRepositoryPolicyRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                System.out.println("Repository policy retrieved successfully.");
            } else {
                if (ex.getCause() instanceof EcrException) {
                    throw (EcrException) ex.getCause();
                } else {
                    String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                    throw new RuntimeException(errorMessage, ex);
                }
            }
        });

        GetRepositoryPolicyResponse result = response.join();
        return result != null ? result.policyText() : null;
    }

    /**
     * Sets the repository policy for the specified ECR repository.
     *
     * @param repoName the name of the ECR repository.
     * @param iamRole  the IAM role to be granted access to the repository.
     * @throws RepositoryPolicyNotFoundException if the repository policy does not exist.
     * @throws EcrException                      if there is an unexpected error setting the repository policy.
     */
    public void setRepoPolicy(String repoName, String iamRole) {
        /*
          This example policy document grants the specified AWS principal the permission to perform the
          `ecr:BatchGetImage` action. This policy is designed to allow the specified principal
          to retrieve Docker images from the ECR repository.
         */
        String policyDocumentTemplate = """
             {
              "Version":"2012-10-17",		 	 	 
              "Statement" : [ {
                "Sid" : "new statement",
                "Effect" : "Allow",
                "Principal" : {
                  "AWS" : "%s"
                },
                "Action" : "ecr:BatchGetImage"
              } ]
            }
             """;

        String policyDocument = String.format(policyDocumentTemplate, iamRole);
        SetRepositoryPolicyRequest setRepositoryPolicyRequest = SetRepositoryPolicyRequest.builder()
            .repositoryName(repoName)
            .policyText(policyDocument)
            .build();

        CompletableFuture<SetRepositoryPolicyResponse> response = getAsyncClient().setRepositoryPolicy(setRepositoryPolicyRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                System.out.println("Repository policy set successfully.");
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof RepositoryPolicyNotFoundException) {
                    throw (RepositoryPolicyNotFoundException) cause;
                } else if (cause instanceof EcrException) {
                    throw (EcrException) cause;
                } else {
                    String errorMessage = "Unexpected error: " + cause.getMessage();
                    throw new RuntimeException(errorMessage, cause);
                }
            }
        });
        response.join();
    }

    /**
     * Pushes a Docker image to an Amazon Elastic Container Registry (ECR) repository.
     *
     * @param repoName  the name of the ECR repository to push the image to.
     * @param imageName the name of the Docker image.
     */
    public void pushDockerImage(String repoName, String imageName) {
        System.out.println("Pushing " + imageName + " to Amazon ECR will take a few seconds.");
        CompletableFuture<AuthConfig> authResponseFuture = getAsyncClient().getAuthorizationToken()
            .thenApply(response -> {
                String token = response.authorizationData().get(0).authorizationToken();
                String decodedToken = new String(Base64.getDecoder().decode(token));
                String password = decodedToken.substring(4);

                DescribeRepositoriesResponse descrRepoResponse = getAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();
                Repository repoData = descrRepoResponse.repositories().stream().filter(r -> r.repositoryName().equals(repoName)).findFirst().orElse(null);
                assert repoData != null;
                String registryURL = repoData.repositoryUri().split("/")[0];

                AuthConfig authConfig = new AuthConfig()
                    .withUsername("AWS")
                    .withPassword(password)
                    .withRegistryAddress(registryURL);
                return authConfig;
            })
            .thenCompose(authConfig -> {
                DescribeRepositoriesResponse descrRepoResponse = getAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();
                Repository repoData = descrRepoResponse.repositories().stream().filter(r -> r.repositoryName().equals(repoName)).findFirst().orElse(null);
                getDockerClient().tagImageCmd(imageName + ":latest", repoData.repositoryUri() + ":latest", imageName).exec();
                try {
                    getDockerClient().pushImageCmd(repoData.repositoryUri()).withTag("echo-text").withAuthConfig(authConfig).start().awaitCompletion();
                    System.out.println("The " + imageName + " was pushed to ECR");

                } catch (InterruptedException e) {
                    throw (RuntimeException) e.getCause();
                }
                return CompletableFuture.completedFuture(authConfig);
            });

        authResponseFuture.join();
    }

    // Make sure local image echo-text exists.
    public boolean isEchoTextImagePresent() {
        try {
            List<Image> images = getDockerClient().listImagesCmd().exec();
            boolean helloWorldFound = false;
            for (Image image : images) {
                String[] repoTags = image.getRepoTags();
                if (repoTags != null) {
                    for (String tag : repoTags) {
                        if (tag.startsWith("echo-text")) {
                            System.out.println(tag);
                            helloWorldFound = true;
                        }
                    }
                }
            }
            if (helloWorldFound) {
                System.out.println("The local image named echo-text exists.");
                return true;
            } else {
                System.out.println("The local image named echo-text does not exist.");
                return false;
            }
        } catch (DockerClientException ex) {
            logger.error("ERROR: " + ex.getMessage());
            return false;
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateRepository](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/CreateRepository)
  + [DeleteRepository](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/DeleteRepository)
  + [DescribeImages](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/DescribeImages)
  + [DescribeRepositories](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/DescribeRepositories)
  + [GetAuthorizationToken](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/GetAuthorizationToken)
  + [GetRepositoryPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/GetRepositoryPolicy)
  + [SetRepositoryPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/SetRepositoryPolicy)
  + [StartLifecyclePolicyPreview](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/StartLifecyclePolicyPreview)

## アクション
<a name="actions"></a>

### `CreateRepository`
<a name="ecr_CreateRepository_java_2_topic"></a>

次のコード例は、`CreateRepository` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an Amazon Elastic Container Registry (Amazon ECR) repository.
     *
     * @param repoName the name of the repository to create.
     * @return the Amazon Resource Name (ARN) of the created repository, or an empty string if the operation failed.
     * @throws IllegalArgumentException     If repository name is invalid.
     * @throws RuntimeException             if an error occurs while creating the repository.
     */
    public String createECRRepository(String repoName) {
        if (repoName == null || repoName.isEmpty()) {
            throw new IllegalArgumentException("Repository name cannot be null or empty");
        }

        CreateRepositoryRequest request = CreateRepositoryRequest.builder()
            .repositoryName(repoName)
            .build();

        CompletableFuture<CreateRepositoryResponse> response = getAsyncClient().createRepository(request);
        try {
            CreateRepositoryResponse result = response.join();
            if (result != null) {
                System.out.println("The " + repoName + " repository was created successfully.");
                return result.repository().repositoryArn();
            } else {
                throw new RuntimeException("Unexpected response type");
            }
        } catch (CompletionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof EcrException ex) {
                if ("RepositoryAlreadyExistsException".equals(ex.awsErrorDetails().errorCode())) {
                    System.out.println("The Amazon ECR repository already exists, moving on...");
                    DescribeRepositoriesRequest describeRequest = DescribeRepositoriesRequest.builder()
                        .repositoryNames(repoName)
                        .build();
                    DescribeRepositoriesResponse describeResponse = getAsyncClient().describeRepositories(describeRequest).join();
                    return describeResponse.repositories().get(0).repositoryArn();
                } else {
                    throw new RuntimeException(ex);
                }
            } else {
                throw new RuntimeException(e);
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateRepository](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/CreateRepository)」を参照してください。

### `DeleteRepository`
<a name="ecr_DeleteRepository_java_2_topic"></a>

次のコード例は、`DeleteRepository` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an ECR (Elastic Container Registry) repository.
     *
     * @param repoName the name of the repository to delete.
     * @throws IllegalArgumentException if the repository name is null or empty.
     * @throws EcrException if there is an error deleting the repository.
     * @throws RuntimeException if an unexpected error occurs during the deletion process.
     */
    public void deleteECRRepository(String repoName) {
        if (repoName == null || repoName.isEmpty()) {
            throw new IllegalArgumentException("Repository name cannot be null or empty");
        }

        DeleteRepositoryRequest repositoryRequest = DeleteRepositoryRequest.builder()
            .force(true)
            .repositoryName(repoName)
            .build();

        CompletableFuture<DeleteRepositoryResponse> response = getAsyncClient().deleteRepository(repositoryRequest);
        response.whenComplete((deleteRepositoryResponse, ex) -> {
            if (deleteRepositoryResponse != null) {
                System.out.println("You have successfully deleted the " + repoName + " repository");
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof EcrException) {
                    throw (EcrException) cause;
                } else {
                    throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                }
            }
        });

        // Wait for the CompletableFuture to complete
        response.join();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteRepository](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/DeleteRepository)」を参照してください。

### `DescribeImages`
<a name="ecr_DescribeImages_java_2_topic"></a>

次のコード例は、`DescribeImages` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     * @throws EcrException             if there is an error retrieving the image information from Amazon ECR.
     * @throws CompletionException      if the asynchronous operation completes exceptionally.
     */
    public void verifyImage(String repositoryName, String imageTag) {
        DescribeImagesRequest request = DescribeImagesRequest.builder()
            .repositoryName(repositoryName)
            .imageIds(ImageIdentifier.builder().imageTag(imageTag).build())
            .build();

        CompletableFuture<DescribeImagesResponse> response = getAsyncClient().describeImages(request);
        response.whenComplete((describeImagesResponse, ex) -> {
            if (ex != null) {
                if (ex instanceof CompletionException) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof EcrException) {
                        throw (EcrException) cause;
                    } else {
                        throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                    }
                } else {
                    throw new RuntimeException("Unexpected error: " + ex.getCause());
                }
            } else if (describeImagesResponse != null && !describeImagesResponse.imageDetails().isEmpty()) {
                System.out.println("Image is present in the repository.");
            } else {
                System.out.println("Image is not present in the repository.");
            }
        });

        // Wait for the CompletableFuture to complete.
        response.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeImages](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/DescribeImages)」を参照してください。

### `DescribeRepositories`
<a name="ecr_DescribeRepositories_java_2_topic"></a>

次のコード例は、`DescribeRepositories` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the repository URI for the specified repository name.
     *
     * @param repoName the name of the repository to retrieve the URI for.
     * @return the repository URI for the specified repository name.
     * @throws EcrException        if there is an error retrieving the repository information.
     * @throws CompletionException if the asynchronous operation completes exceptionally.
     */
    public void getRepositoryURI(String repoName) {
        DescribeRepositoriesRequest request = DescribeRepositoriesRequest.builder()
            .repositoryNames(repoName)
            .build();

        CompletableFuture<DescribeRepositoriesResponse> response = getAsyncClient().describeRepositories(request);
        response.whenComplete((describeRepositoriesResponse, ex) -> {
            if (ex != null) {
                Throwable cause = ex.getCause();
                if (cause instanceof InterruptedException) {
                    Thread.currentThread().interrupt();
                    String errorMessage = "Thread interrupted while waiting for asynchronous operation: " + cause.getMessage();
                    throw new RuntimeException(errorMessage, cause);
                } else if (cause instanceof EcrException) {
                    throw (EcrException) cause;
                } else {
                    String errorMessage = "Unexpected error: " + cause.getMessage();
                    throw new RuntimeException(errorMessage, cause);
                }
            } else {
                if (describeRepositoriesResponse != null) {
                    if (!describeRepositoriesResponse.repositories().isEmpty()) {
                        String repositoryUri = describeRepositoriesResponse.repositories().get(0).repositoryUri();
                        System.out.println("Repository URI found: " + repositoryUri);
                    } else {
                        System.out.println("No repositories found for the given name.");
                    }
                } else {
                    System.err.println("No response received from describeRepositories.");
                }
            }
        });
        response.join();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeRepositories](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/DescribeRepositories)」を参照してください。

### `GetAuthorizationToken`
<a name="ecr_GetAuthorizationToken_java_2_topic"></a>

次のコード例は、`GetAuthorizationToken` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the authorization token for Amazon Elastic Container Registry (ECR).
     * This method makes an asynchronous call to the ECR client to retrieve the authorization token.
     * If the operation is successful, the method prints the token to the console.
     * If an exception occurs, the method handles the exception and prints the error message.
     *
     * @throws EcrException     if there is an error retrieving the authorization token from ECR.
     * @throws RuntimeException if there is an unexpected error during the operation.
     */
    public void getAuthToken() {
        CompletableFuture<GetAuthorizationTokenResponse> response = getAsyncClient().getAuthorizationToken();
        response.whenComplete((authorizationTokenResponse, ex) -> {
            if (authorizationTokenResponse != null) {
                AuthorizationData authorizationData = authorizationTokenResponse.authorizationData().get(0);
                String token = authorizationData.authorizationToken();
                if (!token.isEmpty()) {
                    System.out.println("The token was successfully retrieved.");
                }
            } else {
                if (ex.getCause() instanceof EcrException) {
                    throw (EcrException) ex.getCause();
                } else {
                    String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                    throw new RuntimeException(errorMessage, ex); // Rethrow the exception
                }
            }
        });
        response.join();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAuthorizationToken](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/GetAuthorizationToken)」を参照してください。

### `GetRepositoryPolicy`
<a name="ecr_GetRepositoryPolicy_java_2_topic"></a>

次のコード例は、`GetRepositoryPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Gets the repository policy for the specified repository.
     *
     * @param repoName the name of the repository.
     * @throws EcrException if an AWS error occurs while getting the repository policy.
     */
    public String getRepoPolicy(String repoName) {
        if (repoName == null || repoName.isEmpty()) {
            throw new IllegalArgumentException("Repository name cannot be null or empty");
        }

        GetRepositoryPolicyRequest getRepositoryPolicyRequest = GetRepositoryPolicyRequest.builder()
            .repositoryName(repoName)
            .build();

        CompletableFuture<GetRepositoryPolicyResponse> response = getAsyncClient().getRepositoryPolicy(getRepositoryPolicyRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                System.out.println("Repository policy retrieved successfully.");
            } else {
                if (ex.getCause() instanceof EcrException) {
                    throw (EcrException) ex.getCause();
                } else {
                    String errorMessage = "Unexpected error occurred: " + ex.getMessage();
                    throw new RuntimeException(errorMessage, ex);
                }
            }
        });

        GetRepositoryPolicyResponse result = response.join();
        return result != null ? result.policyText() : null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetRepositoryPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/GetRepositoryPolicy)」を参照してください。

### `PushImageCmd`
<a name="ecr_PushImageCmd_java_2_topic"></a>

次のコード例は、`PushImageCmd` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Pushes a Docker image to an Amazon Elastic Container Registry (ECR) repository.
     *
     * @param repoName  the name of the ECR repository to push the image to.
     * @param imageName the name of the Docker image.
     */
    public void pushDockerImage(String repoName, String imageName) {
        System.out.println("Pushing " + imageName + " to Amazon ECR will take a few seconds.");
        CompletableFuture<AuthConfig> authResponseFuture = getAsyncClient().getAuthorizationToken()
            .thenApply(response -> {
                String token = response.authorizationData().get(0).authorizationToken();
                String decodedToken = new String(Base64.getDecoder().decode(token));
                String password = decodedToken.substring(4);

                DescribeRepositoriesResponse descrRepoResponse = getAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();
                Repository repoData = descrRepoResponse.repositories().stream().filter(r -> r.repositoryName().equals(repoName)).findFirst().orElse(null);
                assert repoData != null;
                String registryURL = repoData.repositoryUri().split("/")[0];

                AuthConfig authConfig = new AuthConfig()
                    .withUsername("AWS")
                    .withPassword(password)
                    .withRegistryAddress(registryURL);
                return authConfig;
            })
            .thenCompose(authConfig -> {
                DescribeRepositoriesResponse descrRepoResponse = getAsyncClient().describeRepositories(b -> b.repositoryNames(repoName)).join();
                Repository repoData = descrRepoResponse.repositories().stream().filter(r -> r.repositoryName().equals(repoName)).findFirst().orElse(null);
                getDockerClient().tagImageCmd(imageName + ":latest", repoData.repositoryUri() + ":latest", imageName).exec();
                try {
                    getDockerClient().pushImageCmd(repoData.repositoryUri()).withTag("echo-text").withAuthConfig(authConfig).start().awaitCompletion();
                    System.out.println("The " + imageName + " was pushed to ECR");

                } catch (InterruptedException e) {
                    throw (RuntimeException) e.getCause();
                }
                return CompletableFuture.completedFuture(authConfig);
            });

        authResponseFuture.join();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PushImageCmd](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/PushImageCmd)」を参照してください。

### `SetRepositoryPolicy`
<a name="ecr_SetRepositoryPolicy_java_2_topic"></a>

次のコード例は、`SetRepositoryPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Sets the repository policy for the specified ECR repository.
     *
     * @param repoName the name of the ECR repository.
     * @param iamRole  the IAM role to be granted access to the repository.
     * @throws RepositoryPolicyNotFoundException if the repository policy does not exist.
     * @throws EcrException                      if there is an unexpected error setting the repository policy.
     */
    public void setRepoPolicy(String repoName, String iamRole) {
        /*
          This example policy document grants the specified AWS principal the permission to perform the
          `ecr:BatchGetImage` action. This policy is designed to allow the specified principal
          to retrieve Docker images from the ECR repository.
         */
        String policyDocumentTemplate = """
             {
              "Version":"2012-10-17",		 	 	 
              "Statement" : [ {
                "Sid" : "new statement",
                "Effect" : "Allow",
                "Principal" : {
                  "AWS" : "%s"
                },
                "Action" : "ecr:BatchGetImage"
              } ]
            }
             """;

        String policyDocument = String.format(policyDocumentTemplate, iamRole);
        SetRepositoryPolicyRequest setRepositoryPolicyRequest = SetRepositoryPolicyRequest.builder()
            .repositoryName(repoName)
            .policyText(policyDocument)
            .build();

        CompletableFuture<SetRepositoryPolicyResponse> response = getAsyncClient().setRepositoryPolicy(setRepositoryPolicyRequest);
        response.whenComplete((resp, ex) -> {
            if (resp != null) {
                System.out.println("Repository policy set successfully.");
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof RepositoryPolicyNotFoundException) {
                    throw (RepositoryPolicyNotFoundException) cause;
                } else if (cause instanceof EcrException) {
                    throw (EcrException) cause;
                } else {
                    String errorMessage = "Unexpected error: " + cause.getMessage();
                    throw new RuntimeException(errorMessage, cause);
                }
            }
        });
        response.join();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SetRepositoryPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/SetRepositoryPolicy)」を参照してください。

### `StartLifecyclePolicyPreview`
<a name="ecr_StartLifecyclePolicyPreview_java_2_topic"></a>

次のコード例は、`StartLifecyclePolicyPreview` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     * @throws EcrException             if there is an error retrieving the image information from Amazon ECR.
     * @throws CompletionException      if the asynchronous operation completes exceptionally.
     */
    public void verifyImage(String repositoryName, String imageTag) {
        DescribeImagesRequest request = DescribeImagesRequest.builder()
            .repositoryName(repositoryName)
            .imageIds(ImageIdentifier.builder().imageTag(imageTag).build())
            .build();

        CompletableFuture<DescribeImagesResponse> response = getAsyncClient().describeImages(request);
        response.whenComplete((describeImagesResponse, ex) -> {
            if (ex != null) {
                if (ex instanceof CompletionException) {
                    Throwable cause = ex.getCause();
                    if (cause instanceof EcrException) {
                        throw (EcrException) cause;
                    } else {
                        throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
                    }
                } else {
                    throw new RuntimeException("Unexpected error: " + ex.getCause());
                }
            } else if (describeImagesResponse != null && !describeImagesResponse.imageDetails().isEmpty()) {
                System.out.println("Image is present in the repository.");
            } else {
                System.out.println("Image is not present in the repository.");
            }
        });

        // Wait for the CompletableFuture to complete.
        response.join();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartLifecyclePolicyPreview](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecr-2015-09-21/StartLifecyclePolicyPreview)」を参照してください。

# SDK for Java 2.x を使用する Amazon ECS の例
<a name="java_2_ecs_code_examples"></a>

次のコード例は、Amazon ECS AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="ecs_CreateCluster_java_2_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ExecuteCommandConfiguration;
import software.amazon.awssdk.services.ecs.model.ExecuteCommandLogging;
import software.amazon.awssdk.services.ecs.model.ClusterConfiguration;
import software.amazon.awssdk.services.ecs.model.CreateClusterResponse;
import software.amazon.awssdk.services.ecs.model.EcsException;
import software.amazon.awssdk.services.ecs.model.CreateClusterRequest;

/**
 * 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 CreateCluster {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                   <clusterName>\s

                Where:
                   clusterName - The name of the ECS cluster to create.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String clusterName = args[0];
        Region region = Region.US_EAST_1;
        EcsClient ecsClient = EcsClient.builder()
                .region(region)
                .build();

        String clusterArn = createGivenCluster(ecsClient, clusterName);
        System.out.println("The cluster ARN is " + clusterArn);
        ecsClient.close();
    }

    public static String createGivenCluster(EcsClient ecsClient, String clusterName) {
        try {
            ExecuteCommandConfiguration commandConfiguration = ExecuteCommandConfiguration.builder()
                    .logging(ExecuteCommandLogging.DEFAULT)
                    .build();

            ClusterConfiguration clusterConfiguration = ClusterConfiguration.builder()
                    .executeCommandConfiguration(commandConfiguration)
                    .build();

            CreateClusterRequest clusterRequest = CreateClusterRequest.builder()
                    .clusterName(clusterName)
                    .configuration(clusterConfiguration)
                    .build();

            CreateClusterResponse response = ecsClient.createCluster(clusterRequest);
            return response.cluster().clusterArn();

        } catch (EcsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecs-2014-11-13/CreateCluster)」を参照してください。

### `CreateService`
<a name="ecs_CreateService_java_2_topic"></a>

次のコード例は、`CreateService` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.AwsVpcConfiguration;
import software.amazon.awssdk.services.ecs.model.NetworkConfiguration;
import software.amazon.awssdk.services.ecs.model.CreateServiceRequest;
import software.amazon.awssdk.services.ecs.model.LaunchType;
import software.amazon.awssdk.services.ecs.model.CreateServiceResponse;
import software.amazon.awssdk.services.ecs.model.EcsException;

/**
 * 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 CreateService {
        public static void main(String[] args) {
                final String usage = """

                                Usage:
                                  <clusterName> <serviceName> <securityGroups> <subnets> <taskDefinition>

                                Where:
                                  clusterName - The name of the ECS cluster.
                                  serviceName - The name of the ECS service to create.
                                  securityGroups - The name of the security group.
                                  subnets - The name of the subnet.
                                  taskDefinition - The name of the task definition.
                                """;

                if (args.length != 5) {
                        System.out.println(usage);
                        System.exit(1);
                }

                String clusterName = args[0];
                String serviceName = args[1];
                String securityGroups = args[2];
                String subnets = args[3];
                String taskDefinition = args[4];
                Region region = Region.US_EAST_1;
                EcsClient ecsClient = EcsClient.builder()
                                .region(region)
                                .build();

                String serviceArn = createNewService(ecsClient, clusterName, serviceName, securityGroups, subnets,
                                taskDefinition);
                System.out.println("The ARN of the service is " + serviceArn);
                ecsClient.close();
        }

        public static String createNewService(EcsClient ecsClient,
                        String clusterName,
                        String serviceName,
                        String securityGroups,
                        String subnets,
                        String taskDefinition) {

                try {
                        AwsVpcConfiguration vpcConfiguration = AwsVpcConfiguration.builder()
                                        .securityGroups(securityGroups)
                                        .subnets(subnets)
                                        .build();

                        NetworkConfiguration configuration = NetworkConfiguration.builder()
                                        .awsvpcConfiguration(vpcConfiguration)
                                        .build();

                        CreateServiceRequest serviceRequest = CreateServiceRequest.builder()
                                        .cluster(clusterName)
                                        .networkConfiguration(configuration)
                                        .desiredCount(1)
                                        .launchType(LaunchType.FARGATE)
                                        .serviceName(serviceName)
                                        .taskDefinition(taskDefinition)
                                        .build();

                        CreateServiceResponse response = ecsClient.createService(serviceRequest);
                        return response.service().serviceArn();

                } catch (EcsException e) {
                        System.err.println(e.awsErrorDetails().errorMessage());
                        System.exit(1);
                }
                return "";
        }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateService](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecs-2014-11-13/CreateService)」を参照してください。

### `DeleteService`
<a name="ecs_DeleteService_java_2_topic"></a>

次のコード例は、`DeleteService` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.DeleteServiceRequest;
import software.amazon.awssdk.services.ecs.model.EcsException;

/**
 * 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 DeleteService {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <clusterName> <serviceArn>\s

                Where:
                  clusterName - The name of the ECS cluster.
                  serviceArn - The ARN of the ECS service.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String clusterName = args[0];
        String serviceArn = args[1];
        Region region = Region.US_EAST_1;
        EcsClient ecsClient = EcsClient.builder()
                .region(region)
                .build();

        deleteSpecificService(ecsClient, clusterName, serviceArn);
        ecsClient.close();
    }

    public static void deleteSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) {
        try {
            DeleteServiceRequest serviceRequest = DeleteServiceRequest.builder()
                    .cluster(clusterName)
                    .service(serviceArn)
                    .build();

            ecsClient.deleteService(serviceRequest);
            System.out.println("The Service was successfully deleted");

        } catch (EcsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteService](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecs-2014-11-13/DeleteService)」を参照してください。

### `DescribeClusters`
<a name="ecs_DescribeClusters_java_2_topic"></a>

次のコード例は、`DescribeClusters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.DescribeClustersRequest;
import software.amazon.awssdk.services.ecs.model.DescribeClustersResponse;
import software.amazon.awssdk.services.ecs.model.Cluster;
import software.amazon.awssdk.services.ecs.model.EcsException;
import java.util.List;

/**
 * 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 DescribeClusters {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <clusterArn> \s

                Where:
                  clusterArn - The ARN of the ECS cluster to describe.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String clusterArn = args[0];
        Region region = Region.US_EAST_1;
        EcsClient ecsClient = EcsClient.builder()
                .region(region)
                .build();

        descCluster(ecsClient, clusterArn);
    }

    public static void descCluster(EcsClient ecsClient, String clusterArn) {
        try {
            DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder()
                    .clusters(clusterArn)
                    .build();

            DescribeClustersResponse response = ecsClient.describeClusters(clustersRequest);
            List<Cluster> clusters = response.clusters();
            for (Cluster cluster : clusters) {
                System.out.println("The cluster name is " + cluster.clusterName());
            }

        } catch (EcsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecs-2014-11-13/DescribeClusters)」を参照してください。

### `DescribeTasks`
<a name="ecs_DescribeTasks_java_2_topic"></a>

次のコード例は、`DescribeTasks` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.DescribeTasksRequest;
import software.amazon.awssdk.services.ecs.model.DescribeTasksResponse;
import software.amazon.awssdk.services.ecs.model.EcsException;
import software.amazon.awssdk.services.ecs.model.Task;
import java.util.List;

/**
 * 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 ListTaskDefinitions {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                  <clusterArn> <taskId>\s

                Where:
                  clusterArn - The ARN of an ECS cluster.
                  taskId - The task Id value.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String clusterArn = args[0];
        String taskId = args[1];
        Region region = Region.US_EAST_1;
        EcsClient ecsClient = EcsClient.builder()
                .region(region)
                .build();

        getAllTasks(ecsClient, clusterArn, taskId);
        ecsClient.close();
    }

    public static void getAllTasks(EcsClient ecsClient, String clusterArn, String taskId) {
        try {
            DescribeTasksRequest tasksRequest = DescribeTasksRequest.builder()
                    .cluster(clusterArn)
                    .tasks(taskId)
                    .build();

            DescribeTasksResponse response = ecsClient.describeTasks(tasksRequest);
            List<Task> tasks = response.tasks();
            for (Task task : tasks) {
                System.out.println("The task ARN is " + task.taskDefinitionArn());
            }

        } catch (EcsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeTasks](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecs-2014-11-13/DescribeTasks)」を参照してください。

### `ListClusters`
<a name="ecs_ListClusters_java_2_topic"></a>

次のコード例は、`ListClusters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.ListClustersResponse;
import software.amazon.awssdk.services.ecs.model.EcsException;
import java.util.List;

/**
 * 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 ListClusters {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        EcsClient ecsClient = EcsClient.builder()
                .region(region)
                .build();

        listAllClusters(ecsClient);
        ecsClient.close();
    }

    public static void listAllClusters(EcsClient ecsClient) {
        try {
            ListClustersResponse response = ecsClient.listClusters();
            List<String> clusters = response.clusterArns();
            for (String cluster : clusters) {
                System.out.println("The cluster arn is " + cluster);
            }

        } catch (EcsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[ListClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecs-2014-11-13/ListClusters)」を参照してください。

### `UpdateService`
<a name="ecs_UpdateService_java_2_topic"></a>

次のコード例は、`UpdateService` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ecs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ecs.EcsClient;
import software.amazon.awssdk.services.ecs.model.EcsException;
import software.amazon.awssdk.services.ecs.model.UpdateServiceRequest;

/**
 * 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 UpdateService {

    public static void main(String[] args) {

        final String usage = """

                Usage:
                   <clusterName> <serviceArn>\s

                Where:
                  clusterName - The cluster name.
                  serviceArn - The service ARN value.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String clusterName = args[0];
        String serviceArn = args[1];
        Region region = Region.US_EAST_1;
        EcsClient ecsClient = EcsClient.builder()
                .region(region)
                .build();

        updateSpecificService(ecsClient, clusterName, serviceArn);
        ecsClient.close();
    }

    public static void updateSpecificService(EcsClient ecsClient, String clusterName, String serviceArn) {
        try {
            UpdateServiceRequest serviceRequest = UpdateServiceRequest.builder()
                    .cluster(clusterName)
                    .service(serviceArn)
                    .desiredCount(0)
                    .build();

            ecsClient.updateService(serviceRequest);
            System.out.println("The service was modified");

        } catch (EcsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateService](https://docs.aws.amazon.com/goto/SdkForJavaV2/ecs-2014-11-13/UpdateService)」を参照してください。

# Java 2.x 用 SDK を使用した Elastic Load Balancing - バージョン 2 の例
<a name="java_2_elastic-load-balancing-v2_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 2 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Elastic Load Balancing
<a name="elastic-load-balancing-v2_Hello_java_2_topic"></a>

次のコード例は、Elastic Load Balancing の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。

```
public class HelloLoadBalancer {

        public static void main(String[] args) {
                ElasticLoadBalancingV2Client loadBalancingV2Client = ElasticLoadBalancingV2Client.builder()
                                .region(Region.US_EAST_1)
                                .build();

                DescribeLoadBalancersResponse loadBalancersResponse = loadBalancingV2Client
                                .describeLoadBalancers(r -> r.pageSize(10));
                List<LoadBalancer> loadBalancerList = loadBalancersResponse.loadBalancers();
                for (LoadBalancer lb : loadBalancerList)
                        System.out.println("Load Balancer DNS name = " + lb.dnsName());
        }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeLoadBalancers](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateListener`
<a name="elastic-load-balancing-v2_CreateListener_java_2_topic"></a>

次のコード例は、`CreateListener` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。

```
    /*
     * Creates an Elastic Load Balancing load balancer that uses the specified
     * subnets
     * and forwards requests to the specified target group.
     */
    public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port,
            String protocol) {
        try {
            List<String> subnetIdStrings = subnetIds.stream()
                    .map(Subnet::subnetId)
                    .collect(Collectors.toList());

            CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder()
                    .subnets(subnetIdStrings)
                    .name(lbName)
                    .scheme("internet-facing")
                    .build();

            // Create and wait for the load balancer to become available.
            CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest);
            String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();

            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(lbARN)
                    .build();

            System.out.println("Waiting for Load Balancer " + lbName + " to become available.");
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancerAvailable(request);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Load Balancer " + lbName + " is available.");

            // Get the DNS name (endpoint) of the load balancer.
            String lbDNSName = lsResponse.loadBalancers().get(0).dnsName();
            System.out.println("*** Load Balancer DNS Name: " + lbDNSName);

            // Create a listener for the load balance.
            Action action = Action.builder()
                    .targetGroupArn(targetGroupARN)
                    .type("forward")
                    .build();

            CreateListenerRequest listenerRequest = CreateListenerRequest.builder()
                    .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())
                    .defaultActions(action)
                    .port(port)
                    .protocol(protocol)
                    .build();

            getLoadBalancerClient().createListener(listenerRequest);
            System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group "
                    + targetGroupARN);

            // Return the load balancer DNS name.
            return lbDNSName;

        } catch (ElasticLoadBalancingV2Exception e) {
            e.printStackTrace();
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateListener](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateListener)」を参照してください。

### `CreateLoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_java_2_topic"></a>

次のコード例は、`CreateLoadBalancer` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。

```
    /*
     * Creates an Elastic Load Balancing load balancer that uses the specified
     * subnets
     * and forwards requests to the specified target group.
     */
    public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port,
            String protocol) {
        try {
            List<String> subnetIdStrings = subnetIds.stream()
                    .map(Subnet::subnetId)
                    .collect(Collectors.toList());

            CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder()
                    .subnets(subnetIdStrings)
                    .name(lbName)
                    .scheme("internet-facing")
                    .build();

            // Create and wait for the load balancer to become available.
            CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest);
            String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();

            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(lbARN)
                    .build();

            System.out.println("Waiting for Load Balancer " + lbName + " to become available.");
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancerAvailable(request);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Load Balancer " + lbName + " is available.");

            // Get the DNS name (endpoint) of the load balancer.
            String lbDNSName = lsResponse.loadBalancers().get(0).dnsName();
            System.out.println("*** Load Balancer DNS Name: " + lbDNSName);

            // Create a listener for the load balance.
            Action action = Action.builder()
                    .targetGroupArn(targetGroupARN)
                    .type("forward")
                    .build();

            CreateListenerRequest listenerRequest = CreateListenerRequest.builder()
                    .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())
                    .defaultActions(action)
                    .port(port)
                    .protocol(protocol)
                    .build();

            getLoadBalancerClient().createListener(listenerRequest);
            System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group "
                    + targetGroupARN);

            // Return the load balancer DNS name.
            return lbDNSName;

        } catch (ElasticLoadBalancingV2Exception e) {
            e.printStackTrace();
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)」を参照してください。

### `CreateTargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_java_2_topic"></a>

次のコード例は、`CreateTargetGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。

```
    /*
     * Creates an Elastic Load Balancing target group. The target group specifies
     * how
     * the load balancer forward requests to instances in the group and how instance
     * health is checked.
     */
    public String createTargetGroup(String protocol, int port, String vpcId, String targetGroupName) {
        CreateTargetGroupRequest targetGroupRequest = CreateTargetGroupRequest.builder()
                .healthCheckPath("/healthcheck")
                .healthCheckTimeoutSeconds(5)
                .port(port)
                .vpcId(vpcId)
                .name(targetGroupName)
                .protocol(protocol)
                .build();

        CreateTargetGroupResponse targetGroupResponse = getLoadBalancerClient().createTargetGroup(targetGroupRequest);
        String targetGroupArn = targetGroupResponse.targetGroups().get(0).targetGroupArn();
        String targetGroup = targetGroupResponse.targetGroups().get(0).targetGroupName();
        System.out.println("The " + targetGroup + " was created with ARN" + targetGroupArn);
        return targetGroupArn;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)」を参照してください。

### `DeleteLoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_java_2_topic"></a>

次のコード例は、`DeleteLoadBalancer` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。

```
    // Deletes a load balancer.
    public void deleteLoadBalancer(String lbName) {
        try {
            // Use a waiter to delete the Load Balancer.
            DescribeLoadBalancersResponse res = getLoadBalancerClient()
                    .describeLoadBalancers(describe -> describe.names(lbName));
            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())
                    .build();

            getLoadBalancerClient().deleteLoadBalancer(
                    builder -> builder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancersDeleted(request);
            waiterResponse.matched().response().ifPresent(System.out::println);

        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(lbName + " was deleted.");
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)」を参照してください。

### `DeleteTargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_java_2_topic"></a>

次のコード例は、`DeleteTargetGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。

```
    // Deletes the target group.
    public void deleteTargetGroup(String targetGroupName) {
        try {
            DescribeTargetGroupsResponse res = getLoadBalancerClient()
                    .describeTargetGroups(describe -> describe.names(targetGroupName));
            getLoadBalancerClient()
                    .deleteTargetGroup(builder -> builder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));
        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(targetGroupName + " was deleted.");
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)」を参照してください。

### `DescribeTargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_java_2_topic"></a>

次のコード例は、`DescribeTargetHealth` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。

```
    // Checks the health of the instances in the target group.
    public List<TargetHealthDescription> checkTargetHealth(String targetGroupName) {
        DescribeTargetGroupsRequest targetGroupsRequest = DescribeTargetGroupsRequest.builder()
                .names(targetGroupName)
                .build();

        DescribeTargetGroupsResponse tgResponse = getLoadBalancerClient().describeTargetGroups(targetGroupsRequest);

        DescribeTargetHealthRequest healthRequest = DescribeTargetHealthRequest.builder()
                .targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())
                .build();

        DescribeTargetHealthResponse healthResponse = getLoadBalancerClient().describeTargetHealth(healthRequest);
        return healthResponse.targetHealthDescriptions();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeTargetHealth](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_java_2_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
public class Main {

    public static final String fileName = "C:\\AWS\\resworkflow\\recommendations.json"; // Modify file location.
    public static final String tableName = "doc-example-recommendation-service";
    public static final String startScript = "C:\\AWS\\resworkflow\\server_startup_script.sh"; // Modify file location.
    public static final String policyFile = "C:\\AWS\\resworkflow\\instance_policy.json"; // Modify file location.
    public static final String ssmJSON = "C:\\AWS\\resworkflow\\ssm_only_policy.json"; // Modify file location.
    public static final String failureResponse = "doc-example-resilient-architecture-failure-response";
    public static final String healthCheck = "doc-example-resilient-architecture-health-check";
    public static final String templateName = "doc-example-resilience-template";
    public static final String roleName = "doc-example-resilience-role";
    public static final String policyName = "doc-example-resilience-pol";
    public static final String profileName = "doc-example-resilience-prof";

    public static final String badCredsProfileName = "doc-example-resilience-prof-bc";

    public static final String targetGroupName = "doc-example-resilience-tg";
    public static final String autoScalingGroupName = "doc-example-resilience-group";
    public static final String lbName = "doc-example-resilience-lb";
    public static final String protocol = "HTTP";
    public static final int port = 80;

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner in = new Scanner(System.in);
        Database database = new Database();
        AutoScaler autoScaler = new AutoScaler();
        LoadBalancer loadBalancer = new LoadBalancer();

        System.out.println(DASHES);
        System.out.println("Welcome to the demonstration of How to Build and Manage a Resilient Service!");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("A - SETUP THE RESOURCES");
        System.out.println("Press Enter when you're ready to start deploying resources.");
        in.nextLine();
        deploy(loadBalancer);
        System.out.println(DASHES);
        System.out.println(DASHES);
        System.out.println("B - DEMO THE RESILIENCE FUNCTIONALITY");
        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        demo(loadBalancer);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("C - DELETE THE RESOURCES");
        System.out.println("""
                This concludes the demo of how to build and manage a resilient service.
                To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources
                that were created for this demo.
                """);

        System.out.println("\n Do you want to delete the resources (y/n)? ");
        String userInput = in.nextLine().trim().toLowerCase(); // Capture user input

        if (userInput.equals("y")) {
            // Delete resources here
            deleteResources(loadBalancer, autoScaler, database);
            System.out.println("Resources deleted.");
        } else {
            System.out.println("""
                    Okay, we'll leave the resources intact.
                    Don't forget to delete them when you're done with them or you might incur unexpected charges.
                    """);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The example has completed. ");
        System.out.println("\n Thanks for watching!");
        System.out.println(DASHES);
    }

    // Deletes the AWS resources used in this example.
    private static void deleteResources(LoadBalancer loadBalancer, AutoScaler autoScaler, Database database)
            throws IOException, InterruptedException {
        loadBalancer.deleteLoadBalancer(lbName);
        System.out.println("*** Wait 30 secs for resource to be deleted");
        TimeUnit.SECONDS.sleep(30);
        loadBalancer.deleteTargetGroup(targetGroupName);
        autoScaler.deleteAutoScaleGroup(autoScalingGroupName);
        autoScaler.deleteRolesPolicies(policyName, roleName, profileName);
        autoScaler.deleteTemplate(templateName);
        database.deleteTable(tableName);
    }

    private static void deploy(LoadBalancer loadBalancer) throws InterruptedException, IOException {
        Scanner in = new Scanner(System.in);
        System.out.println(
                """
                        For this demo, we'll use the AWS SDK for Java (v2) to create several AWS resources
                        to set up a load-balanced web service endpoint and explore some ways to make it resilient
                        against various kinds of failures.

                        Some of the resources create by this demo are:
                        \t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.
                        \t* An EC2 launch template that defines EC2 instances that each contain a Python web server.
                        \t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.
                        \t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.
                        """);

        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating and populating a DynamoDB table named " + tableName);
        Database database = new Database();
        database.createTable(tableName, fileName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an EC2 launch template that runs '{startup_script}' when an instance starts.
                This script starts a Python web server defined in the `server.py` script. The web server
                listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.
                For demo purposes, this server is run as the root user. In production, the best practice is to
                run a web server, such as Apache, with least-privileged credentials.

                The template also defines an IAM policy that each instance uses to assume a role that grants
                permissions to access the DynamoDB recommendation table and Systems Manager parameters
                that control the flow of the demo.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        templateCreator.createTemplate(policyFile, policyName, profileName, startScript, templateName, roleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(
                "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different Availability Zone.");
        System.out.println("*** Wait 30 secs for the VPC to be created");
        TimeUnit.SECONDS.sleep(30);
        AutoScaler autoScaler = new AutoScaler();
        String[] zones = autoScaler.createGroup(3, templateName, autoScalingGroupName);

        System.out.println("""
                At this point, you have EC2 instances created. Once each instance starts, it listens for
                HTTP requests. You can see these instances in the console or continue with the demo.
                Press Enter when you're ready to continue.
                """);

        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating variables that control the flow of the demo.");
        ParameterHelper paramHelper = new ParameterHelper();
        paramHelper.reset();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an Elastic Load Balancing target group and load balancer. The target group
                defines how the load balancer connects to instances. The load balancer provides a
                single endpoint where clients connect and dispatches requests to instances in the group.
                """);

        String vpcId = autoScaler.getDefaultVPC();
        List<Subnet> subnets = autoScaler.getSubnets(vpcId, zones);
        System.out.println("You have retrieved a list with " + subnets.size() + " subnets");
        String targetGroupArn = loadBalancer.createTargetGroup(protocol, port, vpcId, targetGroupName);
        String elbDnsName = loadBalancer.createLoadBalancer(subnets, targetGroupArn, lbName, port, protocol);
        autoScaler.attachLoadBalancerTargetGroup(autoScalingGroupName, targetGroupArn);
        System.out.println("Verifying access to the load balancer endpoint...");
        boolean wasSuccessul = loadBalancer.verifyLoadBalancerEndpoint(elbDnsName);
        if (!wasSuccessul) {
            System.out.println("Couldn't connect to the load balancer, verifying that the port is open...");
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // Create an HTTP GET request to "http://checkip.amazonaws.com"
            HttpGet httpGet = new HttpGet("http://checkip.amazonaws.com");
            try {
                // Execute the request and get the response
                HttpResponse response = httpClient.execute(httpGet);

                // Read the response content.
                String ipAddress = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8).trim();

                // Print the public IP address.
                System.out.println("Public IP Address: " + ipAddress);
                GroupInfo groupInfo = autoScaler.verifyInboundPort(vpcId, port, ipAddress);
                if (!groupInfo.isPortOpen()) {
                    System.out.println("""
                            For this example to work, the default security group for your default VPC must
                            allow access from this computer. You can either add it automatically from this
                            example or add it yourself using the AWS Management Console.
                            """);

                    System.out.println(
                            "Do you want to add a rule to security group " + groupInfo.getGroupName() + " to allow");
                    System.out.println("inbound traffic on port " + port + " from your computer's IP address (y/n) ");
                    String ans = in.nextLine();
                    if ("y".equalsIgnoreCase(ans)) {
                        autoScaler.openInboundPort(groupInfo.getGroupName(), String.valueOf(port), ipAddress);
                        System.out.println("Security group rule added.");
                    } else {
                        System.out.println("No security group rule added.");
                    }
                }

            } catch (AutoScalingException e) {
                e.printStackTrace();
            }
        } else if (wasSuccessul) {
            System.out.println("Your load balancer is ready. You can access it by browsing to:");
            System.out.println("\t http://" + elbDnsName);
        } else {
            System.out.println("Couldn't get a successful response from the load balancer endpoint. Troubleshoot by");
            System.out.println("manually verifying that your VPC and security group are configured correctly and that");
            System.out.println("you can successfully make a GET request to the load balancer.");
        }

        System.out.println("Press Enter when you're ready to continue with the demo.");
        in.nextLine();
    }

    // A method that controls the demo part of the Java program.
    public static void demo(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        ParameterHelper paramHelper = new ParameterHelper();
        System.out.println("Read the ssm_only_policy.json file");
        String ssmOnlyPolicy = readFileAsString(ssmJSON);

        System.out.println("Resetting parameters to starting values for demo.");
        paramHelper.reset();

        System.out.println(
                """
                         This part of the demonstration shows how to toggle different parts of the system
                         to create situations where the web service fails, and shows how using a resilient
                         architecture can keep the web service running in spite of these failures.

                         At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                         The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.
                         The table name is contained in a Systems Manager parameter named self.param_helper.table.
                         To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.
                        """);
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        System.out.println(
                """
                         \nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as
                         healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                        Instead of failing when the recommendation service fails, the web service can return a static response.
                        While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.
                        """);
        paramHelper.put(paramHelper.failureResponse, "static");

        System.out.println("""
                Now, sending a GET request to the load balancer endpoint returns a static response.
                The service still reports as healthy because health checks are still shallow.
                """);
        demoChoices(loadBalancer);

        System.out.println("Let's reinstate the recommendation service.");
        paramHelper.put(paramHelper.tableName, paramHelper.dyntable);

        System.out.println("""
                Let's also substitute bad credentials for one of the instances in the target group so that it can't
                access the DynamoDB recommendation table. We will get an instance id value.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        AutoScaler autoScaler = new AutoScaler();

        // Create a new instance profile based on badCredsProfileName.
        templateCreator.createInstanceProfile(policyFile, policyName, badCredsProfileName, roleName);
        String badInstanceId = autoScaler.getBadInstance(autoScalingGroupName);
        System.out.println("The bad instance id values used for this demo is " + badInstanceId);

        String profileAssociationId = autoScaler.getInstanceProfile(badInstanceId);
        System.out.println("The association Id value is " + profileAssociationId);
        System.out.println("Replacing the profile for instance " + badInstanceId
                + " with a profile that contains bad credentials");
        autoScaler.replaceInstanceProfile(badInstanceId, badCredsProfileName, profileAssociationId);

        System.out.println(
                """
                        Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,
                        depending on which instance is selected by the load balancer.
                        """);

        demoChoices(loadBalancer);

        System.out.println("""
                Let's implement a deep health check. For this demo, a deep health check tests whether
                the web service can access the DynamoDB table that it depends on for recommendations. Note that
                the deep health check is only for ELB routing and not for Auto Scaling instance health.
                This kind of deep health check is not recommended for Auto Scaling instance health, because it
                risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.
                """);

        System.out.println("""
                By implementing deep health checks, the load balancer can detect when one of the instances is failing
                and take that instance out of rotation.
                """);

        paramHelper.put(paramHelper.healthCheck, "deep");

        System.out.println("""
                Now, checking target health indicates that the instance with bad credentials
                is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy
                instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because
                the load balancer takes unhealthy instances out of its rotation.
                """);

        demoChoices(loadBalancer);

        System.out.println(
                """
                        Because the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy
                        instance is to terminate it and let the auto scaler start a new instance to replace it.
                        """);
        autoScaler.terminateInstance(badInstanceId);

        System.out.println("""
                Even while the instance is terminating and the new instance is starting, sending a GET
                request to the web service continues to get a successful recommendation response because
                the load balancer routes requests to the healthy instances. After the replacement instance
                starts and reports as healthy, it is included in the load balancing rotation.
                Note that terminating and replacing an instance typically takes several minutes, during which time you
                can see the changing health check status until the new instance is running and healthy.
                """);

        demoChoices(loadBalancer);
        System.out.println(
                "If the recommendation service fails now, deep health checks mean all instances report as unhealthy.");
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        demoChoices(loadBalancer);
        paramHelper.reset();
    }

    public static void demoChoices(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        String[] actions = {
                "Send a GET request to the load balancer endpoint.",
                "Check the health of load balancer targets.",
                "Go to the next part of the demo."
        };
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("-".repeat(88));
            System.out.println("See the current state of the service by selecting one of the following choices:");
            for (int i = 0; i < actions.length; i++) {
                System.out.println(i + ": " + actions[i]);
            }

            try {
                System.out.print("\nWhich action would you like to take? ");
                int choice = scanner.nextInt();
                System.out.println("-".repeat(88));

                switch (choice) {
                    case 0 -> {
                        System.out.println("Request:\n");
                        System.out.println("GET http://" + loadBalancer.getEndpoint(lbName));
                        CloseableHttpClient httpClient = HttpClients.createDefault();

                        // Create an HTTP GET request to the ELB.
                        HttpGet httpGet = new HttpGet("http://" + loadBalancer.getEndpoint(lbName));

                        // Execute the request and get the response.
                        HttpResponse response = httpClient.execute(httpGet);
                        int statusCode = response.getStatusLine().getStatusCode();
                        System.out.println("HTTP Status Code: " + statusCode);

                        // Display the JSON response
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        reader.close();

                        // Print the formatted JSON response.
                        System.out.println("Full Response:\n");
                        System.out.println(jsonResponse.toString());

                        // Close the HTTP client.
                        httpClient.close();

                    }
                    case 1 -> {
                        System.out.println("\nChecking the health of load balancer targets:\n");
                        List<TargetHealthDescription> health = loadBalancer.checkTargetHealth(targetGroupName);
                        for (TargetHealthDescription target : health) {
                            System.out.printf("\tTarget %s on port %d is %s%n", target.target().id(),
                                    target.target().port(), target.targetHealth().stateAsString());
                        }
                        System.out.println("""
                                Note that it can take a minute or two for the health check to update
                                after changes are made.
                                """);
                    }
                    case 2 -> {
                        System.out.println("\nOkay, let's move on.");
                        System.out.println("-".repeat(88));
                        return; // Exit the method when choice is 2
                    }
                    default -> System.out.println("You must choose a value between 0-2. Please select again.");
                }

            } catch (java.util.InputMismatchException e) {
                System.out.println("Invalid input. Please select again.");
                scanner.nextLine(); // Clear the input buffer.
            }
        }
    }

    public static String readFileAsString(String filePath) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        return new String(bytes);
    }
}
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
public class AutoScaler {

    private static Ec2Client ec2Client;
    private static AutoScalingClient autoScalingClient;
    private static IamClient iamClient;

    private static SsmClient ssmClient;

    private IamClient getIAMClient() {
        if (iamClient == null) {
            iamClient = IamClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return iamClient;
    }

    private SsmClient getSSMClient() {
        if (ssmClient == null) {
            ssmClient = SsmClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ssmClient;
    }

    private Ec2Client getEc2Client() {
        if (ec2Client == null) {
            ec2Client = Ec2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ec2Client;
    }

    private AutoScalingClient getAutoScalingClient() {
        if (autoScalingClient == null) {
            autoScalingClient = AutoScalingClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return autoScalingClient;
    }

    /**
     * Terminates and instances in an EC2 Auto Scaling group. After an instance is
     * terminated, it can no longer be accessed.
     */
    public void terminateInstance(String instanceId) {
        TerminateInstanceInAutoScalingGroupRequest terminateInstanceIRequest = TerminateInstanceInAutoScalingGroupRequest
                .builder()
                .instanceId(instanceId)
                .shouldDecrementDesiredCapacity(false)
                .build();

        getAutoScalingClient().terminateInstanceInAutoScalingGroup(terminateInstanceIRequest);
        System.out.format("Terminated instance %s.", instanceId);
    }

    /**
     * Replaces the profile associated with a running instance. After the profile is
     * replaced, the instance is rebooted to ensure that it uses the new profile.
     * When
     * the instance is ready, Systems Manager is used to restart the Python web
     * server.
     */
    public void replaceInstanceProfile(String instanceId, String newInstanceProfileName, String profileAssociationId)
            throws InterruptedException {
        // Create an IAM instance profile specification.
        software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification iamInstanceProfile = software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification
                .builder()
                .name(newInstanceProfileName) // Make sure 'newInstanceProfileName' is a valid IAM Instance Profile
                                              // name.
                .build();

        // Replace the IAM instance profile association for the EC2 instance.
        ReplaceIamInstanceProfileAssociationRequest replaceRequest = ReplaceIamInstanceProfileAssociationRequest
                .builder()
                .iamInstanceProfile(iamInstanceProfile)
                .associationId(profileAssociationId) // Make sure 'profileAssociationId' is a valid association ID.
                .build();

        try {
            getEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);
            // Handle the response as needed.
        } catch (Ec2Exception e) {
            // Handle exceptions, log, or report the error.
            System.err.println("Error: " + e.getMessage());
        }
        System.out.format("Replaced instance profile for association %s with profile %s.", profileAssociationId,
                newInstanceProfileName);
        TimeUnit.SECONDS.sleep(15);
        boolean instReady = false;
        int tries = 0;

        // Reboot after 60 seconds
        while (!instReady) {
            if (tries % 6 == 0) {
                getEc2Client().rebootInstances(RebootInstancesRequest.builder()
                        .instanceIds(instanceId)
                        .build());
                System.out.println("Rebooting instance " + instanceId + " and waiting for it to be ready.");
            }
            tries++;
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            DescribeInstanceInformationResponse informationResponse = getSSMClient().describeInstanceInformation();
            List<InstanceInformation> instanceInformationList = informationResponse.instanceInformationList();
            for (InstanceInformation info : instanceInformationList) {
                if (info.instanceId().equals(instanceId)) {
                    instReady = true;
                    break;
                }
            }
        }

        SendCommandRequest sendCommandRequest = SendCommandRequest.builder()
                .instanceIds(instanceId)
                .documentName("AWS-RunShellScript")
                .parameters(Collections.singletonMap("commands",
                        Collections.singletonList("cd / && sudo python3 server.py 80")))
                .build();

        getSSMClient().sendCommand(sendCommandRequest);
        System.out.println("Restarted the Python web server on instance " + instanceId + ".");
    }

    public void openInboundPort(String secGroupId, String port, String ipAddress) {
        AuthorizeSecurityGroupIngressRequest ingressRequest = AuthorizeSecurityGroupIngressRequest.builder()
                .groupName(secGroupId)
                .cidrIp(ipAddress)
                .fromPort(Integer.parseInt(port))
                .build();

        getEc2Client().authorizeSecurityGroupIngress(ingressRequest);
        System.out.format("Authorized ingress to %s on port %s from %s.", secGroupId, port, ipAddress);
    }

    /**
     * Detaches a role from an instance profile, detaches policies from the role,
     * and deletes all the resources.
     */
    public void deleteInstanceProfile(String roleName, String profileName) {
        try {
            software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest getInstanceProfileRequest = software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest
                    .builder()
                    .instanceProfileName(profileName)
                    .build();

            GetInstanceProfileResponse response = getIAMClient().getInstanceProfile(getInstanceProfileRequest);
            String name = response.instanceProfile().instanceProfileName();
            System.out.println(name);

            RemoveRoleFromInstanceProfileRequest profileRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .roleName(roleName)
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(profileRequest);
            DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .build();

            getIAMClient().deleteInstanceProfile(deleteInstanceProfileRequest);
            System.out.println("Deleted instance profile " + profileName);

            DeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            // List attached role policies.
            ListAttachedRolePoliciesResponse rolesResponse = getIAMClient()
                    .listAttachedRolePolicies(role -> role.roleName(roleName));
            List<AttachedPolicy> attachedPolicies = rolesResponse.attachedPolicies();
            for (AttachedPolicy attachedPolicy : attachedPolicies) {
                DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
                        .roleName(roleName)
                        .policyArn(attachedPolicy.policyArn())
                        .build();

                getIAMClient().detachRolePolicy(request);
                System.out.println("Detached and deleted policy " + attachedPolicy.policyName());
            }

            getIAMClient().deleteRole(deleteRoleRequest);
            System.out.println("Instance profile and role deleted.");

        } catch (IamException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public void deleteTemplate(String templateName) {
        getEc2Client().deleteLaunchTemplate(name -> name.launchTemplateName(templateName));
        System.out.format(templateName + " was deleted.");
    }

    public void deleteAutoScaleGroup(String groupName) {
        DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder()
                .autoScalingGroupName(groupName)
                .forceDelete(true)
                .build();

        getAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);
        System.out.println(groupName + " was deleted.");
    }

    /*
     * Verify the default security group of the specified VPC allows ingress from
     * this
     * computer. This can be done by allowing ingress from this computer's IP
     * address. In some situations, such as connecting from a corporate network, you
     * must instead specify a prefix list ID. You can also temporarily open the port
     * to
     * any IP address while running this example. If you do, be sure to remove
     * public
     * access when you're done.
     * 
     */
    public GroupInfo verifyInboundPort(String VPC, int port, String ipAddress) {
        boolean portIsOpen = false;
        GroupInfo groupInfo = new GroupInfo();
        try {
            Filter filter = Filter.builder()
                    .name("group-name")
                    .values("default")
                    .build();

            Filter filter1 = Filter.builder()
                    .name("vpc-id")
                    .values(VPC)
                    .build();

            DescribeSecurityGroupsRequest securityGroupsRequest = DescribeSecurityGroupsRequest.builder()
                    .filters(filter, filter1)
                    .build();

            DescribeSecurityGroupsResponse securityGroupsResponse = getEc2Client()
                    .describeSecurityGroups(securityGroupsRequest);
            String securityGroup = securityGroupsResponse.securityGroups().get(0).groupName();
            groupInfo.setGroupName(securityGroup);

            for (SecurityGroup secGroup : securityGroupsResponse.securityGroups()) {
                System.out.println("Found security group: " + secGroup.groupId());

                for (IpPermission ipPermission : secGroup.ipPermissions()) {
                    if (ipPermission.fromPort() == port) {
                        System.out.println("Found inbound rule: " + ipPermission);
                        for (IpRange ipRange : ipPermission.ipRanges()) {
                            String cidrIp = ipRange.cidrIp();
                            if (cidrIp.startsWith(ipAddress) || cidrIp.equals("0.0.0.0/0")) {
                                System.out.println(cidrIp + " is applicable");
                                portIsOpen = true;
                            }
                        }

                        if (!ipPermission.prefixListIds().isEmpty()) {
                            System.out.println("Prefix lList is applicable");
                            portIsOpen = true;
                        }

                        if (!portIsOpen) {
                            System.out
                                    .println("The inbound rule does not appear to be open to either this computer's IP,"
                                            + " all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                        } else {
                            break;
                        }
                    }
                }
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }

        groupInfo.setPortOpen(portIsOpen);
        return groupInfo;
    }

    /*
     * Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto
     * Scaling group.
     * The target group specifies how the load balancer forward requests to the
     * instances
     * in the group.
     */
    public void attachLoadBalancerTargetGroup(String asGroupName, String targetGroupARN) {
        try {
            AttachLoadBalancerTargetGroupsRequest targetGroupsRequest = AttachLoadBalancerTargetGroupsRequest.builder()
                    .autoScalingGroupName(asGroupName)
                    .targetGroupARNs(targetGroupARN)
                    .build();

            getAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);
            System.out.println("Attached load balancer to " + asGroupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Creates an EC2 Auto Scaling group with the specified size.
    public String[] createGroup(int groupSize, String templateName, String autoScalingGroupName) {

        // Get availability zones.
        software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest zonesRequest = software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest
                .builder()
                .build();

        DescribeAvailabilityZonesResponse zonesResponse = getEc2Client().describeAvailabilityZones(zonesRequest);
        List<String> availabilityZoneNames = zonesResponse.availabilityZones().stream()
                .map(software.amazon.awssdk.services.ec2.model.AvailabilityZone::zoneName)
                .collect(Collectors.toList());

        String availabilityZones = String.join(",", availabilityZoneNames);
        LaunchTemplateSpecification specification = LaunchTemplateSpecification.builder()
                .launchTemplateName(templateName)
                .version("$Default")
                .build();

        String[] zones = availabilityZones.split(",");
        CreateAutoScalingGroupRequest groupRequest = CreateAutoScalingGroupRequest.builder()
                .launchTemplate(specification)
                .availabilityZones(zones)
                .maxSize(groupSize)
                .minSize(groupSize)
                .autoScalingGroupName(autoScalingGroupName)
                .build();

        try {
            getAutoScalingClient().createAutoScalingGroup(groupRequest);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Created an EC2 Auto Scaling group named " + autoScalingGroupName);
        return zones;
    }

    public String getDefaultVPC() {
        // Define the filter.
        Filter defaultFilter = Filter.builder()
                .name("is-default")
                .values("true")
                .build();

        software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest request = software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest
                .builder()
                .filters(defaultFilter)
                .build();

        DescribeVpcsResponse response = getEc2Client().describeVpcs(request);
        return response.vpcs().get(0).vpcId();
    }

    // Gets the default subnets in a VPC for a specified list of Availability Zones.
    public List<Subnet> getSubnets(String vpcId, String[] availabilityZones) {
        List<Subnet> subnets = null;
        Filter vpcFilter = Filter.builder()
                .name("vpc-id")
                .values(vpcId)
                .build();

        Filter azFilter = Filter.builder()
                .name("availability-zone")
                .values(availabilityZones)
                .build();

        Filter defaultForAZ = Filter.builder()
                .name("default-for-az")
                .values("true")
                .build();

        DescribeSubnetsRequest request = DescribeSubnetsRequest.builder()
                .filters(vpcFilter, azFilter, defaultForAZ)
                .build();

        DescribeSubnetsResponse response = getEc2Client().describeSubnets(request);
        subnets = response.subnets();
        return subnets;
    }

    // Gets data about the instances in the EC2 Auto Scaling group.
    public String getBadInstance(String groupName) {
        DescribeAutoScalingGroupsRequest request = DescribeAutoScalingGroupsRequest.builder()
                .autoScalingGroupNames(groupName)
                .build();

        DescribeAutoScalingGroupsResponse response = getAutoScalingClient().describeAutoScalingGroups(request);
        AutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);
        List<String> instanceIds = autoScalingGroup.instances().stream()
                .map(instance -> instance.instanceId())
                .collect(Collectors.toList());

        String[] instanceIdArray = instanceIds.toArray(new String[0]);
        for (String instanceId : instanceIdArray) {
            System.out.println("Instance ID: " + instanceId);
            return instanceId;
        }
        return "";
    }

    // Gets data about the profile associated with an instance.
    public String getInstanceProfile(String instanceId) {
        Filter filter = Filter.builder()
                .name("instance-id")
                .values(instanceId)
                .build();

        DescribeIamInstanceProfileAssociationsRequest associationsRequest = DescribeIamInstanceProfileAssociationsRequest
                .builder()
                .filters(filter)
                .build();

        DescribeIamInstanceProfileAssociationsResponse response = getEc2Client()
                .describeIamInstanceProfileAssociations(associationsRequest);
        return response.iamInstanceProfileAssociations().get(0).associationId();
    }

    public void deleteRolesPolicies(String policyName, String roleName, String InstanceProfile) {
        ListPoliciesRequest listPoliciesRequest = ListPoliciesRequest.builder().build();
        ListPoliciesResponse listPoliciesResponse = getIAMClient().listPolicies(listPoliciesRequest);
        for (Policy policy : listPoliciesResponse.policies()) {
            if (policy.policyName().equals(policyName)) {
                // List the entities (users, groups, roles) that are attached to the policy.
                software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest listEntitiesRequest = software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest
                        .builder()
                        .policyArn(policy.arn())
                        .build();
                ListEntitiesForPolicyResponse listEntitiesResponse = iamClient
                        .listEntitiesForPolicy(listEntitiesRequest);
                if (!listEntitiesResponse.policyGroups().isEmpty() || !listEntitiesResponse.policyUsers().isEmpty()
                        || !listEntitiesResponse.policyRoles().isEmpty()) {
                    // Detach the policy from any entities it is attached to.
                    DetachRolePolicyRequest detachPolicyRequest = DetachRolePolicyRequest.builder()
                            .policyArn(policy.arn())
                            .roleName(roleName) // Specify the name of the IAM role
                            .build();

                    getIAMClient().detachRolePolicy(detachPolicyRequest);
                    System.out.println("Policy detached from entities.");
                }

                // Now, you can delete the policy.
                DeletePolicyRequest deletePolicyRequest = DeletePolicyRequest.builder()
                        .policyArn(policy.arn())
                        .build();

                getIAMClient().deletePolicy(deletePolicyRequest);
                System.out.println("Policy deleted successfully.");
                break;
            }
        }

        // List the roles associated with the instance profile
        ListInstanceProfilesForRoleRequest listRolesRequest = ListInstanceProfilesForRoleRequest.builder()
                .roleName(roleName)
                .build();

        // Detach the roles from the instance profile
        ListInstanceProfilesForRoleResponse listRolesResponse = iamClient.listInstanceProfilesForRole(listRolesRequest);
        for (software.amazon.awssdk.services.iam.model.InstanceProfile profile : listRolesResponse.instanceProfiles()) {
            RemoveRoleFromInstanceProfileRequest removeRoleRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(InstanceProfile)
                    .roleName(roleName) // Remove the extra dot here
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(removeRoleRequest);
            System.out.println("Role " + roleName + " removed from instance profile " + InstanceProfile);
        }

        // Delete the instance profile after removing all roles
        DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                .instanceProfileName(InstanceProfile)
                .build();

        getIAMClient().deleteInstanceProfile(r -> r.instanceProfileName(InstanceProfile));
        System.out.println(InstanceProfile + " Deleted");
        System.out.println("All roles and policies are deleted.");
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
public class LoadBalancer {
    public ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;

    public ElasticLoadBalancingV2Client getLoadBalancerClient() {
        if (elasticLoadBalancingV2Client == null) {
            elasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }

        return elasticLoadBalancingV2Client;
    }

    // Checks the health of the instances in the target group.
    public List<TargetHealthDescription> checkTargetHealth(String targetGroupName) {
        DescribeTargetGroupsRequest targetGroupsRequest = DescribeTargetGroupsRequest.builder()
                .names(targetGroupName)
                .build();

        DescribeTargetGroupsResponse tgResponse = getLoadBalancerClient().describeTargetGroups(targetGroupsRequest);

        DescribeTargetHealthRequest healthRequest = DescribeTargetHealthRequest.builder()
                .targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())
                .build();

        DescribeTargetHealthResponse healthResponse = getLoadBalancerClient().describeTargetHealth(healthRequest);
        return healthResponse.targetHealthDescriptions();
    }

    // Gets the HTTP endpoint of the load balancer.
    public String getEndpoint(String lbName) {
        DescribeLoadBalancersResponse res = getLoadBalancerClient()
                .describeLoadBalancers(describe -> describe.names(lbName));
        return res.loadBalancers().get(0).dnsName();
    }

    // Deletes a load balancer.
    public void deleteLoadBalancer(String lbName) {
        try {
            // Use a waiter to delete the Load Balancer.
            DescribeLoadBalancersResponse res = getLoadBalancerClient()
                    .describeLoadBalancers(describe -> describe.names(lbName));
            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())
                    .build();

            getLoadBalancerClient().deleteLoadBalancer(
                    builder -> builder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancersDeleted(request);
            waiterResponse.matched().response().ifPresent(System.out::println);

        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(lbName + " was deleted.");
    }

    // Deletes the target group.
    public void deleteTargetGroup(String targetGroupName) {
        try {
            DescribeTargetGroupsResponse res = getLoadBalancerClient()
                    .describeTargetGroups(describe -> describe.names(targetGroupName));
            getLoadBalancerClient()
                    .deleteTargetGroup(builder -> builder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));
        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(targetGroupName + " was deleted.");
    }

    // Verify this computer can successfully send a GET request to the load balancer
    // endpoint.
    public boolean verifyLoadBalancerEndpoint(String elbDnsName) throws IOException, InterruptedException {
        boolean success = false;
        int retries = 3;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // Create an HTTP GET request to the ELB.
        HttpGet httpGet = new HttpGet("http://" + elbDnsName);
        try {
            while ((!success) && (retries > 0)) {
                // Execute the request and get the response.
                HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);
                if (statusCode == 200) {
                    success = true;
                } else {
                    retries--;
                    System.out.println("Got connection error from load balancer endpoint, retrying...");
                    TimeUnit.SECONDS.sleep(15);
                }
            }

        } catch (org.apache.http.conn.HttpHostConnectException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Status.." + success);
        return success;
    }

    /*
     * Creates an Elastic Load Balancing target group. The target group specifies
     * how
     * the load balancer forward requests to instances in the group and how instance
     * health is checked.
     */
    public String createTargetGroup(String protocol, int port, String vpcId, String targetGroupName) {
        CreateTargetGroupRequest targetGroupRequest = CreateTargetGroupRequest.builder()
                .healthCheckPath("/healthcheck")
                .healthCheckTimeoutSeconds(5)
                .port(port)
                .vpcId(vpcId)
                .name(targetGroupName)
                .protocol(protocol)
                .build();

        CreateTargetGroupResponse targetGroupResponse = getLoadBalancerClient().createTargetGroup(targetGroupRequest);
        String targetGroupArn = targetGroupResponse.targetGroups().get(0).targetGroupArn();
        String targetGroup = targetGroupResponse.targetGroups().get(0).targetGroupName();
        System.out.println("The " + targetGroup + " was created with ARN" + targetGroupArn);
        return targetGroupArn;
    }

    /*
     * Creates an Elastic Load Balancing load balancer that uses the specified
     * subnets
     * and forwards requests to the specified target group.
     */
    public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port,
            String protocol) {
        try {
            List<String> subnetIdStrings = subnetIds.stream()
                    .map(Subnet::subnetId)
                    .collect(Collectors.toList());

            CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder()
                    .subnets(subnetIdStrings)
                    .name(lbName)
                    .scheme("internet-facing")
                    .build();

            // Create and wait for the load balancer to become available.
            CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest);
            String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();

            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(lbARN)
                    .build();

            System.out.println("Waiting for Load Balancer " + lbName + " to become available.");
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancerAvailable(request);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Load Balancer " + lbName + " is available.");

            // Get the DNS name (endpoint) of the load balancer.
            String lbDNSName = lsResponse.loadBalancers().get(0).dnsName();
            System.out.println("*** Load Balancer DNS Name: " + lbDNSName);

            // Create a listener for the load balance.
            Action action = Action.builder()
                    .targetGroupArn(targetGroupARN)
                    .type("forward")
                    .build();

            CreateListenerRequest listenerRequest = CreateListenerRequest.builder()
                    .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())
                    .defaultActions(action)
                    .port(port)
                    .protocol(protocol)
                    .build();

            getLoadBalancerClient().createListener(listenerRequest);
            System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group "
                    + targetGroupARN);

            // Return the load balancer DNS name.
            return lbDNSName;

        } catch (ElasticLoadBalancingV2Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
public class Database {

    private static DynamoDbClient dynamoDbClient;

    public static DynamoDbClient getDynamoDbClient() {
        if (dynamoDbClient == null) {
            dynamoDbClient = DynamoDbClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return dynamoDbClient;
    }

    // Checks to see if the Amazon DynamoDB table exists.
    private boolean doesTableExist(String tableName) {
        try {
            // Describe the table and catch any exceptions.
            DescribeTableRequest describeTableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            getDynamoDbClient().describeTable(describeTableRequest);
            System.out.println("Table '" + tableName + "' exists.");
            return true;

        } catch (ResourceNotFoundException e) {
            System.out.println("Table '" + tableName + "' does not exist.");
        } catch (DynamoDbException e) {
            System.err.println("Error checking table existence: " + e.getMessage());
        }
        return false;
    }

    /*
     * Creates a DynamoDB table to use a recommendation service. The table has a
     * hash key named 'MediaType' that defines the type of media recommended, such
     * as
     * Book or Movie, and a range key named 'ItemId' that, combined with the
     * MediaType,
     * forms a unique identifier for the recommended item.
     */
    public void createTable(String tableName, String fileName) throws IOException {
        // First check to see if the table exists.
        boolean doesExist = doesTableExist(tableName);
        if (!doesExist) {
            DynamoDbWaiter dbWaiter = getDynamoDbClient().waiter();
            CreateTableRequest createTableRequest = CreateTableRequest.builder()
                    .tableName(tableName)
                    .attributeDefinitions(
                            AttributeDefinition.builder()
                                    .attributeName("MediaType")
                                    .attributeType(ScalarAttributeType.S)
                                    .build(),
                            AttributeDefinition.builder()
                                    .attributeName("ItemId")
                                    .attributeType(ScalarAttributeType.N)
                                    .build())
                    .keySchema(
                            KeySchemaElement.builder()
                                    .attributeName("MediaType")
                                    .keyType(KeyType.HASH)
                                    .build(),
                            KeySchemaElement.builder()
                                    .attributeName("ItemId")
                                    .keyType(KeyType.RANGE)
                                    .build())
                    .provisionedThroughput(
                            ProvisionedThroughput.builder()
                                    .readCapacityUnits(5L)
                                    .writeCapacityUnits(5L)
                                    .build())
                    .build();

            getDynamoDbClient().createTable(createTableRequest);
            System.out.println("Creating table " + tableName + "...");

            // Wait until the Amazon DynamoDB table is created.
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Table " + tableName + " created.");

            // Add records to the table.
            populateTable(fileName, tableName);
        }
    }

    public void deleteTable(String tableName) {
        getDynamoDbClient().deleteTable(table -> table.tableName(tableName));
        System.out.println("Table " + tableName + " deleted.");
    }

    // Populates the table with data located in a JSON file using the DynamoDB
    // enhanced client.
    public void populateTable(String fileName, String tableName) throws IOException {
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(getDynamoDbClient())
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        File jsonFile = new File(fileName);
        JsonNode rootNode = objectMapper.readTree(jsonFile);

        DynamoDbTable<Recommendation> mappedTable = enhancedClient.table(tableName,
                TableSchema.fromBean(Recommendation.class));
        for (JsonNode currentNode : rootNode) {
            String mediaType = currentNode.path("MediaType").path("S").asText();
            int itemId = currentNode.path("ItemId").path("N").asInt();
            String title = currentNode.path("Title").path("S").asText();
            String creator = currentNode.path("Creator").path("S").asText();

            // Create a Recommendation object and set its properties.
            Recommendation rec = new Recommendation();
            rec.setMediaType(mediaType);
            rec.setItemId(itemId);
            rec.setTitle(title);
            rec.setCreator(creator);

            // Put the item into the DynamoDB table.
            mappedTable.putItem(rec); // Add the Recommendation to the list.
        }
        System.out.println("Added all records to the " + tableName);
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
public class ParameterHelper {

    String tableName = "doc-example-resilient-architecture-table";
    String dyntable = "doc-example-recommendation-service";
    String failureResponse = "doc-example-resilient-architecture-failure-response";
    String healthCheck = "doc-example-resilient-architecture-health-check";

    public void reset() {
        put(dyntable, tableName);
        put(failureResponse, "none");
        put(healthCheck, "shallow");
    }

    public void put(String name, String value) {
        SsmClient ssmClient = SsmClient.builder()
                .region(Region.US_EAST_1)
                .build();

        PutParameterRequest parameterRequest = PutParameterRequest.builder()
                .name(name)
                .value(value)
                .overwrite(true)
                .type("String")
                .build();

        ssmClient.putParameter(parameterRequest);
        System.out.printf("Setting demo parameter %s to '%s'.", name, value);
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# SDK for Java 2.x を使用した MediaStore の例
<a name="java_2_mediastore_code_examples"></a>

次のコード例は、MediaStore AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateContainer`
<a name="mediastore_CreateContainer_java_2_topic"></a>

次のコード例は、`CreateContainer` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediastore#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.mediastore.MediaStoreClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediastore.model.CreateContainerRequest;
import software.amazon.awssdk.services.mediastore.model.CreateContainerResponse;
import software.amazon.awssdk.services.mediastore.model.MediaStoreException;

/**
 * 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 CreateContainer {
    public static long sleepTime = 10;

    public static void main(String[] args) {
        final String usage = """

                Usage:    <containerName>

                Where:
                   containerName - The name of the container to create.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String containerName = args[0];
        Region region = Region.US_EAST_1;
        MediaStoreClient mediaStoreClient = MediaStoreClient.builder()
                .region(region)
                .build();

        createMediaContainer(mediaStoreClient, containerName);
        mediaStoreClient.close();
    }


    public static void createMediaContainer(MediaStoreClient mediaStoreClient, String containerName) {
        try {
            CreateContainerRequest containerRequest = CreateContainerRequest.builder()
                    .containerName(containerName)
                    .build();

            CreateContainerResponse containerResponse = mediaStoreClient.createContainer(containerRequest);
            String status = containerResponse.container().status().toString();
            while (!status.equalsIgnoreCase("Active")) {
                status = DescribeContainer.checkContainer(mediaStoreClient, containerName);
                System.out.println("Status - " + status);
                Thread.sleep(sleepTime * 1000);
            }

            System.out.println("The container ARN value is " + containerResponse.container().arn());
            System.out.println("Finished ");

        } catch (MediaStoreException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[CreateContainer](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/CreateContainer)」を参照してください。**

### `DeleteContainer`
<a name="mediastore_DeleteContainer_java_2_topic"></a>

次のコード例は、`DeleteContainer` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediastore#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.mediastore.MediaStoreClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediastore.model.CreateContainerRequest;
import software.amazon.awssdk.services.mediastore.model.CreateContainerResponse;
import software.amazon.awssdk.services.mediastore.model.MediaStoreException;

/**
 * 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 CreateContainer {
    public static long sleepTime = 10;

    public static void main(String[] args) {
        final String usage = """

                Usage:    <containerName>

                Where:
                   containerName - The name of the container to create.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String containerName = args[0];
        Region region = Region.US_EAST_1;
        MediaStoreClient mediaStoreClient = MediaStoreClient.builder()
                .region(region)
                .build();

        createMediaContainer(mediaStoreClient, containerName);
        mediaStoreClient.close();
    }


    public static void createMediaContainer(MediaStoreClient mediaStoreClient, String containerName) {
        try {
            CreateContainerRequest containerRequest = CreateContainerRequest.builder()
                    .containerName(containerName)
                    .build();

            CreateContainerResponse containerResponse = mediaStoreClient.createContainer(containerRequest);
            String status = containerResponse.container().status().toString();
            while (!status.equalsIgnoreCase("Active")) {
                status = DescribeContainer.checkContainer(mediaStoreClient, containerName);
                System.out.println("Status - " + status);
                Thread.sleep(sleepTime * 1000);
            }

            System.out.println("The container ARN value is " + containerResponse.container().arn());
            System.out.println("Finished ");

        } catch (MediaStoreException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「*DeleteContainer*」を参照してください。[https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/DeleteContainer](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/DeleteContainer)

### `DeleteObject`
<a name="mediastore_DeleteObject_java_2_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediastore#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediastore.MediaStoreClient;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;
import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient;
import software.amazon.awssdk.services.mediastoredata.model.DeleteObjectRequest;
import software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException;
import java.net.URI;
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 DeleteObject {
    public static void main(String[] args) throws URISyntaxException {
        final String usage = """

                Usage:    <completePath> <containerName>

                Where:
                   completePath - The path (including the container) of the item to delete.
                   containerName - The name of the container.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String completePath = args[0];
        String containerName = args[1];
        Region region = Region.US_EAST_1;
        URI uri = new URI(getEndpoint(containerName));

        MediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder()
                .endpointOverride(uri)
                .region(region)
                .build();

        deleteMediaObject(mediaStoreData, completePath);
        mediaStoreData.close();
    }

    public static void deleteMediaObject(MediaStoreDataClient mediaStoreData, String completePath) {
        try {
            DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
                    .path(completePath)
                    .build();

            mediaStoreData.deleteObject(deleteObjectRequest);

        } catch (MediaStoreDataException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    private static String getEndpoint(String containerName) {
        Region region = Region.US_EAST_1;
        MediaStoreClient mediaStoreClient = MediaStoreClient.builder()
                .region(region)
                .build();

        DescribeContainerRequest containerRequest = DescribeContainerRequest.builder()
                .containerName(containerName)
                .build();

        DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest);
        mediaStoreClient.close();
        return response.container().endpoint();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/DeleteObject)」を参照してください。

### `DescribeContainer`
<a name="mediastore_DescribeContainer_java_2_topic"></a>

次のコード例は、`DescribeContainer` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediastore#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediastore.MediaStoreClient;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;
import software.amazon.awssdk.services.mediastore.model.MediaStoreException;

/**
 * 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 DescribeContainer {

    public static void main(String[] args) {
        final String usage = """

                Usage:    <containerName>

                Where:
                   containerName - The name of the container to describe.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String containerName = args[0];
        Region region = Region.US_EAST_1;
        MediaStoreClient mediaStoreClient = MediaStoreClient.builder()
                .region(region)
                .build();

        System.out.println("Status is " + checkContainer(mediaStoreClient, containerName));
        mediaStoreClient.close();
    }

    public static String checkContainer(MediaStoreClient mediaStoreClient, String containerName) {
        try {
            DescribeContainerRequest describeContainerRequest = DescribeContainerRequest.builder()
                    .containerName(containerName)
                    .build();

            DescribeContainerResponse containerResponse = mediaStoreClient.describeContainer(describeContainerRequest);
            System.out.println("The container name is " + containerResponse.container().name());
            System.out.println("The container ARN is " + containerResponse.container().arn());
            return containerResponse.container().status().toString();

        } catch (MediaStoreException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeContainer](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/DescribeContainer)」を参照してください。

### `GetObject`
<a name="mediastore_GetObject_java_2_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediastore#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediastore.MediaStoreClient;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;
import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient;
import software.amazon.awssdk.services.mediastoredata.model.GetObjectRequest;
import software.amazon.awssdk.services.mediastoredata.model.GetObjectResponse;
import software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
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 GetObject {
    public static void main(String[] args) throws URISyntaxException {
        final String usage = """

                Usage:    <completePath> <containerName> <savePath>

                Where:
                   completePath - The path of the object in the container (for example, Videos5/sampleVideo.mp4).
                   containerName - The name of the container.
                   savePath - The path on the local drive where the file is saved, including the file name (for example, C:/AWS/myvid.mp4).
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String completePath = args[0];
        String containerName = args[1];
        String savePath = args[2];

        Region region = Region.US_EAST_1;
        URI uri = new URI(getEndpoint(containerName));
        MediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder()
                .endpointOverride(uri)
                .region(region)
                .build();

        getMediaObject(mediaStoreData, completePath, savePath);
        mediaStoreData.close();
    }

    public static void getMediaObject(MediaStoreDataClient mediaStoreData, String completePath, String savePath) {

        try {
            GetObjectRequest objectRequest = GetObjectRequest.builder()
                    .path(completePath)
                    .build();

            // Write out the data to a file.
            ResponseInputStream<GetObjectResponse> data = mediaStoreData.getObject(objectRequest);
            byte[] buffer = new byte[data.available()];
            data.read(buffer);

            File targetFile = new File(savePath);
            OutputStream outStream = new FileOutputStream(targetFile);
            outStream.write(buffer);
            System.out.println("The data was written to " + savePath);

        } catch (MediaStoreDataException | IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    private static String getEndpoint(String containerName) {
        Region region = Region.US_EAST_1;
        MediaStoreClient mediaStoreClient = MediaStoreClient.builder()
                .region(region)
                .build();

        DescribeContainerRequest containerRequest = DescribeContainerRequest.builder()
                .containerName(containerName)
                .build();

        DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest);
        return response.container().endpoint();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/GetObject)」を参照してください。

### `ListContainers`
<a name="mediastore_ListContainers_java_2_topic"></a>

次のコード例は、`ListContainers` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediastore#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediastore.MediaStoreClient;
import software.amazon.awssdk.services.mediastore.model.Container;
import software.amazon.awssdk.services.mediastore.model.ListContainersResponse;
import software.amazon.awssdk.services.mediastore.model.MediaStoreException;
import java.util.List;

/**
 * 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 ListContainers {

    public static void main(String[] args) {

        Region region = Region.US_EAST_1;
        MediaStoreClient mediaStoreClient = MediaStoreClient.builder()
                .region(region)
                .build();

        listAllContainers(mediaStoreClient);
        mediaStoreClient.close();
    }

    public static void listAllContainers(MediaStoreClient mediaStoreClient) {
        try {
            ListContainersResponse containersResponse = mediaStoreClient.listContainers();
            List<Container> containers = containersResponse.containers();
            for (Container container : containers) {
                System.out.println("Container name is " + container.name());
            }

        } catch (MediaStoreException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[ListContainers](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/ListContainers)」を参照してください。**

### `PutObject`
<a name="mediastore_PutObject_java_2_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediastore#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediastore.MediaStoreClient;
import software.amazon.awssdk.services.mediastoredata.MediaStoreDataClient;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.mediastoredata.model.PutObjectRequest;
import software.amazon.awssdk.services.mediastoredata.model.MediaStoreDataException;
import software.amazon.awssdk.services.mediastoredata.model.PutObjectResponse;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerRequest;
import software.amazon.awssdk.services.mediastore.model.DescribeContainerResponse;
import java.io.File;
import java.net.URI;
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 PutObject {
    public static void main(String[] args) throws URISyntaxException {
        final String USAGE = """

                To run this example, supply the name of a container, a file location to use, and path in the container\s

                Ex: <containerName> <filePath> <completePath>
                """;

        if (args.length < 3) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String containerName = args[0];
        String filePath = args[1];
        String completePath = args[2];

        Region region = Region.US_EAST_1;
        URI uri = new URI(getEndpoint(containerName));
        MediaStoreDataClient mediaStoreData = MediaStoreDataClient.builder()
                .endpointOverride(uri)
                .region(region)
                .build();

        putMediaObject(mediaStoreData, filePath, completePath);
        mediaStoreData.close();
    }

    public static void putMediaObject(MediaStoreDataClient mediaStoreData, String filePath, String completePath) {
        try {
            File myFile = new File(filePath);
            RequestBody requestBody = RequestBody.fromFile(myFile);

            PutObjectRequest objectRequest = PutObjectRequest.builder()
                    .path(completePath)
                    .contentType("video/mp4")
                    .build();

            PutObjectResponse response = mediaStoreData.putObject(objectRequest, requestBody);
            System.out.println("The saved object is " + response.storageClass().toString());

        } catch (MediaStoreDataException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static String getEndpoint(String containerName) {

        Region region = Region.US_EAST_1;
        MediaStoreClient mediaStoreClient = MediaStoreClient.builder()
                .region(region)
                .build();

        DescribeContainerRequest containerRequest = DescribeContainerRequest.builder()
                .containerName(containerName)
                .build();

        DescribeContainerResponse response = mediaStoreClient.describeContainer(containerRequest);
        return response.container().endpoint();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediastore-2017-09-01/PutObject)」を参照してください。

# AWS Entity Resolution SDK for Java 2.x を使用した例
<a name="java_2_entityresolution_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Entity Resolution。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Entity Resolutionは
<a name="entityresolution_Hello_java_2_topic"></a>

次のコード例は、 AWS Entity Resolutionの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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 HelloEntityResoultion {

    private static final Logger logger = LoggerFactory.getLogger(HelloEntityResoultion.class);

    private static EntityResolutionAsyncClient entityResolutionAsyncClient;
    public static void main(String[] args) {
        listMatchingWorkflows();
    }

    public static EntityResolutionAsyncClient getResolutionAsyncClient() {
        if (entityResolutionAsyncClient == null) {
            /*
            The `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java, version 2,
            and it is designed to provide a high-performance, asynchronous HTTP client for interacting with AWS services.
             It uses the Netty framework to handle the underlying network communication and the Java NIO API to
             provide a non-blocking, event-driven approach to HTTP requests and responses.
             */

            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(50)  // Adjust as needed.
                .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
                .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
                .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
                .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
                .retryStrategy(RetryMode.STANDARD)
                .build();

            entityResolutionAsyncClient = EntityResolutionAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return entityResolutionAsyncClient;
    }

    /**
     * Lists all matching workflows using an asynchronous paginator.
     * <p>
     * This method requests a paginated list of matching workflows from the
     * AWS Entity Resolution service and logs the names of the retrieved workflows.
     * It uses an asynchronous approach with a paginator and waits for the operation
     * to complete using {@code CompletableFuture#join()}.
     * </p>
     */
    public static void listMatchingWorkflows() {
        ListMatchingWorkflowsRequest request = ListMatchingWorkflowsRequest.builder().build();

        ListMatchingWorkflowsPublisher paginator =
            getResolutionAsyncClient().listMatchingWorkflowsPaginator(request);

        // Iterate through the paginated results asynchronously
        CompletableFuture<Void> future = paginator.subscribe(response -> {
            response.workflowSummaries().forEach(workflow ->
                logger.info("Matching Workflow Name: " + workflow.workflowName())
            );
        });

        // Wait for the asynchronous operation to complete
        future.join();
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListMatchingWorkflows](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/ListMatchingWorkflows)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="entityresolution_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ スキーママッピングを作成します。
+  AWS Entity Resolution ワークフローを作成します。
+ ワークフローの照合ジョブを開始します。
+ 照合ジョブの詳細を取得します。
+ スキーママッピングを取得します。
+ すべてのスキーママッピングを一覧表示します。
+ スキーママッピングリソースにタグを付けます。
+  AWS Entity Resolution アセットを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。
 AWS Entity Resolution 機能を示すインタラクティブなシナリオを実行します。  

```
public class EntityResScenario {
    private static final Logger logger = LoggerFactory.getLogger(EntityResScenario.class);
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final String STACK_NAME = "EntityResolutionCdkStack2";
    private static final String ENTITY_RESOLUTION_ROLE_ARN_KEY = "EntityResolutionRoleArn";
    private static final String GLUE_DATA_BUCKET_NAME_KEY = "GlueDataBucketName";
    private static final String JSON_GLUE_TABLE_ARN_KEY = "JsonErGlueTableArn";
    private static final String CSV_GLUE_TABLE_ARN_KEY = "CsvErGlueTableArn";
    private static String glueBucketName;
    private static String workflowName = "workflow-" + UUID.randomUUID();

    private static String jsonSchemaMappingName = "jsonschema-" + UUID.randomUUID();
    private static String jsonSchemaMappingArn = null;
    private static String csvSchemaMappingName = "csv-" + UUID.randomUUID();
    private static String roleARN;
    private static String csvGlueTableArn;
    private static String jsonGlueTableArn;
    private static Scanner scanner = new Scanner(System.in);

    private static EntityResActions actions = new EntityResActions();

    public static void main(String[] args) throws InterruptedException {

        logger.info("Welcome to the AWS Entity Resolution Scenario.");
        logger.info("""
            AWS Entity Resolution is a fully-managed machine learning service provided by 
            Amazon Web Services (AWS) that helps organizations extract, link, and 
            organize information from multiple data sources. It leverages natural 
            language processing and deep learning models to identify and resolve 
            entities, such as people, places, organizations, and products, 
            across structured and unstructured data.
                         
            With Entity Resolution, customers can build robust data integration 
            pipelines to combine and reconcile data from multiple systems, databases, 
            and documents. The service can handle ambiguous, incomplete, or conflicting 
            information, and provide a unified view of entities and their relationships. 
            This can be particularly valuable in applications such as customer 360, 
            fraud detection, supply chain management, and knowledge management, where 
            accurate entity identification is crucial.
                         
            The `EntityResolutionAsyncClient` interface in the AWS SDK for Java 2.x 
            provides a set of methods to programmatically interact with the AWS Entity 
            Resolution service. This allows developers to automate the entity extraction, 
            linking, and deduplication process as part of their data processing workflows. 
            With Entity Resolution, organizations can unlock the value of their data, 
            improve decision-making, and enhance customer experiences by having a reliable, 
            comprehensive view of their key entities.
            """);

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("""
            To prepare the AWS resources needed for this scenario application, the next step uploads
            a CloudFormation template whose resulting stack creates the following resources:
            - An AWS Glue Data Catalog table
            - An AWS IAM role
            - An AWS S3 bucket
            - An AWS Entity Resolution Schema
                            
            It can take a couple minutes for the Stack to finish creating the resources.
            """);
        waitForInputToContinue(scanner);
        logger.info("Generating resources...");
        CloudFormationHelper.deployCloudFormationStack(STACK_NAME);
        Map<String, String> outputsMap = CloudFormationHelper.getStackOutputsAsync(STACK_NAME).join();
        roleARN = outputsMap.get(ENTITY_RESOLUTION_ROLE_ARN_KEY);
        glueBucketName = outputsMap.get(GLUE_DATA_BUCKET_NAME_KEY);
        csvGlueTableArn = outputsMap.get(CSV_GLUE_TABLE_ARN_KEY);
        jsonGlueTableArn = outputsMap.get(JSON_GLUE_TABLE_ARN_KEY);
        logger.info(DASHES);
        waitForInputToContinue(scanner);

        try {
            runScenario();

        } catch (Exception ce) {
            Throwable cause = ce.getCause();
            logger.error("An exception happened: " + (cause != null ? cause.getMessage() : ce.getMessage()));
        }
    }

    private static void runScenario() throws InterruptedException {
        /*
         This JSON is a valid input for the AWS Entity Resolution service.
         The JSON represents an array of three objects, each containing an "id", "name", and "email"
         property. This format aligns with the expected input structure for the
         Entity Resolution service.
         */
        String json = """
            {"id":"1","name":"Jane Doe","email":"jane.doe@example.com"}
            {"id":"2","name":"John Doe","email":"john.doe@example.com"}
            {"id":"3","name":"Jorge Souza","email":"jorge_souza@example.com"}
            """;
        logger.info("Upload the following JSON objects to the {} S3 bucket.", glueBucketName);
        logger.info(json);
        String csv = """
            id,name,email,phone
            1,Jane B.,Doe,jane.doe@example.com,555-876-9846
            2,John Doe Jr.,john.doe@example.com,555-654-3210
            3,María García,maría_garcia@company.com,555-567-1234
            4,Mary Major,mary_major@company.com,555-222-3333
            """;
        logger.info("Upload the following CSV data to the {} S3 bucket.", glueBucketName);
        logger.info(csv);
        waitForInputToContinue(scanner);
        try {
            actions.uploadInputData(glueBucketName, json, csv);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();

            if (cause == null) {
                logger.error("Failed to upload input data: {}", ce.getMessage(), ce);
            }

            if (cause instanceof ResourceNotFoundException) {
                logger.error("Failed to upload input data as the resource was not found: {}", cause.getMessage(), cause);
            }
            return;
        }
        logger.info("The JSON and CSV objects have been uploaded to the S3 bucket.");
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("1. Create Schema Mapping");
        logger.info("""
            Entity Resolution schema mapping aligns and integrates data from 
            multiple sources by identifying and matching corresponding entities 
            like customers or products. It unifies schemas, resolves conflicts, 
            and uses machine learning to link related entities, enabling a 
            consolidated, accurate view for improved data quality and decision-making.
                        
            In this example, the schema mapping lines up with the fields in the JSON and CSV objects. That is, 
            it contains these fields: id, name, and email. 
            """);
        try {
            CreateSchemaMappingResponse response = actions.createSchemaMappingAsync(jsonSchemaMappingName).join();
            jsonSchemaMappingName = response.schemaName();
            logger.info("The JSON schema mapping name is " + jsonSchemaMappingName);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();

            if (cause == null) {
                logger.error("Failed to create JSON schema mapping: {}", ce.getMessage(), ce);
            }

            if (cause instanceof ConflictException) {
                logger.error("Schema mapping conflict detected: {}", cause.getMessage(), cause);
            } else {
                logger.error("Unexpected error while creating schema mapping: {}", cause.getMessage(), cause);
            }
            return;
        }

        try {
            CreateSchemaMappingResponse response = actions.createSchemaMappingAsync(csvSchemaMappingName).join();
            csvSchemaMappingName = response.schemaName();
            logger.info("The CSV schema mapping name is " + csvSchemaMappingName);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause == null) {
                logger.error("Failed to create CSV schema mapping: {}", ce.getMessage(), ce);
            }

            if (cause instanceof ConflictException) {
                logger.error("Schema mapping conflict detected: {}", cause.getMessage(), cause);
            } else {
                logger.error("Unexpected error while creating CSV schema mapping: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. Create an AWS Entity Resolution Workflow. ");
        logger.info("""
            An Entity Resolution matching workflow identifies and links records 
            across datasets that represent the same real-world entity, such as 
            customers or products. Using techniques like schema mapping, 
            data profiling, and machine learning algorithms, 
            it evaluates attributes like names or emails to detect duplicates
            or relationships, even with variations or inconsistencies. 
            The workflow outputs consolidated, de-duplicated data.
                        
            We will use the machine learning-based matching technique.
            """);
        waitForInputToContinue(scanner);
        try {
            String workflowArn = actions.createMatchingWorkflowAsync(
                roleARN, workflowName, glueBucketName, jsonGlueTableArn,
                jsonSchemaMappingName, csvGlueTableArn, csvSchemaMappingName).join();

            logger.info("The workflow ARN is: " + workflowArn);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();

            if (cause == null) {
                logger.error("An unexpected error occurred: {}", ce.getMessage(), ce);
            }

            if (cause instanceof ValidationException) {
                logger.error("Validation error: {}", cause.getMessage(), cause);
            } else if (cause instanceof ConflictException) {
                logger.error("Workflow conflict detected: {}", cause.getMessage(), cause);
            } else {
                logger.error("Unexpected error: {}", cause.getMessage(), cause);
            }
            return;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);
        logger.info("3. Start the matching job of the " + workflowName + " workflow.");
        waitForInputToContinue(scanner);
        String jobId = null;
        try {
            jobId = actions.startMatchingJobAsync(workflowName).join();
            logger.info("The matching job was successfully started.");
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ConflictException) {
                logger.error("Job conflict detected: {}", cause.getMessage(), cause);
            } else {
                logger.error("Unexpected error while starting the job: {}", ce.getMessage(), ce);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. While the matching job is running, let's look at other API methods. First, let's get details for job " + jobId);
        waitForInputToContinue(scanner);
        try {
            actions.getMatchingJobAsync(jobId, workflowName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("The matching job not found: {}", cause.getMessage(), cause);
            } else {
                logger.error("Failed to start matching job: " + (cause != null ? cause.getMessage() : ce.getMessage()));
            }
            return;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5. Get the schema mapping for the JSON data.");
        waitForInputToContinue(scanner);
        try {
            GetSchemaMappingResponse response = actions.getSchemaMappingAsync(jsonSchemaMappingName).join();
            jsonSchemaMappingArn = response.schemaArn();
            logger.info("Schema mapping ARN is " + jsonSchemaMappingArn);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("Schema mapping not found: {}", cause.getMessage(), cause);
            } else {
                logger.error("Error retrieving the specific schema mapping: " + ce.getCause().getMessage());
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("6. List Schema Mappings.");
        try {
            actions.ListSchemaMappings();
        } catch (CompletionException ce) {
            logger.error("Error retrieving schema mappings: " + ce.getCause().getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Tag the {} resource.", jsonSchemaMappingName);
        logger.info("""
            Tags can help you organize and categorize your Entity Resolution resources. 
            You can also use them to scope user permissions by granting a user permission 
            to access or change only resources with certain tag values. 
            In Entity Resolution, SchemaMapping and MatchingWorkflow can be tagged. For this example, 
            the SchemaMapping is tagged.
                """);
        try {
            actions.tagEntityResource(jsonSchemaMappingArn).join();
        } catch (CompletionException ce) {
            logger.error("Error tagging the resource: " + ce.getCause().getMessage());
            return;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("8. View the results of the AWS Entity Resolution Workflow.");
        logger.info("""
            You cannot view the result of the workflow that is in a running state.  
            In order to view the results, you need to wait for the workflow that we started in step 3 to complete.
                        
            If you choose not to wait, you cannot view the results. You can perform  
            this task manually in the AWS Management Console.
                       
            This can take up to 30 mins (y/n).
            """);
        String viewAns = scanner.nextLine().trim();
        boolean isComplete = false;
        if (viewAns.equalsIgnoreCase("y")) {
            logger.info("You selected to view the Entity Resolution Workflow results.");
            countdownWithWorkflowCheck(actions, 1800, jobId, workflowName);
            isComplete = true;
            try {
                JobMetrics metrics = actions.getJobInfo(workflowName, jobId).join();
                logger.info("Number of input records: {}", metrics.inputRecords());
                logger.info("Number of match ids: {}", metrics.matchIDs());
                logger.info("Number of records not processed: {}", metrics.recordsNotProcessed());
                logger.info("Number of total records processed: {}", metrics.totalRecordsProcessed());
                logger.info("The following represents the output data generated by the Entity Resolution workflow based on the JSON and CSV input data. The output data is stored in the {} bucket.", glueBucketName);
                actions.printData(glueBucketName);

                logger.info("""
                                                                          
                    Note that each of the last 2 records are considered a match even though the 'name' differs between the records;
                    For example 'John Doe Jr.' compared to 'John Doe'.
                    The confidence level is a value between 0 and 1, where 1 indicates a perfect match. 
                                       
                    """);

            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof ResourceNotFoundException) {
                    logger.error("The job not found: {}", cause.getMessage(), cause);
                } else {
                    logger.error("Error retrieving job information: " + ce.getCause().getMessage());
                }
                return;
            }
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("9. Do you want to delete the resources, including the workflow? (y/n)");
        logger.info("""
            You cannot delete the workflow that is in a running state.  
            In order to delete the workflow, you need to wait for the workflow to complete.
                        
            You can delete the workflow manually in the AWS Management Console at a later time.
                       
            If you already waited for the workflow to complete in the previous step, 
            the workflow is completed and you can delete it. 
                        
            If the workflow is not completed, this can take up to 30 mins (y/n).
            """);
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            try {
                if (!isComplete) {
                    countdownWithWorkflowCheck(actions, 1800, jobId, workflowName);
                }
                actions.deleteMatchingWorkflowAsync(workflowName).join();
                logger.info("Workflow deleted successfully!");
            } catch (CompletionException ce) {
                logger.info("Error deleting the workflow: {} ", ce.getMessage());
                return;
            }

            try {
                // Delete both schema mappings.
                actions.deleteSchemaMappingAsync(jsonSchemaMappingName).join();
                actions.deleteSchemaMappingAsync(csvSchemaMappingName).join();
                logger.info("Both schema mappings were deleted successfully!");
            } catch (CompletionException ce) {
                logger.error("Error deleting schema mapping: {}", ce.getMessage());
                return;
            }

            waitForInputToContinue(scanner);
            logger.info(DASHES);
            logger.info("""
                Now we delete the CloudFormation stack, which deletes 
                the resources that were created at the beginning of this scenario.
                """);
            waitForInputToContinue(scanner);
            logger.info(DASHES);
            try {
                deleteCloudFormationStack();
            } catch (RuntimeException e) {
                logger.error("Failed to delete the stack: {}", e.getMessage());
                return;
            }

        } else {
            logger.info("You can delete the AWS resources in the AWS Management Console.");
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("This concludes the AWS Entity Resolution scenario.");
        logger.info(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
    }

    public static void countdownWithWorkflowCheck(EntityResActions actions, int totalSeconds, String jobId, String workflowName) throws InterruptedException {
        int secondsElapsed = 0;

        while (true) {
            // Calculate display minutes and seconds.
            int remainingTime = totalSeconds - secondsElapsed;
            int displayMinutes = remainingTime / 60;
            int displaySeconds = remainingTime % 60;

            // Print the countdown.
            System.out.printf("\r%02d:%02d", displayMinutes, displaySeconds);
            Thread.sleep(1000); // Wait for 1 second
            secondsElapsed++;

            // Check workflow status every 60 seconds.
            if (secondsElapsed % 60 == 0 || remainingTime <= 0) {
                GetMatchingJobResponse response = actions.checkWorkflowStatusCompleteAsync(jobId, workflowName).join();
                if (response != null && "SUCCEEDED".equalsIgnoreCase(String.valueOf(response.status()))) {
                    logger.info(""); // Move to the next line after countdown.
                    logger.info("Countdown complete: Workflow is in Completed state!");
                    break; // Break out of the loop if the status is "SUCCEEDED"
                }
            }

            // If countdown reaches zero, reset it for continuous countdown.
            if (remainingTime <= 0) {
                secondsElapsed = 0;
            }
        }
    }

    private static void deleteCloudFormationStack() {
        try {
            CloudFormationHelper.emptyS3Bucket(glueBucketName);
            CloudFormationHelper.destroyCloudFormationStack(STACK_NAME);
            logger.info("Resources deleted successfully!");
        } catch (CloudFormationException e) {
            throw new RuntimeException("Failed to delete CloudFormation stack: " + e.getMessage(), e);
        } catch (S3Exception e) {
            throw new RuntimeException("Failed to empty S3 bucket: " + e.getMessage(), e);
        }
    }
}
```
 AWS Entity Resolution SDK メソッドのラッパークラス。  

```
public class EntityResActions {

    private static final String PREFIX = "eroutput/";
    private static final Logger logger = LoggerFactory.getLogger(EntityResActions.class);

    private static EntityResolutionAsyncClient entityResolutionAsyncClient;

    private static S3AsyncClient s3AsyncClient;

    public static EntityResolutionAsyncClient getResolutionAsyncClient() {
        if (entityResolutionAsyncClient == null) {
            /*
            The `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java, version 2,
            and it is designed to provide a high-performance, asynchronous HTTP client for interacting with AWS services.
             It uses the Netty framework to handle the underlying network communication and the Java NIO API to
             provide a non-blocking, event-driven approach to HTTP requests and responses.
             */

            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(50)  // Adjust as needed.
                .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
                .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
                .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
                .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
                .retryStrategy(RetryMode.STANDARD)
                .build();

            entityResolutionAsyncClient = EntityResolutionAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return entityResolutionAsyncClient;
    }

    public static S3AsyncClient getS3AsyncClient() {
        if (s3AsyncClient == null) {
            /*
            The `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java, version 2,
            and it is designed to provide a high-performance, asynchronous HTTP client for interacting with AWS services.
             It uses the Netty framework to handle the underlying network communication and the Java NIO API to
             provide a non-blocking, event-driven approach to HTTP requests and responses.
             */

            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(50)  // Adjust as needed.
                .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
                .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
                .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
                .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
                .retryStrategy(RetryMode.STANDARD)
                .build();

            s3AsyncClient = S3AsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return s3AsyncClient;
    }

    /**
     * Deletes the schema mapping asynchronously.
     *
     * @param schemaName the name of the schema to delete
     * @return a {@link CompletableFuture} that completes when the schema mapping is deleted successfully,
     * or throws a {@link RuntimeException} if the deletion fails
     */
    public CompletableFuture<DeleteSchemaMappingResponse> deleteSchemaMappingAsync(String schemaName) {
        DeleteSchemaMappingRequest request = DeleteSchemaMappingRequest.builder()
            .schemaName(schemaName)
            .build();

        return getResolutionAsyncClient().deleteSchemaMapping(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    // Successfully deleted the schema mapping, log the success message.
                    logger.info("Schema mapping '{}' deleted successfully.", schemaName);
                } else {
                    // Ensure exception is not null before accessing its cause.
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while deleting the schema mapping.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The schema mapping was not found to delete: " + schemaName, cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to delete schema mapping: " + schemaName, exception);
                }
            });
    }

    /**
     * Lists the schema mappings associated with the current AWS account. This method uses an asynchronous paginator to
     * retrieve the schema mappings, and prints the name of each schema mapping to the console.
     */
    public void ListSchemaMappings() {
        ListSchemaMappingsRequest mappingsRequest = ListSchemaMappingsRequest.builder()
            .build();

        ListSchemaMappingsPublisher paginator = getResolutionAsyncClient().listSchemaMappingsPaginator(mappingsRequest);

        // Iterate through the pages of results
        CompletableFuture<Void> future = paginator.subscribe(response -> {
            response.schemaList().forEach(schemaMapping ->
                logger.info("Schema Mapping Name: " + schemaMapping.schemaName())
            );
        });

        // Wait for the asynchronous operation to complete
        future.join();
    }

    /**
     * Asynchronously deletes a workflow with the specified name.
     *
     * @param workflowName the name of the workflow to be deleted
     * @return a {@link CompletableFuture} that completes when the workflow has been deleted
     * @throws RuntimeException if the deletion of the workflow fails
     */
    public CompletableFuture<DeleteMatchingWorkflowResponse> deleteMatchingWorkflowAsync(String workflowName) {
        DeleteMatchingWorkflowRequest request = DeleteMatchingWorkflowRequest.builder()
            .workflowName(workflowName)
            .build();

        return getResolutionAsyncClient().deleteMatchingWorkflow(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("{} was deleted", workflowName );
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while deleting the workflow.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The workflow to delete was not found.", cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to delete workflow: " + exception.getMessage(), exception);
                }
            });
    }

    /**
     * Creates a schema mapping asynchronously.
     *
     * @param schemaName the name of the schema to create
     * @return a {@link CompletableFuture} that represents the asynchronous creation of the schema mapping
     */
    public CompletableFuture<CreateSchemaMappingResponse> createSchemaMappingAsync(String schemaName) {
        List<SchemaInputAttribute> schemaAttributes = null;
        if (schemaName.startsWith("json")) {
            schemaAttributes = List.of(
                SchemaInputAttribute.builder().matchKey("id").fieldName("id").type(SchemaAttributeType.UNIQUE_ID).build(),
                SchemaInputAttribute.builder().matchKey("name").fieldName("name").type(SchemaAttributeType.NAME).build(),
                SchemaInputAttribute.builder().matchKey("email").fieldName("email").type(SchemaAttributeType.EMAIL_ADDRESS).build()
            );
        } else {
            schemaAttributes = List.of(
                SchemaInputAttribute.builder().matchKey("id").fieldName("id").type(SchemaAttributeType.UNIQUE_ID).build(),
                SchemaInputAttribute.builder().matchKey("name").fieldName("name").type(SchemaAttributeType.NAME).build(),
                SchemaInputAttribute.builder().matchKey("email").fieldName("email").type(SchemaAttributeType.EMAIL_ADDRESS).build(),
                SchemaInputAttribute.builder().fieldName("phone").type(SchemaAttributeType.PROVIDER_ID).subType("STRING").build()
            );
        }

        CreateSchemaMappingRequest request = CreateSchemaMappingRequest.builder()
            .schemaName(schemaName)
            .mappedInputFields(schemaAttributes)
            .build();

        return getResolutionAsyncClient().createSchemaMapping(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("[{}] schema mapping Created Successfully!", schemaName);
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while creating the schema mapping.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("A conflicting schema mapping already exists. Resolve conflicts before proceeding.", cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to create schema mapping: " + exception.getMessage(), exception);
                }
            });
    }

    /**
     * Retrieves the schema mapping asynchronously.
     *
     * @param schemaName the name of the schema to retrieve the mapping for
     * @return a {@link CompletableFuture} that completes with the {@link GetSchemaMappingResponse} when the operation
     * is complete
     * @throws RuntimeException if the schema mapping retrieval fails
     */
    public CompletableFuture<GetSchemaMappingResponse> getSchemaMappingAsync(String schemaName) {
        GetSchemaMappingRequest mappingRequest = GetSchemaMappingRequest.builder()
            .schemaName(schemaName)
            .build();

        return getResolutionAsyncClient().getSchemaMapping(mappingRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    response.mappedInputFields().forEach(attribute ->
                        logger.info("Attribute Name: " + attribute.fieldName() +
                            ", Attribute Type: " + attribute.type().toString()));
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while getting schema mapping.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The requested schema mapping was not found.", cause);
                    }

                    // Wrap other exceptions in a CompletionException with the message.
                    throw new CompletionException("Failed to get schema mapping: " + exception.getMessage(), exception);
                }
            });
    }

    /**
     * Asynchronously retrieves a matching job based on the provided job ID and workflow name.
     *
     * @param jobId        the ID of the job to retrieve
     * @param workflowName the name of the workflow associated with the job
     * @return a {@link CompletableFuture} that completes when the job information is available or an exception occurs
     */
    public CompletableFuture<GetMatchingJobResponse> getMatchingJobAsync(String jobId, String workflowName) {
        GetMatchingJobRequest request = GetMatchingJobRequest.builder()
            .jobId(jobId)
            .workflowName(workflowName)
            .build();

        return getResolutionAsyncClient().getMatchingJob(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    // Successfully fetched the matching job details, log the job status.
                    logger.info("Job status: " + response.status());
                    logger.info("Job details: " + response.toString());
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while fetching the matching job.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The requested job could not be found.", cause);
                    }

                    // Wrap other exceptions in a CompletionException with the message.
                    throw new CompletionException("Error fetching matching job: " + exception.getMessage(), exception);
                }
            });
    }


    /**
     * Starts a matching job asynchronously for the specified workflow name.
     *
     * @param workflowName the name of the workflow for which to start the matching job
     * @return a {@link CompletableFuture} that completes with the job ID of the started matching job, or an empty
     * string if the operation fails
     */
    public CompletableFuture<String> startMatchingJobAsync(String workflowName) {
        StartMatchingJobRequest jobRequest = StartMatchingJobRequest.builder()
            .workflowName(workflowName)
            .build();

        return getResolutionAsyncClient().startMatchingJob(jobRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    String jobId = response.jobId();
                    logger.info("Job ID: " + jobId);
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while starting the job.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("The job is already running. Resolve conflicts before starting a new job.", cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to start the job: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response != null ? response.jobId() : "");
    }

    /**
     * Checks the status of a workflow asynchronously.
     *
     * @param jobId        the ID of the job to check
     * @param workflowName the name of the workflow to check
     * @return a CompletableFuture that resolves to a boolean value indicating whether the workflow has completed
     * successfully
     */
    public CompletableFuture<GetMatchingJobResponse> checkWorkflowStatusCompleteAsync(String jobId, String workflowName) {
        GetMatchingJobRequest request = GetMatchingJobRequest.builder()
            .jobId(jobId)
            .workflowName(workflowName)
            .build();

        return getResolutionAsyncClient().getMatchingJob(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    // Process the response and log the job status.
                    logger.info("Job status: " + response.status());
                } else {
                    // Ensure exception is not null before accessing its cause.
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while checking job status.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The requested resource was not found while checking the job status.", cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to check job status: " + exception.getMessage(), exception);
                }
            });
    }

    /**
     * Creates an asynchronous CompletableFuture to manage the creation of a matching workflow.
     *
     * @param roleARN                 the AWS IAM role ARN to be used for the workflow execution
     * @param workflowName            the name of the workflow to be created
     * @param outputBucket            the S3 bucket path where the workflow output will be stored
     * @param jsonGlueTableArn        the ARN of the Glue Data Catalog table to be used as the input source
     * @param jsonErSchemaMappingName the name of the schema to be used for the input source
     * @return a CompletableFuture that, when completed, will return the ARN of the created workflow
     */
    public CompletableFuture<String> createMatchingWorkflowAsync(
        String roleARN
        , String workflowName
        , String outputBucket
        , String jsonGlueTableArn
        , String jsonErSchemaMappingName
        , String csvGlueTableArn
        , String csvErSchemaMappingName) {

        InputSource jsonInputSource = InputSource.builder()
            .inputSourceARN(jsonGlueTableArn)
            .schemaName(jsonErSchemaMappingName)
            .applyNormalization(false)
            .build();

        InputSource csvInputSource = InputSource.builder()
            .inputSourceARN(csvGlueTableArn)
            .schemaName(csvErSchemaMappingName)
            .applyNormalization(false)
            .build();

        OutputAttribute idOutputAttribute = OutputAttribute.builder()
            .name("id")
            .build();

        OutputAttribute nameOutputAttribute = OutputAttribute.builder()
            .name("name")
            .build();

        OutputAttribute emailOutputAttribute = OutputAttribute.builder()
            .name("email")
            .build();

        OutputAttribute phoneOutputAttribute = OutputAttribute.builder()
            .name("phone")
            .build();

        OutputSource outputSource = OutputSource.builder()
            .outputS3Path("s3://" + outputBucket + "/eroutput")
            .output(idOutputAttribute, nameOutputAttribute, emailOutputAttribute, phoneOutputAttribute)
            .applyNormalization(false)
            .build();

        ResolutionTechniques resolutionType = ResolutionTechniques.builder()
            .resolutionType(ResolutionType.ML_MATCHING)
            .build();

        CreateMatchingWorkflowRequest workflowRequest = CreateMatchingWorkflowRequest.builder()
            .roleArn(roleARN)
            .description("Created by using the AWS SDK for Java")
            .workflowName(workflowName)
            .inputSourceConfig(List.of(jsonInputSource, csvInputSource))
            .outputSourceConfig(List.of(outputSource))
            .resolutionTechniques(resolutionType)
            .build();

        return getResolutionAsyncClient().createMatchingWorkflow(workflowRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("Workflow created successfully.");
                } else {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ValidationException) {
                        throw new CompletionException("Invalid request: Please check input parameters.", cause);
                    }

                    if (cause instanceof ConflictException) {
                        throw new CompletionException("A conflicting workflow already exists. Resolve conflicts before proceeding.", cause);
                    }
                    throw new CompletionException("Failed to create workflow: " + exception.getMessage(), exception);
                }
            })
            .thenApply(CreateMatchingWorkflowResponse::workflowArn);
    }

    /**
     * Tags the specified schema mapping ARN.
     *
     * @param schemaMappingARN the ARN of the schema mapping to tag
     */
    public CompletableFuture<TagResourceResponse> tagEntityResource(String schemaMappingARN) {
        Map<String, String> tags = new HashMap<>();
        tags.put("tag1", "tag1Value");
        tags.put("tag2", "tag2Value");

        TagResourceRequest request = TagResourceRequest.builder()
            .resourceArn(schemaMappingARN)
            .tags(tags)
            .build();

        return getResolutionAsyncClient().tagResource(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    // Successfully tagged the resource, log the success message.
                    logger.info("Successfully tagged the resource.");
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while tagging the resource.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The resource to tag was not found.", cause);
                    }
                    throw new CompletionException("Failed to tag the resource: " + exception.getMessage(), exception);
                }
            });
    }

    public CompletableFuture<JobMetrics> getJobInfo(String workflowName, String jobId) {
        return getResolutionAsyncClient().getMatchingJob(b -> b
                .workflowName(workflowName)
                .jobId(jobId))
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("Job metrics fetched successfully for jobId: " + jobId);
                } else {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("Invalid request: Job id was not found.", cause);
                    }
                    throw new CompletionException("Failed to fetch job info: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response.metrics()); // Extract job metrics
    }

    /**
     * Uploads data to an Amazon S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to upload the data to
     * @param jsonData   the JSON data to be uploaded
     * @param csvData    the CSV data to be uploaded
     * @return a {@link CompletableFuture} representing both asynchronous operation of uploading the data
     * @throws RuntimeException if an error occurs during the file upload
     */

    public void uploadInputData(String bucketName, String jsonData, String csvData) {
        // Upload JSON data.
        String jsonKey = "jsonData/data.json";
        PutObjectRequest jsonUploadRequest = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(jsonKey)
            .contentType("application/json")
            .build();

        CompletableFuture<PutObjectResponse> jsonUploadResponse = getS3AsyncClient().putObject(jsonUploadRequest, AsyncRequestBody.fromString(jsonData));

        // Upload CSV data.
        String csvKey = "csvData/data.csv";
        PutObjectRequest csvUploadRequest = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(csvKey)
            .contentType("text/csv")
            .build();
        CompletableFuture<PutObjectResponse> csvUploadResponse = getS3AsyncClient().putObject(csvUploadRequest, AsyncRequestBody.fromString(csvData));

        CompletableFuture.allOf(jsonUploadResponse, csvUploadResponse)
            .whenComplete((result, ex) -> {
                if (ex != null) {
                    // Wrap an AWS exception.
                    throw new CompletionException("Failed to upload files", ex);
                }
            }).join();

    }

    /**
     * Finds the latest file in the S3 bucket that starts with "run-" in any depth of subfolders
     */
    private CompletableFuture<String> findLatestMatchingFile(String bucketName) {
        ListObjectsV2Request request = ListObjectsV2Request.builder()
            .bucket(bucketName)
            .prefix(PREFIX) // Searches within the given folder
            .build();

        return getS3AsyncClient().listObjectsV2(request)
            .thenApply(response -> response.contents().stream()
                .map(S3Object::key)
                .filter(key -> key.matches(".*?/run-[0-9a-zA-Z\\-]+")) // Matches files like run-XXXXX in any subfolder
                .max(String::compareTo) // Gets the latest file
                .orElse(null))
            .whenComplete((result, exception) -> {
                if (exception == null) {
                    if (result != null) {
                        logger.info("Latest matching file found: " + result);
                    } else {
                        logger.info("No matching files found.");
                    }
                } else {
                    throw new CompletionException("Failed to find latest matching file: " + exception.getMessage(), exception);
                }
            });
    }

    /**
     * Prints the data located in the file in the S3 bucket that starts with "run-" in any depth of subfolders
     */
    public void printData(String bucketName) {
        try {
            // Find the latest file with "run-" prefix in any depth of subfolders.
            String s3Key = findLatestMatchingFile(bucketName).join();
            if (s3Key == null) {
                logger.error("No matching files found in S3.");
                return;
            }

            logger.info("Downloading file: " + s3Key);

            // Read CSV file as String.
            String csvContent = readCSVFromS3Async(bucketName, s3Key).join();
            if (csvContent.isEmpty()) {
                logger.error("File is empty.");
                return;
            }

            // Process CSV content.
            List<String[]> records = parseCSV(csvContent);
            printTable(records);

        } catch (RuntimeException | IOException | CsvException e) {
            logger.error("Error processing CSV file from S3: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Reads a CSV file from S3 and returns it as a String.
     */
    private static CompletableFuture<String> readCSVFromS3Async(String bucketName, String s3Key) {
        GetObjectRequest getObjectRequest = GetObjectRequest.builder()
            .bucket(bucketName)
            .key(s3Key)
            .build();

        // Initiating the asynchronous request to get the file as bytes
        return getS3AsyncClient().getObject(getObjectRequest, AsyncResponseTransformer.toBytes())
            .thenApply(responseBytes -> responseBytes.asUtf8String()) // Convert bytes to UTF-8 string
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    throw new CompletionException("Failed to read CSV from S3: " + exception.getMessage(), exception);
                } else {
                    logger.info("Successfully fetched CSV file content from S3.");
                }
            });
    }

    /**
     * Parses CSV content from a String into a list of records.
     */
    private static List<String[]> parseCSV(String csvContent) throws IOException, CsvException {
        try (CSVReader csvReader = new CSVReader(new StringReader(csvContent))) {
            return csvReader.readAll();
        }
    }

    /**
     * Prints the given CSV data in a formatted table
     */
    private static void printTable(List<String[]> records) {
        if (records.isEmpty()) {
            System.out.println("No records found.");
            return;
        }

        String[] headers = records.get(0);
        List<String[]> rows = records.subList(1, records.size());

        // Determine column widths dynamically based on longest content
        int[] columnWidths = new int[headers.length];
        for (int i = 0; i < headers.length; i++) {
            final int columnIndex = i;
            int maxWidth = Math.max(headers[i].length(), rows.stream()
                .map(row -> row.length > columnIndex ? row[columnIndex].length() : 0)
                .max(Integer::compareTo)
                .orElse(0));
            columnWidths[i] = Math.min(maxWidth, 25); // Limit max width for better readability
        }

        // Enable ANSI Console for colored output
        AnsiConsole.systemInstall();

        // Print table header
        System.out.println(ansi().fgYellow().a("=== CSV Data from S3 ===").reset());
        printRow(headers, columnWidths, true);

        // Print rows
        rows.forEach(row -> printRow(row, columnWidths, false));

        // Restore console to normal
        AnsiConsole.systemUninstall();
    }

    private static void printRow(String[] row, int[] columnWidths, boolean isHeader) {
        String border = IntStream.range(0, columnWidths.length)
            .mapToObj(i -> "-".repeat(columnWidths[i] + 2))
            .collect(Collectors.joining("+", "+", "+"));

        if (isHeader) {
            System.out.println(border);
        }

        System.out.print("|");
        for (int i = 0; i < columnWidths.length; i++) {
            String cell = (i < row.length && row[i] != null) ? row[i] : "";
            System.out.printf(" %-" + columnWidths[i] + "s |", isHeader ? ansi().fgBrightBlue().a(cell).reset() : cell);
        }
        System.out.println();

        if (isHeader) {
            System.out.println(border);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateMatchingWorkflow](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/CreateMatchingWorkflow)
  + [CreateSchemaMapping](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/CreateSchemaMapping)
  + [DeleteMatchingWorkflow](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/DeleteMatchingWorkflow)
  + [DeleteSchemaMapping](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/DeleteSchemaMapping)
  + [GetMatchingJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/GetMatchingJob)
  + [GetSchemaMapping](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/GetSchemaMapping)
  + [ListMatchingWorkflows](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/ListMatchingWorkflows)
  + [ListSchemaMappings](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/ListSchemaMappings)
  + [StartMatchingJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/StartMatchingJob)
  + [TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/TagResource)

## アクション
<a name="actions"></a>

### `CreateMatchingWorkflow`
<a name="entityresolution_CreateMatchingWorkflow_java_2_topic"></a>

次のコード例は、`CreateMatchingWorkflow` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an asynchronous CompletableFuture to manage the creation of a matching workflow.
     *
     * @param roleARN                 the AWS IAM role ARN to be used for the workflow execution
     * @param workflowName            the name of the workflow to be created
     * @param outputBucket            the S3 bucket path where the workflow output will be stored
     * @param jsonGlueTableArn        the ARN of the Glue Data Catalog table to be used as the input source
     * @param jsonErSchemaMappingName the name of the schema to be used for the input source
     * @return a CompletableFuture that, when completed, will return the ARN of the created workflow
     */
    public CompletableFuture<String> createMatchingWorkflowAsync(
        String roleARN
        , String workflowName
        , String outputBucket
        , String jsonGlueTableArn
        , String jsonErSchemaMappingName
        , String csvGlueTableArn
        , String csvErSchemaMappingName) {

        InputSource jsonInputSource = InputSource.builder()
            .inputSourceARN(jsonGlueTableArn)
            .schemaName(jsonErSchemaMappingName)
            .applyNormalization(false)
            .build();

        InputSource csvInputSource = InputSource.builder()
            .inputSourceARN(csvGlueTableArn)
            .schemaName(csvErSchemaMappingName)
            .applyNormalization(false)
            .build();

        OutputAttribute idOutputAttribute = OutputAttribute.builder()
            .name("id")
            .build();

        OutputAttribute nameOutputAttribute = OutputAttribute.builder()
            .name("name")
            .build();

        OutputAttribute emailOutputAttribute = OutputAttribute.builder()
            .name("email")
            .build();

        OutputAttribute phoneOutputAttribute = OutputAttribute.builder()
            .name("phone")
            .build();

        OutputSource outputSource = OutputSource.builder()
            .outputS3Path("s3://" + outputBucket + "/eroutput")
            .output(idOutputAttribute, nameOutputAttribute, emailOutputAttribute, phoneOutputAttribute)
            .applyNormalization(false)
            .build();

        ResolutionTechniques resolutionType = ResolutionTechniques.builder()
            .resolutionType(ResolutionType.ML_MATCHING)
            .build();

        CreateMatchingWorkflowRequest workflowRequest = CreateMatchingWorkflowRequest.builder()
            .roleArn(roleARN)
            .description("Created by using the AWS SDK for Java")
            .workflowName(workflowName)
            .inputSourceConfig(List.of(jsonInputSource, csvInputSource))
            .outputSourceConfig(List.of(outputSource))
            .resolutionTechniques(resolutionType)
            .build();

        return getResolutionAsyncClient().createMatchingWorkflow(workflowRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("Workflow created successfully.");
                } else {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ValidationException) {
                        throw new CompletionException("Invalid request: Please check input parameters.", cause);
                    }

                    if (cause instanceof ConflictException) {
                        throw new CompletionException("A conflicting workflow already exists. Resolve conflicts before proceeding.", cause);
                    }
                    throw new CompletionException("Failed to create workflow: " + exception.getMessage(), exception);
                }
            })
            .thenApply(CreateMatchingWorkflowResponse::workflowArn);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateMatchingWorkflow](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/CreateMatchingWorkflow)」を参照してください。

### `CreateSchemaMapping`
<a name="entityresolution_CreateSchemaMapping_java_2_topic"></a>

次のコード例は、`CreateSchemaMapping` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a schema mapping asynchronously.
     *
     * @param schemaName the name of the schema to create
     * @return a {@link CompletableFuture} that represents the asynchronous creation of the schema mapping
     */
    public CompletableFuture<CreateSchemaMappingResponse> createSchemaMappingAsync(String schemaName) {
        List<SchemaInputAttribute> schemaAttributes = null;
        if (schemaName.startsWith("json")) {
            schemaAttributes = List.of(
                SchemaInputAttribute.builder().matchKey("id").fieldName("id").type(SchemaAttributeType.UNIQUE_ID).build(),
                SchemaInputAttribute.builder().matchKey("name").fieldName("name").type(SchemaAttributeType.NAME).build(),
                SchemaInputAttribute.builder().matchKey("email").fieldName("email").type(SchemaAttributeType.EMAIL_ADDRESS).build()
            );
        } else {
            schemaAttributes = List.of(
                SchemaInputAttribute.builder().matchKey("id").fieldName("id").type(SchemaAttributeType.UNIQUE_ID).build(),
                SchemaInputAttribute.builder().matchKey("name").fieldName("name").type(SchemaAttributeType.NAME).build(),
                SchemaInputAttribute.builder().matchKey("email").fieldName("email").type(SchemaAttributeType.EMAIL_ADDRESS).build(),
                SchemaInputAttribute.builder().fieldName("phone").type(SchemaAttributeType.PROVIDER_ID).subType("STRING").build()
            );
        }

        CreateSchemaMappingRequest request = CreateSchemaMappingRequest.builder()
            .schemaName(schemaName)
            .mappedInputFields(schemaAttributes)
            .build();

        return getResolutionAsyncClient().createSchemaMapping(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("[{}] schema mapping Created Successfully!", schemaName);
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while creating the schema mapping.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("A conflicting schema mapping already exists. Resolve conflicts before proceeding.", cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to create schema mapping: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateSchemaMapping](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/CreateSchemaMapping)」を参照してください。

### `DeleteMatchingWorkflow`
<a name="entityresolution_DeleteMatchingWorkflow_java_2_topic"></a>

次のコード例は、`DeleteMatchingWorkflow` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously deletes a workflow with the specified name.
     *
     * @param workflowName the name of the workflow to be deleted
     * @return a {@link CompletableFuture} that completes when the workflow has been deleted
     * @throws RuntimeException if the deletion of the workflow fails
     */
    public CompletableFuture<DeleteMatchingWorkflowResponse> deleteMatchingWorkflowAsync(String workflowName) {
        DeleteMatchingWorkflowRequest request = DeleteMatchingWorkflowRequest.builder()
            .workflowName(workflowName)
            .build();

        return getResolutionAsyncClient().deleteMatchingWorkflow(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("{} was deleted", workflowName );
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while deleting the workflow.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The workflow to delete was not found.", cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to delete workflow: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteMatchingWorkflow](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/DeleteMatchingWorkflow)」を参照してください。

### `DeleteSchemaMapping`
<a name="entityresolution_DeleteSchemaMapping_java_2_topic"></a>

次のコード例は、`DeleteSchemaMapping` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes the schema mapping asynchronously.
     *
     * @param schemaName the name of the schema to delete
     * @return a {@link CompletableFuture} that completes when the schema mapping is deleted successfully,
     * or throws a {@link RuntimeException} if the deletion fails
     */
    public CompletableFuture<DeleteSchemaMappingResponse> deleteSchemaMappingAsync(String schemaName) {
        DeleteSchemaMappingRequest request = DeleteSchemaMappingRequest.builder()
            .schemaName(schemaName)
            .build();

        return getResolutionAsyncClient().deleteSchemaMapping(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    // Successfully deleted the schema mapping, log the success message.
                    logger.info("Schema mapping '{}' deleted successfully.", schemaName);
                } else {
                    // Ensure exception is not null before accessing its cause.
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while deleting the schema mapping.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The schema mapping was not found to delete: " + schemaName, cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to delete schema mapping: " + schemaName, exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteSchemaMapping](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/DeleteSchemaMapping)」を参照してください。

### `GetMatchingJob`
<a name="entityresolution_GetMatchingJob_java_2_topic"></a>

次のコード例は、`GetMatchingJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously retrieves a matching job based on the provided job ID and workflow name.
     *
     * @param jobId        the ID of the job to retrieve
     * @param workflowName the name of the workflow associated with the job
     * @return a {@link CompletableFuture} that completes when the job information is available or an exception occurs
     */
    public CompletableFuture<GetMatchingJobResponse> getMatchingJobAsync(String jobId, String workflowName) {
        GetMatchingJobRequest request = GetMatchingJobRequest.builder()
            .jobId(jobId)
            .workflowName(workflowName)
            .build();

        return getResolutionAsyncClient().getMatchingJob(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    // Successfully fetched the matching job details, log the job status.
                    logger.info("Job status: " + response.status());
                    logger.info("Job details: " + response.toString());
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while fetching the matching job.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The requested job could not be found.", cause);
                    }

                    // Wrap other exceptions in a CompletionException with the message.
                    throw new CompletionException("Error fetching matching job: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetMatchingJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/GetMatchingJob)」を参照してください。

### `GetSchemaMapping`
<a name="entityresolution_GetSchemaMapping_java_2_topic"></a>

次のコード例は、`GetSchemaMapping` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the schema mapping asynchronously.
     *
     * @param schemaName the name of the schema to retrieve the mapping for
     * @return a {@link CompletableFuture} that completes with the {@link GetSchemaMappingResponse} when the operation
     * is complete
     * @throws RuntimeException if the schema mapping retrieval fails
     */
    public CompletableFuture<GetSchemaMappingResponse> getSchemaMappingAsync(String schemaName) {
        GetSchemaMappingRequest mappingRequest = GetSchemaMappingRequest.builder()
            .schemaName(schemaName)
            .build();

        return getResolutionAsyncClient().getSchemaMapping(mappingRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    response.mappedInputFields().forEach(attribute ->
                        logger.info("Attribute Name: " + attribute.fieldName() +
                            ", Attribute Type: " + attribute.type().toString()));
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while getting schema mapping.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The requested schema mapping was not found.", cause);
                    }

                    // Wrap other exceptions in a CompletionException with the message.
                    throw new CompletionException("Failed to get schema mapping: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/GetSchemaMapping)」の「*GetSchemaMapping*」を参照してください。

### `ListSchemaMappings`
<a name="entityresolution_ListSchemaMappings_java_2_topic"></a>

次のコード例は、`ListSchemaMappings` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists the schema mappings associated with the current AWS account. This method uses an asynchronous paginator to
     * retrieve the schema mappings, and prints the name of each schema mapping to the console.
     */
    public void ListSchemaMappings() {
        ListSchemaMappingsRequest mappingsRequest = ListSchemaMappingsRequest.builder()
            .build();

        ListSchemaMappingsPublisher paginator = getResolutionAsyncClient().listSchemaMappingsPaginator(mappingsRequest);

        // Iterate through the pages of results
        CompletableFuture<Void> future = paginator.subscribe(response -> {
            response.schemaList().forEach(schemaMapping ->
                logger.info("Schema Mapping Name: " + schemaMapping.schemaName())
            );
        });

        // Wait for the asynchronous operation to complete
        future.join();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListSchemaMappings](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/ListSchemaMappings)」を参照してください。

### `StartMatchingJob`
<a name="entityresolution_StartMatchingJob_java_2_topic"></a>

次のコード例は、`StartMatchingJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Starts a matching job asynchronously for the specified workflow name.
     *
     * @param workflowName the name of the workflow for which to start the matching job
     * @return a {@link CompletableFuture} that completes with the job ID of the started matching job, or an empty
     * string if the operation fails
     */
    public CompletableFuture<String> startMatchingJobAsync(String workflowName) {
        StartMatchingJobRequest jobRequest = StartMatchingJobRequest.builder()
            .workflowName(workflowName)
            .build();

        return getResolutionAsyncClient().startMatchingJob(jobRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    String jobId = response.jobId();
                    logger.info("Job ID: " + jobId);
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while starting the job.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("The job is already running. Resolve conflicts before starting a new job.", cause);
                    }

                    // Wrap other AWS exceptions in a CompletionException.
                    throw new CompletionException("Failed to start the job: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response != null ? response.jobId() : "");
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartMatchingJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/StartMatchingJob)」を参照してください。

### `TagResource`
<a name="entityresolution_TagResource_java_2_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/entityresolution#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Tags the specified schema mapping ARN.
     *
     * @param schemaMappingARN the ARN of the schema mapping to tag
     */
    public CompletableFuture<TagResourceResponse> tagEntityResource(String schemaMappingARN) {
        Map<String, String> tags = new HashMap<>();
        tags.put("tag1", "tag1Value");
        tags.put("tag2", "tag2Value");

        TagResourceRequest request = TagResourceRequest.builder()
            .resourceArn(schemaMappingARN)
            .tags(tags)
            .build();

        return getResolutionAsyncClient().tagResource(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    // Successfully tagged the resource, log the success message.
                    logger.info("Successfully tagged the resource.");
                } else {
                    if (exception == null) {
                        throw new CompletionException("An unknown error occurred while tagging the resource.", null);
                    }

                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The resource to tag was not found.", cause);
                    }
                    throw new CompletionException("Failed to tag the resource: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/entityresolution-2018-05-10/TagResource)」を参照してください。

# SDK for Java 2.x を使用した OpenSearch Service の例
<a name="java_2_opensearch_code_examples"></a>

次のコード例は、OpenSearch Service AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello OpenSearch Service
<a name="opensearch_Hello_java_2_topic"></a>

次のコード例は、OpenSearch Service の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient;
import software.amazon.awssdk.services.opensearch.model.ListVersionsRequest;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 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 HelloOpenSearch {
    public static void main(String[] args) {
        try {
            CompletableFuture<Void> future = listVersionsAsync();
            future.join();
            System.out.println("Versions listed successfully.");
        } catch (RuntimeException e) {
            System.err.println("Error occurred while listing versions: " + e.getMessage());
        }
    }

    private static OpenSearchAsyncClient getAsyncClient() {
        return OpenSearchAsyncClient.builder().build();
    }

    public static CompletableFuture<Void> listVersionsAsync() {
        ListVersionsRequest request = ListVersionsRequest.builder()
            .maxResults(10)
            .build();

        return getAsyncClient().listVersions(request).thenAccept(response -> {
            List<String> versionList = response.versions();
            for (String version : versionList) {
                System.out.println("Version info: " + version);
            }
        }).exceptionally(ex -> {
            // Handle the exception, or propagate it as a RuntimeException
            throw new RuntimeException("Failed to list versions", ex);
        });
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListVersions](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/ListVersions)」を参照してください。

## 基本
<a name="basics"></a>

### OpenSearch Service のコアオペレーションについて
<a name="opensearch_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ OpenSearch Service ドメインを作成します。
+ 特定の OpenSearch Service ドメインに関する詳細情報を提供します。
+ アカウントが所有するすべての OpenSearch Service ドメインを一覧表示します。
+ OpenSearch Service ドメインの変更ステータスが完了状態になるまで待ちます。
+ 既存の OpenSearch Service ドメインの設定を変更します。
+ OpenSearch Service ドメインにタグを追加します。
+ OpenSearch Service ドメインに関連付けられているタグを一覧表示します。
+ OpenSearch Service ドメインからタグを削除します。
+ OpenSearch Service ドメインを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/batch#code-examples)での設定と実行の方法を確認してください。
OpenSearch Service の機能を実証するインタラクティブなシナリオを実行します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.opensearch.model.*;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;

public class OpenSearchScenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    private static final Logger logger = LoggerFactory.getLogger(OpenSearchScenario.class);
    static Scanner scanner = new Scanner(System.in);

    static OpenSearchActions openSearchActions = new OpenSearchActions();

    public static void main(String[] args) throws Throwable {
        logger.info("""
            Welcome to the Amazon OpenSearch Service Basics Scenario.

            Use the Amazon OpenSearch Service API to create, configure, and manage OpenSearch Service domains.

            The operations exposed by the AWS OpenSearch Service client are focused on managing the OpenSearch Service domains 
            and their configurations, not the data within the domains (such as indexing or querying documents). 
            For document management, you typically interact directly with the OpenSearch REST API or use other libraries, 
            such as the OpenSearch Java client (https://opensearch.org/docs/latest/clients/java/).

            Let's get started...
        """);
        waitForInputToContinue(scanner);
        try {
            runScenario();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                logger.info("Invalid input. Please try again.");
            }
        }
    }

    private static void runScenario() throws Throwable {
        String currentTimestamp = String.valueOf(System.currentTimeMillis());
        String domainName = "test-domain-" + currentTimestamp;

        logger.info(DASHES);
        logger.info("1. Create an Amazon OpenSearch domain");
        logger.info("""
            An Amazon OpenSearch domain is a managed instance of the OpenSearch engine, 
            which is an open-source search and analytics engine derived from Elasticsearch. 
            An OpenSearch domain is essentially a cluster of compute resources and storage that hosts 
            one or more OpenSearch indexes, enabling you to perform full-text searches, data analysis, and 
            visualizations.

            In this step, we'll initiate the creation of the domain. We'll check on the progress in a later step.
        """);
        waitForInputToContinue(scanner);

        try {
            CompletableFuture<String> future = openSearchActions.createNewDomainAsync(domainName);
            String domainId = future.join();
            logger.info("Domain successfully created with ID: {}", domainId);
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause != null) {
                if (cause instanceof OpenSearchException openSearchEx) {
                    logger.error("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode());
                } else {
                    logger.error("An unexpected error occurred: " + cause.getMessage(), cause);
                }
            } else {
                logger.error("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("2. Describe the Amazon OpenSearch domain");
        logger.info("In this step, we get back the Domain ARN which is used in an upcoming step.");
        waitForInputToContinue(scanner);

        String arn = "";
        try {
            CompletableFuture<String> future = openSearchActions.describeDomainAsync(domainName);
            arn = future.join();
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof OpenSearchException openSearchEx) {
                logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("3. List the domains in your account");
        waitForInputToContinue(scanner);

        try {
            CompletableFuture<List<DomainInfo>> future = openSearchActions.listAllDomainsAsync();
            List<DomainInfo> domainInfoList = future.join();
            for (DomainInfo domain : domainInfoList) {
                logger.info("Domain name is: " + domain.domainName());
            }
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            while (cause.getCause() != null && !(cause instanceof OpenSearchException)) {
                cause = cause.getCause();
            }
            if (cause instanceof OpenSearchException openSearchEx) {
                logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("4. Wait until the domain's change status reaches a completed state");
        logger.info("""
            In this step, we check on the change status of the domain that we initiated in Step 1.
            Until we reach a COMPLETED state, we stay in a loop by sending a DescribeDomainChangeProgressRequest.

            The time it takes for a change to an OpenSearch domain to reach a completed state can range
            from a few minutes to several hours. In this case the change is creating a new domain that we initiated in Step 1.
            The time varies depending on the complexity of the change and the current load on
            the OpenSearch service. In general, simple changes, such as scaling the number of data nodes or
            updating the OpenSearch version, may take 10-30 minutes.
        """);

        waitForInputToContinue(scanner);

        try {
            CompletableFuture<Void> future = openSearchActions.domainChangeProgressAsync(domainName);
            future.join();
            logger.info("Domain change progress completed successfully.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            while (cause.getCause() != null && !(cause instanceof ResourceNotFoundException)) {
                cause = cause.getCause();
            }
            if (cause instanceof ResourceNotFoundException resourceNotFoundException) {
                logger.info("The specific AWS resource was not found: Error message: {}, Error code {}", resourceNotFoundException.awsErrorDetails().errorMessage(), resourceNotFoundException.awsErrorDetails().errorCode());

                if (cause instanceof OpenSearchException ex) {
                    logger.info("An OpenSearch error occurred: Error message: " + ex.getMessage());
                } else {
                    logger.info("An unexpected error occurred: " + rt.getMessage());
                }
                throw cause;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("5. Modify the domain");
        logger.info("""
            You can change your OpenSearch domain's settings, like the number of instances, without starting over from scratch.
            This makes it easy to adjust your domain as your needs change, allowing you to scale up or
            down quickly without recreating everything.

            We modify the domain in this step by changing the number of instances.
        """);

        waitForInputToContinue(scanner);

        try {
            CompletableFuture<UpdateDomainConfigResponse> future = openSearchActions.updateSpecificDomainAsync(domainName);
            UpdateDomainConfigResponse updateResponse = future.join();
            logger.info("Domain update status: " + updateResponse.domainConfig().changeProgressDetails().configChangeStatusAsString());
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof OpenSearchException openSearchEx) {
                logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("6. Wait until the domain's change status reaches a completed state");
        logger.info("""
            In this step, we poll the status until the domain's change status reaches a completed state.
        """);

        waitForInputToContinue(scanner);

        try {
            CompletableFuture<Void> future = openSearchActions.domainChangeProgressAsync(domainName);
            future.join();
            logger.info("Domain change progress completed successfully.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof OpenSearchException ex) {
                logger.info("EC2 error occurred: Error message: " +ex.getMessage());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("7. Tag the Domain");
        logger.info("""
            Tags let you assign arbitrary information to an Amazon OpenSearch Service domain so you can
            categorize and filter on that information. A tag is a key-value pair that you define and
            associate with an OpenSearch Service domain. You can use these tags to track costs by grouping
            expenses for similarly tagged resources.

            In this scenario, we create tags with keys "service" and "instances".
        """);

        waitForInputToContinue(scanner);

        try {
            CompletableFuture<AddTagsResponse> future = openSearchActions.addDomainTagsAsync(arn);
            future.join();
            logger.info("Domain tags added successfully.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            while (cause.getCause() != null && !(cause instanceof OpenSearchException)) {
                cause = cause.getCause();
            }
            if (cause instanceof OpenSearchException openSearchEx) {
                logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
                if (cause != null) {
                    if (cause instanceof OpenSearchException) {
                        logger.error("OpenSearch error occurred: Error message: " + cause.getMessage(), cause);
                    } else {
                        logger.error("An unexpected error occurred: " + cause.getMessage(), cause);
                    }
                } else {
                    logger.error("An unexpected error occurred: " + rt.getMessage(), rt);
                }
                throw cause;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("8. List Domain tags");
        waitForInputToContinue(scanner);

        try {
            CompletableFuture<ListTagsResponse> future = openSearchActions.listDomainTagsAsync(arn);
            ListTagsResponse listTagsResponse = future.join();
            listTagsResponse.tagList().forEach(tag -> logger.info("Tag Key: " + tag.key() + ", Tag Value: " + tag.value()));
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            while (cause.getCause() != null && !(cause instanceof OpenSearchException)) {
                cause = cause.getCause();
            }
            if (cause instanceof OpenSearchException openSearchEx) {
                logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;

        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("9. Delete the domain");
        logger.info("""
            In this step, we'll delete the Amazon OpenSearch domain that we created in Step 1.
            Deleting a domain will remove all data and configuration for that domain.
        """);

        waitForInputToContinue(scanner);

        try {
            CompletableFuture<DeleteDomainResponse> future = openSearchActions.deleteSpecificDomainAsync(domainName);
            future.join();
            logger.info("Domain successfully deleted.");
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            while (cause.getCause() != null && !(cause instanceof OpenSearchException)) {
                cause = cause.getCause();
            }
            if (cause instanceof OpenSearchException openSearchEx) {
                logger.info("OpenSearch error occurred: Error message: {}, Error code {}", openSearchEx.awsErrorDetails().errorMessage(), openSearchEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;

        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("Scenario complete!");
    }
 }
```
OpenSearch Service SDK メソッドのラッパークラス。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.opensearch.OpenSearchAsyncClient;
import software.amazon.awssdk.services.opensearch.model.AddTagsRequest;
import software.amazon.awssdk.services.opensearch.model.AddTagsResponse;
import software.amazon.awssdk.services.opensearch.model.ClusterConfig;
import software.amazon.awssdk.services.opensearch.model.CreateDomainRequest;
import software.amazon.awssdk.services.opensearch.model.DeleteDomainRequest;
import software.amazon.awssdk.services.opensearch.model.DeleteDomainResponse;
import software.amazon.awssdk.services.opensearch.model.DescribeDomainChangeProgressRequest;
import software.amazon.awssdk.services.opensearch.model.DescribeDomainChangeProgressResponse;
import software.amazon.awssdk.services.opensearch.model.DescribeDomainRequest;
import software.amazon.awssdk.services.opensearch.model.DomainInfo;
import software.amazon.awssdk.services.opensearch.model.DomainStatus;
import software.amazon.awssdk.services.opensearch.model.EBSOptions;
import software.amazon.awssdk.services.opensearch.model.ListDomainNamesRequest;
import software.amazon.awssdk.services.opensearch.model.ListTagsRequest;
import software.amazon.awssdk.services.opensearch.model.ListTagsResponse;
import software.amazon.awssdk.services.opensearch.model.NodeToNodeEncryptionOptions;
import software.amazon.awssdk.services.opensearch.model.Tag;
import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigRequest;
import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigResponse;
import software.amazon.awssdk.services.opensearch.model.VolumeType;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class OpenSearchActions {
    private static final Logger logger = LoggerFactory.getLogger(OpenSearchActions.class);
    private static OpenSearchAsyncClient openSearchClientAsyncClient;
    private static OpenSearchAsyncClient getAsyncClient() {
        if (openSearchClientAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryPolicy(RetryPolicy.builder()
                    .numRetries(3)
                    .build())
                .build();

            openSearchClientAsyncClient = OpenSearchAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return openSearchClientAsyncClient;
    }

    /**
     * Creates a new OpenSearch domain asynchronously.
     * @param domainName the name of the new OpenSearch domain to create
     * @return a {@link CompletableFuture} containing the domain ID of the newly created domain
     */
    public CompletableFuture<String> createNewDomainAsync(String domainName) {
        ClusterConfig clusterConfig = ClusterConfig.builder()
            .dedicatedMasterEnabled(true)
            .dedicatedMasterCount(3)
            .dedicatedMasterType("t2.small.search")
            .instanceType("t2.small.search")
            .instanceCount(5)
            .build();

        EBSOptions ebsOptions = EBSOptions.builder()
            .ebsEnabled(true)
            .volumeSize(10)
            .volumeType(VolumeType.GP2)
            .build();

        NodeToNodeEncryptionOptions encryptionOptions = NodeToNodeEncryptionOptions.builder()
            .enabled(true)
            .build();

        CreateDomainRequest domainRequest = CreateDomainRequest.builder()
            .domainName(domainName)
            .engineVersion("OpenSearch_1.0")
            .clusterConfig(clusterConfig)
            .ebsOptions(ebsOptions)
            .nodeToNodeEncryptionOptions(encryptionOptions)
            .build();
        logger.info("Sending domain creation request...");
        return getAsyncClient().createDomain(domainRequest)
                .handle( (createResponse, throwable) -> {
                    if (createResponse != null) {
                        logger.info("Domain status is {}", createResponse.domainStatus().changeProgressDetails().configChangeStatusAsString());
                        logger.info("Domain Id is {}", createResponse.domainStatus().domainId());
                        return createResponse.domainStatus().domainId();
                    }
                    throw new RuntimeException("Failed to create domain", throwable);
                });
    }

    /**
     * Deletes a specific domain asynchronously.
     * @param domainName the name of the domain to be deleted
     * @return a {@link CompletableFuture} that completes when the domain has been deleted
     * or throws a {@link RuntimeException} if the deletion fails
     */
    public CompletableFuture<DeleteDomainResponse> deleteSpecificDomainAsync(String domainName) {
        DeleteDomainRequest domainRequest = DeleteDomainRequest.builder()
            .domainName(domainName)
            .build();

        // Delete domain asynchronously
        return getAsyncClient().deleteDomain(domainRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to delete the domain: " + domainName, exception);
                }
            });
    }

    /**
     * Describes the specified domain asynchronously.
     *
     * @param domainName the name of the domain to describe
     * @return a {@link CompletableFuture} that completes with the ARN of the domain
     * @throws RuntimeException if the domain description fails
     */
    public CompletableFuture<String> describeDomainAsync(String domainName) {
        DescribeDomainRequest request = DescribeDomainRequest.builder()
            .domainName(domainName)
            .build();

        return getAsyncClient().describeDomain(request)
            .handle((response, exception) -> {  // Handle both response and exception
                if (exception != null) {
                    throw new RuntimeException("Failed to describe domain", exception);
                }
                DomainStatus domainStatus = response.domainStatus();
                String endpoint = domainStatus.endpoint();
                String arn = domainStatus.arn();
                String engineVersion = domainStatus.engineVersion();
                logger.info("Domain endpoint is: " + endpoint);
                logger.info("ARN: " + arn);
                System.out.println("Engine version: " + engineVersion);

                return arn;  // Return ARN when successful
            });
    }

    /**
     * Asynchronously lists all the domains in the current AWS account.
     * @return a {@link CompletableFuture} that, when completed, contains a list of {@link DomainInfo} objects representing
     *         the domains in the account.
     * @throws RuntimeException if there was a failure while listing the domains.
     */
    public CompletableFuture<List<DomainInfo>> listAllDomainsAsync() {
        ListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder()
            .engineType("OpenSearch")
            .build();

        return getAsyncClient().listDomainNames(namesRequest)
            .handle((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to list all domains", exception);
                }
                return response.domainNames();  // Return the list of domain names on success
            });
    }

    /**
     * Updates the configuration of a specific domain asynchronously.
     * @param domainName the name of the domain to update
     * @return a {@link CompletableFuture} that represents the asynchronous operation of updating the domain configuration
     */
    public CompletableFuture<UpdateDomainConfigResponse> updateSpecificDomainAsync(String domainName) {
        ClusterConfig clusterConfig = ClusterConfig.builder()
            .instanceCount(3)
            .build();

        UpdateDomainConfigRequest updateDomainConfigRequest = UpdateDomainConfigRequest.builder()
            .domainName(domainName)
            .clusterConfig(clusterConfig)
            .build();

        return getAsyncClient().updateDomainConfig(updateDomainConfigRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to update the domain configuration", exception);
                }
                // Handle success if needed (e.g., logging or additional actions)
            });
    }

    /**
     * Asynchronously checks the progress of a domain change operation in Amazon OpenSearch Service.
     * @param domainName the name of the OpenSearch domain to check the progress for
     * @return a {@link CompletableFuture} that completes when the domain change operation is completed
     */
    public CompletableFuture<Void> domainChangeProgressAsync(String domainName) {
        DescribeDomainChangeProgressRequest request = DescribeDomainChangeProgressRequest.builder()
            .domainName(domainName)
            .build();

        return CompletableFuture.runAsync(() -> {
            boolean isCompleted = false;
            long startTime = System.currentTimeMillis();

            while (!isCompleted) {
                try {
                    // Handle the async client call using `join` to block synchronously for the result
                    DescribeDomainChangeProgressResponse response = getAsyncClient()
                        .describeDomainChangeProgress(request)
                        .handle((resp, ex) -> {
                            if (ex != null) {
                                throw new RuntimeException("Failed to check domain progress", ex);
                            }
                            return resp;
                        }).join();

                    String state = response.changeProgressStatus().statusAsString();  // Get the status as string

                    if ("COMPLETED".equals(state)) {
                        logger.info("\nOpenSearch domain status: Completed");
                        isCompleted = true;
                    } else {
                        for (int i = 0; i < 5; i++) {
                            long elapsedTimeInSeconds = (System.currentTimeMillis() - startTime) / 1000;
                            String formattedTime = String.format("%02d:%02d", elapsedTimeInSeconds / 60, elapsedTimeInSeconds % 60);
                            System.out.print("\rOpenSearch domain state: " + state + " | Time Elapsed: " + formattedTime + " ");
                            System.out.flush();
                            Thread.sleep(1_000);
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Thread was interrupted", e);
                }
            }
        });
    }

    /**
     * Asynchronously adds tags to an Amazon OpenSearch Service domain.
     * @param domainARN the Amazon Resource Name (ARN) of the Amazon OpenSearch Service domain to add tags to
     * @return a {@link CompletableFuture} that completes when the tags have been successfully added to the domain,
     * or throws a {@link RuntimeException} if the operation fails
     */
    public CompletableFuture<AddTagsResponse> addDomainTagsAsync(String domainARN) {
        Tag tag1 = Tag.builder()
            .key("service")
            .value("OpenSearch")
            .build();

        Tag tag2 = Tag.builder()
            .key("instances")
            .value("m3.2xlarge")
            .build();

        List<Tag> tagList = new ArrayList<>();
        tagList.add(tag1);
        tagList.add(tag2);

        AddTagsRequest addTagsRequest = AddTagsRequest.builder()
            .arn(domainARN)
            .tagList(tagList)
            .build();

        return getAsyncClient().addTags(addTagsRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to add tags to the domain: " + domainARN, exception);
                } else {
                    logger.info("Added Tags");
                }
            });
    }


    /**
     * Asynchronously lists the tags associated with the specified Amazon Resource Name (ARN).
     * @param arn the Amazon Resource Name (ARN) of the resource for which to list the tags
     * @return a {@link CompletableFuture} that, when completed, will contain a list of the tags associated with the
     * specified ARN
     * @throws RuntimeException if there is an error listing the tags
     */
    public CompletableFuture<ListTagsResponse> listDomainTagsAsync(String arn) {
        ListTagsRequest tagsRequest = ListTagsRequest.builder()
            .arn(arn)
            .build();

        return getAsyncClient().listTags(tagsRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to list domain tags", exception);
                }

                List<Tag> tagList = response.tagList();
                for (Tag tag : tagList) {
                    logger.info("Tag key is " + tag.key());
                    logger.info("Tag value is " + tag.value());
                }
            });
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AddTags](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/AddTags)
  + [CreateDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/CreateDomain)
  + [DeleteDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/DeleteDomain)
  + [DescribeDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/DescribeDomain)
  + [DescribeDomainChangeProgress](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/DescribeDomainChangeProgress)
  + [ListDomainNames](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/ListDomainNames)
  + [ListTags](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/ListTags)
  + [UpdateDomainConfig](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/UpdateDomainConfig)

## アクション
<a name="actions"></a>

### `AddTags`
<a name="opensearch_AddTags_java_2_topic"></a>

次のコード例は、`AddTags` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously adds tags to an Amazon OpenSearch Service domain.
     * @param domainARN the Amazon Resource Name (ARN) of the Amazon OpenSearch Service domain to add tags to
     * @return a {@link CompletableFuture} that completes when the tags have been successfully added to the domain,
     * or throws a {@link RuntimeException} if the operation fails
     */
    public CompletableFuture<AddTagsResponse> addDomainTagsAsync(String domainARN) {
        Tag tag1 = Tag.builder()
            .key("service")
            .value("OpenSearch")
            .build();

        Tag tag2 = Tag.builder()
            .key("instances")
            .value("m3.2xlarge")
            .build();

        List<Tag> tagList = new ArrayList<>();
        tagList.add(tag1);
        tagList.add(tag2);

        AddTagsRequest addTagsRequest = AddTagsRequest.builder()
            .arn(domainARN)
            .tagList(tagList)
            .build();

        return getAsyncClient().addTags(addTagsRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to add tags to the domain: " + domainARN, exception);
                } else {
                    logger.info("Added Tags");
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[AddTags](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/AddTags)」を参照してください。

### `ChangeProgress`
<a name="opensearch_ChangeProgress_java_2_topic"></a>

次のコード例は、`ChangeProgress` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously checks the progress of a domain change operation in Amazon OpenSearch Service.
     * @param domainName the name of the OpenSearch domain to check the progress for
     * @return a {@link CompletableFuture} that completes when the domain change operation is completed
     */
    public CompletableFuture<Void> domainChangeProgressAsync(String domainName) {
        DescribeDomainChangeProgressRequest request = DescribeDomainChangeProgressRequest.builder()
            .domainName(domainName)
            .build();

        return CompletableFuture.runAsync(() -> {
            boolean isCompleted = false;
            long startTime = System.currentTimeMillis();

            while (!isCompleted) {
                try {
                    // Handle the async client call using `join` to block synchronously for the result
                    DescribeDomainChangeProgressResponse response = getAsyncClient()
                        .describeDomainChangeProgress(request)
                        .handle((resp, ex) -> {
                            if (ex != null) {
                                throw new RuntimeException("Failed to check domain progress", ex);
                            }
                            return resp;
                        }).join();

                    String state = response.changeProgressStatus().statusAsString();  // Get the status as string

                    if ("COMPLETED".equals(state)) {
                        logger.info("\nOpenSearch domain status: Completed");
                        isCompleted = true;
                    } else {
                        for (int i = 0; i < 5; i++) {
                            long elapsedTimeInSeconds = (System.currentTimeMillis() - startTime) / 1000;
                            String formattedTime = String.format("%02d:%02d", elapsedTimeInSeconds / 60, elapsedTimeInSeconds % 60);
                            System.out.print("\rOpenSearch domain state: " + state + " | Time Elapsed: " + formattedTime + " ");
                            System.out.flush();
                            Thread.sleep(1_000);
                        }
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Thread was interrupted", e);
                }
            }
        });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の[ChangeProgress](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/ChangeProgress)」を参照してください。

### `CreateDomain`
<a name="opensearch_CreateDomain_java_2_topic"></a>

次のコード例は、`CreateDomain` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new OpenSearch domain asynchronously.
     * @param domainName the name of the new OpenSearch domain to create
     * @return a {@link CompletableFuture} containing the domain ID of the newly created domain
     */
    public CompletableFuture<String> createNewDomainAsync(String domainName) {
        ClusterConfig clusterConfig = ClusterConfig.builder()
            .dedicatedMasterEnabled(true)
            .dedicatedMasterCount(3)
            .dedicatedMasterType("t2.small.search")
            .instanceType("t2.small.search")
            .instanceCount(5)
            .build();

        EBSOptions ebsOptions = EBSOptions.builder()
            .ebsEnabled(true)
            .volumeSize(10)
            .volumeType(VolumeType.GP2)
            .build();

        NodeToNodeEncryptionOptions encryptionOptions = NodeToNodeEncryptionOptions.builder()
            .enabled(true)
            .build();

        CreateDomainRequest domainRequest = CreateDomainRequest.builder()
            .domainName(domainName)
            .engineVersion("OpenSearch_1.0")
            .clusterConfig(clusterConfig)
            .ebsOptions(ebsOptions)
            .nodeToNodeEncryptionOptions(encryptionOptions)
            .build();
        logger.info("Sending domain creation request...");
        return getAsyncClient().createDomain(domainRequest)
                .handle( (createResponse, throwable) -> {
                    if (createResponse != null) {
                        logger.info("Domain status is {}", createResponse.domainStatus().changeProgressDetails().configChangeStatusAsString());
                        logger.info("Domain Id is {}", createResponse.domainStatus().domainId());
                        return createResponse.domainStatus().domainId();
                    }
                    throw new RuntimeException("Failed to create domain", throwable);
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/CreateDomain)」を参照してください。

### `DeleteDomain`
<a name="opensearch_DeleteDomain_java_2_topic"></a>

次のコード例は、`DeleteDomain` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a specific domain asynchronously.
     * @param domainName the name of the domain to be deleted
     * @return a {@link CompletableFuture} that completes when the domain has been deleted
     * or throws a {@link RuntimeException} if the deletion fails
     */
    public CompletableFuture<DeleteDomainResponse> deleteSpecificDomainAsync(String domainName) {
        DeleteDomainRequest domainRequest = DeleteDomainRequest.builder()
            .domainName(domainName)
            .build();

        // Delete domain asynchronously
        return getAsyncClient().deleteDomain(domainRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to delete the domain: " + domainName, exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/DeleteDomain)」を参照してください。

### `DescribeDomain`
<a name="opensearch_DescribeDomain_java_2_topic"></a>

次のコード例は、`DescribeDomain` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Describes the specified domain asynchronously.
     *
     * @param domainName the name of the domain to describe
     * @return a {@link CompletableFuture} that completes with the ARN of the domain
     * @throws RuntimeException if the domain description fails
     */
    public CompletableFuture<String> describeDomainAsync(String domainName) {
        DescribeDomainRequest request = DescribeDomainRequest.builder()
            .domainName(domainName)
            .build();

        return getAsyncClient().describeDomain(request)
            .handle((response, exception) -> {  // Handle both response and exception
                if (exception != null) {
                    throw new RuntimeException("Failed to describe domain", exception);
                }
                DomainStatus domainStatus = response.domainStatus();
                String endpoint = domainStatus.endpoint();
                String arn = domainStatus.arn();
                String engineVersion = domainStatus.engineVersion();
                logger.info("Domain endpoint is: " + endpoint);
                logger.info("ARN: " + arn);
                System.out.println("Engine version: " + engineVersion);

                return arn;  // Return ARN when successful
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/DescribeDomain)」を参照してください。

### `ListDomainNames`
<a name="opensearch_ListDomainNames_java_2_topic"></a>

次のコード例は、`ListDomainNames` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously lists all the domains in the current AWS account.
     * @return a {@link CompletableFuture} that, when completed, contains a list of {@link DomainInfo} objects representing
     *         the domains in the account.
     * @throws RuntimeException if there was a failure while listing the domains.
     */
    public CompletableFuture<List<DomainInfo>> listAllDomainsAsync() {
        ListDomainNamesRequest namesRequest = ListDomainNamesRequest.builder()
            .engineType("OpenSearch")
            .build();

        return getAsyncClient().listDomainNames(namesRequest)
            .handle((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to list all domains", exception);
                }
                return response.domainNames();  // Return the list of domain names on success
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListDomainNames](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/ListDomainNames)」を参照してください。

### `ListTags`
<a name="opensearch_ListTags_java_2_topic"></a>

次のコード例は、`ListTags` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously adds tags to an Amazon OpenSearch Service domain.
     * @param domainARN the Amazon Resource Name (ARN) of the Amazon OpenSearch Service domain to add tags to
     * @return a {@link CompletableFuture} that completes when the tags have been successfully added to the domain,
     * or throws a {@link RuntimeException} if the operation fails
     */
    public CompletableFuture<AddTagsResponse> addDomainTagsAsync(String domainARN) {
        Tag tag1 = Tag.builder()
            .key("service")
            .value("OpenSearch")
            .build();

        Tag tag2 = Tag.builder()
            .key("instances")
            .value("m3.2xlarge")
            .build();

        List<Tag> tagList = new ArrayList<>();
        tagList.add(tag1);
        tagList.add(tag2);

        AddTagsRequest addTagsRequest = AddTagsRequest.builder()
            .arn(domainARN)
            .tagList(tagList)
            .build();

        return getAsyncClient().addTags(addTagsRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to add tags to the domain: " + domainARN, exception);
                } else {
                    logger.info("Added Tags");
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListTags](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/ListTags)」を参照してください。

### `UpdateDomainConfig`
<a name="opensearch_UpdateDomainConfig_java_2_topic"></a>

次のコード例は、`UpdateDomainConfig` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/opensearch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the configuration of a specific domain asynchronously.
     * @param domainName the name of the domain to update
     * @return a {@link CompletableFuture} that represents the asynchronous operation of updating the domain configuration
     */
    public CompletableFuture<UpdateDomainConfigResponse> updateSpecificDomainAsync(String domainName) {
        ClusterConfig clusterConfig = ClusterConfig.builder()
            .instanceCount(3)
            .build();

        UpdateDomainConfigRequest updateDomainConfigRequest = UpdateDomainConfigRequest.builder()
            .domainName(domainName)
            .clusterConfig(clusterConfig)
            .build();

        return getAsyncClient().updateDomainConfig(updateDomainConfigRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Failed to update the domain configuration", exception);
                }
                // Handle success if needed (e.g., logging or additional actions)
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateDomainConfig](https://docs.aws.amazon.com/goto/SdkForJavaV2/es-2021-01-01/UpdateDomainConfig)」を参照してください。

# SDK for Java 2.x を使用した EventBridge の例
<a name="java_2_eventbridge_code_examples"></a>

次のコード例は、EventBridge AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello EventBridge
<a name="eventbridge_Hello_java_2_topic"></a>

次のコード例は、EventBridge の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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 HelloEventBridge {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        EventBridgeClient eventBrClient = EventBridgeClient.builder()
                .region(region)
                .build();

        listBuses(eventBrClient);
        eventBrClient.close();
    }

    public static void listBuses(EventBridgeClient eventBrClient) {
        try {
            ListEventBusesRequest busesRequest = ListEventBusesRequest.builder()
                    .limit(10)
                    .build();

            ListEventBusesResponse response = eventBrClient.listEventBuses(busesRequest);
            List<EventBus> buses = response.eventBuses();
            for (EventBus bus : buses) {
                System.out.println("The name of the event bus is: " + bus.name());
                System.out.println("The ARN of the event bus is: " + bus.arn());
            }

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListEventBuses](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/ListEventBuses)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="eventbridge_Scenario_GettingStarted_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ルールを作成して、ターゲットを追加する。
+ ルールを有効化および無効化する。
+ ルールとターゲットを一覧表示して更新する。
+ イベントを送信して、リソースをクリーンアップする。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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
 *
 * This Java code example performs the following tasks:
 *
 * This Java V2 example performs the following tasks with Amazon EventBridge:
 *
 * 1. Creates an AWS Identity and Access Management (IAM) role to use with
 * Amazon EventBridge.
 * 2. Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events
 * enabled.
 * 3. Creates a rule that triggers when an object is uploaded to Amazon S3.
 * 4. Lists rules on the event bus.
 * 5. Creates a new Amazon Simple Notification Service (Amazon SNS) topic and
 * lets the user subscribe to it.
 * 6. Adds a target to the rule that sends an email to the specified topic.
 * 7. Creates an EventBridge event that sends an email when an Amazon S3 object
 * is created.
 * 8. Lists Targets.
 * 9. Lists the rules for the same target.
 * 10. Triggers the rule by uploading a file to the Amazon S3 bucket.
 * 11. Disables a specific rule.
 * 12. Checks and print the state of the rule.
 * 13. Adds a transform to the rule to change the text of the email.
 * 14. Enables a specific rule.
 * 15. Triggers the updated rule by uploading a file to the Amazon S3 bucket.
 * 16. Updates the rule to be a custom rule pattern.
 * 17. Sending an event to trigger the rule.
 * 18. Cleans up resources.
 *
 */
public class EventbridgeMVP {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws InterruptedException, IOException {
        final String usage = """

                Usage:
                    <roleName> <bucketName> <topicName> <eventRuleName>

                Where:
                    roleName - The name of the role to create.
                    bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name to create.
                    topicName - The name of the Amazon Simple Notification Service (Amazon SNS) topic to create.
                    eventRuleName - The Amazon EventBridge rule name to create.
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String polJSON = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "\"Service\": \"events.amazonaws.com\"" +
                "}," +
                "\"Action\": \"sts:AssumeRole\"" +
                "}]" +
                "}";

        Scanner sc = new Scanner(System.in);
        String roleName = args[0];
        String bucketName = args[1];
        String topicName = args[2];
        String eventRuleName = args[3];

        Region region = Region.US_EAST_1;
        EventBridgeClient eventBrClient = EventBridgeClient.builder()
                .region(region)
                .build();

        S3Client s3Client = S3Client.builder()
                .region(region)
                .build();

        Region regionGl = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(regionGl)
                .build();

        SnsClient snsClient = SnsClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon EventBridge example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out
                .println("1. Create an AWS Identity and Access Management (IAM) role to use with Amazon EventBridge.");
        String roleArn = createIAMRole(iam, roleName, polJSON);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Create an S3 bucket with EventBridge events enabled.");
        if (checkBucket(s3Client, bucketName)) {
            System.out.println("Bucket " + bucketName + " already exists. Ending this scenario.");
            System.exit(1);
        }

        createBucket(s3Client, bucketName);
        Thread.sleep(3000);
        setBucketNotification(s3Client, bucketName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Create a rule that triggers when an object is uploaded to Amazon S3.");
        Thread.sleep(10000);
        addEventRule(eventBrClient, roleArn, bucketName, eventRuleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. List rules on the event bus.");
        listRules(eventBrClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Create a new SNS topic for testing and let the user subscribe to the topic.");
        String topicArn = createSnsTopic(snsClient, topicName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Add a target to the rule that sends an email to the specified topic.");
        System.out.println("Enter your email to subscribe to the Amazon SNS topic:");
        String email = sc.nextLine();
        subEmail(snsClient, topicArn, email);
        System.out.println(
                "Use the link in the email you received to confirm your subscription. Then, press Enter to continue.");
        sc.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Create an EventBridge event that sends an email when an Amazon S3 object is created.");
        addSnsEventRule(eventBrClient, eventRuleName, topicArn, topicName, eventRuleName, bucketName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 8. List Targets.");
        listTargets(eventBrClient, eventRuleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 9. List the rules for the same target.");
        listTargetRules(eventBrClient, topicArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 10. Trigger the rule by uploading a file to the S3 bucket.");
        System.out.println("Press Enter to continue.");
        sc.nextLine();
        uploadTextFiletoS3(s3Client, bucketName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Disable a specific rule.");
        changeRuleState(eventBrClient, eventRuleName, false);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("12. Check and print the state of the rule.");
        checkRule(eventBrClient, eventRuleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("13. Add a transform to the rule to change the text of the email.");
        updateSnsEventRule(eventBrClient, topicArn, eventRuleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("14. Enable a specific rule.");
        changeRuleState(eventBrClient, eventRuleName, true);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 15. Trigger the updated rule by uploading a file to the S3 bucket.");
        System.out.println("Press Enter to continue.");
        sc.nextLine();
        uploadTextFiletoS3(s3Client, bucketName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 16. Update the rule to be a custom rule pattern.");
        updateToCustomRule(eventBrClient, eventRuleName);
        System.out.println("Updated event rule " + eventRuleName + " to use a custom pattern.");
        updateCustomRuleTargetWithTransform(eventBrClient, topicArn, eventRuleName);
        System.out.println("Updated event target " + topicArn + ".");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("17. Sending an event to trigger the rule. This will trigger a subscription email.");
        triggerCustomRule(eventBrClient, email);
        System.out.println("Events have been sent. Press Enter to continue.");
        sc.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("18. Clean up resources.");
        System.out.println("Do you want to clean up resources (y/n)");
        String ans = sc.nextLine();
        if (ans.compareTo("y") == 0) {
            cleanupResources(eventBrClient, snsClient, s3Client, iam, topicArn, eventRuleName, bucketName, roleName);
        } else {
            System.out.println("The resources will not be cleaned up. ");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The Amazon EventBridge example scenario has successfully completed.");
        System.out.println(DASHES);
    }

    public static void cleanupResources(EventBridgeClient eventBrClient, SnsClient snsClient, S3Client s3Client,
            IamClient iam, String topicArn, String eventRuleName, String bucketName, String roleName) {
        System.out.println("Removing all targets from the event rule.");
        deleteTargetsFromRule(eventBrClient, eventRuleName);
        deleteRuleByName(eventBrClient, eventRuleName);
        deleteSNSTopic(snsClient, topicArn);
        deleteS3Bucket(s3Client, bucketName);
        deleteRole(iam, roleName);
    }

    public static void deleteRole(IamClient iam, String roleName) {
        String policyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess";
        DetachRolePolicyRequest policyRequest = DetachRolePolicyRequest.builder()
                .policyArn(policyArn)
                .roleName(roleName)
                .build();

        iam.detachRolePolicy(policyRequest);
        System.out.println("Successfully detached policy " + policyArn + " from role " + roleName);

        // Delete the role.
        DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
                .roleName(roleName)
                .build();

        iam.deleteRole(roleRequest);
        System.out.println("*** Successfully deleted " + roleName);
    }

    public static void deleteS3Bucket(S3Client s3Client, String bucketName) {
        // Remove all the objects from the S3 bucket.
        ListObjectsRequest listObjects = ListObjectsRequest.builder()
                .bucket(bucketName)
                .build();

        ListObjectsResponse res = s3Client.listObjects(listObjects);
        List<S3Object> objects = res.contents();
        ArrayList<ObjectIdentifier> toDelete = new ArrayList<>();

        for (S3Object myValue : objects) {
            toDelete.add(ObjectIdentifier.builder()
                    .key(myValue.key())
                    .build());
        }

        DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
                .bucket(bucketName)
                .delete(Delete.builder()
                        .objects(toDelete).build())
                .build();

        s3Client.deleteObjects(dor);

        // Delete the S3 bucket.
        DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
                .bucket(bucketName)
                .build();

        s3Client.deleteBucket(deleteBucketRequest);
        System.out.println("You have deleted the bucket and the objects");
    }

    // Delete the SNS topic.
    public static void deleteSNSTopic(SnsClient snsClient, String topicArn) {
        try {
            DeleteTopicRequest request = DeleteTopicRequest.builder()
                    .topicArn(topicArn)
                    .build();

            DeleteTopicResponse result = snsClient.deleteTopic(request);
            System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteRuleByName(EventBridgeClient eventBrClient, String ruleName) {
        DeleteRuleRequest ruleRequest = DeleteRuleRequest.builder()
                .name(ruleName)
                .build();

        eventBrClient.deleteRule(ruleRequest);
        System.out.println("Successfully deleted the rule");
    }

    public static void deleteTargetsFromRule(EventBridgeClient eventBrClient, String eventRuleName) {
        // First, get all targets that will be deleted.
        ListTargetsByRuleRequest request = ListTargetsByRuleRequest.builder()
                .rule(eventRuleName)
                .build();

        ListTargetsByRuleResponse response = eventBrClient.listTargetsByRule(request);
        List<Target> allTargets = response.targets();

        // Get all targets and delete them.
        for (Target myTarget : allTargets) {
            RemoveTargetsRequest removeTargetsRequest = RemoveTargetsRequest.builder()
                    .rule(eventRuleName)
                    .ids(myTarget.id())
                    .build();

            eventBrClient.removeTargets(removeTargetsRequest);
            System.out.println("Successfully removed the target");
        }
    }

    public static void triggerCustomRule(EventBridgeClient eventBrClient, String email) {
        String json = "{" +
                "\"UserEmail\": \"" + email + "\"," +
                "\"Message\": \"This event was generated by example code.\"," +
                "\"UtcTime\": \"Now.\"" +
                "}";

        PutEventsRequestEntry entry = PutEventsRequestEntry.builder()
                .source("ExampleSource")
                .detail(json)
                .detailType("ExampleType")
                .build();

        PutEventsRequest eventsRequest = PutEventsRequest.builder()
                .entries(entry)
                .build();

        eventBrClient.putEvents(eventsRequest);
    }

    public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBrClient, String topicArn,
            String ruleName) {
        String targetId = java.util.UUID.randomUUID().toString();
        InputTransformer inputTransformer = InputTransformer.builder()
                .inputTemplate("\"Notification: sample event was received.\"")
                .build();

        Target target = Target.builder()
                .id(targetId)
                .arn(topicArn)
                .inputTransformer(inputTransformer)
                .build();

        try {
            PutTargetsRequest targetsRequest = PutTargetsRequest.builder()
                    .rule(ruleName)
                    .targets(target)
                    .eventBusName(null)
                    .build();

            eventBrClient.putTargets(targetsRequest);
        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void updateToCustomRule(EventBridgeClient eventBrClient, String ruleName) {
        String customEventsPattern = "{" +
                "\"source\": [\"ExampleSource\"]," +
                "\"detail-type\": [\"ExampleType\"]" +
                "}";

        PutRuleRequest request = PutRuleRequest.builder()
                .name(ruleName)
                .description("Custom test rule")
                .eventPattern(customEventsPattern)
                .build();

        eventBrClient.putRule(request);
    }

    // Update an Amazon S3 object created rule with a transform on the target.
    public static void updateSnsEventRule(EventBridgeClient eventBrClient, String topicArn, String ruleName) {
        String targetId = java.util.UUID.randomUUID().toString();
        Map<String, String> myMap = new HashMap<>();
        myMap.put("bucket", "$.detail.bucket.name");
        myMap.put("time", "$.time");

        InputTransformer inputTransformer = InputTransformer.builder()
                .inputTemplate("\"Notification: an object was uploaded to bucket <bucket> at <time>.\"")
                .inputPathsMap(myMap)
                .build();

        Target target = Target.builder()
                .id(targetId)
                .arn(topicArn)
                .inputTransformer(inputTransformer)
                .build();

        try {
            PutTargetsRequest targetsRequest = PutTargetsRequest.builder()
                    .rule(ruleName)
                    .targets(target)
                    .eventBusName(null)
                    .build();

            eventBrClient.putTargets(targetsRequest);

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void checkRule(EventBridgeClient eventBrClient, String eventRuleName) {
        try {
            DescribeRuleRequest ruleRequest = DescribeRuleRequest.builder()
                    .name(eventRuleName)
                    .build();

            DescribeRuleResponse response = eventBrClient.describeRule(ruleRequest);
            System.out.println("The state of the rule is " + response.stateAsString());

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void changeRuleState(EventBridgeClient eventBrClient, String eventRuleName, Boolean isEnabled) {
        try {
            if (!isEnabled) {
                System.out.println("Disabling the rule: " + eventRuleName);
                DisableRuleRequest ruleRequest = DisableRuleRequest.builder()
                        .name(eventRuleName)
                        .build();

                eventBrClient.disableRule(ruleRequest);
            } else {
                System.out.println("Enabling the rule: " + eventRuleName);
                EnableRuleRequest ruleRequest = EnableRuleRequest.builder()
                        .name(eventRuleName)
                        .build();
                eventBrClient.enableRule(ruleRequest);
            }

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Create and upload a file to an S3 bucket to trigger an event.
    public static void uploadTextFiletoS3(S3Client s3Client, String bucketName) throws IOException {
        // Create a unique file name.
        String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName = "TextFile" + fileSuffix + ".txt";

        File myFile = new File(fileName);
        FileWriter fw = new FileWriter(myFile.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write("This is a sample file for testing uploads.");
        bw.close();

        try {
            PutObjectRequest putOb = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(fileName)
                    .build();

            s3Client.putObject(putOb, RequestBody.fromFile(myFile));

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void listTargetRules(EventBridgeClient eventBrClient, String topicArn) {
        ListRuleNamesByTargetRequest ruleNamesByTargetRequest = ListRuleNamesByTargetRequest.builder()
                .targetArn(topicArn)
                .build();

        ListRuleNamesByTargetResponse response = eventBrClient.listRuleNamesByTarget(ruleNamesByTargetRequest);
        List<String> rules = response.ruleNames();
        for (String rule : rules) {
            System.out.println("The rule name is " + rule);
        }
    }

    public static void listTargets(EventBridgeClient eventBrClient, String ruleName) {
        ListTargetsByRuleRequest ruleRequest = ListTargetsByRuleRequest.builder()
                .rule(ruleName)
                .build();

        ListTargetsByRuleResponse res = eventBrClient.listTargetsByRule(ruleRequest);
        List<Target> targetsList = res.targets();
        for (Target target: targetsList) {
            System.out.println("Target ARN: "+target.arn());
        }
    }

    // Add a rule which triggers an SNS target when a file is uploaded to an S3
    // bucket.
    public static void addSnsEventRule(EventBridgeClient eventBrClient, String ruleName, String topicArn,
            String topicName, String eventRuleName, String bucketName) {
        String targetID = java.util.UUID.randomUUID().toString();
        Target myTarget = Target.builder()
                .id(targetID)
                .arn(topicArn)
                .build();

        List<Target> targets = new ArrayList<>();
        targets.add(myTarget);
        PutTargetsRequest request = PutTargetsRequest.builder()
                .eventBusName(null)
                .targets(targets)
                .rule(ruleName)
                .build();

        eventBrClient.putTargets(request);
        System.out.println("Added event rule " + eventRuleName + " with Amazon SNS target " + topicName + " for bucket "
                + bucketName + ".");
    }

    public static void subEmail(SnsClient snsClient, String topicArn, String email) {
        try {
            SubscribeRequest request = SubscribeRequest.builder()
                    .protocol("email")
                    .endpoint(email)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

            SubscribeResponse result = snsClient.subscribe(request);
            System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void listRules(EventBridgeClient eventBrClient) {
        try {
            ListRulesRequest rulesRequest = ListRulesRequest.builder()
                    .eventBusName("default")
                    .limit(10)
                    .build();

            ListRulesResponse response = eventBrClient.listRules(rulesRequest);
            List<Rule> rules = response.rules();
            for (Rule rule : rules) {
                System.out.println("The rule name is : " + rule.name());
                System.out.println("The rule description is : " + rule.description());
                System.out.println("The rule state is : " + rule.stateAsString());
            }

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static String createSnsTopic(SnsClient snsClient, String topicName) {
        String topicPolicy = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Sid\": \"EventBridgePublishTopic\"," +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "\"Service\": \"events.amazonaws.com\"" +
                "}," +
                "\"Resource\": \"*\"," +
                "\"Action\": \"sns:Publish\"" +
                "}]" +
                "}";

        Map<String, String> topicAttributes = new HashMap<>();
        topicAttributes.put("Policy", topicPolicy);
        CreateTopicRequest topicRequest = CreateTopicRequest.builder()
                .name(topicName)
                .attributes(topicAttributes)
                .build();

        CreateTopicResponse response = snsClient.createTopic(topicRequest);
        System.out.println("Added topic " + topicName + " for email subscriptions.");
        return response.topicArn();
    }

    // Create a new event rule that triggers when an Amazon S3 object is created in
    // a bucket.
    public static void addEventRule(EventBridgeClient eventBrClient, String roleArn, String bucketName,
            String eventRuleName) {
        String pattern = "{\n" +
                "  \"source\": [\"aws.s3\"],\n" +
                "  \"detail-type\": [\"Object Created\"],\n" +
                "  \"detail\": {\n" +
                "    \"bucket\": {\n" +
                "      \"name\": [\"" + bucketName + "\"]\n" +
                "    }\n" +
                "  }\n" +
                "}";

        try {
            PutRuleRequest ruleRequest = PutRuleRequest.builder()
                    .description("Created by using the AWS SDK for Java v2")
                    .name(eventRuleName)
                    .eventPattern(pattern)
                    .roleArn(roleArn)
                    .build();

            PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest);
            System.out.println("The ARN of the new rule is " + ruleResponse.ruleArn());

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Determine if the S3 bucket exists.
    public static Boolean checkBucket(S3Client s3Client, String bucketName) {
        try {
            HeadBucketRequest headBucketRequest = HeadBucketRequest.builder()
                    .bucket(bucketName)
                    .build();

            s3Client.headBucket(headBucketRequest);
            return true;
        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        return false;
    }

    // Set the S3 bucket notification configuration.
    public static void setBucketNotification(S3Client s3Client, String bucketName) {
        try {
            EventBridgeConfiguration eventBridgeConfiguration = EventBridgeConfiguration.builder()
                    .build();

            NotificationConfiguration configuration = NotificationConfiguration.builder()
                    .eventBridgeConfiguration(eventBridgeConfiguration)
                    .build();

            PutBucketNotificationConfigurationRequest configurationRequest = PutBucketNotificationConfigurationRequest
                    .builder()
                    .bucket(bucketName)
                    .notificationConfiguration(configuration)
                    .skipDestinationValidation(true)
                    .build();

            s3Client.putBucketNotificationConfiguration(configurationRequest);
            System.out.println("Added bucket " + bucketName + " with EventBridge events enabled.");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

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

    public static String createIAMRole(IamClient iam, String rolename, String polJSON) {
        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(rolename)
                    .assumeRolePolicyDocument(polJSON)
                    .description("Created using the AWS SDK for Java")
                    .build();

            CreateRoleResponse response = iam.createRole(request);
            AttachRolePolicyRequest rolePolicyRequest = AttachRolePolicyRequest.builder()
                    .roleName(rolename)
                    .policyArn("arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess")
                    .build();

            iam.attachRolePolicy(rolePolicyRequest);
            return response.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [DeleteRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/DeleteRule)
  + [DescribeRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/DescribeRule)
  + [DisableRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/DisableRule)
  + [EnableRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/EnableRule)
  + [ListRuleNamesByTarget](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/ListRuleNamesByTarget)
  + [ListRules](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/ListRules)
  + [ListTargetsByRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/ListTargetsByRule)
  + [PutEvents](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutEvents)
  + [PutRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutRule)
  + [PutTargets](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutTargets)

## アクション
<a name="actions"></a>

### `DeleteRule`
<a name="eventbridge_DeleteRule_java_2_topic"></a>

次のコード例は、`DeleteRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteRuleByName(EventBridgeClient eventBrClient, String ruleName) {
        DeleteRuleRequest ruleRequest = DeleteRuleRequest.builder()
                .name(ruleName)
                .build();

        eventBrClient.deleteRule(ruleRequest);
        System.out.println("Successfully deleted the rule");
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/DeleteRule)」を参照してください。

### `DescribeRule`
<a name="eventbridge_DescribeRule_java_2_topic"></a>

次のコード例は、`DescribeRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
    public static void checkRule(EventBridgeClient eventBrClient, String eventRuleName) {
        try {
            DescribeRuleRequest ruleRequest = DescribeRuleRequest.builder()
                    .name(eventRuleName)
                    .build();

            DescribeRuleResponse response = eventBrClient.describeRule(ruleRequest);
            System.out.println("The state of the rule is " + response.stateAsString());

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/DescribeRule)」を参照してください。

### `DisableRule`
<a name="eventbridge_DisableRule_java_2_topic"></a>

次のコード例は、`DisableRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
そのルール名を使用してルールを無効化します。  

```
    public static void changeRuleState(EventBridgeClient eventBrClient, String eventRuleName, Boolean isEnabled) {
        try {
            if (!isEnabled) {
                System.out.println("Disabling the rule: " + eventRuleName);
                DisableRuleRequest ruleRequest = DisableRuleRequest.builder()
                        .name(eventRuleName)
                        .build();

                eventBrClient.disableRule(ruleRequest);
            } else {
                System.out.println("Enabling the rule: " + eventRuleName);
                EnableRuleRequest ruleRequest = EnableRuleRequest.builder()
                        .name(eventRuleName)
                        .build();
                eventBrClient.enableRule(ruleRequest);
            }

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DisableRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/DisableRule)」を参照してください。

### `EnableRule`
<a name="eventbridge_EnableRule_java_2_topic"></a>

次のコード例は、`EnableRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
そのルール名を使用してルールを有効化します。  

```
    public static void changeRuleState(EventBridgeClient eventBrClient, String eventRuleName, Boolean isEnabled) {
        try {
            if (!isEnabled) {
                System.out.println("Disabling the rule: " + eventRuleName);
                DisableRuleRequest ruleRequest = DisableRuleRequest.builder()
                        .name(eventRuleName)
                        .build();

                eventBrClient.disableRule(ruleRequest);
            } else {
                System.out.println("Enabling the rule: " + eventRuleName);
                EnableRuleRequest ruleRequest = EnableRuleRequest.builder()
                        .name(eventRuleName)
                        .build();
                eventBrClient.enableRule(ruleRequest);
            }

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[EnableRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/EnableRule)」を参照してください。

### `ListRuleNamesByTarget`
<a name="eventbridge_ListRuleNamesByTarget_java_2_topic"></a>

次のコード例は、`ListRuleNamesByTarget` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
ターゲットを使用してすべてのルール名を一覧表示します。  

```
    public static void listTargetRules(EventBridgeClient eventBrClient, String topicArn) {
        ListRuleNamesByTargetRequest ruleNamesByTargetRequest = ListRuleNamesByTargetRequest.builder()
                .targetArn(topicArn)
                .build();

        ListRuleNamesByTargetResponse response = eventBrClient.listRuleNamesByTarget(ruleNamesByTargetRequest);
        List<String> rules = response.ruleNames();
        for (String rule : rules) {
            System.out.println("The rule name is " + rule);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListRuleNamesByTarget](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/ListRuleNamesByTarget)」を参照してください。

### `ListRules`
<a name="eventbridge_ListRules_java_2_topic"></a>

次のコード例は、`ListRules` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
そのルール名を使用してルールを有効化します。  

```
    public static void listRules(EventBridgeClient eventBrClient) {
        try {
            ListRulesRequest rulesRequest = ListRulesRequest.builder()
                    .eventBusName("default")
                    .limit(10)
                    .build();

            ListRulesResponse response = eventBrClient.listRules(rulesRequest);
            List<Rule> rules = response.rules();
            for (Rule rule : rules) {
                System.out.println("The rule name is : " + rule.name());
                System.out.println("The rule description is : " + rule.description());
                System.out.println("The rule state is : " + rule.stateAsString());
            }

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListRules](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/ListRules)」を参照してください。

### `ListTargetsByRule`
<a name="eventbridge_ListTargetsByRule_java_2_topic"></a>

次のコード例は、`ListTargetsByRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
ルール名を使用してルールのすべてのターゲットを一覧表示します。  

```
    public static void listTargets(EventBridgeClient eventBrClient, String ruleName) {
        ListTargetsByRuleRequest ruleRequest = ListTargetsByRuleRequest.builder()
                .rule(ruleName)
                .build();

        ListTargetsByRuleResponse res = eventBrClient.listTargetsByRule(ruleRequest);
        List<Target> targetsList = res.targets();
        for (Target target: targetsList) {
            System.out.println("Target ARN: "+target.arn());
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListTargetsByRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/ListTargetsByRule)」を参照してください。

### `PutEvents`
<a name="eventbridge_PutEvents_java_2_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
    public static void triggerCustomRule(EventBridgeClient eventBrClient, String email) {
        String json = "{" +
                "\"UserEmail\": \"" + email + "\"," +
                "\"Message\": \"This event was generated by example code.\"," +
                "\"UtcTime\": \"Now.\"" +
                "}";

        PutEventsRequestEntry entry = PutEventsRequestEntry.builder()
                .source("ExampleSource")
                .detail(json)
                .detailType("ExampleType")
                .build();

        PutEventsRequest eventsRequest = PutEventsRequest.builder()
                .entries(entry)
                .build();

        eventBrClient.putEvents(eventsRequest);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutEvents)」を参照してください。

### `PutRule`
<a name="eventbridge_PutRule_java_2_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
スケジュールルールを作成します。  

```
    public static void createEBRule(EventBridgeClient eventBrClient, String ruleName, String cronExpression) {
        try {
            PutRuleRequest ruleRequest = PutRuleRequest.builder()
                    .name(ruleName)
                    .eventBusName("default")
                    .scheduleExpression(cronExpression)
                    .state("ENABLED")
                    .description("A test rule that runs on a schedule created by the Java API")
                    .build();

            PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest);
            System.out.println("The ARN of the new rule is " + ruleResponse.ruleArn());

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
Amazon Simple Storage Service バケットにオブジェクトが追加されたときにトリガーするルールを作成します。  

```
    // Create a new event rule that triggers when an Amazon S3 object is created in
    // a bucket.
    public static void addEventRule(EventBridgeClient eventBrClient, String roleArn, String bucketName,
            String eventRuleName) {
        String pattern = "{\n" +
                "  \"source\": [\"aws.s3\"],\n" +
                "  \"detail-type\": [\"Object Created\"],\n" +
                "  \"detail\": {\n" +
                "    \"bucket\": {\n" +
                "      \"name\": [\"" + bucketName + "\"]\n" +
                "    }\n" +
                "  }\n" +
                "}";

        try {
            PutRuleRequest ruleRequest = PutRuleRequest.builder()
                    .description("Created by using the AWS SDK for Java v2")
                    .name(eventRuleName)
                    .eventPattern(pattern)
                    .roleArn(roleArn)
                    .build();

            PutRuleResponse ruleResponse = eventBrClient.putRule(ruleRequest);
            System.out.println("The ARN of the new rule is " + ruleResponse.ruleArn());

        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutRule)」を参照してください。

### `PutTargets`
<a name="eventbridge_PutTargets_java_2_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
Amazon SNS トピックをルールのターゲットとして追加します。  

```
    // Add a rule which triggers an SNS target when a file is uploaded to an S3
    // bucket.
    public static void addSnsEventRule(EventBridgeClient eventBrClient, String ruleName, String topicArn,
            String topicName, String eventRuleName, String bucketName) {
        String targetID = java.util.UUID.randomUUID().toString();
        Target myTarget = Target.builder()
                .id(targetID)
                .arn(topicArn)
                .build();

        List<Target> targets = new ArrayList<>();
        targets.add(myTarget);
        PutTargetsRequest request = PutTargetsRequest.builder()
                .eventBusName(null)
                .targets(targets)
                .rule(ruleName)
                .build();

        eventBrClient.putTargets(request);
        System.out.println("Added event rule " + eventRuleName + " with Amazon SNS target " + topicName + " for bucket "
                + bucketName + ".");
    }
```
ルールのターゲットにインプットトランスフォーマーを追加します。  

```
    public static void updateCustomRuleTargetWithTransform(EventBridgeClient eventBrClient, String topicArn,
            String ruleName) {
        String targetId = java.util.UUID.randomUUID().toString();
        InputTransformer inputTransformer = InputTransformer.builder()
                .inputTemplate("\"Notification: sample event was received.\"")
                .build();

        Target target = Target.builder()
                .id(targetId)
                .arn(topicArn)
                .inputTransformer(inputTransformer)
                .build();

        try {
            PutTargetsRequest targetsRequest = PutTargetsRequest.builder()
                    .rule(ruleName)
                    .targets(target)
                    .eventBusName(null)
                    .build();

            eventBrClient.putTargets(targetsRequest);
        } catch (EventBridgeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutTargets](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutTargets)」を参照してください。

### `RemoveTargets`
<a name="eventbridge_RemoveTargets_java_2_topic"></a>

次のコード例は、`RemoveTargets` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
ルール名を使用してルールのすべてのターゲットを削除します。  

```
    public static void deleteTargetsFromRule(EventBridgeClient eventBrClient, String eventRuleName) {
        // First, get all targets that will be deleted.
        ListTargetsByRuleRequest request = ListTargetsByRuleRequest.builder()
                .rule(eventRuleName)
                .build();

        ListTargetsByRuleResponse response = eventBrClient.listTargetsByRule(request);
        List<Target> allTargets = response.targets();

        // Get all targets and delete them.
        for (Target myTarget : allTargets) {
            RemoveTargetsRequest removeTargetsRequest = RemoveTargetsRequest.builder()
                    .rule(eventRuleName)
                    .ids(myTarget.id())
                    .build();

            eventBrClient.removeTargets(removeTargetsRequest);
            System.out.println("Successfully removed the target");
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[RemoveTargets](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/RemoveTargets)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### EventBridge へのイベント通知の送信
<a name="s3_Scenario_PutBucketNotificationConfiguration_java_2_topic"></a>

次のコード例は、バケットが EventBridge に S3 イベント通知を送信し、Amazon SNS トピックと Amazon SQS キューに通知をルーティングできるようにする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /** This method configures a bucket to send events to AWS EventBridge and creates a rule
     * to route the S3 object created events to a topic and a queue.
     *
     * @param bucketName Name of existing bucket
     * @param topicArn ARN of existing topic to receive S3 event notifications
     * @param queueArn ARN of existing queue to receive S3 event notifications
     *
     *  An AWS CloudFormation stack sets up the bucket, queue, topic before the method runs.
     */
    public static String setBucketNotificationToEventBridge(String bucketName, String topicArn, String queueArn) {
        try {
            // Enable bucket to emit S3 Event notifications to EventBridge.
            s3Client.putBucketNotificationConfiguration(b -> b
                    .bucket(bucketName)
                    .notificationConfiguration(b1 -> b1
                            .eventBridgeConfiguration(
                                    SdkBuilder::build)
                    ).build()).join();

            // Create an EventBridge rule to route Object Created notifications.
            PutRuleRequest putRuleRequest = PutRuleRequest.builder()
                    .name(RULE_NAME)
                    .eventPattern("""
                            {
                              "source": ["aws.s3"],
                              "detail-type": ["Object Created"],
                              "detail": {
                                "bucket": {
                                  "name": ["%s"]
                                }
                              }
                            }
                            """.formatted(bucketName))
                    .build();

            // Add the rule to the default event bus.
            PutRuleResponse putRuleResponse = eventBridgeClient.putRule(putRuleRequest)
                    .whenComplete((r, t) -> {
                        if (t != null) {
                            logger.error("Error creating event bus rule: " + t.getMessage(), t);
                            throw new RuntimeException(t.getCause().getMessage(), t);
                        }
                        logger.info("Event bus rule creation request sent successfully. ARN is: {}", r.ruleArn());
                    }).join();

            // Add the existing SNS topic and SQS queue as targets to the rule.
            eventBridgeClient.putTargets(b -> b
                    .eventBusName("default")
                    .rule(RULE_NAME)
                    .targets(List.of (
                            Target.builder()
                                    .arn(queueArn)
                                    .id("Queue")
                                    .build(),
                            Target.builder()
                                    .arn(topicArn)
                                    .id("Topic")
                                    .build())
                            )
                    ).join();
            return putRuleResponse.ruleArn();
        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [PutBucketNotificationConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketNotificationConfiguration)
  + [PutRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutRule)
  + [PutTargets](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutTargets)

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_java_2_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda Java ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_scheduled_events) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

# SDK for Java 2.x を使用した EventBridge スケジューラの例
<a name="java_2_scheduler_code_examples"></a>

次のコード例は、EventBridge スケジューラ AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello EventBridge スケジューラ
<a name="scheduler_hello_java_2_topic"></a>

次のコード例は、EventBridge スケジューラの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.scheduler.SchedulerAsyncClient;
import software.amazon.awssdk.services.scheduler.model.ListSchedulesRequest;
import software.amazon.awssdk.services.scheduler.model.ScheduleSummary;
import software.amazon.awssdk.services.scheduler.paginators.ListSchedulesPublisher;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class HelloScheduler {

    public static void main(String [] args) {
        listSchedulesAsync();
    }

    /**
     * Lists all the schedules available.
     * <p>
     * This method uses the {@link SchedulerAsyncClient} to make an asynchronous request to
     * list all the schedules available. The method uses the {@link ListSchedulesPublisher}
     * to fetch the schedules in a paginated manner, and then processes the responses
     * asynchronously.
     */
    public static void listSchedulesAsync() {
        SchedulerAsyncClient schedulerAsyncClient = SchedulerAsyncClient.create();

        // Build the request to list schedules
        ListSchedulesRequest listSchedulesRequest = ListSchedulesRequest.builder().build();

        // Use the paginator to fetch all schedules asynchronously.
        ListSchedulesPublisher paginator = schedulerAsyncClient.listSchedulesPaginator(listSchedulesRequest);
        List<ScheduleSummary> results = new ArrayList<>();

        // Subscribe to the paginator to process the response asynchronously
        CompletableFuture<Void> future = paginator.subscribe(response -> {
            response.schedules().forEach(schedule -> {
                results.add(schedule);
                System.out.printf("Schedule: %s%n", schedule.name());
            });
        });

        // Wait for the asynchronous operation to complete.
        future.join();

        // After all schedules are fetched, print the total count.
        System.out.printf("Total of %d schedule(s) available.%n", results.size());
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListSchedules](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/ListSchedules)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateSchedule`
<a name="scheduler_CreateSchedule_java_2_topic"></a>

次のコード例は、`CreateSchedule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new schedule for a target task.
     *
     * @param name                  the name of the schedule
     * @param scheduleExpression    The schedule expression that defines when the schedule should run.
     * @param scheduleGroupName     the name of the schedule group to which the schedule belongs
     * @param targetArn             the Amazon Resource Name (ARN) of the target task
     * @param roleArn               the ARN of the IAM role to be used for the schedule
     * @param input                 the input data for the target task
     * @param deleteAfterCompletion whether to delete the schedule after it's executed
     * @param useFlexibleTimeWindow whether to use a flexible time window for the schedule execution
     * @return true if the schedule was successfully created, false otherwise
     */
    public CompletableFuture<Boolean> createScheduleAsync(
        String name,
        String scheduleExpression,
        String scheduleGroupName,
        String targetArn,
        String roleArn,
        String input,
        boolean deleteAfterCompletion,
        boolean useFlexibleTimeWindow) {

        int hoursToRun = 1;
        int flexibleTimeWindowMinutes = 10;

        Target target = Target.builder()
            .arn(targetArn)
            .roleArn(roleArn)
            .input(input)
            .build();

        FlexibleTimeWindow flexibleTimeWindow = FlexibleTimeWindow.builder()
            .mode(useFlexibleTimeWindow
                ? FlexibleTimeWindowMode.FLEXIBLE
                : FlexibleTimeWindowMode.OFF)
            .maximumWindowInMinutes(useFlexibleTimeWindow
                ? flexibleTimeWindowMinutes
                : null)
            .build();

        Instant startDate = Instant.now();
        Instant endDate = startDate.plus(Duration.ofHours(hoursToRun));

        CreateScheduleRequest request = CreateScheduleRequest.builder()
            .name(name)
            .scheduleExpression(scheduleExpression)
            .groupName(scheduleGroupName)
            .target(target)
            .actionAfterCompletion(deleteAfterCompletion
                ? ActionAfterCompletion.DELETE
                : ActionAfterCompletion.NONE)
            .startDate(startDate)
            .endDate(endDate)
            .flexibleTimeWindow(flexibleTimeWindow)
            .build();

        return getAsyncClient().createSchedule(request)
            .thenApply(response -> {
                logger.info("Successfully created schedule {} in schedule group {}, The ARN is {} ", name, scheduleGroupName, response.scheduleArn());
                return true;
            })
            .whenComplete((result, ex) -> {
                if (ex != null) {
                    if (ex instanceof ConflictException) {
                        // Handle ConflictException
                        logger.error("A conflict exception occurred while creating the schedule: {}", ex.getMessage());
                        throw new CompletionException("A conflict exception occurred while creating the schedule: " + ex.getMessage(), ex);
                    } else {
                        throw new CompletionException("Error creating schedule: " + ex.getMessage(), ex);
                    }
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*「[CreateSchedule](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/CreateSchedule)」を参照してください。

### `CreateScheduleGroup`
<a name="scheduler_CreateScheduleGroup_java_2_topic"></a>

次のコード例は、`CreateScheduleGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new schedule group.
     *
     * @param name the name of the schedule group to be created
     * @return a {@link CompletableFuture} representing the asynchronous operation of creating the schedule group
     */
    public CompletableFuture<CreateScheduleGroupResponse> createScheduleGroup(String name) {
        CreateScheduleGroupRequest request = CreateScheduleGroupRequest.builder()
            .name(name)
            .build();

        logger.info("Initiating createScheduleGroup call for group: {}", name);
        CompletableFuture<CreateScheduleGroupResponse> futureResponse = getAsyncClient().createScheduleGroup(request);
        futureResponse.whenComplete((response, ex) -> {
            if (ex != null) {
                if (ex instanceof CompletionException && ex.getCause() instanceof ConflictException) {
                    // Rethrow the ConflictException
                    throw (ConflictException) ex.getCause();
                } else {
                    throw new CompletionException("Failed to create schedule group: " + name, ex);
                }
            } else if (response == null) {
                throw new RuntimeException("Failed to create schedule group: response was null");
            } else {
                logger.info("Successfully created schedule group '{}': {}", name, response.scheduleGroupArn());
            }
        });

        return futureResponse;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateScheduleGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/CreateScheduleGroup)」を参照してください。

### `DeleteSchedule`
<a name="scheduler_DeleteSchedule_java_2_topic"></a>

次のコード例は、`DeleteSchedule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a schedule with the specified name and group name.
     *
     * @param name      the name of the schedule to be deleted
     * @param groupName the group name of the schedule to be deleted
     * @return a {@link CompletableFuture} that, when completed, indicates whether the schedule was successfully deleted
     * @throws CompletionException if an error occurs while deleting the schedule, except for the case where the schedule is not found
     */
    public CompletableFuture<Boolean> deleteScheduleAsync(String name, String groupName) {
        DeleteScheduleRequest request = DeleteScheduleRequest.builder()
            .name(name)
            .groupName(groupName)
            .build();

        CompletableFuture<DeleteScheduleResponse> response = getAsyncClient().deleteSchedule(request);
        return response.handle((result, ex) -> {
            if (ex != null) {
                if (ex instanceof ResourceNotFoundException) {
                    throw new CompletionException("Resource not found while deleting schedule with ID: " + name, ex);
                } else {
                    throw new CompletionException("Failed to delete schedule.", ex);
                }
            }
            logger.info("Successfully deleted schedule with name {}.", name);
            return true;
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteSchedule](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/DeleteSchedule)」を参照してください。

### `DeleteScheduleGroup`
<a name="scheduler_DeleteScheduleGroup_java_2_topic"></a>

次のコード例は、`DeleteScheduleGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes the specified schedule group.
     *
     * @param name the name of the schedule group to delete
     * @return a {@link CompletableFuture} that completes when the schedule group has been deleted
     * @throws CompletionException if an error occurs while deleting the schedule group
     */
    public CompletableFuture<Void> deleteScheduleGroupAsync(String name) {
        DeleteScheduleGroupRequest request = DeleteScheduleGroupRequest.builder()
            .name(name)
            .build();

        return getAsyncClient().deleteScheduleGroup(request)
            .thenRun(() -> {
                logger.info("Successfully deleted schedule group {}", name);
            })
            .whenComplete((result, ex) -> {
                if (ex != null) {
                    if (ex instanceof ResourceNotFoundException) {
                        throw new CompletionException("The resource was not found: " + ex.getMessage(), ex);
                    } else {
                        throw new CompletionException("Error deleting schedule group: " + ex.getMessage(), ex);
                    }
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteScheduleGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/DeleteScheduleGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 予定されているイベント
<a name="scheduler_ScheduledEventsScenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 必要なリソースを使用して CloudFormation スタックをデプロイします。
+ EventBridge スケジューラのスケジュールグループを作成します。
+ 柔軟な時間枠で 1 回限りの EventBridge スケジューラのスケジュールを作成します。
+ 指定されたレートで定期的な EventBridge スケジューラのスケジュールを作成します。
+ EventBridge スケジューラのスケジュールとスケジュールグループを削除します。
+ リソースをクリーンアップしてスタックを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。
シナリオを実行します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.scheduler.model.SchedulerException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

/**
 * This Java code example performs the following tasks for the Amazon EventBridge Scheduler workflow:
 * <p>
 * 1. Prepare the Application:
 * - Prompt the user for an email address to use for the subscription for the SNS topic subscription.
 * - Deploy the Cloud Formation template in resources/cfn_template.yaml for resource creation.
 * - Store the outputs of the stack into variables for use in the workflow.
 * - Create a schedule group for all workflow schedules.
 * <p>
 * 2. Create one-time Schedule:
 * - Create a one-time schedule to send an initial event.
 * - Use a Flexible Time Window and set the schedule to delete after completion.
 * - Wait for the user to receive the event email from SNS.
 * <p>
 * 3. Create a time-based schedule:
 * - Prompt the user for how many X times per Y hours a recurring event should be scheduled.
 * - Create the scheduled event for X times per hour for Y hours.
 * - Wait for the user to receive the event email from SNS.
 * - Delete the schedule when the user is finished.
 * <p>
 * 4. Clean up:
 * - Prompt the user for y/n answer if they want to destroy the stack and clean up all resources.
 * - Delete the schedule group.
 * - Destroy the Cloud Formation stack and wait until the stack has been removed.
 */

public class EventbridgeSchedulerScenario {

    private static final Logger logger = LoggerFactory.getLogger(EventbridgeSchedulerScenario.class);
    private static final Scanner scanner = new Scanner(System.in);
    private static String STACK_NAME = "workflow-stack-name";
    private static final String scheduleGroupName = "schedules-group";

    private static String recurringScheduleName = "";

    private static String oneTimeScheduleName = "";

    private static final EventbridgeSchedulerActions eventbridgeActions = new EventbridgeSchedulerActions();

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static String roleArn = "";
    public static String snsTopicArn = "";

    public static void main(String[] args) {
        logger.info(DASHES);
        logger.info("Welcome to the Amazon EventBridge Scheduler Workflow.");
        logger.info("""
            Amazon EventBridge Scheduler is a fully managed service that helps you schedule and execute 
            a wide range of tasks and events in the cloud. It's designed to simplify the process of 
            scheduling and managing recurring or one-time events, making it easier for developers and 
            businesses to automate various workflows and processes.
                        
            One of the key features of Amazon EventBridge Scheduler is its ability to schedule events 
            based on a variety of triggers, including time-based schedules, custom event patterns, or 
            even integration with other AWS services. For example, you can use EventBridge Scheduler 
            to schedule a report generation task to run every weekday at 9 AM, or to trigger a 
            Lambda function when a specific Amazon S3 object is created. 
                        
            This flexibility allows you to build complex and dynamic event-driven architectures 
            that adapt to your business needs.
                        
            Lets get started... 
            """);
        waitForInputToContinue();
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("1. Prepare the application.");
        waitForInputToContinue();
        try {
            boolean prepareSuccess = prepareApplication();
            logger.info(DASHES);

            if (prepareSuccess) {
                logger.info("2. Create one-time schedule.");
                logger.info("""
                    A one-time schedule in Amazon EventBridge Scheduler is an event trigger that allows
                    you to schedule a one-time event to run at a specific date and time. This is useful for
                    executing a specific task or workflow at a predetermined time, without the need for recurring
                    or complex scheduling.
                    """);
                waitForInputToContinue();
                createOneTimeSchedule();
                logger.info("Do you want to delete the schedule {} (y/n) ?", oneTimeScheduleName);
                String ans = scanner.nextLine().trim();
                if (ans.equalsIgnoreCase("y")) {
                    eventbridgeActions.deleteScheduleAsync(oneTimeScheduleName,scheduleGroupName);
                }
                logger.info(DASHES);

                logger.info("3. Create a recurring schedule.");
                logger.info("""
                    A recurring schedule is a feature that allows you to schedule and manage the execution
                    of your serverless applications or workloads on a recurring basis. For example, 
                    with EventBridge Scheduler, you can create custom schedules for your AWS Lambda functions, 
                    AWS Step Functions, and other supported event sources, enabling you to automate tasks and 
                    workflows without the need for complex infrastructure management. 
                    """);
                waitForInputToContinue();
                createRecurringSchedule();
                logger.info("Do you want to delete the schedule {} (y/n) ?", oneTimeScheduleName);
                String ans2 = scanner.nextLine().trim();
                if (ans2.equalsIgnoreCase("y")) {
                    eventbridgeActions.deleteScheduleAsync(recurringScheduleName,scheduleGroupName);
                }
                logger.info(DASHES);
            }
        } catch (Exception ex) {
            logger.info("There was a problem with the workflow {}, initiating cleanup...", ex.getMessage());
            cleanUp();
        }

        logger.info(DASHES);
        logger.info("4. Clean up the resources.");
        logger.info("Do you want to delete these AWS resources (y/n) ?");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            cleanUp();
        } else {
            logger.info("The AWS resources will not be deleted.");
        }
        logger.info("Amazon EventBridge Scheduler workflow completed.");
        logger.info(DASHES);
    }

    /**
     * Cleans up the resources associated with the EventBridge scheduler.
     * If any errors occur during the cleanup process, the corresponding error messages are logged.
     */
    public static void cleanUp() {
        logger.info("First, delete the schedule group.");
        logger.info("When the schedule group is deleted, schedules that are part of that group are deleted.");
        waitForInputToContinue();
        try {
            eventbridgeActions.deleteScheduleGroupAsync(scheduleGroupName).join();

        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof SchedulerException schedulerException) {
                logger.error("Scheduler error occurred: Error message: {}, Error code {}",
                    schedulerException.getMessage(), schedulerException.awsErrorDetails().errorCode(), schedulerException);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage());
            }
            return;
        }

        logger.info("Destroy the CloudFormation stack");
        waitForInputToContinue();
        CloudFormationHelper.destroyCloudFormationStack(STACK_NAME);
    }

    /**
     * Prepares the application by creating resources in a CloudFormation stack, including an SNS topic
     * that will be subscribed to the EventBridge Scheduler events. The user will need to confirm the subscription
     * in order to receive event emails.
     *
     * @return true if the application preparation was successful, false otherwise
     */
    public static boolean prepareApplication() {
        logger.info("""
            This example creates resources in a CloudFormation stack, including an SNS topic
            that will be subscribed to the EventBridge Scheduler events.
            You will need to confirm the subscription in order to receive event emails.
             """);

        String emailAddress = promptUserForEmail();
        logger.info("You entered {}", emailAddress);

        logger.info("Do you want to use a custom Stack name (y/n) ?");
        String ans = scanner.nextLine().trim();
        if (ans.equalsIgnoreCase("y")) {
            String newStackName = scanner.nextLine();
            logger.info("You entered {} for the new stack name", newStackName);
            waitForInputToContinue();
            STACK_NAME = newStackName;
        }

        logger.info("Get the roleArn and snsTopicArn values using a Cloudformation template.");
        waitForInputToContinue();
        CloudFormationHelper.deployCloudFormationStack(STACK_NAME, emailAddress);
        Map<String, String> stackOutputs = CloudFormationHelper.getStackOutputs(STACK_NAME);
        roleArn = stackOutputs.get("RoleARN");
        snsTopicArn = stackOutputs.get("SNStopicARN");

        logger.info("The roleARN is {}", roleArn);
        logger.info("The snsTopicArn is {}", snsTopicArn);

        try {
            eventbridgeActions.createScheduleGroup(scheduleGroupName).join();
            logger.info("createScheduleGroupAsync completed successfully.");

        } catch (RuntimeException e) {
            logger.error("Error occurred: {} ", e.getMessage());
            return false;
        }
        logger.info("Application preparation complete.");
        return true;
    }

    /**
     * Waits for the user to enter 'c' followed by <ENTER> to continue the program.
     * This method is used to pause the program execution and wait for user input before
     * proceeding.
     */
    private static void waitForInputToContinue() {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
    }

    /**
     * Prompts the user to enter an email address and validates the input.
     * If the provided email address is invalid, the method will prompt the user to try again.
     *
     * @return the valid email address entered by the user
     */
    private static String promptUserForEmail() {
        logger.info("Enter an email address to use for event subscriptions: ");
        String email = scanner.nextLine();
        if (!isValidEmail(email)) {
            logger.info("Invalid email address. Please try again.");
            return promptUserForEmail();
        }
        return email;
    }

    /**
     * Checks if the given email address is valid.
     *
     * @param email the email address to be validated
     * @return {@code true} if the email address is valid, {@code false} otherwise
     */
    private static boolean isValidEmail(String email) {
        try {
            InternetAddress emailAddress = new InternetAddress(email);
            emailAddress.validate();
            return true;

        } catch (AddressException e) {
            return false;
        }
    }

    /**
     * Creates a one-time schedule to send an initial event in 1 minute with a flexible time window.
     *
     * @return {@code true} if the schedule was created successfully, {@code false} otherwise
     */
    public static Boolean createOneTimeSchedule() {
        oneTimeScheduleName = promptUserForResourceName("Enter a name for the one-time schedule:");
        logger.info("Creating a one-time schedule named {} to send an initial event in 1 minute with a flexible time window...", oneTimeScheduleName);
        LocalDateTime scheduledTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

        String scheduleExpression = "at(" + scheduledTime.format(formatter) + ")";
        return eventbridgeActions.createScheduleAsync(
            oneTimeScheduleName,
            scheduleExpression,
            scheduleGroupName,
            snsTopicArn,
            roleArn,
            "One time scheduled event test from schedule",
            true,
            true).join();
    }


    /**
     * Creates a recurring schedule to send events based on a specific time.
     *
     * @return A {@link CompletableFuture} that completes with a boolean value indicating the success or failure of the operation.
     */
    public static Boolean createRecurringSchedule() {
        logger.info("Creating a recurring schedule to send events for one hour...");
        recurringScheduleName = promptUserForResourceName("Enter a name for the recurring schedule:");

        // Prompt the user for the schedule rate (in minutes).
        int scheduleRateInMinutes = promptUserForInteger("Enter the desired schedule rate (in minutes): ");
        String scheduleExpression = "rate(" + scheduleRateInMinutes + " minutes)";
        return eventbridgeActions.createScheduleAsync(
            recurringScheduleName,
            scheduleExpression,
            scheduleGroupName,
            snsTopicArn,
            roleArn,
            "Recurrent event test from schedule " + recurringScheduleName,
            true,
            true).join();
    }

    /**
     * Prompts the user for a resource name and validates the input.
     *
     * @param prompt the message to display to the user when prompting for the resource name
     * @return the valid resource name entered by the user
     */
    private static String promptUserForResourceName(String prompt) {
        logger.info(prompt);
        String resourceName = scanner.nextLine();
        String regex = "[0-9a-zA-Z-_.]+";
        if (!resourceName.matches(regex)) {
            logger.info("Invalid resource name. Please use a name that matches the pattern " + regex + ".");
            return promptUserForResourceName(prompt);
        }
        return resourceName;
    }

    /**
     * Prompts the user for an integer input and returns the integer value.
     *
     * @param prompt the message to be displayed to the user when prompting for input
     * @return the integer value entered by the user
     */
    private static int promptUserForInteger(String prompt) {
        logger.info(prompt);
        String stringResponse = scanner.nextLine();
        if (stringResponse == null || stringResponse.trim().isEmpty() || !isInteger(stringResponse)) {
            logger.info("Invalid integer.");
            return promptUserForInteger(prompt);
        }
        return Integer.parseInt(stringResponse);
    }

    /**
     * Checks if the given string represents a valid integer.
     *
     * @param str the string to be checked
     * @return {@code true} if the string represents a valid integer, {@code false} otherwise
     */
    private static boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
}
```
サービスオペレーション用のラッパー  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.scheduler.SchedulerAsyncClient;
import software.amazon.awssdk.services.scheduler.model.ActionAfterCompletion;
import software.amazon.awssdk.services.scheduler.model.ConflictException;
import software.amazon.awssdk.services.scheduler.model.CreateScheduleGroupRequest;
import software.amazon.awssdk.services.scheduler.model.CreateScheduleGroupResponse;
import software.amazon.awssdk.services.scheduler.model.CreateScheduleRequest;
import software.amazon.awssdk.services.scheduler.model.DeleteScheduleGroupRequest;
import software.amazon.awssdk.services.scheduler.model.DeleteScheduleRequest;
import software.amazon.awssdk.services.scheduler.model.DeleteScheduleResponse;
import software.amazon.awssdk.services.scheduler.model.FlexibleTimeWindow;
import software.amazon.awssdk.services.scheduler.model.FlexibleTimeWindowMode;
import software.amazon.awssdk.services.scheduler.model.ResourceNotFoundException;
import software.amazon.awssdk.services.scheduler.model.Target;

import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import java.time.Duration;
import java.util.concurrent.CompletionException;

public class EventbridgeSchedulerActions {

    private static SchedulerAsyncClient schedulerClient;
    private static final Logger logger = LoggerFactory.getLogger(EventbridgeSchedulerActions.class);

    public static SchedulerAsyncClient getAsyncClient() {
        if (schedulerClient == null) {
            /*
            The `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java, version 2,
            and it is designed to provide a high-performance, asynchronous HTTP client for interacting with AWS services.
             It uses the Netty framework to handle the underlying network communication and the Java NIO API to
             provide a non-blocking, event-driven approach to HTTP requests and responses.
             */

            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(50)  // Adjust as needed.
                .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
                .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
                .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
                .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
                .retryStrategy(RetryMode.STANDARD)
                .build();

            schedulerClient = SchedulerAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return schedulerClient;
    }


    /**
     * Creates a new schedule group.
     *
     * @param name the name of the schedule group to be created
     * @return a {@link CompletableFuture} representing the asynchronous operation of creating the schedule group
     */
    public CompletableFuture<CreateScheduleGroupResponse> createScheduleGroup(String name) {
        CreateScheduleGroupRequest request = CreateScheduleGroupRequest.builder()
            .name(name)
            .build();

        logger.info("Initiating createScheduleGroup call for group: {}", name);
        CompletableFuture<CreateScheduleGroupResponse> futureResponse = getAsyncClient().createScheduleGroup(request);
        futureResponse.whenComplete((response, ex) -> {
            if (ex != null) {
                if (ex instanceof CompletionException && ex.getCause() instanceof ConflictException) {
                    // Rethrow the ConflictException
                    throw (ConflictException) ex.getCause();
                } else {
                    throw new CompletionException("Failed to create schedule group: " + name, ex);
                }
            } else if (response == null) {
                throw new RuntimeException("Failed to create schedule group: response was null");
            } else {
                logger.info("Successfully created schedule group '{}': {}", name, response.scheduleGroupArn());
            }
        });

        return futureResponse;
    }


    /**
     * Creates a new schedule for a target task.
     *
     * @param name                  the name of the schedule
     * @param scheduleExpression    The schedule expression that defines when the schedule should run.
     * @param scheduleGroupName     the name of the schedule group to which the schedule belongs
     * @param targetArn             the Amazon Resource Name (ARN) of the target task
     * @param roleArn               the ARN of the IAM role to be used for the schedule
     * @param input                 the input data for the target task
     * @param deleteAfterCompletion whether to delete the schedule after it's executed
     * @param useFlexibleTimeWindow whether to use a flexible time window for the schedule execution
     * @return true if the schedule was successfully created, false otherwise
     */
    public CompletableFuture<Boolean> createScheduleAsync(
        String name,
        String scheduleExpression,
        String scheduleGroupName,
        String targetArn,
        String roleArn,
        String input,
        boolean deleteAfterCompletion,
        boolean useFlexibleTimeWindow) {

        int hoursToRun = 1;
        int flexibleTimeWindowMinutes = 10;

        Target target = Target.builder()
            .arn(targetArn)
            .roleArn(roleArn)
            .input(input)
            .build();

        FlexibleTimeWindow flexibleTimeWindow = FlexibleTimeWindow.builder()
            .mode(useFlexibleTimeWindow
                ? FlexibleTimeWindowMode.FLEXIBLE
                : FlexibleTimeWindowMode.OFF)
            .maximumWindowInMinutes(useFlexibleTimeWindow
                ? flexibleTimeWindowMinutes
                : null)
            .build();

        Instant startDate = Instant.now();
        Instant endDate = startDate.plus(Duration.ofHours(hoursToRun));

        CreateScheduleRequest request = CreateScheduleRequest.builder()
            .name(name)
            .scheduleExpression(scheduleExpression)
            .groupName(scheduleGroupName)
            .target(target)
            .actionAfterCompletion(deleteAfterCompletion
                ? ActionAfterCompletion.DELETE
                : ActionAfterCompletion.NONE)
            .startDate(startDate)
            .endDate(endDate)
            .flexibleTimeWindow(flexibleTimeWindow)
            .build();

        return getAsyncClient().createSchedule(request)
            .thenApply(response -> {
                logger.info("Successfully created schedule {} in schedule group {}, The ARN is {} ", name, scheduleGroupName, response.scheduleArn());
                return true;
            })
            .whenComplete((result, ex) -> {
                if (ex != null) {
                    if (ex instanceof ConflictException) {
                        // Handle ConflictException
                        logger.error("A conflict exception occurred while creating the schedule: {}", ex.getMessage());
                        throw new CompletionException("A conflict exception occurred while creating the schedule: " + ex.getMessage(), ex);
                    } else {
                        throw new CompletionException("Error creating schedule: " + ex.getMessage(), ex);
                    }
                }
            });
    }


    /**
     * Deletes the specified schedule group.
     *
     * @param name the name of the schedule group to delete
     * @return a {@link CompletableFuture} that completes when the schedule group has been deleted
     * @throws CompletionException if an error occurs while deleting the schedule group
     */
    public CompletableFuture<Void> deleteScheduleGroupAsync(String name) {
        DeleteScheduleGroupRequest request = DeleteScheduleGroupRequest.builder()
            .name(name)
            .build();

        return getAsyncClient().deleteScheduleGroup(request)
            .thenRun(() -> {
                logger.info("Successfully deleted schedule group {}", name);
            })
            .whenComplete((result, ex) -> {
                if (ex != null) {
                    if (ex instanceof ResourceNotFoundException) {
                        throw new CompletionException("The resource was not found: " + ex.getMessage(), ex);
                    } else {
                        throw new CompletionException("Error deleting schedule group: " + ex.getMessage(), ex);
                    }
                }
            });
    }


    /**
     * Deletes a schedule with the specified name and group name.
     *
     * @param name      the name of the schedule to be deleted
     * @param groupName the group name of the schedule to be deleted
     * @return a {@link CompletableFuture} that, when completed, indicates whether the schedule was successfully deleted
     * @throws CompletionException if an error occurs while deleting the schedule, except for the case where the schedule is not found
     */
    public CompletableFuture<Boolean> deleteScheduleAsync(String name, String groupName) {
        DeleteScheduleRequest request = DeleteScheduleRequest.builder()
            .name(name)
            .groupName(groupName)
            .build();

        CompletableFuture<DeleteScheduleResponse> response = getAsyncClient().deleteSchedule(request);
        return response.handle((result, ex) -> {
            if (ex != null) {
                if (ex instanceof ResourceNotFoundException) {
                    throw new CompletionException("Resource not found while deleting schedule with ID: " + name, ex);
                } else {
                    throw new CompletionException("Failed to delete schedule.", ex);
                }
            }
            logger.info("Successfully deleted schedule with name {}.", name);
            return true;
        });
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateSchedule](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/CreateSchedule)
  + [CreateScheduleGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/CreateScheduleGroup)
  + [DeleteSchedule](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/DeleteSchedule)
  + [DeleteScheduleGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/scheduler-2021-06-30/DeleteScheduleGroups)

# SDK for Java 2.x を使用した Forecast の例
<a name="java_2_forecast_code_examples"></a>

次のコード例は、Forecast AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDataset`
<a name="forecast_CreateDataset_java_2_topic"></a>

次のコード例は、`CreateDataset` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/forecast#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.forecast.ForecastClient;
import software.amazon.awssdk.services.forecast.model.CreateDatasetRequest;
import software.amazon.awssdk.services.forecast.model.Schema;
import software.amazon.awssdk.services.forecast.model.SchemaAttribute;
import software.amazon.awssdk.services.forecast.model.CreateDatasetResponse;
import software.amazon.awssdk.services.forecast.model.ForecastException;
import java.util.ArrayList;
import java.util.List;

/**
 * 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 CreateDataSet {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <name>\s

                Where:
                    name - The name of the data set.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String name = args[0];
        Region region = Region.US_WEST_2;
        ForecastClient forecast = ForecastClient.builder()
                .region(region)
                .build();

        String myDataSetARN = createForecastDataSet(forecast, name);
        System.out.println("The ARN of the new data set is " + myDataSetARN);
        forecast.close();
    }

    public static String createForecastDataSet(ForecastClient forecast, String name) {
        try {
            Schema schema = Schema.builder()
                    .attributes(getSchema())
                    .build();

            CreateDatasetRequest datasetRequest = CreateDatasetRequest.builder()
                    .datasetName(name)
                    .domain("CUSTOM")
                    .datasetType("RELATED_TIME_SERIES")
                    .dataFrequency("D")
                    .schema(schema)
                    .build();

            CreateDatasetResponse response = forecast.createDataset(datasetRequest);
            return response.datasetArn();

        } catch (ForecastException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return "";
    }

    // Create a SchemaAttribute list required to create a data set.
    private static List<SchemaAttribute> getSchema() {

        List<SchemaAttribute> schemaList = new ArrayList<>();
        SchemaAttribute att1 = SchemaAttribute.builder()
                .attributeName("item_id")
                .attributeType("string")
                .build();

        SchemaAttribute att2 = SchemaAttribute.builder()
                .attributeName("timestamp")
                .attributeType("timestamp")
                .build();

        SchemaAttribute att3 = SchemaAttribute.builder()
                .attributeName("target_value")
                .attributeType("float")
                .build();

        // Push the SchemaAttribute objects to the List.
        schemaList.add(att1);
        schemaList.add(att2);
        schemaList.add(att3);
        return schemaList;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDataset](https://docs.aws.amazon.com/goto/SdkForJavaV2/forecast-2018-06-26/CreateDataset)」を参照してください。

### `CreateForecast`
<a name="forecast_CreateForecast_java_2_topic"></a>

次のコード例は、`CreateForecast` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/forecast#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.forecast.ForecastClient;
import software.amazon.awssdk.services.forecast.model.CreateForecastRequest;
import software.amazon.awssdk.services.forecast.model.CreateForecastResponse;
import software.amazon.awssdk.services.forecast.model.ForecastException;

/**
 * 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 CreateForecast {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <name> <predictorArn>\s

                Where:
                    name - The name of the forecast.\s
                    predictorArn - The arn of the predictor to use.\s

                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String name = args[0];
        String predictorArn = args[1];
        Region region = Region.US_WEST_2;
        ForecastClient forecast = ForecastClient.builder()
                .region(region)
                .build();

        String forecastArn = createNewForecast(forecast, name, predictorArn);
        System.out.println("The ARN of the new forecast is " + forecastArn);
        forecast.close();
    }

    public static String createNewForecast(ForecastClient forecast, String name, String predictorArn) {
        try {
            CreateForecastRequest forecastRequest = CreateForecastRequest.builder()
                    .forecastName(name)
                    .predictorArn(predictorArn)
                    .build();

            CreateForecastResponse response = forecast.createForecast(forecastRequest);
            return response.forecastArn();

        } catch (ForecastException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateForecast](https://docs.aws.amazon.com/goto/SdkForJavaV2/forecast-2018-06-26/CreateForecast)」を参照してください。

### `DeleteDataset`
<a name="forecast_DeleteDataset_java_2_topic"></a>

次のコード例は、`DeleteDataset` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/forecast#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.forecast.ForecastClient;
import software.amazon.awssdk.services.forecast.model.DeleteDatasetRequest;
import software.amazon.awssdk.services.forecast.model.ForecastException;

/**
 * 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 DeleteDataset {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <datasetARN>\s

                Where:
                    datasetARN - The ARN of the data set to delete.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String datasetARN = args[0];
        Region region = Region.US_WEST_2;
        ForecastClient forecast = ForecastClient.builder()
                .region(region)
                .build();

        deleteForecastDataSet(forecast, datasetARN);
        forecast.close();
    }

    public static void deleteForecastDataSet(ForecastClient forecast, String myDataSetARN) {
        try {
            DeleteDatasetRequest deleteRequest = DeleteDatasetRequest.builder()
                    .datasetArn(myDataSetARN)
                    .build();

            forecast.deleteDataset(deleteRequest);
            System.out.println("The Data Set was deleted");

        } catch (ForecastException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteDataset](https://docs.aws.amazon.com/goto/SdkForJavaV2/forecast-2018-06-26/DeleteDataset)」を参照してください。

### `DeleteForecast`
<a name="forecast_DeleteForecast_java_2_topic"></a>

次のコード例は、`DeleteForecast` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/forecast#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.forecast.ForecastClient;
import software.amazon.awssdk.services.forecast.model.DeleteDatasetRequest;
import software.amazon.awssdk.services.forecast.model.ForecastException;

/**
 * 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 DeleteDataset {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <datasetARN>\s

                Where:
                    datasetARN - The ARN of the data set to delete.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String datasetARN = args[0];
        Region region = Region.US_WEST_2;
        ForecastClient forecast = ForecastClient.builder()
                .region(region)
                .build();

        deleteForecastDataSet(forecast, datasetARN);
        forecast.close();
    }

    public static void deleteForecastDataSet(ForecastClient forecast, String myDataSetARN) {
        try {
            DeleteDatasetRequest deleteRequest = DeleteDatasetRequest.builder()
                    .datasetArn(myDataSetARN)
                    .build();

            forecast.deleteDataset(deleteRequest);
            System.out.println("The Data Set was deleted");

        } catch (ForecastException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteForecast](https://docs.aws.amazon.com/goto/SdkForJavaV2/forecast-2018-06-26/DeleteForecast)」を参照してください。

### `DescribeForecast`
<a name="forecast_DescribeForecast_java_2_topic"></a>

次のコード例は、`DescribeForecast` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/forecast#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.forecast.ForecastClient;
import software.amazon.awssdk.services.forecast.model.DescribeForecastRequest;
import software.amazon.awssdk.services.forecast.model.DescribeForecastResponse;
import software.amazon.awssdk.services.forecast.model.ForecastException;

/**
 * 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 DescribeForecast {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <forecastarn>\s

                Where:
                    forecastarn - The arn of the forecast (for example, "arn:aws:forecast:us-west-2:xxxxx322:forecast/my_forecast)
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String forecastarn = args[0];
        Region region = Region.US_WEST_2;
        ForecastClient forecast = ForecastClient.builder()
                .region(region)
                .build();

        describe(forecast, forecastarn);
        forecast.close();
    }

    public static void describe(ForecastClient forecast, String forecastarn) {
        try {
            DescribeForecastRequest request = DescribeForecastRequest.builder()
                    .forecastArn(forecastarn)
                    .build();

            DescribeForecastResponse response = forecast.describeForecast(request);
            System.out.println("The name of the forecast is " + response.forecastName());

        } catch (ForecastException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeForecast](https://docs.aws.amazon.com/goto/SdkForJavaV2/forecast-2018-06-26/DescribeForecast)」を参照してください。

### `ListDatasetGroups`
<a name="forecast_ListDatasetGroups_java_2_topic"></a>

次のコード例は、`ListDatasetGroups` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/forecast#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.forecast.ForecastClient;
import software.amazon.awssdk.services.forecast.model.DatasetGroupSummary;
import software.amazon.awssdk.services.forecast.model.ListDatasetGroupsRequest;
import software.amazon.awssdk.services.forecast.model.ListDatasetGroupsResponse;
import software.amazon.awssdk.services.forecast.model.ForecastException;
import java.util.List;

/**
 * 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 ListDataSetGroups {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        ForecastClient forecast = ForecastClient.builder()
                .region(region)
                .build();

        listDataGroups(forecast);
        forecast.close();
    }

    public static void listDataGroups(ForecastClient forecast) {
        try {
            ListDatasetGroupsRequest group = ListDatasetGroupsRequest.builder()
                    .maxResults(10)
                    .build();

            ListDatasetGroupsResponse response = forecast.listDatasetGroups(group);
            List<DatasetGroupSummary> groups = response.datasetGroups();
            for (DatasetGroupSummary myGroup : groups) {
                System.out.println("The Data Set name is " + myGroup.datasetGroupName());
            }

        } catch (ForecastException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListDatasetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/forecast-2018-06-26/ListDatasetGroups)」を参照してください。

### `ListForecasts`
<a name="forecast_ListForecasts_java_2_topic"></a>

次のコード例は、`ListForecasts` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/forecast#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.forecast.ForecastClient;
import software.amazon.awssdk.services.forecast.model.ListForecastsResponse;
import software.amazon.awssdk.services.forecast.model.ListForecastsRequest;
import software.amazon.awssdk.services.forecast.model.ForecastSummary;
import software.amazon.awssdk.services.forecast.model.ForecastException;
import java.util.List;

/**
 * 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 ListForecasts {

    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        ForecastClient forecast = ForecastClient.builder()
                .region(region)
                .build();

        listAllForeCasts(forecast);
        forecast.close();
    }

    public static void listAllForeCasts(ForecastClient forecast) {
        try {
            ListForecastsRequest request = ListForecastsRequest.builder()
                    .maxResults(10)
                    .build();

            ListForecastsResponse response = forecast.listForecasts(request);
            List<ForecastSummary> forecasts = response.forecasts();
            for (ForecastSummary forecastSummary : forecasts) {
                System.out.println("The name of the forecast is " + forecastSummary.forecastName());
            }

        } catch (ForecastException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListForecasts](https://docs.aws.amazon.com/goto/SdkForJavaV2/forecast-2018-06-26/ListForecasts)」を参照してください。

# SDK for Java 2.x を使用する Amazon Glacier の例
<a name="java_2_glacier_code_examples"></a>

次のコード例は、Amazon Glacier AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateVault`
<a name="glacier_CreateVault_java_2_topic"></a>

次のコード例は、`CreateVault` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glacier.GlacierClient;
import software.amazon.awssdk.services.glacier.model.CreateVaultRequest;
import software.amazon.awssdk.services.glacier.model.CreateVaultResponse;
import software.amazon.awssdk.services.glacier.model.GlacierException;

/**
 * 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 CreateVault {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <vaultName>

                Where:
                   vaultName - The name of the vault to create.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String vaultName = args[0];
        GlacierClient glacier = GlacierClient.builder()
                .region(Region.US_EAST_1)
                .build();

        createGlacierVault(glacier, vaultName);
        glacier.close();
    }

    public static void createGlacierVault(GlacierClient glacier, String vaultName) {
        try {
            CreateVaultRequest vaultRequest = CreateVaultRequest.builder()
                    .vaultName(vaultName)
                    .build();

            CreateVaultResponse createVaultResult = glacier.createVault(vaultRequest);
            System.out.println("The URI of the new vault is " + createVaultResult.location());

        } catch (GlacierException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateVault](https://docs.aws.amazon.com/goto/SdkForJavaV2/glacier-2012-06-01/CreateVault)」を参照してください。

### `DeleteArchive`
<a name="glacier_DeleteArchive_java_2_topic"></a>

次のコード例は、`DeleteArchive` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glacier.GlacierClient;
import software.amazon.awssdk.services.glacier.model.DeleteArchiveRequest;
import software.amazon.awssdk.services.glacier.model.GlacierException;

/**
 * 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 DeleteArchive {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <vaultName> <accountId> <archiveId>

                Where:
                   vaultName - The name of the vault that contains the archive to delete.
                   accountId - The account ID value.
                   archiveId - The archive ID value.
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String vaultName = args[0];
        String accountId = args[1];
        String archiveId = args[2];
        GlacierClient glacier = GlacierClient.builder()
                .region(Region.US_EAST_1)
                .build();

        deleteGlacierArchive(glacier, vaultName, accountId, archiveId);
        glacier.close();
    }

    public static void deleteGlacierArchive(GlacierClient glacier, String vaultName, String accountId,
            String archiveId) {
        try {
            DeleteArchiveRequest delArcRequest = DeleteArchiveRequest.builder()
                    .vaultName(vaultName)
                    .accountId(accountId)
                    .archiveId(archiveId)
                    .build();

            glacier.deleteArchive(delArcRequest);
            System.out.println("The archive was deleted.");

        } catch (GlacierException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteArchive](https://docs.aws.amazon.com/goto/SdkForJavaV2/glacier-2012-06-01/DeleteArchive)」を参照してください。

### `DeleteVault`
<a name="glacier_DeleteVault_java_2_topic"></a>

次のコード例は、`DeleteVault` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glacier.GlacierClient;
import software.amazon.awssdk.services.glacier.model.DeleteVaultRequest;
import software.amazon.awssdk.services.glacier.model.GlacierException;

/**
 * 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 DeleteVault {
    public static void main(String[] args) {

        final String usage = """

                Usage:    <vaultName>

                Where:
                   vaultName - The name of the vault to delete.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String vaultName = args[0];
        GlacierClient glacier = GlacierClient.builder()
                .region(Region.US_EAST_1)
                .build();

        deleteGlacierVault(glacier, vaultName);
        glacier.close();
    }

    public static void deleteGlacierVault(GlacierClient glacier, String vaultName) {
        try {
            DeleteVaultRequest delVaultRequest = DeleteVaultRequest.builder()
                    .vaultName(vaultName)
                    .build();

            glacier.deleteVault(delVaultRequest);
            System.out.println("The vault was deleted!");

        } catch (GlacierException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteVault](https://docs.aws.amazon.com/goto/SdkForJavaV2/glacier-2012-06-01/DeleteVault)」を参照してください。

### `InitiateJob`
<a name="glacier_InitiateJob_java_2_topic"></a>

次のコード例は、`InitiateJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glacier#code-examples)での設定と実行の方法を確認してください。
ボールトインベントリを取得します。  

```
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glacier.GlacierClient;
import software.amazon.awssdk.services.glacier.model.JobParameters;
import software.amazon.awssdk.services.glacier.model.InitiateJobResponse;
import software.amazon.awssdk.services.glacier.model.GlacierException;
import software.amazon.awssdk.services.glacier.model.InitiateJobRequest;
import software.amazon.awssdk.services.glacier.model.DescribeJobRequest;
import software.amazon.awssdk.services.glacier.model.DescribeJobResponse;
import software.amazon.awssdk.services.glacier.model.GetJobOutputRequest;
import software.amazon.awssdk.services.glacier.model.GetJobOutputResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 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 ArchiveDownload {
    public static void main(String[] args) {

        final String usage = """

                Usage:    <vaultName> <accountId> <path>

                Where:
                   vaultName - The name of the vault.
                   accountId - The account ID value.
                   path - The path where the file is written to.
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String vaultName = args[0];
        String accountId = args[1];
        String path = args[2];
        GlacierClient glacier = GlacierClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String jobNum = createJob(glacier, vaultName, accountId);
        checkJob(glacier, jobNum, vaultName, accountId, path);
        glacier.close();
    }

    public static String createJob(GlacierClient glacier, String vaultName, String accountId) {
        try {
            JobParameters job = JobParameters.builder()
                    .type("inventory-retrieval")
                    .build();

            InitiateJobRequest initJob = InitiateJobRequest.builder()
                    .jobParameters(job)
                    .accountId(accountId)
                    .vaultName(vaultName)
                    .build();

            InitiateJobResponse response = glacier.initiateJob(initJob);
            System.out.println("The job ID is: " + response.jobId());
            System.out.println("The relative URI path of the job is: " + response.location());
            return response.jobId();

        } catch (GlacierException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);

        }
        return "";
    }

    // Poll S3 Glacier = Polling a Job may take 4-6 hours according to the
    // Documentation.
    public static void checkJob(GlacierClient glacier, String jobId, String name, String account, String path) {
        try {
            boolean finished = false;
            String jobStatus;
            int yy = 0;

            while (!finished) {
                DescribeJobRequest jobRequest = DescribeJobRequest.builder()
                        .jobId(jobId)
                        .accountId(account)
                        .vaultName(name)
                        .build();

                DescribeJobResponse response = glacier.describeJob(jobRequest);
                jobStatus = response.statusCodeAsString();

                if (jobStatus.compareTo("Succeeded") == 0)
                    finished = true;
                else {
                    System.out.println(yy + " status is: " + jobStatus);
                    Thread.sleep(1000);
                }
                yy++;
            }

            System.out.println("Job has Succeeded");
            GetJobOutputRequest jobOutputRequest = GetJobOutputRequest.builder()
                    .jobId(jobId)
                    .vaultName(name)
                    .accountId(account)
                    .build();

            ResponseBytes<GetJobOutputResponse> objectBytes = glacier.getJobOutputAsBytes(jobOutputRequest);
            // Write the data to a local file.
            byte[] data = objectBytes.asByteArray();
            File myFile = new File(path);
            OutputStream os = new FileOutputStream(myFile);
            os.write(data);
            System.out.println("Successfully obtained bytes from a Glacier vault");
            os.close();

        } catch (GlacierException | InterruptedException | IOException e) {
            System.out.println(e.getMessage());
            System.exit(1);

        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[InitiateJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/glacier-2012-06-01/InitiateJob)」を参照してください。

### `ListVaults`
<a name="glacier_ListVaults_java_2_topic"></a>

次のコード例は、`ListVaults` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glacier.model.ListVaultsRequest;
import software.amazon.awssdk.services.glacier.model.ListVaultsResponse;
import software.amazon.awssdk.services.glacier.GlacierClient;
import software.amazon.awssdk.services.glacier.model.DescribeVaultOutput;
import software.amazon.awssdk.services.glacier.model.GlacierException;
import java.util.List;

/**
 * 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 ListVaults {
    public static void main(String[] args) {
        GlacierClient glacier = GlacierClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listAllVault(glacier);
        glacier.close();
    }

    public static void listAllVault(GlacierClient glacier) {
        boolean listComplete = false;
        String newMarker = null;
        int totalVaults = 0;
        System.out.println("Your Amazon Glacier vaults:");
        try {
            while (!listComplete) {
                ListVaultsResponse response = null;
                if (newMarker != null) {
                    ListVaultsRequest request = ListVaultsRequest.builder()
                            .marker(newMarker)
                            .build();

                    response = glacier.listVaults(request);
                } else {
                    ListVaultsRequest request = ListVaultsRequest.builder()
                            .build();
                    response = glacier.listVaults(request);
                }

                List<DescribeVaultOutput> vaultList = response.vaultList();
                for (DescribeVaultOutput v : vaultList) {
                    totalVaults += 1;
                    System.out.println("* " + v.vaultName());
                }

                // Check for further results.
                newMarker = response.marker();
                if (newMarker == null) {
                    listComplete = true;
                }
            }

            if (totalVaults == 0) {
                System.out.println("No vaults found.");
            }

        } catch (GlacierException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListVaults](https://docs.aws.amazon.com/goto/SdkForJavaV2/glacier-2012-06-01/ListVaults)」を参照してください。

### `UploadArchive`
<a name="glacier_UploadArchive_java_2_topic"></a>

次のコード例は、`UploadArchive` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glacier.GlacierClient;
import software.amazon.awssdk.services.glacier.model.UploadArchiveRequest;
import software.amazon.awssdk.services.glacier.model.UploadArchiveResponse;
import software.amazon.awssdk.services.glacier.model.GlacierException;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 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 UploadArchive {

    static final int ONE_MB = 1024 * 1024;

    public static void main(String[] args) {
        final String usage = """

                Usage:   <strPath> <vaultName>\s

                Where:
                   strPath - The path to the archive to upload (for example, C:\\AWS\\test.pdf).
                   vaultName - The name of the vault.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String strPath = args[0];
        String vaultName = args[1];
        File myFile = new File(strPath);
        Path path = Paths.get(strPath);
        GlacierClient glacier = GlacierClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String archiveId = uploadContent(glacier, path, vaultName, myFile);
        System.out.println("The ID of the archived item is " + archiveId);
        glacier.close();
    }

    public static String uploadContent(GlacierClient glacier, Path path, String vaultName, File myFile) {
        // Get an SHA-256 tree hash value.
        String checkVal = computeSHA256(myFile);
        try {
            UploadArchiveRequest uploadRequest = UploadArchiveRequest.builder()
                    .vaultName(vaultName)
                    .checksum(checkVal)
                    .build();

            UploadArchiveResponse res = glacier.uploadArchive(uploadRequest, path);
            return res.archiveId();

        } catch (GlacierException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    private static String computeSHA256(File inputFile) {
        try {
            byte[] treeHash = computeSHA256TreeHash(inputFile);
            System.out.printf("SHA-256 tree hash = %s\n", toHex(treeHash));
            return toHex(treeHash);

        } catch (IOException ioe) {
            System.err.format("Exception when reading from file %s: %s", inputFile, ioe.getMessage());
            System.exit(-1);

        } catch (NoSuchAlgorithmException nsae) {
            System.err.format("Cannot locate MessageDigest algorithm for SHA-256: %s", nsae.getMessage());
            System.exit(-1);
        }
        return "";
    }

    public static byte[] computeSHA256TreeHash(File inputFile) throws IOException,
            NoSuchAlgorithmException {

        byte[][] chunkSHA256Hashes = getChunkSHA256Hashes(inputFile);
        return computeSHA256TreeHash(chunkSHA256Hashes);
    }

    /**
     * Computes an SHA256 checksum for each 1 MB chunk of the input file. This
     * includes the checksum for the last chunk, even if it's smaller than 1 MB.
     */
    public static byte[][] getChunkSHA256Hashes(File file) throws IOException,
            NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        long numChunks = file.length() / ONE_MB;
        if (file.length() % ONE_MB > 0) {
            numChunks++;
        }

        if (numChunks == 0) {
            return new byte[][] { md.digest() };
        }

        byte[][] chunkSHA256Hashes = new byte[(int) numChunks][];
        FileInputStream fileStream = null;

        try {
            fileStream = new FileInputStream(file);
            byte[] buff = new byte[ONE_MB];

            int bytesRead;
            int idx = 0;

            while ((bytesRead = fileStream.read(buff, 0, ONE_MB)) > 0) {
                md.reset();
                md.update(buff, 0, bytesRead);
                chunkSHA256Hashes[idx++] = md.digest();
            }

            return chunkSHA256Hashes;

        } finally {
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (IOException ioe) {
                    System.err.printf("Exception while closing %s.\n %s", file.getName(),
                            ioe.getMessage());
                }
            }
        }
    }

    /**
     * Computes the SHA-256 tree hash for the passed array of 1 MB chunk
     * checksums.
     */
    public static byte[] computeSHA256TreeHash(byte[][] chunkSHA256Hashes)
            throws NoSuchAlgorithmException {

        MessageDigest md = MessageDigest.getInstance("SHA-256");
        byte[][] prevLvlHashes = chunkSHA256Hashes;
        while (prevLvlHashes.length > 1) {
            int len = prevLvlHashes.length / 2;
            if (prevLvlHashes.length % 2 != 0) {
                len++;
            }

            byte[][] currLvlHashes = new byte[len][];
            int j = 0;
            for (int i = 0; i < prevLvlHashes.length; i = i + 2, j++) {

                // If there are at least two elements remaining.
                if (prevLvlHashes.length - i > 1) {

                    // Calculate a digest of the concatenated nodes.
                    md.reset();
                    md.update(prevLvlHashes[i]);
                    md.update(prevLvlHashes[i + 1]);
                    currLvlHashes[j] = md.digest();

                } else { // Take care of the remaining odd chunk
                    currLvlHashes[j] = prevLvlHashes[i];
                }
            }

            prevLvlHashes = currLvlHashes;
        }

        return prevLvlHashes[0];
    }

    /**
     * Returns the hexadecimal representation of the input byte array
     */
    public static String toHex(byte[] data) {
        StringBuilder sb = new StringBuilder(data.length * 2);
        for (byte datum : data) {
            String hex = Integer.toHexString(datum & 0xFF);

            if (hex.length() == 1) {
                // Append leading zero.
                sb.append("0");
            }
            sb.append(hex);
        }
        return sb.toString().toLowerCase();
    }
}
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[UploadArchive](https://docs.aws.amazon.com/goto/SdkForJavaV2/glacier-2012-06-01/UploadArchive)」を参照してください。

# AWS Glue SDK for Java 2.x を使用した例
<a name="java_2_glue_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Glueは
<a name="glue_Hello_java_2_topic"></a>

次のコード例は、 AWS Glueの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
package com.example.glue;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.glue.GlueClient;
import software.amazon.awssdk.services.glue.model.ListJobsRequest;
import software.amazon.awssdk.services.glue.model.ListJobsResponse;
import java.util.List;

public class HelloGlue {
    public static void main(String[] args) {
        GlueClient glueClient = GlueClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listJobs(glueClient);
    }

    public static void listJobs(GlueClient glueClient) {
        ListJobsRequest request = ListJobsRequest.builder()
                .maxResults(10)
                .build();
        ListJobsResponse response = glueClient.listJobs(request);
        List<String> jobList = response.jobNames();
        jobList.forEach(job -> {
            System.out.println("Job Name: " + job);
        });
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/ListJobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 * To set up the resources, see this documentation topic:
 *
 * https://docs.aws.amazon.com/glue/latest/ug/tutorial-add-crawler.html
 *
 * This example performs the following tasks:
 *
 * 1. Create a database.
 * 2. Create a crawler.
 * 3. Get a crawler.
 * 4. Start a crawler.
 * 5. Get a database.
 * 6. Get tables.
 * 7. Create a job.
 * 8. Start a job run.
 * 9. List all jobs.
 * 10. Get job runs.
 * 11. Delete a job.
 * 12. Delete a database.
 * 13. Delete a crawler.
 */

public class GlueScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws InterruptedException {
        final String usage = """

            Usage:
                <iam> <s3Path> <cron> <dbName> <crawlerName> <jobName> <scriptLocation> <locationUri> <bucketNameSc>\s

            Where:
                iam - The ARN of the IAM role that has AWS Glue and S3 permissions.\s
                s3Path - The Amazon Simple Storage Service (Amazon S3) target that contains data (for example, s3://<bucket name>/read).
                cron - A cron expression used to specify the schedule  (i.e., cron(15 12 * * ? *).
                dbName - The database name.\s
                crawlerName - The name of the crawler.\s
                jobName - The name you assign to this job definition.
                scriptLocation - The Amazon S3 path to a script that runs a job.
                locationUri - The location of the database (you can find this file in resources folder).
                bucketNameSc - The Amazon S3 bucket name used when creating a job
                """;

        if (args.length != 9) {
            System.out.println(usage);
            return;
        }
        Scanner scanner = new Scanner(System.in);
        String iam = args[0];
        String s3Path = args[1];
        String cron = args[2];
        String dbName = args[3];
        String crawlerName = args[4];
        String jobName = args[5];
        String scriptLocation = args[6];
        String locationUri = args[7];
        String bucketNameSc = args[8];

        Region region = Region.US_EAST_1;
        GlueClient glueClient = GlueClient.builder()
            .region(region)
            .build();
        System.out.println(DASHES);
        System.out.println("Welcome to the AWS Glue scenario.");
        System.out.println("""
            AWS Glue is a fully managed extract, transform, and load (ETL) service provided by Amazon 
            Web Services (AWS). It is designed to simplify the process of building, running, and maintaining 
            ETL pipelines, which are essential for data integration and data warehousing tasks.
                        
            One of the key features of AWS Glue is its ability to automatically discover and catalog data 
            stored in various sources, such as Amazon S3, Amazon RDS, Amazon Redshift, and other databases. 
            This cataloging process creates a central metadata repository, known as the AWS Glue Data Catalog, 
            which provides a unified view of an organization's data assets. This metadata can then be used to 
            create ETL jobs, which can be scheduled and run on-demand or on a regular basis.
                        
            Lets get started.          
                         
            """);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Create a database.");
        try {
            createDatabase(glueClient, dbName, locationUri);
        } catch (GlueException e) {
            if (e.awsErrorDetails().errorMessage().equals("Database already exists.")) {
                System.out.println("Database " + dbName + " already exists. Skipping creation.");
            } else {
                System.err.println(e.awsErrorDetails().errorMessage());
                return;
            }
        }

        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Create a crawler.");
        try {
            createGlueCrawler(glueClient, iam, s3Path, cron, dbName, crawlerName);
        } catch (GlueException e) {
            if (e.awsErrorDetails().errorMessage().contains("already exists")) {
                System.out.println("Crawler " + crawlerName + " already exists. Skipping creation.");
            } else {
                System.err.println(e.awsErrorDetails().errorMessage());
                System.exit(1);
            }
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Get a crawler.");
        try {
            getSpecificCrawler(glueClient, crawlerName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Start a crawler.");
        try {
            startSpecificCrawler(glueClient, crawlerName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Get a database.");
        try {
            getSpecificDatabase(glueClient, dbName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("*** Wait 5 min for the tables to become available");
        TimeUnit.MINUTES.sleep(5);
        System.out.println("6. Get tables.");
        String myTableName;
        try {
            myTableName = getGlueTables(glueClient, dbName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Create a job.");
        try {
            createJob(glueClient, jobName, iam, scriptLocation);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Start a Job run.");
        try {
            startJob(glueClient, jobName, dbName, myTableName, bucketNameSc);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. List all jobs.");
        try {
            getAllJobs(glueClient);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Get job runs.");
        try {
            getJobRuns(glueClient, jobName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Delete a job.");
        try {
            deleteJob(glueClient, jobName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        System.out.println("*** Wait 5 MIN for the " + crawlerName + " to stop");
        TimeUnit.MINUTES.sleep(5);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("12. Delete a database.");
        try {
            deleteDatabase(glueClient, dbName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Delete a crawler.");
        try {
            deleteSpecificCrawler(glueClient, crawlerName);
        } catch (GlueException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Successfully completed the AWS Glue Scenario");
        System.out.println(DASHES);
    }


    /**
     * Creates a Glue database with the specified name and location URI.
     *
     * @param glueClient  The Glue client to use for the database creation.
     * @param dbName      The name of the database to create.
     * @param locationUri The location URI for the database.
     */
    public static void createDatabase(GlueClient glueClient, String dbName, String locationUri) {
        try {
            DatabaseInput input = DatabaseInput.builder()
                .description("Built with the AWS SDK for Java V2")
                .name(dbName)
                .locationUri(locationUri)
                .build();

            CreateDatabaseRequest request = CreateDatabaseRequest.builder()
                .databaseInput(input)
                .build();

            glueClient.createDatabase(request);
            System.out.println(dbName + " was successfully created");

        } catch (GlueException e) {
            throw e;
        }
    }


    /**
     * Creates a new AWS Glue crawler using the AWS Glue Java API.
     *
     * @param glueClient  the AWS Glue client used to interact with the AWS Glue service
     * @param iam         the IAM role that the crawler will use to access the data source
     * @param s3Path      the S3 path that the crawler will scan for data
     * @param cron        the cron expression that defines the crawler's schedule
     * @param dbName      the name of the AWS Glue database where the crawler will store the metadata
     * @param crawlerName the name of the crawler to be created
     */
    public static void createGlueCrawler(GlueClient glueClient,
                                         String iam,
                                         String s3Path,
                                         String cron,
                                         String dbName,
                                         String crawlerName) {

        try {
            S3Target s3Target = S3Target.builder()
                .path(s3Path)
                .build();

            List<S3Target> targetList = new ArrayList<>();
            targetList.add(s3Target);
            CrawlerTargets targets = CrawlerTargets.builder()
                .s3Targets(targetList)
                .build();

            CreateCrawlerRequest crawlerRequest = CreateCrawlerRequest.builder()
                .databaseName(dbName)
                .name(crawlerName)
                .description("Created by the AWS Glue Java API")
                .targets(targets)
                .role(iam)
                .schedule(cron)
                .build();

            glueClient.createCrawler(crawlerRequest);
            System.out.println(crawlerName + " was successfully created");

        } catch (GlueException e) {
            throw e;
        }
    }

    /**
     * Retrieves a specific crawler from the AWS Glue service and waits for it to be in the "READY" state.
     *
     * @param glueClient  the AWS Glue client used to interact with the Glue service
     * @param crawlerName the name of the crawler to be retrieved
     */
    public static void getSpecificCrawler(GlueClient glueClient, String crawlerName) throws InterruptedException {
        try {
            GetCrawlerRequest crawlerRequest = GetCrawlerRequest.builder()
                .name(crawlerName)
                .build();

            boolean ready = false;
            while (!ready) {
                GetCrawlerResponse response = glueClient.getCrawler(crawlerRequest);
                String status = response.crawler().stateAsString();
                if (status.compareTo("READY") == 0) {
                    ready = true;
                }
                Thread.sleep(3000);
            }

            System.out.println("The crawler is now ready");

        } catch (GlueException | InterruptedException e) {
            throw e;
        }
    }

    /**
     * Starts a specific AWS Glue crawler.
     *
     * @param glueClient  the AWS Glue client to use for the crawler operation
     * @param crawlerName the name of the crawler to start
     * @throws GlueException if there is an error starting the crawler
     */
    public static void startSpecificCrawler(GlueClient glueClient, String crawlerName) {
        try {
            StartCrawlerRequest crawlerRequest = StartCrawlerRequest.builder()
                .name(crawlerName)
                .build();

            glueClient.startCrawler(crawlerRequest);
            System.out.println(crawlerName + " was successfully started!");

        } catch (GlueException e) {
            throw e;
        }
    }

    /**
     * Retrieves the specific database from the AWS Glue service.
     *
     * @param glueClient   an instance of the AWS Glue client used to interact with the service
     * @param databaseName the name of the database to retrieve
     * @throws GlueException if there is an error retrieving the database from the AWS Glue service
     */
    public static void getSpecificDatabase(GlueClient glueClient, String databaseName) {
        try {
            GetDatabaseRequest databasesRequest = GetDatabaseRequest.builder()
                .name(databaseName)
                .build();

            GetDatabaseResponse response = glueClient.getDatabase(databasesRequest);
            Instant createDate = response.database().createTime();

            // Convert the Instant to readable date.
            DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
                .withLocale(Locale.US)
                .withZone(ZoneId.systemDefault());

            formatter.format(createDate);
            System.out.println("The create date of the database is " + createDate);

        } catch (GlueException e) {
            throw e;
        }
    }


    /**
     * Retrieves the names of the tables in the specified Glue database.
     *
     * @param glueClient the Glue client to use for the operation
     * @param dbName     the name of the Glue database to retrieve the table names from
     * @return the name of the first table retrieved, or an empty string if no tables were found
     */
    public static String getGlueTables(GlueClient glueClient, String dbName) {
        String myTableName = "";
        try {
            GetTablesRequest tableRequest = GetTablesRequest.builder()
                .databaseName(dbName)
                .build();

            GetTablesResponse response = glueClient.getTables(tableRequest);
            List<Table> tables = response.tableList();
            if (tables.isEmpty()) {
                System.out.println("No tables were returned");
            } else {
                for (Table table : tables) {
                    myTableName = table.name();
                    System.out.println("Table name is: " + myTableName);
                }
            }

        } catch (GlueException e) {
            throw e;
        }
        return myTableName;
    }


    /**
     * Starts a job run in AWS Glue.
     *
     * @param glueClient    the AWS Glue client to use for the job run
     * @param jobName       the name of the Glue job to run
     * @param inputDatabase the name of the input database
     * @param inputTable    the name of the input table
     * @param outBucket     the URL of the output S3 bucket
     * @throws GlueException if there is an error starting the job run
     */
    public static void startJob(GlueClient glueClient, String jobName, String inputDatabase, String inputTable,
                                String outBucket) {
        try {
            Map<String, String> myMap = new HashMap<>();
            myMap.put("--input_database", inputDatabase);
            myMap.put("--input_table", inputTable);
            myMap.put("--output_bucket_url", outBucket);

            StartJobRunRequest runRequest = StartJobRunRequest.builder()
                .workerType(WorkerType.G_1_X)
                .numberOfWorkers(10)
                .arguments(myMap)
                .jobName(jobName)
                .build();

            StartJobRunResponse response = glueClient.startJobRun(runRequest);
            System.out.println("The request Id of the job is " + response.responseMetadata().requestId());

        } catch (GlueException e) {
            throw e;
        }
    }


    /**
     * Creates a new AWS Glue job.
     *
     * @param glueClient     the AWS Glue client to use for the operation
     * @param jobName        the name of the job to create
     * @param iam            the IAM role to associate with the job
     * @param scriptLocation the location of the script to be used by the job
     * @throws GlueException if there is an error creating the job
     */
    public static void createJob(GlueClient glueClient, String jobName, String iam, String scriptLocation) {
        try {
            JobCommand command = JobCommand.builder()
                .pythonVersion("3")
                .name("glueetl")
                .scriptLocation(scriptLocation)
                .build();

            CreateJobRequest jobRequest = CreateJobRequest.builder()
                .description("A Job created by using the AWS SDK for Java V2")
                .glueVersion("2.0")
                .workerType(WorkerType.G_1_X)
                .numberOfWorkers(10)
                .name(jobName)
                .role(iam)
                .command(command)
                .build();

            glueClient.createJob(jobRequest);
            System.out.println(jobName + " was successfully created.");

        } catch (GlueException e) {
            throw e;
        }
    }


    /**
     * Retrieves and prints information about all the jobs in the Glue data catalog.
     *
     * @param glueClient the Glue client used to interact with the AWS Glue service
     */
    public static void getAllJobs(GlueClient glueClient) {
        try {
            GetJobsRequest jobsRequest = GetJobsRequest.builder()
                .maxResults(10)
                .build();

            GetJobsResponse jobsResponse = glueClient.getJobs(jobsRequest);
            List<Job> jobs = jobsResponse.jobs();
            for (Job job : jobs) {
                System.out.println("Job name is : " + job.name());
                System.out.println("The job worker type is : " + job.workerType().name());
            }

        } catch (GlueException e) {
            throw e;
        }
    }

    /**
     * Retrieves the job runs for a given Glue job and prints the status of the job runs.
     *
     * @param glueClient the Glue client used to make API calls
     * @param jobName    the name of the Glue job to retrieve the job runs for
     */
    public static void getJobRuns(GlueClient glueClient, String jobName) {
        try {
            GetJobRunsRequest runsRequest = GetJobRunsRequest.builder()
                .jobName(jobName)
                .maxResults(20)
                .build();

            boolean jobDone = false;
            while (!jobDone) {
                GetJobRunsResponse response = glueClient.getJobRuns(runsRequest);
                List<JobRun> jobRuns = response.jobRuns();
                for (JobRun jobRun : jobRuns) {
                    String jobState = jobRun.jobRunState().name();
                    if (jobState.compareTo("SUCCEEDED") == 0) {
                        System.out.println(jobName + " has succeeded");
                        jobDone = true;

                    } else if (jobState.compareTo("STOPPED") == 0) {
                        System.out.println("Job run has stopped");
                        jobDone = true;

                    } else if (jobState.compareTo("FAILED") == 0) {
                        System.out.println("Job run has failed");
                        jobDone = true;

                    } else if (jobState.compareTo("TIMEOUT") == 0) {
                        System.out.println("Job run has timed out");
                        jobDone = true;

                    } else {
                        System.out.println("*** Job run state is " + jobRun.jobRunState().name());
                        System.out.println("Job run Id is " + jobRun.id());
                        System.out.println("The Glue version is " + jobRun.glueVersion());
                    }
                    TimeUnit.SECONDS.sleep(5);
                }
            }

        } catch (GlueException e) {
            throw e;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * Deletes a Glue job.
     *
     * @param glueClient the Glue client to use for the operation
     * @param jobName    the name of the job to be deleted
     * @throws GlueException if there is an error deleting the job
     */
    public static void deleteJob(GlueClient glueClient, String jobName) {
        try {
            DeleteJobRequest jobRequest = DeleteJobRequest.builder()
                .jobName(jobName)
                .build();

            glueClient.deleteJob(jobRequest);
            System.out.println(jobName + " was successfully deleted");

        } catch (GlueException e) {
            throw e;
        }
    }

    /**
     * Deletes a AWS Glue Database.
     *
     * @param glueClient   An instance of the AWS Glue client used to interact with the AWS Glue service.
     * @param databaseName The name of the database to be deleted.
     * @throws GlueException If an error occurs while deleting the database.
     */
    public static void deleteDatabase(GlueClient glueClient, String databaseName) {
        try {
            DeleteDatabaseRequest request = DeleteDatabaseRequest.builder()
                .name(databaseName)
                .build();

            glueClient.deleteDatabase(request);
            System.out.println(databaseName + " was successfully deleted");

        } catch (GlueException e) {
            throw e;
        }
    }


    /**
     * Deletes a specific AWS Glue crawler.
     *
     * @param glueClient  the AWS Glue client object
     * @param crawlerName the name of the crawler to be deleted
     * @throws GlueException if an error occurs during the deletion process
     */
    public static void deleteSpecificCrawler(GlueClient glueClient, String crawlerName) {
        try {
            DeleteCrawlerRequest deleteCrawlerRequest = DeleteCrawlerRequest.builder()
                .name(crawlerName)
                .build();

            glueClient.deleteCrawler(deleteCrawlerRequest);
            System.out.println(crawlerName + " was deleted");

        } catch (GlueException e) {
            throw e;
        }
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println("");
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/CreateCrawler)
  + [CreateJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/CreateJob)
  + [DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/DeleteCrawler)
  + [DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/DeleteDatabase)
  + [DeleteJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/DeleteJob)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/DeleteTable)
  + [GetCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetCrawler)
  + [GetDatabase](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetDatabase)
  + [GetDatabases](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetDatabases)
  + [GetJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetJob)
  + [GetJobRun](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetJobRun)
  + [GetJobRuns](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetJobRuns)
  + [GetTables](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetTables)
  + [ListJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/ListJobs)
  + [StartCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/StartCrawler)
  + [StartJobRun](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/StartJobRun)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_java_2_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new AWS Glue crawler using the AWS Glue Java API.
     *
     * @param glueClient  the AWS Glue client used to interact with the AWS Glue service
     * @param iam         the IAM role that the crawler will use to access the data source
     * @param s3Path      the S3 path that the crawler will scan for data
     * @param cron        the cron expression that defines the crawler's schedule
     * @param dbName      the name of the AWS Glue database where the crawler will store the metadata
     * @param crawlerName the name of the crawler to be created
     */
    public static void createGlueCrawler(GlueClient glueClient,
                                         String iam,
                                         String s3Path,
                                         String cron,
                                         String dbName,
                                         String crawlerName) {

        try {
            S3Target s3Target = S3Target.builder()
                .path(s3Path)
                .build();

            List<S3Target> targetList = new ArrayList<>();
            targetList.add(s3Target);
            CrawlerTargets targets = CrawlerTargets.builder()
                .s3Targets(targetList)
                .build();

            CreateCrawlerRequest crawlerRequest = CreateCrawlerRequest.builder()
                .databaseName(dbName)
                .name(crawlerName)
                .description("Created by the AWS Glue Java API")
                .targets(targets)
                .role(iam)
                .schedule(cron)
                .build();

            glueClient.createCrawler(crawlerRequest);
            System.out.println(crawlerName + " was successfully created");

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[CreateCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/CreateCrawler)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_java_2_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new AWS Glue job.
     *
     * @param glueClient     the AWS Glue client to use for the operation
     * @param jobName        the name of the job to create
     * @param iam            the IAM role to associate with the job
     * @param scriptLocation the location of the script to be used by the job
     * @throws GlueException if there is an error creating the job
     */
    public static void createJob(GlueClient glueClient, String jobName, String iam, String scriptLocation) {
        try {
            JobCommand command = JobCommand.builder()
                .pythonVersion("3")
                .name("glueetl")
                .scriptLocation(scriptLocation)
                .build();

            CreateJobRequest jobRequest = CreateJobRequest.builder()
                .description("A Job created by using the AWS SDK for Java V2")
                .glueVersion("2.0")
                .workerType(WorkerType.G_1_X)
                .numberOfWorkers(10)
                .name(jobName)
                .role(iam)
                .command(command)
                .build();

            glueClient.createJob(jobRequest);
            System.out.println(jobName + " was successfully created.");

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CreateJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/CreateJob)」を参照してください。**

### `DeleteCrawler`
<a name="glue_DeleteCrawler_java_2_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a specific AWS Glue crawler.
     *
     * @param glueClient  the AWS Glue client object
     * @param crawlerName the name of the crawler to be deleted
     * @throws GlueException if an error occurs during the deletion process
     */
    public static void deleteSpecificCrawler(GlueClient glueClient, String crawlerName) {
        try {
            DeleteCrawlerRequest deleteCrawlerRequest = DeleteCrawlerRequest.builder()
                .name(crawlerName)
                .build();

            glueClient.deleteCrawler(deleteCrawlerRequest);
            System.out.println(crawlerName + " was deleted");

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/DeleteCrawler)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_java_2_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a AWS Glue Database.
     *
     * @param glueClient   An instance of the AWS Glue client used to interact with the AWS Glue service.
     * @param databaseName The name of the database to be deleted.
     * @throws GlueException If an error occurs while deleting the database.
     */
    public static void deleteDatabase(GlueClient glueClient, String databaseName) {
        try {
            DeleteDatabaseRequest request = DeleteDatabaseRequest.builder()
                .name(databaseName)
                .build();

            glueClient.deleteDatabase(request);
            System.out.println(databaseName + " was successfully deleted");

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/DeleteDatabase)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_java_2_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a Glue job.
     *
     * @param glueClient the Glue client to use for the operation
     * @param jobName    the name of the job to be deleted
     * @throws GlueException if there is an error deleting the job
     */
    public static void deleteJob(GlueClient glueClient, String jobName) {
        try {
            DeleteJobRequest jobRequest = DeleteJobRequest.builder()
                .jobName(jobName)
                .build();

            glueClient.deleteJob(jobRequest);
            System.out.println(jobName + " was successfully deleted");

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/DeleteJob)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_java_2_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves a specific crawler from the AWS Glue service and waits for it to be in the "READY" state.
     *
     * @param glueClient  the AWS Glue client used to interact with the Glue service
     * @param crawlerName the name of the crawler to be retrieved
     */
    public static void getSpecificCrawler(GlueClient glueClient, String crawlerName) throws InterruptedException {
        try {
            GetCrawlerRequest crawlerRequest = GetCrawlerRequest.builder()
                .name(crawlerName)
                .build();

            boolean ready = false;
            while (!ready) {
                GetCrawlerResponse response = glueClient.getCrawler(crawlerRequest);
                String status = response.crawler().stateAsString();
                if (status.compareTo("READY") == 0) {
                    ready = true;
                }
                Thread.sleep(3000);
            }

            System.out.println("The crawler is now ready");

        } catch (GlueException | InterruptedException e) {
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetCrawler)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_java_2_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the specific database from the AWS Glue service.
     *
     * @param glueClient   an instance of the AWS Glue client used to interact with the service
     * @param databaseName the name of the database to retrieve
     * @throws GlueException if there is an error retrieving the database from the AWS Glue service
     */
    public static void getSpecificDatabase(GlueClient glueClient, String databaseName) {
        try {
            GetDatabaseRequest databasesRequest = GetDatabaseRequest.builder()
                .name(databaseName)
                .build();

            GetDatabaseResponse response = glueClient.getDatabase(databasesRequest);
            Instant createDate = response.database().createTime();

            // Convert the Instant to readable date.
            DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
                .withLocale(Locale.US)
                .withZone(ZoneId.systemDefault());

            formatter.format(createDate);
            System.out.println("The create date of the database is " + createDate);

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetDatabase](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetDatabase)」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_java_2_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the job runs for a given Glue job and prints the status of the job runs.
     *
     * @param glueClient the Glue client used to make API calls
     * @param jobName    the name of the Glue job to retrieve the job runs for
     */
    public static void getJobRuns(GlueClient glueClient, String jobName) {
        try {
            GetJobRunsRequest runsRequest = GetJobRunsRequest.builder()
                .jobName(jobName)
                .maxResults(20)
                .build();

            boolean jobDone = false;
            while (!jobDone) {
                GetJobRunsResponse response = glueClient.getJobRuns(runsRequest);
                List<JobRun> jobRuns = response.jobRuns();
                for (JobRun jobRun : jobRuns) {
                    String jobState = jobRun.jobRunState().name();
                    if (jobState.compareTo("SUCCEEDED") == 0) {
                        System.out.println(jobName + " has succeeded");
                        jobDone = true;

                    } else if (jobState.compareTo("STOPPED") == 0) {
                        System.out.println("Job run has stopped");
                        jobDone = true;

                    } else if (jobState.compareTo("FAILED") == 0) {
                        System.out.println("Job run has failed");
                        jobDone = true;

                    } else if (jobState.compareTo("TIMEOUT") == 0) {
                        System.out.println("Job run has timed out");
                        jobDone = true;

                    } else {
                        System.out.println("*** Job run state is " + jobRun.jobRunState().name());
                        System.out.println("Job run Id is " + jobRun.id());
                        System.out.println("The Glue version is " + jobRun.glueVersion());
                    }
                    TimeUnit.SECONDS.sleep(5);
                }
            }

        } catch (GlueException e) {
            throw e;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetJobRuns](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetJobRuns)」を参照してください。

### `GetTables`
<a name="glue_GetTables_java_2_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the names of the tables in the specified Glue database.
     *
     * @param glueClient the Glue client to use for the operation
     * @param dbName     the name of the Glue database to retrieve the table names from
     * @return the name of the first table retrieved, or an empty string if no tables were found
     */
    public static String getGlueTables(GlueClient glueClient, String dbName) {
        String myTableName = "";
        try {
            GetTablesRequest tableRequest = GetTablesRequest.builder()
                .databaseName(dbName)
                .build();

            GetTablesResponse response = glueClient.getTables(tableRequest);
            List<Table> tables = response.tableList();
            if (tables.isEmpty()) {
                System.out.println("No tables were returned");
            } else {
                for (Table table : tables) {
                    myTableName = table.name();
                    System.out.println("Table name is: " + myTableName);
                }
            }

        } catch (GlueException e) {
            throw e;
        }
        return myTableName;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetTables](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/GetTables)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_java_2_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Starts a specific AWS Glue crawler.
     *
     * @param glueClient  the AWS Glue client to use for the crawler operation
     * @param crawlerName the name of the crawler to start
     * @throws GlueException if there is an error starting the crawler
     */
    public static void startSpecificCrawler(GlueClient glueClient, String crawlerName) {
        try {
            StartCrawlerRequest crawlerRequest = StartCrawlerRequest.builder()
                .name(crawlerName)
                .build();

            glueClient.startCrawler(crawlerRequest);
            System.out.println(crawlerName + " was successfully started!");

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[StartCrawler](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/StartCrawler)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_java_2_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Starts a job run in AWS Glue.
     *
     * @param glueClient    the AWS Glue client to use for the job run
     * @param jobName       the name of the Glue job to run
     * @param inputDatabase the name of the input database
     * @param inputTable    the name of the input table
     * @param outBucket     the URL of the output S3 bucket
     * @throws GlueException if there is an error starting the job run
     */
    public static void startJob(GlueClient glueClient, String jobName, String inputDatabase, String inputTable,
                                String outBucket) {
        try {
            Map<String, String> myMap = new HashMap<>();
            myMap.put("--input_database", inputDatabase);
            myMap.put("--input_table", inputTable);
            myMap.put("--output_bucket_url", outBucket);

            StartJobRunRequest runRequest = StartJobRunRequest.builder()
                .workerType(WorkerType.G_1_X)
                .numberOfWorkers(10)
                .arguments(myMap)
                .jobName(jobName)
                .build();

            StartJobRunResponse response = glueClient.startJobRun(runRequest);
            System.out.println("The request Id of the job is " + response.responseMetadata().requestId());

        } catch (GlueException e) {
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[StartJobRun](https://docs.aws.amazon.com/goto/SdkForJavaV2/glue-2017-03-31/StartJobRun)」を参照してください。

# SDK for Java 2.x を使用した HealthImaging の例
<a name="java_2_medical-imaging_code_examples"></a>

次のコード例は、HealthImaging AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CopyImageSet`
<a name="medical-imaging_CopyImageSet_java_2_topic"></a>

次のコード例は、`CopyImageSet` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    /**
     * Copy an AWS HealthImaging image set.
     *
     * @param medicalImagingClient  - The AWS HealthImaging client object.
     * @param datastoreId           - The datastore ID.
     * @param imageSetId            - The image set ID.
     * @param latestVersionId       - The version ID.
     * @param destinationImageSetId - The optional destination image set ID, ignored if null.
     * @param destinationVersionId  - The optional destination version ID, ignored if null.
     * @param force                 - The force flag.
     * @param subsets               - The optional subsets to copy, ignored if null.
     * @return                      - The image set ID of the copy.
     * @throws MedicalImagingException - Base exception for all service exceptions thrown by AWS HealthImaging.
     */
    public static String copyMedicalImageSet(MedicalImagingClient medicalImagingClient,
                                             String datastoreId,
                                             String imageSetId,
                                             String latestVersionId,
                                             String destinationImageSetId,
                                             String destinationVersionId,
                                             boolean force,
                                             Vector<String> subsets) {

        try {
            CopySourceImageSetInformation.Builder copySourceImageSetInformation = CopySourceImageSetInformation.builder()
                    .latestVersionId(latestVersionId);

            // Optionally copy a subset of image instances.
            if (subsets != null) {
                String subsetInstanceToCopy = getCopiableAttributesJSON(imageSetId, subsets);
                copySourceImageSetInformation.dicomCopies(MetadataCopies.builder()
                        .copiableAttributes(subsetInstanceToCopy)
                        .build());
            }

            CopyImageSetInformation.Builder copyImageSetBuilder = CopyImageSetInformation.builder()
                    .sourceImageSet(copySourceImageSetInformation.build());

            // Optionally designate a destination image set.
            if (destinationImageSetId != null) {
                copyImageSetBuilder = copyImageSetBuilder.destinationImageSet(CopyDestinationImageSet.builder()
                        .imageSetId(destinationImageSetId)
                        .latestVersionId(destinationVersionId)
                        .build());
            }

            CopyImageSetRequest copyImageSetRequest = CopyImageSetRequest.builder()
                    .datastoreId(datastoreId)
                    .sourceImageSetId(imageSetId)
                    .copyImageSetInformation(copyImageSetBuilder.build())
                    .force(force)
                    .build();

            CopyImageSetResponse response = medicalImagingClient.copyImageSet(copyImageSetRequest);

            return response.destinationImageSetProperties().imageSetId();
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            throw e;
        }
    }
```
コピー可能な属性を作成するユーティリティ関数。  

```
    /**
     * Create a JSON string of copiable image instances.
     *
     * @param imageSetId - The image set ID.
     * @param subsets    - The subsets to copy.
     * @return A JSON string of copiable image instances.
     */
    private static String getCopiableAttributesJSON(String imageSetId, Vector<String> subsets) {
        StringBuilder subsetInstanceToCopy = new StringBuilder(
                """
                        {
                          "SchemaVersion": 1.1,
                          "Study": {
                            "Series": {
                                "
                                 """
        );

        subsetInstanceToCopy.append(imageSetId);

        subsetInstanceToCopy.append(
                """
                                ": {
                                "Instances": {
                        """
        );

        for (String subset : subsets) {
            subsetInstanceToCopy.append('"' + subset + "\": {},");
        }
        subsetInstanceToCopy.deleteCharAt(subsetInstanceToCopy.length() - 1);
        subsetInstanceToCopy.append("""
                         }
                       }
                    }
                  }
                }
                """);
        return subsetInstanceToCopy.toString();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の[CopyImageSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/CopyImageSet)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `CreateDatastore`
<a name="medical-imaging_CreateDatastore_java_2_topic"></a>

次のコード例は、`CreateDatastore` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static String createMedicalImageDatastore(MedicalImagingClient medicalImagingClient,
            String datastoreName) {
        try {
            CreateDatastoreRequest datastoreRequest = CreateDatastoreRequest.builder()
                    .datastoreName(datastoreName)
                    .build();
            CreateDatastoreResponse response = medicalImagingClient.createDatastore(datastoreRequest);
            return response.datastoreId();
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDatastore](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/CreateDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `DeleteDatastore`
<a name="medical-imaging_DeleteDatastore_java_2_topic"></a>

次のコード例は、`DeleteDatastore` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static void deleteMedicalImagingDatastore(MedicalImagingClient medicalImagingClient,
            String datastoreID) {
        try {
            DeleteDatastoreRequest datastoreRequest = DeleteDatastoreRequest.builder()
                    .datastoreId(datastoreID)
                    .build();
            medicalImagingClient.deleteDatastore(datastoreRequest);
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDatastore](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/DeleteDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `DeleteImageSet`
<a name="medical-imaging_DeleteImageSet_java_2_topic"></a>

次のコード例は、`DeleteImageSet` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static void deleteMedicalImageSet(MedicalImagingClient medicalImagingClient,
            String datastoreId,
            String imagesetId) {
        try {
            DeleteImageSetRequest deleteImageSetRequest = DeleteImageSetRequest.builder()
                    .datastoreId(datastoreId)
                    .imageSetId(imagesetId)
                    .build();

            medicalImagingClient.deleteImageSet(deleteImageSetRequest);

            System.out.println("The image set was deleted.");
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteImageSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/DeleteImageSet)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `GetDICOMImportJob`
<a name="medical-imaging_GetDICOMImportJob_java_2_topic"></a>

次のコード例は、`GetDICOMImportJob` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static DICOMImportJobProperties getDicomImportJob(MedicalImagingClient medicalImagingClient,
            String datastoreId,
            String jobId) {

        try {
            GetDicomImportJobRequest getDicomImportJobRequest = GetDicomImportJobRequest.builder()
                    .datastoreId(datastoreId)
                    .jobId(jobId)
                    .build();
            GetDicomImportJobResponse response = medicalImagingClient.getDICOMImportJob(getDicomImportJobRequest);
            return response.jobProperties();
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetDICOMImportJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/GetDICOMImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `GetDatastore`
<a name="medical-imaging_GetDatastore_java_2_topic"></a>

次のコード例は、`GetDatastore` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static DatastoreProperties getMedicalImageDatastore(MedicalImagingClient medicalImagingClient,
            String datastoreID) {
        try {
            GetDatastoreRequest datastoreRequest = GetDatastoreRequest.builder()
                    .datastoreId(datastoreID)
                    .build();
            GetDatastoreResponse response = medicalImagingClient.getDatastore(datastoreRequest);
            return response.datastoreProperties();
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetDatastore](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/GetDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageFrame`
<a name="medical-imaging_GetImageFrame_java_2_topic"></a>

次のコード例は、`GetImageFrame` を使用する方法を示しています。

**SDK for Java 2.x**  

```
        public static void getMedicalImageSetFrame(MedicalImagingClient medicalImagingClient,
                        String destinationPath,
                        String datastoreId,
                        String imagesetId,
                        String imageFrameId) {

                try {
                        GetImageFrameRequest getImageSetMetadataRequest = GetImageFrameRequest.builder()
                                        .datastoreId(datastoreId)
                                        .imageSetId(imagesetId)
                                        .imageFrameInformation(ImageFrameInformation.builder()
                                                        .imageFrameId(imageFrameId)
                                                        .build())
                                        .build();
                        medicalImagingClient.getImageFrame(getImageSetMetadataRequest,
                                        FileSystems.getDefault().getPath(destinationPath));

                        System.out.println("Image frame downloaded to " + destinationPath);
                } catch (MedicalImagingException e) {
                        System.err.println(e.awsErrorDetails().errorMessage());
                        System.exit(1);
                }
        }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetImageFrame](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/GetImageFrame)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageSet`
<a name="medical-imaging_GetImageSet_java_2_topic"></a>

次のコード例は、`GetImageSet` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static GetImageSetResponse getMedicalImageSet(MedicalImagingClient medicalImagingClient,
            String datastoreId,
            String imagesetId,
            String versionId) {
        try {
            GetImageSetRequest.Builder getImageSetRequestBuilder = GetImageSetRequest.builder()
                    .datastoreId(datastoreId)
                    .imageSetId(imagesetId);

            if (versionId != null) {
                getImageSetRequestBuilder = getImageSetRequestBuilder.versionId(versionId);
            }

            return medicalImagingClient.getImageSet(getImageSetRequestBuilder.build());
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetImageSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/GetImageSet)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageSetMetadata`
<a name="medical-imaging_GetImageSetMetadata_java_2_topic"></a>

次のコード例は、`GetImageSetMetadata` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static void getMedicalImageSetMetadata(MedicalImagingClient medicalImagingClient,
            String destinationPath,
            String datastoreId,
            String imagesetId,
            String versionId) {

        try {
            GetImageSetMetadataRequest.Builder getImageSetMetadataRequestBuilder = GetImageSetMetadataRequest.builder()
                    .datastoreId(datastoreId)
                    .imageSetId(imagesetId);

            if (versionId != null) {
                getImageSetMetadataRequestBuilder = getImageSetMetadataRequestBuilder.versionId(versionId);
            }

            medicalImagingClient.getImageSetMetadata(getImageSetMetadataRequestBuilder.build(),
                    FileSystems.getDefault().getPath(destinationPath));

            System.out.println("Metadata downloaded to " + destinationPath);
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetImageSetMetadata](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/GetImageSetMetadata)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `ListDICOMImportJobs`
<a name="medical-imaging_ListDICOMImportJobs_java_2_topic"></a>

次のコード例は、`ListDICOMImportJobs` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static List<DICOMImportJobSummary> listDicomImportJobs(MedicalImagingClient medicalImagingClient,
            String datastoreId) {

        try {
            ListDicomImportJobsRequest listDicomImportJobsRequest = ListDicomImportJobsRequest.builder()
                    .datastoreId(datastoreId)
                    .build();
            ListDicomImportJobsResponse response = medicalImagingClient.listDICOMImportJobs(listDicomImportJobsRequest);
            return response.jobSummaries();
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return new ArrayList<>();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListDICOMImportJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/ListDICOMImportJobs)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `ListDatastores`
<a name="medical-imaging_ListDatastores_java_2_topic"></a>

次のコード例は、`ListDatastores` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static List<DatastoreSummary> listMedicalImagingDatastores(MedicalImagingClient medicalImagingClient) {
        try {
            ListDatastoresRequest datastoreRequest = ListDatastoresRequest.builder()
                    .build();
            ListDatastoresIterable responses = medicalImagingClient.listDatastoresPaginator(datastoreRequest);
            List<DatastoreSummary> datastoreSummaries = new ArrayList<>();

            responses.stream().forEach(response -> datastoreSummaries.addAll(response.datastoreSummaries()));

            return datastoreSummaries;
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListDatastores](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/ListDatastores)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `ListImageSetVersions`
<a name="medical-imaging_ListImageSetVersions_java_2_topic"></a>

次のコード例は、`ListImageSetVersions` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static List<ImageSetProperties> listMedicalImageSetVersions(MedicalImagingClient medicalImagingClient,
            String datastoreId,
            String imagesetId) {
        try {
            ListImageSetVersionsRequest getImageSetRequest = ListImageSetVersionsRequest.builder()
                    .datastoreId(datastoreId)
                    .imageSetId(imagesetId)
                    .build();

            ListImageSetVersionsIterable responses = medicalImagingClient
                    .listImageSetVersionsPaginator(getImageSetRequest);
            List<ImageSetProperties> imageSetProperties = new ArrayList<>();
            responses.stream().forEach(response -> imageSetProperties.addAll(response.imageSetPropertiesList()));

            return imageSetProperties;
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListImageSetVersions](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/ListImageSetVersions)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `ListTagsForResource`
<a name="medical-imaging_ListTagsForResource_java_2_topic"></a>

次のコード例は、`ListTagsForResource` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static ListTagsForResourceResponse listMedicalImagingResourceTags(MedicalImagingClient medicalImagingClient,
            String resourceArn) {
        try {
            ListTagsForResourceRequest listTagsForResourceRequest = ListTagsForResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .build();

            return medicalImagingClient.listTagsForResource(listTagsForResourceRequest);
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListTagsForResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/ListTagsForResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `SearchImageSets`
<a name="medical-imaging_SearchImageSets_java_2_topic"></a>

次のコード例は、`SearchImageSets` を使用する方法を示しています。

**SDK for Java 2.x**  
画像セットを検索するためのユーティリティ関数。  

```
    public static List<ImageSetsMetadataSummary> searchMedicalImagingImageSets(
            MedicalImagingClient medicalImagingClient,
            String datastoreId, SearchCriteria searchCriteria) {
        try {
            SearchImageSetsRequest datastoreRequest = SearchImageSetsRequest.builder()
                    .datastoreId(datastoreId)
                    .searchCriteria(searchCriteria)
                    .build();
            SearchImageSetsIterable responses = medicalImagingClient
                    .searchImageSetsPaginator(datastoreRequest);
            List<ImageSetsMetadataSummary> imageSetsMetadataSummaries = new ArrayList<>();

            responses.stream().forEach(response -> imageSetsMetadataSummaries
                    .addAll(response.imageSetsMetadataSummaries()));

            return imageSetsMetadataSummaries;
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
ユースケース \$11: EQUAL 演算子。  

```
        List<SearchFilter> searchFilters = Collections.singletonList(SearchFilter.builder()
                .operator(Operator.EQUAL)
                .values(SearchByAttributeValue.builder()
                        .dicomPatientId(patientId)
                        .build())
                .build());

        SearchCriteria searchCriteria = SearchCriteria.builder()
                .filters(searchFilters)
                .build();

        List<ImageSetsMetadataSummary> imageSetsMetadataSummaries = searchMedicalImagingImageSets(
                medicalImagingClient,
                datastoreId, searchCriteria);
        if (imageSetsMetadataSummaries != null) {
            System.out.println("The image sets for patient " + patientId + " are:\n"
                    + imageSetsMetadataSummaries);
            System.out.println();
        }
```
ユースケース \$12: DICOMStudyDate と DICOMStudyTime を使用する BETWEEN 演算子。  

```
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        searchFilters = Collections.singletonList(SearchFilter.builder()
                .operator(Operator.BETWEEN)
                .values(SearchByAttributeValue.builder()
                                .dicomStudyDateAndTime(DICOMStudyDateAndTime.builder()
                                        .dicomStudyDate("19990101")
                                        .dicomStudyTime("000000.000")
                                        .build())
                                .build(),
                        SearchByAttributeValue.builder()
                                .dicomStudyDateAndTime(DICOMStudyDateAndTime.builder()
                                        .dicomStudyDate((LocalDate.now()
                                                .format(formatter)))
                                        .dicomStudyTime("000000.000")
                                        .build())
                                .build())
                .build());

        searchCriteria = SearchCriteria.builder()
                .filters(searchFilters)
                .build();

        imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient,
                datastoreId, searchCriteria);
        if (imageSetsMetadataSummaries != null) {
            System.out.println(
                    "The image sets searched with BETWEEN operator using DICOMStudyDate and DICOMStudyTime are:\n"
                            +
                            imageSetsMetadataSummaries);
            System.out.println();
        }
```
ユースケース \$13: createdAt を使用する BETWEEN 演算子。タイムスタディは以前に永続化されています。  

```
        searchFilters = Collections.singletonList(SearchFilter.builder()
                .operator(Operator.BETWEEN)
                .values(SearchByAttributeValue.builder()
                                .createdAt(Instant.parse("1985-04-12T23:20:50.52Z"))
                                .build(),
                        SearchByAttributeValue.builder()
                                .createdAt(Instant.now())
                                .build())
                .build());

        searchCriteria = SearchCriteria.builder()
                .filters(searchFilters)
                .build();
        imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient,
                datastoreId, searchCriteria);
        if (imageSetsMetadataSummaries != null) {
            System.out.println("The image sets searched with BETWEEN operator using createdAt are:\n "
                    + imageSetsMetadataSummaries);
            System.out.println();
        }
```
ユースケース 4: DICOMSeriesInstanceUID で EQUAL 演算子を使用し、updatedAt で BETWEEN 演算子を使用して、updatedAt フィールドで ASC 順序にレスポンスをソートします。  

```
        Instant startDate = Instant.parse("1985-04-12T23:20:50.52Z");
        Instant endDate = Instant.now();

        searchFilters = Arrays.asList(
                SearchFilter.builder()
                        .operator(Operator.EQUAL)
                        .values(SearchByAttributeValue.builder()
                                .dicomSeriesInstanceUID(seriesInstanceUID)
                                .build())
                        .build(),
                SearchFilter.builder()
                        .operator(Operator.BETWEEN)
                        .values(
                                SearchByAttributeValue.builder().updatedAt(startDate).build(),
                                SearchByAttributeValue.builder().updatedAt(endDate).build()
                        ).build());

        Sort sort = Sort.builder().sortOrder(SortOrder.ASC).sortField(SortField.UPDATED_AT).build();

        searchCriteria = SearchCriteria.builder()
                .filters(searchFilters)
                .sort(sort)
                .build();

        imageSetsMetadataSummaries = searchMedicalImagingImageSets(medicalImagingClient,
                datastoreId, searchCriteria);
        if (imageSetsMetadataSummaries != null) {
            System.out.println("The image sets searched with EQUAL operator on DICOMSeriesInstanceUID and BETWEEN on updatedAt and sort response\n" +
                    "in ASC order on updatedAt field are:\n "
                    + imageSetsMetadataSummaries);
            System.out.println();
        }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SearchImageSets](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/SearchImageSets)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `StartDICOMImportJob`
<a name="medical-imaging_StartDICOMImportJob_java_2_topic"></a>

次のコード例は、`StartDICOMImportJob` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static String startDicomImportJob(MedicalImagingClient medicalImagingClient,
            String jobName,
            String datastoreId,
            String dataAccessRoleArn,
            String inputS3Uri,
            String outputS3Uri) {

        try {
            StartDicomImportJobRequest startDicomImportJobRequest = StartDicomImportJobRequest.builder()
                    .jobName(jobName)
                    .datastoreId(datastoreId)
                    .dataAccessRoleArn(dataAccessRoleArn)
                    .inputS3Uri(inputS3Uri)
                    .outputS3Uri(outputS3Uri)
                    .build();
            StartDicomImportJobResponse response = medicalImagingClient.startDICOMImportJob(startDicomImportJobRequest);
            return response.jobId();
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[StartDICOMImportJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/StartDICOMImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `TagResource`
<a name="medical-imaging_TagResource_java_2_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static void tagMedicalImagingResource(MedicalImagingClient medicalImagingClient,
            String resourceArn,
            Map<String, String> tags) {
        try {
            TagResourceRequest tagResourceRequest = TagResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .tags(tags)
                    .build();

            medicalImagingClient.tagResource(tagResourceRequest);

            System.out.println("Tags have been added to the resource.");
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/TagResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `UntagResource`
<a name="medical-imaging_UntagResource_java_2_topic"></a>

次のコード例は、`UntagResource` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    public static void untagMedicalImagingResource(MedicalImagingClient medicalImagingClient,
            String resourceArn,
            Collection<String> tagKeys) {
        try {
            UntagResourceRequest untagResourceRequest = UntagResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .tagKeys(tagKeys)
                    .build();

            medicalImagingClient.untagResource(untagResourceRequest);

            System.out.println("Tags have been removed from the resource.");
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UntagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/UntagResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### `UpdateImageSetMetadata`
<a name="medical-imaging_UpdateImageSetMetadata_java_2_topic"></a>

次のコード例は、`UpdateImageSetMetadata` を使用する方法を示しています。

**SDK for Java 2.x**  

```
    /**
     * Update the metadata of an AWS HealthImaging image set.
     *
     * @param medicalImagingClient - The AWS HealthImaging client object.
     * @param datastoreId          - The datastore ID.
     * @param imageSetId           - The image set ID.
     * @param versionId            - The version ID.
     * @param metadataUpdates      - A MetadataUpdates object containing the updates.
     * @param force                - The force flag.
     * @throws MedicalImagingException - Base exception for all service exceptions thrown by AWS HealthImaging.
     */
    public static void updateMedicalImageSetMetadata(MedicalImagingClient medicalImagingClient,
                                                     String datastoreId,
                                                     String imageSetId,
                                                     String versionId,
                                                     MetadataUpdates metadataUpdates,
                                                     boolean force) {
        try {
            UpdateImageSetMetadataRequest updateImageSetMetadataRequest = UpdateImageSetMetadataRequest
                    .builder()
                    .datastoreId(datastoreId)
                    .imageSetId(imageSetId)
                    .latestVersionId(versionId)
                    .updateImageSetMetadataUpdates(metadataUpdates)
                    .force(force)
                    .build();

            UpdateImageSetMetadataResponse response = medicalImagingClient.updateImageSetMetadata(updateImageSetMetadataRequest);

            System.out.println("The image set metadata was updated" + response);
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            throw e;
        }
    }
```
ユースケース 1: 属性を挿入または更新します。  

```
                final String insertAttributes = """
                        {
                          "SchemaVersion": 1.1,
                          "Study": {
                            "DICOM": {
                              "StudyDescription": "CT CHEST"
                            }
                          }
                        }
                        """;
                MetadataUpdates metadataInsertUpdates = MetadataUpdates.builder()
                        .dicomUpdates(DICOMUpdates.builder()
                                .updatableAttributes(SdkBytes.fromByteBuffer(
                                        ByteBuffer.wrap(insertAttributes
                                                .getBytes(StandardCharsets.UTF_8))))
                                .build())
                        .build();

                updateMedicalImageSetMetadata(medicalImagingClient, datastoreId, imagesetId,
                        versionid, metadataInsertUpdates, force);
```
ユースケース 2: 属性を削除します。  

```
                final String removeAttributes = """
                        {
                          "SchemaVersion": 1.1,
                          "Study": {
                            "DICOM": {
                              "StudyDescription": "CT CHEST"
                            }
                          }
                        }
                        """;
                MetadataUpdates metadataRemoveUpdates = MetadataUpdates.builder()
                        .dicomUpdates(DICOMUpdates.builder()
                                .removableAttributes(SdkBytes.fromByteBuffer(
                                        ByteBuffer.wrap(removeAttributes
                                                .getBytes(StandardCharsets.UTF_8))))
                                .build())
                        .build();

                updateMedicalImageSetMetadata(medicalImagingClient, datastoreId, imagesetId,
                        versionid, metadataRemoveUpdates, force);
```
ユースケース 3: インスタンスを削除します。  

```
                final String removeInstance = """
                        {
                          "SchemaVersion": 1.1,
                          "Study": {
                            "Series": {
                              "1.1.1.1.1.1.12345.123456789012.123.12345678901234.1": {
                                "Instances": {
                                  "1.1.1.1.1.1.12345.123456789012.123.12345678901234.1": {}
                                }
                              }
                            }
                          }
                        }      
                        """;
                MetadataUpdates metadataRemoveUpdates = MetadataUpdates.builder()
                        .dicomUpdates(DICOMUpdates.builder()
                                .removableAttributes(SdkBytes.fromByteBuffer(
                                        ByteBuffer.wrap(removeInstance
                                                .getBytes(StandardCharsets.UTF_8))))
                                .build())
                        .build();

                updateMedicalImageSetMetadata(medicalImagingClient, datastoreId, imagesetId,
                        versionid, metadataRemoveUpdates, force);
```
ユースケース 4: 以前のバージョンに戻します。  

```
                // In this case, revert to previous version.
                String revertVersionId = Integer.toString(Integer.parseInt(versionid) - 1);
                MetadataUpdates metadataRemoveUpdates = MetadataUpdates.builder()
                        .revertToVersionId(revertVersionId)
                        .build();
                updateMedicalImageSetMetadata(medicalImagingClient, datastoreId, imagesetId,
                        versionid, metadataRemoveUpdates, force);
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateImageSetMetadata](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/UpdateImageSetMetadata)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

## シナリオ
<a name="scenarios"></a>

### データストアにタグを付ける
<a name="medical-imaging_Scenario_TaggingDataStores_java_2_topic"></a>

次のコード例は、HealthImaging データストアにタグを付ける方法を示しています。

**SDK for Java 2.x**  
データストアにタグを付けるには  

```
                final String datastoreArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012";

                TagResource.tagMedicalImagingResource(medicalImagingClient, datastoreArn,
                                ImmutableMap.of("Deployment", "Development"));
```
リソースにタグを付けるためのユーティリティ関数。  

```
    public static void tagMedicalImagingResource(MedicalImagingClient medicalImagingClient,
            String resourceArn,
            Map<String, String> tags) {
        try {
            TagResourceRequest tagResourceRequest = TagResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .tags(tags)
                    .build();

            medicalImagingClient.tagResource(tagResourceRequest);

            System.out.println("Tags have been added to the resource.");
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
データストアのタグを一覧表示します。  

```
                final String datastoreArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012";

                ListTagsForResourceResponse result = ListTagsForResource.listMedicalImagingResourceTags(
                                medicalImagingClient,
                                datastoreArn);
                if (result != null) {
                        System.out.println("Tags for resource: " + result.tags());
                }
```
リソースのタグを一覧表示するユーティリティ関数。  

```
    public static ListTagsForResourceResponse listMedicalImagingResourceTags(MedicalImagingClient medicalImagingClient,
            String resourceArn) {
        try {
            ListTagsForResourceRequest listTagsForResourceRequest = ListTagsForResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .build();

            return medicalImagingClient.listTagsForResource(listTagsForResourceRequest);
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
データストアのタグを解除するには  

```
                final String datastoreArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012";

                UntagResource.untagMedicalImagingResource(medicalImagingClient, datastoreArn,
                                Collections.singletonList("Deployment"));
```
リソースのタグを解除するユーティリティ関数。  

```
    public static void untagMedicalImagingResource(MedicalImagingClient medicalImagingClient,
            String resourceArn,
            Collection<String> tagKeys) {
        try {
            UntagResourceRequest untagResourceRequest = UntagResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .tagKeys(tagKeys)
                    .build();

            medicalImagingClient.untagResource(untagResourceRequest);

            System.out.println("Tags have been removed from the resource.");
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [ListTagsForResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/ListTagsForResource)
  + [TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/TagResource)
  + [UntagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/UntagResource)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

### イメージセットにタグを付ける
<a name="medical-imaging_Scenario_TaggingImageSets_java_2_topic"></a>

次のコード例は、HealthImaging イメージセットにタグを付ける方法を示しています。

**SDK for Java 2.x**  
イメージセットにタグを付けるには  

```
                final String imageSetArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012";

                TagResource.tagMedicalImagingResource(medicalImagingClient, imageSetArn,
                                ImmutableMap.of("Deployment", "Development"));
```
リソースにタグを付けるためのユーティリティ関数。  

```
    public static void tagMedicalImagingResource(MedicalImagingClient medicalImagingClient,
            String resourceArn,
            Map<String, String> tags) {
        try {
            TagResourceRequest tagResourceRequest = TagResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .tags(tags)
                    .build();

            medicalImagingClient.tagResource(tagResourceRequest);

            System.out.println("Tags have been added to the resource.");
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
イメージセットのタグを一覧表示します。  

```
                final String imageSetArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012";

                ListTagsForResourceResponse result = ListTagsForResource.listMedicalImagingResourceTags(
                                medicalImagingClient,
                                imageSetArn);
                if (result != null) {
                        System.out.println("Tags for resource: " + result.tags());
                }
```
リソースのタグを一覧表示するユーティリティ関数。  

```
    public static ListTagsForResourceResponse listMedicalImagingResourceTags(MedicalImagingClient medicalImagingClient,
            String resourceArn) {
        try {
            ListTagsForResourceRequest listTagsForResourceRequest = ListTagsForResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .build();

            return medicalImagingClient.listTagsForResource(listTagsForResourceRequest);
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
```
イメージセットのタグを解除します。  

```
                final String imageSetArn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/imageset/12345678901234567890123456789012";

                UntagResource.untagMedicalImagingResource(medicalImagingClient, imageSetArn,
                                Collections.singletonList("Deployment"));
```
リソースのタグを解除するユーティリティ関数。  

```
    public static void untagMedicalImagingResource(MedicalImagingClient medicalImagingClient,
            String resourceArn,
            Collection<String> tagKeys) {
        try {
            UntagResourceRequest untagResourceRequest = UntagResourceRequest.builder()
                    .resourceArn(resourceArn)
                    .tagKeys(tagKeys)
                    .build();

            medicalImagingClient.untagResource(untagResourceRequest);

            System.out.println("Tags have been removed from the resource.");
        } catch (MedicalImagingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [ListTagsForResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/ListTagsForResource)
  + [TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/TagResource)
  + [UntagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/medical-imaging-2023-07-19/UntagResource)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/medicalimaging#code-examples)での設定と実行の方法を確認してください。

# SDK for Java 2.x を使用した IAM の例
<a name="java_2_iam_code_examples"></a>

次のコード例は、IAM AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_java_2_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.ListPoliciesResponse;
import software.amazon.awssdk.services.iam.model.Policy;
import java.util.List;

/**
 * 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 HelloIAM {
    public static void main(String[] args) {
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listPolicies(iam);
    }

    public static void listPolicies(IamClient iam) {
        ListPoliciesResponse response = iam.listPolicies();
        List<Policy> polList = response.policies();
        polList.forEach(policy -> {
            System.out.println("Policy Name: " + policy.policyName());
        });
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListPolicies)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_java_2_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーアクションをラップする関数を作成します。  

```
/*
  To run this Java V2 code example, 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

  This example performs these operations:

  1. Creates a user that has no permissions.
  2. Creates a role and policy that grants Amazon S3 permissions.
  3. Creates a role.
  4. Grants the user permissions.
  5. Gets temporary credentials by assuming the role.  Creates an Amazon S3 Service client object with the temporary credentials.
  6. Deletes the resources.
 */

public class IAMScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    public static final String PolicyDocument = "{" +
            "  \"Version\": \"2012-10-17\"," +
            "  \"Statement\": [" +
            "    {" +
            "        \"Effect\": \"Allow\"," +
            "        \"Action\": [" +
            "            \"s3:*\"" +
            "       ]," +
            "       \"Resource\": \"*\"" +
            "    }" +
            "   ]" +
            "}";

    public static String userArn;

    public static void main(String[] args) throws Exception {

        final String usage = """

                Usage:
                    <username> <policyName> <roleName> <roleSessionName> <bucketName>\s

                Where:
                    username - The name of the IAM user to create.\s
                    policyName - The name of the policy to create.\s
                    roleName - The name of the role to create.\s
                    roleSessionName - The name of the session required for the assumeRole operation.\s
                    bucketName - The name of the Amazon S3 bucket from which objects are read.\s
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String userName = args[0];
        String policyName = args[1];
        String roleName = args[2];
        String roleSessionName = args[3];
        String bucketName = args[4];

        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS IAM example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(" 1. Create the IAM user.");
        User createUser = createIAMUser(iam, userName);

        System.out.println(DASHES);
        userArn = createUser.arn();

        AccessKey myKey = createIAMAccessKey(iam, userName);
        String accessKey = myKey.accessKeyId();
        String secretKey = myKey.secretAccessKey();
        String assumeRolePolicyDocument = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "	\"AWS\": \"" + userArn + "\"" +
                "}," +
                "\"Action\": \"sts:AssumeRole\"" +
                "}]" +
                "}";

        System.out.println(assumeRolePolicyDocument);
        System.out.println(userName + " was successfully created.");
        System.out.println(DASHES);
        System.out.println("2. Creates a policy.");
        String polArn = createIAMPolicy(iam, policyName);
        System.out.println("The policy " + polArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Creates a role.");
        TimeUnit.SECONDS.sleep(30);
        String roleArn = createIAMRole(iam, roleName, assumeRolePolicyDocument);
        System.out.println(roleArn + " was successfully created.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Grants the user permissions.");
        attachIAMRolePolicy(iam, roleName, polArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("*** Wait for 30 secs so the resource is available");
        TimeUnit.SECONDS.sleep(30);
        System.out.println("5. Gets temporary credentials by assuming the role.");
        System.out.println("Perform an Amazon S3 Service operation using the temporary credentials.");
        assumeRole(roleArn, roleSessionName, bucketName, accessKey, secretKey);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6 Getting ready to delete the AWS resources");
        deleteKey(iam, userName, accessKey);
        deleteRole(iam, roleName, polArn);
        deleteIAMUser(iam, userName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("This IAM Scenario has successfully completed");
        System.out.println(DASHES);
    }

    public static AccessKey createIAMAccessKey(IamClient iam, String user) {
        try {
            CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
                    .userName(user)
                    .build();

            CreateAccessKeyResponse response = iam.createAccessKey(request);
            return response.accessKey();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static User createIAMUser(IamClient iam, String username) {
        try {
            // Create an IamWaiter object
            IamWaiter iamWaiter = iam.waiter();
            CreateUserRequest request = CreateUserRequest.builder()
                    .userName(username)
                    .build();

            // Wait until the user is created.
            CreateUserResponse response = iam.createUser(request);
            GetUserRequest userRequest = GetUserRequest.builder()
                    .userName(response.user().userName())
                    .build();

            WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);
            waitUntilUserExists.matched().response().ifPresent(System.out::println);
            return response.user();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static String createIAMRole(IamClient iam, String rolename, String json) {

        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(rolename)
                    .assumeRolePolicyDocument(json)
                    .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());
            return response.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static String createIAMPolicy(IamClient iam, String policyName) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();
            CreatePolicyRequest request = CreatePolicyRequest.builder()
                    .policyName(policyName)
                    .policyDocument(PolicyDocument).build();

            CreatePolicyResponse response = iam.createPolicy(request);
            GetPolicyRequest polRequest = GetPolicyRequest.builder()
                    .policyArn(response.policy().arn())
                    .build();

            WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
            waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
            return response.policy().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) {
        try {
            ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
                    .roleName(roleName)
                    .build();

            ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
            List<AttachedPolicy> attachedPolicies = response.attachedPolicies();
            String polArn;
            for (AttachedPolicy policy : attachedPolicies) {
                polArn = policy.policyArn();
                if (polArn.compareTo(policyArn) == 0) {
                    System.out.println(roleName + " policy is already attached to this role.");
                    return;
                }
            }

            AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.attachRolePolicy(attachRequest);
            System.out.println("Successfully attached policy " + policyArn + " to role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Invoke an Amazon S3 operation using the Assumed Role.
    public static void assumeRole(String roleArn, String roleSessionName, String bucketName, String keyVal,
            String keySecret) {

        // Use the creds of the new IAM user that was created in this code example.
        AwsBasicCredentials credentials = AwsBasicCredentials.create(keyVal, keySecret);
        StsClient stsClient = StsClient.builder()
                .region(Region.US_EAST_1)
                .credentialsProvider(StaticCredentialsProvider.create(credentials))
                .build();

        try {
            AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                    .roleArn(roleArn)
                    .roleSessionName(roleSessionName)
                    .build();

            AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
            Credentials myCreds = roleResponse.credentials();
            String key = myCreds.accessKeyId();
            String secKey = myCreds.secretAccessKey();
            String secToken = myCreds.sessionToken();

            // List all objects in an Amazon S3 bucket using the temp creds retrieved by
            // invoking assumeRole.
            Region region = Region.US_EAST_1;
            S3Client s3 = S3Client.builder()
                    .credentialsProvider(
                            StaticCredentialsProvider.create(AwsSessionCredentials.create(key, secKey, secToken)))
                    .region(region)
                    .build();

            System.out.println("Created a S3Client using temp credentials.");
            System.out.println("Listing objects in " + bucketName);
            ListObjectsRequest listObjects = ListObjectsRequest.builder()
                    .bucket(bucketName)
                    .build();

            ListObjectsResponse res = s3.listObjects(listObjects);
            List<S3Object> objects = res.contents();
            for (S3Object myValue : objects) {
                System.out.println("The name of the key is " + myValue.key());
                System.out.println("The owner is " + myValue.owner());
            }

        } catch (StsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void deleteRole(IamClient iam, String roleName, String polArn) {

        try {
            // First the policy needs to be detached.
            DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder()
                    .policyArn(polArn)
                    .roleName(roleName)
                    .build();

            iam.detachRolePolicy(rolePolicyRequest);

            // Delete the policy.
            DeletePolicyRequest request = DeletePolicyRequest.builder()
                    .policyArn(polArn)
                    .build();

            iam.deletePolicy(request);
            System.out.println("*** Successfully deleted " + polArn);

            // Delete the role.
            DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            iam.deleteRole(roleRequest);
            System.out.println("*** Successfully deleted " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteKey(IamClient iam, String username, String accessKey) {
        try {
            DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()
                    .accessKeyId(accessKey)
                    .userName(username)
                    .build();

            iam.deleteAccessKey(request);
            System.out.println("Successfully deleted access key " + accessKey +
                    " from user " + username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteIAMUser(IamClient iam, String userName) {
        try {
            DeleteUserRequest request = DeleteUserRequest.builder()
                    .userName(userName)
                    .build();

            iam.deleteUser(request);
            System.out.println("*** Successfully deleted " + userName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_java_2_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.AttachRolePolicyRequest;
import software.amazon.awssdk.services.iam.model.AttachedPolicy;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesRequest;
import software.amazon.awssdk.services.iam.model.ListAttachedRolePoliciesResponse;
import java.util.List;

/**
 * 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 AttachRolePolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <roleName> <policyArn>\s

                Where:
                    roleName - A role name that you can obtain from the AWS Management Console.\s
                    policyArn - A policy ARN that you can obtain from the AWS Management Console.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String roleName = args[0];
        String policyArn = args[1];

        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        attachIAMRolePolicy(iam, roleName, policyArn);
        iam.close();
    }

    public static void attachIAMRolePolicy(IamClient iam, String roleName, String policyArn) {
        try {
            ListAttachedRolePoliciesRequest request = ListAttachedRolePoliciesRequest.builder()
                    .roleName(roleName)
                    .build();

            ListAttachedRolePoliciesResponse response = iam.listAttachedRolePolicies(request);
            List<AttachedPolicy> attachedPolicies = response.attachedPolicies();

            // Ensure that the policy is not attached to this role
            String polArn = "";
            for (AttachedPolicy policy : attachedPolicies) {
                polArn = policy.policyArn();
                if (polArn.compareTo(policyArn) == 0) {
                    System.out.println(roleName + " policy is already attached to this role.");
                    return;
                }
            }

            AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.attachRolePolicy(attachRequest);

            System.out.println("Successfully attached policy " + policyArn +
                    " to role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/AttachRolePolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_java_2_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.CreateAccessKeyRequest;
import software.amazon.awssdk.services.iam.model.CreateAccessKeyResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 CreateAccessKey {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                   <user>\s

                Where:
                   user - An AWS IAM user that you can obtain from the AWS Management Console.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String user = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        String keyId = createIAMAccessKey(iam, user);
        System.out.println("The Key Id is " + keyId);
        iam.close();
    }

    public static String createIAMAccessKey(IamClient iam, String user) {
        try {
            CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
                    .userName(user)
                    .build();

            CreateAccessKeyResponse response = iam.createAccessKey(request);
            return response.accessKey().accessKeyId();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccessKey)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_java_2_topic"></a>

次のコード例は、`CreateAccountAlias` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.CreateAccountAliasRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 CreateAccountAlias {
    public static void main(String[] args) {
        final String usage = """
                Usage:
                    <alias>\s

                Where:
                    alias - The account alias to create (for example, myawsaccount).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String alias = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        createIAMAccountAlias(iam, alias);
        iam.close();
        System.out.println("Done");
    }

    public static void createIAMAccountAlias(IamClient iam, String alias) {
        try {
            CreateAccountAliasRequest request = CreateAccountAliasRequest.builder()
                    .accountAlias(alias)
                    .build();

            iam.createAccountAlias(request);
            System.out.println("Successfully created account alias: " + alias);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateAccountAlias](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateAccountAlias)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_java_2_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.iam.model.CreatePolicyRequest;
import software.amazon.awssdk.services.iam.model.CreatePolicyResponse;
import software.amazon.awssdk.services.iam.model.GetPolicyRequest;
import software.amazon.awssdk.services.iam.model.GetPolicyResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.waiters.IamWaiter;

/**
 * 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 CreatePolicy {

    public static final String PolicyDocument = "{" +
            "  \"Version\": \"2012-10-17\"," +
            "  \"Statement\": [" +
            "    {" +
            "        \"Effect\": \"Allow\"," +
            "        \"Action\": [" +
            "            \"dynamodb:DeleteItem\"," +
            "            \"dynamodb:GetItem\"," +
            "            \"dynamodb:PutItem\"," +
            "            \"dynamodb:Scan\"," +
            "            \"dynamodb:UpdateItem\"" +
            "       ]," +
            "       \"Resource\": \"*\"" +
            "    }" +
            "   ]" +
            "}";

    public static void main(String[] args) {

        final String usage = """
                Usage:
                    CreatePolicy <policyName>\s

                Where:
                    policyName - A unique policy name.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String policyName = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        String result = createIAMPolicy(iam, policyName);
        System.out.println("Successfully created a policy with this ARN value: " + result);
        iam.close();
    }

    public static String createIAMPolicy(IamClient iam, String policyName) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();

            CreatePolicyRequest request = CreatePolicyRequest.builder()
                    .policyName(policyName)
                    .policyDocument(PolicyDocument)
                    .build();

            CreatePolicyResponse response = iam.createPolicy(request);

            // Wait until the policy is created.
            GetPolicyRequest polRequest = GetPolicyRequest.builder()
                    .policyArn(response.policy().arn())
                    .build();

            WaiterResponse<GetPolicyResponse> waitUntilPolicyExists = iamWaiter.waitUntilPolicyExists(polRequest);
            waitUntilPolicyExists.matched().response().ifPresent(System.out::println);
            return response.policy().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_java_2_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
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](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateRole)」を参照してください。**

### `CreateUser`
<a name="iam_CreateUser_java_2_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.services.iam.model.CreateUserRequest;
import software.amazon.awssdk.services.iam.model.CreateUserResponse;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.waiters.IamWaiter;
import software.amazon.awssdk.services.iam.model.GetUserRequest;
import software.amazon.awssdk.services.iam.model.GetUserResponse;

/**
 * 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 CreateUser {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <username>\s

                Where:
                    username - The name of the user to create.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String username = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        String result = createIAMUser(iam, username);
        System.out.println("Successfully created user: " + result);
        iam.close();
    }

    public static String createIAMUser(IamClient iam, String username) {
        try {
            // Create an IamWaiter object.
            IamWaiter iamWaiter = iam.waiter();

            CreateUserRequest request = CreateUserRequest.builder()
                    .userName(username)
                    .build();

            CreateUserResponse response = iam.createUser(request);

            // Wait until the user is created.
            GetUserRequest userRequest = GetUserRequest.builder()
                    .userName(response.user().userName())
                    .build();

            WaiterResponse<GetUserResponse> waitUntilUserExists = iamWaiter.waitUntilUserExists(userRequest);
            waitUntilUserExists.matched().response().ifPresent(System.out::println);
            return response.user().userName();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_java_2_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.DeleteAccessKeyRequest;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeleteAccessKey {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <username> <accessKey>\s

                Where:
                    username - The name of the user.\s
                    accessKey - The access key ID for the secret access key you want to delete.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String username = args[0];
        String accessKey = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();
        deleteKey(iam, username, accessKey);
        iam.close();
    }

    public static void deleteKey(IamClient iam, String username, String accessKey) {
        try {
            DeleteAccessKeyRequest request = DeleteAccessKeyRequest.builder()
                    .accessKeyId(accessKey)
                    .userName(username)
                    .build();

            iam.deleteAccessKey(request);
            System.out.println("Successfully deleted access key " + accessKey +
                    " from user " + username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccessKey)」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_java_2_topic"></a>

次のコード例は、`DeleteAccountAlias` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.DeleteAccountAliasRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeleteAccountAlias {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <alias>\s

                Where:
                    alias - The account alias to delete.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String alias = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        deleteIAMAccountAlias(iam, alias);
        iam.close();
    }

    public static void deleteIAMAccountAlias(IamClient iam, String alias) {
        try {
            DeleteAccountAliasRequest request = DeleteAccountAliasRequest.builder()
                    .accountAlias(alias)
                    .build();

            iam.deleteAccountAlias(request);
            System.out.println("Successfully deleted account alias " + alias);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteAccountAlias](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteAccountAlias)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_java_2_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.DeletePolicyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeletePolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <policyARN>\s

                Where:
                    policyARN - A policy ARN value to delete.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String policyARN = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        deleteIAMPolicy(iam, policyARN);
        iam.close();
    }

    public static void deleteIAMPolicy(IamClient iam, String policyARN) {
        try {
            DeletePolicyRequest request = DeletePolicyRequest.builder()
                    .policyArn(policyARN)
                    .build();

            iam.deletePolicy(request);
            System.out.println("Successfully deleted the policy");

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeletePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeletePolicy)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_java_2_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.DeleteUserRequest;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DeleteUser {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <userName>\s

                Where:
                    userName - The name of the user to delete.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String userName = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        deleteIAMUser(iam, userName);
        System.out.println("Done");
        iam.close();
    }

    public static void deleteIAMUser(IamClient iam, String userName) {
        try {
            DeleteUserRequest request = DeleteUserRequest.builder()
                    .userName(userName)
                    .build();

            iam.deleteUser(request);
            System.out.println("Successfully deleted IAM user " + userName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteUser)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_java_2_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;

/**
 * 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 DetachRolePolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <roleName> <policyArn>\s

                Where:
                    roleName - A role name that you can obtain from the AWS Management Console.\s
                    policyArn - A policy ARN that you can obtain from the AWS Management Console.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String roleName = args[0];
        String policyArn = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();
        detachPolicy(iam, roleName, policyArn);
        System.out.println("Done");
        iam.close();
    }

    public static void detachPolicy(IamClient iam, String roleName, String policyArn) {
        try {
            DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
                    .roleName(roleName)
                    .policyArn(policyArn)
                    .build();

            iam.detachRolePolicy(request);
            System.out.println("Successfully detached policy " + policyArn +
                    " from role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DetachRolePolicy)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_java_2_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.AccessKeyMetadata;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListAccessKeysRequest;
import software.amazon.awssdk.services.iam.model.ListAccessKeysResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;

/**
 * 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 ListAccessKeys {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <userName>\s

                Where:
                    userName - The name of the user for which access keys are retrieved.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String userName = args[0];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listKeys(iam, userName);
        System.out.println("Done");
        iam.close();
    }

    public static void listKeys(IamClient iam, String userName) {
        try {
            boolean done = false;
            String newMarker = null;

            while (!done) {
                ListAccessKeysResponse response;

                if (newMarker == null) {
                    ListAccessKeysRequest request = ListAccessKeysRequest.builder()
                            .userName(userName)
                            .build();

                    response = iam.listAccessKeys(request);

                } else {
                    ListAccessKeysRequest request = ListAccessKeysRequest.builder()
                            .userName(userName)
                            .marker(newMarker)
                            .build();

                    response = iam.listAccessKeys(request);
                }

                for (AccessKeyMetadata metadata : response.accessKeyMetadata()) {
                    System.out.format("Retrieved access key %s", metadata.accessKeyId());
                }

                if (!response.isTruncated()) {
                    done = true;
                } else {
                    newMarker = response.marker();
                }
            }

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListAccessKeys](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListAccessKeys)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_java_2_topic"></a>

次のコード例は、`ListAccountAliases` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListAccountAliasesResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;

/**
 * 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 ListAccountAliases {
    public static void main(String[] args) {
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listAliases(iam);
        System.out.println("Done");
        iam.close();
    }

    public static void listAliases(IamClient iam) {
        try {
            ListAccountAliasesResponse response = iam.listAccountAliases();
            for (String alias : response.accountAliases()) {
                System.out.printf("Retrieved account alias %s", alias);
            }

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListAccountAliases](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListAccountAliases)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_java_2_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.AttachedPermissionsBoundary;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.ListUsersRequest;
import software.amazon.awssdk.services.iam.model.ListUsersResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.User;

/**
 * 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 ListUsers {
    public static void main(String[] args) {
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        listAllUsers(iam);
        System.out.println("Done");
        iam.close();
    }

    public static void listAllUsers(IamClient iam) {
        try {
            boolean done = false;
            String newMarker = null;
            while (!done) {
                ListUsersResponse response;
                if (newMarker == null) {
                    ListUsersRequest request = ListUsersRequest.builder().build();
                    response = iam.listUsers(request);
                } else {
                    ListUsersRequest request = ListUsersRequest.builder()
                            .marker(newMarker)
                            .build();

                    response = iam.listUsers(request);
                }

                for (User user : response.users()) {
                    System.out.format("\n Retrieved user %s", user.userName());
                    AttachedPermissionsBoundary permissionsBoundary = user.permissionsBoundary();
                    if (permissionsBoundary != null)
                        System.out.format("\n Permissions boundary details %s",
                                permissionsBoundary.permissionsBoundaryTypeAsString());
                }

                if (!response.isTruncated()) {
                    done = true;
                } else {
                    newMarker = response.marker();
                }
            }

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/ListUsers)」を参照してください。

### `UpdateAccessKey`
<a name="iam_UpdateAccessKey_java_2_topic"></a>

次のコード例は、`UpdateAccessKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.StatusType;
import software.amazon.awssdk.services.iam.model.UpdateAccessKeyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;

/**
 * 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 UpdateAccessKey {

    private static StatusType statusType;

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <username> <accessId> <status>\s

                Where:
                    username - The name of the user whose key you want to update.\s
                    accessId - The access key ID of the secret access key you want to update.\s
                    status - The status you want to assign to the secret access key.\s
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String username = args[0];
        String accessId = args[1];
        String status = args[2];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        updateKey(iam, username, accessId, status);
        System.out.println("Done");
        iam.close();
    }

    public static void updateKey(IamClient iam, String username, String accessId, String status) {
        try {
            if (status.toLowerCase().equalsIgnoreCase("active")) {
                statusType = StatusType.ACTIVE;
            } else if (status.toLowerCase().equalsIgnoreCase("inactive")) {
                statusType = StatusType.INACTIVE;
            } else {
                statusType = StatusType.UNKNOWN_TO_SDK_VERSION;
            }

            UpdateAccessKeyRequest request = UpdateAccessKeyRequest.builder()
                    .accessKeyId(accessId)
                    .userName(username)
                    .status(statusType)
                    .build();

            iam.updateAccessKey(request);
            System.out.printf("Successfully updated the status of access key %s to" +
                    "status %s for user %s", accessId, status, username);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateAccessKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/UpdateAccessKey)」を参照してください。

### `UpdateUser`
<a name="iam_UpdateUser_java_2_topic"></a>

次のコード例は、`UpdateUser` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
import software.amazon.awssdk.services.iam.model.UpdateUserRequest;

/**
 * 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 UpdateUser {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <curName> <newName>\s

                Where:
                    curName - The current user name.\s
                    newName - An updated user name.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String curName = args[0];
        String newName = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        updateIAMUser(iam, curName, newName);
        System.out.println("Done");
        iam.close();
    }

    public static void updateIAMUser(IamClient iam, String curName, String newName) {
        try {
            UpdateUserRequest request = UpdateUserRequest.builder()
                    .userName(curName)
                    .newUserName(newName)
                    .build();

            iam.updateUser(request);
            System.out.printf("Successfully updated user to username %s", newName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateUser](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/UpdateUser)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_java_2_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
public class Main {

    public static final String fileName = "C:\\AWS\\resworkflow\\recommendations.json"; // Modify file location.
    public static final String tableName = "doc-example-recommendation-service";
    public static final String startScript = "C:\\AWS\\resworkflow\\server_startup_script.sh"; // Modify file location.
    public static final String policyFile = "C:\\AWS\\resworkflow\\instance_policy.json"; // Modify file location.
    public static final String ssmJSON = "C:\\AWS\\resworkflow\\ssm_only_policy.json"; // Modify file location.
    public static final String failureResponse = "doc-example-resilient-architecture-failure-response";
    public static final String healthCheck = "doc-example-resilient-architecture-health-check";
    public static final String templateName = "doc-example-resilience-template";
    public static final String roleName = "doc-example-resilience-role";
    public static final String policyName = "doc-example-resilience-pol";
    public static final String profileName = "doc-example-resilience-prof";

    public static final String badCredsProfileName = "doc-example-resilience-prof-bc";

    public static final String targetGroupName = "doc-example-resilience-tg";
    public static final String autoScalingGroupName = "doc-example-resilience-group";
    public static final String lbName = "doc-example-resilience-lb";
    public static final String protocol = "HTTP";
    public static final int port = 80;

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws IOException, InterruptedException {
        Scanner in = new Scanner(System.in);
        Database database = new Database();
        AutoScaler autoScaler = new AutoScaler();
        LoadBalancer loadBalancer = new LoadBalancer();

        System.out.println(DASHES);
        System.out.println("Welcome to the demonstration of How to Build and Manage a Resilient Service!");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("A - SETUP THE RESOURCES");
        System.out.println("Press Enter when you're ready to start deploying resources.");
        in.nextLine();
        deploy(loadBalancer);
        System.out.println(DASHES);
        System.out.println(DASHES);
        System.out.println("B - DEMO THE RESILIENCE FUNCTIONALITY");
        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        demo(loadBalancer);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("C - DELETE THE RESOURCES");
        System.out.println("""
                This concludes the demo of how to build and manage a resilient service.
                To keep things tidy and to avoid unwanted charges on your account, we can clean up all AWS resources
                that were created for this demo.
                """);

        System.out.println("\n Do you want to delete the resources (y/n)? ");
        String userInput = in.nextLine().trim().toLowerCase(); // Capture user input

        if (userInput.equals("y")) {
            // Delete resources here
            deleteResources(loadBalancer, autoScaler, database);
            System.out.println("Resources deleted.");
        } else {
            System.out.println("""
                    Okay, we'll leave the resources intact.
                    Don't forget to delete them when you're done with them or you might incur unexpected charges.
                    """);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The example has completed. ");
        System.out.println("\n Thanks for watching!");
        System.out.println(DASHES);
    }

    // Deletes the AWS resources used in this example.
    private static void deleteResources(LoadBalancer loadBalancer, AutoScaler autoScaler, Database database)
            throws IOException, InterruptedException {
        loadBalancer.deleteLoadBalancer(lbName);
        System.out.println("*** Wait 30 secs for resource to be deleted");
        TimeUnit.SECONDS.sleep(30);
        loadBalancer.deleteTargetGroup(targetGroupName);
        autoScaler.deleteAutoScaleGroup(autoScalingGroupName);
        autoScaler.deleteRolesPolicies(policyName, roleName, profileName);
        autoScaler.deleteTemplate(templateName);
        database.deleteTable(tableName);
    }

    private static void deploy(LoadBalancer loadBalancer) throws InterruptedException, IOException {
        Scanner in = new Scanner(System.in);
        System.out.println(
                """
                        For this demo, we'll use the AWS SDK for Java (v2) to create several AWS resources
                        to set up a load-balanced web service endpoint and explore some ways to make it resilient
                        against various kinds of failures.

                        Some of the resources create by this demo are:
                        \t* A DynamoDB table that the web service depends on to provide book, movie, and song recommendations.
                        \t* An EC2 launch template that defines EC2 instances that each contain a Python web server.
                        \t* An EC2 Auto Scaling group that manages EC2 instances across several Availability Zones.
                        \t* An Elastic Load Balancing (ELB) load balancer that targets the Auto Scaling group to distribute requests.
                        """);

        System.out.println("Press Enter when you're ready.");
        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating and populating a DynamoDB table named " + tableName);
        Database database = new Database();
        database.createTable(tableName, fileName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an EC2 launch template that runs '{startup_script}' when an instance starts.
                This script starts a Python web server defined in the `server.py` script. The web server
                listens to HTTP requests on port 80 and responds to requests to '/' and to '/healthcheck'.
                For demo purposes, this server is run as the root user. In production, the best practice is to
                run a web server, such as Apache, with least-privileged credentials.

                The template also defines an IAM policy that each instance uses to assume a role that grants
                permissions to access the DynamoDB recommendation table and Systems Manager parameters
                that control the flow of the demo.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        templateCreator.createTemplate(policyFile, policyName, profileName, startScript, templateName, roleName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(
                "Creating an EC2 Auto Scaling group that maintains three EC2 instances, each in a different Availability Zone.");
        System.out.println("*** Wait 30 secs for the VPC to be created");
        TimeUnit.SECONDS.sleep(30);
        AutoScaler autoScaler = new AutoScaler();
        String[] zones = autoScaler.createGroup(3, templateName, autoScalingGroupName);

        System.out.println("""
                At this point, you have EC2 instances created. Once each instance starts, it listens for
                HTTP requests. You can see these instances in the console or continue with the demo.
                Press Enter when you're ready to continue.
                """);

        in.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Creating variables that control the flow of the demo.");
        ParameterHelper paramHelper = new ParameterHelper();
        paramHelper.reset();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
                Creating an Elastic Load Balancing target group and load balancer. The target group
                defines how the load balancer connects to instances. The load balancer provides a
                single endpoint where clients connect and dispatches requests to instances in the group.
                """);

        String vpcId = autoScaler.getDefaultVPC();
        List<Subnet> subnets = autoScaler.getSubnets(vpcId, zones);
        System.out.println("You have retrieved a list with " + subnets.size() + " subnets");
        String targetGroupArn = loadBalancer.createTargetGroup(protocol, port, vpcId, targetGroupName);
        String elbDnsName = loadBalancer.createLoadBalancer(subnets, targetGroupArn, lbName, port, protocol);
        autoScaler.attachLoadBalancerTargetGroup(autoScalingGroupName, targetGroupArn);
        System.out.println("Verifying access to the load balancer endpoint...");
        boolean wasSuccessul = loadBalancer.verifyLoadBalancerEndpoint(elbDnsName);
        if (!wasSuccessul) {
            System.out.println("Couldn't connect to the load balancer, verifying that the port is open...");
            CloseableHttpClient httpClient = HttpClients.createDefault();

            // Create an HTTP GET request to "http://checkip.amazonaws.com"
            HttpGet httpGet = new HttpGet("http://checkip.amazonaws.com");
            try {
                // Execute the request and get the response
                HttpResponse response = httpClient.execute(httpGet);

                // Read the response content.
                String ipAddress = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8).trim();

                // Print the public IP address.
                System.out.println("Public IP Address: " + ipAddress);
                GroupInfo groupInfo = autoScaler.verifyInboundPort(vpcId, port, ipAddress);
                if (!groupInfo.isPortOpen()) {
                    System.out.println("""
                            For this example to work, the default security group for your default VPC must
                            allow access from this computer. You can either add it automatically from this
                            example or add it yourself using the AWS Management Console.
                            """);

                    System.out.println(
                            "Do you want to add a rule to security group " + groupInfo.getGroupName() + " to allow");
                    System.out.println("inbound traffic on port " + port + " from your computer's IP address (y/n) ");
                    String ans = in.nextLine();
                    if ("y".equalsIgnoreCase(ans)) {
                        autoScaler.openInboundPort(groupInfo.getGroupName(), String.valueOf(port), ipAddress);
                        System.out.println("Security group rule added.");
                    } else {
                        System.out.println("No security group rule added.");
                    }
                }

            } catch (AutoScalingException e) {
                e.printStackTrace();
            }
        } else if (wasSuccessul) {
            System.out.println("Your load balancer is ready. You can access it by browsing to:");
            System.out.println("\t http://" + elbDnsName);
        } else {
            System.out.println("Couldn't get a successful response from the load balancer endpoint. Troubleshoot by");
            System.out.println("manually verifying that your VPC and security group are configured correctly and that");
            System.out.println("you can successfully make a GET request to the load balancer.");
        }

        System.out.println("Press Enter when you're ready to continue with the demo.");
        in.nextLine();
    }

    // A method that controls the demo part of the Java program.
    public static void demo(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        ParameterHelper paramHelper = new ParameterHelper();
        System.out.println("Read the ssm_only_policy.json file");
        String ssmOnlyPolicy = readFileAsString(ssmJSON);

        System.out.println("Resetting parameters to starting values for demo.");
        paramHelper.reset();

        System.out.println(
                """
                         This part of the demonstration shows how to toggle different parts of the system
                         to create situations where the web service fails, and shows how using a resilient
                         architecture can keep the web service running in spite of these failures.

                         At the start, the load balancer endpoint returns recommendations and reports that all targets are healthy.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                         The web service running on the EC2 instances gets recommendations by querying a DynamoDB table.
                         The table name is contained in a Systems Manager parameter named self.param_helper.table.
                         To simulate a failure of the recommendation service, let's set this parameter to name a non-existent table.
                        """);
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        System.out.println(
                """
                         \nNow, sending a GET request to the load balancer endpoint returns a failure code. But, the service reports as
                         healthy to the load balancer because shallow health checks don't check for failure of the recommendation service.
                        """);
        demoChoices(loadBalancer);

        System.out.println(
                """
                        Instead of failing when the recommendation service fails, the web service can return a static response.
                        While this is not a perfect solution, it presents the customer with a somewhat better experience than failure.
                        """);
        paramHelper.put(paramHelper.failureResponse, "static");

        System.out.println("""
                Now, sending a GET request to the load balancer endpoint returns a static response.
                The service still reports as healthy because health checks are still shallow.
                """);
        demoChoices(loadBalancer);

        System.out.println("Let's reinstate the recommendation service.");
        paramHelper.put(paramHelper.tableName, paramHelper.dyntable);

        System.out.println("""
                Let's also substitute bad credentials for one of the instances in the target group so that it can't
                access the DynamoDB recommendation table. We will get an instance id value.
                """);

        LaunchTemplateCreator templateCreator = new LaunchTemplateCreator();
        AutoScaler autoScaler = new AutoScaler();

        // Create a new instance profile based on badCredsProfileName.
        templateCreator.createInstanceProfile(policyFile, policyName, badCredsProfileName, roleName);
        String badInstanceId = autoScaler.getBadInstance(autoScalingGroupName);
        System.out.println("The bad instance id values used for this demo is " + badInstanceId);

        String profileAssociationId = autoScaler.getInstanceProfile(badInstanceId);
        System.out.println("The association Id value is " + profileAssociationId);
        System.out.println("Replacing the profile for instance " + badInstanceId
                + " with a profile that contains bad credentials");
        autoScaler.replaceInstanceProfile(badInstanceId, badCredsProfileName, profileAssociationId);

        System.out.println(
                """
                        Now, sending a GET request to the load balancer endpoint returns either a recommendation or a static response,
                        depending on which instance is selected by the load balancer.
                        """);

        demoChoices(loadBalancer);

        System.out.println("""
                Let's implement a deep health check. For this demo, a deep health check tests whether
                the web service can access the DynamoDB table that it depends on for recommendations. Note that
                the deep health check is only for ELB routing and not for Auto Scaling instance health.
                This kind of deep health check is not recommended for Auto Scaling instance health, because it
                risks accidental termination of all instances in the Auto Scaling group when a dependent service fails.
                """);

        System.out.println("""
                By implementing deep health checks, the load balancer can detect when one of the instances is failing
                and take that instance out of rotation.
                """);

        paramHelper.put(paramHelper.healthCheck, "deep");

        System.out.println("""
                Now, checking target health indicates that the instance with bad credentials
                is unhealthy. Note that it might take a minute or two for the load balancer to detect the unhealthy
                instance. Sending a GET request to the load balancer endpoint always returns a recommendation, because
                the load balancer takes unhealthy instances out of its rotation.
                """);

        demoChoices(loadBalancer);

        System.out.println(
                """
                        Because the instances in this demo are controlled by an auto scaler, the simplest way to fix an unhealthy
                        instance is to terminate it and let the auto scaler start a new instance to replace it.
                        """);
        autoScaler.terminateInstance(badInstanceId);

        System.out.println("""
                Even while the instance is terminating and the new instance is starting, sending a GET
                request to the web service continues to get a successful recommendation response because
                the load balancer routes requests to the healthy instances. After the replacement instance
                starts and reports as healthy, it is included in the load balancing rotation.
                Note that terminating and replacing an instance typically takes several minutes, during which time you
                can see the changing health check status until the new instance is running and healthy.
                """);

        demoChoices(loadBalancer);
        System.out.println(
                "If the recommendation service fails now, deep health checks mean all instances report as unhealthy.");
        paramHelper.put(paramHelper.tableName, "this-is-not-a-table");

        demoChoices(loadBalancer);
        paramHelper.reset();
    }

    public static void demoChoices(LoadBalancer loadBalancer) throws IOException, InterruptedException {
        String[] actions = {
                "Send a GET request to the load balancer endpoint.",
                "Check the health of load balancer targets.",
                "Go to the next part of the demo."
        };
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("-".repeat(88));
            System.out.println("See the current state of the service by selecting one of the following choices:");
            for (int i = 0; i < actions.length; i++) {
                System.out.println(i + ": " + actions[i]);
            }

            try {
                System.out.print("\nWhich action would you like to take? ");
                int choice = scanner.nextInt();
                System.out.println("-".repeat(88));

                switch (choice) {
                    case 0 -> {
                        System.out.println("Request:\n");
                        System.out.println("GET http://" + loadBalancer.getEndpoint(lbName));
                        CloseableHttpClient httpClient = HttpClients.createDefault();

                        // Create an HTTP GET request to the ELB.
                        HttpGet httpGet = new HttpGet("http://" + loadBalancer.getEndpoint(lbName));

                        // Execute the request and get the response.
                        HttpResponse response = httpClient.execute(httpGet);
                        int statusCode = response.getStatusLine().getStatusCode();
                        System.out.println("HTTP Status Code: " + statusCode);

                        // Display the JSON response
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(response.getEntity().getContent()));
                        StringBuilder jsonResponse = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            jsonResponse.append(line);
                        }
                        reader.close();

                        // Print the formatted JSON response.
                        System.out.println("Full Response:\n");
                        System.out.println(jsonResponse.toString());

                        // Close the HTTP client.
                        httpClient.close();

                    }
                    case 1 -> {
                        System.out.println("\nChecking the health of load balancer targets:\n");
                        List<TargetHealthDescription> health = loadBalancer.checkTargetHealth(targetGroupName);
                        for (TargetHealthDescription target : health) {
                            System.out.printf("\tTarget %s on port %d is %s%n", target.target().id(),
                                    target.target().port(), target.targetHealth().stateAsString());
                        }
                        System.out.println("""
                                Note that it can take a minute or two for the health check to update
                                after changes are made.
                                """);
                    }
                    case 2 -> {
                        System.out.println("\nOkay, let's move on.");
                        System.out.println("-".repeat(88));
                        return; // Exit the method when choice is 2
                    }
                    default -> System.out.println("You must choose a value between 0-2. Please select again.");
                }

            } catch (java.util.InputMismatchException e) {
                System.out.println("Invalid input. Please select again.");
                scanner.nextLine(); // Clear the input buffer.
            }
        }
    }

    public static String readFileAsString(String filePath) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        return new String(bytes);
    }
}
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
public class AutoScaler {

    private static Ec2Client ec2Client;
    private static AutoScalingClient autoScalingClient;
    private static IamClient iamClient;

    private static SsmClient ssmClient;

    private IamClient getIAMClient() {
        if (iamClient == null) {
            iamClient = IamClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return iamClient;
    }

    private SsmClient getSSMClient() {
        if (ssmClient == null) {
            ssmClient = SsmClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ssmClient;
    }

    private Ec2Client getEc2Client() {
        if (ec2Client == null) {
            ec2Client = Ec2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return ec2Client;
    }

    private AutoScalingClient getAutoScalingClient() {
        if (autoScalingClient == null) {
            autoScalingClient = AutoScalingClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return autoScalingClient;
    }

    /**
     * Terminates and instances in an EC2 Auto Scaling group. After an instance is
     * terminated, it can no longer be accessed.
     */
    public void terminateInstance(String instanceId) {
        TerminateInstanceInAutoScalingGroupRequest terminateInstanceIRequest = TerminateInstanceInAutoScalingGroupRequest
                .builder()
                .instanceId(instanceId)
                .shouldDecrementDesiredCapacity(false)
                .build();

        getAutoScalingClient().terminateInstanceInAutoScalingGroup(terminateInstanceIRequest);
        System.out.format("Terminated instance %s.", instanceId);
    }

    /**
     * Replaces the profile associated with a running instance. After the profile is
     * replaced, the instance is rebooted to ensure that it uses the new profile.
     * When
     * the instance is ready, Systems Manager is used to restart the Python web
     * server.
     */
    public void replaceInstanceProfile(String instanceId, String newInstanceProfileName, String profileAssociationId)
            throws InterruptedException {
        // Create an IAM instance profile specification.
        software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification iamInstanceProfile = software.amazon.awssdk.services.ec2.model.IamInstanceProfileSpecification
                .builder()
                .name(newInstanceProfileName) // Make sure 'newInstanceProfileName' is a valid IAM Instance Profile
                                              // name.
                .build();

        // Replace the IAM instance profile association for the EC2 instance.
        ReplaceIamInstanceProfileAssociationRequest replaceRequest = ReplaceIamInstanceProfileAssociationRequest
                .builder()
                .iamInstanceProfile(iamInstanceProfile)
                .associationId(profileAssociationId) // Make sure 'profileAssociationId' is a valid association ID.
                .build();

        try {
            getEc2Client().replaceIamInstanceProfileAssociation(replaceRequest);
            // Handle the response as needed.
        } catch (Ec2Exception e) {
            // Handle exceptions, log, or report the error.
            System.err.println("Error: " + e.getMessage());
        }
        System.out.format("Replaced instance profile for association %s with profile %s.", profileAssociationId,
                newInstanceProfileName);
        TimeUnit.SECONDS.sleep(15);
        boolean instReady = false;
        int tries = 0;

        // Reboot after 60 seconds
        while (!instReady) {
            if (tries % 6 == 0) {
                getEc2Client().rebootInstances(RebootInstancesRequest.builder()
                        .instanceIds(instanceId)
                        .build());
                System.out.println("Rebooting instance " + instanceId + " and waiting for it to be ready.");
            }
            tries++;
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            DescribeInstanceInformationResponse informationResponse = getSSMClient().describeInstanceInformation();
            List<InstanceInformation> instanceInformationList = informationResponse.instanceInformationList();
            for (InstanceInformation info : instanceInformationList) {
                if (info.instanceId().equals(instanceId)) {
                    instReady = true;
                    break;
                }
            }
        }

        SendCommandRequest sendCommandRequest = SendCommandRequest.builder()
                .instanceIds(instanceId)
                .documentName("AWS-RunShellScript")
                .parameters(Collections.singletonMap("commands",
                        Collections.singletonList("cd / && sudo python3 server.py 80")))
                .build();

        getSSMClient().sendCommand(sendCommandRequest);
        System.out.println("Restarted the Python web server on instance " + instanceId + ".");
    }

    public void openInboundPort(String secGroupId, String port, String ipAddress) {
        AuthorizeSecurityGroupIngressRequest ingressRequest = AuthorizeSecurityGroupIngressRequest.builder()
                .groupName(secGroupId)
                .cidrIp(ipAddress)
                .fromPort(Integer.parseInt(port))
                .build();

        getEc2Client().authorizeSecurityGroupIngress(ingressRequest);
        System.out.format("Authorized ingress to %s on port %s from %s.", secGroupId, port, ipAddress);
    }

    /**
     * Detaches a role from an instance profile, detaches policies from the role,
     * and deletes all the resources.
     */
    public void deleteInstanceProfile(String roleName, String profileName) {
        try {
            software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest getInstanceProfileRequest = software.amazon.awssdk.services.iam.model.GetInstanceProfileRequest
                    .builder()
                    .instanceProfileName(profileName)
                    .build();

            GetInstanceProfileResponse response = getIAMClient().getInstanceProfile(getInstanceProfileRequest);
            String name = response.instanceProfile().instanceProfileName();
            System.out.println(name);

            RemoveRoleFromInstanceProfileRequest profileRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .roleName(roleName)
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(profileRequest);
            DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                    .instanceProfileName(profileName)
                    .build();

            getIAMClient().deleteInstanceProfile(deleteInstanceProfileRequest);
            System.out.println("Deleted instance profile " + profileName);

            DeleteRoleRequest deleteRoleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            // List attached role policies.
            ListAttachedRolePoliciesResponse rolesResponse = getIAMClient()
                    .listAttachedRolePolicies(role -> role.roleName(roleName));
            List<AttachedPolicy> attachedPolicies = rolesResponse.attachedPolicies();
            for (AttachedPolicy attachedPolicy : attachedPolicies) {
                DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
                        .roleName(roleName)
                        .policyArn(attachedPolicy.policyArn())
                        .build();

                getIAMClient().detachRolePolicy(request);
                System.out.println("Detached and deleted policy " + attachedPolicy.policyName());
            }

            getIAMClient().deleteRole(deleteRoleRequest);
            System.out.println("Instance profile and role deleted.");

        } catch (IamException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public void deleteTemplate(String templateName) {
        getEc2Client().deleteLaunchTemplate(name -> name.launchTemplateName(templateName));
        System.out.format(templateName + " was deleted.");
    }

    public void deleteAutoScaleGroup(String groupName) {
        DeleteAutoScalingGroupRequest deleteAutoScalingGroupRequest = DeleteAutoScalingGroupRequest.builder()
                .autoScalingGroupName(groupName)
                .forceDelete(true)
                .build();

        getAutoScalingClient().deleteAutoScalingGroup(deleteAutoScalingGroupRequest);
        System.out.println(groupName + " was deleted.");
    }

    /*
     * Verify the default security group of the specified VPC allows ingress from
     * this
     * computer. This can be done by allowing ingress from this computer's IP
     * address. In some situations, such as connecting from a corporate network, you
     * must instead specify a prefix list ID. You can also temporarily open the port
     * to
     * any IP address while running this example. If you do, be sure to remove
     * public
     * access when you're done.
     * 
     */
    public GroupInfo verifyInboundPort(String VPC, int port, String ipAddress) {
        boolean portIsOpen = false;
        GroupInfo groupInfo = new GroupInfo();
        try {
            Filter filter = Filter.builder()
                    .name("group-name")
                    .values("default")
                    .build();

            Filter filter1 = Filter.builder()
                    .name("vpc-id")
                    .values(VPC)
                    .build();

            DescribeSecurityGroupsRequest securityGroupsRequest = DescribeSecurityGroupsRequest.builder()
                    .filters(filter, filter1)
                    .build();

            DescribeSecurityGroupsResponse securityGroupsResponse = getEc2Client()
                    .describeSecurityGroups(securityGroupsRequest);
            String securityGroup = securityGroupsResponse.securityGroups().get(0).groupName();
            groupInfo.setGroupName(securityGroup);

            for (SecurityGroup secGroup : securityGroupsResponse.securityGroups()) {
                System.out.println("Found security group: " + secGroup.groupId());

                for (IpPermission ipPermission : secGroup.ipPermissions()) {
                    if (ipPermission.fromPort() == port) {
                        System.out.println("Found inbound rule: " + ipPermission);
                        for (IpRange ipRange : ipPermission.ipRanges()) {
                            String cidrIp = ipRange.cidrIp();
                            if (cidrIp.startsWith(ipAddress) || cidrIp.equals("0.0.0.0/0")) {
                                System.out.println(cidrIp + " is applicable");
                                portIsOpen = true;
                            }
                        }

                        if (!ipPermission.prefixListIds().isEmpty()) {
                            System.out.println("Prefix lList is applicable");
                            portIsOpen = true;
                        }

                        if (!portIsOpen) {
                            System.out
                                    .println("The inbound rule does not appear to be open to either this computer's IP,"
                                            + " all IP addresses (0.0.0.0/0), or to a prefix list ID.");
                        } else {
                            break;
                        }
                    }
                }
            }

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }

        groupInfo.setPortOpen(portIsOpen);
        return groupInfo;
    }

    /*
     * Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto
     * Scaling group.
     * The target group specifies how the load balancer forward requests to the
     * instances
     * in the group.
     */
    public void attachLoadBalancerTargetGroup(String asGroupName, String targetGroupARN) {
        try {
            AttachLoadBalancerTargetGroupsRequest targetGroupsRequest = AttachLoadBalancerTargetGroupsRequest.builder()
                    .autoScalingGroupName(asGroupName)
                    .targetGroupARNs(targetGroupARN)
                    .build();

            getAutoScalingClient().attachLoadBalancerTargetGroups(targetGroupsRequest);
            System.out.println("Attached load balancer to " + asGroupName);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Creates an EC2 Auto Scaling group with the specified size.
    public String[] createGroup(int groupSize, String templateName, String autoScalingGroupName) {

        // Get availability zones.
        software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest zonesRequest = software.amazon.awssdk.services.ec2.model.DescribeAvailabilityZonesRequest
                .builder()
                .build();

        DescribeAvailabilityZonesResponse zonesResponse = getEc2Client().describeAvailabilityZones(zonesRequest);
        List<String> availabilityZoneNames = zonesResponse.availabilityZones().stream()
                .map(software.amazon.awssdk.services.ec2.model.AvailabilityZone::zoneName)
                .collect(Collectors.toList());

        String availabilityZones = String.join(",", availabilityZoneNames);
        LaunchTemplateSpecification specification = LaunchTemplateSpecification.builder()
                .launchTemplateName(templateName)
                .version("$Default")
                .build();

        String[] zones = availabilityZones.split(",");
        CreateAutoScalingGroupRequest groupRequest = CreateAutoScalingGroupRequest.builder()
                .launchTemplate(specification)
                .availabilityZones(zones)
                .maxSize(groupSize)
                .minSize(groupSize)
                .autoScalingGroupName(autoScalingGroupName)
                .build();

        try {
            getAutoScalingClient().createAutoScalingGroup(groupRequest);

        } catch (AutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Created an EC2 Auto Scaling group named " + autoScalingGroupName);
        return zones;
    }

    public String getDefaultVPC() {
        // Define the filter.
        Filter defaultFilter = Filter.builder()
                .name("is-default")
                .values("true")
                .build();

        software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest request = software.amazon.awssdk.services.ec2.model.DescribeVpcsRequest
                .builder()
                .filters(defaultFilter)
                .build();

        DescribeVpcsResponse response = getEc2Client().describeVpcs(request);
        return response.vpcs().get(0).vpcId();
    }

    // Gets the default subnets in a VPC for a specified list of Availability Zones.
    public List<Subnet> getSubnets(String vpcId, String[] availabilityZones) {
        List<Subnet> subnets = null;
        Filter vpcFilter = Filter.builder()
                .name("vpc-id")
                .values(vpcId)
                .build();

        Filter azFilter = Filter.builder()
                .name("availability-zone")
                .values(availabilityZones)
                .build();

        Filter defaultForAZ = Filter.builder()
                .name("default-for-az")
                .values("true")
                .build();

        DescribeSubnetsRequest request = DescribeSubnetsRequest.builder()
                .filters(vpcFilter, azFilter, defaultForAZ)
                .build();

        DescribeSubnetsResponse response = getEc2Client().describeSubnets(request);
        subnets = response.subnets();
        return subnets;
    }

    // Gets data about the instances in the EC2 Auto Scaling group.
    public String getBadInstance(String groupName) {
        DescribeAutoScalingGroupsRequest request = DescribeAutoScalingGroupsRequest.builder()
                .autoScalingGroupNames(groupName)
                .build();

        DescribeAutoScalingGroupsResponse response = getAutoScalingClient().describeAutoScalingGroups(request);
        AutoScalingGroup autoScalingGroup = response.autoScalingGroups().get(0);
        List<String> instanceIds = autoScalingGroup.instances().stream()
                .map(instance -> instance.instanceId())
                .collect(Collectors.toList());

        String[] instanceIdArray = instanceIds.toArray(new String[0]);
        for (String instanceId : instanceIdArray) {
            System.out.println("Instance ID: " + instanceId);
            return instanceId;
        }
        return "";
    }

    // Gets data about the profile associated with an instance.
    public String getInstanceProfile(String instanceId) {
        Filter filter = Filter.builder()
                .name("instance-id")
                .values(instanceId)
                .build();

        DescribeIamInstanceProfileAssociationsRequest associationsRequest = DescribeIamInstanceProfileAssociationsRequest
                .builder()
                .filters(filter)
                .build();

        DescribeIamInstanceProfileAssociationsResponse response = getEc2Client()
                .describeIamInstanceProfileAssociations(associationsRequest);
        return response.iamInstanceProfileAssociations().get(0).associationId();
    }

    public void deleteRolesPolicies(String policyName, String roleName, String InstanceProfile) {
        ListPoliciesRequest listPoliciesRequest = ListPoliciesRequest.builder().build();
        ListPoliciesResponse listPoliciesResponse = getIAMClient().listPolicies(listPoliciesRequest);
        for (Policy policy : listPoliciesResponse.policies()) {
            if (policy.policyName().equals(policyName)) {
                // List the entities (users, groups, roles) that are attached to the policy.
                software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest listEntitiesRequest = software.amazon.awssdk.services.iam.model.ListEntitiesForPolicyRequest
                        .builder()
                        .policyArn(policy.arn())
                        .build();
                ListEntitiesForPolicyResponse listEntitiesResponse = iamClient
                        .listEntitiesForPolicy(listEntitiesRequest);
                if (!listEntitiesResponse.policyGroups().isEmpty() || !listEntitiesResponse.policyUsers().isEmpty()
                        || !listEntitiesResponse.policyRoles().isEmpty()) {
                    // Detach the policy from any entities it is attached to.
                    DetachRolePolicyRequest detachPolicyRequest = DetachRolePolicyRequest.builder()
                            .policyArn(policy.arn())
                            .roleName(roleName) // Specify the name of the IAM role
                            .build();

                    getIAMClient().detachRolePolicy(detachPolicyRequest);
                    System.out.println("Policy detached from entities.");
                }

                // Now, you can delete the policy.
                DeletePolicyRequest deletePolicyRequest = DeletePolicyRequest.builder()
                        .policyArn(policy.arn())
                        .build();

                getIAMClient().deletePolicy(deletePolicyRequest);
                System.out.println("Policy deleted successfully.");
                break;
            }
        }

        // List the roles associated with the instance profile
        ListInstanceProfilesForRoleRequest listRolesRequest = ListInstanceProfilesForRoleRequest.builder()
                .roleName(roleName)
                .build();

        // Detach the roles from the instance profile
        ListInstanceProfilesForRoleResponse listRolesResponse = iamClient.listInstanceProfilesForRole(listRolesRequest);
        for (software.amazon.awssdk.services.iam.model.InstanceProfile profile : listRolesResponse.instanceProfiles()) {
            RemoveRoleFromInstanceProfileRequest removeRoleRequest = RemoveRoleFromInstanceProfileRequest.builder()
                    .instanceProfileName(InstanceProfile)
                    .roleName(roleName) // Remove the extra dot here
                    .build();

            getIAMClient().removeRoleFromInstanceProfile(removeRoleRequest);
            System.out.println("Role " + roleName + " removed from instance profile " + InstanceProfile);
        }

        // Delete the instance profile after removing all roles
        DeleteInstanceProfileRequest deleteInstanceProfileRequest = DeleteInstanceProfileRequest.builder()
                .instanceProfileName(InstanceProfile)
                .build();

        getIAMClient().deleteInstanceProfile(r -> r.instanceProfileName(InstanceProfile));
        System.out.println(InstanceProfile + " Deleted");
        System.out.println("All roles and policies are deleted.");
    }
}
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
public class LoadBalancer {
    public ElasticLoadBalancingV2Client elasticLoadBalancingV2Client;

    public ElasticLoadBalancingV2Client getLoadBalancerClient() {
        if (elasticLoadBalancingV2Client == null) {
            elasticLoadBalancingV2Client = ElasticLoadBalancingV2Client.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }

        return elasticLoadBalancingV2Client;
    }

    // Checks the health of the instances in the target group.
    public List<TargetHealthDescription> checkTargetHealth(String targetGroupName) {
        DescribeTargetGroupsRequest targetGroupsRequest = DescribeTargetGroupsRequest.builder()
                .names(targetGroupName)
                .build();

        DescribeTargetGroupsResponse tgResponse = getLoadBalancerClient().describeTargetGroups(targetGroupsRequest);

        DescribeTargetHealthRequest healthRequest = DescribeTargetHealthRequest.builder()
                .targetGroupArn(tgResponse.targetGroups().get(0).targetGroupArn())
                .build();

        DescribeTargetHealthResponse healthResponse = getLoadBalancerClient().describeTargetHealth(healthRequest);
        return healthResponse.targetHealthDescriptions();
    }

    // Gets the HTTP endpoint of the load balancer.
    public String getEndpoint(String lbName) {
        DescribeLoadBalancersResponse res = getLoadBalancerClient()
                .describeLoadBalancers(describe -> describe.names(lbName));
        return res.loadBalancers().get(0).dnsName();
    }

    // Deletes a load balancer.
    public void deleteLoadBalancer(String lbName) {
        try {
            // Use a waiter to delete the Load Balancer.
            DescribeLoadBalancersResponse res = getLoadBalancerClient()
                    .describeLoadBalancers(describe -> describe.names(lbName));
            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(res.loadBalancers().get(0).loadBalancerArn())
                    .build();

            getLoadBalancerClient().deleteLoadBalancer(
                    builder -> builder.loadBalancerArn(res.loadBalancers().get(0).loadBalancerArn()));
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancersDeleted(request);
            waiterResponse.matched().response().ifPresent(System.out::println);

        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(lbName + " was deleted.");
    }

    // Deletes the target group.
    public void deleteTargetGroup(String targetGroupName) {
        try {
            DescribeTargetGroupsResponse res = getLoadBalancerClient()
                    .describeTargetGroups(describe -> describe.names(targetGroupName));
            getLoadBalancerClient()
                    .deleteTargetGroup(builder -> builder.targetGroupArn(res.targetGroups().get(0).targetGroupArn()));
        } catch (ElasticLoadBalancingV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println(targetGroupName + " was deleted.");
    }

    // Verify this computer can successfully send a GET request to the load balancer
    // endpoint.
    public boolean verifyLoadBalancerEndpoint(String elbDnsName) throws IOException, InterruptedException {
        boolean success = false;
        int retries = 3;
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // Create an HTTP GET request to the ELB.
        HttpGet httpGet = new HttpGet("http://" + elbDnsName);
        try {
            while ((!success) && (retries > 0)) {
                // Execute the request and get the response.
                HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("HTTP Status Code: " + statusCode);
                if (statusCode == 200) {
                    success = true;
                } else {
                    retries--;
                    System.out.println("Got connection error from load balancer endpoint, retrying...");
                    TimeUnit.SECONDS.sleep(15);
                }
            }

        } catch (org.apache.http.conn.HttpHostConnectException e) {
            System.out.println(e.getMessage());
        }

        System.out.println("Status.." + success);
        return success;
    }

    /*
     * Creates an Elastic Load Balancing target group. The target group specifies
     * how
     * the load balancer forward requests to instances in the group and how instance
     * health is checked.
     */
    public String createTargetGroup(String protocol, int port, String vpcId, String targetGroupName) {
        CreateTargetGroupRequest targetGroupRequest = CreateTargetGroupRequest.builder()
                .healthCheckPath("/healthcheck")
                .healthCheckTimeoutSeconds(5)
                .port(port)
                .vpcId(vpcId)
                .name(targetGroupName)
                .protocol(protocol)
                .build();

        CreateTargetGroupResponse targetGroupResponse = getLoadBalancerClient().createTargetGroup(targetGroupRequest);
        String targetGroupArn = targetGroupResponse.targetGroups().get(0).targetGroupArn();
        String targetGroup = targetGroupResponse.targetGroups().get(0).targetGroupName();
        System.out.println("The " + targetGroup + " was created with ARN" + targetGroupArn);
        return targetGroupArn;
    }

    /*
     * Creates an Elastic Load Balancing load balancer that uses the specified
     * subnets
     * and forwards requests to the specified target group.
     */
    public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port,
            String protocol) {
        try {
            List<String> subnetIdStrings = subnetIds.stream()
                    .map(Subnet::subnetId)
                    .collect(Collectors.toList());

            CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder()
                    .subnets(subnetIdStrings)
                    .name(lbName)
                    .scheme("internet-facing")
                    .build();

            // Create and wait for the load balancer to become available.
            CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest);
            String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn();

            ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter();
            DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder()
                    .loadBalancerArns(lbARN)
                    .build();

            System.out.println("Waiting for Load Balancer " + lbName + " to become available.");
            WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter
                    .waitUntilLoadBalancerAvailable(request);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Load Balancer " + lbName + " is available.");

            // Get the DNS name (endpoint) of the load balancer.
            String lbDNSName = lsResponse.loadBalancers().get(0).dnsName();
            System.out.println("*** Load Balancer DNS Name: " + lbDNSName);

            // Create a listener for the load balance.
            Action action = Action.builder()
                    .targetGroupArn(targetGroupARN)
                    .type("forward")
                    .build();

            CreateListenerRequest listenerRequest = CreateListenerRequest.builder()
                    .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn())
                    .defaultActions(action)
                    .port(port)
                    .protocol(protocol)
                    .build();

            getLoadBalancerClient().createListener(listenerRequest);
            System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group "
                    + targetGroupARN);

            // Return the load balancer DNS name.
            return lbDNSName;

        } catch (ElasticLoadBalancingV2Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
public class Database {

    private static DynamoDbClient dynamoDbClient;

    public static DynamoDbClient getDynamoDbClient() {
        if (dynamoDbClient == null) {
            dynamoDbClient = DynamoDbClient.builder()
                    .region(Region.US_EAST_1)
                    .build();
        }
        return dynamoDbClient;
    }

    // Checks to see if the Amazon DynamoDB table exists.
    private boolean doesTableExist(String tableName) {
        try {
            // Describe the table and catch any exceptions.
            DescribeTableRequest describeTableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            getDynamoDbClient().describeTable(describeTableRequest);
            System.out.println("Table '" + tableName + "' exists.");
            return true;

        } catch (ResourceNotFoundException e) {
            System.out.println("Table '" + tableName + "' does not exist.");
        } catch (DynamoDbException e) {
            System.err.println("Error checking table existence: " + e.getMessage());
        }
        return false;
    }

    /*
     * Creates a DynamoDB table to use a recommendation service. The table has a
     * hash key named 'MediaType' that defines the type of media recommended, such
     * as
     * Book or Movie, and a range key named 'ItemId' that, combined with the
     * MediaType,
     * forms a unique identifier for the recommended item.
     */
    public void createTable(String tableName, String fileName) throws IOException {
        // First check to see if the table exists.
        boolean doesExist = doesTableExist(tableName);
        if (!doesExist) {
            DynamoDbWaiter dbWaiter = getDynamoDbClient().waiter();
            CreateTableRequest createTableRequest = CreateTableRequest.builder()
                    .tableName(tableName)
                    .attributeDefinitions(
                            AttributeDefinition.builder()
                                    .attributeName("MediaType")
                                    .attributeType(ScalarAttributeType.S)
                                    .build(),
                            AttributeDefinition.builder()
                                    .attributeName("ItemId")
                                    .attributeType(ScalarAttributeType.N)
                                    .build())
                    .keySchema(
                            KeySchemaElement.builder()
                                    .attributeName("MediaType")
                                    .keyType(KeyType.HASH)
                                    .build(),
                            KeySchemaElement.builder()
                                    .attributeName("ItemId")
                                    .keyType(KeyType.RANGE)
                                    .build())
                    .provisionedThroughput(
                            ProvisionedThroughput.builder()
                                    .readCapacityUnits(5L)
                                    .writeCapacityUnits(5L)
                                    .build())
                    .build();

            getDynamoDbClient().createTable(createTableRequest);
            System.out.println("Creating table " + tableName + "...");

            // Wait until the Amazon DynamoDB table is created.
            DescribeTableRequest tableRequest = DescribeTableRequest.builder()
                    .tableName(tableName)
                    .build();

            WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("Table " + tableName + " created.");

            // Add records to the table.
            populateTable(fileName, tableName);
        }
    }

    public void deleteTable(String tableName) {
        getDynamoDbClient().deleteTable(table -> table.tableName(tableName));
        System.out.println("Table " + tableName + " deleted.");
    }

    // Populates the table with data located in a JSON file using the DynamoDB
    // enhanced client.
    public void populateTable(String fileName, String tableName) throws IOException {
        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(getDynamoDbClient())
                .build();
        ObjectMapper objectMapper = new ObjectMapper();
        File jsonFile = new File(fileName);
        JsonNode rootNode = objectMapper.readTree(jsonFile);

        DynamoDbTable<Recommendation> mappedTable = enhancedClient.table(tableName,
                TableSchema.fromBean(Recommendation.class));
        for (JsonNode currentNode : rootNode) {
            String mediaType = currentNode.path("MediaType").path("S").asText();
            int itemId = currentNode.path("ItemId").path("N").asInt();
            String title = currentNode.path("Title").path("S").asText();
            String creator = currentNode.path("Creator").path("S").asText();

            // Create a Recommendation object and set its properties.
            Recommendation rec = new Recommendation();
            rec.setMediaType(mediaType);
            rec.setItemId(itemId);
            rec.setTitle(title);
            rec.setCreator(creator);

            // Put the item into the DynamoDB table.
            mappedTable.putItem(rec); // Add the Recommendation to the list.
        }
        System.out.println("Added all records to the " + tableName);
    }
}
```
Systems Manager のアクションをラップするクラスを作成します。  

```
public class ParameterHelper {

    String tableName = "doc-example-resilient-architecture-table";
    String dyntable = "doc-example-recommendation-service";
    String failureResponse = "doc-example-resilient-architecture-failure-response";
    String healthCheck = "doc-example-resilient-architecture-health-check";

    public void reset() {
        put(dyntable, tableName);
        put(failureResponse, "none");
        put(healthCheck, "shallow");
    }

    public void put(String name, String value) {
        SsmClient ssmClient = SsmClient.builder()
                .region(Region.US_EAST_1)
                .build();

        PutParameterRequest parameterRequest = PutParameterRequest.builder()
                .name(name)
                .value(value)
                .overwrite(true)
                .type("String")
                .build();

        ssmClient.putParameter(parameterRequest);
        System.out.printf("Setting demo parameter %s to '%s'.", name, value);
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/SdkForJavaV2/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/SdkForJavaV2/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/autoscaling-2011-01-01/UpdateAutoScalingGroup)

### IAM Policy Builder API を使用する
<a name="iam_Scenario_IamPolicyBuilder_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ オブジェクト指向の API を使用して IAM ポリシーを作成します。
+ IAM サービスで IAM Policy Builder API を使用します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iam#code-examples)での設定と実行の方法を確認してください。
例では、次の入力を使用します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.policybuilder.iam.IamConditionOperator;
import software.amazon.awssdk.policybuilder.iam.IamEffect;
import software.amazon.awssdk.policybuilder.iam.IamPolicy;
import software.amazon.awssdk.policybuilder.iam.IamPolicyWriter;
import software.amazon.awssdk.policybuilder.iam.IamPrincipal;
import software.amazon.awssdk.policybuilder.iam.IamPrincipalType;
import software.amazon.awssdk.policybuilder.iam.IamResource;
import software.amazon.awssdk.policybuilder.iam.IamStatement;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.GetPolicyResponse;
import software.amazon.awssdk.services.iam.model.GetPolicyVersionResponse;
import software.amazon.awssdk.services.sts.StsClient;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
```
時間ベースのポリシーを作成します。  

```
        public String timeBasedPolicyExample() {
                IamPolicy policy = IamPolicy.builder()
                                .addStatement(b -> b
                                                .effect(IamEffect.ALLOW)
                                                .addAction("dynamodb:GetItem")
                                                .addResource(IamResource.ALL)
                                                .addCondition(b1 -> b1
                                                                .operator(IamConditionOperator.DATE_GREATER_THAN)
                                                                .key("aws:CurrentTime")
                                                                .value("2020-04-01T00:00:00Z"))
                                                .addCondition(b1 -> b1
                                                                .operator(IamConditionOperator.DATE_LESS_THAN)
                                                                .key("aws:CurrentTime")
                                                                .value("2020-06-30T23:59:59Z")))
                                .build();

                // Use an IamPolicyWriter to write out the JSON string to a more readable
                // format.
                return policy.toJson(IamPolicyWriter.builder()
                                .prettyPrint(true)
                                .build());
        }
```
複数の条件を含むポリシーを作成します。  

```
        public String multipleConditionsExample() {
                IamPolicy policy = IamPolicy.builder()
                                .addStatement(b -> b
                                                .effect(IamEffect.ALLOW)
                                                .addAction("dynamodb:GetItem")
                                                .addAction("dynamodb:BatchGetItem")
                                                .addAction("dynamodb:Query")
                                                .addAction("dynamodb:PutItem")
                                                .addAction("dynamodb:UpdateItem")
                                                .addAction("dynamodb:DeleteItem")
                                                .addAction("dynamodb:BatchWriteItem")
                                                .addResource("arn:aws:dynamodb:*:*:table/table-name")
                                                .addConditions(IamConditionOperator.STRING_EQUALS
                                                                .addPrefix("ForAllValues:"),
                                                                "dynamodb:Attributes",
                                                                List.of("column-name1", "column-name2", "column-name3"))
                                                .addCondition(b1 -> b1
                                                                .operator(IamConditionOperator.STRING_EQUALS
                                                                                .addSuffix("IfExists"))
                                                                .key("dynamodb:Select")
                                                                .value("SPECIFIC_ATTRIBUTES")))
                                .build();

                return policy.toJson(IamPolicyWriter.builder()
                                .prettyPrint(true).build());
        }
```
ポリシーにプリンシパルを使用します。  

```
        public String specifyPrincipalsExample() {
                IamPolicy policy = IamPolicy.builder()
                                .addStatement(b -> b
                                                .effect(IamEffect.DENY)
                                                .addAction("s3:*")
                                                .addPrincipal(IamPrincipal.ALL)
                                                .addResource("arn:aws:s3:::amzn-s3-demo-bucket/*")
                                                .addResource("arn:aws:s3:::amzn-s3-demo-bucket")
                                                .addCondition(b1 -> b1
                                                                .operator(IamConditionOperator.ARN_NOT_EQUALS)
                                                                .key("aws:PrincipalArn")
                                                                .value("arn:aws:iam::444455556666:user/user-name")))
                                .build();
                return policy.toJson(IamPolicyWriter.builder()
                                .prettyPrint(true).build());
        }
```
クロスアカウントのアクセスを許可します。  

```
        public String allowCrossAccountAccessExample() {
                IamPolicy policy = IamPolicy.builder()
                                .addStatement(b -> b
                                                .effect(IamEffect.ALLOW)
                                                .addPrincipal(IamPrincipalType.AWS, "111122223333")
                                                .addAction("s3:PutObject")
                                                .addResource("arn:aws:s3:::amzn-s3-demo-bucket/*")
                                                .addCondition(b1 -> b1
                                                                .operator(IamConditionOperator.STRING_EQUALS)
                                                                .key("s3:x-amz-acl")
                                                                .value("bucket-owner-full-control")))
                                .build();
                return policy.toJson(IamPolicyWriter.builder()
                                .prettyPrint(true).build());
        }
```
`IamPolicy` を作成してアップロードします。  

```
        public String createAndUploadPolicyExample(IamClient iam, String accountID, String policyName) {
                // Build the policy.
                IamPolicy policy = IamPolicy.builder() // 'version' defaults to "2012-10-17".
                                .addStatement(IamStatement.builder()
                                                .effect(IamEffect.ALLOW)
                                                .addAction("dynamodb:PutItem")
                                                .addResource("arn:aws:dynamodb:us-east-1:" + accountID
                                                                + ":table/exampleTableName")
                                                .build())
                                .build();
                // Upload the policy.
                iam.createPolicy(r -> r.policyName(policyName).policyDocument(policy.toJson()));
                return policy.toJson(IamPolicyWriter.builder().prettyPrint(true).build());
        }
```
`IamPolicy` をダウンロードして使用します。  

```
        public String createNewBasedOnExistingPolicyExample(IamClient iam, String accountID, String policyName,
                        String newPolicyName) {

                String policyArn = "arn:aws:iam::" + accountID + ":policy/" + policyName;
                GetPolicyResponse getPolicyResponse = iam.getPolicy(r -> r.policyArn(policyArn));

                String policyVersion = getPolicyResponse.policy().defaultVersionId();
                GetPolicyVersionResponse getPolicyVersionResponse = iam
                                .getPolicyVersion(r -> r.policyArn(policyArn).versionId(policyVersion));

                // Create an IamPolicy instance from the JSON string returned from IAM.
                String decodedPolicy = URLDecoder.decode(getPolicyVersionResponse.policyVersion().document(),
                                StandardCharsets.UTF_8);
                IamPolicy policy = IamPolicy.fromJson(decodedPolicy);

                /*
                 * All IamPolicy components are immutable, so use the copy method that creates a
                 * new instance that
                 * can be altered in the same method call.
                 * 
                 * Add the ability to get an item from DynamoDB as an additional action.
                 */
                IamStatement newStatement = policy.statements().get(0).copy(s -> s.addAction("dynamodb:GetItem"));

                // Create a new statement that replaces the original statement.
                IamPolicy newPolicy = policy.copy(p -> p.statements(Arrays.asList(newStatement)));

                // Upload the new policy. IAM now has both policies.
                iam.createPolicy(r -> r.policyName(newPolicyName)
                                .policyDocument(newPolicy.toJson()));

                return newPolicy.toJson(IamPolicyWriter.builder().prettyPrint(true).build());
        }
```
+  詳細については、「[AWS SDK for Java 2.x デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/feature-iam-policy-builder.html)」を参照してください。
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/CreatePolicy)
  + [GetPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/GetPolicy)
  + [GetPolicyVersion](https://docs.aws.amazon.com/goto/SdkForJavaV2/iam-2010-05-08/GetPolicyVersion)

# SDK for Java 2.x を使用した Amazon Inspector の例
<a name="java_2_inspector_code_examples"></a>

次のコード例は、Amazon Inspector AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello
<a name="inspector_Hello_java_2_topic"></a>

次のコード例は、 の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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 HelloInspector {
    private static final Logger logger = LoggerFactory.getLogger(HelloInspector.class);

    public static void main(String[] args) {
        logger.info("Hello Amazon Inspector!");

        try (Inspector2Client inspectorClient = Inspector2Client.builder().build()) {

            logger.info("Listing member accounts for this Inspector administrator account...");
            listMembers(inspectorClient);

            logger.info("The Hello Inspector example completed successfully.");

        } catch (Inspector2Exception e) {
            logger.error("Error: {}", e.getMessage());
            logger.info("Troubleshooting:");
            logger.info("1. Verify AWS credentials are configured");
            logger.info("2. Check IAM permissions for Inspector2");
            logger.info("3. Ensure Inspector2 is enabled in your account");
            logger.info("4. Verify you're using a supported region");
        }
    }

    /**
     * Lists all member accounts associated with the current Inspector administrator account.
     *
     * @param inspectorClient The Inspector2Client used to interact with AWS Inspector.
     */
    public static void listMembers(Inspector2Client inspectorClient) {
        try {
            ListMembersRequest request = ListMembersRequest.builder()
                    .maxResults(50) // optional: limit results
                    .build();

            ListMembersResponse response = inspectorClient.listMembers(request);
            List<Member> members = response.members();

            if (members == null || members.isEmpty()) {
                logger.info("No member accounts found for this Inspector administrator account.");
                return;
            }

            logger.info("Found {} member account(s):", members.size());
            for (Member member : members) {
                logger.info(" - Account ID: {}, Status: {}",
                        member.accountId(),
                        member.relationshipStatusAsString());
            }

        } catch (Inspector2Exception e) {
            logger.error("Failed to list members: {}", e.awsErrorDetails().errorMessage());
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[ListMembers](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListMembers)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="inspector_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Inspector アカウントのステータスを確認します。
+ Inspector が有効になっていることを確認します。
+ セキュリティの検出結果を分析します。
+ スキャンカバレッジを確認します。
+ 検出結果フィルターを作成します。
+ 既存のフィルターを一覧表示します。
+ 使用状況とコストを確認します。
+ カバレッジ統計を取得します。
+ フィルターを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。
 機能を実証するインタラクティブなシナリオを実行します。  

```
/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class InspectorScenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final Logger logger = LoggerFactory.getLogger(InspectorScenario.class);
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        InspectorActions inspectorActions = new InspectorActions();
        logger.info("Amazon Inspector Basics Scenario");

        logger.info("""
                    Amazon Inspector is a security assessment service provided by Amazon Web Services (AWS) that helps
                    improve the security and compliance of applications deployed on AWS. It automatically assesses
                    applications for vulnerabilities or deviations from best practices. By leveraging Amazon Inspector,
                    users can gain insights into the overall security state of their application and identify potential
                    security risks.
                    
                    This service operates by conducting both network and host-based assessments, allowing it to detect a
                    wide range of security issues, including those related to operating systems, network configurations,
                    and application dependencies.
                    """);

        waitForInputToContinue();

        try {
            runScenario(inspectorActions);

            logger.info("");
            logger.info("Scenario completed successfully!");
            logger.info("");
            logger.info("What you learned:");
            logger.info("  - How to check Inspector account status");
            logger.info("  - How to enable Inspector");
            logger.info("  - How to list and analyze findings");
            logger.info("  - How to check coverage information");
            logger.info("  - How to create and manage filters");
            logger.info("  - How to track usage and costs");
            logger.info("  - How to clean up resources");
            logger.info("");

        } catch (Exception ex) {
            logger.error("Scenario failed due to unexpected error: {}", ex.getMessage(), ex);

        } finally {
            scanner.close();
            logger.info("Exiting...");
        }
    }

    /**
     * Runs the Inspector scenario in a step-by-step sequence.
     *
     * All InspectorActions methods are asynchronous and return CompletableFutures.
     * Each step ends with .join(). Any async exception thrown during .join() will bubble up
     *
     */
    public static void runScenario(InspectorActions actions) {
        String filterArn = null;
        boolean inspectorEnabled = false;

        try {
            // Step 1
            logger.info(DASHES);
            logger.info("Step 1: Checking Inspector account status...");
            String status = actions.getAccountStatusAsync().join();
            logger.info(status);
            waitForInputToContinue();

            // Step 2
            logger.info(DASHES);
            logger.info("Step 2: Enabling Inspector...");
            String message = actions.enableInspectorAsync(null).join();
            logger.info(message);
            inspectorEnabled = true;  // track that Inspector was enabled
            waitForInputToContinue();

            // Step 3
            logger.info(DASHES);
            logger.info("Step 3: Listing LOW severity findings...");

            // Call the service method
            List<String> allFindings = actions.listLowSeverityFindingsAsync().join();

            if (!allFindings.isEmpty()) {
                // Only proceed if there are findings
                String lastArn = allFindings.get(allFindings.size() - 1);
                logger.info("Look up details on: {}", lastArn);
                waitForInputToContinue();
                String details = actions.getFindingDetailsAsync(lastArn).join();
                logger.info(details);
            } else {
                logger.info("No LOW severity findings found.");
            }

            waitForInputToContinue();

            // Step 4
            logger.info(DASHES);
            logger.info("Step 4: Listing coverage...");
            String coverage = actions.listCoverageAsync(5).join();
            logger.info(coverage);
            waitForInputToContinue();

            // Step 5
            logger.info(DASHES);
            logger.info("Step 5: Creating filter...");
            String filterName = "suppress-low-" + System.currentTimeMillis();
            filterArn = actions.createLowSeverityFilterAsync(filterName, "Suppress low severity findings").join();
            logger.info("Created filter: {}", filterArn);
            waitForInputToContinue();

            // Step 6
            logger.info(DASHES);
            logger.info("Step 6: Listing filters...");
            String filters = actions.listFiltersAsync(10).join();
            logger.info(filters);
            waitForInputToContinue();

            // Step 7
            logger.info(DASHES);
            logger.info("Step 7: Usage totals...");
            String usage = actions.listUsageTotalsAsync(null, 10).join();
            logger.info(usage);
            waitForInputToContinue();

            // Step 8
            logger.info(DASHES);
            logger.info("Step 8: Coverage statistics...");
            String stats = actions.listCoverageStatisticsAsync().join();
            logger.info(stats);
            waitForInputToContinue();

            // Step 9
            logger.info(DASHES);
            logger.info("Step 9: Delete filter?");
            logger.info("Filter ARN: {}", filterArn);
            logger.info("Delete the filter and disable Inspector? (y/n)");

            if (scanner.nextLine().trim().equalsIgnoreCase("y")) {
                actions.deleteFilterAsync(filterArn).join();
                logger.info("Filter deleted.");
                String disableMsg = actions.disableInspectorAsync(null).join();
                logger.info(disableMsg);
                inspectorEnabled = false; // track that Inspector was disabled
            }

            waitForInputToContinue();

        } catch (Exception ex) {
            logger.error("Scenario encountered an error: {}", ex.getMessage(), ex);
            // Rethrow the exception
            throw ex;

        } finally {
            // Cleanup in case of an exception
            if (filterArn != null) {
                try {
                    actions.deleteFilterAsync(filterArn).join();
                    logger.info("Cleanup: Filter deleted.");
                } catch (Exception e) {
                    logger.warn("Failed to delete filter during cleanup: {}", e.getMessage(), e);
                }
            }

            if (inspectorEnabled) {
                try {
                    actions.disableInspectorAsync(null).join();
                    logger.info("Cleanup: Inspector disabled.");
                } catch (Exception e) {
                    logger.warn("Failed to disable Inspector during cleanup: {}", e.getMessage(), e);
                }
            }
        }
    }

    // Utility Method
    private static void waitForInputToContinue() {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' to continue:");
            String input = scanner.nextLine().trim();
            if (input.equalsIgnoreCase("c")) break;
            logger.info("Invalid input, try again.");
        }
    }
}
```
 SDK メソッドのラッパークラス。  

```
public class InspectorActions {
    private static Inspector2AsyncClient inspectorAsyncClient;
    private static final Logger logger = LoggerFactory.getLogger(InspectorActions.class);

    private static Inspector2AsyncClient getAsyncClient() {
        if (inspectorAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                    .maxConcurrency(100)
                    .connectionTimeout(Duration.ofSeconds(60))
                    .readTimeout(Duration.ofSeconds(60))
                    .writeTimeout(Duration.ofSeconds(60))
                    .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                    .apiCallTimeout(Duration.ofMinutes(2))
                    .apiCallAttemptTimeout(Duration.ofSeconds(90))
                    .retryStrategy(RetryMode.STANDARD)
                    .build();

            inspectorAsyncClient = Inspector2AsyncClient.builder()
                    .httpClient(httpClient)
                    .overrideConfiguration(overrideConfig)
                    .build();
        }
        return inspectorAsyncClient;
    }


    /**
     * Enables AWS Inspector for the provided account(s) and default resource types.
     *
     * @param accountIds Optional list of AWS account IDs.
     */
    public CompletableFuture<String> enableInspectorAsync(List<String> accountIds) {

        // The resource types to enable.
        List<ResourceScanType> resourceTypes = List.of(
                ResourceScanType.EC2,
                ResourceScanType.ECR,
                ResourceScanType.LAMBDA,
                ResourceScanType.LAMBDA_CODE
        );

        // Build the request.
        EnableRequest.Builder requestBuilder = EnableRequest.builder()
                .resourceTypes(resourceTypes);

        if (accountIds != null && !accountIds.isEmpty()) {
            requestBuilder.accountIds(accountIds);
        }

        EnableRequest request = requestBuilder.build();
        return getAsyncClient().enable(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ValidationException) {
                            throw new CompletionException(
                                    "Inspector may already be enabled for this account: %s".formatted(cause.getMessage()),
                                    cause
                            );

                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;
                            throw new CompletionException(
                                    "AWS Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException(
                                "Failed to enable Inspector: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {
                    StringBuilder summary = new StringBuilder("Enable results:\n");

                    if (response.accounts() == null || response.accounts().isEmpty()) {
                        summary.append("Inspector may already be enabled for all target accounts.");
                        return summary.toString();
                    }

                    for (Account account : response.accounts()) {
                        String accountId = account.accountId() != null ? account.accountId() : "Unknown";
                        String status = account.status() != null ? account.statusAsString() : "Unknown";
                        summary.append(" • Account: ").append(accountId)
                                .append(" → Status: ").append(status).append("\n");
                    }

                    return summary.toString();
                });
    }


    /**
     * Retrieves and prints the coverage statistics using a paginator.
     */
    public CompletableFuture<String> listCoverageStatisticsAsync() {
        ListCoverageStatisticsRequest request = ListCoverageStatisticsRequest.builder()
                .build();

        return getAsyncClient().listCoverageStatistics(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();

                        if (cause instanceof ValidationException) {
                            throw new CompletionException(
                                    "Validation error listing coverage statistics: %s".formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;

                            throw new CompletionException(
                                    "Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    e
                            );
                        }

                        throw new CompletionException(
                                "Unexpected error listing coverage statistics: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {
                    List<Counts> countsList = response.countsByGroup();
                    StringBuilder sb = new StringBuilder();

                    if (countsList == null || countsList.isEmpty()) {
                        sb.append("No coverage statistics available.\n");
                        return sb.toString();
                    }

                    sb.append("Coverage Statistics:\n");

                    for (Counts c : countsList) {
                        sb.append("  Group: ").append(c.groupKey()).append("\n")
                                .append("    Total Count: ").append(c.count()).append("\n\n");
                    }

                    return sb.toString();
                });
    }


    /**
     * Asynchronously lists Inspector2 usage totals using a paginator.
     *
     * @param accountIds optional list of account IDs
     * @param maxResults maximum results per page
     * @return CompletableFuture completed with formatted summary text
     */
    public CompletableFuture<String> listUsageTotalsAsync(
            List<String> accountIds,
            int maxResults) {

        logger.info("Starting usage totals paginator…");

        ListUsageTotalsRequest.Builder builder = ListUsageTotalsRequest.builder()
                .maxResults(maxResults);

        if (accountIds != null && !accountIds.isEmpty()) {
            builder.accountIds(accountIds);
        }

        ListUsageTotalsRequest request = builder.build();
        ListUsageTotalsPublisher paginator = getAsyncClient().listUsageTotalsPaginator(request);
        StringBuilder summaryBuilder = new StringBuilder();

        return paginator.subscribe(response -> {
                    if (response.totals() != null && !response.totals().isEmpty()) {
                        response.totals().forEach(total -> {
                            if (total.usage() != null) {
                                total.usage().forEach(usage -> {
                                    logger.info("Usage: {} = {}", usage.typeAsString(), usage.total());
                                    summaryBuilder.append(usage.typeAsString())
                                            .append(": ")
                                            .append(usage.total())
                                            .append("\n");
                                });
                            }
                        });
                    } else {
                        logger.info("Page contained no usage totals.");
                    }
                }).thenRun(() -> logger.info("Successfully listed usage totals."))
                .thenApply(v -> {
                    String summary = summaryBuilder.toString();
                    return summary.isEmpty() ? "No usage totals found." : summary;
                }).exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ValidationException ve) {
                        throw new CompletionException(
                                "Validation error listing usage totals: %s".formatted(ve.getMessage()),
                                ve
                        );
                    }

                    throw new CompletionException("Failed to list usage totals", cause);
                });
    }



    /**
     * Retrieves the account status using the Inspector2Client.
     */
    public CompletableFuture<String> getAccountStatusAsync() {
        BatchGetAccountStatusRequest request = BatchGetAccountStatusRequest.builder()
                .accountIds(Collections.emptyList())
                .build();

        return getAsyncClient().batchGetAccountStatus(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof AccessDeniedException) {
                            throw new CompletionException(
                                    "You do not have sufficient access: %s".formatted(cause.getMessage()),
                                    cause
                            );

                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;

                            throw new CompletionException(
                                    "Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    e
                            );
                        }

                        throw new CompletionException(
                                "Unexpected error getting account status: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {

                    StringBuilder sb = new StringBuilder();
                    List<AccountState> accounts = response.accounts();

                    if (accounts == null || accounts.isEmpty()) {
                        sb.append("No account status returned.\n");
                        return sb.toString();
                    }

                    sb.append("Inspector Account Status:\n");
                    for (AccountState account : accounts) {

                        String accountId = account.accountId() != null
                                ? account.accountId()
                                : "Unknown";

                        sb.append("  Account ID: ").append(accountId).append("\n");

                        // Overall account state
                        if (account.state() != null && account.state().status() != null) {
                            sb.append("  Overall State: ")
                                    .append(account.state().status())
                                    .append("\n");
                        } else {
                            sb.append("  Overall State: Unknown\n");
                        }

                        // Resource state (only status available)
                        ResourceState resources = account.resourceState();
                        if (resources != null) {
                            sb.append("  Resource Status: available\n");
                        }

                        sb.append("\n");
                    }

                    return sb.toString();
                });
    }


    /**
     * Asynchronously lists Inspector2 filters using a paginator.
     *
     * @param maxResults maximum filters per page (nullable)
     * @return CompletableFuture completed with summary text
     */
    public CompletableFuture<String> listFiltersAsync(Integer maxResults) {
        logger.info("Starting async filters paginator…");

        ListFiltersRequest.Builder builder = ListFiltersRequest.builder();
        if (maxResults != null) {
            builder.maxResults(maxResults);
        }

        ListFiltersRequest request = builder.build();

        // Paginator from SDK
        ListFiltersPublisher paginator = getAsyncClient().listFiltersPaginator(request);
        StringBuilder collectedFilterIds = new StringBuilder();

        return paginator.subscribe(response -> {
            response.filters().forEach(filter -> {
                logger.info("Filter: " + filter.arn());
                collectedFilterIds.append(filter.arn()).append("\n");
            });
        }).thenApply(v -> {
            String result = collectedFilterIds.toString();
            logger.info("Successfully listed all filters.");
            return result.isEmpty() ? "No filters found." : result;
        }).exceptionally(ex -> {
            Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

            if (cause instanceof ValidationException ve) {
                throw new CompletionException(
                        "Validation error listing filters: %s".formatted(ve.getMessage()),
                        ve
                );
            }

            throw new RuntimeException("Failed to list filters", ex);
        });
    }


    /**
     * Creates a new LOW severity filter in AWS Inspector2 to suppress findings.
     *
     * @param filterName  the name of the filter to create
     * @param description a descriptive string explaining the purpose of the filter
     * @return a CompletableFuture that completes with the ARN of the created filter
     * @throws CompletionException wraps any validation, Inspector2 service, or unexpected errors
     */
    public CompletableFuture<String> createLowSeverityFilterAsync(
            String filterName,
            String description) {

        // Define a filter to match LOW severity findings.
        StringFilter severityFilter = StringFilter.builder()
                .value(Severity.LOW.toString())
                .comparison(StringComparison.EQUALS)
                .build();

        // Create filter criteria.
        FilterCriteria filterCriteria = FilterCriteria.builder()
                .severity(Collections.singletonList(severityFilter))
                .build();

        // Build the filter creation request.
        CreateFilterRequest request = CreateFilterRequest.builder()
                .name(filterName)
                .filterCriteria(filterCriteria)
                .action(FilterAction.SUPPRESS)
                .description(description)
                .build();

        return getAsyncClient().createFilter(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ValidationException ve) {
                            throw new CompletionException(
                                    "Validation error creating filter: %s".formatted(ve.getMessage()),
                                    ve
                            );
                        }

                        if (cause instanceof Inspector2Exception e) {
                            throw new CompletionException(
                                    "Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    e
                            );
                        }

                        // Unexpected async error
                        throw new CompletionException(
                                "Unexpected error creating filter: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                // Extract and return the ARN of the created filter.
                .thenApply(CreateFilterResponse::arn);
    }


    /**
     * Lists all AWS Inspector findings of LOW severity asynchronously.
     *
     * @return CompletableFuture containing a List of finding ARNs.
     * Returns an empty list if no LOW severity findings are found.
     */
    public CompletableFuture<ArrayList<String>> listLowSeverityFindingsAsync() {
        logger.info("Starting async LOW severity findings paginator…");

        // Build a filter criteria for LOW severity.
        StringFilter severityFilter = StringFilter.builder()
                .value(Severity.LOW.toString())
                .comparison(StringComparison.EQUALS)
                .build();

        FilterCriteria filterCriteria = FilterCriteria.builder()
                .severity(Collections.singletonList(severityFilter))
                .build();

        // Build the request.
        ListFindingsRequest request = ListFindingsRequest.builder()
                .filterCriteria(filterCriteria)
                .build();

        ListFindingsPublisher paginator = getAsyncClient().listFindingsPaginator(request);
        List<String> allArns = Collections.synchronizedList(new ArrayList<>());

        return paginator.subscribe(response -> {
                    if (response.findings() != null && !response.findings().isEmpty()) {
                        response.findings().forEach(finding -> {
                            logger.info("Finding ARN: {}", finding.findingArn());
                            allArns.add(finding.findingArn());
                        });
                    } else {
                        logger.info("Page contained no findings.");
                    }
                })
                .thenRun(() -> logger.info("Successfully listed all LOW severity findings."))
                .thenApply(v -> new ArrayList<>(allArns)) // Return list instead of a formatted string
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
                    if (cause instanceof ValidationException ve) {
                        throw new CompletionException(
                                "Validation error listing LOW severity findings: %s".formatted(ve.getMessage()),
                                ve
                        );
                    }
                    throw new RuntimeException("Failed to list LOW severity findings", ex);
                });
    }



    /**
     * Lists AWS Inspector2 coverage details for scanned resources using a paginator.
     *
     * @param maxResults Maximum number of resources to return.
     */
    public CompletableFuture<String> listCoverageAsync(int maxResults) {
        ListCoverageRequest initialRequest = ListCoverageRequest.builder()
                .maxResults(maxResults)
                .build();

        ListCoveragePublisher paginator = getAsyncClient().listCoveragePaginator(initialRequest);
        StringBuilder summary = new StringBuilder();

        return paginator.subscribe(response -> {
            List<CoveredResource> coveredResources = response.coveredResources();

            if (coveredResources == null || coveredResources.isEmpty()) {
                summary.append("No coverage information available for this page.\n");
                return;
            }

            Map<String, List<CoveredResource>> byType = coveredResources.stream()
                    .collect(Collectors.groupingBy(CoveredResource::resourceTypeAsString));

            byType.forEach((type, list) ->
                    summary.append("  ").append(type)
                            .append(": ").append(list.size())
                            .append(" resource(s)\n")
            );

            // Include up to 3 sample resources per page
            for (int i = 0; i < Math.min(coveredResources.size(), 3); i++) {
                CoveredResource r = coveredResources.get(i);
                summary.append("  - ").append(r.resourceTypeAsString())
                        .append(": ").append(r.resourceId()).append("\n");
                summary.append("    Scan Type: ").append(r.scanTypeAsString()).append("\n");
                if (r.scanStatus() != null) {
                    summary.append("    Status: ").append(r.scanStatus().statusCodeAsString()).append("\n");
                }
                if (r.accountId() != null) {
                    summary.append("    Account ID: ").append(r.accountId()).append("\n");
                }
                summary.append("\n");
            }

        }).thenApply(v -> {
            if (summary.length() == 0) {
                return "No coverage information found across all pages.";
            } else {
                return "Coverage Information:\n" + summary.toString();
            }
        }).exceptionally(ex -> {
            Throwable cause = ex.getCause();
            if (cause instanceof ValidationException) {
                throw new CompletionException(
                        "Validation error listing coverage: " + cause.getMessage(), cause);
            } else if (cause instanceof Inspector2Exception e) {
                throw new CompletionException(
                        "Inspector2 service error: " + e.awsErrorDetails().errorMessage(), e);
            }
            throw new CompletionException("Unexpected error listing coverage: " + ex.getMessage(), ex);
        });
    }


    /**
     * Deletes an AWS Inspector2 filter.
     *
     * @param filterARN The ARN of the filter to delete.
     */
    public CompletableFuture<Void> deleteFilterAsync(String filterARN) {
        return getAsyncClient().deleteFilter(
                        DeleteFilterRequest.builder()
                                .arn(filterARN)
                                .build()
                )
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException rnfe) {
                            String msg = "Filter not found for ARN: %s".formatted(filterARN);
                            logger.warn(msg, rnfe);
                            throw new CompletionException(msg, rnfe);
                        }

                        throw new RuntimeException("Failed to delete the filter: " + cause, cause);
                    }
                    return null;
                });
    }

    /**
     * Retrieves detailed information about a specific AWS Inspector2 finding asynchronously.
     *
     * @param findingArn The ARN of the finding to look up.
     * @return A {@link CompletableFuture} that, when completed, provides a formatted string
     * containing all available details for the finding.
     * @throws RuntimeException if the async call to Inspector2 fails.
     */
    public CompletableFuture<String> getFindingDetailsAsync(String findingArn) {
        BatchGetFindingDetailsRequest request = BatchGetFindingDetailsRequest.builder()
                .findingArns(findingArn)
                .build();

        return getAsyncClient().batchGetFindingDetails(request)
                .thenApply(response -> {
                    if (response.findingDetails() == null || response.findingDetails().isEmpty()) {
                        return String.format("No details found for ARN: ", findingArn);
                    }

                    StringBuilder sb = new StringBuilder();
                    response.findingDetails().forEach(detail -> {
                        sb.append("Finding ARN: ").append(detail.findingArn()).append("\n")
                                .append("Risk Score: ").append(detail.riskScore()).append("\n");

                        // ExploitObserved timings
                        if (detail.exploitObserved() != null) {
                            sb.append("Exploit First Seen: ").append(detail.exploitObserved().firstSeen()).append("\n")
                                    .append("Exploit Last Seen: ").append(detail.exploitObserved().lastSeen()).append("\n");
                        }

                        // Reference URLs
                        if (detail.hasReferenceUrls()) {
                            sb.append("Reference URLs:\n");
                            detail.referenceUrls().forEach(url -> sb.append("  • ").append(url).append("\n"));
                        }

                        // Tools
                        if (detail.hasTools()) {
                            sb.append("Tools:\n");
                            detail.tools().forEach(tool -> sb.append("  • ").append(tool).append("\n"));
                        }

                        // TTPs
                        if (detail.hasTtps()) {
                            sb.append("TTPs:\n");
                            detail.ttps().forEach(ttp -> sb.append("  • ").append(ttp).append("\n"));
                        }

                        // CWEs
                        if (detail.hasCwes()) {
                            sb.append("CWEs:\n");
                            detail.cwes().forEach(cwe -> sb.append("  • ").append(cwe).append("\n"));
                        }

                        // Evidence
                        if (detail.hasEvidences()) {
                            sb.append("Evidence:\n");
                            detail.evidences().forEach(ev -> {
                                sb.append("  - Severity: ").append(ev.severity()).append("\n");

                            });
                        }

                        sb.append("\n");
                    });

                    return sb.toString();
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ResourceNotFoundException rnfe) {
                        return "Finding not found: %s".formatted(findingArn);
                    }

                    // Fallback for other exceptions
                    throw new RuntimeException("Failed to get finding details for ARN: " + findingArn, cause);
                });
    }


    /**
     * Asynchronously disables AWS Inspector for the specified accounts and resource types.
     *
     * @param accountIds a {@link List} of AWS account IDs for which to disable Inspector;
     *                   may be {@code null} or empty to target the current account
     * @return a {@link CompletableFuture} that, when completed, returns a {@link String}
     *         summarizing the disable results for each account
     * @throws CompletionException if the disable operation fails due to validation errors,
     *                             service errors, or other exceptions
     * @see <a href="https://docs.aws.amazon.com/inspector/latest/APIReference/API_Disable.html">
     *      AWS Inspector2 Disable API</a>
     */
    public CompletableFuture<String> disableInspectorAsync(List<String> accountIds) {

        // The resource types to disable.
        List<ResourceScanType> resourceTypes = List.of(
                ResourceScanType.EC2,
                ResourceScanType.ECR,
                ResourceScanType.LAMBDA,
                ResourceScanType.LAMBDA_CODE
        );

        // Build the request.
        DisableRequest.Builder requestBuilder = DisableRequest.builder()
                .resourceTypes(resourceTypes);

        if (accountIds != null && !accountIds.isEmpty()) {
            requestBuilder.accountIds(accountIds);
        }

        DisableRequest request = requestBuilder.build();

        return getAsyncClient().disable(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ValidationException) {
                            throw new CompletionException(
                                    "Inspector may already be disabled for this account: %s".formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;
                            throw new CompletionException(
                                    "AWS Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException(
                                "Failed to disable Inspector: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {
                    StringBuilder summary = new StringBuilder("Disable results:\n");

                    if (response.accounts() == null || response.accounts().isEmpty()) {
                        summary.append("Inspector may already be disabled for all target accounts.");
                        return summary.toString();
                    }

                    for (Account account : response.accounts()) {
                        String accountId = account.accountId() != null ? account.accountId() : "Unknown";
                        String status = account.status() != null ? account.statusAsString() : "Unknown";
                        summary.append(" • Account: ").append(accountId)
                                .append(" → Status: ").append(status).append("\n");
                    }

                    return summary.toString();
                });
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [BatchGetAccountStatus](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/BatchGetAccountStatus)
  + [BatchGetFindingDetails](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/BatchGetFindingDetails)
  + [CreateFilter](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/CreateFilter)
  + [DeleteFilter](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/DeleteFilter)
  + [有効化](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/Enable)
  + [ListCoverage](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListCoverage)
  + [ListCoverageStatistics](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListCoverageStatistics)
  + [ListFilters](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListFilters)
  + [ListFindings](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListFindings)
  + [ListUsageTotals](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListUsageTotals)

## アクション
<a name="actions"></a>

### `BatchGetAccountStatus`
<a name="inspector_GetAccountStatus_java_2_topic"></a>

次の例は、`BatchGetAccountStatus` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the account status using the Inspector2Client.
     */
    public CompletableFuture<String> getAccountStatusAsync() {
        BatchGetAccountStatusRequest request = BatchGetAccountStatusRequest.builder()
                .accountIds(Collections.emptyList())
                .build();

        return getAsyncClient().batchGetAccountStatus(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof AccessDeniedException) {
                            throw new CompletionException(
                                    "You do not have sufficient access: %s".formatted(cause.getMessage()),
                                    cause
                            );

                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;

                            throw new CompletionException(
                                    "Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    e
                            );
                        }

                        throw new CompletionException(
                                "Unexpected error getting account status: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {

                    StringBuilder sb = new StringBuilder();
                    List<AccountState> accounts = response.accounts();

                    if (accounts == null || accounts.isEmpty()) {
                        sb.append("No account status returned.\n");
                        return sb.toString();
                    }

                    sb.append("Inspector Account Status:\n");
                    for (AccountState account : accounts) {

                        String accountId = account.accountId() != null
                                ? account.accountId()
                                : "Unknown";

                        sb.append("  Account ID: ").append(accountId).append("\n");

                        // Overall account state
                        if (account.state() != null && account.state().status() != null) {
                            sb.append("  Overall State: ")
                                    .append(account.state().status())
                                    .append("\n");
                        } else {
                            sb.append("  Overall State: Unknown\n");
                        }

                        // Resource state (only status available)
                        ResourceState resources = account.resourceState();
                        if (resources != null) {
                            sb.append("  Resource Status: available\n");
                        }

                        sb.append("\n");
                    }

                    return sb.toString();
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[BatchGetAccountStatus](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/BatchGetAccountStatus)」を参照してください。

### `BatchGetFindingDetails`
<a name="inspector_BatchGetFindingDetails_java_2_topic"></a>

次の例は、`BatchGetFindingDetails` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves detailed information about a specific AWS Inspector2 finding asynchronously.
     *
     * @param findingArn The ARN of the finding to look up.
     * @return A {@link CompletableFuture} that, when completed, provides a formatted string
     * containing all available details for the finding.
     * @throws RuntimeException if the async call to Inspector2 fails.
     */
    public CompletableFuture<String> getFindingDetailsAsync(String findingArn) {
        BatchGetFindingDetailsRequest request = BatchGetFindingDetailsRequest.builder()
                .findingArns(findingArn)
                .build();

        return getAsyncClient().batchGetFindingDetails(request)
                .thenApply(response -> {
                    if (response.findingDetails() == null || response.findingDetails().isEmpty()) {
                        return String.format("No details found for ARN: ", findingArn);
                    }

                    StringBuilder sb = new StringBuilder();
                    response.findingDetails().forEach(detail -> {
                        sb.append("Finding ARN: ").append(detail.findingArn()).append("\n")
                                .append("Risk Score: ").append(detail.riskScore()).append("\n");

                        // ExploitObserved timings
                        if (detail.exploitObserved() != null) {
                            sb.append("Exploit First Seen: ").append(detail.exploitObserved().firstSeen()).append("\n")
                                    .append("Exploit Last Seen: ").append(detail.exploitObserved().lastSeen()).append("\n");
                        }

                        // Reference URLs
                        if (detail.hasReferenceUrls()) {
                            sb.append("Reference URLs:\n");
                            detail.referenceUrls().forEach(url -> sb.append("  • ").append(url).append("\n"));
                        }

                        // Tools
                        if (detail.hasTools()) {
                            sb.append("Tools:\n");
                            detail.tools().forEach(tool -> sb.append("  • ").append(tool).append("\n"));
                        }

                        // TTPs
                        if (detail.hasTtps()) {
                            sb.append("TTPs:\n");
                            detail.ttps().forEach(ttp -> sb.append("  • ").append(ttp).append("\n"));
                        }

                        // CWEs
                        if (detail.hasCwes()) {
                            sb.append("CWEs:\n");
                            detail.cwes().forEach(cwe -> sb.append("  • ").append(cwe).append("\n"));
                        }

                        // Evidence
                        if (detail.hasEvidences()) {
                            sb.append("Evidence:\n");
                            detail.evidences().forEach(ev -> {
                                sb.append("  - Severity: ").append(ev.severity()).append("\n");

                            });
                        }

                        sb.append("\n");
                    });

                    return sb.toString();
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ResourceNotFoundException rnfe) {
                        return "Finding not found: %s".formatted(findingArn);
                    }

                    // Fallback for other exceptions
                    throw new RuntimeException("Failed to get finding details for ARN: " + findingArn, cause);
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[BatchGetFindingDetails](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/BatchGetFindingDetails)」を参照してください。

### `CreateFilter`
<a name="inspector_CreateFilter_java_2_topic"></a>

次の例は、`CreateFilter` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new LOW severity filter in AWS Inspector2 to suppress findings.
     *
     * @param filterName  the name of the filter to create
     * @param description a descriptive string explaining the purpose of the filter
     * @return a CompletableFuture that completes with the ARN of the created filter
     * @throws CompletionException wraps any validation, Inspector2 service, or unexpected errors
     */
    public CompletableFuture<String> createLowSeverityFilterAsync(
            String filterName,
            String description) {

        // Define a filter to match LOW severity findings.
        StringFilter severityFilter = StringFilter.builder()
                .value(Severity.LOW.toString())
                .comparison(StringComparison.EQUALS)
                .build();

        // Create filter criteria.
        FilterCriteria filterCriteria = FilterCriteria.builder()
                .severity(Collections.singletonList(severityFilter))
                .build();

        // Build the filter creation request.
        CreateFilterRequest request = CreateFilterRequest.builder()
                .name(filterName)
                .filterCriteria(filterCriteria)
                .action(FilterAction.SUPPRESS)
                .description(description)
                .build();

        return getAsyncClient().createFilter(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ValidationException ve) {
                            throw new CompletionException(
                                    "Validation error creating filter: %s".formatted(ve.getMessage()),
                                    ve
                            );
                        }

                        if (cause instanceof Inspector2Exception e) {
                            throw new CompletionException(
                                    "Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    e
                            );
                        }

                        // Unexpected async error
                        throw new CompletionException(
                                "Unexpected error creating filter: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                // Extract and return the ARN of the created filter.
                .thenApply(CreateFilterResponse::arn);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateFilter](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/CreateFilter)」を参照してください。

### `DeleteFilter`
<a name="inspector_DeleteFilter_java_2_topic"></a>

次の例は、`DeleteFilter` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an AWS Inspector2 filter.
     *
     * @param filterARN The ARN of the filter to delete.
     */
    public CompletableFuture<Void> deleteFilterAsync(String filterARN) {
        return getAsyncClient().deleteFilter(
                        DeleteFilterRequest.builder()
                                .arn(filterARN)
                                .build()
                )
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException rnfe) {
                            String msg = "Filter not found for ARN: %s".formatted(filterARN);
                            logger.warn(msg, rnfe);
                            throw new CompletionException(msg, rnfe);
                        }

                        throw new RuntimeException("Failed to delete the filter: " + cause, cause);
                    }
                    return null;
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[DeleteFilter](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/DeleteFilter)」を参照してください。

### `Disable`
<a name="inspector_Disable_java_2_topic"></a>

次の例は、`Disable` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously disables AWS Inspector for the specified accounts and resource types.
     *
     * @param accountIds a {@link List} of AWS account IDs for which to disable Inspector;
     *                   may be {@code null} or empty to target the current account
     * @return a {@link CompletableFuture} that, when completed, returns a {@link String}
     *         summarizing the disable results for each account
     * @throws CompletionException if the disable operation fails due to validation errors,
     *                             service errors, or other exceptions
     * @see <a href="https://docs.aws.amazon.com/inspector/latest/APIReference/API_Disable.html">
     *      AWS Inspector2 Disable API</a>
     */
    public CompletableFuture<String> disableInspectorAsync(List<String> accountIds) {

        // The resource types to disable.
        List<ResourceScanType> resourceTypes = List.of(
                ResourceScanType.EC2,
                ResourceScanType.ECR,
                ResourceScanType.LAMBDA,
                ResourceScanType.LAMBDA_CODE
        );

        // Build the request.
        DisableRequest.Builder requestBuilder = DisableRequest.builder()
                .resourceTypes(resourceTypes);

        if (accountIds != null && !accountIds.isEmpty()) {
            requestBuilder.accountIds(accountIds);
        }

        DisableRequest request = requestBuilder.build();

        return getAsyncClient().disable(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ValidationException) {
                            throw new CompletionException(
                                    "Inspector may already be disabled for this account: %s".formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;
                            throw new CompletionException(
                                    "AWS Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException(
                                "Failed to disable Inspector: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {
                    StringBuilder summary = new StringBuilder("Disable results:\n");

                    if (response.accounts() == null || response.accounts().isEmpty()) {
                        summary.append("Inspector may already be disabled for all target accounts.");
                        return summary.toString();
                    }

                    for (Account account : response.accounts()) {
                        String accountId = account.accountId() != null ? account.accountId() : "Unknown";
                        String status = account.status() != null ? account.statusAsString() : "Unknown";
                        summary.append(" • Account: ").append(accountId)
                                .append(" → Status: ").append(status).append("\n");
                    }

                    return summary.toString();
                });
    }
```
+  API の詳細については、「 API *AWS SDK for Java 2.x リファレンス*」の[「Disable](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/Disable)」を参照してください。

### `Enable`
<a name="inspector_Enable_java_2_topic"></a>

次の例は、`Enable` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Enables AWS Inspector for the provided account(s) and default resource types.
     *
     * @param accountIds Optional list of AWS account IDs.
     */
    public CompletableFuture<String> enableInspectorAsync(List<String> accountIds) {

        // The resource types to enable.
        List<ResourceScanType> resourceTypes = List.of(
                ResourceScanType.EC2,
                ResourceScanType.ECR,
                ResourceScanType.LAMBDA,
                ResourceScanType.LAMBDA_CODE
        );

        // Build the request.
        EnableRequest.Builder requestBuilder = EnableRequest.builder()
                .resourceTypes(resourceTypes);

        if (accountIds != null && !accountIds.isEmpty()) {
            requestBuilder.accountIds(accountIds);
        }

        EnableRequest request = requestBuilder.build();
        return getAsyncClient().enable(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ValidationException) {
                            throw new CompletionException(
                                    "Inspector may already be enabled for this account: %s".formatted(cause.getMessage()),
                                    cause
                            );

                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;
                            throw new CompletionException(
                                    "AWS Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    cause
                            );
                        }

                        throw new CompletionException(
                                "Failed to enable Inspector: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {
                    StringBuilder summary = new StringBuilder("Enable results:\n");

                    if (response.accounts() == null || response.accounts().isEmpty()) {
                        summary.append("Inspector may already be enabled for all target accounts.");
                        return summary.toString();
                    }

                    for (Account account : response.accounts()) {
                        String accountId = account.accountId() != null ? account.accountId() : "Unknown";
                        String status = account.status() != null ? account.statusAsString() : "Unknown";
                        summary.append(" • Account: ").append(accountId)
                                .append(" → Status: ").append(status).append("\n");
                    }

                    return summary.toString();
                });
    }
```
+  API の詳細については、「 API *AWS SDK for Java 2.x リファレンス*」の[「Enable](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/Enable)」を参照してください。

### `ListCoverage`
<a name="inspector_ListCoverage_java_2_topic"></a>

次の例は、`ListCoverage` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists AWS Inspector2 coverage details for scanned resources using a paginator.
     *
     * @param maxResults Maximum number of resources to return.
     */
    public CompletableFuture<String> listCoverageAsync(int maxResults) {
        ListCoverageRequest initialRequest = ListCoverageRequest.builder()
                .maxResults(maxResults)
                .build();

        ListCoveragePublisher paginator = getAsyncClient().listCoveragePaginator(initialRequest);
        StringBuilder summary = new StringBuilder();

        return paginator.subscribe(response -> {
            List<CoveredResource> coveredResources = response.coveredResources();

            if (coveredResources == null || coveredResources.isEmpty()) {
                summary.append("No coverage information available for this page.\n");
                return;
            }

            Map<String, List<CoveredResource>> byType = coveredResources.stream()
                    .collect(Collectors.groupingBy(CoveredResource::resourceTypeAsString));

            byType.forEach((type, list) ->
                    summary.append("  ").append(type)
                            .append(": ").append(list.size())
                            .append(" resource(s)\n")
            );

            // Include up to 3 sample resources per page
            for (int i = 0; i < Math.min(coveredResources.size(), 3); i++) {
                CoveredResource r = coveredResources.get(i);
                summary.append("  - ").append(r.resourceTypeAsString())
                        .append(": ").append(r.resourceId()).append("\n");
                summary.append("    Scan Type: ").append(r.scanTypeAsString()).append("\n");
                if (r.scanStatus() != null) {
                    summary.append("    Status: ").append(r.scanStatus().statusCodeAsString()).append("\n");
                }
                if (r.accountId() != null) {
                    summary.append("    Account ID: ").append(r.accountId()).append("\n");
                }
                summary.append("\n");
            }

        }).thenApply(v -> {
            if (summary.length() == 0) {
                return "No coverage information found across all pages.";
            } else {
                return "Coverage Information:\n" + summary.toString();
            }
        }).exceptionally(ex -> {
            Throwable cause = ex.getCause();
            if (cause instanceof ValidationException) {
                throw new CompletionException(
                        "Validation error listing coverage: " + cause.getMessage(), cause);
            } else if (cause instanceof Inspector2Exception e) {
                throw new CompletionException(
                        "Inspector2 service error: " + e.awsErrorDetails().errorMessage(), e);
            }
            throw new CompletionException("Unexpected error listing coverage: " + ex.getMessage(), ex);
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[ListCoverage](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListCoverage)」を参照してください。

### `ListCoverageStatistics`
<a name="inspector_ListCoverageStatistics_java_2_topic"></a>

次の例は、`ListCoverageStatistics` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves and prints the coverage statistics using a paginator.
     */
    public CompletableFuture<String> listCoverageStatisticsAsync() {
        ListCoverageStatisticsRequest request = ListCoverageStatisticsRequest.builder()
                .build();

        return getAsyncClient().listCoverageStatistics(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();

                        if (cause instanceof ValidationException) {
                            throw new CompletionException(
                                    "Validation error listing coverage statistics: %s".formatted(cause.getMessage()),
                                    cause
                            );
                        }

                        if (cause instanceof Inspector2Exception) {
                            Inspector2Exception e = (Inspector2Exception) cause;

                            throw new CompletionException(
                                    "Inspector2 service error: %s".formatted(e.awsErrorDetails().errorMessage()),
                                    e
                            );
                        }

                        throw new CompletionException(
                                "Unexpected error listing coverage statistics: %s".formatted(exception.getMessage()),
                                exception
                        );
                    }
                })
                .thenApply(response -> {
                    List<Counts> countsList = response.countsByGroup();
                    StringBuilder sb = new StringBuilder();

                    if (countsList == null || countsList.isEmpty()) {
                        sb.append("No coverage statistics available.\n");
                        return sb.toString();
                    }

                    sb.append("Coverage Statistics:\n");

                    for (Counts c : countsList) {
                        sb.append("  Group: ").append(c.groupKey()).append("\n")
                                .append("    Total Count: ").append(c.count()).append("\n\n");
                    }

                    return sb.toString();
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[ListCoverageStatistics](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListCoverageStatistics)」を参照してください。

### `ListFilters`
<a name="inspector_ListFilters_java_2_topic"></a>

次の例は、`ListFilters` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously lists Inspector2 filters using a paginator.
     *
     * @param maxResults maximum filters per page (nullable)
     * @return CompletableFuture completed with summary text
     */
    public CompletableFuture<String> listFiltersAsync(Integer maxResults) {
        logger.info("Starting async filters paginator…");

        ListFiltersRequest.Builder builder = ListFiltersRequest.builder();
        if (maxResults != null) {
            builder.maxResults(maxResults);
        }

        ListFiltersRequest request = builder.build();

        // Paginator from SDK
        ListFiltersPublisher paginator = getAsyncClient().listFiltersPaginator(request);
        StringBuilder collectedFilterIds = new StringBuilder();

        return paginator.subscribe(response -> {
            response.filters().forEach(filter -> {
                logger.info("Filter: " + filter.arn());
                collectedFilterIds.append(filter.arn()).append("\n");
            });
        }).thenApply(v -> {
            String result = collectedFilterIds.toString();
            logger.info("Successfully listed all filters.");
            return result.isEmpty() ? "No filters found." : result;
        }).exceptionally(ex -> {
            Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

            if (cause instanceof ValidationException ve) {
                throw new CompletionException(
                        "Validation error listing filters: %s".formatted(ve.getMessage()),
                        ve
                );
            }

            throw new RuntimeException("Failed to list filters", ex);
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[ListFilters](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListFilters)」を参照してください。

### `ListFindings`
<a name="inspector_ListFindings_java_2_topic"></a>

次の例は、`ListFindings` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists all AWS Inspector findings of LOW severity asynchronously.
     *
     * @return CompletableFuture containing a List of finding ARNs.
     * Returns an empty list if no LOW severity findings are found.
     */
    public CompletableFuture<ArrayList<String>> listLowSeverityFindingsAsync() {
        logger.info("Starting async LOW severity findings paginator…");

        // Build a filter criteria for LOW severity.
        StringFilter severityFilter = StringFilter.builder()
                .value(Severity.LOW.toString())
                .comparison(StringComparison.EQUALS)
                .build();

        FilterCriteria filterCriteria = FilterCriteria.builder()
                .severity(Collections.singletonList(severityFilter))
                .build();

        // Build the request.
        ListFindingsRequest request = ListFindingsRequest.builder()
                .filterCriteria(filterCriteria)
                .build();

        ListFindingsPublisher paginator = getAsyncClient().listFindingsPaginator(request);
        List<String> allArns = Collections.synchronizedList(new ArrayList<>());

        return paginator.subscribe(response -> {
                    if (response.findings() != null && !response.findings().isEmpty()) {
                        response.findings().forEach(finding -> {
                            logger.info("Finding ARN: {}", finding.findingArn());
                            allArns.add(finding.findingArn());
                        });
                    } else {
                        logger.info("Page contained no findings.");
                    }
                })
                .thenRun(() -> logger.info("Successfully listed all LOW severity findings."))
                .thenApply(v -> new ArrayList<>(allArns)) // Return list instead of a formatted string
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;
                    if (cause instanceof ValidationException ve) {
                        throw new CompletionException(
                                "Validation error listing LOW severity findings: %s".formatted(ve.getMessage()),
                                ve
                        );
                    }
                    throw new RuntimeException("Failed to list LOW severity findings", ex);
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[ListFindings](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListFindings)」を参照してください。

### `ListUsageTotals`
<a name="inspector_ListUsageTotals_java_2_topic"></a>

次の例は、`ListUsageTotals` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/inspector#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously lists Inspector2 usage totals using a paginator.
     *
     * @param accountIds optional list of account IDs
     * @param maxResults maximum results per page
     * @return CompletableFuture completed with formatted summary text
     */
    public CompletableFuture<String> listUsageTotalsAsync(
            List<String> accountIds,
            int maxResults) {

        logger.info("Starting usage totals paginator…");

        ListUsageTotalsRequest.Builder builder = ListUsageTotalsRequest.builder()
                .maxResults(maxResults);

        if (accountIds != null && !accountIds.isEmpty()) {
            builder.accountIds(accountIds);
        }

        ListUsageTotalsRequest request = builder.build();
        ListUsageTotalsPublisher paginator = getAsyncClient().listUsageTotalsPaginator(request);
        StringBuilder summaryBuilder = new StringBuilder();

        return paginator.subscribe(response -> {
                    if (response.totals() != null && !response.totals().isEmpty()) {
                        response.totals().forEach(total -> {
                            if (total.usage() != null) {
                                total.usage().forEach(usage -> {
                                    logger.info("Usage: {} = {}", usage.typeAsString(), usage.total());
                                    summaryBuilder.append(usage.typeAsString())
                                            .append(": ")
                                            .append(usage.total())
                                            .append("\n");
                                });
                            }
                        });
                    } else {
                        logger.info("Page contained no usage totals.");
                    }
                }).thenRun(() -> logger.info("Successfully listed usage totals."))
                .thenApply(v -> {
                    String summary = summaryBuilder.toString();
                    return summary.isEmpty() ? "No usage totals found." : summary;
                }).exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ValidationException ve) {
                        throw new CompletionException(
                                "Validation error listing usage totals: %s".formatted(ve.getMessage()),
                                ve
                        );
                    }

                    throw new CompletionException("Failed to list usage totals", cause);
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x 「 API リファレンス*」の[ListUsageTotals](https://docs.aws.amazon.com/goto/SdkForJavaV2/inspector-2016-02-16/ListUsageTotals)」を参照してください。

# AWS IoT SDK for Java 2.x を使用した の例
<a name="java_2_iot_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoTは
<a name="iot_Hello_java_2_topic"></a>

次のコード例は、 AWS IoTの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iot.IotClient;
import software.amazon.awssdk.services.iot.model.ListThingsRequest;
import software.amazon.awssdk.services.iot.model.ListThingsResponse;
import software.amazon.awssdk.services.iot.model.ThingAttribute;
import software.amazon.awssdk.services.iot.paginators.ListThingsIterable;

import java.util.List;

public class HelloIoT {
    public static void main(String[] args) {
        System.out.println("Hello AWS IoT. Here is a listing of your AWS IoT Things:");
        IotClient iotClient = IotClient.builder()
            .region(Region.US_EAST_1)
            .build();

        listAllThings(iotClient);
    }

    public static void listAllThings(IotClient iotClient) {
        iotClient.listThingsPaginator(ListThingsRequest.builder()
                .maxResults(10)
                .build())
            .stream()
            .flatMap(response -> response.things().stream())
            .forEach(attribute -> {
                System.out.println("Thing name: " + attribute.thingName());
                System.out.println("Thing ARN: " + attribute.thingArn());
            });
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[listThings](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/listThings)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iot_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT モノを作成します。
+ デバイス証明書を生成します。
+ 属性を使用して AWS IoT モノを更新します。
+ 一意のエンドポイントを返します。
+  AWS IoT 証明書を一覧表示します。
+  AWS IoT シャドウを更新します。
+ 状態情報を書き込みます。
+ ルールを作成する｡
+ ルールを一覧表示します。
+ モノの名前を使用してモノを検索します。
+  AWS IoT モノを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。
 AWS IoT 機能を示すインタラクティブなシナリオを実行します。  

```
import java.util.Scanner;

/**
 * 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
 *
 * This Java example performs these tasks:
 *
 * 1. Creates an AWS IoT Thing.
 * 2. Generate and attach a device certificate.
 * 3. Update an AWS IoT Thing with Attributes.
 * 4. Get an AWS IoT Endpoint.
 * 5. List your certificates.
 * 6. Updates the shadow for the specified thing..
 * 7. Write out the state information, in JSON format
 * 8. Creates a rule
 * 9. List rules
 * 10. Search things
 * 11. Detach amd delete the certificate.
 * 12. Delete Thing.
 */
public class IotScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) {
        final String usage =
            """
                Usage:
                    <roleARN> <snsAction>

                Where:
                    roleARN - The ARN of an IAM role that has permission to work with AWS IOT.
                    snsAction  - An ARN of an SNS topic.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        IotActions iotActions = new IotActions();
        String thingName;
        String ruleName;
        String roleARN = args[0];
        String snsAction = args[1];
        Scanner scanner = new Scanner(System.in);

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS IoT basics scenario.");
        System.out.println("""
            This example program demonstrates various interactions with the AWS Internet of Things (IoT) Core service. The program guides you through a series of steps, 
            including creating an IoT Thing, generating a device certificate, updating the Thing with attributes, and so on. 
            It utilizes the AWS SDK for Java V2 and incorporates functionality for creating and managing IoT Things, certificates, rules, 
            shadows, and performing searches. The program aims to showcase AWS IoT capabilities and provides a comprehensive example for 
            developers working with AWS IoT in a Java environment.
            
            Let's get started...
       
            """);
        System.out.println(DASHES);

        System.out.println("1. Create an AWS IoT Thing.");
        System.out.println("""
            An AWS IoT Thing represents a virtual entity in the AWS IoT service that can be associated with 
            a physical device.
            """);
        // Prompt the user for input.
        System.out.print("Enter Thing name: ");
        thingName = scanner.nextLine();
        iotActions.createIoTThing(thingName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Generate a device certificate.");
        System.out.println("""
            A device certificate performs a role in securing the communication between devices (Things) 
            and the AWS IoT platform.
            """);

        System.out.print("Do you want to create a certificate for " +thingName +"? (y/n)");
        String certAns = scanner.nextLine();
        String certificateArn="" ;
        if (certAns != null && certAns.trim().equalsIgnoreCase("y")) {
            certificateArn = iotActions.createCertificate();
            System.out.println("Attach the certificate to the AWS IoT Thing.");
            iotActions.attachCertificateToThing(thingName, certificateArn);
        } else {
            System.out.println("A device certificate was not created.");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Update an AWS IoT Thing with Attributes.");
        System.out.println("""
             IoT Thing attributes, represented as key-value pairs, offer a pivotal advantage in facilitating efficient data 
             management and retrieval within the AWS IoT ecosystem. 
            """);
        waitForInputToContinue(scanner);
        iotActions.updateShadowThing(thingName);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Return a unique endpoint specific to the Amazon Web Services account.");
        System.out.println("""
            An IoT Endpoint refers to a specific URL or Uniform Resource Locator that serves as the entry point for communication between IoT devices and the AWS IoT service.
           """);
        waitForInputToContinue(scanner);
        String endpointUrl = iotActions.describeEndpoint();
        System.out.println("The endpoint is "+endpointUrl);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. List your AWS IoT certificates");
        waitForInputToContinue(scanner);
        if (certificateArn.length() > 0) {
            iotActions.listCertificates();
        } else {
            System.out.println("You did not create a certificates. Skipping this step.");
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Create an IoT shadow that refers to a digital representation or virtual twin of a physical IoT device");
        System.out.println("""
            A Thing Shadow refers to a feature that enables you to create a virtual representation, or "shadow," 
            of a physical device or thing. The Thing Shadow allows you to synchronize and control the state of a device between 
            the cloud and the device itself. and the AWS IoT service. For example, you can write and retrieve JSON data from a Thing Shadow. 
           """);
        waitForInputToContinue(scanner);
        iotActions.updateShadowThing(thingName);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Write out the state information, in JSON format.");
        waitForInputToContinue(scanner);
        iotActions.getPayload(thingName);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Creates a rule");
        System.out.println("""
        Creates a rule that is an administrator-level action. 
        Any user who has permission to create rules will be able to access data processed by the rule.
        """);
        System.out.print("Enter Rule name: ");
        ruleName = scanner.nextLine();
        iotActions.createIoTRule(roleARN, ruleName, snsAction);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. List your rules.");
        waitForInputToContinue(scanner);
        iotActions.listIoTRules();
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Search things using the Thing name.");
        waitForInputToContinue(scanner);
        String queryString = "thingName:"+thingName ;
        iotActions.searchThings(queryString);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        if (certificateArn.length() > 0) {
            System.out.print("Do you want to detach and delete the certificate for " +thingName +"? (y/n)");
            String delAns = scanner.nextLine();
            if (delAns != null && delAns.trim().equalsIgnoreCase("y")) {
                System.out.println("11. You selected to detach amd delete the certificate.");
                waitForInputToContinue(scanner);
                iotActions.detachThingPrincipal(thingName, certificateArn);
                iotActions.deleteCertificate(certificateArn);
                waitForInputToContinue(scanner);
            } else {
                System.out.println("11. You selected not to delete the certificate.");
            }
        } else {
            System.out.println("11. You did not create a certificate so there is nothing to delete.");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("12. Delete the AWS IoT Thing.");
        System.out.print("Do you want to delete the IoT Thing? (y/n)");
        String delAns = scanner.nextLine();
        if (delAns != null && delAns.trim().equalsIgnoreCase("y")) {
            iotActions.deleteIoTThing(thingName);
        } else {
            System.out.println("The IoT Thing was not deleted.");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The AWS IoT workflow has successfully completed.");
        System.out.println(DASHES);
    }


    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println("");
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }
}
```
 AWS IoT SDK メソッドのラッパークラス。  

```
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iot.IotAsyncClient;
import software.amazon.awssdk.services.iot.model.Action;
import software.amazon.awssdk.services.iot.model.AttachThingPrincipalRequest;
import software.amazon.awssdk.services.iot.model.AttachThingPrincipalResponse;
import software.amazon.awssdk.services.iot.model.Certificate;
import software.amazon.awssdk.services.iot.model.CreateKeysAndCertificateResponse;
import software.amazon.awssdk.services.iot.model.CreateThingRequest;
import software.amazon.awssdk.services.iot.model.CreateThingResponse;
import software.amazon.awssdk.services.iot.model.CreateTopicRuleRequest;
import software.amazon.awssdk.services.iot.model.CreateTopicRuleResponse;
import software.amazon.awssdk.services.iot.model.DeleteCertificateRequest;
import software.amazon.awssdk.services.iot.model.DeleteCertificateResponse;
import software.amazon.awssdk.services.iot.model.DeleteThingRequest;
import software.amazon.awssdk.services.iot.model.DeleteThingResponse;
import software.amazon.awssdk.services.iot.model.DescribeEndpointRequest;
import software.amazon.awssdk.services.iot.model.DescribeEndpointResponse;
import software.amazon.awssdk.services.iot.model.DescribeThingRequest;
import software.amazon.awssdk.services.iot.model.DescribeThingResponse;
import software.amazon.awssdk.services.iot.model.DetachThingPrincipalRequest;
import software.amazon.awssdk.services.iot.model.DetachThingPrincipalResponse;
import software.amazon.awssdk.services.iot.model.IotException;
import software.amazon.awssdk.services.iot.model.ListCertificatesResponse;
import software.amazon.awssdk.services.iot.model.ListTopicRulesRequest;
import software.amazon.awssdk.services.iot.model.ListTopicRulesResponse;
import software.amazon.awssdk.services.iot.model.SearchIndexRequest;
import software.amazon.awssdk.services.iot.model.SearchIndexResponse;
import software.amazon.awssdk.services.iot.model.TopicRuleListItem;
import software.amazon.awssdk.services.iot.model.SnsAction;
import software.amazon.awssdk.services.iot.model.TopicRulePayload;
import software.amazon.awssdk.services.iotdataplane.IotDataPlaneAsyncClient;
import software.amazon.awssdk.services.iotdataplane.model.GetThingShadowRequest;
import software.amazon.awssdk.services.iotdataplane.model.GetThingShadowResponse;
import software.amazon.awssdk.services.iotdataplane.model.UpdateThingShadowRequest;
import software.amazon.awssdk.services.iotdataplane.model.UpdateThingShadowResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IotActions {

    private static IotAsyncClient iotAsyncClient;

    private static IotDataPlaneAsyncClient iotAsyncDataPlaneClient;

    private static final String TOPIC = "your-iot-topic";

    private static IotDataPlaneAsyncClient getAsyncDataPlaneClient() {
        SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
            .maxConcurrency(100)
            .connectionTimeout(Duration.ofSeconds(60))
            .readTimeout(Duration.ofSeconds(60))
            .writeTimeout(Duration.ofSeconds(60))
            .build();

        ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
            .apiCallTimeout(Duration.ofMinutes(2))
            .apiCallAttemptTimeout(Duration.ofSeconds(90))
            .retryPolicy(RetryPolicy.builder()
                .numRetries(3)
                .build())
            .build();

        if (iotAsyncDataPlaneClient == null) {
            iotAsyncDataPlaneClient = IotDataPlaneAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return iotAsyncDataPlaneClient;
    }


    private static IotAsyncClient getAsyncClient() {
        SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
            .maxConcurrency(100)
            .connectionTimeout(Duration.ofSeconds(60))
            .readTimeout(Duration.ofSeconds(60))
            .writeTimeout(Duration.ofSeconds(60))
            .build();

        ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
            .apiCallTimeout(Duration.ofMinutes(2))
            .apiCallAttemptTimeout(Duration.ofSeconds(90))
            .retryPolicy(RetryPolicy.builder()
                .numRetries(3)
                .build())
            .build();

        if (iotAsyncClient == null) {
            iotAsyncClient = IotAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return iotAsyncClient;
    }

    /**
     * Creates an IoT certificate asynchronously.
     *
     * @return The ARN of the created certificate.
     * <p>
     * This method initiates an asynchronous request to create an IoT certificate.
     * If the request is successful, it prints the certificate details and returns the certificate ARN.
     * If an exception occurs, it prints the error message.
     */
    public String createCertificate() {
        CompletableFuture<CreateKeysAndCertificateResponse> future = getAsyncClient().createKeysAndCertificate();
        final String[] certificateArn = {null};
        future.whenComplete((response, ex) -> {
            if (response != null) {
                String certificatePem = response.certificatePem();
                certificateArn[0] = response.certificateArn();

                // Print the details.
                System.out.println("\nCertificate:");
                System.out.println(certificatePem);
                System.out.println("\nCertificate ARN:");
                System.out.println(certificateArn[0]);

            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + cause.getMessage());
                }
            }
        });

        future.join();
        return certificateArn[0];
    }

    /**
     * Creates an IoT Thing with the specified name asynchronously.
     *
     * @param thingName The name of the IoT Thing to create.
     *
     * This method initiates an asynchronous request to create an IoT Thing with the specified name.
     * If the request is successful, it prints the name of the thing and its ARN value.
     * If an exception occurs, it prints the error message.
     */
    public void createIoTThing(String thingName) {
        CreateThingRequest createThingRequest = CreateThingRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<CreateThingResponse> future = getAsyncClient().createThing(createThingRequest);
        future.whenComplete((createThingResponse, ex) -> {
            if (createThingResponse != null) {
                System.out.println(thingName + " was successfully created. The ARN value is " + createThingResponse.thingArn());
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + cause.getMessage());
                }
            }
        });

        future.join();
    }

    /**
     * Attaches a certificate to an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     * @param certificateArn The ARN of the certificate to attach.
     *
     * This method initiates an asynchronous request to attach a certificate to an IoT Thing.
     * If the request is successful, it prints a confirmation message and additional information about the Thing.
     * If an exception occurs, it prints the error message.
     */
    public void attachCertificateToThing(String thingName, String certificateArn) {
        AttachThingPrincipalRequest principalRequest = AttachThingPrincipalRequest.builder()
            .thingName(thingName)
            .principal(certificateArn)
            .build();

        CompletableFuture<AttachThingPrincipalResponse> future = getAsyncClient().attachThingPrincipal(principalRequest);
        future.whenComplete((attachResponse, ex) -> {
            if (attachResponse != null && attachResponse.sdkHttpResponse().isSuccessful()) {
                System.out.println("Certificate attached to Thing successfully.");

                // Print additional information about the Thing.
                describeThing(thingName);
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to attach certificate to Thing. HTTP Status Code: " +
                        attachResponse.sdkHttpResponse().statusCode());
                }
            }
        });

        future.join();
    }

    /**
     * Describes an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     *
     * This method initiates an asynchronous request to describe an IoT Thing.
     * If the request is successful, it prints the Thing details.
     * If an exception occurs, it prints the error message.
     */
    private void describeThing(String thingName) {
        DescribeThingRequest thingRequest = DescribeThingRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<DescribeThingResponse> future = getAsyncClient().describeThing(thingRequest);
        future.whenComplete((describeResponse, ex) -> {
            if (describeResponse != null) {
                System.out.println("Thing Details:");
                System.out.println("Thing Name: " + describeResponse.thingName());
                System.out.println("Thing ARN: " + describeResponse.thingArn());
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to describe Thing.");
                }
            }
        });

        future.join();
    }

    /**
     * Updates the shadow of an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     *
     * This method initiates an asynchronous request to update the shadow of an IoT Thing.
     * If the request is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void updateShadowThing(String thingName) {
        // Create Thing Shadow State Document.
        String stateDocument = "{\"state\":{\"reported\":{\"temperature\":25, \"humidity\":50}}}";
        SdkBytes data = SdkBytes.fromString(stateDocument, StandardCharsets.UTF_8);
        UpdateThingShadowRequest updateThingShadowRequest = UpdateThingShadowRequest.builder()
            .thingName(thingName)
            .payload(data)
            .build();

        CompletableFuture<UpdateThingShadowResponse> future = getAsyncDataPlaneClient().updateThingShadow(updateThingShadowRequest);
        future.whenComplete((updateResponse, ex) -> {
            if (updateResponse != null) {
                System.out.println("Thing Shadow updated successfully.");
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to update Thing Shadow.");
                }
            }
        });

        future.join();
    }

    /**
     * Describes the endpoint of the IoT service asynchronously.
     *
     * @return A CompletableFuture containing the full endpoint URL.
     *
     * This method initiates an asynchronous request to describe the endpoint of the IoT service.
     * If the request is successful, it prints and returns the full endpoint URL.
     * If an exception occurs, it prints the error message.
     */
    public String describeEndpoint() {
        CompletableFuture<DescribeEndpointResponse> future = getAsyncClient().describeEndpoint(DescribeEndpointRequest.builder().endpointType("iot:Data-ATS").build());
        final String[] result = {null};

        future.whenComplete((endpointResponse, ex) -> {
            if (endpointResponse != null) {
                String endpointUrl = endpointResponse.endpointAddress();
                String exString = getValue(endpointUrl);
                String fullEndpoint = "https://" + exString + "-ats.iot.us-east-1.amazonaws.com";

                System.out.println("Full Endpoint URL: " + fullEndpoint);
                result[0] = fullEndpoint;
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + cause.getMessage());
                }
            }
        });

        future.join();
        return result[0];
    }

    /**
     * Extracts a specific value from the endpoint URL.
     *
     * @param input The endpoint URL to process.
     * @return The extracted value from the endpoint URL.
     */
    private static String getValue(String input) {
        // Define a regular expression pattern for extracting the subdomain.
        Pattern pattern = Pattern.compile("^(.*?)\\.iot\\.us-east-1\\.amazonaws\\.com");

        // Match the pattern against the input string.
        Matcher matcher = pattern.matcher(input);

        // Check if a match is found.
        if (matcher.find()) {
            // Extract the subdomain from the first capturing group.
            String subdomain = matcher.group(1);
            System.out.println("Extracted subdomain: " + subdomain);
            return subdomain ;
        } else {
            System.out.println("No match found");
        }
        return "" ;
    }

    /**
     * Lists all certificates asynchronously.
     *
     * This method initiates an asynchronous request to list all certificates.
     * If the request is successful, it prints the certificate IDs and ARNs.
     * If an exception occurs, it prints the error message.
     */
    public void listCertificates() {
        CompletableFuture<ListCertificatesResponse> future = getAsyncClient().listCertificates();
        future.whenComplete((response, ex) -> {
            if (response != null) {
                List<Certificate> certList = response.certificates();
                for (Certificate cert : certList) {
                    System.out.println("Cert id: " + cert.certificateId());
                    System.out.println("Cert Arn: " + cert.certificateArn());
                }
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to list certificates.");
                }
            }
        });

        future.join();
    }

    /**
     * Retrieves the payload of a Thing's shadow asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     *
     * This method initiates an asynchronous request to get the payload of a Thing's shadow.
     * If the request is successful, it prints the shadow data.
     * If an exception occurs, it prints the error message.
     */
    public void getPayload(String thingName) {
        GetThingShadowRequest getThingShadowRequest = GetThingShadowRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<GetThingShadowResponse> future = getAsyncDataPlaneClient().getThingShadow(getThingShadowRequest);
        future.whenComplete((getThingShadowResponse, ex) -> {
            if (getThingShadowResponse != null) {
                // Extracting payload from response.
                SdkBytes payload = getThingShadowResponse.payload();
                String payloadString = payload.asUtf8String();
                System.out.println("Received Shadow Data: " + payloadString);
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to get Thing Shadow payload.");
                }
            }
        });

        future.join();
    }

    /**
     * Creates an IoT rule asynchronously.
     *
     * @param roleARN The ARN of the IAM role that grants access to the rule's actions.
     * @param ruleName The name of the IoT rule.
     * @param action The ARN of the action to perform when the rule is triggered.
     *
     * This method initiates an asynchronous request to create an IoT rule.
     * If the request is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void createIoTRule(String roleARN, String ruleName, String action) {
        String sql = "SELECT * FROM '" + TOPIC + "'";
        SnsAction action1 = SnsAction.builder()
            .targetArn(action)
            .roleArn(roleARN)
            .build();

        // Create the action.
        Action myAction = Action.builder()
            .sns(action1)
            .build();

        // Create the topic rule payload.
        TopicRulePayload topicRulePayload = TopicRulePayload.builder()
            .sql(sql)
            .actions(myAction)
            .build();

        // Create the topic rule request.
        CreateTopicRuleRequest topicRuleRequest = CreateTopicRuleRequest.builder()
            .ruleName(ruleName)
            .topicRulePayload(topicRulePayload)
            .build();

        CompletableFuture<CreateTopicRuleResponse> future = getAsyncClient().createTopicRule(topicRuleRequest);
        future.whenComplete((response, ex) -> {
            if (response != null) {
                System.out.println("IoT Rule created successfully.");
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to create IoT Rule.");
                }
            }
        });

        future.join();
    }

    /**
     * Lists IoT rules asynchronously.
     *
     * This method initiates an asynchronous request to list IoT rules.
     * If the request is successful, it prints the names and ARNs of the rules.
     * If an exception occurs, it prints the error message.
     */
    public void listIoTRules() {
        ListTopicRulesRequest listTopicRulesRequest = ListTopicRulesRequest.builder().build();
        CompletableFuture<ListTopicRulesResponse> future = getAsyncClient().listTopicRules(listTopicRulesRequest);
        future.whenComplete((listTopicRulesResponse, ex) -> {
            if (listTopicRulesResponse != null) {
                System.out.println("List of IoT Rules:");
                List<TopicRuleListItem> ruleList = listTopicRulesResponse.rules();
                for (TopicRuleListItem rule : ruleList) {
                    System.out.println("Rule Name: " + rule.ruleName());
                    System.out.println("Rule ARN: " + rule.ruleArn());
                    System.out.println("--------------");
                }
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to list IoT Rules.");
                }
            }
        });

        future.join();
    }

    /**
     * Searches for IoT Things asynchronously based on a query string.
     *
     * @param queryString The query string to search for Things.
     *
     * This method initiates an asynchronous request to search for IoT Things.
     * If the request is successful and Things are found, it prints their IDs.
     * If no Things are found, it prints a message indicating so.
     * If an exception occurs, it prints the error message.
     */
    public void searchThings(String queryString) {
        SearchIndexRequest searchIndexRequest = SearchIndexRequest.builder()
            .queryString(queryString)
            .build();

        CompletableFuture<SearchIndexResponse> future = getAsyncClient().searchIndex(searchIndexRequest);
        future.whenComplete((searchIndexResponse, ex) -> {
            if (searchIndexResponse != null) {
                // Process the result.
                if (searchIndexResponse.things().isEmpty()) {
                    System.out.println("No things found.");
                } else {
                    searchIndexResponse.things().forEach(thing -> System.out.println("Thing id found using search is " + thing.thingId()));
                }
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to search for IoT Things.");
                }
            }
        });

        future.join();
    }

    /**
     * Detaches a principal (certificate) from an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     * @param certificateArn The ARN of the certificate to detach.
     *
     * This method initiates an asynchronous request to detach a certificate from an IoT Thing.
     * If the detachment is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void detachThingPrincipal(String thingName, String certificateArn) {
        DetachThingPrincipalRequest thingPrincipalRequest = DetachThingPrincipalRequest.builder()
            .principal(certificateArn)
            .thingName(thingName)
            .build();

        CompletableFuture<DetachThingPrincipalResponse> future = getAsyncClient().detachThingPrincipal(thingPrincipalRequest);
        future.whenComplete((voidResult, ex) -> {
            if (ex == null) {
                System.out.println(certificateArn + " was successfully removed from " + thingName);
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + ex.getMessage());
                }
            }
        });

        future.join();
    }

    /**
     * Deletes a certificate asynchronously.
     *
     * @param certificateArn The ARN of the certificate to delete.
     *
     * This method initiates an asynchronous request to delete a certificate.
     * If the deletion is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void deleteCertificate(String certificateArn) {
        DeleteCertificateRequest certificateProviderRequest = DeleteCertificateRequest.builder()
            .certificateId(extractCertificateId(certificateArn))
            .build();

        CompletableFuture<DeleteCertificateResponse> future = getAsyncClient().deleteCertificate(certificateProviderRequest);
        future.whenComplete((voidResult, ex) -> {
            if (ex == null) {
                System.out.println(certificateArn + " was successfully deleted.");
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + ex.getMessage());
                }
            }
        });

        future.join();
    }

    /**
     * Deletes an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing to delete.
     *
     * This method initiates an asynchronous request to delete an IoT Thing.
     * If the deletion is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void deleteIoTThing(String thingName) {
        DeleteThingRequest deleteThingRequest = DeleteThingRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<DeleteThingResponse> future = getAsyncClient().deleteThing(deleteThingRequest);
        future.whenComplete((voidResult, ex) -> {
            if (ex == null) {
                System.out.println("Deleted Thing " + thingName);
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + ex.getMessage());
                }
            }
        });

        future.join();
    }

    // Get the cert Id  from the Cert ARN value.
    private String extractCertificateId(String certificateArn) {
        // Example ARN: arn:aws:iot:region:account-id:cert/certificate-id.
        String[] arnParts = certificateArn.split(":");
        String certificateIdPart = arnParts[arnParts.length - 1];
        return certificateIdPart.substring(certificateIdPart.lastIndexOf("/") + 1);
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AttachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/AttachThingPrincipal)
  + [CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/CreateKeysAndCertificate)
  + [CreateThing](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/CreateThing)
  + [CreateTopicRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/CreateTopicRule)
  + [DeleteCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DeleteCertificate)
  + [DeleteThing](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DeleteThing)
  + [DeleteTopicRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DeleteTopicRule)
  + [DescribeEndpoint](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DescribeEndpoint)
  + [DescribeThing](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DescribeThing)
  + [DetachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DetachThingPrincipal)
  + [ListCertificates](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/ListCertificates)
  + [ListThings](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/ListThings)
  + [SearchIndex](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/SearchIndex)
  + [UpdateIndexingConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/UpdateIndexingConfiguration)
  + [UpdateThing](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/UpdateThing)

## アクション
<a name="actions"></a>

### `AttachThingPrincipal`
<a name="iot_AttachThingPrincipal_java_2_topic"></a>

次のコード例は、`AttachThingPrincipal` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Attaches a certificate to an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     * @param certificateArn The ARN of the certificate to attach.
     *
     * This method initiates an asynchronous request to attach a certificate to an IoT Thing.
     * If the request is successful, it prints a confirmation message and additional information about the Thing.
     * If an exception occurs, it prints the error message.
     */
    public void attachCertificateToThing(String thingName, String certificateArn) {
        AttachThingPrincipalRequest principalRequest = AttachThingPrincipalRequest.builder()
            .thingName(thingName)
            .principal(certificateArn)
            .build();

        CompletableFuture<AttachThingPrincipalResponse> future = getAsyncClient().attachThingPrincipal(principalRequest);
        future.whenComplete((attachResponse, ex) -> {
            if (attachResponse != null && attachResponse.sdkHttpResponse().isSuccessful()) {
                System.out.println("Certificate attached to Thing successfully.");

                // Print additional information about the Thing.
                describeThing(thingName);
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to attach certificate to Thing. HTTP Status Code: " +
                        attachResponse.sdkHttpResponse().statusCode());
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AttachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/AttachThingPrincipal)」を参照してください。

### `CreateKeysAndCertificate`
<a name="iot_CreateKeysAndCertificate_java_2_topic"></a>

次のコード例は、`CreateKeysAndCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an IoT certificate asynchronously.
     *
     * @return The ARN of the created certificate.
     * <p>
     * This method initiates an asynchronous request to create an IoT certificate.
     * If the request is successful, it prints the certificate details and returns the certificate ARN.
     * If an exception occurs, it prints the error message.
     */
    public String createCertificate() {
        CompletableFuture<CreateKeysAndCertificateResponse> future = getAsyncClient().createKeysAndCertificate();
        final String[] certificateArn = {null};
        future.whenComplete((response, ex) -> {
            if (response != null) {
                String certificatePem = response.certificatePem();
                certificateArn[0] = response.certificateArn();

                // Print the details.
                System.out.println("\nCertificate:");
                System.out.println(certificatePem);
                System.out.println("\nCertificate ARN:");
                System.out.println(certificateArn[0]);

            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + cause.getMessage());
                }
            }
        });

        future.join();
        return certificateArn[0];
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/CreateKeysAndCertificate)」を参照してください。

### `CreateThing`
<a name="iot_CreateThing_java_2_topic"></a>

次のコード例は、`CreateThing` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an IoT Thing with the specified name asynchronously.
     *
     * @param thingName The name of the IoT Thing to create.
     *
     * This method initiates an asynchronous request to create an IoT Thing with the specified name.
     * If the request is successful, it prints the name of the thing and its ARN value.
     * If an exception occurs, it prints the error message.
     */
    public void createIoTThing(String thingName) {
        CreateThingRequest createThingRequest = CreateThingRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<CreateThingResponse> future = getAsyncClient().createThing(createThingRequest);
        future.whenComplete((createThingResponse, ex) -> {
            if (createThingResponse != null) {
                System.out.println(thingName + " was successfully created. The ARN value is " + createThingResponse.thingArn());
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + cause.getMessage());
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateThing](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/CreateThing)」を参照してください。

### `CreateTopicRule`
<a name="iot_CreateTopicRule_java_2_topic"></a>

次のコード例は、`CreateTopicRule` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an IoT rule asynchronously.
     *
     * @param roleARN The ARN of the IAM role that grants access to the rule's actions.
     * @param ruleName The name of the IoT rule.
     * @param action The ARN of the action to perform when the rule is triggered.
     *
     * This method initiates an asynchronous request to create an IoT rule.
     * If the request is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void createIoTRule(String roleARN, String ruleName, String action) {
        String sql = "SELECT * FROM '" + TOPIC + "'";
        SnsAction action1 = SnsAction.builder()
            .targetArn(action)
            .roleArn(roleARN)
            .build();

        // Create the action.
        Action myAction = Action.builder()
            .sns(action1)
            .build();

        // Create the topic rule payload.
        TopicRulePayload topicRulePayload = TopicRulePayload.builder()
            .sql(sql)
            .actions(myAction)
            .build();

        // Create the topic rule request.
        CreateTopicRuleRequest topicRuleRequest = CreateTopicRuleRequest.builder()
            .ruleName(ruleName)
            .topicRulePayload(topicRulePayload)
            .build();

        CompletableFuture<CreateTopicRuleResponse> future = getAsyncClient().createTopicRule(topicRuleRequest);
        future.whenComplete((response, ex) -> {
            if (response != null) {
                System.out.println("IoT Rule created successfully.");
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to create IoT Rule.");
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateTopicRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/CreateTopicRule)」を参照してください。

### `DeleteCertificate`
<a name="iot_DeleteCertificate_java_2_topic"></a>

次のコード例は、`DeleteCertificate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a certificate asynchronously.
     *
     * @param certificateArn The ARN of the certificate to delete.
     *
     * This method initiates an asynchronous request to delete a certificate.
     * If the deletion is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void deleteCertificate(String certificateArn) {
        DeleteCertificateRequest certificateProviderRequest = DeleteCertificateRequest.builder()
            .certificateId(extractCertificateId(certificateArn))
            .build();

        CompletableFuture<DeleteCertificateResponse> future = getAsyncClient().deleteCertificate(certificateProviderRequest);
        future.whenComplete((voidResult, ex) -> {
            if (ex == null) {
                System.out.println(certificateArn + " was successfully deleted.");
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + ex.getMessage());
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteCertificate](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DeleteCertificate)」を参照してください。

### `DeleteThing`
<a name="iot_DeleteThing_java_2_topic"></a>

次のコード例は、`DeleteThing` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing to delete.
     *
     * This method initiates an asynchronous request to delete an IoT Thing.
     * If the deletion is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void deleteIoTThing(String thingName) {
        DeleteThingRequest deleteThingRequest = DeleteThingRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<DeleteThingResponse> future = getAsyncClient().deleteThing(deleteThingRequest);
        future.whenComplete((voidResult, ex) -> {
            if (ex == null) {
                System.out.println("Deleted Thing " + thingName);
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + ex.getMessage());
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「DeleteThing」を参照してください。[https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DeleteThing](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DeleteThing)

### `DescribeEndpoint`
<a name="iot_DescribeEndpoint_java_2_topic"></a>

次のコード例は、`DescribeEndpoint` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Describes the endpoint of the IoT service asynchronously.
     *
     * @return A CompletableFuture containing the full endpoint URL.
     *
     * This method initiates an asynchronous request to describe the endpoint of the IoT service.
     * If the request is successful, it prints and returns the full endpoint URL.
     * If an exception occurs, it prints the error message.
     */
    public String describeEndpoint() {
        CompletableFuture<DescribeEndpointResponse> future = getAsyncClient().describeEndpoint(DescribeEndpointRequest.builder().endpointType("iot:Data-ATS").build());
        final String[] result = {null};

        future.whenComplete((endpointResponse, ex) -> {
            if (endpointResponse != null) {
                String endpointUrl = endpointResponse.endpointAddress();
                String exString = getValue(endpointUrl);
                String fullEndpoint = "https://" + exString + "-ats.iot.us-east-1.amazonaws.com";

                System.out.println("Full Endpoint URL: " + fullEndpoint);
                result[0] = fullEndpoint;
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + cause.getMessage());
                }
            }
        });

        future.join();
        return result[0];
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeEndpoint](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DescribeEndpoint)」を参照してください。

### `DescribeThing`
<a name="iot_DescribeThing_java_2_topic"></a>

次のコード例は、`DescribeThing` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Describes an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     *
     * This method initiates an asynchronous request to describe an IoT Thing.
     * If the request is successful, it prints the Thing details.
     * If an exception occurs, it prints the error message.
     */
    private void describeThing(String thingName) {
        DescribeThingRequest thingRequest = DescribeThingRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<DescribeThingResponse> future = getAsyncClient().describeThing(thingRequest);
        future.whenComplete((describeResponse, ex) -> {
            if (describeResponse != null) {
                System.out.println("Thing Details:");
                System.out.println("Thing Name: " + describeResponse.thingName());
                System.out.println("Thing ARN: " + describeResponse.thingArn());
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to describe Thing.");
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeThing](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DescribeThing)」を参照してください。

### `DetachThingPrincipal`
<a name="iot_DetachThingPrincipal_java_2_topic"></a>

次のコード例は、`DetachThingPrincipal` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Detaches a principal (certificate) from an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     * @param certificateArn The ARN of the certificate to detach.
     *
     * This method initiates an asynchronous request to detach a certificate from an IoT Thing.
     * If the detachment is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void detachThingPrincipal(String thingName, String certificateArn) {
        DetachThingPrincipalRequest thingPrincipalRequest = DetachThingPrincipalRequest.builder()
            .principal(certificateArn)
            .thingName(thingName)
            .build();

        CompletableFuture<DetachThingPrincipalResponse> future = getAsyncClient().detachThingPrincipal(thingPrincipalRequest);
        future.whenComplete((voidResult, ex) -> {
            if (ex == null) {
                System.out.println(certificateArn + " was successfully removed from " + thingName);
            } else {
                Throwable cause = ex.getCause();
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else {
                    System.err.println("Unexpected error: " + ex.getMessage());
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DetachThingPrincipal](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/DetachThingPrincipal)」を参照してください。

### `ListCertificates`
<a name="iot_ListCertificates_java_2_topic"></a>

次のコード例は、`ListCertificates` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists all certificates asynchronously.
     *
     * This method initiates an asynchronous request to list all certificates.
     * If the request is successful, it prints the certificate IDs and ARNs.
     * If an exception occurs, it prints the error message.
     */
    public void listCertificates() {
        CompletableFuture<ListCertificatesResponse> future = getAsyncClient().listCertificates();
        future.whenComplete((response, ex) -> {
            if (response != null) {
                List<Certificate> certList = response.certificates();
                for (Certificate cert : certList) {
                    System.out.println("Cert id: " + cert.certificateId());
                    System.out.println("Cert Arn: " + cert.certificateArn());
                }
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to list certificates.");
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンスの*「[ListCertificates](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/ListCertificates)」を参照してください。

### `SearchIndex`
<a name="iot_SearchIndex_java_2_topic"></a>

次のコード例は、`SearchIndex` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Searches for IoT Things asynchronously based on a query string.
     *
     * @param queryString The query string to search for Things.
     *
     * This method initiates an asynchronous request to search for IoT Things.
     * If the request is successful and Things are found, it prints their IDs.
     * If no Things are found, it prints a message indicating so.
     * If an exception occurs, it prints the error message.
     */
    public void searchThings(String queryString) {
        SearchIndexRequest searchIndexRequest = SearchIndexRequest.builder()
            .queryString(queryString)
            .build();

        CompletableFuture<SearchIndexResponse> future = getAsyncClient().searchIndex(searchIndexRequest);
        future.whenComplete((searchIndexResponse, ex) -> {
            if (searchIndexResponse != null) {
                // Process the result.
                if (searchIndexResponse.things().isEmpty()) {
                    System.out.println("No things found.");
                } else {
                    searchIndexResponse.things().forEach(thing -> System.out.println("Thing id found using search is " + thing.thingId()));
                }
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to search for IoT Things.");
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SearchIndex](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-2015-05-28/SearchIndex)」を参照してください。

# AWS IoT data SDK for Java 2.x を使用した例
<a name="java_2_iot-data-plane_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT data。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetThingShadow`
<a name="iot-data-plane_GetThingShadow_java_2_topic"></a>

次のコード例は、`GetThingShadow` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the payload of a Thing's shadow asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     *
     * This method initiates an asynchronous request to get the payload of a Thing's shadow.
     * If the request is successful, it prints the shadow data.
     * If an exception occurs, it prints the error message.
     */
    public void getPayload(String thingName) {
        GetThingShadowRequest getThingShadowRequest = GetThingShadowRequest.builder()
            .thingName(thingName)
            .build();

        CompletableFuture<GetThingShadowResponse> future = getAsyncDataPlaneClient().getThingShadow(getThingShadowRequest);
        future.whenComplete((getThingShadowResponse, ex) -> {
            if (getThingShadowResponse != null) {
                // Extracting payload from response.
                SdkBytes payload = getThingShadowResponse.payload();
                String payloadString = payload.asUtf8String();
                System.out.println("Received Shadow Data: " + payloadString);
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to get Thing Shadow payload.");
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、「* API リファレンスAWS SDK for Java 2.x *」の「[GetThingShadow](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-data-2015-05-28/GetThingShadow)」を参照してください。

### `UpdateThingShadow`
<a name="iot-data-plane_UpdateThingShadow_java_2_topic"></a>

次のコード例は、`UpdateThingShadow` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the shadow of an IoT Thing asynchronously.
     *
     * @param thingName The name of the IoT Thing.
     *
     * This method initiates an asynchronous request to update the shadow of an IoT Thing.
     * If the request is successful, it prints a confirmation message.
     * If an exception occurs, it prints the error message.
     */
    public void updateShadowThing(String thingName) {
        // Create Thing Shadow State Document.
        String stateDocument = "{\"state\":{\"reported\":{\"temperature\":25, \"humidity\":50}}}";
        SdkBytes data = SdkBytes.fromString(stateDocument, StandardCharsets.UTF_8);
        UpdateThingShadowRequest updateThingShadowRequest = UpdateThingShadowRequest.builder()
            .thingName(thingName)
            .payload(data)
            .build();

        CompletableFuture<UpdateThingShadowResponse> future = getAsyncDataPlaneClient().updateThingShadow(updateThingShadowRequest);
        future.whenComplete((updateResponse, ex) -> {
            if (updateResponse != null) {
                System.out.println("Thing Shadow updated successfully.");
            } else {
                Throwable cause = ex != null ? ex.getCause() : null;
                if (cause instanceof IotException) {
                    System.err.println(((IotException) cause).awsErrorDetails().errorMessage());
                } else if (cause != null) {
                    System.err.println("Unexpected error: " + cause.getMessage());
                } else {
                    System.err.println("Failed to update Thing Shadow.");
                }
            }
        });

        future.join();
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の「[UpdateThingShadow](https://docs.aws.amazon.com/goto/SdkForJavaV2/iot-data-2015-05-28/UpdateThingShadow)」を参照してください。

# AWS IoT FleetWise SDK for Java 2.x を使用した の例
<a name="java_2_iotfleetwise_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT FleetWise。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoT FleetWiseは
<a name="iotfleetwise_Hello_java_2_topic"></a>

次のコード例は、 AWS IoT FleetWiseの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
public class HelloFleetwise {

        public static void main(String[] args) {
            ListSignalCatalogs();
        }

        public static void  ListSignalCatalogs() {
            try (IoTFleetWiseClient fleetWiseClient = IoTFleetWiseClient.builder()
                    .region(Region.US_EAST_1)
                    .credentialsProvider(DefaultCredentialsProvider.create())
                    .build()) {

                ListSignalCatalogsRequest request = ListSignalCatalogsRequest.builder()
                        .maxResults(10) // Optional: limit per page
                        .build();

                ListSignalCatalogsIterable paginator = fleetWiseClient.listSignalCatalogsPaginator(request);
                boolean found = false;

                for (ListSignalCatalogsResponse response : paginator) {
                    for (SignalCatalogSummary summary : response.summaries()) {
                        found = true;
                        System.out.println("Catalog Name: " + summary.name());
                        System.out.println("ARN: " + summary.arn());
                        System.out.println("Created: " + summary.creationTime());
                        System.out.println("Last Modified: " + summary.lastModificationTime());
                        System.out.println("---------------");
                    }
                }

                if (!found) {
                    System.out.println("No AWS Fleetwise Signal Catalogs were found.");
                }

            } catch (IoTFleetWiseException e) {
                System.err.println("Error listing signal catalogs: " + e.awsErrorDetails().errorMessage());
                throw new RuntimeException(e);
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[listSignalCatalogsPaginator](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/listSignalCatalogsPaginator)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iotfleetwise_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 標準化されたシグナルのコレクションを作成します。
+ 車両のグループを表すフリートを作成します。
+ モデルマニフェストを作成します。
+ デコーダーマニフェストを作成します。
+ モデルマニフェストのステータスを確認します。
+ デコーダーのステータスを確認します。
+ IoT モノを作成します。
+ 車両を作成します。
+ 車両の詳細を表示します。
+  AWS IoT FleetWise アセットを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。
 AWS IoT SiteWise 機能を示すインタラクティブなシナリオを実行します。  

```
public class FleetwiseScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    static FleetwiseActions actions = new FleetwiseActions();
    private static final Logger logger = LoggerFactory.getLogger(FleetwiseScenario.class);
    static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        final String usage =
                """
                Usage:
                    <signalCatalogName> <manifestName> <fleetId> <vecName> <decName>
                
                Where:
                    signalCatalogName     - The name of the Signal Catalog to create (eg, catalog30).
                    manifestName          - The name of the Vehicle Model (Model Manifest) to create (eg, manifest30).
                    fleetId               - The ID of the Fleet to create (eg, fleet30).
                    vecName               - The name of the Vehicle to create (eg, vehicle30).
                    decName               - The name of the Decoder Manifest to create (eg, decManifest30).
                """;

        if (args.length != 5) {
            logger.info(usage);
            return;
        }

        String signalCatalogName = args[0];
        String manifestName = args[1];
        String fleetId = args[2];
        String vecName = args[3];
        String decName = args[4];

        logger.info(
                """
                 AWS IoT FleetWise is a managed service that simplifies the 
                 process of collecting, organizing, and transmitting vehicle 
                 data to the cloud in near real-time. Designed for automakers 
                 and fleet operators, it allows you to define vehicle models, 
                 specify the exact data you want to collect (such as engine 
                 temperature, speed, or battery status), and send this data to 
                 AWS for analysis. By using intelligent data collection 
                 techniques, IoT FleetWise reduces the volume of data 
                 transmitted by filtering and transforming it at the edge, 
                 helping to minimize bandwidth usage and costs. 
                
                At its core, AWS IoT FleetWise helps organizations build 
                scalable systems for vehicle data management and analytics, 
                supporting a wide variety of vehicles and sensor configurations. 
                You can define signal catalogs and decoder manifests that describe 
                how raw CAN bus signals are translated into readable data, making 
                the platform highly flexible and extensible. This allows 
                manufacturers to optimize vehicle performance, improve safety, 
                and reduce maintenance costs by gaining real-time visibility 
                into fleet operations. 
                """);

        waitForInputToContinue(scanner);
        logger.info(DASHES);
        try {
            runScenario(signalCatalogName, manifestName, fleetId, vecName, decName);
        } catch (RuntimeException e) {
            logger.info(e.getMessage());
        }
    }

    private static void runScenario(String signalCatalogName,
                                    String manifestName,
                                    String fleetId,
                                    String vecName,
                                    String decName) {
        logger.info(DASHES);
        logger.info("1. Creates a collection of standardized signals that can be reused to create vehicle models");
        String signalCatalogArn;
        try {
            signalCatalogArn = actions.createSignalCatalogAsync(signalCatalogName).join();
            logger.info("The collection ARN is " + signalCatalogArn);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ValidationException) {
                logger.error("The request failed due to a validation issue: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. Create a fleet that represents a group of vehicles");
        logger.info(
                """
                Creating an IoT FleetWise fleet allows you to efficiently collect, 
                organize, and transfer vehicle data to the cloud, enabling real-time 
                insights into vehicle performance and health. 
                
                It helps reduce data costs by allowing you to filter and prioritize 
                only the most relevant vehicle signals, supporting advanced analytics 
                and predictive maintenance use cases.
                """);

        waitForInputToContinue(scanner);
        String fleetid;
        try {
            fleetid = actions.createFleetAsync(signalCatalogArn, fleetId).join();
            logger.info("The fleet Id is " + fleetid);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("The resource was not found: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("3. Create a model manifest");
        logger.info(
                """
                An AWS IoT FleetWise manifest defines the structure and 
                relationships of vehicle data. The model manifest specifies 
                which signals to collect and how they relate to vehicle systems, 
                while the decoder manifest defines how to decode raw vehicle data 
                into meaningful signals. 
                """);
        waitForInputToContinue(scanner);
        String manifestArn;
        try {
            List<Node> nodes = actions.listSignalCatalogNodeAsync(signalCatalogName).join();
            manifestArn = actions.createModelManifestAsync(manifestName, signalCatalogArn, nodes).join();
            logger.info("The manifest ARN is {}", manifestArn);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            logger.error("An unexpected error occurred.", cause);
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. Create a decoder manifest");
        logger.info(
                """
                A decoder manifest in AWS IoT FleetWise defines how raw vehicle 
                data (such as CAN signals) should be interpreted and decoded 
                into meaningful signals. It acts as a translation layer 
                that maps vehicle-specific protocols to standardized data formats
                using decoding rules. This is crucial for extracting usable
                data from different vehicle models, even when their data 
                formats vary.
                
                """);
        waitForInputToContinue(scanner);
        String decArn;
        try {
            decArn = actions.createDecoderManifestAsync(decName, manifestArn).join();
            logger.info("The decoder manifest ARN is {}", decArn);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            logger.error("An unexpected error occurred.", cause);
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("5. Check the status of the model manifest");
        logger.info(
                """
                The model manifest must be in an ACTIVE state before it can be used 
                to create or update a vehicle.
                """);
        waitForInputToContinue(scanner);
        try {
            actions.updateModelManifestAsync(manifestName);
            actions.waitForModelManifestActiveAsync(manifestName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            logger.error("An unexpected error occurred while waiting for the model manifest status.", cause);
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("6. Check the status of the decoder");
        logger.info(
                """
                The decoder manifest must be in an ACTIVE state before it can be used 
                to create or update a vehicle.
                """);
        waitForInputToContinue(scanner);
        try {
            actions.updateDecoderManifestAsync(decName);
            actions.waitForDecoderManifestActiveAsync(decName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            logger.error("An unexpected error occurred while waiting for the decoder manifest status.", cause);
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Create an IoT Thing");
        logger.info(
                """
                AWS IoT FleetWise expects an existing AWS IoT Thing with the same 
                name as the vehicle name you are passing to createVehicle method. 
                Before calling createVehicle(), you must create an AWS IoT Thing 
                with the same name using the AWS IoT Core service.
                """);
        waitForInputToContinue(scanner);
        try {
            actions.createThingIfNotExistsAsync(vecName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceAlreadyExistsException) {
                logger.error("The resource exists: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
                return;
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("8. Create a vehicle");
        logger.info(
                """
                Creating a vehicle in AWS IoT FleetWise allows you to digitally 
                represent and manage a physical vehicle within the AWS ecosystem. 
                This enables efficient ingestion, transformation, and transmission 
                of vehicle telemetry data to the cloud for analysis.
                """);
        waitForInputToContinue(scanner);
        try {
            actions.createVehicleAsync(vecName, manifestArn, decArn).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();

            if (cause instanceof ResourceNotFoundException) {
                logger.error("The required resource was not found: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred while creating vehicle.", cause);
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("9. Display vehicle details");
        waitForInputToContinue(scanner);
        try {
            actions.getVehicleDetailsAsync(vecName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("The resource was not found: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("10. Delete the AWS IoT Fleetwise Assets");
        logger.info("Would you like to delete the IoT Fleetwise Assets? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            try {
                actions.deleteVehicleAsync(vecName).join();
                actions.deleteDecoderManifestAsync(decName).join();
                actions.deleteModelManifestAsync(manifestName).join();
                actions.deleteFleetAsync(fleetid).join();
                actions.deleteSignalCatalogAsync(signalCatalogName).join();
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof ResourceNotFoundException) {
                    // Handle the case where the resource is not found.
                    logger.error("The resource was not found: {}", cause.getMessage());
                } else if (cause instanceof RuntimeException) {
                    // Handle other runtime exceptions.
                    logger.error("An unexpected error occurred: {}", cause.getMessage());
                } else {
                    // Catch any other unexpected exceptions.
                    logger.error("An unknown error occurred.", cause);
                }
                return;
            }

            logger.info(DASHES);
            logger.info(
                    """
                    Thank you for checking out the AWS IoT Fleetwise Service Use demo. We hope you
                    learned something new, or got some inspiration for your own apps today.
                    For more AWS code examples, have a look at:
                    https://docs.aws.amazon.com/code-library/latest/ug/what-is-code-library.html
                    """);
            logger.info(DASHES);
        } else {
            logger.info("The AWS resources will not be deleted.");
        }
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
 AWS IoT FleetWise SDK メソッドのラッパークラス。  

```
public class FleetwiseActions {
    private static final Logger logger = LoggerFactory.getLogger(FleetwiseActions.class);
    private static IoTFleetWiseAsyncClient ioTFleetWiseAsyncClient;

    private static IoTFleetWiseAsyncClient getAsyncClient() {
        if (ioTFleetWiseAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                    .maxConcurrency(100)
                    .connectionTimeout(Duration.ofSeconds(60))
                    .readTimeout(Duration.ofSeconds(60))
                    .writeTimeout(Duration.ofSeconds(60))
                    .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                    .apiCallTimeout(Duration.ofMinutes(2))
                    .apiCallAttemptTimeout(Duration.ofSeconds(90))
                    .retryStrategy(RetryMode.STANDARD)
                    .build();

            ioTFleetWiseAsyncClient = IoTFleetWiseAsyncClient.builder()
                    .httpClient(httpClient)
                    .overrideConfiguration(overrideConfig)
                    .build();
        }
        return ioTFleetWiseAsyncClient;
    }


    /**
     * Creates a signal catalog.
     *
     * @param signalCatalogName the name of the signal catalog to be created
     * @return a {@link CompletableFuture} that completes with the Amazon Resource Name (ARN) of the created signal catalog
     */
    public CompletableFuture<String> createSignalCatalogAsync(String signalCatalogName) {
        return deleteSignalCatalogIfExistsAsync(signalCatalogName)
                .thenCompose(ignored -> delayAsync(2000)) // Wait for 2 seconds
                .thenCompose(ignored -> {
                    List<Node> nodes = List.of(
                            Node.builder().branch(
                                    Branch.builder()
                                            .fullyQualifiedName("Vehicle")
                                            .description("Root branch")
                                            .build()
                            ).build(),
                            Node.builder().branch(
                                    Branch.builder()
                                            .fullyQualifiedName("Vehicle.Powertrain")
                                            .description("Powertrain branch")
                                            .build()
                            ).build(),
                            Node.builder().sensor(
                                    Sensor.builder()
                                            .fullyQualifiedName("Vehicle.Powertrain.EngineRPM")
                                            .description("Engine RPM")
                                            .dataType(NodeDataType.DOUBLE)
                                            .unit("rpm")
                                            .build()
                            ).build(),
                            Node.builder().sensor(
                                    Sensor.builder()
                                            .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed")
                                            .description("Vehicle Speed")
                                            .dataType(NodeDataType.DOUBLE)
                                            .unit("km/h")
                                            .build()
                            ).build()
                    );

                    CreateSignalCatalogRequest request = CreateSignalCatalogRequest.builder()
                            .name(signalCatalogName)
                            .nodes(nodes)
                            .build();

                    CompletableFuture<String> result = new CompletableFuture<>();

                    getAsyncClient().createSignalCatalog(request)
                            .whenComplete((response, exception) -> {
                                if (exception != null) {
                                    Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                                    if (cause instanceof ValidationException) {
                                        result.completeExceptionally(cause);
                                    } else {
                                        result.completeExceptionally(new RuntimeException("Error creating the catalog", cause));
                                    }
                                } else {
                                    result.complete(response.arn());
                                }
                            });

                    return result;
                });
    }

    /**
     * Delays the execution of the current thread asynchronously for the specified duration.
     *
     * @param millis the duration of the delay in milliseconds
     * @return a {@link CompletableFuture} that completes after the specified delay
     */
    private static CompletableFuture<Void> delayAsync(long millis) {
        return CompletableFuture.runAsync(() -> {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException e) {
                throw new CompletionException("Sleep interrupted", e);
            }
        });
    }

    /**
     * Deletes the specified signal catalog.
     *
     * @param signalCatalogName the name of the signal catalog to delete
     * @return a {@link CompletableFuture} representing the asynchronous operation.
     */
    public static CompletableFuture<Void> deleteSignalCatalogIfExistsAsync(String signalCatalogName) {
        DeleteSignalCatalogRequest request = DeleteSignalCatalogRequest.builder()
                .name(signalCatalogName)
                .build();

        return getAsyncClient().deleteSignalCatalog(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                           throw new CompletionException(new RuntimeException("Signal Catalog not found: " + signalCatalogName));
                        }
                        throw new RuntimeException("Failed to delete signal catalog: " + signalCatalogName, cause);
                    }
                    return null;
                });
    }


    /**
     * Creates a new decoder manifest.
     *
     * @param name             the name of the decoder manifest
     * @param modelManifestArn the ARN of the model manifest
     * @return a {@link CompletableFuture} that completes with the ARN of the created decoder manifest
     */
    public CompletableFuture<String> createDecoderManifestAsync(String name, String modelManifestArn) {
        String interfaceId = "can0";
        NetworkInterface networkInterface = NetworkInterface.builder()
                .interfaceId(interfaceId)
                .type(NetworkInterfaceType.CAN_INTERFACE)
                .canInterface(CanInterface.builder()
                        .name("canInterface0")
                        .protocolName("CAN")
                        .protocolVersion("1.0")
                        .build())
                .build();

        // Vehicle.Powertrain.EngineRPM decoder.
        SignalDecoder engineRpmDecoder = SignalDecoder.builder()
                .fullyQualifiedName("Vehicle.Powertrain.EngineRPM")
                .interfaceId(interfaceId)
                .type(SignalDecoderType.CAN_SIGNAL)
                .canSignal(CanSignal.builder()
                        .messageId(100)
                        .isBigEndian(false)
                        .isSigned(false)
                        .startBit(0)
                        .length(16)
                        .factor(1.0)
                        .offset(0.0)
                        .build())
                .build();

        // Vehicle.Powertrain.VehicleSpeed decoder.
        SignalDecoder vehicleSpeedDecoder = SignalDecoder.builder()
                .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed")
                .interfaceId(interfaceId)
                .type(SignalDecoderType.CAN_SIGNAL)
                .canSignal(CanSignal.builder()
                        .messageId(101)
                        .isBigEndian(false)
                        .isSigned(false)
                        .startBit(16)
                        .length(16)
                        .factor(1.0)
                        .offset(0.0)
                        .build())
                .build();

        CreateDecoderManifestRequest request = CreateDecoderManifestRequest.builder()
                .name(name)
                .modelManifestArn(modelManifestArn)
                .networkInterfaces(List.of(networkInterface))
                .signalDecoders(List.of(engineRpmDecoder, vehicleSpeedDecoder))
                .build();

        CompletableFuture<String> result = new CompletableFuture<>();

        getAsyncClient().createDecoderManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof DecoderManifestValidationException) {
                            result.completeExceptionally(new CompletionException("The request contains signal decoders with validation errors: " + cause.getMessage(), cause));
                        } else {
                            result.completeExceptionally(new CompletionException("Failed to create decoder manifest: " + exception.getMessage(), exception));
                        }
                    } else {
                        result.complete(response.arn()); // Complete successfully with the ARN
                    }
                });

        return result;
    }

    /**
     * Deletes a decoder manifest.
     *
     * @param name the name of the decoder manifest to delete
     * @return a {@link CompletableFuture} that completes when the decoder manifest has been deleted
     */
    public CompletableFuture<Void> deleteDecoderManifestAsync(String name) {
        return getAsyncClient().deleteDecoderManifest(DeleteDecoderManifestRequest.builder().name(name).build())
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the decoder manifest: " + cause);
                    }
                    return null;
                });
    }


    /**
     * Deletes a vehicle with the specified name.
     *
     * @param vecName the name of the vehicle to be deleted
     * @return a {@link CompletableFuture} that completes when the vehicle has been deleted
     */
    public CompletableFuture<Void> deleteVehicleAsync(String vecName) {
        DeleteVehicleRequest request = DeleteVehicleRequest.builder()
                .vehicleName(vecName)
                .build();

        return getAsyncClient().deleteVehicle(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the vehicle: " + cause);
                    }
                    return null;
                });
    }


    /**
     * Updates the model manifest.
     *
     * @param name the name of the model manifest to update
     */
    public void updateModelManifestAsync(String name) {
        UpdateModelManifestRequest request = UpdateModelManifestRequest.builder()
                .name(name)
                .status(ManifestStatus.ACTIVE)
                .build();

        getAsyncClient().updateModelManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        throw new CompletionException("Failed to update model manifest: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> null);
    }


    /**
     * Updates the decoder manifest with the given name.
     *
     * @param name the name of the decoder manifest to update
     * @return a {@link CompletableFuture} that completes when the update operation is finished
     */
    public CompletableFuture<Void> updateDecoderManifestAsync(String name) {
        UpdateDecoderManifestRequest request = UpdateDecoderManifestRequest.builder()
                .name(name)
                .status(ManifestStatus.ACTIVE)
                .build();

        return getAsyncClient().updateDecoderManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        throw new CompletionException("Failed to update decoder manifest: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> null);
    }


    /**
     * Creates a new vehicle in the system.
     *
     * @param vecName     the name of the vehicle to be created
     * @param manifestArn the Amazon Resource Name (ARN) of the model manifest for the vehicle
     * @param decArn      the Amazon Resource Name (ARN) of the decoder manifest for the vehicle
     * @return a {@link CompletableFuture} that completes when the vehicle has been created, or throws a
     */
    public CompletableFuture<Void> createVehicleAsync(String vecName, String manifestArn, String decArn) {
        CreateVehicleRequest request = CreateVehicleRequest.builder()
                .vehicleName(vecName)
                .modelManifestArn(manifestArn)
                .decoderManifestArn(decArn)
                .build();

        CompletableFuture<Void> result = new CompletableFuture<>();
        getAsyncClient().createVehicle(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException) {
                            result.completeExceptionally(cause);
                        } else {
                            result.completeExceptionally(new RuntimeException("Failed to create vehicle: " + cause.getMessage(), cause));
                        }
                    } else {
                        logger.info("Vehicle '{}' created successfully.", vecName);
                        result.complete(null); // mark future as complete
                    }
                });

        return result;
    }


    /**
     * Waits for the decoder manifest to become active.
     *
     * @param decoderName the name of the decoder to wait for
     * @return a {@link CompletableFuture} that completes when the decoder manifest becomes active, or exceptionally if an error occurs or the manifest becomes invalid
     */
    public CompletableFuture<Void> waitForDecoderManifestActiveAsync(String decoderName) {
        CompletableFuture<Void> result = new CompletableFuture<>();

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        AtomicInteger secondsElapsed = new AtomicInteger(0);
        AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT);

        logger.info(" Elapsed: 0s | Decoder Status: DRAFT");

        final Runnable pollTask = new Runnable() {
            @Override
            public void run() {
                int elapsed = secondsElapsed.incrementAndGet();

                // Check status every 5 seconds
                if (elapsed % 5 == 0) {
                    GetDecoderManifestRequest request = GetDecoderManifestRequest.builder()
                            .name(decoderName)
                            .build();

                    getAsyncClient().getDecoderManifest(request)
                            .whenComplete((response, exception) -> {
                                if (exception != null) {
                                    Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                                    scheduler.shutdown();
                                    if (cause instanceof ResourceNotFoundException) {
                                        result.completeExceptionally(new RuntimeException("Decoder manifest not found: " + cause.getMessage(), cause));
                                    } else {
                                        result.completeExceptionally(new RuntimeException("Error while polling decoder manifest status: " + exception.getMessage(), exception));
                                    }
                                    return;
                                }

                                ManifestStatus status = response.status();
                                lastStatus.set(status);

                                if (status == ManifestStatus.ACTIVE) {
                                    logger.info("\r Elapsed: {}s | Decoder Status: ACTIVE", elapsed);
                                    scheduler.shutdown();
                                    result.complete(null);
                                } else if (status == ManifestStatus.INVALID) {
                                    logger.info("\r Elapsed: {}s | Decoder Status: INVALID", elapsed);
                                    scheduler.shutdown();
                                    result.completeExceptionally(new RuntimeException("Decoder manifest became INVALID. Cannot proceed."));
                                } else {
                                    logger.info("\r⏱ Elapsed: {}s | Decoder Status: {}", elapsed, status);
                                }
                            });
                } else {
                    logger.info("\r Elapsed: {}s | Decoder Status: {}", elapsed, lastStatus.get());
                }
            }
        };

        // Start the task with an initial delay of 1 second, and repeat every second
        scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS);
        return result;
    }



    /**
     * Waits for the specified model manifest to become active.
     *
     * @param manifestName the name of the model manifest to wait for
     */
    public CompletableFuture<Void> waitForModelManifestActiveAsync(String manifestName) {
        CompletableFuture<Void> result = new CompletableFuture<>();

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        AtomicInteger secondsElapsed = new AtomicInteger(0);
        AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT);

        logger.info("Elapsed: 0s | Status: DRAFT");

        final Runnable pollTask = new Runnable() {
            @Override
            public void run() {
                int elapsed = secondsElapsed.incrementAndGet();

                // Only check status every 5 seconds
                if (elapsed % 5 == 0) {
                    GetModelManifestRequest request = GetModelManifestRequest.builder()
                            .name(manifestName)
                            .build();

                    getAsyncClient().getModelManifest(request)
                            .whenComplete((response, exception) -> {
                                if (exception != null) {
                                    Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                                    scheduler.shutdown();
                                    if (cause instanceof ResourceNotFoundException) {
                                        result.completeExceptionally(new RuntimeException("Model manifest not found: " + cause.getMessage(), cause));
                                    } else {
                                        result.completeExceptionally(new RuntimeException("Error while polling model manifest status: " + exception.getMessage(), exception));
                                    }
                                    return;
                                }

                                ManifestStatus status = response.status();
                                lastStatus.set(status);

                                if (status == ManifestStatus.ACTIVE) {
                                    logger.info("\rElapsed: {}s | Status: ACTIVE", elapsed);
                                    scheduler.shutdown();
                                    result.complete(null);
                                } else if (status == ManifestStatus.INVALID) {
                                    logger.info("\rElapsed: {}s | Status: INVALID", elapsed);
                                    scheduler.shutdown();
                                    result.completeExceptionally(new RuntimeException("Model manifest became INVALID. Cannot proceed."));
                                } else {
                                    logger.info("\rElapsed: {}s | Status: {}", elapsed, status);
                                }
                            });
                } else {
                    logger.info("\rElapsed: {}s | Status: {}", elapsed, lastStatus.get());
                }
            }
        };

        // Start the task with an initial delay of 1 second, and repeat every second
        scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS);
        return result;
    }



    /**
     * Fetches the details of a vehicle.
     *
     * @param vehicleName the name of the vehicle to fetch details for
     * @return a {@link CompletableFuture} that completes when the vehicle details have been fetched
     */
    public CompletableFuture<Void> getVehicleDetailsAsync(String vehicleName) {
        GetVehicleRequest request = GetVehicleRequest.builder()
                .vehicleName(vehicleName)
                .build();

        CompletableFuture<Void> result = new CompletableFuture<>();

        getAsyncClient().getVehicle(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException) {
                            result.completeExceptionally(cause); // don't rewrap
                        } else {
                            result.completeExceptionally(new RuntimeException("Failed to fetch vehicle details: " + cause.getMessage(), cause));
                        }
                    } else {
                        Map<String, Object> details = new HashMap<>();
                        details.put("vehicleName", response.vehicleName());
                        details.put("arn", response.arn());
                        details.put("modelManifestArn", response.modelManifestArn());
                        details.put("decoderManifestArn", response.decoderManifestArn());
                        details.put("attributes", response.attributes());
                        details.put("creationTime", response.creationTime().toString());
                        details.put("lastModificationTime", response.lastModificationTime().toString());

                        logger.info("Vehicle Details:");
                        details.forEach((key, value) -> logger.info("• {} : {}", key, value));

                        result.complete(null); // mark as successful
                    }
                });

        return result;
    }


    /**
     * Creates an IoT Thing if it does not already exist.
     *
     * @param thingName the name of the IoT Thing to create
     * @return a {@link CompletableFuture} that completes when the IoT Thing has been created or if it already exists
     */
    public CompletableFuture<Void> createThingIfNotExistsAsync(String thingName) {
        IotAsyncClient iotClient = IotAsyncClient.builder()
                .region(Region.US_EAST_1)
                .build();

        CreateThingRequest request = CreateThingRequest.builder()
                .thingName(thingName)
                .build();

        return iotClient.createThing(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        if (exception instanceof ResourceAlreadyExistsException) {
                            logger.info(" IoT Thing already exists: " + thingName);
                        } else {
                            throw new CompletionException("Failed to create IoT Thing: " + thingName, exception);
                        }
                    } else {
                        logger.info("IoT Thing created: " + response.thingName());
                    }
                })
                .thenApply(response -> null);
    }


    /**
     * Deletes a model manifest.
     *
     * @param name the name of the model manifest to delete
     * @return a {@link CompletableFuture} that completes when the model manifest has been deleted
     */
    public CompletableFuture<Void> deleteModelManifestAsync(String name) {
        DeleteModelManifestRequest request = DeleteModelManifestRequest.builder()
                .name(name)
                .build();

        return getAsyncClient().deleteModelManifest(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the model manifest: " + cause);
                    }
                    logger.info("{} was successfully deleted", name);
                    return null;
                });
    }


    /**
     * Deletes a signal catalog.
     *
     * @param name the name of the signal catalog to delete
     * @return a {@link CompletableFuture} that completes when the signal catalog is deleted
     */
    public CompletableFuture<Void> deleteSignalCatalogAsync(String name) {
        DeleteSignalCatalogRequest request = DeleteSignalCatalogRequest.builder()
                .name(name)
                .build();

        return getAsyncClient().deleteSignalCatalog(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the signal catalog: " + cause);
                    }
                    logger.info("{} was successfully deleted", name);
                    return null;
                });
    }

    /**
     * Asynchronously retrieves a list of all nodes in the specified signal catalog.
     *
     * @param signalCatalogName the name of the signal catalog to retrieve nodes for
     * @return a {@link CompletableFuture} that, when completed, contains a {@link List} of {@link Node} objects
     * representing all the nodes in the specified signal catalog
     */
    public CompletableFuture<List<Node>> listSignalCatalogNodeAsync(String signalCatalogName) {
        ListSignalCatalogNodesRequest request = ListSignalCatalogNodesRequest.builder()
                .name(signalCatalogName)
                .build();

        List<Node> allNodes = new ArrayList<>();

        return getAsyncClient().listSignalCatalogNodesPaginator(request)
                .subscribe(response -> allNodes.addAll(response.nodes()))
                .thenApply(v -> allNodes);
    }



    /**
     * Creates a model manifest.
     *
     * @param name             the name of the model manifest to create
     * @param signalCatalogArn the Amazon Resource Name (ARN) of the signal catalog
     * @param nodes            a list of nodes to include in the model manifest
     * @return a {@link CompletableFuture} that completes with the ARN of the created model manifest
     */
    public CompletableFuture<String> createModelManifestAsync(String name,
                                                              String signalCatalogArn,
                                                              List<Node> nodes) {
        // Extract the fully qualified names (FQNs) from each Node in the provided list.
        List<String> fqnList = nodes.stream()
                .map(node -> {
                    if (node.sensor() != null) {
                        return node.sensor().fullyQualifiedName();
                    } else if (node.branch() != null) {
                        return node.branch().fullyQualifiedName();
                    } else if (node.attribute() != null) {
                        return node.attribute().fullyQualifiedName();
                    } else {
                        throw new RuntimeException("Unsupported node type");
                    }
                })
                .toList();

        CreateModelManifestRequest request = CreateModelManifestRequest.builder()
                .name(name)
                .signalCatalogArn(signalCatalogArn)
                .nodes(fqnList)
                .build();


        CompletableFuture<String> result = new CompletableFuture<>();
        getAsyncClient().createModelManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof InvalidSignalsException) {
                            result.completeExceptionally(new CompletionException("The request contains signals that aren't valid: " + cause.getMessage(), cause));
                        } else {
                            result.completeExceptionally(new CompletionException("Failed to create model manifest: " + exception.getMessage(), exception));
                        }
                    } else {
                        result.complete(response.arn()); // Complete successfully with the ARN
                    }
                });

        return result;
    }


    /**
     * Deletes a fleet based on the provided fleet ID.
     *
     * @param fleetId the ID of the fleet to be deleted
     */
    public CompletableFuture<Void> deleteFleetAsync(String fleetId) {
        DeleteFleetRequest request = DeleteFleetRequest.builder()
                .fleetId(fleetId)
                .build();

        return getAsyncClient().deleteFleet(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the fleet: " + cause);
                    }
                    logger.info("{} was successfully deleted", fleetId);
                    return null;
                });
    }



    /**
     * Creates a new fleet.
     *
     * @param catARN  the Amazon Resource Name (ARN) of the signal catalog to associate with the fleet
     * @param fleetId the unique identifier for the fleet
     * @return a {@link CompletableFuture} that completes with the ID of the created fleet
     */
    public CompletableFuture<String> createFleetAsync(String catARN, String fleetId) {
        CreateFleetRequest fleetRequest = CreateFleetRequest.builder()
                .fleetId(fleetId)
                .signalCatalogArn(catARN)
                .description("Built using the AWS For Java V2")
                .build();

        CompletableFuture<String> result = new CompletableFuture<>();
        getAsyncClient().createFleet(fleetRequest)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException) {
                            result.completeExceptionally(cause);
                        } else {
                            result.completeExceptionally(new RuntimeException("An unexpected error occurred", cause));
                        }
                    } else {
                        result.complete(response.id());
                    }
                });

        return result;
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [createDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createDecoderManifest)
  + [createFleet](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createFleet)
  + [createModelManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createModelManifest)
  + [createSignalCatalog](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createSignalCatalog)
  + [createVehicle](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createVehicle)
  + [deleteDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteDecoderManifest)
  + [deleteFleet](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteFleet)
  + [deleteModelManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteModelManifest)
  + [deleteSignalCatalog](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteSignalCatalog)
  + [deleteVehicle](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteVehicle)
  + [getDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/getDecoderManifest)
  + [getModelManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/getModelManifest)
  + [getVehicle](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/getVehicle)
  + [listSignalCatalogNodes](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/listSignalCatalogNodes)
  + [updateDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/updateDecoderManifest)
  + [updateModelManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/updateModelManifest)

## アクション
<a name="actions"></a>

### `createDecoderManifest`
<a name="iotfleetwise_CreateDecoderManifest_java_2_topic"></a>

次のコード例は、`createDecoderManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new decoder manifest.
     *
     * @param name             the name of the decoder manifest
     * @param modelManifestArn the ARN of the model manifest
     * @return a {@link CompletableFuture} that completes with the ARN of the created decoder manifest
     */
    public CompletableFuture<String> createDecoderManifestAsync(String name, String modelManifestArn) {
        String interfaceId = "can0";
        NetworkInterface networkInterface = NetworkInterface.builder()
                .interfaceId(interfaceId)
                .type(NetworkInterfaceType.CAN_INTERFACE)
                .canInterface(CanInterface.builder()
                        .name("canInterface0")
                        .protocolName("CAN")
                        .protocolVersion("1.0")
                        .build())
                .build();

        // Vehicle.Powertrain.EngineRPM decoder.
        SignalDecoder engineRpmDecoder = SignalDecoder.builder()
                .fullyQualifiedName("Vehicle.Powertrain.EngineRPM")
                .interfaceId(interfaceId)
                .type(SignalDecoderType.CAN_SIGNAL)
                .canSignal(CanSignal.builder()
                        .messageId(100)
                        .isBigEndian(false)
                        .isSigned(false)
                        .startBit(0)
                        .length(16)
                        .factor(1.0)
                        .offset(0.0)
                        .build())
                .build();

        // Vehicle.Powertrain.VehicleSpeed decoder.
        SignalDecoder vehicleSpeedDecoder = SignalDecoder.builder()
                .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed")
                .interfaceId(interfaceId)
                .type(SignalDecoderType.CAN_SIGNAL)
                .canSignal(CanSignal.builder()
                        .messageId(101)
                        .isBigEndian(false)
                        .isSigned(false)
                        .startBit(16)
                        .length(16)
                        .factor(1.0)
                        .offset(0.0)
                        .build())
                .build();

        CreateDecoderManifestRequest request = CreateDecoderManifestRequest.builder()
                .name(name)
                .modelManifestArn(modelManifestArn)
                .networkInterfaces(List.of(networkInterface))
                .signalDecoders(List.of(engineRpmDecoder, vehicleSpeedDecoder))
                .build();

        CompletableFuture<String> result = new CompletableFuture<>();

        getAsyncClient().createDecoderManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof DecoderManifestValidationException) {
                            result.completeExceptionally(new CompletionException("The request contains signal decoders with validation errors: " + cause.getMessage(), cause));
                        } else {
                            result.completeExceptionally(new CompletionException("Failed to create decoder manifest: " + exception.getMessage(), exception));
                        }
                    } else {
                        result.complete(response.arn()); // Complete successfully with the ARN
                    }
                });

        return result;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[createDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createDecoderManifest)」を参照してください。

### `createFleet`
<a name="iotfleetwise_CreateFleet_java_2_topic"></a>

次のコード例は、`createFleet` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new fleet.
     *
     * @param catARN  the Amazon Resource Name (ARN) of the signal catalog to associate with the fleet
     * @param fleetId the unique identifier for the fleet
     * @return a {@link CompletableFuture} that completes with the ID of the created fleet
     */
    public CompletableFuture<String> createFleetAsync(String catARN, String fleetId) {
        CreateFleetRequest fleetRequest = CreateFleetRequest.builder()
                .fleetId(fleetId)
                .signalCatalogArn(catARN)
                .description("Built using the AWS For Java V2")
                .build();

        CompletableFuture<String> result = new CompletableFuture<>();
        getAsyncClient().createFleet(fleetRequest)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException) {
                            result.completeExceptionally(cause);
                        } else {
                            result.completeExceptionally(new RuntimeException("An unexpected error occurred", cause));
                        }
                    } else {
                        result.complete(response.id());
                    }
                });

        return result;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[createFleet](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createFleet)」を参照してください。

### `createModelManifest`
<a name="iotfleetwise_CreateModelManifest_java_2_topic"></a>

次のコード例は、`createModelManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a model manifest.
     *
     * @param name             the name of the model manifest to create
     * @param signalCatalogArn the Amazon Resource Name (ARN) of the signal catalog
     * @param nodes            a list of nodes to include in the model manifest
     * @return a {@link CompletableFuture} that completes with the ARN of the created model manifest
     */
    public CompletableFuture<String> createModelManifestAsync(String name,
                                                              String signalCatalogArn,
                                                              List<Node> nodes) {
        // Extract the fully qualified names (FQNs) from each Node in the provided list.
        List<String> fqnList = nodes.stream()
                .map(node -> {
                    if (node.sensor() != null) {
                        return node.sensor().fullyQualifiedName();
                    } else if (node.branch() != null) {
                        return node.branch().fullyQualifiedName();
                    } else if (node.attribute() != null) {
                        return node.attribute().fullyQualifiedName();
                    } else {
                        throw new RuntimeException("Unsupported node type");
                    }
                })
                .toList();

        CreateModelManifestRequest request = CreateModelManifestRequest.builder()
                .name(name)
                .signalCatalogArn(signalCatalogArn)
                .nodes(fqnList)
                .build();


        CompletableFuture<String> result = new CompletableFuture<>();
        getAsyncClient().createModelManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                        if (cause instanceof InvalidSignalsException) {
                            result.completeExceptionally(new CompletionException("The request contains signals that aren't valid: " + cause.getMessage(), cause));
                        } else {
                            result.completeExceptionally(new CompletionException("Failed to create model manifest: " + exception.getMessage(), exception));
                        }
                    } else {
                        result.complete(response.arn()); // Complete successfully with the ARN
                    }
                });

        return result;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[createModelManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createModelManifest)」を参照してください。

### `createSignalCatalog`
<a name="iotfleetwise_CreateSignalCatalog_java_2_topic"></a>

次のコード例は、`createSignalCatalog` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a signal catalog.
     *
     * @param signalCatalogName the name of the signal catalog to be created
     * @return a {@link CompletableFuture} that completes with the Amazon Resource Name (ARN) of the created signal catalog
     */
    public CompletableFuture<String> createSignalCatalogAsync(String signalCatalogName) {
        return deleteSignalCatalogIfExistsAsync(signalCatalogName)
                .thenCompose(ignored -> delayAsync(2000)) // Wait for 2 seconds
                .thenCompose(ignored -> {
                    List<Node> nodes = List.of(
                            Node.builder().branch(
                                    Branch.builder()
                                            .fullyQualifiedName("Vehicle")
                                            .description("Root branch")
                                            .build()
                            ).build(),
                            Node.builder().branch(
                                    Branch.builder()
                                            .fullyQualifiedName("Vehicle.Powertrain")
                                            .description("Powertrain branch")
                                            .build()
                            ).build(),
                            Node.builder().sensor(
                                    Sensor.builder()
                                            .fullyQualifiedName("Vehicle.Powertrain.EngineRPM")
                                            .description("Engine RPM")
                                            .dataType(NodeDataType.DOUBLE)
                                            .unit("rpm")
                                            .build()
                            ).build(),
                            Node.builder().sensor(
                                    Sensor.builder()
                                            .fullyQualifiedName("Vehicle.Powertrain.VehicleSpeed")
                                            .description("Vehicle Speed")
                                            .dataType(NodeDataType.DOUBLE)
                                            .unit("km/h")
                                            .build()
                            ).build()
                    );

                    CreateSignalCatalogRequest request = CreateSignalCatalogRequest.builder()
                            .name(signalCatalogName)
                            .nodes(nodes)
                            .build();

                    CompletableFuture<String> result = new CompletableFuture<>();

                    getAsyncClient().createSignalCatalog(request)
                            .whenComplete((response, exception) -> {
                                if (exception != null) {
                                    Throwable cause = exception.getCause() != null ? exception.getCause() : exception;

                                    if (cause instanceof ValidationException) {
                                        result.completeExceptionally(cause);
                                    } else {
                                        result.completeExceptionally(new RuntimeException("Error creating the catalog", cause));
                                    }
                                } else {
                                    result.complete(response.arn());
                                }
                            });

                    return result;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[createSignalCatalog](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createSignalCatalog)」を参照してください。

### `createVehicle`
<a name="iotfleetwise_CreateVehicle_java_2_topic"></a>

次のコード例は、`createVehicle` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new vehicle in the system.
     *
     * @param vecName     the name of the vehicle to be created
     * @param manifestArn the Amazon Resource Name (ARN) of the model manifest for the vehicle
     * @param decArn      the Amazon Resource Name (ARN) of the decoder manifest for the vehicle
     * @return a {@link CompletableFuture} that completes when the vehicle has been created, or throws a
     */
    public CompletableFuture<Void> createVehicleAsync(String vecName, String manifestArn, String decArn) {
        CreateVehicleRequest request = CreateVehicleRequest.builder()
                .vehicleName(vecName)
                .modelManifestArn(manifestArn)
                .decoderManifestArn(decArn)
                .build();

        CompletableFuture<Void> result = new CompletableFuture<>();
        getAsyncClient().createVehicle(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException) {
                            result.completeExceptionally(cause);
                        } else {
                            result.completeExceptionally(new RuntimeException("Failed to create vehicle: " + cause.getMessage(), cause));
                        }
                    } else {
                        logger.info("Vehicle '{}' created successfully.", vecName);
                        result.complete(null); // mark future as complete
                    }
                });

        return result;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[createVehicle](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/createVehicle)」を参照してください。

### `deleteDecoderManifest`
<a name="iotfleetwise_DeleteDecoderManifest_java_2_topic"></a>

次のコード例は、`deleteDecoderManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a decoder manifest.
     *
     * @param name the name of the decoder manifest to delete
     * @return a {@link CompletableFuture} that completes when the decoder manifest has been deleted
     */
    public CompletableFuture<Void> deleteDecoderManifestAsync(String name) {
        return getAsyncClient().deleteDecoderManifest(DeleteDecoderManifestRequest.builder().name(name).build())
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the decoder manifest: " + cause);
                    }
                    return null;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[deleteDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteDecoderManifest)」を参照してください。

### `deleteFleet`
<a name="iotfleetwise_DeleteFleet_java_2_topic"></a>

次のコード例は、`deleteFleet` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a fleet based on the provided fleet ID.
     *
     * @param fleetId the ID of the fleet to be deleted
     */
    public CompletableFuture<Void> deleteFleetAsync(String fleetId) {
        DeleteFleetRequest request = DeleteFleetRequest.builder()
                .fleetId(fleetId)
                .build();

        return getAsyncClient().deleteFleet(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the fleet: " + cause);
                    }
                    logger.info("{} was successfully deleted", fleetId);
                    return null;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[deleteFleet](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteFleet)」を参照してください。

### `deleteModelManifest`
<a name="iotfleetwise_DeleteModelManifest_java_2_topic"></a>

次のコード例は、`deleteModelManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a model manifest.
     *
     * @param name the name of the model manifest to delete
     * @return a {@link CompletableFuture} that completes when the model manifest has been deleted
     */
    public CompletableFuture<Void> deleteModelManifestAsync(String name) {
        DeleteModelManifestRequest request = DeleteModelManifestRequest.builder()
                .name(name)
                .build();

        return getAsyncClient().deleteModelManifest(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the model manifest: " + cause);
                    }
                    logger.info("{} was successfully deleted", name);
                    return null;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[deleteModelManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteModelManifest)」を参照してください。

### `deleteSignalCatalog`
<a name="iotfleetwise_DeleteSignalCatalog_java_2_topic"></a>

次のコード例は、`deleteSignalCatalog` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a signal catalog.
     *
     * @param name the name of the signal catalog to delete
     * @return a {@link CompletableFuture} that completes when the signal catalog is deleted
     */
    public CompletableFuture<Void> deleteSignalCatalogAsync(String name) {
        DeleteSignalCatalogRequest request = DeleteSignalCatalogRequest.builder()
                .name(name)
                .build();

        return getAsyncClient().deleteSignalCatalog(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the signal catalog: " + cause);
                    }
                    logger.info("{} was successfully deleted", name);
                    return null;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[deleteSignalCatalog](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteSignalCatalog)」を参照してください。

### `deleteVehicle`
<a name="iotfleetwise_DeleteVehicle_java_2_topic"></a>

次のコード例は、`deleteVehicle` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a vehicle with the specified name.
     *
     * @param vecName the name of the vehicle to be deleted
     * @return a {@link CompletableFuture} that completes when the vehicle has been deleted
     */
    public CompletableFuture<Void> deleteVehicleAsync(String vecName) {
        DeleteVehicleRequest request = DeleteVehicleRequest.builder()
                .vehicleName(vecName)
                .build();

        return getAsyncClient().deleteVehicle(request)
                .handle((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }
                        throw new RuntimeException("Failed to delete the vehicle: " + cause);
                    }
                    return null;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[deleteVehicle](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/deleteVehicle)」を参照してください。

### `getDecoderManifest`
<a name="iotfleetwise_GetDecoderManifest_java_2_topic"></a>

次のコード例は、`getDecoderManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Waits for the decoder manifest to become active.
     *
     * @param decoderName the name of the decoder to wait for
     * @return a {@link CompletableFuture} that completes when the decoder manifest becomes active, or exceptionally if an error occurs or the manifest becomes invalid
     */
    public CompletableFuture<Void> waitForDecoderManifestActiveAsync(String decoderName) {
        CompletableFuture<Void> result = new CompletableFuture<>();

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        AtomicInteger secondsElapsed = new AtomicInteger(0);
        AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT);

        logger.info(" Elapsed: 0s | Decoder Status: DRAFT");

        final Runnable pollTask = new Runnable() {
            @Override
            public void run() {
                int elapsed = secondsElapsed.incrementAndGet();

                // Check status every 5 seconds
                if (elapsed % 5 == 0) {
                    GetDecoderManifestRequest request = GetDecoderManifestRequest.builder()
                            .name(decoderName)
                            .build();

                    getAsyncClient().getDecoderManifest(request)
                            .whenComplete((response, exception) -> {
                                if (exception != null) {
                                    Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                                    scheduler.shutdown();
                                    if (cause instanceof ResourceNotFoundException) {
                                        result.completeExceptionally(new RuntimeException("Decoder manifest not found: " + cause.getMessage(), cause));
                                    } else {
                                        result.completeExceptionally(new RuntimeException("Error while polling decoder manifest status: " + exception.getMessage(), exception));
                                    }
                                    return;
                                }

                                ManifestStatus status = response.status();
                                lastStatus.set(status);

                                if (status == ManifestStatus.ACTIVE) {
                                    logger.info("\r Elapsed: {}s | Decoder Status: ACTIVE", elapsed);
                                    scheduler.shutdown();
                                    result.complete(null);
                                } else if (status == ManifestStatus.INVALID) {
                                    logger.info("\r Elapsed: {}s | Decoder Status: INVALID", elapsed);
                                    scheduler.shutdown();
                                    result.completeExceptionally(new RuntimeException("Decoder manifest became INVALID. Cannot proceed."));
                                } else {
                                    logger.info("\r⏱ Elapsed: {}s | Decoder Status: {}", elapsed, status);
                                }
                            });
                } else {
                    logger.info("\r Elapsed: {}s | Decoder Status: {}", elapsed, lastStatus.get());
                }
            }
        };

        // Start the task with an initial delay of 1 second, and repeat every second
        scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS);
        return result;
    }
```
+  API の詳細については、「**AWS SDK for Java 2.x API リファレンス」の「[getDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/getDecoderManifest)」を参照してください。

### `getModelManifest`
<a name="iotfleetwise_GetModelManifest_java_2_topic"></a>

次のコード例は、`getModelManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Waits for the specified model manifest to become active.
     *
     * @param manifestName the name of the model manifest to wait for
     */
    public CompletableFuture<Void> waitForModelManifestActiveAsync(String manifestName) {
        CompletableFuture<Void> result = new CompletableFuture<>();

        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        AtomicInteger secondsElapsed = new AtomicInteger(0);
        AtomicReference<ManifestStatus> lastStatus = new AtomicReference<>(ManifestStatus.DRAFT);

        logger.info("Elapsed: 0s | Status: DRAFT");

        final Runnable pollTask = new Runnable() {
            @Override
            public void run() {
                int elapsed = secondsElapsed.incrementAndGet();

                // Only check status every 5 seconds
                if (elapsed % 5 == 0) {
                    GetModelManifestRequest request = GetModelManifestRequest.builder()
                            .name(manifestName)
                            .build();

                    getAsyncClient().getModelManifest(request)
                            .whenComplete((response, exception) -> {
                                if (exception != null) {
                                    Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                                    scheduler.shutdown();
                                    if (cause instanceof ResourceNotFoundException) {
                                        result.completeExceptionally(new RuntimeException("Model manifest not found: " + cause.getMessage(), cause));
                                    } else {
                                        result.completeExceptionally(new RuntimeException("Error while polling model manifest status: " + exception.getMessage(), exception));
                                    }
                                    return;
                                }

                                ManifestStatus status = response.status();
                                lastStatus.set(status);

                                if (status == ManifestStatus.ACTIVE) {
                                    logger.info("\rElapsed: {}s | Status: ACTIVE", elapsed);
                                    scheduler.shutdown();
                                    result.complete(null);
                                } else if (status == ManifestStatus.INVALID) {
                                    logger.info("\rElapsed: {}s | Status: INVALID", elapsed);
                                    scheduler.shutdown();
                                    result.completeExceptionally(new RuntimeException("Model manifest became INVALID. Cannot proceed."));
                                } else {
                                    logger.info("\rElapsed: {}s | Status: {}", elapsed, status);
                                }
                            });
                } else {
                    logger.info("\rElapsed: {}s | Status: {}", elapsed, lastStatus.get());
                }
            }
        };

        // Start the task with an initial delay of 1 second, and repeat every second
        scheduler.scheduleAtFixedRate(pollTask, 1, 1, TimeUnit.SECONDS);
        return result;
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/getModelManifest)」の「*getModelManifest*」を参照してください。

### `getVehicle`
<a name="iotfleetwise_GetVehicle_java_2_topic"></a>

次のコード例は、`getVehicle` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Fetches the details of a vehicle.
     *
     * @param vehicleName the name of the vehicle to fetch details for
     * @return a {@link CompletableFuture} that completes when the vehicle details have been fetched
     */
    public CompletableFuture<Void> getVehicleDetailsAsync(String vehicleName) {
        GetVehicleRequest request = GetVehicleRequest.builder()
                .vehicleName(vehicleName)
                .build();

        CompletableFuture<Void> result = new CompletableFuture<>();

        getAsyncClient().getVehicle(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;

                        if (cause instanceof ResourceNotFoundException) {
                            result.completeExceptionally(cause); // don't rewrap
                        } else {
                            result.completeExceptionally(new RuntimeException("Failed to fetch vehicle details: " + cause.getMessage(), cause));
                        }
                    } else {
                        Map<String, Object> details = new HashMap<>();
                        details.put("vehicleName", response.vehicleName());
                        details.put("arn", response.arn());
                        details.put("modelManifestArn", response.modelManifestArn());
                        details.put("decoderManifestArn", response.decoderManifestArn());
                        details.put("attributes", response.attributes());
                        details.put("creationTime", response.creationTime().toString());
                        details.put("lastModificationTime", response.lastModificationTime().toString());

                        logger.info("Vehicle Details:");
                        details.forEach((key, value) -> logger.info("• {} : {}", key, value));

                        result.complete(null); // mark as successful
                    }
                });

        return result;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[getVehicle](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/getVehicle)」を参照してください。

### `listSignalCatalogNodes`
<a name="iotfleetwise_ListSignalCatalogNodes_java_2_topic"></a>

次のコード例は、`listSignalCatalogNodes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously retrieves a list of all nodes in the specified signal catalog.
     *
     * @param signalCatalogName the name of the signal catalog to retrieve nodes for
     * @return a {@link CompletableFuture} that, when completed, contains a {@link List} of {@link Node} objects
     * representing all the nodes in the specified signal catalog
     */
    public CompletableFuture<List<Node>> listSignalCatalogNodeAsync(String signalCatalogName) {
        ListSignalCatalogNodesRequest request = ListSignalCatalogNodesRequest.builder()
                .name(signalCatalogName)
                .build();

        List<Node> allNodes = new ArrayList<>();

        return getAsyncClient().listSignalCatalogNodesPaginator(request)
                .subscribe(response -> allNodes.addAll(response.nodes()))
                .thenApply(v -> allNodes);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[listSignalCatalogNodes](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/listSignalCatalogNodes)」を参照してください。

### `updateDecoderManifest`
<a name="iotfleetwise_UpdateDecoderManifest_java_2_topic"></a>

次のコード例は、`updateDecoderManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the decoder manifest with the given name.
     *
     * @param name the name of the decoder manifest to update
     * @return a {@link CompletableFuture} that completes when the update operation is finished
     */
    public CompletableFuture<Void> updateDecoderManifestAsync(String name) {
        UpdateDecoderManifestRequest request = UpdateDecoderManifestRequest.builder()
                .name(name)
                .status(ManifestStatus.ACTIVE)
                .build();

        return getAsyncClient().updateDecoderManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        throw new CompletionException("Failed to update decoder manifest: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[updateDecoderManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/updateDecoderManifest)」を参照してください。

### `updateModelManifest`
<a name="iotfleetwise_UpdateModelManifest_java_2_topic"></a>

次のコード例は、`updateModelManifest` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the model manifest.
     *
     * @param name the name of the model manifest to update
     */
    public void updateModelManifestAsync(String name) {
        UpdateModelManifestRequest request = UpdateModelManifestRequest.builder()
                .name(name)
                .status(ManifestStatus.ACTIVE)
                .build();

        getAsyncClient().updateModelManifest(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        throw new CompletionException("Failed to update model manifest: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[updateModelManifest](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotfleetwise-2021-06-17/updateModelManifest)」を参照してください。

# AWS IoT SiteWise SDK for Java 2.x を使用した例
<a name="java_2_iotsitewise_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT SiteWise。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoT SiteWiseは
<a name="iotsitewise_Hello_java_2_topic"></a>

次のコード例は、 AWS IoT SiteWiseの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
public class HelloSitewise {
    private static final Logger logger = LoggerFactory.getLogger(HelloSitewise.class);
    public static void main(String[] args) {
         fetchAssetModels();
    }

    /**
     * Fetches asset models using the provided {@link IoTSiteWiseAsyncClient}.
     */
    public static void fetchAssetModels() {
        IoTSiteWiseAsyncClient siteWiseAsyncClient = IoTSiteWiseAsyncClient.create();
        ListAssetModelsRequest assetModelsRequest = ListAssetModelsRequest.builder()
            .assetModelTypes(AssetModelType.ASSET_MODEL)
            .build();

        // Asynchronous paginator - process paginated results.
        ListAssetModelsPublisher listModelsPaginator = siteWiseAsyncClient.listAssetModelsPaginator(assetModelsRequest);
        CompletableFuture<Void> future = listModelsPaginator.subscribe(response -> {
            response.assetModelSummaries().forEach(assetSummary ->
                logger.info("Asset Model Name: {} ", assetSummary.name())
            );
        });

        // Wait for the asynchronous operation to complete
        future.join();
    }
}
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/ListAssetModels)」の「*ListAssetModels*」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iotsitewise_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT SiteWise アセットモデルを作成します。
+  AWS IoT SiteWise アセットを作成します。
+ プロパティ ID 値を取得します。
+  AWS IoT SiteWise アセットにデータを送信します。
+ Asset AWS IoT SiteWise プロパティの値を取得します。
+  AWS IoT SiteWise ポータルを作成します。
+  AWS IoT SiteWise ゲートウェイを作成します。
+  AWS IoT SiteWise ゲートウェイを記述します。
+  AWS IoT SiteWise アセットを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。
 AWS IoT SiteWise 機能を示すインタラクティブなシナリオを実行します。  

```
public class SitewiseScenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    private static final Logger logger = LoggerFactory.getLogger(SitewiseScenario.class);
    static Scanner scanner = new Scanner(System.in);

    private static final String ROLES_STACK = "RoleSitewise";

    static SitewiseActions sitewiseActions = new SitewiseActions();

    public static void main(String[] args) throws Throwable {
        Scanner scanner = new Scanner(System.in);
        String contactEmail = "user@mydomain.com"; // Change email address.
        String assetModelName = "MyAssetModel1";
        String assetName = "MyAsset1" ;
        String portalName = "MyPortal1" ;
        String gatewayName = "MyGateway1" ;
        String myThing =  "MyThing1" ;

        logger.info("""
            AWS IoT SiteWise is a fully managed software-as-a-service (SaaS) that 
            makes it easy to collect, store, organize, and monitor data from industrial equipment and processes. 
            It is designed to help industrial and manufacturing organizations collect data from their equipment and 
            processes, and use that data to make informed decisions about their operations.
                                            
            One of the key features of AWS IoT SiteWise is its ability to connect to a wide range of industrial 
            equipment and systems, including programmable logic controllers (PLCs), sensors, and other 
            industrial devices. It can collect data from these devices and organize it into a unified data model, 
            making it easier to analyze and gain insights from the data. AWS IoT SiteWise also provides tools for 
            visualizing the data, setting up alarms and alerts, and generating reports.
                                
            Another key feature of AWS IoT SiteWise is its ability to scale to handle large volumes of data. 
            It can collect and store data from thousands of devices and process millions of data points per second, 
            making it suitable for large-scale industrial operations. Additionally, AWS IoT SiteWise is designed 
            to be secure and compliant, with features like role-based access controls, data encryption, 
            and integration with other AWS services for additional security and compliance features.
                        
            Let's get started...
            """);

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        try {
            runScenario(assetModelName, assetName, portalName, contactEmail, gatewayName, myThing);
        } catch (RuntimeException e) {
           logger.info(e.getMessage());
        }
    }

    public static void runScenario(String assetModelName, String assetName,  String portalName, String contactEmail, String gatewayName, String myThing) throws Throwable {
        logger.info("Use AWS CloudFormation to create an IAM role that is required for this scenario.");
        CloudFormationHelper.deployCloudFormationStack(ROLES_STACK);
        Map<String, String> stackOutputs = CloudFormationHelper.getStackOutputsAsync(ROLES_STACK).join();
        String iamRole = stackOutputs.get("SitewiseRoleArn");
        logger.info("The ARN of the IAM role is {}",iamRole);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("1. Create an AWS SiteWise Asset Model");
        logger.info("""
             An AWS IoT SiteWise Asset Model is a way to represent the physical assets, such as equipment,
             processes, and systems, that exist in an industrial environment. This model provides a structured and
             hierarchical representation of these assets, allowing users to define the relationships and properties
             of each asset.
             
             This scenario creates two asset model properties: temperature and humidity.
            """);
        waitForInputToContinue(scanner);
        String assetModelId = null;
        try {
            CreateAssetModelResponse response = sitewiseActions.createAssetModelAsync(assetModelName).join();
            assetModelId = response.assetModelId();
            logger.info("Asset Model successfully created. Asset Model ID: {}. ", assetModelId);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceAlreadyExistsException) {
                try {
                    assetModelId = sitewiseActions.getAssetModelIdAsync(assetModelName).join();
                    logger.info("The Asset Model {} already exists. The id of the existing model is {}. Moving on...", assetModelName, assetModelId);
                } catch (CompletionException cex) {
                    logger.error("Exception thrown acquiring the asset model id: {}", cex.getCause().getCause(), cex);
                    return;
                }
            } else {
                logger.info("An unexpected error occurred: " + cause.getMessage(), cause);
                return;
            }
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("2. Create an AWS IoT SiteWise Asset");
        logger.info("""
             The IoT SiteWise model that we just created defines the structure and metadata for your physical assets. 
             Now we create an asset from the asset model.
             
            """);
        logger.info("Let's wait 30 seconds for the asset to be ready.");
        countdown(30);
        waitForInputToContinue(scanner);
        String assetId;
        try {
            CreateAssetResponse response = sitewiseActions.createAssetAsync(assetName, assetModelId).join();
            assetId = response.assetId();
            logger.info("Asset created with ID: {}", assetId);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.info("The asset model id was not found: {}", cause.getMessage(), cause);
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("3. Retrieve the property ID values");
        logger.info("""
             To send data to an asset, we need to get the property ID values. In this scenario, we access the
             temperature and humidity property ID values. 
            """);
        waitForInputToContinue(scanner);
        Map<String, String>  propertyIds = null;
        try {
            propertyIds = sitewiseActions.getPropertyIds(assetModelId).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof IoTSiteWiseException) {
                logger.error("IoTSiteWiseException occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
            return;
        }
        String humPropId =  propertyIds.get("Humidity");
        logger.info("The Humidity property Id is {}", humPropId);
        String tempPropId = propertyIds.get("Temperature");
        logger.info("The Temperature property Id is {}", tempPropId);

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. Send data to an AWS IoT SiteWise Asset");
        logger.info("""
            By sending data to an IoT SiteWise Asset, you can aggregate data from 
            multiple sources, normalize the data into a standard format, and store it in a 
            centralized location. This makes it easier to analyze and gain insights from the data.
                        
            In this example, we generate sample temperature and humidity data and send it to the AWS IoT SiteWise asset.
                        
            """);
        waitForInputToContinue(scanner);
        try {
            sitewiseActions.sendDataToSiteWiseAsync(assetId, tempPropId, humPropId).join();
            logger.info("Data sent successfully.");
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("The AWS resource was not found: {}", cause.getMessage(), cause);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5. Retrieve the value of the IoT SiteWise Asset property");
        logger.info("""
            IoT SiteWise is an AWS service that allows you to collect, process, and analyze industrial data 
            from connected equipment and sensors. One of the key benefits of reading an IoT SiteWise property 
            is the ability to gain valuable insights from your industrial data.
                       
            """);
        waitForInputToContinue(scanner);
        try {
            Double assetVal = sitewiseActions.getAssetPropValueAsync(tempPropId, assetId).join();
            logger.info("The property name is: {}", "Temperature");
            logger.info("The value of this property is: {}", assetVal);

            waitForInputToContinue(scanner);

            assetVal = sitewiseActions.getAssetPropValueAsync(humPropId, assetId).join();
            logger.info("The property name is: {}", "Humidity");
            logger.info("The value of this property is: {}", assetVal);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
                if (cause instanceof ResourceNotFoundException) {
                    logger.info("The AWS resource was not found: {}", cause.getMessage(), cause);
                } else {
                    logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
                }
                return;
            }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("6. Create an IoT SiteWise Gateway");
        logger.info(
            """
                IoT SiteWise Gateway serves as the bridge between industrial equipment, sensors, and the 
                cloud-based IoT SiteWise service. It is responsible for securely collecting, processing, and 
                transmitting data from various industrial assets to the IoT SiteWise platform, 
                enabling real-time monitoring, analysis, and optimization of industrial operations.
                     
                """);
        waitForInputToContinue(scanner);
        String gatewayId = "";
        try {
            gatewayId = sitewiseActions.createGatewayAsync(gatewayName, myThing).join();
            logger.info("Gateway creation completed successfully. id is {}", gatewayId );
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof IoTSiteWiseException siteWiseEx) {
                logger.error("IoT SiteWise error occurred: Error message: {}, Error code {}",
                        siteWiseEx.getMessage(), siteWiseEx.awsErrorDetails().errorCode(), siteWiseEx);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage());
            }
            return;
        }
        logger.info(DASHES);
        logger.info(DASHES);

        logger.info("7. Describe the IoT SiteWise Gateway");
         waitForInputToContinue(scanner);
        try {
            sitewiseActions.describeGatewayAsync(gatewayId)
                .thenAccept(response -> {
                    logger.info("Gateway Name: {}", response.gatewayName());
                    logger.info("Gateway ARN: {}", response.gatewayArn());
                    logger.info("Gateway Platform: {}", response.gatewayPlatform());
                    logger.info("Gateway Creation Date: {}", response.creationDate());
                }).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException notFoundException) {
                logger.error("A ResourceNotFoundException occurred: Error message: {}, Error code {}",
                        notFoundException.getMessage(), notFoundException.awsErrorDetails().errorCode(), notFoundException);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("8. Delete the AWS IoT SiteWise Assets");
        logger.info(
            """
            Before you can delete the Asset Model, you must delete the assets.  
     
            """);
        logger.info("Would you like to delete the IoT SiteWise Assets? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            logger.info("You selected to delete the SiteWise assets.");

            try {
                sitewiseActions.deleteGatewayAsync(gatewayId).join();
                logger.info("Gateway {} was deleted successfully.", gatewayId);
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof ResourceNotFoundException notFoundException) {
                    logger.error("A ResourceNotFoundException occurred: Error message: {}, Error code {}",
                            notFoundException.getMessage(), notFoundException.awsErrorDetails().errorCode(), notFoundException);
                } else {
                    logger.error("An unexpected error occurred: {}", cause.getMessage());
                }
            }

            try {
                sitewiseActions.deleteAssetAsync(assetId).join();
                logger.info("Request to delete asset {} sent successfully", assetId);
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof ResourceNotFoundException notFoundException) {
                    logger.error("A ResourceNotFoundException occurred: Error message: {}, Error code {}",
                            notFoundException.getMessage(), notFoundException.awsErrorDetails().errorCode(), notFoundException);
                } else {
                    logger.error("An unexpected error occurred: {}", cause.getMessage());
                }
            }
            logger.info("Let's wait 1 minute for the asset to be deleted.");
            countdown(60);
            waitForInputToContinue(scanner);
            logger.info("Delete the AWS IoT SiteWise Asset Model");
            try {
                sitewiseActions.deleteAssetModelAsync(assetModelId).join();
                logger.info("Asset model deleted successfully.");
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof ResourceNotFoundException notFoundException) {
                    logger.error("A ResourceNotFoundException occurred: Error message: {}, Error code {}",
                            notFoundException.getMessage(), notFoundException.awsErrorDetails().errorCode(), notFoundException);
                } else {
                    logger.error("An unexpected error occurred: {}", cause.getMessage());
                }
            }
            waitForInputToContinue(scanner);

        } else {
            logger.info("The resources will not be deleted.");
        }
        logger.info(DASHES);

        logger.info(DASHES);
        CloudFormationHelper.destroyCloudFormationStack(ROLES_STACK);
        logger.info("This concludes the AWS IoT SiteWise Scenario");
        logger.info(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                logger.info("Invalid input. Please try again.");
            }
        }
    }

    public static void countdown(int totalSeconds) throws InterruptedException {
        for (int i = totalSeconds; i >= 0; i--) {
            int displayMinutes = i / 60;
            int displaySeconds = i % 60;
            System.out.printf("\r%02d:%02d", displayMinutes, displaySeconds);
            Thread.sleep(1000); // Wait for 1 second
        }
        System.out.println(); // Move to the next line after countdown
        logger.info("Countdown complete!");
    }
}
```
 AWS IoT SiteWise SDK メソッドのラッパークラス。  

```
public class SitewiseActions {

    private static final Logger logger = LoggerFactory.getLogger(SitewiseActions.class);

    private static IoTSiteWiseAsyncClient ioTSiteWiseAsyncClient;

    private static IoTSiteWiseAsyncClient getAsyncClient() {
        if (ioTSiteWiseAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            ioTSiteWiseAsyncClient = IoTSiteWiseAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return ioTSiteWiseAsyncClient;
    }


    /**
     * Creates an asset model.
     *
     * @param name the name of the asset model to create.
     * @return a {@link CompletableFuture} that represents a {@link CreateAssetModelResponse} result. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps it
     *         available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<CreateAssetModelResponse> createAssetModelAsync(String name) {
        PropertyType humidity = PropertyType.builder()
            .measurement(Measurement.builder().build())
            .build();

        PropertyType temperaturePropertyType = PropertyType.builder()
            .measurement(Measurement.builder().build())
            .build();

        AssetModelPropertyDefinition temperatureProperty = AssetModelPropertyDefinition.builder()
            .name("Temperature")
            .dataType(PropertyDataType.DOUBLE)
            .type(temperaturePropertyType)
            .build();

        AssetModelPropertyDefinition humidityProperty = AssetModelPropertyDefinition.builder()
            .name("Humidity")
            .dataType(PropertyDataType.DOUBLE)
            .type(humidity)
            .build();

        CreateAssetModelRequest createAssetModelRequest = CreateAssetModelRequest.builder()
            .assetModelName(name)
            .assetModelDescription("This is my asset model")
            .assetModelProperties(temperatureProperty, humidityProperty)
            .build();

        return getAsyncClient().createAssetModel(createAssetModelRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to create asset model: {} ", exception.getCause().getMessage());
                }
            });
    }


    /**
     * Creates an asset with the specified name and asset model Id.
     *
     * @param assetName    the name of the asset to create.
     * @param assetModelId the Id of the asset model to associate with the asset.
     * @return a {@link CompletableFuture} that represents a {@link CreateAssetResponse} result. The calling code can
     *         attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps it
     *         available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<CreateAssetResponse> createAssetAsync(String assetName, String assetModelId) {
        CreateAssetRequest createAssetRequest = CreateAssetRequest.builder()
            .assetModelId(assetModelId)
            .assetDescription("Created using the AWS SDK for Java")
            .assetName(assetName)
            .build();

        return getAsyncClient().createAsset(createAssetRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to create asset: {}", exception.getCause().getMessage());
                }
            });
    }

    /**
     * Sends data to the SiteWise service.
     *
     * @param assetId        the ID of the asset to which the data will be sent.
     * @param tempPropertyId the ID of the temperature property.
     * @param humidityPropId the ID of the humidity property.
     * @return a {@link CompletableFuture} that represents a {@link BatchPutAssetPropertyValueResponse} result. The
     *         calling code can attach callbacks, then handle the result or exception by calling
     *         {@link CompletableFuture#join()} or {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps it
     *         available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<BatchPutAssetPropertyValueResponse> sendDataToSiteWiseAsync(String assetId, String tempPropertyId, String humidityPropId) {
        Map<String, Double> sampleData = generateSampleData();
        long timestamp = Instant.now().toEpochMilli();

        TimeInNanos time = TimeInNanos.builder()
            .timeInSeconds(timestamp / 1000)
            .offsetInNanos((int) ((timestamp % 1000) * 1000000))
            .build();

        BatchPutAssetPropertyValueRequest request = BatchPutAssetPropertyValueRequest.builder()
            .entries(Arrays.asList(
                PutAssetPropertyValueEntry.builder()
                    .entryId("entry-3")
                    .assetId(assetId)
                    .propertyId(tempPropertyId)
                    .propertyValues(Arrays.asList(
                        AssetPropertyValue.builder()
                            .value(Variant.builder()
                                .doubleValue(sampleData.get("Temperature"))
                                .build())
                            .timestamp(time)
                            .build()
                    ))
                    .build(),
                PutAssetPropertyValueEntry.builder()
                    .entryId("entry-4")
                    .assetId(assetId)
                    .propertyId(humidityPropId)
                    .propertyValues(Arrays.asList(
                        AssetPropertyValue.builder()
                            .value(Variant.builder()
                                .doubleValue(sampleData.get("Humidity"))
                                .build())
                            .timestamp(time)
                            .build()
                    ))
                    .build()
            ))
            .build();

        return getAsyncClient().batchPutAssetPropertyValue(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("An exception occurred: {}", exception.getCause().getMessage());
                }
            });
    }

    /**
     * Fetches the value of an asset property.
     *
     * @param propId  the ID of the asset property to fetch.
     * @param assetId the ID of the asset to fetch the property value for.
     * @return a {@link CompletableFuture} that represents a {@link Double} result. The calling code can attach
     *         callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<Double> getAssetPropValueAsync(String propId, String assetId) {
        GetAssetPropertyValueRequest assetPropertyValueRequest = GetAssetPropertyValueRequest.builder()
                .propertyId(propId)
                .assetId(assetId)
                .build();

        return getAsyncClient().getAssetPropertyValue(assetPropertyValueRequest)
                .handle((response, exception) -> {
                    if (exception != null) {
                        logger.error("Error occurred while fetching property value: {}.", exception.getCause().getMessage());
                        throw (CompletionException) exception;
                    }
                    return response.propertyValue().value().doubleValue();
                });
    }

    /**
     * Retrieves the property IDs associated with a specific asset model.
     *
     * @param assetModelId the ID of the asset model that defines the properties.
     * @return a {@link CompletableFuture} that represents a {@link Map} result that associates the property name to the
     *         propert ID. The calling code can attach callbacks, then handle the result or exception by calling
     *         {@link CompletableFuture#join()} or {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<Map<String, String>> getPropertyIds(String assetModelId) {
        ListAssetModelPropertiesRequest modelPropertiesRequest = ListAssetModelPropertiesRequest.builder().assetModelId(assetModelId).build();
        return getAsyncClient().listAssetModelProperties(modelPropertiesRequest)
            .handle((response, throwable) -> {
                if (response != null) {
                    return response.assetModelPropertySummaries().stream()
                        .collect(Collectors
                            .toMap(AssetModelPropertySummary::name, AssetModelPropertySummary::id));
                } else {
                    logger.error("Error occurred while fetching property IDs: {}.", throwable.getCause().getMessage());
                    throw (CompletionException) throwable;
                }
            });
    }

    /**
     * Deletes an asset.
     *
     * @param assetId the ID of the asset to be deleted.
     * @return a {@link CompletableFuture} that represents a {@link DeleteAssetResponse} result. The calling code can
     *         attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DeleteAssetResponse> deleteAssetAsync(String assetId) {
        DeleteAssetRequest deleteAssetRequest = DeleteAssetRequest.builder()
            .assetId(assetId)
            .build();

        return getAsyncClient().deleteAsset(deleteAssetRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("An error occurred deleting asset with id: {}", assetId);
                }
            });
    }

    /**
     * Deletes an Asset Model with the specified ID.
     *
     * @param assetModelId the ID of the Asset Model to delete.
     * @return a {@link CompletableFuture} that represents a {@link DeleteAssetModelResponse} result. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DeleteAssetModelResponse> deleteAssetModelAsync(String assetModelId) {
        DeleteAssetModelRequest deleteAssetModelRequest = DeleteAssetModelRequest.builder()
            .assetModelId(assetModelId)
            .build();

        return getAsyncClient().deleteAssetModel(deleteAssetModelRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to delete asset model with ID:{}.", exception.getMessage());
                }
            });
    }

    /**
     * Retrieves the asset model ID for the given asset model name.
     *
     * @param assetModelName the name of the asset model for the ID.
     * @return a {@link CompletableFuture} that represents a {@link String} result of the asset model ID or null if the
     *         asset model cannot be found. The calling code can attach callbacks, then handle the result or exception
     *         by calling {@link CompletableFuture#join()} or {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<String> getAssetModelIdAsync(String assetModelName) {
        ListAssetModelsRequest listAssetModelsRequest = ListAssetModelsRequest.builder().build();
        return getAsyncClient().listAssetModels(listAssetModelsRequest)
                .handle((listAssetModelsResponse, exception) -> {
                    if (exception != null) {
                        logger.error("Failed to retrieve Asset Model ID: {}", exception.getCause().getMessage());
                        throw (CompletionException) exception;
                    }
                    for (AssetModelSummary assetModelSummary : listAssetModelsResponse.assetModelSummaries()) {
                        if (assetModelSummary.name().equals(assetModelName)) {
                            return assetModelSummary.id();
                        }
                    }
                    return null;
                });
    }


    /**
     * Creates a new IoT Sitewise gateway.
     *
     * @param gatewayName The name of the gateway to create.
     * @param myThing     The name of the core device thing to associate with the gateway.
     * @return a {@link CompletableFuture} that represents a {@link String} result of the gateways ID. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<String> createGatewayAsync(String gatewayName, String myThing) {
        GreengrassV2 gg = GreengrassV2.builder()
            .coreDeviceThingName(myThing)
            .build();

        GatewayPlatform platform = GatewayPlatform.builder()
            .greengrassV2(gg)
            .build();

        Map<String, String> tag = new HashMap<>();
        tag.put("Environment", "Production");

        CreateGatewayRequest createGatewayRequest = CreateGatewayRequest.builder()
            .gatewayName(gatewayName)
            .gatewayPlatform(platform)
            .tags(tag)
            .build();

        return getAsyncClient().createGateway(createGatewayRequest)
            .handle((response, exception) -> {
                if (exception != null) {
                    logger.error("Error creating the gateway.");
                    throw (CompletionException) exception;
                }
                logger.info("The ARN of the gateway is {}" ,  response.gatewayArn());
                return response.gatewayId();
            });
    }

    /**
     * Deletes the specified gateway.
     *
     * @param gatewayId the ID of the gateway to delete.
     * @return a {@link CompletableFuture} that represents a {@link DeleteGatewayResponse} result.. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DeleteGatewayResponse> deleteGatewayAsync(String gatewayId) {
        DeleteGatewayRequest deleteGatewayRequest = DeleteGatewayRequest.builder()
            .gatewayId(gatewayId)
            .build();

        return getAsyncClient().deleteGateway(deleteGatewayRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to delete gateway: {}", exception.getCause().getMessage());
                }
            });
    }

    /**
     * Describes the specified gateway.
     *
     * @param gatewayId the ID of the gateway to describe.
     * @return a {@link CompletableFuture} that represents a {@link DescribeGatewayResponse} result. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DescribeGatewayResponse> describeGatewayAsync(String gatewayId) {
        DescribeGatewayRequest request = DescribeGatewayRequest.builder()
            .gatewayId(gatewayId)
            .build();

        return getAsyncClient().describeGateway(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("An error occurred during the describeGateway method: {}", exception.getCause().getMessage());
                }
            });
    }

    private static Map<String, Double> generateSampleData() {
        Map<String, Double> data = new HashMap<>();
        data.put("Temperature", 23.5);
        data.put("Humidity", 65.0);
        return data;
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [BatchPutAssetPropertyValue](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/BatchPutAssetPropertyValue)
  + [CreateAsset](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/CreateAsset)
  + [CreateAssetModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/CreateAssetModel)
  + [CreateGateway](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/CreateGateway)
  + [DeleteAsset](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DeleteAsset)
  + [DeleteAssetModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DeleteAssetModel)
  + [DeleteGateway](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DeleteGateway)
  + [DescribeAssetModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DescribeAssetModel)
  + [DescribeGateway](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DescribeGateway)
  + [GetAssetPropertyValue](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/GetAssetPropertyValue)
  + [ListAssetModelProperties](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/ListAssetModelProperties)
  + [ListAssetModels](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/ListAssetModels)

## アクション
<a name="actions"></a>

### `BatchPutAssetPropertyValue`
<a name="iotsitewise_BatchPutAssetPropertyValue_java_2_topic"></a>

次のコード例は、`BatchPutAssetPropertyValue` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Sends data to the SiteWise service.
     *
     * @param assetId        the ID of the asset to which the data will be sent.
     * @param tempPropertyId the ID of the temperature property.
     * @param humidityPropId the ID of the humidity property.
     * @return a {@link CompletableFuture} that represents a {@link BatchPutAssetPropertyValueResponse} result. The
     *         calling code can attach callbacks, then handle the result or exception by calling
     *         {@link CompletableFuture#join()} or {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps it
     *         available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<BatchPutAssetPropertyValueResponse> sendDataToSiteWiseAsync(String assetId, String tempPropertyId, String humidityPropId) {
        Map<String, Double> sampleData = generateSampleData();
        long timestamp = Instant.now().toEpochMilli();

        TimeInNanos time = TimeInNanos.builder()
            .timeInSeconds(timestamp / 1000)
            .offsetInNanos((int) ((timestamp % 1000) * 1000000))
            .build();

        BatchPutAssetPropertyValueRequest request = BatchPutAssetPropertyValueRequest.builder()
            .entries(Arrays.asList(
                PutAssetPropertyValueEntry.builder()
                    .entryId("entry-3")
                    .assetId(assetId)
                    .propertyId(tempPropertyId)
                    .propertyValues(Arrays.asList(
                        AssetPropertyValue.builder()
                            .value(Variant.builder()
                                .doubleValue(sampleData.get("Temperature"))
                                .build())
                            .timestamp(time)
                            .build()
                    ))
                    .build(),
                PutAssetPropertyValueEntry.builder()
                    .entryId("entry-4")
                    .assetId(assetId)
                    .propertyId(humidityPropId)
                    .propertyValues(Arrays.asList(
                        AssetPropertyValue.builder()
                            .value(Variant.builder()
                                .doubleValue(sampleData.get("Humidity"))
                                .build())
                            .timestamp(time)
                            .build()
                    ))
                    .build()
            ))
            .build();

        return getAsyncClient().batchPutAssetPropertyValue(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("An exception occurred: {}", exception.getCause().getMessage());
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[BatchPutAssetPropertyValue](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/BatchPutAssetPropertyValue)」を参照してください。

### `CreateAsset`
<a name="iotsitewise_CreateAsset_java_2_topic"></a>

次のコード例は、`CreateAsset` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an asset with the specified name and asset model Id.
     *
     * @param assetName    the name of the asset to create.
     * @param assetModelId the Id of the asset model to associate with the asset.
     * @return a {@link CompletableFuture} that represents a {@link CreateAssetResponse} result. The calling code can
     *         attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps it
     *         available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<CreateAssetResponse> createAssetAsync(String assetName, String assetModelId) {
        CreateAssetRequest createAssetRequest = CreateAssetRequest.builder()
            .assetModelId(assetModelId)
            .assetDescription("Created using the AWS SDK for Java")
            .assetName(assetName)
            .build();

        return getAsyncClient().createAsset(createAssetRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to create asset: {}", exception.getCause().getMessage());
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateAsset](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/CreateAsset)」を参照してください。

### `CreateAssetModel`
<a name="iotsitewise_CreateAssetModel_java_2_topic"></a>

次のコード例は、`CreateAssetModel` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an asset model.
     *
     * @param name the name of the asset model to create.
     * @return a {@link CompletableFuture} that represents a {@link CreateAssetModelResponse} result. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps it
     *         available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<CreateAssetModelResponse> createAssetModelAsync(String name) {
        PropertyType humidity = PropertyType.builder()
            .measurement(Measurement.builder().build())
            .build();

        PropertyType temperaturePropertyType = PropertyType.builder()
            .measurement(Measurement.builder().build())
            .build();

        AssetModelPropertyDefinition temperatureProperty = AssetModelPropertyDefinition.builder()
            .name("Temperature")
            .dataType(PropertyDataType.DOUBLE)
            .type(temperaturePropertyType)
            .build();

        AssetModelPropertyDefinition humidityProperty = AssetModelPropertyDefinition.builder()
            .name("Humidity")
            .dataType(PropertyDataType.DOUBLE)
            .type(humidity)
            .build();

        CreateAssetModelRequest createAssetModelRequest = CreateAssetModelRequest.builder()
            .assetModelName(name)
            .assetModelDescription("This is my asset model")
            .assetModelProperties(temperatureProperty, humidityProperty)
            .build();

        return getAsyncClient().createAssetModel(createAssetModelRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to create asset model: {} ", exception.getCause().getMessage());
                }
            });
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/CreateAssetModel)」の「*CreateAssetModel*」を参照してください。

### `CreateGateway`
<a name="iotsitewise_CreateGateway_java_2_topic"></a>

次のコード例は、`CreateGateway` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new IoT Sitewise gateway.
     *
     * @param gatewayName The name of the gateway to create.
     * @param myThing     The name of the core device thing to associate with the gateway.
     * @return a {@link CompletableFuture} that represents a {@link String} result of the gateways ID. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<String> createGatewayAsync(String gatewayName, String myThing) {
        GreengrassV2 gg = GreengrassV2.builder()
            .coreDeviceThingName(myThing)
            .build();

        GatewayPlatform platform = GatewayPlatform.builder()
            .greengrassV2(gg)
            .build();

        Map<String, String> tag = new HashMap<>();
        tag.put("Environment", "Production");

        CreateGatewayRequest createGatewayRequest = CreateGatewayRequest.builder()
            .gatewayName(gatewayName)
            .gatewayPlatform(platform)
            .tags(tag)
            .build();

        return getAsyncClient().createGateway(createGatewayRequest)
            .handle((response, exception) -> {
                if (exception != null) {
                    logger.error("Error creating the gateway.");
                    throw (CompletionException) exception;
                }
                logger.info("The ARN of the gateway is {}" ,  response.gatewayArn());
                return response.gatewayId();
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateGateway](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/CreateGateway)」を参照してください。

### `DeleteAsset`
<a name="iotsitewise_DeleteAsset_java_2_topic"></a>

次の例は、`DeleteAsset` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an asset.
     *
     * @param assetId the ID of the asset to be deleted.
     * @return a {@link CompletableFuture} that represents a {@link DeleteAssetResponse} result. The calling code can
     *         attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DeleteAssetResponse> deleteAssetAsync(String assetId) {
        DeleteAssetRequest deleteAssetRequest = DeleteAssetRequest.builder()
            .assetId(assetId)
            .build();

        return getAsyncClient().deleteAsset(deleteAssetRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("An error occurred deleting asset with id: {}", assetId);
                }
            });
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DeleteAsset)」の「*DeleteAsset*」を参照してください。

### `DeleteAssetModel`
<a name="iotsitewise_DeleteAssetModel_java_2_topic"></a>

次のコード例は、`DeleteAssetModel` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an Asset Model with the specified ID.
     *
     * @param assetModelId the ID of the Asset Model to delete.
     * @return a {@link CompletableFuture} that represents a {@link DeleteAssetModelResponse} result. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DeleteAssetModelResponse> deleteAssetModelAsync(String assetModelId) {
        DeleteAssetModelRequest deleteAssetModelRequest = DeleteAssetModelRequest.builder()
            .assetModelId(assetModelId)
            .build();

        return getAsyncClient().deleteAssetModel(deleteAssetModelRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to delete asset model with ID:{}.", exception.getMessage());
                }
            });
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DeleteAssetModel)」の「*DeleteAssetModel*」を参照してください。

### `DeleteGateway`
<a name="iotsitewise_DeleteGateway_java_2_topic"></a>

次のコード例は、`DeleteGateway` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes the specified gateway.
     *
     * @param gatewayId the ID of the gateway to delete.
     * @return a {@link CompletableFuture} that represents a {@link DeleteGatewayResponse} result.. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DeleteGatewayResponse> deleteGatewayAsync(String gatewayId) {
        DeleteGatewayRequest deleteGatewayRequest = DeleteGatewayRequest.builder()
            .gatewayId(gatewayId)
            .build();

        return getAsyncClient().deleteGateway(deleteGatewayRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("Failed to delete gateway: {}", exception.getCause().getMessage());
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteGateway](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DeleteGateway)」を参照してください。

### `DescribeAssetModel`
<a name="iotsitewise_DescribeAssetModel_java_2_topic"></a>

次の例は、`DescribeAssetModel` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the property IDs associated with a specific asset model.
     *
     * @param assetModelId the ID of the asset model that defines the properties.
     * @return a {@link CompletableFuture} that represents a {@link Map} result that associates the property name to the
     *         propert ID. The calling code can attach callbacks, then handle the result or exception by calling
     *         {@link CompletableFuture#join()} or {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<Map<String, String>> getPropertyIds(String assetModelId) {
        ListAssetModelPropertiesRequest modelPropertiesRequest = ListAssetModelPropertiesRequest.builder().assetModelId(assetModelId).build();
        return getAsyncClient().listAssetModelProperties(modelPropertiesRequest)
            .handle((response, throwable) -> {
                if (response != null) {
                    return response.assetModelPropertySummaries().stream()
                        .collect(Collectors
                            .toMap(AssetModelPropertySummary::name, AssetModelPropertySummary::id));
                } else {
                    logger.error("Error occurred while fetching property IDs: {}.", throwable.getCause().getMessage());
                    throw (CompletionException) throwable;
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAssetModel](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DescribeAssetModel)」を参照してください。

### `DescribeGateway`
<a name="iotsitewise_DescribeGateway_java_2_topic"></a>

次のコード例は、`DescribeGateway` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Describes the specified gateway.
     *
     * @param gatewayId the ID of the gateway to describe.
     * @return a {@link CompletableFuture} that represents a {@link DescribeGatewayResponse} result. The calling code
     *         can attach callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<DescribeGatewayResponse> describeGatewayAsync(String gatewayId) {
        DescribeGatewayRequest request = DescribeGatewayRequest.builder()
            .gatewayId(gatewayId)
            .build();

        return getAsyncClient().describeGateway(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    logger.error("An error occurred during the describeGateway method: {}", exception.getCause().getMessage());
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeGateway](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/DescribeGateway)」を参照してください。

### `GetAssetPropertyValue`
<a name="iotsitewise_GetAssetPropertyValue_java_2_topic"></a>

次の例は、`GetAssetPropertyValue` を使用する方法を説明しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Fetches the value of an asset property.
     *
     * @param propId  the ID of the asset property to fetch.
     * @param assetId the ID of the asset to fetch the property value for.
     * @return a {@link CompletableFuture} that represents a {@link Double} result. The calling code can attach
     *         callbacks, then handle the result or exception by calling {@link CompletableFuture#join()} or
     *         {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<Double> getAssetPropValueAsync(String propId, String assetId) {
        GetAssetPropertyValueRequest assetPropertyValueRequest = GetAssetPropertyValueRequest.builder()
                .propertyId(propId)
                .assetId(assetId)
                .build();

        return getAsyncClient().getAssetPropertyValue(assetPropertyValueRequest)
                .handle((response, exception) -> {
                    if (exception != null) {
                        logger.error("Error occurred while fetching property value: {}.", exception.getCause().getMessage());
                        throw (CompletionException) exception;
                    }
                    return response.propertyValue().value().doubleValue();
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAssetPropertyValue](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/GetAssetPropertyValue)」を参照してください。

### `ListAssetModels`
<a name="iotsitewise_ListAssetModels_java_2_topic"></a>

次のコード例は、`ListAssetModels` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the asset model ID for the given asset model name.
     *
     * @param assetModelName the name of the asset model for the ID.
     * @return a {@link CompletableFuture} that represents a {@link String} result of the asset model ID or null if the
     *         asset model cannot be found. The calling code can attach callbacks, then handle the result or exception
     *         by calling {@link CompletableFuture#join()} or {@link CompletableFuture#get()}.
     *         <p>
     *         If any completion stage in this method throws an exception, the method logs the exception cause and keeps
     *         it available to the calling code as a {@link CompletionException}. By calling
     *         {@link CompletionException#getCause()}, the calling code can access the original exception.
     */
    public CompletableFuture<String> getAssetModelIdAsync(String assetModelName) {
        ListAssetModelsRequest listAssetModelsRequest = ListAssetModelsRequest.builder().build();
        return getAsyncClient().listAssetModels(listAssetModelsRequest)
                .handle((listAssetModelsResponse, exception) -> {
                    if (exception != null) {
                        logger.error("Failed to retrieve Asset Model ID: {}", exception.getCause().getMessage());
                        throw (CompletionException) exception;
                    }
                    for (AssetModelSummary assetModelSummary : listAssetModelsResponse.assetModelSummaries()) {
                        if (assetModelSummary.name().equals(assetModelName)) {
                            return assetModelSummary.id();
                        }
                    }
                    return null;
                });
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/iotsitewise-2019-12-02/ListAssetModels)」の「*ListAssetModels*」を参照してください。

# SDK for Java 2.x を使用する Amazon Keyspaces の例
<a name="java_2_keyspaces_code_examples"></a>

次のコード例は、Amazon Keyspaces AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Keyspaces
<a name="keyspaces_Hello_java_2_topic"></a>

次のコード例は、Amazon Keyspaces の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.keyspaces.KeyspacesClient;
import software.amazon.awssdk.services.keyspaces.model.KeyspaceSummary;
import software.amazon.awssdk.services.keyspaces.model.KeyspacesException;
import software.amazon.awssdk.services.keyspaces.model.ListKeyspacesRequest;
import software.amazon.awssdk.services.keyspaces.model.ListKeyspacesResponse;
import java.util.List;

/**
 * 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 HelloKeyspaces {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        KeyspacesClient keyClient = KeyspacesClient.builder()
                .region(region)
                .build();

        listKeyspaces(keyClient);
    }

    public static void listKeyspaces(KeyspacesClient keyClient) {
        try {
            ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder()
                    .maxResults(10)
                    .build();

            ListKeyspacesResponse response = keyClient.listKeyspaces(keyspacesRequest);
            List<KeyspaceSummary> keyspaces = response.keyspaces();
            for (KeyspaceSummary keyspace : keyspaces) {
                System.out.println("The name of the keyspace is " + keyspace.keyspaceName());
            }

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListKeyspaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/ListKeyspaces)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="keyspaces_Scenario_GetStartedKeyspaces_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キースペースとテーブルを作成する。テーブルスキーマにはムービーデータが保存され、ポイントインタイムリカバリが有効になっています。
+ SigV4 認証による安全な TLS 接続を使用してキースペースに接続します。
+ テーブルに対してクエリを実行します。ムービーデータを追加、取得、更新します。
+ テーブルを更新する。視聴したムービーを追跡する列を追加します。
+ テーブルを以前の状態に戻し、リソースをクリーンアップします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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
 *
 * Before running this Java code example, you must create a
 * Java keystore (JKS) file and place it in your project's resources folder.
 *
 * This file is a secure file format used to hold certificate information for
 * Java applications. This is required to make a connection to Amazon Keyspaces.
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/keyspaces/latest/devguide/using_java_driver.html
 *
 * This Java example performs the following tasks:
 *
 * 1. Create a keyspace.
 * 2. Check for keyspace existence.
 * 3. List keyspaces using a paginator.
 * 4. Create a table with a simple movie data schema and enable point-in-time
 * recovery.
 * 5. Check for the table to be in an Active state.
 * 6. List all tables in the keyspace.
 * 7. Use a Cassandra driver to insert some records into the Movie table.
 * 8. Get all records from the Movie table.
 * 9. Get a specific Movie.
 * 10. Get a UTC timestamp for the current time.
 * 11. Update the table schema to add a ‘watched’ Boolean column.
 * 12. Update an item as watched.
 * 13. Query for items with watched = True.
 * 14. Restore the table back to the previous state using the timestamp.
 * 15. Check for completion of the restore action.
 * 16. Delete the table.
 * 17. Confirm that both tables are deleted.
 * 18. Delete the keyspace.
 */

public class ScenarioKeyspaces {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    /*
     * Usage:
     * fileName - The name of the JSON file that contains movie data. (Get this file
     * from the GitHub repo at resources/sample_file.)
     * keyspaceName - The name of the keyspace to create.
     */
    public static void main(String[] args) throws InterruptedException, IOException {
        String fileName = "<Replace with the JSON file that contains movie data>";
        String keyspaceName = "<Replace with the name of the keyspace to create>";
        String titleUpdate = "The Family";
        int yearUpdate = 2013;
        String tableName = "Movie";
        String tableNameRestore = "MovieRestore";
        Region region = Region.US_EAST_1;
        KeyspacesClient keyClient = KeyspacesClient.builder()
                .region(region)
                .build();

        DriverConfigLoader loader = DriverConfigLoader.fromClasspath("application.conf");
        CqlSession session = CqlSession.builder()
                .withConfigLoader(loader)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon Keyspaces example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Create a keyspace.");
        createKeySpace(keyClient, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        Thread.sleep(5000);
        System.out.println("2. Check for keyspace existence.");
        checkKeyspaceExistence(keyClient, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. List keyspaces using a paginator.");
        listKeyspacesPaginator(keyClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Create a table with a simple movie data schema and enable point-in-time recovery.");
        createTable(keyClient, keyspaceName, tableName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Check for the table to be in an Active state.");
        Thread.sleep(6000);
        checkTable(keyClient, keyspaceName, tableName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. List all tables in the keyspace.");
        listTables(keyClient, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Use a Cassandra driver to insert some records into the Movie table.");
        Thread.sleep(6000);
        loadData(session, fileName, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Get all records from the Movie table.");
        getMovieData(session, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. Get a specific Movie.");
        getSpecificMovie(session, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Get a UTC timestamp for the current time.");
        ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
        System.out.println("DATETIME = " + Date.from(utc.toInstant()));
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Update the table schema to add a watched Boolean column.");
        updateTable(keyClient, keyspaceName, tableName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("12. Update an item as watched.");
        Thread.sleep(10000); // Wait 10 secs for the update.
        updateRecord(session, keyspaceName, titleUpdate, yearUpdate);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("13. Query for items with watched = True.");
        getWatchedData(session, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("14. Restore the table back to the previous state using the timestamp.");
        System.out.println("Note that the restore operation can take up to 20 minutes.");
        restoreTable(keyClient, keyspaceName, utc);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("15. Check for completion of the restore action.");
        Thread.sleep(5000);
        checkRestoredTable(keyClient, keyspaceName, "MovieRestore");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("16. Delete both tables.");
        deleteTable(keyClient, keyspaceName, tableName);
        deleteTable(keyClient, keyspaceName, tableNameRestore);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("17. Confirm that both tables are deleted.");
        checkTableDelete(keyClient, keyspaceName, tableName);
        checkTableDelete(keyClient, keyspaceName, tableNameRestore);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("18. Delete the keyspace.");
        deleteKeyspace(keyClient, keyspaceName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The scenario has completed successfully.");
        System.out.println(DASHES);
    }

    public static void deleteKeyspace(KeyspacesClient keyClient, String keyspaceName) {
        try {
            DeleteKeyspaceRequest deleteKeyspaceRequest = DeleteKeyspaceRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            keyClient.deleteKeyspace(deleteKeyspaceRequest);

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void checkTableDelete(KeyspacesClient keyClient, String keyspaceName, String tableName)
            throws InterruptedException {
        try {
            String status;
            GetTableResponse response;
            GetTableRequest tableRequest = GetTableRequest.builder()
                    .keyspaceName(keyspaceName)
                    .tableName(tableName)
                    .build();

            // Keep looping until table cannot be found and a ResourceNotFoundException is
            // thrown.
            while (true) {
                response = keyClient.getTable(tableRequest);
                status = response.statusAsString();
                System.out.println(". The table status is " + status);
                Thread.sleep(500);
            }

        } catch (ResourceNotFoundException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        System.out.println("The table is deleted");
    }

    public static void deleteTable(KeyspacesClient keyClient, String keyspaceName, String tableName) {
        try {
            DeleteTableRequest tableRequest = DeleteTableRequest.builder()
                    .keyspaceName(keyspaceName)
                    .tableName(tableName)
                    .build();

            keyClient.deleteTable(tableRequest);

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void checkRestoredTable(KeyspacesClient keyClient, String keyspaceName, String tableName)
            throws InterruptedException {
        try {
            boolean tableStatus = false;
            String status;
            GetTableResponse response = null;
            GetTableRequest tableRequest = GetTableRequest.builder()
                    .keyspaceName(keyspaceName)
                    .tableName(tableName)
                    .build();

            while (!tableStatus) {
                response = keyClient.getTable(tableRequest);
                status = response.statusAsString();
                System.out.println("The table status is " + status);

                if (status.compareTo("ACTIVE") == 0) {
                    tableStatus = true;
                }
                Thread.sleep(500);
            }

            List<ColumnDefinition> cols = response.schemaDefinition().allColumns();
            for (ColumnDefinition def : cols) {
                System.out.println("The column name is " + def.name());
                System.out.println("The column type is " + def.type());
            }

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void restoreTable(KeyspacesClient keyClient, String keyspaceName, ZonedDateTime utc) {
        try {
            Instant myTime = utc.toInstant();
            RestoreTableRequest restoreTableRequest = RestoreTableRequest.builder()
                    .restoreTimestamp(myTime)
                    .sourceTableName("Movie")
                    .targetKeyspaceName(keyspaceName)
                    .targetTableName("MovieRestore")
                    .sourceKeyspaceName(keyspaceName)
                    .build();

            RestoreTableResponse response = keyClient.restoreTable(restoreTableRequest);
            System.out.println("The ARN of the restored table is " + response.restoredTableARN());

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void getWatchedData(CqlSession session, String keyspaceName) {
        ResultSet resultSet = session
                .execute("SELECT * FROM \"" + keyspaceName + "\".\"Movie\" WHERE watched = true ALLOW FILTERING;");
        resultSet.forEach(item -> {
            System.out.println("The Movie title is " + item.getString("title"));
            System.out.println("The Movie year is " + item.getInt("year"));
            System.out.println("The plot is " + item.getString("plot"));
        });
    }

    public static void updateRecord(CqlSession session, String keySpace, String titleUpdate, int yearUpdate) {
        String sqlStatement = "UPDATE \"" + keySpace
                + "\".\"Movie\" SET watched=true WHERE title = :k0 AND year = :k1;";
        BatchStatementBuilder builder = BatchStatement.builder(DefaultBatchType.UNLOGGED);
        builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
        PreparedStatement preparedStatement = session.prepare(sqlStatement);
        builder.addStatement(preparedStatement.boundStatementBuilder()
                .setString("k0", titleUpdate)
                .setInt("k1", yearUpdate)
                .build());

        BatchStatement batchStatement = builder.build();
        session.execute(batchStatement);
    }

    public static void updateTable(KeyspacesClient keyClient, String keySpace, String tableName) {
        try {
            ColumnDefinition def = ColumnDefinition.builder()
                    .name("watched")
                    .type("boolean")
                    .build();

            UpdateTableRequest tableRequest = UpdateTableRequest.builder()
                    .keyspaceName(keySpace)
                    .tableName(tableName)
                    .addColumns(def)
                    .build();

            keyClient.updateTable(tableRequest);

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void getSpecificMovie(CqlSession session, String keyspaceName) {
        ResultSet resultSet = session.execute(
                "SELECT * FROM \"" + keyspaceName + "\".\"Movie\" WHERE title = 'The Family' ALLOW FILTERING ;");
        resultSet.forEach(item -> {
            System.out.println("The Movie title is " + item.getString("title"));
            System.out.println("The Movie year is " + item.getInt("year"));
            System.out.println("The plot is " + item.getString("plot"));
        });
    }

    // Get records from the Movie table.
    public static void getMovieData(CqlSession session, String keyspaceName) {
        ResultSet resultSet = session.execute("SELECT * FROM \"" + keyspaceName + "\".\"Movie\";");
        resultSet.forEach(item -> {
            System.out.println("The Movie title is " + item.getString("title"));
            System.out.println("The Movie year is " + item.getInt("year"));
            System.out.println("The plot is " + item.getString("plot"));
        });
    }

    // Load data into the table.
    public static void loadData(CqlSession session, String fileName, String keySpace) throws IOException {
        String sqlStatement = "INSERT INTO \"" + keySpace + "\".\"Movie\" (title, year, plot) values (:k0, :k1, :k2)";
        JsonParser parser = new JsonFactory().createParser(new File(fileName));
        com.fasterxml.jackson.databind.JsonNode rootNode = new ObjectMapper().readTree(parser);
        Iterator<JsonNode> iter = rootNode.iterator();
        ObjectNode currentNode;
        int t = 0;
        while (iter.hasNext()) {

            // Add 20 movies to the table.
            if (t == 20)
                break;
            currentNode = (ObjectNode) iter.next();

            int year = currentNode.path("year").asInt();
            String title = currentNode.path("title").asText();
            String plot = currentNode.path("info").path("plot").toString();

            // Insert the data into the Amazon Keyspaces table.
            BatchStatementBuilder builder = BatchStatement.builder(DefaultBatchType.UNLOGGED);
            builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
            PreparedStatement preparedStatement = session.prepare(sqlStatement);
            builder.addStatement(preparedStatement.boundStatementBuilder()
                    .setString("k0", title)
                    .setInt("k1", year)
                    .setString("k2", plot)
                    .build());

            BatchStatement batchStatement = builder.build();
            session.execute(batchStatement);
            t++;
        }

        System.out.println("You have added " + t + " records successfully!");
    }

    public static void listTables(KeyspacesClient keyClient, String keyspaceName) {
        try {
            ListTablesRequest tablesRequest = ListTablesRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            ListTablesIterable listRes = keyClient.listTablesPaginator(tablesRequest);
            listRes.stream()
                    .flatMap(r -> r.tables().stream())
                    .forEach(content -> System.out.println(" ARN: " + content.resourceArn() +
                            " Table name: " + content.tableName()));

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void checkTable(KeyspacesClient keyClient, String keyspaceName, String tableName)
            throws InterruptedException {
        try {
            boolean tableStatus = false;
            String status;
            GetTableResponse response = null;
            GetTableRequest tableRequest = GetTableRequest.builder()
                    .keyspaceName(keyspaceName)
                    .tableName(tableName)
                    .build();

            while (!tableStatus) {
                response = keyClient.getTable(tableRequest);
                status = response.statusAsString();
                System.out.println(". The table status is " + status);

                if (status.compareTo("ACTIVE") == 0) {
                    tableStatus = true;
                }
                Thread.sleep(500);
            }

            List<ColumnDefinition> cols = response.schemaDefinition().allColumns();
            for (ColumnDefinition def : cols) {
                System.out.println("The column name is " + def.name());
                System.out.println("The column type is " + def.type());
            }

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void createTable(KeyspacesClient keyClient, String keySpace, String tableName) {
        try {
            // Set the columns.
            ColumnDefinition defTitle = ColumnDefinition.builder()
                    .name("title")
                    .type("text")
                    .build();

            ColumnDefinition defYear = ColumnDefinition.builder()
                    .name("year")
                    .type("int")
                    .build();

            ColumnDefinition defReleaseDate = ColumnDefinition.builder()
                    .name("release_date")
                    .type("timestamp")
                    .build();

            ColumnDefinition defPlot = ColumnDefinition.builder()
                    .name("plot")
                    .type("text")
                    .build();

            List<ColumnDefinition> colList = new ArrayList<>();
            colList.add(defTitle);
            colList.add(defYear);
            colList.add(defReleaseDate);
            colList.add(defPlot);

            // Set the keys.
            PartitionKey yearKey = PartitionKey.builder()
                    .name("year")
                    .build();

            PartitionKey titleKey = PartitionKey.builder()
                    .name("title")
                    .build();

            List<PartitionKey> keyList = new ArrayList<>();
            keyList.add(yearKey);
            keyList.add(titleKey);

            SchemaDefinition schemaDefinition = SchemaDefinition.builder()
                    .partitionKeys(keyList)
                    .allColumns(colList)
                    .build();

            PointInTimeRecovery timeRecovery = PointInTimeRecovery.builder()
                    .status(PointInTimeRecoveryStatus.ENABLED)
                    .build();

            CreateTableRequest tableRequest = CreateTableRequest.builder()
                    .keyspaceName(keySpace)
                    .tableName(tableName)
                    .schemaDefinition(schemaDefinition)
                    .pointInTimeRecovery(timeRecovery)
                    .build();

            CreateTableResponse response = keyClient.createTable(tableRequest);
            System.out.println("The table ARN is " + response.resourceArn());

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void listKeyspacesPaginator(KeyspacesClient keyClient) {
        try {
            ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder()
                    .maxResults(10)
                    .build();

            ListKeyspacesIterable listRes = keyClient.listKeyspacesPaginator(keyspacesRequest);
            listRes.stream()
                    .flatMap(r -> r.keyspaces().stream())
                    .forEach(content -> System.out.println(" Name: " + content.keyspaceName()));

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void checkKeyspaceExistence(KeyspacesClient keyClient, String keyspaceName) {
        try {
            GetKeyspaceRequest keyspaceRequest = GetKeyspaceRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            GetKeyspaceResponse response = keyClient.getKeyspace(keyspaceRequest);
            String name = response.keyspaceName();
            System.out.println("The " + name + " KeySpace is ready");

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void createKeySpace(KeyspacesClient keyClient, String keyspaceName) {
        try {
            CreateKeyspaceRequest keyspaceRequest = CreateKeyspaceRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            CreateKeyspaceResponse response = keyClient.createKeyspace(keyspaceRequest);
            System.out.println("The ARN of the KeySpace is " + response.resourceArn());

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateKeyspace](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/CreateKeyspace)
  + [CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/CreateTable)
  + [DeleteKeyspace](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/DeleteKeyspace)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/DeleteTable)
  + [GetKeyspace](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/GetKeyspace)
  + [GetTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/GetTable)
  + [ListKeyspaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/ListKeyspaces)
  + [ListTables](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/ListTables)
  + [RestoreTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/RestoreTable)
  + [UpdateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/UpdateTable)

## アクション
<a name="actions"></a>

### `CreateKeyspace`
<a name="keyspaces_CreateKeyspace_java_2_topic"></a>

次のコード例は、`CreateKeyspace` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void createKeySpace(KeyspacesClient keyClient, String keyspaceName) {
        try {
            CreateKeyspaceRequest keyspaceRequest = CreateKeyspaceRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            CreateKeyspaceResponse response = keyClient.createKeyspace(keyspaceRequest);
            System.out.println("The ARN of the KeySpace is " + response.resourceArn());

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateKeyspace](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/CreateKeyspace)」を参照してください。

### `CreateTable`
<a name="keyspaces_CreateTable_java_2_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void createTable(KeyspacesClient keyClient, String keySpace, String tableName) {
        try {
            // Set the columns.
            ColumnDefinition defTitle = ColumnDefinition.builder()
                    .name("title")
                    .type("text")
                    .build();

            ColumnDefinition defYear = ColumnDefinition.builder()
                    .name("year")
                    .type("int")
                    .build();

            ColumnDefinition defReleaseDate = ColumnDefinition.builder()
                    .name("release_date")
                    .type("timestamp")
                    .build();

            ColumnDefinition defPlot = ColumnDefinition.builder()
                    .name("plot")
                    .type("text")
                    .build();

            List<ColumnDefinition> colList = new ArrayList<>();
            colList.add(defTitle);
            colList.add(defYear);
            colList.add(defReleaseDate);
            colList.add(defPlot);

            // Set the keys.
            PartitionKey yearKey = PartitionKey.builder()
                    .name("year")
                    .build();

            PartitionKey titleKey = PartitionKey.builder()
                    .name("title")
                    .build();

            List<PartitionKey> keyList = new ArrayList<>();
            keyList.add(yearKey);
            keyList.add(titleKey);

            SchemaDefinition schemaDefinition = SchemaDefinition.builder()
                    .partitionKeys(keyList)
                    .allColumns(colList)
                    .build();

            PointInTimeRecovery timeRecovery = PointInTimeRecovery.builder()
                    .status(PointInTimeRecoveryStatus.ENABLED)
                    .build();

            CreateTableRequest tableRequest = CreateTableRequest.builder()
                    .keyspaceName(keySpace)
                    .tableName(tableName)
                    .schemaDefinition(schemaDefinition)
                    .pointInTimeRecovery(timeRecovery)
                    .build();

            CreateTableResponse response = keyClient.createTable(tableRequest);
            System.out.println("The table ARN is " + response.resourceArn());

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[CreateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/CreateTable)」を参照してください。

### `DeleteKeyspace`
<a name="keyspaces_DeleteKeyspace_java_2_topic"></a>

次のコード例は、`DeleteKeyspace` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteKeyspace(KeyspacesClient keyClient, String keyspaceName) {
        try {
            DeleteKeyspaceRequest deleteKeyspaceRequest = DeleteKeyspaceRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            keyClient.deleteKeyspace(deleteKeyspaceRequest);

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[DeleteKeyspace](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/DeleteKeyspace)」を参照してください。

### `DeleteTable`
<a name="keyspaces_DeleteTable_java_2_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteTable(KeyspacesClient keyClient, String keyspaceName, String tableName) {
        try {
            DeleteTableRequest tableRequest = DeleteTableRequest.builder()
                    .keyspaceName(keyspaceName)
                    .tableName(tableName)
                    .build();

            keyClient.deleteTable(tableRequest);

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/DeleteTable)」を参照してください。

### `GetKeyspace`
<a name="keyspaces_GetKeyspace_java_2_topic"></a>

次のコード例は、`GetKeyspace` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void checkKeyspaceExistence(KeyspacesClient keyClient, String keyspaceName) {
        try {
            GetKeyspaceRequest keyspaceRequest = GetKeyspaceRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            GetKeyspaceResponse response = keyClient.getKeyspace(keyspaceRequest);
            String name = response.keyspaceName();
            System.out.println("The " + name + " KeySpace is ready");

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetKeyspace](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/GetKeyspace)」を参照してください。

### `GetTable`
<a name="keyspaces_GetTable_java_2_topic"></a>

次のコード例は、`GetTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void checkTable(KeyspacesClient keyClient, String keyspaceName, String tableName)
            throws InterruptedException {
        try {
            boolean tableStatus = false;
            String status;
            GetTableResponse response = null;
            GetTableRequest tableRequest = GetTableRequest.builder()
                    .keyspaceName(keyspaceName)
                    .tableName(tableName)
                    .build();

            while (!tableStatus) {
                response = keyClient.getTable(tableRequest);
                status = response.statusAsString();
                System.out.println(". The table status is " + status);

                if (status.compareTo("ACTIVE") == 0) {
                    tableStatus = true;
                }
                Thread.sleep(500);
            }

            List<ColumnDefinition> cols = response.schemaDefinition().allColumns();
            for (ColumnDefinition def : cols) {
                System.out.println("The column name is " + def.name());
                System.out.println("The column type is " + def.type());
            }

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/GetTable)」を参照してください。

### `ListKeyspaces`
<a name="keyspaces_ListKeyspaces_java_2_topic"></a>

次のコード例は、`ListKeyspaces` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void listKeyspacesPaginator(KeyspacesClient keyClient) {
        try {
            ListKeyspacesRequest keyspacesRequest = ListKeyspacesRequest.builder()
                    .maxResults(10)
                    .build();

            ListKeyspacesIterable listRes = keyClient.listKeyspacesPaginator(keyspacesRequest);
            listRes.stream()
                    .flatMap(r -> r.keyspaces().stream())
                    .forEach(content -> System.out.println(" Name: " + content.keyspaceName()));

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListKeyspaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/ListKeyspaces)」を参照してください。

### `ListTables`
<a name="keyspaces_ListTables_java_2_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void listTables(KeyspacesClient keyClient, String keyspaceName) {
        try {
            ListTablesRequest tablesRequest = ListTablesRequest.builder()
                    .keyspaceName(keyspaceName)
                    .build();

            ListTablesIterable listRes = keyClient.listTablesPaginator(tablesRequest);
            listRes.stream()
                    .flatMap(r -> r.tables().stream())
                    .forEach(content -> System.out.println(" ARN: " + content.resourceArn() +
                            " Table name: " + content.tableName()));

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListTables](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/ListTables)」を参照してください。

### `RestoreTable`
<a name="keyspaces_RestoreTable_java_2_topic"></a>

次のコード例は、`RestoreTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void restoreTable(KeyspacesClient keyClient, String keyspaceName, ZonedDateTime utc) {
        try {
            Instant myTime = utc.toInstant();
            RestoreTableRequest restoreTableRequest = RestoreTableRequest.builder()
                    .restoreTimestamp(myTime)
                    .sourceTableName("Movie")
                    .targetKeyspaceName(keyspaceName)
                    .targetTableName("MovieRestore")
                    .sourceKeyspaceName(keyspaceName)
                    .build();

            RestoreTableResponse response = keyClient.restoreTable(restoreTableRequest);
            System.out.println("The ARN of the restored table is " + response.restoredTableARN());

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンスの*の「[RestoreTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/RestoreTable)」を参照してください。

### `UpdateTable`
<a name="keyspaces_UpdateTable_java_2_topic"></a>

次のコード例は、`UpdateTable` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
    public static void updateTable(KeyspacesClient keyClient, String keySpace, String tableName) {
        try {
            ColumnDefinition def = ColumnDefinition.builder()
                    .name("watched")
                    .type("boolean")
                    .build();

            UpdateTableRequest tableRequest = UpdateTableRequest.builder()
                    .keyspaceName(keySpace)
                    .tableName(tableName)
                    .addColumns(def)
                    .build();

            keyClient.updateTable(tableRequest);

        } catch (KeyspacesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateTable](https://docs.aws.amazon.com/goto/SdkForJavaV2/keyspaces-2022-02-10/UpdateTable)」を参照してください。

# SDK for Java 2.x を使用した Kinesis の例
<a name="java_2_kinesis_code_examples"></a>

次のコード例は、Kinesis AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateStream`
<a name="kinesis_CreateStream_java_2_topic"></a>

次のコード例は、`CreateStream` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisClient;
import software.amazon.awssdk.services.kinesis.model.CreateStreamRequest;
import software.amazon.awssdk.services.kinesis.model.KinesisException;

/**
 * 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 CreateDataStream {
    public static void main(String[] args) {

        final String usage = """

                Usage:
                    <streamName>

                Where:
                    streamName - The Amazon Kinesis data stream (for example, StockTradeStream).
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String streamName = args[0];
        Region region = Region.US_EAST_1;
        KinesisClient kinesisClient = KinesisClient.builder()
                .region(region)
                .build();
        createStream(kinesisClient, streamName);
        System.out.println("Done");
        kinesisClient.close();
    }

    public static void createStream(KinesisClient kinesisClient, String streamName) {
        try {
            CreateStreamRequest streamReq = CreateStreamRequest.builder()
                    .streamName(streamName)
                    .shardCount(1)
                    .build();

            kinesisClient.createStream(streamReq);

        } catch (KinesisException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/kinesis-2013-12-02/CreateStream)」を参照してください。

### `DeleteStream`
<a name="kinesis_DeleteStream_java_2_topic"></a>

次のコード例は、`DeleteStream` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisClient;
import software.amazon.awssdk.services.kinesis.model.DeleteStreamRequest;
import software.amazon.awssdk.services.kinesis.model.KinesisException;

/**
 * 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 DeleteDataStream {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <streamName>

                Where:
                    streamName - The Amazon Kinesis data stream (for example, StockTradeStream)
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String streamName = args[0];
        Region region = Region.US_EAST_1;
        KinesisClient kinesisClient = KinesisClient.builder()
                .region(region)
                .build();

        deleteStream(kinesisClient, streamName);
        kinesisClient.close();
        System.out.println("Done");
    }

    public static void deleteStream(KinesisClient kinesisClient, String streamName) {
        try {
            DeleteStreamRequest delStream = DeleteStreamRequest.builder()
                    .streamName(streamName)
                    .build();

            kinesisClient.deleteStream(delStream);

        } catch (KinesisException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/kinesis-2013-12-02/DeleteStream)」を参照してください。

### `GetRecords`
<a name="kinesis_GetRecords_java_2_topic"></a>

次のコード例は、`GetRecords` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisClient;
import software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse;
import software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest;
import software.amazon.awssdk.services.kinesis.model.Shard;
import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest;
import software.amazon.awssdk.services.kinesis.model.GetShardIteratorResponse;
import software.amazon.awssdk.services.kinesis.model.Record;
import software.amazon.awssdk.services.kinesis.model.GetRecordsRequest;
import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 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 GetRecords {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <streamName>

                Where:
                    streamName - The Amazon Kinesis data stream to read from (for example, StockTradeStream).
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String streamName = args[0];
        Region region = Region.US_EAST_1;
        KinesisClient kinesisClient = KinesisClient.builder()
                .region(region)
                .build();

        getStockTrades(kinesisClient, streamName);
        kinesisClient.close();
    }

    public static void getStockTrades(KinesisClient kinesisClient, String streamName) {
        String shardIterator;
        String lastShardId = null;
        DescribeStreamRequest describeStreamRequest = DescribeStreamRequest.builder()
                .streamName(streamName)
                .build();

        List<Shard> shards = new ArrayList<>();
        DescribeStreamResponse streamRes;
        do {
            streamRes = kinesisClient.describeStream(describeStreamRequest);
            shards.addAll(streamRes.streamDescription().shards());

            if (shards.size() > 0) {
                lastShardId = shards.get(shards.size() - 1).shardId();
            }
        } while (streamRes.streamDescription().hasMoreShards());

        GetShardIteratorRequest itReq = GetShardIteratorRequest.builder()
                .streamName(streamName)
                .shardIteratorType("TRIM_HORIZON")
                .shardId(lastShardId)
                .build();

        GetShardIteratorResponse shardIteratorResult = kinesisClient.getShardIterator(itReq);
        shardIterator = shardIteratorResult.shardIterator();

        // Continuously read data records from shard.
        List<Record> records;

        // Create new GetRecordsRequest with existing shardIterator.
        // Set maximum records to return to 1000.
        GetRecordsRequest recordsRequest = GetRecordsRequest.builder()
                .shardIterator(shardIterator)
                .limit(1000)
                .build();

        GetRecordsResponse result = kinesisClient.getRecords(recordsRequest);

        // Put result into record list. Result may be empty.
        records = result.records();

        // Print records
        for (Record record : records) {
            SdkBytes byteBuffer = record.data();
            System.out.printf("Seq No: %s - %s%n", record.sequenceNumber(), new String(byteBuffer.asByteArray()));
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[GetRecords](https://docs.aws.amazon.com/goto/SdkForJavaV2/kinesis-2013-12-02/GetRecords)」を参照してください。**

### `PutRecord`
<a name="kinesis_PutRecord_java_2_topic"></a>

次のコード例は、`PutRecord` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kinesis.KinesisClient;
import software.amazon.awssdk.services.kinesis.model.PutRecordRequest;
import software.amazon.awssdk.services.kinesis.model.KinesisException;
import software.amazon.awssdk.services.kinesis.model.DescribeStreamRequest;
import software.amazon.awssdk.services.kinesis.model.DescribeStreamResponse;

/**
 * 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 StockTradesWriter {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <streamName>

                Where:
                    streamName - The Amazon Kinesis data stream to which records are written (for example, StockTradeStream)
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String streamName = args[0];
        Region region = Region.US_EAST_1;
        KinesisClient kinesisClient = KinesisClient.builder()
                .region(region)
                .build();

        // Ensure that the Kinesis Stream is valid.
        validateStream(kinesisClient, streamName);
        setStockData(kinesisClient, streamName);
        kinesisClient.close();
    }

    public static void setStockData(KinesisClient kinesisClient, String streamName) {
        try {
            // Repeatedly send stock trades with a 100 milliseconds wait in between.
            StockTradeGenerator stockTradeGenerator = new StockTradeGenerator();

            // Put in 50 Records for this example.
            int index = 50;
            for (int x = 0; x < index; x++) {
                StockTrade trade = stockTradeGenerator.getRandomTrade();
                sendStockTrade(trade, kinesisClient, streamName);
                Thread.sleep(100);
            }

        } catch (KinesisException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }

    private static void sendStockTrade(StockTrade trade, KinesisClient kinesisClient,
            String streamName) {
        byte[] bytes = trade.toJsonAsBytes();

        // The bytes could be null if there is an issue with the JSON serialization by
        // the Jackson JSON library.
        if (bytes == null) {
            System.out.println("Could not get JSON bytes for stock trade");
            return;
        }

        System.out.println("Putting trade: " + trade);
        PutRecordRequest request = PutRecordRequest.builder()
                .partitionKey(trade.getTickerSymbol()) // We use the ticker symbol as the partition key, explained in
                                                       // the Supplemental Information section below.
                .streamName(streamName)
                .data(SdkBytes.fromByteArray(bytes))
                .build();

        try {
            kinesisClient.putRecord(request);
        } catch (KinesisException e) {
            System.err.println(e.getMessage());
        }
    }

    private static void validateStream(KinesisClient kinesisClient, String streamName) {
        try {
            DescribeStreamRequest describeStreamRequest = DescribeStreamRequest.builder()
                    .streamName(streamName)
                    .build();

            DescribeStreamResponse describeStreamResponse = kinesisClient.describeStream(describeStreamRequest);

            if (!describeStreamResponse.streamDescription().streamStatus().toString().equals("ACTIVE")) {
                System.err.println("Stream " + streamName + " is not active. Please wait a few moments and try again.");
                System.exit(1);
            }

        } catch (KinesisException e) {
            System.err.println("Error found while describing the stream " + streamName);
            System.err.println(e);
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutRecord](https://docs.aws.amazon.com/goto/SdkForJavaV2/kinesis-2013-12-02/PutRecord)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_java_2_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package example;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.KinesisEvent;

public class Handler implements RequestHandler<KinesisEvent, Void> {
    @Override
    public Void handleRequest(final KinesisEvent event, final Context context) {
        LambdaLogger logger = context.getLogger();
        if (event.getRecords().isEmpty()) {
            logger.log("Empty Kinesis Event received");
            return null;
        }
        for (KinesisEvent.KinesisEventRecord record : event.getRecords()) {
            try {
                logger.log("Processed Event with EventId: "+record.getEventID());
                String data = new String(record.getKinesis().getData().array());
                logger.log("Data:"+ data);
                // TODO: Do interesting work based on the new data
            }
            catch (Exception ex) {
                logger.log("An error occurred:"+ex.getMessage());
                throw ex;
            }
        }
        logger.log("Successfully processed:"+event.getRecords().size()+" records");
        return null;
    }

}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_java_2_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.KinesisEvent;
import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ProcessKinesisRecords implements RequestHandler<KinesisEvent, StreamsEventResponse> {

    @Override
    public StreamsEventResponse handleRequest(KinesisEvent input, Context context) {

        List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>();
        String curRecordSequenceNumber = "";

        for (KinesisEvent.KinesisEventRecord kinesisEventRecord : input.getRecords()) {
            try {
                //Process your record
                KinesisEvent.Record kinesisRecord = kinesisEventRecord.getKinesis();
                curRecordSequenceNumber = kinesisRecord.getSequenceNumber();

            } catch (Exception e) {
                /* Since we are working with streams, we can return the failed item immediately.
                   Lambda will immediately begin to retry processing from this failed item onwards. */
                batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber));
                return new StreamsEventResponse(batchItemFailures);
            }
        }
       
       return new StreamsEventResponse(batchItemFailures);   
    }
}
```

# AWS KMS SDK for Java 2.x を使用した例
<a name="java_2_kms_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS KMSは
<a name="kms_Hello_java_2_topic"></a>

次のコード例は、 AWS Key Management Serviceの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.kms.KmsAsyncClient;
import software.amazon.awssdk.services.kms.model.ListKeysRequest;
import software.amazon.awssdk.services.kms.paginators.ListKeysPublisher;
import java.util.concurrent.CompletableFuture;

/**
 * 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 HelloKMS {
    public static void main(String[] args) {
        listAllKeys();
    }

    public static void listAllKeys() {
        KmsAsyncClient kmsAsyncClient = KmsAsyncClient.builder()
            .build();
        ListKeysRequest listKeysRequest = ListKeysRequest.builder()
            .limit(15)
            .build();

        /*
         * The `subscribe` method is required when using paginator methods in the AWS SDK
         * because paginator methods return an instance of a `ListKeysPublisher`, which is
         * based on a reactive stream. This allows asynchronous retrieval of paginated
         * results as they become available. By subscribing to the stream, we can process
         * each page of results as they are emitted.
         */
        ListKeysPublisher keysPublisher = kmsAsyncClient.listKeysPaginator(listKeysRequest);
        CompletableFuture<Void> future = keysPublisher
            .subscribe(r -> r.keys().forEach(key ->
                System.out.println("The key ARN is: " + key.keyArn() + ". The key Id is: " + key.keyId())))
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    System.err.println("Error occurred: " + exception.getMessage());
                } else {
                    System.out.println("Successfully listed all keys.");
                }
            });

        try {
            future.join();
        } catch (Exception e) {
            System.err.println("Failed to list keys: " + e.getMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListKeys](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListKeys)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="kms_Scenario_Basics_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ KMS キーを作成します。
+ アカウントの KMS キーを一覧表示し、詳細を取得します。
+ KMS キーを有効および無効にします。
+ クライアント側の暗号化に使用できる対称データキーを生成します。
+ データのデジタル署名に使用する非対称キーを生成します。
+ キーをダグ付けします。
+ KMS キーを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトでシナリオを実行します。  

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.kms.model.AlreadyExistsException;
import software.amazon.awssdk.services.kms.model.DisabledException;
import software.amazon.awssdk.services.kms.model.EnableKeyRotationResponse;
import software.amazon.awssdk.services.kms.model.KmsException;
import software.amazon.awssdk.services.kms.model.NotFoundException;
import software.amazon.awssdk.services.kms.model.RevokeGrantResponse;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

/**
 * 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 KMSScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static String accountId = "";

    private static final Logger logger = LoggerFactory.getLogger(KMSScenario.class);

    static KMSActions kmsActions = new KMSActions();

    static Scanner scanner = new Scanner(System.in);

    static String aliasName = "alias/dev-encryption-key";

    public static void main(String[] args) {
        final String usage = """
            Usage: <granteePrincipal>

            Where:
               granteePrincipal - The principal (user, service account, or group) to whom the grant or permission is being given. 
            """;

        if (args.length != 1) {
            logger.info(usage);
            return;
        }
        String granteePrincipal = args[0];
        String policyName = "default";

        accountId = kmsActions.getAccountId();
        String keyDesc = "Created by the AWS KMS API";

        logger.info(DASHES);
        logger.info("""
            Welcome to the AWS Key Management SDK Basics scenario.
                        
            This program demonstrates how to interact with AWS Key Management using the AWS SDK for Java (v2).
            The AWS Key Management Service (KMS) is a secure and highly available service that allows you to create 
            and manage AWS KMS keys and control their use across a wide range of AWS services and applications. 
            KMS provides a centralized and unified approach to managing encryption keys, making it easier to meet your 
            data protection and regulatory compliance requirements.
                        
            This Basics scenario creates two key types:
                        
            - A symmetric encryption key is used to encrypt and decrypt data.
            - An asymmetric key used to digitally sign data. 
                        
            Let's get started...
            """);
        waitForInputToContinue(scanner);

        try {
        // Run the methods that belong to this scenario.
        String targetKeyId = runScenario(granteePrincipal, keyDesc, policyName);
        requestDeleteResources(aliasName, targetKeyId);

        } catch (Throwable rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
        }
    }

    private static String runScenario(String granteePrincipal, String keyDesc, String policyName) throws Throwable {
        logger.info(DASHES);
        logger.info("1. Create a symmetric KMS key\n");
        logger.info("First, the program will creates a symmetric KMS key that you can used to encrypt and decrypt data.");
        waitForInputToContinue(scanner);
        String targetKeyId;
        try {
            CompletableFuture<String> futureKeyId = kmsActions.createKeyAsync(keyDesc);
            targetKeyId = futureKeyId.join();
            logger.info("A symmetric key was successfully created " + targetKeyId);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("""
            2. Enable a KMS key
                         
            By default, when the SDK creates an AWS key, it is enabled. The next bit of code checks to 
            determine if the key is enabled. 
             """);
        waitForInputToContinue(scanner);
        boolean isEnabled;
        try {
            CompletableFuture<Boolean> futureIsKeyEnabled = kmsActions.isKeyEnabledAsync(targetKeyId);
            isEnabled = futureIsKeyEnabled.join();
            logger.info("Is the key enabled? {}", isEnabled);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }

        if (!isEnabled)
            try {
                CompletableFuture<Void> future = kmsActions.enableKeyAsync(targetKeyId);
                future.join();

            } catch (RuntimeException rt) {
                Throwable cause = rt.getCause();
                if (cause instanceof KmsException kmsEx) {
                    logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
                } else {
                    logger.info("An unexpected error occurred: " + rt.getMessage());
                }
                throw cause;
            }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("3. Encrypt data using the symmetric KMS key");
        String plaintext = "Hello, AWS KMS!";
        logger.info("""
            One of the main uses of symmetric keys is to encrypt and decrypt data.
            Next, the code encrypts the string {} with the SYMMETRIC_DEFAULT encryption algorithm.
            """, plaintext);
        waitForInputToContinue(scanner);
        SdkBytes encryptedData;
        try {
            CompletableFuture<SdkBytes> future = kmsActions.encryptDataAsync(targetKeyId, plaintext);
            encryptedData = future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof DisabledException kmsDisabledEx) {
                logger.info("KMS error occurred due to a disabled key: Error message: {}, Error code {}", kmsDisabledEx.getMessage(), kmsDisabledEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("4. Create an alias");
        logger.info("""
             
            The alias name should be prefixed with 'alias/'.
            The default, 'alias/dev-encryption-key'.
             """);
        waitForInputToContinue(scanner);

        try {
            CompletableFuture<Void> future = kmsActions.createCustomAliasAsync(targetKeyId, aliasName);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof AlreadyExistsException kmsExistsEx) {
                if (kmsExistsEx.getMessage().contains("already exists")) {
                    logger.info("The alias '" + aliasName + "' already exists. Moving on...");
                }
            } else {
                logger.error("An unexpected error occurred: " + rt.getMessage(), rt);
                deleteKey(targetKeyId);
                throw cause;
            }
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("5. List all of your aliases");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Object> future = kmsActions.listAllAliasesAsync();
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("6. Enable automatic rotation of the KMS key");
        logger.info("""
                        
            By default, when the SDK enables automatic rotation of a KMS key,
            KMS rotates the key material of the KMS key one year (approximately 365 days) from the enable date and every year 
            thereafter. 
            """);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<EnableKeyRotationResponse> future = kmsActions.enableKeyRotationAsync(targetKeyId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("""
            7. Create a grant
                        
            A grant is a policy instrument that allows Amazon Web Services principals to use KMS keys.
            It also can allow them to view a KMS key (DescribeKey) and create and manage grants.
            When authorizing access to a KMS key, grants are considered along with key policies and IAM policies.
            """);

        waitForInputToContinue(scanner);
        String grantId = null;
        try {
            CompletableFuture<String> futureGrantId = kmsActions.grantKeyAsync(targetKeyId, granteePrincipal);
            grantId = futureGrantId.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("8. List grants for the KMS key");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Object> future = kmsActions.displayGrantIdsAsync(targetKeyId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("9. Revoke the grant");
        logger.info("""
            The revocation of a grant immediately removes the permissions and access that the grant had provided. 
            This means that any principal (user, role, or service) that was granted access to perform specific 
            KMS operations on a KMS key will no longer be able to perform those operations.
            """);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<RevokeGrantResponse> future = kmsActions.revokeKeyGrantAsync(targetKeyId, grantId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                if (kmsEx.getMessage().contains("Grant does not exist")) {
                    logger.info("The grant ID '" + grantId + "' does not exist. Moving on...");
                } else {
                    logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
                    throw cause;
                }
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
                deleteAliasName(aliasName);
                deleteKey(targetKeyId);
                throw cause;
            }
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("10. Decrypt the data\n");
        logger.info("""
            Lets decrypt the data that was encrypted in an early step.
            The code uses the same key to decrypt the string that we encrypted earlier in the program.
            """);
        waitForInputToContinue(scanner);
        String decryptedData = "";
        try {
            CompletableFuture<String> future = kmsActions.decryptDataAsync(encryptedData, targetKeyId);
            decryptedData = future.join();
            logger.info("Decrypted data: " + decryptedData);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        logger.info("Decrypted text is: " + decryptedData);
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("11. Replace a key policy\n");
        logger.info("""
            A key policy is a resource policy for a KMS key. Key policies are the primary way to control 
            access to KMS keys. Every KMS key must have exactly one key policy. The statements in the key policy 
            determine who has permission to use the KMS key and how they can use it. 
            You can also use IAM policies and grants to control access to the KMS key, but every KMS key 
            must have a key policy.
                        
            By default, when you create a key by using the SDK, a policy is created that 
            gives the AWS account that owns the KMS key full access to the KMS key.
                        
            Let's try to replace the automatically created policy with the following policy.
                    
                "Version":"2012-10-17",		 	 	 
                "Statement": [{
                "Effect": "Allow",
                "Principal": {"AWS": "arn:aws:iam::0000000000:root"},
                "Action": "kms:*",
                "Resource": "*"
                }] 
            """);

        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Boolean> future = kmsActions.replacePolicyAsync(targetKeyId, policyName, accountId);
            boolean success = future.join();
            if (success) {
                logger.info("Key policy replacement succeeded.");
            } else {
                logger.error("Key policy replacement failed.");
            }

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("12. Get the key policy\n");
        logger.info("The next bit of code that runs gets the key policy to make sure it exists.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<String> future = kmsActions.getKeyPolicyAsync(targetKeyId, policyName);
            String policy = future.join();
            if (!policy.isEmpty()) {
                logger.info("Retrieved policy: " + policy);
            }

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("13. Create an asymmetric KMS key and sign your data\n");
        logger.info("""
             Signing your data with an AWS key can provide several benefits that make it an attractive option 
             for your data signing needs. By using an AWS KMS key, you can leverage the 
             security controls and compliance features provided by AWS,
             which can help you meet various regulatory requirements and enhance the overall security posture 
             of your organization.
            """);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Boolean> future = kmsActions.signVerifyDataAsync();
            boolean success = future.join();
            if (success) {
                logger.info("Sign and verify data operation succeeded.");
            } else {
                logger.error("Sign and verify data operation failed.");
            }

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);

        logger.info(DASHES);
        logger.info("14. Tag your symmetric KMS Key\n");
        logger.info("""
            By using tags, you can improve the overall management, security, and governance of your 
            KMS keys, making it easier to organize, track, and control access to your encrypted data within 
            your AWS environment
            """);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = kmsActions.tagKMSKeyAsync(targetKeyId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            deleteAliasName(aliasName);
            deleteKey(targetKeyId);
            throw cause;
        }
        waitForInputToContinue(scanner);
        return targetKeyId;
    }

    // Deletes KMS resources with user input.
    private static void requestDeleteResources(String aliasName, String targetKeyId) {
        logger.info(DASHES);
        logger.info("15. Schedule the deletion of the KMS key\n");
        logger.info("""
            By default, KMS applies a waiting period of 30 days,
            but you can specify a waiting period of 7-30 days. When this operation is successful, 
            the key state of the KMS key changes to PendingDeletion and the key can't be used in any 
            cryptographic operations. It remains in this state for the duration of the waiting period.
                
            Deleting a KMS key is a destructive and potentially dangerous operation. When a KMS key is deleted, 
            all data that was encrypted under the KMS key is unrecoverable.
            """);
        logger.info("Would you like to delete the Key Management resources? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            logger.info("You selected to delete the AWS KMS resources.");
            waitForInputToContinue(scanner);
            try {
                CompletableFuture<Void> future = kmsActions.deleteSpecificAliasAsync(aliasName);
                future.join();

            } catch (RuntimeException rt) {
                Throwable cause = rt.getCause();
                if (cause instanceof KmsException kmsEx) {
                    logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
                } else {
                    logger.info("An unexpected error occurred: " + rt.getMessage());
                }
            }
            waitForInputToContinue(scanner);
            try {
                CompletableFuture<Void> future = kmsActions.disableKeyAsync(targetKeyId);
                future.join();

            } catch (RuntimeException rt) {
                Throwable cause = rt.getCause();
                if (cause instanceof KmsException kmsEx) {
                    logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
                } else {
                    logger.info("An unexpected error occurred: " + rt.getMessage());
                }
            }

            try {
                CompletableFuture<Void> future = kmsActions.deleteKeyAsync(targetKeyId);
                future.join();

            } catch (RuntimeException rt) {
                Throwable cause = rt.getCause();
                if (cause instanceof KmsException kmsEx) {
                    logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
                } else {
                    logger.info("An unexpected error occurred: " + rt.getMessage());
                }
            }

        } else {
            logger.info("The Key Management resources will not be deleted");
        }

        logger.info(DASHES);
        logger.info("This concludes the AWS Key Management SDK scenario");
        logger.info(DASHES);
    }

    // This method is invoked from Exceptions to clean up the resources.
    private static void deleteKey(String targetKeyId) {
        try {
            CompletableFuture<Void> future = kmsActions.disableKeyAsync(targetKeyId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
        }

        try {
            CompletableFuture<Void> future = kmsActions.deleteKeyAsync(targetKeyId);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
        }
    }

    // This method is invoked from Exceptions to clean up the resources.
    private static void deleteAliasName(String aliasName) {
        try {
            CompletableFuture<Void> future = kmsActions.deleteSpecificAliasAsync(aliasName);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof KmsException kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
        }
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
KMS アクションをラップするクラスを定義します。  

```
public class KMSActions {
    private static final Logger logger = LoggerFactory.getLogger(KMSActions.class);
    private static KmsAsyncClient kmsAsyncClient;

    /**
     * Retrieves an asynchronous AWS Key Management Service (KMS) client.
     * <p>
     * This method creates and returns a singleton instance of the KMS async client, with the following configurations:
     * <ul>
     *   <li>Max concurrency: 100</li>
     *   <li>Connection timeout: 60 seconds</li>
     *   <li>Read timeout: 60 seconds</li>
     *   <li>Write timeout: 60 seconds</li>
     *   <li>API call timeout: 2 minutes</li>
     *   <li>API call attempt timeout: 90 seconds</li>
     *   <li>Retry policy: up to 3 retries</li>
     *   <li>Credentials provider: environment variable credentials provider</li>
     * </ul>
     * <p>
     * If the client instance has already been created, it is returned instead of creating a new one.
     *
     * @return the KMS async client instance
     */
    private static KmsAsyncClient getAsyncClient() {
        if (kmsAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryPolicy(RetryPolicy.builder()
                    .numRetries(3)
                    .build())
                .build();

            kmsAsyncClient = KmsAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return kmsAsyncClient;
    }

    /**
     * Creates a new symmetric encryption key asynchronously.
     *
     * @param keyDesc the description of the key to be created
     * @return a {@link CompletableFuture} that completes with the ID of the newly created key
     * @throws RuntimeException if an error occurs while creating the key
     */
    public CompletableFuture<String> createKeyAsync(String keyDesc) {
        CreateKeyRequest keyRequest = CreateKeyRequest.builder()
            .description(keyDesc)
            .keySpec(KeySpec.SYMMETRIC_DEFAULT)
            .keyUsage(KeyUsageType.ENCRYPT_DECRYPT)
            .build();

        return getAsyncClient().createKey(keyRequest)
            .thenApply(resp -> resp.keyMetadata().keyId())
            .exceptionally(ex -> {
                throw new RuntimeException("An error occurred while creating the key: " + ex.getMessage(), ex);
            });
    }

    /**
     * Asynchronously checks if a specified key is enabled.
     *
     * @param keyId the ID of the key to check
     * @return a {@link CompletableFuture} that, when completed, indicates whether the key is enabled or not
     *
     * @throws RuntimeException if an exception occurs while checking the key state
     */
    public CompletableFuture<Boolean> isKeyEnabledAsync(String keyId) {
        DescribeKeyRequest keyRequest = DescribeKeyRequest.builder()
            .keyId(keyId)
            .build();

        CompletableFuture<DescribeKeyResponse> responseFuture = getAsyncClient().describeKey(keyRequest);
        return responseFuture.whenComplete((resp, ex) -> {
            if (resp != null) {
                KeyState keyState = resp.keyMetadata().keyState();
                if (keyState == KeyState.ENABLED) {
                    logger.info("The key is enabled.");
                } else {
                    logger.info("The key is not enabled. Key state: {}", keyState);
                }
            } else {
                throw new RuntimeException(ex);
            }
        }).thenApply(resp -> resp.keyMetadata().keyState() == KeyState.ENABLED);
    }

    /**
     * Asynchronously enables the specified key.
     *
     * @param keyId the ID of the key to enable
     * @return a {@link CompletableFuture} that completes when the key has been enabled
     */
    public CompletableFuture<Void> enableKeyAsync(String keyId) {
        EnableKeyRequest enableKeyRequest = EnableKeyRequest.builder()
            .keyId(keyId)
            .build();

        CompletableFuture<EnableKeyResponse> responseFuture = getAsyncClient().enableKey(enableKeyRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("Key with ID [{}] has been enabled.", keyId);
            } else {
                if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("KMS error occurred while enabling key: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred while enabling key: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture.thenApply(response -> null);
    }

    /**
     * Encrypts the given text asynchronously using the specified KMS client and key ID.
     *
     * @param keyId the ID of the KMS key to use for encryption
     * @param text the text to encrypt
     * @return a CompletableFuture that completes with the encrypted data as an SdkBytes object
     */
    public CompletableFuture<SdkBytes> encryptDataAsync(String keyId, String text) {
        SdkBytes myBytes = SdkBytes.fromUtf8String(text);
        EncryptRequest encryptRequest = EncryptRequest.builder()
            .keyId(keyId)
            .plaintext(myBytes)
            .build();

        CompletableFuture<EncryptResponse> responseFuture = getAsyncClient().encrypt(encryptRequest).toCompletableFuture();
        return responseFuture.whenComplete((response, ex) -> {
            if (response != null) {
                String algorithm = response.encryptionAlgorithm().toString();
                logger.info("The string was encrypted with algorithm {}.", algorithm);
            } else {
                throw new RuntimeException(ex);
            }
        }).thenApply(EncryptResponse::ciphertextBlob);
    }

    /**
     * Creates a custom alias for the specified target key asynchronously.
     *
     * @param targetKeyId the ID of the target key for the alias
     * @param aliasName   the name of the alias to create
     * @return a {@link CompletableFuture} that completes when the alias creation operation is finished
     */
    public CompletableFuture<Void> createCustomAliasAsync(String targetKeyId, String aliasName) {
        CreateAliasRequest aliasRequest = CreateAliasRequest.builder()
            .aliasName(aliasName)
            .targetKeyId(targetKeyId)
            .build();

        CompletableFuture<CreateAliasResponse> responseFuture = getAsyncClient().createAlias(aliasRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("{} was successfully created.", aliasName);
            } else {
                if (exception instanceof ResourceExistsException) {
                    logger.info("Alias [{}] already exists. Moving on...", aliasName);
                } else if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("KMS error occurred while creating alias: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred while creating alias: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture.thenApply(response -> null);
    }

    /**
     * Asynchronously lists all the aliases in the current AWS account.
     *
     * @return a {@link CompletableFuture} that completes when the list of aliases has been processed
     */
    public CompletableFuture<Object> listAllAliasesAsync() {
        ListAliasesRequest aliasesRequest = ListAliasesRequest.builder()
            .limit(15)
            .build();

        ListAliasesPublisher paginator = getAsyncClient().listAliasesPaginator(aliasesRequest);
        return paginator.subscribe(response -> {
                response.aliases().forEach(alias ->
                    logger.info("The alias name is: " + alias.aliasName())
                );
            })
            .thenApply(v -> null)
            .exceptionally(ex -> {
                if (ex.getCause() instanceof KmsException) {
                    KmsException e = (KmsException) ex.getCause();
                    throw new RuntimeException("A KMS exception occurred: " + e.getMessage());
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + ex.getMessage());
                }
            });
    }

    /**
     * Enables key rotation asynchronously for the specified key ID.
     *
     * @param keyId the ID of the key for which to enable key rotation
     * @return a CompletableFuture that represents the asynchronous operation of enabling key rotation
     * @throws RuntimeException if there was an error enabling key rotation, either due to a KMS exception or an unexpected error
     */
    public CompletableFuture<EnableKeyRotationResponse> enableKeyRotationAsync(String keyId) {
        EnableKeyRotationRequest enableKeyRotationRequest = EnableKeyRotationRequest.builder()
            .keyId(keyId)
            .build();

        CompletableFuture<EnableKeyRotationResponse> responseFuture = getAsyncClient().enableKeyRotation(enableKeyRotationRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("Key rotation has been enabled for key with id [{}]", keyId);
            } else {
                if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("Failed to enable key rotation: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture;
    }

    /**
     * Grants permissions to a specified principal on a customer master key (CMK) asynchronously.
     *
     * @param keyId             The unique identifier for the customer master key (CMK) that the grant applies to.
     * @param granteePrincipal  The principal that is given permission to perform the operations that the grant permits on the CMK.
     * @return A {@link CompletableFuture} that, when completed, contains the ID of the created grant.
     * @throws RuntimeException If an error occurs during the grant creation process.
     */
    public CompletableFuture<String> grantKeyAsync(String keyId, String granteePrincipal) {
        List<GrantOperation> grantPermissions = List.of(
            GrantOperation.ENCRYPT,
            GrantOperation.DECRYPT,
            GrantOperation.DESCRIBE_KEY
        );

        CreateGrantRequest grantRequest = CreateGrantRequest.builder()
            .keyId(keyId)
            .name("grant1")
            .granteePrincipal(granteePrincipal)
            .operations(grantPermissions)
            .build();

        CompletableFuture<CreateGrantResponse> responseFuture = getAsyncClient().createGrant(grantRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex == null) {
                logger.info("Grant created successfully with ID: " + response.grantId());
            } else {
                if (ex instanceof KmsException kmsEx) {
                    throw new RuntimeException("Failed to create grant: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + ex.getMessage(), ex);
                }
            }
        });

        return responseFuture.thenApply(CreateGrantResponse::grantId);
    }

    /**
     * Asynchronously displays the grant IDs for the specified key ID.
     *
     * @param keyId the ID of the AWS KMS key for which to list the grants
     * @return a {@link CompletableFuture} that, when completed, will be null if the operation succeeded, or will throw a {@link RuntimeException} if the operation failed
     * @throws RuntimeException if there was an error listing the grants, either due to an {@link KmsException} or an unexpected error
     */
    public CompletableFuture<Object> displayGrantIdsAsync(String keyId) {
        ListGrantsRequest grantsRequest = ListGrantsRequest.builder()
            .keyId(keyId)
            .limit(15)
            .build();

        ListGrantsPublisher paginator = getAsyncClient().listGrantsPaginator(grantsRequest);
        return paginator.subscribe(response -> {
                response.grants().forEach(grant -> {
                    logger.info("The grant Id is: " + grant.grantId());
                });
            })
            .thenApply(v -> null)
            .exceptionally(ex -> {
                Throwable cause = ex.getCause();
                if (cause instanceof KmsException) {
                    throw new RuntimeException("Failed to list grants: " + cause.getMessage(), cause);
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + cause.getMessage(), cause);
                }
            });
    }

    /**
     * Revokes a grant for the specified AWS KMS key asynchronously.
     *
     * @param keyId   The ID or key ARN of the AWS KMS key.
     * @param grantId The identifier of the grant to be revoked.
     * @return A {@link CompletableFuture} representing the asynchronous operation of revoking the grant.
     *         The {@link CompletableFuture} will complete with a {@link RevokeGrantResponse} object
     *         if the operation is successful, or with a {@code null} value if an error occurs.
     */
    public CompletableFuture<RevokeGrantResponse> revokeKeyGrantAsync(String keyId, String grantId) {
        RevokeGrantRequest grantRequest = RevokeGrantRequest.builder()
            .keyId(keyId)
            .grantId(grantId)
            .build();

        CompletableFuture<RevokeGrantResponse> responseFuture = getAsyncClient().revokeGrant(grantRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("Grant ID: [" + grantId + "] was successfully revoked!");
            } else {
                if (exception instanceof KmsException kmsEx) {
                    if (kmsEx.getMessage().contains("Grant does not exist")) {
                        logger.info("The grant ID '" + grantId + "' does not exist. Moving on...");
                    } else {
                        throw new RuntimeException("KMS error occurred: " + kmsEx.getMessage(), kmsEx);
                    }
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture;
    }


    /**
     * Asynchronously decrypts the given encrypted data using the specified key ID.
     *
     * @param encryptedData The encrypted data to be decrypted.
     * @param keyId The ID of the key to be used for decryption.
     * @return A CompletableFuture that, when completed, will contain the decrypted data as a String.
     *         If an error occurs during the decryption process, the CompletableFuture will complete
     *         exceptionally with the error, and the method will return an empty String.
     */
    public CompletableFuture<String> decryptDataAsync(SdkBytes encryptedData, String keyId) {
        DecryptRequest decryptRequest = DecryptRequest.builder()
            .ciphertextBlob(encryptedData)
            .keyId(keyId)
            .build();

        CompletableFuture<DecryptResponse> responseFuture = getAsyncClient().decrypt(decryptRequest);
        responseFuture.whenComplete((decryptResponse, exception) -> {
            if (exception == null) {
                logger.info("Data decrypted successfully for key ID: " + keyId);
            } else {
                if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("KMS error occurred while decrypting data: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred while decrypting data: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture.thenApply(decryptResponse -> decryptResponse.plaintext().asString(StandardCharsets.UTF_8));
    }

    /**
     * Asynchronously replaces the policy for the specified KMS key.
     *
     * @param keyId       the ID of the KMS key to replace the policy for
     * @param policyName  the name of the policy to be replaced
     * @param accountId   the AWS account ID to be used in the policy
     * @return a {@link CompletableFuture} that completes with a boolean indicating
     *         whether the policy replacement was successful or not
     */
    public CompletableFuture<Boolean> replacePolicyAsync(String keyId, String policyName, String accountId) {
        String policy = """
    {
      "Version":"2012-10-17",		 	 	 
      "Statement": [{
        "Effect": "Allow",
        "Principal": {"AWS": "arn:aws:iam::%s:root"},
        "Action": "kms:*",
        "Resource": "*"
      }]
    }
    """.formatted(accountId);

        PutKeyPolicyRequest keyPolicyRequest = PutKeyPolicyRequest.builder()
            .keyId(keyId)
            .policyName(policyName)
            .policy(policy)
            .build();

        // First, get the current policy to check if it exists
        return getAsyncClient().getKeyPolicy(r -> r.keyId(keyId).policyName(policyName))
            .thenCompose(response -> {
                logger.info("Current policy exists. Replacing it...");
                return getAsyncClient().putKeyPolicy(keyPolicyRequest);
            })
            .thenApply(putPolicyResponse -> {
                logger.info("The key policy has been replaced.");
                return true;
            })
            .exceptionally(throwable -> {
                if (throwable.getCause() instanceof LimitExceededException) {
                    logger.error("Cannot replace policy, as only one policy is allowed per key.");
                    return false;
                }
                throw new RuntimeException("Error replacing policy", throwable);
            });
    }


    /**
     * Asynchronously retrieves the key policy for the specified key ID and policy name.
     *
     * @param keyId       the ID of the AWS KMS key for which to retrieve the policy
     * @param policyName the name of the key policy to retrieve
     * @return a {@link CompletableFuture} that, when completed, contains the key policy as a {@link String}
     */
    public CompletableFuture<String> getKeyPolicyAsync(String keyId, String policyName) {
        GetKeyPolicyRequest policyRequest = GetKeyPolicyRequest.builder()
            .keyId(keyId)
            .policyName(policyName)
            .build();

        return getAsyncClient().getKeyPolicy(policyRequest)
            .thenApply(response -> {
                String policy = response.policy();
                logger.info("The response is: " + policy);
                return policy;
            })
            .exceptionally(ex -> {
                throw new RuntimeException("Failed to get key policy", ex);
            });
    }

    /**
     * Asynchronously signs and verifies data using AWS KMS.
     *
     * <p>The method performs the following steps:
     * <ol>
     *     <li>Creates an AWS KMS key with the specified key spec, key usage, and origin.</li>
     *     <li>Signs the provided message using the created KMS key and the RSASSA-PSS-SHA-256 algorithm.</li>
     *     <li>Verifies the signature of the message using the created KMS key and the RSASSA-PSS-SHA-256 algorithm.</li>
     * </ol>
     *
     * @return a {@link CompletableFuture} that completes with the result of the signature verification,
     *         {@code true} if the signature is valid, {@code false} otherwise.
     * @throws KmsException if any error occurs during the KMS operations.
     * @throws RuntimeException if an unexpected error occurs.
     */
    public CompletableFuture<Boolean> signVerifyDataAsync() {
        String signMessage = "Here is the message that will be digitally signed";

        // Create an AWS KMS key used to digitally sign data.
        CreateKeyRequest createKeyRequest = CreateKeyRequest.builder()
            .keySpec(KeySpec.RSA_2048)
            .keyUsage(KeyUsageType.SIGN_VERIFY)
            .origin(OriginType.AWS_KMS)
            .build();

        return getAsyncClient().createKey(createKeyRequest)
            .thenCompose(createKeyResponse -> {
                String keyId = createKeyResponse.keyMetadata().keyId();

                SdkBytes messageBytes = SdkBytes.fromString(signMessage, Charset.defaultCharset());
                SignRequest signRequest = SignRequest.builder()
                    .keyId(keyId)
                    .message(messageBytes)
                    .signingAlgorithm(SigningAlgorithmSpec.RSASSA_PSS_SHA_256)
                    .build();

                return getAsyncClient().sign(signRequest)
                    .thenCompose(signResponse -> {
                        byte[] signedBytes = signResponse.signature().asByteArray();

                        VerifyRequest verifyRequest = VerifyRequest.builder()
                            .keyId(keyId)
                            .message(SdkBytes.fromByteArray(signMessage.getBytes(Charset.defaultCharset())))
                            .signature(SdkBytes.fromByteBuffer(ByteBuffer.wrap(signedBytes)))
                            .signingAlgorithm(SigningAlgorithmSpec.RSASSA_PSS_SHA_256)
                            .build();

                        return getAsyncClient().verify(verifyRequest)
                            .thenApply(verifyResponse -> {
                                return (boolean) verifyResponse.signatureValid();
                            });
                    });
            })
            .exceptionally(throwable -> {
               throw new RuntimeException("Failed to sign or verify data", throwable);
            });
    }

    /**
     * Asynchronously tags a KMS key with a specific tag.
     *
     * @param keyId the ID of the KMS key to be tagged
     * @return a {@link CompletableFuture} that completes when the tagging operation is finished
     */
    public CompletableFuture<Void> tagKMSKeyAsync(String keyId) {
        Tag tag = Tag.builder()
            .tagKey("Environment")
            .tagValue("Production")
            .build();

        TagResourceRequest tagResourceRequest = TagResourceRequest.builder()
            .keyId(keyId)
            .tags(tag)
            .build();

        return getAsyncClient().tagResource(tagResourceRequest)
            .thenRun(() -> {
                logger.info("{} key was tagged", keyId);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to tag the KMS key", throwable);
            });
    }

    /**
     * Deletes a specific KMS alias asynchronously.
     *
     * @param aliasName the name of the alias to be deleted
     * @return a {@link CompletableFuture} representing the asynchronous operation of deleting the specified alias
     */
    public CompletableFuture<Void> deleteSpecificAliasAsync(String aliasName) {
        DeleteAliasRequest deleteAliasRequest = DeleteAliasRequest.builder()
            .aliasName(aliasName)
            .build();

        return getAsyncClient().deleteAlias(deleteAliasRequest)
            .thenRun(() -> {
                logger.info("Alias {} has been deleted successfully", aliasName);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to delete alias: " + aliasName, throwable);
            });
    }

    /**
     * Asynchronously disables the specified AWS Key Management Service (KMS) key.
     *
     * @param keyId the ID or Amazon Resource Name (ARN) of the KMS key to be disabled
     * @return a CompletableFuture that, when completed, indicates that the key has been disabled successfully
     */
    public CompletableFuture<Void> disableKeyAsync(String keyId) {
        DisableKeyRequest keyRequest = DisableKeyRequest.builder()
            .keyId(keyId)
            .build();

        return getAsyncClient().disableKey(keyRequest)
            .thenRun(() -> {
                logger.info("Key {} has been disabled successfully",keyId);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to disable key: " + keyId, throwable);
            });
    }

    /**
     * Deletes a KMS key asynchronously.
     *
     * <p><strong>Warning:</strong> Deleting a KMS key is a destructive and potentially dangerous operation.
     * When a KMS key is deleted, all data that was encrypted under the KMS key becomes unrecoverable.
     * This means that any files, databases, or other data that were encrypted using the deleted KMS key
     * will become permanently inaccessible. Exercise extreme caution when deleting KMS keys.</p>
     *
     * @param keyId the ID of the KMS key to delete
     * @return a {@link CompletableFuture} that completes when the key deletion is scheduled
     */
    public CompletableFuture<Void> deleteKeyAsync(String keyId) {
        ScheduleKeyDeletionRequest deletionRequest = ScheduleKeyDeletionRequest.builder()
            .keyId(keyId)
            .pendingWindowInDays(7)
            .build();

        return getAsyncClient().scheduleKeyDeletion(deletionRequest)
            .thenRun(() -> {
                logger.info("Key {} will be deleted in 7 days", keyId);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to schedule key deletion for key ID: " + keyId, throwable);
            });
    }


    public String getAccountId(){
        try (StsClient stsClient = StsClient.create()){
            GetCallerIdentityResponse callerIdentity = stsClient.getCallerIdentity();
            return callerIdentity.account();
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateAlias](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/CreateAlias)
  + [CreateGrant](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/CreateGrant)
  + [CreateKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/CreateKey)
  + [Decrypt](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Decrypt)
  + [DescribeKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/DescribeKey)
  + [DisableKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/DisableKey)
  + [EnableKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/EnableKey)
  + [暗号化](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Encrypt)
  + [GetKeyPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/GetKeyPolicy)
  + [ListAliases](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListAliases)
  + [ListGrants](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListGrants)
  + [ListKeys](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListKeys)
  + [RevokeGrant](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/RevokeGrant)
  + [ScheduleKeyDeletion](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ScheduleKeyDeletion)
  + [Sign](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Sign)
  + [TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/TagResource)

## アクション
<a name="actions"></a>

### `CreateAlias`
<a name="kms_CreateAlias_java_2_topic"></a>

次のコード例は、`CreateAlias` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a custom alias for the specified target key asynchronously.
     *
     * @param targetKeyId the ID of the target key for the alias
     * @param aliasName   the name of the alias to create
     * @return a {@link CompletableFuture} that completes when the alias creation operation is finished
     */
    public CompletableFuture<Void> createCustomAliasAsync(String targetKeyId, String aliasName) {
        CreateAliasRequest aliasRequest = CreateAliasRequest.builder()
            .aliasName(aliasName)
            .targetKeyId(targetKeyId)
            .build();

        CompletableFuture<CreateAliasResponse> responseFuture = getAsyncClient().createAlias(aliasRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("{} was successfully created.", aliasName);
            } else {
                if (exception instanceof ResourceExistsException) {
                    logger.info("Alias [{}] already exists. Moving on...", aliasName);
                } else if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("KMS error occurred while creating alias: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred while creating alias: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture.thenApply(response -> null);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の[CreateAlias](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/CreateAlias)を参照してください。

### `CreateGrant`
<a name="kms_CreateGrant_java_2_topic"></a>

次のコード例は、`CreateGrant` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Grants permissions to a specified principal on a customer master key (CMK) asynchronously.
     *
     * @param keyId             The unique identifier for the customer master key (CMK) that the grant applies to.
     * @param granteePrincipal  The principal that is given permission to perform the operations that the grant permits on the CMK.
     * @return A {@link CompletableFuture} that, when completed, contains the ID of the created grant.
     * @throws RuntimeException If an error occurs during the grant creation process.
     */
    public CompletableFuture<String> grantKeyAsync(String keyId, String granteePrincipal) {
        List<GrantOperation> grantPermissions = List.of(
            GrantOperation.ENCRYPT,
            GrantOperation.DECRYPT,
            GrantOperation.DESCRIBE_KEY
        );

        CreateGrantRequest grantRequest = CreateGrantRequest.builder()
            .keyId(keyId)
            .name("grant1")
            .granteePrincipal(granteePrincipal)
            .operations(grantPermissions)
            .build();

        CompletableFuture<CreateGrantResponse> responseFuture = getAsyncClient().createGrant(grantRequest);
        responseFuture.whenComplete((response, ex) -> {
            if (ex == null) {
                logger.info("Grant created successfully with ID: " + response.grantId());
            } else {
                if (ex instanceof KmsException kmsEx) {
                    throw new RuntimeException("Failed to create grant: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + ex.getMessage(), ex);
                }
            }
        });

        return responseFuture.thenApply(CreateGrantResponse::grantId);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の[CreateGrant](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/CreateGrant)を参照してください。

### `CreateKey`
<a name="kms_CreateKey_java_2_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new symmetric encryption key asynchronously.
     *
     * @param keyDesc the description of the key to be created
     * @return a {@link CompletableFuture} that completes with the ID of the newly created key
     * @throws RuntimeException if an error occurs while creating the key
     */
    public CompletableFuture<String> createKeyAsync(String keyDesc) {
        CreateKeyRequest keyRequest = CreateKeyRequest.builder()
            .description(keyDesc)
            .keySpec(KeySpec.SYMMETRIC_DEFAULT)
            .keyUsage(KeyUsageType.ENCRYPT_DECRYPT)
            .build();

        return getAsyncClient().createKey(keyRequest)
            .thenApply(resp -> resp.keyMetadata().keyId())
            .exceptionally(ex -> {
                throw new RuntimeException("An error occurred while creating the key: " + ex.getMessage(), ex);
            });
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[CreateKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/CreateKey)」を参照してください。

### `Decrypt`
<a name="kms_Decrypt_java_2_topic"></a>

次のコード例は、`Decrypt` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously decrypts the given encrypted data using the specified key ID.
     *
     * @param encryptedData The encrypted data to be decrypted.
     * @param keyId The ID of the key to be used for decryption.
     * @return A CompletableFuture that, when completed, will contain the decrypted data as a String.
     *         If an error occurs during the decryption process, the CompletableFuture will complete
     *         exceptionally with the error, and the method will return an empty String.
     */
    public CompletableFuture<String> decryptDataAsync(SdkBytes encryptedData, String keyId) {
        DecryptRequest decryptRequest = DecryptRequest.builder()
            .ciphertextBlob(encryptedData)
            .keyId(keyId)
            .build();

        CompletableFuture<DecryptResponse> responseFuture = getAsyncClient().decrypt(decryptRequest);
        responseFuture.whenComplete((decryptResponse, exception) -> {
            if (exception == null) {
                logger.info("Data decrypted successfully for key ID: " + keyId);
            } else {
                if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("KMS error occurred while decrypting data: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred while decrypting data: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture.thenApply(decryptResponse -> decryptResponse.plaintext().asString(StandardCharsets.UTF_8));
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[Decrypt](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Decrypt)」を参照してください。**

### `DeleteAlias`
<a name="kms_DeleteAlias_java_2_topic"></a>

次のコード例は、`DeleteAlias` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a specific KMS alias asynchronously.
     *
     * @param aliasName the name of the alias to be deleted
     * @return a {@link CompletableFuture} representing the asynchronous operation of deleting the specified alias
     */
    public CompletableFuture<Void> deleteSpecificAliasAsync(String aliasName) {
        DeleteAliasRequest deleteAliasRequest = DeleteAliasRequest.builder()
            .aliasName(aliasName)
            .build();

        return getAsyncClient().deleteAlias(deleteAliasRequest)
            .thenRun(() -> {
                logger.info("Alias {} has been deleted successfully", aliasName);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to delete alias: " + aliasName, throwable);
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteAlias](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/DeleteAlias)」を参照してください。

### `DescribeKey`
<a name="kms_DescribeKey_java_2_topic"></a>

次のコード例は、`DescribeKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously checks if a specified key is enabled.
     *
     * @param keyId the ID of the key to check
     * @return a {@link CompletableFuture} that, when completed, indicates whether the key is enabled or not
     *
     * @throws RuntimeException if an exception occurs while checking the key state
     */
    public CompletableFuture<Boolean> isKeyEnabledAsync(String keyId) {
        DescribeKeyRequest keyRequest = DescribeKeyRequest.builder()
            .keyId(keyId)
            .build();

        CompletableFuture<DescribeKeyResponse> responseFuture = getAsyncClient().describeKey(keyRequest);
        return responseFuture.whenComplete((resp, ex) -> {
            if (resp != null) {
                KeyState keyState = resp.keyMetadata().keyState();
                if (keyState == KeyState.ENABLED) {
                    logger.info("The key is enabled.");
                } else {
                    logger.info("The key is not enabled. Key state: {}", keyState);
                }
            } else {
                throw new RuntimeException(ex);
            }
        }).thenApply(resp -> resp.keyMetadata().keyState() == KeyState.ENABLED);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の [DescribeKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/DescribeKey)を参照してください。

### `DisableKey`
<a name="kms_DisableKey_java_2_topic"></a>

次のコード例は、`DisableKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously disables the specified AWS Key Management Service (KMS) key.
     *
     * @param keyId the ID or Amazon Resource Name (ARN) of the KMS key to be disabled
     * @return a CompletableFuture that, when completed, indicates that the key has been disabled successfully
     */
    public CompletableFuture<Void> disableKeyAsync(String keyId) {
        DisableKeyRequest keyRequest = DisableKeyRequest.builder()
            .keyId(keyId)
            .build();

        return getAsyncClient().disableKey(keyRequest)
            .thenRun(() -> {
                logger.info("Key {} has been disabled successfully",keyId);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to disable key: " + keyId, throwable);
            });
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DisableKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/DisableKey)」を参照してください。

### `EnableKey`
<a name="kms_EnableKey_java_2_topic"></a>

次のコード例は、`EnableKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously enables the specified key.
     *
     * @param keyId the ID of the key to enable
     * @return a {@link CompletableFuture} that completes when the key has been enabled
     */
    public CompletableFuture<Void> enableKeyAsync(String keyId) {
        EnableKeyRequest enableKeyRequest = EnableKeyRequest.builder()
            .keyId(keyId)
            .build();

        CompletableFuture<EnableKeyResponse> responseFuture = getAsyncClient().enableKey(enableKeyRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("Key with ID [{}] has been enabled.", keyId);
            } else {
                if (exception instanceof KmsException kmsEx) {
                    throw new RuntimeException("KMS error occurred while enabling key: " + kmsEx.getMessage(), kmsEx);
                } else {
                    throw new RuntimeException("An unexpected error occurred while enabling key: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture.thenApply(response -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[EnableKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/EnableKey)」を参照してください。

### `Encrypt`
<a name="kms_Encrypt_java_2_topic"></a>

次のコード例は、`Encrypt` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Encrypts the given text asynchronously using the specified KMS client and key ID.
     *
     * @param keyId the ID of the KMS key to use for encryption
     * @param text the text to encrypt
     * @return a CompletableFuture that completes with the encrypted data as an SdkBytes object
     */
    public CompletableFuture<SdkBytes> encryptDataAsync(String keyId, String text) {
        SdkBytes myBytes = SdkBytes.fromUtf8String(text);
        EncryptRequest encryptRequest = EncryptRequest.builder()
            .keyId(keyId)
            .plaintext(myBytes)
            .build();

        CompletableFuture<EncryptResponse> responseFuture = getAsyncClient().encrypt(encryptRequest).toCompletableFuture();
        return responseFuture.whenComplete((response, ex) -> {
            if (response != null) {
                String algorithm = response.encryptionAlgorithm().toString();
                logger.info("The string was encrypted with algorithm {}.", algorithm);
            } else {
                throw new RuntimeException(ex);
            }
        }).thenApply(EncryptResponse::ciphertextBlob);
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[Encrypt](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Encrypt)」を参照してください。**

### `ListAliases`
<a name="kms_ListAliases_java_2_topic"></a>

次のコード例は、`ListAliases` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously lists all the aliases in the current AWS account.
     *
     * @return a {@link CompletableFuture} that completes when the list of aliases has been processed
     */
    public CompletableFuture<Object> listAllAliasesAsync() {
        ListAliasesRequest aliasesRequest = ListAliasesRequest.builder()
            .limit(15)
            .build();

        ListAliasesPublisher paginator = getAsyncClient().listAliasesPaginator(aliasesRequest);
        return paginator.subscribe(response -> {
                response.aliases().forEach(alias ->
                    logger.info("The alias name is: " + alias.aliasName())
                );
            })
            .thenApply(v -> null)
            .exceptionally(ex -> {
                if (ex.getCause() instanceof KmsException) {
                    KmsException e = (KmsException) ex.getCause();
                    throw new RuntimeException("A KMS exception occurred: " + e.getMessage());
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + ex.getMessage());
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListAliases](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListAliases)」を参照してください。

### `ListGrants`
<a name="kms_ListGrants_java_2_topic"></a>

次のコード例は、`ListGrants` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously displays the grant IDs for the specified key ID.
     *
     * @param keyId the ID of the AWS KMS key for which to list the grants
     * @return a {@link CompletableFuture} that, when completed, will be null if the operation succeeded, or will throw a {@link RuntimeException} if the operation failed
     * @throws RuntimeException if there was an error listing the grants, either due to an {@link KmsException} or an unexpected error
     */
    public CompletableFuture<Object> displayGrantIdsAsync(String keyId) {
        ListGrantsRequest grantsRequest = ListGrantsRequest.builder()
            .keyId(keyId)
            .limit(15)
            .build();

        ListGrantsPublisher paginator = getAsyncClient().listGrantsPaginator(grantsRequest);
        return paginator.subscribe(response -> {
                response.grants().forEach(grant -> {
                    logger.info("The grant Id is: " + grant.grantId());
                });
            })
            .thenApply(v -> null)
            .exceptionally(ex -> {
                Throwable cause = ex.getCause();
                if (cause instanceof KmsException) {
                    throw new RuntimeException("Failed to list grants: " + cause.getMessage(), cause);
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + cause.getMessage(), cause);
                }
            });
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[ListGrants](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListGrants)」を参照してください。

### `ListKeyPolicies`
<a name="kms_ListKeyPolicies_java_2_topic"></a>

次のコード例は、`ListKeyPolicies` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously retrieves the key policy for the specified key ID and policy name.
     *
     * @param keyId       the ID of the AWS KMS key for which to retrieve the policy
     * @param policyName the name of the key policy to retrieve
     * @return a {@link CompletableFuture} that, when completed, contains the key policy as a {@link String}
     */
    public CompletableFuture<String> getKeyPolicyAsync(String keyId, String policyName) {
        GetKeyPolicyRequest policyRequest = GetKeyPolicyRequest.builder()
            .keyId(keyId)
            .policyName(policyName)
            .build();

        return getAsyncClient().getKeyPolicy(policyRequest)
            .thenApply(response -> {
                String policy = response.policy();
                logger.info("The response is: " + policy);
                return policy;
            })
            .exceptionally(ex -> {
                throw new RuntimeException("Failed to get key policy", ex);
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListKeyPolicies](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListKeyPolicies)」を参照してください。

### `ListKeys`
<a name="kms_ListKeys_java_2_topic"></a>

次のコード例は、`ListKeys` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.kms.KmsAsyncClient;
import software.amazon.awssdk.services.kms.model.ListKeysRequest;
import software.amazon.awssdk.services.kms.paginators.ListKeysPublisher;
import java.util.concurrent.CompletableFuture;

/**
 * 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 HelloKMS {
    public static void main(String[] args) {
        listAllKeys();
    }

    public static void listAllKeys() {
        KmsAsyncClient kmsAsyncClient = KmsAsyncClient.builder()
            .build();
        ListKeysRequest listKeysRequest = ListKeysRequest.builder()
            .limit(15)
            .build();

        /*
         * The `subscribe` method is required when using paginator methods in the AWS SDK
         * because paginator methods return an instance of a `ListKeysPublisher`, which is
         * based on a reactive stream. This allows asynchronous retrieval of paginated
         * results as they become available. By subscribing to the stream, we can process
         * each page of results as they are emitted.
         */
        ListKeysPublisher keysPublisher = kmsAsyncClient.listKeysPaginator(listKeysRequest);
        CompletableFuture<Void> future = keysPublisher
            .subscribe(r -> r.keys().forEach(key ->
                System.out.println("The key ARN is: " + key.keyArn() + ". The key Id is: " + key.keyId())))
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    System.err.println("Error occurred: " + exception.getMessage());
                } else {
                    System.out.println("Successfully listed all keys.");
                }
            });

        try {
            future.join();
        } catch (Exception e) {
            System.err.println("Failed to list keys: " + e.getMessage());
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListKeys](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ListKeys)」を参照してください。

### `RevokeGrant`
<a name="kms_RevokeGrant_java_2_topic"></a>

次のコード例は、`RevokeGrant` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Revokes a grant for the specified AWS KMS key asynchronously.
     *
     * @param keyId   The ID or key ARN of the AWS KMS key.
     * @param grantId The identifier of the grant to be revoked.
     * @return A {@link CompletableFuture} representing the asynchronous operation of revoking the grant.
     *         The {@link CompletableFuture} will complete with a {@link RevokeGrantResponse} object
     *         if the operation is successful, or with a {@code null} value if an error occurs.
     */
    public CompletableFuture<RevokeGrantResponse> revokeKeyGrantAsync(String keyId, String grantId) {
        RevokeGrantRequest grantRequest = RevokeGrantRequest.builder()
            .keyId(keyId)
            .grantId(grantId)
            .build();

        CompletableFuture<RevokeGrantResponse> responseFuture = getAsyncClient().revokeGrant(grantRequest);
        responseFuture.whenComplete((response, exception) -> {
            if (exception == null) {
                logger.info("Grant ID: [" + grantId + "] was successfully revoked!");
            } else {
                if (exception instanceof KmsException kmsEx) {
                    if (kmsEx.getMessage().contains("Grant does not exist")) {
                        logger.info("The grant ID '" + grantId + "' does not exist. Moving on...");
                    } else {
                        throw new RuntimeException("KMS error occurred: " + kmsEx.getMessage(), kmsEx);
                    }
                } else {
                    throw new RuntimeException("An unexpected error occurred: " + exception.getMessage(), exception);
                }
            }
        });

        return responseFuture;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[RevokeGrant](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/RevokeGrant)」を参照してください。

### `ScheduleKeyDeletion`
<a name="kms_ScheduleKeyDeletion_java_2_topic"></a>

次のコード例は、`ScheduleKeyDeletion` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a KMS key asynchronously.
     *
     * <p><strong>Warning:</strong> Deleting a KMS key is a destructive and potentially dangerous operation.
     * When a KMS key is deleted, all data that was encrypted under the KMS key becomes unrecoverable.
     * This means that any files, databases, or other data that were encrypted using the deleted KMS key
     * will become permanently inaccessible. Exercise extreme caution when deleting KMS keys.</p>
     *
     * @param keyId the ID of the KMS key to delete
     * @return a {@link CompletableFuture} that completes when the key deletion is scheduled
     */
    public CompletableFuture<Void> deleteKeyAsync(String keyId) {
        ScheduleKeyDeletionRequest deletionRequest = ScheduleKeyDeletionRequest.builder()
            .keyId(keyId)
            .pendingWindowInDays(7)
            .build();

        return getAsyncClient().scheduleKeyDeletion(deletionRequest)
            .thenRun(() -> {
                logger.info("Key {} will be deleted in 7 days", keyId);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to schedule key deletion for key ID: " + keyId, throwable);
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ScheduleKeyDeletion](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/ScheduleKeyDeletion)」を参照してください。

### `Sign`
<a name="kms_Sign_java_2_topic"></a>

次のコード例は、`Sign` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously signs and verifies data using AWS KMS.
     *
     * <p>The method performs the following steps:
     * <ol>
     *     <li>Creates an AWS KMS key with the specified key spec, key usage, and origin.</li>
     *     <li>Signs the provided message using the created KMS key and the RSASSA-PSS-SHA-256 algorithm.</li>
     *     <li>Verifies the signature of the message using the created KMS key and the RSASSA-PSS-SHA-256 algorithm.</li>
     * </ol>
     *
     * @return a {@link CompletableFuture} that completes with the result of the signature verification,
     *         {@code true} if the signature is valid, {@code false} otherwise.
     * @throws KmsException if any error occurs during the KMS operations.
     * @throws RuntimeException if an unexpected error occurs.
     */
    public CompletableFuture<Boolean> signVerifyDataAsync() {
        String signMessage = "Here is the message that will be digitally signed";

        // Create an AWS KMS key used to digitally sign data.
        CreateKeyRequest createKeyRequest = CreateKeyRequest.builder()
            .keySpec(KeySpec.RSA_2048)
            .keyUsage(KeyUsageType.SIGN_VERIFY)
            .origin(OriginType.AWS_KMS)
            .build();

        return getAsyncClient().createKey(createKeyRequest)
            .thenCompose(createKeyResponse -> {
                String keyId = createKeyResponse.keyMetadata().keyId();

                SdkBytes messageBytes = SdkBytes.fromString(signMessage, Charset.defaultCharset());
                SignRequest signRequest = SignRequest.builder()
                    .keyId(keyId)
                    .message(messageBytes)
                    .signingAlgorithm(SigningAlgorithmSpec.RSASSA_PSS_SHA_256)
                    .build();

                return getAsyncClient().sign(signRequest)
                    .thenCompose(signResponse -> {
                        byte[] signedBytes = signResponse.signature().asByteArray();

                        VerifyRequest verifyRequest = VerifyRequest.builder()
                            .keyId(keyId)
                            .message(SdkBytes.fromByteArray(signMessage.getBytes(Charset.defaultCharset())))
                            .signature(SdkBytes.fromByteBuffer(ByteBuffer.wrap(signedBytes)))
                            .signingAlgorithm(SigningAlgorithmSpec.RSASSA_PSS_SHA_256)
                            .build();

                        return getAsyncClient().verify(verifyRequest)
                            .thenApply(verifyResponse -> {
                                return (boolean) verifyResponse.signatureValid();
                            });
                    });
            })
            .exceptionally(throwable -> {
               throw new RuntimeException("Failed to sign or verify data", throwable);
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[Sign](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/Sign)」を参照してください。

### `TagResource`
<a name="kms_TagResource_java_2_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously tags a KMS key with a specific tag.
     *
     * @param keyId the ID of the KMS key to be tagged
     * @return a {@link CompletableFuture} that completes when the tagging operation is finished
     */
    public CompletableFuture<Void> tagKMSKeyAsync(String keyId) {
        Tag tag = Tag.builder()
            .tagKey("Environment")
            .tagValue("Production")
            .build();

        TagResourceRequest tagResourceRequest = TagResourceRequest.builder()
            .keyId(keyId)
            .tags(tag)
            .build();

        return getAsyncClient().tagResource(tagResourceRequest)
            .thenRun(() -> {
                logger.info("{} key was tagged", keyId);
            })
            .exceptionally(throwable -> {
                throw new RuntimeException("Failed to tag the KMS key", throwable);
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/kms-2014-11-01/TagResource)」を参照してください。

# SDK for Java 2.x を使用した Lambda の例
<a name="java_2_lambda_code_examples"></a>

次のコード例は、Lambda AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## はじめに
<a name="get_started"></a>

### Hello Lambda
<a name="lambda_Hello_java_2_topic"></a>

次のコード例は、Lambda の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists the AWS Lambda functions associated with the current AWS account.
     *
     * @param awsLambda an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     *
     * @throws LambdaException if an error occurs while interacting with the AWS Lambda service
     */
    public static void listFunctions(LambdaClient awsLambda) {
        try {
            ListFunctionsResponse functionResult = awsLambda.listFunctions();
            List<FunctionConfiguration> list = functionResult.functions();
            for (FunctionConfiguration config : list) {
                System.out.println("The function name is " + config.functionName());
            }

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/ListFunctions)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
/*
 *  Lambda function names appear as:
 *
 *  arn:aws:lambda:us-west-2:335556666777:function:HelloFunction
 *
 *  To find this value, look at the function in the AWS Management Console.
 *
 *  Before running this Java code example, set up your development environment, including your credentials.
 *
 *  For more information, see this documentation topic:
 *
 *  https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 *
 *  This example performs the following tasks:
 *
 * 1. Creates an AWS Lambda function.
 * 2. Gets a specific AWS Lambda function.
 * 3. Lists all Lambda functions.
 * 4. Invokes a Lambda function.
 * 5. Updates the Lambda function code and invokes it again.
 * 6. Updates a Lambda function's configuration value.
 * 7. Deletes a Lambda function.
 */

public class LambdaScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws InterruptedException {
        final String usage = """

            Usage:
                <functionName> <role> <handler> <bucketName> <key>\s

            Where:
                functionName - The name of the Lambda function.\s
                role - The AWS Identity and Access Management (IAM) service role that has Lambda permissions.\s
                handler - The fully qualified method name (for example, example.Handler::handleRequest).\s
                bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the .zip or .jar used to update the Lambda function's code.\s
                key - The Amazon S3 key name that represents the .zip or .jar (for example, LambdaHello-1.0-SNAPSHOT.jar).
                """;

        if (args.length != 5) {
              System.out.println(usage);
              return;
        }

        String functionName = args[0];
        String role = args[1];
        String handler = args[2];
        String bucketName = args[3];
        String key = args[4];
        LambdaClient awsLambda = LambdaClient.builder()
            .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS Lambda Basics scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Create an AWS Lambda function.");
        String funArn = createLambdaFunction(awsLambda, functionName, key, bucketName, role, handler);
        System.out.println("The AWS Lambda ARN is " + funArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Get the " + functionName + " AWS Lambda function.");
        getFunction(awsLambda, functionName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. List all AWS Lambda functions.");
        listFunctions(awsLambda);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Invoke the Lambda function.");
        System.out.println("*** Sleep for 1 min to get Lambda function ready.");
        Thread.sleep(60000);
        invokeFunction(awsLambda, functionName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Update the Lambda function code and invoke it again.");
        updateFunctionCode(awsLambda, functionName, bucketName, key);
        System.out.println("*** Sleep for 1 min to get Lambda function ready.");
        Thread.sleep(60000);
        invokeFunction(awsLambda, functionName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Update a Lambda function's configuration value.");
        updateFunctionConfiguration(awsLambda, functionName, handler);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Delete the AWS Lambda function.");
        LambdaScenario.deleteLambdaFunction(awsLambda, functionName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The AWS Lambda scenario completed successfully");
        System.out.println(DASHES);
        awsLambda.close();
    }

    /**
     * Creates a new Lambda function in AWS using the AWS Lambda Java API.
     *
     * @param awsLambda    the AWS Lambda client used to interact with the AWS Lambda service
     * @param functionName the name of the Lambda function to create
     * @param key          the S3 key of the function code
     * @param bucketName   the name of the S3 bucket containing the function code
     * @param role         the IAM role to assign to the Lambda function
     * @param handler      the fully qualified class name of the function handler
     * @return the Amazon Resource Name (ARN) of the created Lambda function
     */
    public static String createLambdaFunction(LambdaClient awsLambda,
                                              String functionName,
                                              String key,
                                              String bucketName,
                                              String role,
                                              String handler) {

        try {
            LambdaWaiter waiter = awsLambda.waiter();
            FunctionCode code = FunctionCode.builder()
                .s3Key(key)
                .s3Bucket(bucketName)
                .build();

            CreateFunctionRequest functionRequest = CreateFunctionRequest.builder()
                .functionName(functionName)
                .description("Created by the Lambda Java API")
                .code(code)
                .handler(handler)
                .runtime(Runtime.JAVA17)
                .role(role)
                .build();

            // Create a Lambda function using a waiter
            CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest);
            GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder()
                .functionName(functionName)
                .build();
            WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            return functionResponse.functionArn();

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }

    /**
     * Retrieves information about an AWS Lambda function.
     *
     * @param awsLambda    an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     * @param functionName the name of the AWS Lambda function to retrieve information about
     */
    public static void getFunction(LambdaClient awsLambda, String functionName) {
        try {
            GetFunctionRequest functionRequest = GetFunctionRequest.builder()
                .functionName(functionName)
                .build();

            GetFunctionResponse response = awsLambda.getFunction(functionRequest);
            System.out.println("The runtime of this Lambda function is " + response.configuration().runtime());

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Lists the AWS Lambda functions associated with the current AWS account.
     *
     * @param awsLambda an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     *
     * @throws LambdaException if an error occurs while interacting with the AWS Lambda service
     */
    public static void listFunctions(LambdaClient awsLambda) {
        try {
            ListFunctionsResponse functionResult = awsLambda.listFunctions();
            List<FunctionConfiguration> list = functionResult.functions();
            for (FunctionConfiguration config : list) {
                System.out.println("The function name is " + config.functionName());
            }

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Invokes a specific AWS Lambda function.
     *
     * @param awsLambda    an instance of {@link LambdaClient} to interact with the AWS Lambda service
     * @param functionName the name of the AWS Lambda function to be invoked
     */
    public static void invokeFunction(LambdaClient awsLambda, String functionName) {
        InvokeResponse res;
        try {
            // Need a SdkBytes instance for the payload.
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("inputValue", "2000");
            String json = jsonObj.toString();
            SdkBytes payload = SdkBytes.fromUtf8String(json);

            InvokeRequest request = InvokeRequest.builder()
                .functionName(functionName)
                .payload(payload)
                .build();

            res = awsLambda.invoke(request);
            String value = res.payload().asUtf8String();
            System.out.println(value);

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Updates the code for an AWS Lambda function.
     *
     * @param awsLambda  the AWS Lambda client
     * @param functionName the name of the Lambda function to update
     * @param bucketName the name of the S3 bucket where the function code is located
     * @param key the key (file name) of the function code in the S3 bucket
     * @throws LambdaException if there is an error updating the function code
     */
    public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) {
        try {
            LambdaWaiter waiter = awsLambda.waiter();
            UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder()
                .functionName(functionName)
                .publish(true)
                .s3Bucket(bucketName)
                .s3Key(key)
                .build();

            UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest);
            GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder()
                .functionName(functionName)
                .build();

            WaiterResponse<GetFunctionConfigurationResponse> waiterResponse = waiter
                .waitUntilFunctionUpdated(getFunctionConfigRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("The last modified value is " + response.lastModified());

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Updates the configuration of an AWS Lambda function.
     *
     * @param awsLambda     the {@link LambdaClient} instance to use for the AWS Lambda operation
     * @param functionName  the name of the AWS Lambda function to update
     * @param handler       the new handler for the AWS Lambda function
     *
     * @throws LambdaException if there is an error while updating the function configuration
     */
    public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) {
        try {
            UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder()
                .functionName(functionName)
                .handler(handler)
                .runtime(Runtime.JAVA17)
                .build();

            awsLambda.updateFunctionConfiguration(configurationRequest);

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Deletes an AWS Lambda function.
     *
     * @param awsLambda     an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     * @param functionName  the name of the Lambda function to be deleted
     *
     * @throws LambdaException if an error occurs while deleting the Lambda function
     */
    public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) {
        try {
            DeleteFunctionRequest request = DeleteFunctionRequest.builder()
                .functionName(functionName)
                .build();

            awsLambda.deleteFunction(request);
            System.out.println("The " + functionName + " function was deleted");

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/CreateFunction)
  + [DeleteFunction](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/DeleteFunction)
  + [GetFunction](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/GetFunction)
  + [Invoke](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/Invoke)
  + [ListFunctions](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/ListFunctions)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/UpdateFunctionCode)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/UpdateFunctionConfiguration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_java_2_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new Lambda function in AWS using the AWS Lambda Java API.
     *
     * @param awsLambda    the AWS Lambda client used to interact with the AWS Lambda service
     * @param functionName the name of the Lambda function to create
     * @param key          the S3 key of the function code
     * @param bucketName   the name of the S3 bucket containing the function code
     * @param role         the IAM role to assign to the Lambda function
     * @param handler      the fully qualified class name of the function handler
     * @return the Amazon Resource Name (ARN) of the created Lambda function
     */
    public static String createLambdaFunction(LambdaClient awsLambda,
                                              String functionName,
                                              String key,
                                              String bucketName,
                                              String role,
                                              String handler) {

        try {
            LambdaWaiter waiter = awsLambda.waiter();
            FunctionCode code = FunctionCode.builder()
                .s3Key(key)
                .s3Bucket(bucketName)
                .build();

            CreateFunctionRequest functionRequest = CreateFunctionRequest.builder()
                .functionName(functionName)
                .description("Created by the Lambda Java API")
                .code(code)
                .handler(handler)
                .runtime(Runtime.JAVA17)
                .role(role)
                .build();

            // Create a Lambda function using a waiter
            CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest);
            GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder()
                .functionName(functionName)
                .build();
            WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            return functionResponse.functionArn();

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CreateFunction](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/CreateFunction)」を参照してください。**

### `DeleteFunction`
<a name="lambda_DeleteFunction_java_2_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an AWS Lambda function.
     *
     * @param awsLambda     an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     * @param functionName  the name of the Lambda function to be deleted
     *
     * @throws LambdaException if an error occurs while deleting the Lambda function
     */
    public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) {
        try {
            DeleteFunctionRequest request = DeleteFunctionRequest.builder()
                .functionName(functionName)
                .build();

            awsLambda.deleteFunction(request);
            System.out.println("The " + functionName + " function was deleted");

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteFunction](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/DeleteFunction)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_java_2_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves information about an AWS Lambda function.
     *
     * @param awsLambda    an instance of the {@link LambdaClient} class, which is used to interact with the AWS Lambda service
     * @param functionName the name of the AWS Lambda function to retrieve information about
     */
    public static void getFunction(LambdaClient awsLambda, String functionName) {
        try {
            GetFunctionRequest functionRequest = GetFunctionRequest.builder()
                .functionName(functionName)
                .build();

            GetFunctionResponse response = awsLambda.getFunction(functionRequest);
            System.out.println("The runtime of this Lambda function is " + response.configuration().runtime());

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetFunction](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/GetFunction)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_java_2_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Invokes a specific AWS Lambda function.
     *
     * @param awsLambda    an instance of {@link LambdaClient} to interact with the AWS Lambda service
     * @param functionName the name of the AWS Lambda function to be invoked
     */
    public static void invokeFunction(LambdaClient awsLambda, String functionName) {
        InvokeResponse res;
        try {
            // Need a SdkBytes instance for the payload.
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("inputValue", "2000");
            String json = jsonObj.toString();
            SdkBytes payload = SdkBytes.fromUtf8String(json);

            InvokeRequest request = InvokeRequest.builder()
                .functionName(functionName)
                .payload(payload)
                .build();

            res = awsLambda.invoke(request);
            String value = res.payload().asUtf8String();
            System.out.println(value);

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[Invoke](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/Invoke)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_java_2_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the code for an AWS Lambda function.
     *
     * @param awsLambda  the AWS Lambda client
     * @param functionName the name of the Lambda function to update
     * @param bucketName the name of the S3 bucket where the function code is located
     * @param key the key (file name) of the function code in the S3 bucket
     * @throws LambdaException if there is an error updating the function code
     */
    public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) {
        try {
            LambdaWaiter waiter = awsLambda.waiter();
            UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder()
                .functionName(functionName)
                .publish(true)
                .s3Bucket(bucketName)
                .s3Key(key)
                .build();

            UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest);
            GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder()
                .functionName(functionName)
                .build();

            WaiterResponse<GetFunctionConfigurationResponse> waiterResponse = waiter
                .waitUntilFunctionUpdated(getFunctionConfigRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("The last modified value is " + response.lastModified());

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/UpdateFunctionCode)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_java_2_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the configuration of an AWS Lambda function.
     *
     * @param awsLambda     the {@link LambdaClient} instance to use for the AWS Lambda operation
     * @param functionName  the name of the AWS Lambda function to update
     * @param handler       the new handler for the AWS Lambda function
     *
     * @throws LambdaException if there is an error while updating the function configuration
     */
    public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) {
        try {
            UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder()
                .functionName(functionName)
                .handler(handler)
                .runtime(Runtime.JAVA17)
                .build();

            awsLambda.updateFunctionConfiguration(configurationRequest);

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/lambda-2015-03-31/UpdateFunctionConfiguration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_java_2_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Java 2.x**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_java_2_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Java 2.x**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_fsa_app) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_java_2_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 Lambda Java ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_apigateway) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### Step Functions を使用して Lambda 関数を呼び出す
<a name="cross_ServerlessWorkflows_java_2_topic"></a>

次のコード例は、 AWS Lambda 関数を順番に呼び出す AWS Step Functions ステートマシンを作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Step Functions と を使用して AWS サーバーレスワークフローを作成する方法を示します AWS SDK for Java 2.x。各ワークフローステップは、 AWS Lambda 関数を使用して実装されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_workflows_stepfunctions) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SES
+ ステップ関数

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_java_2_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda Java ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_scheduled_events) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

### Neptune API を使用してグラフデータをクエリする
<a name="cross_Neptune_Query_java_2_topic"></a>

次のコード例は、Neptune API を使用してグラフデータをクエリする方法を示しています。

**SDK for Java 2.x**  
 Amazon Neptune Java API を使用して、VPC 内のグラフデータをクエリする Lambda 関数を作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_neptune_lambda) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Lambda
+ Neptune

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_java_2_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rdsdata.RdsDataClient;
import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementRequest;
import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementResponse;
import software.amazon.awssdk.services.rdsdata.model.Field;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class RdsLambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();

        try {
            // Obtain auth token
            String token = createAuthToken();

            // Define connection configuration
            String connectionString = String.format("jdbc:mysql://%s:%s/%s?useSSL=true&requireSSL=true",
                    System.getenv("ProxyHostName"),
                    System.getenv("Port"),
                    System.getenv("DBName"));

            // Establish a connection to the database
            try (Connection connection = DriverManager.getConnection(connectionString, System.getenv("DBUserName"), token);
                 PreparedStatement statement = connection.prepareStatement("SELECT ? + ? AS sum")) {

                statement.setInt(1, 3);
                statement.setInt(2, 2);

                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        int sum = resultSet.getInt("sum");
                        response.setStatusCode(200);
                        response.setBody("The selected sum is: " + sum);
                    }
                }
            }

        } catch (Exception e) {
            response.setStatusCode(500);
            response.setBody("Error: " + e.getMessage());
        }

        return response;
    }

    private String createAuthToken() {
        // Create RDS Data Service client
        RdsDataClient rdsDataClient = RdsDataClient.builder()
                .region(Region.of(System.getenv("AWS_REGION")))
                .credentialsProvider(DefaultCredentialsProvider.create())
                .build();

        // Define authentication request
        ExecuteStatementRequest request = ExecuteStatementRequest.builder()
                .resourceArn(System.getenv("ProxyHostName"))
                .secretArn(System.getenv("DBUserName"))
                .database(System.getenv("DBName"))
                .sql("SELECT 'RDS IAM Authentication'")
                .build();

        // Execute request and obtain authentication token
        ExecuteStatementResponse response = rdsDataClient.executeStatement(request);
        Field tokenField = response.records().get(0).get(0);

        return tokenField.stringValue();
    }
}
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_java_2_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package example;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.KinesisEvent;

public class Handler implements RequestHandler<KinesisEvent, Void> {
    @Override
    public Void handleRequest(final KinesisEvent event, final Context context) {
        LambdaLogger logger = context.getLogger();
        if (event.getRecords().isEmpty()) {
            logger.log("Empty Kinesis Event received");
            return null;
        }
        for (KinesisEvent.KinesisEventRecord record : event.getRecords()) {
            try {
                logger.log("Processed Event with EventId: "+record.getEventID());
                String data = new String(record.getKinesis().getData().array());
                logger.log("Data:"+ data);
                // TODO: Do interesting work based on the new data
            }
            catch (Exception ex) {
                logger.log("An error occurred:"+ex.getMessage());
                throw ex;
            }
        }
        logger.log("Successfully processed:"+event.getRecords().size()+" records");
        return null;
    }

}
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_java_2_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での DynamoDB イベントの消費。  

```
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class example implements RequestHandler<DynamodbEvent, Void> {

    private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();

    @Override
    public Void handleRequest(DynamodbEvent event, Context context) {
        System.out.println(GSON.toJson(event));
        event.getRecords().forEach(this::logDynamoDBRecord);
        return null;
    }

    private void logDynamoDBRecord(DynamodbStreamRecord record) {
        System.out.println(record.getEventID());
        System.out.println(record.getEventName());
        System.out.println("DynamoDB Record: " + GSON.toJson(record.getDynamodb()));
    }
}
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_java_2_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Amazon DocumentDB イベントの消費。  

```
import java.util.List;
import java.util.Map;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

public class Example implements RequestHandler<Map<String, Object>, String> {

    @SuppressWarnings("unchecked")
    @Override
    public String handleRequest(Map<String, Object> event, Context context) {
        List<Map<String, Object>> events = (List<Map<String, Object>>) event.get("events");
        for (Map<String, Object> record : events) {
            Map<String, Object> eventData = (Map<String, Object>) record.get("event");
            processEventData(eventData);
        }

        return "OK";
    }

    @SuppressWarnings("unchecked")
    private void processEventData(Map<String, Object> eventData) {
        String operationType = (String) eventData.get("operationType");
        System.out.println("operationType: %s".formatted(operationType));

        Map<String, Object> ns = (Map<String, Object>) eventData.get("ns");

        String db = (String) ns.get("db");
        System.out.println("db: %s".formatted(db));
        String coll = (String) ns.get("coll");
        System.out.println("coll: %s".formatted(coll));

        Map<String, Object> fullDocument = (Map<String, Object>) eventData.get("fullDocument");
        System.out.println("fullDocument: %s".formatted(fullDocument));
    }

}
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_java_2_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Amazon MSK イベントの消費。  

```
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.KafkaEvent;
import com.amazonaws.services.lambda.runtime.events.KafkaEvent.KafkaEventRecord;

import java.util.Base64;
import java.util.Map;

public class Example implements RequestHandler<KafkaEvent, Void> {

    @Override
    public Void handleRequest(KafkaEvent event, Context context) {
        for (Map.Entry<String, java.util.List<KafkaEventRecord>> entry : event.getRecords().entrySet()) {
            String key = entry.getKey();
            System.out.println("Key: " + key);

            for (KafkaEventRecord record : entry.getValue()) {
                System.out.println("Record: " + record);

                byte[] value = Base64.getDecoder().decode(record.getValue());
                String message = new String(value);
                System.out.println("Message: " + message);
            }
        }

        return null;
    }
}
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_java_2_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Java を使用した Lambda での S3 イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package example;

import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.S3Client;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Handler implements RequestHandler<S3Event, String> {
    private static final Logger logger = LoggerFactory.getLogger(Handler.class);
    @Override
    public String handleRequest(S3Event s3event, Context context) {
        try {
          S3EventNotificationRecord record = s3event.getRecords().get(0);
          String srcBucket = record.getS3().getBucket().getName();
          String srcKey = record.getS3().getObject().getUrlDecodedKey();

          S3Client s3Client = S3Client.builder().build();
          HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey);

          logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType());

          return "Ok";
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
    }

    private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) {
        HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
                .bucket(bucket)
                .key(key)
                .build();
        return s3Client.headObject(headObjectRequest);
    }
}
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_java_2_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package example;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SNSEvent;
import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord;


import java.util.Iterator;
import java.util.List;

public class SNSEventHandler implements RequestHandler<SNSEvent, Boolean> {
    LambdaLogger logger;

    @Override
    public Boolean handleRequest(SNSEvent event, Context context) {
        logger = context.getLogger();
        List<SNSRecord> records = event.getRecords();
        if (!records.isEmpty()) {
            Iterator<SNSRecord> recordsIter = records.iterator();
            while (recordsIter.hasNext()) {
                processRecord(recordsIter.next());
            }
        }
        return Boolean.TRUE;
    }

    public void processRecord(SNSRecord record) {
        try {
            String message = record.getSNS().getMessage();
            logger.log("message: " + message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_java_2_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;

public class Function implements RequestHandler<SQSEvent, Void> {
    @Override
    public Void handleRequest(SQSEvent sqsEvent, Context context) {
        for (SQSMessage msg : sqsEvent.getRecords()) {
            processMessage(msg, context);
        }
        context.getLogger().log("done");
        return null;
    }

    private void processMessage(SQSMessage msg, Context context) {
        try {
            context.getLogger().log("Processed message " + msg.getBody());

            // TODO: Do interesting work based on the new message

        } catch (Exception e) {
            context.getLogger().log("An error occurred");
            throw e;
        }

    }
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_java_2_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.KinesisEvent;
import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ProcessKinesisRecords implements RequestHandler<KinesisEvent, StreamsEventResponse> {

    @Override
    public StreamsEventResponse handleRequest(KinesisEvent input, Context context) {

        List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>();
        String curRecordSequenceNumber = "";

        for (KinesisEvent.KinesisEventRecord kinesisEventRecord : input.getRecords()) {
            try {
                //Process your record
                KinesisEvent.Record kinesisRecord = kinesisEventRecord.getKinesis();
                curRecordSequenceNumber = kinesisRecord.getSequenceNumber();

            } catch (Exception e) {
                /* Since we are working with streams, we can return the failed item immediately.
                   Lambda will immediately begin to retry processing from this failed item onwards. */
                batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber));
                return new StreamsEventResponse(batchItemFailures);
            }
        }
       
       return new StreamsEventResponse(batchItemFailures);   
    }
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_java_2_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での DynamoDB のバッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse;
import com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord;

import java.util.ArrayList;
import java.util.List;

public class ProcessDynamodbRecords implements RequestHandler<DynamodbEvent, StreamsEventResponse> {

    @Override
    public StreamsEventResponse handleRequest(DynamodbEvent input, Context context) {

        List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>();
        String curRecordSequenceNumber = "";

        for (DynamodbEvent.DynamodbStreamRecord dynamodbStreamRecord : input.getRecords()) {
          try {
                //Process your record
                StreamRecord dynamodbRecord = dynamodbStreamRecord.getDynamodb();
                curRecordSequenceNumber = dynamodbRecord.getSequenceNumber();
                
            } catch (Exception e) {
                /* Since we are working with streams, we can return the failed item immediately.
                   Lambda will immediately begin to retry processing from this failed item onwards. */
                batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber));
                return new StreamsEventResponse(batchItemFailures);
            }
        }
       
       return new StreamsEventResponse();   
    }
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_java_2_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse;
 
import java.util.ArrayList;
import java.util.List;
 
public class ProcessSQSMessageBatch implements RequestHandler<SQSEvent, SQSBatchResponse> {
    @Override
    public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) {
         List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new ArrayList<SQSBatchResponse.BatchItemFailure>();

         for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) {
             try {
                 //process your message
             } catch (Exception e) {
                 //Add failed message identifier to the batchItemFailures list
                 batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(message.getMessageId()));
             }
         }
         return new SQSBatchResponse(batchItemFailures);
     }
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_java_2_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Java 2.x**  
 Java SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-java-frameworks-samples) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Java 2.x を使用する Amazon Lex の例
<a name="java_2_lex_code_examples"></a>

次のコード例は、Amazon Lex AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Lex チャットボットを構築する
<a name="cross_LexChatbotLanguages_java_2_topic"></a>

次のコード例は、ウェブサイトの訪問者を引き付けるチャットボットの作成方法を示しています。

**SDK for Java 2.x**  
 Amazon Lex API を使用して、ウェブアプリケーション内にチャットボットを作成し、Web サイトの訪問者と交流する方法を説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lex_chatbot) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon Lex
+ Amazon Translate

# SDK for Java 2.x を使用する Amazon Location の例
<a name="java_2_location_code_examples"></a>

次のコード例は、Amazon Location AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Location
<a name="location_Hello_java_2_topic"></a>

次のコード例は、Amazon Location Service の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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
 *
 * In addition, you need to create a collection using the AWS Management
 * console. For information, see the following documentation.
 *
 * https://docs.aws.amazon.com/location/latest/developerguide/geofence-gs.html

 */
public class HelloLocation {

    private static LocationAsyncClient locationAsyncClient;
    private static final Logger logger = LoggerFactory.getLogger(HelloLocation.class);

    // This Singleton pattern ensures that only one `LocationClient`
    // instance.
    private static LocationAsyncClient getClient() {
        if (locationAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            locationAsyncClient = LocationAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return locationAsyncClient;
    }

    public static void main(String[] args) {
        final String usage = """

            Usage:
                <collectionName>

            Where:
                collectionName - The Amazon location collection name.
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionName = args[0];
        listGeofences(collectionName);
    }

    /**
     * Lists geofences from a specified geofence collection asynchronously.
     *
     * @param collectionName The name of the geofence collection to list geofences from.
     * @return A {@link CompletableFuture} representing the result of the asynchronous operation.
     *         The future completes when all geofences have been processed and logged.
     */
    public static CompletableFuture<Void> listGeofences(String collectionName) {
        ListGeofencesRequest geofencesRequest = ListGeofencesRequest.builder()
                .collectionName(collectionName)
                .build();

        ListGeofencesPublisher paginator = getClient().listGeofencesPaginator(geofencesRequest);
        CompletableFuture<Void> future = paginator.subscribe(response -> {
            if (response.entries().isEmpty()) {
                logger.info("No Geofences were found in the collection.");
            } else {
                response.entries().forEach(geofence ->
                        logger.info("Geofence ID: " + geofence.geofenceId())
                );
            }
        });
        return future;
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [ListGeofenceCollections](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/ListGeofenceCollections)
  + [ListGeofences](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/ListGeofences)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="location_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Location マップを作成します。
+ Amazon Location API キーを作成します。
+ マップ URL を表示します。
+ ジオフェンスコレクションを作成します。
+ ジオフェンスジオメトリを保存します。
+ トラッカーリソースを作成します。
+ デバイスの位置を更新します。
+ 指定されたデバイスの最新の位置更新を取得します。
+ ルート計算ツールを作成します。
+ シアトルとバンクーバー間の距離を決定します。
+ Amazon Location の上位レベルの API を使用します。
+ Amazon Location アセットを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。
Amazon Location Service 機能を示すインタラクティブなシナリオを実行します。  

```
/*
 * 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 LocationScenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    private static final Logger logger = LoggerFactory.getLogger(LocationScenario.class);
    static Scanner scanner = new Scanner(System.in);

    static LocationActions locationActions = new LocationActions();

    public static void main(String[] args) {
        final String usage = """

            Usage:    <mapName> <keyName> <collectionName> <geoId> <trackerName> <calculatorName> <deviceId>

            Where:
              mapName - The name of the map to be create (e.g., "AWSMap").
              keyName - The name of the API key to create (e.g., "AWSApiKey").
              collectionName - The name of the geofence collection (e.g., "AWSLocationCollection").
              geoId - The geographic identifier used for the geofence or map (e.g., "geoId").
              trackerName - The name of the tracker (e.g., "geoTracker").
              calculatorName - The name of the route calculator (e.g., "AWSRouteCalc").
              deviceId - The ID of the device (e.g., "iPhone-112356").
            """;

        if (args.length != 7) {
            logger.info(usage);
            return;
        }

        String mapName = args[0];
        String keyName = args[1];
        String collectionName = args[2];
        String geoId = args[3];
        String trackerName = args[4];
        String calculatorName = args[5];
        String deviceId = args[6];

        logger.info("""
            AWS Location Service is a fully managed service offered by Amazon Web Services (AWS) that
            provides location-based services for developers. This service simplifies
            the integration of location-based features into applications, making it
            easier to build and deploy location-aware applications.
                        
            The AWS Location Service offers a range of location-based services,
            including:
                        
            Maps: The service provides access to high-quality maps, satellite imagery,\s
            and geospatial data from various providers, allowing developers to\s
            easily embed maps into their applications.
                        
            Tracking: The Location Service enables real-time tracking of mobile devices,\s
            assets, or other entities, allowing developers to build applications\s
            that can monitor the location of people, vehicles, or other objects.
                        
            Geocoding: The service provides the ability to convert addresses or\s
            location names into geographic coordinates (latitude and longitude),\s
            and vice versa, enabling developers to integrate location-based search\s
            and routing functionality into their applications.
            """);
        waitForInputToContinue(scanner);
        try {
            runScenario(mapName, keyName, collectionName, geoId, trackerName, calculatorName, deviceId);
        } catch (RuntimeException e) {
            // Clean up AWS Resources.
            cleanUp(mapName, keyName, collectionName, trackerName, calculatorName);
            logger.info(e.getMessage());
        }
    }

    public static void runScenario(String mapName, String keyName, String collectionName, String geoId, String trackerName, String calculatorName, String deviceId) {
        logger.info(DASHES);
        logger.info("1. Create a map");
        logger.info("""
             An AWS Location map can enhance the user experience of your
             application by providing accurate and personalized location-based
             features. For example, you could use the geocoding capabilities to
             allow users to search for and locate businesses, landmarks, or
             other points of interest within a specific region.
            """);

        waitForInputToContinue(scanner);
        String mapArn;
        try {
            mapArn = locationActions.createMap(mapName).join();
            logger.info("The Map ARN is: {}", mapArn);  // Log success in calling code
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ServiceQuotaExceededException) {
                logger.error("The request exceeded the maximum quota: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred while creating the map.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. Create an AWS Location API key");
        logger.info("""
            When you embed a map in a web app or website, the API key is
            included in the map tile URL to authenticate requests. You can
            restrict API keys to specific AWS Location operations (e.g., only
            maps, not geocoding). API keys can expire, ensuring temporary
            access control.
            """);

        try {
            String keyArn = locationActions.createKey(keyName, mapArn).join();
            logger.info("The API key was successfully created: {}", keyArn);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof AccessDeniedException) {
                logger.error("Request was denied: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred while creating the API key.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("3. Display Map URL");
        logger.info("""
            In order to get the MAP URL, you need to get the API Key value.
            You can get the key value using the AWS Management Console under
            Location Services. This operation cannot be completed using the
            AWS SDK. For more information about getting the key value, see 
            the AWS Location Documentation.
            """);
        String mapUrl = "https://maps.geo.aws.amazon.com/maps/v0/maps/"+mapName+"/tiles/{z}/{x}/{y}?key={KeyValue}";
        logger.info("Embed this URL in your Web app: " + mapUrl);
        logger.info("");
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. Create a geofence collection, which manages and stores geofences.");
        waitForInputToContinue(scanner);
        try {
            String collectionArn = locationActions.createGeofenceCollection(collectionName).join();
            logger.info("The geofence collection was successfully created: {}", collectionArn);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ConflictException) {
                logger.error("A conflict occurred: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred while creating the geofence collection.", cause);
            }
            return;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5. Store a geofence geometry in a given geofence collection.");
        logger.info("""
            An AWS Location geofence is a virtual boundary that defines a geographic area
            on a map. It is a useful feature for tracking the location of
            assets or monitoring the movement of objects within a specific region.
                        
            To define a geofence, you need to specify the coordinates of a
            polygon that represents the area of interest. The polygon must be
            defined in a counter-clockwise direction, meaning that the points of
            the polygon must be listed in a counter-clockwise order.
                        
            This is a requirement for the AWS Location service to correctly
            interpret the geofence and ensure that the location data is
            accurately processed within the defined area.
            """);

        waitForInputToContinue(scanner);
        try {
            locationActions.putGeofence(collectionName, geoId).join();
            logger.info("Successfully created geofence: {}", geoId);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ValidationException) {
                logger.error("A validation error occurred while creating geofence: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("6. Create a tracker resource which lets you retrieve current and historical location of devices..");
        waitForInputToContinue(scanner);
        try {
            String trackerArn = locationActions.createTracker(trackerName).join();
            logger.info("Successfully created tracker. ARN: {}", trackerArn);  // Log success
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ConflictException) {
                logger.error("A conflict occurred while creating the tracker: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Update the position of a device in the location tracking system.");
        logger.info("""
            The AWS location service does not enforce a strict format for deviceId, but it must:
              - Be a string (case-sensitive).
              - Be 1–100 characters long.
              - Contain only:
                - Alphanumeric characters (A-Z, a-z, 0-9)
                - Underscores (_)
                - Hyphens (-)
                - Be the same ID used when sending and retrieving positions.
            """);

        waitForInputToContinue(scanner);
        try {
            CompletableFuture<BatchUpdateDevicePositionResponse> future = locationActions.updateDevicePosition(trackerName, deviceId);
            future.join();
            logger.info(deviceId + " was successfully updated in the location tracking system.");
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.info("The resource was not found: {}", cause.getMessage(), cause);
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("8. Retrieve the most recent position update for a specified device..");
        waitForInputToContinue(scanner);
        try {
            GetDevicePositionResponse response = locationActions.getDevicePosition(trackerName, deviceId).join();
            logger.info("Successfully fetched device position: {}", response.position());
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.info("The resource was not found: {}", cause.getMessage(), cause);
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("9. Create a route calculator.");
        waitForInputToContinue(scanner);
        try {
            CreateRouteCalculatorResponse response = locationActions.createRouteCalculator(calculatorName).join();
            logger.info("Route calculator created successfully: {}", response.calculatorArn());
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ConflictException) {
                logger.info("A conflict occurred: {}", cause.getMessage(), cause);
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("10. Determine the distance between Seattle and Vancouver using the route calculator.");
        waitForInputToContinue(scanner);
        try {
            CalculateRouteResponse response = locationActions.calcDistanceAsync(calculatorName).join();
            logger.info("Successfully calculated route. The distance in kilometers is {}", response.summary().distance());
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.info("The resource was not found: {}", cause.getMessage(), cause);
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info("11. Use the GeoPlacesAsyncClient to perform additional operations.");
        logger.info("""
            This scenario will show use of the GeoPlacesClient that enables  
            location search and geocoding capabilities for your applications.\s
                    
            We are going to use this client to perform these AWS Location tasks:
             - Reverse Geocoding (reverseGeocode): Converts geographic coordinates into addresses.
             - Place Search (searchText): Finds places based on search queries.
             - Nearby Search (searchNearby): Finds places near a specific location.
            """);

        logger.info("First we will perform a Reverse Geocoding operation");
        waitForInputToContinue(scanner);
        try {
            locationActions.reverseGeocode().join();
            logger.info("Now we are going to perform a text search using coffee shop.");
            waitForInputToContinue(scanner);
            locationActions.searchText("coffee shop").join();
            waitForInputToContinue(scanner);

            logger.info("Now we are going to perform a nearby Search.");
            //waitForInputToContinue(scanner);
            locationActions.searchNearBy().join();
            waitForInputToContinue(scanner);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                logger.error("A validation error occurred: {}", cause.getMessage(), cause);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
        logger.info(DASHES);

        logger.info("12. Delete the AWS Location Services resources.");
        logger.info("Would you like to delete the AWS Location Services resources? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            cleanUp(mapName, keyName, collectionName, trackerName, calculatorName);
        } else {
            logger.info("The AWS resources will not be deleted.");
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info(" This concludes the AWS Location Service scenario.");
        logger.info(DASHES);
    }

    /**
     * Cleans up resources by deleting the specified map, key, geofence collection, tracker, and route calculator.
     *
     * @param mapName The name of the map to delete.
     * @param keyName The name of the key to delete.
     * @param collectionName The name of the geofence collection to delete.
     * @param trackerName The name of the tracker to delete.
     * @param calculatorName The name of the route calculator to delete.
     */
    private static void cleanUp(String mapName, String keyName, String collectionName, String trackerName, String calculatorName) {
        try {
            locationActions.deleteMap(mapName).join();
            locationActions.deleteKey(keyName).join();
            locationActions.deleteGeofenceCollectionAsync(collectionName).join();
            locationActions.deleteTracker(trackerName).join();
            locationActions.deleteRouteCalculator(calculatorName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.info("The resource was not found: {}", cause.getMessage(), cause);
            } else {
                logger.info("An unexpected error occurred: {}", cause.getMessage(), cause);
            }
            return;
        }
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
Amazon Location Service SDK メソッドのラッパークラス。  

```
public class LocationActions {

    private static LocationAsyncClient locationAsyncClient;

    private static GeoPlacesAsyncClient geoPlacesAsyncClient;
    private static final Logger logger = LoggerFactory.getLogger(LocationActions.class);

    // This Singleton pattern ensures that only one `LocationClient`
    // instance is used throughout the application.
    private LocationAsyncClient getClient() {
        if (locationAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            locationAsyncClient = LocationAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return locationAsyncClient;
    }

    private static GeoPlacesAsyncClient getGeoPlacesClient() {
        if (geoPlacesAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            geoPlacesAsyncClient = GeoPlacesAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return geoPlacesAsyncClient;
    }


    /**
     * Performs a nearby places search based on the provided geographic coordinates (latitude and longitude).
     * The method sends an asynchronous request to search for places within a 1-kilometer radius of the specified location.
     * The results are processed and printed once the search completes successfully.
     */
    public CompletableFuture<SearchNearbyResponse> searchNearBy() {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        List<Double> queryPosition = List.of(longitude, latitude);

        // Set up the request for searching nearby places.
        SearchNearbyRequest request = SearchNearbyRequest.builder()
            .queryPosition(queryPosition)  // Set the position
            .queryRadius(1000L)  // Radius in meters (1000 meters = 1 km).
            .build();

        return getGeoPlacesClient().searchNearby(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                        throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error performing place search", exception);
                }

                // Process the response and print the results.
                response.resultItems().forEach(result -> {
                    logger.info("Place Name: " + result.placeType().name());
                    logger.info("Address: " + result.address().label());
                    logger.info("Distance: " + result.distance() + " meters");
                    logger.info("-------------------------");
                });
            });
    }


    /**
     * Searches for a place using the provided search query and prints the detailed information of the first result.
     *
     * @param searchQuery the search query to be used for the place search (ex, coffee shop)
     */
    public CompletableFuture<Void> searchText(String searchQuery) {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        List<Double> queryPosition = List.of(longitude, latitude);

        SearchTextRequest request = SearchTextRequest.builder()
                .queryText(searchQuery)
                .biasPosition(queryPosition)
                .build();

        return getGeoPlacesClient().searchText(request)
                .thenCompose(response -> {
                    if (response.resultItems().isEmpty()) {
                        logger.info("No places found.");
                        return CompletableFuture.completedFuture(null);
                    }

                    // Get the first place ID
                    String placeId = response.resultItems().get(0).placeId();
                    logger.info("Found Place with id: " + placeId);

                    // Fetch detailed info using getPlace
                    GetPlaceRequest getPlaceRequest = GetPlaceRequest.builder()
                            .placeId(placeId)
                            .build();

                    return getGeoPlacesClient().getPlace(getPlaceRequest)
                            .thenAccept(placeResponse -> {
                                logger.info("Detailed Place Information:");
                                logger.info("Name: " + placeResponse.placeType().name());
                                logger.info("Address: " + placeResponse.address().label());

                                if (placeResponse.foodTypes() != null && !placeResponse.foodTypes().isEmpty()) {
                                    logger.info("Food Types:");
                                    placeResponse.foodTypes().forEach(foodType -> {
                                        logger.info("  - " + foodType);
                                    });
                                } else {
                                    logger.info("No food types available.");
                                }
                                logger.info("-------------------------");
                            });
                })
                .exceptionally(exception -> {
                    Throwable cause = exception.getCause();
                    if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                        throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error performing place search", exception);
                });
    }



    /**
     * Performs reverse geocoding using the AWS Geo Places API.
     * Reverse geocoding is the process of converting geographic coordinates (latitude and longitude) to a human-readable address.
     * This method uses the latitude and longitude of San Francisco as the input, and prints the resulting address.
     */
    public CompletableFuture<ReverseGeocodeResponse> reverseGeocode() {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        logger.info("Use latitude 37.7749 and longitude -122.4194");

        // AWS expects [longitude, latitude].
        List<Double> queryPosition = List.of(longitude, latitude);
        ReverseGeocodeRequest request = ReverseGeocodeRequest.builder()
            .queryPosition(queryPosition)
            .build();
        CompletableFuture<ReverseGeocodeResponse> futureResponse =
            getGeoPlacesClient().reverseGeocode(request);

        return futureResponse.whenComplete((response, exception) -> {
            if (exception != null) {
                Throwable cause = exception.getCause();
                if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                    throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                }
                throw new CompletionException("Error performing reverse geocoding", exception);
            }

            response.resultItems().forEach(result ->
                logger.info("The address is: " + result.address().label())
            );
        });
    }


    /**
     * Calculates the distance between two locations asynchronously.
     *
     * @param routeCalcName the name of the route calculator to use
     * @return a {@link CompletableFuture} that will complete with a {@link CalculateRouteResponse} containing the distance and estimated duration of the route
     */
    public CompletableFuture<CalculateRouteResponse> calcDistanceAsync(String routeCalcName) {
        // Define coordinates for Seattle, WA and Vancouver, BC.
        List<Double> departurePosition = Arrays.asList(-122.3321, 47.6062);
        List<Double> arrivePosition = Arrays.asList(-123.1216, 49.2827);

        CalculateRouteRequest request = CalculateRouteRequest.builder()
            .calculatorName(routeCalcName)
            .departurePosition(departurePosition)
            .destinationPosition(arrivePosition)
            .travelMode("Car") // Options: Car, Truck, Walking, Bicycle
            .distanceUnit("Kilometers") // Options: Meters, Kilometers, Miles
            .build();

        return getClient().calculateRoute(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The AWS resource was not found: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Failed to calculate route: " + exception.getMessage(), exception);
                }
            });
    }


    /**
     * Creates a new route calculator with the specified name and data source.
     *
     * @param routeCalcName the name of the route calculator to be created
     */
    public CompletableFuture<CreateRouteCalculatorResponse> createRouteCalculator(String routeCalcName) {
        String dataSource = "Esri"; // or "Here"
        CreateRouteCalculatorRequest request = CreateRouteCalculatorRequest.builder()
            .calculatorName(routeCalcName)
            .dataSource(dataSource)
            .build();

        return getClient().createRouteCalculator(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("A conflict error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Failed to create route calculator: " + exception.getMessage(), exception);
                }
            });
    }


    /**
     * Retrieves the position of a device using the provided LocationClient.
     *
     * @param trackerName The name of the tracker associated with the device.
     * @param deviceId    The ID of the device to retrieve the position for.
     * @throws RuntimeException If there is an error fetching the device position.
     */
    public CompletableFuture<GetDevicePositionResponse> getDevicePosition(String trackerName, String deviceId) {
        GetDevicePositionRequest request = GetDevicePositionRequest.builder()
            .trackerName(trackerName)
            .deviceId(deviceId)
            .build();

        return getClient().getDevicePosition(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The AWS resource was not found: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error fetching device position: " + exception.getMessage(), exception);
                }
            });
    }


    /**
     * Updates the position of a device in the location tracking system.
     *
     * @param trackerName the name of the tracker associated with the device
     * @param deviceId    the unique identifier of the device
     * @throws RuntimeException if an error occurs while updating the device position
     */
    public CompletableFuture<BatchUpdateDevicePositionResponse> updateDevicePosition(String trackerName, String deviceId) {
        double latitude = 37.7749;  // Example: San Francisco
        double longitude = -122.4194;

        DevicePositionUpdate positionUpdate = DevicePositionUpdate.builder()
            .deviceId(deviceId)
            .sampleTime(Instant.now()) // Timestamp of position update.
            .position(Arrays.asList(longitude, latitude)) // AWS requires [longitude, latitude]
            .build();

        BatchUpdateDevicePositionRequest request = BatchUpdateDevicePositionRequest.builder()
            .trackerName(trackerName)
            .updates(positionUpdate)
            .build();

        CompletableFuture<BatchUpdateDevicePositionResponse> futureResponse = getClient().batchUpdateDevicePosition(request);
        return futureResponse.whenComplete((response, exception) -> {
            if (exception != null) {
                Throwable cause = exception.getCause();
                if (cause instanceof ResourceNotFoundException) {
                    throw new CompletionException("The resource was not found: " + cause.getMessage(), cause);
                } else {
                    throw new CompletionException("Error updating device position: " + exception.getMessage(), exception);
                }
            }
        });
    }


    /**
     * Creates a new tracker resource in your AWS account, which you can use to track the location of devices.
     *
     * @param trackerName the name of the tracker to be created
     * @return a {@link CompletableFuture} that, when completed, will contain the Amazon Resource Name (ARN) of the created tracker
     */
    public CompletableFuture<String> createTracker(String trackerName) {
        CreateTrackerRequest trackerRequest = CreateTrackerRequest.builder()
            .description("Created using the Java V2 SDK")
            .trackerName(trackerName)
            .positionFiltering("TimeBased") // Options: TimeBased, DistanceBased, AccuracyBased
            .build();

        return getClient().createTracker(trackerRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("Conflict occurred while creating tracker: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error creating tracker: " + exception.getMessage(), exception);
                }
            })
            .thenApply(CreateTrackerResponse::trackerArn); // Return only the tracker ARN
    }



    /**
     * Adds a new geofence to the specified collection.
     *
     * @param collectionName the name of the geofence collection to add the geofence to
     * @param geoId          the unique identifier for the geofence
     */
    public CompletableFuture<PutGeofenceResponse> putGeofence(String collectionName, String geoId) {
        // Define the geofence geometry (polygon).
        GeofenceGeometry geofenceGeometry = GeofenceGeometry.builder()
            .polygon(List.of(
                List.of(
                    List.of(-122.3381, 47.6101), // First point
                    List.of(-122.3281, 47.6101),
                    List.of(-122.3281, 47.6201),
                    List.of(-122.3381, 47.6201),
                    List.of(-122.3381, 47.6101) // Closing the polygon
                )
            ))
            .build();

        PutGeofenceRequest geofenceRequest = PutGeofenceRequest.builder()
            .collectionName(collectionName) // Specify the collection.
            .geofenceId(geoId) // Unique ID for the geofence.
            .geometry(geofenceGeometry)
            .build();

        return getClient().putGeofence(geofenceRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ValidationException) {
                        throw new CompletionException("Validation error while creating geofence: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error creating geofence: " + exception.getMessage(), exception);
                }
            });
    }


    /**
     * Creates a new geofence collection.
     *
     * @param collectionName the name of the geofence collection to be created
     */
    public CompletableFuture<String> createGeofenceCollection(String collectionName) {
        CreateGeofenceCollectionRequest collectionRequest = CreateGeofenceCollectionRequest.builder()
            .collectionName(collectionName)
            .description("Created by using the AWS SDK for Java")
            .build();

        return getClient().createGeofenceCollection(collectionRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("The geofence collection was not created due to ConflictException.", cause);
                    }
                    throw new CompletionException("Failed to create geofence collection: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response.collectionArn()); // Return only the ARN
    }




    /**
     * Creates a new API key with the specified name and restrictions.
     *
     * @param keyName the name of the API key to be created
     * @param mapArn  the Amazon Resource Name (ARN) of the map resource to which the API key will be associated
     * @return a {@link CompletableFuture} that completes with the Amazon Resource Name (ARN) of the created API key,
     * or {@code null} if the operation failed
     */
    public CompletableFuture<String> createKey(String keyName, String mapArn) {
        ApiKeyRestrictions keyRestrictions = ApiKeyRestrictions.builder()
            .allowActions("geo:GetMap*")
            .allowResources(mapArn)
            .build();

        CreateKeyRequest request = CreateKeyRequest.builder()
            .keyName(keyName)
            .restrictions(keyRestrictions)
            .noExpiry(true)
            .build();

        return getClient().createKey(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof AccessDeniedException) {
                        throw new CompletionException("The request was denied because of insufficient access or permissions.", cause);
                    }
                    throw new CompletionException("Failed to create API key: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response.keyArn()); // This will never return null if the response reaches here
    }



    /**
     * Creates a new map with the specified name and configuration.
     *
     * @param mapName the name of the map to be created
     * @return a {@link CompletableFuture} that, when completed, will contain the Amazon Resource Name (ARN) of the created map
     * @throws CompletionException if an error occurs while creating the map, such as exceeding the service quota
     */
    public CompletableFuture<String> createMap(String mapName) {
        MapConfiguration configuration = MapConfiguration.builder()
            .style("VectorEsriNavigation")
            .build();

        CreateMapRequest mapRequest = CreateMapRequest.builder()
            .mapName(mapName)
            .configuration(configuration)
            .description("A map created using the Java V2 API")
            .build();

        return getClient().createMap(mapRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ServiceQuotaExceededException) {
                        throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                    }
                    throw new CompletionException("Failed to create map: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response.mapArn()); // Return the map ARN
    }



    /**
     * Deletes a geofence collection asynchronously.
     *
     * @param collectionName the name of the geofence collection to be deleted
     * @return a {@link CompletableFuture} that completes when the geofence collection has been deleted
     */
    public CompletableFuture<Void> deleteGeofenceCollectionAsync(String collectionName) {
        DeleteGeofenceCollectionRequest collectionRequest = DeleteGeofenceCollectionRequest.builder()
            .collectionName(collectionName)
            .build();

        return getClient().deleteGeofenceCollection(collectionRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The requested geofence collection was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete geofence collection: " + exception.getMessage(), exception);
                }
                logger.info("The geofence collection {} was deleted.", collectionName);
            })
            .thenApply(response -> null);
    }



    /**
     * Deletes the specified key from the key-value store.
     *
     * @param keyName the name of the key to be deleted
     * @return a {@link CompletableFuture} that completes when the key has been deleted
     * @throws CompletionException if the key was not found or if an error occurred during the deletion process
     */
    public CompletableFuture<Void> deleteKey(String keyName) {
        DeleteKeyRequest keyRequest = DeleteKeyRequest.builder()
            .keyName(keyName)
            .build();

        return getClient().deleteKey(keyRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The key was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete key: " + exception.getMessage(), exception);
                }
                logger.info("The key {} was deleted.", keyName);
            })
            .thenApply(response -> null);
    }


    /**
     * Deletes a map with the specified name.
     *
     * @param mapName the name of the map to be deleted
     * @return a {@link CompletableFuture} that completes when the map deletion is successful, or throws a {@link CompletionException} if an error occurs
     */
    public CompletableFuture<Void> deleteMap(String mapName) {
        DeleteMapRequest mapRequest = DeleteMapRequest.builder()
            .mapName(mapName)
            .build();

        return getClient().deleteMap(mapRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The map was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete map: " + exception.getMessage(), exception);
                }
                logger.info("The map {} was deleted.", mapName);
            })
            .thenApply(response -> null);
    }


    /**
     * Deletes a tracker with the specified name.
     *
     * @param trackerName the name of the tracker to be deleted
     * @return a {@link CompletableFuture} that completes when the tracker has been deleted
     * @throws CompletionException if an error occurs while deleting the tracker
     *                             - if the tracker was not found, a {@link ResourceNotFoundException} is thrown wrapped in the CompletionException
     *                             - if any other error occurs, a generic CompletionException is thrown with the error message
     */
    public CompletableFuture<Void> deleteTracker(String trackerName) {
        DeleteTrackerRequest trackerRequest = DeleteTrackerRequest.builder()
            .trackerName(trackerName)
            .build();

        return getClient().deleteTracker(trackerRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The tracker was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete the tracker: " + exception.getMessage(), exception);
                }
                logger.info("The tracker {} was deleted.", trackerName);
            })
            .thenApply(response -> null); // Ensures CompletableFuture<Void>
    }


    /**
     * Deletes a route calculator from the system.
     *
     * @param calcName the name of the route calculator to delete
     * @return a {@link CompletableFuture} that completes when the route calculator has been deleted
     * @throws CompletionException if an error occurs while deleting the route calculator
     *                             - If the route calculator was not found, a {@link ResourceNotFoundException} will be thrown
     *                             - If any other error occurs, a generic {@link CompletionException} will be thrown
     */
    public CompletableFuture<Void> deleteRouteCalculator(String calcName) {
        DeleteRouteCalculatorRequest calculatorRequest = DeleteRouteCalculatorRequest.builder()
            .calculatorName(calcName)
            .build();

        return getClient().deleteRouteCalculator(calculatorRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The route calculator was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete the route calculator: " + exception.getMessage(), exception);
                }
                logger.info("The route calculator {} was deleted.", calcName);
            })
            .thenApply(response -> null);
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [BatchUpdateDevicePosition](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/BatchUpdateDevicePosition)
  + [CalculateRoute](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CalculateRoute)
  + [CreateGeofenceCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateGeofenceCollection)
  + [CreateKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateKey)
  + [CreateMap](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateMap)
  + [CreateRouteCalculator](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateRouteCalculator)
  + [CreateTracker](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateTracker)
  + [DeleteGeofenceCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteGeofenceCollection)
  + [DeleteKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteKey)
  + [DeleteMap](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteMap)
  + [DeleteRouteCalculator](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteRouteCalculator)
  + [DeleteTracker](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteTracker)
  + [GetDevicePosition](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/GetDevicePosition)
  + [PutGeofence](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/PutGeofence)

## アクション
<a name="actions"></a>

### `BatchUpdateDevicePosition`
<a name="location_BatchUpdateDevicePosition_java_2_topic"></a>

次のコード例は、`BatchUpdateDevicePosition` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the position of a device in the location tracking system.
     *
     * @param trackerName the name of the tracker associated with the device
     * @param deviceId    the unique identifier of the device
     * @throws RuntimeException if an error occurs while updating the device position
     */
    public CompletableFuture<BatchUpdateDevicePositionResponse> updateDevicePosition(String trackerName, String deviceId) {
        double latitude = 37.7749;  // Example: San Francisco
        double longitude = -122.4194;

        DevicePositionUpdate positionUpdate = DevicePositionUpdate.builder()
            .deviceId(deviceId)
            .sampleTime(Instant.now()) // Timestamp of position update.
            .position(Arrays.asList(longitude, latitude)) // AWS requires [longitude, latitude]
            .build();

        BatchUpdateDevicePositionRequest request = BatchUpdateDevicePositionRequest.builder()
            .trackerName(trackerName)
            .updates(positionUpdate)
            .build();

        CompletableFuture<BatchUpdateDevicePositionResponse> futureResponse = getClient().batchUpdateDevicePosition(request);
        return futureResponse.whenComplete((response, exception) -> {
            if (exception != null) {
                Throwable cause = exception.getCause();
                if (cause instanceof ResourceNotFoundException) {
                    throw new CompletionException("The resource was not found: " + cause.getMessage(), cause);
                } else {
                    throw new CompletionException("Error updating device position: " + exception.getMessage(), exception);
                }
            }
        });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[BatchUpdateDevicePosition](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/BatchUpdateDevicePosition)」を参照してください。

### `CalculateRoute`
<a name="location_CalculateRoute_java_2_topic"></a>

次のコード例は、`CalculateRoute` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Calculates the distance between two locations asynchronously.
     *
     * @param routeCalcName the name of the route calculator to use
     * @return a {@link CompletableFuture} that will complete with a {@link CalculateRouteResponse} containing the distance and estimated duration of the route
     */
    public CompletableFuture<CalculateRouteResponse> calcDistanceAsync(String routeCalcName) {
        // Define coordinates for Seattle, WA and Vancouver, BC.
        List<Double> departurePosition = Arrays.asList(-122.3321, 47.6062);
        List<Double> arrivePosition = Arrays.asList(-123.1216, 49.2827);

        CalculateRouteRequest request = CalculateRouteRequest.builder()
            .calculatorName(routeCalcName)
            .departurePosition(departurePosition)
            .destinationPosition(arrivePosition)
            .travelMode("Car") // Options: Car, Truck, Walking, Bicycle
            .distanceUnit("Kilometers") // Options: Meters, Kilometers, Miles
            .build();

        return getClient().calculateRoute(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The AWS resource was not found: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Failed to calculate route: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CalculateRoute](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CalculateRoute)」を参照してください。

### `CreateGeofenceCollection`
<a name="location_CreateGeofenceCollection_java_2_topic"></a>

次のコード例は、`CreateGeofenceCollection` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new geofence collection.
     *
     * @param collectionName the name of the geofence collection to be created
     */
    public CompletableFuture<String> createGeofenceCollection(String collectionName) {
        CreateGeofenceCollectionRequest collectionRequest = CreateGeofenceCollectionRequest.builder()
            .collectionName(collectionName)
            .description("Created by using the AWS SDK for Java")
            .build();

        return getClient().createGeofenceCollection(collectionRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("The geofence collection was not created due to ConflictException.", cause);
                    }
                    throw new CompletionException("Failed to create geofence collection: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response.collectionArn()); // Return only the ARN
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateGeofenceCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateGeofenceCollection)」を参照してください。

### `CreateKey`
<a name="location_CreateKey_java_2_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new API key with the specified name and restrictions.
     *
     * @param keyName the name of the API key to be created
     * @param mapArn  the Amazon Resource Name (ARN) of the map resource to which the API key will be associated
     * @return a {@link CompletableFuture} that completes with the Amazon Resource Name (ARN) of the created API key,
     * or {@code null} if the operation failed
     */
    public CompletableFuture<String> createKey(String keyName, String mapArn) {
        ApiKeyRestrictions keyRestrictions = ApiKeyRestrictions.builder()
            .allowActions("geo:GetMap*")
            .allowResources(mapArn)
            .build();

        CreateKeyRequest request = CreateKeyRequest.builder()
            .keyName(keyName)
            .restrictions(keyRestrictions)
            .noExpiry(true)
            .build();

        return getClient().createKey(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof AccessDeniedException) {
                        throw new CompletionException("The request was denied because of insufficient access or permissions.", cause);
                    }
                    throw new CompletionException("Failed to create API key: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response.keyArn()); // This will never return null if the response reaches here
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[CreateKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateKey)」を参照してください。

### `CreateMap`
<a name="location_CreateMap_java_2_topic"></a>

次のコード例は、`CreateMap` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new map with the specified name and configuration.
     *
     * @param mapName the name of the map to be created
     * @return a {@link CompletableFuture} that, when completed, will contain the Amazon Resource Name (ARN) of the created map
     * @throws CompletionException if an error occurs while creating the map, such as exceeding the service quota
     */
    public CompletableFuture<String> createMap(String mapName) {
        MapConfiguration configuration = MapConfiguration.builder()
            .style("VectorEsriNavigation")
            .build();

        CreateMapRequest mapRequest = CreateMapRequest.builder()
            .mapName(mapName)
            .configuration(configuration)
            .description("A map created using the Java V2 API")
            .build();

        return getClient().createMap(mapRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ServiceQuotaExceededException) {
                        throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                    }
                    throw new CompletionException("Failed to create map: " + exception.getMessage(), exception);
                }
            })
            .thenApply(response -> response.mapArn()); // Return the map ARN
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateMap](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateMap)」を参照してください。

### `CreateRouteCalculator`
<a name="location_CreateRouteCalculator_java_2_topic"></a>

次のコード例は、`CreateRouteCalculator` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new route calculator with the specified name and data source.
     *
     * @param routeCalcName the name of the route calculator to be created
     */
    public CompletableFuture<CreateRouteCalculatorResponse> createRouteCalculator(String routeCalcName) {
        String dataSource = "Esri"; // or "Here"
        CreateRouteCalculatorRequest request = CreateRouteCalculatorRequest.builder()
            .calculatorName(routeCalcName)
            .dataSource(dataSource)
            .build();

        return getClient().createRouteCalculator(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("A conflict error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Failed to create route calculator: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateRouteCalculator](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateRouteCalculator)」を参照してください。

### `CreateTracker`
<a name="location_CreateTracker_java_2_topic"></a>

次のコード例は、`CreateTracker` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new tracker resource in your AWS account, which you can use to track the location of devices.
     *
     * @param trackerName the name of the tracker to be created
     * @return a {@link CompletableFuture} that, when completed, will contain the Amazon Resource Name (ARN) of the created tracker
     */
    public CompletableFuture<String> createTracker(String trackerName) {
        CreateTrackerRequest trackerRequest = CreateTrackerRequest.builder()
            .description("Created using the Java V2 SDK")
            .trackerName(trackerName)
            .positionFiltering("TimeBased") // Options: TimeBased, DistanceBased, AccuracyBased
            .build();

        return getClient().createTracker(trackerRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ConflictException) {
                        throw new CompletionException("Conflict occurred while creating tracker: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error creating tracker: " + exception.getMessage(), exception);
                }
            })
            .thenApply(CreateTrackerResponse::trackerArn); // Return only the tracker ARN
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateTracker](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/CreateTracker)」を参照してください。

### `DeleteGeofenceCollection`
<a name="location_DeleteGeofenceCollection_java_2_topic"></a>

次のコード例は、`DeleteGeofenceCollection` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a geofence collection asynchronously.
     *
     * @param collectionName the name of the geofence collection to be deleted
     * @return a {@link CompletableFuture} that completes when the geofence collection has been deleted
     */
    public CompletableFuture<Void> deleteGeofenceCollectionAsync(String collectionName) {
        DeleteGeofenceCollectionRequest collectionRequest = DeleteGeofenceCollectionRequest.builder()
            .collectionName(collectionName)
            .build();

        return getClient().deleteGeofenceCollection(collectionRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The requested geofence collection was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete geofence collection: " + exception.getMessage(), exception);
                }
                logger.info("The geofence collection {} was deleted.", collectionName);
            })
            .thenApply(response -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteGeofenceCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteGeofenceCollection)」を参照してください。

### `DeleteKey`
<a name="location_DeleteKey_java_2_topic"></a>

次のコード例は、`DeleteKey` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes the specified key from the key-value store.
     *
     * @param keyName the name of the key to be deleted
     * @return a {@link CompletableFuture} that completes when the key has been deleted
     * @throws CompletionException if the key was not found or if an error occurred during the deletion process
     */
    public CompletableFuture<Void> deleteKey(String keyName) {
        DeleteKeyRequest keyRequest = DeleteKeyRequest.builder()
            .keyName(keyName)
            .build();

        return getClient().deleteKey(keyRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The key was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete key: " + exception.getMessage(), exception);
                }
                logger.info("The key {} was deleted.", keyName);
            })
            .thenApply(response -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteKey](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteKey)」を参照してください。

### `DeleteMap`
<a name="location_DeleteMap_java_2_topic"></a>

次のコード例は、`DeleteMap` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a map with the specified name.
     *
     * @param mapName the name of the map to be deleted
     * @return a {@link CompletableFuture} that completes when the map deletion is successful, or throws a {@link CompletionException} if an error occurs
     */
    public CompletableFuture<Void> deleteMap(String mapName) {
        DeleteMapRequest mapRequest = DeleteMapRequest.builder()
            .mapName(mapName)
            .build();

        return getClient().deleteMap(mapRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The map was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete map: " + exception.getMessage(), exception);
                }
                logger.info("The map {} was deleted.", mapName);
            })
            .thenApply(response -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteMap](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteMap)」を参照してください。

### `DeleteRouteCalculator`
<a name="location_DeleteRouteCalculator_java_2_topic"></a>

次のコード例は、`DeleteRouteCalculator` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a route calculator from the system.
     *
     * @param calcName the name of the route calculator to delete
     * @return a {@link CompletableFuture} that completes when the route calculator has been deleted
     * @throws CompletionException if an error occurs while deleting the route calculator
     *                             - If the route calculator was not found, a {@link ResourceNotFoundException} will be thrown
     *                             - If any other error occurs, a generic {@link CompletionException} will be thrown
     */
    public CompletableFuture<Void> deleteRouteCalculator(String calcName) {
        DeleteRouteCalculatorRequest calculatorRequest = DeleteRouteCalculatorRequest.builder()
            .calculatorName(calcName)
            .build();

        return getClient().deleteRouteCalculator(calculatorRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The route calculator was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete the route calculator: " + exception.getMessage(), exception);
                }
                logger.info("The route calculator {} was deleted.", calcName);
            })
            .thenApply(response -> null);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteRouteCalculator](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteRouteCalculator)」を参照してください。

### `DeleteTracker`
<a name="location_DeleteTracker_java_2_topic"></a>

次のコード例は、`DeleteTracker` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a tracker with the specified name.
     *
     * @param trackerName the name of the tracker to be deleted
     * @return a {@link CompletableFuture} that completes when the tracker has been deleted
     * @throws CompletionException if an error occurs while deleting the tracker
     *                             - if the tracker was not found, a {@link ResourceNotFoundException} is thrown wrapped in the CompletionException
     *                             - if any other error occurs, a generic CompletionException is thrown with the error message
     */
    public CompletableFuture<Void> deleteTracker(String trackerName) {
        DeleteTrackerRequest trackerRequest = DeleteTrackerRequest.builder()
            .trackerName(trackerName)
            .build();

        return getClient().deleteTracker(trackerRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The tracker was not found.", cause);
                    }
                    throw new CompletionException("Failed to delete the tracker: " + exception.getMessage(), exception);
                }
                logger.info("The tracker {} was deleted.", trackerName);
            })
            .thenApply(response -> null); // Ensures CompletableFuture<Void>
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteTracker](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/DeleteTracker)」を参照してください。

### `GetDevicePosition`
<a name="location_GetDevicePosition_java_2_topic"></a>

次のコード例は、`GetDevicePosition` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the position of a device using the provided LocationClient.
     *
     * @param trackerName The name of the tracker associated with the device.
     * @param deviceId    The ID of the device to retrieve the position for.
     * @throws RuntimeException If there is an error fetching the device position.
     */
    public CompletableFuture<GetDevicePositionResponse> getDevicePosition(String trackerName, String deviceId) {
        GetDevicePositionRequest request = GetDevicePositionRequest.builder()
            .trackerName(trackerName)
            .deviceId(deviceId)
            .build();

        return getClient().getDevicePosition(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ResourceNotFoundException) {
                        throw new CompletionException("The AWS resource was not found: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error fetching device position: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetDevicePosition](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/GetDevicePosition)」を参照してください。

### `PutGeofence`
<a name="location_PutGeofence_java_2_topic"></a>

次のコード例は、`PutGeofence` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Adds a new geofence to the specified collection.
     *
     * @param collectionName the name of the geofence collection to add the geofence to
     * @param geoId          the unique identifier for the geofence
     */
    public CompletableFuture<PutGeofenceResponse> putGeofence(String collectionName, String geoId) {
        // Define the geofence geometry (polygon).
        GeofenceGeometry geofenceGeometry = GeofenceGeometry.builder()
            .polygon(List.of(
                List.of(
                    List.of(-122.3381, 47.6101), // First point
                    List.of(-122.3281, 47.6101),
                    List.of(-122.3281, 47.6201),
                    List.of(-122.3381, 47.6201),
                    List.of(-122.3381, 47.6101) // Closing the polygon
                )
            ))
            .build();

        PutGeofenceRequest geofenceRequest = PutGeofenceRequest.builder()
            .collectionName(collectionName) // Specify the collection.
            .geofenceId(geoId) // Unique ID for the geofence.
            .geometry(geofenceGeometry)
            .build();

        return getClient().putGeofence(geofenceRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof ValidationException) {
                        throw new CompletionException("Validation error while creating geofence: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error creating geofence: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutGeofence](https://docs.aws.amazon.com/goto/SdkForJavaV2/location-2020-11-19/PutGeofence)」を参照してください。

# SDK を使用した Location Service Places の例
<a name="java_2_geo-places_code_examples"></a>

次のコード例は、Location Service Places AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ReverseGeocode`
<a name="geo-places_ReverseGeocode_java_2_topic"></a>

次のコード例は、`ReverseGeocode` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Performs reverse geocoding using the AWS Geo Places API.
     * Reverse geocoding is the process of converting geographic coordinates (latitude and longitude) to a human-readable address.
     * This method uses the latitude and longitude of San Francisco as the input, and prints the resulting address.
     */
    public CompletableFuture<ReverseGeocodeResponse> reverseGeocode() {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        logger.info("Use latitude 37.7749 and longitude -122.4194");

        // AWS expects [longitude, latitude].
        List<Double> queryPosition = List.of(longitude, latitude);
        ReverseGeocodeRequest request = ReverseGeocodeRequest.builder()
            .queryPosition(queryPosition)
            .build();
        CompletableFuture<ReverseGeocodeResponse> futureResponse =
            getGeoPlacesClient().reverseGeocode(request);

        return futureResponse.whenComplete((response, exception) -> {
            if (exception != null) {
                Throwable cause = exception.getCause();
                if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                    throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                }
                throw new CompletionException("Error performing reverse geocoding", exception);
            }

            response.resultItems().forEach(result ->
                logger.info("The address is: " + result.address().label())
            );
        });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ReverseGeocode](https://docs.aws.amazon.com/goto/SdkForJavaV2/geo-places-2020-11-19/ReverseGeocode)」を参照してください。

### `SearchNearby`
<a name="geo-places_SearchNearby_java_2_topic"></a>

次のコード例は、`SearchNearby` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Performs a nearby places search based on the provided geographic coordinates (latitude and longitude).
     * The method sends an asynchronous request to search for places within a 1-kilometer radius of the specified location.
     * The results are processed and printed once the search completes successfully.
     */
    public CompletableFuture<SearchNearbyResponse> searchNearBy() {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        List<Double> queryPosition = List.of(longitude, latitude);

        // Set up the request for searching nearby places.
        SearchNearbyRequest request = SearchNearbyRequest.builder()
            .queryPosition(queryPosition)  // Set the position
            .queryRadius(1000L)  // Radius in meters (1000 meters = 1 km).
            .build();

        return getGeoPlacesClient().searchNearby(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                        throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error performing place search", exception);
                }

                // Process the response and print the results.
                response.resultItems().forEach(result -> {
                    logger.info("Place Name: " + result.placeType().name());
                    logger.info("Address: " + result.address().label());
                    logger.info("Distance: " + result.distance() + " meters");
                    logger.info("-------------------------");
                });
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SearchNearby](https://docs.aws.amazon.com/goto/SdkForJavaV2/geo-places-2020-11-19/SearchNearby)」を参照してください。

### `SearchText`
<a name="geo-places_SearchText_java_2_topic"></a>

次のコード例は、`SearchText` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/location#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Searches for a place using the provided search query and prints the detailed information of the first result.
     *
     * @param searchQuery the search query to be used for the place search (ex, coffee shop)
     */
    public CompletableFuture<Void> searchText(String searchQuery) {
        double latitude = 37.7749;  // San Francisco
        double longitude = -122.4194;
        List<Double> queryPosition = List.of(longitude, latitude);

        SearchTextRequest request = SearchTextRequest.builder()
                .queryText(searchQuery)
                .biasPosition(queryPosition)
                .build();

        return getGeoPlacesClient().searchText(request)
                .thenCompose(response -> {
                    if (response.resultItems().isEmpty()) {
                        logger.info("No places found.");
                        return CompletableFuture.completedFuture(null);
                    }

                    // Get the first place ID
                    String placeId = response.resultItems().get(0).placeId();
                    logger.info("Found Place with id: " + placeId);

                    // Fetch detailed info using getPlace
                    GetPlaceRequest getPlaceRequest = GetPlaceRequest.builder()
                            .placeId(placeId)
                            .build();

                    return getGeoPlacesClient().getPlace(getPlaceRequest)
                            .thenAccept(placeResponse -> {
                                logger.info("Detailed Place Information:");
                                logger.info("Name: " + placeResponse.placeType().name());
                                logger.info("Address: " + placeResponse.address().label());

                                if (placeResponse.foodTypes() != null && !placeResponse.foodTypes().isEmpty()) {
                                    logger.info("Food Types:");
                                    placeResponse.foodTypes().forEach(foodType -> {
                                        logger.info("  - " + foodType);
                                    });
                                } else {
                                    logger.info("No food types available.");
                                }
                                logger.info("-------------------------");
                            });
                })
                .exceptionally(exception -> {
                    Throwable cause = exception.getCause();
                    if (cause instanceof software.amazon.awssdk.services.geoplaces.model.ValidationException) {
                        throw new CompletionException("A validation error occurred: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Error performing place search", exception);
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SearchText](https://docs.aws.amazon.com/goto/SdkForJavaV2/geo-places-2020-11-19/SearchText)」を参照してください。

# AWS Marketplace SDK for Java 2.x を使用したカタログ API の例
<a name="java_2_marketplace-catalog_code_examples"></a>

次のコード例は、 AWS Marketplace Catalog API AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [AMI 製品](#ami_products)
+ [チャネルパートナーのオファー](#channel_partner_offers)
+ [コンテナ製品](#container_products)
+ [エンティティ](#entities)
+ [Offers](#offers)
+ [製品](#products)
+ [再販承認](#resale_authorization)
+ [SaaS 製品](#saas_products)
+ [Utilities](#utilities)

## AMI 製品
<a name="ami_products"></a>

### 既存の AMI 製品にディメンションを追加し、オファーの料金条件を更新する
<a name="marketplace-catalog_AddDimensionToAmiProductAndSetPriceInPublicOffer_java_2_topic"></a>

次のコード例は、既存の AMI 製品にディメンションを追加し、オファーの料金条件を更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Identifier": "prod-1111111111111",
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": [
                {
                    "Key": "m7g.8xlarge",
                    "Description": "m7g.8xlarge",
                    "Name": "m7g.8xlarge",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "m5.large",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "m7g.4xlarge",
                                        "Price": "0.45"
                                    },
                                    {
                                        "DimensionKey": "m7g.2xlarge",
                                        "Price": "0.45"
                                    },
                                    {
                                        "DimensionKey": "m7g.8xlarge",
                                        "Price": "0.55"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### AMI 製品をデプロイするリージョンを追加する
<a name="marketplace-catalog_AddRegionExistingAmiProduct_java_2_topic"></a>

次のコード例は、AMI 製品をデプロイするリージョンを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-2",
                    "us-west-2"
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックまたは制限付き AMI 製品と、時間単位の年間料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedAmiProductAndPublicOfferWithHourlyAnnualPricing_java_2_topic"></a>

次のコード例は、パブリックまたは制限付き AMI 製品と、時間単位の年間料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Operating Systems"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-1"
                ]
            }
        },
        {
            "ChangeType": "AddInstanceTypes",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "InstanceTypes": [
                    "t2.micro"
                ]
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Version": {
                    "VersionTitle": "Test AMI Version1.0",
                    "ReleaseNotes": "Test AMI Version"
                },
                "DeliveryOptions": [
                    {
                        "Details": {
                            "AmiDeliveryOptionDetails": {
                                "AmiSource": {
                                    "AmiId": "ami-11111111111111111",
                                    "AccessRoleArn": "arn:aws:iam::111111111111:role/AWSMarketplaceAmiIngestion",
                                    "UserName": "ec2-user",
                                    "OperatingSystemName": "AMAZONLINUX",
                                    "OperatingSystemVersion": "10.0.14393",
                                    "ScanningPort": 22
                                },
                                "UsageInstructions": "Test AMI Version",
                                "RecommendedInstanceType": "t2.micro",
                                "SecurityGroups": [
                                    {
                                        "IpProtocol": "tcp",
                                        "IpRanges": [
                                            "0.0.0.0/0"
                                        ],
                                        "FromPort": 10,
                                        "ToPort": 22
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "t2.micro",
                    "Description": "t2.micro",
                    "Name": "t2.micro",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with hourly-annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P365D"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックまたは制限付き AMI 製品と、時間単位の月額料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedAmiProductAndPublicOfferWithHourlyMonthlyPricing_java_2_topic"></a>

次のコード例は、パブリックまたは制限付き AMI 製品と、時間単位の月額料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Operating Systems"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-1"
                ]
            }
        },
        {
            "ChangeType": "AddInstanceTypes",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "InstanceTypes": [
                    "t2.micro"
                ]
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Version": {
                    "VersionTitle": "Test AMI Version1.0",
                    "ReleaseNotes": "Test AMI Version"
                },
                "DeliveryOptions": [
                    {
                        "Details": {
                            "AmiDeliveryOptionDetails": {
                                "AmiSource": {
                                    "AmiId": "ami-11111111111111111",
                                    "AccessRoleArn": "arn:aws:iam::111111111111:role/AWSMarketplaceAmiIngestion",
                                    "UserName": "ec2-user",
                                    "OperatingSystemName": "AMAZONLINUX",
                                    "OperatingSystemVersion": "10.0.14393",
                                    "ScanningPort": 22
                                },
                                "UsageInstructions": "Test AMI Version",
                                "RecommendedInstanceType": "t2.micro",
                                "SecurityGroups": [
                                    {
                                        "IpProtocol": "tcp",
                                        "IpRanges": [
                                            "0.0.0.0/0"
                                        ],
                                        "FromPort": 10,
                                        "ToPort": 22
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "t2.micro",
                    "Description": "t2.micro",
                    "Name": "t2.micro",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with hourly-monthly pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "RecurringPaymentTerm",
                        "CurrencyCode": "USD",
                        "BillingPeriod": "Monthly",
                        "Price": "15.0"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックまたは制限付き AMI 製品と、時間単位の料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedAmiProductAndPublicOfferWithHourlyPricing_java_2_topic"></a>

次のコード例は、パブリックまたは制限付き AMI 製品と、時間単位の料金でパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Operating Systems"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-1"
                ]
            }
        },
        {
            "ChangeType": "AddInstanceTypes",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "InstanceTypes": [
                    "t2.micro"
                ]
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Version": {
                    "VersionTitle": "Test AMI Version1.0",
                    "ReleaseNotes": "Test AMI Version"
                },
                "DeliveryOptions": [
                    {
                        "Details": {
                            "AmiDeliveryOptionDetails": {
                                "AmiSource": {
                                    "AmiId": "ami-11111111111111111",
                                    "AccessRoleArn": "arn:aws:iam::111111111111:role/AWSMarketplaceAmiIngestion",
                                    "UserName": "ec2-user",
                                    "OperatingSystemName": "AMAZONLINUX",
                                    "OperatingSystemVersion": "10.0.14393",
                                    "ScanningPort": 22
                                },
                                "UsageInstructions": "Test AMI Version",
                                "RecommendedInstanceType": "t2.micro",
                                "SecurityGroups": [
                                    {
                                        "IpProtocol": "tcp",
                                        "IpRanges": [
                                            "0.0.0.0/0"
                                        ],
                                        "FromPort": 10,
                                        "ToPort": 22
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "t2.micro",
                    "Description": "t2.micro",
                    "Name": "t2.micro",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with hourly pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### ドラフトパブリックオファーを使用してドラフト AMI 製品を作成する
<a name="marketplace-catalog_CreateDraftAmiProductWithDraftPublicOffer_java_2_topic"></a>

次のコード例は、ドラフトパブリックオファーを使用してドラフト AMI 製品を作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product"
            }
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier",
                "Name": "Test Offer"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### AMI 製品をデプロイするリージョンを制限する
<a name="marketplace-catalog_RestrictRegionExistingAmiProduct_java_2_topic"></a>

次のコード例は、AMI 製品をデプロイするリージョンを制限する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "RestrictRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-west-2"
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 製品の可視性を制限する
<a name="marketplace-catalog_RestrictExistingAmi_java_2_topic"></a>

次のコード例は、製品の可視性を制限する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateVisibility",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "TargetVisibility": "Restricted"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### AMI アセットを新しいリージョンにデプロイするかどうかを指定する
<a name="marketplace-catalog_UpdateFutureRegionSupport_java_2_topic"></a>

次のコード例は、将来のリージョンをサポートするために によって構築された新しいリージョン AWS に AMI アセットをデプロイするかどうかを指定する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateFutureRegionSupport",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "FutureRegionSupport": {
                    "SupportedRegions": [
                        "All"
                    ]
                }
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

## チャネルパートナーオファー
<a name="channel_partner_offers"></a>

### 任意の製品タイプのドラフト CPPO を作成する
<a name="marketplace-catalog_CreateDraftCppoOffer_java_2_topic"></a>

次のコード例は、購入者に公開する前に内部で確認できるように、任意の製品タイプのドラフト CPPO を作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOfferUsingResaleAuthorization",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ResaleAuthorizationId": "11111111-1111-1111-1111-111111111111",
                "Name": "Test Offer",
                "Description": "Test product"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 契約料金を使用する再販承認の代替プライベートオファーを作成する
<a name="marketplace-catalog_CreateResaleAuthorizationReplacementOffer_java_2_topic"></a>

次のコード例は、既存の契約から契約料金を使用する再販承認代替プライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateReplacementOfferUsingResaleAuthorization",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateReplacementOfferResaleAuth",
            "DetailsDocument": {
                "AgreementId": "agmt-1111111111111111111111111",
                "ResaleAuthorizationId": "resaleauthz-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test replacement offer for SaaSProduct using AWS Marketplace API Reference Codes",
                "Description": "Test private resale replacement offer with contract pricing for SaaSProduct"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Duration": "P12M",
                        "Grants": [
                            {
                                "DimensionKey": "BasicService",
                                "MaxQuantity": 2
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementEndDate": "2024-01-30"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "0"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### チャネルパートナーが作成したすべての CPPO を一覧表示する
<a name="marketplace-catalog_ListAllCppoOffers_java_2_topic"></a>

次のコード例は、チャネルパートナーが作成したすべての CPPO を一覧表示する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
package com.example.awsmarketplace.catalogapi;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.EntitySummary;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesResponse;

public class ListAllCppoOffers {

	/*
	 * List all CPPOs created by a channel partner
	 */
	public static void main(String[] args) {
		
		List<String> cppoOfferIds = getAllCppoOfferIds();

		ReferenceCodesUtils.formatOutput(cppoOfferIds);
	}

	public static List<String> getAllCppoOfferIds() {
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		// get all offer entity ids
		List<String> entityIdList = new ArrayList<String>();

		ListEntitiesRequest listEntitiesRequest = 
				ListEntitiesRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityType(ENTITY_TYPE_OFFER)
				.maxResults(10)
				.nextToken(null)
				.build();

		ListEntitiesResponse listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);

		for (EntitySummary entitySummary : listEntitiesResponse.entitySummaryList()) {
			entityIdList.add(entitySummary.entityId());
		}

		while (listEntitiesResponse.nextToken() != null) {
			listEntitiesRequest = 
					ListEntitiesRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityType(ENTITY_TYPE_OFFER)
					.maxResults(10)
					.nextToken(listEntitiesResponse.nextToken())
					.build();
			listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);

			for (EntitySummary entitySummary : listEntitiesResponse.entitySummaryList()) {
				entityIdList.add(entitySummary.entityId());
			}
		}

		// filter for CPPO offers: ResaleAuthorizationId exists in Details

		List<String> cppoOfferIds = new ArrayList<String>();
		
		for (String entityId : entityIdList) {
			DescribeEntityRequest describeEntityRequest = 
					DescribeEntityRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityId(entityId)
					.build();
			DescribeEntityResponse describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
			
			Document resaleAuthorizationDocument = describeEntityResponse.detailsDocument().asMap().get(ATTRIBUTE_RESALE_AUTHORIZATION_ID);
			String resaleAuthorizationId = resaleAuthorizationDocument != null ? resaleAuthorizationDocument.asString() : "";

			if (!resaleAuthorizationId.isEmpty()) {
			    cppoOfferIds.add(resaleAuthorizationId);
			}
		}
		return cppoOfferIds;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListEntities](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/ListEntities)」を参照してください。

### チャネルパートナーが利用できるすべての共有再販承認を一覧表示する
<a name="marketplace-catalog_ListAllSharedResaleAuthorizations_java_2_topic"></a>

次のコード例は、チャネルパートナーが利用できるすべての共有再販承認を一覧表示する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
package com.example.awsmarketplace.catalogapi;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesResponse;

public class ListAllSharedResaleAuthorizations {

	/*
	 * list all resale authorizations shared to an account
	 */
	public static void main(String[] args) {
		
		List<ListEntitiesResponse> responseList = getListEntityResponseList();
		ReferenceCodesUtils.formatOutput(responseList);
	}

	public static List<ListEntitiesResponse> getListEntityResponseList() {
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		List<ListEntitiesResponse> responseList = new ArrayList<ListEntitiesResponse>();

		ListEntitiesRequest listEntitiesRequest = 
				ListEntitiesRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityType(ENTITY_TYPE_RESALE_AUTHORIZATION)
				.maxResults(10)
				.ownershipType(OWNERSHIP_TYPE_SHARED)
				.nextToken(null)
				.build();

		ListEntitiesResponse listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);

		responseList.add(listEntitiesResponse);

		while (listEntitiesResponse.nextToken() != null) {
			listEntitiesRequest = ListEntitiesRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityType(ENTITY_TYPE_RESALE_AUTHORIZATION)
					.maxResults(10)
					.ownershipType(OWNERSHIP_TYPE_SHARED)
					.nextToken(listEntitiesResponse.nextToken())
					.build();

			listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);

			responseList.add(listEntitiesResponse);
		}
		return responseList;
	}
	
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListEntities](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/ListEntities)」を参照してください。

### CPPO を発行し、購入者の EULA を追加する
<a name="marketplace-catalog_PublishCppoEula_java_2_topic"></a>

次のコード例は、CPPO を発行し、購入者の EULA を追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateOfferUsingResaleAuthorization",
            "Entity": {
            "Type": "Offer@1.0"
            },
            "ChangeName": "CreateCPPOoffer",
            "DetailsDocument": {
                "ResaleAuthorizationId":"resaleauthz-1111111111111", 
                "Name": "Test Offer",
                "Description":"Test product"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
        			{			
            			"Type": "LegalTerm",
            			"Documents": [
            				{
            					"Type": "CustomEula", 
            					"Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
            				}
            			]
        			}
    			]
        	}
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": ["222222222222"]
                    }
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-07-31"
                }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P450D"
                    }
                ]
             }
        },
        { 
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 1 回限りの再販承認を使用して CPPO を発行し、価格マークアップを更新する
<a name="marketplace-catalog_PublishOneTimeCppoWithPriceMarkup_java_2_topic"></a>

次のコード例は、AMI、SaaS、またはコンテナ製品に対して、1 回限りの再販売承認を使用して CPPO を発行し、価格のマークアップを更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateOfferUsingResaleAuthorization",
            "Entity": {
            "Type": "Offer@1.0"
            },
            "ChangeName": "CreateCPPOoffer",
            "DetailsDocument": {
                "ResaleAuthorizationId":"resaleauthz-1111111111111", 
                "Name": "Test Offer",
                "Description":"Test product"
            }
        },
        {
            "ChangeType": "UpdateMarkup",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Percentage" : "5.0"
        }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": ["222222222222"]
                    }
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-07-31"
                }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P450D"
                    }
                ]
             }
        },
        { 
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### ドラフト CPPO を発行し、価格マークアップを更新する
<a name="marketplace-catalog_PublishCppoPriceMarkup_java_2_topic"></a>

次のコード例は、ドラフト CPPO を発行し、価格マークアップを更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateOfferUsingResaleAuthorization",
            "Entity": {
            "Type": "Offer@1.0"
            },
            "ChangeName": "CreateCPPOoffer",
            "DetailsDocument": {
                "ResaleAuthorizationId":"resaleauthz-1111111111111", 
                "Name": "Test Offer",
                "Description":"Test product"
            }
        },
        {
            "ChangeType": "UpdateMarkup",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Percentage" : "5.0"
        }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": ["222222222222"]
                    }
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-07-31"
                }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P450D"
                    }
                ]
             }
        },
        { 
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### CPPO の有効期限を更新する
<a name="marketplace-catalog_UpdateCppoExpiryDate_java_2_topic"></a>

次のコード例は、CPPO の有効期限を更新して、購入者がオファーを評価して承諾する時間を延長する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2025-07-31"
                }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

## コンテナ製品
<a name="container_products"></a>

### ドラフトパブリックオファーを使用するドラフトコンテナ製品を作成する
<a name="marketplace-catalog_CreateDraftContainerProductWithDraftPublicOffer_java_2_topic"></a>

次のコード例は、ドラフトパブリックオファーを使用するドラフトコンテナ製品を作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog":"AWSMarketplace",
    "changeSet":[
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "ContainerProduct@1.0"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product"
            }
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier",
                "Name": "Test Offer"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックオファーと契約料金を使用する制限付きコンテナ製品を作成する
<a name="marketplace-catalog_CreateLimitedContainerProductPublicOffer_java_2_topic"></a>

次のコード例は、パブリックオファー、契約料金、標準 EULA を使用する制限付きコンテナ製品を作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "ContainerProduct@1.0"
            },
            "DetailsDocument": {},
            "ChangeName": "CreateProductChange"
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "Categories": [
                    "Streaming solutions"
                ],
                "ProductTitle": "ContainerProduct",
                "AdditionalResources": [],
                "LongDescription": "Long description goes here",
                "SearchKeywords": [
                    "container streaming"
                ],
                "ShortDescription": "Description1",
                "Highlights": [
                    "Highlight 1",
                    "Highlight 2"
                ],
                "SupportDescription": "No support available",
                "VideoUrls": []
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "Cores",
                    "Description": "Cores per cluster",
                    "Name": "Cores",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddRepositories",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Repositories": [
                    {
                        "RepositoryName": "uniquerepositoryname",
                        "RepositoryType": "ECR"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            },
            "ChangeName": "CreateOfferChange"
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "Constraints": {
                                    "MultipleDimensionSelection": "Disallowed",
                                    "QuantityConfiguration": "Disallowed"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "Cores",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "No refunds"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Some container offer Name",
                "Description": "Some interesting container offer description"
            }
        },
        {
            "ChangeType": "UpdateRenewalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "RenewalTerm"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

## エンティティ
<a name="entities"></a>

### 1 回の呼び出しですべてのエンティティを記述する
<a name="marketplace-catalog_BatchDescribeEntities_java_2_topic"></a>

次のコード例は、1 回の呼び出しですべてのエンティティを記述する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
﻿// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.catalogapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.BatchDescribeEntitiesRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.EntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.BatchDescribeEntitiesResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.EntityDetail;
import software.amazon.awssdk.services.marketplacecatalog.model.BatchDescribeErrorDetail;

import java.util.Arrays;
import java.util.Map;

public class BatchDescribeEntities {

    /*
     * BatchDescribe my entities in a single call and
     *  check if it contains all the information I need to know about the entities.
     */
    public static void main(String[] args) {

        MarketplaceCatalogClient marketplaceCatalogClient =
                MarketplaceCatalogClient.builder()
                        .httpClient(ApacheHttpClient.builder().build())
                        .credentialsProvider(ProfileCredentialsProvider.create())
                        .build();

        BatchDescribeEntitiesRequest batchDescribeEntitiesRequest =
                BatchDescribeEntitiesRequest.builder()
                        .entityRequestList(Arrays.asList(
                                EntityRequest.builder()
                                        .catalog(AWS_MP_CATALOG).entityId(OFFER_ID)
                                        .build(),
                                EntityRequest.builder()
                                        .catalog(AWS_MP_CATALOG).entityId(PRODUCT_ID)
                                        .build()))
                        .build();

        BatchDescribeEntitiesResponse batchDescribeEntitiesResponse = marketplaceCatalogClient.batchDescribeEntities(batchDescribeEntitiesRequest);

        // Reading the successful entities response
        Map<String, EntityDetail> entityDetailsMap = batchDescribeEntitiesResponse.entityDetails();
        for (Map.Entry<String, EntityDetail> entry : entityDetailsMap.entrySet()) {
            System.out.println("EntityId: " + entry.getKey());
            ReferenceCodesUtils.formatOutput(entry.getValue());
        }

        // Logging the failed entities error details
        Map<String, BatchDescribeErrorDetail> entityErrorsMap = batchDescribeEntitiesResponse.errors();
        for (Map.Entry<String, BatchDescribeErrorDetail> entry : entityErrorsMap.entrySet()) {
            System.out.println(String.format("EntityId: %s, ErrorCode: %s, ErrorMessage: %s", entry.getKey(),
                    entry.getValue().errorCode(), entry.getValue().errorMessage()));
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[BatchDescribeEntities](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/BatchDescribeEntities)」を参照してください。

### 製品に関連付けられたすべてのオファーを一覧表示して記述する
<a name="marketplace-catalog_ListProductOffers_java_2_topic"></a>

次のコード例は、製品に関連付けられているすべてのオファーを一覧表示して記述する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
package com.example.awsmarketplace.catalogapi;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.EntitySummary;
import software.amazon.awssdk.services.marketplacecatalog.model.EntityTypeFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferProductIdFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferTargetingFilter;

public class ListProductPrivateOffers {

	private static MarketplaceCatalogClient marketplaceCatalogClient = 
			MarketplaceCatalogClient.builder()
			.httpClient(ApacheHttpClient.builder().build())
			.credentialsProvider(ProfileCredentialsProvider.create())
			.build();
	/*
	 * retrieve all private offer information related to a single product
	 */
	public static void main(String[] args) {

		List<EntitySummary> entitySummaryList = getEntitySummaryList();
		
		// for each offer id, output the offer detail using DescribeEntity API
		
		for (EntitySummary entitySummary : entitySummaryList) {
			DescribeEntityRequest describeEntityRequest = 
					DescribeEntityRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityId(entitySummary.entityId())
					.build();
			DescribeEntityResponse describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
			ReferenceCodesUtils.formatOutput(describeEntityResponse);
		}
	}
	public static List<EntitySummary> getEntitySummaryList() {
		// define list entities filters
		
		EntityTypeFilters entityTypeFilters = 
				EntityTypeFilters.builder()
				.offerFilters(OfferFilters.builder()
						.targeting(OfferTargetingFilter.builder()
								.valueListWithStrings(OFFER_TARGETING_BUYERACCOUNTS)
								.build())
						.productId(OfferProductIdFilter.builder()
								.valueList(PRODUCT_ID)
								.build())
						.build())
				.build();
		
		ListEntitiesRequest listEntitiesRequest = 
				ListEntitiesRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityType(ENTITY_TYPE_OFFER).maxResults(50)
				.entityTypeFilters(entityTypeFilters)
				.nextToken(null)
				.build();
		
		ListEntitiesResponse listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
		
		// save all entitySummary of the results into entitySummaryList
		
		List<EntitySummary> entitySummaryList = new ArrayList<EntitySummary>();
		
		entitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
		
		while ( listEntitiesResponse.nextToken() != null && listEntitiesResponse.nextToken().length() > 0) {
			listEntitiesRequest = 
					ListEntitiesRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityType(ENTITY_TYPE_OFFER).maxResults(50)
					.entityTypeFilters(entityTypeFilters)
					.nextToken(listEntitiesResponse.nextToken())
					.build();
			listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
			entitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
		}
		return entitySummaryList;
	}

}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [DescribeEntity](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/DescribeEntity)
  + [ListEntities](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/ListEntities)

## Offers
<a name="offers"></a>

### SaaS 製品のカスタムディメンションを作成し、プライベートオファーを作成する
<a name="marketplace-catalog_CreateSaasProductCustomDimensionAndPrivateOffer_java_2_topic"></a>

次のコード例は、SaaS 製品のカスタムディメンションを作成し、プライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": [
                {
                    "Types": [
                        "Entitled"
                    ],
                    "Description": "Custom Pricing 4 w/ terms and coverage to be defined in Private Offer",
                    "Unit": "Units",
                    "Key": "Custom4",
                    "Name": "Custom Pricing 4"
                }
            ]
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            },
            "ChangeName": "CreateOfferChange"
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Private Test Offer - SaaS Contract Product",
                "Description": "Private Test Offer - SaaS Contract Product"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "Custom4",
                                        "Price": "300.0"
                                    }
                                ],
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P36M"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ],
    "ChangeSetName": "PrivateOfferWithCustomDimension"
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### AMI または SaaS 製品のドラフトプライベートオファーを作成する
<a name="marketplace-catalog_CreateDraftPrivateOffer_java_2_topic"></a>

次のコード例は、購入者に公開する前に内部で確認するために、AMI または SaaS 製品のドラフトプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "Test Private Offer"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 契約料金と従量制料金を使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractWithPayAsYouGoPricingForSaasProduct_java_2_topic"></a>

次のコード例は、契約料金と従量制料金を使用する、SaaS 製品のプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 契約料金と柔軟な支払いスケジュールを使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractPricingWithFlexiblePaymentScheduleForSaasProduct_java_2_topic"></a>

次のコード例は、契約料金と柔軟な支払いスケジュールを使用する、SaaS 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Grants": [
                            {
                                "DimensionKey": "BasicService",
                                "MaxQuantity": 1
                            },
                            {
                                "DimensionKey": "PremiumService",
                                "MaxQuantity": 1
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P12M"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "200.00"
                            },
                            {
                                "ChargeDate": "2024-02-01",
                                "ChargeAmount": "170.00"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 契約料金を使用する、コンテナ製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractPricingForContainerProduct_java_2_topic"></a>

次のコード例は、契約料金を使用する、コンテナ製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for Container product using AWS Marketplace API Reference Code",
                "Description": "Test private offer for Container product with contract pricing using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "Constraints": {
                                    "MultipleDimensionSelection": "Disallowed",
                                    "QuantityConfiguration": "Disallowed"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "ReqPerHour",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 契約料金を使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractPricingForAmiProduct_java_2_topic"></a>

次のコード例は、契約料金を使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "ReadOnlyUsers",
                                        "Price": "220.00"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 時間単位の年間料金と柔軟な支払いスケジュールを使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithHourlyAnnualPricingAndFlexiblePaymentScheduleForAmiProduct_java_2_topic"></a>

次のコード例は、時間単位の年間料金と柔軟な支払いスケジュールを使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.17"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Duration": "P365D",
                        "Grants": [
                            {
                                "DimensionKey": "t2.micro",
                                "MaxQuantity": 1
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P650D"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "200.00"
                            },
                            {
                                "ChargeDate": "2024-02-01",
                                "ChargeAmount": "170.00"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 時間単位の年間料金を使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithHourlyAnnualPricingForAmiProduct_java_2_topic"></a>

次のコード例は、時間単位の年間料金を使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.17"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P365D"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "220.00"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P650D"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 時間単位の料金を使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithHourlyPricingForAmiProduct_java_2_topic"></a>

次のコード例は、時間単位の料金を使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2025-01-01"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P30D"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### サブスクリプション料金を使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithSubscriptionPricingForSaasProduct_java_2_topic"></a>

次のコード例は、サブスクリプション料金を使用する、SaaS 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.13"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.22"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P30D"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 階層型契約料金を使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithTieredContractPricingForSaasProduct_java_2_topic"></a>

次のコード例は、階層型契約料金を使用する、SaaS 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "120.00"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "200.00"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Disallowed",
                                    "QuantityConfiguration": "Disallowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### サブスクリプション料金を使用する、SaaS 製品向けのパブリック無料トライアルオファーを作成する
<a name="marketplace-catalog_CreatePublicFreeTrialOfferWithSubscriptionPricingForSaasProduct_java_2_topic"></a>

次のコード例は、サブスクリプション料金を使用する、SaaS 製品向けのパブリック無料トライアルオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public free trial offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public free trial offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Free",
                "Terms": [
                    {
                        "Type": "FreeTrialPricingTerm",
                        "Duration": "P20D",
                        "Grants": [
                            {
                                "DimensionKey": "WorkloadSmall"
                            },
                            {
                                "DimensionKey": "WorkloadMedium"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 契約料金を使用する代替プライベートオファーを作成する
<a name="marketplace-catalog_CreateReplacementPrivateOfferWithContractPricing_java_2_topic"></a>

次のコード例は、既存の契約から契約料金を使用する代替プライベートオファーを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateReplacementOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateReplacementOffer",
            "DetailsDocument": {
                "AgreementId": "agmt-1111111111111111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test replacement offer for SaaSProduct using AWS Marketplace API Reference Codes",
                "Description": "Test private replacement offer with contract pricing for SaaSProduct"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Grants": [
                            {
                                "DimensionKey": "BasicService",
                                "MaxQuantity": 2
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementEndDate": "2024-01-30"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "0"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックオファーを記述する
<a name="marketplace-catalog_DescribeOffer_java_2_topic"></a>

次のコード例は、パブリックオファーを記述する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
﻿// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.catalogapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;

public class DescribeEntity {

	/*
	 * Describe my AMI or SaaS or Container product and check if it contains all the information I need to know about the product
	 */
	public static void main(String[] args) {

		String offerId = args.length > 0 ? args[0] : OFFER_ID;

		DescribeEntityResponse describeEntityResponse = getDescribeEntityResponse(offerId);

		ReferenceCodesUtils.formatOutput(describeEntityResponse);
	}

	public static DescribeEntityResponse getDescribeEntityResponse(String offerId) {
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		DescribeEntityRequest describeEntityRequest = 
				DescribeEntityRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityId(offerId)
				.build();

		DescribeEntityResponse describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
		return describeEntityResponse;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeEntity](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/DescribeEntity)」を参照してください。

### ドラフトプライベートオファーを期限切れにする
<a name="marketplace-catalog_ExpirePrivateOffer_java_2_topic"></a>

次のコード例は、購入者にオファーが表示されないように、プライベートオファーの有効期限を過去の日付に設定する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-01-01"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### すべてのプライベートオファーを一覧表示する
<a name="marketplace-catalog_ListAllPrivateOffers_java_2_topic"></a>

次のコード例は、すべてのプライベートオファーを一覧表示する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
package com.example.awsmarketplace.catalogapi;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.EntitySummary;
import software.amazon.awssdk.services.marketplacecatalog.model.EntityTypeFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferAvailabilityEndDateFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferAvailabilityEndDateFilterDateRange;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferBuyerAccountsFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferReleaseDateFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferReleaseDateFilterDateRange;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferTargetingFilter;

public class ListAllPrivateOffers {

	/*
	 * List all my private offers and sort or filter them by Offer Publish Date, Offer Expiry Date and Buyer IDs
	 * 
	 * OfferTargetingFilter = BuyerAccounts (private offer);
	 * OfferBuyerAccountsFilter: Buyer IDs filter
	 * OfferAvailabilityEndDateFilter : Offer Expiry Date filter
	 * OfferReleaseDateFilter : Offer Publish Date filter
	 */
	
	private static MarketplaceCatalogClient marketplaceCatalogClient = 
			MarketplaceCatalogClient.builder()
			.httpClient(ApacheHttpClient.builder().build())
			.credentialsProvider(ProfileCredentialsProvider.create())
			.build();
	
	public static void main(String[] args) {

		String offerReleaseDateAfterValue = "2023-01-01T23:59:59Z";
		String offerAvailableEndDateAfterValue = "2040-12-24T23:59:59Z";
		
		List<EntitySummary> entitySummaryList = getEntitySummaryList(offerReleaseDateAfterValue, offerAvailableEndDateAfterValue);
		
		// for each offer id, output the offer detail using DescribeEntity API
		
		
		for (EntitySummary entitySummary : entitySummaryList) {
			DescribeEntityRequest describeEntityRequest = 
					DescribeEntityRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityId(entitySummary.entityId())
					.build();
			DescribeEntityResponse describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
			ReferenceCodesUtils.formatOutput(describeEntityResponse);
		}
	}
	
	public static List<EntitySummary> getEntitySummaryList (String offerReleaseDateAfterValue, String offerAvailableEndDateAfterValue) {
		
		EntityTypeFilters entityTypeFilters = 
				EntityTypeFilters.builder()
				.offerFilters(OfferFilters.builder()
						.targeting(OfferTargetingFilter.builder()
								.valueListWithStrings(OFFER_TARGETING_BUYERACCOUNTS)
								.build())
						.buyerAccounts(OfferBuyerAccountsFilter.builder()
								.wildCardValue(BUYER_ACCOUNT_ID)
								.build())
						.availabilityEndDate(OfferAvailabilityEndDateFilter.builder()
								.dateRange(OfferAvailabilityEndDateFilterDateRange.builder()
										.afterValue(offerAvailableEndDateAfterValue).build())
								.build())
						.releaseDate(OfferReleaseDateFilter.builder()
								.dateRange(OfferReleaseDateFilterDateRange.builder()
										.afterValue(offerReleaseDateAfterValue)
										.build())
								.build())
						.build())
				.build();
			
		ListEntitiesRequest listEntitiesRequest = 
				ListEntitiesRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityType(ENTITY_TYPE_OFFER).maxResults(10)
				.entityTypeFilters(entityTypeFilters)
				.nextToken(null)
				.build();
		
		ListEntitiesResponse listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
		List<EntitySummary> entitySummaryList = new ArrayList<EntitySummary>();
		
		entitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
		
		while ( listEntitiesResponse.nextToken() != null && listEntitiesResponse.nextToken().length() > 0) {
			listEntitiesRequest = 
					ListEntitiesRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityType(ENTITY_TYPE_OFFER)
					.maxResults(10)
					.entityTypeFilters(entityTypeFilters)
					.nextToken(listEntitiesResponse.nextToken())
					.build();
			listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
			entitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
		}
		
		return entitySummaryList;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 特定の製品 ID に対してリリースされたパブリックオファーとプライベートオファーを一覧表示する
<a name="marketplace-catalog_ListProductPublicOrPrivateReleasedOffers_java_2_topic"></a>

次のコード例は、特定の製品 ID に対してリリースされたパブリックオファーとプライベートオファーを一覧表示する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
package com.example.awsmarketplace.catalogapi;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.EntitySummary;
import software.amazon.awssdk.services.marketplacecatalog.model.EntityTypeFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferProductIdFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferStateFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferTargetingFilter;

public class ListProductPublicOrPrivateReleasedOffers {

	/*
	 * List released Public/Private offers for a specific product id.
	 * Example below is to list released public offers.
	 * To change to released private offers, change OFFER_TARGETING_NONE (None) to OFFER_TARGETING_BUYERACCOUNTS(BuyerAccounts)
	 */
	public static void main(String[] args) {

		List<EntitySummary> entitySummaryList = getEntitySummaryLIst();
		ReferenceCodesUtils.formatOutput(entitySummaryList);
	}

	public static List<EntitySummary> getEntitySummaryLIst() {
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		// define list entities filters
		
		EntityTypeFilters entityTypeFilters = 
				EntityTypeFilters.builder()
				.offerFilters(OfferFilters.builder()
						.targeting(OfferTargetingFilter.builder()
								.valueListWithStrings(OFFER_TARGETING_NONE)
								.build())
						.state(OfferStateFilter.builder()
								.valueListWithStrings(OFFER_STATE_RELEASED)
								.build())
						.productId(OfferProductIdFilter.builder()
								.valueList(PRODUCT_ID)
								.build())
						.build())
				.build();
		
		ListEntitiesRequest listEntitiesRequest = 
				ListEntitiesRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityType(ENTITY_TYPE_OFFER)
				.maxResults(10)
				.entityTypeFilters(entityTypeFilters)
				.nextToken(null)
				.build();
		
		ListEntitiesResponse listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
		
		// save all entitySummary of the results into entitySummaryList
		
		List<EntitySummary> entitySummaryList = new ArrayList<EntitySummary>();
		
		entitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
		
		while ( listEntitiesResponse.nextToken() != null && listEntitiesResponse.nextToken().length() > 0) {
			listEntitiesRequest = 
					ListEntitiesRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityType(ENTITY_TYPE_OFFER)
					.maxResults(10)
					.entityTypeFilters(entityTypeFilters)
					.nextToken(listEntitiesResponse.nextToken())
					.build();
			listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
			entitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
		}
		return entitySummaryList;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### オファーを更新して従量制料金を使用する契約を適用する
<a name="marketplace-catalog_UpdateOfferWithContractAndPayAsYouGoPricing_java_2_topic"></a>

次のコード例は、オファーを更新して従量制料金を使用する契約を適用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 時間単位の年間料金を適用するようにオファーを更新する
<a name="marketplace-catalog_UpdateOfferWithHourlyAnnualPricing_java_2_topic"></a>

次のコード例は、時間単位の年間料金を適用するようにオファーを更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "m5.large",
                                        "Price": "0.13"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P365D"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "m5.large",
                                        "Price": "20.03"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 特定の地理的リージョンにターゲティングを適用するようにオファーを更新する
<a name="marketplace-catalog_UpdateOfferTargeting_java_2_topic"></a>

次のコード例は、特定の地理的リージョンにターゲティングを適用するようにオファーを更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "CountryCodes": [
                        "US",
                        "ES",
                        "FR",
                        "AU"
                    ]
                }
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックオファーの名前と説明を更新する
<a name="marketplace-catalog_UpdateOfferNameAndDescription_java_2_topic"></a>

次のコード例は、パブリックオファーの名前と説明を更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### オファーの EULA を更新する
<a name="marketplace-catalog_UpdateEula_java_2_topic"></a>

以下のコード例は、オファーの EULA を更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "Name": "New offer name",
                "Description": "New offer description"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### プライベートオファーの有効期限を将来の日付に更新する
<a name="marketplace-catalog_UpdateOfferExpirationDateOfPrivateOffer_java_2_topic"></a>

次のコード例は、プライベートオファーの有効期限を将来の日付に更新して、購入者がオファーを評価して承諾する時間を延長する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2026-01-01"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### SaaS 製品向けのパブリック無料トライアルオファーの無料トライアル期間を更新する
<a name="marketplace-catalog_UpdateFreeTrialDurationOfPublicFreeTrialOfferForSaasProduct_java_2_topic"></a>

次のコード例は、SaaS 製品向けのパブリック無料トライアルオファーの無料トライアル期間を更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "FreeTrialPricingTerm",
                        "Duration": "P21D",
                        "Grants": [
                            {
                                "DimensionKey": "WorkloadSmall"
                            },
                            {
                                "DimensionKey": "WorkloadMedium"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### オファーの返金ポリシーを更新する
<a name="marketplace-catalog_UpdateRefundPolicy_java_2_topic"></a>

次のコード例は、オファーの返金ポリシーを更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Updated refund policy description"
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

## 製品
<a name="products"></a>

### AMI、SaaS、またはコンテナ製品を記述する
<a name="marketplace-catalog_DescribeProduct_java_2_topic"></a>

次のコード例は、AMI、SaaS、またはコンテナ製品を記述し、製品について知りたい情報がすべて含まれているかどうかを確認する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
﻿// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.catalogapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;

public class DescribeEntity {

	/*
	 * Describe my AMI or SaaS or Container product and check if it contains all the information I need to know about the product
	 */
	public static void main(String[] args) {

		String offerId = args.length > 0 ? args[0] : OFFER_ID;

		DescribeEntityResponse describeEntityResponse = getDescribeEntityResponse(offerId);

		ReferenceCodesUtils.formatOutput(describeEntityResponse);
	}

	public static DescribeEntityResponse getDescribeEntityResponse(String offerId) {
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		DescribeEntityRequest describeEntityRequest = 
				DescribeEntityRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityId(offerId)
				.build();

		DescribeEntityResponse describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
		return describeEntityResponse;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeEntity](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/DescribeEntity)」を参照してください。

### すべての AMI、SaaS、またはコンテナ製品と、関連するパブリックオファーを一覧表示する
<a name="marketplace-catalog_ListProducts_java_2_topic"></a>

次のコード例は、すべての AMI、SaaS、またはコンテナ製品と、関連するパブリックオファーを一覧表示する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
package com.example.awsmarketplace.catalogapi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.EntitySummary;
import software.amazon.awssdk.services.marketplacecatalog.model.EntityTypeFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.ListEntitiesResponse;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferFilters;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferProductIdFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferStateFilter;
import software.amazon.awssdk.services.marketplacecatalog.model.OfferTargetingFilter;

public class ListEntities {

	/*
	 * List all my AMI or SaaS or Container products and associated public offers
	 */
	public static void main(String[] args) {
		
		Map<String, List<EntitySummary>> allProductsWithOffers = getAllProductsWithOffers();
	
		ReferenceCodesUtils.formatOutput(allProductsWithOffers);
	}

	public static Map<String, List<EntitySummary>> getAllProductsWithOffers() {
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		Map<String, List<EntitySummary>> allProductsWithOffers = new HashMap<String, List<EntitySummary>> ();

		// get all product entities
		List<EntitySummary> productEntityList = new ArrayList<EntitySummary>();

		ListEntitiesRequest listEntitiesRequest = 
				ListEntitiesRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityType(PRODUCT_TYPE_AMI)
				.maxResults(10)
				.nextToken(null)
				.build();
		
	 
		ListEntitiesResponse listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);

		productEntityList.addAll(listEntitiesResponse.entitySummaryList());


		while (listEntitiesResponse.nextToken() != null) {
			listEntitiesRequest = 
					ListEntitiesRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityType(PRODUCT_TYPE_AMI)
					.maxResults(10)
					.nextToken(listEntitiesResponse.nextToken())
					.build();
			listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
			productEntityList.addAll(listEntitiesResponse.entitySummaryList());
		}
		
		// loop through each product entity and get the public released offers associated using product id filter
		
		for ( EntitySummary productEntitySummary : productEntityList) {
			EntityTypeFilters entityTypeFilters = 
					EntityTypeFilters.builder()
					.offerFilters(OfferFilters.builder()
							.targeting(OfferTargetingFilter.builder()
									.valueListWithStrings(OFFER_TARGETING_NONE)
									.build())
							.state(OfferStateFilter.builder()
									.valueListWithStrings(OFFER_STATE_RELEASED)
									.build())
							.productId(OfferProductIdFilter.builder()
									.valueList(productEntitySummary.entityId())
									.build())
							.build())
					.build();
			
			listEntitiesRequest = 
					ListEntitiesRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityType(ENTITY_TYPE_OFFER)
					.maxResults(10)
					.entityTypeFilters(entityTypeFilters)
					.nextToken(null)
					.build();
			
			listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
			
			// save all entitySummary of the results into entitySummaryList
			
			List<EntitySummary> offerEntitySummaryList = new ArrayList<EntitySummary>();
			
			offerEntitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
			
			while ( listEntitiesResponse.nextToken() != null && listEntitiesResponse.nextToken().length() > 0) {
				listEntitiesRequest = 
						ListEntitiesRequest.builder()
						.catalog(AWS_MP_CATALOG)
						.entityType(ENTITY_TYPE_OFFER)
						.maxResults(10)
						.entityTypeFilters(entityTypeFilters)
						.nextToken(listEntitiesResponse.nextToken())
						.build();
				listEntitiesResponse = marketplaceCatalogClient.listEntities(listEntitiesRequest);
				offerEntitySummaryList.addAll(listEntitiesResponse.entitySummaryList());
			}
			
			// save final results into map; key = product id; value = offer entity summary list
			
			allProductsWithOffers.put(productEntitySummary.entityId(), offerEntitySummaryList);
		}
		return allProductsWithOffers;
	}

}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [DescribeEntity](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/DescribeEntity)
  + [ListEntities](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/ListEntities)

## 再販承認
<a name="resale_authorization"></a>

### ドラフト再販承認を作成する
<a name="marketplace-catalog_DraftResaleauthAllproducttype_java_2_topic"></a>

次のコード例は、チャネルパートナーに公開する前に内部で確認できるように、任意の製品タイプのドラフト再販承認を作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 再販承認を記述する
<a name="marketplace-catalog_DescribeResaleAuthorization_java_2_topic"></a>

次のコード例では、再販承認を記述する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
﻿// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.catalogapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;

public class DescribeEntity {

	/*
	 * Describe my AMI or SaaS or Container product and check if it contains all the information I need to know about the product
	 */
	public static void main(String[] args) {

		String offerId = args.length > 0 ? args[0] : OFFER_ID;

		DescribeEntityResponse describeEntityResponse = getDescribeEntityResponse(offerId);

		ReferenceCodesUtils.formatOutput(describeEntityResponse);
	}

	public static DescribeEntityResponse getDescribeEntityResponse(String offerId) {
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		DescribeEntityRequest describeEntityRequest = 
				DescribeEntityRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityId(offerId)
				.build();

		DescribeEntityResponse describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
		return describeEntityResponse;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeEntity](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/DescribeEntity)」を参照してください。

### プライベートオファーを使用して 1 回限りの再販承認を発行する
<a name="marketplace-catalog_OnetimeResaleauthPrivateoffer_java_2_topic"></a>

次のコード例は、プライベートオファーを使用して 1 回限りの再販承認を発行し、チャネルパートナーがそれを使用してチャネルパートナープライベートオファー (CPPO) を作成できるようにする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限付きの複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthExpirydateCppo_java_2_topic"></a>

次のコード例は、時間単位の年間料金を使用して AMI 製品向けに有効期限付きの複数回使用可能な再販承認を発行し、チャネルパートナーがそれを使用してチャネルパートナープライベートオファー (CPPO) を作成できるようにする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限と EULA を含む複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthExpirydateCustomEula_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けに有効期限付きの複数回使用可能な再販承認を発行し、カスタム EULA を追加して購入者に送信できるようにする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限と再販契約ドキュメントを含む複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthExpirydateCustomresellerContractdoc_java_2_topic"></a>

次のコード例は、任意の製品タイプについて、有効期限付きの複数回使用可能な再販承認を発行し、ISV とチャネルパートナー間の再販契約ドキュメントを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    },
                    {
                        "Type": "ResaleLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomResellerContract",
                                "Url": "https://s3.amazonaws.com/aws-mp-standard-contracts/Standard-Contact-for-AWS-Marketplace-2022-07-14.pdf"}
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限付きの複数回使用可能な再販承認を発行し、特定の購入者アカウントを追加する
<a name="marketplace-catalog_PublishMultiuseResaleAuthorizationExpirydateSpecificBuyer_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けに有効期限付きの複数回使用可能な再販承認を発行し、再販用に特定の購入者アカウントを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "111111111111"
                            ]
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限なしの複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthNoExpirydateCppo_java_2_topic"></a>

次のコード例は、時間単位の年間料金を含む AMI 製品について、有効期限なしの複数回使用可能な再販承認を発行する方法を示しており、CP がこれを使用して CPPO を作成できるようにします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限と EULA のない複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthNoExpirydateCustomEula_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けに有効期限のない複数回使用可能な再販承認を発行し、カスタム EULA を追加して購入者に送信できるようにする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限と再販契約ドキュメントのない複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthNoExpirydateCustomresellerContractdoc_java_2_topic"></a>

次のコード例は、任意の製品タイプについて、有効期限なしの複数回使用可能な再販承認を発行し、ISV とチャネルパートナー間の再販契約ドキュメントを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    },
                    {
                        "Type": "ResaleLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomResellerContract",
                                "Url": "https://s3.amazonaws.com/aws-mp-standard-contracts/Standard-Contact-for-AWS-Marketplace-2022-07-14.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 有効期限のない複数回使用可能な再販承認を発行し、特定の購入者アカウントを追加する
<a name="marketplace-catalog_PublishMultiuseResaleAuthorizationNoExpirydateSpecificBuyer_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けに有効期限のない複数回使用可能な再販承認を発行し、再販用に特定の購入者アカウントを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "111111111111"
                            ]
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 1 回限りの再販承認を発行し、柔軟な支払いスケジュールを追加する
<a name="marketplace-catalog_PublishOnetimeResaleAuthorizationFlexiblePayment_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けに 1 回限りの再販売承認を発行し、柔軟な支払いスケジュールを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleFixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.00",
                        "Duration": "P12M",
                        "Grants": [
                          {
                            "DimensionKey": "Users",
                            "MaxQuantity": 10
                          }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ResalePaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2023-09-01",
                                "ChargeAmount": "200.00"
                            },
                            {
                                "ChargeDate": "2023-12-01",
                                "ChargeAmount": "250.00"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-06-30",
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 1 回限りの再販売承認を発行し、EULA を追加する
<a name="marketplace-catalog_OnetimeResaleauthCustomEula_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販売認可を発行し、カスタム EULA を追加して購入者に送信できるようにする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 1 回限りの再販承認を発行し、特定の購入者アカウントを追加する
<a name="marketplace-catalog_PublishOnetimeResaleAuthorizationSpecificBuyer_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販承認を発行し、再販用に特定の購入者アカウントを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": "1"
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "111111111111"
                            ]
                        }
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 1 回限りの再販承認を発行し、リセラー契約ドキュメントを追加する
<a name="marketplace-catalog_OnetimeResaleauthCustomresellerContractdoc_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販売認可を発行し、ISV とチャネルパートナー間のリセラー契約ドキュメントを追加する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 1 回限りの再販売承認を発行し、それが更新かどうかを追加表示する
<a name="marketplace-catalog_OnetimeResaleauthRenewal_java_2_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販売認可を発行し、それが更新かどうかを追加表示する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "222222222222"
                            ]
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType":"UpdateInformation",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "PreExistingBuyerAgreement": {
                    "AcquisitionChannel": "AwsMarketplace",
                    "PricingModel": "Contract"
                }
             }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 再販承認を制限する
<a name="marketplace-catalog_RestrictResaleAuthorization_java_2_topic"></a>

次のコード例は、再販承認を制限する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "RestrictResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "resaleauthz-1111111111111"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 1 回限りまたは複数回使用可能な再販承認の名前と説明を更新する
<a name="marketplace-catalog_UpdateUnpublishedResaleAuthorization_java_2_topic"></a>

次のコード例は、任意の製品タイプについて、公開前に 1 回限りまたは複数回使用可能な再販承認の名前と説明を更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType":"UpdateInformation",
            "Entity": {
            	"Type": "ResaleAuthorization@1.0",
            	"Identifier": "resaleauthz-1111111111111"
            },
            "DetailsDocument": {
            	"Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

## SaaS 製品
<a name="saas_products"></a>

### ドラフトパブリックオファーを使用するドラフト SaaS 製品を作成する
<a name="marketplace-catalog_CreateDraftSaasProductWithDraftPublicOffer_java_2_topic"></a>

次のコード例は、ドラフトパブリックオファーを使用してドラフト SaaS 製品を作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog":"AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "DetailsDocument": {
              "ProductTitle": "Sample product"
            }
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier",
                "Name": "Test Offer"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックまたは制限付き SaaS 製品と、契約料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedSaasProductAndPublicOfferWithContractPricing_java_2_topic"></a>

次のコード例は、パブリックまたは制限付き SaaS 製品と、契約料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "ChangeName": "CreateProductChange",
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl":"https://sample.amazonaws.com/sample-saas-fulfillment-url"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Description": "Basic Service",
                    "Name": "Basic Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "PremiumService",
                    "Description": "Premium Service",
                    "Name": "Premium Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with contract pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P1M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "20"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "25"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            },
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックまたは制限付きの SaaS 製品と、従量制料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedSaasProductAndPublicOfferWithContractWithPayAsYouGoPricing_java_2_topic"></a>

次のコード例は、パブリックまたは制限付き SaaS 製品と、従量制料金の契約を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "ChangeName": "CreateProductChange",
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl":"https://sample.amazonaws.com/sample-saas-fulfillment-url"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Description": "Basic Service",
                    "Name": "Basic Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "PremiumService",
                    "Description": "Premium Service",
                    "Name": "Premium Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "WorkloadSmall",
                    "Description": "Workload: Per medium instance",
                    "Name": "Workload: Per medium instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "WorkloadMedium",
                    "Description": "Workload: Per large instance",
                    "Name": "Workload: Per large instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with contract pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### パブリックまたは制限付きの SaaS 製品と、サブスクリプション料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedSaasProductAndPublicOfferWithSubscriptionPricing_java_2_topic"></a>

次のコード例は、パブリックまたは制限付き SaaS 製品と、サブスクリプション料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "ChangeName": "CreateProductChange",
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl":"https://sample.amazonaws.com/sample-saas-fulfillment-url"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "WorkloadSmall",
                    "Description": "Workload: Per medium instance",
                    "Name": "Workload: Per medium instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "WorkloadMedium",
                    "Description": "Workload: Per large instance",
                    "Name": "Workload: Per large instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with contract pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### SaaS 製品および関連するパブリックオファーを公開する
<a name="marketplace-catalog_PublishSaasProductPublicOffer_java_2_topic"></a>

次のコード例は、SaaS 製品および関連するパブリックオファーを公開する方法を示しています。製品はデフォルトで制限付きの状態になります。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog":"AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://bucketname.s3.amazonaws.com/logo.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Description": "Basic Service",
                    "Name": "Basic Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "PremiumService",
                    "Description": "Premium Service",
                    "Name": "Premium Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl": "https://www.aws.amazon.com/marketplace/management"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "New Test Offer",
                "Description": "New offer description"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Updated refund policy description"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P1M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "20"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "25"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            },
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateRenewalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "RenewalTerm"
                    }
                ]
            }
        },
        {
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 既存のドラフトから SaaS 製品と関連するパブリックオファーを公開する
<a name="marketplace-catalog_PublishExistingSaas_java_2_topic"></a>

次のコード例は、既存のドラフトから SaaS 製品と関連するパブリックオファーを公開する方法を示しています。製品はデフォルトで制限付きの状態になります。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog":"AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateVisibility",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "TargetVisibility": "Public"
            }
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### AMI または SaaS 製品のディメンションを更新する
<a name="marketplace-catalog_UpdateNameDimensionSaasProduct_java_2_topic"></a>

次のコード例は、AMI または SaaS 製品のディメンションを更新する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
この例を実行するには、「**ユーティリティ**」セクションの「*変更セットを開始するユーティリティ*」で、次の JSON 変更セットを `RunChangesets` に渡します。  

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "prod-111111111111"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Types": [
                        "Entitled"
                    ],
                    "Name": "Some new name",
                    "Description": "Some new description"
                }
            ]
        }
    ]
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

## Utilities
<a name="utilities"></a>

### 変更セットを開始するユーティリティ
<a name="marketplace-catalog_ChangeSetUtilities_java_2_topic"></a>

次のコード例は、変更セットを開始するユーティリティを定義する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
JSON ファイルから変更セットをロードし、処理を開始するユーティリティ。  

```
package com.example.awsmarketplace.catalogapi;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.document.Document;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.protocols.json.internal.unmarshall.document.DocumentUnmarshaller;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.Change;
import software.amazon.awssdk.services.marketplacecatalog.model.Entity;
import software.amazon.awssdk.services.marketplacecatalog.model.StartChangeSetRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.StartChangeSetResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;
import com.example.awsmarketplace.catalogapi.Entity.ChangeSet;
import com.example.awsmarketplace.catalogapi.Entity.ChangeSetEntity;
import com.example.awsmarketplace.catalogapi.Entity.Root;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;
import com.example.awsmarketplace.utils.StringSerializer;

/**
 * Before running this Java V2 code example, convert all Details attribute to DetailsDocument if any
 */

public class RunChangesets {
	
	private static final Gson GSON = new GsonBuilder()
			.setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
			.registerTypeAdapter(String.class, new StringSerializer())
			.create();

	public static void main(String[] args) {

		// input json can be specified here or passed from input parameter
		String inputChangeSetFile = "changeSets/offers/CreateReplacementOfferFromAGWithContractPricingDetailDocument.json";
		
		if (args.length > 0)
			inputChangeSetFile = args[0];
		
		// parse the input changeset file to string for process
		String changeSetsInput = readChangeSetToString(inputChangeSetFile);

		// process the changeset request
		try {
			StartChangeSetResponse result = getChangeSetRequestResult(changeSetsInput);
			ReferenceCodesUtils.formatOutput(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static StartChangeSetResponse getChangeSetRequestResult(String changeSetsInput) throws IOException {
		
		//set up AWS credentials
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		//changeset list to save all the changesets in the changesets file
		List<Change> changeSetLists = new ArrayList<Change>();

		// read all changesets into object
		Root root = GSON.fromJson(changeSetsInput, Root.class);
		
		// process each changeset and add each changeset request to changesets list
		for (ChangeSet cs : root.changeSet) {
			
			ChangeSetEntity entity = cs.Entity;
			String entityType = entity.Type;
			String entityIdentifier = StringUtils.defaultIfBlank(entity.Identifier, null);
			Document detailsDocument = getDocumentFromObject(cs.DetailsDocument);
			
			Entity awsEntity = 
					Entity.builder()
					.type(entityType)
					.identifier(entityIdentifier)
					.build();

			Change inputChangeRequest = 
					Change.builder()
					.changeType(cs.ChangeType)
					.changeName(cs.ChangeName)
					.entity(awsEntity)
					.detailsDocument(detailsDocument)
					.build();
			
			changeSetLists.add(inputChangeRequest);
		}
		
		// process all changeset requests
		StartChangeSetRequest startChangeSetRequest = 
				StartChangeSetRequest.builder()
				.catalog(root.catalog)
				.changeSet(changeSetLists)
				.build();

		StartChangeSetResponse result = marketplaceCatalogClient.startChangeSet(startChangeSetRequest);

		return result;
	}

	public static Document getDocumentFromObject(Object detailsObject) {
		
		String detailsString = "{}";
		try {
			detailsString = IOUtils.toString(new ByteArrayInputStream(GSON.toJson(detailsObject).getBytes()), "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		JsonNodeParser jsonNodeParser = JsonNodeParser.create();
		Document doc = jsonNodeParser.parse(detailsString).visit(new DocumentUnmarshaller());
		return doc;
	}
	
	
	public static String readChangeSetToString (String inputChangeSetFile) {
		
		InputStream changesetInputStream = RunChangesets.class.getClassLoader().getResourceAsStream(inputChangeSetFile);

		String changeSetsInput = null;
		
		try {
			changeSetsInput = IOUtils.toString(changesetInputStream, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return changeSetsInput;
		
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartChangeSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

# AWS Marketplace SDK for Java 2.x を使用した契約 API の例
<a name="java_2_marketplace-agreement_code_examples"></a>

次のコード例は、 AWS Marketplace Agreement API AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [契約](#agreements)

## 契約
<a name="agreements"></a>

### すべての契約 ID を取得する
<a name="marketplace-agreement_GetAllAgreementsIds_java_2_topic"></a>

次のコード例は、すべての契約 ID を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AgreementViewSummary;
import software.amazon.awssdk.services.marketplaceagreement.model.Filter;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAllAgreementsIds {

	/*
	 * Get all purchase agreements ids with party type = proposer; 
	 * Depend on the number of agreements in your account, this code may take some time to finish.
	 */
	public static void main(String[] args) {

		List<String> agreementIds = getAllAgreementIds();
		
		ReferenceCodesUtils.formatOutput(agreementIds);

	}

	public static List<String> getAllAgreementIds() {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		// get all filters
		Filter partyType = Filter.builder().name(PARTY_TYPE_FILTER_NAME)
				.values(PARTY_TYPE_FILTER_VALUE_PROPOSER).build();

		Filter agreementType = Filter.builder().name(AGREEMENT_TYPE_FILTER_NAME)
				.values(AGREEMENT_TYPE_FILTER_VALUE_PURCHASEAGREEMENT).build();
		
		List<Filter> searchFilters = new ArrayList<Filter>();
		
		searchFilters.addAll(Arrays.asList(partyType, agreementType));
		
		// Save all results in a list array
		List<AgreementViewSummary> agreementSummaryList = new ArrayList<AgreementViewSummary>();

		SearchAgreementsRequest searchAgreementsRequest = 
				SearchAgreementsRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.filters(searchFilters)
				.build();
		
		SearchAgreementsResponse searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);

		agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());

		while (searchAgreementsResponse.nextToken() != null && searchAgreementsResponse.nextToken().length() > 0) {
			searchAgreementsRequest = 
					SearchAgreementsRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.nextToken(searchAgreementsResponse.nextToken())
					.filters(searchFilters)
					.build();
			searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
			agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());
		}

		List<String> agreementIds = new ArrayList<String>();
		for (AgreementViewSummary summary : agreementSummaryList) {
			agreementIds.add(summary.agreementId());
		}
		return agreementIds;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SearchAgreements](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。

### すべての契約を取得する
<a name="marketplace-agreement_GetAllAgreements_java_2_topic"></a>

次のコード例は、すべての契約を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AgreementViewSummary;
import software.amazon.awssdk.services.marketplaceagreement.model.Filter;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;

import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAllAgreements {

	/*
	 * Get all purchase agreements with party type = proposer; 
	 * Depend on the number of agreements in your account, this code may take some time to finish.
	 */
	public static void main(String[] args) {

		List<AgreementViewSummary> agreementSummaryList = getAllAgreements();

		ReferenceCodesUtils.formatOutput(agreementSummaryList);
	}

	public static List<AgreementViewSummary> getAllAgreements() {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		// get all filters
		
		Filter partyType = Filter.builder().name(PARTY_TYPE_FILTER_NAME)
				.values(PARTY_TYPE_FILTER_VALUE_PROPOSER).build();

		Filter agreementType = Filter.builder().name(AGREEMENT_TYPE_FILTER_NAME)
				.values(AGREEMENT_TYPE_FILTER_VALUE_PURCHASEAGREEMENT).build();
		
		List<Filter> searchFilters = new ArrayList<Filter>();
		
		searchFilters.addAll(Arrays.asList(partyType, agreementType));
		
		// Save all results in a list array

		List<AgreementViewSummary> agreementSummaryList = new ArrayList<AgreementViewSummary>();

		SearchAgreementsRequest searchAgreementsRequest = 
				SearchAgreementsRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.filters(searchFilters)
				.build();
		
		SearchAgreementsResponse searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);

		agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());

		while (searchAgreementsResponse.nextToken() != null && searchAgreementsResponse.nextToken().length() > 0) {
			searchAgreementsRequest = 
					SearchAgreementsRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.nextToken(searchAgreementsResponse.nextToken())
					.filters(searchFilters).build();
			searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
			agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());
		}
		return agreementSummaryList;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SearchAgreements](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。

### 契約から顧客 ID を取得する
<a name="marketplace-agreement_GetAgreementCustomer_java_2_topic"></a>

次のコード例は、契約から顧客 ID を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementResponse;

public class GetAgreementCustomerInfo {

	/*
	 * Obtain metadata about the customer who created the agreement, such as the customer's AWS Account ID
	 */
	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		DescribeAgreementResponse describeAgreementResponse = getDescribeAgreementResponse(agreementId);

		System.out.println("Customer's AWS Account ID is " + describeAgreementResponse.acceptor().accountId());

	}

	public static DescribeAgreementResponse getDescribeAgreementResponse(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		DescribeAgreementRequest describeAgreementRequest = 
				DescribeAgreementRequest.builder()
				.agreementId(agreementId)
				.build();

		DescribeAgreementResponse describeAgreementResponse = marketplaceAgreementClient.describeAgreement(describeAgreementRequest);
		return describeAgreementResponse;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約から財務情報を取得する
<a name="marketplace-agreement_GetAgreementFinancialDetails_java_2_topic"></a>

次のコード例は、契約から財務情報を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementResponse;

public class GetAgreementFinancialDetails {

	/*
	 * Obtain financial details, such as Total Contract Value of the agreement from a given agreement
	 */
	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		String totalContractValue = getTotalContractValue(agreementId);

		System.out.println("Total Contract Value is " + totalContractValue);

	}

	public static String getTotalContractValue(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		DescribeAgreementRequest describeAgreementRequest = 
				DescribeAgreementRequest.builder()
				.agreementId(agreementId)
				.build();

		DescribeAgreementResponse describeAgreementResponse = marketplaceAgreementClient.describeAgreement(describeAgreementRequest);
		
		String totalContractValue = "N/A";

		if ( describeAgreementResponse.estimatedCharges() != null ) {
			totalContractValue = describeAgreementResponse.estimatedCharges().agreementValue() 
					+ " " 
					+ describeAgreementResponse.estimatedCharges().currencyCode();
		}
		return totalContractValue;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約から無料トライアルの詳細を取得する
<a name="marketplace-agreement_GetAgreementTermsFreeTrialDetails_java_2_topic"></a>

次のコード例は、契約から無料トライアルの詳細を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.FreeTrialPricingTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.AGREEMENT_ID;

import java.util.ArrayList;
import java.util.List;

import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementTermsFreeTrialDetails {

	/*
	 * Obtain the details from an agreement of a free trial I have provided to the customer
	 */
	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;
		
		List<FreeTrialPricingTerm> freeTrialPricingTerms = getFreeTrialPricingTerms(agreementId);

		ReferenceCodesUtils.formatOutput(freeTrialPricingTerms);
	}

	public static List<FreeTrialPricingTerm> getFreeTrialPricingTerms(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder().agreementId(agreementId)
					.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);

		List<FreeTrialPricingTerm> freeTrialPricingTerms = new ArrayList<FreeTrialPricingTerm>();

		for (AcceptedTerm acceptedTerm : getAgreementTermsResponse.acceptedTerms()) {
			if (acceptedTerm.freeTrialPricingTerm() != null) {
				freeTrialPricingTerms.add(acceptedTerm.freeTrialPricingTerm());
			}
		}
		return freeTrialPricingTerms;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約に関する情報を取得する
<a name="marketplace-agreement_DescribeAgreement_java_2_topic"></a>

次のコード例は、契約に関する情報を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementResponse;

public class DescribeAgreement {

	public static void main(String[] args) {
		
		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		DescribeAgreementResponse describeAgreementResponse = getResponse(agreementId);

		ReferenceCodesUtils.formatOutput(describeAgreementResponse);

	}

	public static DescribeAgreementResponse getResponse(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		DescribeAgreementRequest describeAgreementRequest = 
				DescribeAgreementRequest.builder()
				.agreementId(agreementId)
				.build();

		DescribeAgreementResponse describeAgreementResponse = marketplaceAgreementClient.describeAgreement(describeAgreementRequest);
		return describeAgreementResponse;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約から製品とオファーの詳細を取得する
<a name="marketplace-agreement_GetProductAndOfferDetailFromAgreement_java_2_topic"></a>

次のコード例は、契約から製品とオファーの詳細を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementResponse;
import software.amazon.awssdk.services.marketplaceagreement.model.Resource;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;

public class GetProductAndOfferDetailFromAgreement {

	public static void main(String[] args) {

		// call Agreement API to get offer and product information for the agreement
		
		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;
		
		List<DescribeEntityResponse> entityResponseList = getEntities(agreementId);

		for (DescribeEntityResponse response : entityResponseList) {
			ReferenceCodesUtils.formatOutput(response);
		}
	}

	public static List<DescribeEntityResponse> getEntities(String agreementId) {
		List<DescribeEntityResponse> entityResponseList = new ArrayList<DescribeEntityResponse> ();
		
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		DescribeAgreementRequest describeAgreementRequest = 
				DescribeAgreementRequest.builder()
				.agreementId(agreementId)
				.build();

		DescribeAgreementResponse describeAgreementResponse = marketplaceAgreementClient.describeAgreement(describeAgreementRequest);

		// get offer id for the given agreement

		String offerId = describeAgreementResponse.proposalSummary().offerId();

		// get all the product ids for this agreement
		
		List<String> productIds = new ArrayList<String>();
		for (Resource resource : describeAgreementResponse.proposalSummary().resources()) {
			productIds.add(resource.id());
		}

		// call Catalog API to get the details of the offer and products
		
		MarketplaceCatalogClient marketplaceCatalogClient = 
				MarketplaceCatalogClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		DescribeEntityRequest describeEntityRequest = 
				DescribeEntityRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityId(offerId).build();

		DescribeEntityResponse describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
		
		entityResponseList.add(describeEntityResponse);

		for (String productId : productIds) {
			describeEntityRequest = 
					DescribeEntityRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.entityId(productId).build();
			describeEntityResponse = marketplaceCatalogClient.describeEntity(describeEntityRequest);
			System.out.println("Print details for product " + productId);
			entityResponseList.add(describeEntityResponse);
		}
		return entityResponseList;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約の EULA を取得する
<a name="marketplace-agreement_GetAgreementTermsEula_java_2_topic"></a>

次のコード例は、契約の EULA を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.DocumentItem;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.AGREEMENT_ID;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementTermsEula {

	/*
	 * Obtain the EULA I have entered into with my customer via the agreement
	 */
	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		List<DocumentItem> legalEulaArray = getLegalEula(agreementId);
		
		ReferenceCodesUtils.formatOutput(legalEulaArray);
	}

	public static List<DocumentItem> getLegalEula(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder().agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);

		List<DocumentItem> legalEulaArray = new ArrayList<>();

		getAgreementTermsResponse.acceptedTerms().stream()
	    	.filter(acceptedTerm -> acceptedTerm.legalTerm() != null && acceptedTerm.legalTerm().hasDocuments())
	    	.flatMap(acceptedTerm -> acceptedTerm.legalTerm().documents().stream())
	    	.filter(docItem -> docItem.type() != null)
	    	.forEach(legalEulaArray::add);
		return legalEulaArray;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 契約の自動更新条件を取得する
<a name="marketplace-agreement_GetAgreementAutoRenewal_java_2_topic"></a>

次のコード例は、契約の自動更新条件を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;

public class GetAgreementAutoRenewal {

	/*
	 * Obtain the auto-renewal status of the agreement
	 */
	
	public static void main(String[] args) {
		
		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;
		
		String autoRenewal = getAutoRenewal(agreementId);

		System.out.println("Auto-Renewal status is " + autoRenewal);
	}

	public static String getAutoRenewal(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder()
				.agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);

		String autoRenewal = "No Auto Renewal";

		for (AcceptedTerm acceptedTerm : getAgreementTermsResponse.acceptedTerms()) {
			if (acceptedTerm.renewalTerm() != null && acceptedTerm.renewalTerm().configuration() != null
					&& acceptedTerm.renewalTerm().configuration().enableAutoRenew() != null) {
				autoRenewal = String.valueOf(acceptedTerm.renewalTerm().configuration().enableAutoRenew().booleanValue());
				break;
			}
		}
		return autoRenewal;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 契約の購入済みディメンションを取得する
<a name="marketplace-agreement_GetAgreementTermsDimensionPurchased_java_2_topic"></a>

次のコード例は、契約の購入済みディメンションを取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.Dimension;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.AGREEMENT_ID;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementTermsDimensionPurchased {

	/*
	 * Obtain the dimensions the buyer has purchased from me via the agreement
	 */
	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		List<String> dimensionKeys = getDimensionKeys(agreementId);

		ReferenceCodesUtils.formatOutput(dimensionKeys);
	}

	public static List<String> getDimensionKeys(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder().agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);

		List<String> dimensionKeys = new ArrayList<String>();
		for (AcceptedTerm acceptedTerm : getAgreementTermsResponse.acceptedTerms()) {
			if (acceptedTerm.configurableUpfrontPricingTerm() != null) {
				if (acceptedTerm.configurableUpfrontPricingTerm().configuration().selectorValue() != null) {
					List<Dimension> dimensions = acceptedTerm.configurableUpfrontPricingTerm().configuration().dimensions();
					for (Dimension dimension : dimensions) {
						dimensionKeys.add(dimension.dimensionKey());
					}
				}

			}
		}
		return dimensionKeys;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 契約の購入済み各ディメンションのインスタンスを取得する
<a name="marketplace-agreement_GetAgreementTermsDimensionInstances_java_2_topic"></a>

次のコード例は、契約の購入済み各ディメンションのインスタンスを取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.Dimension;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.AGREEMENT_ID;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementTermsDimensionInstances {

	/* 
	 * get instances of each dimension that buyer has purchased in the agreement
	 */
	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		Map<String, List<Dimension>> dimensionMap = getDimensions(agreementId);

		ReferenceCodesUtils.formatOutput(dimensionMap);
	}

	public static Map<String, List<Dimension>> getDimensions(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder().agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);

		Map<String, List<Dimension>> dimensionMap = new HashMap<String, List<Dimension>>();

		for (AcceptedTerm acceptedTerm : getAgreementTermsResponse.acceptedTerms()) {
			List<Dimension> dimensionsList = new ArrayList<Dimension>();
			if (acceptedTerm.configurableUpfrontPricingTerm() != null) {
				String selectorValue = "";
				if (acceptedTerm.configurableUpfrontPricingTerm().configuration() != null) {
					if (acceptedTerm.configurableUpfrontPricingTerm().configuration().selectorValue() != null) {
						selectorValue = acceptedTerm.configurableUpfrontPricingTerm().configuration().selectorValue();
					}
					if (acceptedTerm.configurableUpfrontPricingTerm().configuration().hasDimensions()) {
						dimensionsList = acceptedTerm.configurableUpfrontPricingTerm().configuration().dimensions();
					}
				}
				if (selectorValue.length() > 0) {
					dimensionMap.put(selectorValue, dimensionsList);
				}
			}
		}
		return dimensionMap;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 契約の支払いスケジュールを取得する
<a name="marketplace-agreement_GetAgreementTermsPaymentSchedule_java_2_topic"></a>

次のコード例は、契約の支払いスケジュールを取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;
import software.amazon.awssdk.services.marketplaceagreement.model.PaymentScheduleTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.ScheduleItem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementTermsPaymentSchedule {

	/*
	 * Obtain the payment schedule I have agreed to with the agreement, including the invoice date and invoice amount
	 */
	public static void main(String[] args) {
		
		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		List<Map<String, Object>> paymentScheduleArray = getPaymentSchedules(agreementId);

		ReferenceCodesUtils.formatOutput(paymentScheduleArray);
	}

	public static List<Map<String, Object>> getPaymentSchedules(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder().agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);
		List<Map<String, Object>> paymentScheduleArray = new ArrayList<>();

		String currencyCode = "";

		for (AcceptedTerm acceptedTerm : getAgreementTermsResponse.acceptedTerms()) {
			if (acceptedTerm.paymentScheduleTerm() != null) {
				PaymentScheduleTerm paymentScheduleTerm = acceptedTerm.paymentScheduleTerm();
				if (paymentScheduleTerm.currencyCode() != null) {
					currencyCode = paymentScheduleTerm.currencyCode();
				}
				if (paymentScheduleTerm.hasSchedule()) {
					for (ScheduleItem schedule : paymentScheduleTerm.schedule()) {
						if (schedule.chargeDate() != null) {
							String chargeDate = schedule.chargeDate().toString();
							String chargeAmount = schedule.chargeAmount();
							Map<String, Object> scheduleMap = new HashMap<>();
							scheduleMap.put(ATTRIBUTE_CURRENCY_CODE, currencyCode);
							scheduleMap.put(ATTRIBUTE_CHARGE_DATE, chargeDate);
							scheduleMap.put(ATTRIBUTE_CHARGE_AMOUNT, chargeAmount);
							paymentScheduleArray.add(scheduleMap);
						}
					}
				}
			}
		}
		return paymentScheduleArray;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 契約のディメンションあたりの料金を取得する
<a name="marketplace-agreement_GetAgreementTermsPricingEachDimension_java_2_topic"></a>

次のコード例は、契約のディメンションあたりの料金を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.AGREEMENT_ID;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementTermsPricingEachDimension {

	/*
	 * Obtain pricing per each dimension in the agreement
	 */
	public static void main(String[] args) {
		
		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		List<Object> dimensions = getDimensions(agreementId);

		ReferenceCodesUtils.formatOutput(dimensions);
	}

	public static List<Object> getDimensions(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder().agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);

		List<Object> dimensions = new ArrayList<Object>();

		for (AcceptedTerm acceptedTerm : getAgreementTermsResponse.acceptedTerms()) {
			List<Object> rateInfo = new ArrayList<Object>();
			if (acceptedTerm.configurableUpfrontPricingTerm() != null) {
				if (acceptedTerm.configurableUpfrontPricingTerm().type() != null) {
					rateInfo.add(acceptedTerm.configurableUpfrontPricingTerm().type());
				}
				if (acceptedTerm.configurableUpfrontPricingTerm().currencyCode() != null) {
					rateInfo.add(acceptedTerm.configurableUpfrontPricingTerm().currencyCode());
				}
				if (acceptedTerm.configurableUpfrontPricingTerm().hasRateCards()) {
					rateInfo.add(acceptedTerm.configurableUpfrontPricingTerm().rateCards());
				}
				dimensions.add(rateInfo);
			}
		}
		return dimensions;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 契約の料金タイプを取得する
<a name="marketplace-agreement_GetAgreementPricingType_java_2_topic"></a>

次のコード例は、契約の料金タイプを取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.AgreementViewSummary;
import software.amazon.awssdk.services.marketplaceagreement.model.Filter;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsResponse;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import org.apache.commons.lang3.tuple.Triple;

import software.amazon.awssdk.services.marketplacecatalog.MarketplaceCatalogClient;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityRequest;
import software.amazon.awssdk.services.marketplacecatalog.model.DescribeEntityResponse;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

/*
 * Obtain the pricing type of the agreement (contract, FPS, metered, free etc.)
 */
public class GetAgreementPricingType {

	private static final String FILTER_NAME = "OfferId";

	private static final String FILTER_VALUE = OFFER_ID;
	
	// Product types
	private static final String SAAS_PRODUCT = "SaaSProduct";
	private static final String AMI_PRODUCT = "AmiProduct";
	private static final String ML_PRODUCT = "MachineLearningProduct";
	private static final String CONTAINER_PRODUCT = "ContainerProduct";
	private static final String DATA_PRODUCT = "DataProduct";
	private static final String PROSERVICE_PRODUCT = "ProfessionalServicesProduct";
	private static final String AIQ_PRODUCT = "AiqProduct";

	// Pricing types
	private static final String CCP = "CCP";
	private static final String ANNUAL = "Annual";
	private static final String CONTRACT = "Contract";
	private static final String SFT = "SaaS Free Trial";
	private static final String HMA = "Hourly and Monthly Agreements";
	private static final String HOURLY = "Hourly";
	private static final String MONTHLY = "Monthly";
	private static final String AFPS = "Annual FPS";
	private static final String CFPS = "Contract FPS";
	private static final String CCPFPS = "CCP with FPS";
	private static final String BYOL = "BYOL";
	private static final String FREE = "Free";
	private static final String FTH = "Free Trials and Hourly";

	// Agreement term pricing types
	private static final Set<String> LEGAL = Set.of("LegalTerm");
	private static final Set<String> CONFIGURABLE_UPFRONT = Set.of("ConfigurableUpfrontPricingTerm");
	private static final Set<String> USAGE_BASED = Set.of("UsageBasedPricingTerm");
	private static final Set<String> CONFIGURABLE_UPFRONT_AND_USAGE_BASED = Set.of("ConfigurableUpfrontPricingTerm", "UsageBasedPricingTerm");
	private static final Set<String> FREE_TRIAL = Set.of("FreeTrialPricingTerm");
	private static final Set<String> RECURRING_PAYMENT = Set.of("RecurringPaymentTerm");
	private static final Set<String> USAGE_BASED_AND_RECURRING_PAYMENT = Set.of("UsageBasedPricingTerm", "RecurringPaymentTerm");
	private static final Set<String> FIXED_UPFRONT_AND_PAYMENT_SCHEDULE = Set.of("FixedUpfrontPricingTerm", "PaymentScheduleTerm");
	private static final Set<String> FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED = Set.of("FixedUpfrontPricingTerm", "PaymentScheduleTerm", "UsageBasedPricingTerm");
	private static final Set<String> BYOL_PRICING = Set.of("ByolPricingTerm");
	private static final Set<String> FREE_TRIAL_AND_USAGE_BASED = Set.of("FreeTrialPricingTerm", "UsageBasedPricingTerm");

	private static final List<Set<String>> ALL_AGREEMENT_TERM_TYPES_COMBINATION = Arrays.asList(LEGAL, CONFIGURABLE_UPFRONT, USAGE_BASED, CONFIGURABLE_UPFRONT_AND_USAGE_BASED,
			FREE_TRIAL, RECURRING_PAYMENT, USAGE_BASED_AND_RECURRING_PAYMENT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED, BYOL_PRICING, FREE_TRIAL_AND_USAGE_BASED);
	
	private static  MarketplaceAgreementClient marketplaceAgreementClient = 
			MarketplaceAgreementClient.builder()
			.httpClient(ApacheHttpClient.builder().build())
			.credentialsProvider(ProfileCredentialsProvider.create())
			.build();

	private static MarketplaceCatalogClient marketplaceCatalogClient = 
			MarketplaceCatalogClient.builder()
			.httpClient(ApacheHttpClient.builder().build())
			.credentialsProvider(ProfileCredentialsProvider.create())
			.build();

    /*
     * Get agreement Pricing Type given product type, agreement term types and offer types if needed
     */
	public static String getPricingType(String productType, Set<String> agreementTermType, Set<String> offerType) {
		Map<Triple<String, Set<String>, Set<String>>, String> pricingTypes = new HashMap<>();

		pricingTypes.put(Triple.of(SAAS_PRODUCT, CONFIGURABLE_UPFRONT_AND_USAGE_BASED, new HashSet<>()), CCP);
		pricingTypes.put(Triple.of(DATA_PRODUCT, CONFIGURABLE_UPFRONT_AND_USAGE_BASED, new HashSet<>()), CCP);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, CONFIGURABLE_UPFRONT, CONFIGURABLE_UPFRONT_AND_USAGE_BASED), ANNUAL);
		pricingTypes.put(Triple.of(AMI_PRODUCT, CONFIGURABLE_UPFRONT, CONFIGURABLE_UPFRONT_AND_USAGE_BASED), ANNUAL);
		pricingTypes.put(Triple.of(ML_PRODUCT, CONFIGURABLE_UPFRONT, CONFIGURABLE_UPFRONT_AND_USAGE_BASED), ANNUAL);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, CONFIGURABLE_UPFRONT, CONFIGURABLE_UPFRONT), CONTRACT);
		pricingTypes.put(Triple.of(AMI_PRODUCT, CONFIGURABLE_UPFRONT, CONFIGURABLE_UPFRONT), CONTRACT);
		pricingTypes.put(Triple.of(SAAS_PRODUCT, CONFIGURABLE_UPFRONT, new HashSet<>()), CONTRACT);
		pricingTypes.put(Triple.of(DATA_PRODUCT, CONFIGURABLE_UPFRONT, new HashSet<>()), CONTRACT);
		pricingTypes.put(Triple.of(AIQ_PRODUCT, CONFIGURABLE_UPFRONT, new HashSet<>()), CONTRACT);
		pricingTypes.put(Triple.of(PROSERVICE_PRODUCT, CONFIGURABLE_UPFRONT, new HashSet<>()), CONTRACT);
		pricingTypes.put(Triple.of(SAAS_PRODUCT, FREE_TRIAL, new HashSet<>()), SFT);
		pricingTypes.put(Triple.of(AMI_PRODUCT, USAGE_BASED_AND_RECURRING_PAYMENT, new HashSet<>()), HMA);
		pricingTypes.put(Triple.of(SAAS_PRODUCT, USAGE_BASED, new HashSet<>()), HOURLY);
		pricingTypes.put(Triple.of(AMI_PRODUCT, USAGE_BASED, new HashSet<>()), HOURLY);
		pricingTypes.put(Triple.of(ML_PRODUCT, USAGE_BASED, new HashSet<>()), HOURLY);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, RECURRING_PAYMENT, new HashSet<>()), MONTHLY);
		pricingTypes.put(Triple.of(AMI_PRODUCT, RECURRING_PAYMENT, new HashSet<>()), MONTHLY);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED), AFPS);
		pricingTypes.put(Triple.of(AMI_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED), AFPS);
		pricingTypes.put(Triple.of(ML_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, new HashSet<>()), AFPS);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, new HashSet<>()), CFPS);
		pricingTypes.put(Triple.of(AMI_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE), CFPS);
		pricingTypes.put(Triple.of(SAAS_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, new HashSet<>()), CFPS);
		pricingTypes.put(Triple.of(DATA_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, new HashSet<>()), CFPS);
		pricingTypes.put(Triple.of(AIQ_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, new HashSet<>()), CFPS);
		pricingTypes.put(Triple.of(PROSERVICE_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE, new HashSet<>()), CFPS);
		pricingTypes.put(Triple.of(SAAS_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED, new HashSet<>()), CCPFPS);
		pricingTypes.put(Triple.of(DATA_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED, new HashSet<>()), CCPFPS);
		pricingTypes.put(Triple.of(AIQ_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED, new HashSet<>()), CCPFPS);
		pricingTypes.put(Triple.of(PROSERVICE_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE_AND_USAGE_BASED, new HashSet<>()), CCPFPS);
		pricingTypes.put(Triple.of(AMI_PRODUCT, BYOL_PRICING, new HashSet<>()), BYOL);
		pricingTypes.put(Triple.of(SAAS_PRODUCT, BYOL_PRICING, new HashSet<>()), BYOL);
		pricingTypes.put(Triple.of(PROSERVICE_PRODUCT, BYOL_PRICING, new HashSet<>()), BYOL);
		pricingTypes.put(Triple.of(AIQ_PRODUCT, BYOL_PRICING, new HashSet<>()), BYOL);
		pricingTypes.put(Triple.of(ML_PRODUCT, BYOL_PRICING, new HashSet<>()), BYOL);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, BYOL_PRICING, new HashSet<>()), BYOL);
		pricingTypes.put(Triple.of(DATA_PRODUCT, BYOL_PRICING, new HashSet<>()), BYOL);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, LEGAL, new HashSet<>()), FREE);
		pricingTypes.put(Triple.of(AMI_PRODUCT, FREE_TRIAL_AND_USAGE_BASED, new HashSet<>()), FTH);
		pricingTypes.put(Triple.of(CONTAINER_PRODUCT, FREE_TRIAL_AND_USAGE_BASED, new HashSet<>()), FTH);
		pricingTypes.put(Triple.of(ML_PRODUCT, FREE_TRIAL_AND_USAGE_BASED, new HashSet<>()), FTH);

		Triple<String, Set<String>, Set<String>> key = Triple.of(productType, agreementTermType, offerType);

		if (pricingTypes.containsKey(key)) {
			return pricingTypes.get(key);
		} else {
			return "Unknown";
		}
	}

	/*
	 * Given product type and agreement term types, some combinations need to check offer term types as well.
	 */
	public static String needToCheckOfferTermsType(String productType, Set<String> agreementTermTypes) {
		Map<KeyPair, String> offerTermTypes = new HashMap<>();
		offerTermTypes.put(new KeyPair(CONTAINER_PRODUCT, CONFIGURABLE_UPFRONT), "Y");
		offerTermTypes.put(new KeyPair(AMI_PRODUCT, CONFIGURABLE_UPFRONT), "Y");
		offerTermTypes.put(new KeyPair(CONTAINER_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE), "Y");
		offerTermTypes.put(new KeyPair(AMI_PRODUCT, FIXED_UPFRONT_AND_PAYMENT_SCHEDULE), "Y");

		KeyPair key = new KeyPair(productType, agreementTermTypes);
		if (offerTermTypes.containsKey(key)) {
			return offerTermTypes.get(key);
		} else {
			return null;
		}
	}

	public static List<AgreementViewSummary> getAgreementsById() {
		
		List<AgreementViewSummary> agreementSummaryList = new ArrayList<AgreementViewSummary>();

		Filter partyType = Filter.builder().name(PARTY_TYPE_FILTER_NAME).values(PARTY_TYPE_FILTER_VALUE_PROPOSER).build();

		Filter agreementType = Filter.builder().name(AGREEMENT_TYPE_FILTER_NAME).values(AGREEMENT_TYPE_FILTER_VALUE_PURCHASEAGREEMENT).build();

		Filter customizeFilter = Filter.builder().name(FILTER_NAME).values(FILTER_VALUE).build();

		SearchAgreementsRequest searchAgreementsRequest = 
				SearchAgreementsRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.filters(partyType, agreementType, customizeFilter).build();

		SearchAgreementsResponse searchResultResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);

		agreementSummaryList.addAll(searchResultResponse.agreementViewSummaries());

		while (searchResultResponse.nextToken() != null && searchResultResponse.nextToken().length() > 0) {
			searchAgreementsRequest = SearchAgreementsRequest.builder().catalog(AWS_MP_CATALOG)
					.filters(partyType, agreementType).nextToken(searchResultResponse.nextToken()).build();
			searchResultResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
			agreementSummaryList.addAll(searchResultResponse.agreementViewSummaries());
		}
		return agreementSummaryList;

	}

	static class KeyPair {
		private final String first;
		private final Set<String> second;

		public KeyPair(String productType, Set<String> second) {
			this.first = productType;
			this.second = second;
		}

		@Override
		public int hashCode() {
			return Objects.hash(first, second);
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null || getClass() != obj.getClass())
				return false;
			KeyPair other = (KeyPair) obj;
			return Objects.equals(first, other.first) && Objects.equals(second, other.second);
		}
	}

	/*
	 * Get all the term types for the offer
	 */
	public static Set<String> getOfferTermTypes(String offerId) {

		Set<String> offerTermTypes = new HashSet<String>();

		DescribeEntityRequest request = 
				DescribeEntityRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.entityId(offerId)
				.build();

		DescribeEntityResponse result = marketplaceCatalogClient.describeEntity(request);

		String details = result.details();
		
		try {
			ObjectMapper objectMapper = new ObjectMapper();
			JsonNode rootNode = objectMapper.readTree(details);
			JsonNode termsNode = rootNode.get(ATTRIBUTE_TERMS);

			for (JsonNode termNode : termsNode) {
				if (termNode.get(ATTRIBUTE_TYPE_ENTITY) != null ) {
					offerTermTypes.add(termNode.get(ATTRIBUTE_TYPE_ENTITY).asText());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return offerTermTypes;

	}

	/*
	 * Get all the agreement term types
	 */
	public static Set<String> getAgreementTermTypes(GetAgreementTermsResponse agreementTerm) {
		Set<String> agreementTermTypes = new HashSet<String>();
		try {
			for (AcceptedTerm term : agreementTerm.acceptedTerms()) {
				ObjectMapper objectMapper = new ObjectMapper();
				JsonNode termNode = objectMapper.readTree(getJson(term));
				Iterator<Map.Entry<String, JsonNode>> fieldsIterator = termNode.fields();
				while (fieldsIterator.hasNext()) {
					Map.Entry<String, JsonNode> entry = fieldsIterator.next();
					JsonNode value = entry.getValue();
					if (value.isObject() && value.has(ATTRIBUTE_TYPE_AGREEMENT)) {
						agreementTermTypes.add(value.get(ATTRIBUTE_TYPE_AGREEMENT).asText());
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return agreementTermTypes;

	}

	/*
	 * make sure all elements in array2 exist in array1
	 */
	public static boolean allElementsExist(Set<String> array1, Set<String> array2) {
		for (String element : array2) {
			boolean found = false;
			for (String str : array1) {
				if (element.equals(str)) {
					found = true;
					break;
				}
			}
			if (!found) {
				return false;
			}
		}
		return true;
	}

	/*
	 * Find the combinations of the agreement term types for the agreement
	 */
	public static Set<String> getMatchedTermTypesCombination(Set<String> agreementTermTypes) {
		Set<String> matchedCombination = new HashSet<String>();
		for (Set<String> element : ALL_AGREEMENT_TERM_TYPES_COMBINATION) {
			if (allElementsExist(agreementTermTypes, element)) {
				matchedCombination = element;
			}
		}
		return matchedCombination;
	}

	public static void main(String[] args) {

		List<AgreementViewSummary> agreements = getAgreementsById();

		for (AgreementViewSummary summary : agreements) {
			String pricingType = "";
			String agreementId = summary.agreementId();
			System.out.println(agreementId);
			String offerId = summary.proposalSummary().offerId();
			
			//get all pricing term types for the offer in the agreement
			Set<String> offerTermTypes = getOfferTermTypes(offerId);
			String productType = summary.proposalSummary().resources().get(0).type();
			
			//get all pricing term types for the agreement
			GetAgreementTermsRequest getAgreementTermsRequest = 
					GetAgreementTermsRequest.builder().agreementId(agreementId)
					.build();
			GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);
			Set<String> agreementTermTypes = getAgreementTermTypes(getAgreementTermsResponse);
			
			//get matched pricing term type combination set
			Set<String> agreementMatchedTermType = getMatchedTermTypesCombination(agreementTermTypes);
			
			//check to see if this agreement pricing term combination needs additional check on offer pricing terms
			String needToCheckOfferType = needToCheckOfferTermsType(productType, agreementMatchedTermType);
			
			// get the pricing type for the agreement based on the product type, agreement term types and offer term types if needed
			if (needToCheckOfferType != null) {
				Set<String> offerMatchedTermType = getMatchedTermTypesCombination(offerTermTypes);
				pricingType = getPricingType(productType, agreementMatchedTermType, offerMatchedTermType);
			} else if (agreementMatchedTermType == LEGAL) {
				pricingType = FREE;
			} else {
				pricingType = getPricingType(productType, agreementMatchedTermType, new HashSet());
			}
			System.out.println("Pricing type is " + pricingType);
		}
	}

	private static String getJson(Object result) {
		String json = "";

		try {
			ObjectMapper om = new ObjectMapper();
			om.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
			om.registerModule(new JavaTimeModule());
			ObjectWriter ow = om.writer().withDefaultPrettyPrinter();

			json = ow.writeValueAsString(result);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return json;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約の製品タイプを取得する
<a name="marketplace-agreement_GetAgreementProductType_java_2_topic"></a>

次のコード例は、契約の製品タイプを取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementResponse;
import software.amazon.awssdk.services.marketplaceagreement.model.Resource;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;

import java.util.ArrayList;
import java.util.List;

import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementProductType {

	/* 
	 * Obtain the Product Type of the product the agreement was created on
	 */
	public static void main(String[] args) {
		
		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		List<String> productIds = getProducts(agreementId);

		ReferenceCodesUtils.formatOutput(productIds);
	}

	public static List<String> getProducts(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		DescribeAgreementRequest describeAgreementRequest = 
				DescribeAgreementRequest.builder()
				.agreementId(agreementId)
				.build();

		DescribeAgreementResponse describeAgreementResponse = marketplaceAgreementClient.describeAgreement(describeAgreementRequest);

		List<String> productIds = new ArrayList<String>();
		for (Resource resource : describeAgreementResponse.proposalSummary().resources()) {
			productIds.add(resource.id() + ":" + resource.type());
		}
		return productIds;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約のステータスを取得する
<a name="marketplace-agreement_GetAgreementStatus_java_2_topic"></a>

次のコード例は、契約のステータスを取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.AGREEMENT_ID;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.DescribeAgreementResponse;

public class GetAgreementStatus {

	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		DescribeAgreementResponse describeAgreementResponse = getDescribeAgreementResponse(agreementId);

		System.out.println("Agreement status is " + describeAgreementResponse.status());

	}

	public static DescribeAgreementResponse getDescribeAgreementResponse(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		DescribeAgreementRequest describeAgreementRequest = 
				DescribeAgreementRequest.builder()
				.agreementId(agreementId)
				.build();

		DescribeAgreementResponse describeAgreementResponse = marketplaceAgreementClient.describeAgreement(describeAgreementRequest);
		return describeAgreementResponse;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeAgreement](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。

### 契約のサポート条件を取得する
<a name="marketplace-agreement_GetAgreementTermsSupportTerm_java_2_topic"></a>

次のコード例は、契約のサポート条件を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AcceptedTerm;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;
import software.amazon.awssdk.services.marketplaceagreement.model.SupportTerm;

import java.util.ArrayList;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.AGREEMENT_ID;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class GetAgreementTermsSupportTerm {

	/*
	 * Obtain the support and refund policy I have provided to the customer
	 */
	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		List<SupportTerm> supportTerms = getSupportTerms(agreementId);

		ReferenceCodesUtils.formatOutput(supportTerms);
	}

	public static List<SupportTerm> getSupportTerms(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder().agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);

		List<SupportTerm> supportTerms = new ArrayList<>();

		for (AcceptedTerm acceptedTerm : getAgreementTermsResponse.acceptedTerms()) {
			if (acceptedTerm.supportTerm() != null) {
				supportTerms.add(acceptedTerm.supportTerm());
			}
		}
		return supportTerms;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 契約条件を取得する
<a name="marketplace-agreement_GetAgreementTerms_java_2_topic"></a>

次のコード例は、契約条件を取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.GetAgreementTermsResponse;

public class GetAgreementTerms {

	public static void main(String[] args) {

		String agreementId = args.length > 0 ? args[0] : AGREEMENT_ID;

		GetAgreementTermsResponse getAgreementTermsResponse = getAgreementTermsResponse(agreementId);

		ReferenceCodesUtils.formatOutput(getAgreementTermsResponse);

	}

	public static GetAgreementTermsResponse getAgreementTermsResponse(String agreementId) {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		GetAgreementTermsRequest getAgreementTermsRequest = 
				GetAgreementTermsRequest.builder()
				.agreementId(agreementId)
				.build();

		GetAgreementTermsResponse getAgreementTermsResponse = marketplaceAgreementClient.getAgreementTerms(getAgreementTermsRequest);
		return getAgreementTermsResponse;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAgreementTerms](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。

### 終了日で契約を検索する
<a name="marketplace-agreement_SearchAgreementsByEndDate_java_2_topic"></a>

次のコード例は、終了日で契約を検索する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AgreementViewSummary;
import software.amazon.awssdk.services.marketplaceagreement.model.Filter;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

public class SearchAgreementsByEndDate {

	static String beforeOrAfterEndtimeFilterName = BeforeOrAfterEndTimeFilterName.BeforeEndTime.name();

	static String cutoffDate = "2050-11-18T00:00:00Z";

	static String partyTypeFilterValue = PARTY_TYPE_FILTER_VALUE_PROPOSER;

	public static void main(String[] args) {

		List<AgreementViewSummary> agreementSummaryList = getAgreements();

		ReferenceCodesUtils.formatOutput(agreementSummaryList);
	}

	public static List<AgreementViewSummary> getAgreements() {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();

		// set up filters
		
		Filter partyTypeFilter = Filter.builder().name(PARTY_TYPE_FILTER_NAME)
				.values(PARTY_TYPE_FILTER_VALUE_PROPOSER).build();

		Filter agreementTypeFilter = Filter.builder().name(AGREEMENT_TYPE_FILTER_NAME)
				.values(AGREEMENT_TYPE_FILTER_VALUE_PURCHASEAGREEMENT).build();
		
		Filter customizeFilter = Filter.builder().name(beforeOrAfterEndtimeFilterName).values(cutoffDate).build();
		
		List<Filter> filters = new ArrayList<Filter>();
		
		filters.addAll(Arrays.asList(partyTypeFilter, agreementTypeFilter, customizeFilter));
		
		// search agreement with filters
		
		SearchAgreementsRequest searchAgreementsRequest = 
				SearchAgreementsRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.filters(filters)
				.build();
		
		SearchAgreementsResponse searchAgreementResponse= marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
		
		List<AgreementViewSummary> agreementSummaryList = new ArrayList<AgreementViewSummary>();
		
		agreementSummaryList.addAll(searchAgreementResponse.agreementViewSummaries());

		while (searchAgreementResponse.nextToken() != null && searchAgreementResponse.nextToken().length() > 0) {
			searchAgreementsRequest = 
					SearchAgreementsRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.filters(filters)
					.nextToken(searchAgreementResponse.nextToken())
					.build();
			searchAgreementResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
			agreementSummaryList.addAll(searchAgreementResponse.agreementViewSummaries());
		}
		return agreementSummaryList;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SearchAgreements](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。

### 1 つのカスタムフィルターで契約を検索する
<a name="marketplace-agreement_SearchAgreementsByOneFilter_java_2_topic"></a>

次のコード例は、1 つのカスタムフィルターで契約を検索する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AgreementViewSummary;
import software.amazon.awssdk.services.marketplaceagreement.model.Filter;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsResponse;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.example.awsmarketplace.utils.ReferenceCodesUtils;

/**
 * To search by 
 * offer id: OfferId; 
 * product id: ResourceIdentifier; 
 * customer AWS account id: AcceptorAccountId 
 * product type: ResourceType (i.e. SaasProduct)
 * status: Status. status values can be: ACTIVE, CANCELED,
 * 		EXPIRED, RENEWED, REPLACED, ROLLED_BACK, SUPERSEDED, TERMINATED
 */

public class SearchAgreementsByOneFilter {

	private static final String FILTER_NAME = "ResourceType"; 

	private static final String FILTER_VALUE = "SaaSProduct";

	/*
	 * search agreements by one customize filter
	 */
	public static void main(String[] args) {

		List<AgreementViewSummary> agreementSummaryList = getAgreements();

		ReferenceCodesUtils.formatOutput(agreementSummaryList);
	}

	public static List<AgreementViewSummary> getAgreements() {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		Filter partyTypeFilter = Filter.builder().name(PARTY_TYPE_FILTER_NAME)
				.values(PARTY_TYPE_FILTER_VALUE_PROPOSER).build();

		Filter agreementTypeFilter = Filter.builder().name(AGREEMENT_TYPE_FILTER_NAME)
				.values(AGREEMENT_TYPE_FILTER_VALUE_PURCHASEAGREEMENT).build();
		
		Filter customizeFilter = Filter.builder().name(FILTER_NAME).values(FILTER_VALUE).build();
		
		List<Filter> filters = new ArrayList<Filter>();
		
		filters.addAll(Arrays.asList(partyTypeFilter, agreementTypeFilter, customizeFilter));
		
		SearchAgreementsRequest searchAgreementsRequest = 
				SearchAgreementsRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.filters(filters)
				.build();
		SearchAgreementsResponse searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
		
		List<AgreementViewSummary> agreementSummaryList = new ArrayList<AgreementViewSummary>();

		agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());

		while (searchAgreementsResponse.nextToken() != null && searchAgreementsResponse.nextToken().length() > 0) {
			searchAgreementsRequest = 
					SearchAgreementsRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.filters(filters)
					.nextToken(searchAgreementsResponse.nextToken())
					.build();
			searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
			agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());
		}
		return agreementSummaryList;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SearchAgreements](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。

### 2 つのカスタムフィルターで契約を検索する
<a name="marketplace-agreement_SearchAgreementsByTwoFilters_java_2_topic"></a>

次のコード例は、2 つのカスタムフィルターで契約を検索する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/tree/main/java#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.example.awsmarketplace.agreementapi;

import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.marketplaceagreement.MarketplaceAgreementClient;
import software.amazon.awssdk.services.marketplaceagreement.model.AgreementViewSummary;
import software.amazon.awssdk.services.marketplaceagreement.model.Filter;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsRequest;
import software.amazon.awssdk.services.marketplaceagreement.model.SearchAgreementsResponse;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.example.awsmarketplace.utils.ReferenceCodesConstants.*;
import com.example.awsmarketplace.utils.ReferenceCodesUtils;

/**
 * Party Type = Proposer AND Acceptor: 
 * 	AfterEndTime 
 * 	BeforeEndTime
 * 	ResourceIdentifier + BeforeEndTime 
 * 	ResourceIdentifier + AfterEndTime
 * 	ResourceType + BeforeEndTime 
 * 	ResourceType + AfterEndTime 
 * 
 * Party Type = Proposer 
 * 	ResourceIdentifier 
 * 	OfferId 
 * 	AcceptorAccountId 
 * 	Status (ACTIVE) 
 * 	Status (ACTIVE) + ResourceIdentifier 
 * 	Status (ACTIVE) + AcceptorAccountId 
 * 	Status (ACTIVE) + OfferId 
 * 	Status (ACTIVE) + ResourceType 
 * 	AcceptorAccountId + BeforeEndTime 
 * 	AcceptorAccountId + AfterEndTime 
 * 	AcceptorAccountId + AfterEndTime 
 * 	OfferId + BeforeEndTime 
 * 
 * Status values can be: ACTIVE, CANCELLED, EXPIRED, RENEWED, REPLACED, ROLLED_BACK, SUPERSEDED, TERMINATED
 */

public class SearchAgreementsByTwoFilters {

	public static final String FILTER_1_NAME = "ResourceType";

	public static final String FILTER_1_VALUE = "SaaSProduct";

	public static final String FILTER_2_NAME = "Status";

	public static final String FILTER_2_VALUE = "ACTIVE";
	
	/*
	 * search agreements by two customize filter
	 */
	public static void main(String[] args) {

		List<AgreementViewSummary> agreementSummaryList = getAgreements();

		ReferenceCodesUtils.formatOutput(agreementSummaryList);

	}

	public static List<AgreementViewSummary> getAgreements() {
		MarketplaceAgreementClient marketplaceAgreementClient = 
				MarketplaceAgreementClient.builder()
				.httpClient(ApacheHttpClient.builder().build())
				.credentialsProvider(ProfileCredentialsProvider.create())
				.build();
		
		Filter partyTypeFilter = Filter.builder().name(PARTY_TYPE_FILTER_NAME)
				.values(PARTY_TYPE_FILTER_VALUE_PROPOSER).build();

		Filter agreementTypeFilter = Filter.builder().name(AGREEMENT_TYPE_FILTER_NAME)
				.values(AGREEMENT_TYPE_FILTER_VALUE_PURCHASEAGREEMENT).build();
		
		Filter customizeFilter1 = Filter.builder().name(FILTER_1_NAME).values(FILTER_1_VALUE).build();
		
		Filter customizeFilter2 = Filter.builder().name(FILTER_2_NAME).values(FILTER_2_VALUE).build();

		
		List<Filter> filters = new ArrayList<Filter>();
		
		filters.addAll(Arrays.asList(partyTypeFilter, agreementTypeFilter, customizeFilter1, customizeFilter2));
		
		SearchAgreementsRequest searchAgreementsRequest = 
				SearchAgreementsRequest.builder()
				.catalog(AWS_MP_CATALOG)
				.filters(filters)
				.build();
		
		SearchAgreementsResponse searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
		
		List<AgreementViewSummary> agreementSummaryList = new ArrayList<AgreementViewSummary>();

		agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());

		while (searchAgreementsResponse.nextToken() != null && searchAgreementsResponse.nextToken().length() > 0) {
			searchAgreementsRequest = 
					SearchAgreementsRequest.builder()
					.catalog(AWS_MP_CATALOG)
					.filters(filters)
					.nextToken(searchAgreementsResponse.nextToken())
					.build();
			searchAgreementsResponse = marketplaceAgreementClient.searchAgreements(searchAgreementsRequest);
			agreementSummaryList.addAll(searchAgreementsResponse.agreementViewSummaries());
		}
		return agreementSummaryList;
	}

}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SearchAgreements](https://docs.aws.amazon.com/goto/SdkForJavaV2/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。

# SDK for Java 2.x を使用した MediaConvert の例
<a name="java_2_mediaconvert_code_examples"></a>

次のコード例は、MediaConvert AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateJob`
<a name="mediaconvert_CreateJob_java_2_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
package com.example.mediaconvert;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediaconvert.MediaConvertClient;
import software.amazon.awssdk.services.mediaconvert.model.DescribeEndpointsResponse;
import software.amazon.awssdk.services.mediaconvert.model.DescribeEndpointsRequest;
import software.amazon.awssdk.services.mediaconvert.model.Output;
import software.amazon.awssdk.services.mediaconvert.model.MediaConvertException;
import software.amazon.awssdk.services.mediaconvert.model.OutputGroup;
import software.amazon.awssdk.services.mediaconvert.model.OutputGroupSettings;
import software.amazon.awssdk.services.mediaconvert.model.HlsGroupSettings;
import software.amazon.awssdk.services.mediaconvert.model.OutputGroupType;
import software.amazon.awssdk.services.mediaconvert.model.HlsDirectoryStructure;
import software.amazon.awssdk.services.mediaconvert.model.HlsManifestDurationFormat;
import software.amazon.awssdk.services.mediaconvert.model.HlsStreamInfResolution;
import software.amazon.awssdk.services.mediaconvert.model.HlsClientCache;
import software.amazon.awssdk.services.mediaconvert.model.HlsCaptionLanguageSetting;
import software.amazon.awssdk.services.mediaconvert.model.HlsManifestCompression;
import software.amazon.awssdk.services.mediaconvert.model.HlsCodecSpecification;
import software.amazon.awssdk.services.mediaconvert.model.HlsOutputSelection;
import software.amazon.awssdk.services.mediaconvert.model.HlsProgramDateTime;
import software.amazon.awssdk.services.mediaconvert.model.HlsTimedMetadataId3Frame;
import software.amazon.awssdk.services.mediaconvert.model.HlsSegmentControl;
import software.amazon.awssdk.services.mediaconvert.model.FileGroupSettings;
import software.amazon.awssdk.services.mediaconvert.model.ContainerSettings;
import software.amazon.awssdk.services.mediaconvert.model.VideoDescription;
import software.amazon.awssdk.services.mediaconvert.model.ContainerType;
import software.amazon.awssdk.services.mediaconvert.model.ScalingBehavior;
import software.amazon.awssdk.services.mediaconvert.model.VideoTimecodeInsertion;
import software.amazon.awssdk.services.mediaconvert.model.ColorMetadata;
import software.amazon.awssdk.services.mediaconvert.model.RespondToAfd;
import software.amazon.awssdk.services.mediaconvert.model.AfdSignaling;
import software.amazon.awssdk.services.mediaconvert.model.DropFrameTimecode;
import software.amazon.awssdk.services.mediaconvert.model.VideoCodecSettings;
import software.amazon.awssdk.services.mediaconvert.model.H264Settings;
import software.amazon.awssdk.services.mediaconvert.model.VideoCodec;
import software.amazon.awssdk.services.mediaconvert.model.CreateJobRequest;
import software.amazon.awssdk.services.mediaconvert.model.H264RateControlMode;
import software.amazon.awssdk.services.mediaconvert.model.H264QualityTuningLevel;
import software.amazon.awssdk.services.mediaconvert.model.H264SceneChangeDetect;
import software.amazon.awssdk.services.mediaconvert.model.AacAudioDescriptionBroadcasterMix;
import software.amazon.awssdk.services.mediaconvert.model.H264ParControl;
import software.amazon.awssdk.services.mediaconvert.model.AacRawFormat;
import software.amazon.awssdk.services.mediaconvert.model.H264QvbrSettings;
import software.amazon.awssdk.services.mediaconvert.model.H264FramerateConversionAlgorithm;
import software.amazon.awssdk.services.mediaconvert.model.H264CodecLevel;
import software.amazon.awssdk.services.mediaconvert.model.H264FramerateControl;
import software.amazon.awssdk.services.mediaconvert.model.AacCodingMode;
import software.amazon.awssdk.services.mediaconvert.model.H264Telecine;
import software.amazon.awssdk.services.mediaconvert.model.H264FlickerAdaptiveQuantization;
import software.amazon.awssdk.services.mediaconvert.model.H264GopSizeUnits;
import software.amazon.awssdk.services.mediaconvert.model.H264CodecProfile;
import software.amazon.awssdk.services.mediaconvert.model.H264GopBReference;
import software.amazon.awssdk.services.mediaconvert.model.AudioTypeControl;
import software.amazon.awssdk.services.mediaconvert.model.AntiAlias;
import software.amazon.awssdk.services.mediaconvert.model.H264SlowPal;
import software.amazon.awssdk.services.mediaconvert.model.H264SpatialAdaptiveQuantization;
import software.amazon.awssdk.services.mediaconvert.model.H264Syntax;
import software.amazon.awssdk.services.mediaconvert.model.M3u8Settings;
import software.amazon.awssdk.services.mediaconvert.model.InputDenoiseFilter;
import software.amazon.awssdk.services.mediaconvert.model.H264TemporalAdaptiveQuantization;
import software.amazon.awssdk.services.mediaconvert.model.CreateJobResponse;
import software.amazon.awssdk.services.mediaconvert.model.H264UnregisteredSeiTimecode;
import software.amazon.awssdk.services.mediaconvert.model.H264EntropyEncoding;
import software.amazon.awssdk.services.mediaconvert.model.InputPsiControl;
import software.amazon.awssdk.services.mediaconvert.model.ColorSpace;
import software.amazon.awssdk.services.mediaconvert.model.H264RepeatPps;
import software.amazon.awssdk.services.mediaconvert.model.H264FieldEncoding;
import software.amazon.awssdk.services.mediaconvert.model.M3u8NielsenId3;
import software.amazon.awssdk.services.mediaconvert.model.InputDeblockFilter;
import software.amazon.awssdk.services.mediaconvert.model.InputRotate;
import software.amazon.awssdk.services.mediaconvert.model.H264DynamicSubGop;
import software.amazon.awssdk.services.mediaconvert.model.TimedMetadata;
import software.amazon.awssdk.services.mediaconvert.model.JobSettings;
import software.amazon.awssdk.services.mediaconvert.model.AudioDefaultSelection;
import software.amazon.awssdk.services.mediaconvert.model.VideoSelector;
import software.amazon.awssdk.services.mediaconvert.model.AacSpecification;
import software.amazon.awssdk.services.mediaconvert.model.Input;
import software.amazon.awssdk.services.mediaconvert.model.OutputSettings;
import software.amazon.awssdk.services.mediaconvert.model.H264AdaptiveQuantization;
import software.amazon.awssdk.services.mediaconvert.model.AudioLanguageCodeControl;
import software.amazon.awssdk.services.mediaconvert.model.InputFilterEnable;
import software.amazon.awssdk.services.mediaconvert.model.AudioDescription;
import software.amazon.awssdk.services.mediaconvert.model.H264InterlaceMode;
import software.amazon.awssdk.services.mediaconvert.model.AudioCodecSettings;
import software.amazon.awssdk.services.mediaconvert.model.AacSettings;
import software.amazon.awssdk.services.mediaconvert.model.AudioCodec;
import software.amazon.awssdk.services.mediaconvert.model.AacRateControlMode;
import software.amazon.awssdk.services.mediaconvert.model.AacCodecProfile;
import software.amazon.awssdk.services.mediaconvert.model.HlsIFrameOnlyManifest;
import software.amazon.awssdk.services.mediaconvert.model.FrameCaptureSettings;
import software.amazon.awssdk.services.mediaconvert.model.AudioSelector;
import software.amazon.awssdk.services.mediaconvert.model.M3u8PcrControl;
import software.amazon.awssdk.services.mediaconvert.model.InputTimecodeSource;
import software.amazon.awssdk.services.mediaconvert.model.HlsSettings;
import software.amazon.awssdk.services.mediaconvert.model.M3u8Scte35Source;

/**
 * Create a MediaConvert job. Must supply MediaConvert access role Amazon
 * Resource Name (ARN), and a
 * valid video input file via Amazon S3 URL.
 *
 * Also, 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 CreateJob {
        public static void main(String[] args) {
                final String usage = """

                                Usage:
                                    <mcRoleARN> <fileInput>\s

                                Where:
                                    mcRoleARN - The MediaConvert Role ARN.\s
                                    fileInput -  The URL of an Amazon S3 bucket where the input file is located.\s
                                """;

                if (args.length != 2) {
                        System.out.println(usage);
                        System.exit(1);
                }

                String mcRoleARN = args[0];
                String fileInput = args[1];
                Region region = Region.US_WEST_2;
                MediaConvertClient mc = MediaConvertClient.builder()
                                .region(region)
                                .build();

                String id = createMediaJob(mc, mcRoleARN, fileInput);
                System.out.println("MediaConvert job created. Job Id = " + id);
                mc.close();
        }

        public static String createMediaJob(MediaConvertClient mc, String mcRoleARN, String fileInput) {

                String s3path = fileInput.substring(0, fileInput.lastIndexOf('/') + 1) + "javasdk/out/";
                String fileOutput = s3path + "index";
                String thumbsOutput = s3path + "thumbs/";
                String mp4Output = s3path + "mp4/";

                try {
                        System.out.println("MediaConvert role arn: " + mcRoleARN);
                        System.out.println("MediaConvert input file: " + fileInput);
                        System.out.println("MediaConvert output path: " + s3path);

                        // output group Preset HLS low profile
                        Output hlsLow = createOutput("hls_low", "_low", "_$dt$", 750000, 7, 1920, 1080, 640);
                        // output group Preset HLS media profile
                        Output hlsMedium = createOutput("hls_medium", "_medium", "_$dt$", 1200000, 7, 1920, 1080, 1280);
                        // output group Preset HLS high profole
                        Output hlsHigh = createOutput("hls_high", "_high", "_$dt$", 3500000, 8, 1920, 1080, 1920);

                        OutputGroup appleHLS = OutputGroup.builder().name("Apple HLS").customName("Example")
                                        .outputGroupSettings(OutputGroupSettings.builder()
                                                        .type(OutputGroupType.HLS_GROUP_SETTINGS)
                                                        .hlsGroupSettings(HlsGroupSettings.builder()
                                                                        .directoryStructure(
                                                                                        HlsDirectoryStructure.SINGLE_DIRECTORY)
                                                                        .manifestDurationFormat(
                                                                                        HlsManifestDurationFormat.INTEGER)
                                                                        .streamInfResolution(
                                                                                        HlsStreamInfResolution.INCLUDE)
                                                                        .clientCache(HlsClientCache.ENABLED)
                                                                        .captionLanguageSetting(
                                                                                        HlsCaptionLanguageSetting.OMIT)
                                                                        .manifestCompression(
                                                                                        HlsManifestCompression.NONE)
                                                                        .codecSpecification(
                                                                                        HlsCodecSpecification.RFC_4281)
                                                                        .outputSelection(
                                                                                        HlsOutputSelection.MANIFESTS_AND_SEGMENTS)
                                                                        .programDateTime(HlsProgramDateTime.EXCLUDE)
                                                                        .programDateTimePeriod(600)
                                                                        .timedMetadataId3Frame(
                                                                                        HlsTimedMetadataId3Frame.PRIV)
                                                                        .timedMetadataId3Period(10)
                                                                        .destination(fileOutput)
                                                                        .segmentControl(HlsSegmentControl.SEGMENTED_FILES)
                                                                        .minFinalSegmentLength((double) 0)
                                                                        .segmentLength(4).minSegmentLength(0).build())
                                                        .build())
                                        .outputs(hlsLow, hlsMedium, hlsHigh).build();

                        OutputGroup fileMp4 = OutputGroup.builder().name("File Group").customName("mp4")
                                        .outputGroupSettings(OutputGroupSettings.builder()
                                                        .type(OutputGroupType.FILE_GROUP_SETTINGS)
                                                        .fileGroupSettings(FileGroupSettings.builder()
                                                                        .destination(mp4Output).build())
                                                        .build())
                                        .outputs(Output.builder().extension("mp4")
                                                        .containerSettings(ContainerSettings.builder()
                                                                        .container(ContainerType.MP4).build())
                                                        .videoDescription(VideoDescription.builder().width(1280)
                                                                        .height(720)
                                                                        .scalingBehavior(ScalingBehavior.DEFAULT)
                                                                        .sharpness(50).antiAlias(AntiAlias.ENABLED)
                                                                        .timecodeInsertion(
                                                                                        VideoTimecodeInsertion.DISABLED)
                                                                        .colorMetadata(ColorMetadata.INSERT)
                                                                        .respondToAfd(RespondToAfd.NONE)
                                                                        .afdSignaling(AfdSignaling.NONE)
                                                                        .dropFrameTimecode(DropFrameTimecode.ENABLED)
                                                                        .codecSettings(VideoCodecSettings.builder()
                                                                                        .codec(VideoCodec.H_264)
                                                                                        .h264Settings(H264Settings
                                                                                                        .builder()
                                                                                                        .rateControlMode(
                                                                                                                        H264RateControlMode.QVBR)
                                                                                                        .parControl(H264ParControl.INITIALIZE_FROM_SOURCE)
                                                                                                        .qualityTuningLevel(
                                                                                                                        H264QualityTuningLevel.SINGLE_PASS)
                                                                                                        .qvbrSettings(
                                                                                                                        H264QvbrSettings.builder()
                                                                                                                                        .qvbrQualityLevel(
                                                                                                                                                        8)
                                                                                                                                        .build())
                                                                                                        .codecLevel(H264CodecLevel.AUTO)
                                                                                                        .codecProfile(H264CodecProfile.MAIN)
                                                                                                        .maxBitrate(2400000)
                                                                                                        .framerateControl(
                                                                                                                        H264FramerateControl.INITIALIZE_FROM_SOURCE)
                                                                                                        .gopSize(2.0)
                                                                                                        .gopSizeUnits(H264GopSizeUnits.SECONDS)
                                                                                                        .numberBFramesBetweenReferenceFrames(
                                                                                                                        2)
                                                                                                        .gopClosedCadence(
                                                                                                                        1)
                                                                                                        .gopBReference(H264GopBReference.DISABLED)
                                                                                                        .slowPal(H264SlowPal.DISABLED)
                                                                                                        .syntax(H264Syntax.DEFAULT)
                                                                                                        .numberReferenceFrames(
                                                                                                                        3)
                                                                                                        .dynamicSubGop(H264DynamicSubGop.STATIC)
                                                                                                        .fieldEncoding(H264FieldEncoding.PAFF)
                                                                                                        .sceneChangeDetect(
                                                                                                                        H264SceneChangeDetect.ENABLED)
                                                                                                        .minIInterval(0)
                                                                                                        .telecine(H264Telecine.NONE)
                                                                                                        .framerateConversionAlgorithm(
                                                                                                                        H264FramerateConversionAlgorithm.DUPLICATE_DROP)
                                                                                                        .entropyEncoding(
                                                                                                                        H264EntropyEncoding.CABAC)
                                                                                                        .slices(1)
                                                                                                        .unregisteredSeiTimecode(
                                                                                                                        H264UnregisteredSeiTimecode.DISABLED)
                                                                                                        .repeatPps(H264RepeatPps.DISABLED)
                                                                                                        .adaptiveQuantization(
                                                                                                                        H264AdaptiveQuantization.HIGH)
                                                                                                        .spatialAdaptiveQuantization(
                                                                                                                        H264SpatialAdaptiveQuantization.ENABLED)
                                                                                                        .temporalAdaptiveQuantization(
                                                                                                                        H264TemporalAdaptiveQuantization.ENABLED)
                                                                                                        .flickerAdaptiveQuantization(
                                                                                                                        H264FlickerAdaptiveQuantization.DISABLED)
                                                                                                        .softness(0)
                                                                                                        .interlaceMode(H264InterlaceMode.PROGRESSIVE)
                                                                                                        .build())
                                                                                        .build())
                                                                        .build())
                                                        .audioDescriptions(AudioDescription.builder()
                                                                        .audioTypeControl(AudioTypeControl.FOLLOW_INPUT)
                                                                        .languageCodeControl(
                                                                                        AudioLanguageCodeControl.FOLLOW_INPUT)
                                                                        .codecSettings(AudioCodecSettings.builder()
                                                                                        .codec(AudioCodec.AAC)
                                                                                        .aacSettings(AacSettings
                                                                                                        .builder()
                                                                                                        .codecProfile(AacCodecProfile.LC)
                                                                                                        .rateControlMode(
                                                                                                                        AacRateControlMode.CBR)
                                                                                                        .codingMode(AacCodingMode.CODING_MODE_2_0)
                                                                                                        .sampleRate(44100)
                                                                                                        .bitrate(160000)
                                                                                                        .rawFormat(AacRawFormat.NONE)
                                                                                                        .specification(AacSpecification.MPEG4)
                                                                                                        .audioDescriptionBroadcasterMix(
                                                                                                                        AacAudioDescriptionBroadcasterMix.NORMAL)
                                                                                                        .build())
                                                                                        .build())
                                                                        .build())
                                                        .build())
                                        .build();
                        OutputGroup thumbs = OutputGroup.builder().name("File Group").customName("thumbs")
                                        .outputGroupSettings(OutputGroupSettings.builder()
                                                        .type(OutputGroupType.FILE_GROUP_SETTINGS)
                                                        .fileGroupSettings(FileGroupSettings.builder()
                                                                        .destination(thumbsOutput).build())
                                                        .build())
                                        .outputs(Output.builder().extension("jpg")
                                                        .containerSettings(ContainerSettings.builder()
                                                                        .container(ContainerType.RAW).build())
                                                        .videoDescription(VideoDescription.builder()
                                                                        .scalingBehavior(ScalingBehavior.DEFAULT)
                                                                        .sharpness(50).antiAlias(AntiAlias.ENABLED)
                                                                        .timecodeInsertion(
                                                                                        VideoTimecodeInsertion.DISABLED)
                                                                        .colorMetadata(ColorMetadata.INSERT)
                                                                        .dropFrameTimecode(DropFrameTimecode.ENABLED)
                                                                        .codecSettings(VideoCodecSettings.builder()
                                                                                        .codec(VideoCodec.FRAME_CAPTURE)
                                                                                        .frameCaptureSettings(
                                                                                                        FrameCaptureSettings
                                                                                                                        .builder()
                                                                                                                        .framerateNumerator(
                                                                                                                                        1)
                                                                                                                        .framerateDenominator(
                                                                                                                                        1)
                                                                                                                        .maxCaptures(10000000)
                                                                                                                        .quality(80)
                                                                                                                        .build())
                                                                                        .build())
                                                                        .build())
                                                        .build())
                                        .build();

                        Map<String, AudioSelector> audioSelectors = new HashMap<>();
                        audioSelectors.put("Audio Selector 1",
                                        AudioSelector.builder().defaultSelection(AudioDefaultSelection.DEFAULT)
                                                        .offset(0).build());

                        JobSettings jobSettings = JobSettings.builder().inputs(Input.builder()
                                        .audioSelectors(audioSelectors)
                                        .videoSelector(
                                                        VideoSelector.builder().colorSpace(ColorSpace.FOLLOW)
                                                                        .rotate(InputRotate.DEGREE_0).build())
                                        .filterEnable(InputFilterEnable.AUTO).filterStrength(0)
                                        .deblockFilter(InputDeblockFilter.DISABLED)
                                        .denoiseFilter(InputDenoiseFilter.DISABLED).psiControl(InputPsiControl.USE_PSI)
                                        .timecodeSource(InputTimecodeSource.EMBEDDED).fileInput(fileInput).build())
                                        .outputGroups(appleHLS, thumbs, fileMp4).build();

                        CreateJobRequest createJobRequest = CreateJobRequest.builder().role(mcRoleARN)
                                        .settings(jobSettings)
                                        .build();

                        CreateJobResponse createJobResponse = mc.createJob(createJobRequest);
                        return createJobResponse.job().id();

                } catch (MediaConvertException e) {
                        System.out.println(e.toString());
                        System.exit(0);
                }
                return "";
        }

        private final static Output createOutput(String customName,
                        String nameModifier,
                        String segmentModifier,
                        int qvbrMaxBitrate,
                        int qvbrQualityLevel,
                        int originWidth,
                        int originHeight,
                        int targetWidth) {

                int targetHeight = Math.round(originHeight * targetWidth / originWidth)
                                - (Math.round(originHeight * targetWidth / originWidth) % 4);
                Output output = null;
                try {
                        output = Output.builder().nameModifier(nameModifier).outputSettings(OutputSettings.builder()
                                        .hlsSettings(HlsSettings.builder().segmentModifier(segmentModifier)
                                                        .audioGroupId("program_audio")
                                                        .iFrameOnlyManifest(HlsIFrameOnlyManifest.EXCLUDE).build())
                                        .build())
                                        .containerSettings(ContainerSettings.builder().container(ContainerType.M3_U8)
                                                        .m3u8Settings(M3u8Settings.builder().audioFramesPerPes(4)
                                                                        .pcrControl(M3u8PcrControl.PCR_EVERY_PES_PACKET)
                                                                        .pmtPid(480).privateMetadataPid(503)
                                                                        .programNumber(1).patInterval(0).pmtInterval(0)
                                                                        .scte35Source(M3u8Scte35Source.NONE)
                                                                        .scte35Pid(500).nielsenId3(M3u8NielsenId3.NONE)
                                                                        .timedMetadata(TimedMetadata.NONE)
                                                                        .timedMetadataPid(502).videoPid(481)
                                                                        .audioPids(482, 483, 484, 485, 486, 487, 488,
                                                                                        489, 490, 491, 492)
                                                                        .build())
                                                        .build())
                                        .videoDescription(
                                                        VideoDescription.builder().width(targetWidth)
                                                                        .height(targetHeight)
                                                                        .scalingBehavior(ScalingBehavior.DEFAULT)
                                                                        .sharpness(50).antiAlias(AntiAlias.ENABLED)
                                                                        .timecodeInsertion(
                                                                                        VideoTimecodeInsertion.DISABLED)
                                                                        .colorMetadata(ColorMetadata.INSERT)
                                                                        .respondToAfd(RespondToAfd.NONE)
                                                                        .afdSignaling(AfdSignaling.NONE)
                                                                        .dropFrameTimecode(DropFrameTimecode.ENABLED)
                                                                        .codecSettings(VideoCodecSettings.builder()
                                                                                        .codec(VideoCodec.H_264)
                                                                                        .h264Settings(H264Settings
                                                                                                        .builder()
                                                                                                        .rateControlMode(
                                                                                                                        H264RateControlMode.QVBR)
                                                                                                        .parControl(H264ParControl.INITIALIZE_FROM_SOURCE)
                                                                                                        .qualityTuningLevel(
                                                                                                                        H264QualityTuningLevel.SINGLE_PASS)
                                                                                                        .qvbrSettings(H264QvbrSettings
                                                                                                                        .builder()
                                                                                                                        .qvbrQualityLevel(
                                                                                                                                        qvbrQualityLevel)
                                                                                                                        .build())
                                                                                                        .codecLevel(H264CodecLevel.AUTO)
                                                                                                        .codecProfile((targetHeight > 720
                                                                                                                        && targetWidth > 1280)
                                                                                                                                        ? H264CodecProfile.HIGH
                                                                                                                                        : H264CodecProfile.MAIN)
                                                                                                        .maxBitrate(qvbrMaxBitrate)
                                                                                                        .framerateControl(
                                                                                                                        H264FramerateControl.INITIALIZE_FROM_SOURCE)
                                                                                                        .gopSize(2.0)
                                                                                                        .gopSizeUnits(H264GopSizeUnits.SECONDS)
                                                                                                        .numberBFramesBetweenReferenceFrames(
                                                                                                                        2)
                                                                                                        .gopClosedCadence(
                                                                                                                        1)
                                                                                                        .gopBReference(H264GopBReference.DISABLED)
                                                                                                        .slowPal(H264SlowPal.DISABLED)
                                                                                                        .syntax(H264Syntax.DEFAULT)
                                                                                                        .numberReferenceFrames(
                                                                                                                        3)
                                                                                                        .dynamicSubGop(H264DynamicSubGop.STATIC)
                                                                                                        .fieldEncoding(H264FieldEncoding.PAFF)
                                                                                                        .sceneChangeDetect(
                                                                                                                        H264SceneChangeDetect.ENABLED)
                                                                                                        .minIInterval(0)
                                                                                                        .telecine(H264Telecine.NONE)
                                                                                                        .framerateConversionAlgorithm(
                                                                                                                        H264FramerateConversionAlgorithm.DUPLICATE_DROP)
                                                                                                        .entropyEncoding(
                                                                                                                        H264EntropyEncoding.CABAC)
                                                                                                        .slices(1)
                                                                                                        .unregisteredSeiTimecode(
                                                                                                                        H264UnregisteredSeiTimecode.DISABLED)
                                                                                                        .repeatPps(H264RepeatPps.DISABLED)
                                                                                                        .adaptiveQuantization(
                                                                                                                        H264AdaptiveQuantization.HIGH)
                                                                                                        .spatialAdaptiveQuantization(
                                                                                                                        H264SpatialAdaptiveQuantization.ENABLED)
                                                                                                        .temporalAdaptiveQuantization(
                                                                                                                        H264TemporalAdaptiveQuantization.ENABLED)
                                                                                                        .flickerAdaptiveQuantization(
                                                                                                                        H264FlickerAdaptiveQuantization.DISABLED)
                                                                                                        .softness(0)
                                                                                                        .interlaceMode(H264InterlaceMode.PROGRESSIVE)
                                                                                                        .build())
                                                                                        .build())
                                                                        .build())
                                        .audioDescriptions(AudioDescription.builder()
                                                        .audioTypeControl(AudioTypeControl.FOLLOW_INPUT)
                                                        .languageCodeControl(AudioLanguageCodeControl.FOLLOW_INPUT)
                                                        .codecSettings(AudioCodecSettings.builder()
                                                                        .codec(AudioCodec.AAC).aacSettings(AacSettings
                                                                                        .builder()
                                                                                        .codecProfile(AacCodecProfile.LC)
                                                                                        .rateControlMode(
                                                                                                        AacRateControlMode.CBR)
                                                                                        .codingMode(AacCodingMode.CODING_MODE_2_0)
                                                                                        .sampleRate(44100)
                                                                                        .bitrate(96000)
                                                                                        .rawFormat(AacRawFormat.NONE)
                                                                                        .specification(AacSpecification.MPEG4)
                                                                                        .audioDescriptionBroadcasterMix(
                                                                                                        AacAudioDescriptionBroadcasterMix.NORMAL)
                                                                                        .build())
                                                                        .build())
                                                        .build())
                                        .build();
                } catch (MediaConvertException e) {
                        e.printStackTrace();
                        System.exit(0);
                }
                return output;
        }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CreateJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediaconvert-2017-08-29/CreateJob)」を参照してください。**

### `GetJob`
<a name="mediaconvert_GetJob_java_2_topic"></a>

次のコード例は、`GetJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediaconvert.model.DescribeEndpointsResponse;
import software.amazon.awssdk.services.mediaconvert.model.GetJobRequest;
import software.amazon.awssdk.services.mediaconvert.model.DescribeEndpointsRequest;
import software.amazon.awssdk.services.mediaconvert.model.GetJobResponse;
import software.amazon.awssdk.services.mediaconvert.model.MediaConvertException;
import software.amazon.awssdk.services.mediaconvert.MediaConvertClient;
import java.net.URI;

/**
 * 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 GetJob {

    public static void main(String[] args) {

        final String usage = "\n" +
                "  <jobId> \n\n" +
                "Where:\n" +
                "  jobId - The job id value.\n\n";

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String jobId = args[0];
        Region region = Region.US_WEST_2;
        MediaConvertClient mc = MediaConvertClient.builder()
                .region(region)
                .build();

        getSpecificJob(mc, jobId);
        mc.close();
    }

    public static void getSpecificJob(MediaConvertClient mc, String jobId) {
        try {
            GetJobRequest jobRequest = GetJobRequest.builder()
                    .id(jobId)
                    .build();

            GetJobResponse response = mc.getJob(jobRequest);
            System.out.println("The ARN of the job is " + response.job().arn());

        } catch (MediaConvertException e) {
            System.out.println(e.toString());
            System.exit(0);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediaconvert-2017-08-29/GetJob)」を参照してください。

### `ListJobs`
<a name="mediaconvert_ListJobs_java_2_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.mediaconvert.MediaConvertClient;
import software.amazon.awssdk.services.mediaconvert.model.ListJobsRequest;
import software.amazon.awssdk.services.mediaconvert.model.DescribeEndpointsResponse;
import software.amazon.awssdk.services.mediaconvert.model.DescribeEndpointsRequest;
import software.amazon.awssdk.services.mediaconvert.model.ListJobsResponse;
import software.amazon.awssdk.services.mediaconvert.model.Job;
import software.amazon.awssdk.services.mediaconvert.model.MediaConvertException;
import java.net.URI;
import java.util.List;

/**
 * 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 ListJobs {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        MediaConvertClient mc = MediaConvertClient.builder()
                .region(region)
                .build();

        listCompleteJobs(mc);
        mc.close();
    }

    public static void listCompleteJobs(MediaConvertClient mc) {
        try {
            // Create the ListJobsRequest
            ListJobsRequest jobsRequest = ListJobsRequest.builder()
                    .maxResults(10)
                    .status("COMPLETE")
                    .build();

            // Call the listJobs operation
            ListJobsResponse jobsResponse = mc.listJobs(jobsRequest);
            List<Job> jobs = jobsResponse.jobs();
            for (Job job : jobs) {
                System.out.println("The JOB ARN is : " + job.arn());
            }

        } catch (MediaConvertException e) {
            System.out.println(e.toString());
            System.exit(0);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/mediaconvert-2017-08-29/ListJobs)」を参照してください。

# SDK for Java 2.x を使用した Migration Hub の例
<a name="java_2_migration-hub_code_examples"></a>

次のコード例は、Migration Hub AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteProgressUpdateStream`
<a name="migration-hub_DeleteProgressUpdateStream_java_2_topic"></a>

次のコード例は、`DeleteProgressUpdateStream` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/migrationhub#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.migrationhub.MigrationHubClient;
import software.amazon.awssdk.services.migrationhub.model.DeleteProgressUpdateStreamRequest;
import software.amazon.awssdk.services.migrationhub.model.MigrationHubException;

/**
 * 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 DeleteProgressStream {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <progressStream>\s

                Where:
                    progressStream - the name of a progress stream to delete.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String progressStream = args[0];
        Region region = Region.US_WEST_2;
        MigrationHubClient migrationClient = MigrationHubClient.builder()
                .region(region)
                .build();

        deleteStream(migrationClient, progressStream);
        migrationClient.close();
    }

    public static void deleteStream(MigrationHubClient migrationClient, String streamName) {
        try {
            DeleteProgressUpdateStreamRequest deleteProgressUpdateStreamRequest = DeleteProgressUpdateStreamRequest
                    .builder()
                    .progressUpdateStreamName(streamName)
                    .build();

            migrationClient.deleteProgressUpdateStream(deleteProgressUpdateStreamRequest);
            System.out.println(streamName + " is deleted");

        } catch (MigrationHubException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteProgressUpdateStream](https://docs.aws.amazon.com/goto/SdkForJavaV2/migration-hub-2017-05-31/DeleteProgressUpdateStream)」を参照してください。

### `DescribeApplicationState`
<a name="migration-hub_DescribeApplicationState_java_2_topic"></a>

次のコード例は、`DescribeApplicationState` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/migrationhub#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.migrationhub.MigrationHubClient;
import software.amazon.awssdk.services.migrationhub.model.DescribeApplicationStateRequest;
import software.amazon.awssdk.services.migrationhub.model.DescribeApplicationStateResponse;
import software.amazon.awssdk.services.migrationhub.model.MigrationHubException;

/**
 * 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 DescribeAppState {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    DescribeAppState <appId>\s

                Where:
                    appId -  the application id value.\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        Region region = Region.US_WEST_2;
        MigrationHubClient migrationClient = MigrationHubClient.builder()
                .region(region)
                .build();

        describeApplicationState(migrationClient, appId);
        migrationClient.close();
    }

    public static void describeApplicationState(MigrationHubClient migrationClient, String appId) {
        try {
            DescribeApplicationStateRequest applicationStateRequest = DescribeApplicationStateRequest.builder()
                    .applicationId(appId)
                    .build();

            DescribeApplicationStateResponse applicationStateResponse = migrationClient
                    .describeApplicationState(applicationStateRequest);
            System.out.println("The application status is " + applicationStateResponse.applicationStatusAsString());

        } catch (MigrationHubException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeApplicationState](https://docs.aws.amazon.com/goto/SdkForJavaV2/migration-hub-2017-05-31/DescribeApplicationState)」を参照してください。

### `DescribeMigrationTask`
<a name="migration-hub_DescribeMigrationTask_java_2_topic"></a>

次のコード例は、`DescribeMigrationTask` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/migrationhub#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.migrationhub.MigrationHubClient;
import software.amazon.awssdk.services.migrationhub.model.DescribeMigrationTaskRequest;
import software.amazon.awssdk.services.migrationhub.model.DescribeMigrationTaskResponse;
import software.amazon.awssdk.services.migrationhub.model.MigrationHubException;

/**
 * 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 DescribeMigrationTask {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    DescribeMigrationTask <migrationTask> <progressStream>\s

                Where:
                    migrationTask - the name of a migration task.\s
                    progressStream - the name of a progress stream.\s
                """;

        if (args.length < 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String migrationTask = args[0];
        String progressStream = args[1];
        Region region = Region.US_WEST_2;
        MigrationHubClient migrationClient = MigrationHubClient.builder()
                .region(region)
                .build();

        describeMigTask(migrationClient, migrationTask, progressStream);
        migrationClient.close();
    }

    public static void describeMigTask(MigrationHubClient migrationClient, String migrationTask,
            String progressStream) {
        try {
            DescribeMigrationTaskRequest migrationTaskRequestRequest = DescribeMigrationTaskRequest.builder()
                    .progressUpdateStream(progressStream)
                    .migrationTaskName(migrationTask)
                    .build();

            DescribeMigrationTaskResponse migrationTaskResponse = migrationClient
                    .describeMigrationTask(migrationTaskRequestRequest);
            System.out.println("The name is " + migrationTaskResponse.migrationTask().migrationTaskName());

        } catch (MigrationHubException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeMigrationTask](https://docs.aws.amazon.com/goto/SdkForJavaV2/migration-hub-2017-05-31/DescribeMigrationTask)」を参照してください。

### `ImportMigrationTask`
<a name="migration-hub_ImportMigrationTask_java_2_topic"></a>

次のコード例は、`ImportMigrationTask` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/migrationhub#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.migrationhub.MigrationHubClient;
import software.amazon.awssdk.services.migrationhub.model.CreateProgressUpdateStreamRequest;
import software.amazon.awssdk.services.migrationhub.model.ImportMigrationTaskRequest;
import software.amazon.awssdk.services.migrationhub.model.MigrationHubException;

/**
 * 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 ImportMigrationTask {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <migrationTask> <progressStream>\s

                Where:
                    migrationTask - the name of a migration task.\s
                    progressStream - the name of a progress stream.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String migrationTask = args[0];
        String progressStream = args[1];
        Region region = Region.US_WEST_2;
        MigrationHubClient migrationClient = MigrationHubClient.builder()
                .region(region)
                .build();

        importMigrTask(migrationClient, migrationTask, progressStream);
        migrationClient.close();
    }

    public static void importMigrTask(MigrationHubClient migrationClient, String migrationTask, String progressStream) {
        try {
            CreateProgressUpdateStreamRequest progressUpdateStreamRequest = CreateProgressUpdateStreamRequest.builder()
                    .progressUpdateStreamName(progressStream)
                    .dryRun(false)
                    .build();

            migrationClient.createProgressUpdateStream(progressUpdateStreamRequest);
            ImportMigrationTaskRequest migrationTaskRequest = ImportMigrationTaskRequest.builder()
                    .migrationTaskName(migrationTask)
                    .progressUpdateStream(progressStream)
                    .dryRun(false)
                    .build();

            migrationClient.importMigrationTask(migrationTaskRequest);

        } catch (MigrationHubException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  *API の詳細については、「AWS SDK for Java 2.x API リファレンス*」の「[ImportMigrationTask](https://docs.aws.amazon.com/goto/SdkForJavaV2/migration-hub-2017-05-31/ImportMigrationTask)」を参照してください。

### `ListApplications`
<a name="migration-hub_ListApplications_java_2_topic"></a>

次のコード例は、`ListApplications` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/migrationhub#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.migrationhub.MigrationHubClient;
import software.amazon.awssdk.services.migrationhub.model.ApplicationState;
import software.amazon.awssdk.services.migrationhub.model.ListApplicationStatesRequest;
import software.amazon.awssdk.services.migrationhub.model.ListApplicationStatesResponse;
import software.amazon.awssdk.services.migrationhub.model.MigrationHubException;
import java.util.List;

/**
 * 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 ListApplications {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        MigrationHubClient migrationClient = MigrationHubClient.builder()
                .region(region)
                .build();

        listApps(migrationClient);
        migrationClient.close();
    }

    public static void listApps(MigrationHubClient migrationClient) {
        try {
            ListApplicationStatesRequest applicationStatesRequest = ListApplicationStatesRequest.builder()
                    .maxResults(10)
                    .build();

            ListApplicationStatesResponse response = migrationClient.listApplicationStates(applicationStatesRequest);
            List<ApplicationState> apps = response.applicationStateList();
            for (ApplicationState appState : apps) {
                System.out.println("App Id is " + appState.applicationId());
                System.out.println("The status is " + appState.applicationStatus().toString());
            }

        } catch (MigrationHubException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*の「[ListApplications](https://docs.aws.amazon.com/goto/SdkForJavaV2/migration-hub-2017-05-31/ListApplications)」を参照してください。

### `ListCreatedArtifacts`
<a name="migration-hub_ListCreatedArtifacts_java_2_topic"></a>

次のコード例は、`ListCreatedArtifacts` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/migrationhub#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.migrationhub.MigrationHubClient;
import software.amazon.awssdk.services.migrationhub.model.CreatedArtifact;
import software.amazon.awssdk.services.migrationhub.model.ListCreatedArtifactsRequest;
import software.amazon.awssdk.services.migrationhub.model.ListCreatedArtifactsResponse;
import software.amazon.awssdk.services.migrationhub.model.MigrationHubException;
import java.util.List;

/**
 * To run this Java V2 code example, ensure that you have setup 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 ListCreatedArtifacts {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        MigrationHubClient migrationClient = MigrationHubClient.builder()
                .region(region)
                .build();

        listArtifacts(migrationClient);
        migrationClient.close();
    }

    public static void listArtifacts(MigrationHubClient migrationClient) {
        try {
            ListCreatedArtifactsRequest listCreatedArtifactsRequest = ListCreatedArtifactsRequest.builder()
                    .maxResults(10)
                    .migrationTaskName("SampleApp5")
                    .progressUpdateStream("ProgressSteamB")
                    .build();

            ListCreatedArtifactsResponse response = migrationClient.listCreatedArtifacts(listCreatedArtifactsRequest);
            List<CreatedArtifact> apps = response.createdArtifactList();
            for (CreatedArtifact artifact : apps) {
                System.out.println("APp Id is " + artifact.description());
                System.out.println("The name is " + artifact.name());
            }

        } catch (MigrationHubException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListCreatedArtifacts](https://docs.aws.amazon.com/goto/SdkForJavaV2/migration-hub-2017-05-31/ListCreatedArtifacts)」を参照してください。

### `ListMigrationTasks`
<a name="migration-hub_ListMigrationTasks_java_2_topic"></a>

次のコード例は、`ListMigrationTasks` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/migrationhub#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.migrationhub.MigrationHubClient;
import software.amazon.awssdk.services.migrationhub.model.ListMigrationTasksRequest;
import software.amazon.awssdk.services.migrationhub.model.ListMigrationTasksResponse;
import software.amazon.awssdk.services.migrationhub.model.MigrationTaskSummary;
import software.amazon.awssdk.services.migrationhub.model.MigrationHubException;
import java.util.List;

/**
 * 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 ListMigrationTasks {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        MigrationHubClient migrationClient = MigrationHubClient.builder()
                .region(region)
                .build();

        listMigrTasks(migrationClient);
        migrationClient.close();
    }

    public static void listMigrTasks(MigrationHubClient migrationClient) {
        try {
            ListMigrationTasksRequest listMigrationTasksRequest = ListMigrationTasksRequest.builder()
                    .maxResults(10)
                    .build();

            ListMigrationTasksResponse response = migrationClient.listMigrationTasks(listMigrationTasksRequest);
            List<MigrationTaskSummary> migrationList = response.migrationTaskSummaryList();
            for (MigrationTaskSummary migration : migrationList) {
                System.out.println("Migration task name is " + migration.migrationTaskName());
                System.out.println("The Progress update stream is " + migration.progressUpdateStream());
            }

        } catch (MigrationHubException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListMigrationTasks](https://docs.aws.amazon.com/goto/SdkForJavaV2/migration-hub-2017-05-31/ListMigrationTasks)」を参照してください。

# SDK for Java 2.x を使用する Amazon MSK の例
<a name="java_2_kafka_code_examples"></a>

次のコード例は、Amazon MSK AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_java_2_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での Amazon MSK イベントの消費。  

```
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.KafkaEvent;
import com.amazonaws.services.lambda.runtime.events.KafkaEvent.KafkaEventRecord;

import java.util.Base64;
import java.util.Map;

public class Example implements RequestHandler<KafkaEvent, Void> {

    @Override
    public Void handleRequest(KafkaEvent event, Context context) {
        for (Map.Entry<String, java.util.List<KafkaEventRecord>> entry : event.getRecords().entrySet()) {
            String key = entry.getKey();
            System.out.println("Key: " + key);

            for (KafkaEventRecord record : entry.getValue()) {
                System.out.println("Record: " + record);

                byte[] value = Base64.getDecoder().decode(record.getValue());
                String message = new String(value);
                System.out.println("Message: " + message);
            }
        }

        return null;
    }
}
```

# SDK for Java 2.x を使用した Neptune の例
<a name="java_2_neptune_code_examples"></a>

次のコード例は、Neptune AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Neptune
<a name="neptune_Hello_java_2_topic"></a>

次のコード例は、Neptune の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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 HelloNeptune {
    public static void main(String[] args) {
        NeptuneAsyncClient neptuneClient = NeptuneAsyncClient.create();
        describeDbCluster(neptuneClient).join(); // This ensures the async code runs to completion
    }

    /**
     * Describes the Amazon Neptune DB clusters.
     *
     * @param neptuneClient the Neptune asynchronous client used to make the request
     * @return a {@link CompletableFuture} that completes when the operation is finished
     */
    public static CompletableFuture<Void> describeDbCluster(NeptuneAsyncClient neptuneClient) {
        DescribeDbClustersRequest request = DescribeDbClustersRequest.builder()
                .maxRecords(20)
                .build();

        SdkPublisher<DescribeDbClustersResponse> paginator = neptuneClient.describeDBClustersPaginator(request);
        CompletableFuture<Void> future = new CompletableFuture<>();

        paginator.subscribe(new Subscriber<DescribeDbClustersResponse>() {
            private Subscription subscription;

            @Override
            public void onSubscribe(Subscription s) {
                this.subscription = s;
                s.request(Long.MAX_VALUE); // request all items
            }

            @Override
            public void onNext(DescribeDbClustersResponse response) {
                response.dbClusters().forEach(cluster -> {
                    System.out.println("Cluster Identifier: " + cluster.dbClusterIdentifier());
                    System.out.println("Status: " + cluster.status());
                });
            }

            @Override
            public void onError(Throwable t) {
                future.completeExceptionally(t);
            }

            @Override
            public void onComplete() {
                future.complete(null);
            }
        });

        return future.whenComplete((result, throwable) -> {
            neptuneClient.close();
            if (throwable != null) {
                System.err.println("Error describing DB clusters: " + throwable.getMessage());
            }
        });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeDBClustersPaginator](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DescribeDBClustersPaginator)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="neptune_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Neptune サブネットグループを作成します。
+ Neptune クラスターを作成します。
+ Neptune インスタンスを作成します。
+ Neptune インスタンスのステータスをチェックします。
+ Neptune クラスターの詳細を表示します。
+ Neptune クラスターを停止します。
+ Neptune クラスターを起動します。
+ Neptune アセットを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。
Neptune 機能を実証するインタラクティブなシナリオを実行します。  

```
public class NeptuneScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final Logger logger = LoggerFactory.getLogger(NeptuneScenario.class);
    static Scanner scanner = new Scanner(System.in);
    static NeptuneActions neptuneActions = new NeptuneActions();

    public static void main(String[] args) {
        final String usage =
                """
                Usage:
                    <subnetGroupName> <clusterName> <dbInstanceId>
                
                Where:
                    subnetGroupName - The name of an existing Neptune DB subnet group that includes subnets in at least two Availability Zones.
                    clusterName     - The unique identifier for the Neptune DB cluster.
                    dbInstanceId    - The identifier for a specific Neptune DB instance within the cluster.
                """;
        String subnetGroupName = "neptuneSubnetGroup65";
        String clusterName = "neptuneCluster65";
        String dbInstanceId = "neptuneDB65";

        logger.info("""
                   Amazon Neptune is a fully managed graph 
                   database service by AWS, designed specifically
                   for handling complex relationships and connected 
                   datasets at scale. It supports two popular graph models: 
                   property graphs (via openCypher and Gremlin) and RDF 
                   graphs (via SPARQL). This makes Neptune ideal for 
                   use cases such as knowledge graphs, fraud detection, 
                   social networking, recommendation engines, and 
                   network management, where relationships between 
                   entities are central to the data.
                    
                   Being fully managed, Neptune handles database 
                   provisioning, patching, backups, and replication, 
                   while also offering high availability and durability 
                   within AWS's infrastructure.
                    
                   For developers, programming with Neptune allows 
                   for building intelligent, relationship-aware 
                   applications that go beyond traditional tabular 
                   databases. Developers can use the AWS SDK for Java 
                   to automate infrastructure operations (via NeptuneClient). 
                    
                    Let's get started...
                    """);
        waitForInputToContinue(scanner);
        runScenario(subnetGroupName, dbInstanceId, clusterName);
    }

    public static void runScenario(String subnetGroupName, String dbInstanceId, String clusterName) {
        logger.info(DASHES);
        logger.info("1. Create a Neptune DB Subnet Group");
        logger.info("The Neptune DB subnet group is used when launching a Neptune cluster");
        waitForInputToContinue(scanner);
        try {
            neptuneActions.createSubnetGroupAsync(subnetGroupName).join();

        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ServiceQuotaExceededException) {
                logger.error("The request failed due to service quota exceeded: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. Create a Neptune Cluster");
        logger.info("A Neptune Cluster allows you to store and query highly connected datasets with low latency.");
        waitForInputToContinue(scanner);
        String dbClusterId;
        try {
            dbClusterId = neptuneActions.createDBClusterAsync(clusterName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ServiceQuotaExceededException) {
                logger.error("The request failed due to service quota exceeded: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }

        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("3. Create a Neptune DB Instance");
        logger.info("In this step, we add a new database instance to the Neptune cluster");
        waitForInputToContinue(scanner);
        try {
        neptuneActions.createDBInstanceAsync(dbInstanceId, dbClusterId).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ServiceQuotaExceededException) {
                logger.error("The request failed due to service quota exceeded: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. Check the status of the Neptune DB Instance");
        logger.info("""
                    In this step, we will wait until the DB instance 
                    becomes available. This may take around 10 minutes.
                    """);
        waitForInputToContinue(scanner);
        try {
            neptuneActions.checkInstanceStatus(dbInstanceId, "available").join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            logger.error("An unexpected error occurred.", cause);
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5.Show Neptune Cluster details");
        waitForInputToContinue(scanner);
        try {
            neptuneActions.describeDBClustersAsync(clusterName).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("The request failed due to the resource not found: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("6. Stop the Amazon Neptune cluster");
        logger.info("""
                    Once stopped, this step polls the status 
                    until the cluster is in a stopped state.
                    """);
        waitForInputToContinue(scanner);
        try {
            neptuneActions.stopDBClusterAsync(dbClusterId);
            neptuneActions.waitForClusterStatus(dbClusterId, "stopped");
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("The request failed due to the resource not found: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Start the Amazon Neptune cluster");
        logger.info("""
                    Once started, this step polls the clusters 
                    status until it's in an available state.
                    We will also poll the instance status.
                    """);
        waitForInputToContinue(scanner);
        try {
            neptuneActions.startDBClusterAsync(dbClusterId);
            neptuneActions.waitForClusterStatus(dbClusterId, "available");
            neptuneActions.checkInstanceStatus(dbInstanceId, "available").join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof ResourceNotFoundException) {
                logger.error("The request failed due to the resource not found: {}", cause.getMessage());
            } else {
                logger.error("An unexpected error occurred.", cause);
            }
            return;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("8. Delete the Neptune Assets");
        logger.info("Would you like to delete the Neptune Assets? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            logger.info("You selected to delete the Neptune assets.");
            try {
                neptuneActions.deleteNeptuneResourcesAsync(dbInstanceId, clusterName, subnetGroupName);
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof ResourceNotFoundException) {
                    logger.error("The request failed due to the resource not found: {}", cause.getMessage());
                } else {
                    logger.error("An unexpected error occurred.", cause);
                }
                return;
            }
        } else {
            logger.info("You selected not to delete Neptune assets.");
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info(
                """
                Thank you for checking out the Amazon Neptune Service Use demo. We hope you
                learned something new, or got some inspiration for your own apps today.
                For more AWS code examples, have a look at:
                https://docs.aws.amazon.com/code-library/latest/ug/what-is-code-library.html
                """);
        logger.info(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
Neptune SDK メソッドのラッパークラス。  

```
public class NeptuneActions {
    private CompletableFuture<Void> instanceCheckFuture;
    private static NeptuneAsyncClient neptuneAsyncClient;
    private final Region region = Region.US_EAST_1;
    private static final Logger logger = LoggerFactory.getLogger(NeptuneActions.class);
    private final NeptuneClient neptuneClient = NeptuneClient.builder().region(region).build();

    /**
     * Retrieves an instance of the NeptuneAsyncClient.
     * <p>
     * This method initializes and returns a singleton instance of the NeptuneAsyncClient. The client
     * is configured with the following settings:
     * <ul>
     *     <li>Maximum concurrency: 100</li>
     *     <li>Connection timeout: 60 seconds</li>
     *     <li>Read timeout: 60 seconds</li>
     *     <li>Write timeout: 60 seconds</li>
     *     <li>API call timeout: 2 minutes</li>
     *     <li>API call attempt timeout: 90 seconds</li>
     *     <li>Retry strategy: STANDARD</li>
     * </ul>
     * The client is built using the NettyNioAsyncHttpClient.
     *
     * @return the singleton instance of the NeptuneAsyncClient
     */
    private static NeptuneAsyncClient getAsyncClient() {
        if (neptuneAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                    .maxConcurrency(100)
                    .connectionTimeout(Duration.ofSeconds(60))
                    .readTimeout(Duration.ofSeconds(60))
                    .writeTimeout(Duration.ofSeconds(60))
                    .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                    .apiCallTimeout(Duration.ofMinutes(2))
                    .apiCallAttemptTimeout(Duration.ofSeconds(90))
                    .retryStrategy(RetryMode.STANDARD)
                    .build();

            neptuneAsyncClient = NeptuneAsyncClient.builder()
                    .httpClient(httpClient)
                    .overrideConfiguration(overrideConfig)
                    .build();
        }
        return neptuneAsyncClient;
    }

    /**
     * Asynchronously deletes a set of Amazon Neptune resources in a defined order.
     * <p>
     * The method performs the following operations in sequence:
     * <ol>
     *     <li>Deletes the Neptune DB instance identified by {@code dbInstanceId}.</li>
     *     <li>Waits until the DB instance is fully deleted.</li>
     *     <li>Deletes the Neptune DB cluster identified by {@code dbClusterId}.</li>
     *     <li>Deletes the Neptune DB subnet group identified by {@code subnetGroupName}.</li>
     * </ol>
     * <p>
     * If any step fails, the subsequent operations are not performed, and the exception
     * is logged. This method blocks the calling thread until all operations complete.
     *
     * @param dbInstanceId      the ID of the Neptune DB instance to delete
     * @param dbClusterId       the ID of the Neptune DB cluster to delete
     * @param subnetGroupName   the name of the Neptune DB subnet group to delete
     */
    public void deleteNeptuneResourcesAsync(String dbInstanceId, String dbClusterId, String subnetGroupName) {
        deleteDBInstanceAsync(dbInstanceId)
                .thenCompose(v -> waitUntilInstanceDeletedAsync(dbInstanceId))
                .thenCompose(v -> deleteDBClusterAsync(dbClusterId))
                .thenCompose(v -> deleteDBSubnetGroupAsync(subnetGroupName))
                .whenComplete((v, ex) -> {
                    if (ex != null) {
                        logger.info("Failed to delete Neptune resources: " + ex.getMessage());
                    } else {
                        logger.info("Neptune resources deleted successfully.");
                    }
                })
                .join(); // Waits for the entire async chain to complete
    }

    /**
     * Deletes a subnet group.
     *
     * @param subnetGroupName the identifier of the subnet group to delete
     * @return a {@link CompletableFuture} that completes when the cluster has been deleted
     */
    public CompletableFuture<Void> deleteDBSubnetGroupAsync(String subnetGroupName) {
        DeleteDbSubnetGroupRequest request = DeleteDbSubnetGroupRequest.builder()
                .dbSubnetGroupName(subnetGroupName)
                .build();

        return getAsyncClient().deleteDBSubnetGroup(request)
                .thenAccept(response -> logger.info("🗑️ Deleting Subnet Group: " + subnetGroupName));
    }

    /**
     * Deletes a DB instance asynchronously.
     *
     * @param clusterId the identifier of the cluster to delete
     * @return a {@link CompletableFuture} that completes when the cluster has been deleted
     */
    public CompletableFuture<Void> deleteDBClusterAsync(String clusterId) {
        DeleteDbClusterRequest request = DeleteDbClusterRequest.builder()
                .dbClusterIdentifier(clusterId)
                .skipFinalSnapshot(true)
                .build();

        return getAsyncClient().deleteDBCluster(request)
                .thenAccept(response -> System.out.println("🗑️ Deleting DB Cluster: " + clusterId));
    }

    public CompletableFuture<Void> waitUntilInstanceDeletedAsync(String instanceId) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        long startTime = System.currentTimeMillis();
        checkInstanceDeletedRecursive(instanceId, startTime, future);
        return future;
    }

    /**
     * Deletes a DB instance asynchronously.
     *
     * @param instanceId the identifier of the DB instance to be deleted
     * @return a {@link CompletableFuture} that completes when the DB instance has been deleted
     */
    public CompletableFuture<Void> deleteDBInstanceAsync(String instanceId) {
        DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder()
                .dbInstanceIdentifier(instanceId)
                .skipFinalSnapshot(true)
                .build();

        return getAsyncClient().deleteDBInstance(request)
                .thenAccept(response -> System.out.println("🗑️ Deleting DB Instance: " + instanceId));
    }


    private void checkInstanceDeletedRecursive(String instanceId, long startTime, CompletableFuture<Void> future) {
        DescribeDbInstancesRequest request = DescribeDbInstancesRequest.builder()
                .dbInstanceIdentifier(instanceId)
                .build();

        getAsyncClient().describeDBInstances(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof NeptuneException &&
                                ((NeptuneException) cause).awsErrorDetails().errorCode().equals("DBInstanceNotFound")) {
                            long elapsed = (System.currentTimeMillis() - startTime) / 1000;
                            logger.info("\r Instance %s deleted after %ds%n", instanceId, elapsed);
                            future.complete(null);
                            return;
                        }
                        future.completeExceptionally(new CompletionException("Error polling DB instance", cause));
                        return;
                    }

                    String status = response.dbInstances().get(0).dbInstanceStatus();
                    long elapsed = (System.currentTimeMillis() - startTime) / 1000;
                    System.out.printf("\r  Waiting: Instance %s status: %-10s (%ds elapsed)", instanceId, status, elapsed);
                    System.out.flush();

                    CompletableFuture.delayedExecutor(20, TimeUnit.SECONDS)
                            .execute(() -> checkInstanceDeletedRecursive(instanceId, startTime, future));
                });
    }


    public void waitForClusterStatus(String clusterId, String desiredStatus) {
        System.out.printf("Waiting for cluster '%s' to reach status '%s'...\n", clusterId, desiredStatus);
        CompletableFuture<Void> future = new CompletableFuture<>();
        checkClusterStatusRecursive(clusterId, desiredStatus, System.currentTimeMillis(), future);
        future.join();
    }

    private void checkClusterStatusRecursive(String clusterId, String desiredStatus, long startTime, CompletableFuture<Void> future) {
        DescribeDbClustersRequest request = DescribeDbClustersRequest.builder()
                .dbClusterIdentifier(clusterId)
                .build();

        getAsyncClient().describeDBClusters(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        future.completeExceptionally(
                                new CompletionException("Error checking Neptune cluster status", cause)
                        );
                        return;
                    }

                    List<DBCluster> clusters = response.dbClusters();
                    if (clusters.isEmpty()) {
                        future.completeExceptionally(new RuntimeException("Cluster not found: " + clusterId));
                        return;
                    }

                    String currentStatus = clusters.get(0).status();
                    long elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000;
                    System.out.printf("\r Elapsed: %-20s  Cluster status: %-20s", formatElapsedTime((int) elapsedSeconds), currentStatus);
                    System.out.flush();

                    if (desiredStatus.equalsIgnoreCase(currentStatus)) {
                        System.out.printf("\r Neptune cluster reached desired status '%s' after %s.\n", desiredStatus, formatElapsedTime((int) elapsedSeconds));
                        future.complete(null);
                    } else {
                        CompletableFuture.delayedExecutor(20, TimeUnit.SECONDS)
                                .execute(() -> checkClusterStatusRecursive(clusterId, desiredStatus, startTime, future));
                    }
                });
    }


    /**
     * Starts an Amazon Neptune DB cluster.
     *
     * @param clusterIdentifier the unique identifier of the DB cluster to be stopped
     */
    public CompletableFuture<StartDbClusterResponse> startDBClusterAsync(String clusterIdentifier) {
        StartDbClusterRequest clusterRequest = StartDbClusterRequest.builder()
                .dbClusterIdentifier(clusterIdentifier)
                .build();

        return getAsyncClient().startDBCluster(clusterRequest)
                .whenComplete((response, error) -> {
                    if (error != null) {
                        Throwable cause = error.getCause() != null ? error.getCause() : error;

                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }

                        throw new RuntimeException("Failed to start DB cluster: " + cause.getMessage(), cause);
                    } else {
                        logger.info("DB Cluster starting: " + clusterIdentifier);
                    }
                });
    }

    /**
     * Stops an Amazon Neptune DB cluster.
     *
     * @param clusterIdentifier the unique identifier of the DB cluster to be stopped
     */
    public CompletableFuture<StopDbClusterResponse> stopDBClusterAsync(String clusterIdentifier) {
        StopDbClusterRequest clusterRequest = StopDbClusterRequest.builder()
                .dbClusterIdentifier(clusterIdentifier)
                .build();

        return getAsyncClient().stopDBCluster(clusterRequest)
                .whenComplete((response, error) -> {
                    if (error != null) {
                        Throwable cause = error.getCause() != null ? error.getCause() : error;

                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }

                        throw new RuntimeException("Failed to stop DB cluster: " + cause.getMessage(), cause);
                    } else {
                        logger.info("DB Cluster stopped: " + clusterIdentifier);
                    }
                });
    }



    /**
     * Asynchronously describes the specified Amazon RDS DB cluster.
     *
     * @param clusterId the identifier of the DB cluster to describe
     * @return a {@link CompletableFuture} that completes when the operation is done, or throws a {@link RuntimeException}
     * if an error occurs
     */
    public CompletableFuture<Void> describeDBClustersAsync(String clusterId) {
        DescribeDbClustersRequest request = DescribeDbClustersRequest.builder()
                .dbClusterIdentifier(clusterId)
                .build();

        return getAsyncClient().describeDBClusters(request)
                .thenAccept(response -> {
                    for (DBCluster cluster : response.dbClusters()) {
                        logger.info("Cluster Identifier: " + cluster.dbClusterIdentifier());
                        logger.info("Status: " + cluster.status());
                        logger.info("Engine: " + cluster.engine());
                        logger.info("Engine Version: " + cluster.engineVersion());
                        logger.info("Endpoint: " + cluster.endpoint());
                        logger.info("Reader Endpoint: " + cluster.readerEndpoint());
                        logger.info("Availability Zones: " + cluster.availabilityZones());
                        logger.info("Subnet Group: " + cluster.dbSubnetGroup());
                        logger.info("VPC Security Groups:");
                        cluster.vpcSecurityGroups().forEach(vpcGroup ->
                                logger.info("  - " + vpcGroup.vpcSecurityGroupId()));
                        logger.info("Storage Encrypted: " + cluster.storageEncrypted());
                        logger.info("IAM DB Auth Enabled: " + cluster.iamDatabaseAuthenticationEnabled());
                        logger.info("Backup Retention Period: " + cluster.backupRetentionPeriod() + " days");
                        logger.info("Preferred Backup Window: " + cluster.preferredBackupWindow());
                        logger.info("Preferred Maintenance Window: " + cluster.preferredMaintenanceWindow());
                        logger.info("------");
                    }
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ResourceNotFoundException) {
                        throw (ResourceNotFoundException) cause;
                    }

                    throw new RuntimeException("Failed to describe the DB cluster: " + cause.getMessage(), cause);
                });
    }


    public CompletableFuture<Void> checkInstanceStatus(String instanceId, String desiredStatus) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        long startTime = System.currentTimeMillis();
        checkStatusRecursive(instanceId, desiredStatus.toLowerCase(), startTime, future);
        return future;
    }

    /**
     * Checks the status of a Neptune instance recursively until the desired status is reached or a timeout occurs.
     *
     * @param instanceId     the ID of the Neptune instance to check
     * @param desiredStatus  the desired status of the Neptune instance
     * @param startTime      the start time of the operation, used to calculate the elapsed time
     * @param future         a {@link CompletableFuture} that will be completed when the desired status is reached
     */
    private void checkStatusRecursive(String instanceId, String desiredStatus, long startTime, CompletableFuture<Void> future) {
        DescribeDbInstancesRequest request = DescribeDbInstancesRequest.builder()
                .dbInstanceIdentifier(instanceId)
                .build();

        getAsyncClient().describeDBInstances(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        future.completeExceptionally(
                                new CompletionException("Error checking Neptune instance status", cause)
                        );
                        return;
                    }

                    List<DBInstance> instances = response.dbInstances();
                    if (instances.isEmpty()) {
                        future.completeExceptionally(new RuntimeException("Instance not found: " + instanceId));
                        return;
                    }

                    String currentStatus = instances.get(0).dbInstanceStatus();
                    long elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000;
                    System.out.printf("\r Elapsed: %-20s  Status: %-20s", formatElapsedTime((int) elapsedSeconds), currentStatus);
                    System.out.flush();

                    if (desiredStatus.equalsIgnoreCase(currentStatus)) {
                        System.out.printf("\r Neptune instance reached desired status '%s' after %s.\n", desiredStatus, formatElapsedTime((int) elapsedSeconds));
                        future.complete(null);
                    } else {
                        CompletableFuture.delayedExecutor(20, TimeUnit.SECONDS)
                                .execute(() -> checkStatusRecursive(instanceId, desiredStatus, startTime, future));
                    }
                });
    }


    private String formatElapsedTime(int seconds) {
        int minutes = seconds / 60;
        int remainingSeconds = seconds % 60;

        if (minutes > 0) {
            return minutes + (minutes == 1 ? " min" : " mins") + ", " +
                    remainingSeconds + (remainingSeconds == 1 ? " sec" : " secs");
        } else {
            return remainingSeconds + (remainingSeconds == 1 ? " sec" : " secs");
        }
    }


    /**
     * Creates a new Amazon Neptune DB instance asynchronously.
     *
     * @param dbInstanceId the identifier for the new DB instance
     * @param dbClusterId  the identifier for the DB cluster that the new instance will be a part of
     * @return a {@link CompletableFuture} that completes with the identifier of the newly created DB instance
     * @throws CompletionException if the operation fails, with a cause of either:
     *                             - {@link ServiceQuotaExceededException} if the request would exceed the maximum quota, or
     *                             - a general exception with the failure message
     */
    public CompletableFuture<String> createDBInstanceAsync(String dbInstanceId, String dbClusterId) {
        CreateDbInstanceRequest request = CreateDbInstanceRequest.builder()
                .dbInstanceIdentifier(dbInstanceId)
                .dbInstanceClass("db.r5.large")
                .engine("neptune")
                .dbClusterIdentifier(dbClusterId)
                .build();

        return getAsyncClient().createDBInstance(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ServiceQuotaExceededException) {
                            throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                        }
                        throw new CompletionException("Failed to create Neptune DB instance: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> {
                    String instanceId = response.dbInstance().dbInstanceIdentifier();
                    logger.info("Created Neptune DB Instance: " + instanceId);
                    return instanceId;
                });
    }


    /**
     * Creates a new Amazon Neptune DB cluster asynchronously.
     *
     * @param dbName the name of the DB cluster to be created
     * @return a CompletableFuture that, when completed, provides the ID of the created DB cluster
     * @throws CompletionException if the operation fails for any reason, including if the request would exceed the maximum quota
     */
    public CompletableFuture<String> createDBClusterAsync(String dbName) {
        CreateDbClusterRequest request = CreateDbClusterRequest.builder()
                .dbClusterIdentifier(dbName)
                .engine("neptune")
                .deletionProtection(false)
                .backupRetentionPeriod(1)
                .build();

        return getAsyncClient().createDBCluster(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ServiceQuotaExceededException) {
                            throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                        }
                        throw new CompletionException("Failed to create Neptune DB cluster: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> {
                    String clusterId = response.dbCluster().dbClusterIdentifier();
                    logger.info("DB Cluster created: " + clusterId);
                    return clusterId;
                });
    }


    /**
     * Creates a new DB subnet group asynchronously.
     *
     * @param groupName the name of the subnet group to create
     * @return a CompletableFuture that, when completed, returns the Amazon Resource Name (ARN) of the created subnet group
     * @throws CompletionException if the operation fails, with a cause that may be a ServiceQuotaExceededException if the request would exceed the maximum quota
     */
    public CompletableFuture<String> createSubnetGroupAsync(String groupName) {

        // Get the Amazon Virtual Private Cloud (VPC) where the Neptune cluster and resources will be created
        String vpcId = getDefaultVpcId();
        logger.info("VPC is : " + vpcId);

        List<String> subnetList = getSubnetIds(vpcId);
        for (String subnetId : subnetList) {
            System.out.println("Subnet group:" +subnetId);
        }

        CreateDbSubnetGroupRequest request = CreateDbSubnetGroupRequest.builder()
                .dbSubnetGroupName(groupName)
                .dbSubnetGroupDescription("Subnet group for Neptune cluster")
                .subnetIds(subnetList)
                .build();

        return getAsyncClient().createDBSubnetGroup(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ServiceQuotaExceededException) {
                            throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                        }
                        throw new CompletionException("Failed to create subnet group: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> {
                    String name = response.dbSubnetGroup().dbSubnetGroupName();
                    String arn = response.dbSubnetGroup().dbSubnetGroupArn();
                    logger.info("Subnet group created: " + name);
                    return arn;
                });
    }

    private List<String> getSubnetIds(String vpcId) {
        try (Ec2Client ec2 = Ec2Client.builder().region(region).build()) {
            DescribeSubnetsRequest request = DescribeSubnetsRequest.builder()
                    .filters(builder -> builder.name("vpc-id").values(vpcId))
                    .build();

            DescribeSubnetsResponse response = ec2.describeSubnets(request);
            return response.subnets().stream()
                    .map(Subnet::subnetId)
                    .collect(Collectors.toList());
        }
    }

    public static String getDefaultVpcId() {
        Ec2Client ec2 = Ec2Client.builder()
                .region(Region.US_EAST_1)
                .build();

        Filter myFilter = Filter.builder()
                .name("isDefault")
                .values("true")
                .build();

        List<Filter> filterList = new ArrayList<>();
        filterList.add(myFilter);

        DescribeVpcsRequest request = DescribeVpcsRequest.builder()
                .filters(filterList)
                .build();


        DescribeVpcsResponse response = ec2.describeVpcs(request);
        if (!response.vpcs().isEmpty()) {
            Vpc defaultVpc = response.vpcs().get(0);
            return defaultVpc.vpcId();
        } else {
            throw new RuntimeException("No default VPC found in this region.");
        }
    }
}
```
+ API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の以下のトピックを参照してください。
  + [CreateDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateDBCluster)
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateDBInstance)
  + [CreateDBSubnetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateDBSubnetGroup)
  + [CreateGraph](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateGraph)
  + [DeleteDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DeleteDBCluster)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DeleteDBInstance)
  + [DeleteDBSubnetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DeleteDBSubnetGroup)
  + [DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DescribeDBClusters)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DescribeDBInstances)
  + [ExecuteGremlinProfileQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteGremlinProfileQuery)
  + [ExecuteGremlinQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteGremlinQuery)
  + [ExecuteOpenCypherExplainQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteOpenCypherExplainQuery)
  + [ExecuteQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteQuery)
  + [StartDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/StartDBCluster)
  + [StopDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/StopDBCluster)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="neptune_CreateDBCluster_java_2_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new Amazon Neptune DB cluster asynchronously.
     *
     * @param dbName the name of the DB cluster to be created
     * @return a CompletableFuture that, when completed, provides the ID of the created DB cluster
     * @throws CompletionException if the operation fails for any reason, including if the request would exceed the maximum quota
     */
    public CompletableFuture<String> createDBClusterAsync(String dbName) {
        CreateDbClusterRequest request = CreateDbClusterRequest.builder()
                .dbClusterIdentifier(dbName)
                .engine("neptune")
                .deletionProtection(false)
                .backupRetentionPeriod(1)
                .build();

        return getAsyncClient().createDBCluster(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ServiceQuotaExceededException) {
                            throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                        }
                        throw new CompletionException("Failed to create Neptune DB cluster: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> {
                    String clusterId = response.dbCluster().dbClusterIdentifier();
                    logger.info("DB Cluster created: " + clusterId);
                    return clusterId;
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateDBCluster)」を参照してください。

### `CreateDBInstance`
<a name="neptune_CreateDBInstance_java_2_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new Amazon Neptune DB instance asynchronously.
     *
     * @param dbInstanceId the identifier for the new DB instance
     * @param dbClusterId  the identifier for the DB cluster that the new instance will be a part of
     * @return a {@link CompletableFuture} that completes with the identifier of the newly created DB instance
     * @throws CompletionException if the operation fails, with a cause of either:
     *                             - {@link ServiceQuotaExceededException} if the request would exceed the maximum quota, or
     *                             - a general exception with the failure message
     */
    public CompletableFuture<String> createDBInstanceAsync(String dbInstanceId, String dbClusterId) {
        CreateDbInstanceRequest request = CreateDbInstanceRequest.builder()
                .dbInstanceIdentifier(dbInstanceId)
                .dbInstanceClass("db.r5.large")
                .engine("neptune")
                .dbClusterIdentifier(dbClusterId)
                .build();

        return getAsyncClient().createDBInstance(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ServiceQuotaExceededException) {
                            throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                        }
                        throw new CompletionException("Failed to create Neptune DB instance: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> {
                    String instanceId = response.dbInstance().dbInstanceIdentifier();
                    logger.info("Created Neptune DB Instance: " + instanceId);
                    return instanceId;
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateDBInstance)」を参照してください。

### `CreateDBSubnetGroup`
<a name="neptune_CreateDBSubnetGroup_java_2_topic"></a>

次のコード例は、`CreateDBSubnetGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates a new DB subnet group asynchronously.
     *
     * @param groupName the name of the subnet group to create
     * @return a CompletableFuture that, when completed, returns the Amazon Resource Name (ARN) of the created subnet group
     * @throws CompletionException if the operation fails, with a cause that may be a ServiceQuotaExceededException if the request would exceed the maximum quota
     */
    public CompletableFuture<String> createSubnetGroupAsync(String groupName) {

        // Get the Amazon Virtual Private Cloud (VPC) where the Neptune cluster and resources will be created
        String vpcId = getDefaultVpcId();
        logger.info("VPC is : " + vpcId);

        List<String> subnetList = getSubnetIds(vpcId);
        for (String subnetId : subnetList) {
            System.out.println("Subnet group:" +subnetId);
        }

        CreateDbSubnetGroupRequest request = CreateDbSubnetGroupRequest.builder()
                .dbSubnetGroupName(groupName)
                .dbSubnetGroupDescription("Subnet group for Neptune cluster")
                .subnetIds(subnetList)
                .build();

        return getAsyncClient().createDBSubnetGroup(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof ServiceQuotaExceededException) {
                            throw new CompletionException("The operation was denied because the request would exceed the maximum quota.", cause);
                        }
                        throw new CompletionException("Failed to create subnet group: " + exception.getMessage(), exception);
                    }
                })
                .thenApply(response -> {
                    String name = response.dbSubnetGroup().dbSubnetGroupName();
                    String arn = response.dbSubnetGroup().dbSubnetGroupArn();
                    logger.info("Subnet group created: " + name);
                    return arn;
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDBSubnetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateDBSubnetGroup)」を参照してください。

### `CreateGraph`
<a name="neptune_CreateGraph_java_2_topic"></a>

次のコード例は、`CreateGraph` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Executes the process of creating a new Neptune graph.
     *
     * @param client        the Neptune graph client used to interact with the Neptune service
     * @param graphName     the name of the graph to be created
     * @throws NeptuneGraphException if an error occurs while creating the graph
     */
    public static void executeCreateGraph(NeptuneGraphClient client, String graphName) {
        try {
            // Create the graph request
            CreateGraphRequest request = CreateGraphRequest.builder()
                    .graphName(graphName)
                    .provisionedMemory(16)
                    .build();

            // Create the graph
            CreateGraphResponse response = client.createGraph(request);

            // Extract the graph name and ARN
            String createdGraphName = response.name();
            String graphArn = response.arn();
            String graphEndpoint = response.endpoint();

            System.out.println("Graph created successfully!");
            System.out.println("Graph Name: " + createdGraphName);
            System.out.println("Graph ARN: " + graphArn);
            System.out.println("Graph Endpoint: " +graphEndpoint );

        } catch (NeptuneGraphException e) {
            System.err.println("Failed to create graph: " + e.awsErrorDetails().errorMessage());
        } finally {
            client.close();
        }
   }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateGraph](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/CreateGraph)」を参照してください。

### `DeleteDBCluster`
<a name="neptune_DeleteDBCluster_java_2_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a DB instance asynchronously.
     *
     * @param clusterId the identifier of the cluster to delete
     * @return a {@link CompletableFuture} that completes when the cluster has been deleted
     */
    public CompletableFuture<Void> deleteDBClusterAsync(String clusterId) {
        DeleteDbClusterRequest request = DeleteDbClusterRequest.builder()
                .dbClusterIdentifier(clusterId)
                .skipFinalSnapshot(true)
                .build();

        return getAsyncClient().deleteDBCluster(request)
                .thenAccept(response -> System.out.println("🗑️ Deleting DB Cluster: " + clusterId));
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DeleteDBCluster)」を参照してください。

### `DeleteDBInstance`
<a name="neptune_DeleteDBInstance_java_2_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a DB instance asynchronously.
     *
     * @param instanceId the identifier of the DB instance to be deleted
     * @return a {@link CompletableFuture} that completes when the DB instance has been deleted
     */
    public CompletableFuture<Void> deleteDBInstanceAsync(String instanceId) {
        DeleteDbInstanceRequest request = DeleteDbInstanceRequest.builder()
                .dbInstanceIdentifier(instanceId)
                .skipFinalSnapshot(true)
                .build();

        return getAsyncClient().deleteDBInstance(request)
                .thenAccept(response -> System.out.println("🗑️ Deleting DB Instance: " + instanceId));
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DeleteDBInstance)」を参照してください。

### `DeleteDBSubnetGroup`
<a name="neptune_DeleteDBSubnetGroup_java_2_topic"></a>

次のコード例は、`DeleteDBSubnetGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes a subnet group.
     *
     * @param subnetGroupName the identifier of the subnet group to delete
     * @return a {@link CompletableFuture} that completes when the cluster has been deleted
     */
    public CompletableFuture<Void> deleteDBSubnetGroupAsync(String subnetGroupName) {
        DeleteDbSubnetGroupRequest request = DeleteDbSubnetGroupRequest.builder()
                .dbSubnetGroupName(subnetGroupName)
                .build();

        return getAsyncClient().deleteDBSubnetGroup(request)
                .thenAccept(response -> logger.info("🗑️ Deleting Subnet Group: " + subnetGroupName));
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteDBSubnetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DeleteDBSubnetGroup)」を参照してください。

### `DescribeDBClusters`
<a name="neptune_DescribeDBClusters_java_2_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously describes the specified Amazon RDS DB cluster.
     *
     * @param clusterId the identifier of the DB cluster to describe
     * @return a {@link CompletableFuture} that completes when the operation is done, or throws a {@link RuntimeException}
     * if an error occurs
     */
    public CompletableFuture<Void> describeDBClustersAsync(String clusterId) {
        DescribeDbClustersRequest request = DescribeDbClustersRequest.builder()
                .dbClusterIdentifier(clusterId)
                .build();

        return getAsyncClient().describeDBClusters(request)
                .thenAccept(response -> {
                    for (DBCluster cluster : response.dbClusters()) {
                        logger.info("Cluster Identifier: " + cluster.dbClusterIdentifier());
                        logger.info("Status: " + cluster.status());
                        logger.info("Engine: " + cluster.engine());
                        logger.info("Engine Version: " + cluster.engineVersion());
                        logger.info("Endpoint: " + cluster.endpoint());
                        logger.info("Reader Endpoint: " + cluster.readerEndpoint());
                        logger.info("Availability Zones: " + cluster.availabilityZones());
                        logger.info("Subnet Group: " + cluster.dbSubnetGroup());
                        logger.info("VPC Security Groups:");
                        cluster.vpcSecurityGroups().forEach(vpcGroup ->
                                logger.info("  - " + vpcGroup.vpcSecurityGroupId()));
                        logger.info("Storage Encrypted: " + cluster.storageEncrypted());
                        logger.info("IAM DB Auth Enabled: " + cluster.iamDatabaseAuthenticationEnabled());
                        logger.info("Backup Retention Period: " + cluster.backupRetentionPeriod() + " days");
                        logger.info("Preferred Backup Window: " + cluster.preferredBackupWindow());
                        logger.info("Preferred Maintenance Window: " + cluster.preferredMaintenanceWindow());
                        logger.info("------");
                    }
                })
                .exceptionally(ex -> {
                    Throwable cause = ex.getCause() != null ? ex.getCause() : ex;

                    if (cause instanceof ResourceNotFoundException) {
                        throw (ResourceNotFoundException) cause;
                    }

                    throw new RuntimeException("Failed to describe the DB cluster: " + cause.getMessage(), cause);
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DescribeDBClusters)」を参照してください。

### `DescribeDBInstances`
<a name="neptune_DescribeDBInstances_java_2_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Checks the status of a Neptune instance recursively until the desired status is reached or a timeout occurs.
     *
     * @param instanceId     the ID of the Neptune instance to check
     * @param desiredStatus  the desired status of the Neptune instance
     * @param startTime      the start time of the operation, used to calculate the elapsed time
     * @param future         a {@link CompletableFuture} that will be completed when the desired status is reached
     */
    private void checkStatusRecursive(String instanceId, String desiredStatus, long startTime, CompletableFuture<Void> future) {
        DescribeDbInstancesRequest request = DescribeDbInstancesRequest.builder()
                .dbInstanceIdentifier(instanceId)
                .build();

        getAsyncClient().describeDBInstances(request)
                .whenComplete((response, exception) -> {
                    if (exception != null) {
                        Throwable cause = exception.getCause();
                        future.completeExceptionally(
                                new CompletionException("Error checking Neptune instance status", cause)
                        );
                        return;
                    }

                    List<DBInstance> instances = response.dbInstances();
                    if (instances.isEmpty()) {
                        future.completeExceptionally(new RuntimeException("Instance not found: " + instanceId));
                        return;
                    }

                    String currentStatus = instances.get(0).dbInstanceStatus();
                    long elapsedSeconds = (System.currentTimeMillis() - startTime) / 1000;
                    System.out.printf("\r Elapsed: %-20s  Status: %-20s", formatElapsedTime((int) elapsedSeconds), currentStatus);
                    System.out.flush();

                    if (desiredStatus.equalsIgnoreCase(currentStatus)) {
                        System.out.printf("\r Neptune instance reached desired status '%s' after %s.\n", desiredStatus, formatElapsedTime((int) elapsedSeconds));
                        future.complete(null);
                    } else {
                        CompletableFuture.delayedExecutor(20, TimeUnit.SECONDS)
                                .execute(() -> checkStatusRecursive(instanceId, desiredStatus, startTime, future));
                    }
                });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/DescribeDBInstances)」を参照してください。

### `ExecuteGremlinProfileQuery`
<a name="neptune_ExecuteGremlinProfileQuery_java_2_topic"></a>

次のコード例は、`ExecuteGremlinProfileQuery` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Executes a Gremlin query against an Amazon Neptune database using the provided {@link NeptunedataClient}.
     *
     * @param client the {@link NeptunedataClient} instance to use for executing the Gremlin query
     */
    public static void executeGremlinQuery(NeptunedataClient client) {
        try {
            System.out.println("Querying Neptune...");
            ExecuteGremlinQueryRequest request = ExecuteGremlinQueryRequest.builder()
                    .gremlinQuery("g.V().has('code', 'ANC')")
                    .build();

            ExecuteGremlinQueryResponse response = client.executeGremlinQuery(request);

            System.out.println("Full Response:");
            System.out.println(response);

            // Retrieve and print the result
            if (response.result() != null) {
                System.out.println("Query Result:");
                System.out.println(response.result().toString());
            } else {
                System.out.println("No result returned from the query.");
            }
        } catch (NeptunedataException e) {
            System.err.println("Error calling Neptune: " + e.awsErrorDetails().errorMessage());
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
        } finally {
            client.close();
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の[ExecuteGremlinProfileQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteGremlinProfileQuery)」を参照してください。

### `ExecuteGremlinQuery`
<a name="neptune_ExecuteGremlinQuery_java_2_topic"></a>

次のコード例は、`ExecuteGremlinQuery` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Executes a Gremlin PROFILE query using the provided NeptunedataClient.
     *
     * @param client The NeptunedataClient instance to be used for executing the Gremlin PROFILE query.
     */
    private static void executeGremlinProfileQuery(NeptunedataClient client) {
        System.out.println("Executing Gremlin PROFILE query...");

        ExecuteGremlinProfileQueryRequest request = ExecuteGremlinProfileQueryRequest.builder()
                .gremlinQuery("g.V().has('code', 'ANC')")
                .build();

        ExecuteGremlinProfileQueryResponse response = client.executeGremlinProfileQuery(request);
        if (response.output() != null) {
            System.out.println("Query Profile Output:");
            System.out.println(response.output());
        } else {
            System.out.println("No output returned from the profile query.");
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ExecuteGremlinQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteGremlinQuery)」を参照してください。

### `ExecuteOpenCypherExplainQuery`
<a name="neptune_ExecuteOpenCypherExplainQuery_java_2_topic"></a>

次のコード例は、`ExecuteOpenCypherExplainQuery` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Executes an OpenCypher EXPLAIN query using the provided Neptune data client.
     *
     * @param client The Neptune data client to use for the query execution.
     */
    public static void executeGremlinQuery(NeptunedataClient client) {
        try {
            System.out.println("Executing OpenCypher EXPLAIN query...");
            ExecuteOpenCypherExplainQueryRequest request = ExecuteOpenCypherExplainQueryRequest.builder()
                    .openCypherQuery("MATCH (n {code: 'ANC'}) RETURN n")
                    .explainMode("debug")
                    .build();

            ExecuteOpenCypherExplainQueryResponse response = client.executeOpenCypherExplainQuery(request);

            if (response.results() != null) {
                System.out.println("Explain Results:");
                System.out.println(response.results().asUtf8String());
            } else {
                System.out.println("No explain results returned.");
            }

        } catch (NeptunedataException e) {
            System.err.println("Neptune error: " + e.awsErrorDetails().errorMessage());
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
        } finally {
            client.close();
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ExecuteOpenCypherExplainQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteOpenCypherExplainQuery)」を参照してください。

### `ExecuteQuery`
<a name="neptune_ExecuteQuery_java_2_topic"></a>

次のコード例は、`ExecuteQuery` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Executes a Gremlin profile query on the Neptune Analytics graph.
     *
     * @param client       the {@link NeptuneGraphClient} instance to use for the query
     * @param graphId      the identifier of the graph to execute the query on
     *
     * @throws NeptuneGraphException if an error occurs while executing the query on the Neptune Graph
     * @throws Exception if an unexpected error occurs
     */
    public static void executeGremlinProfileQuery(NeptuneGraphClient client, String graphId) {

        try {
            System.out.println("Running openCypher query on Neptune Analytics...");

            ExecuteQueryRequest request = ExecuteQueryRequest.builder()
                    .graphIdentifier(graphId)
                    .queryString("MATCH (n {code: 'ANC'}) RETURN n")
                    .language("OPEN_CYPHER")
                    .build();

            ResponseInputStream<ExecuteQueryResponse> response = client.executeQuery(request);
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, StandardCharsets.UTF_8))) {
                String result = reader.lines().collect(Collectors.joining("\n"));
                System.out.println("Query Result:");
                System.out.println(result);
            } catch (Exception e) {
                System.err.println("Error reading response: " + e.getMessage());
            }

        } catch (NeptuneGraphException e) {
            System.err.println("NeptuneGraph error: " + e.awsErrorDetails().errorMessage());
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
        } finally {
            client.close();
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ExecuteQuery](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/ExecuteQuery)」を参照してください。

### `StartDBCluster`
<a name="neptune_StartDBCluster_java_2_topic"></a>

次のコード例は、`StartDBCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Starts an Amazon Neptune DB cluster.
     *
     * @param clusterIdentifier the unique identifier of the DB cluster to be stopped
     */
    public CompletableFuture<StartDbClusterResponse> startDBClusterAsync(String clusterIdentifier) {
        StartDbClusterRequest clusterRequest = StartDbClusterRequest.builder()
                .dbClusterIdentifier(clusterIdentifier)
                .build();

        return getAsyncClient().startDBCluster(clusterRequest)
                .whenComplete((response, error) -> {
                    if (error != null) {
                        Throwable cause = error.getCause() != null ? error.getCause() : error;

                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }

                        throw new RuntimeException("Failed to start DB cluster: " + cause.getMessage(), cause);
                    } else {
                        logger.info("DB Cluster starting: " + clusterIdentifier);
                    }
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/StartDBCluster)」を参照してください。

### `StopDBCluster`
<a name="neptune_StopDBCluster_java_2_topic"></a>

次のコード例は、`StopDBCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Stops an Amazon Neptune DB cluster.
     *
     * @param clusterIdentifier the unique identifier of the DB cluster to be stopped
     */
    public CompletableFuture<StopDbClusterResponse> stopDBClusterAsync(String clusterIdentifier) {
        StopDbClusterRequest clusterRequest = StopDbClusterRequest.builder()
                .dbClusterIdentifier(clusterIdentifier)
                .build();

        return getAsyncClient().stopDBCluster(clusterRequest)
                .whenComplete((response, error) -> {
                    if (error != null) {
                        Throwable cause = error.getCause() != null ? error.getCause() : error;

                        if (cause instanceof ResourceNotFoundException) {
                            throw (ResourceNotFoundException) cause;
                        }

                        throw new RuntimeException("Failed to stop DB cluster: " + cause.getMessage(), cause);
                    } else {
                        logger.info("DB Cluster stopped: " + clusterIdentifier);
                    }
                });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StopDBCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/neptune-2014-10-31/StopDBCluster)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Neptune API を使用してグラフデータをクエリする
<a name="cross_Neptune_Query_java_2_topic"></a>

次のコード例は、Neptune API を使用してグラフデータをクエリする方法を示しています。

**SDK for Java 2.x**  
 Amazon Neptune Java API を使用して、VPC 内のグラフデータをクエリする Lambda 関数を作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_neptune_lambda) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Lambda
+ Neptune

# SDK for Java 2.x を使用したパートナーセントラルの例
<a name="java_2_partnercentral-selling_code_examples"></a>

次のコード例は、 Partner Central AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AssignOpportunity`
<a name="partnercentral-selling_AssignOpportunity_java_2_topic"></a>

次のコード例は、`AssignOpportunity` を使用する方法を示しています。

**SDK for Java 2.x**  
既存のオポチュニティを他のユーザーに再割り当てします。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.AssignOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.AssignOpportunityResponse;
import software.amazon.awssdk.services.partnercentralselling.model.AssigneeContact;

/*
Purpose
PC-API-07 Assigning a new owner
*/

public class AssignOpportunity {
	
	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();

    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	    	
    	String assigneeFirstName = "John";
    	
    	String assigneeLastName = "Doe";
    	
    	String assigneeEmail = "test@test.com";
    	
    	String businessTitle = "PartnerAccountManager";
    	
    	AssignOpportunityResponse response = getResponse(opportunityId, assigneeFirstName, assigneeLastName, assigneeEmail, businessTitle);
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

	static AssignOpportunityResponse getResponse(String opportunityId, String assigneeFirstName, String assigneeLastName, String assigneeEmail, String businessTitle) {
				
		AssignOpportunityRequest assignOpportunityRequest = AssignOpportunityRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.identifier(opportunityId)
        		.assignee(AssigneeContact.builder()
        				.firstName(assigneeFirstName)
        				.lastName(assigneeLastName)
        				.email(assigneeEmail)
        				.businessTitle(businessTitle)
        				.build())
        		.build();
        
        AssignOpportunityResponse response = client.assignOpportunity(assignOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[AssignOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/AssignOpportunity)」を参照してください。

### `AssociateOpportunity`
<a name="partnercentral-selling_AssociateOpportunity_java_2_topic"></a>

次のコード例は、`AssociateOpportunity` を使用する方法を示しています。

**SDK for Java 2.x**  
オポチュニティとさまざまな関連エンティティとの正式な関連付けを作成します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.AssociateOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.AssociateOpportunityResponse;

/*
Purpose
PC-API -11 Associating a product
PC-API -12 Associating a solution
PC-API -13 Associating an offer
entity_type = Solutions | AWSProducts | AWSMarketplaceOffers 
*/

public class AssociateOpportunity {
	
	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();

    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	    	
    	String entityType = "Solutions";
    	
    	String entityIdentifier = "S-0000000";
    	
    	AssociateOpportunityResponse response = getResponse(opportunityId, entityType, entityIdentifier );
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

static AssociateOpportunityResponse getResponse(String opportunityId, String entityType, String entityIdentifier) {
		
        AssociateOpportunityRequest associateOpportunityRequest = AssociateOpportunityRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.opportunityIdentifier(opportunityId)
        		.relatedEntityType(entityType)
        		.relatedEntityIdentifier(entityIdentifier)
        		.build();
        
        AssociateOpportunityResponse response = client.associateOpportunity(associateOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x APIリファレンス*」の「[AssociateOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/AssociateOpportunity)」を参照してください。

### `CreateOpportunity`
<a name="partnercentral-selling_CreateOpportunity_java_2_topic"></a>

次のコード例は、`CreateOpportunity` を使用する方法を示しています。

**SDK for Java 2.x**  
オポチュニティを作成します。  

```
package org.example;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import static org.example.utils.Constants.*;

import org.example.entity.Root;
import org.example.utils.ReferenceCodesUtils;
import org.example.utils.StringSerializer;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.Account;
import software.amazon.awssdk.services.partnercentralselling.model.Address;
import software.amazon.awssdk.services.partnercentralselling.model.Contact;
import software.amazon.awssdk.services.partnercentralselling.model.CreateOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.CreateOpportunityResponse;
import software.amazon.awssdk.services.partnercentralselling.model.Customer;
import software.amazon.awssdk.services.partnercentralselling.model.ExpectedCustomerSpend;
import software.amazon.awssdk.services.partnercentralselling.model.LifeCycle;
import software.amazon.awssdk.services.partnercentralselling.model.Marketing;
import software.amazon.awssdk.services.partnercentralselling.model.MonetaryValue;
import software.amazon.awssdk.services.partnercentralselling.model.NextStepsHistory;
import software.amazon.awssdk.services.partnercentralselling.model.Project;
import software.amazon.awssdk.services.partnercentralselling.model.SoftwareRevenue;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;

public class CreateOpportunity {
	
	static final Gson GSON = new GsonBuilder()
			.setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
			.registerTypeAdapter(String.class, new StringSerializer())
			.create();
	
	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();

	public static void main(String[] args) {

		String inputFile = "CreateOpportunity2.json";
		
		if (args.length > 0)
			inputFile = args[0];
		
		CreateOpportunityResponse response = createOpportunity(inputFile);
		
		client.close();
	}
	
	static CreateOpportunityResponse createOpportunity(String inputFile) {
		
		String inputString = ReferenceCodesUtils.readInputFileToString(inputFile);
		
		Root root = GSON.fromJson(inputString, Root.class);
				
		List<NextStepsHistory> nextStepsHistories = new ArrayList<NextStepsHistory>();
		if ( root.lifeCycle != null && root.lifeCycle.nextStepsHistories != null) {		
			for (org.example.entity.NextStepsHistory nextStepsHistoryJson : root.lifeCycle.nextStepsHistories) {
				NextStepsHistory nextStepsHistory = NextStepsHistory.builder()
						.time(Instant.parse(nextStepsHistoryJson.time))
						.value(nextStepsHistoryJson.value)
		                .build();
				nextStepsHistories.add(nextStepsHistory);
			}
		}
		
		LifeCycle lifeCycle = null;
		if ( root.lifeCycle != null ) {
			lifeCycle = LifeCycle.builder()
				.closedLostReason(root.lifeCycle.closedLostReason)
				.nextSteps(root.lifeCycle.nextSteps)
				.nextStepsHistory(nextStepsHistories)
				.reviewComments(root.lifeCycle.reviewComments)
				.reviewStatus(root.lifeCycle.reviewStatus)
				.reviewStatusReason(root.lifeCycle.reviewStatusReason)
				.stage(root.lifeCycle.stage)
				.targetCloseDate(root.lifeCycle.targetCloseDate)
				.build();
		}
		
		Marketing marketing = null;
		if ( root.marketing != null ) {
			marketing = Marketing.builder()
					.awsFundingUsed(root.marketing.awsFundingUsed)
					.campaignName(root.marketing.campaignName)
					.channels(root.marketing.channels)
					.source(root.marketing.source)
					.useCases(root.marketing.useCases)
					.build();
					
		}
		
		Address address = null;
		if ( root.customer != null && root.customer.account != null && root.customer.account.address != null ) {
			address = Address.builder()
				.city(root.customer.account.address.city)
                .postalCode(root.customer.account.address.postalCode)
                .stateOrRegion(root.customer.account.address.stateOrRegion)
                .countryCode(root.customer.account.address.countryCode)
                .streetAddress(root.customer.account.address.streetAddress)
                .build();
		}
		
		Account account = null;
		if ( root.customer != null && root.customer.account!= null) {
			account = Account.builder()
	            .address(address)
	            .awsAccountId(root.customer.account.awsAccountId)
                .duns(root.customer.account.duns)
                .industry(root.customer.account.industry)
                .otherIndustry(root.customer.account.otherIndustry)
                .companyName(root.customer.account.companyName)
                .websiteUrl(root.customer.account.websiteUrl)
                .build();
		}
		
		List<Contact> contacts = new ArrayList<Contact>();
		if ( root.customer != null && root.customer.contacts != null) {		
			for (org.example.entity.Contact jsonContact : root.customer.contacts) {
				Contact contact = Contact.builder()
		                .email(jsonContact.email)
		                .firstName(jsonContact.firstName)
		                .lastName(jsonContact.lastName)
		                .phone(jsonContact.phone)
		                .businessTitle(jsonContact.businessTitle)
		                .build();
				contacts.add(contact);
			}
		}

		Customer customer = Customer.builder()
				.account(account)
				.contacts(contacts)
				.build();
		
		Contact oportunityTeamContact = null;
		if (root.opportunityTeam != null && root.opportunityTeam.get(0) != null ) {
			oportunityTeamContact = Contact.builder()
                .firstName(root.opportunityTeam.get(0).firstName)
                .lastName(root.opportunityTeam.get(0).lastName)
                .email(root.opportunityTeam.get(0).email)
                .phone(root.opportunityTeam.get(0).phone)
                .businessTitle(root.opportunityTeam.get(0).businessTitle)
                .build();
		}
		
		List<ExpectedCustomerSpend> expectedCustomerSpends = new ArrayList<ExpectedCustomerSpend>();
		if ( root.project != null && root.project.expectedCustomerSpend != null) {
			for (org.example.entity.ExpectedCustomerSpend expectedCustomerSpendJson : root.project.expectedCustomerSpend) {
				ExpectedCustomerSpend expectedCustomerSpend = null;
				expectedCustomerSpend = ExpectedCustomerSpend.builder()
						.amount(expectedCustomerSpendJson.amount)
						.currencyCode(expectedCustomerSpendJson.currencyCode)
						.frequency(expectedCustomerSpendJson.frequency)
						.targetCompany(expectedCustomerSpendJson.targetCompany)
						.build();
				expectedCustomerSpends.add(expectedCustomerSpend);
			}
        }
        
        Project project = null;
        if ( root.project != null) {
        	project = Project.builder()
                .title(root.project.title)
                .customerBusinessProblem(root.project.customerBusinessProblem)
                .customerUseCase(root.project.customerUseCase)
                .deliveryModels(root.project.deliveryModels)
                .expectedCustomerSpend(expectedCustomerSpends)
                .salesActivities(root.project.salesActivities)
                .competitorName(root.project.competitorName)
                .otherSolutionDescription(root.project.otherSolutionDescription)
                .build();
        }
        
        SoftwareRevenue softwareRevenue = null;
        if ( root.softwareRevenue != null) {
        	MonetaryValue monetaryValue = null;
        	if ( root.softwareRevenue.value != null) {
        		monetaryValue = MonetaryValue.builder()
        				.amount(root.softwareRevenue.value.amount)
        				.currencyCode(root.softwareRevenue.value.currencyCode)
        				.build();
        	}
        	softwareRevenue = SoftwareRevenue.builder()
        			.deliveryModel(root.softwareRevenue.deliveryModel)
        			.effectiveDate(root.softwareRevenue.effectiveDate)
        			.expirationDate(root.softwareRevenue.expirationDate)
        			.value(monetaryValue)
        			.build();
        }
		
		// Building the Actual CreateOpportunity Request
		CreateOpportunityRequest createOpportunityRequest = CreateOpportunityRequest.builder()
				.catalog(CATALOG_TO_USE)
				.clientToken(root.clientToken)
				.primaryNeedsFromAwsWithStrings(root.primaryNeedsFromAws)
				.opportunityType(root.opportunityType)
				.lifeCycle(lifeCycle)
				.marketing(marketing)
				.nationalSecurity(root.nationalSecurity)
				.origin(root.origin)
				.customer(customer)
				.project(project)
				.partnerOpportunityIdentifier(root.partnerOpportunityIdentifier)
				.opportunityTeam(oportunityTeamContact)
				.softwareRevenue(softwareRevenue)
				.build();
		
		CreateOpportunityResponse response = client.createOpportunity(createOpportunityRequest);
		System.out.println("Successfully created: " + response);

		return response;
    }

}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/CreateOpportunity)」を参照してください。

### `DisassociateOpportunity`
<a name="partnercentral-selling_DisassociateOpportunity_java_2_topic"></a>

次のコード例は、`DisassociateOpportunity` を使用する方法を示しています。

**SDK for Java 2.x**  
オポチュニティと関連エンティティ間の既存の関連付けを削除します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.DisassociateOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.DisassociateOpportunityResponse;

/*
Purpose
PC-API -14 Removing a Solution
PC-API -15 Removing an offer
PC-API -16 Removing a product
entity_type = Solutions | AWSProducts | AWSMarketplaceOffers 
*/

public class DisassociateOpportunity {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	
    	String entityType = "Solutions";
    	
    	String entityIdentifier = "S-0000000";
    	
    	DisassociateOpportunityResponse response = getResponse(opportunityId, entityType, entityIdentifier );
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

	static DisassociateOpportunityResponse getResponse(String opportunityId, String entityType, String entityIdentifier) {
		
		DisassociateOpportunityRequest disassociateOpportunityRequest = DisassociateOpportunityRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.opportunityIdentifier(opportunityId)
        		.relatedEntityType(entityType)
        		.relatedEntityIdentifier(entityIdentifier)
        		.build();
        
        DisassociateOpportunityResponse response = client.disassociateOpportunity(disassociateOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DisassociateOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/DisassociateOpportunity)」を参照してください。

### `GetAwsOpportunitySummary`
<a name="partnercentral-selling_GetAwsOpportunitySummary_java_2_topic"></a>

次のコード例は、`GetAwsOpportunitySummary` を使用する方法を示しています。

**SDK for Java 2.x**  
 AWS オポチュニティの概要を取得します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.GetAwsOpportunitySummaryRequest;
import software.amazon.awssdk.services.partnercentralselling.model.GetAwsOpportunitySummaryResponse;

/*
 * Purpose
 * PC-API-25 Retrieves a summary of an AWS Opportunity.
 */

public class GetAwsOpportunitySummary {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	
    	GetAwsOpportunitySummaryResponse response = getResponse(opportunityId);
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

	public static GetAwsOpportunitySummaryResponse getResponse(String opportunityId) {

		GetAwsOpportunitySummaryRequest getOpportunityRequest = GetAwsOpportunitySummaryRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.relatedOpportunityIdentifier(opportunityId)
        		.build();
        
		GetAwsOpportunitySummaryResponse response = client.getAwsOpportunitySummary(getOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetAwsOpportunitySummary](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/GetAwsOpportunitySummary)」を参照してください。

### `GetEngagementInvitation`
<a name="partnercentral-selling_GetEngagementInvitation_java_2_topic"></a>

次のコード例は、`GetEngagementInvitation` を使用する方法を示しています。

**SDK for Java 2.x**  
がパートナー AWS と共有しているエンゲージメントの招待の詳細を取得します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.GetEngagementInvitationRequest;
import software.amazon.awssdk.services.partnercentralselling.model.GetEngagementInvitationResponse;

/*
 * Purpose
 * PC-API-22 Get engagement invitation opportunity
 */

public class GetEngagementInvitation {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	    	
    	GetEngagementInvitationResponse response = getResponse(opportunityId);
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

	static GetEngagementInvitationResponse getResponse(String opportunityId) {
		
		GetEngagementInvitationRequest getOpportunityRequest = GetEngagementInvitationRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.identifier(opportunityId)
        		.build();
        
		GetEngagementInvitationResponse response = client.getEngagementInvitation(getOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetEngagementInvitation](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/GetEngagementInvitation)」を参照してください。

### `GetOpportunity`
<a name="partnercentral-selling_GetOpportunity_java_2_topic"></a>

次のコード例は、`GetOpportunity` を使用する方法を示しています。

**SDK for Java 2.x**  
オポチュニティを取得します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.GetOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.GetOpportunityResponse;

/*
 * Purpose
 * PC-API-08 Get updated Opportunity
 */

public class GetOpportunity {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	
    	GetOpportunityResponse response = getResponse(opportunityId);
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

	public static GetOpportunityResponse getResponse(String opportunityId) {

        GetOpportunityRequest getOpportunityRequest = GetOpportunityRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.identifier(opportunityId)
        		.build();
        
        GetOpportunityResponse response = client.getOpportunity(getOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/GetOpportunity)」を参照してください。

### `ListEngagementInvitations`
<a name="partnercentral-selling_ListEngagementInvitations_java_2_topic"></a>

次のコード例は、`ListEngagementInvitations` を使用する方法を示しています。

**SDK for Java 2.x**  
パートナーに送信されたエンゲージメントの招待の一覧を取得します。  

```
package org.example;

import java.util.ArrayList;
import java.util.List;

import org.example.utils.ReferenceCodesUtils;
import static org.example.utils.Constants.*;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.ListEngagementInvitationsRequest;
import software.amazon.awssdk.services.partnercentralselling.model.ListEngagementInvitationsResponse;
import software.amazon.awssdk.services.partnercentralselling.model.ParticipantType;
import software.amazon.awssdk.services.partnercentralselling.model.EngagementInvitationSummary;

public class ListEngagementInvitations {
	
	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	List<EngagementInvitationSummary> opportunitySummaries = getResponse();
        ReferenceCodesUtils.formatOutput(opportunitySummaries);
    }
    
    static List<EngagementInvitationSummary> getResponse() {
		
		List<EngagementInvitationSummary> opportunitySummaries = new ArrayList<EngagementInvitationSummary>();
		
		ListEngagementInvitationsRequest listOpportunityRequest = ListEngagementInvitationsRequest.builder()
                .catalog(CATALOG_TO_USE)
                .participantType(ParticipantType.RECEIVER)
        		.maxResults(5)
        		.build();
        
		ListEngagementInvitationsResponse response = client.listEngagementInvitations(listOpportunityRequest);
    	
    	opportunitySummaries.addAll(response.engagementInvitationSummaries());
    	
    	client.close();
    	
        return opportunitySummaries;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListEngagementInvitations](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/ListEngagementInvitations)」を参照してください。

### `ListOpportunities`
<a name="partnercentral-selling_ListOpportunities_java_2_topic"></a>

次のコード例は、`ListOpportunities` を使用する方法を示しています。

**SDK for Java 2.x**  
オポチュニティを一覧表示します。  

```
package org.example;

import java.util.ArrayList;
import java.util.List;

import org.example.utils.ReferenceCodesUtils;
import static org.example.utils.Constants.*;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.ListOpportunitiesRequest;
import software.amazon.awssdk.services.partnercentralselling.model.ListOpportunitiesResponse;
import software.amazon.awssdk.services.partnercentralselling.model.OpportunitySummary;

/*
 * Purpose
 * PC-API-18 Getting list of Opportunities
 */

public class ListOpportunititesPaging {
	
	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	List<OpportunitySummary> opportunitySummaries = getResponse();
        ReferenceCodesUtils.formatOutput(opportunitySummaries);
    }
    
    private static List<OpportunitySummary> getResponse() {
    	List<OpportunitySummary> opportunitySummaries = new ArrayList<OpportunitySummary>();
		
		ListOpportunitiesRequest listOpportunityRequest = ListOpportunitiesRequest.builder()
                .catalog(CATALOG_TO_USE)
        		.maxResults(5)
        		.build();
        
    	ListOpportunitiesResponse response = client.listOpportunities(listOpportunityRequest);
    	
    	opportunitySummaries.addAll(response.opportunitySummaries());
    	
    	while (response.nextToken() != null && response.nextToken().length() > 0) {
    		listOpportunityRequest = ListOpportunitiesRequest.builder()
                    .catalog(CATALOG_TO_USE)
            		.maxResults(5)
            		.nextToken(response.nextToken())
            		.build();
    		response = client.listOpportunities(listOpportunityRequest);
    		opportunitySummaries.addAll(response.opportunitySummaries());
    	}
        
    	client.close();
    	
        return opportunitySummaries;
	}
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListOpportunities](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/ListOpportunities)」を参照してください。

### `ListSolutions`
<a name="partnercentral-selling_ListSolutions_java_2_topic"></a>

次のコード例は、`ListSolutions` を使用する方法を示しています。

**SDK for Java 2.x**  
パートナーがパートナーセントラルに登録したパートナーソリューションの一覧を取得します。  

```
package org.example;

import java.util.ArrayList;
import java.util.List;

import static org.example.utils.Constants.*;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.ListSolutionsRequest;
import software.amazon.awssdk.services.partnercentralselling.model.ListSolutionsResponse;
import software.amazon.awssdk.services.partnercentralselling.model.SolutionBase;

/*
 * Purpose
 * PC-API-10 Getting list of solutions
 */

public class ListSolutions {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	List<SolutionBase> solutionSummaries = getResponse();
        ReferenceCodesUtils.formatOutput(solutionSummaries);
    }
    
    static List<SolutionBase> getResponse() {
		List<SolutionBase> solutionSummaries = new ArrayList<SolutionBase>();

		ListSolutionsRequest listSolutionsRequest = ListSolutionsRequest.builder()
				.catalog(CATALOG_TO_USE)
        		.maxResults(5)
        		.build();
        
    	ListSolutionsResponse response = client.listSolutions(listSolutionsRequest);
        
    	solutionSummaries.addAll(response.solutionSummaries());
    	
        return solutionSummaries;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListSolutions](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/ListSolutions)」を参照してください。

### `RejectEngagementInvitation`
<a name="partnercentral-selling_RejectEngagementInvitation_java_2_topic"></a>

次のコード例は、`RejectEngagementInvitation` を使用する方法を示しています。

**SDK for Java 2.x**  
が AWS 共有した EngagementInvitation を拒否します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.RejectEngagementInvitationRequest;
import software.amazon.awssdk.services.partnercentralselling.model.RejectEngagementInvitationResponse;

/*
 * Purpose
 * PC-API-05 AWS Originated(AO) rejection
 */

public class RejectEngagementInvitation {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;

		RejectEngagementInvitationResponse response = getResponse(opportunityId);
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

	static RejectEngagementInvitationResponse getResponse(String invitationId) {
		
        RejectEngagementInvitationRequest rejectOpportunityRequest = RejectEngagementInvitationRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.identifier(invitationId)
        		.rejectionReason("Unable to support")
        		.build();

		RejectEngagementInvitationResponse response = client.rejectEngagementInvitation(rejectOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の[RejectEngagementInvitation](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/RejectEngagementInvitation)」を参照してください。

### `StartEngagementByAcceptingInvitationTask`
<a name="partnercentral-selling_StartEngagementByAcceptingInvitationTask_java_2_topic"></a>

次のコード例は、`StartEngagementByAcceptingInvitationTask` を使用する方法を示しています。

**SDK for Java 2.x**  
EngagementInvitation を受け入れることでエンゲージメントを開始します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.StartEngagementByAcceptingInvitationTaskRequest;
import software.amazon.awssdk.services.partnercentralselling.model.StartEngagementByAcceptingInvitationTaskResponse;
import software.amazon.awssdk.services.partnercentralselling.model.GetEngagementInvitationRequest;
import software.amazon.awssdk.services.partnercentralselling.model.GetEngagementInvitationResponse;
import software.amazon.awssdk.services.partnercentralselling.model.InvitationStatus;

/*
Purpose
PC-API-04: Start Engagement By Accepting InvitationTask for AWS Originated(AO) opportunity
*/

public class StartEngagementByAcceptingInvitationTask {
	
	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())            
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
	static String clientToken = "test-a30d161";

    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	
    	StartEngagementByAcceptingInvitationTaskResponse response = getResponse(opportunityId);
    	
    	if ( response == null) {
    		System.out.println("Opportunity is not AWS Originated.");
    	} else {
    		ReferenceCodesUtils.formatOutput(response);
    	}
    }
    
    private static GetEngagementInvitationResponse getInvitation(String invitationId) {
		
    	GetEngagementInvitationRequest getRequest = GetEngagementInvitationRequest.builder()
        		.catalog(Constants.CATALOG_TO_USE)
        		.identifier(invitationId)
        		.build();

		GetEngagementInvitationResponse response = client.getEngagementInvitation(getRequest);
        
        return response;
	}

	static StartEngagementByAcceptingInvitationTaskResponse getResponse(String invitationId) {
		
		if ( getInvitation(invitationId).status().equals(InvitationStatus.PENDING)) {
			StartEngagementByAcceptingInvitationTaskRequest acceptOpportunityRequest = 
					StartEngagementByAcceptingInvitationTaskRequest.builder()
					.catalog(Constants.CATALOG_TO_USE)
	        		.identifier(invitationId)
	        		.clientToken(clientToken)
	        		.build();

			StartEngagementByAcceptingInvitationTaskResponse response = client.startEngagementByAcceptingInvitationTask(acceptOpportunityRequest);
	        return response;
		}
		return null;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartEngagementByAcceptingInvitationTask](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/StartEngagementByAcceptingInvitationTask)」を参照してください。

### `StartEngagementFromOpportunityTask`
<a name="partnercentral-selling_StartEngagementFromOpportunityTask_java_2_topic"></a>

次のコード例は、`StartEngagementFromOpportunityTask` を使用する方法を示しています。

**SDK for Java 2.x**  
エンゲージメントの招待を受け入れ、パートナーのシステムで対応するオポチュニティを作成することで、既存のオポチュニティからエンゲージメントプロセスを開始します。  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.AwsSubmission;
import software.amazon.awssdk.services.partnercentralselling.model.SalesInvolvementType;
import software.amazon.awssdk.services.partnercentralselling.model.StartEngagementFromOpportunityTaskRequest;
import software.amazon.awssdk.services.partnercentralselling.model.StartEngagementFromOpportunityTaskResponse;
import software.amazon.awssdk.services.partnercentralselling.model.Visibility;

/*
 * Purpose
 * PC-API-01 Partner Originated (PO) opp submission(Start Engagement From Opportunity Task for AO Originated Opportunity)
 */

public class StartEngagementFromOpportunityTask {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	
    	StartEngagementFromOpportunityTaskResponse response = getResponse(opportunityId);
    	
    	ReferenceCodesUtils.formatOutput(response);
    }

	static StartEngagementFromOpportunityTaskResponse getResponse(String opportunityId) {
		
		StartEngagementFromOpportunityTaskRequest submitOpportunityRequest = StartEngagementFromOpportunityTaskRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.identifier(opportunityId)
        		.clientToken("test-annjqwesdsd99")
        		.awsSubmission(AwsSubmission.builder().involvementType(SalesInvolvementType.CO_SELL).visibility(Visibility.FULL).build())
        		.build();

		StartEngagementFromOpportunityTaskResponse response = client.startEngagementFromOpportunityTask(submitOpportunityRequest);
        
        return response;
	}
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartEngagementFromOpportunityTask](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/StartEngagementFromOpportunityTask)」を参照してください。

### `UpdateOpportunity`
<a name="partnercentral-selling_UpdateOpportunity_java_2_topic"></a>

次のコード例は、`UpdateOpportunity` を使用する方法を示しています。

**SDK for Java 2.x**  
オポチュニティを更新します。  

```
package org.example;

import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import static org.example.utils.Constants.*;

import org.example.entity.Root;
import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;
import org.example.utils.StringSerializer;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.Account;
import software.amazon.awssdk.services.partnercentralselling.model.Address;
import software.amazon.awssdk.services.partnercentralselling.model.Contact;
import software.amazon.awssdk.services.partnercentralselling.model.Customer;
import software.amazon.awssdk.services.partnercentralselling.model.ExpectedCustomerSpend;
import software.amazon.awssdk.services.partnercentralselling.model.GetOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.GetOpportunityResponse;
import software.amazon.awssdk.services.partnercentralselling.model.LifeCycle;
import software.amazon.awssdk.services.partnercentralselling.model.Marketing;
import software.amazon.awssdk.services.partnercentralselling.model.NextStepsHistory;
import software.amazon.awssdk.services.partnercentralselling.model.Project;
import software.amazon.awssdk.services.partnercentralselling.model.ReviewStatus;
import software.amazon.awssdk.services.partnercentralselling.model.UpdateOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.UpdateOpportunityResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.ToNumberPolicy;

/*
 * Purpose
 * PC-API-02/06 Update opportunity when LifeCycle.ReviewStatus is not Submitted or In-Review
 */

public class UpdateOpportunity {
	
	static final Gson GSON = new GsonBuilder()
			.setObjectToNumberStrategy(ToNumberPolicy.LAZILY_PARSED_NUMBER)
			.registerTypeAdapter(String.class, new StringSerializer())
			.create();
	
	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
	static String OPPORTUNITY_ORIGIN = ORIGIN_PARTNER_ORIGINATED;

	public static void main(String[] args) {

		String inputFile = "updateOpportunity.json";
		
		if (args.length > 0)
			inputFile = args[0];
		
		UpdateOpportunityResponse response = updateOpportunity(inputFile);
		
		client.close();
	}
	
	public static GetOpportunityResponse getResponse(String opportunityId) {

        GetOpportunityRequest getOpportunityRequest = GetOpportunityRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.identifier(opportunityId)
        		.build();
        
        GetOpportunityResponse response = client.getOpportunity(getOpportunityRequest);
        System.out.println(opportunityId + ":" + response);
        return response;
	}
	
	public static UpdateOpportunityResponse updateOpportunity(String inputFile) {
		
		String inputString = ReferenceCodesUtils.readInputFileToString(inputFile);

		Root root = GSON.fromJson(inputString, Root.class);
		GetOpportunityResponse response = getResponse(root.identifier);

		if (response != null 
				&& response.lifeCycle() != null
				&& response.lifeCycle().reviewStatus() != null
				&& response.lifeCycle().reviewStatus() != ReviewStatus.SUBMITTED
				&& response.lifeCycle().reviewStatus() != ReviewStatus.IN_REVIEW) {
			
			List<NextStepsHistory> nextStepsHistories = new ArrayList<NextStepsHistory>();
			if ( root.lifeCycle != null && root.lifeCycle.nextStepsHistories != null) {		
				for (org.example.entity.NextStepsHistory nextStepsHistoryJson : root.lifeCycle.nextStepsHistories) {
					NextStepsHistory nextStepsHistory = NextStepsHistory.builder()
							.time(Instant.parse(nextStepsHistoryJson.time))
							.value(nextStepsHistoryJson.value)
			                .build();
					nextStepsHistories.add(nextStepsHistory);
				}
			}
			
			LifeCycle lifeCycle = null;
			if ( root.lifeCycle != null ) {
				lifeCycle = LifeCycle.builder()
					.closedLostReason(root.lifeCycle.closedLostReason)
					.nextSteps(root.lifeCycle.nextSteps)
					.nextStepsHistory(nextStepsHistories)
					.reviewComments(root.lifeCycle.reviewComments)
					.reviewStatus(root.lifeCycle.reviewStatus)
					.reviewStatusReason(root.lifeCycle.reviewStatusReason)
					.stage(root.lifeCycle.stage)
					.targetCloseDate(root.lifeCycle.targetCloseDate)
					.build();
			}
			
			Marketing marketing = null;
			if ( root.marketing != null ) {
				marketing = Marketing.builder()
						.awsFundingUsed(root.marketing.awsFundingUsed)
						.campaignName(root.marketing.campaignName)
						.channels(root.marketing.channels)
						.source(root.marketing.source)
						.useCases(root.marketing.useCases)
						.build();
						
			}

			Address address = null;
			if (root.customer != null && root.customer.account != null && root.customer.account.address != null) {
				address = Address.builder().postalCode(root.customer.account.address.postalCode)
						.stateOrRegion(root.customer.account.address.stateOrRegion)
						.countryCode(root.customer.account.address.countryCode).build();
			}

			Account account = null;
			if (root.customer != null && root.customer.account != null) {
				account = Account.builder().address(address).duns(root.customer.account.duns)
						.industry(root.customer.account.industry).companyName(root.customer.account.companyName)
						.websiteUrl(root.customer.account.websiteUrl).build();
			}

			List<Contact> contacts = new ArrayList<Contact>();
			if ( root.customer != null && root.customer.contacts != null) {		
				for (org.example.entity.Contact jsonContact : root.customer.contacts) {
					Contact contact = Contact.builder()
			                .email(jsonContact.email)
			                .firstName(jsonContact.firstName)
			                .lastName(jsonContact.lastName)
			                .phone(jsonContact.phone)
			                .businessTitle(jsonContact.businessTitle)
			                .build();
					contacts.add(contact);
				}
			}

			Customer customer = Customer.builder().account(account).contacts(contacts).build();

			List<ExpectedCustomerSpend> expectedCustomerSpends = new ArrayList<ExpectedCustomerSpend>();
			if ( root.project != null && root.project.expectedCustomerSpend != null) {
				for (org.example.entity.ExpectedCustomerSpend expectedCustomerSpendJson : root.project.expectedCustomerSpend) {
					ExpectedCustomerSpend expectedCustomerSpend = null;
					expectedCustomerSpend = ExpectedCustomerSpend.builder()
							.amount(expectedCustomerSpendJson.amount)
							.currencyCode(expectedCustomerSpendJson.currencyCode)
							.frequency(expectedCustomerSpendJson.frequency)
							.targetCompany(expectedCustomerSpendJson.targetCompany)
							.build();
					expectedCustomerSpends.add(expectedCustomerSpend);
				}
	        }

			Project project = null;
			if (root.project != null) {
				project = Project.builder().title(root.project.title)
						.customerBusinessProblem(root.project.customerBusinessProblem)
						.customerUseCase(root.project.customerUseCase).deliveryModels(root.project.deliveryModels)
						.expectedCustomerSpend(expectedCustomerSpends)
						.salesActivities(root.project.salesActivities).competitorName(root.project.competitorName)
						.otherSolutionDescription(root.project.otherSolutionDescription).build();
			}

			// Building the Actual CreateOpportunity Request
			UpdateOpportunityRequest updateOpportunityRequest = UpdateOpportunityRequest.builder().catalog(root.catalog)
					.identifier(root.identifier).lastModifiedDate(Instant.parse(root.lastModifiedDate))
					.primaryNeedsFromAwsWithStrings(root.primaryNeedsFromAws).opportunityType(root.opportunityType)
					.lifeCycle(lifeCycle)
					.customer(customer)
					.project(project)
					.partnerOpportunityIdentifier(root.partnerOpportunityIdentifier)
					.marketing(marketing)
					.nationalSecurity(root.nationalSecurity)
					.opportunityType(root.opportunityType)
					.build();

			UpdateOpportunityResponse updateResponse = client.updateOpportunity(updateOpportunityRequest);
			System.out.println("Successfully updated opportunity: " + updateResponse);

			return updateResponse;
		} else {
			System.out.println("Opportunity cannot be updated.");
			return null;
		}
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/UpdateOpportunity)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### オポチュニティの関連エンティティを更新する
<a name="partnercentral-selling__UpdateAssociatedEntity_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 古いエンティティの関連付けを解除します。
+ 新しいエンティティを関連付けます。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[シナリオ](https://github.com/aws-samples/partner-crm-integration-samples/tree/main/partner-central-api-sample-codes/java_preview)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
オポチュニティの関連エンティティを更新する  

```
package org.example;

import static org.example.utils.Constants.*;

import org.example.utils.Constants;
import org.example.utils.ReferenceCodesUtils;

import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.partnercentralselling.PartnerCentralSellingClient;
import software.amazon.awssdk.services.partnercentralselling.model.AssociateOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.AssociateOpportunityResponse;
import software.amazon.awssdk.services.partnercentralselling.model.DisassociateOpportunityRequest;
import software.amazon.awssdk.services.partnercentralselling.model.DisassociateOpportunityResponse;

/*
Purpose
PC-API -17 Replacing a solution
*/

public class ReplaceSolution {

	static PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();
	
    public static void main(String[] args) {
    	
    	String opportunityId = args.length > 0 ? args[0] : OPPORTUNITY_ID;
    	
    	String entityType = "Solutions";
    	String originalEntityIdentifier = "S-0000000";
    	String newEntityIdentifier = "S-0011111";
    	
    	disassociateOppornitityResponse(opportunityId, entityType, originalEntityIdentifier );
    	AssociateOpportunityResponse associateOpportunityResponse = associateOpportunityResponse(opportunityId, entityType, newEntityIdentifier );
    	
    	ReferenceCodesUtils.formatOutput(associateOpportunityResponse);
    }

	private static AssociateOpportunityResponse associateOpportunityResponse(String opportunityId, String entityType, String entityIdentifier) {
		
        AssociateOpportunityRequest associateOpportunityRequest = AssociateOpportunityRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.opportunityIdentifier(opportunityId)
        		.relatedEntityType(entityType)
        		.relatedEntityIdentifier(entityIdentifier)
        		.build();
        
        AssociateOpportunityResponse response = client.associateOpportunity(associateOpportunityRequest);
        
        return response;
	}
	
	private static DisassociateOpportunityResponse disassociateOppornitityResponse(String opportunityId, String entityType, String entityIdentifier) {
		PartnerCentralSellingClient client = PartnerCentralSellingClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(DefaultCredentialsProvider.create())
            .httpClient(ApacheHttpClient.builder().build())
            .build();

        DisassociateOpportunityRequest disassociateOpportunityRequest = DisassociateOpportunityRequest.builder()
				.catalog(Constants.CATALOG_TO_USE)
        		.opportunityIdentifier(opportunityId)
        		.relatedEntityType(entityType)
        		.relatedEntityIdentifier(entityIdentifier)
        		.build();
        
        DisassociateOpportunityResponse response = client.disassociateOpportunity(disassociateOpportunityRequest);
        
        return response;
	}
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AssociateOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/AssociateOpportunity)
  + [DisassociateOpportunity](https://docs.aws.amazon.com/goto/SdkForJavaV2/partnercentral-selling-2022-07-26/DisassociateOpportunity)

# SDK for Java 2.x を使用した Amazon Personalize の例
<a name="java_2_personalize_code_examples"></a>

次のコード例は、Amazon Personalize AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateBatchInferenceJob`
<a name="personalize_CreateBatchInferenceJob_java_2_topic"></a>

次のコード例は、`CreateBatchInferenceJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
        public static String createPersonalizeBatchInferenceJob(PersonalizeClient personalizeClient,
                        String solutionVersionArn,
                        String jobName,
                        String s3InputDataSourcePath,
                        String s3DataDestinationPath,
                        String roleArn,
                        String explorationWeight,
                        String explorationItemAgeCutOff) {

                long waitInMilliseconds = 60 * 1000;
                String status;
                String batchInferenceJobArn;

                try {

                        // Set up data input and output parameters.
                        S3DataConfig inputSource = S3DataConfig.builder()
                                        .path(s3InputDataSourcePath)
                                        .build();

                        S3DataConfig outputDestination = S3DataConfig.builder()
                                        .path(s3DataDestinationPath)
                                        .build();

                        BatchInferenceJobInput jobInput = BatchInferenceJobInput.builder()
                                        .s3DataSource(inputSource)
                                        .build();

                        BatchInferenceJobOutput jobOutputLocation = BatchInferenceJobOutput.builder()
                                        .s3DataDestination(outputDestination)
                                        .build();

                        // Optional code to build the User-Personalization specific item exploration
                        // config.
                        HashMap<String, String> explorationConfig = new HashMap<>();

                        explorationConfig.put("explorationWeight", explorationWeight);
                        explorationConfig.put("explorationItemAgeCutOff", explorationItemAgeCutOff);

                        BatchInferenceJobConfig jobConfig = BatchInferenceJobConfig.builder()
                                        .itemExplorationConfig(explorationConfig)
                                        .build();

                        // End optional User-Personalization recipe specific code.

                        CreateBatchInferenceJobRequest createBatchInferenceJobRequest = CreateBatchInferenceJobRequest
                                        .builder()
                                        .solutionVersionArn(solutionVersionArn)
                                        .jobInput(jobInput)
                                        .jobOutput(jobOutputLocation)
                                        .jobName(jobName)
                                        .roleArn(roleArn)
                                        .batchInferenceJobConfig(jobConfig) // Optional
                                        .build();

                        batchInferenceJobArn = personalizeClient.createBatchInferenceJob(createBatchInferenceJobRequest)
                                        .batchInferenceJobArn();

                        DescribeBatchInferenceJobRequest describeBatchInferenceJobRequest = DescribeBatchInferenceJobRequest
                                        .builder()
                                        .batchInferenceJobArn(batchInferenceJobArn)
                                        .build();

                        long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;
                        while (Instant.now().getEpochSecond() < maxTime) {

                                BatchInferenceJob batchInferenceJob = personalizeClient
                                                .describeBatchInferenceJob(describeBatchInferenceJobRequest)
                                                .batchInferenceJob();

                                status = batchInferenceJob.status();
                                System.out.println("Batch inference job status: " + status);

                                if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) {
                                        break;
                                }
                                try {
                                        Thread.sleep(waitInMilliseconds);
                                } catch (InterruptedException e) {
                                        System.out.println(e.getMessage());
                                }
                        }
                        return batchInferenceJobArn;

                } catch (PersonalizeException e) {
                        System.out.println(e.awsErrorDetails().errorMessage());
                }
                return "";
        }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateBatchInferenceJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateBatchInferenceJob)」を参照してください。

### `CreateCampaign`
<a name="personalize_CreateCampaign_java_2_topic"></a>

次のコード例は、`CreateCampaign` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createPersonalCompaign(PersonalizeClient personalizeClient, String solutionVersionArn,
            String name) {

        try {
            CreateCampaignRequest createCampaignRequest = CreateCampaignRequest.builder()
                    .minProvisionedTPS(1)
                    .solutionVersionArn(solutionVersionArn)
                    .name(name)
                    .build();

            CreateCampaignResponse campaignResponse = personalizeClient.createCampaign(createCampaignRequest);
            System.out.println("The campaign ARN is " + campaignResponse.campaignArn());
            return campaignResponse.campaignArn();
        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateCampaign](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateCampaign) 」を参照してください。

### `CreateDataset`
<a name="personalize_CreateDataset_java_2_topic"></a>

次のコード例は、`CreateDataset` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createDataset(PersonalizeClient personalizeClient,
            String datasetName,
            String datasetGroupArn,
            String datasetType,
            String schemaArn) {
        try {
            CreateDatasetRequest request = CreateDatasetRequest.builder()
                    .name(datasetName)
                    .datasetGroupArn(datasetGroupArn)
                    .datasetType(datasetType)
                    .schemaArn(schemaArn)
                    .build();

            String datasetArn = personalizeClient.createDataset(request)
                    .datasetArn();
            System.out.println("Dataset " + datasetName + " created.");
            return datasetArn;

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDataset](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateDataset)」を参照してください。

### `CreateDatasetExportJob`
<a name="personalize_CreateDatasetExportJob_java_2_topic"></a>

次のコード例は、`CreateDatasetExportJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createDatasetExportJob(PersonalizeClient personalizeClient,
            String jobName,
            String datasetArn,
            IngestionMode ingestionMode,
            String roleArn,
            String s3BucketPath,
            String kmsKeyArn) {

        long waitInMilliseconds = 30 * 1000; // 30 seconds
        String status = null;

        try {

            S3DataConfig exportS3DataConfig = S3DataConfig.builder().path(s3BucketPath).kmsKeyArn(kmsKeyArn).build();
            DatasetExportJobOutput jobOutput = DatasetExportJobOutput.builder().s3DataDestination(exportS3DataConfig)
                    .build();

            CreateDatasetExportJobRequest createRequest = CreateDatasetExportJobRequest.builder()
                    .jobName(jobName)
                    .datasetArn(datasetArn)
                    .ingestionMode(ingestionMode)
                    .jobOutput(jobOutput)
                    .roleArn(roleArn)
                    .build();

            String datasetExportJobArn = personalizeClient.createDatasetExportJob(createRequest).datasetExportJobArn();

            DescribeDatasetExportJobRequest describeDatasetExportJobRequest = DescribeDatasetExportJobRequest.builder()
                    .datasetExportJobArn(datasetExportJobArn)
                    .build();

            long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;

            while (Instant.now().getEpochSecond() < maxTime) {

                DatasetExportJob datasetExportJob = personalizeClient
                        .describeDatasetExportJob(describeDatasetExportJobRequest)
                        .datasetExportJob();

                status = datasetExportJob.status();
                System.out.println("Export job status: " + status);

                if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) {
                    return status;
                }
                try {
                    Thread.sleep(waitInMilliseconds);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            }
        } catch (PersonalizeException e) {
            System.out.println(e.awsErrorDetails().errorMessage());
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*のの「[CreateDatasetExportJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateDatasetExportJob)」を参照してください。

### `CreateDatasetGroup`
<a name="personalize_CreateDatasetGroup_java_2_topic"></a>

次のコード例は、`CreateDatasetGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createDatasetGroup(PersonalizeClient personalizeClient, String datasetGroupName) {

        try {
            CreateDatasetGroupRequest createDatasetGroupRequest = CreateDatasetGroupRequest.builder()
                    .name(datasetGroupName)
                    .build();
            return personalizeClient.createDatasetGroup(createDatasetGroupRequest).datasetGroupArn();
        } catch (PersonalizeException e) {
            System.out.println(e.awsErrorDetails().errorMessage());
        }
        return "";
    }
```
ドメインデータセットグループを作成します。  

```
    public static String createDomainDatasetGroup(PersonalizeClient personalizeClient,
            String datasetGroupName,
            String domain) {

        try {
            CreateDatasetGroupRequest createDatasetGroupRequest = CreateDatasetGroupRequest.builder()
                    .name(datasetGroupName)
                    .domain(domain)
                    .build();
            return personalizeClient.createDatasetGroup(createDatasetGroupRequest).datasetGroupArn();
        } catch (PersonalizeException e) {
            System.out.println(e.awsErrorDetails().errorMessage());
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDatasetGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateDatasetGroup)」を参照してください。

### `CreateDatasetImportJob`
<a name="personalize_CreateDatasetImportJob_java_2_topic"></a>

次のコード例は、`CreateDatasetImportJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createPersonalizeDatasetImportJob(PersonalizeClient personalizeClient,
            String jobName,
            String datasetArn,
            String s3BucketPath,
            String roleArn) {

        long waitInMilliseconds = 60 * 1000;
        String status;
        String datasetImportJobArn;

        try {
            DataSource importDataSource = DataSource.builder()
                    .dataLocation(s3BucketPath)
                    .build();

            CreateDatasetImportJobRequest createDatasetImportJobRequest = CreateDatasetImportJobRequest.builder()
                    .datasetArn(datasetArn)
                    .dataSource(importDataSource)
                    .jobName(jobName)
                    .roleArn(roleArn)
                    .build();

            datasetImportJobArn = personalizeClient.createDatasetImportJob(createDatasetImportJobRequest)
                    .datasetImportJobArn();
            DescribeDatasetImportJobRequest describeDatasetImportJobRequest = DescribeDatasetImportJobRequest.builder()
                    .datasetImportJobArn(datasetImportJobArn)
                    .build();

            long maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;

            while (Instant.now().getEpochSecond() < maxTime) {

                DatasetImportJob datasetImportJob = personalizeClient
                        .describeDatasetImportJob(describeDatasetImportJobRequest)
                        .datasetImportJob();

                status = datasetImportJob.status();
                System.out.println("Dataset import job status: " + status);

                if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) {
                    break;
                }
                try {
                    Thread.sleep(waitInMilliseconds);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            }
            return datasetImportJobArn;

        } catch (PersonalizeException e) {
            System.out.println(e.awsErrorDetails().errorMessage());
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateDatasetImportJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateDatasetImportJob)」を参照してください。

### `CreateEventTracker`
<a name="personalize_CreateEventTracker_java_2_topic"></a>

次のコード例は、`CreateEventTracker` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createEventTracker(PersonalizeClient personalizeClient, String eventTrackerName,
            String datasetGroupArn) {

        String eventTrackerId = "";
        String eventTrackerArn;
        long maxTime = 3 * 60 * 60; // 3 hours
        long waitInMilliseconds = 20 * 1000; // 20 seconds
        String status;

        try {

            CreateEventTrackerRequest createEventTrackerRequest = CreateEventTrackerRequest.builder()
                    .name(eventTrackerName)
                    .datasetGroupArn(datasetGroupArn)
                    .build();

            CreateEventTrackerResponse createEventTrackerResponse = personalizeClient
                    .createEventTracker(createEventTrackerRequest);

            eventTrackerArn = createEventTrackerResponse.eventTrackerArn();
            eventTrackerId = createEventTrackerResponse.trackingId();
            System.out.println("Event tracker ARN: " + eventTrackerArn);
            System.out.println("Event tracker ID: " + eventTrackerId);

            maxTime = Instant.now().getEpochSecond() + maxTime;

            DescribeEventTrackerRequest describeRequest = DescribeEventTrackerRequest.builder()
                    .eventTrackerArn(eventTrackerArn)
                    .build();

            while (Instant.now().getEpochSecond() < maxTime) {

                status = personalizeClient.describeEventTracker(describeRequest).eventTracker().status();
                System.out.println("EventTracker status: " + status);

                if (status.equals("ACTIVE") || status.equals("CREATE FAILED")) {
                    break;
                }
                try {
                    Thread.sleep(waitInMilliseconds);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            }
            return eventTrackerId;
        } catch (PersonalizeException e) {
            System.out.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return eventTrackerId;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateEventTracker](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateEventTracker)」を参照してください。

### `CreateFilter`
<a name="personalize_CreateFilter_java_2_topic"></a>

次のコード例は、`CreateFilter` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createFilter(PersonalizeClient personalizeClient,
            String filterName,
            String datasetGroupArn,
            String filterExpression) {
        try {
            CreateFilterRequest request = CreateFilterRequest.builder()
                    .name(filterName)
                    .datasetGroupArn(datasetGroupArn)
                    .filterExpression(filterExpression)
                    .build();

            return personalizeClient.createFilter(request).filterArn();
        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateFilter](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateFilter)」を参照してください。

### `CreateRecommender`
<a name="personalize_CreateRecommender_java_2_topic"></a>

次のコード例は、`CreateRecommender` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createRecommender(PersonalizeClient personalizeClient,
            String name,
            String datasetGroupArn,
            String recipeArn) {

        long maxTime = 0;
        long waitInMilliseconds = 30 * 1000; // 30 seconds
        String recommenderStatus = "";

        try {
            CreateRecommenderRequest createRecommenderRequest = CreateRecommenderRequest.builder()
                    .datasetGroupArn(datasetGroupArn)
                    .name(name)
                    .recipeArn(recipeArn)
                    .build();

            CreateRecommenderResponse recommenderResponse = personalizeClient
                    .createRecommender(createRecommenderRequest);
            String recommenderArn = recommenderResponse.recommenderArn();
            System.out.println("The recommender ARN is " + recommenderArn);

            DescribeRecommenderRequest describeRecommenderRequest = DescribeRecommenderRequest.builder()
                    .recommenderArn(recommenderArn)
                    .build();

            maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;

            while (Instant.now().getEpochSecond() < maxTime) {

                recommenderStatus = personalizeClient.describeRecommender(describeRecommenderRequest).recommender()
                        .status();
                System.out.println("Recommender status: " + recommenderStatus);

                if (recommenderStatus.equals("ACTIVE") || recommenderStatus.equals("CREATE FAILED")) {
                    break;
                }
                try {
                    Thread.sleep(waitInMilliseconds);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            }
            return recommenderArn;

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateRecommender](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateRecommender)」を参照してください。

### `CreateSchema`
<a name="personalize_CreateSchema_java_2_topic"></a>

次のコード例は、`CreateSchema` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createSchema(PersonalizeClient personalizeClient, String schemaName, String filePath) {

        String schema = null;
        try {
            schema = new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        try {
            CreateSchemaRequest createSchemaRequest = CreateSchemaRequest.builder()
                    .name(schemaName)
                    .schema(schema)
                    .build();

            String schemaArn = personalizeClient.createSchema(createSchemaRequest).schemaArn();

            System.out.println("Schema arn: " + schemaArn);

            return schemaArn;

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
ドメインでスキーマを作成します。  

```
    public static String createDomainSchema(PersonalizeClient personalizeClient, String schemaName, String domain,
            String filePath) {

        String schema = null;
        try {
            schema = new String(Files.readAllBytes(Paths.get(filePath)));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

        try {
            CreateSchemaRequest createSchemaRequest = CreateSchemaRequest.builder()
                    .name(schemaName)
                    .domain(domain)
                    .schema(schema)
                    .build();

            String schemaArn = personalizeClient.createSchema(createSchemaRequest).schemaArn();

            System.out.println("Schema arn: " + schemaArn);

            return schemaArn;

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateSchema](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateSchema)」を参照してください。

### `CreateSolution`
<a name="personalize_CreateSolution_java_2_topic"></a>

次のコード例は、`CreateSolution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createPersonalizeSolution(PersonalizeClient personalizeClient,
            String datasetGroupArn,
            String solutionName,
            String recipeArn) {

        try {
            CreateSolutionRequest solutionRequest = CreateSolutionRequest.builder()
                    .name(solutionName)
                    .datasetGroupArn(datasetGroupArn)
                    .recipeArn(recipeArn)
                    .build();

            CreateSolutionResponse solutionResponse = personalizeClient.createSolution(solutionRequest);
            return solutionResponse.solutionArn();

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateSolution](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateSolution)」を参照してください。

### `CreateSolutionVersion`
<a name="personalize_CreateSolutionVersion_java_2_topic"></a>

次のコード例は、`CreateSolutionVersion` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String createPersonalizeSolutionVersion(PersonalizeClient personalizeClient, String solutionArn) {
        long maxTime = 0;
        long waitInMilliseconds = 30 * 1000; // 30 seconds
        String solutionStatus = "";
        String solutionVersionStatus = "";
        String solutionVersionArn = "";

        try {
            DescribeSolutionRequest describeSolutionRequest = DescribeSolutionRequest.builder()
                    .solutionArn(solutionArn)
                    .build();

            maxTime = Instant.now().getEpochSecond() + 3 * 60 * 60;

            // Wait until solution is active.
            while (Instant.now().getEpochSecond() < maxTime) {

                solutionStatus = personalizeClient.describeSolution(describeSolutionRequest).solution().status();
                System.out.println("Solution status: " + solutionStatus);

                if (solutionStatus.equals("ACTIVE") || solutionStatus.equals("CREATE FAILED")) {
                    break;
                }
                try {
                    Thread.sleep(waitInMilliseconds);
                } catch (InterruptedException e) {
                    System.out.println(e.getMessage());
                }
            }

            if (solutionStatus.equals("ACTIVE")) {

                CreateSolutionVersionRequest createSolutionVersionRequest = CreateSolutionVersionRequest.builder()
                        .solutionArn(solutionArn)
                        .build();

                CreateSolutionVersionResponse createSolutionVersionResponse = personalizeClient
                        .createSolutionVersion(createSolutionVersionRequest);
                solutionVersionArn = createSolutionVersionResponse.solutionVersionArn();

                System.out.println("Solution version ARN: " + solutionVersionArn);

                DescribeSolutionVersionRequest describeSolutionVersionRequest = DescribeSolutionVersionRequest.builder()
                        .solutionVersionArn(solutionVersionArn)
                        .build();

                while (Instant.now().getEpochSecond() < maxTime) {

                    solutionVersionStatus = personalizeClient.describeSolutionVersion(describeSolutionVersionRequest)
                            .solutionVersion().status();
                    System.out.println("Solution version status: " + solutionVersionStatus);

                    if (solutionVersionStatus.equals("ACTIVE") || solutionVersionStatus.equals("CREATE FAILED")) {
                        break;
                    }
                    try {
                        Thread.sleep(waitInMilliseconds);
                    } catch (InterruptedException e) {
                        System.out.println(e.getMessage());
                    }
                }
                return solutionVersionArn;
            }
        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateSolutionVersion](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/CreateSolutionVersion)」を参照してください。

### `DeleteCampaign`
<a name="personalize_DeleteCampaign_java_2_topic"></a>

次のコード例は、`DeleteCampaign` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteSpecificCampaign(PersonalizeClient personalizeClient, String campaignArn) {
        try {
            DeleteCampaignRequest campaignRequest = DeleteCampaignRequest.builder()
                    .campaignArn(campaignArn)
                    .build();

            personalizeClient.deleteCampaign(campaignRequest);
            System.out.println("Delete request sent successfully.");
        } catch (PersonalizeException e) {
            System.err.println("Error deleting campaign: " + e.awsErrorDetails().errorMessage());
            throw new RuntimeException(e);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteCampaign](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/DeleteCampaign)」を参照してください。

### `DeleteEventTracker`
<a name="personalize_DeleteEventTracker_java_2_topic"></a>

次のコード例は、`DeleteEventTracker` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteEventTracker(PersonalizeClient personalizeClient, String eventTrackerArn) {
        try {
            DeleteEventTrackerRequest deleteEventTrackerRequest = DeleteEventTrackerRequest.builder()
                    .eventTrackerArn(eventTrackerArn)
                    .build();

            int status = personalizeClient.deleteEventTracker(deleteEventTrackerRequest).sdkHttpResponse().statusCode();

            System.out.println("Status code:" + status);

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteEventTracker](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/DeleteEventTracker)」を参照してください。

### `DeleteSolution`
<a name="personalize_DeleteSolution_java_2_topic"></a>

次のコード例は、`DeleteSolution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteGivenSolution(PersonalizeClient personalizeClient, String solutionArn) {

        try {
            DeleteSolutionRequest solutionRequest = DeleteSolutionRequest.builder()
                    .solutionArn(solutionArn)
                    .build();

            personalizeClient.deleteSolution(solutionRequest);
            System.out.println("Done");

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteSolution](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/DeleteSolution)」を参照してください。

### `DescribeCampaign`
<a name="personalize_DescribeCampaign_java_2_topic"></a>

次のコード例は、`DescribeCampaign` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeSpecificCampaign(PersonalizeClient personalizeClient, String campaignArn) {

        try {
            DescribeCampaignRequest campaignRequest = DescribeCampaignRequest.builder()
                    .campaignArn(campaignArn)
                    .build();

            DescribeCampaignResponse campaignResponse = personalizeClient.describeCampaign(campaignRequest);
            Campaign myCampaign = campaignResponse.campaign();
            System.out.println("The Campaign name is " + myCampaign.name());
            System.out.println("The Campaign status is " + myCampaign.status());

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeCampaign](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/DescribeCampaign)」を参照してください。

### `DescribeRecipe`
<a name="personalize_DescribeRecipe_java_2_topic"></a>

次のコード例は、`DescribeRecipe` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeSpecificRecipe(PersonalizeClient personalizeClient, String recipeArn) {

        try {
            DescribeRecipeRequest recipeRequest = DescribeRecipeRequest.builder()
                    .recipeArn(recipeArn)
                    .build();

            DescribeRecipeResponse recipeResponse = personalizeClient.describeRecipe(recipeRequest);
            System.out.println("The recipe name is " + recipeResponse.recipe().name());

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeRecipe](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/DescribeRecipe)」を参照してください。

### `DescribeSolution`
<a name="personalize_DescribeSolution_java_2_topic"></a>

次のコード例は、`DescribeSolution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeSpecificSolution(PersonalizeClient personalizeClient, String solutionArn) {

        try {
            DescribeSolutionRequest solutionRequest = DescribeSolutionRequest.builder()
                    .solutionArn(solutionArn)
                    .build();

            DescribeSolutionResponse response = personalizeClient.describeSolution(solutionRequest);
            System.out.println("The Solution name is " + response.solution().name());

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeSolution](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/DescribeSolution)」を参照してください。

### `ListCampaigns`
<a name="personalize_ListCampaigns_java_2_topic"></a>

次のコード例は、`ListCampaigns` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void listAllCampaigns(PersonalizeClient personalizeClient, String solutionArn) {

        try {
            ListCampaignsRequest campaignsRequest = ListCampaignsRequest.builder()
                    .maxResults(10)
                    .solutionArn(solutionArn)
                    .build();

            ListCampaignsResponse response = personalizeClient.listCampaigns(campaignsRequest);
            List<CampaignSummary> campaigns = response.campaigns();
            for (CampaignSummary campaign : campaigns) {
                System.out.println("Campaign name is : " + campaign.name());
                System.out.println("Campaign ARN is : " + campaign.campaignArn());
            }

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListCampaigns](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/ListCampaigns)」を参照してください。

### `ListDatasetGroups`
<a name="personalize_ListDatasetGroups_java_2_topic"></a>

次のコード例は、`ListDatasetGroups` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void listDSGroups(PersonalizeClient personalizeClient) {

        try {
            ListDatasetGroupsRequest groupsRequest = ListDatasetGroupsRequest.builder()
                    .maxResults(15)
                    .build();

            ListDatasetGroupsResponse groupsResponse = personalizeClient.listDatasetGroups(groupsRequest);
            List<DatasetGroupSummary> groups = groupsResponse.datasetGroups();
            for (DatasetGroupSummary group : groups) {
                System.out.println("The DataSet name is : " + group.name());
                System.out.println("The DataSet ARN is : " + group.datasetGroupArn());
            }

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListDatasetGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/ListDatasetGroups)」を参照してください。

### `ListRecipes`
<a name="personalize_ListRecipes_java_2_topic"></a>

次のコード例は、`ListRecipes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void listAllRecipes(PersonalizeClient personalizeClient) {

        try {
            ListRecipesRequest recipesRequest = ListRecipesRequest.builder()
                    .maxResults(15)
                    .build();

            ListRecipesResponse response = personalizeClient.listRecipes(recipesRequest);
            List<RecipeSummary> recipes = response.recipes();
            for (RecipeSummary recipe : recipes) {
                System.out.println("The recipe ARN is: " + recipe.recipeArn());
                System.out.println("The recipe name is: " + recipe.name());
            }

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListRecipes](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/ListRecipes)」を参照してください。

### `ListSolutions`
<a name="personalize_ListSolutions_java_2_topic"></a>

次のコード例は、`ListSolutions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static void listAllSolutions(PersonalizeClient personalizeClient, String datasetGroupArn) {

        try {
            ListSolutionsRequest solutionsRequest = ListSolutionsRequest.builder()
                    .maxResults(10)
                    .datasetGroupArn(datasetGroupArn)
                    .build();

            ListSolutionsResponse response = personalizeClient.listSolutions(solutionsRequest);
            List<SolutionSummary> solutions = response.solutions();
            for (SolutionSummary solution : solutions) {
                System.out.println("The solution ARN is: " + solution.solutionArn());
                System.out.println("The solution name is: " + solution.name());
            }

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListSolutions](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/ListSolutions)」を参照してください。

### `UpdateCampaign`
<a name="personalize_UpdateCampaign_java_2_topic"></a>

次のコード例は、`UpdateCampaign` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static String updateCampaign(PersonalizeClient personalizeClient,
            String campaignArn,
            String solutionVersionArn,
            Integer minProvisionedTPS) {

        try {
            // build the updateCampaignRequest
            UpdateCampaignRequest updateCampaignRequest = UpdateCampaignRequest.builder()
                    .campaignArn(campaignArn)
                    .solutionVersionArn(solutionVersionArn)
                    .minProvisionedTPS(minProvisionedTPS)
                    .build();

            // update the campaign
            personalizeClient.updateCampaign(updateCampaignRequest);

            DescribeCampaignRequest campaignRequest = DescribeCampaignRequest.builder()
                    .campaignArn(campaignArn)
                    .build();

            DescribeCampaignResponse campaignResponse = personalizeClient.describeCampaign(campaignRequest);
            Campaign updatedCampaign = campaignResponse.campaign();

            System.out.println("The Campaign status is " + updatedCampaign.status());
            return updatedCampaign.status();

        } catch (PersonalizeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateCampaign](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-2018-05-22/UpdateCampaign)」を参照してください。

# SDK for Java 2.x を使用した Amazon Personalize Events の例
<a name="java_2_personalize-events_code_examples"></a>

次のコード例は、Amazon Personalize Events AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutEvents`
<a name="personalize-events_PutEvents_java_2_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
        public static int putItems(PersonalizeEventsClient personalizeEventsClient,
                        String datasetArn,
                        String item1Id,
                        String item1PropertyName,
                        String item1PropertyValue,
                        String item2Id,
                        String item2PropertyName,
                        String item2PropertyValue) {

                int responseCode = 0;
                ArrayList<Item> items = new ArrayList<>();

                try {
                        Item item1 = Item.builder()
                                        .itemId(item1Id)
                                        .properties(String.format("{\"%1$s\": \"%2$s\"}",
                                                        item1PropertyName, item1PropertyValue))
                                        .build();

                        items.add(item1);

                        Item item2 = Item.builder()
                                        .itemId(item2Id)
                                        .properties(String.format("{\"%1$s\": \"%2$s\"}",
                                                        item2PropertyName, item2PropertyValue))
                                        .build();

                        items.add(item2);

                        PutItemsRequest putItemsRequest = PutItemsRequest.builder()
                                        .datasetArn(datasetArn)
                                        .items(items)
                                        .build();

                        responseCode = personalizeEventsClient.putItems(putItemsRequest).sdkHttpResponse().statusCode();
                        System.out.println("Response code: " + responseCode);
                        return responseCode;

                } catch (PersonalizeEventsException e) {
                        System.out.println(e.awsErrorDetails().errorMessage());
                }
                return responseCode;
        }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutEvents](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-events-2018-03-22/PutEvents)」を参照してください。

### `PutUsers`
<a name="personalize-events_PutUsers_java_2_topic"></a>

次のコード例は、`PutUsers` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
        public static int putUsers(PersonalizeEventsClient personalizeEventsClient,
                        String datasetArn,
                        String user1Id,
                        String user1PropertyName,
                        String user1PropertyValue,
                        String user2Id,
                        String user2PropertyName,
                        String user2PropertyValue) {

                int responseCode = 0;
                ArrayList<User> users = new ArrayList<>();

                try {
                        User user1 = User.builder()
                                        .userId(user1Id)
                                        .properties(String.format("{\"%1$s\": \"%2$s\"}",
                                                        user1PropertyName, user1PropertyValue))
                                        .build();

                        users.add(user1);

                        User user2 = User.builder()
                                        .userId(user2Id)
                                        .properties(String.format("{\"%1$s\": \"%2$s\"}",
                                                        user2PropertyName, user2PropertyValue))
                                        .build();

                        users.add(user2);

                        PutUsersRequest putUsersRequest = PutUsersRequest.builder()
                                        .datasetArn(datasetArn)
                                        .users(users)
                                        .build();

                        responseCode = personalizeEventsClient.putUsers(putUsersRequest).sdkHttpResponse().statusCode();
                        System.out.println("Response code: " + responseCode);
                        return responseCode;

                } catch (PersonalizeEventsException e) {
                        System.out.println(e.awsErrorDetails().errorMessage());
                }
                return responseCode;
        }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutUsers](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-events-2018-03-22/PutUsers)」を参照してください。

# SDK for Java 2.x による Amazon Personalize Runtime の例
<a name="java_2_personalize-runtime_code_examples"></a>

次のコード例は、Amazon Personalize ランタイム AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetPersonalizedRanking`
<a name="personalize-runtime_GetPersonalizedRanking_java_2_topic"></a>

次のコード例は、`GetPersonalizedRanking` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。

```
    public static List<PredictedItem> getRankedRecs(PersonalizeRuntimeClient personalizeRuntimeClient,
            String campaignArn,
            String userId,
            ArrayList<String> items) {

        try {
            GetPersonalizedRankingRequest rankingRecommendationsRequest = GetPersonalizedRankingRequest.builder()
                    .campaignArn(campaignArn)
                    .userId(userId)
                    .inputList(items)
                    .build();

            GetPersonalizedRankingResponse recommendationsResponse = personalizeRuntimeClient
                    .getPersonalizedRanking(rankingRecommendationsRequest);
            List<PredictedItem> rankedItems = recommendationsResponse.personalizedRanking();
            int rank = 1;
            for (PredictedItem item : rankedItems) {
                System.out.println("Item ranked at position " + rank + " details");
                System.out.println("Item Id is : " + item.itemId());
                System.out.println("Item score is : " + item.score());
                System.out.println("---------------------------------------------");
                rank++;
            }
            return rankedItems;
        } catch (PersonalizeRuntimeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetPersonalizedRanking](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-runtime-2018-05-22/GetPersonalizedRanking)」を参照してください。

### `GetRecommendations`
<a name="personalize-runtime_GetRecommendations_java_2_topic"></a>

次のコード例は、`GetRecommendations` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/personalize#code-examples)での設定と実行の方法を確認してください。
推奨アイテムのリストを取得します。  

```
    public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String campaignArn, String userId) {

        try {
            GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder()
                    .campaignArn(campaignArn)
                    .numResults(20)
                    .userId(userId)
                    .build();

            GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient
                    .getRecommendations(recommendationsRequest);
            List<PredictedItem> items = recommendationsResponse.itemList();
            for (PredictedItem item : items) {
                System.out.println("Item Id is : " + item.itemId());
                System.out.println("Item score is : " + item.score());
            }

        } catch (AwsServiceException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
ドメインデータセットグループで作成されたレコメンダーから、推奨アイテムのリストを取得します。  

```
    public static void getRecs(PersonalizeRuntimeClient personalizeRuntimeClient, String recommenderArn,
            String userId) {

        try {
            GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder()
                    .recommenderArn(recommenderArn)
                    .numResults(20)
                    .userId(userId)
                    .build();

            GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient
                    .getRecommendations(recommendationsRequest);
            List<PredictedItem> items = recommendationsResponse.itemList();

            for (PredictedItem item : items) {
                System.out.println("Item Id is : " + item.itemId());
                System.out.println("Item score is : " + item.score());
            }
        } catch (AwsServiceException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
レコメンデーションをリクエストするときはフィルターを使用してください。  

```
    public static void getFilteredRecs(PersonalizeRuntimeClient personalizeRuntimeClient,
            String campaignArn,
            String userId,
            String filterArn,
            String parameter1Name,
            String parameter1Value1,
            String parameter1Value2,
            String parameter2Name,
            String parameter2Value) {

        try {

            Map<String, String> filterValues = new HashMap<>();

            filterValues.put(parameter1Name, String.format("\"%1$s\",\"%2$s\"",
                    parameter1Value1, parameter1Value2));
            filterValues.put(parameter2Name, String.format("\"%1$s\"",
                    parameter2Value));

            GetRecommendationsRequest recommendationsRequest = GetRecommendationsRequest.builder()
                    .campaignArn(campaignArn)
                    .numResults(20)
                    .userId(userId)
                    .filterArn(filterArn)
                    .filterValues(filterValues)
                    .build();

            GetRecommendationsResponse recommendationsResponse = personalizeRuntimeClient
                    .getRecommendations(recommendationsRequest);
            List<PredictedItem> items = recommendationsResponse.itemList();

            for (PredictedItem item : items) {
                System.out.println("Item Id is : " + item.itemId());
                System.out.println("Item score is : " + item.score());
            }
        } catch (PersonalizeRuntimeException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetRecommendations](https://docs.aws.amazon.com/goto/SdkForJavaV2/personalize-runtime-2018-05-22/GetRecommendations)」を参照してください。

# SDK for Java 2.x を使用した Amazon Pinpoint の例
<a name="java_2_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateApp`
<a name="pinpoint_CreateApp_java_2_topic"></a>

次のコード例は、`CreateApp` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.CreateAppRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateAppResponse;
import software.amazon.awssdk.services.pinpoint.model.CreateApplicationRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;

/**
 * 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 CreateApp {
    public static void main(String[] args) {
        final String usage = """

                 Usage:  <appName>

                 Where:
                  appName - The name of the application to create.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
        String appName = args[0];
        System.out.println("Creating an application with name: " + appName);

        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String appID = createApplication(pinpoint, appName);
        System.out.println("App ID is: " + appID);
        pinpoint.close();
    }

    public static String createApplication(PinpointClient pinpoint, String appName) {
        try {
            CreateApplicationRequest appRequest = CreateApplicationRequest.builder()
                    .name(appName)
                    .build();

            CreateAppRequest request = CreateAppRequest.builder()
                    .createApplicationRequest(appRequest)
                    .build();

            CreateAppResponse result = pinpoint.createApp(request);
            return result.applicationResponse().id();

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」**の「[CreateApp](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/CreateApp)」を参照してください。

### `CreateCampaign`
<a name="pinpoint_CreateCampaign_java_2_topic"></a>

次のコード例は、`CreateCampaign` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
キャンペーンの作成  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.CampaignResponse;
import software.amazon.awssdk.services.pinpoint.model.Message;
import software.amazon.awssdk.services.pinpoint.model.Schedule;
import software.amazon.awssdk.services.pinpoint.model.Action;
import software.amazon.awssdk.services.pinpoint.model.MessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.WriteCampaignRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateCampaignResponse;
import software.amazon.awssdk.services.pinpoint.model.CreateCampaignRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;

/**
 * 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 CreateCampaign {
    public static void main(String[] args) {

        final String usage = """

                Usage:   <appId> <segmentId>

                Where:
                  appId - The ID of the application to create the campaign in.
                  segmentId - The ID of the segment to create the campaign from.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        String segmentId = args[1];
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        createPinCampaign(pinpoint, appId, segmentId);
        pinpoint.close();
    }

    public static void createPinCampaign(PinpointClient pinpoint, String appId, String segmentId) {
        CampaignResponse result = createCampaign(pinpoint, appId, segmentId);
        System.out.println("Campaign " + result.name() + " created.");
        System.out.println(result.description());
    }

    public static CampaignResponse createCampaign(PinpointClient client, String appID, String segmentID) {

        try {
            Schedule schedule = Schedule.builder()
                    .startTime("IMMEDIATE")
                    .build();

            Message defaultMessage = Message.builder()
                    .action(Action.OPEN_APP)
                    .body("My message body.")
                    .title("My message title.")
                    .build();

            MessageConfiguration messageConfiguration = MessageConfiguration.builder()
                    .defaultMessage(defaultMessage)
                    .build();

            WriteCampaignRequest request = WriteCampaignRequest.builder()
                    .description("My description")
                    .schedule(schedule)
                    .name("MyCampaign")
                    .segmentId(segmentID)
                    .messageConfiguration(messageConfiguration)
                    .build();

            CreateCampaignResponse result = client.createCampaign(CreateCampaignRequest.builder()
                    .applicationId(appID)
                    .writeCampaignRequest(request).build());

            System.out.println("Campaign ID: " + result.campaignResponse().id());
            return result.campaignResponse();

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return null;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateCampaign](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/CreateCampaign) 」を参照してください。

### `CreateExportJob`
<a name="pinpoint_CreateExportJob_java_2_topic"></a>

次のコード例は、`CreateExportJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
エンドポイントをエクスポートする  

```
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.ExportJobRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpoint.model.CreateExportJobRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateExportJobResponse;
import software.amazon.awssdk.services.pinpoint.model.GetExportJobResponse;
import software.amazon.awssdk.services.pinpoint.model.GetExportJobRequest;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Object;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * To run this code example, you need to create an AWS Identity and Access
 * Management (IAM) role with the correct policy as described in this
 * documentation:
 * https://docs.aws.amazon.com/pinpoint/latest/developerguide/audience-data-export.html
 *
 * Also, 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 ExportEndpoints {
    public static void main(String[] args) {
        final String usage = """

                This program performs the following steps:

                1. Exports the endpoints to an Amazon S3 bucket.
                2. Downloads the exported endpoints files from Amazon S3.
                3. Parses the endpoints files to obtain the endpoint IDs and prints them.
                Usage: ExportEndpoints <applicationId> <s3BucketName> <iamExportRoleArn> <path>

                Where:
                  applicationId - The ID of the Amazon Pinpoint application that has the endpoint.
                  s3BucketName - The name of the Amazon S3 bucket to export the JSON file to.\s
                  iamExportRoleArn - The ARN of an IAM role that grants Amazon Pinpoint write permissions to the S3 bucket.  path - The path where the files downloaded from the Amazon S3 bucket are written (for example, C:/AWS/).
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String applicationId = args[0];
        String s3BucketName = args[1];
        String iamExportRoleArn = args[2];
        String path = args[3];
        System.out.println("Deleting an application with ID: " + applicationId);

        Region region = Region.US_EAST_1;
        PinpointClient pinpoint = PinpointClient.builder()
                .region(region)
                .build();

        S3Client s3Client = S3Client.builder()
                .region(region)
                .build();

        exportAllEndpoints(pinpoint, s3Client, applicationId, s3BucketName, path, iamExportRoleArn);
        pinpoint.close();
        s3Client.close();
    }

    public static void exportAllEndpoints(PinpointClient pinpoint,
            S3Client s3Client,
            String applicationId,
            String s3BucketName,
            String path,
            String iamExportRoleArn) {

        try {
            List<String> objectKeys = exportEndpointsToS3(pinpoint, s3Client, s3BucketName, iamExportRoleArn,
                    applicationId);
            List<String> endpointFileKeys = objectKeys.stream().filter(o -> o.endsWith(".gz"))
                    .collect(Collectors.toList());
            downloadFromS3(s3Client, path, s3BucketName, endpointFileKeys);

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static List<String> exportEndpointsToS3(PinpointClient pinpoint, S3Client s3Client, String s3BucketName,
            String iamExportRoleArn, String applicationId) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH_mm:ss.SSS_z");
        String endpointsKeyPrefix = "exports/" + applicationId + "_" + dateFormat.format(new Date());
        String s3UrlPrefix = "s3://" + s3BucketName + "/" + endpointsKeyPrefix + "/";
        List<String> objectKeys = new ArrayList<>();
        String key;

        try {
            // Defines the export job that Amazon Pinpoint runs.
            ExportJobRequest jobRequest = ExportJobRequest.builder()
                    .roleArn(iamExportRoleArn)
                    .s3UrlPrefix(s3UrlPrefix)
                    .build();

            CreateExportJobRequest exportJobRequest = CreateExportJobRequest.builder()
                    .applicationId(applicationId)
                    .exportJobRequest(jobRequest)
                    .build();

            System.out.format("Exporting endpoints from Amazon Pinpoint application %s to Amazon S3 " +
                    "bucket %s . . .\n", applicationId, s3BucketName);

            CreateExportJobResponse exportResult = pinpoint.createExportJob(exportJobRequest);
            String jobId = exportResult.exportJobResponse().id();
            System.out.println(jobId);
            printExportJobStatus(pinpoint, applicationId, jobId);

            ListObjectsV2Request v2Request = ListObjectsV2Request.builder()
                    .bucket(s3BucketName)
                    .prefix(endpointsKeyPrefix)
                    .build();

            // Create a list of object keys.
            ListObjectsV2Response v2Response = s3Client.listObjectsV2(v2Request);
            List<S3Object> objects = v2Response.contents();
            for (S3Object object : objects) {
                key = object.key();
                objectKeys.add(key);
            }

            return objectKeys;

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    private static void printExportJobStatus(PinpointClient pinpointClient,
            String applicationId,
            String jobId) {

        GetExportJobResponse getExportJobResult;
        String status;

        try {
            // Checks the job status until the job completes or fails.
            GetExportJobRequest exportJobRequest = GetExportJobRequest.builder()
                    .jobId(jobId)
                    .applicationId(applicationId)
                    .build();

            do {
                getExportJobResult = pinpointClient.getExportJob(exportJobRequest);
                status = getExportJobResult.exportJobResponse().jobStatus().toString().toUpperCase();
                System.out.format("Export job %s . . .\n", status);
                TimeUnit.SECONDS.sleep(3);

            } while (!status.equals("COMPLETED") && !status.equals("FAILED"));

            if (status.equals("COMPLETED")) {
                System.out.println("Finished exporting endpoints.");
            } else {
                System.err.println("Failed to export endpoints.");
                System.exit(1);
            }

        } catch (PinpointException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    // Download files from an Amazon S3 bucket and write them to the path location.
    public static void downloadFromS3(S3Client s3Client, String path, String s3BucketName, List<String> objectKeys) {

        String newPath;
        try {
            for (String key : objectKeys) {
                GetObjectRequest objectRequest = GetObjectRequest.builder()
                        .bucket(s3BucketName)
                        .key(key)
                        .build();

                ResponseBytes<GetObjectResponse> objectBytes = s3Client.getObjectAsBytes(objectRequest);
                byte[] data = objectBytes.asByteArray();

                // Write the data to a local file.
                String fileSuffix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                newPath = path + fileSuffix + ".gz";
                File myFile = new File(newPath);
                OutputStream os = new FileOutputStream(myFile);
                os.write(data);
            }
            System.out.println("Download finished.");

        } catch (S3Exception | NullPointerException | IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateExportJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/CreateExportJob)」を参照してください。

### `CreateImportJob`
<a name="pinpoint_CreateImportJob_java_2_topic"></a>

次のコード例は、`CreateImportJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
セグメントのインポート  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.CreateImportJobRequest;
import software.amazon.awssdk.services.pinpoint.model.ImportJobResponse;
import software.amazon.awssdk.services.pinpoint.model.ImportJobRequest;
import software.amazon.awssdk.services.pinpoint.model.Format;
import software.amazon.awssdk.services.pinpoint.model.CreateImportJobResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;

/**
 * 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 ImportSegment {
    public static void main(String[] args) {
        final String usage = """

                Usage:   <appId> <bucket> <key> <roleArn>\s

                Where:
                  appId - The application ID to create a segment for.
                  bucket - The name of the Amazon S3 bucket that contains the segment definitons.
                  key - The key of the S3 object.
                  roleArn - ARN of the role that allows Amazon Pinpoint to access S3. You need to set trust management for this to work. See https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html
                  """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        String bucket = args[1];
        String key = args[2];
        String roleArn = args[3];

        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        ImportJobResponse response = createImportSegment(pinpoint, appId, bucket, key, roleArn);
        System.out.println("Import job for " + bucket + " submitted.");
        System.out.println("See application " + response.applicationId() + " for import job status.");
        System.out.println("See application " + response.jobStatus() + " for import job status.");
        pinpoint.close();
    }

    public static ImportJobResponse createImportSegment(PinpointClient client,
            String appId,
            String bucket,
            String key,
            String roleArn) {

        try {
            ImportJobRequest importRequest = ImportJobRequest.builder()
                    .defineSegment(true)
                    .registerEndpoints(true)
                    .roleArn(roleArn)
                    .format(Format.JSON)
                    .s3Url("s3://" + bucket + "/" + key)
                    .build();

            CreateImportJobRequest jobRequest = CreateImportJobRequest.builder()
                    .importJobRequest(importRequest)
                    .applicationId(appId)
                    .build();

            CreateImportJobResponse jobResponse = client.createImportJob(jobRequest);
            return jobResponse.importJobResponse();

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateImportJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/CreateImportJob)」を参照してください。

### `CreateSegment`
<a name="pinpoint_CreateSegment_java_2_topic"></a>

次のコード例は、`CreateSegment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.AttributeDimension;
import software.amazon.awssdk.services.pinpoint.model.SegmentResponse;
import software.amazon.awssdk.services.pinpoint.model.AttributeType;
import software.amazon.awssdk.services.pinpoint.model.RecencyDimension;
import software.amazon.awssdk.services.pinpoint.model.SegmentBehaviors;
import software.amazon.awssdk.services.pinpoint.model.SegmentDemographics;
import software.amazon.awssdk.services.pinpoint.model.SegmentLocation;
import software.amazon.awssdk.services.pinpoint.model.SegmentDimensions;
import software.amazon.awssdk.services.pinpoint.model.WriteSegmentRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateSegmentRequest;
import software.amazon.awssdk.services.pinpoint.model.CreateSegmentResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import java.util.HashMap;
import java.util.Map;

/**
 * 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 CreateSegment {
        public static void main(String[] args) {
                final String usage = """

                                Usage:   <appId>

                                Where:
                                  appId - The application ID to create a segment for.

                                """;

                if (args.length != 1) {
                        System.out.println(usage);
                        System.exit(1);
                }

                String appId = args[0];
                PinpointClient pinpoint = PinpointClient.builder()
                                .region(Region.US_EAST_1)
                                .build();

                SegmentResponse result = createSegment(pinpoint, appId);
                System.out.println("Segment " + result.name() + " created.");
                System.out.println(result.segmentType());
                pinpoint.close();
        }

        public static SegmentResponse createSegment(PinpointClient client, String appId) {
                try {
                        Map<String, AttributeDimension> segmentAttributes = new HashMap<>();
                        segmentAttributes.put("Team", AttributeDimension.builder()
                                        .attributeType(AttributeType.INCLUSIVE)
                                        .values("Lakers")
                                        .build());

                        RecencyDimension recencyDimension = RecencyDimension.builder()
                                        .duration("DAY_30")
                                        .recencyType("ACTIVE")
                                        .build();

                        SegmentBehaviors segmentBehaviors = SegmentBehaviors.builder()
                                        .recency(recencyDimension)
                                        .build();

                        SegmentDemographics segmentDemographics = SegmentDemographics
                                        .builder()
                                        .build();

                        SegmentLocation segmentLocation = SegmentLocation
                                        .builder()
                                        .build();

                        SegmentDimensions dimensions = SegmentDimensions
                                        .builder()
                                        .attributes(segmentAttributes)
                                        .behavior(segmentBehaviors)
                                        .demographic(segmentDemographics)
                                        .location(segmentLocation)
                                        .build();

                        WriteSegmentRequest writeSegmentRequest = WriteSegmentRequest.builder()
                                        .name("MySegment")
                                        .dimensions(dimensions)
                                        .build();

                        CreateSegmentRequest createSegmentRequest = CreateSegmentRequest.builder()
                                        .applicationId(appId)
                                        .writeSegmentRequest(writeSegmentRequest)
                                        .build();

                        CreateSegmentResponse createSegmentResult = client.createSegment(createSegmentRequest);
                        System.out.println("Segment ID: " + createSegmentResult.segmentResponse().id());
                        System.out.println("Done");
                        return createSegmentResult.segmentResponse();

                } catch (PinpointException e) {
                        System.err.println(e.awsErrorDetails().errorMessage());
                        System.exit(1);
                }
                return null;
        }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateSegment](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/CreateSegment)」を参照してください。

### `DeleteApp`
<a name="pinpoint_DeleteApp_java_2_topic"></a>

次のコード例は、`DeleteApp` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
 アプリケーションを削除します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.DeleteAppRequest;
import software.amazon.awssdk.services.pinpoint.model.DeleteAppResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;

/**
 * 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 DeleteApp {
    public static void main(String[] args) {
        final String usage = """

                Usage:  <appId>

                Where:
                 appId - The ID of the application to delete.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        System.out.println("Deleting an application with ID: " + appId);
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        deletePinApp(pinpoint, appId);
        System.out.println("Done");
        pinpoint.close();
    }

    public static void deletePinApp(PinpointClient pinpoint, String appId) {
        try {
            DeleteAppRequest appRequest = DeleteAppRequest.builder()
                    .applicationId(appId)
                    .build();

            DeleteAppResponse result = pinpoint.deleteApp(appRequest);
            String appName = result.applicationResponse().name();
            System.out.println("Application " + appName + " has been deleted.");

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteApp](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/DeleteApp)」を参照してください。

### `DeleteEndpoint`
<a name="pinpoint_DeleteEndpoint_java_2_topic"></a>

次のコード例は、`DeleteEndpoint` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
エンドポイントを削除します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.DeleteEndpointRequest;
import software.amazon.awssdk.services.pinpoint.model.DeleteEndpointResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;

/**
 * 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 DeleteEndpoint {
    public static void main(String[] args) {
        final String usage = """

                Usage:   <appName> <endpointId >

                Where:
                  appId - The id of the application to delete.
                  endpointId - The id of the endpoint to delete.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        String endpointId = args[1];
        System.out.println("Deleting an endpoint with id: " + endpointId);
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        deletePinEncpoint(pinpoint, appId, endpointId);
        pinpoint.close();
    }

    public static void deletePinEncpoint(PinpointClient pinpoint, String appId, String endpointId) {
        try {
            DeleteEndpointRequest appRequest = DeleteEndpointRequest.builder()
                    .applicationId(appId)
                    .endpointId(endpointId)
                    .build();

            DeleteEndpointResponse result = pinpoint.deleteEndpoint(appRequest);
            String id = result.endpointResponse().id();
            System.out.println("The deleted endpoint id  " + id);

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteEndpoint](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/DeleteEndpoint)」を参照してください。

### `GetEndpoint`
<a name="pinpoint_GetEndpoint_java_2_topic"></a>

次のコード例は、`GetEndpoint` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.EndpointResponse;
import software.amazon.awssdk.services.pinpoint.model.GetEndpointResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpoint.model.GetEndpointRequest;

/**
 * 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 LookUpEndpoint {
    public static void main(String[] args) {
        final String usage = """

                Usage:   <appId> <endpoint>

                Where:
                  appId - The ID of the application to delete.
                  endpoint - The ID of the endpoint.\s
                  """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        String endpoint = args[1];
        System.out.println("Looking up an endpoint point with ID: " + endpoint);
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        lookupPinpointEndpoint(pinpoint, appId, endpoint);
        pinpoint.close();
    }

    public static void lookupPinpointEndpoint(PinpointClient pinpoint, String appId, String endpoint) {
        try {
            GetEndpointRequest appRequest = GetEndpointRequest.builder()
                    .applicationId(appId)
                    .endpointId(endpoint)
                    .build();

            GetEndpointResponse result = pinpoint.getEndpoint(appRequest);
            EndpointResponse endResponse = result.endpointResponse();

            // Uses the Google Gson library to pretty print the endpoint JSON.
            Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                    .setPrettyPrinting()
                    .create();

            String endpointJson = gson.toJson(endResponse);
            System.out.println(endpointJson);

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Done");
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetEndpoint](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/GetEndpoint)」を参照してください。

### `GetSegments`
<a name="pinpoint_GetSegments_java_2_topic"></a>

次のコード例は、`GetSegments` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
セグメントを一覧表示します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.GetSegmentsRequest;
import software.amazon.awssdk.services.pinpoint.model.GetSegmentsResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpoint.model.SegmentResponse;
import java.util.List;

/**
 * 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 ListSegments {
    public static void main(String[] args) {
        final String usage = """

                Usage:   <appId>

                Where:
                  appId - The ID of the application that contains a segment.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listSegs(pinpoint, appId);
        pinpoint.close();
    }

    public static void listSegs(PinpointClient pinpoint, String appId) {
        try {
            GetSegmentsRequest request = GetSegmentsRequest.builder()
                    .applicationId(appId)
                    .build();

            GetSegmentsResponse response = pinpoint.getSegments(request);
            List<SegmentResponse> segments = response.segmentsResponse().item();
            for (SegmentResponse segment : segments) {
                System.out
                        .println("Segement " + segment.id() + " " + segment.name() + " " + segment.lastModifiedDate());
            }

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetSegments](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/GetSegments)」を参照してください。

### `GetSmsChannel`
<a name="pinpoint_GetSmsChannel_java_2_topic"></a>

次のコード例は、`GetSmsChannel` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.SMSChannelResponse;
import software.amazon.awssdk.services.pinpoint.model.GetSmsChannelRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpoint.model.SMSChannelRequest;
import software.amazon.awssdk.services.pinpoint.model.UpdateSmsChannelRequest;
import software.amazon.awssdk.services.pinpoint.model.UpdateSmsChannelResponse;

/**
 * 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 UpdateChannel {
    public static void main(String[] args) {
        final String usage = """

                Usage: CreateChannel <appId>

                Where:
                  appId - The name of the application whose channel is updated.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        SMSChannelResponse getResponse = getSMSChannel(pinpoint, appId);
        toggleSmsChannel(pinpoint, appId, getResponse);
        pinpoint.close();
    }

    private static SMSChannelResponse getSMSChannel(PinpointClient client, String appId) {
        try {
            GetSmsChannelRequest request = GetSmsChannelRequest.builder()
                    .applicationId(appId)
                    .build();

            SMSChannelResponse response = client.getSmsChannel(request).smsChannelResponse();
            System.out.println("Channel state is " + response.enabled());
            return response;

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    private static void toggleSmsChannel(PinpointClient client, String appId, SMSChannelResponse getResponse) {
        boolean enabled = !getResponse.enabled();
        try {
            SMSChannelRequest request = SMSChannelRequest.builder()
                    .enabled(enabled)
                    .build();

            UpdateSmsChannelRequest updateRequest = UpdateSmsChannelRequest.builder()
                    .smsChannelRequest(request)
                    .applicationId(appId)
                    .build();

            UpdateSmsChannelResponse result = client.updateSmsChannel(updateRequest);
            System.out.println("Channel state: " + result.smsChannelResponse().enabled());

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetSmsChannel](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/GetSmsChannel)」を参照してください。

### `GetUserEndpoints`
<a name="pinpoint_GetUserEndpoints_java_2_topic"></a>

次のコード例は、`GetUserEndpoints` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.EndpointResponse;
import software.amazon.awssdk.services.pinpoint.model.GetUserEndpointsRequest;
import software.amazon.awssdk.services.pinpoint.model.GetUserEndpointsResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import java.util.List;

/**
 * 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 ListEndpointIds {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <applicationId> <userId>

                Where:
                   applicationId - The ID of the Amazon Pinpoint application that has the endpoint.
                   userId - The user id applicable to the endpoints""";

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String applicationId = args[0];
        String userId = args[1];
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listAllEndpoints(pinpoint, applicationId, userId);
        pinpoint.close();
    }

    public static void listAllEndpoints(PinpointClient pinpoint,
            String applicationId,
            String userId) {

        try {
            GetUserEndpointsRequest endpointsRequest = GetUserEndpointsRequest.builder()
                    .userId(userId)
                    .applicationId(applicationId)
                    .build();

            GetUserEndpointsResponse response = pinpoint.getUserEndpoints(endpointsRequest);
            List<EndpointResponse> endpoints = response.endpointsResponse().item();

            // Display the results.
            for (EndpointResponse endpoint : endpoints) {
                System.out.println("The channel type is: " + endpoint.channelType());
                System.out.println("The address is  " + endpoint.address());
            }

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetUserEndpoints](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/GetUserEndpoints)」を参照してください。

### `SendMessages`
<a name="pinpoint_SendMessages_java_2_topic"></a>

次のコード例は、`SendMessages` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
E メールメッセージを送信します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration;
import software.amazon.awssdk.services.pinpoint.model.ChannelType;
import software.amazon.awssdk.services.pinpoint.model.SimpleEmailPart;
import software.amazon.awssdk.services.pinpoint.model.SimpleEmail;
import software.amazon.awssdk.services.pinpoint.model.EmailMessage;
import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.MessageRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpointemail.PinpointEmailClient;
import software.amazon.awssdk.services.pinpointemail.model.Body;
import software.amazon.awssdk.services.pinpointemail.model.Content;
import software.amazon.awssdk.services.pinpointemail.model.Destination;
import software.amazon.awssdk.services.pinpointemail.model.EmailContent;
import software.amazon.awssdk.services.pinpointemail.model.Message;
import software.amazon.awssdk.services.pinpointemail.model.SendEmailRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * 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 SendEmailMessage {

        // The character encoding the you want to use for the subject line and
        // message body of the email.
        public static String charset = "UTF-8";

    // The body of the email for recipients whose email clients support HTML content.
    static final String body = """
        Amazon Pinpoint test (AWS SDK for Java 2.x)
                
        This email was sent through the Amazon Pinpoint Email API using the AWS SDK for Java 2.x
                
        """;

        public static void main(String[] args) {
                final String usage = """

                                Usage:    <subject> <appId> <senderAddress> <toAddress>

            Where:
               subject - The email subject to use.
               senderAddress - The from address. This address has to be verified in Amazon Pinpoint in the region you're using to send email\s
               toAddress - The to address. This address has to be verified in Amazon Pinpoint in the region you're using to send email\s
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String subject = args[0];
        String senderAddress = args[1];
        String toAddress = args[2];
        System.out.println("Sending a message");
        PinpointEmailClient pinpoint = PinpointEmailClient.builder()
            .region(Region.US_EAST_1)
            .build();

        sendEmail(pinpoint, subject, senderAddress, toAddress);
        System.out.println("Email was sent");
        pinpoint.close();
    }

    public static void sendEmail(PinpointEmailClient pinpointEmailClient, String subject, String senderAddress, String toAddress) {
        try {
            Content content = Content.builder()
                .data(body)
                .build();

            Body messageBody = Body.builder()
                .text(content)
                .build();

            Message message = Message.builder()
                .body(messageBody)
                .subject(Content.builder().data(subject).build())
                .build();

            Destination destination = Destination.builder()
                .toAddresses(toAddress)
                .build();

            EmailContent emailContent = EmailContent.builder()
                .simple(message)
                .build();

            SendEmailRequest sendEmailRequest = SendEmailRequest.builder()
                .fromEmailAddress(senderAddress)
                .destination(destination)
                .content(emailContent)
                .build();

            pinpointEmailClient.sendEmail(sendEmailRequest);
            System.out.println("Message Sent");

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
CC の値を使用して E メールメッセージを送信します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import  software.amazon.awssdk.services.pinpointemail.PinpointEmailClient;
import software.amazon.awssdk.services.pinpointemail.model.Body;
import software.amazon.awssdk.services.pinpointemail.model.Content;
import software.amazon.awssdk.services.pinpointemail.model.Destination;
import software.amazon.awssdk.services.pinpointemail.model.EmailContent;
import software.amazon.awssdk.services.pinpointemail.model.Message;
import software.amazon.awssdk.services.pinpointemail.model.SendEmailRequest;
import java.util.ArrayList;

/**
 * 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 SendEmailMessageCC {

    // The body of the email.
    static final String body = """
        Amazon Pinpoint test (AWS SDK for Java 2.x)
                
        This email was sent through the Amazon Pinpoint Email API using the AWS SDK for Java 2.x
                
        """;
    public static void main(String[] args) {
        final String usage = """

            Usage:    <subject> <senderAddress> <toAddress> <ccAddress>

            Where:
               subject - The email subject to use.
               senderAddress - The from address. This address has to be verified in Amazon Pinpoint in the region you're using to send email\s
               toAddress - The to address. This address has to be verified in Amazon Pinpoint in the region you're using to send email\s
               ccAddress - The CC address.
            """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String subject = args[0];
        String senderAddress = args[1];
        String toAddress = args[2];
        String ccAddress = args[3];

        System.out.println("Sending a message");
        PinpointEmailClient pinpoint = PinpointEmailClient.builder()
            .region(Region.US_EAST_1)
            .build();

        ArrayList<String> ccList = new ArrayList<>();
        ccList.add(ccAddress);
        sendEmail(pinpoint, subject, senderAddress, toAddress, ccList);
        pinpoint.close();
    }

    public static void sendEmail(PinpointEmailClient pinpointEmailClient, String subject, String senderAddress, String toAddress, ArrayList<String> ccAddresses) {
        try {
            Content content = Content.builder()
                .data(body)
                .build();

            Body messageBody = Body.builder()
                .text(content)
                .build();

            Message message = Message.builder()
                .body(messageBody)
                .subject(Content.builder().data(subject).build())
                .build();

            Destination destination = Destination.builder()
                .toAddresses(toAddress)
                .ccAddresses(ccAddresses)
                .build();

            EmailContent emailContent = EmailContent.builder()
                .simple(message)
                .build();

            SendEmailRequest sendEmailRequest = SendEmailRequest.builder()
                .fromEmailAddress(senderAddress)
                .destination(destination)
                .content(emailContent)
                .build();

            pinpointEmailClient.sendEmail(sendEmailRequest);
            System.out.println("Message Sent");

        } catch (PinpointException e) {
            // Handle exception
            e.printStackTrace();
        }
    }
}
```
SMS メッセージを送信します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.SMSMessage;
import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration;
import software.amazon.awssdk.services.pinpoint.model.ChannelType;
import software.amazon.awssdk.services.pinpoint.model.MessageRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesResponse;
import software.amazon.awssdk.services.pinpoint.model.MessageResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import java.util.HashMap;
import java.util.Map;

/**
 * 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 SendMessage {

        // The type of SMS message that you want to send. If you plan to send
        // time-sensitive content, specify TRANSACTIONAL. If you plan to send
        // marketing-related content, specify PROMOTIONAL.
        public static String messageType = "TRANSACTIONAL";

        // The registered keyword associated with the originating short code.
        public static String registeredKeyword = "myKeyword";

        // The sender ID to use when sending the message. Support for sender ID
        // varies by country or region. For more information, see
        // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html
        public static String senderId = "MySenderID";

        public static void main(String[] args) {
                final String usage = """

                                Usage:   <message> <appId> <originationNumber> <destinationNumber>\s

                                Where:
                                  message - The body of the message to send.
                                  appId - The Amazon Pinpoint project/application ID to use when you send this message.
                                  originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654).
                                  destinationNumber - The recipient's phone number.  For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s
                                  """;

                if (args.length != 4) {
                        System.out.println(usage);
                        System.exit(1);
                }

                String message = args[0];
                String appId = args[1];
                String originationNumber = args[2];
                String destinationNumber = args[3];
                System.out.println("Sending a message");
                PinpointClient pinpoint = PinpointClient.builder()
                                .region(Region.US_EAST_1)
                                .build();

                sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber);
                pinpoint.close();
        }

        public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId,
                        String originationNumber,
                        String destinationNumber) {
                try {
                        Map<String, AddressConfiguration> addressMap = new HashMap<String, AddressConfiguration>();
                        AddressConfiguration addConfig = AddressConfiguration.builder()
                                        .channelType(ChannelType.SMS)
                                        .build();

                        addressMap.put(destinationNumber, addConfig);
                        SMSMessage smsMessage = SMSMessage.builder()
                                        .body(message)
                                        .messageType(messageType)
                                        .originationNumber(originationNumber)
                                        .senderId(senderId)
                                        .keyword(registeredKeyword)
                                        .build();

                        // Create a DirectMessageConfiguration object.
                        DirectMessageConfiguration direct = DirectMessageConfiguration.builder()
                                        .smsMessage(smsMessage)
                                        .build();

                        MessageRequest msgReq = MessageRequest.builder()
                                        .addresses(addressMap)
                                        .messageConfiguration(direct)
                                        .build();

                        // create a SendMessagesRequest object
                        SendMessagesRequest request = SendMessagesRequest.builder()
                                        .applicationId(appId)
                                        .messageRequest(msgReq)
                                        .build();

                        SendMessagesResponse response = pinpoint.sendMessages(request);
                        MessageResponse msg1 = response.messageResponse();
                        Map map1 = msg1.result();

                        // Write out the result of sendMessage.
                        map1.forEach((k, v) -> System.out.println((k + ":" + v)));

                } catch (PinpointException e) {
                        System.err.println(e.awsErrorDetails().errorMessage());
                        System.exit(1);
                }
        }
}
```
SMS メッセージをバッチ送信します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.DirectMessageConfiguration;
import software.amazon.awssdk.services.pinpoint.model.SMSMessage;
import software.amazon.awssdk.services.pinpoint.model.AddressConfiguration;
import software.amazon.awssdk.services.pinpoint.model.ChannelType;
import software.amazon.awssdk.services.pinpoint.model.MessageRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesRequest;
import software.amazon.awssdk.services.pinpoint.model.SendMessagesResponse;
import software.amazon.awssdk.services.pinpoint.model.MessageResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;

import java.util.HashMap;
import java.util.Map;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SendMessageBatch {

    // The type of SMS message that you want to send. If you plan to send
    // time-sensitive content, specify TRANSACTIONAL. If you plan to send
    // marketing-related content, specify PROMOTIONAL.
    public static String messageType = "TRANSACTIONAL";

    // The registered keyword associated with the originating short code.
    public static String registeredKeyword = "myKeyword";

    // The sender ID to use when sending the message. Support for sender ID
    // varies by country or region. For more information, see
    // https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-countries.html
    public static String senderId = "MySenderID";

    public static void main(String[] args) {
        final String usage = """
                
                Usage:   <message> <appId> <originationNumber> <destinationNumber> <destinationNumber1>\s
                
                Where:
                  message - The body of the message to send.
                  appId - The Amazon Pinpoint project/application ID to use when you send this message.
                  originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654).
                  destinationNumber - The recipient's phone number.  For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).
                  destinationNumber1 - The second recipient's phone number.  For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String appId = args[1];
        String originationNumber = args[2];
        String destinationNumber = args[3];
        String destinationNumber1 = args[4];
        System.out.println("Sending a message");
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        sendSMSMessage(pinpoint, message, appId, originationNumber, destinationNumber, destinationNumber1);
        pinpoint.close();
    }

    public static void sendSMSMessage(PinpointClient pinpoint, String message, String appId,
                                      String originationNumber,
                                      String destinationNumber, String destinationNumber1) {
        try {
            Map<String, AddressConfiguration> addressMap = new HashMap<String, AddressConfiguration>();
            AddressConfiguration addConfig = AddressConfiguration.builder()
                    .channelType(ChannelType.SMS)
                    .build();

            // Add an entry to the Map object for each number to whom you want to send a
            // message.
            addressMap.put(destinationNumber, addConfig);
            addressMap.put(destinationNumber1, addConfig);
            SMSMessage smsMessage = SMSMessage.builder()
                    .body(message)
                    .messageType(messageType)
                    .originationNumber(originationNumber)
                    .senderId(senderId)
                    .keyword(registeredKeyword)
                    .build();

            // Create a DirectMessageConfiguration object.
            DirectMessageConfiguration direct = DirectMessageConfiguration.builder()
                    .smsMessage(smsMessage)
                    .build();

            MessageRequest msgReq = MessageRequest.builder()
                    .addresses(addressMap)
                    .messageConfiguration(direct)
                    .build();

            // Create a SendMessagesRequest object.
            SendMessagesRequest request = SendMessagesRequest.builder()
                    .applicationId(appId)
                    .messageRequest(msgReq)
                    .build();

            SendMessagesResponse response = pinpoint.sendMessages(request);
            MessageResponse msg1 = response.messageResponse();
            Map map1 = msg1.result();

            // Write out the result of sendMessage.
            map1.forEach((k, v) -> System.out.println((k + ":" + v)));

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SendMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/SendMessages)」を参照してください。

### `UpdateEndpoint`
<a name="pinpoint_UpdateEndpoint_java_2_topic"></a>

次のコード例は、`UpdateEndpoint` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpoint.PinpointClient;
import software.amazon.awssdk.services.pinpoint.model.EndpointResponse;
import software.amazon.awssdk.services.pinpoint.model.EndpointRequest;
import software.amazon.awssdk.services.pinpoint.model.UpdateEndpointRequest;
import software.amazon.awssdk.services.pinpoint.model.UpdateEndpointResponse;
import software.amazon.awssdk.services.pinpoint.model.GetEndpointRequest;
import software.amazon.awssdk.services.pinpoint.model.GetEndpointResponse;
import software.amazon.awssdk.services.pinpoint.model.PinpointException;
import software.amazon.awssdk.services.pinpoint.model.EndpointDemographic;
import software.amazon.awssdk.services.pinpoint.model.EndpointLocation;
import software.amazon.awssdk.services.pinpoint.model.EndpointUser;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Date;

/**
 * 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 UpdateEndpoint {
    public static void main(String[] args) {
        final String usage = """

                Usage:  <appId>

                Where:
                  appId - The ID of the application to create an endpoint for.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String appId = args[0];
        PinpointClient pinpoint = PinpointClient.builder()
                .region(Region.US_EAST_1)
                .build();

        EndpointResponse response = createEndpoint(pinpoint, appId);
        System.out.println("Got Endpoint: " + response.id());
        pinpoint.close();
    }

    public static EndpointResponse createEndpoint(PinpointClient client, String appId) {
        String endpointId = UUID.randomUUID().toString();
        System.out.println("Endpoint ID: " + endpointId);

        try {
            EndpointRequest endpointRequest = createEndpointRequestData();
            UpdateEndpointRequest updateEndpointRequest = UpdateEndpointRequest.builder()
                    .applicationId(appId)
                    .endpointId(endpointId)
                    .endpointRequest(endpointRequest)
                    .build();

            UpdateEndpointResponse updateEndpointResponse = client.updateEndpoint(updateEndpointRequest);
            System.out.println("Update Endpoint Response: " + updateEndpointResponse.messageBody());

            GetEndpointRequest getEndpointRequest = GetEndpointRequest.builder()
                    .applicationId(appId)
                    .endpointId(endpointId)
                    .build();

            GetEndpointResponse getEndpointResponse = client.getEndpoint(getEndpointRequest);
            System.out.println(getEndpointResponse.endpointResponse().address());
            System.out.println(getEndpointResponse.endpointResponse().channelType());
            System.out.println(getEndpointResponse.endpointResponse().applicationId());
            System.out.println(getEndpointResponse.endpointResponse().endpointStatus());
            System.out.println(getEndpointResponse.endpointResponse().requestId());
            System.out.println(getEndpointResponse.endpointResponse().user());

            return getEndpointResponse.endpointResponse();

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    private static EndpointRequest createEndpointRequestData() {
        try {
            List<String> favoriteTeams = new ArrayList<>();
            favoriteTeams.add("Lakers");
            favoriteTeams.add("Warriors");
            HashMap<String, List<String>> customAttributes = new HashMap<>();
            customAttributes.put("team", favoriteTeams);

            EndpointDemographic demographic = EndpointDemographic.builder()
                    .appVersion("1.0")
                    .make("apple")
                    .model("iPhone")
                    .modelVersion("7")
                    .platform("ios")
                    .platformVersion("10.1.1")
                    .timezone("America/Los_Angeles")
                    .build();

            EndpointLocation location = EndpointLocation.builder()
                    .city("Los Angeles")
                    .country("US")
                    .latitude(34.0)
                    .longitude(-118.2)
                    .postalCode("90068")
                    .region("CA")
                    .build();

            Map<String, Double> metrics = new HashMap<>();
            metrics.put("health", 100.00);
            metrics.put("luck", 75.00);

            EndpointUser user = EndpointUser.builder()
                    .userId(UUID.randomUUID().toString())
                    .build();

            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); // Quoted "Z" to indicate UTC, no timezone
                                                                           // offset
            String nowAsISO = df.format(new Date());

            return EndpointRequest.builder()
                    .address(UUID.randomUUID().toString())
                    .attributes(customAttributes)
                    .channelType("APNS")
                    .demographic(demographic)
                    .effectiveDate(nowAsISO)
                    .location(location)
                    .metrics(metrics)
                    .optOut("NONE")
                    .requestId(UUID.randomUUID().toString())
                    .user(user)
                    .build();

        } catch (PinpointException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateEndpoint](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-2016-12-01/UpdateEndpoint)」を参照してください。

# SDK for Java 2.x を使用した Amazon Pinpoint SMS および音声 API の例
<a name="java_2_pinpoint-sms-voice_code_examples"></a>

次のコード例は、Amazon Pinpoint SMS および音声 API AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendVoiceMessage`
<a name="pinpoint-sms-voice_SendVoiceMessage_java_2_topic"></a>

次のコード例は、`SendVoiceMessage` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.pinpointsmsvoice.PinpointSmsVoiceClient;
import software.amazon.awssdk.services.pinpointsmsvoice.model.SSMLMessageType;
import software.amazon.awssdk.services.pinpointsmsvoice.model.VoiceMessageContent;
import software.amazon.awssdk.services.pinpointsmsvoice.model.SendVoiceMessageRequest;
import software.amazon.awssdk.services.pinpointsmsvoice.model.PinpointSmsVoiceException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SendVoiceMessage {

    // The Amazon Polly voice that you want to use to send the message. For a list
    // of voices, see https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
    static final String voiceName = "Matthew";

    // The language to use when sending the message. For a list of supported
    // languages, see
    // https://docs.aws.amazon.com/polly/latest/dg/SupportedLanguage.html
    static final String languageCode = "en-US";

    // The content of the message. This example uses SSML to customize and control
    // certain aspects of the message, such as by adding pauses and changing
    // phonation. The message can't contain any line breaks.
    static final String ssmlMessage = "<speak>This is a test message sent from "
            + "<emphasis>Amazon Pinpoint</emphasis> "
            + "using the <break strength='weak'/>AWS "
            + "SDK for Java. "
            + "<amazon:effect phonation='soft'>Thank "
            + "you for listening.</amazon:effect></speak>";

    public static void main(String[] args) {

        final String usage = """
                Usage:   <originationNumber> <destinationNumber>\s
                
                Where:
                  originationNumber - The phone number or short code that you specify has to be associated with your Amazon Pinpoint account. For best results, specify long codes in E.164 format (for example, +1-555-555-5654).
                  destinationNumber - The recipient's phone number.  For best results, you should specify the phone number in E.164 format (for example, +1-555-555-5654).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }
        String originationNumber = args[0];
        String destinationNumber = args[1];
        System.out.println("Sending a voice message");

        // Set the content type to application/json.
        List<String> listVal = new ArrayList<>();
        listVal.add("application/json");
        Map<String, List<String>> values = new HashMap<>();
        values.put("Content-Type", listVal);

        ClientOverrideConfiguration config2 = ClientOverrideConfiguration.builder()
                .headers(values)
                .build();

        PinpointSmsVoiceClient client = PinpointSmsVoiceClient.builder()
                .overrideConfiguration(config2)
                .region(Region.US_EAST_1)
                .build();

        sendVoiceMsg(client, originationNumber, destinationNumber);
        client.close();
    }

    public static void sendVoiceMsg(PinpointSmsVoiceClient client, String originationNumber,
                                    String destinationNumber) {
        try {
            SSMLMessageType ssmlMessageType = SSMLMessageType.builder()
                    .languageCode(languageCode)
                    .text(ssmlMessage)
                    .voiceId(voiceName)
                    .build();

            VoiceMessageContent content = VoiceMessageContent.builder()
                    .ssmlMessage(ssmlMessageType)
                    .build();

            SendVoiceMessageRequest voiceMessageRequest = SendVoiceMessageRequest.builder()
                    .destinationPhoneNumber(destinationNumber)
                    .originationPhoneNumber(originationNumber)
                    .content(content)
                    .build();

            client.sendVoiceMessage(voiceMessageRequest);
            System.out.println("The message was sent successfully.");

        } catch (PinpointSmsVoiceException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SendVoiceMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/pinpoint-sms-voice-2018-09-05/SendVoiceMessage)」を参照してください。

# SDK for Java 2.x を使用する Amazon Polly の例
<a name="java_2_polly_code_examples"></a>

次のコード例は、Amazon Polly AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DescribeVoices`
<a name="polly_DescribeVoices_java_2_topic"></a>

次のコード例は、`DescribeVoices` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.polly.PollyClient;
import software.amazon.awssdk.services.polly.model.DescribeVoicesRequest;
import software.amazon.awssdk.services.polly.model.DescribeVoicesResponse;
import software.amazon.awssdk.services.polly.model.PollyException;
import software.amazon.awssdk.services.polly.model.Voice;
import java.util.List;

/**
 * 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 DescribeVoicesSample {
    public static void main(String args[]) {
        PollyClient polly = PollyClient.builder()
                .region(Region.US_WEST_2)
                .build();

        describeVoice(polly);
        polly.close();
    }

    public static void describeVoice(PollyClient polly) {
        try {
            DescribeVoicesRequest voicesRequest = DescribeVoicesRequest.builder()
                    .languageCode("en-US")
                    .build();

            DescribeVoicesResponse enUsVoicesResult = polly.describeVoices(voicesRequest);
            List<Voice> voices = enUsVoicesResult.voices();
            for (Voice myVoice : voices) {
                System.out.println("The ID of the voice is " + myVoice.id());
                System.out.println("The gender of the voice is " + myVoice.gender());
            }

        } catch (PollyException e) {
            System.err.println("Exception caught: " + e);
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeVoices](https://docs.aws.amazon.com/goto/SdkForJavaV2/polly-2016-06-10/DescribeVoices)」を参照してください。

### `ListLexicons`
<a name="polly_ListLexicons_java_2_topic"></a>

次のコード例は、`ListLexicons` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.polly.PollyClient;
import software.amazon.awssdk.services.polly.model.ListLexiconsResponse;
import software.amazon.awssdk.services.polly.model.ListLexiconsRequest;
import software.amazon.awssdk.services.polly.model.LexiconDescription;
import software.amazon.awssdk.services.polly.model.PollyException;
import java.util.List;

/**
 * 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 ListLexicons {
    public static void main(String args[]) {
        PollyClient polly = PollyClient.builder()
                .region(Region.US_WEST_2)
                .build();

        listLexicons(polly);
        polly.close();
    }

    public static void listLexicons(PollyClient client) {
        try {
            ListLexiconsRequest listLexiconsRequest = ListLexiconsRequest.builder()
                    .build();

            ListLexiconsResponse listLexiconsResult = client.listLexicons(listLexiconsRequest);
            List<LexiconDescription> lexiconDescription = listLexiconsResult.lexicons();
            for (LexiconDescription lexDescription : lexiconDescription) {
                System.out.println("The name of the Lexicon is " + lexDescription.name());
            }

        } catch (PollyException e) {
            System.err.println("Exception caught: " + e);
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListLexicons](https://docs.aws.amazon.com/goto/SdkForJavaV2/polly-2016-06-10/ListLexicons)」を参照してください。

### `SynthesizeSpeech`
<a name="polly_SynthesizeSpeech_java_2_topic"></a>

次のコード例は、`SynthesizeSpeech` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
import javazoom.jl.decoder.JavaLayerException;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.polly.PollyClient;
import software.amazon.awssdk.services.polly.model.DescribeVoicesRequest;
import software.amazon.awssdk.services.polly.model.Voice;
import software.amazon.awssdk.services.polly.model.DescribeVoicesResponse;
import software.amazon.awssdk.services.polly.model.OutputFormat;
import software.amazon.awssdk.services.polly.model.PollyException;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechRequest;
import software.amazon.awssdk.services.polly.model.SynthesizeSpeechResponse;
import java.io.IOException;
import java.io.InputStream;
import javazoom.jl.player.advanced.AdvancedPlayer;
import javazoom.jl.player.advanced.PlaybackEvent;
import javazoom.jl.player.advanced.PlaybackListener;

/**
 * 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 PollyDemo {
    private static final String SAMPLE = "Congratulations. You have successfully built this working demo " +
            " of Amazon Polly in Java Version 2. Have fun building voice enabled apps with Amazon Polly (that's me!), and always "
            +
            " look at the AWS website for tips and tricks on using Amazon Polly and other great services from AWS";

    public static void main(String args[]) {
        PollyClient polly = PollyClient.builder()
                .region(Region.US_WEST_2)
                .build();

        talkPolly(polly);
        polly.close();
    }

    public static void talkPolly(PollyClient polly) {
        try {
            DescribeVoicesRequest describeVoiceRequest = DescribeVoicesRequest.builder()
                    .engine("standard")
                    .build();

            DescribeVoicesResponse describeVoicesResult = polly.describeVoices(describeVoiceRequest);
            Voice voice = describeVoicesResult.voices().stream()
                    .filter(v -> v.name().equals("Joanna"))
                    .findFirst()
                    .orElseThrow(() -> new RuntimeException("Voice not found"));
            InputStream stream = synthesize(polly, SAMPLE, voice, OutputFormat.MP3);
            AdvancedPlayer player = new AdvancedPlayer(stream,
                    javazoom.jl.player.FactoryRegistry.systemRegistry().createAudioDevice());
            player.setPlayBackListener(new PlaybackListener() {
                public void playbackStarted(PlaybackEvent evt) {
                    System.out.println("Playback started");
                    System.out.println(SAMPLE);
                }

                public void playbackFinished(PlaybackEvent evt) {
                    System.out.println("Playback finished");
                }
            });

            // play it!
            player.play();

        } catch (PollyException | JavaLayerException | IOException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static InputStream synthesize(PollyClient polly, String text, Voice voice, OutputFormat format)
            throws IOException {
        SynthesizeSpeechRequest synthReq = SynthesizeSpeechRequest.builder()
                .text(text)
                .voiceId(voice.id())
                .outputFormat(format)
                .build();

        ResponseInputStream<SynthesizeSpeechResponse> synthRes = polly.synthesizeSpeech(synthReq);
        return synthRes;
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SynthesizeSpeech](https://docs.aws.amazon.com/goto/SdkForJavaV2/polly-2016-06-10/SynthesizeSpeech)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_java_2_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Java 2.x**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_fsa_app) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Java 2.x を使用する Amazon RDS の例
<a name="java_2_rds_code_examples"></a>

次のコード例は、Amazon RDS AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon RDS
<a name="rds_Hello_java_2_topic"></a>

次のコード例は、Amazon RDS の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse;
import software.amazon.awssdk.services.rds.model.DBInstance;
import software.amazon.awssdk.services.rds.model.RdsException;
import java.util.List;

/**
 * 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 DescribeDBInstances {

    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        describeInstances(rdsClient);
        rdsClient.close();
    }

    public static void describeInstances(RdsClient rdsClient) {
        try {
            DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
            List<DBInstance> instanceList = response.dbInstances();
            for (DBInstance instance : instanceList) {
                System.out.println("Instance ARN is: " + instance.dbInstanceArn());
                System.out.println("The Engine is " + instance.engine());
                System.out.println("Connection endpoint is" + instance.endpoint().address());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBInstances)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="rds_Scenario_GetStartedInstances_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム DB パラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用するように設定した DB インスタンスを作成します。DB インスタンスにはデータベースも含まれています。
+ インスタンスのスナップショットを取得します。
+ インスタンスとパラメータグループを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。
複数のオペレーションを実行します。  

```
import com.google.gson.Gson;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest;
import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse;
import software.amazon.awssdk.services.rds.model.CreateDbParameterGroupResponse;
import software.amazon.awssdk.services.rds.model.CreateDbSnapshotRequest;
import software.amazon.awssdk.services.rds.model.CreateDbSnapshotResponse;
import software.amazon.awssdk.services.rds.model.DBEngineVersion;
import software.amazon.awssdk.services.rds.model.DBInstance;
import software.amazon.awssdk.services.rds.model.DBParameterGroup;
import software.amazon.awssdk.services.rds.model.DBSnapshot;
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest;
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse;
import software.amazon.awssdk.services.rds.model.DescribeDbEngineVersionsRequest;
import software.amazon.awssdk.services.rds.model.DescribeDbEngineVersionsResponse;
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest;
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse;
import software.amazon.awssdk.services.rds.model.DescribeDbParameterGroupsResponse;
import software.amazon.awssdk.services.rds.model.DescribeDbParametersResponse;
import software.amazon.awssdk.services.rds.model.DescribeDbSnapshotsRequest;
import software.amazon.awssdk.services.rds.model.DescribeDbSnapshotsResponse;
import software.amazon.awssdk.services.rds.model.DescribeOrderableDbInstanceOptionsResponse;
import software.amazon.awssdk.services.rds.model.ModifyDbParameterGroupResponse;
import software.amazon.awssdk.services.rds.model.OrderableDBInstanceOption;
import software.amazon.awssdk.services.rds.model.Parameter;
import software.amazon.awssdk.services.rds.model.RdsException;
import software.amazon.awssdk.services.rds.model.CreateDbParameterGroupRequest;
import software.amazon.awssdk.services.rds.model.DescribeDbParameterGroupsRequest;
import software.amazon.awssdk.services.rds.model.DescribeDbParametersRequest;
import software.amazon.awssdk.services.rds.model.ModifyDbParameterGroupRequest;
import software.amazon.awssdk.services.rds.model.DescribeOrderableDbInstanceOptionsRequest;
import software.amazon.awssdk.services.rds.model.DeleteDbParameterGroupRequest;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 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
 *
 * This example requires an AWS Secrets Manager secret that contains the
 * database credentials. If you do not create a
 * secret, this example will not work. For details, see:
 *
 * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html
 *
 * This Java example performs these tasks:
 *
 * 1. Returns a list of the available DB engines.
 * 2. Selects an engine family and create a custom DB parameter group.
 * 3. Gets the parameter groups.
 * 4. Gets parameters in the group.
 * 5. Modifies the auto_increment_offset parameter.
 * 6. Gets and displays the updated parameters.
 * 7. Gets a list of allowed engine versions.
 * 8. Gets a list of micro instance classes available for the selected engine.
 * 9. Creates an RDS database instance that contains a MySql database and uses
 * the parameter group.
 * 10. Waits for the DB instance to be ready and prints out the connection
 * endpoint value.
 * 11. Creates a snapshot of the DB instance.
 * 12. Waits for an RDS DB snapshot to be ready.
 * 13. Deletes the RDS DB instance.
 * 14. Deletes the parameter group.
 */
public class RDSScenario {
    public static long sleepTime = 20;
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws InterruptedException {
        final String usage = """

                Usage:
                    <dbGroupName> <dbParameterGroupFamily> <dbInstanceIdentifier> <dbName> <dbSnapshotIdentifier> <secretName>

                Where:
                    dbGroupName - The database group name.\s
                    dbParameterGroupFamily - The database parameter group name (for example, mysql8.0).
                    dbInstanceIdentifier - The database instance identifier\s
                    dbName - The database name.\s
                    dbSnapshotIdentifier - The snapshot identifier.\s
                    secretName - The name of the AWS Secrets Manager secret that contains the database credentials"
                """;

        if (args.length != 6) {
            System.out.println(usage);
            System.exit(1);
        }

        String dbGroupName = args[0];
        String dbParameterGroupFamily = args[1];
        String dbInstanceIdentifier = args[2];
        String dbName = args[3];
        String dbSnapshotIdentifier = args[4];
        String secretName = args[5];

        Gson gson = new Gson();
        User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class);
        String masterUsername = user.getUsername();
        String masterUserPassword = user.getPassword();

        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();
        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon RDS example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Return a list of the available DB engines");
        describeDBEngines(rdsClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Create a custom parameter group");
        createDBParameterGroup(rdsClient, dbGroupName, dbParameterGroupFamily);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Get the parameter group");
        describeDbParameterGroups(rdsClient, dbGroupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Get the parameters in the group");
        describeDbParameters(rdsClient, dbGroupName, 0);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Modify the auto_increment_offset parameter");
        modifyDBParas(rdsClient, dbGroupName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Display the updated value");
        describeDbParameters(rdsClient, dbGroupName, -1);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Get a list of allowed engine versions");
        getAllowedEngines(rdsClient, dbParameterGroupFamily);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Get a list of micro instance classes available for the selected engine");
        getMicroInstances(rdsClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println(
                "9. Create an RDS database instance that contains a MySql database and uses the parameter group");
        String dbARN = createDatabaseInstance(rdsClient, dbGroupName, dbInstanceIdentifier, dbName, masterUsername,
                masterUserPassword);
        System.out.println("The ARN of the new database is " + dbARN);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Wait for DB instance to be ready");
        waitForInstanceReady(rdsClient, dbInstanceIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Create a snapshot of the DB instance");
        createSnapshot(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("12. Wait for DB snapshot to be ready");
        waitForSnapshotReady(rdsClient, dbInstanceIdentifier, dbSnapshotIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("13. Delete the DB instance");
        deleteDatabaseInstance(rdsClient, dbInstanceIdentifier);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("14. Delete the parameter group");
        deleteParaGroup(rdsClient, dbGroupName, dbARN);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The Scenario has successfully completed.");
        System.out.println(DASHES);

        rdsClient.close();
    }

    private static SecretsManagerClient getSecretClient() {
        Region region = Region.US_WEST_2;
        return SecretsManagerClient.builder()
            .region(region)
            .build();
    }

    public static String getSecretValues(String secretName) {
        SecretsManagerClient secretClient = getSecretClient();
        GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                .secretId(secretName)
                .build();

        GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest);
        return valueResponse.secretString();
    }

    // Delete the parameter group after database has been deleted.
    // An exception is thrown if you attempt to delete the para group while database
    // exists.
    public static void deleteParaGroup(RdsClient rdsClient, String dbGroupName, String dbARN)
            throws InterruptedException {
        try {
            boolean isDataDel = false;
            boolean didFind;
            String instanceARN;

            // Make sure that the database has been deleted.
            while (!isDataDel) {
                DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
                List<DBInstance> instanceList = response.dbInstances();
                int listSize = instanceList.size();
                didFind = false;
                int index = 1;
                for (DBInstance instance : instanceList) {
                    instanceARN = instance.dbInstanceArn();
                    if (instanceARN.compareTo(dbARN) == 0) {
                        System.out.println(dbARN + " still exists");
                        didFind = true;
                    }
                    if ((index == listSize) && (!didFind)) {
                        // Went through the entire list and did not find the database ARN.
                        isDataDel = true;
                    }
                    Thread.sleep(sleepTime * 1000);
                    index++;
                }
            }

            // Delete the para group.
            DeleteDbParameterGroupRequest parameterGroupRequest = DeleteDbParameterGroupRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .build();

            rdsClient.deleteDBParameterGroup(parameterGroupRequest);
            System.out.println(dbGroupName + " was deleted.");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Delete the DB instance.
    public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) {
        try {
            DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .deleteAutomatedBackups(true)
                    .skipFinalSnapshot(true)
                    .build();

            DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest);
            System.out.print("The status of the database is " + response.dbInstance().dbInstanceStatus());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Waits until the snapshot instance is available.
    public static void waitForSnapshotReady(RdsClient rdsClient, String dbInstanceIdentifier,
            String dbSnapshotIdentifier) {
        try {
            boolean snapshotReady = false;
            String snapshotReadyStr;
            System.out.println("Waiting for the snapshot to become available.");

            DescribeDbSnapshotsRequest snapshotsRequest = DescribeDbSnapshotsRequest.builder()
                    .dbSnapshotIdentifier(dbSnapshotIdentifier)
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .build();

            while (!snapshotReady) {
                DescribeDbSnapshotsResponse response = rdsClient.describeDBSnapshots(snapshotsRequest);
                List<DBSnapshot> snapshotList = response.dbSnapshots();
                for (DBSnapshot snapshot : snapshotList) {
                    snapshotReadyStr = snapshot.status();
                    if (snapshotReadyStr.contains("available")) {
                        snapshotReady = true;
                    } else {
                        System.out.print(".");
                        Thread.sleep(sleepTime * 1000);
                    }
                }
            }

            System.out.println("The Snapshot is available!");
        } catch (RdsException | InterruptedException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Create an Amazon RDS snapshot.
    public static void createSnapshot(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) {
        try {
            CreateDbSnapshotRequest snapshotRequest = CreateDbSnapshotRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .dbSnapshotIdentifier(dbSnapshotIdentifier)
                    .build();

            CreateDbSnapshotResponse response = rdsClient.createDBSnapshot(snapshotRequest);
            System.out.println("The Snapshot id is " + response.dbSnapshot().dbiResourceId());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Waits until the database instance is available.
    public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceIdentifier) {
        boolean instanceReady = false;
        String instanceReadyStr;
        System.out.println("Waiting for instance to become available.");
        try {
            DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .build();

            String endpoint = "";
            while (!instanceReady) {
                DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest);
                List<DBInstance> instanceList = response.dbInstances();
                for (DBInstance instance : instanceList) {
                    instanceReadyStr = instance.dbInstanceStatus();
                    if (instanceReadyStr.contains("available")) {
                        endpoint = instance.endpoint().address();
                        instanceReady = true;
                    } else {
                        System.out.print(".");
                        Thread.sleep(sleepTime * 1000);
                    }
                }
            }
            System.out.println("Database instance is available! The connection endpoint is " + endpoint);

        } catch (RdsException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    // Create a database instance and return the ARN of the database.
    public static String createDatabaseInstance(RdsClient rdsClient,
            String dbGroupName,
            String dbInstanceIdentifier,
            String dbName,
            String userName,
            String userPassword) {

        try {
            CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
                .dbInstanceIdentifier(dbInstanceIdentifier)
                .allocatedStorage(100)
                .dbName(dbName)
                .engine("mysql")
                .dbInstanceClass("db.t3.medium") // Updated to a supported class
                .engineVersion("8.0.32")         // Updated to a supported version
                .storageType("gp2")             // Changed to General Purpose SSD (gp2)
                .masterUsername(userName)
                .masterUserPassword(userPassword)
                .build();

            CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest);
            System.out.print("The status is " + response.dbInstance().dbInstanceStatus());
            return response.dbInstance().dbInstanceArn();

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }

        return "";
    }

    // Get a list of micro instances.
    public static void getMicroInstances(RdsClient rdsClient) {
        try {
            DescribeOrderableDbInstanceOptionsRequest dbInstanceOptionsRequest = DescribeOrderableDbInstanceOptionsRequest
                    .builder()
                    .engine("mysql")
                    .build();

            DescribeOrderableDbInstanceOptionsResponse response = rdsClient
                    .describeOrderableDBInstanceOptions(dbInstanceOptionsRequest);
            List<OrderableDBInstanceOption> orderableDBInstances = response.orderableDBInstanceOptions();
            for (OrderableDBInstanceOption dbInstanceOption : orderableDBInstances) {
                System.out.println("The engine version is " + dbInstanceOption.engineVersion());
                System.out.println("The engine description is " + dbInstanceOption.engine());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Get a list of allowed engine versions.
    public static void getAllowedEngines(RdsClient rdsClient, String dbParameterGroupFamily) {
        try {
            DescribeDbEngineVersionsRequest versionsRequest = DescribeDbEngineVersionsRequest.builder()
                    .dbParameterGroupFamily(dbParameterGroupFamily)
                    .engine("mysql")
                    .build();

            DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(versionsRequest);
            List<DBEngineVersion> dbEngines = response.dbEngineVersions();
            for (DBEngineVersion dbEngine : dbEngines) {
                System.out.println("The engine version is " + dbEngine.engineVersion());
                System.out.println("The engine description is " + dbEngine.dbEngineDescription());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Modify auto_increment_offset and auto_increment_increment parameters.
    public static void modifyDBParas(RdsClient rdsClient, String dbGroupName) {
        try {
            Parameter parameter1 = Parameter.builder()
                    .parameterName("auto_increment_offset")
                    .applyMethod("immediate")
                    .parameterValue("5")
                    .build();

            List<Parameter> paraList = new ArrayList<>();
            paraList.add(parameter1);
            ModifyDbParameterGroupRequest groupRequest = ModifyDbParameterGroupRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .parameters(paraList)
                    .build();

            ModifyDbParameterGroupResponse response = rdsClient.modifyDBParameterGroup(groupRequest);
            System.out.println("The parameter group " + response.dbParameterGroupName() + " was successfully modified");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Retrieve parameters in the group.
    public static void describeDbParameters(RdsClient rdsClient, String dbGroupName, int flag) {
        try {
            DescribeDbParametersRequest dbParameterGroupsRequest;
            if (flag == 0) {
                dbParameterGroupsRequest = DescribeDbParametersRequest.builder()
                        .dbParameterGroupName(dbGroupName)
                        .build();
            } else {
                dbParameterGroupsRequest = DescribeDbParametersRequest.builder()
                        .dbParameterGroupName(dbGroupName)
                        .source("user")
                        .build();
            }

            DescribeDbParametersResponse response = rdsClient.describeDBParameters(dbParameterGroupsRequest);
            List<Parameter> dbParameters = response.parameters();
            String paraName;
            for (Parameter para : dbParameters) {
                // Only print out information about either auto_increment_offset or
                // auto_increment_increment.
                paraName = para.parameterName();
                if ((paraName.compareTo("auto_increment_offset") == 0)
                        || (paraName.compareTo("auto_increment_increment ") == 0)) {
                    System.out.println("*** The parameter name is  " + paraName);
                    System.out.println("*** The parameter value is  " + para.parameterValue());
                    System.out.println("*** The parameter data type is " + para.dataType());
                    System.out.println("*** The parameter description is " + para.description());
                    System.out.println("*** The parameter allowed values  is " + para.allowedValues());
                }
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void describeDbParameterGroups(RdsClient rdsClient, String dbGroupName) {
        try {
            DescribeDbParameterGroupsRequest groupsRequest = DescribeDbParameterGroupsRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .maxRecords(20)
                    .build();

            DescribeDbParameterGroupsResponse response = rdsClient.describeDBParameterGroups(groupsRequest);
            List<DBParameterGroup> groups = response.dbParameterGroups();
            for (DBParameterGroup group : groups) {
                System.out.println("The group name is " + group.dbParameterGroupName());
                System.out.println("The group description is " + group.description());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void createDBParameterGroup(RdsClient rdsClient, String dbGroupName, String dbParameterGroupFamily) {
        try {
            CreateDbParameterGroupRequest groupRequest = CreateDbParameterGroupRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .dbParameterGroupFamily(dbParameterGroupFamily)
                    .description("Created by using the AWS SDK for Java")
                    .build();

            CreateDbParameterGroupResponse response = rdsClient.createDBParameterGroup(groupRequest);
            System.out.println("The group name is " + response.dbParameterGroup().dbParameterGroupName());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void describeDBEngines(RdsClient rdsClient) {
        try {
            DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder()
                    .defaultOnly(true)
                    .engine("mysql")
                    .maxRecords(20)
                    .build();

            DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest);
            List<DBEngineVersion> engines = response.dbEngineVersions();

            // Get all DBEngineVersion objects.
            for (DBEngineVersion engineOb : engines) {
                System.out.println("The name of the DB parameter group family for the database engine is "
                        + engineOb.dbParameterGroupFamily());
                System.out.println("The name of the database engine " + engineOb.engine());
                System.out.println("The version number of the database engine " + engineOb.engineVersion());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBInstance)
  + [CreateDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBParameterGroup)
  + [CreateDBSnapshot](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBSnapshot)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBInstance)
  + [DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBParameterGroup)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBInstances)
  + [DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBParameterGroups)
  + [DescribeDBParameters](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBParameters)
  + [DescribeDBSnapshots](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBSnapshots)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/ModifyDBParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_java_2_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import com.google.gson.Gson;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesRequest;
import software.amazon.awssdk.services.rds.model.CreateDbInstanceRequest;
import software.amazon.awssdk.services.rds.model.CreateDbInstanceResponse;
import software.amazon.awssdk.services.rds.model.RdsException;
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse;
import software.amazon.awssdk.services.rds.model.DBInstance;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;

import java.util.List;

/**
 * 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
 *
 * This example requires an AWS Secrets Manager secret that contains the
 * database credentials. If you do not create a
 * secret, this example will not work. For more details, see:
 *
 * https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html
 *
 *
 */

public class CreateDBInstance {
    public static long sleepTime = 20;

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <dbInstanceIdentifier> <dbName> <secretName>

                Where:
                    dbInstanceIdentifier - The database instance identifier.\s
                    dbName - The database name.\s
                    secretName - The name of the AWS Secrets Manager secret that contains the database credentials."
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String dbInstanceIdentifier = args[0];
        String dbName = args[1];
        String secretName = args[2];
        Gson gson = new Gson();
        User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class);
        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        createDatabaseInstance(rdsClient, dbInstanceIdentifier, dbName, user.getUsername(), user.getPassword());
        waitForInstanceReady(rdsClient, dbInstanceIdentifier);
        rdsClient.close();
    }

    private static SecretsManagerClient getSecretClient() {
        Region region = Region.US_WEST_2;
        return SecretsManagerClient.builder()
                .region(region)
                .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
                .build();
    }

    private static String getSecretValues(String secretName) {
        SecretsManagerClient secretClient = getSecretClient();
        GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                .secretId(secretName)
                .build();

        GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest);
        return valueResponse.secretString();
    }

    public static void createDatabaseInstance(RdsClient rdsClient,
            String dbInstanceIdentifier,
            String dbName,
            String userName,
            String userPassword) {

        try {
            CreateDbInstanceRequest instanceRequest = CreateDbInstanceRequest.builder()
                .dbInstanceIdentifier(dbInstanceIdentifier)
                .allocatedStorage(100)
                .dbName(dbName)
                .engine("mysql")
                .dbInstanceClass("db.t3.medium") // Updated to a supported class
                .engineVersion("8.0.32")         // Updated to a supported version
                .storageType("gp2")             // Changed to General Purpose SSD (gp2)
                .masterUsername(userName)
                .masterUserPassword(userPassword)
                .build();

            CreateDbInstanceResponse response = rdsClient.createDBInstance(instanceRequest);
            System.out.print("The status is " + response.dbInstance().dbInstanceStatus());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    // Waits until the database instance is available.
    public static void waitForInstanceReady(RdsClient rdsClient, String dbInstanceIdentifier) {
        boolean instanceReady = false;
        String instanceReadyStr;
        System.out.println("Waiting for instance to become available.");
        try {
            DescribeDbInstancesRequest instanceRequest = DescribeDbInstancesRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .build();

            // Loop until the cluster is ready.
            while (!instanceReady) {
                DescribeDbInstancesResponse response = rdsClient.describeDBInstances(instanceRequest);
                List<DBInstance> instanceList = response.dbInstances();
                for (DBInstance instance : instanceList) {
                    instanceReadyStr = instance.dbInstanceStatus();
                    if (instanceReadyStr.contains("available"))
                        instanceReady = true;
                    else {
                        System.out.print(".");
                        Thread.sleep(sleepTime * 1000);
                    }
                }
            }
            System.out.println("Database instance is available!");

        } catch (RdsException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `CreateDBParameterGroup`
<a name="rds_CreateDBParameterGroup_java_2_topic"></a>

次のコード例は、`CreateDBParameterGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void createDBParameterGroup(RdsClient rdsClient, String dbGroupName, String dbParameterGroupFamily) {
        try {
            CreateDbParameterGroupRequest groupRequest = CreateDbParameterGroupRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .dbParameterGroupFamily(dbParameterGroupFamily)
                    .description("Created by using the AWS SDK for Java")
                    .build();

            CreateDbParameterGroupResponse response = rdsClient.createDBParameterGroup(groupRequest);
            System.out.println("The group name is " + response.dbParameterGroup().dbParameterGroupName());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[CreateDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBParameterGroup)」を参照してください。

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_java_2_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    // Create an Amazon RDS snapshot.
    public static void createSnapshot(RdsClient rdsClient, String dbInstanceIdentifier, String dbSnapshotIdentifier) {
        try {
            CreateDbSnapshotRequest snapshotRequest = CreateDbSnapshotRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .dbSnapshotIdentifier(dbSnapshotIdentifier)
                    .build();

            CreateDbSnapshotResponse response = rdsClient.createDBSnapshot(snapshotRequest);
            System.out.println("The Snapshot id is " + response.dbSnapshot().dbiResourceId());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[CreateDBSnapshot](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/CreateDBSnapshot)」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_java_2_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceRequest;
import software.amazon.awssdk.services.rds.model.DeleteDbInstanceResponse;
import software.amazon.awssdk.services.rds.model.RdsException;

/**
 * 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 DeleteDBInstance {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <dbInstanceIdentifier>\s

                Where:
                    dbInstanceIdentifier - The database instance identifier\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String dbInstanceIdentifier = args[0];
        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        deleteDatabaseInstance(rdsClient, dbInstanceIdentifier);
        rdsClient.close();
    }

    public static void deleteDatabaseInstance(RdsClient rdsClient, String dbInstanceIdentifier) {
        try {
            DeleteDbInstanceRequest deleteDbInstanceRequest = DeleteDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .deleteAutomatedBackups(true)
                    .skipFinalSnapshot(true)
                    .build();

            DeleteDbInstanceResponse response = rdsClient.deleteDBInstance(deleteDbInstanceRequest);
            System.out.print("The status of the database is " + response.dbInstance().dbInstanceStatus());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DeleteDBParameterGroup`
<a name="rds_DeleteDBParameterGroup_java_2_topic"></a>

次のコード例は、`DeleteDBParameterGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    // Delete the parameter group after database has been deleted.
    // An exception is thrown if you attempt to delete the para group while database
    // exists.
    public static void deleteParaGroup(RdsClient rdsClient, String dbGroupName, String dbARN)
            throws InterruptedException {
        try {
            boolean isDataDel = false;
            boolean didFind;
            String instanceARN;

            // Make sure that the database has been deleted.
            while (!isDataDel) {
                DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
                List<DBInstance> instanceList = response.dbInstances();
                int listSize = instanceList.size();
                didFind = false;
                int index = 1;
                for (DBInstance instance : instanceList) {
                    instanceARN = instance.dbInstanceArn();
                    if (instanceARN.compareTo(dbARN) == 0) {
                        System.out.println(dbARN + " still exists");
                        didFind = true;
                    }
                    if ((index == listSize) && (!didFind)) {
                        // Went through the entire list and did not find the database ARN.
                        isDataDel = true;
                    }
                    Thread.sleep(sleepTime * 1000);
                    index++;
                }
            }

            // Delete the para group.
            DeleteDbParameterGroupRequest parameterGroupRequest = DeleteDbParameterGroupRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .build();

            rdsClient.deleteDBParameterGroup(parameterGroupRequest);
            System.out.println(dbGroupName + " was deleted.");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DeleteDBParameterGroup)」を参照してください。

### `DescribeAccountAttributes`
<a name="rds_DescribeAccountAttributes_java_2_topic"></a>

次のコード例は、`DescribeAccountAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.AccountQuota;
import software.amazon.awssdk.services.rds.model.RdsException;
import software.amazon.awssdk.services.rds.model.DescribeAccountAttributesResponse;
import java.util.List;

/**
 * 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 DescribeAccountAttributes {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        getAccountAttributes(rdsClient);
        rdsClient.close();
    }

    public static void getAccountAttributes(RdsClient rdsClient) {
        try {
            DescribeAccountAttributesResponse response = rdsClient.describeAccountAttributes();
            List<AccountQuota> quotasList = response.accountQuotas();
            for (AccountQuota quotas : quotasList) {
                System.out.println("Name is: " + quotas.accountQuotaName());
                System.out.println("Max value is " + quotas.max());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeAccountAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeAccountAttributes)」を参照してください。

### `DescribeDBEngineVersions`
<a name="rds_DescribeDBEngineVersions_java_2_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDBEngines(RdsClient rdsClient) {
        try {
            DescribeDbEngineVersionsRequest engineVersionsRequest = DescribeDbEngineVersionsRequest.builder()
                    .defaultOnly(true)
                    .engine("mysql")
                    .maxRecords(20)
                    .build();

            DescribeDbEngineVersionsResponse response = rdsClient.describeDBEngineVersions(engineVersionsRequest);
            List<DBEngineVersion> engines = response.dbEngineVersions();

            // Get all DBEngineVersion objects.
            for (DBEngineVersion engineOb : engines) {
                System.out.println("The name of the DB parameter group family for the database engine is "
                        + engineOb.dbParameterGroupFamily());
                System.out.println("The name of the database engine " + engineOb.engine());
                System.out.println("The version number of the database engine " + engineOb.engineVersion());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_java_2_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.DescribeDbInstancesResponse;
import software.amazon.awssdk.services.rds.model.DBInstance;
import software.amazon.awssdk.services.rds.model.RdsException;
import java.util.List;

/**
 * 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 DescribeDBInstances {

    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        describeInstances(rdsClient);
        rdsClient.close();
    }

    public static void describeInstances(RdsClient rdsClient) {
        try {
            DescribeDbInstancesResponse response = rdsClient.describeDBInstances();
            List<DBInstance> instanceList = response.dbInstances();
            for (DBInstance instance : instanceList) {
                System.out.println("Instance ARN is: " + instance.dbInstanceArn());
                System.out.println("The Engine is " + instance.engine());
                System.out.println("Connection endpoint is" + instance.endpoint().address());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_java_2_topic"></a>

次のコード例は、`DescribeDBParameterGroups` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeDbParameterGroups(RdsClient rdsClient, String dbGroupName) {
        try {
            DescribeDbParameterGroupsRequest groupsRequest = DescribeDbParameterGroupsRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .maxRecords(20)
                    .build();

            DescribeDbParameterGroupsResponse response = rdsClient.describeDBParameterGroups(groupsRequest);
            List<DBParameterGroup> groups = response.dbParameterGroups();
            for (DBParameterGroup group : groups) {
                System.out.println("The group name is " + group.dbParameterGroupName());
                System.out.println("The group description is " + group.description());
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBParameterGroups)」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_java_2_topic"></a>

次のコード例は、`DescribeDBParameters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    // Retrieve parameters in the group.
    public static void describeDbParameters(RdsClient rdsClient, String dbGroupName, int flag) {
        try {
            DescribeDbParametersRequest dbParameterGroupsRequest;
            if (flag == 0) {
                dbParameterGroupsRequest = DescribeDbParametersRequest.builder()
                        .dbParameterGroupName(dbGroupName)
                        .build();
            } else {
                dbParameterGroupsRequest = DescribeDbParametersRequest.builder()
                        .dbParameterGroupName(dbGroupName)
                        .source("user")
                        .build();
            }

            DescribeDbParametersResponse response = rdsClient.describeDBParameters(dbParameterGroupsRequest);
            List<Parameter> dbParameters = response.parameters();
            String paraName;
            for (Parameter para : dbParameters) {
                // Only print out information about either auto_increment_offset or
                // auto_increment_increment.
                paraName = para.parameterName();
                if ((paraName.compareTo("auto_increment_offset") == 0)
                        || (paraName.compareTo("auto_increment_increment ") == 0)) {
                    System.out.println("*** The parameter name is  " + paraName);
                    System.out.println("*** The parameter value is  " + para.parameterValue());
                    System.out.println("*** The parameter data type is " + para.dataType());
                    System.out.println("*** The parameter description is " + para.description());
                    System.out.println("*** The parameter allowed values  is " + para.allowedValues());
                }
            }

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DescribeDBParameters](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/DescribeDBParameters)」を参照してください。

### `GenerateRDSAuthToken`
<a name="rds_GenerateRDSAuthToken_java_2_topic"></a>

次のコード例は、`GenerateRDSAuthToken` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。
[RdsUtilities](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/rds/RdsUtilities.html) クラスを使用して認証トークンを生成します。  

```
public class GenerateRDSAuthToken {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <dbInstanceIdentifier> <masterUsername>

                Where:
                    dbInstanceIdentifier - The database instance identifier.\s
                    masterUsername - The master user name.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String dbInstanceIdentifier = args[0];
        String masterUsername = args[1];
        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        String token = getAuthToken(rdsClient, dbInstanceIdentifier, masterUsername);
        System.out.println("The token response is " + token);
    }

    public static String getAuthToken(RdsClient rdsClient, String dbInstanceIdentifier, String masterUsername) {

        RdsUtilities utilities = rdsClient.utilities();
        try {
            GenerateAuthenticationTokenRequest tokenRequest = GenerateAuthenticationTokenRequest.builder()
                    .credentialsProvider(ProfileCredentialsProvider.create())
                    .username(masterUsername)
                    .port(3306)
                    .hostname(dbInstanceIdentifier)
                    .build();

            return utilities.generateAuthenticationToken(tokenRequest);

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GenerateRDSAuthToken](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/GenerateRDSAuthToken)」を参照してください。

### `ModifyDBInstance`
<a name="rds_ModifyDBInstance_java_2_topic"></a>

次のコード例は、`ModifyDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.ModifyDbInstanceRequest;
import software.amazon.awssdk.services.rds.model.ModifyDbInstanceResponse;
import software.amazon.awssdk.services.rds.model.RdsException;

/**
 * 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 ModifyDBInstance {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <dbInstanceIdentifier> <dbSnapshotIdentifier>\s
                Where:
                    dbInstanceIdentifier - The database instance identifier.\s
                    masterUserPassword - The updated password that corresponds to the master user name.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String dbInstanceIdentifier = args[0];
        String masterUserPassword = args[1];
        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        updateIntance(rdsClient, dbInstanceIdentifier, masterUserPassword);
        rdsClient.close();
    }

    public static void updateIntance(RdsClient rdsClient, String dbInstanceIdentifier, String masterUserPassword) {
        try {
            // For a demo - modify the DB instance by modifying the master password.
            ModifyDbInstanceRequest modifyDbInstanceRequest = ModifyDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .publiclyAccessible(true)
                    .masterUserPassword(masterUserPassword)
                    .build();

            ModifyDbInstanceResponse instanceResponse = rdsClient.modifyDBInstance(modifyDbInstanceRequest);
            System.out.print("The ARN of the modified database is: " + instanceResponse.dbInstance().dbInstanceArn());

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ModifyDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/ModifyDBInstance)」を参照してください。

### `ModifyDBParameterGroup`
<a name="rds_ModifyDBParameterGroup_java_2_topic"></a>

次のコード例は、`ModifyDBParameterGroup` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
    // Modify auto_increment_offset and auto_increment_increment parameters.
    public static void modifyDBParas(RdsClient rdsClient, String dbGroupName) {
        try {
            Parameter parameter1 = Parameter.builder()
                    .parameterName("auto_increment_offset")
                    .applyMethod("immediate")
                    .parameterValue("5")
                    .build();

            List<Parameter> paraList = new ArrayList<>();
            paraList.add(parameter1);
            ModifyDbParameterGroupRequest groupRequest = ModifyDbParameterGroupRequest.builder()
                    .dbParameterGroupName(dbGroupName)
                    .parameters(paraList)
                    .build();

            ModifyDbParameterGroupResponse response = rdsClient.modifyDBParameterGroup(groupRequest);
            System.out.println("The parameter group " + response.dbParameterGroupName() + " was successfully modified");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/ModifyDBParameterGroup)」を参照してください。

### `RebootDBInstance`
<a name="rds_RebootDBInstance_java_2_topic"></a>

次のコード例は、`RebootDBInstance` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rds.RdsClient;
import software.amazon.awssdk.services.rds.model.RebootDbInstanceRequest;
import software.amazon.awssdk.services.rds.model.RebootDbInstanceResponse;
import software.amazon.awssdk.services.rds.model.RdsException;

/**
 * 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 RebootDBInstance {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <dbInstanceIdentifier>\s

                Where:
                    dbInstanceIdentifier - The database instance identifier\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String dbInstanceIdentifier = args[0];
        Region region = Region.US_WEST_2;
        RdsClient rdsClient = RdsClient.builder()
                .region(region)
                .build();

        rebootInstance(rdsClient, dbInstanceIdentifier);
        rdsClient.close();
    }

    public static void rebootInstance(RdsClient rdsClient, String dbInstanceIdentifier) {
        try {
            RebootDbInstanceRequest rebootDbInstanceRequest = RebootDbInstanceRequest.builder()
                    .dbInstanceIdentifier(dbInstanceIdentifier)
                    .build();

            RebootDbInstanceResponse instanceResponse = rdsClient.rebootDBInstance(rebootDbInstanceRequest);
            System.out.print("The database " + instanceResponse.dbInstance().dbInstanceArn() + " was rebooted");

        } catch (RdsException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンスの*「[RebootDBInstance](https://docs.aws.amazon.com/goto/SdkForJavaV2/rds-2014-10-31/RebootDBInstance)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_java_2_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_Spring_RDS_Rest) にある完全な例を参照してください。  
 完全なソースコードと JDBC API を使用する例のセットアップと実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_rds_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_java_2_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rdsdata.RdsDataClient;
import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementRequest;
import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementResponse;
import software.amazon.awssdk.services.rdsdata.model.Field;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class RdsLambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {

    @Override
    public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) {
        APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent();

        try {
            // Obtain auth token
            String token = createAuthToken();

            // Define connection configuration
            String connectionString = String.format("jdbc:mysql://%s:%s/%s?useSSL=true&requireSSL=true",
                    System.getenv("ProxyHostName"),
                    System.getenv("Port"),
                    System.getenv("DBName"));

            // Establish a connection to the database
            try (Connection connection = DriverManager.getConnection(connectionString, System.getenv("DBUserName"), token);
                 PreparedStatement statement = connection.prepareStatement("SELECT ? + ? AS sum")) {

                statement.setInt(1, 3);
                statement.setInt(2, 2);

                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        int sum = resultSet.getInt("sum");
                        response.setStatusCode(200);
                        response.setBody("The selected sum is: " + sum);
                    }
                }
            }

        } catch (Exception e) {
            response.setStatusCode(500);
            response.setBody("Error: " + e.getMessage());
        }

        return response;
    }

    private String createAuthToken() {
        // Create RDS Data Service client
        RdsDataClient rdsDataClient = RdsDataClient.builder()
                .region(Region.of(System.getenv("AWS_REGION")))
                .credentialsProvider(DefaultCredentialsProvider.create())
                .build();

        // Define authentication request
        ExecuteStatementRequest request = ExecuteStatementRequest.builder()
                .resourceArn(System.getenv("ProxyHostName"))
                .secretArn(System.getenv("DBUserName"))
                .database(System.getenv("DBName"))
                .sql("SELECT 'RDS IAM Authentication'")
                .build();

        // Execute request and obtain authentication token
        ExecuteStatementResponse response = rdsDataClient.executeStatement(request);
        Field tokenField = response.records().get(0).get(0);

        return tokenField.stringValue();
    }
}
```

# SDK for Java 2.x を使用した Amazon RDS Data Service の例
<a name="java_2_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_java_2_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_Spring_RDS_Rest) にある完全な例を参照してください。  
 完全なソースコードと JDBC API を使用する例のセットアップと実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_rds_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for Java 2.x を使用した Amazon Redshift の例
<a name="java_2_redshift_code_examples"></a>

次のコード例は、Amazon Redshift AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Redshift
<a name="redshift_Hello_java_2_topic"></a>

次のコード例は、Amazon Redshift の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshift.RedshiftClient;
import software.amazon.awssdk.services.redshift.paginators.DescribeClustersIterable;

/**
 * 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 HelloRedshift {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        RedshiftClient redshiftClient = RedshiftClient.builder()
            .region(region)
            .build();

        listClustersPaginator(redshiftClient);
    }

    public static void listClustersPaginator(RedshiftClient redshiftClient) {
        DescribeClustersIterable clustersIterable = redshiftClient.describeClustersPaginator();
        clustersIterable.stream()
            .flatMap(r -> r.clusters().stream())
            .forEach(cluster -> System.out
                .println(" Cluster identifier: " + cluster.clusterIdentifier() + " status = " + cluster.clusterStatus()));
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/DescribeClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="redshift_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Redshift クラスターを作成します。
+ クラスター内のデータベースを一覧表示します。
+ Movies という名前のテーブルを作成します。
+ Movies テーブルにデータを入力します。
+ Movies テーブルに対して年に基づくクエリを実行します。
+ Redshift クラスターを変更します。
+ Amazon Redshift クラスターを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
Amazon Redshift 機能を示すインタラクティブなシナリオを実行します。  

```
import com.example.redshift.User;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.redshift.model.ClusterAlreadyExistsException;
import software.amazon.awssdk.services.redshift.model.CreateClusterResponse;
import software.amazon.awssdk.services.redshift.model.DeleteClusterResponse;
import software.amazon.awssdk.services.redshift.model.ModifyClusterResponse;
import software.amazon.awssdk.services.redshift.model.RedshiftException;
import software.amazon.awssdk.services.redshiftdata.model.ExecuteStatementResponse;
import software.amazon.awssdk.services.redshiftdata.model.RedshiftDataException;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;

/**
 * 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
 *
 *
 *  This example requires an AWS Secrets Manager secret that contains the
 *  database credentials. If you do not create a
 *  secret that specifies user name and password, this example will not work. For details, see:
 *
 *  https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html
 *
 This Java example performs these tasks:
 *
 * 1. Prompts the user for a unique cluster ID or use the default value.
 * 2. Creates a Redshift cluster with the specified or default cluster Id value.
 * 3. Waits until the Redshift cluster is available for use.
 * 4. Lists all databases using a pagination API call.
 * 5. Creates a table named "Movies" with fields ID, title, and year.
 * 6. Inserts a specified number of records into the "Movies" table by reading the Movies JSON file.
 * 7. Prompts the user for a movie release year.
 * 8. Runs a SQL query to retrieve movies released in the specified year.
 * 9. Modifies the Redshift cluster.
 * 10. Prompts the user for confirmation to delete the Redshift cluster.
 * 11. If confirmed, deletes the specified Redshift cluster.
 */

public class RedshiftScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final Logger logger = LoggerFactory.getLogger(RedshiftScenario.class);

    static RedshiftActions redshiftActions = new RedshiftActions();
    public static void main(String[] args) throws Exception {
        final String usage = """

            Usage:
                <jsonFilePath> <secretName>\s

            Where:
                jsonFilePath - The path to the Movies JSON file (you can locate that file in ../../../resources/sample_files/movies.json)
                secretName - The name of the secret that belongs to Secret Manager that stores the user name and password used in this scenario. 
            """;

        if (args.length != 2) {
            logger.info(usage);
            return;
        }

        String jsonFilePath = args[0];
        String secretName = args[1];
        Scanner scanner = new Scanner(System.in);
        logger.info(DASHES);
        logger.info("Welcome to the Amazon Redshift SDK Basics scenario.");
        logger.info("""
            This Java program demonstrates how to interact with Amazon Redshift by using the AWS SDK for Java (v2).\s
            Amazon Redshift is a fully managed, petabyte-scale data warehouse service hosted in the cloud.
                                                                                
            The program's primary functionalities include cluster creation, verification of cluster readiness,\s
            list databases, table creation, data population within the table, and execution of SQL statements.
            Furthermore, it demonstrates the process of querying data from the Movie table.\s
                    
            Upon completion of the program, all AWS resources are cleaned up.
            """);

        logger.info("Lets get started...");
        logger.info("""
            First, we will retrieve the user name and password from Secrets Manager.
                    
            Using Amazon Secrets Manager to store Redshift credentials provides several security benefits. 
            It allows you to securely store and manage sensitive information, such as passwords, API keys, and 
            database credentials, without embedding them directly in your application code.
            
            More information can be found here: 
            
            https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html
            """);
        Gson gson = new Gson();
        User user = gson.fromJson(String.valueOf(getSecretValues(secretName)), User.class);
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        try {
            runScenario(user, scanner, jsonFilePath);
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    private static void runScenario(User user, Scanner scanner,  String jsonFilePath) throws Throwable {
        String databaseName = "dev";
        System.out.println(DASHES);
        logger.info("Create a Redshift Cluster");
        logger.info("A Redshift cluster refers to the collection of computing resources and storage that work together to process and analyze large volumes of data.");
        logger.info("Enter a cluster id value or accept the default by hitting Enter (default is redshift-cluster-movies): ");
        String userClusterId = scanner.nextLine();
        String clusterId = userClusterId.isEmpty() ? "redshift-cluster-movies" : userClusterId;
        try {
            CompletableFuture<CreateClusterResponse> future = redshiftActions.createClusterAsync(clusterId, user.getUserName(), user.getUserPassword());
            CreateClusterResponse response = future.join();
            logger.info("Cluster successfully created. Cluster Identifier {} ", response.cluster().clusterIdentifier());

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof ClusterAlreadyExistsException) {
                logger.info("The Cluster {} already exists. Moving on...", clusterId);
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("Wait until {} is available.", clusterId);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = redshiftActions.waitForClusterReadyAsync(clusterId);
            future.join();
            logger.info("Cluster is ready!");

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftException redshiftEx) {
                logger.info("Redshift error occurred: Error message: {}, Error code {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        String databaseInfo = """
            When you created $clusteridD, the dev database is created by default and used in this scenario.\s
            
            To create a custom database, you need to have a CREATEDB privilege.\s
            For more information, see the documentation here: https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_DATABASE.html.
           """.replace("$clusteridD", clusterId);

        logger.info(databaseInfo);
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("List databases in {} ",clusterId);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = redshiftActions.listAllDatabasesAsync(clusterId, user.getUserName(), "dev");
            future.join();
            logger.info("Databases listed successfully.");

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftDataException redshiftEx) {
                logger.error("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.error("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("Now you will create a table named Movies.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<ExecuteStatementResponse> future = redshiftActions.createTableAsync(clusterId, databaseName, user.getUserName());
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftDataException redshiftEx) {
                logger.info("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("Populate the Movies table using the Movies.json file.");
        logger.info("Specify the number of records you would like to add to the Movies Table.");
        logger.info("Please enter a value between 50 and 200.");
        int numRecords;
        do {
            logger.info("Enter a value: ");
            while (!scanner.hasNextInt()) {
                logger.info("Invalid input. Please enter a value between 50 and 200.");
                logger.info("Enter a year: ");
                scanner.next();
            }
            numRecords = scanner.nextInt();
        } while (numRecords < 50 || numRecords > 200);
        try {
            redshiftActions.popTableAsync(clusterId, databaseName, user.getUserName(), jsonFilePath, numRecords).join();  // Wait for the operation to complete
        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftDataException redshiftEx) {
                logger.info("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("Query the Movies table by year. Enter a value between 2012-2014.");
        int movieYear;
        do {
            logger.info("Enter a year: ");
            while (!scanner.hasNextInt()) {
                logger.info("Invalid input. Please enter a valid year between 2012 and 2014.");
                logger.info("Enter a year: ");
                scanner.next();
            }
            movieYear = scanner.nextInt();
            scanner.nextLine();
        } while (movieYear < 2012 || movieYear > 2014);

        String id;
        try {
            CompletableFuture<String> future = redshiftActions.queryMoviesByYearAsync(databaseName, user.getUserName(), movieYear, clusterId);
            id = future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftDataException redshiftEx) {
                logger.info("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }

        logger.info("The identifier of the statement is " + id);
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = redshiftActions.checkStatementAsync(id);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftDataException redshiftEx) {
                logger.info("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = redshiftActions.getResultsAsync(id);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftDataException redshiftEx) {
                logger.info("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("Now you will modify the Redshift cluster.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<ModifyClusterResponse> future = redshiftActions.modifyClusterAsync(clusterId);;
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof RedshiftDataException redshiftEx) {
                logger.info("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: {}", rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("Would you like to delete the Amazon Redshift cluster? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            logger.info("You selected to delete {} ", clusterId);
            waitForInputToContinue(scanner);
            try {
                CompletableFuture<DeleteClusterResponse> future = redshiftActions.deleteRedshiftClusterAsync(clusterId);;
                future.join();

            } catch (RuntimeException rt) {
                Throwable cause = rt.getCause();
                if (cause instanceof RedshiftDataException redshiftEx) {
                    logger.info("Redshift Data error occurred: {} Error code: {}", redshiftEx.getMessage(), redshiftEx.awsErrorDetails().errorCode());
                } else {
                    logger.info("An unexpected error occurred: {}", rt.getMessage());
                }
                throw cause;
            }
        } else {
            logger.info("The {}  was not deleted", clusterId);
        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("This concludes the Amazon Redshift SDK Basics scenario.");
        logger.info(DASHES);
    }

    private static SecretsManagerClient getSecretClient() {
        Region region = Region.US_EAST_1;
        return SecretsManagerClient.builder()
            .region(region)
            .build();
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println("");
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }

    // Get the Amazon Redshift credentials from AWS Secrets Manager.
    private static String getSecretValues(String secretName) {
        SecretsManagerClient secretClient = getSecretClient();
        GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
            .secretId(secretName)
            .build();

        GetSecretValueResponse valueResponse = secretClient.getSecretValue(valueRequest);
        return valueResponse.secretString();
    }
}
```
Amazon Redshift SDK メソッドのラッパークラス。  

```
public class RedshiftActions {

    private static final Logger logger = LoggerFactory.getLogger(RedshiftActions.class);
    private static RedshiftDataAsyncClient redshiftDataAsyncClient;

    private static RedshiftAsyncClient redshiftAsyncClient;

    private static RedshiftAsyncClient getAsyncClient() {
        if (redshiftAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            redshiftAsyncClient = RedshiftAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return redshiftAsyncClient;
    }

    private static RedshiftDataAsyncClient getAsyncDataClient() {
        if (redshiftDataAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            redshiftDataAsyncClient = RedshiftDataAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return redshiftDataAsyncClient;
    }

    /**
     * Creates a new Amazon Redshift cluster asynchronously.
     * @param clusterId     the unique identifier for the cluster
     * @param username      the username for the administrative user
     * @param userPassword  the password for the administrative user
     * @return a CompletableFuture that represents the asynchronous operation of creating the cluster
     * @throws RuntimeException if the cluster creation fails
     */
    public CompletableFuture<CreateClusterResponse> createClusterAsync(String clusterId, String username, String userPassword) {
        CreateClusterRequest clusterRequest = CreateClusterRequest.builder()
            .clusterIdentifier(clusterId)
            .masterUsername(username)
            .masterUserPassword(userPassword)
            .nodeType("ra3.4xlarge")
            .publiclyAccessible(true)
            .numberOfNodes(2)
            .build();

        return getAsyncClient().createCluster(clusterRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("Created cluster ");
                } else {
                    throw new RuntimeException("Failed to create cluster: " + exception.getMessage(), exception);
                }
            });
    }

    /**
     * Waits asynchronously for the specified cluster to become available.
     * @param clusterId the identifier of the cluster to wait for
     * @return a {@link CompletableFuture} that completes when the cluster is ready
     */
    public CompletableFuture<Void> waitForClusterReadyAsync(String clusterId) {
        DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder()
            .clusterIdentifier(clusterId)
            .build();

        logger.info("Waiting for cluster to become available. This may take a few minutes.");
        long startTime = System.currentTimeMillis();

        // Recursive method to poll the cluster status.
        return checkClusterStatusAsync(clustersRequest, startTime);
    }

    private CompletableFuture<Void> checkClusterStatusAsync(DescribeClustersRequest clustersRequest, long startTime) {
        return getAsyncClient().describeClusters(clustersRequest)
            .thenCompose(clusterResponse -> {
                List<Cluster> clusterList = clusterResponse.clusters();
                boolean clusterReady = false;
                for (Cluster cluster : clusterList) {
                    if ("available".equals(cluster.clusterStatus())) {
                        clusterReady = true;
                        break;
                    }
                }

                if (clusterReady) {
                    logger.info(String.format("Cluster is available!"));
                    return CompletableFuture.completedFuture(null);
                } else {
                    long elapsedTimeMillis = System.currentTimeMillis() - startTime;
                    long elapsedSeconds = elapsedTimeMillis / 1000;
                    long minutes = elapsedSeconds / 60;
                    long seconds = elapsedSeconds % 60;
                    System.out.printf("\rElapsed Time: %02d:%02d - Waiting for cluster...", minutes, seconds);
                    System.out.flush();

                    // Wait 1 second before the next status check
                    return CompletableFuture.runAsync(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException("Error during sleep: " + e.getMessage(), e);
                        }
                    }).thenCompose(ignored -> checkClusterStatusAsync(clustersRequest, startTime));
                }
            }).exceptionally(exception -> {
                throw new RuntimeException("Failed to get cluster status: " + exception.getMessage(), exception);
            });
    }

    /**
     * Lists all databases asynchronously for the specified cluster, database user, and database.
     * @param clusterId the identifier of the cluster to list databases for
     * @param dbUser the database user to use for the list databases request
     * @param database the database to list databases for
     * @return a {@link CompletableFuture} that completes when the database listing is complete, or throws a {@link RuntimeException} if there was an error
     */
    public CompletableFuture<Void> listAllDatabasesAsync(String clusterId, String dbUser, String database) {
        ListDatabasesRequest databasesRequest = ListDatabasesRequest.builder()
            .clusterIdentifier(clusterId)
            .dbUser(dbUser)
            .database(database)
            .build();

        // Asynchronous paginator for listing databases.
        ListDatabasesPublisher databasesPaginator = getAsyncDataClient().listDatabasesPaginator(databasesRequest);
        CompletableFuture<Void> future = databasesPaginator.subscribe(response -> {
            response.databases().forEach(db -> {
                logger.info("The database name is {} ", db);
            });
        });

        // Return the future for asynchronous handling.
        return future.exceptionally(exception -> {
            throw new RuntimeException("Failed to list databases: " + exception.getMessage(), exception);
        });
    }

    /**
     * Creates an asynchronous task to execute a SQL statement for creating a new table.
     *
     * @param clusterId    the identifier of the Amazon Redshift cluster
     * @param databaseName the name of the database to create the table in
     * @param userName     the username to use for the database connection
     * @return a {@link CompletableFuture} that completes with the result of the SQL statement execution
     * @throws RuntimeException if there is an error creating the table
     */
    public CompletableFuture<ExecuteStatementResponse> createTableAsync(String clusterId, String databaseName, String userName) {
        ExecuteStatementRequest createTableRequest = ExecuteStatementRequest.builder()
            .clusterIdentifier(clusterId)
            .dbUser(userName)
            .database(databaseName)
            .sql("CREATE TABLE Movies (" +
                "id INT PRIMARY KEY, " +
                "title VARCHAR(100), " +
                "year INT)")
            .build();

        return getAsyncDataClient().executeStatement(createTableRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Error creating table: " + exception.getMessage(), exception);
                } else {
                    logger.info("Table created: Movies");
                }
            });
    }

    /**
     * Asynchronously pops a table from a JSON file.
     *
     * @param clusterId   the ID of the cluster
     * @param databaseName the name of the database
     * @param userName    the username
     * @param fileName    the name of the JSON file
     * @param number      the number of records to process
     * @return a CompletableFuture that completes with the number of records added to the Movies table
     */
    public CompletableFuture<Integer> popTableAsync(String clusterId, String databaseName, String userName, String fileName, int number) {
        return CompletableFuture.supplyAsync(() -> {
                try {
                    JsonParser parser = new JsonFactory().createParser(new File(fileName));
                    JsonNode rootNode = new ObjectMapper().readTree(parser);
                    Iterator<JsonNode> iter = rootNode.iterator();
                    return iter;
                } catch (IOException e) {
                    throw new RuntimeException("Failed to read or parse JSON file: " + e.getMessage(), e);
                }
            }).thenCompose(iter -> processNodesAsync(clusterId, databaseName, userName, iter, number))
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    logger.info("Error {} ", exception.getMessage());
                } else {
                    logger.info("{} records were added to the Movies table." , result);
                }
            });
    }

    private CompletableFuture<Integer> processNodesAsync(String clusterId, String databaseName, String userName, Iterator<JsonNode> iter, int number) {
        return CompletableFuture.supplyAsync(() -> {
            int t = 0;
            try {
                while (iter.hasNext()) {
                    if (t == number)
                        break;
                    JsonNode currentNode = iter.next();
                    int year = currentNode.get("year").asInt();
                    String title = currentNode.get("title").asText();

                    // Use SqlParameter to avoid SQL injection.
                    List<SqlParameter> parameterList = new ArrayList<>();
                    String sqlStatement = "INSERT INTO Movies VALUES( :id , :title, :year);";
                    SqlParameter idParam = SqlParameter.builder()
                        .name("id")
                        .value(String.valueOf(t))
                        .build();

                    SqlParameter titleParam = SqlParameter.builder()
                        .name("title")
                        .value(title)
                        .build();

                    SqlParameter yearParam = SqlParameter.builder()
                        .name("year")
                        .value(String.valueOf(year))
                        .build();
                    parameterList.add(idParam);
                    parameterList.add(titleParam);
                    parameterList.add(yearParam);

                    ExecuteStatementRequest insertStatementRequest = ExecuteStatementRequest.builder()
                        .clusterIdentifier(clusterId)
                        .sql(sqlStatement)
                        .database(databaseName)
                        .dbUser(userName)
                        .parameters(parameterList)
                        .build();

                    getAsyncDataClient().executeStatement(insertStatementRequest);
                    logger.info("Inserted: " + title + " (" + year + ")");
                    t++;
                }
            } catch (RedshiftDataException e) {
                throw new RuntimeException("Error inserting data: " + e.getMessage(), e);
            }
            return t;
        });
    }

    /**
     * Checks the status of an SQL statement asynchronously and handles the completion of the statement.
     *
     * @param sqlId the ID of the SQL statement to check
     * @return a {@link CompletableFuture} that completes when the SQL statement's status is either "FINISHED" or "FAILED"
     */
    public CompletableFuture<Void> checkStatementAsync(String sqlId) {
        DescribeStatementRequest statementRequest = DescribeStatementRequest.builder()
            .id(sqlId)
            .build();

        return getAsyncDataClient().describeStatement(statementRequest)
            .thenCompose(response -> {
                String status = response.statusAsString();
                logger.info("... Status: {} ", status);

                if ("FAILED".equals(status)) {
                    throw new RuntimeException("The Query Failed. Ending program");
                } else if ("FINISHED".equals(status)) {
                    return CompletableFuture.completedFuture(null);
                } else {
                    // Sleep for 1 second and recheck status
                    return CompletableFuture.runAsync(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException("Error during sleep: " + e.getMessage(), e);
                        }
                    }).thenCompose(ignore -> checkStatementAsync(sqlId)); // Recursively call until status is FINISHED or FAILED
                }
            }).whenComplete((result, exception) -> {
                if (exception != null) {
                    // Handle exceptions
                    logger.info("Error: {} ", exception.getMessage());
                } else {
                    logger.info("The statement is finished!");
                }
            });
    }

    /**
     * Asynchronously retrieves the results of a statement execution.
     *
     * @param statementId the ID of the statement for which to retrieve the results
     * @return a {@link CompletableFuture} that completes when the statement result has been processed
     */
    public CompletableFuture<Void> getResultsAsync(String statementId) {
        GetStatementResultRequest resultRequest = GetStatementResultRequest.builder()
            .id(statementId)
            .build();

        return getAsyncDataClient().getStatementResult(resultRequest)
            .handle((response, exception) -> {
                if (exception != null) {
                    logger.info("Error getting statement result {} ", exception.getMessage());
                    throw new RuntimeException("Error getting statement result: " + exception.getMessage(), exception);
                }

                // Extract and print the field values using streams if the response is valid.
                response.records().stream()
                    .flatMap(List::stream)
                    .map(Field::stringValue)
                    .filter(value -> value != null)
                    .forEach(value -> System.out.println("The Movie title field is " + value));

                return response;
            }).thenAccept(response -> {
                // Optionally add more logic here if needed after handling the response
            });
    }


    /**
     * Asynchronously queries movies by a given year from a Redshift database.
     *
     * @param database    the name of the database to query
     * @param dbUser      the user to connect to the database with
     * @param year        the year to filter the movies by
     * @param clusterId   the identifier of the Redshift cluster to connect to
     * @return a {@link CompletableFuture} containing the response ID of the executed SQL statement
     */
    public CompletableFuture<String> queryMoviesByYearAsync(String database,
                                                                   String dbUser,
                                                                   int year,
                                                                   String clusterId) {

        String sqlStatement = "SELECT * FROM Movies WHERE year = :year";
        SqlParameter yearParam = SqlParameter.builder()
            .name("year")
            .value(String.valueOf(year))
            .build();

        ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder()
            .clusterIdentifier(clusterId)
            .database(database)
            .dbUser(dbUser)
            .parameters(yearParam)
            .sql(sqlStatement)
            .build();

        return CompletableFuture.supplyAsync(() -> {
            try {
                ExecuteStatementResponse response = getAsyncDataClient().executeStatement(statementRequest).join(); // Use join() to wait for the result
                return response.id();
            } catch (RedshiftDataException e) {
                throw new RuntimeException("Error executing statement: " + e.getMessage(), e);
            }
        }).exceptionally(exception -> {
            logger.info("Error: {}", exception.getMessage());
            return "";
        });
    }

    /**
     * Modifies an Amazon Redshift cluster asynchronously.
     *
     * @param clusterId the identifier of the cluster to be modified
     * @return a {@link CompletableFuture} that completes when the cluster modification is complete
     */
    public CompletableFuture<ModifyClusterResponse> modifyClusterAsync(String clusterId) {
        ModifyClusterRequest modifyClusterRequest = ModifyClusterRequest.builder()
            .clusterIdentifier(clusterId)
            .preferredMaintenanceWindow("wed:07:30-wed:08:00")
            .build();

        return getAsyncClient().modifyCluster(modifyClusterRequest)
            .whenComplete((clusterResponse, exception) -> {
                if (exception != null) {
                    if (exception.getCause() instanceof RedshiftException) {
                        logger.info("Error: {} ", exception.getMessage());
                    } else {
                        logger.info("Unexpected error: {} ", exception.getMessage());
                    }
                } else {
                    logger.info("The modified cluster was successfully modified and has "
                        + clusterResponse.cluster().preferredMaintenanceWindow() + " as the maintenance window");
                }
            });
    }

    /**
     * Deletes a Redshift cluster asynchronously.
     *
     * @param clusterId the identifier of the Redshift cluster to be deleted
     * @return a {@link CompletableFuture} that represents the asynchronous operation of deleting the Redshift cluster
     */
    public CompletableFuture<DeleteClusterResponse> deleteRedshiftClusterAsync(String clusterId) {
        DeleteClusterRequest deleteClusterRequest = DeleteClusterRequest.builder()
            .clusterIdentifier(clusterId)
            .skipFinalClusterSnapshot(true)
            .build();

        return getAsyncClient().deleteCluster(deleteClusterRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    // Handle exceptions
                    if (exception.getCause() instanceof RedshiftException) {
                        logger.info("Error: {}", exception.getMessage());
                    } else {
                        logger.info("Unexpected error: {}", exception.getMessage());
                    }
                } else {
                    // Handle successful response
                    logger.info("The status is {}", response.cluster().clusterStatus());
                }
            });
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/CreateCluster)
  + [DescribeClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/DescribeClusters)
  + [DescribeStatement](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/DescribeStatement)
  + [ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/ExecuteStatement)
  + [GetStatementResult](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/GetStatementResult)
  + [ListDatabasesPaginator](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/ListDatabasesPaginator)
  + [ModifyCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/ModifyCluster)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="redshift_CreateCluster_java_2_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを作成します。  

```
    /**
     * Creates a new Amazon Redshift cluster asynchronously.
     * @param clusterId     the unique identifier for the cluster
     * @param username      the username for the administrative user
     * @param userPassword  the password for the administrative user
     * @return a CompletableFuture that represents the asynchronous operation of creating the cluster
     * @throws RuntimeException if the cluster creation fails
     */
    public CompletableFuture<CreateClusterResponse> createClusterAsync(String clusterId, String username, String userPassword) {
        CreateClusterRequest clusterRequest = CreateClusterRequest.builder()
            .clusterIdentifier(clusterId)
            .masterUsername(username)
            .masterUserPassword(userPassword)
            .nodeType("ra3.4xlarge")
            .publiclyAccessible(true)
            .numberOfNodes(2)
            .build();

        return getAsyncClient().createCluster(clusterRequest)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("Created cluster ");
                } else {
                    throw new RuntimeException("Failed to create cluster: " + exception.getMessage(), exception);
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/CreateCluster)」を参照してください。

### `DeleteCluster`
<a name="redshift_DeleteCluster_java_2_topic"></a>

次のコード例は、`DeleteCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを削除します。  

```
    /**
     * Deletes a Redshift cluster asynchronously.
     *
     * @param clusterId the identifier of the Redshift cluster to be deleted
     * @return a {@link CompletableFuture} that represents the asynchronous operation of deleting the Redshift cluster
     */
    public CompletableFuture<DeleteClusterResponse> deleteRedshiftClusterAsync(String clusterId) {
        DeleteClusterRequest deleteClusterRequest = DeleteClusterRequest.builder()
            .clusterIdentifier(clusterId)
            .skipFinalClusterSnapshot(true)
            .build();

        return getAsyncClient().deleteCluster(deleteClusterRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    // Handle exceptions
                    if (exception.getCause() instanceof RedshiftException) {
                        logger.info("Error: {}", exception.getMessage());
                    } else {
                        logger.info("Unexpected error: {}", exception.getMessage());
                    }
                } else {
                    // Handle successful response
                    logger.info("The status is {}", response.cluster().clusterStatus());
                }
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/DeleteCluster)」を参照してください。

### `DescribeClusters`
<a name="redshift_DescribeClusters_java_2_topic"></a>

次のコード例は、`DescribeClusters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを記述する  

```
    /**
     * Waits asynchronously for the specified cluster to become available.
     * @param clusterId the identifier of the cluster to wait for
     * @return a {@link CompletableFuture} that completes when the cluster is ready
     */
    public CompletableFuture<Void> waitForClusterReadyAsync(String clusterId) {
        DescribeClustersRequest clustersRequest = DescribeClustersRequest.builder()
            .clusterIdentifier(clusterId)
            .build();

        logger.info("Waiting for cluster to become available. This may take a few minutes.");
        long startTime = System.currentTimeMillis();

        // Recursive method to poll the cluster status.
        return checkClusterStatusAsync(clustersRequest, startTime);
    }

    private CompletableFuture<Void> checkClusterStatusAsync(DescribeClustersRequest clustersRequest, long startTime) {
        return getAsyncClient().describeClusters(clustersRequest)
            .thenCompose(clusterResponse -> {
                List<Cluster> clusterList = clusterResponse.clusters();
                boolean clusterReady = false;
                for (Cluster cluster : clusterList) {
                    if ("available".equals(cluster.clusterStatus())) {
                        clusterReady = true;
                        break;
                    }
                }

                if (clusterReady) {
                    logger.info(String.format("Cluster is available!"));
                    return CompletableFuture.completedFuture(null);
                } else {
                    long elapsedTimeMillis = System.currentTimeMillis() - startTime;
                    long elapsedSeconds = elapsedTimeMillis / 1000;
                    long minutes = elapsedSeconds / 60;
                    long seconds = elapsedSeconds % 60;
                    System.out.printf("\rElapsed Time: %02d:%02d - Waiting for cluster...", minutes, seconds);
                    System.out.flush();

                    // Wait 1 second before the next status check
                    return CompletableFuture.runAsync(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException("Error during sleep: " + e.getMessage(), e);
                        }
                    }).thenCompose(ignored -> checkClusterStatusAsync(clustersRequest, startTime));
                }
            }).exceptionally(exception -> {
                throw new RuntimeException("Failed to get cluster status: " + exception.getMessage(), exception);
            });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeClusters](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/DescribeClusters)」を参照してください。

### `DescribeStatement`
<a name="redshift_DescribeStatement_java_2_topic"></a>

次のコード例は、`DescribeStatement` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Checks the status of an SQL statement asynchronously and handles the completion of the statement.
     *
     * @param sqlId the ID of the SQL statement to check
     * @return a {@link CompletableFuture} that completes when the SQL statement's status is either "FINISHED" or "FAILED"
     */
    public CompletableFuture<Void> checkStatementAsync(String sqlId) {
        DescribeStatementRequest statementRequest = DescribeStatementRequest.builder()
            .id(sqlId)
            .build();

        return getAsyncDataClient().describeStatement(statementRequest)
            .thenCompose(response -> {
                String status = response.statusAsString();
                logger.info("... Status: {} ", status);

                if ("FAILED".equals(status)) {
                    throw new RuntimeException("The Query Failed. Ending program");
                } else if ("FINISHED".equals(status)) {
                    return CompletableFuture.completedFuture(null);
                } else {
                    // Sleep for 1 second and recheck status
                    return CompletableFuture.runAsync(() -> {
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            throw new RuntimeException("Error during sleep: " + e.getMessage(), e);
                        }
                    }).thenCompose(ignore -> checkStatementAsync(sqlId)); // Recursively call until status is FINISHED or FAILED
                }
            }).whenComplete((result, exception) -> {
                if (exception != null) {
                    // Handle exceptions
                    logger.info("Error: {} ", exception.getMessage());
                } else {
                    logger.info("The statement is finished!");
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeStatement](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/DescribeStatement)」を参照してください。

### `ExecuteStatement`
<a name="redshift_ExecuteStatement_java_2_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
SQL ステートメントを実行してデータベーステーブルを作成します。  

```
    /**
     * Creates an asynchronous task to execute a SQL statement for creating a new table.
     *
     * @param clusterId    the identifier of the Amazon Redshift cluster
     * @param databaseName the name of the database to create the table in
     * @param userName     the username to use for the database connection
     * @return a {@link CompletableFuture} that completes with the result of the SQL statement execution
     * @throws RuntimeException if there is an error creating the table
     */
    public CompletableFuture<ExecuteStatementResponse> createTableAsync(String clusterId, String databaseName, String userName) {
        ExecuteStatementRequest createTableRequest = ExecuteStatementRequest.builder()
            .clusterIdentifier(clusterId)
            .dbUser(userName)
            .database(databaseName)
            .sql("CREATE TABLE Movies (" +
                "id INT PRIMARY KEY, " +
                "title VARCHAR(100), " +
                "year INT)")
            .build();

        return getAsyncDataClient().executeStatement(createTableRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    throw new RuntimeException("Error creating table: " + exception.getMessage(), exception);
                } else {
                    logger.info("Table created: Movies");
                }
            });
    }
```
SQL ステートメントを実行して、データベーステーブルにデータを挿入します。  

```
    /**
     * Asynchronously pops a table from a JSON file.
     *
     * @param clusterId   the ID of the cluster
     * @param databaseName the name of the database
     * @param userName    the username
     * @param fileName    the name of the JSON file
     * @param number      the number of records to process
     * @return a CompletableFuture that completes with the number of records added to the Movies table
     */
    public CompletableFuture<Integer> popTableAsync(String clusterId, String databaseName, String userName, String fileName, int number) {
        return CompletableFuture.supplyAsync(() -> {
                try {
                    JsonParser parser = new JsonFactory().createParser(new File(fileName));
                    JsonNode rootNode = new ObjectMapper().readTree(parser);
                    Iterator<JsonNode> iter = rootNode.iterator();
                    return iter;
                } catch (IOException e) {
                    throw new RuntimeException("Failed to read or parse JSON file: " + e.getMessage(), e);
                }
            }).thenCompose(iter -> processNodesAsync(clusterId, databaseName, userName, iter, number))
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    logger.info("Error {} ", exception.getMessage());
                } else {
                    logger.info("{} records were added to the Movies table." , result);
                }
            });
    }

    private CompletableFuture<Integer> processNodesAsync(String clusterId, String databaseName, String userName, Iterator<JsonNode> iter, int number) {
        return CompletableFuture.supplyAsync(() -> {
            int t = 0;
            try {
                while (iter.hasNext()) {
                    if (t == number)
                        break;
                    JsonNode currentNode = iter.next();
                    int year = currentNode.get("year").asInt();
                    String title = currentNode.get("title").asText();

                    // Use SqlParameter to avoid SQL injection.
                    List<SqlParameter> parameterList = new ArrayList<>();
                    String sqlStatement = "INSERT INTO Movies VALUES( :id , :title, :year);";
                    SqlParameter idParam = SqlParameter.builder()
                        .name("id")
                        .value(String.valueOf(t))
                        .build();

                    SqlParameter titleParam = SqlParameter.builder()
                        .name("title")
                        .value(title)
                        .build();

                    SqlParameter yearParam = SqlParameter.builder()
                        .name("year")
                        .value(String.valueOf(year))
                        .build();
                    parameterList.add(idParam);
                    parameterList.add(titleParam);
                    parameterList.add(yearParam);

                    ExecuteStatementRequest insertStatementRequest = ExecuteStatementRequest.builder()
                        .clusterIdentifier(clusterId)
                        .sql(sqlStatement)
                        .database(databaseName)
                        .dbUser(userName)
                        .parameters(parameterList)
                        .build();

                    getAsyncDataClient().executeStatement(insertStatementRequest);
                    logger.info("Inserted: " + title + " (" + year + ")");
                    t++;
                }
            } catch (RedshiftDataException e) {
                throw new RuntimeException("Error inserting data: " + e.getMessage(), e);
            }
            return t;
        });
    }
```
SQL ステートメントを実行して、データベーステーブルをクエリします。  

```
    /**
     * Asynchronously queries movies by a given year from a Redshift database.
     *
     * @param database    the name of the database to query
     * @param dbUser      the user to connect to the database with
     * @param year        the year to filter the movies by
     * @param clusterId   the identifier of the Redshift cluster to connect to
     * @return a {@link CompletableFuture} containing the response ID of the executed SQL statement
     */
    public CompletableFuture<String> queryMoviesByYearAsync(String database,
                                                                   String dbUser,
                                                                   int year,
                                                                   String clusterId) {

        String sqlStatement = "SELECT * FROM Movies WHERE year = :year";
        SqlParameter yearParam = SqlParameter.builder()
            .name("year")
            .value(String.valueOf(year))
            .build();

        ExecuteStatementRequest statementRequest = ExecuteStatementRequest.builder()
            .clusterIdentifier(clusterId)
            .database(database)
            .dbUser(dbUser)
            .parameters(yearParam)
            .sql(sqlStatement)
            .build();

        return CompletableFuture.supplyAsync(() -> {
            try {
                ExecuteStatementResponse response = getAsyncDataClient().executeStatement(statementRequest).join(); // Use join() to wait for the result
                return response.id();
            } catch (RedshiftDataException e) {
                throw new RuntimeException("Error executing statement: " + e.getMessage(), e);
            }
        }).exceptionally(exception -> {
            logger.info("Error: {}", exception.getMessage());
            return "";
        });
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/ExecuteStatement)」を参照してください。

### `GetStatementResult`
<a name="redshift_GetStatementResult_java_2_topic"></a>

次のコード例は、`GetStatementResult` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
ステートメントの結果を確認します。  

```
    /**
     * Asynchronously retrieves the results of a statement execution.
     *
     * @param statementId the ID of the statement for which to retrieve the results
     * @return a {@link CompletableFuture} that completes when the statement result has been processed
     */
    public CompletableFuture<Void> getResultsAsync(String statementId) {
        GetStatementResultRequest resultRequest = GetStatementResultRequest.builder()
            .id(statementId)
            .build();

        return getAsyncDataClient().getStatementResult(resultRequest)
            .handle((response, exception) -> {
                if (exception != null) {
                    logger.info("Error getting statement result {} ", exception.getMessage());
                    throw new RuntimeException("Error getting statement result: " + exception.getMessage(), exception);
                }

                // Extract and print the field values using streams if the response is valid.
                response.records().stream()
                    .flatMap(List::stream)
                    .map(Field::stringValue)
                    .filter(value -> value != null)
                    .forEach(value -> System.out.println("The Movie title field is " + value));

                return response;
            }).thenAccept(response -> {
                // Optionally add more logic here if needed after handling the response
            });
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[GetStatementResult](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/GetStatementResult)」を参照してください。

### `ListDatabases`
<a name="redshift_ListDatabases_java_2_topic"></a>

次のコード例は、`ListDatabases` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Lists all databases asynchronously for the specified cluster, database user, and database.
     * @param clusterId the identifier of the cluster to list databases for
     * @param dbUser the database user to use for the list databases request
     * @param database the database to list databases for
     * @return a {@link CompletableFuture} that completes when the database listing is complete, or throws a {@link RuntimeException} if there was an error
     */
    public CompletableFuture<Void> listAllDatabasesAsync(String clusterId, String dbUser, String database) {
        ListDatabasesRequest databasesRequest = ListDatabasesRequest.builder()
            .clusterIdentifier(clusterId)
            .dbUser(dbUser)
            .database(database)
            .build();

        // Asynchronous paginator for listing databases.
        ListDatabasesPublisher databasesPaginator = getAsyncDataClient().listDatabasesPaginator(databasesRequest);
        CompletableFuture<Void> future = databasesPaginator.subscribe(response -> {
            response.databases().forEach(db -> {
                logger.info("The database name is {} ", db);
            });
        });

        // Return the future for asynchronous handling.
        return future.exceptionally(exception -> {
            throw new RuntimeException("Failed to list databases: " + exception.getMessage(), exception);
        });
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[ListDatabases](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/ListDatabases)」を参照してください。**

### `ModifyCluster`
<a name="redshift_ModifyCluster_java_2_topic"></a>

次のコード例は、`ModifyCluster` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを変更します。  

```
    /**
     * Modifies an Amazon Redshift cluster asynchronously.
     *
     * @param clusterId the identifier of the cluster to be modified
     * @return a {@link CompletableFuture} that completes when the cluster modification is complete
     */
    public CompletableFuture<ModifyClusterResponse> modifyClusterAsync(String clusterId) {
        ModifyClusterRequest modifyClusterRequest = ModifyClusterRequest.builder()
            .clusterIdentifier(clusterId)
            .preferredMaintenanceWindow("wed:07:30-wed:08:00")
            .build();

        return getAsyncClient().modifyCluster(modifyClusterRequest)
            .whenComplete((clusterResponse, exception) -> {
                if (exception != null) {
                    if (exception.getCause() instanceof RedshiftException) {
                        logger.info("Error: {} ", exception.getMessage());
                    } else {
                        logger.info("Unexpected error: {} ", exception.getMessage());
                    }
                } else {
                    logger.info("The modified cluster was successfully modified and has "
                        + clusterResponse.cluster().preferredMaintenanceWindow() + " as the maintenance window");
                }
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ModifyCluster](https://docs.aws.amazon.com/goto/SdkForJavaV2/redshift-2012-12-01/ModifyCluster)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Redshift データ追跡用のウェブアプリケーションの作成
<a name="cross_RedshiftDataTracker_java_2_topic"></a>

次のコード例は、Amazon Redshift データベースを使用して、作業項目を追跡してレポートするウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon Redshift データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Redshift サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/CreatingSpringRedshiftRest) にある詳しい事例を参照してください。  

**この例で使用されているサービス**
+ Amazon Redshift
+ Amazon SES

# SDK for Java 2.x を使用する Amazon Rekognition の例
<a name="java_2_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CompareFaces`
<a name="rekognition_CompareFaces_java_2_topic"></a>

次のコード例は、`CompareFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を比較する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.*;
import software.amazon.awssdk.core.SdkBytes;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CompareFaces {
    public static void main(String[] args) {
        final String usage = """
            Usage: <bucketName> <sourceKey> <targetKey>
           
            Where:
                bucketName - The name of the S3 bucket where the images are stored.
                sourceKey  - The S3 key (file name) for the source image.
                targetKey  - The S3 key (file name) for the target image.
           """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String sourceKey = args[1];
        String targetKey = args[2];

        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();
        compareTwoFaces(rekClient, bucketName, sourceKey, targetKey);
     }

    /**
     * Compares two faces from images stored in an Amazon S3 bucket using AWS Rekognition.
     *
     * <p>This method takes two image keys from an S3 bucket and compares the faces within them.
     * It prints out the confidence level of matched faces and reports the number of unmatched faces.</p>
     *
     * @param rekClient   The {@link RekognitionClient} used to call AWS Rekognition.
     * @param bucketName  The name of the S3 bucket containing the images.
     * @param sourceKey   The object key (file path) for the source image in the S3 bucket.
     * @param targetKey   The object key (file path) for the target image in the S3 bucket.
     * @throws RuntimeException If the Rekognition service returns an error.
     */
    public static void compareTwoFaces(RekognitionClient rekClient, String bucketName, String sourceKey, String targetKey) {
        try {
            Float similarityThreshold = 70F;
            S3Object s3ObjectSource = S3Object.builder()
                    .bucket(bucketName)
                    .name(sourceKey)
                    .build();

            Image sourceImage = Image.builder()
                    .s3Object(s3ObjectSource)
                    .build();

            S3Object s3ObjectTarget = S3Object.builder()
                    .bucket(bucketName)
                    .name(targetKey)
                    .build();

            Image targetImage = Image.builder()
                    .s3Object(s3ObjectTarget)
                    .build();

            CompareFacesRequest facesRequest = CompareFacesRequest.builder()
                    .sourceImage(sourceImage)
                    .targetImage(targetImage)
                    .similarityThreshold(similarityThreshold)
                    .build();

            // Compare the two images.
            CompareFacesResponse compareFacesResult = rekClient.compareFaces(facesRequest);
            List<CompareFacesMatch> faceDetails = compareFacesResult.faceMatches();

            for (CompareFacesMatch match : faceDetails) {
                ComparedFace face = match.face();
                BoundingBox position = face.boundingBox();
                System.out.println("Face at " + position.left().toString()
                        + " " + position.top()
                        + " matches with " + face.confidence().toString()
                        + "% confidence.");
            }

            List<ComparedFace> unmatchedFaces = compareFacesResult.unmatchedFaces();
            System.out.println("There were " + unmatchedFaces.size() + " face(s) that did not match.");

        } catch (RekognitionException e) {
            System.err.println("Error comparing faces: " + e.awsErrorDetails().errorMessage());
            throw new RuntimeException(e);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[CompareFaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/CompareFaces)」を参照してください。

### `CreateCollection`
<a name="rekognition_CreateCollection_java_2_topic"></a>

次のコード例は、`CreateCollection` を使用する方法を示しています。

詳細については、「[コレクションを作成する](https://docs.aws.amazon.com/rekognition/latest/dg/create-collection-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.CreateCollectionResponse;
import software.amazon.awssdk.services.rekognition.model.CreateCollectionRequest;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;

/**
 * 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 CreateCollection {
    public static void main(String[] args) {
        final String usage = """

            Usage: <collectionName>\s

            Where:
                collectionName - The name of the collection.\s
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionId = args[0];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Creating collection: " + collectionId);
        createMyCollection(rekClient, collectionId);
        rekClient.close();
    }

    /**
     * Creates a new Amazon Rekognition collection.
     *
     * @param rekClient    the Amazon Rekognition client used to interact with the Rekognition service
     * @param collectionId the unique identifier for the collection to be created
     */
    public static void createMyCollection(RekognitionClient rekClient, String collectionId) {
        try {
            CreateCollectionRequest collectionRequest = CreateCollectionRequest.builder()
                    .collectionId(collectionId)
                    .build();

            CreateCollectionResponse collectionResponse = rekClient.createCollection(collectionRequest);
            System.out.println("CollectionArn: " + collectionResponse.collectionArn());
            System.out.println("Status code: " + collectionResponse.statusCode().toString());

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[CreateCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/CreateCollection)」を参照してください。

### `DeleteCollection`
<a name="rekognition_DeleteCollection_java_2_topic"></a>

次のコード例は、`DeleteCollection` を使用する方法を示しています。

詳細については、「[コレクションを削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-collection-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.DeleteCollectionRequest;
import software.amazon.awssdk.services.rekognition.model.DeleteCollectionResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;

/**
 * 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 DeleteCollection {
    public static void main(String[] args) {
        final String usage = """
            Usage: <collectionId>\s

            Where:
                collectionId - The id of the collection to delete.\s
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionId = args[0];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Deleting collection: " + collectionId);
        deleteMyCollection(rekClient, collectionId);
        rekClient.close();
    }

    /**
     * Deletes an Amazon Rekognition collection.
     *
     * @param rekClient      An instance of the {@link RekognitionClient} class, which is used to interact with the Amazon Rekognition service.
     * @param collectionId   The ID of the collection to be deleted.
     */
    public static void deleteMyCollection(RekognitionClient rekClient, String collectionId) {
        try {
            DeleteCollectionRequest deleteCollectionRequest = DeleteCollectionRequest.builder()
                    .collectionId(collectionId)
                    .build();

            DeleteCollectionResponse deleteCollectionResponse = rekClient.deleteCollection(deleteCollectionRequest);
            System.out.println(collectionId + ": " + deleteCollectionResponse.statusCode().toString());

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DeleteCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/DeleteCollection)」を参照してください。

### `DeleteFaces`
<a name="rekognition_DeleteFaces_java_2_topic"></a>

次のコード例は、`DeleteFaces` を使用する方法を示しています。

詳細については、「[コレクションから顔を削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-faces-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.DeleteFacesRequest;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;

/**
 * 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 DeleteFacesFromCollection {
    public static void main(String[] args) {
        final String usage = """
            Usage: <collectionId> <faceId>\s

            Where:
                collectionId - The id of the collection from which faces are deleted.\s
                faceId - The id of the face to delete.\s
           """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionId = args[0];
        String faceId = args[1];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Deleting collection: " + collectionId);
        deleteFacesCollection(rekClient, collectionId, faceId);
        rekClient.close();
    }

    /**
     * Deletes a face from the specified Amazon Rekognition collection.
     *
     * @param rekClient     an instance of the Amazon Rekognition client
     * @param collectionId  the ID of the collection from which the face should be deleted
     * @param faceId        the ID of the face to be deleted
     * @throws RekognitionException if an error occurs while deleting the face
     */
    public static void deleteFacesCollection(RekognitionClient rekClient,
            String collectionId,
            String faceId) {

        try {
            DeleteFacesRequest deleteFacesRequest = DeleteFacesRequest.builder()
                    .collectionId(collectionId)
                    .faceIds(faceId)
                    .build();

            rekClient.deleteFaces(deleteFacesRequest);
            System.out.println("The face was deleted from the collection.");

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DeleteFaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/DeleteFaces)」を参照してください。

### `DescribeCollection`
<a name="rekognition_DescribeCollection_java_2_topic"></a>

次のコード例は、`DescribeCollection` を使用する方法を示しています。

詳細については、「[コレクションを定義する](https://docs.aws.amazon.com/rekognition/latest/dg/describe-collection-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.DescribeCollectionRequest;
import software.amazon.awssdk.services.rekognition.model.DescribeCollectionResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;

/**
 * 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 DescribeCollection {
    public static void main(String[] args) {
        final String usage = """
            Usage:    <collectionName>

            Where:
                collectionName - The name of the Amazon Rekognition collection.\s
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionName = args[0];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        describeColl(rekClient, collectionName);
        rekClient.close();
    }

    /**
     * Describes an Amazon Rekognition collection.
     *
     * @param rekClient         The Amazon Rekognition client used to make the request.
     * @param collectionName    The name of the collection to describe.
     *
     * @throws RekognitionException If an error occurs while describing the collection.
     */
    public static void describeColl(RekognitionClient rekClient, String collectionName) {
        try {
            DescribeCollectionRequest describeCollectionRequest = DescribeCollectionRequest.builder()
                    .collectionId(collectionName)
                    .build();

            DescribeCollectionResponse describeCollectionResponse = rekClient
                    .describeCollection(describeCollectionRequest);
            System.out.println("Collection Arn : " + describeCollectionResponse.collectionARN());
            System.out.println("Created : " + describeCollectionResponse.creationTimestamp().toString());

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DescribeCollection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/DescribeCollection)」を参照してください。

### `DetectFaces`
<a name="rekognition_DetectFaces_java_2_topic"></a>

次のコード例は、`DetectFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を検出する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.*;

import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DetectFaces {
    public static void main(String[] args) {
        final String usage = """
                
            Usage:   <bucketName> <sourceImage>
                
            Where:
                bucketName = The name of the Amazon S3 bucket where the source image is stored.
                sourceImage - The name of the source image file in the Amazon S3 bucket. (for example, pic1.png).\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String sourceImage = args[1];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        detectFacesinImage(rekClient, bucketName, sourceImage);
        rekClient.close();
    }

    /**
     * Detects faces in an image stored in an Amazon S3 bucket using the Amazon Rekognition service.
     *
     * @param rekClient    The Amazon Rekognition client used to interact with the Rekognition service.
     * @param bucketName   The name of the Amazon S3 bucket where the source image is stored.
     * @param sourceImage  The name of the source image file in the Amazon S3 bucket.
     */
    public static void detectFacesinImage(RekognitionClient rekClient, String bucketName, String sourceImage) {
        try {
            S3Object s3ObjectTarget = S3Object.builder()
                .bucket(bucketName)
                .name(sourceImage)
                .build();

            Image targetImage = Image.builder()
                .s3Object(s3ObjectTarget)
                .build();

            DetectFacesRequest facesRequest = DetectFacesRequest.builder()
                .attributes(Attribute.ALL)
                .image(targetImage)
                .build();

            DetectFacesResponse facesResponse = rekClient.detectFaces(facesRequest);
            List<FaceDetail> faceDetails = facesResponse.faceDetails();
            for (FaceDetail face : faceDetails) {
                AgeRange ageRange = face.ageRange();
                System.out.println("The detected face is estimated to be between "
                        + ageRange.low().toString() + " and " + ageRange.high().toString()
                        + " years old.");

                System.out.println("There is a smile : " + face.smile().value().toString());
            }

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DetectFaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/DetectFaces)」を参照してください。

### `DetectLabels`
<a name="rekognition_DetectLabels_java_2_topic"></a>

次のコード例は、`DetectLabels` を使用する方法を示しています。

詳細については、「[イメージ内のラベルを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * 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 DetectLabels {
    public static void main(String[] args) {
        final String usage = """
            Usage: <bucketName> <sourceImage>

            Where:
                bucketName - The name of the Amazon S3 bucket where the image is stored
                sourceImage - The name of the image file (for example, pic1.png).\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0] ;
        String sourceImage = args[1] ;
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        detectImageLabels(rekClient, bucketName, sourceImage);
        rekClient.close();
    }

    /**
     * Detects the labels in an image stored in an Amazon S3 bucket using the Amazon Rekognition service.
     *
     * @param rekClient     the Amazon Rekognition client used to make the detection request
     * @param bucketName    the name of the Amazon S3 bucket where the image is stored
     * @param sourceImage   the name of the image file to be analyzed
     */
    public static void detectImageLabels(RekognitionClient rekClient, String bucketName, String sourceImage) {
        try {
            S3Object s3ObjectTarget = S3Object.builder()
                    .bucket(bucketName)
                    .name(sourceImage)
                    .build();

            Image souImage = Image.builder()
                    .s3Object(s3ObjectTarget)
                    .build();

            DetectLabelsRequest detectLabelsRequest = DetectLabelsRequest.builder()
                    .image(souImage)
                    .maxLabels(10)
                    .build();

            DetectLabelsResponse labelsResponse = rekClient.detectLabels(detectLabelsRequest);
            List<Label> labels = labelsResponse.labels();
            System.out.println("Detected labels for the given photo");
            for (Label label : labels) {
                System.out.println(label.name() + ": " + label.confidence().toString());
            }

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DetectLabels](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/DetectLabels)」を参照してください。

### `DetectModerationLabels`
<a name="rekognition_DetectModerationLabels_java_2_topic"></a>

次のコード例は、`DetectModerationLabels` を使用する方法を示しています。

詳細については、「[不適切なイメージを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-images.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * 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 DetectModerationLabels {

    public static void main(String[] args) {
        final String usage = """
            Usage:  <bucketName>  <sourceImage>

            Where:
                bucketName - The name of the S3 bucket where the images are stored.
                sourceImage - The name of the image (for example, pic1.png).\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String sourceImage = args[1];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        detectModLabels(rekClient, bucketName, sourceImage);
        rekClient.close();
    }

    /**
     * Detects moderation labels in an image stored in an Amazon S3 bucket.
     *
     * @param rekClient      the Amazon Rekognition client to use for the detection
     * @param bucketName     the name of the Amazon S3 bucket where the image is stored
     * @param sourceImage    the name of the image file to be analyzed
     *
     * @throws RekognitionException if there is an error during the image detection process
     */
    public static void detectModLabels(RekognitionClient rekClient, String bucketName, String sourceImage) {
        try {
            S3Object s3ObjectTarget = S3Object.builder()
                    .bucket(bucketName)
                    .name(sourceImage)
                    .build();

            Image targetImage = Image.builder()
                    .s3Object(s3ObjectTarget)
                    .build();

            DetectModerationLabelsRequest moderationLabelsRequest = DetectModerationLabelsRequest.builder()
                    .image(targetImage)
                    .minConfidence(60F)
                    .build();

            DetectModerationLabelsResponse moderationLabelsResponse = rekClient
                    .detectModerationLabels(moderationLabelsRequest);
            List<ModerationLabel> labels = moderationLabelsResponse.moderationLabels();
            System.out.println("Detected labels for image");
            for (ModerationLabel label : labels) {
                System.out.println("Label: " + label.name()
                        + "\n Confidence: " + label.confidence().toString() + "%"
                        + "\n Parent:" + label.parentName());
            }

        } catch (RekognitionException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DetectModerationLabels](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/DetectModerationLabels)」を参照してください。

### `DetectText`
<a name="rekognition_DetectText_java_2_topic"></a>

次のコード例は、`DetectText` を使用する方法を示しています。

詳細については、「[イメージ内のテキストを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/text-detecting-text-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * 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 DetectText {
    public static void main(String[] args) {
        final String usage = "\n" +
            "Usage:   <bucketName> <sourceImage>\n" +
            "\n" +
            "Where:\n" +
            "   bucketName - The name of the S3 bucket where the image is stored\n" +
            "   sourceImage - The path to the image that contains text (for example, pic1.png). \n";

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String sourceImage = args[1];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        detectTextLabels(rekClient, bucketName, sourceImage);
        rekClient.close();
    }

    /**
     * Detects text labels in an image stored in an S3 bucket using Amazon Rekognition.
     *
     * @param rekClient    an instance of the Amazon Rekognition client
     * @param bucketName   the name of the S3 bucket where the image is stored
     * @param sourceImage  the name of the image file in the S3 bucket
     * @throws RekognitionException if an error occurs while calling the Amazon Rekognition API
     */
    public static void detectTextLabels(RekognitionClient rekClient, String bucketName, String sourceImage) {
        try {
            S3Object s3ObjectTarget = S3Object.builder()
                    .bucket(bucketName)
                    .name(sourceImage)
                    .build();

            Image souImage = Image.builder()
                    .s3Object(s3ObjectTarget)
                    .build();

            DetectTextRequest textRequest = DetectTextRequest.builder()
                    .image(souImage)
                    .build();

            DetectTextResponse textResponse = rekClient.detectText(textRequest);
            List<TextDetection> textCollection = textResponse.textDetections();
            System.out.println("Detected lines and words");
            for (TextDetection text : textCollection) {
                System.out.println("Detected: " + text.detectedText());
                System.out.println("Confidence: " + text.confidence().toString());
                System.out.println("Id : " + text.id());
                System.out.println("Parent Id: " + text.parentId());
                System.out.println("Type: " + text.type());
                System.out.println();
            }

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[DetectText](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/DetectText)」を参照してください。

### `IndexFaces`
<a name="rekognition_IndexFaces_java_2_topic"></a>

次のコード例は、`IndexFaces` を使用する方法を示しています。

詳細については、「[コレクションに顔を追加する](https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.*;
import java.util.List;

/**
 * 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 AddFacesToCollection {
    public static void main(String[] args) {
        final String usage = """
            Usage: <collectionId> <sourceImage> <bucketName>

            Where:
                collectionName - The name of the collection.
                sourceImage - The name of the image (for example, pic1.png).
                bucketName - The name of the S3 bucket.
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionId = args[0];
        String sourceImage = args[1];
        String bucketName = args[2];;
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        addToCollection(rekClient, collectionId, bucketName, sourceImage);
        rekClient.close();
    }

    /**
     * Adds a face from an image to an Amazon Rekognition collection.
     *
     * @param rekClient     the Amazon Rekognition client
     * @param collectionId  the ID of the collection to add the face to
     * @param bucketName    the name of the Amazon S3 bucket containing the image
     * @param sourceImage   the name of the image file to add to the collection
     * @throws RekognitionException if there is an error while interacting with the Amazon Rekognition service
     */
    public static void addToCollection(RekognitionClient rekClient, String collectionId, String bucketName, String sourceImage) {
        try {
            S3Object s3ObjectTarget = S3Object.builder()
                    .bucket(bucketName)
                    .name(sourceImage)
                    .build();

            Image targetImage = Image.builder()
                    .s3Object(s3ObjectTarget)
                    .build();

            IndexFacesRequest facesRequest = IndexFacesRequest.builder()
                    .collectionId(collectionId)
                    .image(targetImage)
                    .maxFaces(1)
                    .qualityFilter(QualityFilter.AUTO)
                    .detectionAttributes(Attribute.DEFAULT)
                    .build();

            IndexFacesResponse facesResponse = rekClient.indexFaces(facesRequest);
            System.out.println("Results for the image");
            System.out.println("\n Faces indexed:");
            List<FaceRecord> faceRecords = facesResponse.faceRecords();
            for (FaceRecord faceRecord : faceRecords) {
                System.out.println("  Face ID: " + faceRecord.face().faceId());
                System.out.println("  Location:" + faceRecord.faceDetail().boundingBox().toString());
            }

            List<UnindexedFace> unindexedFaces = facesResponse.unindexedFaces();
            System.out.println("Faces not indexed:");
            for (UnindexedFace unindexedFace : unindexedFaces) {
                System.out.println("  Location:" + unindexedFace.faceDetail().boundingBox().toString());
                System.out.println("  Reasons:");
                for (Reason reason : unindexedFace.reasons()) {
                    System.out.println("Reason:  " + reason);
                }
            }

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[IndexFaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/IndexFaces)」を参照してください。

### `ListCollections`
<a name="rekognition_ListCollections_java_2_topic"></a>

次のコード例は、`ListCollections` を使用する方法を示しています。

コレクションの詳細については、「[コレクションを一覧表示する](https://docs.aws.amazon.com/rekognition/latest/dg/list-collection-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.ListCollectionsRequest;
import software.amazon.awssdk.services.rekognition.model.ListCollectionsResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import java.util.List;

/**
 * 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 ListCollections {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Listing collections");
        listAllCollections(rekClient);
        rekClient.close();
    }

    public static void listAllCollections(RekognitionClient rekClient) {
        try {
            ListCollectionsRequest listCollectionsRequest = ListCollectionsRequest.builder()
                    .maxResults(10)
                    .build();

            ListCollectionsResponse response = rekClient.listCollections(listCollectionsRequest);
            List<String> collectionIds = response.collectionIds();
            for (String resultId : collectionIds) {
                System.out.println(resultId);
            }

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[ListCollections](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/ListCollections)」を参照してください。

### `ListFaces`
<a name="rekognition_ListFaces_java_2_topic"></a>

次のコード例は、`ListFaces` を使用する方法を示しています。

詳細については、「[コレクションに顔を保存する](https://docs.aws.amazon.com/rekognition/latest/dg/list-faces-in-collection-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.Face;
import software.amazon.awssdk.services.rekognition.model.ListFacesRequest;
import software.amazon.awssdk.services.rekognition.model.ListFacesResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import java.util.List;

/**
 * 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 ListFacesInCollection {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <collectionId>

                Where:
                   collectionId - The name of the collection.\s
                """;

        if (args.length < 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionId = args[0];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Faces in collection " + collectionId);
        listFacesCollection(rekClient, collectionId);
        rekClient.close();
    }

    public static void listFacesCollection(RekognitionClient rekClient, String collectionId) {
        try {
            ListFacesRequest facesRequest = ListFacesRequest.builder()
                    .collectionId(collectionId)
                    .maxResults(10)
                    .build();

            ListFacesResponse facesResponse = rekClient.listFaces(facesRequest);
            List<Face> faces = facesResponse.faces();
            for (Face face : faces) {
                System.out.println("Confidence level there is a face: " + face.confidence());
                System.out.println("The face Id value is " + face.faceId());
            }

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[ListFaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/ListFaces)」を参照してください。

### `RecognizeCelebrities`
<a name="rekognition_RecognizeCelebrities_java_2_topic"></a>

次のコード例は、`RecognizeCelebrities` を使用する方法を示しています。

詳細については、「[イメージ内で有名人を認識する](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-procedure-image.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.core.SdkBytes;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

import software.amazon.awssdk.services.rekognition.model.*;

/**
 * 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 RecognizeCelebrities {
    public static void main(String[] args) {
        final String usage = """
                Usage:   <bucketName> <sourceImage>

                Where:
                   bucketName - The name of the S3 bucket where the images are stored.
                   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
       }

        String bucketName = args[0];;
        String sourceImage = args[1];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Locating celebrities in " + sourceImage);
        recognizeAllCelebrities(rekClient, bucketName, sourceImage);
        rekClient.close();
    }

    /**
     * Recognizes all celebrities in an image stored in an Amazon S3 bucket.
     *
     * @param rekClient    the Amazon Rekognition client used to perform the celebrity recognition operation
     * @param bucketName   the name of the Amazon S3 bucket where the source image is stored
     * @param sourceImage  the name of the source image file stored in the Amazon S3 bucket
     */
    public static void recognizeAllCelebrities(RekognitionClient rekClient, String bucketName, String sourceImage) {
        try {
            S3Object s3ObjectTarget = S3Object.builder()
                .bucket(bucketName)
                .name(sourceImage)
                .build();

            Image souImage = Image.builder()
                    .s3Object(s3ObjectTarget)
                    .build();

            RecognizeCelebritiesRequest request = RecognizeCelebritiesRequest.builder()
                    .image(souImage)
                    .build();

            RecognizeCelebritiesResponse result = rekClient.recognizeCelebrities(request);
            List<Celebrity> celebs = result.celebrityFaces();
            System.out.println(celebs.size() + " celebrity(s) were recognized.\n");
            for (Celebrity celebrity : celebs) {
                System.out.println("Celebrity recognized: " + celebrity.name());
                System.out.println("Celebrity ID: " + celebrity.id());

                System.out.println("Further information (if available):");
                for (String url : celebrity.urls()) {
                    System.out.println(url);
                }
                System.out.println();
            }
            System.out.println(result.unrecognizedFaces().size() + " face(s) were unrecognized.");

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[RecognizeCelebrities](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/RecognizeCelebrities)」を参照してください。

### `SearchFaces`
<a name="rekognition_SearchFaces_java_2_topic"></a>

次のコード例は、`SearchFaces` を使用する方法を示しています。

詳細については、[顔 (フェイス ID) を検索する](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-id-procedure.html) を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.SearchFacesByImageRequest;
import software.amazon.awssdk.services.rekognition.model.Image;
import software.amazon.awssdk.services.rekognition.model.SearchFacesByImageResponse;
import software.amazon.awssdk.services.rekognition.model.FaceMatch;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * 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 SearchFaceMatchingImageCollection {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <collectionId> <sourceImage>

                Where:
                   collectionId - The id of the collection. \s
                   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s

                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionId = args[0];
        String sourceImage = args[1];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Searching for a face in a collections");
        searchFaceInCollection(rekClient, collectionId, sourceImage);
        rekClient.close();
    }

    public static void searchFaceInCollection(RekognitionClient rekClient, String collectionId, String sourceImage) {
        try {
            InputStream sourceStream = new FileInputStream(new File(sourceImage));
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);
            Image souImage = Image.builder()
                    .bytes(sourceBytes)
                    .build();

            SearchFacesByImageRequest facesByImageRequest = SearchFacesByImageRequest.builder()
                    .image(souImage)
                    .maxFaces(10)
                    .faceMatchThreshold(70F)
                    .collectionId(collectionId)
                    .build();

            SearchFacesByImageResponse imageResponse = rekClient.searchFacesByImage(facesByImageRequest);
            System.out.println("Faces matching in the collection");
            List<FaceMatch> faceImageMatches = imageResponse.faceMatches();
            for (FaceMatch face : faceImageMatches) {
                System.out.println("The similarity level is  " + face.similarity());
                System.out.println();
            }

        } catch (RekognitionException | FileNotFoundException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[SearchFaces](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/SearchFaces)」を参照してください。

### `SearchFacesByImage`
<a name="rekognition_SearchFacesByImage_java_2_topic"></a>

次のコード例は、`SearchFacesByImage` を使用する方法を示しています。

詳細については、「[顔を検索する (イメージ)](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-image-procedure.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.SearchFacesRequest;
import software.amazon.awssdk.services.rekognition.model.SearchFacesResponse;
import software.amazon.awssdk.services.rekognition.model.FaceMatch;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import java.util.List;

/**
 * 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 SearchFaceMatchingIdCollection {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <collectionId> <sourceImage>

                Where:
                   collectionId - The id of the collection. \s
                   sourceImage - The path to the image (for example, C:\\AWS\\pic1.png).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String collectionId = args[0];
        String faceId = args[1];
        Region region = Region.US_WEST_2;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        System.out.println("Searching for a face in a collections");
        searchFacebyId(rekClient, collectionId, faceId);
        rekClient.close();
    }

    public static void searchFacebyId(RekognitionClient rekClient, String collectionId, String faceId) {
        try {
            SearchFacesRequest searchFacesRequest = SearchFacesRequest.builder()
                    .collectionId(collectionId)
                    .faceId(faceId)
                    .faceMatchThreshold(70F)
                    .maxFaces(2)
                    .build();

            SearchFacesResponse imageResponse = rekClient.searchFaces(searchFacesRequest);
            System.out.println("Faces matching in the collection");
            List<FaceMatch> faceImageMatches = imageResponse.faceMatches();
            for (FaceMatch face : faceImageMatches) {
                System.out.println("The similarity level is  " + face.similarity());
                System.out.println();
            }

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[SearchFacesByImage](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/SearchFacesByImage)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_java_2_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Java 2.x**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 画像内の PPE を検出する
<a name="cross_RekognitionPhotoAnalyzerPPE_java_2_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内の個人用防護具 (PPE) を検出するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 個人用保護具を使用してイメージを検出する AWS Lambda 関数を作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_ppe) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### ビデオ内の情報を検出する
<a name="rekognition_VideoDetection_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Rekognition のジョブを開始し、人物、オブジェクト、テキストなどの要素を動画から検出します。
+ ジョブが完了するまでジョブのステータスを確認します。
+ 検出された要素のリストをジョブごとに出力します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/rekognition/#code-examples)での設定と実行の方法を確認してください。
Amazon S3 バケット内のビデオから有名人の結果を取得します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.S3Object;
import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
import software.amazon.awssdk.services.rekognition.model.Video;
import software.amazon.awssdk.services.rekognition.model.StartCelebrityRecognitionResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.CelebrityRecognitionSortBy;
import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
import software.amazon.awssdk.services.rekognition.model.CelebrityRecognition;
import software.amazon.awssdk.services.rekognition.model.CelebrityDetail;
import software.amazon.awssdk.services.rekognition.model.StartCelebrityRecognitionRequest;
import software.amazon.awssdk.services.rekognition.model.GetCelebrityRecognitionRequest;
import software.amazon.awssdk.services.rekognition.model.GetCelebrityRecognitionResponse;
import java.util.List;

/**
 * To run this code example, ensure that you perform the Prerequisites as stated
 * in the Amazon Rekognition Guide:
 * https://docs.aws.amazon.com/rekognition/latest/dg/video-analyzing-with-sqs.html
 *
 * Also, ensure that 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 VideoCelebrityDetection {
    private static String startJobId = "";

    public static void main(String[] args) {
        final String usage = """

                Usage:    <bucket> <video> <topicArn> <roleArn>

                Where:
                   bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                   video - The name of video (for example, people.mp4).\s
                   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        NotificationChannel channel = NotificationChannel.builder()
                .snsTopicArn(topicArn)
                .roleArn(roleArn)
                .build();

        startCelebrityDetection(rekClient, channel, bucket, video);
        getCelebrityDetectionResults(rekClient);
        System.out.println("This example is done!");
        rekClient.close();
    }

    public static void startCelebrityDetection(RekognitionClient rekClient,
            NotificationChannel channel,
            String bucket,
            String video) {
        try {
            S3Object s3Obj = S3Object.builder()
                    .bucket(bucket)
                    .name(video)
                    .build();

            Video vidOb = Video.builder()
                    .s3Object(s3Obj)
                    .build();

            StartCelebrityRecognitionRequest recognitionRequest = StartCelebrityRecognitionRequest.builder()
                    .jobTag("Celebrities")
                    .notificationChannel(channel)
                    .video(vidOb)
                    .build();

            StartCelebrityRecognitionResponse startCelebrityRecognitionResult = rekClient
                    .startCelebrityRecognition(recognitionRequest);
            startJobId = startCelebrityRecognitionResult.jobId();

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void getCelebrityDetectionResults(RekognitionClient rekClient) {
        try {
            String paginationToken = null;
            GetCelebrityRecognitionResponse recognitionResponse = null;
            boolean finished = false;
            String status;
            int yy = 0;

            do {
                if (recognitionResponse != null)
                    paginationToken = recognitionResponse.nextToken();

                GetCelebrityRecognitionRequest recognitionRequest = GetCelebrityRecognitionRequest.builder()
                        .jobId(startJobId)
                        .nextToken(paginationToken)
                        .sortBy(CelebrityRecognitionSortBy.TIMESTAMP)
                        .maxResults(10)
                        .build();

                // Wait until the job succeeds
                while (!finished) {
                    recognitionResponse = rekClient.getCelebrityRecognition(recognitionRequest);
                    status = recognitionResponse.jobStatusAsString();

                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }

                finished = false;

                // Proceed when the job is done - otherwise VideoMetadata is null.
                VideoMetadata videoMetaData = recognitionResponse.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());
                System.out.println("Job");

                List<CelebrityRecognition> celebs = recognitionResponse.celebrities();
                for (CelebrityRecognition celeb : celebs) {
                    long seconds = celeb.timestamp() / 1000;
                    System.out.print("Sec: " + seconds + " ");
                    CelebrityDetail details = celeb.celebrity();
                    System.out.println("Name: " + details.name());
                    System.out.println("Id: " + details.id());
                    System.out.println();
                }

            } while (recognitionResponse.nextToken() != null);

        } catch (RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
ラベル検出オペレーションによって、ビデオ内のラベルを検出します。  

```
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.StartLabelDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
import software.amazon.awssdk.services.rekognition.model.S3Object;
import software.amazon.awssdk.services.rekognition.model.Video;
import software.amazon.awssdk.services.rekognition.model.StartLabelDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.GetLabelDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.GetLabelDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.LabelDetectionSortBy;
import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
import software.amazon.awssdk.services.rekognition.model.LabelDetection;
import software.amazon.awssdk.services.rekognition.model.Label;
import software.amazon.awssdk.services.rekognition.model.Instance;
import software.amazon.awssdk.services.rekognition.model.Parent;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import java.util.List;

/**
 * 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 VideoDetect {
    private static String startJobId = "";

    public static void main(String[] args) {
        final String usage = """

                Usage:    <bucket> <video> <queueUrl> <topicArn> <roleArn>

                Where:
                   bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                   video - The name of the video (for example, people.mp4).\s
                   queueUrl- The URL of a SQS queue.\s
                   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucket = args[0];
        String video = args[1];
        String queueUrl = args[2];
        String topicArn = args[3];
        String roleArn = args[4];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        SqsClient sqs = SqsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        NotificationChannel channel = NotificationChannel.builder()
                .snsTopicArn(topicArn)
                .roleArn(roleArn)
                .build();

        startLabels(rekClient, channel, bucket, video);
        getLabelJob(rekClient, sqs, queueUrl);
        System.out.println("This example is done!");
        sqs.close();
        rekClient.close();
    }

    public static void startLabels(RekognitionClient rekClient,
            NotificationChannel channel,
            String bucket,
            String video) {
        try {
            S3Object s3Obj = S3Object.builder()
                    .bucket(bucket)
                    .name(video)
                    .build();

            Video vidOb = Video.builder()
                    .s3Object(s3Obj)
                    .build();

            StartLabelDetectionRequest labelDetectionRequest = StartLabelDetectionRequest.builder()
                    .jobTag("DetectingLabels")
                    .notificationChannel(channel)
                    .video(vidOb)
                    .minConfidence(50F)
                    .build();

            StartLabelDetectionResponse labelDetectionResponse = rekClient.startLabelDetection(labelDetectionRequest);
            startJobId = labelDetectionResponse.jobId();

            boolean ans = true;
            String status = "";
            int yy = 0;
            while (ans) {

                GetLabelDetectionRequest detectionRequest = GetLabelDetectionRequest.builder()
                        .jobId(startJobId)
                        .maxResults(10)
                        .build();

                GetLabelDetectionResponse result = rekClient.getLabelDetection(detectionRequest);
                status = result.jobStatusAsString();

                if (status.compareTo("SUCCEEDED") == 0)
                    ans = false;
                else
                    System.out.println(yy + " status is: " + status);

                Thread.sleep(1000);
                yy++;
            }

            System.out.println(startJobId + " status is: " + status);

        } catch (RekognitionException | InterruptedException e) {
            e.getMessage();
            System.exit(1);
        }
    }

    public static void getLabelJob(RekognitionClient rekClient, SqsClient sqs, String queueUrl) {
        List<Message> messages;
        ReceiveMessageRequest messageRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .build();

        try {
            messages = sqs.receiveMessage(messageRequest).messages();

            if (!messages.isEmpty()) {
                for (Message message : messages) {
                    String notification = message.body();

                    // Get the status and job id from the notification
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonMessageTree = mapper.readTree(notification);
                    JsonNode messageBodyText = jsonMessageTree.get("Message");
                    ObjectMapper operationResultMapper = new ObjectMapper();
                    JsonNode jsonResultTree = operationResultMapper.readTree(messageBodyText.textValue());
                    JsonNode operationJobId = jsonResultTree.get("JobId");
                    JsonNode operationStatus = jsonResultTree.get("Status");
                    System.out.println("Job found in JSON is " + operationJobId);

                    DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
                            .queueUrl(queueUrl)
                            .build();

                    String jobId = operationJobId.textValue();
                    if (startJobId.compareTo(jobId) == 0) {
                        System.out.println("Job id: " + operationJobId);
                        System.out.println("Status : " + operationStatus.toString());

                        if (operationStatus.asText().equals("SUCCEEDED"))
                            getResultsLabels(rekClient);
                        else
                            System.out.println("Video analysis failed");

                        sqs.deleteMessage(deleteMessageRequest);
                    } else {
                        System.out.println("Job received was not job " + startJobId);
                        sqs.deleteMessage(deleteMessageRequest);
                    }
                }
            }

        } catch (RekognitionException e) {
            e.getMessage();
            System.exit(1);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    // Gets the job results by calling GetLabelDetection
    private static void getResultsLabels(RekognitionClient rekClient) {

        int maxResults = 10;
        String paginationToken = null;
        GetLabelDetectionResponse labelDetectionResult = null;

        try {
            do {
                if (labelDetectionResult != null)
                    paginationToken = labelDetectionResult.nextToken();

                GetLabelDetectionRequest labelDetectionRequest = GetLabelDetectionRequest.builder()
                        .jobId(startJobId)
                        .sortBy(LabelDetectionSortBy.TIMESTAMP)
                        .maxResults(maxResults)
                        .nextToken(paginationToken)
                        .build();

                labelDetectionResult = rekClient.getLabelDetection(labelDetectionRequest);
                VideoMetadata videoMetaData = labelDetectionResult.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());

                List<LabelDetection> detectedLabels = labelDetectionResult.labels();
                for (LabelDetection detectedLabel : detectedLabels) {
                    long seconds = detectedLabel.timestamp();
                    Label label = detectedLabel.label();
                    System.out.println("Millisecond: " + seconds + " ");

                    System.out.println("   Label:" + label.name());
                    System.out.println("   Confidence:" + detectedLabel.label().confidence().toString());

                    List<Instance> instances = label.instances();
                    System.out.println("   Instances of " + label.name());

                    if (instances.isEmpty()) {
                        System.out.println("        " + "None");
                    } else {
                        for (Instance instance : instances) {
                            System.out.println("        Confidence: " + instance.confidence().toString());
                            System.out.println("        Bounding box: " + instance.boundingBox().toString());
                        }
                    }
                    System.out.println("   Parent labels for " + label.name() + ":");
                    List<Parent> parents = label.parents();

                    if (parents.isEmpty()) {
                        System.out.println("        None");
                    } else {
                        for (Parent parent : parents) {
                            System.out.println("   " + parent.name());
                        }
                    }
                    System.out.println();
                }
            } while (labelDetectionResult != null && labelDetectionResult.nextToken() != null);

        } catch (RekognitionException e) {
            e.getMessage();
            System.exit(1);
        }
    }
}
```
Amazon S3 バケットに保存されたビデオ内の顔を検出する  

```
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.StartLabelDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
import software.amazon.awssdk.services.rekognition.model.S3Object;
import software.amazon.awssdk.services.rekognition.model.Video;
import software.amazon.awssdk.services.rekognition.model.StartLabelDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.GetLabelDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.GetLabelDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.LabelDetectionSortBy;
import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
import software.amazon.awssdk.services.rekognition.model.LabelDetection;
import software.amazon.awssdk.services.rekognition.model.Label;
import software.amazon.awssdk.services.rekognition.model.Instance;
import software.amazon.awssdk.services.rekognition.model.Parent;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import java.util.List;

/**
 * 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 VideoDetect {
    private static String startJobId = "";

    public static void main(String[] args) {
        final String usage = """

                Usage:    <bucket> <video> <queueUrl> <topicArn> <roleArn>

                Where:
                   bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                   video - The name of the video (for example, people.mp4).\s
                   queueUrl- The URL of a SQS queue.\s
                   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                """;

        if (args.length != 5) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucket = args[0];
        String video = args[1];
        String queueUrl = args[2];
        String topicArn = args[3];
        String roleArn = args[4];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        SqsClient sqs = SqsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        NotificationChannel channel = NotificationChannel.builder()
                .snsTopicArn(topicArn)
                .roleArn(roleArn)
                .build();

        startLabels(rekClient, channel, bucket, video);
        getLabelJob(rekClient, sqs, queueUrl);
        System.out.println("This example is done!");
        sqs.close();
        rekClient.close();
    }

    public static void startLabels(RekognitionClient rekClient,
            NotificationChannel channel,
            String bucket,
            String video) {
        try {
            S3Object s3Obj = S3Object.builder()
                    .bucket(bucket)
                    .name(video)
                    .build();

            Video vidOb = Video.builder()
                    .s3Object(s3Obj)
                    .build();

            StartLabelDetectionRequest labelDetectionRequest = StartLabelDetectionRequest.builder()
                    .jobTag("DetectingLabels")
                    .notificationChannel(channel)
                    .video(vidOb)
                    .minConfidence(50F)
                    .build();

            StartLabelDetectionResponse labelDetectionResponse = rekClient.startLabelDetection(labelDetectionRequest);
            startJobId = labelDetectionResponse.jobId();

            boolean ans = true;
            String status = "";
            int yy = 0;
            while (ans) {

                GetLabelDetectionRequest detectionRequest = GetLabelDetectionRequest.builder()
                        .jobId(startJobId)
                        .maxResults(10)
                        .build();

                GetLabelDetectionResponse result = rekClient.getLabelDetection(detectionRequest);
                status = result.jobStatusAsString();

                if (status.compareTo("SUCCEEDED") == 0)
                    ans = false;
                else
                    System.out.println(yy + " status is: " + status);

                Thread.sleep(1000);
                yy++;
            }

            System.out.println(startJobId + " status is: " + status);

        } catch (RekognitionException | InterruptedException e) {
            e.getMessage();
            System.exit(1);
        }
    }

    public static void getLabelJob(RekognitionClient rekClient, SqsClient sqs, String queueUrl) {
        List<Message> messages;
        ReceiveMessageRequest messageRequest = ReceiveMessageRequest.builder()
                .queueUrl(queueUrl)
                .build();

        try {
            messages = sqs.receiveMessage(messageRequest).messages();

            if (!messages.isEmpty()) {
                for (Message message : messages) {
                    String notification = message.body();

                    // Get the status and job id from the notification
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode jsonMessageTree = mapper.readTree(notification);
                    JsonNode messageBodyText = jsonMessageTree.get("Message");
                    ObjectMapper operationResultMapper = new ObjectMapper();
                    JsonNode jsonResultTree = operationResultMapper.readTree(messageBodyText.textValue());
                    JsonNode operationJobId = jsonResultTree.get("JobId");
                    JsonNode operationStatus = jsonResultTree.get("Status");
                    System.out.println("Job found in JSON is " + operationJobId);

                    DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
                            .queueUrl(queueUrl)
                            .build();

                    String jobId = operationJobId.textValue();
                    if (startJobId.compareTo(jobId) == 0) {
                        System.out.println("Job id: " + operationJobId);
                        System.out.println("Status : " + operationStatus.toString());

                        if (operationStatus.asText().equals("SUCCEEDED"))
                            getResultsLabels(rekClient);
                        else
                            System.out.println("Video analysis failed");

                        sqs.deleteMessage(deleteMessageRequest);
                    } else {
                        System.out.println("Job received was not job " + startJobId);
                        sqs.deleteMessage(deleteMessageRequest);
                    }
                }
            }

        } catch (RekognitionException e) {
            e.getMessage();
            System.exit(1);
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    // Gets the job results by calling GetLabelDetection
    private static void getResultsLabels(RekognitionClient rekClient) {

        int maxResults = 10;
        String paginationToken = null;
        GetLabelDetectionResponse labelDetectionResult = null;

        try {
            do {
                if (labelDetectionResult != null)
                    paginationToken = labelDetectionResult.nextToken();

                GetLabelDetectionRequest labelDetectionRequest = GetLabelDetectionRequest.builder()
                        .jobId(startJobId)
                        .sortBy(LabelDetectionSortBy.TIMESTAMP)
                        .maxResults(maxResults)
                        .nextToken(paginationToken)
                        .build();

                labelDetectionResult = rekClient.getLabelDetection(labelDetectionRequest);
                VideoMetadata videoMetaData = labelDetectionResult.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());

                List<LabelDetection> detectedLabels = labelDetectionResult.labels();
                for (LabelDetection detectedLabel : detectedLabels) {
                    long seconds = detectedLabel.timestamp();
                    Label label = detectedLabel.label();
                    System.out.println("Millisecond: " + seconds + " ");

                    System.out.println("   Label:" + label.name());
                    System.out.println("   Confidence:" + detectedLabel.label().confidence().toString());

                    List<Instance> instances = label.instances();
                    System.out.println("   Instances of " + label.name());

                    if (instances.isEmpty()) {
                        System.out.println("        " + "None");
                    } else {
                        for (Instance instance : instances) {
                            System.out.println("        Confidence: " + instance.confidence().toString());
                            System.out.println("        Bounding box: " + instance.boundingBox().toString());
                        }
                    }
                    System.out.println("   Parent labels for " + label.name() + ":");
                    List<Parent> parents = label.parents();

                    if (parents.isEmpty()) {
                        System.out.println("        None");
                    } else {
                        for (Parent parent : parents) {
                            System.out.println("   " + parent.name());
                        }
                    }
                    System.out.println();
                }
            } while (labelDetectionResult != null && labelDetectionResult.nextToken() != null);

        } catch (RekognitionException e) {
            e.getMessage();
            System.exit(1);
        }
    }
}
```
Amazon S3 バケットに保存されたビデオ内の不適切なコンテンツや攻撃的なコンテンツを検出します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
import software.amazon.awssdk.services.rekognition.model.S3Object;
import software.amazon.awssdk.services.rekognition.model.Video;
import software.amazon.awssdk.services.rekognition.model.StartContentModerationRequest;
import software.amazon.awssdk.services.rekognition.model.StartContentModerationResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.GetContentModerationResponse;
import software.amazon.awssdk.services.rekognition.model.GetContentModerationRequest;
import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
import software.amazon.awssdk.services.rekognition.model.ContentModerationDetection;
import java.util.List;

/**
 * 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 VideoDetectInappropriate {
    private static String startJobId = "";

    public static void main(String[] args) {

        final String usage = """

                Usage:    <bucket> <video> <topicArn> <roleArn>

                Where:
                   bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                   video - The name of video (for example, people.mp4).\s
                   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        NotificationChannel channel = NotificationChannel.builder()
                .snsTopicArn(topicArn)
                .roleArn(roleArn)
                .build();

        startModerationDetection(rekClient, channel, bucket, video);
        getModResults(rekClient);
        System.out.println("This example is done!");
        rekClient.close();
    }

    public static void startModerationDetection(RekognitionClient rekClient,
            NotificationChannel channel,
            String bucket,
            String video) {

        try {
            S3Object s3Obj = S3Object.builder()
                    .bucket(bucket)
                    .name(video)
                    .build();

            Video vidOb = Video.builder()
                    .s3Object(s3Obj)
                    .build();

            StartContentModerationRequest modDetectionRequest = StartContentModerationRequest.builder()
                    .jobTag("Moderation")
                    .notificationChannel(channel)
                    .video(vidOb)
                    .build();

            StartContentModerationResponse startModDetectionResult = rekClient
                    .startContentModeration(modDetectionRequest);
            startJobId = startModDetectionResult.jobId();

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void getModResults(RekognitionClient rekClient) {
        try {
            String paginationToken = null;
            GetContentModerationResponse modDetectionResponse = null;
            boolean finished = false;
            String status;
            int yy = 0;

            do {
                if (modDetectionResponse != null)
                    paginationToken = modDetectionResponse.nextToken();

                GetContentModerationRequest modRequest = GetContentModerationRequest.builder()
                        .jobId(startJobId)
                        .nextToken(paginationToken)
                        .maxResults(10)
                        .build();

                // Wait until the job succeeds.
                while (!finished) {
                    modDetectionResponse = rekClient.getContentModeration(modRequest);
                    status = modDetectionResponse.jobStatusAsString();

                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }

                finished = false;

                // Proceed when the job is done - otherwise VideoMetadata is null.
                VideoMetadata videoMetaData = modDetectionResponse.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());
                System.out.println("Job");

                List<ContentModerationDetection> mods = modDetectionResponse.moderationLabels();
                for (ContentModerationDetection mod : mods) {
                    long seconds = mod.timestamp() / 1000;
                    System.out.print("Mod label: " + seconds + " ");
                    System.out.println(mod.moderationLabel().toString());
                    System.out.println();
                }

            } while (modDetectionResponse != null && modDetectionResponse.nextToken() != null);

        } catch (RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
Amazon S3 バケットに保存されているビデオ内のテクニカルキューセグメントおよびショット検出セグメントを検出します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.S3Object;
import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
import software.amazon.awssdk.services.rekognition.model.Video;
import software.amazon.awssdk.services.rekognition.model.StartShotDetectionFilter;
import software.amazon.awssdk.services.rekognition.model.StartTechnicalCueDetectionFilter;
import software.amazon.awssdk.services.rekognition.model.StartSegmentDetectionFilters;
import software.amazon.awssdk.services.rekognition.model.StartSegmentDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.StartSegmentDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.GetSegmentDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.GetSegmentDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
import software.amazon.awssdk.services.rekognition.model.SegmentDetection;
import software.amazon.awssdk.services.rekognition.model.TechnicalCueSegment;
import software.amazon.awssdk.services.rekognition.model.ShotSegment;
import software.amazon.awssdk.services.rekognition.model.SegmentType;
import software.amazon.awssdk.services.sqs.SqsClient;
import java.util.List;

/**
 * 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 VideoDetectSegment {
    private static String startJobId = "";

    public static void main(String[] args) {
        final String usage = """

                Usage:    <bucket> <video> <topicArn> <roleArn>

                Where:
                   bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                   video - The name of video (for example, people.mp4).\s
                   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];

        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        SqsClient sqs = SqsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        NotificationChannel channel = NotificationChannel.builder()
                .snsTopicArn(topicArn)
                .roleArn(roleArn)
                .build();

        startSegmentDetection(rekClient, channel, bucket, video);
        getSegmentResults(rekClient);
        System.out.println("This example is done!");
        sqs.close();
        rekClient.close();
    }

    public static void startSegmentDetection(RekognitionClient rekClient,
            NotificationChannel channel,
            String bucket,
            String video) {
        try {
            S3Object s3Obj = S3Object.builder()
                    .bucket(bucket)
                    .name(video)
                    .build();

            Video vidOb = Video.builder()
                    .s3Object(s3Obj)
                    .build();

            StartShotDetectionFilter cueDetectionFilter = StartShotDetectionFilter.builder()
                    .minSegmentConfidence(60F)
                    .build();

            StartTechnicalCueDetectionFilter technicalCueDetectionFilter = StartTechnicalCueDetectionFilter.builder()
                    .minSegmentConfidence(60F)
                    .build();

            StartSegmentDetectionFilters filters = StartSegmentDetectionFilters.builder()
                    .shotFilter(cueDetectionFilter)
                    .technicalCueFilter(technicalCueDetectionFilter)
                    .build();

            StartSegmentDetectionRequest segDetectionRequest = StartSegmentDetectionRequest.builder()
                    .jobTag("DetectingLabels")
                    .notificationChannel(channel)
                    .segmentTypes(SegmentType.TECHNICAL_CUE, SegmentType.SHOT)
                    .video(vidOb)
                    .filters(filters)
                    .build();

            StartSegmentDetectionResponse segDetectionResponse = rekClient.startSegmentDetection(segDetectionRequest);
            startJobId = segDetectionResponse.jobId();

        } catch (RekognitionException e) {
            e.getMessage();
            System.exit(1);
        }
    }

    public static void getSegmentResults(RekognitionClient rekClient) {
        try {
            String paginationToken = null;
            GetSegmentDetectionResponse segDetectionResponse = null;
            boolean finished = false;
            String status;
            int yy = 0;

            do {
                if (segDetectionResponse != null)
                    paginationToken = segDetectionResponse.nextToken();

                GetSegmentDetectionRequest recognitionRequest = GetSegmentDetectionRequest.builder()
                        .jobId(startJobId)
                        .nextToken(paginationToken)
                        .maxResults(10)
                        .build();

                // Wait until the job succeeds.
                while (!finished) {
                    segDetectionResponse = rekClient.getSegmentDetection(recognitionRequest);
                    status = segDetectionResponse.jobStatusAsString();

                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }
                finished = false;

                // Proceed when the job is done - otherwise VideoMetadata is null.
                List<VideoMetadata> videoMetaData = segDetectionResponse.videoMetadata();
                for (VideoMetadata metaData : videoMetaData) {
                    System.out.println("Format: " + metaData.format());
                    System.out.println("Codec: " + metaData.codec());
                    System.out.println("Duration: " + metaData.durationMillis());
                    System.out.println("FrameRate: " + metaData.frameRate());
                    System.out.println("Job");
                }

                List<SegmentDetection> detectedSegments = segDetectionResponse.segments();
                for (SegmentDetection detectedSegment : detectedSegments) {
                    String type = detectedSegment.type().toString();
                    if (type.contains(SegmentType.TECHNICAL_CUE.toString())) {
                        System.out.println("Technical Cue");
                        TechnicalCueSegment segmentCue = detectedSegment.technicalCueSegment();
                        System.out.println("\tType: " + segmentCue.type());
                        System.out.println("\tConfidence: " + segmentCue.confidence().toString());
                    }

                    if (type.contains(SegmentType.SHOT.toString())) {
                        System.out.println("Shot");
                        ShotSegment segmentShot = detectedSegment.shotSegment();
                        System.out.println("\tIndex " + segmentShot.index());
                        System.out.println("\tConfidence: " + segmentShot.confidence().toString());
                    }

                    long seconds = detectedSegment.durationMillis();
                    System.out.println("\tDuration : " + seconds + " milliseconds");
                    System.out.println("\tStart time code: " + detectedSegment.startTimecodeSMPTE());
                    System.out.println("\tEnd time code: " + detectedSegment.endTimecodeSMPTE());
                    System.out.println("\tDuration time code: " + detectedSegment.durationSMPTE());
                    System.out.println();
                }

            } while (segDetectionResponse != null && segDetectionResponse.nextToken() != null);

        } catch (RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
Amazon S3 バケットに保存されたビデオに保存されたビデオ内のテキストを検出します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.S3Object;
import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
import software.amazon.awssdk.services.rekognition.model.Video;
import software.amazon.awssdk.services.rekognition.model.StartTextDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.StartTextDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.GetTextDetectionResponse;
import software.amazon.awssdk.services.rekognition.model.GetTextDetectionRequest;
import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
import software.amazon.awssdk.services.rekognition.model.TextDetectionResult;
import java.util.List;

/**
 * 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 VideoDetectText {
    private static String startJobId = "";

    public static void main(String[] args) {
        final String usage = """

                Usage:    <bucket> <video> <topicArn> <roleArn>

                Where:
                   bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                   video - The name of video (for example, people.mp4).\s
                   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];

        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        NotificationChannel channel = NotificationChannel.builder()
                .snsTopicArn(topicArn)
                .roleArn(roleArn)
                .build();

        startTextLabels(rekClient, channel, bucket, video);
        getTextResults(rekClient);
        System.out.println("This example is done!");
        rekClient.close();
    }

    public static void startTextLabels(RekognitionClient rekClient,
            NotificationChannel channel,
            String bucket,
            String video) {
        try {
            S3Object s3Obj = S3Object.builder()
                    .bucket(bucket)
                    .name(video)
                    .build();

            Video vidOb = Video.builder()
                    .s3Object(s3Obj)
                    .build();

            StartTextDetectionRequest labelDetectionRequest = StartTextDetectionRequest.builder()
                    .jobTag("DetectingLabels")
                    .notificationChannel(channel)
                    .video(vidOb)
                    .build();

            StartTextDetectionResponse labelDetectionResponse = rekClient.startTextDetection(labelDetectionRequest);
            startJobId = labelDetectionResponse.jobId();

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void getTextResults(RekognitionClient rekClient) {
        try {
            String paginationToken = null;
            GetTextDetectionResponse textDetectionResponse = null;
            boolean finished = false;
            String status;
            int yy = 0;

            do {
                if (textDetectionResponse != null)
                    paginationToken = textDetectionResponse.nextToken();

                GetTextDetectionRequest recognitionRequest = GetTextDetectionRequest.builder()
                        .jobId(startJobId)
                        .nextToken(paginationToken)
                        .maxResults(10)
                        .build();

                // Wait until the job succeeds.
                while (!finished) {
                    textDetectionResponse = rekClient.getTextDetection(recognitionRequest);
                    status = textDetectionResponse.jobStatusAsString();

                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }

                finished = false;

                // Proceed when the job is done - otherwise VideoMetadata is null.
                VideoMetadata videoMetaData = textDetectionResponse.videoMetadata();
                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());
                System.out.println("Job");

                List<TextDetectionResult> labels = textDetectionResponse.textDetections();
                for (TextDetectionResult detectedText : labels) {
                    System.out.println("Confidence: " + detectedText.textDetection().confidence().toString());
                    System.out.println("Id : " + detectedText.textDetection().id());
                    System.out.println("Parent Id: " + detectedText.textDetection().parentId());
                    System.out.println("Type: " + detectedText.textDetection().type());
                    System.out.println("Text: " + detectedText.textDetection().detectedText());
                    System.out.println();
                }

            } while (textDetectionResponse != null && textDetectionResponse.nextToken() != null);

        } catch (RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
Amazon S3 バケットに保存されたビデオに保存されたビデオ内の人物を検出します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.rekognition.RekognitionClient;
import software.amazon.awssdk.services.rekognition.model.S3Object;
import software.amazon.awssdk.services.rekognition.model.NotificationChannel;
import software.amazon.awssdk.services.rekognition.model.StartPersonTrackingRequest;
import software.amazon.awssdk.services.rekognition.model.Video;
import software.amazon.awssdk.services.rekognition.model.StartPersonTrackingResponse;
import software.amazon.awssdk.services.rekognition.model.RekognitionException;
import software.amazon.awssdk.services.rekognition.model.GetPersonTrackingResponse;
import software.amazon.awssdk.services.rekognition.model.GetPersonTrackingRequest;
import software.amazon.awssdk.services.rekognition.model.VideoMetadata;
import software.amazon.awssdk.services.rekognition.model.PersonDetection;
import java.util.List;

/**
 * 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 VideoPersonDetection {
    private static String startJobId = "";

    public static void main(String[] args) {

        final String usage = """

                Usage:    <bucket> <video> <topicArn> <roleArn>

                Where:
                   bucket - The name of the bucket in which the video is located (for example, (for example, myBucket).\s
                   video - The name of video (for example, people.mp4).\s
                   topicArn - The ARN of the Amazon Simple Notification Service (Amazon SNS) topic.\s
                   roleArn - The ARN of the AWS Identity and Access Management (IAM) role to use.\s
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucket = args[0];
        String video = args[1];
        String topicArn = args[2];
        String roleArn = args[3];
        Region region = Region.US_EAST_1;
        RekognitionClient rekClient = RekognitionClient.builder()
                .region(region)
                .build();

        NotificationChannel channel = NotificationChannel.builder()
                .snsTopicArn(topicArn)
                .roleArn(roleArn)
                .build();

        startPersonLabels(rekClient, channel, bucket, video);
        getPersonDetectionResults(rekClient);
        System.out.println("This example is done!");
        rekClient.close();
    }

    public static void startPersonLabels(RekognitionClient rekClient,
            NotificationChannel channel,
            String bucket,
            String video) {
        try {
            S3Object s3Obj = S3Object.builder()
                    .bucket(bucket)
                    .name(video)
                    .build();

            Video vidOb = Video.builder()
                    .s3Object(s3Obj)
                    .build();

            StartPersonTrackingRequest personTrackingRequest = StartPersonTrackingRequest.builder()
                    .jobTag("DetectingLabels")
                    .video(vidOb)
                    .notificationChannel(channel)
                    .build();

            StartPersonTrackingResponse labelDetectionResponse = rekClient.startPersonTracking(personTrackingRequest);
            startJobId = labelDetectionResponse.jobId();

        } catch (RekognitionException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void getPersonDetectionResults(RekognitionClient rekClient) {
        try {
            String paginationToken = null;
            GetPersonTrackingResponse personTrackingResult = null;
            boolean finished = false;
            String status;
            int yy = 0;

            do {
                if (personTrackingResult != null)
                    paginationToken = personTrackingResult.nextToken();

                GetPersonTrackingRequest recognitionRequest = GetPersonTrackingRequest.builder()
                        .jobId(startJobId)
                        .nextToken(paginationToken)
                        .maxResults(10)
                        .build();

                // Wait until the job succeeds
                while (!finished) {

                    personTrackingResult = rekClient.getPersonTracking(recognitionRequest);
                    status = personTrackingResult.jobStatusAsString();

                    if (status.compareTo("SUCCEEDED") == 0)
                        finished = true;
                    else {
                        System.out.println(yy + " status is: " + status);
                        Thread.sleep(1000);
                    }
                    yy++;
                }

                finished = false;

                // Proceed when the job is done - otherwise VideoMetadata is null.
                VideoMetadata videoMetaData = personTrackingResult.videoMetadata();

                System.out.println("Format: " + videoMetaData.format());
                System.out.println("Codec: " + videoMetaData.codec());
                System.out.println("Duration: " + videoMetaData.durationMillis());
                System.out.println("FrameRate: " + videoMetaData.frameRate());
                System.out.println("Job");

                List<PersonDetection> detectedPersons = personTrackingResult.persons();
                for (PersonDetection detectedPerson : detectedPersons) {
                    long seconds = detectedPerson.timestamp() / 1000;
                    System.out.print("Sec: " + seconds + " ");
                    System.out.println("Person Identifier: " + detectedPerson.person().index());
                    System.out.println();
                }

            } while (personTrackingResult != null && personTrackingResult.nextToken() != null);

        } catch (RekognitionException | InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [GetCelebrityRecognition](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/GetCelebrityRecognition)
  + [GetContentModeration](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/GetContentModeration)
  + [GetLabelDetection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/GetLabelDetection)
  + [GetPersonTracking](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/GetPersonTracking)
  + [GetSegmentDetection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/GetSegmentDetection)
  + [GetTextDetection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/GetTextDetection)
  + [StartCelebrityRecognition](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/StartCelebrityRecognition)
  + [StartContentModeration](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/StartContentModeration)
  + [StartLabelDetection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/StartLabelDetection)
  + [StartPersonTracking](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/StartPersonTracking)
  + [StartSegmentDetection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/StartSegmentDetection)
  + [StartTextDetection](https://docs.aws.amazon.com/goto/SdkForJavaV2/rekognition-2016-06-27/StartTextDetection)

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_java_2_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用して、Amazon Rekognition を使用し、　Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内でカテゴリ別にオブジェクトを識別するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_photo_analyzer_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_java_2_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用し、Amazon Simple Storage Service (Amazon S3) バケットにあるビデオ内で顔やオブジェクトを検出するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/video_analyzer_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

# SDK for Java 2.x を使用した Route 53 ドメイン登録のコード例
<a name="java_2_route-53-domains_code_examples"></a>

次のコード例は、Route 53 ドメイン登録 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### ハロー Route 53 ドメイン登録
<a name="route-53-domains_Hello_java_2_topic"></a>

次のコード例は、Route 53 ドメイン登録の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.route53domains.Route53DomainsClient;
import software.amazon.awssdk.services.route53.model.Route53Exception;
import software.amazon.awssdk.services.route53domains.model.DomainPrice;
import software.amazon.awssdk.services.route53domains.model.ListPricesRequest;
import software.amazon.awssdk.services.route53domains.model.ListPricesResponse;
import java.util.List;

/**
 * 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
 *
 * This Java code examples performs the following operation:
 *
 * 1. Invokes ListPrices for at least one domain type, such as the “com” type
 * and displays the prices for Registration and Renewal.
 *
 */
public class HelloRoute53 {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) {
        final String usage = "\n" +
                "Usage:\n" +
                "    <hostedZoneId> \n\n" +
                "Where:\n" +
                "    hostedZoneId - The id value of an existing hosted zone. \n";

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String domainType = args[0];
        Region region = Region.US_EAST_1;
        Route53DomainsClient route53DomainsClient = Route53DomainsClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Invokes ListPrices for at least one domain type.");
        listPrices(route53DomainsClient, domainType);
        System.out.println(DASHES);
    }

    public static void listPrices(Route53DomainsClient route53DomainsClient, String domainType) {
        try {
            ListPricesRequest pricesRequest = ListPricesRequest.builder()
                    .maxItems(10)
                    .tld(domainType)
                    .build();

            ListPricesResponse response = route53DomainsClient.listPrices(pricesRequest);
            List<DomainPrice> prices = response.prices();
            for (DomainPrice pr : prices) {
                System.out.println("Name: " + pr.name());
                System.out.println(
                        "Registration: " + pr.registrationPrice().price() + " " + pr.registrationPrice().currency());
                System.out.println("Renewal: " + pr.renewalPrice().price() + " " + pr.renewalPrice().currency());
                System.out.println("Transfer: " + pr.transferPrice().price() + " " + pr.transferPrice().currency());
                System.out.println("Transfer: " + pr.transferPrice().price() + " " + pr.transferPrice().currency());
                System.out.println("Change Ownership: " + pr.changeOwnershipPrice().price() + " "
                        + pr.changeOwnershipPrice().currency());
                System.out.println(
                        "Restoration: " + pr.restorationPrice().price() + " " + pr.restorationPrice().currency());
                System.out.println(" ");
            }

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListPrices](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ListPrices)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="route-53-domains_Scenario_GetStartedRoute53Domains_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 現在のドメインを一覧表示し、過去 1 年間の操作を一覧表示します。
+ 過去 1 年間の請求記録とドメインタイプの価格を表示します。
+ ドメインの候補を取得します。
+ ドメインの可用性と移管可能性を確認します。
+ オプションで、ドメイン登録をリクエストします。
+ 操作の詳細を入手します。
+ オプションで、ドメインの詳細を取得します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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
 *
 * This example uses pagination methods where applicable. For example, to list
 * domains, the
 * listDomainsPaginator method is used. For more information about pagination,
 * see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/pagination.html
 *
 * This Java code example performs the following operations:
 *
 * 1. List current domains.
 * 2. List operations in the past year.
 * 3. View billing for the account in the past year.
 * 4. View prices for domain types.
 * 5. Get domain suggestions.
 * 6. Check domain availability.
 * 7. Check domain transferability.
 * 8. Request a domain registration.
 * 9. Get operation details.
 * 10. Optionally, get domain details.
 */

public class Route53Scenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <domainType> <phoneNumber> <email> <domainSuggestion> <firstName> <lastName> <city>

                Where:
                    domainType - The domain type (for example, com).\s
                    phoneNumber - The phone number to use (for example, +91.9966564xxx)      email - The email address to use.      domainSuggestion - The domain suggestion (for example, findmy.accountants).\s
                    firstName - The first name to use to register a domain.\s
                    lastName -  The last name to use to register a domain.\s
                    city - the city to use to register a domain.\s
                    """;

        if (args.length != 7) {
            System.out.println(usage);
            System.exit(1);
        }

        String domainType = args[0];
        String phoneNumber = args[1];
        String email = args[2];
        String domainSuggestion = args[3];
        String firstName = args[4];
        String lastName = args[5];
        String city = args[6];
        Region region = Region.US_EAST_1;
        Route53DomainsClient route53DomainsClient = Route53DomainsClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon Route 53 domains example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. List current domains.");
        listDomains(route53DomainsClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. List operations in the past year.");
        listOperations(route53DomainsClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. View billing for the account in the past year.");
        listBillingRecords(route53DomainsClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. View prices for domain types.");
        listPrices(route53DomainsClient, domainType);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Get domain suggestions.");
        listDomainSuggestions(route53DomainsClient, domainSuggestion);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Check domain availability.");
        checkDomainAvailability(route53DomainsClient, domainSuggestion);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Check domain transferability.");
        checkDomainTransferability(route53DomainsClient, domainSuggestion);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Request a domain registration.");
        String opId = requestDomainRegistration(route53DomainsClient, domainSuggestion, phoneNumber, email, firstName,
                lastName, city);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. Get operation details.");
        getOperationalDetail(route53DomainsClient, opId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Get domain details.");
        System.out.println("Note: You must have a registered domain to get details.");
        System.out.println("Otherwise, an exception is thrown that states ");
        System.out.println("Domain xxxxxxx not found in xxxxxxx account.");
        getDomainDetails(route53DomainsClient, domainSuggestion);
        System.out.println(DASHES);
    }

    public static void getDomainDetails(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            GetDomainDetailRequest detailRequest = GetDomainDetailRequest.builder()
                    .domainName(domainSuggestion)
                    .build();

            GetDomainDetailResponse response = route53DomainsClient.getDomainDetail(detailRequest);
            System.out.println("The contact first name is " + response.registrantContact().firstName());
            System.out.println("The contact last name is " + response.registrantContact().lastName());
            System.out.println("The contact org name is " + response.registrantContact().organizationName());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void getOperationalDetail(Route53DomainsClient route53DomainsClient, String operationId) {
        try {
            GetOperationDetailRequest detailRequest = GetOperationDetailRequest.builder()
                    .operationId(operationId)
                    .build();

            GetOperationDetailResponse response = route53DomainsClient.getOperationDetail(detailRequest);
            System.out.println("Operation detail message is " + response.message());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static String requestDomainRegistration(Route53DomainsClient route53DomainsClient,
            String domainSuggestion,
            String phoneNumber,
            String email,
            String firstName,
            String lastName,
            String city) {

        try {
            ContactDetail contactDetail = ContactDetail.builder()
                    .contactType(ContactType.COMPANY)
                    .state("LA")
                    .countryCode(CountryCode.IN)
                    .email(email)
                    .firstName(firstName)
                    .lastName(lastName)
                    .city(city)
                    .phoneNumber(phoneNumber)
                    .organizationName("My Org")
                    .addressLine1("My Address")
                    .zipCode("123 123")
                    .build();

            RegisterDomainRequest domainRequest = RegisterDomainRequest.builder()
                    .adminContact(contactDetail)
                    .registrantContact(contactDetail)
                    .techContact(contactDetail)
                    .domainName(domainSuggestion)
                    .autoRenew(true)
                    .durationInYears(1)
                    .build();

            RegisterDomainResponse response = route53DomainsClient.registerDomain(domainRequest);
            System.out.println("Registration requested. Operation Id: " + response.operationId());
            return response.operationId();

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }

    public static void checkDomainTransferability(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            CheckDomainTransferabilityRequest transferabilityRequest = CheckDomainTransferabilityRequest.builder()
                    .domainName(domainSuggestion)
                    .build();

            CheckDomainTransferabilityResponse response = route53DomainsClient
                    .checkDomainTransferability(transferabilityRequest);
            System.out.println("Transferability: " + response.transferability().transferable().toString());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void checkDomainAvailability(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            CheckDomainAvailabilityRequest availabilityRequest = CheckDomainAvailabilityRequest.builder()
                    .domainName(domainSuggestion)
                    .build();

            CheckDomainAvailabilityResponse response = route53DomainsClient
                    .checkDomainAvailability(availabilityRequest);
            System.out.println(domainSuggestion + " is " + response.availability().toString());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void listDomainSuggestions(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            GetDomainSuggestionsRequest suggestionsRequest = GetDomainSuggestionsRequest.builder()
                    .domainName(domainSuggestion)
                    .suggestionCount(5)
                    .onlyAvailable(true)
                    .build();

            GetDomainSuggestionsResponse response = route53DomainsClient.getDomainSuggestions(suggestionsRequest);
            List<DomainSuggestion> suggestions = response.suggestionsList();
            for (DomainSuggestion suggestion : suggestions) {
                System.out.println("Suggestion Name: " + suggestion.domainName());
                System.out.println("Availability: " + suggestion.availability());
                System.out.println(" ");
            }

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void listPrices(Route53DomainsClient route53DomainsClient, String domainType) {
        try {
            ListPricesRequest pricesRequest = ListPricesRequest.builder()
                    .tld(domainType)
                    .build();

            ListPricesIterable listRes = route53DomainsClient.listPricesPaginator(pricesRequest);
            listRes.stream()
                    .flatMap(r -> r.prices().stream())
                    .forEach(content -> System.out.println(" Name: " + content.name() +
                            " Registration: " + content.registrationPrice().price() + " "
                            + content.registrationPrice().currency() +
                            " Renewal: " + content.renewalPrice().price() + " " + content.renewalPrice().currency()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void listBillingRecords(Route53DomainsClient route53DomainsClient) {
        try {
            Date currentDate = new Date();
            LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            ZoneOffset zoneOffset = ZoneOffset.of("+01:00");
            LocalDateTime localDateTime2 = localDateTime.minusYears(1);
            Instant myStartTime = localDateTime2.toInstant(zoneOffset);
            Instant myEndTime = localDateTime.toInstant(zoneOffset);

            ViewBillingRequest viewBillingRequest = ViewBillingRequest.builder()
                    .start(myStartTime)
                    .end(myEndTime)
                    .build();

            ViewBillingIterable listRes = route53DomainsClient.viewBillingPaginator(viewBillingRequest);
            listRes.stream()
                    .flatMap(r -> r.billingRecords().stream())
                    .forEach(content -> System.out.println(" Bill Date:: " + content.billDate() +
                            " Operation: " + content.operationAsString() +
                            " Price: " + content.price()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void listOperations(Route53DomainsClient route53DomainsClient) {
        try {
            Date currentDate = new Date();
            LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            ZoneOffset zoneOffset = ZoneOffset.of("+01:00");
            localDateTime = localDateTime.minusYears(1);
            Instant myTime = localDateTime.toInstant(zoneOffset);

            ListOperationsRequest operationsRequest = ListOperationsRequest.builder()
                    .submittedSince(myTime)
                    .build();

            ListOperationsIterable listRes = route53DomainsClient.listOperationsPaginator(operationsRequest);
            listRes.stream()
                    .flatMap(r -> r.operations().stream())
                    .forEach(content -> System.out.println(" Operation Id: " + content.operationId() +
                            " Status: " + content.statusAsString() +
                            " Date: " + content.submittedDate()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void listDomains(Route53DomainsClient route53DomainsClient) {
        try {
            ListDomainsIterable listRes = route53DomainsClient.listDomainsPaginator();
            listRes.stream()
                    .flatMap(r -> r.domains().stream())
                    .forEach(content -> System.out.println("The domain name is " + content.domainName()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CheckDomainAvailability](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/CheckDomainAvailability)
  + [CheckDomainTransferability](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/CheckDomainTransferability)
  + [GetDomainDetail](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/GetDomainDetail)
  + [GetDomainSuggestions](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/GetDomainSuggestions)
  + [GetOperationDetail](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/GetOperationDetail)
  + [ListDomains](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ListDomains)
  + [ListOperations](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ListOperations)
  + [ListPrices](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ListPrices)
  + [RegisterDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/RegisterDomain)
  + [ViewBilling](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ViewBilling)

## アクション
<a name="actions"></a>

### `CheckDomainAvailability`
<a name="route-53-domains_CheckDomainAvailability_java_2_topic"></a>

次のコード例は、`CheckDomainAvailability` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void checkDomainAvailability(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            CheckDomainAvailabilityRequest availabilityRequest = CheckDomainAvailabilityRequest.builder()
                    .domainName(domainSuggestion)
                    .build();

            CheckDomainAvailabilityResponse response = route53DomainsClient
                    .checkDomainAvailability(availabilityRequest);
            System.out.println(domainSuggestion + " is " + response.availability().toString());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[CheckDomainAvailability](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/CheckDomainAvailability)」を参照してください。

### `CheckDomainTransferability`
<a name="route-53-domains_CheckDomainTransferability_java_2_topic"></a>

次のコード例は、`CheckDomainTransferability` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void checkDomainTransferability(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            CheckDomainTransferabilityRequest transferabilityRequest = CheckDomainTransferabilityRequest.builder()
                    .domainName(domainSuggestion)
                    .build();

            CheckDomainTransferabilityResponse response = route53DomainsClient
                    .checkDomainTransferability(transferabilityRequest);
            System.out.println("Transferability: " + response.transferability().transferable().toString());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[CheckDomainTransferability](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/CheckDomainTransferability)」を参照してください。

### `GetDomainDetail`
<a name="route-53-domains_GetDomainDetail_java_2_topic"></a>

次のコード例は、`GetDomainDetail` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void getDomainDetails(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            GetDomainDetailRequest detailRequest = GetDomainDetailRequest.builder()
                    .domainName(domainSuggestion)
                    .build();

            GetDomainDetailResponse response = route53DomainsClient.getDomainDetail(detailRequest);
            System.out.println("The contact first name is " + response.registrantContact().firstName());
            System.out.println("The contact last name is " + response.registrantContact().lastName());
            System.out.println("The contact org name is " + response.registrantContact().organizationName());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetDomainDetail](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/GetDomainDetail)」を参照してください。

### `GetDomainSuggestions`
<a name="route-53-domains_GetDomainSuggestions_java_2_topic"></a>

次のコード例は、`GetDomainSuggestions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void listDomainSuggestions(Route53DomainsClient route53DomainsClient, String domainSuggestion) {
        try {
            GetDomainSuggestionsRequest suggestionsRequest = GetDomainSuggestionsRequest.builder()
                    .domainName(domainSuggestion)
                    .suggestionCount(5)
                    .onlyAvailable(true)
                    .build();

            GetDomainSuggestionsResponse response = route53DomainsClient.getDomainSuggestions(suggestionsRequest);
            List<DomainSuggestion> suggestions = response.suggestionsList();
            for (DomainSuggestion suggestion : suggestions) {
                System.out.println("Suggestion Name: " + suggestion.domainName());
                System.out.println("Availability: " + suggestion.availability());
                System.out.println(" ");
            }

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetDomainSuggestions](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/GetDomainSuggestions)」を参照してください。

### `GetOperationDetail`
<a name="route-53-domains_GetOperationDetail_java_2_topic"></a>

次のコード例は、`GetOperationDetail` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void getOperationalDetail(Route53DomainsClient route53DomainsClient, String operationId) {
        try {
            GetOperationDetailRequest detailRequest = GetOperationDetailRequest.builder()
                    .operationId(operationId)
                    .build();

            GetOperationDetailResponse response = route53DomainsClient.getOperationDetail(detailRequest);
            System.out.println("Operation detail message is " + response.message());

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[GetOperationDetail](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/GetOperationDetail)」を参照してください。

### `ListDomains`
<a name="route-53-domains_ListDomains_java_2_topic"></a>

次のコード例は、`ListDomains` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void listDomains(Route53DomainsClient route53DomainsClient) {
        try {
            ListDomainsIterable listRes = route53DomainsClient.listDomainsPaginator();
            listRes.stream()
                    .flatMap(r -> r.domains().stream())
                    .forEach(content -> System.out.println("The domain name is " + content.domainName()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListDomains](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ListDomains)」を参照してください。

### `ListOperations`
<a name="route-53-domains_ListOperations_java_2_topic"></a>

次のコード例は、`ListOperations` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void listOperations(Route53DomainsClient route53DomainsClient) {
        try {
            Date currentDate = new Date();
            LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            ZoneOffset zoneOffset = ZoneOffset.of("+01:00");
            localDateTime = localDateTime.minusYears(1);
            Instant myTime = localDateTime.toInstant(zoneOffset);

            ListOperationsRequest operationsRequest = ListOperationsRequest.builder()
                    .submittedSince(myTime)
                    .build();

            ListOperationsIterable listRes = route53DomainsClient.listOperationsPaginator(operationsRequest);
            listRes.stream()
                    .flatMap(r -> r.operations().stream())
                    .forEach(content -> System.out.println(" Operation Id: " + content.operationId() +
                            " Status: " + content.statusAsString() +
                            " Date: " + content.submittedDate()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListOperations](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ListOperations)」を参照してください。

### `ListPrices`
<a name="route-53-domains_ListPrices_java_2_topic"></a>

次のコード例は、`ListPrices` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void listPrices(Route53DomainsClient route53DomainsClient, String domainType) {
        try {
            ListPricesRequest pricesRequest = ListPricesRequest.builder()
                    .tld(domainType)
                    .build();

            ListPricesIterable listRes = route53DomainsClient.listPricesPaginator(pricesRequest);
            listRes.stream()
                    .flatMap(r -> r.prices().stream())
                    .forEach(content -> System.out.println(" Name: " + content.name() +
                            " Registration: " + content.registrationPrice().price() + " "
                            + content.registrationPrice().currency() +
                            " Renewal: " + content.renewalPrice().price() + " " + content.renewalPrice().currency()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListPrices](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ListPrices)」を参照してください。

### `RegisterDomain`
<a name="route-53-domains_RegisterDomain_java_2_topic"></a>

次のコード例は、`RegisterDomain` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static String requestDomainRegistration(Route53DomainsClient route53DomainsClient,
            String domainSuggestion,
            String phoneNumber,
            String email,
            String firstName,
            String lastName,
            String city) {

        try {
            ContactDetail contactDetail = ContactDetail.builder()
                    .contactType(ContactType.COMPANY)
                    .state("LA")
                    .countryCode(CountryCode.IN)
                    .email(email)
                    .firstName(firstName)
                    .lastName(lastName)
                    .city(city)
                    .phoneNumber(phoneNumber)
                    .organizationName("My Org")
                    .addressLine1("My Address")
                    .zipCode("123 123")
                    .build();

            RegisterDomainRequest domainRequest = RegisterDomainRequest.builder()
                    .adminContact(contactDetail)
                    .registrantContact(contactDetail)
                    .techContact(contactDetail)
                    .domainName(domainSuggestion)
                    .autoRenew(true)
                    .durationInYears(1)
                    .build();

            RegisterDomainResponse response = route53DomainsClient.registerDomain(domainRequest);
            System.out.println("Registration requested. Operation Id: " + response.operationId());
            return response.operationId();

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[RegisterDomain](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/RegisterDomain)」を参照してください。

### `ViewBilling`
<a name="route-53-domains_ViewBilling_java_2_topic"></a>

次のコード例は、`ViewBilling` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/route53#code-examples)での設定と実行の方法を確認してください。

```
    public static void listBillingRecords(Route53DomainsClient route53DomainsClient) {
        try {
            Date currentDate = new Date();
            LocalDateTime localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            ZoneOffset zoneOffset = ZoneOffset.of("+01:00");
            LocalDateTime localDateTime2 = localDateTime.minusYears(1);
            Instant myStartTime = localDateTime2.toInstant(zoneOffset);
            Instant myEndTime = localDateTime.toInstant(zoneOffset);

            ViewBillingRequest viewBillingRequest = ViewBillingRequest.builder()
                    .start(myStartTime)
                    .end(myEndTime)
                    .build();

            ViewBillingIterable listRes = route53DomainsClient.viewBillingPaginator(viewBillingRequest);
            listRes.stream()
                    .flatMap(r -> r.billingRecords().stream())
                    .forEach(content -> System.out.println(" Bill Date:: " + content.billDate() +
                            " Operation: " + content.operationAsString() +
                            " Price: " + content.price()));

        } catch (Route53Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ViewBilling](https://docs.aws.amazon.com/goto/SdkForJavaV2/route53domains-2014-05-15/ViewBilling)」を参照してください。

# SDK for Java 2.x を使用する Amazon S3 の例
<a name="java_2_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_java_2_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Bucket;
import software.amazon.awssdk.services.s3.model.ListBucketsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class HelloS3 {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        listBuckets(s3);
    }

    /**
     * Lists all the S3 buckets associated with the provided AWS S3 client.
     *
     * @param s3 the S3Client instance used to interact with the AWS S3 service
     */
    public static void listBuckets(S3Client s3) {
        try {
            ListBucketsResponse response = s3.listBuckets();
            List<Bucket> bucketList = response.buckets();
            bucketList.forEach(bucket -> {
                System.out.println("Bucket Name: " + bucket.name());
            });

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListBuckets)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
シナリオ例。  

```
import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

/**
 * 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
 *
 * This Java code example performs the following tasks:
 *
 * 1. Creates an Amazon S3 bucket.
 * 2. Uploads an object to the bucket.
 * 3. Downloads the object to another local file.
 * 4. Uploads an object using multipart upload.
 * 5. List all objects located in the Amazon S3 bucket.
 * 6. Copies the object to another Amazon S3 bucket.
 * 7. Copy the object to another Amazon S3 bucket using multi copy.
 * 8. Deletes the object from the Amazon S3 bucket.
 * 9. Deletes the Amazon S3 bucket.
 */

public class S3Scenario {

    public static Scanner scanner = new Scanner(System.in);
    static S3Actions s3Actions = new S3Actions();
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final Logger logger = LoggerFactory.getLogger(S3Scenario.class);
    public static void main(String[] args) throws IOException {
        final String usage = """
            Usage:
               <bucketName> <key> <objectPath> <savePath> <toBucket>

            Where:
                bucketName - The name of the  S3 bucket.
                key - The unique identifier for the object stored in the S3 bucket.
                objectPath - The full file path of the object within the S3 bucket (e.g., "documents/reports/annual_report.pdf").
                savePath - The local file path where the object will be downloaded and saved (e.g., "C:/Users/username/Downloads/annual_report.pdf").
                toBucket - The name of the S3 bucket to which the object will be copied.
            """;

        if (args.length != 5) {
            logger.info(usage);
            return;
        }

        String bucketName = args[0];
        String key = args[1];
        String objectPath = args[2];
        String savePath = args[3];
        String toBucket = args[4];

        logger.info(DASHES);
        logger.info("Welcome to the Amazon Simple Storage Service (S3) example scenario.");
        logger.info("""
            Amazon S3 is a highly scalable and durable object storage 
            service provided by Amazon Web Services (AWS). It is designed to store and retrieve 
            any amount of data, from anywhere on the web, at any time.
                        
            The `S3AsyncClient` interface in the AWS SDK for Java 2.x provides a set of methods to 
            programmatically interact with the Amazon S3 (Simple Storage Service) service. This allows 
            developers to automate the management and manipulation of S3 buckets and objects as 
            part of their application deployment pipelines. With S3, teams can focus on building 
            and deploying their applications without having to worry about the underlying storage 
            infrastructure required to host and manage large amounts of data.
                        
            This scenario walks you through how to perform key operations for this service.  
            Let's get started...
            """);
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        try {
            // Run the methods that belong to this scenario.
            runScenario(bucketName, key, objectPath, savePath, toBucket);

        } catch (Throwable rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception kmsEx) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", kmsEx.getMessage(), kmsEx.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
        }
    }

    private static void runScenario(String bucketName, String key, String objectPath, String savePath, String toBucket) throws Throwable {
        logger.info(DASHES);
        logger.info("1. Create an Amazon S3 bucket.");
        try {
            CompletableFuture<Void> future = s3Actions.createBucketAsync(bucketName);
            future.join();
            waitForInputToContinue(scanner);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;

        }
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("2. Upload a local file to the Amazon S3 bucket.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<PutObjectResponse> future = s3Actions.uploadLocalFileAsync(bucketName, key, objectPath);
            future.join();
            logger.info("File uploaded successfully to {}/{}", bucketName, key);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);


        logger.info(DASHES);
        logger.info("3. Download the object to another local file.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = s3Actions.getObjectBytesAsync(bucketName, key, savePath);
            future.join();
            logger.info("Successfully obtained bytes from S3 object and wrote to file {}", savePath);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("4. Perform a multipart upload.");
        waitForInputToContinue(scanner);
        String multipartKey = "multiPartKey";
        try {
            // Call the multipartUpload method
            CompletableFuture<Void> future = s3Actions.multipartUpload(bucketName, multipartKey);
            future.join();
            logger.info("Multipart upload completed successfully for bucket '{}' and key '{}'", bucketName, multipartKey);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("5. List all objects located in the Amazon S3 bucket.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = s3Actions.listAllObjectsAsync(bucketName);
            future.join();
            logger.info("Object listing completed successfully.");

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("6. Copy the object to another Amazon S3 bucket.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<String> future = s3Actions.copyBucketObjectAsync(bucketName, key, toBucket);
            String result = future.join();
            logger.info("Copy operation result: {}", result);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("7. Copy the object to another Amazon S3 bucket using multi copy.");
        waitForInputToContinue(scanner);

        try {
            CompletableFuture<String> future = s3Actions.performMultiCopy(toBucket, bucketName, key);
            String result = future.join();
            logger.info("Copy operation result: {}", result);

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("KMS error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);


        logger.info(DASHES);
        logger.info("8. Delete objects from the Amazon S3 bucket.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = s3Actions.deleteObjectFromBucketAsync(bucketName, key);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        try {
            CompletableFuture<Void> future = s3Actions.deleteObjectFromBucketAsync(bucketName, "multiPartKey");
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("9. Delete the Amazon S3 bucket.");
        waitForInputToContinue(scanner);
        try {
            CompletableFuture<Void> future = s3Actions.deleteBucketAsync(bucketName);
            future.join();

        } catch (RuntimeException rt) {
            Throwable cause = rt.getCause();
            if (cause instanceof S3Exception s3Ex) {
                logger.info("S3 error occurred: Error message: {}, Error code {}", s3Ex.getMessage(), s3Ex.awsErrorDetails().errorCode());
            } else {
                logger.info("An unexpected error occurred: " + rt.getMessage());
            }
            throw cause;
        }
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        logger.info(DASHES);
        logger.info("You successfully completed the Amazon S3 scenario.");
        logger.info(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                // Handle invalid input.
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
オペレーションを含むラッパークラス。  

```
public class S3Actions {

    private static final Logger logger = LoggerFactory.getLogger(S3Actions.class);
    private static S3AsyncClient s3AsyncClient;

    public static S3AsyncClient getAsyncClient() {
        if (s3AsyncClient == null) {
            /*
            The `NettyNioAsyncHttpClient` class is part of the AWS SDK for Java, version 2,
            and it is designed to provide a high-performance, asynchronous HTTP client for interacting with AWS services.
             It uses the Netty framework to handle the underlying network communication and the Java NIO API to
             provide a non-blocking, event-driven approach to HTTP requests and responses.
             */

            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(50)  // Adjust as needed.
                .connectionTimeout(Duration.ofSeconds(60))  // Set the connection timeout.
                .readTimeout(Duration.ofSeconds(60))  // Set the read timeout.
                .writeTimeout(Duration.ofSeconds(60))  // Set the write timeout.
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))  // Set the overall API call timeout.
                .apiCallAttemptTimeout(Duration.ofSeconds(90))  // Set the individual call attempt timeout.
                .retryStrategy(RetryMode.STANDARD)
                .build();

            s3AsyncClient = S3AsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return s3AsyncClient;
    }


    /**
     * Creates an S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to create
     * @return a {@link CompletableFuture} that completes when the bucket is created and ready
     * @throws RuntimeException if there is a failure while creating the bucket
     */
    public CompletableFuture<Void> createBucketAsync(String bucketName) {
        CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
            .bucket(bucketName)
            .build();

        CompletableFuture<CreateBucketResponse> response = getAsyncClient().createBucket(bucketRequest);
        return response.thenCompose(resp -> {
            S3AsyncWaiter s3Waiter = getAsyncClient().waiter();
            HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder()
                .bucket(bucketName)
                .build();

            CompletableFuture<WaiterResponse<HeadBucketResponse>> waiterResponseFuture =
                s3Waiter.waitUntilBucketExists(bucketRequestWait);
            return waiterResponseFuture.thenAccept(waiterResponse -> {
                waiterResponse.matched().response().ifPresent(headBucketResponse -> {
                    logger.info(bucketName + " is ready");
                });
            });
        }).whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to create bucket", ex);
            }
        });
    }


    /**
     * Uploads a local file to an AWS S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to upload the file to
     * @param key        the key (object name) to use for the uploaded file
     * @param objectPath the local file path of the file to be uploaded
     * @return a {@link CompletableFuture} that completes with the {@link PutObjectResponse} when the upload is successful, or throws a {@link RuntimeException} if the upload fails
     */
    public CompletableFuture<PutObjectResponse> uploadLocalFileAsync(String bucketName, String key, String objectPath) {
        PutObjectRequest objectRequest = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

        CompletableFuture<PutObjectResponse> response = getAsyncClient().putObject(objectRequest, AsyncRequestBody.fromFile(Paths.get(objectPath)));
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to upload file", ex);
            }
        });
    }


    /**
     * Asynchronously retrieves the bytes of an object from an Amazon S3 bucket and writes them to a local file.
     *
     * @param bucketName the name of the S3 bucket containing the object
     * @param keyName    the key (or name) of the S3 object to retrieve
     * @param path       the local file path where the object's bytes will be written
     * @return a {@link CompletableFuture} that completes when the object bytes have been written to the local file
     */
    public CompletableFuture<Void> getObjectBytesAsync(String bucketName, String keyName, String path) {
        GetObjectRequest objectRequest = GetObjectRequest.builder()
            .key(keyName)
            .bucket(bucketName)
            .build();

        CompletableFuture<ResponseBytes<GetObjectResponse>> response = getAsyncClient().getObject(objectRequest, AsyncResponseTransformer.toBytes());
        return response.thenAccept(objectBytes -> {
            try {
                byte[] data = objectBytes.asByteArray();
                Path filePath = Paths.get(path);
                Files.write(filePath, data);
                logger.info("Successfully obtained bytes from an S3 object");
            } catch (IOException ex) {
                throw new RuntimeException("Failed to write data to file", ex);
            }
        }).whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to get object bytes from S3", ex);
            }
        });
    }


    /**
     * Asynchronously lists all objects in the specified S3 bucket.
     *
     * @param bucketName the name of the S3 bucket to list objects for
     * @return a {@link CompletableFuture} that completes when all objects have been listed
     */
    public CompletableFuture<Void> listAllObjectsAsync(String bucketName) {
        ListObjectsV2Request initialRequest = ListObjectsV2Request.builder()
            .bucket(bucketName)
            .maxKeys(1)
            .build();

        ListObjectsV2Publisher paginator = getAsyncClient().listObjectsV2Paginator(initialRequest);
        return paginator.subscribe(response -> {
            response.contents().forEach(s3Object -> {
                logger.info("Object key: " + s3Object.key());
            });
        }).thenRun(() -> {
            logger.info("Successfully listed all objects in the bucket: " + bucketName);
        }).exceptionally(ex -> {
            throw new RuntimeException("Failed to list objects", ex);
        });
    }


    /**
     * Asynchronously copies an object from one S3 bucket to another.
     *
     * @param fromBucket the name of the source S3 bucket
     * @param objectKey  the key (name) of the object to be copied
     * @param toBucket   the name of the destination S3 bucket
     * @return a {@link CompletableFuture} that completes with the copy result as a {@link String}
     * @throws RuntimeException if the URL could not be encoded or an S3 exception occurred during the copy
     */
    public CompletableFuture<String> copyBucketObjectAsync(String fromBucket, String objectKey, String toBucket) {
        CopyObjectRequest copyReq = CopyObjectRequest.builder()
            .sourceBucket(fromBucket)
            .sourceKey(objectKey)
            .destinationBucket(toBucket)
            .destinationKey(objectKey)
            .build();

        CompletableFuture<CopyObjectResponse> response = getAsyncClient().copyObject(copyReq);
        response.whenComplete((copyRes, ex) -> {
            if (copyRes != null) {
                logger.info("The " + objectKey + " was copied to " + toBucket);
            } else {
                throw new RuntimeException("An S3 exception occurred during copy", ex);
            }
        });

        return response.thenApply(CopyObjectResponse::copyObjectResult)
            .thenApply(Object::toString);
    }

    /**
     * Performs a multipart upload to an Amazon S3 bucket.
     *
     * @param bucketName the name of the S3 bucket to upload the file to
     * @param key        the key (name) of the file to be uploaded
     * @return a {@link CompletableFuture} that completes when the multipart upload is successful
     */
    public CompletableFuture<Void> multipartUpload(String bucketName, String key) {
        int mB = 1024 * 1024;

        CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

        return getAsyncClient().createMultipartUpload(createMultipartUploadRequest)
            .thenCompose(createResponse -> {
                String uploadId = createResponse.uploadId();
                System.out.println("Upload ID: " + uploadId);

                // Upload part 1.
                UploadPartRequest uploadPartRequest1 = UploadPartRequest.builder()
                    .bucket(bucketName)
                    .key(key)
                    .uploadId(uploadId)
                    .partNumber(1)
                    .contentLength((long) (5 * mB)) // Specify the content length
                    .build();

                CompletableFuture<CompletedPart> part1Future = getAsyncClient().uploadPart(uploadPartRequest1,
                        AsyncRequestBody.fromByteBuffer(getRandomByteBuffer(5 * mB)))
                    .thenApply(uploadPartResponse -> CompletedPart.builder()
                        .partNumber(1)
                        .eTag(uploadPartResponse.eTag())
                        .build());

                // Upload part 2.
                UploadPartRequest uploadPartRequest2 = UploadPartRequest.builder()
                    .bucket(bucketName)
                    .key(key)
                    .uploadId(uploadId)
                    .partNumber(2)
                    .contentLength((long) (3 * mB))
                    .build();

                CompletableFuture<CompletedPart> part2Future = getAsyncClient().uploadPart(uploadPartRequest2,
                        AsyncRequestBody.fromByteBuffer(getRandomByteBuffer(3 * mB)))
                    .thenApply(uploadPartResponse -> CompletedPart.builder()
                        .partNumber(2)
                        .eTag(uploadPartResponse.eTag())
                        .build());

                // Combine the results of both parts.
                return CompletableFuture.allOf(part1Future, part2Future)
                    .thenCompose(v -> {
                        CompletedPart part1 = part1Future.join();
                        CompletedPart part2 = part2Future.join();

                        CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder()
                            .parts(part1, part2)
                            .build();

                        CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder()
                            .bucket(bucketName)
                            .key(key)
                            .uploadId(uploadId)
                            .multipartUpload(completedMultipartUpload)
                            .build();

                        // Complete the multipart upload
                        return getAsyncClient().completeMultipartUpload(completeMultipartUploadRequest);
                    });
            })
            .thenAccept(response -> System.out.println("Multipart upload completed successfully"))
            .exceptionally(ex -> {
                System.err.println("Failed to complete multipart upload: " + ex.getMessage());
                throw new RuntimeException(ex);
            });
    }


    /**
     * Deletes an object from an S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket
     * @param key        the key (file name) of the object to be deleted
     * @return a {@link CompletableFuture} that completes when the object has been deleted
     */
    public CompletableFuture<Void> deleteObjectFromBucketAsync(String bucketName, String key) {
        DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

        CompletableFuture<DeleteObjectResponse> response = getAsyncClient().deleteObject(deleteObjectRequest);
        response.whenComplete((deleteRes, ex) -> {
            if (deleteRes != null) {
                logger.info(key + " was deleted");
            } else {
                throw new RuntimeException("An S3 exception occurred during delete", ex);
            }
        });

        return response.thenApply(r -> null);
    }


    /**
     * Deletes an S3 bucket asynchronously.
     *
     * @param bucket the name of the bucket to be deleted
     * @return a {@link CompletableFuture} that completes when the bucket deletion is successful, or throws a {@link RuntimeException}
     * if an error occurs during the deletion process
     */
    public CompletableFuture<Void> deleteBucketAsync(String bucket) {
        DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
            .bucket(bucket)
            .build();

        CompletableFuture<DeleteBucketResponse> response = getAsyncClient().deleteBucket(deleteBucketRequest);
        response.whenComplete((deleteRes, ex) -> {
            if (deleteRes != null) {
                logger.info(bucket + " was deleted.");
            } else {
                throw new RuntimeException("An S3 exception occurred during bucket deletion", ex);
            }
        });
        return response.thenApply(r -> null);
    }

    public CompletableFuture<String> performMultiCopy(String toBucket, String bucketName, String key) {
        CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder()
            .bucket(toBucket)
            .key(key)
            .build();

        getAsyncClient().createMultipartUpload(createMultipartUploadRequest)
            .thenApply(createMultipartUploadResponse -> {
                String uploadId = createMultipartUploadResponse.uploadId();
                System.out.println("Upload ID: " + uploadId);

                UploadPartCopyRequest uploadPartCopyRequest = UploadPartCopyRequest.builder()
                    .sourceBucket(bucketName)
                    .destinationBucket(toBucket)
                    .sourceKey(key)
                    .destinationKey(key)
                    .uploadId(uploadId)  // Use the valid uploadId.
                    .partNumber(1)  // Ensure the part number is correct.
                    .copySourceRange("bytes=0-1023")  // Adjust range as needed
                    .build();

                return getAsyncClient().uploadPartCopy(uploadPartCopyRequest);
            })
            .thenCompose(uploadPartCopyFuture -> uploadPartCopyFuture)
            .whenComplete((uploadPartCopyResponse, exception) -> {
                if (exception != null) {
                    // Handle any exceptions.
                    logger.error("Error during upload part copy: " + exception.getMessage());
                } else {
                    // Successfully completed the upload part copy.
                    System.out.println("Upload Part Copy completed successfully. ETag: " + uploadPartCopyResponse.copyPartResult().eTag());
                }
            });
        return null;
    }

    private static ByteBuffer getRandomByteBuffer(int size) {
        ByteBuffer buffer = ByteBuffer.allocate(size);
        for (int i = 0; i < size; i++) {
            buffer.put((byte) (Math.random() * 256));
        }
        buffer.flip();
        return buffer;
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObject)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListObjectsV2)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `AbortMultipartUpload`
<a name="s3_AbortMultipartUpload_java_2_topic"></a>

次のコード例は、`AbortMultipartUpload` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.LifecycleRule;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.MultipartUpload;
import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.utils.builder.SdkBuilder;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

import static software.amazon.awssdk.transfer.s3.SizeConstant.KB;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class AbortMultipartUploadExamples {
    static final String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID(); // Change bucket name.
    static final String key = UUID.randomUUID().toString();
    static final String classPathFilePath = "/multipartUploadFiles/s3-userguide.pdf";
    static final String filePath = getFullFilePath(classPathFilePath);
    static final S3Client s3Client = S3Client.create();
    private static final Logger logger = LoggerFactory.getLogger(AbortMultipartUploadExamples.class);
    private static String accountId = getAccountId();

    public static void main(String[] args) {
        doAbortIncompleteMultipartUploadsFromList();
        doAbortMultipartUploadUsingUploadId();
        doAbortIncompleteMultipartUploadsOlderThan();
        doAbortMultipartUploadsUsingLifecycleConfig();
    }

    // A wrapper method that sets up the multipart upload environment for abortIncompleteMultipartUploadsFromList().
    public static void doAbortIncompleteMultipartUploadsFromList() {
        createBucket();
        initiateAndInterruptMultiPartUpload("uploadThread");
        abortIncompleteMultipartUploadsFromList();
        deleteResources();
    }

    /**
     * Aborts all incomplete multipart uploads from the specified S3 bucket.
     * <p>
     * This method retrieves a list of all incomplete multipart uploads in the specified S3 bucket,
     * and then aborts each of those uploads.
     */
    public static void abortIncompleteMultipartUploadsFromList() {
        ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder()
            .bucket(bucketName)
            .build();

        ListMultipartUploadsResponse response = s3Client.listMultipartUploads(listMultipartUploadsRequest);
        List<MultipartUpload> uploads = response.uploads();

        AbortMultipartUploadRequest abortMultipartUploadRequest;
        for (MultipartUpload upload : uploads) {
            abortMultipartUploadRequest = AbortMultipartUploadRequest.builder()
                .bucket(bucketName)
                .key(upload.key())
                .expectedBucketOwner(accountId)
                .uploadId(upload.uploadId())
                .build();

            AbortMultipartUploadResponse abortMultipartUploadResponse = s3Client.abortMultipartUpload(abortMultipartUploadRequest);
            if (abortMultipartUploadResponse.sdkHttpResponse().isSuccessful()) {
                logger.info("Upload ID [{}] to bucket [{}] successfully aborted.", upload.uploadId(), bucketName);
            }
        }
    }

    // A wrapper method that sets up the multipart upload environment for abortIncompleteMultipartUploadsOlderThan().
    static void doAbortIncompleteMultipartUploadsOlderThan() {
        createBucket();
        Instant secondUploadInstant = initiateAndInterruptTwoUploads();
        abortIncompleteMultipartUploadsOlderThan(secondUploadInstant);
        deleteResources();
    }

    static void abortIncompleteMultipartUploadsOlderThan(Instant pointInTime) {
        ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder()
            .bucket(bucketName)
            .build();

        ListMultipartUploadsResponse response = s3Client.listMultipartUploads(listMultipartUploadsRequest);
        List<MultipartUpload> uploads = response.uploads();

        AbortMultipartUploadRequest abortMultipartUploadRequest;
        for (MultipartUpload upload : uploads) {
            logger.info("Found multipartUpload with upload ID [{}], initiated [{}]", upload.uploadId(), upload.initiated());
            if (upload.initiated().isBefore(pointInTime)) {
                abortMultipartUploadRequest = AbortMultipartUploadRequest.builder()
                    .bucket(bucketName)
                    .key(upload.key())
                    .expectedBucketOwner(accountId)
                    .uploadId(upload.uploadId())
                    .build();

                AbortMultipartUploadResponse abortMultipartUploadResponse = s3Client.abortMultipartUpload(abortMultipartUploadRequest);
                if (abortMultipartUploadResponse.sdkHttpResponse().isSuccessful()) {
                    logger.info("Upload ID [{}] to bucket [{}] successfully aborted.", upload.uploadId(), bucketName);
                }
            }
        }
    }

    // A wrapper method that sets up the multipart upload environment for abortMultipartUploadUsingUploadId().
    static void doAbortMultipartUploadUsingUploadId() {
        createBucket();
        try {
            abortMultipartUploadUsingUploadId();
        } catch (S3Exception e) {
            logger.error(e.getMessage());
        } finally {
            deleteResources();
        }
    }

    static void abortMultipartUploadUsingUploadId() {
        String uploadId = startUploadReturningUploadId();
        AbortMultipartUploadResponse response = s3Client.abortMultipartUpload(b -> b
            .uploadId(uploadId)
            .bucket(bucketName)
            .key(key));

        if (response.sdkHttpResponse().isSuccessful()) {
            logger.info("Upload ID [{}] to bucket [{}] successfully aborted.", uploadId, bucketName);
        }
    }

    // A wrapper method that sets up the multipart upload environment for abortMultipartUploadsUsingLifecycleConfig().
    static void doAbortMultipartUploadsUsingLifecycleConfig() {
        createBucket();
        try {
            abortMultipartUploadsUsingLifecycleConfig();
        } catch (S3Exception e) {
            logger.error(e.getMessage());
        } finally {
            deleteResources();
        }
    }

    static void abortMultipartUploadsUsingLifecycleConfig() {
        Collection<LifecycleRule> lifeCycleRules = List.of(LifecycleRule.builder()
            .abortIncompleteMultipartUpload(b -> b.
                daysAfterInitiation(7))
            .status("Enabled")
            .filter(SdkBuilder::build) // Filter element is required.
            .build());

        // If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body.
        PutBucketLifecycleConfigurationResponse response = s3Client.putBucketLifecycleConfiguration(b -> b
            .bucket(bucketName)
            .lifecycleConfiguration(b1 -> b1.rules(lifeCycleRules)));

        if (response.sdkHttpResponse().isSuccessful()) {
            logger.info("Rule to abort incomplete multipart uploads added to bucket.");
        } else {
            logger.error("Unsuccessfully applied rule. HTTP status code is [{}]", response.sdkHttpResponse().statusCode());
        }
    }

    /************************
     Multipart upload methods
     ***********************/

    static void initiateAndInterruptMultiPartUpload(String threadName) {
        Runnable upload = () -> {
            try {
                AbortMultipartUploadExamples.doMultipartUpload();
            } catch (SdkException e) {
                logger.error(e.getMessage());
            }
        };
        Thread uploadThread = new Thread(upload, threadName);
        uploadThread.start();
        try {
            Thread.sleep(Duration.ofSeconds(1).toMillis()); // Give the multipart upload time to register.
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
        uploadThread.interrupt();
    }

    static Instant initiateAndInterruptTwoUploads() {
        Instant firstUploadInstant = Instant.now();
        initiateAndInterruptMultiPartUpload("uploadThread1");
        try {
            Thread.sleep(Duration.ofSeconds(5).toMillis());
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }
        Instant secondUploadInstant = Instant.now();
        initiateAndInterruptMultiPartUpload("uploadThread2");
        return secondUploadInstant;
    }

    static void doMultipartUpload() {
        String uploadId = step1CreateMultipartUpload();
        List<CompletedPart> completedParts = step2UploadParts(uploadId);
        step3CompleteMultipartUpload(uploadId, completedParts);
    }

    static String step1CreateMultipartUpload() {
        CreateMultipartUploadResponse createMultipartUploadResponse = s3Client.createMultipartUpload(b -> b
            .bucket(bucketName)
            .key(key));
        return createMultipartUploadResponse.uploadId();
    }

    static List<CompletedPart> step2UploadParts(String uploadId) {
        int partNumber = 1;
        List<CompletedPart> completedParts = new ArrayList<>();
        ByteBuffer bb = ByteBuffer.allocate(Long.valueOf(1024 * KB).intValue());

        try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
            long fileSize = file.length();
            long position = 0;
            while (position < fileSize) {
                file.seek(position);
                long read = file.getChannel().read(bb);

                bb.flip(); // Swap position and limit before reading from the buffer.
                UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
                    .bucket(bucketName)
                    .key(key)
                    .uploadId(uploadId)
                    .partNumber(partNumber)
                    .build();

                UploadPartResponse partResponse = s3Client.uploadPart(
                    uploadPartRequest,
                    RequestBody.fromByteBuffer(bb));

                CompletedPart part = CompletedPart.builder()
                    .partNumber(partNumber)
                    .eTag(partResponse.eTag())
                    .build();
                completedParts.add(part);
                logger.info("Part {} upload", partNumber);

                bb.clear();
                position += read;
                partNumber++;
            }
        } catch (IOException | S3Exception e) {
            logger.error(e.getMessage());
            return null;
        }
        return completedParts;
    }

    static void step3CompleteMultipartUpload(String uploadId, List<CompletedPart> completedParts) {
        s3Client.completeMultipartUpload(b -> b
            .bucket(bucketName)
            .key(key)
            .uploadId(uploadId)
            .multipartUpload(CompletedMultipartUpload.builder().parts(completedParts).build()));
    }

    static String startUploadReturningUploadId() {
        String uploadId = step1CreateMultipartUpload();
        doMultipartUploadWithUploadId(uploadId);
        return uploadId;

    }

    static void doMultipartUploadWithUploadId(String uploadId) {
        new Thread(() -> {
            try {
                List<CompletedPart> completedParts = step2UploadParts(uploadId);
                step3CompleteMultipartUpload(uploadId, completedParts);
            } catch (SdkException e) {
                logger.error(e.getMessage());
            }
        }, "upload thread").start();
        try {
            Thread.sleep(Duration.ofSeconds(2L).toMillis());
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
            System.exit(1);
        }
    }

    /*************************
     Resource handling methods
     ************************/

    static void createBucket() {
        logger.info("Creating bucket: [{}]", bucketName);
        s3Client.createBucket(b -> b.bucket(bucketName));
        try (S3Waiter s3Waiter = s3Client.waiter()) {
            s3Waiter.waitUntilBucketExists(b -> b.bucket(bucketName));
        }
        logger.info("Bucket created.");
    }

    static void deleteResources() {
        logger.info("Deleting resources ...");
        s3Client.deleteObject(b -> b.bucket(bucketName).key(key));
        s3Client.deleteBucket(b -> b.bucket(bucketName));
        try (S3Waiter s3Waiter = s3Client.waiter()) {
            s3Waiter.waitUntilBucketNotExists(b -> b.bucket(bucketName));
        }
        logger.info("Resources deleted.");
    }

    private static String getAccountId() {
        try (StsClient stsClient = StsClient.create()) {
            return stsClient.getCallerIdentity().account();
        }
    }

    static String getFullFilePath(String filePath) {
        URL uploadDirectoryURL = PerformMultiPartUpload.class.getResource(filePath);
        String fullFilePath;
        try {
            fullFilePath = Objects.requireNonNull(uploadDirectoryURL).toURI().getPath();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
        return fullFilePath;
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[AbortMultipartUpload](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/AbortMultipartUpload)」を参照してください。**

### `CopyObject`
<a name="s3_CopyObject_java_2_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してオブジェクトをコピーします。  

```
    /**
     * Asynchronously copies an object from one S3 bucket to another.
     *
     * @param fromBucket the name of the source S3 bucket
     * @param objectKey  the key (name) of the object to be copied
     * @param toBucket   the name of the destination S3 bucket
     * @return a {@link CompletableFuture} that completes with the copy result as a {@link String}
     * @throws RuntimeException if the URL could not be encoded or an S3 exception occurred during the copy
     */
    public CompletableFuture<String> copyBucketObjectAsync(String fromBucket, String objectKey, String toBucket) {
        CopyObjectRequest copyReq = CopyObjectRequest.builder()
            .sourceBucket(fromBucket)
            .sourceKey(objectKey)
            .destinationBucket(toBucket)
            .destinationKey(objectKey)
            .build();

        CompletableFuture<CopyObjectResponse> response = getAsyncClient().copyObject(copyReq);
        response.whenComplete((copyRes, ex) -> {
            if (copyRes != null) {
                logger.info("The " + objectKey + " was copied to " + toBucket);
            } else {
                throw new RuntimeException("An S3 exception occurred during copy", ex);
            }
        });

        return response.thenApply(CopyObjectResponse::copyObjectResult)
            .thenApply(Object::toString);
    }
```
[S3TransferManager](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html) を使用して、1 つのバケットから別のバケットへ[オブジェクトをコピー](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html#copy(software.amazon.awssdk.transfer.s3.CopyRequest))します。[完全なファイル](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/ObjectCopy.java)と[テスト](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/test/java/TransferManagerTest.java)を表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedCopy;
import software.amazon.awssdk.transfer.s3.model.Copy;
import software.amazon.awssdk.transfer.s3.model.CopyRequest;

import java.util.UUID;

    public String copyObject(S3TransferManager transferManager, String bucketName,
            String key, String destinationBucket, String destinationKey) {
        CopyObjectRequest copyObjectRequest = CopyObjectRequest.builder()
                .sourceBucket(bucketName)
                .sourceKey(key)
                .destinationBucket(destinationBucket)
                .destinationKey(destinationKey)
                .build();

        CopyRequest copyRequest = CopyRequest.builder()
                .copyObjectRequest(copyObjectRequest)
                .build();

        Copy copy = transferManager.copy(copyRequest);

        CompletedCopy completedCopy = copy.completionFuture().join();
        return completedCopy.response().copyObjectResult().eTag();
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CopyObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CopyObject)」を参照してください。**

### `CreateBucket`
<a name="s3_CreateBucket_java_2_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットを作成します。  

```
    /**
     * Creates an S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to create
     * @return a {@link CompletableFuture} that completes when the bucket is created and ready
     * @throws RuntimeException if there is a failure while creating the bucket
     */
    public CompletableFuture<Void> createBucketAsync(String bucketName) {
        CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
            .bucket(bucketName)
            .build();

        CompletableFuture<CreateBucketResponse> response = getAsyncClient().createBucket(bucketRequest);
        return response.thenCompose(resp -> {
            S3AsyncWaiter s3Waiter = getAsyncClient().waiter();
            HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder()
                .bucket(bucketName)
                .build();

            CompletableFuture<WaiterResponse<HeadBucketResponse>> waiterResponseFuture =
                s3Waiter.waitUntilBucketExists(bucketRequestWait);
            return waiterResponseFuture.thenAccept(waiterResponse -> {
                waiterResponse.matched().response().ifPresent(headBucketResponse -> {
                    logger.info(bucketName + " is ready");
                });
            });
        }).whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to create bucket", ex);
            }
        });
    }
```
オブジェクトロックを有効にしてバケットを作成します。  

```
    // 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");
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_java_2_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an S3 bucket asynchronously.
     *
     * @param bucket the name of the bucket to be deleted
     * @return a {@link CompletableFuture} that completes when the bucket deletion is successful, or throws a {@link RuntimeException}
     * if an error occurs during the deletion process
     */
    public CompletableFuture<Void> deleteBucketAsync(String bucket) {
        DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
            .bucket(bucket)
            .build();

        CompletableFuture<DeleteBucketResponse> response = getAsyncClient().deleteBucket(deleteBucketRequest);
        response.whenComplete((deleteRes, ex) -> {
            if (deleteRes != null) {
                logger.info(bucket + " was deleted.");
            } else {
                throw new RuntimeException("An S3 exception occurred during bucket deletion", ex);
            }
        });
        return response.thenApply(r -> null);
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DeleteBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucket)」を参照してください。**

### `DeleteBucketPolicy`
<a name="s3_DeleteBucketPolicy_java_2_topic"></a>

次のコード例は、`DeleteBucketPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteBucketPolicyRequest;

/**
 * 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 DeleteBucketPolicy {
    public static void main(String[] args) {

        final String usage = """

                Usage:
                    <bucketName>

                Where:
                    bucketName - The Amazon S3 bucket to delete the policy from (for example, bucket1).""";

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        System.out.format("Deleting policy from bucket: \"%s\"\n\n", bucketName);
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
                .region(region)
                .build();

        deleteS3BucketPolicy(s3, bucketName);
        s3.close();
    }

    /**
     * Deletes the S3 bucket policy for the specified bucket.
     *
     * @param s3 the {@link S3Client} instance to use for the operation
     * @param bucketName the name of the S3 bucket for which the policy should be deleted
     *
     * @throws S3Exception if there is an error deleting the bucket policy
     */
    public static void deleteS3BucketPolicy(S3Client s3, String bucketName) {
        DeleteBucketPolicyRequest delReq = DeleteBucketPolicyRequest.builder()
                .bucket(bucketName)
                .build();

        try {
            s3.deleteBucketPolicy(delReq);
            System.out.println("Done!");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteBucketPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucketPolicy)」を参照してください。

### `DeleteBucketWebsite`
<a name="s3_DeleteBucketWebsite_java_2_topic"></a>

次のコード例は、`DeleteBucketWebsite` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteBucketWebsiteRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class DeleteWebsiteConfiguration {
    public static void main(String[] args) {
        final String usage = """

            Usage:     <bucketName>

            Where:
                bucketName - The Amazon S3 bucket to delete the website configuration from.
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        System.out.format("Deleting website configuration for Amazon S3 bucket: %s\n", bucketName);
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        deleteBucketWebsiteConfig(s3, bucketName);
        System.out.println("Done!");
        s3.close();
    }

    /**
     * Deletes the website configuration for an Amazon S3 bucket.
     *
     * @param s3 The {@link S3Client} instance used to interact with Amazon S3.
     * @param bucketName The name of the S3 bucket for which the website configuration should be deleted.
     * @throws S3Exception If an error occurs while deleting the website configuration.
     */
    public static void deleteBucketWebsiteConfig(S3Client s3, String bucketName) {
        DeleteBucketWebsiteRequest delReq = DeleteBucketWebsiteRequest.builder()
            .bucket(bucketName)
            .build();

        try {
            s3.deleteBucketWebsite(delReq);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.out.println("Failed to delete website configuration!");
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteBucketWebsite](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucketWebsite)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_java_2_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an object from an S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket
     * @param key        the key (file name) of the object to be deleted
     * @return a {@link CompletableFuture} that completes when the object has been deleted
     */
    public CompletableFuture<Void> deleteObjectFromBucketAsync(String bucketName, String key) {
        DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

        CompletableFuture<DeleteObjectResponse> response = getAsyncClient().deleteObject(deleteObjectRequest);
        response.whenComplete((deleteRes, ex) -> {
            if (deleteRes != null) {
                logger.info(key + " was deleted");
            } else {
                throw new RuntimeException("An S3 exception occurred during delete", ex);
            }
        });

        return response.thenApply(r -> null);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_java_2_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.Delete;
import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.util.ArrayList;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class DeleteMultiObjects {
    public static void main(String[] args) {
        final String usage = """

            Usage:    <bucketName>

            Where:
               bucketName - the Amazon S3 bucket name.
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        deleteBucketObjects(s3, bucketName);
        s3.close();
    }

    /**
     * Deletes multiple objects from an Amazon S3 bucket.
     *
     * @param s3 An Amazon S3 client object.
     * @param bucketName The name of the Amazon S3 bucket to delete objects from.
     */
    public static void deleteBucketObjects(S3Client s3, String bucketName) {
        // Upload three sample objects to the specfied Amazon S3 bucket.
        ArrayList<ObjectIdentifier> keys = new ArrayList<>();
        PutObjectRequest putOb;
        ObjectIdentifier objectId;

        for (int i = 0; i < 3; i++) {
            String keyName = "delete object example " + i;
            objectId = ObjectIdentifier.builder()
                .key(keyName)
                .build();

            putOb = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(keyName)
                .build();

            s3.putObject(putOb, RequestBody.fromString(keyName));
            keys.add(objectId);
        }

        System.out.println(keys.size() + " objects successfully created.");

        // Delete multiple objects in one request.
        Delete del = Delete.builder()
            .objects(keys)
            .build();

        try {
            DeleteObjectsRequest multiObjectDeleteRequest = DeleteObjectsRequest.builder()
                .bucket(bucketName)
                .delete(del)
                .build();

            s3.deleteObjects(multiObjectDeleteRequest);
            System.out.println("Multiple objects are deleted!");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteObjects)」を参照してください。**

### `GetBucketAcl`
<a name="s3_GetBucketAcl_java_2_topic"></a>

次のコード例は、`GetBucketAcl` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectAclRequest;
import software.amazon.awssdk.services.s3.model.GetObjectAclResponse;
import software.amazon.awssdk.services.s3.model.Grant;

import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class GetAcl {
    public static void main(String[] args) {
        final String usage = """

            Usage:
              <bucketName> <objectKey>

            Where:
              bucketName - The Amazon S3 bucket to get the access control list (ACL) for.
              objectKey - The object to get the ACL for.\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String objectKey = args[1];
        System.out.println("Retrieving ACL for object: " + objectKey);
        System.out.println("in bucket: " + bucketName);
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        getBucketACL(s3, objectKey, bucketName);
        s3.close();
        System.out.println("Done!");
    }

    /**
     * Retrieves the Access Control List (ACL) for an object in an Amazon S3 bucket.
     *
     * @param s3 The S3Client object used to interact with the Amazon S3 service.
     * @param objectKey The key of the object for which the ACL is to be retrieved.
     * @param bucketName The name of the bucket containing the object.
     * @return The ID of the grantee who has permission on the object, or an empty string if an error occurs.
     */
    public static String getBucketACL(S3Client s3, String objectKey, String bucketName) {
        try {
            GetObjectAclRequest aclReq = GetObjectAclRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .build();

            GetObjectAclResponse aclRes = s3.getObjectAcl(aclReq);
            List<Grant> grants = aclRes.grants();
            String grantee = "";
            for (Grant grant : grants) {
                System.out.format("  %s: %s\n", grant.grantee().id(), grant.permission());
                grantee = grant.grantee().id();
            }

            return grantee;
        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetBucketAcl](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetBucketAcl)」を参照してください。

### `GetBucketPolicy`
<a name="s3_GetBucketPolicy_java_2_topic"></a>

次のコード例は、`GetBucketPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.GetBucketPolicyResponse;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class GetBucketPolicy {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName>

            Where:
                bucketName - The Amazon S3 bucket to get the policy from.
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName);
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        String polText = getPolicy(s3, bucketName);
        System.out.println("Policy Text: " + polText);
        s3.close();
    }

    /**
     * Retrieves the policy for the specified Amazon S3 bucket.
     *
     * @param s3 the {@link S3Client} instance to use for making the request
     * @param bucketName the name of the S3 bucket for which to retrieve the policy
     * @return the policy text for the specified bucket, or an empty string if an error occurs
     */
    public static String getPolicy(S3Client s3, String bucketName) {
        String policyText;
        System.out.format("Getting policy for bucket: \"%s\"\n\n", bucketName);
        GetBucketPolicyRequest policyReq = GetBucketPolicyRequest.builder()
            .bucket(bucketName)
            .build();

        try {
            GetBucketPolicyResponse policyRes = s3.getBucketPolicy(policyReq);
            policyText = policyRes.policy();
            return policyText;

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetBucketPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetBucketPolicy)」を参照してください。

### `GetBucketReplication`
<a name="s3_GetBucketReplication_java_2_topic"></a>

次のコード例は、`GetBucketReplication` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the replication details for the specified S3 bucket.
     *
     * @param s3Client           the S3 client used to interact with the S3 service
     * @param sourceBucketName   the name of the S3 bucket to retrieve the replication details for
     *
     * @throws S3Exception if there is an error retrieving the replication details
     */
    public static void getReplicationDetails(S3Client s3Client, String sourceBucketName) {
        GetBucketReplicationRequest getRequest = GetBucketReplicationRequest.builder()
            .bucket(sourceBucketName)
            .build();

        try {
            ReplicationConfiguration replicationConfig = s3Client.getBucketReplication(getRequest).replicationConfiguration();
            ReplicationRule rule = replicationConfig.rules().get(0);
            System.out.println("Retrieved destination bucket: " + rule.destination().bucket());
            System.out.println("Retrieved priority: " + rule.priority());
            System.out.println("Retrieved source-bucket replication rule status: " + rule.status());

        } catch (S3Exception e) {
            System.err.println("Failed to retrieve replication details: " + e.awsErrorDetails().errorMessage());
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetBucketReplication](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetBucketReplication)」を参照してください。

### `GetObject`
<a name="s3_GetObject_java_2_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用して、データをバイト配列として読み取ります。  

```
    /**
     * Asynchronously retrieves the bytes of an object from an Amazon S3 bucket and writes them to a local file.
     *
     * @param bucketName the name of the S3 bucket containing the object
     * @param keyName    the key (or name) of the S3 object to retrieve
     * @param path       the local file path where the object's bytes will be written
     * @return a {@link CompletableFuture} that completes when the object bytes have been written to the local file
     */
    public CompletableFuture<Void> getObjectBytesAsync(String bucketName, String keyName, String path) {
        GetObjectRequest objectRequest = GetObjectRequest.builder()
            .key(keyName)
            .bucket(bucketName)
            .build();

        CompletableFuture<ResponseBytes<GetObjectResponse>> response = getAsyncClient().getObject(objectRequest, AsyncResponseTransformer.toBytes());
        return response.thenAccept(objectBytes -> {
            try {
                byte[] data = objectBytes.asByteArray();
                Path filePath = Paths.get(path);
                Files.write(filePath, data);
                logger.info("Successfully obtained bytes from an S3 object");
            } catch (IOException ex) {
                throw new RuntimeException("Failed to write data to file", ex);
            }
        }).whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to get object bytes from S3", ex);
            }
        });
    }
```
[S3TransferManager](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html) を使用して、ローカルファイルに S3 バケットの[オブジェクトをダウンロード](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html#downloadFile(software.amazon.awssdk.transfer.s3.DownloadFileRequest))します。[完全なファイル](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadFile.java)と[テスト](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/test/java/TransferManagerTest.java)を表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload;
import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest;
import software.amazon.awssdk.transfer.s3.model.FileDownload;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

    public Long downloadFile(S3TransferManager transferManager, String bucketName,
                             String key, String downloadedFileWithPath) {
        DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
                .getObjectRequest(b -> b.bucket(bucketName).key(key))
                .destination(Paths.get(downloadedFileWithPath))
                .build();

        FileDownload downloadFile = transferManager.downloadFile(downloadFileRequest);

        CompletedFileDownload downloadResult = downloadFile.completionFuture().join();
        logger.info("Content length [{}]", downloadResult.response().contentLength());
        return downloadResult.response().contentLength();
    }
```
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用して、オブジェクトに属するタグを読み取ります。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest;
import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.Tag;

import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class GetObjectTags {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <keyName>\s

            Where:
                bucketName - The Amazon S3 bucket name.\s
                keyName - A key name that represents the object.\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        listTags(s3, bucketName, keyName);
        s3.close();
    }

    /**
     * Lists the tags associated with an Amazon S3 object.
     *
     * @param s3 the S3Client object used to interact with the Amazon S3 service
     * @param bucketName the name of the S3 bucket that contains the object
     * @param keyName the key (name) of the S3 object
     */
    public static void listTags(S3Client s3, String bucketName, String keyName) {
        try {
            GetObjectTaggingRequest getTaggingRequest = GetObjectTaggingRequest
                .builder()
                .key(keyName)
                .bucket(bucketName)
                .build();

            GetObjectTaggingResponse tags = s3.getObjectTagging(getTaggingRequest);
            List<Tag> tagSet = tags.tagSet();
            for (Tag tag : tagSet) {
                System.out.println(tag.key());
                System.out.println(tag.value());
            }

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してオブジェクトの URL を取得します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetUrlRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.net.URL;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class GetObjectUrl {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <keyName>\s

            Where:
                bucketName - The Amazon S3 bucket name.
                keyName - A key name that represents the object.\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        getURL(s3, bucketName, keyName);
        s3.close();
    }

    /**
     * Retrieves the URL for a specific object in an Amazon S3 bucket.
     *
     * @param s3 the S3Client object used to interact with the Amazon S3 service
     * @param bucketName the name of the S3 bucket where the object is stored
     * @param keyName the name of the object for which the URL should be retrieved
     * @throws S3Exception if there is an error retrieving the URL for the specified object
     */
    public static void getURL(S3Client s3, String bucketName, String keyName) {
        try {
            GetUrlRequest request = GetUrlRequest.builder()
                .bucket(bucketName)
                .key(keyName)
                .build();

            URL url = s3.utilities().getUrl(request);
            System.out.println("The URL for  " + keyName + " is " + url);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用する S3Presigner クライアントオブジェクトを使用してオブジェクトを取得します。  

```
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.time.Duration;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.utils.IoUtils;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class GetObjectPresignedUrl {
    public static void main(String[] args) {
        final String USAGE = """

            Usage:
                <bucketName> <keyName>\s

            Where:
                bucketName - The Amazon S3 bucket name.\s
                keyName - A key name that represents a text file.\s
            """;

        if (args.length != 2) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];
        Region region = Region.US_EAST_1;
        S3Presigner presigner = S3Presigner.builder()
            .region(region)
            .build();

        getPresignedUrl(presigner, bucketName, keyName);
        presigner.close();
    }

    /**
     * Generates a pre-signed URL for an Amazon S3 object.
     *
     * @param presigner The {@link S3Presigner} instance to use for generating the pre-signed URL.
     * @param bucketName The name of the Amazon S3 bucket where the object is stored.
     * @param keyName The key name (file name) of the object in the Amazon S3 bucket.
     *
     * @throws S3Exception If there is an error interacting with the Amazon S3 service.
     * @throws IOException If there is an error opening the HTTP connection or reading/writing the request/response.
     */
    public static void getPresignedUrl(S3Presigner presigner, String bucketName, String keyName) {
        try {
            GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                .bucket(bucketName)
                .key(keyName)
                .build();

            GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder()
                .signatureDuration(Duration.ofMinutes(60))
                .getObjectRequest(getObjectRequest)
                .build();

            PresignedGetObjectRequest presignedGetObjectRequest = presigner.presignGetObject(getObjectPresignRequest);
            String theUrl = presignedGetObjectRequest.url().toString();
            System.out.println("Presigned URL: " + theUrl);
            HttpURLConnection connection = (HttpURLConnection) presignedGetObjectRequest.url().openConnection();
            presignedGetObjectRequest.httpRequest().headers().forEach((header, values) -> {
                values.forEach(value -> {
                    connection.addRequestProperty(header, value);
                });
            });

            // Send any request payload that the service needs (not needed when
            // isBrowserExecutable is true).
            if (presignedGetObjectRequest.signedPayload().isPresent()) {
                connection.setDoOutput(true);

                try (InputStream signedPayload = presignedGetObjectRequest.signedPayload().get().asInputStream();
                     OutputStream httpOutputStream = connection.getOutputStream()) {
                    IoUtils.copy(signedPayload, httpOutputStream);
                }
            }

            // Download the result of executing the request.
            try (InputStream content = connection.getInputStream()) {
                System.out.println("Service returned response: ");
                IoUtils.copy(content, System.out);
            }

        } catch (S3Exception | IOException e) {
            e.printStackTrace();
        }
    }
}
```
ResponseTransformer オブジェクトと [S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してオブジェクトを取得します。  

```
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.core.sync.ResponseTransformer;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class GetObjectData {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <keyName> <path>

            Where:
                bucketName - The Amazon S3 bucket name.\s
                keyName - The key name.\s
                path - The path where the file is written to.\s
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];
        String path = args[2];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        getObjectBytes(s3, bucketName, keyName, path);
        s3.close();
    }

    /**
     * Retrieves the bytes of an object stored in an Amazon S3 bucket and saves them to a local file.
     *
     * @param s3 The S3Client instance used to interact with the Amazon S3 service.
     * @param bucketName The name of the S3 bucket where the object is stored.
     * @param keyName The key (or name) of the S3 object.
     * @param path The local file path where the object's bytes will be saved.
     * @throws IOException If an I/O error occurs while writing the bytes to the local file.
     * @throws S3Exception If an error occurs while retrieving the object from the S3 bucket.
     */
    public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) {
        try {
            GetObjectRequest objectRequest = GetObjectRequest
                .builder()
                .key(keyName)
                .bucket(bucketName)
                .build();

            ResponseBytes<GetObjectResponse> objectBytes = s3.getObject(objectRequest, ResponseTransformer.toBytes());
            byte[] data = objectBytes.asByteArray();

            // Write the data to a local file.
            File myFile = new File(path);
            OutputStream os = new FileOutputStream(myFile);
            os.write(data);
            System.out.println("Successfully obtained bytes from an S3 object");
            os.close();

        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[GetObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObject)」を参照してください。**

### `GetObjectLegalHold`
<a name="s3_GetObjectLegalHold_java_2_topic"></a>

次のコード例は、`GetObjectLegalHold` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    // Get the legal hold details for an S3 object.
    public ObjectLockLegalHold getObjectLegalHold(String bucketName, String objectKey) {
        try {
            GetObjectLegalHoldRequest legalHoldRequest = GetObjectLegalHoldRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .build();

            GetObjectLegalHoldResponse response = getClient().getObjectLegalHold(legalHoldRequest);
            System.out.println("Object legal hold for " + objectKey + " in " + bucketName +
                ":\n\tStatus: " + response.legalHold().status());
            return response.legalHold();

        } catch (S3Exception ex) {
            System.out.println("\tUnable to fetch legal hold: '" + ex.getMessage() + "'");
        }

        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetObjectLegalHold](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObjectLegalHold)」を参照してください。

### `GetObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_java_2_topic"></a>

次のコード例は、`GetObjectLockConfiguration` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    // Get the object lock configuration details for an S3 bucket.
    public void getBucketObjectLockConfiguration(String bucketName) {
        GetObjectLockConfigurationRequest objectLockConfigurationRequest = GetObjectLockConfigurationRequest.builder()
            .bucket(bucketName)
            .build();

        GetObjectLockConfigurationResponse response = getClient().getObjectLockConfiguration(objectLockConfigurationRequest);
        System.out.println("Bucket object lock config for "+bucketName +":  ");
        System.out.println("\tEnabled: "+response.objectLockConfiguration().objectLockEnabled());
        System.out.println("\tRule: "+ response.objectLockConfiguration().rule().defaultRetention());
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetObjectLockConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObjectLockConfiguration)」を参照してください。

### `GetObjectRetention`
<a name="s3_GetObjectRetention_java_2_topic"></a>

次のコード例は、`GetObjectRetention` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    // Get the retention period for an S3 object.
    public ObjectLockRetention getObjectRetention(String bucketName, String key){
        try {
            GetObjectRetentionRequest retentionRequest = GetObjectRetentionRequest.builder()
                .bucket(bucketName)
                .key(key)
                .build();

            GetObjectRetentionResponse response = getClient().getObjectRetention(retentionRequest);
            System.out.println("tObject retention for "+key +" in "+ bucketName +": " + response.retention().mode() +" until "+ response.retention().retainUntilDate() +".");
            return response.retention();

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return null;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetObjectRetention](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObjectRetention)」を参照してください。

### `HeadObject`
<a name="s3_HeadObject_java_2_topic"></a>

次のコード例は、`HeadObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトのコンテンツタイプを調べる  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class GetObjectContentType {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <keyName>

            Where:
                bucketName - The Amazon S3 bucket name.\s
                keyName - The key name.\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        getContentType(s3, bucketName, keyName);
        s3.close();
    }

    /**
     * Retrieves the content type of an object stored in an Amazon S3 bucket.
     *
     * @param s3 an instance of the {@link S3Client} class, which is used to interact with the Amazon S3 service
     * @param bucketName the name of the S3 bucket where the object is stored
     * @param keyName the key (file name) of the object in the S3 bucket
     */
    public static void getContentType(S3Client s3, String bucketName, String keyName) {
        try {
            HeadObjectRequest objectRequest = HeadObjectRequest.builder()
                .key(keyName)
                .bucket(bucketName)
                .build();

            HeadObjectResponse objectHead = s3.headObject(objectRequest);
            String type = objectHead.contentType();
            System.out.println("The object content type is " + type);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
オブジェクトの復元ステータスを取得する  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

public class GetObjectRestoreStatus {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <keyName>\s

            Where:
                bucketName - The Amazon S3 bucket name.\s
                keyName - A key name that represents the object.\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        checkStatus(s3, bucketName, keyName);
        s3.close();
    }

    /**
     * Checks the restoration status of an Amazon S3 object.
     *
     * @param s3         an instance of the {@link S3Client} class used to interact with the Amazon S3 service
     * @param bucketName the name of the Amazon S3 bucket where the object is stored
     * @param keyName    the name of the Amazon S3 object to be checked
     * @throws S3Exception if an error occurs while interacting with the Amazon S3 service
     */
    public static void checkStatus(S3Client s3, String bucketName, String keyName) {
        try {
            HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
                .bucket(bucketName)
                .key(keyName)
                .build();

            HeadObjectResponse response = s3.headObject(headObjectRequest);
            System.out.println("The Amazon S3 object restoration status is " + response.restore());

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[HeadObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/HeadObject)」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_java_2_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.paginators.ListBucketsIterable;
/**
 * 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 ListBuckets {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        listAllBuckets(s3);

    }

    /**
     * Lists all the S3 buckets available in the current AWS account.
     *
     * @param s3 The {@link S3Client} instance to use for interacting with the Amazon S3 service.
     */
    public static void listAllBuckets(S3Client s3) {
        ListBucketsIterable response = s3.listBucketsPaginator();
        response.buckets().forEach(bucket ->
            System.out.println("Bucket Name: " + bucket.name()));
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListBuckets)」を参照してください。**

### `ListMultipartUploads`
<a name="s3_ListMultipartUploads_java_2_topic"></a>

次のコード例は、`ListMultipartUploads` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.MultipartUpload;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.util.List;

/**
 * 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 ListMultipartUploads {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <bucketName>\s

                Where:
                    bucketName - The name of the Amazon S3 bucket where an in-progress multipart upload is occurring.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
                .region(region)
                .build();
        listUploads(s3, bucketName);
        s3.close();
    }

    /**
     * Lists the multipart uploads currently in progress in the specified Amazon S3 bucket.
     *
     * @param s3 the S3Client object used to interact with Amazon S3
     * @param bucketName the name of the Amazon S3 bucket to list the multipart uploads for
     */
    public static void listUploads(S3Client s3, String bucketName) {
        try {
            ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder()
                    .bucket(bucketName)
                    .build();

            ListMultipartUploadsResponse response = s3.listMultipartUploads(listMultipartUploadsRequest);
            List<MultipartUpload> uploads = response.uploads();
            for (MultipartUpload upload : uploads) {
                System.out.println("Upload in progress: Key = \"" + upload.key() + "\", id = " + upload.uploadId());
            }

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListMultipartUploads](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListMultipartUploads)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_java_2_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously lists all objects in the specified S3 bucket.
     *
     * @param bucketName the name of the S3 bucket to list objects for
     * @return a {@link CompletableFuture} that completes when all objects have been listed
     */
    public CompletableFuture<Void> listAllObjectsAsync(String bucketName) {
        ListObjectsV2Request initialRequest = ListObjectsV2Request.builder()
            .bucket(bucketName)
            .maxKeys(1)
            .build();

        ListObjectsV2Publisher paginator = getAsyncClient().listObjectsV2Paginator(initialRequest);
        return paginator.subscribe(response -> {
            response.contents().forEach(s3Object -> {
                logger.info("Object key: " + s3Object.key());
            });
        }).thenRun(() -> {
            logger.info("Successfully listed all objects in the bucket: " + bucketName);
        }).exceptionally(ex -> {
            throw new RuntimeException("Failed to list objects", ex);
        });
    }
```
ページネーションを使用してオブジェクトを一覧表示します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;

public class ListObjectsPaginated {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName>\s

            Where:
                bucketName - The Amazon S3 bucket from which objects are read.\s
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        listBucketObjects(s3, bucketName);
        s3.close();
    }

    /**
     * Lists the objects in the specified S3 bucket.
     *
     * @param s3 the S3Client instance used to interact with Amazon S3
     * @param bucketName the name of the S3 bucket to list the objects from
     */
    public static void listBucketObjects(S3Client s3, String bucketName) {
        try {
            ListObjectsV2Request listReq = ListObjectsV2Request.builder()
                .bucket(bucketName)
                .maxKeys(1)
                .build();

            ListObjectsV2Iterable listRes = s3.listObjectsV2Paginator(listReq);
            listRes.stream()
                .flatMap(r -> r.contents().stream())
                .forEach(content -> System.out.println(" Key: " + content.key() + " size = " + content.size()));

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListObjectsV2)」を参照してください。

### `PutBucketAcl`
<a name="s3_PutBucketAcl_java_2_topic"></a>

次のコード例は、`PutBucketAcl` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.AccessControlPolicy;
import software.amazon.awssdk.services.s3.model.Grant;
import software.amazon.awssdk.services.s3.model.Permission;
import software.amazon.awssdk.services.s3.model.PutBucketAclRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.Type;

import java.util.ArrayList;
import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SetAcl {
    public static void main(String[] args) {
        final String usage = """

            Usage:
              <bucketName> <id>\s

            Where:
              bucketName - The Amazon S3 bucket to grant permissions on.\s
              id - The ID of the owner of this bucket (you can get this value from the AWS Management Console).
            """;

        if (args.length != 2) {
            System.out.println(usage);
            return;
        }

        String bucketName = args[0];
        String id = args[1];
        System.out.format("Setting access \n");
        System.out.println(" in bucket: " + bucketName);
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        setBucketAcl(s3, bucketName, id);
        System.out.println("Done!");
        s3.close();
    }

    /**
     * Sets the Access Control List (ACL) for an Amazon S3 bucket.
     *
     * @param s3 the S3Client instance to be used for the operation
     * @param bucketName the name of the S3 bucket to set the ACL for
     * @param id the ID of the AWS user or account that will be granted full control of the bucket
     * @throws S3Exception if an error occurs while setting the bucket ACL
     */
    public static void setBucketAcl(S3Client s3, String bucketName, String id) {
        try {
            Grant ownerGrant = Grant.builder()
                .grantee(builder -> builder.id(id)
                    .type(Type.CANONICAL_USER))
                .permission(Permission.FULL_CONTROL)
                .build();

            List<Grant> grantList2 = new ArrayList<>();
            grantList2.add(ownerGrant);

            AccessControlPolicy acl = AccessControlPolicy.builder()
                .owner(builder -> builder.id(id))
                .grants(grantList2)
                .build();

            PutBucketAclRequest putAclReq = PutBucketAclRequest.builder()
                .bucket(bucketName)
                .accessControlPolicy(acl)
                .build();

            s3.putBucketAcl(putAclReq);

        } catch (S3Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutBucketAcl](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketAcl)」を参照してください。

### `PutBucketCors`
<a name="s3_PutBucketCors_java_2_topic"></a>

次のコード例は、`PutBucketCors` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;

import java.util.ArrayList;
import java.util.List;

import software.amazon.awssdk.services.s3.model.GetBucketCorsRequest;
import software.amazon.awssdk.services.s3.model.GetBucketCorsResponse;
import software.amazon.awssdk.services.s3.model.DeleteBucketCorsRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.CORSRule;
import software.amazon.awssdk.services.s3.model.CORSConfiguration;
import software.amazon.awssdk.services.s3.model.PutBucketCorsRequest;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class S3Cors {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <accountId>\s

            Where:
                bucketName - The Amazon S3 bucket to upload an object into.
                accountId - The id of the account that owns the Amazon S3 bucket.
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String accountId = args[1];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        setCorsInformation(s3, bucketName, accountId);
        getBucketCorsInformation(s3, bucketName, accountId);
        deleteBucketCorsInformation(s3, bucketName, accountId);
        s3.close();
    }

    /**
     * Deletes the CORS (Cross-Origin Resource Sharing) configuration for an Amazon S3 bucket.
     *
     * @param s3            the {@link S3Client} instance used to interact with the Amazon S3 service
     * @param bucketName    the name of the Amazon S3 bucket for which the CORS configuration should be deleted
     * @param accountId     the expected AWS account ID of the bucket owner
     *
     * @throws S3Exception if an error occurs while deleting the CORS configuration for the bucket
     */
    public static void deleteBucketCorsInformation(S3Client s3, String bucketName, String accountId) {
        try {
            DeleteBucketCorsRequest bucketCorsRequest = DeleteBucketCorsRequest.builder()
                .bucket(bucketName)
                .expectedBucketOwner(accountId)
                .build();

            s3.deleteBucketCors(bucketCorsRequest);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    /**
     * Retrieves the CORS (Cross-Origin Resource Sharing) configuration for the specified S3 bucket.
     *
     * @param s3 the S3Client instance to use for the operation
     * @param bucketName the name of the S3 bucket to retrieve the CORS configuration for
     * @param accountId the expected bucket owner's account ID
     *
     * @throws S3Exception if there is an error retrieving the CORS configuration
     */
    public static void getBucketCorsInformation(S3Client s3, String bucketName, String accountId) {
        try {
            GetBucketCorsRequest bucketCorsRequest = GetBucketCorsRequest.builder()
                .bucket(bucketName)
                .expectedBucketOwner(accountId)
                .build();

            GetBucketCorsResponse corsResponse = s3.getBucketCors(bucketCorsRequest);
            List<CORSRule> corsRules = corsResponse.corsRules();
            for (CORSRule rule : corsRules) {
                System.out.println("allowOrigins: " + rule.allowedOrigins());
                System.out.println("AllowedMethod: " + rule.allowedMethods());
            }

        } catch (S3Exception e) {

            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    /**
     * Sets the Cross-Origin Resource Sharing (CORS) rules for an Amazon S3 bucket.
     *
     * @param s3 The S3Client object used to interact with the Amazon S3 service.
     * @param bucketName The name of the S3 bucket to set the CORS rules for.
     * @param accountId The AWS account ID of the bucket owner.
     */
    public static void setCorsInformation(S3Client s3, String bucketName, String accountId) {
        List<String> allowMethods = new ArrayList<>();
        allowMethods.add("PUT");
        allowMethods.add("POST");
        allowMethods.add("DELETE");

        List<String> allowOrigins = new ArrayList<>();
        allowOrigins.add("http://example.com");
        try {
            // Define CORS rules.
            CORSRule corsRule = CORSRule.builder()
                .allowedMethods(allowMethods)
                .allowedOrigins(allowOrigins)
                .build();

            List<CORSRule> corsRules = new ArrayList<>();
            corsRules.add(corsRule);
            CORSConfiguration configuration = CORSConfiguration.builder()
                .corsRules(corsRules)
                .build();

            PutBucketCorsRequest putBucketCorsRequest = PutBucketCorsRequest.builder()
                .bucket(bucketName)
                .corsConfiguration(configuration)
                .expectedBucketOwner(accountId)
                .build();

            s3.putBucketCors(putBucketCorsRequest);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[PutBucketCors](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketCors)」を参照してください。**

### `PutBucketLifecycleConfiguration`
<a name="s3_PutBucketLifecycleConfiguration_java_2_topic"></a>

次のコード例は、`PutBucketLifecycleConfiguration` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter;
import software.amazon.awssdk.services.s3.model.Transition;
import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationRequest;
import software.amazon.awssdk.services.s3.model.GetBucketLifecycleConfigurationResponse;
import software.amazon.awssdk.services.s3.model.DeleteBucketLifecycleRequest;
import software.amazon.awssdk.services.s3.model.TransitionStorageClass;
import software.amazon.awssdk.services.s3.model.LifecycleRule;
import software.amazon.awssdk.services.s3.model.ExpirationStatus;
import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration;
import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import java.util.ArrayList;
import java.util.List;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class LifecycleConfiguration {
    public static void main(String[] args) {
        final String usage = """

            Usage:
              <bucketName> <accountId>\s

            Where:
              bucketName - The Amazon Simple Storage Service (Amazon S3) bucket to upload an object into.
              accountId - The id of the account that owns the Amazon S3 bucket.
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String accountId = args[1];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        setLifecycleConfig(s3, bucketName, accountId);
        getLifecycleConfig(s3, bucketName, accountId);
        deleteLifecycleConfig(s3, bucketName, accountId);
        System.out.println("You have successfully created, updated, and deleted a Lifecycle configuration");
        s3.close();
    }

    /**
     * Sets the lifecycle configuration for an Amazon S3 bucket.
     *
     * @param s3           The Amazon S3 client to use for the operation.
     * @param bucketName   The name of the Amazon S3 bucket.
     * @param accountId    The expected owner of the Amazon S3 bucket.
     *
     * @throws S3Exception if there is an error setting the lifecycle configuration.
     */
    public static void setLifecycleConfig(S3Client s3, String bucketName, String accountId) {
        try {
            // Create a rule to archive objects with the "glacierobjects/" prefix to the
            // S3 Glacier Flexible Retrieval storage class immediately.
            LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder()
                .prefix("glacierobjects/")
                .build();

            Transition transition = Transition.builder()
                .storageClass(TransitionStorageClass.GLACIER)
                .days(0)
                .build();

            LifecycleRule rule1 = LifecycleRule.builder()
                .id("Archive immediately rule")
                .filter(ruleFilter)
                .transitions(transition)
                .status(ExpirationStatus.ENABLED)
                .build();

            // Create a second rule.
            Transition transition2 = Transition.builder()
                .storageClass(TransitionStorageClass.GLACIER)
                .days(0)
                .build();

            List<Transition> transitionList = new ArrayList<>();
            transitionList.add(transition2);

            LifecycleRuleFilter ruleFilter2 = LifecycleRuleFilter.builder()
                .prefix("glacierobjects/")
                .build();

            LifecycleRule rule2 = LifecycleRule.builder()
                .id("Archive and then delete rule")
                .filter(ruleFilter2)
                .transitions(transitionList)
                .status(ExpirationStatus.ENABLED)
                .build();

            // Add the LifecycleRule objects to an ArrayList.
            ArrayList<LifecycleRule> ruleList = new ArrayList<>();
            ruleList.add(rule1);
            ruleList.add(rule2);

            BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder()
                .rules(ruleList)
                .build();

            PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest
                .builder()
                .bucket(bucketName)
                .lifecycleConfiguration(lifecycleConfiguration)
                .expectedBucketOwner(accountId)
                .build();

            s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    /**
     * Retrieves the lifecycle configuration for an Amazon S3 bucket and adds a new lifecycle rule to it.
     *
     * @param s3 the S3Client instance used to interact with Amazon S3
     * @param bucketName the name of the Amazon S3 bucket
     * @param accountId the expected owner of the Amazon S3 bucket
     */
    public static void getLifecycleConfig(S3Client s3, String bucketName, String accountId) {
        try {
            GetBucketLifecycleConfigurationRequest getBucketLifecycleConfigurationRequest = GetBucketLifecycleConfigurationRequest
                .builder()
                .bucket(bucketName)
                .expectedBucketOwner(accountId)
                .build();

            GetBucketLifecycleConfigurationResponse response = s3
                .getBucketLifecycleConfiguration(getBucketLifecycleConfigurationRequest);
            List<LifecycleRule> newList = new ArrayList<>();
            List<LifecycleRule> rules = response.rules();
            for (LifecycleRule rule : rules) {
                newList.add(rule);
            }

            // Add a new rule with both a prefix predicate and a tag predicate.
            LifecycleRuleFilter ruleFilter = LifecycleRuleFilter.builder()
                .prefix("YearlyDocuments/")
                .build();

            Transition transition = Transition.builder()
                .storageClass(TransitionStorageClass.GLACIER)
                .days(3650)
                .build();

            LifecycleRule rule1 = LifecycleRule.builder()
                .id("NewRule")
                .filter(ruleFilter)
                .transitions(transition)
                .status(ExpirationStatus.ENABLED)
                .build();

            // Add the new rule to the list.
            newList.add(rule1);
            BucketLifecycleConfiguration lifecycleConfiguration = BucketLifecycleConfiguration.builder()
                .rules(newList)
                .build();

            PutBucketLifecycleConfigurationRequest putBucketLifecycleConfigurationRequest = PutBucketLifecycleConfigurationRequest
                .builder()
                .bucket(bucketName)
                .lifecycleConfiguration(lifecycleConfiguration)
                .expectedBucketOwner(accountId)
                .build();

            s3.putBucketLifecycleConfiguration(putBucketLifecycleConfigurationRequest);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    /**
     * Deletes the lifecycle configuration for an Amazon S3 bucket.
     *
     * @param s3 the {@link S3Client} to use for the operation
     * @param bucketName the name of the S3 bucket
     * @param accountId the expected account owner of the S3 bucket
     *
     * @throws S3Exception if an error occurs while deleting the lifecycle configuration
     */
    public static void deleteLifecycleConfig(S3Client s3, String bucketName, String accountId) {
        try {
            DeleteBucketLifecycleRequest deleteBucketLifecycleRequest = DeleteBucketLifecycleRequest
                .builder()
                .bucket(bucketName)
                .expectedBucketOwner(accountId)
                .build();

            s3.deleteBucketLifecycle(deleteBucketLifecycleRequest);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketLifecycleConfiguration)」を参照してください。

### `PutBucketPolicy`
<a name="s3_PutBucketPolicy_java_2_topic"></a>

次のコード例は、`PutBucketPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.regions.Region;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class SetBucketPolicy {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <polFile>

            Where:
                bucketName - The Amazon S3 bucket to set the policy on.
                polFile - A JSON file containing the policy (see the Amazon S3 Readme for an example).\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String polFile = args[1];
        String policyText = getBucketPolicyFromFile(polFile);
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        setPolicy(s3, bucketName, policyText);
        s3.close();
    }

    /**
     * Sets the policy for an Amazon S3 bucket.
     *
     * @param s3         the {@link S3Client} object used to interact with the Amazon S3 service
     * @param bucketName the name of the Amazon S3 bucket
     * @param policyText the text of the policy to be set on the bucket
     * @throws S3Exception if there is an error setting the bucket policy
     */
    public static void setPolicy(S3Client s3, String bucketName, String policyText) {
        System.out.println("Setting policy:");
        System.out.println("----");
        System.out.println(policyText);
        System.out.println("----");
        System.out.format("On Amazon S3 bucket: \"%s\"\n", bucketName);

        try {
            PutBucketPolicyRequest policyReq = PutBucketPolicyRequest.builder()
                .bucket(bucketName)
                .policy(policyText)
                .build();

            s3.putBucketPolicy(policyReq);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        System.out.println("Done!");
    }

    /**
     * Retrieves the bucket policy from a specified file.
     *
     * @param policyFile the path to the file containing the bucket policy
     * @return the content of the bucket policy file as a string
     */
    public static String getBucketPolicyFromFile(String policyFile) {
        StringBuilder fileText = new StringBuilder();
        try {
            List<String> lines = Files.readAllLines(Paths.get(policyFile), StandardCharsets.UTF_8);
            for (String line : lines) {
                fileText.append(line);
            }

        } catch (IOException e) {
            System.out.format("Problem reading file: \"%s\"", policyFile);
            System.out.println(e.getMessage());
        }

        try {
            final JsonParser parser = new ObjectMapper().getFactory().createParser(fileText.toString());
            while (parser.nextToken() != null) {
            }

        } catch (IOException jpe) {
            jpe.printStackTrace();
        }
        return fileText.toString();
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[PutBucketPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketPolicy)」を参照してください。**

### `PutBucketReplication`
<a name="s3_PutBucketReplication_java_2_topic"></a>

次のコード例は、`PutBucketReplication` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Sets the replication configuration for an Amazon S3 bucket.
     *
     * @param s3Client             the S3Client instance to use for the operation
     * @param sourceBucketName     the name of the source bucket
     * @param destBucketName       the name of the destination bucket
     * @param destinationBucketARN the Amazon Resource Name (ARN) of the destination bucket
     * @param roleARN              the ARN of the IAM role to use for the replication configuration
     */
    public static void setReplication(S3Client s3Client, String sourceBucketName, String destBucketName, String destinationBucketARN, String roleARN) {
        try {
            Destination destination = Destination.builder()
                .bucket(destinationBucketARN)
                .storageClass(StorageClass.STANDARD)
                .build();

            // Define a prefix filter for replication.
            ReplicationRuleFilter ruleFilter = ReplicationRuleFilter.builder()
                .prefix("documents/")
                .build();

            // Define delete marker replication setting.
            DeleteMarkerReplication deleteMarkerReplication = DeleteMarkerReplication.builder()
                .status(DeleteMarkerReplicationStatus.DISABLED)
                .build();

            // Create the replication rule.
            ReplicationRule replicationRule = ReplicationRule.builder()
                .priority(1)
                .filter(ruleFilter)
                .status(ReplicationRuleStatus.ENABLED)
                .deleteMarkerReplication(deleteMarkerReplication)
                .destination(destination)
                .build();

            List<ReplicationRule> replicationRuleList = new ArrayList<>();
            replicationRuleList.add(replicationRule);

            // Define the replication configuration with IAM role.
            ReplicationConfiguration configuration = ReplicationConfiguration.builder()
                .role(roleARN)
                .rules(replicationRuleList)
                .build();

            // Apply the replication configuration to the source bucket.
            PutBucketReplicationRequest replicationRequest = PutBucketReplicationRequest.builder()
                .bucket(sourceBucketName)
                .replicationConfiguration(configuration)
                .build();

            s3Client.putBucketReplication(replicationRequest);
            System.out.println("Replication configuration set successfully.");

        } catch (IllegalArgumentException e) {
            System.err.println("Configuration error: " + e.getMessage());
        } catch (S3Exception e) {
            System.err.println("S3 Exception: " + e.awsErrorDetails().errorMessage());
            System.err.println("Status Code: " + e.statusCode());
            System.err.println("Error Code: " + e.awsErrorDetails().errorCode());


        } catch (SdkException e) {
            System.err.println("SDK Exception: " + e.getMessage());
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutBucketReplication](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketReplication)」を参照してください。

### `PutBucketVersioning`
<a name="s3_PutBucketVersioning_java_2_topic"></a>

次のコード例は、`PutBucketVersioning` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Enables bucket versioning for the specified S3 bucket.
     *
     * @param s3Client the S3 client to use for the operation
     * @param bucketName the name of the S3 bucket to enable versioning for
     */
    public static void enableBucketVersioning(S3Client s3Client, String bucketName){
        VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder()
            .status(BucketVersioningStatus.ENABLED)
            .build();

        PutBucketVersioningRequest versioningRequest = PutBucketVersioningRequest.builder()
            .bucket(bucketName)
            .versioningConfiguration(versioningConfiguration)
            .build();

        s3Client.putBucketVersioning(versioningRequest);
        System.out.println("Bucket versioning has been enabled for "+bucketName);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutBucketVersioning](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketVersioning)」を参照してください。

### `PutBucketWebsite`
<a name="s3_PutBucketWebsite_java_2_topic"></a>

次のコード例は、`PutBucketWebsite` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.IndexDocument;
import software.amazon.awssdk.services.s3.model.PutBucketWebsiteRequest;
import software.amazon.awssdk.services.s3.model.WebsiteConfiguration;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.regions.Region;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class SetWebsiteConfiguration {
    public static void main(String[] args) {
        final String usage = """

            Usage:    <bucketName> [indexdoc]\s

            Where:
               bucketName   - The Amazon S3 bucket to set the website configuration on.\s
               indexdoc - The index document, ex. 'index.html'
                          If not specified, 'index.html' will be set.
            """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String indexDoc = "index.html";
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        setWebsiteConfig(s3, bucketName, indexDoc);
        s3.close();
    }

    /**
     * Sets the website configuration for an Amazon S3 bucket.
     *
     * @param s3 The {@link S3Client} instance to use for the AWS SDK operations.
     * @param bucketName The name of the S3 bucket to configure.
     * @param indexDoc The name of the index document to use for the website configuration.
     */
    public static void setWebsiteConfig(S3Client s3, String bucketName, String indexDoc) {
        try {
            WebsiteConfiguration websiteConfig = WebsiteConfiguration.builder()
                .indexDocument(IndexDocument.builder().suffix(indexDoc).build())
                .build();

            PutBucketWebsiteRequest pubWebsiteReq = PutBucketWebsiteRequest.builder()
                .bucket(bucketName)
                .websiteConfiguration(websiteConfig)
                .build();

            s3.putBucketWebsite(pubWebsiteReq);
            System.out.println("The call was successful");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「*PutBucketWebsite*」を参照してください。[https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketWebsite](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketWebsite)

### `PutObject`
<a name="s3_PutObject_java_2_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してバケットにファイルをアップロードします。  

```
    /**
     * Uploads a local file to an AWS S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to upload the file to
     * @param key        the key (object name) to use for the uploaded file
     * @param objectPath the local file path of the file to be uploaded
     * @return a {@link CompletableFuture} that completes with the {@link PutObjectResponse} when the upload is successful, or throws a {@link RuntimeException} if the upload fails
     */
    public CompletableFuture<PutObjectResponse> uploadLocalFileAsync(String bucketName, String key, String objectPath) {
        PutObjectRequest objectRequest = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

        CompletableFuture<PutObjectResponse> response = getAsyncClient().putObject(objectRequest, AsyncRequestBody.fromFile(Paths.get(objectPath)));
        return response.whenComplete((resp, ex) -> {
            if (ex != null) {
                throw new RuntimeException("Failed to upload file", ex);
            }
        });
    }
```
[S3TransferManager](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html) を使用してバケットに[ファイルをアップロード](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html#uploadFile(software.amazon.awssdk.transfer.s3.UploadFileRequest))します。[完全なファイル](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadFile.java)と[テスト](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/test/java/TransferManagerTest.java)を表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedFileUpload;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;
import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.UUID;

    public String uploadFile(S3TransferManager transferManager, String bucketName,
                             String key, URI filePathURI) {
        UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
            .putObjectRequest(b -> b.bucket(bucketName).key(key))
            .source(Paths.get(filePathURI))
            .build();

        FileUpload fileUpload = transferManager.uploadFile(uploadFileRequest);

        CompletedFileUpload uploadResult = fileUpload.completionFuture().join();
        return uploadResult.response().eTag();
    }
```
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してオブジェクトをバケットにアップロードし、タグを設定します。  

```
    /**
     * Puts tags on an Amazon S3 object.
     *
     * @param s3 An {@link S3Client} object that represents the Amazon S3 client.
     * @param bucketName The name of the Amazon S3 bucket.
     * @param objectKey The key of the Amazon S3 object.
     * @param objectPath The file path of the object to be uploaded.
     */
    public static void putS3ObjectTags(S3Client s3, String bucketName, String objectKey, String objectPath) {
        try {
            Tag tag1 = Tag.builder()
                .key("Tag 1")
                .value("This is tag 1")
                .build();

            Tag tag2 = Tag.builder()
                .key("Tag 2")
                .value("This is tag 2")
                .build();

            List<Tag> tags = new ArrayList<>();
            tags.add(tag1);
            tags.add(tag2);

            Tagging allTags = Tagging.builder()
                .tagSet(tags)
                .build();

            PutObjectRequest putOb = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .tagging(allTags)
                .build();

            s3.putObject(putOb, RequestBody.fromBytes(getObjectFile(objectPath)));

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Updates the tags associated with an object in an Amazon S3 bucket.
     *
     * @param s3 an instance of the S3Client class, which is used to interact with the Amazon S3 service
     * @param bucketName the name of the S3 bucket containing the object
     * @param objectKey the key (or name) of the object in the S3 bucket
     * @throws S3Exception if there is an error updating the object's tags
     */
    public static void updateObjectTags(S3Client s3, String bucketName, String objectKey) {
        try {
            GetObjectTaggingRequest taggingRequest = GetObjectTaggingRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .build();

            GetObjectTaggingResponse getTaggingRes = s3.getObjectTagging(taggingRequest);
            List<Tag> obTags = getTaggingRes.tagSet();
            for (Tag sinTag : obTags) {
                System.out.println("The tag key is: " + sinTag.key());
                System.out.println("The tag value is: " + sinTag.value());
            }

            // Replace the object's tags with two new tags.
            Tag tag3 = Tag.builder()
                .key("Tag 3")
                .value("This is tag 3")
                .build();

            Tag tag4 = Tag.builder()
                .key("Tag 4")
                .value("This is tag 4")
                .build();

            List<Tag> tags = new ArrayList<>();
            tags.add(tag3);
            tags.add(tag4);

            Tagging updatedTags = Tagging.builder()
                .tagSet(tags)
                .build();

            PutObjectTaggingRequest taggingRequest1 = PutObjectTaggingRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .tagging(updatedTags)
                .build();

            s3.putObjectTagging(taggingRequest1);
            GetObjectTaggingResponse getTaggingRes2 = s3.getObjectTagging(taggingRequest);
            List<Tag> modTags = getTaggingRes2.tagSet();
            for (Tag sinTag : modTags) {
                System.out.println("The tag key is: " + sinTag.key());
                System.out.println("The tag value is: " + sinTag.value());
            }

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    /**
     * Retrieves the contents of a file as a byte array.
     *
     * @param filePath the path of the file to be read
     * @return a byte array containing the contents of the file, or null if an error occurs
     */
    private static byte[] getObjectFile(String filePath) {
        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;

        try {
            File file = new File(filePath);
            bytesArray = new byte[(int) file.length()];
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return bytesArray;
    }
}
```
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してオブジェクトをバケットにアップロードし、メタデータを設定します。  

```
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class PutObjectMetadata {
    public static void main(String[] args) {
        final String USAGE = """

            Usage:
              <bucketName> <objectKey> <objectPath>\s

            Where:
              bucketName - The Amazon S3 bucket to upload an object into.
              objectKey - The object to upload (for example, book.pdf).
              objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).\s
            """;

        if (args.length != 3) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String bucketName = args[0];
        String objectKey = args[1];
        String objectPath = args[2];
        System.out.println("Putting object " + objectKey + " into bucket " + bucketName);
        System.out.println("  in bucket: " + bucketName);
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        putS3Object(s3, bucketName, objectKey, objectPath);
        s3.close();
    }

    /**
     * Uploads an object to an Amazon S3 bucket with metadata.
     *
     * @param s3 the S3Client object used to interact with the Amazon S3 service
     * @param bucketName the name of the S3 bucket to upload the object to
     * @param objectKey the name of the object to be uploaded
     * @param objectPath the local file path of the object to be uploaded
     */
    public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) {
        try {
            Map<String, String> metadata = new HashMap<>();
            metadata.put("author", "Mary Doe");
            metadata.put("version", "1.0.0.0");

            PutObjectRequest putOb = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .metadata(metadata)
                .build();

            s3.putObject(putOb, RequestBody.fromFile(new File(objectPath)));
            System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName);

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
[S3Client](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してオブジェクトをバケットにアップロードし、オブジェクトの保持値を設定します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRetentionRequest;
import software.amazon.awssdk.services.s3.model.ObjectLockRetention;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class PutObjectRetention {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <key> <bucketName>\s

            Where:
                key - The name of the object (for example, book.pdf).\s
                bucketName - The Amazon S3 bucket name that contains the object (for example, bucket1).\s
            """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String key = args[0];
        String bucketName = args[1];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        setRentionPeriod(s3, key, bucketName);
        s3.close();
    }

    /**
     * Sets the retention period for an object in an Amazon S3 bucket.
     *
     * @param s3     the S3Client object used to interact with the Amazon S3 service
     * @param key    the key (name) of the object in the S3 bucket
     * @param bucket the name of the S3 bucket where the object is stored
     *
     * @throws S3Exception if an error occurs while setting the object retention period
     */
    public static void setRentionPeriod(S3Client s3, String key, String bucket) {
        try {
            LocalDate localDate = LocalDate.parse("2020-07-17");
            LocalDateTime localDateTime = localDate.atStartOfDay();
            Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

            ObjectLockRetention lockRetention = ObjectLockRetention.builder()
                .mode("COMPLIANCE")
                .retainUntilDate(instant)
                .build();

            PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder()
                .bucket(bucket)
                .key(key)
                .bypassGovernanceRetention(true)
                .retention(lockRetention)
                .build();

            // To set Retention on an object, the Amazon S3 bucket must support object
            // locking, otherwise an exception is thrown.
            s3.putObjectRetention(retentionRequest);
            System.out.print("An object retention configuration was successfully placed on the object");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObject)」を参照してください。

### `PutObjectLegalHold`
<a name="s3_PutObjectLegalHold_java_2_topic"></a>

次のコード例は、`PutObjectLegalHold` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    // Set or modify a legal hold on an object in an S3 bucket.
    public void modifyObjectLegalHold(String bucketName, String objectKey, boolean legalHoldOn) {
        ObjectLockLegalHold legalHold ;
        if (legalHoldOn) {
            legalHold = ObjectLockLegalHold.builder()
                .status(ObjectLockLegalHoldStatus.ON)
                .build();
        } else {
            legalHold = ObjectLockLegalHold.builder()
                .status(ObjectLockLegalHoldStatus.OFF)
                .build();
        }

        PutObjectLegalHoldRequest legalHoldRequest = PutObjectLegalHoldRequest.builder()
            .bucket(bucketName)
            .key(objectKey)
            .legalHold(legalHold)
            .build();

        getClient().putObjectLegalHold(legalHoldRequest) ;
        System.out.println("Modified legal hold for "+ objectKey +" in "+bucketName +".");
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutObjectLegalHold](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObjectLegalHold)」を参照してください。

### `PutObjectLockConfiguration`
<a name="s3_PutObjectLockConfiguration_java_2_topic"></a>

次のコード例は、`PutObjectLockConfiguration` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットのオブジェクトロック設定を指定します。  

```
    // Enable object lock on an existing bucket.
    public void enableObjectLockOnBucket(String bucketName) {
        try {
            VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder()
                .status(BucketVersioningStatus.ENABLED)
                .build();

            PutBucketVersioningRequest putBucketVersioningRequest = PutBucketVersioningRequest.builder()
                .bucket(bucketName)
                .versioningConfiguration(versioningConfiguration)
                .build();

            // Enable versioning on the bucket.
            getClient().putBucketVersioning(putBucketVersioningRequest);
            PutObjectLockConfigurationRequest request = PutObjectLockConfigurationRequest.builder()
                .bucket(bucketName)
                .objectLockConfiguration(ObjectLockConfiguration.builder()
                    .objectLockEnabled(ObjectLockEnabled.ENABLED)
                    .build())
                .build();

            getClient().putObjectLockConfiguration(request);
            System.out.println("Successfully enabled object lock on "+bucketName);

        } catch (S3Exception ex) {
            System.out.println("Error modifying object lock: '" + ex.getMessage() + "'");
        }
    }
```
バケットのデフォルトの保存期間を設定します。  

```
    // Set or modify a retention period on an S3 bucket.
    public void modifyBucketDefaultRetention(String bucketName) {
        VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder()
            .mfaDelete(MFADelete.DISABLED)
            .status(BucketVersioningStatus.ENABLED)
            .build();

        PutBucketVersioningRequest versioningRequest = PutBucketVersioningRequest.builder()
            .bucket(bucketName)
            .versioningConfiguration(versioningConfiguration)
            .build();

        getClient().putBucketVersioning(versioningRequest);
        DefaultRetention rention = DefaultRetention.builder()
            .days(1)
            .mode(ObjectLockRetentionMode.GOVERNANCE)
            .build();

        ObjectLockRule lockRule = ObjectLockRule.builder()
            .defaultRetention(rention)
            .build();

        ObjectLockConfiguration objectLockConfiguration = ObjectLockConfiguration.builder()
            .objectLockEnabled(ObjectLockEnabled.ENABLED)
            .rule(lockRule)
            .build();

        PutObjectLockConfigurationRequest putObjectLockConfigurationRequest = PutObjectLockConfigurationRequest.builder()
            .bucket(bucketName)
            .objectLockConfiguration(objectLockConfiguration)
            .build();

        getClient().putObjectLockConfiguration(putObjectLockConfigurationRequest) ;
        System.out.println("Added a default retention to bucket "+bucketName +".");
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutObjectLockConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObjectLockConfiguration)」を参照してください。

### `PutObjectRetention`
<a name="s3_PutObjectRetention_java_2_topic"></a>

次のコード例は、`PutObjectRetention` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    // Set or modify a retention period on an object in an S3 bucket.
    public void modifyObjectRetentionPeriod(String bucketName, String objectKey) {
        // Calculate the instant one day from now.
        Instant futureInstant = Instant.now().plus(1, ChronoUnit.DAYS);

        // Convert the Instant to a ZonedDateTime object with a specific time zone.
        ZonedDateTime zonedDateTime = futureInstant.atZone(ZoneId.systemDefault());

        // Define a formatter for human-readable output.
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // Format the ZonedDateTime object to a human-readable date string.
        String humanReadableDate = formatter.format(zonedDateTime);

        // Print the formatted date string.
        System.out.println("Formatted Date: " + humanReadableDate);
        ObjectLockRetention retention = ObjectLockRetention.builder()
            .mode(ObjectLockRetentionMode.GOVERNANCE)
            .retainUntilDate(futureInstant)
            .build();

        PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder()
            .bucket(bucketName)
            .key(objectKey)
            .retention(retention)
            .build();

        getClient().putObjectRetention(retentionRequest);
        System.out.println("Set retention for "+objectKey +" in " +bucketName +" until "+ humanReadableDate +".");
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutObjectRetention](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObjectRetention)」を参照してください。

### `RestoreObject`
<a name="s3_RestoreObject_java_2_topic"></a>

次のコード例は、`RestoreObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.RestoreRequest;
import software.amazon.awssdk.services.s3.model.GlacierJobParameters;
import software.amazon.awssdk.services.s3.model.RestoreObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.Tier;

/*
 *  For more information about restoring an object, see "Restoring an archived object" at
 *  https://docs.aws.amazon.com/AmazonS3/latest/userguide/restoring-objects.html
 *
 *  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 RestoreObject {
    public static void main(String[] args) {
        final String usage = """

            Usage:
                <bucketName> <keyName> <expectedBucketOwner>

            Where:
                bucketName - The Amazon S3 bucket name.\s
                keyName - The key name of an object with a Storage class value of Glacier.\s
                expectedBucketOwner - The account that owns the bucket (you can obtain this value from the AWS Management Console).\s
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String keyName = args[1];
        String expectedBucketOwner = args[2];
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder()
            .region(region)
            .build();

        restoreS3Object(s3, bucketName, keyName, expectedBucketOwner);
        s3.close();
    }

    /**
     * Restores an S3 object from the Glacier storage class.
     *
     * @param s3                   an instance of the {@link S3Client} to be used for interacting with Amazon S3
     * @param bucketName           the name of the S3 bucket where the object is stored
     * @param keyName              the key (object name) of the S3 object to be restored
     * @param expectedBucketOwner  the AWS account ID of the expected bucket owner
     */
    public static void restoreS3Object(S3Client s3, String bucketName, String keyName, String expectedBucketOwner) {
        try {
            RestoreRequest restoreRequest = RestoreRequest.builder()
                .days(10)
                .glacierJobParameters(GlacierJobParameters.builder().tier(Tier.STANDARD).build())
                .build();

            RestoreObjectRequest objectRequest = RestoreObjectRequest.builder()
                .expectedBucketOwner(expectedBucketOwner)
                .bucket(bucketName)
                .key(keyName)
                .restoreRequest(restoreRequest)
                .build();

            s3.restoreObject(objectRequest);

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[RestoreObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/RestoreObject)」を参照してください。

### `SelectObjectContent`
<a name="s3_SelectObjectContent_java_2_topic"></a>

次のコード例は、`SelectObjectContent` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
次の例は、JSON オブジェクトを使用したクエリを示しています。[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/async/SelectObjectContentExample.java)では、CSV オブジェクトの使用も示しています。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.BlockingInputStreamAsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.CSVInput;
import software.amazon.awssdk.services.s3.model.CSVOutput;
import software.amazon.awssdk.services.s3.model.CompressionType;
import software.amazon.awssdk.services.s3.model.ExpressionType;
import software.amazon.awssdk.services.s3.model.FileHeaderInfo;
import software.amazon.awssdk.services.s3.model.InputSerialization;
import software.amazon.awssdk.services.s3.model.JSONInput;
import software.amazon.awssdk.services.s3.model.JSONOutput;
import software.amazon.awssdk.services.s3.model.JSONType;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.OutputSerialization;
import software.amazon.awssdk.services.s3.model.Progress;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.SelectObjectContentRequest;
import software.amazon.awssdk.services.s3.model.SelectObjectContentResponseHandler;
import software.amazon.awssdk.services.s3.model.Stats;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

public class SelectObjectContentExample {
    static final Logger logger = LoggerFactory.getLogger(SelectObjectContentExample.class);
    static final String BUCKET_NAME = "amzn-s3-demo-bucket-" + UUID.randomUUID();
    static final S3AsyncClient s3AsyncClient = S3AsyncClient.create();
    static String FILE_CSV = "csv";
    static String FILE_JSON = "json";
    static String URL_CSV = "https://raw.githubusercontent.com/mledoze/countries/master/dist/countries.csv";
    static String URL_JSON = "https://raw.githubusercontent.com/mledoze/countries/master/dist/countries.json";

    public static void main(String[] args) {
        SelectObjectContentExample selectObjectContentExample = new SelectObjectContentExample();
        try {
            SelectObjectContentExample.setUp();
            selectObjectContentExample.runSelectObjectContentMethodForJSON();
            selectObjectContentExample.runSelectObjectContentMethodForCSV();
        } catch (SdkException e) {
            logger.error(e.getMessage(), e);
            System.exit(1);
        } finally {
            SelectObjectContentExample.tearDown();
        }
    }

    EventStreamInfo runSelectObjectContentMethodForJSON() {
        // Set up request parameters.
        final String queryExpression = "select * from s3object[*][*] c where c.area < 350000";
        final String fileType = FILE_JSON;

        InputSerialization inputSerialization = InputSerialization.builder()
                .json(JSONInput.builder().type(JSONType.DOCUMENT).build())
                .compressionType(CompressionType.NONE)
                .build();

        OutputSerialization outputSerialization = OutputSerialization.builder()
                .json(JSONOutput.builder().recordDelimiter(null).build())
                .build();

        // Build the SelectObjectContentRequest.
        SelectObjectContentRequest select = SelectObjectContentRequest.builder()
                .bucket(BUCKET_NAME)
                .key(FILE_JSON)
                .expression(queryExpression)
                .expressionType(ExpressionType.SQL)
                .inputSerialization(inputSerialization)
                .outputSerialization(outputSerialization)
                .build();

        EventStreamInfo eventStreamInfo = new EventStreamInfo();
        // Call the selectObjectContent method with the request and a response handler.
        // Supply an EventStreamInfo object to the response handler to gather records and information from the response.
        s3AsyncClient.selectObjectContent(select, buildResponseHandler(eventStreamInfo)).join();

        // Log out information gathered while processing the response stream.
        long recordCount = eventStreamInfo.getRecords().stream().mapToInt(record ->
                record.split("\n").length
        ).sum();
        logger.info("Total records {}: {}", fileType, recordCount);
        logger.info("Visitor onRecords for fileType {} called {} times", fileType, eventStreamInfo.getCountOnRecordsCalled());
        logger.info("Visitor onStats for fileType {}, {}", fileType, eventStreamInfo.getStats());
        logger.info("Visitor onContinuations for fileType {}, {}", fileType, eventStreamInfo.getCountContinuationEvents());
        return eventStreamInfo;
    }

    static SelectObjectContentResponseHandler buildResponseHandler(EventStreamInfo eventStreamInfo) {
        // Use a Visitor to process the response stream. This visitor logs information and gathers details while processing.
        final SelectObjectContentResponseHandler.Visitor visitor = SelectObjectContentResponseHandler.Visitor.builder()
                .onRecords(r -> {
                    logger.info("Record event received.");
                    eventStreamInfo.addRecord(r.payload().asUtf8String());
                    eventStreamInfo.incrementOnRecordsCalled();
                })
                .onCont(ce -> {
                    logger.info("Continuation event received.");
                    eventStreamInfo.incrementContinuationEvents();
                })
                .onProgress(pe -> {
                    Progress progress = pe.details();
                    logger.info("Progress event received:\n bytesScanned:{}\nbytesProcessed: {}\nbytesReturned:{}",
                            progress.bytesScanned(),
                            progress.bytesProcessed(),
                            progress.bytesReturned());
                })
                .onEnd(ee -> logger.info("End event received."))
                .onStats(se -> {
                    logger.info("Stats event received.");
                    eventStreamInfo.addStats(se.details());
                })
                .build();

        // Build the SelectObjectContentResponseHandler with the visitor that processes the stream.
        return SelectObjectContentResponseHandler.builder()
                .subscriber(visitor).build();
    }

    // The EventStreamInfo class is used to store information gathered while processing the response stream.
    static class EventStreamInfo {
        private final List<String> records = new ArrayList<>();
        private Integer countOnRecordsCalled = 0;
        private Integer countContinuationEvents = 0;
        private Stats stats;

        void incrementOnRecordsCalled() {
            countOnRecordsCalled++;
        }

        void incrementContinuationEvents() {
            countContinuationEvents++;
        }

        void addRecord(String record) {
            records.add(record);
        }

        void addStats(Stats stats) {
            this.stats = stats;
        }

        public List<String> getRecords() {
            return records;
        }

        public Integer getCountOnRecordsCalled() {
            return countOnRecordsCalled;
        }

        public Integer getCountContinuationEvents() {
            return countContinuationEvents;
        }

        public Stats getStats() {
            return stats;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SelectObjectContent](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/SelectObjectContent)」を参照してください。

### `UploadPartCopy`
<a name="s3_UploadPartCopy_java_2_topic"></a>

次のコード例は、`UploadPartCopy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    public CompletableFuture<String> performMultiCopy(String toBucket, String bucketName, String key) {
        CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder()
            .bucket(toBucket)
            .key(key)
            .build();

        getAsyncClient().createMultipartUpload(createMultipartUploadRequest)
            .thenApply(createMultipartUploadResponse -> {
                String uploadId = createMultipartUploadResponse.uploadId();
                System.out.println("Upload ID: " + uploadId);

                UploadPartCopyRequest uploadPartCopyRequest = UploadPartCopyRequest.builder()
                    .sourceBucket(bucketName)
                    .destinationBucket(toBucket)
                    .sourceKey(key)
                    .destinationKey(key)
                    .uploadId(uploadId)  // Use the valid uploadId.
                    .partNumber(1)  // Ensure the part number is correct.
                    .copySourceRange("bytes=0-1023")  // Adjust range as needed
                    .build();

                return getAsyncClient().uploadPartCopy(uploadPartCopyRequest);
            })
            .thenCompose(uploadPartCopyFuture -> uploadPartCopyFuture)
            .whenComplete((uploadPartCopyResponse, exception) -> {
                if (exception != null) {
                    // Handle any exceptions.
                    logger.error("Error during upload part copy: " + exception.getMessage());
                } else {
                    // Successfully completed the upload part copy.
                    System.out.println("Upload Part Copy completed successfully. ETag: " + uploadPartCopyResponse.copyPartResult().eTag());
                }
            });
        return null;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UploadPartCopy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/UploadPartCopy)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### バケットが存在するかどうかを確認する
<a name="s3_Scenario_DoesBucketExist_java_2_topic"></a>

次のコード例は、バケットが存在するかどうかを確認する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
SDK for Java V1 [AmazonS3Client\$1doesBucketExistV2 (文字列)](https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3Client.html#doesBucketExistV2-java.lang.String-) メソッドの代わりに、次の `doesBucketExists` メソッドを使用できます。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.http.HttpStatusCode;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.utils.Validate;

public class DoesBucketExist {
    private static final Logger logger = LoggerFactory.getLogger(DoesBucketExist.class);

    public static void main(String[] args) {
        DoesBucketExist doesBucketExist = new DoesBucketExist();

        final S3Client s3SyncClient = S3Client.builder().build();
        final String bucketName = "amzn-s3-demo-bucket"; // Change to the bucket name that you want to check.

        boolean exists = doesBucketExist.doesBucketExist(bucketName, s3SyncClient);
        logger.info("Bucket exists: {}", exists);
    }

    /**
     * Checks if the specified bucket exists. Amazon S3 buckets are named in a global namespace; use this method to
     * determine if a specified bucket name already exists, and therefore can't be used to create a new bucket.
     * <p>
     * Internally this method uses the <a
     * href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html#getBucketAcl(java.util.function.Consumer)">S3Client.getBucketAcl(String)</a>
     * operation to determine whether the bucket exists.
     * <p>
     * This method is equivalent to the AWS SDK for Java V1's <a
     * href="https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3Client.html#doesBucketExistV2-java.lang.String-">AmazonS3Client#doesBucketExistV2(String)</a>.
     *
     * @param bucketName   The name of the bucket to check.
     * @param s3SyncClient An <code>S3Client</code> instance. The method checks for the bucket in the AWS Region
     *                     configured on the instance.
     * @return The value true if the specified bucket exists in Amazon S3; the value false if there is no bucket in
     *         Amazon S3 with that name.
     */
    public boolean doesBucketExist(String bucketName, S3Client s3SyncClient) {
        try {
            Validate.notEmpty(bucketName, "The bucket name must not be null or an empty string.", "");
            s3SyncClient.getBucketAcl(r -> r.bucket(bucketName));
            return true;
        } catch (AwsServiceException ase) {
            // A redirect error or an AccessDenied exception means the bucket exists but it's not in this region
            // or we don't have permissions to it.
            if ((ase.statusCode() == HttpStatusCode.MOVED_PERMANENTLY) || "AccessDenied".equals(ase.awsErrorDetails().errorCode())) {
                return true;
            }
            if (ase.statusCode() == HttpStatusCode.NOT_FOUND) {
                return false;
            }
            throw ase;
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetBucketAcl](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetBucketAcl)」を参照してください。

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_java_2_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
以下は、署名付き URL を作成し、HTTP クライアントライブラリで URL を使用する 3 つの例を示しています。  
+ 3 つの HTTP クライアントライブラリで URL を使用する HTTP GET リクエスト
+ 3 つの HTTP クライアントライブラリで URL を使用する、メタデータ付きヘッダーを持つ HTTP PUT リクエスト
+ 1 つの HTTP クライアントライブラリで URL を使用する、クエリパラメータを含む HTTP PUT リクエスト
 オブジェクトの署名付き URL を生成して、オブジェクトをダウンロードします (GET リクエスト)。  
インポート。  

```
import com.example.s3.util.PresignUrlUtils;
import org.slf4j.Logger;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;
import software.amazon.awssdk.utils.IoUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.UUID;
```
URL を生成する。  

```
    /* Create a pre-signed URL to download an object in a subsequent GET request. */
    public String createPresignedGetUrl(String bucketName, String keyName) {
        try (S3Presigner presigner = S3Presigner.create()) {

            GetObjectRequest objectRequest = GetObjectRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .build();

            GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder()
                    .signatureDuration(Duration.ofMinutes(10))  // The URL will expire in 10 minutes.
                    .getObjectRequest(objectRequest)
                    .build();

            PresignedGetObjectRequest presignedRequest = presigner.presignGetObject(presignRequest);
            logger.info("Presigned URL: [{}]", presignedRequest.url().toString());
            logger.info("HTTP method: [{}]", presignedRequest.httpRequest().method());

            return presignedRequest.url().toExternalForm();
        }
    }
```
次の 3 つの方法のいずれかを使用して、オブジェクトをダウンロードします。  
JDK `HttpURLConnection` (v1.1 以降) クラスを使用してダウンロードを行います。  

```
    /* Use the JDK HttpURLConnection (since v1.1) class to do the download. */
    public byte[] useHttpUrlConnectionToGet(String presignedUrlString) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Capture the response body to a byte array.

        try {
            URL presignedUrl = new URL(presignedUrlString);
            HttpURLConnection connection = (HttpURLConnection) presignedUrl.openConnection();
            connection.setRequestMethod("GET");
            // Download the result of executing the request.
            try (InputStream content = connection.getInputStream()) {
                IoUtils.copy(content, byteArrayOutputStream);
            }
            logger.info("HTTP response code is " + connection.getResponseCode());

        } catch (S3Exception | IOException e) {
            logger.error(e.getMessage(), e);
        }
        return byteArrayOutputStream.toByteArray();
    }
```
JDK `HttpClient` (v11 以降) クラスを使用してダウンロードを行います。  

```
    /* Use the JDK HttpClient (since v11) class to do the download. */
    public byte[] useHttpClientToGet(String presignedUrlString) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Capture the response body to a byte array.

        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder();
        HttpClient httpClient = HttpClient.newHttpClient();
        try {
            URL presignedUrl = new URL(presignedUrlString);
            HttpResponse<InputStream> response = httpClient.send(requestBuilder
                            .uri(presignedUrl.toURI())
                            .GET()
                            .build(),
                    HttpResponse.BodyHandlers.ofInputStream());

            IoUtils.copy(response.body(), byteArrayOutputStream);

            logger.info("HTTP response code is " + response.statusCode());

        } catch (URISyntaxException | InterruptedException | IOException e) {
            logger.error(e.getMessage(), e);
        }
        return byteArrayOutputStream.toByteArray();
    }
```
 AWS SDK for Java `SdkHttpClient` クラスを使用してダウンロードを行います。  

```
    /* Use the AWS SDK for Java SdkHttpClient class to do the download. */
    public byte[] useSdkHttpClientToGet(String presignedUrlString) {

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); // Capture the response body to a byte array.
        try {
            URL presignedUrl = new URL(presignedUrlString);
            SdkHttpRequest request = SdkHttpRequest.builder()
                    .method(SdkHttpMethod.GET)
                    .uri(presignedUrl.toURI())
                    .build();

            HttpExecuteRequest executeRequest = HttpExecuteRequest.builder()
                    .request(request)
                    .build();

            try (SdkHttpClient sdkHttpClient = ApacheHttpClient.create()) {
                HttpExecuteResponse response = sdkHttpClient.prepareRequest(executeRequest).call();
                response.responseBody().ifPresentOrElse(
                        abortableInputStream -> {
                            try {
                                IoUtils.copy(abortableInputStream, byteArrayOutputStream);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        },
                        () -> logger.error("No response body."));

                logger.info("HTTP Response code is {}", response.httpResponse().statusCode());
            }
        } catch (URISyntaxException | IOException e) {
            logger.error(e.getMessage(), e);
        }
        return byteArrayOutputStream.toByteArray();
    }
```
アップロード用に、ヘッダーにメタデータを含む署名付き URL を生成して、ファイルをアップロードします (PUT リクエスト)。  
インポート。  

```
import com.example.s3.util.PresignUrlUtils;
import org.slf4j.Logger;
import software.amazon.awssdk.core.internal.sync.FileContentStreamProvider;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest;
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
```
URL を生成する。  

```
    /* Create a presigned URL to use in a subsequent PUT request */
    public String createPresignedUrl(String bucketName, String keyName, Map<String, String> metadata) {
        try (S3Presigner presigner = S3Presigner.create()) {

            PutObjectRequest objectRequest = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .metadata(metadata)
                    .build();

            PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
                    .signatureDuration(Duration.ofMinutes(10))  // The URL expires in 10 minutes.
                    .putObjectRequest(objectRequest)
                    .build();


            PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest);
            String myURL = presignedRequest.url().toString();
            logger.info("Presigned URL to upload a file to: [{}]", myURL);
            logger.info("HTTP method: [{}]", presignedRequest.httpRequest().method());

            return presignedRequest.url().toExternalForm();
        }
    }
```
次の 3 つの方法のいずれかを使用して、オブジェクトをアップロードします。  
JDK `HttpURLConnection` (v1.1 以降) クラスを使用してアップロードを行います。  

```
    /* Use the JDK HttpURLConnection (since v1.1) class to do the upload. */
    public void useHttpUrlConnectionToPut(String presignedUrlString, File fileToPut, Map<String, String> metadata) {
        logger.info("Begin [{}] upload", fileToPut.toString());
        try {
            URL presignedUrl = new URL(presignedUrlString);
            HttpURLConnection connection = (HttpURLConnection) presignedUrl.openConnection();
            connection.setDoOutput(true);
            metadata.forEach((k, v) -> connection.setRequestProperty("x-amz-meta-" + k, v));
            connection.setRequestMethod("PUT");
            OutputStream out = connection.getOutputStream();

            try (RandomAccessFile file = new RandomAccessFile(fileToPut, "r");
                 FileChannel inChannel = file.getChannel()) {
                ByteBuffer buffer = ByteBuffer.allocate(8192); //Buffer size is 8k

                while (inChannel.read(buffer) > 0) {
                    buffer.flip();
                    for (int i = 0; i < buffer.limit(); i++) {
                        out.write(buffer.get());
                    }
                    buffer.clear();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }

            out.close();
            connection.getResponseCode();
            logger.info("HTTP response code is " + connection.getResponseCode());

        } catch (S3Exception | IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
```
JDK `HttpClient` (v11 以降) クラスを使用してアップロードを行います。  

```
    /* Use the JDK HttpClient (since v11) class to do the upload. */
    public void useHttpClientToPut(String presignedUrlString, File fileToPut, Map<String, String> metadata) {
        logger.info("Begin [{}] upload", fileToPut.toString());

        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder();
        metadata.forEach((k, v) -> requestBuilder.header("x-amz-meta-" + k, v));

        HttpClient httpClient = HttpClient.newHttpClient();
        try {
            final HttpResponse<Void> response = httpClient.send(requestBuilder
                            .uri(new URL(presignedUrlString).toURI())
                            .PUT(HttpRequest.BodyPublishers.ofFile(Path.of(fileToPut.toURI())))
                            .build(),
                    HttpResponse.BodyHandlers.discarding());

            logger.info("HTTP response code is " + response.statusCode());

        } catch (URISyntaxException | InterruptedException | IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
```
 AWS for Java V2 `SdkHttpClient` クラスを使用してアップロードを行います。  

```
    /* Use the AWS SDK for Java V2 SdkHttpClient class to do the upload. */
    public void useSdkHttpClientToPut(String presignedUrlString, File fileToPut, Map<String, String> metadata) {
        logger.info("Begin [{}] upload", fileToPut.toString());

        try {
            URL presignedUrl = new URL(presignedUrlString);

            SdkHttpRequest.Builder requestBuilder = SdkHttpRequest.builder()
                    .method(SdkHttpMethod.PUT)
                    .uri(presignedUrl.toURI());
            // Add headers
            metadata.forEach((k, v) -> requestBuilder.putHeader("x-amz-meta-" + k, v));
            // Finish building the request.
            SdkHttpRequest request = requestBuilder.build();

            HttpExecuteRequest executeRequest = HttpExecuteRequest.builder()
                    .request(request)
                    .contentStreamProvider(new FileContentStreamProvider(fileToPut.toPath()))
                    .build();

            try (SdkHttpClient sdkHttpClient = ApacheHttpClient.create()) {
                HttpExecuteResponse response = sdkHttpClient.prepareRequest(executeRequest).call();
                logger.info("Response code: {}", response.httpResponse().statusCode());
            }
        } catch (URISyntaxException | IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
```
アップロード用に、クエリパラメータを含む署名付き URL を生成して、ファイルをアップロードします (PUT リクエスト)。  
インポート。  

```
import com.example.s3.util.PresignUrlUtils;
import org.slf4j.Logger;
import software.amazon.awssdk.awscore.AwsRequestOverrideConfiguration;
import software.amazon.awssdk.core.internal.sync.FileContentStreamProvider;
import software.amazon.awssdk.http.HttpExecuteRequest;
import software.amazon.awssdk.http.HttpExecuteResponse;
import software.amazon.awssdk.http.SdkHttpClient;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.http.apache.ApacheHttpClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.PresignedPutObjectRequest;
import software.amazon.awssdk.services.s3.presigner.model.PutObjectPresignRequest;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Map;
import java.util.UUID;
```
URL を生成する。  

```
    /**
     *  Creates a presigned URL to use in a subsequent HTTP PUT request. The code adds query parameters
     *  to the request instead of using headers. By using query parameters, you do not need to add the
     *  the parameters as headers when the PUT request is eventually sent.
     *
     * @param bucketName Bucket name where the object will be uploaded.
     * @param keyName Key name of the object that will be uploaded.
     * @param queryParams Query string parameters to be added to the presigned URL.
     * @return
     */
    public String createPresignedUrl(String bucketName, String keyName, Map<String, String> queryParams) {
        try (S3Presigner presigner = S3Presigner.create()) {
            // Create an override configuration to store the query parameters.
            AwsRequestOverrideConfiguration.Builder overrideConfigurationBuilder = AwsRequestOverrideConfiguration.builder();

            queryParams.forEach(overrideConfigurationBuilder::putRawQueryParameter);

            PutObjectRequest objectRequest = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(keyName)
                    .overrideConfiguration(overrideConfigurationBuilder.build()) // Add the override configuration.
                    .build();

            PutObjectPresignRequest presignRequest = PutObjectPresignRequest.builder()
                    .signatureDuration(Duration.ofMinutes(10))  // The URL expires in 10 minutes.
                    .putObjectRequest(objectRequest)
                    .build();


            PresignedPutObjectRequest presignedRequest = presigner.presignPutObject(presignRequest);
            String myURL = presignedRequest.url().toString();
            logger.info("Presigned URL to upload a file to: [{}]", myURL);
            logger.info("HTTP method: [{}]", presignedRequest.httpRequest().method());

            return presignedRequest.url().toExternalForm();
        }
    }
```
 AWS for Java V2 `SdkHttpClient` クラスを使用してアップロードを行います。  

```
    /**
     * Use the AWS SDK for Java V2 SdkHttpClient class to execute the PUT request. Since the
     * URL contains the query parameters, no headers are needed for metadata, SSE settings, or ACL settings.
     *
     * @param presignedUrlString The URL for the PUT request.
     * @param fileToPut File to uplaod
     */
    public void useSdkHttpClientToPut(String presignedUrlString, File fileToPut) {
        logger.info("Begin [{}] upload", fileToPut.toString());

        try {
            URL presignedUrl = new URL(presignedUrlString);

            SdkHttpRequest.Builder requestBuilder = SdkHttpRequest.builder()
                    .method(SdkHttpMethod.PUT)
                    .uri(presignedUrl.toURI());

            SdkHttpRequest request = requestBuilder.build();

            HttpExecuteRequest executeRequest = HttpExecuteRequest.builder()
                    .request(request)
                    .contentStreamProvider(new FileContentStreamProvider(fileToPut.toPath()))
                    .build();

            try (SdkHttpClient sdkHttpClient = ApacheHttpClient.create()) {
                HttpExecuteResponse response = sdkHttpClient.prepareRequest(executeRequest).call();
                logger.info("Response code: {}", response.httpResponse().statusCode());
            }
        } catch (URISyntaxException | IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
```

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_java_2_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Java 2.x**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 不完全なマルチパートアップロードを特定する
<a name="s3_Scenario_AbortMultipartUpload_java_2_topic"></a>

次のコード例は、不完全な Amazon S3 マルチパートアップロードを削除または停止する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
何らかの理由で進行中または不完全なマルチパートアップロードを停止するには、次の例に示すように、リストアップロードを取得してから削除します。  

```
    /**
     * Aborts all incomplete multipart uploads from the specified S3 bucket.
     * <p>
     * This method retrieves a list of all incomplete multipart uploads in the specified S3 bucket,
     * and then aborts each of those uploads.
     */
    public static void abortIncompleteMultipartUploadsFromList() {
        ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder()
            .bucket(bucketName)
            .build();

        ListMultipartUploadsResponse response = s3Client.listMultipartUploads(listMultipartUploadsRequest);
        List<MultipartUpload> uploads = response.uploads();

        AbortMultipartUploadRequest abortMultipartUploadRequest;
        for (MultipartUpload upload : uploads) {
            abortMultipartUploadRequest = AbortMultipartUploadRequest.builder()
                .bucket(bucketName)
                .key(upload.key())
                .expectedBucketOwner(accountId)
                .uploadId(upload.uploadId())
                .build();

            AbortMultipartUploadResponse abortMultipartUploadResponse = s3Client.abortMultipartUpload(abortMultipartUploadRequest);
            if (abortMultipartUploadResponse.sdkHttpResponse().isSuccessful()) {
                logger.info("Upload ID [{}] to bucket [{}] successfully aborted.", upload.uploadId(), bucketName);
            }
        }
    }
```
日付の前後に開始された不完全なマルチパートアップロードを削除するには、次の例に示すように、特定の時点に基づいてマルチパートアップロードを選択的に削除します。  

```
    static void abortIncompleteMultipartUploadsOlderThan(Instant pointInTime) {
        ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder()
            .bucket(bucketName)
            .build();

        ListMultipartUploadsResponse response = s3Client.listMultipartUploads(listMultipartUploadsRequest);
        List<MultipartUpload> uploads = response.uploads();

        AbortMultipartUploadRequest abortMultipartUploadRequest;
        for (MultipartUpload upload : uploads) {
            logger.info("Found multipartUpload with upload ID [{}], initiated [{}]", upload.uploadId(), upload.initiated());
            if (upload.initiated().isBefore(pointInTime)) {
                abortMultipartUploadRequest = AbortMultipartUploadRequest.builder()
                    .bucket(bucketName)
                    .key(upload.key())
                    .expectedBucketOwner(accountId)
                    .uploadId(upload.uploadId())
                    .build();

                AbortMultipartUploadResponse abortMultipartUploadResponse = s3Client.abortMultipartUpload(abortMultipartUploadRequest);
                if (abortMultipartUploadResponse.sdkHttpResponse().isSuccessful()) {
                    logger.info("Upload ID [{}] to bucket [{}] successfully aborted.", upload.uploadId(), bucketName);
                }
            }
        }
    }
```
マルチパートアップロードの開始後にアップロード ID にアクセスできる場合は、その ID を使用して進行中のアップロードを削除できます。  

```
    static void abortMultipartUploadUsingUploadId() {
        String uploadId = startUploadReturningUploadId();
        AbortMultipartUploadResponse response = s3Client.abortMultipartUpload(b -> b
            .uploadId(uploadId)
            .bucket(bucketName)
            .key(key));

        if (response.sdkHttpResponse().isSuccessful()) {
            logger.info("Upload ID [{}] to bucket [{}] successfully aborted.", uploadId, bucketName);
        }
    }
```
特定の日数だけ古い不完全なマルチパートアップロードを一貫して削除するには、バケットのバケットライフサイクル設定を設定します。次の例は、7 日以上経過した不完全なアップロードを削除するルールを作成する方法を示しています。  

```
    static void abortMultipartUploadsUsingLifecycleConfig() {
        Collection<LifecycleRule> lifeCycleRules = List.of(LifecycleRule.builder()
            .abortIncompleteMultipartUpload(b -> b.
                daysAfterInitiation(7))
            .status("Enabled")
            .filter(SdkBuilder::build) // Filter element is required.
            .build());

        // If the action is successful, the service sends back an HTTP 200 response with an empty HTTP body.
        PutBucketLifecycleConfigurationResponse response = s3Client.putBucketLifecycleConfiguration(b -> b
            .bucket(bucketName)
            .lifecycleConfiguration(b1 -> b1.rules(lifeCycleRules)));

        if (response.sdkHttpResponse().isSuccessful()) {
            logger.info("Rule to abort incomplete multipart uploads added to bucket.");
        } else {
            logger.error("Unsuccessfully applied rule. HTTP status code is [{}]", response.sdkHttpResponse().statusCode());
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AbortMultipartUpload](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/AbortMultipartUpload)
  + [ListMultipartUploads](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListMultipartUploads)
  + [PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketLifecycleConfiguration)

### 画像内の PPE を検出する
<a name="cross_RekognitionPhotoAnalyzerPPE_java_2_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内の個人用防護具 (PPE) を検出するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 個人用保護具を使用してイメージを検出する AWS Lambda 関数を作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_ppe) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_java_2_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用して、Amazon Rekognition を使用し、　Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内でカテゴリ別にオブジェクトを識別するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_photo_analyzer_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_java_2_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用し、Amazon Simple Storage Service (Amazon S3) バケットにあるビデオ内で顔やオブジェクトを検出するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/video_analyzer_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### S3 の「ディレクトリ」をダウンロードする
<a name="s3_Scenario_DownloadS3Directory_java_2_topic"></a>

次のコード例は、Amazon S3 バケットの「ディレクトリ」の内容をダウンロードしてフィルタリングする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
この例では、 で [S3TransferManager](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html) AWS SDK for Java 2.x を使用して Amazon S3 バケットから「ディレクトリ」をダウンロードする方法を示します。また、リクエストで [DownloadFilters](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/config/DownloadFilter.html) を使用する方法も示します。  

```
    /**
     * For standard buckets, S3 provides the illusion of a directory structure through the use of keys. When you upload
     * an object to an S3 bucket, you specify a key, which is essentially the "path" to the object. The key can contain
     * forward slashes ("/") to make it appear as if the object is stored in a directory structure, but this is just a
     * logical representation, not an actual directory.
     * <p><pre>
     * In this example, our S3 bucket contains the following objects:
     *
     * folder1/file1.txt
     * folder1/file2.txt
     * folder1/file3.txt
     * folder2/file1.txt
     * folder2/file2.txt
     * folder2/file3.txt
     * folder3/file1.txt
     * folder3/file2.txt
     * folder3/file3.txt
     *
     * When method `downloadS3Directories` is invoked with
     * `destinationPathURI` set to `/test`, the downloaded
     * directory looks like:
     *
     * |- test
     *    |- folder1
     *    	  |- file1.txt
     *    	  |- file2.txt
     *    	  |- file3.txt
     *    |- folder3
     *    	  |- file1.txt
     *    	  |- file2.txt
     *    	  |- file3.txt
     * </pre>
     *
     * @param transferManager    An S3TransferManager instance.
     * @param destinationPathURI local directory to hold the downloaded S3 'directories' and files.
     * @param bucketName         The S3 bucket that contains the 'directories' to download.
     * @return The number of objects (files, in this case) that were downloaded.
     */
    public Integer downloadS3Directories(S3TransferManager transferManager,
                                         URI destinationPathURI, String bucketName) {

        // Define the filters for which 'directories' we want to download.
        DownloadFilter folder1Filter = (S3Object s3Object) -> s3Object.key().startsWith("folder1/");
        DownloadFilter folder3Filter = (S3Object s3Object) -> s3Object.key().startsWith("folder3/");
        DownloadFilter folderFilter = s3Object -> folder1Filter.or(folder3Filter).test(s3Object);

        DirectoryDownload directoryDownload = transferManager.downloadDirectory(DownloadDirectoryRequest.builder()
                .destination(Paths.get(destinationPathURI))
                .bucket(bucketName)
                .filter(folderFilter)
                .build());
        CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join();

        Integer numFilesInFolder1 = Paths.get(destinationPathURI).resolve("folder1").toFile().list().length;
        Integer numFilesInFolder3 = Paths.get(destinationPathURI).resolve("folder3").toFile().list().length;

        try {
            assert numFilesInFolder1 == 3;
            assert numFilesInFolder3 == 3;
            assert !Paths.get(destinationPathURI).resolve("folder2").toFile().exists(); // `folder2` was not downloaded.
        } catch (AssertionError e) {
            logger.error("An assertion failed.");
        }

        completedDirectoryDownload.failedTransfers()
                .forEach(fail -> logger.warn("Object failed to transfer  [{}]", fail.exception().getMessage()));
        return numFilesInFolder1 + numFilesInFolder3;
    }
```

### ローカルディレクトリへのオブジェクトのダウンロード
<a name="s3_DownloadBucketToDirectory_java_2_topic"></a>

次のコード例は、Amazon Simple Storage Service (Amazon S3) バケットからすべてのオブジェクトをローカルディレクトリにダウンロードする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
[S3TransferManager](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html) を使用して、同じ S3 バケットにある[すべての S3 オブジェクトをダウンロード](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html#downloadDirectory(software.amazon.awssdk.transfer.s3.DownloadDirectoryRequest))します。[完全なファイル](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/DownloadToDirectory.java)と[テスト](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/test/java/TransferManagerTest.java)を表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DirectoryDownload;
import software.amazon.awssdk.transfer.s3.model.DownloadDirectoryRequest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

    public Integer downloadObjectsToDirectory(S3TransferManager transferManager,
            URI destinationPathURI, String bucketName) {
        DirectoryDownload directoryDownload = transferManager.downloadDirectory(DownloadDirectoryRequest.builder()
                .destination(Paths.get(destinationPathURI))
                .bucket(bucketName)
                .build());
        CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join();

        completedDirectoryDownload.failedTransfers()
                .forEach(fail -> logger.warn("Object [{}] failed to transfer", fail.toString()));
        return completedDirectoryDownload.failedTransfers().size();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DownloadDirectory](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DownloadDirectory)」を参照してください。

### Amazon S3 オブジェクトをロックする
<a name="s3_Scenario_ObjectLock_java_2_topic"></a>

次のコード例は、S3 オブジェクトロック機能を操作する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/lockscenario#code-examples)での設定と実行の方法を確認してください。
Amazon S3 オブジェクトロック機能を示すインタラクティブなシナリオを実行します。  

```
import software.amazon.awssdk.services.s3.model.ObjectLockLegalHold;
import software.amazon.awssdk.services.s3.model.ObjectLockRetention;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

/*
 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/setup.html

 This Java example performs the following tasks:
    1. Create test Amazon Simple Storage Service (S3) buckets with different lock policies.
    2. Upload sample objects to each bucket.
    3. Set some Legal Hold and Retention Periods on objects and buckets.
    4. Investigate lock policies by viewing settings or attempting to delete or overwrite objects.
    5. Clean up objects and buckets.
 */
public class S3ObjectLockWorkflow {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    static String bucketName;
    static S3LockActions s3LockActions;
    private static final List<String> bucketNames = new ArrayList<>();
    private static final List<String> fileNames = new ArrayList<>();

    public static void main(String[] args) {
        final String usage = """
            Usage:
                <bucketName> \s

            Where:
                bucketName - The Amazon S3 bucket name. 
           """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }
        s3LockActions = new S3LockActions();
        bucketName = args[0];
        Scanner scanner = new Scanner(System.in);

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon Simple Storage Service (S3) Object Locking Feature Scenario.");
        System.out.println("Press Enter to continue...");
        scanner.nextLine();
        configurationSetup();
        System.out.println(DASHES);

        System.out.println(DASHES);
        setup();
        System.out.println("Setup is complete. Press Enter to continue...");
        scanner.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Lets present the user with choices.");
        System.out.println("Press Enter to continue...");
        scanner.nextLine();
        demoActionChoices() ;
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Would you like to clean up the resources? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            cleanup();
            System.out.println("Clean up is complete.");
        }

        System.out.println("Press Enter to continue...");
        scanner.nextLine();
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Amazon S3 Object Locking Workflow is complete.");
        System.out.println(DASHES);
    }

    // Present the user with the demo action choices.
    public static void demoActionChoices() {
        String[] choices = {
            "List all files in buckets.",
            "Attempt to delete a file.",
            "Attempt to delete a file with retention period bypass.",
            "Attempt to overwrite a file.",
            "View the object and bucket retention settings for a file.",
            "View the legal hold settings for a file.",
            "Finish the workflow."
        };

        int choice = 0;
        while (true) {
            System.out.println(DASHES);
            choice = getChoiceResponse("Explore the S3 locking features by selecting one of the following choices:", choices);
            System.out.println(DASHES);
            System.out.println("You selected "+choices[choice]);
            switch (choice) {
                case 0 -> {
                    s3LockActions.listBucketsAndObjects(bucketNames, true);
                }

                case 1 -> {
                    System.out.println("Enter the number of the object to delete:");
                    List<S3InfoObject> allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true);
                    List<String> fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList());
                    String[] fileKeysArray = fileKeys.toArray(new String[0]);
                    int fileChoice = getChoiceResponse(null, fileKeysArray);
                    String objectKey = fileKeys.get(fileChoice);
                    String bucketName = allFiles.get(fileChoice).getBucketName();
                    String version = allFiles.get(fileChoice).getVersion();
                    s3LockActions.deleteObjectFromBucket(bucketName, objectKey, false, version);
                }

                case 2 -> {
                    System.out.println("Enter the number of the object to delete:");
                    List<S3InfoObject> allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true);
                    List<String> fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList());
                    String[] fileKeysArray = fileKeys.toArray(new String[0]);
                    int fileChoice = getChoiceResponse(null, fileKeysArray);
                    String objectKey = fileKeys.get(fileChoice);
                    String bucketName = allFiles.get(fileChoice).getBucketName();
                    String version = allFiles.get(fileChoice).getVersion();
                    s3LockActions.deleteObjectFromBucket(bucketName, objectKey, true, version);
                }

                case 3 -> {
                    System.out.println("Enter the number of the object to overwrite:");
                    List<S3InfoObject> allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true);
                    List<String> fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList());
                    String[] fileKeysArray = fileKeys.toArray(new String[0]);
                    int fileChoice = getChoiceResponse(null, fileKeysArray);
                    String objectKey = fileKeys.get(fileChoice);
                    String bucketName = allFiles.get(fileChoice).getBucketName();

                    // Attempt to overwrite the file.
                    try (BufferedWriter writer = new BufferedWriter(new java.io.FileWriter(objectKey))) {
                        writer.write("This is a modified text.");

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    s3LockActions.uploadFile(bucketName, objectKey, objectKey);
                }

                case 4 -> {
                    System.out.println("Enter the number of the object to overwrite:");
                    List<S3InfoObject> allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true);
                    List<String> fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList());
                    String[] fileKeysArray = fileKeys.toArray(new String[0]);
                    int fileChoice = getChoiceResponse(null, fileKeysArray);
                    String objectKey = fileKeys.get(fileChoice);
                    String bucketName = allFiles.get(fileChoice).getBucketName();
                    s3LockActions.getObjectRetention(bucketName, objectKey);
                }

                case 5 -> {
                    System.out.println("Enter the number of the object to view:");
                    List<S3InfoObject> allFiles = s3LockActions.listBucketsAndObjects(bucketNames, true);
                    List<String> fileKeys = allFiles.stream().map(f -> f.getKeyName()).collect(Collectors.toList());
                    String[] fileKeysArray = fileKeys.toArray(new String[0]);
                    int fileChoice = getChoiceResponse(null, fileKeysArray);
                    String objectKey = fileKeys.get(fileChoice);
                    String bucketName = allFiles.get(fileChoice).getBucketName();
                    s3LockActions.getObjectLegalHold(bucketName, objectKey);
                    s3LockActions.getBucketObjectLockConfiguration(bucketName);
                }

                case 6 -> {
                    System.out.println("Exiting the workflow...");
                    return;
                }

                default -> {
                    System.out.println("Invalid choice. Please select again.");
                }
            }
        }
    }

    // Clean up the resources from the scenario.
    private static void cleanup() {
        List<S3InfoObject> allFiles = s3LockActions.listBucketsAndObjects(bucketNames, false);
        for (S3InfoObject fileInfo : allFiles) {
            String bucketName = fileInfo.getBucketName();
            String key = fileInfo.getKeyName();
            String version = fileInfo.getVersion();
            if (bucketName.contains("lock-enabled") || (bucketName.contains("retention-after-creation"))) {
                ObjectLockLegalHold legalHold = s3LockActions.getObjectLegalHold(bucketName, key);
                if (legalHold != null) {
                    String holdStatus = legalHold.status().name();
                    System.out.println(holdStatus);
                    if (holdStatus.compareTo("ON") == 0) {
                        s3LockActions.modifyObjectLegalHold(bucketName, key, false);
                    }
                }
                // Check for a retention period.
                ObjectLockRetention retention = s3LockActions.getObjectRetention(bucketName, key);
                boolean hasRetentionPeriod ;
                hasRetentionPeriod = retention != null;
                s3LockActions.deleteObjectFromBucket(bucketName, key,hasRetentionPeriod, version);

            } else {
                System.out.println(bucketName +" objects do not have a legal lock");
                s3LockActions.deleteObjectFromBucket(bucketName, key,false, version);
            }
        }

        // Delete the buckets.
        System.out.println("Delete "+bucketName);
        for (String bucket : bucketNames){
            s3LockActions.deleteBucketByName(bucket);
        }
    }

    private static void setup() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("""
                For this workflow, we will use the AWS SDK for Java to create several S3
                buckets and files to demonstrate working with S3 locking features.
                """);

        System.out.println("S3 buckets can be created either with or without object lock enabled.");
        System.out.println("Press Enter to continue...");
        scanner.nextLine();

        // Create three S3 buckets.
        s3LockActions.createBucketWithLockOptions(false, bucketNames.get(0));
        s3LockActions.createBucketWithLockOptions(true, bucketNames.get(1));
        s3LockActions.createBucketWithLockOptions(false, bucketNames.get(2));
        System.out.println("Press Enter to continue.");
        scanner.nextLine();

        System.out.println("Bucket "+bucketNames.get(2) +" will be configured to use object locking with a default retention period.");
        s3LockActions.modifyBucketDefaultRetention(bucketNames.get(2));
        System.out.println("Press Enter to continue.");
        scanner.nextLine();

        System.out.println("Object lock policies can also be added to existing buckets. For this example, we will use "+bucketNames.get(1));
        s3LockActions.enableObjectLockOnBucket(bucketNames.get(1));
        System.out.println("Press Enter to continue.");
        scanner.nextLine();

        // Upload some files to the buckets.
        System.out.println("Now let's add some test files:");
        String fileName = "exampleFile.txt";
        int fileCount = 2;
        try (BufferedWriter writer = new BufferedWriter(new java.io.FileWriter(fileName))) {
            writer.write("This is a sample file for uploading to a bucket.");

        } catch (IOException e) {
            e.printStackTrace();
        }

        for (String bucketName : bucketNames){
            for (int i = 0; i < fileCount; i++) {
                // Get the file name without extension.
                String fileNameWithoutExtension = java.nio.file.Paths.get(fileName).getFileName().toString();
                int extensionIndex = fileNameWithoutExtension.lastIndexOf('.');
                if (extensionIndex > 0) {
                    fileNameWithoutExtension = fileNameWithoutExtension.substring(0, extensionIndex);
                }

                // Create the numbered file names.
                String numberedFileName = fileNameWithoutExtension + i + getFileExtension(fileName);
                fileNames.add(numberedFileName);
                s3LockActions.uploadFile(bucketName, numberedFileName, fileName);
            }
        }

        String question = null;
        System.out.print("Press Enter to continue...");
        scanner.nextLine();
        System.out.println("Now we can set some object lock policies on individual files:");
        for (String bucketName : bucketNames) {
            for (int i = 0; i < fileNames.size(); i++){

                // No modifications to the objects in the first bucket.
                if (!bucketName.equals(bucketNames.get(0))) {
                    String exampleFileName = fileNames.get(i);
                    switch (i) {
                        case 0 -> {
                            question = "Would you like to add a legal hold to " + exampleFileName + " in " + bucketName + " (y/n)?";
                            System.out.println(question);
                            String ans = scanner.nextLine().trim();
                            if (ans.equalsIgnoreCase("y")) {
                                System.out.println("**** You have selected to put a legal hold " + exampleFileName);

                                // Set a legal hold.
                                s3LockActions.modifyObjectLegalHold(bucketName, exampleFileName, true);
                            }
                        }
                        case 1 -> {
                            """
                                Would you like to add a 1 day Governance retention period to %s in %s (y/n)?
                                Reminder: Only a user with the s3:BypassGovernanceRetention permission will be able to delete this file or its bucket until the retention period has expired.
                                """.formatted(exampleFileName, bucketName);
                            System.out.println(question);
                            String ans2 = scanner.nextLine().trim();
                            if (ans2.equalsIgnoreCase("y")) {
                                s3LockActions.modifyObjectRetentionPeriod(bucketName, exampleFileName);
                            }
                        }
                    }
                }
            }
        }
    }

    // Get file extension.
    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0) {
            return fileName.substring(dotIndex);
        }
        return "";
    }

    public static void configurationSetup() {
        String noLockBucketName = bucketName + "-no-lock";
        String lockEnabledBucketName = bucketName + "-lock-enabled";
        String retentionAfterCreationBucketName = bucketName + "-retention-after-creation";
        bucketNames.add(noLockBucketName);
        bucketNames.add(lockEnabledBucketName);
        bucketNames.add(retentionAfterCreationBucketName);
    }

    public static int getChoiceResponse(String question, String[] choices) {
        Scanner scanner = new Scanner(System.in);
        if (question != null) {
            System.out.println(question);
            for (int i = 0; i < choices.length; i++) {
                System.out.println("\t" + (i + 1) + ". " + choices[i]);
            }
        }

        int choiceNumber = 0;
        while (choiceNumber < 1 || choiceNumber > choices.length) {
            String choice = scanner.nextLine();
            try {
                choiceNumber = Integer.parseInt(choice);
            } catch (NumberFormatException e) {
                System.out.println("Invalid choice. Please enter a valid number.");
            }
        }

        return choiceNumber - 1;
    }
}
```
S3 関数のラッパークラス。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.BucketVersioningStatus;
import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DefaultRetention;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectLegalHoldRequest;
import software.amazon.awssdk.services.s3.model.GetObjectLegalHoldResponse;
import software.amazon.awssdk.services.s3.model.GetObjectLockConfigurationRequest;
import software.amazon.awssdk.services.s3.model.GetObjectLockConfigurationResponse;
import software.amazon.awssdk.services.s3.model.GetObjectRetentionRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRetentionResponse;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse;
import software.amazon.awssdk.services.s3.model.MFADelete;
import software.amazon.awssdk.services.s3.model.ObjectLockConfiguration;
import software.amazon.awssdk.services.s3.model.ObjectLockEnabled;
import software.amazon.awssdk.services.s3.model.ObjectLockLegalHold;
import software.amazon.awssdk.services.s3.model.ObjectLockLegalHoldStatus;
import software.amazon.awssdk.services.s3.model.ObjectLockRetention;
import software.amazon.awssdk.services.s3.model.ObjectLockRetentionMode;
import software.amazon.awssdk.services.s3.model.ObjectLockRule;
import software.amazon.awssdk.services.s3.model.PutBucketVersioningRequest;
import software.amazon.awssdk.services.s3.model.PutObjectLegalHoldRequest;
import software.amazon.awssdk.services.s3.model.PutObjectLockConfigurationRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.PutObjectRetentionRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.VersioningConfiguration;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

// Contains application logic for the Amazon S3 operations used in this workflow.
public class S3LockActions {

    private static S3Client getClient() {
        return S3Client.builder()
            .region(Region.US_EAST_1)
            .build();
    }

    // Set or modify a retention period on an object in an S3 bucket.
    public void modifyObjectRetentionPeriod(String bucketName, String objectKey) {
        // Calculate the instant one day from now.
        Instant futureInstant = Instant.now().plus(1, ChronoUnit.DAYS);

        // Convert the Instant to a ZonedDateTime object with a specific time zone.
        ZonedDateTime zonedDateTime = futureInstant.atZone(ZoneId.systemDefault());

        // Define a formatter for human-readable output.
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // Format the ZonedDateTime object to a human-readable date string.
        String humanReadableDate = formatter.format(zonedDateTime);

        // Print the formatted date string.
        System.out.println("Formatted Date: " + humanReadableDate);
        ObjectLockRetention retention = ObjectLockRetention.builder()
            .mode(ObjectLockRetentionMode.GOVERNANCE)
            .retainUntilDate(futureInstant)
            .build();

        PutObjectRetentionRequest retentionRequest = PutObjectRetentionRequest.builder()
            .bucket(bucketName)
            .key(objectKey)
            .retention(retention)
            .build();

        getClient().putObjectRetention(retentionRequest);
        System.out.println("Set retention for "+objectKey +" in " +bucketName +" until "+ humanReadableDate +".");
    }

    // Get the legal hold details for an S3 object.
    public ObjectLockLegalHold getObjectLegalHold(String bucketName, String objectKey) {
        try {
            GetObjectLegalHoldRequest legalHoldRequest = GetObjectLegalHoldRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .build();

            GetObjectLegalHoldResponse response = getClient().getObjectLegalHold(legalHoldRequest);
            System.out.println("Object legal hold for " + objectKey + " in " + bucketName +
                ":\n\tStatus: " + response.legalHold().status());
            return response.legalHold();

        } catch (S3Exception ex) {
            System.out.println("\tUnable to fetch legal hold: '" + ex.getMessage() + "'");
        }

        return null;
    }

    // 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");
    }

    public List<S3InfoObject> listBucketsAndObjects(List<String> bucketNames, Boolean interactive) {
        AtomicInteger counter = new AtomicInteger(0); // Initialize counter.
        return bucketNames.stream()
            .flatMap(bucketName -> listBucketObjectsAndVersions(bucketName).versions().stream()
                .map(version -> {
                    S3InfoObject s3InfoObject = new S3InfoObject();
                    s3InfoObject.setBucketName(bucketName);
                    s3InfoObject.setVersion(version.versionId());
                    s3InfoObject.setKeyName(version.key());
                    return s3InfoObject;
                }))
            .peek(s3InfoObject -> {
                int i = counter.incrementAndGet(); // Increment and get the updated value.
                if (interactive) {
                    System.out.println(i + ": "+ s3InfoObject.getKeyName());
                    System.out.printf("%5s Bucket name: %s\n", "", s3InfoObject.getBucketName());
                    System.out.printf("%5s Version: %s\n", "", s3InfoObject.getVersion());
                }
            })
            .collect(Collectors.toList());
    }

    public ListObjectVersionsResponse listBucketObjectsAndVersions(String bucketName) {
        ListObjectVersionsRequest versionsRequest = ListObjectVersionsRequest.builder()
            .bucket(bucketName)
            .build();

        return getClient().listObjectVersions(versionsRequest);
    }

    // Set or modify a retention period on an S3 bucket.
    public void modifyBucketDefaultRetention(String bucketName) {
        VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder()
            .mfaDelete(MFADelete.DISABLED)
            .status(BucketVersioningStatus.ENABLED)
            .build();

        PutBucketVersioningRequest versioningRequest = PutBucketVersioningRequest.builder()
            .bucket(bucketName)
            .versioningConfiguration(versioningConfiguration)
            .build();

        getClient().putBucketVersioning(versioningRequest);
        DefaultRetention rention = DefaultRetention.builder()
            .days(1)
            .mode(ObjectLockRetentionMode.GOVERNANCE)
            .build();

        ObjectLockRule lockRule = ObjectLockRule.builder()
            .defaultRetention(rention)
            .build();

        ObjectLockConfiguration objectLockConfiguration = ObjectLockConfiguration.builder()
            .objectLockEnabled(ObjectLockEnabled.ENABLED)
            .rule(lockRule)
            .build();

        PutObjectLockConfigurationRequest putObjectLockConfigurationRequest = PutObjectLockConfigurationRequest.builder()
            .bucket(bucketName)
            .objectLockConfiguration(objectLockConfiguration)
            .build();

        getClient().putObjectLockConfiguration(putObjectLockConfigurationRequest) ;
        System.out.println("Added a default retention to bucket "+bucketName +".");
    }

    // Enable object lock on an existing bucket.
    public void enableObjectLockOnBucket(String bucketName) {
        try {
            VersioningConfiguration versioningConfiguration = VersioningConfiguration.builder()
                .status(BucketVersioningStatus.ENABLED)
                .build();

            PutBucketVersioningRequest putBucketVersioningRequest = PutBucketVersioningRequest.builder()
                .bucket(bucketName)
                .versioningConfiguration(versioningConfiguration)
                .build();

            // Enable versioning on the bucket.
            getClient().putBucketVersioning(putBucketVersioningRequest);
            PutObjectLockConfigurationRequest request = PutObjectLockConfigurationRequest.builder()
                .bucket(bucketName)
                .objectLockConfiguration(ObjectLockConfiguration.builder()
                    .objectLockEnabled(ObjectLockEnabled.ENABLED)
                    .build())
                .build();

            getClient().putObjectLockConfiguration(request);
            System.out.println("Successfully enabled object lock on "+bucketName);

        } catch (S3Exception ex) {
            System.out.println("Error modifying object lock: '" + ex.getMessage() + "'");
        }
    }

    public void uploadFile(String bucketName, String objectName, String filePath) {
        Path file = Paths.get(filePath);
        PutObjectRequest request = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(objectName)
            .checksumAlgorithm(ChecksumAlgorithm.SHA256)
            .build();

        PutObjectResponse response = getClient().putObject(request, file);
        if (response != null) {
            System.out.println("\tSuccessfully uploaded " + objectName + " to " + bucketName + ".");
        } else {
            System.out.println("\tCould not upload " + objectName + " to " + bucketName + ".");
        }
    }

    // Set or modify a legal hold on an object in an S3 bucket.
    public void modifyObjectLegalHold(String bucketName, String objectKey, boolean legalHoldOn) {
        ObjectLockLegalHold legalHold ;
        if (legalHoldOn) {
            legalHold = ObjectLockLegalHold.builder()
                .status(ObjectLockLegalHoldStatus.ON)
                .build();
        } else {
            legalHold = ObjectLockLegalHold.builder()
                .status(ObjectLockLegalHoldStatus.OFF)
                .build();
        }

        PutObjectLegalHoldRequest legalHoldRequest = PutObjectLegalHoldRequest.builder()
            .bucket(bucketName)
            .key(objectKey)
            .legalHold(legalHold)
            .build();

        getClient().putObjectLegalHold(legalHoldRequest) ;
        System.out.println("Modified legal hold for "+ objectKey +" in "+bucketName +".");
    }

    // Delete an object from a specific bucket.
    public void deleteObjectFromBucket(String bucketName, String objectKey, boolean hasRetention, String versionId) {
        try {
            DeleteObjectRequest objectRequest;
            if (hasRetention) {
                objectRequest = DeleteObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .versionId(versionId)
                    .bypassGovernanceRetention(true)
                    .build();
            } else {
                objectRequest = DeleteObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .versionId(versionId)
                    .build();
            }

            getClient().deleteObject(objectRequest) ;
            System.out.println("The object was successfully deleted");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    // Get the retention period for an S3 object.
    public ObjectLockRetention getObjectRetention(String bucketName, String key){
        try {
            GetObjectRetentionRequest retentionRequest = GetObjectRetentionRequest.builder()
                .bucket(bucketName)
                .key(key)
                .build();

            GetObjectRetentionResponse response = getClient().getObjectRetention(retentionRequest);
            System.out.println("tObject retention for "+key +" in "+ bucketName +": " + response.retention().mode() +" until "+ response.retention().retainUntilDate() +".");
            return response.retention();

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            return null;
        }
    }

    public void deleteBucketByName(String bucketName) {
        try {
            DeleteBucketRequest request = DeleteBucketRequest.builder()
                .bucket(bucketName)
                .build();

            getClient().deleteBucket(request);
            System.out.println(bucketName +" was deleted.");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    // Get the object lock configuration details for an S3 bucket.
    public void getBucketObjectLockConfiguration(String bucketName) {
        GetObjectLockConfigurationRequest objectLockConfigurationRequest = GetObjectLockConfigurationRequest.builder()
            .bucket(bucketName)
            .build();

        GetObjectLockConfigurationResponse response = getClient().getObjectLockConfiguration(objectLockConfigurationRequest);
        System.out.println("Bucket object lock config for "+bucketName +":  ");
        System.out.println("\tEnabled: "+response.objectLockConfiguration().objectLockEnabled());
        System.out.println("\tRule: "+ response.objectLockConfiguration().rule().defaultRetention());
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [GetObjectLegalHold](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObjectLegalHold)
  + [GetObjectLockConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObjectLockConfiguration)
  + [GetObjectRetention](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObjectRetention)
  + [PutObjectLegalHold](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObjectLegalHold)
  + [PutObjectLockConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObjectLockConfiguration)
  + [PutObjectRetention](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObjectRetention)

### S3 を使用して大量のメッセージを管理する
<a name="sqs_Scenario_SqsExtendedClient_java_2_topic"></a>

次のコード例は、Amazon SQS 拡張クライアントライブラリを使用して大量の Amazon SQS メッセージを操作する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient;
import com.amazon.sqs.javamessaging.ExtendedClientConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ExpirationStatus;
import software.amazon.awssdk.services.s3.model.LifecycleExpiration;
import software.amazon.awssdk.services.s3.model.LifecycleRule;
import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationRequest;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueResponse;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Example of using Amazon SQS Extended Client Library for Java 2.x.
 */
public class SqsExtendedClientExample {
    private static final Logger logger = LoggerFactory.getLogger(SqsExtendedClientExample.class);
    
    private String s3BucketName;
    private String queueUrl;
    private final String queueName;
    private final S3Client s3Client;
    private final SqsClient sqsExtendedClient;
    private final int messageSize;

    /**
     * Constructor with default clients and message size.
     */
    public SqsExtendedClientExample() {
        this(S3Client.create(), 300000);
    }

    /**
     * Constructor with custom S3 client and message size.
     *
     * @param s3Client The S3 client to use
     * @param messageSize The size of the test message to create
     */
    public SqsExtendedClientExample(S3Client s3Client, int messageSize) {
        this.s3Client = s3Client;
        this.messageSize = messageSize;

        // Generate a unique bucket name.
        this.s3BucketName = UUID.randomUUID() + "-" +
                DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime());

        // Generate a unique queue name.
        this.queueName = "MyQueue-" + UUID.randomUUID();

        // Configure the SQS extended client.
        final ExtendedClientConfiguration extendedClientConfig = new ExtendedClientConfiguration()
                .withPayloadSupportEnabled(s3Client, s3BucketName);

        this.sqsExtendedClient = new AmazonSQSExtendedClient(SqsClient.builder().build(), extendedClientConfig);
    }

    public static void main(String[] args) {
        SqsExtendedClientExample example = new SqsExtendedClientExample();
        try {
            example.setup();
            example.sendAndReceiveMessage();
        } finally {
            example.cleanup();
        }
    }

    /**
     * Send a large message and receive it back.
     *
     * @return The received message
     */
    public Message sendAndReceiveMessage() {
        try {
            // Create a large message.
            char[] chars = new char[messageSize];
            Arrays.fill(chars, 'x');
            String largeMessage = new String(chars);

            // Send the message.
            final SendMessageRequest sendMessageRequest = SendMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageBody(largeMessage)
                    .build();

            sqsExtendedClient.sendMessage(sendMessageRequest);
            logger.info("Sent message of size: {}", largeMessage.length());

            // Receive and return the message.
            final ReceiveMessageResponse receiveMessageResponse = sqsExtendedClient.receiveMessage(
                    ReceiveMessageRequest.builder().queueUrl(queueUrl).build());

            List<Message> messages = receiveMessageResponse.messages();
            if (messages.isEmpty()) {
                throw new RuntimeException("No messages received");
            }

            Message message = messages.getFirst();
            logger.info("\nMessage received.");
            logger.info("  ID: {}", message.messageId());
            logger.info("  Receipt handle: {}", message.receiptHandle());
            logger.info("  Message body size: {}", message.body().length());
            logger.info("  Message body (first 5 characters): {}", message.body().substring(0, 5));

            return message;
        } catch (RuntimeException e) {
            logger.error("Error during message processing: {}", e.getMessage(), e);
            throw e;
        }
    }
```
+  詳細については、「[AWS SDK for Java 2.x デベロッパーガイド](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-s3-messages.html)」を参照してください。
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)
  + [PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketLifecycleConfiguration)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)
  + [SendMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SendMessage)

### URI を解析する
<a name="s3_Scenario_URIParsing_java_2_topic"></a>

次のコード例は、Amazon S3 の URI を解析してバケット名やオブジェクトキーなどの重要なコンポーネントを抽出する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
[S3Uri](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Uri.html) クラスを使用して Amazon S3 の URI を解析します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Uri;
import software.amazon.awssdk.services.s3.S3Utilities;

import java.net.URI;
import java.util.List;
import java.util.Map;

    /**
     *
     * @param s3Client    - An S3Client through which you acquire an S3Uri instance.
     * @param s3ObjectUrl - A complex URL (String) that is used to demonstrate S3Uri
     *                    capabilities.
     */
    public static void parseS3UriExample(S3Client s3Client, String s3ObjectUrl) {
        logger.info(s3ObjectUrl);
        // Console output:
        // 'https://s3.us-west-1.amazonaws.com/myBucket/resources/doc.txt?versionId=abc123&partNumber=77&partNumber=88'.

        // Create an S3Utilities object using the configuration of the s3Client.
        S3Utilities s3Utilities = s3Client.utilities();

        // From a String URL create a URI object to pass to the parseUri() method.
        URI uri = URI.create(s3ObjectUrl);
        S3Uri s3Uri = s3Utilities.parseUri(uri);

        // If the URI contains no value for the Region, bucket or key, the SDK returns
        // an empty Optional.
        // The SDK returns decoded URI values.

        Region region = s3Uri.region().orElse(null);
        log("region", region);
        // Console output: 'region: us-west-1'.

        String bucket = s3Uri.bucket().orElse(null);
        log("bucket", bucket);
        // Console output: 'bucket: myBucket'.

        String key = s3Uri.key().orElse(null);
        log("key", key);
        // Console output: 'key: resources/doc.txt'.

        Boolean isPathStyle = s3Uri.isPathStyle();
        log("isPathStyle", isPathStyle);
        // Console output: 'isPathStyle: true'.

        // If the URI contains no query parameters, the SDK returns an empty map.
        Map<String, List<String>> queryParams = s3Uri.rawQueryParameters();
        log("rawQueryParameters", queryParams);
        // Console output: 'rawQueryParameters: {versionId=[abc123], partNumber=[77,
        // 88]}'.

        // Retrieve the first or all values for a query parameter as shown in the
        // following code.
        String versionId = s3Uri.firstMatchingRawQueryParameter("versionId").orElse(null);
        log("firstMatchingRawQueryParameter-versionId", versionId);
        // Console output: 'firstMatchingRawQueryParameter-versionId: abc123'.

        String partNumber = s3Uri.firstMatchingRawQueryParameter("partNumber").orElse(null);
        log("firstMatchingRawQueryParameter-partNumber", partNumber);
        // Console output: 'firstMatchingRawQueryParameter-partNumber: 77'.

        List<String> partNumbers = s3Uri.firstMatchingRawQueryParameters("partNumber");
        log("firstMatchingRawQueryParameter", partNumbers);
        // Console output: 'firstMatchingRawQueryParameter: [77, 88]'.

        /*
         * Object keys and query parameters with reserved or unsafe characters, must be
         * URL-encoded.
         * For example replace whitespace " " with "%20".
         * Valid:
         * "https://s3.us-west-1.amazonaws.com/myBucket/object%20key?query=%5Bbrackets%5D"
         * Invalid:
         * "https://s3.us-west-1.amazonaws.com/myBucket/object key?query=[brackets]"
         * 
         * Virtual-hosted-style URIs with bucket names that contain a dot, ".", the dot
         * must not be URL-encoded.
         * Valid: "https://my.Bucket.s3.us-west-1.amazonaws.com/key"
         * Invalid: "https://my%2EBucket.s3.us-west-1.amazonaws.com/key"
         */
    }

    private static void log(String s3UriElement, Object element) {
        if (element == null) {
            logger.info("{}: {}", s3UriElement, "null");
        } else {
            logger.info("{}: {}", s3UriElement, element);
        }
    }
```

### S3 イベント通知の処理
<a name="s3_Scenario_ProcessS3EventNotification_java_2_topic"></a>

次のコード例は、オブジェクト指向の方法で S3 イベント通知を操作する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
この例は、Amazon SQS を使用して S3 通知イベントを処理する方法を示しています。  

```
    /**
     * This method receives S3 event notifications by using an SqsAsyncClient.
     * After the client receives the messages it deserializes the JSON payload and logs them. It uses
     * the S3EventNotification class (part of the S3 event notification API for Java) to deserialize
     * the JSON payload and access the messages in an object-oriented way.
     *
     * @param queueUrl The URL of the AWS SQS queue that receives the S3 event notifications.
     * @see <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/eventnotifications/s3/model/package-summary.html">S3EventNotification API</a>.
     * <p>
     * To use S3 event notification serialization/deserialization to objects, add the following
     * dependency to your Maven pom.xml file.
     * <dependency>
     * <groupId>software.amazon.awssdk</groupId>
     * <artifactId>s3-event-notifications</artifactId>
     * <version><LATEST></version>
     * </dependency>
     * <p>
     * The S3 event notification API became available with version 2.25.11 of the Java SDK.
     * <p>
     * This example shows the use of the API with AWS SQS, but it can be used to process S3 event notifications
     * in AWS SNS or AWS Lambda as well.
     * <p>
     * Note: The S3EventNotification class does not work with messages routed through AWS EventBridge.
     */
    static void processS3Events(String bucketName, String queueUrl, String queueArn) {
        try {
            // Configure the bucket to send Object Created and Object Tagging notifications to an existing SQS queue.
            s3Client.putBucketNotificationConfiguration(b -> b
                    .notificationConfiguration(ncb -> ncb
                            .queueConfigurations(qcb -> qcb
                                    .events(Event.S3_OBJECT_CREATED, Event.S3_OBJECT_TAGGING)
                                    .queueArn(queueArn)))
                            .bucket(bucketName)
            ).join();

            triggerS3EventNotifications(bucketName);
            // Wait for event notifications to propagate.
            Thread.sleep(Duration.ofSeconds(5).toMillis());

            boolean didReceiveMessages = true;
            while (didReceiveMessages) {
                // Display the number of messages that are available in the queue.
                sqsClient.getQueueAttributes(b -> b
                                .queueUrl(queueUrl)
                                .attributeNames(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES)
                        ).thenAccept(attributeResponse ->
                                logger.info("Approximate number of messages in the queue: {}",
                                        attributeResponse.attributes().get(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES)))
                        .join();

                // Receive the messages.
                ReceiveMessageResponse response = sqsClient.receiveMessage(b -> b
                        .queueUrl(queueUrl)
                ).get();
                logger.info("Count of received messages: {}", response.messages().size());
                didReceiveMessages = !response.messages().isEmpty();

                // Create a collection to hold the received message for deletion
                // after we log the messages.
                HashSet<DeleteMessageBatchRequestEntry> messagesToDelete = new HashSet<>();
                // Process each message.
                response.messages().forEach(message -> {
                    logger.info("Message id: {}", message.messageId());
                    // Deserialize JSON message body to a S3EventNotification object
                    // to access messages in an object-oriented way.
                    S3EventNotification event = S3EventNotification.fromJson(message.body());

                    // Log the S3 event notification record details.
                    if (event.getRecords() != null) {
                        event.getRecords().forEach(record -> {
                            String eventName = record.getEventName();
                            String key = record.getS3().getObject().getKey();
                            logger.info(record.toString());
                            logger.info("Event name is {} and key is {}", eventName, key);
                        });
                    }
                    // Add logged messages to collection for batch deletion.
                    messagesToDelete.add(DeleteMessageBatchRequestEntry.builder()
                            .id(message.messageId())
                            .receiptHandle(message.receiptHandle())
                            .build());
                });
                // Delete messages.
                if (!messagesToDelete.isEmpty()) {
                    sqsClient.deleteMessageBatch(DeleteMessageBatchRequest.builder()
                            .queueUrl(queueUrl)
                            .entries(messagesToDelete)
                            .build()
                    ).join();
                }
            } // End of while block.
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteMessageBatch)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/GetQueueAttributes)
  + [PutBucketNotificationConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketNotificationConfiguration)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)

### EventBridge へのイベント通知の送信
<a name="s3_Scenario_PutBucketNotificationConfiguration_java_2_topic"></a>

次のコード例は、バケットが EventBridge に S3 イベント通知を送信し、Amazon SNS トピックと Amazon SQS キューに通知をルーティングできるようにする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    /** This method configures a bucket to send events to AWS EventBridge and creates a rule
     * to route the S3 object created events to a topic and a queue.
     *
     * @param bucketName Name of existing bucket
     * @param topicArn ARN of existing topic to receive S3 event notifications
     * @param queueArn ARN of existing queue to receive S3 event notifications
     *
     *  An AWS CloudFormation stack sets up the bucket, queue, topic before the method runs.
     */
    public static String setBucketNotificationToEventBridge(String bucketName, String topicArn, String queueArn) {
        try {
            // Enable bucket to emit S3 Event notifications to EventBridge.
            s3Client.putBucketNotificationConfiguration(b -> b
                    .bucket(bucketName)
                    .notificationConfiguration(b1 -> b1
                            .eventBridgeConfiguration(
                                    SdkBuilder::build)
                    ).build()).join();

            // Create an EventBridge rule to route Object Created notifications.
            PutRuleRequest putRuleRequest = PutRuleRequest.builder()
                    .name(RULE_NAME)
                    .eventPattern("""
                            {
                              "source": ["aws.s3"],
                              "detail-type": ["Object Created"],
                              "detail": {
                                "bucket": {
                                  "name": ["%s"]
                                }
                              }
                            }
                            """.formatted(bucketName))
                    .build();

            // Add the rule to the default event bus.
            PutRuleResponse putRuleResponse = eventBridgeClient.putRule(putRuleRequest)
                    .whenComplete((r, t) -> {
                        if (t != null) {
                            logger.error("Error creating event bus rule: " + t.getMessage(), t);
                            throw new RuntimeException(t.getCause().getMessage(), t);
                        }
                        logger.info("Event bus rule creation request sent successfully. ARN is: {}", r.ruleArn());
                    }).join();

            // Add the existing SNS topic and SQS queue as targets to the rule.
            eventBridgeClient.putTargets(b -> b
                    .eventBusName("default")
                    .rule(RULE_NAME)
                    .targets(List.of (
                            Target.builder()
                                    .arn(queueArn)
                                    .id("Queue")
                                    .build(),
                            Target.builder()
                                    .arn(topicArn)
                                    .id("Topic")
                                    .build())
                            )
                    ).join();
            return putRuleResponse.ruleArn();
        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [PutBucketNotificationConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketNotificationConfiguration)
  + [PutRule](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutRule)
  + [PutTargets](https://docs.aws.amazon.com/goto/SdkForJavaV2/eventbridge-2015-10-07/PutTargets)

### アップロードとダウンロードを追跡する
<a name="s3_Scenario_TrackUploadDownload_java_2_topic"></a>

次のコード例は、Amazon S3 オブジェクトのアップロードまたはダウンロードを追跡する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
ファイルのアップロードの進行状況を追跡します。  

```
    public void trackUploadFile(S3TransferManager transferManager, String bucketName,
                             String key, URI filePathURI) {
        UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
                .putObjectRequest(b -> b.bucket(bucketName).key(key))
                .addTransferListener(LoggingTransferListener.create())  // Add listener.
                .source(Paths.get(filePathURI))
                .build();

        FileUpload fileUpload = transferManager.uploadFile(uploadFileRequest);

        fileUpload.completionFuture().join();
        /*
            The SDK provides a LoggingTransferListener implementation of the TransferListener interface.
            You can also implement the interface to provide your own logic.

            Configure log4J2 with settings such as the following.
                <Configuration status="WARN">
                    <Appenders>
                        <Console name="AlignedConsoleAppender" target="SYSTEM_OUT">
                            <PatternLayout pattern="%m%n"/>
                        </Console>
                    </Appenders>

                    <Loggers>
                        <logger name="software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener" level="INFO" additivity="false">
                            <AppenderRef ref="AlignedConsoleAppender"/>
                        </logger>
                    </Loggers>
                </Configuration>

            Log4J2 logs the progress. The following is example output for a 21.3 MB file upload.
                Transfer initiated...
                |                    | 0.0%
                |====                | 21.1%
                |============        | 60.5%
                |====================| 100.0%
                Transfer complete!
        */
    }
```
ファイルのダウンロードの進捗状況を追跡します。  

```
    public void trackDownloadFile(S3TransferManager transferManager, String bucketName,
                             String key, String downloadedFileWithPath) {
        DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder()
                .getObjectRequest(b -> b.bucket(bucketName).key(key))
                .addTransferListener(LoggingTransferListener.create())  // Add listener.
                .destination(Paths.get(downloadedFileWithPath))
                .build();

        FileDownload downloadFile = transferManager.downloadFile(downloadFileRequest);

        CompletedFileDownload downloadResult = downloadFile.completionFuture().join();
        /*
            The SDK provides a LoggingTransferListener implementation of the TransferListener interface.
            You can also implement the interface to provide your own logic.

            Configure log4J2 with settings such as the following.
                <Configuration status="WARN">
                    <Appenders>
                        <Console name="AlignedConsoleAppender" target="SYSTEM_OUT">
                            <PatternLayout pattern="%m%n"/>
                        </Console>
                    </Appenders>

                    <Loggers>
                        <logger name="software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener" level="INFO" additivity="false">
                            <AppenderRef ref="AlignedConsoleAppender"/>
                        </logger>
                    </Loggers>
                </Configuration>

            Log4J2 logs the progress. The following is example output for a 21.3 MB file download.
                Transfer initiated...
                |=======             | 39.4%
                |===============     | 78.8%
                |====================| 100.0%
                Transfer complete!
        */
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [GetObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObject)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObject)

### バケットへのディレクトリのアップロード
<a name="s3_UploadDirectoryToBucket_java_2_topic"></a>

以下のコード例では、ローカルディレクトリを再帰的に Amazon Simple Storage Service (Amazon S3) バケットにアップロードする方法を示します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
[S3TransferManager](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html) を使用して[ローカルディレクトリをアップロード](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/transfer/s3/S3TransferManager.html#uploadDirectory(software.amazon.awssdk.transfer.s3.UploadDirectoryRequest))します。[完全なファイル](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/main/java/com/example/s3/transfermanager/UploadADirectory.java)と[テスト](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javav2/example_code/s3/src/test/java/TransferManagerTest.java)を表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedDirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.DirectoryUpload;
import software.amazon.awssdk.transfer.s3.model.UploadDirectoryRequest;

import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.UUID;

    public Integer uploadDirectory(S3TransferManager transferManager,
            URI sourceDirectory, String bucketName) {
        DirectoryUpload directoryUpload = transferManager.uploadDirectory(UploadDirectoryRequest.builder()
                .source(Paths.get(sourceDirectory))
                .bucket(bucketName)
                .build());

        CompletedDirectoryUpload completedDirectoryUpload = directoryUpload.completionFuture().join();
        completedDirectoryUpload.failedTransfers()
                .forEach(fail -> logger.warn("Object [{}] failed to transfer", fail.toString()));
        return completedDirectoryUpload.failedTransfers().size();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UploadDirectory](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/UploadDirectory)」を参照してください。

### 大きなファイルをアップロードまたはダウンロードする
<a name="s3_Scenario_UsingLargeFiles_java_2_topic"></a>

次のコード例は、Amazon S3 との間で大きなファイルをアップロードまたはダウンロードする方法を示しています。

詳細については、「[マルチパートアップロードを使用したオブジェクトのアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-upload-object.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
S3TransferManager を使用して、S3 バケットとの間でファイルを転送する関数を呼び出します。  

```
    public Integer downloadObjectsToDirectory(S3TransferManager transferManager,
            URI destinationPathURI, String bucketName) {
        DirectoryDownload directoryDownload = transferManager.downloadDirectory(DownloadDirectoryRequest.builder()
                .destination(Paths.get(destinationPathURI))
                .bucket(bucketName)
                .build());
        CompletedDirectoryDownload completedDirectoryDownload = directoryDownload.completionFuture().join();

        completedDirectoryDownload.failedTransfers()
                .forEach(fail -> logger.warn("Object [{}] failed to transfer", fail.toString()));
        return completedDirectoryDownload.failedTransfers().size();
    }
```
ローカルディレクトリ全体をアップロードします。  

```
    public Integer uploadDirectory(S3TransferManager transferManager,
            URI sourceDirectory, String bucketName) {
        DirectoryUpload directoryUpload = transferManager.uploadDirectory(UploadDirectoryRequest.builder()
                .source(Paths.get(sourceDirectory))
                .bucket(bucketName)
                .build());

        CompletedDirectoryUpload completedDirectoryUpload = directoryUpload.completionFuture().join();
        completedDirectoryUpload.failedTransfers()
                .forEach(fail -> logger.warn("Object [{}] failed to transfer", fail.toString()));
        return completedDirectoryUpload.failedTransfers().size();
    }
```
1 つのファイルをアップロードします。  

```
    public String uploadFile(S3TransferManager transferManager, String bucketName,
                             String key, URI filePathURI) {
        UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
            .putObjectRequest(b -> b.bucket(bucketName).key(key))
            .source(Paths.get(filePathURI))
            .build();

        FileUpload fileUpload = transferManager.uploadFile(uploadFileRequest);

        CompletedFileUpload uploadResult = fileUpload.completionFuture().join();
        return uploadResult.response().eTag();
    }
```
コード例では、次のインポートを使用します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
```
[AWS CRT ベースの S3 クライアント](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/crt-based-s3-client.html)上にある [S3 Transfer Manager](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/transfer-manager.html) を使用すると、コンテンツのサイズがしきい値を超えたときにマルチパートアップロードを透過的に実行できます。デフォルトのしきい値は 8 MB です。  

```
    /**
     * Uploads a file to an Amazon S3 bucket using the S3TransferManager.
     *
     * @param filePath the file path of the file to be uploaded
     */
    public void multipartUploadWithTransferManager(String filePath) {
        S3TransferManager transferManager = S3TransferManager.create();
        UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
            .putObjectRequest(b -> b
                .bucket(bucketName)
                .key(key))
            .source(Paths.get(filePath))
            .build();
        FileUpload fileUpload = transferManager.uploadFile(uploadFileRequest);
        fileUpload.completionFuture().join();
        transferManager.close();
    }
```
[S3Client API](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) を使用してマルチパートアップロードを実行します。  

```
    /**
     * Performs a multipart upload to Amazon S3 using the provided S3 client.
     *
     * @param filePath the path to the file to be uploaded
     */
    public void multipartUploadWithS3Client(String filePath) {

        // Initiate the multipart upload.
        CreateMultipartUploadResponse createMultipartUploadResponse = s3Client.createMultipartUpload(b -> b
            .bucket(bucketName)
            .key(key));
        String uploadId = createMultipartUploadResponse.uploadId();

        // Upload the parts of the file.
        int partNumber = 1;
        List<CompletedPart> completedParts = new ArrayList<>();
        ByteBuffer bb = ByteBuffer.allocate(1024 * 1024 * 5); // 5 MB byte buffer

        try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
            long fileSize = file.length();
            long position = 0;
            while (position < fileSize) {
                file.seek(position);
                long read = file.getChannel().read(bb);

                bb.flip(); // Swap position and limit before reading from the buffer.
                UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
                    .bucket(bucketName)
                    .key(key)
                    .uploadId(uploadId)
                    .partNumber(partNumber)
                    .build();

                UploadPartResponse partResponse = s3Client.uploadPart(
                    uploadPartRequest,
                    RequestBody.fromByteBuffer(bb));

                CompletedPart part = CompletedPart.builder()
                    .partNumber(partNumber)
                    .eTag(partResponse.eTag())
                    .build();
                completedParts.add(part);

                bb.clear();
                position += read;
                partNumber++;
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        // Complete the multipart upload.
        s3Client.completeMultipartUpload(b -> b
            .bucket(bucketName)
            .key(key)
            .uploadId(uploadId)
            .multipartUpload(CompletedMultipartUpload.builder().parts(completedParts).build()));
    }
```
マルチパートサポートを有効にして [S3AsyncClient API](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3AsyncClient.html) を使用し、マルチパートアップロードを実行します。  

```
    /**
     * Uploads a file to an S3 bucket using the S3AsyncClient and enabling multipart support.
     *
     * @param filePath the local file path of the file to be uploaded
     */
    public void multipartUploadWithS3AsyncClient(String filePath) {
        // Enable multipart support.
        S3AsyncClient s3AsyncClient = S3AsyncClient.builder()
            .multipartEnabled(true)
            .build();

        CompletableFuture<PutObjectResponse> response = s3AsyncClient.putObject(b -> b
                .bucket(bucketName)
                .key(key),
            Paths.get(filePath));

        response.join();
        logger.info("File uploaded in multiple 8 MiB parts using S3AsyncClient.");
    }
```

### サイズが不明なストリームをアップロードする
<a name="s3_Scenario_UploadStream_java_2_topic"></a>

次のコード例は、サイズが不明なストリームを Amazon S3 オブジェクトにアップロードする方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
[AWS  CRT ベースの S3 クライアント](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/crt-based-s3-client.html)を使用します。  

```
import com.example.s3.util.AsyncExampleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PutObjectFromStreamAsync {
    private static final Logger logger = LoggerFactory.getLogger(PutObjectFromStreamAsync.class);

    public static void main(String[] args) {
        String bucketName = "amzn-s3-demo-bucket-" + UUID.randomUUID(); // Change bucket name.
        String key = UUID.randomUUID().toString();

        AsyncExampleUtils.createBucket(bucketName);
        try {
            PutObjectFromStreamAsync example = new PutObjectFromStreamAsync();
            S3AsyncClient s3AsyncClientCrt = S3AsyncClient.crtCreate();
            PutObjectResponse putObjectResponse = example.putObjectFromStreamCrt(s3AsyncClientCrt, bucketName, key);
            logger.info("Object {} etag: {}", key, putObjectResponse.eTag());
            logger.info("Object {} uploaded to bucket {}.", key, bucketName);
        } catch (SdkException e) {
            logger.error(e.getMessage(), e);
        } finally {
            AsyncExampleUtils.deleteObject(bucketName, key);
            AsyncExampleUtils.deleteBucket(bucketName);
        }
    }

    /**
     * @param s33CrtAsyncClient - To upload content from a stream of unknown size, use can the AWS CRT-based S3 client.
     * @param bucketName - The name of the bucket.
     * @param key - The name of the object.
     * @return software.amazon.awssdk.services.s3.model.PutObjectResponse - Returns metadata pertaining to the put object operation.
     */
    public PutObjectResponse putObjectFromStreamCrt(S3AsyncClient s33CrtAsyncClient, String bucketName, String key) {

        // AsyncExampleUtils.randomString() returns a random string up to 100 characters.
        String randomString = AsyncExampleUtils.randomString();
        logger.info("random string to upload: {}: length={}", randomString, randomString.length());
        InputStream inputStream = new ByteArrayInputStream(randomString.getBytes());

        // Executor required to handle reading from the InputStream on a separate thread so the main upload is not blocked.
        ExecutorService executor = Executors.newSingleThreadExecutor();
        // Specify `null` for the content length when you don't know the content length.
        AsyncRequestBody body = AsyncRequestBody.fromInputStream(inputStream, null, executor);

        CompletableFuture<PutObjectResponse> responseFuture =
                s33CrtAsyncClient.putObject(r -> r.bucket(bucketName).key(key), body);

        PutObjectResponse response = responseFuture.join(); // Wait for the response.
        logger.info("Object {} uploaded to bucket {}.", key, bucketName);
        executor.shutdown();
        return response;
    }
}
```
[ マルチパートアップロードが有効になっている標準の非同期 S3 クライアント](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/s3-async-client-multipart.html#s3-async-client-mp-on)を使用します。  

```
import com.example.s3.util.AsyncExampleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.s3.S3AsyncClient;
import software.amazon.awssdk.services.s3.model.PutObjectResponse;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PutObjectFromStreamAsyncMp {
    private static final Logger logger = LoggerFactory.getLogger(PutObjectFromStreamAsyncMp.class);

    public static void main(String[] args) {
        String bucketName = "amzn-s3-demo-bucket-" + UUID.randomUUID(); // Change bucket name.
        String key = UUID.randomUUID().toString();

        AsyncExampleUtils.createBucket(bucketName);
        try {
            PutObjectFromStreamAsyncMp example = new PutObjectFromStreamAsyncMp();
            S3AsyncClient s3AsyncClientMp = S3AsyncClient.builder().multipartEnabled(true).build();
            PutObjectResponse putObjectResponse = example.putObjectFromStreamMp(s3AsyncClientMp, bucketName, key);
            logger.info("Object {} etag: {}", key, putObjectResponse.eTag());
            logger.info("Object {} uploaded to bucket {}.", key, bucketName);
        } catch (SdkException e) {
            logger.error(e.getMessage(), e);
        } finally {
            AsyncExampleUtils.deleteObject(bucketName, key);
            AsyncExampleUtils.deleteBucket(bucketName);
        }
    }

    /**
     * @param s3AsyncClientMp - To upload content from a stream of unknown size, use can the S3 asynchronous client with multipart enabled.
     * @param bucketName - The name of the bucket.
     * @param key - The name of the object.
     * @return software.amazon.awssdk.services.s3.model.PutObjectResponse - Returns metadata pertaining to the put object operation.
     */
    public PutObjectResponse putObjectFromStreamMp(S3AsyncClient s3AsyncClientMp, String bucketName, String key) {

        // AsyncExampleUtils.randomString() returns a random string up to 100 characters.
        String randomString = AsyncExampleUtils.randomString();
        logger.info("random string to upload: {}: length={}", randomString, randomString.length());
        InputStream inputStream = new ByteArrayInputStream(randomString.getBytes());

        // Executor required to handle reading from the InputStream on a separate thread so the main upload is not blocked.
        ExecutorService executor = Executors.newSingleThreadExecutor();
        // Specify `null` for the content length when you don't know the content length.
        AsyncRequestBody body = AsyncRequestBody.fromInputStream(inputStream, null, executor);

        CompletableFuture<PutObjectResponse> responseFuture =
                s3AsyncClientMp.putObject(r -> r.bucket(bucketName).key(key), body);

        PutObjectResponse response = responseFuture.join(); // Wait for the response.
        logger.info("Object {} uploaded to bucket {}.", key, bucketName);
        executor.shutdown();
        return response;
    }
}
```
[Amazon S3 Transfer Manager](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/transfer-manager.html) を使用します。  

```
import com.example.s3.util.AsyncExampleUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.CompletedUpload;
import software.amazon.awssdk.transfer.s3.model.Upload;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class UploadStream {
    private static final Logger logger = LoggerFactory.getLogger(UploadStream.class);

    public static void main(String[] args) {
        String bucketName = "amzn-s3-demo-bucket" + UUID.randomUUID();
        String key = UUID.randomUUID().toString();

        AsyncExampleUtils.createBucket(bucketName);
        try {
            UploadStream example = new UploadStream();
            CompletedUpload completedUpload = example.uploadStream(S3TransferManager.create(), bucketName, key);
            logger.info("Object {} etag: {}", key, completedUpload.response().eTag());
            logger.info("Object {} uploaded to bucket {}.", key, bucketName);
        } catch (SdkException e) {
            logger.error(e.getMessage(), e);
        } finally {
            AsyncExampleUtils.deleteObject(bucketName, key);
            AsyncExampleUtils.deleteBucket(bucketName);
        }
    }

    /**
     * @param transferManager - To upload content from a stream of unknown size, you can use the S3TransferManager based on the AWS CRT-based S3 client.
     * @param bucketName - The name of the bucket.
     * @param key - The name of the object.
     * @return - software.amazon.awssdk.transfer.s3.model.CompletedUpload - The result of the completed upload.
     */
    public CompletedUpload uploadStream(S3TransferManager transferManager, String bucketName, String key) {

        // AsyncExampleUtils.randomString() returns a random string up to 100 characters.
        String randomString = AsyncExampleUtils.randomString();
        logger.info("random string to upload: {}: length={}", randomString, randomString.length());
        InputStream inputStream = new ByteArrayInputStream(randomString.getBytes());

        // Executor required to handle reading from the InputStream on a separate thread so the main upload is not blocked.
        ExecutorService executor = Executors.newSingleThreadExecutor();
        // Specify `null` for the content length when you don't know the content length.
        AsyncRequestBody body = AsyncRequestBody.fromInputStream(inputStream, null, executor);

        Upload upload = transferManager.upload(builder -> builder
                .requestBody(body)
                .putObjectRequest(req -> req.bucket(bucketName).key(key))
                .build());

        CompletedUpload completedUpload = upload.completionFuture().join();
        executor.shutdown();
        return completedUpload;
    }
}
```

### チェックサムの使用
<a name="s3_Scenario_UseChecksums_java_2_topic"></a>

次のコード例は、チェックサムを使用して Amazon S3 オブジェクトを操作する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
コード例では、以下のインポートのサブセットを使用しています。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm;
import software.amazon.awssdk.services.s3.model.ChecksumMode;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;
import software.amazon.awssdk.services.s3.waiters.S3Waiter;
import software.amazon.awssdk.transfer.s3.S3TransferManager;
import software.amazon.awssdk.transfer.s3.model.FileUpload;
import software.amazon.awssdk.transfer.s3.model.UploadFileRequest;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
```
[`PutObjectRequest` をビルドする](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/PutObjectRequest.Builder.html)ときに、`putObject` メソッドのチェックサムアルゴリズムを指定します。  

```
    public void putObjectWithChecksum() {
        s3Client.putObject(b -> b
                .bucket(bucketName)
                .key(key)
                .checksumAlgorithm(ChecksumAlgorithm.CRC32),
            RequestBody.fromString("This is a test"));
    }
```
[GetObjectRequest をビルドする](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/GetObjectRequest.Builder.html)ときに、`getObject` メソッドのチェックサムを確認します。  

```
    public GetObjectResponse getObjectWithChecksum() {
        return s3Client.getObject(b -> b
                .bucket(bucketName)
                .key(key)
                .checksumMode(ChecksumMode.ENABLED))
            .response();
    }
```
[`PutObjectRequest` をビルドする](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/model/PutObjectRequest.Builder.html)ときに、`putObject` メソッドのチェックサムを事前に計算します。  

```
    public void putObjectWithPrecalculatedChecksum(String filePath) {
        String checksum = calculateChecksum(filePath, "SHA-256");

        s3Client.putObject((b -> b
                .bucket(bucketName)
                .key(key)
                .checksumSHA256(checksum)),
            RequestBody.fromFile(Paths.get(filePath)));
    }
```
[AWS CRT ベースの S3 クライアント](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/crt-based-s3-client.html)上にある [S3 Transfer Manager](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/transfer-manager.html) を使用して、コンテンツのサイズがしきい値を超えたときにマルチパートアップロードを透過的に実行します。デフォルトのしきい値は 8 MB です。  
SDK で使用するチェックサムアルゴリズムを指定できます。デフォルトでは、SDK は CRC32 アルゴリズムを使用します。  

```
    public void multipartUploadWithChecksumTm(String filePath) {
        S3TransferManager transferManager = S3TransferManager.create();
        UploadFileRequest uploadFileRequest = UploadFileRequest.builder()
            .putObjectRequest(b -> b
                .bucket(bucketName)
                .key(key)
                .checksumAlgorithm(ChecksumAlgorithm.SHA1))
            .source(Paths.get(filePath))
            .build();
        FileUpload fileUpload = transferManager.uploadFile(uploadFileRequest);
        fileUpload.completionFuture().join();
        transferManager.close();
    }
```
[S3Client API](https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/s3/S3Client.html) または (S3AsyncClient API) を使用してマルチパートアップロードを実行します。追加のチェックサムを指定する場合は、アップロードの開始時に使用するアルゴリズムを指定する必要があります。また、パートリクエストごとにアルゴリズムを指定し、アップロード後にパートごとに計算されたチェックサムを指定する必要があります。  

```
    public void multipartUploadWithChecksumS3Client(String filePath) {
        ChecksumAlgorithm algorithm = ChecksumAlgorithm.CRC32;

        // Initiate the multipart upload.
        CreateMultipartUploadResponse createMultipartUploadResponse = s3Client.createMultipartUpload(b -> b
            .bucket(bucketName)
            .key(key)
            .checksumAlgorithm(algorithm)); // Checksum specified on initiation.
        String uploadId = createMultipartUploadResponse.uploadId();

        // Upload the parts of the file.
        int partNumber = 1;
        List<CompletedPart> completedParts = new ArrayList<>();
        ByteBuffer bb = ByteBuffer.allocate(1024 * 1024 * 5); // 5 MB byte buffer

        try (RandomAccessFile file = new RandomAccessFile(filePath, "r")) {
            long fileSize = file.length();
            long position = 0;
            while (position < fileSize) {
                file.seek(position);
                long read = file.getChannel().read(bb);

                bb.flip(); // Swap position and limit before reading from the buffer.
                UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
                    .bucket(bucketName)
                    .key(key)
                    .uploadId(uploadId)
                    .checksumAlgorithm(algorithm) // Checksum specified on each part.
                    .partNumber(partNumber)
                    .build();

                UploadPartResponse partResponse = s3Client.uploadPart(
                    uploadPartRequest,
                    RequestBody.fromByteBuffer(bb));

                CompletedPart part = CompletedPart.builder()
                    .partNumber(partNumber)
                    .checksumCRC32(partResponse.checksumCRC32()) // Provide the calculated checksum.
                    .eTag(partResponse.eTag())
                    .build();
                completedParts.add(part);

                bb.clear();
                position += read;
                partNumber++;
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }

        // Complete the multipart upload.
        s3Client.completeMultipartUpload(b -> b
            .bucket(bucketName)
            .key(key)
            .uploadId(uploadId)
            .multipartUpload(CompletedMultipartUpload.builder().parts(completedParts).build()));
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CompleteMultipartUpload](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CompleteMultipartUpload)
  + [CreateMultipartUpload](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateMultipartUpload)
  + [UploadPart](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/UploadPart)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_java_2_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Java を使用した Lambda での S3 イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package example;

import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.S3Client;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Handler implements RequestHandler<S3Event, String> {
    private static final Logger logger = LoggerFactory.getLogger(Handler.class);
    @Override
    public String handleRequest(S3Event s3event, Context context) {
        try {
          S3EventNotificationRecord record = s3event.getRecords().get(0);
          String srcBucket = record.getS3().getBucket().getName();
          String srcKey = record.getS3().getObject().getUrlDecodedKey();

          S3Client s3Client = S3Client.builder().build();
          HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey);

          logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType());

          return "Ok";
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
    }

    private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) {
        HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
                .bucket(bucket)
                .key(key)
                .build();
        return s3Client.headObject(headObjectRequest);
    }
}
```

# SDK for Java 2.x を使用する Amazon S3 Control の例
<a name="java_2_s3-control_code_examples"></a>

次のコード例は、Amazon S3 Control AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3 Control
<a name="s3-control_Hello_java_2_topic"></a>

次のコード例は、Amazon S3 Control の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3control.S3ControlAsyncClient;
import software.amazon.awssdk.services.s3control.model.JobListDescriptor;
import software.amazon.awssdk.services.s3control.model.JobStatus;
import software.amazon.awssdk.services.s3control.model.ListJobsRequest;
import software.amazon.awssdk.services.s3control.paginators.ListJobsPublisher;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

/**
 * Before running this example:
 * <p/>
 * The SDK must be able to authenticate AWS requests on your behalf. If you have not configured
 * authentication for SDKs and tools,see https://docs.aws.amazon.com/sdkref/latest/guide/access.html in the AWS SDKs and Tools Reference Guide.
 * <p/>
 * You must have a runtime environment configured with the Java SDK.
 * See https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html in the Developer Guide if this is not set up.
 */
public class HelloS3Batch {
    private static S3ControlAsyncClient asyncClient;

    public static void main(String[] args) {
        S3BatchActions actions = new S3BatchActions();
        String accountId = actions.getAccountId();
        try {
            listBatchJobsAsync(accountId)
                .exceptionally(ex -> {
                    System.err.println("List batch jobs failed: " + ex.getMessage());
                    return null;
                })
                .join();

        } catch (CompletionException ex) {
            System.err.println("Failed to list batch jobs: " + ex.getMessage());
        }
    }

    /**
     * Retrieves the asynchronous S3 Control client instance.
     * <p>
     * This method creates and returns a singleton instance of the {@link S3ControlAsyncClient}. If the instance
     * has not been created yet, it will be initialized with the following configuration:
     * <ul>
     *   <li>Maximum concurrency: 100</li>
     *   <li>Connection timeout: 60 seconds</li>
     *   <li>Read timeout: 60 seconds</li>
     *   <li>Write timeout: 60 seconds</li>
     *   <li>API call timeout: 2 minutes</li>
     *   <li>API call attempt timeout: 90 seconds</li>
     *   <li>Retry policy: 3 retries</li>
     *   <li>Region: US_EAST_1</li>
     *   <li>Credentials provider: {@link EnvironmentVariableCredentialsProvider}</li>
     * </ul>
     *
     * @return the asynchronous S3 Control client instance
     */
    private static S3ControlAsyncClient getAsyncClient() {
        if (asyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            asyncClient = S3ControlAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return asyncClient;
    }

    /**
     * Asynchronously lists batch jobs that have completed for the specified account.
     *
     * @param accountId the ID of the account to list jobs for
     * @return a CompletableFuture that completes when the job listing operation is finished
     */
    public static CompletableFuture<Void> listBatchJobsAsync(String accountId) {
        ListJobsRequest jobsRequest = ListJobsRequest.builder()
            .jobStatuses(JobStatus.COMPLETE)
            .accountId(accountId)
            .maxResults(10)
            .build();

        ListJobsPublisher publisher = getAsyncClient().listJobsPaginator(jobsRequest);
        return publisher.subscribe(response -> {
            List<JobListDescriptor> jobs = response.jobs();
            for (JobListDescriptor job : jobs) {
                System.out.println("The job id is " + job.jobId());
                System.out.println("The job priority is " + job.priority());
            }
        }).thenAccept(response -> {
            System.out.println("Listing batch jobs completed");
        }).exceptionally(ex -> {
            System.err.println("Failed to list batch jobs: " + ex.getMessage());
            throw new RuntimeException(ex);
        });
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/ListJobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3-control_Basics_java_2_topic"></a>

次のコード例は、Amazon S3 Control のコアオペレーションを学ぶ方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。
コアオペレーションについて学びます。  

```
package com.example.s3.batch;

import software.amazon.awssdk.services.s3.model.S3Exception;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.CompletionException;

public class S3BatchScenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final String STACK_NAME = "MyS3Stack";
    public static void main(String[] args) throws IOException {
        S3BatchActions actions = new S3BatchActions();
        String accountId = actions.getAccountId();
        String uuid = java.util.UUID.randomUUID().toString();
        Scanner scanner = new Scanner(System.in);

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon S3 Batch basics scenario.");
        System.out.println("""
            S3 Batch operations enables efficient and cost-effective processing of large-scale 
            data stored in Amazon S3. It automatically scales resources to handle varying workloads 
            without the need for manual intervention. 
                        
            One of the key features of S3 Batch is its ability to perform tagging operations on objects stored in 
            S3 buckets. Users can leverage S3 Batch to apply, update, or remove tags on thousands or millions of 
            objects in a single operation, streamlining the management and organization of their data. 
                        
            This can be particularly useful for tasks such as cost allocation, lifecycle management, or 
            metadata-driven workflows, where consistent and accurate tagging is essential. 
            S3 Batch's scalability and serverless nature make it an ideal solution for organizations with 
            growing data volumes and complex data management requirements.
                        
            This Java program walks you through Amazon S3 Batch operations. 
                        
            Let's get started...
                   
            """);
        waitForInputToContinue(scanner);
        // Use CloudFormation to stand up the resource required for this scenario.
        System.out.println("Use CloudFormation to stand up the resource required for this scenario.");
        CloudFormationHelper.deployCloudFormationStack(STACK_NAME);

        Map<String, String> stackOutputs = CloudFormationHelper.getStackOutputs(STACK_NAME);
        String iamRoleArn = stackOutputs.get("S3BatchRoleArn");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Setup the required bucket for this scenario.");
        waitForInputToContinue(scanner);
        String bucketName = "amzn-s3-demo-bucket-" + UUID.randomUUID(); // Change bucket name. 
        actions.createBucket(bucketName);
        String reportBucketName = "arn:aws:s3:::"+bucketName;
        String manifestLocation = "arn:aws:s3:::"+bucketName+"/job-manifest.csv";
        System.out.println("Populate the bucket with the required files.");
        String[] fileNames = {"job-manifest.csv", "object-key-1.txt", "object-key-2.txt", "object-key-3.txt", "object-key-4.txt"};
        actions.uploadFilesToBucket(bucketName, fileNames, actions);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Create a S3 Batch Job");
        System.out.println("This job tags all objects listed in the manifest file with tags");
        waitForInputToContinue(scanner);
        String jobId ;
        try {
            jobId = actions.createS3JobAsync(accountId, iamRoleArn, manifestLocation, reportBucketName, uuid).join();
            System.out.println("The Job id is " + jobId);

        } catch (S3Exception e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }

        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Update an existing S3 Batch Operations job's priority");
        System.out.println("""
             In this step, we modify the job priority value. The higher the number, the higher the priority. 
             So, a job with a priority of `30` would have a higher priority than a job with 
             a priority of `20`. This is a common way to represent the priority of a task 
             or job, with higher numbers indicating a higher priority.
             
             Ensure that the job status allows for priority updates. Jobs in certain 
             states (e.g., Cancelled, Failed, or Completed) cannot have their priorities 
             updated. Only jobs in the Active or Suspended state typically allow priority 
             updates.
             """);

        try {
            actions.updateJobPriorityAsync(jobId, accountId)
                .exceptionally(ex -> {
                    System.err.println("Update job priority failed: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (CompletionException ex) {
            System.err.println("Failed to update job priority: " + ex.getMessage());
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Cancel the S3 Batch job");
        System.out.print("Do you want to cancel the Batch job? (y/n): ");
        String cancelAns = scanner.nextLine();
        if (cancelAns != null && cancelAns.trim().equalsIgnoreCase("y")) {
            try {
                actions.cancelJobAsync(jobId, accountId)
                    .exceptionally(ex -> {
                        System.err.println("Cancel job failed: " + ex.getMessage());
                        return null;
                    })
                    .join();
            } catch (CompletionException ex) {
                System.err.println("Failed to cancel job: " + ex.getMessage());
            }
        } else {
            System.out.println("Job " +jobId +" was not canceled.");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Describe the job that was just created");
        waitForInputToContinue(scanner);
        try {
            actions.describeJobAsync(jobId, accountId)
                .exceptionally(ex -> {
                    System.err.println("Describe job failed: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (CompletionException ex) {
            System.err.println("Failed to describe job: " + ex.getMessage());
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Describe the tags associated with the job");
        waitForInputToContinue(scanner);
        try {
            actions.getJobTagsAsync(jobId, accountId)
                .exceptionally(ex -> {
                    System.err.println("Get job tags failed: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (CompletionException ex) {
            System.err.println("Failed to get job tags: " + ex.getMessage());
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Update Batch Job Tags");
        waitForInputToContinue(scanner);
        try {
            actions.putJobTaggingAsync(jobId, accountId)
                .exceptionally(ex -> {
                    System.err.println("Put job tagging failed: " + ex.getMessage());
                    return null;
                })
                .join();
        } catch (CompletionException ex) {
            System.err.println("Failed to put job tagging: " + ex.getMessage());
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Delete the Amazon S3 Batch job tagging.");
        System.out.print("Do you want to delete Batch job tagging? (y/n)");
        String delAns = scanner.nextLine();
        if (delAns != null && delAns.trim().equalsIgnoreCase("y")) {
            try {
                actions.deleteBatchJobTagsAsync(jobId, accountId)
                    .exceptionally(ex -> {
                        System.err.println("Delete batch job tags failed: " + ex.getMessage());
                        return null;
                    })
                    .join();
            } catch (CompletionException ex) {
                System.err.println("Failed to delete batch job tags: " + ex.getMessage());
            }
        } else {
            System.out.println("Tagging was not deleted.");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.print("Do you want to delete the AWS resources used in this scenario? (y/n)");
        String delResAns = scanner.nextLine();
        if (delResAns != null && delResAns.trim().equalsIgnoreCase("y")) {
            actions.deleteFilesFromBucket(bucketName, fileNames, actions);
            actions.deleteBucketFolderAsync(bucketName);
            actions.deleteBucket(bucketName)
                .thenRun(() -> System.out.println("Bucket deletion completed"))
                .exceptionally(ex -> {
                    System.err.println("Error occurred: " + ex.getMessage());
                    return null;
                });
            CloudFormationHelper.destroyCloudFormationStack(STACK_NAME);
        } else {
            System.out.println("The AWS resources were not deleted.");
        }
        System.out.println("The Amazon S3 Batch scenario has successfully completed.");
        System.out.println(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println();
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println();
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }


}
```
オペレーションをラップするアクションクラス。  

```
public class S3BatchActions {

    private static S3ControlAsyncClient asyncClient;

    private static S3AsyncClient s3AsyncClient ;
    /**
     * Retrieves the asynchronous S3 Control client instance.
     * <p>
     * This method creates and returns a singleton instance of the {@link S3ControlAsyncClient}. If the instance
     * has not been created yet, it will be initialized with the following configuration:
     * <ul>
     *   <li>Maximum concurrency: 100</li>
     *   <li>Connection timeout: 60 seconds</li>
     *   <li>Read timeout: 60 seconds</li>
     *   <li>Write timeout: 60 seconds</li>
     *   <li>API call timeout: 2 minutes</li>
     *   <li>API call attempt timeout: 90 seconds</li>
     *   <li>Retry policy: 3 retries</li>
     *   <li>Region: US_EAST_1</li>
     *   <li>Credentials provider: {@link EnvironmentVariableCredentialsProvider}</li>
     * </ul>
     *
     * @return the asynchronous S3 Control client instance
     */
    private static S3ControlAsyncClient getAsyncClient() {
        if (asyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryPolicy(RetryPolicy.builder()
                    .numRetries(3)
                    .build())
                .build();

            asyncClient = S3ControlAsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return asyncClient;
    }

    private static S3AsyncClient getS3AsyncClient() {
        if (asyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            s3AsyncClient = S3AsyncClient.builder()
                .region(Region.US_EAST_1)
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return s3AsyncClient;
    }


    /**
     * Cancels a job asynchronously.
     *
     * @param jobId The ID of the job to be canceled.
     * @param accountId The ID of the account associated with the job.
     * @return A {@link CompletableFuture} that completes when the job status has been updated to "CANCELLED".
     *         If an error occurs during the update, the returned future will complete exceptionally.
     */
    public CompletableFuture<Void> cancelJobAsync(String jobId, String accountId) {
        UpdateJobStatusRequest updateJobStatusRequest = UpdateJobStatusRequest.builder()
            .accountId(accountId)
            .jobId(jobId)
            .requestedJobStatus(String.valueOf(JobStatus.CANCELLED))
            .build();

        return asyncClient.updateJobStatus(updateJobStatusRequest)
            .thenAccept(updateJobStatusResponse -> {
                System.out.println("Job status updated to: " + updateJobStatusResponse.status());
            })
            .exceptionally(ex -> {
                System.err.println("Failed to cancel job: " + ex.getMessage());
                throw new RuntimeException(ex); // Propagate the exception
            });
    }

    /**
     * Updates the priority of a job asynchronously.
     *
     * @param jobId     the ID of the job to update
     * @param accountId the ID of the account associated with the job
     * @return a {@link CompletableFuture} that represents the asynchronous operation, which completes when the job priority has been updated or an error has occurred
     */
    public CompletableFuture<Void> updateJobPriorityAsync(String jobId, String accountId) {
        UpdateJobPriorityRequest priorityRequest = UpdateJobPriorityRequest.builder()
            .accountId(accountId)
            .jobId(jobId)
            .priority(60)
            .build();

        CompletableFuture<Void> future = new CompletableFuture<>();
        getAsyncClient().updateJobPriority(priorityRequest)
            .thenAccept(response -> {
                System.out.println("The job priority was updated");
                future.complete(null); // Complete the CompletableFuture on successful execution
            })
            .exceptionally(ex -> {
                System.err.println("Failed to update job priority: " + ex.getMessage());
                future.completeExceptionally(ex); // Complete the CompletableFuture exceptionally on error
                return null; // Return null to handle the exception
            });

        return future;
    }

    /**
     * Asynchronously retrieves the tags associated with a specific job in an AWS account.
     *
     * @param jobId     the ID of the job for which to retrieve the tags
     * @param accountId the ID of the AWS account associated with the job
     * @return a {@link CompletableFuture} that completes when the job tags have been retrieved, or with an exception if the operation fails
     * @throws RuntimeException if an error occurs while retrieving the job tags
     */
    public CompletableFuture<Void> getJobTagsAsync(String jobId, String accountId) {
        GetJobTaggingRequest request = GetJobTaggingRequest.builder()
            .jobId(jobId)
            .accountId(accountId)
            .build();

        return asyncClient.getJobTagging(request)
            .thenAccept(response -> {
                List<S3Tag> tags = response.tags();
                if (tags.isEmpty()) {
                    System.out.println("No tags found for job ID: " + jobId);
                } else {
                    for (S3Tag tag : tags) {
                        System.out.println("Tag key is: " + tag.key());
                        System.out.println("Tag value is: " + tag.value());
                    }
                }
            })
            .exceptionally(ex -> {
                System.err.println("Failed to get job tags: " + ex.getMessage());
                throw new RuntimeException(ex); // Propagate the exception
            });
    }

    /**
     * Asynchronously deletes the tags associated with a specific batch job.
     *
     * @param jobId     The ID of the batch job whose tags should be deleted.
     * @param accountId The ID of the account associated with the batch job.
     * @return A CompletableFuture that completes when the job tags have been successfully deleted, or an exception is thrown if the deletion fails.
     */
    public CompletableFuture<Void> deleteBatchJobTagsAsync(String jobId, String accountId) {
        DeleteJobTaggingRequest jobTaggingRequest = DeleteJobTaggingRequest.builder()
            .accountId(accountId)
            .jobId(jobId)
            .build();

        return asyncClient.deleteJobTagging(jobTaggingRequest)
            .thenAccept(response -> {
                System.out.println("You have successfully deleted " + jobId + " tagging.");
            })
            .exceptionally(ex -> {
                System.err.println("Failed to delete job tags: " + ex.getMessage());
                throw new RuntimeException(ex);
            });
    }

    /**
     * Asynchronously describes the specified job.
     *
     * @param jobId     the ID of the job to describe
     * @param accountId the ID of the AWS account associated with the job
     * @return a {@link CompletableFuture} that completes when the job description is available
     * @throws RuntimeException if an error occurs while describing the job
     */
    public CompletableFuture<Void> describeJobAsync(String jobId, String accountId) {
        DescribeJobRequest jobRequest = DescribeJobRequest.builder()
            .jobId(jobId)
            .accountId(accountId)
            .build();

        return getAsyncClient().describeJob(jobRequest)
            .thenAccept(response -> {
                System.out.println("Job ID: " + response.job().jobId());
                System.out.println("Description: " + response.job().description());
                System.out.println("Status: " + response.job().statusAsString());
                System.out.println("Role ARN: " + response.job().roleArn());
                System.out.println("Priority: " + response.job().priority());
                System.out.println("Progress Summary: " + response.job().progressSummary());

                // Print out details about the job manifest.
                JobManifest manifest = response.job().manifest();
                System.out.println("Manifest Location: " + manifest.location().objectArn());
                System.out.println("Manifest ETag: " + manifest.location().eTag());

                // Print out details about the job operation.
                JobOperation operation = response.job().operation();
                if (operation.s3PutObjectTagging() != null) {
                    System.out.println("Operation: S3 Put Object Tagging");
                    System.out.println("Tag Set: " + operation.s3PutObjectTagging().tagSet());
                }

                // Print out details about the job report.
                JobReport report = response.job().report();
                System.out.println("Report Bucket: " + report.bucket());
                System.out.println("Report Prefix: " + report.prefix());
                System.out.println("Report Format: " + report.format());
                System.out.println("Report Enabled: " + report.enabled());
                System.out.println("Report Scope: " + report.reportScopeAsString());
            })
            .exceptionally(ex -> {
                System.err.println("Failed to describe job: " + ex.getMessage());
                throw new RuntimeException(ex);
            });
    }

    /**
     * Creates an asynchronous S3 job using the AWS Java SDK.
     *
     * @param accountId         the AWS account ID associated with the job
     * @param iamRoleArn        the ARN of the IAM role to be used for the job
     * @param manifestLocation  the location of the job manifest file in S3
     * @param reportBucketName  the name of the S3 bucket to store the job report
     * @param uuid              a unique identifier for the job
     * @return a CompletableFuture that represents the asynchronous creation of the S3 job.
     *         The CompletableFuture will return the job ID if the job is created successfully,
     *         or throw an exception if there is an error.
     */
    public CompletableFuture<String> createS3JobAsync(String accountId, String iamRoleArn,
                                                      String manifestLocation, String reportBucketName, String uuid) {

        String[] bucketName = new String[]{""};
        String[] parts = reportBucketName.split(":::");
        if (parts.length > 1) {
            bucketName[0] = parts[1];
        } else {
            System.out.println("The input string does not contain the expected format.");
        }

        return CompletableFuture.supplyAsync(() -> getETag(bucketName[0], "job-manifest.csv"))
            .thenCompose(eTag -> {
                  ArrayList<S3Tag> tagSet = new ArrayList<>();
                S3Tag s3Tag = S3Tag.builder()
                    .key("keyOne")
                    .value("ValueOne")
                    .build();
                S3Tag s3Tag2 = S3Tag.builder()
                    .key("keyTwo")
                    .value("ValueTwo")
                    .build();
                tagSet.add(s3Tag);
                tagSet.add(s3Tag2);

                S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder()
                    .tagSet(tagSet)
                    .build();

                JobOperation jobOperation = JobOperation.builder()
                    .s3PutObjectTagging(objectTaggingOperation)
                    .build();

                JobManifestLocation jobManifestLocation = JobManifestLocation.builder()
                    .objectArn(manifestLocation)
                    .eTag(eTag)
                    .build();

                JobManifestSpec manifestSpec = JobManifestSpec.builder()
                    .fieldsWithStrings("Bucket", "Key")
                    .format("S3BatchOperations_CSV_20180820")
                    .build();

                JobManifest jobManifest = JobManifest.builder()
                    .spec(manifestSpec)
                    .location(jobManifestLocation)
                    .build();

                JobReport jobReport = JobReport.builder()
                    .bucket(reportBucketName)
                    .prefix("reports")
                    .format("Report_CSV_20180820")
                    .enabled(true)
                    .reportScope("AllTasks")
                    .build();

                CreateJobRequest jobRequest = CreateJobRequest.builder()
                    .accountId(accountId)
                    .description("Job created using the AWS Java SDK")
                    .manifest(jobManifest)
                    .operation(jobOperation)
                    .report(jobReport)
                    .priority(42)
                    .roleArn(iamRoleArn)
                    .clientRequestToken(uuid)
                    .confirmationRequired(false)
                    .build();

                // Create the job asynchronously.
                 return getAsyncClient().createJob(jobRequest)
                    .thenApply(CreateJobResponse::jobId);
                 })
                 .handle((jobId, ex) -> {
                    if (ex != null) {
                    Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                    if (cause instanceof S3ControlException) {
                        throw new CompletionException(cause);
                    } else {
                        throw new RuntimeException(cause);
                    }
                }
                return jobId;
            });
    }

    /**
     * Retrieves the ETag (Entity Tag) for an object stored in an Amazon S3 bucket.
     *
     * @param bucketName the name of the Amazon S3 bucket where the object is stored
     * @param key the key (file name) of the object in the Amazon S3 bucket
     * @return the ETag of the object
     */
    public String getETag(String bucketName, String key) {
        S3Client s3Client = S3Client.builder()
            .region(Region.US_EAST_1)
            .build();

        HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
            .bucket(bucketName)
            .key(key)
            .build();

        HeadObjectResponse headObjectResponse = s3Client.headObject(headObjectRequest);
        return headObjectResponse.eTag();
    }

    /**
     * Asynchronously adds tags to a job in the system.
     *
     * @param jobId     the ID of the job to add tags to
     * @param accountId the account ID associated with the job
     * @return a CompletableFuture that completes when the tagging operation is finished
     */
    public CompletableFuture<Void> putJobTaggingAsync(String jobId, String accountId) {
        S3Tag departmentTag = S3Tag.builder()
            .key("department")
            .value("Marketing")
            .build();

        S3Tag fiscalYearTag = S3Tag.builder()
            .key("FiscalYear")
            .value("2020")
            .build();

        PutJobTaggingRequest putJobTaggingRequest = PutJobTaggingRequest.builder()
            .jobId(jobId)
            .accountId(accountId)
            .tags(departmentTag, fiscalYearTag)
            .build();

        return asyncClient.putJobTagging(putJobTaggingRequest)
            .thenRun(() -> {
                System.out.println("Additional Tags were added to job " + jobId);
            })
            .exceptionally(ex -> {
                System.err.println("Failed to add tags to job: " + ex.getMessage());
                throw new RuntimeException(ex); // Propagate the exception
            });
    }

    // Setup the S3 bucket required for this scenario.
    /**
     * Creates an Amazon S3 bucket with the specified name.
     *
     * @param bucketName the name of the S3 bucket to create
     * @throws S3Exception if there is an error creating the bucket
     */
    public void createBucket(String bucketName) {
        try {
            S3Client s3Client = S3Client.builder()
                .region(Region.US_EAST_1)
                .build();


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

    /**
     * Uploads a file to an Amazon S3 bucket asynchronously.
     *
     * @param bucketName the name of the S3 bucket to upload the file to
     * @param fileName the name of the file to be uploaded
     * @throws RuntimeException if an error occurs during the file upload
     */
    public void populateBucket(String bucketName, String fileName) {
        // Define the path to the directory.
        Path filePath = Paths.get("src/main/resources/batch/", fileName).toAbsolutePath();
        PutObjectRequest putOb = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(fileName)
            .build();

        CompletableFuture<PutObjectResponse> future = getS3AsyncClient().putObject(putOb, AsyncRequestBody.fromFile(filePath));
        future.whenComplete((result, ex) -> {
            if (ex != null) {
                System.err.println("Error uploading file: " + ex.getMessage());
            } else {
                System.out.println("Successfully placed " + fileName + " into bucket " + bucketName);
            }
        }).join();
    }


    // Update the bucketName in CSV.
    public void updateCSV(String newValue) {
        Path csvFilePath = Paths.get("src/main/resources/batch/job-manifest.csv").toAbsolutePath();
        try {
            // Read all lines from the CSV file.
            List<String> lines = Files.readAllLines(csvFilePath);

            // Update the first value in each line.
            List<String> updatedLines = lines.stream()
                .map(line -> {
                    String[] parts = line.split(",");
                    parts[0] = newValue;
                    return String.join(",", parts);
                })
                .collect(Collectors.toList());

            // Write the updated lines back to the CSV file
            Files.write(csvFilePath, updatedLines);
            System.out.println("CSV file updated successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Deletes an object from an Amazon S3 bucket asynchronously.
     *
     * @param bucketName The name of the S3 bucket where the object is stored.
     * @param objectName The name of the object to be deleted.
     * @return A {@link CompletableFuture} that completes when the object has been deleted,
     *         or throws a {@link RuntimeException} if an error occurs during the deletion.
     */
    public CompletableFuture<Void> deleteBucketObjects(String bucketName, String objectName) {
        ArrayList<ObjectIdentifier> toDelete = new ArrayList<>();
        toDelete.add(ObjectIdentifier.builder()
            .key(objectName)
            .build());

        DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
            .bucket(bucketName)
            .delete(Delete.builder()
                .objects(toDelete).build())
            .build();

        return getS3AsyncClient().deleteObjects(dor)
            .thenAccept(result -> {
                System.out.println("The object was deleted!");
            })
            .exceptionally(ex -> {
                throw new RuntimeException("Error deleting object: " + ex.getMessage(), ex);
            });
    }

    /**
     * Deletes a folder and all its contents asynchronously from an Amazon S3 bucket.
     *
     * @param bucketName the name of the S3 bucket containing the folder to be deleted
     * @return a {@link CompletableFuture} that completes when the folder and its contents have been deleted
     * @throws RuntimeException if any error occurs during the deletion process
     */
    public void deleteBucketFolderAsync(String bucketName) {
        String folderName = "reports/";
        ListObjectsV2Request request = ListObjectsV2Request.builder()
            .bucket(bucketName)
            .prefix(folderName)
            .build();

        CompletableFuture<ListObjectsV2Response> listObjectsFuture = getS3AsyncClient().listObjectsV2(request);
        listObjectsFuture.thenCompose(response -> {
            List<CompletableFuture<DeleteObjectResponse>> deleteFutures = response.contents().stream()
                .map(obj -> {
                    DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
                        .bucket(bucketName)
                        .key(obj.key())
                        .build();
                    return getS3AsyncClient().deleteObject(deleteRequest)
                        .thenApply(deleteResponse -> {
                            System.out.println("Deleted object: " + obj.key());
                            return deleteResponse;
                        });
                })
                .collect(Collectors.toList());

            return CompletableFuture.allOf(deleteFutures.toArray(new CompletableFuture[0]))
                .thenCompose(v -> {
                    // Delete the folder.
                    DeleteObjectRequest deleteRequest = DeleteObjectRequest.builder()
                        .bucket(bucketName)
                        .key(folderName)
                        .build();
                    return getS3AsyncClient().deleteObject(deleteRequest)
                        .thenApply(deleteResponse -> {
                            System.out.println("Deleted folder: " + folderName);
                            return deleteResponse;
                        });
                });
        }).join();
    }

    /**
     * Deletes an Amazon S3 bucket.
     *
     * @param bucketName the name of the bucket to delete
     * @return a {@link CompletableFuture} that completes when the bucket has been deleted, or exceptionally if there is an error
     * @throws RuntimeException if there is an error deleting the bucket
     */
    public CompletableFuture<Void> deleteBucket(String bucketName) {
        S3AsyncClient s3Client = getS3AsyncClient();
        return s3Client.deleteBucket(DeleteBucketRequest.builder()
                .bucket(bucketName)
                .build())
            .thenAccept(deleteBucketResponse -> {
                System.out.println(bucketName + " was deleted");
            })
            .exceptionally(ex -> {
                // Handle the exception or rethrow it.
                throw new RuntimeException("Failed to delete bucket: " + bucketName, ex);
            });
    }

    /**
     * Uploads a set of files to an Amazon S3 bucket.
     *
     * @param bucketName the name of the S3 bucket to upload the files to
     * @param fileNames an array of file names to be uploaded
     * @param actions an instance of {@link S3BatchActions} that provides the implementation for the necessary S3 operations
     * @throws IOException if there's an error creating the text files or uploading the files to the S3 bucket
     */
    public static void uploadFilesToBucket(String bucketName, String[] fileNames, S3BatchActions actions) throws IOException {
        actions.updateCSV(bucketName);
        createTextFiles(fileNames);
        for (String fileName : fileNames) {
            actions.populateBucket(bucketName, fileName);
        }
        System.out.println("All files are placed in the S3 bucket " + bucketName);
    }

    /**
     * Deletes the specified files from the given S3 bucket.
     *
     * @param bucketName the name of the S3 bucket
     * @param fileNames an array of file names to be deleted from the bucket
     * @param actions the S3BatchActions instance to be used for the file deletion
     * @throws IOException if an I/O error occurs during the file deletion
     */
    public void deleteFilesFromBucket(String bucketName, String[] fileNames, S3BatchActions actions) throws IOException {
        for (String fileName : fileNames) {
                   actions.deleteBucketObjects(bucketName, fileName)
                  .thenRun(() -> System.out.println("Object deletion completed"))
                  .exceptionally(ex -> {
                      System.err.println("Error occurred: " + ex.getMessage());
                      return null;
                  });
        }
        System.out.println("All files have been deleted from the bucket " + bucketName);
    }

    public static void createTextFiles(String[] fileNames) {
        String currentDirectory = System.getProperty("user.dir");
        String directoryPath = currentDirectory + "\\src\\main\\resources\\batch";
        Path path = Paths.get(directoryPath);

        try {
            // Create the directory if it doesn't exist.
            if (Files.notExists(path)) {
                Files.createDirectories(path);
                System.out.println("Created directory: " + path.toString());
            } else {
                System.out.println("Directory already exists: " + path.toString());
            }

            for (String fileName : fileNames) {
                // Check if the file is a .txt file.
                if (fileName.endsWith(".txt")) {
                    // Define the path for the new file.
                    Path filePath = path.resolve(fileName);
                    System.out.println("Attempting to create file: " + filePath.toString());

                    // Create and write content to the new file.
                    Files.write(filePath, "This is a test".getBytes());

                    // Verify the file was created.
                    if (Files.exists(filePath)) {
                        System.out.println("Successfully created file: " + filePath.toString());
                    } else {
                        System.out.println("Failed to create file: " + filePath.toString());
                    }
                }
            }

        } catch (IOException e) {
            System.err.println("An error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public String getAccountId() {
        StsClient stsClient = StsClient.builder()
            .region(Region.US_EAST_1)
            .build();

        GetCallerIdentityResponse callerIdentityResponse = stsClient.getCallerIdentity();
        return callerIdentityResponse.account();
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/CreateJob)
  + [DeleteJobTagging](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/DeleteJobTagging)
  + [DescribeJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/DescribeJob)
  + [GetJobTagging](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/GetJobTagging)
  + [ListJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/ListJobs)
  + [PutJobTagging](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/PutJobTagging)
  + [UpdateJobPriority](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/UpdateJobPriority)
  + [UpdateJobStatus](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/UpdateJobStatus)

## アクション
<a name="actions"></a>

### `CreateJob`
<a name="s3-control_CreateJob_java_2_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。
非同期 S3 ジョブを作成します。  

```
    /**
     * Creates an asynchronous S3 job using the AWS Java SDK.
     *
     * @param accountId         the AWS account ID associated with the job
     * @param iamRoleArn        the ARN of the IAM role to be used for the job
     * @param manifestLocation  the location of the job manifest file in S3
     * @param reportBucketName  the name of the S3 bucket to store the job report
     * @param uuid              a unique identifier for the job
     * @return a CompletableFuture that represents the asynchronous creation of the S3 job.
     *         The CompletableFuture will return the job ID if the job is created successfully,
     *         or throw an exception if there is an error.
     */
    public CompletableFuture<String> createS3JobAsync(String accountId, String iamRoleArn,
                                                      String manifestLocation, String reportBucketName, String uuid) {

        String[] bucketName = new String[]{""};
        String[] parts = reportBucketName.split(":::");
        if (parts.length > 1) {
            bucketName[0] = parts[1];
        } else {
            System.out.println("The input string does not contain the expected format.");
        }

        return CompletableFuture.supplyAsync(() -> getETag(bucketName[0], "job-manifest.csv"))
            .thenCompose(eTag -> {
                  ArrayList<S3Tag> tagSet = new ArrayList<>();
                S3Tag s3Tag = S3Tag.builder()
                    .key("keyOne")
                    .value("ValueOne")
                    .build();
                S3Tag s3Tag2 = S3Tag.builder()
                    .key("keyTwo")
                    .value("ValueTwo")
                    .build();
                tagSet.add(s3Tag);
                tagSet.add(s3Tag2);

                S3SetObjectTaggingOperation objectTaggingOperation = S3SetObjectTaggingOperation.builder()
                    .tagSet(tagSet)
                    .build();

                JobOperation jobOperation = JobOperation.builder()
                    .s3PutObjectTagging(objectTaggingOperation)
                    .build();

                JobManifestLocation jobManifestLocation = JobManifestLocation.builder()
                    .objectArn(manifestLocation)
                    .eTag(eTag)
                    .build();

                JobManifestSpec manifestSpec = JobManifestSpec.builder()
                    .fieldsWithStrings("Bucket", "Key")
                    .format("S3BatchOperations_CSV_20180820")
                    .build();

                JobManifest jobManifest = JobManifest.builder()
                    .spec(manifestSpec)
                    .location(jobManifestLocation)
                    .build();

                JobReport jobReport = JobReport.builder()
                    .bucket(reportBucketName)
                    .prefix("reports")
                    .format("Report_CSV_20180820")
                    .enabled(true)
                    .reportScope("AllTasks")
                    .build();

                CreateJobRequest jobRequest = CreateJobRequest.builder()
                    .accountId(accountId)
                    .description("Job created using the AWS Java SDK")
                    .manifest(jobManifest)
                    .operation(jobOperation)
                    .report(jobReport)
                    .priority(42)
                    .roleArn(iamRoleArn)
                    .clientRequestToken(uuid)
                    .confirmationRequired(false)
                    .build();

                // Create the job asynchronously.
                 return getAsyncClient().createJob(jobRequest)
                    .thenApply(CreateJobResponse::jobId);
                 })
                 .handle((jobId, ex) -> {
                    if (ex != null) {
                    Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                    if (cause instanceof S3ControlException) {
                        throw new CompletionException(cause);
                    } else {
                        throw new RuntimeException(cause);
                    }
                }
                return jobId;
            });
    }
```
コンプライアンス保持ジョブを作成します。  

```
    /**
     * Creates a compliance retention job in Amazon S3 Control.
     * <p>
     * A compliance retention job in Amazon S3 Control is a feature that allows you to
     * set a retention period for objects stored in an S3 bucket.
     * This feature is particularly useful for organizations that need to comply with
     * regulatory requirements or internal policies that mandate the retention of data for
     * a specific duration.
     *
     * @param s3ControlClient The S3ControlClient instance to use for the API call.
     * @return The job ID of the created compliance retention job.
     */
    public static String createComplianceRetentionJob(final S3ControlClient s3ControlClient, String roleArn, String bucketName, String accountId) {
        final String manifestObjectArn = "arn:aws:s3:::amzn-s3-demo-manifest-bucket/compliance-objects-manifest.csv";
        final String manifestObjectVersionId = "your-object-version-Id";

        Instant jan2025 = Instant.parse("2025-01-01T00:00:00Z");
        JobOperation jobOperation = JobOperation.builder()
            .s3PutObjectRetention(S3SetObjectRetentionOperation.builder()
                .retention(S3Retention.builder()
                    .mode(S3ObjectLockRetentionMode.COMPLIANCE)
                    .retainUntilDate(jan2025)
                    .build())
                .build())
            .build();

        JobManifestLocation manifestLocation = JobManifestLocation.builder()
            .objectArn(manifestObjectArn)
            .eTag(manifestObjectVersionId)
            .build();

        JobManifestSpec manifestSpec = JobManifestSpec.builder()
            .fieldsWithStrings("Bucket", "Key")
            .format("S3BatchOperations_CSV_20180820")
            .build();

        JobManifest manifestToPublicApi = JobManifest.builder()
            .location(manifestLocation)
            .spec(manifestSpec)
            .build();

        // Report details.
        final String jobReportBucketArn = "arn:aws:s3:::" + bucketName;
        final String jobReportPrefix = "reports/compliance-objects-bops";

        JobReport jobReport = JobReport.builder()
            .enabled(true)
            .reportScope(JobReportScope.ALL_TASKS)
            .bucket(jobReportBucketArn)
            .prefix(jobReportPrefix)
            .format(JobReportFormat.REPORT_CSV_20180820)
            .build();

        final Boolean requiresConfirmation = true;
        final int priority = 10;
        CreateJobRequest request = CreateJobRequest.builder()
            .accountId(accountId)
            .description("Set compliance retain-until to 1 Jan 2025")
            .manifest(manifestToPublicApi)
            .operation(jobOperation)
            .priority(priority)
            .roleArn(roleArn)
            .report(jobReport)
            .confirmationRequired(requiresConfirmation)
            .build();

        // Create the job and get the result.
        CreateJobResponse result = s3ControlClient.createJob(request);
        return result.jobId();
    }
```
リーガルホールド解除ジョブを作成します。  

```
    /**
     * Creates a compliance retention job in Amazon S3 Control.
     * <p>
     * A compliance retention job in Amazon S3 Control is a feature that allows you to
     * set a retention period for objects stored in an S3 bucket.
     * This feature is particularly useful for organizations that need to comply with
     * regulatory requirements or internal policies that mandate the retention of data for
     * a specific duration.
     *
     * @param s3ControlClient The S3ControlClient instance to use for the API call.
     * @return The job ID of the created compliance retention job.
     */
    public static String createComplianceRetentionJob(final S3ControlClient s3ControlClient, String roleArn, String bucketName, String accountId) {
        final String manifestObjectArn = "arn:aws:s3:::amzn-s3-demo-manifest-bucket/compliance-objects-manifest.csv";
        final String manifestObjectVersionId = "your-object-version-Id";

        Instant jan2025 = Instant.parse("2025-01-01T00:00:00Z");
        JobOperation jobOperation = JobOperation.builder()
            .s3PutObjectRetention(S3SetObjectRetentionOperation.builder()
                .retention(S3Retention.builder()
                    .mode(S3ObjectLockRetentionMode.COMPLIANCE)
                    .retainUntilDate(jan2025)
                    .build())
                .build())
            .build();

        JobManifestLocation manifestLocation = JobManifestLocation.builder()
            .objectArn(manifestObjectArn)
            .eTag(manifestObjectVersionId)
            .build();

        JobManifestSpec manifestSpec = JobManifestSpec.builder()
            .fieldsWithStrings("Bucket", "Key")
            .format("S3BatchOperations_CSV_20180820")
            .build();

        JobManifest manifestToPublicApi = JobManifest.builder()
            .location(manifestLocation)
            .spec(manifestSpec)
            .build();

        // Report details.
        final String jobReportBucketArn = "arn:aws:s3:::" + bucketName;
        final String jobReportPrefix = "reports/compliance-objects-bops";

        JobReport jobReport = JobReport.builder()
            .enabled(true)
            .reportScope(JobReportScope.ALL_TASKS)
            .bucket(jobReportBucketArn)
            .prefix(jobReportPrefix)
            .format(JobReportFormat.REPORT_CSV_20180820)
            .build();

        final Boolean requiresConfirmation = true;
        final int priority = 10;
        CreateJobRequest request = CreateJobRequest.builder()
            .accountId(accountId)
            .description("Set compliance retain-until to 1 Jan 2025")
            .manifest(manifestToPublicApi)
            .operation(jobOperation)
            .priority(priority)
            .roleArn(roleArn)
            .report(jobReport)
            .confirmationRequired(requiresConfirmation)
            .build();

        // Create the job and get the result.
        CreateJobResponse result = s3ControlClient.createJob(request);
        return result.jobId();
    }
```
新しいガバナンス保持ジョブを作成します。  

```
/**
 * 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 CreateGovernanceRetentionJob {

    public static void main(String[]args) throws ParseException {
        final String usage = """

            Usage:
                <manifestObjectArn> <jobReportBucketArn> <roleArn> <accountId> <manifestObjectVersionId>

            Where:
                manifestObjectArn - The Amazon Resource Name (ARN) of the S3 object that contains the manifest file for the governance objects.\s
                bucketName - The ARN of the S3 bucket where the job report will be stored.
                roleArn - The ARN of the IAM role that will be used to perform the governance retention operation.
                accountId - Your AWS account Id.
                manifestObjectVersionId =  A unique value that is used as the `eTag` property of the `JobManifestLocation` object.
            """;

        if (args.length != 4) {
            System.out.println(usage);
            return;
        }

        String manifestObjectArn = args[0];
        String jobReportBucketArn = args[1];
        String roleArn = args[2];
        String accountId = args[3];
        String manifestObjectVersionId = args[4];

        S3ControlClient s3ControlClient = S3ControlClient.create();
        createGovernanceRetentionJob(s3ControlClient, manifestObjectArn, jobReportBucketArn, roleArn, accountId, manifestObjectVersionId);
    }

    public static String createGovernanceRetentionJob(final S3ControlClient s3ControlClient, String manifestObjectArn, String jobReportBucketArn, String roleArn, String accountId, String manifestObjectVersionId) throws ParseException {
        final JobManifestLocation manifestLocation = JobManifestLocation.builder()
            .objectArn(manifestObjectArn)
            .eTag(manifestObjectVersionId)
            .build();

        final JobManifestSpec manifestSpec = JobManifestSpec.builder()
            .format(JobManifestFormat.S3_BATCH_OPERATIONS_CSV_20180820)
            .fields(Arrays.asList(JobManifestFieldName.BUCKET, JobManifestFieldName.KEY))
            .build();

        final JobManifest manifestToPublicApi = JobManifest.builder()
            .location(manifestLocation)
            .spec(manifestSpec)
            .build();

        final String jobReportPrefix = "reports/governance-objects";
        final JobReport jobReport = JobReport.builder()
            .enabled(true)
            .reportScope(JobReportScope.ALL_TASKS)
            .bucket(jobReportBucketArn)
            .prefix(jobReportPrefix)
            .format(JobReportFormat.REPORT_CSV_20180820)
            .build();

        final SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
        final Date jan30th = format.parse("30/01/2025");

        final S3SetObjectRetentionOperation s3SetObjectRetentionOperation = S3SetObjectRetentionOperation.builder()
            .retention(S3Retention.builder()
                .mode(S3ObjectLockRetentionMode.GOVERNANCE)
                .retainUntilDate(jan30th.toInstant())
                .build())
            .build();

        final JobOperation jobOperation = JobOperation.builder()
            .s3PutObjectRetention(s3SetObjectRetentionOperation)
            .build();

        final Boolean requiresConfirmation = true;
        final int priority = 10;

        final CreateJobRequest request = CreateJobRequest.builder()
            .accountId(accountId)
            .description("Put governance retention")
            .manifest(manifestToPublicApi)
            .operation(jobOperation)
            .priority(priority)
            .roleArn(roleArn)
            .report(jobReport)
            .confirmationRequired(requiresConfirmation)
            .build();

        final CreateJobResponse result = s3ControlClient.createJob(request);
        return result.jobId();
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/CreateJob)」を参照してください。

### `DeleteJobTagging`
<a name="s3-control_DeleteJobTagging_java_2_topic"></a>

次のコード例は、`DeleteJobTagging` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously deletes the tags associated with a specific batch job.
     *
     * @param jobId     The ID of the batch job whose tags should be deleted.
     * @param accountId The ID of the account associated with the batch job.
     * @return A CompletableFuture that completes when the job tags have been successfully deleted, or an exception is thrown if the deletion fails.
     */
    public CompletableFuture<Void> deleteBatchJobTagsAsync(String jobId, String accountId) {
        DeleteJobTaggingRequest jobTaggingRequest = DeleteJobTaggingRequest.builder()
            .accountId(accountId)
            .jobId(jobId)
            .build();

        return asyncClient.deleteJobTagging(jobTaggingRequest)
            .thenAccept(response -> {
                System.out.println("You have successfully deleted " + jobId + " tagging.");
            })
            .exceptionally(ex -> {
                System.err.println("Failed to delete job tags: " + ex.getMessage());
                throw new RuntimeException(ex);
            });
    }
```
+  API の詳細については、「[AWS SDK for Java 2.x API リファレンス](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/DeleteJobTagging)」の「*DeleteJobTagging*」を参照してください。

### `DescribeJob`
<a name="s3-control_DescribeJob_java_2_topic"></a>

次のコード例は、`DescribeJob` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously describes the specified job.
     *
     * @param jobId     the ID of the job to describe
     * @param accountId the ID of the AWS account associated with the job
     * @return a {@link CompletableFuture} that completes when the job description is available
     * @throws RuntimeException if an error occurs while describing the job
     */
    public CompletableFuture<Void> describeJobAsync(String jobId, String accountId) {
        DescribeJobRequest jobRequest = DescribeJobRequest.builder()
            .jobId(jobId)
            .accountId(accountId)
            .build();

        return getAsyncClient().describeJob(jobRequest)
            .thenAccept(response -> {
                System.out.println("Job ID: " + response.job().jobId());
                System.out.println("Description: " + response.job().description());
                System.out.println("Status: " + response.job().statusAsString());
                System.out.println("Role ARN: " + response.job().roleArn());
                System.out.println("Priority: " + response.job().priority());
                System.out.println("Progress Summary: " + response.job().progressSummary());

                // Print out details about the job manifest.
                JobManifest manifest = response.job().manifest();
                System.out.println("Manifest Location: " + manifest.location().objectArn());
                System.out.println("Manifest ETag: " + manifest.location().eTag());

                // Print out details about the job operation.
                JobOperation operation = response.job().operation();
                if (operation.s3PutObjectTagging() != null) {
                    System.out.println("Operation: S3 Put Object Tagging");
                    System.out.println("Tag Set: " + operation.s3PutObjectTagging().tagSet());
                }

                // Print out details about the job report.
                JobReport report = response.job().report();
                System.out.println("Report Bucket: " + report.bucket());
                System.out.println("Report Prefix: " + report.prefix());
                System.out.println("Report Format: " + report.format());
                System.out.println("Report Enabled: " + report.enabled());
                System.out.println("Report Scope: " + report.reportScopeAsString());
            })
            .exceptionally(ex -> {
                System.err.println("Failed to describe job: " + ex.getMessage());
                throw new RuntimeException(ex);
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/DescribeJob)」を参照してください。

### `GetJobTagging`
<a name="s3-control_GetJobTagging_java_2_topic"></a>

次のコード例は、`GetJobTagging` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously retrieves the tags associated with a specific job in an AWS account.
     *
     * @param jobId     the ID of the job for which to retrieve the tags
     * @param accountId the ID of the AWS account associated with the job
     * @return a {@link CompletableFuture} that completes when the job tags have been retrieved, or with an exception if the operation fails
     * @throws RuntimeException if an error occurs while retrieving the job tags
     */
    public CompletableFuture<Void> getJobTagsAsync(String jobId, String accountId) {
        GetJobTaggingRequest request = GetJobTaggingRequest.builder()
            .jobId(jobId)
            .accountId(accountId)
            .build();

        return asyncClient.getJobTagging(request)
            .thenAccept(response -> {
                List<S3Tag> tags = response.tags();
                if (tags.isEmpty()) {
                    System.out.println("No tags found for job ID: " + jobId);
                } else {
                    for (S3Tag tag : tags) {
                        System.out.println("Tag key is: " + tag.key());
                        System.out.println("Tag value is: " + tag.value());
                    }
                }
            })
            .exceptionally(ex -> {
                System.err.println("Failed to get job tags: " + ex.getMessage());
                throw new RuntimeException(ex); // Propagate the exception
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetJobTagging](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/GetJobTagging)」を参照してください。

### `PutJobTagging`
<a name="s3-control_PutJobTagging_java_2_topic"></a>

次のコード例は、`PutJobTagging` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Asynchronously adds tags to a job in the system.
     *
     * @param jobId     the ID of the job to add tags to
     * @param accountId the account ID associated with the job
     * @return a CompletableFuture that completes when the tagging operation is finished
     */
    public CompletableFuture<Void> putJobTaggingAsync(String jobId, String accountId) {
        S3Tag departmentTag = S3Tag.builder()
            .key("department")
            .value("Marketing")
            .build();

        S3Tag fiscalYearTag = S3Tag.builder()
            .key("FiscalYear")
            .value("2020")
            .build();

        PutJobTaggingRequest putJobTaggingRequest = PutJobTaggingRequest.builder()
            .jobId(jobId)
            .accountId(accountId)
            .tags(departmentTag, fiscalYearTag)
            .build();

        return asyncClient.putJobTagging(putJobTaggingRequest)
            .thenRun(() -> {
                System.out.println("Additional Tags were added to job " + jobId);
            })
            .exceptionally(ex -> {
                System.err.println("Failed to add tags to job: " + ex.getMessage());
                throw new RuntimeException(ex); // Propagate the exception
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutJobTagging](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/PutJobTagging)」を参照してください。

### `UpdateJobPriority`
<a name="s3-control_UpdateJobPriority_java_2_topic"></a>

次のコード例は、`UpdateJobPriority` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates the priority of a job asynchronously.
     *
     * @param jobId     the ID of the job to update
     * @param accountId the ID of the account associated with the job
     * @return a {@link CompletableFuture} that represents the asynchronous operation, which completes when the job priority has been updated or an error has occurred
     */
    public CompletableFuture<Void> updateJobPriorityAsync(String jobId, String accountId) {
        UpdateJobPriorityRequest priorityRequest = UpdateJobPriorityRequest.builder()
            .accountId(accountId)
            .jobId(jobId)
            .priority(60)
            .build();

        CompletableFuture<Void> future = new CompletableFuture<>();
        getAsyncClient().updateJobPriority(priorityRequest)
            .thenAccept(response -> {
                System.out.println("The job priority was updated");
                future.complete(null); // Complete the CompletableFuture on successful execution
            })
            .exceptionally(ex -> {
                System.err.println("Failed to update job priority: " + ex.getMessage());
                future.completeExceptionally(ex); // Complete the CompletableFuture exceptionally on error
                return null; // Return null to handle the exception
            });

        return future;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateJobPriority](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/UpdateJobPriority)」を参照してください。

### `UpdateJobStatus`
<a name="s3-control_UpdateJobStatus_java_2_topic"></a>

次のコード例は、`UpdateJobStatus` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/batch#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Cancels a job asynchronously.
     *
     * @param jobId The ID of the job to be canceled.
     * @param accountId The ID of the account associated with the job.
     * @return A {@link CompletableFuture} that completes when the job status has been updated to "CANCELLED".
     *         If an error occurs during the update, the returned future will complete exceptionally.
     */
    public CompletableFuture<Void> cancelJobAsync(String jobId, String accountId) {
        UpdateJobStatusRequest updateJobStatusRequest = UpdateJobStatusRequest.builder()
            .accountId(accountId)
            .jobId(jobId)
            .requestedJobStatus(String.valueOf(JobStatus.CANCELLED))
            .build();

        return asyncClient.updateJobStatus(updateJobStatusRequest)
            .thenAccept(updateJobStatusResponse -> {
                System.out.println("Job status updated to: " + updateJobStatusResponse.status());
            })
            .exceptionally(ex -> {
                System.err.println("Failed to cancel job: " + ex.getMessage());
                throw new RuntimeException(ex); // Propagate the exception
            });
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateJobStatus](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3control-2018-08-20/UpdateJobStatus)」を参照してください。

# SDK for Java 2.x を使用した S3 ディレクトリバケットの例
<a name="java_2_s3-directory-buckets_code_examples"></a>

次のコード例は、S3 ディレクトリバケット AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3 ディレクトリバケット
<a name="s3-directory-buckets_Hello_java_2_topic"></a>

次のコード例は、Amazon S3 ディレクトリバケットの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。

```
package com.example.s3.directorybucket;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Bucket;
import software.amazon.awssdk.services.s3.model.BucketInfo;
import software.amazon.awssdk.services.s3.model.BucketType;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.CreateBucketResponse;
import software.amazon.awssdk.services.s3.model.DataRedundancy;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.ListDirectoryBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListDirectoryBucketsResponse;
import software.amazon.awssdk.services.s3.model.LocationInfo;
import software.amazon.awssdk.services.s3.model.LocationType;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.util.List;
import java.util.stream.Collectors;

import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;

/**
 * Before running this example:
 * <p>
 * The SDK must be able to authenticate AWS requests on your behalf. If you have
 * not configured
 * authentication for SDKs and tools, see
 * https://docs.aws.amazon.com/sdkref/latest/guide/access.html in the AWS SDKs
 * and Tools Reference Guide.
 * <p>
 * You must have a runtime environment configured with the Java SDK.
 * See
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html in
 * the Developer Guide if this is not set up.
 * <p>
 * To use S3 directory buckets, configure a gateway VPC endpoint. This is the
 * recommended method to enable directory bucket traffic without
 * requiring an internet gateway or NAT device. For more information on
 * configuring VPC gateway endpoints, visit
 * https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-networking.html#s3-express-networking-vpc-gateway.
 * <p>
 * Directory buckets are available in specific AWS Regions and Zones. For
 * details on Regions and Zones supporting directory buckets, see
 * https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-networking.html#s3-express-endpoints.
 */

public class HelloS3DirectoryBuckets {
    private static final Logger logger = LoggerFactory.getLogger(HelloS3DirectoryBuckets.class);

    public static void main(String[] args) {
        String bucketName = "test-bucket-" + System.currentTimeMillis() + "--usw2-az1--x-s3";
        Region region = Region.US_WEST_2;
        String zone = "usw2-az1";
        S3Client s3Client = createS3Client(region);

        try {
            // Create the directory bucket
            createDirectoryBucket(s3Client, bucketName, zone);
            logger.info("Created bucket: {}", bucketName);

            // List all directory buckets
            List<String> bucketNames = listDirectoryBuckets(s3Client);
            bucketNames.forEach(name -> logger.info("Bucket Name: {}", name));
        } catch (S3Exception e) {
            logger.error("An error occurred during S3 operations: {} - Error code: {}",
                    e.awsErrorDetails().errorMessage(), e.awsErrorDetails().errorCode(), e);
        } finally {
            try {
                // Delete the created bucket
                deleteDirectoryBucket(s3Client, bucketName);
                logger.info("Deleted bucket: {}", bucketName);
            } catch (S3Exception e) {
                logger.error("Failed to delete the bucket due to S3 error: {} - Error code: {}",
                        e.awsErrorDetails().errorMessage(), e.awsErrorDetails().errorCode(), e);
            } catch (RuntimeException e) {
                logger.error("Failed to delete the bucket due to unexpected error: {}", e.getMessage(), e);
            } finally {
                s3Client.close();
            }
        }
    }

    /**
     * Creates a new S3 directory bucket in a specified Zone (For example, a
     * specified Availability Zone in this code example).
     *
     * @param s3Client   The S3 client used to create the bucket
     * @param bucketName The name of the bucket to be created
     * @param zone       The region where the bucket will be created
     * @throws S3Exception if there's an error creating the bucket
     */
    public static void createDirectoryBucket(S3Client s3Client, String bucketName, String zone) throws S3Exception {
        logger.info("Creating bucket: {}", bucketName);

        CreateBucketConfiguration bucketConfiguration = CreateBucketConfiguration.builder()
                .location(LocationInfo.builder()
                        .type(LocationType.AVAILABILITY_ZONE)
                        .name(zone).build())
                .bucket(BucketInfo.builder()
                        .type(BucketType.DIRECTORY)
                        .dataRedundancy(DataRedundancy.SINGLE_AVAILABILITY_ZONE)
                        .build())
                .build();
        try {
            CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
                    .bucket(bucketName)
                    .createBucketConfiguration(bucketConfiguration).build();
            CreateBucketResponse response = s3Client.createBucket(bucketRequest);
            logger.info("Bucket created successfully with location: {}", response.location());
        } catch (S3Exception e) {
            logger.error("Error creating bucket: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }

    /**
     * Lists all S3 directory buckets.
     *
     * @param s3Client The S3 client used to interact with S3
     * @return A list of bucket names
     */
    public static List<String> listDirectoryBuckets(S3Client s3Client) {
        logger.info("Listing all directory buckets");

        try {
            // Create a ListBucketsRequest
            ListDirectoryBucketsRequest listBucketsRequest = ListDirectoryBucketsRequest.builder().build();

            // Retrieve the list of buckets
            ListDirectoryBucketsResponse response = s3Client.listDirectoryBuckets(listBucketsRequest);

            // Extract bucket names
            List<String> bucketNames = response.buckets().stream()
                    .map(Bucket::name)
                    .collect(Collectors.toList());

            return bucketNames;
        } catch (S3Exception e) {
            logger.error("Failed to list buckets: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }

    /**
     * Deletes the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the bucket to delete
     */
    public static void deleteDirectoryBucket(S3Client s3Client, String bucketName) {
        try {
            DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
                    .bucket(bucketName)
                    .build();
            s3Client.deleteBucket(deleteBucketRequest);
        } catch (S3Exception e) {
            logger.error("Failed to delete bucket: " + bucketName + " - Error code: " + e.awsErrorDetails().errorCode(),
                    e);
            throw e;
        }
    }

}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)
  + [ListDirectoryBuckets](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListDirectoryBuckets)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3-directory-buckets_Scenario_ExpressBasics_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ VPC と VPC エンドポイントをセットアップします。
+ S3 ディレクトリバケットと S3 Express One Zone ストレージクラスを操作するようにポリシー、ロール、ユーザーを設定します。
+ 2 つの S3 クライアントを作成します。
+ バケットを 2 つ作成します。
+ オブジェクトを作成し、それをコピーします。
+ パフォーマンスの違いを示します。
+ 辞書順の違いを示すために、バケットをデータを追加します。
+ リソースをクリーンアップするかどうかをユーザーに確認します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
Amazon S3 機能を示すインタラクティブなシナリオを実行します。  

```
public class S3DirectoriesScenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    private static final Logger logger = LoggerFactory.getLogger(S3DirectoriesScenario.class);
    static Scanner scanner = new Scanner(System.in);

    private static S3AsyncClient mS3RegularClient;
    private static S3AsyncClient mS3ExpressClient;

    private static String mdirectoryBucketName;
    private static String mregularBucketName;

    private static String stackName = "cfn-stack-s3-express-basics--" + UUID.randomUUID();

    private static String regularUser = "";
    private static String vpcId = "";
    private static String expressUser = "";

    private static String vpcEndpointId = "";

    private static final S3DirectoriesActions s3DirectoriesActions = new S3DirectoriesActions();

    public static void main(String[] args) {
        try {
            s3ExpressScenario();
        } catch (RuntimeException e) {
            logger.info(e.getMessage());
        }
    }

    // Runs the scenario.
    private static void s3ExpressScenario() {
        logger.info(DASHES);
        logger.info("Welcome to the Amazon S3 Express Basics demo using AWS SDK for Java V2.");
        logger.info("""
            Let's get started! First, please note that S3 Express One Zone works best when working within the AWS infrastructure,
            specifically when working in the same Availability Zone (AZ). To see the best results in this example and when you implement
            directory buckets into your infrastructure, it is best to put your compute resources in the same AZ as your directory
            bucket.
            """);
        waitForInputToContinue(scanner);
        logger.info(DASHES);

        // Create an optional VPC and create 2 IAM users.
        UserNames userNames = createVpcUsers();
        String expressUserName = userNames.getExpressUserName();
        String regularUserName = userNames.getRegularUserName();

        //  Set up two S3 clients, one regular and one express,
        //  and two buckets, one regular and one directory.
        setupClientsAndBuckets(expressUserName, regularUserName);

        // Create an S3 session for the express S3 client and add objects to the buckets.
        logger.info("Now let's add some objects to our buckets and demonstrate how to work with S3 Sessions.");
        waitForInputToContinue(scanner);
        String bucketObject = createSessionAddObjects();

        // Demonstrate performance differences between regular and directory buckets.
        demonstratePerformance(bucketObject);

        // Populate the buckets to show the lexicographical difference between
        // regular and express buckets.
        showLexicographicalDifferences(bucketObject);

        logger.info(DASHES);
        logger.info("That's it for our tour of the basic operations for S3 Express One Zone.");
        logger.info("Would you like to cleanUp the AWS resources? (y/n): ");
        String response = scanner.next().trim().toLowerCase();
        if (response.equals("y")) {
            cleanUp(stackName);
        }
    }

    /*
      Delete resources created by this scenario.
    */
    public static void cleanUp(String stackName) {
        try {
            if (mdirectoryBucketName != null) {
                s3DirectoriesActions.deleteBucketAndObjectsAsync(mS3ExpressClient, mdirectoryBucketName).join();
            }
            logger.info("Deleted directory bucket " + mdirectoryBucketName);
            mdirectoryBucketName = null;
            if (mregularBucketName != null) {
                s3DirectoriesActions.deleteBucketAndObjectsAsync(mS3RegularClient, mregularBucketName).join();
            }
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof S3Exception) {
                logger.error("S3Exception occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
        }

        logger.info("Deleted regular bucket " + mregularBucketName);
        mregularBucketName = null;
        CloudFormationHelper.destroyCloudFormationStack(stackName);
    }

    private static void showLexicographicalDifferences(String bucketObject) {
        logger.info(DASHES);
        logger.info("""
            7. Populate the buckets to show the lexicographical (alphabetical) difference 
            when object names are listed. Now let's explore how directory buckets store 
            objects in a different manner to regular buckets. The key is in the name 
            "Directory". Where regular buckets store their key/value pairs in a 
            flat manner, directory buckets use actual directories/folders. 
            This allows for more rapid indexing, traversing, and therefore 
            retrieval times! 
                        
            The more segmented your bucket is, with lots of 
            directories, sub-directories, and objects, the more efficient it becomes. 
            This structural difference also causes `ListObject` operations to behave 
            differently, which can cause unexpected results. Let's add a few more 
            objects in sub-directories to see how the output of 
            ListObjects changes.
            """);

        waitForInputToContinue(scanner);

        //  Populate a few more files in each bucket so that we can use
        //  ListObjects and show the difference.
        String otherObject = "other/" + bucketObject;
        String altObject = "alt/" + bucketObject;
        String otherAltObject = "other/alt/" + bucketObject;

        try {
            s3DirectoriesActions.putObjectAsync(mS3RegularClient, mregularBucketName, otherObject, "").join();
            s3DirectoriesActions.putObjectAsync(mS3ExpressClient, mdirectoryBucketName, otherObject, "").join();
            s3DirectoriesActions.putObjectAsync(mS3RegularClient, mregularBucketName, altObject, "").join();
            s3DirectoriesActions.putObjectAsync(mS3ExpressClient, mdirectoryBucketName, altObject, "").join();
            s3DirectoriesActions.putObjectAsync(mS3RegularClient, mregularBucketName, otherAltObject, "").join();
            s3DirectoriesActions.putObjectAsync(mS3ExpressClient, mdirectoryBucketName, otherAltObject, "").join();

        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof NoSuchBucketException) {
                logger.error("S3Exception occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
            return;
        }

        try {
            // List objects in both S3 buckets.
            List<String> dirBucketObjects = s3DirectoriesActions.listObjectsAsync(mS3ExpressClient, mdirectoryBucketName).join();
            List<String> regBucketObjects = s3DirectoriesActions.listObjectsAsync(mS3RegularClient, mregularBucketName).join();

            logger.info("Directory bucket content");
            for (String obj : dirBucketObjects) {
                logger.info(obj);
            }

            logger.info("Regular bucket content");
            for (String obj : regBucketObjects) {
                logger.info(obj);
            }
        } catch (CompletionException e) {
            logger.error("Async operation failed: {} ", e.getCause().getMessage());
            return;
        }

        logger.info("""
            Notice how the regular bucket lists objects in lexicographical order, while the directory bucket does not. This is 
            because the regular bucket considers the whole "key" to be the object identifier, while the directory bucket actually 
            creates directories and uses the object "key" as a path to the object.
            """);
        waitForInputToContinue(scanner);
    }

    /**
     * Demonstrates the performance difference between downloading an object from a directory bucket and a regular bucket.
     *
     * <p>This method:
     * <ul>
     *     <li>Prompts the user to choose the number of downloads (default is 1,000).</li>
     *     <li>Downloads the specified object from the directory bucket and measures the total time.</li>
     *     <li>Downloads the same object from the regular bucket and measures the total time.</li>
     *     <li>Compares the time differences and prints the results.</li>
     * </ul>
     *
     * <p>Note: The performance difference will be more pronounced if this example is run on an EC2 instance
     * in the same Availability Zone as the buckets.
     *
     * @param bucketObject the name of the object to download
     */
    private static void demonstratePerformance(String bucketObject) {
        logger.info(DASHES);
        logger.info("6. Demonstrate the performance difference.");
        logger.info("""
            Now, let's do a performance test. We'll download the same object from each 
            bucket repeatedly and compare the total time needed. 
                        
            Note: the performance difference will be much more pronounced if this
            example is run in an EC2 instance in the same Availability Zone as 
            the bucket.
            """);
        waitForInputToContinue(scanner);

        int downloads = 1000; // Default value.
        logger.info("The default number of downloads of the same object for this example is set at " + downloads + ".");

        // Ask if the user wants to download a different number.
        logger.info("Would you like to download the file a different number of times? (y/n): ");
        String response = scanner.next().trim().toLowerCase();
        if (response.equals("y")) {
            int maxDownloads = 1_000_000;

            // Ask for a valid number of downloads.
            while (true) {
                logger.info("Enter a number between 1 and " + maxDownloads + " for the number of downloads: ");
                if (scanner.hasNextInt()) {
                    downloads = scanner.nextInt();
                    if (downloads >= 1 && downloads <= maxDownloads) {
                        break;
                    } else {
                        logger.info("Please enter a number between 1 and " + maxDownloads + ".");
                    }
                } else {
                    logger.info("Invalid input. Please enter a valid integer.");
                    scanner.next();
                }
            }

            logger.info("You have chosen to download {}  items.", downloads);
        } else {
            logger.info("No changes made. Using default downloads: {}", downloads);
        }
        // Simulating the download process for the directory bucket.
        logger.info("Downloading from the directory bucket.");
        long directoryTimeStart = System.nanoTime();
        for (int index = 0; index < downloads; index++) {
            if (index % 50 == 0) {
                logger.info("Download " + index + " of " + downloads);
            }

            try {
                // Get the object from the directory bucket.
                s3DirectoriesActions.getObjectAsync(mS3ExpressClient, mdirectoryBucketName, bucketObject).join();
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof NoSuchKeyException) {
                    logger.error("S3Exception occurred: {}", cause.getMessage(), ce);
                } else {
                    logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
                }
                return;
            }
        }
        long directoryTimeDifference = System.nanoTime() - directoryTimeStart;

        // Download from the regular bucket.
        logger.info("Downloading from the regular bucket.");
        long normalTimeStart = System.nanoTime();
        for (int index = 0; index < downloads; index++) {
            if (index % 50 == 0) {
                logger.info("Download " + index + " of " + downloads);
            }

            try {
                s3DirectoriesActions.getObjectAsync(mS3RegularClient, mregularBucketName, bucketObject).join();
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof NoSuchKeyException) {
                    logger.error("S3Exception occurred: {}", cause.getMessage(), ce);
                } else {
                    logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
                }
                return;
            }
        }

        long normalTimeDifference = System.nanoTime() - normalTimeStart;
        logger.info("The directory bucket took " + directoryTimeDifference + " nanoseconds, while the regular bucket took " + normalTimeDifference + " nanoseconds.");
        long difference = normalTimeDifference - directoryTimeDifference;
        logger.info("That's a difference of " + difference + " nanoseconds, or");
        logger.info(difference / 1_000_000_000.0 + " seconds.");

        if (difference < 0) {
            logger.info("The directory buckets were slower. This can happen if you are not running on the cloud within a VPC.");
        }
        waitForInputToContinue(scanner);
    }

    private static String createSessionAddObjects() {
        logger.info(DASHES);
        logger.info("""    
            5. Create an object and copy it.
            We'll create an object consisting of some text and upload it to the 
            regular bucket. 
            """);
        waitForInputToContinue(scanner);

        String bucketObject = "basic-text-object.txt";
        try {
            s3DirectoriesActions.putObjectAsync(mS3RegularClient, mregularBucketName, bucketObject, "Look Ma, I'm a bucket!").join();
            s3DirectoriesActions.createSessionAsync(mS3ExpressClient, mdirectoryBucketName).join();

            // Copy the object to the destination S3 bucket.
            s3DirectoriesActions.copyObjectAsync(mS3ExpressClient, mregularBucketName, bucketObject, mdirectoryBucketName, bucketObject).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof S3Exception) {
                logger.error("S3Exception occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
        }
        logger.info(""" 
            It worked! This is because the S3Client that performed the copy operation 
            is the expressClient using the credentials for the user with permission to 
            work with directory buckets. 
                        
            It's important to remember the user permissions when interacting with 
            directory buckets. Instead of validating permissions on every call as 
            regular buckets do, directory buckets utilize the user credentials and session 
            token to validate. This allows for much faster connection speeds on every call. 
            For single calls, this is low, but for many concurrent calls 
            this adds up to a lot of time saved.
            """);
        waitForInputToContinue(scanner);
        return bucketObject;
    }

    /**
     * Creates VPC users for the S3 Express One Zone scenario.
     * <p>
     * This method performs the following steps:
     * <ol>
     *     <li>Optionally creates a new VPC and VPC Endpoint if the application is running in an EC2 instance in the same Availability Zone as the directory buckets.</li>
     *     <li>Creates two IAM users: one with S3 Express One Zone permissions and one without.</li>
     * </ol>
     *
     * @return a {@link UserNames} object containing the names of the created IAM users
     */
    public static UserNames createVpcUsers() {
        /*
        Optionally create a VPC.
        Create two IAM users, one with S3 Express One Zone permissions and one without.
        */
        logger.info(DASHES);
        logger.info("""
            1. First, we'll set up a new VPC and VPC Endpoint if this program is running in an EC2 instance in the same AZ as your\s
            directory buckets will be. Are you running this in an EC2 instance located in the same AZ as your intended directory buckets?
            """);

        logger.info("Do you want to setup a VPC Endpoint? (y/n)");
        String endpointAns = scanner.nextLine().trim();
        if (endpointAns.equalsIgnoreCase("y")) {
            logger.info("""
                Great! Let's set up a VPC, retrieve the Route Table from it, and create a VPC Endpoint to connect the S3 Client to.
                """);
            try {
                s3DirectoriesActions.setupVPCAsync().join();
            } catch (CompletionException ce) {
                Throwable cause = ce.getCause();
                if (cause instanceof Ec2Exception) {
                    logger.error("IamException occurred: {}", cause.getMessage(), ce);
                } else {
                    logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
                }
            }
            waitForInputToContinue(scanner);
        } else {
            logger.info("Skipping the VPC setup. Don't forget to use this in production!");
        }
        logger.info(DASHES);
        logger.info("""            
            2. Create a RegularUser and ExpressUser by using the AWS CDK.
            One IAM User, named RegularUser, will have permissions to work only 
            with regular buckets and one IAM user, named ExpressUser, will have 
            permissions to work only with directory buckets.
            """);
        waitForInputToContinue(scanner);

        // Create two users required for this scenario.
        Map<String, String> stackOutputs = createUsersUsingCDK(stackName);
        regularUser = stackOutputs.get("RegularUser");
        expressUser = stackOutputs.get("ExpressUser");

        UserNames names = new UserNames();
        names.setRegularUserName(regularUser);
        names.setExpressUserName(expressUser);
        return names;
    }

    /**
     * Creates users using AWS CloudFormation.
     *
     * @return a {@link Map} of String keys and String values representing the stack outputs,
     * which may include user-related information such as user names and IDs.
     */
    public static Map<String, String> createUsersUsingCDK(String stackName) {
        logger.info("We'll use an AWS CloudFormation template to create the IAM users and policies.");
        CloudFormationHelper.deployCloudFormationStack(stackName);
        return CloudFormationHelper.getStackOutputsAsync(stackName).join();
    }

    /**
     * Sets up the necessary clients and buckets for the S3 Express service.
     *
     * @param expressUserName the username for the user with S3 Express permissions
     * @param regularUserName the username for the user with regular S3 permissions
     */
    public static void setupClientsAndBuckets(String expressUserName, String regularUserName) {
        Scanner locscanner = new Scanner(System.in);
        String accessKeyIdforRegUser;
        String secretAccessforRegUser;
        try {
            CreateAccessKeyResponse keyResponse = s3DirectoriesActions.createAccessKeyAsync(regularUserName).join();
            accessKeyIdforRegUser = keyResponse.accessKey().accessKeyId();
            secretAccessforRegUser = keyResponse.accessKey().secretAccessKey();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof IamException) {
                logger.error("IamException occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
            return;
        }

        String accessKeyIdforExpressUser;
        String secretAccessforExpressUser;
        try {
            CreateAccessKeyResponse keyResponseExpress = s3DirectoriesActions.createAccessKeyAsync(expressUserName).join();
            accessKeyIdforExpressUser = keyResponseExpress.accessKey().accessKeyId();
            secretAccessforExpressUser = keyResponseExpress.accessKey().secretAccessKey();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof IamException) {
                logger.error("IamException occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
            return;
        }

        logger.info(DASHES);
        logger.info("""            
            3. Create two S3Clients; one uses the ExpressUser's credentials and one uses the RegularUser's credentials.
            The 2 S3Clients will use different credentials.
            """);
        waitForInputToContinue(locscanner);
        try {
            mS3RegularClient = createS3ClientWithAccessKeyAsync(accessKeyIdforRegUser, secretAccessforRegUser).join();
            mS3ExpressClient = createS3ClientWithAccessKeyAsync(accessKeyIdforExpressUser, secretAccessforExpressUser).join();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof IllegalArgumentException) {
                logger.error("An invalid argument exception occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
            return;
        }

        logger.info("""
            We can now use the ExpressUser client to make calls to S3 Express operations. 
            """);
        waitForInputToContinue(locscanner);
        logger.info(DASHES);
        logger.info("""
            4. Create two buckets.
            Now we will create a directory bucket which is the linchpin of the S3 Express One Zone service. Directory buckets 
            behave differently from regular S3 buckets which we will explore here. We'll also create a regular bucket, put 
            an object into the regular bucket, and copy it to the directory bucket.
            """);

        logger.info("""
            Now, let's choose an availability zone (AZ) for the directory bucket. 
            We'll choose one that is supported.
            """);
        String zoneId;
        String regularBucketName;
        try {
            zoneId = s3DirectoriesActions.selectAvailabilityZoneIdAsync().join();
            regularBucketName = "reg-bucket-" + System.currentTimeMillis();
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof Ec2Exception) {
                logger.error("EC2Exception occurred: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
            }
            return;
        }
        logger.info("""
            Now, let's create the actual directory bucket, as well as a regular bucket."
             """);

        String directoryBucketName = "test-bucket-" + System.currentTimeMillis() + "--" + zoneId + "--x-s3";
        try {
            s3DirectoriesActions.createDirectoryBucketAsync(mS3ExpressClient, directoryBucketName, zoneId).join();
            logger.info("Created directory bucket {}", directoryBucketName);
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof BucketAlreadyExistsException) {
                logger.error("The bucket already exists. Moving on: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
                return;
            }
        }

        // Assign to the data member.
        mdirectoryBucketName = directoryBucketName;
        try {
            s3DirectoriesActions.createBucketAsync(mS3RegularClient, regularBucketName).join();
            logger.info("Created regular bucket {} ", regularBucketName);
            mregularBucketName = regularBucketName;
        } catch (CompletionException ce) {
            Throwable cause = ce.getCause();
            if (cause instanceof BucketAlreadyExistsException) {
                logger.error("The bucket already exists. Moving on: {}", cause.getMessage(), ce);
            } else {
                logger.error("An unexpected error occurred: {}", cause.getMessage(), ce);
                return;
            }
        }
        logger.info("Great! Both buckets were created.");
        waitForInputToContinue(locscanner);
    }

    /**
     * Creates an asynchronous S3 client with the specified access key and secret access key.
     *
     * @param accessKeyId     the AWS access key ID
     * @param secretAccessKey the AWS secret access key
     * @return a {@link CompletableFuture} that asynchronously creates the S3 client
     * @throws IllegalArgumentException if the access key ID or secret access key is null
     */
    public static CompletableFuture<S3AsyncClient> createS3ClientWithAccessKeyAsync(String accessKeyId, String secretAccessKey) {
        return CompletableFuture.supplyAsync(() -> {
            // Validate input parameters
            if (accessKeyId == null || accessKeyId.isBlank() || secretAccessKey == null || secretAccessKey.isBlank()) {
                throw new IllegalArgumentException("Access Key ID and Secret Access Key must not be null or empty");
            }

            AwsBasicCredentials awsCredentials = AwsBasicCredentials.create(accessKeyId, secretAccessKey);
            return S3AsyncClient.builder()
                .credentialsProvider(StaticCredentialsProvider.create(awsCredentials))
                .region(Region.US_WEST_2)
                .build();
        });
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            logger.info("");
            logger.info("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                logger.info("Continuing with the program...");
                logger.info("");
                break;
            } else {
                logger.info("Invalid input. Please try again.");
            }
        }
    }
}
```
Amazon S3 SDK メソッドのラッパークラス。  

```
public class S3DirectoriesActions {

    private static IamAsyncClient iamAsyncClient;

    private static Ec2AsyncClient ec2AsyncClient;
    private static final Logger logger = LoggerFactory.getLogger(S3DirectoriesActions.class);

    private static IamAsyncClient getIAMAsyncClient() {
        if (iamAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            iamAsyncClient = IamAsyncClient.builder()
                .httpClient(httpClient)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return iamAsyncClient;
    }

    private static Ec2AsyncClient getEc2AsyncClient() {
        if (ec2AsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                .maxConcurrency(100)
                .connectionTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                .apiCallTimeout(Duration.ofMinutes(2))
                .apiCallAttemptTimeout(Duration.ofSeconds(90))
                .retryStrategy(RetryMode.STANDARD)
                .build();

            ec2AsyncClient = Ec2AsyncClient.builder()
                .httpClient(httpClient)
                .region(Region.US_WEST_2)
                .overrideConfiguration(overrideConfig)
                .build();
        }
        return ec2AsyncClient;
    }

    /**
     * Deletes the specified S3 bucket and all the objects within it asynchronously.
     *
     * @param s3AsyncClient the S3 asynchronous client to use for the operations
     * @param bucketName the name of the S3 bucket to be deleted
     * @return a {@link CompletableFuture} that completes with a {@link WaiterResponse} containing the
     *         {@link HeadBucketResponse} when the bucket has been successfully deleted
     * @throws CompletionException if there was an error deleting the bucket or its objects
     */
    public CompletableFuture<WaiterResponse<HeadBucketResponse>> deleteBucketAndObjectsAsync(S3AsyncClient s3AsyncClient, String bucketName) {
        ListObjectsV2Request listRequest = ListObjectsV2Request.builder()
            .bucket(bucketName)
            .build();

        return s3AsyncClient.listObjectsV2(listRequest)
            .thenCompose(listResponse -> {
                if (!listResponse.contents().isEmpty()) {
                    List<ObjectIdentifier> objectIdentifiers = listResponse.contents().stream()
                        .map(s3Object -> ObjectIdentifier.builder().key(s3Object.key()).build())
                        .collect(Collectors.toList());

                    DeleteObjectsRequest deleteRequest = DeleteObjectsRequest.builder()
                        .bucket(bucketName)
                        .delete(Delete.builder().objects(objectIdentifiers).build())
                        .build();

                    return s3AsyncClient.deleteObjects(deleteRequest)
                        .thenAccept(deleteResponse -> {
                            if (!deleteResponse.errors().isEmpty()) {
                                deleteResponse.errors().forEach(error ->
                                    logger.error("Couldn't delete object " + error.key() + ". Reason: " + error.message()));
                            }
                        });
                }
                return CompletableFuture.completedFuture(null);
            })
            .thenCompose(ignored -> {
                DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
                    .bucket(bucketName)
                    .build();
                return s3AsyncClient.deleteBucket(deleteBucketRequest);
            })
            .thenCompose(ignored -> {
                S3AsyncWaiter waiter = s3AsyncClient.waiter();
                HeadBucketRequest headBucketRequest = HeadBucketRequest.builder().bucket(bucketName).build();
                return waiter.waitUntilBucketNotExists(headBucketRequest);
            })
            .whenComplete((ignored, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof S3Exception) {
                        throw new CompletionException("Error deleting bucket: " + bucketName, cause);
                    }
                    throw new CompletionException("Failed to delete bucket and objects: " + bucketName, exception);
                }
                logger.info("Bucket deleted successfully: " + bucketName);
            });
    }

    /**
     *  Lists the objects in an S3 bucket asynchronously.
     *
     * @param s3Client the S3 async client to use for the operation
     * @param bucketName the name of the S3 bucket containing the objects to list
     * @return a {@link CompletableFuture} that contains the list of object keys in the specified bucket
     */
    public CompletableFuture<List<String>> listObjectsAsync(S3AsyncClient s3Client, String bucketName) {
        ListObjectsV2Request request = ListObjectsV2Request.builder()
            .bucket(bucketName)
            .build();

        return s3Client.listObjectsV2(request)
            .thenApply(response -> response.contents().stream()
                .map(S3Object::key)
                .toList())
            .whenComplete((result, exception) -> {
                if (exception != null) {
                    throw new CompletionException("Couldn't list objects in bucket: " + bucketName, exception);
                }
            });
    }

    /**
     * Retrieves an object from an Amazon S3 bucket asynchronously.
     *
     * @param s3Client   the S3 async client to use for the operation
     * @param bucketName the name of the S3 bucket containing the object
     * @param keyName    the unique identifier (key) of the object to retrieve
     * @return a {@link CompletableFuture} that, when completed, contains the object's content as a {@link ResponseBytes} of {@link GetObjectResponse}
     */
    public CompletableFuture<ResponseBytes<GetObjectResponse>> getObjectAsync(S3AsyncClient s3Client, String bucketName, String keyName) {
        GetObjectRequest objectRequest = GetObjectRequest.builder()
            .key(keyName)
            .bucket(bucketName)
            .build();

        // Get the object asynchronously and transform it into a byte array
        return s3Client.getObject(objectRequest, AsyncResponseTransformer.toBytes())
            .exceptionally(exception -> {
                Throwable cause = exception.getCause();
                if (cause instanceof NoSuchKeyException) {
                    throw new CompletionException("Failed to get the object. Reason: " + ((S3Exception) cause).awsErrorDetails().errorMessage(), cause);
                }
                throw new CompletionException("Failed to get the object", exception);
            });
    }

    /**
     * Asynchronously copies an object from one S3 bucket to another.
     *
     * @param s3Client           the S3 async client to use for the copy operation
     * @param sourceBucket       the name of the source bucket
     * @param sourceKey          the key of the object to be copied in the source bucket
     * @param destinationBucket  the name of the destination bucket
     * @param destinationKey     the key of the copied object in the destination bucket
     * @return a {@link CompletableFuture} that completes when the copy operation is finished
     */
    public CompletableFuture<Void> copyObjectAsync(S3AsyncClient s3Client, String sourceBucket, String sourceKey, String destinationBucket, String destinationKey) {
        CopyObjectRequest copyRequest = CopyObjectRequest.builder()
            .sourceBucket(sourceBucket)
            .sourceKey(sourceKey)
            .destinationBucket(destinationBucket)
            .destinationKey(destinationKey)
            .build();

        return s3Client.copyObject(copyRequest)
            .thenRun(() -> logger.info("Copied object '" + sourceKey + "' from bucket '" + sourceBucket + "' to bucket '" + destinationBucket + "'"))
            .whenComplete((ignored, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof S3Exception) {
                        throw new CompletionException("Couldn't copy object '" + sourceKey + "' from bucket '" + sourceBucket + "' to bucket '" + destinationBucket + "'. Reason: " + ((S3Exception) cause).awsErrorDetails().errorMessage(), cause);
                    }
                    throw new CompletionException("Failed to copy object", exception);
                }
            });
    }

    /**
     * Asynchronously creates a session for the specified S3 bucket.
     *
     * @param s3Client   the S3 asynchronous client to use for creating the session
     * @param bucketName the name of the S3 bucket for which to create the session
     * @return a {@link CompletableFuture} that completes when the session is created, or throws a {@link CompletionException} if an error occurs
     */
    public CompletableFuture<CreateSessionResponse> createSessionAsync(S3AsyncClient s3Client, String bucketName) {
        CreateSessionRequest request = CreateSessionRequest.builder()
            .bucket(bucketName)
            .build();

        return s3Client.createSession(request)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof S3Exception) {
                        throw new CompletionException("Couldn't create the session. Reason: " + ((S3Exception) cause).awsErrorDetails().errorMessage(), cause);
                    }
                    throw new CompletionException("Unexpected error occurred while creating session", exception);
                }
                logger.info("Created session for bucket: " + bucketName);
            });

    }

    /**
     * Creates a new S3 directory bucket in a specified Zone (For example, a
     * specified Availability Zone in this code example).
     *
     * @param s3Client   The asynchronous S3 client used to create the bucket
     * @param bucketName The name of the bucket to be created
     * @param zone       The Availability Zone where the bucket will be created
     * @throws CompletionException if there's an error creating the bucket
     */
    public CompletableFuture<CreateBucketResponse> createDirectoryBucketAsync(S3AsyncClient s3Client, String bucketName, String zone) {
        logger.info("Creating bucket: " + bucketName);

        CreateBucketConfiguration bucketConfiguration = CreateBucketConfiguration.builder()
            .location(LocationInfo.builder()
                .type(LocationType.AVAILABILITY_ZONE)
                .name(zone)
                .build())
            .bucket(BucketInfo.builder()
                .type(BucketType.DIRECTORY)
                .dataRedundancy(DataRedundancy.SINGLE_AVAILABILITY_ZONE)
                .build())
            .build();

        CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
            .bucket(bucketName)
            .createBucketConfiguration(bucketConfiguration)
            .build();

        return s3Client.createBucket(bucketRequest)
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof BucketAlreadyExistsException) {
                        throw new CompletionException("The bucket already exists: " + ((S3Exception) cause).awsErrorDetails().errorMessage(), cause);
                    }
                    throw new CompletionException("Unexpected error occurred while creating bucket", exception);
                }
                logger.info("Bucket created successfully with location: " + response.location());
            });
    }

    /**
     * Creates an S3 bucket asynchronously.
     *
     * @param s3Client    the S3 async client to use for the bucket creation
     * @param bucketName  the name of the S3 bucket to create
     * @return a {@link CompletableFuture} that completes with the {@link WaiterResponse} containing the {@link HeadBucketResponse}
     *         when the bucket is successfully created
     * @throws CompletionException if there's an error creating the bucket
     */
    public CompletableFuture<WaiterResponse<HeadBucketResponse>> createBucketAsync(S3AsyncClient s3Client, String bucketName) {
        CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
            .bucket(bucketName)
            .build();

        return s3Client.createBucket(bucketRequest)
            .thenCompose(response -> {
                S3AsyncWaiter s3Waiter = s3Client.waiter();
                HeadBucketRequest bucketRequestWait = HeadBucketRequest.builder()
                    .bucket(bucketName)
                    .build();
                return s3Waiter.waitUntilBucketExists(bucketRequestWait);
            })
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof BucketAlreadyExistsException) {
                        throw new CompletionException("The S3 bucket exists: " + cause.getMessage(), cause);
                    } else {
                        throw new CompletionException("Failed to create access key: " + exception.getMessage(), exception);
                    }
                }
                logger.info(bucketName + " is ready");
            });
    }

    /**
     * Uploads an object to an Amazon S3 bucket asynchronously.
     *
     * @param s3Client     the S3 async client to use for the upload
     * @param bucketName   the destination S3 bucket name
     * @param bucketObject the name of the object to be uploaded
     * @param text         the content to be uploaded as the object
     */
    public CompletableFuture<PutObjectResponse> putObjectAsync(S3AsyncClient s3Client, String bucketName, String bucketObject, String text) {
        PutObjectRequest objectRequest = PutObjectRequest.builder()
            .bucket(bucketName)
            .key(bucketObject)
            .build();

        return s3Client.putObject(objectRequest, AsyncRequestBody.fromString(text))
            .whenComplete((response, exception) -> {
                if (exception != null) {
                    Throwable cause = exception.getCause();
                    if (cause instanceof NoSuchBucketException) {
                        throw new CompletionException("The S3 bucket does not exist: " + cause.getMessage(), cause);
                    } else {
                        throw new CompletionException("Failed to create access key: " + exception.getMessage(), exception);
                    }
                }
            });
    }

    /**
     * Creates an AWS IAM access key asynchronously for the specified user name.
     *
     * @param userName the name of the IAM user for whom to create the access key
     * @return a {@link CompletableFuture} that completes with the {@link CreateAccessKeyResponse} containing the created access key
     */
    public CompletableFuture<CreateAccessKeyResponse> createAccessKeyAsync(String userName) {
        CreateAccessKeyRequest request = CreateAccessKeyRequest.builder()
            .userName(userName)
            .build();

        return getIAMAsyncClient().createAccessKey(request)
            .whenComplete((response, exception) -> {
                if (response != null) {
                    logger.info("Access Key Created.");
                } else {
                    if (exception == null) {
                        Throwable cause = exception.getCause();
                        if (cause instanceof IamException) {
                            throw new CompletionException("IAM error while creating access key: " + cause.getMessage(), cause);
                        } else {
                            throw new CompletionException("Failed to create access key: " + exception.getMessage(), exception);
                        }
                    }
                }
            });
    }

    /**
     * Asynchronously selects an Availability Zone ID from the available EC2 zones.
     *
     * @return A {@link CompletableFuture} that resolves to the selected Availability Zone ID.
     * @throws CompletionException if an error occurs during the request or processing.
     */
    public CompletableFuture<String> selectAvailabilityZoneIdAsync() {
        DescribeAvailabilityZonesRequest zonesRequest = DescribeAvailabilityZonesRequest.builder()
            .build();

        return getEc2AsyncClient().describeAvailabilityZones(zonesRequest)
            .thenCompose(response -> {
                List<AvailabilityZone> zonesList = response.availabilityZones();
                if (zonesList.isEmpty()) {
                    logger.info("No availability zones found.");
                    return CompletableFuture.completedFuture(null); // Return null if no zones are found
                }

                List<String> zoneIds = zonesList.stream()
                    .map(AvailabilityZone::zoneId) // Get the zoneId (e.g., "usw2-az1")
                    .toList();

                return CompletableFuture.supplyAsync(() -> promptUserForZoneSelection(zonesList, zoneIds))
                    .thenApply(selectedZone -> {
                        // Return only the selected Zone ID (e.g., "usw2-az1").
                        return selectedZone.zoneId();
                    });
            })
            .whenComplete((result, exception) -> {
                if (exception == null) {
                    if (result != null) {
                        logger.info("Selected Availability Zone ID: " + result);
                    } else {
                        logger.info("No availability zone selected.");
                    }
                } else {
                    Throwable cause = exception.getCause();
                    if (cause instanceof Ec2Exception) {
                        throw new CompletionException("EC2 error while selecting availability zone: " + cause.getMessage(), cause);
                    }
                    throw new CompletionException("Failed to select availability zone: " + exception.getMessage(), exception);
                }
            });
    }

    /**
     * Prompts the user to select an Availability Zone from the given list.
     *
     * @param zonesList the list of Availability Zones
     * @param zoneIds the list of zone IDs
     * @return the selected Availability Zone
     */
    private static AvailabilityZone promptUserForZoneSelection(List<AvailabilityZone> zonesList, List<String> zoneIds) {
        Scanner scanner = new Scanner(System.in);
        int index = -1;

        while (index < 0 || index >= zoneIds.size()) {
            logger.info("Select an availability zone:");
            IntStream.range(0, zoneIds.size()).forEach(i ->
                logger.info(i + ": " + zoneIds.get(i))
            );

            logger.info("Enter the number corresponding to your choice: ");
            if (scanner.hasNextInt()) {
                index = scanner.nextInt();
            } else {
                scanner.next();
            }
        }

        AvailabilityZone selectedZone = zonesList.get(index);
        logger.info("You selected: " + selectedZone.zoneId());
        return selectedZone;
    }

    /**
     * Asynchronously sets up a new VPC, including creating the VPC, finding the associated route table, and
     * creating a VPC endpoint for the S3 service.
     *
     * @return a {@link CompletableFuture} that, when completed, contains a AbstractMap with the
     *         VPC ID and VPC endpoint ID.
     */
    public CompletableFuture<AbstractMap.SimpleEntry<String, String>> setupVPCAsync() {
        String cidr = "10.0.0.0/16";
        CreateVpcRequest vpcRequest = CreateVpcRequest.builder()
            .cidrBlock(cidr)
            .build();

        return getEc2AsyncClient().createVpc(vpcRequest)
            .thenCompose(vpcResponse -> {
                String vpcId = vpcResponse.vpc().vpcId();
                logger.info("VPC Created: {}", vpcId);

                Ec2AsyncWaiter waiter = getEc2AsyncClient().waiter();
                DescribeVpcsRequest request = DescribeVpcsRequest.builder()
                    .vpcIds(vpcId)
                    .build();

                return waiter.waitUntilVpcAvailable(request)
                    .thenApply(waiterResponse -> vpcId);
            })
            .thenCompose(vpcId -> {
                Filter filter = Filter.builder()
                    .name("vpc-id")
                    .values(vpcId)
                    .build();

                DescribeRouteTablesRequest describeRouteTablesRequest = DescribeRouteTablesRequest.builder()
                    .filters(filter)
                    .build();

                return getEc2AsyncClient().describeRouteTables(describeRouteTablesRequest)
                    .thenApply(routeTablesResponse -> {
                        if (routeTablesResponse.routeTables().isEmpty()) {
                            throw new CompletionException("No route tables found for VPC: " + vpcId, null);
                        }
                        String routeTableId = routeTablesResponse.routeTables().get(0).routeTableId();
                        logger.info("Route table found: {}", routeTableId);
                        return new AbstractMap.SimpleEntry<>(vpcId, routeTableId);
                    });
            })
            .thenCompose(vpcAndRouteTable -> {
                String vpcId = vpcAndRouteTable.getKey();
                String routeTableId = vpcAndRouteTable.getValue();
                Region region = getEc2AsyncClient().serviceClientConfiguration().region();
                String serviceName = String.format("com.amazonaws.%s.s3express", region.id());

                CreateVpcEndpointRequest endpointRequest = CreateVpcEndpointRequest.builder()
                    .vpcId(vpcId)
                    .routeTableIds(routeTableId)
                    .serviceName(serviceName)
                    .build();

                return getEc2AsyncClient().createVpcEndpoint(endpointRequest)
                    .thenApply(vpcEndpointResponse -> {
                        String vpcEndpointId = vpcEndpointResponse.vpcEndpoint().vpcEndpointId();
                        logger.info("VPC Endpoint created: {}", vpcEndpointId);
                        return new AbstractMap.SimpleEntry<>(vpcId, vpcEndpointId);
                    });
            })
            .exceptionally(exception -> {
                Throwable cause = exception.getCause() != null ? exception.getCause() : exception;
                if (cause instanceof Ec2Exception) {
                    logger.error("EC2 error during VPC setup: {}", cause.getMessage(), cause);
                    throw new CompletionException("EC2 error during VPC setup: " + cause.getMessage(), cause);
                }

                logger.error("VPC setup failed: {}", cause.getMessage(), cause);
                throw new CompletionException("VPC setup failed: " + cause.getMessage(), cause);
            });
    }

}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucket)
  + [DeleteObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteObject)
  + [GetObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObject)
  + [ListObjects](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListObjects)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `AbortMultipartUpload`
<a name="s3-directory-buckets_AbortMultipartUpload_java_2_topic"></a>

次のコード例は、`AbortMultipartUpload` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のマルチパートアップロードを中止します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucketMultipartUpload;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;


    /**
     * Aborts a specific multipart upload for the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to be uploaded
     * @param uploadId   The upload ID of the multipart upload to abort
     * @return True if the multipart upload is successfully aborted, false otherwise
     */
    public static boolean abortDirectoryBucketMultipartUpload(S3Client s3Client, String bucketName,
            String objectKey, String uploadId) {
        logger.info("Aborting multipart upload: {} for bucket: {}", uploadId, bucketName);
        try {
            // Abort the multipart upload
            AbortMultipartUploadRequest abortMultipartUploadRequest = AbortMultipartUploadRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .uploadId(uploadId)
                    .build();

            s3Client.abortMultipartUpload(abortMultipartUploadRequest);
            logger.info("Aborted multipart upload: {} for object: {}", uploadId, objectKey);
            return true;
        } catch (S3Exception e) {
            logger.error("Failed to abort multipart upload: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            return false;
        }
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[AbortMultipartUpload](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/AbortMultipartUpload)」を参照してください。**

### `CompleteMultipartUpload`
<a name="s3-directory-buckets_CompleteMultipartUpload_java_2_topic"></a>

次のコード例は、`CompleteMultipartUpload` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のマルチパートアップロードを完了します。  

```
import com.example.s3.util.S3DirectoryBucketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucketMultipartUpload;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.multipartUploadForDirectoryBucket;


    /**
     * This method completes the multipart upload request by collating all the
     * upload parts.
     *
     * @param s3Client    The S3 client used to interact with S3
     * @param bucketName  The name of the directory bucket
     * @param objectKey   The key (name) of the object to be uploaded
     * @param uploadId    The upload ID used to track the multipart upload
     * @param uploadParts The list of completed parts
     * @return True if the multipart upload is successfully completed, false
     *         otherwise
     */
    public static boolean completeDirectoryBucketMultipartUpload(S3Client s3Client, String bucketName, String objectKey,
            String uploadId, List<CompletedPart> uploadParts) {
        try {
            CompletedMultipartUpload completedMultipartUpload = CompletedMultipartUpload.builder()
                    .parts(uploadParts)
                    .build();
            CompleteMultipartUploadRequest completeMultipartUploadRequest = CompleteMultipartUploadRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .uploadId(uploadId)
                    .multipartUpload(completedMultipartUpload)
                    .build();

            CompleteMultipartUploadResponse response = s3Client.completeMultipartUpload(completeMultipartUploadRequest);
            logger.info("Multipart upload completed. ETag: {}", response.eTag());
            return true;
        } catch (S3Exception e) {
            logger.error("Failed to complete multipart upload: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            return false;
        }
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[CompleteMultipartUpload](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CompleteMultipartUpload)」を参照してください。**

### `CopyObject`
<a name="s3-directory-buckets_CopyObject_java_2_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットから別のディレクトリバケットにオブジェクトをコピーします。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CopyObjectRequest;
import software.amazon.awssdk.services.s3.model.CopyObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.nio.file.Path;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;

    /**
     * Copies an object from one S3 general purpose bucket to one S3 directory
     * bucket.
     *
     * @param s3Client     The S3 client used to interact with S3
     * @param sourceBucket The name of the source bucket
     * @param objectKey    The key (name) of the object to be copied
     * @param targetBucket The name of the target bucket
     */
    public static void copyDirectoryBucketObject(S3Client s3Client, String sourceBucket, String objectKey,
            String targetBucket) {
        logger.info("Copying object: {} from bucket: {} to bucket: {}", objectKey, sourceBucket, targetBucket);

        try {
            // Create a CopyObjectRequest
            CopyObjectRequest copyReq = CopyObjectRequest.builder()
                    .sourceBucket(sourceBucket)
                    .sourceKey(objectKey)
                    .destinationBucket(targetBucket)
                    .destinationKey(objectKey)
                    .build();

            // Copy the object
            CopyObjectResponse copyRes = s3Client.copyObject(copyReq);
            logger.info("Successfully copied {} from bucket {} into bucket {}. CopyObjectResponse: {}",
                    objectKey, sourceBucket, targetBucket, copyRes.copyObjectResult().toString());

        } catch (S3Exception e) {
            logger.error("Failed to copy object: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CopyObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CopyObject)」を参照してください。**

### `CreateBucket`
<a name="s3-directory-buckets_CreateBucket_java_2_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
S3 ディレクトリバケットを作成します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.BucketInfo;
import software.amazon.awssdk.services.s3.model.BucketType;
import software.amazon.awssdk.services.s3.model.CreateBucketConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.CreateBucketResponse;
import software.amazon.awssdk.services.s3.model.DataRedundancy;
import software.amazon.awssdk.services.s3.model.LocationInfo;
import software.amazon.awssdk.services.s3.model.LocationType;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;

    /**
     * Creates a new S3 directory bucket in a specified Zone (For example, a
     * specified Availability Zone in this code example).
     *
     * @param s3Client   The S3 client used to create the bucket
     * @param bucketName The name of the bucket to be created
     * @param zone       The region where the bucket will be created
     * @throws S3Exception if there's an error creating the bucket
     */
    public static void createDirectoryBucket(S3Client s3Client, String bucketName, String zone) throws S3Exception {
        logger.info("Creating bucket: {}", bucketName);

        CreateBucketConfiguration bucketConfiguration = CreateBucketConfiguration.builder()
                .location(LocationInfo.builder()
                        .type(LocationType.AVAILABILITY_ZONE)
                        .name(zone).build())
                .bucket(BucketInfo.builder()
                        .type(BucketType.DIRECTORY)
                        .dataRedundancy(DataRedundancy.SINGLE_AVAILABILITY_ZONE)
                        .build())
                .build();
        try {
            CreateBucketRequest bucketRequest = CreateBucketRequest.builder()
                    .bucket(bucketName)
                    .createBucketConfiguration(bucketConfiguration).build();
            CreateBucketResponse response = s3Client.createBucket(bucketRequest);
            logger.info("Bucket created successfully with location: {}", response.location());
        } catch (S3Exception e) {
            logger.error("Error creating bucket: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)」を参照してください。**

### `CreateMultipartUpload`
<a name="s3-directory-buckets_CreateMultipartUpload_java_2_topic"></a>

次のコード例は、`CreateMultipartUpload` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットにマルチパートアップロードを作成します。  

```
import com.example.s3.util.S3DirectoryBucketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;

    /**
     * This method creates a multipart upload request that generates a unique upload
     * ID used to track
     * all the upload parts.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to be uploaded
     * @return The upload ID used to track the multipart upload
     */
    public static String createDirectoryBucketMultipartUpload(S3Client s3Client, String bucketName, String objectKey) {
        logger.info("Creating multipart upload for object: {} in bucket: {}", objectKey, bucketName);

        try {
            // Create a CreateMultipartUploadRequest
            CreateMultipartUploadRequest createMultipartUploadRequest = CreateMultipartUploadRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .build();

            // Initiate the multipart upload
            CreateMultipartUploadResponse response = s3Client.createMultipartUpload(createMultipartUploadRequest);
            String uploadId = response.uploadId();
            logger.info("Multipart upload initiated. Upload ID: {}", uploadId);
            return uploadId;

        } catch (S3Exception e) {
            logger.error("Failed to create multipart upload: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[CreateMultipartUpload](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateMultipartUpload)」を参照してください。

### `DeleteBucket`
<a name="s3-directory-buckets_DeleteBucket_java_2_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
S3 ディレクトリバケットを削除します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;

    /**
     * Deletes the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket to delete
     */
    public static void deleteDirectoryBucket(S3Client s3Client, String bucketName) {
        logger.info("Deleting bucket: {}", bucketName);

        try {
            // Create a DeleteBucketRequest
            DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
                    .bucket(bucketName)
                    .build();

            // Delete the bucket
            s3Client.deleteBucket(deleteBucketRequest);
            logger.info("Successfully deleted bucket: {}", bucketName);

        } catch (S3Exception e) {
            logger.error("Failed to delete bucket: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DeleteBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucket)」を参照してください。**

### `DeleteBucketEncryption`
<a name="s3-directory-buckets_DeleteBucketEncryption_java_2_topic"></a>

次のコード例は、`DeleteBucketEncryption` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットの暗号化設定を削除します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteBucketEncryptionRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;

    /**
     * Deletes the encryption configuration from an S3 bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     */
    public static void deleteDirectoryBucketEncryption(S3Client s3Client, String bucketName) {
        DeleteBucketEncryptionRequest deleteRequest = DeleteBucketEncryptionRequest.builder()
                .bucket(bucketName)
                .build();

        try {
            s3Client.deleteBucketEncryption(deleteRequest);
            logger.info("Bucket encryption deleted for bucket: {}", bucketName);
        } catch (S3Exception e) {
            logger.error("Failed to delete bucket encryption: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteBucketEncryption](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucketEncryption)」を参照してください。

### `DeleteBucketPolicy`
<a name="s3-directory-buckets_DeleteBucketPolicy_java_2_topic"></a>

次のコード例は、`DeleteBucketPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のバケットポリシーを削除します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getAwsAccountId;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketPolicy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


    /**
     * Deletes the bucket policy for the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     */
    public static void deleteDirectoryBucketPolicy(S3Client s3Client, String bucketName) {
        logger.info("Deleting policy for bucket: {}", bucketName);

        try {
            // Create a DeleteBucketPolicyRequest
            DeleteBucketPolicyRequest deletePolicyReq = DeleteBucketPolicyRequest.builder()
                    .bucket(bucketName)
                    .build();

            // Delete the bucket policy
            s3Client.deleteBucketPolicy(deletePolicyReq);
            logger.info("Successfully deleted bucket policy");

        } catch (S3Exception e) {
            logger.error("Failed to delete bucket policy: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteBucketPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteBucketPolicy)」を参照してください。

### `DeleteObject`
<a name="s3-directory-buckets_DeleteObject_java_2_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のオブジェクトを削除します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.nio.file.Path;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;




    /**
     * Deletes an object from the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to be deleted
     */
    public static void deleteDirectoryBucketObject(S3Client s3Client, String bucketName, String objectKey) {
        logger.info("Deleting object: {} from bucket: {}", objectKey, bucketName);

        try {
            // Create a DeleteObjectRequest
            DeleteObjectRequest deleteObjectRequest = DeleteObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .build();

            // Delete the object
            s3Client.deleteObject(deleteObjectRequest);
            logger.info("Object {} has been deleted", objectKey);

        } catch (S3Exception e) {
            logger.error("Failed to delete object: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3-directory-buckets_DeleteObjects_java_2_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内の複数のオブジェクトを削除します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Delete;
import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectsResponse;
import software.amazon.awssdk.services.s3.model.ObjectIdentifier;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;


    /**
     * Deletes multiple objects from the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKeys The list of keys (names) of the objects to be deleted
     */
    public static void deleteDirectoryBucketObjects(S3Client s3Client, String bucketName, List<String> objectKeys) {
        logger.info("Deleting objects from bucket: {}", bucketName);

        try {
            // Create a list of ObjectIdentifier.
            List<ObjectIdentifier> identifiers = objectKeys.stream()
                    .map(key -> ObjectIdentifier.builder().key(key).build())
                    .toList();

            Delete delete = Delete.builder()
                    .objects(identifiers)
                    .build();

            DeleteObjectsRequest deleteObjectsRequest = DeleteObjectsRequest.builder()
                    .bucket(bucketName)
                    .delete(delete)
                    .build();

            DeleteObjectsResponse deleteObjectsResponse = s3Client.deleteObjects(deleteObjectsRequest);
            deleteObjectsResponse.deleted().forEach(deleted -> logger.info("Deleted object: {}", deleted.key()));

        } catch (S3Exception e) {
            logger.error("Failed to delete objects: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/DeleteObjects)」を参照してください。**

### `GetBucketEncryption`
<a name="s3-directory-buckets_GetBucketEncryption_java_2_topic"></a>

次のコード例は、`GetBucketEncryption` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットの暗号化設定を取得します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetBucketEncryptionRequest;
import software.amazon.awssdk.services.s3.model.GetBucketEncryptionResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.ServerSideEncryptionRule;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;

    /**
     * Retrieves the encryption configuration for an S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @return The type of server-side encryption applied to the bucket (e.g.,
     *         AES256, aws:kms)
     */
    public static String getDirectoryBucketEncryption(S3Client s3Client, String bucketName) {
        try {
            // Create a GetBucketEncryptionRequest
            GetBucketEncryptionRequest getRequest = GetBucketEncryptionRequest.builder()
                    .bucket(bucketName)
                    .build();

            // Retrieve the bucket encryption configuration
            GetBucketEncryptionResponse response = s3Client.getBucketEncryption(getRequest);
            ServerSideEncryptionRule rule = response.serverSideEncryptionConfiguration().rules().get(0);

            String encryptionType = rule.applyServerSideEncryptionByDefault().sseAlgorithmAsString();
            logger.info("Bucket encryption algorithm: {}", encryptionType);
            logger.info("KMS Customer Managed Key ID: {}", rule.applyServerSideEncryptionByDefault().kmsMasterKeyID());
            logger.info("Bucket Key Enabled: {}", rule.bucketKeyEnabled());

            return encryptionType;
        } catch (S3Exception e) {
            logger.error("Failed to get bucket encryption: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[GetBucketEncryption](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetBucketEncryption)」を参照してください。**

### `GetBucketPolicy`
<a name="s3-directory-buckets_GetBucketPolicy_java_2_topic"></a>

次のコード例は、`GetBucketPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットのポリシーを取得します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.GetBucketPolicyResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getAwsAccountId;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketPolicy;

    /**
     * Retrieves the bucket policy for the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @return The bucket policy text
     */
    public static String getDirectoryBucketPolicy(S3Client s3Client, String bucketName) {
        logger.info("Getting policy for bucket: {}", bucketName);

        try {
            // Create a GetBucketPolicyRequest
            GetBucketPolicyRequest policyReq = GetBucketPolicyRequest.builder()
                    .bucket(bucketName)
                    .build();

            // Retrieve the bucket policy
            GetBucketPolicyResponse response = s3Client.getBucketPolicy(policyReq);

            // Print and return the policy text
            String policyText = response.policy();
            logger.info("Bucket policy: {}", policyText);
            return policyText;

        } catch (S3Exception e) {
            logger.error("Failed to get bucket policy: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[GetBucketPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetBucketPolicy)」を参照してください。

### `GetObject`
<a name="s3-directory-buckets_GetObject_java_2_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットからオブジェクトを取得します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.ResponseBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.nio.charset.StandardCharsets;
import java.nio.file.Path;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;

    /**
     * Retrieves an object from the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to be retrieved
     * @return The retrieved object as a ResponseInputStream
     */
    public static boolean getDirectoryBucketObject(S3Client s3Client, String bucketName, String objectKey) {
        logger.info("Retrieving object: {} from bucket: {}", objectKey, bucketName);

        try {
            // Create a GetObjectRequest
            GetObjectRequest objectRequest = GetObjectRequest.builder()
                    .key(objectKey)
                    .bucket(bucketName)
                    .build();

            // Retrieve the object as bytes
            ResponseBytes<GetObjectResponse> objectBytes = s3Client.getObjectAsBytes(objectRequest);
            byte[] data = objectBytes.asByteArray();

            // Print object contents to console
            String objectContent = new String(data, StandardCharsets.UTF_8);
            logger.info("Object contents: \n{}", objectContent);

            return true;

        } catch (S3Exception e) {
            logger.error("Failed to retrieve object: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            return false;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[GetObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObject)」を参照してください。**

### `GetObjectAttributes`
<a name="s3-directory-buckets_GetObjectAttributes_java_2_topic"></a>

次のコード例は、`GetObjectAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットからオブジェクト属性を取得します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectAttributesRequest;
import software.amazon.awssdk.services.s3.model.GetObjectAttributesResponse;
import software.amazon.awssdk.services.s3.model.ObjectAttributes;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.nio.file.Path;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;

    /**
     * Retrieves attributes for an object in the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to retrieve attributes for
     * @return True if the object attributes are successfully retrieved, false
     *         otherwise
     */
    public static boolean getDirectoryBucketObjectAttributes(S3Client s3Client, String bucketName, String objectKey) {
        logger.info("Retrieving attributes for object: {} from bucket: {}", objectKey, bucketName);

        try {
            // Create a GetObjectAttributesRequest
            GetObjectAttributesRequest getObjectAttributesRequest = GetObjectAttributesRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .objectAttributes(ObjectAttributes.E_TAG, ObjectAttributes.STORAGE_CLASS,
                            ObjectAttributes.OBJECT_SIZE)
                    .build();

            // Retrieve the object attributes
            GetObjectAttributesResponse response = s3Client.getObjectAttributes(getObjectAttributesRequest);
            logger.info("Attributes for object {}:", objectKey);
            logger.info("ETag: {}", response.eTag());
            logger.info("Storage Class: {}", response.storageClass());
            logger.info("Object Size: {}", response.objectSize());
            return true;

        } catch (S3Exception e) {
            logger.error("Failed to retrieve object attributes: {} - Error code: {}",
                    e.awsErrorDetails().errorMessage(), e.awsErrorDetails().errorCode(), e);
            return false;
        }
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[GetObjectAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObjectAttributes)」を参照してください。**

### `HeadBucket`
<a name="s3-directory-buckets_HeadBucket_java_2_topic"></a>

次のコード例は、`HeadBucket` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
指定された S3 ディレクトリバケットが存在し、アクセス可能であるかどうかを確認します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;

    /**
     * Checks if the specified S3 directory bucket exists and is accessible.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket to check
     * @return True if the bucket exists and is accessible, false otherwise
     */
    public static boolean headDirectoryBucket(S3Client s3Client, String bucketName) {
        logger.info("Checking if bucket exists: {}", bucketName);

        try {
            // Create a HeadBucketRequest
            HeadBucketRequest headBucketRequest = HeadBucketRequest.builder()
                    .bucket(bucketName)
                    .build();
            // If the bucket doesn't exist, the following statement throws NoSuchBucketException,
            // which is a subclass of S3Exception.
            s3Client.headBucket(headBucketRequest);
            logger.info("Amazon S3 directory bucket: \"{}\" found.", bucketName);
            return true;

        } catch (S3Exception e) {
            logger.error("Failed to access bucket: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[HeadBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/HeadBucket)」を参照してください。

### `HeadObject`
<a name="s3-directory-buckets_HeadObject_java_2_topic"></a>

次のコード例は、`HeadObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のオブジェクトのメタデータを取得します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.nio.file.Path;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;

    /**
     * Retrieves metadata for an object in the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to retrieve metadata for
     * @return True if the object exists, false otherwise
     */
    public static boolean headDirectoryBucketObject(S3Client s3Client, String bucketName, String objectKey) {
        logger.info("Retrieving metadata for object: {} from bucket: {}", objectKey, bucketName);

        try {
            // Create a HeadObjectRequest
            HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .build();

            // Retrieve the object metadata
            HeadObjectResponse response = s3Client.headObject(headObjectRequest);
            logger.info("Amazon S3 object: \"{}\" found in bucket: \"{}\" with ETag: \"{}\"", objectKey, bucketName,
                    response.eTag());
            logger.info("Content-Type: {}", response.contentType());
            logger.info("Content-Length: {}", response.contentLength());
            logger.info("Last Modified: {}", response.lastModified());
            return true;

        } catch (S3Exception e) {
            logger.error("Failed to retrieve object metadata: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            return false;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[HeadObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/HeadObject)」を参照してください。

### `ListDirectoryBuckets`
<a name="s3-directory-buckets_ListDirectoryBuckets_java_2_topic"></a>

次のコード例は、`ListDirectoryBuckets` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
すべてのディレクトリバケットを一覧表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.Bucket;
import software.amazon.awssdk.services.s3.model.ListDirectoryBucketsRequest;
import software.amazon.awssdk.services.s3.model.ListDirectoryBucketsResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;

     /**
     * Lists all S3 directory buckets and no general purpose buckets.
     *
     * @param s3Client The S3 client used to interact with S3
     * @return A list of bucket names
     */
    public static List<String> listDirectoryBuckets(S3Client s3Client) {
        logger.info("Listing all directory buckets");

        try {
            // Create a ListBucketsRequest
            ListDirectoryBucketsRequest listDirectoryBucketsRequest = ListDirectoryBucketsRequest.builder().build();

            // Retrieve the list of buckets
            ListDirectoryBucketsResponse response = s3Client.listDirectoryBuckets(listDirectoryBucketsRequest);

            // Extract bucket names
            List<String> bucketNames = response.buckets().stream()
                    .map(Bucket::name)
                    .collect(Collectors.toList());

            return bucketNames;
        } catch (S3Exception e) {
            logger.error("Failed to list buckets: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode());
            throw e;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListDirectoryBuckets](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListDirectoryBuckets)」を参照してください。

### `ListMultipartUploads`
<a name="s3-directory-buckets_ListMultipartUploads_java_2_topic"></a>

次のコード例は、`ListMultipartUploads` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のマルチパートアップロードを一覧表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsRequest;
import software.amazon.awssdk.services.s3.model.ListMultipartUploadsResponse;
import software.amazon.awssdk.services.s3.model.MultipartUpload;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import static com.example.s3.util.S3DirectoryBucketUtils.abortDirectoryBucketMultipartUploads;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucketMultipartUpload;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.multipartUploadForDirectoryBucket;


    /**
     * Lists multipart uploads for the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @return A list of MultipartUpload objects representing the multipart uploads
     */
    public static List<MultipartUpload> listDirectoryBucketMultipartUploads(S3Client s3Client, String bucketName) {
        logger.info("Listing in-progress multipart uploads for bucket: {}", bucketName);

        try {
            // Create a ListMultipartUploadsRequest
            ListMultipartUploadsRequest listMultipartUploadsRequest = ListMultipartUploadsRequest.builder()
                    .bucket(bucketName)
                    .build();

            // List the multipart uploads
            ListMultipartUploadsResponse response = s3Client.listMultipartUploads(listMultipartUploadsRequest);
            List<MultipartUpload> uploads = response.uploads();
            for (MultipartUpload upload : uploads) {
                logger.info("In-progress multipart upload: Upload ID: {}, Key: {}, Initiated: {}", upload.uploadId(),
                        upload.key(), upload.initiated());
            }
            return uploads;

        } catch (S3Exception e) {
            logger.error("Failed to list multipart uploads: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode());
            return List.of(); // Return an empty list if an exception is thrown
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListMultipartUploads](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListMultipartUploads)」を参照してください。

### `ListObjectsV2`
<a name="s3-directory-buckets_ListObjectsV2_java_2_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のオブジェクトを一覧表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.S3Object;

import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;

    /**
     * Lists objects in the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @return A list of object keys in the bucket
     */
    public static List<String> listDirectoryBucketObjectsV2(S3Client s3Client, String bucketName) {
        logger.info("Listing objects in bucket: {}", bucketName);

        try {
            // Create a ListObjectsV2Request
            ListObjectsV2Request listObjectsV2Request = ListObjectsV2Request.builder()
                    .bucket(bucketName)
                    .build();

            // Retrieve the list of objects
            ListObjectsV2Response response = s3Client.listObjectsV2(listObjectsV2Request);

            // Extract and return the object keys
            return response.contents().stream()
                    .map(S3Object::key)
                    .collect(Collectors.toList());

        } catch (S3Exception e) {
            logger.error("Failed to list objects: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode());
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListObjectsV2)」を参照してください。

### `ListParts`
<a name="s3-directory-buckets_ListParts_java_2_topic"></a>

次のコード例は、`ListParts` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のマルチパートアップロードの一部を一覧表示します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.ListPartsRequest;
import software.amazon.awssdk.services.s3.model.ListPartsResponse;
import software.amazon.awssdk.services.s3.model.Part;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import static com.example.s3.util.S3DirectoryBucketUtils.abortDirectoryBucketMultipartUploads;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucketMultipartUpload;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.multipartUploadForDirectoryBucket;

    /**
     * Lists the parts of a multipart upload for the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object being uploaded
     * @param uploadId   The upload ID used to track the multipart upload
     * @return A list of Part representing the parts of the multipart upload
     */
    public static List<Part> listDirectoryBucketMultipartUploadParts(S3Client s3Client, String bucketName,
            String objectKey, String uploadId) {
        logger.info("Listing parts for object: {} in bucket: {}", objectKey, bucketName);

        try {
            // Create a ListPartsRequest
            ListPartsRequest listPartsRequest = ListPartsRequest.builder()
                    .bucket(bucketName)
                    .uploadId(uploadId)
                    .key(objectKey)
                    .build();

            // List the parts of the multipart upload
            ListPartsResponse response = s3Client.listParts(listPartsRequest);
            List<Part> parts = response.parts();
            for (Part part : parts) {
                logger.info("Uploaded part: Part number = \"{}\", etag = {}", part.partNumber(), part.eTag());
            }
            return parts;

        } catch (S3Exception e) {
            logger.error("Failed to list parts: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode());
            return List.of(); // Return an empty list if an exception is thrown
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListParts](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/ListParts)」を参照してください。

### `PutBucketEncryption`
<a name="s3-directory-buckets_PutBucketEncryption_java_2_topic"></a>

次のコード例は、`PutBucketEncryption` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
バケット暗号化をディレクトリバケットに設定します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.kms.KmsClient;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutBucketEncryptionRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.ServerSideEncryption;
import software.amazon.awssdk.services.s3.model.ServerSideEncryptionByDefault;
import software.amazon.awssdk.services.s3.model.ServerSideEncryptionConfiguration;
import software.amazon.awssdk.services.s3.model.ServerSideEncryptionRule;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createKmsClient;
import static com.example.s3.util.S3DirectoryBucketUtils.createKmsKey;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.scheduleKeyDeletion;

    /**
     * Sets the default encryption configuration for an S3 bucket as SSE-KMS.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param kmsKeyId   The ID of the customer-managed KMS key
     */
    public static void putDirectoryBucketEncryption(S3Client s3Client, String bucketName, String kmsKeyId) {
        // Define the default encryption configuration to use SSE-KMS. For directory
        // buckets, AWS managed KMS keys aren't supported. Only customer-managed keys
        // are supported.
        ServerSideEncryptionByDefault encryptionByDefault = ServerSideEncryptionByDefault.builder()
                .sseAlgorithm(ServerSideEncryption.AWS_KMS)
                .kmsMasterKeyID(kmsKeyId)
                .build();

        // Create a server-side encryption rule to apply the default encryption
        // configuration. For directory buckets, the bucketKeyEnabled field is enforced
        // to be true.
        ServerSideEncryptionRule rule = ServerSideEncryptionRule.builder()
                .bucketKeyEnabled(true)
                .applyServerSideEncryptionByDefault(encryptionByDefault)
                .build();

        // Create the server-side encryption configuration for the bucket
        ServerSideEncryptionConfiguration encryptionConfiguration = ServerSideEncryptionConfiguration.builder()
                .rules(rule)
                .build();

        // Create the PutBucketEncryption request
        PutBucketEncryptionRequest putRequest = PutBucketEncryptionRequest.builder()
                .bucket(bucketName)
                .serverSideEncryptionConfiguration(encryptionConfiguration)
                .build();

        // Set the bucket encryption
        try {
            s3Client.putBucketEncryption(putRequest);
            logger.info("SSE-KMS Bucket encryption configuration set for the directory bucket: {}", bucketName);
        } catch (S3Exception e) {
            logger.error("Failed to set bucket encryption: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode());
            throw e;
        }
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[PutBucketEncryption](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketEncryption)」を参照してください。**

### `PutBucketPolicy`
<a name="s3-directory-buckets_PutBucketPolicy_java_2_topic"></a>

次のコード例は、`PutBucketPolicy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
バケットポリシーをディレクトリバケットに適用します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getAwsAccountId;

    /**
     * Sets the following bucket policy for the specified S3 directory bucket.
     *<pre>
     * {
     *     "Version":"2012-10-17",		 	 	 
     *     "Statement": [
     *         {
     *             "Sid": "AdminPolicy",
     *             "Effect": "Allow",
     *             "Principal": {
     *                 "AWS": "arn:aws:iam::<ACCOUNT_ID>:root"
     *             },
     *             "Action": "s3express:*",
     *             "Resource": "arn:aws:s3express:us-west-2:<ACCOUNT_ID>:bucket/<DIR_BUCKET_NAME>
     *         }
     *     ]
     * }
     * </pre>
     * This policy grants all S3 directory bucket actions to identities in the same account as the bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param policyText The policy text to be applied
     */
    public static void putDirectoryBucketPolicy(S3Client s3Client, String bucketName, String policyText) {
        logger.info("Setting policy on bucket: {}", bucketName);
        logger.info("Policy: {}", policyText);

        try {
            PutBucketPolicyRequest policyReq = PutBucketPolicyRequest.builder()
                    .bucket(bucketName)
                    .policy(policyText)
                    .build();

            s3Client.putBucketPolicy(policyReq);
            logger.info("Bucket policy set successfully!");

        } catch (S3Exception e) {
            logger.error("Failed to set bucket policy: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutBucketPolicy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketPolicy)」を参照してください。

### `PutObject`
<a name="s3-directory-buckets_PutObject_java_2_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケットにオブジェクトを配置します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.awscore.exception.AwsErrorDetails;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;

import java.io.UncheckedIOException;
import java.nio.file.Path;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;

    /**
     * Puts an object into the specified S3 directory bucket.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to be placed in the bucket
     * @param filePath   The path of the file to be uploaded
     */
    public static void putDirectoryBucketObject(S3Client s3Client, String bucketName, String objectKey, Path filePath) {
        logger.info("Putting object: {} into bucket: {}", objectKey, bucketName);

        try {
            // Create a PutObjectRequest
            PutObjectRequest putObj = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .build();

            // Upload the object
            s3Client.putObject(putObj, filePath);
            logger.info("Successfully placed {} into bucket {}", objectKey, bucketName);

        } catch (UncheckedIOException e) {
            throw S3Exception.builder().message("Failed to read the file: " + e.getMessage()).cause(e)
                    .awsErrorDetails(AwsErrorDetails.builder()
                            .errorCode("ClientSideException:FailedToReadFile")
                            .errorMessage(e.getMessage())
                            .build())
                    .build();
        } catch (S3Exception e) {
            logger.error("Failed to put object: {}", e.getMessage(), e);
            throw e;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[PutObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutObject)」を参照してください。

### `UploadPart`
<a name="s3-directory-buckets_UploadPart_java_2_topic"></a>

次のコード例は、`UploadPart` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ディレクトリバケット内のマルチパートアップロードの一部をアップロードします。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.UploadPartRequest;
import software.amazon.awssdk.services.s3.model.UploadPartResponse;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static com.example.s3.util.S3DirectoryBucketUtils.abortDirectoryBucketMultipartUploads;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucketMultipartUpload;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;

    /**
     * This method creates part requests and uploads individual parts to S3.
     * While it uses the UploadPart API to upload a single part, it does so
     * sequentially to handle multiple parts of a file, returning all the completed
     * parts.
     *
     * @param s3Client   The S3 client used to interact with S3
     * @param bucketName The name of the directory bucket
     * @param objectKey  The key (name) of the object to be uploaded
     * @param uploadId   The upload ID used to track the multipart upload
     * @param filePath   The path to the file to be uploaded
     * @return A list of uploaded parts
     * @throws IOException if an I/O error occurs
     */
    public static List<CompletedPart> multipartUploadForDirectoryBucket(S3Client s3Client, String bucketName,
            String objectKey, String uploadId, Path filePath) throws IOException {
        logger.info("Uploading parts for object: {} in bucket: {}", objectKey, bucketName);

        int partNumber = 1;
        List<CompletedPart> uploadedParts = new ArrayList<>();
        ByteBuffer bb = ByteBuffer.allocate(1024 * 1024 * 5); // 5 MB byte buffer

        // Read the local file, break down into chunks and process
        try (RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r")) {
            long fileSize = file.length();
            int position = 0;

            // Sequentially upload parts of the file
            while (position < fileSize) {
                file.seek(position);
                int read = file.getChannel().read(bb);

                bb.flip(); // Swap position and limit before reading from the buffer
                UploadPartRequest uploadPartRequest = UploadPartRequest.builder()
                        .bucket(bucketName)
                        .key(objectKey)
                        .uploadId(uploadId)
                        .partNumber(partNumber)
                        .build();

                UploadPartResponse partResponse = s3Client.uploadPart(
                        uploadPartRequest,
                        RequestBody.fromByteBuffer(bb));

                // Build the uploaded part
                CompletedPart uploadedPart = CompletedPart.builder()
                        .partNumber(partNumber)
                        .eTag(partResponse.eTag())
                        .build();

                // Add the uploaded part to the list
                uploadedParts.add(uploadedPart);

                // Log to indicate the part upload is done
                logger.info("Uploaded part number: {} with ETag: {}", partNumber, partResponse.eTag());

                bb.clear();
                position += read;
                partNumber++;
            }
        } catch (S3Exception e) {
            logger.error("Failed to list parts: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode());
            throw e;
        }
        return uploadedParts;
    }
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス」の「[UploadPart](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/UploadPart)」を参照してください。**

### `UploadPartCopy`
<a name="s3-directory-buckets_UploadPartCopy_java_2_topic"></a>

次のコード例は、`UploadPartCopy` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
ソースオブジェクトのサイズに基づいてコピーパーツを作成し、個々のパーツをディレクトリバケットにコピーします。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.CompletedPart;
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.UploadPartCopyRequest;
import software.amazon.awssdk.services.s3.model.UploadPartCopyResponse;

import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static com.example.s3.util.S3DirectoryBucketUtils.abortDirectoryBucketMultipartUploads;
import static com.example.s3.util.S3DirectoryBucketUtils.completeDirectoryBucketMultipartUpload;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucketMultipartUpload;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.multipartUploadForDirectoryBucket;

    /**
     * Creates copy parts based on source object size and copies over individual
     * parts.
     *
     * @param s3Client          The S3 client used to interact with S3
     * @param sourceBucket      The name of the source bucket
     * @param sourceKey         The key (name) of the source object
     * @param destinationBucket The name of the destination bucket
     * @param destinationKey    The key (name) of the destination object
     * @param uploadId          The upload ID used to track the multipart upload
     * @return A list of completed parts
     */
    public static List<CompletedPart> multipartUploadCopyForDirectoryBucket(S3Client s3Client, String sourceBucket,
            String sourceKey, String destinationBucket, String destinationKey, String uploadId) {
        // Get the object size to track the end of the copy operation
        HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
                .bucket(sourceBucket)
                .key(sourceKey)
                .build();
        HeadObjectResponse headObjectResponse = s3Client.headObject(headObjectRequest);
        long objectSize = headObjectResponse.contentLength();

        logger.info("Source Object size: {}", objectSize);

        // Copy the object using 20 MB parts
        long partSize = 20 * 1024 * 1024; // 20 MB
        long bytePosition = 0;
        int partNum = 1;
        List<CompletedPart> uploadedParts = new ArrayList<>();

        while (bytePosition < objectSize) {
            long lastByte = Math.min(bytePosition + partSize - 1, objectSize - 1);
            logger.info("Part Number: {}, Byte Position: {}, Last Byte: {}", partNum, bytePosition, lastByte);

            try {
                UploadPartCopyRequest uploadPartCopyRequest = UploadPartCopyRequest.builder()
                        .sourceBucket(sourceBucket)
                        .sourceKey(sourceKey)
                        .destinationBucket(destinationBucket)
                        .destinationKey(destinationKey)
                        .uploadId(uploadId)
                        .copySourceRange("bytes=" + bytePosition + "-" + lastByte)
                        .partNumber(partNum)
                        .build();
                UploadPartCopyResponse uploadPartCopyResponse = s3Client.uploadPartCopy(uploadPartCopyRequest);

                CompletedPart part = CompletedPart.builder()
                        .partNumber(partNum)
                        .eTag(uploadPartCopyResponse.copyPartResult().eTag())
                        .build();
                uploadedParts.add(part);

                bytePosition += partSize;
                partNum++;
            } catch (S3Exception e) {
                logger.error("Failed to copy part number {}: {} - Error code: {}", partNum,
                        e.awsErrorDetails().errorMessage(), e.awsErrorDetails().errorCode());
                throw e;
            }
        }

        return uploadedParts;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UploadPartCopy](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/UploadPartCopy)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### オブジェクトを取得する署名付き URL を作成する
<a name="s3-directory-buckets_GeneratePresignedGetURLForDirectoryBucket_java_2_topic"></a>

次のコード例は、S3 ディレクトリバケットの署名付き URL を作成し、オブジェクトを取得する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3/src/main/java/com/example/s3/directorybucket#code-examples)での設定と実行の方法を確認してください。
S3 ディレクトリバケット内のオブジェクトにアクセスするための署名付き GET URL を生成します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.presigner.S3Presigner;
import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest;
import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest;

import java.nio.file.Path;
import java.time.Duration;

import static com.example.s3.util.S3DirectoryBucketUtils.createDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Client;
import static com.example.s3.util.S3DirectoryBucketUtils.createS3Presigner;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteAllObjectsInDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.deleteDirectoryBucket;
import static com.example.s3.util.S3DirectoryBucketUtils.getFilePath;
import static com.example.s3.util.S3DirectoryBucketUtils.putDirectoryBucketObject;


    /**
     * Generates a presigned URL for accessing an object in the specified S3
     * directory bucket.
     *
     * @param s3Presigner The S3 presigner client used to generate the presigned URL
     * @param bucketName  The name of the directory bucket
     * @param objectKey   The key (name) of the object to access
     * @return A presigned URL for accessing the specified object
     */
    public static String generatePresignedGetURLForDirectoryBucket(S3Presigner s3Presigner, String bucketName,
            String objectKey) {
        logger.info("Generating presigned URL for object: {} in bucket: {}", objectKey, bucketName);

        try {
            // Create a GetObjectRequest
            GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                    .bucket(bucketName)
                    .key(objectKey)
                    .build();

            // Create a GetObjectPresignRequest
            GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder()
                    .signatureDuration(Duration.ofMinutes(10)) // Presigned URL valid for 10 minutes
                    .getObjectRequest(getObjectRequest)
                    .build();

            // Generate the presigned URL
            PresignedGetObjectRequest presignedGetObjectRequest = s3Presigner.presignGetObject(getObjectPresignRequest);

            // Get the presigned URL
            String presignedURL = presignedGetObjectRequest.url().toString();
            logger.info("Presigned URL: {}", presignedURL);
            return presignedURL;

        } catch (S3Exception e) {
            logger.error("Failed to generate presigned URL: {} - Error code: {}", e.awsErrorDetails().errorMessage(),
                    e.awsErrorDetails().errorCode(), e);
            throw e;
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[GetObject](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/GetObject)」を参照してください。**

# SDK for Java 2.x を使用した SageMaker AI の例
<a name="java_2_sagemaker_code_examples"></a>

次のコード例は、SageMaker AI AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello SageMaker AI
<a name="sagemaker_Hello_java_2_topic"></a>

次のコード例は、SageMaker AI の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sagemaker#code-examples)での設定と実行の方法を確認してください。

```
/**
 * 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 HelloSageMaker {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        SageMakerClient sageMakerClient = SageMakerClient.builder()
                .region(region)
                .build();

        listBooks(sageMakerClient);
        sageMakerClient.close();
    }

    public static void listBooks(SageMakerClient sageMakerClient) {
        try {
            ListNotebookInstancesResponse notebookInstancesResponse = sageMakerClient.listNotebookInstances();
            List<NotebookInstanceSummary> items = notebookInstancesResponse.notebookInstances();
            for (NotebookInstanceSummary item : items) {
                System.out.println("The notebook name is: " + item.notebookInstanceName());
            }

        } catch (SageMakerException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListNotebookInstances](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/ListNotebookInstances)」を参照してください。

## アクション
<a name="actions"></a>

### `CreatePipeline`
<a name="sagemaker_CreatePipeline_java_2_topic"></a>

次のコード例は、`CreatePipeline` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
    // Create a pipeline from the example pipeline JSON.
    public static void setupPipeline(SageMakerClient sageMakerClient, String filePath, String roleArn,
            String functionArn, String pipelineName) {
        System.out.println("Setting up the pipeline.");
        JSONParser parser = new JSONParser();

        // Read JSON and get pipeline definition.
        try (FileReader reader = new FileReader(filePath)) {
            Object obj = parser.parse(reader);
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray stepsArray = (JSONArray) jsonObject.get("Steps");
            for (Object stepObj : stepsArray) {
                JSONObject step = (JSONObject) stepObj;
                if (step.containsKey("FunctionArn")) {
                    step.put("FunctionArn", functionArn);
                }
            }
            System.out.println(jsonObject);

            // Create the pipeline.
            CreatePipelineRequest pipelineRequest = CreatePipelineRequest.builder()
                    .pipelineDescription("Java SDK example pipeline")
                    .roleArn(roleArn)
                    .pipelineName(pipelineName)
                    .pipelineDefinition(jsonObject.toString())
                    .build();

            sageMakerClient.createPipeline(pipelineRequest);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        } catch (IOException | ParseException e) {
            throw new RuntimeException(e);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreatePipeline](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/CreatePipeline)」を参照してください。

### `DeletePipeline`
<a name="sagemaker_DeletePipeline_java_2_topic"></a>

次のコード例は、`DeletePipeline` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
    // Delete a SageMaker pipeline by name.
    public static void deletePipeline(SageMakerClient sageMakerClient, String pipelineName) {
        DeletePipelineRequest pipelineRequest = DeletePipelineRequest.builder()
                .pipelineName(pipelineName)
                .build();

        sageMakerClient.deletePipeline(pipelineRequest);
        System.out.println("*** Successfully deleted " + pipelineName);
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeletePipeline](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/DeletePipeline)」を参照してください。

### `DescribePipelineExecution`
<a name="sagemaker_DescribePipelineExecution_java_2_topic"></a>

次のコード例は、`DescribePipelineExecution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
    // Check the status of a pipeline execution.
    public static void waitForPipelineExecution(SageMakerClient sageMakerClient, String executionArn)
            throws InterruptedException {
        String status;
        int index = 0;
        do {
            DescribePipelineExecutionRequest pipelineExecutionRequest = DescribePipelineExecutionRequest.builder()
                    .pipelineExecutionArn(executionArn)
                    .build();

            DescribePipelineExecutionResponse response = sageMakerClient
                    .describePipelineExecution(pipelineExecutionRequest);
            status = response.pipelineExecutionStatusAsString();
            System.out.println(index + ". The Status of the pipeline is " + status);
            TimeUnit.SECONDS.sleep(4);
            index++;
        } while ("Executing".equals(status));
        System.out.println("Pipeline finished with status " + status);
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribePipelineExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/DescribePipelineExecution)」を参照してください。

### `StartPipelineExecution`
<a name="sagemaker_StartPipelineExecution_java_2_topic"></a>

次のコード例は、`StartPipelineExecution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
    // Start a pipeline run with job configurations.
    public static String executePipeline(SageMakerClient sageMakerClient, String bucketName, String queueUrl,
            String roleArn, String pipelineName) {
        System.out.println("Starting pipeline execution.");
        String inputBucketLocation = "s3://" + bucketName + "/samplefiles/latlongtest.csv";
        String output = "s3://" + bucketName + "/outputfiles/";
        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .setPrettyPrinting().create();

        // Set up all parameters required to start the pipeline.
        List<Parameter> parameters = new ArrayList<>();
        Parameter para1 = Parameter.builder()
                .name("parameter_execution_role")
                .value(roleArn)
                .build();

        Parameter para2 = Parameter.builder()
                .name("parameter_queue_url")
                .value(queueUrl)
                .build();

        String inputJSON = "{\n" +
                "  \"DataSourceConfig\": {\n" +
                "    \"S3Data\": {\n" +
                "      \"S3Uri\": \"s3://" + bucketName + "/samplefiles/latlongtest.csv\"\n" +
                "    },\n" +
                "    \"Type\": \"S3_DATA\"\n" +
                "  },\n" +
                "  \"DocumentType\": \"CSV\"\n" +
                "}";

        System.out.println(inputJSON);

        Parameter para3 = Parameter.builder()
                .name("parameter_vej_input_config")
                .value(inputJSON)
                .build();

        // Create an ExportVectorEnrichmentJobOutputConfig object.
        VectorEnrichmentJobS3Data jobS3Data = VectorEnrichmentJobS3Data.builder()
                .s3Uri(output)
                .build();

        ExportVectorEnrichmentJobOutputConfig outputConfig = ExportVectorEnrichmentJobOutputConfig.builder()
                .s3Data(jobS3Data)
                .build();

        String gson4 = gson.toJson(outputConfig);
        Parameter para4 = Parameter.builder()
                .name("parameter_vej_export_config")
                .value(gson4)
                .build();
        System.out.println("parameter_vej_export_config:" + gson.toJson(outputConfig));

        // Create a VectorEnrichmentJobConfig object.
        ReverseGeocodingConfig reverseGeocodingConfig = ReverseGeocodingConfig.builder()
                .xAttributeName("Longitude")
                .yAttributeName("Latitude")
                .build();

        VectorEnrichmentJobConfig jobConfig = VectorEnrichmentJobConfig.builder()
                .reverseGeocodingConfig(reverseGeocodingConfig)
                .build();

        String para5JSON = "{\"MapMatchingConfig\":null,\"ReverseGeocodingConfig\":{\"XAttributeName\":\"Longitude\",\"YAttributeName\":\"Latitude\"}}";
        Parameter para5 = Parameter.builder()
                .name("parameter_step_1_vej_config")
                .value(para5JSON)
                .build();

        System.out.println("parameter_step_1_vej_config:" + gson.toJson(jobConfig));
        parameters.add(para1);
        parameters.add(para2);
        parameters.add(para3);
        parameters.add(para4);
        parameters.add(para5);

        StartPipelineExecutionRequest pipelineExecutionRequest = StartPipelineExecutionRequest.builder()
                .pipelineExecutionDescription("Created using Java SDK")
                .pipelineExecutionDisplayName(pipelineName + "-example-execution")
                .pipelineParameters(parameters)
                .pipelineName(pipelineName)
                .build();

        StartPipelineExecutionResponse response = sageMakerClient.startPipelineExecution(pipelineExecutionRequest);
        return response.pipelineExecutionArn();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[StartPipelineExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/StartPipelineExecution)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 地理空間ジョブとパイプラインの使用を開始する
<a name="sagemaker_Scenario_Pipelines_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パイプラインのリソースを設定します。
+ 地理空間ジョブを実行するパイプラインを設定します。
+ パイプラインの実行を開始します。
+ ジョブ実行のステータスをモニタリングします。
+ パイプラインの出力を表示します。
+ リソースをクリーンアップします。

詳細については、[「Community.aws で SDK を使用して SageMaker パイプラインを作成および実行する AWS SDKs](https://community.aws/posts/create-and-run-sagemaker-pipelines-using-aws-sdks)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
public class SagemakerWorkflow {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static String eventSourceMapping = "";

    public static void main(String[] args) throws InterruptedException {
        final String usage = "\n" +
                "Usage:\n" +
                "    <sageMakerRoleName> <lambdaRoleName> <functionFileLocation> <functionName> <queueName> <bucketName> <lnglatData> <spatialPipelinePath> <pipelineName>\n\n"
                +
                "Where:\n" +
                "    sageMakerRoleName - The name of the Amazon SageMaker role.\n\n" +
                "    lambdaRoleName - The name of the AWS Lambda role.\n\n" +
                "    functionFileLocation - The file location where the JAR file that represents the AWS Lambda function is located.\n\n"
                +
                "    functionName - The name of the AWS Lambda function (for example,SageMakerExampleFunction).\n\n" +
                "    queueName - The name of the Amazon Simple Queue Service (Amazon SQS) queue.\n\n" +
                "    bucketName - The name of the Amazon Simple Storage Service (Amazon S3) bucket.\n\n" +
                "    lnglatData - The file location of the latlongtest.csv file required for this use case.\n\n" +
                "    spatialPipelinePath - The file location of the GeoSpatialPipeline.json file required for this use case.\n\n"
                +
                "    pipelineName - The name of the pipeline to create (for example, sagemaker-sdk-example-pipeline).\n\n";

        if (args.length != 9) {
            System.out.println(usage);
            System.exit(1);
        }

        String sageMakerRoleName = args[0];
        String lambdaRoleName = args[1];
        String functionFileLocation = args[2];
        String functionName = args[3];
        String queueName = args[4];
        String bucketName = args[5];
        String lnglatData = args[6];
        String spatialPipelinePath = args[7];
        String pipelineName = args[8];
        String handlerName = "org.example.SageMakerLambdaFunction::handleRequest";

        Region region = Region.US_WEST_2;
        SageMakerClient sageMakerClient = SageMakerClient.builder()
                .region(region)
                .build();

        IamClient iam = IamClient.builder()
                .region(region)
                .build();

        LambdaClient lambdaClient = LambdaClient.builder()
                .region(region)
                .build();

        SqsClient sqsClient = SqsClient.builder()
                .region(region)
                .build();

        S3Client s3Client = S3Client.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the Amazon SageMaker pipeline example scenario.");
        System.out.println(
                "\nThis example workflow will guide you through setting up and running an" +
                        "\nAmazon SageMaker pipeline. The pipeline uses an AWS Lambda function and an" +
                        "\nAmazon SQS Queue. It runs a vector enrichment reverse geocode job to" +
                        "\nreverse geocode addresses in an input file and store the results in an export file.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("First, we will set up the roles, functions, and queue needed by the SageMaker pipeline.");
        String lambdaRoleArn = checkLambdaRole(iam, lambdaRoleName);
        String sageMakerRoleArn = checkSageMakerRole(iam, sageMakerRoleName);

        String functionArn = checkFunction(lambdaClient, functionName, functionFileLocation, lambdaRoleArn,
                handlerName);
        String queueUrl = checkQueue(sqsClient, lambdaClient, queueName, functionName);
        System.out.println("The queue URL is " + queueUrl);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Setting up bucket " + bucketName);
        if (!checkBucket(s3Client, bucketName)) {
            setupBucket(s3Client, bucketName);
            System.out.println("Put " + lnglatData + " into " + bucketName);
            putS3Object(s3Client, bucketName, "latlongtest.csv", lnglatData);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Now we can create and run our pipeline.");
        setupPipeline(sageMakerClient, spatialPipelinePath, sageMakerRoleArn, functionArn, pipelineName);
        String pipelineExecutionARN = executePipeline(sageMakerClient, bucketName, queueUrl, sageMakerRoleArn,
                pipelineName);
        System.out.println("The pipeline execution ARN value is " + pipelineExecutionARN);
        waitForPipelineExecution(sageMakerClient, pipelineExecutionARN);
        System.out.println("Getting output results " + bucketName);
        getOutputResults(s3Client, bucketName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The pipeline has completed. To view the pipeline and runs " +
                "in SageMaker Studio, follow these instructions:" +
                "\nhttps://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-studio.html");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("Do you want to delete the AWS resources used in this Workflow? (y/n)");
        Scanner in = new Scanner(System.in);
        String delResources = in.nextLine();
        if (delResources.compareTo("y") == 0) {
            System.out.println("Lets clean up the AWS resources. Wait 30 seconds");
            TimeUnit.SECONDS.sleep(30);
            deleteEventSourceMapping(lambdaClient);
            deleteSQSQueue(sqsClient, queueName);
            listBucketObjects(s3Client, bucketName);
            deleteBucket(s3Client, bucketName);
            deleteLambdaFunction(lambdaClient, functionName);
            deleteLambdaRole(iam, lambdaRoleName);
            deleteSagemakerRole(iam, sageMakerRoleName);
            deletePipeline(sageMakerClient, pipelineName);
        } else {
            System.out.println("The AWS Resources were not deleted!");
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("SageMaker pipeline scenario is complete.");
        System.out.println(DASHES);
    }

    private static void readObject(S3Client s3Client, String bucketName, String key) {
        System.out.println("Output file contents: \n");
        GetObjectRequest objectRequest = GetObjectRequest.builder()
                .bucket(bucketName)
                .key(key)
                .build();

        ResponseBytes<GetObjectResponse> objectBytes = s3Client.getObjectAsBytes(objectRequest);
        byte[] byteArray = objectBytes.asByteArray();
        String text = new String(byteArray, StandardCharsets.UTF_8);
        System.out.println("Text output: " + text);
    }

    // Display some results from the output directory.
    public static void getOutputResults(S3Client s3Client, String bucketName) {
        System.out.println("Getting output results {bucketName}.");
        ListObjectsRequest listObjectsRequest = ListObjectsRequest.builder()
                .bucket(bucketName)
                .prefix("outputfiles/")
                .build();

        ListObjectsResponse response = s3Client.listObjects(listObjectsRequest);
        List<S3Object> s3Objects = response.contents();
        for (S3Object object : s3Objects) {
            readObject(s3Client, bucketName, object.key());
        }
    }

    // Check the status of a pipeline execution.
    public static void waitForPipelineExecution(SageMakerClient sageMakerClient, String executionArn)
            throws InterruptedException {
        String status;
        int index = 0;
        do {
            DescribePipelineExecutionRequest pipelineExecutionRequest = DescribePipelineExecutionRequest.builder()
                    .pipelineExecutionArn(executionArn)
                    .build();

            DescribePipelineExecutionResponse response = sageMakerClient
                    .describePipelineExecution(pipelineExecutionRequest);
            status = response.pipelineExecutionStatusAsString();
            System.out.println(index + ". The Status of the pipeline is " + status);
            TimeUnit.SECONDS.sleep(4);
            index++;
        } while ("Executing".equals(status));
        System.out.println("Pipeline finished with status " + status);
    }

    // Delete a SageMaker pipeline by name.
    public static void deletePipeline(SageMakerClient sageMakerClient, String pipelineName) {
        DeletePipelineRequest pipelineRequest = DeletePipelineRequest.builder()
                .pipelineName(pipelineName)
                .build();

        sageMakerClient.deletePipeline(pipelineRequest);
        System.out.println("*** Successfully deleted " + pipelineName);
    }

    // Create a pipeline from the example pipeline JSON.
    public static void setupPipeline(SageMakerClient sageMakerClient, String filePath, String roleArn,
            String functionArn, String pipelineName) {
        System.out.println("Setting up the pipeline.");
        JSONParser parser = new JSONParser();

        // Read JSON and get pipeline definition.
        try (FileReader reader = new FileReader(filePath)) {
            Object obj = parser.parse(reader);
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray stepsArray = (JSONArray) jsonObject.get("Steps");
            for (Object stepObj : stepsArray) {
                JSONObject step = (JSONObject) stepObj;
                if (step.containsKey("FunctionArn")) {
                    step.put("FunctionArn", functionArn);
                }
            }
            System.out.println(jsonObject);

            // Create the pipeline.
            CreatePipelineRequest pipelineRequest = CreatePipelineRequest.builder()
                    .pipelineDescription("Java SDK example pipeline")
                    .roleArn(roleArn)
                    .pipelineName(pipelineName)
                    .pipelineDefinition(jsonObject.toString())
                    .build();

            sageMakerClient.createPipeline(pipelineRequest);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        } catch (IOException | ParseException e) {
            throw new RuntimeException(e);
        }
    }

    // Start a pipeline run with job configurations.
    public static String executePipeline(SageMakerClient sageMakerClient, String bucketName, String queueUrl,
            String roleArn, String pipelineName) {
        System.out.println("Starting pipeline execution.");
        String inputBucketLocation = "s3://" + bucketName + "/samplefiles/latlongtest.csv";
        String output = "s3://" + bucketName + "/outputfiles/";
        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .setPrettyPrinting().create();

        // Set up all parameters required to start the pipeline.
        List<Parameter> parameters = new ArrayList<>();
        Parameter para1 = Parameter.builder()
                .name("parameter_execution_role")
                .value(roleArn)
                .build();

        Parameter para2 = Parameter.builder()
                .name("parameter_queue_url")
                .value(queueUrl)
                .build();

        String inputJSON = "{\n" +
                "  \"DataSourceConfig\": {\n" +
                "    \"S3Data\": {\n" +
                "      \"S3Uri\": \"s3://" + bucketName + "/samplefiles/latlongtest.csv\"\n" +
                "    },\n" +
                "    \"Type\": \"S3_DATA\"\n" +
                "  },\n" +
                "  \"DocumentType\": \"CSV\"\n" +
                "}";

        System.out.println(inputJSON);

        Parameter para3 = Parameter.builder()
                .name("parameter_vej_input_config")
                .value(inputJSON)
                .build();

        // Create an ExportVectorEnrichmentJobOutputConfig object.
        VectorEnrichmentJobS3Data jobS3Data = VectorEnrichmentJobS3Data.builder()
                .s3Uri(output)
                .build();

        ExportVectorEnrichmentJobOutputConfig outputConfig = ExportVectorEnrichmentJobOutputConfig.builder()
                .s3Data(jobS3Data)
                .build();

        String gson4 = gson.toJson(outputConfig);
        Parameter para4 = Parameter.builder()
                .name("parameter_vej_export_config")
                .value(gson4)
                .build();
        System.out.println("parameter_vej_export_config:" + gson.toJson(outputConfig));

        // Create a VectorEnrichmentJobConfig object.
        ReverseGeocodingConfig reverseGeocodingConfig = ReverseGeocodingConfig.builder()
                .xAttributeName("Longitude")
                .yAttributeName("Latitude")
                .build();

        VectorEnrichmentJobConfig jobConfig = VectorEnrichmentJobConfig.builder()
                .reverseGeocodingConfig(reverseGeocodingConfig)
                .build();

        String para5JSON = "{\"MapMatchingConfig\":null,\"ReverseGeocodingConfig\":{\"XAttributeName\":\"Longitude\",\"YAttributeName\":\"Latitude\"}}";
        Parameter para5 = Parameter.builder()
                .name("parameter_step_1_vej_config")
                .value(para5JSON)
                .build();

        System.out.println("parameter_step_1_vej_config:" + gson.toJson(jobConfig));
        parameters.add(para1);
        parameters.add(para2);
        parameters.add(para3);
        parameters.add(para4);
        parameters.add(para5);

        StartPipelineExecutionRequest pipelineExecutionRequest = StartPipelineExecutionRequest.builder()
                .pipelineExecutionDescription("Created using Java SDK")
                .pipelineExecutionDisplayName(pipelineName + "-example-execution")
                .pipelineParameters(parameters)
                .pipelineName(pipelineName)
                .build();

        StartPipelineExecutionResponse response = sageMakerClient.startPipelineExecution(pipelineExecutionRequest);
        return response.pipelineExecutionArn();
    }

    public static void deleteEventSourceMapping(LambdaClient lambdaClient) {
        DeleteEventSourceMappingRequest eventSourceMappingRequest = DeleteEventSourceMappingRequest.builder()
                .uuid(eventSourceMapping)
                .build();

        lambdaClient.deleteEventSourceMapping(eventSourceMappingRequest);
    }

    public static void deleteSagemakerRole(IamClient iam, String roleName) {
        String[] sageMakerRolePolicies = getSageMakerRolePolicies();
        try {
            for (String policy : sageMakerRolePolicies) {
                // First the policy needs to be detached.
                DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder()
                        .policyArn(policy)
                        .roleName(roleName)
                        .build();

                iam.detachRolePolicy(rolePolicyRequest);
            }

            // Delete the role.
            DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            iam.deleteRole(roleRequest);
            System.out.println("*** Successfully deleted " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteLambdaRole(IamClient iam, String roleName) {
        String[] lambdaRolePolicies = getLambdaRolePolicies();
        try {
            for (String policy : lambdaRolePolicies) {
                // First the policy needs to be detached.
                DetachRolePolicyRequest rolePolicyRequest = DetachRolePolicyRequest.builder()
                        .policyArn(policy)
                        .roleName(roleName)
                        .build();

                iam.detachRolePolicy(rolePolicyRequest);
            }

            // Delete the role.
            DeleteRoleRequest roleRequest = DeleteRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            iam.deleteRole(roleRequest);
            System.out.println("*** Successfully deleted " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Delete the specific AWS Lambda function.
    public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) {
        try {
            DeleteFunctionRequest request = DeleteFunctionRequest.builder()
                    .functionName(functionName)
                    .build();

            awsLambda.deleteFunction(request);
            System.out.println("*** " + functionName + " was deleted");

        } catch (LambdaException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    // Delete the specific S3 bucket.
    public static void deleteBucket(S3Client s3Client, String bucketName) {
        DeleteBucketRequest deleteBucketRequest = DeleteBucketRequest.builder()
                .bucket(bucketName)
                .build();
        s3Client.deleteBucket(deleteBucketRequest);
        System.out.println("*** " + bucketName + " was deleted.");
    }

    public static void listBucketObjects(S3Client s3, String bucketName) {
        try {
            ListObjectsRequest listObjects = ListObjectsRequest
                    .builder()
                    .bucket(bucketName)
                    .build();

            ListObjectsResponse res = s3.listObjects(listObjects);
            List<S3Object> objects = res.contents();
            for (S3Object myValue : objects) {
                System.out.print("\n The name of the key is " + myValue.key());
                deleteBucketObjects(s3, bucketName, myValue.key());
            }

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteBucketObjects(S3Client s3, String bucketName, String objectName) {
        ArrayList<ObjectIdentifier> toDelete = new ArrayList<>();
        toDelete.add(ObjectIdentifier.builder()
                .key(objectName)
                .build());
        try {
            DeleteObjectsRequest dor = DeleteObjectsRequest.builder()
                    .bucket(bucketName)
                    .delete(Delete.builder()
                            .objects(toDelete).build())
                    .build();

            s3.deleteObjects(dor);
            System.out.println("*** " + bucketName + " objects were deleted.");

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Delete the specific Amazon SQS queue.
    public static void deleteSQSQueue(SqsClient sqsClient, String queueName) {
        try {
            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                    .queueName(queueName)
                    .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();
            DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()
                    .queueUrl(queueUrl)
                    .build();

            sqsClient.deleteQueue(deleteQueueRequest);

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) {
        try {
            Map<String, String> metadata = new HashMap<>();
            metadata.put("x-amz-meta-myVal", "test");
            PutObjectRequest putOb = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key("samplefiles/" + objectKey)
                    .metadata(metadata)
                    .build();

            s3.putObject(putOb, RequestBody.fromFile(new File(objectPath)));
            System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName);

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void setupBucket(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);
        }
    }

    // Set up the SQS queue to use with the pipeline.
    public static String setupQueue(SqsClient sqsClient, LambdaClient lambdaClient, String queueName,
            String lambdaName) {
        System.out.println("Setting up queue named " + queueName);
        try {
            Map<QueueAttributeName, String> queueAtt = new HashMap<>();
            queueAtt.put(QueueAttributeName.DELAY_SECONDS, "5");
            queueAtt.put(QueueAttributeName.RECEIVE_MESSAGE_WAIT_TIME_SECONDS, "5");
            queueAtt.put(QueueAttributeName.VISIBILITY_TIMEOUT, "300");
            CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .attributes(queueAtt)
                    .build();

            sqsClient.createQueue(createQueueRequest);
            System.out.println("\nGet queue url");
            GetQueueUrlResponse getQueueUrlResponse = sqsClient
                    .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
            TimeUnit.SECONDS.sleep(15);

            connectLambda(sqsClient, lambdaClient, getQueueUrlResponse.queueUrl(), lambdaName);
            System.out.println("Queue ready with Url " + getQueueUrlResponse.queueUrl());
            return getQueueUrlResponse.queueUrl();

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    // Connect the queue to the Lambda function as an event source.
    public static void connectLambda(SqsClient sqsClient, LambdaClient lambdaClient, String queueUrl,
            String lambdaName) {
        System.out.println("Connecting the Lambda function and queue for the pipeline.");
        String queueArn = "";

        // Specify the attributes to retrieve.
        List<QueueAttributeName> atts = new ArrayList<>();
        atts.add(QueueAttributeName.QUEUE_ARN);
        GetQueueAttributesRequest attributesRequest = GetQueueAttributesRequest.builder()
                .queueUrl(queueUrl)
                .attributeNames(atts)
                .build();

        GetQueueAttributesResponse response = sqsClient.getQueueAttributes(attributesRequest);
        Map<String, String> queueAtts = response.attributesAsStrings();
        for (Map.Entry<String, String> queueAtt : queueAtts.entrySet()) {
            System.out.println("Key = " + queueAtt.getKey() + ", Value = " + queueAtt.getValue());
            queueArn = queueAtt.getValue();
        }

        CreateEventSourceMappingRequest eventSourceMappingRequest = CreateEventSourceMappingRequest.builder()
                .eventSourceArn(queueArn)
                .functionName(lambdaName)
                .build();

        CreateEventSourceMappingResponse response1 = lambdaClient.createEventSourceMapping(eventSourceMappingRequest);
        eventSourceMapping = response1.uuid();
        System.out.println("The mapping between the event source and Lambda function was successful");
    }

    // Create an AWS Lambda function.
    public static String createLambdaFunction(LambdaClient awsLambda, String functionName, String filePath, String role,
            String handler) {
        try {
            LambdaWaiter waiter = awsLambda.waiter();
            InputStream is = new FileInputStream(filePath);
            SdkBytes fileToUpload = SdkBytes.fromInputStream(is);
            FunctionCode code = FunctionCode.builder()
                    .zipFile(fileToUpload)
                    .build();

            CreateFunctionRequest functionRequest = CreateFunctionRequest.builder()
                    .functionName(functionName)
                    .description("SageMaker example function.")
                    .code(code)
                    .handler(handler)
                    .runtime(Runtime.JAVA11)
                    .timeout(200)
                    .memorySize(1024)
                    .role(role)
                    .build();

            // Create a Lambda function using a waiter.
            CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest);
            GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder()
                    .functionName(functionName)
                    .build();
            WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest);
            waiterResponse.matched().response().ifPresent(System.out::println);
            System.out.println("The function ARN is " + functionResponse.functionArn());
            return functionResponse.functionArn();

        } catch (LambdaException | FileNotFoundException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }

    public static String createSageMakerRole(IamClient iam, String roleName) {
        String[] sageMakerRolePolicies = getSageMakerRolePolicies();
        System.out.println("Creating a role to use with SageMaker.");
        String assumeRolePolicy = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "\"Service\": [" +
                "\"sagemaker.amazonaws.com\"," +
                "\"sagemaker-geospatial.amazonaws.com\"," +
                "\"lambda.amazonaws.com\"," +
                "\"s3.amazonaws.com\"" +
                "]" +
                "}," +
                "\"Action\": \"sts:AssumeRole\"" +
                "}]" +
                "}";

        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(roleName)
                    .assumeRolePolicyDocument(assumeRolePolicy)
                    .description("Created using the AWS SDK for Java")
                    .build();

            CreateRoleResponse roleResult = iam.createRole(request);

            // Attach the policies to the role.
            for (String policy : sageMakerRolePolicies) {
                AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                        .roleName(roleName)
                        .policyArn(policy)
                        .build();

                iam.attachRolePolicy(attachRequest);
            }

            // Allow time for the role to be ready.
            TimeUnit.SECONDS.sleep(15);
            System.out.println("Role ready with ARN " + roleResult.role().arn());
            return roleResult.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    private static String createLambdaRole(IamClient iam, String roleName) {
        String[] lambdaRolePolicies = getLambdaRolePolicies();
        String assumeRolePolicy = "{" +
                "\"Version\": \"2012-10-17\"," +
                "\"Statement\": [{" +
                "\"Effect\": \"Allow\"," +
                "\"Principal\": {" +
                "\"Service\": [" +
                "\"sagemaker.amazonaws.com\"," +
                "\"sagemaker-geospatial.amazonaws.com\"," +
                "\"lambda.amazonaws.com\"," +
                "\"s3.amazonaws.com\"" +
                "]" +
                "}," +
                "\"Action\": \"sts:AssumeRole\"" +
                "}]" +
                "}";

        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                    .roleName(roleName)
                    .assumeRolePolicyDocument(assumeRolePolicy)
                    .description("Created using the AWS SDK for Java")
                    .build();

            CreateRoleResponse roleResult = iam.createRole(request);

            // Attach the policies to the role.
            for (String policy : lambdaRolePolicies) {
                AttachRolePolicyRequest attachRequest = AttachRolePolicyRequest.builder()
                        .roleName(roleName)
                        .policyArn(policy)
                        .build();

                iam.attachRolePolicy(attachRequest);
            }

            // Allow time for the role to be ready.
            TimeUnit.SECONDS.sleep(15);
            System.out.println("Role ready with ARN " + roleResult.role().arn());
            return roleResult.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "";
    }

    public static String checkFunction(LambdaClient lambdaClient, String functionName, String filePath, String role,
            String handler) {
        System.out.println("Create an AWS Lambda function used in this workflow.");
        String functionArn;
        try {
            // Does this function already exist.
            GetFunctionRequest functionRequest = GetFunctionRequest.builder()
                    .functionName(functionName)
                    .build();

            GetFunctionResponse response = lambdaClient.getFunction(functionRequest);
            functionArn = response.configuration().functionArn();

        } catch (LambdaException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            functionArn = createLambdaFunction(lambdaClient, functionName, filePath, role, handler);
        }
        return functionArn;
    }

    // Check to see if the specific S3 bucket exists. If the S3 bucket exists, this
    // method returns true.
    public static boolean checkBucket(S3Client s3, String bucketName) {
        try {
            HeadBucketRequest headBucketRequest = HeadBucketRequest.builder()
                    .bucket(bucketName)
                    .build();

            s3.headBucket(headBucketRequest);
            System.out.println(bucketName + " exists");
            return true;

        } catch (S3Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
        return false;
    }

    // Checks to see if the Amazon SQS queue exists. If not, this method creates a
    // new queue
    // and returns the ARN value.
    public static String checkQueue(SqsClient sqsClient, LambdaClient lambdaClient, String queueName,
            String lambdaName) {
        System.out.println("Creating a queue for this use case.");
        String queueUrl;
        try {
            GetQueueUrlRequest request = GetQueueUrlRequest.builder()
                    .queueName(queueName)
                    .build();

            GetQueueUrlResponse response = sqsClient.getQueueUrl(request);
            queueUrl = response.queueUrl();
            System.out.println(queueUrl);

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            queueUrl = setupQueue(sqsClient, lambdaClient, queueName, lambdaName);
        }
        return queueUrl;
    }

    // Checks to see if the Lambda role exists. If not, this method creates it.
    public static String checkLambdaRole(IamClient iam, String roleName) {
        System.out.println("Creating a role to for AWS Lambda to use.");
        String roleArn;
        try {
            GetRoleRequest roleRequest = GetRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            GetRoleResponse response = iam.getRole(roleRequest);
            roleArn = response.role().arn();
            System.out.println(roleArn);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            roleArn = createLambdaRole(iam, roleName);
        }
        return roleArn;
    }

    // Checks to see if the SageMaker role exists. If not, this method creates it.
    public static String checkSageMakerRole(IamClient iam, String roleName) {
        System.out.println("Creating a role to for AWS SageMaker to use.");
        String roleArn;
        try {
            GetRoleRequest roleRequest = GetRoleRequest.builder()
                    .roleName(roleName)
                    .build();

            GetRoleResponse response = iam.getRole(roleRequest);
            roleArn = response.role().arn();
            System.out.println(roleArn);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            roleArn = createSageMakerRole(iam, roleName);
        }
        return roleArn;
    }

    private static String[] getSageMakerRolePolicies() {
        String[] sageMakerRolePolicies = new String[3];
        sageMakerRolePolicies[0] = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess";
        sageMakerRolePolicies[1] = "arn:aws:iam::aws:policy/" + "AmazonSageMakerGeospatialFullAccess";
        sageMakerRolePolicies[2] = "arn:aws:iam::aws:policy/AmazonSQSFullAccess";
        return sageMakerRolePolicies;
    }

    private static String[] getLambdaRolePolicies() {
        String[] lambdaRolePolicies = new String[5];
        lambdaRolePolicies[0] = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess";
        lambdaRolePolicies[1] = "arn:aws:iam::aws:policy/AmazonSQSFullAccess";
        lambdaRolePolicies[2] = "arn:aws:iam::aws:policy/service-role/" + "AmazonSageMakerGeospatialFullAccess";
        lambdaRolePolicies[3] = "arn:aws:iam::aws:policy/service-role/"
                + "AmazonSageMakerServiceCatalogProductsLambdaServiceRolePolicy";
        lambdaRolePolicies[4] = "arn:aws:iam::aws:policy/service-role/" + "AWSLambdaSQSQueueExecutionRole";
        return lambdaRolePolicies;
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreatePipeline](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/CreatePipeline)
  + [DeletePipeline](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/DeletePipeline)
  + [DescribePipelineExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/DescribePipelineExecution)
  + [StartPipelineExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/StartPipelineExecution)
  + [UpdatePipeline](https://docs.aws.amazon.com/goto/SdkForJavaV2/sagemaker-2017-07-24/UpdatePipeline)

# SDK for Java 2.x を使用した Secrets Manager の例
<a name="java_2_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_java_2_topic"></a>

次のコード例は、`GetSecretValue` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/secrets-manager#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest;
import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse;
import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException;

/**
 * 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
 *
 * We recommend that you cache your secret values by using client-side caching.
 *
 * Caching secrets improves speed and reduces your costs. For more information,
 * see the following documentation topic:
 *
 * https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html
 */
public class GetSecretValue {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <secretName>\s

                Where:
                    secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String secretName = args[0];
        Region region = Region.US_EAST_1;
        SecretsManagerClient secretsClient = SecretsManagerClient.builder()
                .region(region)
                .build();

        getValue(secretsClient, secretName);
        secretsClient.close();
    }

    public static void getValue(SecretsManagerClient secretsClient, String secretName) {
        try {
            GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                    .secretId(secretName)
                    .build();

            GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest);
            String secret = valueResponse.secretString();
            System.out.println(secret);

        } catch (SecretsManagerException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetSecretValue](https://docs.aws.amazon.com/goto/SdkForJavaV2/secretsmanager-2017-10-17/GetSecretValue)」を参照してください。

# SDK for Java 2.x を使用する Amazon SES の例
<a name="java_2_ses_code_examples"></a>

次のコード例は、Amazon SES AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `ListIdentities`
<a name="ses_ListIdentities_java_2_topic"></a>

次のコード例は、`ListIdentities` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.ListIdentitiesResponse;
import software.amazon.awssdk.services.ses.model.SesException;
import java.io.IOException;
import java.util.List;

/**
 * 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 ListIdentities {

    public static void main(String[] args) throws IOException {
        Region region = Region.US_WEST_2;
        SesClient client = SesClient.builder()
                .region(region)
                .build();

        listSESIdentities(client);
    }

    public static void listSESIdentities(SesClient client) {
        try {
            ListIdentitiesResponse identitiesResponse = client.listIdentities();
            List<String> identities = identitiesResponse.identities();
            for (String identity : identities) {
                System.out.println("The identity is " + identity);
            }

        } catch (SesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[ListIdentities](https://docs.aws.amazon.com/goto/SdkForJavaV2/email-2010-12-01/ListIdentities)」を参照してください。

### `ListTemplates`
<a name="ses_ListTemplates_java_2_topic"></a>

次のコード例は、`ListTemplates` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sesv2.SesV2Client;
import software.amazon.awssdk.services.sesv2.model.ListEmailTemplatesRequest;
import software.amazon.awssdk.services.sesv2.model.ListEmailTemplatesResponse;
import software.amazon.awssdk.services.sesv2.model.SesV2Exception;

public class ListTemplates {

    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        SesV2Client sesv2Client = SesV2Client.builder()
                .region(region)
                .build();

        listAllTemplates(sesv2Client);
    }

    public static void listAllTemplates(SesV2Client sesv2Client) {
        try {
            ListEmailTemplatesRequest templatesRequest = ListEmailTemplatesRequest.builder()
                    .pageSize(1)
                    .build();

            ListEmailTemplatesResponse response = sesv2Client.listEmailTemplates(templatesRequest);
            response.templatesMetadata()
                    .forEach(template -> System.out.println("Template name: " + template.templateName()));

        } catch (SesV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListTemplates](https://docs.aws.amazon.com/goto/SdkForJavaV2/email-2010-12-01/ListTemplates)」を参照してください。

### `SendEmail`
<a name="ses_SendEmail_java_2_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
import software.amazon.awssdk.services.ses.model.Content;
import software.amazon.awssdk.services.ses.model.Destination;
import software.amazon.awssdk.services.ses.model.Message;
import software.amazon.awssdk.services.ses.model.Body;
import software.amazon.awssdk.services.ses.model.SendEmailRequest;
import software.amazon.awssdk.services.ses.model.SesException;

import javax.mail.MessagingException;

/**
 * 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 SendMessageEmailRequest {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <sender> <recipient> <subject>\s

                Where:
                    sender - An email address that represents the sender.\s
                    recipient -  An email address that represents the recipient.\s
                    subject - The  subject line.\s
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String sender = args[0];
        String recipient = args[1];
        String subject = args[2];

        Region region = Region.US_EAST_1;
        SesClient client = SesClient.builder()
                .region(region)
                .build();

        // The HTML body of the email.
        String bodyHTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
                + "<p> See the list of customers.</p>" + "</body>" + "</html>";

        try {
            send(client, sender, recipient, subject, bodyHTML);
            client.close();
            System.out.println("Done");

        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static void send(SesClient client,
            String sender,
            String recipient,
            String subject,
            String bodyHTML) throws MessagingException {

        Destination destination = Destination.builder()
                .toAddresses(recipient)
                .build();

        Content content = Content.builder()
                .data(bodyHTML)
                .build();

        Content sub = Content.builder()
                .data(subject)
                .build();

        Body body = Body.builder()
                .html(content)
                .build();

        Message msg = Message.builder()
                .subject(sub)
                .body(body)
                .build();

        SendEmailRequest emailRequest = SendEmailRequest.builder()
                .destination(destination)
                .message(msg)
                .source(sender)
                .build();

        try {
            System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
            client.sendEmail(emailRequest);

        } catch (SesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ses.SesClient;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.util.ByteArrayDataSource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.Properties;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.ses.model.SendRawEmailRequest;
import software.amazon.awssdk.services.ses.model.RawMessage;
import software.amazon.awssdk.services.ses.model.SesException;

/**
 * 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 SendMessageAttachment {
    public static void main(String[] args) throws IOException {
        final String usage = """

                Usage:
                    <sender> <recipient> <subject> <fileLocation>\s

                Where:
                    sender - An email address that represents the sender.\s
                    recipient -  An email address that represents the recipient.\s
                    subject - The  subject line.\s
                    fileLocation - The location of a Microsoft Excel file to use as an attachment (C:/AWS/customers.xls).\s
                """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String sender = args[0];
        String recipient = args[1];
        String subject = args[2];
        String fileLocation = args[3];

        // The email body for recipients with non-HTML email clients.
        String bodyText = "Hello,\r\n" + "Please see the attached file for a list "
                + "of customers to contact.";

        // The HTML body of the email.
        String bodyHTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
                + "<p>Please see the attached file for a " + "list of customers to contact.</p>" + "</body>"
                + "</html>";

        Region region = Region.US_WEST_2;
        SesClient client = SesClient.builder()
                .region(region)
                .build();

        try {
            sendemailAttachment(client, sender, recipient, subject, bodyText, bodyHTML, fileLocation);
            client.close();
            System.out.println("Done");

        } catch (IOException | MessagingException e) {
            e.printStackTrace();
        }
    }

    public static void sendemailAttachment(SesClient client,
            String sender,
            String recipient,
            String subject,
            String bodyText,
            String bodyHTML,
            String fileLocation) throws AddressException, MessagingException, IOException {

        java.io.File theFile = new java.io.File(fileLocation);
        byte[] fileContent = Files.readAllBytes(theFile.toPath());

        Session session = Session.getDefaultInstance(new Properties());

        // Create a new MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Add subject, from and to lines.
        message.setSubject(subject, "UTF-8");
        message.setFrom(new InternetAddress(sender));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

        // Create a multipart/alternative child container.
        MimeMultipart msgBody = new MimeMultipart("alternative");

        // Create a wrapper for the HTML and text parts.
        MimeBodyPart wrap = new MimeBodyPart();

        // Define the text part.
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent(bodyText, "text/plain; charset=UTF-8");

        // Define the HTML part.
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");

        // Add the text and HTML parts to the child container.
        msgBody.addBodyPart(textPart);
        msgBody.addBodyPart(htmlPart);

        // Add the child container to the wrapper object.
        wrap.setContent(msgBody);

        // Create a multipart/mixed parent container.
        MimeMultipart msg = new MimeMultipart("mixed");

        // Add the parent container to the message.
        message.setContent(msg);
        msg.addBodyPart(wrap);

        // Define the attachment.
        MimeBodyPart att = new MimeBodyPart();
        DataSource fds = new ByteArrayDataSource(fileContent,
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        att.setDataHandler(new DataHandler(fds));

        String reportName = "WorkReport.xls";
        att.setFileName(reportName);

        // Add the attachment to the message.
        msg.addBodyPart(att);

        try {
            System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            message.writeTo(outputStream);

            ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

            byte[] arr = new byte[buf.remaining()];
            buf.get(arr);

            SdkBytes data = SdkBytes.fromByteArray(arr);
            RawMessage rawMessage = RawMessage.builder()
                    .data(data)
                    .build();

            SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
                    .rawMessage(rawMessage)
                    .build();

            client.sendRawEmail(rawEmailRequest);

        } catch (SesException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        System.out.println("Email sent using SesClient with attachment");
    }
}
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[SendEmail](https://docs.aws.amazon.com/goto/SdkForJavaV2/email-2010-12-01/SendEmail)」を参照してください。

### `SendTemplatedEmail`
<a name="ses_SendTemplatedEmail_java_2_topic"></a>

次のコード例は、`SendTemplatedEmail` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sesv2.model.Destination;
import software.amazon.awssdk.services.sesv2.model.EmailContent;
import software.amazon.awssdk.services.sesv2.model.SendEmailRequest;
import software.amazon.awssdk.services.sesv2.model.SesV2Exception;
import software.amazon.awssdk.services.sesv2.SesV2Client;
import software.amazon.awssdk.services.sesv2.model.Template;

/**
 * Before running this AWS SDK for Java (v2) 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
 *
 * Also, make sure that you create a template. See the following documentation
 * topic:
 *
 * https://docs.aws.amazon.com/ses/latest/dg/send-personalized-email-api.html
 */

public class SendEmailTemplate {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <template> <sender> <recipient>\s

                Where:
                    template - The name of the email template.
                    sender - An email address that represents the sender.\s
                    recipient - An email address that represents the recipient.\s
                """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String templateName = args[0];
        String sender = args[1];
        String recipient = args[2];
        Region region = Region.US_EAST_1;
        SesV2Client sesv2Client = SesV2Client.builder()
                .region(region)
                .build();

        send(sesv2Client, sender, recipient, templateName);
    }

    public static void send(SesV2Client client, String sender, String recipient, String templateName) {
        Destination destination = Destination.builder()
                .toAddresses(recipient)
                .build();

        /*
         * Specify both name and favorite animal (favoriteanimal) in your code when
         * defining the Template object.
         * If you don't specify all the variables in the template, Amazon SES doesn't
         * send the email.
         */
        Template myTemplate = Template.builder()
                .templateName(templateName)
                .templateData("{\n" +
                        "  \"name\": \"Jason\"\n," +
                        "  \"favoriteanimal\": \"Cat\"\n" +
                        "}")
                .build();

        EmailContent emailContent = EmailContent.builder()
                .template(myTemplate)
                .build();

        SendEmailRequest emailRequest = SendEmailRequest.builder()
                .destination(destination)
                .content(emailContent)
                .fromEmailAddress(sender)
                .build();

        try {
            System.out.println("Attempting to send an email based on a template using the AWS SDK for Java (v2)...");
            client.sendEmail(emailRequest);
            System.out.println("email based on a template was sent");

        } catch (SesV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SendTemplatedEmail](https://docs.aws.amazon.com/goto/SdkForJavaV2/email-2010-12-01/SendTemplatedEmail)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_java_2_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon DynamoDB API を使用して、DynamoDB 作業データを追跡する動的ウェブアプリケーションを作成する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_dynamodb_web_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### Amazon Redshift データ追跡用のウェブアプリケーションの作成
<a name="cross_RedshiftDataTracker_java_2_topic"></a>

次のコード例は、Amazon Redshift データベースを使用して、作業項目を追跡してレポートするウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon Redshift データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Redshift サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/CreatingSpringRedshiftRest) にある詳しい事例を参照してください。  

**この例で使用されているサービス**
+ Amazon Redshift
+ Amazon SES

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_java_2_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_Spring_RDS_Rest) にある完全な例を参照してください。  
 完全なソースコードと JDBC API を使用する例のセットアップと実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/Creating_rds_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

### 画像内の PPE を検出する
<a name="cross_RekognitionPhotoAnalyzerPPE_java_2_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内の個人用防護具 (PPE) を検出するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 個人用保護具を使用してイメージを検出する AWS Lambda 関数を作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_ppe) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_java_2_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用して、Amazon Rekognition を使用し、　Amazon Simple Storage Service (Amazon S3) バケットにあるイメージ内でカテゴリ別にオブジェクトを識別するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_photo_analyzer_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_java_2_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用し、Amazon Simple Storage Service (Amazon S3) バケットにあるビデオ内で顔やオブジェクトを検出するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/video_analyzer_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### Step Functions を使用して Lambda 関数を呼び出す
<a name="cross_ServerlessWorkflows_java_2_topic"></a>

次のコード例は、 AWS Lambda 関数を順番に呼び出す AWS Step Functions ステートマシンを作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Step Functions と を使用して AWS サーバーレスワークフローを作成する方法を示します AWS SDK for Java 2.x。各ワークフローステップは、 AWS Lambda 関数を使用して実装されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_workflows_stepfunctions) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SES
+ ステップ関数

# SDK for Java 2.x を使用する Amazon SES API v2 の例
<a name="java_2_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateContact`
<a name="sesv2_CreateContact_java_2_topic"></a>

次のコード例は、`CreateContact` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
      try {
        // Create a new contact with the provided email address in the
        CreateContactRequest contactRequest = CreateContactRequest.builder()
            .contactListName(CONTACT_LIST_NAME)
            .emailAddress(emailAddress)
            .build();

        sesClient.createContact(contactRequest);
        contacts.add(emailAddress);

        System.out.println("Contact created: " + emailAddress);

        // Send a welcome email to the new contact
        String welcomeHtml = Files.readString(Paths.get("resources/coupon_newsletter/welcome.html"));
        String welcomeText = Files.readString(Paths.get("resources/coupon_newsletter/welcome.txt"));

        SendEmailRequest welcomeEmailRequest = SendEmailRequest.builder()
            .fromEmailAddress(this.verifiedEmail)
            .destination(Destination.builder().toAddresses(emailAddress).build())
            .content(EmailContent.builder()
                .simple(
                    Message.builder()
                        .subject(Content.builder().data("Welcome to the Weekly Coupons Newsletter").build())
                        .body(Body.builder()
                            .text(Content.builder().data(welcomeText).build())
                            .html(Content.builder().data(welcomeHtml).build())
                            .build())
                        .build())
                .build())
            .build();
        SendEmailResponse welcomeEmailResponse = sesClient.sendEmail(welcomeEmailRequest);
        System.out.println("Welcome email sent: " + welcomeEmailResponse.messageId());
      } catch (AlreadyExistsException e) {
        // If the contact already exists, skip this step for that contact and proceed
        // with the next contact
        System.out.println("Contact already exists, skipping creation...");
      } catch (Exception e) {
        System.err.println("Error occurred while processing email address " + emailAddress + ": " + e.getMessage());
        throw e;
      }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateContact](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateContact)」を参照してください。

### `CreateContactList`
<a name="sesv2_CreateContactList_java_2_topic"></a>

次のコード例は、`CreateContactList` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
    try {
      // 2. Create a contact list
      String contactListName = CONTACT_LIST_NAME;
      CreateContactListRequest createContactListRequest = CreateContactListRequest.builder()
          .contactListName(contactListName)
          .build();
      sesClient.createContactList(createContactListRequest);
      System.out.println("Contact list created: " + contactListName);
    } catch (AlreadyExistsException e) {
      System.out.println("Contact list already exists, skipping creation: weekly-coupons-newsletter");
    } catch (LimitExceededException e) {
      System.err.println("Limit for contact lists has been exceeded.");
      throw e;
    } catch (SesV2Exception e) {
      System.err.println("Error creating contact list: " + e.getMessage());
      throw e;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateContactList](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateContactList)」を参照してください。

### `CreateEmailIdentity`
<a name="sesv2_CreateEmailIdentity_java_2_topic"></a>

次のコード例は、`CreateEmailIdentity` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
    try {
      CreateEmailIdentityRequest createEmailIdentityRequest = CreateEmailIdentityRequest.builder()
          .emailIdentity(verifiedEmail)
          .build();
      sesClient.createEmailIdentity(createEmailIdentityRequest);
      System.out.println("Email identity created: " + verifiedEmail);
    } catch (AlreadyExistsException e) {
      System.out.println("Email identity already exists, skipping creation: " + verifiedEmail);
    } catch (NotFoundException e) {
      System.err.println("The provided email address is not verified: " + verifiedEmail);
      throw e;
    } catch (LimitExceededException e) {
      System.err
          .println("You have reached the limit for email identities. Please remove some identities and try again.");
      throw e;
    } catch (SesV2Exception e) {
      System.err.println("Error creating email identity: " + e.getMessage());
      throw e;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateEmailIdentity](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateEmailIdentity)」を参照してください。

### `CreateEmailTemplate`
<a name="sesv2_CreateEmailTemplate_java_2_topic"></a>

次のコード例は、`CreateEmailTemplate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
    try {
      // Create an email template named "weekly-coupons"
      String newsletterHtml = loadFile("resources/coupon_newsletter/coupon-newsletter.html");
      String newsletterText = loadFile("resources/coupon_newsletter/coupon-newsletter.txt");

      CreateEmailTemplateRequest templateRequest = CreateEmailTemplateRequest.builder()
          .templateName(TEMPLATE_NAME)
          .templateContent(EmailTemplateContent.builder()
              .subject("Weekly Coupons Newsletter")
              .html(newsletterHtml)
              .text(newsletterText)
              .build())
          .build();

      sesClient.createEmailTemplate(templateRequest);

      System.out.println("Email template created: " + TEMPLATE_NAME);
    } catch (AlreadyExistsException e) {
      // If the template already exists, skip this step and proceed with the next
      // operation
      System.out.println("Email template already exists, skipping creation...");
    } catch (LimitExceededException e) {
      // If the limit for email templates is exceeded, fail the workflow and inform
      // the user
      System.err.println("You have reached the limit for email templates. Please remove some templates and try again.");
      throw e;
    } catch (Exception e) {
      System.err.println("Error occurred while creating email template: " + e.getMessage());
      throw e;
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[CreateEmailTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateEmailTemplate)」を参照してください。

### `DeleteContactList`
<a name="sesv2_DeleteContactList_java_2_topic"></a>

次のコード例は、`DeleteContactList` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
    try {
      // Delete the contact list
      DeleteContactListRequest deleteContactListRequest = DeleteContactListRequest.builder()
          .contactListName(CONTACT_LIST_NAME)
          .build();

      sesClient.deleteContactList(deleteContactListRequest);

      System.out.println("Contact list deleted: " + CONTACT_LIST_NAME);
    } catch (NotFoundException e) {
      // If the contact list does not exist, log the error and proceed
      System.out.println("Contact list not found. Skipping deletion...");
    } catch (Exception e) {
      System.err.println("Error occurred while deleting the contact list: " + e.getMessage());
      e.printStackTrace();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteContactList](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/DeleteContactList)」を参照してください。

### `DeleteEmailIdentity`
<a name="sesv2_DeleteEmailIdentity_java_2_topic"></a>

次のコード例は、`DeleteEmailIdentity` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
      try {
        // Delete the email identity
        DeleteEmailIdentityRequest deleteIdentityRequest = DeleteEmailIdentityRequest.builder()
            .emailIdentity(this.verifiedEmail)
            .build();

        sesClient.deleteEmailIdentity(deleteIdentityRequest);

        System.out.println("Email identity deleted: " + this.verifiedEmail);
      } catch (NotFoundException e) {
        // If the email identity does not exist, log the error and proceed
        System.out.println("Email identity not found. Skipping deletion...");
      } catch (Exception e) {
        System.err.println("Error occurred while deleting the email identity: " + e.getMessage());
        e.printStackTrace();
      }
    } else {
      System.out.println("Skipping email identity deletion.");
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteEmailIdentity](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/DeleteEmailIdentity)」を参照してください。

### `DeleteEmailTemplate`
<a name="sesv2_DeleteEmailTemplate_java_2_topic"></a>

次のコード例は、`DeleteEmailTemplate` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
    try {
      // Delete the template
      DeleteEmailTemplateRequest deleteTemplateRequest = DeleteEmailTemplateRequest.builder()
          .templateName(TEMPLATE_NAME)
          .build();

      sesClient.deleteEmailTemplate(deleteTemplateRequest);

      System.out.println("Email template deleted: " + TEMPLATE_NAME);
    } catch (NotFoundException e) {
      // If the email template does not exist, log the error and proceed
      System.out.println("Email template not found. Skipping deletion...");
    } catch (Exception e) {
      System.err.println("Error occurred while deleting the email template: " + e.getMessage());
      e.printStackTrace();
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DeleteEmailTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/DeleteEmailTemplate)」を参照してください。

### `ListContacts`
<a name="sesv2_ListContacts_java_2_topic"></a>

次のコード例は、`ListContacts` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
      ListContactsRequest contactListRequest = ListContactsRequest.builder()
          .contactListName(CONTACT_LIST_NAME)
          .build();

      List<String> contactEmails;
      try {
        ListContactsResponse contactListResponse = sesClient.listContacts(contactListRequest);

        contactEmails = contactListResponse.contacts().stream()
            .map(Contact::emailAddress)
            .toList();
      } catch (Exception e) {
        // TODO: Remove when listContacts's GET body issue is resolved.
        contactEmails = this.contacts;
      }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListContacts](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/ListContacts)」を参照してください。

### `SendEmail`
<a name="sesv2_SendEmail_java_2_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。
メッセージを送信します。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sesv2.model.Body;
import software.amazon.awssdk.services.sesv2.model.Content;
import software.amazon.awssdk.services.sesv2.model.Destination;
import software.amazon.awssdk.services.sesv2.model.EmailContent;
import software.amazon.awssdk.services.sesv2.model.Message;
import software.amazon.awssdk.services.sesv2.model.SendEmailRequest;
import software.amazon.awssdk.services.sesv2.model.SesV2Exception;
import software.amazon.awssdk.services.sesv2.SesV2Client;

/**
 * Before running this AWS SDK for Java (v2) example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class SendEmail {
    public static void main(String[] args) {
        final String usage = """
                             
                             Usage:
                                 <sender> <recipient> <subject>\s
                             
                             Where:
                                 sender - An email address that represents the sender.\s
                                 recipient - An email address that represents the recipient.\s
                                 subject - The subject line.\s
                             """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String sender = args[0];
        String recipient = args[1];
        String subject = args[2];

        Region region = Region.US_EAST_1;
        SesV2Client sesv2Client = SesV2Client.builder()
                .region(region)
                .build();

        // The HTML body of the email.
        String bodyHTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
                + "<p> See the list of customers.</p>" + "</body>" + "</html>";

        send(sesv2Client, sender, recipient, subject, bodyHTML);
    }

    public static void send(SesV2Client client,
                            String sender,
                            String recipient,
                            String subject,
                            String bodyHTML) {

        Destination destination = Destination.builder()
                .toAddresses(recipient)
                .build();

        Content content = Content.builder()
                .data(bodyHTML)
                .build();

        Content sub = Content.builder()
                .data(subject)
                .build();

        Body body = Body.builder()
                .html(content)
                .build();

        Message msg = Message.builder()
                .subject(sub)
                .body(body)
                .build();

        EmailContent emailContent = EmailContent.builder()
                .simple(msg)
                .build();

        SendEmailRequest emailRequest = SendEmailRequest.builder()
                .destination(destination)
                .content(emailContent)
                .fromEmailAddress(sender)
                .build();

        try {
            System.out.println("Attempting to send an email through Amazon SES "
                    + "using the AWS SDK for Java...");
            client.sendEmail(emailRequest);
            System.out.println("email was sent");

        } catch (SesV2Exception e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
テンプレートを使用してメッセージを送信します。  

```
      String coupons = Files.readString(Paths.get("resources/coupon_newsletter/sample_coupons.json"));
      for (String emailAddress : contactEmails) {
        SendEmailRequest newsletterRequest = SendEmailRequest.builder()
            .destination(Destination.builder().toAddresses(emailAddress).build())
            .content(EmailContent.builder()
                .template(Template.builder()
                    .templateName(TEMPLATE_NAME)
                    .templateData(coupons)
                    .build())
                .build())
            .fromEmailAddress(this.verifiedEmail)
            .listManagementOptions(ListManagementOptions.builder()
                .contactListName(CONTACT_LIST_NAME)
                .build())
            .build();
        SendEmailResponse newsletterResponse = sesClient.sendEmail(newsletterRequest);
        System.out.println("Newsletter sent to " + emailAddress + ": " + newsletterResponse.messageId());
      }
```
ヘッダー情報を含むメッセージを送信します。  

```
public class SendwithHeader {

    public static void main(String[] args) {
        final String usage = """
                             
            Usage:
                <sender> <recipient> <subject>\s
                             
            Where:
                sender - An email address that represents the sender.\s
                recipient - An email address that represents the recipient.\s
                subject - The subject line.\s
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String sender = args[0];
        String recipient = args[1];
        String subject = args[2];
        Region region = Region.US_EAST_1;
        SesV2Client sesv2Client = SesV2Client.builder()
                .region(region)
                .build();

        String bodyHTML = """
                <html>
                    <head></head>
                    <body>
                        <h1>Hello!</h1>
                        <p>See the list of customers.</p>
                    </body>
                </html>
                """;

        sendWithHeader(sesv2Client, sender, recipient, subject, bodyHTML);
        sesv2Client.close();
    }

    /**
     * Sends an email using the AWS SES V2 client.
     *
     * @param sesv2Client the SES V2 client to use for sending the email
     * @param sender the email address of the sender
     * @param recipient the email address of the recipient
     * @param subject the subject of the email
     * @param bodyHTML the HTML content of the email body
     */
    public static void sendWithHeader(SesV2Client sesv2Client,
                                      String sender,
                                      String recipient,
                                      String subject,
                                      String bodyHTML) {
        EmailContent emailContent = EmailContent.builder()
                .simple(Message.builder()
                        .body(b -> b.html(c -> c.charset(UTF_8.name()).data(bodyHTML))
                                .text(c -> c.charset(UTF_8.name()).data(bodyHTML)))
                        .subject(c -> c.charset(UTF_8.name()).data(subject))
                        .headers(List.of(
                                MessageHeader.builder()
                                        .name("List-Unsubscribe")
                                        .value("<https://nutrition.co/?address=x&topic=x>, <mailto:unsubscribe@nutrition.co?subject=TopicUnsubscribe>")
                                        .build(),
                                MessageHeader.builder()
                                        .name("List-Unsubscribe-Post")
                                        .value("List-Unsubscribe=One-Click")
                                        .build()))
                        .build())
                .build();

        SendEmailRequest request = SendEmailRequest.builder()
                .fromEmailAddress(sender)
                .destination(d -> d.toAddresses(recipient))
                .content(emailContent)
                .build();

        try {
            SendEmailResponse response = sesv2Client.sendEmail(request);
            System.out.println("Email sent! Message ID: " + response.messageId());
        } catch (SesV2Exception e) {
            System.err.println("Failed to send email: " + e.awsErrorDetails().errorMessage());
            throw new RuntimeException(e);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SendEmail](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/SendEmail)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ニュースレターのシナリオ
<a name="sesv2_NewsletterWorkflow_java_2_topic"></a>

以下のコード例は、Amazon SES API v2 のニュースレターのシナリオを実行する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
    try {
      // 2. Create a contact list
      String contactListName = CONTACT_LIST_NAME;
      CreateContactListRequest createContactListRequest = CreateContactListRequest.builder()
          .contactListName(contactListName)
          .build();
      sesClient.createContactList(createContactListRequest);
      System.out.println("Contact list created: " + contactListName);
    } catch (AlreadyExistsException e) {
      System.out.println("Contact list already exists, skipping creation: weekly-coupons-newsletter");
    } catch (LimitExceededException e) {
      System.err.println("Limit for contact lists has been exceeded.");
      throw e;
    } catch (SesV2Exception e) {
      System.err.println("Error creating contact list: " + e.getMessage());
      throw e;
    }

      try {
        // Create a new contact with the provided email address in the
        CreateContactRequest contactRequest = CreateContactRequest.builder()
            .contactListName(CONTACT_LIST_NAME)
            .emailAddress(emailAddress)
            .build();

        sesClient.createContact(contactRequest);
        contacts.add(emailAddress);

        System.out.println("Contact created: " + emailAddress);

        // Send a welcome email to the new contact
        String welcomeHtml = Files.readString(Paths.get("resources/coupon_newsletter/welcome.html"));
        String welcomeText = Files.readString(Paths.get("resources/coupon_newsletter/welcome.txt"));

        SendEmailRequest welcomeEmailRequest = SendEmailRequest.builder()
            .fromEmailAddress(this.verifiedEmail)
            .destination(Destination.builder().toAddresses(emailAddress).build())
            .content(EmailContent.builder()
                .simple(
                    Message.builder()
                        .subject(Content.builder().data("Welcome to the Weekly Coupons Newsletter").build())
                        .body(Body.builder()
                            .text(Content.builder().data(welcomeText).build())
                            .html(Content.builder().data(welcomeHtml).build())
                            .build())
                        .build())
                .build())
            .build();
        SendEmailResponse welcomeEmailResponse = sesClient.sendEmail(welcomeEmailRequest);
        System.out.println("Welcome email sent: " + welcomeEmailResponse.messageId());
      } catch (AlreadyExistsException e) {
        // If the contact already exists, skip this step for that contact and proceed
        // with the next contact
        System.out.println("Contact already exists, skipping creation...");
      } catch (Exception e) {
        System.err.println("Error occurred while processing email address " + emailAddress + ": " + e.getMessage());
        throw e;
      }
    }

      ListContactsRequest contactListRequest = ListContactsRequest.builder()
          .contactListName(CONTACT_LIST_NAME)
          .build();

      List<String> contactEmails;
      try {
        ListContactsResponse contactListResponse = sesClient.listContacts(contactListRequest);

        contactEmails = contactListResponse.contacts().stream()
            .map(Contact::emailAddress)
            .toList();
      } catch (Exception e) {
        // TODO: Remove when listContacts's GET body issue is resolved.
        contactEmails = this.contacts;
      }


      String coupons = Files.readString(Paths.get("resources/coupon_newsletter/sample_coupons.json"));
      for (String emailAddress : contactEmails) {
        SendEmailRequest newsletterRequest = SendEmailRequest.builder()
            .destination(Destination.builder().toAddresses(emailAddress).build())
            .content(EmailContent.builder()
                .template(Template.builder()
                    .templateName(TEMPLATE_NAME)
                    .templateData(coupons)
                    .build())
                .build())
            .fromEmailAddress(this.verifiedEmail)
            .listManagementOptions(ListManagementOptions.builder()
                .contactListName(CONTACT_LIST_NAME)
                .build())
            .build();
        SendEmailResponse newsletterResponse = sesClient.sendEmail(newsletterRequest);
        System.out.println("Newsletter sent to " + emailAddress + ": " + newsletterResponse.messageId());
      }

    try {
      CreateEmailIdentityRequest createEmailIdentityRequest = CreateEmailIdentityRequest.builder()
          .emailIdentity(verifiedEmail)
          .build();
      sesClient.createEmailIdentity(createEmailIdentityRequest);
      System.out.println("Email identity created: " + verifiedEmail);
    } catch (AlreadyExistsException e) {
      System.out.println("Email identity already exists, skipping creation: " + verifiedEmail);
    } catch (NotFoundException e) {
      System.err.println("The provided email address is not verified: " + verifiedEmail);
      throw e;
    } catch (LimitExceededException e) {
      System.err
          .println("You have reached the limit for email identities. Please remove some identities and try again.");
      throw e;
    } catch (SesV2Exception e) {
      System.err.println("Error creating email identity: " + e.getMessage());
      throw e;
    }

    try {
      // Create an email template named "weekly-coupons"
      String newsletterHtml = loadFile("resources/coupon_newsletter/coupon-newsletter.html");
      String newsletterText = loadFile("resources/coupon_newsletter/coupon-newsletter.txt");

      CreateEmailTemplateRequest templateRequest = CreateEmailTemplateRequest.builder()
          .templateName(TEMPLATE_NAME)
          .templateContent(EmailTemplateContent.builder()
              .subject("Weekly Coupons Newsletter")
              .html(newsletterHtml)
              .text(newsletterText)
              .build())
          .build();

      sesClient.createEmailTemplate(templateRequest);

      System.out.println("Email template created: " + TEMPLATE_NAME);
    } catch (AlreadyExistsException e) {
      // If the template already exists, skip this step and proceed with the next
      // operation
      System.out.println("Email template already exists, skipping creation...");
    } catch (LimitExceededException e) {
      // If the limit for email templates is exceeded, fail the workflow and inform
      // the user
      System.err.println("You have reached the limit for email templates. Please remove some templates and try again.");
      throw e;
    } catch (Exception e) {
      System.err.println("Error occurred while creating email template: " + e.getMessage());
      throw e;
    }

    try {
      // Delete the contact list
      DeleteContactListRequest deleteContactListRequest = DeleteContactListRequest.builder()
          .contactListName(CONTACT_LIST_NAME)
          .build();

      sesClient.deleteContactList(deleteContactListRequest);

      System.out.println("Contact list deleted: " + CONTACT_LIST_NAME);
    } catch (NotFoundException e) {
      // If the contact list does not exist, log the error and proceed
      System.out.println("Contact list not found. Skipping deletion...");
    } catch (Exception e) {
      System.err.println("Error occurred while deleting the contact list: " + e.getMessage());
      e.printStackTrace();
    }

      try {
        // Delete the email identity
        DeleteEmailIdentityRequest deleteIdentityRequest = DeleteEmailIdentityRequest.builder()
            .emailIdentity(this.verifiedEmail)
            .build();

        sesClient.deleteEmailIdentity(deleteIdentityRequest);

        System.out.println("Email identity deleted: " + this.verifiedEmail);
      } catch (NotFoundException e) {
        // If the email identity does not exist, log the error and proceed
        System.out.println("Email identity not found. Skipping deletion...");
      } catch (Exception e) {
        System.err.println("Error occurred while deleting the email identity: " + e.getMessage());
        e.printStackTrace();
      }
    } else {
      System.out.println("Skipping email identity deletion.");
    }

    try {
      // Delete the template
      DeleteEmailTemplateRequest deleteTemplateRequest = DeleteEmailTemplateRequest.builder()
          .templateName(TEMPLATE_NAME)
          .build();

      sesClient.deleteEmailTemplate(deleteTemplateRequest);

      System.out.println("Email template deleted: " + TEMPLATE_NAME);
    } catch (NotFoundException e) {
      // If the email template does not exist, log the error and proceed
      System.out.println("Email template not found. Skipping deletion...");
    } catch (Exception e) {
      System.err.println("Error occurred while deleting the email template: " + e.getMessage());
      e.printStackTrace();
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateContact](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateContact)
  + [CreateContactList](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateContactList)
  + [CreateEmailIdentity](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateEmailIdentity)
  + [CreateEmailTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/CreateEmailTemplate)
  + [DeleteContactList](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/DeleteContactList)
  + [DeleteEmailIdentity](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/DeleteEmailIdentity)
  + [DeleteEmailTemplate](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/DeleteEmailTemplate)
  + [ListContacts](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/ListContacts)
  + [SendEmail.simple](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/SendEmail.simple)
  + [SendEmail.template](https://docs.aws.amazon.com/goto/SdkForJavaV2/sesv2-2019-09-27/SendEmail.template)

# SDK for Java 2.x を使用する Amazon SNS の例
<a name="java_2_sns_code_examples"></a>

次のコード例は、Amazon SNS AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SNS
<a name="sns_Hello_java_2_topic"></a>

次のコード例は、Amazon SNS の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
package com.example.sns;

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.paginators.ListTopicsIterable;

public class HelloSNS {
    public static void main(String[] args) {
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listSNSTopics(snsClient);
        snsClient.close();
    }

    public static void listSNSTopics(SnsClient snsClient) {
        try {
            ListTopicsIterable listTopics = snsClient.listTopicsPaginator();
            listTopics.stream()
                    .flatMap(r -> r.topics().stream())
                    .forEach(content -> System.out.println(" Topic ARN: " + content.topicArn()));

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Java 2.x API リファレンス」の「[ListTopics](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/ListTopics)」を参照してください。

## アクション
<a name="actions"></a>

### `CheckIfPhoneNumberIsOptedOut`
<a name="sns_CheckIfPhoneNumberIsOptedOut_java_2_topic"></a>

次のコード例は、`CheckIfPhoneNumberIsOptedOut` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutRequest;
import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutResponse;
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 CheckOptOut {
    public static void main(String[] args) {

        final String usage = """

                Usage:    <phoneNumber>

                Where:
                   phoneNumber - The mobile phone number to look up (for example, +1XXX5550100).

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String phoneNumber = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        checkPhone(snsClient, phoneNumber);
        snsClient.close();
    }

    public static void checkPhone(SnsClient snsClient, String phoneNumber) {
        try {
            CheckIfPhoneNumberIsOptedOutRequest request = CheckIfPhoneNumberIsOptedOutRequest.builder()
                    .phoneNumber(phoneNumber)
                    .build();

            CheckIfPhoneNumberIsOptedOutResponse result = snsClient.checkIfPhoneNumberIsOptedOut(request);
            System.out.println(
                    result.isOptedOut() + "Phone Number " + phoneNumber + " has Opted Out of receiving sns messages." +
                            "\n\nStatus was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CheckIfPhoneNumberIsOptedOut](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CheckIfPhoneNumberIsOptedOut)」を参照してください。

### `ConfirmSubscription`
<a name="sns_ConfirmSubscription_java_2_topic"></a>

次のコード例は、`ConfirmSubscription` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.ConfirmSubscriptionRequest;
import software.amazon.awssdk.services.sns.model.ConfirmSubscriptionResponse;
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 ConfirmSubscription {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <subscriptionToken> <topicArn>

                Where:
                   subscriptionToken - A short-lived token sent to an endpoint during the Subscribe action.
                   topicArn - The ARN of the topic.\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String subscriptionToken = args[0];
        String topicArn = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        confirmSub(snsClient, subscriptionToken, topicArn);
        snsClient.close();
    }

    public static void confirmSub(SnsClient snsClient, String subscriptionToken, String topicArn) {
        try {
            ConfirmSubscriptionRequest request = ConfirmSubscriptionRequest.builder()
                    .token(subscriptionToken)
                    .topicArn(topicArn)
                    .build();

            ConfirmSubscriptionResponse result = snsClient.confirmSubscription(request);
            System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nSubscription Arn: \n\n"
                    + result.subscriptionArn());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ConfirmSubscription](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/ConfirmSubscription)」を参照してください。

### `CreateTopic`
<a name="sns_CreateTopic_java_2_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_java_2_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.DeleteTopicRequest;
import software.amazon.awssdk.services.sns.model.DeleteTopicResponse;
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 DeleteTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:     <topicArn>

                Where:
                   topicArn - The ARN of the topic to delete.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        System.out.println("Deleting a topic with name: " + topicArn);
        deleteSNSTopic(snsClient, topicArn);
        snsClient.close();
    }

    public static void deleteSNSTopic(SnsClient snsClient, String topicArn) {
        try {
            DeleteTopicRequest request = DeleteTopicRequest.builder()
                    .topicArn(topicArn)
                    .build();

            DeleteTopicResponse result = snsClient.deleteTopic(request);
            System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/DeleteTopic)」を参照してください。

### `GetSMSAttributes`
<a name="sns_GetSMSAttributes_java_2_topic"></a>

次のコード例は、`GetSMSAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.GetSubscriptionAttributesRequest;
import software.amazon.awssdk.services.sns.model.GetSubscriptionAttributesResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
import java.util.Iterator;
import java.util.Map;

/**
 * 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 GetSMSAtrributes {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicArn>

                Where:
                   topicArn - The ARN of the topic from which to retrieve attributes.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        getSNSAttrutes(snsClient, topicArn);
        snsClient.close();
    }

    public static void getSNSAttrutes(SnsClient snsClient, String topicArn) {
        try {
            GetSubscriptionAttributesRequest request = GetSubscriptionAttributesRequest.builder()
                    .subscriptionArn(topicArn)
                    .build();

            // Get the Subscription attributes
            GetSubscriptionAttributesResponse res = snsClient.getSubscriptionAttributes(request);
            Map<String, String> map = res.attributes();

            // Iterate through the map
            Iterator iter = map.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
            }

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }

        System.out.println("\n\nStatus was good");
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[GetSMSAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/GetSMSAttributes)」を参照してください。**

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_java_2_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.GetTopicAttributesRequest;
import software.amazon.awssdk.services.sns.model.GetTopicAttributesResponse;
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 GetTopicAttributes {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicArn>

                Where:
                   topicArn - The ARN of the topic to look up.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        System.out.println("Getting attributes for a topic with name: " + topicArn);
        getSNSTopicAttributes(snsClient, topicArn);
        snsClient.close();
    }

    public static void getSNSTopicAttributes(SnsClient snsClient, String topicArn) {
        try {
            GetTopicAttributesRequest request = GetTopicAttributesRequest.builder()
                    .topicArn(topicArn)
                    .build();

            GetTopicAttributesResponse result = snsClient.getTopicAttributes(request);
            System.out.println("\n\nStatus is " + result.sdkHttpResponse().statusCode() + "\n\nAttributes: \n\n"
                    + result.attributes());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/GetTopicAttributes)」を参照してください。

### `ListPhoneNumbersOptedOut`
<a name="sns_ListPhoneNumbersOptedOut_java_2_topic"></a>

次のコード例は、`ListPhoneNumbersOptedOut` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutRequest;
import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutResponse;
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 ListOptOut {
    public static void main(String[] args) {
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listOpts(snsClient);
        snsClient.close();
    }

    public static void listOpts(SnsClient snsClient) {
        try {
            ListPhoneNumbersOptedOutRequest request = ListPhoneNumbersOptedOutRequest.builder().build();
            ListPhoneNumbersOptedOutResponse result = snsClient.listPhoneNumbersOptedOut(request);
            System.out.println("Status is " + result.sdkHttpResponse().statusCode() + "\n\nPhone Numbers: \n\n"
                    + result.phoneNumbers());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListPhoneNumbersOptedOut](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/ListPhoneNumbersOptedOut)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_java_2_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.ListSubscriptionsRequest;
import software.amazon.awssdk.services.sns.model.ListSubscriptionsResponse;
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 ListSubscriptions {
    public static void main(String[] args) {
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listSNSSubscriptions(snsClient);
        snsClient.close();
    }

    public static void listSNSSubscriptions(SnsClient snsClient) {
        try {
            ListSubscriptionsRequest request = ListSubscriptionsRequest.builder()
                    .build();

            ListSubscriptionsResponse result = snsClient.listSubscriptions(request);
            System.out.println(result.subscriptions());

        } catch (SnsException e) {

            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListSubscriptions](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/ListSubscriptions)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_java_2_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.ListTopicsRequest;
import software.amazon.awssdk.services.sns.model.ListTopicsResponse;
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 ListTopics {
    public static void main(String[] args) {
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        listSNSTopics(snsClient);
        snsClient.close();
    }

    public static void listSNSTopics(SnsClient snsClient) {
        try {
            ListTopicsRequest request = ListTopicsRequest.builder()
                    .build();

            ListTopicsResponse result = snsClient.listTopics(request);
            System.out.println(
                    "Status was " + result.sdkHttpResponse().statusCode() + "\n\nTopics\n\n" + result.topics());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListTopics](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/ListTopics)」を参照してください。

### `Publish`
<a name="sns_Publish_java_2_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
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 PublishTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <topicArn>

                Where:
                   message - The message text to send.
                   topicArn - The ARN of the topic to publish.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String topicArn = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTopic(snsClient, message, topicArn);
        snsClient.close();
    }

    public static void pubTopic(SnsClient snsClient, String message, String topicArn) {
        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .topicArn(topicArn)
                    .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                    .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)」を参照してください。

### `SetSMSAttributes`
<a name="sns_SetSMSAttributes_java_2_topic"></a>

次のコード例は、`SetSMSAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest;
import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
import java.util.HashMap;

/**
 * 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 SetSMSAttributes {
    public static void main(String[] args) {
        HashMap<String, String> attributes = new HashMap<>(1);
        attributes.put("DefaultSMSType", "Transactional");
        attributes.put("UsageReportS3Bucket", "janbucket");

        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        setSNSAttributes(snsClient, attributes);
        snsClient.close();
    }

    public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) {
        try {
            SetSmsAttributesRequest request = SetSmsAttributesRequest.builder()
                    .attributes(attributes)
                    .build();

            SetSmsAttributesResponse result = snsClient.setSMSAttributes(request);
            System.out.println("Set default Attributes to " + attributes + ". Status was "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SetSMSAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/SetSMSAttributes)」を参照してください。

### `SetSubscriptionAttributes`
<a name="sns_SetSubscriptionAttributes_java_2_topic"></a>

次のコード例は、`SetSubscriptionAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import java.util.ArrayList;

/**
 * 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 UseMessageFilterPolicy {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <subscriptionArn>

                Where:
                   subscriptionArn - The ARN of a subscription.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String subscriptionArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        usePolicy(snsClient, subscriptionArn);
        snsClient.close();
    }

    public static void usePolicy(SnsClient snsClient, String subscriptionArn) {
        try {
            SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy();
            // Add a filter policy attribute with a single value
            fp.addAttribute("store", "example_corp");
            fp.addAttribute("event", "order_placed");

            // Add a prefix attribute
            fp.addAttributePrefix("customer_interests", "bas");

            // Add an anything-but attribute
            fp.addAttributeAnythingBut("customer_interests", "baseball");

            // Add a filter policy attribute with a list of values
            ArrayList<String> attributeValues = new ArrayList<>();
            attributeValues.add("rugby");
            attributeValues.add("soccer");
            attributeValues.add("hockey");
            fp.addAttribute("customer_interests", attributeValues);

            // Add a numeric attribute
            fp.addAttribute("price_usd", "=", 0);

            // Add a numeric attribute with a range
            fp.addAttributeRange("price_usd", ">", 0, "<=", 100);

            // Apply the filter policy attributes to an Amazon SNS subscription
            fp.apply(snsClient, subscriptionArn);

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SetSubscriptionAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/SetSubscriptionAttributes)」を参照してください。

### `SetTopicAttributes`
<a name="sns_SetTopicAttributes_java_2_topic"></a>

次のコード例は、`SetTopicAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest;
import software.amazon.awssdk.services.sns.model.SetTopicAttributesResponse;
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 SetTopicAttributes {

    public static void main(String[] args) {
        final String usage = """

                Usage:    <attribute> <topicArn> <value>

                Where:
                   attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy .
                   topicArn - The ARN of the topic.\s
                   value - The value for the attribute.
                """;

        if (args.length < 3) {
            System.out.println(usage);
            System.exit(1);
        }

        String attribute = args[0];
        String topicArn = args[1];
        String value = args[2];

        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        setTopAttr(snsClient, attribute, topicArn, value);
        snsClient.close();
    }

    public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) {
        try {
            SetTopicAttributesRequest request = SetTopicAttributesRequest.builder()
                    .attributeName(attribute)
                    .attributeValue(value)
                    .topicArn(topicArn)
                    .build();

            SetTopicAttributesResponse result = snsClient.setTopicAttributes(request);
            System.out.println(
                    "\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.topicArn()
                            + " updated " + request.attributeName() + " to " + request.attributeValue());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/SetTopicAttributes)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_java_2_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;

/**
 * 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 SubscribeEmail {
    public static void main(String[] args) {
        final String usage = """
                Usage:     <topicArn> <email>

                Where:
                   topicArn - The ARN of the topic to subscribe.
                   email - The email address to use.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        String email = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        subEmail(snsClient, topicArn, email);
        snsClient.close();
    }

    public static void subEmail(SnsClient snsClient, String topicArn, String email) {
        try {
            SubscribeRequest request = SubscribeRequest.builder()
                    .protocol("email")
                    .endpoint(email)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

            SubscribeResponse result = snsClient.subscribe(request);
            System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
HTTP エンドポイントをトピックにサブスクライブします。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;

/**
 * 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 SubscribeHTTPS {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicArn> <url>

                Where:
                   topicArn - The ARN of the topic to subscribe.
                   url - The HTTPS endpoint that you want to receive notifications.
                """;

        if (args.length < 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        String url = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        subHTTPS(snsClient, topicArn, url);
        snsClient.close();
    }

    public static void subHTTPS(SnsClient snsClient, String topicArn, String url) {
        try {
            SubscribeRequest request = SubscribeRequest.builder()
                    .protocol("https")
                    .endpoint(url)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

            SubscribeResponse result = snsClient.subscribe(request);
            System.out.println("Subscription ARN is " + result.subscriptionArn() + "\n\n Status is "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
Lambda 関数をトピックにサブスクライブします。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;

/**
 * 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 SubscribeLambda {

    public static void main(String[] args) {

        final String usage = """

                Usage:    <topicArn> <lambdaArn>

                Where:
                   topicArn - The ARN of the topic to subscribe.
                   lambdaArn - The ARN of an AWS Lambda function.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        String lambdaArn = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String arnValue = subLambda(snsClient, topicArn, lambdaArn);
        System.out.println("Subscription ARN: " + arnValue);
        snsClient.close();
    }

    public static String subLambda(SnsClient snsClient, String topicArn, String lambdaArn) {
        try {
            SubscribeRequest request = SubscribeRequest.builder()
                    .protocol("lambda")
                    .endpoint(lambdaArn)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

            SubscribeResponse result = snsClient.subscribe(request);
            return result.subscriptionArn();

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Subscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Subscribe)」を参照してください。

### `TagResource`
<a name="sns_TagResource_java_2_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.Tag;
import software.amazon.awssdk.services.sns.model.TagResourceRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 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 AddTags {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicArn>

                Where:
                   topicArn - The ARN of the topic to which tags are added.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        addTopicTags(snsClient, topicArn);
        snsClient.close();
    }

    public static void addTopicTags(SnsClient snsClient, String topicArn) {
        try {
            Tag tag = Tag.builder()
                    .key("Team")
                    .value("Development")
                    .build();

            Tag tag2 = Tag.builder()
                    .key("Environment")
                    .value("Gamma")
                    .build();

            List<Tag> tagList = new ArrayList<>();
            tagList.add(tag);
            tagList.add(tag2);

            TagResourceRequest tagResourceRequest = TagResourceRequest.builder()
                    .resourceArn(topicArn)
                    .tags(tagList)
                    .build();

            snsClient.tagResource(tagResourceRequest);
            System.out.println("Tags have been added to " + topicArn);

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/TagResource)」を参照してください。

### `Unsubscribe`
<a name="sns_Unsubscribe_java_2_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.UnsubscribeRequest;
import software.amazon.awssdk.services.sns.model.UnsubscribeResponse;

/**
 * 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 Unsubscribe {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <subscriptionArn>

                Where:
                   subscriptionArn - The ARN of the subscription to delete.
                """;

        if (args.length < 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String subscriptionArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        unSub(snsClient, subscriptionArn);
        snsClient.close();
    }

    public static void unSub(SnsClient snsClient, String subscriptionArn) {
        try {
            UnsubscribeRequest request = UnsubscribeRequest.builder()
                    .subscriptionArn(subscriptionArn)
                    .build();

            UnsubscribeResponse result = snsClient.unsubscribe(request);
            System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()
                    + "\n\nSubscription was removed for " + request.subscriptionArn());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Unsubscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Unsubscribe)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DynamoDB テーブルにデータを送信するアプリケーションを構築する
<a name="cross_SubmitDataApp_java_2_topic"></a>

次のコード例は、Amazon DynamoDB テーブルにデータを送信し、ユーザーがテーブルを更新したときに通知するアプリケーションを構築する方法を示しています。

**SDK for Java 2.x**  
 Amazon DynamoDB Java API を使用してデータを送信し、Amazon Simple Notification Service Java API を使用してテキストメッセージを送信する動的ウェブアプリケーションを作成する方法について説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_first_project) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SNS

### Amazon SNS アプリケーションの構築
<a name="cross_SnsPublishSubscription_java_2_topic"></a>

次のコード例は、サブスクリプションとパブリッシュ機能を持ち、メッセージを翻訳するアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon Simple Notification Service Java API を使用して、サブスクリプションおよびパブリッシュ機能を持つウェブアプリケーションを作成する方法を説明します。さらに、このサンプルアプリケーションではメッセージを翻訳します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_sns_sample_app) で完全な例を参照してください。  
 Java Async API を使用するサンプルの完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_sns_async) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon SNS
+ Amazon Translate

### プッシュ通知のプラットフォームエンドポイントを作成します
<a name="sns_CreatePlatformEndpoint_java_2_topic"></a>

次のコード例は、Amazon SNS プッシュ通知のプラットフォームエンドポイントを作成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointRequest;
import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointResponse;
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
 *
 * In addition, create a platform application using the AWS Management Console.
 * See this doc topic:
 *
 * https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-register.html
 *
 * Without the values created by following the previous link, this code examples
 * does not work.
 */

public class RegistrationExample {
    public static void main(String[] args) {
        final String usage = """

            Usage:     <token> <platformApplicationArn>

            Where:
               token - The device token or registration ID of the mobile device. This is a unique 
               identifier provided by the device platform (e.g., Apple Push Notification Service (APNS) for iOS devices, Firebase Cloud Messaging (FCM) 
               for Android devices) when the mobile app is registered to receive push notifications.

               platformApplicationArn - The ARN value of platform application. You can get this value from the AWS Management Console.\s

            """;

        if (args.length != 2) {
            System.out.println(usage);
            return;
        }

        String token = args[0];
        String platformApplicationArn = args[1];
        SnsClient snsClient = SnsClient.builder()
            .region(Region.US_EAST_1)
            .build();

        createEndpoint(snsClient, token, platformApplicationArn);
    }
    public static void createEndpoint(SnsClient snsClient, String token, String platformApplicationArn) {
        System.out.println("Creating platform endpoint with token " + token);
        try {
            CreatePlatformEndpointRequest endpointRequest = CreatePlatformEndpointRequest.builder()
                .token(token)
                .platformApplicationArn(platformApplicationArn)
                .build();

            CreatePlatformEndpointResponse response = snsClient.createPlatformEndpoint(endpointRequest);
            System.out.println("The ARN of the endpoint is " + response.endpointArn());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }
}
```

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_java_2_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Java 2.x**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/pam_source_files) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### FIFO トピックを作成して発行する
<a name="sns_PublishFifoTopic_java_2_topic"></a>

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。
この例では  
+ 1 つの Amazon SNS FIFO トピック、2 つの Amazon SQS FIFO キュー、および 1 つの標準キューを作成します。
+ キューをトピックにサブスクライブし、メッセージをトピックに発行します。
[テスト](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns/src/test/java/com/example/sns/PriceUpdateExampleTest.java)では、各キューへのメッセージの受信を検証します。[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns/src/main/java/com/example/sns/PriceUpdateExample.java)では、アクセスポリシーの追加と、最後にリソースの削除も示しています。  

```
public class PriceUpdateExample {
    public final static SnsClient snsClient = SnsClient.create();
    public final static SqsClient sqsClient = SqsClient.create();

    public static void main(String[] args) {

        final String usage = "\n" +
            "Usage: " +
            "    <topicName> <wholesaleQueueFifoName> <retailQueueFifoName> <analyticsQueueName>\n\n" +
            "Where:\n" +
            "   fifoTopicName - The name of the FIFO topic that you want to create. \n\n" +
            "   wholesaleQueueARN - The name of a SQS FIFO queue that will be created for the wholesale consumer. \n\n"
            +
            "   retailQueueARN - The name of a SQS FIFO queue that will created for the retail consumer. \n\n" +
            "   analyticsQueueARN - The name of a SQS standard queue that will be created for the analytics consumer. \n\n";
        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        final String fifoTopicName = args[0];
        final String wholeSaleQueueName = args[1];
        final String retailQueueName = args[2];
        final String analyticsQueueName = args[3];

        // For convenience, the QueueData class holds metadata about a queue: ARN, URL,
        // name and type.
        List<QueueData> queues = List.of(
            new QueueData(wholeSaleQueueName, QueueType.FIFO),
            new QueueData(retailQueueName, QueueType.FIFO),
            new QueueData(analyticsQueueName, QueueType.Standard));

        // Create queues.
        createQueues(queues);

        // Create a topic.
        String topicARN = createFIFOTopic(fifoTopicName);

        // Subscribe each queue to the topic.
        subscribeQueues(queues, topicARN);

        // Allow the newly created topic to send messages to the queues.
        addAccessPolicyToQueuesFINAL(queues, topicARN);

        // Publish a sample price update message with payload.
        publishPriceUpdate(topicARN, "{\"product\": 214, \"price\": 79.99}", "Consumables");

        // Clean up resources.
        deleteSubscriptions(queues);
        deleteQueues(queues);
        deleteTopic(topicARN);
    }

    public static String createFIFOTopic(String topicName) {
        try {
            // Create a FIFO topic by using the SNS service client.
            Map<String, String> topicAttributes = Map.of(
                "FifoTopic", "true",
                "ContentBasedDeduplication", "false",
                "FifoThroughputScope", "MessageGroup");

            CreateTopicRequest topicRequest = CreateTopicRequest.builder()
                .name(topicName)
                .attributes(topicAttributes)
                .build();

            CreateTopicResponse response = snsClient.createTopic(topicRequest);
            String topicArn = response.topicArn();
            System.out.println("The topic ARN is" + topicArn);

            return topicArn;

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void subscribeQueues(List<QueueData> queues, String topicARN) {
        queues.forEach(queue -> {
            SubscribeRequest subscribeRequest = SubscribeRequest.builder()
                .topicArn(topicARN)
                .endpoint(queue.queueARN)
                .protocol("sqs")
                .build();

            // Subscribe to the endpoint by using the SNS service client.
            // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO
            // topic.
            SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest);
            System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]");
            queue.subscriptionARN = subscribeResponse.subscriptionArn();
        });
    }

    public static void publishPriceUpdate(String topicArn, String payload, String groupId) {

        try {
            // Create and publish a message that updates the wholesale price.
            String subject = "Price Update";
            String dedupId = UUID.randomUUID().toString();
            String attributeName = "business";
            String attributeValue = "wholesale";

            MessageAttributeValue msgAttValue = MessageAttributeValue.builder()
                .dataType("String")
                .stringValue(attributeValue)
                .build();

            Map<String, MessageAttributeValue> attributes = new HashMap<>();
            attributes.put(attributeName, msgAttValue);
            PublishRequest pubRequest = PublishRequest.builder()
                .topicArn(topicArn)
                .subject(subject)
                .message(payload)
                .messageGroupId(groupId)
                .messageDeduplicationId(dedupId)
                .messageAttributes(attributes)
                .build();

            final PublishResponse response = snsClient.publish(pubRequest);
            System.out.println(response.messageId());
            System.out.println(response.sequenceNumber());
            System.out.println("Message was published to " + topicArn);

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)
  + [Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)
  + [Subscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Subscribe)

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_java_2_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用し、Amazon Simple Storage Service (Amazon S3) バケットにあるビデオ内で顔やオブジェクトを検出するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/video_analyzer_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### トピックへの SMS メッセージの発行
<a name="sns_UsageSmsTopic_java_2_topic"></a>

次のコードの例は以下の方法を示しています。
+ Amazon SNS トピックを作成します。
+ 携帯電話番号をトピックにサブスクライブする。
+ SMS メッセージをトピックに発行して、登録されているすべての電話番号がメッセージを一度に受信できるようにします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。
トピックを作成し、その ARN を返します。  

```
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 "";
    }
}
```
トピックへのエンドポイントのサブスクライブ。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;

/**
 * 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 SubscribeTextSMS {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicArn> <phoneNumber>

                Where:
                   topicArn - The ARN of the topic to subscribe.
                   phoneNumber - A mobile phone number that receives notifications (for example, +1XXX5550100).
                """;

        if (args.length < 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        String phoneNumber = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        subTextSNS(snsClient, topicArn, phoneNumber);
        snsClient.close();
    }

    public static void subTextSNS(SnsClient snsClient, String topicArn, String phoneNumber) {
        try {
            SubscribeRequest request = SubscribeRequest.builder()
                    .protocol("sms")
                    .endpoint(phoneNumber)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

            SubscribeResponse result = snsClient.subscribe(request);
            System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
送信者の ID、上限価格、タイプなど、メッセージ上の属性を設定します。メッセージ属性はオプションです。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest;
import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
import java.util.HashMap;

/**
 * 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 SetSMSAttributes {
    public static void main(String[] args) {
        HashMap<String, String> attributes = new HashMap<>(1);
        attributes.put("DefaultSMSType", "Transactional");
        attributes.put("UsageReportS3Bucket", "janbucket");

        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        setSNSAttributes(snsClient, attributes);
        snsClient.close();
    }

    public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) {
        try {
            SetSmsAttributesRequest request = SetSmsAttributesRequest.builder()
                    .attributes(attributes)
                    .build();

            SetSmsAttributesResponse result = snsClient.setSMSAttributes(request);
            System.out.println("Set default Attributes to " + attributes + ". Status was "
                    + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
トピックへのメッセージの発行 メッセージは、すべての受信者に送信されます。  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
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 PublishTextSMS {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <phoneNumber>

                Where:
                   message - The message text to send.
                   phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String phoneNumber = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTextSMS(snsClient, message, phoneNumber);
        snsClient.close();
    }

    public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) {
        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .phoneNumber(phoneNumber)
                    .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                    .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```

### SMS テキストメッセージを発行する
<a name="sns_PublishTextSMS_java_2_topic"></a>

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
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 PublishTextSMS {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <phoneNumber>

                Where:
                   message - The message text to send.
                   phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String phoneNumber = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTextSMS(snsClient, message, phoneNumber);
        snsClient.close();
    }

    public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) {
        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .phoneNumber(phoneNumber)
                    .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                    .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)」を参照してください。

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
package com.example.sns;

import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
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.DeleteTopicRequest;
import software.amazon.awssdk.services.sns.model.DeleteTopicResponse;
import software.amazon.awssdk.services.sns.model.MessageAttributeValue;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;
import software.amazon.awssdk.services.sns.model.UnsubscribeRequest;
import software.amazon.awssdk.services.sns.model.UnsubscribeResponse;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest;
import software.amazon.awssdk.services.sqs.model.SqsException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 * <p>
 * This Java example performs these tasks:
 * <p>
 * 1. Gives the user three options to choose from.
 * 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic.
 * 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue.
 * 4. Gets the SQS queue Amazon Resource Name (ARN) attribute.
 * 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue.
 * 6. Subscribes to the SQS queue.
 * 7. Publishes a message to the topic.
 * 8. Displays the messages.
 * 9. Deletes the received message.
 * 10. Unsubscribes from the topic.
 * 11. Deletes the SNS topic.
 */
public class SNSWorkflow {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) {
        final String usage = "\n" +
            "Usage:\n" +
            "    <fifoQueueARN>\n\n" +
            "Where:\n" +
            "    accountId - Your AWS account Id value.";

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        SnsClient snsClient = SnsClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .build();

        SqsClient sqsClient = SqsClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .build();

        Scanner in = new Scanner(System.in);
        String accountId = args[0];
        String useFIFO;
        String duplication = "n";
        String topicName;
        String deduplicationID = null;
        String groupId = null;

        String topicArn;
        String sqsQueueName;
        String sqsQueueUrl;
        String sqsQueueArn;
        String subscriptionArn;
        boolean selectFIFO = false;

        String message;
        List<Message> messageList;
        List<String> filterList = new ArrayList<>();
        String msgAttValue = "";

        System.out.println(DASHES);
        System.out.println("Welcome to messaging with topics and queues.");
        System.out.println("In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic.\n" +
            "You can select from several options for configuring the topic and the subscriptions for the queue.\n" +
            "You can then post to the topic and see the results in the queue.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("SNS topics can be configured as FIFO (First-In-First-Out).\n" +
            "FIFO topics deliver messages in order and support deduplication and message filtering.\n" +
            "Would you like to work with FIFO topics? (y/n)");
        useFIFO = in.nextLine();
        if (useFIFO.compareTo("y") == 0) {
            selectFIFO = true;
            System.out.println("You have selected FIFO");
            System.out.println(" Because you have chosen a FIFO topic, deduplication is supported.\n" +
                "        Deduplication IDs are either set in the message or automatically generated from content using a hash function.\n"
                +
                "        If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID,\n"
                +
                "        within the five-minute deduplication interval, is accepted but not delivered.\n" +
                "        For more information about deduplication, see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.");

            System.out.println(
                "Would you like to use content-based deduplication instead of entering a deduplication ID? (y/n)");
            duplication = in.nextLine();
            if (duplication.compareTo("y") == 0) {
                System.out.println("Please enter a group id value");
                groupId = in.nextLine();
            } else {
                System.out.println("Please enter deduplication Id value");
                deduplicationID = in.nextLine();
                System.out.println("Please enter a group id value");
                groupId = in.nextLine();
            }
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Create a topic.");
        System.out.println("Enter a name for your SNS topic.");
        topicName = in.nextLine();
        if (selectFIFO) {
            System.out.println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.");
            topicName = topicName + ".fifo";
            System.out.println("The name of the topic is " + topicName);
            topicArn = createFIFO(snsClient, topicName, duplication);
            System.out.println("The ARN of the FIFO topic is " + topicArn);

        } else {
            System.out.println("The name of the topic is " + topicName);
            topicArn = createSNSTopic(snsClient, topicName);
            System.out.println("The ARN of the non-FIFO topic is " + topicArn);

        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Create an SQS queue.");
        System.out.println("Enter a name for your SQS queue.");
        sqsQueueName = in.nextLine();
        if (selectFIFO) {
            sqsQueueName = sqsQueueName + ".fifo";
        }
        sqsQueueUrl = createQueue(sqsClient, sqsQueueName, selectFIFO);
        System.out.println("The queue URL is " + sqsQueueUrl);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Get the SQS queue ARN attribute.");
        sqsQueueArn = getSQSQueueAttrs(sqsClient, sqsQueueUrl);
        System.out.println("The ARN of the new queue is " + sqsQueueArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Attach an IAM policy to the queue.");

        // Define the policy to use. Make sure that you change the REGION if you are
        // running this code
        // in a different region.
        String policy = """
        {
             "Statement": [
             {
                 "Effect": "Allow",
                         "Principal": {
                     "Service": "sns.amazonaws.com"
                 },
                 "Action": "sqs:SendMessage",
                         "Resource": "arn:aws:sqs:us-east-1:%s:%s",
                         "Condition": {
                     "ArnEquals": {
                         "aws:SourceArn": "arn:aws:sns:us-east-1:%s:%s"
                     }
                 }
             }
             ]
         }
        """.formatted(accountId, sqsQueueName, accountId, topicName);

        setQueueAttr(sqsClient, sqsQueueUrl, policy);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Subscribe to the SQS queue.");
        if (selectFIFO) {
            System.out.println(
                "If you add a filter to this subscription, then only the filtered messages will be received in the queue.\n"
                    +
                    "For information about message filtering, see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n"
                    +
                    "For this example, you can filter messages by a \"tone\" attribute.");
            System.out.println("Would you like to filter messages for " + sqsQueueName + "'s subscription to the topic "
                + topicName + "?  (y/n)");
            String filterAns = in.nextLine();
            if (filterAns.compareTo("y") == 0) {
                boolean moreAns = false;
                System.out.println("You can filter messages by one or more of the following \"tone\" attributes.");
                System.out.println("1. cheerful");
                System.out.println("2. funny");
                System.out.println("3. serious");
                System.out.println("4. sincere");
                while (!moreAns) {
                    System.out.println("Select a number or choose 0 to end.");
                    String ans = in.nextLine();
                    switch (ans) {
                        case "1":
                            filterList.add("cheerful");
                            break;
                        case "2":
                            filterList.add("funny");
                            break;
                        case "3":
                            filterList.add("serious");
                            break;
                        case "4":
                            filterList.add("sincere");
                            break;
                        default:
                            moreAns = true;
                            break;
                    }
                }
            }
        }
        subscriptionArn = subQueue(snsClient, topicArn, sqsQueueArn, filterList);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Publish a message to the topic.");
        if (selectFIFO) {
            System.out.println("Would you like to add an attribute to this message?  (y/n)");
            String msgAns = in.nextLine();
            if (msgAns.compareTo("y") == 0) {
                System.out.println("You can filter messages by one or more of the following \"tone\" attributes.");
                System.out.println("1. cheerful");
                System.out.println("2. funny");
                System.out.println("3. serious");
                System.out.println("4. sincere");
                System.out.println("Select a number or choose 0 to end.");
                String ans = in.nextLine();
                switch (ans) {
                    case "1":
                        msgAttValue = "cheerful";
                        break;
                    case "2":
                        msgAttValue = "funny";
                        break;
                    case "3":
                        msgAttValue = "serious";
                        break;
                    default:
                        msgAttValue = "sincere";
                        break;
                }

                System.out.println("Selected value is " + msgAttValue);
            }
            System.out.println("Enter a message.");
            message = in.nextLine();
            pubMessageFIFO(snsClient, message, topicArn, msgAttValue, duplication, groupId, deduplicationID);

        } else {
            System.out.println("Enter a message.");
            message = in.nextLine();
            pubMessage(snsClient, message, topicArn);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Display the message. Press any key to continue.");
        in.nextLine();
        messageList = receiveMessages(sqsClient, sqsQueueUrl, msgAttValue);
        for (Message mes : messageList) {
            System.out.println("Message Id: " + mes.messageId());
            System.out.println("Full Message: " + mes.body());
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. Delete the received message. Press any key to continue.");
        in.nextLine();
        deleteMessages(sqsClient, sqsQueueUrl, messageList);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Unsubscribe from the topic and delete the queue. Press any key to continue.");
        in.nextLine();
        unSub(snsClient, subscriptionArn);
        deleteSQSQueue(sqsClient, sqsQueueName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Delete the topic. Press any key to continue.");
        in.nextLine();
        deleteSNSTopic(snsClient, topicArn);

        System.out.println(DASHES);
        System.out.println("The SNS/SQS workflow has completed successfully.");
        System.out.println(DASHES);
    }

    public static void deleteSNSTopic(SnsClient snsClient, String topicArn) {
        try {
            DeleteTopicRequest request = DeleteTopicRequest.builder()
                .topicArn(topicArn)
                .build();

            DeleteTopicResponse result = snsClient.deleteTopic(request);
            System.out.println("Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteSQSQueue(SqsClient sqsClient, String queueName) {
        try {
            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                .queueName(queueName)
                .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();
            DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()
                .queueUrl(queueUrl)
                .build();

            sqsClient.deleteQueue(deleteQueueRequest);
            System.out.println(queueName + " was successfully deleted.");

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void unSub(SnsClient snsClient, String subscriptionArn) {
        try {
            UnsubscribeRequest request = UnsubscribeRequest.builder()
                .subscriptionArn(subscriptionArn)
                .build();

            UnsubscribeResponse result = snsClient.unsubscribe(request);
            System.out.println("Status was " + result.sdkHttpResponse().statusCode()
                + "\nSubscription was removed for " + request.subscriptionArn());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) {
        try {
            List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>();
            for (Message msg : messages) {
                DeleteMessageBatchRequestEntry entry = DeleteMessageBatchRequestEntry.builder()
                    .id(msg.messageId())
                    .build();

                entries.add(entry);
            }

            DeleteMessageBatchRequest deleteMessageBatchRequest = DeleteMessageBatchRequest.builder()
                .queueUrl(queueUrl)
                .entries(entries)
                .build();

            sqsClient.deleteMessageBatch(deleteMessageBatchRequest);
            System.out.println("The batch delete of messages was successful");

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl, String msgAttValue) {
        try {
            if (msgAttValue.isEmpty()) {
                ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .maxNumberOfMessages(5)
                    .build();
                return sqsClient.receiveMessage(receiveMessageRequest).messages();
            } else {
                // We know there are filters on the message.
                ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageAttributeNames(msgAttValue) // Include other message attributes if needed.
                    .maxNumberOfMessages(5)
                    .build();

                return sqsClient.receiveMessage(receiveRequest).messages();
            }

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static void pubMessage(SnsClient snsClient, String message, String topicArn) {
        try {
            PublishRequest request = PublishRequest.builder()
                .message(message)
                .topicArn(topicArn)
                .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void pubMessageFIFO(SnsClient snsClient,
                                      String message,
                                      String topicArn,
                                      String msgAttValue,
                                      String duplication,
                                      String groupId,
                                      String deduplicationID) {

        try {
            PublishRequest request;
            // Means the user did not choose to use a message attribute.
            if (msgAttValue.isEmpty()) {
                if (duplication.compareTo("y") == 0) {
                    request = PublishRequest.builder()
                        .message(message)
                        .messageGroupId(groupId)
                        .topicArn(topicArn)
                        .build();
                } else {
                    request = PublishRequest.builder()
                        .message(message)
                        .messageDeduplicationId(deduplicationID)
                        .messageGroupId(groupId)
                        .topicArn(topicArn)
                        .build();
                }

            } else {
                Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
                messageAttributes.put(msgAttValue, MessageAttributeValue.builder()
                    .dataType("String")
                    .stringValue("true")
                    .build());

                if (duplication.compareTo("y") == 0) {
                    request = PublishRequest.builder()
                        .message(message)
                        .messageGroupId(groupId)
                        .topicArn(topicArn)
                        .build();
                } else {
                    // Create a publish request with the message and attributes.
                    request = PublishRequest.builder()
                        .topicArn(topicArn)
                        .message(message)
                        .messageDeduplicationId(deduplicationID)
                        .messageGroupId(groupId)
                        .messageAttributes(messageAttributes)
                        .build();
                }
            }

            // Publish the message to the topic.
            PublishResponse result = snsClient.publish(request);
            System.out
                .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Subscribe to the SQS queue.
    public static String subQueue(SnsClient snsClient, String topicArn, String queueArn, List<String> filterList) {
        try {
            SubscribeRequest request;
            if (filterList.isEmpty()) {
                // No filter subscription is added.
                request = SubscribeRequest.builder()
                    .protocol("sqs")
                    .endpoint(queueArn)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

                SubscribeResponse result = snsClient.subscribe(request);
                System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" +
                    "with the subscription ARN " + result.subscriptionArn());
                return result.subscriptionArn();
            } else {
                request = SubscribeRequest.builder()
                    .protocol("sqs")
                    .endpoint(queueArn)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

                SubscribeResponse result = snsClient.subscribe(request);
                System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" +
                    "with the subscription ARN " + result.subscriptionArn());

                String attributeName = "FilterPolicy";
                Gson gson = new Gson();
                String jsonString = "{\"tone\": []}";
                JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
                JsonArray toneArray = jsonObject.getAsJsonArray("tone");
                for (String value : filterList) {
                    toneArray.add(new JsonPrimitive(value));
                }

                String updatedJsonString = gson.toJson(jsonObject);
                System.out.println(updatedJsonString);
                SetSubscriptionAttributesRequest attRequest = SetSubscriptionAttributesRequest.builder()
                    .subscriptionArn(result.subscriptionArn())
                    .attributeName(attributeName)
                    .attributeValue(updatedJsonString)
                    .build();

                snsClient.setSubscriptionAttributes(attRequest);
                return result.subscriptionArn();
            }

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    // Attach a policy to the queue.
    public static void setQueueAttr(SqsClient sqsClient, String queueUrl, String policy) {
        try {
            Map<software.amazon.awssdk.services.sqs.model.QueueAttributeName, String> attrMap = new HashMap<>();
            attrMap.put(QueueAttributeName.POLICY, policy);

            SetQueueAttributesRequest attributesRequest = SetQueueAttributesRequest.builder()
                .queueUrl(queueUrl)
                .attributes(attrMap)
                .build();

            sqsClient.setQueueAttributes(attributesRequest);
            System.out.println("The policy has been successfully attached.");

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static String getSQSQueueAttrs(SqsClient sqsClient, String queueUrl) {
        // Specify the attributes to retrieve.
        List<QueueAttributeName> atts = new ArrayList<>();
        atts.add(QueueAttributeName.QUEUE_ARN);

        GetQueueAttributesRequest attributesRequest = GetQueueAttributesRequest.builder()
            .queueUrl(queueUrl)
            .attributeNames(atts)
            .build();

        GetQueueAttributesResponse response = sqsClient.getQueueAttributes(attributesRequest);
        Map<String, String> queueAtts = response.attributesAsStrings();
        for (Map.Entry<String, String> queueAtt : queueAtts.entrySet())
            return queueAtt.getValue();

        return "";
    }

    public static String createQueue(SqsClient sqsClient, String queueName, Boolean selectFIFO) {
        try {
            System.out.println("\nCreate Queue");
            if (selectFIFO) {
                Map<QueueAttributeName, String> attrs = new HashMap<>();
                attrs.put(QueueAttributeName.FIFO_QUEUE, "true");
                CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .attributes(attrs)
                    .build();

                sqsClient.createQueue(createQueueRequest);
                System.out.println("\nGet queue url");
                GetQueueUrlResponse getQueueUrlResponse = sqsClient
                    .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
                return getQueueUrlResponse.queueUrl();
            } else {
                CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .build();

                sqsClient.createQueue(createQueueRequest);
                System.out.println("\nGet queue url");
                GetQueueUrlResponse getQueueUrlResponse = sqsClient
                    .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
                return getQueueUrlResponse.queueUrl();
            }

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

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

    public static String createFIFO(SnsClient snsClient, String topicName, String duplication) {
        try {
            // Create a FIFO topic by using the SNS service client.
            Map<String, String> topicAttributes = new HashMap<>();
            if (duplication.compareTo("n") == 0) {
                topicAttributes.put("FifoTopic", "true");
                topicAttributes.put("ContentBasedDeduplication", "false");
            } else {
                topicAttributes.put("FifoTopic", "true");
                topicAttributes.put("ContentBasedDeduplication", "true");
            }

            CreateTopicRequest topicRequest = CreateTopicRequest.builder()
                .name(topicName)
                .attributes(topicAttributes)
                .build();

            CreateTopicResponse response = snsClient.createTopic(topicRequest);
            return response.topicArn();

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Unsubscribe)

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_java_2_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 Lambda Java ランタイム API を使用して AWS Lambda 関数を作成する方法を示します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、Amazon API Gateway によって呼び出される Lambda 関数を作成する方法を示します。この関数は、Amazon DynamoDB テーブルをスキャンして、Amazon Simple Notification Service (Amazon SNS) を使用して、従業員に年間の記念日を祝福するテキストメッセージを送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lambda_apigateway) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_java_2_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Lambda 関数を呼び出す Amazon EventBridge スケジュールされたイベントを作成する方法を示します。cron 式を使用して Lambda 関数が呼び出されるタイミングをスケジュールするように EventBridge を設定します。この例では、Lambda Java ランタイム API を使用して Lambda 関数を作成します。この例では、さまざまな AWS サービスを呼び出して、特定のユースケースを実行します。この例では、年間の記念日に従業員を祝福するモバイルテキストメッセージを従業員に送信するアプリを作成する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_scheduled_events) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_java_2_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での SNS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package example;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SNSEvent;
import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord;


import java.util.Iterator;
import java.util.List;

public class SNSEventHandler implements RequestHandler<SNSEvent, Boolean> {
    LambdaLogger logger;

    @Override
    public Boolean handleRequest(SNSEvent event, Context context) {
        logger = context.getLogger();
        List<SNSRecord> records = event.getRecords();
        if (!records.isEmpty()) {
            Iterator<SNSRecord> recordsIter = records.iterator();
            while (recordsIter.hasNext()) {
                processRecord(recordsIter.next());
            }
        }
        return Boolean.TRUE;
    }

    public void processRecord(SNSRecord record) {
        try {
            String message = record.getSNS().getMessage();
            logger.log("message: " + message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
```

# SDK for Java 2.x を使用する Amazon SQS の例
<a name="java_2_sqs_code_examples"></a>

次のコード例は、Amazon SQS AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon SQS
<a name="sqs_Hello_java_2_topic"></a>

次のコード例は、Amazon SQS の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.SqsException;
import software.amazon.awssdk.services.sqs.paginators.ListQueuesIterable;

/**
 * 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 HelloSQS {
    public static void main(String[] args) {
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();

        listQueues(sqsClient);
        sqsClient.close();
    }

    public static void listQueues(SqsClient sqsClient) {
        try {
            ListQueuesIterable listQueues = sqsClient.listQueuesPaginator();
            listQueues.stream()
                    .flatMap(r -> r.queueUrls().stream())
                    .forEach(content -> System.out.println(" Queue URL: " + content.toLowerCase()));

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListQueues](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ListQueues)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateQueue`
<a name="sqs_CreateQueue_java_2_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.ListQueuesRequest;
import software.amazon.awssdk.services.sqs.model.ListQueuesResponse;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
import software.amazon.awssdk.services.sqs.model.SqsException;
import java.util.List;

/**
 * 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 SQSExample {
    public static void main(String[] args) {
        String queueName = "queue" + System.currentTimeMillis();
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();

        // Perform various tasks on the Amazon SQS queue.
        String queueUrl = createQueue(sqsClient, queueName);
        listQueues(sqsClient);
        listQueuesFilter(sqsClient, queueUrl);
        List<Message> messages = receiveMessages(sqsClient, queueUrl);
        sendBatchMessages(sqsClient, queueUrl);
        changeMessages(sqsClient, queueUrl, messages);
        deleteMessages(sqsClient, queueUrl, messages);
        sqsClient.close();
    }

    public static String createQueue(SqsClient sqsClient, String queueName) {
        try {
            System.out.println("\nCreate Queue");

            CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .build();

            sqsClient.createQueue(createQueueRequest);

            System.out.println("\nGet queue url");

            GetQueueUrlResponse getQueueUrlResponse = sqsClient
                    .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
            return getQueueUrlResponse.queueUrl();

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void listQueues(SqsClient sqsClient) {

        System.out.println("\nList Queues");
        String prefix = "que";

        try {
            ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(prefix).build();
            ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest);
            for (String url : listQueuesResponse.queueUrls()) {
                System.out.println(url);
            }

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void listQueuesFilter(SqsClient sqsClient, String queueUrl) {
        // List queues with filters
        String namePrefix = "queue";
        ListQueuesRequest filterListRequest = ListQueuesRequest.builder()
                .queueNamePrefix(namePrefix)
                .build();

        ListQueuesResponse listQueuesFilteredResponse = sqsClient.listQueues(filterListRequest);
        System.out.println("Queue URLs with prefix: " + namePrefix);
        for (String url : listQueuesFilteredResponse.queueUrls()) {
            System.out.println(url);
        }

        System.out.println("\nSend message");
        try {
            sqsClient.sendMessage(SendMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageBody("Hello world!")
                    .delaySeconds(10)
                    .build());

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void sendBatchMessages(SqsClient sqsClient, String queueUrl) {

        System.out.println("\nSend multiple messages");
        try {
            SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
                    .queueUrl(queueUrl)
                    .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(),
                            SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10)
                                    .build())
                    .build();
            sqsClient.sendMessageBatch(sendMessageBatchRequest);

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl) {

        System.out.println("\nReceive messages");
        try {
            ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .maxNumberOfMessages(5)
                    .build();
            return sqsClient.receiveMessage(receiveMessageRequest).messages();

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static void changeMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) {

        System.out.println("\nChange Message Visibility");
        try {

            for (Message message : messages) {
                ChangeMessageVisibilityRequest req = ChangeMessageVisibilityRequest.builder()
                        .queueUrl(queueUrl)
                        .receiptHandle(message.receiptHandle())
                        .visibilityTimeout(100)
                        .build();
                sqsClient.changeMessageVisibility(req);
            }

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) {
        System.out.println("\nDelete Messages");

        try {
            for (Message message : messages) {
                DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
                        .queueUrl(queueUrl)
                        .receiptHandle(message.receiptHandle())
                        .build();
                sqsClient.deleteMessage(deleteMessageRequest);
            }
        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[CreateQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/CreateQueue)」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_java_2_topic"></a>

次のコード例は、`DeleteMessage` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        try {
            for (Message message : messages) {
                DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder()
                        .queueUrl(queueUrl)
                        .receiptHandle(message.receiptHandle())
                        .build();
                sqsClient.deleteMessage(deleteMessageRequest);
            }
        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteMessage)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_java_2_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.SqsException;

/**
 * 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 DeleteQueue {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <queueName>

                Where:
                   queueName - The name of the Amazon SQS queue to delete.

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String queueName = args[0];
        SqsClient sqs = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();

        deleteSQSQueue(sqs, queueName);
        sqs.close();
    }

    public static void deleteSQSQueue(SqsClient sqsClient, String queueName) {
        try {
            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                    .queueName(queueName)
                    .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();
            DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()
                    .queueUrl(queueUrl)
                    .build();

            sqsClient.deleteQueue(deleteQueueRequest);

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[DeleteQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteQueue)」を参照してください。

### `GetQueueUrl`
<a name="sqs_GetQueueUrl_java_2_topic"></a>

次のコード例は、`GetQueueUrl` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
            GetQueueUrlResponse getQueueUrlResponse = sqsClient
                    .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
            return getQueueUrlResponse.queueUrl();
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetQueueUrl](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/GetQueueUrl)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_java_2_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        String prefix = "que";

        try {
            ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(prefix).build();
            ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest);
            for (String url : listQueuesResponse.queueUrls()) {
                System.out.println(url);
            }

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[ListQueues](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ListQueues)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_java_2_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
        try {
            ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .maxNumberOfMessages(5)
                    .build();
            return sqsClient.receiveMessage(receiveMessageRequest).messages();

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
```
+  API の詳細については、**AWS SDK for Java 2.x API リファレンスの「[ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_java_2_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
`SendMessage` オペレーションの 2 つの例を次に示します。  
+ 本文と遅延を含むメッセージを送信する
+ 本文とメッセージ属性を含むメッセージを送信する
本文と遅延を含むメッセージを送信します。  

```
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
import software.amazon.awssdk.services.sqs.model.SqsException;

/**
 * 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 SendMessages {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <queueName> <message>

                Where:
                   queueName - The name of the queue.
                   message - The message to send.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String queueName = args[0];
        String message = args[1];
        SqsClient sqsClient = SqsClient.builder()
                .region(Region.US_WEST_2)
                .build();
        sendMessage(sqsClient, queueName, message);
        sqsClient.close();
    }

    public static void sendMessage(SqsClient sqsClient, String queueName, String message) {
        try {
            CreateQueueRequest request = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .build();
            sqsClient.createQueue(request);

            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                    .queueName(queueName)
                    .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();
            SendMessageRequest sendMsgRequest = SendMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageBody(message)
                    .delaySeconds(5)
                    .build();

            sqsClient.sendMessage(sendMsgRequest);

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
本文とメッセージ属性を含むメッセージを送信します。  

```
    /**
     * <p>This method demonstrates how to add message attributes to a message.
     * Each attribute must specify a name, value, and data type. You use a Java Map to supply the attributes. The map's
     * key is the attribute name, and you specify the map's entry value using a builder that includes the attribute
     * value and data type.</p>
     *
     * <p>The data type must start with one of "String", "Number" or "Binary". You can optionally
     * define a custom extension by using a "." and your extension.</p>
     *
     * <p>The SQS Developer Guide provides more information on @see <a
     * href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-message-metadata.html#sqs-message-attributes">message
     * attributes</a>.</p>
     *
     * @param thumbailPath Filesystem path of the image.
     * @param queueUrl     URL of the SQS queue.
     */
    static void sendMessageWithAttributes(Path thumbailPath, String queueUrl) {
        Map<String, MessageAttributeValue> messageAttributeMap;
        try {
            messageAttributeMap = Map.of(
                    "Name", MessageAttributeValue.builder()
                            .stringValue("Jane Doe")
                            .dataType("String").build(),
                    "Age", MessageAttributeValue.builder()
                            .stringValue("42")
                            .dataType("Number.int").build(),
                    "Image", MessageAttributeValue.builder()
                            .binaryValue(SdkBytes.fromByteArray(Files.readAllBytes(thumbailPath)))
                            .dataType("Binary.jpg").build()
            );
        } catch (IOException e) {
            LOGGER.error("An I/O exception occurred reading thumbnail image: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }

        SendMessageRequest request = SendMessageRequest.builder()
                .queueUrl(queueUrl)
                .messageBody("Hello SQS")
                .messageAttributes(messageAttributeMap)
                .build();
        try {
            SendMessageResponse sendMessageResponse = SQS_CLIENT.sendMessage(request);
            LOGGER.info("Message ID: {}", sendMessageResponse.messageId());
        } catch (SqsException e) {
            LOGGER.error("Exception occurred sending message: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[SendMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SendMessage)」を参照してください。**

### `SendMessageBatch`
<a name="sqs_SendMessageBatch_java_2_topic"></a>

次のコード例は、`SendMessageBatch` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
            SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder()
                    .queueUrl(queueUrl)
                    .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(),
                            SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10)
                                    .build())
                    .build();
            sqsClient.sendMessageBatch(sendMessageBatchRequest);
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[SendMessageBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SendMessageBatch)」を参照してください。

### `SetQueueAttributes`
<a name="sqs_SetQueueAttributes_java_2_topic"></a>

次のコード例は、`SetQueueAttributes` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
カスタム KMS キーを使用してサーバー側の暗号化 (SSE) を使用するように Amazon SQS を設定します。  

```
    public static void addEncryption(String queueName, String kmsMasterKeyAlias) {
        SqsClient sqsClient = SqsClient.create();

        GetQueueUrlRequest urlRequest = GetQueueUrlRequest.builder()
                .queueName(queueName)
                .build();

        GetQueueUrlResponse getQueueUrlResponse;
        try {
            getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest);
        } catch (QueueDoesNotExistException e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
        String queueUrl = getQueueUrlResponse.queueUrl();


        Map<QueueAttributeName, String> attributes = Map.of(
                QueueAttributeName.KMS_MASTER_KEY_ID, kmsMasterKeyAlias,
                QueueAttributeName.KMS_DATA_KEY_REUSE_PERIOD_SECONDS, "140" // Set the data key reuse period to 140 seconds.
        );                                                                  // This is how long SQS can reuse the data key before requesting a new one from KMS.

        SetQueueAttributesRequest attRequest = SetQueueAttributesRequest.builder()
                .queueUrl(queueUrl)
                .attributes(attributes)
                .build();
        try {
            sqsClient.setQueueAttributes(attRequest);
            LOGGER.info("The attributes have been applied to {}", queueName);
        } catch (InvalidAttributeNameException | InvalidAttributeValueException e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException(e);
        } finally {
            sqsClient.close();
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SetQueueAttributes)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセージングアプリケーションを作成する
<a name="cross_SQSMessageApp_java_2_topic"></a>

次のコード例は、Amazon SQS を使用してメッセージングアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon SQS API を使用して、メッセージを送受信する Spring REST API を開発する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_message_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SQS

### FIFO トピックを作成して発行する
<a name="sns_PublishFifoTopic_java_2_topic"></a>

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

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。
この例では  
+ 1 つの Amazon SNS FIFO トピック、2 つの Amazon SQS FIFO キュー、および 1 つの標準キューを作成します。
+ キューをトピックにサブスクライブし、メッセージをトピックに発行します。
[テスト](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns/src/test/java/com/example/sns/PriceUpdateExampleTest.java)では、各キューへのメッセージの受信を検証します。[完全な例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns/src/main/java/com/example/sns/PriceUpdateExample.java)では、アクセスポリシーの追加と、最後にリソースの削除も示しています。  

```
public class PriceUpdateExample {
    public final static SnsClient snsClient = SnsClient.create();
    public final static SqsClient sqsClient = SqsClient.create();

    public static void main(String[] args) {

        final String usage = "\n" +
            "Usage: " +
            "    <topicName> <wholesaleQueueFifoName> <retailQueueFifoName> <analyticsQueueName>\n\n" +
            "Where:\n" +
            "   fifoTopicName - The name of the FIFO topic that you want to create. \n\n" +
            "   wholesaleQueueARN - The name of a SQS FIFO queue that will be created for the wholesale consumer. \n\n"
            +
            "   retailQueueARN - The name of a SQS FIFO queue that will created for the retail consumer. \n\n" +
            "   analyticsQueueARN - The name of a SQS standard queue that will be created for the analytics consumer. \n\n";
        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        final String fifoTopicName = args[0];
        final String wholeSaleQueueName = args[1];
        final String retailQueueName = args[2];
        final String analyticsQueueName = args[3];

        // For convenience, the QueueData class holds metadata about a queue: ARN, URL,
        // name and type.
        List<QueueData> queues = List.of(
            new QueueData(wholeSaleQueueName, QueueType.FIFO),
            new QueueData(retailQueueName, QueueType.FIFO),
            new QueueData(analyticsQueueName, QueueType.Standard));

        // Create queues.
        createQueues(queues);

        // Create a topic.
        String topicARN = createFIFOTopic(fifoTopicName);

        // Subscribe each queue to the topic.
        subscribeQueues(queues, topicARN);

        // Allow the newly created topic to send messages to the queues.
        addAccessPolicyToQueuesFINAL(queues, topicARN);

        // Publish a sample price update message with payload.
        publishPriceUpdate(topicARN, "{\"product\": 214, \"price\": 79.99}", "Consumables");

        // Clean up resources.
        deleteSubscriptions(queues);
        deleteQueues(queues);
        deleteTopic(topicARN);
    }

    public static String createFIFOTopic(String topicName) {
        try {
            // Create a FIFO topic by using the SNS service client.
            Map<String, String> topicAttributes = Map.of(
                "FifoTopic", "true",
                "ContentBasedDeduplication", "false",
                "FifoThroughputScope", "MessageGroup");

            CreateTopicRequest topicRequest = CreateTopicRequest.builder()
                .name(topicName)
                .attributes(topicAttributes)
                .build();

            CreateTopicResponse response = snsClient.createTopic(topicRequest);
            String topicArn = response.topicArn();
            System.out.println("The topic ARN is" + topicArn);

            return topicArn;

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void subscribeQueues(List<QueueData> queues, String topicARN) {
        queues.forEach(queue -> {
            SubscribeRequest subscribeRequest = SubscribeRequest.builder()
                .topicArn(topicARN)
                .endpoint(queue.queueARN)
                .protocol("sqs")
                .build();

            // Subscribe to the endpoint by using the SNS service client.
            // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO
            // topic.
            SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest);
            System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]");
            queue.subscriptionARN = subscribeResponse.subscriptionArn();
        });
    }

    public static void publishPriceUpdate(String topicArn, String payload, String groupId) {

        try {
            // Create and publish a message that updates the wholesale price.
            String subject = "Price Update";
            String dedupId = UUID.randomUUID().toString();
            String attributeName = "business";
            String attributeValue = "wholesale";

            MessageAttributeValue msgAttValue = MessageAttributeValue.builder()
                .dataType("String")
                .stringValue(attributeValue)
                .build();

            Map<String, MessageAttributeValue> attributes = new HashMap<>();
            attributes.put(attributeName, msgAttValue);
            PublishRequest pubRequest = PublishRequest.builder()
                .topicArn(topicArn)
                .subject(subject)
                .message(payload)
                .messageGroupId(groupId)
                .messageDeduplicationId(dedupId)
                .messageAttributes(attributes)
                .build();

            final PublishResponse response = snsClient.publish(pubRequest);
            System.out.println(response.messageId());
            System.out.println(response.sequenceNumber());
            System.out.println("Message was published to " + topicArn);

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)
  + [Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)
  + [Subscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Subscribe)

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_java_2_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Java 2.x**  
 Amazon Rekognition Java API を使用し、Amazon Simple Storage Service (Amazon S3) バケットにあるビデオ内で顔やオブジェクトを検出するアプリケーションを作成する方法について説明します。アプリケーションは Amazon Simple Email Service (Amazon SES) を使用して、結果を含む E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/video_analyzer_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### S3 を使用して大量のメッセージを管理する
<a name="sqs_Scenario_SqsExtendedClient_java_2_topic"></a>

次のコード例は、Amazon SQS 拡張クライアントライブラリを使用して大量の Amazon SQS メッセージを操作する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient;
import com.amazon.sqs.javamessaging.ExtendedClientConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration;
import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.ExpirationStatus;
import software.amazon.awssdk.services.s3.model.LifecycleExpiration;
import software.amazon.awssdk.services.s3.model.LifecycleRule;
import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest;
import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationRequest;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.CreateQueueResponse;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Example of using Amazon SQS Extended Client Library for Java 2.x.
 */
public class SqsExtendedClientExample {
    private static final Logger logger = LoggerFactory.getLogger(SqsExtendedClientExample.class);
    
    private String s3BucketName;
    private String queueUrl;
    private final String queueName;
    private final S3Client s3Client;
    private final SqsClient sqsExtendedClient;
    private final int messageSize;

    /**
     * Constructor with default clients and message size.
     */
    public SqsExtendedClientExample() {
        this(S3Client.create(), 300000);
    }

    /**
     * Constructor with custom S3 client and message size.
     *
     * @param s3Client The S3 client to use
     * @param messageSize The size of the test message to create
     */
    public SqsExtendedClientExample(S3Client s3Client, int messageSize) {
        this.s3Client = s3Client;
        this.messageSize = messageSize;

        // Generate a unique bucket name.
        this.s3BucketName = UUID.randomUUID() + "-" +
                DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime());

        // Generate a unique queue name.
        this.queueName = "MyQueue-" + UUID.randomUUID();

        // Configure the SQS extended client.
        final ExtendedClientConfiguration extendedClientConfig = new ExtendedClientConfiguration()
                .withPayloadSupportEnabled(s3Client, s3BucketName);

        this.sqsExtendedClient = new AmazonSQSExtendedClient(SqsClient.builder().build(), extendedClientConfig);
    }

    public static void main(String[] args) {
        SqsExtendedClientExample example = new SqsExtendedClientExample();
        try {
            example.setup();
            example.sendAndReceiveMessage();
        } finally {
            example.cleanup();
        }
    }

    /**
     * Send a large message and receive it back.
     *
     * @return The received message
     */
    public Message sendAndReceiveMessage() {
        try {
            // Create a large message.
            char[] chars = new char[messageSize];
            Arrays.fill(chars, 'x');
            String largeMessage = new String(chars);

            // Send the message.
            final SendMessageRequest sendMessageRequest = SendMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageBody(largeMessage)
                    .build();

            sqsExtendedClient.sendMessage(sendMessageRequest);
            logger.info("Sent message of size: {}", largeMessage.length());

            // Receive and return the message.
            final ReceiveMessageResponse receiveMessageResponse = sqsExtendedClient.receiveMessage(
                    ReceiveMessageRequest.builder().queueUrl(queueUrl).build());

            List<Message> messages = receiveMessageResponse.messages();
            if (messages.isEmpty()) {
                throw new RuntimeException("No messages received");
            }

            Message message = messages.getFirst();
            logger.info("\nMessage received.");
            logger.info("  ID: {}", message.messageId());
            logger.info("  Receipt handle: {}", message.receiptHandle());
            logger.info("  Message body size: {}", message.body().length());
            logger.info("  Message body (first 5 characters): {}", message.body().substring(0, 5));

            return message;
        } catch (RuntimeException e) {
            logger.error("Error during message processing: {}", e.getMessage(), e);
            throw e;
        }
    }
```
+  詳細については、「[AWS SDK for Java 2.x デベロッパーガイド](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-s3-messages.html)」を参照してください。
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/CreateBucket)
  + [PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketLifecycleConfiguration)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)
  + [SendMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SendMessage)

### S3 イベント通知の処理
<a name="s3_Scenario_ProcessS3EventNotification_java_2_topic"></a>

次のコード例は、オブジェクト指向の方法で S3 イベント通知を操作する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/s3#code-examples)での設定と実行の方法を確認してください。
この例は、Amazon SQS を使用して S3 通知イベントを処理する方法を示しています。  

```
    /**
     * This method receives S3 event notifications by using an SqsAsyncClient.
     * After the client receives the messages it deserializes the JSON payload and logs them. It uses
     * the S3EventNotification class (part of the S3 event notification API for Java) to deserialize
     * the JSON payload and access the messages in an object-oriented way.
     *
     * @param queueUrl The URL of the AWS SQS queue that receives the S3 event notifications.
     * @see <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/eventnotifications/s3/model/package-summary.html">S3EventNotification API</a>.
     * <p>
     * To use S3 event notification serialization/deserialization to objects, add the following
     * dependency to your Maven pom.xml file.
     * <dependency>
     * <groupId>software.amazon.awssdk</groupId>
     * <artifactId>s3-event-notifications</artifactId>
     * <version><LATEST></version>
     * </dependency>
     * <p>
     * The S3 event notification API became available with version 2.25.11 of the Java SDK.
     * <p>
     * This example shows the use of the API with AWS SQS, but it can be used to process S3 event notifications
     * in AWS SNS or AWS Lambda as well.
     * <p>
     * Note: The S3EventNotification class does not work with messages routed through AWS EventBridge.
     */
    static void processS3Events(String bucketName, String queueUrl, String queueArn) {
        try {
            // Configure the bucket to send Object Created and Object Tagging notifications to an existing SQS queue.
            s3Client.putBucketNotificationConfiguration(b -> b
                    .notificationConfiguration(ncb -> ncb
                            .queueConfigurations(qcb -> qcb
                                    .events(Event.S3_OBJECT_CREATED, Event.S3_OBJECT_TAGGING)
                                    .queueArn(queueArn)))
                            .bucket(bucketName)
            ).join();

            triggerS3EventNotifications(bucketName);
            // Wait for event notifications to propagate.
            Thread.sleep(Duration.ofSeconds(5).toMillis());

            boolean didReceiveMessages = true;
            while (didReceiveMessages) {
                // Display the number of messages that are available in the queue.
                sqsClient.getQueueAttributes(b -> b
                                .queueUrl(queueUrl)
                                .attributeNames(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES)
                        ).thenAccept(attributeResponse ->
                                logger.info("Approximate number of messages in the queue: {}",
                                        attributeResponse.attributes().get(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES)))
                        .join();

                // Receive the messages.
                ReceiveMessageResponse response = sqsClient.receiveMessage(b -> b
                        .queueUrl(queueUrl)
                ).get();
                logger.info("Count of received messages: {}", response.messages().size());
                didReceiveMessages = !response.messages().isEmpty();

                // Create a collection to hold the received message for deletion
                // after we log the messages.
                HashSet<DeleteMessageBatchRequestEntry> messagesToDelete = new HashSet<>();
                // Process each message.
                response.messages().forEach(message -> {
                    logger.info("Message id: {}", message.messageId());
                    // Deserialize JSON message body to a S3EventNotification object
                    // to access messages in an object-oriented way.
                    S3EventNotification event = S3EventNotification.fromJson(message.body());

                    // Log the S3 event notification record details.
                    if (event.getRecords() != null) {
                        event.getRecords().forEach(record -> {
                            String eventName = record.getEventName();
                            String key = record.getS3().getObject().getKey();
                            logger.info(record.toString());
                            logger.info("Event name is {} and key is {}", eventName, key);
                        });
                    }
                    // Add logged messages to collection for batch deletion.
                    messagesToDelete.add(DeleteMessageBatchRequestEntry.builder()
                            .id(message.messageId())
                            .receiptHandle(message.receiptHandle())
                            .build());
                });
                // Delete messages.
                if (!messagesToDelete.isEmpty()) {
                    sqsClient.deleteMessageBatch(DeleteMessageBatchRequest.builder()
                            .queueUrl(queueUrl)
                            .entries(messagesToDelete)
                            .build()
                    ).join();
                }
            } // End of while block.
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteMessageBatch)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/GetQueueAttributes)
  + [PutBucketNotificationConfiguration](https://docs.aws.amazon.com/goto/SdkForJavaV2/s3-2006-03-01/PutBucketNotificationConfiguration)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
package com.example.sns;

import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
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.DeleteTopicRequest;
import software.amazon.awssdk.services.sns.model.DeleteTopicResponse;
import software.amazon.awssdk.services.sns.model.MessageAttributeValue;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest;
import software.amazon.awssdk.services.sns.model.SnsException;
import software.amazon.awssdk.services.sns.model.SubscribeRequest;
import software.amazon.awssdk.services.sns.model.SubscribeResponse;
import software.amazon.awssdk.services.sns.model.UnsubscribeRequest;
import software.amazon.awssdk.services.sns.model.UnsubscribeResponse;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest;
import software.amazon.awssdk.services.sqs.model.SqsException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 * <p>
 * For more information, see the following documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 * <p>
 * This Java example performs these tasks:
 * <p>
 * 1. Gives the user three options to choose from.
 * 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic.
 * 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue.
 * 4. Gets the SQS queue Amazon Resource Name (ARN) attribute.
 * 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue.
 * 6. Subscribes to the SQS queue.
 * 7. Publishes a message to the topic.
 * 8. Displays the messages.
 * 9. Deletes the received message.
 * 10. Unsubscribes from the topic.
 * 11. Deletes the SNS topic.
 */
public class SNSWorkflow {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) {
        final String usage = "\n" +
            "Usage:\n" +
            "    <fifoQueueARN>\n\n" +
            "Where:\n" +
            "    accountId - Your AWS account Id value.";

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        SnsClient snsClient = SnsClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .build();

        SqsClient sqsClient = SqsClient.builder()
            .region(Region.US_EAST_1)
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .build();

        Scanner in = new Scanner(System.in);
        String accountId = args[0];
        String useFIFO;
        String duplication = "n";
        String topicName;
        String deduplicationID = null;
        String groupId = null;

        String topicArn;
        String sqsQueueName;
        String sqsQueueUrl;
        String sqsQueueArn;
        String subscriptionArn;
        boolean selectFIFO = false;

        String message;
        List<Message> messageList;
        List<String> filterList = new ArrayList<>();
        String msgAttValue = "";

        System.out.println(DASHES);
        System.out.println("Welcome to messaging with topics and queues.");
        System.out.println("In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic.\n" +
            "You can select from several options for configuring the topic and the subscriptions for the queue.\n" +
            "You can then post to the topic and see the results in the queue.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("SNS topics can be configured as FIFO (First-In-First-Out).\n" +
            "FIFO topics deliver messages in order and support deduplication and message filtering.\n" +
            "Would you like to work with FIFO topics? (y/n)");
        useFIFO = in.nextLine();
        if (useFIFO.compareTo("y") == 0) {
            selectFIFO = true;
            System.out.println("You have selected FIFO");
            System.out.println(" Because you have chosen a FIFO topic, deduplication is supported.\n" +
                "        Deduplication IDs are either set in the message or automatically generated from content using a hash function.\n"
                +
                "        If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID,\n"
                +
                "        within the five-minute deduplication interval, is accepted but not delivered.\n" +
                "        For more information about deduplication, see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.");

            System.out.println(
                "Would you like to use content-based deduplication instead of entering a deduplication ID? (y/n)");
            duplication = in.nextLine();
            if (duplication.compareTo("y") == 0) {
                System.out.println("Please enter a group id value");
                groupId = in.nextLine();
            } else {
                System.out.println("Please enter deduplication Id value");
                deduplicationID = in.nextLine();
                System.out.println("Please enter a group id value");
                groupId = in.nextLine();
            }
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Create a topic.");
        System.out.println("Enter a name for your SNS topic.");
        topicName = in.nextLine();
        if (selectFIFO) {
            System.out.println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.");
            topicName = topicName + ".fifo";
            System.out.println("The name of the topic is " + topicName);
            topicArn = createFIFO(snsClient, topicName, duplication);
            System.out.println("The ARN of the FIFO topic is " + topicArn);

        } else {
            System.out.println("The name of the topic is " + topicName);
            topicArn = createSNSTopic(snsClient, topicName);
            System.out.println("The ARN of the non-FIFO topic is " + topicArn);

        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Create an SQS queue.");
        System.out.println("Enter a name for your SQS queue.");
        sqsQueueName = in.nextLine();
        if (selectFIFO) {
            sqsQueueName = sqsQueueName + ".fifo";
        }
        sqsQueueUrl = createQueue(sqsClient, sqsQueueName, selectFIFO);
        System.out.println("The queue URL is " + sqsQueueUrl);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Get the SQS queue ARN attribute.");
        sqsQueueArn = getSQSQueueAttrs(sqsClient, sqsQueueUrl);
        System.out.println("The ARN of the new queue is " + sqsQueueArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Attach an IAM policy to the queue.");

        // Define the policy to use. Make sure that you change the REGION if you are
        // running this code
        // in a different region.
        String policy = """
        {
             "Statement": [
             {
                 "Effect": "Allow",
                         "Principal": {
                     "Service": "sns.amazonaws.com"
                 },
                 "Action": "sqs:SendMessage",
                         "Resource": "arn:aws:sqs:us-east-1:%s:%s",
                         "Condition": {
                     "ArnEquals": {
                         "aws:SourceArn": "arn:aws:sns:us-east-1:%s:%s"
                     }
                 }
             }
             ]
         }
        """.formatted(accountId, sqsQueueName, accountId, topicName);

        setQueueAttr(sqsClient, sqsQueueUrl, policy);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Subscribe to the SQS queue.");
        if (selectFIFO) {
            System.out.println(
                "If you add a filter to this subscription, then only the filtered messages will be received in the queue.\n"
                    +
                    "For information about message filtering, see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n"
                    +
                    "For this example, you can filter messages by a \"tone\" attribute.");
            System.out.println("Would you like to filter messages for " + sqsQueueName + "'s subscription to the topic "
                + topicName + "?  (y/n)");
            String filterAns = in.nextLine();
            if (filterAns.compareTo("y") == 0) {
                boolean moreAns = false;
                System.out.println("You can filter messages by one or more of the following \"tone\" attributes.");
                System.out.println("1. cheerful");
                System.out.println("2. funny");
                System.out.println("3. serious");
                System.out.println("4. sincere");
                while (!moreAns) {
                    System.out.println("Select a number or choose 0 to end.");
                    String ans = in.nextLine();
                    switch (ans) {
                        case "1":
                            filterList.add("cheerful");
                            break;
                        case "2":
                            filterList.add("funny");
                            break;
                        case "3":
                            filterList.add("serious");
                            break;
                        case "4":
                            filterList.add("sincere");
                            break;
                        default:
                            moreAns = true;
                            break;
                    }
                }
            }
        }
        subscriptionArn = subQueue(snsClient, topicArn, sqsQueueArn, filterList);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Publish a message to the topic.");
        if (selectFIFO) {
            System.out.println("Would you like to add an attribute to this message?  (y/n)");
            String msgAns = in.nextLine();
            if (msgAns.compareTo("y") == 0) {
                System.out.println("You can filter messages by one or more of the following \"tone\" attributes.");
                System.out.println("1. cheerful");
                System.out.println("2. funny");
                System.out.println("3. serious");
                System.out.println("4. sincere");
                System.out.println("Select a number or choose 0 to end.");
                String ans = in.nextLine();
                switch (ans) {
                    case "1":
                        msgAttValue = "cheerful";
                        break;
                    case "2":
                        msgAttValue = "funny";
                        break;
                    case "3":
                        msgAttValue = "serious";
                        break;
                    default:
                        msgAttValue = "sincere";
                        break;
                }

                System.out.println("Selected value is " + msgAttValue);
            }
            System.out.println("Enter a message.");
            message = in.nextLine();
            pubMessageFIFO(snsClient, message, topicArn, msgAttValue, duplication, groupId, deduplicationID);

        } else {
            System.out.println("Enter a message.");
            message = in.nextLine();
            pubMessage(snsClient, message, topicArn);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Display the message. Press any key to continue.");
        in.nextLine();
        messageList = receiveMessages(sqsClient, sqsQueueUrl, msgAttValue);
        for (Message mes : messageList) {
            System.out.println("Message Id: " + mes.messageId());
            System.out.println("Full Message: " + mes.body());
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. Delete the received message. Press any key to continue.");
        in.nextLine();
        deleteMessages(sqsClient, sqsQueueUrl, messageList);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Unsubscribe from the topic and delete the queue. Press any key to continue.");
        in.nextLine();
        unSub(snsClient, subscriptionArn);
        deleteSQSQueue(sqsClient, sqsQueueName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("11. Delete the topic. Press any key to continue.");
        in.nextLine();
        deleteSNSTopic(snsClient, topicArn);

        System.out.println(DASHES);
        System.out.println("The SNS/SQS workflow has completed successfully.");
        System.out.println(DASHES);
    }

    public static void deleteSNSTopic(SnsClient snsClient, String topicArn) {
        try {
            DeleteTopicRequest request = DeleteTopicRequest.builder()
                .topicArn(topicArn)
                .build();

            DeleteTopicResponse result = snsClient.deleteTopic(request);
            System.out.println("Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteSQSQueue(SqsClient sqsClient, String queueName) {
        try {
            GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder()
                .queueName(queueName)
                .build();

            String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl();
            DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()
                .queueUrl(queueUrl)
                .build();

            sqsClient.deleteQueue(deleteQueueRequest);
            System.out.println(queueName + " was successfully deleted.");

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void unSub(SnsClient snsClient, String subscriptionArn) {
        try {
            UnsubscribeRequest request = UnsubscribeRequest.builder()
                .subscriptionArn(subscriptionArn)
                .build();

            UnsubscribeResponse result = snsClient.unsubscribe(request);
            System.out.println("Status was " + result.sdkHttpResponse().statusCode()
                + "\nSubscription was removed for " + request.subscriptionArn());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void deleteMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) {
        try {
            List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>();
            for (Message msg : messages) {
                DeleteMessageBatchRequestEntry entry = DeleteMessageBatchRequestEntry.builder()
                    .id(msg.messageId())
                    .build();

                entries.add(entry);
            }

            DeleteMessageBatchRequest deleteMessageBatchRequest = DeleteMessageBatchRequest.builder()
                .queueUrl(queueUrl)
                .entries(entries)
                .build();

            sqsClient.deleteMessageBatch(deleteMessageBatchRequest);
            System.out.println("The batch delete of messages was successful");

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl, String msgAttValue) {
        try {
            if (msgAttValue.isEmpty()) {
                ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .maxNumberOfMessages(5)
                    .build();
                return sqsClient.receiveMessage(receiveMessageRequest).messages();
            } else {
                // We know there are filters on the message.
                ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .messageAttributeNames(msgAttValue) // Include other message attributes if needed.
                    .maxNumberOfMessages(5)
                    .build();

                return sqsClient.receiveMessage(receiveRequest).messages();
            }

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return null;
    }

    public static void pubMessage(SnsClient snsClient, String message, String topicArn) {
        try {
            PublishRequest request = PublishRequest.builder()
                .message(message)
                .topicArn(topicArn)
                .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void pubMessageFIFO(SnsClient snsClient,
                                      String message,
                                      String topicArn,
                                      String msgAttValue,
                                      String duplication,
                                      String groupId,
                                      String deduplicationID) {

        try {
            PublishRequest request;
            // Means the user did not choose to use a message attribute.
            if (msgAttValue.isEmpty()) {
                if (duplication.compareTo("y") == 0) {
                    request = PublishRequest.builder()
                        .message(message)
                        .messageGroupId(groupId)
                        .topicArn(topicArn)
                        .build();
                } else {
                    request = PublishRequest.builder()
                        .message(message)
                        .messageDeduplicationId(deduplicationID)
                        .messageGroupId(groupId)
                        .topicArn(topicArn)
                        .build();
                }

            } else {
                Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
                messageAttributes.put(msgAttValue, MessageAttributeValue.builder()
                    .dataType("String")
                    .stringValue("true")
                    .build());

                if (duplication.compareTo("y") == 0) {
                    request = PublishRequest.builder()
                        .message(message)
                        .messageGroupId(groupId)
                        .topicArn(topicArn)
                        .build();
                } else {
                    // Create a publish request with the message and attributes.
                    request = PublishRequest.builder()
                        .topicArn(topicArn)
                        .message(message)
                        .messageDeduplicationId(deduplicationID)
                        .messageGroupId(groupId)
                        .messageAttributes(messageAttributes)
                        .build();
                }
            }

            // Publish the message to the topic.
            PublishResponse result = snsClient.publish(request);
            System.out
                .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    // Subscribe to the SQS queue.
    public static String subQueue(SnsClient snsClient, String topicArn, String queueArn, List<String> filterList) {
        try {
            SubscribeRequest request;
            if (filterList.isEmpty()) {
                // No filter subscription is added.
                request = SubscribeRequest.builder()
                    .protocol("sqs")
                    .endpoint(queueArn)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

                SubscribeResponse result = snsClient.subscribe(request);
                System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" +
                    "with the subscription ARN " + result.subscriptionArn());
                return result.subscriptionArn();
            } else {
                request = SubscribeRequest.builder()
                    .protocol("sqs")
                    .endpoint(queueArn)
                    .returnSubscriptionArn(true)
                    .topicArn(topicArn)
                    .build();

                SubscribeResponse result = snsClient.subscribe(request);
                System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" +
                    "with the subscription ARN " + result.subscriptionArn());

                String attributeName = "FilterPolicy";
                Gson gson = new Gson();
                String jsonString = "{\"tone\": []}";
                JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
                JsonArray toneArray = jsonObject.getAsJsonArray("tone");
                for (String value : filterList) {
                    toneArray.add(new JsonPrimitive(value));
                }

                String updatedJsonString = gson.toJson(jsonObject);
                System.out.println(updatedJsonString);
                SetSubscriptionAttributesRequest attRequest = SetSubscriptionAttributesRequest.builder()
                    .subscriptionArn(result.subscriptionArn())
                    .attributeName(attributeName)
                    .attributeValue(updatedJsonString)
                    .build();

                snsClient.setSubscriptionAttributes(attRequest);
                return result.subscriptionArn();
            }

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    // Attach a policy to the queue.
    public static void setQueueAttr(SqsClient sqsClient, String queueUrl, String policy) {
        try {
            Map<software.amazon.awssdk.services.sqs.model.QueueAttributeName, String> attrMap = new HashMap<>();
            attrMap.put(QueueAttributeName.POLICY, policy);

            SetQueueAttributesRequest attributesRequest = SetQueueAttributesRequest.builder()
                .queueUrl(queueUrl)
                .attributes(attrMap)
                .build();

            sqsClient.setQueueAttributes(attributesRequest);
            System.out.println("The policy has been successfully attached.");

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static String getSQSQueueAttrs(SqsClient sqsClient, String queueUrl) {
        // Specify the attributes to retrieve.
        List<QueueAttributeName> atts = new ArrayList<>();
        atts.add(QueueAttributeName.QUEUE_ARN);

        GetQueueAttributesRequest attributesRequest = GetQueueAttributesRequest.builder()
            .queueUrl(queueUrl)
            .attributeNames(atts)
            .build();

        GetQueueAttributesResponse response = sqsClient.getQueueAttributes(attributesRequest);
        Map<String, String> queueAtts = response.attributesAsStrings();
        for (Map.Entry<String, String> queueAtt : queueAtts.entrySet())
            return queueAtt.getValue();

        return "";
    }

    public static String createQueue(SqsClient sqsClient, String queueName, Boolean selectFIFO) {
        try {
            System.out.println("\nCreate Queue");
            if (selectFIFO) {
                Map<QueueAttributeName, String> attrs = new HashMap<>();
                attrs.put(QueueAttributeName.FIFO_QUEUE, "true");
                CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .attributes(attrs)
                    .build();

                sqsClient.createQueue(createQueueRequest);
                System.out.println("\nGet queue url");
                GetQueueUrlResponse getQueueUrlResponse = sqsClient
                    .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
                return getQueueUrlResponse.queueUrl();
            } else {
                CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .build();

                sqsClient.createQueue(createQueueRequest);
                System.out.println("\nGet queue url");
                GetQueueUrlResponse getQueueUrlResponse = sqsClient
                    .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build());
                return getQueueUrlResponse.queueUrl();
            }

        } catch (SqsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

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

    public static String createFIFO(SnsClient snsClient, String topicName, String duplication) {
        try {
            // Create a FIFO topic by using the SNS service client.
            Map<String, String> topicAttributes = new HashMap<>();
            if (duplication.compareTo("n") == 0) {
                topicAttributes.put("FifoTopic", "true");
                topicAttributes.put("ContentBasedDeduplication", "false");
            } else {
                topicAttributes.put("FifoTopic", "true");
                topicAttributes.put("ContentBasedDeduplication", "true");
            }

            CreateTopicRequest topicRequest = CreateTopicRequest.builder()
                .name(topicName)
                .attributes(topicAttributes)
                .build();

            CreateTopicResponse response = snsClient.createTopic(topicRequest);
            return response.topicArn();

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Unsubscribe)

### バッチメッセージを送受信する
<a name="sqs_Scenario_SendReceiveBatch_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon SQS キューを作成します。
+ キューにバッチメッセージを送信します。
+ キューからバッチメッセージを受信します。
+ キューからバッチメッセージを受信します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
次の例に示すように、 AWS SDK for Java 2.xを使用して、2 つの異なるアプローチで Amazon SQS のバッチメッセージ操作を処理できます。  
**SendRecvBatch.java** は明示的なバッチ操作を使用します。メッセージバッチを手動で作成し、`sendMessageBatch()` と `deleteMessageBatch()` を直接呼び出します。また、失敗したメッセージを含むバッチレスポンスも処理します。このアプローチにより、バッチサイズ設定とエラー処理を完全に制御できます。ただし、バッチ処理ロジックを管理するには、より多くのコードが必要です。  
**SimpleProducerConsumer.java** は、リクエストの自動バッチ処理に高レベルの `SqsAsyncBatchManager` ライブラリを使用します。標準クライアントと同じメソッド署名を使用して、個別の `sendMessage()` および `deleteMessage()` 呼び出しを行います。SDK はこれらの呼び出しを自動的にバッファし、バッチ操作として送信します。このアプローチでは、バッチ処理のパフォーマンス上の利点を提供しながら、コードの変更を最小限に抑えることができます。  
バッチ構成とエラー処理をきめ細かく制御する必要がある場合は、明示的なバッチ処理を使用します。コードの変更を最小限に抑えてパフォーマンスを最適化する場合は、自動バッチ処理を使用します。  
SendRecvBatch.java - メッセージで明示的なバッチ操作を使用します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.BatchResultErrorEntry;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchResponse;
import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchResultEntry;
import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.MessageAttributeValue;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse;
import software.amazon.awssdk.services.sqs.model.SendMessageBatchResultEntry;
import software.amazon.awssdk.services.sqs.model.SqsException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 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
 */

/**
 * This code demonstrates basic message operations in Amazon Simple Queue Service (Amazon SQS).
 */

public class SendRecvBatch {
    private static final Logger LOGGER = LoggerFactory.getLogger(SendRecvBatch.class);
    private static final SqsClient sqsClient = SqsClient.create();


    public static void main(String[] args) {
        usageDemo();
    }
    /**
     * Send a batch of messages in a single request to an SQS queue.
     * This request may return overall success even when some messages were not sent.
     * The caller must inspect the Successful and Failed lists in the response and
     * resend any failed messages.
     *
     * @param queueUrl  The URL of the queue to receive the messages.
     * @param messages  The messages to send to the queue. Each message contains a body and attributes.
     * @return The response from SQS that contains the list of successful and failed messages.
     */
    public static SendMessageBatchResponse sendMessages(
            String queueUrl, List<MessageEntry> messages) {

        try {
            List<SendMessageBatchRequestEntry> entries = new ArrayList<>();

            for (int i = 0; i < messages.size(); i++) {
                MessageEntry message = messages.get(i);
                entries.add(SendMessageBatchRequestEntry.builder()
                        .id(String.valueOf(i))
                        .messageBody(message.getBody())
                        .messageAttributes(message.getAttributes())
                        .build());
            }

            SendMessageBatchRequest sendBatchRequest = SendMessageBatchRequest.builder()
                    .queueUrl(queueUrl)
                    .entries(entries)
                    .build();

            SendMessageBatchResponse response = sqsClient.sendMessageBatch(sendBatchRequest);

            if (!response.successful().isEmpty()) {
                for (SendMessageBatchResultEntry resultEntry : response.successful()) {
                    LOGGER.info("Message sent: {}: {}", resultEntry.messageId(),
                            messages.get(Integer.parseInt(resultEntry.id())).getBody());
                }
            }

            if (!response.failed().isEmpty()) {
                for (BatchResultErrorEntry errorEntry : response.failed()) {
                    LOGGER.warn("Failed to send: {}: {}", errorEntry.id(),
                            messages.get(Integer.parseInt(errorEntry.id())).getBody());
                }
            }

            return response;

        } catch (SqsException e) {
            LOGGER.error("Send messages failed to queue: {}", queueUrl, e);
            throw e;
        }
    }

    /**
     * Receive a batch of messages in a single request from an SQS queue.
     *
     * @param queueUrl   The URL of the queue from which to receive messages.
     * @param maxNumber  The maximum number of messages to receive (capped at 10 by SQS).
     *                   The actual number of messages received might be less.
     * @param waitTime   The maximum time to wait (in seconds) before returning. When
     *                   this number is greater than zero, long polling is used. This
     *                   can result in reduced costs and fewer false empty responses.
     * @return The list of Message objects received. These each contain the body
     *         of the message and metadata and custom attributes.
     */
    public static List<Message> receiveMessages(String queueUrl, int maxNumber, int waitTime) {
        try {
            ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder()
                    .queueUrl(queueUrl)
                    .maxNumberOfMessages(maxNumber)
                    .waitTimeSeconds(waitTime)
                    .messageAttributeNames("All")
                    .build();

            List<Message> messages = sqsClient.receiveMessage(receiveRequest).messages();

            for (Message message : messages) {
                LOGGER.info("Received message: {}: {}", message.messageId(), message.body());
            }

            return messages;

        } catch (SqsException e) {
            LOGGER.error("Couldn't receive messages from queue: {}", queueUrl, e);
            throw e;
        }
    }

    /**
     * Delete a batch of messages from a queue in a single request.
     *
     * @param queueUrl  The URL of the queue from which to delete the messages.
     * @param messages  The list of messages to delete.
     * @return The response from SQS that contains the list of successful and failed
     *         message deletions.
     */
    public static DeleteMessageBatchResponse deleteMessages(String queueUrl, List<Message> messages) {
        try {
            List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>();

            for (int i = 0; i < messages.size(); i++) {
                entries.add(DeleteMessageBatchRequestEntry.builder()
                        .id(String.valueOf(i))
                        .receiptHandle(messages.get(i).receiptHandle())
                        .build());
            }

            DeleteMessageBatchRequest deleteRequest = DeleteMessageBatchRequest.builder()
                    .queueUrl(queueUrl)
                    .entries(entries)
                    .build();

            DeleteMessageBatchResponse response = sqsClient.deleteMessageBatch(deleteRequest);

            if (!response.successful().isEmpty()) {
                for (DeleteMessageBatchResultEntry resultEntry : response.successful()) {
                    LOGGER.info("Deleted {}", messages.get(Integer.parseInt(resultEntry.id())).receiptHandle());
                }
            }

            if (!response.failed().isEmpty()) {
                for (BatchResultErrorEntry errorEntry : response.failed()) {
                    LOGGER.warn("Could not delete {}", messages.get(Integer.parseInt(errorEntry.id())).receiptHandle());
                }
            }

            return response;

        } catch (SqsException e) {
            LOGGER.error("Couldn't delete messages from queue {}", queueUrl, e);
            throw e;
        }
    }

    /**
     * Helper class to represent a message with body and attributes.
     */
    public static class MessageEntry {
        private final String body;
        private final Map<String, MessageAttributeValue> attributes;

        public MessageEntry(String body, Map<String, MessageAttributeValue> attributes) {
            this.body = body;
            this.attributes = attributes != null ? attributes : new HashMap<>();
        }

        public String getBody() {
            return body;
        }

        public Map<String, MessageAttributeValue> getAttributes() {
            return attributes;
        }
    }

    /**
     * Shows how to:
     * * Read the lines from a file and send the lines in
     *   batches of 10 as messages to a queue.
     * * Receive the messages in batches until the queue is empty.
     * * Reassemble the lines of the file and verify they match the original file.
     */
    public static void usageDemo() {
        LOGGER.info("-".repeat(88));
        LOGGER.info("Welcome to the Amazon Simple Queue Service (Amazon SQS) demo!");
        LOGGER.info("-".repeat(88));

        String queueUrl = null;
        try {
            // Create a queue for the demo.
            String queueName = "sqs-usage-demo-message-wrapper-" + System.currentTimeMillis();
            CreateQueueRequest createRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .build();
            queueUrl = sqsClient.createQueue(createRequest).queueUrl();
            LOGGER.info("Created queue: {}", queueUrl);

            try (InputStream inputStream = SendRecvBatch.class.getResourceAsStream("/log4j2.xml");
                 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                
                List<String> lines = reader.lines().toList();

                // Send file lines in batches.
                int batchSize = 10;
                LOGGER.info("Sending file lines in batches of {} as messages.", batchSize);

                for (int i = 0; i < lines.size(); i += batchSize) {
                    List<MessageEntry> messageBatch = new ArrayList<>();

                    for (int j = i; j < Math.min(i + batchSize, lines.size()); j++) {
                        String line = lines.get(j);
                        if (line == null || line.trim().isEmpty()) {
                            continue; // Skip empty lines.
                        }

                        Map<String, MessageAttributeValue> attributes = new HashMap<>();
                        attributes.put("line", MessageAttributeValue.builder()
                                .dataType("String")
                                .stringValue(String.valueOf(j))
                                .build());

                        messageBatch.add(new MessageEntry(lines.get(j), attributes));
                    }

                    sendMessages(queueUrl, messageBatch);
                    System.out.print(".");
                    System.out.flush();
                }

                LOGGER.info("\nDone. Sent {} messages.", lines.size());

                // Receive and process messages.
                LOGGER.info("Receiving, handling, and deleting messages in batches of {}.", batchSize);
                String[] receivedLines = new String[lines.size()];
                boolean moreMessages = true;

                while (moreMessages) {
                    List<Message> receivedMessages = receiveMessages(queueUrl, batchSize, 5);

                    for (Message message : receivedMessages) {
                        int lineNumber = Integer.parseInt(message.messageAttributes().get("line").stringValue());
                        receivedLines[lineNumber] = message.body();
                    }

                    if (!receivedMessages.isEmpty()) {
                        deleteMessages(queueUrl, receivedMessages);
                    } else {
                        moreMessages = false;
                    }
                }

                LOGGER.info("\nDone.");

                // Verify that all lines were received correctly.
                boolean allLinesMatch = true;
                for (int i = 0; i < lines.size(); i++) {
                    String originalLine = lines.get(i);
                    String receivedLine = receivedLines[i] == null ? "" : receivedLines[i];

                    if (!originalLine.equals(receivedLine)) {
                        allLinesMatch = false;
                        break;
                    }
                }

                if (allLinesMatch) {
                    LOGGER.info("Successfully reassembled all file lines!");
                } else {
                    LOGGER.info("Uh oh, some lines were missed!");
                }
            }
        } catch (SqsException e) {
            LOGGER.error("SQS operation failed", e);
        } catch (RuntimeException | IOException e) {
            LOGGER.error("Unexpected runtime error during demo", e);
        } finally {
            // Clean up by deleting the queue if it was created.
            if (queueUrl != null) {
                try {
                    DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder()
                            .queueUrl(queueUrl)
                            .build();
                    sqsClient.deleteQueue(deleteQueueRequest);
                    LOGGER.info("Deleted queue: {}", queueUrl);
                } catch (SqsException e) {
                    LOGGER.error("Failed to delete queue: {}", queueUrl, e);
                }
            }
        }

        LOGGER.info("Thanks for watching!");
        LOGGER.info("-".repeat(88));
    }
 }
```
SimpleProducerConsumer.java - メッセージの自動バッチ処理を使用します。  

```
package com.example.sqs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.sqs.SqsAsyncClient;
import software.amazon.awssdk.services.sqs.batchmanager.SqsAsyncBatchManager;
import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest;
import software.amazon.awssdk.services.sqs.model.DeleteMessageResponse;
import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest;
import software.amazon.awssdk.services.sqs.model.Message;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest;
import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse;
import software.amazon.awssdk.services.sqs.model.SendMessageRequest;
import software.amazon.awssdk.services.sqs.model.SendMessageResponse;
import software.amazon.awssdk.core.exception.SdkException;

import java.math.BigInteger;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Demonstrates the AWS SDK for Java 2.x Automatic Request Batching API for Amazon SQS.
 * 
 * This example showcases the high-level SqsAsyncBatchManager library that provides
 * efficient batching and buffering for SQS operations. The batch manager offers
 * methods that directly mirror SqsAsyncClient methods—sendMessage, changeMessageVisibility,
 * deleteMessage, and receiveMessage—making it a drop-in replacement with minimal code changes.
 * 
 * Key features of the SqsAsyncBatchManager:
 * - Automatic batching: The SDK automatically buffers individual requests and sends them
 *   as batches when maxBatchSize (default: 10) or sendRequestFrequency (default: 200ms) 
 *   thresholds are reached
 * - Familiar API: Method signatures match SqsAsyncClient exactly, requiring no learning curve
 * - Background optimization: The batch manager maintains internal buffers and handles
 *   batching logic transparently
 * - Asynchronous operations: All methods return CompletableFuture for non-blocking execution
 * 
 * Performance benefits demonstrated:
 * - Reduced API calls: Multiple individual requests are consolidated into single batch operations
 * - Lower costs: Fewer API calls result in reduced SQS charges
 * - Higher throughput: Batch operations process more messages per second
 * - Efficient resource utilization: Fewer network round trips and better connection reuse
 * 
 * This example compares:
 * 1. Single-message operations using SqsAsyncClient directly
 * 2. Batch operations using SqsAsyncBatchManager with identical method calls
 * 
 * Usage patterns:
 * - Set batch size to 1 to use SqsAsyncClient for baseline performance measurement
 * - Set batch size > 1 to use SqsAsyncBatchManager for optimized batch processing
 * - Monitor real-time throughput metrics to observe performance improvements
 * 
 * Prerequisites:
 * - AWS SDK for Java 2.x version 2.28.0 or later
 * - An existing SQS queue
 * - Valid AWS credentials configured
 * 
 * The program displays real-time metrics showing the dramatic performance difference
 * between individual operations and automatic batching.
 */
public class SimpleProducerConsumer {

    // The maximum runtime of the program.
    private final static int MAX_RUNTIME_MINUTES = 60;
    private final static Logger log = LoggerFactory.getLogger(SimpleProducerConsumer.class);

    /**
     * Runs the SQS batching demonstration with user-configured parameters.
     * 
     * Prompts for queue name, thread counts, batch size, message size, and runtime.
     * Creates producer and consumer threads to demonstrate batching performance.
     * 
     * @param args command line arguments (not used)
     * @throws InterruptedException if thread operations are interrupted
     */
    public static void main(String[] args) throws InterruptedException {

        final Scanner input = new Scanner(System.in);

        System.out.print("Enter the queue name: ");
        final String queueName = input.nextLine();

        System.out.print("Enter the number of producers: ");
        final int producerCount = input.nextInt();

        System.out.print("Enter the number of consumers: ");
        final int consumerCount = input.nextInt();

        System.out.print("Enter the number of messages per batch: ");
        final int batchSize = input.nextInt();

        System.out.print("Enter the message size in bytes: ");
        final int messageSizeByte = input.nextInt();

        System.out.print("Enter the run time in minutes: ");
        final int runTimeMinutes = input.nextInt();

        // Create SQS async client and batch manager for all operations.
        // The SqsAsyncBatchManager is created from the SqsAsyncClient using the
        // batchManager() factory method, which provides default batching configuration.
        // This high-level library automatically handles request buffering and batching
        // while maintaining the same method signatures as SqsAsyncClient.
        final SqsAsyncClient sqsAsyncClient = SqsAsyncClient.create();
        final SqsAsyncBatchManager batchManager = sqsAsyncClient.batchManager();

        final String queueUrl = sqsAsyncClient.getQueueUrl(GetQueueUrlRequest.builder()
                .queueName(queueName)
                .build()).join().queueUrl();

        // The flag used to stop producer, consumer, and monitor threads.
        final AtomicBoolean stop = new AtomicBoolean(false);

        // Start the producers.
        final AtomicInteger producedCount = new AtomicInteger();
        final Thread[] producers = new Thread[producerCount];
        for (int i = 0; i < producerCount; i++) {
            if (batchSize == 1) {
                producers[i] = new Producer(sqsAsyncClient, queueUrl, messageSizeByte,
                        producedCount, stop);
            } else {
                producers[i] = new BatchProducer(batchManager, queueUrl, batchSize,
                        messageSizeByte, producedCount, stop);
            }
            producers[i].start();
        }

        // Start the consumers.
        final AtomicInteger consumedCount = new AtomicInteger();
        final Thread[] consumers = new Thread[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            if (batchSize == 1) {
                consumers[i] = new Consumer(sqsAsyncClient, queueUrl, consumedCount, stop);
            } else {
                consumers[i] = new BatchConsumer(batchManager, queueUrl, batchSize,
                        consumedCount, stop);
            }
            consumers[i].start();
        }

        // Start the monitor thread.
        final Thread monitor = new Monitor(producedCount, consumedCount, stop);
        monitor.start();

        // Wait for the specified amount of time then stop.
        Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes,
                MAX_RUNTIME_MINUTES)));
        stop.set(true);

        // Join all threads.
        for (int i = 0; i < producerCount; i++) {
            producers[i].join();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumers[i].join();
        }

        monitor.interrupt();
        monitor.join();

        // Close resources
        batchManager.close();
        sqsAsyncClient.close();
    }

    /**
     * Creates a random string of approximately the specified size in bytes.
     * 
     * @param sizeByte the target size in bytes for the generated string
     * @return a random string encoded in base-32
     */
    private static String makeRandomString(int sizeByte) {
        final byte[] bs = new byte[(int) Math.ceil(sizeByte * 5 / 8)];
        new Random().nextBytes(bs);
        bs[0] = (byte) ((bs[0] | 64) & 127);
        return new BigInteger(bs).toString(32);
    }

    /**
     * Sends messages individually using SqsAsyncClient for baseline performance measurement.
     * 
     * This producer demonstrates traditional single-message operations without batching.
     * Each sendMessage() call results in a separate API request to SQS, providing
     * a performance baseline for comparison with the batch operations.
     * 
     * The sendMessage() method signature is identical to SqsAsyncBatchManager.sendMessage(),
     * showing how the high-level batching library maintains API compatibility while
     * adding automatic optimization behind the scenes.
     */
    private static class Producer extends Thread {
        final SqsAsyncClient sqsAsyncClient;
        final String queueUrl;
        final AtomicInteger producedCount;
        final AtomicBoolean stop;
        final String theMessage;

        /**
         * Creates a producer thread for single-message operations.
         * 
         * @param sqsAsyncClient the SQS client for sending messages
         * @param queueUrl the URL of the target queue
         * @param messageSizeByte the size of messages to generate
         * @param producedCount shared counter for tracking sent messages
         * @param stop shared flag to signal thread termination
         */
        Producer(SqsAsyncClient sqsAsyncClient, String queueUrl, int messageSizeByte,
                 AtomicInteger producedCount, AtomicBoolean stop) {
            this.sqsAsyncClient = sqsAsyncClient;
            this.queueUrl = queueUrl;
            this.producedCount = producedCount;
            this.stop = stop;
            this.theMessage = makeRandomString(messageSizeByte);
        }

        /**
         * Continuously sends messages until the stop flag is set.
         * 
         * Uses SqsAsyncClient.sendMessage() directly, resulting in one API call per message.
         * This approach provides baseline performance metrics for comparison with batching.
         * Each call blocks until the individual message is sent, demonstrating traditional
         * one-request-per-operation behavior.
         */
        public void run() {
            try {
                while (!stop.get()) {
                    sqsAsyncClient.sendMessage(SendMessageRequest.builder()
                            .queueUrl(queueUrl)
                            .messageBody(theMessage)
                            .build()).join();
                    producedCount.incrementAndGet();
                }
            } catch (SdkException | java.util.concurrent.CompletionException e) {
                // Handle both SdkException and CompletionException from async operations.
                // If this unlikely condition occurs, stop.
                log.error("Producer: " + e.getMessage());
                System.exit(1);
            }
        }
    }

    /**
     * Sends messages using SqsAsyncBatchManager for automatic request batching and optimization.
     * 
     * This producer demonstrates the AWS SDK for Java 2.x high-level batching library.
     * The SqsAsyncBatchManager automatically buffers individual sendMessage() calls and
     * sends them as batches when thresholds are reached:
     * - maxBatchSize: Maximum 10 messages per batch (default)
     * - sendRequestFrequency: 200ms timeout before sending partial batches (default)
     * 
     * Key advantages of the batching approach:
     * - Identical API: batchManager.sendMessage() has the same signature as sqsAsyncClient.sendMessage()
     * - Automatic optimization: No code changes needed to benefit from batching
     * - Transparent buffering: The SDK handles batching logic internally
     * - Reduced API calls: Multiple messages sent in single batch requests
     * - Lower costs: Fewer API calls result in reduced SQS charges
     * - Higher throughput: Batch operations process significantly more messages per second
     */
    private static class BatchProducer extends Thread {
        final SqsAsyncBatchManager batchManager;
        final String queueUrl;
        final int batchSize;
        final AtomicInteger producedCount;
        final AtomicBoolean stop;
        final String theMessage;

        /**
         * Creates a producer thread for batch operations.
         * 
         * @param batchManager the batch manager for efficient message sending
         * @param queueUrl the URL of the target queue
         * @param batchSize the number of messages to send per batch
         * @param messageSizeByte the size of messages to generate
         * @param producedCount shared counter for tracking sent messages
         * @param stop shared flag to signal thread termination
         */
        BatchProducer(SqsAsyncBatchManager batchManager, String queueUrl, int batchSize,
                      int messageSizeByte, AtomicInteger producedCount,
                      AtomicBoolean stop) {
            this.batchManager = batchManager;
            this.queueUrl = queueUrl;
            this.batchSize = batchSize;
            this.producedCount = producedCount;
            this.stop = stop;
            this.theMessage = makeRandomString(messageSizeByte);
        }

        /**
         * Continuously sends batches of messages using the high-level batching library.
         * 
         * Notice how batchManager.sendMessage() uses the exact same method signature
         * and request builder pattern as SqsAsyncClient.sendMessage(). This demonstrates
         * the drop-in replacement capability of the SqsAsyncBatchManager.
         * 
         * The SDK automatically:
         * - Buffers individual sendMessage() calls internally
         * - Groups them into batch requests when thresholds are met
         * - Sends SendMessageBatchRequest operations to SQS
         * - Returns individual CompletableFuture responses for each message
         * 
         * This transparent batching provides significant performance improvements
         * without requiring changes to application logic or error handling patterns.
         */
        public void run() {
            try {
                while (!stop.get()) {
                    // Send multiple messages using the high-level batch manager.
                    // Each batchManager.sendMessage() call uses identical syntax to
                    // sqsAsyncClient.sendMessage(), demonstrating API compatibility.
                    // The SDK automatically buffers these calls and sends them as
                    // batch operations when maxBatchSize (10) or sendRequestFrequency (200ms)
                    // thresholds are reached, significantly improving throughput.
                    for (int i = 0; i < batchSize; i++) {
                        CompletableFuture<SendMessageResponse> future = batchManager.sendMessage(
                                SendMessageRequest.builder()
                                        .queueUrl(queueUrl)
                                        .messageBody(theMessage)
                                        .build());
                        
                        // Handle the response asynchronously
                        future.whenComplete((response, throwable) -> {
                            if (throwable == null) {
                                producedCount.incrementAndGet();
                            } else if (!(throwable instanceof java.util.concurrent.CancellationException) &&
                                      !(throwable.getMessage() != null && throwable.getMessage().contains("executor not accepting a task"))) {
                                log.error("BatchProducer: Failed to send message", throwable);
                            }
                            // Ignore CancellationException and executor shutdown errors - expected during shutdown
                        });
                    }
                    
                    // Small delay to allow batching to occur
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("BatchProducer interrupted: " + e.getMessage());
            } catch (SdkException | java.util.concurrent.CompletionException e) {
                log.error("BatchProducer: " + e.getMessage());
                System.exit(1);
            }
        }
    }

    /**
     * Receives and deletes messages individually using SqsAsyncClient for baseline measurement.
     * 
     * This consumer demonstrates traditional single-message operations without batching.
     * Each receiveMessage() and deleteMessage() call results in separate API requests,
     * providing a performance baseline for comparison with batch operations.
     * 
     * The method signatures are identical to SqsAsyncBatchManager methods:
     * - receiveMessage() matches batchManager.receiveMessage()
     * - deleteMessage() matches batchManager.deleteMessage()
     * 
     * This API consistency allows easy migration to the high-level batching library.
     */
    private static class Consumer extends Thread {
        final SqsAsyncClient sqsAsyncClient;
        final String queueUrl;
        final AtomicInteger consumedCount;
        final AtomicBoolean stop;

        /**
         * Creates a consumer thread for single-message operations.
         * 
         * @param sqsAsyncClient the SQS client for receiving messages
         * @param queueUrl the URL of the source queue
         * @param consumedCount shared counter for tracking processed messages
         * @param stop shared flag to signal thread termination
         */
        Consumer(SqsAsyncClient sqsAsyncClient, String queueUrl, AtomicInteger consumedCount,
                 AtomicBoolean stop) {
            this.sqsAsyncClient = sqsAsyncClient;
            this.queueUrl = queueUrl;
            this.consumedCount = consumedCount;
            this.stop = stop;
        }

        /**
         * Continuously receives and deletes messages using traditional single-request operations.
         * 
         * Uses SqsAsyncClient methods directly:
         * - receiveMessage(): One API call per receive operation
         * - deleteMessage(): One API call per delete operation
         * 
         * This approach demonstrates the baseline performance without batching optimization.
         * Compare these method calls with the identical signatures used in BatchConsumer
         * to see how the high-level batching library maintains API compatibility.
         */
        public void run() {
            try {
                while (!stop.get()) {
                    try {
                        final ReceiveMessageResponse result = sqsAsyncClient.receiveMessage(
                                ReceiveMessageRequest.builder()
                                        .queueUrl(queueUrl)
                                        .build()).join();

                        if (!result.messages().isEmpty()) {
                            final Message m = result.messages().get(0);
                            // Note: deleteMessage() signature identical to batchManager.deleteMessage()
                            sqsAsyncClient.deleteMessage(DeleteMessageRequest.builder()
                                    .queueUrl(queueUrl)
                                    .receiptHandle(m.receiptHandle())
                                    .build()).join();
                            consumedCount.incrementAndGet();
                        }
                    } catch (SdkException | java.util.concurrent.CompletionException e) {
                        log.error(e.getMessage());
                    }
                }
            } catch (SdkException | java.util.concurrent.CompletionException e) {
                // Handle both SdkException and CompletionException from async operations.
                // If this unlikely condition occurs, stop.
                log.error("Consumer: " + e.getMessage());
                System.exit(1);
            }
        }
    }

    /**
     * Receives and deletes messages using SqsAsyncBatchManager for automatic optimization.
     * 
     * This consumer demonstrates the AWS SDK for Java 2.x high-level batching library
     * for message consumption. The SqsAsyncBatchManager provides two key optimizations:
     * 
     * 1. Receive optimization: Maintains an internal buffer of messages fetched in the
     *    background, so receiveMessage() calls return immediately from the buffer
     * 2. Delete batching: Automatically buffers deleteMessage() calls and sends them
     *    as DeleteMessageBatchRequest operations when thresholds are reached
     * 
     * Key features:
     * - Identical API: receiveMessage() and deleteMessage() have the same signatures
     *   as SqsAsyncClient methods, making this a true drop-in replacement
     * - Background fetching: The batch manager continuously fetches messages to keep
     *   the internal buffer populated, reducing receive latency
     * - Automatic delete batching: Individual deleteMessage() calls are buffered and
     *   sent as batch operations (up to 10 per batch, 200ms frequency)
     * - Transparent optimization: No application logic changes needed to benefit
     * 
     * Performance benefits:
     * - Reduced API calls through automatic batching of delete operations
     * - Lower latency for receives due to background message buffering
     * - Higher overall throughput with fewer network round trips
     */
    private static class BatchConsumer extends Thread {
        final SqsAsyncBatchManager batchManager;
        final String queueUrl;
        final int batchSize;
        final AtomicInteger consumedCount;
        final AtomicBoolean stop;

        /**
         * Creates a consumer thread for batch operations.
         * 
         * @param batchManager the batch manager for efficient message processing
         * @param queueUrl the URL of the source queue
         * @param batchSize the maximum number of messages to receive per batch
         * @param consumedCount shared counter for tracking processed messages
         * @param stop shared flag to signal thread termination
         */
        BatchConsumer(SqsAsyncBatchManager batchManager, String queueUrl, int batchSize,
                      AtomicInteger consumedCount, AtomicBoolean stop) {
            this.batchManager = batchManager;
            this.queueUrl = queueUrl;
            this.batchSize = batchSize;
            this.consumedCount = consumedCount;
            this.stop = stop;
        }

        /**
         * Continuously receives and deletes messages using the high-level batching library.
         * 
         * Demonstrates the key advantage of SqsAsyncBatchManager: identical method signatures
         * with automatic optimization. Notice how:
         * 
         * - batchManager.receiveMessage() uses the same syntax as sqsAsyncClient.receiveMessage()
         * - batchManager.deleteMessage() uses the same syntax as sqsAsyncClient.deleteMessage()
         * 
         * Behind the scenes, the batch manager:
         * 1. Maintains an internal message buffer populated by background fetching
         * 2. Returns messages immediately from the buffer (reduced latency)
         * 3. Automatically batches deleteMessage() calls into DeleteMessageBatchRequest operations
         * 4. Sends batch deletes when maxBatchSize (10) or sendRequestFrequency (200ms) is reached
         * 
         * This provides significant performance improvements with zero code changes
         * compared to traditional SqsAsyncClient usage patterns.
         */
        public void run() {
            try {
                while (!stop.get()) {
                    // Receive messages using the high-level batch manager.
                    // This call uses identical syntax to sqsAsyncClient.receiveMessage()
                    // but benefits from internal message buffering for improved performance.
                    final ReceiveMessageResponse result = batchManager.receiveMessage(
                            ReceiveMessageRequest.builder()
                                    .queueUrl(queueUrl)
                                    .maxNumberOfMessages(Math.min(batchSize, 10))
                                    .build()).join();

                    if (!result.messages().isEmpty()) {
                        final List<Message> messages = result.messages();
                        
                        // Delete messages using the batch manager.
                        // Each deleteMessage() call uses identical syntax to SqsAsyncClient
                        // but the SDK automatically buffers these calls and sends them
                        // as DeleteMessageBatchRequest operations for optimal performance.
                        for (Message message : messages) {
                            CompletableFuture<DeleteMessageResponse> future = batchManager.deleteMessage(
                                    DeleteMessageRequest.builder()
                                            .queueUrl(queueUrl)
                                            .receiptHandle(message.receiptHandle())
                                            .build());
                            
                            future.whenComplete((response, throwable) -> {
                                if (throwable == null) {
                                    consumedCount.incrementAndGet();
                                } else if (!(throwable instanceof java.util.concurrent.CancellationException) &&
                                          !(throwable.getMessage() != null && throwable.getMessage().contains("executor not accepting a task"))) {
                                    log.error("BatchConsumer: Failed to delete message", throwable);
                                }
                                // Ignore CancellationException and executor shutdown errors - expected during shutdown
                            });
                        }
                    }
                    
                    // Small delay to prevent tight polling
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                log.error("BatchConsumer interrupted: " + e.getMessage());
            } catch (SdkException | java.util.concurrent.CompletionException e) {
                // Handle both SdkException and CompletionException from async operations.
                // If this unlikely condition occurs, stop.
                log.error("BatchConsumer: " + e.getMessage());
                System.exit(1);
            }
        }
    }

    /**
     * Displays real-time throughput statistics every second.
     * 
     * This thread logs the current count of produced and consumed messages
     * to help you monitor the performance comparison.
     */
    private static class Monitor extends Thread {
        private final AtomicInteger producedCount;
        private final AtomicInteger consumedCount;
        private final AtomicBoolean stop;

        /**
         * Creates a monitoring thread that displays throughput statistics.
         * 
         * @param producedCount shared counter for messages sent
         * @param consumedCount shared counter for messages processed
         * @param stop shared flag to signal thread termination
         */
        Monitor(AtomicInteger producedCount, AtomicInteger consumedCount,
                AtomicBoolean stop) {
            this.producedCount = producedCount;
            this.consumedCount = consumedCount;
            this.stop = stop;
        }

        /**
         * Logs throughput statistics every second until stopped.
         * 
         * Displays the current count of produced and consumed messages
         * to help monitor the performance comparison between batching strategies.
         */
        public void run() {
            try {
                while (!stop.get()) {
                    Thread.sleep(1000);
                    log.info("produced messages = " + producedCount.get()
                            + ", consumed messages = " + consumedCount.get());
                }
            } catch (InterruptedException e) {
                // Allow the thread to exit.
            }
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/CreateQueue)
  + [DeleteMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteMessage)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteQueue)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ReceiveMessage)
  + [SendMessage](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SendMessage)
  + [SendMessageBatch](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/SendMessageBatch)

### Amazon SQS Java Messaging Library を使用して JMS インターフェイスを操作する
<a name="sqs_Scenario_UseJMS_java_2_topic"></a>

次のコード例は、Amazon SQS Java Messaging Library を使用して JMS インターフェイスを操作する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
次の例は、標準の Amazon SQS キューで動作し、以下を含みます。  
+ テキストメッセージの送信。
+ 同期的なメッセージの受信。
+ 非同期的なメッセージの受信。
+ CLIENT\$1ACKNOWLEDGE モードを使用したメッセージの受信。
+ UNORDERED\$1ACKNOWLEDGE モードを使用したメッセージの受信。
+ Spring を使用した依存関係の注入。
+ 他の例で使用される一般的なメソッドを提供するユーティリティクラス。
JMS を Amazon SQS で使用する方法の詳細については、「[Amazon SQS デベロッパーガイド](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-java-message-service-jms-client.html)」を参照してください。  
テキストメッセージの送信。  

```
    /**
     * This method establishes a connection to a standard Amazon SQS queue using the Amazon SQS
     * Java Messaging Library and sends text messages to it. It uses JMS (Java Message Service) API
     * with automatic acknowledgment mode to ensure reliable message delivery, and automatically
     * manages all messaging resources.
     *
     * @throws JMSException If there is a problem connecting to or sending messages to the queue
     */
    public static void doSendTextMessage() throws JMSException {
        // Create a connection factory.
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                SqsClient.create()
        );

        // Create the connection in a try-with-resources statement so that it's closed automatically.
        try (SQSConnection connection = connectionFactory.createConnection()) {

            // Create the queue if needed.
            SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT);

            // Create a session that uses the JMS auto-acknowledge mode.
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME));

            createAndSendMessages(session, producer);
        } // The connection closes automatically. This also closes the session.
        LOGGER.info("Connection closed");
    }

    /**
     * This method reads text input from the keyboard and sends each line as a separate message
     * to a standard Amazon SQS queue using the Amazon SQS Java Messaging Library. It continues
     * to accept input until the user enters an empty line, using JMS (Java Message Service) API to
     * handle the message delivery.
     *
     * @param session The JMS session used to create messages
     * @param producer The JMS message producer used to send messages to the queue
     */
    private static void createAndSendMessages(Session session, MessageProducer producer) {
        BufferedReader inputReader = new BufferedReader(
                new InputStreamReader(System.in, Charset.defaultCharset()));

        try {
            String input;
            while (true) {
                LOGGER.info("Enter message to send (leave empty to exit): ");
                input = inputReader.readLine();
                if (input == null || input.isEmpty()) break;

                TextMessage message = session.createTextMessage(input);
                producer.send(message);
                LOGGER.info("Send message {}", message.getJMSMessageID());
            }
        } catch (EOFException e) {
            // Just return on EOF
        } catch (IOException e) {
            LOGGER.error("Failed reading input: {}", e.getMessage(), e);
        } catch (JMSException e) {
            LOGGER.error("Failed sending message: {}", e.getMessage(), e);
        }
    }
```
同期的なメッセージの受信。  

```
    /**
     * This method receives messages from a standard Amazon SQS queue using the Amazon SQS Java
     * Messaging Library. It creates a connection to the queue using JMS (Java Message Service),
     * waits for messages to arrive, and processes them one at a time. The method handles all
     * necessary setup and cleanup of messaging resources.
     *
     * @throws JMSException If there is a problem connecting to or receiving messages from the queue
     */
    public static void doReceiveMessageSync() throws JMSException {
        // Create a connection factory.
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                SqsClient.create()
        );

        // Create a connection.
        try (SQSConnection connection = connectionFactory.createConnection() ) {

            // Create the queue if needed.
            SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT);

            // Create a session.
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME));

            connection.start();

            receiveMessages(consumer);
        }  // The connection closes automatically. This also closes the session.
        LOGGER.info("Connection closed");
    }

    /**
     * This method continuously checks for new messages from a standard Amazon SQS queue using
     * the Amazon SQS Java Messaging Library. It waits up to 20 seconds for each message, processes
     * it using JMS (Java Message Service), and confirms receipt. The method stops checking for
     * messages after 20 seconds of no activity.
     *
     * @param consumer The JMS message consumer that receives messages from the queue
     */
    private static void receiveMessages(MessageConsumer consumer) {
        try {
            while (true) {
                LOGGER.info("Waiting for messages...");
                // Wait 1 minute for a message
                Message message = consumer.receive(Duration.ofSeconds(20).toMillis());
                if (message == null) {
                    LOGGER.info("Shutting down after 20 seconds of silence.");
                    break;
                }
                SqsJmsExampleUtils.handleMessage(message);
                message.acknowledge();
                LOGGER.info("Acknowledged message {}", message.getJMSMessageID());
            }
        } catch (JMSException e) {
            LOGGER.error("Error receiving from SQS: {}", e.getMessage(), e);
        }
    }
```
非同期的なメッセージの受信。  

```
    /**
     * This method sets up automatic message handling for a standard Amazon SQS queue using the
     * Amazon SQS Java Messaging Library. It creates a listener that processes messages as soon
     * as they arrive using JMS (Java Message Service), runs for 5 seconds, then cleans up all
     * messaging resources.
     *
     * @throws JMSException If there is a problem connecting to or receiving messages from the queue
     */
    public static void doReceiveMessageAsync() throws JMSException {
        // Create a connection factory.
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                SqsClient.create()
        );

        // Create a connection.
        try (SQSConnection connection = connectionFactory.createConnection() ) {

            // Create the queue if needed.
            SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT);

            // Create a session.
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

            try {
                // Create a consumer for the queue.
                MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME));
                // Provide an implementation of the MessageListener interface, which has a single 'onMessage' method.
                // We use a lambda expression for the implementation.
                consumer.setMessageListener(message -> {
                    try {
                        SqsJmsExampleUtils.handleMessage(message);
                        message.acknowledge();
                    } catch (JMSException e) {
                        LOGGER.error("Error processing message: {}", e.getMessage());
                    }
                });
                // Start receiving incoming messages.
                connection.start();
                LOGGER.info("Waiting for messages...");
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }  // The connection closes automatically. This also closes the session.
        LOGGER.info( "Connection closed" );
    }
```
CLIENT\$1ACKNOWLEDGE モードを使用したメッセージの受信。  

```
    /**
     * This method demonstrates how message acknowledgment affects message processing in a standard
     * Amazon SQS queue using the Amazon SQS Java Messaging Library. It sends messages to the queue,
     * then shows how JMS (Java Message Service) client acknowledgment mode handles both explicit
     * and implicit message confirmations, including how acknowledging one message can automatically
     * acknowledge previous messages.
     *
     * @throws JMSException If there is a problem with the messaging operations
     */
    public static void doReceiveMessagesSyncClientAcknowledge() throws JMSException {
        // Create a connection factory.
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                SqsClient.create()
        );

        // Create the connection in a try-with-resources statement so that it's closed automatically.
        try (SQSConnection connection = connectionFactory.createConnection() ) {

            // Create the queue if needed.
            SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, TIME_OUT_SECONDS);

            // Create a session with client acknowledge mode.
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

            // Create a producer and consumer.
            MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME));
            MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME));

            // Open the connection.
            connection.start();

            // Send two text messages.
            sendMessage(producer, session, "Message 1");
            sendMessage(producer, session, "Message 2");

            // Receive a message and don't acknowledge it.
            receiveMessage(consumer, false);

            // Receive another message and acknowledge it.
            receiveMessage(consumer, true);

            // Wait for the visibility time out, so that unacknowledged messages reappear in the queue,
            LOGGER.info("Waiting for visibility timeout...");
            try {
                Thread.sleep(TIME_OUT_MILLIS);
            } catch (InterruptedException e) {
                LOGGER.error("Interrupted while waiting for visibility timeout", e);
                Thread.currentThread().interrupt();
                throw new RuntimeException("Processing interrupted", e);
            }

            /*  We will attempt to receive another message, but none will be available. This is because in
                CLIENT_ACKNOWLEDGE mode, when we acknowledged the second message, all previous messages were
                automatically acknowledged as well. Therefore, although we never directly acknowledged the first
                message, it was implicitly acknowledged when we confirmed the second one. */
            receiveMessage(consumer, true);
        } // The connection closes automatically. This also closes the session.
        LOGGER.info("Connection closed.");

    }


    /**
     * Sends a text message using the specified JMS MessageProducer and Session.
     *
     * @param producer    The JMS MessageProducer used to send the message
     * @param session     The JMS Session used to create the text message
     * @param messageText The text content to be sent in the message
     * @throws JMSException If there is an error creating or sending the message
     */
    private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException {
        // Create a text message and send it.
        producer.send(session.createTextMessage(messageText));
    }

    /**
     * Receives and processes a message from a JMS queue using the specified consumer.
     * The method waits for a message until the configured timeout period is reached.
     * If a message is received, it is logged and optionally acknowledged based on the
     * acknowledge parameter.
     *
     * @param consumer    The JMS MessageConsumer used to receive messages from the queue
     * @param acknowledge Boolean flag indicating whether to acknowledge the message.
     *                    If true, the message will be acknowledged after processing
     * @throws JMSException If there is an error receiving, processing, or acknowledging the message
     */
    private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException {
        // Receive a message.
        Message message = consumer.receive(TIME_OUT_MILLIS);

        if (message == null) {
            LOGGER.info("Queue is empty!");
        } else {
            // Since this queue has only text messages, cast the message object and print the text.
            LOGGER.info("Received: {}    Acknowledged: {}", ((TextMessage) message).getText(), acknowledge);

            // Acknowledge the message if asked.
            if (acknowledge) message.acknowledge();
        }
    }
```
UNORDERED\$1ACKNOWLEDGE モードを使用したメッセージの受信。  

```
    /**
     * Demonstrates message acknowledgment behavior in UNORDERED_ACKNOWLEDGE mode with Amazon SQS JMS.
     * In this mode, each message must be explicitly acknowledged regardless of receive order.
     * Unacknowledged messages return to the queue after the visibility timeout expires,
     * unlike CLIENT_ACKNOWLEDGE mode where acknowledging one message acknowledges all previous messages.
     *
     * @throws JMSException         If a JMS-related error occurs during message operations
     */
    public static void doReceiveMessagesUnorderedAcknowledge() throws JMSException {
        // Create a connection factory.
        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                SqsClient.create()
        );

        // Create the connection in a try-with-resources statement so that it's closed automatically.
        try( SQSConnection connection = connectionFactory.createConnection() ) {

            // Create the queue if needed.
            SqsJmsExampleUtils.ensureQueueExists(connection, QUEUE_NAME, TIME_OUT_SECONDS);

            // Create a session with unordered acknowledge mode.
            Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE);

            // Create the producer and consumer.
            MessageProducer producer = session.createProducer(session.createQueue(QUEUE_NAME));
            MessageConsumer consumer = session.createConsumer(session.createQueue(QUEUE_NAME));

            // Open a connection.
            connection.start();

            // Send two text messages.
            sendMessage(producer, session, "Message 1");
            sendMessage(producer, session, "Message 2");

            // Receive a message and don't acknowledge it.
            receiveMessage(consumer, false);

            // Receive another message and acknowledge it.
            receiveMessage(consumer, true);

            // Wait for the visibility time out, so that unacknowledged messages reappear in the queue.
            LOGGER.info("Waiting for visibility timeout...");
            try {
                Thread.sleep(TIME_OUT_MILLIS);
            } catch (InterruptedException e) {
                LOGGER.error("Interrupted while waiting for visibility timeout", e);
                Thread.currentThread().interrupt();
                throw new RuntimeException("Processing interrupted", e);
            }

            /*  We will attempt to receive another message, and we'll get the first message again. This occurs
                because in UNORDERED_ACKNOWLEDGE mode, each message requires its own separate acknowledgment.
                Since we only acknowledged the second message, the first message remains in the queue for
                redelivery. */
            receiveMessage(consumer, true);

            LOGGER.info("Connection closed.");
        } // The connection closes automatically. This also closes the session.
    }

    /**
     * Sends a text message to an Amazon SQS queue using JMS.
     *
     * @param producer    The JMS MessageProducer for the queue
     * @param session     The JMS Session for message creation
     * @param messageText The message content
     * @throws JMSException If message creation or sending fails
     */
    private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException {
        // Create a text message and send it.
        producer.send(session.createTextMessage(messageText));
    }
    /**
     * Synchronously receives a message from an Amazon SQS queue using the JMS API
     * with an acknowledgment parameter.
     *
     * @param consumer    The JMS MessageConsumer for the queue
     * @param acknowledge If true, acknowledges the message after receipt
     * @throws JMSException If message reception or acknowledgment fails
     */
    private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException {
        // Receive a message.
        Message message = consumer.receive(TIME_OUT_MILLIS);

        if (message == null) {
            LOGGER.info("Queue is empty!");
        } else {
            // Since this queue has only text messages, cast the message object and print the text.
            LOGGER.info("Received: {}    Acknowledged: {}", ((TextMessage) message).getText(), acknowledge);

            // Acknowledge the message if asked.
            if (acknowledge) message.acknowledge();
        }
    }
```
Spring を使用した依存関係の注入。  

```
package com.example.sqs.jms.spring;

import com.amazon.sqs.javamessaging.SQSConnection;
import com.example.sqs.jms.SqsJmsExampleUtils;
import jakarta.jms.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * Demonstrates how to send and receive messages using the Amazon SQS Java Messaging Library
 * with Spring Framework integration. This example connects to a standard Amazon SQS message
 * queue using Spring's dependency injection to configure the connection and messaging components.
 * The application uses the JMS (Java Message Service) API to handle message operations.
 */
public class SpringExample {
    private static final Integer POLLING_SECONDS = 15;
    private static final String SPRING_XML_CONFIG_FILE = "SpringExampleConfiguration.xml.txt";
    private static final Logger LOGGER = LoggerFactory.getLogger(SpringExample.class);

    /**
     * Demonstrates sending and receiving messages through a standard Amazon SQS message queue
     * using Spring Framework configuration. This method loads connection settings from an XML file,
     * establishes a messaging session using the Amazon SQS Java Messaging Library, and processes
     * messages using JMS (Java Message Service) operations. If the queue doesn't exist, it will
     * be created automatically.
     *
     * @param args Command line arguments (not used)
     */
    public static void main(String[] args) {

        URL resource = SpringExample.class.getClassLoader().getResource(SPRING_XML_CONFIG_FILE);
        File springFile = new File(resource.getFile());
        if (!springFile.exists() || !springFile.canRead()) {
            LOGGER.error("File " + SPRING_XML_CONFIG_FILE + " doesn't exist or isn't readable.");
            System.exit(1);
        }

        try (FileSystemXmlApplicationContext context =
                     new FileSystemXmlApplicationContext("file://" + springFile.getAbsolutePath())) {

            Connection connection;
            try {
                connection = context.getBean(Connection.class);
            } catch (NoSuchBeanDefinitionException e) {
                LOGGER.error("Can't find the JMS connection to use: " + e.getMessage(), e);
                System.exit(2);
                return;
            }

            String queueName;
            try {
                queueName = context.getBean("queueName", String.class);
            } catch (NoSuchBeanDefinitionException e) {
                LOGGER.error("Can't find the name of the queue to use: " + e.getMessage(), e);
                System.exit(3);
                return;
            }
            try {
                if (connection instanceof SQSConnection) {
                    SqsJmsExampleUtils.ensureQueueExists((SQSConnection) connection, queueName, SqsJmsExampleUtils.QUEUE_VISIBILITY_TIMEOUT);
                }
                // Create the JMS session.
                Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

                SqsJmsExampleUtils.sendTextMessage(session, queueName);
                MessageConsumer consumer = session.createConsumer(session.createQueue(queueName));

                receiveMessages(consumer);
            } catch (JMSException e) {
                LOGGER.error(e.getMessage(), e);
                throw new RuntimeException(e);
            }
        }   // Spring context autocloses. Managed Spring beans that implement AutoClosable, such as the
        // 'connection' bean, are also closed.
        LOGGER.info("Context closed");
    }

    /**
     * Continuously checks for and processes messages from a standard Amazon SQS message queue
     * using the Amazon SQS Java Messaging Library underlying the JMS API. This method waits for incoming messages,
     * processes them when they arrive, and acknowledges their receipt using JMS (Java Message
     * Service) operations. The method will stop checking for messages after 15 seconds of
     * inactivity.
     *
     * @param consumer The JMS message consumer used to receive messages from the queue
     */
    private static void receiveMessages(MessageConsumer consumer) {
        try {
            while (true) {
                LOGGER.info("Waiting for messages...");
                // Wait 15 seconds for a message.
                Message message = consumer.receive(TimeUnit.SECONDS.toMillis(POLLING_SECONDS));
                if (message == null) {
                    LOGGER.info("Shutting down after {} seconds of silence.", POLLING_SECONDS);
                    break;
                }
                SqsJmsExampleUtils.handleMessage(message);
                message.acknowledge();
                LOGGER.info("Message acknowledged.");
            }
        } catch (JMSException e) {
            LOGGER.error("Error receiving from SQS.", e);
        }
    }
}
```
Spring の Bean 定義。  

```
<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        ">
    <!-- Define the AWS Region -->
    <bean id="region" class="software.amazon.awssdk.regions.Region" factory-method="of">
        <constructor-arg value="us-east-1"/>
    </bean>

    <bean id="credentialsProviderBean" class="software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider"
          factory-method="create"/>

    <bean id="clientBuilder" class="software.amazon.awssdk.services.sqs.SqsClient" factory-method="builder"/>

    <bean id="regionSetClientBuilder" factory-bean="clientBuilder" factory-method="region">
        <constructor-arg ref="region"/>
    </bean>

    <!-- Configure the Builder with Credentials Provider -->
    <bean id="sqsClient" factory-bean="regionSetClientBuilder" factory-method="credentialsProvider">
        <constructor-arg ref="credentialsProviderBean"/>
    </bean>

    <bean id="providerConfiguration" class="com.amazon.sqs.javamessaging.ProviderConfiguration">
        <property name="numberOfMessagesToPrefetch" value="5"/>
    </bean>

    <bean id="connectionFactory" class="com.amazon.sqs.javamessaging.SQSConnectionFactory">
        <constructor-arg ref="providerConfiguration"/>
        <constructor-arg ref="clientBuilder"/>
    </bean>

    <bean id="connection"
          factory-bean="connectionFactory"
          factory-method="createConnection"
          init-method="start"
          destroy-method="close"/>

    <bean id="queueName" class="java.lang.String">
        <constructor-arg value="SQSJMSClientExampleQueue"/>
    </bean>
</beans>
```
他の例で使用される一般的なメソッドを提供するユーティリティクラス。  

```
package com.example.sqs.jms;

import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper;
import com.amazon.sqs.javamessaging.ProviderConfiguration;
import com.amazon.sqs.javamessaging.SQSConnection;
import com.amazon.sqs.javamessaging.SQSConnectionFactory;
import jakarta.jms.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.CreateQueueRequest;
import software.amazon.awssdk.services.sqs.model.QueueAttributeName;

import java.time.Duration;
import java.util.Base64;
import java.util.Map;

/**
 * This utility class provides helper methods for working with Amazon Simple Queue Service (Amazon SQS)
 * through the Java Message Service (JMS) interface. It contains common operations for managing message
 * queues and handling message delivery.
 */
public class SqsJmsExampleUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(SqsJmsExampleUtils.class);
    public static final Long QUEUE_VISIBILITY_TIMEOUT = 5L;

    /**
     * This method verifies that a message queue exists and creates it if necessary. The method checks for
     * an existing queue first to optimize performance.
     *
     * @param connection The active connection to the messaging service
     * @param queueName The name of the queue to verify or create
     * @param visibilityTimeout The duration in seconds that messages will be hidden after being received
     * @throws JMSException If there is an error accessing or creating the queue
     */
    public static void ensureQueueExists(SQSConnection connection, String queueName, Long visibilityTimeout) throws JMSException {
        AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient();

       /* In most cases, you can do this with just a 'createQueue' call, but 'getQueueUrl'
       (called by 'queueExists') is a faster operation for the common case where the queue
       already exists. Also, many users and roles have permission to call 'getQueueUrl'
       but don't have permission to call 'createQueue'.
       */
        if( !client.queueExists(queueName) ) {
            CreateQueueRequest createQueueRequest = CreateQueueRequest.builder()
                    .queueName(queueName)
                    .attributes(Map.of(QueueAttributeName.VISIBILITY_TIMEOUT, String.valueOf(visibilityTimeout)))
                    .build();
            client.createQueue( createQueueRequest );
        }
    }

    /**
     * This method sends a simple text message to a specified message queue. It handles all necessary
     * setup for the message delivery process.
     *
     * @param session The active messaging session used to create and send the message
     * @param queueName The name of the queue where the message will be sent
     */
    public static void sendTextMessage(Session session, String queueName) {
        // Rest of implementation...

        try {
            MessageProducer producer = session.createProducer( session.createQueue( queueName) );
            Message message = session.createTextMessage("Hello world!");
            producer.send(message);
        } catch (JMSException e) {
            LOGGER.error( "Error receiving from SQS", e );
        }
    }

    /**
     * This method processes incoming messages and logs their content based on the message type.
     * It supports text messages, binary data, and Java objects.
     *
     * @param message The message to be processed and logged
     * @throws JMSException If there is an error reading the message content
     */
    public static void handleMessage(Message message) throws JMSException {
        // Rest of implementation...
        LOGGER.info( "Got message {}", message.getJMSMessageID() );
        LOGGER.info( "Content: ");
        if(message instanceof TextMessage txtMessage) {
            LOGGER.info( "\t{}", txtMessage.getText() );
        } else if(message instanceof BytesMessage byteMessage){
            // Assume the length fits in an int - SQS only supports sizes up to 256k so that
            // should be true
            byte[] bytes = new byte[(int)byteMessage.getBodyLength()];
            byteMessage.readBytes(bytes);
            LOGGER.info( "\t{}", Base64.getEncoder().encodeToString( bytes ) );
        } else if( message instanceof ObjectMessage) {
            ObjectMessage objMessage = (ObjectMessage) message;
            LOGGER.info( "\t{}", objMessage.getObject() );
        }
    }

    /**
     * This method sets up automatic message processing for a specified queue. It creates a listener
     * that will receive and handle incoming messages without blocking the main program.
     *
     * @param session The active messaging session
     * @param queueName The name of the queue to monitor
     * @param connection The active connection to the messaging service
     */
    public static void receiveMessagesAsync(Session session, String queueName, Connection connection) {
        // Rest of implementation...
        try {
            // Create a consumer for the queue.
            MessageConsumer consumer = session.createConsumer(session.createQueue(queueName));
            // Provide an implementation of the MessageListener interface, which has a single 'onMessage' method.
            // We use a lambda expression for the implementation.
            consumer.setMessageListener(message -> {
                try {
                    SqsJmsExampleUtils.handleMessage(message);
                    message.acknowledge();
                } catch (JMSException e) {
                    LOGGER.error("Error processing message: {}", e.getMessage());
                }
            });
            // Start receiving incoming messages.
            connection.start();
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * This method performs cleanup operations after message processing is complete. It receives
     * any messages in the specified queue, removes the message queue and closes all
     * active connections to prevent resource leaks.
     *
     * @param queueName The name of the queue to be removed
     * @param visibilityTimeout The duration in seconds that messages are hidden after being received
     * @throws JMSException If there is an error during the cleanup process
     */
    public static void cleanUpExample(String queueName, Long visibilityTimeout) throws JMSException {
        LOGGER.info("Performing cleanup.");

        SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                new ProviderConfiguration(),
                SqsClient.create()
        );

        try (SQSConnection connection = connectionFactory.createConnection() ) {
            ensureQueueExists(connection, queueName, visibilityTimeout);
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

            receiveMessagesAsync(session, queueName, connection);

            SqsClient sqsClient = connection.getWrappedAmazonSQSClient().getAmazonSQSClient();
            try {
                String queueUrl = sqsClient.getQueueUrl(b -> b.queueName(queueName)).queueUrl();
                sqsClient.deleteQueue(b -> b.queueUrl(queueUrl));
                LOGGER.info("Queue deleted: {}", queueUrl);
            } catch (SdkException e) {
                LOGGER.error("Error during SQS operations: ", e);
            }
        }
        LOGGER.info("Clean up: Connection closed");
    }

    /**
     * This method creates a background task that sends multiple messages to a specified queue
     * after waiting for a set time period. The task operates independently to ensure efficient
     * message processing without interrupting other operations.
     *
     * @param queueName The name of the queue where messages will be sent
     * @param secondsToWait The number of seconds to wait before sending messages
     * @param numMessages The number of messages to send
     * @param visibilityTimeout The duration in seconds that messages remain hidden after being received
     * @return A task that can be executed to send the messages
     */
    public static Runnable sendAMessageAsync(String queueName, Long secondsToWait, Integer numMessages, Long visibilityTimeout) {
        return () -> {
            try {
                Thread.sleep(Duration.ofSeconds(secondsToWait).toMillis());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
            try {
                SQSConnectionFactory connectionFactory = new SQSConnectionFactory(
                        new ProviderConfiguration(),
                        SqsClient.create()
                );
                try (SQSConnection connection = connectionFactory.createConnection()) {
                    ensureQueueExists(connection, queueName, visibilityTimeout);
                    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
                    for (int i = 1; i <= numMessages; i++) {
                        MessageProducer producer = session.createProducer(session.createQueue(queueName));
                        producer.send(session.createTextMessage("Hello World " + i + "!"));
                    }
                }
            } catch (JMSException e) {
                LOGGER.error(e.getMessage(), e);
                throw new RuntimeException(e);
            }
        };
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/CreateQueue)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/DeleteQueue)

### キュータグの操作
<a name="sqs_Scenario_WorkWithTags_java_2_topic"></a>

次のコード例は、Amazon SQS でタグ付け操作を実行する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
次の例では、キューのタグを作成し、タグを一覧表示し、タグを削除します。  

```
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.ListQueueTagsResponse;
import software.amazon.awssdk.services.sqs.model.QueueDoesNotExistException;
import software.amazon.awssdk.services.sqs.model.SqsException;

import java.util.Map;
import java.util.UUID;

/**
 * Before running this Java V2 code example, set up your development environment, including your credentials. For more
 * information, see the <a href="https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html">AWS
 * SDK for Java Developer Guide</a>.
 */
public class TagExamples {
    static final SqsClient sqsClient = SqsClient.create();
    static final String queueName = "TagExamples-queue-" + UUID.randomUUID().toString().replace("-", "").substring(0, 20);
    private static final Logger LOGGER = LoggerFactory.getLogger(TagExamples.class);

    public static void main(String[] args) {
        final String queueUrl;
        try {
            queueUrl = sqsClient.createQueue(b -> b.queueName(queueName)).queueUrl();
            LOGGER.info("Queue created. The URL is: {}", queueUrl);
        } catch (RuntimeException e) {
            LOGGER.error("Program ending because queue was not created.");
            throw new RuntimeException(e);
        }
        try {
            addTags(queueUrl);
            listTags(queueUrl);
            removeTags(queueUrl);
        } catch (RuntimeException e) {
            LOGGER.error("Program ending because of an error in a method.");
        } finally {
            try {
                sqsClient.deleteQueue(b -> b.queueUrl(queueUrl));
                LOGGER.info("Queue successfully deleted. Program ending.");
                sqsClient.close();
            } catch (RuntimeException e) {
                LOGGER.error("Program ending.");
            } finally {
                sqsClient.close();
            }
        }
    }

    /** This method demonstrates how to use a Java Map to a tag a aueue.
     * @param queueUrl The URL of the queue to tag.
     */
    public static void addTags(String queueUrl) {
        // Build a map of the tags.
        final Map<String, String> tagsToAdd = Map.of(
                "Team", "Development",
                "Priority", "Beta",
                "Accounting ID", "456def");

        try {
            // Add tags to the queue using a Consumer<TagQueueRequest.Builder> parameter.
            sqsClient.tagQueue(b -> b
                    .queueUrl(queueUrl)
                    .tags(tagsToAdd)
            );
        } catch (QueueDoesNotExistException e) {
            LOGGER.error("Queue does not exist: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /** This method demonstrates how to view the tags for a queue.
     * @param queueUrl The URL of the queue whose tags you want to list.
     */
    public static void listTags(String queueUrl) {
        ListQueueTagsResponse response;
        try {
            // Call the listQueueTags method with a Consumer<ListQueueTagsRequest.Builder> parameter that creates a ListQueueTagsRequest.
            response = sqsClient.listQueueTags(b -> b
                    .queueUrl(queueUrl));
        } catch (SqsException e) {
            LOGGER.error("Exception thrown: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }

        // Log the tags.
        response.tags()
                .forEach((k, v) ->
                        LOGGER.info("Key: {} -> Value: {}", k, v));
    }

    /**
     * This method demonstrates how to remove tags from a queue.
     * @param queueUrl The URL of the queue whose tags you want to remove.
     */
    public static void removeTags(String queueUrl) {
        try {
            // Call the untagQueue method with a Consumer<UntagQueueRequest.Builder> parameter.
            sqsClient.untagQueue(b -> b
                    .queueUrl(queueUrl)
                    .tagKeys("Accounting ID") // Remove a single tag.
            );
        } catch (SqsException e) {
            LOGGER.error("Exception thrown: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [ListQueueTags](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/ListQueueTags)
  + [TagQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/TagQueue)
  + [UntagQueue](https://docs.aws.amazon.com/goto/SdkForJavaV2/sqs-2012-11-05/UntagQueue)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_java_2_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage;

public class Function implements RequestHandler<SQSEvent, Void> {
    @Override
    public Void handleRequest(SQSEvent sqsEvent, Context context) {
        for (SQSMessage msg : sqsEvent.getRecords()) {
            processMessage(msg, context);
        }
        context.getLogger().log("done");
        return null;
    }

    private void processMessage(SQSMessage msg, Context context) {
        try {
            context.getLogger().log("Processed message " + msg.getBody());

            // TODO: Do interesting work based on the new message

        } catch (Exception e) {
            context.getLogger().log("An error occurred");
            throw e;
        }

    }
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_java_2_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Java を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.SQSEvent;
import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse;
 
import java.util.ArrayList;
import java.util.List;
 
public class ProcessSQSMessageBatch implements RequestHandler<SQSEvent, SQSBatchResponse> {
    @Override
    public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) {
         List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new ArrayList<SQSBatchResponse.BatchItemFailure>();

         for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) {
             try {
                 //process your message
             } catch (Exception e) {
                 //Add failed message identifier to the batchItemFailures list
                 batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(message.getMessageId()));
             }
         }
         return new SQSBatchResponse(batchItemFailures);
     }
}
```

# SDK for Java 2.x を使用した Step Function の例
<a name="java_2_sfn_code_examples"></a>

次のコード例は、Step Functions AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Step Functions
<a name="sfn_Hello_java_2_topic"></a>

次のコード例は、Step Functions の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。
Java バージョンの Hello  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.ListStateMachinesResponse;
import software.amazon.awssdk.services.sfn.model.SfnException;
import software.amazon.awssdk.services.sfn.model.StateMachineListItem;
import java.util.List;

/**
 * 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 ListStateMachines {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        SfnClient sfnClient = SfnClient.builder()
                .region(region)
                .build();

        listMachines(sfnClient);
        sfnClient.close();
    }

    public static void listMachines(SfnClient sfnClient) {
        try {
            ListStateMachinesResponse response = sfnClient.listStateMachines();
            List<StateMachineListItem> machines = response.stateMachines();
            for (StateMachineListItem machine : machines) {
                System.out.println("The name of the state machine is: " + machine.name());
                System.out.println("The ARN value is : " + machine.stateMachineArn());
            }

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListStateMachines](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/ListStateMachines)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="sfn_Scenario_GetStartedStateMachines_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ アクティビティを作成します。
+ 以前に作成したアクティビティをステップとして含む Amazon States Language 定義からステートマシンを作成します。
+ ステートマシンを実行し、ユーザー入力でアクティビティに応答します。
+ 実行が完了したら最終ステータスと出力を取得して、リソースをクリーンアップします。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
/**
 * You can obtain the JSON file to create a state machine in the following
 * GitHub location.
 * <p>
 * https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/sample_files
 * <p>
 * To run this code example, place the chat_sfn_state_machine.json file into
 * your project's resources folder.
 * <p>
 * Also, set up your development environment, including your credentials.
 * <p>
 * For information, see this documentation topic:
 * <p>
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 * <p>
 * This Java code example performs the following tasks:
 * <p>
 * 1. Creates an activity.
 * 2. Creates a state machine.
 * 3. Describes the state machine.
 * 4. Starts execution of the state machine and interacts with it.
 * 5. Describes the execution.
 * 6. Delete the activity.
 * 7. Deletes the state machine.
 */
public class StepFunctionsScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) throws Exception {
        final String usage = """

            Usage:
                <roleARN> <activityName> <stateMachineName>

            Where:
                roleName - The name of the IAM role to create for this state machine.
                activityName - The name of an activity to create.
                stateMachineName - The name of the state machine to create.
                jsonFile - The location of the chat_sfn_state_machine.json file. You can located it in resources/sample_files. 
            """;

        if (args.length != 4) {
            System.out.println(usage);
            System.exit(1);
        }

        String roleName = args[0];
        String activityName = args[1];
        String stateMachineName = args[2];
        String jsonFile = args[3];
        String polJSON = """
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Sid": "",
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "states.amazonaws.com"
                        },
                        "Action": "sts:AssumeRole"
                    }
                ]
            }
            """;


        Scanner sc = new Scanner(System.in);
        boolean action = false;

        Region region = Region.US_EAST_1;
        SfnClient sfnClient = SfnClient.builder()
            .region(region)
            .build();

        Region regionGl = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
            .region(regionGl)
            .build();

        System.out.println(DASHES);
        System.out.println("Welcome to the AWS Step Functions example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Create an activity.");
        String activityArn = createActivity(sfnClient, activityName);
        System.out.println("The ARN of the activity is " + activityArn);
        System.out.println(DASHES);

        // Read the file using FileInputStream
        FileInputStream inputStream = new FileInputStream(jsonFile);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readValue(inputStream, JsonNode.class);
        String jsonString = mapper.writeValueAsString(jsonNode);

        // Modify the Resource node.
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode root = objectMapper.readTree(jsonString);
        ((ObjectNode) root.path("States").path("GetInput")).put("Resource", activityArn);

        // Convert the modified Java object back to a JSON string.
        String stateDefinition = objectMapper.writeValueAsString(root);
        System.out.println(stateDefinition);

        System.out.println(DASHES);
        System.out.println("2. Create a state machine.");
        String roleARN = createIAMRole(iam, roleName, polJSON);
        String stateMachineArn = createMachine(sfnClient, roleARN, stateMachineName, stateDefinition);
        System.out.println("The ARN of the state machine is " + stateMachineArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Describe the state machine.");
        describeStateMachine(sfnClient, stateMachineArn);
        System.out.println("What should ChatSFN call you?");
        String userName = sc.nextLine();
        System.out.println("Hello " + userName);
        System.out.println(DASHES);

        System.out.println(DASHES);
        // The JSON to pass to the StartExecution call.
        String executionJson = "{ \"name\" : \"" + userName + "\" }";
        System.out.println(executionJson);
        System.out.println("4. Start execution of the state machine and interact with it.");
        String runArn = startWorkflow(sfnClient, stateMachineArn, executionJson);
        System.out.println("The ARN of the state machine execution is " + runArn);
        List<String> myList;
        while (!action) {
            myList = getActivityTask(sfnClient, activityArn);
            System.out.println("ChatSFN: " + myList.get(1));
            System.out.println(userName + " please specify a value.");
            String myAction = sc.nextLine();
            if (myAction.compareTo("done") == 0)
                action = true;

            System.out.println("You have selected " + myAction);
            String taskJson = "{ \"action\" : \"" + myAction + "\" }";
            System.out.println(taskJson);
            sendTaskSuccess(sfnClient, myList.get(0), taskJson);
        }
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Describe the execution.");
        describeExe(sfnClient, runArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Delete the activity.");
        deleteActivity(sfnClient, activityArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Delete the state machines.");
        deleteMachine(sfnClient, stateMachineArn);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("The AWS Step Functions example scenario is complete.");
        System.out.println(DASHES);
    }

    public static String createIAMRole(IamClient iam, String rolename, String polJSON) {
        try {
            CreateRoleRequest request = CreateRoleRequest.builder()
                .roleName(rolename)
                .assumeRolePolicyDocument(polJSON)
                .description("Created using the AWS SDK for Java")
                .build();

            CreateRoleResponse response = iam.createRole(request);
            return response.role().arn();

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static void describeExe(SfnClient sfnClient, String executionArn) {
        try {
            DescribeExecutionRequest executionRequest = DescribeExecutionRequest.builder()
                .executionArn(executionArn)
                .build();

            String status = "";
            boolean hasSucceeded = false;
            while (!hasSucceeded) {
                DescribeExecutionResponse response = sfnClient.describeExecution(executionRequest);
                status = response.statusAsString();
                if (status.compareTo("RUNNING") == 0) {
                    System.out.println("The state machine is still running, let's wait for it to finish.");
                    Thread.sleep(2000);
                } else if (status.compareTo("SUCCEEDED") == 0) {
                    System.out.println("The Step Function workflow has succeeded");
                    hasSucceeded = true;
                } else {
                    System.out.println("The Status is neither running or succeeded");
                }
            }
            System.out.println("The Status is " + status);

        } catch (SfnException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }

    public static void sendTaskSuccess(SfnClient sfnClient, String token, String json) {
        try {
            SendTaskSuccessRequest successRequest = SendTaskSuccessRequest.builder()
                .taskToken(token)
                .output(json)
                .build();

            sfnClient.sendTaskSuccess(successRequest);

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static List<String> getActivityTask(SfnClient sfnClient, String actArn) {
        List<String> myList = new ArrayList<>();
        GetActivityTaskRequest getActivityTaskRequest = GetActivityTaskRequest.builder()
            .activityArn(actArn)
            .build();

        GetActivityTaskResponse response = sfnClient.getActivityTask(getActivityTaskRequest);
        myList.add(response.taskToken());
        myList.add(response.input());
        return myList;
    }

    public static void deleteActivity(SfnClient sfnClient, String actArn) {
        try {
            DeleteActivityRequest activityRequest = DeleteActivityRequest.builder()
                .activityArn(actArn)
                .build();

            sfnClient.deleteActivity(activityRequest);
            System.out.println("You have deleted " + actArn);

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }

    public static void describeStateMachine(SfnClient sfnClient, String stateMachineArn) {
        try {
            DescribeStateMachineRequest stateMachineRequest = DescribeStateMachineRequest.builder()
                .stateMachineArn(stateMachineArn)
                .build();

            DescribeStateMachineResponse response = sfnClient.describeStateMachine(stateMachineRequest);
            System.out.println("The name of the State machine is " + response.name());
            System.out.println("The status of the State machine is " + response.status());
            System.out.println("The ARN value of the State machine is " + response.stateMachineArn());
            System.out.println("The role ARN value is " + response.roleArn());

        } catch (SfnException e) {
            System.err.println(e.getMessage());
        }
    }

    public static void deleteMachine(SfnClient sfnClient, String stateMachineArn) {
        try {
            DeleteStateMachineRequest deleteStateMachineRequest = DeleteStateMachineRequest.builder()
                .stateMachineArn(stateMachineArn)
                .build();

            sfnClient.deleteStateMachine(deleteStateMachineRequest);
            DescribeStateMachineRequest describeStateMachine = DescribeStateMachineRequest.builder()
                .stateMachineArn(stateMachineArn)
                .build();

            while (true) {
                DescribeStateMachineResponse response = sfnClient.describeStateMachine(describeStateMachine);
                System.out.println("The state machine is not deleted yet. The status is " + response.status());
                Thread.sleep(3000);
            }

        } catch (SfnException | InterruptedException e) {
            System.err.println(e.getMessage());
        }
        System.out.println(stateMachineArn + " was successfully deleted.");
    }

    public static String startWorkflow(SfnClient sfnClient, String stateMachineArn, String jsonEx) {
        UUID uuid = UUID.randomUUID();
        String uuidValue = uuid.toString();
        try {
            StartExecutionRequest executionRequest = StartExecutionRequest.builder()
                .input(jsonEx)
                .stateMachineArn(stateMachineArn)
                .name(uuidValue)
                .build();

            StartExecutionResponse response = sfnClient.startExecution(executionRequest);
            return response.executionArn();

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static String createMachine(SfnClient sfnClient, String roleARN, String stateMachineName, String json) {
        try {
            CreateStateMachineRequest machineRequest = CreateStateMachineRequest.builder()
                .definition(json)
                .name(stateMachineName)
                .roleArn(roleARN)
                .type(StateMachineType.STANDARD)
                .build();

            CreateStateMachineResponse response = sfnClient.createStateMachine(machineRequest);
            return response.stateMachineArn();

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }

    public static String createActivity(SfnClient sfnClient, String activityName) {
        try {
            CreateActivityRequest activityRequest = CreateActivityRequest.builder()
                .name(activityName)
                .build();

            CreateActivityResponse response = sfnClient.createActivity(activityRequest);
            return response.activityArn();

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateActivity](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/CreateActivity)
  + [CreateStateMachine](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/CreateStateMachine)
  + [DeleteActivity](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DeleteActivity)
  + [DeleteStateMachine](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DeleteStateMachine)
  + [DescribeExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DescribeExecution)
  + [DescribeStateMachine](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DescribeStateMachine)
  + [GetActivityTask](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/GetActivityTask)
  + [ListActivities](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/ListActivities)
  + [ListStateMachines](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/ListStateMachines)
  + [SendTaskSuccess](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/SendTaskSuccess)
  + [StartExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/StartExecution)
  + [StopExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/StopExecution)

## アクション
<a name="actions"></a>

### `CreateActivity`
<a name="sfn_CreateActivity_java_2_topic"></a>

次のコード例は、`CreateActivity` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static String createActivity(SfnClient sfnClient, String activityName) {
        try {
            CreateActivityRequest activityRequest = CreateActivityRequest.builder()
                .name(activityName)
                .build();

            CreateActivityResponse response = sfnClient.createActivity(activityRequest);
            return response.activityArn();

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateActivity](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/CreateActivity)」を参照してください。

### `CreateStateMachine`
<a name="sfn_CreateStateMachine_java_2_topic"></a>

次のコード例は、`CreateStateMachine` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static String createMachine(SfnClient sfnClient, String roleARN, String stateMachineName, String json) {
        try {
            CreateStateMachineRequest machineRequest = CreateStateMachineRequest.builder()
                .definition(json)
                .name(stateMachineName)
                .roleArn(roleARN)
                .type(StateMachineType.STANDARD)
                .build();

            CreateStateMachineResponse response = sfnClient.createStateMachine(machineRequest);
            return response.stateMachineArn();

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateStateMachine](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/CreateStateMachine)」を参照してください。

### `DeleteActivity`
<a name="sfn_DeleteActivity_java_2_topic"></a>

次のコード例は、`DeleteActivity` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteActivity(SfnClient sfnClient, String actArn) {
        try {
            DeleteActivityRequest activityRequest = DeleteActivityRequest.builder()
                .activityArn(actArn)
                .build();

            sfnClient.deleteActivity(activityRequest);
            System.out.println("You have deleted " + actArn);

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteActivity](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DeleteActivity)」を参照してください。

### `DeleteStateMachine`
<a name="sfn_DeleteStateMachine_java_2_topic"></a>

次のコード例は、`DeleteStateMachine` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static void deleteMachine(SfnClient sfnClient, String stateMachineArn) {
        try {
            DeleteStateMachineRequest deleteStateMachineRequest = DeleteStateMachineRequest.builder()
                .stateMachineArn(stateMachineArn)
                .build();

            sfnClient.deleteStateMachine(deleteStateMachineRequest);
            DescribeStateMachineRequest describeStateMachine = DescribeStateMachineRequest.builder()
                .stateMachineArn(stateMachineArn)
                .build();

            while (true) {
                DescribeStateMachineResponse response = sfnClient.describeStateMachine(describeStateMachine);
                System.out.println("The state machine is not deleted yet. The status is " + response.status());
                Thread.sleep(3000);
            }

        } catch (SfnException | InterruptedException e) {
            System.err.println(e.getMessage());
        }
        System.out.println(stateMachineArn + " was successfully deleted.");
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteStateMachine](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DeleteStateMachine)」を参照してください。

### `DescribeExecution`
<a name="sfn_DescribeExecution_java_2_topic"></a>

次のコード例は、`DescribeExecution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeExe(SfnClient sfnClient, String executionArn) {
        try {
            DescribeExecutionRequest executionRequest = DescribeExecutionRequest.builder()
                .executionArn(executionArn)
                .build();

            String status = "";
            boolean hasSucceeded = false;
            while (!hasSucceeded) {
                DescribeExecutionResponse response = sfnClient.describeExecution(executionRequest);
                status = response.statusAsString();
                if (status.compareTo("RUNNING") == 0) {
                    System.out.println("The state machine is still running, let's wait for it to finish.");
                    Thread.sleep(2000);
                } else if (status.compareTo("SUCCEEDED") == 0) {
                    System.out.println("The Step Function workflow has succeeded");
                    hasSucceeded = true;
                } else {
                    System.out.println("The Status is neither running or succeeded");
                }
            }
            System.out.println("The Status is " + status);

        } catch (SfnException | InterruptedException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DescribeExecution)」を参照してください。

### `DescribeStateMachine`
<a name="sfn_DescribeStateMachine_java_2_topic"></a>

次のコード例は、`DescribeStateMachine` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeStateMachine(SfnClient sfnClient, String stateMachineArn) {
        try {
            DescribeStateMachineRequest stateMachineRequest = DescribeStateMachineRequest.builder()
                .stateMachineArn(stateMachineArn)
                .build();

            DescribeStateMachineResponse response = sfnClient.describeStateMachine(stateMachineRequest);
            System.out.println("The name of the State machine is " + response.name());
            System.out.println("The status of the State machine is " + response.status());
            System.out.println("The ARN value of the State machine is " + response.stateMachineArn());
            System.out.println("The role ARN value is " + response.roleArn());

        } catch (SfnException e) {
            System.err.println(e.getMessage());
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeStateMachine](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/DescribeStateMachine)」を参照してください。

### `GetActivityTask`
<a name="sfn_GetActivityTask_java_2_topic"></a>

次のコード例は、`GetActivityTask` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static List<String> getActivityTask(SfnClient sfnClient, String actArn) {
        List<String> myList = new ArrayList<>();
        GetActivityTaskRequest getActivityTaskRequest = GetActivityTaskRequest.builder()
            .activityArn(actArn)
            .build();

        GetActivityTaskResponse response = sfnClient.getActivityTask(getActivityTaskRequest);
        myList.add(response.taskToken());
        myList.add(response.input());
        return myList;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[GetActivityTask](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/GetActivityTask)」を参照してください。

### `ListActivities`
<a name="sfn_ListActivities_java_2_topic"></a>

次のコード例は、`ListActivities` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.ListActivitiesRequest;
import software.amazon.awssdk.services.sfn.model.ListActivitiesResponse;
import software.amazon.awssdk.services.sfn.model.SfnException;
import software.amazon.awssdk.services.sfn.model.ActivityListItem;
import java.util.List;

/**
 * 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 ListActivities {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        SfnClient sfnClient = SfnClient.builder()
                .region(region)
                .build();

        listAllActivites(sfnClient);
        sfnClient.close();
    }

    public static void listAllActivites(SfnClient sfnClient) {
        try {
            ListActivitiesRequest activitiesRequest = ListActivitiesRequest.builder()
                    .maxResults(10)
                    .build();

            ListActivitiesResponse response = sfnClient.listActivities(activitiesRequest);
            List<ActivityListItem> items = response.activities();
            for (ActivityListItem item : items) {
                System.out.println("The activity ARN is " + item.activityArn());
                System.out.println("The activity name is " + item.name());
            }

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListActivities](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/ListActivities)」を参照してください。

### `ListExecutions`
<a name="sfn_ListExecutions_java_2_topic"></a>

次のコード例は、`ListExecutions` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static void getExeHistory(SfnClient sfnClient, String exeARN) {
        try {
            GetExecutionHistoryRequest historyRequest = GetExecutionHistoryRequest.builder()
                    .executionArn(exeARN)
                    .maxResults(10)
                    .build();

            GetExecutionHistoryResponse historyResponse = sfnClient.getExecutionHistory(historyRequest);
            List<HistoryEvent> events = historyResponse.events();
            for (HistoryEvent event : events) {
                System.out.println("The event type is " + event.type().toString());
            }

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListExecutions](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/ListExecutions)」を参照してください。

### `ListStateMachines`
<a name="sfn_ListStateMachines_java_2_topic"></a>

次のコード例は、`ListStateMachines` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sfn.SfnClient;
import software.amazon.awssdk.services.sfn.model.ListStateMachinesResponse;
import software.amazon.awssdk.services.sfn.model.SfnException;
import software.amazon.awssdk.services.sfn.model.StateMachineListItem;
import java.util.List;

/**
 * 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 ListStateMachines {
    public static void main(String[] args) {
        Region region = Region.US_EAST_1;
        SfnClient sfnClient = SfnClient.builder()
                .region(region)
                .build();

        listMachines(sfnClient);
        sfnClient.close();
    }

    public static void listMachines(SfnClient sfnClient) {
        try {
            ListStateMachinesResponse response = sfnClient.listStateMachines();
            List<StateMachineListItem> machines = response.stateMachines();
            for (StateMachineListItem machine : machines) {
                System.out.println("The name of the state machine is: " + machine.name());
                System.out.println("The ARN value is : " + machine.stateMachineArn());
            }

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ListStateMachines](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/ListStateMachines)」を参照してください。

### `SendTaskSuccess`
<a name="sfn_SendTaskSuccess_java_2_topic"></a>

次のコード例は、`SendTaskSuccess` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static void sendTaskSuccess(SfnClient sfnClient, String token, String json) {
        try {
            SendTaskSuccessRequest successRequest = SendTaskSuccessRequest.builder()
                .taskToken(token)
                .output(json)
                .build();

            sfnClient.sendTaskSuccess(successRequest);

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SendTaskSuccess](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/SendTaskSuccess)」を参照してください。

### `StartExecution`
<a name="sfn_StartExecution_java_2_topic"></a>

次のコード例は、`StartExecution` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    public static String startWorkflow(SfnClient sfnClient, String stateMachineArn, String jsonEx) {
        UUID uuid = UUID.randomUUID();
        String uuidValue = uuid.toString();
        try {
            StartExecutionRequest executionRequest = StartExecutionRequest.builder()
                .input(jsonEx)
                .stateMachineArn(stateMachineArn)
                .name(uuidValue)
                .build();

            StartExecutionResponse response = sfnClient.startExecution(executionRequest);
            return response.executionArn();

        } catch (SfnException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[StartExecution](https://docs.aws.amazon.com/goto/SdkForJavaV2/states-2016-11-23/StartExecution)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Step Functions を使用して Lambda 関数を呼び出す
<a name="cross_ServerlessWorkflows_java_2_topic"></a>

次のコード例は、 AWS Lambda 関数を順番に呼び出す AWS Step Functions ステートマシンを作成する方法を示しています。

**SDK for Java 2.x**  
 AWS Step Functions と を使用して AWS サーバーレスワークフローを作成する方法を示します AWS SDK for Java 2.x。各ワークフローステップは、 AWS Lambda 関数を使用して実装されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_workflows_stepfunctions) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SES
+ ステップ関数

# AWS STS SDK for Java 2.x を使用した例
<a name="java_2_sts_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_java_2_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sts#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sts.StsClient;
import software.amazon.awssdk.services.sts.model.AssumeRoleRequest;
import software.amazon.awssdk.services.sts.model.StsException;
import software.amazon.awssdk.services.sts.model.AssumeRoleResponse;
import software.amazon.awssdk.services.sts.model.Credentials;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

/**
 * To make this code example work, create a Role that you want to assume.
 * Then define a Trust Relationship in the AWS Console. You can use this as an
 * example:
 *
 * {
 * "Version":"2012-10-17",		 	 	 
 * "Statement": [
 * {
 * "Effect": "Allow",
 * "Principal": {
 * "AWS": "<Specify the ARN of your IAM user you are using in this code example>"
 * },
 * "Action": "sts:AssumeRole"
 * }
 * ]
 * }
 *
 * For more information, see "Editing the Trust Relationship for an Existing
 * Role" in the AWS Directory Service guide.
 *
 * Also, 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 AssumeRole {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <roleArn> <roleSessionName>\s

                Where:
                    roleArn - The Amazon Resource Name (ARN) of the role to assume (for example, arn:aws:iam::000008047983:role/s3role).\s
                    roleSessionName - An identifier for the assumed role session (for example, mysession).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String roleArn = args[0];
        String roleSessionName = args[1];
        Region region = Region.US_EAST_1;
        StsClient stsClient = StsClient.builder()
                .region(region)
                .build();

        assumeGivenRole(stsClient, roleArn, roleSessionName);
        stsClient.close();
    }

    public static void assumeGivenRole(StsClient stsClient, String roleArn, String roleSessionName) {
        try {
            AssumeRoleRequest roleRequest = AssumeRoleRequest.builder()
                    .roleArn(roleArn)
                    .roleSessionName(roleSessionName)
                    .build();

            AssumeRoleResponse roleResponse = stsClient.assumeRole(roleRequest);
            Credentials myCreds = roleResponse.credentials();

            // Display the time when the temp creds expire.
            Instant exTime = myCreds.expiration();
            String tokenInfo = myCreds.sessionToken();

            // Convert the Instant to readable date.
            DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
                    .withLocale(Locale.US)
                    .withZone(ZoneId.systemDefault());

            formatter.format(exTime);
            System.out.println("The token " + tokenInfo + "  expires on " + exTime);

        } catch (StsException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/SdkForJavaV2/sts-2011-06-15/AssumeRole)」を参照してください。**

# サポート SDK for Java 2.x を使用した例
<a name="java_2_support_code_examples"></a>

次のコード例は、 AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち サポートは
<a name="support_Hello_java_2_topic"></a>

次のコード例は、 サポートの使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.support.SupportClient;
import software.amazon.awssdk.services.support.model.Category;
import software.amazon.awssdk.services.support.model.DescribeServicesRequest;
import software.amazon.awssdk.services.support.model.DescribeServicesResponse;
import software.amazon.awssdk.services.support.model.Service;
import software.amazon.awssdk.services.support.model.SupportException;
import java.util.ArrayList;
import java.util.List;

/**
 * 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
 *
 * In addition, you must have the AWS Business Support Plan to use the AWS
 * Support Java API. For more information, see:
 *
 * https://aws.amazon.com/premiumsupport/plans/
 *
 * This Java example performs the following task:
 *
 * 1. Gets and displays available services.
 *
 *
 * NOTE: To see multiple operations, see SupportScenario.
 */

public class HelloSupport {
    public static void main(String[] args) {
        Region region = Region.US_WEST_2;
        SupportClient supportClient = SupportClient.builder()
                .region(region)
                .build();

        System.out.println("***** Step 1. Get and display available services.");
        displayServices(supportClient);
    }

    // Return a List that contains a Service name and Category name.
    public static void displayServices(SupportClient supportClient) {
        try {
            DescribeServicesRequest servicesRequest = DescribeServicesRequest.builder()
                    .language("en")
                    .build();

            DescribeServicesResponse response = supportClient.describeServices(servicesRequest);
            List<Service> services = response.services();

            System.out.println("Get the first 10 services");
            int index = 1;
            for (Service service : services) {
                if (index == 11)
                    break;

                System.out.println("The Service name is: " + service.name());

                // Display the Categories for this service.
                List<Category> categories = service.categories();
                for (Category cat : categories) {
                    System.out.println("The category name is: " + cat.name());
                }
                index++;
            }

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeServices](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeServices)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="support_Scenario_GetStartedSupportCases_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ケースの利用可能なサービスと重要度レベルを取得して表示します。
+ 選択したサービス、カテゴリ、重要度レベルを使用してサポートケースを作成する方法
+ 当日のオープンケースのリストを取得して表示する方法
+ 新しいケースに添付セットとコミュニケーションを追加する方法
+ ケースの新しい添付ファイルとコミュニケーションについて説明する方法
+ ケースを解決する方法
+ 当日の解決済みケースのリストを取得して表示します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。
さまざまな サポート オペレーションを実行します。  

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.support.SupportClient;
import software.amazon.awssdk.services.support.model.AddAttachmentsToSetResponse;
import software.amazon.awssdk.services.support.model.AddCommunicationToCaseRequest;
import software.amazon.awssdk.services.support.model.AddCommunicationToCaseResponse;
import software.amazon.awssdk.services.support.model.Attachment;
import software.amazon.awssdk.services.support.model.AttachmentDetails;
import software.amazon.awssdk.services.support.model.CaseDetails;
import software.amazon.awssdk.services.support.model.Category;
import software.amazon.awssdk.services.support.model.Communication;
import software.amazon.awssdk.services.support.model.CreateCaseRequest;
import software.amazon.awssdk.services.support.model.CreateCaseResponse;
import software.amazon.awssdk.services.support.model.DescribeAttachmentRequest;
import software.amazon.awssdk.services.support.model.DescribeAttachmentResponse;
import software.amazon.awssdk.services.support.model.DescribeCasesRequest;
import software.amazon.awssdk.services.support.model.DescribeCasesResponse;
import software.amazon.awssdk.services.support.model.DescribeCommunicationsRequest;
import software.amazon.awssdk.services.support.model.DescribeCommunicationsResponse;
import software.amazon.awssdk.services.support.model.DescribeServicesRequest;
import software.amazon.awssdk.services.support.model.DescribeServicesResponse;
import software.amazon.awssdk.services.support.model.DescribeSeverityLevelsRequest;
import software.amazon.awssdk.services.support.model.DescribeSeverityLevelsResponse;
import software.amazon.awssdk.services.support.model.ResolveCaseRequest;
import software.amazon.awssdk.services.support.model.ResolveCaseResponse;
import software.amazon.awssdk.services.support.model.Service;
import software.amazon.awssdk.services.support.model.SeverityLevel;
import software.amazon.awssdk.services.support.model.SupportException;
import software.amazon.awssdk.services.support.model.AddAttachmentsToSetRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * 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
 *
 * In addition, you must have the AWS Business Support Plan to use the AWS
 * Support Java API. For more information, see:
 *
 * https://aws.amazon.com/premiumsupport/plans/
 *
 * This Java example performs the following tasks:
 *
 * 1. Gets and displays available services.
 * 2. Gets and displays severity levels.
 * 3. Creates a support case by using the selected service, category, and
 * severity level.
 * 4. Gets a list of open cases for the current day.
 * 5. Creates an attachment set with a generated file.
 * 6. Adds a communication with the attachment to the support case.
 * 7. Lists the communications of the support case.
 * 8. Describes the attachment set included with the communication.
 * 9. Resolves the support case.
 * 10. Gets a list of resolved cases for the current day.
 */
public class SupportScenario {

    public static final String DASHES = new String(new char[80]).replace("\0", "-");

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <fileAttachment>Where:
                    fileAttachment - The file can be a simple saved .txt file to use as an email attachment.\s
                """;

      //  if (args.length != 1) {
      //      System.out.println(usage);
      //      System.exit(1);
      //  }

        String fileAttachment = "C:\\AWS\\test.txt" ; //args[0];
        Region region = Region.US_WEST_2;
        SupportClient supportClient = SupportClient.builder()
                .region(region)
                .build();

        System.out.println(DASHES);
        System.out.println("***** Welcome to the AWS Support case example scenario.");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("1. Get and display available services.");
        List<String> sevCatList = displayServices(supportClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("2. Get and display Support severity levels.");
        String sevLevel = displaySevLevels(supportClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("3. Create a support case using the selected service, category, and severity level.");
        String caseId = createSupportCase(supportClient, sevCatList, sevLevel);
        if (caseId.compareTo("") == 0) {
            System.out.println("A support case was not successfully created!");
            System.exit(1);
        } else
            System.out.println("Support case " + caseId + " was successfully created!");
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("4. Get open support cases.");
        getOpenCase(supportClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("5. Create an attachment set with a generated file to add to the case.");
        String attachmentSetId = addAttachment(supportClient, fileAttachment);
        System.out.println("The Attachment Set id value is" + attachmentSetId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("6. Add communication with the attachment to the support case.");
        addAttachSupportCase(supportClient, caseId, attachmentSetId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. List the communications of the support case.");
        String attachId = listCommunications(supportClient, caseId);
        System.out.println("The Attachment id value is" + attachId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("8. Describe the attachment set included with the communication.");
        describeAttachment(supportClient, attachId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("9. Resolve the support case.");
        resolveSupportCase(supportClient, caseId);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("10. Get a list of resolved cases for the current day.");
        getResolvedCase(supportClient);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("***** This Scenario has successfully completed");
        System.out.println(DASHES);
    }

    public static void getResolvedCase(SupportClient supportClient) {
        try {
            // Specify the start and end time.
            Instant now = Instant.now();
            java.time.LocalDate.now();
            Instant yesterday = now.minus(1, ChronoUnit.DAYS);

            DescribeCasesRequest describeCasesRequest = DescribeCasesRequest.builder()
                    .maxResults(30)
                    .afterTime(yesterday.toString())
                    .beforeTime(now.toString())
                    .includeResolvedCases(true)
                    .build();

            DescribeCasesResponse response = supportClient.describeCases(describeCasesRequest);
            List<CaseDetails> cases = response.cases();
            for (CaseDetails sinCase : cases) {
                if (sinCase.status().compareTo("resolved") == 0)
                    System.out.println("The case status is " + sinCase.status());
            }

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void resolveSupportCase(SupportClient supportClient, String caseId) {
        try {
            ResolveCaseRequest caseRequest = ResolveCaseRequest.builder()
                    .caseId(caseId)
                    .build();

            ResolveCaseResponse response = supportClient.resolveCase(caseRequest);
            System.out.println("The status of case " + caseId + " is " + response.finalCaseStatus());

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static void describeAttachment(SupportClient supportClient, String attachId) {
        try {
            DescribeAttachmentRequest attachmentRequest = DescribeAttachmentRequest.builder()
                    .attachmentId(attachId)
                    .build();

            DescribeAttachmentResponse response = supportClient.describeAttachment(attachmentRequest);
            System.out.println("The name of the file is " + response.attachment().fileName());

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static String listCommunications(SupportClient supportClient, String caseId) {
        try {
            String attachId = null;
            DescribeCommunicationsRequest communicationsRequest = DescribeCommunicationsRequest.builder()
                    .caseId(caseId)
                    .maxResults(10)
                    .build();

            DescribeCommunicationsResponse response = supportClient.describeCommunications(communicationsRequest);
            List<Communication> communications = response.communications();
            for (Communication comm : communications) {
                System.out.println("the body is: " + comm.body());

                // Get the attachment id value.
                List<AttachmentDetails> attachments = comm.attachmentSet();
                for (AttachmentDetails detail : attachments) {
                    attachId = detail.attachmentId();
                }
            }
            return attachId;

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }

    public static void addAttachSupportCase(SupportClient supportClient, String caseId, String attachmentSetId) {
        try {
            AddCommunicationToCaseRequest caseRequest = AddCommunicationToCaseRequest.builder()
                    .caseId(caseId)
                    .attachmentSetId(attachmentSetId)
                    .communicationBody("Please refer to attachment for details.")
                    .build();

            AddCommunicationToCaseResponse response = supportClient.addCommunicationToCase(caseRequest);
            if (response.result())
                System.out.println("You have successfully added a communication to an AWS Support case");
            else
                System.out.println("There was an error adding the communication to an AWS Support case");

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static String addAttachment(SupportClient supportClient, String fileAttachment) {
        try {
            File myFile = new File(fileAttachment);
            InputStream sourceStream = new FileInputStream(myFile);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);

            Attachment attachment = Attachment.builder()
                    .fileName(myFile.getName())
                    .data(sourceBytes)
                    .build();

            AddAttachmentsToSetRequest setRequest = AddAttachmentsToSetRequest.builder()
                    .attachments(attachment)
                    .build();

            AddAttachmentsToSetResponse response = supportClient.addAttachmentsToSet(setRequest);
            return response.attachmentSetId();

        } catch (SupportException | FileNotFoundException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }

    public static void getOpenCase(SupportClient supportClient) {
        try {
            // Specify the start and end time.
            Instant now = Instant.now();
            java.time.LocalDate.now();
            Instant yesterday = now.minus(1, ChronoUnit.DAYS);

            DescribeCasesRequest describeCasesRequest = DescribeCasesRequest.builder()
                    .maxResults(20)
                    .afterTime(yesterday.toString())
                    .beforeTime(now.toString())
                    .build();

            DescribeCasesResponse response = supportClient.describeCases(describeCasesRequest);
            List<CaseDetails> cases = response.cases();
            for (CaseDetails sinCase : cases) {
                System.out.println("The case status is " + sinCase.status());
                System.out.println("The case Id is " + sinCase.caseId());
                System.out.println("The case subject is " + sinCase.subject());
            }

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }

    public static String createSupportCase(SupportClient supportClient, List<String> sevCatList, String sevLevel) {
        try {
            String serviceCode = sevCatList.get(0);
            String caseCat = sevCatList.get(1);
            CreateCaseRequest caseRequest = CreateCaseRequest.builder()
                    .categoryCode(caseCat.toLowerCase())
                    .serviceCode(serviceCode.toLowerCase())
                    .severityCode(sevLevel.toLowerCase())
                    .communicationBody("Test issue with " + serviceCode.toLowerCase())
                    .subject("Test case, please ignore")
                    .language("en")
                    .issueType("technical")
                    .build();

            CreateCaseResponse response = supportClient.createCase(caseRequest);
            return response.caseId();

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }

    public static String displaySevLevels(SupportClient supportClient) {
        try {
            DescribeSeverityLevelsRequest severityLevelsRequest = DescribeSeverityLevelsRequest.builder()
                    .language("en")
                    .build();

            DescribeSeverityLevelsResponse response = supportClient.describeSeverityLevels(severityLevelsRequest);
            List<SeverityLevel> severityLevels = response.severityLevels();
            String levelName = null;
            for (SeverityLevel sevLevel : severityLevels) {
                System.out.println("The severity level name is: " + sevLevel.name());
                if (sevLevel.name().compareTo("High") == 0)
                    levelName = sevLevel.name();
            }
            return levelName;

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }

    // Return a List that contains a Service name and Category name.
    public static List<String> displayServices(SupportClient supportClient) {
        try {
            DescribeServicesRequest servicesRequest = DescribeServicesRequest.builder()
                    .language("en")
                    .build();

            DescribeServicesResponse response = supportClient.describeServices(servicesRequest);
            String serviceCode = null;
            String catName = null;
            List<String> sevCatList = new ArrayList<>();
            List<Service> services = response.services();

            System.out.println("Get the first 10 services");
            int index = 1;
            for (Service service : services) {
                if (index == 11)
                    break;

                System.out.println("The Service name is: " + service.name());
                if (service.name().compareTo("Account") == 0)
                    serviceCode = service.code();

                // Get the Categories for this service.
                List<Category> categories = service.categories();
                for (Category cat : categories) {
                    System.out.println("The category name is: " + cat.name());
                    if (cat.name().compareTo("Security") == 0)
                        catName = cat.name();
                }
                index++;
            }

            // Push the two values to the list.
            sevCatList.add(serviceCode);
            sevCatList.add(catName);
            return sevCatList;

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return null;
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [AddAttachmentsToSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/AddAttachmentsToSet)
  + [AddCommunicationToCase](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/AddCommunicationToCase)
  + [CreateCase](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/CreateCase)
  + [DescribeAttachment](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeAttachment)
  + [DescribeCases](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeCases)
  + [DescribeCommunications](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeCommunications)
  + [DescribeServices](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeServices)
  + [DescribeSeverityLevels](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeSeverityLevels)
  + [ResolveCase](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/ResolveCase)

## アクション
<a name="actions"></a>

### `AddAttachmentsToSet`
<a name="support_AddAttachmentsToSet_java_2_topic"></a>

次のコード例は、`AddAttachmentsToSet` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static String addAttachment(SupportClient supportClient, String fileAttachment) {
        try {
            File myFile = new File(fileAttachment);
            InputStream sourceStream = new FileInputStream(myFile);
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);

            Attachment attachment = Attachment.builder()
                    .fileName(myFile.getName())
                    .data(sourceBytes)
                    .build();

            AddAttachmentsToSetRequest setRequest = AddAttachmentsToSetRequest.builder()
                    .attachments(attachment)
                    .build();

            AddAttachmentsToSetResponse response = supportClient.addAttachmentsToSet(setRequest);
            return response.attachmentSetId();

        } catch (SupportException | FileNotFoundException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AddAttachmentsToSet](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/AddAttachmentsToSet)」を参照してください。

### `AddCommunicationToCase`
<a name="support_AddCommunicationToCase_java_2_topic"></a>

次のコード例は、`AddCommunicationToCase` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static void addAttachSupportCase(SupportClient supportClient, String caseId, String attachmentSetId) {
        try {
            AddCommunicationToCaseRequest caseRequest = AddCommunicationToCaseRequest.builder()
                    .caseId(caseId)
                    .attachmentSetId(attachmentSetId)
                    .communicationBody("Please refer to attachment for details.")
                    .build();

            AddCommunicationToCaseResponse response = supportClient.addCommunicationToCase(caseRequest);
            if (response.result())
                System.out.println("You have successfully added a communication to an AWS Support case");
            else
                System.out.println("There was an error adding the communication to an AWS Support case");

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[AddCommunicationToCase](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/AddCommunicationToCase)」を参照してください。

### `CreateCase`
<a name="support_CreateCase_java_2_topic"></a>

次のコード例は、`CreateCase` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static String createSupportCase(SupportClient supportClient, List<String> sevCatList, String sevLevel) {
        try {
            String serviceCode = sevCatList.get(0);
            String caseCat = sevCatList.get(1);
            CreateCaseRequest caseRequest = CreateCaseRequest.builder()
                    .categoryCode(caseCat.toLowerCase())
                    .serviceCode(serviceCode.toLowerCase())
                    .severityCode(sevLevel.toLowerCase())
                    .communicationBody("Test issue with " + serviceCode.toLowerCase())
                    .subject("Test case, please ignore")
                    .language("en")
                    .issueType("technical")
                    .build();

            CreateCaseResponse response = supportClient.createCase(caseRequest);
            return response.caseId();

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateCase](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/CreateCase)」を参照してください。

### `DescribeAttachment`
<a name="support_DescribeAttachment_java_2_topic"></a>

次のコード例は、`DescribeAttachment` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static void describeAttachment(SupportClient supportClient, String attachId) {
        try {
            DescribeAttachmentRequest attachmentRequest = DescribeAttachmentRequest.builder()
                    .attachmentId(attachId)
                    .build();

            DescribeAttachmentResponse response = supportClient.describeAttachment(attachmentRequest);
            System.out.println("The name of the file is " + response.attachment().fileName());

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeAttachment](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeAttachment)」を参照してください。

### `DescribeCases`
<a name="support_DescribeCases_java_2_topic"></a>

次のコード例は、`DescribeCases` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static void getOpenCase(SupportClient supportClient) {
        try {
            // Specify the start and end time.
            Instant now = Instant.now();
            java.time.LocalDate.now();
            Instant yesterday = now.minus(1, ChronoUnit.DAYS);

            DescribeCasesRequest describeCasesRequest = DescribeCasesRequest.builder()
                    .maxResults(20)
                    .afterTime(yesterday.toString())
                    .beforeTime(now.toString())
                    .build();

            DescribeCasesResponse response = supportClient.describeCases(describeCasesRequest);
            List<CaseDetails> cases = response.cases();
            for (CaseDetails sinCase : cases) {
                System.out.println("The case status is " + sinCase.status());
                System.out.println("The case Id is " + sinCase.caseId());
                System.out.println("The case subject is " + sinCase.subject());
            }

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeCases](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeCases)」を参照してください。

### `DescribeCommunications`
<a name="support_DescribeCommunications_java_2_topic"></a>

次のコード例は、`DescribeCommunications` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static String listCommunications(SupportClient supportClient, String caseId) {
        try {
            String attachId = null;
            DescribeCommunicationsRequest communicationsRequest = DescribeCommunicationsRequest.builder()
                    .caseId(caseId)
                    .maxResults(10)
                    .build();

            DescribeCommunicationsResponse response = supportClient.describeCommunications(communicationsRequest);
            List<Communication> communications = response.communications();
            for (Communication comm : communications) {
                System.out.println("the body is: " + comm.body());

                // Get the attachment id value.
                List<AttachmentDetails> attachments = comm.attachmentSet();
                for (AttachmentDetails detail : attachments) {
                    attachId = detail.attachmentId();
                }
            }
            return attachId;

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeCommunications](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeCommunications)」を参照してください。

### `DescribeServices`
<a name="support_DescribeServices_java_2_topic"></a>

次のコード例は、`DescribeServices` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    // Return a List that contains a Service name and Category name.
    public static List<String> displayServices(SupportClient supportClient) {
        try {
            DescribeServicesRequest servicesRequest = DescribeServicesRequest.builder()
                    .language("en")
                    .build();

            DescribeServicesResponse response = supportClient.describeServices(servicesRequest);
            String serviceCode = null;
            String catName = null;
            List<String> sevCatList = new ArrayList<>();
            List<Service> services = response.services();

            System.out.println("Get the first 10 services");
            int index = 1;
            for (Service service : services) {
                if (index == 11)
                    break;

                System.out.println("The Service name is: " + service.name());
                if (service.name().compareTo("Account") == 0)
                    serviceCode = service.code();

                // Get the Categories for this service.
                List<Category> categories = service.categories();
                for (Category cat : categories) {
                    System.out.println("The category name is: " + cat.name());
                    if (cat.name().compareTo("Security") == 0)
                        catName = cat.name();
                }
                index++;
            }

            // Push the two values to the list.
            sevCatList.add(serviceCode);
            sevCatList.add(catName);
            return sevCatList;

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return null;
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeServices](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeServices)」を参照してください。

### `DescribeSeverityLevels`
<a name="support_DescribeSeverityLevels_java_2_topic"></a>

次のコード例は、`DescribeSeverityLevels` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static String displaySevLevels(SupportClient supportClient) {
        try {
            DescribeSeverityLevelsRequest severityLevelsRequest = DescribeSeverityLevelsRequest.builder()
                    .language("en")
                    .build();

            DescribeSeverityLevelsResponse response = supportClient.describeSeverityLevels(severityLevelsRequest);
            List<SeverityLevel> severityLevels = response.severityLevels();
            String levelName = null;
            for (SeverityLevel sevLevel : severityLevels) {
                System.out.println("The severity level name is: " + sevLevel.name());
                if (sevLevel.name().compareTo("High") == 0)
                    levelName = sevLevel.name();
            }
            return levelName;

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
        return "";
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DescribeSeverityLevels](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/DescribeSeverityLevels)」を参照してください。

### `ResolveCase`
<a name="support_ResolveCase_java_2_topic"></a>

次のコード例は、`ResolveCase` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
    public static void resolveSupportCase(SupportClient supportClient, String caseId) {
        try {
            ResolveCaseRequest caseRequest = ResolveCaseRequest.builder()
                    .caseId(caseId)
                    .build();

            ResolveCaseResponse response = supportClient.resolveCase(caseRequest);
            System.out.println("The status of case " + caseId + " is " + response.finalCaseStatus());

        } catch (SupportException e) {
            System.out.println(e.getLocalizedMessage());
            System.exit(1);
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[ResolveCase](https://docs.aws.amazon.com/goto/SdkForJavaV2/support-2013-04-15/ResolveCase)」を参照してください。

# SDK for Java 2.x を使用した Systems Manager の例
<a name="java_2_ssm_code_examples"></a>

次のコード例は、Systems Manager AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにちは、Systems Manager
<a name="ssm_Hello_java_2_topic"></a>

次のコード例は、Systems Manager の使用を開始する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.DocumentFilter;
import software.amazon.awssdk.services.ssm.model.ListDocumentsRequest;
import software.amazon.awssdk.services.ssm.model.ListDocumentsResponse;

public class HelloSSM {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <awsAccount>

                Where:
                    awsAccount - Your AWS Account number.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String awsAccount = args[0] ;
        Region region = Region.US_EAST_1;
        SsmClient ssmClient = SsmClient.builder()
            .region(region)
            .build();

        listDocuments(ssmClient, awsAccount);
    }

    /*
    This code automatically fetches the next set of results using the `nextToken` and
    stops once the desired maxResults (20 in this case) have been reached.
    */
    public static void listDocuments(SsmClient ssmClient, String awsAccount) {
        String nextToken = null;
        int totalDocumentsReturned = 0;
        int maxResults = 20;
        do {
            ListDocumentsRequest request = ListDocumentsRequest.builder()
                .documentFilterList(
                    DocumentFilter.builder()
                        .key("Owner")
                        .value(awsAccount)
                        .build()
                    )
                .maxResults(maxResults)
                .nextToken(nextToken)
                .build();

            ListDocumentsResponse response = ssmClient.listDocuments(request);
            response.documentIdentifiers().forEach(identifier -> System.out.println("Document Name: " + identifier.name()));
            nextToken = response.nextToken();
            totalDocumentsReturned += response.documentIdentifiers().size();
        } while (nextToken != null && totalDocumentsReturned < maxResults);
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListDocuments](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/ListDocuments)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ssm_Scenario_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ メンテナンスウィンドウを作成します。
+ メンテナンスウィンドウのスケジュールを変更します。
+ ドキュメントを作成します。
+ 指定された EC2 インスタンスにコマンドを送信します。
+ 新しい OpsItem を作成します。
+ OpsItem を更新して解決します。
+ メンテナンスウィンドウ、OpsItem、ドキュメントを削除します。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.services.ssm.model.DocumentAlreadyExistsException;
import software.amazon.awssdk.services.ssm.model.SsmException;

import java.util.Map;
import java.util.Scanner;
public class SSMScenario {
    public static final String DASHES = new String(new char[80]).replace("\0", "-");
    private static final String ROLES_STACK = "SsmStack3`1";

    public static void main(String[] args) {
        String usage = """
            Usage:
              <title> <source> <category> <severity>
      
            Where:
                title - The title of the parameter (default is Disk Space Alert).
                source - The source of the parameter (default is EC2).
                category - The category of the parameter. Valid values are 'Availability', 'Cost', 'Performance', 'Recovery', 'Security' (default is Performance).
                severity - The severity of the parameter. Severity should be a number from 1 to 4 (default is 2).
        """;

        Scanner scanner = new Scanner(System.in);
        SSMActions actions = new SSMActions();
        String documentName;
        String windowName;

        System.out.println("Use AWS CloudFormation to create the EC2 instance that is required for this scenario.");
        CloudFormationHelper.deployCloudFormationStack(ROLES_STACK);
        Map<String, String> stackOutputs = CloudFormationHelper.getStackOutputsAsync(ROLES_STACK).join();
        String instanceId = stackOutputs.get("InstanceId");
        System.out.println("The Instance ID: " + instanceId +" was created.");
        String title = "Disk Space Alert" ;
        String source = "EC2" ;
        String category = "Availability" ;
        String severity = "2" ;

        System.out.println(DASHES);
        System.out.println("""
                Welcome to the AWS Systems Manager SDK Basics scenario.
                This Java program demonstrates how to interact with AWS Systems Manager using the AWS SDK for Java (v2).
                AWS Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management solution.
                The program's primary functionalities include creating a maintenance window, creating a document, sending a command to a document,
                listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting AWS SSM resources.
                Upon completion of the program, all AWS resources are cleaned up.
                Let's get started...
            
                """);
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("1. Create an SSM maintenance window.");
        System.out.println("Please enter the maintenance window name (default is ssm-maintenance-window):");
        String win = scanner.nextLine();
        windowName = win.isEmpty() ? "ssm-maintenance-window" : win;
        String winId = null;
        try {
            winId = actions.createMaintenanceWindow(windowName);
            waitForInputToContinue(scanner);
            System.out.println("The maintenance window ID is: " + winId);
        } catch (DocumentAlreadyExistsException e) {
            System.err.println("The SSM maintenance window already exists. Retrieving existing window ID...");
            String existingWinId = actions.createMaintenanceWindow(windowName);
            System.out.println("Existing window ID: " + existingWinId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("2. Modify the maintenance window by changing the schedule");
        waitForInputToContinue(scanner);
        try {
            actions.updateSSMMaintenanceWindow(winId, windowName);
            waitForInputToContinue(scanner);
            System.out.println("The SSM maintenance window was successfully updated");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("3. Create an SSM document that defines the actions that Systems Manager performs on your managed nodes.");
        System.out.println("Please enter the document name (default is ssmdocument):");
        String doc = scanner.nextLine();
        documentName = doc.isEmpty() ? "ssmdocument" : doc;
        try {
            actions.createSSMDoc(documentName);
            waitForInputToContinue(scanner);
            System.out.println("The SSM document was successfully created");
        } catch (DocumentAlreadyExistsException e) {
            System.err.println("The SSM document already exists. Moving on");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("4. Now we are going to run a command on an EC2 instance");
        waitForInputToContinue(scanner);
        String commandId="";
        try {
            commandId = actions.sendSSMCommand(documentName, instanceId);
            waitForInputToContinue(scanner);
            System.out.println("The command was successfully sent. Command ID: " + commandId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
        } catch (InterruptedException e) {
            System.err.println("Thread was interrupted: " + e.getMessage());
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println("5. Lets get the time when the specific command was sent to the specific managed node");
        waitForInputToContinue(scanner);
        try {
            actions.displayCommands(commandId);
            System.out.println("The command invocations were successfully displayed.");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("""
             6. Now we will create an SSM OpsItem. 
             A SSM OpsItem is a feature provided by Amazon's Systems Manager (SSM) service. 
             It is a type of operational data item that allows you to manage and track various operational issues, 
             events, or tasks within your AWS environment.
             
             You can create OpsItems to track and manage operational issues as they arise. 
             For example, you could create an OpsItem whenever your application detects a critical error 
             or an anomaly in your infrastructure.
            """);

        waitForInputToContinue(scanner);
        String opsItemId;
        try {
            opsItemId = actions.createSSMOpsItem(title, source, category, severity);
            System.out.println(opsItemId + " was created");
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }
        waitForInputToContinue(scanner);
        System.out.println(DASHES);

        System.out.println(DASHES);
        System.out.println("7. Now we will update the SSM OpsItem "+opsItemId);
        waitForInputToContinue(scanner);
        String description = "An update to "+opsItemId ;
        try {
            actions.updateOpsItem(opsItemId, title, description);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }

        System.out.println(DASHES);
        System.out.println("8. Now we will get the status of the SSM OpsItem "+opsItemId);
        waitForInputToContinue(scanner);
        try {
            actions.describeOpsItems(opsItemId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }

        System.out.println(DASHES);
        System.out.println("9. Now we will resolve the SSM OpsItem "+opsItemId);
        waitForInputToContinue(scanner);
        try {
            actions.resolveOpsItem(opsItemId);
        } catch (SsmException e) {
            System.err.println("SSM error: " + e.getMessage());
            return;
        } catch (RuntimeException e) {
            System.err.println("Unexpected error: " + e.getMessage());
            return;
        }

        System.out.println(DASHES);
        System.out.println("10. Would you like to delete the AWS Systems Manager resources? (y/n)");
        String delAns = scanner.nextLine().trim();
        if (delAns.equalsIgnoreCase("y")) {
            System.out.println("You selected to delete the resources.");
            waitForInputToContinue(scanner);
            try {
                actions.deleteMaintenanceWindow(winId);
                actions.deleteDoc(documentName);
            } catch (SsmException e) {
                System.err.println("SSM error: " + e.getMessage());
                return;
            } catch (RuntimeException e) {
                System.err.println("Unexpected error: " + e.getMessage());
                return;
            }
        } else {
            System.out.println("The AWS Systems Manager resources will not be deleted");
        }
        System.out.println(DASHES);
        CloudFormationHelper.destroyCloudFormationStack(ROLES_STACK);
        System.out.println("This concludes the AWS Systems Manager SDK Basics scenario.");
        System.out.println(DASHES);
    }

    private static void waitForInputToContinue(Scanner scanner) {
        while (true) {
            System.out.println("");
            System.out.println("Enter 'c' followed by <ENTER> to continue:");
            String input = scanner.nextLine();

            if (input.trim().equalsIgnoreCase("c")) {
                System.out.println("Continuing with the program...");
                System.out.println("");
                break;
            } else {
                // Handle invalid input.
                System.out.println("Invalid input. Please try again.");
            }
        }
    }
}
```
Systems Manager SDK メソッドのラッパークラス。  

```
public class SSMActions {

    private static SsmAsyncClient ssmAsyncClient;

    private static SsmAsyncClient getAsyncClient() {
        if (ssmAsyncClient == null) {
            SdkAsyncHttpClient httpClient = NettyNioAsyncHttpClient.builder()
                    .maxConcurrency(100)
                    .connectionTimeout(Duration.ofSeconds(60))
                    .readTimeout(Duration.ofSeconds(60))
                    .writeTimeout(Duration.ofSeconds(60))
                    .build();

            ClientOverrideConfiguration overrideConfig = ClientOverrideConfiguration.builder()
                    .apiCallTimeout(Duration.ofMinutes(2))
                    .apiCallAttemptTimeout(Duration.ofSeconds(90))
                    .retryPolicy(RetryPolicy.builder()
                            .numRetries(3)
                            .build())
                    .build();

            ssmAsyncClient = SsmAsyncClient.builder()
                    .region(Region.US_WEST_2)
                    .httpClient(httpClient)
                    .overrideConfiguration(overrideConfig)
                    .build();
        }
        return ssmAsyncClient;
    }

    /**
     * Deletes an AWS SSM document asynchronously.
     *
     * @param documentName The name of the document to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM document.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteDoc(String documentName) {
        DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder()
                .name(documentName)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteDocument(documentRequest)
                    .thenAccept(response -> {
                        System.out.println("The SSM document was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Deletes an AWS SSM Maintenance Window asynchronously.
     *
     * @param winId The ID of the Maintenance Window to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM Maintenance Window.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteMaintenanceWindow(String winId) {
        DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder()
                .windowId(winId)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteMaintenanceWindow(windowRequest)
                    .thenAccept(response -> {
                        System.out.println("The maintenance window was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Resolves an AWS SSM OpsItem asynchronously.
     *
     * @param opsID The ID of the OpsItem to resolve.
     * <p>
     * This method initiates an asynchronous request to resolve an SSM OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void resolveOpsItem(String opsID) {
        UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder()
                .opsItemId(opsID)
                .status(OpsItemStatus.RESOLVED)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().updateOpsItem(opsItemRequest)
                    .thenAccept(response -> {
                        System.out.println("OpsItem resolved successfully.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Describes AWS SSM OpsItems asynchronously.
     *
     * @param key The key to filter OpsItems by (e.g., OPS_ITEM_ID).
     *
     * This method initiates an asynchronous request to describe SSM OpsItems.
     * If the request is successful, it prints the title and status of each OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void describeOpsItems(String key) {
        OpsItemFilter filter = OpsItemFilter.builder()
                .key(OpsItemFilterKey.OPS_ITEM_ID)
                .values(key)
                .operator(OpsItemFilterOperator.EQUAL)
                .build();

        DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder()
                .maxResults(10)
                .opsItemFilters(filter)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().describeOpsItems(itemsRequest)
                    .thenAccept(itemsResponse -> {
                        List<OpsItemSummary> items = itemsResponse.opsItemSummaries();
                        for (OpsItemSummary item : items) {
                            System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString());
                        }
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }

    /**
     * Updates the AWS SSM OpsItem asynchronously.
     *
     * @param opsItemId The ID of the OpsItem to update.
     * @param title The new title of the OpsItem.
     * @param description The new description of the OpsItem.
     * <p>
     * This method initiates an asynchronous request to update an SSM OpsItem.
     * If the request is successful, it completes without returning a value.
     * If an exception occurs, it handles the error appropriately.
     */
    public void updateOpsItem(String opsItemId, String title, String description) {
        Map<String, OpsItemDataValue> operationalData = new HashMap<>();
        operationalData.put("key1", OpsItemDataValue.builder().value("value1").build());
        operationalData.put("key2", OpsItemDataValue.builder().value("value2").build());

        CompletableFuture<Void> future = getOpsItem(opsItemId).thenCompose(opsItem -> {
            UpdateOpsItemRequest request = UpdateOpsItemRequest.builder()
                    .opsItemId(opsItemId)
                    .title(title)
                    .operationalData(operationalData)
                    .status(opsItem.statusAsString())
                    .description(description)
                    .build();

            return getAsyncClient().updateOpsItem(request).thenAccept(response -> {
                System.out.println(opsItemId + " updated successfully.");
            }).exceptionally(ex -> {
                throw new CompletionException(ex);
            });
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }


    private static CompletableFuture<OpsItem> getOpsItem(String opsItemId) {
        GetOpsItemRequest request = GetOpsItemRequest.builder().opsItemId(opsItemId).build();
        return getAsyncClient().getOpsItem(request).thenApply(GetOpsItemResponse::opsItem);
    }

    /**
     * Creates an SSM OpsItem asynchronously.
     *
     * @param title The title of the OpsItem.
     * @param source The source of the OpsItem.
     * @param category The category of the OpsItem.
     * @param severity The severity of the OpsItem.
     * @return The ID of the created OpsItem.
     * <p>
     * This method initiates an asynchronous request to create an SSM OpsItem.
     * If the request is successful, it returns the OpsItem ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createSSMOpsItem(String title, String source, String category, String severity) {
        CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder()
                .description("Created by the SSM Java API")
                .title(title)
                .source(source)
                .category(category)
                .severity(severity)
                .build();

        CompletableFuture<CreateOpsItemResponse> future = getAsyncClient().createOpsItem(opsItemRequest);

        try {
            CreateOpsItemResponse response = future.join();
            return response.opsItemId();
        } catch (CompletionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof SsmException) {
                throw (SsmException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }
    }

    /**
     * Displays the date and time when the specific command was invoked.
     *
     * @param commandId The ID of the command to describe.
     * <p>
     * This method initiates an asynchronous request to list command invocations and prints the date and time of each command invocation.
     * If an exception occurs, it handles the error appropriately.
     */
    public void displayCommands(String commandId) {
        ListCommandInvocationsRequest commandInvocationsRequest = ListCommandInvocationsRequest.builder()
                .commandId(commandId)
                .build();

        CompletableFuture<ListCommandInvocationsResponse> future = getAsyncClient().listCommandInvocations(commandInvocationsRequest);
        future.thenAccept(response -> {
            List<CommandInvocation> commandList = response.commandInvocations();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault());
            for (CommandInvocation invocation : commandList) {
                System.out.println("The time of the command invocation is " + formatter.format(invocation.requestedDateTime()));
            }
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw (SsmException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }).join();
    }

    /**
     * Sends a SSM command to a managed node asynchronously.
     *
     * @param documentName The name of the document to use.
     * @param instanceId The ID of the instance to send the command to.
     * @return The command ID.
     * <p>
     * This method initiates asynchronous requests to send a SSM command to a managed node.
     * It waits until the document is active, sends the command, and checks the command execution status.
     */
    public String sendSSMCommand(String documentName, String instanceId) throws InterruptedException, SsmException {
        // Before we use Document to send a command - make sure it is active.
        CompletableFuture<Void> documentActiveFuture = CompletableFuture.runAsync(() -> {
            boolean isDocumentActive = false;
            DescribeDocumentRequest request = DescribeDocumentRequest.builder()
                    .name(documentName)
                    .build();

            while (!isDocumentActive) {
                CompletableFuture<DescribeDocumentResponse> response = getAsyncClient().describeDocument(request);
                String documentStatus = response.join().document().statusAsString();
                if (documentStatus.equals("Active")) {
                    System.out.println("The SSM document is active and ready to use.");
                    isDocumentActive = true;
                } else {
                    System.out.println("The SSM document is not active. Status: " + documentStatus);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        documentActiveFuture.join();

        // Create the SendCommandRequest.
        SendCommandRequest commandRequest = SendCommandRequest.builder()
                .documentName(documentName)
                .instanceIds(instanceId)
                .build();

        // Send the command.
        CompletableFuture<SendCommandResponse> commandFuture = getAsyncClient().sendCommand(commandRequest);
        final String[] commandId = {null};

        commandFuture.whenComplete((commandResponse, ex) -> {
            if (commandResponse != null) {
                commandId[0] = commandResponse.command().commandId();
                System.out.println("Command ID: " + commandId[0]);

                // Wait for the command execution to complete.
                GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder()
                        .commandId(commandId[0])
                        .instanceId(instanceId)
                        .build();

                try {
                    System.out.println("Wait 5 secs");
                    TimeUnit.SECONDS.sleep(5);

                    // Retrieve the command execution details.
                    CompletableFuture<GetCommandInvocationResponse> invocationFuture = getAsyncClient().getCommandInvocation(invocationRequest);
                    invocationFuture.whenComplete((commandInvocationResponse, invocationEx) -> {
                        if (commandInvocationResponse != null) {
                            // Check the status of the command execution.
                            CommandInvocationStatus status = commandInvocationResponse.status();
                            if (status == CommandInvocationStatus.SUCCESS) {
                                System.out.println("Command execution successful");
                            } else {
                                System.out.println("Command execution failed. Status: " + status);
                            }
                        } else {
                            Throwable invocationCause = (invocationEx instanceof CompletionException) ? invocationEx.getCause() : invocationEx;
                            throw new CompletionException(invocationCause);
                        }
                    }).join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof SsmException) {
                    throw (SsmException) cause;
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();

        return commandId[0];
    }

    /**
     * Creates an AWS SSM document asynchronously.
     *
     * @param docName The name of the document to create.
     * <p>
     * This method initiates an asynchronous request to create an SSM document.
     * If the request is successful, it prints the document status.
     * If an exception occurs, it handles the error appropriately.
     */
    public void createSSMDoc(String docName) throws SsmException {
        String jsonData = """
        {
        "schemaVersion": "2.2",
        "description": "Run a simple shell command",
        "mainSteps": [
            {
                "action": "aws:runShellScript",
                "name": "runEchoCommand",
                "inputs": {
                  "runCommand": [
                    "echo 'Hello, world!'"
                  ]
                }
              }
            ]
        }
        """;

        CreateDocumentRequest request = CreateDocumentRequest.builder()
                .content(jsonData)
                .name(docName)
                .documentType(DocumentType.COMMAND)
                .build();

        CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request);
        future.thenAccept(response -> {
            System.out.println("The status of the SSM document is " + response.documentDescription().status());
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof DocumentAlreadyExistsException) {
                throw new CompletionException(cause);
            } else if (cause instanceof SsmException) {
                throw new CompletionException(cause);
            } else {
                throw new RuntimeException(cause);
            }
        }).join();
    }

    /**
     * Updates an SSM maintenance window asynchronously.
     *
     * @param id The ID of the maintenance window to update.
     * @param name The new name for the maintenance window.
     * <p>
     * This method initiates an asynchronous request to update an SSM maintenance window.
     * If the request is successful, it prints a success message.
     * If an exception occurs, it handles the error appropriately.
     */
    public void updateSSMMaintenanceWindow(String id, String name) throws SsmException {
        UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder()
                .windowId(id)
                .allowUnassociatedTargets(true)
                .duration(24)
                .enabled(true)
                .name(name)
                .schedule("cron(0 0 ? * MON *)")
                .build();

        CompletableFuture<UpdateMaintenanceWindowResponse> future = getAsyncClient().updateMaintenanceWindow(updateRequest);
        future.whenComplete((response, ex) -> {
            if (response != null) {
                System.out.println("The SSM maintenance window was successfully updated");
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();
    }

    /**
     * Creates an SSM maintenance window asynchronously.
     *
     * @param winName The name of the maintenance window.
     * @return The ID of the created or existing maintenance window.
     * <p>
     * This method initiates an asynchronous request to create an SSM maintenance window.
     * If the request is successful, it prints the maintenance window ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException {
        CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder()
                .name(winName)
                .description("This is my maintenance window")
                .allowUnassociatedTargets(true)
                .duration(2)
                .cutoff(1)
                .schedule("cron(0 10 ? * MON-FRI *)")
                .build();

        CompletableFuture<CreateMaintenanceWindowResponse> future = getAsyncClient().createMaintenanceWindow(request);
        final String[] windowId = {null};
        future.whenComplete((response, ex) -> {
            if (response != null) {
                String maintenanceWindowId = response.windowId();
                System.out.println("The maintenance window id is " + maintenanceWindowId);
                windowId[0] = maintenanceWindowId;
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof DocumentAlreadyExistsException) {
                    throw new CompletionException(cause);
                } else if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();

        if (windowId[0] == null) {
            MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder()
                    .key("name")
                    .values(winName)
                    .build();

            DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder()
                    .filters(filter)
                    .build();

            CompletableFuture<DescribeMaintenanceWindowsResponse> describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest);
            describeFuture.whenComplete((describeResponse, describeEx) -> {
                if (describeResponse != null) {
                    List<MaintenanceWindowIdentity> windows = describeResponse.windowIdentities();
                    if (!windows.isEmpty()) {
                        windowId[0] = windows.get(0).windowId();
                        System.out.println("Window ID: " + windowId[0]);
                    } else {
                        System.out.println("Window not found.");
                        windowId[0] = "";
                    }
                } else {
                    Throwable describeCause = (describeEx instanceof CompletionException) ? describeEx.getCause() : describeEx;
                    throw new RuntimeException("Error describing maintenance windows: " + describeCause.getMessage(), describeCause);
                }
            }).join();
        }

        return windowId[0];
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [CreateDocument](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateDocument)
  + [CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateMaintenanceWindow)
  + [CreateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateOpsItem)
  + [DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DeleteMaintenanceWindow)
  + [ListCommandInvocations](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/ListCommandInvocations)
  + [SendCommand](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/SendCommand)
  + [UpdateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/UpdateOpsItem)

## アクション
<a name="actions"></a>

### `CreateDocument`
<a name="ssm_CreateDocument_java_2_topic"></a>

次のコード例は、`CreateDocument` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an AWS SSM document asynchronously.
     *
     * @param docName The name of the document to create.
     * <p>
     * This method initiates an asynchronous request to create an SSM document.
     * If the request is successful, it prints the document status.
     * If an exception occurs, it handles the error appropriately.
     */
    public void createSSMDoc(String docName) throws SsmException {
        String jsonData = """
        {
        "schemaVersion": "2.2",
        "description": "Run a simple shell command",
        "mainSteps": [
            {
                "action": "aws:runShellScript",
                "name": "runEchoCommand",
                "inputs": {
                  "runCommand": [
                    "echo 'Hello, world!'"
                  ]
                }
              }
            ]
        }
        """;

        CreateDocumentRequest request = CreateDocumentRequest.builder()
                .content(jsonData)
                .name(docName)
                .documentType(DocumentType.COMMAND)
                .build();

        CompletableFuture<CreateDocumentResponse> future = getAsyncClient().createDocument(request);
        future.thenAccept(response -> {
            System.out.println("The status of the SSM document is " + response.documentDescription().status());
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof DocumentAlreadyExistsException) {
                throw new CompletionException(cause);
            } else if (cause instanceof SsmException) {
                throw new CompletionException(cause);
            } else {
                throw new RuntimeException(cause);
            }
        }).join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateDocument](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateDocument)」を参照してください。

### `CreateMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_java_2_topic"></a>

次のコード例は、`CreateMaintenanceWindow` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an SSM maintenance window asynchronously.
     *
     * @param winName The name of the maintenance window.
     * @return The ID of the created or existing maintenance window.
     * <p>
     * This method initiates an asynchronous request to create an SSM maintenance window.
     * If the request is successful, it prints the maintenance window ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createMaintenanceWindow(String winName) throws SsmException, DocumentAlreadyExistsException {
        CreateMaintenanceWindowRequest request = CreateMaintenanceWindowRequest.builder()
                .name(winName)
                .description("This is my maintenance window")
                .allowUnassociatedTargets(true)
                .duration(2)
                .cutoff(1)
                .schedule("cron(0 10 ? * MON-FRI *)")
                .build();

        CompletableFuture<CreateMaintenanceWindowResponse> future = getAsyncClient().createMaintenanceWindow(request);
        final String[] windowId = {null};
        future.whenComplete((response, ex) -> {
            if (response != null) {
                String maintenanceWindowId = response.windowId();
                System.out.println("The maintenance window id is " + maintenanceWindowId);
                windowId[0] = maintenanceWindowId;
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof DocumentAlreadyExistsException) {
                    throw new CompletionException(cause);
                } else if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();

        if (windowId[0] == null) {
            MaintenanceWindowFilter filter = MaintenanceWindowFilter.builder()
                    .key("name")
                    .values(winName)
                    .build();

            DescribeMaintenanceWindowsRequest winRequest = DescribeMaintenanceWindowsRequest.builder()
                    .filters(filter)
                    .build();

            CompletableFuture<DescribeMaintenanceWindowsResponse> describeFuture = getAsyncClient().describeMaintenanceWindows(winRequest);
            describeFuture.whenComplete((describeResponse, describeEx) -> {
                if (describeResponse != null) {
                    List<MaintenanceWindowIdentity> windows = describeResponse.windowIdentities();
                    if (!windows.isEmpty()) {
                        windowId[0] = windows.get(0).windowId();
                        System.out.println("Window ID: " + windowId[0]);
                    } else {
                        System.out.println("Window not found.");
                        windowId[0] = "";
                    }
                } else {
                    Throwable describeCause = (describeEx instanceof CompletionException) ? describeEx.getCause() : describeEx;
                    throw new RuntimeException("Error describing maintenance windows: " + describeCause.getMessage(), describeCause);
                }
            }).join();
        }

        return windowId[0];
    }
```
+  API の詳細については、AWS SDK for Java 2.x API リファレンスの「[CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateMaintenanceWindow)」を参照してください。**

### `CreateOpsItem`
<a name="ssm_CreateOpsItem_java_2_topic"></a>

次のコード例は、`CreateOpsItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an SSM OpsItem asynchronously.
     *
     * @param title The title of the OpsItem.
     * @param source The source of the OpsItem.
     * @param category The category of the OpsItem.
     * @param severity The severity of the OpsItem.
     * @return The ID of the created OpsItem.
     * <p>
     * This method initiates an asynchronous request to create an SSM OpsItem.
     * If the request is successful, it returns the OpsItem ID.
     * If an exception occurs, it handles the error appropriately.
     */
    public String createSSMOpsItem(String title, String source, String category, String severity) {
        CreateOpsItemRequest opsItemRequest = CreateOpsItemRequest.builder()
                .description("Created by the SSM Java API")
                .title(title)
                .source(source)
                .category(category)
                .severity(severity)
                .build();

        CompletableFuture<CreateOpsItemResponse> future = getAsyncClient().createOpsItem(opsItemRequest);

        try {
            CreateOpsItemResponse response = future.join();
            return response.opsItemId();
        } catch (CompletionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof SsmException) {
                throw (SsmException) cause;
            } else {
                throw new RuntimeException(cause);
            }
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[CreateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/CreateOpsItem)」を参照してください。

### `DeleteDocument`
<a name="ssm_DeleteDocument_java_2_topic"></a>

次のコード例は、`DeleteDocument` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an AWS SSM document asynchronously.
     *
     * @param documentName The name of the document to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM document.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteDoc(String documentName) {
        DeleteDocumentRequest documentRequest = DeleteDocumentRequest.builder()
                .name(documentName)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteDocument(documentRequest)
                    .thenAccept(response -> {
                        System.out.println("The SSM document was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteDocument](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DeleteDocument)」を参照してください。

### `DeleteMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_java_2_topic"></a>

次のコード例は、`DeleteMaintenanceWindow` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an AWS SSM Maintenance Window asynchronously.
     *
     * @param winId The ID of the Maintenance Window to delete.
     * <p>
     * This method initiates an asynchronous request to delete an SSM Maintenance Window.
     * If an exception occurs, it handles the error appropriately.
     */
    public void deleteMaintenanceWindow(String winId) {
        DeleteMaintenanceWindowRequest windowRequest = DeleteMaintenanceWindowRequest.builder()
                .windowId(winId)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().deleteMaintenanceWindow(windowRequest)
                    .thenAccept(response -> {
                        System.out.println("The maintenance window was successfully deleted.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DeleteMaintenanceWindow)」を参照してください。

### `DescribeOpsItems`
<a name="ssm_DescribeOpsItems_java_2_topic"></a>

次のコード例は、`DescribeOpsItems` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Describes AWS SSM OpsItems asynchronously.
     *
     * @param key The key to filter OpsItems by (e.g., OPS_ITEM_ID).
     *
     * This method initiates an asynchronous request to describe SSM OpsItems.
     * If the request is successful, it prints the title and status of each OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void describeOpsItems(String key) {
        OpsItemFilter filter = OpsItemFilter.builder()
                .key(OpsItemFilterKey.OPS_ITEM_ID)
                .values(key)
                .operator(OpsItemFilterOperator.EQUAL)
                .build();

        DescribeOpsItemsRequest itemsRequest = DescribeOpsItemsRequest.builder()
                .maxResults(10)
                .opsItemFilters(filter)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().describeOpsItems(itemsRequest)
                    .thenAccept(itemsResponse -> {
                        List<OpsItemSummary> items = itemsResponse.opsItemSummaries();
                        for (OpsItemSummary item : items) {
                            System.out.println("The item title is " + item.title() + " and the status is " + item.status().toString());
                        }
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeOpsItems](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DescribeOpsItems)」を参照してください。

### `DescribeParameters`
<a name="ssm_DescribeParameters_java_2_topic"></a>

次のコード例は、`DescribeParameters` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.GetParameterRequest;
import software.amazon.awssdk.services.ssm.model.GetParameterResponse;
import software.amazon.awssdk.services.ssm.model.SsmException;

/**
 * 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 GetParameter {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <paraName>

                Where:
                    paraName - The name of the parameter.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String paraName = args[0];
        Region region = Region.US_EAST_1;
        SsmClient ssmClient = SsmClient.builder()
                .region(region)
                .build();

        getParaValue(ssmClient, paraName);
        ssmClient.close();
    }

    public static void getParaValue(SsmClient ssmClient, String paraName) {
        try {
            GetParameterRequest parameterRequest = GetParameterRequest.builder()
                    .name(paraName)
                    .build();

            GetParameterResponse parameterResponse = ssmClient.getParameter(parameterRequest);
            System.out.println("The parameter value is " + parameterResponse.parameter().value());

        } catch (SsmException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DescribeParameters](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/DescribeParameters)」を参照してください。

### `PutParameter`
<a name="ssm_PutParameter_java_2_topic"></a>

次のコード例は、`PutParameter` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.ssm.SsmClient;
import software.amazon.awssdk.services.ssm.model.ParameterType;
import software.amazon.awssdk.services.ssm.model.PutParameterRequest;
import software.amazon.awssdk.services.ssm.model.SsmException;

public class PutParameter {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <paraName>

                Where:
                    paraName - The name of the parameter.
                    paraValue - The value of the parameter.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String paraName = args[0];
        String paraValue = args[1];
        Region region = Region.US_EAST_1;
        SsmClient ssmClient = SsmClient.builder()
                .region(region)
                .build();

        putParaValue(ssmClient, paraName, paraValue);
        ssmClient.close();
    }

    public static void putParaValue(SsmClient ssmClient, String paraName, String value) {
        try {
            PutParameterRequest parameterRequest = PutParameterRequest.builder()
                    .name(paraName)
                    .type(ParameterType.STRING)
                    .value(value)
                    .build();

            ssmClient.putParameter(parameterRequest);
            System.out.println("The parameter was successfully added.");

        } catch (SsmException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[PutParameter](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/PutParameter)」を参照してください。

### `SendCommand`
<a name="ssm_SendCommand_java_2_topic"></a>

次のコード例は、`SendCommand` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Sends a SSM command to a managed node asynchronously.
     *
     * @param documentName The name of the document to use.
     * @param instanceId The ID of the instance to send the command to.
     * @return The command ID.
     * <p>
     * This method initiates asynchronous requests to send a SSM command to a managed node.
     * It waits until the document is active, sends the command, and checks the command execution status.
     */
    public String sendSSMCommand(String documentName, String instanceId) throws InterruptedException, SsmException {
        // Before we use Document to send a command - make sure it is active.
        CompletableFuture<Void> documentActiveFuture = CompletableFuture.runAsync(() -> {
            boolean isDocumentActive = false;
            DescribeDocumentRequest request = DescribeDocumentRequest.builder()
                    .name(documentName)
                    .build();

            while (!isDocumentActive) {
                CompletableFuture<DescribeDocumentResponse> response = getAsyncClient().describeDocument(request);
                String documentStatus = response.join().document().statusAsString();
                if (documentStatus.equals("Active")) {
                    System.out.println("The SSM document is active and ready to use.");
                    isDocumentActive = true;
                } else {
                    System.out.println("The SSM document is not active. Status: " + documentStatus);
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });

        documentActiveFuture.join();

        // Create the SendCommandRequest.
        SendCommandRequest commandRequest = SendCommandRequest.builder()
                .documentName(documentName)
                .instanceIds(instanceId)
                .build();

        // Send the command.
        CompletableFuture<SendCommandResponse> commandFuture = getAsyncClient().sendCommand(commandRequest);
        final String[] commandId = {null};

        commandFuture.whenComplete((commandResponse, ex) -> {
            if (commandResponse != null) {
                commandId[0] = commandResponse.command().commandId();
                System.out.println("Command ID: " + commandId[0]);

                // Wait for the command execution to complete.
                GetCommandInvocationRequest invocationRequest = GetCommandInvocationRequest.builder()
                        .commandId(commandId[0])
                        .instanceId(instanceId)
                        .build();

                try {
                    System.out.println("Wait 5 secs");
                    TimeUnit.SECONDS.sleep(5);

                    // Retrieve the command execution details.
                    CompletableFuture<GetCommandInvocationResponse> invocationFuture = getAsyncClient().getCommandInvocation(invocationRequest);
                    invocationFuture.whenComplete((commandInvocationResponse, invocationEx) -> {
                        if (commandInvocationResponse != null) {
                            // Check the status of the command execution.
                            CommandInvocationStatus status = commandInvocationResponse.status();
                            if (status == CommandInvocationStatus.SUCCESS) {
                                System.out.println("Command execution successful");
                            } else {
                                System.out.println("Command execution failed. Status: " + status);
                            }
                        } else {
                            Throwable invocationCause = (invocationEx instanceof CompletionException) ? invocationEx.getCause() : invocationEx;
                            throw new CompletionException(invocationCause);
                        }
                    }).join();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof SsmException) {
                    throw (SsmException) cause;
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();

        return commandId[0];
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[SendCommand](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/SendCommand)」を参照してください。

### `UpdateMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_java_2_topic"></a>

次のコード例は、`UpdateMaintenanceWindow` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Updates an SSM maintenance window asynchronously.
     *
     * @param id The ID of the maintenance window to update.
     * @param name The new name for the maintenance window.
     * <p>
     * This method initiates an asynchronous request to update an SSM maintenance window.
     * If the request is successful, it prints a success message.
     * If an exception occurs, it handles the error appropriately.
     */
    public void updateSSMMaintenanceWindow(String id, String name) throws SsmException {
        UpdateMaintenanceWindowRequest updateRequest = UpdateMaintenanceWindowRequest.builder()
                .windowId(id)
                .allowUnassociatedTargets(true)
                .duration(24)
                .enabled(true)
                .name(name)
                .schedule("cron(0 0 ? * MON *)")
                .build();

        CompletableFuture<UpdateMaintenanceWindowResponse> future = getAsyncClient().updateMaintenanceWindow(updateRequest);
        future.whenComplete((response, ex) -> {
            if (response != null) {
                System.out.println("The SSM maintenance window was successfully updated");
            } else {
                Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
                if (cause instanceof SsmException) {
                    throw new CompletionException(cause);
                } else {
                    throw new RuntimeException(cause);
                }
            }
        }).join();
    }
```
+  API の詳細については、*AWS SDK for Java 2.x API リファレンス*の「[UpdateMaintenanceWindow](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/UpdateMaintenanceWindow)」を参照してください。

### `UpdateOpsItem`
<a name="ssm_UpdateOpsItem_java_2_topic"></a>

次のコード例は、`UpdateOpsItem` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Resolves an AWS SSM OpsItem asynchronously.
     *
     * @param opsID The ID of the OpsItem to resolve.
     * <p>
     * This method initiates an asynchronous request to resolve an SSM OpsItem.
     * If an exception occurs, it handles the error appropriately.
     */
    public void resolveOpsItem(String opsID) {
        UpdateOpsItemRequest opsItemRequest = UpdateOpsItemRequest.builder()
                .opsItemId(opsID)
                .status(OpsItemStatus.RESOLVED)
                .build();

        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            getAsyncClient().updateOpsItem(opsItemRequest)
                    .thenAccept(response -> {
                        System.out.println("OpsItem resolved successfully.");
                    })
                    .exceptionally(ex -> {
                        throw new CompletionException(ex);
                    }).join();
        }).exceptionally(ex -> {
            Throwable cause = (ex instanceof CompletionException) ? ex.getCause() : ex;
            if (cause instanceof SsmException) {
                throw new RuntimeException("SSM error: " + cause.getMessage(), cause);
            } else {
                throw new RuntimeException("Unexpected error: " + cause.getMessage(), cause);
            }
        });

        try {
            future.join();
        } catch (CompletionException ex) {
            throw ex.getCause() instanceof RuntimeException ? (RuntimeException) ex.getCause() : ex;
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[UpdateOpsItem](https://docs.aws.amazon.com/goto/SdkForJavaV2/ssm-2014-11-06/UpdateOpsItem)」を参照してください。

# SDK for Java 2.x を使用する Amazon Textract の例
<a name="java_2_textract_code_examples"></a>

次のコード例は、Amazon Textract AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AnalyzeDocument`
<a name="textract_AnalyzeDocument_java_2_topic"></a>

次のコード例は、`AnalyzeDocument` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/textract#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.textract.TextractClient;
import software.amazon.awssdk.services.textract.model.AnalyzeDocumentRequest;
import software.amazon.awssdk.services.textract.model.Document;
import software.amazon.awssdk.services.textract.model.FeatureType;
import software.amazon.awssdk.services.textract.model.AnalyzeDocumentResponse;
import software.amazon.awssdk.services.textract.model.Block;
import software.amazon.awssdk.services.textract.model.TextractException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 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 AnalyzeDocument {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <sourceDoc>\s

                Where:
                    sourceDoc - The path where the document is located (must be an image, for example, C:/AWS/book.png).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String sourceDoc = args[0];
        Region region = Region.US_EAST_2;
        TextractClient textractClient = TextractClient.builder()
                .region(region)
                .build();

        analyzeDoc(textractClient, sourceDoc);
        textractClient.close();
    }

    public static void analyzeDoc(TextractClient textractClient, String sourceDoc) {
        try {
            InputStream sourceStream = new FileInputStream(new File(sourceDoc));
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);

            // Get the input Document object as bytes
            Document myDoc = Document.builder()
                    .bytes(sourceBytes)
                    .build();

            List<FeatureType> featureTypes = new ArrayList<FeatureType>();
            featureTypes.add(FeatureType.FORMS);
            featureTypes.add(FeatureType.TABLES);

            AnalyzeDocumentRequest analyzeDocumentRequest = AnalyzeDocumentRequest.builder()
                    .featureTypes(featureTypes)
                    .document(myDoc)
                    .build();

            AnalyzeDocumentResponse analyzeDocument = textractClient.analyzeDocument(analyzeDocumentRequest);
            List<Block> docInfo = analyzeDocument.blocks();
            Iterator<Block> blockIterator = docInfo.iterator();

            while (blockIterator.hasNext()) {
                Block block = blockIterator.next();
                System.out.println("The block type is " + block.blockType().toString());
            }

        } catch (TextractException | FileNotFoundException e) {

            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の [AnalyzeDocument](https://docs.aws.amazon.com/goto/SdkForJavaV2/textract-2018-06-27/AnalyzeDocument)」を参照してください。

### `DetectDocumentText`
<a name="textract_DetectDocumentText_java_2_topic"></a>

次のコード例は、`DetectDocumentText` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/textract#code-examples)での設定と実行の方法を確認してください。
入力ドキュメントからテキストを検出します。  

```
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.textract.TextractClient;
import software.amazon.awssdk.services.textract.model.Document;
import software.amazon.awssdk.services.textract.model.DetectDocumentTextRequest;
import software.amazon.awssdk.services.textract.model.DetectDocumentTextResponse;
import software.amazon.awssdk.services.textract.model.Block;
import software.amazon.awssdk.services.textract.model.DocumentMetadata;
import software.amazon.awssdk.services.textract.model.TextractException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

/**
 * 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 DetectDocumentText {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <sourceDoc>\s

                Where:
                    sourceDoc - The path where the document is located (must be an image, for example, C:/AWS/book.png).\s
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String sourceDoc = args[0];
        Region region = Region.US_EAST_2;
        TextractClient textractClient = TextractClient.builder()
                .region(region)
                .build();

        detectDocText(textractClient, sourceDoc);
        textractClient.close();
    }

    public static void detectDocText(TextractClient textractClient, String sourceDoc) {
        try {
            InputStream sourceStream = new FileInputStream(new File(sourceDoc));
            SdkBytes sourceBytes = SdkBytes.fromInputStream(sourceStream);

            // Get the input Document object as bytes.
            Document myDoc = Document.builder()
                    .bytes(sourceBytes)
                    .build();

            DetectDocumentTextRequest detectDocumentTextRequest = DetectDocumentTextRequest.builder()
                    .document(myDoc)
                    .build();

            // Invoke the Detect operation.
            DetectDocumentTextResponse textResponse = textractClient.detectDocumentText(detectDocumentTextRequest);
            List<Block> docInfo = textResponse.blocks();
            for (Block block : docInfo) {
                System.out.println("The block type is " + block.blockType().toString());
            }

            DocumentMetadata documentMetadata = textResponse.documentMetadata();
            System.out.println("The number of pages in the document is " + documentMetadata.pages());

        } catch (TextractException | FileNotFoundException e) {

            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
Amazon S3 バケット内のドキュメントからテキストを検出する  

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.textract.model.S3Object;
import software.amazon.awssdk.services.textract.TextractClient;
import software.amazon.awssdk.services.textract.model.Document;
import software.amazon.awssdk.services.textract.model.DetectDocumentTextRequest;
import software.amazon.awssdk.services.textract.model.DetectDocumentTextResponse;
import software.amazon.awssdk.services.textract.model.Block;
import software.amazon.awssdk.services.textract.model.DocumentMetadata;
import software.amazon.awssdk.services.textract.model.TextractException;

/**
 * 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 DetectDocumentTextS3 {

    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <bucketName> <docName>\s

                Where:
                    bucketName - The name of the Amazon S3 bucket that contains the document.\s

                    docName - The document name (must be an image, i.e., book.png).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String docName = args[1];
        Region region = Region.US_WEST_2;
        TextractClient textractClient = TextractClient.builder()
                .region(region)
                .build();

        detectDocTextS3(textractClient, bucketName, docName);
        textractClient.close();
    }

    public static void detectDocTextS3(TextractClient textractClient, String bucketName, String docName) {
        try {
            S3Object s3Object = S3Object.builder()
                    .bucket(bucketName)
                    .name(docName)
                    .build();

            // Create a Document object and reference the s3Object instance.
            Document myDoc = Document.builder()
                    .s3Object(s3Object)
                    .build();

            DetectDocumentTextRequest detectDocumentTextRequest = DetectDocumentTextRequest.builder()
                    .document(myDoc)
                    .build();

            DetectDocumentTextResponse textResponse = textractClient.detectDocumentText(detectDocumentTextRequest);
            for (Block block : textResponse.blocks()) {
                System.out.println("The block type is " + block.blockType().toString());
            }

            DocumentMetadata documentMetadata = textResponse.documentMetadata();
            System.out.println("The number of pages in the document is " + documentMetadata.pages());

        } catch (TextractException e) {

            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[DetectDocumentText](https://docs.aws.amazon.com/goto/SdkForJavaV2/textract-2018-06-27/DetectDocumentText)」を参照してください。

### `StartDocumentAnalysis`
<a name="textract_StartDocumentAnalysis_java_2_topic"></a>

次のコード例は、`StartDocumentAnalysis` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/textract#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.textract.model.S3Object;
import software.amazon.awssdk.services.textract.TextractClient;
import software.amazon.awssdk.services.textract.model.StartDocumentAnalysisRequest;
import software.amazon.awssdk.services.textract.model.DocumentLocation;
import software.amazon.awssdk.services.textract.model.TextractException;
import software.amazon.awssdk.services.textract.model.StartDocumentAnalysisResponse;
import software.amazon.awssdk.services.textract.model.GetDocumentAnalysisRequest;
import software.amazon.awssdk.services.textract.model.GetDocumentAnalysisResponse;
import software.amazon.awssdk.services.textract.model.FeatureType;
import java.util.ArrayList;
import java.util.List;

/**
 * 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 StartDocumentAnalysis {
    public static void main(String[] args) {
        final String usage = """

                Usage:
                    <bucketName> <docName>\s

                Where:
                    bucketName - The name of the Amazon S3 bucket that contains the document.\s
                    docName - The document name (must be an image, for example, book.png).\s
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String bucketName = args[0];
        String docName = args[1];
        Region region = Region.US_WEST_2;
        TextractClient textractClient = TextractClient.builder()
                .region(region)
                .build();

        String jobId = startDocAnalysisS3(textractClient, bucketName, docName);
        System.out.println("Getting results for job " + jobId);
        String status = getJobResults(textractClient, jobId);
        System.out.println("The job status is " + status);
        textractClient.close();
    }

    public static String startDocAnalysisS3(TextractClient textractClient, String bucketName, String docName) {
        try {
            List<FeatureType> myList = new ArrayList<>();
            myList.add(FeatureType.TABLES);
            myList.add(FeatureType.FORMS);

            S3Object s3Object = S3Object.builder()
                    .bucket(bucketName)
                    .name(docName)
                    .build();

            DocumentLocation location = DocumentLocation.builder()
                    .s3Object(s3Object)
                    .build();

            StartDocumentAnalysisRequest documentAnalysisRequest = StartDocumentAnalysisRequest.builder()
                    .documentLocation(location)
                    .featureTypes(myList)
                    .build();

            StartDocumentAnalysisResponse response = textractClient.startDocumentAnalysis(documentAnalysisRequest);

            // Get the job ID
            String jobId = response.jobId();
            return jobId;

        } catch (TextractException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }

    private static String getJobResults(TextractClient textractClient, String jobId) {
        boolean finished = false;
        int index = 0;
        String status = "";

        try {
            while (!finished) {
                GetDocumentAnalysisRequest analysisRequest = GetDocumentAnalysisRequest.builder()
                        .jobId(jobId)
                        .maxResults(1000)
                        .build();

                GetDocumentAnalysisResponse response = textractClient.getDocumentAnalysis(analysisRequest);
                status = response.jobStatus().toString();

                if (status.compareTo("SUCCEEDED") == 0)
                    finished = true;
                else {
                    System.out.println(index + " status is: " + status);
                    Thread.sleep(1000);
                }
                index++;
            }

            return status;

        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartDocumentAnalysis](https://docs.aws.amazon.com/goto/SdkForJavaV2/textract-2018-06-27/StartDocumentAnalysis)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_java_2_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Java 2.x**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_fsa_app) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Java 2.x を使用した Amazon Transcribe の例
<a name="java_2_transcribe_code_examples"></a>

次のコード例は、Amazon Transcribe AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `ListTranscriptionJobs`
<a name="transcribe_ListTranscriptionJobs_java_2_topic"></a>

次のコード例は、`ListTranscriptionJobs` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
public class ListTranscriptionJobs {
    public static void main(String[] args) {
        TranscribeClient transcribeClient = TranscribeClient.builder()
            .region(Region.US_EAST_1)
            .build();

            listTranscriptionJobs(transcribeClient);
        }

        public static void listTranscriptionJobs(TranscribeClient transcribeClient) {
            ListTranscriptionJobsRequest listJobsRequest = ListTranscriptionJobsRequest.builder()
                .build();

            transcribeClient.listTranscriptionJobsPaginator(listJobsRequest).stream()
                .flatMap(response -> response.transcriptionJobSummaries().stream())
                .forEach(jobSummary -> {
                    System.out.println("Job Name: " + jobSummary.transcriptionJobName());
                    System.out.println("Job Status: " + jobSummary.transcriptionJobStatus());
                    System.out.println("Output Location: " + jobSummary.outputLocationType());
                    // Add more information as needed

                    // Retrieve additional details for the job if necessary
                    GetTranscriptionJobResponse jobDetails = transcribeClient.getTranscriptionJob(
                        GetTranscriptionJobRequest.builder()
                            .transcriptionJobName(jobSummary.transcriptionJobName())
                            .build());

                    // Display additional details
                    System.out.println("Language Code: " + jobDetails.transcriptionJob().languageCode());
                    System.out.println("Media Format: " + jobDetails.transcriptionJob().mediaFormat());
                    // Add more details as needed

                    System.out.println("--------------");
                });
        }
    }
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[ListTranscriptionJobs](https://docs.aws.amazon.com/goto/SdkForJavaV2/transcribe-2017-10-26/ListTranscriptionJobs)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 音声の文字起こしとジョブデータを取得する
<a name="transcribe_Scenario_GettingStartedTranscriptionJobs_java_2_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Transcribe で文字起こしジョブを開始します。
+  ジョブが完了するまで待ちます。
+ 書き起こしが保存されている URI を取得します。

詳細については、「[Amazon Transcribe の開始方法](https://docs.aws.amazon.com/transcribe/latest/dg/getting-started.html)」を参照してください。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
PCM ファイルを書き起こします。  

```
/**
 * To run this AWS code example, ensure that you have set up your development
 * environment, including your AWS credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class TranscribeStreamingDemoFile {
    private static final Region REGION = Region.US_EAST_1;
    private static TranscribeStreamingAsyncClient client;

    public static void main(String args[]) throws ExecutionException, InterruptedException {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    <file> \n\n" +
                "Where:\n" +
                "    file - the location of a PCM file to transcribe. In this example, ensure the PCM file is 16 hertz (Hz). \n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String file = args[0];
        client = TranscribeStreamingAsyncClient.builder()
                .region(REGION)
                .build();

        CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
                new AudioStreamPublisher(getStreamFromFile(file)),
                getResponseHandler());

        result.get();
        client.close();
    }

    private static InputStream getStreamFromFile(String file) {
        try {
            File inputFile = new File(file);
            InputStream audioStream = new FileInputStream(inputFile);
            return audioStream;

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
        return StartStreamTranscriptionRequest.builder()
                .languageCode(LanguageCode.EN_US)
                .mediaEncoding(MediaEncoding.PCM)
                .mediaSampleRateHertz(mediaSampleRateHertz)
                .build();
    }

    private static StartStreamTranscriptionResponseHandler getResponseHandler() {
        return StartStreamTranscriptionResponseHandler.builder()
                .onResponse(r -> {
                    System.out.println("Received Initial response");
                })
                .onError(e -> {
                    System.out.println(e.getMessage());
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    System.out.println("Error Occurred: " + sw.toString());
                })
                .onComplete(() -> {
                    System.out.println("=== All records stream successfully ===");
                })
                .subscriber(event -> {
                    List<Result> results = ((TranscriptEvent) event).transcript().results();
                    if (results.size() > 0) {
                        if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
                            System.out.println(results.get(0).alternatives().get(0).transcript());
                        }
                    }
                })
                .build();
    }

    private static class AudioStreamPublisher implements Publisher<AudioStream> {
        private final InputStream inputStream;
        private static Subscription currentSubscription;

        private AudioStreamPublisher(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void subscribe(Subscriber<? super AudioStream> s) {

            if (this.currentSubscription == null) {
                this.currentSubscription = new SubscriptionImpl(s, inputStream);
            } else {
                this.currentSubscription.cancel();
                this.currentSubscription = new SubscriptionImpl(s, inputStream);
            }
            s.onSubscribe(currentSubscription);
        }
    }

    public static class SubscriptionImpl implements Subscription {
        private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;
        private final Subscriber<? super AudioStream> subscriber;
        private final InputStream inputStream;
        private ExecutorService executor = Executors.newFixedThreadPool(1);
        private AtomicLong demand = new AtomicLong(0);

        SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
            this.subscriber = s;
            this.inputStream = inputStream;
        }

        @Override
        public void request(long n) {
            if (n <= 0) {
                subscriber.onError(new IllegalArgumentException("Demand must be positive"));
            }

            demand.getAndAdd(n);

            executor.submit(() -> {
                try {
                    do {
                        ByteBuffer audioBuffer = getNextEvent();
                        if (audioBuffer.remaining() > 0) {
                            AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
                            subscriber.onNext(audioEvent);
                        } else {
                            subscriber.onComplete();
                            break;
                        }
                    } while (demand.decrementAndGet() > 0);
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            });
        }

        @Override
        public void cancel() {
            executor.shutdown();
        }

        private ByteBuffer getNextEvent() {
            ByteBuffer audioBuffer = null;
            byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];

            int len = 0;
            try {
                len = inputStream.read(audioBytes);

                if (len <= 0) {
                    audioBuffer = ByteBuffer.allocate(0);
                } else {
                    audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }

            return audioBuffer;
        }

        private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
            return AudioEvent.builder()
                    .audioChunk(SdkBytes.fromByteBuffer(bb))
                    .build();
        }
    }
}
```
コンピュータのマイクからのストリーミングオーディオを文字起こしします。  

```
public class TranscribeStreamingDemoApp {
    private static final Region REGION = Region.US_EAST_1;
    private static TranscribeStreamingAsyncClient client;

    public static void main(String[] args)
            throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException {

        client = TranscribeStreamingAsyncClient.builder()
                .credentialsProvider(getCredentials())
                .region(REGION)
                .build();

        CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
                new AudioStreamPublisher(getStreamFromMic()),
                getResponseHandler());

        result.get();
        client.close();
    }

    private static InputStream getStreamFromMic() throws LineUnavailableException {

        // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
        int sampleRate = 16000;
        AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line not supported");
            System.exit(0);
        }

        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();

        InputStream audioStream = new AudioInputStream(line);
        return audioStream;
    }

    private static AwsCredentialsProvider getCredentials() {
        return DefaultCredentialsProvider.create();
    }

    private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
        return StartStreamTranscriptionRequest.builder()
                .languageCode(LanguageCode.EN_US.toString())
                .mediaEncoding(MediaEncoding.PCM)
                .mediaSampleRateHertz(mediaSampleRateHertz)
                .build();
    }

    private static StartStreamTranscriptionResponseHandler getResponseHandler() {
        return StartStreamTranscriptionResponseHandler.builder()
                .onResponse(r -> {
                    System.out.println("Received Initial response");
                })
                .onError(e -> {
                    System.out.println(e.getMessage());
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    System.out.println("Error Occurred: " + sw);
                })
                .onComplete(() -> {
                    System.out.println("=== All records stream successfully ===");
                })
                .subscriber(event -> {
                    List<Result> results = ((TranscriptEvent) event).transcript().results();
                    if (results.size() > 0) {
                        if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
                            System.out.println(results.get(0).alternatives().get(0).transcript());
                        }
                    }
                })
                .build();
    }

    
    private static class AudioStreamPublisher implements Publisher<AudioStream> {
        private static Subscription currentSubscription;
        private final InputStream inputStream;

        private AudioStreamPublisher(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void subscribe(Subscriber<? super AudioStream> s) {

            if (currentSubscription == null) {
                currentSubscription = new SubscriptionImpl(s, inputStream);
            } else {
                currentSubscription.cancel();
                currentSubscription = new SubscriptionImpl(s, inputStream);
            }
            s.onSubscribe(currentSubscription);
        }
    }

    public static class SubscriptionImpl implements Subscription {
        private static final int CHUNK_SIZE_IN_BYTES = 1024;
        private final Subscriber<? super AudioStream> subscriber;
        private final InputStream inputStream;
        private final ExecutorService executor = Executors.newFixedThreadPool(1);
        private final AtomicLong demand = new AtomicLong(0);

        SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
            this.subscriber = s;
            this.inputStream = inputStream;
        }

        @Override
        public void request(long n) {
            if (n <= 0) {
                subscriber.onError(new IllegalArgumentException("Demand must be positive"));
            }

            demand.getAndAdd(n);

            executor.submit(() -> {
                try {
                    do {
                        ByteBuffer audioBuffer = getNextEvent();
                        if (audioBuffer.remaining() > 0) {
                            AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
                            subscriber.onNext(audioEvent);
                        } else {
                            subscriber.onComplete();
                            break;
                        }
                    } while (demand.decrementAndGet() > 0);
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            });
        }

        @Override
        public void cancel() {
            executor.shutdown();
        }

        private ByteBuffer getNextEvent() {
            ByteBuffer audioBuffer = null;
            byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];

            int len = 0;
            try {
                len = inputStream.read(audioBytes);

                if (len <= 0) {
                    audioBuffer = ByteBuffer.allocate(0);
                } else {
                    audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }

            return audioBuffer;
        }

        private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
            return AudioEvent.builder()
                    .audioChunk(SdkBytes.fromByteBuffer(bb))
                    .build();
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の以下のトピックを参照してください。
  + [GetTranscriptionJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/transcribe-2017-10-26/GetTranscriptionJob)
  + [StartTranscriptionJob](https://docs.aws.amazon.com/goto/SdkForJavaV2/transcribe-2017-10-26/StartTranscriptionJob)

# SDK for Java 2.x を使用した Amazon Transcribe ストリーミングの例
<a name="java_2_transcribe-streaming_code_examples"></a>

次のコード例は、Amazon Transcribe Streaming AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `StartMedicalStreamTranscription`
<a name="transcribe-streaming_StartMedicalStreamTranscription_java_2_topic"></a>

次のコード例は、`StartMedicalStreamTranscription` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。

```
/*
To run this AWS code example, ensure that you have set up your development
 environment, including your AWS credentials.

 For information, see this documentation topic:

 https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html

This code demonstrates the process of starting a medical transcription job using the AWS Transcribe
Streaming service, including setting up the audio input stream, configuring the transcription request,
and handling the transcription response.
 */

public class TranscribeMedicalStreamingDemoApp {
    private static TranscribeStreamingAsyncClient client;

    public static void main(String args[])
        throws ExecutionException, InterruptedException, LineUnavailableException {

        client = TranscribeStreamingAsyncClient.builder()
            .credentialsProvider(getCredentials())
            .build();

        CompletableFuture<Void> result = client.startMedicalStreamTranscription(getMedicalRequest(16_000),
            new AudioStreamPublisher(getStreamFromMic()),
            getMedicalResponseHandler());

        result.get();
        client.close();
    }

    private static InputStream getStreamFromMic() throws LineUnavailableException {

        // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
        int sampleRate = 16000;
        AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line not supported");
            throw new LineUnavailableException("The audio system microphone line is not supported.");
        }

        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();

        InputStream audioStream = new AudioInputStream(line);
        return audioStream;
    }

    private static AwsCredentialsProvider getCredentials() {
        return DefaultCredentialsProvider.create();
    }

    private static StartMedicalStreamTranscriptionRequest getMedicalRequest(Integer mediaSampleRateHertz) {
        return StartMedicalStreamTranscriptionRequest.builder()
            .languageCode(LanguageCode.EN_US.toString()) // For medical transcription, EN_US is typically used.
            .mediaEncoding(MediaEncoding.PCM)
            .mediaSampleRateHertz(mediaSampleRateHertz)
            .specialty(Specialty.PRIMARYCARE) // Specify the medical specialty.
            .type(Type.CONVERSATION) // Set the type as CONVERSATION or DICTATION.
            .build();
    }

    private static StartMedicalStreamTranscriptionResponseHandler getMedicalResponseHandler() {
        return StartMedicalStreamTranscriptionResponseHandler.builder()
            .onResponse(r -> {
                System.out.println("Received Initial response");
            })
            .onError(e -> {
                System.out.println(e.getMessage());
                StringWriter sw = new StringWriter();
                e.printStackTrace(new PrintWriter(sw));
                System.out.println("Error Occurred: " + sw.toString());
            })
            .onComplete(() -> {
                System.out.println("=== All records streamed successfully ===");
            })
            .subscriber(event -> {
                List<MedicalResult> results = ((MedicalTranscriptEvent) event).transcript().results();
                if (results.size() > 0) {
                    if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
                        System.out.println(results.get(0).alternatives().get(0).transcript());
                    }
                }
            })
            .build();
    }

    private static class AudioStreamPublisher implements Publisher<AudioStream> {
        private final InputStream inputStream;
        private static Subscription currentSubscription;

        private AudioStreamPublisher(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void subscribe(Subscriber<? super AudioStream> s) {

            if (this.currentSubscription == null) {
                this.currentSubscription = new SubscriptionImpl(s, inputStream);
            } else {
                this.currentSubscription.cancel();
                this.currentSubscription = new SubscriptionImpl(s, inputStream);
            }
            s.onSubscribe(currentSubscription);
        }
    }

    public static class SubscriptionImpl implements Subscription {
        private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;
        private final Subscriber<? super AudioStream> subscriber;
        private final InputStream inputStream;
        private ExecutorService executor = Executors.newFixedThreadPool(1);
        private AtomicLong demand = new AtomicLong(0);

        SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
            this.subscriber = s;
            this.inputStream = inputStream;
        }

        @Override
        public void request(long n) {
            if (n <= 0) {
                subscriber.onError(new IllegalArgumentException("Demand must be positive"));
            }

            demand.getAndAdd(n);
            executor.submit(() -> {
                try {
                    do {
                        ByteBuffer audioBuffer = getNextEvent();
                        if (audioBuffer.remaining() > 0) {
                            AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
                            subscriber.onNext(audioEvent);
                        } else {
                            subscriber.onComplete();
                            break;
                        }
                    } while (demand.decrementAndGet() > 0);
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            });
        }

        @Override
        public void cancel() {
            executor.shutdown();
        }

        private ByteBuffer getNextEvent() {
            ByteBuffer audioBuffer = null;
            byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];

            int len = 0;
            try {
                len = inputStream.read(audioBytes);

                if (len <= 0) {
                    audioBuffer = ByteBuffer.allocate(0);
                } else {
                    audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }

            return audioBuffer;
        }

        private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
            return AudioEvent.builder()
                .audioChunk(SdkBytes.fromByteBuffer(bb))
                .build();
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Java 2.x API リファレンス*」の「[StartMedicalStreamTranscription](https://docs.aws.amazon.com/goto/SdkForJavaV2/transcribe-streaming-2017-10-26/StartMedicalStreamTranscription)」を参照してください。

### `StartStreamTranscription`
<a name="transcribe-streaming_StartStreamTranscription_java_2_topic"></a>

次のコード例は、`StartStreamTranscription` を使用する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。

```
public class TranscribeStreamingDemoApp {
    private static final Region REGION = Region.US_EAST_1;
    private static TranscribeStreamingAsyncClient client;

    public static void main(String[] args)
            throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException {

        client = TranscribeStreamingAsyncClient.builder()
                .credentialsProvider(getCredentials())
                .region(REGION)
                .build();

        CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
                new AudioStreamPublisher(getStreamFromMic()),
                getResponseHandler());

        result.get();
        client.close();
    }

    private static InputStream getStreamFromMic() throws LineUnavailableException {

        // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
        int sampleRate = 16000;
        AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line not supported");
            System.exit(0);
        }

        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();

        InputStream audioStream = new AudioInputStream(line);
        return audioStream;
    }

    private static AwsCredentialsProvider getCredentials() {
        return DefaultCredentialsProvider.create();
    }

    private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
        return StartStreamTranscriptionRequest.builder()
                .languageCode(LanguageCode.EN_US.toString())
                .mediaEncoding(MediaEncoding.PCM)
                .mediaSampleRateHertz(mediaSampleRateHertz)
                .build();
    }

    private static StartStreamTranscriptionResponseHandler getResponseHandler() {
        return StartStreamTranscriptionResponseHandler.builder()
                .onResponse(r -> {
                    System.out.println("Received Initial response");
                })
                .onError(e -> {
                    System.out.println(e.getMessage());
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    System.out.println("Error Occurred: " + sw);
                })
                .onComplete(() -> {
                    System.out.println("=== All records stream successfully ===");
                })
                .subscriber(event -> {
                    List<Result> results = ((TranscriptEvent) event).transcript().results();
                    if (results.size() > 0) {
                        if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
                            System.out.println(results.get(0).alternatives().get(0).transcript());
                        }
                    }
                })
                .build();
    }

    
    private static class AudioStreamPublisher implements Publisher<AudioStream> {
        private static Subscription currentSubscription;
        private final InputStream inputStream;

        private AudioStreamPublisher(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void subscribe(Subscriber<? super AudioStream> s) {

            if (currentSubscription == null) {
                currentSubscription = new SubscriptionImpl(s, inputStream);
            } else {
                currentSubscription.cancel();
                currentSubscription = new SubscriptionImpl(s, inputStream);
            }
            s.onSubscribe(currentSubscription);
        }
    }

    public static class SubscriptionImpl implements Subscription {
        private static final int CHUNK_SIZE_IN_BYTES = 1024;
        private final Subscriber<? super AudioStream> subscriber;
        private final InputStream inputStream;
        private final ExecutorService executor = Executors.newFixedThreadPool(1);
        private final AtomicLong demand = new AtomicLong(0);

        SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
            this.subscriber = s;
            this.inputStream = inputStream;
        }

        @Override
        public void request(long n) {
            if (n <= 0) {
                subscriber.onError(new IllegalArgumentException("Demand must be positive"));
            }

            demand.getAndAdd(n);

            executor.submit(() -> {
                try {
                    do {
                        ByteBuffer audioBuffer = getNextEvent();
                        if (audioBuffer.remaining() > 0) {
                            AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
                            subscriber.onNext(audioEvent);
                        } else {
                            subscriber.onComplete();
                            break;
                        }
                    } while (demand.decrementAndGet() > 0);
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            });
        }

        @Override
        public void cancel() {
            executor.shutdown();
        }

        private ByteBuffer getNextEvent() {
            ByteBuffer audioBuffer = null;
            byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];

            int len = 0;
            try {
                len = inputStream.read(audioBytes);

                if (len <= 0) {
                    audioBuffer = ByteBuffer.allocate(0);
                } else {
                    audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }

            return audioBuffer;
        }

        private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
            return AudioEvent.builder()
                    .audioChunk(SdkBytes.fromByteBuffer(bb))
                    .build();
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の「[StartStreamTranscription](https://docs.aws.amazon.com/goto/SdkForJavaV2/transcribe-streaming-2017-10-26/StartStreamTranscription)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 音声ファイルの文字起こし
<a name="transcribe-streaming_Scenario_StreamEvents_File_java_2_topic"></a>

次のコード例は、Amazon Transcribe ストリーミングを使用してソース音声ファイルの文字起こしを生成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。

```
/**
 * To run this AWS code example, ensure that you have set up your development
 * environment, including your AWS credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class TranscribeStreamingDemoFile {
    private static final Region REGION = Region.US_EAST_1;
    private static TranscribeStreamingAsyncClient client;

    public static void main(String args[]) throws ExecutionException, InterruptedException {

        final String USAGE = "\n" +
                "Usage:\n" +
                "    <file> \n\n" +
                "Where:\n" +
                "    file - the location of a PCM file to transcribe. In this example, ensure the PCM file is 16 hertz (Hz). \n";

        if (args.length != 1) {
            System.out.println(USAGE);
            System.exit(1);
        }

        String file = args[0];
        client = TranscribeStreamingAsyncClient.builder()
                .region(REGION)
                .build();

        CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
                new AudioStreamPublisher(getStreamFromFile(file)),
                getResponseHandler());

        result.get();
        client.close();
    }

    private static InputStream getStreamFromFile(String file) {
        try {
            File inputFile = new File(file);
            InputStream audioStream = new FileInputStream(inputFile);
            return audioStream;

        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
        return StartStreamTranscriptionRequest.builder()
                .languageCode(LanguageCode.EN_US)
                .mediaEncoding(MediaEncoding.PCM)
                .mediaSampleRateHertz(mediaSampleRateHertz)
                .build();
    }

    private static StartStreamTranscriptionResponseHandler getResponseHandler() {
        return StartStreamTranscriptionResponseHandler.builder()
                .onResponse(r -> {
                    System.out.println("Received Initial response");
                })
                .onError(e -> {
                    System.out.println(e.getMessage());
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    System.out.println("Error Occurred: " + sw.toString());
                })
                .onComplete(() -> {
                    System.out.println("=== All records stream successfully ===");
                })
                .subscriber(event -> {
                    List<Result> results = ((TranscriptEvent) event).transcript().results();
                    if (results.size() > 0) {
                        if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
                            System.out.println(results.get(0).alternatives().get(0).transcript());
                        }
                    }
                })
                .build();
    }

    private static class AudioStreamPublisher implements Publisher<AudioStream> {
        private final InputStream inputStream;
        private static Subscription currentSubscription;

        private AudioStreamPublisher(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void subscribe(Subscriber<? super AudioStream> s) {

            if (this.currentSubscription == null) {
                this.currentSubscription = new SubscriptionImpl(s, inputStream);
            } else {
                this.currentSubscription.cancel();
                this.currentSubscription = new SubscriptionImpl(s, inputStream);
            }
            s.onSubscribe(currentSubscription);
        }
    }

    public static class SubscriptionImpl implements Subscription {
        private static final int CHUNK_SIZE_IN_BYTES = 1024 * 1;
        private final Subscriber<? super AudioStream> subscriber;
        private final InputStream inputStream;
        private ExecutorService executor = Executors.newFixedThreadPool(1);
        private AtomicLong demand = new AtomicLong(0);

        SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
            this.subscriber = s;
            this.inputStream = inputStream;
        }

        @Override
        public void request(long n) {
            if (n <= 0) {
                subscriber.onError(new IllegalArgumentException("Demand must be positive"));
            }

            demand.getAndAdd(n);

            executor.submit(() -> {
                try {
                    do {
                        ByteBuffer audioBuffer = getNextEvent();
                        if (audioBuffer.remaining() > 0) {
                            AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
                            subscriber.onNext(audioEvent);
                        } else {
                            subscriber.onComplete();
                            break;
                        }
                    } while (demand.decrementAndGet() > 0);
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            });
        }

        @Override
        public void cancel() {
            executor.shutdown();
        }

        private ByteBuffer getNextEvent() {
            ByteBuffer audioBuffer = null;
            byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];

            int len = 0;
            try {
                len = inputStream.read(audioBytes);

                if (len <= 0) {
                    audioBuffer = ByteBuffer.allocate(0);
                } else {
                    audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }

            return audioBuffer;
        }

        private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
            return AudioEvent.builder()
                    .audioChunk(SdkBytes.fromByteBuffer(bb))
                    .build();
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の「[StartStreamTranscription](https://docs.aws.amazon.com/goto/SdkForJavaV2/transcribe-streaming-2017-10-26/StartStreamTranscription)」を参照してください。

### マイク音声の文字起こし
<a name="transcribe-streaming_Scenario_StreamEvents_Microphone_java_2_topic"></a>

次のコード例は、Amazon Transcribe ストリーミングを使用してマイクから文字起こしを生成する方法を示しています。

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。

```
public class TranscribeStreamingDemoApp {
    private static final Region REGION = Region.US_EAST_1;
    private static TranscribeStreamingAsyncClient client;

    public static void main(String[] args)
            throws URISyntaxException, ExecutionException, InterruptedException, LineUnavailableException {

        client = TranscribeStreamingAsyncClient.builder()
                .credentialsProvider(getCredentials())
                .region(REGION)
                .build();

        CompletableFuture<Void> result = client.startStreamTranscription(getRequest(16_000),
                new AudioStreamPublisher(getStreamFromMic()),
                getResponseHandler());

        result.get();
        client.close();
    }

    private static InputStream getStreamFromMic() throws LineUnavailableException {

        // Signed PCM AudioFormat with 16kHz, 16 bit sample size, mono
        int sampleRate = 16000;
        AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
        DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);

        if (!AudioSystem.isLineSupported(info)) {
            System.out.println("Line not supported");
            System.exit(0);
        }

        TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info);
        line.open(format);
        line.start();

        InputStream audioStream = new AudioInputStream(line);
        return audioStream;
    }

    private static AwsCredentialsProvider getCredentials() {
        return DefaultCredentialsProvider.create();
    }

    private static StartStreamTranscriptionRequest getRequest(Integer mediaSampleRateHertz) {
        return StartStreamTranscriptionRequest.builder()
                .languageCode(LanguageCode.EN_US.toString())
                .mediaEncoding(MediaEncoding.PCM)
                .mediaSampleRateHertz(mediaSampleRateHertz)
                .build();
    }

    private static StartStreamTranscriptionResponseHandler getResponseHandler() {
        return StartStreamTranscriptionResponseHandler.builder()
                .onResponse(r -> {
                    System.out.println("Received Initial response");
                })
                .onError(e -> {
                    System.out.println(e.getMessage());
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    System.out.println("Error Occurred: " + sw);
                })
                .onComplete(() -> {
                    System.out.println("=== All records stream successfully ===");
                })
                .subscriber(event -> {
                    List<Result> results = ((TranscriptEvent) event).transcript().results();
                    if (results.size() > 0) {
                        if (!results.get(0).alternatives().get(0).transcript().isEmpty()) {
                            System.out.println(results.get(0).alternatives().get(0).transcript());
                        }
                    }
                })
                .build();
    }

    
    private static class AudioStreamPublisher implements Publisher<AudioStream> {
        private static Subscription currentSubscription;
        private final InputStream inputStream;

        private AudioStreamPublisher(InputStream inputStream) {
            this.inputStream = inputStream;
        }

        @Override
        public void subscribe(Subscriber<? super AudioStream> s) {

            if (currentSubscription == null) {
                currentSubscription = new SubscriptionImpl(s, inputStream);
            } else {
                currentSubscription.cancel();
                currentSubscription = new SubscriptionImpl(s, inputStream);
            }
            s.onSubscribe(currentSubscription);
        }
    }

    public static class SubscriptionImpl implements Subscription {
        private static final int CHUNK_SIZE_IN_BYTES = 1024;
        private final Subscriber<? super AudioStream> subscriber;
        private final InputStream inputStream;
        private final ExecutorService executor = Executors.newFixedThreadPool(1);
        private final AtomicLong demand = new AtomicLong(0);

        SubscriptionImpl(Subscriber<? super AudioStream> s, InputStream inputStream) {
            this.subscriber = s;
            this.inputStream = inputStream;
        }

        @Override
        public void request(long n) {
            if (n <= 0) {
                subscriber.onError(new IllegalArgumentException("Demand must be positive"));
            }

            demand.getAndAdd(n);

            executor.submit(() -> {
                try {
                    do {
                        ByteBuffer audioBuffer = getNextEvent();
                        if (audioBuffer.remaining() > 0) {
                            AudioEvent audioEvent = audioEventFromBuffer(audioBuffer);
                            subscriber.onNext(audioEvent);
                        } else {
                            subscriber.onComplete();
                            break;
                        }
                    } while (demand.decrementAndGet() > 0);
                } catch (Exception e) {
                    subscriber.onError(e);
                }
            });
        }

        @Override
        public void cancel() {
            executor.shutdown();
        }

        private ByteBuffer getNextEvent() {
            ByteBuffer audioBuffer = null;
            byte[] audioBytes = new byte[CHUNK_SIZE_IN_BYTES];

            int len = 0;
            try {
                len = inputStream.read(audioBytes);

                if (len <= 0) {
                    audioBuffer = ByteBuffer.allocate(0);
                } else {
                    audioBuffer = ByteBuffer.wrap(audioBytes, 0, len);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }

            return audioBuffer;
        }

        private AudioEvent audioEventFromBuffer(ByteBuffer bb) {
            return AudioEvent.builder()
                    .audioChunk(SdkBytes.fromByteBuffer(bb))
                    .build();
        }
    }
}
```
+  API の詳細については、「AWS SDK for Java 2.x API リファレンス**」の「[StartStreamTranscription](https://docs.aws.amazon.com/goto/SdkForJavaV2/transcribe-streaming-2017-10-26/StartStreamTranscription)」を参照してください。

# SDK for Java 2.x を使用した Amazon Translate の例
<a name="java_2_translate_code_examples"></a>

次のコード例は、Amazon Translate AWS SDK for Java 2.x で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Lex チャットボットを構築する
<a name="cross_LexChatbotLanguages_java_2_topic"></a>

次のコード例は、ウェブサイトの訪問者を引き付けるチャットボットの作成方法を示しています。

**SDK for Java 2.x**  
 Amazon Lex API を使用して、ウェブアプリケーション内にチャットボットを作成し、Web サイトの訪問者と交流する方法を説明します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_lex_chatbot) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon Lex
+ Amazon Translate

### Amazon SNS アプリケーションの構築
<a name="cross_SnsPublishSubscription_java_2_topic"></a>

次のコード例は、サブスクリプションとパブリッシュ機能を持ち、メッセージを翻訳するアプリケーションを作成する方法を示しています。

**SDK for Java 2.x**  
 Amazon Simple Notification Service Java API を使用して、サブスクリプションおよびパブリッシュ機能を持つウェブアプリケーションを作成する方法を説明します。さらに、このサンプルアプリケーションではメッセージを翻訳します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_sns_sample_app) で完全な例を参照してください。  
 Java Async API を使用するサンプルの完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_sns_async) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon SNS
+ Amazon Translate

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_java_2_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Java 2.x**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/usecases/creating_fsa_app) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Kotlin のコード例
<a name="kotlin_1_code_examples"></a>

次のコード例は、 で AWS SDK for Kotlin を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for Kotlin デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/home.html) ** – で Kotlin を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23kotlin)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [API ゲートウェイ](kotlin_1_api-gateway_code_examples.md)
+ [Aurora](kotlin_1_aurora_code_examples.md)
+ [Auto Scaling](kotlin_1_auto-scaling_code_examples.md)
+ [Amazon Bedrock](kotlin_1_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](kotlin_1_bedrock-runtime_code_examples.md)
+ [CloudWatch](kotlin_1_cloudwatch_code_examples.md)
+ [CloudWatch Logs](kotlin_1_cloudwatch-logs_code_examples.md)
+ [Amazon Cognito ID プロバイダー](kotlin_1_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](kotlin_1_comprehend_code_examples.md)
+ [DynamoDB](kotlin_1_dynamodb_code_examples.md)
+ [Amazon EC2](kotlin_1_ec2_code_examples.md)
+ [Amazon ECR](kotlin_1_ecr_code_examples.md)
+ [OpenSearch Service](kotlin_1_opensearch_code_examples.md)
+ [EventBridge](kotlin_1_eventbridge_code_examples.md)
+ [AWS Glue](kotlin_1_glue_code_examples.md)
+ [IAM](kotlin_1_iam_code_examples.md)
+ [AWS IoT](kotlin_1_iot_code_examples.md)
+ [AWS IoT data](kotlin_1_iot-data-plane_code_examples.md)
+ [AWS IoT FleetWise](kotlin_1_iotfleetwise_code_examples.md)
+ [Amazon Keyspaces](kotlin_1_keyspaces_code_examples.md)
+ [AWS KMS](kotlin_1_kms_code_examples.md)
+ [Lambda](kotlin_1_lambda_code_examples.md)
+ [Amazon Location](kotlin_1_location_code_examples.md)
+ [MediaConvert](kotlin_1_mediaconvert_code_examples.md)
+ [Amazon Pinpoint](kotlin_1_pinpoint_code_examples.md)
+ [Amazon RDS](kotlin_1_rds_code_examples.md)
+ [Amazon RDS データサービス](kotlin_1_rds-data_code_examples.md)
+ [Amazon Redshift](kotlin_1_redshift_code_examples.md)
+ [Amazon Rekognition](kotlin_1_rekognition_code_examples.md)
+ [Route 53 ドメイン登録](kotlin_1_route-53-domains_code_examples.md)
+ [Amazon S3](kotlin_1_s3_code_examples.md)
+ [SageMaker AI](kotlin_1_sagemaker_code_examples.md)
+ [Secrets Manager](kotlin_1_secrets-manager_code_examples.md)
+ [Amazon SES](kotlin_1_ses_code_examples.md)
+ [Amazon SNS](kotlin_1_sns_code_examples.md)
+ [Amazon SQS](kotlin_1_sqs_code_examples.md)
+ [ステップ関数](kotlin_1_sfn_code_examples.md)
+ [サポート](kotlin_1_support_code_examples.md)
+ [Amazon Translate](kotlin_1_translate_code_examples.md)

# SDK for Kotlin を使用した API Gateway の例
<a name="kotlin_1_api-gateway_code_examples"></a>

次のコード例は、API Gateway で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_kotlin_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Kotlin**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_pam) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

# SDK for Kotlin を使用した Aurora の例
<a name="kotlin_1_aurora_code_examples"></a>

次のコード例は、Aurora で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="aurora_Scenario_GetStartedClusters_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム Aurora DB クラスターパラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用する DB クラスターを作成する
+ データベースを含む DB インスタンスを作成します。
+ DB クラスターのスナップショットを作成して、リソースをクリーンアップします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a
secret, this example will not work. For more details, see:

https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html

This Kotlin example performs the following tasks:

1. Returns a list of the available DB engines.
2. Creates a custom DB parameter group.
3. Gets the parameter groups.
4. Gets the parameters in the group.
5. Modifies the auto_increment_increment parameter.
6. Displays the updated parameter value.
7. Gets a list of allowed engine versions.
8. Creates an Aurora DB cluster database.
9. Waits for DB instance to be ready.
10. Gets a list of instance classes available for the selected engine.
11. Creates a database instance in the cluster.
12. Waits for the database instance in the cluster to be ready.
13. Creates a snapshot.
14. Waits for DB snapshot to be ready.
15. Deletes the DB instance.
16. Deletes the DB cluster.
17. Deletes the DB cluster group.
 */

var slTime: Long = 20

suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <dbClusterGroupName> <dbParameterGroupFamily> <dbInstanceClusterIdentifier> <dbName> <dbSnapshotIdentifier> <secretName>
        Where:
            dbClusterGroupName - The database group name. 
            dbParameterGroupFamily - The database parameter group name.
            dbInstanceClusterIdentifier - The database instance identifier. 
            dbName -  The database name. 
            dbSnapshotIdentifier - The snapshot identifier.
            secretName - The name of the AWS Secrets Manager secret that contains the database credentials.
    """

    if (args.size != 7) {
        println(usage)
        exitProcess(1)
    }

    val dbClusterGroupName = args[0]
    val dbParameterGroupFamily = args[1]
    val dbInstanceClusterIdentifier = args[2]
    val dbInstanceIdentifier = args[3]
    val dbName = args[4]
    val dbSnapshotIdentifier = args[5]
    val secretName = args[6]

    val gson = Gson()
    val user = gson.fromJson(getSecretValues(secretName).toString(), User::class.java)
    val username = user.username
    val userPassword = user.password

    println("1. Return a list of the available DB engines")
    describeAuroraDBEngines()

    println("2. Create a custom parameter group")
    createDBClusterParameterGroup(dbClusterGroupName, dbParameterGroupFamily)

    println("3. Get the parameter group")
    describeDbClusterParameterGroups(dbClusterGroupName)

    println("4. Get the parameters in the group")
    describeDbClusterParameters(dbClusterGroupName, 0)

    println("5. Modify the auto_increment_offset parameter")
    modifyDBClusterParas(dbClusterGroupName)

    println("6. Display the updated parameter value")
    describeDbClusterParameters(dbClusterGroupName, -1)

    println("7. Get a list of allowed engine versions")
    getAllowedClusterEngines(dbParameterGroupFamily)

    println("8. Create an Aurora DB cluster database")
    val arnClusterVal = createDBCluster(dbClusterGroupName, dbName, dbInstanceClusterIdentifier, username, userPassword)
    println("The ARN of the cluster is $arnClusterVal")

    println("9. Wait for DB instance to be ready")
    waitForClusterInstanceReady(dbInstanceClusterIdentifier)

    println("10. Get a list of instance classes available for the selected engine")
    val instanceClass = getListInstanceClasses()

    println("11. Create a database instance in the cluster.")
    val clusterDBARN = createDBInstanceCluster(dbInstanceIdentifier, dbInstanceClusterIdentifier, instanceClass)
    println("The ARN of the database is $clusterDBARN")

    println("12. Wait for DB instance to be ready")
    waitDBAuroraInstanceReady(dbInstanceIdentifier)

    println("13. Create a snapshot")
    createDBClusterSnapshot(dbInstanceClusterIdentifier, dbSnapshotIdentifier)

    println("14. Wait for DB snapshot to be ready")
    waitSnapshotReady(dbSnapshotIdentifier, dbInstanceClusterIdentifier)

    println("15. Delete the DB instance")
    deleteDBInstance(dbInstanceIdentifier)

    println("16. Delete the DB cluster")
    deleteCluster(dbInstanceClusterIdentifier)

    println("17. Delete the DB cluster group")
    if (clusterDBARN != null) {
        deleteDBClusterGroup(dbClusterGroupName, clusterDBARN)
    }
    println("The Scenario has successfully completed.")
}

@Throws(InterruptedException::class)
suspend fun deleteDBClusterGroup(
    dbClusterGroupName: String,
    clusterDBARN: String,
) {
    var isDataDel = false
    var didFind: Boolean
    var instanceARN: String

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        // Make sure that the database has been deleted.
        while (!isDataDel) {
            val response = rdsClient.describeDbInstances()
            val instanceList = response.dbInstances
            val listSize = instanceList?.size
            isDataDel = false
            didFind = false
            var index = 1
            if (instanceList != null) {
                for (instance in instanceList) {
                    instanceARN = instance.dbInstanceArn.toString()
                    if (instanceARN.compareTo(clusterDBARN) == 0) {
                        println("$clusterDBARN still exists")
                        didFind = true
                    }
                    if (index == listSize && !didFind) {
                        // Went through the entire list and did not find the database ARN.
                        isDataDel = true
                    }
                    delay(slTime * 1000)
                    index++
                }
            }
        }
        val clusterParameterGroupRequest =
            DeleteDbClusterParameterGroupRequest {
                dbClusterParameterGroupName = dbClusterGroupName
            }

        rdsClient.deleteDbClusterParameterGroup(clusterParameterGroupRequest)
        println("$dbClusterGroupName was deleted.")
    }
}

suspend fun deleteCluster(dbInstanceClusterIdentifier: String) {
    val deleteDbClusterRequest =
        DeleteDbClusterRequest {
            dbClusterIdentifier = dbInstanceClusterIdentifier
            skipFinalSnapshot = true
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        rdsClient.deleteDbCluster(deleteDbClusterRequest)
        println("$dbInstanceClusterIdentifier was deleted!")
    }
}

suspend fun deleteDBInstance(dbInstanceIdentifierVal: String) {
    val deleteDbInstanceRequest =
        DeleteDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            deleteAutomatedBackups = true
            skipFinalSnapshot = true
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.deleteDbInstance(deleteDbInstanceRequest)
        print("The status of the database is ${response.dbInstance?.dbInstanceStatus}")
    }
}

suspend fun waitSnapshotReady(
    dbSnapshotIdentifier: String?,
    dbInstanceClusterIdentifier: String?,
) {
    var snapshotReady = false
    var snapshotReadyStr: String
    println("Waiting for the snapshot to become available.")

    val snapshotsRequest =
        DescribeDbClusterSnapshotsRequest {
            dbClusterSnapshotIdentifier = dbSnapshotIdentifier
            dbClusterIdentifier = dbInstanceClusterIdentifier
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        while (!snapshotReady) {
            val response = rdsClient.describeDbClusterSnapshots(snapshotsRequest)
            val snapshotList = response.dbClusterSnapshots
            if (snapshotList != null) {
                for (snapshot in snapshotList) {
                    snapshotReadyStr = snapshot.status.toString()
                    if (snapshotReadyStr.contains("available")) {
                        snapshotReady = true
                    } else {
                        println(".")
                        delay(slTime * 5000)
                    }
                }
            }
        }
    }
    println("The Snapshot is available!")
}

suspend fun createDBClusterSnapshot(
    dbInstanceClusterIdentifier: String?,
    dbSnapshotIdentifier: String?,
) {
    val snapshotRequest =
        CreateDbClusterSnapshotRequest {
            dbClusterIdentifier = dbInstanceClusterIdentifier
            dbClusterSnapshotIdentifier = dbSnapshotIdentifier
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbClusterSnapshot(snapshotRequest)
        println("The Snapshot ARN is ${response.dbClusterSnapshot?.dbClusterSnapshotArn}")
    }
}

suspend fun waitDBAuroraInstanceReady(dbInstanceIdentifierVal: String?) {
    var instanceReady = false
    var instanceReadyStr: String
    println("Waiting for instance to become available.")
    val instanceRequest =
        DescribeDbInstancesRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
        }

    var endpoint = ""
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        while (!instanceReady) {
            val response = rdsClient.describeDbInstances(instanceRequest)
            response.dbInstances?.forEach { instance ->
                instanceReadyStr = instance.dbInstanceStatus.toString()
                if (instanceReadyStr.contains("available")) {
                    endpoint = instance.endpoint?.address.toString()
                    instanceReady = true
                } else {
                    print(".")
                    delay(sleepTime * 1000)
                }
            }
        }
    }
    println("Database instance is available! The connection endpoint is $endpoint")
}

suspend fun createDBInstanceCluster(
    dbInstanceIdentifierVal: String?,
    dbInstanceClusterIdentifierVal: String?,
    instanceClassVal: String?,
): String? {
    val instanceRequest =
        CreateDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            dbClusterIdentifier = dbInstanceClusterIdentifierVal
            engine = "aurora-mysql"
            dbInstanceClass = instanceClassVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbInstance(instanceRequest)
        print("The status is ${response.dbInstance?.dbInstanceStatus}")
        return response.dbInstance?.dbInstanceArn
    }
}

suspend fun getListInstanceClasses(): String {
    val optionsRequest =
        DescribeOrderableDbInstanceOptionsRequest {
            engine = "aurora-mysql"
            maxRecords = 20
        }
    var instanceClass = ""
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeOrderableDbInstanceOptions(optionsRequest)
        response.orderableDbInstanceOptions?.forEach { instanceOption ->
            instanceClass = instanceOption.dbInstanceClass.toString()
            println("The instance class is ${instanceOption.dbInstanceClass}")
            println("The engine version is ${instanceOption.engineVersion}")
        }
    }
    return instanceClass
}

// Waits until the database instance is available.
suspend fun waitForClusterInstanceReady(dbClusterIdentifierVal: String?) {
    var instanceReady = false
    var instanceReadyStr: String
    println("Waiting for instance to become available.")

    val instanceRequest =
        DescribeDbClustersRequest {
            dbClusterIdentifier = dbClusterIdentifierVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        while (!instanceReady) {
            val response = rdsClient.describeDbClusters(instanceRequest)
            response.dbClusters?.forEach { cluster ->
                instanceReadyStr = cluster.status.toString()
                if (instanceReadyStr.contains("available")) {
                    instanceReady = true
                } else {
                    print(".")
                    delay(sleepTime * 1000)
                }
            }
        }
    }
    println("Database cluster is available!")
}

suspend fun createDBCluster(
    dbParameterGroupFamilyVal: String?,
    dbName: String?,
    dbClusterIdentifierVal: String?,
    userName: String?,
    password: String?,
): String? {
    val clusterRequest =
        CreateDbClusterRequest {
            databaseName = dbName
            dbClusterIdentifier = dbClusterIdentifierVal
            dbClusterParameterGroupName = dbParameterGroupFamilyVal
            engine = "aurora-mysql"
            masterUsername = userName
            masterUserPassword = password
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbCluster(clusterRequest)
        return response.dbCluster?.dbClusterArn
    }
}

// Get a list of allowed engine versions.
suspend fun getAllowedClusterEngines(dbParameterGroupFamilyVal: String?) {
    val versionsRequest =
        DescribeDbEngineVersionsRequest {
            dbParameterGroupFamily = dbParameterGroupFamilyVal
            engine = "aurora-mysql"
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbEngineVersions(versionsRequest)
        response.dbEngineVersions?.forEach { dbEngine ->
            println("The engine version is ${dbEngine.engineVersion}")
            println("The engine description is ${dbEngine.dbEngineDescription}")
        }
    }
}

// Modify the auto_increment_offset parameter.
suspend fun modifyDBClusterParas(dClusterGroupName: String?) {
    val parameter1 =
        Parameter {
            parameterName = "auto_increment_offset"
            applyMethod = ApplyMethod.fromValue("immediate")
            parameterValue = "5"
        }

    val paraList = ArrayList<Parameter>()
    paraList.add(parameter1)
    val groupRequest =
        ModifyDbClusterParameterGroupRequest {
            dbClusterParameterGroupName = dClusterGroupName
            parameters = paraList
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.modifyDbClusterParameterGroup(groupRequest)
        println("The parameter group ${response.dbClusterParameterGroupName} was successfully modified")
    }
}

suspend fun describeDbClusterParameters(
    dbCLusterGroupName: String?,
    flag: Int,
) {
    val dbParameterGroupsRequest: DescribeDbClusterParametersRequest
    dbParameterGroupsRequest =
        if (flag == 0) {
            DescribeDbClusterParametersRequest {
                dbClusterParameterGroupName = dbCLusterGroupName
            }
        } else {
            DescribeDbClusterParametersRequest {
                dbClusterParameterGroupName = dbCLusterGroupName
                source = "user"
            }
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbClusterParameters(dbParameterGroupsRequest)
        response.parameters?.forEach { para ->
            // Only print out information about either auto_increment_offset or auto_increment_increment.
            val paraName = para.parameterName
            if (paraName != null) {
                if (paraName.compareTo("auto_increment_offset") == 0 || paraName.compareTo("auto_increment_increment ") == 0) {
                    println("*** The parameter name is  $paraName")
                    println("*** The parameter value is  ${para.parameterValue}")
                    println("*** The parameter data type is ${para.dataType}")
                    println("*** The parameter description is ${para.description}")
                    println("*** The parameter allowed values  is ${para.allowedValues}")
                }
            }
        }
    }
}

suspend fun describeDbClusterParameterGroups(dbClusterGroupName: String?) {
    val groupsRequest =
        DescribeDbClusterParameterGroupsRequest {
            dbClusterParameterGroupName = dbClusterGroupName
            maxRecords = 20
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbClusterParameterGroups(groupsRequest)
        response.dbClusterParameterGroups?.forEach { group ->
            println("The group name is ${group.dbClusterParameterGroupName}")
            println("The group ARN is ${group.dbClusterParameterGroupArn}")
        }
    }
}

suspend fun createDBClusterParameterGroup(
    dbClusterGroupNameVal: String?,
    dbParameterGroupFamilyVal: String?,
) {
    val groupRequest =
        CreateDbClusterParameterGroupRequest {
            dbClusterParameterGroupName = dbClusterGroupNameVal
            dbParameterGroupFamily = dbParameterGroupFamilyVal
            description = "Created by using the AWS SDK for Kotlin"
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbClusterParameterGroup(groupRequest)
        println("The group name is ${response.dbClusterParameterGroup?.dbClusterParameterGroupName}")
    }
}

suspend fun describeAuroraDBEngines() {
    val engineVersionsRequest =
        DescribeDbEngineVersionsRequest {
            engine = "aurora-mysql"
            defaultOnly = true
            maxRecords = 20
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbEngineVersions(engineVersionsRequest)
        response.dbEngineVersions?.forEach { engineOb ->
            println("The name of the DB parameter group family for the database engine is ${engineOb.dbParameterGroupFamily}")
            println("The name of the database engine ${engineOb.engine}")
            println("The version number of the database engine ${engineOb.engineVersion}")
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBCluster](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateDBClusterParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateDBClusterSnapshot](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteDBCluster](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteDBClusterParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBClusterParameterGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBClusterParameters](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBClusterSnapshots](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBClusters](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBEngineVersions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeOrderableDBInstanceOptions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ModifyDBClusterParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="aurora_CreateDBCluster_kotlin_1_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createDBCluster(
    dbParameterGroupFamilyVal: String?,
    dbName: String?,
    dbClusterIdentifierVal: String?,
    userName: String?,
    password: String?,
): String? {
    val clusterRequest =
        CreateDbClusterRequest {
            databaseName = dbName
            dbClusterIdentifier = dbClusterIdentifierVal
            dbClusterParameterGroupName = dbParameterGroupFamilyVal
            engine = "aurora-mysql"
            masterUsername = userName
            masterUserPassword = password
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbCluster(clusterRequest)
        return response.dbCluster?.dbClusterArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateDBCluster](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_kotlin_1_topic"></a>

次のコード例は、`CreateDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createDBClusterParameterGroup(
    dbClusterGroupNameVal: String?,
    dbParameterGroupFamilyVal: String?,
) {
    val groupRequest =
        CreateDbClusterParameterGroupRequest {
            dbClusterParameterGroupName = dbClusterGroupNameVal
            dbParameterGroupFamily = dbParameterGroupFamilyVal
            description = "Created by using the AWS SDK for Kotlin"
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbClusterParameterGroup(groupRequest)
        println("The group name is ${response.dbClusterParameterGroup?.dbClusterParameterGroupName}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateDBClusterParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateDBClusterSnapshot`
<a name="aurora_CreateDBClusterSnapshot_kotlin_1_topic"></a>

次のコード例は、`CreateDBClusterSnapshot` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createDBClusterSnapshot(
    dbInstanceClusterIdentifier: String?,
    dbSnapshotIdentifier: String?,
) {
    val snapshotRequest =
        CreateDbClusterSnapshotRequest {
            dbClusterIdentifier = dbInstanceClusterIdentifier
            dbClusterSnapshotIdentifier = dbSnapshotIdentifier
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbClusterSnapshot(snapshotRequest)
        println("The Snapshot ARN is ${response.dbClusterSnapshot?.dbClusterSnapshotArn}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateDBClusterSnapshot](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateDBInstance`
<a name="aurora_CreateDBInstance_kotlin_1_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createDBInstanceCluster(
    dbInstanceIdentifierVal: String?,
    dbInstanceClusterIdentifierVal: String?,
    instanceClassVal: String?,
): String? {
    val instanceRequest =
        CreateDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            dbClusterIdentifier = dbInstanceClusterIdentifierVal
            engine = "aurora-mysql"
            dbInstanceClass = instanceClassVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbInstance(instanceRequest)
        print("The status is ${response.dbInstance?.dbInstanceStatus}")
        return response.dbInstance?.dbInstanceArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteDBCluster`
<a name="aurora_DeleteDBCluster_kotlin_1_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteCluster(dbInstanceClusterIdentifier: String) {
    val deleteDbClusterRequest =
        DeleteDbClusterRequest {
            dbClusterIdentifier = dbInstanceClusterIdentifier
            skipFinalSnapshot = true
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        rdsClient.deleteDbCluster(deleteDbClusterRequest)
        println("$dbInstanceClusterIdentifier was deleted!")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteDBCluster](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_kotlin_1_topic"></a>

次のコード例は、`DeleteDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
@Throws(InterruptedException::class)
suspend fun deleteDBClusterGroup(
    dbClusterGroupName: String,
    clusterDBARN: String,
) {
    var isDataDel = false
    var didFind: Boolean
    var instanceARN: String

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        // Make sure that the database has been deleted.
        while (!isDataDel) {
            val response = rdsClient.describeDbInstances()
            val instanceList = response.dbInstances
            val listSize = instanceList?.size
            isDataDel = false
            didFind = false
            var index = 1
            if (instanceList != null) {
                for (instance in instanceList) {
                    instanceARN = instance.dbInstanceArn.toString()
                    if (instanceARN.compareTo(clusterDBARN) == 0) {
                        println("$clusterDBARN still exists")
                        didFind = true
                    }
                    if (index == listSize && !didFind) {
                        // Went through the entire list and did not find the database ARN.
                        isDataDel = true
                    }
                    delay(slTime * 1000)
                    index++
                }
            }
        }
        val clusterParameterGroupRequest =
            DeleteDbClusterParameterGroupRequest {
                dbClusterParameterGroupName = dbClusterGroupName
            }

        rdsClient.deleteDbClusterParameterGroup(clusterParameterGroupRequest)
        println("$dbClusterGroupName was deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteDBClusterParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteDBInstance`
<a name="aurora_DeleteDBInstance_kotlin_1_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteDBInstance(dbInstanceIdentifierVal: String) {
    val deleteDbInstanceRequest =
        DeleteDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            deleteAutomatedBackups = true
            skipFinalSnapshot = true
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.deleteDbInstance(deleteDbInstanceRequest)
        print("The status of the database is ${response.dbInstance?.dbInstanceStatus}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeDBClusterParameterGroups`
<a name="aurora_DescribeDBClusterParameterGroups_kotlin_1_topic"></a>

次のコード例は、`DescribeDBClusterParameterGroups` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeDbClusterParameterGroups(dbClusterGroupName: String?) {
    val groupsRequest =
        DescribeDbClusterParameterGroupsRequest {
            dbClusterParameterGroupName = dbClusterGroupName
            maxRecords = 20
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbClusterParameterGroups(groupsRequest)
        response.dbClusterParameterGroups?.forEach { group ->
            println("The group name is ${group.dbClusterParameterGroupName}")
            println("The group ARN is ${group.dbClusterParameterGroupArn}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeDBClusterParameterGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_kotlin_1_topic"></a>

次のコード例は、`DescribeDBClusterParameters` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeDbClusterParameters(
    dbCLusterGroupName: String?,
    flag: Int,
) {
    val dbParameterGroupsRequest: DescribeDbClusterParametersRequest
    dbParameterGroupsRequest =
        if (flag == 0) {
            DescribeDbClusterParametersRequest {
                dbClusterParameterGroupName = dbCLusterGroupName
            }
        } else {
            DescribeDbClusterParametersRequest {
                dbClusterParameterGroupName = dbCLusterGroupName
                source = "user"
            }
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbClusterParameters(dbParameterGroupsRequest)
        response.parameters?.forEach { para ->
            // Only print out information about either auto_increment_offset or auto_increment_increment.
            val paraName = para.parameterName
            if (paraName != null) {
                if (paraName.compareTo("auto_increment_offset") == 0 || paraName.compareTo("auto_increment_increment ") == 0) {
                    println("*** The parameter name is  $paraName")
                    println("*** The parameter value is  ${para.parameterValue}")
                    println("*** The parameter data type is ${para.dataType}")
                    println("*** The parameter description is ${para.description}")
                    println("*** The parameter allowed values  is ${para.allowedValues}")
                }
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeDBClusterParameters](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeDBClusterSnapshots`
<a name="aurora_DescribeDBClusterSnapshots_kotlin_1_topic"></a>

次のコード例は、`DescribeDBClusterSnapshots` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun waitSnapshotReady(
    dbSnapshotIdentifier: String?,
    dbInstanceClusterIdentifier: String?,
) {
    var snapshotReady = false
    var snapshotReadyStr: String
    println("Waiting for the snapshot to become available.")

    val snapshotsRequest =
        DescribeDbClusterSnapshotsRequest {
            dbClusterSnapshotIdentifier = dbSnapshotIdentifier
            dbClusterIdentifier = dbInstanceClusterIdentifier
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        while (!snapshotReady) {
            val response = rdsClient.describeDbClusterSnapshots(snapshotsRequest)
            val snapshotList = response.dbClusterSnapshots
            if (snapshotList != null) {
                for (snapshot in snapshotList) {
                    snapshotReadyStr = snapshot.status.toString()
                    if (snapshotReadyStr.contains("available")) {
                        snapshotReady = true
                    } else {
                        println(".")
                        delay(slTime * 5000)
                    }
                }
            }
        }
    }
    println("The Snapshot is available!")
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeDBClusterSnapshots](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeDBClusters`
<a name="aurora_DescribeDBClusters_kotlin_1_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeDbClusterParameters(
    dbCLusterGroupName: String?,
    flag: Int,
) {
    val dbParameterGroupsRequest: DescribeDbClusterParametersRequest
    dbParameterGroupsRequest =
        if (flag == 0) {
            DescribeDbClusterParametersRequest {
                dbClusterParameterGroupName = dbCLusterGroupName
            }
        } else {
            DescribeDbClusterParametersRequest {
                dbClusterParameterGroupName = dbCLusterGroupName
                source = "user"
            }
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbClusterParameters(dbParameterGroupsRequest)
        response.parameters?.forEach { para ->
            // Only print out information about either auto_increment_offset or auto_increment_increment.
            val paraName = para.parameterName
            if (paraName != null) {
                if (paraName.compareTo("auto_increment_offset") == 0 || paraName.compareTo("auto_increment_increment ") == 0) {
                    println("*** The parameter name is  $paraName")
                    println("*** The parameter value is  ${para.parameterValue}")
                    println("*** The parameter data type is ${para.dataType}")
                    println("*** The parameter description is ${para.description}")
                    println("*** The parameter allowed values  is ${para.allowedValues}")
                }
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeDBClusters](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_kotlin_1_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
// Get a list of allowed engine versions.
suspend fun getAllowedClusterEngines(dbParameterGroupFamilyVal: String?) {
    val versionsRequest =
        DescribeDbEngineVersionsRequest {
            dbParameterGroupFamily = dbParameterGroupFamilyVal
            engine = "aurora-mysql"
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbEngineVersions(versionsRequest)
        response.dbEngineVersions?.forEach { dbEngine ->
            println("The engine version is ${dbEngine.engineVersion}")
            println("The engine description is ${dbEngine.dbEngineDescription}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeDBEngineVersions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeDBInstances`
<a name="aurora_DescribeDBInstances_kotlin_1_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun waitDBAuroraInstanceReady(dbInstanceIdentifierVal: String?) {
    var instanceReady = false
    var instanceReadyStr: String
    println("Waiting for instance to become available.")
    val instanceRequest =
        DescribeDbInstancesRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
        }

    var endpoint = ""
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        while (!instanceReady) {
            val response = rdsClient.describeDbInstances(instanceRequest)
            response.dbInstances?.forEach { instance ->
                instanceReadyStr = instance.dbInstanceStatus.toString()
                if (instanceReadyStr.contains("available")) {
                    endpoint = instance.endpoint?.address.toString()
                    instanceReady = true
                } else {
                    print(".")
                    delay(sleepTime * 1000)
                }
            }
        }
    }
    println("Database instance is available! The connection endpoint is $endpoint")
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeDBInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_kotlin_1_topic"></a>

次のコード例は、`ModifyDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
// Modify the auto_increment_offset parameter.
suspend fun modifyDBClusterParas(dClusterGroupName: String?) {
    val parameter1 =
        Parameter {
            parameterName = "auto_increment_offset"
            applyMethod = ApplyMethod.fromValue("immediate")
            parameterValue = "5"
        }

    val paraList = ArrayList<Parameter>()
    paraList.add(parameter1)
    val groupRequest =
        ModifyDbClusterParameterGroupRequest {
            dbClusterParameterGroupName = dClusterGroupName
            parameters = paraList
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.modifyDbClusterParameterGroup(groupRequest)
        println("The parameter group ${response.dbClusterParameterGroupName} was successfully modified")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ModifyDBClusterParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/serverless_rds) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for Kotlin を使用した Auto Scaling の例
<a name="kotlin_1_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="auto-scaling_Scenario_GroupsAndInstances_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 起動テンプレートとアベイラビリティーゾーンを使用して、Amazon EC2 Auto Scaling グループを作成し、実行中のインスタンスに関する情報を取得します。
+ Amazon CloudWatch メトリクスの収集を有効にします。
+ グループの希望するキャパシティを更新し、インスタンスが起動するのを待ちます。
+  グループ内の最も古いインスタンスを削除します。
+ ユーザーのリクエストやキャパシティの変更に応じて発生するスケーリングアクティビティを一覧表示します。
+ CloudWatch メトリクスの統計を取得して、リソースをクリーンアップします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <groupName> <launchTemplateName> <serviceLinkedRoleARN> <vpcZoneId>

    Where:
        groupName - The name of the Auto Scaling group.
        launchTemplateName - The name of the launch template. 
        serviceLinkedRoleARN - The Amazon Resource Name (ARN) of the service-linked role that the Auto Scaling group uses.
        vpcZoneId - A subnet Id for a virtual private cloud (VPC) where instances in the Auto Scaling group can be created.
    """

    if (args.size != 4) {
        println(usage)
        exitProcess(1)
    }

    val groupName = args[0]
    val launchTemplateName = args[1]
    val serviceLinkedRoleARN = args[2]
    val vpcZoneId = args[3]

    println("**** Create an Auto Scaling group named $groupName")
    createAutoScalingGroup(groupName, launchTemplateName, serviceLinkedRoleARN, vpcZoneId)

    println("Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned")
    delay(60000)

    val instanceId = getSpecificAutoScaling(groupName)
    if (instanceId.compareTo("") == 0) {
        println("Error - no instance Id value")
        exitProcess(1)
    } else {
        println("The instance Id value is $instanceId")
    }

    println("**** Describe Auto Scaling with the Id value $instanceId")
    describeAutoScalingInstance(instanceId)

    println("**** Enable metrics collection $instanceId")
    enableMetricsCollection(groupName)

    println("**** Update an Auto Scaling group to maximum size of 3")
    updateAutoScalingGroup(groupName, launchTemplateName, serviceLinkedRoleARN)

    println("**** Describe all Auto Scaling groups to show the current state of the groups")
    describeAutoScalingGroups(groupName)

    println("**** Describe account details")
    describeAccountLimits()

    println("Wait 1 min for the resources, including the instance. Otherwise, an empty instance Id is returned")
    delay(60000)

    println("**** Set desired capacity to 2")
    setDesiredCapacity(groupName)

    println("**** Get the two instance Id values and state")
    getAutoScalingGroups(groupName)

    println("**** List the scaling activities that have occurred for the group")
    describeScalingActivities(groupName)

    println("**** Terminate an instance in the Auto Scaling group")
    terminateInstanceInAutoScalingGroup(instanceId)

    println("**** Stop the metrics collection")
    disableMetricsCollection(groupName)

    println("**** Delete the Auto Scaling group")
    deleteSpecificAutoScalingGroup(groupName)
}

suspend fun describeAutoScalingGroups(groupName: String) {
    val groupsReques =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
            maxRecords = 10
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingGroups(groupsReques)
        response.autoScalingGroups?.forEach { group ->
            println("The service to use for the health checks: ${group.healthCheckType}")
        }
    }
}

suspend fun disableMetricsCollection(groupName: String) {
    val disableMetricsCollectionRequest =
        DisableMetricsCollectionRequest {
            autoScalingGroupName = groupName
            metrics = listOf("GroupMaxSize")
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest)
        println("The disable metrics collection operation was successful")
    }
}

suspend fun describeScalingActivities(groupName: String?) {
    val scalingActivitiesRequest =
        DescribeScalingActivitiesRequest {
            autoScalingGroupName = groupName
            maxRecords = 10
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeScalingActivities(scalingActivitiesRequest)
        response.activities?.forEach { activity ->
            println("The activity Id is ${activity.activityId}")
            println("The activity details are ${activity.details}")
        }
    }
}

suspend fun getAutoScalingGroups(groupName: String) {
    val scalingGroupsRequest =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest)
        response.autoScalingGroups?.forEach { group ->
            println("The group name is ${group.autoScalingGroupName}")
            println("The group ARN is ${group.autoScalingGroupArn}")
            group.instances?.forEach { instance ->
                println("The instance id is ${instance.instanceId}")
                println("The lifecycle state is " + instance.lifecycleState)
            }
        }
    }
}

suspend fun setDesiredCapacity(groupName: String) {
    val capacityRequest =
        SetDesiredCapacityRequest {
            autoScalingGroupName = groupName
            desiredCapacity = 2
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.setDesiredCapacity(capacityRequest)
        println("You set the DesiredCapacity to 2")
    }
}

suspend fun updateAutoScalingGroup(
    groupName: String,
    launchTemplateNameVal: String,
    serviceLinkedRoleARNVal: String,
) {
    val templateSpecification =
        LaunchTemplateSpecification {
            launchTemplateName = launchTemplateNameVal
        }

    val groupRequest =
        UpdateAutoScalingGroupRequest {
            maxSize = 3
            serviceLinkedRoleArn = serviceLinkedRoleARNVal
            autoScalingGroupName = groupName
            launchTemplate = templateSpecification
        }

    val groupsRequestWaiter =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.updateAutoScalingGroup(groupRequest)
        autoScalingClient.waitUntilGroupExists(groupsRequestWaiter)
        println("You successfully updated the Auto Scaling group  $groupName")
    }
}

suspend fun createAutoScalingGroup(
    groupName: String,
    launchTemplateNameVal: String,
    serviceLinkedRoleARNVal: String,
    vpcZoneIdVal: String,
) {
    val templateSpecification =
        LaunchTemplateSpecification {
            launchTemplateName = launchTemplateNameVal
        }

    val request =
        CreateAutoScalingGroupRequest {
            autoScalingGroupName = groupName
            availabilityZones = listOf("us-east-1a")
            launchTemplate = templateSpecification
            maxSize = 1
            minSize = 1
            vpcZoneIdentifier = vpcZoneIdVal
            serviceLinkedRoleArn = serviceLinkedRoleARNVal
        }

    // This object is required for the waiter call.
    val groupsRequestWaiter =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.createAutoScalingGroup(request)
        autoScalingClient.waitUntilGroupExists(groupsRequestWaiter)
        println("$groupName was created!")
    }
}

suspend fun describeAutoScalingInstance(id: String) {
    val describeAutoScalingInstancesRequest =
        DescribeAutoScalingInstancesRequest {
            instanceIds = listOf(id)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingInstances(describeAutoScalingInstancesRequest)
        response.autoScalingInstances?.forEach { group ->
            println("The instance lifecycle state is: ${group.lifecycleState}")
        }
    }
}

suspend fun enableMetricsCollection(groupName: String?) {
    val collectionRequest =
        EnableMetricsCollectionRequest {
            autoScalingGroupName = groupName
            metrics = listOf("GroupMaxSize")
            granularity = "1Minute"
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.enableMetricsCollection(collectionRequest)
        println("The enable metrics collection operation was successful")
    }
}

suspend fun getSpecificAutoScaling(groupName: String): String {
    var instanceId = ""
    val scalingGroupsRequest =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest)
        response.autoScalingGroups?.forEach { group ->
            println("The group name is ${group.autoScalingGroupName}")
            println("The group ARN is ${group.autoScalingGroupArn}")

            group.instances?.forEach { instance ->
                instanceId = instance.instanceId.toString()
            }
        }
    }
    return instanceId
}

suspend fun describeAccountLimits() {
    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAccountLimits(DescribeAccountLimitsRequest {})
        println("The max number of Auto Scaling groups is ${response.maxNumberOfAutoScalingGroups}")
        println("The current number of Auto Scaling groups is ${response.numberOfAutoScalingGroups}")
    }
}

suspend fun terminateInstanceInAutoScalingGroup(instanceIdVal: String) {
    val request =
        TerminateInstanceInAutoScalingGroupRequest {
            instanceId = instanceIdVal
            shouldDecrementDesiredCapacity = false
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.terminateInstanceInAutoScalingGroup(request)
        println("You have terminated instance $instanceIdVal")
    }
}

suspend fun deleteSpecificAutoScalingGroup(groupName: String) {
    val deleteAutoScalingGroupRequest =
        DeleteAutoScalingGroupRequest {
            autoScalingGroupName = groupName
            forceDelete = true
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest)
        println("You successfully deleted $groupName")
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CreateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeAutoScalingGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeAutoScalingInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeScalingActivities](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DisableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [EnableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [SetDesiredCapacity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [TerminateInstanceInAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_kotlin_1_topic"></a>

次のコード例は、`CreateAutoScalingGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createAutoScalingGroup(
    groupName: String,
    launchTemplateNameVal: String,
    serviceLinkedRoleARNVal: String,
    vpcZoneIdVal: String,
) {
    val templateSpecification =
        LaunchTemplateSpecification {
            launchTemplateName = launchTemplateNameVal
        }

    val request =
        CreateAutoScalingGroupRequest {
            autoScalingGroupName = groupName
            availabilityZones = listOf("us-east-1a")
            launchTemplate = templateSpecification
            maxSize = 1
            minSize = 1
            vpcZoneIdentifier = vpcZoneIdVal
            serviceLinkedRoleArn = serviceLinkedRoleARNVal
        }

    // This object is required for the waiter call.
    val groupsRequestWaiter =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.createAutoScalingGroup(request)
        autoScalingClient.waitUntilGroupExists(groupsRequestWaiter)
        println("$groupName was created!")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[CreateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_kotlin_1_topic"></a>

次のコード例は、`DeleteAutoScalingGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteSpecificAutoScalingGroup(groupName: String) {
    val deleteAutoScalingGroupRequest =
        DeleteAutoScalingGroupRequest {
            autoScalingGroupName = groupName
            forceDelete = true
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.deleteAutoScalingGroup(deleteAutoScalingGroupRequest)
        println("You successfully deleted $groupName")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeleteAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_kotlin_1_topic"></a>

次のコード例は、`DescribeAutoScalingGroups` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getAutoScalingGroups(groupName: String) {
    val scalingGroupsRequest =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingGroups(scalingGroupsRequest)
        response.autoScalingGroups?.forEach { group ->
            println("The group name is ${group.autoScalingGroupName}")
            println("The group ARN is ${group.autoScalingGroupArn}")
            group.instances?.forEach { instance ->
                println("The instance id is ${instance.instanceId}")
                println("The lifecycle state is " + instance.lifecycleState)
            }
        }
    }
}
```
+  API の詳細については、AWS SDK for Kotlin API リファレンスの「[DescribeAutoScalingGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_kotlin_1_topic"></a>

次のコード例は、`DescribeAutoScalingInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeAutoScalingInstance(id: String) {
    val describeAutoScalingInstancesRequest =
        DescribeAutoScalingInstancesRequest {
            instanceIds = listOf(id)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingInstances(describeAutoScalingInstancesRequest)
        response.autoScalingInstances?.forEach { group ->
            println("The instance lifecycle state is: ${group.lifecycleState}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeAutoScalingInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_kotlin_1_topic"></a>

次のコード例は、`DescribeScalingActivities` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeAutoScalingGroups(groupName: String) {
    val groupsReques =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
            maxRecords = 10
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        val response = autoScalingClient.describeAutoScalingGroups(groupsReques)
        response.autoScalingGroups?.forEach { group ->
            println("The service to use for the health checks: ${group.healthCheckType}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeScalingActivities](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_kotlin_1_topic"></a>

次のコード例は、`DisableMetricsCollection` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun disableMetricsCollection(groupName: String) {
    val disableMetricsCollectionRequest =
        DisableMetricsCollectionRequest {
            autoScalingGroupName = groupName
            metrics = listOf("GroupMaxSize")
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.disableMetricsCollection(disableMetricsCollectionRequest)
        println("The disable metrics collection operation was successful")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DisableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_kotlin_1_topic"></a>

次のコード例は、`EnableMetricsCollection` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun enableMetricsCollection(groupName: String?) {
    val collectionRequest =
        EnableMetricsCollectionRequest {
            autoScalingGroupName = groupName
            metrics = listOf("GroupMaxSize")
            granularity = "1Minute"
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.enableMetricsCollection(collectionRequest)
        println("The enable metrics collection operation was successful")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[EnableMetricsCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_kotlin_1_topic"></a>

次のコード例は、`SetDesiredCapacity` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun setDesiredCapacity(groupName: String) {
    val capacityRequest =
        SetDesiredCapacityRequest {
            autoScalingGroupName = groupName
            desiredCapacity = 2
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.setDesiredCapacity(capacityRequest)
        println("You set the DesiredCapacity to 2")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[SetDesiredCapacity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_kotlin_1_topic"></a>

次のコード例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun terminateInstanceInAutoScalingGroup(instanceIdVal: String) {
    val request =
        TerminateInstanceInAutoScalingGroupRequest {
            instanceId = instanceIdVal
            shouldDecrementDesiredCapacity = false
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.terminateInstanceInAutoScalingGroup(request)
        println("You have terminated instance $instanceIdVal")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」**の「[TerminateInstanceInAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_kotlin_1_topic"></a>

次のコード例は、`UpdateAutoScalingGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/autoscale#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateAutoScalingGroup(
    groupName: String,
    launchTemplateNameVal: String,
    serviceLinkedRoleARNVal: String,
) {
    val templateSpecification =
        LaunchTemplateSpecification {
            launchTemplateName = launchTemplateNameVal
        }

    val groupRequest =
        UpdateAutoScalingGroupRequest {
            maxSize = 3
            serviceLinkedRoleArn = serviceLinkedRoleARNVal
            autoScalingGroupName = groupName
            launchTemplate = templateSpecification
        }

    val groupsRequestWaiter =
        DescribeAutoScalingGroupsRequest {
            autoScalingGroupNames = listOf(groupName)
        }

    AutoScalingClient { region = "us-east-1" }.use { autoScalingClient ->
        autoScalingClient.updateAutoScalingGroup(groupRequest)
        autoScalingClient.waitUntilGroupExists(groupsRequestWaiter)
        println("You successfully updated the Auto Scaling group  $groupName")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[UpdateAutoScalingGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon Bedrock の例
<a name="kotlin_1_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_kotlin_1_topic"></a>

次のコード例は、`ListFoundationModels` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/bedrock#code-examples)での設定と実行の方法を確認してください。
利用可能な Amazon Bedrock 基盤モデルを一覧表示します。  

```
suspend fun listFoundationModels(): List<FoundationModelSummary>? {
    BedrockClient.fromEnvironment { region = "us-east-1" }.use { bedrockClient ->
        val response = bedrockClient.listFoundationModels(ListFoundationModelsRequest {})
        response.modelSummaries?.forEach { model ->
            println("==========================================")
            println(" Model ID: ${model.modelId}")
            println("------------------------------------------")
            println(" Name: ${model.modelName}")
            println(" Provider: ${model.providerName}")
            println(" Input modalities: ${model.inputModalities}")
            println(" Output modalities: ${model.outputModalities}")
            println(" Supported customizations: ${model.customizationsSupported}")
            println(" Supported inference types: ${model.inferenceTypesSupported}")
            println("------------------------------------------\n")
        }
        return response.modelSummaries
    }
}
```
+  API の詳細については、「**AWS SDK for Kotlin API リファレンス」の「[ListFoundationModels](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon Bedrock ランタイムの例
<a name="kotlin_1_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイムで AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [Amazon Nova](#amazon_nova)

## Amazon Nova
<a name="amazon_nova"></a>

### Converse
<a name="bedrock-runtime_Converse_AmazonNovaText_kotlin_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
import aws.sdk.kotlin.services.bedrockruntime.BedrockRuntimeClient
import aws.sdk.kotlin.services.bedrockruntime.model.ContentBlock
import aws.sdk.kotlin.services.bedrockruntime.model.ConversationRole
import aws.sdk.kotlin.services.bedrockruntime.model.ConverseRequest
import aws.sdk.kotlin.services.bedrockruntime.model.Message

/**
 * This example demonstrates how to use the Amazon Nova foundation models to generate text.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Create a message
 * - Configure and send a request
 * - Process the response
 */
suspend fun main() {
    converse().also { println(it) }
}

suspend fun converse(): String {
    // Create and configure the Bedrock runtime client
    BedrockRuntimeClient { region = "us-east-1" }.use { client ->

        // Specify the model ID. For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        val modelId = "amazon.nova-lite-v1:0"

        // Create the message with the user's prompt
        val prompt = "Describe the purpose of a 'hello world' program in one line."
        val message = Message {
            role = ConversationRole.User
            content = listOf(ContentBlock.Text(prompt))
        }

        // Configure the request with optional model parameters
        val request = ConverseRequest {
            this.modelId = modelId
            messages = listOf(message)
            inferenceConfig {
                maxTokens = 500 // Maximum response length
                temperature = 0.5F // Lower values: more focused output
                // topP = 0.8F // Alternative to temperature
            }
        }

        // Send the request and process the model's response
        runCatching {
            val response = client.converse(request)
            return response.output!!.asMessage().content.first().asText()
        }.getOrElse { error ->
            error.message?.let { e -> System.err.println("ERROR: Can't invoke '$modelId'. Reason: $e") }
            throw RuntimeException("Failed to generate text with model $modelId", error)
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin の API リファレンス*」の「[Converse](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AmazonNovaText_kotlin_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
import aws.sdk.kotlin.services.bedrockruntime.BedrockRuntimeClient
import aws.sdk.kotlin.services.bedrockruntime.model.ContentBlock
import aws.sdk.kotlin.services.bedrockruntime.model.ConversationRole
import aws.sdk.kotlin.services.bedrockruntime.model.ConverseStreamOutput
import aws.sdk.kotlin.services.bedrockruntime.model.ConverseStreamRequest
import aws.sdk.kotlin.services.bedrockruntime.model.Message

/**
 * This example demonstrates how to use the Amazon Nova foundation models
 * to generate streaming text responses.
 * It shows how to:
 * - Set up the Amazon Bedrock runtime client
 * - Create a message with a prompt
 * - Configure a streaming request with parameters
 * - Process the response stream in real time
 */
suspend fun main() {
    converseStream()
}

suspend fun converseStream(): String {
    // A buffer to collect the complete response
    val completeResponseBuffer = StringBuilder()

    // Create and configure the Bedrock runtime client
    BedrockRuntimeClient { region = "us-east-1" }.use { client ->

        // Specify the model ID. For the latest available models, see:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html
        val modelId = "amazon.nova-lite-v1:0"

        // Create the message with the user's prompt
        val prompt = "Describe the purpose of a 'hello world' program in a paragraph."
        val message = Message {
            role = ConversationRole.User
            content = listOf(ContentBlock.Text(prompt))
        }

        // Configure the request with optional model parameters
        val request = ConverseStreamRequest {
            this.modelId = modelId
            messages = listOf(message)
            inferenceConfig {
                maxTokens = 500 // Maximum response length
                temperature = 0.5F // Lower values: more focused output
                // topP = 0.8F // Alternative to temperature
            }
        }

        // Process the streaming response
        runCatching {
            client.converseStream(request) { response ->
                response.stream?.collect { chunk ->
                    when (chunk) {
                        is ConverseStreamOutput.ContentBlockDelta -> {
                            // Process each text chunk as it arrives
                            chunk.value.delta?.asText()?.let { text ->
                                print(text)
                                System.out.flush() // Ensure immediate output
                                completeResponseBuffer.append(text)
                            }
                        }
                        else -> {} // Other output block types can be handled as needed
                    }
                }
            }
        }.onFailure { error ->
            error.message?.let { e -> System.err.println("ERROR: Can't invoke '$modelId'. Reason: $e") }
            throw RuntimeException("Failed to generate text with model $modelId: $error", error)
        }
    }

    return completeResponseBuffer.toString()
}
```
+  API の詳細については、「*AWS SDK for Kotlin の API リファレンス*」の「[ConverseStream](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した CloudWatch の例
<a name="kotlin_1_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello CloudWatch
<a name="cloudwatch_Hello_kotlin_1_topic"></a>

次のコード例は、CloudWatch の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */
suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
           <namespace> 
        Where:
           namespace - The namespace to filter against (for example, AWS/EC2). 
    """

    if (args.size != 1) {
        println(usage)
        exitProcess(0)
    }

    val namespace = args[0]
    listAllMets(namespace)
}

suspend fun listAllMets(namespaceVal: String?) {
    val request =
        ListMetricsRequest {
            namespace = namespaceVal
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient
            .listMetricsPaginated(request)
            .transform { it.metrics?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println("Name is ${obj.metricName}")
                println("Namespace is ${obj.namespace}")
            }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[ListMetrics](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="cloudwatch_GetStartedMetricsDashboardsAlarms_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ CloudWatch の名前空間とメトリクスを一覧表示します。
+ メトリクスと予想請求額の統計の取得
+ ダッシュボードの作成と更新
+ メトリクスの作成とデータの追加
+ アラームの作成/トリガーとアラーム履歴の表示
+ 異常ディテクターの追加
+ メトリクス画像を取得し、リソースをクリーンアップします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。
CloudWatch の機能を実証するインタラクティブなシナリオを実行します。  

```
/**
 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

 To enable billing metrics and statistics for this example, make sure billing alerts are enabled for your account:
 https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html#turning_on_billing_metrics

 This Kotlin code example performs the following tasks:

 1. List available namespaces from Amazon CloudWatch. Select a namespace from the list.
 2. List available metrics within the selected namespace.
 3. Get statistics for the selected metric over the last day.
 4. Get CloudWatch estimated billing for the last week.
 5. Create a new CloudWatch dashboard with metrics.
 6. List dashboards using a paginator.
 7. Create a new custom metric by adding data for it.
 8. Add the custom metric to the dashboard.
 9. Create an alarm for the custom metric.
 10. Describe current alarms.
 11. Get current data for the new custom metric.
 12. Push data into the custom metric to trigger the alarm.
 13. Check the alarm state using the action DescribeAlarmsForMetric.
 14. Get alarm history for the new alarm.
 15. Add an anomaly detector for the custom metric.
 16. Describe current anomaly detectors.
 17. Get a metric image for the custom metric.
 18. Clean up the Amazon CloudWatch resources.
 */

val DASHES: String? = String(CharArray(80)).replace("\u0000", "-")

suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <myDate> <costDateWeek> <dashboardName> <dashboardJson> <dashboardAdd> <settings> <metricImage>  

        Where:
            myDate - The start date to use to get metric statistics. (For example, 2023-01-11T18:35:24.00Z.) 
            costDateWeek - The start date to use to get AWS Billing and Cost Management statistics. (For example, 2023-01-11T18:35:24.00Z.) 
            dashboardName - The name of the dashboard to create. 
            dashboardJson - The location of a JSON file to use to create a dashboard. (See Readme file.) 
            dashboardAdd - The location of a JSON file to use to update a dashboard. (See Readme file.) 
            settings - The location of a JSON file from which various values are read. (See Readme file.) 
            metricImage - The location of a BMP file that is used to create a graph. 
    """

    if (args.size != 7) {
        println(usage)
        System.exit(1)
    }

    val myDate = args[0]
    val costDateWeek = args[1]
    val dashboardName = args[2]
    val dashboardJson = args[3]
    val dashboardAdd = args[4]
    val settings = args[5]
    var metricImage = args[6]
    val dataPoint = "10.0".toDouble()
    val inOb = Scanner(System.`in`)

    println(DASHES)
    println("Welcome to the Amazon CloudWatch example scenario.")
    println(DASHES)

    println(DASHES)
    println("1. List at least five available unique namespaces from Amazon CloudWatch. Select a CloudWatch namespace from the list.")
    val list: ArrayList<String> = listNameSpaces()
    for (z in 0..4) {
        println("    ${z + 1}. ${list[z]}")
    }

    var selectedNamespace: String
    var selectedMetrics = ""
    var num = inOb.nextLine().toInt()
    println("You selected $num")

    if (1 <= num && num <= 5) {
        selectedNamespace = list[num - 1]
    } else {
        println("You did not select a valid option.")
        exitProcess(1)
    }
    println("You selected $selectedNamespace")
    println(DASHES)

    println(DASHES)
    println("2. List available metrics within the selected namespace and select one from the list.")
    val metList = listMets(selectedNamespace)
    for (z in 0..4) {
        println("    ${ z + 1}. ${metList?.get(z)}")
    }
    num = inOb.nextLine().toInt()
    if (1 <= num && num <= 5) {
        selectedMetrics = metList!![num - 1]
    } else {
        println("You did not select a valid option.")
        System.exit(1)
    }
    println("You selected $selectedMetrics")
    val myDimension = getSpecificMet(selectedNamespace)
    if (myDimension == null) {
        println("Error - Dimension is null")
        exitProcess(1)
    }
    println(DASHES)

    println(DASHES)
    println("3. Get statistics for the selected metric over the last day.")
    val metricOption: String
    val statTypes = ArrayList<String>()
    statTypes.add("SampleCount")
    statTypes.add("Average")
    statTypes.add("Sum")
    statTypes.add("Minimum")
    statTypes.add("Maximum")

    for (t in 0..4) {
        println("    ${t + 1}. ${statTypes[t]}")
    }
    println("Select a metric statistic by entering a number from the preceding list:")
    num = inOb.nextLine().toInt()
    if (1 <= num && num <= 5) {
        metricOption = statTypes[num - 1]
    } else {
        println("You did not select a valid option.")
        exitProcess(1)
    }
    println("You selected $metricOption")
    getAndDisplayMetricStatistics(selectedNamespace, selectedMetrics, metricOption, myDate, myDimension)
    println(DASHES)

    println(DASHES)
    println("4. Get CloudWatch estimated billing for the last week.")
    getMetricStatistics(costDateWeek)
    println(DASHES)

    println(DASHES)
    println("5. Create a new CloudWatch dashboard with metrics.")
    createDashboardWithMetrics(dashboardName, dashboardJson)
    println(DASHES)

    println(DASHES)
    println("6. List dashboards using a paginator.")
    listDashboards()
    println(DASHES)

    println(DASHES)
    println("7. Create a new custom metric by adding data to it.")
    createNewCustomMetric(dataPoint)
    println(DASHES)

    println(DASHES)
    println("8. Add an additional metric to the dashboard.")
    addMetricToDashboard(dashboardAdd, dashboardName)
    println(DASHES)

    println(DASHES)
    println("9. Create an alarm for the custom metric.")
    val alarmName: String = createAlarm(settings)
    println(DASHES)

    println(DASHES)
    println("10. Describe 10 current alarms.")
    describeAlarms()
    println(DASHES)

    println(DASHES)
    println("11. Get current data for the new custom metric.")
    getCustomMetricData(settings)
    println(DASHES)

    println(DASHES)
    println("12. Push data into the custom metric to trigger the alarm.")
    addMetricDataForAlarm(settings)
    println(DASHES)

    println(DASHES)
    println("13. Check the alarm state using the action DescribeAlarmsForMetric.")
    checkForMetricAlarm(settings)
    println(DASHES)

    println(DASHES)
    println("14. Get alarm history for the new alarm.")
    getAlarmHistory(settings, myDate)
    println(DASHES)

    println(DASHES)
    println("15. Add an anomaly detector for the custom metric.")
    addAnomalyDetector(settings)
    println(DASHES)

    println(DASHES)
    println("16. Describe current anomaly detectors.")
    describeAnomalyDetectors(settings)
    println(DASHES)

    println(DASHES)
    println("17. Get a metric image for the custom metric.")
    getAndOpenMetricImage(metricImage)
    println(DASHES)

    println(DASHES)
    println("18. Clean up the Amazon CloudWatch resources.")
    deleteDashboard(dashboardName)
    deleteAlarm(alarmName)
    deleteAnomalyDetector(settings)
    println(DASHES)

    println(DASHES)
    println("The Amazon CloudWatch example scenario is complete.")
    println(DASHES)
}

suspend fun deleteAnomalyDetector(fileName: String) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    val singleMetricAnomalyDetectorVal =
        SingleMetricAnomalyDetector {
            metricName = customMetricName
            namespace = customMetricNamespace
            stat = "Maximum"
        }

    val request =
        DeleteAnomalyDetectorRequest {
            singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.deleteAnomalyDetector(request)
        println("Successfully deleted the Anomaly Detector.")
    }
}

suspend fun deleteAlarm(alarmNameVal: String) {
    val request =
        DeleteAlarmsRequest {
            alarmNames = listOf(alarmNameVal)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.deleteAlarms(request)
        println("Successfully deleted alarm $alarmNameVal")
    }
}

suspend fun deleteDashboard(dashboardName: String) {
    val dashboardsRequest =
        DeleteDashboardsRequest {
            dashboardNames = listOf(dashboardName)
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.deleteDashboards(dashboardsRequest)
        println("$dashboardName was successfully deleted.")
    }
}

suspend fun getAndOpenMetricImage(fileName: String) {
    println("Getting Image data for custom metric.")
    val myJSON = """{
        "title": "Example Metric Graph",
        "view": "timeSeries",
        "stacked ": false,
        "period": 10,
        "width": 1400,
        "height": 600,
        "metrics": [
            [
            "AWS/Billing",
            "EstimatedCharges",
            "Currency",
            "USD"
            ]
        ]
        }"""

    val imageRequest =
        GetMetricWidgetImageRequest {
            metricWidget = myJSON
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.getMetricWidgetImage(imageRequest)
        val bytes = response.metricWidgetImage
        if (bytes != null) {
            File(fileName).writeBytes(bytes)
        }
    }
    println("You have successfully written data to $fileName")
}

suspend fun describeAnomalyDetectors(fileName: String) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    val detectorsRequest =
        DescribeAnomalyDetectorsRequest {
            maxResults = 10
            metricName = customMetricName
            namespace = customMetricNamespace
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.describeAnomalyDetectors(detectorsRequest)
        response.anomalyDetectors?.forEach { detector ->
            println("Metric name: ${detector.singleMetricAnomalyDetector?.metricName}")
            println("State: ${detector.stateValue}")
        }
    }
}

suspend fun addAnomalyDetector(fileName: String?) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    val singleMetricAnomalyDetectorVal =
        SingleMetricAnomalyDetector {
            metricName = customMetricName
            namespace = customMetricNamespace
            stat = "Maximum"
        }

    val anomalyDetectorRequest =
        PutAnomalyDetectorRequest {
            singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putAnomalyDetector(anomalyDetectorRequest)
        println("Added anomaly detector for metric $customMetricName.")
    }
}

suspend fun getAlarmHistory(
    fileName: String,
    date: String,
) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val alarmNameVal = rootNode.findValue("exampleAlarmName").asText()
    val start = Instant.parse(date)
    val endDateVal = Instant.now()

    val historyRequest =
        DescribeAlarmHistoryRequest {
            startDate =
                aws.smithy.kotlin.runtime.time
                    .Instant(start)
            endDate =
                aws.smithy.kotlin.runtime.time
                    .Instant(endDateVal)
            alarmName = alarmNameVal
            historyItemType = HistoryItemType.Action
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.describeAlarmHistory(historyRequest)
        val historyItems = response.alarmHistoryItems
        if (historyItems != null) {
            if (historyItems.isEmpty()) {
                println("No alarm history data found for $alarmNameVal.")
            } else {
                for (item in historyItems) {
                    println("History summary ${item.historySummary}")
                    println("Time stamp: ${item.timestamp}")
                }
            }
        }
    }
}

suspend fun checkForMetricAlarm(fileName: String?) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()
    var hasAlarm = false
    var retries = 10

    val metricRequest =
        DescribeAlarmsForMetricRequest {
            metricName = customMetricName
            namespace = customMetricNamespace
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        while (!hasAlarm && retries > 0) {
            val response = cwClient.describeAlarmsForMetric(metricRequest)
            if (response.metricAlarms?.count()!! > 0) {
                hasAlarm = true
            }
            retries--
            delay(20000)
            println(".")
        }
        if (!hasAlarm) {
            println("No Alarm state found for $customMetricName after 10 retries.")
        } else {
            println("Alarm state found for $customMetricName.")
        }
    }
}

suspend fun addMetricDataForAlarm(fileName: String?) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    // Set an Instant object.
    val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)
    val instant = Instant.parse(time)
    val datum =
        MetricDatum {
            metricName = customMetricName
            unit = StandardUnit.None
            value = 1001.00
            timestamp =
                aws.smithy.kotlin.runtime.time
                    .Instant(instant)
        }

    val datum2 =
        MetricDatum {
            metricName = customMetricName
            unit = StandardUnit.None
            value = 1002.00
            timestamp =
                aws.smithy.kotlin.runtime.time
                    .Instant(instant)
        }

    val metricDataList = ArrayList<MetricDatum>()
    metricDataList.add(datum)
    metricDataList.add(datum2)

    val request =
        PutMetricDataRequest {
            namespace = customMetricNamespace
            metricData = metricDataList
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putMetricData(request)
        println("Added metric values for for metric $customMetricName")
    }
}

suspend fun getCustomMetricData(fileName: String) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    // Set the date.
    val nowDate = Instant.now()
    val hours: Long = 1
    val minutes: Long = 30
    val date2 =
        nowDate.plus(hours, ChronoUnit.HOURS).plus(
            minutes,
            ChronoUnit.MINUTES,
        )

    val met =
        Metric {
            metricName = customMetricName
            namespace = customMetricNamespace
        }

    val metStat =
        MetricStat {
            stat = "Maximum"
            period = 1
            metric = met
        }

    val dataQUery =
        MetricDataQuery {
            metricStat = metStat
            id = "foo2"
            returnData = true
        }

    val dq = ArrayList<MetricDataQuery>()
    dq.add(dataQUery)
    val getMetReq =
        GetMetricDataRequest {
            maxDatapoints = 10
            scanBy = ScanBy.TimestampDescending
            startTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(nowDate)
            endTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(date2)
            metricDataQueries = dq
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.getMetricData(getMetReq)
        response.metricDataResults?.forEach { item ->
            println("The label is ${item.label}")
            println("The status code is ${item.statusCode}")
        }
    }
}

suspend fun describeAlarms() {
    val typeList = ArrayList<AlarmType>()
    typeList.add(AlarmType.MetricAlarm)
    val alarmsRequest =
        DescribeAlarmsRequest {
            alarmTypes = typeList
            maxRecords = 10
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.describeAlarms(alarmsRequest)
        response.metricAlarms?.forEach { alarm ->
            println("Alarm name: ${alarm.alarmName}")
            println("Alarm description: ${alarm.alarmDescription}")
        }
    }
}

suspend fun createAlarm(fileName: String): String {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode: JsonNode = ObjectMapper().readTree(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()
    val alarmNameVal = rootNode.findValue("exampleAlarmName").asText()
    val emailTopic = rootNode.findValue("emailTopic").asText()
    val accountId = rootNode.findValue("accountId").asText()
    val region2 = rootNode.findValue("region").asText()

    // Create a List for alarm actions.
    val alarmActionObs: MutableList<String> = ArrayList()
    alarmActionObs.add("arn:aws:sns:$region2:$accountId:$emailTopic")
    val alarmRequest =
        PutMetricAlarmRequest {
            alarmActions = alarmActionObs
            alarmDescription = "Example metric alarm"
            alarmName = alarmNameVal
            comparisonOperator = ComparisonOperator.GreaterThanOrEqualToThreshold
            threshold = 100.00
            metricName = customMetricName
            namespace = customMetricNamespace
            evaluationPeriods = 1
            period = 10
            statistic = Statistic.Maximum
            datapointsToAlarm = 1
            treatMissingData = "ignore"
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putMetricAlarm(alarmRequest)
        println("$alarmNameVal was successfully created!")
        return alarmNameVal
    }
}

suspend fun addMetricToDashboard(
    fileNameVal: String,
    dashboardNameVal: String,
) {
    val dashboardRequest =
        PutDashboardRequest {
            dashboardName = dashboardNameVal
            dashboardBody = readFileAsString(fileNameVal)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putDashboard(dashboardRequest)
        println("$dashboardNameVal was successfully updated.")
    }
}

suspend fun createNewCustomMetric(dataPoint: Double) {
    val dimension =
        Dimension {
            name = "UNIQUE_PAGES"
            value = "URLS"
        }

    // Set an Instant object.
    val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)
    val instant = Instant.parse(time)
    val datum =
        MetricDatum {
            metricName = "PAGES_VISITED"
            unit = StandardUnit.None
            value = dataPoint
            timestamp =
                aws.smithy.kotlin.runtime.time
                    .Instant(instant)
            dimensions = listOf(dimension)
        }

    val request =
        PutMetricDataRequest {
            namespace = "SITE/TRAFFIC"
            metricData = listOf(datum)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putMetricData(request)
        println("Added metric values for for metric PAGES_VISITED")
    }
}

suspend fun listDashboards() {
    CloudWatchClient { region = "us-east-1" }.use { cwClient ->
        cwClient
            .listDashboardsPaginated({})
            .transform { it.dashboardEntries?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println("Name is ${obj.dashboardName}")
                println("Dashboard ARN is ${obj.dashboardArn}")
            }
    }
}

suspend fun createDashboardWithMetrics(
    dashboardNameVal: String,
    fileNameVal: String,
) {
    val dashboardRequest =
        PutDashboardRequest {
            dashboardName = dashboardNameVal
            dashboardBody = readFileAsString(fileNameVal)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.putDashboard(dashboardRequest)
        println("$dashboardNameVal was successfully created.")
        val messages = response.dashboardValidationMessages
        if (messages != null) {
            if (messages.isEmpty()) {
                println("There are no messages in the new Dashboard")
            } else {
                for (message in messages) {
                    println("Message is: ${message.message}")
                }
            }
        }
    }
}

fun readFileAsString(file: String): String = String(Files.readAllBytes(Paths.get(file)))

suspend fun getMetricStatistics(costDateWeek: String?) {
    val start = Instant.parse(costDateWeek)
    val endDate = Instant.now()
    val dimension =
        Dimension {
            name = "Currency"
            value = "USD"
        }

    val dimensionList: MutableList<Dimension> = ArrayList()
    dimensionList.add(dimension)

    val statisticsRequest =
        GetMetricStatisticsRequest {
            metricName = "EstimatedCharges"
            namespace = "AWS/Billing"
            dimensions = dimensionList
            statistics = listOf(Statistic.Maximum)
            startTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(start)
            endTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(endDate)
            period = 86400
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.getMetricStatistics(statisticsRequest)
        val data: List<Datapoint>? = response.datapoints
        if (data != null) {
            if (!data.isEmpty()) {
                for (datapoint in data) {
                    println("Timestamp:  ${datapoint.timestamp} Maximum value: ${datapoint.maximum}")
                }
            } else {
                println("The returned data list is empty")
            }
        }
    }
}

suspend fun getAndDisplayMetricStatistics(
    nameSpaceVal: String,
    metVal: String,
    metricOption: String,
    date: String,
    myDimension: Dimension,
) {
    val start = Instant.parse(date)
    val endDate = Instant.now()
    val statisticsRequest =
        GetMetricStatisticsRequest {
            endTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(endDate)
            startTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(start)
            dimensions = listOf(myDimension)
            metricName = metVal
            namespace = nameSpaceVal
            period = 86400
            statistics = listOf(Statistic.fromValue(metricOption))
        }

    CloudWatchClient { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.getMetricStatistics(statisticsRequest)
        val data = response.datapoints
        if (data != null) {
            if (data.isNotEmpty()) {
                for (datapoint in data) {
                    println("Timestamp: ${datapoint.timestamp} Maximum value: ${datapoint.maximum}")
                }
            } else {
                println("The returned data list is empty")
            }
        }
    }
}

suspend fun listMets(namespaceVal: String?): ArrayList<String>? {
    val metList = ArrayList<String>()
    val request =
        ListMetricsRequest {
            namespace = namespaceVal
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val reponse = cwClient.listMetrics(request)
        reponse.metrics?.forEach { metrics ->
            val data = metrics.metricName
            if (!metList.contains(data)) {
                metList.add(data!!)
            }
        }
    }
    return metList
}

suspend fun getSpecificMet(namespaceVal: String?): Dimension? {
    val request =
        ListMetricsRequest {
            namespace = namespaceVal
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.listMetrics(request)
        val myList = response.metrics
        if (myList != null) {
            return myList[0].dimensions?.get(0)
        }
    }
    return null
}

suspend fun listNameSpaces(): ArrayList<String> {
    val nameSpaceList = ArrayList<String>()
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.listMetrics(ListMetricsRequest {})
        response.metrics?.forEach { metrics ->
            val data = metrics.namespace
            if (!nameSpaceList.contains(data)) {
                nameSpaceList.add(data!!)
            }
        }
    }
    return nameSpaceList
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [DeleteAlarms](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteAnomalyDetector](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteDashboards](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeAlarmHistory](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeAlarms](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeAlarmsForMetric](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeAnomalyDetectors](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetMetricData](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetMetricStatistics](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetMetricWidgetImage](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListMetrics](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutAnomalyDetector](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutDashboard](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutMetricAlarm](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutMetricData](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_kotlin_1_topic"></a>

次のコード例は、`DeleteAlarms` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteAlarm(alarmNameVal: String) {
    val request =
        DeleteAlarmsRequest {
            alarmNames = listOf(alarmNameVal)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.deleteAlarms(request)
        println("Successfully deleted alarm $alarmNameVal")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteAlarms](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteAnomalyDetector`
<a name="cloudwatch_DeleteAnomalyDetector_kotlin_1_topic"></a>

次のコード例は、`DeleteAnomalyDetector` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteAnomalyDetector(fileName: String) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    val singleMetricAnomalyDetectorVal =
        SingleMetricAnomalyDetector {
            metricName = customMetricName
            namespace = customMetricNamespace
            stat = "Maximum"
        }

    val request =
        DeleteAnomalyDetectorRequest {
            singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.deleteAnomalyDetector(request)
        println("Successfully deleted the Anomaly Detector.")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeleteAnomalyDetector](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteDashboards`
<a name="cloudwatch_DeleteDashboards_kotlin_1_topic"></a>

次のコード例は、`DeleteDashboards` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteDashboard(dashboardName: String) {
    val dashboardsRequest =
        DeleteDashboardsRequest {
            dashboardNames = listOf(dashboardName)
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.deleteDashboards(dashboardsRequest)
        println("$dashboardName was successfully deleted.")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeleteDashboards](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAlarmHistory`
<a name="cloudwatch_DescribeAlarmHistory_kotlin_1_topic"></a>

次のコード例は、`DescribeAlarmHistory` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getAlarmHistory(
    fileName: String,
    date: String,
) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val alarmNameVal = rootNode.findValue("exampleAlarmName").asText()
    val start = Instant.parse(date)
    val endDateVal = Instant.now()

    val historyRequest =
        DescribeAlarmHistoryRequest {
            startDate =
                aws.smithy.kotlin.runtime.time
                    .Instant(start)
            endDate =
                aws.smithy.kotlin.runtime.time
                    .Instant(endDateVal)
            alarmName = alarmNameVal
            historyItemType = HistoryItemType.Action
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.describeAlarmHistory(historyRequest)
        val historyItems = response.alarmHistoryItems
        if (historyItems != null) {
            if (historyItems.isEmpty()) {
                println("No alarm history data found for $alarmNameVal.")
            } else {
                for (item in historyItems) {
                    println("History summary ${item.historySummary}")
                    println("Time stamp: ${item.timestamp}")
                }
            }
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス**」の「[DescribeAlarmHistory](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAlarms`
<a name="cloudwatch_DescribeAlarms_kotlin_1_topic"></a>

次のコード例は、`DescribeAlarms` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeAlarms() {
    val typeList = ArrayList<AlarmType>()
    typeList.add(AlarmType.MetricAlarm)
    val alarmsRequest =
        DescribeAlarmsRequest {
            alarmTypes = typeList
            maxRecords = 10
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.describeAlarms(alarmsRequest)
        response.metricAlarms?.forEach { alarm ->
            println("Alarm name: ${alarm.alarmName}")
            println("Alarm description: ${alarm.alarmDescription}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DescribeAlarms](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_kotlin_1_topic"></a>

次のコード例は、`DescribeAlarmsForMetric` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun checkForMetricAlarm(fileName: String?) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()
    var hasAlarm = false
    var retries = 10

    val metricRequest =
        DescribeAlarmsForMetricRequest {
            metricName = customMetricName
            namespace = customMetricNamespace
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        while (!hasAlarm && retries > 0) {
            val response = cwClient.describeAlarmsForMetric(metricRequest)
            if (response.metricAlarms?.count()!! > 0) {
                hasAlarm = true
            }
            retries--
            delay(20000)
            println(".")
        }
        if (!hasAlarm) {
            println("No Alarm state found for $customMetricName after 10 retries.")
        } else {
            println("Alarm state found for $customMetricName.")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeAlarmsForMetric](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAnomalyDetectors`
<a name="cloudwatch_DescribeAnomalyDetectors_kotlin_1_topic"></a>

次のコード例は、`DescribeAnomalyDetectors` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeAnomalyDetectors(fileName: String) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    val detectorsRequest =
        DescribeAnomalyDetectorsRequest {
            maxResults = 10
            metricName = customMetricName
            namespace = customMetricNamespace
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.describeAnomalyDetectors(detectorsRequest)
        response.anomalyDetectors?.forEach { detector ->
            println("Metric name: ${detector.singleMetricAnomalyDetector?.metricName}")
            println("State: ${detector.stateValue}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DescribeAnomalyDetectors](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_kotlin_1_topic"></a>

次のコード例は、`DisableAlarmActions` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun disableActions(alarmName: String) {
    val request =
        DisableAlarmActionsRequest {
            alarmNames = listOf(alarmName)
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.disableAlarmActions(request)
        println("Successfully disabled actions on alarm $alarmName")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DisableAlarmActions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_kotlin_1_topic"></a>

次のコード例は、`EnableAlarmActions` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun enableActions(alarm: String) {
    val request =
        EnableAlarmActionsRequest {
            alarmNames = listOf(alarm)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.enableAlarmActions(request)
        println("Successfully enabled actions on alarm $alarm")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[EnableAlarmActions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetMetricData`
<a name="cloudwatch_GetMetricData_kotlin_1_topic"></a>

次のコード例は、`GetMetricData` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getCustomMetricData(fileName: String) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    // Set the date.
    val nowDate = Instant.now()
    val hours: Long = 1
    val minutes: Long = 30
    val date2 =
        nowDate.plus(hours, ChronoUnit.HOURS).plus(
            minutes,
            ChronoUnit.MINUTES,
        )

    val met =
        Metric {
            metricName = customMetricName
            namespace = customMetricNamespace
        }

    val metStat =
        MetricStat {
            stat = "Maximum"
            period = 1
            metric = met
        }

    val dataQUery =
        MetricDataQuery {
            metricStat = metStat
            id = "foo2"
            returnData = true
        }

    val dq = ArrayList<MetricDataQuery>()
    dq.add(dataQUery)
    val getMetReq =
        GetMetricDataRequest {
            maxDatapoints = 10
            scanBy = ScanBy.TimestampDescending
            startTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(nowDate)
            endTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(date2)
            metricDataQueries = dq
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.getMetricData(getMetReq)
        response.metricDataResults?.forEach { item ->
            println("The label is ${item.label}")
            println("The status code is ${item.statusCode}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[GetMetricData](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetMetricStatistics`
<a name="cloudwatch_GetMetricStatistics_kotlin_1_topic"></a>

次のコード例は、`GetMetricStatistics` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getAndDisplayMetricStatistics(
    nameSpaceVal: String,
    metVal: String,
    metricOption: String,
    date: String,
    myDimension: Dimension,
) {
    val start = Instant.parse(date)
    val endDate = Instant.now()
    val statisticsRequest =
        GetMetricStatisticsRequest {
            endTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(endDate)
            startTime =
                aws.smithy.kotlin.runtime.time
                    .Instant(start)
            dimensions = listOf(myDimension)
            metricName = metVal
            namespace = nameSpaceVal
            period = 86400
            statistics = listOf(Statistic.fromValue(metricOption))
        }

    CloudWatchClient { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.getMetricStatistics(statisticsRequest)
        val data = response.datapoints
        if (data != null) {
            if (data.isNotEmpty()) {
                for (datapoint in data) {
                    println("Timestamp: ${datapoint.timestamp} Maximum value: ${datapoint.maximum}")
                }
            } else {
                println("The returned data list is empty")
            }
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[GetMetricStatistics](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetMetricWidgetImage`
<a name="cloudwatch_GetMetricWidgetImage_kotlin_1_topic"></a>

次のコード例は、`GetMetricWidgetImage` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getAndOpenMetricImage(fileName: String) {
    println("Getting Image data for custom metric.")
    val myJSON = """{
        "title": "Example Metric Graph",
        "view": "timeSeries",
        "stacked ": false,
        "period": 10,
        "width": 1400,
        "height": 600,
        "metrics": [
            [
            "AWS/Billing",
            "EstimatedCharges",
            "Currency",
            "USD"
            ]
        ]
        }"""

    val imageRequest =
        GetMetricWidgetImageRequest {
            metricWidget = myJSON
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.getMetricWidgetImage(imageRequest)
        val bytes = response.metricWidgetImage
        if (bytes != null) {
            File(fileName).writeBytes(bytes)
        }
    }
    println("You have successfully written data to $fileName")
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[GetMetricWidgetImage](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListDashboards`
<a name="cloudwatch_ListDashboards_kotlin_1_topic"></a>

次のコード例は、`ListDashboards` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listDashboards() {
    CloudWatchClient { region = "us-east-1" }.use { cwClient ->
        cwClient
            .listDashboardsPaginated({})
            .transform { it.dashboardEntries?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println("Name is ${obj.dashboardName}")
                println("Dashboard ARN is ${obj.dashboardArn}")
            }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[ListDashboards](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_kotlin_1_topic"></a>

次のコード例は、`ListMetrics` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listMets(namespaceVal: String?): ArrayList<String>? {
    val metList = ArrayList<String>()
    val request =
        ListMetricsRequest {
            namespace = namespaceVal
        }
    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val reponse = cwClient.listMetrics(request)
        reponse.metrics?.forEach { metrics ->
            val data = metrics.metricName
            if (!metList.contains(data)) {
                metList.add(data!!)
            }
        }
    }
    return metList
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[ListMetrics](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutAnomalyDetector`
<a name="cloudwatch_PutAnomalyDetector_kotlin_1_topic"></a>

次のコード例は、`PutAnomalyDetector` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun addAnomalyDetector(fileName: String?) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    val singleMetricAnomalyDetectorVal =
        SingleMetricAnomalyDetector {
            metricName = customMetricName
            namespace = customMetricNamespace
            stat = "Maximum"
        }

    val anomalyDetectorRequest =
        PutAnomalyDetectorRequest {
            singleMetricAnomalyDetector = singleMetricAnomalyDetectorVal
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putAnomalyDetector(anomalyDetectorRequest)
        println("Added anomaly detector for metric $customMetricName.")
    }
}
```
+  API の詳細については、**「AWS SDK for Kotlin API リファレンス」の「[PutAnomalyDetector](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutDashboard`
<a name="cloudwatch_PutDashboard_kotlin_1_topic"></a>

次のコード例は、`PutDashboard` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createDashboardWithMetrics(
    dashboardNameVal: String,
    fileNameVal: String,
) {
    val dashboardRequest =
        PutDashboardRequest {
            dashboardName = dashboardNameVal
            dashboardBody = readFileAsString(fileNameVal)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        val response = cwClient.putDashboard(dashboardRequest)
        println("$dashboardNameVal was successfully created.")
        val messages = response.dashboardValidationMessages
        if (messages != null) {
            if (messages.isEmpty()) {
                println("There are no messages in the new Dashboard")
            } else {
                for (message in messages) {
                    println("Message is: ${message.message}")
                }
            }
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[PutDashboard](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_kotlin_1_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun putMetricAlarm(
    alarmNameVal: String,
    instanceIdVal: String,
) {
    val dimensionOb =
        Dimension {
            name = "InstanceId"
            value = instanceIdVal
        }

    val request =
        PutMetricAlarmRequest {
            alarmName = alarmNameVal
            comparisonOperator = ComparisonOperator.GreaterThanThreshold
            evaluationPeriods = 1
            metricName = "CPUUtilization"
            namespace = "AWS/EC2"
            period = 60
            statistic = Statistic.fromValue("Average")
            threshold = 70.0
            actionsEnabled = false
            alarmDescription = "An Alarm created by the Kotlin SDK when server CPU utilization exceeds 70%"
            unit = StandardUnit.fromValue("Seconds")
            dimensions = listOf(dimensionOb)
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putMetricAlarm(request)
        println("Successfully created an alarm with name $alarmNameVal")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[PutMetricAlarm](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_kotlin_1_topic"></a>

次のコード例は、`PutMetricData` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun addMetricDataForAlarm(fileName: String?) {
    // Read values from the JSON file.
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val customMetricNamespace = rootNode.findValue("customMetricNamespace").asText()
    val customMetricName = rootNode.findValue("customMetricName").asText()

    // Set an Instant object.
    val time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)
    val instant = Instant.parse(time)
    val datum =
        MetricDatum {
            metricName = customMetricName
            unit = StandardUnit.None
            value = 1001.00
            timestamp =
                aws.smithy.kotlin.runtime.time
                    .Instant(instant)
        }

    val datum2 =
        MetricDatum {
            metricName = customMetricName
            unit = StandardUnit.None
            value = 1002.00
            timestamp =
                aws.smithy.kotlin.runtime.time
                    .Instant(instant)
        }

    val metricDataList = ArrayList<MetricDatum>()
    metricDataList.add(datum)
    metricDataList.add(datum2)

    val request =
        PutMetricDataRequest {
            namespace = customMetricNamespace
            metricData = metricDataList
        }

    CloudWatchClient.fromEnvironment { region = "us-east-1" }.use { cwClient ->
        cwClient.putMetricData(request)
        println("Added metric values for for metric $customMetricName")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[PutMetricData](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した CloudWatch Logs のコード例
<a name="kotlin_1_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteSubscriptionFilter`
<a name="cloudwatch-logs_DeleteSubscriptionFilter_kotlin_1_topic"></a>

次のコード例は、`DeleteSubscriptionFilter` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteSubFilter(
    filter: String?,
    logGroup: String?,
) {
    val request =
        DeleteSubscriptionFilterRequest {
            filterName = filter
            logGroupName = logGroup
        }

    CloudWatchLogsClient.fromEnvironment { region = "us-west-2" }.use { logs ->
        logs.deleteSubscriptionFilter(request)
        println("Successfully deleted CloudWatch logs subscription filter named $filter")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」**の「[DeleteSubscriptionFilter](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeSubscriptionFilters`
<a name="cloudwatch-logs_DescribeSubscriptionFilters_kotlin_1_topic"></a>

次のコード例は、`DescribeSubscriptionFilters` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeFilters(logGroup: String) {
    val request =
        DescribeSubscriptionFiltersRequest {
            logGroupName = logGroup
            limit = 1
        }

    CloudWatchLogsClient.fromEnvironment { region = "us-west-2" }.use { cwlClient ->
        val response = cwlClient.describeSubscriptionFilters(request)
        response.subscriptionFilters?.forEach { filter ->
            println("Retrieved filter with name  ${filter.filterName} pattern ${filter.filterPattern} and destination ${filter.destinationArn}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」**の「[DescribeSubscriptionFilters](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `StartLiveTail`
<a name="cloudwatch-logs_StartLiveTail_kotlin_1_topic"></a>

次のコード例は、`StartLiveTail` を使用する方法を示しています。

**SDK for Kotlin**  
必要なファイルを含めます。  

```
import aws.sdk.kotlin.services.cloudwatchlogs.CloudWatchLogsClient
import aws.sdk.kotlin.services.cloudwatchlogs.model.StartLiveTailRequest
import aws.sdk.kotlin.services.cloudwatchlogs.model.StartLiveTailResponseStream
import kotlinx.coroutines.flow.takeWhile
```
Live Tail セッションを開始します。  

```
    val client = CloudWatchLogsClient.fromEnvironment()

    val request = StartLiveTailRequest {
        logGroupIdentifiers = logGroupIdentifiersVal
        logStreamNames = logStreamNamesVal
        logEventFilterPattern = logEventFilterPatternVal
    }

    val startTime = System.currentTimeMillis()

    try {
        client.startLiveTail(request) { response ->
            val stream = response.responseStream
            if (stream != null) {
                /* Set a timeout to unsubcribe from the flow. This will:
                * 1). Close the stream
                * 2). Stop the Live Tail session
                */
                stream.takeWhile { System.currentTimeMillis() - startTime < 10000 }.collect { value ->
                    if (value is StartLiveTailResponseStream.SessionStart) {
                        println(value.asSessionStart())
                    } else if (value is StartLiveTailResponseStream.SessionUpdate) {
                        for (e in value.asSessionUpdate().sessionResults!!) {
                            println(e)
                        }
                    } else {
                        throw IllegalArgumentException("Unknown event type")
                    }
                }
            } else {
                throw IllegalArgumentException("No response stream")
            }
        }
    } catch (e: Exception) {
        println("Exception occurred during StartLiveTail: $e")
        System.exit(1)
    }
```
+  API の詳細については、「**AWS SDK for Kotlin API リファレンス」の「[StartLiveTail](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用する Amazon Cognito ID プロバイダーの例
<a name="kotlin_1_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AdminGetUser`
<a name="cognito-identity-provider_AdminGetUser_kotlin_1_topic"></a>

次のコード例は、`AdminGetUser` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getAdminUser(
    userNameVal: String?,
    poolIdVal: String?,
) {
    val userRequest =
        AdminGetUserRequest {
            username = userNameVal
            userPoolId = poolIdVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val response = identityProviderClient.adminGetUser(userRequest)
        println("User status ${response.userStatus}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[AdminGetUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_kotlin_1_topic"></a>

次のコード例は、`AdminInitiateAuth` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
suspend fun checkAuthMethod(
    clientIdVal: String,
    userNameVal: String,
    passwordVal: String,
    userPoolIdVal: String,
): AdminInitiateAuthResponse {
    val authParas = mutableMapOf<String, String>()
    authParas["USERNAME"] = userNameVal
    authParas["PASSWORD"] = passwordVal

    val authRequest =
        AdminInitiateAuthRequest {
            clientId = clientIdVal
            userPoolId = userPoolIdVal
            authParameters = authParas
            authFlow = AuthFlowType.AdminUserPasswordAuth
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val response = identityProviderClient.adminInitiateAuth(authRequest)
        println("Result Challenge is ${response.challengeName}")
        return response
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[AdminInitiateAuth](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_kotlin_1_topic"></a>

次のコード例は、`AdminRespondToAuthChallenge` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
// Respond to an authentication challenge.
suspend fun adminRespondToAuthChallenge(
    userName: String,
    clientIdVal: String?,
    mfaCode: String,
    sessionVal: String?,
) {
    println("SOFTWARE_TOKEN_MFA challenge is generated")
    val challengeResponsesOb = mutableMapOf<String, String>()
    challengeResponsesOb["USERNAME"] = userName
    challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode

    val adminRespondToAuthChallengeRequest =
        AdminRespondToAuthChallengeRequest {
            challengeName = ChallengeNameType.SoftwareTokenMfa
            clientId = clientIdVal
            challengeResponses = challengeResponsesOb
            session = sessionVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(adminRespondToAuthChallengeRequest)
        println("respondToAuthChallengeResult.getAuthenticationResult() ${respondToAuthChallengeResult.authenticationResult}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[AdminRespondToAuthChallenge](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_kotlin_1_topic"></a>

次のコード例は、`AssociateSoftwareToken` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getSecretForAppMFA(sessionVal: String?): String? {
    val softwareTokenRequest =
        AssociateSoftwareTokenRequest {
            session = sessionVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest)
        val secretCode = tokenResponse.secretCode
        println("Enter this token into Google Authenticator")
        println(secretCode)
        return tokenResponse.session
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[AssociateSoftwareToken](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ConfirmSignUp`
<a name="cognito-identity-provider_ConfirmSignUp_kotlin_1_topic"></a>

次のコード例は、`ConfirmSignUp` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
suspend fun confirmSignUp(
    clientIdVal: String?,
    codeVal: String?,
    userNameVal: String?,
) {
    val signUpRequest =
        ConfirmSignUpRequest {
            clientId = clientIdVal
            confirmationCode = codeVal
            username = userNameVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        identityProviderClient.confirmSignUp(signUpRequest)
        println("$userNameVal  was confirmed")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ConfirmSignUp](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListUsers`
<a name="cognito-identity-provider_ListUsers_kotlin_1_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllUsers(userPoolId: String) {
    val request =
        ListUsersRequest {
            this.userPoolId = userPoolId
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { cognitoClient ->
        val response = cognitoClient.listUsers(request)
        response.users?.forEach { user ->
            println("The user name is ${user.username}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListUsers](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ResendConfirmationCode`
<a name="cognito-identity-provider_ResendConfirmationCode_kotlin_1_topic"></a>

次のコード例は、`ResendConfirmationCode` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
suspend fun resendConfirmationCode(
    clientIdVal: String?,
    userNameVal: String?,
) {
    val codeRequest =
        ResendConfirmationCodeRequest {
            clientId = clientIdVal
            username = userNameVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val response = identityProviderClient.resendConfirmationCode(codeRequest)
        println("Method of delivery is " + (response.codeDeliveryDetails?.deliveryMedium))
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ResendConfirmationCode](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SignUp`
<a name="cognito-identity-provider_SignUp_kotlin_1_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
suspend fun signUp(
    clientIdVal: String?,
    userNameVal: String?,
    passwordVal: String?,
    emailVal: String?,
) {
    val userAttrs =
        AttributeType {
            name = "email"
            value = emailVal
        }

    val userAttrsList = mutableListOf<AttributeType>()
    userAttrsList.add(userAttrs)
    val signUpRequest =
        SignUpRequest {
            userAttributes = userAttrsList
            username = userNameVal
            clientId = clientIdVal
            password = passwordVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        identityProviderClient.signUp(signUpRequest)
        println("User has been signed up")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[SignUp](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_kotlin_1_topic"></a>

次のコード例は、`VerifySoftwareToken` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
// Verify the TOTP and register for MFA.
suspend fun verifyTOTP(
    sessionVal: String?,
    codeVal: String?,
) {
    val tokenRequest =
        VerifySoftwareTokenRequest {
            userCode = codeVal
            session = sessionVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest)
        println("The status of the token is ${verifyResponse.status}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[VerifySoftwareToken](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### MFA を必要とするユーザープールでユーザーをサインアップする
<a name="cognito-identity-provider_Scenario_SignUpUserWithMfa_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。
+ MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。
+ パスワードと MFA コードを使用してサインインします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/cognito#code-examples)での設定と実行の方法を確認してください。

```
/**
 Before running this Kotlin code example, set up your development environment, including your credentials.

 For more information, see the following documentation:
 https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html

 TIP: To set up the required user pool, run the AWS Cloud Development Kit (AWS CDK) script provided in this GitHub repo at resources/cdk/cognito_scenario_user_pool_with_mfa.

 This code example performs the following operations:

 1. Invokes the signUp method to sign up a user.
 2. Invokes the adminGetUser method to get the user's confirmation status.
 3. Invokes the ResendConfirmationCode method if the user requested another code.
 4. Invokes the confirmSignUp method.
 5. Invokes the initiateAuth to sign in. This results in being prompted to set up TOTP (time-based one-time password). (The response is “ChallengeName”: “MFA_SETUP”).
 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private key. This can be used with Google Authenticator.
 7. Invokes the VerifySoftwareToken method to verify the TOTP and register for MFA.
 8. Invokes the AdminInitiateAuth to sign in again. This results in being prompted to submit a TOTP (Response: “ChallengeName”: “SOFTWARE_TOKEN_MFA”).
 9. Invokes the AdminRespondToAuthChallenge to get back a token.
 */

suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <clientId> <poolId>
        Where:
            clientId - The app client Id value that you can get from the AWS CDK script.
            poolId - The pool Id that you can get from the AWS CDK script. 
    """

    if (args.size != 2) {
        println(usage)
        exitProcess(1)
    }

    val clientId = args[0]
    val poolId = args[1]

    // Use the console to get data from the user.
    println("*** Enter your use name")
    val inOb = Scanner(System.`in`)
    val userName = inOb.nextLine()
    println(userName)

    println("*** Enter your password")
    val password: String = inOb.nextLine()

    println("*** Enter your email")
    val email = inOb.nextLine()

    println("*** Signing up $userName")
    signUp(clientId, userName, password, email)

    println("*** Getting $userName in the user pool")
    getAdminUser(userName, poolId)

    println("*** Conformation code sent to $userName. Would you like to send a new code? (Yes/No)")
    val ans = inOb.nextLine()

    if (ans.compareTo("Yes") == 0) {
        println("*** Sending a new confirmation code")
        resendConfirmationCode(clientId, userName)
    }
    println("*** Enter the confirmation code that was emailed")
    val code = inOb.nextLine()
    confirmSignUp(clientId, code, userName)

    println("*** Rechecking the status of $userName in the user pool")
    getAdminUser(userName, poolId)

    val authResponse = checkAuthMethod(clientId, userName, password, poolId)
    val mySession = authResponse.session
    val newSession = getSecretForAppMFA(mySession)
    println("*** Enter the 6-digit code displayed in Google Authenticator")
    val myCode = inOb.nextLine()

    // Verify the TOTP and register for MFA.
    verifyTOTP(newSession, myCode)
    println("*** Re-enter a 6-digit code displayed in Google Authenticator")
    val mfaCode: String = inOb.nextLine()
    val authResponse1 = checkAuthMethod(clientId, userName, password, poolId)
    val session2 = authResponse1.session
    adminRespondToAuthChallenge(userName, clientId, mfaCode, session2)
}

suspend fun checkAuthMethod(
    clientIdVal: String,
    userNameVal: String,
    passwordVal: String,
    userPoolIdVal: String,
): AdminInitiateAuthResponse {
    val authParas = mutableMapOf<String, String>()
    authParas["USERNAME"] = userNameVal
    authParas["PASSWORD"] = passwordVal

    val authRequest =
        AdminInitiateAuthRequest {
            clientId = clientIdVal
            userPoolId = userPoolIdVal
            authParameters = authParas
            authFlow = AuthFlowType.AdminUserPasswordAuth
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val response = identityProviderClient.adminInitiateAuth(authRequest)
        println("Result Challenge is ${response.challengeName}")
        return response
    }
}

suspend fun resendConfirmationCode(
    clientIdVal: String?,
    userNameVal: String?,
) {
    val codeRequest =
        ResendConfirmationCodeRequest {
            clientId = clientIdVal
            username = userNameVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val response = identityProviderClient.resendConfirmationCode(codeRequest)
        println("Method of delivery is " + (response.codeDeliveryDetails?.deliveryMedium))
    }
}

// Respond to an authentication challenge.
suspend fun adminRespondToAuthChallenge(
    userName: String,
    clientIdVal: String?,
    mfaCode: String,
    sessionVal: String?,
) {
    println("SOFTWARE_TOKEN_MFA challenge is generated")
    val challengeResponsesOb = mutableMapOf<String, String>()
    challengeResponsesOb["USERNAME"] = userName
    challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode

    val adminRespondToAuthChallengeRequest =
        AdminRespondToAuthChallengeRequest {
            challengeName = ChallengeNameType.SoftwareTokenMfa
            clientId = clientIdVal
            challengeResponses = challengeResponsesOb
            session = sessionVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val respondToAuthChallengeResult = identityProviderClient.adminRespondToAuthChallenge(adminRespondToAuthChallengeRequest)
        println("respondToAuthChallengeResult.getAuthenticationResult() ${respondToAuthChallengeResult.authenticationResult}")
    }
}

// Verify the TOTP and register for MFA.
suspend fun verifyTOTP(
    sessionVal: String?,
    codeVal: String?,
) {
    val tokenRequest =
        VerifySoftwareTokenRequest {
            userCode = codeVal
            session = sessionVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val verifyResponse = identityProviderClient.verifySoftwareToken(tokenRequest)
        println("The status of the token is ${verifyResponse.status}")
    }
}

suspend fun getSecretForAppMFA(sessionVal: String?): String? {
    val softwareTokenRequest =
        AssociateSoftwareTokenRequest {
            session = sessionVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val tokenResponse = identityProviderClient.associateSoftwareToken(softwareTokenRequest)
        val secretCode = tokenResponse.secretCode
        println("Enter this token into Google Authenticator")
        println(secretCode)
        return tokenResponse.session
    }
}

suspend fun confirmSignUp(
    clientIdVal: String?,
    codeVal: String?,
    userNameVal: String?,
) {
    val signUpRequest =
        ConfirmSignUpRequest {
            clientId = clientIdVal
            confirmationCode = codeVal
            username = userNameVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        identityProviderClient.confirmSignUp(signUpRequest)
        println("$userNameVal  was confirmed")
    }
}

suspend fun getAdminUser(
    userNameVal: String?,
    poolIdVal: String?,
) {
    val userRequest =
        AdminGetUserRequest {
            username = userNameVal
            userPoolId = poolIdVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        val response = identityProviderClient.adminGetUser(userRequest)
        println("User status ${response.userStatus}")
    }
}

suspend fun signUp(
    clientIdVal: String?,
    userNameVal: String?,
    passwordVal: String?,
    emailVal: String?,
) {
    val userAttrs =
        AttributeType {
            name = "email"
            value = emailVal
        }

    val userAttrsList = mutableListOf<AttributeType>()
    userAttrsList.add(userAttrs)
    val signUpRequest =
        SignUpRequest {
            userAttributes = userAttrsList
            username = userNameVal
            clientId = clientIdVal
            password = passwordVal
        }

    CognitoIdentityProviderClient.fromEnvironment { region = "us-east-1" }.use { identityProviderClient ->
        identityProviderClient.signUp(signUpRequest)
        println("User has been signed up")
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [AdminGetUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [AdminInitiateAuth](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [AdminRespondToAuthChallenge](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [AssociateSoftwareToken](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ConfirmDevice](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ConfirmSignUp](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [InitiateAuth](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListUsers](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ResendConfirmationCode](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [RespondToAuthChallenge](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [SignUp](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [VerifySoftwareToken](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

# SDK for Kotlin を使用した Amazon Comprehend の例
<a name="kotlin_1_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### メッセージングアプリケーションを作成する
<a name="cross_SQSMessageApp_kotlin_1_topic"></a>

次のコード例は、Amazon SQS を使用してメッセージングアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon SQS API を使用して、メッセージを送受信する Spring REST API を開発する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_message_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SQS

# SDK for Kotlin を使用した DynamoDB の例
<a name="kotlin_1_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。
DynamoDB テーブルを作成します。  

```
suspend fun createScenarioTable(
    tableNameVal: String,
    key: String,
) {
    val attDef =
        AttributeDefinition {
            attributeName = key
            attributeType = ScalarAttributeType.N
        }

    val attDef1 =
        AttributeDefinition {
            attributeName = "title"
            attributeType = ScalarAttributeType.S
        }

    val keySchemaVal =
        KeySchemaElement {
            attributeName = key
            keyType = KeyType.Hash
        }

    val keySchemaVal1 =
        KeySchemaElement {
            attributeName = "title"
            keyType = KeyType.Range
        }

    val request =
        CreateTableRequest {
            attributeDefinitions = listOf(attDef, attDef1)
            keySchema = listOf(keySchemaVal, keySchemaVal1)
            billingMode = BillingMode.PayPerRequest
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.createTable(request)
        ddb.waitUntilTableExists {
            // suspend call
            tableName = tableNameVal
        }
        println("The table was successfully created ${response.tableDescription?.tableArn}")
    }
}
```
サンプルの JSON ファイルをダウンロードして抽出するヘルパー関数を作成します。  

```
// Load data into the table.
suspend fun loadData(
    tableName: String,
    fileName: String,
) {
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val iter: Iterator<JsonNode> = rootNode.iterator()
    var currentNode: ObjectNode

    var t = 0
    while (iter.hasNext()) {
        if (t == 50) {
            break
        }

        currentNode = iter.next() as ObjectNode
        val year = currentNode.path("year").asInt()
        val title = currentNode.path("title").asText()
        val info = currentNode.path("info").toString()
        putMovie(tableName, year, title, info)
        t++
    }
}

suspend fun putMovie(
    tableNameVal: String,
    year: Int,
    title: String,
    info: String,
) {
    val itemValues = mutableMapOf<String, AttributeValue>()
    val strVal = year.toString()
    // Add all content to the table.
    itemValues["year"] = AttributeValue.N(strVal)
    itemValues["title"] = AttributeValue.S(title)
    itemValues["info"] = AttributeValue.S(info)

    val request =
        PutItemRequest {
            tableName = tableNameVal
            item = itemValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.putItem(request)
        println("Added $title to the Movie table.")
    }
}
```
テーブルから項目を取得します。  

```
suspend fun getMovie(
    tableNameVal: String,
    keyName: String,
    keyVal: String,
) {
    val keyToGet = mutableMapOf<String, AttributeValue>()
    keyToGet[keyName] = AttributeValue.N(keyVal)
    keyToGet["title"] = AttributeValue.S("King Kong")

    val request =
        GetItemRequest {
            key = keyToGet
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val returnedItem = ddb.getItem(request)
        val numbersMap = returnedItem.item
        numbersMap?.forEach { key1 ->
            println(key1.key)
            println(key1.value)
        }
    }
}
```
完全な例です。  

```
suspend fun main() {
    val tableName = "Movies"
    val fileName = "../../../resources/sample_files/movies.json"
    val partitionAlias = "#a"

    println("Creating an Amazon DynamoDB table named Movies with a key named id and a sort key named title.")
    createScenarioTable(tableName, "year")
    loadData(tableName, fileName)
    getMovie(tableName, "year", "1933")
    scanMovies(tableName)
    val count = queryMovieTable(tableName, "year", partitionAlias)
    println("There are $count Movies released in 2013.")
    deletIssuesTable(tableName)
}

suspend fun createScenarioTable(
    tableNameVal: String,
    key: String,
) {
    val attDef =
        AttributeDefinition {
            attributeName = key
            attributeType = ScalarAttributeType.N
        }

    val attDef1 =
        AttributeDefinition {
            attributeName = "title"
            attributeType = ScalarAttributeType.S
        }

    val keySchemaVal =
        KeySchemaElement {
            attributeName = key
            keyType = KeyType.Hash
        }

    val keySchemaVal1 =
        KeySchemaElement {
            attributeName = "title"
            keyType = KeyType.Range
        }

    val request =
        CreateTableRequest {
            attributeDefinitions = listOf(attDef, attDef1)
            keySchema = listOf(keySchemaVal, keySchemaVal1)
            billingMode = BillingMode.PayPerRequest
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.createTable(request)
        ddb.waitUntilTableExists {
            // suspend call
            tableName = tableNameVal
        }
        println("The table was successfully created ${response.tableDescription?.tableArn}")
    }
}

// Load data into the table.
suspend fun loadData(
    tableName: String,
    fileName: String,
) {
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val iter: Iterator<JsonNode> = rootNode.iterator()
    var currentNode: ObjectNode

    var t = 0
    while (iter.hasNext()) {
        if (t == 50) {
            break
        }

        currentNode = iter.next() as ObjectNode
        val year = currentNode.path("year").asInt()
        val title = currentNode.path("title").asText()
        val info = currentNode.path("info").toString()
        putMovie(tableName, year, title, info)
        t++
    }
}

suspend fun putMovie(
    tableNameVal: String,
    year: Int,
    title: String,
    info: String,
) {
    val itemValues = mutableMapOf<String, AttributeValue>()
    val strVal = year.toString()
    // Add all content to the table.
    itemValues["year"] = AttributeValue.N(strVal)
    itemValues["title"] = AttributeValue.S(title)
    itemValues["info"] = AttributeValue.S(info)

    val request =
        PutItemRequest {
            tableName = tableNameVal
            item = itemValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.putItem(request)
        println("Added $title to the Movie table.")
    }
}

suspend fun getMovie(
    tableNameVal: String,
    keyName: String,
    keyVal: String,
) {
    val keyToGet = mutableMapOf<String, AttributeValue>()
    keyToGet[keyName] = AttributeValue.N(keyVal)
    keyToGet["title"] = AttributeValue.S("King Kong")

    val request =
        GetItemRequest {
            key = keyToGet
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val returnedItem = ddb.getItem(request)
        val numbersMap = returnedItem.item
        numbersMap?.forEach { key1 ->
            println(key1.key)
            println(key1.value)
        }
    }
}

suspend fun deletIssuesTable(tableNameVal: String) {
    val request =
        DeleteTableRequest {
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.deleteTable(request)
        println("$tableNameVal was deleted")
    }
}

suspend fun queryMovieTable(
    tableNameVal: String,
    partitionKeyName: String,
    partitionAlias: String,
): Int {
    val attrNameAlias = mutableMapOf<String, String>()
    attrNameAlias[partitionAlias] = "year"

    // Set up mapping of the partition name with the value.
    val attrValues = mutableMapOf<String, AttributeValue>()
    attrValues[":$partitionKeyName"] = AttributeValue.N("2013")

    val request =
        QueryRequest {
            tableName = tableNameVal
            keyConditionExpression = "$partitionAlias = :$partitionKeyName"
            expressionAttributeNames = attrNameAlias
            this.expressionAttributeValues = attrValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.query(request)
        return response.count
    }
}

suspend fun scanMovies(tableNameVal: String) {
    val request =
        ScanRequest {
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.scan(request)
        response.items?.forEach { item ->
            item.keys.forEach { key ->
                println("The key name is $key\n")
                println("The value is ${item[key]}")
            }
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [BatchWriteItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Query](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Scan](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdateItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateTable`
<a name="dynamodb_CreateTable_kotlin_1_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createNewTable(
    tableNameVal: String,
    key: String,
): String? {
    val attDef =
        AttributeDefinition {
            attributeName = key
            attributeType = ScalarAttributeType.S
        }

    val keySchemaVal =
        KeySchemaElement {
            attributeName = key
            keyType = KeyType.Hash
        }

    val request =
        CreateTableRequest {
            attributeDefinitions = listOf(attDef)
            keySchema = listOf(keySchemaVal)
            billingMode = BillingMode.PayPerRequest
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        var tableArn: String
        val response = ddb.createTable(request)
        ddb.waitUntilTableExists {
            // suspend call
            tableName = tableNameVal
        }
        tableArn = response.tableDescription!!.tableArn.toString()
        println("Table $tableArn is ready")
        return tableArn
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_kotlin_1_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteDynamoDBItem(
    tableNameVal: String,
    keyName: String,
    keyVal: String,
) {
    val keyToGet = mutableMapOf<String, AttributeValue>()
    keyToGet[keyName] = AttributeValue.S(keyVal)

    val request =
        DeleteItemRequest {
            tableName = tableNameVal
            key = keyToGet
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.deleteItem(request)
        println("Item with key matching $keyVal was deleted")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeleteItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_kotlin_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteDynamoDBTable(tableNameVal: String) {
    val request =
        DeleteTableRequest {
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.deleteTable(request)
        println("$tableNameVal was deleted")
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_kotlin_1_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getSpecificItem(
    tableNameVal: String,
    keyName: String,
    keyVal: String,
) {
    val keyToGet = mutableMapOf<String, AttributeValue>()
    keyToGet[keyName] = AttributeValue.S(keyVal)

    val request =
        GetItemRequest {
            key = keyToGet
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val returnedItem = ddb.getItem(request)
        val numbersMap = returnedItem.item
        numbersMap?.forEach { key1 ->
            println(key1.key)
            println(key1.value)
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[GetItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_kotlin_1_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllTables() {
    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.listTables(ListTablesRequest {})
        response.tableNames?.forEach { tableName ->
            println("Table name is $tableName")
        }
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[ListTables](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_kotlin_1_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun putItemInTable(
    tableNameVal: String,
    key: String,
    keyVal: String,
    albumTitle: String,
    albumTitleValue: String,
    awards: String,
    awardVal: String,
    songTitle: String,
    songTitleVal: String,
) {
    val itemValues = mutableMapOf<String, AttributeValue>()

    // Add all content to the table.
    itemValues[key] = AttributeValue.S(keyVal)
    itemValues[songTitle] = AttributeValue.S(songTitleVal)
    itemValues[albumTitle] = AttributeValue.S(albumTitleValue)
    itemValues[awards] = AttributeValue.S(awardVal)

    val request =
        PutItemRequest {
            tableName = tableNameVal
            item = itemValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.putItem(request)
        println(" A new item was placed into $tableNameVal.")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[PutItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Query`
<a name="dynamodb_Query_kotlin_1_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun queryDynTable(
    tableNameVal: String,
    partitionKeyName: String,
    partitionKeyVal: String,
    partitionAlias: String,
): Int {
    val attrNameAlias = mutableMapOf<String, String>()
    attrNameAlias[partitionAlias] = partitionKeyName

    // Set up mapping of the partition name with the value.
    val attrValues = mutableMapOf<String, AttributeValue>()
    attrValues[":$partitionKeyName"] = AttributeValue.S(partitionKeyVal)

    val request =
        QueryRequest {
            tableName = tableNameVal
            keyConditionExpression = "$partitionAlias = :$partitionKeyName"
            expressionAttributeNames = attrNameAlias
            this.expressionAttributeValues = attrValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.query(request)
        return response.count
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[Query](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_kotlin_1_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun scanItems(tableNameVal: String) {
    val request =
        ScanRequest {
            tableName = tableNameVal
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        val response = ddb.scan(request)
        response.items?.forEach { item ->
            item.keys.forEach { key ->
                println("The key name is $key\n")
                println("The value is ${item[key]}")
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[Scan](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `UpdateItem`
<a name="dynamodb_UpdateItem_kotlin_1_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateTableItem(
    tableNameVal: String,
    keyName: String,
    keyVal: String,
    name: String,
    updateVal: String,
) {
    val itemKey = mutableMapOf<String, AttributeValue>()
    itemKey[keyName] = AttributeValue.S(keyVal)

    val updatedValues = mutableMapOf<String, AttributeValueUpdate>()
    updatedValues[name] =
        AttributeValueUpdate {
            value = AttributeValue.S(updateVal)
            action = AttributeAction.Put
        }

    val request =
        UpdateItemRequest {
            tableName = tableNameVal
            key = itemKey
            attributeUpdates = updatedValues
        }

    DynamoDbClient.fromEnvironment { region = "us-east-1" }.use { ddb ->
        ddb.updateItem(request)
        println("Item in $tableNameVal was updated")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[UpdateItem](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_kotlin_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Kotlin**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_pam) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon DynamoDB API を使用して、DynamoDB 作業データを追跡する動的ウェブアプリケーションを作成する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/itemtracker_dynamodb) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_kotlin_1_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun main() {
    val ddb = DynamoDbClient.fromEnvironment { region = "us-east-1" }
    val tableName = "MoviesPartiQBatch"
    println("Creating an Amazon DynamoDB table named $tableName with a key named id and a sort key named title.")
    createTablePartiQLBatch(ddb, tableName, "year")
    putRecordBatch(ddb)
    updateTableItemBatchBatch(ddb)
    deleteItemsBatch(ddb)
    deleteTablePartiQLBatch(tableName)
}

suspend fun createTablePartiQLBatch(
    ddb: DynamoDbClient,
    tableNameVal: String,
    key: String,
) {
    val attDef =
        AttributeDefinition {
            attributeName = key
            attributeType = ScalarAttributeType.N
        }

    val attDef1 =
        AttributeDefinition {
            attributeName = "title"
            attributeType = ScalarAttributeType.S
        }

    val keySchemaVal =
        KeySchemaElement {
            attributeName = key
            keyType = KeyType.Hash
        }

    val keySchemaVal1 =
        KeySchemaElement {
            attributeName = "title"
            keyType = KeyType.Range
        }

    val request =
        CreateTableRequest {
            attributeDefinitions = listOf(attDef, attDef1)
            keySchema = listOf(keySchemaVal, keySchemaVal1)
            billingMode = BillingMode.PayPerRequest
            tableName = tableNameVal
        }

    val response = ddb.createTable(request)
    ddb.waitUntilTableExists {
        // suspend call
        tableName = tableNameVal
    }
    println("The table was successfully created ${response.tableDescription?.tableArn}")
}

suspend fun putRecordBatch(ddb: DynamoDbClient) {
    val sqlStatement = "INSERT INTO MoviesPartiQBatch VALUE {'year':?, 'title' : ?, 'info' : ?}"

    // Create three movies to add to the Amazon DynamoDB table.
    val parametersMovie1 = mutableListOf<AttributeValue>()
    parametersMovie1.add(AttributeValue.N("2022"))
    parametersMovie1.add(AttributeValue.S("My Movie 1"))
    parametersMovie1.add(AttributeValue.S("No Information"))

    val statementRequestMovie1 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersMovie1
        }

    // Set data for Movie 2.
    val parametersMovie2 = mutableListOf<AttributeValue>()
    parametersMovie2.add(AttributeValue.N("2022"))
    parametersMovie2.add(AttributeValue.S("My Movie 2"))
    parametersMovie2.add(AttributeValue.S("No Information"))

    val statementRequestMovie2 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersMovie2
        }

    // Set data for Movie 3.
    val parametersMovie3 = mutableListOf<AttributeValue>()
    parametersMovie3.add(AttributeValue.N("2022"))
    parametersMovie3.add(AttributeValue.S("My Movie 3"))
    parametersMovie3.add(AttributeValue.S("No Information"))

    val statementRequestMovie3 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersMovie3
        }

    // Add all three movies to the list.
    val myBatchStatementList = mutableListOf<BatchStatementRequest>()
    myBatchStatementList.add(statementRequestMovie1)
    myBatchStatementList.add(statementRequestMovie2)
    myBatchStatementList.add(statementRequestMovie3)

    val batchRequest =
        BatchExecuteStatementRequest {
            statements = myBatchStatementList
        }
    val response = ddb.batchExecuteStatement(batchRequest)
    println("ExecuteStatement successful: " + response.toString())
    println("Added new movies using a batch command.")
}

suspend fun updateTableItemBatchBatch(ddb: DynamoDbClient) {
    val sqlStatement =
        "UPDATE MoviesPartiQBatch SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack' where year=? and title=?"
    val parametersRec1 = mutableListOf<AttributeValue>()
    parametersRec1.add(AttributeValue.N("2022"))
    parametersRec1.add(AttributeValue.S("My Movie 1"))
    val statementRequestRec1 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersRec1
        }

    // Update record 2.
    val parametersRec2 = mutableListOf<AttributeValue>()
    parametersRec2.add(AttributeValue.N("2022"))
    parametersRec2.add(AttributeValue.S("My Movie 2"))
    val statementRequestRec2 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersRec2
        }

    // Update record 3.
    val parametersRec3 = mutableListOf<AttributeValue>()
    parametersRec3.add(AttributeValue.N("2022"))
    parametersRec3.add(AttributeValue.S("My Movie 3"))
    val statementRequestRec3 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersRec3
        }

    // Add all three movies to the list.
    val myBatchStatementList = mutableListOf<BatchStatementRequest>()
    myBatchStatementList.add(statementRequestRec1)
    myBatchStatementList.add(statementRequestRec2)
    myBatchStatementList.add(statementRequestRec3)

    val batchRequest =
        BatchExecuteStatementRequest {
            statements = myBatchStatementList
        }

    val response = ddb.batchExecuteStatement(batchRequest)
    println("ExecuteStatement successful: $response")
    println("Updated three movies using a batch command.")
    println("Items were updated!")
}

suspend fun deleteItemsBatch(ddb: DynamoDbClient) {
    // Specify three records to delete.
    val sqlStatement = "DELETE FROM MoviesPartiQBatch WHERE year = ? and title=?"
    val parametersRec1 = mutableListOf<AttributeValue>()
    parametersRec1.add(AttributeValue.N("2022"))
    parametersRec1.add(AttributeValue.S("My Movie 1"))

    val statementRequestRec1 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersRec1
        }

    // Specify record 2.
    val parametersRec2 = mutableListOf<AttributeValue>()
    parametersRec2.add(AttributeValue.N("2022"))
    parametersRec2.add(AttributeValue.S("My Movie 2"))
    val statementRequestRec2 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersRec2
        }

    // Specify record 3.
    val parametersRec3 = mutableListOf<AttributeValue>()
    parametersRec3.add(AttributeValue.N("2022"))
    parametersRec3.add(AttributeValue.S("My Movie 3"))
    val statementRequestRec3 =
        BatchStatementRequest {
            statement = sqlStatement
            parameters = parametersRec3
        }

    // Add all three movies to the list.
    val myBatchStatementList = mutableListOf<BatchStatementRequest>()
    myBatchStatementList.add(statementRequestRec1)
    myBatchStatementList.add(statementRequestRec2)
    myBatchStatementList.add(statementRequestRec3)

    val batchRequest =
        BatchExecuteStatementRequest {
            statements = myBatchStatementList
        }

    ddb.batchExecuteStatement(batchRequest)
    println("Deleted three movies using a batch command.")
}

suspend fun deleteTablePartiQLBatch(tableNameVal: String) {
    val request =
        DeleteTableRequest {
            tableName = tableNameVal
        }

    DynamoDbClient { region = "us-east-1" }.use { ddb ->
        ddb.deleteTable(request)
        println("$tableNameVal was deleted")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[BatchExecuteStatement](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_kotlin_1_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
suspend fun main() {
    val ddb = DynamoDbClient.fromEnvironment { region = "us-east-1" }
    val tableName = "MoviesPartiQ"
    val fileName = "../../../resources/sample_files/movies.json"
    println("Creating an Amazon DynamoDB table named MoviesPartiQ with a key named id and a sort key named title.")
    createTablePartiQL(ddb, tableName, "year")
    loadDataPartiQL(ddb, fileName)

    println("******* Getting data from the MoviesPartiQ table.")
    getMoviePartiQL(ddb)

    println("******* Putting a record into the MoviesPartiQ table.")
    putRecordPartiQL(ddb)

    println("******* Updating a record.")
    updateTableItemPartiQL(ddb)

    println("******* Querying the movies released in 2013.")
    queryTablePartiQL(ddb)

    println("******* Deleting the MoviesPartiQ table.")
    deleteTablePartiQL(tableName)
}

suspend fun createTablePartiQL(
    ddb: DynamoDbClient,
    tableNameVal: String,
    key: String,
) {
    val attDef =
        AttributeDefinition {
            attributeName = key
            attributeType = ScalarAttributeType.N
        }

    val attDef1 =
        AttributeDefinition {
            attributeName = "title"
            attributeType = ScalarAttributeType.S
        }

    val keySchemaVal =
        KeySchemaElement {
            attributeName = key
            keyType = KeyType.Hash
        }

    val keySchemaVal1 =
        KeySchemaElement {
            attributeName = "title"
            keyType = KeyType.Range
        }

    val request =
        CreateTableRequest {
            attributeDefinitions = listOf(attDef, attDef1)
            keySchema = listOf(keySchemaVal, keySchemaVal1)
            billingMode = BillingMode.PayPerRequest
            tableName = tableNameVal
        }

    val response = ddb.createTable(request)
    ddb.waitUntilTableExists {
        // suspend call
        tableName = tableNameVal
    }
    println("The table was successfully created ${response.tableDescription?.tableArn}")
}

suspend fun loadDataPartiQL(
    ddb: DynamoDbClient,
    fileName: String,
) {
    val sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val iter: Iterator<JsonNode> = rootNode.iterator()
    var currentNode: ObjectNode
    var t = 0

    while (iter.hasNext()) {
        if (t == 200) {
            break
        }

        currentNode = iter.next() as ObjectNode
        val year = currentNode.path("year").asInt()
        val title = currentNode.path("title").asText()
        val info = currentNode.path("info").toString()

        val parameters: MutableList<AttributeValue> = ArrayList<AttributeValue>()
        parameters.add(AttributeValue.N(year.toString()))
        parameters.add(AttributeValue.S(title))
        parameters.add(AttributeValue.S(info))

        executeStatementPartiQL(ddb, sqlStatement, parameters)
        println("Added Movie $title")
        parameters.clear()
        t++
    }
}

suspend fun getMoviePartiQL(ddb: DynamoDbClient) {
    val sqlStatement = "SELECT * FROM MoviesPartiQ where year=? and title=?"
    val parameters: MutableList<AttributeValue> = ArrayList<AttributeValue>()
    parameters.add(AttributeValue.N("2012"))
    parameters.add(AttributeValue.S("The Perks of Being a Wallflower"))
    val response = executeStatementPartiQL(ddb, sqlStatement, parameters)
    println("ExecuteStatement successful: $response")
}

suspend fun putRecordPartiQL(ddb: DynamoDbClient) {
    val sqlStatement = "INSERT INTO MoviesPartiQ VALUE {'year':?, 'title' : ?, 'info' : ?}"
    val parameters: MutableList<AttributeValue> = java.util.ArrayList()
    parameters.add(AttributeValue.N("2020"))
    parameters.add(AttributeValue.S("My Movie"))
    parameters.add(AttributeValue.S("No Info"))
    executeStatementPartiQL(ddb, sqlStatement, parameters)
    println("Added new movie.")
}

suspend fun updateTableItemPartiQL(ddb: DynamoDbClient) {
    val sqlStatement = "UPDATE MoviesPartiQ SET info = 'directors\":[\"Merian C. Cooper\",\"Ernest B. Schoedsack\' where year=? and title=?"
    val parameters: MutableList<AttributeValue> = java.util.ArrayList()
    parameters.add(AttributeValue.N("2013"))
    parameters.add(AttributeValue.S("The East"))
    executeStatementPartiQL(ddb, sqlStatement, parameters)
    println("Item was updated!")
}

// Query the table where the year is 2013.
suspend fun queryTablePartiQL(ddb: DynamoDbClient) {
    val sqlStatement = "SELECT * FROM MoviesPartiQ where year = ?"
    val parameters: MutableList<AttributeValue> = java.util.ArrayList()
    parameters.add(AttributeValue.N("2013"))
    val response = executeStatementPartiQL(ddb, sqlStatement, parameters)
    println("ExecuteStatement successful: $response")
}

suspend fun deleteTablePartiQL(tableNameVal: String) {
    val request =
        DeleteTableRequest {
            tableName = tableNameVal
        }

    DynamoDbClient { region = "us-east-1" }.use { ddb ->
        ddb.deleteTable(request)
        println("$tableNameVal was deleted")
    }
}

suspend fun executeStatementPartiQL(
    ddb: DynamoDbClient,
    statementVal: String,
    parametersVal: List<AttributeValue>,
): ExecuteStatementResponse {
    val request =
        ExecuteStatementRequest {
            statement = statementVal
            parameters = parametersVal
        }

    return ddb.executeStatement(request)
}
```
+  API の詳細については、**「AWS SDK for Kotlin API リファレンス」の「[ExecuteStatement](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon EC2 の例
<a name="kotlin_1_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_kotlin_1_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeEC2SecurityGroups(groupId: String) {
    val request =
        DescribeSecurityGroupsRequest {
            groupIds = listOf(groupId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeSecurityGroups(request)
        response.securityGroups?.forEach { group ->
            println("Found Security Group with id ${group.groupId}, vpc id ${group.vpcId} and description ${group.description}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeSecurityGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
/**
 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

 This Kotlin example performs the following tasks:

 1. Creates an RSA key pair and saves the private key data as a .pem file.
 2. Lists key pairs.
 3. Creates a security group for the default VPC.
 4. Displays security group information.
 5. Gets a list of Amazon Linux 2 AMIs and selects one.
 6. Gets more information about the image.
 7. Gets a list of instance types that are compatible with the selected AMI’s architecture.
 8. Creates an instance with the key pair, security group, AMI, and an instance type.
 9. Displays information about the instance.
 10. Stops the instance and waits for it to stop.
 11. Starts the instance and waits for it to start.
 12. Allocates an Elastic IP address and associates it with the instance.
 13. Displays SSH connection info for the instance.
 14. Disassociates and deletes the Elastic IP address.
 15. Terminates the instance.
 16. Deletes the security group.
 17. Deletes the key pair.
 */

val DASHES = String(CharArray(80)).replace("\u0000", "-")

suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <keyName> <fileName> <groupName> <groupDesc> <vpcId> <myIpAddress>

        Where:
            keyName - A key pair name (for example, TestKeyPair). 
            fileName - A file name where the key information is written to. 
            groupName - The name of the security group. 
            groupDesc - The description of the security group. 
            vpcId - A VPC ID. You can get this value from the AWS Management Console. 
            myIpAddress - The IP address of your development machine. 

"""

    if (args.size != 6) {
        println(usage)
        exitProcess(0)
    }

    val keyName = args[0]
    val fileName = args[1]
    val groupName = args[2]
    val groupDesc = args[3]
    val vpcId = args[4]
    val myIpAddress = args[5]
    var newInstanceId: String? = ""

    println(DASHES)
    println("Welcome to the Amazon EC2 example scenario.")
    println(DASHES)

    println(DASHES)
    println("1. Create an RSA key pair and save the private key material as a .pem file.")
    createKeyPairSc(keyName, fileName)
    println(DASHES)

    println(DASHES)
    println("2. List key pairs.")
    describeEC2KeysSc()
    println(DASHES)

    println(DASHES)
    println("3. Create a security group.")
    val groupId = createEC2SecurityGroupSc(groupName, groupDesc, vpcId, myIpAddress)
    println(DASHES)

    println(DASHES)
    println("4. Display security group info for the newly created security group.")
    describeSecurityGroupsSc(groupId.toString())
    println(DASHES)

    println(DASHES)
    println("5. Get a list of Amazon Linux 2 AMIs and select one with amzn2 in the name.")
    val instanceId = getParaValuesSc()
    if (instanceId == "") {
        println("The instance Id value isn't valid.")
        exitProcess(0)
    }
    println("The instance Id is $instanceId.")
    println(DASHES)

    println(DASHES)
    println("6. Get more information about an amzn2 image and return the AMI value.")
    val amiValue = instanceId?.let { describeImageSc(it) }
    if (instanceId == "") {
        println("The instance Id value is invalid.")
        exitProcess(0)
    }
    println("The AMI value is $amiValue.")
    println(DASHES)

    println(DASHES)
    println("7. Get a list of instance types.")
    val instanceType = getInstanceTypesSc()
    println(DASHES)

    println(DASHES)
    println("8. Create an instance.")
    if (amiValue != null) {
        newInstanceId = runInstanceSc(instanceType, keyName, groupName, amiValue)
        println("The instance Id is $newInstanceId")
    }
    println(DASHES)

    println(DASHES)
    println("9. Display information about the running instance. ")
    var ipAddress = describeEC2InstancesSc(newInstanceId)
    println("You can SSH to the instance using this command:")
    println("ssh -i " + fileName + "ec2-user@" + ipAddress)
    println(DASHES)

    println(DASHES)
    println("10.  Stop the instance.")
    if (newInstanceId != null) {
        stopInstanceSc(newInstanceId)
    }
    println(DASHES)

    println(DASHES)
    println("11.  Start the instance.")
    if (newInstanceId != null) {
        startInstanceSc(newInstanceId)
    }
    ipAddress = describeEC2InstancesSc(newInstanceId)
    println("You can SSH to the instance using this command:")
    println("ssh -i " + fileName + "ec2-user@" + ipAddress)
    println(DASHES)

    println(DASHES)
    println("12. Allocate an Elastic IP address and associate it with the instance.")
    val allocationId = allocateAddressSc()
    println("The allocation Id value is $allocationId")
    val associationId = associateAddressSc(newInstanceId, allocationId)
    println("The associate Id value is $associationId")
    println(DASHES)

    println(DASHES)
    println("13. Describe the instance again.")
    ipAddress = describeEC2InstancesSc(newInstanceId)
    println("You can SSH to the instance using this command:")
    println("ssh -i " + fileName + "ec2-user@" + ipAddress)
    println(DASHES)

    println(DASHES)
    println("14. Disassociate and release the Elastic IP address.")
    disassociateAddressSc(associationId)
    releaseEC2AddressSc(allocationId)
    println(DASHES)

    println(DASHES)
    println("15. Terminate the instance and use a waiter.")
    if (newInstanceId != null) {
        terminateEC2Sc(newInstanceId)
    }
    println(DASHES)

    println(DASHES)
    println("16. Delete the security group.")
    if (groupId != null) {
        deleteEC2SecGroupSc(groupId)
    }
    println(DASHES)

    println(DASHES)
    println("17. Delete the key pair.")
    deleteKeysSc(keyName)
    println(DASHES)

    println(DASHES)
    println("You successfully completed the Amazon EC2 scenario.")
    println(DASHES)
}

suspend fun deleteKeysSc(keyPair: String) {
    val request =
        DeleteKeyPairRequest {
            keyName = keyPair
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.deleteKeyPair(request)
        println("Successfully deleted key pair named $keyPair")
    }
}

suspend fun deleteEC2SecGroupSc(groupIdVal: String) {
    val request =
        DeleteSecurityGroupRequest {
            groupId = groupIdVal
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.deleteSecurityGroup(request)
        println("Successfully deleted security group with Id $groupIdVal")
    }
}

suspend fun terminateEC2Sc(instanceIdVal: String) {
    val ti =
        TerminateInstancesRequest {
            instanceIds = listOf(instanceIdVal)
        }
    println("Wait for the instance to terminate. This will take a few minutes.")
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.terminateInstances(ti)
        ec2.waitUntilInstanceTerminated {
            // suspend call
            instanceIds = listOf(instanceIdVal)
        }
        println("$instanceIdVal is terminated!")
    }
}

suspend fun releaseEC2AddressSc(allocId: String?) {
    val request =
        ReleaseAddressRequest {
            allocationId = allocId
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.releaseAddress(request)
        println("Successfully released Elastic IP address $allocId")
    }
}

suspend fun disassociateAddressSc(associationIdVal: String?) {
    val addressRequest =
        DisassociateAddressRequest {
            associationId = associationIdVal
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.disassociateAddress(addressRequest)
        println("You successfully disassociated the address!")
    }
}

suspend fun associateAddressSc(
    instanceIdVal: String?,
    allocationIdVal: String?,
): String? {
    val associateRequest =
        AssociateAddressRequest {
            instanceId = instanceIdVal
            allocationId = allocationIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val associateResponse = ec2.associateAddress(associateRequest)
        return associateResponse.associationId
    }
}

suspend fun allocateAddressSc(): String? {
    val allocateRequest =
        AllocateAddressRequest {
            domain = DomainType.Vpc
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val allocateResponse = ec2.allocateAddress(allocateRequest)
        return allocateResponse.allocationId
    }
}

suspend fun startInstanceSc(instanceId: String) {
    val request =
        StartInstancesRequest {
            instanceIds = listOf(instanceId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.startInstances(request)
        println("Waiting until instance $instanceId starts. This will take a few minutes.")
        ec2.waitUntilInstanceRunning {
            // suspend call
            instanceIds = listOf(instanceId)
        }
        println("Successfully started instance $instanceId")
    }
}

suspend fun stopInstanceSc(instanceId: String) {
    val request =
        StopInstancesRequest {
            instanceIds = listOf(instanceId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.stopInstances(request)
        println("Waiting until instance $instanceId stops. This will take a few minutes.")
        ec2.waitUntilInstanceStopped {
            // suspend call
            instanceIds = listOf(instanceId)
        }
        println("Successfully stopped instance $instanceId")
    }
}

suspend fun describeEC2InstancesSc(newInstanceId: String?): String {
    var pubAddress = ""
    var isRunning = false
    val request =
        DescribeInstancesRequest {
            instanceIds = listOf(newInstanceId.toString())
        }

    while (!isRunning) {
        Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
            val response = ec2.describeInstances(request)
            val state =
                response.reservations
                    ?.get(0)
                    ?.instances
                    ?.get(0)
                    ?.state
                    ?.name
                    ?. value
            if (state != null) {
                if (state.compareTo("running") == 0) {
                    println("Image id is ${response.reservations!!.get(0).instances?.get(0)?.imageId}")
                    println("Instance type is ${response.reservations!!.get(0).instances?.get(0)?.instanceType}")
                    println("Instance state is ${response.reservations!!.get(0).instances?.get(0)?.state}")
                    pubAddress =
                        response.reservations!!
                            .get(0)
                            .instances
                            ?.get(0)
                            ?.publicIpAddress
                            .toString()
                    println("Instance address is $pubAddress")
                    isRunning = true
                }
            }
        }
    }
    return pubAddress
}

suspend fun runInstanceSc(
    instanceTypeVal: String,
    keyNameVal: String,
    groupNameVal: String,
    amiIdVal: String,
): String {
    val runRequest =
        RunInstancesRequest {
            instanceType = InstanceType.fromValue(instanceTypeVal)
            keyName = keyNameVal
            securityGroups = listOf(groupNameVal)
            maxCount = 1
            minCount = 1
            imageId = amiIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.runInstances(runRequest)
        val instanceId = response.instances?.get(0)?.instanceId
        println("Successfully started EC2 Instance $instanceId based on AMI $amiIdVal")
        return instanceId.toString()
    }
}

// Get a list of instance types.
suspend fun getInstanceTypesSc(): String {
    var instanceType = ""
    val filterObs = ArrayList<Filter>()
    val filter =
        Filter {
            name = "processor-info.supported-architecture"
            values = listOf("arm64")
        }

    filterObs.add(filter)
    val typesRequest =
        DescribeInstanceTypesRequest {
            filters = filterObs
            maxResults = 10
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeInstanceTypes(typesRequest)
        response.instanceTypes?.forEach { type ->
            println("The memory information of this type is ${type.memoryInfo?.sizeInMib}")
            println("Maximum number of network cards is ${type.networkInfo?.maximumNetworkCards}")
            instanceType = type.instanceType.toString()
        }
        return instanceType
    }
}

// Display the Description field that corresponds to the instance Id value.
suspend fun describeImageSc(instanceId: String): String? {
    val imagesRequest =
        DescribeImagesRequest {
            imageIds = listOf(instanceId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeImages(imagesRequest)
        println("The description of the first image is ${response.images?.get(0)?.description}")
        println("The name of the first image is  ${response.images?.get(0)?.name}")

        // Return the image Id value.
        return response.images?.get(0)?.imageId
    }
}

// Get the Id value of an instance with amzn2 in the name.
suspend fun getParaValuesSc(): String? {
    val parameterRequest =
        GetParametersByPathRequest {
            path = "/aws/service/ami-amazon-linux-latest"
        }

    SsmClient.fromEnvironment { region = "us-west-2" }.use { ssmClient ->
        val response = ssmClient.getParametersByPath(parameterRequest)
        response.parameters?.forEach { para ->
            println("The name of the para is: ${para.name}")
            println("The type of the para is: ${para.type}")
            println("")
            if (para.name?.let { filterName(it) } == true) {
                return para.value
            }
        }
    }
    return ""
}

fun filterName(name: String): Boolean {
    val parts = name.split("/").toTypedArray()
    val myValue = parts[4]
    return myValue.contains("amzn2")
}

suspend fun describeSecurityGroupsSc(groupId: String) {
    val request =
        DescribeSecurityGroupsRequest {
            groupIds = listOf(groupId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeSecurityGroups(request)
        for (group in response.securityGroups!!) {
            println("Found Security Group with id " + group.groupId.toString() + " and group VPC " + group.vpcId)
        }
    }
}

suspend fun createEC2SecurityGroupSc(
    groupNameVal: String?,
    groupDescVal: String?,
    vpcIdVal: String?,
    myIpAddress: String?,
): String? {
    val request =
        CreateSecurityGroupRequest {
            groupName = groupNameVal
            description = groupDescVal
            vpcId = vpcIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val resp = ec2.createSecurityGroup(request)
        val ipRange =
            IpRange {
                cidrIp = "$myIpAddress/0"
            }

        val ipPerm =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 80
                fromPort = 80
                ipRanges = listOf(ipRange)
            }

        val ipPerm2 =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 22
                fromPort = 22
                ipRanges = listOf(ipRange)
            }

        val authRequest =
            AuthorizeSecurityGroupIngressRequest {
                groupName = groupNameVal
                ipPermissions = listOf(ipPerm, ipPerm2)
            }
        ec2.authorizeSecurityGroupIngress(authRequest)
        println("Successfully added ingress policy to Security Group $groupNameVal")
        return resp.groupId
    }
}

suspend fun describeEC2KeysSc() {
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeKeyPairs(DescribeKeyPairsRequest {})
        response.keyPairs?.forEach { keyPair ->
            println("Found key pair with name ${keyPair.keyName} and fingerprint ${ keyPair.keyFingerprint}")
        }
    }
}

suspend fun createKeyPairSc(
    keyNameVal: String,
    fileNameVal: String,
) {
    val request =
        CreateKeyPairRequest {
            keyName = keyNameVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.createKeyPair(request)
        val content = response.keyMaterial
        if (content != null) {
            File(fileNameVal).writeText(content)
        }
        println("Successfully created key pair named $keyNameVal")
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [AllocateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [AssociateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [AuthorizeSecurityGroupIngress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateKeyPair](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateSecurityGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteKeyPair](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteSecurityGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeImages](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeInstanceTypes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeKeyPairs](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeSecurityGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DisassociateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ReleaseAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [RunInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StopInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [TerminateInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UnmonitorInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_kotlin_1_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getAllocateAddress(instanceIdVal: String?): String? {
    val allocateRequest =
        AllocateAddressRequest {
            domain = DomainType.Vpc
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val allocateResponse = ec2.allocateAddress(allocateRequest)
        val allocationIdVal = allocateResponse.allocationId

        val request =
            AssociateAddressRequest {
                instanceId = instanceIdVal
                allocationId = allocationIdVal
            }

        val associateResponse = ec2.associateAddress(request)
        return associateResponse.associationId
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[AllocateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_kotlin_1_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun associateAddressSc(
    instanceIdVal: String?,
    allocationIdVal: String?,
): String? {
    val associateRequest =
        AssociateAddressRequest {
            instanceId = instanceIdVal
            allocationId = allocationIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val associateResponse = ec2.associateAddress(associateRequest)
        return associateResponse.associationId
    }
}
```
+  API の詳細については、「*AWS  SDK for Kotlin API リファレンス*」の「[AssociateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_kotlin_1_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createEC2SecurityGroupSc(
    groupNameVal: String?,
    groupDescVal: String?,
    vpcIdVal: String?,
    myIpAddress: String?,
): String? {
    val request =
        CreateSecurityGroupRequest {
            groupName = groupNameVal
            description = groupDescVal
            vpcId = vpcIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val resp = ec2.createSecurityGroup(request)
        val ipRange =
            IpRange {
                cidrIp = "$myIpAddress/0"
            }

        val ipPerm =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 80
                fromPort = 80
                ipRanges = listOf(ipRange)
            }

        val ipPerm2 =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 22
                fromPort = 22
                ipRanges = listOf(ipRange)
            }

        val authRequest =
            AuthorizeSecurityGroupIngressRequest {
                groupName = groupNameVal
                ipPermissions = listOf(ipPerm, ipPerm2)
            }
        ec2.authorizeSecurityGroupIngress(authRequest)
        println("Successfully added ingress policy to Security Group $groupNameVal")
        return resp.groupId
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[AuthorizeSecurityGroupIngress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_kotlin_1_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createEC2KeyPair(keyNameVal: String) {
    val request =
        CreateKeyPairRequest {
            keyName = keyNameVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.createKeyPair(request)
        println("The key ID is ${response.keyPairId}")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateKeyPair](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_kotlin_1_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createEC2SecurityGroup(
    groupNameVal: String?,
    groupDescVal: String?,
    vpcIdVal: String?,
): String? {
    val request =
        CreateSecurityGroupRequest {
            groupName = groupNameVal
            description = groupDescVal
            vpcId = vpcIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val resp = ec2.createSecurityGroup(request)
        val ipRange =
            IpRange {
                cidrIp = "0.0.0.0/0"
            }

        val ipPerm =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 80
                fromPort = 80
                ipRanges = listOf(ipRange)
            }

        val ipPerm2 =
            IpPermission {
                ipProtocol = "tcp"
                toPort = 22
                fromPort = 22
                ipRanges = listOf(ipRange)
            }

        val authRequest =
            AuthorizeSecurityGroupIngressRequest {
                groupName = groupNameVal
                ipPermissions = listOf(ipPerm, ipPerm2)
            }
        ec2.authorizeSecurityGroupIngress(authRequest)
        println("Successfully added ingress policy to Security Group $groupNameVal")
        return resp.groupId
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateSecurityGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_kotlin_1_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteKeys(keyPair: String?) {
    val request =
        DeleteKeyPairRequest {
            keyName = keyPair
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.deleteKeyPair(request)
        println("Successfully deleted key pair named $keyPair")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteKeyPair](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_kotlin_1_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteEC2SecGroup(groupIdVal: String) {
    val request =
        DeleteSecurityGroupRequest {
            groupId = groupIdVal
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.deleteSecurityGroup(request)
        println("Successfully deleted Security Group with id $groupIdVal")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteSecurityGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_kotlin_1_topic"></a>

次のコード例は、`DescribeInstanceTypes` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
// Get a list of instance types.
suspend fun getInstanceTypesSc(): String {
    var instanceType = ""
    val filterObs = ArrayList<Filter>()
    val filter =
        Filter {
            name = "processor-info.supported-architecture"
            values = listOf("arm64")
        }

    filterObs.add(filter)
    val typesRequest =
        DescribeInstanceTypesRequest {
            filters = filterObs
            maxResults = 10
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeInstanceTypes(typesRequest)
        response.instanceTypes?.forEach { type ->
            println("The memory information of this type is ${type.memoryInfo?.sizeInMib}")
            println("Maximum number of network cards is ${type.networkInfo?.maximumNetworkCards}")
            instanceType = type.instanceType.toString()
        }
        return instanceType
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeInstanceTypes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_kotlin_1_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeEC2Instances() {
    val request =
        DescribeInstancesRequest {
            maxResults = 6
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeInstances(request)
        response.reservations?.forEach { reservation ->
            reservation.instances?.forEach { instance ->
                println("Instance Id is ${instance.instanceId}")
                println("Image id is ${instance.imageId}")
                println("Instance type is ${instance.instanceType}")
                println("Instance state name is ${instance.state?.name}")
                println("monitoring information is ${instance.monitoring?.state}")
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_kotlin_1_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeEC2Keys() {
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeKeyPairs(DescribeKeyPairsRequest {})
        response.keyPairs?.forEach { keyPair ->
            println("Found key pair with name ${keyPair.keyName} and fingerprint ${ keyPair.keyFingerprint}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeKeyPairs](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_kotlin_1_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeEC2SecurityGroups(groupId: String) {
    val request =
        DescribeSecurityGroupsRequest {
            groupIds = listOf(groupId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.describeSecurityGroups(request)
        response.securityGroups?.forEach { group ->
            println("Found Security Group with id ${group.groupId}, vpc id ${group.vpcId} and description ${group.description}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeSecurityGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_kotlin_1_topic"></a>

次のコード例は、`DisassociateAddress` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun disassociateAddressSc(associationIdVal: String?) {
    val addressRequest =
        DisassociateAddressRequest {
            associationId = associationIdVal
        }
    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.disassociateAddress(addressRequest)
        println("You successfully disassociated the address!")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DisassociateAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_kotlin_1_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun releaseEC2AddressSc(allocId: String?) {
    val request =
        ReleaseAddressRequest {
            allocationId = allocId
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.releaseAddress(request)
        println("Successfully released Elastic IP address $allocId")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ReleaseAddress](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_kotlin_1_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createEC2Instance(
    name: String,
    amiId: String,
): String? {
    val request =
        RunInstancesRequest {
            imageId = amiId
            instanceType = InstanceType.T1Micro
            maxCount = 1
            minCount = 1
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.runInstances(request)
        val instanceId = response.instances?.get(0)?.instanceId
        val tag =
            Tag {
                key = "Name"
                value = name
            }

        val requestTags =
            CreateTagsRequest {
                resources = listOf(instanceId.toString())
                tags = listOf(tag)
            }
        ec2.createTags(requestTags)
        println("Successfully started EC2 Instance $instanceId based on AMI $amiId")
        return instanceId
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[RunInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_kotlin_1_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun startInstanceSc(instanceId: String) {
    val request =
        StartInstancesRequest {
            instanceIds = listOf(instanceId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.startInstances(request)
        println("Waiting until instance $instanceId starts. This will take a few minutes.")
        ec2.waitUntilInstanceRunning {
            // suspend call
            instanceIds = listOf(instanceId)
        }
        println("Successfully started instance $instanceId")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[StartInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_kotlin_1_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun stopInstanceSc(instanceId: String) {
    val request =
        StopInstancesRequest {
            instanceIds = listOf(instanceId)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        ec2.stopInstances(request)
        println("Waiting until instance $instanceId stops. This will take a few minutes.")
        ec2.waitUntilInstanceStopped {
            // suspend call
            instanceIds = listOf(instanceId)
        }
        println("Successfully stopped instance $instanceId")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[StopInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_kotlin_1_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
suspend fun terminateEC2(instanceID: String) {
    val request =
        TerminateInstancesRequest {
            instanceIds = listOf(instanceID)
        }

    Ec2Client.fromEnvironment { region = "us-west-2" }.use { ec2 ->
        val response = ec2.terminateInstances(request)
        response.terminatingInstances?.forEach { instance ->
            println("The ID of the terminated instance is ${instance.instanceId}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[TerminateInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon ECR の例
<a name="kotlin_1_ecr_code_examples"></a>

次のコード例は、Amazon ECR で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon ECR
<a name="ecr_Hello_kotlin_1_topic"></a>

次のコード例は、Amazon ECR の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.ecr.EcrClient
import aws.sdk.kotlin.services.ecr.model.ListImagesRequest
import kotlin.system.exitProcess

suspend fun main(args: Array<String>) {
    val usage = """
            Usage: <repositoryName> 

            Where:
               repositoryName - The name of the Amazon ECR repository. 
            
    """.trimIndent()

    if (args.size != 1) {
        println(usage)
        exitProcess(1)
    }

    val repoName = args[0]
    listImageTags(repoName)
}

suspend fun listImageTags(repoName: String?) {
    val listImages =
        ListImagesRequest {
            repositoryName = repoName
        }

    EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
        val imageResponse = ecrClient.listImages(listImages)
        imageResponse.imageIds?.forEach { imageId ->
            println("Image tag: ${imageId.imageTag}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[listImages](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ecr_Scenario_RepositoryManagement_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon ECR リポジトリを作成します。
+ リポジトリポリシーを設定します。
+ リポジトリ URI を取得します。
+ Amazon ECR 認可トークンを取得します。
+ Amazon ECR リポジトリのライフサイクルポリシーを設定します。
+ Docker イメージを Amazon ECR リポジトリにプッシュします。
+ Amazon ECR リポジトリにイメージが存在しているか確認します。
+ アカウントの Amazon ECR リポジトリをリストし、その詳細を取得します。
+ Amazon ECR リポジトリを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。
Amazon ECR 機能を示すインタラクティブなシナリオを実行します。  

```
import java.util.Scanner

/**
 * Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 *
 * This code example requires an IAM Role that has permissions to interact with the Amazon ECR service.
 *
 * To create an IAM role, see:
 *
 * https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html
 *
 * This code example requires a local docker image named echo-text. Without a local image,
 * this program will not successfully run. For more information including how to create the local
 * image, see:
 *
 * /scenarios/basics/ecr/README
 *
 */

val DASHES = String(CharArray(80)).replace("\u0000", "-")

suspend fun main(args: Array<String>) {
    val usage =
        """
        Usage: <iamRoleARN> <accountId>

        Where:
           iamRoleARN - The IAM role ARN that has the necessary permissions to access and manage the Amazon ECR repository.
           accountId - Your AWS account number. 
        
        """.trimIndent()

    if (args.size != 2) {
        println(usage)
        return
    }

    var iamRole = args[0]
    var localImageName: String
    var accountId = args[1]
    val ecrActions = ECRActions()
    val scanner = Scanner(System.`in`)

    println(
        """
        The Amazon Elastic Container Registry (ECR) is a fully-managed Docker container registry 
        service provided by AWS. It allows developers and organizations to securely 
        store, manage, and deploy Docker container images. 
        ECR provides a simple and scalable way to manage container images throughout their lifecycle, 
        from building and testing to production deployment. 
                        
        The `EcrClient` service client that is part of the AWS SDK for Kotlin provides a set of methods to 
        programmatically interact with the Amazon ECR service. This allows developers to 
        automate the storage, retrieval, and management of container images as part of their application 
        deployment pipelines. With ECR, teams can focus on building and deploying their 
        applications without having to worry about the underlying infrastructure required to 
        host and manage a container registry.
            
        This scenario walks you through how to perform key operations for this service.  
        Let's get started...
        
         You have two choices:
            1 - Run the entire program.
            2 - Delete an existing Amazon ECR repository named echo-text (created from a previous execution of 
            this program that did not complete).
          
        """.trimIndent(),
    )

    while (true) {
        val input = scanner.nextLine()
        if (input.trim { it <= ' ' }.equals("1", ignoreCase = true)) {
            println("Continuing with the program...")
            println("")
            break
        } else if (input.trim { it <= ' ' }.equals("2", ignoreCase = true)) {
            val repoName = "echo-text"
            ecrActions.deleteECRRepository(repoName)
            return
        } else {
            // Handle invalid input.
            println("Invalid input. Please try again.")
        }
    }

    waitForInputToContinue(scanner)
    println(DASHES)
    println(
        """
        1. Create an ECR repository.
         
        The first task is to ensure we have a local Docker image named echo-text. 
        If this image exists, then an Amazon ECR repository is created. 
        
        An ECR repository is a private Docker container repository provided 
        by Amazon Web Services (AWS). It is a managed service that makes it easy 
        to store, manage, and deploy Docker container images. 
        
        """.trimIndent(),
    )

    // Ensure that a local docker image named echo-text exists.
    val doesExist = ecrActions.listLocalImages()
    val repoName: String
    if (!doesExist) {
        println("The local image named echo-text does not exist")
        return
    } else {
        localImageName = "echo-text"
        repoName = "echo-text"
    }

    val repoArn = ecrActions.createECRRepository(repoName).toString()
    println("The ARN of the ECR repository is $repoArn")
    waitForInputToContinue(scanner)

    println(DASHES)
    println(
        """
        2. Set an ECR repository policy.
        
        Setting an ECR repository policy using the `setRepositoryPolicy` function is crucial for maintaining
        the security and integrity of your container images. The repository policy allows you to 
        define specific rules and restrictions for accessing and managing the images stored within your ECR 
        repository.    
        
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    ecrActions.setRepoPolicy(repoName, iamRole)
    waitForInputToContinue(scanner)

    println(DASHES)
    println(
        """
        3. Display ECR repository policy.
        
        Now we will retrieve the ECR policy to ensure it was successfully set.   
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    val policyText = ecrActions.getRepoPolicy(repoName)
    println("Policy Text:")
    println(policyText)
    waitForInputToContinue(scanner)

    println(DASHES)
    println(
        """
        4. Retrieve an ECR authorization token.
        
        You need an authorization token to securely access and interact with the Amazon ECR registry. 
        The `getAuthorizationToken` method of the `EcrAsyncClient` is responsible for securely accessing 
        and interacting with an Amazon ECR repository. This operation is responsible for obtaining a 
        valid authorization token, which is required to authenticate your requests to the ECR service. 
        
        Without a valid authorization token, you would not be able to perform any operations on the 
        ECR repository, such as pushing, pulling, or managing your Docker images.    
        
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    ecrActions.getAuthToken()
    waitForInputToContinue(scanner)

    println(DASHES)
    println(
        """
        5. Get the ECR Repository URI.
                    
        The URI  of an Amazon ECR repository is important. When you want to deploy a container image to 
        a container orchestration platform like Amazon Elastic Kubernetes Service (EKS) 
        or Amazon Elastic Container Service (ECS), you need to specify the full image URI, 
        which includes the ECR repository URI. This allows the container runtime to pull the 
        correct container image from the ECR repository.    
        
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    val repositoryURI: String? = ecrActions.getRepositoryURI(repoName)
    println("The repository URI is $repositoryURI")
    waitForInputToContinue(scanner)

    println(DASHES)
    println(
        """
        6. Set an ECR Lifecycle Policy.
                    
        An ECR Lifecycle Policy is used to manage the lifecycle of Docker images stored in your ECR repositories. 
        These policies allow you to automatically remove old or unused Docker images from your repositories, 
        freeing up storage space and reducing costs.    
        
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    val pol = ecrActions.setLifeCyclePolicy(repoName)
    println(pol)
    waitForInputToContinue(scanner)

    println(DASHES)
    println(
        """
        7. Push a docker image to the Amazon ECR Repository.
            
        The `pushImageCmd()` method pushes a local Docker image to an Amazon ECR repository.
        It sets up the Docker client by connecting to the local Docker host using the default port.
        It then retrieves the authorization token for the ECR repository by making a call to the AWS SDK.
            
        The method uses the authorization token to create an `AuthConfig` object, which is used to authenticate
        the Docker client when pushing the image. Finally, the method tags the Docker image with the specified
        repository name and image tag, and then pushes the image to the ECR repository using the Docker client.
        If the push operation is successful, the method prints a message indicating that the image was pushed to ECR.
        
        """.trimIndent(),
    )

    waitForInputToContinue(scanner)
    ecrActions.pushDockerImage(repoName, localImageName)
    waitForInputToContinue(scanner)

    println(DASHES)
    println("8. Verify if the image is in the ECR Repository.")
    waitForInputToContinue(scanner)
    ecrActions.verifyImage(repoName, localImageName)
    waitForInputToContinue(scanner)

    println(DASHES)
    println("9. As an optional step, you can interact with the image in Amazon ECR by using the CLI.")
    println("Would you like to view instructions on how to use the CLI to run the image? (y/n)")
    val ans = scanner.nextLine().trim()
    if (ans.equals("y", true)) {
        val instructions = """
        1. Authenticate with ECR - Before you can pull the image from Amazon ECR, you need to authenticate with the registry. You can do this using the AWS CLI:
        
            aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin $accountId.dkr.ecr.us-east-1.amazonaws.com
        
        2. Describe the image using this command:
        
           aws ecr describe-images --repository-name $repoName --image-ids imageTag=$localImageName
        
        3. Run the Docker container and view the output using this command:
        
           docker run --rm $accountId.dkr.ecr.us-east-1.amazonaws.com/$repoName:$localImageName
        """
        println(instructions)
    }
    waitForInputToContinue(scanner)

    println(DASHES)
    println("10. Delete the ECR Repository.")
    println(
        """
        If the repository isn't empty, you must either delete the contents of the repository 
        or use the force option (used in this scenario) to delete the repository and have Amazon ECR delete all of its contents 
        on your behalf.
        
        """.trimIndent(),
    )
    println("Would you like to delete the Amazon ECR Repository? (y/n)")
    val delAns = scanner.nextLine().trim { it <= ' ' }
    if (delAns.equals("y", ignoreCase = true)) {
        println("You selected to delete the AWS ECR resources.")
        waitForInputToContinue(scanner)
        ecrActions.deleteECRRepository(repoName)
    }

    println(DASHES)
    println("This concludes the Amazon ECR SDK scenario")
    println(DASHES)
}

private fun waitForInputToContinue(scanner: Scanner) {
    while (true) {
        println("")
        println("Enter 'c' followed by <ENTER> to continue:")
        val input = scanner.nextLine()
        if (input.trim { it <= ' ' }.equals("c", ignoreCase = true)) {
            println("Continuing with the program...")
            println("")
            break
        } else {
            // Handle invalid input.
            println("Invalid input. Please try again.")
        }
    }
}
```
Amazon ECR SDK メソッドのラッパークラス。  

```
import aws.sdk.kotlin.services.ecr.EcrClient
import aws.sdk.kotlin.services.ecr.model.CreateRepositoryRequest
import aws.sdk.kotlin.services.ecr.model.DeleteRepositoryRequest
import aws.sdk.kotlin.services.ecr.model.DescribeImagesRequest
import aws.sdk.kotlin.services.ecr.model.DescribeRepositoriesRequest
import aws.sdk.kotlin.services.ecr.model.EcrException
import aws.sdk.kotlin.services.ecr.model.GetRepositoryPolicyRequest
import aws.sdk.kotlin.services.ecr.model.ImageIdentifier
import aws.sdk.kotlin.services.ecr.model.RepositoryAlreadyExistsException
import aws.sdk.kotlin.services.ecr.model.SetRepositoryPolicyRequest
import aws.sdk.kotlin.services.ecr.model.StartLifecyclePolicyPreviewRequest
import com.github.dockerjava.api.DockerClient
import com.github.dockerjava.api.command.DockerCmdExecFactory
import com.github.dockerjava.api.model.AuthConfig
import com.github.dockerjava.core.DockerClientBuilder
import com.github.dockerjava.netty.NettyDockerCmdExecFactory
import java.io.IOException
import java.util.Base64

class ECRActions {
    private var dockerClient: DockerClient? = null

    private fun getDockerClient(): DockerClient? {
        val osName = System.getProperty("os.name")
        if (osName.startsWith("Windows")) {
            // Make sure Docker Desktop is running.
            val dockerHost = "tcp://localhost:2375" // Use the Docker Desktop default port.
            val dockerCmdExecFactory: DockerCmdExecFactory =
                NettyDockerCmdExecFactory().withReadTimeout(20000).withConnectTimeout(20000)
            dockerClient = DockerClientBuilder.getInstance(dockerHost).withDockerCmdExecFactory(dockerCmdExecFactory).build()
        } else {
            dockerClient = DockerClientBuilder.getInstance().build()
        }
        return dockerClient
    }


    /**
     * Sets the lifecycle policy for the specified repository.
     *
     * @param repoName the name of the repository for which to set the lifecycle policy.
     */
    suspend fun setLifeCyclePolicy(repoName: String): String? {
        val polText =
            """
             {
             "rules": [
                 {
                     "rulePriority": 1,
                     "description": "Expire images older than 14 days",
                     "selection": {
                         "tagStatus": "any",
                         "countType": "sinceImagePushed",
                         "countUnit": "days",
                         "countNumber": 14
                     },
                     "action": {
                         "type": "expire"
                     }
                 }
            ]
            }
            
            """.trimIndent()
        val lifecyclePolicyPreviewRequest =
            StartLifecyclePolicyPreviewRequest {
                lifecyclePolicyText = polText
                repositoryName = repoName
            }

        // Execute the request asynchronously.
        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val response = ecrClient.startLifecyclePolicyPreview(lifecyclePolicyPreviewRequest)
            return response.lifecyclePolicyText
        }
    }


    /**
     * Retrieves the repository URI for the specified repository name.
     *
     * @param repoName the name of the repository to retrieve the URI for.
     * @return the repository URI for the specified repository name.
     */
    suspend fun getRepositoryURI(repoName: String?): String? {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }
        val request =
            DescribeRepositoriesRequest {
                repositoryNames = listOf(repoName)
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val describeRepositoriesResponse = ecrClient.describeRepositories(request)
            if (!describeRepositoriesResponse.repositories?.isEmpty()!!) {
                return describeRepositoriesResponse?.repositories?.get(0)?.repositoryUri
            } else {
                println("No repositories found for the given name.")
                return ""
            }
        }
    }


    /**
     * Retrieves the authorization token for Amazon Elastic Container Registry (ECR).
     *
     */
    suspend fun getAuthToken() {
        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            // Retrieve the authorization token for ECR.
            val response = ecrClient.getAuthorizationToken()
            val authorizationData = response.authorizationData?.get(0)
            val token = authorizationData?.authorizationToken
            if (token != null) {
                println("The token was successfully retrieved.")
            }
        }
    }


    /**
     * Gets the repository policy for the specified repository.
     *
     * @param repoName the name of the repository.
     */
    suspend fun getRepoPolicy(repoName: String?): String? {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }

        // Create the request
        val getRepositoryPolicyRequest =
            GetRepositoryPolicyRequest {
                repositoryName = repoName
            }
        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val response = ecrClient.getRepositoryPolicy(getRepositoryPolicyRequest)
            val responseText = response.policyText
            return responseText
        }
    }


    /**
     * Sets the repository policy for the specified ECR repository.
     *
     * @param repoName the name of the ECR repository.
     * @param iamRole the IAM role to be granted access to the repository.
     */
    suspend fun setRepoPolicy(
        repoName: String?,
        iamRole: String?,
    ) {
        val policyDocumentTemplate =
            """
             {
              "Version":"2012-10-17",		 	 	 
              "Statement" : [ {
                "Sid" : "new statement",
                "Effect" : "Allow",
                "Principal" : {
                  "AWS" : "$iamRole"
                },
                "Action" : "ecr:BatchGetImage"
              } ]
            }
             
            """.trimIndent()
        val setRepositoryPolicyRequest =
            SetRepositoryPolicyRequest {
                repositoryName = repoName
                policyText = policyDocumentTemplate
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val response = ecrClient.setRepositoryPolicy(setRepositoryPolicyRequest)
            if (response != null) {
                println("Repository policy set successfully.")
            }
        }
    }


    /**
     * Creates an Amazon Elastic Container Registry (Amazon ECR) repository.
     *
     * @param repoName the name of the repository to create.
     * @return the Amazon Resource Name (ARN) of the created repository, or an empty string if the operation failed.
     * @throws RepositoryAlreadyExistsException if the repository exists.
     * @throws EcrException         if an error occurs while creating the repository.
     */
    suspend fun createECRRepository(repoName: String?): String? {
        val request =
            CreateRepositoryRequest {
                repositoryName = repoName
            }

        return try {
            EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
                val response = ecrClient.createRepository(request)
                response.repository?.repositoryArn
            }
        } catch (e: RepositoryAlreadyExistsException) {
            println("Repository already exists: $repoName")
            repoName?.let { getRepoARN(it) }
        } catch (e: EcrException) {
            println("An error occurred: ${e.message}")
            null
        }
    }

    suspend fun getRepoARN(repoName: String): String? {
        // Fetch the existing repository's ARN.
        val describeRequest =
            DescribeRepositoriesRequest {
                repositoryNames = listOf(repoName)
            }
        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val describeResponse = ecrClient.describeRepositories(describeRequest)
            return describeResponse.repositories?.get(0)?.repositoryArn
        }
    }

    fun listLocalImages(): Boolean = try {
        val images = getDockerClient()?.listImagesCmd()?.exec()
        images?.any { image ->
            image.repoTags?.any { tag -> tag.startsWith("echo-text") } ?: false
        } ?: false
    } catch (ex: Exception) {
        println("ERROR: ${ex.message}")
        false
    }


    /**
     * Pushes a Docker image to an Amazon Elastic Container Registry (ECR) repository.
     *
     * @param repoName the name of the ECR repository to push the image to.
     * @param imageName the name of the Docker image.
     */
    suspend fun pushDockerImage(
        repoName: String,
        imageName: String,
    ) {
        println("Pushing $imageName to $repoName will take a few seconds")
        val authConfig = getAuthConfig(repoName)

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val desRequest =
                DescribeRepositoriesRequest {
                    repositoryNames = listOf(repoName)
                }

            val describeRepoResponse = ecrClient.describeRepositories(desRequest)
            val repoData =
                describeRepoResponse.repositories?.firstOrNull { it.repositoryName == repoName }
                    ?: throw RuntimeException("Repository not found: $repoName")

            val tagImageCmd = getDockerClient()?.tagImageCmd("$imageName", "${repoData.repositoryUri}", imageName)
            if (tagImageCmd != null) {
                tagImageCmd.exec()
            }
            val pushImageCmd =
                repoData.repositoryUri?.let {
                    dockerClient?.pushImageCmd(it)
                        // ?.withTag("latest")
                        ?.withAuthConfig(authConfig)
                }

            try {
                if (pushImageCmd != null) {
                    pushImageCmd.start().awaitCompletion()
                }
                println("The $imageName was pushed to Amazon ECR")
            } catch (e: IOException) {
                throw RuntimeException(e)
            }
        }
    }


    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     */
    suspend fun verifyImage(
        repoName: String?,
        imageTagVal: String?,
    ) {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }
        require(!(imageTagVal == null || imageTagVal.isEmpty())) { "Image tag cannot be null or empty" }

        val imageId =
            ImageIdentifier {
                imageTag = imageTagVal
            }
        val request =
            DescribeImagesRequest {
                repositoryName = repoName
                imageIds = listOf(imageId)
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val describeImagesResponse = ecrClient.describeImages(request)
            if (describeImagesResponse != null && !describeImagesResponse.imageDetails?.isEmpty()!!) {
                println("Image is present in the repository.")
            } else {
                println("Image is not present in the repository.")
            }
        }
    }


    /**
     * Deletes an ECR (Elastic Container Registry) repository.
     *
     * @param repoName the name of the repository to delete.
     */
    suspend fun deleteECRRepository(repoName: String) {
        if (repoName.isNullOrEmpty()) {
            throw IllegalArgumentException("Repository name cannot be null or empty")
        }

        val repositoryRequest =
            DeleteRepositoryRequest {
                force = true
                repositoryName = repoName
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            ecrClient.deleteRepository(repositoryRequest)
            println("You have successfully deleted the $repoName repository")
        }
    }

    // Return an AuthConfig.
    private suspend fun getAuthConfig(repoName: String): AuthConfig {
        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            // Retrieve the authorization token for ECR.
            val response = ecrClient.getAuthorizationToken()
            val authorizationData = response.authorizationData?.get(0)
            val token = authorizationData?.authorizationToken
            val decodedToken = String(Base64.getDecoder().decode(token))
            val password = decodedToken.substring(4)

            val request =
                DescribeRepositoriesRequest {
                    repositoryNames = listOf(repoName)
                }

            val descrRepoResponse = ecrClient.describeRepositories(request)
            val repoData = descrRepoResponse.repositories?.firstOrNull { it.repositoryName == repoName }
            val registryURL: String = repoData?.repositoryUri?.split("/")?.get(0) ?: ""

            return AuthConfig()
                .withUsername("AWS")
                .withPassword(password)
                .withRegistryAddress(registryURL)
        }
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [CreateRepository](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteRepository](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeImages](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeRepositories](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetAuthorizationToken](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetRepositoryPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [SetRepositoryPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartLifecyclePolicyPreview](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateRepository`
<a name="ecr_CreateRepository_kotlin_1_topic"></a>

次のコード例は、`CreateRepository` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Creates an Amazon Elastic Container Registry (Amazon ECR) repository.
     *
     * @param repoName the name of the repository to create.
     * @return the Amazon Resource Name (ARN) of the created repository, or an empty string if the operation failed.
     * @throws RepositoryAlreadyExistsException if the repository exists.
     * @throws EcrException         if an error occurs while creating the repository.
     */
    suspend fun createECRRepository(repoName: String?): String? {
        val request =
            CreateRepositoryRequest {
                repositoryName = repoName
            }

        return try {
            EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
                val response = ecrClient.createRepository(request)
                response.repository?.repositoryArn
            }
        } catch (e: RepositoryAlreadyExistsException) {
            println("Repository already exists: $repoName")
            repoName?.let { getRepoARN(it) }
        } catch (e: EcrException) {
            println("An error occurred: ${e.message}")
            null
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateRepository](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteRepository`
<a name="ecr_DeleteRepository_kotlin_1_topic"></a>

次のコード例は、`DeleteRepository` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Deletes an ECR (Elastic Container Registry) repository.
     *
     * @param repoName the name of the repository to delete.
     */
    suspend fun deleteECRRepository(repoName: String) {
        if (repoName.isNullOrEmpty()) {
            throw IllegalArgumentException("Repository name cannot be null or empty")
        }

        val repositoryRequest =
            DeleteRepositoryRequest {
                force = true
                repositoryName = repoName
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            ecrClient.deleteRepository(repositoryRequest)
            println("You have successfully deleted the $repoName repository")
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteRepository](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeImages`
<a name="ecr_DescribeImages_kotlin_1_topic"></a>

次のコード例は、`DescribeImages` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     */
    suspend fun verifyImage(
        repoName: String?,
        imageTagVal: String?,
    ) {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }
        require(!(imageTagVal == null || imageTagVal.isEmpty())) { "Image tag cannot be null or empty" }

        val imageId =
            ImageIdentifier {
                imageTag = imageTagVal
            }
        val request =
            DescribeImagesRequest {
                repositoryName = repoName
                imageIds = listOf(imageId)
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val describeImagesResponse = ecrClient.describeImages(request)
            if (describeImagesResponse != null && !describeImagesResponse.imageDetails?.isEmpty()!!) {
                println("Image is present in the repository.")
            } else {
                println("Image is not present in the repository.")
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeImages](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeRepositories`
<a name="ecr_DescribeRepositories_kotlin_1_topic"></a>

次のコード例は、`DescribeRepositories` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the repository URI for the specified repository name.
     *
     * @param repoName the name of the repository to retrieve the URI for.
     * @return the repository URI for the specified repository name.
     */
    suspend fun getRepositoryURI(repoName: String?): String? {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }
        val request =
            DescribeRepositoriesRequest {
                repositoryNames = listOf(repoName)
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val describeRepositoriesResponse = ecrClient.describeRepositories(request)
            if (!describeRepositoriesResponse.repositories?.isEmpty()!!) {
                return describeRepositoriesResponse?.repositories?.get(0)?.repositoryUri
            } else {
                println("No repositories found for the given name.")
                return ""
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeRepositories](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetAuthorizationToken`
<a name="ecr_GetAuthorizationToken_kotlin_1_topic"></a>

次のコード例は、`GetAuthorizationToken` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Retrieves the authorization token for Amazon Elastic Container Registry (ECR).
     *
     */
    suspend fun getAuthToken() {
        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            // Retrieve the authorization token for ECR.
            val response = ecrClient.getAuthorizationToken()
            val authorizationData = response.authorizationData?.get(0)
            val token = authorizationData?.authorizationToken
            if (token != null) {
                println("The token was successfully retrieved.")
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[GetAuthorizationToken](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetRepositoryPolicy`
<a name="ecr_GetRepositoryPolicy_kotlin_1_topic"></a>

次のコード例は、`GetRepositoryPolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Gets the repository policy for the specified repository.
     *
     * @param repoName the name of the repository.
     */
    suspend fun getRepoPolicy(repoName: String?): String? {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }

        // Create the request
        val getRepositoryPolicyRequest =
            GetRepositoryPolicyRequest {
                repositoryName = repoName
            }
        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val response = ecrClient.getRepositoryPolicy(getRepositoryPolicyRequest)
            val responseText = response.policyText
            return responseText
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[GetRepositoryPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PushImageCmd`
<a name="ecr_PushImageCmd_kotlin_1_topic"></a>

次のコード例は、`PushImageCmd` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Pushes a Docker image to an Amazon Elastic Container Registry (ECR) repository.
     *
     * @param repoName the name of the ECR repository to push the image to.
     * @param imageName the name of the Docker image.
     */
    suspend fun pushDockerImage(
        repoName: String,
        imageName: String,
    ) {
        println("Pushing $imageName to $repoName will take a few seconds")
        val authConfig = getAuthConfig(repoName)

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val desRequest =
                DescribeRepositoriesRequest {
                    repositoryNames = listOf(repoName)
                }

            val describeRepoResponse = ecrClient.describeRepositories(desRequest)
            val repoData =
                describeRepoResponse.repositories?.firstOrNull { it.repositoryName == repoName }
                    ?: throw RuntimeException("Repository not found: $repoName")

            val tagImageCmd = getDockerClient()?.tagImageCmd("$imageName", "${repoData.repositoryUri}", imageName)
            if (tagImageCmd != null) {
                tagImageCmd.exec()
            }
            val pushImageCmd =
                repoData.repositoryUri?.let {
                    dockerClient?.pushImageCmd(it)
                        // ?.withTag("latest")
                        ?.withAuthConfig(authConfig)
                }

            try {
                if (pushImageCmd != null) {
                    pushImageCmd.start().awaitCompletion()
                }
                println("The $imageName was pushed to Amazon ECR")
            } catch (e: IOException) {
                throw RuntimeException(e)
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[PushImageCmd](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SetRepositoryPolicy`
<a name="ecr_SetRepositoryPolicy_kotlin_1_topic"></a>

次のコード例は、`SetRepositoryPolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Sets the repository policy for the specified ECR repository.
     *
     * @param repoName the name of the ECR repository.
     * @param iamRole the IAM role to be granted access to the repository.
     */
    suspend fun setRepoPolicy(
        repoName: String?,
        iamRole: String?,
    ) {
        val policyDocumentTemplate =
            """
             {
              "Version":"2012-10-17",		 	 	 
              "Statement" : [ {
                "Sid" : "new statement",
                "Effect" : "Allow",
                "Principal" : {
                  "AWS" : "$iamRole"
                },
                "Action" : "ecr:BatchGetImage"
              } ]
            }
             
            """.trimIndent()
        val setRepositoryPolicyRequest =
            SetRepositoryPolicyRequest {
                repositoryName = repoName
                policyText = policyDocumentTemplate
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val response = ecrClient.setRepositoryPolicy(setRepositoryPolicyRequest)
            if (response != null) {
                println("Repository policy set successfully.")
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[SetRepositoryPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `StartLifecyclePolicyPreview`
<a name="ecr_StartLifecyclePolicyPreview_kotlin_1_topic"></a>

次のコード例は、`StartLifecyclePolicyPreview` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Verifies the existence of an image in an Amazon Elastic Container Registry (Amazon ECR) repository asynchronously.
     *
     * @param repositoryName The name of the Amazon ECR repository.
     * @param imageTag       The tag of the image to verify.
     */
    suspend fun verifyImage(
        repoName: String?,
        imageTagVal: String?,
    ) {
        require(!(repoName == null || repoName.isEmpty())) { "Repository name cannot be null or empty" }
        require(!(imageTagVal == null || imageTagVal.isEmpty())) { "Image tag cannot be null or empty" }

        val imageId =
            ImageIdentifier {
                imageTag = imageTagVal
            }
        val request =
            DescribeImagesRequest {
                repositoryName = repoName
                imageIds = listOf(imageId)
            }

        EcrClient.fromEnvironment { region = "us-east-1" }.use { ecrClient ->
            val describeImagesResponse = ecrClient.describeImages(request)
            if (describeImagesResponse != null && !describeImagesResponse.imageDetails?.isEmpty()!!) {
                println("Image is present in the repository.")
            } else {
                println("Image is not present in the repository.")
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[StartLifecyclePolicyPreview](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した OpenSearch Service の例
<a name="kotlin_1_opensearch_code_examples"></a>

次のコード例は、OpenSearch Service で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDomain`
<a name="opensearch_CreateDomain_kotlin_1_topic"></a>

次のコード例は、`CreateDomain` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/opensearch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createNewDomain(domainNameVal: String?) {
    val clusterConfigOb =
        ClusterConfig {
            dedicatedMasterEnabled = true
            dedicatedMasterCount = 3
            dedicatedMasterType = OpenSearchPartitionInstanceType.fromValue("t2.small.search")
            instanceType = OpenSearchPartitionInstanceType.fromValue("t2.small.search")
            instanceCount = 5
        }

    val ebsOptionsOb =
        EbsOptions {
            ebsEnabled = true
            volumeSize = 10
            volumeType = VolumeType.Gp2
        }

    val encryptionOptionsOb =
        NodeToNodeEncryptionOptions {
            enabled = true
        }

    val request =
        CreateDomainRequest {
            domainName = domainNameVal
            engineVersion = "OpenSearch_1.0"
            clusterConfig = clusterConfigOb
            ebsOptions = ebsOptionsOb
            nodeToNodeEncryptionOptions = encryptionOptionsOb
        }

    println("Sending domain creation request...")
    OpenSearchClient.fromEnvironment { region = "us-east-1" }.use { searchClient ->
        val createResponse = searchClient.createDomain(request)
        println("Domain status is ${createResponse.domainStatus}")
        println("Domain Id is ${createResponse.domainStatus?.domainId}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateDomain](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteDomain`
<a name="opensearch_DeleteDomain_kotlin_1_topic"></a>

次のコード例は、`DeleteDomain` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/opensearch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteSpecificDomain(domainNameVal: String) {
    val request =
        DeleteDomainRequest {
            domainName = domainNameVal
        }
    OpenSearchClient.fromEnvironment { region = "us-east-1" }.use { searchClient ->
        searchClient.deleteDomain(request)
        println("$domainNameVal was successfully deleted.")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」**の「[DeleteDomain](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListDomainNames`
<a name="opensearch_ListDomainNames_kotlin_1_topic"></a>

次のコード例は、`ListDomainNames` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/opensearch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllDomains() {
    OpenSearchClient.fromEnvironment { region = "us-east-1" }.use { searchClient ->
        val response: ListDomainNamesResponse = searchClient.listDomainNames(ListDomainNamesRequest {})
        response.domainNames?.forEach { domain ->
            println("Domain name is " + domain.domainName)
        }
    }
}
```
+  API の詳細については、AWS SDK for Kotlin API リファレンスの「[ListDomainNames](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。**

### `UpdateDomainConfig`
<a name="opensearch_UpdateDomainConfig_kotlin_1_topic"></a>

次のコード例は、`UpdateDomainConfig` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/opensearch#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateSpecificDomain(domainNameVal: String?) {
    val clusterConfigOb =
        ClusterConfig {
            instanceCount = 3
        }

    val request =
        UpdateDomainConfigRequest {
            domainName = domainNameVal
            clusterConfig = clusterConfigOb
        }

    println("Sending domain update request...")
    OpenSearchClient.fromEnvironment { region = "us-east-1" }.use { searchClient ->
        val updateResponse = searchClient.updateDomainConfig(request)
        println("Domain update response from Amazon OpenSearch Service:")
        println(updateResponse.toString())
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[UpdateDomainConfig](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した EventBridge の例
<a name="kotlin_1_eventbridge_code_examples"></a>

次のコード例は、EventBridge で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello EventBridge
<a name="eventbridge_Hello_kotlin_1_topic"></a>

次のコード例は、EventBridge の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.eventbridge.EventBridgeClient
import aws.sdk.kotlin.services.eventbridge.model.ListEventBusesRequest
import aws.sdk.kotlin.services.eventbridge.model.ListEventBusesResponse

suspend fun main() {
    listBusesHello()
}

suspend fun listBusesHello() {
    val request =
        ListEventBusesRequest {
            limit = 10
        }

    EventBridgeClient.fromEnvironment { region = "us-west-2" }.use { eventBrClient ->
        val response: ListEventBusesResponse = eventBrClient.listEventBuses(request)
        response.eventBuses?.forEach { bus ->
            println("The name of the event bus is ${bus.name}")
            println("The ARN of the event bus is ${bus.arn}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListEventBuses](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="eventbridge_Scenario_GettingStarted_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ルールを作成して、ターゲットを追加する。
+ ルールを有効化および無効化する。
+ ルールとターゲットを一覧表示して更新する。
+ イベントを送信して、リソースをクリーンアップする。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
/*
 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

 This Kotlin example performs the following tasks with Amazon EventBridge:

 1. Creates an AWS Identity and Access Management (IAM) role to use with Amazon EventBridge.
 2. Creates an Amazon Simple Storage Service (Amazon S3) bucket with EventBridge events enabled.
 3. Creates a rule that triggers when an object is uploaded to Amazon S3.
 4. Lists rules on the event bus.
 5. Creates a new Amazon Simple Notification Service (Amazon SNS) topic and lets the user subscribe to it.
 6. Adds a target to the rule that sends an email to the specified topic.
 7. Creates an EventBridge event that sends an email when an Amazon S3 object is created.
 8. Lists targets.
 9. Lists the rules for the same target.
 10. Triggers the rule by uploading a file to the S3 bucket.
 11. Disables a specific rule.
 12. Checks and prints the state of the rule.
 13. Adds a transform to the rule to change the text of the email.
 14. Enables a specific rule.
 15. Triggers the updated rule by uploading a file to the S3 bucket.
 16. Updates the rule to a custom rule pattern.
 17. Sends an event to trigger the rule.
 18. Cleans up resources.
*/
val DASHES: String = String(CharArray(80)).replace("\u0000", "-")

suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <roleName> <bucketName> <topicName> <eventRuleName>

    Where:
        roleName - The name of the role to create.
        bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name to create.
        topicName - The name of the Amazon Simple Notification Service (Amazon SNS) topic to create.
        eventRuleName - The Amazon EventBridge rule name to create.
    """
    val polJSON =
        "{" +
            "\"Version\": \"2012-10-17\"," +
            "\"Statement\": [{" +
            "\"Effect\": \"Allow\"," +
            "\"Principal\": {" +
            "\"Service\": \"events.amazonaws.com\"" +
            "}," +
            "\"Action\": \"sts:AssumeRole\"" +
            "}]" +
            "}"

    if (args.size != 4) {
        println(usage)
        exitProcess(1)
    }

    val sc = Scanner(System.`in`)
    val roleName = args[0]
    val bucketName = args[1]
    val topicName = args[2]
    val eventRuleName = args[3]

    println(DASHES)
    println("Welcome to the Amazon EventBridge example scenario.")
    println(DASHES)

    println(DASHES)
    println("1. Create an AWS Identity and Access Management (IAM) role to use with Amazon EventBridge.")
    val roleArn = createIAMRole(roleName, polJSON)
    println(DASHES)

    println(DASHES)
    println("2. Create an S3 bucket with EventBridge events enabled.")
    if (checkBucket(bucketName)) {
        println("$bucketName already exists. Ending this scenario.")
        exitProcess(1)
    }

    createBucket(bucketName)
    delay(3000)
    setBucketNotification(bucketName)
    println(DASHES)

    println(DASHES)
    println("3. Create a rule that triggers when an object is uploaded to Amazon S3.")
    delay(10000)
    addEventRule(roleArn, bucketName, eventRuleName)
    println(DASHES)

    println(DASHES)
    println("4. List rules on the event bus.")
    listRules()
    println(DASHES)

    println(DASHES)
    println("5. Create a new SNS topic for testing and let the user subscribe to the topic.")
    val topicArn = createSnsTopic(topicName)
    println(DASHES)

    println(DASHES)
    println("6. Add a target to the rule that sends an email to the specified topic.")
    println("Enter your email to subscribe to the Amazon SNS topic:")
    val email = sc.nextLine()
    subEmail(topicArn, email)
    println("Use the link in the email you received to confirm your subscription. Then press Enter to continue.")
    sc.nextLine()
    println(DASHES)

    println(DASHES)
    println("7. Create an EventBridge event that sends an email when an Amazon S3 object is created.")
    addSnsEventRule(eventRuleName, topicArn, topicName, eventRuleName, bucketName)
    println(DASHES)

    println(DASHES)
    println("8. List targets.")
    listTargets(eventRuleName)
    println(DASHES)

    println(DASHES)
    println(" 9. List the rules for the same target.")
    listTargetRules(topicArn)
    println(DASHES)

    println(DASHES)
    println("10. Trigger the rule by uploading a file to the S3 bucket.")
    println("Press Enter to continue.")
    sc.nextLine()
    uploadTextFiletoS3(bucketName)
    println(DASHES)

    println(DASHES)
    println("11. Disable a specific rule.")
    changeRuleState(eventRuleName, false)
    println(DASHES)

    println(DASHES)
    println("12. Check and print the state of the rule.")
    checkRule(eventRuleName)
    println(DASHES)

    println(DASHES)
    println("13. Add a transform to the rule to change the text of the email.")
    updateSnsEventRule(topicArn, eventRuleName)
    println(DASHES)

    println(DASHES)
    println("14. Enable a specific rule.")
    changeRuleState(eventRuleName, true)
    println(DASHES)

    println(DASHES)
    println("15. Trigger the updated rule by uploading a file to the S3 bucket.")
    println("Press Enter to continue.")
    sc.nextLine()
    uploadTextFiletoS3(bucketName)
    println(DASHES)

    println(DASHES)
    println("16. Update the rule to a custom rule pattern.")
    updateToCustomRule(eventRuleName)
    println("Updated event rule $eventRuleName to use a custom pattern.")
    updateCustomRuleTargetWithTransform(topicArn, eventRuleName)
    println("Updated event target $topicArn.")
    println(DASHES)

    println(DASHES)
    println("17. Send an event to trigger the rule. This will trigger a subscription email.")
    triggerCustomRule(email)
    println("Events have been sent. Press Enter to continue.")
    sc.nextLine()
    println(DASHES)

    println(DASHES)
    println("18. Clean up resources.")
    println("Do you want to clean up resources (y/n)")
    val ans = sc.nextLine()
    if (ans.compareTo("y") == 0) {
        cleanupResources(topicArn, eventRuleName, bucketName, roleName)
    } else {
        println("The resources will not be cleaned up. ")
    }
    println(DASHES)

    println(DASHES)
    println("The Amazon EventBridge example scenario has successfully completed.")
    println(DASHES)
}

suspend fun cleanupResources(
    topicArn: String?,
    eventRuleName: String?,
    bucketName: String?,
    roleName: String?,
) {
    println("Removing all targets from the event rule.")
    deleteTargetsFromRule(eventRuleName)
    deleteRuleByName(eventRuleName)
    deleteSNSTopic(topicArn)
    deleteS3Bucket(bucketName)
    deleteRole(roleName)
}

suspend fun deleteRole(roleNameVal: String?) {
    val policyArnVal = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess"
    val policyRequest =
        DetachRolePolicyRequest {
            policyArn = policyArnVal
            roleName = roleNameVal
        }
    IamClient.fromEnvironment { region = "us-east-1" }.use { iam ->
        iam.detachRolePolicy(policyRequest)
        println("Successfully detached policy $policyArnVal from role $roleNameVal")

        // Delete the role.
        val roleRequest =
            DeleteRoleRequest {
                roleName = roleNameVal
            }

        iam.deleteRole(roleRequest)
        println("*** Successfully deleted $roleNameVal")
    }
}

suspend fun deleteS3Bucket(bucketName: String?) {
    // Remove all the objects from the S3 bucket.
    val listObjects =
        ListObjectsRequest {
            bucket = bucketName
        }
    S3Client.fromEnvironment { region = "us-east-1" }.use { s3Client ->
        val res = s3Client.listObjects(listObjects)
        val myObjects = res.contents
        val toDelete = mutableListOf<ObjectIdentifier>()

        if (myObjects != null) {
            for (myValue in myObjects) {
                toDelete.add(
                    ObjectIdentifier {
                        key = myValue.key
                    },
                )
            }
        }

        val delOb =
            Delete {
                objects = toDelete
            }

        val dor =
            DeleteObjectsRequest {
                bucket = bucketName
                delete = delOb
            }
        s3Client.deleteObjects(dor)

        // Delete the S3 bucket.
        val deleteBucketRequest =
            DeleteBucketRequest {
                bucket = bucketName
            }
        s3Client.deleteBucket(deleteBucketRequest)
        println("You have deleted the bucket and the objects")
    }
}

// Delete the SNS topic.
suspend fun deleteSNSTopic(topicArnVal: String?) {
    val request =
        DeleteTopicRequest {
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.deleteTopic(request)
        println(" $topicArnVal was deleted.")
    }
}

suspend fun deleteRuleByName(ruleName: String?) {
    val ruleRequest =
        DeleteRuleRequest {
            name = ruleName
        }
    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.deleteRule(ruleRequest)
        println("Successfully deleted the rule")
    }
}

suspend fun deleteTargetsFromRule(eventRuleName: String?) {
    // First, get all targets that will be deleted.
    val request =
        ListTargetsByRuleRequest {
            rule = eventRuleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listTargetsByRule(request)
        val allTargets = response.targets

        // Get all targets and delete them.
        if (allTargets != null) {
            for (myTarget in allTargets) {
                val removeTargetsRequest =
                    RemoveTargetsRequest {
                        rule = eventRuleName
                        ids = listOf(myTarget.id.toString())
                    }
                eventBrClient.removeTargets(removeTargetsRequest)
                println("Successfully removed the target")
            }
        }
    }
}

suspend fun triggerCustomRule(email: String) {
    val json =
        "{" +
            "\"UserEmail\": \"" + email + "\"," +
            "\"Message\": \"This event was generated by example code.\"" +
            "\"UtcTime\": \"Now.\"" +
            "}"

    val entry =
        PutEventsRequestEntry {
            source = "ExampleSource"
            detail = json
            detailType = "ExampleType"
        }

    val eventsRequest =
        PutEventsRequest {
            this.entries = listOf(entry)
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putEvents(eventsRequest)
    }
}

suspend fun updateCustomRuleTargetWithTransform(
    topicArn: String?,
    ruleName: String?,
) {
    val targetId = UUID.randomUUID().toString()

    val inputTransformerOb =
        InputTransformer {
            inputTemplate = "\"Notification: sample event was received.\""
        }

    val target =
        Target {
            id = targetId
            arn = topicArn
            inputTransformer = inputTransformerOb
        }

    val targetsRequest =
        PutTargetsRequest {
            rule = ruleName
            targets = listOf(target)
            eventBusName = null
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putTargets(targetsRequest)
    }
}

suspend fun updateToCustomRule(ruleName: String?) {
    val customEventsPattern =
        "{" +
            "\"source\": [\"ExampleSource\"]," +
            "\"detail-type\": [\"ExampleType\"]" +
            "}"
    val request =
        PutRuleRequest {
            name = ruleName
            description = "Custom test rule"
            eventPattern = customEventsPattern
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putRule(request)
    }
}

// Update an Amazon S3 object created rule with a transform on the target.
suspend fun updateSnsEventRule(
    topicArn: String?,
    ruleName: String?,
) {
    val targetId = UUID.randomUUID().toString()
    val myMap = mutableMapOf<String, String>()
    myMap["bucket"] = "$.detail.bucket.name"
    myMap["time"] = "$.time"

    val inputTransOb =
        InputTransformer {
            inputTemplate = "\"Notification: an object was uploaded to bucket <bucket> at <time>.\""
            inputPathsMap = myMap
        }
    val targetOb =
        Target {
            id = targetId
            arn = topicArn
            inputTransformer = inputTransOb
        }

    val targetsRequest =
        PutTargetsRequest {
            rule = ruleName
            targets = listOf(targetOb)
            eventBusName = null
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putTargets(targetsRequest)
    }
}

suspend fun checkRule(eventRuleName: String?) {
    val ruleRequest =
        DescribeRuleRequest {
            name = eventRuleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.describeRule(ruleRequest)
        println("The state of the rule is $response")
    }
}

suspend fun changeRuleState(
    eventRuleName: String,
    isEnabled: Boolean?,
) {
    if (!isEnabled!!) {
        println("Disabling the rule: $eventRuleName")
        val ruleRequest =
            DisableRuleRequest {
                name = eventRuleName
            }
        EventBridgeClient { region = "us-east-1" }.use { eventBrClient ->
            eventBrClient.disableRule(ruleRequest)
        }
    } else {
        println("Enabling the rule: $eventRuleName")
        val ruleRequest =
            EnableRuleRequest {
                name = eventRuleName
            }
        EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
            eventBrClient.enableRule(ruleRequest)
        }
    }
}

// Create and upload a file to an S3 bucket to trigger an event.
@Throws(IOException::class)
suspend fun uploadTextFiletoS3(bucketName: String?) {
    val fileSuffix = SimpleDateFormat("yyyyMMddHHmmss").format(Date())
    val fileName = "TextFile$fileSuffix.txt"
    val myFile = File(fileName)
    val fw = FileWriter(myFile.absoluteFile)
    val bw = BufferedWriter(fw)
    bw.write("This is a sample file for testing uploads.")
    bw.close()

    val putOb =
        PutObjectRequest {
            bucket = bucketName
            key = fileName
            body = myFile.asByteStream()
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3Client ->
        s3Client.putObject(putOb)
    }
}

suspend fun listTargetRules(topicArnVal: String?) {
    val ruleNamesByTargetRequest =
        ListRuleNamesByTargetRequest {
            targetArn = topicArnVal
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listRuleNamesByTarget(ruleNamesByTargetRequest)
        response.ruleNames?.forEach { rule ->
            println("The rule name is $rule")
        }
    }
}

suspend fun listTargets(ruleName: String?) {
    val ruleRequest =
        ListTargetsByRuleRequest {
            rule = ruleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listTargetsByRule(ruleRequest)
        response.targets?.forEach { target ->
            println("Target ARN: ${target.arn}")
        }
    }
}

// Add a rule that triggers an SNS target when a file is uploaded to an S3 bucket.
suspend fun addSnsEventRule(
    ruleName: String?,
    topicArn: String?,
    topicName: String,
    eventRuleName: String,
    bucketName: String,
) {
    val targetID = UUID.randomUUID().toString()
    val myTarget =
        Target {
            id = targetID
            arn = topicArn
        }

    val targetsOb = mutableListOf<Target>()
    targetsOb.add(myTarget)

    val request =
        PutTargetsRequest {
            eventBusName = null
            targets = targetsOb
            rule = ruleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putTargets(request)
        println("Added event rule $eventRuleName with Amazon SNS target $topicName for bucket $bucketName.")
    }
}

suspend fun subEmail(
    topicArnVal: String?,
    email: String?,
) {
    val request =
        SubscribeRequest {
            protocol = "email"
            endpoint = email
            returnSubscriptionArn = true
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.subscribe(request)
        println(" Subscription ARN: ${result.subscriptionArn}")
    }
}

suspend fun createSnsTopic(topicName: String): String? {
    val topicPolicy = """
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Sid": "EventBridgePublishTopic",
                "Effect": "Allow",
                "Principal": {
                    "Service": "events.amazonaws.com"
                },
                "Resource": "*",
                "Action": "sns:Publish"
            }
        ]
    }
    """.trimIndent()

    val topicAttributes = mutableMapOf<String, String>()
    topicAttributes["Policy"] = topicPolicy

    val topicRequest =
        CreateTopicRequest {
            name = topicName
            attributes = topicAttributes
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val response = snsClient.createTopic(topicRequest)
        println("Added topic $topicName for email subscriptions.")
        return response.topicArn
    }
}

suspend fun listRules() {
    val rulesRequest =
        ListRulesRequest {
            eventBusName = "default"
            limit = 10
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listRules(rulesRequest)
        response.rules?.forEach { rule ->
            println("The rule name is ${rule.name}")
            println("The rule ARN is ${rule.arn}")
        }
    }
}

// Create a new event rule that triggers when an Amazon S3 object is created in a bucket.
suspend fun addEventRule(
    roleArnVal: String?,
    bucketName: String,
    eventRuleName: String?,
) {
    val pattern = """
    {
        "source": ["aws.s3"],
        "detail-type": ["Object Created"],
        "detail": {
            "bucket": {
                "name": ["$bucketName"]
            }
        }
    }
    """.trimIndent()

    val ruleRequest =
        PutRuleRequest {
            description = "Created by using the AWS SDK for Kotlin"
            name = eventRuleName
            eventPattern = pattern
            roleArn = roleArnVal
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val ruleResponse = eventBrClient.putRule(ruleRequest)
        println("The ARN of the new rule is ${ruleResponse.ruleArn}")
    }
}

// Set the Amazon S3 bucket notification configuration.
suspend fun setBucketNotification(bucketName: String) {
    val eventBridgeConfig =
        EventBridgeConfiguration {
        }

    val configuration =
        NotificationConfiguration {
            eventBridgeConfiguration = eventBridgeConfig
        }

    val configurationRequest =
        PutBucketNotificationConfigurationRequest {
            bucket = bucketName
            notificationConfiguration = configuration
            skipDestinationValidation = true
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3Client ->
        s3Client.putBucketNotificationConfiguration(configurationRequest)
        println("Added bucket $bucketName with EventBridge events enabled.")
    }
}

// Create an S3 bucket using a waiter.
suspend fun createBucket(bucketName: String) {
    val request =
        CreateBucketRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.createBucket(request)
        s3.waitUntilBucketExists {
            bucket = bucketName
        }
        println("$bucketName is ready")
    }
}

suspend fun checkBucket(bucketName: String?): Boolean {
    try {
        // Determine if the S3 bucket exists.
        val headBucketRequest =
            HeadBucketRequest {
                bucket = bucketName
            }

        S3Client.fromEnvironment { region = "us-east-1" }.use { s3Client ->
            s3Client.headBucket(headBucketRequest)
            return true
        }
    } catch (e: S3Exception) {
        System.err.println(e.message)
    }
    return false
}

suspend fun createIAMRole(
    rolenameVal: String?,
    polJSON: String?,
): String? {
    val request =
        CreateRoleRequest {
            roleName = rolenameVal
            assumeRolePolicyDocument = polJSON
            description = "Created using the AWS SDK for Kotlin"
        }

    val rolePolicyRequest =
        AttachRolePolicyRequest {
            roleName = rolenameVal
            policyArn = "arn:aws:iam::aws:policy/AmazonEventBridgeFullAccess"
        }

    IamClient.fromEnvironment { region = "us-east-1" }.use { iam ->
        val response = iam.createRole(request)
        iam.attachRolePolicy(rolePolicyRequest)
        return response.role?.arn
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [DeleteRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DisableRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [EnableRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListRuleNamesByTarget](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListRules](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListTargetsByRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutEvents](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutTargets](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `DeleteRule`
<a name="eventbridge_DeleteRule_kotlin_1_topic"></a>

次のコード例は、`DeleteRule` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteRuleByName(ruleName: String?) {
    val ruleRequest =
        DeleteRuleRequest {
            name = ruleName
        }
    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.deleteRule(ruleRequest)
        println("Successfully deleted the rule")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeRule`
<a name="eventbridge_DescribeRule_kotlin_1_topic"></a>

次のコード例は、`DescribeRule` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun checkRule(eventRuleName: String?) {
    val ruleRequest =
        DescribeRuleRequest {
            name = eventRuleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.describeRule(ruleRequest)
        println("The state of the rule is $response")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DisableRule`
<a name="eventbridge_DisableRule_kotlin_1_topic"></a>

次のコード例は、`DisableRule` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun changeRuleState(
    eventRuleName: String,
    isEnabled: Boolean?,
) {
    if (!isEnabled!!) {
        println("Disabling the rule: $eventRuleName")
        val ruleRequest =
            DisableRuleRequest {
                name = eventRuleName
            }
        EventBridgeClient { region = "us-east-1" }.use { eventBrClient ->
            eventBrClient.disableRule(ruleRequest)
        }
    } else {
        println("Enabling the rule: $eventRuleName")
        val ruleRequest =
            EnableRuleRequest {
                name = eventRuleName
            }
        EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
            eventBrClient.enableRule(ruleRequest)
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DisableRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `EnableRule`
<a name="eventbridge_EnableRule_kotlin_1_topic"></a>

次のコード例は、`EnableRule` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun changeRuleState(
    eventRuleName: String,
    isEnabled: Boolean?,
) {
    if (!isEnabled!!) {
        println("Disabling the rule: $eventRuleName")
        val ruleRequest =
            DisableRuleRequest {
                name = eventRuleName
            }
        EventBridgeClient { region = "us-east-1" }.use { eventBrClient ->
            eventBrClient.disableRule(ruleRequest)
        }
    } else {
        println("Enabling the rule: $eventRuleName")
        val ruleRequest =
            EnableRuleRequest {
                name = eventRuleName
            }
        EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
            eventBrClient.enableRule(ruleRequest)
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[EnableRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListRuleNamesByTarget`
<a name="eventbridge_ListRuleNamesByTarget_kotlin_1_topic"></a>

次のコード例は、`ListRuleNamesByTarget` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listTargetRules(topicArnVal: String?) {
    val ruleNamesByTargetRequest =
        ListRuleNamesByTargetRequest {
            targetArn = topicArnVal
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listRuleNamesByTarget(ruleNamesByTargetRequest)
        response.ruleNames?.forEach { rule ->
            println("The rule name is $rule")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListRuleNamesByTarget](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListRules`
<a name="eventbridge_ListRules_kotlin_1_topic"></a>

次のコード例は、`ListRules` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listRules() {
    val rulesRequest =
        ListRulesRequest {
            eventBusName = "default"
            limit = 10
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listRules(rulesRequest)
        response.rules?.forEach { rule ->
            println("The rule name is ${rule.name}")
            println("The rule ARN is ${rule.arn}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListRules](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListTargetsByRule`
<a name="eventbridge_ListTargetsByRule_kotlin_1_topic"></a>

次のコード例は、`ListTargetsByRule` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listTargets(ruleName: String?) {
    val ruleRequest =
        ListTargetsByRuleRequest {
            rule = ruleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listTargetsByRule(ruleRequest)
        response.targets?.forEach { target ->
            println("Target ARN: ${target.arn}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListTargetsByRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutEvents`
<a name="eventbridge_PutEvents_kotlin_1_topic"></a>

次のコード例は、`PutEvents` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun triggerCustomRule(email: String) {
    val json =
        "{" +
            "\"UserEmail\": \"" + email + "\"," +
            "\"Message\": \"This event was generated by example code.\"" +
            "\"UtcTime\": \"Now.\"" +
            "}"

    val entry =
        PutEventsRequestEntry {
            source = "ExampleSource"
            detail = json
            detailType = "ExampleType"
        }

    val eventsRequest =
        PutEventsRequest {
            this.entries = listOf(entry)
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putEvents(eventsRequest)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[PutEvents](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutRule`
<a name="eventbridge_PutRule_kotlin_1_topic"></a>

次のコード例は、`PutRule` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。
スケジュールルールを作成します。  

```
suspend fun createScRule(
    ruleName: String?,
    cronExpression: String?,
) {
    val ruleRequest =
        PutRuleRequest {
            name = ruleName
            eventBusName = "default"
            scheduleExpression = cronExpression
            state = RuleState.Enabled
            description = "A test rule that runs on a schedule created by the Kotlin API"
        }

    EventBridgeClient.fromEnvironment { region = "us-west-2" }.use { eventBrClient ->
        val ruleResponse = eventBrClient.putRule(ruleRequest)
        println("The ARN of the new rule is ${ruleResponse.ruleArn}")
    }
}
```
Amazon Simple Storage Service バケットにオブジェクトが追加されたときにトリガーするルールを作成します。  

```
// Create a new event rule that triggers when an Amazon S3 object is created in a bucket.
suspend fun addEventRule(
    roleArnVal: String?,
    bucketName: String,
    eventRuleName: String?,
) {
    val pattern = """
    {
        "source": ["aws.s3"],
        "detail-type": ["Object Created"],
        "detail": {
            "bucket": {
                "name": ["$bucketName"]
            }
        }
    }
    """.trimIndent()

    val ruleRequest =
        PutRuleRequest {
            description = "Created by using the AWS SDK for Kotlin"
            name = eventRuleName
            eventPattern = pattern
            roleArn = roleArnVal
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val ruleResponse = eventBrClient.putRule(ruleRequest)
        println("The ARN of the new rule is ${ruleResponse.ruleArn}")
    }
}
```
+  API の詳細については、*AWS SDK for kotlin API リファレンス*の「[PutRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutTargets`
<a name="eventbridge_PutTargets_kotlin_1_topic"></a>

次のコード例は、`PutTargets` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
// Add a rule that triggers an SNS target when a file is uploaded to an S3 bucket.
suspend fun addSnsEventRule(
    ruleName: String?,
    topicArn: String?,
    topicName: String,
    eventRuleName: String,
    bucketName: String,
) {
    val targetID = UUID.randomUUID().toString()
    val myTarget =
        Target {
            id = targetID
            arn = topicArn
        }

    val targetsOb = mutableListOf<Target>()
    targetsOb.add(myTarget)

    val request =
        PutTargetsRequest {
            eventBusName = null
            targets = targetsOb
            rule = ruleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putTargets(request)
        println("Added event rule $eventRuleName with Amazon SNS target $topicName for bucket $bucketName.")
    }
}
```
ルールのターゲットにインプットトランスフォーマーを追加します。  

```
suspend fun updateCustomRuleTargetWithTransform(
    topicArn: String?,
    ruleName: String?,
) {
    val targetId = UUID.randomUUID().toString()

    val inputTransformerOb =
        InputTransformer {
            inputTemplate = "\"Notification: sample event was received.\""
        }

    val target =
        Target {
            id = targetId
            arn = topicArn
            inputTransformer = inputTransformerOb
        }

    val targetsRequest =
        PutTargetsRequest {
            rule = ruleName
            targets = listOf(target)
            eventBusName = null
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        eventBrClient.putTargets(targetsRequest)
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[PutTargets](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `RemoveTargets`
<a name="eventbridge_RemoveTargets_kotlin_1_topic"></a>

次のコード例は、`RemoveTargets` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/eventbridge#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteTargetsFromRule(eventRuleName: String?) {
    // First, get all targets that will be deleted.
    val request =
        ListTargetsByRuleRequest {
            rule = eventRuleName
        }

    EventBridgeClient.fromEnvironment { region = "us-east-1" }.use { eventBrClient ->
        val response = eventBrClient.listTargetsByRule(request)
        val allTargets = response.targets

        // Get all targets and delete them.
        if (allTargets != null) {
            for (myTarget in allTargets) {
                val removeTargetsRequest =
                    RemoveTargetsRequest {
                        rule = eventRuleName
                        ids = listOf(myTarget.id.toString())
                    }
                eventBrClient.removeTargets(removeTargetsRequest)
                println("Successfully removed the target")
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[RemoveTargets](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# AWS Glue SDK for Kotlin を使用した の例
<a name="kotlin_1_glue_code_examples"></a>

次のコード例は、 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/glue#code-examples)での設定と実行の方法を確認してください。

```
suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <iam> <s3Path> <cron> <dbName> <crawlerName> <jobName> <scriptLocation> <locationUri>

        Where:
            iam - The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that has AWS Glue and Amazon Simple Storage Service (Amazon S3) permissions.
            s3Path - The Amazon Simple Storage Service (Amazon S3) target that contains data (for example, CSV data).
            cron - A cron expression used to specify the schedule (for example, cron(15 12 * * ? *).
            dbName - The database name. 
            crawlerName - The name of the crawler. 
            jobName - The name you assign to this job definition.
            scriptLocation - Specifies the Amazon S3 path to a script that runs a job.
            locationUri - Specifies the location of the database 
        """

    if (args.size != 8) {
        println(usage)
        exitProcess(1)
    }

    val iam = args[0]
    val s3Path = args[1]
    val cron = args[2]
    val dbName = args[3]
    val crawlerName = args[4]
    val jobName = args[5]
    val scriptLocation = args[6]
    val locationUri = args[7]

    println("About to start the AWS Glue Scenario")
    createDatabase(dbName, locationUri)
    createCrawler(iam, s3Path, cron, dbName, crawlerName)
    getCrawler(crawlerName)
    startCrawler(crawlerName)
    getDatabase(dbName)
    getGlueTables(dbName)
    createJob(jobName, iam, scriptLocation)
    startJob(jobName)
    getJobs()
    getJobRuns(jobName)
    deleteJob(jobName)
    println("*** Wait for 5 MIN so the $crawlerName is ready to be deleted")
    TimeUnit.MINUTES.sleep(5)
    deleteMyDatabase(dbName)
    deleteCrawler(crawlerName)
}

suspend fun createDatabase(
    dbName: String?,
    locationUriVal: String?,
) {
    val input =
        DatabaseInput {
            description = "Built with the AWS SDK for Kotlin"
            name = dbName
            locationUri = locationUriVal
        }

    val request =
        CreateDatabaseRequest {
            databaseInput = input
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        glueClient.createDatabase(request)
        println("The database was successfully created")
    }
}

suspend fun createCrawler(
    iam: String?,
    s3Path: String?,
    cron: String?,
    dbName: String?,
    crawlerName: String,
) {
    val s3Target =
        S3Target {
            path = s3Path
        }

    val targetList = ArrayList<S3Target>()
    targetList.add(s3Target)

    val targetOb =
        CrawlerTargets {
            s3Targets = targetList
        }

    val crawlerRequest =
        CreateCrawlerRequest {
            databaseName = dbName
            name = crawlerName
            description = "Created by the AWS Glue Java API"
            targets = targetOb
            role = iam
            schedule = cron
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        glueClient.createCrawler(crawlerRequest)
        println("$crawlerName was successfully created")
    }
}

suspend fun getCrawler(crawlerName: String?) {
    val request =
        GetCrawlerRequest {
            name = crawlerName
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.getCrawler(request)
        val role = response.crawler?.role
        println("The role associated with this crawler is $role")
    }
}

suspend fun startCrawler(crawlerName: String) {
    val crawlerRequest =
        StartCrawlerRequest {
            name = crawlerName
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        glueClient.startCrawler(crawlerRequest)
        println("$crawlerName was successfully started.")
    }
}

suspend fun getDatabase(databaseName: String?) {
    val request =
        GetDatabaseRequest {
            name = databaseName
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.getDatabase(request)
        val dbDesc = response.database?.description
        println("The database description is $dbDesc")
    }
}

suspend fun getGlueTables(dbName: String?) {
    val tableRequest =
        GetTablesRequest {
            databaseName = dbName
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.getTables(tableRequest)
        response.tableList?.forEach { tableName ->
            println("Table name is ${tableName.name}")
        }
    }
}

suspend fun startJob(jobNameVal: String?) {
    val runRequest =
        StartJobRunRequest {
            workerType = WorkerType.G1X
            numberOfWorkers = 10
            jobName = jobNameVal
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.startJobRun(runRequest)
        println("The job run Id is ${response.jobRunId}")
    }
}

suspend fun createJob(
    jobName: String,
    iam: String?,
    scriptLocationVal: String?,
) {
    val commandOb =
        JobCommand {
            pythonVersion = "3"
            name = "MyJob1"
            scriptLocation = scriptLocationVal
        }

    val jobRequest =
        CreateJobRequest {
            description = "A Job created by using the AWS SDK for Java V2"
            glueVersion = "2.0"
            workerType = WorkerType.G1X
            numberOfWorkers = 10
            name = jobName
            role = iam
            command = commandOb
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        glueClient.createJob(jobRequest)
        println("$jobName was successfully created.")
    }
}

suspend fun getJobs() {
    val request =
        GetJobsRequest {
            maxResults = 10
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.getJobs(request)
        response.jobs?.forEach { job ->
            println("Job name is ${job.name}")
        }
    }
}

suspend fun getJobRuns(jobNameVal: String?) {
    val request =
        GetJobRunsRequest {
            jobName = jobNameVal
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.getJobRuns(request)
        response.jobRuns?.forEach { job ->
            println("Job name is ${job.jobName}")
        }
    }
}

suspend fun deleteJob(jobNameVal: String) {
    val jobRequest =
        DeleteJobRequest {
            jobName = jobNameVal
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        glueClient.deleteJob(jobRequest)
        println("$jobNameVal was successfully deleted")
    }
}

suspend fun deleteMyDatabase(databaseName: String) {
    val request =
        DeleteDatabaseRequest {
            name = databaseName
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        glueClient.deleteDatabase(request)
        println("$databaseName was successfully deleted")
    }
}

suspend fun deleteCrawler(crawlerName: String) {
    val request =
        DeleteCrawlerRequest {
            name = crawlerName
        }
    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        glueClient.deleteCrawler(request)
        println("$crawlerName was deleted")
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateJob](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteCrawler](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteDatabase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteJob](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetCrawler](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetDatabase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetDatabases](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetJob](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetJobRun](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetJobRuns](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetTables](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListJobs](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartCrawler](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartJobRun](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_kotlin_1_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/glue#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createGlueCrawler(
    iam: String?,
    s3Path: String?,
    cron: String?,
    dbName: String?,
    crawlerName: String,
) {
    val s3Target =
        S3Target {
            path = s3Path
        }

    // Add the S3Target to a list.
    val targetList = mutableListOf<S3Target>()
    targetList.add(s3Target)

    val targetOb =
        CrawlerTargets {
            s3Targets = targetList
        }

    val request =
        CreateCrawlerRequest {
            databaseName = dbName
            name = crawlerName
            description = "Created by the AWS Glue Kotlin API"
            targets = targetOb
            role = iam
            schedule = cron
        }

    GlueClient.fromEnvironment { region = "us-west-2" }.use { glueClient ->
        glueClient.createCrawler(request)
        println("$crawlerName was successfully created")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス* の「[CreateCrawler](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_kotlin_1_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/glue#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getSpecificCrawler(crawlerName: String?) {
    val request =
        GetCrawlerRequest {
            name = crawlerName
        }
    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.getCrawler(request)
        val role = response.crawler?.role
        println("The role associated with this crawler is $role")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス* の「[GetCrawler](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_kotlin_1_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/glue#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getSpecificDatabase(databaseName: String?) {
    val request =
        GetDatabaseRequest {
            name = databaseName
        }

    GlueClient.fromEnvironment { region = "us-east-1" }.use { glueClient ->
        val response = glueClient.getDatabase(request)
        val dbDesc = response.database?.description
        println("The database description is $dbDesc")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス* の「[GetDatabase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_kotlin_1_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/glue#code-examples)での設定と実行の方法を確認してください。

```
suspend fun startSpecificCrawler(crawlerName: String?) {
    val request =
        StartCrawlerRequest {
            name = crawlerName
        }

    GlueClient.fromEnvironment { region = "us-west-2" }.use { glueClient ->
        glueClient.startCrawler(request)
        println("$crawlerName was successfully started.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス* の「[StartCrawler](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した IAM の例
<a name="kotlin_1_iam_code_examples"></a>

次のコード例は、IAM で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_kotlin_1_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーアクションをラップする関数を作成します。  

```
suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <username> <policyName> <roleName> <roleSessionName> <fileLocation> <bucketName> 

    Where:
        username - The name of the IAM user to create. 
        policyName - The name of the policy to create. 
        roleName - The name of the role to create. 
        roleSessionName - The name of the session required for the assumeRole operation. 
        fileLocation - The file location to the JSON required to create the role (see Readme). 
        bucketName - The name of the Amazon S3 bucket from which objects are read. 
    """

    if (args.size != 6) {
        println(usage)
        exitProcess(1)
    }

    val userName = args[0]
    val policyName = args[1]
    val roleName = args[2]
    val roleSessionName = args[3]
    val fileLocation = args[4]
    val bucketName = args[5]

    createUser(userName)
    println("$userName was successfully created.")

    val polArn = createPolicy(policyName)
    println("The policy $polArn was successfully created.")

    val roleArn = createRole(roleName, fileLocation)
    println("$roleArn was successfully created.")
    attachRolePolicy(roleName, polArn)

    println("*** Wait for 1 MIN so the resource is available.")
    delay(60000)
    assumeGivenRole(roleArn, roleSessionName, bucketName)

    println("*** Getting ready to delete the AWS resources.")
    deleteRole(roleName, polArn)
    deleteUser(userName)
    println("This IAM Scenario has successfully completed.")
}

suspend fun createUser(usernameVal: String?): String? {
    val request =
        CreateUserRequest {
            userName = usernameVal
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createUser(request)
        return response.user?.userName
    }
}

suspend fun createPolicy(policyNameVal: String?): String {
    val policyDocumentValue = """
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "s3:*"
                ],
                "Resource": "*"
            }
        ]
    }
    """.trimIndent()

    val request =
        CreatePolicyRequest {
            policyName = policyNameVal
            policyDocument = policyDocumentValue
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createPolicy(request)
        return response.policy?.arn.toString()
    }
}

suspend fun createRole(
    rolenameVal: String?,
    fileLocation: String?,
): String? {
    val jsonObject = fileLocation?.let { readJsonSimpleDemo(it) } as JSONObject

    val request =
        CreateRoleRequest {
            roleName = rolenameVal
            assumeRolePolicyDocument = jsonObject.toJSONString()
            description = "Created using the AWS SDK for Kotlin"
        }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createRole(request)
        return response.role?.arn
    }
}

suspend fun attachRolePolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        ListAttachedRolePoliciesRequest {
            roleName = roleNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAttachedRolePolicies(request)
        val attachedPolicies = response.attachedPolicies

        // Ensure that the policy is not attached to this role.
        val checkStatus: Int
        if (attachedPolicies != null) {
            checkStatus = checkMyList(attachedPolicies, policyArnVal)
            if (checkStatus == -1) {
                return
            }
        }

        val policyRequest =
            AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policyArnVal
            }
        iamClient.attachRolePolicy(policyRequest)
        println("Successfully attached policy $policyArnVal to role $roleNameVal")
    }
}

fun checkMyList(
    attachedPolicies: List<AttachedPolicy>,
    policyArnVal: String,
): Int {
    for (policy in attachedPolicies) {
        val polArn = policy.policyArn.toString()

        if (polArn.compareTo(policyArnVal) == 0) {
            println("The policy is already attached to this role.")
            return -1
        }
    }
    return 0
}

suspend fun assumeGivenRole(
    roleArnVal: String?,
    roleSessionNameVal: String?,
    bucketName: String,
) {
    val stsClient = StsClient.fromEnvironment { region = "us-east-1" }
    val roleRequest =
        AssumeRoleRequest {
            roleArn = roleArnVal
            roleSessionName = roleSessionNameVal
        }

    val roleResponse = stsClient.assumeRole(roleRequest)
    val myCreds = roleResponse.credentials
    val key = myCreds?.accessKeyId
    val secKey = myCreds?.secretAccessKey
    val secToken = myCreds?.sessionToken

    val staticCredentials = StaticCredentialsProvider {
        accessKeyId = key
        secretAccessKey = secKey
        sessionToken = secToken
    }

    // List all objects in an Amazon S3 bucket using the temp creds.
    val s3 = S3Client.fromEnvironment {
        region = "us-east-1"
        credentialsProvider = staticCredentials
    }

    println("Created a S3Client using temp credentials.")
    println("Listing objects in $bucketName")

    val listObjects =
        ListObjectsRequest {
            bucket = bucketName
        }

    val response = s3.listObjects(listObjects)
    response.contents?.forEach { myObject ->
        println("The name of the key is ${myObject.key}")
        println("The owner is ${myObject.owner}")
    }
}

suspend fun deleteRole(
    roleNameVal: String,
    polArn: String,
) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }

    // First the policy needs to be detached.
    val rolePolicyRequest =
        DetachRolePolicyRequest {
            policyArn = polArn
            roleName = roleNameVal
        }

    iam.detachRolePolicy(rolePolicyRequest)

    // Delete the policy.
    val request =
        DeletePolicyRequest {
            policyArn = polArn
        }

    iam.deletePolicy(request)
    println("*** Successfully deleted $polArn")

    // Delete the role.
    val roleRequest =
        DeleteRoleRequest {
            roleName = roleNameVal
        }

    iam.deleteRole(roleRequest)
    println("*** Successfully deleted $roleNameVal")
}

suspend fun deleteUser(userNameVal: String) {
    val iam = IamClient.fromEnvironment { region = "AWS_GLOBAL" }
    val request =
        DeleteUserRequest {
            userName = userNameVal
        }

    iam.deleteUser(request)
    println("*** Successfully deleted $userNameVal")
}

@Throws(java.lang.Exception::class)
fun readJsonSimpleDemo(filename: String): Any? {
    val reader = FileReader(filename)
    val jsonParser = JSONParser()
    return jsonParser.parse(reader)
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreatePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeletePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteRole](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DetachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutUserPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_kotlin_1_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun attachIAMRolePolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        ListAttachedRolePoliciesRequest {
            roleName = roleNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAttachedRolePolicies(request)
        val attachedPolicies = response.attachedPolicies

        // Ensure that the policy is not attached to this role.
        val checkStatus: Int
        if (attachedPolicies != null) {
            checkStatus = checkList(attachedPolicies, policyArnVal)
            if (checkStatus == -1) {
                return
            }
        }

        val policyRequest =
            AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policyArnVal
            }
        iamClient.attachRolePolicy(policyRequest)
        println("Successfully attached policy $policyArnVal to role $roleNameVal")
    }
}

fun checkList(
    attachedPolicies: List<AttachedPolicy>,
    policyArnVal: String,
): Int {
    for (policy in attachedPolicies) {
        val polArn = policy.policyArn.toString()

        if (polArn.compareTo(policyArnVal) == 0) {
            println("The policy is already attached to this role.")
            return -1
        }
    }
    return 0
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[AttachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_kotlin_1_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createIAMAccessKey(user: String?): String {
    val request =
        CreateAccessKeyRequest {
            userName = user
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createAccessKey(request)
        return response.accessKey?.accessKeyId.toString()
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[CreateAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_kotlin_1_topic"></a>

次のコード例は、`CreateAccountAlias` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createIAMAccountAlias(alias: String) {
    val request =
        CreateAccountAliasRequest {
            accountAlias = alias
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.createAccountAlias(request)
        println("Successfully created account alias named $alias")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateAccountAlias](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_kotlin_1_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createIAMPolicy(policyNameVal: String?): String {
    val policyDocumentVal = """
    {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "dynamodb:DeleteItem",
                    "dynamodb:GetItem",
                    "dynamodb:PutItem",
                    "dynamodb:Scan",
                    "dynamodb:UpdateItem"
                ],
                "Resource": "*"
            }
        ]
    }
    """.trimIndent()

    val request =
        CreatePolicyRequest {
            policyName = policyNameVal
            policyDocument = policyDocumentVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createPolicy(request)
        return response.policy?.arn.toString()
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[CreatePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_kotlin_1_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createIAMUser(usernameVal: String?): String? {
    val request =
        CreateUserRequest {
            userName = usernameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createUser(request)
        return response.user?.userName
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[CreateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_kotlin_1_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteKey(
    userNameVal: String,
    accessKey: String,
) {
    val request =
        DeleteAccessKeyRequest {
            accessKeyId = accessKey
            userName = userNameVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deleteAccessKey(request)
        println("Successfully deleted access key $accessKey from $userNameVal")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeleteAccessKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_kotlin_1_topic"></a>

次のコード例は、`DeleteAccountAlias` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteIAMAccountAlias(alias: String) {
    val request =
        DeleteAccountAliasRequest {
            accountAlias = alias
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deleteAccountAlias(request)
        println("Successfully deleted account alias $alias")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteAccountAlias](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_kotlin_1_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteIAMPolicy(policyARNVal: String?) {
    val request =
        DeletePolicyRequest {
            policyArn = policyARNVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deletePolicy(request)
        println("Successfully deleted $policyARNVal")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeletePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_kotlin_1_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteIAMUser(userNameVal: String) {
    val request =
        DeleteUserRequest {
            userName = userNameVal
        }

    // To delete a user, ensure that the user's access keys are deleted first.
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.deleteUser(request)
        println("Successfully deleted user $userNameVal")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DeleteUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_kotlin_1_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun detachPolicy(
    roleNameVal: String,
    policyArnVal: String,
) {
    val request =
        DetachRolePolicyRequest {
            roleName = roleNameVal
            policyArn = policyArnVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.detachRolePolicy(request)
        println("Successfully detached policy $policyArnVal from role $roleNameVal")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[DetachRolePolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_kotlin_1_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getIAMPolicy(policyArnVal: String?) {
    val request =
        GetPolicyRequest {
            policyArn = policyArnVal
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.getPolicy(request)
        println("Successfully retrieved policy ${response.policy?.policyName}")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[GetPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_kotlin_1_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listKeys(userNameVal: String?) {
    val request =
        ListAccessKeysRequest {
            userName = userNameVal
        }
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAccessKeys(request)
        response.accessKeyMetadata?.forEach { md ->
            println("Retrieved access key ${md.accessKeyId}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[ListAccessKeys](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_kotlin_1_topic"></a>

次のコード例は、`ListAccountAliases` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAliases() {
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listAccountAliases(ListAccountAliasesRequest {})
        response.accountAliases?.forEach { alias ->
            println("Retrieved account alias $alias")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListAccountAliases](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_kotlin_1_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllUsers() {
    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.listUsers(ListUsersRequest { })
        response.users?.forEach { user ->
            println("Retrieved user ${user.userName}")
            val permissionsBoundary = user.permissionsBoundary
            if (permissionsBoundary != null) {
                println("Permissions boundary details ${permissionsBoundary.permissionsBoundaryType}")
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListUsers](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `UpdateUser`
<a name="iam_UpdateUser_kotlin_1_topic"></a>

次のコード例は、`UpdateUser` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iam#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateIAMUser(
    curName: String?,
    newName: String?,
) {
    val request =
        UpdateUserRequest {
            userName = curName
            newUserName = newName
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        iamClient.updateUser(request)
        println("Successfully updated user to $newName")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[UpdateUser](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# AWS IoT SDK for Kotlin を使用した の例
<a name="kotlin_1_iot_code_examples"></a>

次のコード例は、 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoTは
<a name="iot_Hello_kotlin_1_topic"></a>

次のコード例は、 AWS IoTの使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.iot.IotClient
import aws.sdk.kotlin.services.iot.model.ListThingsRequest

suspend fun main() {
    println("A listing of your AWS IoT Things:")
    listAllThings()
}

suspend fun listAllThings() {
    val thingsRequest =
        ListThingsRequest {
            maxResults = 10
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val response = iotClient.listThings(thingsRequest)
        val thingList = response.things
        if (thingList != null) {
            for (attribute in thingList) {
                println("Thing name ${attribute.thingName}")
                println("Thing ARN: ${attribute.thingArn}")
            }
        }
    }
}
```
+  API の詳細については、[*AWS SDK for Kotlin API リファレンス*]の「[listThings](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iot_Scenario_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT モノを作成します。
+ デバイス証明書を生成します。
+ 属性を使用して AWS IoT モノを更新します。
+ 一意のエンドポイントを返します。
+  AWS IoT 証明書を一覧表示します。
+  AWS IoT シャドウを更新します。
+ 状態情報を書き込みます。
+ ルールを作成する｡
+ ルールを一覧表示します。
+ モノの名前を使用してモノを検索します。
+  AWS IoT モノを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.iot.IotClient
import aws.sdk.kotlin.services.iot.model.Action
import aws.sdk.kotlin.services.iot.model.AttachThingPrincipalRequest
import aws.sdk.kotlin.services.iot.model.AttributePayload
import aws.sdk.kotlin.services.iot.model.CreateThingRequest
import aws.sdk.kotlin.services.iot.model.CreateTopicRuleRequest
import aws.sdk.kotlin.services.iot.model.DeleteCertificateRequest
import aws.sdk.kotlin.services.iot.model.DeleteThingRequest
import aws.sdk.kotlin.services.iot.model.DescribeEndpointRequest
import aws.sdk.kotlin.services.iot.model.DescribeThingRequest
import aws.sdk.kotlin.services.iot.model.DetachThingPrincipalRequest
import aws.sdk.kotlin.services.iot.model.ListTopicRulesRequest
import aws.sdk.kotlin.services.iot.model.SearchIndexRequest
import aws.sdk.kotlin.services.iot.model.SnsAction
import aws.sdk.kotlin.services.iot.model.TopicRulePayload
import aws.sdk.kotlin.services.iot.model.UpdateThingRequest
import aws.sdk.kotlin.services.iotdataplane.IotDataPlaneClient
import aws.sdk.kotlin.services.iotdataplane.model.GetThingShadowRequest
import aws.sdk.kotlin.services.iotdataplane.model.UpdateThingShadowRequest
import aws.smithy.kotlin.runtime.content.ByteStream
import aws.smithy.kotlin.runtime.content.toByteArray
import java.util.Scanner
import java.util.regex.Pattern
import kotlin.system.exitProcess

/**
 * Before running this Kotlin code example, ensure that your development environment
 * is set up, including configuring your credentials.
 *
 * For detailed instructions, refer to the following documentation topic:
 * [Setting Up Your Development Environment](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html)
 *
 * This code example requires an SNS topic and an IAM Role.
 * Follow the steps in the documentation to set up these resources:
 *
 * - [Creating an SNS Topic](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html#step-create-topic)
 * - [Creating an IAM Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)
 */

val DASHES = String(CharArray(80)).replace("\u0000", "-")
val TOPIC = "your-iot-topic"

suspend fun main(args: Array<String>) {
    val usage =
        """
        Usage:
            <roleARN> <snsAction> 

        Where:
            roleARN - The ARN of an IAM role that has permission to work with AWS IOT.
            snsAction  - An ARN of an SNS topic.
        
        """.trimIndent()

    if (args.size != 2) {
        println(usage)
        exitProcess(1)
    }

    var thingName: String
    val roleARN = args[0]
    val snsAction = args[1]
    val scanner = Scanner(System.`in`)

    println(DASHES)
    println("Welcome to the AWS IoT example scenario.")
    println(
        """
        This example program demonstrates various interactions with the AWS Internet of Things (IoT) Core service. 
        The program guides you through a series of steps, including creating an IoT thing, generating a device certificate, 
        updating the thing with attributes, and so on. 
        
        It utilizes the AWS SDK for Kotlin and incorporates functionality for creating and managing IoT things, certificates, rules, 
        shadows, and performing searches. The program aims to showcase AWS IoT capabilities and provides a comprehensive example for 
        developers working with AWS IoT in a Kotlin environment.
        """.trimIndent(),
    )

    print("Press Enter to continue...")
    scanner.nextLine()
    println(DASHES)

    println(DASHES)
    println("1. Create an AWS IoT thing.")
    println(
        """
        An AWS IoT thing represents a virtual entity in the AWS IoT service that can be associated with a physical device.
        """.trimIndent(),
    )
    // Prompt the user for input.
    print("Enter thing name: ")
    thingName = scanner.nextLine()
    createIoTThing(thingName)
    describeThing(thingName)
    println(DASHES)

    println(DASHES)
    println("2. Generate a device certificate.")
    println(
        """
        A device certificate performs a role in securing the communication between devices (things) and the AWS IoT platform.
        """.trimIndent(),
    )

    print("Do you want to create a certificate for $thingName? (y/n)")
    val certAns = scanner.nextLine()
    var certificateArn: String? = ""
    if (certAns != null && certAns.trim { it <= ' ' }.equals("y", ignoreCase = true)) {
        certificateArn = createCertificate()
        println("Attach the certificate to the AWS IoT thing.")
        attachCertificateToThing(thingName, certificateArn)
    } else {
        println("A device certificate was not created.")
    }
    println(DASHES)

    println(DASHES)
    println("3. Update an AWS IoT thing with Attributes.")
    println(
        """
        IoT thing attributes, represented as key-value pairs, offer a pivotal advantage in facilitating efficient data 
        management and retrieval within the AWS IoT ecosystem. 
        """.trimIndent(),
    )
    print("Press Enter to continue...")
    scanner.nextLine()
    updateThing(thingName)
    println(DASHES)

    println(DASHES)
    println("4. Return a unique endpoint specific to the Amazon Web Services account.")
    println(
        """
        An IoT Endpoint refers to a specific URL or Uniform Resource Locator that serves as the entry point for communication between IoT devices and the AWS IoT service.
        """.trimIndent(),
    )
    print("Press Enter to continue...")
    scanner.nextLine()
    val endpointUrl = describeEndpoint()
    println(DASHES)

    println(DASHES)
    println("5. List your AWS IoT certificates")
    print("Press Enter to continue...")
    scanner.nextLine()
    if (certificateArn!!.isNotEmpty()) {
        listCertificates()
    } else {
        println("You did not create a certificates. Skipping this step.")
    }
    println(DASHES)

    println(DASHES)
    println("6. Create an IoT shadow that refers to a digital representation or virtual twin of a physical IoT device")
    println(
        """
        A thing shadow refers to a feature that enables you to create a virtual representation, or "shadow," 
        of a physical device or thing. The thing shadow allows you to synchronize and control the state of a device between 
        the cloud and the device itself. and the AWS IoT service. For example, you can write and retrieve JSON data from a thing shadow. 
        
        """.trimIndent(),
    )
    print("Press Enter to continue...")
    scanner.nextLine()
    updateShawdowThing(thingName)
    println(DASHES)

    println(DASHES)
    println("7. Write out the state information, in JSON format.")
    print("Press Enter to continue...")
    scanner.nextLine()
    getPayload(thingName)
    println(DASHES)

    println(DASHES)
    println("8. Creates a rule")
    println(
        """
        Creates a rule that is an administrator-level action. 
        Any user who has permission to create rules will be able to access data processed by the rule.
        """.trimIndent(),
    )
    print("Enter Rule name: ")
    val ruleName = scanner.nextLine()
    createIoTRule(roleARN, ruleName, snsAction)
    println(DASHES)

    println(DASHES)
    println("9. List your rules.")
    print("Press Enter to continue...")
    scanner.nextLine()
    listIoTRules()
    println(DASHES)

    println(DASHES)
    println("10. Search things using the name.")
    print("Press Enter to continue...")
    scanner.nextLine()
    val queryString = "thingName:$thingName"
    searchThings(queryString)
    println(DASHES)

    println(DASHES)
    if (certificateArn.length > 0) {
        print("Do you want to detach and delete the certificate for $thingName? (y/n)")
        val delAns = scanner.nextLine()
        if (delAns != null && delAns.trim { it <= ' ' }.equals("y", ignoreCase = true)) {
            println("11. You selected to detach amd delete the certificate.")
            print("Press Enter to continue...")
            scanner.nextLine()
            detachThingPrincipal(thingName, certificateArn)
            deleteCertificate(certificateArn)
        } else {
            println("11. You selected not to delete the certificate.")
        }
    } else {
        println("11. You did not create a certificate so there is nothing to delete.")
    }
    println(DASHES)

    println(DASHES)
    println("12. Delete the AWS IoT thing.")
    print("Do you want to delete the IoT thing? (y/n)")
    val delAns = scanner.nextLine()
    if (delAns != null && delAns.trim { it <= ' ' }.equals("y", ignoreCase = true)) {
        deleteIoTThing(thingName)
    } else {
        println("The IoT thing was not deleted.")
    }
    println(DASHES)

    println(DASHES)
    println("The AWS IoT workflow has successfully completed.")
    println(DASHES)
}

suspend fun deleteIoTThing(thingNameVal: String) {
    val deleteThingRequest =
        DeleteThingRequest {
            thingName = thingNameVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.deleteThing(deleteThingRequest)
        println("Deleted $thingNameVal")
    }
}

suspend fun deleteCertificate(certificateArn: String) {
    val certificateProviderRequest =
        DeleteCertificateRequest {
            certificateId = extractCertificateId(certificateArn)
        }
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.deleteCertificate(certificateProviderRequest)
        println("$certificateArn was successfully deleted.")
    }
}

private fun extractCertificateId(certificateArn: String): String? {
    // Example ARN: arn:aws:iot:region:account-id:cert/certificate-id.
    val arnParts = certificateArn.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
    val certificateIdPart = arnParts[arnParts.size - 1]
    return certificateIdPart.substring(certificateIdPart.lastIndexOf("/") + 1)
}

suspend fun detachThingPrincipal(
    thingNameVal: String,
    certificateArn: String,
) {
    val thingPrincipalRequest =
        DetachThingPrincipalRequest {
            principal = certificateArn
            thingName = thingNameVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.detachThingPrincipal(thingPrincipalRequest)
        println("$certificateArn was successfully removed from $thingNameVal")
    }
}

suspend fun searchThings(queryStringVal: String?) {
    val searchIndexRequest =
        SearchIndexRequest {
            queryString = queryStringVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val searchIndexResponse = iotClient.searchIndex(searchIndexRequest)
        if (searchIndexResponse.things?.isEmpty() == true) {
            println("No things found.")
        } else {
            searchIndexResponse.things
                ?.forEach { thing -> println("Thing id found using search is ${thing.thingId}") }
        }
    }
}

suspend fun listIoTRules() {
    val listTopicRulesRequest = ListTopicRulesRequest {}

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val listTopicRulesResponse = iotClient.listTopicRules(listTopicRulesRequest)
        println("List of IoT rules:")
        val ruleList = listTopicRulesResponse.rules
        ruleList?.forEach { rule ->
            println("Rule name: ${rule.ruleName}")
            println("Rule ARN: ${rule.ruleArn}")
            println("--------------")
        }
    }
}

suspend fun createIoTRule(
    roleARNVal: String?,
    ruleNameVal: String?,
    action: String?,
) {
    val sqlVal = "SELECT * FROM '$TOPIC '"
    val action1 =
        SnsAction {
            targetArn = action
            roleArn = roleARNVal
        }

    val myAction =
        Action {
            sns = action1
        }

    val topicRulePayloadVal =
        TopicRulePayload {
            sql = sqlVal
            actions = listOf(myAction)
        }

    val topicRuleRequest =
        CreateTopicRuleRequest {
            ruleName = ruleNameVal
            topicRulePayload = topicRulePayloadVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.createTopicRule(topicRuleRequest)
        println("IoT rule created successfully.")
    }
}

suspend fun getPayload(thingNameVal: String?) {
    val getThingShadowRequest =
        GetThingShadowRequest {
            thingName = thingNameVal
        }

    IotDataPlaneClient.fromEnvironment { region = "us-east-1" }.use { iotPlaneClient ->
        val getThingShadowResponse = iotPlaneClient.getThingShadow(getThingShadowRequest)
        val payload = getThingShadowResponse.payload
        val payloadString = payload?.let { java.lang.String(it, Charsets.UTF_8) }
        println("Received shadow data: $payloadString")
    }
}

suspend fun listCertificates() {
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val response = iotClient.listCertificates()
        val certList = response.certificates
        certList?.forEach { cert ->
            println("Cert id: ${cert.certificateId}")
            println("Cert Arn: ${cert.certificateArn}")
        }
    }
}

suspend fun describeEndpoint(): String? {
    val request = DescribeEndpointRequest {}
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val endpointResponse = iotClient.describeEndpoint(request)
        val endpointUrl: String? = endpointResponse.endpointAddress
        val exString: String = getValue(endpointUrl)
        val fullEndpoint = "https://$exString-ats.iot.us-east-1.amazonaws.com"
        println("Full endpoint URL: $fullEndpoint")
        return fullEndpoint
    }
}

private fun getValue(input: String?): String {
    // Define a regular expression pattern for extracting the subdomain.
    val pattern = Pattern.compile("^(.*?)\\.iot\\.us-east-1\\.amazonaws\\.com")

    // Match the pattern against the input string.
    val matcher = pattern.matcher(input)

    // Check if a match is found.
    if (matcher.find()) {
        val subdomain = matcher.group(1)
        println("Extracted subdomain: $subdomain")
        return subdomain
    } else {
        println("No match found")
    }
    return ""
}

suspend fun updateThing(thingNameVal: String?) {
    val newLocation = "Office"
    val newFirmwareVersion = "v2.0"
    val attMap: MutableMap<String, String> = HashMap()
    attMap["location"] = newLocation
    attMap["firmwareVersion"] = newFirmwareVersion

    val attributePayloadVal =
        AttributePayload {
            attributes = attMap
        }

    val updateThingRequest =
        UpdateThingRequest {
            thingName = thingNameVal
            attributePayload = attributePayloadVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        // Update the IoT thing attributes.
        iotClient.updateThing(updateThingRequest)
        println("$thingNameVal attributes updated successfully.")
    }
}

suspend fun updateShawdowThing(thingNameVal: String?) {
    // Create the thing shadow state document.
    val stateDocument = "{\"state\":{\"reported\":{\"temperature\":25, \"humidity\":50}}}"
    val byteStream: ByteStream = ByteStream.fromString(stateDocument)
    val byteArray: ByteArray = byteStream.toByteArray()

    val updateThingShadowRequest =
        UpdateThingShadowRequest {
            thingName = thingNameVal
            payload = byteArray
        }

    IotDataPlaneClient.fromEnvironment { region = "us-east-1" }.use { iotPlaneClient ->
        iotPlaneClient.updateThingShadow(updateThingShadowRequest)
        println("The thing shadow was updated successfully.")
    }
}

suspend fun attachCertificateToThing(
    thingNameVal: String?,
    certificateArn: String?,
) {
    val principalRequest =
        AttachThingPrincipalRequest {
            thingName = thingNameVal
            principal = certificateArn
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.attachThingPrincipal(principalRequest)
        println("Certificate attached to $thingNameVal successfully.")
    }
}

suspend fun describeThing(thingNameVal: String) {
    val thingRequest =
        DescribeThingRequest {
            thingName = thingNameVal
        }

    // Print Thing details.
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val describeResponse = iotClient.describeThing(thingRequest)
        println("Thing details:")
        println("Thing name: ${describeResponse.thingName}")
        println("Thing ARN:  ${describeResponse.thingArn}")
    }
}

suspend fun createCertificate(): String? {
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val response = iotClient.createKeysAndCertificate()
        val certificatePem = response.certificatePem
        val certificateArn = response.certificateArn

        // Print the details.
        println("\nCertificate:")
        println(certificatePem)
        println("\nCertificate ARN:")
        println(certificateArn)
        return certificateArn
    }
}

suspend fun createIoTThing(thingNameVal: String) {
    val createThingRequest =
        CreateThingRequest {
            thingName = thingNameVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.createThing(createThingRequest)
        println("Created $thingNameVal}")
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [AttachThingPrincipal](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateKeysAndCertificate](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateTopicRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteCertificate](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteTopicRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeEndpoint](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DetachThingPrincipal](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListCertificates](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListThings](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [SearchIndex](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdateIndexingConfiguration](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdateThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `AttachThingPrincipal`
<a name="iot_AttachThingPrincipal_kotlin_1_topic"></a>

次のコード例は、`AttachThingPrincipal` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun attachCertificateToThing(
    thingNameVal: String?,
    certificateArn: String?,
) {
    val principalRequest =
        AttachThingPrincipalRequest {
            thingName = thingNameVal
            principal = certificateArn
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.attachThingPrincipal(principalRequest)
        println("Certificate attached to $thingNameVal successfully.")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[AttachThingPrincipal](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateKeysAndCertificate`
<a name="iot_CreateKeysAndCertificate_kotlin_1_topic"></a>

次のコード例は、`CreateKeysAndCertificate` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createCertificate(): String? {
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val response = iotClient.createKeysAndCertificate()
        val certificatePem = response.certificatePem
        val certificateArn = response.certificateArn

        // Print the details.
        println("\nCertificate:")
        println(certificatePem)
        println("\nCertificate ARN:")
        println(certificateArn)
        return certificateArn
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateKeysAndCertificate](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateThing`
<a name="iot_CreateThing_kotlin_1_topic"></a>

次のコード例は、`CreateThing` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createIoTThing(thingNameVal: String) {
    val createThingRequest =
        CreateThingRequest {
            thingName = thingNameVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.createThing(createThingRequest)
        println("Created $thingNameVal}")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateTopicRule`
<a name="iot_CreateTopicRule_kotlin_1_topic"></a>

次のコード例は、`CreateTopicRule` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createIoTRule(
    roleARNVal: String?,
    ruleNameVal: String?,
    action: String?,
) {
    val sqlVal = "SELECT * FROM '$TOPIC '"
    val action1 =
        SnsAction {
            targetArn = action
            roleArn = roleARNVal
        }

    val myAction =
        Action {
            sns = action1
        }

    val topicRulePayloadVal =
        TopicRulePayload {
            sql = sqlVal
            actions = listOf(myAction)
        }

    val topicRuleRequest =
        CreateTopicRuleRequest {
            ruleName = ruleNameVal
            topicRulePayload = topicRulePayloadVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.createTopicRule(topicRuleRequest)
        println("IoT rule created successfully.")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateTopicRule](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteCertificate`
<a name="iot_DeleteCertificate_kotlin_1_topic"></a>

次のコード例は、`DeleteCertificate` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteCertificate(certificateArn: String) {
    val certificateProviderRequest =
        DeleteCertificateRequest {
            certificateId = extractCertificateId(certificateArn)
        }
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.deleteCertificate(certificateProviderRequest)
        println("$certificateArn was successfully deleted.")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteCertificate](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteThing`
<a name="iot_DeleteThing_kotlin_1_topic"></a>

次のコード例は、`DeleteThing` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteIoTThing(thingNameVal: String) {
    val deleteThingRequest =
        DeleteThingRequest {
            thingName = thingNameVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.deleteThing(deleteThingRequest)
        println("Deleted $thingNameVal")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeEndpoint`
<a name="iot_DescribeEndpoint_kotlin_1_topic"></a>

次のコード例は、`DescribeEndpoint` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeEndpoint(): String? {
    val request = DescribeEndpointRequest {}
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val endpointResponse = iotClient.describeEndpoint(request)
        val endpointUrl: String? = endpointResponse.endpointAddress
        val exString: String = getValue(endpointUrl)
        val fullEndpoint = "https://$exString-ats.iot.us-east-1.amazonaws.com"
        println("Full endpoint URL: $fullEndpoint")
        return fullEndpoint
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeEndpoint](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeThing`
<a name="iot_DescribeThing_kotlin_1_topic"></a>

次のコード例は、`DescribeThing` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeThing(thingNameVal: String) {
    val thingRequest =
        DescribeThingRequest {
            thingName = thingNameVal
        }

    // Print Thing details.
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val describeResponse = iotClient.describeThing(thingRequest)
        println("Thing details:")
        println("Thing name: ${describeResponse.thingName}")
        println("Thing ARN:  ${describeResponse.thingArn}")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DetachThingPrincipal`
<a name="iot_DetachThingPrincipal_kotlin_1_topic"></a>

次のコード例は、`DetachThingPrincipal` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun detachThingPrincipal(
    thingNameVal: String,
    certificateArn: String,
) {
    val thingPrincipalRequest =
        DetachThingPrincipalRequest {
            principal = certificateArn
            thingName = thingNameVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        iotClient.detachThingPrincipal(thingPrincipalRequest)
        println("$certificateArn was successfully removed from $thingNameVal")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DetachThingPrincipal](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListCertificates`
<a name="iot_ListCertificates_kotlin_1_topic"></a>

次のコード例は、`ListCertificates` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listCertificates() {
    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val response = iotClient.listCertificates()
        val certList = response.certificates
        certList?.forEach { cert ->
            println("Cert id: ${cert.certificateId}")
            println("Cert Arn: ${cert.certificateArn}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListCertificates](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SearchIndex`
<a name="iot_SearchIndex_kotlin_1_topic"></a>

次のコード例は、`SearchIndex` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun searchThings(queryStringVal: String?) {
    val searchIndexRequest =
        SearchIndexRequest {
            queryString = queryStringVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        val searchIndexResponse = iotClient.searchIndex(searchIndexRequest)
        if (searchIndexResponse.things?.isEmpty() == true) {
            println("No things found.")
        } else {
            searchIndexResponse.things
                ?.forEach { thing -> println("Thing id found using search is ${thing.thingId}") }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[SearchIndex](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `UpdateThing`
<a name="iot_UpdateThing_kotlin_1_topic"></a>

次のコード例は、`UpdateThing` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateThing(thingNameVal: String?) {
    val newLocation = "Office"
    val newFirmwareVersion = "v2.0"
    val attMap: MutableMap<String, String> = HashMap()
    attMap["location"] = newLocation
    attMap["firmwareVersion"] = newFirmwareVersion

    val attributePayloadVal =
        AttributePayload {
            attributes = attMap
        }

    val updateThingRequest =
        UpdateThingRequest {
            thingName = thingNameVal
            attributePayload = attributePayloadVal
        }

    IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient ->
        // Update the IoT thing attributes.
        iotClient.updateThing(updateThingRequest)
        println("$thingNameVal attributes updated successfully.")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[UpdateThing](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# AWS IoT data SDK for Kotlin を使用した の例
<a name="kotlin_1_iot-data-plane_code_examples"></a>

次のコード例は、 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT data。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetThingShadow`
<a name="iot-data-plane_GetThingShadow_kotlin_1_topic"></a>

次のコード例は、`GetThingShadow` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getPayload(thingNameVal: String?) {
    val getThingShadowRequest =
        GetThingShadowRequest {
            thingName = thingNameVal
        }

    IotDataPlaneClient.fromEnvironment { region = "us-east-1" }.use { iotPlaneClient ->
        val getThingShadowResponse = iotPlaneClient.getThingShadow(getThingShadowRequest)
        val payload = getThingShadowResponse.payload
        val payloadString = payload?.let { java.lang.String(it, Charsets.UTF_8) }
        println("Received shadow data: $payloadString")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[GetThingShadow](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `UpdateThingShadow`
<a name="iot-data-plane_UpdateThingShadow_kotlin_1_topic"></a>

次のコード例は、`UpdateThingShadow` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iot#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateShawdowThing(thingNameVal: String?) {
    // Create the thing shadow state document.
    val stateDocument = "{\"state\":{\"reported\":{\"temperature\":25, \"humidity\":50}}}"
    val byteStream: ByteStream = ByteStream.fromString(stateDocument)
    val byteArray: ByteArray = byteStream.toByteArray()

    val updateThingShadowRequest =
        UpdateThingShadowRequest {
            thingName = thingNameVal
            payload = byteArray
        }

    IotDataPlaneClient.fromEnvironment { region = "us-east-1" }.use { iotPlaneClient ->
        iotPlaneClient.updateThingShadow(updateThingShadowRequest)
        println("The thing shadow was updated successfully.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[UpdateThingShadow](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# AWS IoT FleetWise SDK for Kotlin を使用した の例
<a name="kotlin_1_iotfleetwise_code_examples"></a>

次のコード例は、 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT FleetWise。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoT FleetWiseは
<a name="iotfleetwise_Hello_kotlin_1_topic"></a>

次のコード例は、 AWS IoT FleetWiseの使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */
suspend fun main() {
    listSignalCatalogs()
}

/**
 * Lists the AWS FleetWise Signal Catalogs associated with the current AWS account.
 */
suspend fun listSignalCatalogs() {
    val request = ListSignalCatalogsRequest {
        maxResults = 10
    }

    IotFleetWiseClient { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.listSignalCatalogs(request)
        val summaries = response.summaries

        if (summaries.isNullOrEmpty()) {
            println("No AWS FleetWise Signal Catalogs were found.")
        } else {
            summaries.forEach { summary ->
                with(summary) {
                    println("Catalog Name: $name")
                    println("ARN: $arn")
                    println("Created: $creationTime")
                    println("Last Modified: $lastModificationTime")
                    println("---------------")
                }
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[listSignalCatalogsPaginator](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iotfleetwise_Scenario_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 標準化されたシグナルのコレクションを作成します。
+ 車両のグループを表すフリートを作成します。
+ モデルマニフェストを作成します。
+ デコーダーマニフェストを作成します。
+ モデルマニフェストのステータスを確認します。
+ デコーダーのステータスを確認します。
+ IoT モノを作成します。
+ 車両を作成します。
+ 車両の詳細を表示します。
+  AWS IoT FleetWise アセットを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。
 AWS IoT SiteWise 機能を示すインタラクティブなシナリオを実行します。  

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */
var scanner = Scanner(System.`in`)
val DASHES = String(CharArray(80)).replace("\u0000", "-")
suspend fun main(args: Array<String>) {
    val usage =
        """
        Usage:
            <signalCatalogName> <manifestName> <fleetId> <vecName> <decName>
                        
        Where:
            signalCatalogName     - The name of the Signal Catalog to create (eg, catalog30).
            manifestName          - The name of the Vehicle Model (Model Manifest) to create (eg, manifest30).
            fleetId               - The ID of the Fleet to create (eg, fleet30).
            vecName               - The name of the Vehicle to create (eg, vehicle30).
            decName               - The name of the Decoder Manifest to create (eg, decManifest30).
                        
        """.trimIndent()

    if (args.size != 5) {
        println(usage)
        return
    }

    val signalCatalogName = args[0]
    val manifestName = args[1]
    val fleetId = args[2]
    val vecName = args[3]
    val decName = args[4]

    println(
        """
        AWS IoT FleetWise is a managed service that simplifies the 
        process of collecting, organizing, and transmitting vehicle 
        data to the cloud in near real-time. Designed for automakers 
        and fleet operators, it allows you to define vehicle models, 
        specify the exact data you want to collect (such as engine 
        temperature, speed, or battery status), and send this data to 
        AWS for analysis. By using intelligent data collection 
        techniques, IoT FleetWise reduces the volume of data 
        transmitted by filtering and transforming it at the edge, 
        helping to minimize bandwidth usage and costs. 
                
        At its core, AWS IoT FleetWise helps organizations build 
        scalable systems for vehicle data management and analytics, 
        supporting a wide variety of vehicles and sensor configurations. 
        You can define signal catalogs and decoder manifests that describe 
        how raw CAN bus signals are translated into readable data, making 
        the platform highly flexible and extensible. This allows 
        manufacturers to optimize vehicle performance, improve safety, 
        and reduce maintenance costs by gaining real-time visibility 
        into fleet operations. 
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    println(DASHES)
    runScenario(signalCatalogName, fleetId, manifestName, decName, vecName)
}

suspend fun runScenario(signalCatalogName: String, fleetIdVal: String, manifestName: String, decName: String, vecName: String) {
    println(DASHES)
    println("1. Creates a collection of standardized signals that can be reused to create vehicle models")
    waitForInputToContinue(scanner)
    val signalCatalogArn = createbranchVehicle(signalCatalogName)
    println("The collection ARN is $signalCatalogArn")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("2. Create a fleet that represents a group of vehicles")
    println(
        """
        Creating an IoT FleetWise fleet allows you to efficiently collect, 
        organize, and transfer vehicle data to the cloud, enabling real-time 
        insights into vehicle performance and health. 
                
        It helps reduce data costs by allowing you to filter and prioritize 
        only the most relevant vehicle signals, supporting advanced analytics 
        and predictive maintenance use cases.
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    val fleetid = createFleet(signalCatalogArn, fleetIdVal)
    println("The fleet Id is $fleetid")
    waitForInputToContinue(scanner)
    val nodeList = listSignalCatalogNode(signalCatalogName)
    println(DASHES)

    println(DASHES)
    println("3. Create a model manifest")
    println(
        """
        An AWS IoT FleetWise manifest defines the structure and 
        relationships of vehicle data. The model manifest specifies 
        which signals to collect and how they relate to vehicle systems, 
        while the decoder manifest defines how to decode raw vehicle data 
        into meaningful signals. 
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    val nodes = listSignalCatalogNode(signalCatalogName)
    val manifestArn = nodes?.let { createModelManifest(manifestName, signalCatalogArn, it) }
    println("The manifest ARN is $manifestArn")
    println(DASHES)

    println(DASHES)
    println("4. Create a decoder manifest")
    println(
        """
        A decoder manifest in AWS IoT FleetWise defines how raw vehicle 
        data (such as CAN signals) should be interpreted and decoded 
        into meaningful signals. It acts as a translation layer 
        that maps vehicle-specific protocols to standardized data formats
        using decoding rules. This is crucial for extracting usable
        data from different vehicle models, even when their data 
        formats vary.
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    val decArn = createDecoderManifest(decName, manifestArn)
    println("The decoder manifest ARN is $decArn")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("5. Check the status of the model manifest")
    println(
        """
        The model manifest must be in an ACTIVE state before it can be used 
        to create or update a vehicle.
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    updateModelManifest(manifestName)
    waitForModelManifestActive(manifestName)
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("6. Check the status of the decoder")
    println(
        """
        The decoder manifest must be in an ACTIVE state before it can be used 
        to create or update a vehicle.
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    updateDecoderManifest(decName)
    waitForDecoderManifestActive(decName)
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("7. Create an IoT Thing")
    println(
        """
        AWS IoT FleetWise expects an existing AWS IoT Thing with the same 
        name as the vehicle name you are passing to createVehicle method. 
        Before calling createVehicle(), you must create an AWS IoT Thing 
        with the same name using the AWS IoT Core service.
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    createThingIfNotExist(vecName)
    println(DASHES)

    println(DASHES)
    println("8. Create a vehicle")
    println(
        """
        Creating a vehicle in AWS IoT FleetWise allows you to digitally 
        represent and manage a physical vehicle within the AWS ecosystem. 
        This enables efficient ingestion, transformation, and transmission 
        of vehicle telemetry data to the cloud for analysis.
        """.trimIndent(),
    )
    waitForInputToContinue(scanner)
    createVehicle(vecName, manifestArn, decArn)
    println(DASHES)

    println(DASHES)
    println("9. Display vehicle details")
    waitForInputToContinue(scanner)
    getVehicleDetails(vecName)
    waitForInputToContinue(scanner)
    println(DASHES)
    println(DASHES)
    println("10. Delete the AWS IoT Fleetwise Assets")
    println("Would you like to delete the IoT Fleetwise Assets? (y/n)")
    val delAns = scanner.nextLine().trim()
    if (delAns.equals("y", ignoreCase = true)) {
        deleteVehicle(vecName)
        deleteDecoderManifest(decName)
        deleteModelManifest(manifestName)
        deleteFleet(fleetid)
        deleteSignalCatalog(signalCatalogName)
    }

    println(DASHES)
    println(
        """
        Thank you for checking out the AWS IoT Fleetwise Service Use demo. We hope you
        learned something new, or got some inspiration for your own apps today.
        For more AWS code examples, have a look at:
        https://docs.aws.amazon.com/code-library/latest/ug/what-is-code-library.html
        """.trimIndent(),
    )
    println(DASHES)
}

suspend fun deleteVehicle(vecName: String) {
    val request = DeleteVehicleRequest {
        vehicleName = vecName
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteVehicle(request)
        println("Vehicle $vecName was deleted successfully.")
    }
}

suspend fun getVehicleDetails(vehicleNameVal: String) {
    val request = GetVehicleRequest {
        vehicleName = vehicleNameVal
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.getVehicle(request)
        val details = mapOf(
            "vehicleName" to response.vehicleName,
            "arn" to response.arn,
            "modelManifestArn" to response.modelManifestArn,
            "decoderManifestArn" to response.decoderManifestArn,
            "attributes" to response.attributes.toString(),
            "creationTime" to response.creationTime.toString(),
            "lastModificationTime" to response.lastModificationTime.toString(),
        )

        println("Vehicle Details:")
        for ((key, value) in details) {
            println("• %-20s : %s".format(key, value))
        }
    }
}

suspend fun createVehicle(vecName: String, manifestArn: String?, decArn: String) {
    val request = CreateVehicleRequest {
        vehicleName = vecName
        modelManifestArn = manifestArn
        decoderManifestArn = decArn
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.createVehicle(request)
        println("Vehicle $vecName was created successfully.")
    }
}

/**
 * Creates an IoT Thing if it does not already exist.
 *
 * @param vecName the name of the IoT Thing to create
 */
suspend fun createThingIfNotExist(vecName: String) {
    val request = CreateThingRequest {
        thingName = vecName
    }

    IotClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.createThing(request)
        println("The $vecName IoT Thing was successfully created")
    }
}

suspend fun updateDecoderManifest(nameVal: String) {
    val request = UpdateDecoderManifestRequest {
        name = nameVal
        status = ManifestStatus.Active
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.updateDecoderManifest(request)
        println("$nameVal was successfully updated")
    }
}

/**
 * Waits for the specified model manifest to become active.
 *
 * @param decNameVal the name of the model manifest to wait for
 */
suspend fun waitForDecoderManifestActive(decNameVal: String) {
    var elapsedSeconds = 0
    var lastStatus: ManifestStatus = ManifestStatus.Draft

    print("⏳ Elapsed: 0s | Status: DRAFT")
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        while (true) {
            delay(1000)
            elapsedSeconds++
            if (elapsedSeconds % 5 == 0) {
                val request = GetDecoderManifestRequest {
                    name = decNameVal
                }

                val response = fleetwiseClient.getDecoderManifest(request)
                lastStatus = response.status ?: ManifestStatus.Draft

                when (lastStatus) {
                    ManifestStatus.Active -> {
                        print("\rElapsed: ${elapsedSeconds}s | Status: ACTIVE ✅\n")
                        return
                    }

                    ManifestStatus.Invalid -> {
                        print("\rElapsed: ${elapsedSeconds}s | Status: INVALID ❌\n")
                        throw RuntimeException("Model manifest became INVALID. Cannot proceed.")
                    }

                    else -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
                    }
                }
            } else {
                print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
            }
        }
    }
}

/**
 * Waits for the specified model manifest to become active.
 *
 * @param manifestName the name of the model manifest to wait for
 */
suspend fun waitForModelManifestActive(manifestNameVal: String) {
    var elapsedSeconds = 0
    var lastStatus: ManifestStatus = ManifestStatus.Draft

    print("⏳ Elapsed: 0s | Status: DRAFT")
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        while (true) {
            delay(1000)
            elapsedSeconds++
            if (elapsedSeconds % 5 == 0) {
                val request = GetModelManifestRequest {
                    name = manifestNameVal
                }

                val response = fleetwiseClient.getModelManifest(request)
                lastStatus = response.status ?: ManifestStatus.Draft

                when (lastStatus) {
                    ManifestStatus.Active -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: ACTIVE ✅\n")
                        return
                    }

                    ManifestStatus.Invalid -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: INVALID ❌\n")
                        throw RuntimeException("Model manifest became INVALID. Cannot proceed.")
                    }

                    else -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
                    }
                }
            } else {
                print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
            }
        }
    }
}

/**
 * Updates the model manifest.
 *
 * @param nameVal the name of the model manifest to update
 */
suspend fun updateModelManifest(nameVal: String) {
    val request = UpdateModelManifestRequest {
        name = nameVal
        status = ManifestStatus.Active
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.updateModelManifest(request)
        println("$nameVal was successfully updated")
    }
}

suspend fun deleteDecoderManifest(nameVal: String) {
    val request = DeleteDecoderManifestRequest {
        name = nameVal
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteDecoderManifest(request)
        println("$nameVal was successfully deleted")
    }
}

/**
 * Creates a new decoder manifest.
 *
 * @param decName             the name of the decoder manifest
 * @param modelManifestArnVal the ARN of the model manifest
 * @return the ARN of the decoder manifest
 */
suspend fun createDecoderManifest(decName: String, modelManifestArnVal: String?): String {
    val interfaceIdVal = "can0"

    val canInter = CanInterface {
        name = "canInterface0"
        protocolName = "CAN"
        protocolVersion = "1.0"
    }

    val networkInterface = NetworkInterface {
        interfaceId = interfaceIdVal
        type = NetworkInterfaceType.CanInterface
        canInterface = canInter
    }

    val carRpmSig = CanSignal {
        messageId = 100
        isBigEndian = false
        isSigned = false
        startBit = 16
        length = 16
        factor = 1.0
        offset = 0.0
    }

    val carSpeedSig = CanSignal {
        messageId = 101
        isBigEndian = false
        isSigned = false
        startBit = 0
        length = 16
        factor = 1.0
        offset = 0.0
    }

    val engineRpmDecoder = SignalDecoder {
        fullyQualifiedName = "Vehicle.Powertrain.EngineRPM"
        interfaceId = interfaceIdVal
        type = SignalDecoderType.CanSignal
        canSignal = carRpmSig
    }

    val vehicleSpeedDecoder = SignalDecoder {
        fullyQualifiedName = "Vehicle.Powertrain.VehicleSpeed"
        interfaceId = interfaceIdVal
        type = SignalDecoderType.CanSignal
        canSignal = carSpeedSig
    }

    val request = CreateDecoderManifestRequest {
        name = decName
        modelManifestArn = modelManifestArnVal
        networkInterfaces = listOf(networkInterface)
        signalDecoders = listOf(engineRpmDecoder, vehicleSpeedDecoder)
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createDecoderManifest(request)
        return response.arn
    }
}

/**
 * Deletes a signal catalog.
 *
 * @param name the name of the signal catalog to delete
 */
suspend fun deleteSignalCatalog(catName: String) {
    val request = DeleteSignalCatalogRequest {
        name = catName
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteSignalCatalog(request)
        println(" $catName was successfully deleted")
    }
}

/**
 * Deletes a fleet based on the provided fleet ID.
 *
 * @param fleetId the ID of the fleet to be deleted
 */
suspend fun deleteFleet(fleetIdVal: String) {
    val request = DeleteFleetRequest {
        fleetId = fleetIdVal
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteFleet(request)
        println(" $fleetIdVal was successfully deleted")
    }
}

/**
 * Deletes a model manifest.
 *
 * @param nameVal the name of the model manifest to delete
 */
suspend fun deleteModelManifest(nameVal: String) {
    val request = DeleteModelManifestRequest {
        name = nameVal
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteModelManifest(request)
        println(" $nameVal was successfully deleted")
    }
}

/**
 * Creates a model manifest.
 *
 * @param name              the name of the model manifest to create
 * @param signalCatalogArn  the Amazon Resource Name (ARN) of the signal catalog
 * @param nodes             a list of nodes to include in the model manifest
 * @return a {@link CompletableFuture} that completes with the ARN of the created model manifest
 */
suspend fun createModelManifest(nameVal: String, signalCatalogArnVal: String, nodesList: List<Node>): String {
    val fqnList: List<String> = nodesList.map { node ->
        when (node) {
            is Node.Sensor -> node.asSensor().fullyQualifiedName
            is Node.Branch -> node.asBranch().fullyQualifiedName
            else -> throw RuntimeException("Unsupported node type")
        }
    }

    val request = CreateModelManifestRequest {
        name = nameVal
        signalCatalogArn = signalCatalogArnVal
        nodes = fqnList
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createModelManifest(request)
        return response.arn
    }
}

/**
 * Lists the signal catalog nodes asynchronously.
 *
 * @param signalCatalogName the name of the signal catalog
 * @return a CompletableFuture that, when completed, contains a list of nodes in the specified signal catalog
 * @throws CompletionException if an exception occurs during the asynchronous operation
 */
suspend fun listSignalCatalogNode(signalCatalogName: String): List<Node>? {
    val request = ListSignalCatalogNodesRequest {
        name = signalCatalogName
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.listSignalCatalogNodes(request)
        return response.nodes
    }
}

/**
 * Creates a new fleet.
 *
 * @param catARN the Amazon Resource Name (ARN) of the signal catalog to associate with the fleet
 * @param fleetId the unique identifier for the fleet
 * @return the ID of the created fleet
 */
suspend fun createFleet(catARN: String, fleetIdVal: String): String {
    val fleetRequest = CreateFleetRequest {
        fleetId = fleetIdVal
        signalCatalogArn = catARN
        description = "Built using the AWS For Kotlin"
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createFleet(fleetRequest)
        return response.id
    }
}

/**
 * Creates a signal catalog.
 *
 * @param signalCatalogName the name of the signal catalog to create the branch vehicle in
 * @return the ARN (Amazon Resource Name) of the created signal catalog
 */
suspend fun createbranchVehicle(signalCatalogName: String): String {
    delay(2000) // Wait for 2 seconds
    val branchVehicle = Branch {
        fullyQualifiedName = "Vehicle"
        description = "Root branch"
    }

    val branchPowertrain = Branch {
        fullyQualifiedName = "Vehicle.Powertrain"
        description = "Powertrain branch"
    }

    val sensorRPM = Sensor {
        fullyQualifiedName = "Vehicle.Powertrain.EngineRPM"
        description = "Engine RPM"
        dataType = NodeDataType.Double
        unit = "rpm"
    }

    val sensorKM = Sensor {
        fullyQualifiedName = "Vehicle.Powertrain.VehicleSpeed"
        description = "Vehicle Speed"
        dataType = NodeDataType.Double
        unit = "km/h"
    }

    // Wrap each specific node type (Branch and Sensor) into the sealed Node class
    // so they can be included in the CreateSignalCatalogRequest.
    val myNodes = listOf(
        Node.Branch(branchVehicle),
        Node.Branch(branchPowertrain),
        Node.Sensor(sensorRPM),
        Node.Sensor(sensorKM),
    )

    val request = CreateSignalCatalogRequest {
        name = signalCatalogName
        nodes = myNodes
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createSignalCatalog(request)
        return response.arn
    }
}

private fun waitForInputToContinue(scanner: Scanner) {
    while (true) {
        println("")
        println("Enter 'c' followed by <ENTER> to continue:")
        val input = scanner.nextLine()

        if (input.trim { it <= ' ' }.equals("c", ignoreCase = true)) {
            println("Continuing with the program...")
            println("")
            break
        } else {
            println("Invalid input. Please try again.")
        }
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [createDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [createFleet](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [createModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [createSignalCatalog](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [createVehicle](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [deleteDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [deleteFleet](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [deleteModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [deleteSignalCatalog](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [deleteVehicle](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [getDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [getModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [getVehicle](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [listSignalCatalogNodes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [updateDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [updateModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `createDecoderManifest`
<a name="iotfleetwise_CreateDecoderManifest_kotlin_1_topic"></a>

次のコード例は、`createDecoderManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a new decoder manifest.
 *
 * @param decName             the name of the decoder manifest
 * @param modelManifestArnVal the ARN of the model manifest
 * @return the ARN of the decoder manifest
 */
suspend fun createDecoderManifest(decName: String, modelManifestArnVal: String?): String {
    val interfaceIdVal = "can0"

    val canInter = CanInterface {
        name = "canInterface0"
        protocolName = "CAN"
        protocolVersion = "1.0"
    }

    val networkInterface = NetworkInterface {
        interfaceId = interfaceIdVal
        type = NetworkInterfaceType.CanInterface
        canInterface = canInter
    }

    val carRpmSig = CanSignal {
        messageId = 100
        isBigEndian = false
        isSigned = false
        startBit = 16
        length = 16
        factor = 1.0
        offset = 0.0
    }

    val carSpeedSig = CanSignal {
        messageId = 101
        isBigEndian = false
        isSigned = false
        startBit = 0
        length = 16
        factor = 1.0
        offset = 0.0
    }

    val engineRpmDecoder = SignalDecoder {
        fullyQualifiedName = "Vehicle.Powertrain.EngineRPM"
        interfaceId = interfaceIdVal
        type = SignalDecoderType.CanSignal
        canSignal = carRpmSig
    }

    val vehicleSpeedDecoder = SignalDecoder {
        fullyQualifiedName = "Vehicle.Powertrain.VehicleSpeed"
        interfaceId = interfaceIdVal
        type = SignalDecoderType.CanSignal
        canSignal = carSpeedSig
    }

    val request = CreateDecoderManifestRequest {
        name = decName
        modelManifestArn = modelManifestArnVal
        networkInterfaces = listOf(networkInterface)
        signalDecoders = listOf(engineRpmDecoder, vehicleSpeedDecoder)
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createDecoderManifest(request)
        return response.arn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[createDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `createFleet`
<a name="iotfleetwise_CreateFleet_kotlin_1_topic"></a>

次のコード例は、`createFleet` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a new fleet.
 *
 * @param catARN the Amazon Resource Name (ARN) of the signal catalog to associate with the fleet
 * @param fleetId the unique identifier for the fleet
 * @return the ID of the created fleet
 */
suspend fun createFleet(catARN: String, fleetIdVal: String): String {
    val fleetRequest = CreateFleetRequest {
        fleetId = fleetIdVal
        signalCatalogArn = catARN
        description = "Built using the AWS For Kotlin"
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createFleet(fleetRequest)
        return response.id
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[createFleet](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `createModelManifest`
<a name="iotfleetwise_CreateModelManifest_kotlin_1_topic"></a>

次のコード例は、`createModelManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a model manifest.
 *
 * @param name              the name of the model manifest to create
 * @param signalCatalogArn  the Amazon Resource Name (ARN) of the signal catalog
 * @param nodes             a list of nodes to include in the model manifest
 * @return a {@link CompletableFuture} that completes with the ARN of the created model manifest
 */
suspend fun createModelManifest(nameVal: String, signalCatalogArnVal: String, nodesList: List<Node>): String {
    val fqnList: List<String> = nodesList.map { node ->
        when (node) {
            is Node.Sensor -> node.asSensor().fullyQualifiedName
            is Node.Branch -> node.asBranch().fullyQualifiedName
            else -> throw RuntimeException("Unsupported node type")
        }
    }

    val request = CreateModelManifestRequest {
        name = nameVal
        signalCatalogArn = signalCatalogArnVal
        nodes = fqnList
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createModelManifest(request)
        return response.arn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[createModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `createSignalCatalog`
<a name="iotfleetwise_CreateSignalCatalog_kotlin_1_topic"></a>

次のコード例は、`createSignalCatalog` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a signal catalog.
 *
 * @param signalCatalogName the name of the signal catalog to create the branch vehicle in
 * @return the ARN (Amazon Resource Name) of the created signal catalog
 */
suspend fun createbranchVehicle(signalCatalogName: String): String {
    delay(2000) // Wait for 2 seconds
    val branchVehicle = Branch {
        fullyQualifiedName = "Vehicle"
        description = "Root branch"
    }

    val branchPowertrain = Branch {
        fullyQualifiedName = "Vehicle.Powertrain"
        description = "Powertrain branch"
    }

    val sensorRPM = Sensor {
        fullyQualifiedName = "Vehicle.Powertrain.EngineRPM"
        description = "Engine RPM"
        dataType = NodeDataType.Double
        unit = "rpm"
    }

    val sensorKM = Sensor {
        fullyQualifiedName = "Vehicle.Powertrain.VehicleSpeed"
        description = "Vehicle Speed"
        dataType = NodeDataType.Double
        unit = "km/h"
    }

    // Wrap each specific node type (Branch and Sensor) into the sealed Node class
    // so they can be included in the CreateSignalCatalogRequest.
    val myNodes = listOf(
        Node.Branch(branchVehicle),
        Node.Branch(branchPowertrain),
        Node.Sensor(sensorRPM),
        Node.Sensor(sensorKM),
    )

    val request = CreateSignalCatalogRequest {
        name = signalCatalogName
        nodes = myNodes
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.createSignalCatalog(request)
        return response.arn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[createSignalCatalog](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `createVehicle`
<a name="iotfleetwise_CreateVehicle_kotlin_1_topic"></a>

次のコード例は、`createVehicle` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createVehicle(vecName: String, manifestArn: String?, decArn: String) {
    val request = CreateVehicleRequest {
        vehicleName = vecName
        modelManifestArn = manifestArn
        decoderManifestArn = decArn
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.createVehicle(request)
        println("Vehicle $vecName was created successfully.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[createVehicle](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `deleteDecoderManifest`
<a name="iotfleetwise_DeleteDecoderManifest_kotlin_1_topic"></a>

次のコード例は、`deleteDecoderManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteDecoderManifest(nameVal: String) {
    val request = DeleteDecoderManifestRequest {
        name = nameVal
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteDecoderManifest(request)
        println("$nameVal was successfully deleted")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[deleteDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `deleteFleet`
<a name="iotfleetwise_DeleteFleet_kotlin_1_topic"></a>

次のコード例は、`deleteFleet` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes a fleet based on the provided fleet ID.
 *
 * @param fleetId the ID of the fleet to be deleted
 */
suspend fun deleteFleet(fleetIdVal: String) {
    val request = DeleteFleetRequest {
        fleetId = fleetIdVal
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteFleet(request)
        println(" $fleetIdVal was successfully deleted")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[deleteFleet](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `deleteModelManifest`
<a name="iotfleetwise_DeleteModelManifest_kotlin_1_topic"></a>

次のコード例は、`deleteModelManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes a model manifest.
 *
 * @param nameVal the name of the model manifest to delete
 */
suspend fun deleteModelManifest(nameVal: String) {
    val request = DeleteModelManifestRequest {
        name = nameVal
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteModelManifest(request)
        println(" $nameVal was successfully deleted")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[deleteModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `deleteSignalCatalog`
<a name="iotfleetwise_DeleteSignalCatalog_kotlin_1_topic"></a>

次のコード例は、`deleteSignalCatalog` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes a signal catalog.
 *
 * @param name the name of the signal catalog to delete
 */
suspend fun deleteSignalCatalog(catName: String) {
    val request = DeleteSignalCatalogRequest {
        name = catName
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteSignalCatalog(request)
        println(" $catName was successfully deleted")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[deleteSignalCatalog](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `deleteVehicle`
<a name="iotfleetwise_DeleteVehicle_kotlin_1_topic"></a>

次のコード例は、`deleteVehicle` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteVehicle(vecName: String) {
    val request = DeleteVehicleRequest {
        vehicleName = vecName
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.deleteVehicle(request)
        println("Vehicle $vecName was deleted successfully.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[deleteVehicle](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `getDecoderManifest`
<a name="iotfleetwise_GetDecoderManifest_kotlin_1_topic"></a>

次のコード例は、`getDecoderManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Waits for the specified model manifest to become active.
 *
 * @param decNameVal the name of the model manifest to wait for
 */
suspend fun waitForDecoderManifestActive(decNameVal: String) {
    var elapsedSeconds = 0
    var lastStatus: ManifestStatus = ManifestStatus.Draft

    print("⏳ Elapsed: 0s | Status: DRAFT")
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        while (true) {
            delay(1000)
            elapsedSeconds++
            if (elapsedSeconds % 5 == 0) {
                val request = GetDecoderManifestRequest {
                    name = decNameVal
                }

                val response = fleetwiseClient.getDecoderManifest(request)
                lastStatus = response.status ?: ManifestStatus.Draft

                when (lastStatus) {
                    ManifestStatus.Active -> {
                        print("\rElapsed: ${elapsedSeconds}s | Status: ACTIVE ✅\n")
                        return
                    }

                    ManifestStatus.Invalid -> {
                        print("\rElapsed: ${elapsedSeconds}s | Status: INVALID ❌\n")
                        throw RuntimeException("Model manifest became INVALID. Cannot proceed.")
                    }

                    else -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
                    }
                }
            } else {
                print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[getDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `getModelManifest`
<a name="iotfleetwise_GetModelManifest_kotlin_1_topic"></a>

次のコード例は、`getModelManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Waits for the specified model manifest to become active.
 *
 * @param manifestName the name of the model manifest to wait for
 */
suspend fun waitForModelManifestActive(manifestNameVal: String) {
    var elapsedSeconds = 0
    var lastStatus: ManifestStatus = ManifestStatus.Draft

    print("⏳ Elapsed: 0s | Status: DRAFT")
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        while (true) {
            delay(1000)
            elapsedSeconds++
            if (elapsedSeconds % 5 == 0) {
                val request = GetModelManifestRequest {
                    name = manifestNameVal
                }

                val response = fleetwiseClient.getModelManifest(request)
                lastStatus = response.status ?: ManifestStatus.Draft

                when (lastStatus) {
                    ManifestStatus.Active -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: ACTIVE ✅\n")
                        return
                    }

                    ManifestStatus.Invalid -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: INVALID ❌\n")
                        throw RuntimeException("Model manifest became INVALID. Cannot proceed.")
                    }

                    else -> {
                        print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
                    }
                }
            } else {
                print("\r Elapsed: ${elapsedSeconds}s | Status: $lastStatus")
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[getModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `getVehicle`
<a name="iotfleetwise_GetVehicle_kotlin_1_topic"></a>

次のコード例は、`getVehicle` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getVehicleDetails(vehicleNameVal: String) {
    val request = GetVehicleRequest {
        vehicleName = vehicleNameVal
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.getVehicle(request)
        val details = mapOf(
            "vehicleName" to response.vehicleName,
            "arn" to response.arn,
            "modelManifestArn" to response.modelManifestArn,
            "decoderManifestArn" to response.decoderManifestArn,
            "attributes" to response.attributes.toString(),
            "creationTime" to response.creationTime.toString(),
            "lastModificationTime" to response.lastModificationTime.toString(),
        )

        println("Vehicle Details:")
        for ((key, value) in details) {
            println("• %-20s : %s".format(key, value))
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[getVehicle](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `listSignalCatalogNodes`
<a name="iotfleetwise_ListSignalCatalogNodes_kotlin_1_topic"></a>

次のコード例は、`listSignalCatalogNodes` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Lists the signal catalog nodes asynchronously.
 *
 * @param signalCatalogName the name of the signal catalog
 * @return a CompletableFuture that, when completed, contains a list of nodes in the specified signal catalog
 * @throws CompletionException if an exception occurs during the asynchronous operation
 */
suspend fun listSignalCatalogNode(signalCatalogName: String): List<Node>? {
    val request = ListSignalCatalogNodesRequest {
        name = signalCatalogName
    }

    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        val response = fleetwiseClient.listSignalCatalogNodes(request)
        return response.nodes
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[listSignalCatalogNodes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `updateDecoderManifest`
<a name="iotfleetwise_UpdateDecoderManifest_kotlin_1_topic"></a>

次のコード例は、`updateDecoderManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateDecoderManifest(nameVal: String) {
    val request = UpdateDecoderManifestRequest {
        name = nameVal
        status = ManifestStatus.Active
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.updateDecoderManifest(request)
        println("$nameVal was successfully updated")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[updateDecoderManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `updateModelManifest`
<a name="iotfleetwise_UpdateModelManifest_kotlin_1_topic"></a>

次のコード例は、`updateModelManifest` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/iotfleetwise#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Updates the model manifest.
 *
 * @param nameVal the name of the model manifest to update
 */
suspend fun updateModelManifest(nameVal: String) {
    val request = UpdateModelManifestRequest {
        name = nameVal
        status = ManifestStatus.Active
    }
    IotFleetWiseClient.fromEnvironment { region = "us-east-1" }.use { fleetwiseClient ->
        fleetwiseClient.updateModelManifest(request)
        println("$nameVal was successfully updated")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[updateModelManifest](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon Keyspaces の例
<a name="kotlin_1_keyspaces_code_examples"></a>

次のコード例は、Amazon Keyspaces で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Keyspaces
<a name="keyspaces_Hello_kotlin_1_topic"></a>

次のコード例は、Amazon Keyspaces の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
*/

suspend fun main() {
    listKeyspaces()
}

suspend fun listKeyspaces() {
    val keyspacesRequest =
        ListKeyspacesRequest {
            maxResults = 10
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response = keyClient.listKeyspaces(keyspacesRequest)
        response.keyspaces?.forEach { keyspace ->
            println("The name of the keyspace is ${keyspace.keyspaceName}")
        }
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[ListKeyspaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="keyspaces_Scenario_GetStartedKeyspaces_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キースペースとテーブルを作成する。テーブルスキーマにはムービーデータが保存され、ポイントインタイムリカバリが有効になっています。
+ SigV4 認証による安全な TLS 接続を使用してキースペースに接続します。
+ テーブルに対してクエリを実行します。ムービーデータを追加、取得、更新します。
+ テーブルを更新する。視聴したムービーを追跡する列を追加します。
+ テーブルを以前の状態に戻し、リソースをクリーンアップします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
/**
 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

 This example uses a secure file format to hold certificate information for
 Kotlin applications. This is required to make a connection to Amazon Keyspaces.
 For more information, see the following documentation topic:

 https://docs.aws.amazon.com/keyspaces/latest/devguide/using_java_driver.html

 This Kotlin example performs the following tasks:

 1. Create a keyspace.
 2. Check for keyspace existence.
 3. List keyspaces using a paginator.
 4. Create a table with a simple movie data schema and enable point-in-time recovery.
 5. Check for the table to be in an Active state.
 6. List all tables in the keyspace.
 7. Use a Cassandra driver to insert some records into the Movie table.
 8. Get all records from the Movie table.
 9. Get a specific Movie.
 10. Get a UTC timestamp for the current time.
 11. Update the table schema to add a ‘watched’ Boolean column.
 12. Update an item as watched.
 13. Query for items with watched = True.
 14. Restore the table back to the previous state using the timestamp.
 15. Check for completion of the restore action.
 16. Delete the table.
 17. Confirm that both tables are deleted.
 18. Delete the keyspace.
 */

/*
   Usage:
     fileName - The name of the JSON file that contains movie data. (Get this file from the GitHub repo at resources/sample_file.)
     keyspaceName - The name of the keyspace to create.
 */
val DASHES: String = String(CharArray(80)).replace("\u0000", "-")

suspend fun main() {
    val fileName = "<Replace with the JSON file that contains movie data>"
    val keyspaceName = "<Replace with the name of the keyspace to create>"
    val titleUpdate = "The Family"
    val yearUpdate = 2013
    val tableName = "MovieKotlin"
    val tableNameRestore = "MovieRestore"

    val loader = DriverConfigLoader.fromClasspath("application.conf")
    val session =
        CqlSession
            .builder()
            .withConfigLoader(loader)
            .build()

    println(DASHES)
    println("Welcome to the Amazon Keyspaces example scenario.")
    println(DASHES)

    println(DASHES)
    println("1. Create a keyspace.")
    createKeySpace(keyspaceName)
    println(DASHES)

    println(DASHES)
    delay(5000)
    println("2. Check for keyspace existence.")
    checkKeyspaceExistence(keyspaceName)
    println(DASHES)

    println(DASHES)
    println("3. List keyspaces using a paginator.")
    listKeyspacesPaginator()
    println(DASHES)

    println(DASHES)
    println("4. Create a table with a simple movie data schema and enable point-in-time recovery.")
    createTable(keyspaceName, tableName)
    println(DASHES)

    println(DASHES)
    println("5. Check for the table to be in an Active state.")
    delay(6000)
    checkTable(keyspaceName, tableName)
    println(DASHES)

    println(DASHES)
    println("6. List all tables in the keyspace.")
    listTables(keyspaceName)
    println(DASHES)

    println(DASHES)
    println("7. Use a Cassandra driver to insert some records into the Movie table.")
    delay(6000)
    loadData(session, fileName, keyspaceName)
    println(DASHES)

    println(DASHES)
    println("8. Get all records from the Movie table.")
    getMovieData(session, keyspaceName)
    println(DASHES)

    println(DASHES)
    println("9. Get a specific Movie.")
    getSpecificMovie(session, keyspaceName)
    println(DASHES)

    println(DASHES)
    println("10. Get a UTC timestamp for the current time.")
    val utc = ZonedDateTime.now(ZoneOffset.UTC)
    println("DATETIME = ${Date.from(utc.toInstant())}")
    println(DASHES)

    println(DASHES)
    println("11. Update the table schema to add a watched Boolean column.")
    updateTable(keyspaceName, tableName)
    println(DASHES)

    println(DASHES)
    println("12. Update an item as watched.")
    delay(10000) // Wait 10 seconds for the update.
    updateRecord(session, keyspaceName, titleUpdate, yearUpdate)
    println(DASHES)

    println(DASHES)
    println("13. Query for items with watched = True.")
    getWatchedData(session, keyspaceName)
    println(DASHES)

    println(DASHES)
    println("14. Restore the table back to the previous state using the timestamp.")
    println("Note that the restore operation can take up to 20 minutes.")
    restoreTable(keyspaceName, utc)
    println(DASHES)

    println(DASHES)
    println("15. Check for completion of the restore action.")
    delay(5000)
    checkRestoredTable(keyspaceName, "MovieRestore")
    println(DASHES)

    println(DASHES)
    println("16. Delete both tables.")
    deleteTable(keyspaceName, tableName)
    deleteTable(keyspaceName, tableNameRestore)
    println(DASHES)

    println(DASHES)
    println("17. Confirm that both tables are deleted.")
    checkTableDelete(keyspaceName, tableName)
    checkTableDelete(keyspaceName, tableNameRestore)
    println(DASHES)

    println(DASHES)
    println("18. Delete the keyspace.")
    deleteKeyspace(keyspaceName)
    println(DASHES)

    println(DASHES)
    println("The scenario has completed successfully.")
    println(DASHES)
}

suspend fun deleteKeyspace(keyspaceNameVal: String?) {
    val deleteKeyspaceRequest =
        DeleteKeyspaceRequest {
            keyspaceName = keyspaceNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient.deleteKeyspace(deleteKeyspaceRequest)
    }
}

suspend fun checkTableDelete(
    keyspaceNameVal: String?,
    tableNameVal: String?,
) {
    var status: String
    var response: GetTableResponse
    val tableRequest =
        GetTableRequest {
            keyspaceName = keyspaceNameVal
            tableName = tableNameVal
        }

    try {
        KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
            // Keep looping until the table cannot be found and a ResourceNotFoundException is thrown.
            while (true) {
                response = keyClient.getTable(tableRequest)
                status = response.status.toString()
                println(". The table status is $status")
                delay(500)
            }
        }
    } catch (e: ResourceNotFoundException) {
        println(e.message)
    }
    println("The table is deleted")
}

suspend fun deleteTable(
    keyspaceNameVal: String?,
    tableNameVal: String?,
) {
    val tableRequest =
        DeleteTableRequest {
            keyspaceName = keyspaceNameVal
            tableName = tableNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient.deleteTable(tableRequest)
    }
}

suspend fun checkRestoredTable(
    keyspaceNameVal: String?,
    tableNameVal: String?,
) {
    var tableStatus = false
    var status: String
    var response: GetTableResponse? = null

    val tableRequest =
        GetTableRequest {
            keyspaceName = keyspaceNameVal
            tableName = tableNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        while (!tableStatus) {
            response = keyClient.getTable(tableRequest)
            status = response!!.status.toString()
            println("The table status is $status")

            if (status.compareTo("ACTIVE") == 0) {
                tableStatus = true
            }
            delay(500)
        }

        val cols = response!!.schemaDefinition?.allColumns
        if (cols != null) {
            for (def in cols) {
                println("The column name is ${def.name}")
                println("The column type is ${def.type}")
            }
        }
    }
}

suspend fun restoreTable(
    keyspaceName: String?,
    utc: ZonedDateTime,
) {
    // Create an aws.smithy.kotlin.runtime.time.Instant value.
    val timeStamp =
        aws.smithy.kotlin.runtime.time
            .Instant(utc.toInstant())
    val restoreTableRequest =
        RestoreTableRequest {
            restoreTimestamp = timeStamp
            sourceTableName = "MovieKotlin"
            targetKeyspaceName = keyspaceName
            targetTableName = "MovieRestore"
            sourceKeyspaceName = keyspaceName
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response = keyClient.restoreTable(restoreTableRequest)
        println("The ARN of the restored table is ${response.restoredTableArn}")
    }
}

fun getWatchedData(
    session: CqlSession,
    keyspaceName: String,
) {
    val resultSet = session.execute("SELECT * FROM \"$keyspaceName\".\"MovieKotlin\" WHERE watched = true ALLOW FILTERING;")
    resultSet.forEach { item: Row ->
        println("The Movie title is ${item.getString("title")}")
        println("The Movie year is ${item.getInt("year")}")
        println("The plot is ${item.getString("plot")}")
    }
}

fun updateRecord(
    session: CqlSession,
    keySpace: String,
    titleUpdate: String?,
    yearUpdate: Int,
) {
    val sqlStatement =
        "UPDATE \"$keySpace\".\"MovieKotlin\" SET watched=true WHERE title = :k0 AND year = :k1;"
    val builder = BatchStatement.builder(DefaultBatchType.UNLOGGED)
    builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM)
    val preparedStatement = session.prepare(sqlStatement)
    builder.addStatement(
        preparedStatement
            .boundStatementBuilder()
            .setString("k0", titleUpdate)
            .setInt("k1", yearUpdate)
            .build(),
    )
    val batchStatement = builder.build()
    session.execute(batchStatement)
}

suspend fun updateTable(
    keySpace: String?,
    tableNameVal: String?,
) {
    val def =
        ColumnDefinition {
            name = "watched"
            type = "boolean"
        }

    val tableRequest =
        UpdateTableRequest {
            keyspaceName = keySpace
            tableName = tableNameVal
            addColumns = listOf(def)
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient.updateTable(tableRequest)
    }
}

fun getSpecificMovie(
    session: CqlSession,
    keyspaceName: String,
) {
    val resultSet =
        session.execute("SELECT * FROM \"$keyspaceName\".\"MovieKotlin\" WHERE title = 'The Family' ALLOW FILTERING ;")

    resultSet.forEach { item: Row ->
        println("The Movie title is ${item.getString("title")}")
        println("The Movie year is ${item.getInt("year")}")
        println("The plot is ${item.getString("plot")}")
    }
}

// Get records from the Movie table.
fun getMovieData(
    session: CqlSession,
    keyspaceName: String,
) {
    val resultSet = session.execute("SELECT * FROM \"$keyspaceName\".\"MovieKotlin\";")
    resultSet.forEach { item: Row ->
        println("The Movie title is ${item.getString("title")}")
        println("The Movie year is ${item.getInt("year")}")
        println("The plot is ${item.getString("plot")}")
    }
}

// Load data into the table.
fun loadData(
    session: CqlSession,
    fileName: String,
    keySpace: String,
) {
    val sqlStatement =
        "INSERT INTO \"$keySpace\".\"MovieKotlin\" (title, year, plot) values (:k0, :k1, :k2)"
    val parser = JsonFactory().createParser(File(fileName))
    val rootNode = ObjectMapper().readTree<JsonNode>(parser)
    val iter: Iterator<JsonNode> = rootNode.iterator()
    var currentNode: ObjectNode

    var t = 0
    while (iter.hasNext()) {
        if (t == 50) {
            break
        }

        currentNode = iter.next() as ObjectNode
        val year = currentNode.path("year").asInt()
        val title = currentNode.path("title").asText()
        val info = currentNode.path("info").toString()

        // Insert the data into the Amazon Keyspaces table.
        val builder = BatchStatement.builder(DefaultBatchType.UNLOGGED)
        builder.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM)
        val preparedStatement: PreparedStatement = session.prepare(sqlStatement)
        builder.addStatement(
            preparedStatement
                .boundStatementBuilder()
                .setString("k0", title)
                .setInt("k1", year)
                .setString("k2", info)
                .build(),
        )

        val batchStatement = builder.build()
        session.execute(batchStatement)
        t++
    }
}

suspend fun listTables(keyspaceNameVal: String?) {
    val tablesRequest =
        ListTablesRequest {
            keyspaceName = keyspaceNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient
            .listTablesPaginated(tablesRequest)
            .transform { it.tables?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println(" ARN: ${obj.resourceArn} Table name: ${obj.tableName}")
            }
    }
}

suspend fun checkTable(
    keyspaceNameVal: String?,
    tableNameVal: String?,
) {
    var tableStatus = false
    var status: String
    var response: GetTableResponse? = null

    val tableRequest =
        GetTableRequest {
            keyspaceName = keyspaceNameVal
            tableName = tableNameVal
        }
    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        while (!tableStatus) {
            response = keyClient.getTable(tableRequest)
            status = response!!.status.toString()
            println(". The table status is $status")
            if (status.compareTo("ACTIVE") == 0) {
                tableStatus = true
            }
            delay(500)
        }
        val cols: List<ColumnDefinition>? = response!!.schemaDefinition?.allColumns
        if (cols != null) {
            for (def in cols) {
                println("The column name is ${def.name}")
                println("The column type is ${def.type}")
            }
        }
    }
}

suspend fun createTable(
    keySpaceVal: String?,
    tableNameVal: String?,
) {
    // Set the columns.
    val defTitle =
        ColumnDefinition {
            name = "title"
            type = "text"
        }

    val defYear =
        ColumnDefinition {
            name = "year"
            type = "int"
        }

    val defReleaseDate =
        ColumnDefinition {
            name = "release_date"
            type = "timestamp"
        }

    val defPlot =
        ColumnDefinition {
            name = "plot"
            type = "text"
        }

    val colList = ArrayList<ColumnDefinition>()
    colList.add(defTitle)
    colList.add(defYear)
    colList.add(defReleaseDate)
    colList.add(defPlot)

    // Set the keys.
    val yearKey =
        PartitionKey {
            name = "year"
        }

    val titleKey =
        PartitionKey {
            name = "title"
        }

    val keyList = ArrayList<PartitionKey>()
    keyList.add(yearKey)
    keyList.add(titleKey)

    val schemaDefinitionOb =
        SchemaDefinition {
            partitionKeys = keyList
            allColumns = colList
        }

    val timeRecovery =
        PointInTimeRecovery {
            status = PointInTimeRecoveryStatus.Enabled
        }

    val tableRequest =
        CreateTableRequest {
            keyspaceName = keySpaceVal
            tableName = tableNameVal
            schemaDefinition = schemaDefinitionOb
            pointInTimeRecovery = timeRecovery
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response = keyClient.createTable(tableRequest)
        println("The table ARN is ${response.resourceArn}")
    }
}

suspend fun listKeyspacesPaginator() {
    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient
            .listKeyspacesPaginated(ListKeyspacesRequest {})
            .transform { it.keyspaces?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println("Name: ${obj.keyspaceName}")
            }
    }
}

suspend fun checkKeyspaceExistence(keyspaceNameVal: String?) {
    val keyspaceRequest =
        GetKeyspaceRequest {
            keyspaceName = keyspaceNameVal
        }
    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response: GetKeyspaceResponse = keyClient.getKeyspace(keyspaceRequest)
        val name = response.keyspaceName
        println("The $name KeySpace is ready")
    }
}

suspend fun createKeySpace(keyspaceNameVal: String) {
    val keyspaceRequest =
        CreateKeyspaceRequest {
            keyspaceName = keyspaceNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response = keyClient.createKeyspace(keyspaceRequest)
        println("The ARN of the KeySpace is ${response.resourceArn}")
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [CreateKeyspace](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteKeyspace](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetKeyspace](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListKeyspaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListTables](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [RestoreTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateKeyspace`
<a name="keyspaces_CreateKeyspace_kotlin_1_topic"></a>

次のコード例は、`CreateKeyspace` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createKeySpace(keyspaceNameVal: String) {
    val keyspaceRequest =
        CreateKeyspaceRequest {
            keyspaceName = keyspaceNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response = keyClient.createKeyspace(keyspaceRequest)
        println("The ARN of the KeySpace is ${response.resourceArn}")
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[CreateKeyspace](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateTable`
<a name="keyspaces_CreateTable_kotlin_1_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createTable(
    keySpaceVal: String?,
    tableNameVal: String?,
) {
    // Set the columns.
    val defTitle =
        ColumnDefinition {
            name = "title"
            type = "text"
        }

    val defYear =
        ColumnDefinition {
            name = "year"
            type = "int"
        }

    val defReleaseDate =
        ColumnDefinition {
            name = "release_date"
            type = "timestamp"
        }

    val defPlot =
        ColumnDefinition {
            name = "plot"
            type = "text"
        }

    val colList = ArrayList<ColumnDefinition>()
    colList.add(defTitle)
    colList.add(defYear)
    colList.add(defReleaseDate)
    colList.add(defPlot)

    // Set the keys.
    val yearKey =
        PartitionKey {
            name = "year"
        }

    val titleKey =
        PartitionKey {
            name = "title"
        }

    val keyList = ArrayList<PartitionKey>()
    keyList.add(yearKey)
    keyList.add(titleKey)

    val schemaDefinitionOb =
        SchemaDefinition {
            partitionKeys = keyList
            allColumns = colList
        }

    val timeRecovery =
        PointInTimeRecovery {
            status = PointInTimeRecoveryStatus.Enabled
        }

    val tableRequest =
        CreateTableRequest {
            keyspaceName = keySpaceVal
            tableName = tableNameVal
            schemaDefinition = schemaDefinitionOb
            pointInTimeRecovery = timeRecovery
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response = keyClient.createTable(tableRequest)
        println("The table ARN is ${response.resourceArn}")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteKeyspace`
<a name="keyspaces_DeleteKeyspace_kotlin_1_topic"></a>

次のコード例は、`DeleteKeyspace` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteKeyspace(keyspaceNameVal: String?) {
    val deleteKeyspaceRequest =
        DeleteKeyspaceRequest {
            keyspaceName = keyspaceNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient.deleteKeyspace(deleteKeyspaceRequest)
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[DeleteKeyspace](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteTable`
<a name="keyspaces_DeleteTable_kotlin_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteTable(
    keyspaceNameVal: String?,
    tableNameVal: String?,
) {
    val tableRequest =
        DeleteTableRequest {
            keyspaceName = keyspaceNameVal
            tableName = tableNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient.deleteTable(tableRequest)
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[DeleteTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetKeyspace`
<a name="keyspaces_GetKeyspace_kotlin_1_topic"></a>

次のコード例は、`GetKeyspace` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun checkKeyspaceExistence(keyspaceNameVal: String?) {
    val keyspaceRequest =
        GetKeyspaceRequest {
            keyspaceName = keyspaceNameVal
        }
    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response: GetKeyspaceResponse = keyClient.getKeyspace(keyspaceRequest)
        val name = response.keyspaceName
        println("The $name KeySpace is ready")
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[GetKeyspace](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetTable`
<a name="keyspaces_GetTable_kotlin_1_topic"></a>

次のコード例は、`GetTable` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun checkTable(
    keyspaceNameVal: String?,
    tableNameVal: String?,
) {
    var tableStatus = false
    var status: String
    var response: GetTableResponse? = null

    val tableRequest =
        GetTableRequest {
            keyspaceName = keyspaceNameVal
            tableName = tableNameVal
        }
    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        while (!tableStatus) {
            response = keyClient.getTable(tableRequest)
            status = response!!.status.toString()
            println(". The table status is $status")
            if (status.compareTo("ACTIVE") == 0) {
                tableStatus = true
            }
            delay(500)
        }
        val cols: List<ColumnDefinition>? = response!!.schemaDefinition?.allColumns
        if (cols != null) {
            for (def in cols) {
                println("The column name is ${def.name}")
                println("The column type is ${def.type}")
            }
        }
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[GetTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListKeyspaces`
<a name="keyspaces_ListKeyspaces_kotlin_1_topic"></a>

次のコード例は、`ListKeyspaces` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listKeyspacesPaginator() {
    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient
            .listKeyspacesPaginated(ListKeyspacesRequest {})
            .transform { it.keyspaces?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println("Name: ${obj.keyspaceName}")
            }
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[ListKeyspaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListTables`
<a name="keyspaces_ListTables_kotlin_1_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listTables(keyspaceNameVal: String?) {
    val tablesRequest =
        ListTablesRequest {
            keyspaceName = keyspaceNameVal
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient
            .listTablesPaginated(tablesRequest)
            .transform { it.tables?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println(" ARN: ${obj.resourceArn} Table name: ${obj.tableName}")
            }
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[ListTables](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `RestoreTable`
<a name="keyspaces_RestoreTable_kotlin_1_topic"></a>

次のコード例は、`RestoreTable` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun restoreTable(
    keyspaceName: String?,
    utc: ZonedDateTime,
) {
    // Create an aws.smithy.kotlin.runtime.time.Instant value.
    val timeStamp =
        aws.smithy.kotlin.runtime.time
            .Instant(utc.toInstant())
    val restoreTableRequest =
        RestoreTableRequest {
            restoreTimestamp = timeStamp
            sourceTableName = "MovieKotlin"
            targetKeyspaceName = keyspaceName
            targetTableName = "MovieRestore"
            sourceKeyspaceName = keyspaceName
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        val response = keyClient.restoreTable(restoreTableRequest)
        println("The ARN of the restored table is ${response.restoredTableArn}")
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[RestoreTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `UpdateTable`
<a name="keyspaces_UpdateTable_kotlin_1_topic"></a>

次のコード例は、`UpdateTable` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateTable(
    keySpace: String?,
    tableNameVal: String?,
) {
    val def =
        ColumnDefinition {
            name = "watched"
            type = "boolean"
        }

    val tableRequest =
        UpdateTableRequest {
            keyspaceName = keySpace
            tableName = tableNameVal
            addColumns = listOf(def)
        }

    KeyspacesClient.fromEnvironment { region = "us-east-1" }.use { keyClient ->
        keyClient.updateTable(tableRequest)
    }
}
```
+  API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の「[UpdateTable](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# AWS KMS SDK for Kotlin を使用した の例
<a name="kotlin_1_kms_code_examples"></a>

次のコード例は、 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateAlias`
<a name="kms_CreateAlias_kotlin_1_topic"></a>

次のコード例は、`CreateAlias` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createCustomAlias(
    targetKeyIdVal: String?,
    aliasNameVal: String?,
) {
    val request =
        CreateAliasRequest {
            aliasName = aliasNameVal
            targetKeyId = targetKeyIdVal
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        kmsClient.createAlias(request)
        println("$aliasNameVal was successfully created")
    }
}
```
+  API の詳細については、**「AWS SDK for Kotlin API リファレンス」の「[CreateAlias](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateGrant`
<a name="kms_CreateGrant_kotlin_1_topic"></a>

次のコード例は、`CreateGrant` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createNewGrant(
    keyIdVal: String?,
    granteePrincipalVal: String?,
    operation: String,
): String? {
    val operationOb = GrantOperation.fromValue(operation)
    val grantOperationList = ArrayList<GrantOperation>()
    grantOperationList.add(operationOb)

    val request =
        CreateGrantRequest {
            keyId = keyIdVal
            granteePrincipal = granteePrincipalVal
            operations = grantOperationList
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val response = kmsClient.createGrant(request)
        return response.grantId
    }
}
```
+  API の詳細については、[AWS SDK for Kotlin API リファレンス](https://sdk.amazonaws.com/kotlin/api/latest/index.html)の「*CreateGrant*」を参照してください。

### `CreateKey`
<a name="kms_CreateKey_kotlin_1_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createKey(keyDesc: String?): String? {
    val request =
        CreateKeyRequest {
            description = keyDesc
            customerMasterKeySpec = CustomerMasterKeySpec.SymmetricDefault
            keyUsage = KeyUsageType.fromValue("ENCRYPT_DECRYPT")
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val result = kmsClient.createKey(request)
        println("Created a customer key with id " + result.keyMetadata?.arn)
        return result.keyMetadata?.keyId
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Decrypt`
<a name="kms_Decrypt_kotlin_1_topic"></a>

次のコード例は、`Decrypt` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun encryptData(keyIdValue: String): ByteArray? {
    val text = "This is the text to encrypt by using the AWS KMS Service"
    val myBytes: ByteArray = text.toByteArray()

    val encryptRequest =
        EncryptRequest {
            keyId = keyIdValue
            plaintext = myBytes
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val response = kmsClient.encrypt(encryptRequest)
        val algorithm: String = response.encryptionAlgorithm.toString()
        println("The encryption algorithm is $algorithm")

        // Return the encrypted data.
        return response.ciphertextBlob
    }
}

suspend fun decryptData(
    encryptedDataVal: ByteArray?,
    keyIdVal: String?,
) {
    val decryptRequest =
        DecryptRequest {
            ciphertextBlob = encryptedDataVal
            keyId = keyIdVal
        }
    KmsClient { region = "us-west-2" }.use { kmsClient ->
        val decryptResponse = kmsClient.decrypt(decryptRequest)
        val myVal = decryptResponse.plaintext

        // Print the decrypted data.
        print(myVal)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[Decrypt](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeKey`
<a name="kms_DescribeKey_kotlin_1_topic"></a>

次のコード例は、`DescribeKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeSpecifcKey(keyIdVal: String?) {
    val request =
        DescribeKeyRequest {
            keyId = keyIdVal
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val response = kmsClient.describeKey(request)
        println("The key description is ${response.keyMetadata?.description}")
        println("The key ARN is ${response.keyMetadata?.arn}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DisableKey`
<a name="kms_DisableKey_kotlin_1_topic"></a>

次のコード例は、`DisableKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun disableKey(keyIdVal: String?) {
    val request =
        DisableKeyRequest {
            keyId = keyIdVal
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        kmsClient.disableKey(request)
        println("$keyIdVal was successfully disabled")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DisableKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `EnableKey`
<a name="kms_EnableKey_kotlin_1_topic"></a>

次のコード例は、`EnableKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun enableKey(keyIdVal: String?) {
    val request =
        EnableKeyRequest {
            keyId = keyIdVal
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        kmsClient.enableKey(request)
        println("$keyIdVal was successfully enabled.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[EnableKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Encrypt`
<a name="kms_Encrypt_kotlin_1_topic"></a>

次のコード例は、`Encrypt` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun encryptData(keyIdValue: String): ByteArray? {
    val text = "This is the text to encrypt by using the AWS KMS Service"
    val myBytes: ByteArray = text.toByteArray()

    val encryptRequest =
        EncryptRequest {
            keyId = keyIdValue
            plaintext = myBytes
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val response = kmsClient.encrypt(encryptRequest)
        val algorithm: String = response.encryptionAlgorithm.toString()
        println("The encryption algorithm is $algorithm")

        // Return the encrypted data.
        return response.ciphertextBlob
    }
}

suspend fun decryptData(
    encryptedDataVal: ByteArray?,
    keyIdVal: String?,
) {
    val decryptRequest =
        DecryptRequest {
            ciphertextBlob = encryptedDataVal
            keyId = keyIdVal
        }
    KmsClient { region = "us-west-2" }.use { kmsClient ->
        val decryptResponse = kmsClient.decrypt(decryptRequest)
        val myVal = decryptResponse.plaintext

        // Print the decrypted data.
        print(myVal)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[Encrypt](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListAliases`
<a name="kms_ListAliases_kotlin_1_topic"></a>

次のコード例は、`ListAliases` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllAliases() {
    val request =
        ListAliasesRequest {
            limit = 15
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val response = kmsClient.listAliases(request)
        response.aliases?.forEach { alias ->
            println("The alias name is ${alias.aliasName}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListAliases](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListGrants`
<a name="kms_ListGrants_kotlin_1_topic"></a>

次のコード例は、`ListGrants` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun displayGrantIds(keyIdVal: String?) {
    val request =
        ListGrantsRequest {
            keyId = keyIdVal
            limit = 15
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val response = kmsClient.listGrants(request)
        response.grants?.forEach { grant ->
            println("The grant Id is ${grant.grantId}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListGrants](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListKeys`
<a name="kms_ListKeys_kotlin_1_topic"></a>

次のコード例は、`ListKeys` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/kms#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllKeys() {
    val request =
        ListKeysRequest {
            limit = 15
        }

    KmsClient.fromEnvironment { region = "us-west-2" }.use { kmsClient ->
        val response = kmsClient.listKeys(request)
        response.keys?.forEach { key ->
            println("The key ARN is ${key.keyArn}")
            println("The key Id is ${key.keyId}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListKeys](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用する Lambda の例
<a name="kotlin_1_lambda_code_examples"></a>

次のコード例は、Lambda で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/lambda#code-examples)での設定と実行の方法を確認してください。

```
suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <functionName> <role> <handler> <bucketName> <updatedBucketName> <key> 

        Where:
            functionName - The name of the AWS Lambda function. 
            role - The AWS Identity and Access Management (IAM) service role that has AWS Lambda permissions. 
            handler - The fully qualified method name (for example, example.Handler::handleRequest). 
            bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the ZIP or JAR used for the Lambda function's code.
            updatedBucketName - The Amazon S3 bucket name that contains the .zip or .jar used to update the Lambda function's code. 
            key - The Amazon S3 key name that represents the .zip or .jar file (for example, LambdaHello-1.0-SNAPSHOT.jar).
            """

    if (args.size != 6) {
        println(usage)
        exitProcess(1)
    }

    val functionName = args[0]
    val role = args[1]
    val handler = args[2]
    val bucketName = args[3]
    val updatedBucketName = args[4]
    val key = args[5]

    println("Creating a Lambda function named $functionName.")
    val funArn = createScFunction(functionName, bucketName, key, handler, role)
    println("The AWS Lambda ARN is $funArn")

    // Get a specific Lambda function.
    println("Getting the $functionName AWS Lambda function.")
    getFunction(functionName)

    // List the Lambda functions.
    println("Listing all AWS Lambda functions.")
    listFunctionsSc()

    // Invoke the Lambda function.
    println("*** Invoke the Lambda function.")
    invokeFunctionSc(functionName)

    // Update the AWS Lambda function code.
    println("*** Update the Lambda function code.")
    updateFunctionCode(functionName, updatedBucketName, key)

    // println("*** Invoke the function again after updating the code.")
    invokeFunctionSc(functionName)

    // Update the AWS Lambda function configuration.
    println("Update the run time of the function.")
    updateFunctionConfiguration(functionName, handler)

    // Delete the AWS Lambda function.
    println("Delete the AWS Lambda function.")
    delFunction(functionName)
}

suspend fun createScFunction(
    myFunctionName: String,
    s3BucketName: String,
    myS3Key: String,
    myHandler: String,
    myRole: String,
): String {
    val functionCode =
        FunctionCode {
            s3Bucket = s3BucketName
            s3Key = myS3Key
        }

    val request =
        CreateFunctionRequest {
            functionName = myFunctionName
            code = functionCode
            description = "Created by the Lambda Kotlin API"
            handler = myHandler
            role = myRole
            runtime = Runtime.Java17
        }

    // Create a Lambda function using a waiter
    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        val functionResponse = awsLambda.createFunction(request)
        awsLambda.waitUntilFunctionActive {
            functionName = myFunctionName
        }
        return functionResponse.functionArn.toString()
    }
}

suspend fun getFunction(functionNameVal: String) {
    val functionRequest =
        GetFunctionRequest {
            functionName = functionNameVal
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        val response = awsLambda.getFunction(functionRequest)
        println("The runtime of this Lambda function is ${response.configuration?.runtime}")
    }
}

suspend fun listFunctionsSc() {
    val request =
        ListFunctionsRequest {
            maxItems = 10
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        val response = awsLambda.listFunctions(request)
        response.functions?.forEach { function ->
            println("The function name is ${function.functionName}")
        }
    }
}

suspend fun invokeFunctionSc(functionNameVal: String) {
    val json = """{"inputValue":"1000"}"""
    val byteArray = json.trimIndent().encodeToByteArray()
    val request =
        InvokeRequest {
            functionName = functionNameVal
            payload = byteArray
            logType = LogType.Tail
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        val res = awsLambda.invoke(request)
        println("The function payload is ${res.payload?.toString(Charsets.UTF_8)}")
    }
}

suspend fun updateFunctionCode(
    functionNameVal: String?,
    bucketName: String?,
    key: String?,
) {
    val functionCodeRequest =
        UpdateFunctionCodeRequest {
            functionName = functionNameVal
            publish = true
            s3Bucket = bucketName
            s3Key = key
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        val response = awsLambda.updateFunctionCode(functionCodeRequest)
        awsLambda.waitUntilFunctionUpdated {
            functionName = functionNameVal
        }
        println("The last modified value is " + response.lastModified)
    }
}

suspend fun updateFunctionConfiguration(
    functionNameVal: String?,
    handlerVal: String?,
) {
    val configurationRequest =
        UpdateFunctionConfigurationRequest {
            functionName = functionNameVal
            handler = handlerVal
            runtime = Runtime.Java17
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        awsLambda.updateFunctionConfiguration(configurationRequest)
    }
}

suspend fun delFunction(myFunctionName: String) {
    val request =
        DeleteFunctionRequest {
            functionName = myFunctionName
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        awsLambda.deleteFunction(request)
        println("$myFunctionName was deleted")
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteFunction](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetFunction](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Invoke](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListFunctions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdateFunctionCode](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdateFunctionConfiguration](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_kotlin_1_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/lambda#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createNewFunction(
    myFunctionName: String,
    s3BucketName: String,
    myS3Key: String,
    myHandler: String,
    myRole: String,
): String? {
    val functionCode =
        FunctionCode {
            s3Bucket = s3BucketName
            s3Key = myS3Key
        }

    val request =
        CreateFunctionRequest {
            functionName = myFunctionName
            code = functionCode
            description = "Created by the Lambda Kotlin API"
            handler = myHandler
            role = myRole
            runtime = Runtime.Java17
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        val functionResponse = awsLambda.createFunction(request)
        awsLambda.waitUntilFunctionActive {
            functionName = myFunctionName
        }
        return functionResponse.functionArn
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin の API リファレンス*」の「[CreateFunction](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteFunction`
<a name="lambda_DeleteFunction_kotlin_1_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/lambda#code-examples)での設定と実行の方法を確認してください。

```
suspend fun delLambdaFunction(myFunctionName: String) {
    val request =
        DeleteFunctionRequest {
            functionName = myFunctionName
        }

    LambdaClient { region = "us-east-1" }.use { awsLambda ->
        awsLambda.deleteFunction(request)
        println("$myFunctionName was deleted")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteFunction](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_kotlin_1_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/lambda#code-examples)での設定と実行の方法を確認してください。

```
suspend fun invokeFunction(functionNameVal: String) {
    val json = """{"inputValue":"1000"}"""
    val byteArray = json.trimIndent().encodeToByteArray()
    val request =
        InvokeRequest {
            functionName = functionNameVal
            logType = LogType.Tail
            payload = byteArray
        }

    LambdaClient { region = "us-west-2" }.use { awsLambda ->
        val res = awsLambda.invoke(request)
        println("${res.payload?.toString(Charsets.UTF_8)}")
        println("The log result is ${res.logResult}")
    }
}
```
+  API の詳細については、**「AWS SDK for Kotlin API リファレンス」の「[Invoke](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_kotlin_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Kotlin**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_pam) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

# SDK for Kotlin を使用した Amazon Location の例
<a name="kotlin_1_location_code_examples"></a>

次のコード例は、Amazon Location で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Location
<a name="location_Hello_kotlin_1_topic"></a>

次のコード例は、Amazon Location Service の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

In addition, you need to create a collection using the AWS Management
console. For information, see the following documentation.

https://docs.aws.amazon.com/location/latest/developerguide/geofence-gs.html

 */
suspend fun main(args: Array<String>) {
    val usage = """

        Usage:
            <colletionName>

        Where:
            colletionName - The Amazon location collection name. 
    """

    if (args.size != 1) {
        println(usage)
        exitProcess(0)
    }
    val colletionName = args[0]
    listGeofences(colletionName)
}

/**
 * Lists the geofences for the specified collection name.
 *
 * @param collectionName the name of the geofence collection
 */
suspend fun listGeofences(collectionName: String) {
    val request = ListGeofencesRequest {
        this.collectionName = collectionName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.listGeofences(request)
        val geofences = response.entries
        if (geofences.isNullOrEmpty()) {
            println("No Geofences found")
        } else {
            geofences.forEach { geofence ->
                println("Geofence ID: ${geofence.geofenceId}")
            }
        }
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [ListGeofenceCollections](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListGeofences](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="location_Scenario_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Location マップを作成します。
+ Amazon Location API キーを作成します。
+ マップ URL を表示します。
+ ジオフェンスコレクションを作成します。
+ ジオフェンスジオメトリを保存します。
+ トラッカーリソースを作成します。
+ デバイスの位置を更新します。
+ 指定されたデバイスの最新の位置更新を取得します。
+ ルート計算ツールを作成します。
+ シアトルとバンクーバー間の距離を決定します。
+ Amazon Location の上位レベルの API を使用します。
+ Amazon Location アセットを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */

val scanner = Scanner(System.`in`)
val DASHES = String(CharArray(80)).replace("\u0000", "-")
suspend fun main(args: Array<String>) {
    val usage = """

        Usage:    <mapName> <keyName> <collectionName> <geoId> <trackerName> <calculatorName> <deviceId>

        Where:
            mapName - The name of the map to create (e.g., "AWSMap").
            keyName - The name of the API key to create (e.g., "AWSApiKey").
            collectionName - The name of the geofence collection (e.g., "AWSLocationCollection").
            geoId - The geographic identifier used for the geofence or map (e.g., "geoId").
            trackerName - The name of the tracker (e.g., "geoTracker").
            calculatorName - The name of the route calculator (e.g., "AWSRouteCalc").
            deviceId - The ID of the device (e.g., "iPhone-112356").
    """

    if (args.size != 7) {
        println(usage)
        exitProcess(0)
    }

    val mapName = args[0]
    val keyName = args[1]
    val collectionName = args[2]
    val geoId = args[3]
    val trackerName = args[4]
    val calculatorName = args[5]
    val deviceId = args[6]

    println(
        """
    AWS Location Service is a fully managed service offered by Amazon Web Services (AWS) that
    provides location-based services for developers. This service simplifies
    the integration of location-based features into applications, making it
    easier to build and deploy location-aware applications.

    The AWS Location Service offers a range of location-based services,
    including:

    - Maps: The service provides access to high-quality maps, satellite imagery,
      and geospatial data from various providers, allowing developers to
      easily embed maps into their applications.

    - Tracking: The Location Service enables real-time tracking of mobile devices,
      assets, or other entities, allowing developers to build applications
      that can monitor the location of people, vehicles, or other objects.

    - Geocoding: The service provides the ability to convert addresses or
      location names into geographic coordinates (latitude and longitude),
      and vice versa, enabling developers to integrate location-based search
      and routing functionality into their applications.
        """.trimIndent(),
    )

    waitForInputToContinue(scanner)
    println(DASHES)
    println("1. Create an AWS Location Service map")
    println(
        """
        An AWS Location map can enhance the user experience of your
        application by providing accurate and personalized location-based
        features. For example, you could use the geocoding capabilities to
        allow users to search for and locate businesses, landmarks, or
        other points of interest within a specific region.
            
        """.trimIndent(),
    )

    waitForInputToContinue(scanner)
    val mapArn = createMap(mapName)
    println("The Map ARN is: $mapArn")
    waitForInputToContinue(scanner)
    println(DASHES)

    waitForInputToContinue(scanner)
    println("2. Create an AWS Location API key")
    println(
        """
            When you embed a map in a web app or website, the API key is
            included in the map tile URL to authenticate requests. You can
            restrict API keys to specific AWS Location operations (e.g., only
            maps, not geocoding). API keys can expire, ensuring temporary
            access control.
            
        """.trimIndent(),
    )
    val keyArn = createKey(keyName, mapArn)
    println("The Key ARN is: $keyArn")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("3. Display Map URL")
    println(
        """
        In order to get the MAP URL, you need to get the API Key value.
        You can get the key value using the AWS Management Console under
        Location Services. This operation cannot be completed using the
        AWS SDK. For more information about getting the key value, see 
        the AWS Location Documentation.
        """.trimIndent(),
    )
    val mapUrl = "https://maps.geo.aws.amazon.com/maps/v0/maps/$mapName/tiles/{z}/{x}/{y}?key={KeyValue}"
    println("Embed this URL in your Web app: $mapUrl")
    println("")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("4. Create a geofence collection, which manages and stores geofences.")
    waitForInputToContinue(scanner)
    val collectionArn: String =
        createGeofenceCollection(collectionName)
    println("The geofence collection was successfully created: $collectionArn")
    waitForInputToContinue(scanner)

    println(DASHES)
    println("5. Store a geofence geometry in a given geofence collection.")
    println(
        """
        An AWS Location geofence is a virtual boundary that defines a geographic area
        on a map. It is a useful feature for tracking the location of
        assets or monitoring the movement of objects within a specific region.
                        
        To define a geofence, you need to specify the coordinates of a
        polygon that represents the area of interest. The polygon must be
        defined in a counter-clockwise direction, meaning that the points of
        the polygon must be listed in a counter-clockwise order.
                        
        This is a requirement for the AWS Location service to correctly
        interpret the geofence and ensure that the location data is
        accurately processed within the defined area.
        """.trimIndent(),
    )

    waitForInputToContinue(scanner)
    putGeofence(collectionName, geoId)
    println("Successfully created geofence: $geoId")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("6. Create a tracker resource which lets you retrieve current and historical location of devices.")
    waitForInputToContinue(scanner)
    val trackerArn: String = createTracker(trackerName)
    println("Successfully created tracker. ARN: $trackerArn")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("7. Update the position of a device in the location tracking system.")
    println(
        """
        The AWS location service does not enforce a strict format for deviceId, but it must:
            - Be a string (case-sensitive).
            - Be 1–100 characters long.
            - Contain only:
            - Alphanumeric characters (A-Z, a-z, 0-9)
            - Underscores (_)
            - Hyphens (-)
            - Be the same ID used when sending and retrieving positions.
            
        """.trimIndent(),
    )

    waitForInputToContinue(scanner)
    updateDevicePosition(trackerName, deviceId)
    println("$deviceId was successfully updated in the location tracking system.")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("8. Retrieve the most recent position update for a specified device.")
    waitForInputToContinue(scanner)
    val response = getDevicePosition(trackerName, deviceId)
    println("Successfully fetched device position: ${response.position}")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("9. Create a route calculator.")
    waitForInputToContinue(scanner)
    val routeResponse = createRouteCalculator(calculatorName)
    println("Route calculator created successfully: ${routeResponse.calculatorArn}")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("10. Determine the distance in kilometers between Seattle and Vancouver using the route calculator.")
    waitForInputToContinue(scanner)
    val responseDis = calcDistance(calculatorName)
    println("Successfully calculated route. The distance in kilometers is ${responseDis.summary?.distance}")
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("11. Use the GeoPlacesClient to perform additional operations.")
    println(
        """
        This scenario will show use of the GeoPlacesClient that enables  
        location search and geocoding capabilities for your applications. 
                    
        We are going to use this client to perform these AWS Location tasks:
            - Reverse Geocoding (reverseGeocode): Converts geographic coordinates into addresses.
            - Place Search (searchText): Finds places based on search queries.
            - Nearby Search (searchNearby): Finds places near a specific location.
            
        """.trimIndent(),
    )

    waitForInputToContinue(scanner)
    println("First we will perform a Reverse Geocoding operation")
    waitForInputToContinue(scanner)
    reverseGeocode()

    println("Now we are going to perform a text search using coffee shop.")
    waitForInputToContinue(scanner)
    searchText("coffee shop")
    waitForInputToContinue(scanner)

    println("Now we are going to perform a nearby Search.")
    waitForInputToContinue(scanner)
    searchNearby()
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println("12. Delete the AWS Location Services resources.")
    println("Would you like to delete the AWS Location Services resources? (y/n)")
    val delAns = scanner.nextLine().trim { it <= ' ' }
    if (delAns.equals("y", ignoreCase = true)) {
        deleteMap(mapName)
        deleteKey(keyName)
        deleteGeofenceCollection(collectionName)
        deleteTracker(trackerName)
        deleteRouteCalculator(calculatorName)
    } else {
        println("The AWS resources will not be deleted.")
    }
    waitForInputToContinue(scanner)
    println(DASHES)

    println(DASHES)
    println(" This concludes the AWS Location Service scenario.")
    println(DASHES)
}

/**
 * Deletes a route calculator from the system.
 * @param calcName the name of the route calculator to delete
 */
suspend fun deleteRouteCalculator(calcName: String) {
    val calculatorRequest = DeleteRouteCalculatorRequest {
        this.calculatorName = calcName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteRouteCalculator(calculatorRequest)
        println("The route calculator $calcName was deleted.")
    }
}


/**
 * Deletes a tracker with the specified name.
 * @param trackerName the name of the tracker to be deleted
 */
suspend fun deleteTracker(trackerName: String) {
    val trackerRequest = DeleteTrackerRequest {
        this.trackerName = trackerName
    }

    LocationClient { region = "us-east-1" }.use { client ->
        client.deleteTracker(trackerRequest)
        println("The tracker $trackerName was deleted.")
    }
}


/**
 * Deletes a geofence collection.
 *
 * @param collectionName the name of the geofence collection to be deleted
 * @return a {@link CompletableFuture} that completes when the geofence collection has been deleted
 */
suspend fun deleteGeofenceCollection(collectionName: String) {
    val collectionRequest = DeleteGeofenceCollectionRequest {
        this.collectionName = collectionName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteGeofenceCollection(collectionRequest)
        println("The geofence collection $collectionName was deleted.")
    }
}

/**
 * Deletes the specified key from the key-value store.
 *
 * @param keyName the name of the key to be deleted
 */
suspend fun deleteKey(keyName: String) {
    val keyRequest = DeleteKeyRequest {
        this.keyName = keyName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteKey(keyRequest)
        println("The key $keyName was deleted.")
    }
}

/**
 * Deletes the specified key from the key-value store.
 *
 * @param keyName the name of the key to be deleted
 */
suspend fun deleteMap(mapName: String) {
    val mapRequest = DeleteMapRequest {
        this.mapName = mapName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteMap(mapRequest)
        println("The map $mapName was deleted.")
    }
}


/**
 * Performs a nearby places search based on the provided geographic coordinates (latitude and longitude).
 * The method sends an asynchronous request to search for places within a 1-kilometer radius of the specified location.
 * The results are processed and printed once the search completes successfully.
 */
suspend fun searchNearby() {
    val latitude = 37.7749
    val longitude = -122.4194
    val queryPosition = listOf(longitude, latitude)

    // Set up the request for searching nearby places.
    val request = SearchNearbyRequest {
        this.queryPosition = queryPosition
        this.queryRadius = 1000L
    }

    GeoPlacesClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.searchNearby(request)

        // Process the response and print the results.
        response.resultItems?.forEach { result ->
            println("Title: ${result.title}")
            println("Address: ${result.address?.label}")
            println("Distance: ${result.distance} meters")
            println("-------------------------")
        }
    }
}


/**
 * Searches for a place using the provided search query and prints the detailed information of the first result.
 *
 * @param searchQuery the search query to be used for the place search (ex, coffee shop)
 */
suspend fun searchText(searchQuery: String) {
    val latitude = 37.7749
    val longitude = -122.4194
    val queryPosition = listOf(longitude, latitude)

    val request = SearchTextRequest {
        this.queryText = searchQuery
        this.biasPosition = queryPosition
    }

    GeoPlacesClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.searchText(request)

        response.resultItems?.firstOrNull()?.let { result ->
            val placeId = result.placeId // Get Place ID
            println("Found Place with id: $placeId")

            // Fetch detailed info using getPlace.
            val getPlaceRequest = GetPlaceRequest {
                this.placeId = placeId
            }

            val placeResponse = client.getPlace(getPlaceRequest)

            // Print detailed place information.
            println("Detailed Place Information:")
            println("Title: ${placeResponse.title}")
            println("Address: ${placeResponse.address?.label}")

            // Print each food type (if any).
            placeResponse.foodTypes?.takeIf { it.isNotEmpty() }?.let {
                println("Food Types:")
                it.forEach { foodType ->
                    println("  - $foodType")
                }
            } ?: run {
                println("No food types available.")
            }

            println("-------------------------")
        }
    }
}

/**
 * Performs reverse geocoding using the AWS Geo Places API.
 * Reverse geocoding is the process of converting geographic coordinates (latitude and longitude) to a human-readable address.
 * This method uses the latitude and longitude of San Francisco as the input, and prints the resulting address.
 */
suspend fun reverseGeocode() {
    val latitude = 37.7749
    val longitude = -122.4194
    println("Use latitude 37.7749 and longitude -122.4194")

    // AWS expects [longitude, latitude].
    val queryPosition = listOf(longitude, latitude)
    val request = ReverseGeocodeRequest {
        this.queryPosition = queryPosition
    }

    GeoPlacesClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.reverseGeocode(request)
        response.resultItems?.forEach { result ->
            println("The address is: ${result.address?.label}")
        }
    }
}


/**
 * Calculates the distance between two locations.
 *
 * @param routeCalcName the name of the route calculator to use
 * @return a {@link CompletableFuture} that will complete with a {@link CalculateRouteResponse} containing the distance and estimated duration of the route
 */
suspend fun calcDistance(routeCalcName: String): CalculateRouteResponse {
    // Define coordinates for Seattle, WA and Vancouver, BC.
    val departurePosition = listOf(-122.3321, 47.6062)
    val arrivePosition = listOf(-123.1216, 49.2827)

    val request = CalculateRouteRequest {
        this.calculatorName = routeCalcName
        this.departurePosition = departurePosition
        this.destinationPosition = arrivePosition
        this.travelMode = TravelMode.Car // Options: Car, Truck, Walking, Bicycle
        this.distanceUnit = DistanceUnit.Kilometers // Options: Meters, Kilometers, Miles
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        return client.calculateRoute(request)
    }
}

/**
 * Creates a new route calculator with the specified name and data source.
 *
 * @param routeCalcName the name of the route calculator to be created
 */
suspend fun createRouteCalculator(routeCalcName: String): CreateRouteCalculatorResponse {
    val dataSource = "Esri"

    val request = CreateRouteCalculatorRequest {
        this.calculatorName = routeCalcName
        this.dataSource = dataSource
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        return client.createRouteCalculator(request)
    }
}

/**
 * Retrieves the position of a device using the provided LocationClient.
 *
 * @param trackerName The name of the tracker associated with the device.
 * @param deviceId    The ID of the device to retrieve the position for.
 */
suspend fun getDevicePosition(trackerName: String, deviceId: String): GetDevicePositionResponse {
    val request = GetDevicePositionRequest {
        this.trackerName = trackerName
        this.deviceId = deviceId
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        return client.getDevicePosition(request)
    }
}

/**
 * Updates the position of a device in the location tracking system.
 *
 * @param trackerName the name of the tracker associated with the device
 * @param deviceId    the unique identifier of the device
 */
suspend fun updateDevicePosition(trackerName: String, deviceId: String) {
    val latitude = 37.7749
    val longitude = -122.4194

    val positionUpdate = DevicePositionUpdate {
        this.deviceId = deviceId
        sampleTime = aws.smithy.kotlin.runtime.time.Instant.now() // Timestamp of position update.
        position = listOf(longitude, latitude) // AWS requires [longitude, latitude]
    }

    val request = BatchUpdateDevicePositionRequest {
        this.trackerName = trackerName
        updates = listOf(positionUpdate)
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.batchUpdateDevicePosition(request)
    }
}

/**
 * Creates a new tracker resource in your AWS account, which you can use to track the location of devices.
 *
 * @param trackerName the name of the tracker to be created
 * @return a {@link CompletableFuture} that, when completed, will contain the Amazon Resource Name (ARN) of the created tracker
 */
suspend fun createTracker(trackerName: String): String {
    val trackerRequest = CreateTrackerRequest {
        description = "Created using the Kotlin SDK"
        this.trackerName = trackerName
        positionFiltering = PositionFiltering.TimeBased // Options: TimeBased, DistanceBased, AccuracyBased
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createTracker(trackerRequest)
        return response.trackerArn
    }
}

/**
 * Adds a new geofence to the specified collection.
 *
 * @param collectionName the name of the geofence collection to add the geofence to
 * @param geoId          the unique identifier for the geofence
 */
suspend fun putGeofence(collectionName: String, geoId: String) {
    val geofenceGeometry = GeofenceGeometry {
        polygon = listOf(
            listOf(
                listOf(-122.3381, 47.6101),
                listOf(-122.3281, 47.6101),
                listOf(-122.3281, 47.6201),
                listOf(-122.3381, 47.6201),
                listOf(-122.3381, 47.6101),
            ),
        )
    }

    val geofenceRequest = PutGeofenceRequest {
        this.collectionName = collectionName
        this.geofenceId = geoId
        this.geometry = geofenceGeometry
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.putGeofence(geofenceRequest)
    }
}

/**
 * Creates a new geofence collection.
 *
 * @param collectionName the name of the geofence collection to be created
 */
suspend fun createGeofenceCollection(collectionName: String): String {
    val collectionRequest = CreateGeofenceCollectionRequest {
        this.collectionName = collectionName
        description = "Created by using the AWS SDK for Kotlin"
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createGeofenceCollection(collectionRequest)
        return response.collectionArn
    }
}

/**
 * Creates a new API key with the specified name and restrictions.
 *
 * @param keyName the name of the API key to be created
 * @param mapArn  the Amazon Resource Name (ARN) of the map resource to which the API key will be associated
 * @return the Amazon Resource Name (ARN) of the created API key
 */
suspend fun createKey(keyName: String, mapArn: String): String {
    val keyRestrictions = ApiKeyRestrictions {
        allowActions = listOf("geo:GetMap*")
        allowResources = listOf(mapArn)
    }

    val request = CreateKeyRequest {
        this.keyName = keyName
        this.restrictions = keyRestrictions
        noExpiry = true
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createKey(request)
        return response.keyArn
    }
}

/**
 * Creates a new map with the specified name and configuration.
 *
 * @param mapName the name of the map to be created
 * @return he Amazon Resource Name (ARN) of the created map
 */
suspend fun createMap(mapName: String): String {
    val configuration = MapConfiguration {
        style = "VectorEsriNavigation"
    }

    val mapRequest = CreateMapRequest {
        this.mapName = mapName
        this.configuration = configuration
        description = "A map created using the Kotlin SDK"
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createMap(mapRequest)
        return response.mapArn
    }
}

fun waitForInputToContinue(scanner: Scanner) {
    while (true) {
        println("")
        println("Enter 'c' followed by <ENTER> to continue:")
        val input = scanner.nextLine()
        if (input.trim { it <= ' ' }.equals("c", ignoreCase = true)) {
            println("Continuing with the program...")
            println("")
            break
        } else {
            println("Invalid input. Please try again.")
        }
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [BatchUpdateDevicePosition](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CalculateRoute](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateGeofenceCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateMap](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateRouteCalculator](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateTracker](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteGeofenceCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteMap](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteRouteCalculator](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteTracker](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetDevicePosition](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutGeofence](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `BatchUpdateDevicePosition`
<a name="location_BatchUpdateDevicePosition_kotlin_1_topic"></a>

次のコード例は、`BatchUpdateDevicePosition` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Updates the position of a device in the location tracking system.
 *
 * @param trackerName the name of the tracker associated with the device
 * @param deviceId    the unique identifier of the device
 */
suspend fun updateDevicePosition(trackerName: String, deviceId: String) {
    val latitude = 37.7749
    val longitude = -122.4194

    val positionUpdate = DevicePositionUpdate {
        this.deviceId = deviceId
        sampleTime = aws.smithy.kotlin.runtime.time.Instant.now() // Timestamp of position update.
        position = listOf(longitude, latitude) // AWS requires [longitude, latitude]
    }

    val request = BatchUpdateDevicePositionRequest {
        this.trackerName = trackerName
        updates = listOf(positionUpdate)
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.batchUpdateDevicePosition(request)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[BatchUpdateDevicePosition](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CalculateRoute`
<a name="location_CalculateRoute_kotlin_1_topic"></a>

次のコード例は、`CalculateRoute` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Calculates the distance between two locations.
 *
 * @param routeCalcName the name of the route calculator to use
 * @return a {@link CompletableFuture} that will complete with a {@link CalculateRouteResponse} containing the distance and estimated duration of the route
 */
suspend fun calcDistance(routeCalcName: String): CalculateRouteResponse {
    // Define coordinates for Seattle, WA and Vancouver, BC.
    val departurePosition = listOf(-122.3321, 47.6062)
    val arrivePosition = listOf(-123.1216, 49.2827)

    val request = CalculateRouteRequest {
        this.calculatorName = routeCalcName
        this.departurePosition = departurePosition
        this.destinationPosition = arrivePosition
        this.travelMode = TravelMode.Car // Options: Car, Truck, Walking, Bicycle
        this.distanceUnit = DistanceUnit.Kilometers // Options: Meters, Kilometers, Miles
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        return client.calculateRoute(request)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CalculateRoute](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateGeofenceCollection`
<a name="location_CreateGeofenceCollection_kotlin_1_topic"></a>

次のコード例は、`CreateGeofenceCollection` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a new geofence collection.
 *
 * @param collectionName the name of the geofence collection to be created
 */
suspend fun createGeofenceCollection(collectionName: String): String {
    val collectionRequest = CreateGeofenceCollectionRequest {
        this.collectionName = collectionName
        description = "Created by using the AWS SDK for Kotlin"
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createGeofenceCollection(collectionRequest)
        return response.collectionArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateGeofenceCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateKey`
<a name="location_CreateKey_kotlin_1_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a new API key with the specified name and restrictions.
 *
 * @param keyName the name of the API key to be created
 * @param mapArn  the Amazon Resource Name (ARN) of the map resource to which the API key will be associated
 * @return the Amazon Resource Name (ARN) of the created API key
 */
suspend fun createKey(keyName: String, mapArn: String): String {
    val keyRestrictions = ApiKeyRestrictions {
        allowActions = listOf("geo:GetMap*")
        allowResources = listOf(mapArn)
    }

    val request = CreateKeyRequest {
        this.keyName = keyName
        this.restrictions = keyRestrictions
        noExpiry = true
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createKey(request)
        return response.keyArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateMap`
<a name="location_CreateMap_kotlin_1_topic"></a>

次のコード例は、`CreateMap` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a new map with the specified name and configuration.
 *
 * @param mapName the name of the map to be created
 * @return he Amazon Resource Name (ARN) of the created map
 */
suspend fun createMap(mapName: String): String {
    val configuration = MapConfiguration {
        style = "VectorEsriNavigation"
    }

    val mapRequest = CreateMapRequest {
        this.mapName = mapName
        this.configuration = configuration
        description = "A map created using the Kotlin SDK"
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createMap(mapRequest)
        return response.mapArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateMap](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateRouteCalculator`
<a name="location_CreateRouteCalculator_kotlin_1_topic"></a>

次のコード例は、`CreateRouteCalculator` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a new route calculator with the specified name and data source.
 *
 * @param routeCalcName the name of the route calculator to be created
 */
suspend fun createRouteCalculator(routeCalcName: String): CreateRouteCalculatorResponse {
    val dataSource = "Esri"

    val request = CreateRouteCalculatorRequest {
        this.calculatorName = routeCalcName
        this.dataSource = dataSource
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        return client.createRouteCalculator(request)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateRouteCalculator](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateTracker`
<a name="location_CreateTracker_kotlin_1_topic"></a>

次のコード例は、`CreateTracker` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Creates a new tracker resource in your AWS account, which you can use to track the location of devices.
 *
 * @param trackerName the name of the tracker to be created
 * @return a {@link CompletableFuture} that, when completed, will contain the Amazon Resource Name (ARN) of the created tracker
 */
suspend fun createTracker(trackerName: String): String {
    val trackerRequest = CreateTrackerRequest {
        description = "Created using the Kotlin SDK"
        this.trackerName = trackerName
        positionFiltering = PositionFiltering.TimeBased // Options: TimeBased, DistanceBased, AccuracyBased
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        val response = client.createTracker(trackerRequest)
        return response.trackerArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンスの「[CreateTracker](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。*

### `DeleteGeofenceCollection`
<a name="location_DeleteGeofenceCollection_kotlin_1_topic"></a>

次のコード例は、`DeleteGeofenceCollection` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes a geofence collection.
 *
 * @param collectionName the name of the geofence collection to be deleted
 * @return a {@link CompletableFuture} that completes when the geofence collection has been deleted
 */
suspend fun deleteGeofenceCollection(collectionName: String) {
    val collectionRequest = DeleteGeofenceCollectionRequest {
        this.collectionName = collectionName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteGeofenceCollection(collectionRequest)
        println("The geofence collection $collectionName was deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteGeofenceCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteKey`
<a name="location_DeleteKey_kotlin_1_topic"></a>

次のコード例は、`DeleteKey` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes the specified key from the key-value store.
 *
 * @param keyName the name of the key to be deleted
 */
suspend fun deleteKey(keyName: String) {
    val keyRequest = DeleteKeyRequest {
        this.keyName = keyName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteKey(keyRequest)
        println("The key $keyName was deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteKey](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteMap`
<a name="location_DeleteMap_kotlin_1_topic"></a>

次のコード例は、`DeleteMap` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes the specified key from the key-value store.
 *
 * @param keyName the name of the key to be deleted
 */
suspend fun deleteMap(mapName: String) {
    val mapRequest = DeleteMapRequest {
        this.mapName = mapName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteMap(mapRequest)
        println("The map $mapName was deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンスの「[DeleteMap](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。*

### `DeleteRouteCalculator`
<a name="location_DeleteRouteCalculator_kotlin_1_topic"></a>

次のコード例は、`DeleteRouteCalculator` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes a route calculator from the system.
 * @param calcName the name of the route calculator to delete
 */
suspend fun deleteRouteCalculator(calcName: String) {
    val calculatorRequest = DeleteRouteCalculatorRequest {
        this.calculatorName = calcName
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.deleteRouteCalculator(calculatorRequest)
        println("The route calculator $calcName was deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteRouteCalculator](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteTracker`
<a name="location_DeleteTracker_kotlin_1_topic"></a>

次のコード例は、`DeleteTracker` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Deletes a tracker with the specified name.
 * @param trackerName the name of the tracker to be deleted
 */
suspend fun deleteTracker(trackerName: String) {
    val trackerRequest = DeleteTrackerRequest {
        this.trackerName = trackerName
    }

    LocationClient { region = "us-east-1" }.use { client ->
        client.deleteTracker(trackerRequest)
        println("The tracker $trackerName was deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteTracker](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetDevicePosition`
<a name="location_GetDevicePosition_kotlin_1_topic"></a>

次のコード例は、`GetDevicePosition` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Retrieves the position of a device using the provided LocationClient.
 *
 * @param trackerName The name of the tracker associated with the device.
 * @param deviceId    The ID of the device to retrieve the position for.
 */
suspend fun getDevicePosition(trackerName: String, deviceId: String): GetDevicePositionResponse {
    val request = GetDevicePositionRequest {
        this.trackerName = trackerName
        this.deviceId = deviceId
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        return client.getDevicePosition(request)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[GetDevicePosition](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutGeofence`
<a name="location_PutGeofence_kotlin_1_topic"></a>

次のコード例は、`PutGeofence` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/location#code-examples)での設定と実行の方法を確認してください。

```
/**
 * Adds a new geofence to the specified collection.
 *
 * @param collectionName the name of the geofence collection to add the geofence to
 * @param geoId          the unique identifier for the geofence
 */
suspend fun putGeofence(collectionName: String, geoId: String) {
    val geofenceGeometry = GeofenceGeometry {
        polygon = listOf(
            listOf(
                listOf(-122.3381, 47.6101),
                listOf(-122.3281, 47.6101),
                listOf(-122.3281, 47.6201),
                listOf(-122.3381, 47.6201),
                listOf(-122.3381, 47.6101),
            ),
        )
    }

    val geofenceRequest = PutGeofenceRequest {
        this.collectionName = collectionName
        this.geofenceId = geoId
        this.geometry = geofenceGeometry
    }

    LocationClient.fromEnvironment { region = "us-east-1" }.use { client ->
        client.putGeofence(geofenceRequest)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[PutGeofence](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した MediaConvert の例
<a name="kotlin_1_mediaconvert_code_examples"></a>

次のコード例は、MediaConvert で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateJob`
<a name="mediaconvert_CreateJob_kotlin_1_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createMediaJob(
    mcClient: MediaConvertClient,
    mcRoleARN: String,
    fileInput1: String,
): String? {
    // Step 1: Describe endpoints to get the MediaConvert endpoint URL
    val describeResponse = mcClient.describeEndpoints(
        DescribeEndpointsRequest {
            maxResults = 1
        },
    )

    val endpointUrl = describeResponse.endpoints?.firstOrNull()?.url
        ?: error("No MediaConvert endpoint found")

    // Step 2: Create MediaConvert client with resolved endpoint
    val mediaConvert = MediaConvertClient.fromEnvironment {
        region = "us-west-2"
        endpointProvider = MediaConvertEndpointProvider {
            Endpoint(endpointUrl)
        }
    }

    // Output destination folder in S3 - put in 'output/' folder beside input
    val outputDestination = fileInput1.substringBeforeLast('/') + "/output/"

    // Step 3: Create the job request with minimal valid video codec settings
    val jobRequest = CreateJobRequest {
        role = mcRoleARN
        settings = JobSettings {
            inputs = listOf(
                Input {
                    fileInput = fileInput1
                },
            )
            outputGroups = listOf(
                OutputGroup {
                    outputGroupSettings = OutputGroupSettings {
                        type = OutputGroupType.FileGroupSettings
                        fileGroupSettings = FileGroupSettings {
                            destination = outputDestination
                        }
                    }
                    outputs = listOf(
                        Output {
                            containerSettings = ContainerSettings {
                                container = ContainerType.Mp4
                            }
                            videoDescription = VideoDescription {
                                width = 1280
                                height = 720
                                codecSettings = VideoCodecSettings {
                                    codec = VideoCodec.H264
                                    h264Settings = H264Settings {
                                        rateControlMode = H264RateControlMode.Qvbr
                                        qvbrSettings = H264QvbrSettings {
                                            qvbrQualityLevel = 7
                                        }
                                        maxBitrate = 5_000_000
                                        codecLevel = H264CodecLevel.Auto
                                        codecProfile = H264CodecProfile.Main
                                        framerateControl = H264FramerateControl.InitializeFromSource
                                    }
                                }
                            }
                        },
                    )
                },
            )
        }
    }

    // Step 4: Call MediaConvert to create the job
    val response = mediaConvert.createJob(jobRequest)

    // Return the job ID or null if not found
    return response.job?.id
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateJob](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetJob`
<a name="mediaconvert_GetJob_kotlin_1_topic"></a>

次のコード例は、`GetJob` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getSpecificJob(mcClient: MediaConvertClient, jobId: String) {
    // 1. Discover the correct endpoint
    val res = mcClient.describeEndpoints(DescribeEndpointsRequest { maxResults = 1 })
    var endpointUrl = res.endpoints?.firstOrNull()?.url
        ?: error(" No MediaConvert endpoint found")

    // 2. Create a new client using the endpoint
    val clientWithEndpoint = MediaConvertClient {
        region = "us-west-2"
        endpointUrl = endpointUrl
    }

    // 3. Get the job details
    val jobResponse = clientWithEndpoint.getJob(GetJobRequest { id = jobId })
    val job = jobResponse.job

    println("Job status: ${job?.status}")
    println("Job ARN: ${job?.arn}")
    println("Output group count: ${job?.settings?.outputGroups?.size}")
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[GetJob](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListJobs`
<a name="mediaconvert_ListJobs_kotlin_1_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/mediaconvert#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listCompleteJobs(mcClient: MediaConvertClient) {
    val describeEndpoints =
        DescribeEndpointsRequest {
            maxResults = 20
        }

    val res = mcClient.describeEndpoints(describeEndpoints)
    if (res.endpoints?.size!! <= 0) {
        println("Cannot find MediaConvert service endpoint URL!")
        exitProcess(0)
    }
    val endpointURL = res.endpoints!![0].url!!
    val mediaConvert =
        MediaConvertClient.fromEnvironment {
            region = "us-west-2"
            endpointProvider =
                MediaConvertEndpointProvider {
                    Endpoint(endpointURL)
                }
        }

    val jobsRequest =
        ListJobsRequest {
            maxResults = 10
            status = JobStatus.fromValue("COMPLETE")
        }

    val jobsResponse = mediaConvert.listJobs(jobsRequest)
    val jobs = jobsResponse.jobs
    if (jobs != null) {
        for (job in jobs) {
            println("The JOB ARN is ${job.arn}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListJobs](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon Pinpoint 例
<a name="kotlin_1_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateApp`
<a name="pinpoint_CreateApp_kotlin_1_topic"></a>

次のコード例は、`CreateApp` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createApplication(applicationName: String?): String? {
    val createApplicationRequestOb =
        CreateApplicationRequest {
            name = applicationName
        }

    PinpointClient.fromEnvironment { region = "us-west-2" }.use { pinpoint ->
        val result =
            pinpoint.createApp(
                CreateAppRequest {
                    createApplicationRequest = createApplicationRequestOb
                },
            )
        return result.applicationResponse?.id
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」**の「[CreateApp](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateCampaign`
<a name="pinpoint_CreateCampaign_kotlin_1_topic"></a>

次のコード例は、`CreateCampaign` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createPinCampaign(
    appId: String,
    segmentIdVal: String,
) {
    val scheduleOb =
        Schedule {
            startTime = "IMMEDIATE"
        }

    val defaultMessageOb =
        Message {
            action = Action.OpenApp
            body = "My message body"
            title = "My message title"
        }

    val messageConfigurationOb =
        MessageConfiguration {
            defaultMessage = defaultMessageOb
        }

    val writeCampaign =
        WriteCampaignRequest {
            description = "My description"
            schedule = scheduleOb
            name = "MyCampaign"
            segmentId = segmentIdVal
            messageConfiguration = messageConfigurationOb
        }

    PinpointClient.fromEnvironment { region = "us-west-2" }.use { pinpoint ->
        val result: CreateCampaignResponse =
            pinpoint.createCampaign(
                CreateCampaignRequest {
                    applicationId = appId
                    writeCampaignRequest = writeCampaign
                },
            )
        println("Campaign ID is ${result.campaignResponse?.id}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateCampaign](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateSegment`
<a name="pinpoint_CreateSegment_kotlin_1_topic"></a>

次のコード例は、`CreateSegment` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createPinpointSegment(applicationIdVal: String?): String? {
    val segmentAttributes = mutableMapOf<String, AttributeDimension>()
    val myList = mutableListOf<String>()
    myList.add("Lakers")

    val atts =
        AttributeDimension {
            attributeType = AttributeType.Inclusive
            values = myList
        }

    segmentAttributes["Team"] = atts
    val recencyDimension =
        RecencyDimension {
            duration = Duration.fromValue("DAY_30")
            recencyType = RecencyType.fromValue("ACTIVE")
        }

    val segmentBehaviors =
        SegmentBehaviors {
            recency = recencyDimension
        }

    val segmentLocation = SegmentLocation {}
    val dimensionsOb =
        SegmentDimensions {
            attributes = segmentAttributes
            behavior = segmentBehaviors
            demographic = SegmentDemographics {}
            location = segmentLocation
        }

    val writeSegmentRequestOb =
        WriteSegmentRequest {
            name = "MySegment101"
            dimensions = dimensionsOb
        }

    PinpointClient.fromEnvironment { region = "us-west-2" }.use { pinpoint ->
        val createSegmentResult: CreateSegmentResponse =
            pinpoint.createSegment(
                CreateSegmentRequest {
                    applicationId = applicationIdVal
                    writeSegmentRequest = writeSegmentRequestOb
                },
            )
        println("Segment ID is ${createSegmentResult.segmentResponse?.id}")
        return createSegmentResult.segmentResponse?.id
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateSegment](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteApp`
<a name="pinpoint_DeleteApp_kotlin_1_topic"></a>

次のコード例は、`DeleteApp` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deletePinApp(appId: String?) {
    PinpointClient.fromEnvironment { region = "us-west-2" }.use { pinpoint ->
        val result =
            pinpoint.deleteApp(
                DeleteAppRequest {
                    applicationId = appId
                },
            )
        val appName = result.applicationResponse?.name
        println("Application $appName has been deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteApp](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteEndpoint`
<a name="pinpoint_DeleteEndpoint_kotlin_1_topic"></a>

次のコード例は、`DeleteEndpoint` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deletePinEncpoint(
    appIdVal: String?,
    endpointIdVal: String?,
) {
    val deleteEndpointRequest =
        DeleteEndpointRequest {
            applicationId = appIdVal
            endpointId = endpointIdVal
        }

    PinpointClient.fromEnvironment { region = "us-west-2" }.use { pinpoint ->
        val result = pinpoint.deleteEndpoint(deleteEndpointRequest)
        val id = result.endpointResponse?.id
        println("The deleted endpoint is  $id")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteEndpoint](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetEndpoint`
<a name="pinpoint_GetEndpoint_kotlin_1_topic"></a>

次のコード例は、`GetEndpoint` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
suspend fun lookupPinpointEndpoint(
    appId: String?,
    endpoint: String?,
) {
    PinpointClient.fromEnvironment { region = "us-west-2" }.use { pinpoint ->
        val result =
            pinpoint.getEndpoint(
                GetEndpointRequest {
                    applicationId = appId
                    endpointId = endpoint
                },
            )
        val endResponse = result.endpointResponse

        // Uses the Google Gson library to pretty print the endpoint JSON.
        val gson: com.google.gson.Gson =
            GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .setPrettyPrinting()
                .create()

        val endpointJson: String = gson.toJson(endResponse)
        println(endpointJson)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[GetEndpoint](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetSegments`
<a name="pinpoint_GetSegments_kotlin_1_topic"></a>

次のコード例は、`GetSegments` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listSegs(appId: String?) {
    PinpointClient.fromEnvironment { region = "us-west-2" }.use { pinpoint ->
        val response =
            pinpoint.getSegments(
                GetSegmentsRequest {
                    applicationId = appId
                },
            )
        response.segmentsResponse?.item?.forEach { segment ->
            println("Segement id is ${segment.id}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[GetSegments](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SendMessages`
<a name="pinpoint_SendMessages_kotlin_1_topic"></a>

次のコード例は、`SendMessages` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/pinpoint#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */

val body: String =
    """
    Amazon Pinpoint test (AWS SDK for Kotlin)
            
    This email was sent through the Amazon Pinpoint Email API using the AWS SDK for Kotlin.
                            
    """.trimIndent()

suspend fun main(args: Array<String>) {
    val usage = """
    Usage: 
        <subject> <appId> <senderAddress> <toAddress>

    Where:
        subject - The email subject to use.
        senderAddress - The from address. This address has to be verified in Amazon Pinpoint in the region you're using to send email 
        toAddress - The to address. This address has to be verified in Amazon Pinpoint in the region you're using to send email 
    """

    if (args.size != 3) {
        println(usage)
        exitProcess(0)
    }

    val subject = args[0]
    val senderAddress = args[1]
    val toAddress = args[2]
    sendEmail(subject, senderAddress, toAddress)
}

suspend fun sendEmail(
    subjectVal: String?,
    senderAddress: String,
    toAddressVal: String,
) {
    var content =
        Content {
            data = body
        }

    val messageBody =
        Body {
            text = content
        }

    val subContent =
        Content {
            data = subjectVal
        }

    val message =
        Message {
            body = messageBody
            subject = subContent
        }

    val destinationOb =
        Destination {
            toAddresses = listOf(toAddressVal)
        }

    val emailContent =
        EmailContent {
            simple = message
        }

    val sendEmailRequest =
        SendEmailRequest {
            fromEmailAddress = senderAddress
            destination = destinationOb
            this.content = emailContent
        }

    PinpointEmailClient.fromEnvironment { region = "us-east-1" }.use { pinpointemail ->
        pinpointemail.sendEmail(sendEmailRequest)
        println("Message Sent")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[SendMessages](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon RDS の例
<a name="kotlin_1_rds_code_examples"></a>

次のコード例は、Amazon RDS で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="rds_Scenario_GetStartedInstances_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム DB パラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用するように設定した DB インスタンスを作成します。DB インスタンスにはデータベースも含まれています。
+ インスタンスのスナップショットを取得します。
+ インスタンスとパラメータグループを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this 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-kotlin/latest/developer-guide/setup.html

This example requires an AWS Secrets Manager secret that contains the database credentials. If you do not create a
secret, this example will not work. For more details, see:

https://docs.aws.amazon.com/secretsmanager/latest/userguide/integrating_how-services-use-secrets_RS.html

This example performs the following tasks:

1. Returns a list of the available DB engines by invoking the DescribeDbEngineVersions method.
2. Selects an engine family and create a custom DB parameter group by invoking the createDBParameterGroup method.
3. Gets the parameter groups by invoking the DescribeDbParameterGroups method.
4. Gets parameters in the group by invoking the DescribeDbParameters method.
5. Modifies both the auto_increment_offset and auto_increment_increment parameters by invoking the modifyDbParameterGroup method.
6. Gets and displays the updated parameters.
7. Gets a list of allowed engine versions by invoking the describeDbEngineVersions method.
8. Gets a list of micro instance classes available for the selected engine.
9. Creates an Amazon Relational Database Service (Amazon RDS) database instance that contains a MySQL database and uses the parameter group.
10. Waits for DB instance to be ready and prints out the connection endpoint value.
11. Creates a snapshot of the DB instance.
12. Waits for the DB snapshot to be ready.
13. Deletes the DB instance.
14. Deletes the parameter group.
 */

var sleepTime: Long = 20

suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <dbGroupName> <dbParameterGroupFamily> <dbInstanceIdentifier> <dbName> <dbSnapshotIdentifier><secretName>

        Where:
            dbGroupName - The database group name. 
            dbParameterGroupFamily - The database parameter group name.
            dbInstanceIdentifier - The database instance identifier. 
            dbName -  The database name. 
            dbSnapshotIdentifier - The snapshot identifier. 
            secretName - The name of the AWS Secrets Manager secret that contains the database credentials.
    """

    if (args.size != 6) {
        println(usage)
        exitProcess(1)
    }

    val dbGroupName = args[0]
    val dbParameterGroupFamily = args[1]
    val dbInstanceIdentifier = args[2]
    val dbName = args[3]
    val dbSnapshotIdentifier = args[4]
    val secretName = args[5]

    val gson = Gson()
    val user = gson.fromJson(getSecretValues(secretName).toString(), User::class.java)
    val username = user.username
    val userPassword = user.password

    println("1. Return a list of the available DB engines")
    describeDBEngines()

    println("2. Create a custom parameter group")
    createDBParameterGroup(dbGroupName, dbParameterGroupFamily)

    println("3. Get the parameter groups")
    describeDbParameterGroups(dbGroupName)

    println("4. Get the parameters in the group")
    describeDbParameters(dbGroupName, 0)

    println("5. Modify the auto_increment_offset parameter")
    modifyDBParas(dbGroupName)

    println("6. Display the updated value")
    describeDbParameters(dbGroupName, -1)

    println("7. Get a list of allowed engine versions")
    getAllowedEngines(dbParameterGroupFamily)

    println("8. Get a list of micro instance classes available for the selected engine")
    getMicroInstances()

    println("9. Create an RDS database instance that contains a MySql database and uses the parameter group")
    val dbARN = createDatabaseInstance(dbGroupName, dbInstanceIdentifier, dbName, username, userPassword)
    println("The ARN of the new database is $dbARN")

    println("10. Wait for DB instance to be ready")
    waitForDbInstanceReady(dbInstanceIdentifier)

    println("11. Create a snapshot of the DB instance")
    createDbSnapshot(dbInstanceIdentifier, dbSnapshotIdentifier)

    println("12. Wait for DB snapshot to be ready")
    waitForSnapshotReady(dbInstanceIdentifier, dbSnapshotIdentifier)

    println("13. Delete the DB instance")
    deleteDbInstance(dbInstanceIdentifier)

    println("14. Delete the parameter group")
    if (dbARN != null) {
        deleteParaGroup(dbGroupName, dbARN)
    }

    println("The Scenario has successfully completed.")
}

suspend fun deleteParaGroup(
    dbGroupName: String,
    dbARN: String,
) {
    var isDataDel = false
    var didFind: Boolean
    var instanceARN: String

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        // Make sure that the database has been deleted.
        while (!isDataDel) {
            val response = rdsClient.describeDbInstances()
            val instanceList = response.dbInstances
            val listSize = instanceList?.size
            isDataDel = false // Reset this value.
            didFind = false // Reset this value.
            var index = 1
            if (instanceList != null) {
                for (instance in instanceList) {
                    instanceARN = instance.dbInstanceArn.toString()
                    if (instanceARN.compareTo(dbARN) == 0) {
                        println("$dbARN still exists")
                        didFind = true
                    }
                    if (index == listSize && !didFind) {
                        // Went through the entire list and did not find the database name.
                        isDataDel = true
                    }
                    index++
                }
            }
        }

        // Delete the para group.
        val parameterGroupRequest =
            DeleteDbParameterGroupRequest {
                dbParameterGroupName = dbGroupName
            }
        rdsClient.deleteDbParameterGroup(parameterGroupRequest)
        println("$dbGroupName was deleted.")
    }
}

suspend fun deleteDbInstance(dbInstanceIdentifierVal: String) {
    val deleteDbInstanceRequest =
        DeleteDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            deleteAutomatedBackups = true
            skipFinalSnapshot = true
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.deleteDbInstance(deleteDbInstanceRequest)
        print("The status of the database is ${response.dbInstance?.dbInstanceStatus}")
    }
}

// Waits until the snapshot instance is available.
suspend fun waitForSnapshotReady(
    dbInstanceIdentifierVal: String?,
    dbSnapshotIdentifierVal: String?,
) {
    var snapshotReady = false
    var snapshotReadyStr: String
    println("Waiting for the snapshot to become available.")

    val snapshotsRequest =
        DescribeDbSnapshotsRequest {
            dbSnapshotIdentifier = dbSnapshotIdentifierVal
            dbInstanceIdentifier = dbInstanceIdentifierVal
        }

    while (!snapshotReady) {
        RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
            val response = rdsClient.describeDbSnapshots(snapshotsRequest)
            val snapshotList: List<DbSnapshot>? = response.dbSnapshots
            if (snapshotList != null) {
                for (snapshot in snapshotList) {
                    snapshotReadyStr = snapshot.status.toString()
                    if (snapshotReadyStr.contains("available")) {
                        snapshotReady = true
                    } else {
                        print(".")
                        delay(sleepTime * 1000)
                    }
                }
            }
        }
    }
    println("The Snapshot is available!")
}

// Create an Amazon RDS snapshot.
suspend fun createDbSnapshot(
    dbInstanceIdentifierVal: String?,
    dbSnapshotIdentifierVal: String?,
) {
    val snapshotRequest =
        CreateDbSnapshotRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            dbSnapshotIdentifier = dbSnapshotIdentifierVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbSnapshot(snapshotRequest)
        print("The Snapshot id is ${response.dbSnapshot?.dbiResourceId}")
    }
}

// Waits until the database instance is available.
suspend fun waitForDbInstanceReady(dbInstanceIdentifierVal: String?) {
    var instanceReady = false
    var instanceReadyStr: String
    println("Waiting for instance to become available.")

    val instanceRequest =
        DescribeDbInstancesRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
        }
    var endpoint = ""
    while (!instanceReady) {
        RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
            val response = rdsClient.describeDbInstances(instanceRequest)
            val instanceList = response.dbInstances
            if (instanceList != null) {
                for (instance in instanceList) {
                    instanceReadyStr = instance.dbInstanceStatus.toString()
                    if (instanceReadyStr.contains("available")) {
                        endpoint = instance.endpoint?.address.toString()
                        instanceReady = true
                    } else {
                        print(".")
                        delay(sleepTime * 1000)
                    }
                }
            }
        }
    }
    println("Database instance is available! The connection endpoint is $endpoint")
}

// Create a database instance and return the ARN of the database.
suspend fun createDatabaseInstance(
    dbGroupNameVal: String?,
    dbInstanceIdentifierVal: String?,
    dbNameVal: String?,
    masterUsernameVal: String?,
    masterUserPasswordVal: String?,
): String? {
    val instanceRequest =
        CreateDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            allocatedStorage = 100
            dbName = dbNameVal
            dbParameterGroupName = dbGroupNameVal
            engine = "mysql"
            dbInstanceClass = "db.t3.micro"
            engineVersion = "8.0.35"
            storageType = "gp2"
            masterUsername = masterUsernameVal
            masterUserPassword = masterUserPasswordVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbInstance(instanceRequest)
        print("The status is ${response.dbInstance?.dbInstanceStatus}")
        return response.dbInstance?.dbInstanceArn
    }
}

// Get a list of micro instances.
suspend fun getMicroInstances() {
    val dbInstanceOptionsRequest =
        DescribeOrderableDbInstanceOptionsRequest {
            engine = "mysql"
        }
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeOrderableDbInstanceOptions(dbInstanceOptionsRequest)
        val orderableDBInstances = response.orderableDbInstanceOptions
        if (orderableDBInstances != null) {
            for (dbInstanceOption in orderableDBInstances) {
                println("The engine version is ${dbInstanceOption.engineVersion}")
                println("The engine description is ${dbInstanceOption.engine}")
            }
        }
    }
}

// Get a list of allowed engine versions.
suspend fun getAllowedEngines(dbParameterGroupFamilyVal: String?) {
    val versionsRequest =
        DescribeDbEngineVersionsRequest {
            dbParameterGroupFamily = dbParameterGroupFamilyVal
            engine = "mysql"
        }
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbEngineVersions(versionsRequest)
        val dbEngines: List<DbEngineVersion>? = response.dbEngineVersions
        if (dbEngines != null) {
            for (dbEngine in dbEngines) {
                println("The engine version is ${dbEngine.engineVersion}")
                println("The engine description is ${dbEngine.dbEngineDescription}")
            }
        }
    }
}

// Modify the auto_increment_offset parameter.
suspend fun modifyDBParas(dbGroupName: String) {
    val parameter1 =
        Parameter {
            parameterName = "auto_increment_offset"
            applyMethod = ApplyMethod.Immediate
            parameterValue = "5"
        }

    val paraList: ArrayList<Parameter> = ArrayList()
    paraList.add(parameter1)
    val groupRequest =
        ModifyDbParameterGroupRequest {
            dbParameterGroupName = dbGroupName
            parameters = paraList
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.modifyDbParameterGroup(groupRequest)
        println("The parameter group ${response.dbParameterGroupName} was successfully modified")
    }
}

// Retrieve parameters in the group.
suspend fun describeDbParameters(
    dbGroupName: String?,
    flag: Int,
) {
    val dbParameterGroupsRequest: DescribeDbParametersRequest
    dbParameterGroupsRequest =
        if (flag == 0) {
            DescribeDbParametersRequest {
                dbParameterGroupName = dbGroupName
            }
        } else {
            DescribeDbParametersRequest {
                dbParameterGroupName = dbGroupName
                source = "user"
            }
        }
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbParameters(dbParameterGroupsRequest)
        val dbParameters: List<Parameter>? = response.parameters
        var paraName: String
        if (dbParameters != null) {
            for (para in dbParameters) {
                // Only print out information about either auto_increment_offset or auto_increment_increment.
                paraName = para.parameterName.toString()
                if (paraName.compareTo("auto_increment_offset") == 0 || paraName.compareTo("auto_increment_increment ") == 0) {
                    println("*** The parameter name is  $paraName")
                    System.out.println("*** The parameter value is  ${para.parameterValue}")
                    System.out.println("*** The parameter data type is ${para.dataType}")
                    System.out.println("*** The parameter description is ${para.description}")
                    System.out.println("*** The parameter allowed values  is ${para.allowedValues}")
                }
            }
        }
    }
}

suspend fun describeDbParameterGroups(dbGroupName: String?) {
    val groupsRequest =
        DescribeDbParameterGroupsRequest {
            dbParameterGroupName = dbGroupName
            maxRecords = 20
        }
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbParameterGroups(groupsRequest)
        val groups = response.dbParameterGroups
        if (groups != null) {
            for (group in groups) {
                println("The group name is ${group.dbParameterGroupName}")
                println("The group description is ${group.description}")
            }
        }
    }
}

// Create a parameter group.
suspend fun createDBParameterGroup(
    dbGroupName: String?,
    dbParameterGroupFamilyVal: String?,
) {
    val groupRequest =
        CreateDbParameterGroupRequest {
            dbParameterGroupName = dbGroupName
            dbParameterGroupFamily = dbParameterGroupFamilyVal
            description = "Created by using the AWS SDK for Kotlin"
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbParameterGroup(groupRequest)
        println("The group name is ${response.dbParameterGroup?.dbParameterGroupName}")
    }
}

// Returns a list of the available DB engines.
suspend fun describeDBEngines() {
    val engineVersionsRequest =
        DescribeDbEngineVersionsRequest {
            defaultOnly = true
            engine = "mysql"
            maxRecords = 20
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbEngineVersions(engineVersionsRequest)
        val engines: List<DbEngineVersion>? = response.dbEngineVersions

        // Get all DbEngineVersion objects.
        if (engines != null) {
            for (engineOb in engines) {
                println("The name of the DB parameter group family for the database engine is ${engineOb.dbParameterGroupFamily}.")
                println("The name of the database engine ${engineOb.engine}.")
                println("The version number of the database engine ${engineOb.engineVersion}")
            }
        }
    }
}

suspend fun getSecretValues(secretName: String?): String? {
    val valueRequest =
        GetSecretValueRequest {
            secretId = secretName
        }

    SecretsManagerClient.fromEnvironment { region = "us-west-2" }.use { secretsClient ->
        val valueResponse = secretsClient.getSecretValue(valueRequest)
        return valueResponse.secretString
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateDBParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateDBSnapshot](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteDBParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBEngineVersions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBParameterGroups](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBParameters](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeDBSnapshots](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeOrderableDBInstanceOptions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ModifyDBParameterGroup](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_kotlin_1_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createDatabaseInstance(
    dbInstanceIdentifierVal: String?,
    dbNamedbVal: String?,
    masterUsernameVal: String?,
    masterUserPasswordVal: String?,
) {
    val instanceRequest =
        CreateDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            allocatedStorage = 100
            dbName = dbNamedbVal
            engine = "mysql"
            dbInstanceClass = "db.t3.micro" // Use a supported instance class
            engineVersion = "8.0.39" // Use a supported engine version
            storageType = "gp2"
            masterUsername = masterUsernameVal
            masterUserPassword = masterUserPasswordVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.createDbInstance(instanceRequest)
        print("The status is ${response.dbInstance?.dbInstanceStatus}")
    }
}

// Waits until the database instance is available.
suspend fun waitForInstanceReady(dbInstanceIdentifierVal: String?) {
    val sleepTime: Long = 20
    var instanceReady = false
    var instanceReadyStr: String
    println("Waiting for instance to become available.")

    val instanceRequest =
        DescribeDbInstancesRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        while (!instanceReady) {
            val response = rdsClient.describeDbInstances(instanceRequest)
            val instanceList = response.dbInstances
            if (instanceList != null) {
                for (instance in instanceList) {
                    instanceReadyStr = instance.dbInstanceStatus.toString()
                    if (instanceReadyStr.contains("available")) {
                        instanceReady = true
                    } else {
                        println("...$instanceReadyStr")
                        delay(sleepTime * 1000)
                    }
                }
            }
        }
        println("Database instance is available!")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_kotlin_1_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteDatabaseInstance(dbInstanceIdentifierVal: String?) {
    val deleteDbInstanceRequest =
        DeleteDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            deleteAutomatedBackups = true
            skipFinalSnapshot = true
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.deleteDbInstance(deleteDbInstanceRequest)
        print("The status of the database is ${response.dbInstance?.dbInstanceStatus}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAccountAttributes`
<a name="rds_DescribeAccountAttributes_kotlin_1_topic"></a>

次のコード例は、`DescribeAccountAttributes` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getAccountAttributes() {
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeAccountAttributes(DescribeAccountAttributesRequest {})
        response.accountQuotas?.forEach { quotas ->
            val response = response.accountQuotas
            println("Name is: ${quotas.accountQuotaName}")
            println("Max value is ${quotas.max}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeAccountAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_kotlin_1_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeInstances() {
    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val response = rdsClient.describeDbInstances(DescribeDbInstancesRequest {})
        response.dbInstances?.forEach { instance ->
            println("Instance Identifier is ${instance.dbInstanceIdentifier}")
            println("The Engine is ${instance.engine}")
            println("Connection endpoint is ${instance.endpoint?.address}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeDBInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ModifyDBInstance`
<a name="rds_ModifyDBInstance_kotlin_1_topic"></a>

次のコード例は、`ModifyDBInstance` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rds#code-examples)での設定と実行の方法を確認してください。

```
suspend fun updateIntance(
    dbInstanceIdentifierVal: String?,
    masterUserPasswordVal: String?,
) {
    val request =
        ModifyDbInstanceRequest {
            dbInstanceIdentifier = dbInstanceIdentifierVal
            publiclyAccessible = true
            masterUserPassword = masterUserPasswordVal
        }

    RdsClient.fromEnvironment { region = "us-west-2" }.use { rdsClient ->
        val instanceResponse = rdsClient.modifyDbInstance(request)
        println("The ARN of the modified database is ${instanceResponse.dbInstance?.dbInstanceArn}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ModifyDBInstance](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/serverless_rds) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for Kotlin を使用した Amazon RDS データサービスの例
<a name="kotlin_1_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/serverless_rds) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for Kotlin を使用した Amazon Redshift の例
<a name="kotlin_1_redshift_code_examples"></a>

次のコード例は、Amazon Redshift で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="redshift_CreateCluster_kotlin_1_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを作成します。  

```
suspend fun createCluster(
    clusterId: String?,
    masterUsernameVal: String?,
    masterUserPasswordVal: String?,
) {
    val clusterRequest =
        CreateClusterRequest {
            clusterIdentifier = clusterId
            availabilityZone = "us-east-1a"
            masterUsername = masterUsernameVal
            masterUserPassword = masterUserPasswordVal
            nodeType = "ra3.4xlarge"
            publiclyAccessible = true
            numberOfNodes = 2
        }

    RedshiftClient.fromEnvironment { region = "us-east-1" }.use { redshiftClient ->
        val clusterResponse = redshiftClient.createCluster(clusterRequest)
        println("Created cluster ${clusterResponse.cluster?.clusterIdentifier}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateCluster](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteCluster`
<a name="redshift_DeleteCluster_kotlin_1_topic"></a>

次のコード例は、`DeleteCluster` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを削除します。  

```
suspend fun deleteRedshiftCluster(clusterId: String?) {
    val request =
        DeleteClusterRequest {
            clusterIdentifier = clusterId
            skipFinalClusterSnapshot = true
        }

    RedshiftClient.fromEnvironment { region = "us-west-2" }.use { redshiftClient ->
        val response = redshiftClient.deleteCluster(request)
        println("The status is ${response.cluster?.clusterStatus}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteCluster](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeClusters`
<a name="redshift_DescribeClusters_kotlin_1_topic"></a>

次のコード例は、`DescribeClusters` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを記述します。  

```
suspend fun describeRedshiftClusters() {
    RedshiftClient.fromEnvironment { region = "us-west-2" }.use { redshiftClient ->
        val clusterResponse = redshiftClient.describeClusters(DescribeClustersRequest {})
        val clusterList = clusterResponse.clusters

        if (clusterList != null) {
            for (cluster in clusterList) {
                println("Cluster database name is ${cluster.dbName}")
                println("Cluster status is ${cluster.clusterStatus}")
            }
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeClusters](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ModifyCluster`
<a name="redshift_ModifyCluster_kotlin_1_topic"></a>

次のコード例は、`ModifyCluster` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/redshift#code-examples)での設定と実行の方法を確認してください。
クラスターを変更します。  

```
suspend fun modifyCluster(clusterId: String?) {
    val modifyClusterRequest =
        ModifyClusterRequest {
            clusterIdentifier = clusterId
            preferredMaintenanceWindow = "wed:07:30-wed:08:00"
        }

    RedshiftClient { region = "us-west-2" }.use { redshiftClient ->
        val clusterResponse = redshiftClient.modifyCluster(modifyClusterRequest)
        println(
            "The modified cluster was successfully modified and has ${clusterResponse.cluster?.preferredMaintenanceWindow} as the maintenance window",
        )
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ModifyCluster](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Redshift データ追跡用のウェブアプリケーションの作成
<a name="cross_RedshiftDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon Redshift データベースを使用して、作業項目を追跡してレポートするウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon Redshift データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Redshift サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_redshift_application) にある詳しい事例を参照してください。  

**この例で使用されているサービス**
+ Amazon Redshift
+ Amazon SES

# SDK for Kotlin を使用する Amazon Rekognition の例
<a name="kotlin_1_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CompareFaces`
<a name="rekognition_CompareFaces_kotlin_1_topic"></a>

次のコード例は、`CompareFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を比較する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun compareTwoFaces(
    similarityThresholdVal: Float,
    sourceImageVal: String,
    targetImageVal: String,
) {
    val sourceBytes = (File(sourceImageVal).readBytes())
    val targetBytes = (File(targetImageVal).readBytes())

    // Create an Image object for the source image.
    val souImage =
        Image {
            bytes = sourceBytes
        }

    val tarImage =
        Image {
            bytes = targetBytes
        }

    val facesRequest =
        CompareFacesRequest {
            sourceImage = souImage
            targetImage = tarImage
            similarityThreshold = similarityThresholdVal
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->

        val compareFacesResult = rekClient.compareFaces(facesRequest)
        val faceDetails = compareFacesResult.faceMatches

        if (faceDetails != null) {
            for (match: CompareFacesMatch in faceDetails) {
                val face = match.face
                val position = face?.boundingBox
                if (position != null) {
                    println("Face at ${position.left} ${position.top} matches with ${face.confidence} % confidence.")
                }
            }
        }

        val uncompared = compareFacesResult.unmatchedFaces
        if (uncompared != null) {
            println("There was ${uncompared.size} face(s) that did not match")
        }

        println("Source image rotation: ${compareFacesResult.sourceImageOrientationCorrection}")
        println("target image rotation: ${compareFacesResult.targetImageOrientationCorrection}")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[CompareFaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateCollection`
<a name="rekognition_CreateCollection_kotlin_1_topic"></a>

次のコード例は、`CreateCollection` を使用する方法を示しています。

詳細については、「[コレクションを作成する](https://docs.aws.amazon.com/rekognition/latest/dg/create-collection-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createMyCollection(collectionIdVal: String) {
    val request =
        CreateCollectionRequest {
            collectionId = collectionIdVal
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.createCollection(request)
        println("Collection ARN is ${response.collectionArn}")
        println("Status code is ${response.statusCode}")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[CreateCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteCollection`
<a name="rekognition_DeleteCollection_kotlin_1_topic"></a>

次のコード例は、`DeleteCollection` を使用する方法を示しています。

詳細については、「[コレクションを削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-collection-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteMyCollection(collectionIdVal: String) {
    val request =
        DeleteCollectionRequest {
            collectionId = collectionIdVal
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.deleteCollection(request)
        println("The collectionId status is ${response.statusCode}")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[DeleteCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteFaces`
<a name="rekognition_DeleteFaces_kotlin_1_topic"></a>

次のコード例は、`DeleteFaces` を使用する方法を示しています。

詳細については、「[コレクションから顔を削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-faces-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteFacesCollection(
    collectionIdVal: String?,
    faceIdVal: String,
) {
    val deleteFacesRequest =
        DeleteFacesRequest {
            collectionId = collectionIdVal
            faceIds = listOf(faceIdVal)
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        rekClient.deleteFaces(deleteFacesRequest)
        println("$faceIdVal was deleted from the collection")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[DeleteFaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeCollection`
<a name="rekognition_DescribeCollection_kotlin_1_topic"></a>

次のコード例は、`DescribeCollection` を使用する方法を示しています。

詳細については、「[コレクションを定義する](https://docs.aws.amazon.com/rekognition/latest/dg/describe-collection-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeColl(collectionName: String) {
    val request =
        DescribeCollectionRequest {
            collectionId = collectionName
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.describeCollection(request)
        println("The collection Arn is ${response.collectionArn}")
        println("The collection contains this many faces ${response.faceCount}")
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[DescribeCollection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DetectFaces`
<a name="rekognition_DetectFaces_kotlin_1_topic"></a>

次のコード例は、`DetectFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を検出する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun detectFacesinImage(sourceImage: String?) {
    val souImage =
        Image {
            bytes = (File(sourceImage).readBytes())
        }

    val request =
        DetectFacesRequest {
            attributes = listOf(Attribute.All)
            image = souImage
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.detectFaces(request)
        response.faceDetails?.forEach { face ->
            val ageRange = face.ageRange
            println("The detected face is estimated to be between ${ageRange?.low} and ${ageRange?.high} years old.")
            println("There is a smile ${face.smile?.value}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[DetectFaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DetectLabels`
<a name="rekognition_DetectLabels_kotlin_1_topic"></a>

次のコード例は、`DetectLabels` を使用する方法を示しています。

詳細については、「[イメージ内のラベルを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun detectImageLabels(sourceImage: String) {
    val souImage =
        Image {
            bytes = (File(sourceImage).readBytes())
        }
    val request =
        DetectLabelsRequest {
            image = souImage
            maxLabels = 10
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.detectLabels(request)
        response.labels?.forEach { label ->
            println("${label.name} : ${label.confidence}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[DetectLabels](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DetectModerationLabels`
<a name="rekognition_DetectModerationLabels_kotlin_1_topic"></a>

次のコード例は、`DetectModerationLabels` を使用する方法を示しています。

詳細については、「[不適切なイメージを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-images.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun detectModLabels(sourceImage: String) {
    val myImage =
        Image {
            this.bytes = (File(sourceImage).readBytes())
        }

    val request =
        DetectModerationLabelsRequest {
            image = myImage
            minConfidence = 60f
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.detectModerationLabels(request)
        response.moderationLabels?.forEach { label ->
            println("Label: ${label.name} - Confidence: ${label.confidence} % Parent: ${label.parentName}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[DetectModerationLabels](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DetectText`
<a name="rekognition_DetectText_kotlin_1_topic"></a>

次のコード例は、`DetectText` を使用する方法を示しています。

詳細については、「[イメージ内のテキストを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/text-detecting-text-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun detectTextLabels(sourceImage: String?) {
    val souImage =
        Image {
            bytes = (File(sourceImage).readBytes())
        }

    val request =
        DetectTextRequest {
            image = souImage
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.detectText(request)
        response.textDetections?.forEach { text ->
            println("Detected: ${text.detectedText}")
            println("Confidence: ${text.confidence}")
            println("Id: ${text.id}")
            println("Parent Id:  ${text.parentId}")
            println("Type: ${text.type}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[DetectText](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `IndexFaces`
<a name="rekognition_IndexFaces_kotlin_1_topic"></a>

次のコード例は、`IndexFaces` を使用する方法を示しています。

詳細については、「[コレクションに顔を追加する](https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun addToCollection(
    collectionIdVal: String?,
    sourceImage: String,
) {
    val souImage =
        Image {
            bytes = (File(sourceImage).readBytes())
        }

    val request =
        IndexFacesRequest {
            collectionId = collectionIdVal
            image = souImage
            maxFaces = 1
            qualityFilter = QualityFilter.Auto
            detectionAttributes = listOf(Attribute.Default)
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val facesResponse = rekClient.indexFaces(request)

        // Display the results.
        println("Results for the image")
        println("\n Faces indexed:")
        facesResponse.faceRecords?.forEach { faceRecord ->
            println("Face ID: ${faceRecord.face?.faceId}")
            println("Location: ${faceRecord.faceDetail?.boundingBox}")
        }

        println("Faces not indexed:")
        facesResponse.unindexedFaces?.forEach { unindexedFace ->
            println("Location: ${unindexedFace.faceDetail?.boundingBox}")
            println("Reasons:")

            unindexedFace.reasons?.forEach { reason ->
                println("Reason:  $reason")
            }
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[IndexFaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListCollections`
<a name="rekognition_ListCollections_kotlin_1_topic"></a>

次のコード例は、`ListCollections` を使用する方法を示しています。

コレクションの詳細については、「[コレクションを一覧表示する](https://docs.aws.amazon.com/rekognition/latest/dg/list-collection-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllCollections() {
    val request =
        ListCollectionsRequest {
            maxResults = 10
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.listCollections(request)
        response.collectionIds?.forEach { resultId ->
            println(resultId)
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[ListCollections](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListFaces`
<a name="rekognition_ListFaces_kotlin_1_topic"></a>

次のコード例は、`ListFaces` を使用する方法を示しています。

詳細については、「[コレクションに顔を保存する](https://docs.aws.amazon.com/rekognition/latest/dg/list-faces-in-collection-procedure.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listFacesCollection(collectionIdVal: String?) {
    val request =
        ListFacesRequest {
            collectionId = collectionIdVal
            maxResults = 10
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.listFaces(request)
        response.faces?.forEach { face ->
            println("Confidence level there is a face: ${face.confidence}")
            println("The face Id value is ${face.faceId}")
        }
    }
}
```
+  API の詳細については、「AWS SDK for Kotlin API Reference」の「[ListFaces](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `RecognizeCelebrities`
<a name="rekognition_RecognizeCelebrities_kotlin_1_topic"></a>

次のコード例は、`RecognizeCelebrities` を使用する方法を示しています。

詳細については、「[イメージ内で有名人を認識する](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-procedure-image.html)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。

```
suspend fun recognizeAllCelebrities(sourceImage: String?) {
    val souImage =
        Image {
            bytes = (File(sourceImage).readBytes())
        }

    val request =
        RecognizeCelebritiesRequest {
            image = souImage
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val response = rekClient.recognizeCelebrities(request)
        response.celebrityFaces?.forEach { celebrity ->
            println("Celebrity recognized: ${celebrity.name}")
            println("Celebrity ID:${celebrity.id}")
            println("Further information (if available):")
            celebrity.urls?.forEach { url ->
                println(url)
            }
        }
        println("${response.unrecognizedFaces?.size} face(s) were unrecognized.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[RecognizeCelebrities](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_kotlin_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Kotlin**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_pam) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### ビデオ内の情報を検出する
<a name="rekognition_VideoDetection_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Rekognition のジョブを開始し、人物、オブジェクト、テキストなどの要素を動画から検出します。
+ ジョブが完了するまでジョブのステータスを確認します。
+ 検出された要素のリストをジョブごとに出力します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/rekognition#code-examples)での設定と実行の方法を確認してください。
Amazon S3 バケットに保存されたビデオ内の顔を検出する  

```
suspend fun startFaceDetection(
    channelVal: NotificationChannel?,
    bucketVal: String,
    videoVal: String,
) {
    val s3Obj =
        S3Object {
            bucket = bucketVal
            name = videoVal
        }
    val vidOb =
        Video {
            s3Object = s3Obj
        }

    val request =
        StartFaceDetectionRequest {
            jobTag = "Faces"
            faceAttributes = FaceAttributes.All
            notificationChannel = channelVal
            video = vidOb
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val startLabelDetectionResult = rekClient.startFaceDetection(request)
        startJobId = startLabelDetectionResult.jobId.toString()
    }
}

suspend fun getFaceResults() {
    var finished = false
    var status: String
    var yy = 0
    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        var response: GetFaceDetectionResponse? = null

        val recognitionRequest =
            GetFaceDetectionRequest {
                jobId = startJobId
                maxResults = 10
            }

        // Wait until the job succeeds.
        while (!finished) {
            response = rekClient.getFaceDetection(recognitionRequest)
            status = response.jobStatus.toString()
            if (status.compareTo("Succeeded") == 0) {
                finished = true
            } else {
                println("$yy status is: $status")
                delay(1000)
            }
            yy++
        }

        // Proceed when the job is done - otherwise VideoMetadata is null.
        val videoMetaData = response?.videoMetadata
        println("Format: ${videoMetaData?.format}")
        println("Codec: ${videoMetaData?.codec}")
        println("Duration: ${videoMetaData?.durationMillis}")
        println("FrameRate: ${videoMetaData?.frameRate}")

        // Show face information.
        response?.faces?.forEach { face ->
            println("Age: ${face.face?.ageRange}")
            println("Face: ${face.face?.beard}")
            println("Eye glasses: ${face?.face?.eyeglasses}")
            println("Mustache: ${face.face?.mustache}")
            println("Smile: ${face.face?.smile}")
        }
    }
}
```
Amazon S3 バケットに保存されたビデオ内の不適切なコンテンツや攻撃的なコンテンツを検出します。  

```
suspend fun startModerationDetection(
    channel: NotificationChannel?,
    bucketVal: String?,
    videoVal: String?,
) {
    val s3Obj =
        S3Object {
            bucket = bucketVal
            name = videoVal
        }
    val vidOb =
        Video {
            s3Object = s3Obj
        }
    val request =
        StartContentModerationRequest {
            jobTag = "Moderation"
            notificationChannel = channel
            video = vidOb
        }

    RekognitionClient.fromEnvironment { region = "us-east-1" }.use { rekClient ->
        val startModDetectionResult = rekClient.startContentModeration(request)
        startJobId = startModDetectionResult.jobId.toString()
    }
}

suspend fun getModResults() {
    var finished = false
    var status: String
    var yy = 0
    RekognitionClient { region = "us-east-1" }.use { rekClient ->
        var modDetectionResponse: GetContentModerationResponse? = null

        val modRequest =
            GetContentModerationRequest {
                jobId = startJobId
                maxResults = 10
            }

        // Wait until the job succeeds.
        while (!finished) {
            modDetectionResponse = rekClient.getContentModeration(modRequest)
            status = modDetectionResponse.jobStatus.toString()
            if (status.compareTo("Succeeded") == 0) {
                finished = true
            } else {
                println("$yy status is: $status")
                delay(1000)
            }
            yy++
        }

        // Proceed when the job is done - otherwise VideoMetadata is null.
        val videoMetaData = modDetectionResponse?.videoMetadata
        println("Format: ${videoMetaData?.format}")
        println("Codec: ${videoMetaData?.codec}")
        println("Duration: ${videoMetaData?.durationMillis}")
        println("FrameRate: ${videoMetaData?.frameRate}")

        modDetectionResponse?.moderationLabels?.forEach { mod ->
            val seconds: Long = mod.timestamp / 1000
            print("Mod label: $seconds ")
            println(mod.moderationLabel)
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [GetCelebrityRecognition](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetContentModeration](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetLabelDetection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetPersonTracking](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetSegmentDetection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetTextDetection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartCelebrityRecognition](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartContentModeration](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartLabelDetection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartPersonTracking](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartSegmentDetection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartTextDetection](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_kotlin_1_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Kotlin**  
 Amazon Simple Storage Service (Amazon S3) バケットにある画像内からカテゴリ別にオブジェクトを Amazon Rekognition を使用して識別するアプリケーションを、Amazon Rekognition Kotlin API を使用して作成する方法を示します。アプリケーションは、Amazon Simple Email Service (Amazon SES) を使用して、結果を記載した E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_photo_analyzer_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

# SDK for Kotlin を使用した Route 53 ドメイン登録の例
<a name="kotlin_1_route-53-domains_code_examples"></a>

次のコード例は、Route 53 ドメイン登録で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### ハロー Route 53 ドメイン登録
<a name="route-53-domains_Hello_kotlin_1_topic"></a>

次のコード例は、Route 53 ドメイン登録の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
/**
 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */
suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
           <domainType> 

       Where:
           domainType - The domain type (for example, com). 
    """

    if (args.size != 1) {
        println(usage)
        exitProcess(0)
    }

    val domainType = args[0]
    println("Invokes ListPrices using a Paginated method.")
    listPricesPaginated(domainType)
}

suspend fun listPricesPaginated(domainType: String) {
    val pricesRequest =
        ListPricesRequest {
            maxItems = 10
            tld = domainType
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .listPricesPaginated(pricesRequest)
            .transform { it.prices?.forEach { obj -> emit(obj) } }
            .collect { pr ->
                println("Registration: ${pr.registrationPrice} ${pr.registrationPrice?.currency}")
                println("Renewal: ${pr.renewalPrice?.price} ${pr.renewalPrice?.currency}")
                println("Transfer: ${pr.transferPrice?.price} ${pr.transferPrice?.currency}")
                println("Restoration: ${pr.restorationPrice?.price} ${pr.restorationPrice?.currency}")
            }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListPrices](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="route-53-domains_Scenario_GetStartedRoute53Domains_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 現在のドメインを一覧表示し、過去 1 年間の操作を一覧表示します。
+ 過去 1 年間の請求記録とドメインタイプの価格を表示します。
+ ドメインの候補を取得します。
+ ドメインの可用性と移管可能性を確認します。
+ オプションで、ドメイン登録をリクエストします。
+ 操作の詳細を入手します。
+ オプションで、ドメインの詳細を取得します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

This Kotlin code example performs the following operations:

1. List current domains.
2. List operations in the past year.
3. View billing for the account in the past year.
4. View prices for domain types.
5. Get domain suggestions.
6. Check domain availability.
7. Check domain transferability.
8. Request a domain registration.
9. Get operation details.
10. Optionally, get domain details.
 */

val DASHES: String = String(CharArray(80)).replace("\u0000", "-")

suspend fun main(args: Array<String>) {
    val usage = """
        Usage:
            <domainType> <phoneNumber> <email> <domainSuggestion> <firstName> <lastName> <city>
        Where:
           domainType - The domain type (for example, com). 
           phoneNumber - The phone number to use (for example, +1.2065550100)      
           email - The email address to use.      
           domainSuggestion - The domain suggestion (for example, findmy.example). 
           firstName - The first name to use to register a domain. 
           lastName -  The last name to use to register a domain. 
           city - The city to use to register a domain. 
    """

    if (args.size != 7) {
        println(usage)
        exitProcess(1)
    }

    val domainType = args[0]
    val phoneNumber = args[1]
    val email = args[2]
    val domainSuggestion = args[3]
    val firstName = args[4]
    val lastName = args[5]
    val city = args[6]

    println(DASHES)
    println("Welcome to the Amazon Route 53 domains example scenario.")
    println(DASHES)

    println(DASHES)
    println("1. List current domains.")
    listDomains()
    println(DASHES)

    println(DASHES)
    println("2. List operations in the past year.")
    listOperations()
    println(DASHES)

    println(DASHES)
    println("3. View billing for the account in the past year.")
    listBillingRecords()
    println(DASHES)

    println(DASHES)
    println("4. View prices for domain types.")
    listAllPrices(domainType)
    println(DASHES)

    println(DASHES)
    println("5. Get domain suggestions.")
    listDomainSuggestions(domainSuggestion)
    println(DASHES)

    println(DASHES)
    println("6. Check domain availability.")
    checkDomainAvailability(domainSuggestion)
    println(DASHES)

    println(DASHES)
    println("7. Check domain transferability.")
    checkDomainTransferability(domainSuggestion)
    println(DASHES)

    println(DASHES)
    println("8. Request a domain registration.")
    val opId = requestDomainRegistration(domainSuggestion, phoneNumber, email, firstName, lastName, city)
    println(DASHES)

    println(DASHES)
    println("9. Get operation details.")
    getOperationalDetail(opId)
    println(DASHES)

    println(DASHES)
    println("10. Get domain details.")
    println("Note: You must have a registered domain to get details.")
    println("Otherwise an exception is thrown that states ")
    println("Domain xxxxxxx not found in xxxxxxx account.")
    getDomainDetails(domainSuggestion)
    println(DASHES)
}

suspend fun getDomainDetails(domainSuggestion: String?) {
    val detailRequest =
        GetDomainDetailRequest {
            domainName = domainSuggestion
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.getDomainDetail(detailRequest)
        println("The contact first name is ${response.registrantContact?.firstName}")
        println("The contact last name is ${response.registrantContact?.lastName}")
        println("The contact org name is ${response.registrantContact?.organizationName}")
    }
}

suspend fun getOperationalDetail(opId: String?) {
    val detailRequest =
        GetOperationDetailRequest {
            operationId = opId
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.getOperationDetail(detailRequest)
        println("Operation detail message is ${response.message}")
    }
}

suspend fun requestDomainRegistration(
    domainSuggestion: String?,
    phoneNumberVal: String?,
    emailVal: String?,
    firstNameVal: String?,
    lastNameVal: String?,
    cityVal: String?,
): String? {
    val contactDetail =
        ContactDetail {
            contactType = ContactType.Company
            state = "LA"
            countryCode = CountryCode.In
            email = emailVal
            firstName = firstNameVal
            lastName = lastNameVal
            city = cityVal
            phoneNumber = phoneNumberVal
            organizationName = "My Org"
            addressLine1 = "My Address"
            zipCode = "123 123"
        }

    val domainRequest =
        RegisterDomainRequest {
            adminContact = contactDetail
            registrantContact = contactDetail
            techContact = contactDetail
            domainName = domainSuggestion
            autoRenew = true
            durationInYears = 1
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.registerDomain(domainRequest)
        println("Registration requested. Operation Id: ${response.operationId}")
        return response.operationId
    }
}

suspend fun checkDomainTransferability(domainSuggestion: String?) {
    val transferabilityRequest =
        CheckDomainTransferabilityRequest {
            domainName = domainSuggestion
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.checkDomainTransferability(transferabilityRequest)
        println("Transferability: ${response.transferability?.transferable}")
    }
}

suspend fun checkDomainAvailability(domainSuggestion: String) {
    val availabilityRequest =
        CheckDomainAvailabilityRequest {
            domainName = domainSuggestion
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.checkDomainAvailability(availabilityRequest)
        println("$domainSuggestion is ${response.availability}")
    }
}

suspend fun listDomainSuggestions(domainSuggestion: String?) {
    val suggestionsRequest =
        GetDomainSuggestionsRequest {
            domainName = domainSuggestion
            suggestionCount = 5
            onlyAvailable = true
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.getDomainSuggestions(suggestionsRequest)
        response.suggestionsList?.forEach { suggestion ->
            println("Suggestion Name: ${suggestion.domainName}")
            println("Availability: ${suggestion.availability}")
            println(" ")
        }
    }
}

suspend fun listAllPrices(domainType: String?) {
    val pricesRequest =
        ListPricesRequest {
            tld = domainType
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .listPricesPaginated(pricesRequest)
            .transform { it.prices?.forEach { obj -> emit(obj) } }
            .collect { pr ->
                println("Registration: ${pr.registrationPrice} ${pr.registrationPrice?.currency}")
                println("Renewal: ${pr.renewalPrice?.price} ${pr.renewalPrice?.currency}")
                println("Transfer: ${pr.transferPrice?.price} ${pr.transferPrice?.currency}")
                println("Restoration: ${pr.restorationPrice?.price} ${pr.restorationPrice?.currency}")
            }
    }
}

suspend fun listBillingRecords() {
    val currentDate = Date()
    val localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
    val zoneOffset = ZoneOffset.of("+01:00")
    val localDateTime2 = localDateTime.minusYears(1)
    val myStartTime = localDateTime2.toInstant(zoneOffset)
    val myEndTime = localDateTime.toInstant(zoneOffset)
    val timeStart: Instant? = myStartTime?.let { Instant(it) }
    val timeEnd: Instant? = myEndTime?.let { Instant(it) }

    val viewBillingRequest =
        ViewBillingRequest {
            start = timeStart
            end = timeEnd
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .viewBillingPaginated(viewBillingRequest)
            .transform { it.billingRecords?.forEach { obj -> emit(obj) } }
            .collect { billing ->
                println("Bill Date: ${billing.billDate}")
                println("Operation: ${billing.operation}")
                println("Price: ${billing.price}")
            }
    }
}

suspend fun listOperations() {
    val currentDate = Date()
    var localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
    val zoneOffset = ZoneOffset.of("+01:00")
    localDateTime = localDateTime.minusYears(1)
    val myTime: java.time.Instant? = localDateTime.toInstant(zoneOffset)
    val time2: Instant? = myTime?.let { Instant(it) }
    val operationsRequest =
        ListOperationsRequest {
            submittedSince = time2
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .listOperationsPaginated(operationsRequest)
            .transform { it.operations?.forEach { obj -> emit(obj) } }
            .collect { content ->
                println("Operation Id: ${content.operationId}")
                println("Status: ${content.status}")
                println("Date: ${content.submittedDate}")
            }
    }
}

suspend fun listDomains() {
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .listDomainsPaginated(ListDomainsRequest {})
            .transform { it.domains?.forEach { obj -> emit(obj) } }
            .collect { content ->
                println("The domain name is ${content.domainName}")
            }
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CheckDomainAvailability](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CheckDomainTransferability](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetDomainDetail](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetDomainSuggestions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetOperationDetail](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListDomains](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListOperations](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListPrices](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [RegisterDomain](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ViewBilling](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CheckDomainAvailability`
<a name="route-53-domains_CheckDomainAvailability_kotlin_1_topic"></a>

次のコード例は、`CheckDomainAvailability` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun checkDomainAvailability(domainSuggestion: String) {
    val availabilityRequest =
        CheckDomainAvailabilityRequest {
            domainName = domainSuggestion
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.checkDomainAvailability(availabilityRequest)
        println("$domainSuggestion is ${response.availability}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CheckDomainAvailability](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CheckDomainTransferability`
<a name="route-53-domains_CheckDomainTransferability_kotlin_1_topic"></a>

次のコード例は、`CheckDomainTransferability` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun checkDomainTransferability(domainSuggestion: String?) {
    val transferabilityRequest =
        CheckDomainTransferabilityRequest {
            domainName = domainSuggestion
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.checkDomainTransferability(transferabilityRequest)
        println("Transferability: ${response.transferability?.transferable}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CheckDomainTransferability](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetDomainDetail`
<a name="route-53-domains_GetDomainDetail_kotlin_1_topic"></a>

次のコード例は、`GetDomainDetail` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getDomainDetails(domainSuggestion: String?) {
    val detailRequest =
        GetDomainDetailRequest {
            domainName = domainSuggestion
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.getDomainDetail(detailRequest)
        println("The contact first name is ${response.registrantContact?.firstName}")
        println("The contact last name is ${response.registrantContact?.lastName}")
        println("The contact org name is ${response.registrantContact?.organizationName}")
    }
}
```
+  API の詳細については、「**AWS SDK for Kotlin API リファレンス」の「[GetDomainDetail](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetDomainSuggestions`
<a name="route-53-domains_GetDomainSuggestions_kotlin_1_topic"></a>

次のコード例は、`GetDomainSuggestions` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listDomainSuggestions(domainSuggestion: String?) {
    val suggestionsRequest =
        GetDomainSuggestionsRequest {
            domainName = domainSuggestion
            suggestionCount = 5
            onlyAvailable = true
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.getDomainSuggestions(suggestionsRequest)
        response.suggestionsList?.forEach { suggestion ->
            println("Suggestion Name: ${suggestion.domainName}")
            println("Availability: ${suggestion.availability}")
            println(" ")
        }
    }
}
```
+  API の詳細については、「*AWS API リファレンス*」の「[GetDomainSuggestions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetOperationDetail`
<a name="route-53-domains_GetOperationDetail_kotlin_1_topic"></a>

次のコード例は、`GetOperationDetail` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getOperationalDetail(opId: String?) {
    val detailRequest =
        GetOperationDetailRequest {
            operationId = opId
        }
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.getOperationDetail(detailRequest)
        println("Operation detail message is ${response.message}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[GetOperationDetail](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListDomains`
<a name="route-53-domains_ListDomains_kotlin_1_topic"></a>

次のコード例は、`ListDomains` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listDomains() {
    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .listDomainsPaginated(ListDomainsRequest {})
            .transform { it.domains?.forEach { obj -> emit(obj) } }
            .collect { content ->
                println("The domain name is ${content.domainName}")
            }
    }
}
```
+  API の詳細については、「**AWS SDK for Kotlin API リファレンス」の「[ListDomains](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListOperations`
<a name="route-53-domains_ListOperations_kotlin_1_topic"></a>

次のコード例は、`ListOperations` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listOperations() {
    val currentDate = Date()
    var localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
    val zoneOffset = ZoneOffset.of("+01:00")
    localDateTime = localDateTime.minusYears(1)
    val myTime: java.time.Instant? = localDateTime.toInstant(zoneOffset)
    val time2: Instant? = myTime?.let { Instant(it) }
    val operationsRequest =
        ListOperationsRequest {
            submittedSince = time2
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .listOperationsPaginated(operationsRequest)
            .transform { it.operations?.forEach { obj -> emit(obj) } }
            .collect { content ->
                println("Operation Id: ${content.operationId}")
                println("Status: ${content.status}")
                println("Date: ${content.submittedDate}")
            }
    }
}
```
+  API の詳細については、「**AWS SDK for Kotlin API リファレンス」の「[ListOperations](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListPrices`
<a name="route-53-domains_ListPrices_kotlin_1_topic"></a>

次のコード例は、`ListPrices` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllPrices(domainType: String?) {
    val pricesRequest =
        ListPricesRequest {
            tld = domainType
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .listPricesPaginated(pricesRequest)
            .transform { it.prices?.forEach { obj -> emit(obj) } }
            .collect { pr ->
                println("Registration: ${pr.registrationPrice} ${pr.registrationPrice?.currency}")
                println("Renewal: ${pr.renewalPrice?.price} ${pr.renewalPrice?.currency}")
                println("Transfer: ${pr.transferPrice?.price} ${pr.transferPrice?.currency}")
                println("Restoration: ${pr.restorationPrice?.price} ${pr.restorationPrice?.currency}")
            }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ListPrices](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `RegisterDomain`
<a name="route-53-domains_RegisterDomain_kotlin_1_topic"></a>

次のコード例は、`RegisterDomain` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun requestDomainRegistration(
    domainSuggestion: String?,
    phoneNumberVal: String?,
    emailVal: String?,
    firstNameVal: String?,
    lastNameVal: String?,
    cityVal: String?,
): String? {
    val contactDetail =
        ContactDetail {
            contactType = ContactType.Company
            state = "LA"
            countryCode = CountryCode.In
            email = emailVal
            firstName = firstNameVal
            lastName = lastNameVal
            city = cityVal
            phoneNumber = phoneNumberVal
            organizationName = "My Org"
            addressLine1 = "My Address"
            zipCode = "123 123"
        }

    val domainRequest =
        RegisterDomainRequest {
            adminContact = contactDetail
            registrantContact = contactDetail
            techContact = contactDetail
            domainName = domainSuggestion
            autoRenew = true
            durationInYears = 1
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        val response = route53DomainsClient.registerDomain(domainRequest)
        println("Registration requested. Operation Id: ${response.operationId}")
        return response.operationId
    }
}
```
+  API の詳細については、「**AWS SDK for Kotlin API リファレンス」の「[RegisterDomain](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ViewBilling`
<a name="route-53-domains_ViewBilling_kotlin_1_topic"></a>

次のコード例は、`ViewBilling` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/route53#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listBillingRecords() {
    val currentDate = Date()
    val localDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
    val zoneOffset = ZoneOffset.of("+01:00")
    val localDateTime2 = localDateTime.minusYears(1)
    val myStartTime = localDateTime2.toInstant(zoneOffset)
    val myEndTime = localDateTime.toInstant(zoneOffset)
    val timeStart: Instant? = myStartTime?.let { Instant(it) }
    val timeEnd: Instant? = myEndTime?.let { Instant(it) }

    val viewBillingRequest =
        ViewBillingRequest {
            start = timeStart
            end = timeEnd
        }

    Route53DomainsClient.fromEnvironment { region = "us-east-1" }.use { route53DomainsClient ->
        route53DomainsClient
            .viewBillingPaginated(viewBillingRequest)
            .transform { it.billingRecords?.forEach { obj -> emit(obj) } }
            .collect { billing ->
                println("Bill Date: ${billing.billDate}")
                println("Operation: ${billing.operation}")
                println("Price: ${billing.price}")
            }
    }
}
```
+  API の詳細については、「**AWS SDK for Kotlin API リファレンス」の「[ViewBilling](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon S3 の例
<a name="kotlin_1_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <bucketName> <key> <objectPath> <savePath> <toBucket>

    Where:
        bucketName - The Amazon S3 bucket to create.
        key - The key to use.
        objectPath - The path where the file is located (for example, C:/AWS/book2.pdf).   
        savePath - The path where the file is saved after it's downloaded (for example, C:/AWS/book2.pdf).     
        toBucket - An Amazon S3 bucket to where an object is copied to (for example, C:/AWS/book2.pdf). 
        """

    if (args.size != 4) {
        println(usage)
        exitProcess(1)
    }

    val bucketName = args[0]
    val key = args[1]
    val objectPath = args[2]
    val savePath = args[3]
    val toBucket = args[4]

    // Create an Amazon S3 bucket.
    createBucket(bucketName)

    // Update a local file to the Amazon S3 bucket.
    putObject(bucketName, key, objectPath)

    // Download the object to another local file.
    getObjectFromMrap(bucketName, key, savePath)

    // List all objects located in the Amazon S3 bucket.
    listBucketObs(bucketName)

    // Copy the object to another Amazon S3 bucket
    copyBucketOb(bucketName, key, toBucket)

    // Delete the object from the Amazon S3 bucket.
    deleteBucketObs(bucketName, key)

    // Delete the Amazon S3 bucket.
    deleteBucket(bucketName)
    println("All Amazon S3 operations were successfully performed")
}

suspend fun createBucket(bucketName: String) {
    val request =
        CreateBucketRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.createBucket(request)
        println("$bucketName is ready")
    }
}

suspend fun putObject(
    bucketName: String,
    objectKey: String,
    objectPath: String,
) {
    val metadataVal = mutableMapOf<String, String>()
    metadataVal["myVal"] = "test"

    val request =
        PutObjectRequest {
            bucket = bucketName
            key = objectKey
            metadata = metadataVal
            this.body = Paths.get(objectPath).asByteStream()
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        val response = s3.putObject(request)
        println("Tag information is ${response.eTag}")
    }
}

suspend fun getObjectFromMrap(
    bucketName: String,
    keyName: String,
    path: String,
) {
    val request =
        GetObjectRequest {
            key = keyName
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.getObject(request) { resp ->
            val myFile = File(path)
            resp.body?.writeToFile(myFile)
            println("Successfully read $keyName from $bucketName")
        }
    }
}

suspend fun listBucketObs(bucketName: String) {
    val request =
        ListObjectsRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->

        val response = s3.listObjects(request)
        response.contents?.forEach { myObject ->
            println("The name of the key is ${myObject.key}")
            println("The owner is ${myObject.owner}")
        }
    }
}

suspend fun copyBucketOb(
    fromBucket: String,
    objectKey: String,
    toBucket: String,
) {
    var encodedUrl = ""
    try {
        encodedUrl = URLEncoder.encode("$fromBucket/$objectKey", StandardCharsets.UTF_8.toString())
    } catch (e: UnsupportedEncodingException) {
        println("URL could not be encoded: " + e.message)
    }

    val request =
        CopyObjectRequest {
            copySource = encodedUrl
            bucket = toBucket
            key = objectKey
        }
    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.copyObject(request)
    }
}

suspend fun deleteBucketObs(
    bucketName: String,
    objectName: String,
) {
    val objectId =
        ObjectIdentifier {
            key = objectName
        }

    val delOb =
        Delete {
            objects = listOf(objectId)
        }

    val request =
        DeleteObjectsRequest {
            bucket = bucketName
            delete = delOb
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.deleteObjects(request)
        println("$objectName was deleted from $bucketName")
    }
}

suspend fun deleteBucket(bucketName: String?) {
    val request =
        DeleteBucketRequest {
            bucket = bucketName
        }
    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.deleteBucket(request)
        println("The $bucketName was successfully deleted!")
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateBucket](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteBucket](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteObjects](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetObject](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListObjectsV2](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [PutObject](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_kotlin_1_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun copyBucketObject(
    fromBucket: String,
    objectKey: String,
    toBucket: String,
) {
    var encodedUrl = ""
    try {
        encodedUrl = URLEncoder.encode("$fromBucket/$objectKey", StandardCharsets.UTF_8.toString())
    } catch (e: UnsupportedEncodingException) {
        println("URL could not be encoded: " + e.message)
    }

    val request =
        CopyObjectRequest {
            copySource = encodedUrl
            bucket = toBucket
            key = objectKey
        }
    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.copyObject(request)
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CopyObject](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_kotlin_1_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createNewBucket(bucketName: String) {
    val request =
        CreateBucketRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.createBucket(request)
        println("$bucketName is ready")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateBucket](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateMultiRegionAccessPoint`
<a name="s3_CreateMultiRegionAccessPoint_kotlin_1_topic"></a>

次のコード例は、`CreateMultiRegionAccessPoint` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。
us-west-2 リージョンにリクエストを送信するように S3 コントロールクライアントを設定します。  

```
        suspend fun createS3ControlClient(): S3ControlClient {
            // Configure your S3ControlClient to send requests to US West (Oregon).
            val s3Control = S3ControlClient.fromEnvironment {
                region = "us-west-2"
            }
            return s3Control
        }
```
マルチリージョンアクセスポイントを作成します。  

```
    suspend fun createMrap(
        s3Control: S3ControlClient,
        accountIdParam: String,
        bucketName1: String,
        bucketName2: String,
        mrapName: String,
    ): String {
        println("Creating MRAP ...")
        val createMrapResponse: CreateMultiRegionAccessPointResponse =
            s3Control.createMultiRegionAccessPoint {
                accountId = accountIdParam
                clientToken = UUID.randomUUID().toString()
                details {
                    name = mrapName
                    regions = listOf(
                        Region {
                            bucket = bucketName1
                        },
                        Region {
                            bucket = bucketName2
                        },
                    )
                }
            }
        val requestToken: String? = createMrapResponse.requestTokenArn

        // Use the request token to check for the status of the CreateMultiRegionAccessPoint operation.
        if (requestToken != null) {
            waitForSucceededStatus(s3Control, requestToken, accountIdParam)
            println("MRAP created")
        }

        val getMrapResponse =
            s3Control.getMultiRegionAccessPoint(
                input = GetMultiRegionAccessPointRequest {
                    accountId = accountIdParam
                    name = mrapName
                },
            )
        val mrapAlias = getMrapResponse.accessPoint?.alias
        return "arn:aws:s3::$accountIdParam:accesspoint/$mrapAlias"
    }
```
マルチリージョンアクセスポイントが使用可能になるまで待ちます。  

```
        suspend fun waitForSucceededStatus(
            s3Control: S3ControlClient,
            requestToken: String,
            accountIdParam: String,
            timeBetweenChecks: Duration = 1.minutes,
        ) {
            var describeResponse: DescribeMultiRegionAccessPointOperationResponse
            describeResponse = s3Control.describeMultiRegionAccessPointOperation(
                input = DescribeMultiRegionAccessPointOperationRequest {
                    accountId = accountIdParam
                    requestTokenArn = requestToken
                },
            )

            var status: String? = describeResponse.asyncOperation?.requestStatus
            while (status != "SUCCEEDED") {
                delay(timeBetweenChecks)
                describeResponse = s3Control.describeMultiRegionAccessPointOperation(
                    input = DescribeMultiRegionAccessPointOperationRequest {
                        accountId = accountIdParam
                        requestTokenArn = requestToken
                    },
                )
                status = describeResponse.asyncOperation?.requestStatus
                println(status)
            }
        }
```
+  詳細については、「[AWS SDK for Kotlin デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/use-services-s3-mrap.html)」を参照してください。
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[CreateMultiRegionAccessPoint](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。**

### `DeleteBucketPolicy`
<a name="s3_DeleteBucketPolicy_kotlin_1_topic"></a>

次のコード例は、`DeleteBucketPolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteS3BucketPolicy(bucketName: String?) {
    val request =
        DeleteBucketPolicyRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.deleteBucketPolicy(request)
        println("Done!")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteBucketPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_kotlin_1_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteBucketObjects(
    bucketName: String,
    objectName: String,
) {
    val objectId =
        ObjectIdentifier {
            key = objectName
        }

    val delOb =
        Delete {
            objects = listOf(objectId)
        }

    val request =
        DeleteObjectsRequest {
            bucket = bucketName
            delete = delOb
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.deleteObjects(request)
        println("$objectName was deleted from $bucketName")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DeleteObjects](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetBucketPolicy`
<a name="s3_GetBucketPolicy_kotlin_1_topic"></a>

次のコード例は、`GetBucketPolicy` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getPolicy(bucketName: String): String? {
    println("Getting policy for bucket $bucketName")

    val request =
        GetBucketPolicyRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        val policyRes = s3.getBucketPolicy(request)
        return policyRes.policy
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[GetBucketPolicy](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetObject`
<a name="s3_GetObject_kotlin_1_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getObjectBytes(
    bucketName: String,
    keyName: String,
    path: String,
) {
    val request =
        GetObjectRequest {
            key = keyName
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.getObject(request) { resp ->
            val myFile = File(path)
            resp.body?.writeToFile(myFile)
            println("Successfully read $keyName from $bucketName")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[GetObject](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetObjectAcl`
<a name="s3_GetObjectAcl_kotlin_1_topic"></a>

次のコード例は、`GetObjectAcl` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getBucketACL(
    objectKey: String,
    bucketName: String,
) {
    val request =
        GetObjectAclRequest {
            bucket = bucketName
            key = objectKey
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        val response = s3.getObjectAcl(request)
        response.grants?.forEach { grant ->
            println("Grant permission is ${grant.permission}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[GetObjectAcl](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_kotlin_1_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listBucketObjects(bucketName: String) {
    val request =
        ListObjectsRequest {
            bucket = bucketName
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        val response = s3.listObjects(request)
        response.contents?.forEach { myObject ->
            println("The name of the key is ${myObject.key}")
            println("The object is ${myObject.size?.let { calKb(it) }} KBs")
            println("The owner is ${myObject.owner}")
        }
    }
}

private fun calKb(intValue: Long): Long = intValue / 1024
```
+  API の詳細については、「AWS SDK for Kotlin API リファレンス」の「[ListObjectsV2](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。**

### `PutBucketAcl`
<a name="s3_PutBucketAcl_kotlin_1_topic"></a>

次のコード例は、`PutBucketAcl` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun setBucketAcl(
    bucketName: String,
    idVal: String,
) {
    val myGrant =
        Grantee {
            id = idVal
            type = Type.CanonicalUser
        }

    val ownerGrant =
        Grant {
            grantee = myGrant
            permission = Permission.FullControl
        }

    val grantList = mutableListOf<Grant>()
    grantList.add(ownerGrant)

    val ownerOb =
        Owner {
            id = idVal
        }

    val acl =
        AccessControlPolicy {
            owner = ownerOb
            grants = grantList
        }

    val request =
        PutBucketAclRequest {
            bucket = bucketName
            accessControlPolicy = acl
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        s3.putBucketAcl(request)
        println("An ACL was successfully set on $bucketName")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[PutBucketAcl](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `PutObject`
<a name="s3_PutObject_kotlin_1_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。

```
suspend fun putS3Object(
    bucketName: String,
    objectKey: String,
    objectPath: String,
) {
    val metadataVal = mutableMapOf<String, String>()
    metadataVal["myVal"] = "test"

    val request =
        PutObjectRequest {
            bucket = bucketName
            key = objectKey
            metadata = metadataVal
            body = File(objectPath).asByteStream()
        }

    S3Client.fromEnvironment { region = "us-east-1" }.use { s3 ->
        val response = s3.putObject(request)
        println("Tag information is ${response.eTag}")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[PutObject](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_kotlin_1_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。
`GetObject` の署名済みリクエストを作成し、その URL を使用してオブジェクトをダウンロードします。  

```
suspend fun getObjectPresigned(
    s3: S3Client,
    bucketName: String,
    keyName: String,
): String {
    // Create a GetObjectRequest.
    val unsignedRequest =
        GetObjectRequest {
            bucket = bucketName
            key = keyName
        }

    // Presign the GetObject request.
    val presignedRequest = s3.presignGetObject(unsignedRequest, 24.hours)

    // Use the URL from the presigned HttpRequest in a subsequent HTTP GET request to retrieve the object.
    val objectContents = URL(presignedRequest.url.toString()).readText()

    return objectContents
}
```
詳細オプションを使用して `GetObject` 署名済みリクエストを作成します。  

```
suspend fun getObjectPresignedMoreOptions(
    s3: S3Client,
    bucketName: String,
    keyName: String,
): HttpRequest {
    // Create a GetObjectRequest.
    val unsignedRequest =
        GetObjectRequest {
            bucket = bucketName
            key = keyName
        }

    // Presign the GetObject request.
    val presignedRequest =
        s3.presignGetObject(unsignedRequest, signer = CrtAwsSigner) {
            signingDate = Instant.now() + 12.hours // Presigned request can be used 12 hours from now.
            algorithm = AwsSigningAlgorithm.SIGV4_ASYMMETRIC
            signatureType = AwsSignatureType.HTTP_REQUEST_VIA_QUERY_PARAMS
            expiresAfter = 8.hours // Presigned request expires 8 hours later.
        }
    return presignedRequest
}
```
`PutObject` の署名済みリクエストを作成し、それを使用してオブジェクトをアップロードします。  

```
suspend fun putObjectPresigned(
    s3: S3Client,
    bucketName: String,
    keyName: String,
    content: String,
) {
    // Create a PutObjectRequest.
    val unsignedRequest =
        PutObjectRequest {
            bucket = bucketName
            key = keyName
        }

    // Presign the request.
    val presignedRequest = s3.presignPutObject(unsignedRequest, 24.hours)

    // Use the URL and any headers from the presigned HttpRequest in a subsequent HTTP PUT request to retrieve the object.
    // Create a PUT request using the OKHttpClient API.
    val putRequest =
        Request
            .Builder()
            .url(presignedRequest.url.toString())
            .apply {
                presignedRequest.headers.forEach { key, values ->
                    header(key, values.joinToString(", "))
                }
            }.put(content.toRequestBody())
            .build()

    val response = OkHttpClient().newCall(putRequest).execute()
    assert(response.isSuccessful)
}
```
+  詳細については、「[AWS SDK for Kotlin デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/presign-requests.html)」を参照してください。

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_kotlin_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Kotlin**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_pam) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_kotlin_1_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Kotlin**  
 Amazon Simple Storage Service (Amazon S3) バケットにある画像内からカテゴリ別にオブジェクトを Amazon Rekognition を使用して識別するアプリケーションを、Amazon Rekognition Kotlin API を使用して作成する方法を示します。アプリケーションは、Amazon Simple Email Service (Amazon SES) を使用して、結果を記載した E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_photo_analyzer_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### マルチリージョンアクセスポイント からオブジェクトを取得する
<a name="s3_GetObject_MRAP_kotlin_1_topic"></a>

次のコード例は、マルチリージョンアクセスポイントからオブジェクトを取得する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/s3#code-examples)での設定と実行の方法を確認してください。
非対称 Sigv4 (Sigv4a) 署名アルゴリズムを使用するように S3 クライアントを設定します。  

```
        suspend fun createS3Client(): S3Client {
            // Configure your S3Client to use the Asymmetric SigV4 (SigV4a) signing algorithm.
            val sigV4aScheme = SigV4AsymmetricAuthScheme(DefaultAwsSigner)
            val s3 = S3Client.fromEnvironment {
                authSchemes = listOf(sigV4aScheme)
            }
            return s3
        }
```
バケット名の代わりにマルチリージョンアクセスポイント ARN を使用してオブジェクトを取得します。  

```
    suspend fun getObjectFromMrap(
        s3: S3Client,
        mrapArn: String,
        keyName: String,
    ): String? {
        val request = GetObjectRequest {
            bucket = mrapArn // Use the ARN instead of the bucket name for object operations.
            key = keyName
        }

        var stringObj: String? = null
        s3.getObject(request) { resp ->
            stringObj = resp.body?.decodeToString()
            if (stringObj != null) {
                println("Successfully read $keyName from $mrapArn")
            }
        }
        return stringObj
    }
```
+  詳細については、「[AWS SDK for Kotlin デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/use-services-s3-mrap.html)」を参照してください。
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[GetObject](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した SageMaker AI の例
<a name="kotlin_1_sagemaker_code_examples"></a>

次のコード例は、SageMaker AI で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello SageMaker AI
<a name="sagemaker_Hello_kotlin_1_topic"></a>

次のコード例は、SageMaker AI の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sagemaker#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listBooks() {
    SageMakerClient.fromEnvironment { region = "us-west-2" }.use { sageMakerClient ->
        val response = sageMakerClient.listNotebookInstances(ListNotebookInstancesRequest {})
        response.notebookInstances?.forEach { item ->
            println("The notebook name is: ${item.notebookInstanceName}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListNotebookInstances](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## アクション
<a name="actions"></a>

### `CreatePipeline`
<a name="sagemaker_CreatePipeline_kotlin_1_topic"></a>

次のコード例は、`CreatePipeline` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
// Create a pipeline from the example pipeline JSON.
suspend fun setupPipeline(filePath: String?, roleArnVal: String?, functionArnVal: String?, pipelineNameVal: String?) {
    println("Setting up the pipeline.")
    val parser = JSONParser()

    // Read JSON and get pipeline definition.
    FileReader(filePath).use { reader ->
        val obj: Any = parser.parse(reader)
        val jsonObject: JSONObject = obj as JSONObject
        val stepsArray: JSONArray = jsonObject.get("Steps") as JSONArray
        for (stepObj in stepsArray) {
            val step: JSONObject = stepObj as JSONObject
            if (step.containsKey("FunctionArn")) {
                step.put("FunctionArn", functionArnVal)
            }
        }
        println(jsonObject)

        // Create the pipeline.
        val pipelineRequest = CreatePipelineRequest {
            pipelineDescription = "Kotlin SDK example pipeline"
            roleArn = roleArnVal
            pipelineName = pipelineNameVal
            pipelineDefinition = jsonObject.toString()
        }

        SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
            sageMakerClient.createPipeline(pipelineRequest)
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreatePipeline](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeletePipeline`
<a name="sagemaker_DeletePipeline_kotlin_1_topic"></a>

次のコード例は、`DeletePipeline` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
// Delete a SageMaker pipeline by name.
suspend fun deletePipeline(pipelineNameVal: String) {
    val pipelineRequest = DeletePipelineRequest {
        pipelineName = pipelineNameVal
    }

    SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
        sageMakerClient.deletePipeline(pipelineRequest)
        println("*** Successfully deleted $pipelineNameVal")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeletePipeline](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribePipelineExecution`
<a name="sagemaker_DescribePipelineExecution_kotlin_1_topic"></a>

次のコード例は、`DescribePipelineExecution` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
suspend fun waitForPipelineExecution(executionArn: String?) {
    var status: String
    var index = 0
    do {
        val pipelineExecutionRequest = DescribePipelineExecutionRequest {
            pipelineExecutionArn = executionArn
        }

        SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
            val response = sageMakerClient.describePipelineExecution(pipelineExecutionRequest)
            status = response.pipelineExecutionStatus.toString()
            println("$index. The status of the pipeline is $status")
            TimeUnit.SECONDS.sleep(4)
            index++
        }
    } while ("Executing" == status)
    println("Pipeline finished with status $status")
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribePipelineExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `StartPipelineExecution`
<a name="sagemaker_StartPipelineExecution_kotlin_1_topic"></a>

次のコード例は、`StartPipelineExecution` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
// Start a pipeline run with job configurations.
suspend fun executePipeline(bucketName: String, queueUrl: String?, roleArn: String?, pipelineNameVal: String): String? {
    println("Starting pipeline execution.")
    val inputBucketLocation = "s3://$bucketName/samplefiles/latlongtest.csv"
    val output = "s3://$bucketName/outputfiles/"

    val gson = GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .setPrettyPrinting()
        .create()

    // Set up all parameters required to start the pipeline.
    val parameters: MutableList<Parameter> = java.util.ArrayList<Parameter>()

    val para1 = Parameter {
        name = "parameter_execution_role"
        value = roleArn
    }
    val para2 = Parameter {
        name = "parameter_queue_url"
        value = queueUrl
    }

    val inputJSON = """{
        "DataSourceConfig": {
        "S3Data": {
            "S3Uri": "s3://$bucketName/samplefiles/latlongtest.csv"
        },
        "Type": "S3_DATA"
        },
        "DocumentType": "CSV"
    }"""
    println(inputJSON)
    val para3 = Parameter {
        name = "parameter_vej_input_config"
        value = inputJSON
    }

    // Create an ExportVectorEnrichmentJobOutputConfig object.
    val jobS3Data = VectorEnrichmentJobS3Data {
        s3Uri = output
    }

    val outputConfig = ExportVectorEnrichmentJobOutputConfig {
        s3Data = jobS3Data
    }

    val gson4: String = gson.toJson(outputConfig)
    val para4: Parameter = Parameter {
        name = "parameter_vej_export_config"
        value = gson4
    }
    println("parameter_vej_export_config:" + gson.toJson(outputConfig))

    val para5JSON =
        "{\"MapMatchingConfig\":null,\"ReverseGeocodingConfig\":{\"XAttributeName\":\"Longitude\",\"YAttributeName\":\"Latitude\"}}"

    val para5: Parameter = Parameter {
        name = "parameter_step_1_vej_config"
        value = para5JSON
    }

    parameters.add(para1)
    parameters.add(para2)
    parameters.add(para3)
    parameters.add(para4)
    parameters.add(para5)

    val pipelineExecutionRequest = StartPipelineExecutionRequest {
        pipelineExecutionDescription = "Created using Kotlin SDK"
        pipelineExecutionDisplayName = "$pipelineName-example-execution"
        pipelineParameters = parameters
        pipelineName = pipelineNameVal
    }

    SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
        val response = sageMakerClient.startPipelineExecution(pipelineExecutionRequest)
        return response.pipelineExecutionArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[StartPipelineExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 地理空間ジョブとパイプラインの使用を開始する
<a name="sagemaker_Scenario_Pipelines_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パイプラインのリソースを設定します。
+ 地理空間ジョブを実行するパイプラインを設定します。
+ パイプラインの実行を開始します。
+ ジョブ実行のステータスをモニタリングします。
+ パイプラインの出力を表示します。
+ リソースをクリーンアップします。

詳細については、[「Community.aws で SDK を使用して SageMaker パイプラインを作成および実行する AWS SDKs](https://community.aws/posts/create-and-run-sagemaker-pipelines-using-aws-sdks)」を参照してください。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/workflow_sagemaker_pipes#code-examples)での設定と実行の方法を確認してください。

```
val DASHES = String(CharArray(80)).replace("\u0000", "-")
private var eventSourceMapping = ""

suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
          <sageMakerRoleName> <lambdaRoleName> <functionName> <functionKey> <queueName> <bucketName> <bucketFunction> <lnglatData> <spatialPipelinePath> <pipelineName>

    Where:
        sageMakerRoleName - The name of the Amazon SageMaker role.
        lambdaRoleName - The name of the AWS Lambda role.
        functionName - The name of the AWS Lambda function (for example,SageMakerExampleFunction).
        functionKey - The name of the Amazon S3 key name that represents the Lambda function (for example, SageMakerLambda.zip).
        queueName - The name of the Amazon Simple Queue Service (Amazon SQS) queue.
        bucketName - The name of the Amazon Simple Storage Service (Amazon S3) bucket.
        bucketFunction - The name of the Amazon S3 bucket that contains the Lambda ZIP file. 
        lnglatData - The file location of the latlongtest.csv file required for this use case.
        spatialPipelinePath - The file location of the GeoSpatialPipeline.json file required for this use case.
        pipelineName - The name of the pipeline to create (for example, sagemaker-sdk-example-pipeline).
    """

    if (args.size != 10) {
        println(usage)
        exitProcess(1)
    }

    val sageMakerRoleName = args[0]
    val lambdaRoleName = args[1]
    val functionKey = args[2]
    val functionName = args[3]
    val queueName = args[4]
    val bucketName = args[5]
    val bucketFunction = args[6]
    val lnglatData = args[7]
    val spatialPipelinePath = args[8]
    val pipelineName = args[9]
    val handlerName = "org.example.SageMakerLambdaFunction::handleRequest"

    println(DASHES)
    println("Welcome to the Amazon SageMaker pipeline example scenario.")
    println(
        """
         This example workflow will guide you through setting up and running an
         Amazon SageMaker pipeline. The pipeline uses an AWS Lambda function and an
         Amazon SQS Queue. It runs a vector enrichment reverse geocode job to
         reverse geocode addresses in an input file and store the results in an export file.
        """.trimIndent(),
    )
    println(DASHES)

    println(DASHES)
    println("First, we will set up the roles, functions, and queue needed by the SageMaker pipeline.")
    val lambdaRoleArn: String = checkLambdaRole(lambdaRoleName)
    val sageMakerRoleArn: String = checkSageMakerRole(sageMakerRoleName)
    val functionArn = checkFunction(functionName, bucketFunction, functionKey, handlerName, lambdaRoleArn)
    val queueUrl = checkQueue(queueName, functionName)
    println(DASHES)

    println(DASHES)
    println("Setting up bucket $bucketName")
    if (!checkBucket(bucketName)) {
        setupBucket(bucketName)
        println("Put $lnglatData into $bucketName")
        val objectKey = "samplefiles/latlongtest.csv"
        putS3Object(bucketName, objectKey, lnglatData)
    }
    println(DASHES)

    println(DASHES)
    println("Now we can create and run our pipeline.")
    setupPipeline(spatialPipelinePath, sageMakerRoleArn, functionArn, pipelineName)
    val pipelineExecutionARN = executePipeline(bucketName, queueUrl, sageMakerRoleArn, pipelineName)
    println("The pipeline execution ARN value is $pipelineExecutionARN")
    waitForPipelineExecution(pipelineExecutionARN)
    println("Wait 30 secs to get output results $bucketName")
    TimeUnit.SECONDS.sleep(30)
    getOutputResults(bucketName)
    println(DASHES)

    println(DASHES)
    println(
        """
             The pipeline has completed. To view the pipeline and runs in SageMaker Studio, follow these instructions:
             https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-studio.html
        """.trimIndent(),
    )
    println(DASHES)

    println(DASHES)
    println("Do you want to delete the AWS resources used in this Workflow? (y/n)")
    val `in` = Scanner(System.`in`)
    val delResources = `in`.nextLine()
    if (delResources.compareTo("y") == 0) {
        println("Lets clean up the AWS resources. Wait 30 seconds")
        TimeUnit.SECONDS.sleep(30)
        deleteEventSourceMapping(functionName)
        deleteSQSQueue(queueName)
        listBucketObjects(bucketName)
        deleteBucket(bucketName)
        delLambdaFunction(functionName)
        deleteLambdaRole(lambdaRoleName)
        deleteSagemakerRole(sageMakerRoleName)
        deletePipeline(pipelineName)
    } else {
        println("The AWS Resources were not deleted!")
    }
    println(DASHES)

    println(DASHES)
    println("SageMaker pipeline scenario is complete.")
    println(DASHES)
}

// Delete a SageMaker pipeline by name.
suspend fun deletePipeline(pipelineNameVal: String) {
    val pipelineRequest = DeletePipelineRequest {
        pipelineName = pipelineNameVal
    }

    SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
        sageMakerClient.deletePipeline(pipelineRequest)
        println("*** Successfully deleted $pipelineNameVal")
    }
}

suspend fun deleteSagemakerRole(roleNameVal: String) {
    val sageMakerRolePolicies = getSageMakerRolePolicies()
    IamClient { region = "us-west-2" }.use { iam ->
        for (policy in sageMakerRolePolicies) {
            // First the policy needs to be detached.
            val rolePolicyRequest = DetachRolePolicyRequest {
                policyArn = policy
                roleName = roleNameVal
            }
            iam.detachRolePolicy(rolePolicyRequest)
        }

        // Delete the role.
        val roleRequest = DeleteRoleRequest {
            roleName = roleNameVal
        }
        iam.deleteRole(roleRequest)
        println("*** Successfully deleted $roleNameVal")
    }
}

suspend fun deleteLambdaRole(roleNameVal: String) {
    val lambdaRolePolicies = getLambdaRolePolicies()
    IamClient { region = "us-west-2" }.use { iam ->
        for (policy in lambdaRolePolicies) {
            // First the policy needs to be detached.
            val rolePolicyRequest = DetachRolePolicyRequest {
                policyArn = policy
                roleName = roleNameVal
            }
            iam.detachRolePolicy(rolePolicyRequest)
        }

        // Delete the role.
        val roleRequest = DeleteRoleRequest {
            roleName = roleNameVal
        }
        iam.deleteRole(roleRequest)
        println("*** Successfully deleted $roleNameVal")
    }
}

suspend fun delLambdaFunction(myFunctionName: String) {
    val request = DeleteFunctionRequest {
        functionName = myFunctionName
    }

    LambdaClient { region = "us-west-2" }.use { awsLambda ->
        awsLambda.deleteFunction(request)
        println("$myFunctionName was deleted")
    }
}

suspend fun deleteBucket(bucketName: String?) {
    val request = DeleteBucketRequest {
        bucket = bucketName
    }
    S3Client { region = "us-east-1" }.use { s3 ->
        s3.deleteBucket(request)
        println("The $bucketName was successfully deleted!")
    }
}

suspend fun deleteBucketObjects(bucketName: String, objectName: String?) {
    val toDelete = ArrayList<ObjectIdentifier>()
    val obId = ObjectIdentifier {
        key = objectName
    }
    toDelete.add(obId)
    val delOb = Delete {
        objects = toDelete
    }
    val dor = DeleteObjectsRequest {
        bucket = bucketName
        delete = delOb
    }

    S3Client { region = "us-east-1" }.use { s3Client ->
        s3Client.deleteObjects(dor)
        println("*** $bucketName objects were deleted.")
    }
}

suspend fun listBucketObjects(bucketNameVal: String) {
    val listObjects = ListObjectsRequest {
        bucket = bucketNameVal
    }

    S3Client { region = "us-east-1" }.use { s3Client ->
        val res = s3Client.listObjects(listObjects)
        val objects = res.contents
        if (objects != null) {
            for (myValue in objects) {
                println("The name of the key is ${myValue.key}")
                deleteBucketObjects(bucketNameVal, myValue.key)
            }
        }
    }
}

// Delete the specific Amazon SQS queue.
suspend fun deleteSQSQueue(queueNameVal: String?) {
    val getQueueRequest = GetQueueUrlRequest {
        queueName = queueNameVal
    }

    SqsClient { region = "us-west-2" }.use { sqsClient ->
        val urlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl
        val deleteQueueRequest = DeleteQueueRequest {
            queueUrl = urlVal
        }
        sqsClient.deleteQueue(deleteQueueRequest)
    }
}

// Delete the queue event mapping.
suspend fun deleteEventSourceMapping(functionNameVal: String) {
    if (eventSourceMapping.compareTo("") == 0) {
        LambdaClient { region = "us-west-2" }.use { lambdaClient ->
            val request = ListEventSourceMappingsRequest {
                functionName = functionNameVal
            }
            val response = lambdaClient.listEventSourceMappings(request)
            val eventList = response.eventSourceMappings
            if (eventList != null) {
                for (event in eventList) {
                    eventSourceMapping = event.uuid.toString()
                }
            }
        }
    }

    val eventSourceMappingRequest = DeleteEventSourceMappingRequest {
        uuid = eventSourceMapping
    }
    LambdaClient { region = "us-west-2" }.use { lambdaClient ->
        lambdaClient.deleteEventSourceMapping(eventSourceMappingRequest)
        println("The event mapping is deleted!")
    }
}

// Reads the objects in the S3 bucket and displays the values.
private suspend fun readObject(bucketName: String, keyVal: String?) {
    println("Output file contents: \n")
    val objectRequest = GetObjectRequest {
        bucket = bucketName
        key = keyVal
    }
    S3Client { region = "us-east-1" }.use { s3Client ->
        s3Client.getObject(objectRequest) { resp ->
            val byteArray = resp.body?.toByteArray()
            val text = byteArray?.let { String(it, StandardCharsets.UTF_8) }
            println("Text output: $text")
        }
    }
}

// Display the results from the output directory.
suspend fun getOutputResults(bucketName: String?) {
    println("Getting output results $bucketName.")
    val listObjectsRequest = ListObjectsRequest {
        bucket = bucketName
        prefix = "outputfiles/"
    }
    S3Client { region = "us-east-1" }.use { s3Client ->
        val response = s3Client.listObjects(listObjectsRequest)
        val s3Objects: List<Object>? = response.contents
        if (s3Objects != null) {
            for (`object` in s3Objects) {
                if (bucketName != null) {
                    readObject(bucketName, (`object`.key))
                }
            }
        }
    }
}

suspend fun waitForPipelineExecution(executionArn: String?) {
    var status: String
    var index = 0
    do {
        val pipelineExecutionRequest = DescribePipelineExecutionRequest {
            pipelineExecutionArn = executionArn
        }

        SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
            val response = sageMakerClient.describePipelineExecution(pipelineExecutionRequest)
            status = response.pipelineExecutionStatus.toString()
            println("$index. The status of the pipeline is $status")
            TimeUnit.SECONDS.sleep(4)
            index++
        }
    } while ("Executing" == status)
    println("Pipeline finished with status $status")
}

// Start a pipeline run with job configurations.
suspend fun executePipeline(bucketName: String, queueUrl: String?, roleArn: String?, pipelineNameVal: String): String? {
    println("Starting pipeline execution.")
    val inputBucketLocation = "s3://$bucketName/samplefiles/latlongtest.csv"
    val output = "s3://$bucketName/outputfiles/"

    val gson = GsonBuilder()
        .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
        .setPrettyPrinting()
        .create()

    // Set up all parameters required to start the pipeline.
    val parameters: MutableList<Parameter> = java.util.ArrayList<Parameter>()

    val para1 = Parameter {
        name = "parameter_execution_role"
        value = roleArn
    }
    val para2 = Parameter {
        name = "parameter_queue_url"
        value = queueUrl
    }

    val inputJSON = """{
        "DataSourceConfig": {
        "S3Data": {
            "S3Uri": "s3://$bucketName/samplefiles/latlongtest.csv"
        },
        "Type": "S3_DATA"
        },
        "DocumentType": "CSV"
    }"""
    println(inputJSON)
    val para3 = Parameter {
        name = "parameter_vej_input_config"
        value = inputJSON
    }

    // Create an ExportVectorEnrichmentJobOutputConfig object.
    val jobS3Data = VectorEnrichmentJobS3Data {
        s3Uri = output
    }

    val outputConfig = ExportVectorEnrichmentJobOutputConfig {
        s3Data = jobS3Data
    }

    val gson4: String = gson.toJson(outputConfig)
    val para4: Parameter = Parameter {
        name = "parameter_vej_export_config"
        value = gson4
    }
    println("parameter_vej_export_config:" + gson.toJson(outputConfig))

    val para5JSON =
        "{\"MapMatchingConfig\":null,\"ReverseGeocodingConfig\":{\"XAttributeName\":\"Longitude\",\"YAttributeName\":\"Latitude\"}}"

    val para5: Parameter = Parameter {
        name = "parameter_step_1_vej_config"
        value = para5JSON
    }

    parameters.add(para1)
    parameters.add(para2)
    parameters.add(para3)
    parameters.add(para4)
    parameters.add(para5)

    val pipelineExecutionRequest = StartPipelineExecutionRequest {
        pipelineExecutionDescription = "Created using Kotlin SDK"
        pipelineExecutionDisplayName = "$pipelineName-example-execution"
        pipelineParameters = parameters
        pipelineName = pipelineNameVal
    }

    SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
        val response = sageMakerClient.startPipelineExecution(pipelineExecutionRequest)
        return response.pipelineExecutionArn
    }
}

// Create a pipeline from the example pipeline JSON.
suspend fun setupPipeline(filePath: String?, roleArnVal: String?, functionArnVal: String?, pipelineNameVal: String?) {
    println("Setting up the pipeline.")
    val parser = JSONParser()

    // Read JSON and get pipeline definition.
    FileReader(filePath).use { reader ->
        val obj: Any = parser.parse(reader)
        val jsonObject: JSONObject = obj as JSONObject
        val stepsArray: JSONArray = jsonObject.get("Steps") as JSONArray
        for (stepObj in stepsArray) {
            val step: JSONObject = stepObj as JSONObject
            if (step.containsKey("FunctionArn")) {
                step.put("FunctionArn", functionArnVal)
            }
        }
        println(jsonObject)

        // Create the pipeline.
        val pipelineRequest = CreatePipelineRequest {
            pipelineDescription = "Kotlin SDK example pipeline"
            roleArn = roleArnVal
            pipelineName = pipelineNameVal
            pipelineDefinition = jsonObject.toString()
        }

        SageMakerClient { region = "us-west-2" }.use { sageMakerClient ->
            sageMakerClient.createPipeline(pipelineRequest)
        }
    }
}

suspend fun putS3Object(bucketName: String, objectKey: String, objectPath: String) {
    val request = PutObjectRequest {
        bucket = bucketName
        key = objectKey
        body = File(objectPath).asByteStream()
    }

    S3Client { region = "us-east-1" }.use { s3 ->
        s3.putObject(request)
        println("Successfully placed $objectKey into bucket $bucketName")
    }
}

suspend fun setupBucket(bucketName: String) {
    val request = CreateBucketRequest {
        bucket = bucketName
    }

    S3Client { region = "us-east-1" }.use { s3 ->
        s3.createBucket(request)
        println("$bucketName is ready")
    }
}

suspend fun checkBucket(bucketName: String): Boolean {
    try {
        val headBucketRequest = HeadBucketRequest {
            bucket = bucketName
        }
        S3Client { region = "us-east-1" }.use { s3Client ->
            s3Client.headBucket(headBucketRequest)
            println("$bucketName exists")
            return true
        }
    } catch (e: S3Exception) {
        println("Bucket does not exist")
    }
    return false
}

// Connect the queue to the Lambda function as an event source.
suspend fun connectLambda(queueUrlVal: String?, lambdaNameVal: String?) {
    println("Connecting the Lambda function and queue for the pipeline.")
    var queueArn = ""

    // Specify the attributes to retrieve.
    val atts: MutableList<QueueAttributeName> = ArrayList()
    atts.add(QueueAttributeName.QueueArn)
    val attributesRequest = GetQueueAttributesRequest {
        queueUrl = queueUrlVal
        attributeNames = atts
    }

    SqsClient { region = "us-west-2" }.use { sqsClient ->
        val response = sqsClient.getQueueAttributes(attributesRequest)
        val queueAtts = response.attributes
        if (queueAtts != null) {
            for ((key, value) in queueAtts) {
                println("Key = $key, Value = $value")
                queueArn = value
            }
        }
    }
    val eventSourceMappingRequest = CreateEventSourceMappingRequest {
        eventSourceArn = queueArn
        functionName = lambdaNameVal
    }
    LambdaClient { region = "us-west-2" }.use { lambdaClient ->
        val response1 = lambdaClient.createEventSourceMapping(eventSourceMappingRequest)
        eventSourceMapping = response1.uuid.toString()
        println("The mapping between the event source and Lambda function was successful")
    }
}

// Set up the SQS queue to use with the pipeline.
suspend fun setupQueue(queueNameVal: String, lambdaNameVal: String): String {
    println("Setting up queue named $queueNameVal")
    val queueAtt: MutableMap<String, String> = HashMap()
    queueAtt.put("DelaySeconds", "5")
    queueAtt.put("ReceiveMessageWaitTimeSeconds", "5")
    queueAtt.put("VisibilityTimeout", "300")

    val createQueueRequest = CreateQueueRequest {
        queueName = queueNameVal
        attributes = queueAtt
    }

    SqsClient { region = "us-west-2" }.use { sqsClient ->
        sqsClient.createQueue(createQueueRequest)
        println("\nGet queue url")
        val getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest { queueName = queueNameVal })
        TimeUnit.SECONDS.sleep(15)
        connectLambda(getQueueUrlResponse.queueUrl, lambdaNameVal)
        println("Queue ready with Url " + getQueueUrlResponse.queueUrl)
        return getQueueUrlResponse.queueUrl.toString()
    }
}

// Checks to see if the Amazon SQS queue exists. If not, this method creates a new queue
// and returns the ARN value.
suspend fun checkQueue(queueNameVal: String, lambdaNameVal: String): String? {
    println("Checking to see if the queue exists. If not, a new queue will be created for use in this workflow.")
    var queueUrl: String
    try {
        val request = GetQueueUrlRequest {
            queueName = queueNameVal
        }

        SqsClient { region = "us-west-2" }.use { sqsClient ->
            val response = sqsClient.getQueueUrl(request)
            queueUrl = response.queueUrl.toString()
            println(queueUrl)
        }
    } catch (e: SqsException) {
        println(e.message + " A new queue will be created")
        queueUrl = setupQueue(queueNameVal, lambdaNameVal)
    }
    return queueUrl
}

suspend fun createNewFunction(myFunctionName: String, s3BucketName: String, myS3Key: String, myHandler: String, myRole: String): String {
    val functionCode = FunctionCode {
        s3Bucket = s3BucketName
        s3Key = myS3Key
    }

    val request = CreateFunctionRequest {
        functionName = myFunctionName
        code = functionCode
        description = "Created by the Lambda Kotlin API"
        handler = myHandler
        role = myRole
        runtime = Runtime.Java11
        memorySize = 1024
        timeout = 200
    }

    LambdaClient { region = "us-west-2" }.use { awsLambda ->
        val functionResponse = awsLambda.createFunction(request)
        awsLambda.waitUntilFunctionActive {
            functionName = myFunctionName
        }
        println("${functionResponse.functionArn} was created")
        return functionResponse.functionArn.toString()
    }
}

suspend fun checkFunction(myFunctionName: String, s3BucketName: String, myS3Key: String, myHandler: String, myRole: String): String {
    println("Checking to see if the function exists. If not, a new AWS Lambda function will be created for use in this workflow.")
    var functionArn: String
    try {
        // Does this function already exist.
        val functionRequest = GetFunctionRequest {
            functionName = myFunctionName
        }
        LambdaClient { region = "us-west-2" }.use { lambdaClient ->
            val response = lambdaClient.getFunction(functionRequest)
            functionArn = response.configuration?.functionArn.toString()
            println("$functionArn exists")
        }
    } catch (e: LambdaException) {
        println(e.message + " A new function will be created")
        functionArn = createNewFunction(myFunctionName, s3BucketName, myS3Key, myHandler, myRole)
    }
    return functionArn
}

// Checks to see if the SageMaker role exists. If not, this method creates it.
suspend fun checkSageMakerRole(roleNameVal: String): String {
    println("Checking to see if the role exists. If not, a new role will be created for AWS SageMaker to use.")
    var roleArn: String
    try {
        val roleRequest = GetRoleRequest {
            roleName = roleNameVal
        }
        IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
            val response = iamClient.getRole(roleRequest)
            roleArn = response.role?.arn.toString()
            println(roleArn)
        }
    } catch (e: IamException) {
        println(e.message + " A new role will be created")
        roleArn = createSageMakerRole(roleNameVal)
    }
    return roleArn
}

suspend fun createSageMakerRole(roleNameVal: String): String {
    val sageMakerRolePolicies = getSageMakerRolePolicies()
    println("Creating a role to use with SageMaker.")
    val assumeRolePolicy = "{" +
        "\"Version\": \"2012-10-17\"," +
        "\"Statement\": [{" +
        "\"Effect\": \"Allow\"," +
        "\"Principal\": {" +
        "\"Service\": [" +
        "\"sagemaker.amazonaws.com\"," +
        "\"sagemaker-geospatial.amazonaws.com\"," +
        "\"lambda.amazonaws.com\"," +
        "\"s3.amazonaws.com\"" +
        "]" +
        "}," +
        "\"Action\": \"sts:AssumeRole\"" +
        "}]" +
        "}"

    val request = CreateRoleRequest {
        roleName = roleNameVal
        assumeRolePolicyDocument = assumeRolePolicy
        description = "Created using the AWS SDK for Kotlin"
    }
    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val roleResult = iamClient.createRole(request)

        // Attach the policies to the role.
        for (policy in sageMakerRolePolicies) {
            val attachRequest = AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policy
            }
            iamClient.attachRolePolicy(attachRequest)
        }

        // Allow time for the role to be ready.
        TimeUnit.SECONDS.sleep(15)
        System.out.println("Role ready with ARN ${roleResult.role?.arn}")
        return roleResult.role?.arn.toString()
    }
}

// Checks to see if the Lambda role exists. If not, this method creates it.
suspend fun checkLambdaRole(roleNameVal: String): String {
    println("Checking to see if the role exists. If not, a new role will be created for AWS Lambda to use.")
    var roleArn: String
    val roleRequest = GetRoleRequest {
        roleName = roleNameVal
    }

    try {
        IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
            val response = iamClient.getRole(roleRequest)
            roleArn = response.role?.arn.toString()
            println(roleArn)
        }
    } catch (e: IamException) {
        println(e.message + " A new role will be created")
        roleArn = createLambdaRole(roleNameVal)
    }

    return roleArn
}

private suspend fun createLambdaRole(roleNameVal: String): String {
    val lambdaRolePolicies = getLambdaRolePolicies()
    val assumeRolePolicy = "{" +
        "\"Version\": \"2012-10-17\"," +
        "\"Statement\": [{" +
        "\"Effect\": \"Allow\"," +
        "\"Principal\": {" +
        "\"Service\": [" +
        "\"sagemaker.amazonaws.com\"," +
        "\"sagemaker-geospatial.amazonaws.com\"," +
        "\"lambda.amazonaws.com\"," +
        "\"s3.amazonaws.com\"" +
        "]" +
        "}," +
        "\"Action\": \"sts:AssumeRole\"" +
        "}]" +
        "}"

    val request = CreateRoleRequest {
        roleName = roleNameVal
        assumeRolePolicyDocument = assumeRolePolicy
        description = "Created using the AWS SDK for Kotlin"
    }

    IamClient { region = "AWS_GLOBAL" }.use { iamClient ->
        val roleResult = iamClient.createRole(request)

        // Attach the policies to the role.
        for (policy in lambdaRolePolicies) {
            val attachRequest = AttachRolePolicyRequest {
                roleName = roleNameVal
                policyArn = policy
            }
            iamClient.attachRolePolicy(attachRequest)
        }

        // Allow time for the role to be ready.
        TimeUnit.SECONDS.sleep(15)
        println("Role ready with ARN " + roleResult.role?.arn)
        return roleResult.role?.arn.toString()
    }
}

fun getLambdaRolePolicies(): Array<String?> {
    val lambdaRolePolicies = arrayOfNulls<String>(5)
    lambdaRolePolicies[0] = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"
    lambdaRolePolicies[1] = "arn:aws:iam::aws:policy/AmazonSQSFullAccess"
    lambdaRolePolicies[2] = "arn:aws:iam::aws:policy/service-role/" + "AmazonSageMakerGeospatialFullAccess"
    lambdaRolePolicies[3] = "arn:aws:iam::aws:policy/service-role/" + "AmazonSageMakerServiceCatalogProductsLambdaServiceRolePolicy"
    lambdaRolePolicies[4] = "arn:aws:iam::aws:policy/service-role/" + "AWSLambdaSQSQueueExecutionRole"
    return lambdaRolePolicies
}

fun getSageMakerRolePolicies(): Array<String?> {
    val sageMakerRolePolicies = arrayOfNulls<String>(3)
    sageMakerRolePolicies[0] = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"
    sageMakerRolePolicies[1] = "arn:aws:iam::aws:policy/service-role/" + "AmazonSageMakerGeospatialFullAccess"
    sageMakerRolePolicies[2] = "arn:aws:iam::aws:policy/AmazonSQSFullAccess"
    return sageMakerRolePolicies
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CreatePipeline](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeletePipeline](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribePipelineExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartPipelineExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [UpdatePipeline](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

# SDK for Kotlin を使用した Secrets Manager の例
<a name="kotlin_1_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_kotlin_1_topic"></a>

次のコード例は、`GetSecretValue` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/secrets-manager#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getValue(secretName: String?) {
    val valueRequest =
        GetSecretValueRequest {
            secretId = secretName
        }

    SecretsManagerClient.fromEnvironment { region = "us-east-1" }.use { secretsClient ->
        val response = secretsClient.getSecretValue(valueRequest)
        val secret = response.secretString
        println("The secret value is $secret")
    }
}
```
+  API の詳細については、**「AWS SDK for Kotlin API リファレンス」の「[GetSecretValue](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon SES の例
<a name="kotlin_1_ses_code_examples"></a>

次のコード例は、Amazon SES で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon DynamoDB API を使用して、DynamoDB 作業データを追跡する動的ウェブアプリケーションを作成する方法を示しています。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/itemtracker_dynamodb) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### Amazon Redshift データ追跡用のウェブアプリケーションの作成
<a name="cross_RedshiftDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon Redshift データベースを使用して、作業項目を追跡してレポートするウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon Redshift データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Redshift サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_redshift_application) にある詳しい事例を参照してください。  

**この例で使用されているサービス**
+ Amazon Redshift
+ Amazon SES

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_kotlin_1_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon RDS データベースに保存されている作業項目を追跡してレポートするウェブアプリケーションを作成する方法を説明します。  
 Amazon Aurora サーバーレスデータをクエリする Spring REST API と React アプリケーションで使用するための完全なソースコードと設定方法については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/serverless_rds) にある完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_kotlin_1_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Kotlin**  
 Amazon Simple Storage Service (Amazon S3) バケットにある画像内からカテゴリ別にオブジェクトを Amazon Rekognition を使用して識別するアプリケーションを、Amazon Rekognition Kotlin API を使用して作成する方法を示します。アプリケーションは、Amazon Simple Email Service (Amazon SES) を使用して、結果を記載した E メール通知を管理者に送信します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_photo_analyzer_app) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

# SDK for Kotlin を使用した Amazon SNS の例
<a name="kotlin_1_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon SNS
<a name="sns_Hello_kotlin_1_topic"></a>

次のコード例は、Amazon SNS の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.ListTopicsRequest
import aws.sdk.kotlin.services.sns.paginators.listTopicsPaginated
import kotlinx.coroutines.flow.transform

/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */
suspend fun main() {
    listTopicsPag()
}

suspend fun listTopicsPag() {
    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient
            .listTopicsPaginated(ListTopicsRequest { })
            .transform { it.topics?.forEach { topic -> emit(topic) } }
            .collect { topic ->
                println("The topic ARN is ${topic.topicArn}")
            }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListTopics](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_kotlin_1_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createSNSTopic(topicName: String): String {
    val request =
        CreateTopicRequest {
            name = topicName
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.createTopic(request)
        return result.topicArn.toString()
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_kotlin_1_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteSNSTopic(topicArnVal: String) {
    val request =
        DeleteTopicRequest {
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.deleteTopic(request)
        println("$topicArnVal was successfully deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_kotlin_1_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getSNSTopicAttributes(topicArnVal: String) {
    val request =
        GetTopicAttributesRequest {
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.getTopicAttributes(request)
        println("${result.attributes}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[GetTopicAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_kotlin_1_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listSNSSubscriptions() {
    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val response = snsClient.listSubscriptions(ListSubscriptionsRequest {})
        response.subscriptions?.forEach { sub ->
            println("Sub ARN is ${sub.subscriptionArn}")
            println("Sub protocol is ${sub.protocol}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListSubscriptions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_kotlin_1_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listSNSTopics() {
    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val response = snsClient.listTopics(ListTopicsRequest { })
        response.topics?.forEach { topic ->
            println("The topic ARN is ${topic.topicArn}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListTopics](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Publish`
<a name="sns_Publish_kotlin_1_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun pubTopic(
    topicArnVal: String,
    messageVal: String,
) {
    val request =
        PublishRequest {
            message = messageVal
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[Publish](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SetTopicAttributes`
<a name="sns_SetTopicAttributes_kotlin_1_topic"></a>

次のコード例は、`SetTopicAttributes` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun setTopAttr(
    attribute: String?,
    topicArnVal: String?,
    value: String?,
) {
    val request =
        SetTopicAttributesRequest {
            attributeName = attribute
            attributeValue = value
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.setTopicAttributes(request)
        println("Topic ${request.topicArn} was updated.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[SetTopicAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_kotlin_1_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
suspend fun subEmail(
    topicArnVal: String,
    email: String,
): String {
    val request =
        SubscribeRequest {
            protocol = "email"
            endpoint = email
            returnSubscriptionArn = true
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.subscribe(request)
        return result.subscriptionArn.toString()
    }
}
```
Lambda 関数をトピックにサブスクライブします。  

```
suspend fun subLambda(
    topicArnVal: String?,
    lambdaArn: String?,
) {
    val request =
        SubscribeRequest {
            protocol = "lambda"
            endpoint = lambdaArn
            returnSubscriptionArn = true
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.subscribe(request)
        println(" The subscription Arn is ${result.subscriptionArn}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[Subscribe](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `TagResource`
<a name="sns_TagResource_kotlin_1_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun addTopicTags(topicArn: String) {
    val tag =
        Tag {
            key = "Team"
            value = "Development"
        }

    val tag2 =
        Tag {
            key = "Environment"
            value = "Gamma"
        }

    val tagList = mutableListOf<Tag>()
    tagList.add(tag)
    tagList.add(tag2)

    val request =
        TagResourceRequest {
            resourceArn = topicArn
            tags = tagList
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.tagResource(request)
        println("Tags have been added to $topicArn")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[TagResource](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `Unsubscribe`
<a name="sns_Unsubscribe_kotlin_1_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun unSub(subscriptionArnVal: String) {
    val request =
        UnsubscribeRequest {
            subscriptionArn = subscriptionArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.unsubscribe(request)
        println("Subscription was removed for ${request.subscriptionArn}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[Unsubscribe](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon SNS アプリケーションの構築
<a name="cross_SnsPublishSubscription_kotlin_1_topic"></a>

次のコード例は、サブスクリプションとパブリッシュ機能を持ち、メッセージを翻訳するアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon SNS Kotlin API を使用して、サブスクリプションおよび発行機能を持つアプリケーションを作成する方法を示しています。さらに、このサンプルアプリケーションではメッセージを翻訳します。  
 詳細なソースコードとウェブアプリケーションを作成する手順については、「[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/subpub_app)」の詳しい例を参照してください。  
 詳細なソースコードと Android ネイティブアプリケーションを作成する手順については、「[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/subpub_app_android)」の詳しい例を参照してください。  

**この例で使用されているサービス**
+ Amazon SNS
+ Amazon Translate

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_kotlin_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Kotlin**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_pam) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### SMS テキストメッセージを発行する
<a name="sns_PublishTextSMS_kotlin_1_topic"></a>

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun pubTextSMS(
    messageVal: String?,
    phoneNumberVal: String?,
) {
    val request =
        PublishRequest {
            message = messageVal
            phoneNumber = phoneNumberVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[Publish](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
package com.example.sns

import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.CreateTopicRequest
import aws.sdk.kotlin.services.sns.model.DeleteTopicRequest
import aws.sdk.kotlin.services.sns.model.PublishRequest
import aws.sdk.kotlin.services.sns.model.SetSubscriptionAttributesRequest
import aws.sdk.kotlin.services.sns.model.SubscribeRequest
import aws.sdk.kotlin.services.sns.model.UnsubscribeRequest
import aws.sdk.kotlin.services.sqs.SqsClient
import aws.sdk.kotlin.services.sqs.model.CreateQueueRequest
import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequest
import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequestEntry
import aws.sdk.kotlin.services.sqs.model.DeleteQueueRequest
import aws.sdk.kotlin.services.sqs.model.GetQueueAttributesRequest
import aws.sdk.kotlin.services.sqs.model.GetQueueUrlRequest
import aws.sdk.kotlin.services.sqs.model.Message
import aws.sdk.kotlin.services.sqs.model.QueueAttributeName
import aws.sdk.kotlin.services.sqs.model.ReceiveMessageRequest
import aws.sdk.kotlin.services.sqs.model.SetQueueAttributesRequest
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import java.util.Scanner

/**
Before running this Kotlin code example, set up your development environment,
including your AWS credentials.

For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html

This Kotlin example performs the following tasks:

 1. Gives the user three options to choose from.
 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic.
 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue.
 4. Gets the SQS queue Amazon Resource Name (ARN) attribute.
 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue.
 6. Subscribes to the SQS queue.
 7. Publishes a message to the topic.
 8. Displays the messages.
 9. Deletes the received message.
 10. Unsubscribes from the topic.
 11. Deletes the SNS topic.
 */

val DASHES: String = String(CharArray(80)).replace("\u0000", "-")
suspend fun main() {
    val input = Scanner(System.`in`)
    val useFIFO: String
    var duplication = "n"
    var topicName: String
    var deduplicationID: String? = null
    var groupId: String? = null
    val topicArn: String?
    var sqsQueueName: String
    val sqsQueueUrl: String?
    val sqsQueueArn: String
    val subscriptionArn: String?
    var selectFIFO = false
    val message: String
    val messageList: List<Message?>?
    val filterList = ArrayList<String>()
    var msgAttValue = ""

    println(DASHES)
    println("Welcome to the AWS SDK for Kotlin messaging with topics and queues.")
    println(
        """
                In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic.
                You can select from several options for configuring the topic and the subscriptions for the queue.
                You can then post to the topic and see the results in the queue.
        """.trimIndent(),
    )
    println(DASHES)

    println(DASHES)
    println(
        """
                SNS topics can be configured as FIFO (First-In-First-Out).
                FIFO topics deliver messages in order and support deduplication and message filtering.
                Would you like to work with FIFO topics? (y/n)
        """.trimIndent(),
    )
    useFIFO = input.nextLine()
    if (useFIFO.compareTo("y") == 0) {
        selectFIFO = true
        println("You have selected FIFO")
        println(
            """ Because you have chosen a FIFO topic, deduplication is supported.
        Deduplication IDs are either set in the message or automatically generated from content using a hash function.
        If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID,
        within the five-minute deduplication interval, is accepted but not delivered.
        For more information about deduplication, see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.""",
        )

        println("Would you like to use content-based deduplication instead of entering a deduplication ID? (y/n)")
        duplication = input.nextLine()
        if (duplication.compareTo("y") == 0) {
            println("Enter a group id value")
            groupId = input.nextLine()
        } else {
            println("Enter deduplication Id value")
            deduplicationID = input.nextLine()
            println("Enter a group id value")
            groupId = input.nextLine()
        }
    }
    println(DASHES)

    println(DASHES)
    println("2. Create a topic.")
    println("Enter a name for your SNS topic.")
    topicName = input.nextLine()
    if (selectFIFO) {
        println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.")
        topicName = "$topicName.fifo"
        println("The name of the topic is $topicName")
        topicArn = createFIFO(topicName, duplication)
        println("The ARN of the FIFO topic is $topicArn")
    } else {
        println("The name of the topic is $topicName")
        topicArn = createSNSTopic(topicName)
        println("The ARN of the non-FIFO topic is $topicArn")
    }
    println(DASHES)

    println(DASHES)
    println("3. Create an SQS queue.")
    println("Enter a name for your SQS queue.")
    sqsQueueName = input.nextLine()
    if (selectFIFO) {
        sqsQueueName = "$sqsQueueName.fifo"
    }
    sqsQueueUrl = createQueue(sqsQueueName, selectFIFO)
    println("The queue URL is $sqsQueueUrl")
    println(DASHES)

    println(DASHES)
    println("4. Get the SQS queue ARN attribute.")
    sqsQueueArn = getSQSQueueAttrs(sqsQueueUrl)
    println("The ARN of the new queue is $sqsQueueArn")
    println(DASHES)

    println(DASHES)
    println("5. Attach an IAM policy to the queue.")
    // Define the policy to use.
    val policy = """{
     "Statement": [
     {
         "Effect": "Allow",
                 "Principal": {
             "Service": "sns.amazonaws.com"
         },
         "Action": "sqs:SendMessage",
                 "Resource": "$sqsQueueArn",
                 "Condition": {
             "ArnEquals": {
                 "aws:SourceArn": "$topicArn"
             }
         }
     }
     ]
     }"""
    setQueueAttr(sqsQueueUrl, policy)
    println(DASHES)

    println(DASHES)
    println("6. Subscribe to the SQS queue.")
    if (selectFIFO) {
        println(
            """If you add a filter to this subscription, then only the filtered messages will be received in the queue.
For information about message filtering, see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html
For this example, you can filter messages by a "tone" attribute.""",
        )
        println("Would you like to filter messages for $sqsQueueName's subscription to the topic $topicName?  (y/n)")
        val filterAns: String = input.nextLine()
        if (filterAns.compareTo("y") == 0) {
            var moreAns = false
            println("You can filter messages by using one or more of the following \"tone\" attributes.")
            println("1. cheerful")
            println("2. funny")
            println("3. serious")
            println("4. sincere")
            while (!moreAns) {
                println("Select a number or choose 0 to end.")
                val ans: String = input.nextLine()
                when (ans) {
                    "1" -> filterList.add("cheerful")
                    "2" -> filterList.add("funny")
                    "3" -> filterList.add("serious")
                    "4" -> filterList.add("sincere")
                    else -> moreAns = true
                }
            }
        }
    }
    subscriptionArn = subQueue(topicArn, sqsQueueArn, filterList)
    println(DASHES)

    println(DASHES)
    println("7. Publish a message to the topic.")
    if (selectFIFO) {
        println("Would you like to add an attribute to this message?  (y/n)")
        val msgAns: String = input.nextLine()
        if (msgAns.compareTo("y") == 0) {
            println("You can filter messages by one or more of the following \"tone\" attributes.")
            println("1. cheerful")
            println("2. funny")
            println("3. serious")
            println("4. sincere")
            println("Select a number or choose 0 to end.")
            val ans: String = input.nextLine()
            msgAttValue = when (ans) {
                "1" -> "cheerful"
                "2" -> "funny"
                "3" -> "serious"
                else -> "sincere"
            }
            println("Selected value is $msgAttValue")
        }
        println("Enter a message.")
        message = input.nextLine()
        pubMessageFIFO(message, topicArn, msgAttValue, duplication, groupId, deduplicationID)
    } else {
        println("Enter a message.")
        message = input.nextLine()
        pubMessage(message, topicArn)
    }
    println(DASHES)

    println(DASHES)
    println("8. Display the message. Press any key to continue.")
    input.nextLine()
    messageList = receiveMessages(sqsQueueUrl, msgAttValue)
    if (messageList != null) {
        for (mes in messageList) {
            println("Message Id: ${mes.messageId}")
            println("Full Message: ${mes.body}")
        }
    }
    println(DASHES)

    println(DASHES)
    println("9. Delete the received message. Press any key to continue.")
    input.nextLine()
    if (messageList != null) {
        deleteMessages(sqsQueueUrl, messageList)
    }
    println(DASHES)

    println(DASHES)
    println("10. Unsubscribe from the topic and delete the queue. Press any key to continue.")
    input.nextLine()
    unSub(subscriptionArn)
    deleteSQSQueue(sqsQueueName)
    println(DASHES)

    println(DASHES)
    println("11. Delete the topic. Press any key to continue.")
    input.nextLine()
    deleteSNSTopic(topicArn)
    println(DASHES)

    println(DASHES)
    println("The SNS/SQS workflow has completed successfully.")
    println(DASHES)
}

suspend fun deleteSNSTopic(topicArnVal: String?) {
    val request = DeleteTopicRequest {
        topicArn = topicArnVal
    }

    SnsClient { region = "us-east-1" }.use { snsClient ->
        snsClient.deleteTopic(request)
        println("$topicArnVal was deleted")
    }
}

suspend fun deleteSQSQueue(queueNameVal: String) {
    val getQueueRequest = GetQueueUrlRequest {
        queueName = queueNameVal
    }

    SqsClient { region = "us-east-1" }.use { sqsClient ->
        val queueUrlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl
        val deleteQueueRequest = DeleteQueueRequest {
            queueUrl = queueUrlVal
        }

        sqsClient.deleteQueue(deleteQueueRequest)
        println("$queueNameVal was successfully deleted.")
    }
}

suspend fun unSub(subscripArn: String?) {
    val request = UnsubscribeRequest {
        subscriptionArn = subscripArn
    }
    SnsClient { region = "us-east-1" }.use { snsClient ->
        snsClient.unsubscribe(request)
        println("Subscription was removed for $subscripArn")
    }
}

suspend fun deleteMessages(queueUrlVal: String?, messages: List<Message>) {
    val entriesVal: MutableList<DeleteMessageBatchRequestEntry> = mutableListOf()
    for (msg in messages) {
        val entry = DeleteMessageBatchRequestEntry {
            id = msg.messageId
        }
        entriesVal.add(entry)
    }

    val deleteMessageBatchRequest = DeleteMessageBatchRequest {
        queueUrl = queueUrlVal
        entries = entriesVal
    }

    SqsClient { region = "us-east-1" }.use { sqsClient ->
        sqsClient.deleteMessageBatch(deleteMessageBatchRequest)
        println("The batch delete of messages was successful")
    }
}

suspend fun receiveMessages(queueUrlVal: String?, msgAttValue: String): List<Message>? {
    if (msgAttValue.isEmpty()) {
        val request = ReceiveMessageRequest {
            queueUrl = queueUrlVal
            maxNumberOfMessages = 5
        }
        SqsClient { region = "us-east-1" }.use { sqsClient ->
            return sqsClient.receiveMessage(request).messages
        }
    } else {
        val receiveRequest = ReceiveMessageRequest {
            queueUrl = queueUrlVal
            waitTimeSeconds = 1
            maxNumberOfMessages = 5
        }
        SqsClient { region = "us-east-1" }.use { sqsClient ->
            return sqsClient.receiveMessage(receiveRequest).messages
        }
    }
}

suspend fun pubMessage(messageVal: String?, topicArnVal: String?) {
    val request = PublishRequest {
        message = messageVal
        topicArn = topicArnVal
    }

    SnsClient { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}

suspend fun pubMessageFIFO(
    messageVal: String?,
    topicArnVal: String?,
    msgAttValue: String,
    duplication: String,
    groupIdVal: String?,
    deduplicationID: String?,
) {
    // Means the user did not choose to use a message attribute.
    if (msgAttValue.isEmpty()) {
        if (duplication.compareTo("y") == 0) {
            val request = PublishRequest {
                message = messageVal
                messageGroupId = groupIdVal
                topicArn = topicArnVal
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        } else {
            val request = PublishRequest {
                message = messageVal
                messageDeduplicationId = deduplicationID
                messageGroupId = groupIdVal
                topicArn = topicArnVal
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        }
    } else {
        val messAttr = aws.sdk.kotlin.services.sns.model.MessageAttributeValue {
            dataType = "String"
            stringValue = "true"
        }

        val mapAtt: Map<String, aws.sdk.kotlin.services.sns.model.MessageAttributeValue> =
            mapOf(msgAttValue to messAttr)
        if (duplication.compareTo("y") == 0) {
            val request = PublishRequest {
                message = messageVal
                messageGroupId = groupIdVal
                topicArn = topicArnVal
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        } else {
            // Create a publish request with the message and attributes.
            val request = PublishRequest {
                topicArn = topicArnVal
                message = messageVal
                messageDeduplicationId = deduplicationID
                messageGroupId = groupIdVal
                messageAttributes = mapAtt
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        }
    }
}

// Subscribe to the SQS queue.
suspend fun subQueue(topicArnVal: String?, queueArnVal: String, filterList: List<String?>): String? {
    val request: SubscribeRequest
    if (filterList.isEmpty()) {
        // No filter subscription is added.
        request = SubscribeRequest {
            protocol = "sqs"
            endpoint = queueArnVal
            returnSubscriptionArn = true
            topicArn = topicArnVal
        }

        SnsClient { region = "us-east-1" }.use { snsClient ->
            val result = snsClient.subscribe(request)
            println(
                "The queue " + queueArnVal + " has been subscribed to the topic " + topicArnVal + "\n" +
                    "with the subscription ARN " + result.subscriptionArn,
            )
            return result.subscriptionArn
        }
    } else {
        request = SubscribeRequest {
            protocol = "sqs"
            endpoint = queueArnVal
            returnSubscriptionArn = true
            topicArn = topicArnVal
        }

        SnsClient { region = "us-east-1" }.use { snsClient ->
            val result = snsClient.subscribe(request)
            println("The queue $queueArnVal has been subscribed to the topic $topicArnVal with the subscription ARN ${result.subscriptionArn}")

            val attributeNameVal = "FilterPolicy"
            val gson = Gson()
            val jsonString = "{\"tone\": []}"
            val jsonObject = gson.fromJson(jsonString, JsonObject::class.java)
            val toneArray = jsonObject.getAsJsonArray("tone")
            for (value: String? in filterList) {
                toneArray.add(JsonPrimitive(value))
            }

            val updatedJsonString: String = gson.toJson(jsonObject)
            println(updatedJsonString)
            val attRequest = SetSubscriptionAttributesRequest {
                subscriptionArn = result.subscriptionArn
                attributeName = attributeNameVal
                attributeValue = updatedJsonString
            }

            snsClient.setSubscriptionAttributes(attRequest)
            return result.subscriptionArn
        }
    }
}

suspend fun setQueueAttr(queueUrlVal: String?, policy: String) {
    val attrMap: MutableMap<String, String> = HashMap()
    attrMap[QueueAttributeName.Policy.toString()] = policy

    val attributesRequest = SetQueueAttributesRequest {
        queueUrl = queueUrlVal
        attributes = attrMap
    }

    SqsClient { region = "us-east-1" }.use { sqsClient ->
        sqsClient.setQueueAttributes(attributesRequest)
        println("The policy has been successfully attached.")
    }
}

suspend fun getSQSQueueAttrs(queueUrlVal: String?): String {
    val atts: MutableList<QueueAttributeName> = ArrayList()
    atts.add(QueueAttributeName.QueueArn)

    val attributesRequest = GetQueueAttributesRequest {
        queueUrl = queueUrlVal
        attributeNames = atts
    }
    SqsClient { region = "us-east-1" }.use { sqsClient ->
        val response = sqsClient.getQueueAttributes(attributesRequest)
        val mapAtts = response.attributes
        if (mapAtts != null) {
            mapAtts.forEach { entry ->
                println("${entry.key} : ${entry.value}")
                return entry.value
            }
        }
    }
    return ""
}

suspend fun createQueue(queueNameVal: String?, selectFIFO: Boolean): String? {
    println("\nCreate Queue")
    if (selectFIFO) {
        val attrs = mutableMapOf<String, String>()
        attrs[QueueAttributeName.FifoQueue.toString()] = "true"

        val createQueueRequest = CreateQueueRequest {
            queueName = queueNameVal
            attributes = attrs
        }

        SqsClient { region = "us-east-1" }.use { sqsClient ->
            sqsClient.createQueue(createQueueRequest)
            println("\nGet queue url")

            val urlRequest = GetQueueUrlRequest {
                queueName = queueNameVal
            }

            val getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest)
            return getQueueUrlResponse.queueUrl
        }
    } else {
        val createQueueRequest = CreateQueueRequest {
            queueName = queueNameVal
        }

        SqsClient { region = "us-east-1" }.use { sqsClient ->
            sqsClient.createQueue(createQueueRequest)
            println("Get queue url")

            val urlRequest = GetQueueUrlRequest {
                queueName = queueNameVal
            }

            val getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest)
            return getQueueUrlResponse.queueUrl
        }
    }
}

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

suspend fun createFIFO(topicName: String?, duplication: String): String? {
    val topicAttributes: MutableMap<String, String> = HashMap()
    if (duplication.compareTo("n") == 0) {
        topicAttributes["FifoTopic"] = "true"
        topicAttributes["ContentBasedDeduplication"] = "false"
    } else {
        topicAttributes["FifoTopic"] = "true"
        topicAttributes["ContentBasedDeduplication"] = "true"
    }

    val topicRequest = CreateTopicRequest {
        name = topicName
        attributes = topicAttributes
    }
    SnsClient { region = "us-east-1" }.use { snsClient ->
        val response = snsClient.createTopic(topicRequest)
        return response.topicArn
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [CreateQueue](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteMessageBatch](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteQueue](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetQueueAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Publish](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ReceiveMessage](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [SetQueueAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Subscribe](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Unsubscribe](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

# SDK for Kotlin を使用した Amazon SQS の例
<a name="kotlin_1_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon SQS
<a name="sqs_Hello_kotlin_1_topic"></a>

次のコード例は、Amazon SQS の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
package com.kotlin.sqs

import aws.sdk.kotlin.services.sqs.SqsClient
import aws.sdk.kotlin.services.sqs.paginators.listQueuesPaginated
import kotlinx.coroutines.flow.transform

suspend fun main() {
    listTopicsPag()
}

suspend fun listTopicsPag() {
    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient
            .listQueuesPaginated { }
            .transform { it.queueUrls?.forEach { queue -> emit(queue) } }
            .collect { queue ->
                println("The Queue URL is $queue")
            }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListQueues](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateQueue`
<a name="sqs_CreateQueue_kotlin_1_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createQueue(queueNameVal: String): String {
    println("Create Queue")
    val createQueueRequest =
        CreateQueueRequest {
            queueName = queueNameVal
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient.createQueue(createQueueRequest)
        println("Get queue url")

        val getQueueUrlRequest =
            GetQueueUrlRequest {
                queueName = queueNameVal
            }

        val getQueueUrlResponse = sqsClient.getQueueUrl(getQueueUrlRequest)
        return getQueueUrlResponse.queueUrl.toString()
    }
}
```
+  API の詳細については、[AWS SDK for Kotlin API リファレンス](https://sdk.amazonaws.com/kotlin/api/latest/index.html)の「*CreateQueue*」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_kotlin_1_topic"></a>

次のコード例は、`DeleteMessage` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteMessages(queueUrlVal: String) {
    println("Delete Messages from $queueUrlVal")

    val purgeRequest =
        PurgeQueueRequest {
            queueUrl = queueUrlVal
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient.purgeQueue(purgeRequest)
        println("Messages are successfully deleted from $queueUrlVal")
    }
}

suspend fun deleteQueue(queueUrlVal: String) {
    val request =
        DeleteQueueRequest {
            queueUrl = queueUrlVal
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient.deleteQueue(request)
        println("$queueUrlVal was deleted!")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteMessage](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_kotlin_1_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteMessages(queueUrlVal: String) {
    println("Delete Messages from $queueUrlVal")

    val purgeRequest =
        PurgeQueueRequest {
            queueUrl = queueUrlVal
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient.purgeQueue(purgeRequest)
        println("Messages are successfully deleted from $queueUrlVal")
    }
}

suspend fun deleteQueue(queueUrlVal: String) {
    val request =
        DeleteQueueRequest {
            queueUrl = queueUrlVal
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient.deleteQueue(request)
        println("$queueUrlVal was deleted!")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteQueue](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_kotlin_1_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listQueues() {
    println("\nList Queues")

    val prefix = "que"
    val listQueuesRequest =
        ListQueuesRequest {
            queueNamePrefix = prefix
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        val response = sqsClient.listQueues(listQueuesRequest)
        response.queueUrls?.forEach { url ->
            println(url)
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListQueues](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_kotlin_1_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
suspend fun receiveMessages(queueUrlVal: String?) {
    println("Retrieving messages from $queueUrlVal")

    val receiveMessageRequest =
        ReceiveMessageRequest {
            queueUrl = queueUrlVal
            maxNumberOfMessages = 5
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        val response = sqsClient.receiveMessage(receiveMessageRequest)
        response.messages?.forEach { message ->
            println(message.body)
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ReceiveMessage](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_kotlin_1_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
suspend fun sendMessages(
    queueUrlVal: String,
    message: String,
) {
    println("Sending multiple messages")
    println("\nSend message")
    val sendRequest =
        SendMessageRequest {
            queueUrl = queueUrlVal
            messageBody = message
            delaySeconds = 10
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient.sendMessage(sendRequest)
        println("A single message was successfully sent.")
    }
}

suspend fun sendBatchMessages(queueUrlVal: String?) {
    println("Sending multiple messages")

    val msg1 =
        SendMessageBatchRequestEntry {
            id = "id1"
            messageBody = "Hello from msg 1"
        }

    val msg2 =
        SendMessageBatchRequestEntry {
            id = "id2"
            messageBody = "Hello from msg 2"
        }

    val sendMessageBatchRequest =
        SendMessageBatchRequest {
            queueUrl = queueUrlVal
            entries = listOf(msg1, msg2)
        }

    SqsClient.fromEnvironment { region = "us-east-1" }.use { sqsClient ->
        sqsClient.sendMessageBatch(sendMessageBatchRequest)
        println("Batch message were successfully sent.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[SendMessage](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセージングアプリケーションを作成する
<a name="cross_SQSMessageApp_kotlin_1_topic"></a>

次のコード例は、Amazon SQS を使用してメッセージングアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon SQS API を使用して、メッセージを送受信する Spring REST API を開発する方法を示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/creating_message_application) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon SQS

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
package com.example.sns

import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.CreateTopicRequest
import aws.sdk.kotlin.services.sns.model.DeleteTopicRequest
import aws.sdk.kotlin.services.sns.model.PublishRequest
import aws.sdk.kotlin.services.sns.model.SetSubscriptionAttributesRequest
import aws.sdk.kotlin.services.sns.model.SubscribeRequest
import aws.sdk.kotlin.services.sns.model.UnsubscribeRequest
import aws.sdk.kotlin.services.sqs.SqsClient
import aws.sdk.kotlin.services.sqs.model.CreateQueueRequest
import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequest
import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequestEntry
import aws.sdk.kotlin.services.sqs.model.DeleteQueueRequest
import aws.sdk.kotlin.services.sqs.model.GetQueueAttributesRequest
import aws.sdk.kotlin.services.sqs.model.GetQueueUrlRequest
import aws.sdk.kotlin.services.sqs.model.Message
import aws.sdk.kotlin.services.sqs.model.QueueAttributeName
import aws.sdk.kotlin.services.sqs.model.ReceiveMessageRequest
import aws.sdk.kotlin.services.sqs.model.SetQueueAttributesRequest
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonPrimitive
import java.util.Scanner

/**
Before running this Kotlin code example, set up your development environment,
including your AWS credentials.

For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html

This Kotlin example performs the following tasks:

 1. Gives the user three options to choose from.
 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic.
 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue.
 4. Gets the SQS queue Amazon Resource Name (ARN) attribute.
 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue.
 6. Subscribes to the SQS queue.
 7. Publishes a message to the topic.
 8. Displays the messages.
 9. Deletes the received message.
 10. Unsubscribes from the topic.
 11. Deletes the SNS topic.
 */

val DASHES: String = String(CharArray(80)).replace("\u0000", "-")
suspend fun main() {
    val input = Scanner(System.`in`)
    val useFIFO: String
    var duplication = "n"
    var topicName: String
    var deduplicationID: String? = null
    var groupId: String? = null
    val topicArn: String?
    var sqsQueueName: String
    val sqsQueueUrl: String?
    val sqsQueueArn: String
    val subscriptionArn: String?
    var selectFIFO = false
    val message: String
    val messageList: List<Message?>?
    val filterList = ArrayList<String>()
    var msgAttValue = ""

    println(DASHES)
    println("Welcome to the AWS SDK for Kotlin messaging with topics and queues.")
    println(
        """
                In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic.
                You can select from several options for configuring the topic and the subscriptions for the queue.
                You can then post to the topic and see the results in the queue.
        """.trimIndent(),
    )
    println(DASHES)

    println(DASHES)
    println(
        """
                SNS topics can be configured as FIFO (First-In-First-Out).
                FIFO topics deliver messages in order and support deduplication and message filtering.
                Would you like to work with FIFO topics? (y/n)
        """.trimIndent(),
    )
    useFIFO = input.nextLine()
    if (useFIFO.compareTo("y") == 0) {
        selectFIFO = true
        println("You have selected FIFO")
        println(
            """ Because you have chosen a FIFO topic, deduplication is supported.
        Deduplication IDs are either set in the message or automatically generated from content using a hash function.
        If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID,
        within the five-minute deduplication interval, is accepted but not delivered.
        For more information about deduplication, see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.""",
        )

        println("Would you like to use content-based deduplication instead of entering a deduplication ID? (y/n)")
        duplication = input.nextLine()
        if (duplication.compareTo("y") == 0) {
            println("Enter a group id value")
            groupId = input.nextLine()
        } else {
            println("Enter deduplication Id value")
            deduplicationID = input.nextLine()
            println("Enter a group id value")
            groupId = input.nextLine()
        }
    }
    println(DASHES)

    println(DASHES)
    println("2. Create a topic.")
    println("Enter a name for your SNS topic.")
    topicName = input.nextLine()
    if (selectFIFO) {
        println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.")
        topicName = "$topicName.fifo"
        println("The name of the topic is $topicName")
        topicArn = createFIFO(topicName, duplication)
        println("The ARN of the FIFO topic is $topicArn")
    } else {
        println("The name of the topic is $topicName")
        topicArn = createSNSTopic(topicName)
        println("The ARN of the non-FIFO topic is $topicArn")
    }
    println(DASHES)

    println(DASHES)
    println("3. Create an SQS queue.")
    println("Enter a name for your SQS queue.")
    sqsQueueName = input.nextLine()
    if (selectFIFO) {
        sqsQueueName = "$sqsQueueName.fifo"
    }
    sqsQueueUrl = createQueue(sqsQueueName, selectFIFO)
    println("The queue URL is $sqsQueueUrl")
    println(DASHES)

    println(DASHES)
    println("4. Get the SQS queue ARN attribute.")
    sqsQueueArn = getSQSQueueAttrs(sqsQueueUrl)
    println("The ARN of the new queue is $sqsQueueArn")
    println(DASHES)

    println(DASHES)
    println("5. Attach an IAM policy to the queue.")
    // Define the policy to use.
    val policy = """{
     "Statement": [
     {
         "Effect": "Allow",
                 "Principal": {
             "Service": "sns.amazonaws.com"
         },
         "Action": "sqs:SendMessage",
                 "Resource": "$sqsQueueArn",
                 "Condition": {
             "ArnEquals": {
                 "aws:SourceArn": "$topicArn"
             }
         }
     }
     ]
     }"""
    setQueueAttr(sqsQueueUrl, policy)
    println(DASHES)

    println(DASHES)
    println("6. Subscribe to the SQS queue.")
    if (selectFIFO) {
        println(
            """If you add a filter to this subscription, then only the filtered messages will be received in the queue.
For information about message filtering, see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html
For this example, you can filter messages by a "tone" attribute.""",
        )
        println("Would you like to filter messages for $sqsQueueName's subscription to the topic $topicName?  (y/n)")
        val filterAns: String = input.nextLine()
        if (filterAns.compareTo("y") == 0) {
            var moreAns = false
            println("You can filter messages by using one or more of the following \"tone\" attributes.")
            println("1. cheerful")
            println("2. funny")
            println("3. serious")
            println("4. sincere")
            while (!moreAns) {
                println("Select a number or choose 0 to end.")
                val ans: String = input.nextLine()
                when (ans) {
                    "1" -> filterList.add("cheerful")
                    "2" -> filterList.add("funny")
                    "3" -> filterList.add("serious")
                    "4" -> filterList.add("sincere")
                    else -> moreAns = true
                }
            }
        }
    }
    subscriptionArn = subQueue(topicArn, sqsQueueArn, filterList)
    println(DASHES)

    println(DASHES)
    println("7. Publish a message to the topic.")
    if (selectFIFO) {
        println("Would you like to add an attribute to this message?  (y/n)")
        val msgAns: String = input.nextLine()
        if (msgAns.compareTo("y") == 0) {
            println("You can filter messages by one or more of the following \"tone\" attributes.")
            println("1. cheerful")
            println("2. funny")
            println("3. serious")
            println("4. sincere")
            println("Select a number or choose 0 to end.")
            val ans: String = input.nextLine()
            msgAttValue = when (ans) {
                "1" -> "cheerful"
                "2" -> "funny"
                "3" -> "serious"
                else -> "sincere"
            }
            println("Selected value is $msgAttValue")
        }
        println("Enter a message.")
        message = input.nextLine()
        pubMessageFIFO(message, topicArn, msgAttValue, duplication, groupId, deduplicationID)
    } else {
        println("Enter a message.")
        message = input.nextLine()
        pubMessage(message, topicArn)
    }
    println(DASHES)

    println(DASHES)
    println("8. Display the message. Press any key to continue.")
    input.nextLine()
    messageList = receiveMessages(sqsQueueUrl, msgAttValue)
    if (messageList != null) {
        for (mes in messageList) {
            println("Message Id: ${mes.messageId}")
            println("Full Message: ${mes.body}")
        }
    }
    println(DASHES)

    println(DASHES)
    println("9. Delete the received message. Press any key to continue.")
    input.nextLine()
    if (messageList != null) {
        deleteMessages(sqsQueueUrl, messageList)
    }
    println(DASHES)

    println(DASHES)
    println("10. Unsubscribe from the topic and delete the queue. Press any key to continue.")
    input.nextLine()
    unSub(subscriptionArn)
    deleteSQSQueue(sqsQueueName)
    println(DASHES)

    println(DASHES)
    println("11. Delete the topic. Press any key to continue.")
    input.nextLine()
    deleteSNSTopic(topicArn)
    println(DASHES)

    println(DASHES)
    println("The SNS/SQS workflow has completed successfully.")
    println(DASHES)
}

suspend fun deleteSNSTopic(topicArnVal: String?) {
    val request = DeleteTopicRequest {
        topicArn = topicArnVal
    }

    SnsClient { region = "us-east-1" }.use { snsClient ->
        snsClient.deleteTopic(request)
        println("$topicArnVal was deleted")
    }
}

suspend fun deleteSQSQueue(queueNameVal: String) {
    val getQueueRequest = GetQueueUrlRequest {
        queueName = queueNameVal
    }

    SqsClient { region = "us-east-1" }.use { sqsClient ->
        val queueUrlVal = sqsClient.getQueueUrl(getQueueRequest).queueUrl
        val deleteQueueRequest = DeleteQueueRequest {
            queueUrl = queueUrlVal
        }

        sqsClient.deleteQueue(deleteQueueRequest)
        println("$queueNameVal was successfully deleted.")
    }
}

suspend fun unSub(subscripArn: String?) {
    val request = UnsubscribeRequest {
        subscriptionArn = subscripArn
    }
    SnsClient { region = "us-east-1" }.use { snsClient ->
        snsClient.unsubscribe(request)
        println("Subscription was removed for $subscripArn")
    }
}

suspend fun deleteMessages(queueUrlVal: String?, messages: List<Message>) {
    val entriesVal: MutableList<DeleteMessageBatchRequestEntry> = mutableListOf()
    for (msg in messages) {
        val entry = DeleteMessageBatchRequestEntry {
            id = msg.messageId
        }
        entriesVal.add(entry)
    }

    val deleteMessageBatchRequest = DeleteMessageBatchRequest {
        queueUrl = queueUrlVal
        entries = entriesVal
    }

    SqsClient { region = "us-east-1" }.use { sqsClient ->
        sqsClient.deleteMessageBatch(deleteMessageBatchRequest)
        println("The batch delete of messages was successful")
    }
}

suspend fun receiveMessages(queueUrlVal: String?, msgAttValue: String): List<Message>? {
    if (msgAttValue.isEmpty()) {
        val request = ReceiveMessageRequest {
            queueUrl = queueUrlVal
            maxNumberOfMessages = 5
        }
        SqsClient { region = "us-east-1" }.use { sqsClient ->
            return sqsClient.receiveMessage(request).messages
        }
    } else {
        val receiveRequest = ReceiveMessageRequest {
            queueUrl = queueUrlVal
            waitTimeSeconds = 1
            maxNumberOfMessages = 5
        }
        SqsClient { region = "us-east-1" }.use { sqsClient ->
            return sqsClient.receiveMessage(receiveRequest).messages
        }
    }
}

suspend fun pubMessage(messageVal: String?, topicArnVal: String?) {
    val request = PublishRequest {
        message = messageVal
        topicArn = topicArnVal
    }

    SnsClient { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}

suspend fun pubMessageFIFO(
    messageVal: String?,
    topicArnVal: String?,
    msgAttValue: String,
    duplication: String,
    groupIdVal: String?,
    deduplicationID: String?,
) {
    // Means the user did not choose to use a message attribute.
    if (msgAttValue.isEmpty()) {
        if (duplication.compareTo("y") == 0) {
            val request = PublishRequest {
                message = messageVal
                messageGroupId = groupIdVal
                topicArn = topicArnVal
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        } else {
            val request = PublishRequest {
                message = messageVal
                messageDeduplicationId = deduplicationID
                messageGroupId = groupIdVal
                topicArn = topicArnVal
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        }
    } else {
        val messAttr = aws.sdk.kotlin.services.sns.model.MessageAttributeValue {
            dataType = "String"
            stringValue = "true"
        }

        val mapAtt: Map<String, aws.sdk.kotlin.services.sns.model.MessageAttributeValue> =
            mapOf(msgAttValue to messAttr)
        if (duplication.compareTo("y") == 0) {
            val request = PublishRequest {
                message = messageVal
                messageGroupId = groupIdVal
                topicArn = topicArnVal
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        } else {
            // Create a publish request with the message and attributes.
            val request = PublishRequest {
                topicArn = topicArnVal
                message = messageVal
                messageDeduplicationId = deduplicationID
                messageGroupId = groupIdVal
                messageAttributes = mapAtt
            }

            SnsClient { region = "us-east-1" }.use { snsClient ->
                val result = snsClient.publish(request)
                println(result.messageId.toString() + " Message sent.")
            }
        }
    }
}

// Subscribe to the SQS queue.
suspend fun subQueue(topicArnVal: String?, queueArnVal: String, filterList: List<String?>): String? {
    val request: SubscribeRequest
    if (filterList.isEmpty()) {
        // No filter subscription is added.
        request = SubscribeRequest {
            protocol = "sqs"
            endpoint = queueArnVal
            returnSubscriptionArn = true
            topicArn = topicArnVal
        }

        SnsClient { region = "us-east-1" }.use { snsClient ->
            val result = snsClient.subscribe(request)
            println(
                "The queue " + queueArnVal + " has been subscribed to the topic " + topicArnVal + "\n" +
                    "with the subscription ARN " + result.subscriptionArn,
            )
            return result.subscriptionArn
        }
    } else {
        request = SubscribeRequest {
            protocol = "sqs"
            endpoint = queueArnVal
            returnSubscriptionArn = true
            topicArn = topicArnVal
        }

        SnsClient { region = "us-east-1" }.use { snsClient ->
            val result = snsClient.subscribe(request)
            println("The queue $queueArnVal has been subscribed to the topic $topicArnVal with the subscription ARN ${result.subscriptionArn}")

            val attributeNameVal = "FilterPolicy"
            val gson = Gson()
            val jsonString = "{\"tone\": []}"
            val jsonObject = gson.fromJson(jsonString, JsonObject::class.java)
            val toneArray = jsonObject.getAsJsonArray("tone")
            for (value: String? in filterList) {
                toneArray.add(JsonPrimitive(value))
            }

            val updatedJsonString: String = gson.toJson(jsonObject)
            println(updatedJsonString)
            val attRequest = SetSubscriptionAttributesRequest {
                subscriptionArn = result.subscriptionArn
                attributeName = attributeNameVal
                attributeValue = updatedJsonString
            }

            snsClient.setSubscriptionAttributes(attRequest)
            return result.subscriptionArn
        }
    }
}

suspend fun setQueueAttr(queueUrlVal: String?, policy: String) {
    val attrMap: MutableMap<String, String> = HashMap()
    attrMap[QueueAttributeName.Policy.toString()] = policy

    val attributesRequest = SetQueueAttributesRequest {
        queueUrl = queueUrlVal
        attributes = attrMap
    }

    SqsClient { region = "us-east-1" }.use { sqsClient ->
        sqsClient.setQueueAttributes(attributesRequest)
        println("The policy has been successfully attached.")
    }
}

suspend fun getSQSQueueAttrs(queueUrlVal: String?): String {
    val atts: MutableList<QueueAttributeName> = ArrayList()
    atts.add(QueueAttributeName.QueueArn)

    val attributesRequest = GetQueueAttributesRequest {
        queueUrl = queueUrlVal
        attributeNames = atts
    }
    SqsClient { region = "us-east-1" }.use { sqsClient ->
        val response = sqsClient.getQueueAttributes(attributesRequest)
        val mapAtts = response.attributes
        if (mapAtts != null) {
            mapAtts.forEach { entry ->
                println("${entry.key} : ${entry.value}")
                return entry.value
            }
        }
    }
    return ""
}

suspend fun createQueue(queueNameVal: String?, selectFIFO: Boolean): String? {
    println("\nCreate Queue")
    if (selectFIFO) {
        val attrs = mutableMapOf<String, String>()
        attrs[QueueAttributeName.FifoQueue.toString()] = "true"

        val createQueueRequest = CreateQueueRequest {
            queueName = queueNameVal
            attributes = attrs
        }

        SqsClient { region = "us-east-1" }.use { sqsClient ->
            sqsClient.createQueue(createQueueRequest)
            println("\nGet queue url")

            val urlRequest = GetQueueUrlRequest {
                queueName = queueNameVal
            }

            val getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest)
            return getQueueUrlResponse.queueUrl
        }
    } else {
        val createQueueRequest = CreateQueueRequest {
            queueName = queueNameVal
        }

        SqsClient { region = "us-east-1" }.use { sqsClient ->
            sqsClient.createQueue(createQueueRequest)
            println("Get queue url")

            val urlRequest = GetQueueUrlRequest {
                queueName = queueNameVal
            }

            val getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest)
            return getQueueUrlResponse.queueUrl
        }
    }
}

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

suspend fun createFIFO(topicName: String?, duplication: String): String? {
    val topicAttributes: MutableMap<String, String> = HashMap()
    if (duplication.compareTo("n") == 0) {
        topicAttributes["FifoTopic"] = "true"
        topicAttributes["ContentBasedDeduplication"] = "false"
    } else {
        topicAttributes["FifoTopic"] = "true"
        topicAttributes["ContentBasedDeduplication"] = "true"
    }

    val topicRequest = CreateTopicRequest {
        name = topicName
        attributes = topicAttributes
    }
    SnsClient { region = "us-east-1" }.use { snsClient ->
        val response = snsClient.createTopic(topicRequest)
        return response.topicArn
    }
}
```
+ API の詳細については、『*AWS SDK for Kotlin API リファレンス*』の以下のトピックを参照してください。
  + [CreateQueue](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteMessageBatch](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteQueue](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetQueueAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Publish](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ReceiveMessage](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [SetQueueAttributes](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Subscribe](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [Unsubscribe](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

# SDK for Kotlin を使用した Step Function の例
<a name="kotlin_1_sfn_code_examples"></a>

次のコード例は、Step Functions で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Step Functions
<a name="sfn_Hello_kotlin_1_topic"></a>

次のコード例は、Step Functions の使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.sfn.SfnClient
import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest

/**
 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */

suspend fun main() {
    println(DASHES)
    println("Welcome to the AWS Step Functions Hello example.")
    println("Lets list up to ten of your state machines:")
    println(DASHES)

    listMachines()
}

suspend fun listMachines() {
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.listStateMachines(ListStateMachinesRequest {})
        response.stateMachines?.forEach { machine ->
            println("The name of the state machine is ${machine.name}")
            println("The ARN value is ${machine.stateMachineArn}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListStateMachines](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="sfn_Scenario_GetStartedStateMachines_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ アクティビティを作成します。
+ 以前に作成したアクティビティをステップとして含む Amazon States Language 定義からステートマシンを作成します。
+ ステートマシンを実行し、ユーザー入力でアクティビティに応答します。
+ 実行が完了したら最終ステータスと出力を取得して、リソースをクリーンアップします。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.iam.IamClient
import aws.sdk.kotlin.services.iam.model.CreateRoleRequest
import aws.sdk.kotlin.services.sfn.SfnClient
import aws.sdk.kotlin.services.sfn.model.CreateActivityRequest
import aws.sdk.kotlin.services.sfn.model.CreateStateMachineRequest
import aws.sdk.kotlin.services.sfn.model.DeleteActivityRequest
import aws.sdk.kotlin.services.sfn.model.DeleteStateMachineRequest
import aws.sdk.kotlin.services.sfn.model.DescribeExecutionRequest
import aws.sdk.kotlin.services.sfn.model.DescribeStateMachineRequest
import aws.sdk.kotlin.services.sfn.model.GetActivityTaskRequest
import aws.sdk.kotlin.services.sfn.model.ListActivitiesRequest
import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest
import aws.sdk.kotlin.services.sfn.model.SendTaskSuccessRequest
import aws.sdk.kotlin.services.sfn.model.StartExecutionRequest
import aws.sdk.kotlin.services.sfn.model.StateMachineType
import aws.sdk.kotlin.services.sfn.paginators.listActivitiesPaginated
import aws.sdk.kotlin.services.sfn.paginators.listStateMachinesPaginated
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.node.ObjectNode
import kotlinx.coroutines.flow.transform
import java.util.Scanner
import java.util.UUID
import kotlin.collections.ArrayList
import kotlin.system.exitProcess

/**
 To run this code example, place the chat_sfn_state_machine.json file into your project's resources folder.

 You can obtain the JSON file to create a state machine in the following GitHub location:

 https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/sample_files

 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

 This Kotlin code example performs the following tasks:

 1. List activities using a paginator.
 2. List state machines using a paginator.
 3. Creates an activity.
 4. Creates a state machine.
 5. Describes the state machine.
 6. Starts execution of the state machine and interacts with it.
 7. Describes the execution.
 8. Deletes the activity.
 9. Deletes the state machine.
 */

val DASHES: String = String(CharArray(80)).replace("\u0000", "-")

suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <roleARN> <activityName> <stateMachineName>

    Where:
        roleName - The name of the IAM role to create for this state machine.
        activityName - The name of an activity to create.    
        stateMachineName - The name of the state machine to create.
        jsonFile - The location of the chat_sfn_state_machine.json file. You can located it in resources/sample_files. 
    """

    if (args.size != 4) {
        println(usage)
        exitProcess(0)
    }

    val roleName = args[0]
    val activityName = args[1]
    val stateMachineName = args[2]
    val jsonFile = args[3]
    val sc = Scanner(System.`in`)
    var action = false

    val polJSON = """{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "states.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
    }"""

    println(DASHES)
    println("Welcome to the AWS Step Functions example scenario.")
    println(DASHES)

    println(DASHES)
    println("1. List activities using a Paginator.")
    listActivitesPagnator()
    println(DASHES)

    println(DASHES)
    println("2. List state machines using a paginator.")
    listStatemachinesPagnator()
    println(DASHES)

    println(DASHES)
    println("3. Create a new activity.")
    val activityArn = createActivity(activityName)
    println("The ARN of the Activity is $activityArn")
    println(DASHES)

    // Get JSON to use for the state machine and place the activityArn value into it.
    val stream = GetStream()
    val jsonString = stream.getStream(jsonFile)

    // Modify the Resource node.
    val objectMapper = ObjectMapper()
    val root: JsonNode = objectMapper.readTree(jsonString)
    (root.path("States").path("GetInput") as ObjectNode).put("Resource", activityArn)

    // Convert the modified Java object back to a JSON string.
    val stateDefinition = objectMapper.writeValueAsString(root)
    println(stateDefinition)

    println(DASHES)
    println("4. Create a state machine.")
    val roleARN = createIAMRole(roleName, polJSON)
    val stateMachineArn = createMachine(roleARN, stateMachineName, stateDefinition)
    println("The ARN of the state machine is $stateMachineArn")
    println(DASHES)

    println(DASHES)
    println("5. Describe the state machine.")
    describeStateMachine(stateMachineArn)
    println("What should ChatSFN call you?")
    val userName = sc.nextLine()
    println("Hello $userName")
    println(DASHES)

    println(DASHES)
    // The JSON to pass to the StartExecution call.
    val executionJson = "{ \"name\" : \"$userName\" }"
    println(executionJson)
    println("6. Start execution of the state machine and interact with it.")
    val runArn = startWorkflow(stateMachineArn, executionJson)
    println("The ARN of the state machine execution is $runArn")
    var myList: List<String>
    while (!action) {
        myList = getActivityTask(activityArn)
        println("ChatSFN: " + myList[1])
        println("$userName please specify a value.")
        val myAction = sc.nextLine()
        if (myAction.compareTo("done") == 0) {
            action = true
        }
        println("You have selected $myAction")
        val taskJson = "{ \"action\" : \"$myAction\" }"
        println(taskJson)
        sendTaskSuccess(myList[0], taskJson)
    }
    println(DASHES)

    println(DASHES)
    println("7. Describe the execution.")
    describeExe(runArn)
    println(DASHES)

    println(DASHES)
    println("8. Delete the activity.")
    deleteActivity(activityArn)
    println(DASHES)

    println(DASHES)
    println("9. Delete the state machines.")
    deleteMachine(stateMachineArn)
    println(DASHES)

    println(DASHES)
    println("The AWS Step Functions example scenario is complete.")
    println(DASHES)
}

suspend fun listStatemachinesPagnator() {
    val machineRequest =
        ListStateMachinesRequest {
            maxResults = 10
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient
            .listStateMachinesPaginated(machineRequest)
            .transform { it.stateMachines?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println(" The state machine ARN is ${obj.stateMachineArn}")
            }
    }
}

suspend fun listActivitesPagnator() {
    val activitiesRequest =
        ListActivitiesRequest {
            maxResults = 10
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient
            .listActivitiesPaginated(activitiesRequest)
            .transform { it.activities?.forEach { obj -> emit(obj) } }
            .collect { obj ->
                println(" The activity ARN is ${obj.activityArn}")
            }
    }
}

suspend fun deleteMachine(stateMachineArnVal: String?) {
    val deleteStateMachineRequest =
        DeleteStateMachineRequest {
            stateMachineArn = stateMachineArnVal
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient.deleteStateMachine(deleteStateMachineRequest)
        println("$stateMachineArnVal was successfully deleted.")
    }
}

suspend fun deleteActivity(actArn: String?) {
    val activityRequest =
        DeleteActivityRequest {
            activityArn = actArn
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient.deleteActivity(activityRequest)
        println("You have deleted $actArn")
    }
}

suspend fun describeExe(executionArnVal: String?) {
    val executionRequest =
        DescribeExecutionRequest {
            executionArn = executionArnVal
        }

    var status = ""
    var hasSucceeded = false
    while (!hasSucceeded) {
        SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
            val response = sfnClient.describeExecution(executionRequest)
            status = response.status.toString()
            if (status.compareTo("Running") == 0) {
                println("The state machine is still running, let's wait for it to finish.")
                Thread.sleep(2000)
            } else if (status.compareTo("Succeeded") == 0) {
                println("The Step Function workflow has succeeded")
                hasSucceeded = true
            } else {
                println("The Status is $status")
            }
        }
    }
    println("The Status is $status")
}

suspend fun sendTaskSuccess(
    token: String?,
    json: String?,
) {
    val successRequest =
        SendTaskSuccessRequest {
            taskToken = token
            output = json
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient.sendTaskSuccess(successRequest)
    }
}

suspend fun getActivityTask(actArn: String?): List<String> {
    val myList: MutableList<String> = ArrayList()
    val getActivityTaskRequest =
        GetActivityTaskRequest {
            activityArn = actArn
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.getActivityTask(getActivityTaskRequest)
        myList.add(response.taskToken.toString())
        myList.add(response.input.toString())
        return myList
    }
}

suspend fun startWorkflow(
    stateMachineArnVal: String?,
    jsonEx: String?,
): String? {
    val uuid = UUID.randomUUID()
    val uuidValue = uuid.toString()
    val executionRequest =
        StartExecutionRequest {
            input = jsonEx
            stateMachineArn = stateMachineArnVal
            name = uuidValue
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.startExecution(executionRequest)
        return response.executionArn
    }
}

suspend fun describeStateMachine(stateMachineArnVal: String?) {
    val stateMachineRequest =
        DescribeStateMachineRequest {
            stateMachineArn = stateMachineArnVal
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.describeStateMachine(stateMachineRequest)
        println("The name of the State machine is ${response.name}")
        println("The status of the State machine is ${response.status}")
        println("The ARN value of the State machine is ${response.stateMachineArn}")
        println("The role ARN value is ${response.roleArn}")
    }
}

suspend fun createMachine(
    roleARNVal: String?,
    stateMachineName: String?,
    jsonVal: String?,
): String? {
    val machineRequest =
        CreateStateMachineRequest {
            definition = jsonVal
            name = stateMachineName
            roleArn = roleARNVal
            type = StateMachineType.Standard
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.createStateMachine(machineRequest)
        return response.stateMachineArn
    }
}

suspend fun createIAMRole(
    roleNameVal: String?,
    polJSON: String?,
): String? {
    val request =
        CreateRoleRequest {
            roleName = roleNameVal
            assumeRolePolicyDocument = polJSON
            description = "Created using the AWS SDK for Kotlin"
        }

    IamClient.fromEnvironment { region = "AWS_GLOBAL" }.use { iamClient ->
        val response = iamClient.createRole(request)
        return response.role?.arn
    }
}

suspend fun createActivity(activityName: String): String? {
    val activityRequest =
        CreateActivityRequest {
            name = activityName
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.createActivity(activityRequest)
        return response.activityArn
    }
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [CreateActivity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateStateMachine](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteActivity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DeleteStateMachine](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeStateMachine](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [GetActivityTask](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListActivities](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ListStateMachines](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [SendTaskSuccess](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StartExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [StopExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateActivity`
<a name="sfn_CreateActivity_kotlin_1_topic"></a>

次のコード例は、`CreateActivity` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createActivity(activityName: String): String? {
    val activityRequest =
        CreateActivityRequest {
            name = activityName
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.createActivity(activityRequest)
        return response.activityArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateActivity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateStateMachine`
<a name="sfn_CreateStateMachine_kotlin_1_topic"></a>

次のコード例は、`CreateStateMachine` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createMachine(
    roleARNVal: String?,
    stateMachineName: String?,
    jsonVal: String?,
): String? {
    val machineRequest =
        CreateStateMachineRequest {
            definition = jsonVal
            name = stateMachineName
            roleArn = roleARNVal
            type = StateMachineType.Standard
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.createStateMachine(machineRequest)
        return response.stateMachineArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[CreateStateMachine](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteActivity`
<a name="sfn_DeleteActivity_kotlin_1_topic"></a>

次のコード例は、`DeleteActivity` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteActivity(actArn: String?) {
    val activityRequest =
        DeleteActivityRequest {
            activityArn = actArn
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient.deleteActivity(activityRequest)
        println("You have deleted $actArn")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteActivity](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DeleteStateMachine`
<a name="sfn_DeleteStateMachine_kotlin_1_topic"></a>

次のコード例は、`DeleteStateMachine` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun deleteMachine(stateMachineArnVal: String?) {
    val deleteStateMachineRequest =
        DeleteStateMachineRequest {
            stateMachineArn = stateMachineArnVal
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient.deleteStateMachine(deleteStateMachineRequest)
        println("$stateMachineArnVal was successfully deleted.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DeleteStateMachine](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeExecution`
<a name="sfn_DescribeExecution_kotlin_1_topic"></a>

次のコード例は、`DescribeExecution` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeExe(executionArnVal: String?) {
    val executionRequest =
        DescribeExecutionRequest {
            executionArn = executionArnVal
        }

    var status = ""
    var hasSucceeded = false
    while (!hasSucceeded) {
        SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
            val response = sfnClient.describeExecution(executionRequest)
            status = response.status.toString()
            if (status.compareTo("Running") == 0) {
                println("The state machine is still running, let's wait for it to finish.")
                Thread.sleep(2000)
            } else if (status.compareTo("Succeeded") == 0) {
                println("The Step Function workflow has succeeded")
                hasSucceeded = true
            } else {
                println("The Status is $status")
            }
        }
    }
    println("The Status is $status")
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeStateMachine`
<a name="sfn_DescribeStateMachine_kotlin_1_topic"></a>

次のコード例は、`DescribeStateMachine` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeStateMachine(stateMachineArnVal: String?) {
    val stateMachineRequest =
        DescribeStateMachineRequest {
            stateMachineArn = stateMachineArnVal
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.describeStateMachine(stateMachineRequest)
        println("The name of the State machine is ${response.name}")
        println("The status of the State machine is ${response.status}")
        println("The ARN value of the State machine is ${response.stateMachineArn}")
        println("The role ARN value is ${response.roleArn}")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[DescribeStateMachine](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `GetActivityTask`
<a name="sfn_GetActivityTask_kotlin_1_topic"></a>

次のコード例は、`GetActivityTask` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getActivityTask(actArn: String?): List<String> {
    val myList: MutableList<String> = ArrayList()
    val getActivityTaskRequest =
        GetActivityTaskRequest {
            activityArn = actArn
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.getActivityTask(getActivityTaskRequest)
        myList.add(response.taskToken.toString())
        myList.add(response.input.toString())
        return myList
    }
}
```
+  API の詳細については、*AWS  SDK for Kotlin API リファレンス*の「[GetActivityTask](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListActivities`
<a name="sfn_ListActivities_kotlin_1_topic"></a>

次のコード例は、`ListActivities` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listAllActivites() {
    val activitiesRequest =
        ListActivitiesRequest {
            maxResults = 10
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.listActivities(activitiesRequest)
        response.activities?.forEach { item ->
            println("The activity ARN is ${item.activityArn}")
            println("The activity name is ${item.name}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListActivities](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListExecutions`
<a name="sfn_ListExecutions_kotlin_1_topic"></a>

次のコード例は、`ListExecutions` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getExeHistory(exeARN: String?) {
    val historyRequest =
        GetExecutionHistoryRequest {
            executionArn = exeARN
            maxResults = 10
        }

    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.getExecutionHistory(historyRequest)
        response.events?.forEach { event ->
            println("The event type is ${event.type}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListExecutions](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ListStateMachines`
<a name="sfn_ListStateMachines_kotlin_1_topic"></a>

次のコード例は、`ListStateMachines` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
import aws.sdk.kotlin.services.sfn.SfnClient
import aws.sdk.kotlin.services.sfn.model.ListStateMachinesRequest

/**
 Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
 */

suspend fun main() {
    println(DASHES)
    println("Welcome to the AWS Step Functions Hello example.")
    println("Lets list up to ten of your state machines:")
    println(DASHES)

    listMachines()
}

suspend fun listMachines() {
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.listStateMachines(ListStateMachinesRequest {})
        response.stateMachines?.forEach { machine ->
            println("The name of the state machine is ${machine.name}")
            println("The ARN value is ${machine.stateMachineArn}")
        }
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[ListStateMachines](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `SendTaskSuccess`
<a name="sfn_SendTaskSuccess_kotlin_1_topic"></a>

次のコード例は、`SendTaskSuccess` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun sendTaskSuccess(
    token: String?,
    json: String?,
) {
    val successRequest =
        SendTaskSuccessRequest {
            taskToken = token
            output = json
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        sfnClient.sendTaskSuccess(successRequest)
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[SendTaskSuccess](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `StartExecution`
<a name="sfn_StartExecution_kotlin_1_topic"></a>

次のコード例は、`StartExecution` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
suspend fun startWorkflow(
    stateMachineArnVal: String?,
    jsonEx: String?,
): String? {
    val uuid = UUID.randomUUID()
    val uuidValue = uuid.toString()
    val executionRequest =
        StartExecutionRequest {
            input = jsonEx
            stateMachineArn = stateMachineArnVal
            name = uuidValue
        }
    SfnClient.fromEnvironment { region = "us-east-1" }.use { sfnClient ->
        val response = sfnClient.startExecution(executionRequest)
        return response.executionArn
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[StartExecution](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# サポート SDK for Kotlin を使用した の例
<a name="kotlin_1_support_code_examples"></a>

次のコード例は、 で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち サポートは
<a name="support_Hello_kotlin_1_topic"></a>

次のコード例は、 サポートの使用を開始する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html

In addition, you must have the AWS Business Support Plan to use the AWS Support Java API. For more information, see:

https://aws.amazon.com/premiumsupport/plans/

This Kotlin example performs the following task:

1. Gets and displays available services.
 */

suspend fun main() {
    displaySomeServices()
}

// Return a List that contains a Service name and Category name.
suspend fun displaySomeServices() {
    val servicesRequest =
        DescribeServicesRequest {
            language = "en"
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeServices(servicesRequest)
        println("Get the first 10 services")
        var index = 1

        response.services?.forEach { service ->
            if (index == 11) {
                return@forEach
            }

            println("The Service name is: " + service.name)

            // Get the categories for this service.
            service.categories?.forEach { cat ->
                println("The category name is ${cat.name}")
                index++
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeServices](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="support_Scenario_GetStartedSupportCases_kotlin_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ケースの利用可能なサービスと重要度レベルを取得して表示します。
+ 選択したサービス、カテゴリ、重要度レベルを使用してサポートケースを作成する方法
+ 当日のオープンケースのリストを取得して表示する方法
+ 新しいケースに添付セットとコミュニケーションを追加する方法
+ ケースの新しい添付ファイルとコミュニケーションについて説明する方法
+ ケースを解決する方法
+ 当日の解決済みケースのリストを取得して表示します。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
/**
Before running this Kotlin 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-kotlin/latest/developer-guide/setup.html
In addition, you must have the AWS Business Support Plan to use the AWS Support Java API. For more information, see:

https://aws.amazon.com/premiumsupport/plans/

This Kotlin example performs the following tasks:
1. Gets and displays available services.
2. Gets and displays severity levels.
3. Creates a support case by using the selected service, category, and severity level.
4. Gets a list of open cases for the current day.
5. Creates an attachment set with a generated file.
6. Adds a communication with the attachment to the support case.
7. Lists the communications of the support case.
8. Describes the attachment set included with the communication.
9. Resolves the support case.
10. Gets a list of resolved cases for the current day.
*/

suspend fun main(args: Array<String>) {
    val usage = """
    Usage:
        <fileAttachment> 
    Where:
         fileAttachment - The file can be a simple saved .txt file to use as an email attachment.
    """

    if (args.size != 1) {
        println(usage)
        exitProcess(0)
    }

    val fileAttachment = args[0]
    println("***** Welcome to the AWS Support case example scenario.")
    println("***** Step 1. Get and display available services.")
    val sevCatList = displayServices()

    println("***** Step 2. Get and display Support severity levels.")
    val sevLevel = displaySevLevels()

    println("***** Step 3. Create a support case using the selected service, category, and severity level.")
    val caseIdVal = createSupportCase(sevCatList, sevLevel)
    if (caseIdVal != null) {
        println("Support case $caseIdVal was successfully created!")
    } else {
        println("A support case was not successfully created!")
        exitProcess(1)
    }

    println("***** Step 4. Get open support cases.")
    getOpenCase()

    println("***** Step 5. Create an attachment set with a generated file to add to the case.")
    val attachmentSetId = addAttachment(fileAttachment)
    println("The Attachment Set id value is $attachmentSetId")

    println("***** Step 6. Add communication with the attachment to the support case.")
    addAttachSupportCase(caseIdVal, attachmentSetId)

    println("***** Step 7. List the communications of the support case.")
    val attachId = listCommunications(caseIdVal)
    println("The Attachment id value is $attachId")

    println("***** Step 8. Describe the attachment set included with the communication.")
    describeAttachment(attachId)

    println("***** Step 9. Resolve the support case.")
    resolveSupportCase(caseIdVal)

    println("***** Step 10. Get a list of resolved cases for the current day.")
    getResolvedCase()
    println("***** This Scenario has successfully completed")
}

suspend fun getResolvedCase() {
    // Specify the start and end time.
    val now = Instant.now()
    LocalDate.now()
    val yesterday = now.minus(1, ChronoUnit.DAYS)
    val describeCasesRequest =
        DescribeCasesRequest {
            maxResults = 30
            afterTime = yesterday.toString()
            beforeTime = now.toString()
            includeResolvedCases = true
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeCases(describeCasesRequest)
        response.cases?.forEach { sinCase ->
            println("The case status is ${sinCase.status}")
            println("The case Id is ${sinCase.caseId}")
            println("The case subject is ${sinCase.subject}")
        }
    }
}

suspend fun resolveSupportCase(caseIdVal: String) {
    val caseRequest =
        ResolveCaseRequest {
            caseId = caseIdVal
        }
    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.resolveCase(caseRequest)
        println("The status of case $caseIdVal is ${response.finalCaseStatus}")
    }
}

suspend fun describeAttachment(attachId: String?) {
    val attachmentRequest =
        DescribeAttachmentRequest {
            attachmentId = attachId
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeAttachment(attachmentRequest)
        println("The name of the file is ${response.attachment?.fileName}")
    }
}

suspend fun listCommunications(caseIdVal: String?): String? {
    val communicationsRequest =
        DescribeCommunicationsRequest {
            caseId = caseIdVal
            maxResults = 10
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeCommunications(communicationsRequest)
        response.communications?.forEach { comm ->
            println("the body is: " + comm.body)
            comm.attachmentSet?.forEach { detail ->
                return detail.attachmentId
            }
        }
    }
    return ""
}

suspend fun addAttachSupportCase(
    caseIdVal: String?,
    attachmentSetIdVal: String?,
) {
    val caseRequest =
        AddCommunicationToCaseRequest {
            caseId = caseIdVal
            attachmentSetId = attachmentSetIdVal
            communicationBody = "Please refer to attachment for details."
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.addCommunicationToCase(caseRequest)
        if (response.result) {
            println("You have successfully added a communication to an AWS Support case")
        } else {
            println("There was an error adding the communication to an AWS Support case")
        }
    }
}

suspend fun addAttachment(fileAttachment: String): String? {
    val myFile = File(fileAttachment)
    val sourceBytes = (File(fileAttachment).readBytes())
    val attachmentVal =
        Attachment {
            fileName = myFile.name
            data = sourceBytes
        }

    val setRequest =
        AddAttachmentsToSetRequest {
            attachments = listOf(attachmentVal)
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.addAttachmentsToSet(setRequest)
        return response.attachmentSetId
    }
}

suspend fun getOpenCase() {
    // Specify the start and end time.
    val now = Instant.now()
    LocalDate.now()
    val yesterday = now.minus(1, ChronoUnit.DAYS)
    val describeCasesRequest =
        DescribeCasesRequest {
            maxResults = 20
            afterTime = yesterday.toString()
            beforeTime = now.toString()
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeCases(describeCasesRequest)
        response.cases?.forEach { sinCase ->
            println("The case status is ${sinCase.status}")
            println("The case Id is ${sinCase.caseId}")
            println("The case subject is ${sinCase.subject}")
        }
    }
}

suspend fun createSupportCase(
    sevCatListVal: List<String>,
    sevLevelVal: String,
): String? {
    val serCode = sevCatListVal[0]
    val caseCategory = sevCatListVal[1]
    val caseRequest =
        CreateCaseRequest {
            categoryCode = caseCategory.lowercase(Locale.getDefault())
            serviceCode = serCode.lowercase(Locale.getDefault())
            severityCode = sevLevelVal.lowercase(Locale.getDefault())
            communicationBody = "Test issue with ${serCode.lowercase(Locale.getDefault())}"
            subject = "Test case, please ignore"
            language = "en"
            issueType = "technical"
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.createCase(caseRequest)
        return response.caseId
    }
}

suspend fun displaySevLevels(): String {
    var levelName = ""
    val severityLevelsRequest =
        DescribeSeverityLevelsRequest {
            language = "en"
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeSeverityLevels(severityLevelsRequest)
        response.severityLevels?.forEach { sevLevel ->
            println("The severity level name is: ${sevLevel.name}")
            if (sevLevel.name == "High") {
                levelName = sevLevel.name!!
            }
        }
        return levelName
    }
}

// Return a List that contains a Service name and Category name.
suspend fun displayServices(): List<String> {
    var serviceCode = ""
    var catName = ""
    val sevCatList = mutableListOf<String>()
    val servicesRequest =
        DescribeServicesRequest {
            language = "en"
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeServices(servicesRequest)
        println("Get the first 10 services")
        var index = 1

        response.services?.forEach { service ->
            if (index == 11) {
                return@forEach
            }

            println("The Service name is ${service.name}")
            if (service.name == "Account") {
                serviceCode = service.code.toString()
            }

            // Get the categories for this service.
            service.categories?.forEach { cat ->
                println("The category name is ${cat.name}")
                if (cat.name == "Security") {
                    catName = cat.name!!
                }
            }
            index++
        }
    }

    // Push the two values to the list.
    serviceCode.let { sevCatList.add(it) }
    catName.let { sevCatList.add(it) }
    return sevCatList
}
```
+ API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の以下のトピックを参照してください。
  + [AddAttachmentsToSet](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [AddCommunicationToCase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [CreateCase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeAttachment](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeCases](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeCommunications](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeServices](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [DescribeSeverityLevels](https://sdk.amazonaws.com/kotlin/api/latest/index.html)
  + [ResolveCase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)

## アクション
<a name="actions"></a>

### `AddAttachmentsToSet`
<a name="support_AddAttachmentsToSet_kotlin_1_topic"></a>

次のコード例は、`AddAttachmentsToSet` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun addAttachment(fileAttachment: String): String? {
    val myFile = File(fileAttachment)
    val sourceBytes = (File(fileAttachment).readBytes())
    val attachmentVal =
        Attachment {
            fileName = myFile.name
            data = sourceBytes
        }

    val setRequest =
        AddAttachmentsToSetRequest {
            attachments = listOf(attachmentVal)
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.addAttachmentsToSet(setRequest)
        return response.attachmentSetId
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[AddAttachmentsToSet](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `AddCommunicationToCase`
<a name="support_AddCommunicationToCase_kotlin_1_topic"></a>

次のコード例は、`AddCommunicationToCase` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun addAttachSupportCase(
    caseIdVal: String?,
    attachmentSetIdVal: String?,
) {
    val caseRequest =
        AddCommunicationToCaseRequest {
            caseId = caseIdVal
            attachmentSetId = attachmentSetIdVal
            communicationBody = "Please refer to attachment for details."
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.addCommunicationToCase(caseRequest)
        if (response.result) {
            println("You have successfully added a communication to an AWS Support case")
        } else {
            println("There was an error adding the communication to an AWS Support case")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[AddCommunicationToCase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `CreateCase`
<a name="support_CreateCase_kotlin_1_topic"></a>

次のコード例は、`CreateCase` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun createSupportCase(
    sevCatListVal: List<String>,
    sevLevelVal: String,
): String? {
    val serCode = sevCatListVal[0]
    val caseCategory = sevCatListVal[1]
    val caseRequest =
        CreateCaseRequest {
            categoryCode = caseCategory.lowercase(Locale.getDefault())
            serviceCode = serCode.lowercase(Locale.getDefault())
            severityCode = sevLevelVal.lowercase(Locale.getDefault())
            communicationBody = "Test issue with ${serCode.lowercase(Locale.getDefault())}"
            subject = "Test case, please ignore"
            language = "en"
            issueType = "technical"
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.createCase(caseRequest)
        return response.caseId
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[CreateCase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeAttachment`
<a name="support_DescribeAttachment_kotlin_1_topic"></a>

次のコード例は、`DescribeAttachment` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun describeAttachment(attachId: String?) {
    val attachmentRequest =
        DescribeAttachmentRequest {
            attachmentId = attachId
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeAttachment(attachmentRequest)
        println("The name of the file is ${response.attachment?.fileName}")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeAttachment](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeCases`
<a name="support_DescribeCases_kotlin_1_topic"></a>

次のコード例は、`DescribeCases` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun getOpenCase() {
    // Specify the start and end time.
    val now = Instant.now()
    LocalDate.now()
    val yesterday = now.minus(1, ChronoUnit.DAYS)
    val describeCasesRequest =
        DescribeCasesRequest {
            maxResults = 20
            afterTime = yesterday.toString()
            beforeTime = now.toString()
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeCases(describeCasesRequest)
        response.cases?.forEach { sinCase ->
            println("The case status is ${sinCase.status}")
            println("The case Id is ${sinCase.caseId}")
            println("The case subject is ${sinCase.subject}")
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeCases](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeCommunications`
<a name="support_DescribeCommunications_kotlin_1_topic"></a>

次のコード例は、`DescribeCommunications` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun listCommunications(caseIdVal: String?): String? {
    val communicationsRequest =
        DescribeCommunicationsRequest {
            caseId = caseIdVal
            maxResults = 10
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeCommunications(communicationsRequest)
        response.communications?.forEach { comm ->
            println("the body is: " + comm.body)
            comm.attachmentSet?.forEach { detail ->
                return detail.attachmentId
            }
        }
    }
    return ""
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeCommunications](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeServices`
<a name="support_DescribeServices_kotlin_1_topic"></a>

次のコード例は、`DescribeServices` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
// Return a List that contains a Service name and Category name.
suspend fun displayServices(): List<String> {
    var serviceCode = ""
    var catName = ""
    val sevCatList = mutableListOf<String>()
    val servicesRequest =
        DescribeServicesRequest {
            language = "en"
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeServices(servicesRequest)
        println("Get the first 10 services")
        var index = 1

        response.services?.forEach { service ->
            if (index == 11) {
                return@forEach
            }

            println("The Service name is ${service.name}")
            if (service.name == "Account") {
                serviceCode = service.code.toString()
            }

            // Get the categories for this service.
            service.categories?.forEach { cat ->
                println("The category name is ${cat.name}")
                if (cat.name == "Security") {
                    catName = cat.name!!
                }
            }
            index++
        }
    }

    // Push the two values to the list.
    serviceCode.let { sevCatList.add(it) }
    catName.let { sevCatList.add(it) }
    return sevCatList
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeServices](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `DescribeSeverityLevels`
<a name="support_DescribeSeverityLevels_kotlin_1_topic"></a>

次のコード例は、`DescribeSeverityLevels` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun displaySevLevels(): String {
    var levelName = ""
    val severityLevelsRequest =
        DescribeSeverityLevelsRequest {
            language = "en"
        }

    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.describeSeverityLevels(severityLevelsRequest)
        response.severityLevels?.forEach { sevLevel ->
            println("The severity level name is: ${sevLevel.name}")
            if (sevLevel.name == "High") {
                levelName = sevLevel.name!!
            }
        }
        return levelName
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[DescribeSeverityLevels](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

### `ResolveCase`
<a name="support_ResolveCase_kotlin_1_topic"></a>

次のコード例は、`ResolveCase` を使用する方法を示しています。

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/support#code-examples)での設定と実行の方法を確認してください。

```
suspend fun resolveSupportCase(caseIdVal: String) {
    val caseRequest =
        ResolveCaseRequest {
            caseId = caseIdVal
        }
    SupportClient.fromEnvironment { region = "us-west-2" }.use { supportClient ->
        val response = supportClient.resolveCase(caseRequest)
        println("The status of case $caseIdVal is ${response.finalCaseStatus}")
    }
}
```
+  API の詳細については、「*AWS SDK for Kotlin API リファレンス*」の「[ResolveCase](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

# SDK for Kotlin を使用した Amazon Translate の例
<a name="kotlin_1_translate_code_examples"></a>

次のコード例は、Amazon Translate で AWS SDK for Kotlin を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon SNS アプリケーションの構築
<a name="cross_SnsPublishSubscription_kotlin_1_topic"></a>

次のコード例は、サブスクリプションとパブリッシュ機能を持ち、メッセージを翻訳するアプリケーションを作成する方法を示しています。

**SDK for Kotlin**  
 Amazon SNS Kotlin API を使用して、サブスクリプションおよび発行機能を持つアプリケーションを作成する方法を示しています。さらに、このサンプルアプリケーションではメッセージを翻訳します。  
 詳細なソースコードとウェブアプリケーションを作成する手順については、「[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/subpub_app)」の詳しい例を参照してください。  
 詳細なソースコードと Android ネイティブアプリケーションを作成する手順については、「[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/usecases/subpub_app_android)」の詳しい例を参照してください。  

**この例で使用されているサービス**
+ Amazon SNS
+ Amazon Translate

# SDK for PHP のコード例
<a name="php_3_code_examples"></a>

次のコード例は、 AWS SDK for PHP で を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for PHP デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/welcome.html) ** – で PHP を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23php)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [API ゲートウェイ](php_3_api-gateway_code_examples.md)
+ [Aurora](php_3_aurora_code_examples.md)
+ [Auto Scaling](php_3_auto-scaling_code_examples.md)
+ [Amazon Bedrock](php_3_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](php_3_bedrock-runtime_code_examples.md)
+ [Amazon DocumentDB](php_3_docdb_code_examples.md)
+ [DynamoDB](php_3_dynamodb_code_examples.md)
+ [Amazon EC2](php_3_ec2_code_examples.md)
+ [AWS Glue](php_3_glue_code_examples.md)
+ [IAM](php_3_iam_code_examples.md)
+ [Kinesis](php_3_kinesis_code_examples.md)
+ [AWS KMS](php_3_kms_code_examples.md)
+ [Lambda](php_3_lambda_code_examples.md)
+ [Amazon MSK](php_3_kafka_code_examples.md)
+ [Amazon RDS](php_3_rds_code_examples.md)
+ [Amazon RDS データサービス](php_3_rds-data_code_examples.md)
+ [Amazon Rekognition](php_3_rekognition_code_examples.md)
+ [Amazon S3](php_3_s3_code_examples.md)
+ [S3 ディレクトリバケット](php_3_s3-directory-buckets_code_examples.md)
+ [Amazon SES](php_3_ses_code_examples.md)
+ [Amazon SNS](php_3_sns_code_examples.md)
+ [Amazon SQS](php_3_sqs_code_examples.md)

# SDK for PHP を使用した API Gateway の例
<a name="php_3_api-gateway_code_examples"></a>

次のコード例は、API Gateway AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `GetBasePathMapping`
<a name="api-gateway_GetBasePathMapping_php_3_topic"></a>

次のコード例は、`GetBasePathMapping` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/apigateway#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\ApiGateway\ApiGatewayClient;
use Aws\Exception\AwsException;


/* ////////////////////////////////////////////////////////////////////////////
 * Purpose: Gets the base path mapping for a custom domain name in
 * Amazon API Gateway.
 *
 * Prerequisites: A custom domain name in API Gateway. For more information,
 * see "Custom Domain Names" in the Amazon API Gateway Developer Guide.
 *
 * Inputs:
 * - $apiGatewayClient: An initialized AWS SDK for PHP API client for
 *   API Gateway.
 * - $basePath: The base path name that callers must provide as part of the
 *   URL after the domain name.
 * - $domainName: The custom domain name for the base path mapping.
 *
 * Returns: The base path mapping, if available; otherwise, the error message.
 * ///////////////////////////////////////////////////////////////////////// */

function getBasePathMapping($apiGatewayClient, $basePath, $domainName)
{
    try {
        $result = $apiGatewayClient->getBasePathMapping([
            'basePath' => $basePath,
            'domainName' => $domainName,
        ]);
        return 'The base path mapping\'s effective URI is: ' .
            $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e['message'];
    }
}

function getsTheBasePathMapping()
{
    $apiGatewayClient = new ApiGatewayClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2015-07-09'
    ]);

    echo getBasePathMapping($apiGatewayClient, '(none)', 'example.com');
}

// Uncomment the following line to run this code in an AWS account.
// getsTheBasePathMapping();
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetBasePathMapping](https://docs.aws.amazon.com/goto/SdkForPHPV3/apigateway-2015-07-09/GetBasePathMapping)」を参照してください。

### `ListBasePathMappings`
<a name="api-gateway_ListBasePathMappings_php_3_topic"></a>

次のコード例は、`ListBasePathMappings` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/apigateway#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\ApiGateway\ApiGatewayClient;
use Aws\Exception\AwsException;


/* ////////////////////////////////////////////////////////////////////////////
 * Purpose: Lists the base path mapping for a custom domain name in
 * Amazon API Gateway.
 *
 * Prerequisites: A custom domain name in API Gateway. For more information,
 * see "Custom Domain Names" in the Amazon API Gateway Developer Guide.
 *
 * Inputs:
 * - $apiGatewayClient: An initialized AWS SDK for PHP API client for
 *   API Gateway.
 * - $domainName: The custom domain name for the base path mappings.
 *
 * Returns: Information about the base path mappings, if available;
 * otherwise, the error message.
 * ///////////////////////////////////////////////////////////////////////// */

function listBasePathMappings($apiGatewayClient, $domainName)
{
    try {
        $result = $apiGatewayClient->getBasePathMappings([
            'domainName' => $domainName
        ]);
        return 'The base path mapping(s) effective URI is: ' .
            $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e['message'];
    }
}

function listTheBasePathMappings()
{
    $apiGatewayClient = new ApiGatewayClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2015-07-09'
    ]);

    echo listBasePathMappings($apiGatewayClient, 'example.com');
}

// Uncomment the following line to run this code in an AWS account.
// listTheBasePathMappings();
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListBasePathMappings](https://docs.aws.amazon.com/goto/SdkForPHPV3/apigateway-2015-07-09/ListBasePathMappings)」を参照してください。

### `UpdateBasePathMapping`
<a name="api-gateway_UpdateBasePathMapping_php_3_topic"></a>

次のコード例は、`UpdateBasePathMapping` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/apigateway#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\ApiGateway\ApiGatewayClient;
use Aws\Exception\AwsException;


/* ////////////////////////////////////////////////////////////////////////////
 *
 * Purpose: Updates the base path mapping for a custom domain name
 * in Amazon API Gateway.
 *
 * Inputs:
 * - $apiGatewayClient: An initialized AWS SDK for PHP API client for
 *   API Gateway.
 * - $basePath: The base path name that callers must provide as part of the
 *   URL after the domain name.
 * - $domainName: The custom domain name for the base path mapping.
 * - $patchOperations: The base path update operations to apply.
 *
 * Returns: Information about the updated base path mapping, if available;
 * otherwise, the error message.
 * ///////////////////////////////////////////////////////////////////////// */

function updateBasePathMapping(
    $apiGatewayClient,
    $basePath,
    $domainName,
    $patchOperations
) {
    try {
        $result = $apiGatewayClient->updateBasePathMapping([
            'basePath' => $basePath,
            'domainName' => $domainName,
            'patchOperations' => $patchOperations
        ]);
        return 'The updated base path\'s URI is: ' .
            $result['@metadata']['effectiveUri'];
    } catch (AwsException $e) {
        return 'Error: ' . $e['message'];
    }
}

function updateTheBasePathMapping()
{
    $patchOperations = array([
        'op' => 'replace',
        'path' => '/stage',
        'value' => 'stage2'
    ]);

    $apiGatewayClient = new ApiGatewayClient([
        'profile' => 'default',
        'region' => 'us-east-1',
        'version' => '2015-07-09'
    ]);

    echo updateBasePathMapping(
        $apiGatewayClient,
        '(none)',
        'example.com',
        $patchOperations
    );
}

// Uncomment the following line to run this code in an AWS account.
// updateTheBasePathMapping();
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[UpdateBasePathMapping](https://docs.aws.amazon.com/goto/SdkForPHPV3/apigateway-2015-07-09/UpdateBasePathMapping)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_php_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for PHP**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/applications/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

# SDK for PHP を使用した Aurora の例
<a name="php_3_aurora_code_examples"></a>

次のコード例は、Aurora AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_php_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for PHP**  
 を使用して AWS SDK for PHP 、Amazon RDS データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful PHP バックエンドと対話します。  
+ React.js ウェブアプリケーションを AWS サービスに統合します。
+ Amazon RDS テーブル内の項目の一覧表示、追加、更新、削除を行います。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for PHP を使用した自動スケーリングの例
<a name="php_3_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにちは、Auto Scaling
<a name="auto-scaling_Hello_php_3_topic"></a>

次のコード例は、Auto Scaling の使用を開始する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function helloService()
    {
        $autoScalingClient = new AutoScalingClient([
            'region' => 'us-west-2',
            'version' => 'latest',
            'profile' => 'default',
        ]);

        $groups = $autoScalingClient->describeAutoScalingGroups([]);
        var_dump($groups);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="auto-scaling_Scenario_GroupsAndInstances_php_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 起動テンプレートとアベイラビリティーゾーンを使用して、Amazon EC2 Auto Scaling グループを作成し、実行中のインスタンスに関する情報を取得します。
+ Amazon CloudWatch メトリクスの収集を有効にします。
+ グループの希望するキャパシティを更新し、インスタンスが起動するのを待ちます。
+  グループ内の最も古いインスタンスを削除します。
+ ユーザーのリクエストやキャパシティの変更に応じて発生するスケーリングアクティビティを一覧表示します。
+ CloudWatch メトリクスの統計を取得して、リソースをクリーンアップします。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
namespace AutoScaling;

use Aws\AutoScaling\AutoScalingClient;
use Aws\CloudWatch\CloudWatchClient;
use Aws\Ec2\Ec2Client;
use AwsUtilities\AWSServiceClass;
use AwsUtilities\RunnableExample;

class GettingStartedWithAutoScaling implements RunnableExample
{
    protected Ec2Client $ec2Client;
    protected AutoScalingClient $autoScalingClient;
    protected AutoScalingService $autoScalingService;
    protected CloudWatchClient $cloudWatchClient;
    protected string $templateName;
    protected string $autoScalingGroupName;
    protected array $role;

    public function runExample()
    {
        echo("\n");
        echo("--------------------------------------\n");
        print("Welcome to the Amazon EC2 Auto Scaling getting started demo using PHP!\n");
        echo("--------------------------------------\n");

        $clientArgs = [
            'region' => 'us-west-2',
            'version' => 'latest',
            'profile' => 'default',
        ];
        $uniqid = uniqid();

        $this->autoScalingClient = new AutoScalingClient($clientArgs);
        $this->autoScalingService = new AutoScalingService($this->autoScalingClient);
        $this->cloudWatchClient = new CloudWatchClient($clientArgs);

        AWSServiceClass::$waitTime = 5;
        AWSServiceClass::$maxWaitAttempts = 20;

        /**
         * Step 0: Create an EC2 launch template that you'll use to create an Auto Scaling group.
         */
        $this->ec2Client = new EC2Client($clientArgs);
        $this->templateName = "example_launch_template_$uniqid";
        $instanceType = "t1.micro";
        $amiId = "ami-0ca285d4c2cda3300";
        $launchTemplate = $this->ec2Client->createLaunchTemplate(
            [
            'LaunchTemplateName' => $this->templateName,
            'LaunchTemplateData' => [
                'InstanceType' => $instanceType,
                'ImageId' => $amiId,
            ]
            ]
        );

        /**
         * Step 1: CreateAutoScalingGroup: pass it the launch template you created in step 0.
         */
        $availabilityZones[] = $this->ec2Client->describeAvailabilityZones([])['AvailabilityZones'][1]['ZoneName'];

        $this->autoScalingGroupName = "demoAutoScalingGroupName_$uniqid";
        $minSize = 1;
        $maxSize = 1;
        $launchTemplateId = $launchTemplate['LaunchTemplate']['LaunchTemplateId'];
        $this->autoScalingService->createAutoScalingGroup(
            $this->autoScalingGroupName,
            $availabilityZones,
            $minSize,
            $maxSize,
            $launchTemplateId
        );

        $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]);
        $autoScalingGroup = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]);

        /**
         * Step 2: DescribeAutoScalingInstances: show that one instance has launched.
         */
        $instanceIds = [$autoScalingGroup['AutoScalingGroups'][0]['Instances'][0]['InstanceId']];
        $instances = $this->autoScalingService->describeAutoScalingInstances($instanceIds);
        echo "The Auto Scaling group {$this->autoScalingGroupName} was created successfully.\n";
        echo count($instances['AutoScalingInstances']) . " instances were created for the group.\n";
        echo $autoScalingGroup['AutoScalingGroups'][0]['MaxSize'] . " is the max number of instances for the group.\n";

        /**
         * Step 3: EnableMetricsCollection: enable all metrics or a subset.
         */
        $this->autoScalingService->enableMetricsCollection($this->autoScalingGroupName, "1Minute");

        /**
         * Step 4: UpdateAutoScalingGroup: update max size to 3.
         */
        echo "Updating the max number of instances to 3.\n";
        $this->autoScalingService->updateAutoScalingGroup($this->autoScalingGroupName, ['MaxSize' => 3]);

        /**
         * Step 5: DescribeAutoScalingGroups: show the current state of the group.
         */
        $autoScalingGroup = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]);
        echo $autoScalingGroup['AutoScalingGroups'][0]['MaxSize'];
        echo " is the updated max number of instances for the group.\n";

        $limits = $this->autoScalingService->describeAccountLimits();
        echo "Here are your account limits:\n";
        echo "MaxNumberOfAutoScalingGroups: {$limits['MaxNumberOfAutoScalingGroups']}\n";
        echo "MaxNumberOfLaunchConfigurations: {$limits['MaxNumberOfLaunchConfigurations']}\n";
        echo "NumberOfAutoScalingGroups: {$limits['NumberOfAutoScalingGroups']}\n";
        echo "NumberOfLaunchConfigurations: {$limits['NumberOfLaunchConfigurations']}\n";

        /**
         * Step 6: SetDesiredCapacity: set desired capacity to 2.
         */
        $this->autoScalingService->setDesiredCapacity($this->autoScalingGroupName, 2);
        sleep(10); // Wait for the group to start processing the request.
        $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]);

        /**
         * Step 7: DescribeAutoScalingInstances: show that two instances are launched.
         */
        $autoScalingGroups = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]);
        foreach ($autoScalingGroups['AutoScalingGroups'] as $autoScalingGroup) {
            echo "There is a group named: {$autoScalingGroup['AutoScalingGroupName']}";
            echo "with an ARN of {$autoScalingGroup['AutoScalingGroupARN']}.\n";
            foreach ($autoScalingGroup['Instances'] as $instance) {
                echo "{$autoScalingGroup['AutoScalingGroupName']} has an instance with id of: ";
                echo "{$instance['InstanceId']} and a lifecycle state of: {$instance['LifecycleState']}.\n";
            }
        }

        /**
         * Step 8: TerminateInstanceInAutoScalingGroup: terminate one of the instances in the group.
         */
        $this->autoScalingService->terminateInstanceInAutoScalingGroup($instance['InstanceId'], false);
        do {
            sleep(10);
            $instances = $this->autoScalingService->describeAutoScalingInstances([$instance['InstanceId']]);
        } while (count($instances['AutoScalingInstances']) > 0);
        do {
            sleep(10);
            $autoScalingGroups = $this->autoScalingService->describeAutoScalingGroups([$this->autoScalingGroupName]);
            $instances = $autoScalingGroups['AutoScalingGroups'][0]['Instances'];
        } while (count($instances) < 2);
        $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]);
        foreach ($autoScalingGroups['AutoScalingGroups'] as $autoScalingGroup) {
            echo "There is a group named: {$autoScalingGroup['AutoScalingGroupName']}";
            echo "with an ARN of {$autoScalingGroup['AutoScalingGroupARN']}.\n";
            foreach ($autoScalingGroup['Instances'] as $instance) {
                echo "{$autoScalingGroup['AutoScalingGroupName']} has an instance with id of: ";
                echo "{$instance['InstanceId']} and a lifecycle state of: {$instance['LifecycleState']}.\n";
            }
        }

        /**
         * Step 9: DescribeScalingActivities: list the scaling activities that have occurred for the group so far.
         */
        $activities = $this->autoScalingService->describeScalingActivities($autoScalingGroup['AutoScalingGroupName']);
        echo "We found " . count($activities['Activities']) . " activities.\n";
        foreach ($activities['Activities'] as $activity) {
            echo "{$activity['ActivityId']} - {$activity['StartTime']} - {$activity['Description']}\n";
        }

        /**
         * Step 10: Use the Amazon CloudWatch API to get and show some metrics collected for the group.
         */
        $metricsNamespace = 'AWS/AutoScaling';
        $metricsDimensions = [
            [
                'Name' => 'AutoScalingGroupName',
                'Value' => $autoScalingGroup['AutoScalingGroupName'],
            ],
        ];
        $metrics = $this->cloudWatchClient->listMetrics(
            [
            'Dimensions' => $metricsDimensions,
            'Namespace' => $metricsNamespace,
            ]
        );
        foreach ($metrics['Metrics'] as $metric) {
            $timespan = 5;
            if ($metric['MetricName'] != 'GroupTotalCapacity' && $metric['MetricName'] != 'GroupMaxSize') {
                continue;
            }
            echo "Over the last $timespan minutes, {$metric['MetricName']} recorded:\n";
            $stats = $this->cloudWatchClient->getMetricStatistics(
                [
                'Dimensions' => $metricsDimensions,
                'EndTime' => time(),
                'StartTime' => time() - (5 * 60),
                'MetricName' => $metric['MetricName'],
                'Namespace' => $metricsNamespace,
                'Period' => 60,
                'Statistics' => ['Sum'],
                ]
            );
            foreach ($stats['Datapoints'] as $stat) {
                echo "{$stat['Timestamp']}: {$stat['Sum']}\n";
            }
        }

        return $instances;
    }

    public function cleanUp()
    {
        /**
         * Step 11: DisableMetricsCollection: disable all metrics.
         */
        $this->autoScalingService->disableMetricsCollection($this->autoScalingGroupName);

        /**
         * Step 12: DeleteAutoScalingGroup: to delete the group you must stop all instances.
         * - UpdateAutoScalingGroup with MinSize=0
         * - TerminateInstanceInAutoScalingGroup for each instance,
         *     specify ShouldDecrementDesiredCapacity=True. Wait for instances to stop.
         * - Now you can delete the group.
         */
        $this->autoScalingService->updateAutoScalingGroup($this->autoScalingGroupName, ['MinSize' => 0]);
        $this->autoScalingService->terminateAllInstancesInAutoScalingGroup($this->autoScalingGroupName);
        $this->autoScalingService->waitUntilGroupInService([$this->autoScalingGroupName]);
        $this->autoScalingService->deleteAutoScalingGroup($this->autoScalingGroupName);

        /**
         * Step 13: Delete launch template.
         */
        $this->ec2Client->deleteLaunchTemplate(
            [
            'LaunchTemplateName' => $this->templateName,
            ]
        );
    }

    public function helloService()
    {
        $autoScalingClient = new AutoScalingClient([
            'region' => 'us-west-2',
            'version' => 'latest',
            'profile' => 'default',
        ]);

        $groups = $autoScalingClient->describeAutoScalingGroups([]);
        var_dump($groups);
    }
}
```
+ API の詳細については、「AWS SDK for PHP API リファレンス**」の以下のトピックを参照してください。
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingInstances)
  + [DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeScalingActivities)
  + [DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DisableMetricsCollection)
  + [EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/EnableMetricsCollection)
  + [SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/SetDesiredCapacity)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

## アクション
<a name="actions"></a>

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_php_3_topic"></a>

次のコード例は、`CreateAutoScalingGroup` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function createAutoScalingGroup(
        $autoScalingGroupName,
        $availabilityZones,
        $minSize,
        $maxSize,
        $launchTemplateId
    ) {
        return $this->autoScalingClient->createAutoScalingGroup([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'AvailabilityZones' => $availabilityZones,
            'MinSize' => $minSize,
            'MaxSize' => $maxSize,
            'LaunchTemplate' => [
                'LaunchTemplateId' => $launchTemplateId,
            ],
        ]);
    }
```
+  詳細については、*AWS SDK for PHP API リファレンス*の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_php_3_topic"></a>

次のコード例は、`DeleteAutoScalingGroup` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function deleteAutoScalingGroup($autoScalingGroupName)
    {
        return $this->autoScalingClient->deleteAutoScalingGroup([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'ForceDelete' => true,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_php_3_topic"></a>

次のコード例は、`DescribeAutoScalingGroups` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function describeAutoScalingGroups($autoScalingGroupNames)
    {
        return $this->autoScalingClient->describeAutoScalingGroups([
            'AutoScalingGroupNames' => $autoScalingGroupNames
        ]);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_php_3_topic"></a>

次のコード例は、`DescribeAutoScalingInstances` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function describeAutoScalingInstances($instanceIds)
    {
        return $this->autoScalingClient->describeAutoScalingInstances([
            'InstanceIds' => $instanceIds
        ]);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_php_3_topic"></a>

次のコード例は、`DescribeScalingActivities` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function describeScalingActivities($autoScalingGroupName)
    {
        return $this->autoScalingClient->describeScalingActivities([
            'AutoScalingGroupName' => $autoScalingGroupName,
        ]);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_php_3_topic"></a>

次のコード例は、`DisableMetricsCollection` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function disableMetricsCollection($autoScalingGroupName)
    {
        return $this->autoScalingClient->disableMetricsCollection([
            'AutoScalingGroupName' => $autoScalingGroupName,
        ]);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_php_3_topic"></a>

次のコード例は、`EnableMetricsCollection` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function enableMetricsCollection($autoScalingGroupName, $granularity)
    {
        return $this->autoScalingClient->enableMetricsCollection([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'Granularity' => $granularity,
        ]);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_php_3_topic"></a>

次のコード例は、`SetDesiredCapacity` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function setDesiredCapacity($autoScalingGroupName, $desiredCapacity)
    {
        return $this->autoScalingClient->setDesiredCapacity([
            'AutoScalingGroupName' => $autoScalingGroupName,
            'DesiredCapacity' => $desiredCapacity,
        ]);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_php_3_topic"></a>

次のコード例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function terminateInstanceInAutoScalingGroup(
        $instanceId,
        $shouldDecrementDesiredCapacity = true,
        $attempts = 0
    ) {
        try {
            return $this->autoScalingClient->terminateInstanceInAutoScalingGroup([
                'InstanceId' => $instanceId,
                'ShouldDecrementDesiredCapacity' => $shouldDecrementDesiredCapacity,
            ]);
        } catch (AutoScalingException $exception) {
            if ($exception->getAwsErrorCode() == "ScalingActivityInProgress" && $attempts < 5) {
                error_log("Cannot terminate an instance while it is still pending. Waiting then trying again.");
                sleep(5 * (1 + $attempts));
                return $this->terminateInstanceInAutoScalingGroup(
                    $instanceId,
                    $shouldDecrementDesiredCapacity,
                    ++$attempts
                );
            } else {
                throw $exception;
            }
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_php_3_topic"></a>

次のコード例は、`UpdateAutoScalingGroup` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    public function updateAutoScalingGroup($autoScalingGroupName, $args)
    {
        if (array_key_exists('MaxSize', $args)) {
            $maxSize = ['MaxSize' => $args['MaxSize']];
        } else {
            $maxSize = [];
        }
        if (array_key_exists('MinSize', $args)) {
            $minSize = ['MinSize' => $args['MinSize']];
        } else {
            $minSize = [];
        }
        $parameters = ['AutoScalingGroupName' => $autoScalingGroupName];
        $parameters = array_merge($parameters, $minSize, $maxSize);
        return $this->autoScalingClient->updateAutoScalingGroup($parameters);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。

# SDK for PHP を使用した Amazon Bedrock の例
<a name="php_3_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_php_3_topic"></a>

次のコード例は、`ListFoundationModels` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。
利用可能な Amazon Bedrock 基盤モデルを一覧表示します。  

```
    public function listFoundationModels()
    {
        $bedrockClient = new BedrockClient([
            'region' => 'us-west-2',
            'profile' => 'default'
        ]);
        $response = $bedrockClient->listFoundationModels();
        return $response['modelSummaries'];
    }
```
+  API の詳細については、「AWS SDK for PHP API リファレンス**」の「[ListFoundationModels](https://docs.aws.amazon.com/goto/SdkForPHPV3/bedrock-2023-04-20/ListFoundationModels)」を参照してください。

# SDK for PHP を使用した Amazon Bedrock ランタイムの例
<a name="php_3_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイム AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)
+ [Amazon Nova](#amazon_nova)
+ [Amazon Titan Image Generator](#amazon_titan_image_generator)
+ [Anthropic Claude](#anthropic_claude)
+ [Stable Diffusion](#stable_diffusion)

## シナリオ
<a name="scenarios"></a>

### Amazon Bedrock で複数の基盤モデルを呼び出す
<a name="bedrock-runtime_Scenario_InvokeModels_php_3_topic"></a>

次のコード例は、Amazon Bedrock でさまざまな大規模言語モデル (LLM) にプロンプトを準備して送信する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/bedrock-runtime/#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で複数の LLM を呼び出します。  

```
namespace BedrockRuntime;

class GettingStartedWithBedrockRuntime
{
    protected BedrockRuntimeService $bedrockRuntimeService;
    public function runExample()
    {
        echo "\n";
        echo "---------------------------------------------------------------------\n";
        echo "Welcome to the Amazon Bedrock Runtime getting started demo using PHP!\n";
        echo "---------------------------------------------------------------------\n";
        $bedrockRuntimeService = new BedrockRuntimeService();
        $prompt = 'In one paragraph, who are you?';
        echo "\nPrompt: " . $prompt;
        echo "\n\nAnthropic Claude:\n";
        echo $bedrockRuntimeService->invokeClaude($prompt);
        echo "\n---------------------------------------------------------------------\n";
        $image_prompt = 'stylized picture of a cute old steampunk robot';
        echo "\nImage prompt: " . $image_prompt;
        echo "\n\nStability.ai Stable Diffusion XL:\n";
        $diffusionSeed = rand(0, 4294967295);
        $style_preset = 'photographic';
        $base64 = $bedrockRuntimeService->invokeStableDiffusion($image_prompt, $diffusionSeed, $style_preset);
        $image_path = $this->saveImage($base64, 'stability.stable-diffusion-xl');
        echo "The generated image has been saved to $image_path";
        echo "\n\nAmazon Titan Image Generation:\n";
        $titanSeed = rand(0, 2147483647);
        $base64 = $bedrockRuntimeService->invokeTitanImage($image_prompt, $titanSeed);
        $image_path = $this->saveImage($base64, 'amazon.titan-image-generator-v2');
        echo "The generated image has been saved to $image_path";
    }

    private function saveImage($base64_image_data, $model_id): string
    {
        $output_dir = "output";
        if (!file_exists($output_dir)) {
            mkdir($output_dir);
        }

        $i = 1;
        while (file_exists("$output_dir/$model_id" . '_' . "$i.png")) {
            $i++;
        }

        $image_data = base64_decode($base64_image_data);
        $file_path = "$output_dir/$model_id" . '_' . "$i.png";
        $file = fopen($file_path, 'wb');
        fwrite($file, $image_data);
        fclose($file);
        return $file_path;
    }
}
```
+ API の詳細については、「AWS SDK for PHP API リファレンス**」の以下のトピックを参照してください。
  + [InvokeModel](https://docs.aws.amazon.com/goto/SdkForPHPV3/bedrock-runtime-2023-09-30/InvokeModel)
  + [InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/SdkForPHPV3/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)

## Amazon Nova
<a name="amazon_nova"></a>

### Converse
<a name="bedrock-runtime_Converse_AmazonNovaText_php_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
// Use the Conversation API to send a text message to Amazon Nova.

use Aws\BedrockRuntime\BedrockRuntimeClient;
use Aws\Exception\AwsException;
use RuntimeException;

class Converse
{
    public function converse(): string
    {
        // Create a Bedrock Runtime client in the AWS Region you want to use.
        $client = new BedrockRuntimeClient([
            'region' => 'us-east-1',
            'profile' => 'default'
        ]);

        // Set the model ID, e.g., Amazon Nova Lite.
        $modelId = 'amazon.nova-lite-v1:0';

        // Start a conversation with the user message.
        $userMessage = "Describe the purpose of a 'hello world' program in one line.";
        $conversation = [
            [
                "role" => "user",
                "content" => [["text" => $userMessage]]
            ]
        ];

        try {
            // Send the message to the model, using a basic inference configuration.
            $response = $client->converse([
                'modelId' => $modelId,
                'messages' => $conversation,
                'inferenceConfig' => [
                    'maxTokens' => 512,
                    'temperature' => 0.5
                ]
            ]);

            // Extract and return the response text.
            $responseText = $response['output']['message']['content'][0]['text'];
            return $responseText;
        } catch (AwsException $e) {
            echo "ERROR: Can't invoke {$modelId}. Reason: {$e->getAwsErrorMessage()}";
            throw new RuntimeException("Failed to invoke model: " . $e->getAwsErrorMessage(), 0, $e);
        }
    }
}

$demo = new Converse();
echo $demo->converse();
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[Converse](https://docs.aws.amazon.com/goto/SdkForPHPV3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Amazon Titan Image Generator
<a name="amazon_titan_image_generator"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_TitanImageGenerator_php_3_topic"></a>

次のコード例は、Amazon Bedrock で Amazon Titan Image を呼び出して画像を生成する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Titan Image Generator を使用して画像を作成します。  

```
    public function invokeTitanImage(string $prompt, int $seed)
    {
        // The different model providers have individual request and response formats.
        // For the format, ranges, and default values for Titan Image models refer to:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-titan-image.html

        $base64_image_data = "";
        try {
            $modelId = 'amazon.titan-image-generator-v2:0';
            $request = json_encode([
                'taskType' => 'TEXT_IMAGE',
                'textToImageParams' => [
                    'text' => $prompt
                ],
                'imageGenerationConfig' => [
                    'numberOfImages' => 1,
                    'quality' => 'standard',
                    'cfgScale' => 8.0,
                    'height' => 512,
                    'width' => 512,
                    'seed' => $seed
                ]
            ]);
            $result = $this->bedrockRuntimeClient->invokeModel([
                'contentType' => 'application/json',
                'body' => $request,
                'modelId' => $modelId,
            ]);
            $response_body = json_decode($result['body']);
            $base64_image_data = $response_body->images[0];
        } catch (Exception $e) {
            echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n";
        }

        return $base64_image_data;
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForPHPV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Anthropic Claude
<a name="anthropic_claude"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AnthropicClaude_php_3_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Anthropic Claude 2 基盤モデルを呼び出して、テキストを生成します。  

```
    public function invokeClaude($prompt)
    {
        // The different model providers have individual request and response formats.
        // For the format, ranges, and default values for Anthropic Claude, refer to:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-claude.html

        $completion = "";
        try {
            $modelId = 'anthropic.claude-3-haiku-20240307-v1:0';
        // Claude requires you to enclose the prompt as follows:
            $body = [
                'anthropic_version' => 'bedrock-2023-05-31',
                'max_tokens' => 512,
                'temperature' => 0.5,
                'messages' => [[
                    'role' => 'user',
                    'content' => $prompt
                ]]
            ];
            $result = $this->bedrockRuntimeClient->invokeModel([
                'contentType' => 'application/json',
                'body' => json_encode($body),
                'modelId' => $modelId,
            ]);
            $response_body = json_decode($result['body']);
            $completion = $response_body->content[0]->text;
        } catch (Exception $e) {
            echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n";
        }

        return $completion;
    }
```
+  API の詳細については、「**AWS SDK for PHP API リファレンス」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForPHPV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Stable Diffusion
<a name="stable_diffusion"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_StableDiffusion_php_3_topic"></a>

次のコード例は、Amazon Bedrock で Stability.ai Stable Diffusion XL を呼び出して画像を生成する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Stable Diffusion で画像を作成します。  

```
    public function invokeStableDiffusion(string $prompt, int $seed, string $style_preset)
    {
        // The different model providers have individual request and response formats.
        // For the format, ranges, and available style_presets of Stable Diffusion models refer to:
        // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-stability-diffusion.html

        $base64_image_data = "";
        try {
            $modelId = 'stability.stable-diffusion-xl-v1';
            $body = [
                'text_prompts' => [
                    ['text' => $prompt]
                ],
                'seed' => $seed,
                'cfg_scale' => 10,
                'steps' => 30
            ];
            if ($style_preset) {
                $body['style_preset'] = $style_preset;
            }

            $result = $this->bedrockRuntimeClient->invokeModel([
                'contentType' => 'application/json',
                'body' => json_encode($body),
                'modelId' => $modelId,
            ]);
            $response_body = json_decode($result['body']);
            $base64_image_data = $response_body->artifacts[0]->base64;
        } catch (Exception $e) {
            echo "Error: ({$e->getCode()}) - {$e->getMessage()}\n";
        }

        return $base64_image_data;
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/goto/SdkForPHPV3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

# SDK for PHP を使用した Amazon DocumentDB の例
<a name="php_3_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_php_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
<?php

require __DIR__.'/vendor/autoload.php';

use Bref\Context\Context;
use Bref\Event\Handler;

class DocumentDBEventHandler implements Handler
{
    public function handle($event, Context $context): string
    {

        $events = $event['events'] ?? [];
        foreach ($events as $record) {
            $this->logDocumentDBEvent($record['event']);
        }
        return 'OK';
    }

    private function logDocumentDBEvent($event): void
    {
        // Extract information from the event record

        $operationType = $event['operationType'] ?? 'Unknown';
        $db = $event['ns']['db'] ?? 'Unknown';
        $collection = $event['ns']['coll'] ?? 'Unknown';
        $fullDocument = $event['fullDocument'] ?? [];

        // Log the event details

        echo "Operation type: $operationType\n";
        echo "Database: $db\n";
        echo "Collection: $collection\n";
        echo "Full document: " . json_encode($fullDocument, JSON_PRETTY_PRINT) . "\n";
    }
}
return new DocumentDBEventHandler();
```

# SDK for PHP を使用した DynamoDB の例
<a name="php_3_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_php_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
この例ではサポートファイルを使用しているため、PHP 例の README.md ファイルの[ガイダンスをお読みください](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/php/README.md#prerequisites)。  

```
namespace DynamoDb\Basics;

use Aws\DynamoDb\Marshaler;
use DynamoDb;
use DynamoDb\DynamoDBAttribute;
use DynamoDb\DynamoDBService;

use function AwsUtilities\loadMovieData;
use function AwsUtilities\testable_readline;

class GettingStartedWithDynamoDB
{
    public function run()
    {
        echo("\n");
        echo("--------------------------------------\n");
        print("Welcome to the Amazon DynamoDB getting started demo using PHP!\n");
        echo("--------------------------------------\n");

        $uuid = uniqid();
        $service = new DynamoDBService();

        $tableName = "ddb_demo_table_$uuid";
        $service->createTable(
            $tableName,
            [
                new DynamoDBAttribute('year', 'N', 'HASH'),
                new DynamoDBAttribute('title', 'S', 'RANGE')
            ]
        );

        echo "Waiting for table...";
        $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]);
        echo "table $tableName found!\n";

        echo "What's the name of the last movie you watched?\n";
        while (empty($movieName)) {
            $movieName = testable_readline("Movie name: ");
        }
        echo "And what year was it released?\n";
        $movieYear = "year";
        while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) {
            $movieYear = testable_readline("Year released: ");
        }

        $service->putItem([
            'Item' => [
                'year' => [
                    'N' => "$movieYear",
                ],
                'title' => [
                    'S' => $movieName,
                ],
            ],
            'TableName' => $tableName,
        ]);

        echo "How would you rate the movie from 1-10?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        echo "What was the movie about?\n";
        while (empty($plot)) {
            $plot = testable_readline("Plot summary: ");
        }
        $key = [
            'Item' => [
                'title' => [
                    'S' => $movieName,
                ],
                'year' => [
                    'N' => $movieYear,
                ],
            ]
        ];
        $attributes = ["rating" =>
            [
                'AttributeName' => 'rating',
                'AttributeType' => 'N',
                'Value' => $rating,
            ],
            'plot' => [
                'AttributeName' => 'plot',
                'AttributeType' => 'S',
                'Value' => $plot,
            ]
        ];
        $service->updateItemAttributesByKey($tableName, $key, $attributes);
        echo "Movie added and updated.";

        $batch = json_decode(loadMovieData());

        $service->writeBatch($tableName, $batch);


        $movie = $service->getItemByKey($tableName, $key);
        echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n";
        echo "What rating would you like to give {$movie['Item']['title']['S']}?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        $service->updateItemAttributeByKey($tableName, $key, 'rating', 'N', $rating);

        $movie = $service->getItemByKey($tableName, $key);
        echo "Ok, you have rated {$movie['Item']['title']['S']} as a {$movie['Item']['rating']['N']}\n";

        $service->deleteItemByKey($tableName, $key);
        echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n";

        echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n";
        $birthYear = "not a number";
        while (!is_numeric($birthYear) || $birthYear >= date("Y")) {
            $birthYear = testable_readline("Birth year: ");
        }
        $birthKey = [
            'Key' => [
                'year' => [
                    'N' => "$birthYear",
                ],
            ],
        ];
        $result = $service->query($tableName, $birthKey);
        $marshal = new Marshaler();
        echo "Here are the movies in our collection released the year you were born:\n";
        $oops = "Oops! There were no movies released in that year (that we know of).\n";
        $display = "";
        foreach ($result['Items'] as $movie) {
            $movie = $marshal->unmarshalItem($movie);
            $display .= $movie['title'] . "\n";
        }
        echo ($display) ?: $oops;

        $yearsKey = [
            'Key' => [
                'year' => [
                    'N' => [
                        'minRange' => 1990,
                        'maxRange' => 1999,
                    ],
                ],
            ],
        ];
        $filter = "year between 1990 and 1999";
        echo "\nHere's a list of all the movies released in the 90s:\n";
        $result = $service->scan($tableName, $yearsKey, $filter);
        foreach ($result['Items'] as $movie) {
            $movie = $marshal->unmarshalItem($movie);
            echo $movie['title'] . "\n";
        }

        echo "\nCleaning up this demo by deleting table $tableName...\n";
        $service->deleteTable($tableName);
    }
}
```
+ API の詳細については、「AWS SDK for PHP API リファレンス**」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/BatchWriteItem)
  + [CreateTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/CreateTable)
  + [DeleteItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteItem)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Scan)
  + [UpdateItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/UpdateItem)

## アクション
<a name="actions"></a>

### `BatchExecuteStatement`
<a name="dynamodb_BatchExecuteStatement_php_3_topic"></a>

次のコード例は、`BatchExecuteStatement` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    public function getItemByPartiQLBatch(string $tableName, array $keys): Result
    {
        $statements = [];
        foreach ($keys as $key) {
            list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']);
            $statements[] = [
                'Statement' => "$statement",
                'Parameters' => $parameters,
            ];
        }

        return $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => $statements,
        ]);
    }

    public function insertItemByPartiQLBatch(string $statement, array $parameters)
    {
        $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => [
                [
                    'Statement' => "$statement",
                    'Parameters' => $parameters,
                ],
            ],
        ]);
    }

    public function updateItemByPartiQLBatch(string $statement, array $parameters)
    {
        $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => [
                [
                    'Statement' => "$statement",
                    'Parameters' => $parameters,
                ],
            ],
        ]);
    }

    public function deleteItemByPartiQLBatch(string $statement, array $parameters)
    {
        $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => [
                [
                    'Statement' => "$statement",
                    'Parameters' => $parameters,
                ],
            ],
        ]);
    }
```
+  API の詳細については*AWS SDK for PHP API リファレンス*の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_php_3_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    public function writeBatch(string $TableName, array $Batch, int $depth = 2)
    {
        if (--$depth <= 0) {
            throw new Exception("Max depth exceeded. Please try with fewer batch items or increase depth.");
        }

        $marshal = new Marshaler();
        $total = 0;
        foreach (array_chunk($Batch, 25) as $Items) {
            foreach ($Items as $Item) {
                $BatchWrite['RequestItems'][$TableName][] = ['PutRequest' => ['Item' => $marshal->marshalItem($Item)]];
            }
            try {
                echo "Batching another " . count($Items) . " for a total of " . ($total += count($Items)) . " items!\n";
                $response = $this->dynamoDbClient->batchWriteItem($BatchWrite);
                $BatchWrite = [];
            } catch (Exception $e) {
                echo "uh oh...";
                echo $e->getMessage();
                die();
            }
            if ($total >= 250) {
                echo "250 movies is probably enough. Right? We can stop there.\n";
                break;
            }
        }
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。**

### `CreateTable`
<a name="dynamodb_CreateTable_php_3_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルを作成します。  

```
        $tableName = "ddb_demo_table_$uuid";
        $service->createTable(
            $tableName,
            [
                new DynamoDBAttribute('year', 'N', 'HASH'),
                new DynamoDBAttribute('title', 'S', 'RANGE')
            ]
        );

    public function createTable(string $tableName, array $attributes)
    {
        $keySchema = [];
        $attributeDefinitions = [];
        foreach ($attributes as $attribute) {
            if (is_a($attribute, DynamoDBAttribute::class)) {
                $keySchema[] = ['AttributeName' => $attribute->AttributeName, 'KeyType' => $attribute->KeyType];
                $attributeDefinitions[] =
                    ['AttributeName' => $attribute->AttributeName, 'AttributeType' => $attribute->AttributeType];
            }
        }

        $this->dynamoDbClient->createTable([
            'TableName' => $tableName,
            'KeySchema' => $keySchema,
            'AttributeDefinitions' => $attributeDefinitions,
            'ProvisionedThroughput' => ['ReadCapacityUnits' => 10, 'WriteCapacityUnits' => 10],
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[CreateTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_php_3_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        $key = [
            'Item' => [
                'title' => [
                    'S' => $movieName,
                ],
                'year' => [
                    'N' => $movieYear,
                ],
            ]
        ];

        $service->deleteItemByKey($tableName, $key);
        echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n";

    public function deleteItemByKey(string $tableName, array $key)
    {
        $this->dynamoDbClient->deleteItem([
            'Key' => $key['Item'],
            'TableName' => $tableName,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[DeleteItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteItem)」を参照してください。**

### `DeleteTable`
<a name="dynamodb_DeleteTable_php_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    public function deleteTable(string $TableName)
    {
        $this->customWaiter(function () use ($TableName) {
            return $this->dynamoDbClient->deleteTable([
                'TableName' => $TableName,
            ]);
        });
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `ExecuteStatement`
<a name="dynamodb_ExecuteStatement_php_3_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    public function insertItemByPartiQL(string $statement, array $parameters)
    {
        $this->dynamoDbClient->executeStatement([
            'Statement' => "$statement",
            'Parameters' => $parameters,
        ]);
    }

    public function getItemByPartiQL(string $tableName, array $key): Result
    {
        list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']);

        return $this->dynamoDbClient->executeStatement([
            'Parameters' => $parameters,
            'Statement' => $statement,
        ]);
    }

    public function updateItemByPartiQL(string $statement, array $parameters)
    {
        $this->dynamoDbClient->executeStatement([
            'Statement' => $statement,
            'Parameters' => $parameters,
        ]);
    }

    public function deleteItemByPartiQL(string $statement, array $parameters)
    {
        $this->dynamoDbClient->executeStatement([
            'Statement' => $statement,
            'Parameters' => $parameters,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_php_3_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        $movie = $service->getItemByKey($tableName, $key);
        echo "\nThe movie {$movie['Item']['title']['S']} was released in {$movie['Item']['year']['N']}.\n";

    public function getItemByKey(string $tableName, array $key)
    {
        return $this->dynamoDbClient->getItem([
            'Key' => $key['Item'],
            'TableName' => $tableName,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/GetItem)」を参照してください。**

### `ListTables`
<a name="dynamodb_ListTables_php_3_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
    public function listTables($exclusiveStartTableName = "", $limit = 100)
    {
        $this->dynamoDbClient->listTables([
            'ExclusiveStartTableName' => $exclusiveStartTableName,
            'Limit' => $limit,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListTables](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_php_3_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        echo "What's the name of the last movie you watched?\n";
        while (empty($movieName)) {
            $movieName = testable_readline("Movie name: ");
        }
        echo "And what year was it released?\n";
        $movieYear = "year";
        while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) {
            $movieYear = testable_readline("Year released: ");
        }

        $service->putItem([
            'Item' => [
                'year' => [
                    'N' => "$movieYear",
                ],
                'title' => [
                    'S' => $movieName,
                ],
            ],
            'TableName' => $tableName,
        ]);

    public function putItem(array $array)
    {
        $this->dynamoDbClient->putItem($array);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/PutItem)」を参照してください。**

### `Query`
<a name="dynamodb_Query_php_3_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        $birthKey = [
            'Key' => [
                'year' => [
                    'N' => "$birthYear",
                ],
            ],
        ];
        $result = $service->query($tableName, $birthKey);

    public function query(string $tableName, $key)
    {
        $expressionAttributeValues = [];
        $expressionAttributeNames = [];
        $keyConditionExpression = "";
        $index = 1;
        foreach ($key as $name => $value) {
            $keyConditionExpression .= "#" . array_key_first($value) . " = :v$index,";
            $expressionAttributeNames["#" . array_key_first($value)] = array_key_first($value);
            $hold = array_pop($value);
            $expressionAttributeValues[":v$index"] = [
                array_key_first($hold) => array_pop($hold),
            ];
        }
        $keyConditionExpression = substr($keyConditionExpression, 0, -1);
        $query = [
            'ExpressionAttributeValues' => $expressionAttributeValues,
            'ExpressionAttributeNames' => $expressionAttributeNames,
            'KeyConditionExpression' => $keyConditionExpression,
            'TableName' => $tableName,
        ];
        return $this->dynamoDbClient->query($query);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Query)」を参照してください。**

### `Scan`
<a name="dynamodb_Scan_php_3_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        $yearsKey = [
            'Key' => [
                'year' => [
                    'N' => [
                        'minRange' => 1990,
                        'maxRange' => 1999,
                    ],
                ],
            ],
        ];
        $filter = "year between 1990 and 1999";
        echo "\nHere's a list of all the movies released in the 90s:\n";
        $result = $service->scan($tableName, $yearsKey, $filter);
        foreach ($result['Items'] as $movie) {
            $movie = $marshal->unmarshalItem($movie);
            echo $movie['title'] . "\n";
        }

    public function scan(string $tableName, array $key, string $filters)
    {
        $query = [
            'ExpressionAttributeNames' => ['#year' => 'year'],
            'ExpressionAttributeValues' => [
                ":min" => ['N' => '1990'],
                ":max" => ['N' => '1999'],
            ],
            'FilterExpression' => "#year between :min and :max",
            'TableName' => $tableName,
        ];
        return $this->dynamoDbClient->scan($query);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Scan](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/Scan)」を参照してください。**

### `UpdateItem`
<a name="dynamodb_UpdateItem_php_3_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
        echo "What rating would you like to give {$movie['Item']['title']['S']}?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        $service->updateItemAttributeByKey($tableName, $key, 'rating', 'N', $rating);

    public function updateItemAttributeByKey(
        string $tableName,
        array $key,
        string $attributeName,
        string $attributeType,
        string $newValue
    ) {
        $this->dynamoDbClient->updateItem([
            'Key' => $key['Item'],
            'TableName' => $tableName,
            'UpdateExpression' => "set #NV=:NV",
            'ExpressionAttributeNames' => [
                '#NV' => $attributeName,
            ],
            'ExpressionAttributeValues' => [
                ':NV' => [
                    $attributeType => $newValue
                ]
            ],
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_php_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for PHP**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/applications/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_php_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
namespace DynamoDb\PartiQL_Basics;

use Aws\DynamoDb\Marshaler;
use DynamoDb;
use DynamoDb\DynamoDBAttribute;

use function AwsUtilities\loadMovieData;
use function AwsUtilities\testable_readline;

class GettingStartedWithPartiQLBatch
{
    public function run()
    {
        echo("\n");
        echo("--------------------------------------\n");
        print("Welcome to the Amazon DynamoDB - PartiQL getting started demo using PHP!\n");
        echo("--------------------------------------\n");

        $uuid = uniqid();
        $service = new DynamoDb\DynamoDBService();

        $tableName = "partiql_demo_table_$uuid";
        $service->createTable(
            $tableName,
            [
                new DynamoDBAttribute('year', 'N', 'HASH'),
                new DynamoDBAttribute('title', 'S', 'RANGE')
            ]
        );

        echo "Waiting for table...";
        $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]);
        echo "table $tableName found!\n";

        echo "What's the name of the last movie you watched?\n";
        while (empty($movieName)) {
            $movieName = testable_readline("Movie name: ");
        }
        echo "And what year was it released?\n";
        $movieYear = "year";
        while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) {
            $movieYear = testable_readline("Year released: ");
        }
        $key = [
            'Item' => [
                'year' => [
                    'N' => "$movieYear",
                ],
                'title' => [
                    'S' => $movieName,
                ],
            ],
        ];
        list($statement, $parameters) = $service->buildStatementAndParameters("INSERT", $tableName, $key);
        $service->insertItemByPartiQLBatch($statement, $parameters);

        echo "How would you rate the movie from 1-10?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        echo "What was the movie about?\n";
        while (empty($plot)) {
            $plot = testable_readline("Plot summary: ");
        }
        $attributes = [
            new DynamoDBAttribute('rating', 'N', 'HASH', $rating),
            new DynamoDBAttribute('plot', 'S', 'RANGE', $plot),
        ];

        list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes);
        $service->updateItemByPartiQLBatch($statement, $parameters);
        echo "Movie added and updated.\n";

        $batch = json_decode(loadMovieData());

        $service->writeBatch($tableName, $batch);

        $movie = $service->getItemByPartiQLBatch($tableName, [$key]);
        echo "\nThe movie {$movie['Responses'][0]['Item']['title']['S']} 
        was released in {$movie['Responses'][0]['Item']['year']['N']}.\n";
        echo "What rating would you like to give {$movie['Responses'][0]['Item']['title']['S']}?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        $attributes = [
            new DynamoDBAttribute('rating', 'N', 'HASH', $rating),
            new DynamoDBAttribute('plot', 'S', 'RANGE', $plot)
        ];
        list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes);
        $service->updateItemByPartiQLBatch($statement, $parameters);

        $movie = $service->getItemByPartiQLBatch($tableName, [$key]);
        echo "Okay, you have rated {$movie['Responses'][0]['Item']['title']['S']} 
        as a {$movie['Responses'][0]['Item']['rating']['N']}\n";

        $service->deleteItemByPartiQLBatch($statement, $parameters);
        echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n";

        echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n";
        $birthYear = "not a number";
        while (!is_numeric($birthYear) || $birthYear >= date("Y")) {
            $birthYear = testable_readline("Birth year: ");
        }
        $birthKey = [
            'Key' => [
                'year' => [
                    'N' => "$birthYear",
                ],
            ],
        ];
        $result = $service->query($tableName, $birthKey);
        $marshal = new Marshaler();
        echo "Here are the movies in our collection released the year you were born:\n";
        $oops = "Oops! There were no movies released in that year (that we know of).\n";
        $display = "";
        foreach ($result['Items'] as $movie) {
            $movie = $marshal->unmarshalItem($movie);
            $display .= $movie['title'] . "\n";
        }
        echo ($display) ?: $oops;

        $yearsKey = [
            'Key' => [
                'year' => [
                    'N' => [
                        'minRange' => 1990,
                        'maxRange' => 1999,
                    ],
                ],
            ],
        ];
        $filter = "year between 1990 and 1999";
        echo "\nHere's a list of all the movies released in the 90s:\n";
        $result = $service->scan($tableName, $yearsKey, $filter);
        foreach ($result['Items'] as $movie) {
            $movie = $marshal->unmarshalItem($movie);
            echo $movie['title'] . "\n";
        }

        echo "\nCleaning up this demo by deleting table $tableName...\n";
        $service->deleteTable($tableName);
    }
}

    public function insertItemByPartiQLBatch(string $statement, array $parameters)
    {
        $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => [
                [
                    'Statement' => "$statement",
                    'Parameters' => $parameters,
                ],
            ],
        ]);
    }

    public function getItemByPartiQLBatch(string $tableName, array $keys): Result
    {
        $statements = [];
        foreach ($keys as $key) {
            list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']);
            $statements[] = [
                'Statement' => "$statement",
                'Parameters' => $parameters,
            ];
        }

        return $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => $statements,
        ]);
    }

    public function updateItemByPartiQLBatch(string $statement, array $parameters)
    {
        $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => [
                [
                    'Statement' => "$statement",
                    'Parameters' => $parameters,
                ],
            ],
        ]);
    }

    public function deleteItemByPartiQLBatch(string $statement, array $parameters)
    {
        $this->dynamoDbClient->batchExecuteStatement([
            'Statements' => [
                [
                    'Statement' => "$statement",
                    'Parameters' => $parameters,
                ],
            ],
        ]);
    }
```
+  API の詳細については、「AWS SDK for PHP API リファレンス」**の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_php_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
namespace DynamoDb\PartiQL_Basics;

use Aws\DynamoDb\Marshaler;
use DynamoDb;
use DynamoDb\DynamoDBAttribute;

use function AwsUtilities\testable_readline;
use function AwsUtilities\loadMovieData;

class GettingStartedWithPartiQL
{
    public function run()
    {
        echo("\n");
        echo("--------------------------------------\n");
        print("Welcome to the Amazon DynamoDB - PartiQL getting started demo using PHP!\n");
        echo("--------------------------------------\n");

        $uuid = uniqid();
        $service = new DynamoDb\DynamoDBService();

        $tableName = "partiql_demo_table_$uuid";
        $service->createTable(
            $tableName,
            [
                new DynamoDBAttribute('year', 'N', 'HASH'),
                new DynamoDBAttribute('title', 'S', 'RANGE')
            ]
        );

        echo "Waiting for table...";
        $service->dynamoDbClient->waitUntil("TableExists", ['TableName' => $tableName]);
        echo "table $tableName found!\n";

        echo "What's the name of the last movie you watched?\n";
        while (empty($movieName)) {
            $movieName = testable_readline("Movie name: ");
        }
        echo "And what year was it released?\n";
        $movieYear = "year";
        while (!is_numeric($movieYear) || intval($movieYear) != $movieYear) {
            $movieYear = testable_readline("Year released: ");
        }
        $key = [
            'Item' => [
                'year' => [
                    'N' => "$movieYear",
                ],
                'title' => [
                    'S' => $movieName,
                ],
            ],
        ];
        list($statement, $parameters) = $service->buildStatementAndParameters("INSERT", $tableName, $key);
        $service->insertItemByPartiQL($statement, $parameters);

        echo "How would you rate the movie from 1-10?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        echo "What was the movie about?\n";
        while (empty($plot)) {
            $plot = testable_readline("Plot summary: ");
        }
        $attributes = [
            new DynamoDBAttribute('rating', 'N', 'HASH', $rating),
            new DynamoDBAttribute('plot', 'S', 'RANGE', $plot),
        ];

        list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes);
        $service->updateItemByPartiQL($statement, $parameters);
        echo "Movie added and updated.\n";



        $batch = json_decode(loadMovieData());

        $service->writeBatch($tableName, $batch);

        $movie = $service->getItemByPartiQL($tableName, $key);
        echo "\nThe movie {$movie['Items'][0]['title']['S']} was released in {$movie['Items'][0]['year']['N']}.\n";
        echo "What rating would you like to give {$movie['Items'][0]['title']['S']}?\n";
        $rating = 0;
        while (!is_numeric($rating) || intval($rating) != $rating || $rating < 1 || $rating > 10) {
            $rating = testable_readline("Rating (1-10): ");
        }
        $attributes = [
            new DynamoDBAttribute('rating', 'N', 'HASH', $rating),
            new DynamoDBAttribute('plot', 'S', 'RANGE', $plot)
        ];
        list($statement, $parameters) = $service->buildStatementAndParameters("UPDATE", $tableName, $key, $attributes);
        $service->updateItemByPartiQL($statement, $parameters);

        $movie = $service->getItemByPartiQL($tableName, $key);
        echo "Okay, you have rated {$movie['Items'][0]['title']['S']} as a {$movie['Items'][0]['rating']['N']}\n";

        $service->deleteItemByPartiQL($statement, $parameters);
        echo "But, bad news, this was a trap. That movie has now been deleted because of your rating...harsh.\n";

        echo "That's okay though. The book was better. Now, for something lighter, in what year were you born?\n";
        $birthYear = "not a number";
        while (!is_numeric($birthYear) || $birthYear >= date("Y")) {
            $birthYear = testable_readline("Birth year: ");
        }
        $birthKey = [
            'Key' => [
                'year' => [
                    'N' => "$birthYear",
                ],
            ],
        ];
        $result = $service->query($tableName, $birthKey);
        $marshal = new Marshaler();
        echo "Here are the movies in our collection released the year you were born:\n";
        $oops = "Oops! There were no movies released in that year (that we know of).\n";
        $display = "";
        foreach ($result['Items'] as $movie) {
            $movie = $marshal->unmarshalItem($movie);
            $display .= $movie['title'] . "\n";
        }
        echo ($display) ?: $oops;

        $yearsKey = [
            'Key' => [
                'year' => [
                    'N' => [
                        'minRange' => 1990,
                        'maxRange' => 1999,
                    ],
                ],
            ],
        ];
        $filter = "year between 1990 and 1999";
        echo "\nHere's a list of all the movies released in the 90s:\n";
        $result = $service->scan($tableName, $yearsKey, $filter);
        foreach ($result['Items'] as $movie) {
            $movie = $marshal->unmarshalItem($movie);
            echo $movie['title'] . "\n";
        }

        echo "\nCleaning up this demo by deleting table $tableName...\n";
        $service->deleteTable($tableName);
    }
}

    public function insertItemByPartiQL(string $statement, array $parameters)
    {
        $this->dynamoDbClient->executeStatement([
            'Statement' => "$statement",
            'Parameters' => $parameters,
        ]);
    }

    public function getItemByPartiQL(string $tableName, array $key): Result
    {
        list($statement, $parameters) = $this->buildStatementAndParameters("SELECT", $tableName, $key['Item']);

        return $this->dynamoDbClient->executeStatement([
            'Parameters' => $parameters,
            'Statement' => $statement,
        ]);
    }

    public function updateItemByPartiQL(string $statement, array $parameters)
    {
        $this->dynamoDbClient->executeStatement([
            'Statement' => $statement,
            'Parameters' => $parameters,
        ]);
    }

    public function deleteItemByPartiQL(string $statement, array $parameters)
    {
        $this->dynamoDbClient->executeStatement([
            'Statement' => $statement,
            'Parameters' => $parameters,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForPHPV3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_php_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での DynamoDB イベントの消費。  

```
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\DynamoDb\DynamoDbEvent;
use Bref\Event\DynamoDb\DynamoDbHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends DynamoDbHandler
{
    private StderrLogger $logger;

    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handleDynamoDb(DynamoDbEvent $event, Context $context): void
    {
        $this->logger->info("Processing DynamoDb table items");
        $records = $event->getRecords();

        foreach ($records as $record) {
            $eventName = $record->getEventName();
            $keys = $record->getKeys();
            $old = $record->getOldImage();
            $new = $record->getNewImage();
            
            $this->logger->info("Event Name:".$eventName."\n");
            $this->logger->info("Keys:". json_encode($keys)."\n");
            $this->logger->info("Old Image:". json_encode($old)."\n");
            $this->logger->info("New Image:". json_encode($new));
            
            // TODO: Do interesting work based on the new data

            // Any exception thrown will be logged and the invocation will be marked as failed
        }

        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords items");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_php_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での DynamoDB バッチ項目失敗のレポート。  

```
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\DynamoDb\DynamoDbEvent;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handle(mixed $event, Context $context): array
    {
        $dynamoDbEvent = new DynamoDbEvent($event);
        $this->logger->info("Processing records");

        $records = $dynamoDbEvent->getRecords();
        $failedRecords = [];
        foreach ($records as $record) {
            try {
                $data = $record->getData();
                $this->logger->info(json_encode($data));
                // TODO: Do interesting work based on the new data
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
                // failed processing the record
                $failedRecords[] = $record->getSequenceNumber();
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");

        // change format for the response
        $failures = array_map(
            fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber],
            $failedRecords
        );

        return [
            'batchItemFailures' => $failures
        ];
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

# SDK for PHP を使用した Amazon EC2 の例
<a name="php_3_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateVpc`
<a name="ec2_CreateVpc_php_3_topic"></a>

次のコード例は、`CreateVpc` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * @param string $cidr
     * @return array
     */
    public function createVpc(string $cidr): array
    {
        try {
            $result = $this->ec2Client->createVpc([
                "CidrBlock" => $cidr,
            ]);
            return $result['Vpc'];
        }catch(Ec2Exception $caught){
            echo "There was a problem creating the VPC: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[CreateVpc](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/CreateVpc)」を参照してください。

### `CreateVpcEndpoint`
<a name="ec2_CreateVpcEndpoint_php_3_topic"></a>

次のコード例は、`CreateVpcEndpoint` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * @param string $serviceName
     * @param string $vpcId
     * @param array $routeTableIds
     * @return array
     */
    public function createVpcEndpoint(string $serviceName, string $vpcId, array $routeTableIds): array
    {
        try {
            $result = $this->ec2Client->createVpcEndpoint([
                'ServiceName' => $serviceName,
                'VpcId' => $vpcId,
                'RouteTableIds' => $routeTableIds,
            ]);

            return $result["VpcEndpoint"];
        } catch(Ec2Exception $caught){
            echo "There was a problem creating the VPC Endpoint: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[CreateVpcEndpoint](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/CreateVpcEndpoint)」を参照してください。

### `DeleteVpc`
<a name="ec2_DeleteVpc_php_3_topic"></a>

次のコード例は、`DeleteVpc` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * @param string $vpcId
     * @return void
     */
    public function deleteVpc(string $vpcId)
    {
        try {
            $this->ec2Client->deleteVpc([
                "VpcId" => $vpcId,
            ]);
        }catch(Ec2Exception $caught){
            echo "There was a problem deleting the VPC: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[DeleteVpc](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/DeleteVpc)」を参照してください。**

### `DeleteVpcEndpoints`
<a name="ec2_DeleteVpcEndpoints_php_3_topic"></a>

次のコード例は、`DeleteVpcEndpoints` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * @param string $vpcEndpointId
     * @return void
     */
    public function deleteVpcEndpoint(string $vpcEndpointId)
    {
        try {
            $this->ec2Client->deleteVpcEndpoints([
                "VpcEndpointIds" => [$vpcEndpointId],
            ]);
        }catch (Ec2Exception $caught){
            echo "There was a problem deleting the VPC Endpoint: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteVpcEndpoints](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/DeleteVpcEndpoints)」を参照してください。

### `DescribeRouteTables`
<a name="ec2_DescribeRouteTables_php_3_topic"></a>

次のコード例は、`DescribeRouteTables` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * @param array $routeTableIds
     * @param array $filters
     * @return array
     */
    public function describeRouteTables(array $routeTableIds = [], array $filters = []): array
    {
        $parameters = [];
        if($routeTableIds){
            $parameters['RouteTableIds'] = $routeTableIds;
        }
        if($filters){
            $parameters['Filters'] = $filters;
        }
        try {
            $paginator = $this->ec2Client->getPaginator("DescribeRouteTables", $parameters);
            $contents = [];
            foreach ($paginator as $result) {
                foreach ($result['RouteTables'] as $object) {
                    $contents[] = $object['RouteTableId'];
                }
            }
        }catch (Ec2Exception $caught){
            echo "There was a problem paginating the results of DescribeRouteTables: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
        return $contents;
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DescribeRouteTables](https://docs.aws.amazon.com/goto/SdkForPHPV3/ec2-2016-11-15/DescribeRouteTables)」を参照してください。

# AWS Glue SDK for PHP を使用した の例
<a name="php_3_glue_code_examples"></a>

次のコード例は、 AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_php_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
namespace Glue;

use Aws\Glue\GlueClient;
use Aws\S3\S3Client;
use AwsUtilities\AWSServiceClass;
use GuzzleHttp\Psr7\Stream;
use Iam\IAMService;

class GettingStartedWithGlue
{
    public function run()
    {
        echo("\n");
        echo("--------------------------------------\n");
        print("Welcome to the AWS Glue getting started demo using PHP!\n");
        echo("--------------------------------------\n");

        $clientArgs = [
            'region' => 'us-west-2',
            'version' => 'latest',
            'profile' => 'default',
        ];
        $uniqid = uniqid();

        $glueClient = new GlueClient($clientArgs);
        $glueService = new GlueService($glueClient);
        $iamService = new IAMService();
        $crawlerName = "example-crawler-test-" . $uniqid;

        AWSServiceClass::$waitTime = 5;
        AWSServiceClass::$maxWaitAttempts = 20;

        $role = $iamService->getRole("AWSGlueServiceRole-DocExample");

        $databaseName = "doc-example-database-$uniqid";
        $path = 's3://crawler-public-us-east-1/flight/2016/csv';
        $glueService->createCrawler($crawlerName, $role['Role']['Arn'], $databaseName, $path);
        $glueService->startCrawler($crawlerName);

        echo "Waiting for crawler";
        do {
            $crawler = $glueService->getCrawler($crawlerName);
            echo ".";
            sleep(10);
        } while ($crawler['Crawler']['State'] != "READY");
        echo "\n";

        $database = $glueService->getDatabase($databaseName);
        echo "Found a database named " . $database['Database']['Name'] . "\n";

        //Upload job script
        $s3client = new S3Client($clientArgs);
        $bucketName = "test-glue-bucket-" . $uniqid;
        $s3client->createBucket([
            'Bucket' => $bucketName,
            'CreateBucketConfiguration' => ['LocationConstraint' => 'us-west-2'],
        ]);

        $s3client->putObject([
            'Bucket' => $bucketName,
            'Key' => 'run_job.py',
            'SourceFile' => __DIR__ . '/flight_etl_job_script.py'
        ]);
        $s3client->putObject([
            'Bucket' => $bucketName,
            'Key' => 'setup_scenario_getting_started.yaml',
            'SourceFile' => __DIR__ . '/setup_scenario_getting_started.yaml'
        ]);

        $tables = $glueService->getTables($databaseName);

        $jobName = 'test-job-' . $uniqid;
        $scriptLocation = "s3://$bucketName/run_job.py";
        $job = $glueService->createJob($jobName, $role['Role']['Arn'], $scriptLocation);

        $outputBucketUrl = "s3://$bucketName";
        $runId = $glueService->startJobRun($jobName, $databaseName, $tables, $outputBucketUrl)['JobRunId'];

        echo "waiting for job";
        do {
            $jobRun = $glueService->getJobRun($jobName, $runId);
            echo ".";
            sleep(10);
        } while (!array_intersect([$jobRun['JobRun']['JobRunState']], ['SUCCEEDED', 'STOPPED', 'FAILED', 'TIMEOUT']));
        echo "\n";

        $jobRuns = $glueService->getJobRuns($jobName);

        $objects = $s3client->listObjects([
            'Bucket' => $bucketName,
        ])['Contents'];

        foreach ($objects as $object) {
            echo $object['Key'] . "\n";
        }

        echo "Downloading " . $objects[1]['Key'] . "\n";
        /** @var Stream $downloadObject */
        $downloadObject = $s3client->getObject([
            'Bucket' => $bucketName,
            'Key' => $objects[1]['Key'],
        ])['Body']->getContents();
        echo "Here is the first 1000 characters in the object.";
        echo substr($downloadObject, 0, 1000);

        $jobs = $glueService->listJobs();
        echo "Current jobs:\n";
        foreach ($jobs['JobNames'] as $jobsName) {
            echo "{$jobsName}\n";
        }

        echo "Delete the job.\n";
        $glueClient->deleteJob([
            'JobName' => $job['Name'],
        ]);

        echo "Delete the tables.\n";
        foreach ($tables['TableList'] as $table) {
            $glueService->deleteTable($table['Name'], $databaseName);
        }

        echo "Delete the databases.\n";
        $glueClient->deleteDatabase([
            'Name' => $databaseName,
        ]);

        echo "Delete the crawler.\n";
        $glueClient->deleteCrawler([
            'Name' => $crawlerName,
        ]);

        $deleteObjects = $s3client->listObjectsV2([
            'Bucket' => $bucketName,
        ]);
        echo "Delete all objects in the bucket.\n";
        $deleteObjects = $s3client->deleteObjects([
            'Bucket' => $bucketName,
            'Delete' => [
                'Objects' => $deleteObjects['Contents'],
            ]
        ]);
        echo "Delete the bucket.\n";
        $s3client->deleteBucket(['Bucket' => $bucketName]);

        echo "This job was brought to you by the number $uniqid\n";
    }
}

namespace Glue;

use Aws\Glue\GlueClient;
use Aws\Result;

use function PHPUnit\Framework\isEmpty;

class GlueService extends \AwsUtilities\AWSServiceClass
{
    protected GlueClient $glueClient;

    public function __construct($glueClient)
    {
        $this->glueClient = $glueClient;
    }

    public function getCrawler($crawlerName)
    {
        return $this->customWaiter(function () use ($crawlerName) {
            return $this->glueClient->getCrawler([
                'Name' => $crawlerName,
            ]);
        });
    }

    public function createCrawler($crawlerName, $role, $databaseName, $path): Result
    {
        return $this->customWaiter(function () use ($crawlerName, $role, $databaseName, $path) {
            return $this->glueClient->createCrawler([
                'Name' => $crawlerName,
                'Role' => $role,
                'DatabaseName' => $databaseName,
                'Targets' => [
                    'S3Targets' =>
                        [[
                            'Path' => $path,
                        ]]
                ],
            ]);
        });
    }

    public function startCrawler($crawlerName): Result
    {
        return $this->glueClient->startCrawler([
            'Name' => $crawlerName,
        ]);
    }

    public function getDatabase(string $databaseName): Result
    {
        return $this->customWaiter(function () use ($databaseName) {
            return $this->glueClient->getDatabase([
                'Name' => $databaseName,
            ]);
        });
    }

    public function getTables($databaseName): Result
    {
        return $this->glueClient->getTables([
            'DatabaseName' => $databaseName,
        ]);
    }

    public function createJob($jobName, $role, $scriptLocation, $pythonVersion = '3', $glueVersion = '3.0'): Result
    {
        return $this->glueClient->createJob([
            'Name' => $jobName,
            'Role' => $role,
            'Command' => [
                'Name' => 'glueetl',
                'ScriptLocation' => $scriptLocation,
                'PythonVersion' => $pythonVersion,
            ],
            'GlueVersion' => $glueVersion,
        ]);
    }

    public function startJobRun($jobName, $databaseName, $tables, $outputBucketUrl): Result
    {
        return $this->glueClient->startJobRun([
            'JobName' => $jobName,
            'Arguments' => [
                'input_database' => $databaseName,
                'input_table' => $tables['TableList'][0]['Name'],
                'output_bucket_url' => $outputBucketUrl,
                '--input_database' => $databaseName,
                '--input_table' => $tables['TableList'][0]['Name'],
                '--output_bucket_url' => $outputBucketUrl,
            ],
        ]);
    }

    public function listJobs($maxResults = null, $nextToken = null, $tags = []): Result
    {
        $arguments = [];
        if ($maxResults) {
            $arguments['MaxResults'] = $maxResults;
        }
        if ($nextToken) {
            $arguments['NextToken'] = $nextToken;
        }
        if (!empty($tags)) {
            $arguments['Tags'] = $tags;
        }
        return $this->glueClient->listJobs($arguments);
    }

    public function getJobRuns($jobName, $maxResults = 0, $nextToken = ''): Result
    {
        $arguments = ['JobName' => $jobName];
        if ($maxResults) {
            $arguments['MaxResults'] = $maxResults;
        }
        if ($nextToken) {
            $arguments['NextToken'] = $nextToken;
        }
        return $this->glueClient->getJobRuns($arguments);
    }

    public function getJobRun($jobName, $runId, $predecessorsIncluded = false): Result
    {
        return $this->glueClient->getJobRun([
            'JobName' => $jobName,
            'RunId' => $runId,
            'PredecessorsIncluded' => $predecessorsIncluded,
        ]);
    }

    public function deleteJob($jobName)
    {
        return $this->glueClient->deleteJob([
            'JobName' => $jobName,
        ]);
    }

    public function deleteTable($tableName, $databaseName)
    {
        return $this->glueClient->deleteTable([
            'DatabaseName' => $databaseName,
            'Name' => $tableName,
        ]);
    }

    public function deleteDatabase($databaseName)
    {
        return $this->glueClient->deleteDatabase([
            'Name' => $databaseName,
        ]);
    }

    public function deleteCrawler($crawlerName)
    {
        return $this->glueClient->deleteCrawler([
            'Name' => $crawlerName,
        ]);
    }
}
```
+ API の詳細については、「*AWS SDK for PHP API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/CreateCrawler)
  + [CreateJob](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/CreateJob)
  + [DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteCrawler)
  + [DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteDatabase)
  + [DeleteJob](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteJob)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteTable)
  + [GetCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetCrawler)
  + [GetDatabase](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetDatabase)
  + [GetDatabases](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetDatabases)
  + [GetJob](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetJob)
  + [GetJobRun](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetJobRun)
  + [GetJobRuns](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetJobRuns)
  + [GetTables](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetTables)
  + [ListJobs](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/ListJobs)
  + [StartCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/StartCrawler)
  + [StartJobRun](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/StartJobRun)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_php_3_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $crawlerName = "example-crawler-test-" . $uniqid;

        $role = $iamService->getRole("AWSGlueServiceRole-DocExample");

        $path = 's3://crawler-public-us-east-1/flight/2016/csv';
        $glueService->createCrawler($crawlerName, $role['Role']['Arn'], $databaseName, $path);

    public function createCrawler($crawlerName, $role, $databaseName, $path): Result
    {
        return $this->customWaiter(function () use ($crawlerName, $role, $databaseName, $path) {
            return $this->glueClient->createCrawler([
                'Name' => $crawlerName,
                'Role' => $role,
                'DatabaseName' => $databaseName,
                'Targets' => [
                    'S3Targets' =>
                        [[
                            'Path' => $path,
                        ]]
                ],
            ]);
        });
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[CreateCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/CreateCrawler)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_php_3_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $role = $iamService->getRole("AWSGlueServiceRole-DocExample");

        $jobName = 'test-job-' . $uniqid;

        $scriptLocation = "s3://$bucketName/run_job.py";
        $job = $glueService->createJob($jobName, $role['Role']['Arn'], $scriptLocation);

    public function createJob($jobName, $role, $scriptLocation, $pythonVersion = '3', $glueVersion = '3.0'): Result
    {
        return $this->glueClient->createJob([
            'Name' => $jobName,
            'Role' => $role,
            'Command' => [
                'Name' => 'glueetl',
                'ScriptLocation' => $scriptLocation,
                'PythonVersion' => $pythonVersion,
            ],
            'GlueVersion' => $glueVersion,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[CreateJob](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/CreateJob)」を参照してください。**

### `DeleteCrawler`
<a name="glue_DeleteCrawler_php_3_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        echo "Delete the crawler.\n";
        $glueClient->deleteCrawler([
            'Name' => $crawlerName,
        ]);

    public function deleteCrawler($crawlerName)
    {
        return $this->glueClient->deleteCrawler([
            'Name' => $crawlerName,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteCrawler)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_php_3_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        echo "Delete the databases.\n";
        $glueClient->deleteDatabase([
            'Name' => $databaseName,
        ]);

    public function deleteDatabase($databaseName)
    {
        return $this->glueClient->deleteDatabase([
            'Name' => $databaseName,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteDatabase)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_php_3_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        echo "Delete the job.\n";
        $glueClient->deleteJob([
            'JobName' => $job['Name'],
        ]);

    public function deleteJob($jobName)
    {
        return $this->glueClient->deleteJob([
            'JobName' => $jobName,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteJob](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteJob)」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_php_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        echo "Delete the tables.\n";
        foreach ($tables['TableList'] as $table) {
            $glueService->deleteTable($table['Name'], $databaseName);
        }

    public function deleteTable($tableName, $databaseName)
    {
        return $this->glueClient->deleteTable([
            'DatabaseName' => $databaseName,
            'Name' => $tableName,
        ]);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/DeleteTable)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_php_3_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        echo "Waiting for crawler";
        do {
            $crawler = $glueService->getCrawler($crawlerName);
            echo ".";
            sleep(10);
        } while ($crawler['Crawler']['State'] != "READY");
        echo "\n";

    public function getCrawler($crawlerName)
    {
        return $this->customWaiter(function () use ($crawlerName) {
            return $this->glueClient->getCrawler([
                'Name' => $crawlerName,
            ]);
        });
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetCrawler)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_php_3_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $databaseName = "doc-example-database-$uniqid";

        $database = $glueService->getDatabase($databaseName);
        echo "Found a database named " . $database['Database']['Name'] . "\n";

    public function getDatabase(string $databaseName): Result
    {
        return $this->customWaiter(function () use ($databaseName) {
            return $this->glueClient->getDatabase([
                'Name' => $databaseName,
            ]);
        });
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetDatabase](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetDatabase)」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_php_3_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $jobName = 'test-job-' . $uniqid;

        $outputBucketUrl = "s3://$bucketName";
        $runId = $glueService->startJobRun($jobName, $databaseName, $tables, $outputBucketUrl)['JobRunId'];

        echo "waiting for job";
        do {
            $jobRun = $glueService->getJobRun($jobName, $runId);
            echo ".";
            sleep(10);
        } while (!array_intersect([$jobRun['JobRun']['JobRunState']], ['SUCCEEDED', 'STOPPED', 'FAILED', 'TIMEOUT']));
        echo "\n";

    public function getJobRun($jobName, $runId, $predecessorsIncluded = false): Result
    {
        return $this->glueClient->getJobRun([
            'JobName' => $jobName,
            'RunId' => $runId,
            'PredecessorsIncluded' => $predecessorsIncluded,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetJobRun](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetJobRun)」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_php_3_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $jobName = 'test-job-' . $uniqid;

        $jobRuns = $glueService->getJobRuns($jobName);

    public function getJobRuns($jobName, $maxResults = 0, $nextToken = ''): Result
    {
        $arguments = ['JobName' => $jobName];
        if ($maxResults) {
            $arguments['MaxResults'] = $maxResults;
        }
        if ($nextToken) {
            $arguments['NextToken'] = $nextToken;
        }
        return $this->glueClient->getJobRuns($arguments);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetJobRuns](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetJobRuns)」を参照してください。

### `GetTables`
<a name="glue_GetTables_php_3_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $databaseName = "doc-example-database-$uniqid";

        $tables = $glueService->getTables($databaseName);

    public function getTables($databaseName): Result
    {
        return $this->glueClient->getTables([
            'DatabaseName' => $databaseName,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetTables](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/GetTables)」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_php_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $jobs = $glueService->listJobs();
        echo "Current jobs:\n";
        foreach ($jobs['JobNames'] as $jobsName) {
            echo "{$jobsName}\n";
        }

    public function listJobs($maxResults = null, $nextToken = null, $tags = []): Result
    {
        $arguments = [];
        if ($maxResults) {
            $arguments['MaxResults'] = $maxResults;
        }
        if ($nextToken) {
            $arguments['NextToken'] = $nextToken;
        }
        if (!empty($tags)) {
            $arguments['Tags'] = $tags;
        }
        return $this->glueClient->listJobs($arguments);
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/ListJobs)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_php_3_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $crawlerName = "example-crawler-test-" . $uniqid;

        $databaseName = "doc-example-database-$uniqid";

        $glueService->startCrawler($crawlerName);

    public function startCrawler($crawlerName): Result
    {
        return $this->glueClient->startCrawler([
            'Name' => $crawlerName,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[StartCrawler](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/StartCrawler)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_php_3_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
        $jobName = 'test-job-' . $uniqid;

        $databaseName = "doc-example-database-$uniqid";

        $tables = $glueService->getTables($databaseName);

        $outputBucketUrl = "s3://$bucketName";
        $runId = $glueService->startJobRun($jobName, $databaseName, $tables, $outputBucketUrl)['JobRunId'];

    public function startJobRun($jobName, $databaseName, $tables, $outputBucketUrl): Result
    {
        return $this->glueClient->startJobRun([
            'JobName' => $jobName,
            'Arguments' => [
                'input_database' => $databaseName,
                'input_table' => $tables['TableList'][0]['Name'],
                'output_bucket_url' => $outputBucketUrl,
                '--input_database' => $databaseName,
                '--input_table' => $tables['TableList'][0]['Name'],
                '--output_bucket_url' => $outputBucketUrl,
            ],
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[StartJobRun](https://docs.aws.amazon.com/goto/SdkForPHPV3/glue-2017-03-31/StartJobRun)」を参照してください。

# SDK for PHP を使用した IAM の例
<a name="php_3_iam_code_examples"></a>

次のコード例は、IAM AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_php_3_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
namespace Iam\Basics;

require 'vendor/autoload.php';

use Aws\Credentials\Credentials;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use Aws\Sts\StsClient;
use Iam\IAMService;

echo("\n");
echo("--------------------------------------\n");
print("Welcome to the IAM getting started demo using PHP!\n");
echo("--------------------------------------\n");

$uuid = uniqid();
$service = new IAMService();

$user = $service->createUser("iam_demo_user_$uuid");
echo "Created user with the arn: {$user['Arn']}\n";

$key = $service->createAccessKey($user['UserName']);
$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";

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

$service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);

$inlinePolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{$assumeRoleRole['Arn']}\"}]
}";
$inlinePolicy = $service->createUserPolicy("iam_demo_inline_policy_$uuid", $inlinePolicyDocument, $user['UserName']);
//First, fail to list the buckets with the user
$credentials = new Credentials($key['AccessKeyId'], $key['SecretAccessKey']);
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
try {
    $s3Client->listBuckets([
    ]);
    echo "this should not run";
} catch (S3Exception $exception) {
    echo "successfully failed!\n";
}

$stsClient = new StsClient(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $credentials]);
sleep(10);
$assumedRole = $stsClient->assumeRole([
    'RoleArn' => $assumeRoleRole['Arn'],
    'RoleSessionName' => "DemoAssumeRoleSession_$uuid",
]);
$assumedCredentials = [
    'key' => $assumedRole['Credentials']['AccessKeyId'],
    'secret' => $assumedRole['Credentials']['SecretAccessKey'],
    'token' => $assumedRole['Credentials']['SessionToken'],
];
$s3Client = new S3Client(['region' => 'us-west-2', 'version' => 'latest', 'credentials' => $assumedCredentials]);
try {
    $s3Client->listBuckets([]);
    echo "this should now run!\n";
} catch (S3Exception $exception) {
    echo "this should now not fail\n";
}

$service->detachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);
$deletePolicy = $service->deletePolicy($listAllBucketsPolicy['Arn']);
echo "Delete policy: {$listAllBucketsPolicy['PolicyName']}\n";
$deletedRole = $service->deleteRole($assumeRoleRole['Arn']);
echo "Deleted role: {$assumeRoleRole['RoleName']}\n";
$deletedKey = $service->deleteAccessKey($key['AccessKeyId'], $user['UserName']);
$deletedUser = $service->deleteUser($user['UserName']);
echo "Delete user: {$user['UserName']}\n";
```
+ API の詳細については、「*AWS SDK for PHP API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_php_3_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$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";

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

$service->attachRolePolicy($assumeRoleRole['RoleName'], $listAllBucketsPolicy['Arn']);

    public function attachRolePolicy($roleName, $policyArn)
    {
        return $this->customWaiter(function () use ($roleName, $policyArn) {
            $this->iamClient->attachRolePolicy([
                'PolicyArn' => $policyArn,
                'RoleName' => $roleName,
            ]);
        });
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/AttachRolePolicy)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_php_3_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

$listAllBucketsPolicyDocument = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
}";
$listAllBucketsPolicy = $service->createPolicy("iam_demo_policy_$uuid", $listAllBucketsPolicyDocument);
echo "Created policy: {$listAllBucketsPolicy['PolicyName']}\n";

    /**
     * @param string $policyName
     * @param string $policyDocument
     * @return array
     */
    public function createPolicy(string $policyName, string $policyDocument)
    {
        $result = $this->customWaiter(function () use ($policyName, $policyDocument) {
            return $this->iamClient->createPolicy([
                'PolicyName' => $policyName,
                'PolicyDocument' => $policyDocument,
            ]);
        });
        return $result['Policy'];
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_php_3_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$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](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateRole)」を参照してください。**

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_php_3_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function createServiceLinkedRole($awsServiceName, $customSuffix = "", $description = "")
    {
        $createServiceLinkedRoleArguments = ['AWSServiceName' => $awsServiceName];
        if ($customSuffix) {
            $createServiceLinkedRoleArguments['CustomSuffix'] = $customSuffix;
        }
        if ($description) {
            $createServiceLinkedRoleArguments['Description'] = $description;
        }
        return $this->iamClient->createServiceLinkedRole($createServiceLinkedRoleArguments);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateServiceLinkedRole)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_php_3_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

$user = $service->createUser("iam_demo_user_$uuid");
echo "Created user with the arn: {$user['Arn']}\n";


    /**
     * @param string $name
     * @return array
     * @throws AwsException
     */
    public function createUser(string $name): array
    {
        $result = $this->iamClient->createUser([
            'UserName' => $name,
        ]);

        return $result['User'];
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/CreateUser)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_php_3_topic"></a>

次のコード例は、`GetAccountPasswordPolicy` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function getAccountPasswordPolicy()
    {
        return $this->iamClient->getAccountPasswordPolicy();
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/GetAccountPasswordPolicy)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_php_3_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function getPolicy($policyArn)
    {
        return $this->customWaiter(function () use ($policyArn) {
            return $this->iamClient->getPolicy(['PolicyArn' => $policyArn]);
        });
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/GetPolicy)」を参照してください。

### `GetRole`
<a name="iam_GetRole_php_3_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function getRole($roleName)
    {
        return $this->customWaiter(function () use ($roleName) {
            return $this->iamClient->getRole(['RoleName' => $roleName]);
        });
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[GetRole](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/GetRole)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_php_3_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function listAttachedRolePolicies($roleName, $pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listAttachRolePoliciesArguments = ['RoleName' => $roleName];
        if ($pathPrefix) {
            $listAttachRolePoliciesArguments['PathPrefix'] = $pathPrefix;
        }
        if ($marker) {
            $listAttachRolePoliciesArguments['Marker'] = $marker;
        }
        if ($maxItems) {
            $listAttachRolePoliciesArguments['MaxItems'] = $maxItems;
        }
        return $this->iamClient->listAttachedRolePolicies($listAttachRolePoliciesArguments);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListAttachedRolePolicies)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_php_3_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function listGroups($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listGroupsArguments = [];
        if ($pathPrefix) {
            $listGroupsArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listGroupsArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listGroupsArguments["MaxItems"] = $maxItems;
        }

        return $this->iamClient->listGroups($listGroupsArguments);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListGroup](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListGroups)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_php_3_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function listPolicies($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listPoliciesArguments = [];
        if ($pathPrefix) {
            $listPoliciesArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listPoliciesArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listPoliciesArguments["MaxItems"] = $maxItems;
        }

        return $this->iamClient->listPolicies($listPoliciesArguments);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListPolicies)」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_php_3_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function listRolePolicies($roleName, $marker = "", $maxItems = 0)
    {
        $listRolePoliciesArguments = ['RoleName' => $roleName];
        if ($marker) {
            $listRolePoliciesArguments['Marker'] = $marker;
        }
        if ($maxItems) {
            $listRolePoliciesArguments['MaxItems'] = $maxItems;
        }
        return $this->customWaiter(function () use ($listRolePoliciesArguments) {
            return $this->iamClient->listRolePolicies($listRolePoliciesArguments);
        });
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListRolePolicies](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListRolePolicies)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_php_3_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    /**
     * @param string $pathPrefix
     * @param string $marker
     * @param int $maxItems
     * @return Result
     * $roles = $service->listRoles();
     */
    public function listRoles($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listRolesArguments = [];
        if ($pathPrefix) {
            $listRolesArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listRolesArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listRolesArguments["MaxItems"] = $maxItems;
        }
        return $this->iamClient->listRoles($listRolesArguments);
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListRoles](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListRoles)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_php_3_topic"></a>

次のコード例は、`ListSAMLProviders` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function listSAMLProviders()
    {
        return $this->iamClient->listSAMLProviders();
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListSAMLProviders](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListSAMLProviders)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_php_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
$uuid = uniqid();
$service = new IAMService();

    public function listUsers($pathPrefix = "", $marker = "", $maxItems = 0)
    {
        $listUsersArguments = [];
        if ($pathPrefix) {
            $listUsersArguments["PathPrefix"] = $pathPrefix;
        }
        if ($marker) {
            $listUsersArguments["Marker"] = $marker;
        }
        if ($maxItems) {
            $listUsersArguments["MaxItems"] = $maxItems;
        }

        return $this->iamClient->listUsers($listUsersArguments);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/SdkForPHPV3/iam-2010-05-08/ListUsers)」を参照してください。

# SDK for PHP を使用した Kinesis の例
<a name="php_3_kinesis_code_examples"></a>

次のコード例は、Kinesis AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_php_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Kinesis\KinesisEvent;
use Bref\Event\Kinesis\KinesisHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends KinesisHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handleKinesis(KinesisEvent $event, Context $context): void
    {
        $this->logger->info("Processing records");
        $records = $event->getRecords();
        foreach ($records as $record) {
            $data = $record->getData();
            $this->logger->info(json_encode($data));
            // TODO: Do interesting work based on the new data

            // Any exception thrown will be logged and the invocation will be marked as failed
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_php_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Kinesis\KinesisEvent;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handle(mixed $event, Context $context): array
    {
        $kinesisEvent = new KinesisEvent($event);
        $this->logger->info("Processing records");
        $records = $kinesisEvent->getRecords();

        $failedRecords = [];
        foreach ($records as $record) {
            try {
                $data = $record->getData();
                $this->logger->info(json_encode($data));
                // TODO: Do interesting work based on the new data
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
                // failed processing the record
                $failedRecords[] = $record->getSequenceNumber();
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");

        // change format for the response
        $failures = array_map(
            fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber],
            $failedRecords
        );

        return [
            'batchItemFailures' => $failures
        ];
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

# AWS KMS SDK for PHP を使用した の例
<a name="php_3_kms_code_examples"></a>

次のコード例は、 AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS KMSは
<a name="kms_Hello_php_3_topic"></a>

次のコード例は、 AWS Key Management Serviceの使用を開始する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
include "vendor/autoload.php";

use Aws\Kms\KmsClient;

echo "This file shows how to connect to the KmsClient, uses a paginator to get the keys for the account, and lists the KeyIds for up to 10 keys.\n";

$client = new KmsClient([]);

$pageLength = 10; // Change this value to change the number of records shown, or to break up the result into pages.

$keys = [];
$keysPaginator = $client->getPaginator("ListKeys", ['Limit' => $pageLength]);
foreach($keysPaginator as $page){
    foreach($page['Keys'] as $index => $key){
        echo "The $index index Key's ID is: {$key['KeyId']}\n";
    }
    echo "End of page one of results. Alter the \$pageLength variable to see more results.\n";
    break;
}
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListKeys](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ListKeys)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="kms_Scenario_Basics_php_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ KMS キーを作成します。
+ アカウントの KMS キーを一覧表示し、詳細を取得します。
+ KMS キーを有効および無効にします。
+ クライアント側の暗号化に使用できる対称データキーを生成します。
+ データのデジタル署名に使用する非対称キーを生成します。
+ キーをダグ付けします。
+ KMS キーを削除します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
        echo "\n";
        echo "--------------------------------------\n";
        echo <<<WELCOME
Welcome to the AWS Key Management Service SDK Basics scenario.
        
This program demonstrates how to interact with AWS Key Management Service using the AWS SDK for PHP (v3).
The AWS Key Management Service (KMS) is a secure and highly available service that allows you to create
and manage AWS KMS keys and control their use across a wide range of AWS services and applications.
KMS provides a centralized and unified approach to managing encryption keys, making it easier to meet your
data protection and regulatory compliance requirements.

This KMS Basics scenario creates two key types:
- A symmetric encryption key is used to encrypt and decrypt data.
- An asymmetric key used to digitally sign data.

Let's get started...\n
WELCOME;
        echo "--------------------------------------\n";
        $this->pressEnter();

        $this->kmsClient = new KmsClient([]);
        // Initialize the KmsService class with the client. This allows you to override any defaults in the client before giving it to the service class.
        $this->kmsService = new KmsService($this->kmsClient);

        // 1. Create a symmetric KMS key.
        echo "\n";
        echo "1. Create a symmetric KMS key.\n";
        echo "First, we will create a symmetric KMS key that is used to encrypt and decrypt data by invoking createKey().\n";
        $this->pressEnter();

        $key = $this->kmsService->createKey();
        $this->resources['symmetricKey'] = $key['KeyId'];
        echo "Created a customer key with ARN {$key['Arn']}.\n";
        $this->pressEnter();

        // 2. Enable a KMS key.
        echo "\n";
        echo "2. Enable a KMS key.\n";
        echo "By default when you create an AWS key, it is enabled. The code checks to
determine if the key is enabled. If it is not enabled, the code enables it.\n";
        $this->pressEnter();

        $keyInfo = $this->kmsService->describeKey($key['KeyId']);
        if(!$keyInfo['Enabled']){
            echo "The key was not enabled, so we will enable it.\n";
            $this->pressEnter();
            $this->kmsService->enableKey($key['KeyId']);
            echo "The key was successfully enabled.\n";
        }else{
            echo "The key was already enabled, so there was no need to enable it.\n";
        }
        $this->pressEnter();

        // 3. Encrypt data using the symmetric KMS key.
        echo "\n";
        echo "3. Encrypt data using the symmetric KMS key.\n";
        echo "One of the main uses of symmetric keys is to encrypt and decrypt data.\n";
        echo "Next, we'll encrypt the string 'Hello, AWS KMS!' with the SYMMETRIC_DEFAULT encryption algorithm.\n";
        $this->pressEnter();
        $text = "Hello, AWS KMS!";
        $encryption = $this->kmsService->encrypt($key['KeyId'], $text);
        echo "The plaintext data was successfully encrypted with the algorithm: {$encryption['EncryptionAlgorithm']}.\n";
        $this->pressEnter();

        // 4. Create an alias.
        echo "\n";
        echo "4. Create an alias.\n";
        $aliasInput = testable_readline("Please enter an alias prefixed with \"alias/\" or press enter to use a default value: ");
        if($aliasInput == ""){
            $aliasInput = "alias/dev-encryption-key";
        }
        $this->kmsService->createAlias($key['KeyId'], $aliasInput);
        $this->resources['alias'] = $aliasInput;
        echo "The alias \"$aliasInput\" was successfully created.\n";
        $this->pressEnter();

        // 5. List all of your aliases.
        $aliasPageSize = 10;
        echo "\n";
        echo "5. List all of your aliases, up to $aliasPageSize.\n";
        $this->pressEnter();
        $aliasPaginator = $this->kmsService->listAliases();
        foreach($aliasPaginator as $pages){
            foreach($pages['Aliases'] as $alias){
                echo $alias['AliasName'] . "\n";
            }
            break;
        }
        $this->pressEnter();

        // 6. Enable automatic rotation of the KMS key.
        echo "\n";
        echo "6. Enable automatic rotation of the KMS key.\n";
        echo "By default, when the SDK enables automatic rotation of a KMS key,
KMS rotates the key material of the KMS key one year (approximately 365 days) from the enable date and every year 
thereafter.";
        $this->pressEnter();
        $this->kmsService->enableKeyRotation($key['KeyId']);
        echo "The key's rotation was successfully set for key: {$key['KeyId']}\n";
        $this->pressEnter();

        // 7. Create a grant.
        echo "7. Create a grant.\n";
        echo "\n";
        echo "A grant is a policy instrument that allows Amazon Web Services principals to use KMS keys.
It also can allow them to view a KMS key (DescribeKey) and create and manage grants.
When authorizing access to a KMS key, grants are considered along with key policies and IAM policies.\n";
        $granteeARN = testable_readline("Please enter the Amazon Resource Name (ARN) of an Amazon Web Services principal. Valid principals include Amazon Web Services accounts, IAM users, IAM roles, federated users, and assumed role users. For help with the ARN syntax for a principal, see IAM ARNs in the Identity and Access Management User Guide. \nTo skip this step, press enter without any other values: ");
        if($granteeARN){
            $operations = [
                "ENCRYPT",
                "DECRYPT",
                "DESCRIBE_KEY",
            ];
            $grant = $this->kmsService->createGrant($key['KeyId'], $granteeARN, $operations);
            echo "The grant Id is: {$grant['GrantId']}\n";
        }else{
            echo "Steps 7, 8, and 9 will be skipped.\n";
        }
        $this->pressEnter();

        // 8. List grants for the KMS key.
        if($granteeARN){
            echo "8. List grants for the KMS key.\n\n";
            $grantsPaginator = $this->kmsService->listGrants($key['KeyId']);
            foreach($grantsPaginator as $page){
                foreach($page['Grants'] as $grant){
                    echo $grant['GrantId'] . "\n";
                }
            }
        }else{
            echo "Skipping step 8...\n";
        }
        $this->pressEnter();

        // 9. Revoke the grant.
        if($granteeARN) {
            echo "\n";
            echo "9. Revoke the grant.\n";
            $this->pressEnter();
            $this->kmsService->revokeGrant($grant['GrantId'], $keyInfo['KeyId']);
            echo "{$grant['GrantId']} was successfully revoked!\n";
        }else{
            echo "Skipping step 9...\n";
        }
        $this->pressEnter();

        // 10. Decrypt the data.
        echo "\n";
        echo "10. Decrypt the data.\n";
        echo "Let's decrypt the data that was encrypted before.\n";
        echo "We'll use the same key to decrypt the string that we encrypted earlier in the program.\n";
        $this->pressEnter();
        $decryption = $this->kmsService->decrypt($keyInfo['KeyId'], $encryption['CiphertextBlob'], $encryption['EncryptionAlgorithm']);
        echo "The decrypted text is: {$decryption['Plaintext']}\n";
        $this->pressEnter();

        // 11. Replace a Key Policy.
        echo "\n";
        echo "11. Replace a Key Policy.\n";
        echo "A key policy is a resource policy for a KMS key. Key policies are the primary way to control access to KMS keys.\n";
        echo "Every KMS key must have exactly one key policy. The statements in the key policy determine who has permission to use the KMS key and how they can use it.\n";
        echo " You can also use IAM policies and grants to control access to the KMS key, but every KMS key must have a key policy.\n";
        echo "We will replace the key's policy with a new one:\n";
        $stsClient = new StsClient([]);
        $result = $stsClient->getCallerIdentity();
        $accountId = $result['Account'];
        $keyPolicy = <<< KEYPOLICY
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [{
        "Effect": "Allow",
        "Principal": {"AWS": "arn:aws:iam::$accountId:root"},
        "Action": "kms:*",
        "Resource": "*"
    }]
}
KEYPOLICY;
        echo $keyPolicy;
        $this->pressEnter();
        $this->kmsService->putKeyPolicy($keyInfo['KeyId'], $keyPolicy);
        echo "The Key Policy was successfully replaced!\n";
        $this->pressEnter();

        // 12. Retrieve the key policy.
        echo "\n";
        echo "12. Retrieve the key policy.\n";
        echo "Let's get some information about the new policy and print it to the screen.\n";
        $this->pressEnter();
        $policyInfo = $this->kmsService->getKeyPolicy($keyInfo['KeyId']);
        echo "We got the info! Here is the policy: \n";
        echo $policyInfo['Policy'] . "\n";
        $this->pressEnter();

        // 13. Create an asymmetric KMS key and sign data.
        echo "\n";
        echo "13. Create an asymmetric KMS key and sign data.\n";
        echo "Signing your data with an AWS key can provide several benefits that make it an attractive option for your data signing needs.\n";
        echo "By using an AWS KMS key, you can leverage the security controls and compliance features provided by AWS, which can help you meet various regulatory requirements and enhance the overall security posture of your organization.\n";
        echo "First we'll create the asymmetric key.\n";
        $this->pressEnter();
        $keySpec = "RSA_2048";
        $keyUsage = "SIGN_VERIFY";
        $asymmetricKey = $this->kmsService->createKey($keySpec, $keyUsage);
        $this->resources['asymmetricKey'] = $asymmetricKey['KeyId'];
        echo "Created the key with ID: {$asymmetricKey['KeyId']}\n";
        echo "Next, we'll sign the data.\n";
        $this->pressEnter();
        $algorithm = "RSASSA_PSS_SHA_256";
        $sign = $this->kmsService->sign($asymmetricKey['KeyId'], $text, $algorithm);
        $verify = $this->kmsService->verify($asymmetricKey['KeyId'], $text, $sign['Signature'], $algorithm);
        echo "Signature verification result: {$sign['signature']}\n";
        $this->pressEnter();

        // 14. Tag the symmetric KMS key.
        echo "\n";
        echo "14. Tag the symmetric KMS key.\n";
        echo "By using tags, you can improve the overall management, security, and governance of your KMS keys, making it easier to organize, track, and control access to your encrypted data within your AWS environment.\n";
        echo "Let's tag our symmetric key as Environment->Production\n";
        $this->pressEnter();
        $this->kmsService->tagResource($key['KeyId'], [
            [
                'TagKey' => "Environment",
                'TagValue' => "Production",
            ],
        ]);
        echo "The key was successfully tagged!\n";
        $this->pressEnter();

        // 15. Schedule the deletion of the KMS key
        echo "\n";
        echo "15. Schedule the deletion of the KMS key.\n";
        echo "By default, KMS applies a waiting period of 30 days, but you can specify a waiting period of 7-30 days.\n";
        echo "When this operation is successful, the key state of the KMS key changes to PendingDeletion and the key can't be used in any cryptographic operations.\n";
        echo "It remains in this state for the duration of the waiting period.\n\n";

        echo "Deleting a KMS key is a destructive and potentially dangerous operation. When a KMS key is deleted, all data that was encrypted under the KMS key is unrecoverable.\n\n";

        $cleanUp = testable_readline("Would you like to delete the resources created during this scenario, including the keys? (y/n): ");
        if($cleanUp == "Y" || $cleanUp == "y"){
            $this->cleanUp();
        }

        echo "--------------------------------------------------------------------------------\n";
        echo "This concludes the AWS Key Management SDK Basics scenario\n";
        echo "--------------------------------------------------------------------------------\n";



namespace Kms;

use Aws\Kms\Exception\KmsException;
use Aws\Kms\KmsClient;
use Aws\Result;
use Aws\ResultPaginator;
use AwsUtilities\AWSServiceClass;

class KmsService extends AWSServiceClass
{

    protected KmsClient $client;
    protected bool $verbose;

    /***
     * @param KmsClient|null $client
     * @param bool $verbose
     */
    public function __construct(KmsClient $client = null, bool $verbose = false)
    {
        $this->verbose = $verbose;
        if($client){
            $this->client = $client;
            return;
        }
        $this->client = new KmsClient([]);
    }


    /***
     * @param string $keySpec
     * @param string $keyUsage
     * @param string $description
     * @return array
     */
    public function createKey(string $keySpec = "", string $keyUsage = "", string $description = "Created by the SDK for PHP")
    {
        $parameters = ['Description' => $description];
        if($keySpec && $keyUsage){
            $parameters['KeySpec'] = $keySpec;
            $parameters['KeyUsage'] = $keyUsage;
        }
        try {
            $result = $this->client->createKey($parameters);
            return $result['KeyMetadata'];
        }catch(KmsException $caught){
            // Check for error specific to createKey operations
            if ($caught->getAwsErrorMessage() == "LimitExceededException"){
                echo "The request was rejected because a quota was exceeded. For more information, see Quotas in the Key Management Service Developer Guide.";
            }
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param string $ciphertext
     * @param string $algorithm
     * @return Result
     */
    public function decrypt(string $keyId, string $ciphertext, string $algorithm = "SYMMETRIC_DEFAULT")
    {
        try{
            return $this->client->decrypt([
                'CiphertextBlob' => $ciphertext,
                'EncryptionAlgorithm' => $algorithm,
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem decrypting the data: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param string $text
     * @return Result
     */
    public function encrypt(string $keyId, string $text)
    {
        try {
            return $this->client->encrypt([
                'KeyId' => $keyId,
                'Plaintext' => $text,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "DisabledException"){
                echo "The request was rejected because the specified KMS key is not enabled.\n";
            }
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param int $limit
     * @return ResultPaginator
     */
    public function listAliases(string $keyId = "", int $limit = 0)
    {
        $args = [];
        if($keyId){
            $args['KeyId'] = $keyId;
        }
        if($limit){
            $args['Limit'] = $limit;
        }
        try{
            return $this->client->getPaginator("ListAliases", $args);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "InvalidMarkerException"){
                echo "The request was rejected because the marker that specifies where pagination should next begin is not valid.\n";
            }
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param string $alias
     * @return void
     */
    public function createAlias(string $keyId, string $alias)
    {
        try{
            $this->client->createAlias([
                'TargetKeyId' => $keyId,
                'AliasName' => $alias,
            ]);
        }catch (KmsException $caught){
            if($caught->getAwsErrorMessage() == "InvalidAliasNameException"){
                echo "The request was rejected because the specified alias name is not valid.";
            }
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param string $granteePrincipal
     * @param array $operations
     * @param array $grantTokens
     * @return Result
     */
    public function createGrant(string $keyId, string $granteePrincipal, array $operations, array $grantTokens = [])
    {
        $args = [
            'KeyId' => $keyId,
            'GranteePrincipal' => $granteePrincipal,
            'Operations' => $operations,
        ];
        if($grantTokens){
            $args['GrantTokens'] = $grantTokens;
        }
        try{
            return $this->client->createGrant($args);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "InvalidGrantTokenException"){
                echo "The request was rejected because the specified grant token is not valid.\n";
            }
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @return array
     */
    public function describeKey(string $keyId)
    {
        try {
            $result = $this->client->describeKey([
                "KeyId" => $keyId,
            ]);
            return $result['KeyMetadata'];
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @return void
     */
    public function disableKey(string $keyId)
    {
        try {
            $this->client->disableKey([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem disabling the key: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @return void
     */
    public function enableKey(string $keyId)
    {
        try {
            $this->client->enableKey([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }



    /***
     * @return array
     */
    public function listKeys()
    {
        try {
            $contents = [];
            $paginator = $this->client->getPaginator("ListKeys");
            foreach($paginator as $result){
                foreach ($result['Content'] as $object) {
                    $contents[] = $object;
                }
            }
            return $contents;
        }catch(KmsException $caught){
            echo "There was a problem listing the keys: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @return Result
     */
    public function listGrants(string $keyId)
    {
        try{
            return $this->client->listGrants([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "    The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }


    /***
     * @param string $keyId
     * @return Result
     */
    public function getKeyPolicy(string $keyId)
    {
        try {
            return $this->client->getKeyPolicy([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem getting the key policy: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }


    /***
     * @param string $grantId
     * @param string $keyId
     * @return void
     */
    public function revokeGrant(string $grantId, string $keyId)
    {
        try{
            $this->client->revokeGrant([
                'GrantId' => $grantId,
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem with revoking the grant: {$caught->getAwsErrorMessage()}.\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param int $pendingWindowInDays
     * @return void
     */
    public function scheduleKeyDeletion(string $keyId, int $pendingWindowInDays = 7)
    {
        try {
            $this->client->scheduleKeyDeletion([
                'KeyId' => $keyId,
                'PendingWindowInDays' => $pendingWindowInDays,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem scheduling the key deletion: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param array $tags
     * @return void
     */
    public function tagResource(string $keyId, array $tags)
    {
        try {
            $this->client->tagResource([
                'KeyId' => $keyId,
                'Tags' => $tags,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem applying the tag(s): {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param string $message
     * @param string $algorithm
     * @return Result
     */
    public function sign(string $keyId, string $message, string $algorithm)
    {
        try {
            return $this->client->sign([
                'KeyId' => $keyId,
                'Message' => $message,
                'SigningAlgorithm' => $algorithm,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem signing the data: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param int $rotationPeriodInDays
     * @return void
     */
    public function enableKeyRotation(string $keyId, int $rotationPeriodInDays = 365)
    {
        try{
            $this->client->enableKeyRotation([
                'KeyId' => $keyId,
                'RotationPeriodInDays' => $rotationPeriodInDays,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param string $policy
     * @return void
     */
    public function putKeyPolicy(string $keyId, string $policy)
    {
        try {
            $this->client->putKeyPolicy([
                'KeyId' => $keyId,
                'Policy' => $policy,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem replacing the key policy: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $aliasName
     * @return void
     */
    public function deleteAlias(string $aliasName)
    {
        try {
            $this->client->deleteAlias([
                'AliasName' => $aliasName,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem deleting the alias: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }



    /***
     * @param string $keyId
     * @param string $message
     * @param string $signature
     * @param string $signingAlgorithm
     * @return bool
     */
    public function verify(string $keyId, string $message, string $signature, string $signingAlgorithm)
    {
        try {
            $result = $this->client->verify([
                'KeyId' => $keyId,
                'Message' => $message,
                'Signature' => $signature,
                'SigningAlgorithm' => $signingAlgorithm,
            ]);
            return $result['SignatureValid'];
        }catch(KmsException $caught){
            echo "There was a problem verifying the signature: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }


}
```
+ API の詳細については、「*AWS SDK for PHP API リファレンス*」の以下のトピックを参照してください。
  + [CreateAlias](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/CreateAlias)
  + [CreateGrant](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/CreateGrant)
  + [CreateKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/CreateKey)
  + [Decrypt](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Decrypt)
  + [DescribeKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/DescribeKey)
  + [DisableKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/DisableKey)
  + [EnableKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/EnableKey)
  + [暗号化](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Encrypt)
  + [GetKeyPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/GetKeyPolicy)
  + [ListAliases](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ListAliases)
  + [ListGrants](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ListGrants)
  + [ListKeys](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ListKeys)
  + [RevokeGrant](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/RevokeGrant)
  + [ScheduleKeyDeletion](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ScheduleKeyDeletion)
  + [Sign](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Sign)
  + [TagResource](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/TagResource)

## アクション
<a name="actions"></a>

### `CreateAlias`
<a name="kms_CreateAlias_php_3_topic"></a>

次のコード例は、`CreateAlias` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param string $alias
     * @return void
     */
    public function createAlias(string $keyId, string $alias)
    {
        try{
            $this->client->createAlias([
                'TargetKeyId' => $keyId,
                'AliasName' => $alias,
            ]);
        }catch (KmsException $caught){
            if($caught->getAwsErrorMessage() == "InvalidAliasNameException"){
                echo "The request was rejected because the specified alias name is not valid.";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の[CreateAlias](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/CreateAlias)を参照してください。

### `CreateGrant`
<a name="kms_CreateGrant_php_3_topic"></a>

次のコード例は、`CreateGrant` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param string $granteePrincipal
     * @param array $operations
     * @param array $grantTokens
     * @return Result
     */
    public function createGrant(string $keyId, string $granteePrincipal, array $operations, array $grantTokens = [])
    {
        $args = [
            'KeyId' => $keyId,
            'GranteePrincipal' => $granteePrincipal,
            'Operations' => $operations,
        ];
        if($grantTokens){
            $args['GrantTokens'] = $grantTokens;
        }
        try{
            return $this->client->createGrant($args);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "InvalidGrantTokenException"){
                echo "The request was rejected because the specified grant token is not valid.\n";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の[CreateGrant](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/CreateGrant)を参照してください。

### `CreateKey`
<a name="kms_CreateKey_php_3_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keySpec
     * @param string $keyUsage
     * @param string $description
     * @return array
     */
    public function createKey(string $keySpec = "", string $keyUsage = "", string $description = "Created by the SDK for PHP")
    {
        $parameters = ['Description' => $description];
        if($keySpec && $keyUsage){
            $parameters['KeySpec'] = $keySpec;
            $parameters['KeyUsage'] = $keyUsage;
        }
        try {
            $result = $this->client->createKey($parameters);
            return $result['KeyMetadata'];
        }catch(KmsException $caught){
            // Check for error specific to createKey operations
            if ($caught->getAwsErrorMessage() == "LimitExceededException"){
                echo "The request was rejected because a quota was exceeded. For more information, see Quotas in the Key Management Service Developer Guide.";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[CreateKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/CreateKey)」を参照してください。

### `Decrypt`
<a name="kms_Decrypt_php_3_topic"></a>

次のコード例は、`Decrypt` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param string $ciphertext
     * @param string $algorithm
     * @return Result
     */
    public function decrypt(string $keyId, string $ciphertext, string $algorithm = "SYMMETRIC_DEFAULT")
    {
        try{
            return $this->client->decrypt([
                'CiphertextBlob' => $ciphertext,
                'EncryptionAlgorithm' => $algorithm,
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem decrypting the data: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Decrypt](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Decrypt)」を参照してください。**

### `DeleteAlias`
<a name="kms_DeleteAlias_php_3_topic"></a>

次のコード例は、`DeleteAlias` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $aliasName
     * @return void
     */
    public function deleteAlias(string $aliasName)
    {
        try {
            $this->client->deleteAlias([
                'AliasName' => $aliasName,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem deleting the alias: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[DeleteAlias](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/DeleteAlias)」を参照してください。

### `DescribeKey`
<a name="kms_DescribeKey_php_3_topic"></a>

次のコード例は、`DescribeKey` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @return array
     */
    public function describeKey(string $keyId)
    {
        try {
            $result = $this->client->describeKey([
                "KeyId" => $keyId,
            ]);
            return $result['KeyMetadata'];
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の [DescribeKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/DescribeKey)を参照してください。

### `DisableKey`
<a name="kms_DisableKey_php_3_topic"></a>

次のコード例は、`DisableKey` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @return void
     */
    public function disableKey(string $keyId)
    {
        try {
            $this->client->disableKey([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem disabling the key: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、**「AWS SDK for PHP API リファレンス」の「[DisableKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/DisableKey)」を参照してください。

### `EnableKey`
<a name="kms_EnableKey_php_3_topic"></a>

次のコード例は、`EnableKey` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @return void
     */
    public function enableKey(string $keyId)
    {
        try {
            $this->client->enableKey([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[EnableKey](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/EnableKey)」を参照してください。

### `Encrypt`
<a name="kms_Encrypt_php_3_topic"></a>

次のコード例は、`Encrypt` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param string $text
     * @return Result
     */
    public function encrypt(string $keyId, string $text)
    {
        try {
            return $this->client->encrypt([
                'KeyId' => $keyId,
                'Plaintext' => $text,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "DisabledException"){
                echo "The request was rejected because the specified KMS key is not enabled.\n";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Encrypt](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Encrypt)」を参照してください。**

### `ListAliases`
<a name="kms_ListAliases_php_3_topic"></a>

次のコード例は、`ListAliases` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param int $limit
     * @return ResultPaginator
     */
    public function listAliases(string $keyId = "", int $limit = 0)
    {
        $args = [];
        if($keyId){
            $args['KeyId'] = $keyId;
        }
        if($limit){
            $args['Limit'] = $limit;
        }
        try{
            return $this->client->getPaginator("ListAliases", $args);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "InvalidMarkerException"){
                echo "The request was rejected because the marker that specifies where pagination should next begin is not valid.\n";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListAliases](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ListAliases)」を参照してください。

### `ListGrants`
<a name="kms_ListGrants_php_3_topic"></a>

次のコード例は、`ListGrants` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @return Result
     */
    public function listGrants(string $keyId)
    {
        try{
            return $this->client->listGrants([
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            if($caught->getAwsErrorMessage() == "NotFoundException"){
                echo "    The request was rejected because the specified entity or resource could not be found.\n";
            }
            throw $caught;
        }
    }
```
+  API の詳細については、「AWS SDK for PHP API リファレンス」の「[ListGrants](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ListGrants)」を参照してください。

### `ListKeys`
<a name="kms_ListKeys_php_3_topic"></a>

次のコード例は、`ListKeys` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @return array
     */
    public function listKeys()
    {
        try {
            $contents = [];
            $paginator = $this->client->getPaginator("ListKeys");
            foreach($paginator as $result){
                foreach ($result['Content'] as $object) {
                    $contents[] = $object;
                }
            }
            return $contents;
        }catch(KmsException $caught){
            echo "There was a problem listing the keys: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[ListKeys](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ListKeys)」を参照してください。

### `PutKeyPolicy`
<a name="kms_PutKeyPolicy_php_3_topic"></a>

次のコード例は、`PutKeyPolicy` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param string $policy
     * @return void
     */
    public function putKeyPolicy(string $keyId, string $policy)
    {
        try {
            $this->client->putKeyPolicy([
                'KeyId' => $keyId,
                'Policy' => $policy,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem replacing the key policy: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[PutKeyPolicy](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/PutKeyPolicy)」を参照してください。

### `RevokeGrant`
<a name="kms_RevokeGrant_php_3_topic"></a>

次のコード例は、`RevokeGrant` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $grantId
     * @param string $keyId
     * @return void
     */
    public function revokeGrant(string $grantId, string $keyId)
    {
        try{
            $this->client->revokeGrant([
                'GrantId' => $grantId,
                'KeyId' => $keyId,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem with revoking the grant: {$caught->getAwsErrorMessage()}.\n";
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[RevokeGrant](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/RevokeGrant)」を参照してください。

### `ScheduleKeyDeletion`
<a name="kms_ScheduleKeyDeletion_php_3_topic"></a>

次のコード例は、`ScheduleKeyDeletion` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param int $pendingWindowInDays
     * @return void
     */
    public function scheduleKeyDeletion(string $keyId, int $pendingWindowInDays = 7)
    {
        try {
            $this->client->scheduleKeyDeletion([
                'KeyId' => $keyId,
                'PendingWindowInDays' => $pendingWindowInDays,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem scheduling the key deletion: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ScheduleKeyDeletion](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/ScheduleKeyDeletion)」を参照してください。

### `Sign`
<a name="kms_Sign_php_3_topic"></a>

次のコード例は、`Sign` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param string $message
     * @param string $algorithm
     * @return Result
     */
    public function sign(string $keyId, string $message, string $algorithm)
    {
        try {
            return $this->client->sign([
                'KeyId' => $keyId,
                'Message' => $message,
                'SigningAlgorithm' => $algorithm,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem signing the data: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、「*AWS SDK for PHP API リファレンス*」の「[Sign](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/Sign)」を参照してください。

### `TagResource`
<a name="kms_TagResource_php_3_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
    /***
     * @param string $keyId
     * @param array $tags
     * @return void
     */
    public function tagResource(string $keyId, array $tags)
    {
        try {
            $this->client->tagResource([
                'KeyId' => $keyId,
                'Tags' => $tags,
            ]);
        }catch(KmsException $caught){
            echo "There was a problem applying the tag(s): {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/SdkForPHPV3/kms-2014-11-01/TagResource)」を参照してください。

# SDK for PHP を使用した Lambda の例
<a name="php_3_lambda_code_examples"></a>

次のコード例は、Lambda AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_php_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
namespace Lambda;

use Aws\S3\S3Client;
use GuzzleHttp\Psr7\Stream;
use Iam\IAMService;

class GettingStartedWithLambda
{
    public function run()
    {
        echo("\n");
        echo("--------------------------------------\n");
        print("Welcome to the AWS Lambda getting started demo using PHP!\n");
        echo("--------------------------------------\n");

        $clientArgs = [
            'region' => 'us-west-2',
            'version' => 'latest',
            'profile' => 'default',
        ];
        $uniqid = uniqid();

        $iamService = new IAMService();
        $s3client = new S3Client($clientArgs);
        $lambdaService = new LambdaService();

        echo "First, let's create a role to run our Lambda code.\n";
        $roleName = "test-lambda-role-$uniqid";
        $rolePolicyDocument = "{
            \"Version\": \"2012-10-17\",
            \"Statement\": [
                {
                    \"Effect\": \"Allow\",
                    \"Principal\": {
                        \"Service\": \"lambda.amazonaws.com\"
                    },
                    \"Action\": \"sts:AssumeRole\"
                }
            ]
        }";
        $role = $iamService->createRole($roleName, $rolePolicyDocument);
        echo "Created role {$role['RoleName']}.\n";

        $iamService->attachRolePolicy(
            $role['RoleName'],
            "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
        );
        echo "Attached the AWSLambdaBasicExecutionRole to {$role['RoleName']}.\n";

        echo "\nNow let's create an S3 bucket and upload our Lambda code there.\n";
        $bucketName = "amzn-s3-demo-bucket-$uniqid";
        $s3client->createBucket([
            'Bucket' => $bucketName,
        ]);
        echo "Created bucket $bucketName.\n";

        $functionName = "doc_example_lambda_$uniqid";
        $codeBasic = __DIR__ . "/lambda_handler_basic.zip";
        $handler = "lambda_handler_basic";
        $file = file_get_contents($codeBasic);
        $s3client->putObject([
            'Bucket' => $bucketName,
            'Key' => $functionName,
            'Body' => $file,
        ]);
        echo "Uploaded the Lambda code.\n";

        $createLambdaFunction = $lambdaService->createFunction($functionName, $role, $bucketName, $handler);
        // Wait until the function has finished being created.
        do {
            $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']);
        } while ($getLambdaFunction['Configuration']['State'] == "Pending");
        echo "Created Lambda function {$getLambdaFunction['Configuration']['FunctionName']}.\n";

        sleep(1);

        echo "\nOk, let's invoke that Lambda code.\n";
        $basicParams = [
            'action' => 'increment',
            'number' => 3,
        ];
        /** @var Stream $invokeFunction */
        $invokeFunction = $lambdaService->invoke($functionName, $basicParams)['Payload'];
        $result = json_decode($invokeFunction->getContents())->result;
        echo "After invoking the Lambda code with the input of {$basicParams['number']} we received $result.\n";

        echo "\nSince that's working, let's update the Lambda code.\n";
        $codeCalculator = "lambda_handler_calculator.zip";
        $handlerCalculator = "lambda_handler_calculator";
        echo "First, put the new code into the S3 bucket.\n";
        $file = file_get_contents($codeCalculator);
        $s3client->putObject([
            'Bucket' => $bucketName,
            'Key' => $functionName,
            'Body' => $file,
        ]);
        echo "New code uploaded.\n";

        $lambdaService->updateFunctionCode($functionName, $bucketName, $functionName);
        // Wait for the Lambda code to finish updating.
        do {
            $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']);
        } while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful");
        echo "New Lambda code uploaded.\n";

        $environment = [
            'Variable' => ['Variables' => ['LOG_LEVEL' => 'DEBUG']],
        ];
        $lambdaService->updateFunctionConfiguration($functionName, $handlerCalculator, $environment);
        do {
            $getLambdaFunction = $lambdaService->getFunction($createLambdaFunction['FunctionName']);
        } while ($getLambdaFunction['Configuration']['LastUpdateStatus'] !== "Successful");
        echo "Lambda code updated with new handler and a LOG_LEVEL of DEBUG for more information.\n";

        echo "Invoke the new code with some new data.\n";
        $calculatorParams = [
            'action' => 'plus',
            'x' => 5,
            'y' => 4,
        ];
        $invokeFunction = $lambdaService->invoke($functionName, $calculatorParams, "Tail");
        $result = json_decode($invokeFunction['Payload']->getContents())->result;
        echo "Indeed, {$calculatorParams['x']} + {$calculatorParams['y']} does equal $result.\n";
        echo "Here's the extra debug info: ";
        echo base64_decode($invokeFunction['LogResult']) . "\n";

        echo "\nBut what happens if you try to divide by zero?\n";
        $divZeroParams = [
            'action' => 'divide',
            'x' => 5,
            'y' => 0,
        ];
        $invokeFunction = $lambdaService->invoke($functionName, $divZeroParams, "Tail");
        $result = json_decode($invokeFunction['Payload']->getContents())->result;
        echo "You get a |$result| result.\n";
        echo "And an error message: ";
        echo base64_decode($invokeFunction['LogResult']) . "\n";

        echo "\nHere's all the Lambda functions you have in this Region:\n";
        $listLambdaFunctions = $lambdaService->listFunctions(5);
        $allLambdaFunctions = $listLambdaFunctions['Functions'];
        $next = $listLambdaFunctions->get('NextMarker');
        while ($next != false) {
            $listLambdaFunctions = $lambdaService->listFunctions(5, $next);
            $next = $listLambdaFunctions->get('NextMarker');
            $allLambdaFunctions = array_merge($allLambdaFunctions, $listLambdaFunctions['Functions']);
        }
        foreach ($allLambdaFunctions as $function) {
            echo "{$function['FunctionName']}\n";
        }

        echo "\n\nAnd don't forget to clean up your data!\n";

        $lambdaService->deleteFunction($functionName);
        echo "Deleted Lambda function.\n";
        $iamService->deleteRole($role['RoleName']);
        echo "Deleted Role.\n";
        $deleteObjects = $s3client->listObjectsV2([
            'Bucket' => $bucketName,
        ]);
        $deleteObjects = $s3client->deleteObjects([
            'Bucket' => $bucketName,
            'Delete' => [
                'Objects' => $deleteObjects['Contents'],
            ]
        ]);
        echo "Deleted all objects from the S3 bucket.\n";
        $s3client->deleteBucket(['Bucket' => $bucketName]);
        echo "Deleted the bucket.\n";
    }
}
```
+ API の詳細については、「*AWS SDK for PHP API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/CreateFunction)
  + [DeleteFunction](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteFunction)
  + [GetFunction](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetFunction)
  + [Invoke](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/Invoke)
  + [ListFunctions](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListFunctions)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionCode)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionConfiguration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_php_3_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    public function createFunction($functionName, $role, $bucketName, $handler)
    {
        //This assumes the Lambda function is in an S3 bucket.
        return $this->customWaiter(function () use ($functionName, $role, $bucketName, $handler) {
            return $this->lambdaClient->createFunction([
                'Code' => [
                    'S3Bucket' => $bucketName,
                    'S3Key' => $functionName,
                ],
                'FunctionName' => $functionName,
                'Role' => $role['Arn'],
                'Runtime' => 'python3.9',
                'Handler' => "$handler.lambda_handler",
            ]);
        });
    }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[CreateFunction](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/CreateFunction)」を参照してください。**

### `DeleteFunction`
<a name="lambda_DeleteFunction_php_3_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    public function deleteFunction($functionName)
    {
        return $this->lambdaClient->deleteFunction([
            'FunctionName' => $functionName,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteFunction](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/DeleteFunction)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_php_3_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    public function getFunction($functionName)
    {
        return $this->lambdaClient->getFunction([
            'FunctionName' => $functionName,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetFunction](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/GetFunction)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_php_3_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    public function invoke($functionName, $params, $logType = 'None')
    {
        return $this->lambdaClient->invoke([
            'FunctionName' => $functionName,
            'Payload' => json_encode($params),
            'LogType' => $logType,
        ]);
    }
```
+  API の詳細については、**AWS SDK for PHP API リファレンスの「[Invoke](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/Invoke)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_php_3_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    public function listFunctions($maxItems = 50, $marker = null)
    {
        if (is_null($marker)) {
            return $this->lambdaClient->listFunctions([
                'MaxItems' => $maxItems,
            ]);
        }

        return $this->lambdaClient->listFunctions([
            'Marker' => $marker,
            'MaxItems' => $maxItems,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/ListFunctions)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_php_3_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    public function updateFunctionCode($functionName, $s3Bucket, $s3Key)
    {
        return $this->lambdaClient->updateFunctionCode([
            'FunctionName' => $functionName,
            'S3Bucket' => $s3Bucket,
            'S3Key' => $s3Key,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionCode)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_php_3_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
    public function updateFunctionConfiguration($functionName, $handler, $environment = '')
    {
        return $this->lambdaClient->updateFunctionConfiguration([
            'FunctionName' => $functionName,
            'Handler' => "$handler.lambda_handler",
            'Environment' => $environment,
        ]);
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForPHPV3/lambda-2015-03-31/UpdateFunctionConfiguration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_php_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for PHP**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/applications/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_php_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
<?php
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;
use Aws\Rds\AuthTokenGenerator;
use Aws\Credentials\CredentialProvider;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }


    private function getAuthToken(): string {
        // Define connection authentication parameters
        $dbConnection = [
            'hostname' => getenv('DB_HOSTNAME'),
            'port' => getenv('DB_PORT'),
            'username' => getenv('DB_USERNAME'),
            'region' => getenv('AWS_REGION'),
        ];

        // Create RDS AuthTokenGenerator object
        $generator = new AuthTokenGenerator(CredentialProvider::defaultProvider());

        // Request authorization token from RDS, specifying the username
        return $generator->createToken(
            $dbConnection['hostname'] . ':' . $dbConnection['port'],
            $dbConnection['region'],
            $dbConnection['username']
        );
    }

    private function getQueryResults() {
        // Obtain auth token
        $token = $this->getAuthToken();

        // Define connection configuration
        $connectionConfig = [
            'host' => getenv('DB_HOSTNAME'),
            'user' => getenv('DB_USERNAME'),
            'password' => $token,
            'database' => getenv('DB_NAME'),
        ];

        // Create the connection to the DB
        $conn = new PDO(
            "mysql:host={$connectionConfig['host']};dbname={$connectionConfig['database']}",
            $connectionConfig['user'],
            $connectionConfig['password'],
            [
                PDO::MYSQL_ATTR_SSL_CA => '/path/to/rds-ca-2019-root.pem',
                PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => true,
            ]
        );

        // Obtain the result of the query
        $stmt = $conn->prepare('SELECT ?+? AS sum');
        $stmt->execute([3, 2]);

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * @param mixed $event
     * @param Context $context
     * @return array
     */
    public function handle(mixed $event, Context $context): array
    {
        $this->logger->info("Processing query");

        // Execute database flow
        $result = $this->getQueryResults();

        return [
            'sum' => $result['sum']
        ];
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_php_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Kinesis\KinesisEvent;
use Bref\Event\Kinesis\KinesisHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends KinesisHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handleKinesis(KinesisEvent $event, Context $context): void
    {
        $this->logger->info("Processing records");
        $records = $event->getRecords();
        foreach ($records as $record) {
            $data = $record->getData();
            $this->logger->info(json_encode($data));
            // TODO: Do interesting work based on the new data

            // Any exception thrown will be logged and the invocation will be marked as failed
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_php_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での DynamoDB イベントの消費。  

```
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\DynamoDb\DynamoDbEvent;
use Bref\Event\DynamoDb\DynamoDbHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends DynamoDbHandler
{
    private StderrLogger $logger;

    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handleDynamoDb(DynamoDbEvent $event, Context $context): void
    {
        $this->logger->info("Processing DynamoDb table items");
        $records = $event->getRecords();

        foreach ($records as $record) {
            $eventName = $record->getEventName();
            $keys = $record->getKeys();
            $old = $record->getOldImage();
            $new = $record->getNewImage();
            
            $this->logger->info("Event Name:".$eventName."\n");
            $this->logger->info("Keys:". json_encode($keys)."\n");
            $this->logger->info("Old Image:". json_encode($old)."\n");
            $this->logger->info("New Image:". json_encode($new));
            
            // TODO: Do interesting work based on the new data

            // Any exception thrown will be logged and the invocation will be marked as failed
        }

        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords items");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_php_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
<?php

require __DIR__.'/vendor/autoload.php';

use Bref\Context\Context;
use Bref\Event\Handler;

class DocumentDBEventHandler implements Handler
{
    public function handle($event, Context $context): string
    {

        $events = $event['events'] ?? [];
        foreach ($events as $record) {
            $this->logDocumentDBEvent($record['event']);
        }
        return 'OK';
    }

    private function logDocumentDBEvent($event): void
    {
        // Extract information from the event record

        $operationType = $event['operationType'] ?? 'Unknown';
        $db = $event['ns']['db'] ?? 'Unknown';
        $collection = $event['ns']['coll'] ?? 'Unknown';
        $fullDocument = $event['fullDocument'] ?? [];

        // Log the event details

        echo "Operation type: $operationType\n";
        echo "Database: $db\n";
        echo "Collection: $collection\n";
        echo "Full document: " . json_encode($fullDocument, JSON_PRETTY_PRINT) . "\n";
    }
}
return new DocumentDBEventHandler();
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_php_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での Amazon MSK イベントの消費。  

```
<?php
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

// using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Kafka\KafkaEvent;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handle(mixed $event, Context $context): void
    {
        $kafkaEvent = new KafkaEvent($event);
        $this->logger->info("Processing records");
        $records = $kafkaEvent->getRecords();

        foreach ($records as $record) {
            try {
                $key = $record->getKey();
                $this->logger->info("Key: $key");

                $values = $record->getValue();
                $this->logger->info(json_encode($values));

                foreach ($values as $value) {
                    $this->logger->info("Value: $value");
                }
                
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_php_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用して Lambda で S3 イベントの消費。  

```
<?php

use Bref\Context\Context;
use Bref\Event\S3\S3Event;
use Bref\Event\S3\S3Handler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';


class Handler extends S3Handler 
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }
    
    public function handleS3(S3Event $event, Context $context) : void
    {
        $this->logger->info("Processing S3 records");

        // Get the object from the event and show its content type
        $records = $event->getRecords();
        
        foreach ($records as $record) 
        {
            $bucket = $record->getBucket()->getName();
            $key = urldecode($record->getObject()->getKey());

            try {
                $fileSize = urldecode($record->getObject()->getSize());
                echo "File Size: " . $fileSize . "\n";
                // TODO: Implement your custom processing logic here
            } catch (Exception $e) {
                echo $e->getMessage() . "\n";
                echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n";
                throw $e;
            }
        }
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_php_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用して Lambda で SNS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

/* 
Since native PHP support for AWS Lambda is not available, we are utilizing Bref's PHP functions runtime for AWS Lambda.
For more information on Bref's PHP runtime for Lambda, refer to: https://bref.sh/docs/runtimes/function

Another approach would be to create a custom runtime. 
A practical example can be found here: https://aws.amazon.com/blogs/apn/aws-lambda-custom-runtime-for-php-a-practical-example/
*/

// Additional composer packages may be required when using Bref or any other PHP functions runtime.
// require __DIR__ . '/vendor/autoload.php';

use Bref\Context\Context;
use Bref\Event\Sns\SnsEvent;
use Bref\Event\Sns\SnsHandler;

class Handler extends SnsHandler
{
    public function handleSns(SnsEvent $event, Context $context): void
    {
        foreach ($event->getRecords() as $record) {
            $message = $record->getMessage();

            // TODO: Implement your custom processing logic here
            // Any exception thrown will be logged and the invocation will be marked as failed

            echo "Processed Message: $message" . PHP_EOL;
        }
    }
}

return new Handler();
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_php_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\InvalidLambdaEvent;
use Bref\Event\Sqs\SqsEvent;
use Bref\Event\Sqs\SqsHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends SqsHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws InvalidLambdaEvent
     */
    public function handleSqs(SqsEvent $event, Context $context): void
    {
        foreach ($event->getRecords() as $record) {
            $body = $record->getBody();
            // TODO: Do interesting work based on the new message
        }
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_php_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Kinesis\KinesisEvent;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handle(mixed $event, Context $context): array
    {
        $kinesisEvent = new KinesisEvent($event);
        $this->logger->info("Processing records");
        $records = $kinesisEvent->getRecords();

        $failedRecords = [];
        foreach ($records as $record) {
            try {
                $data = $record->getData();
                $this->logger->info(json_encode($data));
                // TODO: Do interesting work based on the new data
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
                // failed processing the record
                $failedRecords[] = $record->getSequenceNumber();
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");

        // change format for the response
        $failures = array_map(
            fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber],
            $failedRecords
        );

        return [
            'batchItemFailures' => $failures
        ];
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_php_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での DynamoDB バッチ項目失敗のレポート。  

```
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\DynamoDb\DynamoDbEvent;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handle(mixed $event, Context $context): array
    {
        $dynamoDbEvent = new DynamoDbEvent($event);
        $this->logger->info("Processing records");

        $records = $dynamoDbEvent->getRecords();
        $failedRecords = [];
        foreach ($records as $record) {
            try {
                $data = $record->getData();
                $this->logger->info(json_encode($data));
                // TODO: Do interesting work based on the new data
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
                // failed processing the record
                $failedRecords[] = $record->getSequenceNumber();
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");

        // change format for the response
        $failures = array_map(
            fn(string $sequenceNumber) => ['itemIdentifier' => $sequenceNumber],
            $failedRecords
        );

        return [
            'batchItemFailures' => $failures
        ];
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_php_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

use Bref\Context\Context;
use Bref\Event\Sqs\SqsEvent;
use Bref\Event\Sqs\SqsHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends SqsHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handleSqs(SqsEvent $event, Context $context): void
    {
        $this->logger->info("Processing SQS records");
        $records = $event->getRecords();

        foreach ($records as $record) {
            try {
                // Assuming the SQS message is in JSON format
                $message = json_decode($record->getBody(), true);
                $this->logger->info(json_encode($message));
                // TODO: Implement your custom processing logic here
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
                // failed processing the record
                $this->markAsFailed($record);
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords SQS records");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

# SDK for PHP を使用した Amazon MSK の例
<a name="php_3_kafka_code_examples"></a>

次のコード例は、Amazon MSK AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_php_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での Amazon MSK イベントの消費。  

```
<?php
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

// using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Kafka\KafkaEvent;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handle(mixed $event, Context $context): void
    {
        $kafkaEvent = new KafkaEvent($event);
        $this->logger->info("Processing records");
        $records = $kafkaEvent->getRecords();

        foreach ($records as $record) {
            try {
                $key = $record->getKey();
                $this->logger->info("Key: $key");

                $values = $record->getValue();
                $this->logger->info(json_encode($values));

                foreach ($values as $value) {
                    $this->logger->info("Value: $value");
                }
                
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords records");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

# SDK for PHP を使用した Amazon RDS の例
<a name="php_3_rds_code_examples"></a>

次のコード例は、Amazon RDS AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_php_3_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require __DIR__ . '/vendor/autoload.php';

use Aws\Exception\AwsException;



$rdsClient = new Aws\Rds\RdsClient([
    'region' => 'us-east-2'
]);

$dbIdentifier = '<<{{db-identifier}}>>';
$dbClass = 'db.t2.micro';
$storage = 5;
$engine = 'MySQL';
$username = 'MyUser';
$password = 'MyPassword';

try {
    $result = $rdsClient->createDBInstance([
        'DBInstanceIdentifier' => $dbIdentifier,
        'DBInstanceClass' => $dbClass,
        'AllocatedStorage' => $storage,
        'Engine' => $engine,
        'MasterUsername' => $username,
        'MasterUserPassword' => $password,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    echo $e->getMessage();
    echo "\n";
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/SdkForPHPV3/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_php_3_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require __DIR__ . '/vendor/autoload.php';

use Aws\Exception\AwsException;



$rdsClient = new Aws\Rds\RdsClient([
    'region' => 'us-east-2'
]);

$dbIdentifier = '<<{{db-identifier}}>>';
$snapshotName = '<<{{backup_2018_12_25}}>>';

try {
    $result = $rdsClient->createDBSnapshot([
        'DBInstanceIdentifier' => $dbIdentifier,
        'DBSnapshotIdentifier' => $snapshotName,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    echo $e->getMessage();
    echo "\n";
}
```
+  API の詳細については、**「AWS SDK for PHP API リファレンス」の「[CreateDBSnapshot](https://docs.aws.amazon.com/goto/SdkForPHPV3/rds-2014-10-31/CreateDBSnapshot)」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_php_3_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require __DIR__ . '/vendor/autoload.php';

use Aws\Exception\AwsException;


//Create an RDSClient
$rdsClient = new Aws\Rds\RdsClient([
    'region' => 'us-east-1'
]);

$dbIdentifier = '<<{{db-identifier}}>>';

try {
    $result = $rdsClient->deleteDBInstance([
        'DBInstanceIdentifier' => $dbIdentifier,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    echo $e->getMessage();
    echo "\n";
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/SdkForPHPV3/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_php_3_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require __DIR__ . '/vendor/autoload.php';

use Aws\Exception\AwsException;


//Create an RDSClient
$rdsClient = new Aws\Rds\RdsClient([
    'region' => 'us-east-2'
]);

try {
    $result = $rdsClient->describeDBInstances();
    foreach ($result['DBInstances'] as $instance) {
        print('<p>DB Identifier: ' . $instance['DBInstanceIdentifier']);
        print('<br />Endpoint: ' . $instance['Endpoint']["Address"]
            . ':' . $instance['Endpoint']["Port"]);
        print('<br />Current Status: ' . $instance["DBInstanceStatus"]);
        print('</p>');
    }
    print(" Raw Result ");
    var_dump($result);
} catch (AwsException $e) {
    echo $e->getMessage();
    echo "\n";
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForPHPV3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_php_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for PHP**  
 を使用して AWS SDK for PHP 、Amazon RDS データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful PHP バックエンドと対話します。  
+ React.js ウェブアプリケーションを AWS サービスに統合します。
+ Amazon RDS テーブル内の項目の一覧表示、追加、更新、削除を行います。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_php_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
<?php
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\Handler as StdHandler;
use Bref\Logger\StderrLogger;
use Aws\Rds\AuthTokenGenerator;
use Aws\Credentials\CredentialProvider;

require __DIR__ . '/vendor/autoload.php';

class Handler implements StdHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }


    private function getAuthToken(): string {
        // Define connection authentication parameters
        $dbConnection = [
            'hostname' => getenv('DB_HOSTNAME'),
            'port' => getenv('DB_PORT'),
            'username' => getenv('DB_USERNAME'),
            'region' => getenv('AWS_REGION'),
        ];

        // Create RDS AuthTokenGenerator object
        $generator = new AuthTokenGenerator(CredentialProvider::defaultProvider());

        // Request authorization token from RDS, specifying the username
        return $generator->createToken(
            $dbConnection['hostname'] . ':' . $dbConnection['port'],
            $dbConnection['region'],
            $dbConnection['username']
        );
    }

    private function getQueryResults() {
        // Obtain auth token
        $token = $this->getAuthToken();

        // Define connection configuration
        $connectionConfig = [
            'host' => getenv('DB_HOSTNAME'),
            'user' => getenv('DB_USERNAME'),
            'password' => $token,
            'database' => getenv('DB_NAME'),
        ];

        // Create the connection to the DB
        $conn = new PDO(
            "mysql:host={$connectionConfig['host']};dbname={$connectionConfig['database']}",
            $connectionConfig['user'],
            $connectionConfig['password'],
            [
                PDO::MYSQL_ATTR_SSL_CA => '/path/to/rds-ca-2019-root.pem',
                PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT => true,
            ]
        );

        // Obtain the result of the query
        $stmt = $conn->prepare('SELECT ?+? AS sum');
        $stmt->execute([3, 2]);

        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    /**
     * @param mixed $event
     * @param Context $context
     * @return array
     */
    public function handle(mixed $event, Context $context): array
    {
        $this->logger->info("Processing query");

        // Execute database flow
        $result = $this->getQueryResults();

        return [
            'sum' => $result['sum']
        ];
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

# SDK for PHP を使用した Amazon RDS データサービスの例
<a name="php_3_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_php_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for PHP**  
 を使用して AWS SDK for PHP 、Amazon RDS データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful PHP バックエンドと対話します。  
+ React.js ウェブアプリケーションを AWS サービスに統合します。
+ Amazon RDS テーブル内の項目の一覧表示、追加、更新、削除を行います。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for PHP を使用する Amazon Rekognition の例
<a name="php_3_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_php_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for PHP**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/applications/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

# SDK for PHP を使用した Amazon S3 のコードサンプル
<a name="php_3_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_php_3_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
use Aws\S3\S3Client;

$client = new S3Client(['region' => 'us-west-2']);
$results = $client->listBuckets();
var_dump($results);
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/ListBuckets)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_php_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
        echo("\n");
        echo("--------------------------------------\n");
        print("Welcome to the Amazon S3 getting started demo using PHP!\n");
        echo("--------------------------------------\n");

        $region = 'us-west-2';

        $this->s3client = new S3Client([
                'region' => $region,
        ]);
        /* Inline declaration example
        $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']);
        */

        $this->bucketName = "amzn-s3-demo-bucket-" . uniqid();

        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.");
        }

        $fileName = __DIR__ . "/local-file-" . uniqid();
        try {
            $this->s3client->putObject([
                'Bucket' => $this->bucketName,
                'Key' => $fileName,
                'SourceFile' => __DIR__ . '/testfile.txt'
            ]);
            echo "Uploaded $fileName to $this->bucketName.\n";
        } catch (Exception $exception) {
            echo "Failed to upload $fileName with error: " . $exception->getMessage();
            exit("Please fix error with file upload before continuing.");
        }

        try {
            $file = $this->s3client->getObject([
                'Bucket' => $this->bucketName,
                'Key' => $fileName,
            ]);
            $body = $file->get('Body');
            $body->rewind();
            echo "Downloaded the file and it begins with: {$body->read(26)}.\n";
        } catch (Exception $exception) {
            echo "Failed to download $fileName from $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with file downloading before continuing.");
        }

        try {
            $folder = "copied-folder";
            $this->s3client->copyObject([
                'Bucket' => $this->bucketName,
                'CopySource' => "$this->bucketName/$fileName",
                'Key' => "$folder/$fileName-copy",
            ]);
            echo "Copied $fileName to $folder/$fileName-copy.\n";
        } catch (Exception $exception) {
            echo "Failed to copy $fileName with error: " . $exception->getMessage();
            exit("Please fix error with object copying before continuing.");
        }

        try {
            $contents = $this->s3client->listObjectsV2([
                'Bucket' => $this->bucketName,
            ]);
            echo "The contents of your bucket are: \n";
            foreach ($contents['Contents'] as $content) {
                echo $content['Key'] . "\n";
            }
        } catch (Exception $exception) {
            echo "Failed to list objects in $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with listing objects before continuing.");
        }

        try {
            $objects = [];
            foreach ($contents['Contents'] as $content) {
                $objects[] = [
                    'Key' => $content['Key'],
                ];
            }
            $this->s3client->deleteObjects([
                'Bucket' => $this->bucketName,
                'Delete' => [
                    'Objects' => $objects,
                ],
            ]);
            $check = $this->s3client->listObjectsV2([
                'Bucket' => $this->bucketName,
            ]);
            if (isset($check['Contents']) && count($check['Contents']) > 0) {
                throw new Exception("Bucket wasn't empty.");
            }
            echo "Deleted all objects and folders from $this->bucketName.\n";
        } catch (Exception $exception) {
            echo "Failed to delete $fileName from $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with object deletion before continuing.");
        }

        try {
            $this->s3client->deleteBucket([
                'Bucket' => $this->bucketName,
            ]);
            echo "Deleted bucket $this->bucketName.\n";
        } catch (Exception $exception) {
            echo "Failed to delete $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with bucket deletion before continuing.");
        }

        echo "Successfully ran the Amazon S3 with PHP demo.\n";
```
+ API の詳細については、「*AWS SDK for PHP API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/GetObject)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/ListObjectsV2)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_php_3_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトの単純なコピー。  

```
        $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']);

        try {
            $folder = "copied-folder";
            $this->s3client->copyObject([
                'Bucket' => $this->bucketName,
                'CopySource' => "$this->bucketName/$fileName",
                'Key' => "$folder/$fileName-copy",
            ]);
            echo "Copied $fileName to $folder/$fileName-copy.\n";
        } catch (Exception $exception) {
            echo "Failed to copy $fileName with error: " . $exception->getMessage();
            exit("Please fix error with object copying before continuing.");
        }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[CopyObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CopyObject)」を参照してください。**

### `CreateBucket`
<a name="s3_CreateBucket_php_3_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケットを作成します。  

```
        $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.");
        }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[CreateBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CreateBucket)」を参照してください。**

### `DeleteBucket`
<a name="s3_DeleteBucket_php_3_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。
空のバケットを削除します。  

```
        $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']);

        try {
            $this->s3client->deleteBucket([
                'Bucket' => $this->bucketName,
            ]);
            echo "Deleted bucket $this->bucketName.\n";
        } catch (Exception $exception) {
            echo "Failed to delete $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with bucket deletion before continuing.");
        }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[DeleteBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/DeleteBucket)」を参照してください。**

### `DeleteObject`
<a name="s3_DeleteObject_php_3_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
    public function deleteObject(string $bucketName, string $fileName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $fileName], $args);
        try {
            $this->client->deleteObject($parameters);
            if ($this->verbose) {
                echo "Deleted the object named: $fileName from $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete $fileName from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object deletion before continuing.";
            }
            throw $exception;
        }
    }
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_php_3_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。
キーのリストからオブジェクトのセットを削除します。  

```
        $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']);

        try {
            $objects = [];
            foreach ($contents['Contents'] as $content) {
                $objects[] = [
                    'Key' => $content['Key'],
                ];
            }
            $this->s3client->deleteObjects([
                'Bucket' => $this->bucketName,
                'Delete' => [
                    'Objects' => $objects,
                ],
            ]);
            $check = $this->s3client->listObjectsV2([
                'Bucket' => $this->bucketName,
            ]);
            if (isset($check['Contents']) && count($check['Contents']) > 0) {
                throw new Exception("Bucket wasn't empty.");
            }
            echo "Deleted all objects and folders from $this->bucketName.\n";
        } catch (Exception $exception) {
            echo "Failed to delete $fileName from $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with object deletion before continuing.");
        }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/DeleteObjects)」を参照してください。**

### `GetObject`
<a name="s3_GetObject_php_3_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトを取得します。  

```
        $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']);

        try {
            $file = $this->s3client->getObject([
                'Bucket' => $this->bucketName,
                'Key' => $fileName,
            ]);
            $body = $file->get('Body');
            $body->rewind();
            echo "Downloaded the file and it begins with: {$body->read(26)}.\n";
        } catch (Exception $exception) {
            echo "Failed to download $fileName from $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with file downloading before continuing.");
        }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[GetObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/GetObject)」を参照してください。**

### `ListObjectsV2`
<a name="s3_ListObjectsV2_php_3_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。
バケット内のオブジェクトを一覧表示します。  

```
        $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']);

        try {
            $contents = $this->s3client->listObjectsV2([
                'Bucket' => $this->bucketName,
            ]);
            echo "The contents of your bucket are: \n";
            foreach ($contents['Contents'] as $content) {
                echo $content['Key'] . "\n";
            }
        } catch (Exception $exception) {
            echo "Failed to list objects in $this->bucketName with error: " . $exception->getMessage();
            exit("Please fix error with listing objects before continuing.");
        }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/ListObjectsV2)」を参照してください。**

### `PutObject`
<a name="s3_PutObject_php_3_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトをバケットにアップロードします。  

```
        $s3client = new Aws\S3\S3Client(['region' => 'us-west-2']);

        $fileName = __DIR__ . "/local-file-" . uniqid();
        try {
            $this->s3client->putObject([
                'Bucket' => $this->bucketName,
                'Key' => $fileName,
                'SourceFile' => __DIR__ . '/testfile.txt'
            ]);
            echo "Uploaded $fileName to $this->bucketName.\n";
        } catch (Exception $exception) {
            echo "Failed to upload $fileName with error: " . $exception->getMessage();
            exit("Please fix error with file upload before continuing.");
        }
```
+  API の詳細については、AWS SDK for PHP API リファレンスの「[PutObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/PutObject)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_php_3_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
namespace S3;
use Aws\Exception\AwsException;
use AwsUtilities\PrintableLineBreak;
use AwsUtilities\TestableReadline;
use DateTime;

require 'vendor/autoload.php';

class PresignedURL
{
    use PrintableLineBreak;
    use TestableReadline;

    public function run()
    {
        $s3Service = new S3Service();

        $expiration = new DateTime("+20 minutes");
        $linebreak = $this->getLineBreak();

        echo $linebreak;
        echo ("Welcome to the Amazon S3 presigned URL demo.\n");
        echo $linebreak;

        $bucket = $this->testable_readline("First, please enter the name of the S3 bucket to use: ");
        $key = $this->testable_readline("Next, provide the key of an object in the given bucket: ");
        echo $linebreak;
        $command = $s3Service->getClient()->getCommand('GetObject', [
            'Bucket' => $bucket,
            'Key' => $key,
        ]);
        try {
            $preSignedUrl = $s3Service->preSignedUrl($command, $expiration);
            echo "Your preSignedUrl is \n$preSignedUrl\nand will be good for the next 20 minutes.\n";
            echo $linebreak;
            echo "Thanks for trying the Amazon S3 presigned URL demo.\n";
        } catch (AwsException $exception) {
            echo $linebreak;
            echo "Something went wrong: $exception";
            die();
        }
    }
}

$runner = new PresignedURL();
$runner->run();



namespace S3;

use Aws\CommandInterface;
use Aws\Exception\AwsException;
use Aws\Result;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use AwsUtilities\AWSServiceClass;
use DateTimeInterface;

class S3Service extends AWSServiceClass
{
    protected S3Client $client;
    protected bool $verbose;

    public function __construct(S3Client $client = null, $verbose = false)
    {
        if ($client) {
            $this->client = $client;
        } else {
            $this->client = new S3Client([
                'version' => 'latest',
                'region' => 'us-west-2',
            ]);
        }
        $this->verbose = $verbose;
    }

    public function setVerbose($verbose)
    {
        $this->verbose = $verbose;
    }

    public function isVerbose(): bool
    {
        return $this->verbose;
    }

    public function getClient(): S3Client
    {
        return $this->client;
    }

    public function setClient(S3Client $client)
    {
        $this->client = $client;
    }


    public function emptyAndDeleteBucket($bucketName, array $args = [])
    {
        try {
            $objects = $this->listAllObjects($bucketName, $args);
            $this->deleteObjects($bucketName, $objects, $args);
            if ($this->verbose) {
                echo "Deleted all objects and folders from $bucketName.\n";
            }
            $this->deleteBucket($bucketName, $args);
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete $bucketName with error: {$exception->getMessage()}\n";
                echo "\nPlease fix error with bucket deletion before continuing.\n";
            }
            throw $exception;
        }
    }



    public function createBucket(string $bucketName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName], $args);
        try {
            $this->client->createBucket($parameters);
            if ($this->verbose) {
                echo "Created the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to create $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with bucket creation before continuing.";
            }
            throw $exception;
        }
    }



    public function putObject(string $bucketName, string $key, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key], $args);
        try {
            $this->client->putObject($parameters);
            if ($this->verbose) {
                echo "Uploaded the object named: $key to the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to create $key in $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object uploading before continuing.";
            }
            throw $exception;
        }
    }



    public function getObject(string $bucketName, string $key, array $args = []): Result
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key], $args);
        try {
            $object = $this->client->getObject($parameters);
            if ($this->verbose) {
                echo "Downloaded the object named: $key to the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to download $key from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object downloading before continuing.";
            }
            throw $exception;
        }
        return $object;
    }



    public function copyObject($bucketName, $key, $copySource, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key, "CopySource" => $copySource], $args);
        try {
            $this->client->copyObject($parameters);
            if ($this->verbose) {
                echo "Copied the object from: $copySource in $bucketName to: $key.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to copy $copySource in $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object copying before continuing.";
            }
            throw $exception;
        }
    }



    public function listObjects(string $bucketName, $start = 0, $max = 1000, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Marker' => $start, "MaxKeys" => $max], $args);
        try {
            $objects = $this->client->listObjectsV2($parameters);
            if ($this->verbose) {
                echo "Retrieved the list of objects from: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to retrieve the objects from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with list objects before continuing.";
            }
            throw $exception;
        }
        return $objects;
    }



    public function listAllObjects($bucketName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName], $args);

        $contents = [];
        $paginator = $this->client->getPaginator("ListObjectsV2", $parameters);

        foreach ($paginator as $result) {
            if($result['KeyCount'] == 0){
                break;
            }
            foreach ($result['Contents'] as $object) {
                $contents[] = $object;
            }
        }
        return $contents;
    }



    public function deleteObjects(string $bucketName, array $objects, array $args = [])
    {
        $listOfObjects = array_map(
            function ($object) {
                return ['Key' => $object];
            },
            array_column($objects, 'Key')
        );
        if(!$listOfObjects){
            return;
        }

        $parameters = array_merge(['Bucket' => $bucketName, 'Delete' => ['Objects' => $listOfObjects]], $args);
        try {
            $this->client->deleteObjects($parameters);
            if ($this->verbose) {
                echo "Deleted the list of objects from: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete the list of objects from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object deletion before continuing.";
            }
            throw $exception;
        }
    }



    public function deleteBucket(string $bucketName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName], $args);
        try {
            $this->client->deleteBucket($parameters);
            if ($this->verbose) {
                echo "Deleted the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with bucket deletion before continuing.";
            }
            throw $exception;
        }
    }



    public function deleteObject(string $bucketName, string $fileName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $fileName], $args);
        try {
            $this->client->deleteObject($parameters);
            if ($this->verbose) {
                echo "Deleted the object named: $fileName from $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete $fileName from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object deletion before continuing.";
            }
            throw $exception;
        }
    }



    public function listBuckets(array $args = [])
    {
        try {
            $buckets = $this->client->listBuckets($args);
            if ($this->verbose) {
                echo "Retrieved all " . count($buckets) . "\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to retrieve bucket list with error: {$exception->getMessage()}\n";
                echo "Please fix error with bucket lists before continuing.";
            }
            throw $exception;
        }
        return $buckets;
    }



    public function preSignedUrl(CommandInterface $command, DateTimeInterface|int|string $expires, array $options = [])
    {
        $request = $this->client->createPresignedRequest($command, $expires, $options);
        try {
            $presignedUrl = (string)$request->getUri();
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to create a presigned url: {$exception->getMessage()}\n";
                echo "Please fix error with presigned urls before continuing.";
            }
            throw $exception;
        }
        return $presignedUrl;
    }



    public function createSession(string $bucketName)
    {
        try{
            $result = $this->client->createSession([
                'Bucket' => $bucketName,
            ]);
            return $result;
        }catch(S3Exception $caught){
            if($caught->getAwsErrorType() == "NoSuchBucket"){
                echo "The specified bucket does not exist.";
            }
            throw $caught;
        }
    }

}
```

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_php_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for PHP**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/applications/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_php_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用して Lambda で S3 イベントの消費。  

```
<?php

use Bref\Context\Context;
use Bref\Event\S3\S3Event;
use Bref\Event\S3\S3Handler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';


class Handler extends S3Handler 
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }
    
    public function handleS3(S3Event $event, Context $context) : void
    {
        $this->logger->info("Processing S3 records");

        // Get the object from the event and show its content type
        $records = $event->getRecords();
        
        foreach ($records as $record) 
        {
            $bucket = $record->getBucket()->getName();
            $key = urldecode($record->getObject()->getKey());

            try {
                $fileSize = urldecode($record->getObject()->getSize());
                echo "File Size: " . $fileSize . "\n";
                // TODO: Implement your custom processing logic here
            } catch (Exception $e) {
                echo $e->getMessage() . "\n";
                echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n";
                throw $e;
            }
        }
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

# SDK for PHP を使用した S3 ディレクトリバケットの例
<a name="php_3_s3-directory-buckets_code_examples"></a>

次のコード例は、S3 ディレクトリバケット AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3-directory-buckets_Scenario_ExpressBasics_php_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ VPC と VPC エンドポイントをセットアップします。
+ S3 ディレクトリバケットと S3 Express One Zone ストレージクラスを操作するようにポリシー、ロール、ユーザーを設定します。
+ 2 つの S3 クライアントを作成します。
+ バケットを 2 つ作成します。
+ オブジェクトを作成し、それをコピーします。
+ パフォーマンスの違いを示します。
+ 辞書順の違いを示すために、バケットをデータを追加します。
+ ユーザーにリソースをクリーンアップするかどうかを確認するプロンプトを表示します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/s3/express#code-examples)での設定と実行の方法を確認してください。
Amazon S3 ディレクトリバケットと S3 Express One Zone の基本を示すシナリオを実行します。  

```
        echo "\n";
        echo "--------------------------------------\n";
        echo "Welcome to the Amazon S3 Express Basics demo using PHP!\n";
        echo "--------------------------------------\n";

        // Change these both of these values to use a different region/availability zone.
        $region = "us-west-2";
        $az = "usw2-az1";

        $this->s3Service = new S3Service(new S3Client(['region' => $region]));
        $this->iamService = new IAMService(new IamClient(['region' => $region]));

        $uuid = uniqid();

        echo <<<INTRO
Let's get started! First, please note that S3 Express One Zone works best when working within the AWS infrastructure,
specifically when working in the same Availability Zone. To see the best results in this example, and when you implement
Directory buckets into your infrastructure, it is best to put your Compute resources in the same AZ as your Directory
bucket.\n
INTRO;
        pressEnter();
        // 1. Configure a gateway VPC endpoint. This is the recommended method to allow S3 Express One Zone traffic without
        // the need to pass through an internet gateway or NAT device.
        echo "\n";
        echo "1. First, we'll set up a new VPC and VPC Endpoint if this program is running in an EC2 instance in the same AZ as your Directory buckets will be.\n";
        $ec2Choice = testable_readline("Are you running this in an EC2 instance located in the same AZ as your intended Directory buckets? Enter Y/y to setup a VPC Endpoint, or N/n/blank to skip this section.");
        if($ec2Choice == "Y" || $ec2Choice == "y") {
            echo "Great! Let's set up a VPC, retrieve the Route Table from it, and create a VPC Endpoint to connect the S3 Client to.\n";
            pressEnter();
            $this->ec2Service = new EC2Service(new Ec2Client(['region' => $region]));
            $cidr = "10.0.0.0/16";
            $vpc = $this->ec2Service->createVpc($cidr);
            $this->resources['vpcId'] = $vpc['VpcId'];

            $this->ec2Service->waitForVpcAvailable($vpc['VpcId']);

            $routeTable = $this->ec2Service->describeRouteTables([], [
                [
                    'Name' => "vpc-id",
                    'Values' => [$vpc['VpcId']],
                ],
            ]);

            $serviceName = "com.amazonaws." . $this->ec2Service->getRegion() . ".s3express";
            $vpcEndpoint = $this->ec2Service->createVpcEndpoint($serviceName, $vpc['VpcId'], [$routeTable[0]]);
            $this->resources['vpcEndpointId'] = $vpcEndpoint['VpcEndpointId'];
        }else{
            echo "Skipping the VPC setup. Don't forget to use this in production!\n";
        }

        // 2. Policies, user, and roles with CDK.
        echo "\n";
        echo "2. Policies, users, and roles with CDK.\n";
        echo "Now, we'll set up some policies, roles, and a user. This user will only have permissions to do S3 Express One Zone actions.\n";
        pressEnter();

        $this->cloudFormationClient = new CloudFormationClient([]);
        $stackName = "cfn-stack-s3-express-basics-" . uniqid();
        $file = file_get_contents(__DIR__ . "/../../../../resources/cfn/s3_express_basics/s3_express_template.yml");
        $result = $this->cloudFormationClient->createStack([
            'StackName' => $stackName,
            'TemplateBody' => $file,
            'Capabilities' => ['CAPABILITY_IAM'],
        ]);
        $waiter = $this->cloudFormationClient->getWaiter("StackCreateComplete", ['StackName' => $stackName]);
        try {
            $waiter->promise()->wait();
        }catch(CloudFormationException $caught){
            echo "Error waiting for the CloudFormation stack to create: {$caught->getAwsErrorMessage()}\n";
            throw $caught;
        }
        $this->resources['stackName'] = $stackName;
        $stackInfo = $this->cloudFormationClient->describeStacks([
            'StackName' => $result['StackId'],
        ]);

        $expressUserName = "";
        $regularUserName = "";
        foreach($stackInfo['Stacks'][0]['Outputs'] as $output) {
            if ($output['OutputKey'] == "RegularUser") {
                $regularUserName = $output['OutputValue'];
            }
            if ($output['OutputKey'] == "ExpressUser") {
                $expressUserName = $output['OutputValue'];
            }
        }
        $regularKey = $this->iamService->createAccessKey($regularUserName);
        $regularCredentials = new Credentials($regularKey['AccessKeyId'], $regularKey['SecretAccessKey']);
        $expressKey = $this->iamService->createAccessKey($expressUserName);
        $expressCredentials = new Credentials($expressKey['AccessKeyId'], $expressKey['SecretAccessKey']);

        // 3. Create an additional client using the credentials with S3 Express permissions.
        echo "\n";
        echo "3. Create an additional client using the credentials with S3 Express permissions.\n";
        echo "This client is created with the credentials associated with the user account with the S3 Express policy attached, so it can perform S3 Express operations.\n";
        pressEnter();
        $s3RegularClient = new S3Client([
            'Region' => $region,
            'Credentials' => $regularCredentials,
        ]);
        $s3RegularService = new S3Service($s3RegularClient);
        $s3ExpressClient = new S3Client([
            'Region' => $region,
            'Credentials' => $expressCredentials,
        ]);
        $s3ExpressService = new S3Service($s3ExpressClient);
        echo "All the roles and policies were created an attached to the user. Then, a new S3 Client and Service were created using that user's credentials.\n";
        echo "We can now use this client to make calls to S3 Express operations. Keeping permissions in mind (and adhering to least-privilege) is crucial to S3 Express.\n";
        pressEnter();

        // 4. Create two buckets.
        echo "\n";
        echo "3. Create two buckets.\n";
        echo "Now we will create a Directory bucket, which is the linchpin of the S3 Express One Zone service.\n";
        echo "Directory buckets behave in different ways from regular S3 buckets, which we will explore here.\n";
        echo "We'll also create a normal bucket, put an object into the normal bucket, and copy it over to the Directory bucket.\n";
        pressEnter();

        // Create a directory bucket. These are different from normal S3 buckets in subtle ways.
        $directoryBucketName = "s3-express-demo-directory-bucket-$uuid--$az--x-s3";
        echo "Now, let's create the actual Directory bucket, as well as a regular bucket.\n";
        pressEnter();
        $s3ExpressService->createBucket($directoryBucketName, [
            'CreateBucketConfiguration' => [
                'Bucket' => [
                    'Type' => "Directory", // This is what causes S3 to create a Directory bucket as opposed to a normal bucket.
                    'DataRedundancy' => "SingleAvailabilityZone",
                ],
                'Location' => [
                    'Name' => $az,
                    'Type' => "AvailabilityZone",
                ],
            ],
        ]);
        $this->resources['directoryBucketName'] = $directoryBucketName;

        // Create a normal bucket.
        $normalBucketName = "normal-bucket-$uuid";
        $s3RegularService->createBucket($normalBucketName);
        $this->resources['normalBucketName'] = $normalBucketName;
        echo "Great! Both buckets were created.\n";
        pressEnter();

        // 5. Create an object and copy it over.
        echo "\n";
        echo "5. Create an object and copy it over.\n";
        echo "We'll create a basic object consisting of some text and upload it to the normal bucket.\n";
        echo "Next, we'll copy the object into the Directory bucket using the regular client.\n";
        echo "This works fine, because Copy operations are not restricted for Directory buckets.\n";
        pressEnter();

        $objectKey = "basic-text-object";
        $s3RegularService->putObject($normalBucketName, $objectKey, $args = ['Body' => "Look Ma, I'm a bucket!"]);
        $this->resources['objectKey'] = $objectKey;

        // Create a session to access the directory bucket. The SDK Client will automatically refresh this as needed.
        $s3ExpressService->createSession($directoryBucketName);
        $s3ExpressService->copyObject($directoryBucketName, $objectKey, "$normalBucketName/$objectKey");

        echo "It worked! It's important to remember the user permissions when interacting with Directory buckets.\n";
        echo "Instead of validating permissions on every call as normal buckets do, Directory buckets utilize the user credentials and session token to validate.\n";
        echo "This allows for much faster connection speeds on every call. For single calls, this is low, but for many concurrent calls, this adds up to a lot of time saved.\n";
        pressEnter();

        // 6. Demonstrate performance difference.
        echo "\n";
        echo "6. Demonstrate performance difference.\n";
        $downloads = 1000;
        echo "Now, let's do a performance test. We'll download the same object from each bucket $downloads times and compare the total time needed. Note: the performance difference will be much more pronounced if this example is run in an EC2 instance in the same AZ as the bucket.\n";
        $downloadChoice = testable_readline("If you would like to download each object $downloads times, press enter. Otherwise, enter a custom amount and press enter.");
        if($downloadChoice && is_numeric($downloadChoice) && $downloadChoice < 1000000){ // A million is enough. I promise.
            $downloads = $downloadChoice;
        }

        // Download the object $downloads times from each bucket and time it to demonstrate the speed difference.
        $directoryStartTime = hrtime(true);
        for($i = 0; $i < $downloads; ++$i){
            $s3ExpressService->getObject($directoryBucketName, $objectKey);
        }
        $directoryEndTime = hrtime(true);
        $directoryTimeDiff = $directoryEndTime - $directoryStartTime;

        $normalStartTime = hrtime(true);
        for($i = 0; $i < $downloads; ++$i){
            $s3RegularService->getObject($normalBucketName, $objectKey);
        }
        $normalEndTime = hrtime(true);
        $normalTimeDiff = $normalEndTime - $normalStartTime;

        echo "The directory bucket took $directoryTimeDiff nanoseconds, while the normal bucket took $normalTimeDiff.\n";
        echo "That's a difference of " . ($normalTimeDiff - $directoryTimeDiff) . " nanoseconds, or " . (($normalTimeDiff - $directoryTimeDiff)/1000000000) . " seconds.\n";
        pressEnter();

        // 7. Populate the buckets to show the lexicographical difference.
        echo "\n";
        echo "7. Populate the buckets to show the lexicographical difference.\n";
        echo "Now let's explore how Directory buckets store objects in a different manner to regular buckets.\n";
        echo "The key is in the name \"Directory!\"\n";
        echo "Where regular buckets store their key/value pairs in a flat manner, Directory buckets use actual directories/folders.\n";
        echo "This allows for more rapid indexing, traversing, and therefore retrieval times!\n";
        echo "The more segmented your bucket is, with lots of directories, sub-directories, and objects, the more efficient it becomes.\n";
        echo "This structural difference also causes ListObjects to behave differently, which can cause unexpected results.\n";
        echo "Let's add a few more objects with layered directories as see how the output of ListObjects changes.\n";
        pressEnter();

        // Populate a few more files in each bucket so that we can use ListObjects and show the difference.
        $otherObject = "other/$objectKey";
        $altObject = "alt/$objectKey";
        $otherAltObject = "other/alt/$objectKey";
        $s3ExpressService->putObject($directoryBucketName, $otherObject);
        $s3RegularService->putObject($normalBucketName, $otherObject);
        $this->resources['otherObject'] = $otherObject;
        $s3ExpressService->putObject($directoryBucketName, $altObject);
        $s3RegularService->putObject($normalBucketName, $altObject);
        $this->resources['altObject'] = $altObject;
        $s3ExpressService->putObject($directoryBucketName, $otherAltObject);
        $s3RegularService->putObject($normalBucketName, $otherAltObject);
        $this->resources['otherAltObject'] = $otherAltObject;

        $listDirectoryBucket = $s3ExpressService->listObjects($directoryBucketName);
        $listNormalBucket = $s3RegularService->listObjects($normalBucketName);

        // Directory bucket content
        echo "Directory bucket content\n";
        foreach($listDirectoryBucket['Contents'] as $result){
            echo $result['Key'] . "\n";
        }

        // Normal bucket content
        echo "\nNormal bucket content\n";
        foreach($listNormalBucket['Contents'] as $result){
            echo $result['Key'] . "\n";
        }

        echo "Notice how the normal bucket lists objects in lexicographical order, while the directory bucket does not. This is because the normal bucket considers the whole \"key\" to be the object identifies, while the directory bucket actually creates directories and uses the object \"key\" as a path to the object.\n";
        pressEnter();

        echo "\n";
        echo "That's it for our tour of the basic operations for S3 Express One Zone.\n";
        $cleanUp = testable_readline("Would you like to delete all the resources created during this demo? Enter Y/y to delete all the resources.");
        if($cleanUp){
            $this->cleanUp();
        }



namespace S3;

use Aws\CommandInterface;
use Aws\Exception\AwsException;
use Aws\Result;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use AwsUtilities\AWSServiceClass;
use DateTimeInterface;

class S3Service extends AWSServiceClass
{
    protected S3Client $client;
    protected bool $verbose;

    public function __construct(S3Client $client = null, $verbose = false)
    {
        if ($client) {
            $this->client = $client;
        } else {
            $this->client = new S3Client([
                'version' => 'latest',
                'region' => 'us-west-2',
            ]);
        }
        $this->verbose = $verbose;
    }

    public function setVerbose($verbose)
    {
        $this->verbose = $verbose;
    }

    public function isVerbose(): bool
    {
        return $this->verbose;
    }

    public function getClient(): S3Client
    {
        return $this->client;
    }

    public function setClient(S3Client $client)
    {
        $this->client = $client;
    }


    public function emptyAndDeleteBucket($bucketName, array $args = [])
    {
        try {
            $objects = $this->listAllObjects($bucketName, $args);
            $this->deleteObjects($bucketName, $objects, $args);
            if ($this->verbose) {
                echo "Deleted all objects and folders from $bucketName.\n";
            }
            $this->deleteBucket($bucketName, $args);
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete $bucketName with error: {$exception->getMessage()}\n";
                echo "\nPlease fix error with bucket deletion before continuing.\n";
            }
            throw $exception;
        }
    }



    public function createBucket(string $bucketName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName], $args);
        try {
            $this->client->createBucket($parameters);
            if ($this->verbose) {
                echo "Created the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to create $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with bucket creation before continuing.";
            }
            throw $exception;
        }
    }



    public function putObject(string $bucketName, string $key, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key], $args);
        try {
            $this->client->putObject($parameters);
            if ($this->verbose) {
                echo "Uploaded the object named: $key to the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to create $key in $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object uploading before continuing.";
            }
            throw $exception;
        }
    }



    public function getObject(string $bucketName, string $key, array $args = []): Result
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key], $args);
        try {
            $object = $this->client->getObject($parameters);
            if ($this->verbose) {
                echo "Downloaded the object named: $key to the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to download $key from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object downloading before continuing.";
            }
            throw $exception;
        }
        return $object;
    }



    public function copyObject($bucketName, $key, $copySource, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $key, "CopySource" => $copySource], $args);
        try {
            $this->client->copyObject($parameters);
            if ($this->verbose) {
                echo "Copied the object from: $copySource in $bucketName to: $key.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to copy $copySource in $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object copying before continuing.";
            }
            throw $exception;
        }
    }



    public function listObjects(string $bucketName, $start = 0, $max = 1000, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Marker' => $start, "MaxKeys" => $max], $args);
        try {
            $objects = $this->client->listObjectsV2($parameters);
            if ($this->verbose) {
                echo "Retrieved the list of objects from: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to retrieve the objects from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with list objects before continuing.";
            }
            throw $exception;
        }
        return $objects;
    }



    public function listAllObjects($bucketName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName], $args);

        $contents = [];
        $paginator = $this->client->getPaginator("ListObjectsV2", $parameters);

        foreach ($paginator as $result) {
            if($result['KeyCount'] == 0){
                break;
            }
            foreach ($result['Contents'] as $object) {
                $contents[] = $object;
            }
        }
        return $contents;
    }



    public function deleteObjects(string $bucketName, array $objects, array $args = [])
    {
        $listOfObjects = array_map(
            function ($object) {
                return ['Key' => $object];
            },
            array_column($objects, 'Key')
        );
        if(!$listOfObjects){
            return;
        }

        $parameters = array_merge(['Bucket' => $bucketName, 'Delete' => ['Objects' => $listOfObjects]], $args);
        try {
            $this->client->deleteObjects($parameters);
            if ($this->verbose) {
                echo "Deleted the list of objects from: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete the list of objects from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object deletion before continuing.";
            }
            throw $exception;
        }
    }



    public function deleteBucket(string $bucketName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName], $args);
        try {
            $this->client->deleteBucket($parameters);
            if ($this->verbose) {
                echo "Deleted the bucket named: $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with bucket deletion before continuing.";
            }
            throw $exception;
        }
    }



    public function deleteObject(string $bucketName, string $fileName, array $args = [])
    {
        $parameters = array_merge(['Bucket' => $bucketName, 'Key' => $fileName], $args);
        try {
            $this->client->deleteObject($parameters);
            if ($this->verbose) {
                echo "Deleted the object named: $fileName from $bucketName.\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to delete $fileName from $bucketName with error: {$exception->getMessage()}\n";
                echo "Please fix error with object deletion before continuing.";
            }
            throw $exception;
        }
    }



    public function listBuckets(array $args = [])
    {
        try {
            $buckets = $this->client->listBuckets($args);
            if ($this->verbose) {
                echo "Retrieved all " . count($buckets) . "\n";
            }
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to retrieve bucket list with error: {$exception->getMessage()}\n";
                echo "Please fix error with bucket lists before continuing.";
            }
            throw $exception;
        }
        return $buckets;
    }



    public function preSignedUrl(CommandInterface $command, DateTimeInterface|int|string $expires, array $options = [])
    {
        $request = $this->client->createPresignedRequest($command, $expires, $options);
        try {
            $presignedUrl = (string)$request->getUri();
        } catch (AwsException $exception) {
            if ($this->verbose) {
                echo "Failed to create a presigned url: {$exception->getMessage()}\n";
                echo "Please fix error with presigned urls before continuing.";
            }
            throw $exception;
        }
        return $presignedUrl;
    }



    public function createSession(string $bucketName)
    {
        try{
            $result = $this->client->createSession([
                'Bucket' => $bucketName,
            ]);
            return $result;
        }catch(S3Exception $caught){
            if($caught->getAwsErrorType() == "NoSuchBucket"){
                echo "The specified bucket does not exist.";
            }
            throw $caught;
        }
    }

}
```
+ API の詳細については、「*AWS SDK for PHP API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/DeleteBucket)
  + [DeleteObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/DeleteObject)
  + [GetObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/GetObject)
  + [ListObjects](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/ListObjects)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForPHPV3/s3-2006-03-01/PutObject)

# SDK for PHP を使用した Amazon SES の例
<a name="php_3_ses_code_examples"></a>

次のコード例は、Amazon SES AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_php_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for PHP**  
 を使用して AWS SDK for PHP 、Amazon RDS データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信するウェブアプリケーションを作成する方法を示します。この例では、React.js で構築されたフロントエンドを使用して RESTful PHP バックエンドと対話します。  
+ React.js ウェブアプリケーションを AWS サービスに統合します。
+ Amazon RDS テーブル内の項目の一覧表示、追加、更新、削除を行います。
+ Amazon SES を使用して、フィルター処理された作業項目の E メールレポートを送信します。
+ 含まれている AWS CloudFormation スクリプトを使用してサンプルリソースをデプロイおよび管理します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for PHP を使用した Amazon SNS のコードサンプル
<a name="php_3_sns_code_examples"></a>

次のコード例は、Amazon SNS AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CheckIfPhoneNumberIsOptedOut`
<a name="sns_CheckIfPhoneNumberIsOptedOut_php_3_topic"></a>

次のコード例は、`CheckIfPhoneNumberIsOptedOut` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Indicates whether the phone number owner has opted out of receiving SMS messages from your AWS SNS account.
 *
 * 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'
]);

$phone = '+1XXX5550100';

try {
    $result = $SnSclient->checkIfPhoneNumberIsOptedOut([
        'phoneNumber' => $phone,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#check-if-a-phone-number-has-opted-out)」を参照してください。
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[CheckIfPhoneNumberIsOptedOut](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/CheckIfPhoneNumberIsOptedOut)」を参照してください。

### `ConfirmSubscription`
<a name="sns_ConfirmSubscription_php_3_topic"></a>

次のコード例は、`ConfirmSubscription` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Verifies an endpoint owner's intent to receive messages by
 * validating the token sent to the endpoint by an earlier Subscribe action.
 *
 * 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'
]);

$subscription_token = 'arn:aws:sns:us-east-1:111122223333:MyTopic:123456-abcd-12ab-1234-12ba3dc1234a';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->confirmSubscription([
        'Token' => $subscription_token,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ConfirmSubscription](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/ConfirmSubscription)」を参照してください。

### `CreateTopic`
<a name="sns_CreateTopic_php_3_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic)」を参照してください。
+  API の詳細については、AWS SDK for PHP API リファレンスの**「[CreateTopic](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/CreateTopic)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_php_3_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Deletes an SNS topic and all its subscriptions.
 *
 * 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'
]);

$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->deleteTopic([
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[DeleteTopic](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/DeleteTopic)」を参照してください。

### `GetSMSAttributes`
<a name="sns_GetSMSAttributes_php_3_topic"></a>

次のコード例は、`GetSMSAttributes` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Get the type of SMS Message sent by default from the AWS SNS service.
 *
 * 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'
]);

try {
    $result = $SnSclient->getSMSAttributes([
        'attributes' => ['DefaultSMSType'],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#get-sms-attributes)」を参照してください。
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetSMSAttributes](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/GetSMSAttributes)」を参照してください。

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_php_3_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->getTopicAttributes([
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[GetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/GetTopicAttributes)」を参照してください。

### `ListPhoneNumbersOptedOut`
<a name="sns_ListPhoneNumbersOptedOut_php_3_topic"></a>

次のコード例は、`ListPhoneNumbersOptedOut` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Returns a list of phone numbers that are opted out of receiving SMS messages from your AWS SNS account.
 *
 * 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'
]);

try {
    $result = $SnSclient->listPhoneNumbersOptedOut();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#list-opted-out-phone-numbers)」を参照してください。
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListPhoneNumbersOptedOut](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/ListPhoneNumbersOptedOut)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_php_3_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Returns a list of Amazon SNS subscriptions in 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'
]);

try {
    $result = $SnSclient->listSubscriptions();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListSubscriptions](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/ListSubscriptions)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_php_3_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Returns a list of the requester's topics from your AWS SNS account in the region specified.
 *
 * 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'
]);

try {
    $result = $SnSclient->listTopics();
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[ListTopics](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/ListTopics)」を参照してください。

### `Publish`
<a name="sns_Publish_php_3_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Sends a message to an Amazon SNS topic.
 *
 * 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'
]);

$message = 'This message is sent from a Amazon SNS code sample.';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->publish([
        'Message' => $message,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-subscribing-unsubscribing-topics.html#publish-a-message-to-an-sns-topic)」を参照してください。
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Publish](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Publish)」を参照してください。**

### `SetSMSAttributes`
<a name="sns_SetSMSAttributes_php_3_topic"></a>

次のコード例は、`SetSMSAttributes` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

try {
    $result = $SnSclient->SetSMSAttributes([
        'attributes' => [
            'DefaultSMSType' => 'Transactional',
        ],
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#set-sms-attributes)」を参照してください。
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[SetSMSAttributes](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/SetSMSAttributes)」を参照してください。

### `SetTopicAttributes`
<a name="sns_SetTopicAttributes_php_3_topic"></a>

次のコード例は、`SetTopicAttributes` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Configure the message delivery status attributes for an Amazon SNS Topic.
 *
 * 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'
]);
$attribute = 'Policy | DisplayName | DeliveryPolicy';
$value = 'First Topic';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->setTopicAttributes([
        'AttributeName' => $attribute,
        'AttributeValue' => $value,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[SetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/SetTopicAttributes)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_php_3_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Prepares to subscribe an endpoint by sending the endpoint a confirmation message.
 *
 * 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'
]);

$protocol = 'email';
$endpoint = 'sample@example.com';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->subscribe([
        'Protocol' => $protocol,
        'Endpoint' => $endpoint,
        'ReturnSubscriptionArn' => true,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
HTTP エンドポイントをトピックにサブスクライブします。  

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Prepares to subscribe an endpoint by sending the endpoint a confirmation message.
 *
 * 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'
]);

$protocol = 'https';
$endpoint = 'https://';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->subscribe([
        'Protocol' => $protocol,
        'Endpoint' => $endpoint,
        'ReturnSubscriptionArn' => true,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[Subscribe](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Subscribe)」を参照してください。

### `Unsubscribe`
<a name="sns_Unsubscribe_php_3_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Deletes a subscription to an Amazon SNS topic.
 *
 * 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'
]);

$subscription = 'arn:aws:sns:us-east-1:111122223333:MySubscription';

try {
    $result = $SnSclient->unsubscribe([
        'SubscriptionArn' => $subscription,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-subscribing-unsubscribing-topics.html#unsubscribe-from-a-topic)」を参照してください。
+  API の詳細については、*AWS SDK for PHP API リファレンス*の「[Unsubscribe](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Unsubscribe)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_php_3_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for PHP**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/applications/photo_asset_manager) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### SMS テキストメッセージを発行する
<a name="sns_PublishTextSMS_php_3_topic"></a>

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Sends a text message (SMS message) directly to a phone number using Amazon SNS.
 *
 * 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'
]);

$message = 'This message is sent from a Amazon SNS code sample.';
$phone = '+1XXX5550100';

try {
    $result = $SnSclient->publish([
        'Message' => $message,
        'PhoneNumber' => $phone,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  詳細については、「[AWS SDK for PHP デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#publish-to-a-text-message-sms-message)」を参照してください。
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Publish](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Publish)」を参照してください。**

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_php_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用して Lambda で SNS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

/* 
Since native PHP support for AWS Lambda is not available, we are utilizing Bref's PHP functions runtime for AWS Lambda.
For more information on Bref's PHP runtime for Lambda, refer to: https://bref.sh/docs/runtimes/function

Another approach would be to create a custom runtime. 
A practical example can be found here: https://aws.amazon.com/blogs/apn/aws-lambda-custom-runtime-for-php-a-practical-example/
*/

// Additional composer packages may be required when using Bref or any other PHP functions runtime.
// require __DIR__ . '/vendor/autoload.php';

use Bref\Context\Context;
use Bref\Event\Sns\SnsEvent;
use Bref\Event\Sns\SnsHandler;

class Handler extends SnsHandler
{
    public function handleSns(SnsEvent $event, Context $context): void
    {
        foreach ($event->getRecords() as $record) {
            $message = $record->getMessage();

            // TODO: Implement your custom processing logic here
            // Any exception thrown will be logged and the invocation will be marked as failed

            echo "Processed Message: $message" . PHP_EOL;
        }
    }
}

return new Handler();
```

# SDK for PHP を使用した Amazon SQS の例
<a name="php_3_sqs_code_examples"></a>

次のコード例は、Amazon SQS AWS SDK for PHP で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_php_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での SQS イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

# using bref/bref and bref/logger for simplicity

use Bref\Context\Context;
use Bref\Event\InvalidLambdaEvent;
use Bref\Event\Sqs\SqsEvent;
use Bref\Event\Sqs\SqsHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends SqsHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws InvalidLambdaEvent
     */
    public function handleSqs(SqsEvent $event, Context $context): void
    {
        foreach ($event->getRecords() as $record) {
            $body = $record->getBody();
            // TODO: Do interesting work based on the new message
        }
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_php_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for PHP**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
PHP を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
<?php

use Bref\Context\Context;
use Bref\Event\Sqs\SqsEvent;
use Bref\Event\Sqs\SqsHandler;
use Bref\Logger\StderrLogger;

require __DIR__ . '/vendor/autoload.php';

class Handler extends SqsHandler
{
    private StderrLogger $logger;
    public function __construct(StderrLogger $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @throws JsonException
     * @throws \Bref\Event\InvalidLambdaEvent
     */
    public function handleSqs(SqsEvent $event, Context $context): void
    {
        $this->logger->info("Processing SQS records");
        $records = $event->getRecords();

        foreach ($records as $record) {
            try {
                // Assuming the SQS message is in JSON format
                $message = json_decode($record->getBody(), true);
                $this->logger->info(json_encode($message));
                // TODO: Implement your custom processing logic here
            } catch (Exception $e) {
                $this->logger->error($e->getMessage());
                // failed processing the record
                $this->markAsFailed($record);
            }
        }
        $totalRecords = count($records);
        $this->logger->info("Successfully processed $totalRecords SQS records");
    }
}

$logger = new StderrLogger();
return new Handler($logger);
```

# Tools for PowerShell V4 のコード例
<a name="powershell_4_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ Tools for PowerShell V4 デベロッパーガイド ](https://docs.aws.amazon.com/powershell/latest/v4/pstools-welcome.html) ** – で PowerShell を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](powershell_4_acm_code_examples.md)
+ [Application Auto Scaling](powershell_4_application-auto-scaling_code_examples.md)
+ [WorkSpaces Applications](powershell_4_appstream_code_examples.md)
+ [Aurora](powershell_4_aurora_code_examples.md)
+ [Auto Scaling](powershell_4_auto-scaling_code_examples.md)
+ [AWS Budgets](powershell_4_budgets_code_examples.md)
+ [AWS Cloud9](powershell_4_cloud9_code_examples.md)
+ [CloudFormation](powershell_4_cloudformation_code_examples.md)
+ [CloudFront](powershell_4_cloudfront_code_examples.md)
+ [CloudTrail](powershell_4_cloudtrail_code_examples.md)
+ [CloudWatch](powershell_4_cloudwatch_code_examples.md)
+ [CodeCommit](powershell_4_codecommit_code_examples.md)
+ [CodeDeploy](powershell_4_codedeploy_code_examples.md)
+ [CodePipeline](powershell_4_codepipeline_code_examples.md)
+ [Amazon Cognito ID](powershell_4_cognito-identity_code_examples.md)
+ [AWS Config](powershell_4_config-service_code_examples.md)
+ [Device Farm](powershell_4_device-farm_code_examples.md)
+ [Directory Service](powershell_4_directory-service_code_examples.md)
+ [AWS DMS](powershell_4_database-migration-service_code_examples.md)
+ [DynamoDB](powershell_4_dynamodb_code_examples.md)
+ [Amazon EC2](powershell_4_ec2_code_examples.md)
+ [Amazon ECR](powershell_4_ecr_code_examples.md)
+ [Amazon ECS](powershell_4_ecs_code_examples.md)
+ [Amazon EFS](powershell_4_efs_code_examples.md)
+ [Amazon EKS](powershell_4_eks_code_examples.md)
+ [Elastic Load Balancing - バージョン 1](powershell_4_elastic-load-balancing_code_examples.md)
+ [Elastic Load Balancing - バージョン 2](powershell_4_elastic-load-balancing-v2_code_examples.md)
+ [Amazon FSx](powershell_4_fsx_code_examples.md)
+ [Amazon Glacier](powershell_4_glacier_code_examples.md)
+ [AWS Glue](powershell_4_glue_code_examples.md)
+ [AWS Health](powershell_4_health_code_examples.md)
+ [IAM](powershell_4_iam_code_examples.md)
+ [Kinesis](powershell_4_kinesis_code_examples.md)
+ [Lambda](powershell_4_lambda_code_examples.md)
+ [Amazon ML](powershell_4_machine-learning_code_examples.md)
+ [Macie](powershell_4_macie2_code_examples.md)
+ [AWS の料金表](powershell_4_pricing_code_examples.md)
+ [リソースグループ](powershell_4_resource-groups_code_examples.md)
+ [リソースグループタグ付け API](powershell_4_resource-groups-tagging-api_code_examples.md)
+ [Route 53](powershell_4_route-53_code_examples.md)
+ [Amazon S3](powershell_4_s3_code_examples.md)
+ [Security Hub CSPM](powershell_4_securityhub_code_examples.md)
+ [Amazon SES](powershell_4_ses_code_examples.md)
+ [Amazon SES API v2](powershell_4_sesv2_code_examples.md)
+ [Amazon SNS](powershell_4_sns_code_examples.md)
+ [Amazon SQS](powershell_4_sqs_code_examples.md)
+ [AWS STS](powershell_4_sts_code_examples.md)
+ [サポート](powershell_4_support_code_examples.md)
+ [Systems Manager](powershell_4_ssm_code_examples.md)
+ [Amazon Translate](powershell_4_translate_code_examples.md)
+ [AWS WAFV2](powershell_4_wafv2_code_examples.md)
+ [WorkSpaces](powershell_4_workspaces_code_examples.md)

# Tools for PowerShell V4 を使用した ACM の例
<a name="powershell_4_acm_code_examples"></a>

次のコード例は、ACM で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-ACMCertificate`
<a name="acm_GetCertificate_powershell_4_topic"></a>

次のコード例は、`Get-ACMCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、証明書の ARN を使用して証明書とそのチェーンを返す方法を示します。**  

```
Get-ACMCertificate -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ACMCertificateDetail`
<a name="acm_DescribeCertificate_powershell_4_topic"></a>

次のコード例は、`Get-ACMCertificateDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定した証明書の詳細を返します。**  

```
Get-ACMCertificateDetail -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
**出力:**  

```
CertificateArn          : arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
CreatedAt               : 1/21/2016 5:55:59 PM
DomainName              : www.example.com
DomainValidationOptions : {www.example.com}
InUseBy                 : {}
IssuedAt                : 1/1/0001 12:00:00 AM
Issuer                  :
KeyAlgorithm            : RSA-2048
NotAfter                : 1/1/0001 12:00:00 AM
NotBefore               : 1/1/0001 12:00:00 AM
RevocationReason        :
RevokedAt               : 1/1/0001 12:00:00 AM
Serial                  :
SignatureAlgorithm      : SHA256WITHRSA
Status                  : PENDING_VALIDATION
Subject                 : CN=www.example.com
SubjectAlternativeNames : {www.example.net}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ACMCertificateList`
<a name="acm_ListCertificates_powershell_4_topic"></a>

次のコード例は、`Get-ACMCertificateList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 証明書の ARN のリストと各 ARN のドメイン名を取得します。コマンドレットは自動的にページ分割され、すべての ARN を取得します。ページ分割を手動で制御するには、-MaxItem パラメータを使用して各サービス呼び出しに対して返される証明書 ARN の数を制御し、-NextToken パラメータを使用して各呼び出しの開始点を示します。**  

```
Get-ACMCertificateList
```
**出力:**  

```
CertificateArn                                                                      DomainName
--------------                                                                      ----------
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012 www.example.com
```
**例 2: 指定された状態に証明書の状態が一致するすべての証明書 ARN のリストを取得します。**  

```
Get-ACMCertificateList -CertificateStatus "VALIDATION_TIMED_OUT","FAILED"
```
**例 3: この例では、キータイプが RSA\$12048、拡張キーの使用法または目的が CODE\$1SIGNING である、us-east-1 リージョン内のすべての証明書のリストを返します。これらのフィルタリングパラメータの値については、API リファレンスの「ListCertificates Filters」トピック: https://docs.aws.amazon.com/acm/latest/APIReference/API\$1Filters.html を参照してください。**  

```
Get-ACMCertificateList -Region us-east-1 -Includes_KeyType RSA_2048 -Includes_ExtendedKeyUsage CODE_SIGNING
```
**出力:**  

```
CertificateArn                                                                      DomainName                
--------------                                                                      ----------                
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-d7c0-48c1-af8d-2133d8f30zzz *.route53docs.com
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-98a5-443d-a734-800430c80zzz nerdzizm.net               
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-2be6-4376-8fa7-bad559525zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-e7ca-44c5-803e-24d9f2f36zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-1241-4b71-80b1-090305a62zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-8709-4568-8c64-f94617c99zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-a8fa-4a61-98cf-e08ccc0eezzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-fa47-40fe-a714-2d277d3eezzz *.route53docs.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListCertificates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ACMCertificate`
<a name="acm_RequestCertificate_powershell_4_topic"></a>

次のコード例は、`New-ACMCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 新しい証明書を作成します。サービスは新しい証明書の ARN を返します。**  

```
New-ACMCertificate -DomainName "www.example.com"
```
**出力:**  

```
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
```
**例 2: 新しい証明書を作成します。サービスは新しい証明書の ARN を返します。**  

```
New-ACMCertificate -DomainName "www.example.com" -SubjectAlternativeName "example.com","www.example.net"
```
**出力:**  

```
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の[RequestCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ACMCertificate`
<a name="acm_DeleteCertificate_powershell_4_topic"></a>

次のコード例は、`Remove-ACMCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された ARN で識別される証明書および関連するプライベートキーを削除します。コマンドレットは、操作を続行する前に確認を求めます。確認を表示しないようにするには、-Force スイッチを追加します。**  

```
Remove-ACMCertificate -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Send-ACMValidationEmail`
<a name="acm_ResendValidationEmail_powershell_4_topic"></a>

次のコード例は、`Send-ACMValidationEmail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「www.example.com」のドメイン所有権を検証する E メールの送信をリクエストします。シェルの \$1ConfirmPreference が「Medium」以下に設定されている場合、コマンドレットは続行する前に確認を求めます。-Force スイッチを追加すると、確認メッセージが表示されなくなります。**  

```
$params = @{
    CertificateArn="arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
    Domain="www.example.com"
    ValidationDomain="example.com"    
}        
Send-ACMValidationEmail @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResendValidationEmail](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Application Auto Scaling の例
<a name="powershell_4_application-auto-scaling_code_examples"></a>

次のコード例は、Application Auto Scaling で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-AASScalableTarget`
<a name="application-auto-scaling_RegisterScalableTarget_powershell_4_topic"></a>

次のコード例は、`Add-AASScalableTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、スケーラブルなターゲットを登録または更新します。スケーラブルターゲットとは、Application Auto Scaling がスケールアウトおよびスケールインできるリソースです。**  

```
Add-AASScalableTarget -ServiceNamespace AppStream -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -MinCapacity 2 -MaxCapacity 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterScalableTarget](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-AASScalableTarget`
<a name="application-auto-scaling_DescribeScalableTargets_powershell_4_topic"></a>

次のコード例は、`Get-AASScalableTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前空間内の Application Autoscaling Scalable ターゲットに関する情報を提供します。**  

```
Get-AASScalableTarget -ServiceNamespace "AppStream"
```
**出力:**  

```
CreationTime      : 11/7/2019 2:30:03 AM
MaxCapacity       : 5
MinCapacity       : 1
ResourceId        : fleet/Test
RoleARN           : arn:aws:iam::012345678912:role/aws-service-role/appstream.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_AppStreamFleet
ScalableDimension : appstream:fleet:DesiredCapacity
ServiceNamespace  : appstream
SuspendedState    : Amazon.ApplicationAutoScaling.Model.SuspendedState
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScalableTargets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-AASScalingActivity`
<a name="application-auto-scaling_DescribeScalingActivities_powershell_4_topic"></a>

次のコード例は、`Get-AASScalingActivity` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された名前空間における過去 6 週間のスケーリングアクティビティに関する詳細情報を提供します。**  

```
Get-AASScalingActivity -ServiceNamespace AppStream
```
**出力:**  

```
ActivityId        : 2827409f-b639-4cdb-a957-8055d5d07434
Cause             : monitor alarm Appstream2-MyFleet-default-scale-in-Alarm in state ALARM triggered policy default-scale-in
Description       : Setting desired capacity to 2.
Details           :
EndTime           : 12/14/2019 11:32:49 AM
ResourceId        : fleet/MyFleet
ScalableDimension : appstream:fleet:DesiredCapacity
ServiceNamespace  : appstream
StartTime         : 12/14/2019 11:32:14 AM
StatusCode        : Successful
StatusMessage     : Successfully set desired capacity to 2. Change successfully fulfilled by appstream.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-AASScalingPolicy`
<a name="application-auto-scaling_DescribeScalingPolicies_powershell_4_topic"></a>

次のコード例は、`Get-AASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、指定されたサービス名前空間の Application Auto Scaling スケーリングポリシーを記述します。**  

```
Get-AASScalingPolicy -ServiceNamespace AppStream
```
**出力:**  

```
Alarms                                   : {Appstream2-LabFleet-default-scale-out-Alarm}
CreationTime                             : 9/3/2019 2:48:15 AM
PolicyARN                                : arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:5659b069-b5cd-4af1-9f7f-3e956d36233e:resource/appstream/fleet/LabFleet:
                                           policyName/default-scale-out
PolicyName                               : default-scale-out
PolicyType                               : StepScaling
ResourceId                               : fleet/LabFleet
ScalableDimension                        : appstream:fleet:DesiredCapacity
ServiceNamespace                         : appstream
StepScalingPolicyConfiguration           : Amazon.ApplicationAutoScaling.Model.StepScalingPolicyConfiguration
TargetTrackingScalingPolicyConfiguration :

Alarms                                   : {Appstream2-LabFleet-default-scale-in-Alarm}
CreationTime                             : 9/3/2019 2:48:15 AM
PolicyARN                                : arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:5659b069-b5cd-4af1-9f7f-3e956d36233e:resource/appstream/fleet/LabFleet:
                                           policyName/default-scale-in
PolicyName                               : default-scale-in
PolicyType                               : StepScaling
ResourceId                               : fleet/LabFleet
ScalableDimension                        : appstream:fleet:DesiredCapacity
ServiceNamespace                         : appstream
StepScalingPolicyConfiguration           : Amazon.ApplicationAutoScaling.Model.StepScalingPolicyConfiguration
TargetTrackingScalingPolicyConfiguration :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScalingPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-AASScheduledAction`
<a name="application-auto-scaling_DescribeScheduledActions_powershell_4_topic"></a>

次のコード例は、`Get-AASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットには、Auto Scaling グループにスケジュールされた、実行されていないか終了時刻に達していないアクションが一覧表示されます。 **  

```
Get-AASScheduledAction -ServiceNamespace AppStream
```
**出力:**  

```
CreationTime         : 12/22/2019 9:25:52 AM
EndTime              : 1/1/0001 12:00:00 AM
ResourceId           : fleet/MyFleet
ScalableDimension    : appstream:fleet:DesiredCapacity
ScalableTargetAction : Amazon.ApplicationAutoScaling.Model.ScalableTargetAction
Schedule             : cron(0 0 8 ? * MON-FRI *)
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:012345678912:scheduledAction:4897ca24-3caa-4bf1-8484-851a089b243c:resource/appstream/fleet/MyFleet:scheduledActionName
                       /WeekDaysFleetScaling
ScheduledActionName  : WeekDaysFleetScaling
ServiceNamespace     : appstream
StartTime            : 1/1/0001 12:00:00 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-AASScalableTarget`
<a name="application-auto-scaling_DeregisterScalableTarget_powershell_4_topic"></a>

次のコード例は、`Remove-AASScalableTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Application Auto Scaling のスケーラブルターゲットを登録解除します。スケーラブルターゲットの登録を解除すると、それに関連付けられているスケーリングポリシーが削除されます。**  

```
Remove-AASScalableTarget -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -ServiceNamespace AppStream
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-AASScalableTarget (DeregisterScalableTarget)" on target "fleet/MyFleet".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[DeregisterScalableTarget](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Remove-AASScalingPolicy`
<a name="application-auto-scaling_DeleteScalingPolicy_powershell_4_topic"></a>

次のコード例は、`Remove-AASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Application Auto Scaling スケーラブルターゲットの指定されたスケーリングポリシーを削除します。**  

```
Remove-AASScalingPolicy -ServiceNamespace AppStream -PolicyName "default-scale-out" -ResourceId fleet/Test -ScalableDimension appstream:fleet:DesiredCapacity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteScalingPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-AASScheduledAction`
<a name="application-auto-scaling_DeleteScheduledAction_powershell_4_topic"></a>

次のコード例は、`Remove-AASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Application Auto Scaling スケーラブルターゲットの指定されたスケジュールされたアクションを削除します。**  

```
Remove-AASScheduledAction -ServiceNamespace AppStream -ScheduledActionName WeekDaysFleetScaling -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-AASScheduledAction (DeleteScheduledAction)" on target "WeekDaysFleetScaling".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-AASScalingPolicy`
<a name="application-auto-scaling_PutScalingPolicy_powershell_4_topic"></a>

次のコード例は、`Set-AASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Application Auto Scaling のスケーラブルターゲットのポリシーを作成または更新します。各スケーラブルターゲットは、サービス名前空間、リソース ID、スケーラブルなディメンションによって識別されます。**  

```
Set-AASScalingPolicy -ServiceNamespace AppStream -PolicyName ASFleetScaleInPolicy -PolicyType StepScaling  -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -StepScalingPolicyConfiguration_AdjustmentType ChangeInCapacity -StepScalingPolicyConfiguration_Cooldown 360 -StepScalingPolicyConfiguration_MetricAggregationType Average -StepScalingPolicyConfiguration_StepAdjustments @{ScalingAdjustment = -1; MetricIntervalUpperBound = 0}
```
**出力:**  

```
Alarms    PolicyARN
------    ---------
{}        arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:4897ca24-3caa-4bf1-8484-851a089b243c:resource/appstream/fleet/MyFleet:policyName/ASFleetScaleInPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutScalingPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-AASScheduledAction`
<a name="application-auto-scaling_PutScheduledAction_powershell_4_topic"></a>

次のコード例は、`Set-AASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Application Auto Scaling のスケーラブルターゲットのスケジュールされたアクションを作成または更新します。各スケーラブルターゲットは、サービス名前空間、リソース ID、スケーラブルなディメンションによって識別されます。**  

```
Set-AASScheduledAction -ServiceNamespace AppStream -ResourceId fleet/MyFleet -Schedule "cron(0 0 8 ? * MON-FRI *)" -ScalableDimension appstream:fleet:DesiredCapacity -ScheduledActionName WeekDaysFleetScaling -ScalableTargetAction_MinCapacity 5 -ScalableTargetAction_MaxCapacity 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutScheduledAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した WorkSpaces Applications の例
<a name="powershell_4_appstream_code_examples"></a>

次のコード例は、WorkSpaces アプリケーションで AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-APSResourceTag`
<a name="appstream_TagResource_powershell_4_topic"></a>

次のコード例は、`Add-APSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream リソースにリソースタグを追加します。**  

```
Add-APSResourceTag -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest -Tag @{StackState='Test'} -Select ^Tag
```
**出力:**  

```
Name                           Value
----                           -----
StackState                     Test
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Copy-APSImage`
<a name="appstream_CopyImage_powershell_4_topic"></a>

次のコード例は、`Copy-APSImage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、画像を他のリージョンにコピーします**  

```
Copy-APSImage -DestinationImageName TestImageCopy -DestinationRegion us-west-2 -SourceImageName Powershell
```
**出力:**  

```
TestImageCopy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CopyImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-APSUSer`
<a name="appstream_DisableUser_powershell_4_topic"></a>

次のコード例は、`Disable-APSUSer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、USERPOOL のユーザーを無効にします**  

```
Disable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-APSUser`
<a name="appstream_EnableUser_powershell_4_topic"></a>

次のコード例は、`Enable-APSUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、USERPOOL で無効になっているユーザーを有効にします**  

```
Enable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSAssociatedFleetList`
<a name="appstream_ListAssociatedFleets_powershell_4_topic"></a>

次のコード例は、`Get-APSAssociatedFleetList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スタックに関連付けられたフリートを表示します**  

```
Get-APSAssociatedFleetList -StackName PowershellStack
```
**出力:**  

```
PowershellFleet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAssociatedFleets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSAssociatedStackList`
<a name="appstream_ListAssociatedStacks_powershell_4_topic"></a>

次のコード例は、`Get-APSAssociatedStackList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、フリートに関連付けられたスタックを表示します**  

```
Get-APSAssociatedStackList -FleetName PowershellFleet
```
**出力:**  

```
PowershellStack
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAssociatedStacks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSDirectoryConfigList`
<a name="appstream_DescribeDirectoryConfigs_powershell_4_topic"></a>

次のコード例は、`Get-APSDirectoryConfigList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream で作成されたディレクトリ設定を表示します**  

```
Get-APSDirectoryConfigList | Select DirectoryName, OrganizationalUnitDistinguishedNames, CreatedTime
```
**出力:**  

```
DirectoryName OrganizationalUnitDistinguishedNames CreatedTime
------------- ------------------------------------ -----------
Test.com      {OU=AppStream,DC=Test,DC=com}    9/6/2019 10:56:40 AM
contoso.com   {OU=AppStream,OU=contoso,DC=contoso,DC=com}  8/9/2019 9:08:50 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDirectoryConfigs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSFleetList`
<a name="appstream_DescribeFleets_powershell_4_topic"></a>

次のコード例は、`Get-APSFleetList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、フリートの詳細を表示します**  

```
Get-APSFleetList -Name Test
```
**出力:**  

```
Arn                            : arn:aws:appstream:us-east-1:1234567890:fleet/Test
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 9/12/2019 5:00:45 PM
Description                    : Test
DisconnectTimeoutInSeconds     : 900
DisplayName                    : Test
DomainJoinInfo                 :
EnableDefaultInternetAccess    : False
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 900
ImageArn                       : arn:aws:appstream:us-east-1:1234567890:image/Test
ImageName                      : Test
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : Test
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeFleets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSImageBuilderList`
<a name="appstream_DescribeImageBuilders_powershell_4_topic"></a>

次のコード例は、`Get-APSImageBuilderList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ImageBuilder の詳細を表示します**  

```
Get-APSImageBuilderList -Name TestImage
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:1234567890:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : STOPPED
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeImageBuilders](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSImageList`
<a name="appstream_DescribeImages_powershell_4_topic"></a>

次のコード例は、`Get-APSImageList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、プライベート AppStream イメージを表示します**  

```
Get-APSImageList -Type PRIVATE | select DisplayName, ImageBuilderName, Visibility, arn
```
**出力:**  

```
DisplayName          ImageBuilderName      Visibility Arn
-----------          ----------------      ---------- ---
OfficeApps           OfficeApps            PRIVATE    arn:aws:appstream:us-east-1:123456789012:image/OfficeApps
SessionScriptV2      SessionScriptTest     PRIVATE    arn:aws:appstream:us-east-1:123456789012:image/SessionScriptV2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeImages](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSImagePermission`
<a name="appstream_DescribeImagePermissions_powershell_4_topic"></a>

次のコード例は、`Get-APSImagePermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、共有 AppStream イメージへのアクセス許可を表示します**  

```
Get-APSImagePermission -Name Powershell  | select SharedAccountId, @{n="AllowFleet";e={$_.ImagePermissions.AllowFleet}}, @{n="AllowImageBuilder";e={$_.ImagePermissions.AllowImageBuilder}}
```
**出力:**  

```
SharedAccountId AllowFleet AllowImageBuilder
--------------- ---------- -----------------
123456789012          True              True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeImagePermissions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSSessionList`
<a name="appstream_DescribeSessions_powershell_4_topic"></a>

次のコード例は、`Get-APSSessionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、フリートへのセッションのリストを表示します。**  

```
Get-APSSessionList -FleetName PowershellFleet -StackName PowershellStack
```
**出力:**  

```
AuthenticationType         : API
ConnectionState            : CONNECTED
FleetName                  : PowershellFleet
Id                         : d8987c70-4394-4324-a396-2d485c26f2a2
MaxExpirationTime          : 12/27/2019 4:54:07 AM
NetworkAccessConfiguration : Amazon.AppStream.Model.NetworkAccessConfiguration
StackName                  : PowershellStack
StartTime                  : 12/26/2019 12:54:12 PM
State                      : ACTIVE
UserId                     : Test
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSessions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSStackList`
<a name="appstream_DescribeStacks_powershell_4_topic"></a>

次のコード例は、`Get-APSStackList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream スタックのリストを表示します**  

```
Get-APSStackList | Select DisplayName, Arn, CreatedTime
```
**出力:**  

```
DisplayName                   Arn                                                                          CreatedTime
-----------                   ---                                                                          -----------
PowershellStack               arn:aws:appstream:us-east-1:123456789012:stack/PowershellStack               4/24/2019 8:49:29 AM
SessionScriptTest             arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest             9/12/2019 3:23:12 PM
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DescribeStacks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSTagsForResourceList`
<a name="appstream_ListTagsForResource_powershell_4_topic"></a>

次のコード例は、`Get-APSTagsForResourceList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream リソースのタグを表示します**  

```
Get-APSTagsForResourceList -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest
```
**出力:**  

```
Key        Value
---        -----
StackState Test
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSUsageReportSubscription`
<a name="appstream_DescribeUsageReportSubscriptions_powershell_4_topic"></a>

次のコード例は、`Get-APSUsageReportSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStreamUsageReport 設定の詳細を表示します**  

```
Get-APSUsageReportSubscription
```
**出力:**  

```
LastGeneratedReportDate S3BucketName                                   Schedule SubscriptionErrors
----------------------- ------------                                   -------- ------------------
1/1/0001 12:00:00 AM    appstream-logs-us-east-1-123456789012-sik1hnxe DAILY    {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeUsageReportSubscriptions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSUser`
<a name="appstream_DescribeUsers_powershell_4_topic"></a>

次のコード例は、`Get-APSUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ステータスが有効なユーザーのリストを表示します**  

```
Get-APSUser -AuthenticationType USERPOOL | Select-Object UserName, AuthenticationType, Enabled
```
**出力:**  

```
UserName                   AuthenticationType Enabled
--------                   ------------------ -------
foo1@contoso.com USERPOOL              True
foo2@contoso.com        USERPOOL              True
foo3@contoso.com    USERPOOL              True
foo4@contoso.com   USERPOOL              True
foo5@contoso.com         USERPOOL              True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeUsers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-APSUserStackAssociation`
<a name="appstream_DescribeUserStackAssociations_powershell_4_topic"></a>

次のコード例は、`Get-APSUserStackAssociation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スタックに割り当てられたユーザーのリストを表示します**  

```
Get-APSUserStackAssociation -StackName PowershellStack
```
**出力:**  

```
AuthenticationType SendEmailNotification StackName       UserName
------------------ --------------------- ---------       --------
USERPOOL           False                 PowershellStack TestUser1@lab.com
USERPOOL           False                 PowershellStack TestUser2@lab.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeUserStackAssociations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSDirectoryConfig`
<a name="appstream_CreateDirectoryConfig_powershell_4_topic"></a>

次のコード例は、`New-APSDirectoryConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream にディレクトリ設定を作成します**  

```
New-APSDirectoryConfig -ServiceAccountCredentials_AccountName contoso\ServiceAccount -ServiceAccountCredentials_AccountPassword MyPass -DirectoryName contoso.com -OrganizationalUnitDistinguishedName "OU=AppStream,OU=Contoso,DC=Contoso,DC=com"
```
**出力:**  

```
CreatedTime            DirectoryName OrganizationalUnitDistinguishedNames        ServiceAccountCredentials
-----------            ------------- ------------------------------------        -------------------------
12/27/2019 11:00:30 AM contoso.com   {OU=AppStream,OU=Contoso,DC=Contoso,DC=com} Amazon.AppStream.Model.ServiceAccountCredentials
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDirectoryConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSFleet`
<a name="appstream_CreateFleet_powershell_4_topic"></a>

次のコード例は、`New-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しい AppStream フリートを作成します**  

```
New-APSFleet -ComputeCapacity_DesiredInstance 1 -InstanceType stream.standard.medium -Name TestFleet -DisplayName TestFleet -FleetType ON_DEMAND -EnableDefaultInternetAccess $True -VpcConfig_SubnetIds "subnet-123ce32","subnet-a1234cfd" -VpcConfig_SecurityGroupIds sg-4d012a34 -ImageName SessionScriptTest -Region us-west-2
```
**出力:**  

```
Arn                            : arn:aws:appstream:us-west-2:123456789012:fleet/TestFleet
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 12/27/2019 11:24:42 AM
Description                    :
DisconnectTimeoutInSeconds     : 900
DisplayName                    : TestFleet
DomainJoinInfo                 :
EnableDefaultInternetAccess    : True
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 0
ImageArn                       : arn:aws:appstream:us-west-2:123456789012:image/SessionScriptTest
ImageName                      : SessionScriptTest
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : TestFleet
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSImageBuilder`
<a name="appstream_CreateImageBuilder_powershell_4_topic"></a>

次のコード例は、`New-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream に Image Builder を作成します**  

```
New-APSImageBuilder -InstanceType stream.standard.medium -Name TestIB -DisplayName TestIB -ImageName AppStream-WinServer2012R2-12-12-2019 -EnableDefaultInternetAccess $True -VpcConfig_SubnetId subnet-a1234cfd -VpcConfig_SecurityGroupIds sg-2d012a34 -Region us-west-2
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 12-16-2019
Arn                         : arn:aws:appstream:us-west-2:123456789012:image-builder/TestIB
CreatedTime                 : 12/27/2019 11:39:24 AM
Description                 :
DisplayName                 : TestIB
DomainJoinInfo              :
EnableDefaultInternetAccess : True
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-west-2::image/AppStream-WinServer2012R2-12-12-2019
ImageBuilderErrors          : {}
InstanceType                : stream.standard.medium
Name                        : TestIB
NetworkAccessConfiguration  :
Platform                    : WINDOWS
State                       : PENDING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateImageBuilder](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSImageBuilderStreamingURL`
<a name="appstream_CreateImageBuilderStreamingURL_powershell_4_topic"></a>

次のコード例は、`New-APSImageBuilderStreamingURL` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、有効期間が 2 時間の ImageBuilder ストリーミング URL を作成します。**  

```
New-APSImageBuilderStreamingURL -Name TestIB -Validity 7200 -Region us-west-2
```
**出力:**  

```
Expires               StreamingURL
-------               ------------
12/27/2019 1:49:13 PM https://appstream2.us-west-2.aws.amazon.com/authenticate?parameters=eyJ0eXBlIjoiQURNSU4iLCJleHBpcmVzIjoiMTU3NzQ1NDU1MyIsImF3c0FjY291bnRJZCI6IjM5MzQwMzgxMTQwNyIsInVzZXJJZCI6ImFkbWluIiwiY2F
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateImageBuilderStreamingURL](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSStack`
<a name="appstream_CreateStack_powershell_4_topic"></a>

次のコード例は、`New-APSStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しい AppStream スタックを作成します。**  

```
New-APSStack -Name TestStack -DisplayName TestStack -ApplicationSettings_Enabled $True -ApplicationSettings_SettingsGroup TestStack -Region us-west-2
```
**出力:**  

```
AccessEndpoints     : {}
ApplicationSettings : Amazon.AppStream.Model.ApplicationSettingsResponse
Arn                 : arn:aws:appstream:us-west-2:123456789012:stack/TestStack
CreatedTime         : 12/27/2019 12:34:19 PM
Description         :
DisplayName         : TestStack
EmbedHostDomains    : {}
FeedbackURL         :
Name                : TestStack
RedirectURL         :
StackErrors         : {}
StorageConnectors   : {}
UserSettings        : {Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting}
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[CreateStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSStreamingURL`
<a name="appstream_CreateStreamingURL_powershell_4_topic"></a>

次のコード例は、`New-APSStreamingURL` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スタックのストリーミング URL を作成します**  

```
New-APSStreamingURL -StackName SessionScriptTest -FleetName SessionScriptNew -UserId TestUser
```
**出力:**  

```
Expires                StreamingURL
-------                ------------
12/27/2019 12:43:37 PM https://appstream2.us-east-1.aws.amazon.com/authenticate?parameters=eyJ0eXBlIjoiRU5EX1VTRVIiLCJleHBpcmVzIjoiMTU3NzQ1MDYxNyIsImF3c0FjY291bnRJZCI6IjM5MzQwMzgxMTQwNyIsInVzZXJJZCI6IlRlc3RVc2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateStreamingURL](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSUsageReportSubscription`
<a name="appstream_CreateUsageReportSubscription_powershell_4_topic"></a>

次のコード例は、`New-APSUsageReportSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream 使用状況レポートを有効にします**  

```
New-APSUsageReportSubscription
```
**出力:**  

```
S3BucketName                                   Schedule
------------                                   --------
appstream-logs-us-east-1-123456789012-sik2hnxe DAILY
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateUsageReportSubscription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-APSUser`
<a name="appstream_CreateUser_powershell_4_topic"></a>

次のコード例は、`New-APSUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、USERPOOL にユーザーを作成します**  

```
New-APSUser -UserName Test@lab.com -AuthenticationType USERPOOL -FirstName 'kt' -LastName 'aws' -Select ^UserName
```
**出力:**  

```
Test@lab.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-APSFleet`
<a name="appstream_AssociateFleet_powershell_4_topic"></a>

次のコード例は、`Register-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、フリートをスタックに登録します**  

```
Register-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssociateFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-APSUserStackBatch`
<a name="appstream_BatchAssociateUserStack_powershell_4_topic"></a>

次のコード例は、`Register-APSUserStackBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、USERPOOL のユーザーにスタックを割り当てます**  

```
Register-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchAssociateUserStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSDirectoryConfig`
<a name="appstream_DeleteDirectoryConfig_powershell_4_topic"></a>

次のコード例は、`Remove-APSDirectoryConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream ディレクトリ設定を削除します**  

```
Remove-APSDirectoryConfig -DirectoryName contoso.com
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSDirectoryConfig (DeleteDirectoryConfig)" on target "contoso.com".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteDirectoryConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSFleet`
<a name="appstream_DeleteFleet_powershell_4_topic"></a>

次のコード例は、`Remove-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream フリートを削除します**  

```
Remove-APSFleet -Name TestFleet -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSFleet (DeleteFleet)" on target "TestFleet".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSImage`
<a name="appstream_DeleteImage_powershell_4_topic"></a>

次のコード例は、`Remove-APSImage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、イメージを削除します**  

```
Remove-APSImage -Name TestImage -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImage (DeleteImage)" on target "TestImage".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A

Applications                : {}
AppstreamAgentVersion       : LATEST
Arn                         : arn:aws:appstream:us-west-2:123456789012:image/TestImage
BaseImageArn                :
CreatedTime                 : 12/27/2019 1:34:10 PM
Description                 :
DisplayName                 : TestImage
ImageBuilderName            :
ImageBuilderSupported       : True
ImagePermissions            :
Name                        : TestImage
Platform                    : WINDOWS
PublicBaseImageReleasedDate : 6/12/2018 12:00:00 AM
State                       : AVAILABLE
StateChangeReason           :
Visibility                  : PRIVATE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSImageBuilder`
<a name="appstream_DeleteImageBuilder_powershell_4_topic"></a>

次のコード例は、`Remove-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ImageBuilder を削除します**  

```
Remove-APSImageBuilder -Name TestIB -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImageBuilder (DeleteImageBuilder)" on target "TestIB".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A

AccessEndpoints             : {}
AppstreamAgentVersion       : 12-16-2019
Arn                         : arn:aws:appstream:us-west-2:123456789012:image-builder/TestIB
CreatedTime                 : 12/27/2019 11:39:24 AM
Description                 :
DisplayName                 : TestIB
DomainJoinInfo              :
EnableDefaultInternetAccess : True
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-west-2::image/AppStream-WinServer2012R2-12-12-2019
ImageBuilderErrors          : {}
InstanceType                : stream.standard.medium
Name                        : TestIB
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : DELETING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteImageBuilder](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSImagePermission`
<a name="appstream_DeleteImagePermissions_powershell_4_topic"></a>

次のコード例は、`Remove-APSImagePermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、イメージへのアクセス許可を削除します**  

```
Remove-APSImagePermission -Name Powershell -SharedAccountId 123456789012
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImagePermission (DeleteImagePermissions)" on target "Powershell".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteImagePermissions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSResourceTag`
<a name="appstream_UntagResource_powershell_4_topic"></a>

次のコード例は、`Remove-APSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream リソースからリソースタグを削除します**  

```
Remove-APSResourceTag -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest -TagKey StackState
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSResourceTag (UntagResource)" on target "arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UntagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSStack`
<a name="appstream_DeleteStack_powershell_4_topic"></a>

次のコード例は、`Remove-APSStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スタックを削除します**  

```
Remove-APSStack -Name TestStack -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSStack (DeleteStack)" on target "TestStack".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DeleteStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSUsageReportSubscription`
<a name="appstream_DeleteUsageReportSubscription_powershell_4_topic"></a>

次のコード例は、`Remove-APSUsageReportSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream 使用状況レポートのサブスクリプションを無効にします**  

```
Remove-APSUsageReportSubscription
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSUsageReportSubscription (DeleteUsageReportSubscription)" on target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)*) の「[DeleteUsageReportSubscription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-APSUser`
<a name="appstream_DeleteUser_powershell_4_topic"></a>

次のコード例は、`Remove-APSUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、USERPOOL からユーザーを削除します**  

```
Remove-APSUser -UserName TestUser@lab.com -AuthenticationType USERPOOL
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSUser (DeleteUser)" on target "TestUser@lab.com".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Revoke-APSSession`
<a name="appstream_ExpireSession_powershell_4_topic"></a>

次のコード例は、`Revoke-APSSession` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream フリートへのセッションを取り消します**  

```
Revoke-APSSession -SessionId 6cd2f9a3-f948-4aa1-8014-8a7dcde14877
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ExpireSession](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-APSFleet`
<a name="appstream_StartFleet_powershell_4_topic"></a>

次のコード例は、`Start-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、フリートを開始します**  

```
Start-APSFleet -Name PowershellFleet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-APSImageBuilder`
<a name="appstream_StartImageBuilder_powershell_4_topic"></a>

次のコード例は、`Start-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ImageBuilder を起動します**  

```
Start-APSImageBuilder -Name TestImage
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:123456789012:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : PENDING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartImageBuilder](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-APSFleet`
<a name="appstream_StopFleet_powershell_4_topic"></a>

次のコード例は、`Stop-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、フリートを停止します**  

```
Stop-APSFleet -Name PowershellFleet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StopFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-APSImageBuilder`
<a name="appstream_StopImageBuilder_powershell_4_topic"></a>

次のコード例は、`Stop-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ImageBuilder を停止します**  

```
Stop-APSImageBuilder -Name TestImage
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:123456789012:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : STOPPING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StopImageBuilder](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-APSFleet`
<a name="appstream_DisassociateFleet_powershell_4_topic"></a>

次のコード例は、`Unregister-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スタックからフリートを登録解除します**  

```
Unregister-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisassociateFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-APSUserStackBatch`
<a name="appstream_BatchDisassociateUserStack_powershell_4_topic"></a>

次のコード例は、`Unregister-APSUserStackBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、割り当てられたスタックからユーザーを削除します**  

```
Unregister-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchDisassociateUserStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-APSDirectoryConfig`
<a name="appstream_UpdateDirectoryConfig_powershell_4_topic"></a>

次のコード例は、`Update-APSDirectoryConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream で作成されたディレクトリ設定を更新します。**  

```
Update-APSDirectoryConfig -ServiceAccountCredentials_AccountName contoso\ServiceAccount -ServiceAccountCredentials_AccountPassword MyPass@1$@# -DirectoryName contoso.com -OrganizationalUnitDistinguishedName "OU=AppStreamNew,OU=Contoso,DC=Contoso,DC=com"
```
**出力:**  

```
CreatedTime           DirectoryName OrganizationalUnitDistinguishedNames           ServiceAccountCredentials
-----------           ------------- ------------------------------------           -------------------------
12/27/2019 3:50:02 PM contoso.com   {OU=AppStreamNew,OU=Contoso,DC=Contoso,DC=com} Amazon.AppStream.Model.ServiceAccountCredentials
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateDirectoryConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-APSFleet`
<a name="appstream_UpdateFleet_powershell_4_topic"></a>

次のコード例は、`Update-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、フリートのプロパティを更新します**  

```
Update-APSFleet -Name PowershellFleet -EnableDefaultInternetAccess $True -DisconnectTimeoutInSecond 950
```
**出力:**  

```
Arn                            : arn:aws:appstream:us-east-1:123456789012:fleet/PowershellFleet
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 4/24/2019 8:39:41 AM
Description                    : PowershellFleet
DisconnectTimeoutInSeconds     : 950
DisplayName                    : PowershellFleet
DomainJoinInfo                 :
EnableDefaultInternetAccess    : True
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 900
ImageArn                       : arn:aws:appstream:us-east-1:123456789012:image/Powershell
ImageName                      : Powershell
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : PowershellFleet
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-APSImagePermission`
<a name="appstream_UpdateImagePermissions_powershell_4_topic"></a>

次のコード例は、`Update-APSImagePermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AppStream イメージを他のアカウントと共有します**  

```
Update-APSImagePermission -Name Powershell -SharedAccountId 123456789012 -ImagePermissions_AllowFleet $True -ImagePermissions_AllowImageBuilder $True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateImagePermissions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-APSStack`
<a name="appstream_UpdateStack_powershell_4_topic"></a>

次のコード例は、`Update-APSStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スタック上のアプリケーション設定の永続化とホームフォルダを更新 (有効化) します**  

```
Update-APSStack -Name PowershellStack -ApplicationSettings_Enabled $True -ApplicationSettings_SettingsGroup PowershellStack -StorageConnector @{ConnectorType="HOMEFOLDERS"}
```
**出力:**  

```
AccessEndpoints     : {}
ApplicationSettings : Amazon.AppStream.Model.ApplicationSettingsResponse
Arn                 : arn:aws:appstream:us-east-1:123456789012:stack/PowershellStack
CreatedTime         : 4/24/2019 8:49:29 AM
Description         : PowershellStack
DisplayName         : PowershellStack
EmbedHostDomains    : {}
FeedbackURL         :
Name                : PowershellStack
RedirectURL         :
StackErrors         : {}
StorageConnectors   : {Amazon.AppStream.Model.StorageConnector, Amazon.AppStream.Model.StorageConnector}
UserSettings        : {Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting}
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[UpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Aurora の例
<a name="powershell_4_aurora_code_examples"></a>

次のコード例は、Aurora で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-RDSOrderableDBInstanceOption`
<a name="aurora_DescribeOrderableDBInstanceOptions_powershell_4_topic"></a>

次のコード例は、`Get-RDSOrderableDBInstanceOption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は、 AWS リージョン内で特定の DB インスタンスクラスをサポートする DB エンジンのバージョンを一覧表示します。**  

```
$params = @{
  Engine = 'aurora-postgresql'
  DBInstanceClass = 'db.r5.large'
  Region = 'us-east-1'
}
Get-RDSOrderableDBInstanceOption @params
```
**例 2: この例は、 AWS リージョン内で特定の DB エンジンのバージョンをサポートする DB インスタンスクラスを一覧表示します。**  

```
$params = @{
  Engine = 'aurora-postgresql'
  EngineVersion = '13.6'
  Region = 'us-east-1'
}
Get-RDSOrderableDBInstanceOption @params
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Auto Scaling の例
<a name="powershell_4_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ASLoadBalancer`
<a name="auto-scaling_AttachLoadBalancers_powershell_4_topic"></a>

次のコード例は、`Add-ASLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したロードバランサーを、指定した Auto Scaling グループにアタッチします。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Complete-ASLifecycleAction`
<a name="auto-scaling_CompleteLifecycleAction_powershell_4_topic"></a>

次のコード例は、`Complete-ASLifecycleAction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したライフサイクルアクションを完了します。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-ASMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_powershell_4_topic"></a>

次のコード例は、`Disable-ASMetricsCollection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Dismount-ASInstance`
<a name="auto-scaling_DetachInstances_powershell_4_topic"></a>

次のコード例は、`Dismount-ASInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループから指定したインスタンスをデタッチし、希望する容量を減らして、Auto Scaling が代替インスタンスを起動しないようにします。**  

```
Dismount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**出力:**  

```
ActivityId           : 06733445-ce94-4039-be1b-b9f1866e276e
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-93633f9b was detached in response to a user request, shrinking
                       the capacity from 2 to 1.
Description          : Detaching EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
**例 2: この例では、希望する容量を減らすことなく、指定したインスタンスを指定した Auto Scaling グループからデタッチします。Auto Scaling が代替インスタンスを起動します。**  

```
Dismount-ASInstance -InstanceId i-7bf746a2 -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**出力:**  

```
ActivityId           : f43a3cd4-d38c-4af7-9fe0-d76ec2307b6d
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-7bf746a2 was detached in response to a user request.
Description          : Detaching EC2 instance: i-7bf746a2
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Dismount-ASLoadBalancer`
<a name="auto-scaling_DetachLoadBalancers_powershell_4_topic"></a>

次のコード例は、`Dismount-ASLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループから指定したロードバランサーをデタッチします。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-ASMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_powershell_4_topic"></a>

次のコード例は、`Enable-ASMetricsCollection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enter-ASStandby`
<a name="auto-scaling_EnterStandby_powershell_4_topic"></a>

次のコード例は、`Enter-ASStandby` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスをスタンバイモードにし、希望する容量を減らして、Auto Scaling が代替インスタンスを起動しないようにします。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**出力:**  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request,
                       shrinking the capacity from 2 to 1.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
**例 2: この例では、希望する容量を減らすことなく、指定したインスタンスをスタンバイモードにします。Auto Scaling が代替インスタンスを起動します。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**出力:**  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnterStandby](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Exit-ASStandby`
<a name="auto-scaling_ExitStandby_powershell_4_topic"></a>

次のコード例は、`Exit-ASStandby` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスをスタンバイモードから解除します。**  

```
Exit-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
**出力:**  

```
ActivityId           : 1833d3e8-e32f-454e-b731-0670ad4c6934
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:51:21Z instance i-95b8484f was moved out of standby in response to a user 
                       request, increasing the capacity from 1 to 2.
Description          : Moving EC2 instance out of Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 30
StartTime            : 11/22/2015 7:51:21 AM
StatusCode           : PreInService
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ExitStandby](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASAccountLimit`
<a name="auto-scaling_DescribeAccountLimits_powershell_4_topic"></a>

次のコード例は、`Get-ASAccountLimit` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウントの Auto Scaling リソース制限について説明します。**  

```
Get-ASAccountLimit
```
**出力:**  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASAdjustmentType`
<a name="auto-scaling_DescribeAdjustmentTypes_powershell_4_topic"></a>

次のコード例は、`Get-ASAdjustmentType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされている調整タイプを記述します。**  

```
Get-ASAdjustmentType
```
**出力:**  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASAutoScalingGroup`
<a name="auto-scaling_DescribeAutoScalingGroups_powershell_4_topic"></a>

次のコード例は、`Get-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling グループの名前を一覧表示します。**  

```
Get-ASAutoScalingGroup | format-table -property AutoScalingGroupName
```
**出力:**  

```
AutoScalingGroupName
--------------------
my-asg-1
my-asg-2
my-asg-3
my-asg-4
my-asg-5
my-asg-6
```
**例 2: この例では、指定した Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1
```
**出力:**  

```
AutoScalingGroupARN     : arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480
                          f03:autoScalingGroupName/my-asg-1
AutoScalingGroupName    : my-asg-1
AvailabilityZones       : {us-west-2b, us-west-2a}
CreatedTime             : 3/1/2015 9:05:31 AM
DefaultCooldown         : 300
DesiredCapacity         : 2
EnabledMetrics          : {}
HealthCheckGracePeriod  : 300
HealthCheckType         : EC2
Instances               : {my-lc}
LaunchConfigurationName : my-lc
LoadBalancerNames       : {}
MaxSize                 : 0
MinSize                 : 0
PlacementGroup          :
Status                  :
SuspendedProcesses      : {}
Tags                    : {}
TerminationPolicies     : {Default}
VPCZoneIdentifier       : subnet-e4f33493,subnet-5264e837
```
**例 3: この例では、指定した 2 つの Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**例 5: この例では、すべての Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup
```
**例 6: この例では、指定した Auto Scaling グループ用の起動テンプレートを記述します。この例では、[インスタンスの購入オプション] が [起動テンプレートに準拠する] に設定されていることを前提としています。このオプションが [購入オプションとインスタンスタイプを組み合わせる] に設定されている場合、LaunchTemplate には「MixedInstancesPolicy.LaunchTemplate」プロパティを使用してアクセスできます。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-ag-1).LaunchTemplate
```
**出力:**  

```
LaunchTemplateId     LaunchTemplateName   Version
----------------     ------------------   -------
lt-06095fd619cb40371 test-launch-template $Default
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASAutoScalingInstance`
<a name="auto-scaling_DescribeAutoScalingInstances_powershell_4_topic"></a>

次のコード例は、`Get-ASAutoScalingInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は、Auto Scaling インスタンスの ID を一覧表示します。**  

```
Get-ASAutoScalingInstance | format-table -property InstanceId
```
**出力:**  

```
InstanceId
----------
i-12345678
i-87654321
i-abcd1234
```
**例 2: この例では、指定した Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance -InstanceId i-12345678
```
**出力:**  

```
AutoScalingGroupName    : my-asg
AvailabilityZone        : us-west-2b
HealthStatus            : HEALTHY
InstanceId              : i-12345678
LaunchConfigurationName : my-lc
LifecycleState          : InService
```
**例 3: この例では、指定した 2 つの Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance -InstanceId @("i-12345678", "i-87654321")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**例 5: この例では、すべての Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASAutoScalingNotificationType`
<a name="auto-scaling_DescribeAutoScalingNotificationTypes_powershell_4_topic"></a>

次のコード例は、`Get-ASAutoScalingNotificationType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされている通知タイプを一覧表示します。**  

```
Get-ASAutoScalingNotificationType
```
**出力:**  

```
autoscaling:EC2_INSTANCE_LAUNCH
autoscaling:EC2_INSTANCE_LAUNCH_ERROR
autoscaling:EC2_INSTANCE_TERMINATE
autoscaling:EC2_INSTANCE_TERMINATE_ERROR
autoscaling:TEST_NOTIFICATION
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASLaunchConfiguration`
<a name="auto-scaling_DescribeLaunchConfigurations_powershell_4_topic"></a>

次のコード例は、`Get-ASLaunchConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、起動設定の名前を一覧表示します。**  

```
Get-ASLaunchConfiguration | format-table -property LaunchConfigurationName
```
**出力:**  

```
LaunchConfigurationName
-----------------------
my-lc-1
my-lc-2
my-lc-3
my-lc-4
my-lc-5
```
**例 2: この例では、指定した起動設定を記述します。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName my-lc-1
```
**出力:**  

```
AssociatePublicIpAddress     : True
BlockDeviceMappings          : {/dev/xvda}
ClassicLinkVPCId             :
ClassicLinkVPCSecurityGroups : {}
CreatedTime                  : 12/12/2014 3:22:08 PM
EbsOptimized                 : False
IamInstanceProfile           :
ImageId                      : ami-043a5034
InstanceMonitoring           : Amazon.AutoScaling.Model.InstanceMonitoring
InstanceType                 : t2.micro
KernelId                     :
KeyName                      : 
LaunchConfigurationARN       : arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:7e5f31e4-693b-4604-9322-
                               e6f68d7fafad:launchConfigurationName/my-lc-1
LaunchConfigurationName      : my-lc-1
PlacementTenancy             :
RamdiskId                    :
SecurityGroups               : {sg-67ef0308}
SpotPrice                    :
UserData                     :
```
**例 3: この例では、指定した 2 つの起動設定を記述します。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName @("my-lc-1", "my-lc-2")
```
**例 4: この例では、すべての起動設定を記述します。**  

```
Get-ASLaunchConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASLifecycleHook`
<a name="auto-scaling_DescribeLifecycleHooks_powershell_4_topic"></a>

次のコード例は、`Get-ASLifecycleHook` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**出力:**  

```
AutoScalingGroupName  : my-asg
DefaultResult         : ABANDON
GlobalTimeout         : 172800
HeartbeatTimeout      : 3600
LifecycleHookName     : myLifecycleHook
LifecycleTransition   : auto-scaling:EC2_INSTANCE_LAUNCHING
NotificationMetadata  :
NotificationTargetARN : arn:aws:sns:us-west-2:123456789012:my-topic
RoleARN               : arn:aws:iam::123456789012:role/my-iam-role
```
**例 2: この例では、指定した Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**例 3: この例では、すべての Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASLifecycleHookType`
<a name="auto-scaling_DescribeLifecycleHookTypes_powershell_4_topic"></a>

次のコード例は、`Get-ASLifecycleHookType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は、Auto Scaling でサポートされているライフサイクルフックの種類を一覧表示します。**  

```
Get-ASLifecycleHookType
```
**出力:**  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASLoadBalancer`
<a name="auto-scaling_DescribeLoadBalancers_powershell_4_topic"></a>

次のコード例は、`Get-ASLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのロードバランサーを記述します。**  

```
Get-ASLoadBalancer -AutoScalingGroupName my-asg
```
**出力:**  

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASMetricCollectionType`
<a name="auto-scaling_DescribeMetricCollectionTypes_powershell_4_topic"></a>

次のコード例は、`Get-ASMetricCollectionType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされているメトリクスコレクションタイプを一覧表示します。**  

```
(Get-ASMetricCollectionType).Metrics
```
**出力:**  

```
Metric
------
GroupMinSize
GroupMaxSize
GroupDesiredCapacity
GroupInServiceInstances
GroupPendingInstances
GroupTerminatingInstances
GroupStandbyInstances
GroupTotalInstances
```
**例 2: この例では、対応する粒度を一覧表示します。**  

```
(Get-ASMetricCollectionType).Granularities
```
**出力:**  

```
Granularity
-----------
1Minute
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASNotificationConfiguration`
<a name="auto-scaling_DescribeNotificationConfigurations_powershell_4_topic"></a>

次のコード例は、`Get-ASNotificationConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
Get-ASNotificationConfiguration -AutoScalingGroupName my-asg | format-list
```
**出力:**  

```
AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_LAUNCH
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic

AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_TERMINATE
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic
```
**例 2: この例では、すべての Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
Get-ASNotificationConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASPolicy`
<a name="auto-scaling_DescribePolicies_powershell_4_topic"></a>

次のコード例は、`Get-ASPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのすべてのポリシーを記述します。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg
```
**出力:**  

```
AdjustmentType          : ChangeInCapacity
Alarms                  : {}
AutoScalingGroupName    : my-asg
Cooldown                : 0
EstimatedInstanceWarmup : 0
MetricAggregationType   :
MinAdjustmentMagnitude  : 0
MinAdjustmentStep       : 0
PolicyARN               : arn:aws:auto-scaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef
                          :autoScalingGroupName/my-asg:policyName/myScaleInPolicy
PolicyName              : myScaleInPolicy
PolicyType              : SimpleScaling
ScalingAdjustment       : -1
StepAdjustments         : {}
```
**例 2: この例では、指定した Auto Scaling グループの指定したポリシーを記述します。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**例 3: この例では、すべての Auto Scaling グループのすべてのポリシーを記述します。**  

```
Get-ASPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribePolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASScalingActivity`
<a name="auto-scaling_DescribeScalingActivities_powershell_4_topic"></a>

次のコード例は、`Get-ASScalingActivity` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: こので例は、指定した Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity -AutoScalingGroupName my-asg
```
**出力:**  

```
ActivityId           : 063308ae-aa22-4a9b-94f4-9fae4EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:45:16Z a user request explicitly set group desired capacity changing the desired
                       capacity from 1 to 2.  At 2015-11-22T15:45:34Z an instance was started in response to a difference
                       between desired and actual capacity, increasing the capacity from 1 to 2.
Description          : Launching a new EC2 instance: i-26e715fc
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/22/2015 7:46:09 AM
Progress             : 100
StartTime            : 11/22/2015 7:45:35 AM
StatusCode           : Successful
StatusMessage        :

ActivityId           : ce719997-086d-4c73-a2f1-ab703EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:57:53Z a user request created an AutoScalingGroup changing the desired capacity
                        from 0 to 1.  At 2015-11-20T22:57:58Z an instance was started in response to a difference betwe
                       en desired and actual capacity, increasing the capacity from 0 to 1.
Description          : Launching a new EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/20/2015 2:58:32 PM
Progress             : 100
StartTime            : 11/20/2015 2:57:59 PM
StatusCode           : Successful
StatusMessage        :
```
**例 2: この例では、指定したスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity -ActivityId "063308ae-aa22-4a9b-94f4-9fae4EXAMPLE"
```
**例 3: この例では、すべての Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASScalingProcessType`
<a name="auto-scaling_DescribeScalingProcessTypes_powershell_4_topic"></a>

次のコード例は、`Get-ASScalingProcessType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされているプロセスタイプを一覧表示します。**  

```
Get-ASScalingProcessType
```
**出力:**  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASScheduledAction`
<a name="auto-scaling_DescribeScheduledActions_powershell_4_topic"></a>

次のコード例は、`Get-ASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのスケジュールされたスケーリングアクティビティを記述します。**  

```
Get-ASScheduledAction -AutoScalingGroupName my-asg
```
**出力:**  

```
AutoScalingGroupName : my-asg
DesiredCapacity      : 10
EndTime              : 
MaxSize              : 
MinSize              : 
Recurrence           :
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8a4c5f24-6ec6-4306-a2dd-f7
                       2c3af3a4d6:autoScalingGroupName/my-asg:scheduledActionName/myScheduledAction
ScheduledActionName  : myScheduledAction
StartTime            : 11/30/2015 8:00:00 AM
Time                 : 11/30/2015 8:00:00 AM
```
**例 2: この例では、指定したスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction -ScheduledActionName @("myScheduledScaleOut", "myScheduledScaleIn")
```
**例 3: この例では、指定した時刻までに開始されるスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction -StartTime "2015-12-01T08:00:00Z"
```
**例 4: この例では、指定した時刻までに終了するスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction -EndTime "2015-12-30T08:00:00Z"
```
**例 5: この例では、すべての Auto Scaling グループのスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASTag`
<a name="auto-scaling_DescribeTags_powershell_4_topic"></a>

次のコード例は、`Get-ASTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、キー値が「myTag」または「myTag2」のタグを記述します。フィルター名に使用できる値は、「auto-scaling-group」、「key」、「value」、および「propagate-at-launch」です。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-ASTag -Filter @( @{ Name="key"; Values=@("myTag", "myTag2") } )
```
**出力:**  

```
Key               : myTag2
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue2

Key               : myTag
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してフィルターパラメータのフィルターを作成する必要があります。**  

```
$keys = New-Object string[] 2
$keys[0] = "myTag"
$keys[1] = "myTag2"
$filter = New-Object Amazon.AutoScaling.Model.Filter
$filter.Name = "key"
$filter.Values = $keys
Get-ASTag -Filter @( $filter )
```
**例 3: この例では、すべての Auto Scaling グループのすべてのタグを記述します。**  

```
Get-ASTag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASTerminationPolicyType`
<a name="auto-scaling_DescribeTerminationPolicyTypes_powershell_4_topic"></a>

次のコード例は、`Get-ASTerminationPolicyType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Auto Scaling でサポートされている終了ポリシーを一覧表示します。**  

```
Get-ASTerminationPolicyType
```
**出力:**  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Mount-ASInstance`
<a name="auto-scaling_AttachInstances_powershell_4_topic"></a>

次のコード例は、`Mount-ASInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスを、指定した Auto Scaling グループにアタッチします。Auto Scaling は、Auto Scaling グループの希望する容量を自動的に増やします。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ASAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_powershell_4_topic"></a>

次のコード例は、`New-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した名前と属性で Auto Scaling グループを作成します。デフォルトの希望する容量は最小サイズになります。したがって、この Auto Scaling グループは、指定した 2 つのアベイラビリティーゾーンのそれぞれに 1 つずつ、合計 2 つのインスタンスを起動します。**  

```
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ASLaunchConfiguration`
<a name="auto-scaling_CreateLaunchConfiguration_powershell_4_topic"></a>

次のコード例は、`New-ASLaunchConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「my-lc」という名前の起動設定を作成します。この起動設定を使用する Auto Scaling グループによって起動された EC2 インスタンスは、指定されたインスタンスタイプ、AMI、セキュリティグループ、および IAM ロールを使用します。**  

```
New-ASLaunchConfiguration -LaunchConfigurationName my-lc -InstanceType "m3.medium" -ImageId "ami-12345678" -SecurityGroup "sg-12345678" -IamInstanceProfile "myIamRole"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ASAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_powershell_4_topic"></a>

次のコード例は、`Remove-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに実行中のインスタンスがない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASAutoScalingGroup (DeleteAutoScalingGroup)" on Target "my-asg".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force
```
**例 3: この例では、指定した Auto Scaling グループを削除し、そのグループに含まれる実行中のインスタンスをすべて終了します。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ASLaunchConfiguration`
<a name="auto-scaling_DeleteLaunchConfiguration_powershell_4_topic"></a>

次のコード例は、`Remove-ASLaunchConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した起動設定が Auto Scaling グループにアタッチされていない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLaunchConfiguration (DeleteLaunchConfiguration)" on Target "my-lc".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ASLifecycleHook`
<a name="auto-scaling_DeleteLifecycleHook_powershell_4_topic"></a>

次のコード例は、`Remove-ASLifecycleHook` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したライフサイクルフックを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLifecycleHook (DeleteLifecycleHook)" on Target "myLifecycleHook".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ASNotificationConfiguration`
<a name="auto-scaling_DeleteNotificationConfiguration_powershell_4_topic"></a>

次のコード例は、`Remove-ASNotificationConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した通知アクションを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASNotificationConfiguration (DeleteNotificationConfiguration)" on Target
"arn:aws:sns:us-west-2:123456789012:my-topic".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic" -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ASPolicy`
<a name="auto-scaling_DeletePolicy_powershell_4_topic"></a>

次のコード例は、`Remove-ASPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASPolicy (DeletePolicy)" on Target "myScaleInPolicy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeletePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ASScheduledAction`
<a name="auto-scaling_DeleteScheduledAction_powershell_4_topic"></a>

次のコード例は、`Remove-ASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したスケジュールされたアクションを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASScheduledAction (DeleteScheduledAction)" on Target "myScheduledAction".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction" -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ASTag`
<a name="auto-scaling_DeleteTags_powershell_4_topic"></a>

次のコード例は、`Remove-ASTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループから指定したタグを削除します。操作を続行する前に確認画面が表示されます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } )
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ASTag (DeleteTags)" on target "Amazon.AutoScaling.Model.Tag".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } ) -Force
```
**例 3: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg"
$tag.Key = "myTag"
Remove-ASTag -Tag $tag -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Resume-ASProcess`
<a name="auto-scaling_ResumeProcesses_powershell_4_topic"></a>

次のコード例は、`Resume-ASProcess` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループの中断されたすべての Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResumeProcesses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ASDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_powershell_4_topic"></a>

次のコード例は、`Set-ASDesiredCapacity` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループのサイズを設定します。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**例 2: この例では、指定した Auto Scaling グループのサイズを設定し、クールダウン期間が完了するまで待ってから、新しいサイズにスケールします。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ASInstanceHealth`
<a name="auto-scaling_SetInstanceHealth_powershell_4_topic"></a>

次のコード例は、`Set-ASInstanceHealth` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスのステータスを「Unhealthy」に設定し、使用を中止します。Auto Scaling はインスタンスを終了して置き換えます。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**例 2: この例では、指定したインスタンスのステータスを「Healthy」に設定し、そのまま稼働させます。Auto Scaling グループのヘルスチェック猶予期間は無視されます。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetInstanceHealth](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ASInstanceProtection`
<a name="auto-scaling_SetInstanceProtection_powershell_4_topic"></a>

次のコード例は、`Set-ASInstanceProtection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスのインスタンス保護を有効にします。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $true
```
**例 2: この例では、指定したインスタンスのインスタンス保護を無効にします。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetInstanceProtection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ASTag`
<a name="auto-scaling_CreateOrUpdateTags_powershell_4_topic"></a>

次のコード例は、`Set-ASTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに単一のタグを追加します。タグキーは「myTag」で、タグ値は「myTagValue」です。Auto Scaling は、このタグを Auto Scaling グループによって起動された後続の EC2 インスタンスに伝播します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Set-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag"; Value="myTagValue"; PropagateAtLaunch=$true} )
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg" 
$tag.Key = "myTag" 
$tag.Value = "myTagValue"
$tag.PropagateAtLaunch = $true
Set-ASTag -Tag $tag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-ASPolicy`
<a name="auto-scaling_ExecutePolicy_powershell_4_topic"></a>

次のコード例は、`Start-ASPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**例 2: この例では、クールダウン期間が完了するまで待機した後、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ExecutePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-ASInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_powershell_4_topic"></a>

次のコード例は、`Stop-ASInstanceInAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスを終了し、Auto Scaling グループの希望する容量を減らして、Auto Scaling が代替インスタンスを起動しないようにします。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $true
```
**出力:**  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request, shrinking the capacity from 2 to 1.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
**例 2: この例では、Auto Scaling グループの希望する容量を減らすことなく、指定したインスタンスを終了します。Auto Scaling が代替インスタンスを起動します。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $false
```
**出力:**  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Suspend-ASProcess`
<a name="auto-scaling_SuspendProcesses_powershell_4_topic"></a>

次のコード例は、`Suspend-ASProcess` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループのすべての Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SuspendProcesses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-ASAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_powershell_4_topic"></a>

次のコード例は、`Update-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループの最小サイズと最大サイズを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**例 2: この例では、指定した Auto Scaling グループのデフォルトのクールダウン期間を更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**例 3: この例では、指定した Auto Scaling グループのアベイラビリティーゾーンを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**例 4: この例では、指定した Auto Scaling グループを更新して、Elastic Load Balancing のヘルスチェックを使用します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-ASLifecycleActionHeartbeat`
<a name="auto-scaling_RecordLifecycleActionHeartbeat_powershell_4_topic"></a>

次のコード例は、`Write-ASLifecycleActionHeartbeat` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したライフサイクルアクションのハートビートを記録します。これにより、カスタムアクションが完了するまでインスタンスは保留中の状態になります。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-ASLifecycleHook`
<a name="auto-scaling_PutLifecycleHook_powershell_4_topic"></a>

次のコード例は、`Write-ASLifecycleHook` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したライフサイクルフックを、指定した Auto Scaling グループに追加します。**  

```
Write-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName "myLifecycleHook" -LifecycleTransition "autoscaling:EC2_INSTANCE_LAUNCHING" -NotificationTargetARN "arn:aws:sns:us-west-2:123456789012:my-sns-topic" -RoleARN "arn:aws:iam::123456789012:role/my-iam-role"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutLifecycleHook](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-ASNotificationConfiguration`
<a name="auto-scaling_PutNotificationConfiguration_powershell_4_topic"></a>

次のコード例は、`Write-ASNotificationConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループが、EC2 インスタンスの起動時に指定した SNS トピックに通知を送信するように設定します。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType "autoscaling:EC2_INSTANCE_LAUNCH" -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**例 2: この例では、指定した Auto Scaling グループが、EC2 インスタンスの起動または終了時に、指定した SNS トピックに通知を送信するように設定します。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType @("autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_TERMINATE") -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-ASScalingPolicy`
<a name="auto-scaling_PutScalingPolicy_powershell_4_topic"></a>

次のコード例は、`Write-ASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Auto Scaling グループに指定したポリシーを追加します。指定した調整タイプによって、ScalingAdjustment パラメータの解釈方法が決まります。「ChangeInCapacity」では、正の値を指定すると、指定したインスタンス数だけ容量が増え、負の値を指定すると、指定したインスタンス数だけ容量が減ります。**  

```
Write-ASScalingPolicy -AutoScalingGroupName my-asg -AdjustmentType "ChangeInCapacity" -PolicyName "myScaleInPolicy" -ScalingAdjustment -1
```
**出力:**  

```
arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef:autoScalingGroupName/my-asg
:policyName/myScaleInPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutScalingPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-ASScheduledUpdateGroupAction`
<a name="auto-scaling_PutScheduledUpdateGroupAction_powershell_4_topic"></a>

次のコード例は、`Write-ASScheduledUpdateGroupAction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、1 回限りのスケジュールされたアクションを作成または更新して、指定した開始時刻に希望する容量を変更します。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS Budgets Tools for PowerShell V4 を使用した の例
<a name="powershell_4_budgets_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Budgets。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-BGTBudget`
<a name="budgets_CreateBudget_powershell_4_topic"></a>

次のコード例は、`New-BGTBudget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された予算と時間の制約を持つ新しい予算を作成し、E メール通知を設定します。**  

```
$notification = @{
    NotificationType = "ACTUAL"
    ComparisonOperator = "GREATER_THAN"
    Threshold = 80
}

$addressObject = @{
    Address = @("user@domain.com")
    SubscriptionType = "EMAIL"
}

$subscriber = New-Object Amazon.Budgets.Model.NotificationWithSubscribers
$subscriber.Notification = $notification
$subscriber.Subscribers.Add($addressObject)

$startDate = [datetime]::new(2017,09,25)
$endDate = [datetime]::new(2017,10,25)

New-BGTBudget -Budget_BudgetName "Tester" -Budget_BudgetType COST -CostTypes_IncludeTax $true -Budget_TimeUnit MONTHLY -BudgetLimit_Unit USD -TimePeriod_Start $startDate -TimePeriod_End $endDate -AccountId 123456789012 -BudgetLimit_Amount 200 -NotificationsWithSubscriber $subscriber
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateBudget](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS Cloud9 Tools for PowerShell V4 を使用した の例
<a name="powershell_4_cloud9_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Cloud9。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-C9EnvironmentData`
<a name="cloud9_DescribeEnvironments_powershell_4_topic"></a>

次のコード例は、`Get-C9EnvironmentData` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AWS Cloud9 開発環境に関する情報を取得します。**  

```
Get-C9EnvironmentData -EnvironmentId 685f892f431b45c2b28cb69eadcdb0EX,1980b80e5f584920801c09086667f0EX
```
**出力:**  

```
Arn         : arn:aws:cloud9:us-east-1:123456789012:environment:685f892f431b45c2b28cb69eadcdb0EX
Description : Created from CodeStar.
Id          : 685f892f431b45c2b28cb69eadcdb0EX
Lifecycle   : Amazon.Cloud9.Model.EnvironmentLifecycle
Name        : my-demo-ec2-env
OwnerArn    : arn:aws:iam::123456789012:user/MyDemoUser
Type        : ec2

Arn         : arn:aws:cloud9:us-east-1:123456789012:environment:1980b80e5f584920801c09086667f0EX
Description :
Id          : 1980b80e5f584920801c09086667f0EX
Lifecycle   : Amazon.Cloud9.Model.EnvironmentLifecycle
Name        : my-demo-ssh-env
OwnerArn    : arn:aws:iam::123456789012:user/MyDemoUser
Type        : ssh
```
**例 2: この例では、指定された AWS Cloud9 開発環境のライフサイクルステータスに関する情報を取得します。**  

```
(Get-C9EnvironmentData -EnvironmentId 685f892f431b45c2b28cb69eadcdb0EX).Lifecycle
```
**出力:**  

```
FailureResource Reason Status
--------------- ------ ------
                       CREATED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEnvironments](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-C9EnvironmentList`
<a name="cloud9_ListEnvironments_powershell_4_topic"></a>

次のコード例は、`Get-C9EnvironmentList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、使用可能な AWS Cloud9 開発環境識別子のリストを取得します。**  

```
Get-C9EnvironmentList
```
**出力:**  

```
685f892f431b45c2b28cb69eadcdb0EX
1980b80e5f584920801c09086667f0EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListEnvironments](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-C9EnvironmentMembershipList`
<a name="cloud9_DescribeEnvironmentMemberships_powershell_4_topic"></a>

次のコード例は、`Get-C9EnvironmentMembershipList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AWS Cloud9 開発環境の環境メンバーに関する情報を取得します。**  

```
Get-C9EnvironmentMembershipList -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-write
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX

EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
**例 2: この例では、指定された AWS Cloud9 開発環境の所有者に関する情報を取得します。**  

```
Get-C9EnvironmentMembershipList -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission owner
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
**例 3: この例では、multiple AWS Cloud9 開発環境の指定された環境メンバーに関する情報を取得します。**  

```
Get-C9EnvironmentMembershipList -UserArn arn:aws:iam::123456789012:user/MyDemoUser
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/17/2018 7:48:14 PM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX

EnvironmentId : 1980b80e5f584920801c09086667f0EX
LastAccess    : 1/16/2018 11:21:24 PM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEnvironmentMemberships](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-C9EnvironmentStatus`
<a name="cloud9_DescribeEnvironmentStatus_powershell_4_topic"></a>

次のコード例は、`Get-C9EnvironmentStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AWS Cloud9 開発環境のステータス情報を取得します。**  

```
Get-C9EnvironmentStatus -EnvironmentId 349c86d4579e4e7298d500ff57a6b2EX
```
**出力:**  

```
Message                     Status
-------                     ------
Environment is ready to use ready
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEnvironmentStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-C9EnvironmentEC2`
<a name="cloud9_CreateEnvironmentEc2_powershell_4_topic"></a>

次のコード例は、`New-C9EnvironmentEC2` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された設定で AWS Cloud9 開発環境を作成し、Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを起動してから、インスタンスから環境に接続します。**  

```
New-C9EnvironmentEC2 -Name my-demo-env -AutomaticStopTimeMinutes 60 -Description "My demonstration development environment." -InstanceType t2.micro -OwnerArn arn:aws:iam::123456789012:user/MyDemoUser -SubnetId subnet-d43a46EX
```
**出力:**  

```
ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateEnvironmentEc2](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-C9EnvironmentMembership`
<a name="cloud9_CreateEnvironmentMembership_powershell_4_topic"></a>

次のコード例は、`New-C9EnvironmentMembership` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された環境メンバーを指定された AWS Cloud9 開発環境に追加します。**  

```
New-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission read-write
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-write
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-C9Environment`
<a name="cloud9_DeleteEnvironment_powershell_4_topic"></a>

次のコード例は、`Remove-C9Environment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AWS Cloud9 開発環境を削除します。環境が Amazon EC2 インスタンスに接続されている場合、インスタンスも終了します。**  

```
Remove-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteEnvironment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-C9EnvironmentMembership`
<a name="cloud9_DeleteEnvironmentMembership_powershell_4_topic"></a>

次のコード例は、`Remove-C9EnvironmentMembership` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AWS Cloud9 開発環境から指定された環境メンバーを削除します。**  

```
Remove-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteEnvironmentMembership](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-C9Environment`
<a name="cloud9_UpdateEnvironment_powershell_4_topic"></a>

次のコード例は、`Update-C9Environment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された既存の AWS Cloud9 開発環境の指定された設定を変更します。**  

```
Update-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Description "My changed demonstration development environment." -Name my-changed-demo-env
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateEnvironment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-C9EnvironmentMembership`
<a name="cloud9_UpdateEnvironmentMembership_powershell_4_topic"></a>

次のコード例は、`Update-C9EnvironmentMembership` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AWS Cloud9 開発環境の指定された既存の環境メンバーの設定を変更します。**  

```
Update-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission read-only
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-only
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。.

# CloudFormation Tools for PowerShell V4 を使用した の例
<a name="powershell_4_cloudformation_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています CloudFormation。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CFNStack`
<a name="cloudformation_DescribeStacks_powershell_4_topic"></a>

次のコード例は、`Get-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ユーザーのスタックのすべてを記述するスタックインスタンスのコレクションを返します。**  

```
Get-CFNStack
```
**例 2: 指定されたスタックを記述するスタックインスタンスを返します。**  

```
Get-CFNStack -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DescribeStacks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFNStackEvent`
<a name="cloudformation_DescribeStackEvents_powershell_4_topic"></a>

次のコード例は、`Get-CFNStackEvent` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたスタックに関するすべてのスタック関連イベントを返します。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DescribeStackEvents](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFNStackResource`
<a name="cloudformation_DescribeStackResource_powershell_4_topic"></a>

次のコード例は、`Get-CFNStackResource` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 論理 ID「MyDBInstance」を使用して、指定されたスタックに関連付けられているテンプレートで識別されたリソースの説明を返します。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DescribeStackResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFNStackResourceList`
<a name="cloudformation_DescribeStackResources_powershell_4_topic"></a>

次のコード例は、`Get-CFNStackResourceList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたスタックに関連付けられた最大 100 個の AWS リソースのリソースの説明を返します。スタックに関連付けられているすべてのリソースの詳細情報を取得するには、Get-CFNStackResourceSummary を使用します。これは、結果の手動ページングもサポートしています。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**例 2: 論理 ID「Ec2Instance」を使用して、指定されたスタックに関連付けられているテンプレートで識別された Amazon EC2 インスタンスの説明を返します。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**例 3: インスタンス ID「i-123456」で識別される Amazon EC2 インスタンスが含まれるスタックに関連付けられた、最大 100 個のリソースの説明を返します。スタックに関連付けられているすべてのリソースの詳細情報を取得するには、Get-CFNStackResourceSummary を使用します。これは、結果の手動ページングもサポートしています。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456"
```
**例 4: スタックのテンプレートで論理 ID「Ec2Instance」によって識別される Amazon EC2 インスタンスの説明を返します。スタックは、スタックに含まれるリソースの物理リソース ID を使用して識別され、この場合はインスタンス ID が「i-123456」の Amazon EC2 インスタンスも含まれます。テンプレートのコンテンツによっては、スタックの識別に異なる物理リソース (Amazon S3 バケットなど) を使用することもできます。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456" -LogicalResourceId "Ec2Instance"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DescribeStackResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFNStackResourceSummary`
<a name="cloudformation_ListStackResources_powershell_4_topic"></a>

次のコード例は、`Get-CFNStackResourceSummary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたスタックに関連付けられているすべてのリソースの説明を返します。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[ListStackResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFNStackSummary`
<a name="cloudformation_ListStacks_powershell_4_topic"></a>

次のコード例は、`Get-CFNStackSummary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべてのスタックの概要情報を返します。**  

```
Get-CFNStackSummary
```
**例 2: 現在作成中のすべてのスタックの概要情報を返します。**  

```
Get-CFNStackSummary -StackStatusFilter "CREATE_IN_PROGRESS"
```
**例 3: 現在作成中または更新中のすべてのスタックの概要情報を返します。**  

```
Get-CFNStackSummary -StackStatusFilter @("CREATE_IN_PROGRESS", "UPDATE_IN_PROGRESS")
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[ListStacks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFNTemplate`
<a name="cloudformation_GetTemplate_powershell_4_topic"></a>

次のコード例は、`Get-CFNTemplate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたスタックに関連付けられているテンプレートを返します。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[GetTemplate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Measure-CFNTemplateCost`
<a name="cloudformation_EstimateTemplateCost_powershell_4_topic"></a>

次のコード例は、`Measure-CFNTemplateCost` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: テンプレートの実行に必要なリソースを記述するクエリ文字列を含む AWS Simple Monthly Calculator URL を返します。テンプレートは指定された Amazon S3 URL から取得され、単一のカスタマイゼーションパラメータが適用されます。パラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Measure-CFNTemplateCost -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                        -Region us-west-1 `
                        -Parameter @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" }
```
**例 2: テンプレートの実行に必要なリソースを記述するクエリ文字列を含む AWS Simple Monthly Calculator URL を返します。テンプレートは提供されたコンテンツから解析され、カスタマイゼーションパラメータが適用されます (この例は、テンプレートコンテンツが「KeyName」と「InstanceType」の 2 つのパラメータを宣言していることを前提としています)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**例 3: New-Object を使用してテンプレートパラメータのセットを構築し、テンプレートの実行に必要なリソースを記述するクエリ文字列を含む AWS Simple Monthly Calculator URL を返します。テンプレートは、カスタマイゼーションパラメータを使用して、提供されたコンテンツから解析されます (この例は、テンプレートコンテンツが「KeyName」と「InstanceType」の 2 つのパラメータを宣言していることを前提としています)。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "KeyName"
$p1.ParameterValue = "myKeyPairName"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "InstanceType"
$p2.ParameterValue = "m1.large"

Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" -Parameter @( $p1, $p2 )
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CFNStack`
<a name="cloudformation_CreateStack_powershell_4_topic"></a>

次のコード例は、`New-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、提供されたコンテンツから解析されます (「PK1」と「PK2」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」と「PV2」はこれらのパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗しても、スタックはロールバックされません。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" }) `
             -DisableRollback $true
```
**例 2: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、提供されたコンテンツから解析されます (「PK1」と「PK2」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」と「PV2」はこれらのパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗すると、スタックがロールバックされます。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "PK1"
$p1.ParameterValue = "PV1"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "PK2"
$p2.ParameterValue = "PV2"

New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( $p1, $p2 ) `
             -OnFailure "ROLLBACK"
```
**例 3: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、Amazon S3 URL から取得されます (「PK1」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」はパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗すると、スタックがロールバックされます (-DisableRollback \$1false を指定する場合と同じです)**。  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**例 4: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、Amazon S3 URL から取得されます (「PK1」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」はパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗すると、スタックがロールバックされます (-DisableRollback \$1false を指定する場合と同じです)。指定された通知 AEN は、公開されたスタック関連のイベントを受け取ります。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" } `
             -NotificationARN @( "arn1", "arn2" )
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[CreateStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CFNStack`
<a name="cloudformation_DeleteStack_powershell_4_topic"></a>

次のコード例は、`Remove-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたスタックを削除します。**  

```
Remove-CFNStack -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[DeleteStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Resume-CFNUpdateRollback`
<a name="cloudformation_ContinueUpdateRollback_powershell_4_topic"></a>

次のコード例は、`Resume-CFNUpdateRollback` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたスタックのロールバックを続行します。このスタックの状態は「UPDATE\$1ROLLBACK\$1FAILED」になっている必要があります。続行されたロールバックが成功すると、スタックの状態が「UPDATE\$1ROLLBACK\$1COMPLETE」になります。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-CFNUpdateStack`
<a name="cloudformation_CancelUpdateStack_powershell_4_topic"></a>

次のコード例は、`Stop-CFNUpdateStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたスタックで行われている更新をキャンセルします。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[CancelUpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Test-CFNStack`
<a name="cloudformation_Test-CFNStack_powershell_4_topic"></a>

次のコード例は、`Test-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: スタックが UPDATE\$1ROLLBACK\$1COMPLETE、CREATE\$1COMPLETE、ROLLBACK\$1COMPLETE、または UPDATE\$1COMPLETE のいずれかの状態に達したかどうかをテストします。**  

```
Test-CFNStack -StackName MyStack
```
**出力:**  

```
False
```
**例 2: スタックが UPDATE\$1COMPLETE または UPDATE\$1ROLLBACK\$1COMPLETE のいずれかの状態に達したかどうかをテストします。**  

```
Test-CFNStack -StackName MyStack -Status UPDATE_COMPLETE,UPDATE_ROLLBACK_COMPLETE
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Test-CFNStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Test-CFNTemplate`
<a name="cloudformation_ValidateTemplate_powershell_4_topic"></a>

次のコード例は、`Test-CFNTemplate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたテンプレートコンテンツを検証します。出力は、テンプレートの機能、説明、パラメータを詳しく説明します。**  

```
Test-CFNTemplate -TemplateBody "{TEMPLATE CONTENT HERE}"
```
**例 2: Amazon S3 URL 経由でアクセスされる、指定されたテンプレートを検証します。出力は、テンプレートの機能、説明、パラメータを詳しく説明します。**  

```
Test-CFNTemplate -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[ValidateTemplate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CFNStack`
<a name="cloudformation_UpdateStack_powershell_4_topic"></a>

次のコード例は、`Update-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたテンプレートとカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」はテンプレートで宣言されているパラメータの名前を表し、「PV1」はその値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**例 2: 指定されたテンプレートとカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」と「PK2」はテンプレートで宣言されているパラメータの名前を表し、「PV1」と「PV2」はそれらの要求された値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**例 3: 指定されたテンプレートとカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」はテンプレートで宣言されているパラメータの名前を表し、「PV2」はその値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**例 4: 指定されたテンプレート (Amazon S3 から取得されたもの) とカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」と「PK2」はテンプレートで宣言されているパラメータの名前を表し、「PV1」と「PV2」はそれらの要求された値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**例 5: 指定されたテンプレート (Amazon S3 から取得されたもの) とカスタマイゼーションパラメータでスタック「MyStack」(この例では IAM リソースが含まれていることを想定) を更新します。「PK1」と「PK2」はテンプレートで宣言されているパラメータの名前を表し、「PV1」と「PV2」はそれらの要求された値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。IAM リソースが含まれるスタックでは、-Capabilities「CAPABILITY\$1IAM」パラメータを指定する必要があります。指定されていない場合は、更新が「InsufficientCapabilities」エラーで失敗します。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } ) `
                -Capabilities "CAPABILITY_IAM"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V4)*」の「[UpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Wait-CFNStack`
<a name="cloudformation_Wait-CFNStack_powershell_4_topic"></a>

次のコード例は、`Wait-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: スタックが UPDATE\$1ROLLBACK\$1COMPLETE、CREATE\$1COMPLETE、ROLLBACK\$1COMPLETE、または UPDATE\$1COMPLETE のいずれかの状態に達したかどうかをテストします。スタックがいずれかの状態にも達していない場合、コマンドは 2 秒間スリープしてから再度ステータスをテストします。これは、スタックがリクエストされた状態のいずれかに達するか、デフォルトのタイムアウト期間である 60 秒を経過するまで繰り返されます。タイムアウト期間を超えると、例外がスローされます。スタックがタイムアウト期間内にリクエストされた状態のいずれかに達すると、パイプラインに返されます。**  

```
$stack = Wait-CFNStack -StackName MyStack
```
**例 2: この例では、スタックが指定の状態のいずれかに達するまで合計 5 分 (300 秒) 待機します。この例では、タイムアウトの前にいずれかの状態に達しているため、スタックオブジェクトはパイプラインに返されます。**  

```
Wait-CFNStack -StackName MyStack -Timeout 300 -Status CREATE_COMPLETE,ROLLBACK_COMPLETE
```
**出力:**  

```
Capabilities      : {CAPABILITY_IAM}
ChangeSetId       :
CreationTime      : 6/1/2017 9:29:33 AM
Description       : AWS CloudFormation Sample Template ec2_instance_with_instance_profile: Create an EC2 instance with an associated instance profile. **WARNING** This template creates one or more Amazon EC2
                    instances and an Amazon SQS queue. You will be billed for the AWS resources used if you create a stack from this template.
DisableRollback   : False
LastUpdatedTime   : 1/1/0001 12:00:00 AM
NotificationARNs  : {}
Outputs           : {}
Parameters        : {}
RoleARN           :
StackId           : arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/7ea87b50-46e7-11e7-9c9b-503a90a9c4d1
StackName         : MyStack
StackStatus       : CREATE_COMPLETE
StackStatusReason :
Tags              : {}
TimeoutInMinutes  : 0
```
**例 3: この例では、スタックがタイムアウト期間 (この場合はデフォルト期間 60 秒) 内にリクエストされた状態のいずれかに達しなかった場合のエラー出力を示します。**  

```
Wait-CFNStack -StackName MyStack -Status CREATE_COMPLETE,ROLLBACK_COMPLETE
```
**出力:**  

```
Wait-CFNStack : Timed out after 60 seconds waiting for CloudFormation stack MyStack in region us-west-2 to reach one of state(s): UPDATE_ROLLBACK_COMPLETE,CREATE_COMPLETE,ROLLBACK_COMPLETE,UPDATE_COMPLETE
At line:1 char:1
+ Wait-CFNStack -StackName MyStack -State CREATE_COMPLETE,ROLLBACK_COMPLETE
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Amazon.PowerShe...tCFNStackCmdlet:WaitCFNStackCmdlet) [Wait-CFNStack], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Amazon.PowerShell.Cmdlets.CFN.WaitCFNStackCmdlet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Wait-CFNStack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した CloudFront の例
<a name="powershell_4_cloudfront_code_examples"></a>

次のコード例は、CloudFront で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CFCloudFrontOriginAccessIdentity`
<a name="cloudfront_GetCloudFrontOriginAccessIdentity_powershell_4_topic"></a>

次のコード例は、`Get-CFCloudFrontOriginAccessIdentity` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、-Id パラメータで指定した、特定の Amazon CloudFront オリジンアクセスアイデンティティを返します。-Id パラメータは必須ではありませんが、指定しないと、結果は返されません。**  

```
Get-CFCloudFrontOriginAccessIdentity -Id E3XXXXXXXXXXRT
```
**出力:**  

```
      CloudFrontOriginAccessIdentityConfig    Id                                      S3CanonicalUserId
      ------------------------------------    --                                      -----------------
      Amazon.CloudFront.Model.CloudFrontOr... E3XXXXXXXXXXRT                          4b6e...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetCloudFrontOriginAccessIdentity](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFCloudFrontOriginAccessIdentityConfig`
<a name="cloudfront_GetCloudFrontOriginAccessIdentityConfig_powershell_4_topic"></a>

次のコード例は、`Get-CFCloudFrontOriginAccessIdentityConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、-Id パラメータで指定した、単一の Amazon CloudFront オリジンアクセスアイデンティティに関する設定情報を返します。-Id パラメータを指定しないと、エラーが発生します。**  

```
Get-CFCloudFrontOriginAccessIdentityConfig -Id E3XXXXXXXXXXRT
```
**出力:**  

```
      CallerReference                                             Comment
      ---------------                                             -------
      mycallerreference: 2/1/2011 1:16:32 PM                      Caller reference: 2/1/2011 1:16:32 PM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetCloudFrontOriginAccessIdentityConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFCloudFrontOriginAccessIdentityList`
<a name="cloudfront_ListCloudFrontOriginAccessIdentities_powershell_4_topic"></a>

次のコード例は、`Get-CFCloudFrontOriginAccessIdentityList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Amazon CloudFront オリジンアクセスアイデンティティのリストを返します。-MaxItem パラメータは値として 2 を指定しているため、結果には 2 つのアイデンティティが含まれます。**  

```
Get-CFCloudFrontOriginAccessIdentityList -MaxItem 2
```
**出力:**  

```
IsTruncated : True
Items       : {E326XXXXXXXXXT, E1YWXXXXXXX9B}
Marker      :
MaxItems    : 2
NextMarker  : E1YXXXXXXXXX9B
Quantity    : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFDistribution`
<a name="cloudfront_GetDistribution_powershell_4_topic"></a>

次のコード例は、`Get-CFDistribution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 特定のディストリビューションに関する情報を取得します。**  

```
Get-CFDistribution -Id EXAMPLE0000ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDistribution](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFDistributionConfig`
<a name="cloudfront_GetDistributionConfig_powershell_4_topic"></a>

次のコード例は、`Get-CFDistributionConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 特定のディストリビューションの設定を取得します。**  

```
Get-CFDistributionConfig -Id EXAMPLE0000ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDistributionConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFDistributionList`
<a name="cloudfront_ListDistributions_powershell_4_topic"></a>

次のコード例は、`Get-CFDistributionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ディストリビューションを返します。**  

```
Get-CFDistributionList
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDistributions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CFDistribution`
<a name="cloudfront_CreateDistribution_powershell_4_topic"></a>

次のコード例は、`New-CFDistribution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ロギングとキャッシュを使用して設定した、基本的な CloudFront ディストリビューションを作成します。**  

```
$origin = New-Object Amazon.CloudFront.Model.Origin
$origin.DomainName = "amzn-s3-demo-bucket.s3.amazonaws.com"
$origin.Id = "UniqueOrigin1"
$origin.S3OriginConfig = New-Object Amazon.CloudFront.Model.S3OriginConfig
$origin.S3OriginConfig.OriginAccessIdentity = ""
New-CFDistribution `
      -DistributionConfig_Enabled $true `
      -DistributionConfig_Comment "Test distribution" `
      -Origins_Item $origin `
      -Origins_Quantity 1 `
      -Logging_Enabled $true `
      -Logging_IncludeCookie $true `
      -Logging_Bucket amzn-s3-demo-logging-bucket.s3.amazonaws.com `
      -Logging_Prefix "help/" `
      -DistributionConfig_CallerReference Client1 `
      -DistributionConfig_DefaultRootObject index.html `
      -DefaultCacheBehavior_TargetOriginId $origin.Id `
      -ForwardedValues_QueryString $true `
      -Cookies_Forward all `
      -WhitelistedNames_Quantity 0 `
      -TrustedSigners_Enabled $false `
      -TrustedSigners_Quantity 0 `
      -DefaultCacheBehavior_ViewerProtocolPolicy allow-all `
      -DefaultCacheBehavior_MinTTL 1000 `
      -DistributionConfig_PriceClass "PriceClass_All" `
      -CacheBehaviors_Quantity 0 `
      -Aliases_Quantity 0
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDistribution](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CFInvalidation`
<a name="cloudfront_CreateInvalidation_powershell_4_topic"></a>

次のコード例は、`New-CFInvalidation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ID が EXAMPLENSTXAXE であるディストリビューションで、新しいキャッシュ削除を作成します。CallerReference はユーザーが選択した固有の ID です。この例では、2019 年 5 月 15 日の午前 9 時を表すタイムスタンプを使用しています。\$1Paths 変数には、ユーザーがディストリビューションのキャッシュに含めたくない画像ファイルやメディアファイルへの 3 つのパスが格納されます。-Paths\$1Quantity パラメータ値は、-Paths\$1Item パラメータで指定したパスの総数です。**  

```
$Paths = "/images/*.gif", "/images/image1.jpg", "/videos/*.mp4"
New-CFInvalidation -DistributionId "EXAMPLENSTXAXE" -InvalidationBatch_CallerReference 20190515090000 -Paths_Item $Paths -Paths_Quantity 3
```
**出力:**  

```
Invalidation                         Location                                                                                          
------------                         --------                                                                                          
Amazon.CloudFront.Model.Invalidation https://cloudfront.amazonaws.com/2018-11-05/distribution/EXAMPLENSTXAXE/invalidation/EXAMPLE8NOK9H
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateInvalidation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CFSignedCookie`
<a name="cloudfront_New-CFSignedCookie_powershell_4_topic"></a>

次のコード例は、`New-CFSignedCookie` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 既定ポリシーを使用して、指定されたリソースに署名付き Cookie を作成します。Cookie は 1 年間有効です。**  

```
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/image1.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddYears(1)
}
New-CFSignedCookie @params
```
**出力:**  

```
Expires
-------
[CloudFront-Expires, 1472227284]
```
**例 2: カスタムポリシーを使用して、指定リソースに署名付き Cookie を作成します。Cookie は 24 時間後に有効になり、1 週間後に期限切れになります。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/content/*.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=$start.AddDays(7)
    "ActiveFrom"=$start
}

New-CFSignedCookie @params
```
**出力:**  

```
Policy
------
[CloudFront-Policy, eyJTd...wIjo...
```
**例 3: カスタムポリシーを使用して、指定リソースに署名付き Cookie を作成します。Cookie は 24 時間後に有効になり、1 週間後に期限切れになります。リソースへのアクセスは、指定の IP 範囲に制限されます。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/content/*.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=$start.AddDays(7)
    "ActiveFrom"=$start
	"IpRange"="192.0.2.0/24"
}

New-CFSignedCookie @params
```
**出力:**  

```
Policy                                                                                                                                         ------                                                                                                                                         [CloudFront-Policy, eyJTd...wIjo...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[「New-CFSignedCookie](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CFSignedUrl`
<a name="cloudfront_New-CFSignedUrl_powershell_4_topic"></a>

次のコード例は、`New-CFSignedUrl` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 既定ポリシーを使用して、指定リソースへの署名付き URL を作成します。URL は 1 時間有効です。署名付き URL を含む System.Uri オブジェクトがパイプラインに出力されます。**  

```
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddHours(1)
}
New-CFSignedUrl @params
```
**例 2: カスタムポリシーを使用して、指定リソースへの署名付き URL を作成します。URL は 24 時間後に有効になり、1 週間後に期限切れになります。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddDays(7)
    "ActiveFrom"=$start
}
New-CFSignedUrl @params
```
**例 3: カスタムポリシーを使用して、指定リソースへの署名付き URL を作成します。URL は 24 時間後に有効になり、1 週間後に期限切れになります。リソースへのアクセスは、指定の IP 範囲に制限されます。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddDays(7)
    "ActiveFrom"=$start
    "IpRange"="192.0.2.0/24"	
}
New-CFSignedUrl @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[New-CFSignedUrl](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した CloudTrail の例
<a name="powershell_4_cloudtrail_code_examples"></a>

次のコード例は、CloudTrail で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Find-CTEvent`
<a name="cloudtrail_LookupEvents_powershell_4_topic"></a>

次のコード例は、`Find-CTEvent` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 過去 7 日間に発生したすべてのイベントを返します。コマンドレットはデフォルトで、すべてのイベントを配信するために複数の呼び出しを自動的に実行し、サービスがこれ以上データがないことを示した時点で終了します。**  

```
Find-CTEvent
```
**例 2: 現在のシェルのデフォルト以外のリージョンを指定して、過去 7 日間に発生したすべてのイベントを返します。**  

```
Find-CTEvent -Region eu-central-1
```
**例 3: RunInstances API コールに関連付けられているすべてのイベントを返します。**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**例 4: 使用可能な最初の 5 つのイベントを返します。**  

```
Find-CTEvent -MaxResult 5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[LookupEvents](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CTTrail`
<a name="cloudtrail_DescribeTrails_powershell_4_topic"></a>

次のコード例は、`Get-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: アカウントの現在のリージョンに関連付けられているすべての証跡の設定を返します。**  

```
Get-CTTrail
```
**例 2: 指定された証跡の設定を返します。**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**例 3: 現在のシェルのデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された、指定された証跡の設定を返します。**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTrails](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CTTrailStatus`
<a name="cloudtrail_GetTrailStatus_powershell_4_topic"></a>

次のコード例は、`Get-CTTrailStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「myExampleTrail」という名前の証跡のステータス情報を返します。返されるデータには、配信エラー、Amazon SNS および Amazon S3 エラー、証跡のログ記録の開始時間と停止時間に関する情報が含まれます。この例では、証跡が現在のシェルのデフォルトリージョンと同じリージョンで作成されたことを前提としています。**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**例 2: 現在のシェルのデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された証跡のステータス情報を返します。**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)*の「[GetTrailStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CTTrail`
<a name="cloudtrail_CreateTrail_powershell_4_topic"></a>

次のコード例は、`New-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ログファイルストレージにバケット「amzn-s3-demo-bucket」を使用する証跡を作成します。**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**例 2: ログファイルストレージにバケット「amzn-s3-demo-bucket」を使用する証跡を作成します。ログを表す S3 オブジェクトには、共通キープレフィックス「mylogs」があります。新しいログがバケットに配信されると、SNS トピック「mlog-deliverytopic」に通知が送信されます。この例では、スプラッティングを使用してパラメータ値をコマンドレットに指定します。**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTrail](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CTTrail`
<a name="cloudtrail_DeleteTrail_powershell_4_topic"></a>

次のコード例は、`Remove-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された証跡を削除します。コマンドを実行する前に確認を求められます。-Force スイッチを追加すると、確認メッセージが表示されなくなります。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTrail](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-CTLogging`
<a name="cloudtrail_StartLogging_powershell_4_topic"></a>

次のコード例は、`Start-CTLogging` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 'myExampleTrail' という名前の証跡の AWS API コールとログファイルの配信の記録を開始します。この例では、証跡が現在のシェルのデフォルトリージョンと同じリージョンで作成されたことを前提としています。**  

```
Start-CTLogging -Name myExampleTrail
```
**例 2: 現在のシェルデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された証跡の AWS API コールとログファイルの配信の記録を開始します。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartLogging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-CTLogging`
<a name="cloudtrail_StopLogging_powershell_4_topic"></a>

次のコード例は、`Stop-CTLogging` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 'myExampleTrail' という名前の証跡の AWS API コールとログファイル配信の記録を停止します。この例では、証跡が現在のシェルのデフォルトリージョンと同じリージョンで作成されたことを前提としています。**  

```
Stop-CTLogging -Name myExampleTrail
```
**例 2: 現在のシェルデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された証跡の AWS API コールとログファイル配信の記録を停止します。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)*の「[StopLogging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CTTrail`
<a name="cloudtrail_UpdateTrail_powershell_4_topic"></a>

次のコード例は、`Update-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: グローバルサービスイベント (IAM からのイベントなど) が記録されるように指定された証跡を更新し、以降のログファイルの共通キープレフィックスを「globallogs」に変更します。**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**例 2: 新しいログ配信に関する通知が指定された SNS トピックに送信されるように、指定された証跡を更新します。**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**例 3: ログが別のバケットに配信されるように、指定された証跡を更新します。**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateTrail](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した CloudWatch の例
<a name="powershell_4_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CWAlarm`
<a name="cloudwatch_DescribeAlarms_powershell_4_topic"></a>

次のコード例は、`Get-CWAlarm` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: CloudWatch から複合アラームとメトリクスアラームを含むすべてのアラームを返します。**  

```
Get-CWAlarm -MaxRecords 1
```
**出力:**  

```
CompositeAlarms MetricAlarms         NextToken
--------------- ------------         ---------
                {MetricAlarms-01}    NextToken-01
                {MetricAlarms-02}    NextToken-02
                {MetricAlarms-03}    NextToken-03
```
**例 2: -AlarmType パラメータを CompositeAlarms に設定した後、CloudWatch から複合アラームデータのみを返します。**  

```
Get-CWAlarm -AlarmType 'CompositeAlarms'
```
**出力:**  

```
CompositeAlarms        MetricAlarms NextToken
---------------        ------------ ---------
{CompositeAlarms-01}
{CompositeAlarms-02}
{CompositeAlarms-03}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAlarms](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CWDashboard`
<a name="cloudwatch_GetDashboard_powershell_4_topic"></a>

次のコード例は、`Get-CWDashboard` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたダッシュボードの本体である arn を返します。**  

```
Get-CWDashboard -DashboardName Dashboard1
```
**出力:**  

```
DashboardArn                                          DashboardBody
------------                                          -------------
arn:aws:cloudwatch::123456789012:dashboard/Dashboard1 {...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDashboard](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CWDashboardList`
<a name="cloudwatch_ListDashboards_powershell_4_topic"></a>

次のコード例は、`Get-CWDashboardList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: アカウントのダッシュボードのコレクションを返します。**  

```
Get-CWDashboardList
```
**出力:**  

```
DashboardArn DashboardName LastModified        Size
------------ ------------- ------------        ----
arn:...      Dashboard1    7/6/2017 8:14:15 PM 252
```
**例 2: 名前が 'dev' で始まるアカウントのダッシュボードのコレクションを返します。**  

```
Get-CWDashboardList -DashboardNamePrefix dev
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDashboards](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CWDashboard`
<a name="cloudwatch_DeleteDashboards_powershell_4_topic"></a>

次のコード例は、`Remove-CWDashboard` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定したダッシュボードを削除し、次に進む前に確認を促します。確認を省略するには、-Force スイッチをコマンドに追加します。**  

```
Remove-CWDashboard -DashboardName Dashboard1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteDashboards](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-CWDashboard`
<a name="cloudwatch_PutDashboard_powershell_4_topic"></a>

次のコード例は、`Write-CWDashboard` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 'Dashboard1' という名前のダッシュボードを作成または更新して、2 つのメトリクスウィジェットを並べて表示します。**  

```
$dashBody = @"
{
    "widgets":[
        {
             "type":"metric",
             "x":0,
             "y":0,
             "width":12,
             "height":6,
             "properties":{
                "metrics":[
                   [
                      "AWS/EC2",
                      "CPUUtilization",
                      "InstanceId",
                      "i-012345"
                   ]
                ],
                "period":300,
                "stat":"Average",
                "region":"us-east-1",
                "title":"EC2 Instance CPU"
             }
        },
        {
             "type":"metric",
             "x":12,
             "y":0,
             "width":12,
             "height":6,
             "properties":{
                "metrics":[
                   [
                      "AWS/S3",
                      "BucketSizeBytes",
                      "BucketName",
                      "amzn-s3-demo-bucket"
                   ]
                ],
                "period":86400,
                "stat":"Maximum",
                "region":"us-east-1",
                "title":"amzn-s3-demo-bucket bytes"
            }
        }
    ]
}
"@

Write-CWDashboard -DashboardName Dashboard1 -DashboardBody $dashBody
```
**例 2: ダッシュボードを作成または更新し、ダッシュボードを説明するコンテンツをコマンドレットにパイプします。**  

```
$dashBody = @"
{
...
}
"@
        
$dashBody | Write-CWDashboard -DashboardName Dashboard1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutDashboard](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-CWMetricData`
<a name="cloudwatch_PutMetricData_powershell_4_topic"></a>

次のコード例は、`Write-CWMetricData` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 新しい MetricDatum オブジェクトを作成し、Amazon Web Services の CloudWatch メトリクスに書き込みます。**  

```
### Create a MetricDatum .NET object
$Metric = New-Object -TypeName Amazon.CloudWatch.Model.MetricDatum
$Metric.Timestamp = [DateTime]::UtcNow
$Metric.MetricName = 'CPU'
$Metric.Value = 50

### Write the metric data to the CloudWatch service
Write-CWMetricData -Namespace instance1 -MetricData $Metric
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutMetricData](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した CodeCommit の例
<a name="powershell_4_codecommit_code_examples"></a>

次のコード例は、CodeCommit で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CCBranch`
<a name="codecommit_GetBranch_powershell_4_topic"></a>

次のコード例は、`Get-CCBranch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリの指定されたブランチに関する情報を取得します。**  

```
Get-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch
```
**出力:**  

```
BranchName                              CommitId
----------                              --------
MyNewBranch                             7763222d...561fc9c9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBranch](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CCBranchList`
<a name="codecommit_ListBranches_powershell_4_topic"></a>

次のコード例は、`Get-CCBranchList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリのブランチ名のリストを取得します。**  

```
Get-CCBranchList -RepositoryName MyDemoRepo
```
**出力:**  

```
master
MyNewBranch
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListBranches](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CCRepository`
<a name="codecommit_GetRepository_powershell_4_topic"></a>

次のコード例は、`Get-CCRepository` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリの情報を取得します。**  

```
Get-CCRepository -RepositoryName MyDemoRepo
```
**出力:**  

```
AccountId             : 80398EXAMPLE
Arn                   : arn:aws:codecommit:us-east-1:80398EXAMPLE:MyDemoRepo
CloneUrlHttp          : https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CloneUrlSsh           : ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CreationDate          : 9/8/2015 3:21:33 PM
DefaultBranch         :
LastModifiedDate      : 9/8/2015 3:21:33 PM
RepositoryDescription : This is a repository for demonstration purposes.
RepositoryId          : c7d0d2b0-ce40-4303-b4c3-38529EXAMPLE
RepositoryName        : MyDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetRepository](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CCRepositoryBatch`
<a name="codecommit_BatchGetRepositories_powershell_4_topic"></a>

次のコード例は、`Get-CCRepositoryBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリのうち、見つかったリポジトリと見つからないリポジトリを確認します。**  

```
Get-CCRepositoryBatch -RepositoryName MyDemoRepo, MyNewRepo, AMissingRepo
```
**出力:**  

```
Repositories                            RepositoriesNotFound
------------                            --------------------
{MyDemoRepo, MyNewRepo}                {AMissingRepo}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchGetRepositories](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CCRepositoryList`
<a name="codecommit_ListRepositories_powershell_4_topic"></a>

次のコード例は、`Get-CCRepositoryList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべてのリポジトリをリポジトリ名で昇順に一覧表示します。**  

```
Get-CCRepositoryList -Order Ascending -SortBy RepositoryName
```
**出力:**  

```
RepositoryId                            RepositoryName
------------                            --------------
c7d0d2b0-ce40-4303-b4c3-38529EXAMPLE    MyDemoRepo
05f30c66-e3e3-4f91-a0cd-1c84aEXAMPLE    MyNewRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListRepositories](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CCBranch`
<a name="codecommit_CreateBranch_powershell_4_topic"></a>

次のコード例は、`New-CCBranch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリの指定された名前と指定されたコミット ID を持つ新しいブランチを作成します。**  

```
New-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch -CommitId 7763222d...561fc9c9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateBranch](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CCRepository`
<a name="codecommit_CreateRepository_powershell_4_topic"></a>

次のコード例は、`New-CCRepository` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前と説明を持つ新しいリポジトリを作成します。**  

```
New-CCRepository -RepositoryName MyDemoRepo -RepositoryDescription "This is a repository for demonstration purposes."
```
**出力:**  

```
AccountId             : 80398EXAMPLE
Arn                   : arn:aws:codecommit:us-east-1:80398EXAMPLE:MyDemoRepo
CloneUrlHttp          : https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CloneUrlSsh           : ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CreationDate          : 9/18/2015 4:13:25 PM
DefaultBranch         :
LastModifiedDate      : 9/18/2015 4:13:25 PM
RepositoryDescription : This is a repository for demonstration purposes.
RepositoryId          : 43ef2443-3372-4b12-9e78-65c27EXAMPLE
RepositoryName        : MyDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateRepository](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CCRepository`
<a name="codecommit_DeleteRepository_powershell_4_topic"></a>

次のコード例は、`Remove-CCRepository` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリを強制的に削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでリポジトリを削除します。**  

```
Remove-CCRepository -RepositoryName MyDemoRepo
```
**出力:**  

```
43ef2443-3372-4b12-9e78-65c27EXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteRepository](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CCDefaultBranch`
<a name="codecommit_UpdateDefaultBranch_powershell_4_topic"></a>

次のコード例は、`Update-CCDefaultBranch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリのデフォルトブランチを指定されたブランチに変更します。**  

```
Update-CCDefaultBranch -RepositoryName MyDemoRepo -DefaultBranchName MyNewBranch
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateDefaultBranch](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CCRepositoryDescription`
<a name="codecommit_UpdateRepositoryDescription_powershell_4_topic"></a>

次のコード例は、`Update-CCRepositoryDescription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリの説明を変更します。**  

```
Update-CCRepositoryDescription -RepositoryName MyDemoRepo -RepositoryDescription "This is an updated description."
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[UpdateRepositoryDescription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Update-CCRepositoryName`
<a name="codecommit_UpdateRepositoryName_powershell_4_topic"></a>

次のコード例は、`Update-CCRepositoryName` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリポジトリの名前を変更します。**  

```
Update-CCRepositoryName -NewName MyDemoRepo2 -OldName MyDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateRepositoryName](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した CodeDeploy の例
<a name="powershell_4_codedeploy_code_examples"></a>

次のコード例は、CodeDeploy で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-CDOnPremiseInstanceTag`
<a name="codedeploy_AddTagsToOnPremisesInstances_powershell_4_topic"></a>

次のコード例は、`Add-CDOnPremiseInstanceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたオンプレミスインスタンスに指定されたキーと値を持つオンプレミスインスタンスタグを追加します。**  

```
Add-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddTagsToOnPremisesInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDApplication`
<a name="codedeploy_GetApplication_powershell_4_topic"></a>

次のコード例は、`Get-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションに関する情報を取得します。**  

```
Get-CDApplication -ApplicationName CodeDeployDemoApplication
```
**出力:**  

```
ApplicationId                           ApplicationName              CreateTime              LinkedToGitHub
-------------                           ---------------              ----------              --------------
e07fb938-091e-4f2f-8963-4d3e8EXAMPLE    CodeDeployDemoApplication    7/20/2015 9:49:48 PM    False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetApplication](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDApplicationBatch`
<a name="codedeploy_BatchGetApplications_powershell_4_topic"></a>

次のコード例は、`Get-CDApplicationBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションに関する情報を取得します。**  

```
Get-CDApplicationBatch -ApplicationName CodeDeployDemoApplication, CodePipelineDemoApplication
```
**出力:**  

```
ApplicationId                           ApplicationName              CreateTime              LinkedToGitHub
-------------                           ---------------              ----------              --------------
e07fb938-091e-4f2f-8963-4d3e8EXAMPLE    CodeDeployDemoApplication    7/20/2015 9:49:48 PM    False
1ecfd602-62f1-4038-8f0d-06688EXAMPLE    CodePipelineDemoApplication  8/13/2015 5:53:26 PM    False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchGetApplications](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDApplicationList`
<a name="codedeploy_ListApplications_powershell_4_topic"></a>

次のコード例は、`Get-CDApplicationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、使用可能なアプリケーションのリストを取得します。**  

```
Get-CDApplicationList
```
**出力:**  

```
CodeDeployDemoApplication
CodePipelineDemoApplication
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListApplications](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDApplicationRevision`
<a name="codedeploy_GetApplicationRevision_powershell_4_topic"></a>

次のコード例は、`Get-CDApplicationRevision` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションリビジョンに関する情報を取得します。**  

```
$revision = Get-CDApplicationRevision -ApplicationName CodeDeployDemoApplication -S3Location_Bucket amzn-s3-demo-bucket -Revision_RevisionType S3 -S3Location_Key 5xd27EX.zip -S3Location_BundleType zip -S3Location_ETag 4565c1ac97187f190c1a90265EXAMPLE
Write-Output ("Description = " + $revision.RevisionInfo.Description + ", RegisterTime = " + $revision.RevisionInfo.RegisterTime)
```
**出力:**  

```
Description = Application revision registered by Deployment ID: d-CX9CHN3EX, RegisterTime = 07/20/2015 23:46:42
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetApplicationRevision](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDApplicationRevisionList`
<a name="codedeploy_ListApplicationRevisions_powershell_4_topic"></a>

次のコード例は、`Get-CDApplicationRevisionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションで使用可能なリビジョンに関する情報を取得します。**  

```
ForEach ($revision in (Get-CDApplicationRevisionList -ApplicationName CodeDeployDemoApplication -Deployed Ignore)) {
>>   If ($revision.RevisionType -Eq "S3") {
>>     Write-Output ("Type = S3, Bucket = " + $revision.S3Location.Bucket + ", BundleType = " + $revision.S3Location.BundleType + ", ETag = " + $revision.S3Location.ETag + ", Key = " + $revision.S3Location.Key)
>>   }
>>   If ($revision.RevisionType -Eq "GitHub") {
>>     Write-Output ("Type = GitHub, CommitId = " + $revision.GitHubLocation.CommitId + ", Repository = " + $revision.GitHubLocation.Repository)
>>   }
>> }
>>
```
**出力:**  

```
Type = S3, Bucket = amzn-s3-demo-bucket, BundleType = zip, ETag = 4565c1ac97187f190c1a90265EXAMPLE, Key = 5xd27EX.zip
Type = GitHub, CommitId = f48933c3...76405362, Repository = MyGitHubUser/CodeDeployDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListApplicationRevisions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeployment`
<a name="codedeploy_GetDeployment_powershell_4_topic"></a>

次のコード例は、`Get-CDDeployment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイに関する概要情報を取得します。**  

```
Get-CDDeployment -DeploymentId d-QZMRGSTEX
```
**出力:**  

```
ApplicationName               : CodeDeployDemoApplication
CompleteTime                  : 7/23/2015 11:26:04 PM
CreateTime                    : 7/23/2015 11:24:43 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodeDeployDemoFleet
DeploymentId                  : d-QZMRGSTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded
```
**例 2: この例では、指定されたデプロイに参加しているインスタンスのステータスに関する情報を取得します。**  

```
(Get-CDDeployment -DeploymentId d-QZMRGSTEX).DeploymentOverview
```
**出力:**  

```
Failed     : 0
InProgress : 0
Pending    : 0
Skipped    : 0
Succeeded  : 3
```
**例 3: この例では、指定されたデプロイのアプリケーションリビジョンに関する情報を取得します。**  

```
(Get-CDDeployment -DeploymentId d-QZMRGSTEX).Revision.S3Location
```
**出力:**  

```
Bucket     : amzn-s3-demo-bucket
BundleType : zip
ETag       : cfbb81b304ee5e27efc21adaed3EXAMPLE
Key        : clzfqEX
Version    :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDeployment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentBatch`
<a name="codedeploy_BatchGetDeployments_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイに関する情報を取得します。**  

```
Get-CDDeploymentBatch -DeploymentId d-QZMRGSTEX, d-RR0T5KTEX
```
**出力:**  

```
ApplicationName               : CodeDeployDemoApplication
CompleteTime                  : 7/23/2015 11:26:04 PM
CreateTime                    : 7/23/2015 11:24:43 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodeDeployDemoFleet
DeploymentId                  : d-QZMRGSTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded

ApplicationName               : CodePipelineDemoApplication
CompleteTime                  : 7/23/2015 6:07:30 PM
CreateTime                    : 7/23/2015 6:06:29 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodePipelineDemoFleet
DeploymentId                  : d-RR0T5KTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchGetDeployments](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentConfig`
<a name="codedeploy_GetDeploymentConfig_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイ設定に関する概要情報を取得します。**  

```
Get-CDDeploymentConfig -DeploymentConfigName ThreeQuartersHealthy
```
**出力:**  

```
CreateTime              DeploymentConfigId                      DeploymentConfigName    MinimumHealthyHosts
----------              ------------------                      --------------------    -------------------
10/3/2014 4:32:30 PM    518a3950-d034-46a1-9d2c-3c949EXAMPLE    ThreeQuartersHealthy    Amazon.CodeDeploy.Model.MinimumHealthyHosts
```
**例 2: この例では、指定されたデプロイ設定の定義に関する情報を取得します。**  

```
Write-Output ((Get-CDDeploymentConfig -DeploymentConfigName ThreeQuartersHealthy).MinimumHealthyHosts)
```
**出力:**  

```
Type             Value
----             -----
FLEET_PERCENT    75
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDeploymentConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentConfigList`
<a name="codedeploy_ListDeploymentConfigs_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentConfigList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、使用可能なデプロイ設定のリストを取得します。**  

```
Get-CDDeploymentConfigList
```
**出力:**  

```
ThreeQuartersHealthy
CodeDeployDefault.OneAtATime
CodeDeployDefault.AllAtOnce
CodeDeployDefault.HalfAtATime
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDeploymentConfigs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentGroup`
<a name="codedeploy_GetDeploymentGroup_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイグループに関する情報を取得します。**  

```
Get-CDDeploymentGroup -ApplicationName CodeDeployDemoApplication -DeploymentGroupName CodeDeployDemoFleet
```
**出力:**  

```
ApplicationName              : CodeDeployDemoApplication
AutoScalingGroups            : {}
DeploymentConfigName         : CodeDeployDefault.OneAtATime
DeploymentGroupId            : 7d7c098a-b444-4b27-96ef-22791EXAMPLE
DeploymentGroupName          : CodeDeployDemoFleet
Ec2TagFilters                : {Name}
OnPremisesInstanceTagFilters : {}
ServiceRoleArn               : arn:aws:iam::80398EXAMPLE:role/CodeDeploySampleStack-4ph6EX-CodeDeployTrustRole-O9MWP7XTL8EX
TargetRevision               : Amazon.CodeDeploy.Model.RevisionLocation
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDeploymentGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentGroupList`
<a name="codedeploy_ListDeploymentGroups_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentGroupList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションのデプロイグループのリストを取得します。**  

```
Get-CDDeploymentGroupList -ApplicationName CodeDeployDemoApplication
```
**出力:**  

```
ApplicationName              DeploymentGroups                                    NextToken
---------------              ----------------                                    ---------
CodeDeployDemoApplication    {CodeDeployDemoFleet, CodeDeployProductionFleet}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDeploymentGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentInstance`
<a name="codedeploy_GetDeploymentInstance_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイの指定されたインスタンスに関する情報を取得します。**  

```
Get-CDDeploymentInstance -DeploymentId d-QZMRGSTEX -InstanceId i-254e22EX
```
**出力:**  

```
DeploymentId    : d-QZMRGSTEX
InstanceId      : arn:aws:ec2:us-east-1:80398EXAMPLE:instance/i-254e22EX
LastUpdatedAt   : 7/23/2015 11:25:24 PM
LifecycleEvents : {ApplicationStop, DownloadBundle, BeforeInstall, Install...}
Status          : Succeeded
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDeploymentInstance](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentInstanceList`
<a name="codedeploy_ListDeploymentInstances_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentInstanceList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイのインスタンス ID のリストを取得します。**  

```
Get-CDDeploymentInstanceList -DeploymentId d-QZMRGSTEX
```
**出力:**  

```
i-254e22EX
i-274e22EX
i-3b4e22EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDeploymentInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDDeploymentList`
<a name="codedeploy_ListDeployments_powershell_4_topic"></a>

次のコード例は、`Get-CDDeploymentList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションとデプロイグループのデプロイ ID のリストを取得します。**  

```
Get-CDDeploymentList -ApplicationName CodeDeployDemoApplication -DeploymentGroupName CodeDeployDemoFleet
```
**出力:**  

```
d-QZMRGSTEX
d-RR0T5KTEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDeployments](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDOnPremiseInstance`
<a name="codedeploy_GetOnPremisesInstance_powershell_4_topic"></a>

次のコード例は、`Get-CDOnPremiseInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたオンプレミスインスタンスに関する情報を取得します。**  

```
Get-CDOnPremiseInstance -InstanceName AssetTag12010298EX
```
**出力:**  

```
DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX_rDH556dxEX
InstanceName   : AssetTag12010298EX
RegisterTime   : 4/3/2015 6:36:24 PM
Tags           : {Name}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetOnPremisesInstance](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDOnPremiseInstanceBatch`
<a name="codedeploy_BatchGetOnPremisesInstances_powershell_4_topic"></a>

次のコード例は、`Get-CDOnPremiseInstanceBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたオンプレミスインスタンスに関する情報を取得します。**  

```
Get-CDOnPremiseInstanceBatch -InstanceName AssetTag12010298EX, AssetTag12010298EX-2
```
**出力:**  

```
DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployFRWUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX-2_XmeSz18rEX
InstanceName   : AssetTag12010298EX-2
RegisterTime   : 4/3/2015 6:38:52 PM
Tags           : {Name}

DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX_rDH556dxEX
InstanceName   : AssetTag12010298EX
RegisterTime   : 4/3/2015 6:36:24 PM
Tags           : {Name}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchGetOnPremisesInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CDOnPremiseInstanceList`
<a name="codedeploy_ListOnPremisesInstances_powershell_4_topic"></a>

次のコード例は、`Get-CDOnPremiseInstanceList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、使用可能なオンプレミスインスタンス名のリストを取得します。**  

```
Get-CDOnPremiseInstanceList
```
**出力:**  

```
AssetTag12010298EX
AssetTag12010298EX-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListOnPremisesInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CDApplication`
<a name="codedeploy_CreateApplication_powershell_4_topic"></a>

次のコード例は、`New-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した名前で新しいアプリケーションを作成します。**  

```
New-CDApplication -ApplicationName MyNewApplication
```
**出力:**  

```
f19e4b61-2231-4328-b0fd-e57f5EXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateApplication](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CDDeployment`
<a name="codedeploy_CreateDeployment_powershell_4_topic"></a>

次のコード例は、`New-CDDeployment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイ設定とアプリケーションリビジョンを使用して、指定されたアプリケーションとデプロイグループの新しいデプロイを作成します。**  

```
New-CDDeployment -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -IgnoreApplicationStopFailures $True -S3Location_Key aws-codedeploy_linux-master.zip -RevisionType S3
```
**出力:**  

```
d-ZHROG7UEX
```
**例 2: この例では、ブルー/グリーンデプロイの置き換え環境に含めるために、そのインスタンスを識別する必要がある EC2 インスタンスタグのグループを指定する方法を示します。**  

```
New-CDDeployment -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -IgnoreApplicationStopFailures $True -S3Location_Key aws-codedeploy_linux-master.zip -RevisionType S3 -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
**出力:**  

```
d-ZHROG7UEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDeployment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CDDeploymentConfig`
<a name="codedeploy_CreateDeploymentConfig_powershell_4_topic"></a>

次のコード例は、`New-CDDeploymentConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前と動作で新しいデプロイ設定を作成します。**  

```
New-CDDeploymentConfig -DeploymentConfigName AtLeastTwoHealthyHosts -MinimumHealthyHosts_Type HOST_COUNT -MinimumHealthyHosts_Value 2
```
**出力:**  

```
0f3e8187-44ef-42da-aeed-b6823EXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDeploymentConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CDDeploymentGroup`
<a name="codedeploy_CreateDeploymentGroup_powershell_4_topic"></a>

次のコード例は、`New-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションに対して指定された名前、Auto Scaling グループ、デプロイ設定、タグ、サービスロールを持つデプロイグループを作成します。**  

```
New-CDDeploymentGroup -ApplicationName MyNewApplication -AutoScalingGroup CodeDeployDemo-ASG -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -Ec2TagFilter @{Key="Name"; Type="KEY_AND_VALUE"; Value="CodeDeployDemo"} -ServiceRoleArn arn:aws:iam::80398EXAMPLE:role/CodeDeployDemo
```
**出力:**  

```
16bbf199-95fd-40fc-a909-0bbcfEXAMPLE
```
**例 2: この例では、ブルー/グリーンデプロイの置き換え環境に含めるために、そのインスタンスを識別する必要がある EC2 インスタンスタグのグループを指定する方法を示します。**  

```
New-CDDeploymentGroup -ApplicationName MyNewApplication -AutoScalingGroup CodeDeployDemo-ASG -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -Ec2TagFilter @{Key="Name"; Type="KEY_AND_VALUE"; Value="CodeDeployDemo"} -ServiceRoleArn arn:aws:iam::80398EXAMPLE:role/CodeDeployDemo -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
**出力:**  

```
16bbf199-95fd-40fc-a909-0bbcfEXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDeploymentGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-CDApplicationRevision`
<a name="codedeploy_RegisterApplicationRevision_powershell_4_topic"></a>

次のコード例は、`Register-CDApplicationRevision` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションに対し、指定された Amazon S3 ロケーションでアプリケーションリビジョンを登録します。**  

```
Register-CDApplicationRevision -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -S3Location_Key aws-codedeploy_linux-master.zip -Revision_RevisionType S3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterApplicationRevision](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-CDOnPremiseInstance`
<a name="codedeploy_RegisterOnPremisesInstance_powershell_4_topic"></a>

次のコード例は、`Register-CDOnPremiseInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前と IAM ユーザーでオンプレミスインスタンスを登録します。**  

```
Register-CDOnPremiseInstance -IamUserArn arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser -InstanceName AssetTag12010298EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CDApplication`
<a name="codedeploy_DeleteApplication_powershell_4_topic"></a>

次のコード例は、`Remove-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前のアプリケーションを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでアプリケーションを削除します。**  

```
Remove-CDApplication -ApplicationName MyNewApplication
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteApplication](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CDDeploymentConfig`
<a name="codedeploy_DeleteDeploymentConfig_powershell_4_topic"></a>

次のコード例は、`Remove-CDDeploymentConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前のデプロイ設定を削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでデプロイ設定を削除します。**  

```
Remove-CDDeploymentConfig -DeploymentConfigName AtLeastTwoHealthyHosts
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteDeploymentConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CDDeploymentGroup`
<a name="codedeploy_DeleteDeploymentGroup_powershell_4_topic"></a>

次のコード例は、`Remove-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションの指定された名前のデプロイグループを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでデプロイグループを削除します。**  

```
Remove-CDDeploymentGroup -ApplicationName MyNewApplication -DeploymentGroupName MyNewDeploymentGroup
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteDeploymentGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CDOnPremiseInstanceTag`
<a name="codedeploy_RemoveTagsFromOnPremisesInstances_powershell_4_topic"></a>

次のコード例は、`Remove-CDOnPremiseInstanceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前のオンプレミスインスタンスの指定されたタグを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでタグを削除します。**  

```
Remove-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveTagsFromOnPremisesInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-CDDeployment`
<a name="codedeploy_StopDeployment_powershell_4_topic"></a>

次のコード例は、`Stop-CDDeployment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたデプロイ ID を持つデプロイの停止を試みます。**  

```
Stop-CDDeployment -DeploymentId d-LJQNREYEX
```
**出力:**  

```
Status     StatusMessage
------     -------------
Pending    Stopping Pending. Stopping to schedule commands in the deployment instances
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の[StopDeployment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-CDOnPremiseInstance`
<a name="codedeploy_DeregisterOnPremisesInstance_powershell_4_topic"></a>

次のコード例は、`Unregister-CDOnPremiseInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前のオンプレミスインスタンスを登録解除します。**  

```
Unregister-CDOnPremiseInstance -InstanceName AssetTag12010298EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CDApplication`
<a name="codedeploy_UpdateApplication_powershell_4_topic"></a>

次のコード例は、`Update-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションの名前を変更します。**  

```
Update-CDApplication -ApplicationName MyNewApplication -NewApplicationName MyNewApplication-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateApplication](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CDDeploymentGroup`
<a name="codedeploy_UpdateDeploymentGroup_powershell_4_topic"></a>

次のコード例は、`Update-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーションの指定されたデプロイグループの名前を変更します。**  

```
Update-CDDeploymentGroup -ApplicationName MyNewApplication -CurrentDeploymentGroupName MyNewDeploymentGroup -NewDeploymentGroupName MyNewDeploymentGroup-2
```
**例 2: この例では、ブルー/グリーンデプロイの置き換え環境に含めるために、そのインスタンスを識別する必要がある EC2 インスタンスタグのグループを指定する方法を示します。**  

```
Update-CDDeploymentGroup -ApplicationName MyNewApplication -CurrentDeploymentGroupName MyNewDeploymentGroup -NewDeploymentGroupName MyNewDeploymentGroup-2 -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateDeploymentGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した CodePipeline の例
<a name="powershell_4_codepipeline_code_examples"></a>

次のコード例は、CodePipeline で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Confirm-CPJob`
<a name="codepipeline_AcknowledgeJob_powershell_4_topic"></a>

次のコード例は、`Confirm-CPJob` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、特定のジョブのステータスを取得します。**  

```
Confirm-CPJob -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE -Nonce 3
```
**出力:**  

```
Value
-----
InProgress
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AcknowledgeJob](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-CPStageTransition`
<a name="codepipeline_DisableStageTransition_powershell_4_topic"></a>

次のコード例は、`Disable-CPStageTransition` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたパイプライン内の指定されたステージに対してインバウンド移行を無効にします。**  

```
Disable-CPStageTransition -PipelineName CodePipelineDemo -Reason "Disabling temporarily." -StageName Beta -TransitionType Inbound
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableStageTransition](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-CPStageTransition`
<a name="codepipeline_EnableStageTransition_powershell_4_topic"></a>

次のコード例は、`Enable-CPStageTransition` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたパイプライン内の指定されたステージに対してインバウンド移行を有効にします。**  

```
Enable-CPStageTransition -PipelineName CodePipelineDemo -StageName Beta -TransitionType Inbound
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableStageTransition](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CPActionType`
<a name="codepipeline_ListActionTypes_powershell_4_topic"></a>

次のコード例は、`Get-CPActionType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された所有者が使用可能なすべてのアクションに関する情報を取得します。**  

```
ForEach ($actionType in (Get-CPActionType -ActionOwnerFilter AWS)) {
  Write-Output ("For Category = " + $actionType.Id.Category + ", Owner = " + $actionType.Id.Owner + ", Provider = " + $actionType.Id.Provider + ", Version = " + $actionType.Id.Version + ":")
  Write-Output ("  ActionConfigurationProperties:")
  ForEach ($acp in $actionType.ActionConfigurationProperties) {
    Write-Output ("    For " + $acp.Name + ":")
    Write-Output ("      Description = " + $acp.Description)
    Write-Output ("      Key = " + $acp.Key)
    Write-Output ("      Queryable = " + $acp.Queryable)
    Write-Output ("      Required = " + $acp.Required)
    Write-Output ("      Secret = " + $acp.Secret)
  }
  Write-Output ("  InputArtifactDetails:")
  Write-Output ("    MaximumCount = " + $actionType.InputArtifactDetails.MaximumCount)
  Write-Output ("    MinimumCount = " + $actionType.InputArtifactDetails.MinimumCount)
  Write-Output ("  OutputArtifactDetails:")
  Write-Output ("    MaximumCount = " + $actionType.OutputArtifactDetails.MaximumCount)
  Write-Output ("    MinimumCount = " + $actionType.OutputArtifactDetails.MinimumCount)
  Write-Output ("  Settings:")
  Write-Output ("    EntityUrlTemplate = " + $actionType.Settings.EntityUrlTemplate)
  Write-Output ("    ExecutionUrlTemplate = " + $actionType.Settings.ExecutionUrlTemplate)
}
```
**出力:**  

```
For Category = Deploy, Owner = AWS, Provider = ElasticBeanstalk, Version = 1:
  ActionConfigurationProperties:
    For ApplicationName:
      Description = The AWS Elastic Beanstalk Application name
      Key = True
      Queryable = False
      Required = True
      Secret = False
    For EnvironmentName:
      Description = The AWS Elastic Beanstalk Environment name
      Key = True
      Queryable = False
      Required = True
      Secret = False
  InputArtifactDetails:
    MaximumCount = 1
    MinimumCount = 1
  OutputArtifactDetails:
    MaximumCount = 0
    MinimumCount = 0
  Settings:
    EntityUrlTemplate = https://console.aws.amazon.com/elasticbeanstalk/r/application/{Config:ApplicationName}
    ExecutionUrlTemplate = https://console.aws.amazon.com/elasticbeanstalk/r/application/{Config:ApplicationName} 
For Category = Deploy, Owner = AWS, Provider = CodeDeploy, Version = 1:
  ActionConfigurationProperties:
    For ApplicationName:
      Description = The AWS CodeDeploy Application name
      Key = True
      Queryable = False
      Required = True
      Secret = False
    For DeploymentGroupName:
      Description = The AWS CodeDeploy Deployment Group name
      Key = True
      Queryable = False
      Required = True
      Secret = False
  InputArtifactDetails:
    MaximumCount = 1
    MinimumCount = 1
  OutputArtifactDetails:
    MaximumCount = 0
    MinimumCount = 0
  Settings:
    EntityUrlTemplate = https://console.aws.amazon.com/codedeploy/home?#/applications/{Config:ApplicationName}/deployment-groups/{Config:DeploymentGroupName}
    ExecutionUrlTemplate = https://console.aws.amazon.com/codedeploy/home?#/deployments/{ExternalExecutionId}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListActionTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CPActionableJobList`
<a name="codepipeline_PollForJobs_powershell_4_topic"></a>

次のコード例は、`Get-CPActionableJobList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアクションカテゴリ、所有者、プロバイダー、バージョン、およびクエリパラメータのすべての実行可能なジョブに関する情報を取得します。**  

```
Get-CPActionableJobList -ActionTypeId_Category Build -ActionTypeId_Owner Custom -ActionTypeId_Provider MyCustomProviderName -ActionTypeId_Version 1 -QueryParam @{"ProjectName" = "MyProjectName"}
```
**出力:**  

```
AccountId       Data                                 Id                                      Nonce
---------       ----                                 --                                      -----
80398EXAMPLE    Amazon.CodePipeline.Model.JobData    0de392f5-712d-4f41-ace3-f57a0EXAMPLE    3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PollForJobs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CPJobDetail`
<a name="codepipeline_GetJobDetails_powershell_4_topic"></a>

次のコード例は、`Get-CPJobDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたジョブに関する一般的な情報を取得します。**  

```
Get-CPJobDetail -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE
```
**出力:**  

```
AccountId       Data                                 Id
---------       ----                                 --
80398EXAMPLE    Amazon.CodePipeline.Model.JobData    f570dc12-5ef3-44bc-945a-6e133EXAMPLE
```
**例 2: この例では、指定されたジョブに関する詳細情報を取得します。**  

```
$jobDetails = Get-CPJobDetail -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE
Write-Output ("For Job " + $jobDetails.Id + ":")
Write-Output ("  AccountId = " + $jobDetails.AccountId)
$jobData = $jobDetails.Data
Write-Output ("  Configuration:")
ForEach ($key in $jobData.ActionConfiguration.Keys) {
  $value = $jobData.ActionConfiguration.$key
  Write-Output ("    " + $key + " = " + $value)
}
Write-Output ("  ActionTypeId:")
Write-Output ("    Category = " + $jobData.ActionTypeId.Category)
Write-Output ("    Owner = " + $jobData.ActionTypeId.Owner)
Write-Output ("    Provider = " + $jobData.ActionTypeId.Provider)
Write-Output ("    Version = " + $jobData.ActionTypeId.Version)
Write-Output ("  ArtifactCredentials:")
Write-Output ("    AccessKeyId = " + $jobData.ArtifactCredentials.AccessKeyId)
Write-Output ("    SecretAccessKey = " + $jobData.ArtifactCredentials.SecretAccessKey)
Write-Output ("    SessionToken = " + $jobData.ArtifactCredentials.SessionToken)
Write-Output ("  InputArtifacts:")
ForEach ($ia in $jobData.InputArtifacts) {
  Write-Output ("    " + $ia.Name)
}
Write-Output ("  OutputArtifacts:")
ForEach ($oa in $jobData.OutputArtifacts) {
  Write-Output ("    " + $oa.Name)
}
Write-Output ("  PipelineContext:")
$context = $jobData.PipelineContext
Write-Output ("    Name = " + $context.Action.Name)
Write-Output ("    PipelineName = " + $context.PipelineName)
Write-Output ("    Stage = " + $context.Stage.Name)
```
**出力:**  

```
For Job f570dc12-5ef3-44bc-945a-6e133EXAMPLE:
  AccountId = 80398EXAMPLE
  Configuration:
  ActionTypeId:
    Category = Build
    Owner = Custom
    Provider = MyCustomProviderName
    Version = 1
  ArtifactCredentials:
    AccessKeyId = ASIAIEI3...IXI6YREX
    SecretAccessKey = cqAFDhEi...RdQyfa2u
    SessionToken = AQoDYXdz...5u+lsAU=
  InputArtifacts:
    MyApp
  OutputArtifacts:
    MyAppBuild
  PipelineContext:
    Name = Build
    PipelineName = CodePipelineDemo
    Stage = Build
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetJobDetails](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CPPipeline`
<a name="codepipeline_GetPipeline_powershell_4_topic"></a>

次のコード例は、`Get-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたパイプラインに関する一般的な情報を取得します。**  

```
Get-CPPipeline -Name CodePipelineDemo -Version 1
```
**出力:**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {Source, Build, Beta, TestStage}
Version       : 1
```
**例 2: この例では、指定されたパイプラインに関する詳細情報を取得します。**  

```
$pipeline = Get-CPPipeline -Name CodePipelineDemo
Write-Output ("Name = " + $pipeline.Name)
Write-Output ("RoleArn = " + $pipeline.RoleArn)
Write-Output ("Version = " + $pipeline.Version)
Write-Output ("ArtifactStore:")
Write-Output ("  Location = " + $pipeline.ArtifactStore.Location)
Write-Output ("  Type = " + $pipeline.ArtifactStore.Type.Value)
Write-Output ("Stages:")
ForEach ($stage in $pipeline.Stages) {
  Write-Output ("  Name = " + $stage.Name)
  Write-Output ("    Actions:")
  ForEach ($action in $stage.Actions) {
    Write-Output ("      Name = " + $action.Name)
	Write-Output ("        Category = " + $action.ActionTypeId.Category)
	Write-Output ("        Owner = " + $action.ActionTypeId.Owner)
	Write-Output ("        Provider = " + $action.ActionTypeId.Provider)
	Write-Output ("        Version = " + $action.ActionTypeId.Version)
	Write-Output ("        Configuration:")
	ForEach ($key in $action.Configuration.Keys) {
	  $value = $action.Configuration.$key
	  Write-Output ("          " + $key + " = " + $value)
	}
	Write-Output ("        InputArtifacts:")
	ForEach ($ia in $action.InputArtifacts) {
	  Write-Output ("          " + $ia.Name)
	}
	ForEach ($oa in $action.OutputArtifacts) {
	  Write-Output ("          " + $oa.Name)
	}
	Write-Output ("        RunOrder = " + $action.RunOrder)
  }
}
```
**出力:**  

```
Name = CodePipelineDemo
RoleArn = arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Version = 3
ArtifactStore:
  Location = amzn-s3-demo-bucket
  Type = S3
Stages:
  Name = Source
    Actions:
      Name = Source
        Category = Source
        Owner = ThirdParty
        Provider = GitHub
        Version = 1
        Configuration:
          Branch = master
          OAuthToken = ****
          Owner = my-user-name
          Repo = MyRepoName
        InputArtifacts:
          MyApp
        RunOrder = 1
  Name = Build
    Actions:
      Name = Build
        Category = Build
        Owner = Custom
        Provider = MyCustomProviderName
        Version = 1
        Configuration:
          ProjectName = MyProjectName
        InputArtifacts:
          MyApp
          MyAppBuild
        RunOrder = 1
  Name = Beta
    Actions:
      Name = CodePipelineDemoFleet
        Category = Deploy
        Owner = AWS
        Provider = CodeDeploy
        Version = 1
        Configuration:
          ApplicationName = CodePipelineDemoApplication
          DeploymentGroupName = CodePipelineDemoFleet
        InputArtifacts:
          MyAppBuild
        RunOrder = 1
  Name = TestStage
    Actions:
      Name = MyJenkinsTestAction
        Category = Test
        Owner = Custom
        Provider = MyCustomTestProvider
        Version = 1
        Configuration:
          ProjectName = MyJenkinsProjectName
        InputArtifacts:
          MyAppBuild
        RunOrder = 1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPipeline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CPPipelineList`
<a name="codepipeline_ListPipelines_powershell_4_topic"></a>

次のコード例は、`Get-CPPipelineList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、使用可能なパイプラインのリストを取得します。**  

```
Get-CPPipelineList
```
**出力:**  

```
Created                  Name                Updated                  Version
-------                  ----                -------                  -------
8/13/2015 10:17:54 PM    CodePipelineDemo    8/13/2015 10:17:54 PM    3
7/8/2015 2:41:53 AM      MyFirstPipeline     7/22/2015 9:06:37 PM     7
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListPipelines](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CPPipelineState`
<a name="codepipeline_GetPipelineState_powershell_4_topic"></a>

次のコード例は、`Get-CPPipelineState` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたパイプラインのステージに関する一般的な情報を取得します。**  

```
Get-CPPipelineState -Name CodePipelineDemo
```
**出力:**  

```
Created         : 8/13/2015 10:17:54 PM
PipelineName    : CodePipelineDemo
PipelineVersion : 1
StageStates     : {Source, Build, Beta, TestStage}
Updated         : 8/13/2015 10:17:54 PM
```
**例 2: この例では、指定されたパイプラインの状態に関する詳細情報を取得します。**  

```
ForEach ($stageState in (Get-CPPipelineState -Name $arg).StageStates) {
  Write-Output ("For " + $stageState.StageName + ":")
  Write-Output ("  InboundTransitionState:")
  Write-Output ("    DisabledReason = " + $stageState.InboundTransitionState.DisabledReason)
  Write-Output ("    Enabled = " + $stageState.InboundTransitionState.Enabled)
  Write-Output ("    LastChangedAt = " + $stageState.InboundTransitionState.LastChangedAt)
  Write-Output ("    LastChangedBy = " + $stageState.InboundTransitionState.LastChangedBy)
  Write-Output ("  ActionStates:")
  ForEach ($actionState in $stageState.ActionStates) {
    Write-Output ("    For " + $actionState.ActionName + ":")
	Write-Output ("      CurrentRevision:")
    Write-Output ("        Created = " + $actionState.CurrentRevision.Created)
	Write-Output ("        RevisionChangeId = " + $actionState.CurrentRevision.RevisionChangeId)
	Write-Output ("        RevisionId = " + $actionState.CurrentRevision.RevisionId)
	Write-Output ("      EntityUrl = " + $actionState.EntityUrl)
	Write-Output ("      LatestExecution:")
    Write-Output ("        ErrorDetails:")
    Write-Output ("          Code = " + $actionState.LatestExecution.ErrorDetails.Code)
	Write-Output ("          Message = " + $actionState.LatestExecution.ErrorDetails.Message)
	Write-Output ("        ExternalExecutionId = " + $actionState.LatestExecution.ExternalExecutionId)
	Write-Output ("        ExternalExecutionUrl = " + $actionState.LatestExecution.ExternalExecutionUrl)
	Write-Output ("        LastStatusChange	= " + $actionState.LatestExecution.LastStatusChange)
	Write-Output ("        PercentComplete = " + $actionState.LatestExecution.PercentComplete)
	Write-Output ("        Status = " + $actionState.LatestExecution.Status)
	Write-Output ("        Summary = " + $actionState.LatestExecution.Summary)
	Write-Output ("      RevisionUrl = " + $actionState.RevisionUrl)
  }
}
```
**出力:**  

```
For Source:
  InboundTransitionState:
    DisabledReason =
    Enabled =
    LastChangedAt =
    LastChangedBy =
  ActionStates:
    For Source:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = https://github.com/my-user-name/MyRepoName/tree/master
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId =
        ExternalExecutionUrl =
        LastStatusChange = 07/20/2015 23:28:45
        PercentComplete = 0
        Status = Succeeded
        Summary =
      RevisionUrl =
For Build:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For Build:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = http://54.174.131.1EX/job/MyJenkinsDemo
      LatestExecution:
        ErrorDetails:
          Code = TimeoutError
          Message = The action failed because a job worker exceeded its time limit. If this is a custom action, make sure that the job worker is configured correctly.
        ExternalExecutionId =
        ExternalExecutionUrl =
        LastStatusChange = 07/21/2015 00:29:29
        PercentComplete = 0
        Status = Failed
        Summary =
      RevisionUrl =
For Beta:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For CodePipelineDemoFleet:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = https://console.aws.amazon.com/codedeploy/home?#/applications/CodePipelineDemoApplication/deployment-groups/CodePipelineDemoFleet
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId = d-D5LTCZXEX
        ExternalExecutionUrl = https://console.aws.amazon.com/codedeploy/home?#/deployments/d-D5LTCZXEX
        LastStatusChange = 07/08/2015 22:07:42
        PercentComplete = 0
        Status = Succeeded
        Summary = Deployment Succeeded
      RevisionUrl =
For TestStage:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For MyJenkinsTestAction25:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = http://54.174.131.1EX/job/MyJenkinsDemo
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId = 5
        ExternalExecutionUrl = http://54.174.131.1EX/job/MyJenkinsDemo/5
        LastStatusChange = 07/08/2015 22:09:03
        PercentComplete = 0
        Status = Succeeded
        Summary = Finished
      RevisionUrl =
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPipelineState](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CPCustomActionType`
<a name="codepipeline_CreateCustomActionType_powershell_4_topic"></a>

次のコード例は、`New-CPCustomActionType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたプロパティを使用して新しいカスタムアクションを作成します。**  

```
New-CPCustomActionType -Category Build -ConfigurationProperty @{"Description" = "The name of the build project must be provided when this action is added to the pipeline."; "Key" = $True; "Name" = "ProjectName"; "Queryable" = $False; "Required" = $True; "Secret" = $False; "Type" = "String"} -Settings_EntityUrlTemplate "https://my-build-instance/job/{Config:ProjectName}/" -Settings_ExecutionUrlTemplate "https://my-build-instance/job/mybuildjob/lastSuccessfulBuild{ExternalExecutionId}/" -InputArtifactDetails_MaximumCount 1 -OutputArtifactDetails_MaximumCount 1 -InputArtifactDetails_MinimumCount 0 -OutputArtifactDetails_MinimumCount 0 -Provider "MyBuildProviderName" -Version 1
```
**出力:**  

```
ActionConfigurationProperties : {ProjectName}
Id                            : Amazon.CodePipeline.Model.ActionTypeId
InputArtifactDetails          : Amazon.CodePipeline.Model.ArtifactDetails
OutputArtifactDetails         : Amazon.CodePipeline.Model.ArtifactDetails
Settings                      : Amazon.CodePipeline.Model.ActionTypeSettings
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateCustomActionType](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CPPipeline`
<a name="codepipeline_CreatePipeline_powershell_4_topic"></a>

次のコード例は、`New-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された設定で新しいパイプラインを作成します。**  

```
$pipeline = New-Object Amazon.CodePipeline.Model.PipelineDeclaration

$sourceStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration
$deployStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration

$sourceStageActionOutputArtifact = New-Object Amazon.CodePipeline.Model.OutputArtifact
$sourceStageActionOutputArtifact.Name = "MyApp"

$sourceStageAction.ActionTypeId = @{"Category" = "Source"; "Owner" = "AWS"; "Provider" = "S3"; "Version" = 1}
$sourceStageAction.Configuration.Add("S3Bucket", "amzn-s3-demo-bucket")
$sourceStageAction.Configuration.Add("S3ObjectKey", "my-object-key-name.zip")
$sourceStageAction.OutputArtifacts.Add($sourceStageActionOutputArtifact)
$sourceStageAction.Name = "Source"

$deployStageActionInputArtifact = New-Object Amazon.CodePipeline.Model.InputArtifact
$deployStageActionInputArtifact.Name = "MyApp"

$deployStageAction.ActionTypeId = @{"Category" = "Deploy"; "Owner" = "AWS"; "Provider" = "CodeDeploy"; "Version" = 1}
$deployStageAction.Configuration.Add("ApplicationName", "CodePipelineDemoApplication")
$deployStageAction.Configuration.Add("DeploymentGroupName", "CodePipelineDemoFleet")
$deployStageAction.InputArtifacts.Add($deployStageActionInputArtifact)
$deployStageAction.Name = "CodePipelineDemoFleet"

$sourceStage = New-Object Amazon.CodePipeline.Model.StageDeclaration
$deployStage = New-Object Amazon.CodePipeline.Model.StageDeclaration

$sourceStage.Name = "Source"
$deployStage.Name = "Beta"

$sourceStage.Actions.Add($sourceStageAction)
$deployStage.Actions.Add($deployStageAction)

$pipeline.ArtifactStore = @{"Location" = "amzn-s3-demo-bucket"; "Type" = "S3"}
$pipeline.Name = "CodePipelineDemo"
$pipeline.RoleArn = "arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole"
$pipeline.Stages.Add($sourceStage)
$pipeline.Stages.Add($deployStage)
$pipeline.Version = 1

New-CPPipeline -Pipeline $pipeline
```
**出力:**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {Source, Beta}
Version       : 1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreatePipeline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CPCustomActionType`
<a name="codepipeline_DeleteCustomActionType_powershell_4_topic"></a>

次のコード例は、`Remove-CPCustomActionType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したカスタムアクションを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでカスタムアクションを削除します。**  

```
Remove-CPCustomActionType -Category Build -Provider MyBuildProviderName -Version 1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteCustomActionType](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CPPipeline`
<a name="codepipeline_DeletePipeline_powershell_4_topic"></a>

次のコード例は、`Remove-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたパイプラインを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでパイプラインを削除します。**  

```
Remove-CPPipeline -Name CodePipelineDemo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeletePipeline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-CPPipelineExecution`
<a name="codepipeline_StartPipelineExecution_powershell_4_topic"></a>

次のコード例は、`Start-CPPipelineExecution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたパイプラインの実行を開始します。**  

```
Start-CPPipelineExecution -Name CodePipelineDemo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartPipelineExecution](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CPPipeline`
<a name="codepipeline_UpdatePipeline_powershell_4_topic"></a>

次のコード例は、`Update-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された設定で指定された既存のパイプラインを更新します。**  

```
$pipeline = New-Object Amazon.CodePipeline.Model.PipelineDeclaration

$sourceStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration
$deployStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration

$sourceStageActionOutputArtifact = New-Object Amazon.CodePipeline.Model.OutputArtifact
$sourceStageActionOutputArtifact.Name = "MyApp"

$sourceStageAction.ActionTypeId = @{"Category" = "Source"; "Owner" = "AWS"; "Provider" = "S3"; "Version" = 1}
$sourceStageAction.Configuration.Add("S3Bucket", "amzn-s3-demo-bucket")
$sourceStageAction.Configuration.Add("S3ObjectKey", "my-object-key-name.zip")
$sourceStageAction.OutputArtifacts.Add($sourceStageActionOutputArtifact)
$sourceStageAction.Name = "Source"

$deployStageActionInputArtifact = New-Object Amazon.CodePipeline.Model.InputArtifact
$deployStageActionInputArtifact.Name = "MyApp"

$deployStageAction.ActionTypeId = @{"Category" = "Deploy"; "Owner" = "AWS"; "Provider" = "CodeDeploy"; "Version" = 1}
$deployStageAction.Configuration.Add("ApplicationName", "CodePipelineDemoApplication")
$deployStageAction.Configuration.Add("DeploymentGroupName", "CodePipelineDemoFleet")
$deployStageAction.InputArtifacts.Add($deployStageActionInputArtifact)
$deployStageAction.Name = "CodePipelineDemoFleet"

$sourceStage = New-Object Amazon.CodePipeline.Model.StageDeclaration
$deployStage = New-Object Amazon.CodePipeline.Model.StageDeclaration

$sourceStage.Name = "MyInputFiles"
$deployStage.Name = "MyTestDeployment"

$sourceStage.Actions.Add($sourceStageAction)
$deployStage.Actions.Add($deployStageAction)

$pipeline.ArtifactStore = @{"Location" = "amzn-s3-demo-bucket"; "Type" = "S3"}
$pipeline.Name = "CodePipelineDemo"
$pipeline.RoleArn = "arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole"
$pipeline.Stages.Add($sourceStage)
$pipeline.Stages.Add($deployStage)
$pipeline.Version = 1

Update-CPPipeline -Pipeline $pipeline
```
**出力:**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {InputFiles, TestDeployment}
Version       : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdatePipeline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon Cognito ID の例
<a name="powershell_4_cognito-identity_code_examples"></a>

次のコード例は、Amazon Cognito Identity で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CGIIdentityPool`
<a name="cognito-identity_DescribeIdentityPool_powershell_4_topic"></a>

次のコード例は、`Get-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 特定のアイデンティティプールに関する情報をその ID を用いて取得します。**  

```
Get-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
**出力:**  

```
LoggedAt                       : 8/12/2015 4:29:40 PM
AllowUnauthenticatedIdentities : True
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
IdentityPoolName               : CommonTests1
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 142
HttpStatusCode                 : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeIdentityPool](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CGIIdentityPoolList`
<a name="cognito-identity_ListIdentityPools_powershell_4_topic"></a>

次のコード例は、`Get-CGIIdentityPoolList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 既存のアイデンティティプールのリストを取得します。**  

```
Get-CGIIdentityPoolList
```
**出力:**  

```
IdentityPoolId                                                     IdentityPoolName
--------------                                                     ----------------
us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1                     CommonTests1
us-east-1:118d242d-204e-4b88-b803-EXAMPLEGUID2                     Tests2
us-east-1:15d49393-ab16-431a-b26e-EXAMPLEGUID3                     CommonTests13
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListIdentityPools](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CGIIdentityPoolRole`
<a name="cognito-identity_GetIdentityPoolRoles_powershell_4_topic"></a>

次のコード例は、`Get-CGIIdentityPoolRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 特定のアイデンティティプールのロールに関する情報を取得します。**  

```
Get-CGIIdentityPoolRole -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
**出力:**  

```
LoggedAt         : 8/12/2015 4:33:51 PM
IdentityPoolId   : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
Roles            : {[unauthenticated, arn:aws:iam::123456789012:role/CommonTests1Role]}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 165
HttpStatusCode   : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-CGIIdentityPool`
<a name="cognito-identity_CreateIdentityPool_powershell_4_topic"></a>

次のコード例は、`New-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 認証されていない ID を許可する新しいアイデンティティプールを作成します。**  

```
New-CGIIdentityPool -AllowUnauthenticatedIdentities $true -IdentityPoolName CommonTests13
```
**出力:**  

```
LoggedAt                       : 8/12/2015 4:56:07 PM
AllowUnauthenticatedIdentities : True
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:15d49393-ab16-431a-b26e-EXAMPLEGUID3
IdentityPoolName               : CommonTests13
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 136
HttpStatusCode                 : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateIdentityPool](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CGIIdentityPool`
<a name="cognito-identity_DeleteIdentityPool_powershell_4_topic"></a>

次のコード例は、`Remove-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 特定のアイデンティティプールを削除します。**  

```
Remove-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[DeleteIdentityPool](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Set-CGIIdentityPoolRole`
<a name="cognito-identity_SetIdentityPoolRoles_powershell_4_topic"></a>

次のコード例は、`Set-CGIIdentityPoolRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 認証されていない IAM ロールを持つように特定のアイデンティティプールを設定します。**  

```
Set-CGIIdentityPoolRole -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1 -Role @{ "unauthenticated" = "arn:aws:iam::123456789012:role/CommonTests1Role" }
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-CGIIdentityPool`
<a name="cognito-identity_UpdateIdentityPool_powershell_4_topic"></a>

次のコード例は、`Update-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: アイデンティティプールプロパティの一部を更新します。この場合、アイデンティティプールの名前を更新します。**  

```
Update-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1 -IdentityPoolName NewPoolName
```
**出力:**  

```
LoggedAt                       : 8/12/2015 4:53:33 PM
AllowUnauthenticatedIdentities : False
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
IdentityPoolName               : NewPoolName
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 135
HttpStatusCode                 : OK
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[UpdateIdentityPool](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS Config Tools for PowerShell V4 を使用した の例
<a name="powershell_4_config-service_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Config。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-CFGResourceTag`
<a name="config-service_TagResource_powershell_4_topic"></a>

次のコード例は、`Add-CFGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定タグをリソース ARN に関連付けます。この場合、リソース ARN は config-rule/config-rule-16iyn0 です。**  

```
Add-CFGResourceTag -ResourceArn arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-16iyn0 -Tag @{Key="Release";Value="Beta"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregateComplianceByConfigRuleList`
<a name="config-service_DescribeAggregateComplianceByConfigRules_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregateComplianceByConfigRuleList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定の設定ルールの詳細を ConfigurationAggregatorの「kaju」フィルタリングから取得して、ルールの「コンプライアンス」を展開/返します。**  

```
Get-CFGAggregateComplianceByConfigRuleList -ConfigurationAggregatorName kaju -Filters_ConfigRuleName ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK | Select-Object -ExpandProperty Compliance
```
**出力:**  

```
ComplianceContributorCount                            ComplianceType
--------------------------                            --------------
Amazon.ConfigService.Model.ComplianceContributorCount NON_COMPLIANT
```
**例 2: この例では、指定の ConfigurationAggregator から詳細を取得し、アグリゲータの対象となるすべてのリージョンの指定アカウントに対してフィルタリングして、さらにすべてのルールのコンプライアンスを返します。**  

```
Get-CFGAggregateComplianceByConfigRuleList -ConfigurationAggregatorName kaju -Filters_AccountId 123456789012 | Select-Object ConfigRuleName, @{N="Compliance";E={$_.Compliance.ComplianceType}}
```
**出力:**  

```
ConfigRuleName                      Compliance
--------------                      ----------
ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK NON_COMPLIANT
ec2-instance-no-public-ip           NON_COMPLIANT
desired-instance-type               NON_COMPLIANT
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAggregateComplianceByConfigRules](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregateComplianceDetailsByConfigRule`
<a name="config-service_GetAggregateComplianceDetailsByConfigRule_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregateComplianceDetailsByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアカウント、アグリゲータ、リージョン、および設定ルールの「COMPLIANT」状態にある AWS Config ルールdesired-instance-type」の resource-id と resource-type の出力を選択する評価結果を返します。**  

```
Get-CFGAggregateComplianceDetailsByConfigRule -AccountId 123456789012 -AwsRegion eu-west-1 -ComplianceType COMPLIANT -ConfigRuleName desired-instance-type -ConfigurationAggregatorName raju | Select-Object -ExpandProperty EvaluationResultIdentifier | Select-Object -ExpandProperty EvaluationResultQualifier
```
**出力:**  

```
ConfigRuleName        ResourceId          ResourceType
--------------        ----------          ------------
desired-instance-type i-0f1bf2f34c5678d12 AWS::EC2::Instance
desired-instance-type i-0fd12dd3456789123 AWS::EC2::Instance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAggregateComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregateConfigRuleComplianceSummary`
<a name="config-service_GetAggregateConfigRuleComplianceSummary_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregateConfigRuleComplianceSummary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定アグリゲータの非準拠ルールの数を返します。**  

```
(Get-CFGAggregateConfigRuleComplianceSummary -ConfigurationAggregatorName raju).AggregateComplianceCounts.ComplianceSummary.NonCompliantResourceCount
```
**出力:**  

```
CapExceeded CappedCount
----------- -----------
False       5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAggregateConfigRuleComplianceSummary](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregateDiscoveredResourceCount`
<a name="config-service_GetAggregateDiscoveredResourceCounts_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregateDiscoveredResourceCount` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、us-east-1 リージョンでフィルタリングされた指定アグリゲータのリソース数を返します。**  

```
Get-CFGAggregateDiscoveredResourceCount -ConfigurationAggregatorName Master -Filters_Region us-east-1
```
**出力:**  

```
GroupByKey GroupedResourceCounts NextToken TotalDiscoveredResources
---------- --------------------- --------- ------------------------
           {}                              455
```
**例 2: この例では、特定のアグリゲータのフィルタリングされたリージョンの RESOURCE\$1TYPE 別にグループ化されたリソース数を返します。**  

```
Get-CFGAggregateDiscoveredResourceCount -ConfigurationAggregatorName Master -Filters_Region us-east-1 -GroupByKey RESOURCE_TYPE | 
			Select-Object -ExpandProperty GroupedResourceCounts
```
**出力:**  

```
GroupName                          ResourceCount
---------                          -------------
AWS::CloudFormation::Stack         12
AWS::CloudFront::Distribution      1
AWS::CloudTrail::Trail             1
AWS::DynamoDB::Table               1
AWS::EC2::EIP                      2
AWS::EC2::FlowLog                  2
AWS::EC2::InternetGateway          4
AWS::EC2::NatGateway               2
AWS::EC2::NetworkAcl               4
AWS::EC2::NetworkInterface         12
AWS::EC2::RouteTable               13
AWS::EC2::SecurityGroup            18
AWS::EC2::Subnet                   16
AWS::EC2::VPC                      4
AWS::EC2::VPCEndpoint              2
AWS::EC2::VPCPeeringConnection     1
AWS::IAM::Group                    2
AWS::IAM::Policy                   51
AWS::IAM::Role                     78
AWS::IAM::User                     7
AWS::Lambda::Function              3
AWS::RDS::DBSecurityGroup          1
AWS::S3::Bucket                    3
AWS::SSM::AssociationCompliance    107
AWS::SSM::ManagedInstanceInventory 108
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAggregateDiscoveredResourceCounts](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregateDiscoveredResourceList`
<a name="config-service_ListAggregateDiscoveredResources_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregateDiscoveredResourceList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「アイルランド」アグリゲータで集約された指定リソースタイプのリソース ID を返します。リソースタイプのリストについては、https://docs.aws.amazon.com/sdkfornet/v3/apidocs/index.html?page=ConfigService/TConfigServiceResourceType.html&tocid=Amazon\$1ConfigService\$1ResourceType を確認してください。**  

```
Get-CFGAggregateDiscoveredResourceList -ConfigurationAggregatorName Ireland -ResourceType ([Amazon.ConfigService.ResourceType]::AWSAutoScalingAutoScalingGroup)
```
**出力:**  

```
ResourceId      : arn:aws:autoscaling:eu-west-1:123456789012:autoScalingGroup:12e3b4fc-1234-1234-a123-1d2ba3c45678:autoScalingGroupName/asg-1
ResourceName    : asg-1
ResourceType    : AWS::AutoScaling::AutoScalingGroup
SourceAccountId : 123456789012
SourceRegion    : eu-west-1
```
**例 2: この例では、us-east-1 リージョンでフィルタリングされた指定アグリゲータの「default」という名前のリソースタイプ `AwsEC2SecurityGroup` を返します。**  

```
Get-CFGAggregateDiscoveredResourceList -ConfigurationAggregatorName raju -ResourceType ([Amazon.ConfigService.ResourceType]::AWSEC2SecurityGroup) -Filters_Region us-east-1 -Filters_ResourceName default
```
**出力:**  

```
ResourceId      : sg-01234bd5dbfa67c89
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1

ResourceId      : sg-0123a4ebbf56789be
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1

ResourceId      : sg-4fc1d234
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAggregateDiscoveredResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregateResourceConfig`
<a name="config-service_GetAggregateResourceconfig-service_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregateResourceConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、集約された指定リソースの設定項目を返して、設定を展開します。**  

```
(Get-CFGAggregateResourceConfig -ResourceIdentifier_SourceRegion us-east-1 -ResourceIdentifier_SourceAccountId 123456789012 -ResourceIdentifier_ResourceId sg-4fc1d234 -ResourceIdentifier_ResourceType ([Amazon.ConfigService.ResourceType]::AWSEC2SecurityGroup) -ConfigurationAggregatorName raju).Configuration | ConvertFrom-Json
```
**出力:**  

```
{"description":"default VPC security group","groupName":"default","ipPermissions":[{"ipProtocol":"-1","ipv6Ranges":[],"prefixListIds":[],"userIdGroupPairs":[{"groupId":"sg-4fc1d234","userId":"123456789012"}],"ipv4Ranges":[],"ipRanges":[]},{"fromPort":3389,"ipProtocol":"tcp","ipv6Ranges":[],"prefixListIds":[],"toPort":3389,"userIdGroupPairs":[],"ipv4Ranges":[{"cidrIp":"54.240.197.224/29","description":"office subnet"},{"cidrIp":"72.21.198.65/32","description":"home pc"}],"ipRanges":["54.240.197.224/29","72.21.198.65/32"]}],"ownerId":"123456789012","groupId":"sg-4fc1d234","ipPermissionsEgress":[{"ipProtocol":"-1","ipv6Ranges":[],"prefixListIds":[],"userIdGroupPairs":[],"ipv4Ranges":[{"cidrIp":"0.0.0.0/0"}],"ipRanges":["0.0.0.0/0"]}],"tags":[],"vpcId":"vpc-2d1c2e34"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAggregateResourceconfig-service](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregateResourceConfigBatch`
<a name="config-service_BatchGetAggregateResourceconfig-service_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregateResourceConfigBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定アグリゲータに存在するリソース (識別済み) の現在の設定項目を取得します。**  

```
$resIdentifier=[Amazon.ConfigService.Model.AggregateResourceIdentifier]@{
		ResourceId= "i-012e3cb4df567e8aa"
		ResourceName = "arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa"
		ResourceType = [Amazon.ConfigService.ResourceType]::AWSEC2Instance
		SourceAccountId = "123456789012"
		SourceRegion = "eu-west-1"
	}
		
	Get-CFGAggregateResourceConfigBatch -ResourceIdentifier $resIdentifier -ConfigurationAggregatorName raju
```
**出力:**  

```
BaseConfigurationItems UnprocessedResourceIdentifiers
---------------------- ------------------------------
{}                     {arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchGetAggregateResourceconfig-service](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGAggregationAuthorizationList`
<a name="config-service_DescribeAggregationAuthorizations_powershell_4_topic"></a>

次のコード例は、`Get-CFGAggregationAuthorizationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アグリゲータに付与された認証を取得します。**  

```
Get-CFGAggregationAuthorizationList
```
**出力:**  

```
AggregationAuthorizationArn                                                            AuthorizedAccountId AuthorizedAwsRegion CreationTime
---------------------------                                                            ------------------- ------------------- ------------
arn:aws:config-service:eu-west-1:123456789012:aggregation-authorization/123456789012/eu-west-1 123456789012        eu-west-1           8/26/2019 12:55:27 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAggregationAuthorizations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGComplianceByConfigRule`
<a name="config-service_DescribeComplianceByConfigRule_powershell_4_topic"></a>

次のコード例は、`Get-CFGComplianceByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ルールの現在の評価結果がないため、INSUFFICIENT\$1DATA が返されるルール ebs-optimized-instance のコンプライアンスの詳細を取得します。**  

```
(Get-CFGComplianceByConfigRule -ConfigRuleName ebs-optimized-instance).Compliance
```
**出力:**  

```
ComplianceContributorCount ComplianceType
-------------------------- --------------
                           INSUFFICIENT_DATA
```
**例 2: この例では、ルール ALB\$1HTTP\$1TO\$1HTTPS\$1REDIRECTION\$1CHECK の非準拠リソースの数を返します。**  

```
(Get-CFGComplianceByConfigRule -ConfigRuleName ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK -ComplianceType NON_COMPLIANT).Compliance.ComplianceContributorCount
```
**出力:**  

```
CapExceeded CappedCount
----------- -----------
False       2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeComplianceByConfigRule](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGComplianceByResource`
<a name="config-service_DescribeComplianceByResource_powershell_4_topic"></a>

次のコード例は、`Get-CFGComplianceByResource` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「COMPLIANT」コンプライアンスタイプの `AWS::SSM::ManagedInstanceInventory` リソースタイプを確認します。**  

```
Get-CFGComplianceByResource -ComplianceType COMPLIANT -ResourceType AWS::SSM::ManagedInstanceInventory
```
**出力:**  

```
Compliance                            ResourceId          ResourceType
----------                            ----------          ------------
Amazon.ConfigService.Model.Compliance i-0123bcf4b567890e3 AWS::SSM::ManagedInstanceInventory
Amazon.ConfigService.Model.Compliance i-0a1234f6f5d6b78f7 AWS::SSM::ManagedInstanceInventory
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeComplianceByResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGComplianceDetailsByConfigRule`
<a name="config-service_GetComplianceDetailsByConfigRule_powershell_4_topic"></a>

次のコード例は、`Get-CFGComplianceDetailsByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ルール access-keys-rotated の評価結果を取得し、コンプライアンスタイプ別にグループ化された出力を返します。**  

```
Get-CFGComplianceDetailsByConfigRule -ConfigRuleName access-keys-rotated | Group-Object ComplianceType
```
**出力:**  

```
Count Name                      Group
----- ----                      -----
    2 COMPLIANT                 {Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationResult}
    5 NON_COMPLIANT             {Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationRes...
```
**例 2: この例では、COMPLIANT リソースの access-keys-rotated ルールのコンプライアンスの詳細をクエリします。**  

```
Get-CFGComplianceDetailsByConfigRule -ConfigRuleName access-keys-rotated -ComplianceType COMPLIANT | ForEach-Object {$_.EvaluationResultIdentifier.EvaluationResultQualifier}
```
**出力:**  

```
ConfigRuleName      ResourceId            ResourceType
--------------      ----------            ------------
access-keys-rotated BCAB1CDJ2LITAPVEW3JAH AWS::IAM::User
access-keys-rotated BCAB1CDJ2LITL3EHREM4Q AWS::IAM::User
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGComplianceDetailsByResource`
<a name="config-service_GetComplianceDetailsByResource_powershell_4_topic"></a>

次のコード例は、`Get-CFGComplianceDetailsByResource` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリソースについて次のような結果が出ました。**  

```
Get-CFGComplianceDetailsByResource -ResourceId ABCD5STJ4EFGHIVEW6JAH -ResourceType 'AWS::IAM::User'
```
**出力:**  

```
Annotation                 :
ComplianceType             : COMPLIANT
ConfigRuleInvokedTime      : 8/25/2019 11:34:56 PM
EvaluationResultIdentifier : Amazon.ConfigService.Model.EvaluationResultIdentifier
ResultRecordedTime         : 8/25/2019 11:34:56 PM
ResultToken                :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetComplianceDetailsByResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGComplianceSummaryByConfigRule`
<a name="config-service_GetComplianceSummaryByConfigRule_powershell_4_topic"></a>

次のコード例は、`Get-CFGComplianceSummaryByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、非準拠の Config ルールの数を返します。**  

```
Get-CFGComplianceSummaryByConfigRule -Select ComplianceSummary.NonCompliantResourceCount
```
**出力:**  

```
CapExceeded CappedCount
----------- -----------
False       9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetComplianceSummaryByConfigRule](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGComplianceSummaryByResourceType`
<a name="config-service_GetComplianceSummaryByResourceType_powershell_4_topic"></a>

次のコード例は、`Get-CFGComplianceSummaryByResourceType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、準拠または非準拠のリソースの数を返し、出力を json に変換します。**  

```
Get-CFGComplianceSummaryByResourceType -Select ComplianceSummariesByResourceType.ComplianceSummary | ConvertTo-Json
{
  "ComplianceSummaryTimestamp": "2019-12-14T06:14:49.778Z",
  "CompliantResourceCount": {
    "CapExceeded": false,
    "CappedCount": 2
  },
  "NonCompliantResourceCount": {
    "CapExceeded": true,
    "CappedCount": 100
  }
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetComplianceSummaryByResourceType](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGConfigRule`
<a name="config-service_DescribeConfigRules_powershell_4_topic"></a>

次のコード例は、`Get-CFGConfigRule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、選択したプロパティを持つアカウントの設定ルールを一覧表示します。**  

```
Get-CFGConfigRule | Select-Object ConfigRuleName, ConfigRuleId, ConfigRuleArn, ConfigRuleState
```
**出力:**  

```
ConfigRuleName                                    ConfigRuleId       ConfigRuleArn                                                        ConfigRuleState
--------------                                    ------------       -------------                                                        ---------------
ALB_REDIRECTION_CHECK                             config-rule-12iyn3 arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-12iyn3 ACTIVE
access-keys-rotated                               config-rule-aospfr arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-aospfr ACTIVE
autoscaling-group-elb-healthcheck-required        config-rule-cn1f2x arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-cn1f2x ACTIVE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConfigRules](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGConfigRuleEvaluationStatus`
<a name="config-service_DescribeConfigRuleEvaluationStatus_powershell_4_topic"></a>

次のコード例は、`Get-CFGConfigRuleEvaluationStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定された設定ルールのステータス情報を返します。**  

```
Get-CFGConfigRuleEvaluationStatus -ConfigRuleName root-account-mfa-enabled, vpc-flow-logs-enabled
```
**出力:**  

```
ConfigRuleArn                : arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-kvq1wk
ConfigRuleId                 : config-rule-kvq1wk
ConfigRuleName               : root-account-mfa-enabled
FirstActivatedTime           : 8/27/2019 8:05:17 AM
FirstEvaluationStarted       : True
LastErrorCode                :
LastErrorMessage             :
LastFailedEvaluationTime     : 1/1/0001 12:00:00 AM
LastFailedInvocationTime     : 1/1/0001 12:00:00 AM
LastSuccessfulEvaluationTime : 12/13/2019 8:12:03 AM
LastSuccessfulInvocationTime : 12/13/2019 8:12:03 AM

ConfigRuleArn                : arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-z1s23b
ConfigRuleId                 : config-rule-z1s23b
ConfigRuleName               : vpc-flow-logs-enabled
FirstActivatedTime           : 8/14/2019 6:23:44 AM
FirstEvaluationStarted       : True
LastErrorCode                :
LastErrorMessage             :
LastFailedEvaluationTime     : 1/1/0001 12:00:00 AM
LastFailedInvocationTime     : 1/1/0001 12:00:00 AM
LastSuccessfulEvaluationTime : 12/13/2019 7:12:01 AM
LastSuccessfulInvocationTime : 12/13/2019 7:12:01 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConfigRuleEvaluationStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGConfigurationAggregatorList`
<a name="config-service_DescribeConfigurationAggregators_powershell_4_topic"></a>

次のコード例は、`Get-CFGConfigurationAggregatorList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リージョン/アカウントのすべてのアグリゲータを返します。**  

```
Get-CFGConfigurationAggregatorList
```
**出力:**  

```
AccountAggregationSources     : {Amazon.ConfigService.Model.AccountAggregationSource}
ConfigurationAggregatorArn    : arn:aws:config-service:eu-west-1:123456789012:config-aggregator/config-aggregator-xabca1me
ConfigurationAggregatorName   : IrelandMaster
CreationTime                  : 8/25/2019 11:42:39 PM
LastUpdatedTime               : 8/25/2019 11:42:39 PM
OrganizationAggregationSource :

AccountAggregationSources     : {}
ConfigurationAggregatorArn    : arn:aws:config-service:eu-west-1:123456789012:config-aggregator/config-aggregator-qubqabcd
ConfigurationAggregatorName   : raju
CreationTime                  : 8/11/2019 8:39:25 AM
LastUpdatedTime               : 8/11/2019 8:39:25 AM
OrganizationAggregationSource : Amazon.ConfigService.Model.OrganizationAggregationSource
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConfigurationAggregators](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGConfigurationAggregatorSourcesStatus`
<a name="config-service_DescribeConfigurationAggregatorSourcesStatus_powershell_4_topic"></a>

次のコード例は、`Get-CFGConfigurationAggregatorSourcesStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定アグリゲータ内のソースに対してリクエストされたフィールドを表示します。**  

```
Get-CFGConfigurationAggregatorSourcesStatus -ConfigurationAggregatorName raju | select SourceType, LastUpdateStatus, LastUpdateTime, SourceId
```
**出力:**  

```
SourceType   LastUpdateStatus LastUpdateTime        SourceId
----------   ---------------- --------------        --------
ORGANIZATION SUCCEEDED        12/31/2019 7:45:06 AM Organization
ACCOUNT      SUCCEEDED        12/31/2019 7:09:38 AM 612641234567
ACCOUNT      SUCCEEDED        12/31/2019 7:12:53 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:18:10 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:25:17 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:25:49 AM 612641234567
ACCOUNT      SUCCEEDED        12/31/2019 7:26:11 AM 612641234567
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConfigurationAggregatorSourcesStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGConfigurationRecorder`
<a name="config-service_DescribeConfigurationRecorders_powershell_4_topic"></a>

次のコード例は、`Get-CFGConfigurationRecorder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、設定レコーダーの詳細を返します。**  

```
Get-CFGConfigurationRecorder | Format-List
```
**出力:**  

```
Name           : default
RecordingGroup : Amazon.ConfigService.Model.RecordingGroup
RoleARN        : arn:aws:iam::123456789012:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConfigurationRecorders](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGConfigurationRecorderStatus`
<a name="config-service_DescribeConfigurationRecorderStatus_powershell_4_topic"></a>

次のコード例は、`Get-CFGConfigurationRecorderStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、設定レコーダーのステータスを返します。**  

```
Get-CFGConfigurationRecorderStatus
```
**出力:**  

```
LastErrorCode        :
LastErrorMessage     :
LastStartTime        : 10/11/2019 10:13:51 AM
LastStatus           : Success
LastStatusChangeTime : 12/31/2019 6:14:12 AM
LastStopTime         : 10/11/2019 10:13:46 AM
Name                 : default
Recording            : True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConfigurationRecorderStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGConformancePack`
<a name="config-service_DescribeConformancePacks_powershell_4_topic"></a>

次のコード例は、`Get-CFGConformancePack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべての適合パックを一覧表示します。**  

```
Get-CFGConformancePack
```
**出力:**  

```
ConformancePackArn             : arn:aws:config:eu-west-1:123456789012:conformance-pack/dono/conformance-pack-p0acq8bpz
ConformancePackId              : conformance-pack-p0acabcde
ConformancePackInputParameters : {}
ConformancePackName            : dono
CreatedBy                      :
DeliveryS3Bucket               : kt-ps-examples
DeliveryS3KeyPrefix            :
LastUpdateRequestedTime        : 12/31/2019 8:45:31 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConformancePacks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGDeliveryChannel`
<a name="config-service_DescribeDeliveryChannels_powershell_4_topic"></a>

次のコード例は、`Get-CFGDeliveryChannel` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リージョンの配信チャネルを取得し、詳細を表示します。**  

```
Get-CFGDeliveryChannel -Region eu-west-1 | Select-Object Name, S3BucketName, S3KeyPrefix, @{N="DeliveryFrequency";E={$_.ConfigSnapshotDeliveryProperties.DeliveryFrequency}}
```
**出力:**  

```
Name    S3BucketName               S3KeyPrefix DeliveryFrequency
----    ------------               ----------- -----------------
default config-bucket-NA my          TwentyFour_Hours
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDeliveryChannels](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-CFGResourceTag`
<a name="config-service_ListTagsForResource_powershell_4_topic"></a>

次のコード例は、`Get-CFGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定リソースに関連付けられたタグを一覧表示します。**  

```
Get-CFGResourceTag -ResourceArn $rules[0].ConfigRuleArn
```
**出力:**  

```
Key     Value
---     -----
Version 1.3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-CFGConformancePack`
<a name="config-service_DeleteConformancePack_powershell_4_topic"></a>

次のコード例は、`Remove-CFGConformancePack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定の適合パックと、パックのすべてのルール、修復アクション、評価結果を削除します。**  

```
Remove-CFGConformancePack -ConformancePackName dono
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-CFGConformancePack (DeleteConformancePack)" on target "dono".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteConformancePack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-CFGConformancePack`
<a name="config-service_PutConformancePack_powershell_4_topic"></a>

次のコード例は、`Write-CFGConformancePack` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、適合パックを作成し、指定の yaml ファイルからテンプレートを取得します。 **  

```
Write-CFGConformancePack -ConformancePackName dono -DeliveryS3Bucket amzn-s3-demo-bucket -TemplateBody (Get-Content C:\windows\temp\template.yaml -Raw)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutConformancePack](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-CFGDeliveryChannel`
<a name="config-service_PutDeliveryChannel_powershell_4_topic"></a>

次のコード例は、`Write-CFGDeliveryChannel` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、既存の配信チャネルの deliveryFrequency プロパティを変更します。**  

```
Write-CFGDeliveryChannel -ConfigSnapshotDeliveryProperties_DeliveryFrequency TwentyFour_Hours -DeliveryChannelName default -DeliveryChannel_S3BucketName amzn-s3-demo-bucket -DeliveryChannel_S3KeyPrefix my
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutDeliveryChannel](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Device Farm の例
<a name="powershell_4_device-farm_code_examples"></a>

次のコード例は、Device Farm で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-DFUpload`
<a name="device-farm_CreateUpload_powershell_4_topic"></a>

次のコード例は、`New-DFUpload` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Android アプリの AWS Device Farm アップロードを作成します。プロジェクト ARN は、New-DFProject または Get-DFProjectList の出力から取得できます。New-DFUpload 出力内の署名付き URL を使用して、ファイルを Device Farm にアップロードします。**  

```
New-DFUpload -ContentType "application/octet-stream" -ProjectArn "arn:aws:devicefarm:us-west-2:123456789012:project:EXAMPLEa-7ec1-4741-9c1f-d3e04EXAMPLE" -Name "app.apk" -Type ANDROID_APP
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateUpload](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Directory Service Tools for PowerShell V4 を使用した の例
<a name="powershell_4_directory-service_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています Directory Service。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-DSIpRoute`
<a name="directory-service_AddIpRoutes_powershell_4_topic"></a>

次のコード例は、`Add-DSIpRoute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 Directory-id に割り当てられたリソースタグを削除します**  

```
Add-DSIpRoute -DirectoryId d-123456ijkl -IpRoute @{CidrIp ="203.0.113.5/32"} -UpdateSecurityGroupForDirectoryController $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddIpRoutes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-DSResourceTag`
<a name="directory-service_AddTagsToResource_powershell_4_topic"></a>

次のコード例は、`Add-DSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定の Directory-id にリソースタグを追加します。**  

```
Add-DSResourceTag -ResourceId d-123456ijkl -Tag @{Key="myTag"; Value="mytgValue"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddTagsToResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Approve-DSTrust`
<a name="directory-service_VerifyTrust_powershell_4_topic"></a>

次のコード例は、`Approve-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された Trustid の AWS Directory Service VerifyTrust API オペレーションを呼び出します。**  

```
Approve-DSTrust -TrustId t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[VerifyTrust](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Confirm-DSSharedDirectory`
<a name="directory-service_AcceptSharedDirectory_powershell_4_topic"></a>

次のコード例は、`Confirm-DSSharedDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリ所有者から送信されたディレクトリ共有リクエストを受け入れます AWS アカウント。**  

```
Confirm-DSSharedDirectory -SharedDirectoryId d-9067012345
```
**出力:**  

```
CreatedDateTime     : 12/30/2019 4:20:27 AM
LastUpdatedDateTime : 12/30/2019 4:21:40 AM
OwnerAccountId      : 123456781234
OwnerDirectoryId    : d-123456ijkl
SharedAccountId     : 123456784321
SharedDirectoryId   : d-9067012345
ShareMethod         :
ShareNotes          : This is test sharing
ShareStatus         : Sharing
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AcceptSharedDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Connect-DSDirectory`
<a name="directory-service_ConnectDirectory_powershell_4_topic"></a>

次のコード例は、`Connect-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、オンプレミスディレクトリに接続するための AD Connector を作成します。**  

```
Connect-DSDirectory -Name contoso.com -ConnectSettings_CustomerUserName Administrator -Password $Password -ConnectSettings_CustomerDnsIp 172.31.36.96 -ShortName CONTOSO -Size Small -ConnectSettings_VpcId vpc-123459da -ConnectSettings_SubnetId subnet-1234ccaa, subnet-5678ffbb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ConnectDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Deny-DSSharedDirectory`
<a name="directory-service_RejectSharedDirectory_powershell_4_topic"></a>

次のコード例は、`Deny-DSSharedDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリ所有者アカウントから送信されたディレクトリ共有リクエストを拒否します。**  

```
Deny-DSSharedDirectory -SharedDirectoryId d-9067012345
```
**出力:**  

```
d-9067012345
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RejectSharedDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-DSDirectoryShare`
<a name="directory-service_UnshareDirectory_powershell_4_topic"></a>

次のコード例は、`Disable-DSDirectoryShare` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリ所有者とコンシューマーアカウントの間のディレクトリ共有を停止します。**  

```
Disable-DSDirectoryShare -DirectoryId d-123456ijkl -UnshareTarget_Id 123456784321 -UnshareTarget_Type ACCOUNT
```
**出力:**  

```
d-9067012345
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UnshareDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-DSLDAPS`
<a name="directory-service_DisableLDAPS_powershell_4_topic"></a>

次のコード例は、`Disable-DSLDAPS` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ディレクトリの LDAP セキュアコールを非アクティブ化します。**  

```
Disable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableLDAPS](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-DSRadius`
<a name="directory-service_DisableRadius_powershell_4_topic"></a>

次のコード例は、`Disable-DSRadius` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AD Connector または Microsoft AD ディレクトリ用に設定された RADIUS サーバーを無効にします。**  

```
Disable-DSRadius -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableRadius](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-DSSso`
<a name="directory-service_DisableSso_powershell_4_topic"></a>

次のコード例は、`Disable-DSSso` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリのシングルサインオンを無効にします。**  

```
Disable-DSSso -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableSso](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-DSDirectoryShare`
<a name="directory-service_ShareDirectory_powershell_4_topic"></a>

次のコード例は、`Enable-DSDirectoryShare` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Handshake メソッドを使用して AWS 、アカウント内の指定されたディレクトリを別の AWS アカウントと共有します。 **  

```
Enable-DSDirectoryShare -DirectoryId d-123456ijkl -ShareTarget_Id 123456784321 -ShareMethod HANDSHAKE -ShareTarget_Type ACCOUNT
```
**出力:**  

```
d-9067012345
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ShareDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-DSLDAPS`
<a name="directory-service_EnableLDAPS_powershell_4_topic"></a>

次のコード例は、`Enable-DSLDAPS` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ディレクトリのスイッチをアクティブ化して、常に LDAP セキュアコールを使用するようにします。**  

```
Enable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableLDAPS](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-DSRadius`
<a name="directory-service_EnableRadius_powershell_4_topic"></a>

次のコード例は、`Enable-DSRadius` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AD Connector または Microsoft AD ディレクトリ用に指定された RADIUS サーバー設定で多要素認証 (MFA) を有効にします。**  

```
Enable-DSRadius -DirectoryId d-123456ijkl 
-RadiusSettings_AuthenticationProtocol PAP 
-RadiusSettings_DisplayLabel Radius 
-RadiusSettings_RadiusPort 1812 
-RadiusSettings_RadiusRetry 4 
-RadiusSettings_RadiusServer 10.4.185.113 
-RadiusSettings_RadiusTimeout 50 
-RadiusSettings_SharedSecret wJalrXUtnFEMI
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableRadius](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-DSSso`
<a name="directory-service_EnableSso_powershell_4_topic"></a>

次のコード例は、`Enable-DSSso` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリのシングルサインオンを有効にします。 **  

```
Enable-DSSso -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableSso](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSCertificate`
<a name="directory-service_DescribeCertificate_powershell_4_topic"></a>

次のコード例は、`Get-DSCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、セキュリティ保護された LDAP 接続に登録された証明書に関する情報を表示します。**  

```
Get-DSCertificate -DirectoryId d-123456ijkl -CertificateId c-906731e34f
```
**出力:**  

```
CertificateId      : c-906731e34f
CommonName         : contoso-EC2AMAZ-CTGG2NM-CA
ExpiryDateTime     : 4/15/2025 6:34:15 PM
RegisteredDateTime : 4/15/2020 6:38:56 PM
State              : Registered
StateReason        : Certificate registered successfully.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSCertificateList`
<a name="directory-service_ListCertificates_powershell_4_topic"></a>

次のコード例は、`Get-DSCertificateList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ディレクトリのセキュリティ保護された LDAP 接続用に登録されたすべての証明書が一覧表示されます。**  

```
Get-DSCertificateList -DirectoryId d-123456ijkl
```
**出力:**  

```
CertificateId CommonName                 ExpiryDateTime       State
------------- ----------                 --------------       -----
c-906731e34f  contoso-EC2AMAZ-CTGG2NM-CA 4/15/2025 6:34:15 PM Registered
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListCertificates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSConditionalForwarder`
<a name="directory-service_DescribeConditionalForwarders_powershell_4_topic"></a>

次のコード例は、`Get-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 Directory-id の設定済みの条件付きフォワーダーをすべて取得します。**  

```
Get-DSConditionalForwarder -DirectoryId d-123456ijkl
```
**出力:**  

```
DnsIpAddrs      RemoteDomainName ReplicationScope
----------      ---------------- ----------------
{172.31.77.239} contoso.com      Domain
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeConditionalForwarders](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSDirectory`
<a name="directory-service_DescribeDirectories_powershell_4_topic"></a>

次のコード例は、`Get-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、このアカウントに属するディレクトリに関する情報を取得します。**  

```
Get-DSDirectory | Select-Object DirectoryId, Name, DnsIpAddrs, Type
```
**出力:**  

```
DirectoryId  Name           DnsIpAddrs                     Type
-----------  ----           ----------                     ----
d-123456abcd abcd.example.com {172.31.74.189, 172.31.13.145} SimpleAD
d-123456efgh wifi.example.com {172.31.16.108, 172.31.10.56}  ADConnector
d-123456ijkl lan2.example.com {172.31.10.56, 172.31.16.108}  MicrosoftAD
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDirectories](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSDirectoryLimit`
<a name="directory-service_GetDirectoryLimits_powershell_4_topic"></a>

次のコード例は、`Get-DSDirectoryLimit` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、us-east-1 リージョンのディレクトリ制限情報を表示します。**  

```
Get-DSDirectoryLimit -Region us-east-1
```
**出力:**  

```
CloudOnlyDirectoriesCurrentCount : 1
CloudOnlyDirectoriesLimit        : 10
CloudOnlyDirectoriesLimitReached : False
CloudOnlyMicrosoftADCurrentCount : 1
CloudOnlyMicrosoftADLimit        : 20
CloudOnlyMicrosoftADLimitReached : False
ConnectedDirectoriesCurrentCount : 1
ConnectedDirectoriesLimit        : 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDirectoryLimits](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSDomainControllerList`
<a name="directory-service_DescribeDomainControllers_powershell_4_topic"></a>

次のコード例は、`Get-DSDomainControllerList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 directory-id に対して起動されたドメインコントローラーの詳細なリストを取得します。**  

```
Get-DSDomainControllerList -DirectoryId d-123456ijkl
```
**出力:**  

```
AvailabilityZone          : us-east-1b
DirectoryId               : d-123456ijkl
DnsIpAddr                 : 172.31.16.108
DomainControllerId        : dc-1234567aa6
LaunchTime                : 4/4/2019 4:53:43 AM
Status                    : Active
StatusLastUpdatedDateTime : 4/24/2019 1:37:54 PM
StatusReason              :
SubnetId                  : subnet-1234kkaa
VpcId                     : vpc-123459d

AvailabilityZone          : us-east-1d
DirectoryId               : d-123456ijkl
DnsIpAddr                 : 172.31.10.56
DomainControllerId        : dc-1234567aa7
LaunchTime                : 4/4/2019 4:53:43 AM
Status                    : Active
StatusLastUpdatedDateTime : 4/4/2019 5:14:31 AM
StatusReason              :
SubnetId                  : subnet-5678ffbb
VpcId                     : vpc-123459d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDomainControllers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSEventTopic`
<a name="directory-service_DescribeEventTopics_powershell_4_topic"></a>

次のコード例は、`Get-DSEventTopic` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、ディレクトリのステータスが変更されたときの通知用に設定された SNS トピックの情報を表示します。**  

```
Get-DSEventTopic -DirectoryId d-123456ijkl
```
**出力:**  

```
CreatedDateTime : 12/13/2019 11:15:32 AM
DirectoryId     : d-123456ijkl
Status          : Registered
TopicArn        : arn:aws:sns:us-east-1:123456781234:snstopicname
TopicName       : snstopicname
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEventTopics](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSIpRouteList`
<a name="directory-service_ListIpRoutes_powershell_4_topic"></a>

次のコード例は、`Get-DSIpRouteList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、ディレクトリ IP ルーティングで設定されたパブリック IP アドレスブロックを取得します。**  

```
Get-DSIpRouteList -DirectoryId d-123456ijkl
```
**出力:**  

```
AddedDateTime       : 12/13/2019 12:27:22 PM
CidrIp              : 203.0.113.5/32
Description         : Public IP of On-Prem DNS Server
DirectoryId         : d-123456ijkl
IpRouteStatusMsg    : Added
IpRouteStatusReason :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListIpRoutes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSLDAPSSetting`
<a name="directory-service_DescribeLDAPSSettings_powershell_4_topic"></a>

次のコード例は、`Get-DSLDAPSSetting` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ディレクトリの LDAP セキュリティのステータスを説明します。**  

```
Get-DSLDAPSSetting -DirectoryId d-123456ijkl
```
**出力:**  

```
LastUpdatedDateTime  LDAPSStatus LDAPSStatusReason
-------------------  ----------- -----------------
4/15/2020 6:51:03 PM Enabled     LDAPS is enabled successfully.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLDAPSSettings](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSLogSubscriptionList`
<a name="directory-service_ListLogSubscriptions_powershell_4_topic"></a>

次のコード例は、`Get-DSLogSubscriptionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 directory-id のログサブスクリプション情報を取得します。**  

```
Get-DSLogSubscriptionList -DirectoryId d-123456ijkl
```
**出力:**  

```
DirectoryId  LogGroupName                                        SubscriptionCreatedDateTime
-----------  ------------                                        ---------------------------
d-123456ijkl /aws/directoryservice/d-123456ijkl-lan2.example.com 12/14/2019 9:05:23 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListLogSubscriptions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSResourceTag`
<a name="directory-service_ListTagsForResource_powershell_4_topic"></a>

次のコード例は、`Get-DSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定ディレクトリのすべてのタグを取得します。**  

```
Get-DSResourceTag -ResourceId d-123456ijkl
```
**出力:**  

```
Key   Value
---   -----
myTag myTagValue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSSchemaExtension`
<a name="directory-service_ListSchemaExtensions_powershell_4_topic"></a>

次のコード例は、`Get-DSSchemaExtension` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Microsoft AD ディレクトリに適用されているすべてのスキーマ拡張を一覧表示します。**  

```
Get-DSSchemaExtension -DirectoryId d-123456ijkl
```
**出力:**  

```
Description                 : ManagedADSchemaExtension
DirectoryId                 : d-123456ijkl
EndDateTime                 : 4/12/2020 10:30:49 AM
SchemaExtensionId           : e-9067306643
SchemaExtensionStatus       : Completed
SchemaExtensionStatusReason : Schema updates are complete.
StartDateTime               : 4/12/2020 10:28:42 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListSchemaExtensions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSSharedDirectory`
<a name="directory-service_DescribeSharedDirectories_powershell_4_topic"></a>

次のコード例は、`Get-DSSharedDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウントの共有ディレクトリを取得します。**  

```
Get-DSSharedDirectory -OwnerDirectoryId d-123456ijkl -SharedDirectoryId d-9067012345
```
**出力:**  

```
CreatedDateTime     : 12/30/2019 4:34:37 AM
LastUpdatedDateTime : 12/30/2019 4:35:22 AM
OwnerAccountId      : 123456781234
OwnerDirectoryId    : d-123456ijkl
SharedAccountId     : 123456784321
SharedDirectoryId   : d-9067012345
ShareMethod         : HANDSHAKE
ShareNotes          : This is a test Sharing
ShareStatus         : Shared
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSharedDirectories](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSSnapshot`
<a name="directory-service_DescribeSnapshots_powershell_4_topic"></a>

次のコード例は、`Get-DSSnapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、このアカウントに属する指定ディレクトリのスナップショットに関する情報を取得します。**  

```
Get-DSSnapshot -DirectoryId d-123456ijkl
```
**出力:**  

```
DirectoryId : d-123456ijkl
Name        :
SnapshotId  : s-9064bd1234
StartTime   : 12/13/2019 6:33:01 PM
Status      : Completed
Type        : Auto

DirectoryId : d-123456ijkl
Name        :
SnapshotId  : s-9064bb4321
StartTime   : 12/9/2019 9:48:11 PM
Status      : Completed
Type        : Auto
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSnapshots](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSSnapshotLimit`
<a name="directory-service_GetSnapshotLimits_powershell_4_topic"></a>

次のコード例は、`Get-DSSnapshotLimit` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定ディレクトリの手動スナップショット制限を取得します。**  

```
Get-DSSnapshotLimit -DirectoryId d-123456ijkl
```
**出力:**  

```
ManualSnapshotsCurrentCount ManualSnapshotsLimit ManualSnapshotsLimitReached
--------------------------- -------------------- ---------------------------
0                           5                    False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetSnapshotLimits](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DSTrust`
<a name="directory-service_DescribeTrusts_powershell_4_topic"></a>

次のコード例は、`Get-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定された directory-id 用に作成された信頼関係の情報を取得します。**  

```
Get-DSTrust -DirectoryId d-123456abcd
```
**出力:**  

```
CreatedDateTime          : 7/5/2019 4:55:42 AM
DirectoryId              : d-123456abcd
LastUpdatedDateTime      : 7/5/2019 4:56:04 AM
RemoteDomainName         : contoso.com
SelectiveAuth            : Disabled
StateLastUpdatedDateTime : 7/5/2019 4:56:04 AM
TrustDirection           : One-Way: Incoming
TrustId                  : t-9067157123
TrustState               : Created
TrustStateReason         :
TrustType                : Forest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTrusts](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSAlias`
<a name="directory-service_CreateAlias_powershell_4_topic"></a>

次のコード例は、`New-DSAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリのエイリアスを作成し、指定 directory-id にエイリアスを割り当てます。**  

```
New-DSAlias -DirectoryId d-123456ijkl -Alias MyOrgName
```
**出力:**  

```
Alias     DirectoryId
-----     -----------
myorgname d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAlias](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSComputer`
<a name="directory-service_CreateComputer_powershell_4_topic"></a>

次のコード例は、`New-DSComputer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しい Active Directory コンピュータオブジェクトを作成します。**  

```
New-DSComputer -DirectoryId d-123456ijkl -ComputerName ADMemberServer -Password $Password
```
**出力:**  

```
ComputerAttributes                  ComputerId                                    ComputerName
------------------                  ----------                                    ------------
{WindowsSamName, DistinguishedName} S-1-5-21-1191241402-978882507-2717148213-1662 ADMemberServer
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateComputer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSConditionalForwarder`
<a name="directory-service_CreateConditionalForwarder_powershell_4_topic"></a>

次のコード例は、`New-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AWS Directory-id に条件付きフォワーダーを作成します。 **  

```
New-DSConditionalForwarder -DirectoryId d-123456ijkl -DnsIpAddr 172.31.36.96,172.31.10.56 -RemoteDomainName contoso.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateConditionalForwarder](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSDirectory`
<a name="directory-service_CreateDirectory_powershell_4_topic"></a>

次のコード例は、`New-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しい Simple AD ディレクトリを作成します。**  

```
New-DSDirectory -Name corp.example.com -Password $Password -Size Small -VpcSettings_VpcId vpc-123459d -VpcSettings_SubnetIds subnet-1234kkaa,subnet-5678ffbb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSLogSubscription`
<a name="directory-service_CreateLogSubscription_powershell_4_topic"></a>

次のコード例は、`New-DSLogSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウントの指定 Amazon CloudWatch ロググループに Directory Service ドメインコントローラーセキュリティログをリアルタイムに転送するためのサブスクリプションを作成します。**  

```
New-DSLogSubscription -DirectoryId d-123456ijkl -LogGroupName /aws/directoryservice/d-123456ijkl-lan2.example.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLogSubscription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSMicrosoftAD`
<a name="directory-service_CreateMicrosoftAD_powershell_4_topic"></a>

次のコード例は、`New-DSMicrosoftAD` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 に新しい Microsoft AD Directory を作成します AWS クラウド。**  

```
New-DSMicrosoftAD -Name corp.example.com -Password $Password -edition Standard -VpcSettings_VpcId vpc-123459d -VpcSettings_SubnetIds subnet-1234kkaa,subnet-5678ffbb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateMicrosoftAD](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSSnapshot`
<a name="directory-service_CreateSnapshot_powershell_4_topic"></a>

次のコード例は、`New-DSSnapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリスナップショットを作成します。**  

```
New-DSSnapshot -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DSTrust`
<a name="directory-service_CreateTrust_powershell_4_topic"></a>

次のコード例は、`New-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS Managed Microsoft AD ディレクトリと既存のオンプレミス Microsoft Active Directory の間に双方向のフォレスト全体の信頼を作成します。**  

```
New-DSTrust -DirectoryId d-123456ijkl -RemoteDomainName contoso.com -TrustDirection Two-Way -TrustType Forest -TrustPassword $Password -ConditionalForwarderIpAddr 172.31.36.96
```
**出力:**  

```
t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTrust](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-DSCertificate`
<a name="directory-service_RegisterCertificate_powershell_4_topic"></a>

次のコード例は、`Register-DSCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、セキュリティで保護された LDAP 接続の証明書を登録します。**  

```
$Certificate = Get-Content contoso.cer -Raw
Register-DSCertificate -DirectoryId d-123456ijkl -CertificateData $Certificate
```
**出力:**  

```
c-906731e350
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-DSEventTopic`
<a name="directory-service_RegisterEventTopic_powershell_4_topic"></a>

次のコード例は、`Register-DSEventTopic` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ディレクトリをパブリッシャーとして SNS トピックに関連付けます。**  

```
Register-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterEventTopic](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DSConditionalForwarder`
<a name="directory-service_DeleteConditionalForwarder_powershell_4_topic"></a>

次のコード例は、`Remove-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS Direcotry 用に設定された条件付きフォワーダーを削除します。**  

```
Remove-DSConditionalForwarder -DirectoryId d-123456ijkl -RemoteDomainName contoso.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteConditionalForwarder](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DSDirectory`
<a name="directory-service_DeleteDirectory_powershell_4_topic"></a>

次のコード例は、`Remove-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS ディレクトリサービスディレクトリ (Simple AD/Microsoft AD/AD Connector) を削除します。**  

```
Remove-DSDirectory -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DSIpRoute`
<a name="directory-service_RemoveIpRoutes_powershell_4_topic"></a>

次のコード例は、`Remove-DSIpRoute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 IP を Directory-id の設定済み IP ルートから削除します。 **  

```
Remove-DSIpRoute -DirectoryId d-123456ijkl -CidrIp 203.0.113.5/32
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveIpRoutes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DSLogSubscription`
<a name="directory-service_DeleteLogSubscription_powershell_4_topic"></a>

次のコード例は、`Remove-DSLogSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 Directory-id のログサブスクリプションを削除します**  

```
Remove-DSLogSubscription -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLogSubscription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DSResourceTag`
<a name="directory-service_RemoveTagsFromResource_powershell_4_topic"></a>

次のコード例は、`Remove-DSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 Directory-id に割り当てられたリソースタグを削除します**  

```
Remove-DSResourceTag -ResourceId d-123456ijkl -TagKey myTag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DSSnapshot`
<a name="directory-service_DeleteSnapshot_powershell_4_topic"></a>

次のコード例は、`Remove-DSSnapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、手動で作成されたスナップショットを削除します。**  

```
Remove-DSSnapshot -SnapshotId s-9068b488kc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の[DeleteSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DSTrust`
<a name="directory-service_DeleteTrust_powershell_4_topic"></a>

次のコード例は、`Remove-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS Managed AD Directory と外部ドメイン間の既存の信頼関係ヒントを削除します。**  

```
Get-DSTrust -DirectoryId d-123456ijkl -Select Trusts.TrustId | Remove-DSTrust
```
**出力:**  

```
t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTrust](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Reset-DSUserPassword`
<a name="directory-service_ResetUserPassword_powershell_4_topic"></a>

次のコード例は、`Reset-DSUserPassword` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS Managed microsoft AD または Simple AD Directory で ADUser という名前の Active Direcotry ユーザーのパスワードをリセットします。**  

```
Reset-DSUserPassword -UserName ADuser -DirectoryId d-123456ijkl -NewPassword $Password
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResetUserPassword](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Restore-DSFromSnapshot`
<a name="directory-service_RestoreFromSnapshot_powershell_4_topic"></a>

次のコード例は、`Restore-DSFromSnapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、既存のディレクトリスナップショットを使用してディレクトリを復元します。**  

```
Restore-DSFromSnapshot -SnapshotId s-9068b488kc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RestoreFromSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-DSDomainControllerCount`
<a name="directory-service_UpdateNumberOfDomainControllers_powershell_4_topic"></a>

次のコード例は、`Set-DSDomainControllerCount` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 directory-id のドメインコントローラーの数を 3 に設定します。**  

```
Set-DSDomainControllerCount -DirectoryId d-123456ijkl -DesiredNumber 3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateNumberOfDomainControllers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-DSSchemaExtension`
<a name="directory-service_StartSchemaExtension_powershell_4_topic"></a>

次のコード例は、`Start-DSSchemaExtension` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Microsoft AD ディレクトリにスキーマ拡張を適用します。**  

```
$ldif = Get-Content D:\Users\Username\Downloads\ExtendedSchema.ldf -Raw
Start-DSSchemaExtension -DirectoryId d-123456ijkl -CreateSnapshotBeforeSchemaExtension $true -Description ManagedADSchemaExtension -LdifContent $ldif
```
**出力:**  

```
e-9067306643
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartSchemaExtension](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-DSSchemaExtension`
<a name="directory-service_CancelSchemaExtension_powershell_4_topic"></a>

次のコード例は、`Stop-DSSchemaExtension` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Microsoft AD ディレクトリへの進行中のスキーマ拡張をキャンセルします。**  

```
Stop-DSSchemaExtension -DirectoryId d-123456ijkl -SchemaExtensionId e-9067306643
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CancelSchemaExtension](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-DSCertificate`
<a name="directory-service_DeregisterCertificate_powershell_4_topic"></a>

次のコード例は、`Unregister-DSCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、セキュリティで保護された LDAP 接続用に登録された証明書をシステムから削除します。**  

```
Unregister-DSCertificate -DirectoryId d-123456ijkl -CertificateId c-906731e34f
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-DSEventTopic`
<a name="directory-service_DeregisterEventTopic_powershell_4_topic"></a>

次のコード例は、`Unregister-DSEventTopic` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された SNS トピックへの発行者として指定されたディレクトリを削除します。**  

```
Unregister-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterEventTopic](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-DSConditionalForwarder`
<a name="directory-service_UpdateConditionalForwarder_powershell_4_topic"></a>

次のコード例は、`Update-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS ディレクトリ用に設定された条件付きフォワーダーを更新します。**  

```
Update-DSConditionalForwarder -DirectoryId d-123456ijkl -DnsIpAddr 172.31.36.96,172.31.16.108 -RemoteDomainName contoso.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateConditionalForwarder](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-DSRadius`
<a name="directory-service_UpdateRadius_powershell_4_topic"></a>

次のコード例は、`Update-DSRadius` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、AD Connector または Microsoft AD ディレクトリの RADIUS サーバー情報を更新します。**  

```
Update-DSRadius -DirectoryId d-123456ijkl -RadiusSettings_RadiusRetry 3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateRadius](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-DSTrust`
<a name="directory-service_UpdateTrust_powershell_4_topic"></a>

次のコード例は、`Update-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 trust-id の SelectiveAuth パラメータを Disabled から Enabled に更新します。**  

```
Update-DSTrust -TrustId t-9067157123 -SelectiveAuth Enabled
```
**出力:**  

```
RequestId                            TrustId
---------                            -------
138864a7-c9a8-4ad1-a828-eae479e85b45 t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateTrust](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS DMS Tools for PowerShell V4 を使用した の例
<a name="powershell_4_database-migration-service_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS DMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-DMSReplicationTask`
<a name="database-migration-service_CreateReplicationTask_powershell_4_topic"></a>

次のコード例は、`New-DMSReplicationTask` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、CdcStartPosition の代わりに CdcStartTime を使用する新しい AWS Database Migration Service レプリケーションタスクを作成します。 CdcStartPosition MigrationType は「full-load-and-cdc」に設定されます。つまり、ターゲットテーブルは空である必要があります。新しいタスクには、Stage のキーと Test のキー値を持つタグが付けられます。このコマンドレットで使用される値の詳細については、 AWS 「 Database Migration Service ユーザーガイド」の「タスクの作成 (https://docs.aws.amazon.com/dms/latest/userguide/CHAP\$1Tasks.Creating.html)」を参照してください。**  

```
New-DMSReplicationTask -ReplicationInstanceArn "arn:aws:dms:us-east-1:123456789012:rep:EXAMPLE66XFJUWATDJGBEXAMPLE"`
  -CdcStartTime "2019-08-08T12:12:12"`
  -CdcStopPosition "server_time:2019-08-09T12:12:12"`
  -MigrationType "full-load-and-cdc"`
  -ReplicationTaskIdentifier "task1"`
  -ReplicationTaskSetting ""`
  -SourceEndpointArn "arn:aws:dms:us-east-1:123456789012:endpoint:EXAMPLEW5UANC7Y3P4EEXAMPLE"`
  -TableMapping "file:////home/testuser/table-mappings.json"`
  -Tag @{"Key"="Stage";"Value"="Test"}`
  -TargetEndpointArn "arn:aws:dms:us-east-1:123456789012:endpoint:EXAMPLEJZASXWHTWCLNEXAMPLE"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateReplicationTask](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した DynamoDB の例
<a name="powershell_4_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-DDBIndexSchema`
<a name="dynamodb_Add-DDBIndexSchema_powershell_4_topic"></a>

次のコード例は、`Add-DDBIndexSchema` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: TableSchema オブジェクトをパイプラインに書き込む前に、空の TableSchema オブジェクトを作成し、新しいローカルセカンダリインデックス定義を追加します。**  

```
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema = New-DDBTableSchema
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{LastPostDateTime}                          {}                                          {LastPostIndex}
```
**例 2: TableSchema オブジェクトをパイプラインに書き戻す前に、指定 TableSchema オブジェクトに新しいローカルセカンダリインデックス定義を追加します。TableSchema オブジェクトは、-Schema パラメータを使用して指定することもできます。**  

```
New-DDBTableSchema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{LastPostDateTime}                          {}                                          {LastPostIndex}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Add-DDBIndexSchema](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-DDBKeySchema`
<a name="dynamodb_Add-DDBKeySchema_powershell_4_topic"></a>

次のコード例は、`Add-DDBKeySchema` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: TableSchema オブジェクトをパイプラインに書き込む前に、空の TableSchema オブジェクトを作成し、指定キーデータを使用してキーと属性定義のエントリを追加します。キータイプはデフォルトで「HASH」と宣言されます。範囲キーを宣言するには、値「RANGE」を持つ -KeyType パラメータを使用します。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
**例 2: TableSchema オブジェクトをパイプラインに書き込む前に、指定 TableSchema オブジェクトに新しいキーと属性定義のエントリを追加します。キータイプはデフォルトで「HASH」と宣言されます。範囲キーを宣言するには、値「RANGE」を持つ -KeyType パラメータを使用します。TableSchema オブジェクトは、-Schema パラメータを使用して指定することもできます。**  

```
New-DDBTableSchema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Add-DDBKeySchema](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `ConvertFrom-DDBItem`
<a name="dynamodb_ConvertFrom-DDBItem_powershell_4_topic"></a>

次のコード例は、`ConvertFrom-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ConvertFrom-DDBItem を使用して、Get-DDBItem の結果を DynamoDB AttributeValues のハッシュテーブルから string や double などの一般的なタイプのハッシュテーブルに変換します。**  

```
@{
    SongTitle = 'Somewhere Down The Road'
    Artist    = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ConvertFrom-DDBItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `ConvertTo-DDBItem`
<a name="dynamodb_ConvertTo-DDBItem_powershell_4_topic"></a>

次のコード例は、`ConvertTo-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ハッシュテーブルを DynamoDB 属性値のディクショナリに変換する例。**  

```
@{
    SongTitle = 'Somewhere Down The Road'
    Artist    = 'No One You Know'
} | ConvertTo-DDBItem

Key       Value
---       -----
SongTitle Amazon.DynamoDBv2.Model.AttributeValue
Artist    Amazon.DynamoDBv2.Model.AttributeValue
```
**例 2: ハッシュテーブルを DynamoDB 属性値のディクショナリに変換する例。**  

```
@{
    MyMap        = @{
        MyString = 'my string'
    }
    MyStringSet  = [System.Collections.Generic.HashSet[String]]@('my', 'string')
    MyNumericSet = [System.Collections.Generic.HashSet[Int]]@(1, 2, 3)
    MyBinarySet  = [System.Collections.Generic.HashSet[System.IO.MemoryStream]]@(
        ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes('my'))),
        ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes('string')))
    )
    MyList1      = @('my', 'string')
    MyList2      = [System.Collections.Generic.List[Int]]@(1, 2)
    MyList3      = [System.Collections.ArrayList]@('one', 2, $true)
} | ConvertTo-DDBItem
```
**出力:**  

```
Key          Value
---          -----
MyStringSet  Amazon.DynamoDBv2.Model.AttributeValue
MyList1      Amazon.DynamoDBv2.Model.AttributeValue
MyNumericSet Amazon.DynamoDBv2.Model.AttributeValue
MyList2      Amazon.DynamoDBv2.Model.AttributeValue
MyBinarySet  Amazon.DynamoDBv2.Model.AttributeValue
MyMap        Amazon.DynamoDBv2.Model.AttributeValue
MyList3      Amazon.DynamoDBv2.Model.AttributeValue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ConvertTo-DDBItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DDBBatchItem`
<a name="dynamodb_BatchGetItem_powershell_4_topic"></a>

次のコード例は、`Get-DDBBatchItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: DynamoDB テーブルの「Music」と「Songs」から「Somewhere Down The Road」という SongTitle の項目を取得します。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem

$keysAndAttributes = New-Object Amazon.DynamoDBv2.Model.KeysAndAttributes
$list = New-Object 'System.Collections.Generic.List[System.Collections.Generic.Dictionary[String, Amazon.DynamoDBv2.Model.AttributeValue]]'
$list.Add($key)
$keysAndAttributes.Keys = $list

$requestItem = @{
    'Music' = [Amazon.DynamoDBv2.Model.KeysAndAttributes]$keysAndAttributes
    'Songs' = [Amazon.DynamoDBv2.Model.KeysAndAttributes]$keysAndAttributes
}

$batchItems = Get-DDBBatchItem -RequestItem $requestItem
$batchItems.GetEnumerator() | ForEach-Object {$PSItem.Value} | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Artist                         No One You Know
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
CriticRating                   10
Genre                          Country
Price                          1.94
Artist                         No One You Know
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
CriticRating                   10
Genre                          Country
Price                          1.94
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[BatchGetItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DDBItem`
<a name="dynamodb_GetItem_powershell_4_topic"></a>

次のコード例は、`Get-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: パーティションキー SongTitle とソートキー Artist を含む DynamoDB 項目を返します。**  

```
$key = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DDBTable`
<a name="dynamodb_DescribeTable_powershell_4_topic"></a>

次のコード例は、`Get-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定テーブルの詳細を返します。**  

```
Get-DDBTable -TableName "myTable"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-DDBTableList`
<a name="dynamodb_ListTables_powershell_4_topic"></a>

次のコード例は、`Get-DDBTableList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべてのテーブルの詳細を返し、サービスが他にテーブルがないことを知らせるまで自動で繰り返します。**  

```
Get-DDBTableList
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTables](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Invoke-DDBQuery`
<a name="dynamodb_Query_powershell_4_topic"></a>

次のコード例は、`Invoke-DDBQuery` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定の SongTitle と Artist を含む DynamoDB 項目を返すクエリを呼び出します。**  

```
$invokeDDBQuery = @{
    TableName = 'Music'
    KeyConditionExpression = ' SongTitle = :SongTitle and Artist = :Artist'
    ExpressionAttributeValues = @{
        ':SongTitle' = 'Somewhere Down The Road'
        ':Artist' = 'No One You Know'
    } | ConvertTo-DDBItem
}
Invoke-DDBQuery @invokeDDBQuery | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Query](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Invoke-DDBScan`
<a name="dynamodb_Scan_powershell_4_topic"></a>

次のコード例は、`Invoke-DDBScan` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: Music テーブルのすべての項目を返します。**  

```
Invoke-DDBScan -TableName 'Music' | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
Genre                          Country
Artist                         No One You Know
Price                          1.98
CriticRating                   8.4
SongTitle                      My Dog Spot
AlbumTitle                     Hey Now
```
**例 2: Music テーブル内の CriticRating が 9 以上の項目を返します。**  

```
$scanFilter = @{
        CriticRating = [Amazon.DynamoDBv2.Model.Condition]@{
            AttributeValueList = @(@{N = '9'})
            ComparisonOperator = 'GE'
        }
    }
    Invoke-DDBScan -TableName 'Music' -ScanFilter $scanFilter | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Scan](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DDBTable`
<a name="dynamodb_CreateTable_powershell_4_topic"></a>

次のコード例は、`New-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ「Thread」という名前のテーブルを作成します。テーブルの作成に使用したスキーマは、図のように各 cmdlet にパイプ処理するか、-Schema パラメータを使用して指定できます。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyType RANGE -KeyDataType "S"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**出力:**  

```
AttributeDefinitions   : {ForumName, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {}
```
**例 2: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ Thread という名前のテーブルを作成します。ローカルセカンダリインデックスも定義されます。ローカルセカンダリインデックスのキーは、テーブルのプライマリハッシュキー (ForumName) から自動的に設定されます。テーブルの作成に使用したスキーマは、図のように各 cmdlet にパイプ処理するか、-Schema パラメータを使用して指定できます。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S"
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**出力:**  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
**例 3: この例では、単一のパイプラインを使用して、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキー、およびローカルセカンダリインデックスを持つ「Thread」という名前のテーブルを作成する方法を示します。TableSchema がパイプラインまたは -Schema パラメータから提供されない場合、Add-DDBKeySchema と Add-DDBIndexSchema によって新しい TableSchema オブジェクトが作成されます。**  

```
New-DDBTableSchema |
  Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S" |
  Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S" |
  Add-DDBIndexSchema -IndexName "LastPostIndex" `
                     -RangeKeyName "LastPostDateTime" `
                     -RangeKeyDataType "S" `
                     -ProjectionType "keys_only" |
  New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**出力:**  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-DDBTableSchema`
<a name="dynamodb_New-DDBTableSchema_powershell_4_topic"></a>

次のコード例は、`New-DDBTableSchema` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 新しい Amazon DynamoDB テーブルの作成に使用するキーとインデックスの定義を受け入れる準備が整った空の TableSchema オブジェクトを作成します。返されたオブジェクトは、Add-DDBKeySchema、Add-DDBIndexSchema、New-DDBTable コマンドレットにパイプするか、各コマンドレットの -Schema パラメータを使用して渡すことができます。**  

```
New-DDBTableSchema
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{}                                          {}                                          {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[New-DDBTableSchema](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DDBItem`
<a name="dynamodb_DeleteItem_powershell_4_topic"></a>

次のコード例は、`Remove-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたキーと一致する DynamoDB 項目を削除します。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem
Remove-DDBItem -TableName 'Music' -Key $key -Confirm:$false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-DDBTable`
<a name="dynamodb_DeleteTable_powershell_4_topic"></a>

次のコード例は、`Remove-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたテーブルを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-DDBTable -TableName "myTable"
```
**例 2: 指定されたテーブルを削除します。操作を続行する前に確認画面は表示されません。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-DDBBatchItem`
<a name="dynamodb_BatchWriteItem_powershell_4_topic"></a>

次のコード例は、`Set-DDBBatchItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 新しい項目を作成する、または既存の項目を「Music 」DynamoDB テーブルおよび「Songs」DynamoDB テーブルの新しい項目で置き換えます。**  

```
$item = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
    AlbumTitle = 'Somewhat Famous'
    Price = 1.94
    Genre = 'Country'
    CriticRating = 10.0
} | ConvertTo-DDBItem

$writeRequest = New-Object Amazon.DynamoDBv2.Model.WriteRequest
$writeRequest.PutRequest = [Amazon.DynamoDBv2.Model.PutRequest]$item

$requestItem = @{
    'Music' = [Amazon.DynamoDBv2.Model.WriteRequest]($writeRequest)
    'Songs' = [Amazon.DynamoDBv2.Model.WriteRequest]($writeRequest)
}

Set-DDBBatchItem -RequestItem $requestItem
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[BatchWriteItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Set-DDBItem`
<a name="dynamodb_PutItem_powershell_4_topic"></a>

次のコード例は、`Set-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 新しい項目を作成する、または既存の項目を新しい項目で置き換えます。**  

```
$item = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
        AlbumTitle = 'Somewhat Famous'
        Price = 1.94
        Genre = 'Country'
        CriticRating = 9.0
} | ConvertTo-DDBItem
Set-DDBItem -TableName 'Music' -Item $item
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-DDBItem`
<a name="dynamodb_UpdateItem_powershell_4_topic"></a>

次のコード例は、`Update-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: パーティションキー SongTitle とソートキー Artist を含む DynamoDB 項目のジャンル属性を「Rap」に設定します。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem

$updateDdbItem = @{
    TableName = 'Music'
    Key = $key
    UpdateExpression = 'set Genre = :val1'
    ExpressionAttributeValue = (@{
        ':val1' = ([Amazon.DynamoDBv2.Model.AttributeValue]'Rap')
    })
}
Update-DDBItem @updateDdbItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateItem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-DDBTable`
<a name="dynamodb_UpdateTable_powershell_4_topic"></a>

次のコード例は、`Update-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたテーブルのプロビジョンされたスループットを更新します。**  

```
Update-DDBTable -TableName "myTable" -ReadCapacity 10 -WriteCapacity 5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon EC2 の例
<a name="powershell_4_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-EC2CapacityReservation`
<a name="ec2_CreateCapacityReservation_powershell_4_topic"></a>

次のコード例は、`Add-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された属性で新しいキャパシティ予約を作成します。**  

```
Add-EC2CapacityReservation -InstanceType m4.xlarge -InstanceCount 2 -AvailabilityZone eu-west-1b -EbsOptimized True -InstancePlatform Windows
```
**出力:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateCapacityReservation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-EC2InternetGateway`
<a name="ec2_AttachInternetGateway_powershell_4_topic"></a>

次のコード例は、`Add-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインターネットゲートウェイを特定の VPC にアタッチします。**  

```
Add-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
**例 2: この例では、VPC とインターネットゲートウェイを作成し、インターネットゲートウェイを VPC にアタッチします。**  

```
$vpc = New-EC2Vpc -CidrBlock 10.0.0.0/16
New-EC2InternetGateway | Add-EC2InternetGateway -VpcId $vpc.VpcId
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[AttachInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Add-EC2NetworkInterface`
<a name="ec2_AttachNetworkInterface_powershell_4_topic"></a>

次のコード例は、`Add-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したネットワークインターフェイスを指定したインスタンスにアタッチします。**  

```
Add-EC2NetworkInterface -NetworkInterfaceId eni-12345678 -InstanceId i-1a2b3c4d -DeviceIndex 1
```
**出力:**  

```
eni-attach-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-EC2Volume`
<a name="ec2_AttachVolume_powershell_4_topic"></a>

次のコード例は、`Add-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたボリュームを指定されたインスタンスにアタッチし、指定されたデバイス名で公開します。**  

```
Add-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
**出力:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : attaching
VolumeId            : vol-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)*の「[AttachVolume](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-EC2VpnGateway`
<a name="ec2_AttachVpnGateway_powershell_4_topic"></a>

次のコード例は、`Add-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した仮想プライベートゲートウェイを指定した VPC にアタッチします。**  

```
Add-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
**出力:**  

```
State        VpcId
-----        -----
attaching    vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Approve-EC2VpcPeeringConnection`
<a name="ec2_AcceptVpcPeeringConnection_powershell_4_topic"></a>

次のコード例は、`Approve-EC2VpcPeeringConnection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リクエストされた VpcPeeringConnectionId pcx-1dfad234b56ff78be を承認します。**  

```
Approve-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-1dfad234b56ff78be
```
**出力:**  

```
AccepterVpcInfo        : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
ExpirationTime         : 1/1/0001 12:00:00 AM
RequesterVpcInfo       : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
Status                 : Amazon.EC2.Model.VpcPeeringConnectionStateReason
Tags                   : {}
VpcPeeringConnectionId : pcx-1dfad234b56ff78be
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AcceptVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Confirm-EC2ProductInstance`
<a name="ec2_ConfirmProductInstance_powershell_4_topic"></a>

次のコード例は、`Confirm-EC2ProductInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された製品コードが指定されたインスタンスに関連付けられているかどうかを判断します。**  

```
Confirm-EC2ProductInstance -ProductCode 774F4FF8 -InstanceId i-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ConfirmProductInstance](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Copy-EC2Image`
<a name="ec2_CopyImage_powershell_4_topic"></a>

次のコード例は、`Copy-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「欧州 (アイルランド)」リージョンの指定 AMI を「米国西部 (オレゴン)」リージョンにコピーします。-Region が指定されていない場合、現在のデフォルトリージョンが送信先リージョンとして使用されます。**  

```
Copy-EC2Image -SourceRegion eu-west-1 -SourceImageId ami-12345678 -Region us-west-2 -Name "Copy of ami-12345678"
```
**出力:**  

```
ami-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CopyImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Copy-EC2Snapshot`
<a name="ec2_CopySnapshot_powershell_4_topic"></a>

次のコード例は、`Copy-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスナップショットを欧州 (アイルランド) リージョンから米国西部 (オレゴン) リージョンにコピーします。**  

```
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678 -Region us-west-2
```
**例 2: デフォルトのリージョンを設定し、Region パラメータを省略すると、デフォルトの送信先リージョンがデフォルトのリージョンになります。**  

```
Set-DefaultAWSRegion us-west-2
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CopySnapshot](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Deny-EC2VpcPeeringConnection`
<a name="ec2_RejectVpcPeeringConnection_powershell_4_topic"></a>

次のコード例は、`Deny-EC2VpcPeeringConnection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 上記の例では、VpcPeering リクエスト ID pcx-01a2b3ce45fe67eb8 のリクエストを拒否します。**  

```
Deny-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-01a2b3ce45fe67eb8
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RejectVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-EC2VgwRoutePropagation`
<a name="ec2_DisableVgwRoutePropagation_powershell_4_topic"></a>

次のコード例は、`Disable-EC2VgwRoutePropagation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、VGW が指定されたルーティングテーブルにルートを自動的に伝播することを無効にします。**  

```
Disable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-EC2VpcClassicLink`
<a name="ec2_DisableVpcClassicLink_powershell_4_topic"></a>

次のコード例は、`Disable-EC2VpcClassicLink` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、vpc-01e23c4a5d6db78e9 の EC2VpcClassicLink を無効にします。True または False を返します。**  

```
Disable-EC2VpcClassicLink -VpcId vpc-01e23c4a5d6db78e9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableVpcClassicLink](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DisableVpcClassicLinkDnsSupport_powershell_4_topic"></a>

次のコード例は、`Disable-EC2VpcClassicLinkDnsSupport` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、vpc-0b12d3456a7e8910d の ClassicLink DNS サポートを無効にします。**  

```
Disable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Dismount-EC2InternetGateway`
<a name="ec2_DetachInternetGateway_powershell_4_topic"></a>

次のコード例は、`Dismount-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPC から指定されたインターネットゲートウェイをデタッチします。**  

```
Dismount-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Dismount-EC2NetworkInterface`
<a name="ec2_DetachNetworkInterface_powershell_4_topic"></a>

次のコード例は、`Dismount-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ネットワークインターフェイスとインスタンス間の指定されたアタッチメントを削除します。**  

```
Dismount-EC2NetworkInterface -AttachmentId eni-attach-1a2b3c4d -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Dismount-EC2Volume`
<a name="ec2_DetachVolume_powershell_4_topic"></a>

次のコード例は、`Dismount-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたボリュームをデタッチします。**  

```
Dismount-EC2Volume -VolumeId vol-12345678
```
**出力:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : detaching
VolumeId            : vol-12345678
```
**例 2: インスタンス ID とデバイス名を指定して、正しいボリュームをデタッチするようにすることもできます。**  

```
Dismount-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachVolume](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Dismount-EC2VpnGateway`
<a name="ec2_DetachVpnGateway_powershell_4_topic"></a>

次のコード例は、`Dismount-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPC から指定された仮想プライベートゲートウェイをデタッチします。**  

```
Dismount-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2CapacityReservation`
<a name="ec2_ModifyCapacityReservation_powershell_4_topic"></a>

次のコード例は、`Edit-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンス数を 1 に変更して CapacityReservationId cr-0c1f2345db6f7cdba を変更します。**  

```
Edit-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba -InstanceCount 1
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyCapacityReservation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2Host`
<a name="ec2_ModifyHosts_powershell_4_topic"></a>

次のコード例は、`Edit-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、専有ホスト h-01e23f4cd567890f3 の 自動配置設定をオフに変更します。**  

```
Edit-EC2Host -HostId h-03e09f8cd681609f3 -AutoPlacement off
```
**出力:**  

```
Successful            Unsuccessful
----------            ------------
{h-01e23f4cd567890f3} {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyHosts](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2IdFormat`
<a name="ec2_ModifyIdFormat_powershell_4_topic"></a>

次のコード例は、`Edit-EC2IdFormat` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリソースタイプの長い ID 形式を有効にします。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $true
```
**例 2: この例では、指定されたリソースタイプの長い ID 形式を無効にします。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyIdFormat](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2ImageAttribute`
<a name="ec2_ModifyImageAttribute_powershell_4_topic"></a>

次のコード例は、`Edit-EC2ImageAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AMI の説明を更新します。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Description "New description"
```
**例 2: この例では、AMI を公開します (たとえば、誰でも使用 AWS アカウント できるようにします）。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserGroup all
```
**例 3: この例では、AMI を非公開にします (例えば、所有者である自分だけが使用できるようにします)。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserGroup all
```
**例 4: この例では、指定された に起動アクセス許可を付与します AWS アカウント。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserId 111122223333
```
**例 5: この例では、指定された から起動アクセス許可を削除します AWS アカウント。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserId 111122223333
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyImageAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2InstanceAttribute`
<a name="ec2_ModifyInstanceAttribute_powershell_4_topic"></a>

次のコード例は、`Edit-EC2InstanceAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスのインスタンスタイプを変更します。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceType m3.medium
```
**例 2: この例では、単一ルート I/O 仮想化 (SR-IOV) ネットワークサポートパラメータ -SriovNetSupport の値に「simple」を指定して、指定されたインスタンスの拡張ネットワーキングを有効にします。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SriovNetSupport "simple"
```
**例 3: この例では、指定されたインスタンスのセキュリティグループを変更します。インスタンスは VPC にある必要があります。名前ではなく、各セキュリティグループの ID を指定する必要があります。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -Group @( "sg-12345678", "sg-45678901" )
```
**例 4: この例では、指定されたインスタンスの EBS I/O 最適化を有効にします。この機能は、すべてのインスタンスタイプで使用できるわけではありません。EBS 最適化インスタンスを使用する場合は、追加料金が適用されます。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -EbsOptimized $true
```
**例 5: この例では、指定されたインスタンスの送信元/送信先チェックを有効にします。NAT インスタンスが NAT を実行するには、値が「false」である必要があります。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SourceDestCheck $true
```
**例 6: この例では、指定されたインスタンスの終了を無効にします。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -DisableApiTermination $true
```
**例 7: この例では、インスタンスからシャットダウンを開始したときに終了するように、指定されたインスタンスを変更します。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceInitiatedShutdownBehavior terminate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyInstanceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2InstanceCreditSpecification`
<a name="ec2_ModifyInstanceCreditSpecification_powershell_4_topic"></a>

次のコード例は、`Edit-EC2InstanceCreditSpecification` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: これにより、インスタンス i-01234567890abcdef の T2 無制限クレジットが有効になります。**  

```
$Credit = New-Object -TypeName Amazon.EC2.Model.InstanceCreditSpecificationRequest
$Credit.InstanceId = "i-01234567890abcdef"
$Credit.CpuCredits = "unlimited"
Edit-EC2InstanceCreditSpecification -InstanceCreditSpecification $Credit
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2NetworkInterfaceAttribute`
<a name="ec2_ModifyNetworkInterfaceAttribute_powershell_4_topic"></a>

次のコード例は、`Edit-EC2NetworkInterfaceAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された添付ファイルが終了時に削除されるように、指定されたネットワークインターフェイスを変更します。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Attachment_AttachmentId eni-attach-1a2b3c4d -Attachment_DeleteOnTermination $true
```
**例 2: この例では、指定されたネットワークインターフェイスの説明を変更します。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Description "my description"
```
**例 3: この例では、指定されたネットワークインターフェイスのセキュリティグループを変更します。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Groups sg-1a2b3c4d
```
**例 4: この例では、指定されたネットワークインターフェイスの送信元/送信先チェックを無効にします。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2ReservedInstance`
<a name="ec2_ModifyReservedInstances_powershell_4_topic"></a>

次のコード例は、`Edit-EC2ReservedInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリザーブドインスタンスのアベイラビリティーゾーン、インスタンス数、プラットフォームを変更します。**  

```
$config = New-Object Amazon.EC2.Model.ReservedInstancesConfiguration
$config.AvailabilityZone = "us-west-2a"
$config.InstanceCount = 1
$config.Platform = "EC2-VPC"

Edit-EC2ReservedInstance `
-ReservedInstancesId @("FE32132D-70D5-4795-B400-AE435EXAMPLE", "0CC556F3-7AB8-4C00-B0E5-98666EXAMPLE") `
-TargetConfiguration $config
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyReservedInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2SnapshotAttribute`
<a name="ec2_ModifySnapshotAttribute_powershell_4_topic"></a>

次のコード例は、`Edit-EC2SnapshotAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、CreateVolumePermission 属性を設定して、指定されたスナップショットを公開します。**  

```
Edit-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission -OperationType Add -GroupName all
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifySnapshotAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2SpotFleetRequest`
<a name="ec2_ModifySpotFleetRequest_powershell_4_topic"></a>

次のコード例は、`Edit-EC2SpotFleetRequest` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンド例では、指定されたスポットフリートリクエストのターゲット容量を更新します。**  

```
Edit-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TargetCapacity 10
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifySpotFleetRequest](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2SubnetAttribute`
<a name="ec2_ModifySubnetAttribute_powershell_4_topic"></a>

次のコード例は、`Edit-EC2SubnetAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたサブネットのパブリック IP アドレス指定を有効にします。**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $true
```
**例 2: この例では、指定されたサブネットのパブリック IP アドレス指定を無効にします。**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifySubnetAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2VolumeAttribute`
<a name="ec2_ModifyVolumeAttribute_powershell_4_topic"></a>

次のコード例は、`Edit-EC2VolumeAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたボリュームの指定された属性を変更します。ボリュームの I/O オペレーションは、データの不整合の可能性が原因で中断された後に自動的に再開されます。**  

```
Edit-EC2VolumeAttribute -VolumeId vol-12345678 -AutoEnableIO $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyVolumeAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-EC2VpcAttribute`
<a name="ec2_ModifyVpcAttribute_powershell_4_topic"></a>

次のコード例は、`Edit-EC2VpcAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPC の DNS ホスト名のサポートを有効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $true
```
**例 2: この例では、指定された VPC の DNS ホスト名のサポートを無効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $false
```
**例 3: この例では、指定された VPC の DNS 解決のサポートを有効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $true
```
**例 4: この例では、指定された VPC の DNS 解決のサポートを無効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyVpcAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-EC2VgwRoutePropagation`
<a name="ec2_EnableVgwRoutePropagation_powershell_4_topic"></a>

次のコード例は、`Enable-EC2VgwRoutePropagation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VGW が指定されたルーティングテーブルに自動的にルートを伝播できるようにします。**  

```
Enable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-EC2VolumeIO`
<a name="ec2_EnableVolumeIo_powershell_4_topic"></a>

次のコード例は、`Enable-EC2VolumeIO` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、I/O オペレーションが無効になっている場合に、指定されたボリュームの I/O オペレーションを有効にします。**  

```
Enable-EC2VolumeIO -VolumeId vol-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableVolumeIo](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-EC2VpcClassicLink`
<a name="ec2_EnableVpcClassicLink_powershell_4_topic"></a>

次のコード例は、`Enable-EC2VpcClassicLink` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ClassicLink の VPC vpc-0123456b789b0d12f を有効にします。**  

```
Enable-EC2VpcClassicLink -VpcId vpc-0123456b789b0d12f
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableVpcClassicLink](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_EnableVpcClassicLinkDnsSupport_powershell_4_topic"></a>

次のコード例は、`Enable-EC2VpcClassicLinkDnsSupport` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、vpc-0b12d3456a7e8910d が ClassicLink の DNS ホスト名解決をサポートできるようにします。**  

```
Enable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2AccountAttribute`
<a name="ec2_DescribeAccountAttributes_powershell_4_topic"></a>

次のコード例は、`Get-EC2AccountAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リージョンの EC2-Classic および EC2-VPC にインスタンスを起動できるか、または EC2-VPC にのみインスタンスを起動できるかを記述します。**  

```
(Get-EC2AccountAttribute -AttributeName supported-platforms).AttributeValues
```
**出力:**  

```
AttributeValue
--------------
EC2
VPC
```
**例 2: この例では、デフォルトの VPC を記述します。リージョンにデフォルトの VPC がない場合は「none」です。**  

```
(Get-EC2AccountAttribute -AttributeName default-vpc).AttributeValues
```
**出力:**  

```
AttributeValue
--------------
vpc-12345678
```
**例 3: この例では、実行できるオンデマンドインスタンスの最大数を記述します。**  

```
(Get-EC2AccountAttribute -AttributeName max-instances).AttributeValues
```
**出力:**  

```
AttributeValue
--------------
20
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAccountAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Address`
<a name="ec2_DescribeAddresses_powershell_4_topic"></a>

次のコード例は、`Get-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2-Classic のインスタンスに指定された Elastic IP アドレスを記述します。**  

```
Get-EC2Address -AllocationId eipalloc-12345678
```
**出力:**  

```
AllocationId            : eipalloc-12345678
AssociationId           : eipassoc-12345678
Domain                  : vpc
InstanceId              : i-87654321
NetworkInterfaceId      : eni-12345678
NetworkInterfaceOwnerId : 12345678
PrivateIpAddress        : 10.0.2.172
PublicIp                : 198.51.100.2
```
**例 2: この例では、VPC 内のインスタンスの Elastic IP アドレスを記述します。この構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-EC2Address -Filter @{ Name="domain";Values="vpc" }
```
**例 3: この例では、EC2-Classic のインスタンスに指定された Elastic IP アドレスを記述します。**  

```
Get-EC2Address -PublicIp 203.0.113.17
```
**出力:**  

```
AllocationId            :
AssociationId           :
Domain                  : standard
InstanceId              : i-12345678
NetworkInterfaceId      :
NetworkInterfaceOwnerId :
PrivateIpAddress        :
PublicIp                : 203.0.113.17
```
**例 4: この例では、EC2-Classic のインスタンスの Elastic IP アドレスを記述します。この構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-EC2Address -Filter @{ Name="domain";Values="standard" }
```
**例 5: この例では、すべての Elastic IP アドレスを記述します。**  

```
Get-EC2Address
```
**例 6: この例では、フィルターで指定されたインスタンス ID のパブリック IP とプライベート IP を返します。**  

```
Get-EC2Address -Region eu-west-1 -Filter @{Name="instance-id";Values="i-0c12d3f4f567ffb89"} | Select-Object PrivateIpAddress, PublicIp
```
**出力:**  

```
PrivateIpAddress PublicIp
---------------- --------
10.0.0.99        63.36.5.227
```
**例 7: この例では、割り当て ID、関連付け ID、インスタンス ID を持つすべての Elastic IP を取得します。**  

```
Get-EC2Address -Region eu-west-1 | Select-Object InstanceId, AssociationId, AllocationId, PublicIp
```
**出力:**  

```
InstanceId          AssociationId              AllocationId               PublicIp
----------          -------------              ------------               --------
                                               eipalloc-012e3b456789e1fad 17.212.120.178
i-0c123dfd3415bac67 eipassoc-0e123456bb7890bdb eipalloc-01cd23ebf45f7890c 17.212.124.77
                                               eipalloc-012345678eeabcfad 17.212.225.7
i-0123d405c67e89a0c eipassoc-0c123b456783966ba eipalloc-0123cdd456a8f7892 37.216.52.173
i-0f1bf2f34c5678d09 eipassoc-0e12934568a952d96 eipalloc-0e1c23e4d5e6789e4 37.218.222.278
i-012e3cb4df567e8aa eipassoc-0d1b2fa4d67d03810 eipalloc-0123f456f78a01b58 37.210.82.27
i-0123bcf4b567890e1 eipassoc-01d2345f678903fb1 eipalloc-0e1db23cfef5c45c7 37.215.222.270
```
**例 8: この例では、タグキー「Category」と値「Prod」に一致する EC2 IP アドレスのリストを取得します。**  

```
Get-EC2Address -Filter @{Name="tag:Category";Values="Prod"}
```
**出力:**  

```
AllocationId            : eipalloc-0123f456f81a01b58
AssociationId           : eipassoc-0d1b23a456d103810
CustomerOwnedIp         :
CustomerOwnedIpv4Pool   :
Domain                  : vpc
InstanceId              : i-012e3cb4df567e1aa
NetworkBorderGroup      : eu-west-1
NetworkInterfaceId      : eni-0123f41d5a60d5f40
NetworkInterfaceOwnerId : 123456789012
PrivateIpAddress        : 192.168.1.84
PublicIp                : 34.250.81.29
PublicIpv4Pool          : amazon
Tags                    : {Category, Name}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAddresses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2AvailabilityZone`
<a name="ec2_DescribeAvailabilityZones_powershell_4_topic"></a>

次のコード例は、`Get-EC2AvailabilityZone` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、利用可能な現在のリージョンのアベイラビリティーゾーンについて記述します。**  

```
Get-EC2AvailabilityZone
```
**出力:**  

```
Messages    RegionName    State        ZoneName
--------    ----------    -----        --------
{}          us-west-2     available    us-west-2a
{}          us-west-2     available    us-west-2b
{}          us-west-2     available    us-west-2c
```
**例 2: この例では、障害状態にあるアベイラビリティーゾーンを記述します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-EC2AvailabilityZone -Filter @{ Name="state";Values="impaired" }
```
**例 3: PowerShell バージョン 2 では、New-Object を使用してフィルターを作成する必要があります。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = "impaired"

Get-EC2AvailabilityZone -Filter $filter
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAvailabilityZones](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2BundleTask`
<a name="ec2_DescribeBundleTasks_powershell_4_topic"></a>

次のコード例は、`Get-EC2BundleTask` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したバンドルタスクを記述します。**  

```
Get-EC2BundleTask -BundleId bun-12345678
```
**例 2: この例では、状態が「完了」または「失敗」のバンドルタスクについて説明します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "complete", "failed" )

Get-EC2BundleTask -Filter $filter
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeBundleTasks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2CapacityReservation`
<a name="ec2_DescribeCapacityReservations_powershell_4_topic"></a>

次のコード例は、`Get-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リージョンの 1 つ以上のキャパシティ予約について記述します。**  

```
Get-EC2CapacityReservation -Region eu-west-1
```
**出力:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeCapacityReservations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2ConsoleOutput`
<a name="ec2_GetConsoleOutput_powershell_4_topic"></a>

次のコード例は、`Get-EC2ConsoleOutput` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Linux インスタンスのコンソール出力を取得します。コンソール出力はエンコードされます。**  

```
Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456
```
**出力:**  

```
InstanceId          Output
----------          ------
i-0e194d3c47c123637 WyAgICAwLjAwMDAwMF0gQ29tbW...bGU9dHR5UzAgc2Vs
```
**例 2: この例では、エンコードされたコンソール出力を変数に保存してからデコードします。**  

```
$Output_encoded = (Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456).Output
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Output_encoded))
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetConsoleOutput](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2CustomerGateway`
<a name="ec2_DescribeCustomerGateways_powershell_4_topic"></a>

次のコード例は、`Get-EC2CustomerGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたカスタマーゲートウェイについて記述します。**  

```
Get-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**出力:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
**例 2: この例では、保留中または使用可能な状態のカスタマーゲートウェイを記述します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2CustomerGateway -Filter $filter
```
**例 3: この例では、すべてのカスタマーゲートウェイを記述します。**  

```
Get-EC2CustomerGateway
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeCustomerGateways](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2DhcpOption`
<a name="ec2_DescribeDhcpOptions_powershell_4_topic"></a>

次のコード例は、`Get-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、DHCP オプションセットを一覧表示します。**  

```
Get-EC2DhcpOption
```
**出力:**  

```
DhcpConfigurations                    DhcpOptionsId    Tag
------------------                    -------------    ---
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
{domain-name-servers}                 dopt-3a4b5c6d    {}
```
**例 2: この例では、指定された DHCP オプションセットの設定の詳細を取得します。**  

```
(Get-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d).DhcpConfigurations
```
**出力:**  

```
Key                    Values
---                    ------
domain-name            {abc.local}
domain-name-servers    {10.0.0.101, 10.0.0.102}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2FlowLog`
<a name="ec2_DescribeFlowLogs_powershell_4_topic"></a>

次のコード例は、`Get-EC2FlowLog` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ログの送信先タイプが「s3」の 1 つ以上のフローログを記述します。**  

```
Get-EC2FlowLog -Filter @{Name="log-destination-type";Values="s3"}
```
**出力:**  

```
CreationTime             : 2/25/2019 9:07:36 PM
DeliverLogsErrorMessage  :
DeliverLogsPermissionArn :
DeliverLogsStatus        : SUCCESS
FlowLogId                : fl-01b2e3d45f67f8901
FlowLogStatus            : ACTIVE
LogDestination           : arn:aws:s3:::amzn-s3-demo-bucket-dd-tata
LogDestinationType       : s3
LogGroupName             :
ResourceId               : eni-01d2dda3456b7e890
TrafficType              : ALL
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeFlowLogs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Host`
<a name="ec2_DescribeHosts_powershell_4_topic"></a>

次のコード例は、`Get-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2 ホストの詳細を返します。**  

```
Get-EC2Host
```
**出力:**  

```
AllocationTime    : 3/23/2019 4:55:22 PM
AutoPlacement     : off
AvailabilityZone  : eu-west-1b
AvailableCapacity : Amazon.EC2.Model.AvailableCapacity
ClientToken       :
HostId            : h-01e23f4cd567890f1
HostProperties    : Amazon.EC2.Model.HostProperties
HostReservationId :
Instances         : {}
ReleaseTime       : 1/1/0001 12:00:00 AM
State             : available
Tags              : {}
```
**例 2: この例では、ホスト h-01e23f4cd567899f1 の AvailableInstanceCapacity をクエリします。**  

```
Get-EC2Host -HostId h-01e23f4cd567899f1 | Select-Object -ExpandProperty AvailableCapacity | Select-Object -expand AvailableInstanceCapacity
```
**出力:**  

```
AvailableCapacity InstanceType TotalCapacity
----------------- ------------ -------------
11                m4.xlarge    11
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeHosts](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2HostReservationOffering`
<a name="ec2_DescribeHostReservationOfferings_powershell_4_topic"></a>

次のコード例は、`Get-EC2HostReservationOffering` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、PaymentOption が「NoUpfront」である、指定されたフィルター「instance-family」で購入できる専有ホスト予約を記述します。**  

```
Get-EC2HostReservationOffering -Filter @{Name="instance-family";Values="m4"} | Where-Object PaymentOption -eq NoUpfront
```
**出力:**  

```
CurrencyCode   :
Duration       : 94608000
HourlyPrice    : 1.307
InstanceFamily : m4
OfferingId     : hro-0c1f234567890d9ab
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000

CurrencyCode   :
Duration       : 31536000
HourlyPrice    : 1.830
InstanceFamily : m4
OfferingId     : hro-04ad12aaaf34b5a67
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeHostReservationOfferings](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2HostReservationPurchasePreview`
<a name="ec2_GetHostReservationPurchasePreview_powershell_4_topic"></a>

次のコード例は、`Get-EC2HostReservationPurchasePreview` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、専有ホスト h-01e23f4cd567890f1 の構成と一致する設定の予約購入をプレビューします。**  

```
Get-EC2HostReservationPurchasePreview -OfferingId hro-0c1f23456789d0ab -HostIdSet h-01e23f4cd567890f1
```
**出力:**  

```
CurrencyCode Purchase TotalHourlyPrice TotalUpfrontPrice
------------ -------- ---------------- -----------------
             {}       1.307            0.000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetHostReservationPurchasePreview](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2IdFormat`
<a name="ec2_DescribeIdFormat_powershell_4_topic"></a>

次のコード例は、`Get-EC2IdFormat` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリソースタイプの ID 形式を記述します。**  

```
Get-EC2IdFormat -Resource instance
```
**出力:**  

```
Resource       UseLongIds
--------       ----------
instance       False
```
**例 2: この例では、長い ID をサポートするすべてのリソースタイプの ID 形式を記述します。**  

```
Get-EC2IdFormat
```
**出力:**  

```
Resource       UseLongIds
--------       ----------
reservation    False
instance       False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeIdFormat](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2IdentityIdFormat`
<a name="ec2_DescribeIdentityIdFormat_powershell_4_topic"></a>

次のコード例は、`Get-EC2IdentityIdFormat` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロールのリソース「image」の ID 形式を返します。**  

```
Get-EC2IdentityIdFormat -PrincipalArn arn:aws:iam::123456789511:role/JDBC -Resource image
```
**出力:**  

```
Deadline             Resource UseLongIds
--------             -------- ----------
8/2/2018 11:30:00 PM image    True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeIdentityIdFormat](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Image`
<a name="ec2_DescribeImages_powershell_4_topic"></a>

次のコード例は、`Get-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AMI を記述します。**  

```
Get-EC2Image -ImageId ami-12345678
```
**出力:**  

```
Architecture        : x86_64
BlockDeviceMappings : {/dev/xvda}
CreationDate        : 2014-10-20T00:56:28.000Z
Description         : My image
Hypervisor          : xen
ImageId             : ami-12345678
ImageLocation       : 123456789012/my-image
ImageOwnerAlias     :
ImageType           : machine
KernelId            :
Name                : my-image
OwnerId             : 123456789012
Platform            :
ProductCodes        : {}
Public              : False
RamdiskId           :
RootDeviceName      : /dev/xvda
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         :
Tags                : {Name}
VirtualizationType  : hvm
```
**例 2: この例では、所有している AMI を記述します。**  

```
Get-EC2Image -owner self
```
**例 3: この例では、Microsoft Windows Server を実行するパブリック AMI を記述します。**  

```
Get-EC2Image -Filter @{ Name="platform"; Values="windows" }
```
**例 4: この例では、「us-west-2」リージョンのすべてのパブリック AMI を記述します。**  

```
Get-EC2Image -Region us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeImages](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2ImageAttribute`
<a name="ec2_DescribeImageAttribute_powershell_4_topic"></a>

次のコード例は、`Get-EC2ImageAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AMI の説明を取得します。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute description
```
**出力:**  

```
BlockDeviceMappings : {}
Description         : My image description
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**例 2: この例では、指定された AMI の起動許可を取得します。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
**出力:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {all}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**例 3: この例では、拡張ネットワーキングが有効になっているかどうかをテストします。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute sriovNetSupport
```
**出力:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     : simple
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeImageAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2ImageByName`
<a name="ec2_Get-EC2ImageByName_powershell_4_topic"></a>

次のコード例は、`Get-EC2ImageByName` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在サポートされているフィルター名の完全なセットを記述します。**  

```
Get-EC2ImageByName
```
**出力:**  

```
WINDOWS_2016_BASE
WINDOWS_2016_NANO
WINDOWS_2016_CORE
WINDOWS_2016_CONTAINER
WINDOWS_2016_SQL_SERVER_ENTERPRISE_2016
WINDOWS_2016_SQL_SERVER_STANDARD_2016
WINDOWS_2016_SQL_SERVER_WEB_2016
WINDOWS_2016_SQL_SERVER_EXPRESS_2016
WINDOWS_2012R2_BASE
WINDOWS_2012R2_CORE
WINDOWS_2012R2_SQL_SERVER_EXPRESS_2016
WINDOWS_2012R2_SQL_SERVER_STANDARD_2016
WINDOWS_2012R2_SQL_SERVER_WEB_2016
WINDOWS_2012R2_SQL_SERVER_EXPRESS_2014
WINDOWS_2012R2_SQL_SERVER_STANDARD_2014
WINDOWS_2012R2_SQL_SERVER_WEB_2014
WINDOWS_2012_BASE
WINDOWS_2012_SQL_SERVER_EXPRESS_2014
WINDOWS_2012_SQL_SERVER_STANDARD_2014
WINDOWS_2012_SQL_SERVER_WEB_2014
WINDOWS_2012_SQL_SERVER_EXPRESS_2012
WINDOWS_2012_SQL_SERVER_STANDARD_2012
WINDOWS_2012_SQL_SERVER_WEB_2012
WINDOWS_2012_SQL_SERVER_EXPRESS_2008
WINDOWS_2012_SQL_SERVER_STANDARD_2008
WINDOWS_2012_SQL_SERVER_WEB_2008
WINDOWS_2008R2_BASE
WINDOWS_2008R2_SQL_SERVER_EXPRESS_2012
WINDOWS_2008R2_SQL_SERVER_STANDARD_2012
WINDOWS_2008R2_SQL_SERVER_WEB_2012
WINDOWS_2008R2_SQL_SERVER_EXPRESS_2008
WINDOWS_2008R2_SQL_SERVER_STANDARD_2008
WINDOWS_2008R2_SQL_SERVER_WEB_2008
WINDOWS_2008RTM_BASE
WINDOWS_2008RTM_SQL_SERVER_EXPRESS_2008
WINDOWS_2008RTM_SQL_SERVER_STANDARD_2008
WINDOWS_2008_BEANSTALK_IIS75
WINDOWS_2012_BEANSTALK_IIS8
VPC_NAT
```
**例 2: この例では、指定 AMI を記述します。は毎月最新の更新で新しい Windows AMI を AWS リリースするため、このコマンドを使用して AMIs を見つけると便利です。New-EC2Instance に「ImageId」を指定し、指定フィルターの現在の AMI を使用してインスタンスを起動できます。**  

```
Get-EC2ImageByName -Names WINDOWS_2016_BASE
```
**出力:**  

```
Architecture        : x86_64
BlockDeviceMappings : {/dev/sda1, xvdca, xvdcb, xvdcc...}
CreationDate        : yyyy.mm.ddThh:mm:ss.000Z
Description         : Microsoft Windows Server 2016 with Desktop Experience Locale English AMI provided by Amazon
Hypervisor          : xen
ImageId             : ami-xxxxxxxx
ImageLocation       : amazon/Windows_Server-2016-English-Full-Base-yyyy.mm.dd
ImageOwnerAlias     : amazon
ImageType           : machine
KernelId            :
Name                : Windows_Server-2016-English-Full-Base-yyyy.mm.dd
OwnerId             : 801119661308
Platform            : Windows
ProductCodes        : {}
Public              : True
RamdiskId           :
RootDeviceName      : /dev/sda1
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         :
Tags                : {}
VirtualizationType  : hvm
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Get-EC2ImageByName](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2ImportImageTask`
<a name="ec2_DescribeImportImageTasks_powershell_4_topic"></a>

次のコード例は、`Get-EC2ImportImageTask` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたイメージのインポートタスクを記述します。**  

```
Get-EC2ImportImageTask -ImportTaskId import-ami-hgfedcba
```
**出力:**  

```
Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
**例 2: この例では、すべてのイメージのインポートタスクを記述します。**  

```
Get-EC2ImportImageTask
```
**出力:**  

```
Architecture    :
Description     : Windows Image 1
Hypervisor      :
ImageId         :
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {}
Status          : deleted
StatusMessage   : User initiated task cancelation

Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeImportImageTasks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2ImportSnapshotTask`
<a name="ec2_DescribeImportSnapshotTasks_powershell_4_topic"></a>

次のコード例は、`Get-EC2ImportSnapshotTask` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスナップショットのインポートタスクを記述します。**  

```
Get-EC2ImportSnapshotTask -ImportTaskId import-snap-abcdefgh
```
**出力:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
**例 2: この例では、すべてのスナップショットのインポートタスクを記述します。**  

```
Get-EC2ImportSnapshotTask
```
**出力:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail 
Disk Image Import 2     import-snap-hgfedcba       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeImportSnapshotTasks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Instance`
<a name="ec2_DescribeInstances_powershell_4_topic"></a>

次のコード例は、`Get-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスを記述します。**  

```
(Get-EC2Instance -InstanceId i-12345678).Instances
```
**出力:**  

```
AmiLaunchIndex        : 0
Architecture          : x86_64
BlockDeviceMappings   : {/dev/sda1}
ClientToken           : TleEy1448154045270
EbsOptimized          : False
Hypervisor            : xen
IamInstanceProfile    : Amazon.EC2.Model.IamInstanceProfile
ImageId               : ami-12345678
InstanceId            : i-12345678
InstanceLifecycle     :
InstanceType          : t2.micro
KernelId              :
KeyName               : my-key-pair
LaunchTime            : 12/4/2015 4:44:40 PM
Monitoring            : Amazon.EC2.Model.Monitoring
NetworkInterfaces     : {ip-10-0-2-172.us-west-2.compute.internal}
Placement             : Amazon.EC2.Model.Placement
Platform              : Windows
PrivateDnsName        : ip-10-0-2-172.us-west-2.compute.internal
PrivateIpAddress      : 10.0.2.172
ProductCodes          : {}
PublicDnsName         : 
PublicIpAddress       : 
RamdiskId             :
RootDeviceName        : /dev/sda1
RootDeviceType        : ebs
SecurityGroups        : {default}
SourceDestCheck       : True
SpotInstanceRequestId :
SriovNetSupport       :
State                 : Amazon.EC2.Model.InstanceState
StateReason           :
StateTransitionReason :
SubnetId              : subnet-12345678
Tags                  : {Name}
VirtualizationType    : hvm
VpcId                 : vpc-12345678
```
**例 2: この例では、現在のリージョンのすべてのインスタンスを予約別にグループ化して記述します。インスタンスの詳細を表示するには、各予約オブジェクト内のインスタンスコレクションを展開します。**  

```
Get-EC2Instance
```
**出力:**  

```
GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 226008221399
ReservationId : r-c5df370c

GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 854251627541
ReservationId : r-63e65bab
...
```
**例 3: この例では、フィルターを使用して VPC の特定のサブネット内の EC2 インスタンスをクエリする方法を示します。**  

```
(Get-EC2Instance -Filter @{Name="vpc-id";Values="vpc-1a2bc34d"},@{Name="subnet-id";Values="subnet-1a2b3c4d"}).Instances
```
**出力:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-01af...82cf180e19 t2.medium    Windows  10.0.0.98                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0374...7e9d5b0c45 t2.xlarge    Windows  10.0.0.53                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**例 4: この例では、複数の値を持つフィルターを使用して、実行中および停止中の EC2 インスタンスをクエリする方法を示します。**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

(Get-EC2Instance @InstanceParams).Instances
```
**出力:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**例 5: この例では、複数の値を持つフィルターを使用して、実行中と停止中の両方の EC2 インスタンスをクエリし、Select-Object コマンドレットを使用して出力する特定の値を選択する方法を示します。**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

$SelectParams = @{
    Property = @(
        "InstanceID", "InstanceType", "Platform", "PrivateIpAddress",
        @{Name="Name";Expression={$_.Tags[$_.Tags.Key.IndexOf("Name")].Value}},
        @{Name="State";Expression={$_.State.Name}}
    )
}

$result = Get-EC2Instance @InstanceParams
$result.Instances | Select-Object @SelectParams | Format-Table -AutoSize
```
**出力:**  

```
InstanceId          InstanceType Platform PrivateIpAddress Name         State
----------          ------------ -------- ---------------- ----         -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7         ec2-name-01  running
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8         ec2-name-02  stopped
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10        ec2-name-03  running
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11        ec2-name-04  stopped
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5         ec2-name-05  running
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6         ec2-name-06  stopped
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2InstanceAttribute`
<a name="ec2_DescribeInstanceAttribute_powershell_4_topic"></a>

次のコード例は、`Get-EC2InstanceAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスのインスタンスタイプを記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceType
```
**出力:**  

```
InstanceType                      : t2.micro
```
**例 2: この例では、指定されたインスタンスで拡張ネットワーキングが有効になっているかどうかを記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**出力:**  

```
SriovNetSupport                   : simple
```
**例 3: この例では、指定されたインスタンスのセキュリティグループについて記述します。**  

```
(Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute groupSet).Groups
```
**出力:**  

```
GroupId
-------
sg-12345678
sg-45678901
```
**例 4: この例では、指定したインスタンスで EBS 最適化が有効になっているかどうかを記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**出力:**  

```
EbsOptimized                      : False
```
**例 5: この例では、指定されたインスタンスの「disableApiTermination」属性を記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**出力:**  

```
DisableApiTermination             : False
```
**例 6: この例では、指定されたインスタンスの「instanceInitiatedShutdownBehavior」属性を記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
**出力:**  

```
InstanceInitiatedShutdownBehavior : stop
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstanceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2InstanceMetadata`
<a name="ec2_Get-EC2InstanceMetadata_powershell_4_topic"></a>

次のコード例は、`Get-EC2InstanceMetadata` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: クエリできるインスタンスメタデータの利用可能なカテゴリを一覧表示します。**  

```
Get-EC2InstanceMetadata -ListCategory
```
**出力:**  

```
AmiId
LaunchIndex
ManifestPath
AncestorAmiId
BlockDeviceMapping
InstanceId
InstanceType
LocalHostname
LocalIpv4
KernelId
AvailabilityZone
ProductCode
PublicHostname
PublicIpv4
PublicKey
RamdiskId
Region
ReservationId
SecurityGroup
UserData
InstanceMonitoring
IdentityDocument
IdentitySignature
IdentityPkcs7
```
**例 2: インスタンスの起動に使用された Amazon マシンイメージ (AMI) の ID を返します。**  

```
Get-EC2InstanceMetadata -Category AmiId
```
**出力:**  

```
ami-b2e756ca
```
**例 3: この例では、インスタンスの JSON 形式の ID ドキュメントをクエリします。**  

```
Get-EC2InstanceMetadata -Category IdentityDocument
{
  "availabilityZone" : "us-west-2a",
  "devpayProductCodes" : null,
  "marketplaceProductCodes" : null,
  "version" : "2017-09-30",
  "instanceId" : "i-01ed50f7e2607f09e",
  "billingProducts" : [ "bp-6ba54002" ],
  "instanceType" : "t2.small",
  "pendingTime" : "2018-03-07T16:26:04Z",
  "imageId" : "ami-b2e756ca",
  "privateIp" : "10.0.0.171",
  "accountId" : "111122223333",
  "architecture" : "x86_64",
  "kernelId" : null,
  "ramdiskId" : null,
  "region" : "us-west-2"
}
```
**例 4: この例では、パスクエリを使用してインスタンスのネットワークインターフェイスの MAC を取得します。**  

```
Get-EC2InstanceMetadata -Path "/network/interfaces/macs"
```
**出力:**  

```
02:80:7f:ef:4c:e0/
```
**例 5: インスタンスに関連付けられた IAM ロールがある場合、インスタンスの LastUpdated の日付、InstanceProfileArn、InstanceProfileId など、インスタンスプロファイルが更新された最終時刻に関する情報が返されます。**  

```
Get-EC2InstanceMetadata -Path "/iam/info"
```
**出力:**  

```
{
  "Code" : "Success",
  "LastUpdated" : "2018-03-08T03:38:40Z",
  "InstanceProfileArn" : "arn:aws:iam::111122223333:instance-profile/MyLaunchRole_Profile",
  "InstanceProfileId" : "AIPAI4...WVK2RW"
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Get-EC2InstanceMetadata](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2InstanceStatus`
<a name="ec2_DescribeInstanceStatus_powershell_4_topic"></a>

次のコード例は、`Get-EC2InstanceStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスのステータスを記述します。**  

```
Get-EC2InstanceStatus -InstanceId i-12345678
```
**出力:**  

```
AvailabilityZone : us-west-2a
Events           : {}
InstanceId       : i-12345678
InstanceState    : Amazon.EC2.Model.InstanceState
Status           : Amazon.EC2.Model.InstanceStatusSummary
SystemStatus     : Amazon.EC2.Model.InstanceStatusSummary
```

```
$status = Get-EC2InstanceStatus -InstanceId i-12345678
$status.InstanceState
```
**出力:**  

```
Code    Name
----    ----
16      running
```

```
$status.Status
```
**出力:**  

```
Details           Status
-------           ------
{reachability}    ok
```

```
$status.SystemStatus
```
**出力:**  

```
Details           Status
-------           ------
{reachability}    ok
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstanceStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2InternetGateway`
<a name="ec2_DescribeInternetGateways_powershell_4_topic"></a>

次のコード例は、`Get-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインターネットゲートウェイを記述します。**  

```
Get-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**出力:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
```
**例 2: この例では、すべてのインターネットゲートウェイを記述します。**  

```
Get-EC2InternetGateway
```
**出力:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
{}                igw-2a3b4c5d          {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInternetGateways](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2KeyPair`
<a name="ec2_DescribeKeyPairs_powershell_4_topic"></a>

次のコード例は、`Get-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したキーペアを記述します。**  

```
Get-EC2KeyPair -KeyName my-key-pair
```
**出力:**  

```
KeyFingerprint                                              KeyName
--------------                                              -------
1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f my-key-pair
```
**例 2: この例では、すべてのキーペアを記述します。**  

```
Get-EC2KeyPair
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeKeyPairs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2NetworkAcl`
<a name="ec2_DescribeNetworkAcls_powershell_4_topic"></a>

次のコード例は、`Get-EC2NetworkAcl` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したネットワーク ACL を記述します。**  

```
Get-EC2NetworkAcl -NetworkAclId acl-12345678
```
**出力:**  

```
Associations : {aclassoc-1a2b3c4d}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {Name}
VpcId        : vpc-12345678
```
**例 2: この例では、指定されたネットワーク ACL のルールを記述します。**  

```
(Get-EC2NetworkAcl -NetworkAclId acl-12345678).Entries
```
**出力:**  

```
CidrBlock    : 0.0.0.0/0
Egress       : True
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767

CidrBlock    : 0.0.0.0/0
Egress       : False
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767
```
**例 3: この例では、すべてのネットワーク ACL を記述します。**  

```
Get-EC2NetworkAcl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeNetworkAcls](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2NetworkInterface`
<a name="ec2_DescribeNetworkInterfaces_powershell_4_topic"></a>

次のコード例は、`Get-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**出力:**  

```
Association        :
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
AvailabilityZone   : us-west-2c
Description        :
Groups             : {my-security-group}
MacAddress         : 0a:e9:a6:19:4c:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-107.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.107
PrivateIpAddresses : {ip-10-0-0-107.us-west-2.compute.internal}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : in-use
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
**例 2: この例では、すべてのネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterface
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeNetworkInterfaces](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2NetworkInterfaceAttribute`
<a name="ec2_DescribeNetworkInterfaceAttribute_powershell_4_topic"></a>

次のコード例は、`Get-EC2NetworkInterfaceAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Attachment
```
**出力:**  

```
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
```
**例 2: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Description
```
**出力:**  

```
Description        : My description
```
**例 3: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute GroupSet
```
**出力:**  

```
Groups             : {my-security-group}
```
**例 4: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute SourceDestCheck
```
**出力:**  

```
SourceDestCheck    : True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2PasswordData`
<a name="ec2_GetPasswordData_powershell_4_topic"></a>

次のコード例は、`Get-EC2PasswordData` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Amazon EC2 が指定された Windows インスタンスの管理者アカウントに割り当てたパスワードを復号します。pem ファイルを指定すると、-Decrypt スイッチの設定が自動的に適用されます。**  

```
Get-EC2PasswordData -InstanceId i-12345678 -PemFile C:\path\my-key-pair.pem
```
**出力:**  

```
mYZ(PA9?C)Q
```
**例 2: (Windows PowerShell のみ) インスタンスを検査して、インスタンスの起動に使用されるキーペアの名前を判断し、 AWS Toolkit for Visual Studio の設定ストアで対応するキーペアデータを見つけようとします。キーペアデータが見つかった場合、パスワードは復号されます。**  

```
Get-EC2PasswordData -InstanceId i-12345678 -Decrypt
```
**出力:**  

```
mYZ(PA9?C)Q
```
**例 3: インスタンスの暗号化されたパスワードデータを返します。**  

```
Get-EC2PasswordData -InstanceId i-12345678
```
**出力:**  

```
iVz3BAK/WAXV.....dqt8WeMA==
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPasswordData](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2PlacementGroup`
<a name="ec2_DescribePlacementGroups_powershell_4_topic"></a>

次のコード例は、`Get-EC2PlacementGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したプレイスメントグループを記述します。**  

```
Get-EC2PlacementGroup -GroupName my-placement-group
```
**出力:**  

```
GroupName             State        Strategy
---------             -----        --------
my-placement-group    available    cluster
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribePlacementGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2PrefixList`
<a name="ec2_DescribePrefixLists_powershell_4_topic"></a>

次のコード例は、`Get-EC2PrefixList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 リージョンの AWS のサービス プレフィックスリスト形式で使用可能な を取得します。**  

```
Get-EC2PrefixList
```
**出力:**  

```
Cidrs                                          PrefixListId PrefixListName
-----                                          ------------ --------------
{52.94.5.0/24, 52.119.240.0/21, 52.94.24.0/23} pl-6fa54006  com.amazonaws.eu-west-1.dynamodb
{52.218.0.0/17, 54.231.128.0/19}               pl-6da54004  com.amazonaws.eu-west-1.s3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribePrefixLists](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Region`
<a name="ec2_DescribeRegions_powershell_4_topic"></a>

次のコード例は、`Get-EC2Region` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、使用可能なリージョンについて記述します。**  

```
Get-EC2Region
```
**出力:**  

```
Endpoint                            RegionName
--------                            ----------
ec2.eu-west-1.amazonaws.com         eu-west-1
ec2.ap-southeast-1.amazonaws.com    ap-southeast-1
ec2.ap-southeast-2.amazonaws.com    ap-southeast-2
ec2.eu-central-1.amazonaws.com      eu-central-1
ec2.ap-northeast-1.amazonaws.com    ap-northeast-1
ec2.us-east-1.amazonaws.com         us-east-1
ec2.sa-east-1.amazonaws.com         sa-east-1
ec2.us-west-1.amazonaws.com         us-west-1
ec2.us-west-2.amazonaws.com         us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeRegions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2RouteTable`
<a name="ec2_DescribeRouteTables_powershell_4_topic"></a>

次のコード例は、`Get-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべてのルートテーブルについて記述します。**  

```
Get-EC2RouteTable
```
**出力:**  

```
DestinationCidrBlock    : 10.0.0.0/16
DestinationPrefixListId :
GatewayId               : local
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRouteTable
State                   : active
VpcPeeringConnectionId  :

DestinationCidrBlock    : 0.0.0.0/0
DestinationPrefixListId :
GatewayId               : igw-1a2b3c4d
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRoute
State                   : active
VpcPeeringConnectionId  :
```
**例 2: この例では、指定されたルートテーブルの詳細を返します。**  

```
Get-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**例 3: この例では、指定された VPC のルートテーブルを記述します。**  

```
Get-EC2RouteTable -Filter @{ Name="vpc-id"; Values="vpc-1a2b3c4d" }
```
**出力:**  

```
Associations    : {rtbassoc-12345678}
PropagatingVgws : {}
Routes          : {, }
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeRouteTables](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2ScheduledInstance`
<a name="ec2_DescribeScheduledInstances_powershell_4_topic"></a>

次のコード例は、`Get-EC2ScheduledInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定のスケジュールされたインスタンスを記述します。**  

```
Get-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012
```
**出力:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
**例 2: この例では、すべてのスケジュールされたインスタンスを記述します。**  

```
Get-EC2ScheduledInstance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScheduledInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2ScheduledInstanceAvailability`
<a name="ec2_DescribeScheduledInstanceAvailability_powershell_4_topic"></a>

次のコード例は、`Get-EC2ScheduledInstanceAvailability` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した日付から毎週日曜日に発生するスケジュールを記述します。**  

```
Get-EC2ScheduledInstanceAvailability -Recurrence_Frequency Weekly -Recurrence_Interval 1 -Recurrence_OccurrenceDay 1 -FirstSlotStartTimeRange_EarliestTime 2016-01-31T00:00:00Z -FirstSlotStartTimeRange_LatestTime 2016-01-31T04:00:00Z
```
**出力:**  

```
AvailabilityZone            : us-west-2b
AvailableInstanceCount      : 20
FirstSlotStartTime          : 1/31/2016 8:00:00 AM
HourlyPrice                 : 0.095
InstanceType                : c4.large
MaxTermDurationInDays       : 366
MinTermDurationInDays       : 366
NetworkPlatform             : EC2-VPC
Platform                    : Linux/UNIX
PurchaseToken               : eyJ2IjoiMSIsInMiOjEsImMiOi...
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
SlotDurationInHours         : 23
TotalScheduledInstanceHours : 1219

...
```
**例 2: 結果を絞り込むには、オペレーティングシステム、ネットワーク、インスタンスタイプなどの条件でフィルターを追加できます。**  

```
-Filter @{ Name="platform";Values="Linux/UNIX" },@{ Name="network-platform";Values="EC2-VPC" },@{ Name="instance-type";Values="c4.large" }
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeScheduledInstanceAvailability](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SecurityGroup`
<a name="ec2_DescribeSecurityGroups_powershell_4_topic"></a>

次のコード例は、`Get-EC2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、VPC に指定されたセキュリティグループについて記述します。VPC に属するセキュリティグループを使用する場合は、グループ名 (-GroupName パラメータ) ではなくセキュリティグループ ID (-GroupId パラメータ) を使用してグループを参照する必要があります。**  

```
Get-EC2SecurityGroup -GroupId sg-12345678
```
**出力:**  

```
Description         : default VPC security group
GroupId             : sg-12345678
GroupName           : default
IpPermissions       : {Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {Amazon.EC2.Model.IpPermission}
OwnerId             : 123456789012
Tags                : {}
VpcId               : vpc-12345678
```
**例 2: この例では、EC2-Classic に指定されたセキュリティグループを記述します。EC2-Classic のセキュリティグループを使用する場合は、グループ名 (-GroupName パラメータ) またはグループ ID (-GroupId パラメータ) を使用してセキュリティグループを参照できます。**  

```
Get-EC2SecurityGroup -GroupName my-security-group
```
**出力:**  

```
Description         : my security group
GroupId             : sg-45678901
GroupName           : my-security-group
IpPermissions       : {Amazon.EC2.Model.IpPermission, Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {}
OwnerId             : 123456789012
Tags                : {}
VpcId               :
```
**例 3: この例では、vpc-0fc1ff23456b789eb のすべてのセキュリティグループを取得します。**  

```
Get-EC2SecurityGroup -Filter @{Name="vpc-id";Values="vpc-0fc1ff23456b789eb"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSecurityGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Snapshot`
<a name="ec2_DescribeSnapshots_powershell_4_topic"></a>

次のコード例は、`Get-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したスナップショットを記述します。**  

```
Get-EC2Snapshot -SnapshotId snap-12345678
```
**出力:**  

```
DataEncryptionKeyId :
Description         : Created by CreateImage(i-1a2b3c4d) for ami-12345678 from vol-12345678
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            : 100%
SnapshotId          : snap-12345678
StartTime           : 10/23/2014 6:01:28 AM
State               : completed
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 8
```
**例 2: この例では、「Name」タグを持つスナップショットを記述します。**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" }
```
**例 3: この例では、「Name」タグと値「TestValue」を持つスナップショットを記述します。**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" -and $_.Tags.Value -eq "TestValue" }
```
**例 4: この例では、すべてのスナップショットを記述します。**  

```
Get-EC2Snapshot -Owner self
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSnapshots](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SnapshotAttribute`
<a name="ec2_DescribeSnapshotAttribute_powershell_4_topic"></a>

次のコード例は、`Get-EC2SnapshotAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスナップショットの指定された属性を記述します。**  

```
Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute ProductCodes
```
**出力:**  

```
CreateVolumePermissions    ProductCodes    SnapshotId
-----------------------    ------------    ----------
{}                         {}              snap-12345678
```
**例 2: この例では、指定されたスナップショットの指定された属性を記述します。**  

```
(Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission).CreateVolumePermissions
```
**出力:**  

```
Group    UserId
-----    ------
all
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSnapshotAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SpotDatafeedSubscription`
<a name="ec2_DescribeSpotDatafeedSubscription_powershell_4_topic"></a>

次のコード例は、`Get-EC2SpotDatafeedSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スポットインスタンスのデータフィードについて記述します。**  

```
Get-EC2SpotDatafeedSubscription
```
**出力:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SpotFleetInstance`
<a name="ec2_DescribeSpotFleetInstances_powershell_4_topic"></a>

次のコード例は、`Get-EC2SpotFleetInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスポットフリートリクエストに関連付けられたインスタンスについて記述します。**  

```
Get-EC2SpotFleetInstance -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
**出力:**  

```
InstanceId    InstanceType    SpotInstanceRequestId
----------    ------------    ---------------------
i-f089262a    c3.large        sir-12345678
i-7e8b24a4    c3.large        sir-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSpotFleetInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SpotFleetRequest`
<a name="ec2_DescribeSpotFleetRequests_powershell_4_topic"></a>

次のコード例は、`Get-EC2SpotFleetRequest` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスポットフリートリクエストを記述します。**  

```
Get-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE | format-list
```
**出力:**  

```
ConfigData            : Amazon.EC2.Model.SpotFleetRequestConfigData
CreateTime            : 12/26/2015 8:23:33 AM
SpotFleetRequestId    : sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
SpotFleetRequestState : active
```
**例 2: この例では、すべてのスポットフリートリクエストを記述します。**  

```
Get-EC2SpotFleetRequest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSpotFleetRequests](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SpotFleetRequestHistory`
<a name="ec2_DescribeSpotFleetRequestHistory_powershell_4_topic"></a>

次のコード例は、`Get-EC2SpotFleetRequestHistory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスポットフリートリクエストの履歴を記述します。**  

```
Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z
```
**出力:**  

```
HistoryRecords     : {Amazon.EC2.Model.HistoryRecord, Amazon.EC2.Model.HistoryRecord...}
LastEvaluatedTime  : 12/26/2015 8:29:11 AM
NextToken          :
SpotFleetRequestId : sfr-088bc5f1-7e7b-451a-bd13-757f10672b93
StartTime          : 12/25/2015 8:00:00 AM
```

```
(Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z).HistoryRecords
```
**出力:**  

```
EventInformation                     EventType             Timestamp
----------------                     ---------             ---------
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:34 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:05 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSpotFleetRequestHistory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SpotInstanceRequest`
<a name="ec2_DescribeSpotInstanceRequests_powershell_4_topic"></a>

次のコード例は、`Get-EC2SpotInstanceRequest` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したスポットインスタンスを記述します。**  

```
Get-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**出力:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 4/8/2015 2:51:33 PM
Fault                    :
InstanceId               : i-12345678
LaunchedAvailabilityZone : us-west-2b
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.020000
State                    : active
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {Name}
Type                     : one-time
```
**例 2: この例では、すべてのスポットインスタンスリクエストを記述します。**  

```
Get-EC2SpotInstanceRequest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2SpotPriceHistory`
<a name="ec2_DescribeSpotPriceHistory_powershell_4_topic"></a>

次のコード例は、`Get-EC2SpotPriceHistory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスタイプとアベイラビリティーゾーンのスポット料金履歴から直近 10 件のエントリを取得します。-AvailabilityZone パラメータに指定された値は、コマンドレットの -Region パラメータ (例に示されていない) に指定されたリージョン値に対して有効であるか、シェルでデフォルトとして設定されている必要があることに注意してください。このコマンド例では、「us-west-2」のデフォルトリージョンが環境で設定されていることを前提としています。**  

```
Get-EC2SpotPriceHistory -InstanceType c3.large -AvailabilityZone us-west-2a -MaxResult 10
```
**出力:**  

```
AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:39:49 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017200
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:38:29 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 6:57:13 AM
...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSpotPriceHistory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Subnet`
<a name="ec2_DescribeSubnets_powershell_4_topic"></a>

次のコード例は、`Get-EC2Subnet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したサブネットを記述します。**  

```
Get-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : available
SubnetId                : subnet-1a2b3c4d
Tags                    : {}
VpcId                   : vpc-12345678
```
**例 2: この例では、すべてのサブネットを記述します。**  

```
Get-EC2Subnet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSubnets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Tag`
<a name="ec2_DescribeTags_powershell_4_topic"></a>

次のコード例は、`Get-EC2Tag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リソースタイプ「image」のタグを取得します。**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="image"}
```
**出力:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
Name        ami-0a123b4ccb567a8ea image        Win7-Imported
auto-delete ami-0a123b4ccb567a8ea image        never
```
**例 2: この例では、すべてのリソースのすべてのタグを取得し、リソースタイプ別にグループ化します。**  

```
Get-EC2Tag | Group-Object resourcetype
```
**出力:**  

```
Count Name                      Group
----- ----                      -----
    9 subnet                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   53 instance                  {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    3 route-table               {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    5 security-group            {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   30 volume                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    1 internet-gateway          {Amazon.EC2.Model.TagDescription}
    3 network-interface         {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    4 elastic-ip                {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    1 dhcp-options              {Amazon.EC2.Model.TagDescription}
    2 image                     {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    3 vpc                       {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
```
**例 3: この例では、指定されたリージョンでタグ「auto-delete」と値「no」を持つすべてのリソースを表示します。**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"}
```
**出力:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
auto-delete i-0f1bce234d5dd678b   instance     no
auto-delete vol-01d234aa5678901a2 volume       no
auto-delete vol-01234bfb5def6f7b8 volume       no
auto-delete vol-01ccb23f4c5e67890 volume       no
```
**例 4: この例では、タグ「auto-delete」と値「no」を持つすべてのリソースを取得し、次のパイプでさらにフィルターして「instance」リソースタイプのみを解析し、最終的に各インスタンスリソースに対して、そのインスタンス ID 自体を値とする「ThisInstance」タグを作成します。**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"} | Where-Object ResourceType -eq "instance" | ForEach-Object {New-EC2Tag -ResourceId $_.ResourceId -Tag @{Key="ThisInstance";Value=$_.ResourceId}}
```
**例 5: この例では、すべてのインスタンスリソースのタグと「Name」キーを取得し、テーブル形式で表示します。**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="instance"},@{Name="key";Values="Name"} | Select-Object ResourceId, @{Name="Name-Tag";Expression={$PSItem.Value}} | Format-Table -AutoSize
```
**出力:**  

```
ResourceId          Name-Tag
----------          --------
i-012e3cb4df567e1aa jump1
i-01c23a45d6fc7a89f repro-3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Volume`
<a name="ec2_DescribeVolumes_powershell_4_topic"></a>

次のコード例は、`Get-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した EBS ボリュームを記述します。**  

```
Get-EC2Volume -VolumeId vol-12345678
```
**出力:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 7/17/2015 4:35:19 PM
Encrypted        : False
Iops             : 90
KmsKeyId         :
Size             : 30
SnapshotId       : snap-12345678
State            : in-use
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : standard
```
**例 2: この例では、ステータスが「使用可能」の EBS ボリュームを記述します。**  

```
Get-EC2Volume -Filter @{ Name="status"; Values="available" }
```
**出力:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 12/21/2015 2:31:29 PM
Encrypted        : False
Iops             : 60
KmsKeyId         :
Size             : 20
SnapshotId       : snap-12345678
State            : available
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
...
```
**例 3: この例では、すべての EBS ボリュームを記述します。**  

```
Get-EC2Volume
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVolumes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VolumeAttribute`
<a name="ec2_DescribeVolumeAttribute_powershell_4_topic"></a>

次のコード例は、`Get-EC2VolumeAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたボリュームの指定された属性を記述します。**  

```
Get-EC2VolumeAttribute -VolumeId vol-12345678 -Attribute AutoEnableIO
```
**出力:**  

```
AutoEnableIO    ProductCodes    VolumeId
------------    ------------    --------
False           {}              vol-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVolumeAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VolumeStatus`
<a name="ec2_DescribeVolumeStatus_powershell_4_topic"></a>

次のコード例は、`Get-EC2VolumeStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたボリュームのステータスを記述します。**  

```
Get-EC2VolumeStatus -VolumeId vol-12345678
```
**出力:**  

```
Actions          : {}
AvailabilityZone : us-west-2a
Events           : {}
VolumeId         : vol-12345678
VolumeStatus     : Amazon.EC2.Model.VolumeStatusInfo
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus
```
**出力:**  

```
Details                         Status
-------                         ------
{io-enabled, io-performance}    ok
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus.Details
```
**出力:**  

```
Name                            Status
----                            ------
io-enabled                      passed
io-performance                  not-applicable
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVolumeStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2Vpc`
<a name="ec2_DescribeVpcs_powershell_4_topic"></a>

次のコード例は、`Get-EC2Vpc` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した VPC を記述します。**  

```
Get-EC2Vpc -VpcId vpc-12345678
```
**出力:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : available
Tags            : {Name}
VpcId           : vpc-12345678
```
**例 2: この例では、デフォルトの VPC を記述します (リージョンごとに 1 つだけ指定できます)。アカウントがこのリージョンで EC2-Classic をサポートしている場合、デフォルトの VPC はありません。**  

```
Get-EC2Vpc -Filter @{Name="isDefault"; Values="true"}
```
**出力:**  

```
CidrBlock       : 172.31.0.0/16
DhcpOptionsId   : dopt-12345678
InstanceTenancy : default
IsDefault       : True
State           : available
Tags            : {}
VpcId           : vpc-45678901
```
**例 3: この例では、指定されたフィルターに一致する VPC を記述します (つまり、値 「10.0.0.0/16」に一致する CIDR を持ち、状態が「available」である VPC)。**  

```
Get-EC2Vpc -Filter @{Name="cidr"; Values="10.0.0.0/16"},@{Name="state";Values="available"}
```
**例 4: この例では、すべての VPC を記述します。**  

```
Get-EC2Vpc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpcs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VpcAttribute`
<a name="ec2_DescribeVpcAttribute_powershell_4_topic"></a>

次のコード例は、`Get-EC2VpcAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「enableDnsSupport」属性を記述します。**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsSupport
```
**出力:**  

```
EnableDnsSupport
----------------
True
```
**例 2: この例では、「enableDnsHostnames」属性を記述します。**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsHostnames
```
**出力:**  

```
EnableDnsHostnames
------------------
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpcAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VpcClassicLink`
<a name="ec2_DescribeVpcClassicLink_powershell_4_topic"></a>

次のコード例は、`Get-EC2VpcClassicLink` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 上記の例では、リージョンの ClassicLinkEnabled 状態を持つすべての VPC を返します。**  

```
Get-EC2VpcClassicLink -Region eu-west-1
```
**出力:**  

```
ClassicLinkEnabled Tags   VpcId
------------------ ----   -----
False              {Name} vpc-0fc1ff23f45b678eb
False              {}     vpc-01e23c4a5d6db78e9
False              {Name} vpc-0123456b078b9d01f
False              {}     vpc-12cf3b4f
False              {Name} vpc-0b12d3456a7e8901d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpcClassicLink](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DescribeVpcClassicLinkDnsSupport_powershell_4_topic"></a>

次のコード例は、`Get-EC2VpcClassicLinkDnsSupport` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リージョン eu-west-1 の VPC の ClassicLink DNS サポートステータスを記述します。**  

```
Get-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
**出力:**  

```
ClassicLinkDnsSupported VpcId
----------------------- -----
False                   vpc-0b12d3456a7e8910d
False                   vpc-12cf3b4f
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VpcEndpoint`
<a name="ec2_DescribeVpcEndpoints_powershell_4_topic"></a>

次のコード例は、`Get-EC2VpcEndpoint` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リージョン eu-west-1 の 1 つ以上の VPC エンドポイントについて記述します。次に、出力を次のコマンドにパイプします。このコマンドは VpcEndpointId プロパティを選択し、配列 VPC ID を文字列配列として返します。**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object -ExpandProperty VpcEndpointId
```
**出力:**  

```
vpce-01a2ab3f4f5cc6f7d
vpce-01d2b345a6787890b
vpce-0012e34d567890e12
vpce-0c123db4567890123
```
**例 2: この例では、リージョン eu-west-1 のすべての vpc エンドポイントを記述し、VpcEndpointId、VpcId、ServiceName、および PrivateDnsEnabled プロパティを選択して表形式で表示します。**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object VpcEndpointId, VpcId, ServiceName, PrivateDnsEnabled | Format-Table -AutoSize
```
**出力:**  

```
VpcEndpointId          VpcId                 ServiceName                         PrivateDnsEnabled
-------------          -----                 -----------                         -----------------
vpce-02a2ab2f2f2cc2f2d vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssm                      True
vpce-01d1b111a1114561b vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2                      True
vpce-0011e23d45167e838 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2messages              True
vpce-0c123db4567890123 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssmmessages              True
```
**例 3: この例では、VPC エンドポイント vpce-01a2ab3f4f5cc6f7d のポリシードキュメントを JSON ファイルにエクスポートします。**  

```
Get-EC2VpcEndpoint -Region eu-west-1 -VpcEndpointId vpce-01a2ab3f4f5cc6f7d | Select-Object -expand PolicyDocument | Out-File vpce_policyDocument.json
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpcEndpoints](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VpcEndpointService`
<a name="ec2_DescribeVpcEndpointServices_powershell_4_topic"></a>

次のコード例は、`Get-EC2VpcEndpointService` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたフィルター (この場合は com.amazonaws.eu-west-1.ecs) を持つ EC2 VPC エンドポイントサービスについて記述します。さらに、ServiceDetails プロパティも展開され、詳細が表示されます。**  

```
Get-EC2VpcEndpointService -Region eu-west-1 -MaxResult 5 -Filter @{Name="service-name";Values="com.amazonaws.eu-west-1.ecs"} | Select-Object -ExpandProperty ServiceDetails
```
**出力:**  

```
AcceptanceRequired         : False
AvailabilityZones          : {eu-west-1a, eu-west-1b, eu-west-1c}
BaseEndpointDnsNames       : {ecs.eu-west-1.vpce.amazonaws.com}
Owner                      : amazon
PrivateDnsName             : ecs.eu-west-1.amazonaws.com
ServiceName                : com.amazonaws.eu-west-1.ecs
ServiceType                : {Amazon.EC2.Model.ServiceTypeDetail}
VpcEndpointPolicySupported : False
```
**例 2: この例では、すべての EC2 VPC エンドポイントサービスを取得し、「ssm」に一致する ServiceNames を返します。**  

```
Get-EC2VpcEndpointService -Region eu-west-1 | Select-Object -ExpandProperty Servicenames | Where-Object { -match "ssm"}
```
**出力:**  

```
com.amazonaws.eu-west-1.ssm
com.amazonaws.eu-west-1.ssmmessages
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpcEndpointServices](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VpnConnection`
<a name="ec2_DescribeVpnConnections_powershell_4_topic"></a>

次のコード例は、`Get-EC2VpnConnection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPN 接続を記述します。**  

```
Get-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**出力:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      : Amazon.EC2.Model.VpnConnectionOptions
Routes                       : {Amazon.EC2.Model.VpnStaticRoute}
State                        : available
Tags                         : {}
Type                         : ipsec.1
VgwTelemetry                 : {Amazon.EC2.Model.VgwTelemetry, Amazon.EC2.Model.VgwTelemetry}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**例 2: この例では、保留中または使用可能な状態の VPN 接続を記述します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnConnection -Filter $filter
```
**例 3: この例では、すべての VPN 接続を記述します。**  

```
Get-EC2VpnConnection
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpnConnections](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EC2VpnGateway`
<a name="ec2_DescribeVpnGateways_powershell_4_topic"></a>

次のコード例は、`Get-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された仮想プライベートゲートウェイを記述します。**  

```
Get-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**出力:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {vpc-12345678}
VpnGatewayId     : vgw-1a2b3c4d
```
**例 2: この例では、保留中または使用可能な状態の仮想プライベートゲートウェイを記述します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnGateway -Filter $filter
```
**例 3: この例では、仮想プライベートゲートウェイを記述します。**  

```
Get-EC2VpnGateway
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeVpnGateways](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Grant-EC2SecurityGroupEgress`
<a name="ec2_AuthorizeSecurityGroupEgress_powershell_4_topic"></a>

次のコード例は、`Grant-EC2SecurityGroupEgress` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループの退出ルールを定義します。このルールは、TCP ポート 80 で、指定された IP アドレス範囲へのアクセスを許可します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 3: この例では、TCP ポート 80 で指定されたソースセキュリティグループへのアクセスを許可します。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AuthorizeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Grant-EC2SecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_powershell_4_topic"></a>

次のコード例は、`Grant-EC2SecurityGroupIngress` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2-VPC のセキュリティグループの進入ルールを定義します。これらのルールは、SSH (ポート 22) と RDC (ポート 3389) の特定の IP アドレスへのアクセスを許可します。セキュリティグループの名前ではなく、セキュリティグループの ID を使用して、EC2-VPC のセキュリティグループを識別する必要があります。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**例 3: この例では、EC2-Classic のセキュリティグループの進入ルールを定義します。これらのルールは、SSH (ポート 22) と RDC (ポート 3389) の特定の IP アドレスへのアクセスを許可します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**例 4: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**例 5: この例では、指定されたソースセキュリティグループ (sg-1a2b3c4d) から指定されたセキュリティグループ (sg-12345678) への TCP ポート 8081 のアクセスを許可します。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="8081"; ToPort="8081"; UserIdGroupPairs=$ug } )
```
**例 6: この例では、セキュリティグループ sg-1234abcd の進入ルールに、TCP ポート 22 トラフィック用の CIDR 5.5.5.5/32 を説明付きで追加します。**  

```
$IpRange = New-Object -TypeName Amazon.EC2.Model.IpRange
$IpRange.CidrIp = "5.5.5.5/32"
$IpRange.Description = "SSH from Office"
$IpPermission = New-Object Amazon.EC2.Model.IpPermission
$IpPermission.IpProtocol = "tcp"
$IpPermission.ToPort = 22
$IpPermission.FromPort = 22
$IpPermission.Ipv4Ranges = $IpRange
Grant-EC2SecurityGroupIngress -GroupId sg-1234abcd -IpPermission $IpPermission
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Import-EC2Image`
<a name="ec2_ImportImage_powershell_4_topic"></a>

次のコード例は、`Import-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、べき等性トークンを使用して、指定された Amazon S3 バケットから Amazon EC2 にシングルディスク仮想マシンイメージをインポートします。この例では、「VM Import Prequisites」トピックで説明されているように、デフォルトの名前が「vmimport」の VM Import サービスロールが存在し、指定されたバケットへの Amazon EC2 アクセスを許可するポリシーが付与されている必要があります。カスタムロールを使用するには、`-RoleName` パラメータを使用してロール名を指定します。**  

```
$container = New-Object Amazon.EC2.Model.ImageDiskContainer
$container.Format="VMDK"
$container.UserBucket = New-Object Amazon.EC2.Model.UserBucket
$container.UserBucket.S3Bucket = "amzn-s3-demo-bucket"
$container.UserBucket.S3Key = "Win_2008_Server_Standard_SP2_64-bit-disk1.vmdk"

$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Windows 2008 Standard Image Import"
    "Platform"="Windows"
    "LicenseType"="AWS"
}

Import-EC2Image -DiskContainer $container @parms
```
**出力:**  

```
Architecture    : 
Description     : Windows 2008 Standard Image
Hypervisor      : 
ImageId         : 
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        : 2
SnapshotDetails : {}
Status          : active
StatusMessage   : pending
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ImportImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Import-EC2KeyPair`
<a name="ec2_ImportKeyPair_powershell_4_topic"></a>

次のコード例は、`Import-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パブリックキーを EC2 にインポートします。最初の行は、パブリックキーファイル (\$1.pub) の内容を変数 `$publickey` に保存します。次に、パブリックキーファイルの UTF8 形式を Base64 でエンコードされた文字列に変換し、変換された文字列を変数 `$pkbase64` に保存します。最後の行では、変換されたパブリックキーが EC2 にインポートされます。コマンドレットは、キーフィンガープリントと名前を結果として返します。**  

```
$publickey=[Io.File]::ReadAllText("C:\Users\TestUser\.ssh\id_rsa.pub")
$pkbase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($publickey))
Import-EC2KeyPair -KeyName Example-user-key -PublicKey $pkbase64
```
**出力:**  

```
KeyFingerprint                                  KeyName
--------------                                  -------
do:d0:15:8f:79:97:12:be:00:fd:df:31:z3:b1:42:z1 Example-user-key
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ImportKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Import-EC2Snapshot`
<a name="ec2_ImportSnapshot_powershell_4_topic"></a>

次のコード例は、`Import-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「VMDK」形式の VM ディスクイメージを Amazon EBS スナップショットにインポートします。この例では、http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/VMImportPrerequisites.html の `VM Import Prequisites` トピックで説明されているように、デフォルトの名前が「vmimport」の VM Import サービスロールと、指定されたバケットへの Amazon EC2 アクセスを許可するポリシーが必要です。カスタムロールを使用するには、`-RoleName` パラメータを使用してロール名を指定します。**  

```
$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Disk Image Import"
    "DiskContainer_Description" = "Data disk"
    "DiskContainer_Format" = "VMDK"
    "DiskContainer_S3Bucket" = "amzn-s3-demo-bucket"
    "DiskContainer_S3Key" = "datadiskimage.vmdk"
}

Import-EC2Snapshot @parms
```
**出力:**  

```
Description            ImportTaskId               SnapshotTaskDetail                                                          
-----------------      --------------------       ------------------                                                          
Disk Image Import      import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ImportSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Move-EC2AddressToVpc`
<a name="ec2_MoveAddressToVpc_powershell_4_topic"></a>

次のコード例は、`Move-EC2AddressToVpc` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パブリック IP アドレスが 12.345.67.89 の EC2 インスタンスを、米国東部 (バージニア北部) リージョンの EC2-VPC プラットフォームに移動します。**  

```
Move-EC2AddressToVpc -PublicIp 12.345.67.89 -Region us-east-1
```
**例 2: この例では、Get-EC2Instance コマンドの結果を Move-EC2AddressToVpc コマンドレットにパイプします。Get-EC2Instance コマンドは、インスタンス ID で指定されたインスタンスを取得し、インスタンスのパブリック IP アドレスプロパティを返します。**  

```
(Get-EC2Instance -Instance i-12345678).Instances.PublicIpAddress | Move-EC2AddressToVpc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)*の「[MoveAddressToVpc](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Address`
<a name="ec2_AllocateAddress_powershell_4_topic"></a>

次のコード例は、`New-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、VPC 内のインスタンスで使用する Elastic IP アドレスを割り当てます。**  

```
New-EC2Address -Domain Vpc
```
**出力:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
eipalloc-12345678    vpc         198.51.100.2
```
**例 2: この例では、EC2-Classic のインスタンスで使用する Elastic IP アドレスを割り当てます。**  

```
New-EC2Address
```
**出力:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
                     standard    203.0.113.17
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AllocateAddress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2CustomerGateway`
<a name="ec2_CreateCustomerGateway_powershell_4_topic"></a>

次のコード例は、`New-EC2CustomerGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたカスタマーゲートウェイを作成します。**  

```
New-EC2CustomerGateway -Type ipsec.1 -PublicIp 203.0.113.12 -BgpAsn 65534
```
**出力:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateCustomerGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2DhcpOption`
<a name="ec2_CreateDhcpOptions_powershell_4_topic"></a>

次のコード例は、`New-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された DHCP オプションのセットを作成します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$options = @( @{Key="domain-name";Values=@("abc.local")}, @{Key="domain-name-servers";Values=@("10.0.0.101","10.0.0.102")})
New-EC2DhcpOption -DhcpConfiguration $options
```
**出力:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して各 DHCP オプションを作成する必要があります。**  

```
$option1 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option1.Key = "domain-name"
$option1.Values = "abc.local"

$option2 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option2.Key = "domain-name-servers"
$option2.Values = @("10.0.0.101","10.0.0.102")

New-EC2DhcpOption -DhcpConfiguration @($option1, $option2)
```
**出力:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2FlowLog`
<a name="ec2_CreateFlowLogs_powershell_4_topic"></a>

次のコード例は、`New-EC2FlowLog` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「Admin」ロールの権限を使用して、サブネット subnet-1d234567 に対する EC2 フローログを、すべての「REJECT」トラフィックを対象に、「subnet1-log」という名前の cloud-watch-log に作成します。**  

```
New-EC2FlowLog -ResourceId "subnet-1d234567" -LogDestinationType cloud-watch-logs -LogGroupName subnet1-log -TrafficType "REJECT" -ResourceType Subnet -DeliverLogsPermissionArn "arn:aws:iam::98765432109:role/Admin"
```
**出力:**  

```
ClientToken                                  FlowLogIds             Unsuccessful
-----------                                  ----------             ------------
m1VN2cxP3iB4qo//VUKl5EU6cF7gQLOxcqNefvjeTGw= {fl-012fc34eed5678c9d} {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateFlowLogs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Host`
<a name="ec2_AllocateHosts_powershell_4_topic"></a>

次のコード例は、`New-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスタイプとアベイラビリティーゾーンのアカウントに専有ホストを割り当てます。**  

```
New-EC2Host -AutoPlacement on -AvailabilityZone eu-west-1b -InstanceType m4.xlarge -Quantity 1
```
**出力:**  

```
h-01e23f4cd567890f3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AllocateHosts](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2HostReservation`
<a name="ec2_PurchaseHostReservation_powershell_4_topic"></a>

次のコード例は、`New-EC2HostReservation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、専有ホスト h-01e23f4cd567890f1 の構成と一致する設定で、hro-0c1f23456789d0ab の予約サービスを購入します。**  

```
New-EC2HostReservation -OfferingId hro-0c1f23456789d0ab HostIdSet h-01e23f4cd567890f1
```
**出力:**  

```
ClientToken       :
CurrencyCode      :
Purchase          : {hr-0123f4b5d67bedc89}
TotalHourlyPrice  : 1.307
TotalUpfrontPrice : 0.000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PurchaseHostReservation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Image`
<a name="ec2_CreateImage_powershell_4_topic"></a>

次のコード例は、`New-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスから、指定された名前と説明を持つ AMI を作成します。Amazon EC2 は、イメージを作成する前にインスタンスのクリーンシャットダウンを試み、完了時にインスタンスを再起動します。**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI"
```
**例 2: この例では、指定されたインスタンスから、指定された名前と説明を持つ AMI を作成します。Amazon EC2 は、インスタンスのシャットダウンと再起動をせずにイメージを作成するため、作成されたイメージのファイルシステムの整合性は保証されません。**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -NoReboot $true
```
**例 3: この例では、3 つのボリュームを持つ AMI を作成します。最初のボリュームは Amazon EBS スナップショットに基づいています。2 番目のボリュームは空の 100 GiB Amazon EBS ボリュームです。3 番目のボリュームはインスタンスストアボリュームです。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ebsBlock1 = @{SnapshotId="snap-1a2b3c4d"}
$ebsBlock2 = @{VolumeSize=100}

New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -BlockDeviceMapping @( @{DeviceName="/dev/sdf";Ebs=$ebsBlock1}, @{DeviceName="/dev/sdg";Ebs=$ebsBlock2}, @{DeviceName="/dev/sdc";VirtualName="ephemeral0"})
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Instance`
<a name="ec2_RunInstances_powershell_4_topic"></a>

次のコード例は、`New-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2-Classic またはデフォルトの VPC で指定された AMI の単一のインスタンスを起動します。**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -InstanceType m3.medium -KeyName my-key-pair -SecurityGroup my-security-group
```
**例 2: この例では、VPC で指定された AMI の単一のインスタンスを起動します。**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -SubnetId subnet-12345678 -InstanceType t2.micro -KeyName my-key-pair -SecurityGroupId sg-12345678
```
**例 3: EBS ボリュームまたはインスタンスストアボリュームを追加するには、ブロックデバイスマッピングを定義してコマンドに追加します。この例では、インスタンスストアボリュームとして追加します。**  

```
$bdm = New-Object Amazon.EC2.Model.BlockDeviceMapping
$bdm.VirtualName = "ephemeral0"
$bdm.DeviceName = "/dev/sdf"

New-EC2Instance -ImageId ami-12345678 -BlockDeviceMapping $bdm ...
```
**例 4: 現在の Windows AMI のいずれかを指定するには、Get-EC2ImageByName を使用して AMI ID を取得します。この例では、Windows Server 2016 の現在のベース AMI からインスタンスを起動します。**  

```
$ami = Get-EC2ImageByName WINDOWS_2016_BASE

New-EC2Instance -ImageId $ami.ImageId ...
```
**例 5: 指定された専有ホスト環境でインスタンスを起動します。**  

```
New-EC2Instance -ImageId ami-1a2b3c4d -InstanceType m4.large -KeyName my-key-pair -SecurityGroupId sg-1a2b3c4d  -AvailabilityZone us-west-1a -Tenancy host -HostID h-1a2b3c4d5e6f1a2b3
```
**例 6: このリクエストは 2 つのインスタンスを起動し、ウェブサーバーのキーと本番稼働用の値を持つタグをインスタンスに適用します。リクエストは、作成されたボリューム (この場合は各インスタンスのルートボリューム) に、コストセンターのキーと cc123 の値を持つタグも適用します。**  

```
$tag1 = @{ Key="webserver"; Value="production" }
$tag2 = @{ Key="cost-center"; Value="cc123" }

$tagspec1 = new-object Amazon.EC2.Model.TagSpecification
$tagspec1.ResourceType = "instance"
$tagspec1.Tags.Add($tag1)

$tagspec2 = new-object Amazon.EC2.Model.TagSpecification
$tagspec2.ResourceType = "volume"
$tagspec2.Tags.Add($tag2)

New-EC2Instance -ImageId "ami-1a2b3c4d" -KeyName "my-key-pair" -MaxCount 2 -InstanceType "t2.large" -SubnetId "subnet-1a2b3c4d" -TagSpecification $tagspec1,$tagspec2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RunInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2InstanceExportTask`
<a name="ec2_CreateInstanceExportTask_powershell_4_topic"></a>

次のコード例は、`New-EC2InstanceExportTask` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、停止したインスタンス `i-0800b00a00EXAMPLE` を仮想ハードディスク (VHD)として S3 バケット `testbucket-export-instances-2019` にエクスポートします。ターゲット環境は で`Microsoft`、インスタンスが `us-east-1` リージョンにあり、ユーザーのデフォルト AWS リージョンが us-east-1 ではないため、リージョンパラメータが追加されます。エクスポートタスクのステータスを取得するには、このコマンドの結果から `ExportTaskId` 値をコピーし、`Get-EC2ExportTask -ExportTaskId export_task_ID_from_results.` を実行します。**  

```
New-EC2InstanceExportTask -InstanceId i-0800b00a00EXAMPLE -ExportToS3Task_DiskImageFormat VHD -ExportToS3Task_S3Bucket "amzn-s3-demo-bucket" -TargetEnvironment Microsoft -Region us-east-1
```
**出力:**  

```
Description           : 
ExportTaskId          : export-i-077c73108aEXAMPLE
ExportToS3Task        : Amazon.EC2.Model.ExportToS3Task
InstanceExportDetails : Amazon.EC2.Model.InstanceExportDetails
State                 : active
StatusMessage         :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateInstanceExportTask](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2InternetGateway`
<a name="ec2_CreateInternetGateway_powershell_4_topic"></a>

次のコード例は、`New-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インターネットゲートウェイを作成します。**  

```
New-EC2InternetGateway
```
**出力:**  

```
Attachments    InternetGatewayId    Tags
-----------    -----------------    ----
{}             igw-1a2b3c4d         {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2KeyPair`
<a name="ec2_CreateKeyPair_powershell_4_topic"></a>

次のコード例は、`New-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、キーペアを作成し、指定した名前のファイルに PEM エンコードされた RSA プライベートキーをキャプチャします。PowerShell を使用している場合は、有効なキーを生成するためにエンコーディングを ascii に設定する必要があります。詳細については、「 コマンドラインインターフェイスユーザーガイド」のAmazon EC2 AWS キーペアの作成、表示、削除 (https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-keypairs.html)」を参照してください。**  

```
(New-EC2KeyPair -KeyName "my-key-pair").KeyMaterial | Out-File -Encoding ascii -FilePath C:\path\my-key-pair.pem
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2NetworkAcl`
<a name="ec2_CreateNetworkAcl_powershell_4_topic"></a>

次のコード例は、`New-EC2NetworkAcl` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した VPC に対してネットワーク ACL を作成します。**  

```
New-EC2NetworkAcl -VpcId vpc-12345678
```
**出力:**  

```
Associations : {}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {}
VpcId        : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateNetworkAcl](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2NetworkAclEntry`
<a name="ec2_CreateNetworkAclEntry_powershell_4_topic"></a>

次のコード例は、`New-EC2NetworkAclEntry` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したネットワーク ACL のエントリを作成します。このルールは、UDP ポート 53 (DNS) 上の任意の場所 (0.0.0.0/0) から任意の関連付けられたサブネットへの受信トラフィックを許可します。**  

```
New-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 0.0.0.0/0 -RuleAction allow
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateNetworkAclEntry](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2NetworkInterface`
<a name="ec2_CreateNetworkInterface_powershell_4_topic"></a>

次のコード例は、`New-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワークインターフェイスを作成します。**  

```
New-EC2NetworkInterface -SubnetId subnet-1a2b3c4d -Description "my network interface" -Group sg-12345678 -PrivateIpAddress 10.0.0.17
```
**出力:**  

```
Association        :
Attachment         :
AvailabilityZone   : us-west-2c
Description        : my network interface
Groups             : {my-security-group}
MacAddress         : 0a:72:bc:1a:cd:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-17.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.17
PrivateIpAddresses : {}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : pending
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2PlacementGroup`
<a name="ec2_CreatePlacementGroup_powershell_4_topic"></a>

次のコード例は、`New-EC2PlacementGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された名前のプレイスメントグループを作成します。**  

```
New-EC2PlacementGroup -GroupName my-placement-group -Strategy cluster
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreatePlacementGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Route`
<a name="ec2_CreateRoute_powershell_4_topic"></a>

次のコード例は、`New-EC2Route` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したルートテーブルに対してルートを作成します。ルートはすべてのトラフィックと一致し、これを指定されたインターネットゲートウェイに送信します。**  

```
New-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0 -GatewayId igw-1a2b3c4d
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateRoute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2RouteTable`
<a name="ec2_CreateRouteTable_powershell_4_topic"></a>

次のコード例は、`New-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPC に対してルートテーブルを作成します。**  

```
New-EC2RouteTable -VpcId vpc-12345678
```
**出力:**  

```
Associations    : {}
PropagatingVgws : {}
Routes          : {}
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2ScheduledInstance`
<a name="ec2_RunScheduledInstances_powershell_4_topic"></a>

次のコード例は、`New-EC2ScheduledInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定のスケジュールされたインスタンスを起動します。**  

```
New-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012 -InstanceCount 1 `
-IamInstanceProfile_Name my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType c4.large `
-LaunchSpecification_SubnetId subnet-12345678`
-LaunchSpecification_SecurityGroupId sg-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RunScheduledInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2ScheduledInstancePurchase`
<a name="ec2_PurchaseScheduledInstances_powershell_4_topic"></a>

次のコード例は、`New-EC2ScheduledInstancePurchase` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スケジュールされたインスタンスを購入します。**  

```
$request = New-Object Amazon.EC2.Model.PurchaseRequest
$request.InstanceCount = 1
$request.PurchaseToken = "eyJ2IjoiMSIsInMiOjEsImMiOi..."
New-EC2ScheduledInstancePurchase -PurchaseRequest $request
```
**出力:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PurchaseScheduledInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2SecurityGroup`
<a name="ec2_CreateSecurityGroup_powershell_4_topic"></a>

次のコード例は、`New-EC2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPC 用にセキュリティグループを作成します。**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group" -VpcId vpc-12345678
```
**出力:**  

```
sg-12345678
```
**例 2: この例では、EC2-Classic のセキュリティグループを作成します。**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group"
```
**出力:**  

```
sg-45678901
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateSecurityGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Snapshot`
<a name="ec2_CreateSnapshot_powershell_4_topic"></a>

次のコード例は、`New-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたボリュームのスナップショットを作成します。**  

```
New-EC2Snapshot -VolumeId vol-12345678 -Description "This is a test"
```
**出力:**  

```
DataEncryptionKeyId :
Description         : This is a test
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            :
SnapshotId          : snap-12345678
StartTime           : 12/22/2015 1:28:42 AM
State               : pending
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 20
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2SpotDatafeedSubscription`
<a name="ec2_CreateSpotDatafeedSubscription_powershell_4_topic"></a>

次のコード例は、`New-EC2SpotDatafeedSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スポットインスタンスのデータフィードを作成します。**  

```
New-EC2SpotDatafeedSubscription -Bucket amzn-s3-demo-bucket -Prefix spotdata
```
**出力:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Subnet`
<a name="ec2_CreateSubnet_powershell_4_topic"></a>

次のコード例は、`New-EC2Subnet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した CIDR でサブネットを作成します。**  

```
New-EC2Subnet -VpcId vpc-12345678 -CidrBlock 10.0.0.0/24
```
**出力:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : pending
SubnetId                : subnet-1a2b3c4d
Tag                     : {}
VpcId                   : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateSubnet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Tag`
<a name="ec2_CreateTags_powershell_4_topic"></a>

次のコード例は、`New-EC2Tag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したリソースに単一のタグを追加します。タグキーは「myTag」で、タグ値は「myTagValue」です。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
New-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag"; Value="myTagValue" }
```
**例 2: この例では、指定されたリソースに指定されたタグを更新または追加します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
New-EC2Tag -Resource i-12345678 -Tag @( @{ Key="myTag"; Value="newTagValue" }, @{ Key="test"; Value="anotherTagValue" } )
```
**例 3: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

New-EC2Tag -Resource i-12345678 -Tag $tag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Volume`
<a name="ec2_CreateVolume_powershell_4_topic"></a>

次のコード例は、`New-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したボリュームを作成します。**  

```
New-EC2Volume -Size 50 -AvailabilityZone us-west-2a -VolumeType gp2
```
**出力:**  

```
Attachments      : {}
AvailabilityZone : us-west-2a
CreateTime       : 12/22/2015 1:42:07 AM
Encrypted        : False
Iops             : 150
KmsKeyId         :
Size             : 50
SnapshotId       :
State            : creating
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
```
**例 2: このリクエスト例では、ボリュームを作成し、キーがスタック、値が本番環境のタグを適用します。**  

```
$tag = @{ Key="stack"; Value="production" }

$tagspec = new-object Amazon.EC2.Model.TagSpecification
$tagspec.ResourceType = "volume"
$tagspec.Tags.Add($tag)

New-EC2Volume -Size 80 -AvailabilityZone "us-west-2a" -TagSpecification $tagspec
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVolume](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2Vpc`
<a name="ec2_CreateVpc_powershell_4_topic"></a>

次のコード例は、`New-EC2Vpc` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した CIDR で VPC を作成します。Amazon VPC では、VPC 用に、デフォルトの DHCP オプションセット、メインルートテーブル、デフォルトのネットワーク ACL も作成します。**  

```
New-EC2VPC -CidrBlock 10.0.0.0/16
```
**出力:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : pending
Tags            : {}
VpcId           : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVpc](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2VpcEndpoint`
<a name="ec2_CreateVpcEndpoint_powershell_4_topic"></a>

次のコード例は、`New-EC2VpcEndpoint` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、VPC vpc-0fc1ff23f45b678eb でサービス com.amazonaws.eu-west-1.s3 の新しい VPC エンドポイントを作成します。**  

```
New-EC2VpcEndpoint -ServiceName com.amazonaws.eu-west-1.s3 -VpcId vpc-0fc1ff23f45b678eb
```
**出力:**  

```
ClientToken VpcEndpoint
----------- -----------
            Amazon.EC2.Model.VpcEndpoint
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVpcEndpoint](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2VpnConnection`
<a name="ec2_CreateVpnConnection_powershell_4_topic"></a>

次のコード例は、`New-EC2VpnConnection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した仮想プライベートゲートウェイと指定したカスタマーゲートウェイの間に VPN 接続を作成します。出力には、ネットワーク管理者が必要とする設定情報が XML 形式で含まれます。**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d
```
**出力:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      :
Routes                       : {}
State                        : pending
Tags                         : {}
Type                         :
VgwTelemetry                 : {}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**例 2: この例では、VPN 接続を作成し、指定された名前のファイルに設定をキャプチャします。**  

```
(New-EC2VpnConnection -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d).CustomerGatewayConfiguration | Out-File C:\path\vpn-configuration.xml
```
**例 3: この例では、指定された仮想プライベートゲートウェイと指定されたカスタマーゲートウェイの間に VPN 接続を作成します。**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d -Options_StaticRoutesOnly $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVpnConnection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2VpnConnectionRoute`
<a name="ec2_CreateVpnConnectionRoute_powershell_4_topic"></a>

次のコード例は、`New-EC2VpnConnectionRoute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPN 接続に対して指定された静的ルートを作成します。**  

```
New-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EC2VpnGateway`
<a name="ec2_CreateVpnGateway_powershell_4_topic"></a>

次のコード例は、`New-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された仮想プライベートゲートウェイを作成します。**  

```
New-EC2VpnGateway -Type ipsec.1
```
**出力:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {}
VpnGatewayId     : vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-EC2Address`
<a name="ec2_AssociateAddress_powershell_4_topic"></a>

次のコード例は、`Register-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された Elastic IP アドレスを VPC 内の指定されたインスタンスに関連付けます。**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -AllocationId eipalloc-12345678
```
**出力:**  

```
eipassoc-12345678
```
**例 2: この例では、指定された Elastic IP アドレスを EC2-Classic の指定されたインスタンスに関連付けます。**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -PublicIp 203.0.113.17
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssociateAddress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-EC2DhcpOption`
<a name="ec2_AssociateDhcpOptions_powershell_4_topic"></a>

次のコード例は、`Register-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された DHCP オプションセットを指定された VPC に関連付けます。**  

```
Register-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d -VpcId vpc-12345678
```
**例 2: この例では、デフォルトの DHCP オプションセットを指定された VPC に関連付けます。**  

```
Register-EC2DhcpOption -DhcpOptionsId default -VpcId vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssociateDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-EC2Image`
<a name="ec2_RegisterImage_powershell_4_topic"></a>

次のコード例は、`Register-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Amazon S3 の指定されたマニフェストファイルを使用して AMI を登録します。**  

```
Register-EC2Image -ImageLocation amzn-s3-demo-bucket/my-web-server-ami/image.manifest.xml -Name my-web-server-ami
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-EC2PrivateIpAddress`
<a name="ec2_AssignPrivateIpAddresses_powershell_4_topic"></a>

次のコード例は、`Register-EC2PrivateIpAddress` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたセカンダリプライベート IP アドレスを指定されたネットワークインターフェイスに割り当てます。**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
**例 2: この例では、2 つのセカンダリプライベート IP アドレスを作成し、指定されたネットワークインターフェイスに割り当てます。**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -SecondaryPrivateIpAddressCount 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-EC2RouteTable`
<a name="ec2_AssociateRouteTable_powershell_4_topic"></a>

次のコード例は、`Register-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたルートテーブルを指定されたサブネットに関連付けます。**  

```
Register-EC2RouteTable -RouteTableId rtb-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
rtbassoc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssociateRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Address`
<a name="ec2_ReleaseAddress_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、VPC 内のインスタンスに指定された Elastic IP アドレスを解放します。**  

```
Remove-EC2Address -AllocationId eipalloc-12345678 -Force
```
**例 2: この例では、EC2-Classic のインスタンスに指定された Elastic IP アドレスを解放します。**  

```
Remove-EC2Address -PublicIp 198.51.100.2 -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReleaseAddress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2CapacityReservation`
<a name="ec2_CancelCapacityReservation_powershell_4_topic"></a>

次のコード例は、`Remove-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、キャパシティ予約 cr-0c1f2345db6f7cdba をキャンセルします。**  

```
Remove-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2CapacityReservation (CancelCapacityReservation)" on target "cr-0c1f2345db6f7cdba".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CancelCapacityReservation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2CustomerGateway`
<a name="ec2_DeleteCustomerGateway_powershell_4_topic"></a>

次のコード例は、`Remove-EC2CustomerGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたカスタマーゲートウェイを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2CustomerGateway (DeleteCustomerGateway)" on Target "cgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteCustomerGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2DhcpOption`
<a name="ec2_DeleteDhcpOptions_powershell_4_topic"></a>

次のコード例は、`Remove-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された DHCP オプションのセットを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2DhcpOption (DeleteDhcpOptions)" on Target "dopt-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteDhcpOptions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2FlowLog`
<a name="ec2_DeleteFlowLogs_powershell_4_topic"></a>

次のコード例は、`Remove-EC2FlowLog` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された FlowLogId fl-01a2b3456a789c01 を削除します。**  

```
Remove-EC2FlowLog -FlowLogId fl-01a2b3456a789c01
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2FlowLog (DeleteFlowLogs)" on target "fl-01a2b3456a789c01".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteFlowLogs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Host`
<a name="ec2_ReleaseHosts_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたホスト ID h-0badafd1dcb2f3456 を解放します。**  

```
Remove-EC2Host -HostId h-0badafd1dcb2f3456
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Host (ReleaseHosts)" on target "h-0badafd1dcb2f3456".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Successful            Unsuccessful
----------            ------------
{h-0badafd1dcb2f3456} {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReleaseHosts](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Instance`
<a name="ec2_TerminateInstances_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスを終了します (インスタンスが実行中または「停止状態」である可能性があります)。コマンドレットは、続行する前に確認を求めるプロンプトを表示します。プロンプトを表示しないようにするには、-Force スイッチを使用します。**  

```
Remove-EC2Instance -InstanceId i-12345678
```
**出力:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TerminateInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2InternetGateway`
<a name="ec2_DeleteInternetGateway_powershell_4_topic"></a>

次のコード例は、`Remove-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインターネットゲートウェイを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2InternetGateway (DeleteInternetGateway)" on Target "igw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteInternetGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2KeyPair`
<a name="ec2_DeleteKeyPair_powershell_4_topic"></a>

次のコード例は、`Remove-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したキーペアを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2KeyPair -KeyName my-key-pair
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2KeyPair (DeleteKeyPair)" on Target "my-key-pair".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteKeyPair](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2NetworkAcl`
<a name="ec2_DeleteNetworkAcl_powershell_4_topic"></a>

次のコード例は、`Remove-EC2NetworkAcl` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワーク ACL を削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2NetworkAcl -NetworkAclId acl-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAcl (DeleteNetworkAcl)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteNetworkAcl](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2NetworkAclEntry`
<a name="ec2_DeleteNetworkAclEntry_powershell_4_topic"></a>

次のコード例は、`Remove-EC2NetworkAclEntry` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワーク ACL から指定されたルールを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAclEntry (DeleteNetworkAclEntry)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteNetworkAclEntry](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2NetworkInterface`
<a name="ec2_DeleteNetworkInterface_powershell_4_topic"></a>

次のコード例は、`Remove-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワークインターフェイスを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkInterface (DeleteNetworkInterface)" on Target "eni-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteNetworkInterface](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2PlacementGroup`
<a name="ec2_DeletePlacementGroup_powershell_4_topic"></a>

次のコード例は、`Remove-EC2PlacementGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたプレイスメントグループを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2PlacementGroup -GroupName my-placement-group
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2PlacementGroup (DeletePlacementGroup)" on Target "my-placement-group".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeletePlacementGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Route`
<a name="ec2_DeleteRoute_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Route` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したルートテーブルから指定したルートを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Route (DeleteRoute)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteRoute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2RouteTable`
<a name="ec2_DeleteRouteTable_powershell_4_topic"></a>

次のコード例は、`Remove-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたルートテーブルを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2RouteTable (DeleteRouteTable)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2SecurityGroup`
<a name="ec2_DeleteSecurityGroup_powershell_4_topic"></a>

次のコード例は、`Remove-EC2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2SecurityGroup -GroupId sg-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SecurityGroup (DeleteSecurityGroup)" on Target "sg-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: この例では、EC2-Classic の指定されたセキュリティグループを削除します。**  

```
Remove-EC2SecurityGroup -GroupName my-security-group -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteSecurityGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Snapshot`
<a name="ec2_DeleteSnapshot_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: こので例は、指定したスナップショットを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Snapshot -SnapshotId snap-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Snapshot (DeleteSnapshot)" on target "snap-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteSnapshot](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2SpotDatafeedSubscription`
<a name="ec2_DeleteSpotDatafeedSubscription_powershell_4_topic"></a>

次のコード例は、`Remove-EC2SpotDatafeedSubscription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、スポットインスタンスのデータフィードを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2SpotDatafeedSubscription
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SpotDatafeedSubscription (DeleteSpotDatafeedSubscription)" on Target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Subnet`
<a name="ec2_DeleteSubnet_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Subnet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したサブネットを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Subnet (DeleteSubnet)" on Target "subnet-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteSubnet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Tag`
<a name="ec2_DeleteTags_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Tag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、タグ値に関係なく、指定されたリソースから指定されたタグを削除します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag" } -Force
```
**例 2: この例では、指定されたタグ値が一致する場合にのみ、指定されたリソースから指定されたタグを削除します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag";Value="myTagValue" } -Force
```
**例 3: この例では、タグ値に関係なく、指定されたリソースから指定されたタグを削除します。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
**例 4: この例では、指定されたタグ値が一致する場合にのみ、指定されたリソースから指定されたタグを削除します。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Volume`
<a name="ec2_DeleteVolume_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたボリュームをデタッチします。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Volume -VolumeId vol-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Volume (DeleteVolume)" on target "vol-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteVolume](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2Vpc`
<a name="ec2_DeleteVpc_powershell_4_topic"></a>

次のコード例は、`Remove-EC2Vpc` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した VPC を削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Vpc -VpcId vpc-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Vpc (DeleteVpc)" on Target "vpc-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteVpc](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2VpnConnection`
<a name="ec2_DeleteVpnConnection_powershell_4_topic"></a>

次のコード例は、`Remove-EC2VpnConnection` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPN 接続を削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnection (DeleteVpnConnection)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteVpnConnection](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2VpnConnectionRoute`
<a name="ec2_DeleteVpnConnectionRoute_powershell_4_topic"></a>

次のコード例は、`Remove-EC2VpnConnectionRoute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された VPN 接続から指定された静的ルートを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnectionRoute (DeleteVpnConnectionRoute)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EC2VpnGateway`
<a name="ec2_DeleteVpnGateway_powershell_4_topic"></a>

次のコード例は、`Remove-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された仮想プライベートゲートウェイを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnGateway (DeleteVpnGateway)" on Target "vgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteVpnGateway](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Request-EC2SpotFleet`
<a name="ec2_RequestSpotFleet_powershell_4_topic"></a>

次のコード例は、`Request-EC2SpotFleet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したインスタンスタイプが最低価格のアベイラビリティーゾーンで、スポットフリートリクエストを作成します。アカウントが EC2-VPC のみをサポートしている場合、スポットフリートは、デフォルトのサブネットが存在する、最低料金のアベイラビリティーゾーンでインスタンスを起動します。アカウントが EC2-Classic をサポートしている場合、スポットフリートは、最低料金のアベイラビリティーゾーンの EC2-Classic でインスタンスを起動します。リクエストで指定したスポット料金を超えて課金されることはありません。**  

```
$sg = New-Object Amazon.EC2.Model.GroupIdentifier
$sg.GroupId = "sg-12345678"
$lc = New-Object Amazon.EC2.Model.SpotFleetLaunchSpecification
$lc.ImageId = "ami-12345678"
$lc.InstanceType = "m3.medium"
$lc.SecurityGroups.Add($sg) 
Request-EC2SpotFleet -SpotFleetRequestConfig_SpotPrice 0.04 `
-SpotFleetRequestConfig_TargetCapacity 2 `
-SpotFleetRequestConfig_IamFleetRole arn:aws:iam::123456789012:role/my-spot-fleet-role `
-SpotFleetRequestConfig_LaunchSpecification $lc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RequestSpotFleet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Request-EC2SpotInstance`
<a name="ec2_RequestSpotInstances_powershell_4_topic"></a>

次のコード例は、`Request-EC2SpotInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたサブネットで 1 回限りのスポットインスタンスをリクエストします。セキュリティグループは、指定されたサブネットを含む VPC 用に作成する必要があり、ネットワークインターフェイスを使用して ID で指定する必要があります。ネットワークインターフェイスの指定時、ネットワークインターフェイスを使用してサブネット ID を含める必要があります。**  

```
$n = New-Object Amazon.EC2.Model.InstanceNetworkInterfaceSpecification
$n.DeviceIndex = 0
$n.SubnetId = "subnet-12345678"
$n.Groups.Add("sg-12345678")
Request-EC2SpotInstance -InstanceCount 1 -SpotPrice 0.050 -Type one-time `
-IamInstanceProfile_Arn arn:aws:iam::123456789012:instance-profile/my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType m3.medium `
-LaunchSpecification_NetworkInterface $n
```
**出力:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 12/26/2015 7:44:10 AM
Fault                    :
InstanceId               :
LaunchedAvailabilityZone :
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.050000
State                    : open
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {}
Type                     : one-time
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RequestSpotInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Reset-EC2ImageAttribute`
<a name="ec2_ResetImageAttribute_powershell_4_topic"></a>

次のコード例は、`Reset-EC2ImageAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「launchPermission」属性をデフォルト値にリセットします。デフォルトでは、AMI はプライベートです。**  

```
Reset-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResetImageAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Reset-EC2InstanceAttribute`
<a name="ec2_ResetInstanceAttribute_powershell_4_topic"></a>

次のコード例は、`Reset-EC2InstanceAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスの「sriovNetSupport」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**例 2: この例では、指定されたインスタンスの「ebsOptimized」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**例 3: この例では、指定されたインスタンスの「sourceDestCheck」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sourceDestCheck
```
**例 4: この例では、指定されたインスタンスの「disableApiTermination」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**例 5: この例では、指定されたインスタンスの「instanceInitiatedShutdownBehavior」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResetInstanceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Reset-EC2NetworkInterfaceAttribute`
<a name="ec2_ResetNetworkInterfaceAttribute_powershell_4_topic"></a>

次のコード例は、`Reset-EC2NetworkInterfaceAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワークインターフェイスの送信元/送信先チェックをリセットします。**  

```
Reset-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResetNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Reset-EC2SnapshotAttribute`
<a name="ec2_ResetSnapshotAttribute_powershell_4_topic"></a>

次のコード例は、`Reset-EC2SnapshotAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したスナップショットに指定した属性を設定します。**  

```
Reset-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResetSnapshotAttribute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Restart-EC2Instance`
<a name="ec2_RebootInstances_powershell_4_topic"></a>

次のコード例は、`Restart-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスを再起動します。**  

```
Restart-EC2Instance -InstanceId i-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RebootInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Revoke-EC2SecurityGroupEgress`
<a name="ec2_RevokeSecurityGroupEgress_powershell_4_topic"></a>

次のコード例は、`Revoke-EC2SecurityGroupEgress` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループのルールを削除します。これにより、TCP ポート 80 で指定された IP アドレス範囲へのアクセスが取り消されます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 3: この例では、TCP ポート 80 で指定されたソースセキュリティグループへのアクセスを取り消します。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RevokeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Revoke-EC2SecurityGroupIngress`
<a name="ec2_RevokeSecurityGroupIngress_powershell_4_topic"></a>

次のコード例は、`Revoke-EC2SecurityGroupIngress` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループに対して、指定されたアドレス範囲から TCP ポート 22 へのアクセスを取り消します。セキュリティグループの名前ではなく、セキュリティグループの ID を使用して、EC2-VPC のセキュリティグループを識別する必要があります。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**例 3: この例では、EC2-Classic の指定されたセキュリティグループに対して、指定されたアドレス範囲から TCP ポート 22 へのアクセスを取り消します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
**例 4: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RevokeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Send-EC2InstanceStatus`
<a name="ec2_ReportInstanceStatus_powershell_4_topic"></a>

次のコード例は、`Send-EC2InstanceStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスのステータスフィードバックを報告します。**  

```
Send-EC2InstanceStatus -Instance i-12345678 -Status impaired -ReasonCode unresponsive
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReportInstanceStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-EC2NetworkAclAssociation`
<a name="ec2_ReplaceNetworkAclAssociation_powershell_4_topic"></a>

次のコード例は、`Set-EC2NetworkAclAssociation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワーク ACL を、指定されたネットワーク ACL 関連付けを持つサブネットに関連付けます。**  

```
Set-EC2NetworkAclAssociation -NetworkAclId acl-12345678 -AssociationId aclassoc-1a2b3c4d
```
**出力:**  

```
aclassoc-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReplaceNetworkAclAssociation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-EC2NetworkAclEntry`
<a name="ec2_ReplaceNetworkAclEntry_powershell_4_topic"></a>

次のコード例は、`Set-EC2NetworkAclEntry` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワーク ACL の指定されたエントリを置き換えます。新しいルールでは、指定されたアドレスから関連付けられた任意のサブネットへのインバウンドトラフィックが許可されます。**  

```
Set-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 203.0.113.12/24 -RuleAction allow
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReplaceNetworkAclEntry](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-EC2Route`
<a name="ec2_ReplaceRoute_powershell_4_topic"></a>

次のコード例は、`Set-EC2Route` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したルートテーブルの指定したルートを置き換えます。新しいルートは、指定されたトラフィックを指定された仮想プライベートゲートウェイに送信します。**  

```
Set-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 10.0.0.0/24 -GatewayId vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReplaceRoute](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-EC2RouteTableAssociation`
<a name="ec2_ReplaceRouteTableAssociation_powershell_4_topic"></a>

次のコード例は、`Set-EC2RouteTableAssociation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたルートテーブルを、指定されたルートテーブルの関連付けを持つサブネットに関連付けます。**  

```
Set-EC2RouteTableAssociation -RouteTableId rtb-1a2b3c4d -AssociationId rtbassoc-12345678
```
**出力:**  

```
rtbassoc-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReplaceRouteTableAssociation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-EC2Instance`
<a name="ec2_StartInstances_powershell_4_topic"></a>

次のコード例は、`Start-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスを開始します。**  

```
Start-EC2Instance -InstanceId i-12345678
```
**出力:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
**例 2: この例では、指定されたインスタンスを開始します。**  

```
@("i-12345678", "i-76543210") | Start-EC2Instance
```
**例 3: この例では、現在停止しているインスタンスのセットを開始します。Get-EC2Instance によって返されるインスタンスオブジェクトは、Start-EC2Instance にパイプされます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
(Get-EC2Instance -Filter @{ Name="instance-state-name"; Values="stopped"}).Instances | Start-EC2Instance
```
**例 4: PowerShell バージョン 2 では、New-Object を使用してフィルターパラメータのフィルターを作成する必要があります。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "instance-state-name"
$filter.Values = "stopped"

(Get-EC2Instance -Filter $filter).Instances | Start-EC2Instance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-EC2InstanceMonitoring`
<a name="ec2_MonitorInstances_powershell_4_topic"></a>

次のコード例は、`Start-EC2InstanceMonitoring` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスの詳細モニタリングを有効にします。**  

```
Start-EC2InstanceMonitoring -InstanceId i-12345678
```
**出力:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[MonitorInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-EC2ImportTask`
<a name="ec2_CancelImportTask_powershell_4_topic"></a>

次のコード例は、`Stop-EC2ImportTask` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインポートタスク (スナップショットまたはイメージのインポート) をキャンセルします。必要に応じて、`-CancelReason` パラメータを使用して理由を指定できます。**  

```
Stop-EC2ImportTask -ImportTaskId import-ami-abcdefgh
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CancelImportTask](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-EC2Instance`
<a name="ec2_StopInstances_powershell_4_topic"></a>

次のコード例は、`Stop-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスを停止します。**  

```
Stop-EC2Instance -InstanceId i-12345678
```
**出力:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StopInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-EC2InstanceMonitoring`
<a name="ec2_UnmonitorInstances_powershell_4_topic"></a>

次のコード例は、`Stop-EC2InstanceMonitoring` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたインスタンスの詳細モニタリングを無効にします。**  

```
Stop-EC2InstanceMonitoring -InstanceId i-12345678
```
**出力:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UnmonitorInstances](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-EC2SpotFleetRequest`
<a name="ec2_CancelSpotFleetRequests_powershell_4_topic"></a>

次のコード例は、`Stop-EC2SpotFleetRequest` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスポットフリートリクエストをキャンセルし、関連付けられたスポットインスタンスを終了します。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $true
```
**例 2: この例では、関連付けられたスポットインスタンスを終了せずに、指定されたスポットフリートリクエストをキャンセルします。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CancelSpotFleetRequests](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-EC2SpotInstanceRequest`
<a name="ec2_CancelSpotInstanceRequests_powershell_4_topic"></a>

次のコード例は、`Stop-EC2SpotInstanceRequest` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたスポットインスタンスリクエストをキャンセルします。**  

```
Stop-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**出力:**  

```
SpotInstanceRequestId    State
---------------------    -----
sir-12345678             cancelled
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CancelSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-EC2Address`
<a name="ec2_DisassociateAddress_powershell_4_topic"></a>

次のコード例は、`Unregister-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、VPC 内の指定されたインスタンスから指定された Elastic IP アドレスの関連付けを解除します。**  

```
Unregister-EC2Address -AssociationId eipassoc-12345678
```
**例 2: この例では、EC2-Classic 内の指定されたインスタンスから指定された Elastic IP アドレスの関連付けを解除します。**  

```
Unregister-EC2Address -PublicIp 203.0.113.17
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisassociateAddress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-EC2Image`
<a name="ec2_DeregisterImage_powershell_4_topic"></a>

次のコード例は、`Unregister-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された AMI の登録を解除します。**  

```
Unregister-EC2Image -ImageId ami-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-EC2PrivateIpAddress`
<a name="ec2_UnassignPrivateIpAddresses_powershell_4_topic"></a>

次のコード例は、`Unregister-EC2PrivateIpAddress` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたネットワークインターフェイスから指定されたプライベート IP アドレスの割り当てを解除します。**  

```
Unregister-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UnassignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-EC2RouteTable`
<a name="ec2_DisassociateRouteTable_powershell_4_topic"></a>

次のコード例は、`Unregister-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ルートテーブルとサブネット間の指定された関連付けを削除します。**  

```
Unregister-EC2RouteTable -AssociationId rtbassoc-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisassociateRouteTable](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-EC2SecurityGroupRuleIngressDescription`
<a name="ec2_UpdateSecurityGroupRuleDescriptionsIngress_powershell_4_topic"></a>

次のコード例は、`Update-EC2SecurityGroupRuleIngressDescription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 進入 (受信) セキュリティグループルールの説明を更新します。**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithUpdatedDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
  "Description" = "Updated rule description"
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithUpdatedDescription
```
**例 2: 既存の進入 (受信) セキュリティグループルールの説明を削除します (リクエストでパラメータを省略)。**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithoutDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithoutDescription
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateSecurityGroupRuleDescriptionsIngress](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon ECR の例
<a name="powershell_4_ecr_code_examples"></a>

次のコード例は、Amazon ECR で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-ECRLoginCommand`
<a name="ecr_Get-ECRLoginCommand_powershell_4_topic"></a>

次のコード例は、`Get-ECRLoginCommand` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: IAM プリンシパルがアクセスできる Amazon ECR レジストリへの認証に使用できるログイン情報を含む PSObject を返します。認証トークンを取得するための呼び出しに必要な認証情報とリージョンエンドポイントは、シェルのデフォルト (`Set-AWSCredential/Set-DefaultAWSRegion` または `Initialize-AWSDefaultConfiguration` のコマンドレットによって設定される) から取得されます。Invoke-Expression で コマンドプロパティを使用すると、指定レジストリにログインしたり、返された認証情報をログインを必要とする他のツールで使用したりできます。**  

```
Get-ECRLoginCommand
```
**出力:**  

```
Username      : AWS
Password      : eyJwYXlsb2Fk...kRBVEFfS0VZIn0=
ProxyEndpoint : https://123456789012.dkr.ecr.us-west-2.amazonaws.com
Endpoint      : https://123456789012.dkr.ecr.us-west-2.amazonaws.com
ExpiresAt     : 9/26/2017 6:08:23 AM
Command       : docker login --username AWS --password eyJwYXlsb2Fk...kRBVEFfS0VZIn0= https://123456789012.dkr.ecr.us-west-2.amazonaws.com
```
**例 2: Docker ログインコマンドへの入力として使用するログイン情報を含む PSObject を取得します。IAM プリンシパルがそのレジストリにアクセスできる限り、認証する任意の Amazon ECR レジストリ URI を指定できます。**  

```
(Get-ECRLoginCommand).Password | docker login --username AWS --password-stdin 012345678910.dkr.ecr.us-east-1.amazonaws.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Get-ECRLoginCommand](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon ECS の例
<a name="powershell_4_ecs_code_examples"></a>

次のコード例は、Amazon ECS で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-ECSClusterDetail`
<a name="ecs_DescribeClusters_powershell_4_topic"></a>

次のコード例は、`Get-ECSClusterDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットでは、1 つ以上の ECS クラスターを記述します。**  

```
Get-ECSClusterDetail -Cluster "LAB-ECS-CL" -Include SETTINGS | Select-Object *
```
**出力:**  

```
LoggedAt         : 12/27/2019 9:27:41 PM
Clusters         : {LAB-ECS-CL}
Failures         : {}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 396
HttpStatusCode   : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeClusters](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ECSClusterList`
<a name="ecs_ListClusters_powershell_4_topic"></a>

次のコード例は、`Get-ECSClusterList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、既存の ECS クラスターのリストを返します。**  

```
Get-ECSClusterList
```
**出力:**  

```
arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListClusters](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ECSClusterService`
<a name="ecs_ListServices_powershell_4_topic"></a>

次のコード例は、`Get-ECSClusterService` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、デフォルトのクラスターで実行されているすべてのサービスを一覧表示します。**  

```
Get-ECSClusterService
```
**例 2: この例では、指定されたクラスターで実行されているすべてのサービスを一覧表示します。**  

```
Get-ECSClusterService -Cluster myCluster
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListServices](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ECSService`
<a name="ecs_DescribeServices_powershell_4_topic"></a>

次のコード例は、`Get-ECSService` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、デフォルトのクラスターから特定のサービスの詳細を取得する方法を示します。**  

```
Get-ECSService -Service my-hhtp-service
```
**例 2: この例では、名前付きクラスターで実行されている特定のサービスの詳細を取得する方法を示します。**  

```
Get-ECSService -Cluster myCluster -Service my-hhtp-service
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeServices](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ECSCluster`
<a name="ecs_CreateCluster_powershell_4_topic"></a>

次のコード例は、`New-ECSCluster` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは新しい Amazon ECS クラスターを作成します。**  

```
New-ECSCluster -ClusterName "LAB-ECS-CL" -Setting @{Name="containerInsights"; Value="enabled"}
```
**出力:**  

```
ActiveServicesCount               : 0
Attachments                       : {}
AttachmentsStatus                 :
CapacityProviders                 : {}
ClusterArn                        : arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
ClusterName                       : LAB-ECS-CL
DefaultCapacityProviderStrategy   : {}
PendingTasksCount                 : 0
RegisteredContainerInstancesCount : 0
RunningTasksCount                 : 0
Settings                          : {containerInsights}
Statistics                        : {}
Status                            : ACTIVE
Tags                              : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateCluster](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ECSService`
<a name="ecs_CreateService_powershell_4_topic"></a>

次のコード例は、`New-ECSService` を使用する方法を示しています。

**Tools for PowerShell V4**  
例 1: このコマンド例では、デフォルトのクラスターに「ecs-simple-service」というサービスを作成します。このサービスは `ecs-demo` タスク定義を使用し、そのタスクのインスタンスを 10 個保持します。  

```
New-ECSService -ServiceName ecs-simple-service -TaskDefinition ecs-demo -DesiredCount 10
```
例 2: このコマンド例では、デフォルトクラスター内で、ロードバランサーの背後に「ecs-simple-service」という名前のサービスを作成します。このサービスは `ecs-demo` タスク定義を使用し、そのタスクのインスタンスを 10 個保持します。  

```
$lb = @{
    LoadBalancerName = "EC2Contai-EcsElast-S06278JGSJCM"
    ContainerName = "simple-demo"
    ContainerPort = 80
}        
New-ECSService -ServiceName ecs-simple-service -TaskDefinition ecs-demo -DesiredCount 10 -LoadBalancer $lb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateService](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ECSCluster`
<a name="ecs_DeleteCluster_powershell_4_topic"></a>

次のコード例は、`Remove-ECSCluster` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、指定された ECS クラスターを削除します。削除する前に、このクラスターからすべてのコンテナインスタンスを登録解除する必要があります。**  

```
Remove-ECSCluster -Cluster "LAB-ECS"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ECSCluster (DeleteCluster)" on target "LAB-ECS".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteCluster](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ECSService`
<a name="ecs_DeleteService_powershell_4_topic"></a>

次のコード例は、`Remove-ECSService` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: デフォルトクラスターで「my-http-service」という名前のサービスを削除します。サービスを削除する前に、必要数と実行中の数が 0 である必要があります。コマンドを続行する前に確認を求められます。確認を省略するには、-Force スイッチを追加します。**  

```
Remove-ECSService -Service my-http-service
```
**例 2: 名前付きクラスターで「my-http-service」という名前のサービスを削除します。**  

```
Remove-ECSService -Cluster myCluster -Service my-http-service
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteService](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-ECSClusterSetting`
<a name="ecs_UpdateClusterSettings_powershell_4_topic"></a>

次のコード例は、`Update-ECSClusterSetting` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、ECS クラスターに使用する設定を変更します。**  

```
Update-ECSClusterSetting -Cluster "LAB-ECS-CL" -Setting @{Name="containerInsights"; Value="disabled"}
```
**出力:**  

```
ActiveServicesCount               : 0
Attachments                       : {}
AttachmentsStatus                 :
CapacityProviders                 : {}
ClusterArn                        : arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
ClusterName                       : LAB-ECS-CL
DefaultCapacityProviderStrategy   : {}
PendingTasksCount                 : 0
RegisteredContainerInstancesCount : 0
RunningTasksCount                 : 0
Settings                          : {containerInsights}
Statistics                        : {}
Status                            : ACTIVE
Tags                              : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateClusterSettings](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-ECSService`
<a name="ecs_UpdateService_powershell_4_topic"></a>

次のコード例は、`Update-ECSService` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンド例では、「my-http-service」サービスを更新して「amazon-ecs-sample」タスク定義を使用します**  

```
Update-ECSService -Service my-http-service -TaskDefinition amazon-ecs-sample
```
**例 2: このコマンド例では、`my-http-service` サービスの必要数を 10 に更新します。**  

```
Update-ECSService -Service my-http-service -DesiredCount 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateService](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon EFS の例
<a name="powershell_4_efs_code_examples"></a>

次のコード例は、Amazon EFS で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Edit-EFSMountTargetSecurityGroup`
<a name="efs_ModifyMountTargetSecurityGroups_powershell_4_topic"></a>

次のコード例は、`Edit-EFSMountTargetSecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたマウントターゲットに対して有効なセキュリティグループを更新します。「sg-xxxxxxxx」の形式で最大 5 つ指定できます。**  

```
Edit-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d -SecurityGroup sg-group1,sg-group3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EFSFileSystem`
<a name="efs_DescribeFileSystems_powershell_4_topic"></a>

次のコード例は、`Get-EFSFileSystem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: リージョン内の発信者のアカウントが所有するすべてのファイルシステムのコレクションを返します。**  

```
Get-EFSFileSystem
```
**出力:**  

```
CreationTime         : 5/26/2015 4:02:38 PM
CreationToken        : 1a2bff54-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-1a2b3c4d
LifeCycleState       : available
Name                 :
NumberOfMountTargets : 0
OwnerId              : 123456789012
SizeInBytes          : Amazon.ElasticFileSystem.Model.FileSystemSize

CreationTime         : 5/26/2015 4:06:23 PM
CreationToken        : 2b4daa14-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-4d3c2b1a
...
```
**例 2: 指定されたファイルシステムの詳細を返します。**  

```
Get-EFSFileSystem -FileSystemId fs-1a2b3c4d
```
**例 3: ファイルシステムの作成時に指定されたべき等性作成トークンを使用して、ファイルシステムの詳細を返します。**  

```
Get-EFSFileSystem -CreationToken 1a2bff54-85e0-4747-bd95-7bc172c4f555
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeFileSystems](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EFSMountTarget`
<a name="efs_DescribeMountTargets_powershell_4_topic"></a>

次のコード例は、`Get-EFSMountTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたファイルシステムに関連付けられたマウントターゲットのコレクションを返します。**  

```
Get-EFSMountTarget -FileSystemId fs-1a2b3c4d
```
**出力:**  

```
FileSystemId       : fs-1a2b3c4d
IpAddress          : 10.0.0.131
LifeCycleState     : available
MountTargetId      : fsmt-1a2b3c4d
NetworkInterfaceId : eni-1a2b3c4d
OwnerId            : 123456789012
SubnetId           : subnet-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMountTargets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EFSMountTargetSecurityGroup`
<a name="efs_DescribeMountTargetSecurityGroups_powershell_4_topic"></a>

次のコード例は、`Get-EFSMountTargetSecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: マウントターゲットに関連付けられたネットワークインターフェイスに現在割り当てられているセキュリティグループの ID を返します。**  

```
Get-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d
```
**出力:**  

```
sg-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EFSTag`
<a name="efs_DescribeTags_powershell_4_topic"></a>

次のコード例は、`Get-EFSTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたファイルシステムに現在関連付けられているタグのコレクションを返します。**  

```
Get-EFSTag -FileSystemId fs-1a2b3c4d
```
**出力:**  

```
Key         Value
---         -----
Name        My File System
tagkey1     tagvalue1
tagkey2     tagvalue2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EFSFileSystem`
<a name="efs_CreateFileSystem_powershell_4_topic"></a>

次のコード例は、`New-EFSFileSystem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 新しい空のファイルシステムを作成します。作成のべき等性を保証するために使用されるトークンは自動的に生成され、返されたオブジェクトの `CreationToken` メンバーからアクセスできます。**  

```
New-EFSFileSystem
```
**出力:**  

```
CreationTime         : 5/26/2015 4:02:38 PM
CreationToken        : 1a2bff54-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-1a2b3c4d
LifeCycleState       : creating
Name                 :
NumberOfMountTargets : 0
OwnerId              : 123456789012
SizeInBytes          : Amazon.ElasticFileSystem.Model.FileSystemSize
```
**例 2: カスタムトークンを使用して新しい空のファイルシステムを作成し、作成のべき等性を保証します。**  

```
New-EFSFileSystem -CreationToken "MyUniqueToken"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateFileSystem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EFSMountTarget`
<a name="efs_CreateMountTarget_powershell_4_topic"></a>

次のコード例は、`New-EFSMountTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ファイルシステムのマウントターゲットを新規に作成します。指定されたサブネットを使用して、マウントターゲットが作成される仮想プライベートクラウド (VPC) と、(サブネットのアドレス範囲から) 自動割り当てされる IP アドレスを決定します。割り当てられた IP アドレスを使用して、このファイルシステムを Amazon EC2 インスタンスにマウントできます。セキュリティグループが指定されていないため、ターゲット用に作成されたネットワークインターフェイスは、サブネットの VPC のデフォルトのセキュリティグループに関連付けられます。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
FileSystemId       : fs-1a2b3c4d
IpAddress          : 10.0.0.131
LifeCycleState     : creating
MountTargetId      : fsmt-1a2b3c4d
NetworkInterfaceId : eni-1a2b3c4d
OwnerId            : 123456789012
SubnetId           : subnet-1a2b3c4d
```
**例 2: 自動割り当て IP アドレスを使用して、指定されたファイルシステムの新しいマウントターゲットを作成します。マウントターゲット用に作成されたネットワークインターフェイスは、指定されたセキュリティグループに関連付けられます (「sg-xxxxxxxx」の形式で最大 5 つまで指定できます)。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d -SecurityGroup sg-group1,sg-group2,sg-group3
```
**例 3: 指定された IP アドレスを使用して、指定されたファイルシステムの新しいマウントターゲットを作成します。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d -IpAddress 10.0.0.131
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateMountTarget](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EFSTag`
<a name="efs_CreateTags_powershell_4_topic"></a>

次のコード例は、`New-EFSTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定ファイルシステムにタグのコレクションを適用します。指定キーを持つタグが既にファイルシステムに存在する場合、タグの値は更新されます。**  

```
New-EFSTag -FileSystemId fs-1a2b3c4d -Tag @{Key="tagkey1";Value="tagvalue1"},@{Key="tagkey2";Value="tagvalue2"}
```
**例 2: 指定ファイルシステムの名前タグを設定します。この値は、Get-EFSFileSystem コマンドレットを使用するときに、他のファイルシステムの詳細とともに返されます。**  

```
New-EFSTag -FileSystemId fs-1a2b3c4d -Tag @{Key="Name";Value="My File System"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EFSFileSystem`
<a name="efs_DeleteFileSystem_powershell_4_topic"></a>

次のコード例は、`Remove-EFSFileSystem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 使用されなくなった指定されたファイルシステムを削除します (ファイルシステムにマウントターゲットがある場合は、最初に削除する必要があります)。コマンドレットが続行される前に確認を求めるプロンプトが表示されます。プロンプトを表示しないようにするには、`-Force` スイッチを使用します。**  

```
Remove-EFSFileSystem -FileSystemId fs-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteFileSystem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EFSMountTarget`
<a name="efs_DeleteMountTarget_powershell_4_topic"></a>

次のコード例は、`Remove-EFSMountTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたマウントターゲットを削除します。操作を続行する前に確認画面が表示されます。プロンプトを表示しないようにするには、`-Force` スイッチを使用します。このオペレーションでは、ターゲットを介してファイルシステムのマウントが強制的に中断されることに注意してください。可能であれば、このコマンドを実行する前にファイルシステムのアンマウントを検討してください。**  

```
Remove-EFSMountTarget -MountTargetId fsmt-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteMountTarget](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EFSTag`
<a name="efs_DeleteTags_powershell_4_topic"></a>

次のコード例は、`Remove-EFSTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ファイルシステムから 1 つ以上のタグのコレクションを削除します。コマンドレットが続行される前に確認を求めるプロンプトが表示されます。プロンプトを表示しないようにするには、`-Force` スイッチを使用します。**  

```
Remove-EFSTag -FileSystemId fs-1a2b3c4d -TagKey "tagkey1","tagkey2"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon EKS の例
<a name="powershell_4_eks_code_examples"></a>

次のコード例は、Amazon EKS で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-EKSResourceTag`
<a name="eks_TagResource_powershell_4_topic"></a>

次のコード例は、`Add-EKSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、指定されたタグを、指定された resourceArn を持つリソースに関連付けます。**  

```
Add-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD" -Tag @{Name = "EKSPRODCLUSTER"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSCluster`
<a name="eks_DescribeCluster_powershell_4_topic"></a>

次のコード例は、`Get-EKSCluster` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS クラスターに関する詳細情報を返します。**  

```
Get-EKSCluster -Name "PROD"
```
**出力:**  

```
Arn                  : arn:aws:eks:us-west-2:012345678912:cluster/PROD
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/25/2019 6:46:17 AM
Endpoint             : https://669608765450FBBE54D1D78A3D71B72C.gr8.us-west-2.eks.amazonaws.com
Identity             : Amazon.EKS.Model.Identity
Logging              : Amazon.EKS.Model.Logging
Name                 : PROD
PlatformVersion      : eks.7
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678912:role/eks-iam-role
Status               : ACTIVE
Tags                 : {}
Version              : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeCluster](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSClusterList`
<a name="eks_ListClusters_powershell_4_topic"></a>

次のコード例は、`Get-EKSClusterList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、指定されたリージョン AWS アカウント の の Amazon EKS クラスターを一覧表示します。**  

```
Get-EKSClusterList
```
**出力:**  

```
 PROD
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListClusters](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSFargateProfile`
<a name="eks_DescribeFargateProfile_powershell_4_topic"></a>

次のコード例は、`Get-EKSFargateProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、 AWS Fargate プロファイルに関する説明情報を返します。**  

```
Get-EKSFargateProfile -FargateProfileName "EKSFargate" -ClusterName "TEST"
```
**出力:**  

```
ClusterName         : TEST
CreatedAt           : 12/26/2019 12:34:47 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargate/42b7a119-e16b-a279-ce97-bdf303adec92
FargateProfileName  : EKSFargate
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : ACTIVE
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeFargateProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSFargateProfileList`
<a name="eks_ListFargateProfiles_powershell_4_topic"></a>

次のコード例は、`Get-EKSFargateProfileList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、指定されたリージョンの 内の指定されたクラスターに関連付けられた AWS Fargate プロファイル AWS アカウント を一覧表示します。**  

```
Get-EKSFargateProfileList -ClusterName "TEST"
```
**出力:**  

```
EKSFargate
EKSFargateProfile
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListFargateProfiles](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSNodegroup`
<a name="eks_DescribeNodegroup_powershell_4_topic"></a>

次のコード例は、`Get-EKSNodegroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS ノードグループに関する詳細情報を返します。**  

```
Get-EKSNodegroup -NodegroupName "ProdEKSNodeGroup" -ClusterName "PROD"
```
**出力:**  

```
AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 10:16:45 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      :
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : CREATING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeNodegroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSNodegroupList`
<a name="eks_ListNodegroups_powershell_4_topic"></a>

次のコード例は、`Get-EKSNodegroupList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、指定されたリージョンの 内の指定されたクラスターに関連付けられた Amazon EKS ノードグループ AWS アカウント を一覧表示します。 **  

```
Get-EKSNodegroupList -ClusterName PROD
```
**出力:**  

```
 ProdEKSNodeGroup
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListNodegroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSResourceTag`
<a name="eks_ListTagsForResource_powershell_4_topic"></a>

次のコード例は、`Get-EKSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS リソースのタグを一覧表示します。 **  

```
Get-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD"
```
**出力:**  

```
Key  Value
---  -----
Name EKSPRODCLUSTER
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSUpdate`
<a name="eks_DescribeUpdate_powershell_4_topic"></a>

次のコード例は、`Get-EKSUpdate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS クラスターまたは関連するマネージドノードグループに対する更新に関する詳細情報を返します。**  

```
Get-EKSUpdate -Name "PROD" -UpdateId "ee708232-7d2e-4ed7-9270-d0b5176f0726"
```
**出力:**  

```
CreatedAt : 12/25/2019 5:03:07 PM
Errors    : {}
Id        : ee708232-7d2e-4ed7-9270-d0b5176f0726
Params    : {Amazon.EKS.Model.UpdateParam}
Status    : Successful
Type      : LoggingUpdate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeUpdate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-EKSUpdateList`
<a name="eks_ListUpdates_powershell_4_topic"></a>

次のコード例は、`Get-EKSUpdateList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、指定されたリージョンの 内の Amazon EKS クラスターまたはマネージドノードグループに関連付けられた更新 AWS アカウントを一覧表示します。**  

```
Get-EKSUpdateList -Name "PROD"
```
**出力:**  

```
ee708232-7d2e-4ed7-9270-d0b5176f0726
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListUpdates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EKSCluster`
<a name="eks_CreateCluster_powershell_4_topic"></a>

次のコード例は、`New-EKSCluster` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「prod」という新しいクラスターを作成します。**  

```
New-EKSCluster -Name prod -ResourcesVpcConfig @{SubnetIds=@("subnet-0a1b2c3d","subnet-3a2b1c0d");SecurityGroupIds="sg-6979fe18"} -RoleArn "arn:aws:iam::012345678901:role/eks-service-role"
```
**出力:**  

```
Arn                  : arn:aws:eks:us-west-2:012345678901:cluster/prod
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/10/2018 9:25:31 PM
Endpoint             :
Name                 : prod
PlatformVersion      : eks.3
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678901:role/eks-service-role
Status               : CREATING
Version              : 1.10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateCluster](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EKSFargateProfile`
<a name="eks_CreateFargateProfile_powershell_4_topic"></a>

次のコード例は、`New-EKSFargateProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS クラスターの AWS Fargate プロファイルを作成します。Fargate インフラストラクチャでポッドをスケジュールできるようにするには、クラスター内に少なくとも 1 つの Fargate プロファイルが必要です。**  

```
New-EKSFargateProfile -FargateProfileName EKSFargateProfile -ClusterName TEST -Subnet "subnet-02f6ff500ff2067a0", "subnet-0cd976f08d5fbfaae" -PodExecutionRoleArn arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole -Selector @{Namespace="default"}
```
**出力:**  

```
ClusterName         : TEST
CreatedAt           : 12/26/2019 12:38:21 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargateProfile/20b7a11b-8292-41c1-bc56-ffa5e60f6224
FargateProfileName  : EKSFargateProfile
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : CREATING
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateFargateProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-EKSNodeGroup`
<a name="eks_CreateNodegroup_powershell_4_topic"></a>

次のコード例は、`New-EKSNodeGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS クラスターのマネージド型ワーカーノードグループを作成します。クラスターの現在の Kubernetes バージョンと同じクラスター対してのみノードグループを作成できます。すべてのノードグループは、クラスターのそれぞれのマイナー Kubernetes バージョンの最新の AMI リリースバージョンで作成されます。**  

```
New-EKSNodeGroup -NodeGroupName "ProdEKSNodeGroup" -AmiType "AL2_x86_64" -DiskSize 40 -ClusterName "PROD" -ScalingConfig_DesiredSize 2 -ScalingConfig_MinSize 2 -ScalingConfig_MaxSize 5 -InstanceType t3.large -NodeRole "arn:aws:iam::012345678912:role/NodeInstanceRole" -Subnet "subnet-0d1a9fff35efa7691","subnet-0a3f4928edbc224d4"
```
**出力:**  

```
AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 10:16:45 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      :
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : CREATING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateNodegroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EKSCluster`
<a name="eks_DeleteCluster_powershell_4_topic"></a>

次のコード例は、`Remove-EKSCluster` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS クラスターコントロールプレーンを削除します。**  

```
Remove-EKSCluster -Name "DEV-KUBE-CL"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSCluster (DeleteCluster)" on target "DEV-KUBE-CL".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Arn                  : arn:aws:eks:us-west-2:012345678912:cluster/DEV-KUBE-CL
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/25/2019 9:33:25 AM
Endpoint             : https://02E6D31E3E4F8C15D7BE7F58D527776A.yl4.us-west-2.eks.amazonaws.com
Identity             : Amazon.EKS.Model.Identity
Logging              : Amazon.EKS.Model.Logging
Name                 : DEV-KUBE-CL
PlatformVersion      : eks.7
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678912:role/eks-iam-role
Status               : DELETING
Tags                 : {}
Version              : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteCluster](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EKSFargateProfile`
<a name="eks_DeleteFargateProfile_powershell_4_topic"></a>

次のコード例は、`Remove-EKSFargateProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは AWS Fargate プロファイルを削除します。Fargate プロファイルを削除すると、そのプロファイルで Fargate で作成された Fargate 上で実行中のポッドは削除されます。**  

```
Remove-EKSFargateProfile -FargateProfileName "EKSFargate" -ClusterName "TEST"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSFargateProfile (DeleteFargateProfile)" on target "EKSFargate".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

ClusterName         : TEST
CreatedAt           : 12/26/2019 12:34:47 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargate/42b7a119-e16b-a279-ce97-bdf303adec92
FargateProfileName  : EKSFargate
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : DELETING
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteFargateProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EKSNodegroup`
<a name="eks_DeleteNodegroup_powershell_4_topic"></a>

次のコード例は、`Remove-EKSNodegroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、クラスターの Amazon EKS ノードグループを削除します。**  

```
Remove-EKSNodegroup -NodegroupName "ProdEKSNodeGroup" -ClusterName "PROD"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSNodegroup (DeleteNodegroup)" on target "ProdEKSNodeGroup".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 11:01:16 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      : Amazon.EKS.Model.NodegroupResources
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : DELETING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteNodegroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-EKSResourceTag`
<a name="eks_UntagResource_powershell_4_topic"></a>

次のコード例は、`Remove-EKSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、EKS リソースから指定されたタグを削除します。**  

```
Remove-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD" -TagKey "Name"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSResourceTag (UntagResource)" on target "arn:aws:eks:us-west-2:012345678912:cluster/PROD".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UntagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-EKSClusterConfig`
<a name="eks_UpdateClusterConfig_powershell_4_topic"></a>

次のコード例は、`Update-EKSClusterConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: Amazon EKS クラスター設定を更新します。更新中もクラスターは引き続き機能します。**  

```
Update-EKSClusterConfig -Name "PROD" -Logging_ClusterLogging @{Types="api","audit","authenticator","controllerManager","scheduler",Enabled="True"}
```
**出力:**  

```
CreatedAt : 12/25/2019 5:03:07 PM
Errors    : {}
Id        : ee708232-7d2e-4ed7-9270-d0b5176f0726
Params    : {Amazon.EKS.Model.UpdateParam}
Status    : InProgress
Type      : LoggingUpdate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateClusterConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-EKSClusterVersion`
<a name="eks_UpdateClusterVersion_powershell_4_topic"></a>

次のコード例は、`Update-EKSClusterVersion` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドレットは、Amazon EKS クラスターを指定された Kubernetes バージョンに更新します。更新中もクラスターは引き続き機能します。**  

```
Update-EKSClusterVersion -Name "PROD-KUBE-CL" -Version 1.14
```
**出力:**  

```
CreatedAt : 12/26/2019 9:50:37 AM
Errors    : {}
Id        : ef186eff-3b3a-4c25-bcfc-3dcdf9e898a8
Params    : {Amazon.EKS.Model.UpdateParam, Amazon.EKS.Model.UpdateParam}
Status    : InProgress
Type      : VersionUpdate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateClusterVersion](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Elastic Load Balancing - バージョン 1 の例
<a name="powershell_4_elastic-load-balancing_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 1 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ELBLoadBalancerToSubnet`
<a name="elastic-load-balancing_AttachLoadBalancerToSubnets_powershell_4_topic"></a>

次のコード例は、`Add-ELBLoadBalancerToSubnet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーに設定された一連のサブネットのセットに、指定されたサブネットを追加します。出力にはサブネットの完全なリストが含まれます。**  

```
Add-ELBLoadBalancerToSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**出力:**  

```
subnet-12345678
subnet-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachLoadBalancerToSubnets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-ELBResourceTag`
<a name="elastic-load-balancing_AddTags_powershell_4_topic"></a>

次のコード例は、`Add-ELBResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーにタグを追加します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Add-ELBResourceTag -LoadBalancerName my-load-balancer -Tag @{ Key="project";Value="lima" },@{ Key="department";Value="digital-media" }
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.ElasticLoadBalancing.Model.Tag
$tag.Key = "project"
$tag.Value = "lima"
Add-ELBResourceTag -LoadBalancerName my-load-balancer -Tag $tag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_DisableAvailabilityZonesForLoadBalancer_powershell_4_topic"></a>

次のコード例は、`Disable-ELBAvailabilityZoneForLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーからを指定されたアベイラビリティーゾーンを削除します。出力には残りのアベイラビリティーゾーンが含まれます。**  

```
Disable-ELBAvailabilityZoneForLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a
```
**出力:**  

```
us-west-2b
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Dismount-ELBLoadBalancerFromSubnet`
<a name="elastic-load-balancing_DetachLoadBalancerFromSubnets_powershell_4_topic"></a>

次のコード例は、`Dismount-ELBLoadBalancerFromSubnet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーに設定されたサブネットのセットから、指定されたサブネットを削除します。出力には残りのサブネットが含まれます。**  

```
Dismount-ELBLoadBalancerFromSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**出力:**  

```
subnet-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachLoadBalancerFromSubnets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_ModifyLoadBalancerAttributes_powershell_4_topic"></a>

次のコード例は、`Edit-ELBLoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーのクロスゾーン負荷分散を有効にします。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer -CrossZoneLoadBalancing_Enabled $true
```
**例 2: この例では、指定されたロードバランサーの Connection Draining を無効にします。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer -ConnectionDraining_Enabled $false
```
**例 3: この例では、指定されたロードバランサーのアクセスログ記録を有効にします。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer `
>> -AccessLog_Enabled $true `
>> -AccessLog_S3BucketName amzn-s3-demo-logging-bucket `
>> -AccessLog_S3BucketPrefix my-app/prod `
>> -AccessLog_EmitInterval 60
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_EnableAvailabilityZonesForLoadBalancer_powershell_4_topic"></a>

次のコード例は、`Enable-ELBAvailabilityZoneForLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアベイラビリティーゾーンを指定されたロードバランサーに追加します。出力には、アベイラビリティーゾーンの完全なリストが含まれます。**  

```
Enable-ELBAvailabilityZoneForLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a
```
**出力:**  

```
us-west-2a
us-west-2b
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELBInstanceHealth`
<a name="elastic-load-balancing_DescribeInstanceHealth_powershell_4_topic"></a>

次のコード例は、`Get-ELBInstanceHealth` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーに登録されているインスタンスの状態を記述します。**  

```
Get-ELBInstanceHealth -LoadBalancerName my-load-balancer
```
**出力:**  

```
Description                   InstanceId                    ReasonCode                    State
-----------                   ----------                    ----------                    -----
N/A                           i-87654321                    N/A                           InService
Instance has failed at lea... i-12345678                    Instance                      OutOfService
```
**例 2: この例では、指定されたロードバランサーに登録されている指定されたインスタンスの状態を記述します。**  

```
Get-ELBInstanceHealth -LoadBalancerName my-load-balancer -Instance i-12345678
```
**例 3: この例では、指定されたインスタンスの状態の完全な説明を表示します。**  

```
(Get-ELBInstanceHealth -LoadBalancerName my-load-balancer -Instance i-12345678).Description
```
**出力:**  

```
Instance has failed at least the UnhealthyThreshold number of health checks consecutively.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstanceHealth](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELBLoadBalancer`
<a name="elastic-load-balancing_DescribeLoadBalancers_powershell_4_topic"></a>

次のコード例は、`Get-ELBLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ロードバランサーの名前を一覧表示します。**  

```
Get-ELBLoadBalancer | format-table -property LoadBalancerName
```
**出力:**  

```
LoadBalancerName
----------------
my-load-balancer
my-other-load-balancer
my-internal-load-balancer
```
**例 2: この例では、指定されたロードバランサーを記述します。**  

```
Get-ELBLoadBalancer -LoadBalancerName my-load-balancer
```
**出力:**  

```
AvailabilityZones         : {us-west-2a, us-west-2b}
BackendServerDescriptions : {Amazon.ElasticLoadBalancing.Model.BackendServerDescription}
CanonicalHostedZoneName   : my-load-balancer-1234567890.us-west-2.elb.amazonaws.com
CanonicalHostedZoneNameID : Z3DZXE0EXAMPLE
CreatedTime               : 4/11/2015 12:12:45 PM
DNSName                   : my-load-balancer-1234567890.us-west-2.elb.amazonaws.com
HealthCheck               : Amazon.ElasticLoadBalancing.Model.HealthCheck
Instances                 : {i-207d9717, i-afefb49b}
ListenerDescriptions      : {Amazon.ElasticLoadBalancing.Model.ListenerDescription}
LoadBalancerName          : my-load-balancer
Policies                  : Amazon.ElasticLoadBalancing.Model.Policies
Scheme                    : internet-facing
SecurityGroups            : {sg-a61988c3}
SourceSecurityGroup       : Amazon.ElasticLoadBalancing.Model.SourceSecurityGroup
Subnets                   : {subnet-15aaab61}
VPCId                     : vpc-a01106c2
```
**例 3: この例では、現在の AWS リージョンのすべてのロードバランサーについて説明します。**  

```
Get-ELBLoadBalancer
```
**例 4: この例では、使用可能なすべての AWS リージョンのすべてのロードバランサーを記述します。**  

```
Get-AWSRegion | % { Get-ELBLoadBalancer -Region $_ }
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Get-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_DescribeLoadBalancerAttributes_powershell_4_topic"></a>

次のコード例は、`Get-ELBLoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーの属性を記述します。**  

```
Get-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer
```
**出力:**  

```
AccessLog              : Amazon.ElasticLoadBalancing.Model.AccessLog
AdditionalAttributes   : {}
ConnectionDraining     : Amazon.ElasticLoadBalancing.Model.ConnectionDraining
ConnectionSettings     : Amazon.ElasticLoadBalancing.Model.ConnectionSettings
CrossZoneLoadBalancing : Amazon.ElasticLoadBalancing.Model.CrossZoneLoadBalancing
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicies_powershell_4_topic"></a>

次のコード例は、`Get-ELBLoadBalancerPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーに関連付けられたポリシーを記述します。**  

```
Get-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer
```
**出力:**  

```
PolicyAttributeDescriptions             PolicyName                              PolicyTypeName
---------------------------             ----------                              --------------
{ProxyProtocol}                         my-ProxyProtocol-policy                 ProxyProtocolPolicyType
{CookieName}                            my-app-cookie-policy                    AppCookieStickinessPolicyType
```
**例 2: この例では、指定されたポリシーの属性を記述します。**  

```
(Get-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-ProxyProtocol-policy).PolicyAttributeDescriptions
```
**出力:**  

```
AttributeName    AttributeValue
-------------    --------------
ProxyProtocol    true
```
**例 3: この例では、サンプルポリシーを含む事前定義されたポリシーを記述します。サンプルポリシーの名前には ELBSample- プレフィックスが付いています。**  

```
Get-ELBLoadBalancerPolicy
```
**出力:**  

```
PolicyAttributeDescriptions             PolicyName                              PolicyTypeName
---------------------------             ----------                              --------------
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-05               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-03               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-02               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2014-10               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2014-01               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2011-08               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSample-ELBDefaultCipherPolicy        SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSample-OpenSSLDefaultCipherPolicy    SSLNegotiationPolicyType
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[DescribeLoadBalancerPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Get-ELBLoadBalancerPolicyType`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicyTypes_powershell_4_topic"></a>

次のコード例は、`Get-ELBLoadBalancerPolicyType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Elastic Load Balancing でサポートされているポリシータイプを取得します。**  

```
Get-ELBLoadBalancerPolicyType
```
**出力:**  

```
Description                             PolicyAttributeTypeDescriptions         PolicyTypeName
-----------                             -------------------------------         --------------
Stickiness policy with session lifet... {CookieExpirationPeriod}                LBCookieStickinessPolicyType
Policy that controls authentication ... {PublicKeyPolicyName}                   BackendServerAuthenticationPolicyType
Listener policy that defines the cip... {Protocol-SSLv2, Protocol-TLSv1, Pro... SSLNegotiationPolicyType
Policy containing a list of public k... {PublicKey}                             PublicKeyPolicyType
Stickiness policy with session lifet... {CookieName}                            AppCookieStickinessPolicyType
Policy that controls whether to incl... {ProxyProtocol}                         ProxyProtocolPolicyType
```
**例 2: この例では、指定されたポリシータイプを記述します。**  

```
Get-ELBLoadBalancerPolicyType -PolicyTypeName ProxyProtocolPolicyType
```
**出力:**  

```
Description                             PolicyAttributeTypeDescriptions         PolicyTypeName
-----------                             -------------------------------         --------------
Policy that controls whether to incl... {ProxyProtocol}                         ProxyProtocolPolicyType
```
**例 3: この例では、指定されたポリシータイプの完全な説明を表示します。**  

```
(Get-ELBLoadBalancerPolicyType -PolicyTypeName).Description
```
**出力:**  

```
Policy that controls whether to include the IP address and port of the originating request for TCP messages. 
This policy operates on TCP/SSL listeners only
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLoadBalancerPolicyTypes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELBResourceTag`
<a name="elastic-load-balancing_DescribeTags_powershell_4_topic"></a>

次のコード例は、`Get-ELBResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーのタグを一覧表示します。**  

```
Get-ELBResourceTag -LoadBalancerName @("my-load-balancer","my-internal-load-balancer")
```
**出力:**  

```
LoadBalancerName             Tags
----------------             ----
my-load-balancer             {project, department}
my-internal-load-balancer    {project, department}
```
**例 2: この例では、指定されたロードバランサーのタグを記述します。**  

```
(Get-ELBResourceTag -LoadBalancerName my-load-balancer).Tags
```
**出力:**  

```
Key           Value
---           -----
project       lima
department    digital-media
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Join-ELBSecurityGroupToLoadBalancer`
<a name="elastic-load-balancing_ApplySecurityGroupsToLoadBalancer_powershell_4_topic"></a>

次のコード例は、`Join-ELBSecurityGroupToLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーの現在のセキュリティグループを、指定されたセキュリティグループに置き換えます。**  

```
Join-ELBSecurityGroupToLoadBalancer -LoadBalancerName my-load-balancer -SecurityGroup sg-87654321
```
**出力:**  

```
sg-87654321
```
**例 2: 現在のセキュリティグループを保持し、追加のセキュリティグループを指定するには、既存のセキュリティグループと新しいセキュリティグループの両方を指定します。**  

```
Join-ELBSecurityGroupToLoadBalancer -LoadBalancerName my-load-balancer -SecurityGroup @("sg-12345678", "sg-87654321")
```
**出力:**  

```
sg-12345678
sg-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ApplySecurityGroupsToLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELBAppCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateAppCookieStickinessPolicy_powershell_4_topic"></a>

次のコード例は、`New-ELBAppCookieStickinessPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたアプリケーション生成 Cookie のスティッキーセッション存続期間に従うスティッキーポリシーを生成します。**  

```
New-ELBAppCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-app-cookie-policy -CookieName my-app-cookie
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAppCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELBLBCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateLbCookieStickinessPolicy_powershell_4_topic"></a>

次のコード例は、`New-ELBLBCookieStickinessPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された有効期間 (秒) によって制御されたスティッキーセッションの存続期間を持つスティッキーポリシーを生成します。**  

```
New-ELBLBCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy -CookieExpirationPeriod 60
```
**例 2: この例では、ブラウザ (user-agent) の有効期間によって制御されるスティッキーセッションの有効期間を持つスティッキーポリシーを作成します。**  

```
New-ELBLBCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLbCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELBLoadBalancer`
<a name="elastic-load-balancing_CreateLoadBalancer_powershell_4_topic"></a>

次のコード例は、`New-ELBLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、VPC に HTTP リスナーを持つロードバランサーを作成します。**  

```
$httpListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpListener.Protocol = "http"
$httpListener.LoadBalancerPort = 80
$httpListener.InstanceProtocol = "http"
$httpListener.InstancePort = 80
New-ELBLoadBalancer -LoadBalancerName my-vpc-load-balancer -SecurityGroup sg-a61988c3 -Subnet subnet-15aaab61 -Listener $httpListener

my-vpc-load-balancer-1234567890.us-west-2.elb.amazonaws.com
```
**例 2: この例では、EC2-Classic に HTTP リスナーを持つロードバランサーを作成します。**  

```
New-ELBLoadBalancer -LoadBalancerName my-classic-load-balancer -AvailabilityZone us-west-2a` -Listener $httpListener
```
**出力:**  

```
my-classic-load-balancer-123456789.us-west-2.elb.amazonaws.com
```
**例 3: この例では、HTTP リスナーを持つロードバランサーを作成します。**  

```
$httpsListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpsListener.Protocol = "https"
$httpsListener.LoadBalancerPort = 443
$httpsListener.InstanceProtocol = "http"
$httpsListener.InstancePort = 80 
$httpsListener.SSLCertificateId="arn:aws:iam::123456789012:server-certificate/my-server-cert"
New-ELBLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a -Listener $httpsListener

my-load-balancer-123456789.us-west-2.elb.amazonaws.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELBLoadBalancerListener`
<a name="elastic-load-balancing_CreateLoadBalancerListeners_powershell_4_topic"></a>

次のコード例は、`New-ELBLoadBalancerListener` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したロードバランサーに HTTPS リスナーを追加します。**  

```
$httpsListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpsListener.Protocol = "https"
$httpsListener.LoadBalancerPort = 443
$httpsListener.InstanceProtocol = "https"
$httpsListener.InstancePort = 443 
$httpsListener.SSLCertificateId="arn:aws:iam::123456789012:server-certificate/my-server-cert"
New-ELBLoadBalancerListener -LoadBalancerName my-load-balancer -Listener $httpsListener
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_CreateLoadBalancerPolicy_powershell_4_topic"></a>

次のコード例は、`New-ELBLoadBalancerPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーのプロキシプロトコルポリシーを作成します。**  

```
$attribute = New-Object Amazon.ElasticLoadBalancing.Model.PolicyAttribute -Property @{
         AttributeName="ProxyProtocol"
         AttributeValue="True"
    }
New-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-ProxyProtocol-policy -PolicyTypeName ProxyProtocolPolicyType -PolicyAttribute $attribute
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-ELBInstanceWithLoadBalancer`
<a name="elastic-load-balancing_RegisterInstancesWithLoadBalancer_powershell_4_topic"></a>

次のコード例は、`Register-ELBInstanceWithLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された EC2 インスタンスを指定されたロードバランサーに登録します。**  

```
Register-ELBInstanceWithLoadBalancer -LoadBalancerName my-load-balancer -Instance i-12345678
```
**出力:**  

```
InstanceId
----------
i-12345678
i-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterInstancesWithLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELBInstanceFromLoadBalancer`
<a name="elastic-load-balancing_DeregisterInstancesFromLoadBalancer_powershell_4_topic"></a>

次のコード例は、`Remove-ELBInstanceFromLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーから指定された EC2 インスタンスを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBInstanceFromLoadBalancer -LoadBalancerName my-load-balancer -Instance i-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBInstanceFromLoadBalancer (DeregisterInstancesFromLoadBalancer)" on Target
"Amazon.ElasticLoadBalancing.Model.Instance".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

InstanceId
----------
i-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterInstancesFromLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELBLoadBalancer`
<a name="elastic-load-balancing_DeleteLoadBalancer_powershell_4_topic"></a>

次のコード例は、`Remove-ELBLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBLoadBalancer -LoadBalancerName my-load-balancer
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancer (DeleteLoadBalancer)" on Target "my-load-balancer".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELBLoadBalancerListener`
<a name="elastic-load-balancing_DeleteLoadBalancerListeners_powershell_4_topic"></a>

次のコード例は、`Remove-ELBLoadBalancerListener` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーのポート 80 のリスナーを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBLoadBalancerListener -LoadBalancerName my-load-balancer -LoadBalancerPort 80
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancerListener (DeleteLoadBalancerListeners)" on Target "80".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DeleteLoadBalancerPolicy_powershell_4_topic"></a>

次のコード例は、`Remove-ELBLoadBalancerPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーから指定されたポリシーを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancerPolicy (DeleteLoadBalancerPolicy)" on Target "my-duration-cookie-policy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELBResourceTag`
<a name="elastic-load-balancing_RemoveTags_powershell_4_topic"></a>

次のコード例は、`Remove-ELBResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーから指定されたタグを削除します。Force パラメータを指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-ELBResourceTag -LoadBalancerName my-load-balancer -Tag @{ Key="project" }
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELBResourceTag (RemoveTags)" on target "Amazon.ElasticLoadBalancing.Model.TagKeyOnly".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.ElasticLoadBalancing.Model.TagKeyOnly
$tag.Key = "project"
Remove-ELBResourceTag -Tag $tag -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELBHealthCheck`
<a name="elastic-load-balancing_ConfigureHealthCheck_powershell_4_topic"></a>

次のコード例は、`Set-ELBHealthCheck` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーのヘルスチェック設定を構成します。**  

```
Set-ELBHealthCheck -LoadBalancerName my-load-balancer `
>> -HealthCheck_HealthyThreshold 2 `
>> -HealthCheck_UnhealthyThreshold 2 `
>> -HealthCheck_Target "HTTP:80/ping" `
>> -HealthCheck_Interval 30 `
>> -HealthCheck_Timeout 3
```
**出力:**  

```
HealthyThreshold   : 2
Interval           : 30
Target             : HTTP:80/ping
Timeout            : 3
UnhealthyThreshold : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ConfigureHealthCheck](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELBLoadBalancerListenerSSLCertificate`
<a name="elastic-load-balancing_SetLoadBalancerListenerSslCertificate_powershell_4_topic"></a>

次のコード例は、`Set-ELBLoadBalancerListenerSSLCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナーの SSL 接続を終了する証明書を置き換えます。**  

```
Set-ELBLoadBalancerListenerSSLCertificate -LoadBalancerName my-load-balancer `
>> -LoadBalancerPort 443 `
>> -SSLCertificateId "arn:aws:iam::123456789012:server-certificate/new-server-cert"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetLoadBalancerListenerSslCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELBLoadBalancerPolicyForBackendServer`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesForBackendServer_powershell_4_topic"></a>

次のコード例は、`Set-ELBLoadBalancerPolicyForBackendServer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたポートのポリシーを指定されたポリシーに置き換えます。**  

```
Set-ELBLoadBalancerPolicyForBackendServer -LoadBalancerName my-load-balancer -InstancePort 80 -PolicyName my-ProxyProtocol-policy
```
**例 2: この例では、指定されたポートに関連付けられているすべてのポリシーを削除します。**  

```
Set-ELBLoadBalancerPolicyForBackendServer -LoadBalancerName my-load-balancer -InstancePort 80
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetLoadBalancerPoliciesForBackendServer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELBLoadBalancerPolicyOfListener`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesOfListener_powershell_4_topic"></a>

次のコード例は、`Set-ELBLoadBalancerPolicyOfListener` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナーのポリシーを指定されたポリシーに置き換えます。**  

```
Set-ELBLoadBalancerPolicyOfListener -LoadBalancerName my-load-balancer -LoadBalancerPort 443 -PolicyName my-SSLNegotiation-policy
```
**例 2: この例では、指定されたリスナーに関連付けられているすべてのポリシーを削除します。**  

```
Set-ELBLoadBalancerPolicyOfListener -LoadBalancerName my-load-balancer -LoadBalancerPort 443
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetLoadBalancerPoliciesOfListener](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Elastic Load Balancing - バージョン 2 の例
<a name="powershell_4_elastic-load-balancing-v2_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 2 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_AddListenerCertificates_powershell_4_topic"></a>

次のコード例は、`Add-ELB2ListenerCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナーに証明書を追加します。**  

```
Add-ELB2ListenerCertificate -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618' -Certificate @{CertificateArn = 'arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97'}
```
**出力:**  

```
CertificateArn                                                                      IsDefault
--------------                                                                      ---------
arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97 False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddListenerCertificates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-ELB2Tag`
<a name="elastic-load-balancing-v2_AddTags_powershell_4_topic"></a>

次のコード例は、`Add-ELB2Tag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された `AWS.Tools.ElasticLoadBalancingV2` リソースに新しいタグを追加します。**  

```
Add-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Tag @{Key = 'productVersion'; Value = '1.0.0'}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-ELB2Listener`
<a name="elastic-load-balancing-v2_ModifyListener_powershell_4_topic"></a>

次のコード例は、`Edit-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナーのデフォルトアクションを固定レスポンスに変更します。**  

```
$newDefaultAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{
    "FixedResponseConfig" = @{
    "ContentType" = "text/plain"
    "MessageBody" = "Hello World"
    "StatusCode" = "200"
  }
  "Type" = [Amazon.ElasticLoadBalancingV2.ActionTypeEnum]::FixedResponse
}

Edit-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/d19f2f14974db685' -Port 8080 -DefaultAction $newDefaultAction
```
**出力:**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/d19f2f14974db685
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676
Port            : 8080
Protocol        : HTTP
SslPolicy       :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyListener](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_ModifyLoadBalancerAttributes_powershell_4_topic"></a>

次のコード例は、`Edit-ELB2LoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーの属性を変更します。**  

```
Edit-ELB2LoadBalancerAttribute -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Attribute @{Key = 'deletion_protection.enabled'; Value = 'true'}
```
**出力:**  

```
Key                                             Value
---                                             -----
deletion_protection.enabled                     true
access_logs.s3.enabled                          false
access_logs.s3.bucket
access_logs.s3.prefix
idle_timeout.timeout_seconds                    60
routing.http2.enabled                           true
routing.http.drop_invalid_header_fields.enabled false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-ELB2Rule`
<a name="elastic-load-balancing-v2_ModifyRule_powershell_4_topic"></a>

次のコード例は、`Edit-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナールール設定を変更します。**  

```
$newRuleCondition = [Amazon.ElasticLoadBalancingV2.Model.RuleCondition]@{
    "PathPatternConfig" = @{
    "Values" = "/login1","/login2","/login3" 
  }
  "Field" = "path-pattern"
}

Edit-ELB2Rule -RuleArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc' -Condition $newRuleCondition
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 10
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyRule](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_ModifyTargetGroup_powershell_4_topic"></a>

次のコード例は、`Edit-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたターゲットグループのプロパティを変更します。**  

```
Edit-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -HealthCheckIntervalSecond 60 -HealthCheckPath '/index.html' -HealthCheckPort 8080
```
**出力:**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 60
HealthCheckPath            : /index.html
HealthCheckPort            : 8080
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 5
LoadBalancerArns           : {}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970
TargetGroupName            : test-tg
TargetType                 : instance
UnhealthyThresholdCount    : 2
VpcId                      : vpc-2cfd7000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyTargetGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_ModifyTargetGroupAttributes_powershell_4_topic"></a>

次のコード例は、`Edit-ELB2TargetGroupAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたターゲットグループの deregistration\$1delay 属性を変更します。**  

```
Edit-ELB2TargetGroupAttribute -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -Attribute @{Key = 'deregistration_delay.timeout_seconds'; Value = 600}
```
**出力:**  

```
Key                                   Value
---                                   -----
stickiness.enabled                    false
deregistration_delay.timeout_seconds  600
stickiness.type                       lb_cookie
stickiness.lb_cookie.duration_seconds 86400
slow_start.duration_seconds           0
load_balancing.algorithm.type         round_robin
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2AccountLimit`
<a name="elastic-load-balancing-v2_DescribeAccountLimits_powershell_4_topic"></a>

次のコード例は、`Get-ELB2AccountLimit` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、特定のリージョンの ELB2 アカウント制限を一覧表示します。**  

```
Get-ELB2AccountLimit
```
**出力:**  

```
Max  Name
---  ----
3000 target-groups
1000 targets-per-application-load-balancer
50   listeners-per-application-load-balancer
100  rules-per-application-load-balancer
50   network-load-balancers
3000 targets-per-network-load-balancer
500  targets-per-availability-zone-per-network-load-balancer
50   listeners-per-network-load-balancer
5    condition-values-per-alb-rule
5    condition-wildcards-per-alb-rule
100  target-groups-per-application-load-balancer
5    target-groups-per-action-on-application-load-balancer
1    target-groups-per-action-on-network-load-balancer
50   application-load-balancers
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2Listener`
<a name="elastic-load-balancing-v2_DescribeListeners_powershell_4_topic"></a>

次のコード例は、`Get-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された ALB/NLB のリスナーを記述します。**  

```
Get-ELB2Listener -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**出力:**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/1dac07c21187d41e
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f
Port            : 80
Protocol        : HTTP
SslPolicy       : 

Certificates    : {Amazon.ElasticLoadBalancingV2.Model.Certificate}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f
Port            : 443
Protocol        : HTTPS
SslPolicy       : ELBSecurityPolicy-2016-08
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeListeners](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_DescribeListenerCertificates_powershell_4_topic"></a>

次のコード例は、`Get-ELB2ListenerCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナーの証明書を記述します。**  

```
Get-ELB2ListenerCertificate -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**出力:**  

```
CertificateArn                                                                      IsDefault
--------------                                                                      ---------
arn:aws:acm:us-east-1:123456789012:certificate/5fc7c092-68bf-4862-969c-22fd48b6e17c True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeListenerCertificates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_powershell_4_topic"></a>

次のコード例は、`Get-ELB2LoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定されたリージョンのすべてのロードバランサーを表示します。**  

```
Get-ELB2LoadBalancer
```
**出力:**  

```
AvailabilityZones     : {us-east-1c}
CanonicalHostedZoneId : Z26RNL4JYFTOTI
CreatedTime           : 6/22/18 11:21:50 AM
DNSName               : test-elb1234567890-238d34ad8d94bc2e.elb.us-east-1.amazonaws.com
IpAddressType         : ipv4
LoadBalancerArn       : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/test-elb1234567890/238d34ad8d94bc2e
LoadBalancerName      : test-elb1234567890
Scheme                : internet-facing
SecurityGroups        : {}
State                 : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState
Type                  : network
VpcId                 : vpc-2cf00000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_DescribeLoadBalancerAttributes_powershell_4_topic"></a>

次のコード例は、`Get-ELB2LoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定されたロードバランサーの属性を記述します。**  

```
Get-ELB2LoadBalancerAttribute -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/test-elb/238d34ad8d94bc2e'
```
**出力:**  

```
Key                               Value
---                               -----
access_logs.s3.enabled            false
load_balancing.cross_zone.enabled true
access_logs.s3.prefix             
deletion_protection.enabled       false
access_logs.s3.bucket
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2Rule`
<a name="elastic-load-balancing-v2_DescribeRules_powershell_4_topic"></a>

次のコード例は、`Get-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナー ARN のリスナールールを記述します。**  

```
Get-ELB2Rule -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 1
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/2286fff5055e0f79

Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 2
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/14e7b036567623ba

Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {}
IsDefault  : True
Priority   : default
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/853948cf3aa9b2bf
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeRules](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2SSLPolicy`
<a name="elastic-load-balancing-v2_DescribeSslPolicies_powershell_4_topic"></a>

次のコード例は、`Get-ELB2SSLPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ElasticLoadBalancingV2 で使用可能なすべてのリスナーポリシーを一覧表示します。**  

```
Get-ELB2SSLPolicy
```
**出力:**  

```
Ciphers                                                                                                           Name                                  SslProtocols
-------                                                                                                           ----                                  ------------
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-2016-08             {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-2-2017-01     {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-1-2017-01     {TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-2-Ext-2018-06 {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-2018-06          {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-2015-05             {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-0-2015-04     {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-2-Res-2019-08  {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-1-2019-08      {TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-2-2019-08      {TLSv1.2}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSslPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2Tag`
<a name="elastic-load-balancing-v2_DescribeTags_powershell_4_topic"></a>

次のコード例は、`Get-ELB2Tag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリソースのタグを一覧表示します。**  

```
Get-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**出力:**  

```
ResourceArn                                                                                    Tags
-----------                                                                                    ----
arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f {stage, internalName, version}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DescribeTargetGroups_powershell_4_topic"></a>

次のコード例は、`Get-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたターゲットグループを記述します。**  

```
Get-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**出力:**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 30
HealthCheckPath            : /
HealthCheckPort            : traffic-port
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 5
LoadBalancerArns           : {arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970
TargetGroupName            : test-tg
TargetType                 : instance
UnhealthyThresholdCount    : 2
VpcId                      : vpc-2cfd7000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTargetGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_DescribeTargetGroupAttributes_powershell_4_topic"></a>

次のコード例は、`Get-ELB2TargetGroupAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたターゲットグループの属性を記述します。**  

```
Get-ELB2TargetGroupAttribute -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**出力:**  

```
Key                                   Value
---                                   -----
stickiness.enabled                    false
deregistration_delay.timeout_seconds  300
stickiness.type                       lb_cookie
stickiness.lb_cookie.duration_seconds 86400
slow_start.duration_seconds           0
load_balancing.algorithm.type         round_robin
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ELB2TargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_powershell_4_topic"></a>

次のコード例は、`Get-ELB2TargetHealth` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたターゲットグループに存在するターゲットのヘルスステータスを返します。**  

```
Get-ELB2TargetHealth -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**出力:**  

```
HealthCheckPort Target                                                TargetHealth
--------------- ------                                                ------------
80              Amazon.ElasticLoadBalancingV2.Model.TargetDescription Amazon.ElasticLoadBalancingV2.Model.TargetHealth
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTargetHealth](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELB2Listener`
<a name="elastic-load-balancing-v2_CreateListener_powershell_4_topic"></a>

次のコード例は、`New-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたターゲットグループにトラフィックを送信するデフォルトのアクション「Forward」を持つ新しい ALB リスナーを作成します。**  

```
$defaultAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{
  ForwardConfig = @{
    TargetGroups = @(
      @{ TargetGroupArn = "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testAlbTG/3d61c2f20aa5bccb" }
    )
    TargetGroupStickinessConfig = @{
      DurationSeconds = 900
      Enabled = $true
    }
  }
  Type = "Forward"
}

New-ELB2Listener -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676' -Port 8001 -Protocol "HTTP" -DefaultAction $defaultAction
```
**出力:**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/1c84f02aec143e80
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676
Port            : 8001
Protocol        : HTTP
SslPolicy       :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateListener](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_powershell_4_topic"></a>

次のコード例は、`New-ELB2LoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、2 つのサブネットを持つインターネット向けの新しい Application Load Balancer を作成します。**  

```
New-ELB2LoadBalancer -Type application -Scheme internet-facing -IpAddressType ipv4 -Name 'New-Test-ALB' -SecurityGroup 'sg-07c3414abb8811cbd' -subnet 'subnet-c37a67a6','subnet-fc02eea0'
```
**出力:**  

```
AvailabilityZones     : {us-east-1b, us-east-1a}
CanonicalHostedZoneId : Z35SXDOTRQ7X7K
CreatedTime           : 12/28/19 2:58:03 PM
DNSName               : New-Test-ALB-1391502222.us-east-1.elb.amazonaws.com
IpAddressType         : ipv4
LoadBalancerArn       : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/New-Test-ALB/dab2e4d90eb51493
LoadBalancerName      : New-Test-ALB
Scheme                : internet-facing
SecurityGroups        : {sg-07c3414abb8811cbd}
State                 : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState
Type                  : application
VpcId                 : vpc-2cfd7000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELB2Rule`
<a name="elastic-load-balancing-v2_CreateRule_powershell_4_topic"></a>

次のコード例は、`New-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナーに対し、顧客ヘッダー値に基づいた固定レスポンスアクションを持つ新しいリスナールールを作成します。**  

```
$newRuleAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{           
  "FixedResponseConfig" = @{
    "ContentType" = "text/plain"
    "MessageBody" = "Hello World"
    "StatusCode" = "200"
  }
  "Type" = [Amazon.ElasticLoadBalancingV2.ActionTypeEnum]::FixedResponse
}

$newRuleCondition = [Amazon.ElasticLoadBalancingV2.Model.RuleCondition]@{
  "httpHeaderConfig" = @{
    "HttpHeaderName" = "customHeader"
    "Values" = "header2","header1" 
  }         
  "Field" = "http-header"
}

New-ELB2Rule -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/1c84f02aec143e80' -Action $newRuleAction -Condition $newRuleCondition -Priority 10
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 10
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateRule](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_powershell_4_topic"></a>

次のコード例は、`New-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたパラメータを使用して新しいターゲットグループを作成します。**  

```
New-ELB2TargetGroup -HealthCheckEnabled 1 -HealthCheckIntervalSeconds 30 -HealthCheckPath '/index.html' -HealthCheckPort 80 -HealthCheckTimeoutSecond 5 -HealthyThresholdCount 2 -UnhealthyThresholdCount 5 -Port 80 -Protocol 'HTTP' -TargetType instance -VpcId 'vpc-2cfd7000' -Name 'NewTargetGroup'
```
**出力:**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 30
HealthCheckPath            : /index.html
HealthCheckPort            : 80
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 2
LoadBalancerArns           : {}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/NewTargetGroup/534e484681d801bf
TargetGroupName            : NewTargetGroup
TargetType                 : instance
UnhealthyThresholdCount    : 5
VpcId                      : vpc-2cfd7000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTargetGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-ELB2Target`
<a name="elastic-load-balancing-v2_RegisterTargets_powershell_4_topic"></a>

次のコード例は、`Register-ELB2Target` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、「i-0672a4c4cdeae3111」インスタンスを指定されたターゲットグループに登録します。**  

```
Register-ELB2Target -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -Target @{Port = 80; Id = 'i-0672a4c4cdeae3111'}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterTargets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELB2Listener`
<a name="elastic-load-balancing-v2_DeleteListener_powershell_4_topic"></a>

次のコード例は、`Remove-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナーを削除します。**  

```
Remove-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Listener (DeleteListener)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
**例 2: この例では、ロードバランサーから指定されたリスナーを削除します。**  

```
Remove-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Listener (DeleteListener)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteListener](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_RemoveListenerCertificates_powershell_4_topic"></a>

次のコード例は、`Remove-ELB2ListenerCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したターゲットグループから指定した証明書を削除します。**  

```
Remove-ELB2ListenerCertificate -Certificate @{CertificateArn = 'arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97'} -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2ListenerCertificate (RemoveListenerCertificates)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveListenerCertificates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_powershell_4_topic"></a>

次のコード例は、`Remove-ELB2LoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーを削除します。**  

```
Remove-ELB2LoadBalancer -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2LoadBalancer (DeleteLoadBalancer)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELB2Rule`
<a name="elastic-load-balancing-v2_DeleteRule_powershell_4_topic"></a>

次のコード例は、`Remove-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リスナーから指定されたルールを削除します。**  

```
Remove-ELB2Rule -RuleArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/3873f123b98f7618/4b25eb10a42e33ab'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Rule (DeleteRule)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/3873f123b98f7618/4b25eb10a42e33ab".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteRule](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELB2Tag`
<a name="elastic-load-balancing-v2_RemoveTags_powershell_4_topic"></a>

次のコード例は、`Remove-ELB2Tag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたキーのタグを削除します。**  

```
Remove-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -TagKey 'productVersion'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Tag (RemoveTags)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_powershell_4_topic"></a>

次のコード例は、`Remove-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたターゲットグループを削除します。**  

```
Remove-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testsssss/4e0b6076bc6483a7'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2TargetGroup (DeleteTargetGroup)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testsssss/4e0b6076bc6483a7".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTargetGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELB2IpAddressType`
<a name="elastic-load-balancing-v2_SetIpAddressType_powershell_4_topic"></a>

次のコード例は、`Set-ELB2IpAddressType` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ロードバランサーの IP アドレスタイプを「IPv4」から「DualStack」に変更します。**  

```
Set-ELB2IpAddressType -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -IpAddressType dualstack
```
**出力:**  

```
Value
-----
dualstack
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetIpAddressType](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELB2RulePriority`
<a name="elastic-load-balancing-v2_SetRulePriorities_powershell_4_topic"></a>

次のコード例は、`Set-ELB2RulePriority` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリスナールールの優先度を変更します。**  

```
Set-ELB2RulePriority -RulePriority -RulePriority @{Priority = 11; RuleArn = 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/a4eb199fa5046f80/dbf4c6dcef3ec6f8'}
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 11
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/a4eb199fa5046f80/dbf4c6dcef3ec6f8
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetRulePriorities](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELB2SecurityGroup`
<a name="elastic-load-balancing-v2_SetSecurityGroups_powershell_4_topic"></a>

次のコード例は、`Set-ELB2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、セキュリティグループ「sg-07c3414abb8811cbd」を指定されたロードバランサーに追加します。**  

```
Set-ELB2SecurityGroup -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -SecurityGroup 'sg-07c3414abb8811cbd'
```
**出力:**  

```
sg-07c3414abb8811cbd
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetSecurityGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-ELB2Subnet`
<a name="elastic-load-balancing-v2_SetSubnets_powershell_4_topic"></a>

次のコード例は、`Set-ELB2Subnet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたロードバランサーのサブネットを変更します。**  

```
Set-ELB2Subnet -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Subnet 'subnet-7d8a0a51','subnet-c37a67a6'
```
**出力:**  

```
LoadBalancerAddresses SubnetId        ZoneName
--------------------- --------        --------
{}                    subnet-7d8a0a51 us-east-1c
{}                    subnet-c37a67a6 us-east-1b
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetSubnets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-ELB2Target`
<a name="elastic-load-balancing-v2_DeregisterTargets_powershell_4_topic"></a>

次のコード例は、`Unregister-ELB2Target` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンス「i-0672a4c4cdeae3111」を指定されたターゲットグループから登録解除します。**  

```
$targetDescription = New-Object Amazon.ElasticLoadBalancingV2.Model.TargetDescription
$targetDescription.Id = 'i-0672a4c4cdeae3111'
Unregister-ELB2Target -Target $targetDescription -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterTargets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon FSx の例
<a name="powershell_4_fsx_code_examples"></a>

次のコード例は、Amazon FSx で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-FSXResourceTag`
<a name="fsx_TagResource_powershell_4_topic"></a>

次のコード例は、`Add-FSXResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定リソースにタグを追加します。**  

```
Add-FSXResourceTag -ResourceARN "arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a" -Tag @{Key="Users";Value="Test"} -PassThru
```
**出力:**  

```
arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-FSXBackup`
<a name="fsx_DescribeBackups_powershell_4_topic"></a>

次のコード例は、`Get-FSXBackup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ファイルシステム ID に対して昨日以降に作成されたバックアップを取得します。**  

```
Get-FSXBackup -Filter @{Name="file-system-id";Values=$fsx.FileSystemId} | Where-Object CreationTime -gt (Get-Date).AddDays(-1)
```
**出力:**  

```
BackupId        : backup-01dac234e56782bcc
CreationTime    : 6/14/2019 3:35:14 AM
FailureDetails  :
FileSystem      : Amazon.FSx.Model.FileSystem
KmsKeyId        : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f1-e1234c5af123
Lifecycle       : AVAILABLE
ProgressPercent : 100
ResourceARN     : arn:aws:fsx:eu-west-1:123456789012:backup/backup-01dac234e56782bcc
Tags            : {}
Type            : AUTOMATIC
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeBackups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-FSXFileSystem`
<a name="fsx_DescribeFileSystems_powershell_4_topic"></a>

次のコード例は、`Get-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定の filesystemId の説明を返します。**  

```
Get-FSXFileSystem -FileSystemId fs-01cd23bc4bdf5678a
```
**出力:**  

```
CreationTime         : 1/17/2019 9:55:30 AM
DNSName              : fs-01cd23bc4bdf5678a.ktmsad.local
FailureDetails       :
FileSystemId         : fs-01cd23bc4bdf5678a
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-5b67-8bde-a9f0-e1234c5af678
Lifecycle            : AVAILABLE
LustreConfiguration  :
NetworkInterfaceIds  : {eni-07d1dda1322b7e209}
OwnerId              : 123456789012
ResourceARN          : arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a
StorageCapacity      : 300
SubnetIds            : {subnet-7d123456}
Tags                 : {FSx-Service}
VpcId                : vpc-41cf2b3f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeFileSystems](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-FSXResourceTagList`
<a name="fsx_ListTagsForResource_powershell_4_topic"></a>

次のコード例は、`Get-FSXResourceTagList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定リソース ARN のタグを一覧表示します。**  

```
Get-FSXResourceTagList -ResourceARN $fsx.ResourceARN
```
**出力:**  

```
Key         Value
---         -----
FSx-Service Windows
Users       Dev
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-FSXBackup`
<a name="fsx_CreateBackup_powershell_4_topic"></a>

次のコード例は、`New-FSXBackup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ファイルシステムのバックアップを作成します。**  

```
New-FSXBackup -FileSystemId fs-0b1fac2345623456ba
```
**出力:**  

```
BackupId        : backup-0b1fac2345623456ba
CreationTime    : 6/14/2019 5:37:17 PM
FailureDetails  :
FileSystem      : Amazon.FSx.Model.FileSystem
KmsKeyId        : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f3-e1234c5af678
Lifecycle       : CREATING
ProgressPercent : 0
ResourceARN     : arn:aws:fsx:eu-west-1:123456789012:backup/backup-0b1fac2345623456ba
Tags            : {}
Type            : USER_INITIATED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateBackup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-FSXFileSystem`
<a name="fsx_CreateFileSystem_powershell_4_topic"></a>

次のコード例は、`New-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定サブネットからのアクセスを許可し、1 秒あたり最大 8 メガバイトのスループットをサポートする新しい 300GB のWindows ファイルシステムを作成します。新しいファイルシステムは、指定の Microsoft Active Directory に自動的に結合されます。**  

```
New-FSXFileSystem -FileSystemType WINDOWS -StorageCapacity 300 -SubnetId subnet-1a2b3c4d5e6f -WindowsConfiguration @{ThroughputCapacity=8;ActiveDirectoryId='d-1a2b3c4d'}
```
**出力:**  

```
CreationTime         : 12/10/2018 6:06:59 PM
DNSName              : fs-abcdef01234567890.example.com
FailureDetails       :
FileSystemId         : fs-abcdef01234567890
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:us-west-2:123456789012:key/a1234567-252c-45e9-afaa-123456789abc
Lifecycle            : CREATING
LustreConfiguration  :
NetworkInterfaceIds  : {}
OwnerId              : 123456789012
ResourceARN          : arn:aws:fsx:us-west-2:123456789012:file-system/fs-abcdef01234567890
StorageCapacity      : 300
SubnetIds            : {subnet-1a2b3c4d5e6f}
Tags                 : {}
VpcId                : vpc-1a2b3c4d5e6f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateFileSystem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-FSXFileSystemFromBackup`
<a name="fsx_CreateFileSystemFromBackup_powershell_4_topic"></a>

次のコード例は、`New-FSXFileSystemFromBackup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、既存の Amazon FSx for Windows File Server バックアップから新しい Amazon FSx ファイルシステムを作成します。**  

```
New-FSXFileSystemFromBackup -BackupId $backupID -Tag @{Key="tag:Name";Value="from-manual-backup"} -SubnetId $SubnetID -SecurityGroupId $SG_ID -WindowsConfiguration @{ThroughputCapacity=8;ActiveDirectoryId=$DirectoryID}
```
**出力:**  

```
CreationTime         : 8/8/2019 12:59:58 PM
DNSName              : fs-012ff34e56789120.ktmsad.local
FailureDetails       :
FileSystemId         : fs-012ff34e56789120
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-5b67-1bde-a2f3-e4567c8a9321
Lifecycle            : CREATING
LustreConfiguration  :
NetworkInterfaceIds  : {}
OwnerId              : 933303704102
ResourceARN          : arn:aws:fsx:eu-west-1:123456789012:file-system/fs-012ff34e56789120
StorageCapacity      : 300
SubnetIds            : {subnet-fa1ae23c}
Tags                 : {tag:Name}
VpcId                : vpc-12cf3b4f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateFileSystemFromBackup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-FSXBackup`
<a name="fsx_DeleteBackup_powershell_4_topic"></a>

次のコード例は、`Remove-FSXBackup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 backup-id を削除します。**  

```
Remove-FSXBackup -BackupId $backupID
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXBackup (DeleteBackup)" on target "backup-0bbca1e2345678e12".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

BackupId                 Lifecycle
--------                 ---------
backup-0bbca1e2345678e12 DELETED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBackup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-FSXFileSystem`
<a name="fsx_DeleteFileSystem_powershell_4_topic"></a>

次のコード例は、`Remove-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 FSX ファイルシステム ID を削除します。**  

```
Remove-FSXFileSystem -FileSystemId fs-012ff34e567890120
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXFileSystem (DeleteFileSystem)" on target "fs-012ff34e567890120".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

FileSystemId         Lifecycle WindowsResponse
------------         --------- ---------------
fs-012ff34e567890120 DELETING  Amazon.FSx.Model.DeleteFileSystemWindowsResponse
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteFileSystem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-FSXResourceTag`
<a name="fsx_UntagResource_powershell_4_topic"></a>

次のコード例は、`Remove-FSXResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 FSX ファイルシステムリソース ARN のリソースタグを削除します。**  

```
Remove-FSXResourceTag -ResourceARN $FSX.ResourceARN -TagKey Users
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXResourceTag (UntagResource)" on target "arn:aws:fsx:eu-west-1:933303704102:file-system/fs-07cd45bc6bdf2674a".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UntagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-FSXFileSystem`
<a name="fsx_UpdateFileSystem_powershell_4_topic"></a>

次のコード例は、`Update-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、UpdateFileSystemWindowsConfiguration を介して FSX ファイルシステムの自動バックアップ保持日数を更新します。**  

```
$UpdateFSXWinConfig = [Amazon.FSx.Model.UpdateFileSystemWindowsConfiguration]::new()
	$UpdateFSXWinConfig.AutomaticBackupRetentionDays = 35
	Update-FSXFileSystem -FileSystemId $FSX.FileSystemId -WindowsConfiguration $UpdateFSXWinConfig
```
**出力:**  

```
CreationTime         : 1/17/2019 9:55:30 AM
DNSName              : fs-01cd23bc4bdf5678a.ktmsad.local
FailureDetails       :
FileSystemId         : fs-01cd23bc4bdf5678a
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f2-e1234c5af678
Lifecycle            : AVAILABLE
LustreConfiguration  :
NetworkInterfaceIds  : {eni-01cd23bc4bdf5678a}
OwnerId              : 933303704102
ResourceARN          : arn:aws:fsx:eu-west-1:933303704102:file-system/fs-07cd45bc6bdf2674a
StorageCapacity      : 300
SubnetIds            : {subnet-1d234567}
Tags                 : {FSx-Service}
VpcId                : vpc-23cf4b5f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateFileSystem](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon Glacier の例
<a name="powershell_4_glacier_code_examples"></a>

次のコード例は、Amazon Glacier で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-GLCJob`
<a name="glacier_DescribeJob_powershell_4_topic"></a>

次のコード例は、`Get-GLCJob` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定したジョブの詳細を返します。ジョブが正常に完了したら、Read-GCJobOutput コマンドレットを使用して、ジョブの内容 (アーカイブまたはインベントリのリスト) をローカルファイルシステムに取得できます。**  

```
Get-GLCJob -VaultName myvault -JobId "op1x...JSbthM"
```
**出力:**  

```
Action                       : ArchiveRetrieval
ArchiveId                    : o9O9j...X-TpIhQJw
ArchiveSHA256TreeHash        : 79f3ea754c02f58...dc57bf4395b
ArchiveSizeInBytes           : 38034480
Completed                    : False
CompletionDate               : 1/1/0001 12:00:00 AM
CreationDate                 : 12/13/2018 11:00:14 AM
InventoryRetrievalParameters :
InventorySizeInBytes         : 0
JobDescription               :
JobId                        : op1x...JSbthM
JobOutputPath                :
OutputLocation               :
RetrievalByteRange           : 0-38034479
SelectParameters             :
SHA256TreeHash               : 79f3ea754c02f58...dc57bf4395b
SNSTopic                     :
StatusCode                   : InProgress
StatusMessage                :
Tier                         : Standard
VaultARN                     : arn:aws:glacier:us-west-2:012345678912:vaults/test
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeJob](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-GLCVault`
<a name="glacier_CreateVault_powershell_4_topic"></a>

次のコード例は、`New-GLCVault` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ユーザーアカウント用に新しいボールトを作成します。-AccountId パラメータに値が指定されていないため、コマンドレットは現在のアカウントを示すデフォルトの「-」を使用します。**  

```
New-GLCVault -VaultName myvault
```
**出力:**  

```
/01234567812/vaults/myvault
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVault](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Read-GLCJobOutput`
<a name="glacier_GetJobOutput_powershell_4_topic"></a>

次のコード例は、`Read-GLCJobOutput` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定したジョブで取得がスケジュールされているアーカイブコンテンツをダウンロードし、コンテンツをディスク上のファイルに保存します。ダウンロード時に、チェックサムがある場合は自動的に検証されます。必要に応じて `-Select '*'` を指定すると、チェックサムを含むレスポンス全体を返すことができます。**  

```
Read-GLCJobOutput -VaultName myvault -JobId "HSWjArc...Zq2XLiW" -FilePath "c:\temp\blue.bin"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetJobOutput](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-GLCJob`
<a name="glacier_InitiateJob_powershell_4_topic"></a>

次のコード例は、`Start-GLCJob` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定したユーザー所有のボールトからアーカイブを取得するジョブを開始します。ジョブのステータスは、Get-GLCJob コマンドレットを使用して確認できます。ジョブが正常に完了したら、Read-GCJobOutput コマンドレットを使用して、アーカイブの内容をローカルファイルシステムに取得できます。**  

```
Start-GLCJob -VaultName myvault -JobType "archive-retrieval" -JobDescription "archive retrieval" -ArchiveId "o9O9j...TX-TpIhQJw"
```
**出力:**  

```
JobId            JobOutputPath Location
-----            ------------- --------
op1x...JSbthM                  /012345678912/vaults/test/jobs/op1xe...I4HqCHkSJSbthM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[InitiateJob](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-GLCArchive`
<a name="glacier_UploadArchive_powershell_4_topic"></a>

次のコード例は、`Write-GLCArchive` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定したボールトに単一のファイルをアップロードし、アーカイブ ID と計算されたチェックサムを返します。**  

```
Write-GLCArchive -VaultName myvault -FilePath c:\temp\blue.bin
```
**出力:**  

```
FilePath                    ArchiveId              Checksum
--------                    ---------              --------
C:\temp\blue.bin            o9O9jUUs...TTX-TpIhQJw 79f3e...f4395b
```
**例 2: フォルダ階層の内容を、ユーザーアカウント内の指定したボールトにアップロードします。アップロードされたファイルごとに、コマンドレットはファイル名、対応するアーカイブ ID、アーカイブの計算されたチェックサムを出力します。**  

```
Write-GLCArchive -VaultName myvault -FolderPath . -Recurse
```
**出力:**  

```
FilePath                    ArchiveId              Checksum
--------                    ---------              --------
C:\temp\blue.bin            o9O9jUUs...TTX-TpIhQJw 79f3e...f4395b
C:\temp\green.bin           qXAfOdSG...czo729UHXrw d50a1...9184b9
C:\temp\lum.bin             39aNifP3...q9nb8nZkFIg 28886...5c3e27
C:\temp\red.bin             vp7E6rU_...Ejk_HhjAxKA e05f7...4e34f5
C:\temp\Folder1\file1.txt   _eRINlip...5Sxy7dD2BaA d0d2a...c8a3ba
C:\temp\Folder2\file2.iso   -Ix3jlmu...iXiDh-XfOPA 7469e...3e86f1
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[UploadArchive](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS Glue Tools for PowerShell V4 を使用した の例
<a name="powershell_4_glue_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-GLUEJob`
<a name="glue_CreateJob_powershell_4_topic"></a>

次のコード例は、`New-GLUEJob` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 Glue AWS で新しいジョブを作成します。コマンド名の値は常に です`glueetl`。 AWS Glue は Python または Scala で記述されたジョブスクリプトの実行をサポートしています。この例では、ジョブスクリプト (MyTestGlueJob.py) は Python で記述されています。Python パラメータは `$DefArgs` 変数で指定され、ハッシュテーブルを受け入れる `DefaultArguments` パラメータで PowerShell コマンドに渡されます。`$JobParams`変数のパラメータは、 Glue API リファレンスのジョブ (https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html) トピックに記載されている CreateJob API AWS から取得されます。**  

```
$Command = New-Object Amazon.Glue.Model.JobCommand
$Command.Name = 'glueetl'
$Command.ScriptLocation = 's3://amzn-s3-demo-source-bucket/admin/MyTestGlueJob.py'
$Command

$Source = "source_test_table"
$Target = "target_test_table"
$Connections = $Source, $Target

$DefArgs = @{
     '--TempDir' = 's3://amzn-s3-demo-bucket/admin'
     '--job-bookmark-option' = 'job-bookmark-disable'
     '--job-language' = 'python'
     }
$DefArgs

$ExecutionProp = New-Object Amazon.Glue.Model.ExecutionProperty
$ExecutionProp.MaxConcurrentRuns = 1
$ExecutionProp

$JobParams = @{
    "AllocatedCapacity"    = "5"
    "Command"              = $Command
    "Connections_Connection" = $Connections
    "DefaultArguments"  = $DefArgs
    "Description"       = "This is a test"
    "ExecutionProperty" = $ExecutionProp
    "MaxRetries"        = "1"
    "Name"              = "MyOregonTestGlueJob"
    "Role"              = "Amazon-GlueServiceRoleForSSM"
    "Timeout"           = "20"
     }

New-GlueJob @JobParams
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateJob](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS Health Tools for PowerShell V4 を使用した の例
<a name="powershell_4_health_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Health。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-HLTHEvent`
<a name="health_DescribeEvents_powershell_4_topic"></a>

次のコード例は、`Get-HLTHEvent` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは AWS Personal Health Dashboard からイベントを返します。ユーザーは -Region パラメータを追加して、米国東部 (バージニア北部) リージョンでサービスに対して使用可能なイベントを表示しますが、-Filter\$1Region パラメータは、欧州 (ロンドン) および米国西部 (オレゴン) リージョン (eu-west-2 および us-west-2) でログされたイベントをフィルタリングします。-Filter\$1StartTime パラメータはイベントが開始できる時間の範囲をフィルタリングし、-Filter\$1EndTime パラメータはイベントが終了する時間の範囲をフィルタリングします。その結果、指定された -Filter\$1StartTime 範囲内で開始し、スケジュールされた -Filter\$1EndTime 範囲内で終了する RDS の定期メンテナンスイベントが表示されます。**  

```
Get-HLTHEvent -Region us-east-1 -Filter_Region "eu-west-2","us-west-2" -Filter_StartTime @{from="3/14/2019 6:30:00AM";to="3/15/2019 5:00:00PM"} -Filter_EndTime @{from="3/21/2019 7:00:00AM";to="3/21/2019 5:00:00PM"}
```
**出力:**  

```
Arn               : arn:aws:health:us-west-2::event/RDS/AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED/AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED_USW2_20190314_20190321
AvailabilityZone  : 
EndTime           : 3/21/2019 2:00:00 PM
EventTypeCategory : scheduledChange
EventTypeCode     : AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED
LastUpdatedTime   : 2/28/2019 2:26:07 PM
Region            : us-west-2
Service           : RDS
StartTime         : 3/14/2019 2:00:00 PM
StatusCode        : open
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEvents](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した IAM の例
<a name="powershell_4_iam_code_examples"></a>

次のコード例は、IAM で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-IAMClientIDToOpenIDConnectProvider`
<a name="iam_AddClientIdToOpenIdConnectProvider_powershell_4_topic"></a>

次のコード例は、`Add-IAMClientIDToOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、クライアント ID (または対象者) `my-application-ID` を `server.example.com` という名前の既存の OIDC プロバイダーに追加します。**  

```
Add-IAMClientIDToOpenIDConnectProvider -ClientID "my-application-ID" -OpenIDConnectProviderARN "arn:aws:iam::123456789012:oidc-provider/server.example.com"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddClientIdToOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-IAMRoleTag`
<a name="iam_TagRole_powershell_4_topic"></a>

次のコード例は、`Add-IAMRoleTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ID 管理サービスのロールにタグを追加します。**  

```
Add-IAMRoleTag -RoleName AdminRoleacess -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-IAMRoleToInstanceProfile`
<a name="iam_AddRoleToInstanceProfile_powershell_4_topic"></a>

次のコード例は、`Add-IAMRoleToInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、`S3Access` という名前のロールを `webserver` という名前の既存のインスタンスプロファイルに追加します。インスタンスプロファイルを作成するには、`New-IAMInstanceProfile` コマンドを使用します。このコマンドを使用してインスタンスプロファイルを作成し、ロールに関連付けると、EC2 インスタンスにアタッチできます。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile-Name` パラメータと共に使用して、新しいインスタンスを起動します。**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddRoleToInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-IAMUserTag`
<a name="iam_TagUser_powershell_4_topic"></a>

次のコード例は、`Add-IAMUserTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ID 管理サービスのユーザーにタグを追加します。**  

```
Add-IAMUserTag -UserName joe -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Add-IAMUserToGroup`
<a name="iam_AddUserToGroup_powershell_4_topic"></a>

次のコード例は、`Add-IAMUserToGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、`Bob` という名前のユーザーを `Admins` という名前のグループに追加します。**  

```
Add-IAMUserToGroup -UserName "Bob" -GroupName "Admins"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddUserToGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Disable-IAMMFADevice`
<a name="iam_DeactivateMfaDevice_powershell_4_topic"></a>

次のコード例は、`Disable-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、シリアル番号 `123456789012` を持つユーザー `Bob` に関連付けられているハードウェア MFA デバイスを無効にします。**  

```
Disable-IAMMFADevice -UserName "Bob" -SerialNumber "123456789012"
```
**例 2: このコマンドは、ARN `arn:aws:iam::210987654321:mfa/David` を持つユーザー `David` に関連付けられている仮想 MFA デバイスを無効にします。仮想 MFA デバイスはアカウントから削除されないことに注意してください。仮想デバイスはまだ存在し、`Get-IAMVirtualMFADevice` コマンドの出力に表示されます。同じユーザーに対して新しい仮想 MFA デバイスを作成する前に、`Remove-IAMVirtualMFADevice` コマンドを使用して、古い仮想 MFA デバイスを削除する必要があります。**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeactivateMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-IAMPassword`
<a name="iam_ChangePassword_powershell_4_topic"></a>

次のコード例は、`Edit-IAMPassword` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、コマンドを実行しているユーザーのパスワードを変更します。このコマンドは、IAM ユーザーのみが呼び出すことができます。 AWS アカウント (ルート) 認証情報でサインインしたときにこのコマンドが呼び出された場合、コマンドは`InvalidUserType`エラーを返します。**  

```
Edit-IAMPassword -OldPassword "MyOldP@ssw0rd" -NewPassword "MyNewP@ssw0rd"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ChangePassword](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Enable-IAMMFADevice`
<a name="iam_EnableMfaDevice_powershell_4_topic"></a>

次のコード例は、`Enable-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、シリアル番号 `987654321098` を持つハードウェア MFA デバイスを有効にし、このデバイスをユーザー `Bob` に関連付けます。また、このコマンドは、デバイスからの最初の 2 つのコードを順番に含めます。**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**例 2: この例では、仮想 MFA デバイスを作成して有効にします。最初のコマンドは仮想デバイスを作成し、そのデバイスのオブジェクト表現を変数 `$MFADevice` に返します。`.Base32StringSeed` または `QRCodePng` プロパティを使用して、ユーザーのソフトウェアアプリケーションを設定できます。最後のコマンドはデバイスをユーザー `David` に割り当て、デバイスをシリアル番号で識別します。コマンドは、仮想 MFA デバイスからの最初の 2 つのコードを順番に含める AWS ことで、デバイスを と同期します。**  

```
$MFADevice = New-IAMVirtualMFADevice -VirtualMFADeviceName "MyMFADevice"
# see example for New-IAMVirtualMFADevice to see how to configure the software program with PNG or base32 seed code
Enable-IAMMFADevice -UserName "David" -SerialNumber -SerialNumber $MFADevice.SerialNumber -AuthenticationCode1 "24681357" -AuthenticationCode2 "13572468"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[EnableMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAccessKey`
<a name="iam_ListAccessKeys_powershell_4_topic"></a>

次のコード例は、`Get-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、`Bob` という名前の IAM ユーザーのアクセスキーを一覧表示します。IAM ユーザーのシークレットアクセスキーを一覧表示できないことに注意してください。シークレットアクセスキーを紛失した場合は、`New-IAMAccessKey` コマンドレットを使用して新しいアクセスキーを作成する必要があります。**  

```
Get-IAMAccessKey -UserName "Bob"
```
**出力:**  

```
AccessKeyId                CreateDate                   Status              UserName
-----------                ----------                   ------              --------
AKIAIOSFODNN7EXAMPLE       12/3/2014 10:53:41 AM        Active              Bob
AKIAI44QH8DHBEXAMPLE       6/6/2013 8:42:26 PM          Inactive            Bob
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAccessKeys](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_powershell_4_topic"></a>

次のコード例は、`Get-IAMAccessKeyLastUsed` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたアクセスキーの所有ユーザー名と最終使用情報を返します。**  

```
Get-IAMAccessKeyLastUsed -AccessKeyId ABCDEXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAccessKeyLastUsed](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAccountAlias`
<a name="iam_ListAccountAliases_powershell_4_topic"></a>

次のコード例は、`Get-IAMAccountAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、 AWS アカウントのアカウントエイリアスを返します。**  

```
Get-IAMAccountAlias
```
**出力:**  

```
ExampleCo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAccountAliases](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAccountAuthorizationDetail`
<a name="iam_GetAccountAuthorizationDetails_powershell_4_topic"></a>

次のコード例は、`Get-IAMAccountAuthorizationDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウント内の ID に関する認可の詳細を取得し、返されたオブジェクトの要素リスト (ユーザー、グループ、ロールを含む) を表示します。例えば、`UserDetailList` プロパティには、ユーザーに関する詳細が表示されます。同様の情報は、`RoleDetailList` および `GroupDetailList` プロパティで入手可能です。**  

```
$Details=Get-IAMAccountAuthorizationDetail
$Details
```
**出力:**  

```
GroupDetailList : {Administrators, Developers, Testers, Backup}
IsTruncated     : False
Marker          : 
RoleDetailList  : {TestRole1, AdminRole, TesterRole, clirole...}
UserDetailList  : {Administrator, Bob, BackupToS3, }
```

```
$Details.UserDetailList
```
**出力:**  

```
Arn            : arn:aws:iam::123456789012:user/Administrator
CreateDate     : 10/16/2014 9:03:09 AM
GroupList      : {Administrators}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE1
UserName       : Administrator
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/Bob
CreateDate     : 4/6/2015 12:54:42 PM
GroupList      : {Developers}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE2
UserName       : bab
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/BackupToS3
CreateDate     : 1/27/2015 10:15:08 AM
GroupList      : {Backup}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE3
UserName       : BackupToS3
UserPolicyList : {BackupServicePermissionsToS3Buckets}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAccountAuthorizationDetails](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMAccountPasswordPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在のアカウントのパスワードポリシーに関する詳細を返します。アカウントのためにパスワードポリシーが定義されていない場合、コマンドは `NoSuchEntity` エラーを返します。**  

```
Get-IAMAccountPasswordPolicy
```
**出力:**  

```
AllowUsersToChangePassword : True
ExpirePasswords            : True
HardExpiry                 : False
MaxPasswordAge             : 90
MinimumPasswordLength      : 8
PasswordReusePrevention    : 20
RequireLowercaseCharacters : True
RequireNumbers             : True
RequireSymbols             : False
RequireUppercaseCharacters : True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAccountSummary`
<a name="iam_GetAccountSummary_powershell_4_topic"></a>

次のコード例は、`Get-IAMAccountSummary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウント内の現在の IAM エンティティの使用状況と現在の IAM エンティティのクォータに関する情報を返します。**  

```
Get-IAMAccountSummary
```
**出力:**  

```
Key                                        Value
Users                                      7
GroupPolicySizeQuota                       5120
PolicyVersionsInUseQuota                   10000
ServerCertificatesQuota                    20
AccountSigningCertificatesPresent          0
AccountAccessKeysPresent                   0
Groups                                     3
UsersQuota                                 5000
RolePolicySizeQuota                        10240
UserPolicySizeQuota                        2048
GroupsPerUserQuota                         10
AssumeRolePolicySizeQuota                  2048
AttachedPoliciesPerGroupQuota              2
Roles                                      9
VersionsPerPolicyQuota                     5
GroupsQuota                                100
PolicySizeQuota                            5120
Policies                                   5
RolesQuota                                 250
ServerCertificates                         0
AttachedPoliciesPerRoleQuota               2
MFADevicesInUse                            2
PoliciesQuota                              1000
AccountMFAEnabled                          1
Providers                                  2
InstanceProfilesQuota                      100
MFADevices                                 4
AccessKeysPerUserQuota                     2
AttachedPoliciesPerUserQuota               2
SigningCertificatesPerUserQuota            2
PolicyVersionsInUse                        4
InstanceProfiles                           1
...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAccountSummary](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAttachedGroupPolicyList`
<a name="iam_ListAttachedGroupPolicies_powershell_4_topic"></a>

次のコード例は、`Get-IAMAttachedGroupPolicyList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、 AWS アカウント`Admins`内の という名前の IAM グループにアタッチされている管理ポリシーの名前と ARNs を返します。グループに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMGroupPolicyList` コマンドを使用します。**  

```
Get-IAMAttachedGroupPolicyList -GroupName "Admins"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
arn:aws:iam::aws:policy/AdministratorAccess               AdministratorAccess
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAttachedGroupPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAttachedRolePolicyList`
<a name="iam_ListAttachedRolePolicies_powershell_4_topic"></a>

次のコード例は、`Get-IAMAttachedRolePolicyList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、 AWS アカウントの `SecurityAuditRole` という名前の IAM ロールにアタッチされている管理ポリシーの名前と ARN を返します。ロールに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMRolePolicyList` コマンドを使用します。**  

```
Get-IAMAttachedRolePolicyList -RoleName "SecurityAuditRole"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMAttachedUserPolicyList`
<a name="iam_ListAttachedUserPolicies_powershell_4_topic"></a>

次のコード例は、`Get-IAMAttachedUserPolicyList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、 AWS アカウント`Bob`で という名前の IAM ユーザー用の管理ポリシーの名前と ARNs を返します。IAM ユーザーに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMUserPolicyList` コマンドを使用します。**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAttachedUserPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMContextKeysForCustomPolicy`
<a name="iam_GetContextKeysForCustomPolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMContextKeysForCustomPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、提供されたポリシー JSON に含まれるすべてのコンテキストキーを取得します。複数のポリシーを指定するには、値のカンマ区切りリストとして指定できます。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForCustomPolicy -PolicyInputList $policy1,$policy2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetContextKeysForCustomPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMContextKeysForPrincipalPolicy`
<a name="iam_GetContextKeysForPrincipalPolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMContextKeysForPrincipalPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、提供されたポリシー JSON に含まれるすべてのコンテキストキーと IAM エンティティ (ユーザー/ロールなど) にアタッチされたポリシーを取得します。-PolicyInputList では、複数の値リストをカンマ区切り値として指定できます。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForPrincipalPolicy -PolicyInputList $policy1,$policy2 -PolicySourceArn arn:aws:iam::852640994763:user/TestUser
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMCredentialReport`
<a name="iam_GetCredentialReport_powershell_4_topic"></a>

次のコード例は、`Get-IAMCredentialReport` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、返されたレポートを開き、それをテキスト行の配列としてパイプラインに出力します。最初の行は、カンマで区切られた列名のヘッダーです。連続する各行は 1 人のユーザーの詳細行で、各フィールドはカンマで区切られています。レポートを表示するには、`Request-IAMCredentialReport` コマンドレットを使用してレポートを生成する必要があります。レポートを 1 つの文字列として取得するには、`-AsTextArray` ではなく `-Raw` を使用します。`-AsTextArray` スイッチには、エイリアス `-SplitLines` も使用できます。出力の列の完全なリストについては、サービス API リファレンスを参照してください。`-AsTextArray` または `-SplitLines` を使用しない場合は、.NET `StreamReader` クラスを使用して、`.Content` プロパティからテキストを抽出する必要があることに注意してください。**  

```
Request-IAMCredentialReport
```
**出力:**  

```
Description                                                         State
-----------                                                         -----
No report exists. Starting a new report generation task             STARTED
```

```
Get-IAMCredentialReport -AsTextArray
```
**出力:**  

```
      user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_2_active,access_key_2_last_rotated,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated root_account,arn:aws:iam::123456789012:root,2014-10-15T16:31:25+00:00,not_supported,2015-04-20T17:41:10+00:00,not_supported,not_supported,true,false,N/A,false,N/A,false,N/A,false,N/A
Administrator,arn:aws:iam::123456789012:user/Administrator,2014-10-16T16:03:09+00:00,true,2015-04-20T15:18:32+00:00,2014-10-16T16:06:00+00:00,N/A,false,true,2014-12-03T18:53:41+00:00,true,2015-03-25T20:38:14+00:00,false,N/A,false,N/A
Bill,arn:aws:iam::123456789012:user/Bill,2015-04-15T18:27:44+00:00,false,N/A,N/A,N/A,false,false,N/A,false,N/A,false,2015-04-20T20:00:12+00:00,false,N/A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetCredentialReport](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMEntitiesForPolicy`
<a name="iam_ListEntitiesForPolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMEntitiesForPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ポリシー `arn:aws:iam::123456789012:policy/TestPolicy` がアタッチされている IAM グループ、ロール、ユーザーのリストを返します。**  

```
Get-IAMEntitiesForPolicy -PolicyArn "arn:aws:iam::123456789012:policy/TestPolicy"
```
**出力:**  

```
IsTruncated  : False
Marker       : 
PolicyGroups : {}
PolicyRoles  : {testRole}
PolicyUsers  : {Bob, Theresa}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListEntitiesForPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMGroup`
<a name="iam_GetGroup_powershell_4_topic"></a>

次のコード例は、`Get-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、グループに属するすべての IAM ユーザーのコレクションを含む、IAM グループ `Testers` に関する詳細を返します。**  

```
$results = Get-IAMGroup -GroupName "Testers"
$results
```
**出力:**  

```
Group                                     IsTruncated           Marker                Users
-----                                     -----------           ------                -----
Amazon.IdentityManagement.Model.Group     False                                       {Theresa, David}
```

```
$results.Group
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : 3RHNZZGQJ7QHMAEXAMPLE1
GroupName  : Testers
Path       : /
```

```
$results.Users
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/Theresa
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : 4OSVDDJJTF4XEEXAMPLE2
UserName         : Theresa

Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE3
UserName         : David
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMGroupForUser`
<a name="iam_ListGroupsForUser_powershell_4_topic"></a>

次のコード例は、`Get-IAMGroupForUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ユーザー `David` が属する IAM グループのリストを返します。**  

```
Get-IAMGroupForUser -UserName David
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE2
GroupName  : Testers
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE3
GroupName  : Developers
Path       : /
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListGroupsForUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMGroupList`
<a name="iam_ListGroups_powershell_4_topic"></a>

次のコード例は、`Get-IAMGroupList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の で定義されているすべての IAM グループのコレクションを返します AWS アカウント。**  

```
Get-IAMGroupList
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /

Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE2
GroupName  : Developers
Path       : /

Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE3
GroupName  : Testers
Path       : /
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMGroupPolicy`
<a name="iam_GetGroupPolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、グループ `Testers` の `PowerUserAccess-Testers` という名前の埋め込みインラインポリシーに関する詳細を返します。`PolicyDocument` プロパティは URL エンコードされています。この例では、`UrlDecode` .NET メソッドを使用してデコードされています。**  

```
$results = Get-IAMGroupPolicy -GroupName Testers -PolicyName PowerUserAccess-Testers
$results
```
**出力:**  

```
GroupName     PolicyDocument                                              PolicyName
---------     --------------                                              ----------
Testers       %7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0A%20... PowerUserAccess-Testers

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
  ]
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMGroupPolicyList`
<a name="iam_ListGroupPolicies_powershell_4_topic"></a>

次のコード例は、`Get-IAMGroupPolicyList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、グループ `Testers` に埋め込まれているインラインポリシーのリストを返します。グループにアタッチされている管理ポリシーを取得するには、コマンド `Get-IAMAttachedGroupPolicyList` を使用します。**  

```
Get-IAMGroupPolicyList -GroupName Testers
```
**出力:**  

```
Deny-Assume-S3-Role-In-Production
PowerUserAccess-Testers
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListGroupPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMInstanceProfile`
<a name="iam_GetInstanceProfile_powershell_4_topic"></a>

次のコード例は、`Get-IAMInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の AWS アカウントで定義されている `ec2instancerole` という名前のインスタンスプロファイルの詳細を返します。**  

```
Get-IAMInstanceProfile -InstanceProfileName ec2instancerole
```
**出力:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMInstanceProfileForRole`
<a name="iam_ListInstanceProfilesForRole_powershell_4_topic"></a>

次のコード例は、`Get-IAMInstanceProfileForRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ロール `ec2instancerole` に関連付けられているインスタンスプロファイルの詳細を返します。**  

```
Get-IAMInstanceProfileForRole -RoleName ec2instancerole
```
**出力:**  

```
      Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
      CreateDate          : 2/17/2015 2:49:04 PM
      InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
      InstanceProfileName : ec2instancerole
      Path                : /
      Roles               : {ec2instancerole}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListInstanceProfilesForRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMInstanceProfileList`
<a name="iam_ListInstanceProfiles_powershell_4_topic"></a>

次のコード例は、`Get-IAMInstanceProfileList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の で定義されているインスタンスプロファイルのコレクションを返します AWS アカウント。**  

```
Get-IAMInstanceProfileList
```
**出力:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListInstanceProfiles](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMLoginProfile`
<a name="iam_GetLoginProfile_powershell_4_topic"></a>

次のコード例は、`Get-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パスワードの作成日と、IAM ユーザー `David` のパスワードのリセットが必要かどうかを返します。**  

```
Get-IAMLoginProfile -UserName David
```
**出力:**  

```
CreateDate                   PasswordResetRequired                 UserName
----------                   ---------------------                 --------
12/10/2014 3:39:44 PM        False                                 David
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetLoginProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMMFADevice`
<a name="iam_ListMfaDevices_powershell_4_topic"></a>

次のコード例は、`Get-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ユーザー `David` に割り当てられた MFA デバイスに関する詳細を返します。この例では、`SerialNumber` は物理デバイスの実際のシリアル番号ではなく ARN であるため、仮想デバイスであることがわかります。**  

```
Get-IAMMFADevice -UserName David
```
**出力:**  

```
EnableDate                  SerialNumber                           UserName
----------                  ------------                           --------
4/8/2015 9:41:10 AM         arn:aws:iam::123456789012:mfa/David    David
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListMfaDevices](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMOpenIDConnectProvider`
<a name="iam_GetOpenIdConnectProvider_powershell_4_topic"></a>

次のコード例は、`Get-IAMOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/accounts.google.com` である OpenID Connect プロバイダーに関する詳細を返します。`ClientIDList` プロパティは、このプロバイダーに定義されているすべてのクライアント ID を含むコレクションです。**  

```
Get-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/oidc.example.com
```
**出力:**  

```
ClientIDList         CreateDate                ThumbprintList                               Url
------------         ----------                --------------                               ---
{MyOIDCApp}          2/3/2015 3:00:30 PM       {12345abcdefghijk67890lmnopqrst98765uvwxy}   oidc.example.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMOpenIDConnectProviderList`
<a name="iam_ListOpenIdConnectProviders_powershell_4_topic"></a>

次のコード例は、`Get-IAMOpenIDConnectProviderList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の AWS アカウントで定義されているすべての OpenID Connect プロバイダーの ARN のリストを返します。**  

```
Get-IAMOpenIDConnectProviderList
```
**出力:**  

```
Arn
---
arn:aws:iam::123456789012:oidc-provider/server.example.com
arn:aws:iam::123456789012:oidc-provider/another.provider.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListOpenIdConnectProviders](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMPolicy`
<a name="iam_GetPolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` である管理ポリシーに関する詳細を返します。**  

```
Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**出力:**  

```
Arn              : arn:aws:iam::aws:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 2/6/2015 10:40:08 AM
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[GetPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMPolicyList`
<a name="iam_ListPolicies_powershell_4_topic"></a>

次のコード例は、`Get-IAMPolicyList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の AWS アカウントで使用できる最初の 3 つの管理ポリシーのコレクションを返します。`-scope`が指定されていないため、デフォルトで に設定`all`され、 AWS 管理ポリシーとカスタマー管理ポリシーの両方が含まれます。**  

```
Get-IAMPolicyList -MaxItem 3
```
**出力:**  

```
Arn              : arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : AWSDirectConnectReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:08 AM
      
Arn              : arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:27 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : NJKMU274MET4EEXAMPLE2
PolicyName       : AmazonGlacierReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:27 AM
      
Arn              : arn:aws:iam::aws:policy/AWSMarketplaceFullAccess
AttachmentCount  : 0
CreateDate       : 2/11/2015 9:21:45 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : 5ULJSO2FYVPYGEXAMPLE3
PolicyName       : AWSMarketplaceFullAccess
UpdateDate       : 2/11/2015 9:21:45 AM
```
**例 2: この例では、現在の AWS アカウントで使用できる最初の 2 つのカスタマー管理ポリシーのコレクションを返します。`-Scope local` を使用して、出力をカスタマー管理ポリシーのみに制限します。**  

```
Get-IAMPolicyList -Scope local -MaxItem 2
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:policy/MyLocalPolicy
AttachmentCount  : 0
CreateDate       : 2/12/2015 9:39:09 AM
DefaultVersionId : v2
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : SQVCBLC4VAOUCEXAMPLE4
PolicyName       : MyLocalPolicy
UpdateDate       : 2/12/2015 9:39:53 AM

Arn              : arn:aws:iam::123456789012:policy/policyforec2instancerole
AttachmentCount  : 1
CreateDate       : 2/17/2015 2:51:38 PM
DefaultVersionId : v11
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : X5JPBLJH2Z2SOEXAMPLE5
PolicyName       : policyforec2instancerole
UpdateDate       : 2/18/2015 8:52:31 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMPolicyVersion`
<a name="iam_GetPolicyVersion_powershell_4_topic"></a>

次のコード例は、`Get-IAMPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MyManagedPolicy` であるポリシーの `v2` バージョンのポリシードキュメントを返します。`Document` プロパティ内のポリシードキュメントは URL でエンコードされ、この例では `UrlDecode` .NET メソッドを使用してデコードされます。**  

```
$results = Get-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy -VersionId v2
$results
```
**出力:**  

```
CreateDate             Document                                        IsDefaultVersion     VersionId
----------             --------                                        ----------------     ---------
2/12/2015 9:39:53 AM   %7B%0A%20%20%22Version%22%3A%20%222012-10...    True                 v2

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
$policy = [System.Web.HttpUtility]::UrlDecode($results.Document)
$policy
{
  "Version":"2012-10-17",		 	 	 
  "Statement": 
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMPolicyVersionList`
<a name="iam_ListPolicyVersions_powershell_4_topic"></a>

次のコード例は、`Get-IAMPolicyVersionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MyManagedPolicy` であるポリシーの使用可能なバージョンのリストを返します。特定のバージョンのポリシードキュメントを取得するには、`Get-IAMPolicyVersion` コマンドを使用して、必要なバージョンの `VersionId` を指定します。**  

```
Get-IAMPolicyVersionList -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy
```
**出力:**  

```
CreateDate                   Document                 IsDefaultVersion                  VersionId
----------                   --------                 ----------------                  ---------
2/12/2015 9:39:53 AM                                  True                              v2
2/12/2015 9:39:09 AM                                  False                             v1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListPolicyVersions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMRole`
<a name="iam_GetRole_powershell_4_topic"></a>

次のコード例は、`Get-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`lamda_exec_role` の詳細を返します。これには、このロールの引き受け先を指定する信頼ポリシードキュメントが含まれています。ポリシードキュメントは URL でエンコードされており、.NET `UrlDecode` メソッドを使用してデコードできます。この例では、元のポリシーは、ポリシーにアップロードされる前にすべての空白が削除されています。ロールを引き受けるユーザーが実行できる操作を決定するアクセス許可ポリシードキュメントを確認するには、インラインポリシーには `Get-IAMRolePolicy` を使用し、アタッチされた管理ポリシーには `Get-IAMPolicyVersion` を使用します。**  

```
$results = Get-IamRole -RoleName lambda_exec_role
$results | Format-List
```
**出力:**  

```
Arn                      : arn:aws:iam::123456789012:role/lambda_exec_role
AssumeRolePolicyDocument : %7B%22Version%22%3A%222012-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22
                           %3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service
                           %22%3A%22lambda.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole
                           %22%7D%5D%7D
CreateDate               : 4/2/2015 9:16:11 AM
Path                     : /
RoleId                   : 2YBIKAIBHNKB4EXAMPLE1
RoleName                 : lambda_exec_role
```

```
$policy = [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
$policy
```
**出力:**  

```
{"Version":"2012-10-17",		 	 	 "Statement":[{"Sid":"","Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMRoleList`
<a name="iam_ListRoles_powershell_4_topic"></a>

次のコード例は、`Get-IAMRoleList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウント内のすべての IAM ロールのリストを取得します。**  

```
Get-IAMRoleList
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListRoles](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMRolePolicy`
<a name="iam_GetRolePolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ロール `lamda_exec_role` に埋め込まれている `oneClick_lambda_exec_role_policy` という名前のポリシーのアクセス許可ポリシードキュメントを返します。結果のポリシードキュメントは URL エンコードされます。この例では、`UrlDecode` .NET メソッドを使用してデコードされています。**  

```
$results = Get-IAMRolePolicy -RoleName lambda_exec_role -PolicyName oneClick_lambda_exec_role_policy
$results
```
**出力:**  

```
PolicyDocument                                            PolicyName                           UserName
--------------                                            ----------                           --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    oneClick_lambda_exec_role_policy     lambda_exec_role
```

```
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
```
**出力:**  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:*"
      ],
      "Resource": "arn:aws:logs:us-east-1:555555555555:log-group:/aws/lambda/aws-example-function:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/*"
      ]
    }
  ]
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMRolePolicyList`
<a name="iam_ListRolePolicies_powershell_4_topic"></a>

次のコード例は、`Get-IAMRolePolicyList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ロール `lamda_exec_role` に埋め込まれているインラインポリシーの名前のリストを返します。インラインポリシーの詳細を表示するには、`Get-IAMRolePolicy` コマンドを使用します。**  

```
Get-IAMRolePolicyList -RoleName lambda_exec_role
```
**出力:**  

```
oneClick_lambda_exec_role_policy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListRolePolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMRoleTagList`
<a name="iam_ListRoleTags_powershell_4_topic"></a>

次のコード例は、`Get-IAMRoleTagList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ロールに関連付けられているタグを取得します。**  

```
Get-IAMRoleTagList -RoleName MyRoleName
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListRoleTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMSAMLProvider`
<a name="iam_GetSamlProvider_powershell_4_topic"></a>

次のコード例は、`Get-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARM が arn:aws:iam::123456789012:saml-provider/SAMLADFS である SAML 2.0 プロバイダーに関する詳細を取得します。レスポンスには、SAML プロバイダーエンティティを作成するために ID AWS プロバイダーから取得したメタデータドキュメントと、作成日と有効期限が含まれます。**  

```
Get-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
**出力:**  

```
CreateDate                 SAMLMetadataDocument                                          ValidUntil
----------                 --------------------                                          ----------
12/23/2014 12:16:55 PM    <EntityDescriptor ID="_12345678-1234-5678-9012-example1...    12/23/2114 12:16:54 PM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetSamlProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMSAMLProviderList`
<a name="iam_ListSAMLProviders_powershell_4_topic"></a>

次のコード例は、`Get-IAMSAMLProviderList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の AWS アカウントで作成された SAML 2.0 プロバイダーのリストを取得します。これは、各 SAML プロバイダーの ARN、作成日、有効期限を返します。**  

```
Get-IAMSAMLProviderList
```
**出力:**  

```
Arn                                                 CreateDate                      ValidUntil
---                                                 ----------                      ----------
arn:aws:iam::123456789012:saml-provider/SAMLADFS    12/23/2014 12:16:55 PM          12/23/2114 12:16:54 PM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[ListSAMLProviders](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Get-IAMServerCertificate`
<a name="iam_GetServerCertificate_powershell_4_topic"></a>

次のコード例は、`Get-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`MyServerCertificate` という名前のサーバー証明書に関する詳細を取得します。証明書の詳細は、`CertificateBody` および `ServerCertificateMetadata` プロパティで確認できます。**  

```
$result = Get-IAMServerCertificate -ServerCertificateName MyServerCertificate
$result | format-list
```
**出力:**  

```
CertificateBody           : -----BEGIN CERTIFICATE-----
                            MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                            VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                            b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                            BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                            MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                            VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                            b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                            YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                            21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                            rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                            Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                            nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                            FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                            NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                            -----END CERTIFICATE-----
CertificateChain          : 
ServerCertificateMetadata : Amazon.IdentityManagement.Model.ServerCertificateMetadata
```

```
$result.ServerCertificateMetadata
```
**出力:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMServerCertificateList`
<a name="iam_ListServerCertificates_powershell_4_topic"></a>

次のコード例は、`Get-IAMServerCertificateList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の AWS アカウントにアップロードされたサーバー証明書のリストを取得します。**  

```
Get-IAMServerCertificateList
```
**出力:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListServerCertificates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMServiceLastAccessedDetail`
<a name="iam_GetServiceLastAccessedDetails_powershell_4_topic"></a>

次のコード例は、`Get-IAMServiceLastAccessedDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リクエスト呼び出しに関連付けられた IAM エンティティ (ユーザー、グループ、ロール、またはポリシー) が最後にアクセスしたサービスの詳細が表示されます。**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
**出力:**  

```
f0b7a819-eab0-929b-dc26-ca598911cb9f
```

```
Get-IAMServiceLastAccessedDetail -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMServiceLastAccessedDetailWithEntity`
<a name="iam_GetServiceLastAccessedDetailsWithEntities_powershell_4_topic"></a>

次のコード例は、`Get-IAMServiceLastAccessedDetailWithEntity` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、それぞれの IAM エンティティによるリクエスト内のサービスの最終アクセスタイムスタンプを提供します。**  

```
$results = Get-IAMServiceLastAccessedDetailWithEntity -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f -ServiceNamespace ec2
$results
```
**出力:**  

```
EntityDetailsList : {Amazon.IdentityManagement.Model.EntityDetails}
Error             : 
IsTruncated       : False
JobCompletionDate : 12/29/19 11:19:31 AM
JobCreationDate   : 12/29/19 11:19:31 AM
JobStatus         : COMPLETED
Marker            :
```

```
$results.EntityDetailsList
```
**出力:**  

```
EntityInfo                                 LastAuthenticated
----------                                 -----------------
Amazon.IdentityManagement.Model.EntityInfo 11/16/19 3:47:00 PM
```

```
$results.EntityInfo
```
**出力:**  

```
Arn  : arn:aws:iam::123456789012:user/TestUser
Id   : AIDA4NBK5CXF5TZHU1234
Name : TestUser
Path : /
Type : USER
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetServiceLastAccessedDetailsWithEntities](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMSigningCertificate`
<a name="iam_ListSigningCertificates_powershell_4_topic"></a>

次のコード例は、`Get-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前のユーザーに関連付けられている署名証明書に関する詳細を取得します。**  

```
Get-IAMSigningCertificate -UserName Bob
```
**出力:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListSigningCertificates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMUser`
<a name="iam_GetUser_powershell_4_topic"></a>

次のコード例は、`Get-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`David` という名前のユーザーに関する詳細を取得します。**  

```
Get-IAMUser -UserName David
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE1
UserName         : David
```
**例 2: この例では、現在サインインしている IAM ユーザーに関する詳細を取得します。**  

```
Get-IAMUser
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 10/16/2014 9:03:09 AM
PasswordLastUsed : 3/4/2015 12:12:33 PM
Path             : /
UserId           : 7K3GJEANSKZF2EXAMPLE2
UserName         : Bob
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMUserList`
<a name="iam_ListUsers_powershell_4_topic"></a>

次のコード例は、`Get-IAMUserList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の のユーザーのコレクションを取得します AWS アカウント。**  

```
Get-IAMUserList
```
**出力:**  

```
      Arn              : arn:aws:iam::123456789012:user/Administrator
      CreateDate       : 10/16/2014 9:03:09 AM
      PasswordLastUsed : 3/4/2015 12:12:33 PM
      Path             : /
      UserId           : 7K3GJEANSKZF2EXAMPLE1
      UserName         : Administrator
      
      Arn              : arn:aws:iam::123456789012:user/Bob
      CreateDate       : 4/6/2015 12:54:42 PM
      PasswordLastUsed : 1/1/0001 12:00:00 AM
      Path             : /
      UserId           : L3EWNONDOM3YUEXAMPLE2
      UserName         : bab
      
      Arn              : arn:aws:iam::123456789012:user/David
      CreateDate       : 12/10/2014 3:39:27 PM
      PasswordLastUsed : 3/19/2015 8:44:04 AM
      Path             : /
      UserId           : Y4FKWQCXTA52QEXAMPLE3
      UserName         : David
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListUsers](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMUserPolicy`
<a name="iam_GetUserPolicy_powershell_4_topic"></a>

次のコード例は、`Get-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`David` という名前の IAM ユーザーに埋め込まれている `Davids_IAM_Admin_Policy` という名前のインラインポリシーの詳細を取得します。ポリシードキュメントは URL エンコードされています。**  

```
$results = Get-IAMUserPolicy -PolicyName Davids_IAM_Admin_Policy -UserName David
$results
```
**出力:**  

```
PolicyDocument                                            PolicyName                    UserName
--------------                                            ----------                    --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    Davids_IAM_Admin_Policy       David

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:GetUser",
        "iam:ListUsers"
      ],
      "Resource": [
        "arn:aws:iam::111122223333:user/*"
      ]
    }
  ]
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMUserPolicyList`
<a name="iam_ListUserPolicies_powershell_4_topic"></a>

次のコード例は、`Get-IAMUserPolicyList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`David` という名前の IAM ユーザーに埋め込まれているインラインポリシーの名前のリストを取得します。**  

```
Get-IAMUserPolicyList -UserName David
```
**出力:**  

```
Davids_IAM_Admin_Policy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListUserPolicies](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMUserTagList`
<a name="iam_ListUserTags_powershell_4_topic"></a>

次のコード例は、`Get-IAMUserTagList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ユーザーに関連付けられているタグを取得します。**  

```
Get-IAMUserTagList -UserName joe
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListUserTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-IAMVirtualMFADevice`
<a name="iam_ListVirtualMfaDevices_powershell_4_topic"></a>

次のコード例は、`Get-IAMVirtualMFADevice` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS アカウントのユーザーに割り当てられた仮想 MFA デバイスのコレクションを取得します。それぞれの `User` プロパティは、デバイスが割り当てられている IAM ユーザーの詳細を含むオブジェクトです。**  

```
Get-IAMVirtualMFADevice -AssignmentStatus Assigned
```
**出力:**  

```
Base32StringSeed : 
EnableDate       : 4/13/2015 12:03:42 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/David
User             : Amazon.IdentityManagement.Model.User

Base32StringSeed : 
EnableDate       : 4/13/2015 12:06:41 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/root-account-mfa-device
User             : Amazon.IdentityManagement.Model.User
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListVirtualMfaDevices](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMAccessKey`
<a name="iam_CreateAccessKey_powershell_4_topic"></a>

次のコード例は、`New-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しいアクセスキーとシークレットアクセスキーのペアを作成し、それをユーザー `David` に割り当てます。`SecretAccessKey` を取得できるのはこのときだけなので、`AccessKeyId` と `SecretAccessKey` の値は必ずファイルに保存してください。後で取得することはできません。シークレットアクセスキーを紛失した場合は、新しいアクセスキーペアを作成する必要があります。**  

```
New-IAMAccessKey -UserName David
```
**出力:**  

```
AccessKeyId     : AKIAIOSFODNN7EXAMPLE
CreateDate      : 4/13/2015 1:00:42 PM
SecretAccessKey : wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Status          : Active
UserName        : David
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAccessKey](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMAccountAlias`
<a name="iam_CreateAccountAlias_powershell_4_topic"></a>

次のコード例は、`New-IAMAccountAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントのアカウントエイリアス AWS を に変更します`mycompanyaws`。ユーザーログオンページのアドレスが、https://mycompanyaws.signin.aws.amazon.com/console に変わります。エイリアスの代わりにアカウント ID 番号を使用する元の URL (https://<accountidnumber>.signin.aws.amazon.com/console) は引き続き機能します。ただし、以前に定義したエイリアスベースの URL は機能しなくなります。**  

```
New-IAMAccountAlias -AccountAlias mycompanyaws
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAccountAlias](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMGroup`
<a name="iam_CreateGroup_powershell_4_topic"></a>

次のコード例は、`New-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Developers` という名前の新しい IAM グループを作成します。**  

```
New-IAMGroup -GroupName Developers
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 4/14/2015 11:21:31 AM
GroupId    : QNEJ5PM4NFSQCEXAMPLE1
GroupName  : Developers
Path       : /
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMInstanceProfile`
<a name="iam_CreateInstanceProfile_powershell_4_topic"></a>

次のコード例は、`New-IAMInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`ProfileForDevEC2Instance` という名前の新しい IAM インスタンスプロファイルを作成します。`Add-IAMRoleToInstanceProfile` コマンドを個別に実行して、インスタンスにアクセス許可を与える既存の IAM ロールにインスタンスプロファイルを関連付ける必要があります。最後に、EC2 インスタンスを起動する際に、インスタンスプロファイルを EC2 インスタンスにアタッチします。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile_Name` パラメータと共に使用します。**  

```
New-IAMInstanceProfile -InstanceProfileName ProfileForDevEC2Instance
```
**出力:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ProfileForDevEC2Instance
CreateDate          : 4/14/2015 11:31:39 AM
InstanceProfileId   : DYMFXL556EY46EXAMPLE1
InstanceProfileName : ProfileForDevEC2Instance
Path                : /
Roles               : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMLoginProfile`
<a name="iam_CreateLoginProfile_powershell_4_topic"></a>

次のコード例は、`New-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Bob という名前の IAM ユーザーの (一時的な) パスワードを作成し、次回 `Bob` がサインインしたときに、ユーザーにパスワードを変更するように要求するフラグを設定しています。**  

```
New-IAMLoginProfile -UserName Bob -Password P@ssw0rd -PasswordResetRequired $true
```
**出力:**  

```
CreateDate                    PasswordResetRequired                UserName
----------                    ---------------------                --------
4/14/2015 12:26:30 PM         True                                 Bob
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateLoginProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMOpenIDConnectProvider`
<a name="iam_CreateOpenIdConnectProvider_powershell_4_topic"></a>

次のコード例は、`New-IAMOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、URL `https://example.oidcprovider.com` とクライアント ID `my-testapp-1` にある OIDC 互換プロバイダーサービスに関連付けられた IAM OIDC プロバイダーを作成します。OIDC プロバイダーがサムプリントを提供します。サムプリントを認証するには、http://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc-obtain-thumbprint.html にある手順に従ってください。**  

```
New-IAMOpenIDConnectProvider -Url https://example.oidcprovider.com -ClientIDList my-testapp-1 -ThumbprintList 990F419EXAMPLEECF12DDEDA5EXAMPLE52F20D9E
```
**出力:**  

```
arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMPolicy`
<a name="iam_CreatePolicy_powershell_4_topic"></a>

次のコード例は、`New-IAMPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 という名前の現在の AWS アカウントに新しい IAM `MySamplePolicy` ポリシーを作成します。 ファイルはポリシーコンテンツ`MySamplePolicy.json`を提供します。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。**  

```
New-IAMPolicy -PolicyName MySamplePolicy -PolicyDocument (Get-Content -Raw MySamplePolicy.json)
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 4/14/2015 2:45:59 PM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : LD4KP6HVFE7WGEXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 4/14/2015 2:45:59 PM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreatePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMPolicyVersion`
<a name="iam_CreatePolicyVersion_powershell_4_topic"></a>

次のコード例は、`New-IAMPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MyPolicy` である IAM ポリシーの新しい「v2」バージョンを作成し、それをデフォルトのバージョンにします。`NewPolicyVersion.json` ファイルは、ポリシーの内容を提供します。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。**  

```
New-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -PolicyDocument (Get-content -Raw NewPolicyVersion.json) -SetAsDefault $true
```
**出力:**  

```
CreateDate                           Document                  IsDefaultVersion             VersionId
----------                           --------                  ----------------             ---------
4/15/2015 10:54:54 AM                                          True                         v2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreatePolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMRole`
<a name="iam_CreateRole_powershell_4_topic"></a>

次のコード例は、`New-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`MyNewRole` という名前の新しいロールを作成し、`NewRoleTrustPolicy.json` ファイルにあるポリシーをそのロールにアタッチします。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。出力に表示されるポリシードキュメントは、URL でエンコードされています。この例では、`UrlDecode` .NET メソッドを使用してデコードされています。**  

```
$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole
$results
```
**出力:**  

```
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"
    }
  ]
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMSAMLProvider`
<a name="iam_CreateSAMLProvider_powershell_4_topic"></a>

次のコード例は、`New-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM に新しい SAML プロバイダーエンティティを作成します。これは `MySAMLProvider` という名前で、SAML サービスプロバイダーのウェブサイトから個別にダウンロードされた `SAMLMetaData.xml` ファイルにある SAML メタデータドキュメントによって記述されます。**  

```
New-IAMSAMLProvider -Name MySAMLProvider -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
**出力:**  

```
arn:aws:iam::123456789012:saml-provider/MySAMLProvider
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateSAMLProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_powershell_4_topic"></a>

次のコード例は、`New-IAMServiceLinkedRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、自動スケーリングサービスのサービスにリンクされたロールを作成します。**  

```
New-IAMServiceLinkedRole -AWSServiceName autoscaling.amazonaws.com -CustomSuffix RoleNameEndsWithThis -Description "My service-linked role to support autoscaling"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMUser`
<a name="iam_CreateUser_powershell_4_topic"></a>

次のコード例は、`New-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前の IAM ユーザーを作成します。Bob が AWS コンソールにサインインする必要がある場合は、 コマンドを個別に実行`New-IAMLoginProfile`して、パスワードでサインインプロファイルを作成する必要があります。Bob が AWS PowerShell またはクロスプラットフォーム CLI コマンドを実行したり、 AWS API コールを実行したりする必要がある場合は、 `New-IAMAccessKey` コマンドを個別に実行してアクセスキーを作成する必要があります。**  

```
New-IAMUser -UserName Bob
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 4/22/2015 12:02:11 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : AIDAJWGEFDMEMEXAMPLE1
UserName         : Bob
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-IAMVirtualMFADevice`
<a name="iam_CreateVirtualMfaDevice_powershell_4_topic"></a>

次のコード例は、`New-IAMVirtualMFADevice` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しい仮想 MFA デバイスを作成します。2 行目と 3 行目は、仮想 MFA ソフトウェアプログラムが (QR コードの代わりに) アカウントを作成するのに必要な `Base32StringSeed` 値を抽出します。この値でプログラムを設定したら、プログラムから 2 つの連続した認証コードを取得します。最後に、最後のコマンドを使用して仮想 MFA デバイスを IAM ユーザー `Bob` にリンクし、アカウントを 2 つの認証コードと同期します。**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$SR = New-Object System.IO.StreamReader($Device.Base32StringSeed)
$base32stringseed = $SR.ReadToEnd()
$base32stringseed   
CZWZMCQNW4DEXAMPLE3VOUGXJFZYSUW7EXAMPLECR4NJFD65GX2SLUDW2EXAMPLE
```
**出力:**  

```
-- Pause here to enter base-32 string seed code into virtual MFA program to register account. --

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
**例 2: この例では、新しい仮想 MFA デバイスを作成します。2 行目と 3 行目は、`QRCodePNG` 値を抽出してファイルに書き込みます。(Base32StringSeed 値を手動で入力する代わりに) このイメージを仮想 MFA ソフトウェアプログラムでスキャンして、アカウントを作成できます。仮想 MFA プログラムでアカウントを作成したら、2 つの連続した認証コードを取得して最後のコマンドに入力し、仮想 MFA デバイスを IAM ユーザー `Bob` にリンクして、アカウントを同期します。**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$BR = New-Object System.IO.BinaryReader($Device.QRCodePNG)
$BR.ReadBytes($BR.BaseStream.Length) | Set-Content -Encoding Byte -Path QRCode.png
```
**出力:**  

```
 -- Pause here to scan PNG with virtual MFA program to register account. -- 

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Publish-IAMServerCertificate`
<a name="iam_UploadServerCertificate_powershell_4_topic"></a>

次のコード例は、`Publish-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しいサーバー証明書を IAM アカウントにアップロードします。証明書本文、プライベートキー、および (オプションで) 証明書チェーンを含むファイルは、すべて PEM エンコードされる必要があります。パラメータにはファイル名ではなくファイルの実際の内容が必要であることに注意してください。ファイルの内容を正常に処理するには、`-Raw` スイッチパラメータを使用する必要があります。**  

```
Publish-IAMServerCertificate -ServerCertificateName MyTestCert -CertificateBody (Get-Content -Raw server.crt) -PrivateKey (Get-Content -Raw server.key)
```
**出力:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/MyTestCert
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /
ServerCertificateId   : ASCAJIEXAMPLE7J7HQZYW
ServerCertificateName : MyTestCert
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UploadServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Publish-IAMSigningCertificate`
<a name="iam_UploadSigningCertificate_powershell_4_topic"></a>

次のコード例は、`Publish-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しい X.509 署名証明書をアップロードし、`Bob` という名前の IAM ユーザーに関連付けます。証明書の本文を含むファイルは PEM でエンコードされています。`CertificateBody` パラメータには、ファイル名ではなく証明書ファイルの実際の内容が必要です。ファイルを正常に処理するには、`-Raw` スイッチパラメータを使用する必要があります。**  

```
Publish-IAMSigningCertificate -UserName Bob -CertificateBody (Get-Content -Raw SampleSigningCert.pem)
```
**出力:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCEXAMPLEHMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UploadSigningCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-IAMGroupPolicy`
<a name="iam_AttachGroupPolicy_powershell_4_topic"></a>

次のコード例は、`Register-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`TesterPolicy` という名前のカスタマー管理ポリシーを IAM グループ `Testers` にアタッチします。そのグループのユーザーは、そのポリシーのデフォルトバージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**例 2: この例では、 という名前 AWS の管理ポリシーを IAM グループ `AdministratorAccess`にアタッチします`Admins`。そのグループのユーザーは、そのポリシーの最新バージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMGroupPolicy -GroupName Admins -PolicyArn arn:aws:iam::aws:policy/AdministratorAccess
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-IAMRolePolicy`
<a name="iam_AttachRolePolicy_powershell_4_topic"></a>

次のコード例は、`Register-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 という名前 AWS の管理ポリシーを IAM ロール `SecurityAudit`にアタッチします`CoSecurityAuditors`。そのロールを引き受けるユーザーは、そのポリシーの最新バージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMRolePolicy -RoleName CoSecurityAuditors -PolicyArn arn:aws:iam::aws:policy/SecurityAudit
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-IAMUserPolicy`
<a name="iam_AttachUserPolicy_powershell_4_topic"></a>

次のコード例は、`Register-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 という名前 AWS の管理ポリシーを IAM ユーザー `AmazonCognitoPowerUser`にアタッチします`Bob`。ユーザーは、そのポリシーの最新バージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AttachUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMAccessKey`
<a name="iam_DeleteAccessKey_powershell_4_topic"></a>

次のコード例は、`Remove-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 という名前のユーザー`AKIAIOSFODNN7EXAMPLE`からキー ID を持つ AWS アクセスキーペアを削除します`Bob`。**  

```
Remove-IAMAccessKey -AccessKeyId AKIAIOSFODNN7EXAMPLE -UserName Bob -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteAccessKey](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMAccountAlias`
<a name="iam_DeleteAccountAlias_powershell_4_topic"></a>

次のコード例は、`Remove-IAMAccountAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 からアカウントエイリアスを削除します AWS アカウント。https://mycompanyaws.signin.aws.amazon.com/console で、エイリアスを持つユーザーサインインページは機能しなくなりました。代わりに、https://<accountidnumber>.signin.aws.amazon.com/console の AWS アカウント ID 番号で元の URL を使用する必要があります。**  

```
Remove-IAMAccountAlias -AccountAlias mycompanyaws
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteAccountAlias](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMAccountPasswordPolicy`
<a name="iam_DeleteAccountPasswordPolicy_powershell_4_topic"></a>

次のコード例は、`Remove-IAMAccountPasswordPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 のパスワードポリシーを削除 AWS アカウント し、すべての値を元のデフォルトにリセットします。パスワードポリシーが現在存在しない場合、次のエラーメッセージが表示されます。The account policy with name PasswordPolicy cannot be found.**  

```
Remove-IAMAccountPasswordPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMClientIDFromOpenIDConnectProvider`
<a name="iam_RemoveClientIdFromOpenIdConnectProvider_powershell_4_topic"></a>

次のコード例は、`Remove-IAMClientIDFromOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` である IAM OIDC プロバイダーに関連付けられているクライアント ID のリストから、クライアント ID `My-TestApp-3` を削除します。**  

```
Remove-IAMClientIDFromOpenIDConnectProvider -ClientID My-TestApp-3 -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveClientIdFromOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMGroup`
<a name="iam_DeleteGroup_powershell_4_topic"></a>

次のコード例は、`Remove-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`MyTestGroup` という名前の IAM グループを削除します。最初のコマンドはグループのメンバーであるすべての IAM ユーザーを削除し、2 番目のコマンドは IAM グループを削除します。どちらのコマンドも、確認を求めるプロンプトが表示されなくても機能します。**  

```
(Get-IAMGroup -GroupName MyTestGroup).Users | Remove-IAMUserFromGroup -GroupName MyTestGroup -Force
Remove-IAMGroup -GroupName MyTestGroup -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMGroupPolicy`
<a name="iam_DeleteGroupPolicy_powershell_4_topic"></a>

次のコード例は、`Remove-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`TesterPolicy` という名前のインラインポリシーを IAM グループ `Testers` から削除します。そのグループのユーザーは、そのポリシーで定義されているアクセス権限をすぐに失います。**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMInstanceProfile`
<a name="iam_DeleteInstanceProfile_powershell_4_topic"></a>

次のコード例は、`Remove-IAMInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`MyAppInstanceProfile` という名前の EC2 インスタンスプロファイルを削除します。最初のコマンドはインスタンスプロファイルからすべてのロールをデタッチし、2 番目のコマンドはインスタンスプロファイルを削除します。**  

```
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMLoginProfile`
<a name="iam_DeleteLoginProfile_powershell_4_topic"></a>

次のコード例は、`Remove-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前の IAM ユーザーからログインプロファイルを削除します。これにより、ユーザーは AWS コンソールにサインインできなくなります。ユーザーアカウントにアタッチされている可能性のある AWS アクセスキーを使用して、ユーザーが AWS CLI、PowerShell、または API コールを実行できないようにします。**  

```
Remove-IAMLoginProfile -UserName Bob
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLoginProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMOpenIDConnectProvider`
<a name="iam_DeleteOpenIdConnectProvider_powershell_4_topic"></a>

次のコード例は、`Remove-IAMOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、プロバイダー `example.oidcprovider.com` に接続する IAM OIDC プロバイダーを削除します。ロールの信頼ポリシーの `Principal` 要素で、このプロバイダーを参照するロールをすべて更新または削除してください。**  

```
Remove-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMPolicy`
<a name="iam_DeletePolicy_powershell_4_topic"></a>

次のコード例は、`Remove-IAMPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーを削除します。ポリシーを削除する前に、`Remove-IAMPolicyVersion` を実行して、デフォルト以外のすべてのバージョンを削除する必要があります。また、すべての IAM ユーザー、グループ、またはロールからポリシーをデタッチする必要があります。**  

```
Remove-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**例 2: この例では、最初にデフォルト以外のポリシーバージョンをすべて削除し、アタッチされているすべての IAM エンティティからデタッチして、最後にポリシー自体を削除することでポリシーを削除します。1 行目では、ポリシーオブジェクトを取得します。2 行目では、デフォルトバージョンとしてフラグが立てられていないすべてのポリシーバージョンをコレクションに取得し、コレクション内の各ポリシーを削除します。3 行目では、ポリシーがアタッチされているすべての IAM ユーザー、グループ、およびロールを取得します。4 行目から 6 行目では、アタッチされている各エンティティからポリシーをデタッチします。最後の行では、このコマンドを使用して管理ポリシーと残りのデフォルトバージョンを削除します。この例には、確認を求めるプロンプトを非表示にするための `-Force` switch パラメータが、このパラメータを必要とする行に含まれています。**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
$attached = Get-IAMEntitiesForPolicy -PolicyArn $pol.Arn
$attached.PolicyGroups | Unregister-IAMGroupPolicy -PolicyArn $pol.arn
$attached.PolicyRoles | Unregister-IAMRolePolicy -PolicyArn $pol.arn
$attached.PolicyUsers | Unregister-IAMUserPolicy -PolicyArn $pol.arn
Remove-IAMPolicy $pol.Arn -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeletePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMPolicyVersion`
<a name="iam_DeletePolicyVersion_powershell_4_topic"></a>

次のコード例は、`Remove-IAMPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`v2` と識別されたバージョンを ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーから削除します。**  

```
Remove-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy -VersionID v2
```
**例 2: この例では、最初にデフォルト以外のポリシーバージョンをすべて削除し、次にポリシー自体を削除することでポリシーを削除します。1 行目では、ポリシーオブジェクトを取得します。2 行目では、デフォルトとしてフラグが立てられていないすべてのポリシーバージョンをコレクションに取得し、このコマンドを使用してコレクション内の各ポリシーを削除します。最後の行では、ポリシー自体と残りのデフォルトバージョンを削除します。管理ポリシーを正常に削除するには、`Unregister-IAMUserPolicy`、`Unregister-IAMGroupPolicy`、`Unregister-IAMRolePolicy` コマンドを使用して、ユーザー、グループ、またはロールからポリシーをデタッチする必要があることに注意してください。`Remove-IAMPolicy` コマンドレットの例を参照してください。**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
Remove-IAMPolicy -PolicyArn $pol.Arn -force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeletePolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMRole`
<a name="iam_DeleteRole_powershell_4_topic"></a>

次のコード例は、`Remove-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の IAM アカウントから `MyNewRole` という名前のロールを削除します。ロールを削除する前に、まず `Unregister-IAMRolePolicy` コマンドを使用して、管理ポリシーをデタッチする必要があります。インラインポリシーは、ロールと共に削除されます。**  

```
Remove-IAMRole -RoleName MyNewRole
```
**例 2: この例では、`MyNewRole` という名前のロールから管理ポリシーをすべてデタッチして、ロールを削除します。最初の行では、ロールにアタッチされているすべての管理ポリシーをコレクションとして取得し、コレクション内の各ポリシーをロールからデタッチします。2 行目では、ロール自体を削除します。インラインポリシーは、ロールと共に削除されます。**  

```
Get-IAMAttachedRolePolicyList -RoleName MyNewRole | Unregister-IAMRolePolicy -RoleName MyNewRole
Remove-IAMRole -RoleName MyNewRole
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMRoleFromInstanceProfile`
<a name="iam_RemoveRoleFromInstanceProfile_powershell_4_topic"></a>

次のコード例は、`Remove-IAMRoleFromInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`MyNewRole` という名前の EC2 インスタンスプロファイルから `MyNewRole` という名前のロールを削除します。IAM コンソールで作成されたインスタンスプロファイルは、この例のように、常にロールと同じ名前になります。API または CLI で作成する場合、名前は異なる場合があります。**  

```
Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyNewRole -RoleName MyNewRole -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMRolePermissionsBoundary`
<a name="iam_DeleteRolePermissionsBoundary_powershell_4_topic"></a>

次のコード例は、`Remove-IAMRolePermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は、IAM ロールにアタッチされたアクセス許可の境界を削除する方法を示しています。**  

```
Remove-IAMRolePermissionsBoundary -RoleName MyRoleName
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMRolePolicy`
<a name="iam_DeleteRolePolicy_powershell_4_topic"></a>

次のコード例は、`Remove-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ロール `S3BackupRole` に埋め込まれているインラインポリシー `S3AccessPolicy` を削除します。**  

```
Remove-IAMRolePolicy -PolicyName S3AccessPolicy -RoleName S3BackupRole
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMRoleTag`
<a name="iam_UntagRole_powershell_4_topic"></a>

次のコード例は、`Remove-IAMRoleTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、タグキーが「abac」の「MyRoleName」という名前のロールからタグを削除します。複数のタグを削除するには、カンマで区切ったタグキーリストを指定します。**  

```
Remove-IAMRoleTag -RoleName MyRoleName -TagKey "abac","xyzw"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UntagRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMSAMLProvider`
<a name="iam_DeleteSAMLProvider_powershell_4_topic"></a>

次のコード例は、`Remove-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider` である IAM SAML 2.0 プロバイダーを削除します。**  

```
Remove-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteSAMLProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMServerCertificate`
<a name="iam_DeleteServerCertificate_powershell_4_topic"></a>

次のコード例は、`Remove-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`MyServerCert` という名前のサーバー証明書を削除します。**  

```
Remove-IAMServerCertificate -ServerCertificateName MyServerCert
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_powershell_4_topic"></a>

次のコード例は、`Remove-IAMServiceLinkedRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、サービスにリンクされたロールを削除しました。サービスがこのロールをまだ使用している場合、このコマンドは失敗することに注意してください。**  

```
Remove-IAMServiceLinkedRole -RoleName AWSServiceRoleForAutoScaling_RoleNameEndsWithThis
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteServiceLinkedRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMSigningCertificate`
<a name="iam_DeleteSigningCertificate_powershell_4_topic"></a>

次のコード例は、`Remove-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前の IAM ユーザーから ID `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` の付いた署名証明書を削除します。**  

```
Remove-IAMSigningCertificate -UserName Bob -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteSigningCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMUser`
<a name="iam_DeleteUser_powershell_4_topic"></a>

次のコード例は、`Remove-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前の IAM ユーザーを削除します。**  

```
Remove-IAMUser -UserName Bob
```
**例 2: この例では、`Theresa` という名前の IAM ユーザーと、最初に削除する必要がある要素をすべて削除します。**  

```
$name = "Theresa"

# find any groups and remove user from them
$groups = Get-IAMGroupForUser -UserName $name
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName $name -Force }

# find any inline policies and delete them
$inlinepols = Get-IAMUserPolicies -UserName $name
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName $name -Force}

# find any managed polices and detach them
$managedpols = Get-IAMAttachedUserPolicies -UserName $name
foreach ($pol in $managedpols) { Unregister-IAMUserPolicy -PolicyArn $pol.PolicyArn -UserName $name }

# find any signing certificates and delete them
$certs = Get-IAMSigningCertificate -UserName $name
foreach ($cert in $certs) { Remove-IAMSigningCertificate -CertificateId $cert.CertificateId -UserName $name -Force }

# find any access keys and delete them
$keys = Get-IAMAccessKey -UserName $name
foreach ($key in $keys) { Remove-IAMAccessKey -AccessKeyId $key.AccessKeyId -UserName $name -Force }

# delete the user's login profile, if one exists - note: need to use try/catch to suppress not found error
try { $prof = Get-IAMLoginProfile -UserName $name -ea 0 } catch { out-null }
if ($prof) { Remove-IAMLoginProfile -UserName $name -Force }

# find any MFA device, detach it, and if virtual, delete it.
$mfa = Get-IAMMFADevice -UserName $name
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}

# finally, remove the user
Remove-IAMUser -UserName $name -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMUserFromGroup`
<a name="iam_RemoveUserFromGroup_powershell_4_topic"></a>

次のコード例は、`Remove-IAMUserFromGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ユーザー `Bob` をグループ `Testers` から削除します。**  

```
Remove-IAMUserFromGroup -GroupName Testers -UserName Bob
```
**例 2: この例では、IAM ユーザー `Theresa` がメンバーとなっているグループをすべて検索し、それらのグループから `Theresa` を削除します。**  

```
$groups = Get-IAMGroupForUser -UserName Theresa 
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName Theresa -Force }
```
**例 3: この例は、IAM ユーザー `Bob` を `Testers` グループから削除する別の方法を示しています。**  

```
Get-IAMGroupForUser -UserName Bob | Remove-IAMUserFromGroup -UserName Bob -GroupName Testers -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveUserFromGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMUserPermissionsBoundary`
<a name="iam_DeleteUserPermissionsBoundary_powershell_4_topic"></a>

次のコード例は、`Remove-IAMUserPermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は、IAM ユーザーにアタッチされたアクセス許可の境界を削除する方法を示しています。**  

```
Remove-IAMUserPermissionsBoundary -UserName joe
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。い。

### `Remove-IAMUserPolicy`
<a name="iam_DeleteUserPolicy_powershell_4_topic"></a>

次のコード例は、`Remove-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前の IAM ユーザーに埋め込まれている `AccessToEC2Policy` という名前のインラインポリシーを削除します。**  

```
Remove-IAMUserPolicy -PolicyName AccessToEC2Policy -UserName Bob
```
**例 2: この例では、`Theresa` という名前の IAM ユーザーに埋め込まれているすべてのインラインポリシーを検索し、削除します。**  

```
$inlinepols = Get-IAMUserPolicies -UserName Theresa
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName Theresa -Force}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMUserTag`
<a name="iam_UntagUser_powershell_4_topic"></a>

次のコード例は、`Remove-IAMUserTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、タグキーが「abac」と「xyzw」の「joe」という名前のユーザーからタグを削除します。複数のタグを削除するには、カンマで区切ったタグキーリストを指定します。**  

```
Remove-IAMUserTag -UserName joe -TagKey "abac","xyzw"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UntagUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-IAMVirtualMFADevice`
<a name="iam_DeleteVirtualMfaDevice_powershell_4_topic"></a>

次のコード例は、`Remove-IAMVirtualMFADevice` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:mfa/bob` である IAM 仮想 MFA デバイスを削除します。**  

```
Remove-IAMVirtualMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/bob
```
**例 2: この例では、IAM ユーザー Theresa に MFA デバイスが割り当てられているかどうかを確認します。割り当てられているデバイスが見つかった場合、そのデバイスはその IAM ユーザーに対して無効になります。デバイスが仮想の場合は、そのデバイスも削除されます。**  

```
$mfa = Get-IAMMFADevice -UserName Theresa
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Request-IAMCredentialReport`
<a name="iam_GenerateCredentialReport_powershell_4_topic"></a>

次のコード例は、`Request-IAMCredentialReport` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、4 時間ごとに実行できる新しいレポートの生成を要求しています。最新のレポートがまだ新しい場合、[状態] フィールドには `COMPLETE` と表示されます。`Get-IAMCredentialReport` を使用して、完成したレポートを表示します。**  

```
Request-IAMCredentialReport
```
**出力:**  

```
Description                                                    State
-----------                                                    -----
No report exists. Starting a new report generation task        STARTED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GenerateCredentialReport](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Request-IAMServiceLastAccessedDetail`
<a name="iam_GenerateServiceLastAccessedDetails_powershell_4_topic"></a>

次のコード例は、`Request-IAMServiceLastAccessedDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は GenerateServiceLastAccessedDetails API と同等のコマンドレットです。これにより、Get-IAMServiceLastAccessedDetail と Get-IAMServiceLastAccessedDetailWithEntity で使用できるジョブ ID が提供されます。**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GenerateServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-IAMDefaultPolicyVersion`
<a name="iam_SetDefaultPolicyVersion_powershell_4_topic"></a>

次のコード例は、`Set-IAMDefaultPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ARN が `arn:aws:iam::123456789012:policy/MyPolicy` であるポリシーの `v2` バージョンをデフォルトのアクティブなバージョンとして設定します。**  

```
Set-IAMDefaultPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -VersionId v2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SetDefaultPolicyVersion](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-IAMRolePermissionsBoundary`
<a name="iam_PutRolePermissionsBoundary_powershell_4_topic"></a>

次のコード例は、`Set-IAMRolePermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は、IAM ロールのアクセス許可の境界を設定する方法を示しています。 AWS 管理ポリシーまたはカスタムポリシーをアクセス許可の境界として設定できます。**  

```
Set-IAMRolePermissionsBoundary -RoleName MyRoleName -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-IAMUserPermissionsBoundary`
<a name="iam_PutUserPermissionsBoundary_powershell_4_topic"></a>

次のコード例は、`Set-IAMUserPermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例は、ユーザーのアクセス許可の境界を設定する方法を示しています。 AWS 管理ポリシーまたはカスタムポリシーをアクセス許可の境界として設定できます。 **  

```
Set-IAMUserPermissionsBoundary -UserName joe -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Sync-IAMMFADevice`
<a name="iam_ResyncMfaDevice_powershell_4_topic"></a>

次のコード例は、`Sync-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ユーザー `Bob` に関連付けられていて、ARN が `arn:aws:iam::123456789012:mfa/bob` である MFA デバイスを、2 つの認証コードを提供した認証プログラムと同期します。**  

```
Sync-IAMMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/theresa -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Bob
```
**例 2: この例では、IAM ユーザー `Theresa` に関連付けられている IAM MFA デバイスを、シリアル番号が `ABCD12345678` であり、2 つの認証コードを提供した物理デバイスと同期します。**  

```
Sync-IAMMFADevice -SerialNumber ABCD12345678 -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Theresa
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResyncMfaDevice](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-IAMGroupPolicy`
<a name="iam_DetachGroupPolicy_powershell_4_topic"></a>

次のコード例は、`Unregister-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/TesterAccessPolicy` である管理グループポリシーを `Testers` という名前のグループからデタッチします。**  

```
Unregister-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterAccessPolicy
```
**例 2: この例では、`Testers` という名前のグループにアタッチされているすべての管理ポリシーを検索し、グループからデタッチします。**  

```
Get-IAMAttachedGroupPolicies -GroupName Testers | Unregister-IAMGroupPolicy -Groupname Testers
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-IAMRolePolicy`
<a name="iam_DetachRolePolicy_powershell_4_topic"></a>

次のコード例は、`Unregister-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy` である管理グループポリシーを `FedTesterRole` という名前のロールからデタッチします。**  

```
Unregister-IAMRolePolicy -RoleName FedTesterRole -PolicyArn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy
```
**例 2: この例では、`FedTesterRole` という名前のロールにアタッチされているすべての管理ポリシーを検索し、ロールからデタッチします。**  

```
Get-IAMAttachedRolePolicyList -RoleName FedTesterRole | Unregister-IAMRolePolicy -Rolename FedTesterRole
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-IAMUserPolicy`
<a name="iam_DetachUserPolicy_powershell_4_topic"></a>

次のコード例は、`Unregister-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/TesterPolicy` である管理ポリシーを `Bob` という名前の IAM ユーザーからデタッチします。**  

```
Unregister-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**例 2: この例では、`Theresa` という名前の IAM ユーザーにアタッチされているすべての管理ポリシーを検索し、それらのポリシーをユーザーからデタッチします。**  

```
Get-IAMAttachedUserPolicyList -UserName Theresa | Unregister-IAMUserPolicy -Username Theresa
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DetachUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMAccessKey`
<a name="iam_UpdateAccessKey_powershell_4_topic"></a>

次のコード例は、`Update-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前の IAM ユーザーのアクセスキー `AKIAIOSFODNN7EXAMPLE` のステータスを `Inactive` に変更します。**  

```
Update-IAMAccessKey -UserName Bob -AccessKeyId AKIAIOSFODNN7EXAMPLE -Status Inactive
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateAccessKey](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMAccountPasswordPolicy`
<a name="iam_UpdateAccountPasswordPolicy_powershell_4_topic"></a>

次のコード例は、`Update-IAMAccountPasswordPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した設定でアカウントのパスワードポリシーを更新します。コマンドに含まれていないパラメータは変更されないままにはならないことに注意してください。代わりに、デフォルト値にリセットされます。**  

```
Update-IAMAccountPasswordPolicy -AllowUsersToChangePasswords $true -HardExpiry $false -MaxPasswordAge 90 -MinimumPasswordLength 8 -PasswordReusePrevention 20 -RequireLowercaseCharacters $true -RequireNumbers $true -RequireSymbols $true -RequireUppercaseCharacters $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMAssumeRolePolicy`
<a name="iam_UpdateAssumeRolePolicy_powershell_4_topic"></a>

次のコード例は、`Update-IAMAssumeRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`ClientRole` という名前の IAM ロールを新しい信頼ポリシーで更新します。その内容は、ファイル `ClientRolePolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` スイッチパラメータを使用する必要があることに注意してください。**  

```
Update-IAMAssumeRolePolicy -RoleName ClientRole -PolicyDocument (Get-Content -raw ClientRolePolicy.json)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateAssumeRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMGroup`
<a name="iam_UpdateGroup_powershell_4_topic"></a>

次のコード例は、`Update-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM グループ `Testers` の名前を `AppTesters` に変更します。**  

```
Update-IAMGroup -GroupName Testers -NewGroupName AppTesters
```
**例 2: この例では、IAM グループ `AppTesters` のパスを `/Org1/Org2/` に変更します。これにより、グループの ARN が `arn:aws:iam::123456789012:group/Org1/Org2/AppTesters` に変更されます。**  

```
Update-IAMGroup -GroupName AppTesters -NewPath /Org1/Org2/
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMLoginProfile`
<a name="iam_UpdateLoginProfile_powershell_4_topic"></a>

次のコード例は、`Update-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ユーザー `Bob` に新しい一時パスワードを設定し、ユーザーが次回サインインしたときにパスワードを変更するようユーザーに要求します。**  

```
Update-IAMLoginProfile -UserName Bob -Password "P@ssw0rd1234" -PasswordResetRequired $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateLoginProfile](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMOpenIDConnectProviderThumbprint`
<a name="iam_UpdateOpenIdConnectProviderThumbprint_powershell_4_topic"></a>

次のコード例は、`Update-IAMOpenIDConnectProviderThumbprint` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` である OIDC プロバイダーの証明書サムプリントリストを更新して、新しいサムプリントを使用します。OIDC プロバイダーは、プロバイダーに関連付けられている証明書が変更されると、新しい値を共有します。**  

```
Update-IAMOpenIDConnectProviderThumbprint -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com -ThumbprintList 7359755EXAMPLEabc3060bce3EXAMPLEec4542a3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateOpenIdConnectProviderThumbprint](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMRole`
<a name="iam_UpdateRole_powershell_4_topic"></a>

次のコード例は、`Update-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ロールの説明と、ロールのセッションをリクエストできる最大セッション期間の値 (秒単位) を更新します。**  

```
Update-IAMRole -RoleName MyRoleName -Description "My testing role" -MaxSessionDuration 43200
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMRoleDescription`
<a name="iam_UpdateRoleDescription_powershell_4_topic"></a>

次のコード例は、`Update-IAMRoleDescription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントの IAM ロールの説明を更新します。**  

```
Update-IAMRoleDescription -RoleName MyRoleName -Description "My testing role"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateRoleDescription](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMSAMLProvider`
<a name="iam_UpdateSamlProvider_powershell_4_topic"></a>

次のコード例は、`Update-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:saml-provider/SAMLADFS` である IAM の SAML プロバイダーを、ファイル `SAMLMetaData.xml` の新しい SAML メタデータドキュメントで更新します。JSON ファイルの内容を正常に処理するには、`-Raw` スイッチパラメータを使用する必要があることに注意してください。**  

```
Update-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateSamlProvider](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMServerCertificate`
<a name="iam_UpdateServerCertificate_powershell_4_topic"></a>

次のコード例は、`Update-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`MyServerCertificate` という証明書の名前を `MyRenamedServerCertificate` に変更します。**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewServerCertificateName MyRenamedServerCertificate
```
**例 2: この例では、`MyServerCertificate` という証明書を /Org1/Org2/ というパスに移動します。これにより、リソースの ARN が `arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate` に変更されます。**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewPath /Org1/Org2/
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMSigningCertificate`
<a name="iam_UpdateSigningCertificate_powershell_4_topic"></a>

次のコード例は、`Update-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`Bob` という名前の IAM ユーザーに関連付けられ、証明書 ID が `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` である証明書を更新し、無効としてマークされるようにします。**  

```
Update-IAMSigningCertificate -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU -UserName Bob -Status Inactive
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateSigningCertificate](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-IAMUser`
<a name="iam_UpdateUser_powershell_4_topic"></a>

次のコード例は、`Update-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、IAM ユーザー `Bob` の名前を `Robert` に変更します。**  

```
Update-IAMUser -UserName Bob -NewUserName Robert
```
**例 2: この例では、IAM ユーザー `Bob` のパスを `/Org1/Org2/` に変更します。これにより、ユーザーの ARN は実質的に `arn:aws:iam::123456789012:user/Org1/Org2/bob` に変更されます。**  

```
Update-IAMUser -UserName Bob -NewPath /Org1/Org2/
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateUser](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-IAMGroupPolicy`
<a name="iam_PutGroupPolicy_powershell_4_topic"></a>

次のコード例は、`Write-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`AppTesterPolicy` という名前のインラインポリシーを作成し、IAM グループ `AppTesters` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容がファイル `apptesterpolicy.json` に送られます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMGroupPolicy -GroupName AppTesters -PolicyName AppTesterPolicy -PolicyDocument (Get-Content -Raw apptesterpolicy.json)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutGroupPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-IAMRolePolicy`
<a name="iam_PutRolePolicy_powershell_4_topic"></a>

次のコード例は、`Write-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`FedTesterRolePolicy` という名前のインラインポリシーを作成し、IAM ロール `FedTesterRole` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容は、ファイル `FedTesterPolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMRolePolicy -RoleName FedTesterRole -PolicyName FedTesterRolePolicy -PolicyDocument (Get-Content -Raw FedTesterPolicy.json)
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[PutRolePolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Write-IAMUserPolicy`
<a name="iam_PutUserPolicy_powershell_4_topic"></a>

次のコード例は、`Write-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`EC2AccessPolicy` という名前のインラインポリシーを作成し、IAM ユーザー `Bob` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容は、ファイル `EC2AccessPolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutUserPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Kinesis の例
<a name="powershell_4_kinesis_code_examples"></a>

次のコード例は、Kinesis で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-KINRecord`
<a name="kinesis_GetRecords_powershell_4_topic"></a>

次のコード例は、`Get-KINRecord` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、一連の 1 つ以上のレコードからデータを返して抽出する方法を示しています。Get-KINRecord に供給されたイテレータは、この例で変数 \$1records にキャプチャされるレコードの開始位置を決定します。その後、\$1records コレクションにインデックスを付けることで、個々のレコードにアクセスできます。レコード内のデータが UTF-8 でエンコードされたテキストであると仮定すると、最終コマンドは、オブジェクト内の MemoryStream からデータを抽出してテキストとしてコンソールに返す方法を示します。**  

```
$records
$records = Get-KINRecord -ShardIterator "AAAAAAAAAAGIc....9VnbiRNaP"
```
**出力:**  

```
MillisBehindLatest NextShardIterator            Records
------------------ -----------------            -------
0                  AAAAAAAAAAERNIq...uDn11HuUs  {Key1, Key2}
```

```
$records.Records[0]
```
**出力:**  

```
ApproximateArrivalTimestamp Data                   PartitionKey SequenceNumber
--------------------------- ----                   ------------ --------------
3/7/2016 5:14:33 PM         System.IO.MemoryStream Key1         4955986459776...931586
```

```
[Text.Encoding]::UTF8.GetString($records.Records[0].Data.ToArray())
```
**出力:**  

```
test data from string
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetRecords](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-KINShardIterator`
<a name="kinesis_GetShardIterator_powershell_4_topic"></a>

次のコード例は、`Get-KINShardIterator` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたシャードと開始位置のシャードイテレータを返します。シャード識別子とシーケンス番号の詳細は、返されたストリームオブジェクトのシャードコレクションを参照することで、Get-KINStream コマンドレットの出力から取得できます。返されたイテレータを Get-KINRecord コマンドレットとともに使用して、シャード内のデータレコードをプルできます。**  

```
Get-KINShardIterator -StreamName "mystream" -ShardId "shardId-000000000000" -ShardIteratorType AT_SEQUENCE_NUMBER -StartingSequenceNumber "495598645..."
```
**出力:**  

```
AAAAAAAAAAGIc....9VnbiRNaP
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetShardIterator](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-KINStream`
<a name="kinesis_DescribeStream_powershell_4_topic"></a>

次のコード例は、`Get-KINStream` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたストリームの詳細を返します。**  

```
Get-KINStream -StreamName "mystream"
```
**出力:**  

```
HasMoreShards        : False
RetentionPeriodHours : 24
Shards               : {}
StreamARN            : arn:aws:kinesis:us-west-2:123456789012:stream/mystream
StreamName           : mystream
StreamStatus         : ACTIVE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeStream](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-KINStream`
<a name="kinesis_CreateStream_powershell_4_topic"></a>

次のコード例は、`New-KINStream` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 新しいストリームを作成します。デフォルトでは、このコマンドレットは出力を返さないため、後で使用するために -StreamName パラメータに指定された値を返すために -PassThru スイッチが追加されます。**  

```
$streamName = New-KINStream -StreamName "mystream" -ShardCount 1 -PassThru
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateStream](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-KINStream`
<a name="kinesis_DeleteStream_powershell_4_topic"></a>

次のコード例は、`Remove-KINStream` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたストリームを削除します。コマンドを実行する前に確認を求められます。確認メッセージを非表示にするには -Force スイッチを使用します。**  

```
Remove-KINStream -StreamName "mystream"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteStream](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-KINRecord`
<a name="kinesis_PutRecord_powershell_4_topic"></a>

次のコード例は、`Write-KINRecord` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: -Text パラメータに指定された文字列を含むレコードを書き込みます。**  

```
Write-KINRecord -Text "test data from string" -StreamName "mystream" -PartitionKey "Key1"
```
**例 2: 指定されたファイルに含まれるデータを含むレコードを書き込みます。ファイルはバイトのシーケンスとして扱われるため、テキストが含まれている場合は、このコマンドレットで使用する前に、必要なエンコードで記述する必要があります。**  

```
Write-KINRecord -FilePath "C:\TestData.txt" -StreamName "mystream" -PartitionKey "Key2"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutRecord](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Lambda の例
<a name="powershell_4_lambda_code_examples"></a>

次のコード例は、Lambda で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-LMResourceTag`
<a name="lambda_TagResource_powershell_4_topic"></a>

次のコード例は、`Add-LMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 3 つのタグ (Washington、Oregon、California) およびそれぞれに関連付けされた値を、ARN で識別される指定の関数に追加します。**  

```
Add-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -Tag @{ "Washington" = "Olympia"; "Oregon" = "Salem"; "California" = "Sacramento" }
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMAccountSetting`
<a name="lambda_GetAccountSettings_powershell_4_topic"></a>

次のコード例は、`Get-LMAccountSetting` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントの制限値と使用量を比較するための情報を表示します。**  

```
Get-LMAccountSetting | Select-Object @{Name="TotalCodeSizeLimit";Expression={$_.AccountLimit.TotalCodeSize}}, @{Name="TotalCodeSizeUsed";Expression={$_.AccountUsage.TotalCodeSize}}
```
**出力:**  

```
TotalCodeSizeLimit TotalCodeSizeUsed
------------------ -----------------
       80530636800          15078795
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAccountSettings](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMAlias`
<a name="lambda_GetAlias_powershell_4_topic"></a>

次のコード例は、`Get-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、特定の Lambda 関数エイリアスのルーティング設定の重点を取得します。**  

```
Get-LMAlias -FunctionName "MylambdaFunction123" -Name "newlabel1" -Select RoutingConfig
```
**出力:**  

```
AdditionalVersionWeights
------------------------
{[1, 0.6]}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAlias](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMFunctionConcurrency`
<a name="lambda_GetFunctionConcurrency_powershell_4_topic"></a>

次のコード例は、`Get-LMFunctionConcurrency` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数の予約済み同時実行数が取得されます**  

```
Get-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -Select *
```
**出力:**  

```
ReservedConcurrentExecutions
----------------------------
100
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetFunctionConcurrency](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMFunctionConfiguration`
<a name="lambda_GetFunctionConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-LMFunctionConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数のバージョン固有設定を返します。**  

```
Get-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Qualifier "PowershellAlias"
```
**出力:**  

```
CodeSha256                 : uWOW0R7z+f0VyLuUg7+/D08hkMFsq0SF4seuyUZJ/R8=
CodeSize                   : 1426
DeadLetterConfig           : Amazon.Lambda.Model.DeadLetterConfig
Description                : Verson 3 to test Aliases
Environment                : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn                : arn:aws:lambda:us-east-1:123456789012:function:MylambdaFunction123
                             :PowershellAlias
FunctionName               : MylambdaFunction123
Handler                    : lambda_function.launch_instance
KMSKeyArn                  : 
LastModified               : 2019-12-25T09:52:59.872+0000
LastUpdateStatus           : Successful
LastUpdateStatusReason     : 
LastUpdateStatusReasonCode : 
Layers                     : {}
MasterArn                  : 
MemorySize                 : 128
RevisionId                 : 5d7de38b-87f2-4260-8f8a-e87280e10c33
Role                       : arn:aws:iam::123456789012:role/service-role/lambda
Runtime                    : python3.8
State                      : Active
StateReason                : 
StateReasonCode            : 
Timeout                    : 600
TracingConfig              : Amazon.Lambda.Model.TracingConfigResponse
Version                    : 4
VpcConfig                  : Amazon.Lambda.Model.VpcConfigDetail
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[GetFunctionConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Get-LMFunctionList`
<a name="lambda_ListFunctions_powershell_4_topic"></a>

次のコード例は、`Get-LMFunctionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、コードサイズ順にすべての Lambda 関数を表示します**  

```
Get-LMFunctionList | Sort-Object -Property CodeSize | Select-Object FunctionName, RunTime, Timeout, CodeSize
```
**出力:**  

```
FunctionName                                                 Runtime   Timeout CodeSize
------------                                                 -------   ------- --------
test                                                         python2.7       3      243
MylambdaFunction123                                          python3.8     600      659
myfuncpython1                                                python3.8     303      675
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListFunctions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMPolicy`
<a name="lambda_GetPolicy_powershell_4_topic"></a>

次のコード例は、`Get-LMPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した Lambda 関数の関数ポリシーを表示します**  

```
Get-LMPolicy -FunctionName test -Select Policy
```
**出力:**  

```
{"Version":"2012-10-17",		 	 	 "Id":"default","Statement":[{"Sid":"xxxx","Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-1:123456789102:function:test"}]}
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[GetPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMProvisionedConcurrencyConfig`
<a name="lambda_GetProvisionedConcurrencyConfig_powershell_4_topic"></a>

次のコード例は、`Get-LMProvisionedConcurrencyConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数の指定されたエイリアスにプロビジョニングされた同時実行設定を取得します。**  

```
C:\>Get-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
**出力:**  

```
AllocatedProvisionedConcurrentExecutions : 0
AvailableProvisionedConcurrentExecutions : 0
LastModified                             : 2020-01-15T03:21:26+0000
RequestedProvisionedConcurrentExecutions : 70
Status                                   : IN_PROGRESS
StatusReason                             :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMProvisionedConcurrencyConfigList`
<a name="lambda_ListProvisionedConcurrencyConfigs_powershell_4_topic"></a>

次のコード例は、`Get-LMProvisionedConcurrencyConfigList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数にプロビジョニングされた同時実行設定のリストを取得します。**  

```
Get-LMProvisionedConcurrencyConfigList -FunctionName "MylambdaFunction123"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListProvisionedConcurrencyConfigs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMResourceTag`
<a name="lambda_ListTags_powershell_4_topic"></a>

次のコード例は、`Get-LMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定した関数に現在設定されているタグとその値を取得します。**  

```
Get-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
**出力:**  

```
Key        Value
---        -----
California Sacramento
Oregon     Salem
Washington Olympia
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-LMVersionsByFunction`
<a name="lambda_ListVersionsByFunction_powershell_4_topic"></a>

次のコード例は、`Get-LMVersionsByFunction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数の各バージョンのバージョン固有設定に関するリストを返します。**  

```
Get-LMVersionsByFunction -FunctionName "MylambdaFunction123"
```
**出力:**  

```
FunctionName        Runtime   MemorySize Timeout CodeSize LastModified                 RoleName
------------        -------   ---------- ------- -------- ------------                 --------
MylambdaFunction123 python3.8        128     600      659 2020-01-10T03:20:56.390+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:19:02.238+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:39:36.779+0000 lambda
MylambdaFunction123 python3.8        128     600     1426 2019-12-25T09:52:59.872+0000 lambda
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListVersionsByFunction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-LMAlias`
<a name="lambda_CreateAlias_powershell_4_topic"></a>

次のコード例は、`New-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたバージョンおよびルーティング設定の新しい Lambda エイリアスを作成し、受信する呼び出しリクエストの割合を指定します。**  

```
New-LMAlias -FunctionName "MylambdaFunction123" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6} -Description "Alias for version 4" -FunctionVersion 4 -Name "PowershellAlias"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAlias](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Publish-LMFunction`
<a name="lambda_CreateFunction_powershell_4_topic"></a>

次のコード例は、`Publish-LMFunction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、 AWS Lambda で MyFunction という名前の新しい C\$1 (dotnetcore1.0 ランタイム) 関数を作成し、ローカルファイルシステムの zip ファイルから関数のコンパイルされたバイナリを提供します (相対パスまたは絶対パスを使用できます）。C\$1 Lambda 関数は、AssemblyName::Namespace.ClassName::MethodName の指定を使用して関数のハンドラーを指定します。ハンドラー仕様のアセンブリ名 (.dll サフィックスなし)、名前空間、クラス名、メソッド名の部分を適切に置き換える必要があります。新しい関数には、指定された値で「envvar1」および「envvar2」の環境変数が設定されます。**  

```
Publish-LMFunction -Description "My C# Lambda Function" `
        -FunctionName MyFunction `
        -ZipFilename .\MyFunctionBinaries.zip `
        -Handler "AssemblyName::Namespace.ClassName::MethodName" `
        -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" `
        -Runtime dotnetcore1.0 `
        -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
```
**出力:**  

```
CodeSha256       : /NgBMd...gq71I=
CodeSize         : 214784
DeadLetterConfig :
Description      : My C# Lambda Function
Environment      : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn      : arn:aws:lambda:us-west-2:123456789012:function:ToUpper
FunctionName     : MyFunction
Handler          : AssemblyName::Namespace.ClassName::MethodName
KMSKeyArn        :
LastModified     : 2016-12-29T23:50:14.207+0000
MemorySize       : 128
Role             : arn:aws:iam::123456789012:role/LambdaFullExecRole
Runtime          : dotnetcore1.0
Timeout          : 3
Version          : $LATEST
VpcConfig        :
```
**例 2: この例は前の例と似ていますが、関数バイナリが最初に Amazon S3 バケット (目的の Lambda 関数と同じリージョンにある必要がある) にアップロードされ、結果の S3 オブジェクトが関数の作成時に参照される点が異なります。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key MyFunctionBinaries.zip -File .\MyFunctionBinaries.zip    
Publish-LMFunction -Description "My C# Lambda Function" `
        -FunctionName MyFunction `
        -BucketName amzn-s3-demo-bucket `
        -Key MyFunctionBinaries.zip `
        -Handler "AssemblyName::Namespace.ClassName::MethodName" `
        -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" `
        -Runtime dotnetcore1.0 `
        -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateFunction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Publish-LMVersion`
<a name="lambda_PublishVersion_powershell_4_topic"></a>

次のコード例は、`Publish-LMVersion` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数コードの既存のスナップショットのバージョンを作成します**  

```
Publish-LMVersion -FunctionName "MylambdaFunction123" -Description "Publishing Existing Snapshot of function code as a  new version through Powershell"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PublishVersion](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-LMAlias`
<a name="lambda_DeleteAlias_powershell_4_topic"></a>

次のコード例は、`Remove-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、コマンドに記述された Lambda 関数のエイリアスを削除します。**  

```
Remove-LMAlias -FunctionName "MylambdaFunction123" -Name "NewAlias"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteAlias](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-LMFunction`
<a name="lambda_DeleteFunction_powershell_4_topic"></a>

次のコード例は、`Remove-LMFunction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数の特定のバージョンを削除します。**  

```
Remove-LMFunction -FunctionName "MylambdaFunction123" -Qualifier '3'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteFunction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-LMFunctionConcurrency`
<a name="lambda_DeleteFunctionConcurrency_powershell_4_topic"></a>

次のコード例は、`Remove-LMFunctionConcurrency` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数の関数同時実行数を削除します。**  

```
Remove-LMFunctionConcurrency -FunctionName "MylambdaFunction123"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteFunctionConcurrency](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-LMPermission`
<a name="lambda_RemovePermission_powershell_4_topic"></a>

次のコード例は、`Remove-LMPermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Lambda 関数の指定された StatementId の関数ポリシーを削除します。**  

```
$policy =  Get-LMPolicy -FunctionName "MylambdaFunction123" -Select Policy | ConvertFrom-Json| Select-Object -ExpandProperty Statement
Remove-LMPermission -FunctionName "MylambdaFunction123" -StatementId $policy[0].Sid
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemovePermission](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-LMProvisionedConcurrencyConfig`
<a name="lambda_DeleteProvisionedConcurrencyConfig_powershell_4_topic"></a>

次のコード例は、`Remove-LMProvisionedConcurrencyConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、特定のエイリアスのプロビジョニングされた同時実行設定を削除します。**  

```
Remove-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-LMResourceTag`
<a name="lambda_UntagResource_powershell_4_topic"></a>

次のコード例は、`Remove-LMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 提供されたタグを関数から削除します。-Force スイッチが指定されていない限り、cmdlet は続行する前に確認を求めます。タグを削除するため、サービスが 1 回呼び出されます。**  

```
Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -TagKey "Washington","Oregon","California"
```
**例 2: 提供されたタグを関数から削除します。-Force スイッチが指定されていない限り、cmdlet は続行する前に確認を求めます。提供されたタグにつき、サービスに 1 回呼び出しが行われます。**  

```
"Washington","Oregon","California" | Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UntagResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-LMAlias`
<a name="lambda_UpdateAlias_powershell_4_topic"></a>

次のコード例は、`Update-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、既存の Lambda 関数エイリアスの設定を更新します。RoutingConfiguration の値を更新し、トラフィックの 60% (0.6) をバージョン 1 に変換します。**  

```
Update-LMAlias -FunctionName "MylambdaFunction123" -Description " Alias for version 2" -FunctionVersion 2 -Name "newlabel1" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateAlias](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-LMFunctionCode`
<a name="lambda_UpdateFunctionCode_powershell_4_topic"></a>

次のコード例は、`Update-LMFunctionCode` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「MyFunction」という名前の関数を、指定された zip ファイルに含まれる新しいコンテンツで更新します。C\$1 .NET Core Lambda 関数には、zip ファイルはコンパイルされたアセンブリが含まれている必要があります。**  

```
Update-LMFunctionCode -FunctionName MyFunction -ZipFilename .\UpdatedCode.zip
```
**例 2: この例は前の例と似ていますが、更新されたコードを含む Amazon S3 オブジェクトを使用して関数を更新します。**  

```
Update-LMFunctionCode -FunctionName MyFunction -BucketName amzn-s3-demo-bucket -Key UpdatedCode.zip
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateFunctionCode](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-LMFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_powershell_4_topic"></a>

次のコード例は、`Update-LMFunctionConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、既存の Lambda 関数の設定を更新します**  

```
Update-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Handler "lambda_function.launch_instance" -Timeout 600 -Environment_Variable @{ "envvar1"="value";"envvar2"="value" } -Role arn:aws:iam::123456789101:role/service-role/lambda -DeadLetterConfig_TargetArn arn:aws:sns:us-east-1: 123456789101:MyfirstTopic
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-LMFunctionConcurrency`
<a name="lambda_PutFunctionConcurrency_powershell_4_topic"></a>

次のコード例は、`Write-LMFunctionConcurrency` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、関数全体の同時実行設定を適用します。**  

```
Write-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -ReservedConcurrentExecution 100
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[PutFunctionConcurrency](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-LMProvisionedConcurrencyConfig`
<a name="lambda_PutProvisionedConcurrencyConfig_powershell_4_topic"></a>

次のコード例は、`Write-LMProvisionedConcurrencyConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、プロビジョニングされた同時実行設定を関数のエイリアスに追加します。**  

```
Write-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -ProvisionedConcurrentExecution 20 -Qualifier "NewAlias1"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon ML の例
<a name="powershell_4_machine-learning_code_examples"></a>

次のコード例は、Amazon ML で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-MLBatchPrediction`
<a name="machine-learning_GetBatchPrediction_powershell_4_topic"></a>

次のコード例は、`Get-MLBatchPrediction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: id ID を含むバッチ予測の詳細なメタデータを返します。**  

```
Get-MLBatchPrediction -BatchPredictionId ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBatchPrediction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLBatchPredictionList`
<a name="machine-learning_DescribeBatchPredictions_powershell_4_topic"></a>

次のコード例は、`Get-MLBatchPredictionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: リクエストで指定された検索条件に一致するすべての BatchPredictions および関連するデータレコードのリストを返します。**  

```
Get-MLBatchPredictionList
```
**例 2: ステータスが COMPLETED であるすべての BatchPredictions のリストを返します。**  

```
Get-MLBatchPredictionList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeBatchPredictions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLDataSource`
<a name="machine-learning_GetDataSource_powershell_4_topic"></a>

次のコード例は、`Get-MLDataSource` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ID を含む DataSource のメタデータ、ステータス、データファイル情報を返します。**  

```
Get-MLDataSource -DataSourceId ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDataSource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLDataSourceList`
<a name="machine-learning_DescribeDataSources_powershell_4_topic"></a>

次のコード例は、`Get-MLDataSourceList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべての DataSourcesとそれに関連するデータレコードのリストを返します。**  

```
Get-MLDataSourceList
```
**例 2: ステータスが COMPLETED であるすべての DataSources のリストを返します。**  

```
Get-MLDataDourceList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDataSources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLEvaluation`
<a name="machine-learning_GetEvaluation_powershell_4_topic"></a>

次のコード例は、`Get-MLEvaluation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ID を含む Evaluation のメタデータとステータスを返します。**  

```
Get-MLEvaluation -EvaluationId ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetEvaluation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLEvaluationList`
<a name="machine-learning_DescribeEvaluations_powershell_4_topic"></a>

次のコード例は、`Get-MLEvaluationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべての Evaluation リソースのリストを返します**  

```
Get-MLEvaluationList
```
**例 2: ステータスが COMPLETED であるすべての Evaulation のリストを返します。**  

```
Get-MLEvaluationList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEvaluations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLModel`
<a name="machine-learning_GetMLModel_powershell_4_topic"></a>

次のコード例は、`Get-MLModel` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ID を含む MLModel の詳細メタデータ、ステータス、スキーマ、データファイル情報を返します。**  

```
Get-MLModel -ModelId ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetMLModel](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLModelList`
<a name="machine-learning_DescribeMLModels_powershell_4_topic"></a>

次のコード例は、`Get-MLModelList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべての Model とそれに関連するデータレコードのリストを返します。 **  

```
Get-MLModelList
```
**例 2: ステータスが COMPLETED であるすべての Model のリストを返します。**  

```
Get-MLModelList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMLModels](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-MLPrediction`
<a name="machine-learning_Predict_powershell_4_topic"></a>

次のコード例は、`Get-MLPrediction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ID を含むモデルのリアルタイム予測エンドポイント URL にレコードを送信します。**  

```
Get-MLPrediction -ModelId ID -PredictEndpoint URL -Record @{"A" = "B"; "C" = "D";}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Predict](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-MLBatchPrediction`
<a name="machine-learning_CreateBatchPrediction_powershell_4_topic"></a>

次のコード例は、`New-MLBatchPrediction` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ID を含むモデルの新しいバッチ予測リクエストを作成し、指定 S3 の場所に出力を配置します。**  

```
New-MLBatchPrediction -ModelId ID -Name NAME -OutputURI s3://...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateBatchPrediction](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-MLDataSourceFromS3`
<a name="machine-learning_CreateDataSourceFromS3_powershell_4_topic"></a>

次のコード例は、`New-MLDataSourceFromS3` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 名前が NAME、スキーマが SCHEMA である S3 の場所のデータを使用してデータソースを作成します。**  

```
New-MLDataSourceFromS3 -Name NAME -ComputeStatistics $true -DataSpec_DataLocationS3 "s3://BUCKET/KEY" -DataSchema SCHEMA
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDataSourceFromS3](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-MLEvaluation`
<a name="machine-learning_CreateEvaluation_powershell_4_topic"></a>

次のコード例は、`New-MLEvaluation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定のデータソース ID とモデル ID の評価を作成します**  

```
New-MLEvaluation -Name NAME -DataSourceId DSID -ModelId MID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateEvaluation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-MLModel`
<a name="machine-learning_CreateMLModel_powershell_4_topic"></a>

次のコード例は、`New-MLModel` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: トレーニングデータを使用して新しいモデルを作成します。**  

```
New-MLModel -Name NAME -ModelType BINARY -Parameter @{...} -TrainingDataSourceId ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateMLModel](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-MLRealtimeEndpoint`
<a name="machine-learning_CreateRealtimeEndpoint_powershell_4_topic"></a>

次のコード例は、`New-MLRealtimeEndpoint` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定モデル ID の新しいリアルタイム予測エンドポイントを作成します。**  

```
New-MLRealtimeEndpoint -ModelId ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateRealtimeEndpoint](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Macie の例
<a name="powershell_4_macie2_code_examples"></a>

次のコード例は、Macie で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-MAC2FindingList`
<a name="macie2_ListFindings_powershell_4_topic"></a>

次のコード例は、`Get-MAC2FindingList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「CREDIT\$1CARD\$1NUMBER」または「US\$1SOCIAL\$1SECURITY\$1NUMBER」タイプの機密データ検出を含む検出結果の FindingIds のリストを返します。**  

```
$criterionAddProperties = New-Object Amazon.Macie2.Model.CriterionAdditionalProperties

$criterionAddProperties.Eq = @(
"CREDIT_CARD_NUMBER"
"US_SOCIAL_SECURITY_NUMBER"
)

$FindingCriterion = @{
'classificationDetails.result.sensitiveData.detections.type' = [Amazon.Macie2.Model.CriterionAdditionalProperties]$criterionAddProperties
}

Get-MAC2FindingList -FindingCriteria_Criterion $FindingCriterion -MaxResult 5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListFindings](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS の料金表 Tools for PowerShell V4 を使用した の例
<a name="powershell_4_pricing_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS の料金表。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-PLSAttributeValue`
<a name="pricing_GetAttributeValues_powershell_4_topic"></a>

次のコード例は、`Get-PLSAttributeValue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: us-east-1 リージョンの Amazon EC2 の属性「volumeType」の値を返します。**  

```
Get-PLSAttributeValue -ServiceCode AmazonEC2 -AttributeName "volumeType" -region us-east-1
```
**出力:**  

```
Value
-----
Cold HDD
General Purpose
Magnetic
Provisioned IOPS
Throughput Optimized HDD
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAttributeValues](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-PLSProduct`
<a name="pricing_GetProducts_powershell_4_topic"></a>

次のコード例は、`Get-PLSProduct` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: Amazon EC2 のすべての製品の詳細を返します。**  

```
Get-PLSProduct -ServiceCode AmazonEC2 -Region us-east-1
```
**出力:**  

```
{"product":{"productFamily":"Compute Instance","attributes":{"enhancedNetworkingSupported":"Yes","memory":"30.5 GiB","dedicatedEbsThroughput":"800 Mbps","vcpu":"4","locationType":"AWS Region","storage":"EBS only","instanceFamily":"Memory optimized","operatingSystem":"SUSE","physicalProcessor":"Intel Xeon E5-2686 v4 (Broadwell)","clockSpeed":"2.3 GHz","ecu":"Variable","networkPerformance":"Up to 10 Gigabit","servicename":"Amazon Elastic Compute Cloud","instanceType":"r4.xlarge","tenancy":"Shared","usagetype":"USW2-BoxUsage:r4.xlarge","normalizationSizeFactor":"8","processorFeatures":"Intel AVX, Intel AVX2, Intel Turbo","servicecode":"AmazonEC2","licenseModel":"No License required","currentGeneration":"Yes","preInstalledSw":"NA","location":"US West (Oregon)","processorArchitecture":"64-bit","operation":"RunInstances:000g"},...
```
**例 2: us-east-1 リージョン内の Amazon EC2 のデータのうち、SSD ベースの「General Purpose」のボリュームタイプでフィルタリングされたデータを返します。**  

```
Get-PLSProduct -ServiceCode AmazonEC2 -Filter @{Type="TERM_MATCH";Field="volumeType";Value="General Purpose"},@{Type="TERM_MATCH";Field="storageMedia";Value="SSD-backed"} -Region us-east-1
```
**出力:**  

```
{"product":{"productFamily":"Storage","attributes":{"storageMedia":"SSD-backed","maxThroughputvolume":"160 MB/sec","volumeType":"General Purpose","maxIopsvolume":"10000",...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetProducts](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-PLSService`
<a name="pricing_DescribeServices_powershell_4_topic"></a>

次のコード例は、`Get-PLSService` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: us-east-1 リージョンで使用可能なすべてのサービスコードのメタデータを返します。**  

```
Get-PLSService -Region us-east-1
```
**出力:**  

```
AttributeNames                                                  ServiceCode
--------------                                                  -----------
{productFamily, servicecode, groupDescription, termType...}     AWSBudgets
{productFamily, servicecode, termType, usagetype...}            AWSCloudTrail
{productFamily, servicecode, termType, usagetype...}            AWSCodeCommit
{productFamily, servicecode, termType, usagetype...}            AWSCodeDeploy
{productFamily, servicecode, termType, usagetype...}            AWSCodePipeline
{productFamily, servicecode, termType, usagetype...}            AWSConfig
...
```
**例 2: us-east-1 リージョンの Amazon EC2 サービスのメタデータを返します。**  

```
Get-PLSService -ServiceCode AmazonEC2 -Region us-east-1
```
**出力:**  

```
AttributeNames                                                         ServiceCode
--------------                                                         -----------
{volumeType, maxIopsvolume, instanceCapacity10xlarge, locationType...} AmazonEC2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeServices](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Resource Groups の例
<a name="powershell_4_resource-groups_code_examples"></a>

次のコード例は、Resource Groups で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-RGResourceTag`
<a name="resource-groups_Tag_powershell_4_topic"></a>

次のコード例は、`Add-RGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリソースグループ ARN に値「workboxes」を持つタグキー「Instances」を追加します。**  

```
Add-RGResourceTag -Tag @{Instances="workboxes"} -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes
```
**出力:**  

```
Arn                                                            Tags
---                                                            ----
arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes {[Instances, workboxes]}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Tag](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Find-RGResource`
<a name="resource-groups_SearchResources_powershell_4_topic"></a>

次のコード例は、`Find-RGResource` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、タグフィルターを使用してインスタンスリソースタイプの ResourceQuery を作成し、リソースを検索します。**  

```
$query = [Amazon.ResourceGroups.Model.ResourceQuery]::new()
$query.Type = [Amazon.ResourceGroups.QueryType]::TAG_FILTERS_1_0
$query.Query = ConvertTo-Json -Compress -Depth 4 -InputObject @{
  ResourceTypeFilters = @('AWS::EC2::Instance')
  TagFilters = @(@{
    Key = 'auto'
    Values = @('no')
  })
 }

Find-RGResource -ResourceQuery $query | Select-Object -ExpandProperty ResourceIdentifiers
```
**出力:**  

```
ResourceArn                                                     ResourceType
-----------                                                     ------------
arn:aws:ec2:eu-west-1:123456789012:instance/i-0123445b6cb7bd67b AWS::EC2::Instance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SearchResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGGroup`
<a name="resource-groups_GetGroup_powershell_4_topic"></a>

次のコード例は、`Get-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、グループ名に従ってリソースグループを取得します。**  

```
Get-RGGroup -GroupName auto-no
```
**出力:**  

```
Description GroupArn                                                     Name
----------- --------                                                     ----
            arn:aws:resource-groups:eu-west-1:123456789012:group/auto-no auto-no
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGGroupList`
<a name="resource-groups_ListGroups_powershell_4_topic"></a>

次のコード例は、`Get-RGGroupList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、既に作成されたリソースグループを一覧表示します。**  

```
Get-RGGroupList
```
**出力:**  

```
GroupArn                                                                  GroupName
--------                                                                  ---------
arn:aws:resource-groups:eu-west-1:123456789012:group/auto-no              auto-no
arn:aws:resource-groups:eu-west-1:123456789012:group/auto-yes             auto-yes
arn:aws:resource-groups:eu-west-1:123456789012:group/build600             build600
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGGroupQuery`
<a name="resource-groups_GetGroupQuery_powershell_4_topic"></a>

次のコード例は、`Get-RGGroupQuery` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリソースグループのリソースクエリを取得します。**  

```
Get-RGGroupQuery -GroupName auto-no | Select-Object -ExpandProperty ResourceQuery
```
**出力:**  

```
Query                                                                                        Type
-----                                                                                        ----
{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"auto","Values":["no"]}]} TAG_FILTERS_1_0
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetGroupQuery](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGGroupResourceList`
<a name="resource-groups_ListGroupResources_powershell_4_topic"></a>

次のコード例は、`Get-RGGroupResourceList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リソースタイプでフィルタリングされたグループリソースを一覧表示します。**  

```
Get-RGGroupResourceList -Filter @{Name="resource-type";Values="AWS::EC2::Instance"} -GroupName auto-yes | Select-Object -ExpandProperty ResourceIdentifiers
```
**出力:**  

```
ResourceArn                                                     ResourceType
-----------                                                     ------------
arn:aws:ec2:eu-west-1:123456789012:instance/i-0123bc45b567890e1 AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-0a1caf2345f67d8dc AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-0fd12dd3456789012 AWS::EC2::Instance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListGroupResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGResourceTag`
<a name="resource-groups_GetTags_powershell_4_topic"></a>

次のコード例は、`Get-RGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定されたリソースグループ ARN のタグを一覧表示します。**  

```
Get-RGResourceTag -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes
```
**出力:**  

```
Key       Value
---       -----
Instances workboxes
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-RGGroup`
<a name="resource-groups_CreateGroup_powershell_4_topic"></a>

次のコード例は、`New-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、TestPowerShellGroup という名前の新しいタグベースの AWS Resource Groups リソースグループを作成します。グループには、タグキー「Name」とタグ値「test2」でタグ付けされた現在のリージョンの Amazon EC2 インスタンスが含まれます。コマンドは、クエリとグループのタイプ、および操作の結果を返します。**  

```
$ResourceQuery = New-Object -TypeName Amazon.ResourceGroups.Model.ResourceQuery
$ResourceQuery.Type = "TAG_FILTERS_1_0"
$ResourceQuery.Query = '{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"Name","Values":["test2"]}]}'
$ResourceQuery

New-RGGroup -Name TestPowerShellGroup -ResourceQuery $ResourceQuery -Description "Test resource group."
```
**出力:**  

```
Query                                                                                           Type           
-----                                                                                           ----           
{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"Name","Values":["test2"]}]} TAG_FILTERS_1_0

LoggedAt         : 11/20/2018 2:40:59 PM
Group            : Amazon.ResourceGroups.Model.Group
ResourceQuery    : Amazon.ResourceGroups.Model.ResourceQuery
Tags             : {}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 338
HttpStatusCode   : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-RGGroup`
<a name="resource-groups_DeleteGroup_powershell_4_topic"></a>

次のコード例は、`Remove-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、名前付きリソースグループを削除します。**  

```
Remove-RGGroup -GroupName non-tag-cfn-elbv2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-RGGroup (DeleteGroup)" on target "non-tag-cfn-elbv2".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Description GroupArn                                                               Name
----------- --------                                                               ----
            arn:aws:resource-groups:eu-west-1:123456789012:group/non-tag-cfn-elbv2 non-tag-cfn-elbv2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-RGResourceTag`
<a name="resource-groups_Untag_powershell_4_topic"></a>

次のコード例は、`Remove-RGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リソースグループから指定されたタグを削除します。**  

```
Remove-RGResourceTag -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes -Key Instances
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-RGResourceTag (Untag)" on target "arn:aws:resource-groups:eu-west-1:933303704102:group/workboxes".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Arn                                                            Keys
---                                                            ----
arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes {Instances}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Untag](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-RGGroup`
<a name="resource-groups_UpdateGroup_powershell_4_topic"></a>

次のコード例は、`Update-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、グループの説明を更新します。**  

```
Update-RGGroup -GroupName auto-yes -Description "Instances auto-remove"
```
**出力:**  

```
Description             GroupArn                                                      Name
-----------             --------                                                      ----
Instances to be cleaned arn:aws:resource-groups:eu-west-1:123456789012:group/auto-yes auto-yes
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)*の「[UpdateGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-RGGroupQuery`
<a name="resource-groups_UpdateGroupQuery_powershell_4_topic"></a>

次のコード例は、`Update-RGGroupQuery` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、クエリオブジェクトを作成し、グループのクエリを更新します。**  

```
$query = [Amazon.ResourceGroups.Model.ResourceQuery]::new()
$query.Type = [Amazon.ResourceGroups.QueryType]::TAG_FILTERS_1_0
$query.Query = @{
  ResourceTypeFilters = @('AWS::EC2::Instance')
  TagFilters = @(@{
  Key='Environment'
  Values='Build600.11'
  })
} | ConvertTo-Json -Compress -Depth 4

Update-RGGroupQuery -GroupName build600 -ResourceQuery $query
```
**出力:**  

```
GroupName ResourceQuery
--------- -------------
build600  Amazon.ResourceGroups.Model.ResourceQuery
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateGroupQuery](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用したリソースグループタグ付け API の例
<a name="powershell_4_resource-groups-tagging-api_code_examples"></a>

次のコード例は、Resource Groups Tagging API で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-RGTResourceTag`
<a name="resource-groups-tagging-api_TagResources_powershell_4_topic"></a>

次のコード例は、`Add-RGTResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、値「beta」と「preprod\$1test」を含むタグキー「stage」と「version」を Amazon S3 バケットと Amazon DynamoDB テーブルに追加します。タグを適用するため、サービスが 1 回呼び出されます。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

Add-RGTResourceTag -ResourceARNList $arn1,$arn2 -Tag @{ "stage"="beta"; "version"="preprod_test" }
```
**例 2: この例では、指定されたタグと値を Amazon S3 バケットと Amazon DynamoDB テーブルに追加します。コマンドレットにパイプされたリソース ARN ごとに 1 回ずつ、2 回サービスが呼び出されます。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

$arn1,$arn2 | Add-RGTResourceTag -Tag @{ "stage"="beta"; "version"="preprod_test" }
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TagResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGTResource`
<a name="resource-groups-tagging-api_GetResources_powershell_4_topic"></a>

次のコード例は、`Get-RGTResource` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: リージョン内のすべてのタグ付けされたリソースと、リソースに関連付けられたタグキーを返します。コマンドレットに -Region パラメータが指定されていない場合、シェルまたは EC2 インスタンスメタデータからリージョンを推測しようとします。**  

```
Get-RGTResource
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}   
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 2: リージョン内の指定されたタイプのタグ付けされたリソースをすべて返します。各サービス名とリソースタイプの文字列は、リソースの Amazon リソースネーム (ARN) に埋め込まれている文字列と同じです。**  

```
Get-RGTResource -ResourceType "s3"
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 3: リージョン内の指定されたタイプのタグ付けされたリソースをすべて返します。リソースタイプをコマンドレットにパイプすると、指定されたリソースタイプごとにサービスへの呼び出しが 1 回行われることに注意してください。**  

```
"dynamodb","s3" | Get-RGTResource
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}   
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 4: 指定されたフィルターに一致するタグ付けされたすべてのリソースを返します。**  

```
Get-RGTResource -TagFilter @{ Key="stage" }
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 5: 指定されたフィルターとリソースタイプに一致するタグ付けされたすべてのリソースを返します。**  

```
Get-RGTResource -TagFilter @{ Key="stage" } -ResourceType "dynamodb"
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}
```
**例 6: 指定されたフィルターに一致するタグ付けされたすべてのリソースを返します。**  

```
Get-RGTResource -TagFilter @{ Key="stage"; Values=@("beta","gamma") }
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGTTagKey`
<a name="resource-groups-tagging-api_GetTagKeys_powershell_4_topic"></a>

次のコード例は、`Get-RGTTagKey` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたリージョンのすべてのタグキーを返します。-Region パラメータが指定されていない場合、コマンドレットはデフォルトのシェルリージョンまたは EC2 インスタンスメタデータからリージョンを推測しようとします。タグキーは特定の順序では返されないことに注意してください。**  

```
Get-RGTTagKey -region us-west-2
```
**出力:**  

```
version
stage
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetTagKeys](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-RGTTagValue`
<a name="resource-groups-tagging-api_GetTagValues_powershell_4_topic"></a>

次のコード例は、`Get-RGTTagValue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: リージョン内の指定されたタグの値を返します。-Region パラメータが指定されていない場合、コマンドレットはデフォルトのシェルリージョンまたは EC2 インスタンスメタデータからリージョンを推測しようとします。**  

```
Get-RGTTagValue -Key "stage" -Region us-west-2
```
**出力:**  

```
beta
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetTagValues](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-RGTResourceTag`
<a name="resource-groups-tagging-api_UntagResources_powershell_4_topic"></a>

次のコード例は、`Remove-RGTResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: Amazon S3 バケットと Amazon DynamoDB テーブルからタグキー「stage」と「version」、および関連する値を削除します。タグを削除するために、サービスが 1 回呼び出されます。タグを削除する前に、コマンドレットで確認を求められます。確認を表示しないようにするには、-Force パラメータを追加します。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

Remove-RGTResourceTag -ResourceARNList $arn1,$arn2 -TagKey "stage","version"
```
**例 2: Amazon S3 バケットと Amazon DynamoDB テーブルからタグキー「stage」と「version」、および関連する値を削除します。コマンドレットにパイプされたリソース ARN ごとに 1 回ずつ、2 回サービスが呼び出されます。各呼び出しの前に、コマンドレットで確認を求められます。確認を表示しないようにするには、-Force パラメータを追加します。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

$arn1,$arn2 | Remove-RGTResourceTag -TagKey "stage","version"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UntagResources](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Route 53 の例
<a name="powershell_4_route-53_code_examples"></a>

次のコード例は、Route 53 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Edit-R53ResourceRecordSet`
<a name="route-53_ChangeResourceRecordSets_powershell_4_topic"></a>

次のコード例は、`Edit-R53ResourceRecordSet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、www.example.com の A レコードを作成し、test.example.com の A レコードを 192.0.2.3 から 192.0.2.1 に変更します。変更 TXT タイプのレコードの値は二重引用符で囲む必要があることに注意してください。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "TXT"
$change1.ResourceRecordSet.TTL = 600
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="item 1 item 2 item 3"})

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "DELETE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "test.example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.TTL = 600
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.3"})

$change3 = New-Object Amazon.Route53.Model.Change
$change3.Action = "CREATE"
$change3.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change3.ResourceRecordSet.Name = "test.example.com"
$change3.ResourceRecordSet.Type = "A"
$change3.ResourceRecordSet.TTL = 600
$change3.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.1"})

$params = @{
    HostedZoneId="Z1PA6795UKMFR9"
	ChangeBatch_Comment="This change batch creates a TXT record for www.example.com. and changes the A record for test.example.com. from 192.0.2.3 to 192.0.2.1."
	ChangeBatch_Change=$change1,$change2,$change3
}

Edit-R53ResourceRecordSet @params
```
**例 2: この例は、エイリアスリソースレコードセットの作成方法を示します。「Z222222222」は、エイリアスリソースレコードセットを作成する Amazon Route 53 ホストゾーンの ID です。「example.com」は、エイリアスを作成するゾーン頂点 Zone Apex で、「www.example.com」は、エイリアスを作成するサブドメインです。「Z1111111111111」はロードバランサーのホストゾーン ID の例で、「example-load-balancer-1111111111.us-east-1.elb.amazonaws.com」は Amazon Route 53 が example.com および www.example.com のクエリに応答するロードバランサードメイン名の例です。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $false

$params = @{
    HostedZoneId="Z222222222"
	ChangeBatch_Comment="This change batch creates two alias resource record sets, one for the zone apex, example.com, and one for www.example.com, that both point to example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
	ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**例 3: この例では、www.example.com の A レコードを 2 つ作成します。割合が 4 分の 1 (1/(1\$13)) の Amazon Route 53 は、最初のリソースレコードセット (192.0.2.9 と 192.0.2.10) の 2 つの値を使用して www.example.com のクエリに応答します。割合が 4 分の 3 (3/(1\$13)) の Amazon Route 53 は、2 番目のリソースレコードセット (192.0.2.11 と 192.0.2.12) の 2 つの値を使用して www.example.com のクエリに応答します。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "Rack 2, Positions 4 and 5"
$change1.ResourceRecordSet.Weight = 1
$change1.ResourceRecordSet.TTL = 600
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.9"})
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.10"})

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "www.example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "Rack 5, Positions 1 and 2"
$change2.ResourceRecordSet.Weight = 3
$change2.ResourceRecordSet.TTL = 600
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.11"})
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.12"})

$params = @{
    HostedZoneId="Z1PA6795UKMFR9"
    ChangeBatch_Comment="This change creates two weighted resource record sets, each of which has two values."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**例 4: この例は、example.com が加重エイリアスリソースレコードセットを作成するドメインであると仮定した、加重エイリアスリソースレコードセットの作成方法を示します。SetIdentifier は、2 つの加重エイリアスリソースレコードセットを相互に区別します。Name 要素と Type 要素が両方のリソースレコードセットに同じ値を持つため、この要素は必要です。Z1111111111111 および Z3333333333333 は、DNSName の値で指定された ELB ロードバランサーのホストゾーン ID の例です。example-load-balancer-2222222222.us-east-1.elb.amazonaws.com および example-load-balancer-4444444444.us-east-1.elb.amazonaws.com は Amazon Route 53 が example.com のクエリに応答する Elastic Load Balancing ドメインの例です。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "1"
$change1.ResourceRecordSet.Weight = 3
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-2222222222.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "2"
$change2.ResourceRecordSet.Weight = 1
$change2.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change2.ResourceRecordSet.AliasTarget.HostedZoneId = "Z3333333333333"
$change2.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-4444444444.us-east-1.elb.amazonaws.com."
$change2.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $false

$params = @{
    HostedZoneId="Z5555555555"
    ChangeBatch_Comment="This change batch creates two weighted alias resource record sets. Amazon Route 53 responds to queries for example.com with the first ELB domain 3/4ths of the times and the second one 1/4th of the time."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**例 5: この例では、レイテンシーエイリアスリソースレコードセットを 2 つ作成します。1 つは米国西部 (オレゴン) リージョン (us-west-2) の ELB ロードバランサー用で、もう 1 つはアジアパシフィック (シンガポール) リージョン (ap-southeast-1) のロードバランサー用です。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "Oregon load balancer 1"
$change1.ResourceRecordSet.Region = us-west-2
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-2222222222.us-west-2.elb.amazonaws.com"
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "Singapore load balancer 1"
$change2.ResourceRecordSet.Region = ap-southeast-1
$change2.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change2.ResourceRecordSet.AliasTarget.HostedZoneId = "Z2222222222222"
$change2.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.ap-southeast-1.elb.amazonaws.com"
$change2.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$params = @{
    HostedZoneId="Z5555555555"
    ChangeBatch_Comment="This change batch creates two latency resource record sets, one for the US West (Oregon) region and one for the Asia Pacific (Singapore) region."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ChangeResourceRecordSets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53AccountLimit`
<a name="route-53_GetAccountLimit_powershell_4_topic"></a>

次のコード例は、`Get-R53AccountLimit` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在のアカウントを使用して作成できるホストゾーンの最大数を返します。**  

```
Get-R53AccountLimit -Type MAX_HOSTED_ZONES_BY_OWNER
```
**出力:**  

```
15
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAccountLimit](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53CheckerIpRanges`
<a name="route-53_GetCheckerIpRanges_powershell_4_topic"></a>

次のコード例は、`Get-R53CheckerIpRanges` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Route53 ヘルスチェッカーの CIDR を返します。**  

```
Get-R53CheckerIpRanges
```
**出力:**  

```
15.177.2.0/23
15.177.6.0/23
15.177.10.0/23
15.177.14.0/23
15.177.18.0/23
15.177.22.0/23
15.177.26.0/23
15.177.30.0/23
15.177.34.0/23
15.177.38.0/23
15.177.42.0/23
15.177.46.0/23
15.177.50.0/23
15.177.54.0/23
15.177.58.0/23
15.177.62.0/23
54.183.255.128/26
54.228.16.0/26
54.232.40.64/26
54.241.32.64/26
54.243.31.192/26
54.244.52.192/26
54.245.168.0/26
54.248.220.0/26
54.250.253.192/26
54.251.31.128/26
54.252.79.128/26
54.252.254.192/26
54.255.254.192/26
107.23.255.0/26
176.34.159.192/26
177.71.207.128/26
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetCheckerIpRanges](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53HostedZone`
<a name="route-53_GetHostedZone_powershell_4_topic"></a>

次のコード例は、`Get-R53HostedZone` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ID Z1D633PJN98FT9 を持つホストゾーンの詳細を返します。**  

```
Get-R53HostedZone -Id Z1D633PJN98FT9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetHostedZone](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53HostedZoneCount`
<a name="route-53_GetHostedZoneCount_powershell_4_topic"></a>

次のコード例は、`Get-R53HostedZoneCount` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 現在のパブリックホストゾーンとプライベートホストゾーンの合計数を返します AWS アカウント。**  

```
Get-R53HostedZoneCount
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetHostedZoneCount](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53HostedZoneLimit`
<a name="route-53_GetHostedZoneLimit_powershell_4_topic"></a>

次のコード例は、`Get-R53HostedZoneLimit` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ホストゾーンで作成できるレコードの数の上限を返します。**  

```
Get-R53HostedZoneLimit -HostedZoneId Z3MEQ8T7HAAAAF -Type MAX_RRSETS_BY_ZONE
```
**出力:**  

```
5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetHostedZoneLimit](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53HostedZoneList`
<a name="route-53_ListHostedZones_powershell_4_topic"></a>

次のコード例は、`Get-R53HostedZoneList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべてのパブリックホストゾーンとプライベートホストゾーンを出力します。**  

```
Get-R53HostedZoneList
```
**例 2: ID NZ8X2CISAMPLE を持つ再利用可能な委託セットに関連付けられているすべてのホストゾーンを出力します**  

```
Get-R53HostedZoneList -DelegationSetId NZ8X2CISAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListHostedZones](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53HostedZonesByName`
<a name="route-53_ListHostedZonesByName_powershell_4_topic"></a>

次のコード例は、`Get-R53HostedZonesByName` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべてのパブリックホストゾーンとプライベートホストゾーンを、ドメイン名で ASCII 順に返します。**  

```
Get-R53HostedZonesByName
```
**例 2: パブリックホストゾーンとプライベートホストゾーンを、ドメイン名で ASCII 順に指定した DNS 名から返します。**  

```
Get-R53HostedZonesByName -DnsName example2.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListHostedZonesByName](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53QueryLoggingConfigList`
<a name="route-53_ListQueryLoggingConfigs_powershell_4_topic"></a>

次のコード例は、`Get-R53QueryLoggingConfigList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、現在の AWS アカウントに関連付けられている DNS クエリのログ記録のすべての設定を返します。**  

```
Get-R53QueryLoggingConfigList
```
**出力:**  

```
Id                                   HostedZoneId   CloudWatchLogsLogGroupArn
--                                   ------------   -------------------------
59b0fa33-4fea-4471-a88c-926476aaa40d Z385PDS6EAAAZR arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example1.com:*
ee528e95-4e03-4fdc-9d28-9e24ddaaa063 Z94SJHBV1AAAAZ arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example2.com:*
e38dddda-ceb6-45c1-8cb7-f0ae56aaaa2b Z3MEQ8T7AAA1BF arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example3.com:*
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListQueryLoggingConfigs](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-R53ReusableDelegationSet`
<a name="route-53_GetReusableDelegationSet_powershell_4_topic"></a>

次のコード例は、`Get-R53ReusableDelegationSet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、委任セットに割り当てられた 4 つのネームサーバーを含む、指定委任セットに関する情報を取得します。**  

```
Get-R53ReusableDelegationSet -Id N23DS9X4AYEAAA
```
**出力:**  

```
Id                            CallerReference NameServers
--                            --------------- -----------
/delegationset/N23DS9X4AYEAAA testcaller      {ns-545.awsdns-04.net, ns-1264.awsdns-30.org, ns-2004.awsdns-58.co.uk, ns-240.awsdns-30.com}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetReusableDelegationSet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-R53HostedZone`
<a name="route-53_CreateHostedZone_powershell_4_topic"></a>

次のコード例は、`New-R53HostedZone` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 再利用可能な委託セットに関連付けられた「example.com」という名前の新しいホストゾーンを作成します。CallerReference パラメータの値を指定する必要があります。それによって、必要に応じて再試行が必要なリクエストのオペレーションを 2 回実行するリスクがなくなります。ホストゾーンは VPC で作成され、自動的にプライベートになるため、-HostedZoneConfig\$1PrivateZone パラメータは設定しないでください。**  

```
$params = @{
    Name="example.com"
    CallerReference="myUniqueIdentifier"
    HostedZoneConfig_Comment="This is my first hosted zone"
    DelegationSetId="NZ8X2CISAMPLE"
    VPC_VPCId="vpc-1a2b3c4d"
    VPC_VPCRegion="us-east-1"
}

New-R53HostedZone @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateHostedZone](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-R53QueryLoggingConfig`
<a name="route-53_CreateQueryLoggingConfig_powershell_4_topic"></a>

次のコード例は、`New-R53QueryLoggingConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ホストゾーンの新しい Route53 DNS クエリのログ記録設定を作成します。Amazon Route53 は、指定 Cloudwatch ロググループに DNS クエリログを発行します。**  

```
New-R53QueryLoggingConfig -HostedZoneId Z3MEQ8T7HAAAAF -CloudWatchLogsLogGroupArn arn:aws:logs:us-east-1:111111111111:log-group:/aws/route53/example.com:*
```
**出力:**  

```
QueryLoggingConfig                      Location
------------------                      --------
Amazon.Route53.Model.QueryLoggingConfig https://route53.amazonaws.com/2013-04-01/queryloggingconfig/ee5aaa95-4e03-4fdc-9d28-9e24ddaaaaa3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-R53ReusableDelegationSet`
<a name="route-53_CreateReusableDelegationSet_powershell_4_topic"></a>

次のコード例は、`New-R53ReusableDelegationSet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、複数のホストゾーンで再利用できる 4 つのネームサーバーの再利用可能な委任セットを作成します。**  

```
New-R53ReusableDelegationSet -CallerReference testcallerreference
```
**出力:**  

```
DelegationSet                      Location
-------------                      --------
Amazon.Route53.Model.DelegationSet https://route53.amazonaws.com/2013-04-01/delegationset/N23DS9XAAAAAXM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateReusableDelegationSet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-R53VPCWithHostedZone`
<a name="route-53_AssociateVPCWithHostedZone_powershell_4_topic"></a>

次のコード例は、`Register-R53VPCWithHostedZone` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 VPC をプライベートホストゾーンに関連付けます。**  

```
Register-R53VPCWithHostedZone -HostedZoneId Z3MEQ8T7HAAAAF -VPC_VPCId vpc-f1b9aaaa -VPC_VPCRegion us-east-1
```
**出力:**  

```
Id                     Status  SubmittedAt         Comment
--                     ------  -----------         -------
/change/C3SCAAA633Z6DX PENDING 01/28/2020 19:32:02
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssociateVPCWithHostedZone](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-R53HostedZone`
<a name="route-53_DeleteHostedZone_powershell_4_topic"></a>

次のコード例は、`Remove-R53HostedZone` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された ID を持つホストゾーンを削除します。-Force スイッチパラメータを追加しない限り、コマンドを進める前に確認を求められます。**  

```
Remove-R53HostedZone -Id Z1PA6795UKMFR9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteHostedZone](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-R53QueryLoggingConfig`
<a name="route-53_DeleteQueryLoggingConfig_powershell_4_topic"></a>

次のコード例は、`Remove-R53QueryLoggingConfig` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、DNS クエリログ記録の指定された設定を削除します。**  

```
Remove-R53QueryLoggingConfig -Id ee528e95-4e03-4fdc-9d28-9e24daaa20063
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-R53ReusableDelegationSet`
<a name="route-53_DeleteReusableDelegationSet_powershell_4_topic"></a>

次のコード例は、`Remove-R53ReusableDelegationSet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、再利用可能な指定委任セットを削除します。**  

```
Remove-R53ReusableDelegationSet -Id N23DS9X4AYAAAM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteReusableDelegationSet](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-R53VPCFromHostedZone`
<a name="route-53_DisassociateVPCFromHostedZone_powershell_4_topic"></a>

次のコード例は、`Unregister-R53VPCFromHostedZone` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 VPC とプライベートホストゾーンの関連付けを解除します。**  

```
Unregister-R53VPCFromHostedZone -HostedZoneId Z3MEQ8T7HAAAAF -VPC_VPCId vpc-f1b9aaaa -VPC_VPCRegion us-east-1
```
**出力:**  

```
Id                     Status  SubmittedAt         Comment
--                     ------  -----------         -------
/change/C2XFCAAAA9HKZG PENDING 01/28/2020 10:35:55
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisassociateVPCFromHostedZone](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-R53HostedZoneComment`
<a name="route-53_UpdateHostedZoneComment_powershell_4_topic"></a>

次のコード例は、`Update-R53HostedZoneComment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定ホストゾーンのコメントを更新します。**  

```
Update-R53HostedZoneComment -Id Z385PDS6AAAAAR -Comment "This is my first hosted zone"
```
**出力:**  

```
Id                     : /hostedzone/Z385PDS6AAAAAR
Name                   : example.com.
CallerReference        : C5B55555-7147-EF04-8341-69131E805C89
Config                 : Amazon.Route53.Model.HostedZoneConfig
ResourceRecordSetCount : 9
LinkedService          :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateHostedZoneComment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon S3 の例
<a name="powershell_4_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Copy-S3Object`
<a name="s3_CopyObject_powershell_4_topic"></a>

次のコード例は、`Copy-S3Object` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、オブジェクト「sample.txt」をバケット「test-files」から同じバケットにコピーします。ただし、新しいキー「sample-copy.txt」を使用します。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -DestinationKey sample-copy.txt
```
**例 2: このコマンドは、オブジェクト「sample.txt」をバケット「test-files」からバケット「backup-files」にコピーします。ただし、キーは「sample-copy.txt」を使用します。**  

```
Copy-S3Object -BucketName amzn-s3-demo-source-bucket -Key sample.txt -DestinationKey sample-copy.txt -DestinationBucket amzn-s3-demo-destination-bucket
```
**例 3: このコマンドは、オブジェクト「sample.txt」をバケット「test-files」からダウンロードして、「local-sample.txt」という名前のローカルファイルに保存します。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -LocalFile local-sample.txt
```
**例 4: 指定したファイルに 1 つのオブジェクトをダウンロードします。ダウンロードしたファイルは c:\$1downloads\$1data\$1archive.zip に保存されます。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key data/archive.zip -LocalFolder c:\downloads
```
**例 5: 指定した key prefix と一致するすべてのオブジェクトをローカルフォルダにダウンロードします。相対的なキー階層は、ダウンロードの場所全体のサブフォルダとして保存されます。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix data -LocalFolder c:\downloads
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CopyObject](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3ACL`
<a name="s3_GetACL_powershell_4_topic"></a>

次のコード例は、`Get-S3ACL` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: コマンドは、S3 オブジェクトのオブジェクト所有者の詳細を取得します。**  

```
Get-S3ACL -BucketName 'amzn-s3-demo-bucket' -key 'initialize.ps1' -Select AccessControlList.Owner
```
**出力:**  

```
DisplayName Id
----------- --
testusername      9988776a6554433d22f1100112e334acb45566778899009e9887bd7f66c5f544
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetACL](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3Bucket`
<a name="s3_ListBuckets_powershell_4_topic"></a>

次のコード例は、`Get-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドはすべての S3 バケットを返します。**  

```
Get-S3Bucket
```
**例 2: このコマンドは「test-files」という名前のバケットを返します。**  

```
Get-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListBuckets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketAccelerateConfiguration`
<a name="s3_GetBucketAccelerateConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketAccelerateConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定したバケットで転送加速設定が有効になっている場合、このコマンドは Enabled の値を返します。**  

```
Get-S3BucketAccelerateConfiguration -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Value                                  
-----                                    
Enabled
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketAnalyticsConfiguration`
<a name="s3_GetBucketAnalyticsConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketAnalyticsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケット内の「testfilter」という名前の分析フィルターの詳細を返します。**  

```
Get-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketAnalyticsConfigurationList`
<a name="s3_ListBucketAnalyticsConfigurations_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketAnalyticsConfigurationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットの最初の 100 つの分析設定を返します。**  

```
Get-S3BucketAnalyticsConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListBucketAnalyticsConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketEncryption`
<a name="s3_GetBucketEncryption_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketEncryption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: のコマンドは、指定したバケットに関連付けられたすべてのサーバー側暗号化ルールを返します。**  

```
Get-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketEncryption](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketInventoryConfiguration`
<a name="s3_GetBucketInventoryConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketInventoryConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケット内の「testinventory」という名前のインベントリの詳細を返します。**  

```
Get-S3BucketInventoryConfiguration -BucketName 'amzn-s3-demo-bucket' -InventoryId 'testinventory'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketInventoryConfigurationList`
<a name="s3_ListBucketInventoryConfigurations_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketInventoryConfigurationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットの最初の 100 つのインベントリ設定を返します。**  

```
Get-S3BucketInventoryConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListBucketInventoryConfigurations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketLocation`
<a name="s3_GetBucketLocation_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketLocation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、制約が存在する場合、バケット「amzn-s3-demo-bucket」の場所の制約を返します。**  

```
Get-S3BucketLocation -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Value
-----
ap-south-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketLocation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketLogging`
<a name="s3_GetBucketLogging_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketLogging` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定したバケットのログ記録ステータスを返します。**  

```
Get-S3BucketLogging -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
TargetBucketName   Grants TargetPrefix
----------------   ------ ------------
testbucket1        {}     testprefix
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketLogging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketMetricsConfiguration`
<a name="s3_GetBucketMetricsConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketMetricsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットの「testfilter」という名前のメトリクスフィルターに関する詳細を返します。**  

```
Get-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testfilter'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketNotification`
<a name="s3_GetBucketNotification_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketNotification` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したバケットの通知設定を取得します。**  

```
Get-S3BucketNotification -BucketName amzn-s3-demo-bucket | select -ExpandProperty TopicConfigurations
```
**出力:**  

```
Id   Topic
--   -----
mimo arn:aws:sns:eu-west-1:123456789012:topic-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketNotification](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketPolicy`
<a name="s3_GetBucketPolicy_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットに関連付けられたバケットポリシーを出力します。**  

```
Get-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketPolicyStatus`
<a name="s3_GetBucketPolicyStatus_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketPolicyStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットのポリシーステータスを返し、バケットがパブリックかどうかを示します。**  

```
Get-S3BucketPolicyStatus -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketPolicyStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketReplication`
<a name="s3_GetBucketReplication_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketReplication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットに設定されているレプリケーション設定の情報を返します。**  

```
Get-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketReplication](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketRequestPayment`
<a name="s3_GetBucketRequestPayment_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketRequestPayment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットのリクエストの支払い設定を返します。デフォルトでは、バケット所有者はバケットからのダウンロード料金を支払います。**  

```
Get-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketRequestPayment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketTagging`
<a name="s3_GetBucketTagging_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketTagging` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定バケットに関連付けられたすべてのタグを返します。**  

```
Get-S3BucketTagging -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketTagging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketVersioning`
<a name="s3_GetBucketVersioning_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketVersioning` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定バケットに関するバージョニングステータスを返します。**  

```
Get-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketVersioning](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3BucketWebsite`
<a name="s3_GetBucketWebsite_powershell_4_topic"></a>

次のコード例は、`Get-S3BucketWebsite` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 S3 バケットの静的ウェブサイトの設定の詳細を返します。**  

```
Get-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetBucketWebsite](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3CORSConfiguration`
<a name="s3_GetCORSConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-S3CORSConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 S3 バケットに対応するすべての CORS 設定ルールを含むオブジェクトを返します。**  

```
Get-S3CORSConfiguration -BucketName 'amzn-s3-demo-bucket' -Select Configuration.Rules
```
**出力:**  

```
AllowedMethods : {PUT, POST, DELETE}
AllowedOrigins : {http://www.example1.com}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {*}

AllowedMethods : {PUT, POST, DELETE}
AllowedOrigins : {http://www.example2.com}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {*}

AllowedMethods : {GET}
AllowedOrigins : {*}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetCORSConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3LifecycleConfiguration`
<a name="s3_GetLifecycleConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-S3LifecycleConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、バケットのライフサイクル設定を取得します。**  

```
Get-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket
```
**出力:**  

```
Rules
-----
{Remove-in-150-days, Archive-to-Glacier-in-30-days}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3Object`
<a name="s3_ListObjects_powershell_4_topic"></a>

次のコード例は、`Get-S3Object` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、バケット「test-files」内のすべての項目に関する情報を取得します。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket
```
**例 2: このコマンドは、バケット「test-files」内の項目「sample.txt」に関する情報を取得します。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt
```
**例 3: このコマンドは、バケット「test-files」からプレフィックス「sample」を持つすべての項目に関する情報を取得します。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix sample
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference(V4)*」の「[ListObjects](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3ObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_powershell_4_topic"></a>

次のコード例は、`Get-S3ObjectLockConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定した S3 バケットのオブジェクトロック設定が有効になっている場合、このコマンドは値「Enabled」を返しま。**  

```
Get-S3ObjectLockConfiguration -BucketName 'amzn-s3-demo-bucket' -Select ObjectLockConfiguration.ObjectLockEnabled
```
**出力:**  

```
Value
-----
Enabled
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetObjectLockConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3ObjectMetadata`
<a name="s3_GetObjectMetadata_powershell_4_topic"></a>

次のコード例は、`Get-S3ObjectMetadata` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定された S3 バケット内のキー 「ListTrusts.txt」を含むオブジェクトのメタデータを返します。**  

```
Get-S3ObjectMetadata -BucketName 'amzn-s3-demo-bucket' -Key 'ListTrusts.txt'
```
**出力:**  

```
Headers                                       : Amazon.S3.Model.HeadersCollection
Metadata                                      : Amazon.S3.Model.MetadataCollection
DeleteMarker                                  : 
AcceptRanges                                  : bytes
ContentRange                                  : 
Expiration                                    : 
RestoreExpiration                             : 
RestoreInProgress                             : False
LastModified                                  : 01/01/2020 08:02:05
ETag                                          : "d000011112a222e333e3bb4ee5d43d21"
MissingMeta                                   : 0
VersionId                                     : null
Expires                                       : 01/01/0001 00:00:00
WebsiteRedirectLocation                       : 
ServerSideEncryptionMethod                    : AES256
ServerSideEncryptionCustomerMethod            : 
ServerSideEncryptionKeyManagementServiceKeyId : 
ReplicationStatus                             : 
PartsCount                                    : 
ObjectLockLegalHoldStatus                     : 
ObjectLockMode                                : 
ObjectLockRetainUntilDate                     : 01/01/0001 00:00:00
StorageClass                                  : 
RequestCharged                                :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetObjectMetadata](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3ObjectRetention`
<a name="s3_GetObjectRetention_powershell_4_topic"></a>

次のコード例は、`Get-S3ObjectRetention` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、オブジェクトが保持されるまでのモードと日付を返します。**  

```
Get-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetObjectRetention](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3ObjectTagSet`
<a name="s3_GetObjectTagging_powershell_4_topic"></a>

次のコード例は、`Get-S3ObjectTagSet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した S3 バケット上に存在するオブジェクトに関連付けられたタグを返します。**  

```
Get-S3ObjectTagSet -Key 'testfile.txt' -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Key  Value
---  -----
test value
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetObjectTagging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3PreSignedURL`
<a name="s3_GetPreSignedURL_powershell_4_topic"></a>

次のコード例は、`Get-S3PreSignedURL` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: コマンドは、指定キーと有効期限の署名付き URL を返します。**  

```
Get-S3PreSignedURL -BucketName 'amzn-s3-demo-bucket' -Key 'testkey' -Expires '2023-11-16'
```
**例 2: コマンドは、指定キーと有効期限を持つディレクトリバケットの署名付き URL を返します。**  

```
[Amazon.AWSConfigsS3]::UseSignatureVersion4 = $true
      Get-S3PreSignedURL -BucketName amzn-s3-demo-bucket--usw2-az1--x-s3 -Key 'testkey' -Expire '2023-11-17'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPreSignedURL](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3PublicAccessBlock`
<a name="s3_GetPublicAccessBlock_powershell_4_topic"></a>

次のコード例は、`Get-S3PublicAccessBlock` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 S3 バケットのパブリックアクセスブロック設定を返します。**  

```
Get-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPublicAccessBlock](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-S3Version`
<a name="s3_ListVersions_powershell_4_topic"></a>

次のコード例は、`Get-S3Version` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 S3 バケット内のすべてのバージョンのオブジェクトに関するメタデータを返します。**  

```
Get-S3Version -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
IsTruncated         : False
KeyMarker           : 
VersionIdMarker     : 
NextKeyMarker       : 
NextVersionIdMarker : 
Versions            : {EC2.txt, EC2MicrosoftWindowsGuide.txt, ListDirectories.json, ListTrusts.json}
Name                : amzn-s3-demo-bucket
Prefix              : 
MaxKeys             : 1000
CommonPrefixes      : {}
Delimiter           :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListVersions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-S3Bucket`
<a name="s3_PutBucket_powershell_4_topic"></a>

次のコード例は、`New-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、「sample-bucket」という名前の新しいプライベートバケットを作成します。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket
```
**例 2: このコマンドは、読み取り/書き込みアクセス許可を持つ「sample-bucket」という名前の新しいバケットを作成します。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket -PublicReadWrite
```
**例 3: このコマンドは、読み取り専用アクセス許可を持つ「sample-bucket」という名前の新しいバケットを作成します。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket -PublicReadOnly
```
**例 4: このコマンドは、PutBucketConfiguration を使用して「amzn-s3-demo-bucket--use1-az5--x-s3」という名前の新しいディレクトリバケットを作成します。**  

```
$bucketConfiguration = @{
      BucketInfo = @{
          DataRedundancy = 'SingleAvailabilityZone'
          Type = 'Directory'
      }
      Location = @{
          Name = 'usw2-az1'
          Type = 'AvailabilityZone'
      }
    }
New-S3Bucket -BucketName amzn-s3-demo-bucket--usw2-az1--x-s3 -BucketConfiguration $bucketConfiguration -Region us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucket](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Read-S3Object`
<a name="s3_GetObject_powershell_4_topic"></a>

次のコード例は、`Read-S3Object` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、バケット「amzn-s3-demo-bucket」から項目「sample.txt」を取得し、現在の場所の「local-sample.txt」という名前のファイルに保存します。このコマンドを呼び出す前にファイル「local-sample.txt」が存在していなくても構いません。**  

```
Read-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -File local-sample.txt
```
**例 2: このコマンドは、バケット「amzn-s3-demo-bucket」から仮想ディレクトリ「DIR」を取得し、現在の場所の「Local-DIR」という名前のフォルダに保存します。このコマンドを呼び出す前に、フォルダー「Local-DIR」が存在していなくても構いません。**  

```
Read-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix DIR -Folder Local-DIR
```
**例 3: バケット名に「config」を含むバケットから、キーが「.json」で終わるすべてのオブジェクトを、指定したフォルダ内のファイルにダウンロードします。オブジェクトキーはファイル名の設定に使用されます。**  

```
Get-S3Bucket | ? { $_.BucketName -like '*config*' } | Get-S3Object | ? { $_.Key -like '*.json' } | Read-S3Object -Folder C:\ConfigObjects
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetObject](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3Bucket`
<a name="s3_DeleteBucket_powershell_4_topic"></a>

次のコード例は、`Remove-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、バケット「test-files」からすべてのオブジェクトとオブジェクトバージョンを削除してから、バケットを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force スイッチを追加すると、確認メッセージが表示されなくなります。空でないバケットは削除できないことに注意が必要です。**  

```
Remove-S3Bucket -BucketName amzn-s3-demo-bucket -DeleteBucketContent
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucket](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketAnalyticsConfiguration`
<a name="s3_DeleteBucketAnalyticsConfiguration_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketAnalyticsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケット内の「testfilter」という名前の分析フィルターを削除します。**  

```
Remove-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketEncryption`
<a name="s3_DeleteBucketEncryption_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketEncryption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: これは、指定した S3 バケットで有効になっている暗号化を無効にします。**  

```
Remove-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketEncryption (DeleteBucketEncryption)" on target "s3casetestbucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketEncryption](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketInventoryConfiguration`
<a name="s3_DeleteBucketInventoryConfiguration_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketInventoryConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットに対応する「testInventoryName」という名前のインベントリを削除します。**  

```
Remove-S3BucketInventoryConfiguration -BucketName 'amzn-s3-demo-bucket' -InventoryId 'testInventoryName'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketInventoryConfiguration (DeleteBucketInventoryConfiguration)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketMetricsConfiguration`
<a name="s3_DeleteBucketMetricsConfiguration_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketMetricsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケット内の「testmetrics」という名前のメトリクスフィルターを削除します。**  

```
Remove-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testmetrics'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketPolicy`
<a name="s3_DeleteBucketPolicy_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketPolicy` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットに関連付けられたバケットポリシーを削除します。**  

```
Remove-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketPolicy](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketReplication`
<a name="s3_DeleteBucketReplication_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketReplication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットに関連付けられているレプリケーションの設定を削除します。なお、このオペレーションには s3:DeleteReplicationConfiguration アクションに対するアクセス許可が必要です。オペレーションを続行する前に確認を求めるプロンプトが表示されます。プロンプトを表示しないようにするには、-Force スイッチを使用します。**  

```
Remove-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketReplication](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketTagging`
<a name="s3_DeleteBucketTagging_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketTagging` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットに関連付けられたすべてのタグを削除します。**  

```
Remove-S3BucketTagging -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketTagging (DeleteBucketTagging)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketTagging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3BucketWebsite`
<a name="s3_DeleteBucketWebsite_powershell_4_topic"></a>

次のコード例は、`Remove-S3BucketWebsite` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットの静的ウェブサイトホスティングのプロパティを無効にします。**  

```
Remove-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketWebsite (DeleteBucketWebsite)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteBucketWebsite](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3CORSConfiguration`
<a name="s3_DeleteCORSConfiguration_powershell_4_topic"></a>

次のコード例は、`Remove-S3CORSConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットの CORS 設定を削除します。**  

```
Remove-S3CORSConfiguration -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3CORSConfiguration (DeleteCORSConfiguration)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteCORSConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3LifecycleConfiguration`
<a name="s3_DeleteLifecycleConfiguration_powershell_4_topic"></a>

次のコード例は、`Remove-S3LifecycleConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: コマンドは、指定 S3 バケットのすべてのライフサイクルルールを削除します。**  

```
Remove-S3LifecycleConfiguration -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3MultipartUpload`
<a name="s3_AbortMultipartUpload_powershell_4_topic"></a>

次のコード例は、`Remove-S3MultipartUpload` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、5 日より前に作成されたマルチパートアップロードを中止します。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -DaysBefore 5
```
**例 2: このコマンドは、2014 年 1 月 2 日より前に作成されたマルチパートアップロードを中止します。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -InitiatedDate "Thursday, January 02, 2014"
```
**例 3: このコマンドは、2014 年 1 月 2 日 10:45:37 より前に作成されたマルチパートアップロードを中止します。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -InitiatedDate "2014/01/02 10:45:37"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AbortMultipartUpload](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3Object`
<a name="s3_DeleteObjects_powershell_4_topic"></a>

次のコード例は、`Remove-S3Object` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、バケット「test-files」からオブジェクト「sample.txt」を削除します。コマンドを実行する前に、確認を求めるプロンプトが表示されます。-Force スイッチを追加すると、確認メッセージが表示されなくなります。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt
```
**例 2: このコマンドは、指定されたバージョンのオブジェクト「sample.txt」をバケット「test-files」から削除します。これは、バケットがオブジェクトバージョンを有効にするように設定されていることを前提としています。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -VersionId HLbxnx6V9omT6AQYVpks8mmFKQcejpqt
```
**例 3: このコマンドは、バケット「test-files」からオブジェクト「sample1.txt」、「sample2.txt」、「sample3.txt」を 1 回のバッチ操作で削除します。このサービスの応答では、削除の成功またはエラーのステータスを問わず、処理されたすべてのキーがリスト表示されます。このサービスで処理できなかったキーのエラーのみを取得するには、-ReportErrorsOnly パラメータを追加します (このパラメータは -Quiet というエイリアスを使用して指定することもできます)。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -KeyCollection @( "sample1.txt", "sample2.txt", "sample3.txt" )
```
**例 4: この例では、-KeyCollection パラメータを指定したインライン式を使用して、削除するオブジェクトのキーを取得します。Get-S3Object は Amazon.S3.Model.S3Object インスタンスのコレクションを返します。各インスタンスには、オブジェクトを識別する文字列型の Key メンバーがあります。**  

```
Remove-S3Object -bucketname "amzn-s3-demo-bucket" -KeyCollection (Get-S3Object "test-files" -KeyPrefix "prefix/subprefix" | select -ExpandProperty Key)
```
**例 5: この例では、バケット内のキープレフィックス「prefix/subprefix」を持つすべてのオブジェクトを取得して削除します。受け取るオブジェクトは一度に 1 つずつ処理されることに注意が必要です。大規模なコレクションの場合は、コレクションをコマンドレットの -InputObject (エイリアスは -S3ObjectCollection) パラメータに渡して、サービスを 1 回呼び出すだけでバッチで削除できるようにすることを検討してください。**  

```
Get-S3Object -BucketName "amzn-s3-demo-bucket" -KeyPrefix "prefix/subprefix" | Remove-S3Object -Force
```
**例 6: この例では、削除マーカーを表す Amazon.S3.Model.S3ObjectVersion インスタンスのコレクションを、削除コマンドレットにパイプします。受け取るオブジェクトは一度に 1 つずつ処理されることに注意が必要です。大規模なコレクションの場合は、コレクションをコマンドレットの -InputObject (エイリアスは -S3ObjectCollection) パラメータに渡して、サービスを 1 回呼び出すだけでバッチで削除できるようにすることを検討してください。**  

```
(Get-S3Version -BucketName "amzn-s3-demo-bucket").Versions | Where {$_.IsDeleteMarker -eq "True"} | Remove-S3Object -Force
```
**例 7: このスクリプトは、-KeyAndVersionCollection パラメータで使用するオブジェクトの配列を作成することで、オブジェクトセット (この場合は削除マーカー) をバッチで削除する方法を示しています。**  

```
$keyVersions = @()
$markers = (Get-S3Version -BucketName $BucketName).Versions | Where {$_.IsDeleteMarker -eq "True"}
foreach ($marker in $markers) { $keyVersions += @{ Key = $marker.Key; VersionId = $marker.VersionId } }
Remove-S3Object -BucketName $BucketName -KeyAndVersionCollection $keyVersions -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteObjects](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3ObjectTagSet`
<a name="s3_DeleteObjectTagging_powershell_4_topic"></a>

次のコード例は、`Remove-S3ObjectTagSet` を使用する方法を示しています。

**Tools for PowerShell V4**  
**このコマンドは、指定した S3 バケット内のキー「testfile.txt」を持つオブジェクトに関連付けられたすべてのタグを削除します。**  

```
Remove-S3ObjectTagSet -Key 'testfile.txt' -BucketName 'amzn-s3-demo-bucket' -Select '^Key'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3ObjectTagSet (DeleteObjectTagging)" on target "testfile.txt".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
testfile.txt
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteObjectTagging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-S3PublicAccessBlock`
<a name="s3_DeletePublicAccessBlock_powershell_4_topic"></a>

次のコード例は、`Remove-S3PublicAccessBlock` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定したバケットのブロックパブリックアクセス設定をオフにします。**  

```
Remove-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket' -Force -Select '^BucketName'
```
**出力:**  

```
amzn-s3-demo-bucket
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeletePublicAccessBlock](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-S3BucketEncryption`
<a name="s3_PutBucketEncryption_powershell_4_topic"></a>

次のコード例は、`Set-S3BucketEncryption` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定したバケットで Amazon S3 マネージドキー (SSE-S3) を使用したデフォルトの AES256 サーバー側暗号化を有効にします。**  

```
$Encryptionconfig = @{ServerSideEncryptionByDefault = @{ServerSideEncryptionAlgorithm = "AES256"}}
Set-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket' -ServerSideEncryptionConfiguration_ServerSideEncryptionRule $Encryptionconfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketEncryption](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Test-S3Bucket`
<a name="s3_Test-S3Bucket_powershell_4_topic"></a>

次のコード例は、`Test-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、バケットが存在する場合は True を返し、存在しない場合は False を返します。コマンドは、バケットがユーザーに属していない場合でも True を返します。**  

```
Test-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Test-S3Bucket](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3BucketAccelerateConfiguration`
<a name="s3_PutBucketAccelerateConfiguration_powershell_4_topic"></a>

次のコード例は、`Write-S3BucketAccelerateConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定 S3 バケットの転送加速を有効にします。**  

```
$statusVal = New-Object Amazon.S3.BucketAccelerateStatus('Enabled')
Write-S3BucketAccelerateConfiguration -BucketName 'amzn-s3-demo-bucket' -AccelerateConfiguration_Status $statusVal
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3BucketNotification`
<a name="s3_PutBucketNotification_powershell_4_topic"></a>

次のコード例は、`Write-S3BucketNotification` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、S3 イベント ObjectRemovedDelete の SNS トピック設定を設定して、指定した S3 バケットの通知を有効にします。**  

```
$topic =  [Amazon.S3.Model.TopicConfiguration] @{
  Id = "delete-event"
  Topic = "arn:aws:sns:eu-west-1:123456789012:topic-1"
  Event = [Amazon.S3.EventType]::ObjectRemovedDelete
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -TopicConfiguration $topic
```
**例 2: この例では、指定したバケットの ObjectCreatedAll の通知を有効にして、Lambda 関数に送信します。**  

```
$lambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = "s3:ObjectCreated:*"
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:rdplock"
  Id = "ObjectCreated-Lambda"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".pem"}
      )
    }
  }
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -LambdaFunctionConfiguration $lambdaConfig
```
**例 3: この例では、異なるキーサフィックスに基づいて 2 つの異なる Lambda 設定を作成し、両方を 1 つのコマンドで設定します。**  

```
#Lambda Config 1

$firstLambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = "s3:ObjectCreated:*"
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifynet"
  Id = "ObjectCreated-dada-ps1"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".ps1"}
      )
    }
  }
}

#Lambda Config 2

$secondlambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = [Amazon.S3.EventType]::ObjectCreatedAll
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifyssm"
  Id = "ObjectCreated-dada-json"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".json"}
      )
    }
  }
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -LambdaFunctionConfiguration $firstLambdaConfig,$secondlambdaConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketNotification](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3BucketReplication`
<a name="s3_PutBucketReplication_powershell_4_topic"></a>

次のコード例は、`Write-S3BucketReplication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、バケット「amzn-s3-demo-bucket」内のキー名プレフィックス「TaxDocs」で作成された新しいオブジェクトの「amzn-s3-demo-bucket」バケットへのレプリケーションを有効にする単一のルールを使用してレプリケーション設定を指定します。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Enabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1
}

Write-S3BucketReplication @params
```
**例 2: この例では、キー名のプレフィックスが「TaxDocs」または「OtherDocs」の新しく作成されたオブジェクトを、バケット「amzn-s3-demo-bucket」にレプリケートするための複数のルールを使用して、レプリケーション設定を指定します。キーのプレフィックスの重複は許可されません。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Enabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$rule2 = New-Object Amazon.S3.Model.ReplicationRule
$rule2.ID = "Rule-2"
$rule2.Status = "Enabled"
$rule2.Prefix = "OtherDocs"
$rule2.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1,$rule2
}

Write-S3BucketReplication @params
```
**例 3: この例では、指定されたバケットのレプリケーション設定を更新して、「TaxDocs」というキー名のプレフィックスを持つオブジェクトのバケット「amzn-s3-demo-bucket」へのレプリケーションを制御するルールを無効にします。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Disabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1
}

Write-S3BucketReplication @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketReplication](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3BucketRequestPayment`
<a name="s3_PutBucketRequestPayment_powershell_4_topic"></a>

次のコード例は、`Write-S3BucketRequestPayment` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットのリクエスト支払い設定を更新して、バケットからのダウンロードをリクエストしたユーザーにダウンロード料金が請求されるようにします。デフォルトでは、バケット所有者がダウンロード料金を支払います。リクエストの支払いをデフォルトに戻すには、RequestPaymentConfiguration\$1Payer パラメーターに「BucketOwner」を使用します。**  

```
Write-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket -RequestPaymentConfiguration_Payer Requester
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketRequestPayment](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3BucketTagging`
<a name="s3_PutBucketTagging_powershell_4_topic"></a>

次のコード例は、`Write-S3BucketTagging` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、`cloudtrail-test-2018` という名前のバケットに 2 つのタグを適用します。1 つは Stage のキーと値が Test のタグで、もう 1 つはキーが Environment で、値は Alpha のタグです。タグがバケットに追加されたことを確認するには、`Get-S3BucketTagging -BucketName bucket_name` を実行します。結果では、最初のコマンドでバケットに適用したタグが表示されるはずです。`Write-S3BucketTagging` は、バケットに設定されている既存のタグセット全体を上書きすることに注意が必要です。個別のタグを追加または削除するには、リソースグループとタグ付けの API コマンドレット、`Add-RGTResourceTag`、`Remove-RGTResourceTag` を実行します。または、 AWS マネジメントコンソールのタグエディタを使用して S3 バケットタグを管理します。**  

```
Write-S3BucketTagging -BucketName amzn-s3-demo-bucket -TagSet @( @{ Key="Stage"; Value="Test" }, @{ Key="Environment"; Value="Alpha" } )
```
**例 2: このコマンドは、バケット `cloudtrail-test-2018` を `Write-S3BucketTagging` コマンドレットにパイプします。これにより、Stage:Production と Department:Finance というタグがバケットに適用されます。`Write-S3BucketTagging` は、バケットに設定されている既存のタグセット全体を上書きすることに注意が必要です。**  

```
Get-S3Bucket -BucketName amzn-s3-demo-bucket | Write-S3BucketTagging -TagSet @( @{ Key="Stage"; Value="Production" }, @{ Key="Department"; Value="Finance" } )
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketTagging](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3BucketVersioning`
<a name="s3_PutBucketVersioning_powershell_4_topic"></a>

次のコード例は、`Write-S3BucketVersioning` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケットのバージョニングを有効にします。**  

```
Write-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket' -VersioningConfig_Status Enabled
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketVersioning](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3BucketWebsite`
<a name="s3_PutBucketWebsite_powershell_4_topic"></a>

次のコード例は、`Write-S3BucketWebsite` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定したバケットのウェブサイトのホスティングを有効にして、インデックスドキュメントを「index.html」、エラードキュメントを「error.html」と指定します。**  

```
Write-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket' -WebsiteConfiguration_IndexDocumentSuffix 'index.html' -WebsiteConfiguration_ErrorDocument 'error.html'
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutBucketWebsite](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3LifecycleConfiguration`
<a name="s3_PutLifecycleConfiguration_powershell_4_topic"></a>

次のコード例は、`Write-S3LifecycleConfiguration` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、\$1NewRule で指定されている設定を書き込み/置き換えます。この設定では、指定のプレフィックスとタグ値を持つスコープオブジェクトを制限します。**  

```
$NewRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  @{
			Days=  50
		}
		Id =  "Test-From-Write-cmdlet-1"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands=  @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "non-use"
							"Value" = "yes"
						}
					}
				)
			}
		}
		"Status"= 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 75
		}
	}
    
	Write-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket -Configuration_Rule $NewRule
```
**例 2: この例では、フィルタリングを使用して複数のルールを設定します。\$1ArchiveRule は、オブジェクトを 30 日後に Glacier にアーカイブし、120 日後に DeepArchive にアーカイブするように設定します。\$1ExpireRule は、「py」プレフィックスと tag:key「archieved」が「yes」に設定されているオブジェクトについて、現在のバージョンと以前のバージョンの両方を 150 日で期限切れにします。**  

```
$ExpireRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  @{
			Days=  150
		}
		Id =  "Remove-in-150-days"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands=  @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "archived"
							"Value" = "yes"
						}
					}
				)
			}
		}
		Status= 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 150
		}
	}

	$ArchiveRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  $null
		Id =  "Archive-to-Glacier-in-30-days"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands= @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "reviewed"
							"Value" = "yes"
						}
					}
				)
			}
		}
		Status = 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 75
		}
		Transitions = @(
			@{
				Days = 30
				"StorageClass"= 'Glacier'
			},
			@{
				Days = 120
				"StorageClass"= [Amazon.S3.S3StorageClass]::DeepArchive
			}
		)
	}

	Write-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket -Configuration_Rule $ExpireRule,$ArchiveRule
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3Object`
<a name="s3_PutObject_powershell_4_topic"></a>

次のコード例は、`Write-S3Object` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、単一のファイル「local-sample.txt」を Amazon S3 にアップロードして、バケット「test-files」に「sample.txt」というキーを持つオブジェクトを作成します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "sample.txt" -File .\local-sample.txt
```
**例 2: このコマンドは、単一のファイル「sample.txt」を Amazon S3 にアップロードして、バケット「test-files」に「sample.txt」というキーを持つオブジェクトを作成します。-Key パラメータを指定しない場合、ファイル名が S3 オブジェクトキーとして使用されます。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -File .\sample.txt
```
**例 3: このコマンドは、単一のファイル「local-sample.txt」を Amazon S3 にアップロードして、バケット「test-files」に「prefix/to/sample.txt」というキーを持つオブジェクトを作成します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "prefix/to/sample.txt" -File .\local-sample.txt
```
**例 4: このコマンドは、サブディレクトリ「Scripts」内のすべてのファイルをバケット「test-files」にアップロードして、共通のキープレフィックス「SampleScripts」を各オブジェクトに適用します。アップロードされた各ファイルは「SampleScripts/filename」というキーを持ちます。ただし、「filename」の部分はそれぞれ異なります。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder .\Scripts -KeyPrefix SampleScripts\
```
**例 5: このコマンドは、ローカルディレクトリ「Scripts」内のすべての \$1.ps1 ファイルをバケット「test-files」にアップロードして、共通のキープレフィックス「SampleScripts」を各オブジェクトに適用します。アップロードされた各ファイルは「SampleScripts/filename.ps1」というキーを持ちます。ただし、「filename」の部分はそれぞれ異なります。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder .\Scripts -KeyPrefix SampleScripts\ -SearchPattern *.ps1
```
**例 6: このコマンドは、「sample.txt」というキーを持つ、指定されたコンテンツ文字列を含む新しい S3 オブジェクトを作成します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "sample.txt" -Content "object contents"
```
**例 7: このコマンドは、指定したファイル (ファイル名をキーとして使用) をアップロードして、指定したタグを新しいオブジェクトに適用します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -File "sample.txt" -TagSet @{Key="key1";Value="value1"},@{Key="key2";Value="value2"}
```
**例 8: このコマンドは、指定したフォルダを再帰的にアップロードして、指定したタグをすべての新しいオブジェクトに適用します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder . -KeyPrefix "TaggedFiles" -Recurse -TagSet @{Key="key1";Value="value1"},@{Key="key2";Value="value2"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutObject](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-S3ObjectRetention`
<a name="s3_PutObjectRetention_powershell_4_topic"></a>

次のコード例は、`Write-S3ObjectRetention` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、指定した S3 バケット内の「testfile.txt」オブジェクトの期限日「2019 年 12 月 31 日 00:00:00」までガバナンス保持モードを有効にします。**  

```
Write-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt' -Retention_Mode GOVERNANCE -Retention_RetainUntilDate "2019-12-31T00:00:00"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutObjectRetention](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Security Hub CSPM の例
<a name="powershell_4_securityhub_code_examples"></a>

次のコード例は、Security Hub CSPM で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-SHUBFinding`
<a name="securityhub_GetSHUBFinding_powershell_4_topic"></a>

次のコード例は、`Get-SHUBFinding` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、Amazon EC2; サービスから Security Hub の検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.ResourceType = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'PREFIX'
    Value = 'AwsEc2'
}
Get-SHUBFinding -Filter $filter
```
**例 2: このコマンドは、 AWS アカウント ID 123456789012 から Security Hub の検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.AwsAccountId = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = '123456789012'
}
Get-SHUBFinding -Filter $filter
```
**例 3: このコマンドは、標準の「pci-dss」用に生成された Security Hub の検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.GeneratorId = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'PREFIX'
    Value = 'pci-dss'
}
Get-SHUBFinding -Filter $filter
```
**例 4: このコマンドは、ワークフローステータスが NOTIFIED である Security Hub の、重要度が重大である検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.SeverityLabel = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = 'CRITICAL'
}
$filter.WorkflowStatus = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = 'NOTIFIED'
}
Get-SHUBFinding -Filter $filter
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetFindings](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon SES の例
<a name="powershell_4_ses_code_examples"></a>

次のコード例は、Amazon SES で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-SESIdentity`
<a name="ses_ListIdentities_powershell_4_topic"></a>

次のコード例は、`Get-SESIdentity` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、検証ステータスに関係なく、特定の AWS アカウントのすべての ID (E メールアドレスとドメイン) を含むリストを返します。**  

```
Get-SESIdentity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListIdentities](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SESSendQuota`
<a name="ses_GetSendQuota_powershell_4_topic"></a>

次のコード例は、`Get-SESSendQuota` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、ユーザーの現在の送信制限を返します。**  

```
Get-SESSendQuota
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetSendQuota](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SESSendStatistic`
<a name="ses_GetSendStatistics_powershell_4_topic"></a>

次のコード例は、`Get-SESSendStatistic` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、ユーザーの統計の送信を返します。結果は、送信アクティビティの最新の 2 週間を示すデータポイントのリストです。このリスト内の各データポイントには、15 分間隔の統計が含まれます。**  

```
Get-SESSendStatistic
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetSendStatistics](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon SES API v2 の例
<a name="powershell_4_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Send-SES2Email`
<a name="sesv2_SendSES2Email_powershell_4_topic"></a>

次のコード例は、`Send-SES2Email` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、標準の E メールメッセージを送信する方法を示します。**  

```
Send-SES2Email -FromEmailAddress "sender@example.com" -Destination_ToAddress "recipient@example.com" -Subject_Data "Email Subject" -Text_Data "Email Body"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SendEmail](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon SNS の例
<a name="powershell_4_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Publish-SNSMessage`
<a name="sns_Publish_powershell_4_topic"></a>

次のコード例は、`Publish-SNSMessage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インラインで宣言された単一の MessageAttribute を使用してメッセージを発行しています。**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**例 2: この例では、事前に宣言された複数の MessageAttribute を使用してメッセージを発行しています。**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Publish](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Amazon SQS の例
<a name="powershell_4_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-SQSPermission`
<a name="sqs_AddPermission_powershell_4_topic"></a>

次のコード例は、`Add-SQSPermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された が指定されたキューからメッセージを送信 AWS アカウント することを許可します。**  

```
Add-SQSPermission -Action SendMessage -AWSAccountId 80398EXAMPLE -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddPermission](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Clear-SQSQueue`
<a name="sqs_PurgeQueue_powershell_4_topic"></a>

次のコード例は、`Clear-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したキューからすべてのメッセージを削除します。**  

```
Clear-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PurgeQueue](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-SQSMessageVisibility`
<a name="sqs_ChangeMessageVisibility_powershell_4_topic"></a>

次のコード例は、`Edit-SQSMessageVisibility` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したキュー内の指定した受信ハンドルを持つメッセージの可視性タイムアウトを 10 時間 (10 時間 × 60 分 × 60 秒 = 36,000 秒) に変更します。**  

```
Edit-SQSMessageVisibility -QueueUrl https://sqs.us-east-1.amazonaws.com/8039EXAMPLE/MyQueue -ReceiptHandle AQEBgGDh...J/Iqww== -VisibilityTimeout 36000
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[ChangeMessageVisibility](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Edit-SQSMessageVisibilityBatch`
<a name="sqs_ChangeMessageVisibilityBatch_powershell_4_topic"></a>

次のコード例は、`Edit-SQSMessageVisibilityBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したキュー内の指定した受信ハンドルを持つ 2 つのメッセージの可視性タイムアウトを変更します。最初のメッセージの可視性タイムアウトを 10 時間 (10 時間 × 60 分 × 60 秒 = 36,000 秒) に変更します。2 番目のメッセージの可視性タイムアウトを 5 時間 (5 時間 × 60 分 × 60 秒 = 18,000 秒) に変更します。**  

```
$changeVisibilityRequest1 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry
$changeVisibilityRequest1.Id = "Request1"
$changeVisibilityRequest1.ReceiptHandle = "AQEBd329...v6gl8Q=="
$changeVisibilityRequest1.VisibilityTimeout = 36000

$changeVisibilityRequest2 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry
$changeVisibilityRequest2.Id = "Request2"
$changeVisibilityRequest2.ReceiptHandle = "AQEBgGDh...J/Iqww=="
$changeVisibilityRequest2.VisibilityTimeout = 18000

Edit-SQSMessageVisibilityBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $changeVisibilityRequest1, $changeVisibilityRequest2
```
**出力:**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {Request2, Request1}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ChangeMessageVisibilityBatch](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SQSDeadLetterSourceQueue`
<a name="sqs_ListDeadLetterSourceQueues_powershell_4_topic"></a>

次のコード例は、`Get-SQSDeadLetterSourceQueue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、デッドレターキューとして指定したキューに依存するすべてのキューの URL を一覧表示します。**  

```
Get-SQSDeadLetterSourceQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDeadLetterSourceQueues](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SQSQueue`
<a name="sqs_ListQueues_powershell_4_topic"></a>

次のコード例は、`Get-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべてのキューを一覧表示します。**  

```
Get-SQSQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/AnotherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/DeadLetterQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
**例 2: この例では、指定した名前で始まるすべてのキューを一覧表示します。**  

```
Get-SQSQueue -QueueNamePrefix My
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListQueues](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SQSQueueAttribute`
<a name="sqs_GetQueueAttributes_powershell_4_topic"></a>

次のコード例は、`Get-SQSQueueAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したキューのすべての属性を一覧表示します。**  

```
Get-SQSQueueAttribute -AttributeName All -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
VisibilityTimeout                     : 30
DelaySeconds                          : 0
MaximumMessageSize                    : 262144
MessageRetentionPeriod                : 345600
ApproximateNumberOfMessages           : 0
ApproximateNumberOfMessagesNotVisible : 0
ApproximateNumberOfMessagesDelayed    : 0
CreatedTimestamp                      : 2/11/2015 5:53:35 PM
LastModifiedTimestamp                 : 12/29/2015 2:23:17 PM
QueueARN                              : arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue
Policy                                : {"Version":"2012-10-17",		 	 	 "Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/SQSDefaultPolicy","Statement":[{"Sid":"Sid14
                                        495134224EX","Effect":"Allow","Principal":{"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80
                                        398EXAMPLE:MyQueue","Condition":{"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}},{"Sid":
                                        "SendMessagesFromMyQueue","Effect":"Allow","Principal":{"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":"
                                        arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue"}]}
Attributes                            : {[QueueArn, arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue], [ApproximateNumberOfMessages, 0], 
                                        [ApproximateNumberOfMessagesNotVisible, 0], [ApproximateNumberOfMessagesDelayed, 0]...}
```
**例 2: この例では、指定したキューの指定した属性のみを別個に一覧表示します。**  

```
Get-SQSQueueAttribute -AttributeName MaximumMessageSize, VisibilityTimeout -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
VisibilityTimeout                     : 30
DelaySeconds                          : 0
MaximumMessageSize                    : 262144
MessageRetentionPeriod                : 345600
ApproximateNumberOfMessages           : 0
ApproximateNumberOfMessagesNotVisible : 0
ApproximateNumberOfMessagesDelayed    : 0
CreatedTimestamp                      : 2/11/2015 5:53:35 PM
LastModifiedTimestamp                 : 12/29/2015 2:23:17 PM
QueueARN                              : arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue
Policy                                : {"Version":"2012-10-17",		 	 	 "Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/SQSDefaultPolicy","Statement":[{"Sid":"Sid14
                                        495134224EX","Effect":"Allow","Principal":{"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80
                                        398EXAMPLE:MyQueue","Condition":{"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}},{"Sid":
                                        "SendMessagesFromMyQueue","Effect":"Allow","Principal":{"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":"
                                        arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue"}]}
Attributes                            : {[MaximumMessageSize, 262144], [VisibilityTimeout, 30]}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetQueueAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SQSQueueUrl`
<a name="sqs_GetQueueUrl_powershell_4_topic"></a>

次のコード例は、`Get-SQSQueueUrl` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した名前のキューの URL を表示します。**  

```
Get-SQSQueueUrl -QueueName MyQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetQueueUrl](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-SQSQueue`
<a name="sqs_CreateQueue_powershell_4_topic"></a>

次のコード例は、`New-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した名前でキューを作成します。**  

```
New-SQSQueue -QueueName MyQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[CreateQueue](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `Receive-SQSMessage`
<a name="sqs_ReceiveMessage_powershell_4_topic"></a>

次のコード例は、`Receive-SQSMessage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したキューで次に受信する 10 件までのメッセージに関する情報を表示します。情報には、指定したメッセージ属性 (存在する場合) の値が含まれます。**  

```
Receive-SQSMessage -AttributeName SenderId, SentTimestamp -MessageAttributeName StudentName, StudentGrade -MessageCount 10 -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
Attributes             : {[SenderId, AIDAIAZKMSNQ7TEXAMPLE], [SentTimestamp, 1451495923744]}
Body                   : Information about John Doe's grade.
MD5OfBody              : ea572796e3c231f974fe75d89EXAMPLE
MD5OfMessageAttributes : 48c1ee811f0fe7c4e88fbe0f5EXAMPLE
MessageAttributes      : {[StudentGrade, Amazon.SQS.Model.MessageAttributeValue], [StudentName, Amazon.SQS.Model.MessageAttributeValue]}
MessageId              : 53828c4b-631b-469b-8833-c093cEXAMPLE
ReceiptHandle          : AQEBpfGp...20Q5cg==
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ReceiveMessage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SQSMessage`
<a name="sqs_DeleteMessage_powershell_4_topic"></a>

次のコード例は、`Remove-SQSMessage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した受信ハンドルを持つメッセージを指定したキューから削除します。**  

```
Remove-SQSMessage -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -ReceiptHandle AQEBd329...v6gl8Q==
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteMessage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SQSMessageBatch`
<a name="sqs_DeleteMessageBatch_powershell_4_topic"></a>

次のコード例は、`Remove-SQSMessageBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した受信ハンドルを持つ 2 つのメッセージを指定したキューから削除します。**  

```
$deleteMessageRequest1 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry
$deleteMessageRequest1.Id = "Request1"
$deleteMessageRequest1.ReceiptHandle = "AQEBX2g4...wtJSQg=="

$deleteMessageRequest2 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry
$deleteMessageRequest2.Id = "Request2"
$deleteMessageRequest2.ReceiptHandle = "AQEBqOVY...KTsLYg=="

Remove-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $deleteMessageRequest1, $deleteMessageRequest2
```
**出力:**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {Request1, Request2}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteMessageBatch](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SQSPermission`
<a name="sqs_RemovePermission_powershell_4_topic"></a>

次のコード例は、`Remove-SQSPermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定したラベルを持つアクセス許可設定を、指定したキューから削除します。**  

```
Remove-SQSPermission -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemovePermission](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SQSQueue`
<a name="sqs_DeleteQueue_powershell_4_topic"></a>

次のコード例は、`Remove-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: こので例は、指定したキューを削除します。**  

```
Remove-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteQueue](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Send-SQSMessage`
<a name="sqs_SendMessage_powershell_4_topic"></a>

次のコード例は、`Send-SQSMessage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した属性とメッセージ本文を持つメッセージを指定したキューに送信し、メッセージの配信を 10 秒遅延させます。**  

```
$cityAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Send-SQSMessage -DelayInSeconds 10 -MessageAttributes $messageAttributes -MessageBody "Information about the largest city in Any Region." -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
MD5OfMessageAttributes              MD5OfMessageBody                    MessageId                                          
----------------------              ----------------                    ---------                                          
1d3e51347bc042efbdf6dda31EXAMPLE    51b0a3256d59467f973009b73EXAMPLE    c35fed8f-c739-4d0c-818b-1820eEXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SendMessage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Send-SQSMessageBatch`
<a name="sqs_SendMessageBatch_powershell_4_topic"></a>

次のコード例は、`Send-SQSMessageBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定した属性とメッセージ本文を持つ 2 つのメッセージを指定したキューに送信します。最初のメッセージでは配信を 15 秒遅延させ、2 番目のメッセージでは配信を 10 秒遅延させます。**  

```
$student1NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student1NameAttributeValue.DataType = "String"
$student1NameAttributeValue.StringValue = "John Doe"

$student1GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student1GradeAttributeValue.DataType = "Number"
$student1GradeAttributeValue.StringValue = "89"

$student2NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student2NameAttributeValue.DataType = "String"
$student2NameAttributeValue.StringValue = "Jane Doe"

$student2GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student2GradeAttributeValue.DataType = "Number"
$student2GradeAttributeValue.StringValue = "93"

$message1 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry 
$message1.DelaySeconds = 15
$message1.Id = "FirstMessage"
$message1.MessageAttributes.Add("StudentName", $student1NameAttributeValue)
$message1.MessageAttributes.Add("StudentGrade", $student1GradeAttributeValue)
$message1.MessageBody = "Information about John Doe's grade."

$message2 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry 
$message2.DelaySeconds = 10
$message2.Id = "SecondMessage"
$message2.MessageAttributes.Add("StudentName", $student2NameAttributeValue)
$message2.MessageAttributes.Add("StudentGrade", $student2GradeAttributeValue)
$message2.MessageBody = "Information about Jane Doe's grade."

Send-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $message1, $message2
```
**出力:**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {FirstMessage, SecondMessage}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SendMessageBatch](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Set-SQSQueueAttribute`
<a name="sqs_SetQueueAttributes_powershell_4_topic"></a>

次のコード例は、`Set-SQSQueueAttribute` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、キューを SNS トピックにサブスクライブするポリシーを設定する方法を示します。メッセージをトピックに発行すると、メッセージはサブスクライブしたキューに送信されます。**  

```
# create the queue and topic to be associated
$qurl = New-SQSQueue -QueueName "myQueue"
$topicarn = New-SNSTopic -Name "myTopic"

# get the queue ARN to inject into the policy; it will be returned
# in the output's QueueARN member but we need to put it into a variable
# so text expansion in the policy string takes effect
$qarn = (Get-SQSQueueAttribute -QueueUrl $qurl -AttributeName "QueueArn").QueueARN

# construct the policy and inject arns
$policy = @"
{
  "Version":"2012-10-17",		 	 	 
  "Id": "$qarn/SQSPOLICY",
  "Statement": [
      {
      "Sid": "1",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "SQS:SendMessage",
      "Resource": "$qarn",
      "Condition": {
        "ArnEquals": {
          "aws:SourceArn": "$topicarn"
          }
      }
    }
  ]
}
"@

# set the policy
Set-SQSQueueAttribute -QueueUrl $qurl -Attribute @{ Policy=$policy }
```
**例 2: この例では、指定したキューに指定した属性を設定します。**  

```
Set-SQSQueueAttribute -Attribute @{"DelaySeconds" = "10"; "MaximumMessageSize" = "131072"} -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[SetQueueAttributes](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS STS Tools for PowerShell V4 を使用した の例
<a name="powershell_4_sts_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Convert-STSAuthorizationMessage`
<a name="sts_DecodeAuthorizationMessage_powershell_4_topic"></a>

次のコード例は、`Convert-STSAuthorizationMessage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: リクエストへの応答として返された、指定されたエンコード済みメッセージコンテンツに含まれる追加情報をデコードします。承認ステータスの詳細は、アクションをリクエストしたユーザーが見てはならない特権情報である可能性があるため、追加情報はエンコードされます。**  

```
Convert-STSAuthorizationMessage -EncodedMessage "...encoded message..."
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DecodeAuthorizationMessage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-STSFederationToken`
<a name="sts_GetFederationToken_powershell_4_topic"></a>

次のコード例は、`Get-STSFederationToken` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 「Bob」をフェデレーションユーザーの名前として使用して、1 時間有効なフェデレーショントークンをリクエストします。この名前は、リソースベースのポリシー (Amazon S3 バケットポリシーなど) のフェデレーションユーザー名を参照するために使用できます。提供される JSON 形式の IAM ポリシーを使用して、IAM ユーザーが利用できるアクセス権限の範囲を絞り込みます。指定されたポリシーでは、リクエストしたユーザーに付与されたアクセス権限よりも多くのアクセス権限を付与することはできません。フェデレーションユーザーの最終的なアクセス権限は、渡されたポリシーと IAM ユーザーポリシーの共通部分に基づいて最も制限の厳しい一式となります。**  

```
Get-STSFederationToken -Name "Bob" -Policy "...JSON policy..." -DurationInSeconds 3600
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetFederationToken](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-STSSessionToken`
<a name="sts_GetSessionToken_powershell_4_topic"></a>

次のコード例は、`Get-STSSessionToken` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 一定期間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。一時的な認証情報をリクエストするために使用される認証情報は、現在のシェルのデフォルトから推測されます。他の認証情報を指定するには、-ProfileName または-AccessKey/-SecretKey パラメータを使用します。**  

```
Get-STSSessionToken
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 2: 1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。リクエストを行うために使用される認証情報は、指定されたプロファイルから取得されます。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 3: プロファイル「myprofilename」で認証情報が指定されているアカウントに関連付けられた MFA デバイスの識別番号とデバイスから提供された値を使用して、1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile -SerialNumber YourMFADeviceSerialNumber -TokenCode 123456
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetSessionToken](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Use-STSRole`
<a name="sts_AssumeRole_powershell_4_topic"></a>

次のコード例は、`Use-STSRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: リクエスト元のユーザーが通常アクセスできない AWS リソースにアクセスするために 1 時間使用できる一時的な認証情報 (アクセスキー、シークレットキー、セッショントークン) のセットを返します。返される認証情報には、引き受けているロールのアクセスポリシーと提供されたポリシーで許可されている権限があります (提供されたポリシーを使用して、引き受けているロールのアクセスポリシーで定義されている権限を超える権限を付与することはできません)。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600
```
**例 2: 引き受けているロールのアクセスポリシーで定義されているのと同じ権限を持つ、1 時間有効の一時的な認証情報を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600
```
**例 3: コマンドレットの実行に使用されるユーザー認証情報に関連付けられている MFA からシリアル番号と生成されたトークンを提供する一時的な認証情報一式を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"
```
**例 4: 顧客アカウントで定義されているロールを引き受けた一時的な認証情報一式を返します。第三者が引き受けることができるロールごとに、顧客アカウントは、ロールを引き受けるたび、-ExternalId パラメータで渡す必要がある識別子を使用してロールを作成する必要があります。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssumeRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Use-STSWebIdentityRole`
<a name="sts_AssumeRoleWithWebIdentity_powershell_4_topic"></a>

次のコード例は、`Use-STSWebIdentityRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: Login with Amazon ID プロバイダーで認証されたユーザーの一時的な認証情報一式 (1 時間有効) を返します。認証情報は、ロール ARN によって識別されるロールに関連付けられたアクセスポリシーを引き受けます。オプションで、JSON ポリシーを-Policy パラメータに渡して、アクセス権限をさらに絞り込むことができます (ロールに関連付けられている権限で使用可能な権限よりも多くの権限を付与することはできません)。-WebIdentityToken に渡される値は、ID プロバイダーから返された一意のユーザー識別子です。**  

```
Use-STSWebIdentityRole -DurationInSeconds 3600 -ProviderId "www.amazon.com" -RoleSessionName "app1" -RoleArn "arn:aws:iam::123456789012:role/FederatedWebIdentityRole" -WebIdentityToken "Atza...DVI0r1"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# サポート Tools for PowerShell V4 を使用した の例
<a name="powershell_4_support_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ASACommunicationToCase`
<a name="support_AddCommunicationToCase_powershell_4_topic"></a>

次のコード例は、`Add-ASACommunicationToCase` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定したケースに E メールの本文を追加します。**  

```
Add-ASACommunicationToCase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -CommunicationBody "Some text about the case"
```
**例 2: 指定されたケースに E メールの本文と、E メールの CC 行に含まれる 1 つ以上の E メールアドレスを追加します。**  

```
Add-ASACommunicationToCase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -CcEmailAddress @("email1@address.com", "email2@address.com") -CommunicationBody "Some text about the case"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)*) の「[AddCommunicationToCase](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASACase`
<a name="support_DescribeCases_powershell_4_topic"></a>

次のコード例は、`Get-ASACase` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべてのサポートケースの詳細を返します。**  

```
Get-ASACase
```
**例 2: 指定された日時以降のすべてのサポートケースの詳細を返します。**  

```
Get-ASACase -AfterTime "2013-09-10T03:06Z"
```
**例 3: 解決済みのサポートケースを含め、最初の 10 件のサポートケースの詳細を返します。**  

```
Get-ASACase -MaxResult 10 -IncludeResolvedCases $true
```
**例 4: 単一の指定されたサポートケースの詳細を返します。**  

```
Get-ASACase -CaseIdList "case-12345678910-2013-c4c1d2bf33c5cf47"
```
**例 5: 指定されたサポートケースの詳細を返します。**  

```
Get-ASACase -CaseIdList @("case-12345678910-2013-c4c1d2bf33c5cf47", "case-18929034710-2011-c4fdeabf33c5cf47")
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeCases](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASACommunication`
<a name="support_DescribeCommunications_powershell_4_topic"></a>

次のコード例は、`Get-ASACommunication` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたケースのすべてのコミュニケーションを返します。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
**例 2: 指定されたケースについて、2012 年 1 月 1 日の午前 0 時 (UTC) 以降のすべてのコミュニケーションを返します。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -AfterTime "2012-01-10T00:00Z"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeCommunications](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASAService`
<a name="support_DescribeServices_powershell_4_topic"></a>

次のコード例は、`Get-ASAService` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 使用可能なすべてのサービスコード、名前、カテゴリを返します。**  

```
Get-ASAService
```
**例 2: 指定されたコードを持つサービスの名前とカテゴリを返します。**  

```
Get-ASAService -ServiceCodeList "amazon-cloudfront"
```
**例 3: 指定されたサービスコードの名前とカテゴリを返します。**  

```
Get-ASAService -ServiceCodeList @("amazon-cloudfront", "amazon-cloudwatch")
```
**例 4: 指定されたサービスコードの名前とカテゴリ (日本語) を返します。現在、英語 (「en」) と日本語 (「ja」) の言語コードがサポートされています。**  

```
Get-ASAService -ServiceCodeList @("amazon-cloudfront", "amazon-cloudwatch") -Language "ja"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeServices](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASASeverityLevel`
<a name="support_DescribeSeverityLevels_powershell_4_topic"></a>

次のコード例は、`Get-ASASeverityLevel` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: AWS サポートケースに割り当てることができる重要度レベルのリストを返します。**  

```
Get-ASASeverityLevel
```
**例 2: AWS サポートケースに割り当てることができる重要度レベルのリストを返します。レベルの名前は日本語で返されます。**  

```
Get-ASASeverityLevel -Language "ja"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeSeverityLevels](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASATrustedAdvisorCheck`
<a name="support_DescribeTrustedAdvisorChecks_powershell_4_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheck` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: Trusted Advisor チェックのコレクションを返します。英語出力の場合は「en」、日本語出力の場合は「ja」のいずれかを使用できる Language パラメータを指定する必要があります。**  

```
Get-ASATrustedAdvisorCheck -Language "en"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTrustedAdvisorChecks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASATrustedAdvisorCheckRefreshStatus`
<a name="support_DescribeTrustedAdvisorCheckRefreshStatuses_powershell_4_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheckRefreshStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたチェックの更新リクエストの現在のステータスを返します。Request-ASATrustedAdvisorCheckRefresh を使用して、チェックのステータス情報の更新をリクエストできます。**  

```
Get-ASATrustedAdvisorCheckRefreshStatus -CheckId @("checkid1", "checkid2")
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTrustedAdvisorCheckRefreshStatuses](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASATrustedAdvisorCheckResult`
<a name="support_DescribeTrustedAdvisorCheckResult_powershell_4_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheckResult` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: Trusted Advisor チェックの結果を返します。利用可能な Trusted Advisor チェックのリストは、Get-ASATrustedAdvisorChecks を使用して取得できます。出力は、チェックの全体的なステータス、最後のチェック実行時のタイムスタンプ、および特定のチェックの一意のチェック ID です。結果を日本語で出力するには、-Language「ja」パラメータを追加します。**  

```
Get-ASATrustedAdvisorCheckResult -CheckId "checkid1"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTrustedAdvisorCheckResult](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-ASATrustedAdvisorCheckSummary`
<a name="support_DescribeTrustedAdvisorCheckSummaries_powershell_4_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheckSummary` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された Trusted Advisor チェックの最新の概要を返します。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId "checkid1"
```
**例 2: 指定された Trusted Advisor チェックの最新の概要を返します。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId @("checkid1", "checkid2")
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[DescribeTrustedAdvisorCheckSummaries](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

### `New-ASACase`
<a name="support_CreateCase_powershell_4_topic"></a>

次のコード例は、`New-ASACase` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: AWS サポートセンターで新しいケースを作成します。-ServiceCode および -CategoryCode パラメータの値は、Get-ASAService コマンドレットを使用して取得できます。-SeverityCode パラメータの値は、Get-ASASeverityLevel コマンドレットを使用して取得できます。-IssueType パラメータ値は、「customer-service」または「technical」のいずれかです。成功すると、 AWS サポートケース番号が出力されます。デフォルトでは、ケースは英語で処理され、日本語を使用するには、-Language「ja」パラメータを追加します。-ServiceCode、-CategoryCode、-Subject、-CommunicationBody パラメータは必須です。**  

```
New-ASACase -ServiceCode "amazon-cloudfront" -CategoryCode "APIs" -SeverityCode "low" -Subject "subject text" -CommunicationBody "description of the case" -CcEmailAddress @("email1@domain.com", "email2@domain.com") -IssueType "technical"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateCase](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Request-ASATrustedAdvisorCheckRefresh`
<a name="support_RefreshTrustedAdvisorCheck_powershell_4_topic"></a>

次のコード例は、`Request-ASATrustedAdvisorCheckRefresh` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された Trusted Advisor チェックの更新をリクエストします。**  

```
Request-ASATrustedAdvisorCheckRefresh -CheckId "checkid1"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RefreshTrustedAdvisorCheck](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Resolve-ASACase`
<a name="support_ResolveCase_powershell_4_topic"></a>

次のコード例は、`Resolve-ASACase` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたケースの初期状態と、解決のための呼び出しが完了した後の現在の状態を返します。**  

```
Resolve-ASACase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ResolveCase](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した Systems Manager の例
<a name="powershell_4_ssm_code_examples"></a>

次のコード例は、Systems Manager で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-SSMResourceTag`
<a name="ssm_AddTagsToResource_powershell_4_topic"></a>

次のコード例は、`Add-SSMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しいタグを使用してメンテナンスウィンドウを更新します。コマンドが成功した場合、出力はありません。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$option1 = @{Key="Stack";Value=@("Production")}
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $option1
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して各タグを作成する必要があります。コマンドが成功した場合、出力はありません。**  

```
$tag1 = New-Object Amazon.SimpleSystemsManagement.Model.Tag
$tag1.Key = "Stack"
$tag1.Value = "Production"
		
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $tag1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AddTagsToResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-SSMDocumentPermission`
<a name="ssm_ModifyDocumentPermission_powershell_4_topic"></a>

次のコード例は、`Edit-SSMDocumentPermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ドキュメントのすべてのアカウントに「共有」アクセス許可を追加します。コマンドが成功した場合、出力はありません。**  

```
Edit-SSMDocumentPermission -Name "RunShellScript" -PermissionType "Share" -AccountIdsToAdd all
```
**例 2: この例では、ドキュメントの特定のアカウントに「共有」アクセス許可を追加します。コマンドが成功した場合、出力はありません。**  

```
Edit-SSMDocumentPermission -Name "RunShellScriptNew" -PermissionType "Share" -AccountIdsToAdd "123456789012"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyDocumentPermission](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMActivation`
<a name="ssm_DescribeActivations_powershell_4_topic"></a>

次のコード例は、`Get-SSMActivation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントのアクティベーションに関する詳細情報を示します。**  

```
Get-SSMActivation
```
**出力:**  

```
ActivationId        : 08e51e79-1e36-446c-8e63-9458569c1363
CreatedDate         : 3/1/2017 12:01:51 AM
DefaultInstanceName : MyWebServers
Description         :
ExpirationDate      : 3/2/2017 12:01:51 AM
Expired             : False
IamRole             : AutomationRole
RegistrationLimit   : 10
RegistrationsCount  : 0
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeActivations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAssociation`
<a name="ssm_DescribeAssociation_powershell_4_topic"></a>

次のコード例は、`Get-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスとドキュメントの関連付けを記述します。**  

```
Get-SSMAssociation -InstanceId "i-0000293ffd8c57862" -Name "AWS-UpdateSSMAgent"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temp_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAssociation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAssociationExecution`
<a name="ssm_DescribeAssociationExecutions_powershell_4_topic"></a>

次のコード例は、`Get-SSMAssociationExecution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された関連付け ID の実行を返します。**  

```
Get-SSMAssociationExecution -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**出力:**  

```
AssociationId         : 123a45a0-c678-9012-3456-78901234db5e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 123a45a0-c678-9012-3456-78901234db5e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=4}
Status                : Success
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAssociationExecutions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAssociationExecutionTarget`
<a name="ssm_DescribeAssociationExecutionTargets_powershell_4_topic"></a>

次のコード例は、`Get-SSMAssociationExecutionTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、関連付けの実行ターゲットの一部であるリソース ID とその実行ステータスを表示します。**  

```
Get-SSMAssociationExecutionTarget -AssociationId 123a45a0-c678-9012-3456-78901234db5e -ExecutionId 123a45a0-c678-9012-3456-78901234db5e | Select-Object ResourceId, Status
```
**出力:**  

```
ResourceId           Status
----------           ------
i-0b1b2a3456f7a890b  Success
i-01c12a45d6fc7a89f  Success
i-0a1caf234f56d7dc8  Success
i-012a3fd45af6dbcfe  Failed
i-0ddc1df23c4a5fb67  Success
```
**例 2: このコマンドは、コマンドドキュメントが関連付けられている昨日以降の特定のオートメーションにおける、特定の実行をチェックします。さらに、関連付けの実行が失敗したかどうかを確認し、失敗した場合は、実行のコマンド呼び出しの詳細情報とインスタンス ID が表示されます。**  

```
$AssociationExecution= Get-SSMAssociationExecutionTarget -AssociationId 1c234567-890f-1aca-a234-5a678d901cb0 -ExecutionId 12345ca12-3456-2345-2b45-23456789012 | 
    Where-Object {$_.LastExecutionDate -gt (Get-Date -Hour 00 -Minute 00).AddDays(-1)} 

foreach ($execution in $AssociationExecution) {
    if($execution.Status -ne 'Success'){
        Write-Output "There was an issue executing the association $($execution.AssociationId) on $($execution.ResourceId)"
        Get-SSMCommandInvocation -CommandId $execution.OutputSource.OutputSourceId -Detail:$true | Select-Object -ExpandProperty CommandPlugins
    }
}
```
**出力:**  

```
There was an issue executing the association 1c234567-890f-1aca-a234-5a678d901cb0 on i-0a1caf234f56d7dc8


Name                   : aws:runPowerShellScript
Output                 : 
                         ----------ERROR-------
                         failed to run commands: exit status 1
OutputS3BucketName     : 
OutputS3KeyPrefix      : 
OutputS3Region         : eu-west-1
ResponseCode           : 1
ResponseFinishDateTime : 5/29/2019 11:04:49 AM
ResponseStartDateTime  : 5/29/2019 11:04:49 AM
StandardErrorUrl       : 
StandardOutputUrl      : 
Status                 : Failed
StatusDetails          : Failed
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAssociationExecutionTargets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAssociationList`
<a name="ssm_ListAssociations_powershell_4_topic"></a>

次のコード例は、`Get-SSMAssociationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスのすべての関連付けを一覧表示します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="InstanceId";Value=@("i-0000293ffd8c57862")}
Get-SSMAssociationList -AssociationFilterList $filter1
```
**出力:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**例 2: この例では、設定ドキュメントのすべての関連付けを一覧表示します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter2 = @{Key="Name";Value=@("AWS-UpdateSSMAgent")}
Get-SSMAssociationList -AssociationFilterList $filter2
```
**出力:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**例 3: PowerShell バージョン 2 では、New-Object を使用して各フィルターを作成する必要があります。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.AssociationFilter
$filter1.Key = "InstanceId"
$filter1.Value = "i-0000293ffd8c57862"

Get-SSMAssociationList -AssociationFilterList $filter1
```
**出力:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAssociations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAssociationVersionList`
<a name="ssm_ListAssociationVersions_powershell_4_topic"></a>

次のコード例は、`Get-SSMAssociationVersionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定された関連付けのすべてのバージョンを取得します。**  

```
Get-SSMAssociationVersionList -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**出力:**  

```
AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    :
AssociationVersion : 2
ComplianceSeverity :
CreatedDate        : 3/12/2019 9:21:01 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression :
Targets            : {InstanceIds}

AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    : test-case-1234567890
AssociationVersion : 1
ComplianceSeverity :
CreatedDate        : 3/2/2019 8:53:29 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression : rate(30minutes)
Targets            : {InstanceIds}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListAssociationVersions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAutomationExecution`
<a name="ssm_GetAutomationExecution_powershell_4_topic"></a>

次のコード例は、`Get-SSMAutomationExecution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、オートメーションの実行に関する詳細を表示します。**  

```
Get-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
**出力:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
FailureMessage            : Step launchInstance failed maximum allowed times. You are not authorized to perform this operation. Encoded
                            authorization failure message: B_V2QyyN7NhSZQYpmVzpEc4oSnj2GLTNYnXUHsTbqJkNMoDgubmbtthLmZyaiUYekORIrA42-fv1x-04q5Fjff6glh
                            Yb6TI5b0GQeeNrpwNvpDzmO-PSR1swlAbg9fdM9BcNjyrznspUkWpuKu9EC1Ou6v3OXU1KC9nZ7mPlWMFZNkSioQqpwWEvMw-GZktsQzm67qOhUhBNOLWYhbS
                            pkfiqzY-5nw3S0obx30fhd3EJa5O_-GjV_a0nFXQJa70ik40bFOrEh3MtCSbrQT6--DvFy_FQ8TKvkIXadyVskeJI84XOF5WmA60f1pi5GI08i-nRfZS6oDeU
                            gELBjjoFKD8s3L2aI0B6umWVxnQOjqhQRxwJ53b54sZJ2PW3v_mtg9-q0CK0ezS3xfh_y0ilaUGOAZG-xjQFuvU_JZedWpla3xi-MZsmblAifBI
                            (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID:
                            6a002f94-ba37-43fd-99e6-39517715fce5)
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
Parameters                : {[AutomationAssumeRole, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [InstanceIamRole,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [SourceAmiId,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
StepExecutions            : {launchInstance, updateOSSoftware, stopInstance, createImage...}
```
**例 2: この例では、指定されたオートメーションの実行 ID におけるステップの詳細情報を一覧表示します。**  

```
Get-SSMAutomationExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object -ExpandProperty StepExecutions | Select-Object StepName, Action, StepStatus, ValidNextSteps
```
**出力:**  

```
StepName                  Action                  StepStatus ValidNextSteps
--------                  ------                  ---------- --------------
LaunchInstance            aws:runInstances        Success    {OSCompatibilityCheck}
OSCompatibilityCheck      aws:runCommand          Success    {RunPreUpdateScript}
RunPreUpdateScript        aws:runCommand          Success    {UpdateEC2Config}
UpdateEC2Config           aws:runCommand          Cancelled  {}
UpdateSSMAgent            aws:runCommand          Pending    {}
UpdateAWSPVDriver         aws:runCommand          Pending    {}
UpdateAWSEnaNetworkDriver aws:runCommand          Pending    {}
UpdateAWSNVMe             aws:runCommand          Pending    {}
InstallWindowsUpdates     aws:runCommand          Pending    {}
RunPostUpdateScript       aws:runCommand          Pending    {}
RunSysprepGeneralize      aws:runCommand          Pending    {}
StopInstance              aws:changeInstanceState Pending    {}
CreateImage               aws:createImage         Pending    {}
TerminateInstance         aws:changeInstanceState Pending    {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetAutomationExecution](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAutomationExecutionList`
<a name="ssm_DescribeAutomationExecutions_powershell_4_topic"></a>

次のコード例は、`Get-SSMAutomationExecutionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントに関連付けられているすべてのアクティブなオートメーションの実行と、終了したオートメーションの実行を記述します。**  

```
Get-SSMAutomationExecutionList
```
**出力:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutedBy                : admin
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
LogFile                   :
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
```
**例 2: この例では、AutomationExecutionStatus の「Success」以外の実行について、ExecutionID、ドキュメント、実行開始/終了タイムスタンプを表示します。**  

```
Get-SSMAutomationExecutionList | Where-Object AutomationExecutionStatus -ne "Success" | Select-Object AutomationExecutionId, DocumentName, AutomationExecutionStatus, ExecutionStartTime, ExecutionEndTime | Format-Table -AutoSize
```
**出力:**  

```
AutomationExecutionId                DocumentName                            AutomationExecutionStatus ExecutionStartTime   ExecutionEndTime
---------------------                ------------                            ------------------------- ------------------   ----------------
e1d2bad3-4567-8901-ae23-456c7c8901be AWS-UpdateWindowsAmi                    Cancelled                 4/16/2019 5:37:04 AM 4/16/2019 5:47:29 AM
61234567-a7f8-90e1-2b34-567b8bf9012c Fixed-UpdateAmi                         Cancelled                 4/16/2019 5:33:04 AM 4/16/2019 5:40:15 AM
91234d56-7e89-0ac1-2aee-34ea5d6a7c89 AWS-UpdateWindowsAmi                    Failed                    4/16/2019 5:22:46 AM 4/16/2019 5:27:29 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAutomationExecutions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAutomationStepExecution`
<a name="ssm_DescribeAutomationStepExecutions_powershell_4_topic"></a>

次のコード例は、`Get-SSMAutomationStepExecution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、オートメーションワークフローにおけるすべてのアクティブなステップの実行と、終了したステップの実行に関する情報を表示します。**  

```
Get-SSMAutomationStepExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object StepName, Action, StepStatus
```
**出力:**  

```
StepName                  Action                  StepStatus
--------                  ------                  ----------
LaunchInstance            aws:runInstances        Success
OSCompatibilityCheck      aws:runCommand          Success
RunPreUpdateScript        aws:runCommand          Success
UpdateEC2Config           aws:runCommand          Cancelled
UpdateSSMAgent            aws:runCommand          Pending
UpdateAWSPVDriver         aws:runCommand          Pending
UpdateAWSEnaNetworkDriver aws:runCommand          Pending
UpdateAWSNVMe             aws:runCommand          Pending
InstallWindowsUpdates     aws:runCommand          Pending
RunPostUpdateScript       aws:runCommand          Pending
RunSysprepGeneralize      aws:runCommand          Pending
StopInstance              aws:changeInstanceState Pending
CreateImage               aws:createImage         Pending
TerminateInstance         aws:changeInstanceState Pending
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAutomationStepExecutions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMAvailablePatch`
<a name="ssm_DescribeAvailablePatches_powershell_4_topic"></a>

次のコード例は、`Get-SSMAvailablePatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Windows Server 2012 で利用でき、MSRC 重要度が「緊急」のすべてのパッチを取得します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="PRODUCT";Values=@("WindowsServer2012")}
$filter2 = @{Key="MSRC_SEVERITY";Values=@("Critical")}

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**出力:**  

```
Classification : SecurityUpdates
ContentUrl     : https://support.microsoft.com/en-us/kb/2727528
Description    : A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain control
                 over it. You can help protect your system by installing this update from Microsoft. After you install this update, you may have to
                 restart your system.
Id             : 1eb507be-2040-4eeb-803d-abc55700b715
KbNumber       : KB2727528
Language       : All
MsrcNumber     : MS12-072
MsrcSeverity   : Critical
Product        : WindowsServer2012
ProductFamily  : Windows
ReleaseDate    : 11/13/2012 6:00:00 PM
Title          : Security Update for Windows Server 2012 (KB2727528)
Vendor         : Microsoft
...
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して各フィルターを作成する必要があります。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "PRODUCT"
$filter1.Values = "WindowsServer2012"
$filter2 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter2.Key = "MSRC_SEVERITY"
$filter2.Values = "Critical"

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**例 3: この例では、過去 20 日間にリリースされた、Windows Server 2019 に一致する製品に適用されるすべてのパッチの更新情報を取得します。**  

```
Get-SSMAvailablePatch | Where-Object ReleaseDate -ge (Get-Date).AddDays(-20) | Where-Object Product -eq "WindowsServer2019" | Select-Object ReleaseDate, Product, Title
```
**出力:**  

```
ReleaseDate         Product           Title
-----------         -------           -----
4/9/2019 5:00:12 PM WindowsServer2019 2019-04 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4493478)
4/9/2019 5:00:06 PM WindowsServer2019 2019-04 Cumulative Update for Windows Server 2019 for x64-based Systems (KB4493509)
4/2/2019 5:00:06 PM WindowsServer2019 2019-03 Servicing Stack Update for Windows Server 2019 for x64-based Systems (KB4493510)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeAvailablePatches](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMCommand`
<a name="ssm_ListCommands_powershell_4_topic"></a>

次のコード例は、`Get-SSMCommand` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リクエストされたすべてのコマンドを一覧表示します。**  

```
Get-SSMCommand
```
**出力:**  

```
CommandId          : 4b75a163-d39a-4d97-87c9-98ae52c6be35
Comment            : Apply association with id at update time: 4cc73e42-d5ae-4879-84f8-57e09c0efcd0
CompletedCount     : 1
DocumentName       : AWS-RefreshAssociation
ErrorCount         : 0
ExpiresAfter       : 2/24/2017 3:19:08 AM
InstanceIds        : {i-0cb2b964d3e14fd9f}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName :
OutputS3KeyPrefix  :
OutputS3Region     :
Parameters         : {[associationIds, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 2/24/2017 3:18:08 AM
ServiceRole        :
Status             : Success
StatusDetails      : Success
TargetCount        : 1
Targets            : {}
```
**例 2: この例では、特定のコマンドのステータスを取得します。**  

```
Get-SSMCommand -CommandId "4b75a163-d39a-4d97-87c9-98ae52c6be35"
```
**例 3: この例では、2019-04-01T00:00:00Z より後に呼び出されたすべての SSM コマンドを取得します。 **  

```
Get-SSMCommand -Filter @{Key="InvokedAfter";Value="2019-04-01T00:00:00Z"} | Select-Object CommandId, DocumentName, Status, RequestedDateTime | Sort-Object -Property RequestedDateTime -Descending
```
**出力:**  

```
CommandId                            DocumentName               Status    RequestedDateTime
---------                            ------------               ------    -----------------
edb1b23e-456a-7adb-aef8-90e-012ac34f AWS-RunPowerShellScript    Cancelled 4/16/2019 5:45:23 AM
1a2dc3fb-4567-890d-a1ad-234b5d6bc7d9 AWS-ConfigureAWSPackage    Success   4/6/2019 9:19:42 AM
12c3456c-7e90-4f12-1232-1234f5b67893 KT-Retrieve-Cloud-Type-Win Failed    4/2/2019 4:13:07 AM
fe123b45-240c-4123-a2b3-234bdd567ecf AWS-RunInspecChecks        Failed    4/1/2019 2:27:31 PM
1eb23aa4-567d-4123-12a3-4c1c2ab34561 AWS-RunPowerShellScript    Success   4/1/2019 1:05:55 PM
1c2f3bb4-ee12-4bc1-1a23-12345eea123e AWS-RunInspecChecks        Failed    4/1/2019 11:13:09 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListCommands](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMCommandInvocation`
<a name="ssm_ListCommandInvocations_powershell_4_topic"></a>

次のコード例は、`Get-SSMCommandInvocation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、コマンドのすべての呼び出しを一覧表示します。**  

```
Get-SSMCommandInvocation -CommandId "b8eac879-0541-439d-94ec-47a80d554f44" -Detail $true
```
**出力:**  

```
CommandId          : b8eac879-0541-439d-94ec-47a80d554f44
CommandPlugins     : {aws:runShellScript}
Comment            : IP config
DocumentName       : AWS-RunShellScript
InstanceId         : i-0cb2b964d3e14fd9f
InstanceName       :
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
RequestedDateTime  : 2/22/2017 8:13:16 PM
ServiceRole        :
StandardErrorUrl   :
StandardOutputUrl  :
Status             : Success
StatusDetails      : Success
TraceOutput        :
```
**例 2: この例では、コマンド ID e1eb2e3c-ed4c-5123-45c1-234f5612345f の呼び出し用の CommandPlugins を一覧表示します。**  

```
Get-SSMCommandInvocation -CommandId e1eb2e3c-ed4c-5123-45c1-234f5612345f -Detail:$true | Select-Object -ExpandProperty CommandPlugins
```
**出力:**  

```
Name                   : aws:runPowerShellScript
Output                 : Completed 17.7 KiB/17.7 KiB (40.1 KiB/s) with 1 file(s) remainingdownload: s3://dd-aess-r-ctmer/KUMO.png to ..\..\programdata\KUMO.png
                         kumo available

OutputS3BucketName     :
OutputS3KeyPrefix      :
OutputS3Region         : eu-west-1
ResponseCode           : 0
ResponseFinishDateTime : 4/3/2019 11:53:23 AM
ResponseStartDateTime  : 4/3/2019 11:53:21 AM
StandardErrorUrl       :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListCommandInvocations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMCommandInvocationDetail`
<a name="ssm_GetCommandInvocation_powershell_4_topic"></a>

次のコード例は、`Get-SSMCommandInvocationDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスで実行されたコマンドの詳細情報を表示します。**  

```
Get-SSMCommandInvocationDetail -InstanceId "i-0cb2b964d3e14fd9f" -CommandId "b8eac879-0541-439d-94ec-47a80d554f44"
```
**出力:**  

```
CommandId              : b8eac879-0541-439d-94ec-47a80d554f44
Comment                : IP config
DocumentName           : AWS-RunShellScript
ExecutionElapsedTime   : PT0.004S
ExecutionEndDateTime   : 2017-02-22T20:13:16.651Z
ExecutionStartDateTime : 2017-02-22T20:13:16.651Z
InstanceId             : i-0cb2b964d3e14fd9f
PluginName             : aws:runShellScript
ResponseCode           : 0
StandardErrorContent   :
StandardErrorUrl       :
StandardOutputContent  :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetCommandInvocation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMComplianceItemList`
<a name="ssm_ListComplianceItems_powershell_4_topic"></a>

次のコード例は、`Get-SSMComplianceItemList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、任意のリソース ID とタイプのコンプライアンス項目リストを一覧表示し、コンプライアンスタイプを「関連付け」でフィルタリングします。**  

```
Get-SSMComplianceItemList -ResourceId i-1a2caf345f67d0dc2 -ResourceType ManagedInstance -Filter @{Key="ComplianceType";Values="Association"}
```
**出力:**  

```
ComplianceType   : Association
Details          : {[DocumentName, AWS-GatherSoftwareInventory], [DocumentVersion, 1]}
ExecutionSummary : Amazon.SimpleSystemsManagement.Model.ComplianceExecutionSummary
Id               : 123a45a1-c234-1234-1245-67891236db4e
ResourceId       : i-1a2caf345f67d0dc2
ResourceType     : ManagedInstance
Severity         : UNSPECIFIED
Status           : COMPLIANT
Title            :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListComplianceItems](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMComplianceSummaryList`
<a name="ssm_ListComplianceSummaries_powershell_4_topic"></a>

次のコード例は、`Get-SSMComplianceSummaryList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべてのコンプライアンスタイプの準拠リソースと非準拠リソースの集計カウントを返します。**  

```
Get-SSMComplianceSummaryList
```
**出力:**  

```
ComplianceType CompliantSummary                                      NonCompliantSummary
-------------- ----------------                                      -------------------
FleetTotal     Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Association    Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Custom:InSpec  Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Patch          Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListComplianceSummaries](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMConnectionStatus`
<a name="ssm_GetConnectionStatus_powershell_4_topic"></a>

次のコード例は、`Get-SSMConnectionStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスが接続され、Session Manager 接続を受信する準備ができているかどうかを判断するため、インスタンスの Session Manager 接続ステータスを取得します。**  

```
Get-SSMConnectionStatus -Target i-0a1caf234f12d3dc4
```
**出力:**  

```
Status    Target
------    ------
Connected i-0a1caf234f12d3dc4
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetConnectionStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMDefaultPatchBaseline`
<a name="ssm_GetDefaultPatchBaseline_powershell_4_topic"></a>

次のコード例は、`Get-SSMDefaultPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、デフォルトのパッチベースラインを表示します。**  

```
Get-SSMDefaultPatchBaseline
```
**出力:**  

```
arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMDeployablePatchSnapshotForInstance`
<a name="ssm_GetDeployablePatchSnapshotForInstance_powershell_4_topic"></a>

次のコード例は、`Get-SSMDeployablePatchSnapshotForInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスで使用されるパッチベースラインの現在のスナップショットを表示します。このコマンドは、インスタンス認証情報を使用してインスタンスから実行する必要があります。この例では、インスタンス認証情報が使用されるようにするため、Credentials パラメータに `Amazon.Runtime.InstanceProfileAWSCredentials` オブジェクトを渡します。**  

```
$credentials = [Amazon.Runtime.InstanceProfileAWSCredentials]::new()
Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f" -Credentials $credentials
```
**出力:**  

```
InstanceId          SnapshotDownloadUrl
----------          -------------------
i-0cb2b964d3e14fd9f https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...1692/4681775b-098f-4435...
```
**例 2: この例は、完全な SnapshotDownloadUrl を取得する方法を示しています。このコマンドは、インスタンス認証情報を使用してインスタンスから実行する必要があります。この例では、インスタンス認証情報が使用されるようにするため PowerShell セッションが `Amazon.Runtime.InstanceProfileAWSCredentials` オブジェクトを使用するように設定しています。**  

```
Set-AWSCredential -Credential ([Amazon.Runtime.InstanceProfileAWSCredentials]::new())
(Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f").SnapshotDownloadUrl
```
**出力:**  

```
https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDeployablePatchSnapshotForInstance](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMDocument`
<a name="ssm_GetDocument_powershell_4_topic"></a>

次のコード例は、`Get-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ドキュメントのコンテンツを返します。**  

```
Get-SSMDocument -Name "RunShellScript"
```
**出力:**  

```
Content
-------
{...
```
**例 2: この例では、ドキュメントの完全なコンテンツを表示します。**  

```
(Get-SSMDocument -Name "RunShellScript").Content
{
   "schemaVersion":"2.0",
   "description":"Run an updated script",
   "parameters":{
      "commands":{
         "type":"StringList",
         "description":"(Required) Specify a shell script or a command to run.",
         "minItems":1,
         "displayType":"textarea"
      }
   },
   "mainSteps":[
      {
         "action":"aws:runShellScript",
         "name":"runShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      },
      {
         "action":"aws:runPowerShellScript",
         "name":"runPowerShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      }
   ]
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetDocument](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMDocumentDescription`
<a name="ssm_DescribeDocument_powershell_4_topic"></a>

次のコード例は、`Get-SSMDocumentDescription` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ドキュメントに関する情報を返します。**  

```
Get-SSMDocumentDescription -Name "RunShellScript"
```
**出力:**  

```
CreatedDate     : 2/24/2017 5:25:13 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 123456789012
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Active
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDocument](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMDocumentList`
<a name="ssm_ListDocuments_powershell_4_topic"></a>

次のコード例は、`Get-SSMDocumentList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: アカウント内のすべての設定ドキュメントを一覧表示します。**  

```
Get-SSMDocumentList
```
**出力:**  

```
DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ApplyPatchBaseline
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureAWSPackage
Owner           : Amazon
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 2.0

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureCloudWatch
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2
...
```
**例 2: この例では、名前が「プラットフォーム」と一致するすべてのオートメーションドキュメントを取得します。**  

```
Get-SSMDocumentList -DocumentFilterList @{Key="DocumentType";Value="Automation"} | Where-Object Name -Match "Platform"
```
**出力:**  

```
DocumentFormat  : JSON
DocumentType    : Automation
DocumentVersion : 7
Name            : KT-Get-Platform
Owner           : 987654123456
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 0.3
Tags            : {}
TargetType      :
VersionName     :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDocuments](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMDocumentPermission`
<a name="ssm_DescribeDocumentPermission_powershell_4_topic"></a>

次のコード例は、`Get-SSMDocumentPermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ドキュメントのすべてのバージョンを一覧表示します。**  

```
Get-SSMDocumentVersionList -Name "RunShellScript"
```
**出力:**  

```
CreatedDate          DocumentVersion IsDefaultVersion Name
-----------          --------------- ---------------- ----
2/24/2017 5:25:13 AM 1               True             RunShellScript
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeDocumentPermission](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMDocumentVersionList`
<a name="ssm_ListDocumentVersions_powershell_4_topic"></a>

次のコード例は、`Get-SSMDocumentVersionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ドキュメントのすべてのバージョンを一覧表示します。**  

```
Get-SSMDocumentVersionList -Name "AWS-UpdateSSMAgent"
```
**出力:**  

```
CreatedDate       : 6/1/2021 5:19:10 PM
DocumentFormat    : JSON
DocumentVersion   : 1
IsDefaultVersion  : True
Name              : AWS-UpdateSSMAgent
Status            : Active
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListDocumentVersions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMEffectiveInstanceAssociationList`
<a name="ssm_DescribeEffectiveInstanceAssociations_powershell_4_topic"></a>

次のコード例は、`Get-SSMEffectiveInstanceAssociationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスの有効な関連付けを記述します。**  

```
Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5
```
**出力:**  

```
AssociationId                        Content
-------------                        -------
d8617c07-2079-4c18-9847-1655fc2698b0 {...
```
**例 2: この例では、インスタンスの有効な関連付けの内容を記述します。**  

```
(Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5).Content
```
**出力:**  

```
{
    "schemaVersion": "1.2",
    "description": "Update the Amazon SSM Agent to the latest version or specified version.",
    "parameters": {
        "version": {
            "default": "",
            "description": "(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agen
t will be updated to the latest version.",
            "type": "String"
        },
        "allowDowngrade": {
            "default": "false",
            "description": "(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set
 to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.",
            "type": "String",
            "allowedValues": [
                "true",
                "false"
            ]
        }
    },
    "runtimeConfig": {
        "aws:updateSsmAgent": {
            "properties": [
                {
                "agentName": "amazon-ssm-agent",
                "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json",
                "allowDowngrade": "{{ allowDowngrade }}",
                "targetVersion": "{{ version }}"
                }
            ]
        }
    }
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEffectiveInstanceAssociations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMEffectivePatchesForPatchBaseline`
<a name="ssm_DescribeEffectivePatchesForPatchBaseline_powershell_4_topic"></a>

次のコード例は、`Get-SSMEffectivePatchesForPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべてのパッチベースラインを一覧表示します。結果の最大表示件数は 1 です。**  

```
Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1
```
**出力:**  

```
Patch                                      PatchStatus
-----                                      -----------
Amazon.SimpleSystemsManagement.Model.Patch Amazon.SimpleSystemsManagement.Model.PatchStatus
```
**例 2: この例では、すべてのパッチベースラインのパッチステータスを表示します。結果の最大表示件数は 1 です。**  

```
(Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1).PatchStatus
```
**出力:**  

```
ApprovalDate          DeploymentStatus
------------          ----------------
12/21/2010 6:00:00 PM APPROVED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeEffectivePatchesForPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInstanceAssociationsStatus`
<a name="ssm_DescribeInstanceAssociationsStatus_powershell_4_topic"></a>

次のコード例は、`Get-SSMInstanceAssociationsStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスの関連付けの詳細情報を表示します。**  

```
Get-SSMInstanceAssociationsStatus -InstanceId "i-0000293ffd8c57862"
```
**出力:**  

```
AssociationId    : d8617c07-2079-4c18-9847-1655fc2698b0
DetailedStatus   : Pending
DocumentVersion  : 1
ErrorCode        :
ExecutionDate    : 2/20/2015 8:31:11 AM
ExecutionSummary : temp_status_change
InstanceId       : i-0000293ffd8c57862
Name             : AWS-UpdateSSMAgent
OutputUrl        :
Status           : Pending
```
**例 2: この例では、指定されたインスタンス ID におけるインスタンスの関連付けのステータスを確認し、それらの関連付けの実行ステータスを表示します。**  

```
Get-SSMInstanceAssociationsStatus -InstanceId i-012e3cb4df567e8aa | ForEach-Object {Get-SSMAssociationExecution -AssociationId .AssociationId}
```
**出力:**  

```
AssociationId         : 512a34a5-c678-1234-1234-12345678db9e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 512a34a5-c678-1234-1234-12345678db9e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=9}
Status                : Success
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstanceAssociationsStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInstanceInformation`
<a name="ssm_DescribeInstanceInformation_powershell_4_topic"></a>

次のコード例は、`Get-SSMInstanceInformation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、各インスタンスの詳細情報を表示します。**  

```
Get-SSMInstanceInformation
```
**出力:**  

```
ActivationId                           :
AgentVersion                           : 2.0.672.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : ip-172-31-44-222.us-west-2.compute.internal
IamRole                                :
InstanceId                             : i-0cb2b964d3e14fd9f
IPAddress                              : 172.31.44.222
IsLatestVersion                        : True
LastAssociationExecutionDate           : 2/24/2017 3:18:09 AM
LastPingDateTime                       : 2/24/2017 3:35:03 AM
LastSuccessfulAssociationExecutionDate : 2/24/2017 3:18:09 AM
Name                                   :
PingStatus                             : ConnectionLost
PlatformName                           : Amazon Linux AMI
PlatformType                           : Linux
PlatformVersion                        : 2016.09
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**例 2: この例では、-Filter パラメータを使用して、 `AgentVersion`が `us-east-1`のリージョン内の AWS Systems Manager インスタンスのみに結果をフィルタリングする方法を示します`2.2.800.0`。有効な -Filter キー値のリストは、InstanceInformation の API リファレンストピック (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformation.html\$1systemsmanager-Type-InstanceInformation-ActivationId) で確認できます。**  

```
$Filters = @{
    Key="AgentVersion"
    Values="2.2.800.0"
}
Get-SSMInstanceInformation -Region us-east-1 -Filter $Filters
```
**出力:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.01
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.02
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**例 3: この例では、-InstanceInformationFilterList パラメータを使用して、 `Windows`または `us-east-1``PlatformTypes`を持つリージョン内の AWS Systems Manager インスタンスのみに結果をフィルタリングする方法を示します`Linux`。有効な -InstanceInformationFilterList キー値のリストは、InstanceInformationFilter の API リファレンストピック (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformationFilter.html) で確認できます。**  

```
$Filters = @{
   Key="PlatformTypes"
   ValueSet=("Windows","Linux")
}
Get-SSMInstanceInformation -Region us-east-1 -InstanceInformationFilterList $Filters
```
**出力:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.27
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Ubuntu Server 18.04 LTS
PlatformType                           : Linux
PlatformVersion                        : 18.04
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.100
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**例 4: この例では、ssm マネージドインスタンスを一覧表示し、InstanceId、PingStatus、LastPingDateTime、PlatformName を csv ファイルにエクスポートします。**  

```
Get-SSMInstanceInformation | Select-Object InstanceId, PingStatus, LastPingDateTime, PlatformName | Export-Csv Instance-details.csv -NoTypeInformation
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstanceInformation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInstancePatch`
<a name="ssm_DescribeInstancePatches_powershell_4_topic"></a>

次のコード例は、`Get-SSMInstancePatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスのパッチコンプライアンスの詳細を取得します。**  

```
Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstancePatches](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInstancePatchState`
<a name="ssm_DescribeInstancePatchStates_powershell_4_topic"></a>

次のコード例は、`Get-SSMInstancePatchState` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスのパッチの概要状態を取得します。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407"
```
**例 2: この例では、2 つのインスタンスにおけるパッチの概要状態を取得します。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407","i-09a618aec652973a9"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstancePatchStates](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInstancePatchStatesForPatchGroup`
<a name="ssm_DescribeInstancePatchStatesForPatchGroup_powershell_4_topic"></a>

次のコード例は、`Get-SSMInstancePatchStatesForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチグループにおけるインスタンスごとのパッチの概要状態を取得します。**  

```
Get-SSMInstancePatchStatesForPatchGroup -PatchGroup "Production"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeInstancePatchStatesForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInventory`
<a name="ssm_GetInventory_powershell_4_topic"></a>

次のコード例は、`Get-SSMInventory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インベントリのカスタムメタデータを取得します。**  

```
Get-SSMInventory
```
**出力:**  

```
Data                                                                                  Id
----                                                                                  --
{[AWS:InstanceInformation, Amazon.SimpleSystemsManagement.Model.InventoryResultItem]} i-0cb2b964d3e14fd9f
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetInventory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInventoryEntriesList`
<a name="ssm_ListInventoryEntries_powershell_4_topic"></a>

次のコード例は、`Get-SSMInventoryEntriesList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスのすべてのカスタムインベントリエントリを一覧表示します。**  

```
Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo"
```
**出力:**  

```
CaptureTime   : 2016-08-22T10:01:01Z
Entries       : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,System.String]}
InstanceId    : i-0cb2b964d3e14fd9f
NextToken     :
SchemaVersion : 1.0
TypeName      : Custom:RackInfo
```
**例 2: この例では詳細を一覧表示します。**  

```
(Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo").Entries
```
**出力:**  

```
Key          Value
---          -----
RackLocation Bay B/Row C/Rack D/Shelf E
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListInventoryEntries](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInventoryEntryList`
<a name="ssm_Get-SSMInventoryEntryList_powershell_4_topic"></a>

次のコード例は、`Get-SSMInventoryEntryList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスの `AWS:Network` タイプのインベントリエントリを取得します。**  

```
Get-SSMInventoryEntryList -InstanceId mi-088dcb0ecea37b076 -TypeName AWS:Network | Select-Object -ExpandProperty Entries
```
**出力:**  

```
Key        Value
---        -----
DHCPServer 172.31.11.2
DNSServer  172.31.0.1
Gateway    172.31.11.2
IPV4       172.31.11.222
IPV6       fe12::3456:7da8:901a:12a3
MacAddress 1A:23:4E:5B:FB:67
Name       Amazon Elastic Network Adapter
SubnetMask 255.255.240.0
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Get-SSMInventoryEntryList](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMInventorySchema`
<a name="ssm_GetInventorySchema_powershell_4_topic"></a>

次のコード例は、`Get-SSMInventorySchema` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントのインベントリタイプ名のリストを返します。**  

```
Get-SSMInventorySchema
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetInventorySchema](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMLatestEC2Image`
<a name="ssm_Get-SSMLatestEC2Image_powershell_4_topic"></a>

次のコード例は、`Get-SSMLatestEC2Image` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、最新の Windows AMI をすべて一覧表示します。**  

```
PS Get-SSMLatestEC2Image -Path ami-windows-latest
```
**出力:**  

```
Name                                                                    Value
----                                                                    -----
Windows_Server-2008-R2_SP1-English-64Bit-SQL_2012_SP4_Express           ami-0e5ddd288daff4fab
Windows_Server-2012-R2_RTM-Chinese_Simplified-64Bit-Base                ami-0c5ea64e6bec1cb50
Windows_Server-2012-R2_RTM-Chinese_Traditional-64Bit-Base               ami-09775eff0bf8c113d
Windows_Server-2012-R2_RTM-Dutch-64Bit-Base                             ami-025064b67e28cf5df
...
```
**例 2: この例では、us-west-2 リージョンの特定の Amazon Linux イメージの AMI ID を取得します。**  

```
PS Get-SSMLatestEC2Image -Path ami-amazon-linux-latest -ImageName amzn-ami-hvm-x86_64-ebs -Region us-west-2
```
**出力:**  

```
ami-09b92cd132204c704
```
**例 3: この例では、指定されたワイルドカード表現に一致する最新の Windows AMI をすべて一覧表示します。**  

```
Get-SSMLatestEC2Image -Path ami-windows-latest -ImageName *Windows*2019*English*
```
**出力:**  

```
Name                                                     Value
----                                                     -----
Windows_Server-2019-English-Full-SQL_2017_Web            ami-085e9d27da5b73a42
Windows_Server-2019-English-STIG-Core                    ami-0bfd85c29148c7f80
Windows_Server-2019-English-Full-SQL_2019_Web            ami-02099560d7fb11f20
Windows_Server-2019-English-Full-SQL_2016_SP2_Standard   ami-0d7ae2d81c07bd598
...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[Get-SSMLatestEC2Image](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindow`
<a name="ssm_GetMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウの詳細を取得します。**  

```
Get-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d"
```
**出力:**  

```
AllowUnassociatedTargets : False
CreatedDate              : 2/20/2017 6:14:05 PM
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
ModifiedDate             : 2/20/2017 6:14:05 PM
Name                     : TestMaintWin
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowExecution`
<a name="ssm_GetMaintenanceWindowExecution_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウの実行の一部として実行されるタスクに関する情報を一覧表示します。**  

```
Get-SSMMaintenanceWindowExecution -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
TaskIds           : {ac0c6ae1-daa3-4a89-832e-d384503b6586}
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetMaintenanceWindowExecution](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowExecutionList`
<a name="ssm_DescribeMaintenanceWindowExecutions_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウにおけるすべての実行を一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d"
```
**出力:**  

```
EndTime           : 2/20/2017 6:30:17 PM
StartTime         : 2/20/2017 6:30:16 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
WindowExecutionId : 6f3215cf-4101-4fa0-9b7b-9523269599c7
WindowId          : mw-03eb9db42890fb82d
```
**例 2: この例では、指定されたメンテナンスウィンドウにおける指定された日付より前のすべての実行を一覧表示します。**  

```
$option1 = @{Key="ExecutedBefore";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
**例 3: この例では、指定されたメンテナンスウィンドウにおける指定された日付より後のすべての実行を一覧表示します。**  

```
$option1 = @{Key="ExecutedAfter";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMaintenanceWindowExecutions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowExecutionTask`
<a name="ssm_GetMaintenanceWindowExecutionTask_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionTask` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウの実行の一部であったタスクに関する情報を一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionTask -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:35 PM
MaxConcurrency    : 1
MaxErrors         : 1
Priority          : 10
ServiceRole       : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The maximum error count was exceeded.
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskParameters    : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskPara
                    meterValueExpression]}
Type              : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetMaintenanceWindowExecutionTask](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowExecutionTaskInvocationList`
<a name="ssm_DescribeMaintenanceWindowExecutionTaskInvocations_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionTaskInvocationList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウの実行の一部として実行される、タスクの呼び出しを一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionTaskInvocationList -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:34 PM
ExecutionId       :
InvocationId      : e274b6e1-fe56-4e32-bd2a-8073c6381d8b
OwnerInformation  :
Parameters        : {"documentName":"AWS-RunShellScript","instanceIds":["i-0000293ffd8c57862"],"parameters":{"commands":["df"]},"maxConcurrency":"1",
                    "maxErrors":"1"}
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The instance IDs list contains an invalid entry.
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
WindowTargetId    :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMaintenanceWindowExecutionTaskInvocations](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowExecutionTaskList`
<a name="ssm_DescribeMaintenanceWindowExecutionTasks_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionTaskList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウの実行に関連するタスクを一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionTaskList -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : SUCCESS
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskType          : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMaintenanceWindowExecutionTasks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowList`
<a name="ssm_DescribeMaintenanceWindows_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントにおけるすべてのメンテナンスウィンドウを一覧表示します。**  

```
Get-SSMMaintenanceWindowList
```
**出力:**  

```
Cutoff   : 1
Duration : 4
Enabled  : True
Name     : My-First-Maintenance-Window
WindowId : mw-06d59c1a07c022145
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMaintenanceWindows](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowTarget`
<a name="ssm_DescribeMaintenanceWindowTargets_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowTarget` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウのすべてのターゲットを一覧表示します。**  

```
Get-SSMMaintenanceWindowTarget -WindowId "mw-06cf17cbefcb4bf4f"
```
**出力:**  

```
OwnerInformation : Single instance
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : 350d44e6-28cc-44e2-951f-4b2c985838f6

OwnerInformation : Two instances in a list
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : e078a987-2866-47be-bedd-d9cf49177d3a
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMaintenanceWindowTargets](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMMaintenanceWindowTaskList`
<a name="ssm_DescribeMaintenanceWindowTasks_powershell_4_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowTaskList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウのすべてのタスクを一覧表示します。**  

```
Get-SSMMaintenanceWindowTaskList -WindowId "mw-06cf17cbefcb4bf4f"
```
**出力:**  

```
LoggingInfo    :
MaxConcurrency : 1
MaxErrors      : 1
Priority       : 10
ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
Targets        : {InstanceIds}
TaskArn        : AWS-RunShellScript
TaskParameters : {[commands, Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression]}
Type           : RUN_COMMAND
WindowId       : mw-06cf17cbefcb4bf4f
WindowTaskId   : a23e338d-ff30-4398-8aa3-09cd052ebf17
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeMaintenanceWindowTasks](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMParameterHistory`
<a name="ssm_GetParameterHistory_powershell_4_topic"></a>

次のコード例は、`Get-SSMParameterHistory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パラメータの値の履歴を一覧表示します。**  

```
Get-SSMParameterHistory -Name "Welcome"
```
**出力:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:55:25 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
Value            : helloWorld
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetParameterHistory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMParameterList`
<a name="ssm_DescribeParameters_powershell_4_topic"></a>

次のコード例は、`Get-SSMParameterList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべてのパラメータを一覧表示します。**  

```
Get-SSMParameterList
```
**出力:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:58:23 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeParameters](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMParameterValue`
<a name="ssm_GetParameters_powershell_4_topic"></a>

次のコード例は、`Get-SSMParameterValue` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パラメータの値を一覧表示します。**  

```
Get-SSMParameterValue -Name "Welcome"
```
**出力:**  

```
InvalidParameters Parameters
----------------- ----------
{}                {Welcome}
```
**例 2: この例では、値の詳細を一覧表示します。**  

```
(Get-SSMParameterValue -Name "Welcome").Parameters
```
**出力:**  

```
Name    Type   Value
----    ----   -----
Welcome String Good day, Sunshine!
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetParameters](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMPatchBaseline`
<a name="ssm_DescribePatchBaselines_powershell_4_topic"></a>

次のコード例は、`Get-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、すべてのパッチベースラインを一覧表示します。**  

```
Get-SSMPatchBaseline
```
**出力:**  

```
BaselineDescription                                             BaselineId                                                            BaselineName
-------------------                                             ----------                                                            ------------
Default Patch Baseline Provided by AWS.                         arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultP...
Baseline containing all updates approved for production systems pb-045f10b4f382baeda                                                  Production-B...
Baseline containing all updates approved for production systems pb-0a2f1059b670ebd31                                                  Production-B...
```
**例 2: この例では、 が提供するすべてのパッチベースラインを一覧表示します AWS。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="OWNER";Values=@("AWS")}
```
**出力:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**例 3: この例では、所有者しているすべてのパッチベースラインを一覧表示します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="OWNER";Values=@("Self")}
```
**出力:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**例 4: PowerShell バージョン 2 では、New-Object を使用して各タグを作成する必要があります。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "OWNER"
$filter1.Values = "AWS"

Get-SSMPatchBaseline -Filter $filter1
```
**出力:**  

```
BaselineDescription                     BaselineId                                                            BaselineName             DefaultBaselin
                                                                                                                                       e
-------------------                     ----------                                                            ------------             --------------
Default Patch Baseline Provided by AWS. arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultPatchBaseline True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribePatchBaselines](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMPatchBaselineDetail`
<a name="ssm_GetPatchBaseline_powershell_4_topic"></a>

次のコード例は、`Get-SSMPatchBaselineDetail` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチベースラインの詳細を表示します。**  

```
Get-SSMPatchBaselineDetail -BaselineId "pb-03da896ca3b68b639"
```
**出力:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:02:19 PM
Name            : Production-Baseline
PatchGroups     : {}
RejectedPatches : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMPatchBaselineForPatchGroup`
<a name="ssm_GetPatchBaselineForPatchGroup_powershell_4_topic"></a>

次のコード例は、`Get-SSMPatchBaselineForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチグループのパッチベースラインを表示します。**  

```
Get-SSMPatchBaselineForPatchGroup -PatchGroup "Production"
```
**出力:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[GetPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMPatchGroup`
<a name="ssm_DescribePatchGroups_powershell_4_topic"></a>

次のコード例は、`Get-SSMPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチグループの登録を一覧表示します。**  

```
Get-SSMPatchGroup
```
**出力:**  

```
BaselineIdentity                                           PatchGroup
----------------                                           ----------
Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribePatchGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMPatchGroupState`
<a name="ssm_DescribePatchGroupState_powershell_4_topic"></a>

次のコード例は、`Get-SSMPatchGroupState` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチグループのパッチコンプライアンスの概要を取得します。**  

```
Get-SSMPatchGroupState -PatchGroup "Production"
```
**出力:**  

```
Instances                          : 4
InstancesWithFailedPatches         : 1
InstancesWithInstalledOtherPatches : 4
InstancesWithInstalledPatches      : 3
InstancesWithMissingPatches        : 0
InstancesWithNotApplicablePatches  : 0
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribePatchGroupState](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMResourceComplianceSummaryList`
<a name="ssm_ListResourceComplianceSummaries_powershell_4_topic"></a>

次のコード例は、`Get-SSMResourceComplianceSummaryList` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リソースレベルの概要数を取得します。概要には、「Windows10」に一致する製品の準拠ステータスと非準拠ステータス、および詳細なコンプライアンス項目の重要度数に関する情報が含まれます。MaxResult のデフォルトは、パラメータが指定されていない場合は 100 であり、この値は有効ではないため、MaxResult パラメータが追加され、値は 50 に設定されます。**  

```
$FilterValues = @{
		"Key"="Product"
        "Type"="EQUAL"
        "Values"="Windows10"
}
        Get-SSMResourceComplianceSummaryList -Filter $FilterValues -MaxResult 50
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListResourceComplianceSummaries](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-SSMResourceTag`
<a name="ssm_ListTagsForResource_powershell_4_topic"></a>

次のコード例は、`Get-SSMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウのタグを一覧表示します。**  

```
Get-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow"
```
**出力:**  

```
Key   Value
---   -----
Stack Production
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-SSMActivation`
<a name="ssm_CreateActivation_powershell_4_topic"></a>

次のコード例は、`New-SSMActivation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、マネージドインスタンスを作成します。**  

```
New-SSMActivation -DefaultInstanceName "MyWebServers" -IamRole "SSMAutomationRole" -RegistrationLimit 10
```
**出力:**  

```
ActivationCode       ActivationId
--------------       ------------
KWChhOxBTiwDcKE9BlKC 08e51e79-1e36-446c-8e63-9458569c1363
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateActivation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-SSMAssociation`
<a name="ssm_CreateAssociation_powershell_4_topic"></a>

次のコード例は、`New-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンス ID を使用して、設定ドキュメントをインスタンスに関連付けます。**  

```
New-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Associated
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : Associated with AWS-UpdateSSMAgent
Status.AdditionalInfo :
```
**例 2: この例では、ターゲットを使用して、設定ドキュメントをインスタンスに関連付けます。**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
New-SSMAssociation -Name "AWS-UpdateSSMAgent" -Target $target
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**例 3: この例では、ターゲットとパラメータを使用して、設定ドキュメントをインスタンスに関連付けます。**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
$params = @{
  "action"="configure"
  "mode"="ec2"
  "optionalConfigurationSource"="ssm"
  "optionalConfigurationLocation"=""
  "optionalRestart"="yes"
}
New-SSMAssociation -Name "Configure-CloudWatch" -AssociationName "CWConfiguration" -Target $target -Parameter $params
```
**出力:**  

```
Name                  : Configure-CloudWatch
InstanceId            :
Date                  : 5/17/2018 3:17:44 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**例 4: この例では、`AWS-GatherSoftwareInventory` を使用して、リージョン内におけるすべてのインスタンスとの関連付けを作成します。また、収集するパラメータにカスタムファイルとレジストリの場所を指定します。**  

```
$params = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$params["windowsRegistry"] ='[{"Path":"HKEY_LOCAL_MACHINE\SOFTWARE\Amazon\MachineImage","Recursive":false,"ValueNames":["AMIName"]}]'
$params["files"] = '[{"Path":"C:\Program Files","Pattern":["*.exe"],"Recursive":true}, {"Path":"C:\ProgramData","Pattern":["*.log"],"Recursive":true}]' 
New-SSMAssociation -AssociationName new-in-mum -Name AWS-GatherSoftwareInventory -Target @{Key="instanceids";Values="*"} -Parameter $params -region ap-south-1 -ScheduleExpression "rate(720 minutes)"
```
**出力:**  

```
Name                  : AWS-GatherSoftwareInventory
InstanceId            :
Date                  : 6/9/2019 8:57:56 AM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAssociation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-SSMAssociationFromBatch`
<a name="ssm_CreateAssociationBatch_powershell_4_topic"></a>

次のコード例は、`New-SSMAssociationFromBatch` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、設定ドキュメントを複数のインスタンスに関連付けます。出力では、成功したオペレーションと失敗したオペレーションのリストが返されます (該当する場合)。**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
New-SSMAssociationFromBatch -Entry $option1,$option2
```
**出力:**  

```
Failed  Successful
------  ----------
{}      {Amazon.SimpleSystemsManagement.Model.FailedCreateAssociation, Amazon.SimpleSystemsManagement.Model.FailedCreateAsso...
```
**例 2: この例では、成功したオペレーションの詳細を表示します。**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
(New-SSMAssociationFromBatch -Entry $option1,$option2).Successful
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateAssociationBatch](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-SSMDocument`
<a name="ssm_CreateDocument_powershell_4_topic"></a>

次のコード例は、`New-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アカウントにドキュメントを作成します。ドキュメントは JSON 形式である必要があります。設定ドキュメントの記述については、「SSM API Reference」の「Configuration Document」を参照してください。**  

```
New-SSMDocument -Content (Get-Content -Raw "c:\temp\RunShellScript.json") -Name "RunShellScript" -DocumentType "Command"
```
**出力:**  

```
CreatedDate     : 3/1/2017 1:21:33 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Creating
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateDocument](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-SSMMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`New-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、そのウィンドウは、毎週火曜日の午後 4 時に 4 時間実行され (カットオフは 1 時間)、関連付けられていないターゲットを許可する、指定された名前の新しいメンテナンスウィンドウを作成します。**  

```
New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 -AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)"
```
**出力:**  

```
mw-03eb53e1ea7383998
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-SSMPatchBaseline`
<a name="ssm_CreatePatchBaseline_powershell_4_topic"></a>

次のコード例は、`New-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、本番環境で Windows Server 2019 を実行しているマネージドインスタンスに対して、Microsoft からリリースされてから 7 日後にパッチを承認するパッチベースラインを作成します。**  

```
$rule = New-Object Amazon.SimpleSystemsManagement.Model.PatchRule
$rule.ApproveAfterDays = 7

$ruleFilters = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilterGroup

$patchFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$patchFilter.Key="PRODUCT"
$patchFilter.Values="WindowsServer2019"

$severityFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$severityFilter.Key="MSRC_SEVERITY"
$severityFilter.Values.Add("Critical")
$severityFilter.Values.Add("Important")
$severityFilter.Values.Add("Moderate")

$classificationFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$classificationFilter.Key = "CLASSIFICATION"
$classificationFilter.Values.Add( "SecurityUpdates" )
$classificationFilter.Values.Add( "Updates" )
$classificationFilter.Values.Add( "UpdateRollups" )
$classificationFilter.Values.Add( "CriticalUpdates" )

$ruleFilters.PatchFilters.Add($severityFilter)
$ruleFilters.PatchFilters.Add($classificationFilter)
$ruleFilters.PatchFilters.Add($patchFilter)
$rule.PatchFilterGroup = $ruleFilters

New-SSMPatchBaseline -Name "Production-Baseline-Windows2019" -Description "Baseline containing all updates approved for production systems" -ApprovalRules_PatchRule $rule
```
**出力:**  

```
pb-0z4z6221c4296b23z
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreatePatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-SSMDefaultPatchBaseline`
<a name="ssm_RegisterDefaultPatchBaseline_powershell_4_topic"></a>

次のコード例は、`Register-SSMDefaultPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチベースラインをデフォルトのパッチベースラインとして登録します。**  

```
Register-SSMDefaultPatchBaseline -BaselineId "pb-03da896ca3b68b639"
```
**出力:**  

```
pb-03da896ca3b68b639
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-SSMPatchBaselineForPatchGroup`
<a name="ssm_RegisterPatchBaselineForPatchGroup_powershell_4_topic"></a>

次のコード例は、`Register-SSMPatchBaselineForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチグループのパッチベースラインを登録します。**  

```
Register-SSMPatchBaselineForPatchGroup -BaselineId "pb-03da896ca3b68b639" -PatchGroup "Production"
```
**出力:**  

```
BaselineId           PatchGroup
----------           ----------
pb-03da896ca3b68b639 Production
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-SSMTargetWithMaintenanceWindow`
<a name="ssm_RegisterTargetWithMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`Register-SSMTargetWithMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスをメンテナンスウィンドウに登録します。**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**出力:**  

```
d8e47760-23ed-46a5-9f28-927337725398
```
**例 2: この例では、複数のインスタンスをメンテナンスウィンドウに登録します。**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862","i-0cb2b964d3e14fd9f")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**出力:**  

```
6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
**例 3: この例では、EC2 タグを使用して、インスタンスをメンテナンスウィンドウに登録します。**  

```
$option1 = @{Key="tag:Environment";Values=@("Production")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Production Web Servers" -ResourceType "INSTANCE"
```
**出力:**  

```
2994977e-aefb-4a71-beac-df620352f184
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterTargetWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-SSMTaskWithMaintenanceWindow`
<a name="ssm_RegisterTaskWithMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`Register-SSMTaskWithMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンス ID を使用して、タスクをメンテナンスウィンドウに登録します。出力はタスク ID です。**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

Register-SSMTaskWithMaintenanceWindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="InstanceIds";Values="i-0000293ffd8c57862" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**出力:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**例 2: この例では、ターゲット ID を使用して、タスクをメンテナンスウィンドウに登録します。出力はタスク ID です。**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

register-ssmtaskwithmaintenancewindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="WindowTargetIds";Values="350d44e6-28cc-44e2-951f-4b2c985838f6" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**出力:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**例 3: この例では、run コマンドドキュメント `AWS-RunPowerShellScript` のパラメータオブジェクトを作成し、ターゲット ID を使用して任意のメンテナンスウィンドウを持つタスクを作成します。返される出力はタスク ID です。**  

```
$parameters = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$parameters.Add("commands",@("ipconfig","dir env:\computername"))
$parameters.Add("executionTimeout",@(3600))

$props = @{
    WindowId = "mw-0123e4cce56ff78ae"
    ServiceRoleArn = "arn:aws:iam::123456789012:role/MaintenanceWindowsRole"
    MaxConcurrency = 1
    MaxError = 1
    TaskType = "RUN_COMMAND"
    TaskArn = "AWS-RunPowerShellScript"
    Target = @{Key="WindowTargetIds";Values="fe1234ea-56d7-890b-12f3-456b789bee0f"}
    Priority = 1
    RunCommand_Parameter = $parameters
    Name = "set-via-cmdlet"
}

Register-SSMTaskWithMaintenanceWindow @props
```
**出力:**  

```
f1e2ef34-5678-12e3-456a-12334c5c6cbe
```
**例 4: この例では、 という名前のドキュメントを使用して AWS Systems Manager Automation タスクを登録します`Create-Snapshots`。**  

```
$automationParameters = @{}
$automationParameters.Add( "instanceId", @("{{ TARGET_ID }}") )
$automationParameters.Add( "AutomationAssumeRole", @("{arn:aws:iam::111111111111:role/AutomationRole}") )
$automationParameters.Add( "SnapshotTimeout", @("PT20M") )
Register-SSMTaskWithMaintenanceWindow -WindowId mw-123EXAMPLE456`
    -ServiceRoleArn "arn:aws:iam::123456789012:role/MW-Role"`
    -MaxConcurrency 1 -MaxError 1 -TaskArn "CreateVolumeSnapshots"`
    -Target @{ Key="WindowTargetIds";Values="4b5acdf4-946c-4355-bd68-4329a43a5fd1" }`
    -TaskType "AUTOMATION"`
    -Priority 4`
    -Automation_DocumentVersion '$DEFAULT' -Automation_Parameter $automationParameters -Name "Create-Snapshots"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterTaskWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SSMActivation`
<a name="ssm_DeleteActivation_powershell_4_topic"></a>

次のコード例は、`Remove-SSMActivation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、アクティベーションを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMActivation -ActivationId "08e51e79-1e36-446c-8e63-9458569c1363"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteActivation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SSMAssociation`
<a name="ssm_DeleteAssociation_powershell_4_topic"></a>

次のコード例は、`Remove-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスとドキュメント間の関連付けを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteAssociation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SSMDocument`
<a name="ssm_DeleteDocument_powershell_4_topic"></a>

次のコード例は、`Remove-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ドキュメントを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMDocument -Name "RunShellScript"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteDocument](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SSMMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`Remove-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウを削除します。**  

```
Remove-SSMMaintenanceWindow -WindowId "mw-06d59c1a07c022145"
```
**出力:**  

```
mw-06d59c1a07c022145
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SSMParameter`
<a name="ssm_DeleteParameter_powershell_4_topic"></a>

次のコード例は、`Remove-SSMParameter` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例ではパラメータを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMParameter -Name "helloWorld"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteParameter](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SSMPatchBaseline`
<a name="ssm_DeletePatchBaseline_powershell_4_topic"></a>

次のコード例は、`Remove-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチベースラインを削除します。**  

```
Remove-SSMPatchBaseline -BaselineId "pb-045f10b4f382baeda"
```
**出力:**  

```
pb-045f10b4f382baeda
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeletePatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-SSMResourceTag`
<a name="ssm_RemoveTagsFromResource_powershell_4_topic"></a>

次のコード例は、`Remove-SSMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウからタグを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -TagKey "Production"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Send-SSMCommand`
<a name="ssm_SendCommand_powershell_4_topic"></a>

次のコード例は、`Send-SSMCommand` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ターゲットインスタンスで echo コマンドを実行します。**  

```
Send-SSMCommand -DocumentName "AWS-RunPowerShellScript" -Parameter @{commands = "echo helloWorld"} -Target @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
```
**出力:**  

```
CommandId          : d8d190fc-32c1-4d65-a0df-ff5ff3965524
Comment            : 
CompletedCount     : 0
DocumentName       : AWS-RunPowerShellScript
ErrorCount         : 0
ExpiresAfter       : 3/7/2017 10:48:37 PM
InstanceIds        : {}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName : 
OutputS3KeyPrefix  : 
OutputS3Region     : 
Parameters         : {[commands, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 3/7/2017 9:48:37 PM
ServiceRole        : 
Status             : Pending
StatusDetails      : Pending
TargetCount        : 0
Targets            : {instanceids}
```
**例 2: この例は、ネストされたパラメータを受け入れるコマンドを実行する方法を示しています。**  

```
Send-SSMCommand -DocumentName "AWS-RunRemoteScript" -Parameter @{ sourceType="GitHub";sourceInfo='{"owner": "me","repository": "amazon-ssm","path": "Examples/Install-Win32OpenSSH"}'; "commandLine"=".\Install-Win32OpenSSH.ps1"} -InstanceId i-0cb2b964d3e14fd9f
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[SendCommand](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-SSMAutomationExecution`
<a name="ssm_StartAutomationExecution_powershell_4_topic"></a>

次のコード例は、`Start-SSMAutomationExecution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、オートメーションロール、AMI ソース ID、および Amazon EC2 インスタンスロールを指定するドキュメントを実行します。**  

```
Start-SSMAutomationExecution -DocumentName AWS-UpdateLinuxAmi -Parameter @{'AutomationAssumeRole'='arn:aws:iam::123456789012:role/SSMAutomationRole';'SourceAmiId'='ami-f173cc91';'InstanceIamRole'='EC2InstanceRole'}
```
**出力:**  

```
3a532a4f-0382-11e7-9df7-6f11185f6dd1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartAutomationExecution](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Start-SSMSession`
<a name="ssm_StartSession_powershell_4_topic"></a>

次のコード例は、`Start-SSMSession` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、Session Manager のセッションのターゲットへの接続を開始し、ポート転送を有効にします。**  

```
Start-SSMSession -Target 'i-064578e5e7454488f' -DocumentName 'AWS-StartPortForwardingSession' -Parameter @{ localPortNumber = '8080'; portNumber = '80' }
```
**出力:**  

```
SessionId    StreamUrl
----------    ----------
random-id0    wss://ssmmessages.amazonaws.com/v1/data-channel/random-id
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StartSession](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-SSMAutomationExecution`
<a name="ssm_StopAutomationExecution_powershell_4_topic"></a>

次のコード例は、`Stop-SSMAutomationExecution` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、オートメーションの実行を停止します。コマンドが成功した場合、出力はありません。**  

```
Stop-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StopAutomationExecution](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-SSMCommand`
<a name="ssm_CancelCommand_powershell_4_topic"></a>

次のコード例は、`Stop-SSMCommand` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、コマンドのキャンセルを試みます。オペレーションが成功した場合、出力はありません。**  

```
Stop-SSMCommand -CommandId "9ded293e-e792-4440-8e3e-7b8ec5feaa38"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CancelCommand](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-SSMManagedInstance`
<a name="ssm_DeregisterManagedInstance_powershell_4_topic"></a>

次のコード例は、`Unregister-SSMManagedInstance` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、マネージドインスタンスを登録解除します。コマンドが成功した場合、出力はありません。**  

```
Unregister-SSMManagedInstance -InstanceId "mi-08ab247cdf1046573"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterManagedInstance](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-SSMPatchBaselineForPatchGroup`
<a name="ssm_DeregisterPatchBaselineForPatchGroup_powershell_4_topic"></a>

次のコード例は、`Unregister-SSMPatchBaselineForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、パッチグループをパッチベースラインから登録解除します。**  

```
Unregister-SSMPatchBaselineForPatchGroup -BaselineId "pb-045f10b4f382baeda" -PatchGroup "Production"
```
**出力:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-SSMTargetFromMaintenanceWindow`
<a name="ssm_DeregisterTargetFromMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`Unregister-SSMTargetFromMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウからターゲットを削除します。**  

```
Unregister-SSMTargetFromMaintenanceWindow -WindowTargetId "6ab5c208-9fc4-4697-84b7-b02a6cc25f7d" -WindowId "mw-06cf17cbefcb4bf4f"
```
**出力:**  

```
WindowId             WindowTargetId
--------             --------------
mw-06cf17cbefcb4bf4f 6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-SSMTaskFromMaintenanceWindow`
<a name="ssm_DeregisterTaskFromMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`Unregister-SSMTaskFromMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウからタスクを削除します。**  

```
Unregister-SSMTaskFromMaintenanceWindow -WindowTaskId "f34a2c47-ddfd-4c85-a88d-72366b69af1b" -WindowId "mw-03a342e62c96d31b0"
```
**出力:**  

```
WindowId             WindowTaskId
--------             ------------
mw-03a342e62c96d31b0 f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeregisterTaskFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-SSMAssociation`
<a name="ssm_UpdateAssociation_powershell_4_topic"></a>

次のコード例は、`Update-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、新しいドキュメントバージョンとの関連付けを更新します。**  

```
Update-SSMAssociation -AssociationId "93285663-92df-44cb-9f26-2292d4ecc439" -DocumentVersion "1"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateAssociation](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-SSMAssociationStatus`
<a name="ssm_UpdateAssociationStatus_powershell_4_topic"></a>

次のコード例は、`Update-SSMAssociationStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、インスタンスと設定ドキュメント間の関連付けのステータスを更新します。**  

```
Update-SSMAssociationStatus -Name "AWS-UpdateSSMAgent" -InstanceId "i-0000293ffd8c57862" -AssociationStatus_Date "2015-02-20T08:31:11Z" -AssociationStatus_Name "Pending" -AssociationStatus_Message "temporary_status_change" -AssociationStatus_AdditionalInfo "Additional-Config-Needed"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temporary_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateAssociationStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-SSMDocument`
<a name="ssm_UpdateDocument_powershell_4_topic"></a>

次のコード例は、`Update-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: これは、指定した JSON ファイルの更新内容を含むドキュメントの新しいバージョンを作成するためのものです。ドキュメントは JSON 形式である必要があります。ドキュメントバージョンは、「Get-SSMDocumentVersionList」コマンドレットで取得できます。**  

```
Update-SSMDocument -Name RunShellScript -DocumentVersion "1" -Content (Get-Content -Raw "c:\temp\RunShellScript.json")
```
**出力:**  

```
CreatedDate     : 3/1/2017 2:59:17 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 2
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 2
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Updating
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateDocument](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-SSMDocumentDefaultVersion`
<a name="ssm_UpdateDocumentDefaultVersion_powershell_4_topic"></a>

次のコード例は、`Update-SSMDocumentDefaultVersion` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: ここではドキュメントのデフォルトバージョンを更新します。利用可能なドキュメントバージョンは、「Get-SSMDocumentVersionList」コマンドレットで取得できます。**  

```
Update-SSMDocumentDefaultVersion -Name "RunShellScript" -DocumentVersion "2"
```
**出力:**  

```
DefaultVersion Name
-------------- ----
2              RunShellScript
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateDocumentDefaultVersion](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-SSMMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_powershell_4_topic"></a>

次のコード例は、`Update-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、メンテナンスウィンドウの名前を更新します。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Name "My-Renamed-MW"
```
**出力:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**例 2: この例では、メンテナンスウィンドウを有効にします。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $true
```
**出力:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**例 3: この例では、メンテナンスウィンドウを無効にします。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $false
```
**出力:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : False
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-SSMManagedInstanceRole`
<a name="ssm_UpdateManagedInstanceRole_powershell_4_topic"></a>

次のコード例は、`Update-SSMManagedInstanceRole` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、マネージドインスタンスのロールを更新します。コマンドが成功した場合、出力はありません。**  

```
Update-SSMManagedInstanceRole -InstanceId "mi-08ab247cdf1046573" -IamRole "AutomationRole"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdateManagedInstanceRole](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Update-SSMPatchBaseline`
<a name="ssm_UpdatePatchBaseline_powershell_4_topic"></a>

次のコード例は、`Update-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、2 つのパッチを拒否済み、1 つのパッチを承認済みとして既存のパッチベースラインに追加します。**  

```
Update-SSMPatchBaseline -BaselineId "pb-03da896ca3b68b639" -RejectedPatch "KB2032276","MS10-048" -ApprovedPatch "KB2124261"
```
**出力:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {KB2124261}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:22:10 PM
Name            : Production-Baseline
RejectedPatches : {KB2032276, MS10-048}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[UpdatePatchBaseline](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-SSMComplianceItem`
<a name="ssm_PutComplianceItems_powershell_4_topic"></a>

次のコード例は、`Write-SSMComplianceItem` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、任意のマネージドインスタンスのカスタムコンプライアンス項目を書き込みます。**  

```
$item = [Amazon.SimpleSystemsManagement.Model.ComplianceItemEntry]::new()
$item.Id = "07Jun2019-3"
$item.Severity="LOW"
$item.Status="COMPLIANT"
$item.Title="Fin-test-1 - custom"
Write-SSMComplianceItem -ResourceId mi-012dcb3ecea45b678 -ComplianceType Custom:VSSCompliant2 -ResourceType ManagedInstance -Item $item -ExecutionSummary_ExecutionTime "07-Jun-2019"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutComplianceItems](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-SSMInventory`
<a name="ssm_PutInventory_powershell_4_topic"></a>

次のコード例は、`Write-SSMInventory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、ラックの場所情報をインスタンスに割り当てます。コマンドが成功した場合、出力はありません。**  

```
$data = New-Object "System.Collections.Generic.Dictionary[System.String,System.String]"
$data.Add("RackLocation", "Bay B/Row C/Rack D/Shelf F")

$items = New-Object "System.Collections.Generic.List[System.Collections.Generic.Dictionary[System.String, System.String]]"
$items.Add($data)

$customInventoryItem = New-Object Amazon.SimpleSystemsManagement.Model.InventoryItem
$customInventoryItem.CaptureTime = "2016-08-22T10:01:01Z"
$customInventoryItem.Content = $items
$customInventoryItem.TypeName = "Custom:TestRackInfo2"
$customInventoryItem.SchemaVersion = "1.0"

$inventoryItems = @($customInventoryItem)

Write-SSMInventory -InstanceId "i-0cb2b964d3e14fd9f" -Item $inventoryItems
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[PutInventory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Write-SSMParameter`
<a name="ssm_PutParameter_powershell_4_topic"></a>

次のコード例は、`Write-SSMParameter` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例ではパラメータを作成します。コマンドが成功した場合、出力はありません。**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "helloWorld"
```
**例 2: この例ではパラメータを変更します。コマンドが成功した場合、出力はありません。**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "Good day, Sunshine!" -Overwrite $true
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V4) の「[PutParameter](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。**

# Tools for PowerShell V4 を使用した Amazon Translate の例
<a name="powershell_4_translate_code_examples"></a>

次のコード例は、Amazon Translate で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ConvertTo-TRNTargetLanguage`
<a name="translate_TranslateText_powershell_4_topic"></a>

次のコード例は、`ConvertTo-TRNTargetLanguage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された英語テキストをフランス語に変換します。変換するテキストは、-Text パラメータとして渡すこともできます。**  

```
"Hello World" | ConvertTo-TRNTargetLanguage -SourceLanguageCode en -TargetLanguageCode fr
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TranslateText](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# AWS WAFV2 Tools for PowerShell V4 を使用した の例
<a name="powershell_4_wafv2_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS WAFV2。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-WAF2WebACL`
<a name="wafv2_CreateWebAcl_powershell_4_topic"></a>

次のコード例は、`New-WAF2WebACL` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このコマンドは、「waf-test」という名前の新しいウェブ ACL を作成します。サービス API ドキュメントによると、「DefaultAction」は必須プロパティです。したがって、「-DefaultAction\$1Allow」または「-DefaultAction\$1Block」の値を指定する必要があります。「-DefaultAction\$1Allow」と「-DefaultAction\$1Block」は必須プロパティではないため、上記の例に示すように、値「@\$1\$1」をプレースホルダーとして使用できます。**  

```
New-WAF2WebACL -Name "waf-test" -Scope REGIONAL -Region eu-west-1 -VisibilityConfig_CloudWatchMetricsEnabled $true -VisibilityConfig_SampledRequestsEnabled $true -VisibilityConfig_MetricName "waf-test" -Description "Test" -DefaultAction_Allow @{}
```
**出力:**  

```
ARN         : arn:aws:wafv2:eu-west-1:139480602983:regional/webacl/waf-test/19460b3f-db14-4b9a-8e23-a417e1eb007f
Description : Test
Id          : 19460b3f-db14-4b9a-8e23-a417e1eb007f
LockToken   : 5a0cd5eb-d911-4341-b313-b429e6d6b6ab
Name        : waf-test
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateWebAcl](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V4 を使用した WorkSpaces の例
<a name="powershell_4_workspaces_code_examples"></a>

次のコード例は、WorkSpaces で AWS Tools for PowerShell V4 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Approve-WKSIpRule`
<a name="workspaces_AuthorizeIpRules_powershell_4_topic"></a>

次のコード例は、`Approve-WKSIpRule` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、既存の IP グループにルールを追加します。**  

```
$Rule = @(
@{IPRule = "10.1.0.0/0"; RuleDesc = "First Rule Added"},
@{IPRule = "10.2.0.0/0"; RuleDesc = "Second Rule Added"}
)

Approve-WKSIpRule -GroupId wsipg-abcnx2fcw -UserRule $Rule
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AuthorizeIpRules](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Copy-WKSWorkspaceImage`
<a name="workspaces_CopyWorkspaceImage_powershell_4_topic"></a>

次のコード例は、`Copy-WKSWorkspaceImage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 ID を持つワークスペースイメージを、us-west-2 から「CopiedImageTest」という名前の現在のリージョンにコピーします。**  

```
Copy-WKSWorkspaceImage -Name CopiedImageTest -SourceRegion us-west-2 -SourceImageId wsi-djfoedhw6
```
**出力:**  

```
wsi-456abaqfe
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CopyWorkspaceImage](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-WKSClientProperty`
<a name="workspaces_ModifyClientProperties_powershell_4_topic"></a>

次のコード例は、`Edit-WKSClientProperty` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、WorkSpaces クライアントの再接続を有効にします**  

```
Edit-WKSClientProperty -Region us-west-2 -ClientProperties_ReconnectEnabled "ENABLED" -ResourceId d-123414a369
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyClientProperties](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-WKSSelfServicePermission`
<a name="workspaces_ModifySelfservicePermissions_powershell_4_topic"></a>

次のコード例は、`Edit-WKSSelfServicePermission` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、セルフサービスのアクセス許可を有効にして、指定ディレクトリのコンピューティングタイプを変更し、ボリュームサイズを増やせるようにします。**  

```
Edit-WKSSelfservicePermission -Region us-west-2 -ResourceId d-123454a369 -SelfservicePermissions_ChangeComputeType ENABLED -SelfservicePermissions_IncreaseVolumeSize ENABLED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifySelfservicePermissions](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-WKSWorkspaceAccessProperty`
<a name="workspaces_ModifyWorkspaceAccessProperties_powershell_4_topic"></a>

次のコード例は、`Edit-WKSWorkspaceAccessProperty` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ディレクトリの Android と Chrome OS で Workspace アクセスを有効にします。**  

```
Edit-WKSWorkspaceAccessProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceAccessProperties_DeviceTypeAndroid ALLOW -WorkspaceAccessProperties_DeviceTypeChromeOs ALLOW
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyWorkspaceAccessProperties](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-WKSWorkspaceCreationProperty`
<a name="workspaces_ModifyWorkspaceCreationProperties_powershell_4_topic"></a>

次のコード例は、`Edit-WKSWorkspaceCreationProperty` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルでは、Workspace の作成中にインターネットアクセスとメンテナンスモードをデフォルト値として true に設定します。**  

```
Edit-WKSWorkspaceCreationProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceCreationProperties_EnableInternetAccess $true -WorkspaceCreationProperties_EnableMaintenanceMode $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyWorkspaceCreationProperties](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-WKSWorkspaceProperty`
<a name="workspaces_ModifyWorkspaceProperties_powershell_4_topic"></a>

次のコード例は、`Edit-WKSWorkspaceProperty` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定された Workspace の Workspace 実行モードプロパティを Auto Stop に変更します。**  

```
Edit-WKSWorkspaceProperty -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceProperties_RunningMode AUTO_STOP
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyWorkspaceProperties](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Edit-WKSWorkspaceState`
<a name="workspaces_ModifyWorkspaceState_powershell_4_topic"></a>

次のコード例は、`Edit-WKSWorkspaceState` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定された Workspace の状態を Available に変更します。**  

```
Edit-WKSWorkspaceState -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceState AVAILABLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[ModifyWorkspaceState](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSClientProperty`
<a name="workspaces_DescribeClientProperties_powershell_4_topic"></a>

次のコード例は、`Get-WKSClientProperty` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ディレクトリのワークスペースクライアントのクライアントプロパティを取得します。**  

```
Get-WKSClientProperty -ResourceId d-223562a123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeClientProperties](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSIpGroup`
<a name="workspaces_DescribeIpGroups_powershell_4_topic"></a>

次のコード例は、`Get-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定リージョン内の指定 IP グループの詳細を取得します。**  

```
Get-WKSIpGroup -Region us-east-1 -GroupId wsipg-8m1234v45
```
**出力:**  

```
GroupDesc GroupId         GroupName UserRules
--------- -------         --------- ---------
          wsipg-8m1234v45 TestGroup {Amazon.WorkSpaces.Model.IpRuleItem, Amazon.WorkSpaces.Model.IpRuleItem}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeIpGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSTag`
<a name="workspaces_DescribeTags_powershell_4_topic"></a>

次のコード例は、`Get-WKSTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定された Workspace のタグを取得します。**  

```
Get-WKSTag -WorkspaceId ws-w361s234r -Region us-west-2
```
**出力:**  

```
Key         Value
---         -----
auto-delete no
purpose     Workbench
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSWorkspace`
<a name="workspaces_DescribeWorkspaces_powershell_4_topic"></a>

次のコード例は、`Get-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: すべての WorkSpaces の詳細をパイプラインに取得します。**  

```
Get-WKSWorkspace
```
**出力:**  

```
BundleId                    : wsb-1a2b3c4d
ComputerName                :
DirectoryId                 : d-1a2b3c4d
ErrorCode                   :
ErrorMessage                :
IpAddress                   :
RootVolumeEncryptionEnabled : False
State                       : PENDING
SubnetId                    :
UserName                    : myuser
UserVolumeEncryptionEnabled : False
VolumeEncryptionKey         :
WorkspaceId                 : ws-1a2b3c4d
WorkspaceProperties         : Amazon.WorkSpaces.Model.WorkspaceProperties
```
**例 2: このコマンドは、`us-west-2` リージョンのワークスペースの `WorkSpaceProperties` の子プロパティの値を表示します。`WorkSpaceProperties` の子プロパティの詳細については、https://docs.aws.amazon.com/workspaces/latest/api/API\$1WorkspaceProperties.html を参照してください。**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties
```
**出力:**  

```
        ComputeTypeName                     : STANDARD
        RootVolumeSizeGib                   : 80
        RunningMode                         : AUTO_STOP
        RunningModeAutoStopTimeoutInMinutes : 60
        UserVolumeSizeGib                   : 50
```
**例 3: このコマンドは、`us-west-2` リージョン内のワークスペースにおける `WorkSpaceProperties` の子プロパティ `RootVolumeSizeGib` の値を表示します。GiB 単位のルートボリュームサイズは 80 です。**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties.RootVolumeSizeGib
```
**出力:**  

```
        80
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSWorkspaceBundle`
<a name="workspaces_DescribeWorkspaceBundles_powershell_4_topic"></a>

次のコード例は、`Get-WKSWorkspaceBundle` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、現在のリージョンのすべての Workspace バンドルの詳細を取得します。**  

```
Get-WKSWorkspaceBundle
```
**出力:**  

```
BundleId        : wsb-sfhdgv342
ComputeType     : Amazon.WorkSpaces.Model.ComputeType
Description     : This bundle is custom
ImageId         : wsi-235aeqges
LastUpdatedTime : 12/26/2019 06:44:07
Name            : CustomBundleTest
Owner           : 233816212345
RootStorage     : Amazon.WorkSpaces.Model.RootStorage
UserStorage     : Amazon.WorkSpaces.Model.UserStorage
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeWorkspaceBundles](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSWorkspaceDirectory`
<a name="workspaces_DescribeWorkspaceDirectories_powershell_4_topic"></a>

次のコード例は、`Get-WKSWorkspaceDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、登録されたディレクトリの詳細を一覧表示します。**  

```
Get-WKSWorkspaceDirectory
```
**出力:**  

```
Alias                       : TestWorkspace
CustomerUserName            : Administrator
DirectoryId                 : d-123414a369
DirectoryName               : TestDirectory.com
DirectoryType               : MicrosoftAD
DnsIpAddresses              : {172.31.43.45, 172.31.2.97}
IamRoleId                   : arn:aws:iam::761234567801:role/workspaces_RoleDefault
IpGroupIds                  : {}
RegistrationCode            : WSpdx+4RRT43
SelfservicePermissions      : Amazon.WorkSpaces.Model.SelfservicePermissions
State                       : REGISTERED
SubnetIds                   : {subnet-1m3m7b43, subnet-ard11aba}
Tenancy                     : SHARED
WorkspaceAccessProperties   : Amazon.WorkSpaces.Model.WorkspaceAccessProperties
WorkspaceCreationProperties : Amazon.WorkSpaces.Model.DefaultWorkspaceCreationProperties
WorkspaceSecurityGroupId    : sg-0ed2441234a123c43
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeWorkspaceDirectories](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSWorkspaceImage`
<a name="workspaces_DescribeWorkspaceImages_powershell_4_topic"></a>

次のコード例は、`Get-WKSWorkspaceImage` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、リージョン内のすべてのイメージの詳細をすべて取得します。**  

```
Get-WKSWorkspaceImage
```
**出力:**  

```
Description     :This image is copied from another image
ErrorCode       :
ErrorMessage    :
ImageId         : wsi-345ahdjgo
Name            : CopiedImageTest
OperatingSystem : Amazon.WorkSpaces.Model.OperatingSystem
RequiredTenancy : DEFAULT
State           : AVAILABLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeWorkspaceImages](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSWorkspaceSnapshot`
<a name="workspaces_DescribeWorkspaceSnapshots_powershell_4_topic"></a>

次のコード例は、`Get-WKSWorkspaceSnapshot` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定ワークスペース用に作成された最新のスナップショットのタイムスタンプを示します。**  

```
Get-WKSWorkspaceSnapshot -WorkspaceId ws-w361s100v
```
**出力:**  

```
RebuildSnapshots                   RestoreSnapshots
----------------                   ----------------
{Amazon.WorkSpaces.Model.Snapshot} {Amazon.WorkSpaces.Model.Snapshot}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeWorkspaceSnapshots](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Get-WKSWorkspacesConnectionStatus`
<a name="workspaces_DescribeWorkspacesConnectionStatus_powershell_4_topic"></a>

次のコード例は、`Get-WKSWorkspacesConnectionStatus` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定された Workspace の接続ステータスを取得します。**  

```
Get-WKSWorkspacesConnectionStatus -WorkspaceId ws-w123s234r
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DescribeWorkspacesConnectionStatus](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-WKSIpGroup`
<a name="workspaces_CreateIpGroup_powershell_4_topic"></a>

次のコード例は、`New-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、FreshEmptyIpGroup という名前の空の IP グループを作成します**  

```
New-WKSIpGroup -GroupName "FreshNewIPGroup"
```
**出力:**  

```
wsipg-w45rty4ty
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateIpGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-WKSTag`
<a name="workspaces_CreateTags_powershell_4_topic"></a>

次のコード例は、`New-WKSTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、`ws-wsname` という名前のワークスペースに新しいタグを追加します。タグのキーは「Name」で、キー値は `AWS_Workspace` です。**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag
```
**例 2: この例では、`ws-wsname` という名前のワークスペースに複数のタグを追加します。1 つのタグには「Name」のキーと `AWS_Workspace` のキー値があり、もう 1 つのタグには「Stage」のタグキーと「Test」のキー値があります。**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"

$tag2 = New-Object Amazon.WorkSpaces.Model.Tag
$tag2.Key = "Stage"
$tag2.Value = "Test"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag,$tag2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `New-WKSWorkspace`
<a name="workspaces_CreateWorkspaces_powershell_4_topic"></a>

次のコード例は、`New-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定されたバンドル、ディレクトリ、ユーザーの WorkSpace を作成します。**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME"}
```
**例 2: この例では、複数の WorkSpaces を作成します。**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_1"},@{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_2"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[CreateWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-WKSIpGroup`
<a name="workspaces_AssociateIpGroups_powershell_4_topic"></a>

次のコード例は、`Register-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定 IP グループを指定ディレクトリに登録します。**  

```
Register-WKSIpGroup -GroupId wsipg-23ahsdres -DirectoryId d-123412e123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[AssociateIpGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Register-WKSWorkspaceDirectory`
<a name="workspaces_RegisterWorkspaceDirectory_powershell_4_topic"></a>

次のコード例は、`Register-WKSWorkspaceDirectory` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、Workspaces Service の指定されたディレクトリを登録します。**  

```
Register-WKSWorkspaceDirectory -DirectoryId d-123412a123 -EnableWorkDoc $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RegisterWorkspaceDirectory](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-WKSIpGroup`
<a name="workspaces_DeleteIpGroup_powershell_4_topic"></a>

次のコード例は、`Remove-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: この例では、指定 IP グループを削除します。**  

```
Remove-WKSIpGroup -GroupId wsipg-32fhgtred
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSIpGroup (DeleteIpGroup)" on target "wsipg-32fhgtred".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteIpGroup](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-WKSTag`
<a name="workspaces_DeleteTags_powershell_4_topic"></a>

次のコード例は、`Remove-WKSTag` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、Workspace に関連付けられたタグを削除します。**  

```
Remove-WKSTag -ResourceId ws-w10b3abcd -TagKey "Type"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSTag (DeleteTags)" on target "ws-w10b3abcd".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Remove-WKSWorkspace`
<a name="workspaces_TerminateWorkspaces_powershell_4_topic"></a>

次のコード例は、`Remove-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 複数の WorkSpaces を終了します。-Force スイッチを使用すると、コマンドレットの確認を求めるプロンプトが表示されなくなります。**  

```
Remove-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0" -Force
```
**例 2: すべての WorkSpaces のコレクションを取得し、Remove-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、すべての WorkSpaces を終了します。コマンドレットは、各 WorkSpace が終了する前にプロンプトを表示します。確認を非表示にするには、-Force スイッチを追加します。**  

```
Get-WKSWorkspaces | Remove-WKSWorkspace
```
**例 3: この例では、終了する WorkSpaces を定義する TerminateRequest オブジェクトを渡す方法を示します。-Force スイッチが指定されていない限り、コマンドレットは続行する前に確認を求めます。**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Remove-WKSWorkspace -Request $arrRequest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[TerminateWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Reset-WKSWorkspace`
<a name="workspaces_RebuildWorkspaces_powershell_4_topic"></a>

次のコード例は、`Reset-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された WorkSpace を再構築します。**  

```
Reset-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**例 2: すべての WorkSpaces のコレクションを取得し、Reset-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、WorkSpaces を再構築します。**  

```
Get-WKSWorkspaces | Reset-WKSWorkspace
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RebuildWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Restart-WKSWorkspace`
<a name="workspaces_RebootWorkspaces_powershell_4_topic"></a>

次のコード例は、`Restart-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 指定された WorkSpace を再起動します。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**例 2: 複数の WorkSpaces を再起動します。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d","ws-5a6b7c8d"
```
**例 3: すべての WorkSpaces のコレクションを取得し、Restart-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、WorkSpaces を再起動します。**  

```
Get-WKSWorkspaces | Restart-WKSWorkspace
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[RebootWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Stop-WKSWorkspace`
<a name="workspaces_StopWorkspaces_powershell_4_topic"></a>

次のコード例は、`Stop-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: 複数の WorkSpaces を停止します。**  

```
Stop-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0"
```
**例 2: すべての WorkSpaces のコレクションを取得し、Stop-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、WorkSpaces を停止します。**  

```
Get-WKSWorkspaces | Stop-WKSWorkspace
```
**例 3: この例では、停止する WorkSpaces を定義する StopRequest オブジェクトを渡す方法を示します。**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Stop-WKSWorkspace -Request $arrRequest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[StopWorkspaces](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

### `Unregister-WKSIpGroup`
<a name="workspaces_DisassociateIpGroups_powershell_4_topic"></a>

次のコード例は、`Unregister-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V4**  
**例 1: このサンプルは、指定ディレクトリから指定 IP グループを登録解除します。**  

```
Unregister-WKSIpGroup -GroupId wsipg-12abcdphq -DirectoryId d-123454b123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V4)* の「[DisassociateIpGroups](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

# Tools for PowerShell V5 のコード例
<a name="powershell_5_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ Tools for PowerShell V5 デベロッパーガイド ](https://docs.aws.amazon.com/powershell/v5/userguide/pstools-welcome.html) ** – で PowerShell を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](powershell_5_acm_code_examples.md)
+ [Application Auto Scaling](powershell_5_application-auto-scaling_code_examples.md)
+ [WorkSpaces Applications](powershell_5_appstream_code_examples.md)
+ [Aurora](powershell_5_aurora_code_examples.md)
+ [Auto Scaling](powershell_5_auto-scaling_code_examples.md)
+ [AWS Budgets](powershell_5_budgets_code_examples.md)
+ [AWS Cloud9](powershell_5_cloud9_code_examples.md)
+ [CloudFormation](powershell_5_cloudformation_code_examples.md)
+ [CloudFront](powershell_5_cloudfront_code_examples.md)
+ [CloudTrail](powershell_5_cloudtrail_code_examples.md)
+ [CloudWatch](powershell_5_cloudwatch_code_examples.md)
+ [CodeCommit](powershell_5_codecommit_code_examples.md)
+ [CodeDeploy](powershell_5_codedeploy_code_examples.md)
+ [CodePipeline](powershell_5_codepipeline_code_examples.md)
+ [Amazon Cognito ID](powershell_5_cognito-identity_code_examples.md)
+ [AWS Config](powershell_5_config-service_code_examples.md)
+ [Device Farm](powershell_5_device-farm_code_examples.md)
+ [Directory Service](powershell_5_directory-service_code_examples.md)
+ [AWS DMS](powershell_5_database-migration-service_code_examples.md)
+ [DynamoDB](powershell_5_dynamodb_code_examples.md)
+ [Amazon EC2](powershell_5_ec2_code_examples.md)
+ [Amazon ECR](powershell_5_ecr_code_examples.md)
+ [Amazon ECS](powershell_5_ecs_code_examples.md)
+ [Amazon EFS](powershell_5_efs_code_examples.md)
+ [Amazon EKS](powershell_5_eks_code_examples.md)
+ [Elastic Load Balancing - バージョン 1](powershell_5_elastic-load-balancing_code_examples.md)
+ [Elastic Load Balancing - バージョン 2](powershell_5_elastic-load-balancing-v2_code_examples.md)
+ [Amazon FSx](powershell_5_fsx_code_examples.md)
+ [Amazon Glacier](powershell_5_glacier_code_examples.md)
+ [AWS Glue](powershell_5_glue_code_examples.md)
+ [AWS Health](powershell_5_health_code_examples.md)
+ [IAM](powershell_5_iam_code_examples.md)
+ [Kinesis](powershell_5_kinesis_code_examples.md)
+ [Lambda](powershell_5_lambda_code_examples.md)
+ [Amazon ML](powershell_5_machine-learning_code_examples.md)
+ [Macie](powershell_5_macie2_code_examples.md)
+ [AWS の料金表](powershell_5_pricing_code_examples.md)
+ [リソースグループ](powershell_5_resource-groups_code_examples.md)
+ [リソースグループタグ付け API](powershell_5_resource-groups-tagging-api_code_examples.md)
+ [Route 53](powershell_5_route-53_code_examples.md)
+ [Amazon S3](powershell_5_s3_code_examples.md)
+ [Security Hub CSPM](powershell_5_securityhub_code_examples.md)
+ [Amazon SES](powershell_5_ses_code_examples.md)
+ [Amazon SES API v2](powershell_5_sesv2_code_examples.md)
+ [Amazon SNS](powershell_5_sns_code_examples.md)
+ [Amazon SQS](powershell_5_sqs_code_examples.md)
+ [AWS STS](powershell_5_sts_code_examples.md)
+ [サポート](powershell_5_support_code_examples.md)
+ [Systems Manager](powershell_5_ssm_code_examples.md)
+ [Amazon Translate](powershell_5_translate_code_examples.md)
+ [AWS WAFV2](powershell_5_wafv2_code_examples.md)
+ [WorkSpaces](powershell_5_workspaces_code_examples.md)

# Tools for PowerShell V5 を使用した ACM の例
<a name="powershell_5_acm_code_examples"></a>

次のコード例は、ACM で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-ACMCertificate`
<a name="acm_GetCertificate_powershell_5_topic"></a>

次のコード例は、`Get-ACMCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、証明書の ARN を使用して証明書とそのチェーンを返す方法を示します。**  

```
Get-ACMCertificate -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ACMCertificateDetail`
<a name="acm_DescribeCertificate_powershell_5_topic"></a>

次のコード例は、`Get-ACMCertificateDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定した証明書の詳細を返します。**  

```
Get-ACMCertificateDetail -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
**出力:**  

```
CertificateArn          : arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
CreatedAt               : 1/21/2016 5:55:59 PM
DomainName              : www.example.com
DomainValidationOptions : {www.example.com}
InUseBy                 : {}
IssuedAt                : 1/1/0001 12:00:00 AM
Issuer                  :
KeyAlgorithm            : RSA-2048
NotAfter                : 1/1/0001 12:00:00 AM
NotBefore               : 1/1/0001 12:00:00 AM
RevocationReason        :
RevokedAt               : 1/1/0001 12:00:00 AM
Serial                  :
SignatureAlgorithm      : SHA256WITHRSA
Status                  : PENDING_VALIDATION
Subject                 : CN=www.example.com
SubjectAlternativeNames : {www.example.net}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ACMCertificateList`
<a name="acm_ListCertificates_powershell_5_topic"></a>

次のコード例は、`Get-ACMCertificateList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 証明書の ARN のリストと各 ARN のドメイン名を取得します。コマンドレットは自動的にページ分割され、すべての ARN を取得します。ページ分割を手動で制御するには、-MaxItem パラメータを使用して各サービス呼び出しに対して返される証明書 ARN の数を制御し、-NextToken パラメータを使用して各呼び出しの開始点を示します。**  

```
Get-ACMCertificateList
```
**出力:**  

```
CertificateArn                                                                      DomainName
--------------                                                                      ----------
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012 www.example.com
```
**例 2: 指定された状態に証明書の状態が一致するすべての証明書 ARN のリストを取得します。**  

```
Get-ACMCertificateList -CertificateStatus "VALIDATION_TIMED_OUT","FAILED"
```
**例 3: この例では、キータイプが RSA\$12048、拡張キーの使用法または目的が CODE\$1SIGNING である、us-east-1 リージョン内のすべての証明書のリストを返します。これらのフィルタリングパラメータの値については、API リファレンスの「ListCertificates Filters」トピック: https://docs.aws.amazon.com/acm/latest/APIReference/API\$1Filters.html を参照してください。**  

```
Get-ACMCertificateList -Region us-east-1 -Includes_KeyType RSA_2048 -Includes_ExtendedKeyUsage CODE_SIGNING
```
**出力:**  

```
CertificateArn                                                                      DomainName                
--------------                                                                      ----------                
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-d7c0-48c1-af8d-2133d8f30zzz *.route53docs.com
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-98a5-443d-a734-800430c80zzz nerdzizm.net               
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-2be6-4376-8fa7-bad559525zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-e7ca-44c5-803e-24d9f2f36zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-1241-4b71-80b1-090305a62zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-8709-4568-8c64-f94617c99zzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-a8fa-4a61-98cf-e08ccc0eezzz                           
arn:aws:acm:us-east-1:8xxxxxxxxxxx:certificate/xxxxxxxx-fa47-40fe-a714-2d277d3eezzz *.route53docs.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListCertificates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ACMCertificate`
<a name="acm_RequestCertificate_powershell_5_topic"></a>

次のコード例は、`New-ACMCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 新しい証明書を作成します。サービスは新しい証明書の ARN を返します。**  

```
New-ACMCertificate -DomainName "www.example.com"
```
**出力:**  

```
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
```
**例 2: 新しい証明書を作成します。サービスは新しい証明書の ARN を返します。**  

```
New-ACMCertificate -DomainName "www.example.com" -SubjectAlternativeName "example.com","www.example.net"
```
**出力:**  

```
arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[RequestCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ACMCertificate`
<a name="acm_DeleteCertificate_powershell_5_topic"></a>

次のコード例は、`Remove-ACMCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された ARN で識別される証明書および関連するプライベートキーを削除します。コマンドレットは、操作を続行する前に確認を求めます。確認を表示しないようにするには、-Force スイッチを追加します。**  

```
Remove-ACMCertificate -CertificateArn "arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Send-ACMValidationEmail`
<a name="acm_ResendValidationEmail_powershell_5_topic"></a>

次のコード例は、`Send-ACMValidationEmail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「www.example.com」のドメイン所有権を検証する E メールの送信をリクエストします。シェルの \$1ConfirmPreference が「Medium」以下に設定されている場合、コマンドレットは続行する前に確認を求めます。-Force スイッチを追加すると、確認メッセージが表示されなくなります。**  

```
$params = @{
    CertificateArn="arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012"
    Domain="www.example.com"
    ValidationDomain="example.com"    
}        
Send-ACMValidationEmail @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResendValidationEmail](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Application Auto Scaling の例
<a name="powershell_5_application-auto-scaling_code_examples"></a>

次のコード例は、Application Auto Scaling で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-AASScalableTarget`
<a name="application-auto-scaling_RegisterScalableTarget_powershell_5_topic"></a>

次のコード例は、`Add-AASScalableTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、スケーラブルなターゲットを登録または更新します。スケーラブルターゲットとは、Application Auto Scaling がスケールアウトおよびスケールインできるリソースです。**  

```
Add-AASScalableTarget -ServiceNamespace AppStream -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -MinCapacity 2 -MaxCapacity 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RegisterScalableTarget](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-AASScalableTarget`
<a name="application-auto-scaling_DescribeScalableTargets_powershell_5_topic"></a>

次のコード例は、`Get-AASScalableTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前空間内の Application Autoscaling Scalable ターゲットに関する情報を提供します。**  

```
Get-AASScalableTarget -ServiceNamespace "AppStream"
```
**出力:**  

```
CreationTime      : 11/7/2019 2:30:03 AM
MaxCapacity       : 5
MinCapacity       : 1
ResourceId        : fleet/Test
RoleARN           : arn:aws:iam::012345678912:role/aws-service-role/appstream.application-autoscaling.amazonaws.com/AWSServiceRoleForApplicationAutoScaling_AppStreamFleet
ScalableDimension : appstream:fleet:DesiredCapacity
ServiceNamespace  : appstream
SuspendedState    : Amazon.ApplicationAutoScaling.Model.SuspendedState
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScalableTargets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-AASScalingActivity`
<a name="application-auto-scaling_DescribeScalingActivities_powershell_5_topic"></a>

次のコード例は、`Get-AASScalingActivity` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された名前空間における過去 6 週間のスケーリングアクティビティに関する詳細情報を提供します。**  

```
Get-AASScalingActivity -ServiceNamespace AppStream
```
**出力:**  

```
ActivityId        : 2827409f-b639-4cdb-a957-8055d5d07434
Cause             : monitor alarm Appstream2-MyFleet-default-scale-in-Alarm in state ALARM triggered policy default-scale-in
Description       : Setting desired capacity to 2.
Details           :
EndTime           : 12/14/2019 11:32:49 AM
ResourceId        : fleet/MyFleet
ScalableDimension : appstream:fleet:DesiredCapacity
ServiceNamespace  : appstream
StartTime         : 12/14/2019 11:32:14 AM
StatusCode        : Successful
StatusMessage     : Successfully set desired capacity to 2. Change successfully fulfilled by appstream.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-AASScalingPolicy`
<a name="application-auto-scaling_DescribeScalingPolicies_powershell_5_topic"></a>

次のコード例は、`Get-AASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、指定されたサービス名前空間の Application Auto Scaling スケーリングポリシーを記述します。**  

```
Get-AASScalingPolicy -ServiceNamespace AppStream
```
**出力:**  

```
Alarms                                   : {Appstream2-LabFleet-default-scale-out-Alarm}
CreationTime                             : 9/3/2019 2:48:15 AM
PolicyARN                                : arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:5659b069-b5cd-4af1-9f7f-3e956d36233e:resource/appstream/fleet/LabFleet:
                                           policyName/default-scale-out
PolicyName                               : default-scale-out
PolicyType                               : StepScaling
ResourceId                               : fleet/LabFleet
ScalableDimension                        : appstream:fleet:DesiredCapacity
ServiceNamespace                         : appstream
StepScalingPolicyConfiguration           : Amazon.ApplicationAutoScaling.Model.StepScalingPolicyConfiguration
TargetTrackingScalingPolicyConfiguration :

Alarms                                   : {Appstream2-LabFleet-default-scale-in-Alarm}
CreationTime                             : 9/3/2019 2:48:15 AM
PolicyARN                                : arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:5659b069-b5cd-4af1-9f7f-3e956d36233e:resource/appstream/fleet/LabFleet:
                                           policyName/default-scale-in
PolicyName                               : default-scale-in
PolicyType                               : StepScaling
ResourceId                               : fleet/LabFleet
ScalableDimension                        : appstream:fleet:DesiredCapacity
ServiceNamespace                         : appstream
StepScalingPolicyConfiguration           : Amazon.ApplicationAutoScaling.Model.StepScalingPolicyConfiguration
TargetTrackingScalingPolicyConfiguration :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScalingPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-AASScheduledAction`
<a name="application-auto-scaling_DescribeScheduledActions_powershell_5_topic"></a>

次のコード例は、`Get-AASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットには、Auto Scaling グループにスケジュールされた、実行されていないか終了時刻に達していないアクションが一覧表示されます。 **  

```
Get-AASScheduledAction -ServiceNamespace AppStream
```
**出力:**  

```
CreationTime         : 12/22/2019 9:25:52 AM
EndTime              : 1/1/0001 12:00:00 AM
ResourceId           : fleet/MyFleet
ScalableDimension    : appstream:fleet:DesiredCapacity
ScalableTargetAction : Amazon.ApplicationAutoScaling.Model.ScalableTargetAction
Schedule             : cron(0 0 8 ? * MON-FRI *)
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:012345678912:scheduledAction:4897ca24-3caa-4bf1-8484-851a089b243c:resource/appstream/fleet/MyFleet:scheduledActionName
                       /WeekDaysFleetScaling
ScheduledActionName  : WeekDaysFleetScaling
ServiceNamespace     : appstream
StartTime            : 1/1/0001 12:00:00 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-AASScalableTarget`
<a name="application-auto-scaling_DeregisterScalableTarget_powershell_5_topic"></a>

次のコード例は、`Remove-AASScalableTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Application Auto Scaling のスケーラブルターゲットを登録解除します。スケーラブルターゲットの登録を解除すると、それに関連付けられているスケーリングポリシーが削除されます。**  

```
Remove-AASScalableTarget -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -ServiceNamespace AppStream
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-AASScalableTarget (DeregisterScalableTarget)" on target "fleet/MyFleet".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeregisterScalableTarget](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-AASScalingPolicy`
<a name="application-auto-scaling_DeleteScalingPolicy_powershell_5_topic"></a>

次のコード例は、`Remove-AASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Application Auto Scaling スケーラブルターゲットの指定されたスケーリングポリシーを削除します。**  

```
Remove-AASScalingPolicy -ServiceNamespace AppStream -PolicyName "default-scale-out" -ResourceId fleet/Test -ScalableDimension appstream:fleet:DesiredCapacity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-AASScheduledAction`
<a name="application-auto-scaling_DeleteScheduledAction_powershell_5_topic"></a>

次のコード例は、`Remove-AASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Application Auto Scaling スケーラブルターゲットの指定されたスケジュールされたアクションを削除します。**  

```
Remove-AASScheduledAction -ServiceNamespace AppStream -ScheduledActionName WeekDaysFleetScaling -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-AASScheduledAction (DeleteScheduledAction)" on target "WeekDaysFleetScaling".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-AASScalingPolicy`
<a name="application-auto-scaling_PutScalingPolicy_powershell_5_topic"></a>

次のコード例は、`Set-AASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Application Auto Scaling のスケーラブルターゲットのポリシーを作成または更新します。各スケーラブルターゲットは、サービス名前空間、リソース ID、スケーラブルなディメンションによって識別されます。**  

```
Set-AASScalingPolicy -ServiceNamespace AppStream -PolicyName ASFleetScaleInPolicy -PolicyType StepScaling  -ResourceId fleet/MyFleet -ScalableDimension appstream:fleet:DesiredCapacity -StepScalingPolicyConfiguration_AdjustmentType ChangeInCapacity -StepScalingPolicyConfiguration_Cooldown 360 -StepScalingPolicyConfiguration_MetricAggregationType Average -StepScalingPolicyConfiguration_StepAdjustments @{ScalingAdjustment = -1; MetricIntervalUpperBound = 0}
```
**出力:**  

```
Alarms    PolicyARN
------    ---------
{}        arn:aws:autoscaling:us-west-2:012345678912:scalingPolicy:4897ca24-3caa-4bf1-8484-851a089b243c:resource/appstream/fleet/MyFleet:policyName/ASFleetScaleInPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-AASScheduledAction`
<a name="application-auto-scaling_PutScheduledAction_powershell_5_topic"></a>

次のコード例は、`Set-AASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Application Auto Scaling のスケーラブルターゲットのスケジュールされたアクションを作成または更新します。各スケーラブルターゲットは、サービス名前空間、リソース ID、スケーラブルなディメンションによって識別されます。**  

```
Set-AASScheduledAction -ServiceNamespace AppStream -ResourceId fleet/MyFleet -Schedule "cron(0 0 8 ? * MON-FRI *)" -ScalableDimension appstream:fleet:DesiredCapacity -ScheduledActionName WeekDaysFleetScaling -ScalableTargetAction_MinCapacity 5 -ScalableTargetAction_MaxCapacity 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した WorkSpaces アプリケーションの例
<a name="powershell_5_appstream_code_examples"></a>

次のコード例は、WorkSpaces アプリケーションで AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-APSResourceTag`
<a name="appstream_TagResource_powershell_5_topic"></a>

次のコード例は、`Add-APSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream リソースにリソースタグを追加します。**  

```
Add-APSResourceTag -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest -Tag @{StackState='Test'} -Select ^Tag
```
**出力:**  

```
Name                           Value
----                           -----
StackState                     Test
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Copy-APSImage`
<a name="appstream_CopyImage_powershell_5_topic"></a>

次のコード例は、`Copy-APSImage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、画像を他のリージョンにコピーします**  

```
Copy-APSImage -DestinationImageName TestImageCopy -DestinationRegion us-west-2 -SourceImageName Powershell
```
**出力:**  

```
TestImageCopy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CopyImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-APSUSer`
<a name="appstream_DisableUser_powershell_5_topic"></a>

次のコード例は、`Disable-APSUSer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、USERPOOL のユーザーを無効にします**  

```
Disable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-APSUser`
<a name="appstream_EnableUser_powershell_5_topic"></a>

次のコード例は、`Enable-APSUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、USERPOOL で無効になっているユーザーを有効にします**  

```
Enable-APSUser -AuthenticationType USERPOOL -UserName TestUser@lab.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSAssociatedFleetList`
<a name="appstream_ListAssociatedFleets_powershell_5_topic"></a>

次のコード例は、`Get-APSAssociatedFleetList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スタックに関連付けられたフリートを表示します**  

```
Get-APSAssociatedFleetList -StackName PowershellStack
```
**出力:**  

```
PowershellFleet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListAssociatedFleets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSAssociatedStackList`
<a name="appstream_ListAssociatedStacks_powershell_5_topic"></a>

次のコード例は、`Get-APSAssociatedStackList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、フリートに関連付けられたスタックを表示します**  

```
Get-APSAssociatedStackList -FleetName PowershellFleet
```
**出力:**  

```
PowershellStack
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListAssociatedStacks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSDirectoryConfigList`
<a name="appstream_DescribeDirectoryConfigs_powershell_5_topic"></a>

次のコード例は、`Get-APSDirectoryConfigList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream で作成されたディレクトリ設定を表示します**  

```
Get-APSDirectoryConfigList | Select DirectoryName, OrganizationalUnitDistinguishedNames, CreatedTime
```
**出力:**  

```
DirectoryName OrganizationalUnitDistinguishedNames CreatedTime
------------- ------------------------------------ -----------
Test.com      {OU=AppStream,DC=Test,DC=com}    9/6/2019 10:56:40 AM
contoso.com   {OU=AppStream,OU=contoso,DC=contoso,DC=com}  8/9/2019 9:08:50 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeDirectoryConfigs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSFleetList`
<a name="appstream_DescribeFleets_powershell_5_topic"></a>

次のコード例は、`Get-APSFleetList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、フリートの詳細を表示します**  

```
Get-APSFleetList -Name Test
```
**出力:**  

```
Arn                            : arn:aws:appstream:us-east-1:1234567890:fleet/Test
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 9/12/2019 5:00:45 PM
Description                    : Test
DisconnectTimeoutInSeconds     : 900
DisplayName                    : Test
DomainJoinInfo                 :
EnableDefaultInternetAccess    : False
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 900
ImageArn                       : arn:aws:appstream:us-east-1:1234567890:image/Test
ImageName                      : Test
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : Test
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeFleets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSImageBuilderList`
<a name="appstream_DescribeImageBuilders_powershell_5_topic"></a>

次のコード例は、`Get-APSImageBuilderList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ImageBuilder の詳細を表示します**  

```
Get-APSImageBuilderList -Name TestImage
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:1234567890:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : STOPPED
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeImageBuilders](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSImageList`
<a name="appstream_DescribeImages_powershell_5_topic"></a>

次のコード例は、`Get-APSImageList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、プライベート AppStream イメージを表示します**  

```
Get-APSImageList -Type PRIVATE | select DisplayName, ImageBuilderName, Visibility, arn
```
**出力:**  

```
DisplayName          ImageBuilderName      Visibility Arn
-----------          ----------------      ---------- ---
OfficeApps           OfficeApps            PRIVATE    arn:aws:appstream:us-east-1:123456789012:image/OfficeApps
SessionScriptV2      SessionScriptTest     PRIVATE    arn:aws:appstream:us-east-1:123456789012:image/SessionScriptV2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeImages](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSImagePermission`
<a name="appstream_DescribeImagePermissions_powershell_5_topic"></a>

次のコード例は、`Get-APSImagePermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、共有 AppStream イメージへのアクセス許可を表示します**  

```
Get-APSImagePermission -Name Powershell  | select SharedAccountId, @{n="AllowFleet";e={$_.ImagePermissions.AllowFleet}}, @{n="AllowImageBuilder";e={$_.ImagePermissions.AllowImageBuilder}}
```
**出力:**  

```
SharedAccountId AllowFleet AllowImageBuilder
--------------- ---------- -----------------
123456789012          True              True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSSessionList`
<a name="appstream_DescribeSessions_powershell_5_topic"></a>

次のコード例は、`Get-APSSessionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、フリートへのセッションのリストを表示します。**  

```
Get-APSSessionList -FleetName PowershellFleet -StackName PowershellStack
```
**出力:**  

```
AuthenticationType         : API
ConnectionState            : CONNECTED
FleetName                  : PowershellFleet
Id                         : d8987c70-4394-4324-a396-2d485c26f2a2
MaxExpirationTime          : 12/27/2019 4:54:07 AM
NetworkAccessConfiguration : Amazon.AppStream.Model.NetworkAccessConfiguration
StackName                  : PowershellStack
StartTime                  : 12/26/2019 12:54:12 PM
State                      : ACTIVE
UserId                     : Test
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSessions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSStackList`
<a name="appstream_DescribeStacks_powershell_5_topic"></a>

次のコード例は、`Get-APSStackList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream スタックのリストを表示します**  

```
Get-APSStackList | Select DisplayName, Arn, CreatedTime
```
**出力:**  

```
DisplayName                   Arn                                                                          CreatedTime
-----------                   ---                                                                          -----------
PowershellStack               arn:aws:appstream:us-east-1:123456789012:stack/PowershellStack               4/24/2019 8:49:29 AM
SessionScriptTest             arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest             9/12/2019 3:23:12 PM
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSTagsForResourceList`
<a name="appstream_ListTagsForResource_powershell_5_topic"></a>

次のコード例は、`Get-APSTagsForResourceList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream リソースのタグを表示します**  

```
Get-APSTagsForResourceList -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest
```
**出力:**  

```
Key        Value
---        -----
StackState Test
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-APSUsageReportSubscription`
<a name="appstream_DescribeUsageReportSubscriptions_powershell_5_topic"></a>

次のコード例は、`Get-APSUsageReportSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStreamUsageReport 設定の詳細を表示します**  

```
Get-APSUsageReportSubscription
```
**出力:**  

```
LastGeneratedReportDate S3BucketName                                   Schedule SubscriptionErrors
----------------------- ------------                                   -------- ------------------
1/1/0001 12:00:00 AM    appstream-logs-us-east-1-123456789012-sik1hnxe DAILY    {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeUsageReportSubscriptions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSUser`
<a name="appstream_DescribeUsers_powershell_5_topic"></a>

次のコード例は、`Get-APSUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ステータスが有効なユーザーのリストを表示します**  

```
Get-APSUser -AuthenticationType USERPOOL | Select-Object UserName, AuthenticationType, Enabled
```
**出力:**  

```
UserName                   AuthenticationType Enabled
--------                   ------------------ -------
foo1@contoso.com USERPOOL              True
foo2@contoso.com        USERPOOL              True
foo3@contoso.com    USERPOOL              True
foo4@contoso.com   USERPOOL              True
foo5@contoso.com         USERPOOL              True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeUsers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-APSUserStackAssociation`
<a name="appstream_DescribeUserStackAssociations_powershell_5_topic"></a>

次のコード例は、`Get-APSUserStackAssociation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スタックに割り当てられたユーザーのリストを表示します**  

```
Get-APSUserStackAssociation -StackName PowershellStack
```
**出力:**  

```
AuthenticationType SendEmailNotification StackName       UserName
------------------ --------------------- ---------       --------
USERPOOL           False                 PowershellStack TestUser1@lab.com
USERPOOL           False                 PowershellStack TestUser2@lab.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeUserStackAssociations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSDirectoryConfig`
<a name="appstream_CreateDirectoryConfig_powershell_5_topic"></a>

次のコード例は、`New-APSDirectoryConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream にディレクトリ設定を作成します**  

```
New-APSDirectoryConfig -ServiceAccountCredentials_AccountName contoso\ServiceAccount -ServiceAccountCredentials_AccountPassword MyPass -DirectoryName contoso.com -OrganizationalUnitDistinguishedName "OU=AppStream,OU=Contoso,DC=Contoso,DC=com"
```
**出力:**  

```
CreatedTime            DirectoryName OrganizationalUnitDistinguishedNames        ServiceAccountCredentials
-----------            ------------- ------------------------------------        -------------------------
12/27/2019 11:00:30 AM contoso.com   {OU=AppStream,OU=Contoso,DC=Contoso,DC=com} Amazon.AppStream.Model.ServiceAccountCredentials
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSFleet`
<a name="appstream_CreateFleet_powershell_5_topic"></a>

次のコード例は、`New-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しい AppStream フリートを作成します**  

```
New-APSFleet -ComputeCapacity_DesiredInstance 1 -InstanceType stream.standard.medium -Name TestFleet -DisplayName TestFleet -FleetType ON_DEMAND -EnableDefaultInternetAccess $True -VpcConfig_SubnetIds "subnet-123ce32","subnet-a1234cfd" -VpcConfig_SecurityGroupIds sg-4d012a34 -ImageName SessionScriptTest -Region us-west-2
```
**出力:**  

```
Arn                            : arn:aws:appstream:us-west-2:123456789012:fleet/TestFleet
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 12/27/2019 11:24:42 AM
Description                    :
DisconnectTimeoutInSeconds     : 900
DisplayName                    : TestFleet
DomainJoinInfo                 :
EnableDefaultInternetAccess    : True
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 0
ImageArn                       : arn:aws:appstream:us-west-2:123456789012:image/SessionScriptTest
ImageName                      : SessionScriptTest
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : TestFleet
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSImageBuilder`
<a name="appstream_CreateImageBuilder_powershell_5_topic"></a>

次のコード例は、`New-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream に Image Builder を作成します**  

```
New-APSImageBuilder -InstanceType stream.standard.medium -Name TestIB -DisplayName TestIB -ImageName AppStream-WinServer2012R2-12-12-2019 -EnableDefaultInternetAccess $True -VpcConfig_SubnetId subnet-a1234cfd -VpcConfig_SecurityGroupIds sg-2d012a34 -Region us-west-2
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 12-16-2019
Arn                         : arn:aws:appstream:us-west-2:123456789012:image-builder/TestIB
CreatedTime                 : 12/27/2019 11:39:24 AM
Description                 :
DisplayName                 : TestIB
DomainJoinInfo              :
EnableDefaultInternetAccess : True
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-west-2::image/AppStream-WinServer2012R2-12-12-2019
ImageBuilderErrors          : {}
InstanceType                : stream.standard.medium
Name                        : TestIB
NetworkAccessConfiguration  :
Platform                    : WINDOWS
State                       : PENDING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSImageBuilderStreamingURL`
<a name="appstream_CreateImageBuilderStreamingURL_powershell_5_topic"></a>

次のコード例は、`New-APSImageBuilderStreamingURL` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、有効期間が 2 時間の ImageBuilder ストリーミング URL を作成します。**  

```
New-APSImageBuilderStreamingURL -Name TestIB -Validity 7200 -Region us-west-2
```
**出力:**  

```
Expires               StreamingURL
-------               ------------
12/27/2019 1:49:13 PM https://appstream2.us-west-2.aws.amazon.com/authenticate?parameters=eyJ0eXBlIjoiQURNSU4iLCJleHBpcmVzIjoiMTU3NzQ1NDU1MyIsImF3c0FjY291bnRJZCI6IjM5MzQwMzgxMTQwNyIsInVzZXJJZCI6ImFkbWluIiwiY2F
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateImageBuilderStreamingURL](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSStack`
<a name="appstream_CreateStack_powershell_5_topic"></a>

次のコード例は、`New-APSStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しい AppStream スタックを作成します。**  

```
New-APSStack -Name TestStack -DisplayName TestStack -ApplicationSettings_Enabled $True -ApplicationSettings_SettingsGroup TestStack -Region us-west-2
```
**出力:**  

```
AccessEndpoints     : {}
ApplicationSettings : Amazon.AppStream.Model.ApplicationSettingsResponse
Arn                 : arn:aws:appstream:us-west-2:123456789012:stack/TestStack
CreatedTime         : 12/27/2019 12:34:19 PM
Description         :
DisplayName         : TestStack
EmbedHostDomains    : {}
FeedbackURL         :
Name                : TestStack
RedirectURL         :
StackErrors         : {}
StorageConnectors   : {}
UserSettings        : {Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting}
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSStreamingURL`
<a name="appstream_CreateStreamingURL_powershell_5_topic"></a>

次のコード例は、`New-APSStreamingURL` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スタックのストリーミング URL を作成します**  

```
New-APSStreamingURL -StackName SessionScriptTest -FleetName SessionScriptNew -UserId TestUser
```
**出力:**  

```
Expires                StreamingURL
-------                ------------
12/27/2019 12:43:37 PM https://appstream2.us-east-1.aws.amazon.com/authenticate?parameters=eyJ0eXBlIjoiRU5EX1VTRVIiLCJleHBpcmVzIjoiMTU3NzQ1MDYxNyIsImF3c0FjY291bnRJZCI6IjM5MzQwMzgxMTQwNyIsInVzZXJJZCI6IlRlc3RVc2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateStreamingURL](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSUsageReportSubscription`
<a name="appstream_CreateUsageReportSubscription_powershell_5_topic"></a>

次のコード例は、`New-APSUsageReportSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream 使用状況レポートを有効にします**  

```
New-APSUsageReportSubscription
```
**出力:**  

```
S3BucketName                                   Schedule
------------                                   --------
appstream-logs-us-east-1-123456789012-sik2hnxe DAILY
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateUsageReportSubscription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-APSUser`
<a name="appstream_CreateUser_powershell_5_topic"></a>

次のコード例は、`New-APSUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、USERPOOL にユーザーを作成します**  

```
New-APSUser -UserName Test@lab.com -AuthenticationType USERPOOL -FirstName 'kt' -LastName 'aws' -Select ^UserName
```
**出力:**  

```
Test@lab.com
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-APSFleet`
<a name="appstream_AssociateFleet_powershell_5_topic"></a>

次のコード例は、`Register-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、フリートをスタックに登録します**  

```
Register-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AssociateFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-APSUserStackBatch`
<a name="appstream_BatchAssociateUserStack_powershell_5_topic"></a>

次のコード例は、`Register-APSUserStackBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、USERPOOL のユーザーにスタックを割り当てます**  

```
Register-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchAssociateUserStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSDirectoryConfig`
<a name="appstream_DeleteDirectoryConfig_powershell_5_topic"></a>

次のコード例は、`Remove-APSDirectoryConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream ディレクトリ設定を削除します**  

```
Remove-APSDirectoryConfig -DirectoryName contoso.com
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSDirectoryConfig (DeleteDirectoryConfig)" on target "contoso.com".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSFleet`
<a name="appstream_DeleteFleet_powershell_5_topic"></a>

次のコード例は、`Remove-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream フリートを削除します**  

```
Remove-APSFleet -Name TestFleet -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSFleet (DeleteFleet)" on target "TestFleet".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSImage`
<a name="appstream_DeleteImage_powershell_5_topic"></a>

次のコード例は、`Remove-APSImage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、イメージを削除します**  

```
Remove-APSImage -Name TestImage -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImage (DeleteImage)" on target "TestImage".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A

Applications                : {}
AppstreamAgentVersion       : LATEST
Arn                         : arn:aws:appstream:us-west-2:123456789012:image/TestImage
BaseImageArn                :
CreatedTime                 : 12/27/2019 1:34:10 PM
Description                 :
DisplayName                 : TestImage
ImageBuilderName            :
ImageBuilderSupported       : True
ImagePermissions            :
Name                        : TestImage
Platform                    : WINDOWS
PublicBaseImageReleasedDate : 6/12/2018 12:00:00 AM
State                       : AVAILABLE
StateChangeReason           :
Visibility                  : PRIVATE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSImageBuilder`
<a name="appstream_DeleteImageBuilder_powershell_5_topic"></a>

次のコード例は、`Remove-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ImageBuilder を削除します**  

```
Remove-APSImageBuilder -Name TestIB -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImageBuilder (DeleteImageBuilder)" on target "TestIB".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A

AccessEndpoints             : {}
AppstreamAgentVersion       : 12-16-2019
Arn                         : arn:aws:appstream:us-west-2:123456789012:image-builder/TestIB
CreatedTime                 : 12/27/2019 11:39:24 AM
Description                 :
DisplayName                 : TestIB
DomainJoinInfo              :
EnableDefaultInternetAccess : True
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-west-2::image/AppStream-WinServer2012R2-12-12-2019
ImageBuilderErrors          : {}
InstanceType                : stream.standard.medium
Name                        : TestIB
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : DELETING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSImagePermission`
<a name="appstream_DeleteImagePermissions_powershell_5_topic"></a>

次のコード例は、`Remove-APSImagePermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、イメージへのアクセス許可を削除します**  

```
Remove-APSImagePermission -Name Powershell -SharedAccountId 123456789012
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSImagePermission (DeleteImagePermissions)" on target "Powershell".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSResourceTag`
<a name="appstream_UntagResource_powershell_5_topic"></a>

次のコード例は、`Remove-APSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream リソースからリソースタグを削除します**  

```
Remove-APSResourceTag -ResourceArn arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest -TagKey StackState
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSResourceTag (UntagResource)" on target "arn:aws:appstream:us-east-1:123456789012:stack/SessionScriptTest".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-APSStack`
<a name="appstream_DeleteStack_powershell_5_topic"></a>

次のコード例は、`Remove-APSStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スタックを削除します**  

```
Remove-APSStack -Name TestStack -Region us-west-2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSStack (DeleteStack)" on target "TestStack".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSUsageReportSubscription`
<a name="appstream_DeleteUsageReportSubscription_powershell_5_topic"></a>

次のコード例は、`Remove-APSUsageReportSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream 使用状況レポートのサブスクリプションを無効にします**  

```
Remove-APSUsageReportSubscription
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSUsageReportSubscription (DeleteUsageReportSubscription)" on target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteUsageReportSubscription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-APSUser`
<a name="appstream_DeleteUser_powershell_5_topic"></a>

次のコード例は、`Remove-APSUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、USERPOOL からユーザーを削除します**  

```
Remove-APSUser -UserName TestUser@lab.com -AuthenticationType USERPOOL
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-APSUser (DeleteUser)" on target "TestUser@lab.com".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): A
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Revoke-APSSession`
<a name="appstream_ExpireSession_powershell_5_topic"></a>

次のコード例は、`Revoke-APSSession` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream フリートへのセッションを取り消します**  

```
Revoke-APSSession -SessionId 6cd2f9a3-f948-4aa1-8014-8a7dcde14877
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ExpireSession](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-APSFleet`
<a name="appstream_StartFleet_powershell_5_topic"></a>

次のコード例は、`Start-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、フリートを開始します**  

```
Start-APSFleet -Name PowershellFleet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StartFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-APSImageBuilder`
<a name="appstream_StartImageBuilder_powershell_5_topic"></a>

次のコード例は、`Start-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ImageBuilder を起動します**  

```
Start-APSImageBuilder -Name TestImage
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:123456789012:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : PENDING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StartImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-APSFleet`
<a name="appstream_StopFleet_powershell_5_topic"></a>

次のコード例は、`Stop-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、フリートを停止します**  

```
Stop-APSFleet -Name PowershellFleet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StopFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-APSImageBuilder`
<a name="appstream_StopImageBuilder_powershell_5_topic"></a>

次のコード例は、`Stop-APSImageBuilder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ImageBuilder を停止します**  

```
Stop-APSImageBuilder -Name TestImage
```
**出力:**  

```
AccessEndpoints             : {}
AppstreamAgentVersion       : 06-19-2019
Arn                         : arn:aws:appstream:us-east-1:123456789012:image-builder/TestImage
CreatedTime                 : 1/14/2019 4:33:05 AM
Description                 :
DisplayName                 : TestImage
DomainJoinInfo              :
EnableDefaultInternetAccess : False
IamRoleArn                  :
ImageArn                    : arn:aws:appstream:us-east-1::image/Base-Image-Builder-05-02-2018
ImageBuilderErrors          : {}
InstanceType                : stream.standard.large
Name                        : TestImage
NetworkAccessConfiguration  : Amazon.AppStream.Model.NetworkAccessConfiguration
Platform                    : WINDOWS
State                       : STOPPING
StateChangeReason           :
VpcConfig                   : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StopImageBuilder](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-APSFleet`
<a name="appstream_DisassociateFleet_powershell_5_topic"></a>

次のコード例は、`Unregister-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スタックからフリートを登録解除します**  

```
Unregister-APSFleet -StackName TestStack -FleetName TestFleet -Region us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisassociateFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-APSUserStackBatch`
<a name="appstream_BatchDisassociateUserStack_powershell_5_topic"></a>

次のコード例は、`Unregister-APSUserStackBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、割り当てられたスタックからユーザーを削除します**  

```
Unregister-APSUserStackBatch -UserStackAssociation @{AuthenticationType="USERPOOL";SendEmailNotification=$False;StackName="PowershellStack";UserName="TestUser1@lab.com"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchDisassociateUserStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-APSDirectoryConfig`
<a name="appstream_UpdateDirectoryConfig_powershell_5_topic"></a>

次のコード例は、`Update-APSDirectoryConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream で作成されたディレクトリ設定を更新します。**  

```
Update-APSDirectoryConfig -ServiceAccountCredentials_AccountName contoso\ServiceAccount -ServiceAccountCredentials_AccountPassword MyPass@1$@# -DirectoryName contoso.com -OrganizationalUnitDistinguishedName "OU=AppStreamNew,OU=Contoso,DC=Contoso,DC=com"
```
**出力:**  

```
CreatedTime           DirectoryName OrganizationalUnitDistinguishedNames           ServiceAccountCredentials
-----------           ------------- ------------------------------------           -------------------------
12/27/2019 3:50:02 PM contoso.com   {OU=AppStreamNew,OU=Contoso,DC=Contoso,DC=com} Amazon.AppStream.Model.ServiceAccountCredentials
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateDirectoryConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-APSFleet`
<a name="appstream_UpdateFleet_powershell_5_topic"></a>

次のコード例は、`Update-APSFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、フリートのプロパティを更新します**  

```
Update-APSFleet -Name PowershellFleet -EnableDefaultInternetAccess $True -DisconnectTimeoutInSecond 950
```
**出力:**  

```
Arn                            : arn:aws:appstream:us-east-1:123456789012:fleet/PowershellFleet
ComputeCapacityStatus          : Amazon.AppStream.Model.ComputeCapacityStatus
CreatedTime                    : 4/24/2019 8:39:41 AM
Description                    : PowershellFleet
DisconnectTimeoutInSeconds     : 950
DisplayName                    : PowershellFleet
DomainJoinInfo                 :
EnableDefaultInternetAccess    : True
FleetErrors                    : {}
FleetType                      : ON_DEMAND
IamRoleArn                     :
IdleDisconnectTimeoutInSeconds : 900
ImageArn                       : arn:aws:appstream:us-east-1:123456789012:image/Powershell
ImageName                      : Powershell
InstanceType                   : stream.standard.medium
MaxUserDurationInSeconds       : 57600
Name                           : PowershellFleet
State                          : STOPPED
VpcConfig                      : Amazon.AppStream.Model.VpcConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-APSImagePermission`
<a name="appstream_UpdateImagePermissions_powershell_5_topic"></a>

次のコード例は、`Update-APSImagePermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AppStream イメージを他のアカウントと共有します**  

```
Update-APSImagePermission -Name Powershell -SharedAccountId 123456789012 -ImagePermissions_AllowFleet $True -ImagePermissions_AllowImageBuilder $True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateImagePermissions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-APSStack`
<a name="appstream_UpdateStack_powershell_5_topic"></a>

次のコード例は、`Update-APSStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スタック上のアプリケーション設定の永続化とホームフォルダを更新 (有効化) します**  

```
Update-APSStack -Name PowershellStack -ApplicationSettings_Enabled $True -ApplicationSettings_SettingsGroup PowershellStack -StorageConnector @{ConnectorType="HOMEFOLDERS"}
```
**出力:**  

```
AccessEndpoints     : {}
ApplicationSettings : Amazon.AppStream.Model.ApplicationSettingsResponse
Arn                 : arn:aws:appstream:us-east-1:123456789012:stack/PowershellStack
CreatedTime         : 4/24/2019 8:49:29 AM
Description         : PowershellStack
DisplayName         : PowershellStack
EmbedHostDomains    : {}
FeedbackURL         :
Name                : PowershellStack
RedirectURL         :
StackErrors         : {}
StorageConnectors   : {Amazon.AppStream.Model.StorageConnector, Amazon.AppStream.Model.StorageConnector}
UserSettings        : {Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting, Amazon.AppStream.Model.UserSetting}
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Aurora の例
<a name="powershell_5_aurora_code_examples"></a>

次のコード例は、Aurora で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-RDSOrderableDBInstanceOption`
<a name="aurora_DescribeOrderableDBInstanceOptions_powershell_5_topic"></a>

次のコード例は、`Get-RDSOrderableDBInstanceOption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は、 AWS リージョン内で特定の DB インスタンスクラスをサポートする DB エンジンのバージョンを一覧表示します。**  

```
$params = @{
  Engine = 'aurora-postgresql'
  DBInstanceClass = 'db.r5.large'
  Region = 'us-east-1'
}
Get-RDSOrderableDBInstanceOption @params
```
**例 2: この例は、 AWS リージョン内で特定の DB エンジンのバージョンをサポートする DB インスタンスクラスを一覧表示します。**  

```
$params = @{
  Engine = 'aurora-postgresql'
  EngineVersion = '13.6'
  Region = 'us-east-1'
}
Get-RDSOrderableDBInstanceOption @params
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Auto Scaling の例
<a name="powershell_5_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ASLoadBalancer`
<a name="auto-scaling_AttachLoadBalancers_powershell_5_topic"></a>

次のコード例は、`Add-ASLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したロードバランサーを、指定した Auto Scaling グループにアタッチします。**  

```
Add-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Complete-ASLifecycleAction`
<a name="auto-scaling_CompleteLifecycleAction_powershell_5_topic"></a>

次のコード例は、`Complete-ASLifecycleAction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したライフサイクルアクションを完了します。**  

```
Complete-ASLifecycleAction -LifecycleHookName myLifecycleHook -AutoScalingGroupName my-asg -LifecycleActionResult CONTINUE -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CompleteLifecycleAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-ASMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_powershell_5_topic"></a>

次のコード例は、`Disable-ASMetricsCollection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg -Metric @("GroupMinSize", "GroupMaxSize")
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを無効にします。**  

```
Disable-ASMetricsCollection -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Dismount-ASInstance`
<a name="auto-scaling_DetachInstances_powershell_5_topic"></a>

次のコード例は、`Dismount-ASInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループから指定したインスタンスをデタッチし、希望する容量を減らして、Auto Scaling が代替インスタンスを起動しないようにします。**  

```
Dismount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**出力:**  

```
ActivityId           : 06733445-ce94-4039-be1b-b9f1866e276e
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-93633f9b was detached in response to a user request, shrinking
                       the capacity from 2 to 1.
Description          : Detaching EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
**例 2: この例では、希望する容量を減らすことなく、指定したインスタンスを指定した Auto Scaling グループからデタッチします。Auto Scaling が代替インスタンスを起動します。**  

```
Dismount-ASInstance -InstanceId i-7bf746a2 -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**出力:**  

```
ActivityId           : f43a3cd4-d38c-4af7-9fe0-d76ec2307b6d
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:34:59Z instance i-7bf746a2 was detached in response to a user request.
Description          : Detaching EC2 instance: i-7bf746a2
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/20/2015 2:34:59 PM
StatusCode           : InProgress
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DetachInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Dismount-ASLoadBalancer`
<a name="auto-scaling_DetachLoadBalancers_powershell_5_topic"></a>

次のコード例は、`Dismount-ASLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループから指定したロードバランサーをデタッチします。**  

```
Dismount-ASLoadBalancer -LoadBalancerName my-lb -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DetachLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-ASMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_powershell_5_topic"></a>

次のコード例は、`Enable-ASMetricsCollection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection  -Metric @("GroupMinSize", "GroupMaxSize") -AutoScalingGroupName my-asg -Granularity 1Minute
```
**例 2: この例では、指定した Auto Scaling グループのすべてのメトリクスのモニタリングを有効にします。**  

```
Enable-ASMetricsCollection -AutoScalingGroupName my-asg -Granularity 1Minute
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableMetricsCollection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enter-ASStandby`
<a name="auto-scaling_EnterStandby_powershell_5_topic"></a>

次のコード例は、`Enter-ASStandby` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスをスタンバイモードにし、希望する容量を減らして、Auto Scaling が代替インスタンスを起動しないようにします。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $true
```
**出力:**  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request,
                       shrinking the capacity from 2 to 1.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
**例 2: この例では、希望する容量を減らすことなく、指定したインスタンスをスタンバイモードにします。Auto Scaling が代替インスタンスを起動します。**  

```
Enter-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg -ShouldDecrementDesiredCapacity $false
```
**出力:**  

```
ActivityId           : e36a5a54-ced6-4df8-bd19-708e2a59a649
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:48:06Z instance i-95b8484f was moved to standby in response to a user request.
Description          : Moving EC2 instance to Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 50
StartTime            : 11/22/2015 7:48:06 AM
StatusCode           : InProgress
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnterStandby](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Exit-ASStandby`
<a name="auto-scaling_ExitStandby_powershell_5_topic"></a>

次のコード例は、`Exit-ASStandby` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスをスタンバイモードから解除します。**  

```
Exit-ASStandby -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
**出力:**  

```
ActivityId           : 1833d3e8-e32f-454e-b731-0670ad4c6934
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:51:21Z instance i-95b8484f was moved out of standby in response to a user 
                       request, increasing the capacity from 1 to 2.
Description          : Moving EC2 instance out of Standby: i-95b8484f
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 30
StartTime            : 11/22/2015 7:51:21 AM
StatusCode           : PreInService
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ExitStandby](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASAccountLimit`
<a name="auto-scaling_DescribeAccountLimits_powershell_5_topic"></a>

次のコード例は、`Get-ASAccountLimit` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウントの Auto Scaling リソース制限について説明します。**  

```
Get-ASAccountLimit
```
**出力:**  

```
MaxNumberOfAutoScalingGroups    : 20
MaxNumberOfLaunchConfigurations : 100
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASAdjustmentType`
<a name="auto-scaling_DescribeAdjustmentTypes_powershell_5_topic"></a>

次のコード例は、`Get-ASAdjustmentType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされている調整タイプを記述します。**  

```
Get-ASAdjustmentType
```
**出力:**  

```
Type
----
ChangeInCapacity
ExactCapacity
PercentChangeInCapacity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAdjustmentTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASAutoScalingGroup`
<a name="auto-scaling_DescribeAutoScalingGroups_powershell_5_topic"></a>

次のコード例は、`Get-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling グループの名前を一覧表示します。**  

```
Get-ASAutoScalingGroup | format-table -property AutoScalingGroupName
```
**出力:**  

```
AutoScalingGroupName
--------------------
my-asg-1
my-asg-2
my-asg-3
my-asg-4
my-asg-5
my-asg-6
```
**例 2: この例では、指定した Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1
```
**出力:**  

```
AutoScalingGroupARN     : arn:aws:autoscaling:us-west-2:123456789012:autoScalingGroup:930d940e-891e-4781-a11a-7b0acd480
                          f03:autoScalingGroupName/my-asg-1
AutoScalingGroupName    : my-asg-1
AvailabilityZones       : {us-west-2b, us-west-2a}
CreatedTime             : 3/1/2015 9:05:31 AM
DefaultCooldown         : 300
DesiredCapacity         : 2
EnabledMetrics          : {}
HealthCheckGracePeriod  : 300
HealthCheckType         : EC2
Instances               : {my-lc}
LaunchConfigurationName : my-lc
LoadBalancerNames       : {}
MaxSize                 : 0
MinSize                 : 0
PlacementGroup          :
Status                  :
SuspendedProcesses      : {}
Tags                    : {}
TerminationPolicies     : {Default}
VPCZoneIdentifier       : subnet-e4f33493,subnet-5264e837
```
**例 3: この例では、指定した 2 つの Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup -AutoScalingGroupName @("my-asg-1", "my-asg-2")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg-1).Instances
```
**例 5: この例では、すべての Auto Scaling グループを記述します。**  

```
Get-ASAutoScalingGroup
```
**例 6: この例では、指定した Auto Scaling グループ用の起動テンプレートを記述します。この例では、[インスタンスの購入オプション] が [起動テンプレートに準拠する] に設定されていることを前提としています。このオプションが [購入オプションとインスタンスタイプを組み合わせる] に設定されている場合、LaunchTemplate には「MixedInstancesPolicy.LaunchTemplate」プロパティを使用してアクセスできます。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-ag-1).LaunchTemplate
```
**出力:**  

```
LaunchTemplateId     LaunchTemplateName   Version
----------------     ------------------   -------
lt-06095fd619cb40371 test-launch-template $Default
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASAutoScalingInstance`
<a name="auto-scaling_DescribeAutoScalingInstances_powershell_5_topic"></a>

次のコード例は、`Get-ASAutoScalingInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は、Auto Scaling インスタンスの ID を一覧表示します。**  

```
Get-ASAutoScalingInstance | format-table -property InstanceId
```
**出力:**  

```
InstanceId
----------
i-12345678
i-87654321
i-abcd1234
```
**例 2: この例では、指定した Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance -InstanceId i-12345678
```
**出力:**  

```
AutoScalingGroupName    : my-asg
AvailabilityZone        : us-west-2b
HealthStatus            : HEALTHY
InstanceId              : i-12345678
LaunchConfigurationName : my-lc
LifecycleState          : InService
```
**例 3: この例では、指定した 2 つの Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance -InstanceId @("i-12345678", "i-87654321")
```
**例 4: この例では、指定した Auto Scaling グループの Auto Scaling インスタンスを記述します。**  

```
(Get-ASAutoScalingGroup -AutoScalingGroupName my-asg).Instances | Get-ASAutoScalingInstance
```
**例 5: この例では、すべての Auto Scaling インスタンスを記述します。**  

```
Get-ASAutoScalingInstance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASAutoScalingNotificationType`
<a name="auto-scaling_DescribeAutoScalingNotificationTypes_powershell_5_topic"></a>

次のコード例は、`Get-ASAutoScalingNotificationType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされている通知タイプを一覧表示します。**  

```
Get-ASAutoScalingNotificationType
```
**出力:**  

```
autoscaling:EC2_INSTANCE_LAUNCH
autoscaling:EC2_INSTANCE_LAUNCH_ERROR
autoscaling:EC2_INSTANCE_TERMINATE
autoscaling:EC2_INSTANCE_TERMINATE_ERROR
autoscaling:TEST_NOTIFICATION
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAutoScalingNotificationTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASLaunchConfiguration`
<a name="auto-scaling_DescribeLaunchConfigurations_powershell_5_topic"></a>

次のコード例は、`Get-ASLaunchConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、起動設定の名前を一覧表示します。**  

```
Get-ASLaunchConfiguration | format-table -property LaunchConfigurationName
```
**出力:**  

```
LaunchConfigurationName
-----------------------
my-lc-1
my-lc-2
my-lc-3
my-lc-4
my-lc-5
```
**例 2: この例では、指定した起動設定を記述します。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName my-lc-1
```
**出力:**  

```
AssociatePublicIpAddress     : True
BlockDeviceMappings          : {/dev/xvda}
ClassicLinkVPCId             :
ClassicLinkVPCSecurityGroups : {}
CreatedTime                  : 12/12/2014 3:22:08 PM
EbsOptimized                 : False
IamInstanceProfile           :
ImageId                      : ami-043a5034
InstanceMonitoring           : Amazon.AutoScaling.Model.InstanceMonitoring
InstanceType                 : t2.micro
KernelId                     :
KeyName                      : 
LaunchConfigurationARN       : arn:aws:autoscaling:us-west-2:123456789012:launchConfiguration:7e5f31e4-693b-4604-9322-
                               e6f68d7fafad:launchConfigurationName/my-lc-1
LaunchConfigurationName      : my-lc-1
PlacementTenancy             :
RamdiskId                    :
SecurityGroups               : {sg-67ef0308}
SpotPrice                    :
UserData                     :
```
**例 3: この例では、指定した 2 つの起動設定を記述します。**  

```
Get-ASLaunchConfiguration -LaunchConfigurationName @("my-lc-1", "my-lc-2")
```
**例 4: この例では、すべての起動設定を記述します。**  

```
Get-ASLaunchConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLaunchConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASLifecycleHook`
<a name="auto-scaling_DescribeLifecycleHooks_powershell_5_topic"></a>

次のコード例は、`Get-ASLifecycleHook` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**出力:**  

```
AutoScalingGroupName  : my-asg
DefaultResult         : ABANDON
GlobalTimeout         : 172800
HeartbeatTimeout      : 3600
LifecycleHookName     : myLifecycleHook
LifecycleTransition   : auto-scaling:EC2_INSTANCE_LAUNCHING
NotificationMetadata  :
NotificationTargetARN : arn:aws:sns:us-west-2:123456789012:my-topic
RoleARN               : arn:aws:iam::123456789012:role/my-iam-role
```
**例 2: この例では、指定した Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook -AutoScalingGroupName my-asg
```
**例 3: この例では、すべての Auto Scaling グループのすべてのライフサイクルフックを記述します。**  

```
Get-ASLifecycleHook
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLifecycleHooks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASLifecycleHookType`
<a name="auto-scaling_DescribeLifecycleHookTypes_powershell_5_topic"></a>

次のコード例は、`Get-ASLifecycleHookType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は、Auto Scaling でサポートされているライフサイクルフックの種類を一覧表示します。**  

```
Get-ASLifecycleHookType
```
**出力:**  

```
autoscaling:EC2_INSTANCE_LAUNCHING
auto-scaling:EC2_INSTANCE_TERMINATING
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLifecycleHookTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASLoadBalancer`
<a name="auto-scaling_DescribeLoadBalancers_powershell_5_topic"></a>

次のコード例は、`Get-ASLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのロードバランサーを記述します。**  

```
Get-ASLoadBalancer -AutoScalingGroupName my-asg
```
**出力:**  

```
LoadBalancerName    State
----------------    -----
my-lb               Added
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASMetricCollectionType`
<a name="auto-scaling_DescribeMetricCollectionTypes_powershell_5_topic"></a>

次のコード例は、`Get-ASMetricCollectionType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされているメトリクスコレクションタイプを一覧表示します。**  

```
(Get-ASMetricCollectionType).Metrics
```
**出力:**  

```
Metric
------
GroupMinSize
GroupMaxSize
GroupDesiredCapacity
GroupInServiceInstances
GroupPendingInstances
GroupTerminatingInstances
GroupStandbyInstances
GroupTotalInstances
```
**例 2: この例では、対応する粒度を一覧表示します。**  

```
(Get-ASMetricCollectionType).Granularities
```
**出力:**  

```
Granularity
-----------
1Minute
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeMetricCollectionTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASNotificationConfiguration`
<a name="auto-scaling_DescribeNotificationConfigurations_powershell_5_topic"></a>

次のコード例は、`Get-ASNotificationConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
Get-ASNotificationConfiguration -AutoScalingGroupName my-asg | format-list
```
**出力:**  

```
AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_LAUNCH
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic

AutoScalingGroupName : my-asg
NotificationType     : auto-scaling:EC2_INSTANCE_TERMINATE
TopicARN             : arn:aws:sns:us-west-2:123456789012:my-topic
```
**例 2: この例では、すべての Auto Scaling グループに関連付けられている通知アクションを記述します。**  

```
Get-ASNotificationConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeNotificationConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASPolicy`
<a name="auto-scaling_DescribePolicies_powershell_5_topic"></a>

次のコード例は、`Get-ASPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのすべてのポリシーを記述します。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg
```
**出力:**  

```
AdjustmentType          : ChangeInCapacity
Alarms                  : {}
AutoScalingGroupName    : my-asg
Cooldown                : 0
EstimatedInstanceWarmup : 0
MetricAggregationType   :
MinAdjustmentMagnitude  : 0
MinAdjustmentStep       : 0
PolicyARN               : arn:aws:auto-scaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef
                          :autoScalingGroupName/my-asg:policyName/myScaleInPolicy
PolicyName              : myScaleInPolicy
PolicyType              : SimpleScaling
ScalingAdjustment       : -1
StepAdjustments         : {}
```
**例 2: この例では、指定した Auto Scaling グループの指定したポリシーを記述します。**  

```
Get-ASPolicy -AutoScalingGroupName my-asg -PolicyName @("myScaleOutPolicy", "myScaleInPolicy")
```
**例 3: この例では、すべての Auto Scaling グループのすべてのポリシーを記述します。**  

```
Get-ASPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribePolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASScalingActivity`
<a name="auto-scaling_DescribeScalingActivities_powershell_5_topic"></a>

次のコード例は、`Get-ASScalingActivity` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: こので例は、指定した Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity -AutoScalingGroupName my-asg
```
**出力:**  

```
ActivityId           : 063308ae-aa22-4a9b-94f4-9fae4EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-22T15:45:16Z a user request explicitly set group desired capacity changing the desired
                       capacity from 1 to 2.  At 2015-11-22T15:45:34Z an instance was started in response to a difference
                       between desired and actual capacity, increasing the capacity from 1 to 2.
Description          : Launching a new EC2 instance: i-26e715fc
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/22/2015 7:46:09 AM
Progress             : 100
StartTime            : 11/22/2015 7:45:35 AM
StatusCode           : Successful
StatusMessage        :

ActivityId           : ce719997-086d-4c73-a2f1-ab703EXAMPLE
AutoScalingGroupName : my-asg
Cause                : At 2015-11-20T22:57:53Z a user request created an AutoScalingGroup changing the desired capacity
                        from 0 to 1.  At 2015-11-20T22:57:58Z an instance was started in response to a difference betwe
                       en desired and actual capacity, increasing the capacity from 0 to 1.
Description          : Launching a new EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 11/20/2015 2:58:32 PM
Progress             : 100
StartTime            : 11/20/2015 2:57:59 PM
StatusCode           : Successful
StatusMessage        :
```
**例 2: この例では、指定したスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity -ActivityId "063308ae-aa22-4a9b-94f4-9fae4EXAMPLE"
```
**例 3: この例では、すべての Auto Scaling グループの過去 6 週間のスケーリングアクティビティを記述します。**  

```
Get-ASScalingActivity
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScalingActivities](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASScalingProcessType`
<a name="auto-scaling_DescribeScalingProcessTypes_powershell_5_topic"></a>

次のコード例は、`Get-ASScalingProcessType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされているプロセスタイプを一覧表示します。**  

```
Get-ASScalingProcessType
```
**出力:**  

```
ProcessName
-----------
AZRebalance
AddToLoadBalancer
AlarmNotification
HealthCheck
Launch
ReplaceUnhealthy
ScheduledActions
Terminate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScalingProcessTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASScheduledAction`
<a name="auto-scaling_DescribeScheduledActions_powershell_5_topic"></a>

次のコード例は、`Get-ASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのスケジュールされたスケーリングアクティビティを記述します。**  

```
Get-ASScheduledAction -AutoScalingGroupName my-asg
```
**出力:**  

```
AutoScalingGroupName : my-asg
DesiredCapacity      : 10
EndTime              : 
MaxSize              : 
MinSize              : 
Recurrence           :
ScheduledActionARN   : arn:aws:autoscaling:us-west-2:123456789012:scheduledUpdateGroupAction:8a4c5f24-6ec6-4306-a2dd-f7
                       2c3af3a4d6:autoScalingGroupName/my-asg:scheduledActionName/myScheduledAction
ScheduledActionName  : myScheduledAction
StartTime            : 11/30/2015 8:00:00 AM
Time                 : 11/30/2015 8:00:00 AM
```
**例 2: この例では、指定したスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction -ScheduledActionName @("myScheduledScaleOut", "myScheduledScaleIn")
```
**例 3: この例では、指定した時刻までに開始されるスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction -StartTime "2015-12-01T08:00:00Z"
```
**例 4: この例では、指定した時刻までに終了するスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction -EndTime "2015-12-30T08:00:00Z"
```
**例 5: この例では、すべての Auto Scaling グループのスケジュールされたスケーリングアクションを記述します。**  

```
Get-ASScheduledAction
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScheduledActions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASTag`
<a name="auto-scaling_DescribeTags_powershell_5_topic"></a>

次のコード例は、`Get-ASTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、キー値が「myTag」または「myTag2」のタグを記述します。フィルター名に使用できる値は、「auto-scaling-group」、「key」、「value」、および「propagate-at-launch」です。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-ASTag -Filter @( @{ Name="key"; Values=@("myTag", "myTag2") } )
```
**出力:**  

```
Key               : myTag2
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue2

Key               : myTag
PropagateAtLaunch : True
ResourceId        : my-asg
ResourceType      : auto-scaling-group
Value             : myTagValue
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してフィルターパラメータのフィルターを作成する必要があります。**  

```
$keys = New-Object string[] 2
$keys[0] = "myTag"
$keys[1] = "myTag2"
$filter = New-Object Amazon.AutoScaling.Model.Filter
$filter.Name = "key"
$filter.Values = $keys
Get-ASTag -Filter @( $filter )
```
**例 3: この例では、すべての Auto Scaling グループのすべてのタグを記述します。**  

```
Get-ASTag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ASTerminationPolicyType`
<a name="auto-scaling_DescribeTerminationPolicyTypes_powershell_5_topic"></a>

次のコード例は、`Get-ASTerminationPolicyType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Auto Scaling でサポートされている終了ポリシーを一覧表示します。**  

```
Get-ASTerminationPolicyType
```
**出力:**  

```
ClosestToNextInstanceHour
Default
NewestInstance
OldestInstance
OldestLaunchConfiguration
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeTerminationPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Mount-ASInstance`
<a name="auto-scaling_AttachInstances_powershell_5_topic"></a>

次のコード例は、`Mount-ASInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスを、指定した Auto Scaling グループにアタッチします。Auto Scaling は、Auto Scaling グループの希望する容量を自動的に増やします。**  

```
Mount-ASInstance -InstanceId i-93633f9b -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ASAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_powershell_5_topic"></a>

次のコード例は、`New-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した名前と属性で Auto Scaling グループを作成します。デフォルトの希望する容量は最小サイズになります。したがって、この Auto Scaling グループは、指定した 2 つのアベイラビリティーゾーンのそれぞれに 1 つずつ、合計 2 つのインスタンスを起動します。**  

```
New-ASAutoScalingGroup -AutoScalingGroupName my-asg -LaunchConfigurationName my-lc -MinSize 2 -MaxSize 6 -AvailabilityZone @("us-west-2a", "us-west-2b")
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ASLaunchConfiguration`
<a name="auto-scaling_CreateLaunchConfiguration_powershell_5_topic"></a>

次のコード例は、`New-ASLaunchConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「my-lc」という名前の起動設定を作成します。この起動設定を使用する Auto Scaling グループによって起動された EC2 インスタンスは、指定されたインスタンスタイプ、AMI、セキュリティグループ、および IAM ロールを使用します。**  

```
New-ASLaunchConfiguration -LaunchConfigurationName my-lc -InstanceType "m3.medium" -ImageId "ami-12345678" -SecurityGroup "sg-12345678" -IamInstanceProfile "myIamRole"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ASAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_powershell_5_topic"></a>

次のコード例は、`Remove-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに実行中のインスタンスがない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASAutoScalingGroup (DeleteAutoScalingGroup)" on Target "my-asg".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -Force
```
**例 3: この例では、指定した Auto Scaling グループを削除し、そのグループに含まれる実行中のインスタンスをすべて終了します。**  

```
Remove-ASAutoScalingGroup -AutoScalingGroupName my-asg -ForceDelete $true -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ASLaunchConfiguration`
<a name="auto-scaling_DeleteLaunchConfiguration_powershell_5_topic"></a>

次のコード例は、`Remove-ASLaunchConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した起動設定が Auto Scaling グループにアタッチされていない場合、そのグループを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLaunchConfiguration (DeleteLaunchConfiguration)" on Target "my-lc".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASLaunchConfiguration -LaunchConfigurationName my-lc -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteLaunchConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ASLifecycleHook`
<a name="auto-scaling_DeleteLifecycleHook_powershell_5_topic"></a>

次のコード例は、`Remove-ASLifecycleHook` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したライフサイクルフックを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASLifecycleHook (DeleteLifecycleHook)" on Target "myLifecycleHook".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ASNotificationConfiguration`
<a name="auto-scaling_DeleteNotificationConfiguration_powershell_5_topic"></a>

次のコード例は、`Remove-ASNotificationConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した通知アクションを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASNotificationConfiguration (DeleteNotificationConfiguration)" on Target
"arn:aws:sns:us-west-2:123456789012:my-topic".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASNotificationConfiguration -AutoScalingGroupName my-asg -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic" -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ASPolicy`
<a name="auto-scaling_DeletePolicy_powershell_5_topic"></a>

次のコード例は、`Remove-ASPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASPolicy (DeletePolicy)" on Target "myScaleInPolicy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASPolicy -AutoScalingGroupName my-asg -PolicyName myScaleInPolicy -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ASScheduledAction`
<a name="auto-scaling_DeleteScheduledAction_powershell_5_topic"></a>

次のコード例は、`Remove-ASScheduledAction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したスケジュールされたアクションを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ASScheduledAction (DeleteScheduledAction)" on Target "myScheduledAction".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASScheduledAction -AutoScalingGroupName my-asg -ScheduledAction "myScheduledAction" -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteScheduledAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ASTag`
<a name="auto-scaling_DeleteTags_powershell_5_topic"></a>

次のコード例は、`Remove-ASTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループから指定したタグを削除します。操作を続行する前に確認画面が表示されます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } )
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ASTag (DeleteTags)" on target "Amazon.AutoScaling.Model.Tag".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: Force パラメータを指定すると、操作を続行する前に確認を求めるプロンプトが表示されません。**  

```
Remove-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag" } ) -Force
```
**例 3: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg"
$tag.Key = "myTag"
Remove-ASTag -Tag $tag -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Resume-ASProcess`
<a name="auto-scaling_ResumeProcesses_powershell_5_topic"></a>

次のコード例は、`Resume-ASProcess` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループの中断されたすべての Auto Scaling プロセスを再開します。**  

```
Resume-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResumeProcesses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-ASDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_powershell_5_topic"></a>

次のコード例は、`Set-ASDesiredCapacity` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループのサイズを設定します。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2
```
**例 2: この例では、指定した Auto Scaling グループのサイズを設定し、クールダウン期間が完了するまで待ってから、新しいサイズにスケールします。**  

```
Set-ASDesiredCapacity -AutoScalingGroupName my-asg -DesiredCapacity 2 -HonorCooldown $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SetDesiredCapacity](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-ASInstanceHealth`
<a name="auto-scaling_SetInstanceHealth_powershell_5_topic"></a>

次のコード例は、`Set-ASInstanceHealth` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスのステータスを「Unhealthy」に設定し、使用を中止します。Auto Scaling はインスタンスを終了して置き換えます。**  

```
Set-ASInstanceHealth -HealthStatus Unhealthy -InstanceId i-93633f9b
```
**例 2: この例では、指定したインスタンスのステータスを「Healthy」に設定し、そのまま稼働させます。Auto Scaling グループのヘルスチェック猶予期間は無視されます。**  

```
Set-ASInstanceHealth -HealthStatus Healthy -InstanceId i-93633f9b -ShouldRespectGracePeriod $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SetInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-ASInstanceProtection`
<a name="auto-scaling_SetInstanceProtection_powershell_5_topic"></a>

次のコード例は、`Set-ASInstanceProtection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスのインスタンス保護を有効にします。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $true
```
**例 2: この例では、指定したインスタンスのインスタンス保護を無効にします。**  

```
Set-ASInstanceProtection -AutoScalingGroupName my-asg -InstanceId i-12345678 -ProtectedFromScaleIn $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SetInstanceProtection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-ASTag`
<a name="auto-scaling_CreateOrUpdateTags_powershell_5_topic"></a>

次のコード例は、`Set-ASTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに単一のタグを追加します。タグキーは「myTag」で、タグ値は「myTagValue」です。Auto Scaling は、このタグを Auto Scaling グループによって起動された後続の EC2 インスタンスに伝播します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Set-ASTag -Tag @( @{ResourceType="auto-scaling-group"; ResourceId="my-asg"; Key="myTag"; Value="myTagValue"; PropagateAtLaunch=$true} )
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.AutoScaling.Model.Tag
$tag.ResourceType = "auto-scaling-group"
$tag.ResourceId = "my-asg" 
$tag.Key = "myTag" 
$tag.Value = "myTagValue"
$tag.PropagateAtLaunch = $true
Set-ASTag -Tag $tag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)*の「[CreateOrUpdateTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-ASPolicy`
<a name="auto-scaling_ExecutePolicy_powershell_5_topic"></a>

次のコード例は、`Start-ASPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy"
```
**例 2: この例では、クールダウン期間が完了するまで待機した後、指定した Auto Scaling グループの指定したポリシーを実行します。**  

```
Start-ASPolicy -AutoScalingGroupName my-asg -PolicyName "myScaleInPolicy" -HonorCooldown $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ExecutePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-ASInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_powershell_5_topic"></a>

次のコード例は、`Stop-ASInstanceInAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスを終了し、Auto Scaling グループの希望する容量を減らして、Auto Scaling が代替インスタンスを起動しないようにします。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $true
```
**出力:**  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request, shrinking the capacity from 2 to 1.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
**例 2: この例では、Auto Scaling グループの希望する容量を減らすことなく、指定したインスタンスを終了します。Auto Scaling が代替インスタンスを起動します。**  

```
Stop-ASInstanceInAutoScalingGroup -InstanceId i-93633f9b -ShouldDecrementDesiredCapacity $false
```
**出力:**  

```
ActivityId           : 2e40d9bd-1902-444c-abf3-6ea0002efdc5
AutoScalingGroupName :
Cause                : At 2015-11-22T16:09:03Z instance i-93633f9b was taken out of service in response to a user 
                       request.
Description          : Terminating EC2 instance: i-93633f9b
Details              : {"Availability Zone":"us-west-2b","Subnet ID":"subnet-5264e837"}
EndTime              : 
Progress             : 0
StartTime            : 11/22/2015 8:09:03 AM
StatusCode           : InProgress
StatusMessage        :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Suspend-ASProcess`
<a name="auto-scaling_SuspendProcesses_powershell_5_topic"></a>

次のコード例は、`Suspend-ASProcess` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの指定した Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg -ScalingProcess "AlarmNotification"
```
**例 2: この例では、指定した Auto Scaling グループのすべての Auto Scaling プロセスを中断します。**  

```
Suspend-ASProcess -AutoScalingGroupName my-asg
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SuspendProcesses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-ASAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_powershell_5_topic"></a>

次のコード例は、`Update-ASAutoScalingGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループの最小サイズと最大サイズを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -MaxSize 5 -MinSize 1
```
**例 2: この例では、指定した Auto Scaling グループのデフォルトのクールダウン期間を更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -DefaultCooldown 10
```
**例 3: この例では、指定した Auto Scaling グループのアベイラビリティーゾーンを更新します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -AvailabilityZone @("us-west-2a", "us-west-2b")
```
**例 4: この例では、指定した Auto Scaling グループを更新して、Elastic Load Balancing のヘルスチェックを使用します。**  

```
Update-ASAutoScalingGroup -AutoScalingGroupName my-asg -HealthCheckType ELB -HealthCheckGracePeriod 60
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-ASLifecycleActionHeartbeat`
<a name="auto-scaling_RecordLifecycleActionHeartbeat_powershell_5_topic"></a>

次のコード例は、`Write-ASLifecycleActionHeartbeat` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したライフサイクルアクションのハートビートを記録します。これにより、カスタムアクションが完了するまでインスタンスは保留中の状態になります。**  

```
Write-ASLifecycleActionHeartbeat -AutoScalingGroupName my-asg -LifecycleHookName myLifecycleHook -LifecycleActionToken bcd2f1b8-9a78-44d3-8a7a-4dd07d7cf635
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RecordLifecycleActionHeartbeat](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-ASLifecycleHook`
<a name="auto-scaling_PutLifecycleHook_powershell_5_topic"></a>

次のコード例は、`Write-ASLifecycleHook` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したライフサイクルフックを、指定した Auto Scaling グループに追加します。**  

```
Write-ASLifecycleHook -AutoScalingGroupName my-asg -LifecycleHookName "myLifecycleHook" -LifecycleTransition "autoscaling:EC2_INSTANCE_LAUNCHING" -NotificationTargetARN "arn:aws:sns:us-west-2:123456789012:my-sns-topic" -RoleARN "arn:aws:iam::123456789012:role/my-iam-role"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutLifecycleHook](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-ASNotificationConfiguration`
<a name="auto-scaling_PutNotificationConfiguration_powershell_5_topic"></a>

次のコード例は、`Write-ASNotificationConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループが、EC2 インスタンスの起動時に指定した SNS トピックに通知を送信するように設定します。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType "autoscaling:EC2_INSTANCE_LAUNCH" -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
**例 2: この例では、指定した Auto Scaling グループが、EC2 インスタンスの起動または終了時に、指定した SNS トピックに通知を送信するように設定します。**  

```
Write-ASNotificationConfiguration -AutoScalingGroupName my-asg -NotificationType @("autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_TERMINATE") -TopicARN "arn:aws:sns:us-west-2:123456789012:my-topic"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutNotificationConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-ASScalingPolicy`
<a name="auto-scaling_PutScalingPolicy_powershell_5_topic"></a>

次のコード例は、`Write-ASScalingPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Auto Scaling グループに指定したポリシーを追加します。指定した調整タイプによって、ScalingAdjustment パラメータの解釈方法が決まります。「ChangeInCapacity」では、正の値を指定すると、指定したインスタンス数だけ容量が増え、負の値を指定すると、指定したインスタンス数だけ容量が減ります。**  

```
Write-ASScalingPolicy -AutoScalingGroupName my-asg -AdjustmentType "ChangeInCapacity" -PolicyName "myScaleInPolicy" -ScalingAdjustment -1
```
**出力:**  

```
arn:aws:autoscaling:us-west-2:123456789012:scalingPolicy:aa3836ab-5462-42c7-adab-e1d769fc24ef:autoScalingGroupName/my-asg
:policyName/myScaleInPolicy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutScalingPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-ASScheduledUpdateGroupAction`
<a name="auto-scaling_PutScheduledUpdateGroupAction_powershell_5_topic"></a>

次のコード例は、`Write-ASScheduledUpdateGroupAction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、1 回限りのスケジュールされたアクションを作成または更新して、指定した開始時刻に希望する容量を変更します。**  

```
Write-ASScheduledUpdateGroupAction -AutoScalingGroupName my-asg -ScheduledActionName "myScheduledAction" -StartTime "2015-12-01T00:00:00Z" -DesiredCapacity 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutScheduledUpdateGroupAction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# AWS Budgets Tools for PowerShell V5 を使用した の例
<a name="powershell_5_budgets_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Budgets。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-BGTBudget`
<a name="budgets_CreateBudget_powershell_5_topic"></a>

次のコード例は、`New-BGTBudget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された予算と時間の制約を持つ新しい予算を作成し、E メール通知を設定します。**  

```
$notification = @{
    NotificationType = "ACTUAL"
    ComparisonOperator = "GREATER_THAN"
    Threshold = 80
}

$addressObject = @{
    Address = @("user@domain.com")
    SubscriptionType = "EMAIL"
}

$subscriber = New-Object Amazon.Budgets.Model.NotificationWithSubscribers
$subscriber.Notification = $notification
$subscriber.Subscribers.Add($addressObject)

$startDate = [datetime]::new(2017,09,25)
$endDate = [datetime]::new(2017,10,25)

New-BGTBudget -Budget_BudgetName "Tester" -Budget_BudgetType COST -CostTypes_IncludeTax $true -Budget_TimeUnit MONTHLY -BudgetLimit_Unit USD -TimePeriod_Start $startDate -TimePeriod_End $endDate -AccountId 123456789012 -BudgetLimit_Amount 200 -NotificationsWithSubscriber $subscriber
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateBudget](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# AWS Cloud9 Tools for PowerShell V5 を使用した の例
<a name="powershell_5_cloud9_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Cloud9。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-C9EnvironmentData`
<a name="cloud9_DescribeEnvironments_powershell_5_topic"></a>

次のコード例は、`Get-C9EnvironmentData` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AWS Cloud9 開発環境に関する情報を取得します。**  

```
Get-C9EnvironmentData -EnvironmentId 685f892f431b45c2b28cb69eadcdb0EX,1980b80e5f584920801c09086667f0EX
```
**出力:**  

```
Arn         : arn:aws:cloud9:us-east-1:123456789012:environment:685f892f431b45c2b28cb69eadcdb0EX
Description : Created from CodeStar.
Id          : 685f892f431b45c2b28cb69eadcdb0EX
Lifecycle   : Amazon.Cloud9.Model.EnvironmentLifecycle
Name        : my-demo-ec2-env
OwnerArn    : arn:aws:iam::123456789012:user/MyDemoUser
Type        : ec2

Arn         : arn:aws:cloud9:us-east-1:123456789012:environment:1980b80e5f584920801c09086667f0EX
Description :
Id          : 1980b80e5f584920801c09086667f0EX
Lifecycle   : Amazon.Cloud9.Model.EnvironmentLifecycle
Name        : my-demo-ssh-env
OwnerArn    : arn:aws:iam::123456789012:user/MyDemoUser
Type        : ssh
```
**例 2: この例では、指定された AWS Cloud9 開発環境のライフサイクルステータスに関する情報を取得します。**  

```
(Get-C9EnvironmentData -EnvironmentId 685f892f431b45c2b28cb69eadcdb0EX).Lifecycle
```
**出力:**  

```
FailureResource Reason Status
--------------- ------ ------
                       CREATED
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeEnvironments](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-C9EnvironmentList`
<a name="cloud9_ListEnvironments_powershell_5_topic"></a>

次のコード例は、`Get-C9EnvironmentList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、使用可能な AWS Cloud9 開発環境識別子のリストを取得します。**  

```
Get-C9EnvironmentList
```
**出力:**  

```
685f892f431b45c2b28cb69eadcdb0EX
1980b80e5f584920801c09086667f0EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListEnvironments](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-C9EnvironmentMembershipList`
<a name="cloud9_DescribeEnvironmentMemberships_powershell_5_topic"></a>

次のコード例は、`Get-C9EnvironmentMembershipList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AWS Cloud9 開発環境の環境メンバーに関する情報を取得します。**  

```
Get-C9EnvironmentMembershipList -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-write
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX

EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
**例 2: この例では、指定された AWS Cloud9 開発環境の所有者に関する情報を取得します。**  

```
Get-C9EnvironmentMembershipList -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission owner
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
**例 3: この例では、multiple AWS Cloud9 開発環境の指定された環境メンバーに関する情報を取得します。**  

```
Get-C9EnvironmentMembershipList -UserArn arn:aws:iam::123456789012:user/MyDemoUser
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/17/2018 7:48:14 PM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX

EnvironmentId : 1980b80e5f584920801c09086667f0EX
LastAccess    : 1/16/2018 11:21:24 PM
Permissions   : owner
UserArn       : arn:aws:iam::123456789012:user/MyDemoUser
UserId        : AIDAJ3LOROMOUXTBSU6EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeEnvironmentMemberships](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-C9EnvironmentStatus`
<a name="cloud9_DescribeEnvironmentStatus_powershell_5_topic"></a>

次のコード例は、`Get-C9EnvironmentStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AWS Cloud9 開発環境のステータス情報を取得します。**  

```
Get-C9EnvironmentStatus -EnvironmentId 349c86d4579e4e7298d500ff57a6b2EX
```
**出力:**  

```
Message                     Status
-------                     ------
Environment is ready to use ready
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeEnvironmentStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-C9EnvironmentEC2`
<a name="cloud9_CreateEnvironmentEc2_powershell_5_topic"></a>

次のコード例は、`New-C9EnvironmentEC2` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された設定で AWS Cloud9 開発環境を作成し、Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを起動してから、インスタンスから環境に接続します。**  

```
New-C9EnvironmentEC2 -Name my-demo-env -AutomaticStopTimeMinutes 60 -Description "My demonstration development environment." -InstanceType t2.micro -OwnerArn arn:aws:iam::123456789012:user/MyDemoUser -SubnetId subnet-d43a46EX
```
**出力:**  

```
ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateEnvironmentEc2](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-C9EnvironmentMembership`
<a name="cloud9_CreateEnvironmentMembership_powershell_5_topic"></a>

次のコード例は、`New-C9EnvironmentMembership` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された環境メンバーを指定された AWS Cloud9 開発環境に追加します。**  

```
New-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission read-write
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-write
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-C9Environment`
<a name="cloud9_DeleteEnvironment_powershell_5_topic"></a>

次のコード例は、`Remove-C9Environment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AWS Cloud9 開発環境を削除します。環境が Amazon EC2 インスタンスに接続されている場合、インスタンスも終了します。**  

```
Remove-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteEnvironment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-C9EnvironmentMembership`
<a name="cloud9_DeleteEnvironmentMembership_powershell_5_topic"></a>

次のコード例は、`Remove-C9EnvironmentMembership` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AWS Cloud9 開発環境から指定された環境メンバーを削除します。**  

```
Remove-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-C9Environment`
<a name="cloud9_UpdateEnvironment_powershell_5_topic"></a>

次のコード例は、`Update-C9Environment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された既存の AWS Cloud9 開発環境の指定された設定を変更します。**  

```
Update-C9Environment -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Description "My changed demonstration development environment." -Name my-changed-demo-env
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateEnvironment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-C9EnvironmentMembership`
<a name="cloud9_UpdateEnvironmentMembership_powershell_5_topic"></a>

次のコード例は、`Update-C9EnvironmentMembership` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AWS Cloud9 開発環境の指定された既存の環境メンバーの設定を変更します。**  

```
Update-C9EnvironmentMembership -UserArn arn:aws:iam::123456789012:user/AnotherDemoUser -EnvironmentId ffd88420d4824eeeaeaa8a04bfde8cEX -Permission read-only
```
**出力:**  

```
EnvironmentId : ffd88420d4824eeeaeaa8a04bfde8cEX
LastAccess    : 1/1/0001 12:00:00 AM
Permissions   : read-only
UserArn       : arn:aws:iam::123456789012:user/AnotherDemoUser
UserId        : AIDAJ3BA6O2FMJWCWXHEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateEnvironmentMembership](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# CloudFormation Tools for PowerShell V5 を使用した の例
<a name="powershell_5_cloudformation_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています CloudFormation。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CFNStack`
<a name="cloudformation_DescribeStacks_powershell_5_topic"></a>

次のコード例は、`Get-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ユーザーのスタックのすべてを記述するスタックインスタンスのコレクションを返します。**  

```
Get-CFNStack
```
**例 2: 指定されたスタックを記述するスタックインスタンスを返します。**  

```
Get-CFNStack -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFNStackEvent`
<a name="cloudformation_DescribeStackEvents_powershell_5_topic"></a>

次のコード例は、`Get-CFNStackEvent` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたスタックに関するすべてのスタック関連イベントを返します。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DescribeStackEvents](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFNStackResource`
<a name="cloudformation_DescribeStackResource_powershell_5_topic"></a>

次のコード例は、`Get-CFNStackResource` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 論理 ID「MyDBInstance」を使用して、指定されたスタックに関連付けられているテンプレートで識別されたリソースの説明を返します。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DescribeStackResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFNStackResourceList`
<a name="cloudformation_DescribeStackResources_powershell_5_topic"></a>

次のコード例は、`Get-CFNStackResourceList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたスタックに関連付けられた最大 100 個の AWS リソースのリソースの説明を返します。スタックに関連付けられているすべてのリソースの詳細情報を取得するには、Get-CFNStackResourceSummary を使用します。これは、結果の手動ページングもサポートしています。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**例 2: 論理 ID「Ec2Instance」を使用して、指定されたスタックに関連付けられているテンプレートで識別された Amazon EC2 インスタンスの説明を返します。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**例 3: インスタンス ID「i-123456」で識別される Amazon EC2 インスタンスが含まれるスタックに関連付けられた、最大 100 個のリソースの説明を返します。スタックに関連付けられているすべてのリソースの詳細情報を取得するには、Get-CFNStackResourceSummary を使用します。これは、結果の手動ページングもサポートしています。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456"
```
**例 4: スタックのテンプレートで論理 ID「Ec2Instance」によって識別される Amazon EC2 インスタンスの説明を返します。スタックは、スタックに含まれるリソースの物理リソース ID を使用して識別され、この場合はインスタンス ID が「i-123456」の Amazon EC2 インスタンスも含まれます。テンプレートのコンテンツによっては、スタックの識別に異なる物理リソース (Amazon S3 バケットなど) を使用することもできます。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456" -LogicalResourceId "Ec2Instance"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DescribeStackResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFNStackResourceSummary`
<a name="cloudformation_ListStackResources_powershell_5_topic"></a>

次のコード例は、`Get-CFNStackResourceSummary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたスタックに関連付けられているすべてのリソースの説明を返します。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[ListStackResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFNStackSummary`
<a name="cloudformation_ListStacks_powershell_5_topic"></a>

次のコード例は、`Get-CFNStackSummary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべてのスタックの概要情報を返します。**  

```
Get-CFNStackSummary
```
**例 2: 現在作成中のすべてのスタックの概要情報を返します。**  

```
Get-CFNStackSummary -StackStatusFilter "CREATE_IN_PROGRESS"
```
**例 3: 現在作成中または更新中のすべてのスタックの概要情報を返します。**  

```
Get-CFNStackSummary -StackStatusFilter @("CREATE_IN_PROGRESS", "UPDATE_IN_PROGRESS")
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[ListStacks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFNTemplate`
<a name="cloudformation_GetTemplate_powershell_5_topic"></a>

次のコード例は、`Get-CFNTemplate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたスタックに関連付けられているテンプレートを返します。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[GetTemplate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Measure-CFNTemplateCost`
<a name="cloudformation_EstimateTemplateCost_powershell_5_topic"></a>

次のコード例は、`Measure-CFNTemplateCost` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: テンプレートの実行に必要なリソースを記述するクエリ文字列を含む AWS Simple Monthly Calculator URL を返します。テンプレートは指定された Amazon S3 URL から取得され、単一のカスタマイゼーションパラメータが適用されます。パラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Measure-CFNTemplateCost -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                        -Region us-west-1 `
                        -Parameter @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" }
```
**例 2: テンプレートの実行に必要なリソースを記述するクエリ文字列を含む AWS Simple Monthly Calculator URL を返します。テンプレートは提供されたコンテンツから解析され、カスタマイゼーションパラメータが適用されます (この例は、テンプレートコンテンツが「KeyName」と「InstanceType」の 2 つのパラメータを宣言していることを前提としています)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**例 3: New-Object を使用してテンプレートパラメータのセットを構築し、テンプレートの実行に必要なリソースを記述するクエリ文字列を含む AWS Simple Monthly Calculator URL を返します。テンプレートは、カスタマイゼーションパラメータを使用して、提供されたコンテンツから解析されます (この例は、テンプレートコンテンツが「KeyName」と「InstanceType」の 2 つのパラメータを宣言していることを前提としています)。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "KeyName"
$p1.ParameterValue = "myKeyPairName"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "InstanceType"
$p2.ParameterValue = "m1.large"

Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" -Parameter @( $p1, $p2 )
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CFNStack`
<a name="cloudformation_CreateStack_powershell_5_topic"></a>

次のコード例は、`New-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、提供されたコンテンツから解析されます (「PK1」と「PK2」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」と「PV2」はこれらのパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗しても、スタックはロールバックされません。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" }) `
             -DisableRollback $true
```
**例 2: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、提供されたコンテンツから解析されます (「PK1」と「PK2」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」と「PV2」はこれらのパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗すると、スタックがロールバックされます。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "PK1"
$p1.ParameterValue = "PV1"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "PK2"
$p2.ParameterValue = "PV2"

New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( $p1, $p2 ) `
             -OnFailure "ROLLBACK"
```
**例 3: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、Amazon S3 URL から取得されます (「PK1」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」はパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗すると、スタックがロールバックされます (-DisableRollback \$1false を指定する場合と同じです)**。  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**例 4: 指定された名前を使用して新しいスタックを作成します。テンプレートは、カスタマイゼーションパラメータを使用して、Amazon S3 URL から取得されます (「PK1」はテンプレートコンテンツで宣言されたパラメータの名前を表し、「PV1」はパラメータの値を表します)。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。スタックの作成に失敗すると、スタックがロールバックされます (-DisableRollback \$1false を指定する場合と同じです)。指定された通知 AEN は、公開されたスタック関連のイベントを受け取ります。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" } `
             -NotificationARN @( "arn1", "arn2" )
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CFNStack`
<a name="cloudformation_DeleteStack_powershell_5_topic"></a>

次のコード例は、`Remove-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたスタックを削除します。**  

```
Remove-CFNStack -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Resume-CFNUpdateRollback`
<a name="cloudformation_ContinueUpdateRollback_powershell_5_topic"></a>

次のコード例は、`Resume-CFNUpdateRollback` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたスタックのロールバックを続行します。このスタックの状態は「UPDATE\$1ROLLBACK\$1FAILED」になっている必要があります。続行されたロールバックが成功すると、スタックの状態が「UPDATE\$1ROLLBACK\$1COMPLETE」になります。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-CFNUpdateStack`
<a name="cloudformation_CancelUpdateStack_powershell_5_topic"></a>

次のコード例は、`Stop-CFNUpdateStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたスタックで行われている更新をキャンセルします。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[CancelUpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Test-CFNStack`
<a name="cloudformation_Test-CFNStack_powershell_5_topic"></a>

次のコード例は、`Test-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: スタックが UPDATE\$1ROLLBACK\$1COMPLETE、CREATE\$1COMPLETE、ROLLBACK\$1COMPLETE、または UPDATE\$1COMPLETE のいずれかの状態に達したかどうかをテストします。**  

```
Test-CFNStack -StackName MyStack
```
**出力:**  

```
False
```
**例 2: スタックが UPDATE\$1COMPLETE または UPDATE\$1ROLLBACK\$1COMPLETE のいずれかの状態に達したかどうかをテストします。**  

```
Test-CFNStack -StackName MyStack -Status UPDATE_COMPLETE,UPDATE_ROLLBACK_COMPLETE
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Test-CFNStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Test-CFNTemplate`
<a name="cloudformation_ValidateTemplate_powershell_5_topic"></a>

次のコード例は、`Test-CFNTemplate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたテンプレートコンテンツを検証します。出力は、テンプレートの機能、説明、パラメータを詳しく説明します。**  

```
Test-CFNTemplate -TemplateBody "{TEMPLATE CONTENT HERE}"
```
**例 2: Amazon S3 URL 経由でアクセスされる、指定されたテンプレートを検証します。出力は、テンプレートの機能、説明、パラメータを詳しく説明します。**  

```
Test-CFNTemplate -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[ValidateTemplate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CFNStack`
<a name="cloudformation_UpdateStack_powershell_5_topic"></a>

次のコード例は、`Update-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたテンプレートとカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」はテンプレートで宣言されているパラメータの名前を表し、「PV1」はその値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**例 2: 指定されたテンプレートとカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」と「PK2」はテンプレートで宣言されているパラメータの名前を表し、「PV1」と「PV2」はそれらの要求された値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**例 3: 指定されたテンプレートとカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」はテンプレートで宣言されているパラメータの名前を表し、「PV2」はその値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**例 4: 指定されたテンプレート (Amazon S3 から取得されたもの) とカスタマイゼーションパラメータでスタック「MyStack」を更新します。「PK1」と「PK2」はテンプレートで宣言されているパラメータの名前を表し、「PV1」と「PV2」はそれらの要求された値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**例 5: 指定されたテンプレート (Amazon S3 から取得されたもの) とカスタマイゼーションパラメータでスタック「MyStack」(この例では IAM リソースが含まれていることを想定) を更新します。「PK1」と「PK2」はテンプレートで宣言されているパラメータの名前を表し、「PV1」と「PV2」はそれらの要求された値を表します。カスタマイゼーションパラメータは、「ParameterKey」と「ParameterValue」の代わりに、「Key」と「Value」を使用して指定することもできます。IAM リソースが含まれるスタックでは、-Capabilities「CAPABILITY\$1IAM」パラメータを指定する必要があります。指定されていない場合は、更新が「InsufficientCapabilities」エラーで失敗します。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } ) `
                -Capabilities "CAPABILITY_IAM"
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Wait-CFNStack`
<a name="cloudformation_Wait-CFNStack_powershell_5_topic"></a>

次のコード例は、`Wait-CFNStack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: スタックが UPDATE\$1ROLLBACK\$1COMPLETE、CREATE\$1COMPLETE、ROLLBACK\$1COMPLETE、または UPDATE\$1COMPLETE のいずれかの状態に達したかどうかをテストします。スタックがいずれかの状態にも達していない場合、コマンドは 2 秒間スリープしてから再度ステータスをテストします。これは、スタックがリクエストされた状態のいずれかに達するか、デフォルトのタイムアウト期間である 60 秒を経過するまで繰り返されます。タイムアウト期間を超えると、例外がスローされます。スタックがタイムアウト期間内にリクエストされた状態のいずれかに達すると、パイプラインに返されます。**  

```
$stack = Wait-CFNStack -StackName MyStack
```
**例 2: この例では、スタックが指定の状態のいずれかに達するまで合計 5 分 (300 秒) 待機します。この例では、タイムアウトの前にいずれかの状態に達しているため、スタックオブジェクトはパイプラインに返されます。**  

```
Wait-CFNStack -StackName MyStack -Timeout 300 -Status CREATE_COMPLETE,ROLLBACK_COMPLETE
```
**出力:**  

```
Capabilities      : {CAPABILITY_IAM}
ChangeSetId       :
CreationTime      : 6/1/2017 9:29:33 AM
Description       : AWS CloudFormation Sample Template ec2_instance_with_instance_profile: Create an EC2 instance with an associated instance profile. **WARNING** This template creates one or more Amazon EC2
                    instances and an Amazon SQS queue. You will be billed for the AWS resources used if you create a stack from this template.
DisableRollback   : False
LastUpdatedTime   : 1/1/0001 12:00:00 AM
NotificationARNs  : {}
Outputs           : {}
Parameters        : {}
RoleARN           :
StackId           : arn:aws:cloudformation:us-west-2:123456789012:stack/MyStack/7ea87b50-46e7-11e7-9c9b-503a90a9c4d1
StackName         : MyStack
StackStatus       : CREATE_COMPLETE
StackStatusReason :
Tags              : {}
TimeoutInMinutes  : 0
```
**例 3: この例では、スタックがタイムアウト期間 (この場合はデフォルト期間 60 秒) 内にリクエストされた状態のいずれかに達しなかった場合のエラー出力を示します。**  

```
Wait-CFNStack -StackName MyStack -Status CREATE_COMPLETE,ROLLBACK_COMPLETE
```
**出力:**  

```
Wait-CFNStack : Timed out after 60 seconds waiting for CloudFormation stack MyStack in region us-west-2 to reach one of state(s): UPDATE_ROLLBACK_COMPLETE,CREATE_COMPLETE,ROLLBACK_COMPLETE,UPDATE_COMPLETE
At line:1 char:1
+ Wait-CFNStack -StackName MyStack -State CREATE_COMPLETE,ROLLBACK_COMPLETE
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (Amazon.PowerShe...tCFNStackCmdlet:WaitCFNStackCmdlet) [Wait-CFNStack], InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Amazon.PowerShell.Cmdlets.CFN.WaitCFNStackCmdlet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Wait-CFNStack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した CloudFront の例
<a name="powershell_5_cloudfront_code_examples"></a>

次のコード例は、CloudFront で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CFCloudFrontOriginAccessIdentity`
<a name="cloudfront_GetCloudFrontOriginAccessIdentity_powershell_5_topic"></a>

次のコード例は、`Get-CFCloudFrontOriginAccessIdentity` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、-Id パラメータで指定した、特定の Amazon CloudFront オリジンアクセスアイデンティティを返します。-Id パラメータは必須ではありませんが、指定しないと、結果は返されません。**  

```
Get-CFCloudFrontOriginAccessIdentity -Id E3XXXXXXXXXXRT
```
**出力:**  

```
      CloudFrontOriginAccessIdentityConfig    Id                                      S3CanonicalUserId
      ------------------------------------    --                                      -----------------
      Amazon.CloudFront.Model.CloudFrontOr... E3XXXXXXXXXXRT                          4b6e...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetCloudFrontOriginAccessIdentity](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFCloudFrontOriginAccessIdentityConfig`
<a name="cloudfront_GetCloudFrontOriginAccessIdentityConfig_powershell_5_topic"></a>

次のコード例は、`Get-CFCloudFrontOriginAccessIdentityConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、-Id パラメータで指定した、単一の Amazon CloudFront オリジンアクセスアイデンティティに関する設定情報を返します。-Id パラメータを指定しないと、エラーが発生します。**  

```
Get-CFCloudFrontOriginAccessIdentityConfig -Id E3XXXXXXXXXXRT
```
**出力:**  

```
      CallerReference                                             Comment
      ---------------                                             -------
      mycallerreference: 2/1/2011 1:16:32 PM                      Caller reference: 2/1/2011 1:16:32 PM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetCloudFrontOriginAccessIdentityConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFCloudFrontOriginAccessIdentityList`
<a name="cloudfront_ListCloudFrontOriginAccessIdentities_powershell_5_topic"></a>

次のコード例は、`Get-CFCloudFrontOriginAccessIdentityList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Amazon CloudFront オリジンアクセスアイデンティティのリストを返します。-MaxItem パラメータは値として 2 を指定しているため、結果には 2 つのアイデンティティが含まれます。**  

```
Get-CFCloudFrontOriginAccessIdentityList -MaxItem 2
```
**出力:**  

```
IsTruncated : True
Items       : {E326XXXXXXXXXT, E1YWXXXXXXX9B}
Marker      :
MaxItems    : 2
NextMarker  : E1YXXXXXXXXX9B
Quantity    : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListCloudFrontOriginAccessIdentities](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFDistribution`
<a name="cloudfront_GetDistribution_powershell_5_topic"></a>

次のコード例は、`Get-CFDistribution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 特定のディストリビューションに関する情報を取得します。**  

```
Get-CFDistribution -Id EXAMPLE0000ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDistribution](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFDistributionConfig`
<a name="cloudfront_GetDistributionConfig_powershell_5_topic"></a>

次のコード例は、`Get-CFDistributionConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 特定のディストリビューションの設定を取得します。**  

```
Get-CFDistributionConfig -Id EXAMPLE0000ID
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDistributionConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFDistributionList`
<a name="cloudfront_ListDistributions_powershell_5_topic"></a>

次のコード例は、`Get-CFDistributionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ディストリビューションを返します。**  

```
Get-CFDistributionList
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListDistributions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CFDistribution`
<a name="cloudfront_CreateDistribution_powershell_5_topic"></a>

次のコード例は、`New-CFDistribution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ロギングとキャッシュを使用して設定した、基本的な CloudFront ディストリビューションを作成します。**  

```
$origin = New-Object Amazon.CloudFront.Model.Origin
$origin.DomainName = "amzn-s3-demo-bucket.s3.amazonaws.com"
$origin.Id = "UniqueOrigin1"
$origin.S3OriginConfig = New-Object Amazon.CloudFront.Model.S3OriginConfig
$origin.S3OriginConfig.OriginAccessIdentity = ""
New-CFDistribution `
      -DistributionConfig_Enabled $true `
      -DistributionConfig_Comment "Test distribution" `
      -Origins_Item $origin `
      -Origins_Quantity 1 `
      -Logging_Enabled $true `
      -Logging_IncludeCookie $true `
      -Logging_Bucket amzn-s3-demo-logging-bucket.s3.amazonaws.com `
      -Logging_Prefix "help/" `
      -DistributionConfig_CallerReference Client1 `
      -DistributionConfig_DefaultRootObject index.html `
      -DefaultCacheBehavior_TargetOriginId $origin.Id `
      -ForwardedValues_QueryString $true `
      -Cookies_Forward all `
      -WhitelistedNames_Quantity 0 `
      -TrustedSigners_Enabled $false `
      -TrustedSigners_Quantity 0 `
      -DefaultCacheBehavior_ViewerProtocolPolicy allow-all `
      -DefaultCacheBehavior_MinTTL 1000 `
      -DistributionConfig_PriceClass "PriceClass_All" `
      -CacheBehaviors_Quantity 0 `
      -Aliases_Quantity 0
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateDistribution](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CFInvalidation`
<a name="cloudfront_CreateInvalidation_powershell_5_topic"></a>

次のコード例は、`New-CFInvalidation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ID が EXAMPLENSTXAXE であるディストリビューションで、新しいキャッシュ削除を作成します。CallerReference はユーザーが選択した固有の ID です。この例では、2019 年 5 月 15 日の午前 9 時を表すタイムスタンプを使用しています。\$1Paths 変数には、ユーザーがディストリビューションのキャッシュに含めたくない画像ファイルやメディアファイルへの 3 つのパスが格納されます。-Paths\$1Quantity パラメータ値は、-Paths\$1Item パラメータで指定したパスの総数です。**  

```
$Paths = "/images/*.gif", "/images/image1.jpg", "/videos/*.mp4"
New-CFInvalidation -DistributionId "EXAMPLENSTXAXE" -InvalidationBatch_CallerReference 20190515090000 -Paths_Item $Paths -Paths_Quantity 3
```
**出力:**  

```
Invalidation                         Location                                                                                          
------------                         --------                                                                                          
Amazon.CloudFront.Model.Invalidation https://cloudfront.amazonaws.com/2018-11-05/distribution/EXAMPLENSTXAXE/invalidation/EXAMPLE8NOK9H
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateInvalidation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CFSignedCookie`
<a name="cloudfront_New-CFSignedCookie_powershell_5_topic"></a>

次のコード例は、`New-CFSignedCookie` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 既定ポリシーを使用して、指定されたリソースに署名付き Cookie を作成します。Cookie は 1 年間有効です。**  

```
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/image1.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddYears(1)
}
New-CFSignedCookie @params
```
**出力:**  

```
Expires
-------
[CloudFront-Expires, 1472227284]
```
**例 2: カスタムポリシーを使用して、指定リソースに署名付き Cookie を作成します。Cookie は 24 時間後に有効になり、1 週間後に期限切れになります。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/content/*.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=$start.AddDays(7)
    "ActiveFrom"=$start
}

New-CFSignedCookie @params
```
**出力:**  

```
Policy
------
[CloudFront-Policy, eyJTd...wIjo...
```
**例 3: カスタムポリシーを使用して、指定リソースに署名付き Cookie を作成します。Cookie は 24 時間後に有効になり、1 週間後に期限切れになります。リソースへのアクセスは、指定の IP 範囲に制限されます。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="http://xyz.cloudfront.net/content/*.jpeg"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=$start.AddDays(7)
    "ActiveFrom"=$start
	"IpRange"="192.0.2.0/24"
}

New-CFSignedCookie @params
```
**出力:**  

```
Policy                                                                                                                                         ------                                                                                                                                         [CloudFront-Policy, eyJTd...wIjo...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[New-CFSignedCookie](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CFSignedUrl`
<a name="cloudfront_New-CFSignedUrl_powershell_5_topic"></a>

次のコード例は、`New-CFSignedUrl` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 既定ポリシーを使用して、指定リソースへの署名付き URL を作成します。URL は 1 時間有効です。署名付き URL を含む System.Uri オブジェクトがパイプラインに出力されます。**  

```
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddHours(1)
}
New-CFSignedUrl @params
```
**例 2: カスタムポリシーを使用して、指定リソースへの署名付き URL を作成します。URL は 24 時間後に有効になり、1 週間後に期限切れになります。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddDays(7)
    "ActiveFrom"=$start
}
New-CFSignedUrl @params
```
**例 3: カスタムポリシーを使用して、指定リソースへの署名付き URL を作成します。URL は 24 時間後に有効になり、1 週間後に期限切れになります。リソースへのアクセスは、指定の IP 範囲に制限されます。**  

```
$start = (Get-Date).AddHours(24)
$params = @{
	"ResourceUri"="https://cdn.example.com/index.html"
	"KeyPairId"="AKIAIOSFODNN7EXAMPLE"
	"PrivateKeyFile"="C:\pk-AKIAIOSFODNN7EXAMPLE.pem"
	"ExpiresOn"=(Get-Date).AddDays(7)
    "ActiveFrom"=$start
    "IpRange"="192.0.2.0/24"	
}
New-CFSignedUrl @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[New-CFSignedUrl](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した CloudTrail の例
<a name="powershell_5_cloudtrail_code_examples"></a>

次のコード例は、CloudTrail で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Find-CTEvent`
<a name="cloudtrail_LookupEvents_powershell_5_topic"></a>

次のコード例は、`Find-CTEvent` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 過去 7 日間に発生したすべてのイベントを返します。コマンドレットはデフォルトで、すべてのイベントを配信するために複数の呼び出しを自動的に実行し、サービスがこれ以上データがないことを示した時点で終了します。**  

```
Find-CTEvent
```
**例 2: 現在のシェルのデフォルト以外のリージョンを指定して、過去 7 日間に発生したすべてのイベントを返します。**  

```
Find-CTEvent -Region eu-central-1
```
**例 3: RunInstances API コールに関連付けられているすべてのイベントを返します。**  

```
Find-CTEvent -LookupAttribute @{ AttributeKey="EventName"; AttributeValue="RunInstances" }
```
**例 4: 使用可能な最初の 5 つのイベントを返します。**  

```
Find-CTEvent -MaxResult 5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[LookupEvents](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CTTrail`
<a name="cloudtrail_DescribeTrails_powershell_5_topic"></a>

次のコード例は、`Get-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: アカウントの現在のリージョンに関連付けられているすべての証跡の設定を返します。**  

```
Get-CTTrail
```
**例 2: 指定された証跡の設定を返します。**  

```
Get-CTTrail -TrailNameList trail1,trail2
```
**例 3: 現在のシェルのデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された、指定された証跡の設定を返します。**  

```
Get-CTTrail -TrailNameList trailABC,trailDEF -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeTrails](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CTTrailStatus`
<a name="cloudtrail_GetTrailStatus_powershell_5_topic"></a>

次のコード例は、`Get-CTTrailStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「myExampleTrail」という名前の証跡のステータス情報を返します。返されるデータには、配信エラー、Amazon SNS および Amazon S3 エラー、証跡のログ記録の開始時間と停止時間に関する情報が含まれます。この例では、証跡が現在のシェルのデフォルトリージョンと同じリージョンで作成されたことを前提としています。**  

```
Get-CTTrailStatus -Name myExampleTrail
```
**例 2: 現在のシェルのデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された証跡のステータス情報を返します。**  

```
Get-CTTrailStatus -Name myExampleTrail -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetTrailStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CTTrail`
<a name="cloudtrail_CreateTrail_powershell_5_topic"></a>

次のコード例は、`New-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ログファイルストレージにバケット「amzn-s3-demo-bucket」を使用する証跡を作成します。**  

```
New-CTTrail -Name "awscloudtrail-example" -S3BucketName "amzn-s3-demo-bucket"
```
**例 2: ログファイルストレージにバケット「amzn-s3-demo-bucket」を使用する証跡を作成します。ログを表す S3 オブジェクトには、共通キープレフィックス「mylogs」があります。新しいログがバケットに配信されると、SNS トピック「mlog-deliverytopic」に通知が送信されます。この例では、スプラッティングを使用してパラメータ値をコマンドレットに指定します。**  

```
$params = @{
    Name="awscloudtrail-example"
    S3BucketName="amzn-s3-demo-bucket"
    S3KeyPrefix="mylogs"
    SnsTopicName="mlog-deliverytopic"
}      
New-CTTrail @params
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateTrail](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CTTrail`
<a name="cloudtrail_DeleteTrail_powershell_5_topic"></a>

次のコード例は、`Remove-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された証跡を削除します。コマンドを実行する前に確認を求められます。-Force スイッチを追加すると、確認メッセージが表示されなくなります。**  

```
Remove-CTTrail -Name "awscloudtrail-example"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteTrail](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-CTLogging`
<a name="cloudtrail_StartLogging_powershell_5_topic"></a>

次のコード例は、`Start-CTLogging` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 'myExampleTrail' という名前の証跡の AWS API コールとログファイルの配信の記録を開始します。この例では、証跡が現在のシェルのデフォルトリージョンと同じリージョンで作成されたことを前提としています。**  

```
Start-CTLogging -Name myExampleTrail
```
**例 2: 現在のシェルデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された証跡の AWS API コールとログファイルの配信の記録を開始します。**  

```
Start-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StartLogging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-CTLogging`
<a name="cloudtrail_StopLogging_powershell_5_topic"></a>

次のコード例は、`Stop-CTLogging` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 'myExampleTrail' という名前の証跡の AWS API コールとログファイル配信の記録を停止します。この例では、証跡が現在のシェルのデフォルトリージョンと同じリージョンで作成されたことを前提としています。**  

```
Stop-CTLogging -Name myExampleTrail
```
**例 2: 現在のシェルデフォルト (この場合はフランクフルト (eu-central-1) リージョン) 以外のリージョンで作成された証跡の AWS API コールとログファイル配信の記録を停止します。**  

```
Stop-CTLogging -Name myExampleTrail -Region eu-central-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StopLogging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CTTrail`
<a name="cloudtrail_UpdateTrail_powershell_5_topic"></a>

次のコード例は、`Update-CTTrail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: グローバルサービスイベント (IAM からのイベントなど) が記録されるように指定された証跡を更新し、以降のログファイルの共通キープレフィックスを「globallogs」に変更します。**  

```
Update-CTTrail -Name "awscloudtrail-example" -IncludeGlobalServiceEvents $true -S3KeyPrefix "globallogs"
```
**例 2: 新しいログ配信に関する通知が指定された SNS トピックに送信されるように、指定された証跡を更新します。**  

```
Update-CTTrail -Name "awscloudtrail-example" -SnsTopicName "mlog-deliverytopic2"
```
**例 3: ログが別のバケットに配信されるように、指定された証跡を更新します。**  

```
Update-CTTrail -Name "awscloudtrail-example" -S3BucketName "otherlogs"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateTrail](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した CloudWatch の例
<a name="powershell_5_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CWDashboard`
<a name="cloudwatch_GetDashboard_powershell_5_topic"></a>

次のコード例は、`Get-CWDashboard` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたダッシュボードの本体である arn を返します。**  

```
Get-CWDashboard -DashboardName Dashboard1
```
**出力:**  

```
DashboardArn                                          DashboardBody
------------                                          -------------
arn:aws:cloudwatch::123456789012:dashboard/Dashboard1 {...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDashboard](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CWDashboardList`
<a name="cloudwatch_ListDashboards_powershell_5_topic"></a>

次のコード例は、`Get-CWDashboardList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: アカウントのダッシュボードのコレクションを返します。**  

```
Get-CWDashboardList
```
**出力:**  

```
DashboardArn DashboardName LastModified        Size
------------ ------------- ------------        ----
arn:...      Dashboard1    7/6/2017 8:14:15 PM 252
```
**例 2: 名前が 'dev' で始まるアカウントのダッシュボードのコレクションを返します。**  

```
Get-CWDashboardList -DashboardNamePrefix dev
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListDashboards](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CWDashboard`
<a name="cloudwatch_DeleteDashboards_powershell_5_topic"></a>

次のコード例は、`Remove-CWDashboard` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定したダッシュボードを削除し、次に進む前に確認を促します。確認を省略するには、-Force スイッチをコマンドに追加します。**  

```
Remove-CWDashboard -DashboardName Dashboard1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteDashboards](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-CWDashboard`
<a name="cloudwatch_PutDashboard_powershell_5_topic"></a>

次のコード例は、`Write-CWDashboard` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 'Dashboard1' という名前のダッシュボードを作成または更新して、2 つのメトリクスウィジェットを並べて表示します。**  

```
$dashBody = @"
{
    "widgets":[
        {
             "type":"metric",
             "x":0,
             "y":0,
             "width":12,
             "height":6,
             "properties":{
                "metrics":[
                   [
                      "AWS/EC2",
                      "CPUUtilization",
                      "InstanceId",
                      "i-012345"
                   ]
                ],
                "period":300,
                "stat":"Average",
                "region":"us-east-1",
                "title":"EC2 Instance CPU"
             }
        },
        {
             "type":"metric",
             "x":12,
             "y":0,
             "width":12,
             "height":6,
             "properties":{
                "metrics":[
                   [
                      "AWS/S3",
                      "BucketSizeBytes",
                      "BucketName",
                      "amzn-s3-demo-bucket"
                   ]
                ],
                "period":86400,
                "stat":"Maximum",
                "region":"us-east-1",
                "title":"amzn-s3-demo-bucket bytes"
            }
        }
    ]
}
"@

Write-CWDashboard -DashboardName Dashboard1 -DashboardBody $dashBody
```
**例 2: ダッシュボードを作成または更新し、ダッシュボードを説明するコンテンツをコマンドレットにパイプします。**  

```
$dashBody = @"
{
...
}
"@
        
$dashBody | Write-CWDashboard -DashboardName Dashboard1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutDashboard](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-CWMetricData`
<a name="cloudwatch_PutMetricData_powershell_5_topic"></a>

次のコード例は、`Write-CWMetricData` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 新しい MetricDatum オブジェクトを作成し、Amazon Web Services の CloudWatch メトリクスに書き込みます。**  

```
### Create a MetricDatum .NET object
$Metric = New-Object -TypeName Amazon.CloudWatch.Model.MetricDatum
$Metric.Timestamp = [DateTime]::UtcNow
$Metric.MetricName = 'CPU'
$Metric.Value = 50

### Write the metric data to the CloudWatch service
Write-CWMetricData -Namespace instance1 -MetricData $Metric
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutMetricData](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した CodeCommit の例
<a name="powershell_5_codecommit_code_examples"></a>

次のコード例は、CodeCommit で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CCBranch`
<a name="codecommit_GetBranch_powershell_5_topic"></a>

次のコード例は、`Get-CCBranch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリの指定されたブランチに関する情報を取得します。**  

```
Get-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch
```
**出力:**  

```
BranchName                              CommitId
----------                              --------
MyNewBranch                             7763222d...561fc9c9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetBranch](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CCBranchList`
<a name="codecommit_ListBranches_powershell_5_topic"></a>

次のコード例は、`Get-CCBranchList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリのブランチ名のリストを取得します。**  

```
Get-CCBranchList -RepositoryName MyDemoRepo
```
**出力:**  

```
master
MyNewBranch
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListBranches](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CCRepository`
<a name="codecommit_GetRepository_powershell_5_topic"></a>

次のコード例は、`Get-CCRepository` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリの情報を取得します。**  

```
Get-CCRepository -RepositoryName MyDemoRepo
```
**出力:**  

```
AccountId             : 80398EXAMPLE
Arn                   : arn:aws:codecommit:us-east-1:80398EXAMPLE:MyDemoRepo
CloneUrlHttp          : https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CloneUrlSsh           : ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CreationDate          : 9/8/2015 3:21:33 PM
DefaultBranch         :
LastModifiedDate      : 9/8/2015 3:21:33 PM
RepositoryDescription : This is a repository for demonstration purposes.
RepositoryId          : c7d0d2b0-ce40-4303-b4c3-38529EXAMPLE
RepositoryName        : MyDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetRepository](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CCRepositoryBatch`
<a name="codecommit_BatchGetRepositories_powershell_5_topic"></a>

次のコード例は、`Get-CCRepositoryBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリのうち、見つかったリポジトリと見つからないリポジトリを確認します。**  

```
Get-CCRepositoryBatch -RepositoryName MyDemoRepo, MyNewRepo, AMissingRepo
```
**出力:**  

```
Repositories                            RepositoriesNotFound
------------                            --------------------
{MyDemoRepo, MyNewRepo}                {AMissingRepo}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchGetRepositories](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CCRepositoryList`
<a name="codecommit_ListRepositories_powershell_5_topic"></a>

次のコード例は、`Get-CCRepositoryList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべてのリポジトリをリポジトリ名で昇順に一覧表示します。**  

```
Get-CCRepositoryList -Order Ascending -SortBy RepositoryName
```
**出力:**  

```
RepositoryId                            RepositoryName
------------                            --------------
c7d0d2b0-ce40-4303-b4c3-38529EXAMPLE    MyDemoRepo
05f30c66-e3e3-4f91-a0cd-1c84aEXAMPLE    MyNewRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListRepositories](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CCBranch`
<a name="codecommit_CreateBranch_powershell_5_topic"></a>

次のコード例は、`New-CCBranch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリの指定された名前と指定されたコミット ID を持つ新しいブランチを作成します。**  

```
New-CCBranch -RepositoryName MyDemoRepo -BranchName MyNewBranch -CommitId 7763222d...561fc9c9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateBranch](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CCRepository`
<a name="codecommit_CreateRepository_powershell_5_topic"></a>

次のコード例は、`New-CCRepository` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前と説明を持つ新しいリポジトリを作成します。**  

```
New-CCRepository -RepositoryName MyDemoRepo -RepositoryDescription "This is a repository for demonstration purposes."
```
**出力:**  

```
AccountId             : 80398EXAMPLE
Arn                   : arn:aws:codecommit:us-east-1:80398EXAMPLE:MyDemoRepo
CloneUrlHttp          : https://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CloneUrlSsh           : ssh://git-codecommit.us-east-1.amazonaws.com/v1/repos/MyDemoRepo
CreationDate          : 9/18/2015 4:13:25 PM
DefaultBranch         :
LastModifiedDate      : 9/18/2015 4:13:25 PM
RepositoryDescription : This is a repository for demonstration purposes.
RepositoryId          : 43ef2443-3372-4b12-9e78-65c27EXAMPLE
RepositoryName        : MyDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateRepository](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CCRepository`
<a name="codecommit_DeleteRepository_powershell_5_topic"></a>

次のコード例は、`Remove-CCRepository` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリを強制的に削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでリポジトリを削除します。**  

```
Remove-CCRepository -RepositoryName MyDemoRepo
```
**出力:**  

```
43ef2443-3372-4b12-9e78-65c27EXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteRepository](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CCDefaultBranch`
<a name="codecommit_UpdateDefaultBranch_powershell_5_topic"></a>

次のコード例は、`Update-CCDefaultBranch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリのデフォルトブランチを指定されたブランチに変更します。**  

```
Update-CCDefaultBranch -RepositoryName MyDemoRepo -DefaultBranchName MyNewBranch
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateDefaultBranch](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CCRepositoryDescription`
<a name="codecommit_UpdateRepositoryDescription_powershell_5_topic"></a>

次のコード例は、`Update-CCRepositoryDescription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリの説明を変更します。**  

```
Update-CCRepositoryDescription -RepositoryName MyDemoRepo -RepositoryDescription "This is an updated description."
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateRepositoryDescription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CCRepositoryName`
<a name="codecommit_UpdateRepositoryName_powershell_5_topic"></a>

次のコード例は、`Update-CCRepositoryName` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリポジトリの名前を変更します。**  

```
Update-CCRepositoryName -NewName MyDemoRepo2 -OldName MyDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateRepositoryName](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した CodeDeploy の例
<a name="powershell_5_codedeploy_code_examples"></a>

次のコード例は、CodeDeploy で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-CDOnPremiseInstanceTag`
<a name="codedeploy_AddTagsToOnPremisesInstances_powershell_5_topic"></a>

次のコード例は、`Add-CDOnPremiseInstanceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたオンプレミスインスタンスに指定されたキーと値を持つオンプレミスインスタンスタグを追加します。**  

```
Add-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AddTagsToOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDApplication`
<a name="codedeploy_GetApplication_powershell_5_topic"></a>

次のコード例は、`Get-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションに関する情報を取得します。**  

```
Get-CDApplication -ApplicationName CodeDeployDemoApplication
```
**出力:**  

```
ApplicationId                           ApplicationName              CreateTime              LinkedToGitHub
-------------                           ---------------              ----------              --------------
e07fb938-091e-4f2f-8963-4d3e8EXAMPLE    CodeDeployDemoApplication    7/20/2015 9:49:48 PM    False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetApplication](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDApplicationBatch`
<a name="codedeploy_BatchGetApplications_powershell_5_topic"></a>

次のコード例は、`Get-CDApplicationBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションに関する情報を取得します。**  

```
Get-CDApplicationBatch -ApplicationName CodeDeployDemoApplication, CodePipelineDemoApplication
```
**出力:**  

```
ApplicationId                           ApplicationName              CreateTime              LinkedToGitHub
-------------                           ---------------              ----------              --------------
e07fb938-091e-4f2f-8963-4d3e8EXAMPLE    CodeDeployDemoApplication    7/20/2015 9:49:48 PM    False
1ecfd602-62f1-4038-8f0d-06688EXAMPLE    CodePipelineDemoApplication  8/13/2015 5:53:26 PM    False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchGetApplications](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDApplicationList`
<a name="codedeploy_ListApplications_powershell_5_topic"></a>

次のコード例は、`Get-CDApplicationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、使用可能なアプリケーションのリストを取得します。**  

```
Get-CDApplicationList
```
**出力:**  

```
CodeDeployDemoApplication
CodePipelineDemoApplication
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListApplications](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDApplicationRevision`
<a name="codedeploy_GetApplicationRevision_powershell_5_topic"></a>

次のコード例は、`Get-CDApplicationRevision` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションリビジョンに関する情報を取得します。**  

```
$revision = Get-CDApplicationRevision -ApplicationName CodeDeployDemoApplication -S3Location_Bucket amzn-s3-demo-bucket -Revision_RevisionType S3 -S3Location_Key 5xd27EX.zip -S3Location_BundleType zip -S3Location_ETag 4565c1ac97187f190c1a90265EXAMPLE
Write-Output ("Description = " + $revision.RevisionInfo.Description + ", RegisterTime = " + $revision.RevisionInfo.RegisterTime)
```
**出力:**  

```
Description = Application revision registered by Deployment ID: d-CX9CHN3EX, RegisterTime = 07/20/2015 23:46:42
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetApplicationRevision](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDApplicationRevisionList`
<a name="codedeploy_ListApplicationRevisions_powershell_5_topic"></a>

次のコード例は、`Get-CDApplicationRevisionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションで使用可能なリビジョンに関する情報を取得します。**  

```
ForEach ($revision in (Get-CDApplicationRevisionList -ApplicationName CodeDeployDemoApplication -Deployed Ignore)) {
>>   If ($revision.RevisionType -Eq "S3") {
>>     Write-Output ("Type = S3, Bucket = " + $revision.S3Location.Bucket + ", BundleType = " + $revision.S3Location.BundleType + ", ETag = " + $revision.S3Location.ETag + ", Key = " + $revision.S3Location.Key)
>>   }
>>   If ($revision.RevisionType -Eq "GitHub") {
>>     Write-Output ("Type = GitHub, CommitId = " + $revision.GitHubLocation.CommitId + ", Repository = " + $revision.GitHubLocation.Repository)
>>   }
>> }
>>
```
**出力:**  

```
Type = S3, Bucket = amzn-s3-demo-bucket, BundleType = zip, ETag = 4565c1ac97187f190c1a90265EXAMPLE, Key = 5xd27EX.zip
Type = GitHub, CommitId = f48933c3...76405362, Repository = MyGitHubUser/CodeDeployDemoRepo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListApplicationRevisions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeployment`
<a name="codedeploy_GetDeployment_powershell_5_topic"></a>

次のコード例は、`Get-CDDeployment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイに関する概要情報を取得します。**  

```
Get-CDDeployment -DeploymentId d-QZMRGSTEX
```
**出力:**  

```
ApplicationName               : CodeDeployDemoApplication
CompleteTime                  : 7/23/2015 11:26:04 PM
CreateTime                    : 7/23/2015 11:24:43 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodeDeployDemoFleet
DeploymentId                  : d-QZMRGSTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded
```
**例 2: この例では、指定されたデプロイに参加しているインスタンスのステータスに関する情報を取得します。**  

```
(Get-CDDeployment -DeploymentId d-QZMRGSTEX).DeploymentOverview
```
**出力:**  

```
Failed     : 0
InProgress : 0
Pending    : 0
Skipped    : 0
Succeeded  : 3
```
**例 3: この例では、指定されたデプロイのアプリケーションリビジョンに関する情報を取得します。**  

```
(Get-CDDeployment -DeploymentId d-QZMRGSTEX).Revision.S3Location
```
**出力:**  

```
Bucket     : amzn-s3-demo-bucket
BundleType : zip
ETag       : cfbb81b304ee5e27efc21adaed3EXAMPLE
Key        : clzfqEX
Version    :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDeployment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentBatch`
<a name="codedeploy_BatchGetDeployments_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイに関する情報を取得します。**  

```
Get-CDDeploymentBatch -DeploymentId d-QZMRGSTEX, d-RR0T5KTEX
```
**出力:**  

```
ApplicationName               : CodeDeployDemoApplication
CompleteTime                  : 7/23/2015 11:26:04 PM
CreateTime                    : 7/23/2015 11:24:43 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodeDeployDemoFleet
DeploymentId                  : d-QZMRGSTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded

ApplicationName               : CodePipelineDemoApplication
CompleteTime                  : 7/23/2015 6:07:30 PM
CreateTime                    : 7/23/2015 6:06:29 PM
Creator                       : user
DeploymentConfigName          : CodeDeployDefault.OneAtATime
DeploymentGroupName           : CodePipelineDemoFleet
DeploymentId                  : d-RR0T5KTEX
DeploymentOverview            : Amazon.CodeDeploy.Model.DeploymentOverview
Description                   :
ErrorInformation              :
IgnoreApplicationStopFailures : False
Revision                      : Amazon.CodeDeploy.Model.RevisionLocation
StartTime                     : 1/1/0001 12:00:00 AM
Status                        : Succeeded
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchGetDeployments](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentConfig`
<a name="codedeploy_GetDeploymentConfig_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイ設定に関する概要情報を取得します。**  

```
Get-CDDeploymentConfig -DeploymentConfigName ThreeQuartersHealthy
```
**出力:**  

```
CreateTime              DeploymentConfigId                      DeploymentConfigName    MinimumHealthyHosts
----------              ------------------                      --------------------    -------------------
10/3/2014 4:32:30 PM    518a3950-d034-46a1-9d2c-3c949EXAMPLE    ThreeQuartersHealthy    Amazon.CodeDeploy.Model.MinimumHealthyHosts
```
**例 2: この例では、指定されたデプロイ設定の定義に関する情報を取得します。**  

```
Write-Output ((Get-CDDeploymentConfig -DeploymentConfigName ThreeQuartersHealthy).MinimumHealthyHosts)
```
**出力:**  

```
Type             Value
----             -----
FLEET_PERCENT    75
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentConfigList`
<a name="codedeploy_ListDeploymentConfigs_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentConfigList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、使用可能なデプロイ設定のリストを取得します。**  

```
Get-CDDeploymentConfigList
```
**出力:**  

```
ThreeQuartersHealthy
CodeDeployDefault.OneAtATime
CodeDeployDefault.AllAtOnce
CodeDeployDefault.HalfAtATime
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListDeploymentConfigs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentGroup`
<a name="codedeploy_GetDeploymentGroup_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイグループに関する情報を取得します。**  

```
Get-CDDeploymentGroup -ApplicationName CodeDeployDemoApplication -DeploymentGroupName CodeDeployDemoFleet
```
**出力:**  

```
ApplicationName              : CodeDeployDemoApplication
AutoScalingGroups            : {}
DeploymentConfigName         : CodeDeployDefault.OneAtATime
DeploymentGroupId            : 7d7c098a-b444-4b27-96ef-22791EXAMPLE
DeploymentGroupName          : CodeDeployDemoFleet
Ec2TagFilters                : {Name}
OnPremisesInstanceTagFilters : {}
ServiceRoleArn               : arn:aws:iam::80398EXAMPLE:role/CodeDeploySampleStack-4ph6EX-CodeDeployTrustRole-O9MWP7XTL8EX
TargetRevision               : Amazon.CodeDeploy.Model.RevisionLocation
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentGroupList`
<a name="codedeploy_ListDeploymentGroups_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentGroupList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションのデプロイグループのリストを取得します。**  

```
Get-CDDeploymentGroupList -ApplicationName CodeDeployDemoApplication
```
**出力:**  

```
ApplicationName              DeploymentGroups                                    NextToken
---------------              ----------------                                    ---------
CodeDeployDemoApplication    {CodeDeployDemoFleet, CodeDeployProductionFleet}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListDeploymentGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentInstance`
<a name="codedeploy_GetDeploymentInstance_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイの指定されたインスタンスに関する情報を取得します。**  

```
Get-CDDeploymentInstance -DeploymentId d-QZMRGSTEX -InstanceId i-254e22EX
```
**出力:**  

```
DeploymentId    : d-QZMRGSTEX
InstanceId      : arn:aws:ec2:us-east-1:80398EXAMPLE:instance/i-254e22EX
LastUpdatedAt   : 7/23/2015 11:25:24 PM
LifecycleEvents : {ApplicationStop, DownloadBundle, BeforeInstall, Install...}
Status          : Succeeded
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDeploymentInstance](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentInstanceList`
<a name="codedeploy_ListDeploymentInstances_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentInstanceList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイのインスタンス ID のリストを取得します。**  

```
Get-CDDeploymentInstanceList -DeploymentId d-QZMRGSTEX
```
**出力:**  

```
i-254e22EX
i-274e22EX
i-3b4e22EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListDeploymentInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDDeploymentList`
<a name="codedeploy_ListDeployments_powershell_5_topic"></a>

次のコード例は、`Get-CDDeploymentList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションとデプロイグループのデプロイ ID のリストを取得します。**  

```
Get-CDDeploymentList -ApplicationName CodeDeployDemoApplication -DeploymentGroupName CodeDeployDemoFleet
```
**出力:**  

```
d-QZMRGSTEX
d-RR0T5KTEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListDeployments](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDOnPremiseInstance`
<a name="codedeploy_GetOnPremisesInstance_powershell_5_topic"></a>

次のコード例は、`Get-CDOnPremiseInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたオンプレミスインスタンスに関する情報を取得します。**  

```
Get-CDOnPremiseInstance -InstanceName AssetTag12010298EX
```
**出力:**  

```
DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX_rDH556dxEX
InstanceName   : AssetTag12010298EX
RegisterTime   : 4/3/2015 6:36:24 PM
Tags           : {Name}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDOnPremiseInstanceBatch`
<a name="codedeploy_BatchGetOnPremisesInstances_powershell_5_topic"></a>

次のコード例は、`Get-CDOnPremiseInstanceBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたオンプレミスインスタンスに関する情報を取得します。**  

```
Get-CDOnPremiseInstanceBatch -InstanceName AssetTag12010298EX, AssetTag12010298EX-2
```
**出力:**  

```
DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployFRWUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX-2_XmeSz18rEX
InstanceName   : AssetTag12010298EX-2
RegisterTime   : 4/3/2015 6:38:52 PM
Tags           : {Name}

DeregisterTime : 1/1/0001 12:00:00 AM
IamUserArn     : arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser
InstanceArn    : arn:aws:codedeploy:us-east-1:80398EXAMPLE:instance/AssetTag12010298EX_rDH556dxEX
InstanceName   : AssetTag12010298EX
RegisterTime   : 4/3/2015 6:36:24 PM
Tags           : {Name}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchGetOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CDOnPremiseInstanceList`
<a name="codedeploy_ListOnPremisesInstances_powershell_5_topic"></a>

次のコード例は、`Get-CDOnPremiseInstanceList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、使用可能なオンプレミスインスタンス名のリストを取得します。**  

```
Get-CDOnPremiseInstanceList
```
**出力:**  

```
AssetTag12010298EX
AssetTag12010298EX-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CDApplication`
<a name="codedeploy_CreateApplication_powershell_5_topic"></a>

次のコード例は、`New-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した名前で新しいアプリケーションを作成します。**  

```
New-CDApplication -ApplicationName MyNewApplication
```
**出力:**  

```
f19e4b61-2231-4328-b0fd-e57f5EXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateApplication](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CDDeployment`
<a name="codedeploy_CreateDeployment_powershell_5_topic"></a>

次のコード例は、`New-CDDeployment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイ設定とアプリケーションリビジョンを使用して、指定されたアプリケーションとデプロイグループの新しいデプロイを作成します。**  

```
New-CDDeployment -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -IgnoreApplicationStopFailures $True -S3Location_Key aws-codedeploy_linux-master.zip -RevisionType S3
```
**出力:**  

```
d-ZHROG7UEX
```
**例 2: この例では、ブルー/グリーンデプロイの置き換え環境に含めるために、そのインスタンスを識別する必要がある EC2 インスタンスタグのグループを指定する方法を示します。**  

```
New-CDDeployment -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -IgnoreApplicationStopFailures $True -S3Location_Key aws-codedeploy_linux-master.zip -RevisionType S3 -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
**出力:**  

```
d-ZHROG7UEX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateDeployment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CDDeploymentConfig`
<a name="codedeploy_CreateDeploymentConfig_powershell_5_topic"></a>

次のコード例は、`New-CDDeploymentConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前と動作で新しいデプロイ設定を作成します。**  

```
New-CDDeploymentConfig -DeploymentConfigName AtLeastTwoHealthyHosts -MinimumHealthyHosts_Type HOST_COUNT -MinimumHealthyHosts_Value 2
```
**出力:**  

```
0f3e8187-44ef-42da-aeed-b6823EXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CDDeploymentGroup`
<a name="codedeploy_CreateDeploymentGroup_powershell_5_topic"></a>

次のコード例は、`New-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションに対して指定された名前、Auto Scaling グループ、デプロイ設定、タグ、サービスロールを持つデプロイグループを作成します。**  

```
New-CDDeploymentGroup -ApplicationName MyNewApplication -AutoScalingGroup CodeDeployDemo-ASG -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -Ec2TagFilter @{Key="Name"; Type="KEY_AND_VALUE"; Value="CodeDeployDemo"} -ServiceRoleArn arn:aws:iam::80398EXAMPLE:role/CodeDeployDemo
```
**出力:**  

```
16bbf199-95fd-40fc-a909-0bbcfEXAMPLE
```
**例 2: この例では、ブルー/グリーンデプロイの置き換え環境に含めるために、そのインスタンスを識別する必要がある EC2 インスタンスタグのグループを指定する方法を示します。**  

```
New-CDDeploymentGroup -ApplicationName MyNewApplication -AutoScalingGroup CodeDeployDemo-ASG -DeploymentConfigName CodeDeployDefault.OneAtATime -DeploymentGroupName MyNewDeploymentGroup -Ec2TagFilter @{Key="Name"; Type="KEY_AND_VALUE"; Value="CodeDeployDemo"} -ServiceRoleArn arn:aws:iam::80398EXAMPLE:role/CodeDeployDemo -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
**出力:**  

```
16bbf199-95fd-40fc-a909-0bbcfEXAMPLE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-CDApplicationRevision`
<a name="codedeploy_RegisterApplicationRevision_powershell_5_topic"></a>

次のコード例は、`Register-CDApplicationRevision` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションに対し、指定された Amazon S3 ロケーションでアプリケーションリビジョンを登録します。**  

```
Register-CDApplicationRevision -ApplicationName MyNewApplication -S3Location_Bucket amzn-s3-demo-bucket -S3Location_BundleType zip -S3Location_Key aws-codedeploy_linux-master.zip -Revision_RevisionType S3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RegisterApplicationRevision](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-CDOnPremiseInstance`
<a name="codedeploy_RegisterOnPremisesInstance_powershell_5_topic"></a>

次のコード例は、`Register-CDOnPremiseInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前と IAM ユーザーでオンプレミスインスタンスを登録します。**  

```
Register-CDOnPremiseInstance -IamUserArn arn:aws:iam::80398EXAMPLE:user/CodeDeployDemoUser -InstanceName AssetTag12010298EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RegisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CDApplication`
<a name="codedeploy_DeleteApplication_powershell_5_topic"></a>

次のコード例は、`Remove-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前のアプリケーションを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでアプリケーションを削除します。**  

```
Remove-CDApplication -ApplicationName MyNewApplication
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteApplication](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CDDeploymentConfig`
<a name="codedeploy_DeleteDeploymentConfig_powershell_5_topic"></a>

次のコード例は、`Remove-CDDeploymentConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前のデプロイ設定を削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでデプロイ設定を削除します。**  

```
Remove-CDDeploymentConfig -DeploymentConfigName AtLeastTwoHealthyHosts
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteDeploymentConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CDDeploymentGroup`
<a name="codedeploy_DeleteDeploymentGroup_powershell_5_topic"></a>

次のコード例は、`Remove-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションの指定された名前のデプロイグループを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでデプロイグループを削除します。**  

```
Remove-CDDeploymentGroup -ApplicationName MyNewApplication -DeploymentGroupName MyNewDeploymentGroup
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CDOnPremiseInstanceTag`
<a name="codedeploy_RemoveTagsFromOnPremisesInstances_powershell_5_topic"></a>

次のコード例は、`Remove-CDOnPremiseInstanceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前のオンプレミスインスタンスの指定されたタグを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでタグを削除します。**  

```
Remove-CDOnPremiseInstanceTag -InstanceName AssetTag12010298EX -Tag @{"Key" = "Name"; "Value" = "CodeDeployDemo-OnPrem"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RemoveTagsFromOnPremisesInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-CDDeployment`
<a name="codedeploy_StopDeployment_powershell_5_topic"></a>

次のコード例は、`Stop-CDDeployment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたデプロイ ID を持つデプロイの停止を試みます。**  

```
Stop-CDDeployment -DeploymentId d-LJQNREYEX
```
**出力:**  

```
Status     StatusMessage
------     -------------
Pending    Stopping Pending. Stopping to schedule commands in the deployment instances
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StopDeployment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-CDOnPremiseInstance`
<a name="codedeploy_DeregisterOnPremisesInstance_powershell_5_topic"></a>

次のコード例は、`Unregister-CDOnPremiseInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前のオンプレミスインスタンスを登録解除します。**  

```
Unregister-CDOnPremiseInstance -InstanceName AssetTag12010298EX
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeregisterOnPremisesInstance](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CDApplication`
<a name="codedeploy_UpdateApplication_powershell_5_topic"></a>

次のコード例は、`Update-CDApplication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションの名前を変更します。**  

```
Update-CDApplication -ApplicationName MyNewApplication -NewApplicationName MyNewApplication-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)*の「[UpdateApplication](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CDDeploymentGroup`
<a name="codedeploy_UpdateDeploymentGroup_powershell_5_topic"></a>

次のコード例は、`Update-CDDeploymentGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーションの指定されたデプロイグループの名前を変更します。**  

```
Update-CDDeploymentGroup -ApplicationName MyNewApplication -CurrentDeploymentGroupName MyNewDeploymentGroup -NewDeploymentGroupName MyNewDeploymentGroup-2
```
**例 2: この例では、ブルー/グリーンデプロイの置き換え環境に含めるために、そのインスタンスを識別する必要がある EC2 インスタンスタグのグループを指定する方法を示します。**  

```
Update-CDDeploymentGroup -ApplicationName MyNewApplication -CurrentDeploymentGroupName MyNewDeploymentGroup -NewDeploymentGroupName MyNewDeploymentGroup-2 -Ec2TagSetList @(@{Key="key1";Type="KEY_ONLY"},@{Key="Key2";Type="KEY_AND_VALUE";Value="Value2"}),@(@{Key="Key3";Type="VALUE_ONLY";Value="Value3"})
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateDeploymentGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した CodePipeline の例
<a name="powershell_5_codepipeline_code_examples"></a>

次のコード例は、CodePipeline で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Confirm-CPJob`
<a name="codepipeline_AcknowledgeJob_powershell_5_topic"></a>

次のコード例は、`Confirm-CPJob` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、特定のジョブのステータスを取得します。**  

```
Confirm-CPJob -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE -Nonce 3
```
**出力:**  

```
Value
-----
InProgress
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AcknowledgeJob](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-CPStageTransition`
<a name="codepipeline_DisableStageTransition_powershell_5_topic"></a>

次のコード例は、`Disable-CPStageTransition` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたパイプライン内の指定されたステージに対してインバウンド移行を無効にします。**  

```
Disable-CPStageTransition -PipelineName CodePipelineDemo -Reason "Disabling temporarily." -StageName Beta -TransitionType Inbound
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableStageTransition](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-CPStageTransition`
<a name="codepipeline_EnableStageTransition_powershell_5_topic"></a>

次のコード例は、`Enable-CPStageTransition` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたパイプライン内の指定されたステージに対してインバウンド移行を有効にします。**  

```
Enable-CPStageTransition -PipelineName CodePipelineDemo -StageName Beta -TransitionType Inbound
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableStageTransition](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CPActionType`
<a name="codepipeline_ListActionTypes_powershell_5_topic"></a>

次のコード例は、`Get-CPActionType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された所有者が使用可能なすべてのアクションに関する情報を取得します。**  

```
ForEach ($actionType in (Get-CPActionType -ActionOwnerFilter AWS)) {
  Write-Output ("For Category = " + $actionType.Id.Category + ", Owner = " + $actionType.Id.Owner + ", Provider = " + $actionType.Id.Provider + ", Version = " + $actionType.Id.Version + ":")
  Write-Output ("  ActionConfigurationProperties:")
  ForEach ($acp in $actionType.ActionConfigurationProperties) {
    Write-Output ("    For " + $acp.Name + ":")
    Write-Output ("      Description = " + $acp.Description)
    Write-Output ("      Key = " + $acp.Key)
    Write-Output ("      Queryable = " + $acp.Queryable)
    Write-Output ("      Required = " + $acp.Required)
    Write-Output ("      Secret = " + $acp.Secret)
  }
  Write-Output ("  InputArtifactDetails:")
  Write-Output ("    MaximumCount = " + $actionType.InputArtifactDetails.MaximumCount)
  Write-Output ("    MinimumCount = " + $actionType.InputArtifactDetails.MinimumCount)
  Write-Output ("  OutputArtifactDetails:")
  Write-Output ("    MaximumCount = " + $actionType.OutputArtifactDetails.MaximumCount)
  Write-Output ("    MinimumCount = " + $actionType.OutputArtifactDetails.MinimumCount)
  Write-Output ("  Settings:")
  Write-Output ("    EntityUrlTemplate = " + $actionType.Settings.EntityUrlTemplate)
  Write-Output ("    ExecutionUrlTemplate = " + $actionType.Settings.ExecutionUrlTemplate)
}
```
**出力:**  

```
For Category = Deploy, Owner = AWS, Provider = ElasticBeanstalk, Version = 1:
  ActionConfigurationProperties:
    For ApplicationName:
      Description = The AWS Elastic Beanstalk Application name
      Key = True
      Queryable = False
      Required = True
      Secret = False
    For EnvironmentName:
      Description = The AWS Elastic Beanstalk Environment name
      Key = True
      Queryable = False
      Required = True
      Secret = False
  InputArtifactDetails:
    MaximumCount = 1
    MinimumCount = 1
  OutputArtifactDetails:
    MaximumCount = 0
    MinimumCount = 0
  Settings:
    EntityUrlTemplate = https://console.aws.amazon.com/elasticbeanstalk/r/application/{Config:ApplicationName}
    ExecutionUrlTemplate = https://console.aws.amazon.com/elasticbeanstalk/r/application/{Config:ApplicationName} 
For Category = Deploy, Owner = AWS, Provider = CodeDeploy, Version = 1:
  ActionConfigurationProperties:
    For ApplicationName:
      Description = The AWS CodeDeploy Application name
      Key = True
      Queryable = False
      Required = True
      Secret = False
    For DeploymentGroupName:
      Description = The AWS CodeDeploy Deployment Group name
      Key = True
      Queryable = False
      Required = True
      Secret = False
  InputArtifactDetails:
    MaximumCount = 1
    MinimumCount = 1
  OutputArtifactDetails:
    MaximumCount = 0
    MinimumCount = 0
  Settings:
    EntityUrlTemplate = https://console.aws.amazon.com/codedeploy/home?#/applications/{Config:ApplicationName}/deployment-groups/{Config:DeploymentGroupName}
    ExecutionUrlTemplate = https://console.aws.amazon.com/codedeploy/home?#/deployments/{ExternalExecutionId}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListActionTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CPActionableJobList`
<a name="codepipeline_PollForJobs_powershell_5_topic"></a>

次のコード例は、`Get-CPActionableJobList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアクションカテゴリ、所有者、プロバイダー、バージョン、およびクエリパラメータのすべての実行可能なジョブに関する情報を取得します。**  

```
Get-CPActionableJobList -ActionTypeId_Category Build -ActionTypeId_Owner Custom -ActionTypeId_Provider MyCustomProviderName -ActionTypeId_Version 1 -QueryParam @{"ProjectName" = "MyProjectName"}
```
**出力:**  

```
AccountId       Data                                 Id                                      Nonce
---------       ----                                 --                                      -----
80398EXAMPLE    Amazon.CodePipeline.Model.JobData    0de392f5-712d-4f41-ace3-f57a0EXAMPLE    3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PollForJobs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CPJobDetail`
<a name="codepipeline_GetJobDetails_powershell_5_topic"></a>

次のコード例は、`Get-CPJobDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたジョブに関する一般的な情報を取得します。**  

```
Get-CPJobDetail -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE
```
**出力:**  

```
AccountId       Data                                 Id
---------       ----                                 --
80398EXAMPLE    Amazon.CodePipeline.Model.JobData    f570dc12-5ef3-44bc-945a-6e133EXAMPLE
```
**例 2: この例では、指定されたジョブに関する詳細情報を取得します。**  

```
$jobDetails = Get-CPJobDetail -JobId f570dc12-5ef3-44bc-945a-6e133EXAMPLE
Write-Output ("For Job " + $jobDetails.Id + ":")
Write-Output ("  AccountId = " + $jobDetails.AccountId)
$jobData = $jobDetails.Data
Write-Output ("  Configuration:")
ForEach ($key in $jobData.ActionConfiguration.Keys) {
  $value = $jobData.ActionConfiguration.$key
  Write-Output ("    " + $key + " = " + $value)
}
Write-Output ("  ActionTypeId:")
Write-Output ("    Category = " + $jobData.ActionTypeId.Category)
Write-Output ("    Owner = " + $jobData.ActionTypeId.Owner)
Write-Output ("    Provider = " + $jobData.ActionTypeId.Provider)
Write-Output ("    Version = " + $jobData.ActionTypeId.Version)
Write-Output ("  ArtifactCredentials:")
Write-Output ("    AccessKeyId = " + $jobData.ArtifactCredentials.AccessKeyId)
Write-Output ("    SecretAccessKey = " + $jobData.ArtifactCredentials.SecretAccessKey)
Write-Output ("    SessionToken = " + $jobData.ArtifactCredentials.SessionToken)
Write-Output ("  InputArtifacts:")
ForEach ($ia in $jobData.InputArtifacts) {
  Write-Output ("    " + $ia.Name)
}
Write-Output ("  OutputArtifacts:")
ForEach ($oa in $jobData.OutputArtifacts) {
  Write-Output ("    " + $oa.Name)
}
Write-Output ("  PipelineContext:")
$context = $jobData.PipelineContext
Write-Output ("    Name = " + $context.Action.Name)
Write-Output ("    PipelineName = " + $context.PipelineName)
Write-Output ("    Stage = " + $context.Stage.Name)
```
**出力:**  

```
For Job f570dc12-5ef3-44bc-945a-6e133EXAMPLE:
  AccountId = 80398EXAMPLE
  Configuration:
  ActionTypeId:
    Category = Build
    Owner = Custom
    Provider = MyCustomProviderName
    Version = 1
  ArtifactCredentials:
    AccessKeyId = ASIAIEI3...IXI6YREX
    SecretAccessKey = cqAFDhEi...RdQyfa2u
    SessionToken = AQoDYXdz...5u+lsAU=
  InputArtifacts:
    MyApp
  OutputArtifacts:
    MyAppBuild
  PipelineContext:
    Name = Build
    PipelineName = CodePipelineDemo
    Stage = Build
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetJobDetails](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CPPipeline`
<a name="codepipeline_GetPipeline_powershell_5_topic"></a>

次のコード例は、`Get-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたパイプラインに関する一般的な情報を取得します。**  

```
Get-CPPipeline -Name CodePipelineDemo -Version 1
```
**出力:**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {Source, Build, Beta, TestStage}
Version       : 1
```
**例 2: この例では、指定されたパイプラインに関する詳細情報を取得します。**  

```
$pipeline = Get-CPPipeline -Name CodePipelineDemo
Write-Output ("Name = " + $pipeline.Name)
Write-Output ("RoleArn = " + $pipeline.RoleArn)
Write-Output ("Version = " + $pipeline.Version)
Write-Output ("ArtifactStore:")
Write-Output ("  Location = " + $pipeline.ArtifactStore.Location)
Write-Output ("  Type = " + $pipeline.ArtifactStore.Type.Value)
Write-Output ("Stages:")
ForEach ($stage in $pipeline.Stages) {
  Write-Output ("  Name = " + $stage.Name)
  Write-Output ("    Actions:")
  ForEach ($action in $stage.Actions) {
    Write-Output ("      Name = " + $action.Name)
	Write-Output ("        Category = " + $action.ActionTypeId.Category)
	Write-Output ("        Owner = " + $action.ActionTypeId.Owner)
	Write-Output ("        Provider = " + $action.ActionTypeId.Provider)
	Write-Output ("        Version = " + $action.ActionTypeId.Version)
	Write-Output ("        Configuration:")
	ForEach ($key in $action.Configuration.Keys) {
	  $value = $action.Configuration.$key
	  Write-Output ("          " + $key + " = " + $value)
	}
	Write-Output ("        InputArtifacts:")
	ForEach ($ia in $action.InputArtifacts) {
	  Write-Output ("          " + $ia.Name)
	}
	ForEach ($oa in $action.OutputArtifacts) {
	  Write-Output ("          " + $oa.Name)
	}
	Write-Output ("        RunOrder = " + $action.RunOrder)
  }
}
```
**出力:**  

```
Name = CodePipelineDemo
RoleArn = arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Version = 3
ArtifactStore:
  Location = amzn-s3-demo-bucket
  Type = S3
Stages:
  Name = Source
    Actions:
      Name = Source
        Category = Source
        Owner = ThirdParty
        Provider = GitHub
        Version = 1
        Configuration:
          Branch = master
          OAuthToken = ****
          Owner = my-user-name
          Repo = MyRepoName
        InputArtifacts:
          MyApp
        RunOrder = 1
  Name = Build
    Actions:
      Name = Build
        Category = Build
        Owner = Custom
        Provider = MyCustomProviderName
        Version = 1
        Configuration:
          ProjectName = MyProjectName
        InputArtifacts:
          MyApp
          MyAppBuild
        RunOrder = 1
  Name = Beta
    Actions:
      Name = CodePipelineDemoFleet
        Category = Deploy
        Owner = AWS
        Provider = CodeDeploy
        Version = 1
        Configuration:
          ApplicationName = CodePipelineDemoApplication
          DeploymentGroupName = CodePipelineDemoFleet
        InputArtifacts:
          MyAppBuild
        RunOrder = 1
  Name = TestStage
    Actions:
      Name = MyJenkinsTestAction
        Category = Test
        Owner = Custom
        Provider = MyCustomTestProvider
        Version = 1
        Configuration:
          ProjectName = MyJenkinsProjectName
        InputArtifacts:
          MyAppBuild
        RunOrder = 1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetPipeline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CPPipelineList`
<a name="codepipeline_ListPipelines_powershell_5_topic"></a>

次のコード例は、`Get-CPPipelineList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、使用可能なパイプラインのリストを取得します。**  

```
Get-CPPipelineList
```
**出力:**  

```
Created                  Name                Updated                  Version
-------                  ----                -------                  -------
8/13/2015 10:17:54 PM    CodePipelineDemo    8/13/2015 10:17:54 PM    3
7/8/2015 2:41:53 AM      MyFirstPipeline     7/22/2015 9:06:37 PM     7
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListPipelines](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CPPipelineState`
<a name="codepipeline_GetPipelineState_powershell_5_topic"></a>

次のコード例は、`Get-CPPipelineState` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたパイプラインのステージに関する一般的な情報を取得します。**  

```
Get-CPPipelineState -Name CodePipelineDemo
```
**出力:**  

```
Created         : 8/13/2015 10:17:54 PM
PipelineName    : CodePipelineDemo
PipelineVersion : 1
StageStates     : {Source, Build, Beta, TestStage}
Updated         : 8/13/2015 10:17:54 PM
```
**例 2: この例では、指定されたパイプラインの状態に関する詳細情報を取得します。**  

```
ForEach ($stageState in (Get-CPPipelineState -Name $arg).StageStates) {
  Write-Output ("For " + $stageState.StageName + ":")
  Write-Output ("  InboundTransitionState:")
  Write-Output ("    DisabledReason = " + $stageState.InboundTransitionState.DisabledReason)
  Write-Output ("    Enabled = " + $stageState.InboundTransitionState.Enabled)
  Write-Output ("    LastChangedAt = " + $stageState.InboundTransitionState.LastChangedAt)
  Write-Output ("    LastChangedBy = " + $stageState.InboundTransitionState.LastChangedBy)
  Write-Output ("  ActionStates:")
  ForEach ($actionState in $stageState.ActionStates) {
    Write-Output ("    For " + $actionState.ActionName + ":")
	Write-Output ("      CurrentRevision:")
    Write-Output ("        Created = " + $actionState.CurrentRevision.Created)
	Write-Output ("        RevisionChangeId = " + $actionState.CurrentRevision.RevisionChangeId)
	Write-Output ("        RevisionId = " + $actionState.CurrentRevision.RevisionId)
	Write-Output ("      EntityUrl = " + $actionState.EntityUrl)
	Write-Output ("      LatestExecution:")
    Write-Output ("        ErrorDetails:")
    Write-Output ("          Code = " + $actionState.LatestExecution.ErrorDetails.Code)
	Write-Output ("          Message = " + $actionState.LatestExecution.ErrorDetails.Message)
	Write-Output ("        ExternalExecutionId = " + $actionState.LatestExecution.ExternalExecutionId)
	Write-Output ("        ExternalExecutionUrl = " + $actionState.LatestExecution.ExternalExecutionUrl)
	Write-Output ("        LastStatusChange	= " + $actionState.LatestExecution.LastStatusChange)
	Write-Output ("        PercentComplete = " + $actionState.LatestExecution.PercentComplete)
	Write-Output ("        Status = " + $actionState.LatestExecution.Status)
	Write-Output ("        Summary = " + $actionState.LatestExecution.Summary)
	Write-Output ("      RevisionUrl = " + $actionState.RevisionUrl)
  }
}
```
**出力:**  

```
For Source:
  InboundTransitionState:
    DisabledReason =
    Enabled =
    LastChangedAt =
    LastChangedBy =
  ActionStates:
    For Source:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = https://github.com/my-user-name/MyRepoName/tree/master
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId =
        ExternalExecutionUrl =
        LastStatusChange = 07/20/2015 23:28:45
        PercentComplete = 0
        Status = Succeeded
        Summary =
      RevisionUrl =
For Build:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For Build:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = http://54.174.131.1EX/job/MyJenkinsDemo
      LatestExecution:
        ErrorDetails:
          Code = TimeoutError
          Message = The action failed because a job worker exceeded its time limit. If this is a custom action, make sure that the job worker is configured correctly.
        ExternalExecutionId =
        ExternalExecutionUrl =
        LastStatusChange = 07/21/2015 00:29:29
        PercentComplete = 0
        Status = Failed
        Summary =
      RevisionUrl =
For Beta:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For CodePipelineDemoFleet:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = https://console.aws.amazon.com/codedeploy/home?#/applications/CodePipelineDemoApplication/deployment-groups/CodePipelineDemoFleet
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId = d-D5LTCZXEX
        ExternalExecutionUrl = https://console.aws.amazon.com/codedeploy/home?#/deployments/d-D5LTCZXEX
        LastStatusChange = 07/08/2015 22:07:42
        PercentComplete = 0
        Status = Succeeded
        Summary = Deployment Succeeded
      RevisionUrl =
For TestStage:
  InboundTransitionState:
    DisabledReason =
    Enabled = True
    LastChangedAt = 01/01/0001 00:00:00
    LastChangedBy =
  ActionStates:
    For MyJenkinsTestAction25:
      CurrentRevision:
        Created =
        RevisionChangeId =
        RevisionId =
      EntityUrl = http://54.174.131.1EX/job/MyJenkinsDemo
      LatestExecution:
        ErrorDetails:
          Code =
          Message =
        ExternalExecutionId = 5
        ExternalExecutionUrl = http://54.174.131.1EX/job/MyJenkinsDemo/5
        LastStatusChange = 07/08/2015 22:09:03
        PercentComplete = 0
        Status = Succeeded
        Summary = Finished
      RevisionUrl =
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetPipelineState](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CPCustomActionType`
<a name="codepipeline_CreateCustomActionType_powershell_5_topic"></a>

次のコード例は、`New-CPCustomActionType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたプロパティを使用して新しいカスタムアクションを作成します。**  

```
New-CPCustomActionType -Category Build -ConfigurationProperty @{"Description" = "The name of the build project must be provided when this action is added to the pipeline."; "Key" = $True; "Name" = "ProjectName"; "Queryable" = $False; "Required" = $True; "Secret" = $False; "Type" = "String"} -Settings_EntityUrlTemplate "https://my-build-instance/job/{Config:ProjectName}/" -Settings_ExecutionUrlTemplate "https://my-build-instance/job/mybuildjob/lastSuccessfulBuild{ExternalExecutionId}/" -InputArtifactDetails_MaximumCount 1 -OutputArtifactDetails_MaximumCount 1 -InputArtifactDetails_MinimumCount 0 -OutputArtifactDetails_MinimumCount 0 -Provider "MyBuildProviderName" -Version 1
```
**出力:**  

```
ActionConfigurationProperties : {ProjectName}
Id                            : Amazon.CodePipeline.Model.ActionTypeId
InputArtifactDetails          : Amazon.CodePipeline.Model.ArtifactDetails
OutputArtifactDetails         : Amazon.CodePipeline.Model.ArtifactDetails
Settings                      : Amazon.CodePipeline.Model.ActionTypeSettings
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateCustomActionType](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CPPipeline`
<a name="codepipeline_CreatePipeline_powershell_5_topic"></a>

次のコード例は、`New-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された設定で新しいパイプラインを作成します。**  

```
$pipeline = New-Object Amazon.CodePipeline.Model.PipelineDeclaration

$sourceStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration
$deployStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration

$sourceStageActionOutputArtifact = New-Object Amazon.CodePipeline.Model.OutputArtifact
$sourceStageActionOutputArtifact.Name = "MyApp"

$sourceStageAction.ActionTypeId = @{"Category" = "Source"; "Owner" = "AWS"; "Provider" = "S3"; "Version" = 1}
$sourceStageAction.Configuration.Add("S3Bucket", "amzn-s3-demo-bucket")
$sourceStageAction.Configuration.Add("S3ObjectKey", "my-object-key-name.zip")
$sourceStageAction.OutputArtifacts.Add($sourceStageActionOutputArtifact)
$sourceStageAction.Name = "Source"

$deployStageActionInputArtifact = New-Object Amazon.CodePipeline.Model.InputArtifact
$deployStageActionInputArtifact.Name = "MyApp"

$deployStageAction.ActionTypeId = @{"Category" = "Deploy"; "Owner" = "AWS"; "Provider" = "CodeDeploy"; "Version" = 1}
$deployStageAction.Configuration.Add("ApplicationName", "CodePipelineDemoApplication")
$deployStageAction.Configuration.Add("DeploymentGroupName", "CodePipelineDemoFleet")
$deployStageAction.InputArtifacts.Add($deployStageActionInputArtifact)
$deployStageAction.Name = "CodePipelineDemoFleet"

$sourceStage = New-Object Amazon.CodePipeline.Model.StageDeclaration
$deployStage = New-Object Amazon.CodePipeline.Model.StageDeclaration

$sourceStage.Name = "Source"
$deployStage.Name = "Beta"

$sourceStage.Actions.Add($sourceStageAction)
$deployStage.Actions.Add($deployStageAction)

$pipeline.ArtifactStore = @{"Location" = "amzn-s3-demo-bucket"; "Type" = "S3"}
$pipeline.Name = "CodePipelineDemo"
$pipeline.RoleArn = "arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole"
$pipeline.Stages.Add($sourceStage)
$pipeline.Stages.Add($deployStage)
$pipeline.Version = 1

New-CPPipeline -Pipeline $pipeline
```
**出力:**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {Source, Beta}
Version       : 1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreatePipeline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CPCustomActionType`
<a name="codepipeline_DeleteCustomActionType_powershell_5_topic"></a>

次のコード例は、`Remove-CPCustomActionType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したカスタムアクションを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでカスタムアクションを削除します。**  

```
Remove-CPCustomActionType -Category Build -Provider MyBuildProviderName -Version 1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteCustomActionType](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CPPipeline`
<a name="codepipeline_DeletePipeline_powershell_5_topic"></a>

次のコード例は、`Remove-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたパイプラインを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force パラメータを追加して、プロンプトなしでパイプラインを削除します。**  

```
Remove-CPPipeline -Name CodePipelineDemo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeletePipeline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-CPPipelineExecution`
<a name="codepipeline_StartPipelineExecution_powershell_5_topic"></a>

次のコード例は、`Start-CPPipelineExecution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたパイプラインの実行を開始します。**  

```
Start-CPPipelineExecution -Name CodePipelineDemo
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StartPipelineExecution](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CPPipeline`
<a name="codepipeline_UpdatePipeline_powershell_5_topic"></a>

次のコード例は、`Update-CPPipeline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された設定で指定された既存のパイプラインを更新します。**  

```
$pipeline = New-Object Amazon.CodePipeline.Model.PipelineDeclaration

$sourceStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration
$deployStageAction = New-Object Amazon.CodePipeline.Model.ActionDeclaration

$sourceStageActionOutputArtifact = New-Object Amazon.CodePipeline.Model.OutputArtifact
$sourceStageActionOutputArtifact.Name = "MyApp"

$sourceStageAction.ActionTypeId = @{"Category" = "Source"; "Owner" = "AWS"; "Provider" = "S3"; "Version" = 1}
$sourceStageAction.Configuration.Add("S3Bucket", "amzn-s3-demo-bucket")
$sourceStageAction.Configuration.Add("S3ObjectKey", "my-object-key-name.zip")
$sourceStageAction.OutputArtifacts.Add($sourceStageActionOutputArtifact)
$sourceStageAction.Name = "Source"

$deployStageActionInputArtifact = New-Object Amazon.CodePipeline.Model.InputArtifact
$deployStageActionInputArtifact.Name = "MyApp"

$deployStageAction.ActionTypeId = @{"Category" = "Deploy"; "Owner" = "AWS"; "Provider" = "CodeDeploy"; "Version" = 1}
$deployStageAction.Configuration.Add("ApplicationName", "CodePipelineDemoApplication")
$deployStageAction.Configuration.Add("DeploymentGroupName", "CodePipelineDemoFleet")
$deployStageAction.InputArtifacts.Add($deployStageActionInputArtifact)
$deployStageAction.Name = "CodePipelineDemoFleet"

$sourceStage = New-Object Amazon.CodePipeline.Model.StageDeclaration
$deployStage = New-Object Amazon.CodePipeline.Model.StageDeclaration

$sourceStage.Name = "MyInputFiles"
$deployStage.Name = "MyTestDeployment"

$sourceStage.Actions.Add($sourceStageAction)
$deployStage.Actions.Add($deployStageAction)

$pipeline.ArtifactStore = @{"Location" = "amzn-s3-demo-bucket"; "Type" = "S3"}
$pipeline.Name = "CodePipelineDemo"
$pipeline.RoleArn = "arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole"
$pipeline.Stages.Add($sourceStage)
$pipeline.Stages.Add($deployStage)
$pipeline.Version = 1

Update-CPPipeline -Pipeline $pipeline
```
**出力:**  

```
ArtifactStore : Amazon.CodePipeline.Model.ArtifactStore
Name          : CodePipelineDemo
RoleArn       : arn:aws:iam::80398EXAMPLE:role/CodePipelineServiceRole
Stages        : {InputFiles, TestDeployment}
Version       : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdatePipeline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Amazon Cognito ID の例
<a name="powershell_5_cognito-identity_code_examples"></a>

次のコード例は、Amazon Cognito Identity で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-CGIIdentityPool`
<a name="cognito-identity_DescribeIdentityPool_powershell_5_topic"></a>

次のコード例は、`Get-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 特定のアイデンティティプールに関する情報をその ID を用いて取得します。**  

```
Get-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
**出力:**  

```
LoggedAt                       : 8/12/2015 4:29:40 PM
AllowUnauthenticatedIdentities : True
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
IdentityPoolName               : CommonTests1
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 142
HttpStatusCode                 : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CGIIdentityPoolList`
<a name="cognito-identity_ListIdentityPools_powershell_5_topic"></a>

次のコード例は、`Get-CGIIdentityPoolList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 既存のアイデンティティプールのリストを取得します。**  

```
Get-CGIIdentityPoolList
```
**出力:**  

```
IdentityPoolId                                                     IdentityPoolName
--------------                                                     ----------------
us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1                     CommonTests1
us-east-1:118d242d-204e-4b88-b803-EXAMPLEGUID2                     Tests2
us-east-1:15d49393-ab16-431a-b26e-EXAMPLEGUID3                     CommonTests13
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListIdentityPools](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CGIIdentityPoolRole`
<a name="cognito-identity_GetIdentityPoolRoles_powershell_5_topic"></a>

次のコード例は、`Get-CGIIdentityPoolRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 特定のアイデンティティプールのロールに関する情報を取得します。**  

```
Get-CGIIdentityPoolRole -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
**出力:**  

```
LoggedAt         : 8/12/2015 4:33:51 PM
IdentityPoolId   : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
Roles            : {[unauthenticated, arn:aws:iam::123456789012:role/CommonTests1Role]}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 165
HttpStatusCode   : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-CGIIdentityPool`
<a name="cognito-identity_CreateIdentityPool_powershell_5_topic"></a>

次のコード例は、`New-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 認証されていない ID を許可する新しいアイデンティティプールを作成します。**  

```
New-CGIIdentityPool -AllowUnauthenticatedIdentities $true -IdentityPoolName CommonTests13
```
**出力:**  

```
LoggedAt                       : 8/12/2015 4:56:07 PM
AllowUnauthenticatedIdentities : True
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:15d49393-ab16-431a-b26e-EXAMPLEGUID3
IdentityPoolName               : CommonTests13
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 136
HttpStatusCode                 : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-CGIIdentityPool`
<a name="cognito-identity_DeleteIdentityPool_powershell_5_topic"></a>

次のコード例は、`Remove-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 特定のアイデンティティプールを削除します。**  

```
Remove-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-CGIIdentityPoolRole`
<a name="cognito-identity_SetIdentityPoolRoles_powershell_5_topic"></a>

次のコード例は、`Set-CGIIdentityPoolRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 認証されていない IAM ロールを持つように特定のアイデンティティプールを設定します。**  

```
Set-CGIIdentityPoolRole -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1 -Role @{ "unauthenticated" = "arn:aws:iam::123456789012:role/CommonTests1Role" }
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SetIdentityPoolRoles](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-CGIIdentityPool`
<a name="cognito-identity_UpdateIdentityPool_powershell_5_topic"></a>

次のコード例は、`Update-CGIIdentityPool` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: アイデンティティプールプロパティの一部を更新します。この場合、アイデンティティプールの名前を更新します。**  

```
Update-CGIIdentityPool -IdentityPoolId us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1 -IdentityPoolName NewPoolName
```
**出力:**  

```
LoggedAt                       : 8/12/2015 4:53:33 PM
AllowUnauthenticatedIdentities : False
DeveloperProviderName          :
IdentityPoolId                 : us-east-1:0de2af35-2988-4d0b-b22d-EXAMPLEGUID1
IdentityPoolName               : NewPoolName
OpenIdConnectProviderARNs      : {}
SupportedLoginProviders        : {}
ResponseMetadata               : Amazon.Runtime.ResponseMetadata
ContentLength                  : 135
HttpStatusCode                 : OK
```
+  API の詳細については、「*AWS Tools for PowerShell Cmdlet Reference (V5)*」の「[UpdateIdentityPool](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# AWS Config Tools for PowerShell V5 を使用した の例
<a name="powershell_5_config-service_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Config。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-CFGResourceTag`
<a name="config-service_TagResource_powershell_5_topic"></a>

次のコード例は、`Add-CFGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定タグをリソース ARN に関連付けます。この場合、リソース ARN は config-rule/config-rule-16iyn0 です。**  

```
Add-CFGResourceTag -ResourceArn arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-16iyn0 -Tag @{Key="Release";Value="Beta"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[TagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregateComplianceByConfigRuleList`
<a name="config-service_DescribeAggregateComplianceByConfigRules_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregateComplianceByConfigRuleList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定の設定ルールの詳細を ConfigurationAggregatorの「kaju」フィルタリングから取得して、ルールの「コンプライアンス」を展開/返します。**  

```
Get-CFGAggregateComplianceByConfigRuleList -ConfigurationAggregatorName kaju -Filters_ConfigRuleName ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK | Select-Object -ExpandProperty Compliance
```
**出力:**  

```
ComplianceContributorCount                            ComplianceType
--------------------------                            --------------
Amazon.ConfigService.Model.ComplianceContributorCount NON_COMPLIANT
```
**例 2: この例では、指定の ConfigurationAggregator から詳細を取得し、アグリゲータの対象となるすべてのリージョンの指定アカウントに対してフィルタリングして、さらにすべてのルールのコンプライアンスを返します。**  

```
Get-CFGAggregateComplianceByConfigRuleList -ConfigurationAggregatorName kaju -Filters_AccountId 123456789012 | Select-Object ConfigRuleName, @{N="Compliance";E={$_.Compliance.ComplianceType}}
```
**出力:**  

```
ConfigRuleName                      Compliance
--------------                      ----------
ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK NON_COMPLIANT
ec2-instance-no-public-ip           NON_COMPLIANT
desired-instance-type               NON_COMPLIANT
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAggregateComplianceByConfigRules](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregateComplianceDetailsByConfigRule`
<a name="config-service_GetAggregateComplianceDetailsByConfigRule_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregateComplianceDetailsByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアカウント、アグリゲータ、リージョン、および設定ルールの「COMPLIANT」状態にある AWS Config ルールdesired-instance-type」の resource-id と resource-type の出力を選択する評価結果を返します。**  

```
Get-CFGAggregateComplianceDetailsByConfigRule -AccountId 123456789012 -AwsRegion eu-west-1 -ComplianceType COMPLIANT -ConfigRuleName desired-instance-type -ConfigurationAggregatorName raju | Select-Object -ExpandProperty EvaluationResultIdentifier | Select-Object -ExpandProperty EvaluationResultQualifier
```
**出力:**  

```
ConfigRuleName        ResourceId          ResourceType
--------------        ----------          ------------
desired-instance-type i-0f1bf2f34c5678d12 AWS::EC2::Instance
desired-instance-type i-0fd12dd3456789123 AWS::EC2::Instance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetAggregateComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregateConfigRuleComplianceSummary`
<a name="config-service_GetAggregateConfigRuleComplianceSummary_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregateConfigRuleComplianceSummary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定アグリゲータの非準拠ルールの数を返します。**  

```
(Get-CFGAggregateConfigRuleComplianceSummary -ConfigurationAggregatorName raju).AggregateComplianceCounts.ComplianceSummary.NonCompliantResourceCount
```
**出力:**  

```
CapExceeded CappedCount
----------- -----------
False       5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetAggregateConfigRuleComplianceSummary](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregateDiscoveredResourceCount`
<a name="config-service_GetAggregateDiscoveredResourceCounts_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregateDiscoveredResourceCount` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、us-east-1 リージョンでフィルタリングされた指定アグリゲータのリソース数を返します。**  

```
Get-CFGAggregateDiscoveredResourceCount -ConfigurationAggregatorName Master -Filters_Region us-east-1
```
**出力:**  

```
GroupByKey GroupedResourceCounts NextToken TotalDiscoveredResources
---------- --------------------- --------- ------------------------
           {}                              455
```
**例 2: この例では、特定のアグリゲータのフィルタリングされたリージョンの RESOURCE\$1TYPE 別にグループ化されたリソース数を返します。**  

```
Get-CFGAggregateDiscoveredResourceCount -ConfigurationAggregatorName Master -Filters_Region us-east-1 -GroupByKey RESOURCE_TYPE | 
			Select-Object -ExpandProperty GroupedResourceCounts
```
**出力:**  

```
GroupName                          ResourceCount
---------                          -------------
AWS::CloudFormation::Stack         12
AWS::CloudFront::Distribution      1
AWS::CloudTrail::Trail             1
AWS::DynamoDB::Table               1
AWS::EC2::EIP                      2
AWS::EC2::FlowLog                  2
AWS::EC2::InternetGateway          4
AWS::EC2::NatGateway               2
AWS::EC2::NetworkAcl               4
AWS::EC2::NetworkInterface         12
AWS::EC2::RouteTable               13
AWS::EC2::SecurityGroup            18
AWS::EC2::Subnet                   16
AWS::EC2::VPC                      4
AWS::EC2::VPCEndpoint              2
AWS::EC2::VPCPeeringConnection     1
AWS::IAM::Group                    2
AWS::IAM::Policy                   51
AWS::IAM::Role                     78
AWS::IAM::User                     7
AWS::Lambda::Function              3
AWS::RDS::DBSecurityGroup          1
AWS::S3::Bucket                    3
AWS::SSM::AssociationCompliance    107
AWS::SSM::ManagedInstanceInventory 108
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetAggregateDiscoveredResourceCounts](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregateDiscoveredResourceList`
<a name="config-service_ListAggregateDiscoveredResources_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregateDiscoveredResourceList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「アイルランド」アグリゲータで集約された指定リソースタイプのリソース ID を返します。リソースタイプのリストについては、https://docs.aws.amazon.com/sdkfornet/v4/apidocs/index.html?page=ConfigService/TConfigServiceResourceType.html&tocid=Amazon\$1ConfigService\$1ResourceType を確認してください。**  

```
Get-CFGAggregateDiscoveredResourceList -ConfigurationAggregatorName Ireland -ResourceType ([Amazon.ConfigService.ResourceType]::AWSAutoScalingAutoScalingGroup)
```
**出力:**  

```
ResourceId      : arn:aws:autoscaling:eu-west-1:123456789012:autoScalingGroup:12e3b4fc-1234-1234-a123-1d2ba3c45678:autoScalingGroupName/asg-1
ResourceName    : asg-1
ResourceType    : AWS::AutoScaling::AutoScalingGroup
SourceAccountId : 123456789012
SourceRegion    : eu-west-1
```
**例 2: この例では、us-east-1 リージョンでフィルタリングされた指定アグリゲータの「default」という名前のリソースタイプ `AwsEC2SecurityGroup` を返します。**  

```
Get-CFGAggregateDiscoveredResourceList -ConfigurationAggregatorName raju -ResourceType ([Amazon.ConfigService.ResourceType]::AWSEC2SecurityGroup) -Filters_Region us-east-1 -Filters_ResourceName default
```
**出力:**  

```
ResourceId      : sg-01234bd5dbfa67c89
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1

ResourceId      : sg-0123a4ebbf56789be
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1

ResourceId      : sg-4fc1d234
ResourceName    : default
ResourceType    : AWS::EC2::SecurityGroup
SourceAccountId : 123456789102
SourceRegion    : us-east-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListAggregateDiscoveredResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregateResourceConfig`
<a name="config-service_GetAggregateResourceconfig-service_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregateResourceConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、集約された指定リソースの設定項目を返して、設定を展開します。**  

```
(Get-CFGAggregateResourceConfig -ResourceIdentifier_SourceRegion us-east-1 -ResourceIdentifier_SourceAccountId 123456789012 -ResourceIdentifier_ResourceId sg-4fc1d234 -ResourceIdentifier_ResourceType ([Amazon.ConfigService.ResourceType]::AWSEC2SecurityGroup) -ConfigurationAggregatorName raju).Configuration | ConvertFrom-Json
```
**出力:**  

```
{"description":"default VPC security group","groupName":"default","ipPermissions":[{"ipProtocol":"-1","ipv6Ranges":[],"prefixListIds":[],"userIdGroupPairs":[{"groupId":"sg-4fc1d234","userId":"123456789012"}],"ipv4Ranges":[],"ipRanges":[]},{"fromPort":3389,"ipProtocol":"tcp","ipv6Ranges":[],"prefixListIds":[],"toPort":3389,"userIdGroupPairs":[],"ipv4Ranges":[{"cidrIp":"54.240.197.224/29","description":"office subnet"},{"cidrIp":"72.21.198.65/32","description":"home pc"}],"ipRanges":["54.240.197.224/29","72.21.198.65/32"]}],"ownerId":"123456789012","groupId":"sg-4fc1d234","ipPermissionsEgress":[{"ipProtocol":"-1","ipv6Ranges":[],"prefixListIds":[],"userIdGroupPairs":[],"ipv4Ranges":[{"cidrIp":"0.0.0.0/0"}],"ipRanges":["0.0.0.0/0"]}],"tags":[],"vpcId":"vpc-2d1c2e34"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetAggregateResourceconfig-service](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregateResourceConfigBatch`
<a name="config-service_BatchGetAggregateResourceconfig-service_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregateResourceConfigBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定アグリゲータに存在するリソース (識別済み) の現在の設定項目を取得します。**  

```
$resIdentifier=[Amazon.ConfigService.Model.AggregateResourceIdentifier]@{
		ResourceId= "i-012e3cb4df567e8aa"
		ResourceName = "arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa"
		ResourceType = [Amazon.ConfigService.ResourceType]::AWSEC2Instance
		SourceAccountId = "123456789012"
		SourceRegion = "eu-west-1"
	}
		
	Get-CFGAggregateResourceConfigBatch -ResourceIdentifier $resIdentifier -ConfigurationAggregatorName raju
```
**出力:**  

```
BaseConfigurationItems UnprocessedResourceIdentifiers
---------------------- ------------------------------
{}                     {arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchGetAggregateResourceconfig-service](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGAggregationAuthorizationList`
<a name="config-service_DescribeAggregationAuthorizations_powershell_5_topic"></a>

次のコード例は、`Get-CFGAggregationAuthorizationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アグリゲータに付与された認証を取得します。**  

```
Get-CFGAggregationAuthorizationList
```
**出力:**  

```
AggregationAuthorizationArn                                                            AuthorizedAccountId AuthorizedAwsRegion CreationTime
---------------------------                                                            ------------------- ------------------- ------------
arn:aws:config-service:eu-west-1:123456789012:aggregation-authorization/123456789012/eu-west-1 123456789012        eu-west-1           8/26/2019 12:55:27 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAggregationAuthorizations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGComplianceByConfigRule`
<a name="config-service_DescribeComplianceByConfigRule_powershell_5_topic"></a>

次のコード例は、`Get-CFGComplianceByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ルールの現在の評価結果がないため、INSUFFICIENT\$1DATA が返されるルール ebs-optimized-instance のコンプライアンスの詳細を取得します。**  

```
(Get-CFGComplianceByConfigRule -ConfigRuleName ebs-optimized-instance).Compliance
```
**出力:**  

```
ComplianceContributorCount ComplianceType
-------------------------- --------------
                           INSUFFICIENT_DATA
```
**例 2: この例では、ルール ALB\$1HTTP\$1TO\$1HTTPS\$1REDIRECTION\$1CHECK の非準拠リソースの数を返します。**  

```
(Get-CFGComplianceByConfigRule -ConfigRuleName ALB_HTTP_TO_HTTPS_REDIRECTION_CHECK -ComplianceType NON_COMPLIANT).Compliance.ComplianceContributorCount
```
**出力:**  

```
CapExceeded CappedCount
----------- -----------
False       2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeComplianceByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGComplianceByResource`
<a name="config-service_DescribeComplianceByResource_powershell_5_topic"></a>

次のコード例は、`Get-CFGComplianceByResource` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「COMPLIANT」コンプライアンスタイプの `AWS::SSM::ManagedInstanceInventory` リソースタイプを確認します。**  

```
Get-CFGComplianceByResource -ComplianceType COMPLIANT -ResourceType AWS::SSM::ManagedInstanceInventory
```
**出力:**  

```
Compliance                            ResourceId          ResourceType
----------                            ----------          ------------
Amazon.ConfigService.Model.Compliance i-0123bcf4b567890e3 AWS::SSM::ManagedInstanceInventory
Amazon.ConfigService.Model.Compliance i-0a1234f6f5d6b78f7 AWS::SSM::ManagedInstanceInventory
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeComplianceByResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGComplianceDetailsByConfigRule`
<a name="config-service_GetComplianceDetailsByConfigRule_powershell_5_topic"></a>

次のコード例は、`Get-CFGComplianceDetailsByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ルール access-keys-rotated の評価結果を取得し、コンプライアンスタイプ別にグループ化された出力を返します。**  

```
Get-CFGComplianceDetailsByConfigRule -ConfigRuleName access-keys-rotated | Group-Object ComplianceType
```
**出力:**  

```
Count Name                      Group
----- ----                      -----
    2 COMPLIANT                 {Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationResult}
    5 NON_COMPLIANT             {Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationResult, Amazon.ConfigService.Model.EvaluationRes...
```
**例 2: この例では、COMPLIANT リソースの access-keys-rotated ルールのコンプライアンスの詳細をクエリします。**  

```
Get-CFGComplianceDetailsByConfigRule -ConfigRuleName access-keys-rotated -ComplianceType COMPLIANT | ForEach-Object {$_.EvaluationResultIdentifier.EvaluationResultQualifier}
```
**出力:**  

```
ConfigRuleName      ResourceId            ResourceType
--------------      ----------            ------------
access-keys-rotated BCAB1CDJ2LITAPVEW3JAH AWS::IAM::User
access-keys-rotated BCAB1CDJ2LITL3EHREM4Q AWS::IAM::User
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetComplianceDetailsByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGComplianceDetailsByResource`
<a name="config-service_GetComplianceDetailsByResource_powershell_5_topic"></a>

次のコード例は、`Get-CFGComplianceDetailsByResource` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリソースについて次のような結果が出ました。**  

```
Get-CFGComplianceDetailsByResource -ResourceId ABCD5STJ4EFGHIVEW6JAH -ResourceType 'AWS::IAM::User'
```
**出力:**  

```
Annotation                 :
ComplianceType             : COMPLIANT
ConfigRuleInvokedTime      : 8/25/2019 11:34:56 PM
EvaluationResultIdentifier : Amazon.ConfigService.Model.EvaluationResultIdentifier
ResultRecordedTime         : 8/25/2019 11:34:56 PM
ResultToken                :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetComplianceDetailsByResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGComplianceSummaryByConfigRule`
<a name="config-service_GetComplianceSummaryByConfigRule_powershell_5_topic"></a>

次のコード例は、`Get-CFGComplianceSummaryByConfigRule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、非準拠の Config ルールの数を返します。**  

```
Get-CFGComplianceSummaryByConfigRule -Select ComplianceSummary.NonCompliantResourceCount
```
**出力:**  

```
CapExceeded CappedCount
----------- -----------
False       9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetComplianceSummaryByConfigRule](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGComplianceSummaryByResourceType`
<a name="config-service_GetComplianceSummaryByResourceType_powershell_5_topic"></a>

次のコード例は、`Get-CFGComplianceSummaryByResourceType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、準拠または非準拠のリソースの数を返し、出力を json に変換します。**  

```
Get-CFGComplianceSummaryByResourceType -Select ComplianceSummariesByResourceType.ComplianceSummary | ConvertTo-Json
{
  "ComplianceSummaryTimestamp": "2019-12-14T06:14:49.778Z",
  "CompliantResourceCount": {
    "CapExceeded": false,
    "CappedCount": 2
  },
  "NonCompliantResourceCount": {
    "CapExceeded": true,
    "CappedCount": 100
  }
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetComplianceSummaryByResourceType](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGConfigRule`
<a name="config-service_DescribeConfigRules_powershell_5_topic"></a>

次のコード例は、`Get-CFGConfigRule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、選択したプロパティを持つアカウントの設定ルールを一覧表示します。**  

```
Get-CFGConfigRule | Select-Object ConfigRuleName, ConfigRuleId, ConfigRuleArn, ConfigRuleState
```
**出力:**  

```
ConfigRuleName                                    ConfigRuleId       ConfigRuleArn                                                        ConfigRuleState
--------------                                    ------------       -------------                                                        ---------------
ALB_REDIRECTION_CHECK                             config-rule-12iyn3 arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-12iyn3 ACTIVE
access-keys-rotated                               config-rule-aospfr arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-aospfr ACTIVE
autoscaling-group-elb-healthcheck-required        config-rule-cn1f2x arn:aws:config-service:eu-west-1:123456789012:config-rule/config-rule-cn1f2x ACTIVE
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConfigRules](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGConfigRuleEvaluationStatus`
<a name="config-service_DescribeConfigRuleEvaluationStatus_powershell_5_topic"></a>

次のコード例は、`Get-CFGConfigRuleEvaluationStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定された設定ルールのステータス情報を返します。**  

```
Get-CFGConfigRuleEvaluationStatus -ConfigRuleName root-account-mfa-enabled, vpc-flow-logs-enabled
```
**出力:**  

```
ConfigRuleArn                : arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-kvq1wk
ConfigRuleId                 : config-rule-kvq1wk
ConfigRuleName               : root-account-mfa-enabled
FirstActivatedTime           : 8/27/2019 8:05:17 AM
FirstEvaluationStarted       : True
LastErrorCode                :
LastErrorMessage             :
LastFailedEvaluationTime     : 1/1/0001 12:00:00 AM
LastFailedInvocationTime     : 1/1/0001 12:00:00 AM
LastSuccessfulEvaluationTime : 12/13/2019 8:12:03 AM
LastSuccessfulInvocationTime : 12/13/2019 8:12:03 AM

ConfigRuleArn                : arn:aws:config:eu-west-1:123456789012:config-rule/config-rule-z1s23b
ConfigRuleId                 : config-rule-z1s23b
ConfigRuleName               : vpc-flow-logs-enabled
FirstActivatedTime           : 8/14/2019 6:23:44 AM
FirstEvaluationStarted       : True
LastErrorCode                :
LastErrorMessage             :
LastFailedEvaluationTime     : 1/1/0001 12:00:00 AM
LastFailedInvocationTime     : 1/1/0001 12:00:00 AM
LastSuccessfulEvaluationTime : 12/13/2019 7:12:01 AM
LastSuccessfulInvocationTime : 12/13/2019 7:12:01 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConfigRuleEvaluationStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGConfigurationAggregatorList`
<a name="config-service_DescribeConfigurationAggregators_powershell_5_topic"></a>

次のコード例は、`Get-CFGConfigurationAggregatorList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リージョン/アカウントのすべてのアグリゲータを返します。**  

```
Get-CFGConfigurationAggregatorList
```
**出力:**  

```
AccountAggregationSources     : {Amazon.ConfigService.Model.AccountAggregationSource}
ConfigurationAggregatorArn    : arn:aws:config-service:eu-west-1:123456789012:config-aggregator/config-aggregator-xabca1me
ConfigurationAggregatorName   : IrelandMaster
CreationTime                  : 8/25/2019 11:42:39 PM
LastUpdatedTime               : 8/25/2019 11:42:39 PM
OrganizationAggregationSource :

AccountAggregationSources     : {}
ConfigurationAggregatorArn    : arn:aws:config-service:eu-west-1:123456789012:config-aggregator/config-aggregator-qubqabcd
ConfigurationAggregatorName   : raju
CreationTime                  : 8/11/2019 8:39:25 AM
LastUpdatedTime               : 8/11/2019 8:39:25 AM
OrganizationAggregationSource : Amazon.ConfigService.Model.OrganizationAggregationSource
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConfigurationAggregators](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGConfigurationAggregatorSourcesStatus`
<a name="config-service_DescribeConfigurationAggregatorSourcesStatus_powershell_5_topic"></a>

次のコード例は、`Get-CFGConfigurationAggregatorSourcesStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定アグリゲータ内のソースに対してリクエストされたフィールドを表示します。**  

```
Get-CFGConfigurationAggregatorSourcesStatus -ConfigurationAggregatorName raju | select SourceType, LastUpdateStatus, LastUpdateTime, SourceId
```
**出力:**  

```
SourceType   LastUpdateStatus LastUpdateTime        SourceId
----------   ---------------- --------------        --------
ORGANIZATION SUCCEEDED        12/31/2019 7:45:06 AM Organization
ACCOUNT      SUCCEEDED        12/31/2019 7:09:38 AM 612641234567
ACCOUNT      SUCCEEDED        12/31/2019 7:12:53 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:18:10 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:25:17 AM 933301234567
ACCOUNT      SUCCEEDED        12/31/2019 7:25:49 AM 612641234567
ACCOUNT      SUCCEEDED        12/31/2019 7:26:11 AM 612641234567
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConfigurationAggregatorSourcesStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGConfigurationRecorder`
<a name="config-service_DescribeConfigurationRecorders_powershell_5_topic"></a>

次のコード例は、`Get-CFGConfigurationRecorder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、設定レコーダーの詳細を返します。**  

```
Get-CFGConfigurationRecorder | Format-List
```
**出力:**  

```
Name           : default
RecordingGroup : Amazon.ConfigService.Model.RecordingGroup
RoleARN        : arn:aws:iam::123456789012:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConfigurationRecorders](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGConfigurationRecorderStatus`
<a name="config-service_DescribeConfigurationRecorderStatus_powershell_5_topic"></a>

次のコード例は、`Get-CFGConfigurationRecorderStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、設定レコーダーのステータスを返します。**  

```
Get-CFGConfigurationRecorderStatus
```
**出力:**  

```
LastErrorCode        :
LastErrorMessage     :
LastStartTime        : 10/11/2019 10:13:51 AM
LastStatus           : Success
LastStatusChangeTime : 12/31/2019 6:14:12 AM
LastStopTime         : 10/11/2019 10:13:46 AM
Name                 : default
Recording            : True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConfigurationRecorderStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGConformancePack`
<a name="config-service_DescribeConformancePacks_powershell_5_topic"></a>

次のコード例は、`Get-CFGConformancePack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべての適合パックを一覧表示します。**  

```
Get-CFGConformancePack
```
**出力:**  

```
ConformancePackArn             : arn:aws:config:eu-west-1:123456789012:conformance-pack/dono/conformance-pack-p0acq8bpz
ConformancePackId              : conformance-pack-p0acabcde
ConformancePackInputParameters : {}
ConformancePackName            : dono
CreatedBy                      :
DeliveryS3Bucket               : kt-ps-examples
DeliveryS3KeyPrefix            :
LastUpdateRequestedTime        : 12/31/2019 8:45:31 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConformancePacks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGDeliveryChannel`
<a name="config-service_DescribeDeliveryChannels_powershell_5_topic"></a>

次のコード例は、`Get-CFGDeliveryChannel` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リージョンの配信チャネルを取得し、詳細を表示します。**  

```
Get-CFGDeliveryChannel -Region eu-west-1 | Select-Object Name, S3BucketName, S3KeyPrefix, @{N="DeliveryFrequency";E={$_.ConfigSnapshotDeliveryProperties.DeliveryFrequency}}
```
**出力:**  

```
Name    S3BucketName               S3KeyPrefix DeliveryFrequency
----    ------------               ----------- -----------------
default config-bucket-NA my          TwentyFour_Hours
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeDeliveryChannels](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-CFGResourceTag`
<a name="config-service_ListTagsForResource_powershell_5_topic"></a>

次のコード例は、`Get-CFGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定リソースに関連付けられたタグを一覧表示します。**  

```
Get-CFGResourceTag -ResourceArn $rules[0].ConfigRuleArn
```
**出力:**  

```
Key     Value
---     -----
Version 1.3
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-CFGConformancePack`
<a name="config-service_DeleteConformancePack_powershell_5_topic"></a>

次のコード例は、`Remove-CFGConformancePack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定の適合パックと、パックのすべてのルール、修復アクション、評価結果を削除します。**  

```
Remove-CFGConformancePack -ConformancePackName dono
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-CFGConformancePack (DeleteConformancePack)" on target "dono".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteConformancePack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-CFGConformancePack`
<a name="config-service_PutConformancePack_powershell_5_topic"></a>

次のコード例は、`Write-CFGConformancePack` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、適合パックを作成し、指定の yaml ファイルからテンプレートを取得します。 **  

```
Write-CFGConformancePack -ConformancePackName dono -DeliveryS3Bucket amzn-s3-demo-bucket -TemplateBody (Get-Content C:\windows\temp\template.yaml -Raw)
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutConformancePack](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-CFGDeliveryChannel`
<a name="config-service_PutDeliveryChannel_powershell_5_topic"></a>

次のコード例は、`Write-CFGDeliveryChannel` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、既存の配信チャネルの deliveryFrequency プロパティを変更します。**  

```
Write-CFGDeliveryChannel -ConfigSnapshotDeliveryProperties_DeliveryFrequency TwentyFour_Hours -DeliveryChannelName default -DeliveryChannel_S3BucketName amzn-s3-demo-bucket -DeliveryChannel_S3KeyPrefix my
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutDeliveryChannel](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Device Farm の例
<a name="powershell_5_device-farm_code_examples"></a>

次のコード例は、Device Farm で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-DFUpload`
<a name="device-farm_CreateUpload_powershell_5_topic"></a>

次のコード例は、`New-DFUpload` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Android アプリの AWS Device Farm アップロードを作成します。プロジェクト ARN は、New-DFProject または Get-DFProjectList の出力から取得できます。New-DFUpload 出力内の署名付き URL を使用して、ファイルを Device Farm にアップロードします。**  

```
New-DFUpload -ContentType "application/octet-stream" -ProjectArn "arn:aws:devicefarm:us-west-2:123456789012:project:EXAMPLEa-7ec1-4741-9c1f-d3e04EXAMPLE" -Name "app.apk" -Type ANDROID_APP
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateUpload](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Directory Service Tools for PowerShell V5 を使用した の例
<a name="powershell_5_directory-service_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています Directory Service。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-DSIpRoute`
<a name="directory-service_AddIpRoutes_powershell_5_topic"></a>

次のコード例は、`Add-DSIpRoute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 Directory-id に割り当てられたリソースタグを削除します**  

```
Add-DSIpRoute -DirectoryId d-123456ijkl -IpRoute @{CidrIp ="203.0.113.5/32"} -UpdateSecurityGroupForDirectoryController $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AddIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-DSResourceTag`
<a name="directory-service_AddTagsToResource_powershell_5_topic"></a>

次のコード例は、`Add-DSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定の Directory-id にリソースタグを追加します。**  

```
Add-DSResourceTag -ResourceId d-123456ijkl -Tag @{Key="myTag"; Value="mytgValue"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AddTagsToResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Approve-DSTrust`
<a name="directory-service_VerifyTrust_powershell_5_topic"></a>

次のコード例は、`Approve-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された Trustid の AWS Directory Service VerifyTrust API オペレーションを呼び出します。**  

```
Approve-DSTrust -TrustId t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[VerifyTrust](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Confirm-DSSharedDirectory`
<a name="directory-service_AcceptSharedDirectory_powershell_5_topic"></a>

次のコード例は、`Confirm-DSSharedDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリ所有者から送信されたディレクトリ共有リクエストを受け入れます AWS アカウント。**  

```
Confirm-DSSharedDirectory -SharedDirectoryId d-9067012345
```
**出力:**  

```
CreatedDateTime     : 12/30/2019 4:20:27 AM
LastUpdatedDateTime : 12/30/2019 4:21:40 AM
OwnerAccountId      : 123456781234
OwnerDirectoryId    : d-123456ijkl
SharedAccountId     : 123456784321
SharedDirectoryId   : d-9067012345
ShareMethod         :
ShareNotes          : This is test sharing
ShareStatus         : Sharing
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AcceptSharedDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Connect-DSDirectory`
<a name="directory-service_ConnectDirectory_powershell_5_topic"></a>

次のコード例は、`Connect-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、オンプレミスディレクトリに接続するための AD Connector を作成します。**  

```
Connect-DSDirectory -Name contoso.com -ConnectSettings_CustomerUserName Administrator -Password $Password -ConnectSettings_CustomerDnsIp 172.31.36.96 -ShortName CONTOSO -Size Small -ConnectSettings_VpcId vpc-123459da -ConnectSettings_SubnetId subnet-1234ccaa, subnet-5678ffbb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[ConnectDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Deny-DSSharedDirectory`
<a name="directory-service_RejectSharedDirectory_powershell_5_topic"></a>

次のコード例は、`Deny-DSSharedDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリ所有者アカウントから送信されたディレクトリ共有リクエストを拒否します。**  

```
Deny-DSSharedDirectory -SharedDirectoryId d-9067012345
```
**出力:**  

```
d-9067012345
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[RejectSharedDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-DSDirectoryShare`
<a name="directory-service_UnshareDirectory_powershell_5_topic"></a>

次のコード例は、`Disable-DSDirectoryShare` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリ所有者とコンシューマーアカウントの間のディレクトリ共有を停止します。**  

```
Disable-DSDirectoryShare -DirectoryId d-123456ijkl -UnshareTarget_Id 123456784321 -UnshareTarget_Type ACCOUNT
```
**出力:**  

```
d-9067012345
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[UnshareDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-DSLDAPS`
<a name="directory-service_DisableLDAPS_powershell_5_topic"></a>

次のコード例は、`Disable-DSLDAPS` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ディレクトリの LDAP セキュアコールを非アクティブ化します。**  

```
Disable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableLDAPS](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-DSRadius`
<a name="directory-service_DisableRadius_powershell_5_topic"></a>

次のコード例は、`Disable-DSRadius` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AD Connector または Microsoft AD ディレクトリ用に設定された RADIUS サーバーを無効にします。**  

```
Disable-DSRadius -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableRadius](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-DSSso`
<a name="directory-service_DisableSso_powershell_5_topic"></a>

次のコード例は、`Disable-DSSso` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリのシングルサインオンを無効にします。**  

```
Disable-DSSso -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableSso](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-DSDirectoryShare`
<a name="directory-service_ShareDirectory_powershell_5_topic"></a>

次のコード例は、`Enable-DSDirectoryShare` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Handshake メソッドを使用して AWS 、アカウント内の指定されたディレクトリを別の AWS アカウントと共有します。 **  

```
Enable-DSDirectoryShare -DirectoryId d-123456ijkl -ShareTarget_Id 123456784321 -ShareMethod HANDSHAKE -ShareTarget_Type ACCOUNT
```
**出力:**  

```
d-9067012345
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[ShareDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-DSLDAPS`
<a name="directory-service_EnableLDAPS_powershell_5_topic"></a>

次のコード例は、`Enable-DSLDAPS` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ディレクトリのスイッチをアクティブ化して、常に LDAP セキュアコールを使用するようにします。**  

```
Enable-DSLDAPS -DirectoryId d-123456ijkl -Type Client
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableLDAPS](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-DSRadius`
<a name="directory-service_EnableRadius_powershell_5_topic"></a>

次のコード例は、`Enable-DSRadius` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AD Connector または Microsoft AD ディレクトリ用に指定された RADIUS サーバー設定で多要素認証 (MFA) を有効にします。**  

```
Enable-DSRadius -DirectoryId d-123456ijkl 
-RadiusSettings_AuthenticationProtocol PAP 
-RadiusSettings_DisplayLabel Radius 
-RadiusSettings_RadiusPort 1812 
-RadiusSettings_RadiusRetry 4 
-RadiusSettings_RadiusServer 10.4.185.113 
-RadiusSettings_RadiusTimeout 50 
-RadiusSettings_SharedSecret wJalrXUtnFEMI
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableRadius](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-DSSso`
<a name="directory-service_EnableSso_powershell_5_topic"></a>

次のコード例は、`Enable-DSSso` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリのシングルサインオンを有効にします。 **  

```
Enable-DSSso -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableSso](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSCertificate`
<a name="directory-service_DescribeCertificate_powershell_5_topic"></a>

次のコード例は、`Get-DSCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、セキュリティ保護された LDAP 接続に登録された証明書に関する情報を表示します。**  

```
Get-DSCertificate -DirectoryId d-123456ijkl -CertificateId c-906731e34f
```
**出力:**  

```
CertificateId      : c-906731e34f
CommonName         : contoso-EC2AMAZ-CTGG2NM-CA
ExpiryDateTime     : 4/15/2025 6:34:15 PM
RegisteredDateTime : 4/15/2020 6:38:56 PM
State              : Registered
StateReason        : Certificate registered successfully.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSCertificateList`
<a name="directory-service_ListCertificates_powershell_5_topic"></a>

次のコード例は、`Get-DSCertificateList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ディレクトリのセキュリティ保護された LDAP 接続用に登録されたすべての証明書が一覧表示されます。**  

```
Get-DSCertificateList -DirectoryId d-123456ijkl
```
**出力:**  

```
CertificateId CommonName                 ExpiryDateTime       State
------------- ----------                 --------------       -----
c-906731e34f  contoso-EC2AMAZ-CTGG2NM-CA 4/15/2025 6:34:15 PM Registered
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListCertificates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSConditionalForwarder`
<a name="directory-service_DescribeConditionalForwarders_powershell_5_topic"></a>

次のコード例は、`Get-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 Directory-id の設定済みの条件付きフォワーダーをすべて取得します。**  

```
Get-DSConditionalForwarder -DirectoryId d-123456ijkl
```
**出力:**  

```
DnsIpAddrs      RemoteDomainName ReplicationScope
----------      ---------------- ----------------
{172.31.77.239} contoso.com      Domain
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeConditionalForwarders](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSDirectory`
<a name="directory-service_DescribeDirectories_powershell_5_topic"></a>

次のコード例は、`Get-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、このアカウントに属するディレクトリに関する情報を取得します。**  

```
Get-DSDirectory | Select-Object DirectoryId, Name, DnsIpAddrs, Type
```
**出力:**  

```
DirectoryId  Name           DnsIpAddrs                     Type
-----------  ----           ----------                     ----
d-123456abcd abcd.example.com {172.31.74.189, 172.31.13.145} SimpleAD
d-123456efgh wifi.example.com {172.31.16.108, 172.31.10.56}  ADConnector
d-123456ijkl lan2.example.com {172.31.10.56, 172.31.16.108}  MicrosoftAD
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeDirectories](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSDirectoryLimit`
<a name="directory-service_GetDirectoryLimits_powershell_5_topic"></a>

次のコード例は、`Get-DSDirectoryLimit` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、us-east-1 リージョンのディレクトリ制限情報を表示します。**  

```
Get-DSDirectoryLimit -Region us-east-1
```
**出力:**  

```
CloudOnlyDirectoriesCurrentCount : 1
CloudOnlyDirectoriesLimit        : 10
CloudOnlyDirectoriesLimitReached : False
CloudOnlyMicrosoftADCurrentCount : 1
CloudOnlyMicrosoftADLimit        : 20
CloudOnlyMicrosoftADLimitReached : False
ConnectedDirectoriesCurrentCount : 1
ConnectedDirectoriesLimit        : 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetDirectoryLimits](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSDomainControllerList`
<a name="directory-service_DescribeDomainControllers_powershell_5_topic"></a>

次のコード例は、`Get-DSDomainControllerList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 directory-id に対して起動されたドメインコントローラーの詳細なリストを取得します。**  

```
Get-DSDomainControllerList -DirectoryId d-123456ijkl
```
**出力:**  

```
AvailabilityZone          : us-east-1b
DirectoryId               : d-123456ijkl
DnsIpAddr                 : 172.31.16.108
DomainControllerId        : dc-1234567aa6
LaunchTime                : 4/4/2019 4:53:43 AM
Status                    : Active
StatusLastUpdatedDateTime : 4/24/2019 1:37:54 PM
StatusReason              :
SubnetId                  : subnet-1234kkaa
VpcId                     : vpc-123459d

AvailabilityZone          : us-east-1d
DirectoryId               : d-123456ijkl
DnsIpAddr                 : 172.31.10.56
DomainControllerId        : dc-1234567aa7
LaunchTime                : 4/4/2019 4:53:43 AM
Status                    : Active
StatusLastUpdatedDateTime : 4/4/2019 5:14:31 AM
StatusReason              :
SubnetId                  : subnet-5678ffbb
VpcId                     : vpc-123459d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeDomainControllers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSEventTopic`
<a name="directory-service_DescribeEventTopics_powershell_5_topic"></a>

次のコード例は、`Get-DSEventTopic` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、ディレクトリのステータスが変更されたときの通知用に設定された SNS トピックの情報を表示します。**  

```
Get-DSEventTopic -DirectoryId d-123456ijkl
```
**出力:**  

```
CreatedDateTime : 12/13/2019 11:15:32 AM
DirectoryId     : d-123456ijkl
Status          : Registered
TopicArn        : arn:aws:sns:us-east-1:123456781234:snstopicname
TopicName       : snstopicname
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeEventTopics](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSIpRouteList`
<a name="directory-service_ListIpRoutes_powershell_5_topic"></a>

次のコード例は、`Get-DSIpRouteList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、ディレクトリ IP ルーティングで設定されたパブリック IP アドレスブロックを取得します。**  

```
Get-DSIpRouteList -DirectoryId d-123456ijkl
```
**出力:**  

```
AddedDateTime       : 12/13/2019 12:27:22 PM
CidrIp              : 203.0.113.5/32
Description         : Public IP of On-Prem DNS Server
DirectoryId         : d-123456ijkl
IpRouteStatusMsg    : Added
IpRouteStatusReason :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSLDAPSSetting`
<a name="directory-service_DescribeLDAPSSettings_powershell_5_topic"></a>

次のコード例は、`Get-DSLDAPSSetting` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ディレクトリの LDAP セキュリティのステータスを説明します。**  

```
Get-DSLDAPSSetting -DirectoryId d-123456ijkl
```
**出力:**  

```
LastUpdatedDateTime  LDAPSStatus LDAPSStatusReason
-------------------  ----------- -----------------
4/15/2020 6:51:03 PM Enabled     LDAPS is enabled successfully.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLDAPSSettings](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSLogSubscriptionList`
<a name="directory-service_ListLogSubscriptions_powershell_5_topic"></a>

次のコード例は、`Get-DSLogSubscriptionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 directory-id のログサブスクリプション情報を取得します。**  

```
Get-DSLogSubscriptionList -DirectoryId d-123456ijkl
```
**出力:**  

```
DirectoryId  LogGroupName                                        SubscriptionCreatedDateTime
-----------  ------------                                        ---------------------------
d-123456ijkl /aws/directoryservice/d-123456ijkl-lan2.example.com 12/14/2019 9:05:23 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListLogSubscriptions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSResourceTag`
<a name="directory-service_ListTagsForResource_powershell_5_topic"></a>

次のコード例は、`Get-DSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定ディレクトリのすべてのタグを取得します。**  

```
Get-DSResourceTag -ResourceId d-123456ijkl
```
**出力:**  

```
Key   Value
---   -----
myTag myTagValue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-DSSchemaExtension`
<a name="directory-service_ListSchemaExtensions_powershell_5_topic"></a>

次のコード例は、`Get-DSSchemaExtension` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Microsoft AD ディレクトリに適用されているすべてのスキーマ拡張を一覧表示します。**  

```
Get-DSSchemaExtension -DirectoryId d-123456ijkl
```
**出力:**  

```
Description                 : ManagedADSchemaExtension
DirectoryId                 : d-123456ijkl
EndDateTime                 : 4/12/2020 10:30:49 AM
SchemaExtensionId           : e-9067306643
SchemaExtensionStatus       : Completed
SchemaExtensionStatusReason : Schema updates are complete.
StartDateTime               : 4/12/2020 10:28:42 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListSchemaExtensions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSSharedDirectory`
<a name="directory-service_DescribeSharedDirectories_powershell_5_topic"></a>

次のコード例は、`Get-DSSharedDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウントの共有ディレクトリを取得します。**  

```
Get-DSSharedDirectory -OwnerDirectoryId d-123456ijkl -SharedDirectoryId d-9067012345
```
**出力:**  

```
CreatedDateTime     : 12/30/2019 4:34:37 AM
LastUpdatedDateTime : 12/30/2019 4:35:22 AM
OwnerAccountId      : 123456781234
OwnerDirectoryId    : d-123456ijkl
SharedAccountId     : 123456784321
SharedDirectoryId   : d-9067012345
ShareMethod         : HANDSHAKE
ShareNotes          : This is a test Sharing
ShareStatus         : Shared
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSharedDirectories](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSSnapshot`
<a name="directory-service_DescribeSnapshots_powershell_5_topic"></a>

次のコード例は、`Get-DSSnapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、このアカウントに属する指定ディレクトリのスナップショットに関する情報を取得します。**  

```
Get-DSSnapshot -DirectoryId d-123456ijkl
```
**出力:**  

```
DirectoryId : d-123456ijkl
Name        :
SnapshotId  : s-9064bd1234
StartTime   : 12/13/2019 6:33:01 PM
Status      : Completed
Type        : Auto

DirectoryId : d-123456ijkl
Name        :
SnapshotId  : s-9064bb4321
StartTime   : 12/9/2019 9:48:11 PM
Status      : Completed
Type        : Auto
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSSnapshotLimit`
<a name="directory-service_GetSnapshotLimits_powershell_5_topic"></a>

次のコード例は、`Get-DSSnapshotLimit` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定ディレクトリの手動スナップショット制限を取得します。**  

```
Get-DSSnapshotLimit -DirectoryId d-123456ijkl
```
**出力:**  

```
ManualSnapshotsCurrentCount ManualSnapshotsLimit ManualSnapshotsLimitReached
--------------------------- -------------------- ---------------------------
0                           5                    False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetSnapshotLimits](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DSTrust`
<a name="directory-service_DescribeTrusts_powershell_5_topic"></a>

次のコード例は、`Get-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定された directory-id 用に作成された信頼関係の情報を取得します。**  

```
Get-DSTrust -DirectoryId d-123456abcd
```
**出力:**  

```
CreatedDateTime          : 7/5/2019 4:55:42 AM
DirectoryId              : d-123456abcd
LastUpdatedDateTime      : 7/5/2019 4:56:04 AM
RemoteDomainName         : contoso.com
SelectiveAuth            : Disabled
StateLastUpdatedDateTime : 7/5/2019 4:56:04 AM
TrustDirection           : One-Way: Incoming
TrustId                  : t-9067157123
TrustState               : Created
TrustStateReason         :
TrustType                : Forest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeTrusts](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSAlias`
<a name="directory-service_CreateAlias_powershell_5_topic"></a>

次のコード例は、`New-DSAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリのエイリアスを作成し、指定 directory-id にエイリアスを割り当てます。**  

```
New-DSAlias -DirectoryId d-123456ijkl -Alias MyOrgName
```
**出力:**  

```
Alias     DirectoryId
-----     -----------
myorgname d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateAlias](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSComputer`
<a name="directory-service_CreateComputer_powershell_5_topic"></a>

次のコード例は、`New-DSComputer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しい Active Directory コンピュータオブジェクトを作成します。**  

```
New-DSComputer -DirectoryId d-123456ijkl -ComputerName ADMemberServer -Password $Password
```
**出力:**  

```
ComputerAttributes                  ComputerId                                    ComputerName
------------------                  ----------                                    ------------
{WindowsSamName, DistinguishedName} S-1-5-21-1191241402-978882507-2717148213-1662 ADMemberServer
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateComputer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSConditionalForwarder`
<a name="directory-service_CreateConditionalForwarder_powershell_5_topic"></a>

次のコード例は、`New-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AWS Directory-id に条件付きフォワーダーを作成します。 **  

```
New-DSConditionalForwarder -DirectoryId d-123456ijkl -DnsIpAddr 172.31.36.96,172.31.10.56 -RemoteDomainName contoso.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSDirectory`
<a name="directory-service_CreateDirectory_powershell_5_topic"></a>

次のコード例は、`New-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しい Simple AD ディレクトリを作成します。**  

```
New-DSDirectory -Name corp.example.com -Password $Password -Size Small -VpcSettings_VpcId vpc-123459d -VpcSettings_SubnetIds subnet-1234kkaa,subnet-5678ffbb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSLogSubscription`
<a name="directory-service_CreateLogSubscription_powershell_5_topic"></a>

次のコード例は、`New-DSLogSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウントの指定の Amazon CloudWatch ロググループに Directory Service ドメインコントローラーセキュリティログをリアルタイムに転送するためのサブスクリプションを作成します。**  

```
New-DSLogSubscription -DirectoryId d-123456ijkl -LogGroupName /aws/directoryservice/d-123456ijkl-lan2.example.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateLogSubscription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSMicrosoftAD`
<a name="directory-service_CreateMicrosoftAD_powershell_5_topic"></a>

次のコード例は、`New-DSMicrosoftAD` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 に新しい Microsoft AD Directory を作成します AWS クラウド。**  

```
New-DSMicrosoftAD -Name corp.example.com -Password $Password -edition Standard -VpcSettings_VpcId vpc-123459d -VpcSettings_SubnetIds subnet-1234kkaa,subnet-5678ffbb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateMicrosoftAD](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSSnapshot`
<a name="directory-service_CreateSnapshot_powershell_5_topic"></a>

次のコード例は、`New-DSSnapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリスナップショットを作成します。**  

```
New-DSSnapshot -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DSTrust`
<a name="directory-service_CreateTrust_powershell_5_topic"></a>

次のコード例は、`New-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS Managed Microsoft AD ディレクトリと既存のオンプレミス Microsoft Active Directory の間に双方向のフォレスト全体の信頼を作成します。**  

```
New-DSTrust -DirectoryId d-123456ijkl -RemoteDomainName contoso.com -TrustDirection Two-Way -TrustType Forest -TrustPassword $Password -ConditionalForwarderIpAddr 172.31.36.96
```
**出力:**  

```
t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateTrust](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-DSCertificate`
<a name="directory-service_RegisterCertificate_powershell_5_topic"></a>

次のコード例は、`Register-DSCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、セキュリティで保護された LDAP 接続の証明書を登録します。**  

```
$Certificate = Get-Content contoso.cer -Raw
Register-DSCertificate -DirectoryId d-123456ijkl -CertificateData $Certificate
```
**出力:**  

```
c-906731e350
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RegisterCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-DSEventTopic`
<a name="directory-service_RegisterEventTopic_powershell_5_topic"></a>

次のコード例は、`Register-DSEventTopic` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ディレクトリをパブリッシャーとして SNS トピックに関連付けます。**  

```
Register-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RegisterEventTopic](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DSConditionalForwarder`
<a name="directory-service_DeleteConditionalForwarder_powershell_5_topic"></a>

次のコード例は、`Remove-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS Direcotry 用に設定された条件付きフォワーダーを削除します。**  

```
Remove-DSConditionalForwarder -DirectoryId d-123456ijkl -RemoteDomainName contoso.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DSDirectory`
<a name="directory-service_DeleteDirectory_powershell_5_topic"></a>

次のコード例は、`Remove-DSDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS ディレクトリサービスディレクトリ (Simple AD/Microsoft AD/AD Connector) を削除します。**  

```
Remove-DSDirectory -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DSIpRoute`
<a name="directory-service_RemoveIpRoutes_powershell_5_topic"></a>

次のコード例は、`Remove-DSIpRoute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 IP を Directory-id の設定済み IP ルートから削除します。 **  

```
Remove-DSIpRoute -DirectoryId d-123456ijkl -CidrIp 203.0.113.5/32
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RemoveIpRoutes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DSLogSubscription`
<a name="directory-service_DeleteLogSubscription_powershell_5_topic"></a>

次のコード例は、`Remove-DSLogSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 Directory-id のログサブスクリプションを削除します**  

```
Remove-DSLogSubscription -DirectoryId d-123456ijkl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteLogSubscription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DSResourceTag`
<a name="directory-service_RemoveTagsFromResource_powershell_5_topic"></a>

次のコード例は、`Remove-DSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 Directory-id に割り当てられたリソースタグを削除します**  

```
Remove-DSResourceTag -ResourceId d-123456ijkl -TagKey myTag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DSSnapshot`
<a name="directory-service_DeleteSnapshot_powershell_5_topic"></a>

次のコード例は、`Remove-DSSnapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、手動で作成されたスナップショットを削除します。**  

```
Remove-DSSnapshot -SnapshotId s-9068b488kc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DSTrust`
<a name="directory-service_DeleteTrust_powershell_5_topic"></a>

次のコード例は、`Remove-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS Managed AD Directory と外部ドメイン間の既存の信頼関係ヒントを削除します。**  

```
Get-DSTrust -DirectoryId d-123456ijkl -Select Trusts.TrustId | Remove-DSTrust
```
**出力:**  

```
t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteTrust](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Reset-DSUserPassword`
<a name="directory-service_ResetUserPassword_powershell_5_topic"></a>

次のコード例は、`Reset-DSUserPassword` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS Managed microsoft AD または Simple AD Directory で ADUser という名前の Active Direcotry ユーザーのパスワードをリセットします。**  

```
Reset-DSUserPassword -UserName ADuser -DirectoryId d-123456ijkl -NewPassword $Password
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResetUserPassword](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Restore-DSFromSnapshot`
<a name="directory-service_RestoreFromSnapshot_powershell_5_topic"></a>

次のコード例は、`Restore-DSFromSnapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、既存のディレクトリスナップショットを使用してディレクトリを復元します。**  

```
Restore-DSFromSnapshot -SnapshotId s-9068b488kc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RestoreFromSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-DSDomainControllerCount`
<a name="directory-service_UpdateNumberOfDomainControllers_powershell_5_topic"></a>

次のコード例は、`Set-DSDomainControllerCount` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 directory-id のドメインコントローラーの数を 3 に設定します。**  

```
Set-DSDomainControllerCount -DirectoryId d-123456ijkl -DesiredNumber 3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateNumberOfDomainControllers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-DSSchemaExtension`
<a name="directory-service_StartSchemaExtension_powershell_5_topic"></a>

次のコード例は、`Start-DSSchemaExtension` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Microsoft AD ディレクトリにスキーマ拡張を適用します。**  

```
$ldif = Get-Content D:\Users\Username\Downloads\ExtendedSchema.ldf -Raw
Start-DSSchemaExtension -DirectoryId d-123456ijkl -CreateSnapshotBeforeSchemaExtension $true -Description ManagedADSchemaExtension -LdifContent $ldif
```
**出力:**  

```
e-9067306643
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StartSchemaExtension](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-DSSchemaExtension`
<a name="directory-service_CancelSchemaExtension_powershell_5_topic"></a>

次のコード例は、`Stop-DSSchemaExtension` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Microsoft AD ディレクトリへの進行中のスキーマ拡張をキャンセルします。**  

```
Stop-DSSchemaExtension -DirectoryId d-123456ijkl -SchemaExtensionId e-9067306643
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CancelSchemaExtension](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-DSCertificate`
<a name="directory-service_DeregisterCertificate_powershell_5_topic"></a>

次のコード例は、`Unregister-DSCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、セキュリティで保護された LDAP 接続用に登録された証明書をシステムから削除します。**  

```
Unregister-DSCertificate -DirectoryId d-123456ijkl -CertificateId c-906731e34f
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeregisterCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-DSEventTopic`
<a name="directory-service_DeregisterEventTopic_powershell_5_topic"></a>

次のコード例は、`Unregister-DSEventTopic` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された SNS トピックへの発行者として指定されたディレクトリを削除します。**  

```
Unregister-DSEventTopic -DirectoryId d-123456ijkl -TopicName snstopicname
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeregisterEventTopic](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-DSConditionalForwarder`
<a name="directory-service_UpdateConditionalForwarder_powershell_5_topic"></a>

次のコード例は、`Update-DSConditionalForwarder` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS ディレクトリ用に設定された条件付きフォワーダーを更新します。**  

```
Update-DSConditionalForwarder -DirectoryId d-123456ijkl -DnsIpAddr 172.31.36.96,172.31.16.108 -RemoteDomainName contoso.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateConditionalForwarder](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-DSRadius`
<a name="directory-service_UpdateRadius_powershell_5_topic"></a>

次のコード例は、`Update-DSRadius` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、AD Connector または Microsoft AD ディレクトリの RADIUS サーバー情報を更新します。**  

```
Update-DSRadius -DirectoryId d-123456ijkl -RadiusSettings_RadiusRetry 3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateRadius](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-DSTrust`
<a name="directory-service_UpdateTrust_powershell_5_topic"></a>

次のコード例は、`Update-DSTrust` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 trust-id の SelectiveAuth パラメータを Disabled から Enabled に更新します。**  

```
Update-DSTrust -TrustId t-9067157123 -SelectiveAuth Enabled
```
**出力:**  

```
RequestId                            TrustId
---------                            -------
138864a7-c9a8-4ad1-a828-eae479e85b45 t-9067157123
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateTrust](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# AWS DMS Tools for PowerShell V5 を使用した の例
<a name="powershell_5_database-migration-service_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS DMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-DMSReplicationTask`
<a name="database-migration-service_CreateReplicationTask_powershell_5_topic"></a>

次のコード例は、`New-DMSReplicationTask` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、CdcStartPosition の代わりに CdcStartTime を使用する新しい AWS Database Migration Service レプリケーションタスクを作成します。 CdcStartPosition MigrationType は「full-load-and-cdc」に設定されます。つまり、ターゲットテーブルは空である必要があります。新しいタスクには、Stage のキーと Test のキー値を持つタグが付けられます。このコマンドレットで使用される値の詳細については、 AWS 「 Database Migration Service ユーザーガイド」の「タスクの作成 (https://docs.aws.amazon.com/dms/latest/userguide/CHAP\$1Tasks.Creating.html)」を参照してください。**  

```
New-DMSReplicationTask -ReplicationInstanceArn "arn:aws:dms:us-east-1:123456789012:rep:EXAMPLE66XFJUWATDJGBEXAMPLE"`
  -CdcStartTime "2019-08-08T12:12:12"`
  -CdcStopPosition "server_time:2019-08-09T12:12:12"`
  -MigrationType "full-load-and-cdc"`
  -ReplicationTaskIdentifier "task1"`
  -ReplicationTaskSetting ""`
  -SourceEndpointArn "arn:aws:dms:us-east-1:123456789012:endpoint:EXAMPLEW5UANC7Y3P4EEXAMPLE"`
  -TableMapping "file:////home/testuser/table-mappings.json"`
  -Tag @{"Key"="Stage";"Value"="Test"}`
  -TargetEndpointArn "arn:aws:dms:us-east-1:123456789012:endpoint:EXAMPLEJZASXWHTWCLNEXAMPLE"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateReplicationTask](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した DynamoDB の例
<a name="powershell_5_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-DDBIndexSchema`
<a name="dynamodb_Add-DDBIndexSchema_powershell_5_topic"></a>

次のコード例は、`Add-DDBIndexSchema` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: TableSchema オブジェクトをパイプラインに書き込む前に、空の TableSchema オブジェクトを作成し、新しいローカルセカンダリインデックス定義を追加します。**  

```
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema = New-DDBTableSchema
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{LastPostDateTime}                          {}                                          {LastPostIndex}
```
**例 2: TableSchema オブジェクトをパイプラインに書き戻す前に、指定 TableSchema オブジェクトに新しいローカルセカンダリインデックス定義を追加します。TableSchema オブジェクトは、-Schema パラメータを使用して指定することもできます。**  

```
New-DDBTableSchema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{LastPostDateTime}                          {}                                          {LastPostIndex}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Add-DDBIndexSchema](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-DDBKeySchema`
<a name="dynamodb_Add-DDBKeySchema_powershell_5_topic"></a>

次のコード例は、`Add-DDBKeySchema` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: TableSchema オブジェクトをパイプラインに書き込む前に、空の TableSchema オブジェクトを作成し、指定キーデータを使用してキーと属性定義のエントリを追加します。キータイプはデフォルトで「HASH」と宣言されます。範囲キーを宣言するには、値「RANGE」を持つ -KeyType パラメータを使用します。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
**例 2: TableSchema オブジェクトをパイプラインに書き込む前に、指定 TableSchema オブジェクトに新しいキーと属性定義のエントリを追加します。キータイプはデフォルトで「HASH」と宣言されます。範囲キーを宣言するには、値「RANGE」を持つ -KeyType パラメータを使用します。TableSchema オブジェクトは、-Schema パラメータを使用して指定することもできます。**  

```
New-DDBTableSchema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{ForumName}                                 {ForumName}                                 {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Add-DDBKeySchema](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `ConvertFrom-DDBItem`
<a name="dynamodb_ConvertFrom-DDBItem_powershell_5_topic"></a>

次のコード例は、`ConvertFrom-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ConvertFrom-DDBItem を使用して、Get-DDBItem の結果を DynamoDB AttributeValues のハッシュテーブルから string や double などの一般的なタイプのハッシュテーブルに変換します。**  

```
@{
    SongTitle = 'Somewhere Down The Road'
    Artist    = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ConvertFrom-DDBItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `ConvertTo-DDBItem`
<a name="dynamodb_ConvertTo-DDBItem_powershell_5_topic"></a>

次のコード例は、`ConvertTo-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ハッシュテーブルを DynamoDB 属性値のディクショナリに変換する例。**  

```
@{
    SongTitle = 'Somewhere Down The Road'
    Artist    = 'No One You Know'
} | ConvertTo-DDBItem

Key       Value
---       -----
SongTitle Amazon.DynamoDBv2.Model.AttributeValue
Artist    Amazon.DynamoDBv2.Model.AttributeValue
```
**例 2: ハッシュテーブルを DynamoDB 属性値のディクショナリに変換する例。**  

```
@{
    MyMap        = @{
        MyString = 'my string'
    }
    MyStringSet  = [System.Collections.Generic.HashSet[String]]@('my', 'string')
    MyNumericSet = [System.Collections.Generic.HashSet[Int]]@(1, 2, 3)
    MyBinarySet  = [System.Collections.Generic.HashSet[System.IO.MemoryStream]]@(
        ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes('my'))),
        ([IO.MemoryStream]::new([Text.Encoding]::UTF8.GetBytes('string')))
    )
    MyList1      = @('my', 'string')
    MyList2      = [System.Collections.Generic.List[Int]]@(1, 2)
    MyList3      = [System.Collections.ArrayList]@('one', 2, $true)
} | ConvertTo-DDBItem
```
**出力:**  

```
Key          Value
---          -----
MyStringSet  Amazon.DynamoDBv2.Model.AttributeValue
MyList1      Amazon.DynamoDBv2.Model.AttributeValue
MyNumericSet Amazon.DynamoDBv2.Model.AttributeValue
MyList2      Amazon.DynamoDBv2.Model.AttributeValue
MyBinarySet  Amazon.DynamoDBv2.Model.AttributeValue
MyMap        Amazon.DynamoDBv2.Model.AttributeValue
MyList3      Amazon.DynamoDBv2.Model.AttributeValue
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ConvertTo-DDBItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DDBBatchItem`
<a name="dynamodb_BatchGetItem_powershell_5_topic"></a>

次のコード例は、`Get-DDBBatchItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: DynamoDB テーブルの「Music」と「Songs」から「Somewhere Down The Road」という SongTitle の項目を取得します。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem

$keysAndAttributes = New-Object Amazon.DynamoDBv2.Model.KeysAndAttributes
$list = New-Object 'System.Collections.Generic.List[System.Collections.Generic.Dictionary[String, Amazon.DynamoDBv2.Model.AttributeValue]]'
$list.Add($key)
$keysAndAttributes.Keys = $list

$requestItem = @{
    'Music' = [Amazon.DynamoDBv2.Model.KeysAndAttributes]$keysAndAttributes
    'Songs' = [Amazon.DynamoDBv2.Model.KeysAndAttributes]$keysAndAttributes
}

$batchItems = Get-DDBBatchItem -RequestItem $requestItem
$batchItems.GetEnumerator() | ForEach-Object {$PSItem.Value} | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Artist                         No One You Know
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
CriticRating                   10
Genre                          Country
Price                          1.94
Artist                         No One You Know
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
CriticRating                   10
Genre                          Country
Price                          1.94
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchGetItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DDBItem`
<a name="dynamodb_GetItem_powershell_5_topic"></a>

次のコード例は、`Get-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: パーティションキー SongTitle とソートキー Artist を含む DynamoDB 項目を返します。**  

```
$key = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
} | ConvertTo-DDBItem

Get-DDBItem -TableName 'Music' -Key $key | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
SongTitle                      Somewhere Down The Road
Price                          1.94
Artist                         No One You Know
CriticRating                   9
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DDBTable`
<a name="dynamodb_DescribeTable_powershell_5_topic"></a>

次のコード例は、`Get-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定テーブルの詳細を返します。**  

```
Get-DDBTable -TableName "myTable"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-DDBTableList`
<a name="dynamodb_ListTables_powershell_5_topic"></a>

次のコード例は、`Get-DDBTableList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべてのテーブルの詳細を返し、サービスが他にテーブルがないことを知らせるまで自動で繰り返します。**  

```
Get-DDBTableList
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListTables](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Invoke-DDBQuery`
<a name="dynamodb_Query_powershell_5_topic"></a>

次のコード例は、`Invoke-DDBQuery` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定の SongTitle と Artist を含む DynamoDB 項目を返すクエリを呼び出します。**  

```
$invokeDDBQuery = @{
    TableName = 'Music'
    KeyConditionExpression = ' SongTitle = :SongTitle and Artist = :Artist'
    ExpressionAttributeValues = @{
        ':SongTitle' = 'Somewhere Down The Road'
        ':Artist' = 'No One You Know'
    } | ConvertTo-DDBItem
}
Invoke-DDBQuery @invokeDDBQuery | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Query](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Invoke-DDBScan`
<a name="dynamodb_Scan_powershell_5_topic"></a>

次のコード例は、`Invoke-DDBScan` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: Music テーブルのすべての項目を返します。**  

```
Invoke-DDBScan -TableName 'Music' | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
Genre                          Country
Artist                         No One You Know
Price                          1.98
CriticRating                   8.4
SongTitle                      My Dog Spot
AlbumTitle                     Hey Now
```
**例 2: Music テーブル内の CriticRating が 9 以上の項目を返します。**  

```
$scanFilter = @{
        CriticRating = [Amazon.DynamoDBv2.Model.Condition]@{
            AttributeValueList = @(@{N = '9'})
            ComparisonOperator = 'GE'
        }
    }
    Invoke-DDBScan -TableName 'Music' -ScanFilter $scanFilter | ConvertFrom-DDBItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Country
Artist                         No One You Know
Price                          1.94
CriticRating                   9
SongTitle                      Somewhere Down The Road
AlbumTitle                     Somewhat Famous
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Scan](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DDBTable`
<a name="dynamodb_CreateTable_powershell_5_topic"></a>

次のコード例は、`New-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ「Thread」という名前のテーブルを作成します。テーブルの作成に使用したスキーマは、図のように各 cmdlet にパイプ処理するか、-Schema パラメータを使用して指定できます。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyType RANGE -KeyDataType "S"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**出力:**  

```
AttributeDefinitions   : {ForumName, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {}
```
**例 2: この例では、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキーを持つ Thread という名前のテーブルを作成します。ローカルセカンダリインデックスも定義されます。ローカルセカンダリインデックスのキーは、テーブルのプライマリハッシュキー (ForumName) から自動的に設定されます。テーブルの作成に使用したスキーマは、図のように各 cmdlet にパイプ処理するか、-Schema パラメータを使用して指定できます。**  

```
$schema = New-DDBTableSchema
$schema | Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S"
$schema | Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S"
$schema | Add-DDBIndexSchema -IndexName "LastPostIndex" -RangeKeyName "LastPostDateTime" -RangeKeyDataType "S" -ProjectionType "keys_only"
$schema | New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**出力:**  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
**例 3: この例では、単一のパイプラインを使用して、「ForumName」(キータイプハッシュ) と「Subject」(キータイプ範囲) で構成されるプライマリキー、およびローカルセカンダリインデックスを持つ「Thread」という名前のテーブルを作成する方法を示します。TableSchema がパイプラインまたは -Schema パラメータから提供されない場合、Add-DDBKeySchema と Add-DDBIndexSchema によって新しい TableSchema オブジェクトが作成されます。**  

```
New-DDBTableSchema |
  Add-DDBKeySchema -KeyName "ForumName" -KeyDataType "S" |
  Add-DDBKeySchema -KeyName "Subject" -KeyDataType "S" |
  Add-DDBIndexSchema -IndexName "LastPostIndex" `
                     -RangeKeyName "LastPostDateTime" `
                     -RangeKeyDataType "S" `
                     -ProjectionType "keys_only" |
  New-DDBTable -TableName "Thread" -ReadCapacity 10 -WriteCapacity 5
```
**出力:**  

```
AttributeDefinitions   : {ForumName, LastPostDateTime, Subject}
TableName              : Thread
KeySchema              : {ForumName, Subject}
TableStatus            : CREATING
CreationDateTime       : 10/28/2013 4:39:49 PM
ProvisionedThroughput  : Amazon.DynamoDBv2.Model.ProvisionedThroughputDescription
TableSizeBytes         : 0
ItemCount              : 0
LocalSecondaryIndexes  : {LastPostIndex}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-DDBTableSchema`
<a name="dynamodb_New-DDBTableSchema_powershell_5_topic"></a>

次のコード例は、`New-DDBTableSchema` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 新しい Amazon DynamoDB テーブルの作成に使用するキーとインデックスの定義を受け入れる準備が整った空の TableSchema オブジェクトを作成します。返されたオブジェクトは、Add-DDBKeySchema、Add-DDBIndexSchema、New-DDBTable コマンドレットにパイプするか、各コマンドレットの -Schema パラメータを使用して渡すことができます。**  

```
New-DDBTableSchema
```
**出力:**  

```
AttributeSchema                             KeySchema                                   LocalSecondaryIndexSchema
---------------                             ---------                                   -------------------------
{}                                          {}                                          {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[New-DDBTableSchema](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DDBItem`
<a name="dynamodb_DeleteItem_powershell_5_topic"></a>

次のコード例は、`Remove-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたキーと一致する DynamoDB 項目を削除します。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem
Remove-DDBItem -TableName 'Music' -Key $key -Confirm:$false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-DDBTable`
<a name="dynamodb_DeleteTable_powershell_5_topic"></a>

次のコード例は、`Remove-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたテーブルを削除します。操作を続行する前に確認画面が表示されます。**  

```
Remove-DDBTable -TableName "myTable"
```
**例 2: 指定されたテーブルを削除します。操作を続行する前に確認画面は表示されません。**  

```
Remove-DDBTable -TableName "myTable" -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-DDBBatchItem`
<a name="dynamodb_BatchWriteItem_powershell_5_topic"></a>

次のコード例は、`Set-DDBBatchItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 新しい項目を作成する、または既存の項目を「Music 」DynamoDB テーブルおよび「Songs」DynamoDB テーブルの新しい項目で置き換えます。**  

```
$item = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
    AlbumTitle = 'Somewhat Famous'
    Price = 1.94
    Genre = 'Country'
    CriticRating = 10.0
} | ConvertTo-DDBItem

$writeRequest = New-Object Amazon.DynamoDBv2.Model.WriteRequest
$writeRequest.PutRequest = [Amazon.DynamoDBv2.Model.PutRequest]$item

$requestItem = @{
    'Music' = [Amazon.DynamoDBv2.Model.WriteRequest]($writeRequest)
    'Songs' = [Amazon.DynamoDBv2.Model.WriteRequest]($writeRequest)
}

Set-DDBBatchItem -RequestItem $requestItem
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[BatchWriteItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-DDBItem`
<a name="dynamodb_PutItem_powershell_5_topic"></a>

次のコード例は、`Set-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 新しい項目を作成する、または既存の項目を新しい項目で置き換えます。**  

```
$item = @{
  SongTitle = 'Somewhere Down The Road'
  Artist = 'No One You Know'
        AlbumTitle = 'Somewhat Famous'
        Price = 1.94
        Genre = 'Country'
        CriticRating = 9.0
} | ConvertTo-DDBItem
Set-DDBItem -TableName 'Music' -Item $item
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PutItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-DDBItem`
<a name="dynamodb_UpdateItem_powershell_5_topic"></a>

次のコード例は、`Update-DDBItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: パーティションキー SongTitle とソートキー Artist を含む DynamoDB 項目のジャンル属性を「Rap」に設定します。**  

```
$key = @{
    SongTitle = 'Somewhere Down The Road'
    Artist = 'No One You Know'
} | ConvertTo-DDBItem

$updateDdbItem = @{
    TableName = 'Music'
    Key = $key
    UpdateExpression = 'set Genre = :val1'
    ExpressionAttributeValue = (@{
        ':val1' = ([Amazon.DynamoDBv2.Model.AttributeValue]'Rap')
    })
}
Update-DDBItem @updateDdbItem
```
**出力:**  

```
Name                           Value
----                           -----
Genre                          Rap
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateItem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-DDBTable`
<a name="dynamodb_UpdateTable_powershell_5_topic"></a>

次のコード例は、`Update-DDBTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたテーブルのプロビジョンされたスループットを更新します。**  

```
Update-DDBTable -TableName "myTable" -ReadCapacity 10 -WriteCapacity 5
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Amazon EC2 の例
<a name="powershell_5_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-EC2CapacityReservation`
<a name="ec2_CreateCapacityReservation_powershell_5_topic"></a>

次のコード例は、`Add-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された属性で新しいキャパシティ予約を作成します。**  

```
Add-EC2CapacityReservation -InstanceType m4.xlarge -InstanceCount 2 -AvailabilityZone eu-west-1b -EbsOptimized True -InstancePlatform Windows
```
**出力:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-EC2InternetGateway`
<a name="ec2_AttachInternetGateway_powershell_5_topic"></a>

次のコード例は、`Add-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインターネットゲートウェイを特定の VPC にアタッチします。**  

```
Add-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
**例 2: この例では、VPC とインターネットゲートウェイを作成し、インターネットゲートウェイを VPC にアタッチします。**  

```
$vpc = New-EC2Vpc -CidrBlock 10.0.0.0/16
New-EC2InternetGateway | Add-EC2InternetGateway -VpcId $vpc.VpcId
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-EC2NetworkInterface`
<a name="ec2_AttachNetworkInterface_powershell_5_topic"></a>

次のコード例は、`Add-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したネットワークインターフェイスを指定したインスタンスにアタッチします。**  

```
Add-EC2NetworkInterface -NetworkInterfaceId eni-12345678 -InstanceId i-1a2b3c4d -DeviceIndex 1
```
**出力:**  

```
eni-attach-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-EC2Volume`
<a name="ec2_AttachVolume_powershell_5_topic"></a>

次のコード例は、`Add-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたボリュームを指定されたインスタンスにアタッチし、指定されたデバイス名で公開します。**  

```
Add-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
**出力:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : attaching
VolumeId            : vol-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachVolume](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-EC2VpnGateway`
<a name="ec2_AttachVpnGateway_powershell_5_topic"></a>

次のコード例は、`Add-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した仮想プライベートゲートウェイを指定した VPC にアタッチします。**  

```
Add-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
**出力:**  

```
State        VpcId
-----        -----
attaching    vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Approve-EC2VpcPeeringConnection`
<a name="ec2_AcceptVpcPeeringConnection_powershell_5_topic"></a>

次のコード例は、`Approve-EC2VpcPeeringConnection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リクエストされた VpcPeeringConnectionId pcx-1dfad234b56ff78be を承認します。**  

```
Approve-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-1dfad234b56ff78be
```
**出力:**  

```
AccepterVpcInfo        : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
ExpirationTime         : 1/1/0001 12:00:00 AM
RequesterVpcInfo       : Amazon.EC2.Model.VpcPeeringConnectionVpcInfo
Status                 : Amazon.EC2.Model.VpcPeeringConnectionStateReason
Tags                   : {}
VpcPeeringConnectionId : pcx-1dfad234b56ff78be
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AcceptVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Confirm-EC2ProductInstance`
<a name="ec2_ConfirmProductInstance_powershell_5_topic"></a>

次のコード例は、`Confirm-EC2ProductInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された製品コードが指定されたインスタンスに関連付けられているかどうかを判断します。**  

```
Confirm-EC2ProductInstance -ProductCode 774F4FF8 -InstanceId i-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ConfirmProductInstance](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Copy-EC2Image`
<a name="ec2_CopyImage_powershell_5_topic"></a>

次のコード例は、`Copy-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「欧州 (アイルランド)」リージョンの指定 AMI を「米国西部 (オレゴン)」リージョンにコピーします。-Region が指定されていない場合、現在のデフォルトリージョンが送信先リージョンとして使用されます。**  

```
Copy-EC2Image -SourceRegion eu-west-1 -SourceImageId ami-12345678 -Region us-west-2 -Name "Copy of ami-12345678"
```
**出力:**  

```
ami-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CopyImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Copy-EC2Snapshot`
<a name="ec2_CopySnapshot_powershell_5_topic"></a>

次のコード例は、`Copy-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスナップショットを欧州 (アイルランド) リージョンから米国西部 (オレゴン) リージョンにコピーします。**  

```
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678 -Region us-west-2
```
**例 2: デフォルトのリージョンを設定し、Region パラメータを省略すると、デフォルトの送信先リージョンがデフォルトのリージョンになります。**  

```
Set-DefaultAWSRegion us-west-2
Copy-EC2Snapshot -SourceRegion eu-west-1 -SourceSnapshotId snap-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CopySnapshot](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Deny-EC2VpcPeeringConnection`
<a name="ec2_RejectVpcPeeringConnection_powershell_5_topic"></a>

次のコード例は、`Deny-EC2VpcPeeringConnection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 上記の例では、VpcPeering リクエスト ID pcx-01a2b3ce45fe67eb8 のリクエストを拒否します。**  

```
Deny-EC2VpcPeeringConnection -VpcPeeringConnectionId pcx-01a2b3ce45fe67eb8
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RejectVpcPeeringConnection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-EC2VgwRoutePropagation`
<a name="ec2_DisableVgwRoutePropagation_powershell_5_topic"></a>

次のコード例は、`Disable-EC2VgwRoutePropagation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、VGW が指定されたルーティングテーブルにルートを自動的に伝播することを無効にします。**  

```
Disable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-EC2VpcClassicLink`
<a name="ec2_DisableVpcClassicLink_powershell_5_topic"></a>

次のコード例は、`Disable-EC2VpcClassicLink` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、vpc-01e23c4a5d6db78e9 の EC2VpcClassicLink を無効にします。True または False を返します。**  

```
Disable-EC2VpcClassicLink -VpcId vpc-01e23c4a5d6db78e9
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DisableVpcClassicLinkDnsSupport_powershell_5_topic"></a>

次のコード例は、`Disable-EC2VpcClassicLinkDnsSupport` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、vpc-0b12d3456a7e8910d の ClassicLink DNS サポートを無効にします。**  

```
Disable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Dismount-EC2InternetGateway`
<a name="ec2_DetachInternetGateway_powershell_5_topic"></a>

次のコード例は、`Dismount-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPC から指定されたインターネットゲートウェイをデタッチします。**  

```
Dismount-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d -VpcId vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DetachInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Dismount-EC2NetworkInterface`
<a name="ec2_DetachNetworkInterface_powershell_5_topic"></a>

次のコード例は、`Dismount-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ネットワークインターフェイスとインスタンス間の指定されたアタッチメントを削除します。**  

```
Dismount-EC2NetworkInterface -AttachmentId eni-attach-1a2b3c4d -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DetachNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Dismount-EC2Volume`
<a name="ec2_DetachVolume_powershell_5_topic"></a>

次のコード例は、`Dismount-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたボリュームをデタッチします。**  

```
Dismount-EC2Volume -VolumeId vol-12345678
```
**出力:**  

```
AttachTime          : 12/22/2015 1:53:58 AM
DeleteOnTermination : False
Device              : /dev/sdh
InstanceId          : i-1a2b3c4d
State               : detaching
VolumeId            : vol-12345678
```
**例 2: インスタンス ID とデバイス名を指定して、正しいボリュームをデタッチするようにすることもできます。**  

```
Dismount-EC2Volume -VolumeId vol-12345678 -InstanceId i-1a2b3c4d -Device /dev/sdh
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)*の「[DetachVolume](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Dismount-EC2VpnGateway`
<a name="ec2_DetachVpnGateway_powershell_5_topic"></a>

次のコード例は、`Dismount-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPC から指定された仮想プライベートゲートウェイをデタッチします。**  

```
Dismount-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d -VpcId vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DetachVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2CapacityReservation`
<a name="ec2_ModifyCapacityReservation_powershell_5_topic"></a>

次のコード例は、`Edit-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンス数を 1 に変更して CapacityReservationId cr-0c1f2345db6f7cdba を変更します。**  

```
Edit-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba -InstanceCount 1
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2Host`
<a name="ec2_ModifyHosts_powershell_5_topic"></a>

次のコード例は、`Edit-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、専有ホスト h-01e23f4cd567890f3 の 自動配置設定をオフに変更します。**  

```
Edit-EC2Host -HostId h-03e09f8cd681609f3 -AutoPlacement off
```
**出力:**  

```
Successful            Unsuccessful
----------            ------------
{h-01e23f4cd567890f3} {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyHosts](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2IdFormat`
<a name="ec2_ModifyIdFormat_powershell_5_topic"></a>

次のコード例は、`Edit-EC2IdFormat` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリソースタイプの長い ID 形式を有効にします。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $true
```
**例 2: この例では、指定されたリソースタイプの長い ID 形式を無効にします。**  

```
Edit-EC2IdFormat -Resource instance -UseLongId $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2ImageAttribute`
<a name="ec2_ModifyImageAttribute_powershell_5_topic"></a>

次のコード例は、`Edit-EC2ImageAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AMI の説明を更新します。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Description "New description"
```
**例 2: この例では、AMI を公開します (例: 誰でも AWS アカウント 使用できる）。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserGroup all
```
**例 3: この例では、AMI を非公開にします (例えば、所有者である自分だけが使用できるようにします)。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserGroup all
```
**例 4: この例では、指定された に起動アクセス許可を付与します AWS アカウント。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType add -UserId 111122223333
```
**例 5: この例では、指定された から起動アクセス許可を削除します AWS アカウント。**  

```
Edit-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission -OperationType remove -UserId 111122223333
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2InstanceAttribute`
<a name="ec2_ModifyInstanceAttribute_powershell_5_topic"></a>

次のコード例は、`Edit-EC2InstanceAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスのインスタンスタイプを変更します。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceType m3.medium
```
**例 2: この例では、単一ルート I/O 仮想化 (SR-IOV) ネットワークサポートパラメータ -SriovNetSupport の値に「simple」を指定して、指定されたインスタンスの拡張ネットワーキングを有効にします。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SriovNetSupport "simple"
```
**例 3: この例では、指定されたインスタンスのセキュリティグループを変更します。インスタンスは VPC にある必要があります。名前ではなく、各セキュリティグループの ID を指定する必要があります。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -Group @( "sg-12345678", "sg-45678901" )
```
**例 4: この例では、指定されたインスタンスの EBS I/O 最適化を有効にします。この機能は、すべてのインスタンスタイプで使用できるわけではありません。EBS 最適化インスタンスを使用する場合は、追加料金が適用されます。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -EbsOptimized $true
```
**例 5: この例では、指定されたインスタンスの送信元/送信先チェックを有効にします。NAT インスタンスが NAT を実行するには、値が「false」である必要があります。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -SourceDestCheck $true
```
**例 6: この例では、指定されたインスタンスの終了を無効にします。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -DisableApiTermination $true
```
**例 7: この例では、インスタンスからシャットダウンを開始したときに終了するように、指定されたインスタンスを変更します。**  

```
Edit-EC2InstanceAttribute -InstanceId i-12345678 -InstanceInitiatedShutdownBehavior terminate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2InstanceCreditSpecification`
<a name="ec2_ModifyInstanceCreditSpecification_powershell_5_topic"></a>

次のコード例は、`Edit-EC2InstanceCreditSpecification` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: これにより、インスタンス i-01234567890abcdef の T2 無制限クレジットが有効になります。**  

```
$Credit = New-Object -TypeName Amazon.EC2.Model.InstanceCreditSpecificationRequest
$Credit.InstanceId = "i-01234567890abcdef"
$Credit.CpuCredits = "unlimited"
Edit-EC2InstanceCreditSpecification -InstanceCreditSpecification $Credit
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyInstanceCreditSpecification](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2NetworkInterfaceAttribute`
<a name="ec2_ModifyNetworkInterfaceAttribute_powershell_5_topic"></a>

次のコード例は、`Edit-EC2NetworkInterfaceAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された添付ファイルが終了時に削除されるように、指定されたネットワークインターフェイスを変更します。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Attachment_AttachmentId eni-attach-1a2b3c4d -Attachment_DeleteOnTermination $true
```
**例 2: この例では、指定されたネットワークインターフェイスの説明を変更します。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Description "my description"
```
**例 3: この例では、指定されたネットワークインターフェイスのセキュリティグループを変更します。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -Groups sg-1a2b3c4d
```
**例 4: この例では、指定されたネットワークインターフェイスの送信元/送信先チェックを無効にします。**  

```
Edit-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2ReservedInstance`
<a name="ec2_ModifyReservedInstances_powershell_5_topic"></a>

次のコード例は、`Edit-EC2ReservedInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリザーブドインスタンスのアベイラビリティーゾーン、インスタンス数、プラットフォームを変更します。**  

```
$config = New-Object Amazon.EC2.Model.ReservedInstancesConfiguration
$config.AvailabilityZone = "us-west-2a"
$config.InstanceCount = 1
$config.Platform = "EC2-VPC"

Edit-EC2ReservedInstance `
-ReservedInstancesId @("FE32132D-70D5-4795-B400-AE435EXAMPLE", "0CC556F3-7AB8-4C00-B0E5-98666EXAMPLE") `
-TargetConfiguration $config
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyReservedInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2SnapshotAttribute`
<a name="ec2_ModifySnapshotAttribute_powershell_5_topic"></a>

次のコード例は、`Edit-EC2SnapshotAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、CreateVolumePermission 属性を設定して、指定されたスナップショットを公開します。**  

```
Edit-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission -OperationType Add -GroupName all
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifySnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2SpotFleetRequest`
<a name="ec2_ModifySpotFleetRequest_powershell_5_topic"></a>

次のコード例は、`Edit-EC2SpotFleetRequest` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンド例では、指定されたスポットフリートリクエストのターゲット容量を更新します。**  

```
Edit-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TargetCapacity 10
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifySpotFleetRequest](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2SubnetAttribute`
<a name="ec2_ModifySubnetAttribute_powershell_5_topic"></a>

次のコード例は、`Edit-EC2SubnetAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたサブネットのパブリック IP アドレス指定を有効にします。**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $true
```
**例 2: この例では、指定されたサブネットのパブリック IP アドレス指定を無効にします。**  

```
Edit-EC2SubnetAttribute -SubnetId subnet-1a2b3c4d -MapPublicIpOnLaunch $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifySubnetAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2VolumeAttribute`
<a name="ec2_ModifyVolumeAttribute_powershell_5_topic"></a>

次のコード例は、`Edit-EC2VolumeAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたボリュームの指定された属性を変更します。ボリュームの I/O オペレーションは、データの不整合の可能性が原因で中断された後に自動的に再開されます。**  

```
Edit-EC2VolumeAttribute -VolumeId vol-12345678 -AutoEnableIO $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-EC2VpcAttribute`
<a name="ec2_ModifyVpcAttribute_powershell_5_topic"></a>

次のコード例は、`Edit-EC2VpcAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPC の DNS ホスト名のサポートを有効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $true
```
**例 2: この例では、指定された VPC の DNS ホスト名のサポートを無効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsHostnames $false
```
**例 3: この例では、指定された VPC の DNS 解決のサポートを有効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $true
```
**例 4: この例では、指定された VPC の DNS 解決のサポートを無効にします。**  

```
Edit-EC2VpcAttribute -VpcId vpc-12345678 -EnableDnsSupport $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-EC2VgwRoutePropagation`
<a name="ec2_EnableVgwRoutePropagation_powershell_5_topic"></a>

次のコード例は、`Enable-EC2VgwRoutePropagation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VGW が指定されたルーティングテーブルに自動的にルートを伝播できるようにします。**  

```
Enable-EC2VgwRoutePropagation -RouteTableId rtb-12345678 -GatewayId vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableVgwRoutePropagation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-EC2VolumeIO`
<a name="ec2_EnableVolumeIo_powershell_5_topic"></a>

次のコード例は、`Enable-EC2VolumeIO` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、I/O オペレーションが無効になっている場合に、指定されたボリュームの I/O オペレーションを有効にします。**  

```
Enable-EC2VolumeIO -VolumeId vol-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableVolumeIo](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-EC2VpcClassicLink`
<a name="ec2_EnableVpcClassicLink_powershell_5_topic"></a>

次のコード例は、`Enable-EC2VpcClassicLink` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ClassicLink の VPC vpc-0123456b789b0d12f を有効にします。**  

```
Enable-EC2VpcClassicLink -VpcId vpc-0123456b789b0d12f
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-EC2VpcClassicLinkDnsSupport`
<a name="ec2_EnableVpcClassicLinkDnsSupport_powershell_5_topic"></a>

次のコード例は、`Enable-EC2VpcClassicLinkDnsSupport` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、vpc-0b12d3456a7e8910d が ClassicLink の DNS ホスト名解決をサポートできるようにします。**  

```
Enable-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2AccountAttribute`
<a name="ec2_DescribeAccountAttributes_powershell_5_topic"></a>

次のコード例は、`Get-EC2AccountAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リージョンの EC2-Classic および EC2-VPC にインスタンスを起動できるか、または EC2-VPC にのみインスタンスを起動できるかを記述します。**  

```
(Get-EC2AccountAttribute -AttributeName supported-platforms).AttributeValues
```
**出力:**  

```
AttributeValue
--------------
EC2
VPC
```
**例 2: この例では、デフォルトの VPC を記述します。リージョンにデフォルトの VPC がない場合は「none」です。**  

```
(Get-EC2AccountAttribute -AttributeName default-vpc).AttributeValues
```
**出力:**  

```
AttributeValue
--------------
vpc-12345678
```
**例 3: この例では、実行できるオンデマンドインスタンスの最大数を記述します。**  

```
(Get-EC2AccountAttribute -AttributeName max-instances).AttributeValues
```
**出力:**  

```
AttributeValue
--------------
20
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAccountAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Address`
<a name="ec2_DescribeAddresses_powershell_5_topic"></a>

次のコード例は、`Get-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2-Classic のインスタンスに指定された Elastic IP アドレスを記述します。**  

```
Get-EC2Address -AllocationId eipalloc-12345678
```
**出力:**  

```
AllocationId            : eipalloc-12345678
AssociationId           : eipassoc-12345678
Domain                  : vpc
InstanceId              : i-87654321
NetworkInterfaceId      : eni-12345678
NetworkInterfaceOwnerId : 12345678
PrivateIpAddress        : 10.0.2.172
PublicIp                : 198.51.100.2
```
**例 2: この例では、VPC 内のインスタンスの Elastic IP アドレスを記述します。この構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-EC2Address -Filter @{ Name="domain";Values="vpc" }
```
**例 3: この例では、EC2-Classic のインスタンスに指定された Elastic IP アドレスを記述します。**  

```
Get-EC2Address -PublicIp 203.0.113.17
```
**出力:**  

```
AllocationId            :
AssociationId           :
Domain                  : standard
InstanceId              : i-12345678
NetworkInterfaceId      :
NetworkInterfaceOwnerId :
PrivateIpAddress        :
PublicIp                : 203.0.113.17
```
**例 4: この例では、EC2-Classic のインスタンスの Elastic IP アドレスを記述します。この構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-EC2Address -Filter @{ Name="domain";Values="standard" }
```
**例 5: この例では、すべての Elastic IP アドレスを記述します。**  

```
Get-EC2Address
```
**例 6: この例では、フィルターで指定されたインスタンス ID のパブリック IP とプライベート IP を返します。**  

```
Get-EC2Address -Region eu-west-1 -Filter @{Name="instance-id";Values="i-0c12d3f4f567ffb89"} | Select-Object PrivateIpAddress, PublicIp
```
**出力:**  

```
PrivateIpAddress PublicIp
---------------- --------
10.0.0.99        63.36.5.227
```
**例 7: この例では、割り当て ID、関連付け ID、インスタンス ID を持つすべての Elastic IP を取得します。**  

```
Get-EC2Address -Region eu-west-1 | Select-Object InstanceId, AssociationId, AllocationId, PublicIp
```
**出力:**  

```
InstanceId          AssociationId              AllocationId               PublicIp
----------          -------------              ------------               --------
                                               eipalloc-012e3b456789e1fad 17.212.120.178
i-0c123dfd3415bac67 eipassoc-0e123456bb7890bdb eipalloc-01cd23ebf45f7890c 17.212.124.77
                                               eipalloc-012345678eeabcfad 17.212.225.7
i-0123d405c67e89a0c eipassoc-0c123b456783966ba eipalloc-0123cdd456a8f7892 37.216.52.173
i-0f1bf2f34c5678d09 eipassoc-0e12934568a952d96 eipalloc-0e1c23e4d5e6789e4 37.218.222.278
i-012e3cb4df567e8aa eipassoc-0d1b2fa4d67d03810 eipalloc-0123f456f78a01b58 37.210.82.27
i-0123bcf4b567890e1 eipassoc-01d2345f678903fb1 eipalloc-0e1db23cfef5c45c7 37.215.222.270
```
**例 8: この例では、タグキー「Category」と値「Prod」に一致する EC2 IP アドレスのリストを取得します。**  

```
Get-EC2Address -Filter @{Name="tag:Category";Values="Prod"}
```
**出力:**  

```
AllocationId            : eipalloc-0123f456f81a01b58
AssociationId           : eipassoc-0d1b23a456d103810
CustomerOwnedIp         :
CustomerOwnedIpv4Pool   :
Domain                  : vpc
InstanceId              : i-012e3cb4df567e1aa
NetworkBorderGroup      : eu-west-1
NetworkInterfaceId      : eni-0123f41d5a60d5f40
NetworkInterfaceOwnerId : 123456789012
PrivateIpAddress        : 192.168.1.84
PublicIp                : 34.250.81.29
PublicIpv4Pool          : amazon
Tags                    : {Category, Name}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAddresses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2AvailabilityZone`
<a name="ec2_DescribeAvailabilityZones_powershell_5_topic"></a>

次のコード例は、`Get-EC2AvailabilityZone` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、利用可能な現在のリージョンのアベイラビリティーゾーンについて記述します。**  

```
Get-EC2AvailabilityZone
```
**出力:**  

```
Messages    RegionName    State        ZoneName
--------    ----------    -----        --------
{}          us-west-2     available    us-west-2a
{}          us-west-2     available    us-west-2b
{}          us-west-2     available    us-west-2c
```
**例 2: この例では、障害状態にあるアベイラビリティーゾーンを記述します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Get-EC2AvailabilityZone -Filter @{ Name="state";Values="impaired" }
```
**例 3: PowerShell バージョン 2 では、New-Object を使用してフィルターを作成する必要があります。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = "impaired"

Get-EC2AvailabilityZone -Filter $filter
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAvailabilityZones](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2BundleTask`
<a name="ec2_DescribeBundleTasks_powershell_5_topic"></a>

次のコード例は、`Get-EC2BundleTask` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したバンドルタスクを記述します。**  

```
Get-EC2BundleTask -BundleId bun-12345678
```
**例 2: この例では、状態が「完了」または「失敗」のバンドルタスクについて説明します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "complete", "failed" )

Get-EC2BundleTask -Filter $filter
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeBundleTasks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2CapacityReservation`
<a name="ec2_DescribeCapacityReservations_powershell_5_topic"></a>

次のコード例は、`Get-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リージョンの 1 つ以上のキャパシティ予約について記述します。**  

```
Get-EC2CapacityReservation -Region eu-west-1
```
**出力:**  

```
AvailabilityZone       : eu-west-1b
AvailableInstanceCount : 2
CapacityReservationId  : cr-0c1f2345db6f7cdba
CreateDate             : 3/28/2019 9:29:41 AM
EbsOptimized           : True
EndDate                : 1/1/0001 12:00:00 AM
EndDateType            : unlimited
EphemeralStorage       : False
InstanceMatchCriteria  : open
InstancePlatform       : Windows
InstanceType           : m4.xlarge
State                  : active
Tags                   : {}
Tenancy                : default
TotalInstanceCount     : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeCapacityReservations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2ConsoleOutput`
<a name="ec2_GetConsoleOutput_powershell_5_topic"></a>

次のコード例は、`Get-EC2ConsoleOutput` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Linux インスタンスのコンソール出力を取得します。コンソール出力はエンコードされます。**  

```
Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456
```
**出力:**  

```
InstanceId          Output
----------          ------
i-0e194d3c47c123637 WyAgICAwLjAwMDAwMF0gQ29tbW...bGU9dHR5UzAgc2Vs
```
**例 2: この例では、エンコードされたコンソール出力を変数に保存してからデコードします。**  

```
$Output_encoded = (Get-EC2ConsoleOutput -InstanceId i-0e19abcd47c123456).Output
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($Output_encoded))
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetConsoleOutput](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2CustomerGateway`
<a name="ec2_DescribeCustomerGateways_powershell_5_topic"></a>

次のコード例は、`Get-EC2CustomerGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたカスタマーゲートウェイについて記述します。**  

```
Get-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**出力:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
**例 2: この例では、保留中または使用可能な状態のカスタマーゲートウェイを記述します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2CustomerGateway -Filter $filter
```
**例 3: この例では、すべてのカスタマーゲートウェイを記述します。**  

```
Get-EC2CustomerGateway
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeCustomerGateways](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2DhcpOption`
<a name="ec2_DescribeDhcpOptions_powershell_5_topic"></a>

次のコード例は、`Get-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、DHCP オプションセットを一覧表示します。**  

```
Get-EC2DhcpOption
```
**出力:**  

```
DhcpConfigurations                    DhcpOptionsId    Tag
------------------                    -------------    ---
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
{domain-name-servers}                 dopt-3a4b5c6d    {}
```
**例 2: この例では、指定された DHCP オプションセットの設定の詳細を取得します。**  

```
(Get-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d).DhcpConfigurations
```
**出力:**  

```
Key                    Values
---                    ------
domain-name            {abc.local}
domain-name-servers    {10.0.0.101, 10.0.0.102}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2FlowLog`
<a name="ec2_DescribeFlowLogs_powershell_5_topic"></a>

次のコード例は、`Get-EC2FlowLog` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ログの送信先タイプが「s3」の 1 つ以上のフローログを記述します。**  

```
Get-EC2FlowLog -Filter @{Name="log-destination-type";Values="s3"}
```
**出力:**  

```
CreationTime             : 2/25/2019 9:07:36 PM
DeliverLogsErrorMessage  :
DeliverLogsPermissionArn :
DeliverLogsStatus        : SUCCESS
FlowLogId                : fl-01b2e3d45f67f8901
FlowLogStatus            : ACTIVE
LogDestination           : arn:aws:s3:::amzn-s3-demo-bucket-dd-tata
LogDestinationType       : s3
LogGroupName             :
ResourceId               : eni-01d2dda3456b7e890
TrafficType              : ALL
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[DescribeFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Host`
<a name="ec2_DescribeHosts_powershell_5_topic"></a>

次のコード例は、`Get-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2 ホストの詳細を返します。**  

```
Get-EC2Host
```
**出力:**  

```
AllocationTime    : 3/23/2019 4:55:22 PM
AutoPlacement     : off
AvailabilityZone  : eu-west-1b
AvailableCapacity : Amazon.EC2.Model.AvailableCapacity
ClientToken       :
HostId            : h-01e23f4cd567890f1
HostProperties    : Amazon.EC2.Model.HostProperties
HostReservationId :
Instances         : {}
ReleaseTime       : 1/1/0001 12:00:00 AM
State             : available
Tags              : {}
```
**例 2: この例では、ホスト h-01e23f4cd567899f1 の AvailableInstanceCapacity をクエリします。**  

```
Get-EC2Host -HostId h-01e23f4cd567899f1 | Select-Object -ExpandProperty AvailableCapacity | Select-Object -expand AvailableInstanceCapacity
```
**出力:**  

```
AvailableCapacity InstanceType TotalCapacity
----------------- ------------ -------------
11                m4.xlarge    11
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeHosts](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2HostReservationOffering`
<a name="ec2_DescribeHostReservationOfferings_powershell_5_topic"></a>

次のコード例は、`Get-EC2HostReservationOffering` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、PaymentOption が「NoUpfront」である、指定されたフィルター「instance-family」で購入できる専有ホスト予約を記述します。**  

```
Get-EC2HostReservationOffering -Filter @{Name="instance-family";Values="m4"} | Where-Object PaymentOption -eq NoUpfront
```
**出力:**  

```
CurrencyCode   :
Duration       : 94608000
HourlyPrice    : 1.307
InstanceFamily : m4
OfferingId     : hro-0c1f234567890d9ab
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000

CurrencyCode   :
Duration       : 31536000
HourlyPrice    : 1.830
InstanceFamily : m4
OfferingId     : hro-04ad12aaaf34b5a67
PaymentOption  : NoUpfront
UpfrontPrice   : 0.000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeHostReservationOfferings](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2HostReservationPurchasePreview`
<a name="ec2_GetHostReservationPurchasePreview_powershell_5_topic"></a>

次のコード例は、`Get-EC2HostReservationPurchasePreview` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、専有ホスト h-01e23f4cd567890f1 の構成と一致する設定の予約購入をプレビューします。**  

```
Get-EC2HostReservationPurchasePreview -OfferingId hro-0c1f23456789d0ab -HostIdSet h-01e23f4cd567890f1
```
**出力:**  

```
CurrencyCode Purchase TotalHourlyPrice TotalUpfrontPrice
------------ -------- ---------------- -----------------
             {}       1.307            0.000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetHostReservationPurchasePreview](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2IdFormat`
<a name="ec2_DescribeIdFormat_powershell_5_topic"></a>

次のコード例は、`Get-EC2IdFormat` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリソースタイプの ID 形式を記述します。**  

```
Get-EC2IdFormat -Resource instance
```
**出力:**  

```
Resource       UseLongIds
--------       ----------
instance       False
```
**例 2: この例では、長い ID をサポートするすべてのリソースタイプの ID 形式を記述します。**  

```
Get-EC2IdFormat
```
**出力:**  

```
Resource       UseLongIds
--------       ----------
reservation    False
instance       False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2IdentityIdFormat`
<a name="ec2_DescribeIdentityIdFormat_powershell_5_topic"></a>

次のコード例は、`Get-EC2IdentityIdFormat` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロールのリソース「image」の ID 形式を返します。**  

```
Get-EC2IdentityIdFormat -PrincipalArn arn:aws:iam::123456789511:role/JDBC -Resource image
```
**出力:**  

```
Deadline             Resource UseLongIds
--------             -------- ----------
8/2/2018 11:30:00 PM image    True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeIdentityIdFormat](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Image`
<a name="ec2_DescribeImages_powershell_5_topic"></a>

次のコード例は、`Get-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AMI を記述します。**  

```
Get-EC2Image -ImageId ami-12345678
```
**出力:**  

```
Architecture        : x86_64
BlockDeviceMappings : {/dev/xvda}
CreationDate        : 2014-10-20T00:56:28.000Z
Description         : My image
Hypervisor          : xen
ImageId             : ami-12345678
ImageLocation       : 123456789012/my-image
ImageOwnerAlias     :
ImageType           : machine
KernelId            :
Name                : my-image
OwnerId             : 123456789012
Platform            :
ProductCodes        : {}
Public              : False
RamdiskId           :
RootDeviceName      : /dev/xvda
RootDeviceType      : ebs
SriovNetSupport     : simple
State               : available
StateReason         :
Tags                : {Name}
VirtualizationType  : hvm
```
**例 2: この例では、所有している AMI を記述します。**  

```
Get-EC2Image -owner self
```
**例 3: この例では、Microsoft Windows Server を実行するパブリック AMI を記述します。**  

```
Get-EC2Image -Filter @{ Name="platform"; Values="windows" }
```
**例 4: この例では、「us-west-2」リージョンのすべてのパブリック AMI を記述します。**  

```
Get-EC2Image -Region us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeImages](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2ImageAttribute`
<a name="ec2_DescribeImageAttribute_powershell_5_topic"></a>

次のコード例は、`Get-EC2ImageAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AMI の説明を取得します。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute description
```
**出力:**  

```
BlockDeviceMappings : {}
Description         : My image description
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**例 2: この例では、指定された AMI の起動許可を取得します。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
**出力:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {all}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     :
```
**例 3: この例では、拡張ネットワーキングが有効になっているかどうかをテストします。**  

```
Get-EC2ImageAttribute -ImageId ami-12345678 -Attribute sriovNetSupport
```
**出力:**  

```
BlockDeviceMappings : {}
Description         :
ImageId             : ami-12345678
KernelId            :
LaunchPermissions   : {}
ProductCodes        : {}
RamdiskId           :
SriovNetSupport     : simple
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2ImportImageTask`
<a name="ec2_DescribeImportImageTasks_powershell_5_topic"></a>

次のコード例は、`Get-EC2ImportImageTask` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたイメージのインポートタスクを記述します。**  

```
Get-EC2ImportImageTask -ImportTaskId import-ami-hgfedcba
```
**出力:**  

```
Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
**例 2: この例では、すべてのイメージのインポートタスクを記述します。**  

```
Get-EC2ImportImageTask
```
**出力:**  

```
Architecture    :
Description     : Windows Image 1
Hypervisor      :
ImageId         :
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {}
Status          : deleted
StatusMessage   : User initiated task cancelation

Architecture    : x86_64
Description     : Windows Image 2
Hypervisor      :
ImageId         : ami-1a2b3c4d
ImportTaskId    : import-ami-hgfedcba
LicenseType     : AWS
Platform        : Windows
Progress        :
SnapshotDetails : {/dev/sda1}
Status          : completed
StatusMessage   :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeImportImageTasks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2ImportSnapshotTask`
<a name="ec2_DescribeImportSnapshotTasks_powershell_5_topic"></a>

次のコード例は、`Get-EC2ImportSnapshotTask` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスナップショットのインポートタスクを記述します。**  

```
Get-EC2ImportSnapshotTask -ImportTaskId import-snap-abcdefgh
```
**出力:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
**例 2: この例では、すべてのスナップショットのインポートタスクを記述します。**  

```
Get-EC2ImportSnapshotTask
```
**出力:**  

```
Description             ImportTaskId               SnapshotTaskDetail                                                          
-----------------       --------------------       ------------------                                                          
Disk Image Import 1     import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail 
Disk Image Import 2     import-snap-hgfedcba       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeImportSnapshotTasks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Instance`
<a name="ec2_DescribeInstances_powershell_5_topic"></a>

次のコード例は、`Get-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスを記述します。**  

```
(Get-EC2Instance -InstanceId i-12345678).Instances
```
**出力:**  

```
AmiLaunchIndex        : 0
Architecture          : x86_64
BlockDeviceMappings   : {/dev/sda1}
ClientToken           : TleEy1448154045270
EbsOptimized          : False
Hypervisor            : xen
IamInstanceProfile    : Amazon.EC2.Model.IamInstanceProfile
ImageId               : ami-12345678
InstanceId            : i-12345678
InstanceLifecycle     :
InstanceType          : t2.micro
KernelId              :
KeyName               : my-key-pair
LaunchTime            : 12/4/2015 4:44:40 PM
Monitoring            : Amazon.EC2.Model.Monitoring
NetworkInterfaces     : {ip-10-0-2-172.us-west-2.compute.internal}
Placement             : Amazon.EC2.Model.Placement
Platform              : Windows
PrivateDnsName        : ip-10-0-2-172.us-west-2.compute.internal
PrivateIpAddress      : 10.0.2.172
ProductCodes          : {}
PublicDnsName         : 
PublicIpAddress       : 
RamdiskId             :
RootDeviceName        : /dev/sda1
RootDeviceType        : ebs
SecurityGroups        : {default}
SourceDestCheck       : True
SpotInstanceRequestId :
SriovNetSupport       :
State                 : Amazon.EC2.Model.InstanceState
StateReason           :
StateTransitionReason :
SubnetId              : subnet-12345678
Tags                  : {Name}
VirtualizationType    : hvm
VpcId                 : vpc-12345678
```
**例 2: この例では、現在のリージョンのすべてのインスタンスを予約別にグループ化して記述します。インスタンスの詳細を表示するには、各予約オブジェクト内のインスタンスコレクションを展開します。**  

```
Get-EC2Instance
```
**出力:**  

```
GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 226008221399
ReservationId : r-c5df370c

GroupNames    : {}
Groups        : {}
Instances     : {}
OwnerId       : 123456789012
RequesterId   : 854251627541
ReservationId : r-63e65bab
...
```
**例 3: この例では、フィルターを使用して VPC の特定のサブネット内の EC2 インスタンスをクエリする方法を示します。**  

```
(Get-EC2Instance -Filter @{Name="vpc-id";Values="vpc-1a2bc34d"},@{Name="subnet-id";Values="subnet-1a2b3c4d"}).Instances
```
**出力:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-01af...82cf180e19 t2.medium    Windows  10.0.0.98                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0374...7e9d5b0c45 t2.xlarge    Windows  10.0.0.53                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**例 4: この例では、複数の値を持つフィルターを使用して、実行中および停止中の EC2 インスタンスをクエリする方法を示します。**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

(Get-EC2Instance @InstanceParams).Instances
```
**出力:**  

```
InstanceId          InstanceType Platform PrivateIpAddress PublicIpAddress SecurityGroups SubnetId        VpcId
----------          ------------ -------- ---------------- --------------- -------------- --------        -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11                        ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6                         ...            subnet-1a2b3c4d vpc-1a2b3c4d
```
**例 5: この例では、複数の値を持つフィルターを使用して、実行中と停止中の両方の EC2 インスタンスをクエリし、Select-Object コマンドレットを使用して出力する特定の値を選択する方法を示します。**  

```
$InstanceParams = @{
    Filter = @(
        @{'Name' = 'instance-state-name';'Values' = @("running","stopped")}
    )
}

$SelectParams = @{
    Property = @(
        "InstanceID", "InstanceType", "Platform", "PrivateIpAddress",
        @{Name="Name";Expression={$_.Tags[$_.Tags.Key.IndexOf("Name")].Value}},
        @{Name="State";Expression={$_.State.Name}}
    )
}

$result = Get-EC2Instance @InstanceParams
$result.Instances | Select-Object @SelectParams | Format-Table -AutoSize
```
**出力:**  

```
InstanceId          InstanceType Platform PrivateIpAddress Name         State
----------          ------------ -------- ---------------- ----         -----
i-05a9...f6c5f46e18 t3.medium             10.0.1.7         ec2-name-01  running
i-02cf...945c4fdd07 t3.medium    Windows  10.0.1.8         ec2-name-02  stopped
i-0ac0...c037f9f3a1 t3.xlarge    Windows  10.0.1.10        ec2-name-03  running
i-066b...57b7b08888 t3.medium    Windows  10.0.1.11        ec2-name-04  stopped
i-0fee...82e83ccd72 t3.medium    Windows  10.0.1.5         ec2-name-05  running
i-0a68...274cc5043b t3.medium    Windows  10.0.1.6         ec2-name-06  stopped
```
**例 6: この例では、実際に EC2 インスタンスを取得することなく、DryRun パラメータを使用して EC2 インスタンス取得のアクセス許可を検証します。注: 成功すると例外がスローされますが、これは正常な動作です。**  

```
Get-EC2Tag -DryRun $true
```
**出力:**  

```
Get-EC2Instance: Request would have succeeded, but DryRun flag is set.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2InstanceAttribute`
<a name="ec2_DescribeInstanceAttribute_powershell_5_topic"></a>

次のコード例は、`Get-EC2InstanceAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスのインスタンスタイプを記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceType
```
**出力:**  

```
InstanceType                      : t2.micro
```
**例 2: この例では、指定されたインスタンスで拡張ネットワーキングが有効になっているかどうかを記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**出力:**  

```
SriovNetSupport                   : simple
```
**例 3: この例では、指定されたインスタンスのセキュリティグループについて記述します。**  

```
(Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute groupSet).Groups
```
**出力:**  

```
GroupId
-------
sg-12345678
sg-45678901
```
**例 4: この例では、指定したインスタンスで EBS 最適化が有効になっているかどうかを記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**出力:**  

```
EbsOptimized                      : False
```
**例 5: この例では、指定されたインスタンスの「disableApiTermination」属性を記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**出力:**  

```
DisableApiTermination             : False
```
**例 6: この例では、指定されたインスタンスの「instanceInitiatedShutdownBehavior」属性を記述します。**  

```
Get-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
**出力:**  

```
InstanceInitiatedShutdownBehavior : stop
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2InstanceMetadata`
<a name="ec2_Get-EC2InstanceMetadata_powershell_5_topic"></a>

次のコード例は、`Get-EC2InstanceMetadata` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: クエリできるインスタンスメタデータの利用可能なカテゴリを一覧表示します。**  

```
Get-EC2InstanceMetadata -ListCategory
```
**出力:**  

```
AmiId
LaunchIndex
ManifestPath
AncestorAmiId
BlockDeviceMapping
InstanceId
InstanceType
LocalHostname
LocalIpv4
KernelId
AvailabilityZone
ProductCode
PublicHostname
PublicIpv4
PublicKey
RamdiskId
Region
ReservationId
SecurityGroup
UserData
InstanceMonitoring
IdentityDocument
IdentitySignature
IdentityPkcs7
```
**例 2: インスタンスの起動に使用された Amazon マシンイメージ (AMI) の ID を返します。**  

```
Get-EC2InstanceMetadata -Category AmiId
```
**出力:**  

```
ami-b2e756ca
```
**例 3: この例では、インスタンスの JSON 形式の ID ドキュメントをクエリします。**  

```
Get-EC2InstanceMetadata -Category IdentityDocument
{
  "availabilityZone" : "us-west-2a",
  "devpayProductCodes" : null,
  "marketplaceProductCodes" : null,
  "version" : "2017-09-30",
  "instanceId" : "i-01ed50f7e2607f09e",
  "billingProducts" : [ "bp-6ba54002" ],
  "instanceType" : "t2.small",
  "pendingTime" : "2018-03-07T16:26:04Z",
  "imageId" : "ami-b2e756ca",
  "privateIp" : "10.0.0.171",
  "accountId" : "111122223333",
  "architecture" : "x86_64",
  "kernelId" : null,
  "ramdiskId" : null,
  "region" : "us-west-2"
}
```
**例 4: この例では、パスクエリを使用してインスタンスのネットワークインターフェイスの MAC を取得します。**  

```
Get-EC2InstanceMetadata -Path "/network/interfaces/macs"
```
**出力:**  

```
02:80:7f:ef:4c:e0/
```
**例 5: インスタンスに関連付けられた IAM ロールがある場合、インスタンスの LastUpdated の日付、InstanceProfileArn、InstanceProfileId など、インスタンスプロファイルが更新された最終時刻に関する情報が返されます。**  

```
Get-EC2InstanceMetadata -Path "/iam/info"
```
**出力:**  

```
{
  "Code" : "Success",
  "LastUpdated" : "2018-03-08T03:38:40Z",
  "InstanceProfileArn" : "arn:aws:iam::111122223333:instance-profile/MyLaunchRole_Profile",
  "InstanceProfileId" : "AIPAI4...WVK2RW"
}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Get-EC2InstanceMetadata](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2InstanceStatus`
<a name="ec2_DescribeInstanceStatus_powershell_5_topic"></a>

次のコード例は、`Get-EC2InstanceStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスのステータスを記述します。**  

```
Get-EC2InstanceStatus -InstanceId i-12345678
```
**出力:**  

```
AvailabilityZone : us-west-2a
Events           : {}
InstanceId       : i-12345678
InstanceState    : Amazon.EC2.Model.InstanceState
Status           : Amazon.EC2.Model.InstanceStatusSummary
SystemStatus     : Amazon.EC2.Model.InstanceStatusSummary
```

```
$status = Get-EC2InstanceStatus -InstanceId i-12345678
$status.InstanceState
```
**出力:**  

```
Code    Name
----    ----
16      running
```

```
$status.Status
```
**出力:**  

```
Details           Status
-------           ------
{reachability}    ok
```

```
$status.SystemStatus
```
**出力:**  

```
Details           Status
-------           ------
{reachability}    ok
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2InternetGateway`
<a name="ec2_DescribeInternetGateways_powershell_5_topic"></a>

次のコード例は、`Get-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインターネットゲートウェイを記述します。**  

```
Get-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**出力:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
```
**例 2: この例では、すべてのインターネットゲートウェイを記述します。**  

```
Get-EC2InternetGateway
```
**出力:**  

```
Attachments       InternetGatewayId     Tags
-----------       -----------------     ----
{vpc-1a2b3c4d}    igw-1a2b3c4d          {}
{}                igw-2a3b4c5d          {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeInternetGateways](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2KeyPair`
<a name="ec2_DescribeKeyPairs_powershell_5_topic"></a>

次のコード例は、`Get-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したキーペアを記述します。**  

```
Get-EC2KeyPair -KeyName my-key-pair
```
**出力:**  

```
KeyFingerprint                                              KeyName
--------------                                              -------
1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f my-key-pair
```
**例 2: この例では、すべてのキーペアを記述します。**  

```
Get-EC2KeyPair
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeKeyPairs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2NetworkAcl`
<a name="ec2_DescribeNetworkAcls_powershell_5_topic"></a>

次のコード例は、`Get-EC2NetworkAcl` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したネットワーク ACL を記述します。**  

```
Get-EC2NetworkAcl -NetworkAclId acl-12345678
```
**出力:**  

```
Associations : {aclassoc-1a2b3c4d}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {Name}
VpcId        : vpc-12345678
```
**例 2: この例では、指定されたネットワーク ACL のルールを記述します。**  

```
(Get-EC2NetworkAcl -NetworkAclId acl-12345678).Entries
```
**出力:**  

```
CidrBlock    : 0.0.0.0/0
Egress       : True
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767

CidrBlock    : 0.0.0.0/0
Egress       : False
IcmpTypeCode :
PortRange    :
Protocol     : -1
RuleAction   : deny
RuleNumber   : 32767
```
**例 3: この例では、すべてのネットワーク ACL を記述します。**  

```
Get-EC2NetworkAcl
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeNetworkAcls](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2NetworkInterface`
<a name="ec2_DescribeNetworkInterfaces_powershell_5_topic"></a>

次のコード例は、`Get-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**出力:**  

```
Association        :
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
AvailabilityZone   : us-west-2c
Description        :
Groups             : {my-security-group}
MacAddress         : 0a:e9:a6:19:4c:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-107.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.107
PrivateIpAddresses : {ip-10-0-0-107.us-west-2.compute.internal}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : in-use
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
**例 2: この例では、すべてのネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterface
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeNetworkInterfaces](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2NetworkInterfaceAttribute`
<a name="ec2_DescribeNetworkInterfaceAttribute_powershell_5_topic"></a>

次のコード例は、`Get-EC2NetworkInterfaceAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Attachment
```
**出力:**  

```
Attachment         : Amazon.EC2.Model.NetworkInterfaceAttachment
```
**例 2: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute Description
```
**出力:**  

```
Description        : My description
```
**例 3: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute GroupSet
```
**出力:**  

```
Groups             : {my-security-group}
```
**例 4: この例では、指定されたネットワークインターフェイスを記述します。**  

```
Get-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-12345678 -Attribute SourceDestCheck
```
**出力:**  

```
SourceDestCheck    : True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2PasswordData`
<a name="ec2_GetPasswordData_powershell_5_topic"></a>

次のコード例は、`Get-EC2PasswordData` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Amazon EC2 が指定された Windows インスタンスの管理者アカウントに割り当てたパスワードを復号します。pem ファイルを指定すると、-Decrypt スイッチの設定が自動的に適用されます。**  

```
Get-EC2PasswordData -InstanceId i-12345678 -PemFile C:\path\my-key-pair.pem
```
**出力:**  

```
mYZ(PA9?C)Q
```
**例 2: (Windows PowerShell のみ) インスタンスを検査して、インスタンスの起動に使用されるキーペアの名前を判断し、 AWS Toolkit for Visual Studio の設定ストアで対応するキーペアデータを見つけようとします。キーペアデータが見つかった場合、パスワードは復号されます。**  

```
Get-EC2PasswordData -InstanceId i-12345678 -Decrypt
```
**出力:**  

```
mYZ(PA9?C)Q
```
**例 3: インスタンスの暗号化されたパスワードデータを返します。**  

```
Get-EC2PasswordData -InstanceId i-12345678
```
**出力:**  

```
iVz3BAK/WAXV.....dqt8WeMA==
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[GetPasswordData](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2PlacementGroup`
<a name="ec2_DescribePlacementGroups_powershell_5_topic"></a>

次のコード例は、`Get-EC2PlacementGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したプレイスメントグループを記述します。**  

```
Get-EC2PlacementGroup -GroupName my-placement-group
```
**出力:**  

```
GroupName             State        Strategy
---------             -----        --------
my-placement-group    available    cluster
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribePlacementGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2PrefixList`
<a name="ec2_DescribePrefixLists_powershell_5_topic"></a>

次のコード例は、`Get-EC2PrefixList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 リージョンの AWS のサービス プレフィックスリスト形式で使用可能な を取得します。**  

```
Get-EC2PrefixList
```
**出力:**  

```
Cidrs                                          PrefixListId PrefixListName
-----                                          ------------ --------------
{52.94.5.0/24, 52.119.240.0/21, 52.94.24.0/23} pl-6fa54006  com.amazonaws.eu-west-1.dynamodb
{52.218.0.0/17, 54.231.128.0/19}               pl-6da54004  com.amazonaws.eu-west-1.s3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribePrefixLists](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Region`
<a name="ec2_DescribeRegions_powershell_5_topic"></a>

次のコード例は、`Get-EC2Region` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、使用可能なリージョンについて記述します。**  

```
Get-EC2Region
```
**出力:**  

```
Endpoint                            RegionName
--------                            ----------
ec2.eu-west-1.amazonaws.com         eu-west-1
ec2.ap-southeast-1.amazonaws.com    ap-southeast-1
ec2.ap-southeast-2.amazonaws.com    ap-southeast-2
ec2.eu-central-1.amazonaws.com      eu-central-1
ec2.ap-northeast-1.amazonaws.com    ap-northeast-1
ec2.us-east-1.amazonaws.com         us-east-1
ec2.sa-east-1.amazonaws.com         sa-east-1
ec2.us-west-1.amazonaws.com         us-west-1
ec2.us-west-2.amazonaws.com         us-west-2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeRegions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2RouteTable`
<a name="ec2_DescribeRouteTables_powershell_5_topic"></a>

次のコード例は、`Get-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべてのルートテーブルについて記述します。**  

```
Get-EC2RouteTable
```
**出力:**  

```
DestinationCidrBlock    : 10.0.0.0/16
DestinationPrefixListId :
GatewayId               : local
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRouteTable
State                   : active
VpcPeeringConnectionId  :

DestinationCidrBlock    : 0.0.0.0/0
DestinationPrefixListId :
GatewayId               : igw-1a2b3c4d
InstanceId              :
InstanceOwnerId         :
NetworkInterfaceId      :
Origin                  : CreateRoute
State                   : active
VpcPeeringConnectionId  :
```
**例 2: この例では、指定されたルートテーブルの詳細を返します。**  

```
Get-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**例 3: この例では、指定された VPC のルートテーブルを記述します。**  

```
Get-EC2RouteTable -Filter @{ Name="vpc-id"; Values="vpc-1a2b3c4d" }
```
**出力:**  

```
Associations    : {rtbassoc-12345678}
PropagatingVgws : {}
Routes          : {, }
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeRouteTables](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2ScheduledInstance`
<a name="ec2_DescribeScheduledInstances_powershell_5_topic"></a>

次のコード例は、`Get-EC2ScheduledInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定のスケジュールされたインスタンスを記述します。**  

```
Get-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012
```
**出力:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
**例 2: この例では、すべてのスケジュールされたインスタンスを記述します。**  

```
Get-EC2ScheduledInstance
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2ScheduledInstanceAvailability`
<a name="ec2_DescribeScheduledInstanceAvailability_powershell_5_topic"></a>

次のコード例は、`Get-EC2ScheduledInstanceAvailability` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した日付から毎週日曜日に発生するスケジュールを記述します。**  

```
Get-EC2ScheduledInstanceAvailability -Recurrence_Frequency Weekly -Recurrence_Interval 1 -Recurrence_OccurrenceDay 1 -FirstSlotStartTimeRange_EarliestTime 2016-01-31T00:00:00Z -FirstSlotStartTimeRange_LatestTime 2016-01-31T04:00:00Z
```
**出力:**  

```
AvailabilityZone            : us-west-2b
AvailableInstanceCount      : 20
FirstSlotStartTime          : 1/31/2016 8:00:00 AM
HourlyPrice                 : 0.095
InstanceType                : c4.large
MaxTermDurationInDays       : 366
MinTermDurationInDays       : 366
NetworkPlatform             : EC2-VPC
Platform                    : Linux/UNIX
PurchaseToken               : eyJ2IjoiMSIsInMiOjEsImMiOi...
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
SlotDurationInHours         : 23
TotalScheduledInstanceHours : 1219

...
```
**例 2: 結果を絞り込むには、オペレーティングシステム、ネットワーク、インスタンスタイプなどの条件でフィルターを追加できます。**  

```
-Filter @{ Name="platform";Values="Linux/UNIX" },@{ Name="network-platform";Values="EC2-VPC" },@{ Name="instance-type";Values="c4.large" }
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeScheduledInstanceAvailability](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SecurityGroup`
<a name="ec2_DescribeSecurityGroups_powershell_5_topic"></a>

次のコード例は、`Get-EC2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、VPC に指定されたセキュリティグループについて記述します。VPC に属するセキュリティグループを使用する場合は、グループ名 (-GroupName パラメータ) ではなくセキュリティグループ ID (-GroupId パラメータ) を使用してグループを参照する必要があります。**  

```
Get-EC2SecurityGroup -GroupId sg-12345678
```
**出力:**  

```
Description         : default VPC security group
GroupId             : sg-12345678
GroupName           : default
IpPermissions       : {Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {Amazon.EC2.Model.IpPermission}
OwnerId             : 123456789012
Tags                : {}
VpcId               : vpc-12345678
```
**例 2: この例では、EC2-Classic に指定されたセキュリティグループを記述します。EC2-Classic のセキュリティグループを使用する場合は、グループ名 (-GroupName パラメータ) またはグループ ID (-GroupId パラメータ) を使用してセキュリティグループを参照できます。**  

```
Get-EC2SecurityGroup -GroupName my-security-group
```
**出力:**  

```
Description         : my security group
GroupId             : sg-45678901
GroupName           : my-security-group
IpPermissions       : {Amazon.EC2.Model.IpPermission, Amazon.EC2.Model.IpPermission}
IpPermissionsEgress : {}
OwnerId             : 123456789012
Tags                : {}
VpcId               :
```
**例 3: この例では、vpc-0fc1ff23456b789eb のすべてのセキュリティグループを取得します。**  

```
Get-EC2SecurityGroup -Filter @{Name="vpc-id";Values="vpc-0fc1ff23456b789eb"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Snapshot`
<a name="ec2_DescribeSnapshots_powershell_5_topic"></a>

次のコード例は、`Get-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したスナップショットを記述します。**  

```
Get-EC2Snapshot -SnapshotId snap-12345678
```
**出力:**  

```
DataEncryptionKeyId :
Description         : Created by CreateImage(i-1a2b3c4d) for ami-12345678 from vol-12345678
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            : 100%
SnapshotId          : snap-12345678
StartTime           : 10/23/2014 6:01:28 AM
State               : completed
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 8
```
**例 2: この例では、「Name」タグを持つスナップショットを記述します。**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" }
```
**例 3: この例では、「Name」タグと値「TestValue」を持つスナップショットを記述します。**  

```
Get-EC2Snapshot | ? { $_.Tags.Count -gt 0 -and $_.Tags.Key -eq "Name" -and $_.Tags.Value -eq "TestValue" }
```
**例 4: この例では、すべてのスナップショットを記述します。**  

```
Get-EC2Snapshot -Owner self
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SnapshotAttribute`
<a name="ec2_DescribeSnapshotAttribute_powershell_5_topic"></a>

次のコード例は、`Get-EC2SnapshotAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスナップショットの指定された属性を記述します。**  

```
Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute ProductCodes
```
**出力:**  

```
CreateVolumePermissions    ProductCodes    SnapshotId
-----------------------    ------------    ----------
{}                         {}              snap-12345678
```
**例 2: この例では、指定されたスナップショットの指定された属性を記述します。**  

```
(Get-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission).CreateVolumePermissions
```
**出力:**  

```
Group    UserId
-----    ------
all
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SpotDatafeedSubscription`
<a name="ec2_DescribeSpotDatafeedSubscription_powershell_5_topic"></a>

次のコード例は、`Get-EC2SpotDatafeedSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スポットインスタンスのデータフィードについて記述します。**  

```
Get-EC2SpotDatafeedSubscription
```
**出力:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SpotFleetInstance`
<a name="ec2_DescribeSpotFleetInstances_powershell_5_topic"></a>

次のコード例は、`Get-EC2SpotFleetInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスポットフリートリクエストに関連付けられたインスタンスについて記述します。**  

```
Get-EC2SpotFleetInstance -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
```
**出力:**  

```
InstanceId    InstanceType    SpotInstanceRequestId
----------    ------------    ---------------------
i-f089262a    c3.large        sir-12345678
i-7e8b24a4    c3.large        sir-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSpotFleetInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SpotFleetRequest`
<a name="ec2_DescribeSpotFleetRequests_powershell_5_topic"></a>

次のコード例は、`Get-EC2SpotFleetRequest` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスポットフリートリクエストを記述します。**  

```
Get-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE | format-list
```
**出力:**  

```
ConfigData            : Amazon.EC2.Model.SpotFleetRequestConfigData
CreateTime            : 12/26/2015 8:23:33 AM
SpotFleetRequestId    : sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE
SpotFleetRequestState : active
```
**例 2: この例では、すべてのスポットフリートリクエストを記述します。**  

```
Get-EC2SpotFleetRequest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SpotFleetRequestHistory`
<a name="ec2_DescribeSpotFleetRequestHistory_powershell_5_topic"></a>

次のコード例は、`Get-EC2SpotFleetRequestHistory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスポットフリートリクエストの履歴を記述します。**  

```
Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z
```
**出力:**  

```
HistoryRecords     : {Amazon.EC2.Model.HistoryRecord, Amazon.EC2.Model.HistoryRecord...}
LastEvaluatedTime  : 12/26/2015 8:29:11 AM
NextToken          :
SpotFleetRequestId : sfr-088bc5f1-7e7b-451a-bd13-757f10672b93
StartTime          : 12/25/2015 8:00:00 AM
```

```
(Get-EC2SpotFleetRequestHistory -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -StartTime 2015-12-26T00:00:00Z).HistoryRecords
```
**出力:**  

```
EventInformation                     EventType             Timestamp
----------------                     ---------             ---------
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    fleetRequestChange    12/26/2015 8:23:33 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:34 AM
Amazon.EC2.Model.EventInformation    launched              12/26/2015 8:25:05 AM
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSpotFleetRequestHistory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SpotInstanceRequest`
<a name="ec2_DescribeSpotInstanceRequests_powershell_5_topic"></a>

次のコード例は、`Get-EC2SpotInstanceRequest` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したスポットインスタンスを記述します。**  

```
Get-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**出力:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 4/8/2015 2:51:33 PM
Fault                    :
InstanceId               : i-12345678
LaunchedAvailabilityZone : us-west-2b
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.020000
State                    : active
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {Name}
Type                     : one-time
```
**例 2: この例では、すべてのスポットインスタンスリクエストを記述します。**  

```
Get-EC2SpotInstanceRequest
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2SpotPriceHistory`
<a name="ec2_DescribeSpotPriceHistory_powershell_5_topic"></a>

次のコード例は、`Get-EC2SpotPriceHistory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスタイプとアベイラビリティーゾーンのスポット料金履歴から直近 10 件のエントリを取得します。-AvailabilityZone パラメータに指定された値は、コマンドレットの -Region パラメータ (例に示されていない) に指定されたリージョン値に対して有効であるか、シェルでデフォルトとして設定されている必要があることに注意してください。このコマンド例では、「us-west-2」のデフォルトリージョンが環境で設定されていることを前提としています。**  

```
Get-EC2SpotPriceHistory -InstanceType c3.large -AvailabilityZone us-west-2a -MaxResult 10
```
**出力:**  

```
AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:39:49 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017200
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 7:38:29 AM

AvailabilityZone   : us-west-2a
InstanceType       : c3.large
Price              : 0.017300
ProductDescription : Linux/UNIX (Amazon VPC)
Timestamp          : 12/25/2015 6:57:13 AM
...
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSpotPriceHistory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Subnet`
<a name="ec2_DescribeSubnets_powershell_5_topic"></a>

次のコード例は、`Get-EC2Subnet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したサブネットを記述します。**  

```
Get-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : available
SubnetId                : subnet-1a2b3c4d
Tags                    : {}
VpcId                   : vpc-12345678
```
**例 2: この例では、すべてのサブネットを記述します。**  

```
Get-EC2Subnet
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeSubnets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Tag`
<a name="ec2_DescribeTags_powershell_5_topic"></a>

次のコード例は、`Get-EC2Tag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リソースタイプ「image」のタグを取得します。**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="image"}
```
**出力:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
Name        ami-0a123b4ccb567a8ea image        Win7-Imported
auto-delete ami-0a123b4ccb567a8ea image        never
```
**例 2: この例では、すべてのリソースのすべてのタグを取得し、リソースタイプ別にグループ化します。**  

```
Get-EC2Tag | Group-Object resourcetype
```
**出力:**  

```
Count Name                      Group
----- ----                      -----
    9 subnet                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   53 instance                  {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    3 route-table               {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    5 security-group            {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
   30 volume                    {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription...}
    1 internet-gateway          {Amazon.EC2.Model.TagDescription}
    3 network-interface         {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    4 elastic-ip                {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    1 dhcp-options              {Amazon.EC2.Model.TagDescription}
    2 image                     {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
    3 vpc                       {Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription, Amazon.EC2.Model.TagDescription}
```
**例 3: この例では、指定されたリージョンでタグ「auto-delete」と値「no」を持つすべてのリソースを表示します。**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"}
```
**出力:**  

```
Key         ResourceId            ResourceType Value
---         ----------            ------------ -----
auto-delete i-0f1bce234d5dd678b   instance     no
auto-delete vol-01d234aa5678901a2 volume       no
auto-delete vol-01234bfb5def6f7b8 volume       no
auto-delete vol-01ccb23f4c5e67890 volume       no
```
**例 4: この例では、タグ「auto-delete」と値「no」を持つすべてのリソースを取得し、次のパイプでさらにフィルターして「instance」リソースタイプのみを解析し、最終的に各インスタンスリソースに対して、そのインスタンス ID 自体を値とする「ThisInstance」タグを作成します。**  

```
Get-EC2Tag -Region eu-west-1 -Filter @{Name="tag:auto-delete";Values="no"} | Where-Object ResourceType -eq "instance" | ForEach-Object {New-EC2Tag -ResourceId $_.ResourceId -Tag @{Key="ThisInstance";Value=$_.ResourceId}}
```
**例 5: この例では、すべてのインスタンスリソースのタグと「Name」キーを取得し、テーブル形式で表示します。**  

```
Get-EC2Tag -Filter @{Name="resource-type";Values="instance"},@{Name="key";Values="Name"} | Select-Object ResourceId, @{Name="Name-Tag";Expression={$PSItem.Value}} | Format-Table -AutoSize
```
**出力:**  

```
ResourceId          Name-Tag
----------          --------
i-012e3cb4df567e1aa jump1
i-01c23a45d6fc7a89f repro-3
```
**例 6: この例では、実際に EC2 タグを取得することなく、DryRun パラメータを使用して EC2 タグ取得のアクセス許可を検証します。注: 成功すると例外がスローされますが、これは正常な動作です。**  

```
Get-EC2Tag -DryRun $true
```
**出力:**  

```
Get-EC2Tag: Request would have succeeded, but DryRun flag is set.
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-EC2Volume`
<a name="ec2_DescribeVolumes_powershell_5_topic"></a>

次のコード例は、`Get-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した EBS ボリュームを記述します。**  

```
Get-EC2Volume -VolumeId vol-12345678
```
**出力:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 7/17/2015 4:35:19 PM
Encrypted        : False
Iops             : 90
KmsKeyId         :
Size             : 30
SnapshotId       : snap-12345678
State            : in-use
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : standard
```
**例 2: この例では、ステータスが「使用可能」の EBS ボリュームを記述します。**  

```
Get-EC2Volume -Filter @{ Name="status"; Values="available" }
```
**出力:**  

```
Attachments      : {}
AvailabilityZone : us-west-2c
CreateTime       : 12/21/2015 2:31:29 PM
Encrypted        : False
Iops             : 60
KmsKeyId         :
Size             : 20
SnapshotId       : snap-12345678
State            : available
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
...
```
**例 3: この例では、すべての EBS ボリュームを記述します。**  

```
Get-EC2Volume
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVolumes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VolumeAttribute`
<a name="ec2_DescribeVolumeAttribute_powershell_5_topic"></a>

次のコード例は、`Get-EC2VolumeAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたボリュームの指定された属性を記述します。**  

```
Get-EC2VolumeAttribute -VolumeId vol-12345678 -Attribute AutoEnableIO
```
**出力:**  

```
AutoEnableIO    ProductCodes    VolumeId
------------    ------------    --------
False           {}              vol-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVolumeAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VolumeStatus`
<a name="ec2_DescribeVolumeStatus_powershell_5_topic"></a>

次のコード例は、`Get-EC2VolumeStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたボリュームのステータスを記述します。**  

```
Get-EC2VolumeStatus -VolumeId vol-12345678
```
**出力:**  

```
Actions          : {}
AvailabilityZone : us-west-2a
Events           : {}
VolumeId         : vol-12345678
VolumeStatus     : Amazon.EC2.Model.VolumeStatusInfo
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus
```
**出力:**  

```
Details                         Status
-------                         ------
{io-enabled, io-performance}    ok
```

```
(Get-EC2VolumeStatus -VolumeId vol-12345678).VolumeStatus.Details
```
**出力:**  

```
Name                            Status
----                            ------
io-enabled                      passed
io-performance                  not-applicable
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVolumeStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2Vpc`
<a name="ec2_DescribeVpcs_powershell_5_topic"></a>

次のコード例は、`Get-EC2Vpc` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した VPC を記述します。**  

```
Get-EC2Vpc -VpcId vpc-12345678
```
**出力:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : available
Tags            : {Name}
VpcId           : vpc-12345678
```
**例 2: この例では、デフォルトの VPC を記述します (リージョンごとに 1 つだけ指定できます)。アカウントがこのリージョンで EC2-Classic をサポートしている場合、デフォルトの VPC はありません。**  

```
Get-EC2Vpc -Filter @{Name="isDefault"; Values="true"}
```
**出力:**  

```
CidrBlock       : 172.31.0.0/16
DhcpOptionsId   : dopt-12345678
InstanceTenancy : default
IsDefault       : True
State           : available
Tags            : {}
VpcId           : vpc-45678901
```
**例 3: この例では、指定されたフィルターに一致する VPC を記述します (つまり、値 「10.0.0.0/16」に一致する CIDR を持ち、状態が「available」である VPC)。**  

```
Get-EC2Vpc -Filter @{Name="cidr"; Values="10.0.0.0/16"},@{Name="state";Values="available"}
```
**例 4: この例では、すべての VPC を記述します。**  

```
Get-EC2Vpc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpcs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VpcAttribute`
<a name="ec2_DescribeVpcAttribute_powershell_5_topic"></a>

次のコード例は、`Get-EC2VpcAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「enableDnsSupport」属性を記述します。**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsSupport
```
**出力:**  

```
EnableDnsSupport
----------------
True
```
**例 2: この例では、「enableDnsHostnames」属性を記述します。**  

```
Get-EC2VpcAttribute -VpcId vpc-12345678 -Attribute enableDnsHostnames
```
**出力:**  

```
EnableDnsHostnames
------------------
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpcAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VpcClassicLink`
<a name="ec2_DescribeVpcClassicLink_powershell_5_topic"></a>

次のコード例は、`Get-EC2VpcClassicLink` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 上記の例では、リージョンの ClassicLinkEnabled 状態を持つすべての VPC を返します。**  

```
Get-EC2VpcClassicLink -Region eu-west-1
```
**出力:**  

```
ClassicLinkEnabled Tags   VpcId
------------------ ----   -----
False              {Name} vpc-0fc1ff23f45b678eb
False              {}     vpc-01e23c4a5d6db78e9
False              {Name} vpc-0123456b078b9d01f
False              {}     vpc-12cf3b4f
False              {Name} vpc-0b12d3456a7e8901d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpcClassicLink](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VpcClassicLinkDnsSupport`
<a name="ec2_DescribeVpcClassicLinkDnsSupport_powershell_5_topic"></a>

次のコード例は、`Get-EC2VpcClassicLinkDnsSupport` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リージョン eu-west-1 の VPC の ClassicLink DNS サポートステータスを記述します。**  

```
Get-EC2VpcClassicLinkDnsSupport -VpcId vpc-0b12d3456a7e8910d -Region eu-west-1
```
**出力:**  

```
ClassicLinkDnsSupported VpcId
----------------------- -----
False                   vpc-0b12d3456a7e8910d
False                   vpc-12cf3b4f
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpcClassicLinkDnsSupport](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VpcEndpoint`
<a name="ec2_DescribeVpcEndpoints_powershell_5_topic"></a>

次のコード例は、`Get-EC2VpcEndpoint` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リージョン eu-west-1 の 1 つ以上の VPC エンドポイントについて記述します。次に、出力を次のコマンドにパイプします。このコマンドは VpcEndpointId プロパティを選択し、配列 VPC ID を文字列配列として返します。**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object -ExpandProperty VpcEndpointId
```
**出力:**  

```
vpce-01a2ab3f4f5cc6f7d
vpce-01d2b345a6787890b
vpce-0012e34d567890e12
vpce-0c123db4567890123
```
**例 2: この例では、リージョン eu-west-1 のすべての vpc エンドポイントを記述し、VpcEndpointId、VpcId、ServiceName、および PrivateDnsEnabled プロパティを選択して表形式で表示します。**  

```
Get-EC2VpcEndpoint -Region eu-west-1 | Select-Object VpcEndpointId, VpcId, ServiceName, PrivateDnsEnabled | Format-Table -AutoSize
```
**出力:**  

```
VpcEndpointId          VpcId                 ServiceName                         PrivateDnsEnabled
-------------          -----                 -----------                         -----------------
vpce-02a2ab2f2f2cc2f2d vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssm                      True
vpce-01d1b111a1114561b vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2                      True
vpce-0011e23d45167e838 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ec2messages              True
vpce-0c123db4567890123 vpc-0fc6ff46f65b039eb com.amazonaws.eu-west-1.ssmmessages              True
```
**例 3: この例では、VPC エンドポイント vpce-01a2ab3f4f5cc6f7d のポリシードキュメントを JSON ファイルにエクスポートします。**  

```
Get-EC2VpcEndpoint -Region eu-west-1 -VpcEndpointId vpce-01a2ab3f4f5cc6f7d | Select-Object -expand PolicyDocument | Out-File vpce_policyDocument.json
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpcEndpoints](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VpcEndpointService`
<a name="ec2_DescribeVpcEndpointServices_powershell_5_topic"></a>

次のコード例は、`Get-EC2VpcEndpointService` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたフィルター (この場合は com.amazonaws.eu-west-1.ecs) を持つ EC2 VPC エンドポイントサービスについて記述します。さらに、ServiceDetails プロパティも展開され、詳細が表示されます。**  

```
Get-EC2VpcEndpointService -Region eu-west-1 -MaxResult 5 -Filter @{Name="service-name";Values="com.amazonaws.eu-west-1.ecs"} | Select-Object -ExpandProperty ServiceDetails
```
**出力:**  

```
AcceptanceRequired         : False
AvailabilityZones          : {eu-west-1a, eu-west-1b, eu-west-1c}
BaseEndpointDnsNames       : {ecs.eu-west-1.vpce.amazonaws.com}
Owner                      : amazon
PrivateDnsName             : ecs.eu-west-1.amazonaws.com
ServiceName                : com.amazonaws.eu-west-1.ecs
ServiceType                : {Amazon.EC2.Model.ServiceTypeDetail}
VpcEndpointPolicySupported : False
```
**例 2: この例では、すべての EC2 VPC エンドポイントサービスを取得し、「ssm」に一致する ServiceNames を返します。**  

```
Get-EC2VpcEndpointService -Region eu-west-1 | Select-Object -ExpandProperty Servicenames | Where-Object { -match "ssm"}
```
**出力:**  

```
com.amazonaws.eu-west-1.ssm
com.amazonaws.eu-west-1.ssmmessages
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpcEndpointServices](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VpnConnection`
<a name="ec2_DescribeVpnConnections_powershell_5_topic"></a>

次のコード例は、`Get-EC2VpnConnection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPN 接続を記述します。**  

```
Get-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**出力:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      : Amazon.EC2.Model.VpnConnectionOptions
Routes                       : {Amazon.EC2.Model.VpnStaticRoute}
State                        : available
Tags                         : {}
Type                         : ipsec.1
VgwTelemetry                 : {Amazon.EC2.Model.VgwTelemetry, Amazon.EC2.Model.VgwTelemetry}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**例 2: この例では、保留中または使用可能な状態の VPN 接続を記述します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnConnection -Filter $filter
```
**例 3: この例では、すべての VPN 接続を記述します。**  

```
Get-EC2VpnConnection
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpnConnections](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EC2VpnGateway`
<a name="ec2_DescribeVpnGateways_powershell_5_topic"></a>

次のコード例は、`Get-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された仮想プライベートゲートウェイを記述します。**  

```
Get-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**出力:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {vpc-12345678}
VpnGatewayId     : vgw-1a2b3c4d
```
**例 2: この例では、保留中または使用可能な状態の仮想プライベートゲートウェイを記述します。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "state"
$filter.Values = @( "pending", "available" )

Get-EC2VpnGateway -Filter $filter
```
**例 3: この例では、仮想プライベートゲートウェイを記述します。**  

```
Get-EC2VpnGateway
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeVpnGateways](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Grant-EC2SecurityGroupEgress`
<a name="ec2_AuthorizeSecurityGroupEgress_powershell_5_topic"></a>

次のコード例は、`Grant-EC2SecurityGroupEgress` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループの退出ルールを定義します。このルールは、TCP ポート 80 で、指定された IP アドレス範囲へのアクセスを許可します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 3: この例では、TCP ポート 80 で指定されたソースセキュリティグループへのアクセスを許可します。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AuthorizeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Grant-EC2SecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_powershell_5_topic"></a>

次のコード例は、`Grant-EC2SecurityGroupIngress` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2-VPC のセキュリティグループの進入ルールを定義します。これらのルールは、SSH (ポート 22) と RDC (ポート 3389) の特定の IP アドレスへのアクセスを許可します。セキュリティグループの名前ではなく、セキュリティグループの ID を使用して、EC2-VPC のセキュリティグループを識別する必要があります。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
```
**例 3: この例では、EC2-Classic のセキュリティグループの進入ルールを定義します。これらのルールは、SSH (ポート 22) と RDC (ポート 3389) の特定の IP アドレスへのアクセスを許可します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" }
$ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" }

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**例 4: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip1 = New-Object Amazon.EC2.Model.IpPermission
$ip1.IpProtocol = "tcp"
$ip1.FromPort = 22
$ip1.ToPort = 22
$ip1.IpRanges.Add("203.0.113.25/32")

$ip2 = new-object Amazon.EC2.Model.IpPermission
$ip2.IpProtocol = "tcp"
$ip2.FromPort = 3389
$ip2.ToPort = 3389
$ip2.IpRanges.Add("203.0.113.25/32")

Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
```
**例 5: この例では、指定されたソースセキュリティグループ (sg-1a2b3c4d) から指定されたセキュリティグループ (sg-12345678) への TCP ポート 8081 のアクセスを許可します。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"

Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="8081"; ToPort="8081"; UserIdGroupPairs=$ug } )
```
**例 6: この例では、セキュリティグループ sg-1234abcd の進入ルールに、TCP ポート 22 トラフィック用の CIDR 5.5.5.5/32 を説明付きで追加します。**  

```
$IpRange = New-Object -TypeName Amazon.EC2.Model.IpRange
$IpRange.CidrIp = "5.5.5.5/32"
$IpRange.Description = "SSH from Office"
$IpPermission = New-Object Amazon.EC2.Model.IpPermission
$IpPermission.IpProtocol = "tcp"
$IpPermission.ToPort = 22
$IpPermission.FromPort = 22
$IpPermission.Ipv4Ranges = $IpRange
Grant-EC2SecurityGroupIngress -GroupId sg-1234abcd -IpPermission $IpPermission
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Import-EC2Image`
<a name="ec2_ImportImage_powershell_5_topic"></a>

次のコード例は、`Import-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、べき等性トークンを使用して、指定された Amazon S3 バケットから Amazon EC2 にシングルディスク仮想マシンイメージをインポートします。この例では、「VM Import Prequisites」トピックで説明されているように、デフォルトの名前が「vmimport」の VM Import サービスロールが存在し、指定されたバケットへの Amazon EC2 アクセスを許可するポリシーが付与されている必要があります。カスタムロールを使用するには、`-RoleName` パラメータを使用してロール名を指定します。**  

```
$container = New-Object Amazon.EC2.Model.ImageDiskContainer
$container.Format="VMDK"
$container.UserBucket = New-Object Amazon.EC2.Model.UserBucket
$container.UserBucket.S3Bucket = "amzn-s3-demo-bucket"
$container.UserBucket.S3Key = "Win_2008_Server_Standard_SP2_64-bit-disk1.vmdk"

$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Windows 2008 Standard Image Import"
    "Platform"="Windows"
    "LicenseType"="AWS"
}

Import-EC2Image -DiskContainer $container @parms
```
**出力:**  

```
Architecture    : 
Description     : Windows 2008 Standard Image
Hypervisor      : 
ImageId         : 
ImportTaskId    : import-ami-abcdefgh
LicenseType     : AWS
Platform        : Windows
Progress        : 2
SnapshotDetails : {}
Status          : active
StatusMessage   : pending
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ImportImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Import-EC2KeyPair`
<a name="ec2_ImportKeyPair_powershell_5_topic"></a>

次のコード例は、`Import-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パブリックキーを EC2 にインポートします。最初の行は、パブリックキーファイル (\$1.pub) の内容を変数 `$publickey` に保存します。次に、パブリックキーファイルの UTF8 形式を Base64 でエンコードされた文字列に変換し、変換された文字列を変数 `$pkbase64` に保存します。最後の行では、変換されたパブリックキーが EC2 にインポートされます。コマンドレットは、キーフィンガープリントと名前を結果として返します。**  

```
$publickey=[Io.File]::ReadAllText("C:\Users\TestUser\.ssh\id_rsa.pub")
$pkbase64 = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($publickey))
Import-EC2KeyPair -KeyName Example-user-key -PublicKey $pkbase64
```
**出力:**  

```
KeyFingerprint                                  KeyName
--------------                                  -------
do:d0:15:8f:79:97:12:be:00:fd:df:31:z3:b1:42:z1 Example-user-key
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ImportKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Import-EC2Snapshot`
<a name="ec2_ImportSnapshot_powershell_5_topic"></a>

次のコード例は、`Import-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「VMDK」形式の VM ディスクイメージを Amazon EBS スナップショットにインポートします。この例では、http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/VMImportPrerequisites.html の `VM Import Prequisites` トピックで説明されているように、デフォルトの名前が「vmimport」の VM Import サービスロールと、指定されたバケットへの Amazon EC2 アクセスを許可するポリシーが必要です。カスタムロールを使用するには、`-RoleName` パラメータを使用してロール名を指定します。**  

```
$parms = @{
    "ClientToken"="idempotencyToken"
    "Description"="Disk Image Import"
    "DiskContainer_Description" = "Data disk"
    "DiskContainer_Format" = "VMDK"
    "DiskContainer_S3Bucket" = "amzn-s3-demo-bucket"
    "DiskContainer_S3Key" = "datadiskimage.vmdk"
}

Import-EC2Snapshot @parms
```
**出力:**  

```
Description            ImportTaskId               SnapshotTaskDetail                                                          
-----------------      --------------------       ------------------                                                          
Disk Image Import      import-snap-abcdefgh       Amazon.EC2.Model.SnapshotTaskDetail
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[ImportSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Move-EC2AddressToVpc`
<a name="ec2_MoveAddressToVpc_powershell_5_topic"></a>

次のコード例は、`Move-EC2AddressToVpc` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パブリック IP アドレスが 12.345.67.89 の EC2 インスタンスを、米国東部 (バージニア北部) リージョンの EC2-VPC プラットフォームに移動します。**  

```
Move-EC2AddressToVpc -PublicIp 12.345.67.89 -Region us-east-1
```
**例 2: この例では、Get-EC2Instance コマンドの結果を Move-EC2AddressToVpc コマンドレットにパイプします。Get-EC2Instance コマンドは、インスタンス ID で指定されたインスタンスを取得し、インスタンスのパブリック IP アドレスプロパティを返します。**  

```
(Get-EC2Instance -Instance i-12345678).Instances.PublicIpAddress | Move-EC2AddressToVpc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[MoveAddressToVpc](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Address`
<a name="ec2_AllocateAddress_powershell_5_topic"></a>

次のコード例は、`New-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、VPC 内のインスタンスで使用する Elastic IP アドレスを割り当てます。**  

```
New-EC2Address -Domain Vpc
```
**出力:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
eipalloc-12345678    vpc         198.51.100.2
```
**例 2: この例では、EC2-Classic のインスタンスで使用する Elastic IP アドレスを割り当てます。**  

```
New-EC2Address
```
**出力:**  

```
AllocationId         Domain      PublicIp
------------         ------      --------
                     standard    203.0.113.17
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AllocateAddress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2CustomerGateway`
<a name="ec2_CreateCustomerGateway_powershell_5_topic"></a>

次のコード例は、`New-EC2CustomerGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたカスタマーゲートウェイを作成します。**  

```
New-EC2CustomerGateway -Type ipsec.1 -PublicIp 203.0.113.12 -BgpAsn 65534
```
**出力:**  

```
BgpAsn            : 65534
CustomerGatewayId : cgw-1a2b3c4d
IpAddress         : 203.0.113.12
State             : available
Tags              : {}
Type              : ipsec.1
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2DhcpOption`
<a name="ec2_CreateDhcpOptions_powershell_5_topic"></a>

次のコード例は、`New-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された DHCP オプションのセットを作成します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$options = @( @{Key="domain-name";Values=@("abc.local")}, @{Key="domain-name-servers";Values=@("10.0.0.101","10.0.0.102")})
New-EC2DhcpOption -DhcpConfiguration $options
```
**出力:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-1a2b3c4d    {}
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して各 DHCP オプションを作成する必要があります。**  

```
$option1 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option1.Key = "domain-name"
$option1.Values = "abc.local"

$option2 = New-Object Amazon.EC2.Model.DhcpConfiguration
$option2.Key = "domain-name-servers"
$option2.Values = @("10.0.0.101","10.0.0.102")

New-EC2DhcpOption -DhcpConfiguration @($option1, $option2)
```
**出力:**  

```
DhcpConfigurations                    DhcpOptionsId    Tags
------------------                    -------------    ----
{domain-name, domain-name-servers}    dopt-2a3b4c5d    {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2FlowLog`
<a name="ec2_CreateFlowLogs_powershell_5_topic"></a>

次のコード例は、`New-EC2FlowLog` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「Admin」ロールの権限を使用して、サブネット subnet-1d234567 に対する EC2 フローログを、すべての「REJECT」トラフィックを対象に、「subnet1-log」という名前の cloud-watch-log に作成します。**  

```
New-EC2FlowLog -ResourceId "subnet-1d234567" -LogDestinationType cloud-watch-logs -LogGroupName subnet1-log -TrafficType "REJECT" -ResourceType Subnet -DeliverLogsPermissionArn "arn:aws:iam::98765432109:role/Admin"
```
**出力:**  

```
ClientToken                                  FlowLogIds             Unsuccessful
-----------                                  ----------             ------------
m1VN2cxP3iB4qo//VUKl5EU6cF7gQLOxcqNefvjeTGw= {fl-012fc34eed5678c9d} {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Host`
<a name="ec2_AllocateHosts_powershell_5_topic"></a>

次のコード例は、`New-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスタイプとアベイラビリティーゾーンのアカウントに専有ホストを割り当てます。**  

```
New-EC2Host -AutoPlacement on -AvailabilityZone eu-west-1b -InstanceType m4.xlarge -Quantity 1
```
**出力:**  

```
h-01e23f4cd567890f3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AllocateHosts](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2HostReservation`
<a name="ec2_PurchaseHostReservation_powershell_5_topic"></a>

次のコード例は、`New-EC2HostReservation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、専有ホスト h-01e23f4cd567890f1 の構成と一致する設定で、hro-0c1f23456789d0ab の予約サービスを購入します。**  

```
New-EC2HostReservation -OfferingId hro-0c1f23456789d0ab HostIdSet h-01e23f4cd567890f1
```
**出力:**  

```
ClientToken       :
CurrencyCode      :
Purchase          : {hr-0123f4b5d67bedc89}
TotalHourlyPrice  : 1.307
TotalUpfrontPrice : 0.000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PurchaseHostReservation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Image`
<a name="ec2_CreateImage_powershell_5_topic"></a>

次のコード例は、`New-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスから、指定された名前と説明を持つ AMI を作成します。Amazon EC2 は、イメージを作成する前にインスタンスのクリーンシャットダウンを試み、完了時にインスタンスを再起動します。**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI"
```
**例 2: この例では、指定されたインスタンスから、指定された名前と説明を持つ AMI を作成します。Amazon EC2 は、インスタンスのシャットダウンと再起動をせずにイメージを作成するため、作成されたイメージのファイルシステムの整合性は保証されません。**  

```
New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -NoReboot $true
```
**例 3: この例では、3 つのボリュームを持つ AMI を作成します。最初のボリュームは Amazon EBS スナップショットに基づいています。2 番目のボリュームは空の 100 GiB Amazon EBS ボリュームです。3 番目のボリュームはインスタンスストアボリュームです。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ebsBlock1 = @{SnapshotId="snap-1a2b3c4d"}
$ebsBlock2 = @{VolumeSize=100}

New-EC2Image -InstanceId i-12345678 -Name "my-web-server" -Description "My web server AMI" -BlockDeviceMapping @( @{DeviceName="/dev/sdf";Ebs=$ebsBlock1}, @{DeviceName="/dev/sdg";Ebs=$ebsBlock2}, @{DeviceName="/dev/sdc";VirtualName="ephemeral0"})
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Instance`
<a name="ec2_RunInstances_powershell_5_topic"></a>

次のコード例は、`New-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2-Classic またはデフォルトの VPC で指定された AMI の単一のインスタンスを起動します。**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -InstanceType m3.medium -KeyName my-key-pair -SecurityGroup my-security-group
```
**例 2: この例では、VPC で指定された AMI の単一のインスタンスを起動します。**  

```
New-EC2Instance -ImageId ami-12345678 -MinCount 1 -MaxCount 1 -SubnetId subnet-12345678 -InstanceType t2.micro -KeyName my-key-pair -SecurityGroupId sg-12345678
```
**例 3: EBS ボリュームまたはインスタンスストアボリュームを追加するには、ブロックデバイスマッピングを定義してコマンドに追加します。この例では、インスタンスストアボリュームとして追加します。**  

```
$bdm = New-Object Amazon.EC2.Model.BlockDeviceMapping
$bdm.VirtualName = "ephemeral0"
$bdm.DeviceName = "/dev/sdf"

New-EC2Instance -ImageId ami-12345678 -BlockDeviceMapping $bdm ...
```
**例 4: 現在の Windows AMI のいずれかを指定するには、Get-SSMLatestEC2Image を使用して AMI ID を取得します。この例では、Windows Server 2016 の現在のベース AMI からインスタンスを起動します。**  

```
$ami = (Get-SSMLatestEC2Image -Path 'ami-windows-latest' -ImageName 'WINDOWS*2016*English*Core*BASE').Value

New-EC2Instance -ImageId $ami ...
```
**例 5: 指定された専有ホスト環境でインスタンスを起動します。**  

```
New-EC2Instance -ImageId ami-1a2b3c4d -InstanceType m4.large -KeyName my-key-pair -SecurityGroupId sg-1a2b3c4d  -AvailabilityZone us-west-1a -Tenancy host -HostID h-1a2b3c4d5e6f1a2b3
```
**例 6: このリクエストは 2 つのインスタンスを起動し、ウェブサーバーのキーと本番稼働用の値を持つタグをインスタンスに適用します。リクエストは、作成されたボリューム (この場合は各インスタンスのルートボリューム) に、コストセンターのキーと cc123 の値を持つタグも適用します。**  

```
$tag1 = @{ Key="webserver"; Value="production" }
$tag2 = @{ Key="cost-center"; Value="cc123" }

$tagspec1 = new-object Amazon.EC2.Model.TagSpecification
$tagspec1.ResourceType = "instance"
$tagspec1.Tags.Add($tag1)

$tagspec2 = new-object Amazon.EC2.Model.TagSpecification
$tagspec2.ResourceType = "volume"
$tagspec2.Tags.Add($tag2)

New-EC2Instance -ImageId "ami-1a2b3c4d" -KeyName "my-key-pair" -MaxCount 2 -InstanceType "t2.large" -SubnetId "subnet-1a2b3c4d" -TagSpecification $tagspec1,$tagspec2
```
**例 7: この例では、インスタンスを実際に作成せずに DryRun パラメータを使用して EC2 インスタンスを起動するためのアクセス許可を検証します。注: 成功すると例外がスローされますが、これは正常な動作です。**  

```
New-EC2Instance -ImageId 'ami-12345678' -InstanceType 't2.micro' -KeyName 'my-key-pair' -Region 'us-west-2' -DryRun $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RunInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2InstanceExportTask`
<a name="ec2_CreateInstanceExportTask_powershell_5_topic"></a>

次のコード例は、`New-EC2InstanceExportTask` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、停止したインスタンス `i-0800b00a00EXAMPLE` を仮想ハードディスク (VHD)として S3 バケット `testbucket-export-instances-2019` にエクスポートします。ターゲット環境は で`Microsoft`、インスタンスが `us-east-1` リージョンにあり、ユーザーのデフォルト AWS リージョンが us-east-1 ではないため、リージョンパラメータが追加されます。エクスポートタスクのステータスを取得するには、このコマンドの結果から `ExportTaskId` 値をコピーし、`Get-EC2ExportTask -ExportTaskId export_task_ID_from_results.` を実行します。**  

```
New-EC2InstanceExportTask -InstanceId i-0800b00a00EXAMPLE -ExportToS3Task_DiskImageFormat VHD -ExportToS3Task_S3Bucket "amzn-s3-demo-bucket" -TargetEnvironment Microsoft -Region us-east-1
```
**出力:**  

```
Description           : 
ExportTaskId          : export-i-077c73108aEXAMPLE
ExportToS3Task        : Amazon.EC2.Model.ExportToS3Task
InstanceExportDetails : Amazon.EC2.Model.InstanceExportDetails
State                 : active
StatusMessage         :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateInstanceExportTask](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2InternetGateway`
<a name="ec2_CreateInternetGateway_powershell_5_topic"></a>

次のコード例は、`New-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インターネットゲートウェイを作成します。**  

```
New-EC2InternetGateway
```
**出力:**  

```
Attachments    InternetGatewayId    Tags
-----------    -----------------    ----
{}             igw-1a2b3c4d         {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2KeyPair`
<a name="ec2_CreateKeyPair_powershell_5_topic"></a>

次のコード例は、`New-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、キーペアを作成し、指定した名前のファイルに PEM エンコードされた RSA プライベートキーをキャプチャします。PowerShell を使用している場合は、有効なキーを生成するためにエンコーディングを ascii に設定する必要があります。詳細については、「 コマンドラインインターフェイスユーザーガイド」のAmazon EC2 AWS キーペアの作成、表示、削除 (https://docs.aws.amazon.com/cli/latest/userguide/cli-services-ec2-keypairs.html)」を参照してください。**  

```
(New-EC2KeyPair -KeyName "my-key-pair").KeyMaterial | Out-File -Encoding ascii -FilePath C:\path\my-key-pair.pem
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2NetworkAcl`
<a name="ec2_CreateNetworkAcl_powershell_5_topic"></a>

次のコード例は、`New-EC2NetworkAcl` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した VPC に対してネットワーク ACL を作成します。**  

```
New-EC2NetworkAcl -VpcId vpc-12345678
```
**出力:**  

```
Associations : {}
Entries      : {Amazon.EC2.Model.NetworkAclEntry, Amazon.EC2.Model.NetworkAclEntry}
IsDefault    : False
NetworkAclId : acl-12345678
Tags         : {}
VpcId        : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2NetworkAclEntry`
<a name="ec2_CreateNetworkAclEntry_powershell_5_topic"></a>

次のコード例は、`New-EC2NetworkAclEntry` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したネットワーク ACL のエントリを作成します。このルールは、UDP ポート 53 (DNS) 上の任意の場所 (0.0.0.0/0) から任意の関連付けられたサブネットへの受信トラフィックを許可します。**  

```
New-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 0.0.0.0/0 -RuleAction allow
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2NetworkInterface`
<a name="ec2_CreateNetworkInterface_powershell_5_topic"></a>

次のコード例は、`New-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワークインターフェイスを作成します。**  

```
New-EC2NetworkInterface -SubnetId subnet-1a2b3c4d -Description "my network interface" -Group sg-12345678 -PrivateIpAddress 10.0.0.17
```
**出力:**  

```
Association        :
Attachment         :
AvailabilityZone   : us-west-2c
Description        : my network interface
Groups             : {my-security-group}
MacAddress         : 0a:72:bc:1a:cd:7f
NetworkInterfaceId : eni-12345678
OwnerId            : 123456789012
PrivateDnsName     : ip-10-0-0-17.us-west-2.compute.internal
PrivateIpAddress   : 10.0.0.17
PrivateIpAddresses : {}
RequesterId        :
RequesterManaged   : False
SourceDestCheck    : True
Status             : pending
SubnetId           : subnet-1a2b3c4d
TagSet             : {}
VpcId              : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2PlacementGroup`
<a name="ec2_CreatePlacementGroup_powershell_5_topic"></a>

次のコード例は、`New-EC2PlacementGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された名前のプレイスメントグループを作成します。**  

```
New-EC2PlacementGroup -GroupName my-placement-group -Strategy cluster
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreatePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Route`
<a name="ec2_CreateRoute_powershell_5_topic"></a>

次のコード例は、`New-EC2Route` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したルートテーブルに対してルートを作成します。ルートはすべてのトラフィックと一致し、これを指定されたインターネットゲートウェイに送信します。**  

```
New-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0 -GatewayId igw-1a2b3c4d
```
**出力:**  

```
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateRoute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2RouteTable`
<a name="ec2_CreateRouteTable_powershell_5_topic"></a>

次のコード例は、`New-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPC に対してルートテーブルを作成します。**  

```
New-EC2RouteTable -VpcId vpc-12345678
```
**出力:**  

```
Associations    : {}
PropagatingVgws : {}
Routes          : {}
RouteTableId    : rtb-1a2b3c4d
Tags            : {}
VpcId           : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2ScheduledInstance`
<a name="ec2_RunScheduledInstances_powershell_5_topic"></a>

次のコード例は、`New-EC2ScheduledInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定のスケジュールされたインスタンスを起動します。**  

```
New-EC2ScheduledInstance -ScheduledInstanceId sci-1234-1234-1234-1234-123456789012 -InstanceCount 1 `
-IamInstanceProfile_Name my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType c4.large `
-LaunchSpecification_SubnetId subnet-12345678`
-LaunchSpecification_SecurityGroupId sg-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RunScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2ScheduledInstancePurchase`
<a name="ec2_PurchaseScheduledInstances_powershell_5_topic"></a>

次のコード例は、`New-EC2ScheduledInstancePurchase` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スケジュールされたインスタンスを購入します。**  

```
$request = New-Object Amazon.EC2.Model.PurchaseRequest
$request.InstanceCount = 1
$request.PurchaseToken = "eyJ2IjoiMSIsInMiOjEsImMiOi..."
New-EC2ScheduledInstancePurchase -PurchaseRequest $request
```
**出力:**  

```
AvailabilityZone            : us-west-2b
CreateDate                  : 1/25/2016 1:43:38 PM
HourlyPrice                 : 0.095
InstanceCount               : 1
InstanceType                : c4.large
NetworkPlatform             : EC2-VPC
NextSlotStartTime           : 1/31/2016 1:00:00 AM
Platform                    : Linux/UNIX
PreviousSlotEndTime         : 
Recurrence                  : Amazon.EC2.Model.ScheduledInstanceRecurrence
ScheduledInstanceId         : sci-1234-1234-1234-1234-123456789012
SlotDurationInHours         : 32
TermEndDate                 : 1/31/2017 1:00:00 AM
TermStartDate               : 1/31/2016 1:00:00 AM
TotalScheduledInstanceHours : 1696
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[PurchaseScheduledInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2SecurityGroup`
<a name="ec2_CreateSecurityGroup_powershell_5_topic"></a>

次のコード例は、`New-EC2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPC 用にセキュリティグループを作成します。**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group" -VpcId vpc-12345678
```
**出力:**  

```
sg-12345678
```
**例 2: この例では、EC2-Classic のセキュリティグループを作成します。**  

```
New-EC2SecurityGroup -GroupName my-security-group -Description "my security group"
```
**出力:**  

```
sg-45678901
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Snapshot`
<a name="ec2_CreateSnapshot_powershell_5_topic"></a>

次のコード例は、`New-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたボリュームのスナップショットを作成します。**  

```
New-EC2Snapshot -VolumeId vol-12345678 -Description "This is a test"
```
**出力:**  

```
DataEncryptionKeyId :
Description         : This is a test
Encrypted           : False
KmsKeyId            :
OwnerAlias          :
OwnerId             : 123456789012
Progress            :
SnapshotId          : snap-12345678
StartTime           : 12/22/2015 1:28:42 AM
State               : pending
StateMessage        :
Tags                : {}
VolumeId            : vol-12345678
VolumeSize          : 20
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2SpotDatafeedSubscription`
<a name="ec2_CreateSpotDatafeedSubscription_powershell_5_topic"></a>

次のコード例は、`New-EC2SpotDatafeedSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スポットインスタンスのデータフィードを作成します。**  

```
New-EC2SpotDatafeedSubscription -Bucket amzn-s3-demo-bucket -Prefix spotdata
```
**出力:**  

```
Bucket  : amzn-s3-demo-bucket
Fault   :
OwnerId : 123456789012
Prefix  : spotdata
State   : Active
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Subnet`
<a name="ec2_CreateSubnet_powershell_5_topic"></a>

次のコード例は、`New-EC2Subnet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した CIDR でサブネットを作成します。**  

```
New-EC2Subnet -VpcId vpc-12345678 -CidrBlock 10.0.0.0/24
```
**出力:**  

```
AvailabilityZone        : us-west-2c
AvailableIpAddressCount : 251
CidrBlock               : 10.0.0.0/24
DefaultForAz            : False
MapPublicIpOnLaunch     : False
State                   : pending
SubnetId                : subnet-1a2b3c4d
Tag                     : {}
VpcId                   : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateSubnet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Tag`
<a name="ec2_CreateTags_powershell_5_topic"></a>

次のコード例は、`New-EC2Tag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したリソースに単一のタグを追加します。タグキーは「myTag」で、タグ値は「myTagValue」です。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
New-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag"; Value="myTagValue" }
```
**例 2: この例では、指定されたリソースに指定されたタグを更新または追加します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
New-EC2Tag -Resource i-12345678 -Tag @( @{ Key="myTag"; Value="newTagValue" }, @{ Key="test"; Value="anotherTagValue" } )
```
**例 3: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

New-EC2Tag -Resource i-12345678 -Tag $tag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Volume`
<a name="ec2_CreateVolume_powershell_5_topic"></a>

次のコード例は、`New-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したボリュームを作成します。**  

```
New-EC2Volume -Size 50 -AvailabilityZone us-west-2a -VolumeType gp2
```
**出力:**  

```
Attachments      : {}
AvailabilityZone : us-west-2a
CreateTime       : 12/22/2015 1:42:07 AM
Encrypted        : False
Iops             : 150
KmsKeyId         :
Size             : 50
SnapshotId       :
State            : creating
Tags             : {}
VolumeId         : vol-12345678
VolumeType       : gp2
```
**例 2: このリクエスト例では、ボリュームを作成し、キーがスタック、値が本番環境のタグを適用します。**  

```
$tag = @{ Key="stack"; Value="production" }

$tagspec = new-object Amazon.EC2.Model.TagSpecification
$tagspec.ResourceType = "volume"
$tagspec.Tags.Add($tag)

New-EC2Volume -Size 80 -AvailabilityZone "us-west-2a" -TagSpecification $tagspec
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateVolume](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2Vpc`
<a name="ec2_CreateVpc_powershell_5_topic"></a>

次のコード例は、`New-EC2Vpc` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した CIDR で VPC を作成します。Amazon VPC では、VPC 用に、デフォルトの DHCP オプションセット、メインルートテーブル、デフォルトのネットワーク ACL も作成します。**  

```
New-EC2VPC -CidrBlock 10.0.0.0/16
```
**出力:**  

```
CidrBlock       : 10.0.0.0/16
DhcpOptionsId   : dopt-1a2b3c4d
InstanceTenancy : default
IsDefault       : False
State           : pending
Tags            : {}
VpcId           : vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateVpc](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2VpcEndpoint`
<a name="ec2_CreateVpcEndpoint_powershell_5_topic"></a>

次のコード例は、`New-EC2VpcEndpoint` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、VPC vpc-0fc1ff23f45b678eb でサービス com.amazonaws.eu-west-1.s3 の新しい VPC エンドポイントを作成します。**  

```
New-EC2VpcEndpoint -ServiceName com.amazonaws.eu-west-1.s3 -VpcId vpc-0fc1ff23f45b678eb
```
**出力:**  

```
ClientToken VpcEndpoint
----------- -----------
            Amazon.EC2.Model.VpcEndpoint
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateVpcEndpoint](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2VpnConnection`
<a name="ec2_CreateVpnConnection_powershell_5_topic"></a>

次のコード例は、`New-EC2VpnConnection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した仮想プライベートゲートウェイと指定したカスタマーゲートウェイの間に VPN 接続を作成します。出力には、ネットワーク管理者が必要とする設定情報が XML 形式で含まれます。**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d
```
**出力:**  

```
CustomerGatewayConfiguration : [XML document]
CustomerGatewayId            : cgw-1a2b3c4d
Options                      :
Routes                       : {}
State                        : pending
Tags                         : {}
Type                         :
VgwTelemetry                 : {}
VpnConnectionId              : vpn-12345678
VpnGatewayId                 : vgw-1a2b3c4d
```
**例 2: この例では、VPN 接続を作成し、指定された名前のファイルに設定をキャプチャします。**  

```
(New-EC2VpnConnection -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d).CustomerGatewayConfiguration | Out-File C:\path\vpn-configuration.xml
```
**例 3: この例では、指定された仮想プライベートゲートウェイと指定されたカスタマーゲートウェイの間に VPN 接続を作成します。**  

```
New-EC2VpnConnection -Type ipsec.1 -CustomerGatewayId cgw-1a2b3c4d -VpnGatewayId vgw-1a2b3c4d -Options_StaticRoutesOnly $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2VpnConnectionRoute`
<a name="ec2_CreateVpnConnectionRoute_powershell_5_topic"></a>

次のコード例は、`New-EC2VpnConnectionRoute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPN 接続に対して指定された静的ルートを作成します。**  

```
New-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EC2VpnGateway`
<a name="ec2_CreateVpnGateway_powershell_5_topic"></a>

次のコード例は、`New-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された仮想プライベートゲートウェイを作成します。**  

```
New-EC2VpnGateway -Type ipsec.1
```
**出力:**  

```
AvailabilityZone :
State            : available
Tags             : {}
Type             : ipsec.1
VpcAttachments   : {}
VpnGatewayId     : vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-EC2Address`
<a name="ec2_AssociateAddress_powershell_5_topic"></a>

次のコード例は、`Register-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された Elastic IP アドレスを VPC 内の指定されたインスタンスに関連付けます。**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -AllocationId eipalloc-12345678
```
**出力:**  

```
eipassoc-12345678
```
**例 2: この例では、指定された Elastic IP アドレスを EC2-Classic の指定されたインスタンスに関連付けます。**  

```
C:\> Register-EC2Address -InstanceId i-12345678 -PublicIp 203.0.113.17
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AssociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-EC2DhcpOption`
<a name="ec2_AssociateDhcpOptions_powershell_5_topic"></a>

次のコード例は、`Register-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された DHCP オプションセットを指定された VPC に関連付けます。**  

```
Register-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d -VpcId vpc-12345678
```
**例 2: この例では、デフォルトの DHCP オプションセットを指定された VPC に関連付けます。**  

```
Register-EC2DhcpOption -DhcpOptionsId default -VpcId vpc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AssociateDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-EC2Image`
<a name="ec2_RegisterImage_powershell_5_topic"></a>

次のコード例は、`Register-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Amazon S3 の指定されたマニフェストファイルを使用して AMI を登録します。**  

```
Register-EC2Image -ImageLocation amzn-s3-demo-bucket/my-web-server-ami/image.manifest.xml -Name my-web-server-ami
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RegisterImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-EC2PrivateIpAddress`
<a name="ec2_AssignPrivateIpAddresses_powershell_5_topic"></a>

次のコード例は、`Register-EC2PrivateIpAddress` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたセカンダリプライベート IP アドレスを指定されたネットワークインターフェイスに割り当てます。**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
**例 2: この例では、2 つのセカンダリプライベート IP アドレスを作成し、指定されたネットワークインターフェイスに割り当てます。**  

```
Register-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -SecondaryPrivateIpAddressCount 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AssignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-EC2RouteTable`
<a name="ec2_AssociateRouteTable_powershell_5_topic"></a>

次のコード例は、`Register-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたルートテーブルを指定されたサブネットに関連付けます。**  

```
Register-EC2RouteTable -RouteTableId rtb-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
rtbassoc-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AssociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Address`
<a name="ec2_ReleaseAddress_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、VPC 内のインスタンスに指定された Elastic IP アドレスを解放します。**  

```
Remove-EC2Address -AllocationId eipalloc-12345678 -Force
```
**例 2: この例では、EC2-Classic のインスタンスに指定された Elastic IP アドレスを解放します。**  

```
Remove-EC2Address -PublicIp 198.51.100.2 -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ReleaseAddress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2CapacityReservation`
<a name="ec2_CancelCapacityReservation_powershell_5_topic"></a>

次のコード例は、`Remove-EC2CapacityReservation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、キャパシティ予約 cr-0c1f2345db6f7cdba をキャンセルします。**  

```
Remove-EC2CapacityReservation -CapacityReservationId cr-0c1f2345db6f7cdba
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2CapacityReservation (CancelCapacityReservation)" on target "cr-0c1f2345db6f7cdba".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CancelCapacityReservation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2CustomerGateway`
<a name="ec2_DeleteCustomerGateway_powershell_5_topic"></a>

次のコード例は、`Remove-EC2CustomerGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたカスタマーゲートウェイを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2CustomerGateway -CustomerGatewayId cgw-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2CustomerGateway (DeleteCustomerGateway)" on Target "cgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteCustomerGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2DhcpOption`
<a name="ec2_DeleteDhcpOptions_powershell_5_topic"></a>

次のコード例は、`Remove-EC2DhcpOption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された DHCP オプションのセットを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2DhcpOption -DhcpOptionsId dopt-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2DhcpOption (DeleteDhcpOptions)" on Target "dopt-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteDhcpOptions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2FlowLog`
<a name="ec2_DeleteFlowLogs_powershell_5_topic"></a>

次のコード例は、`Remove-EC2FlowLog` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された FlowLogId fl-01a2b3456a789c01 を削除します。**  

```
Remove-EC2FlowLog -FlowLogId fl-01a2b3456a789c01
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2FlowLog (DeleteFlowLogs)" on target "fl-01a2b3456a789c01".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteFlowLogs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Host`
<a name="ec2_ReleaseHosts_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Host` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたホスト ID h-0badafd1dcb2f3456 を解放します。**  

```
Remove-EC2Host -HostId h-0badafd1dcb2f3456
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Host (ReleaseHosts)" on target "h-0badafd1dcb2f3456".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Successful            Unsuccessful
----------            ------------
{h-0badafd1dcb2f3456} {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ReleaseHosts](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Instance`
<a name="ec2_TerminateInstances_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスを終了します (インスタンスが実行中または「停止状態」である可能性があります)。コマンドレットは、続行する前に確認を求めるプロンプトを表示します。プロンプトを表示しないようにするには、-Force スイッチを使用します。**  

```
Remove-EC2Instance -InstanceId i-12345678
```
**出力:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[TerminateInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2InternetGateway`
<a name="ec2_DeleteInternetGateway_powershell_5_topic"></a>

次のコード例は、`Remove-EC2InternetGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインターネットゲートウェイを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2InternetGateway -InternetGatewayId igw-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2InternetGateway (DeleteInternetGateway)" on Target "igw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteInternetGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2KeyPair`
<a name="ec2_DeleteKeyPair_powershell_5_topic"></a>

次のコード例は、`Remove-EC2KeyPair` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したキーペアを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2KeyPair -KeyName my-key-pair
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2KeyPair (DeleteKeyPair)" on Target "my-key-pair".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteKeyPair](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2NetworkAcl`
<a name="ec2_DeleteNetworkAcl_powershell_5_topic"></a>

次のコード例は、`Remove-EC2NetworkAcl` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワーク ACL を削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2NetworkAcl -NetworkAclId acl-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAcl (DeleteNetworkAcl)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteNetworkAcl](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2NetworkAclEntry`
<a name="ec2_DeleteNetworkAclEntry_powershell_5_topic"></a>

次のコード例は、`Remove-EC2NetworkAclEntry` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワーク ACL から指定されたルールを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkAclEntry (DeleteNetworkAclEntry)" on Target "acl-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2NetworkInterface`
<a name="ec2_DeleteNetworkInterface_powershell_5_topic"></a>

次のコード例は、`Remove-EC2NetworkInterface` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワークインターフェイスを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2NetworkInterface -NetworkInterfaceId eni-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2NetworkInterface (DeleteNetworkInterface)" on Target "eni-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteNetworkInterface](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2PlacementGroup`
<a name="ec2_DeletePlacementGroup_powershell_5_topic"></a>

次のコード例は、`Remove-EC2PlacementGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたプレイスメントグループを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2PlacementGroup -GroupName my-placement-group
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2PlacementGroup (DeletePlacementGroup)" on Target "my-placement-group".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeletePlacementGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Route`
<a name="ec2_DeleteRoute_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Route` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したルートテーブルから指定したルートを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 0.0.0.0/0
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Route (DeleteRoute)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteRoute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2RouteTable`
<a name="ec2_DeleteRouteTable_powershell_5_topic"></a>

次のコード例は、`Remove-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたルートテーブルを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2RouteTable -RouteTableId rtb-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2RouteTable (DeleteRouteTable)" on Target "rtb-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2SecurityGroup`
<a name="ec2_DeleteSecurityGroup_powershell_5_topic"></a>

次のコード例は、`Remove-EC2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2SecurityGroup -GroupId sg-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SecurityGroup (DeleteSecurityGroup)" on Target "sg-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: この例では、EC2-Classic の指定されたセキュリティグループを削除します。**  

```
Remove-EC2SecurityGroup -GroupName my-security-group -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteSecurityGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Snapshot`
<a name="ec2_DeleteSnapshot_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Snapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: こので例は、指定したスナップショットを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Snapshot -SnapshotId snap-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Snapshot (DeleteSnapshot)" on target "snap-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteSnapshot](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2SpotDatafeedSubscription`
<a name="ec2_DeleteSpotDatafeedSubscription_powershell_5_topic"></a>

次のコード例は、`Remove-EC2SpotDatafeedSubscription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、スポットインスタンスのデータフィードを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2SpotDatafeedSubscription
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2SpotDatafeedSubscription (DeleteSpotDatafeedSubscription)" on Target "".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteSpotDatafeedSubscription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Subnet`
<a name="ec2_DeleteSubnet_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Subnet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したサブネットを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Subnet -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Subnet (DeleteSubnet)" on Target "subnet-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteSubnet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-EC2Tag`
<a name="ec2_DeleteTags_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Tag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、タグ値に関係なく、指定されたリソースから指定されたタグを削除します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag" } -Force
```
**例 2: この例では、指定されたタグ値が一致する場合にのみ、指定されたリソースから指定されたタグを削除します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-EC2Tag -Resource i-12345678 -Tag @{ Key="myTag";Value="myTagValue" } -Force
```
**例 3: この例では、タグ値に関係なく、指定されたリソースから指定されたタグを削除します。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
**例 4: この例では、指定されたタグ値が一致する場合にのみ、指定されたリソースから指定されたタグを削除します。**  

```
$tag = New-Object Amazon.EC2.Model.Tag
$tag.Key = "myTag"
$tag.Value = "myTagValue"

Remove-EC2Tag -Resource i-12345678 -Tag $tag -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Volume`
<a name="ec2_DeleteVolume_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Volume` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたボリュームをデタッチします。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Volume -VolumeId vol-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EC2Volume (DeleteVolume)" on target "vol-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteVolume](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2Vpc`
<a name="ec2_DeleteVpc_powershell_5_topic"></a>

次のコード例は、`Remove-EC2Vpc` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した VPC を削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2Vpc -VpcId vpc-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2Vpc (DeleteVpc)" on Target "vpc-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteVpc](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2VpnConnection`
<a name="ec2_DeleteVpnConnection_powershell_5_topic"></a>

次のコード例は、`Remove-EC2VpnConnection` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPN 接続を削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2VpnConnection -VpnConnectionId vpn-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnection (DeleteVpnConnection)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteVpnConnection](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2VpnConnectionRoute`
<a name="ec2_DeleteVpnConnectionRoute_powershell_5_topic"></a>

次のコード例は、`Remove-EC2VpnConnectionRoute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された VPN 接続から指定された静的ルートを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2VpnConnectionRoute -VpnConnectionId vpn-12345678 -DestinationCidrBlock 11.12.0.0/16
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnConnectionRoute (DeleteVpnConnectionRoute)" on Target "vpn-12345678".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteVpnConnectionRoute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EC2VpnGateway`
<a name="ec2_DeleteVpnGateway_powershell_5_topic"></a>

次のコード例は、`Remove-EC2VpnGateway` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された仮想プライベートゲートウェイを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-EC2VpnGateway -VpnGatewayId vgw-1a2b3c4d
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-EC2VpnGateway (DeleteVpnGateway)" on Target "vgw-1a2b3c4d".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteVpnGateway](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Request-EC2SpotFleet`
<a name="ec2_RequestSpotFleet_powershell_5_topic"></a>

次のコード例は、`Request-EC2SpotFleet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したインスタンスタイプが最低価格のアベイラビリティーゾーンで、スポットフリートリクエストを作成します。アカウントが EC2-VPC のみをサポートしている場合、スポットフリートは、デフォルトのサブネットが存在する、最低料金のアベイラビリティーゾーンでインスタンスを起動します。アカウントが EC2-Classic をサポートしている場合、スポットフリートは、最低料金のアベイラビリティーゾーンの EC2-Classic でインスタンスを起動します。リクエストで指定したスポット料金を超えて課金されることはありません。**  

```
$sg = New-Object Amazon.EC2.Model.GroupIdentifier
$sg.GroupId = "sg-12345678"
$lc = New-Object Amazon.EC2.Model.SpotFleetLaunchSpecification
$lc.ImageId = "ami-12345678"
$lc.InstanceType = "m3.medium"
$lc.SecurityGroups.Add($sg) 
Request-EC2SpotFleet -SpotFleetRequestConfig_SpotPrice 0.04 `
-SpotFleetRequestConfig_TargetCapacity 2 `
-SpotFleetRequestConfig_IamFleetRole arn:aws:iam::123456789012:role/my-spot-fleet-role `
-SpotFleetRequestConfig_LaunchSpecification $lc
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の[RequestSpotFleet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Request-EC2SpotInstance`
<a name="ec2_RequestSpotInstances_powershell_5_topic"></a>

次のコード例は、`Request-EC2SpotInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたサブネットで 1 回限りのスポットインスタンスをリクエストします。セキュリティグループは、指定されたサブネットを含む VPC 用に作成する必要があり、ネットワークインターフェイスを使用して ID で指定する必要があります。ネットワークインターフェイスの指定時、ネットワークインターフェイスを使用してサブネット ID を含める必要があります。**  

```
$n = New-Object Amazon.EC2.Model.InstanceNetworkInterfaceSpecification
$n.DeviceIndex = 0
$n.SubnetId = "subnet-12345678"
$n.Groups.Add("sg-12345678")
Request-EC2SpotInstance -InstanceCount 1 -SpotPrice 0.050 -Type one-time `
-IamInstanceProfile_Arn arn:aws:iam::123456789012:instance-profile/my-iam-role `
-LaunchSpecification_ImageId ami-12345678 `
-LaunchSpecification_InstanceType m3.medium `
-LaunchSpecification_NetworkInterface $n
```
**出力:**  

```
ActualBlockHourlyPrice   :
AvailabilityZoneGroup    :
BlockDurationMinutes     : 0
CreateTime               : 12/26/2015 7:44:10 AM
Fault                    :
InstanceId               :
LaunchedAvailabilityZone :
LaunchGroup              :
LaunchSpecification      : Amazon.EC2.Model.LaunchSpecification
ProductDescription       : Linux/UNIX
SpotInstanceRequestId    : sir-12345678
SpotPrice                : 0.050000
State                    : open
Status                   : Amazon.EC2.Model.SpotInstanceStatus
Tags                     : {}
Type                     : one-time
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RequestSpotInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Reset-EC2ImageAttribute`
<a name="ec2_ResetImageAttribute_powershell_5_topic"></a>

次のコード例は、`Reset-EC2ImageAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「launchPermission」属性をデフォルト値にリセットします。デフォルトでは、AMI はプライベートです。**  

```
Reset-EC2ImageAttribute -ImageId ami-12345678 -Attribute launchPermission
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResetImageAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Reset-EC2InstanceAttribute`
<a name="ec2_ResetInstanceAttribute_powershell_5_topic"></a>

次のコード例は、`Reset-EC2InstanceAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスの「sriovNetSupport」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sriovNetSupport
```
**例 2: この例では、指定されたインスタンスの「ebsOptimized」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute ebsOptimized
```
**例 3: この例では、指定されたインスタンスの「sourceDestCheck」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute sourceDestCheck
```
**例 4: この例では、指定されたインスタンスの「disableApiTermination」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute disableApiTermination
```
**例 5: この例では、指定されたインスタンスの「instanceInitiatedShutdownBehavior」属性をリセットします。**  

```
Reset-EC2InstanceAttribute -InstanceId i-12345678 -Attribute instanceInitiatedShutdownBehavior
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResetInstanceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Reset-EC2NetworkInterfaceAttribute`
<a name="ec2_ResetNetworkInterfaceAttribute_powershell_5_topic"></a>

次のコード例は、`Reset-EC2NetworkInterfaceAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワークインターフェイスの送信元/送信先チェックをリセットします。**  

```
Reset-EC2NetworkInterfaceAttribute -NetworkInterfaceId eni-1a2b3c4d -SourceDestCheck
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResetNetworkInterfaceAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Reset-EC2SnapshotAttribute`
<a name="ec2_ResetSnapshotAttribute_powershell_5_topic"></a>

次のコード例は、`Reset-EC2SnapshotAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したスナップショットに指定した属性を設定します。**  

```
Reset-EC2SnapshotAttribute -SnapshotId snap-12345678 -Attribute CreateVolumePermission
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ResetSnapshotAttribute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Restart-EC2Instance`
<a name="ec2_RebootInstances_powershell_5_topic"></a>

次のコード例は、`Restart-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスを再起動します。**  

```
Restart-EC2Instance -InstanceId i-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RebootInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Revoke-EC2SecurityGroupEgress`
<a name="ec2_RevokeSecurityGroupEgress_powershell_5_topic"></a>

次のコード例は、`Revoke-EC2SecurityGroupEgress` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループのルールを削除します。これにより、TCP ポート 80 で指定された IP アドレス範囲へのアクセスが取り消されます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 80
$ip.ToPort = 80
$ip.IpRanges.Add("203.0.113.0/24")
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission $ip
```
**例 3: この例では、TCP ポート 80 で指定されたソースセキュリティグループへのアクセスを取り消します。**  

```
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair
$ug.GroupId = "sg-1a2b3c4d"
$ug.UserId = "123456789012"
Revoke-EC2SecurityGroupEgress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="80"; ToPort="80"; UserIdGroupPairs=$ug } )
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RevokeSecurityGroupEgress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Revoke-EC2SecurityGroupIngress`
<a name="ec2_RevokeSecurityGroupIngress_powershell_5_topic"></a>

次のコード例は、`Revoke-EC2SecurityGroupIngress` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、EC2-VPC の指定されたセキュリティグループに対して、指定されたアドレス範囲から TCP ポート 22 へのアクセスを取り消します。セキュリティグループの名前ではなく、セキュリティグループの ID を使用して、EC2-VPC のセキュリティグループを識別する必要があります。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }
Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission $ip
```
**例 3: この例では、EC2-Classic の指定されたセキュリティグループに対して、指定されたアドレス範囲から TCP ポート 22 へのアクセスを取り消します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$ip = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.0/24" }

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
**例 4: PowerShell バージョン 2 では、New-Object を使用して IpPermission オブジェクトを作成する必要があります。**  

```
$ip = New-Object Amazon.EC2.Model.IpPermission
$ip.IpProtocol = "tcp"
$ip.FromPort = 22
$ip.ToPort = 22
$ip.IpRanges.Add("203.0.113.0/24")

Revoke-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission $ip
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RevokeSecurityGroupIngress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Send-EC2InstanceStatus`
<a name="ec2_ReportInstanceStatus_powershell_5_topic"></a>

次のコード例は、`Send-EC2InstanceStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスのステータスフィードバックを報告します。**  

```
Send-EC2InstanceStatus -Instance i-12345678 -Status impaired -ReasonCode unresponsive
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ReportInstanceStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-EC2NetworkAclAssociation`
<a name="ec2_ReplaceNetworkAclAssociation_powershell_5_topic"></a>

次のコード例は、`Set-EC2NetworkAclAssociation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワーク ACL を、指定されたネットワーク ACL 関連付けを持つサブネットに関連付けます。**  

```
Set-EC2NetworkAclAssociation -NetworkAclId acl-12345678 -AssociationId aclassoc-1a2b3c4d
```
**出力:**  

```
aclassoc-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ReplaceNetworkAclAssociation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-EC2NetworkAclEntry`
<a name="ec2_ReplaceNetworkAclEntry_powershell_5_topic"></a>

次のコード例は、`Set-EC2NetworkAclEntry` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワーク ACL の指定されたエントリを置き換えます。新しいルールでは、指定されたアドレスから関連付けられた任意のサブネットへのインバウンドトラフィックが許可されます。**  

```
Set-EC2NetworkAclEntry -NetworkAclId acl-12345678 -Egress $false -RuleNumber 100 -Protocol 17 -PortRange_From 53 -PortRange_To 53 -CidrBlock 203.0.113.12/24 -RuleAction allow
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ReplaceNetworkAclEntry](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-EC2Route`
<a name="ec2_ReplaceRoute_powershell_5_topic"></a>

次のコード例は、`Set-EC2Route` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したルートテーブルの指定したルートを置き換えます。新しいルートは、指定されたトラフィックを指定された仮想プライベートゲートウェイに送信します。**  

```
Set-EC2Route -RouteTableId rtb-1a2b3c4d -DestinationCidrBlock 10.0.0.0/24 -GatewayId vgw-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ReplaceRoute](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-EC2RouteTableAssociation`
<a name="ec2_ReplaceRouteTableAssociation_powershell_5_topic"></a>

次のコード例は、`Set-EC2RouteTableAssociation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたルートテーブルを、指定されたルートテーブルの関連付けを持つサブネットに関連付けます。**  

```
Set-EC2RouteTableAssociation -RouteTableId rtb-1a2b3c4d -AssociationId rtbassoc-12345678
```
**出力:**  

```
rtbassoc-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ReplaceRouteTableAssociation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-EC2Instance`
<a name="ec2_StartInstances_powershell_5_topic"></a>

次のコード例は、`Start-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスを開始します。**  

```
Start-EC2Instance -InstanceId i-12345678
```
**出力:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
**例 2: この例では、指定されたインスタンスを開始します。**  

```
@("i-12345678", "i-76543210") | Start-EC2Instance
```
**例 3: この例では、現在停止しているインスタンスのセットを開始します。Get-EC2Instance によって返されるインスタンスオブジェクトは、Start-EC2Instance にパイプされます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
(Get-EC2Instance -Filter @{ Name="instance-state-name"; Values="stopped"}).Instances | Start-EC2Instance
```
**例 4: PowerShell バージョン 2 では、New-Object を使用してフィルターパラメータのフィルターを作成する必要があります。**  

```
$filter = New-Object Amazon.EC2.Model.Filter
$filter.Name = "instance-state-name"
$filter.Values = "stopped"

(Get-EC2Instance -Filter $filter).Instances | Start-EC2Instance
```
**例 5: この例では、インスタンスを実際に開始せずに DryRun パラメータを使用して EC2 インスタンスを開始するためのアクセス許可を検証します。注: 成功すると例外がスローされますが、これは正常な動作です。**  

```
Start-EC2Instance -InstanceId 'i-0abcdef123456' -Region 'us-west-1' -DryRun $true
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StartInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Start-EC2InstanceMonitoring`
<a name="ec2_MonitorInstances_powershell_5_topic"></a>

次のコード例は、`Start-EC2InstanceMonitoring` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスの詳細モニタリングを有効にします。**  

```
Start-EC2InstanceMonitoring -InstanceId i-12345678
```
**出力:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[MonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-EC2ImportTask`
<a name="ec2_CancelImportTask_powershell_5_topic"></a>

次のコード例は、`Stop-EC2ImportTask` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインポートタスク (スナップショットまたはイメージのインポート) をキャンセルします。必要に応じて、`-CancelReason` パラメータを使用して理由を指定できます。**  

```
Stop-EC2ImportTask -ImportTaskId import-ami-abcdefgh
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CancelImportTask](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-EC2Instance`
<a name="ec2_StopInstances_powershell_5_topic"></a>

次のコード例は、`Stop-EC2Instance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスを停止します。**  

```
Stop-EC2Instance -InstanceId i-12345678
```
**出力:**  

```
CurrentState                      InstanceId    PreviousState
------------                      ----------    -------------
Amazon.EC2.Model.InstanceState    i-12345678    Amazon.EC2.Model.InstanceState
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[StopInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-EC2InstanceMonitoring`
<a name="ec2_UnmonitorInstances_powershell_5_topic"></a>

次のコード例は、`Stop-EC2InstanceMonitoring` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたインスタンスの詳細モニタリングを無効にします。**  

```
Stop-EC2InstanceMonitoring -InstanceId i-12345678
```
**出力:**  

```
InstanceId    Monitoring
----------    ----------
i-12345678    Amazon.EC2.Model.Monitoring
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UnmonitorInstances](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-EC2SpotFleetRequest`
<a name="ec2_CancelSpotFleetRequests_powershell_5_topic"></a>

次のコード例は、`Stop-EC2SpotFleetRequest` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスポットフリートリクエストをキャンセルし、関連付けられたスポットインスタンスを終了します。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $true
```
**例 2: この例では、関連付けられたスポットインスタンスを終了せずに、指定されたスポットフリートリクエストをキャンセルします。**  

```
Stop-EC2SpotFleetRequest -SpotFleetRequestId sfr-73fbd2ce-aa30-494c-8788-1cee4EXAMPLE -TerminateInstance $false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CancelSpotFleetRequests](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Stop-EC2SpotInstanceRequest`
<a name="ec2_CancelSpotInstanceRequests_powershell_5_topic"></a>

次のコード例は、`Stop-EC2SpotInstanceRequest` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたスポットインスタンスリクエストをキャンセルします。**  

```
Stop-EC2SpotInstanceRequest -SpotInstanceRequestId sir-12345678
```
**出力:**  

```
SpotInstanceRequestId    State
---------------------    -----
sir-12345678             cancelled
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CancelSpotInstanceRequests](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-EC2Address`
<a name="ec2_DisassociateAddress_powershell_5_topic"></a>

次のコード例は、`Unregister-EC2Address` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、VPC 内の指定されたインスタンスから指定された Elastic IP アドレスの関連付けを解除します。**  

```
Unregister-EC2Address -AssociationId eipassoc-12345678
```
**例 2: この例では、EC2-Classic 内の指定されたインスタンスから指定された Elastic IP アドレスの関連付けを解除します。**  

```
Unregister-EC2Address -PublicIp 203.0.113.17
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisassociateAddress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-EC2Image`
<a name="ec2_DeregisterImage_powershell_5_topic"></a>

次のコード例は、`Unregister-EC2Image` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された AMI の登録を解除します。**  

```
Unregister-EC2Image -ImageId ami-12345678
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeregisterImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-EC2PrivateIpAddress`
<a name="ec2_UnassignPrivateIpAddresses_powershell_5_topic"></a>

次のコード例は、`Unregister-EC2PrivateIpAddress` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたネットワークインターフェイスから指定されたプライベート IP アドレスの割り当てを解除します。**  

```
Unregister-EC2PrivateIpAddress -NetworkInterfaceId eni-1a2b3c4d -PrivateIpAddress 10.0.0.82
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UnassignPrivateIpAddresses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Unregister-EC2RouteTable`
<a name="ec2_DisassociateRouteTable_powershell_5_topic"></a>

次のコード例は、`Unregister-EC2RouteTable` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ルートテーブルとサブネット間の指定された関連付けを削除します。**  

```
Unregister-EC2RouteTable -AssociationId rtbassoc-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisassociateRouteTable](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-EC2SecurityGroupRuleIngressDescription`
<a name="ec2_UpdateSecurityGroupRuleDescriptionsIngress_powershell_5_topic"></a>

次のコード例は、`Update-EC2SecurityGroupRuleIngressDescription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 進入 (受信) セキュリティグループルールの説明を更新します。**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithUpdatedDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
  "Description" = "Updated rule description"
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithUpdatedDescription
```
**例 2: 既存の進入 (受信) セキュリティグループルールの説明を削除します (リクエストでパラメータを省略)。**  

```
$existingInboundRule = Get-EC2SecurityGroupRule -SecurityGroupRuleId "sgr-1234567890"
$ruleWithoutDescription = [Amazon.EC2.Model.SecurityGroupRuleDescription]@{
  "SecurityGroupRuleId" = $existingInboundRule.SecurityGroupRuleId
}

Update-EC2SecurityGroupRuleIngressDescription -GroupId $existingInboundRule.GroupId -SecurityGroupRuleDescription $ruleWithoutDescription
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateSecurityGroupRuleDescriptionsIngress](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Amazon ECR の例
<a name="powershell_5_ecr_code_examples"></a>

次のコード例は、Amazon ECR で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-ECRLoginCommand`
<a name="ecr_Get-ECRLoginCommand_powershell_5_topic"></a>

次のコード例は、`Get-ECRLoginCommand` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: IAM プリンシパルがアクセスできる Amazon ECR レジストリへの認証に使用できるログイン情報を含む PSObject を返します。認証トークンを取得するための呼び出しに必要な認証情報とリージョンエンドポイントは、シェルのデフォルト (`Set-AWSCredential/Set-DefaultAWSRegion` または `Initialize-AWSDefaultConfiguration` のコマンドレットによって設定される) から取得されます。Invoke-Expression で コマンドプロパティを使用すると、指定レジストリにログインしたり、返された認証情報をログインを必要とする他のツールで使用したりできます。**  

```
Get-ECRLoginCommand
```
**出力:**  

```
Username      : AWS
Password      : eyJwYXlsb2Fk...kRBVEFfS0VZIn0=
ProxyEndpoint : https://123456789012.dkr.ecr.us-west-2.amazonaws.com
Endpoint      : https://123456789012.dkr.ecr.us-west-2.amazonaws.com
ExpiresAt     : 9/26/2017 6:08:23 AM
Command       : docker login --username AWS --password eyJwYXlsb2Fk...kRBVEFfS0VZIn0= https://123456789012.dkr.ecr.us-west-2.amazonaws.com
```
**例 2: Docker ログインコマンドへの入力として使用するログイン情報を含む PSObject を取得します。IAM プリンシパルがそのレジストリにアクセスできる限り、認証する任意の Amazon ECR レジストリ URI を指定できます。**  

```
(Get-ECRLoginCommand).Password | docker login --username AWS --password-stdin 012345678910.dkr.ecr.us-east-1.amazonaws.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[Get-ECRLoginCommand](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Amazon ECS の例
<a name="powershell_5_ecs_code_examples"></a>

次のコード例は、Amazon ECS で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-ECSClusterDetail`
<a name="ecs_DescribeClusters_powershell_5_topic"></a>

次のコード例は、`Get-ECSClusterDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットでは、1 つ以上の ECS クラスターを記述します。**  

```
Get-ECSClusterDetail -Cluster "LAB-ECS-CL" -Include SETTINGS | Select-Object *
```
**出力:**  

```
LoggedAt         : 12/27/2019 9:27:41 PM
Clusters         : {LAB-ECS-CL}
Failures         : {}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 396
HttpStatusCode   : OK
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeClusters](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ECSClusterList`
<a name="ecs_ListClusters_powershell_5_topic"></a>

次のコード例は、`Get-ECSClusterList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、既存の ECS クラスターのリストを返します。**  

```
Get-ECSClusterList
```
**出力:**  

```
arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListClusters](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ECSClusterService`
<a name="ecs_ListServices_powershell_5_topic"></a>

次のコード例は、`Get-ECSClusterService` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、デフォルトのクラスターで実行されているすべてのサービスを一覧表示します。**  

```
Get-ECSClusterService
```
**例 2: この例では、指定されたクラスターで実行されているすべてのサービスを一覧表示します。**  

```
Get-ECSClusterService -Cluster myCluster
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListServices](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ECSService`
<a name="ecs_DescribeServices_powershell_5_topic"></a>

次のコード例は、`Get-ECSService` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、デフォルトのクラスターから特定のサービスの詳細を取得する方法を示します。**  

```
Get-ECSService -Service my-hhtp-service
```
**例 2: この例では、名前付きクラスターで実行されている特定のサービスの詳細を取得する方法を示します。**  

```
Get-ECSService -Cluster myCluster -Service my-hhtp-service
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ECSCluster`
<a name="ecs_CreateCluster_powershell_5_topic"></a>

次のコード例は、`New-ECSCluster` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは新しい Amazon ECS クラスターを作成します。**  

```
New-ECSCluster -ClusterName "LAB-ECS-CL" -Setting @{Name="containerInsights"; Value="enabled"}
```
**出力:**  

```
ActiveServicesCount               : 0
Attachments                       : {}
AttachmentsStatus                 :
CapacityProviders                 : {}
ClusterArn                        : arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
ClusterName                       : LAB-ECS-CL
DefaultCapacityProviderStrategy   : {}
PendingTasksCount                 : 0
RegisteredContainerInstancesCount : 0
RunningTasksCount                 : 0
Settings                          : {containerInsights}
Statistics                        : {}
Status                            : ACTIVE
Tags                              : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateCluster](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ECSService`
<a name="ecs_CreateService_powershell_5_topic"></a>

次のコード例は、`New-ECSService` を使用する方法を示しています。

**Tools for PowerShell V5**  
例 1: このコマンド例では、デフォルトのクラスターに「ecs-simple-service」というサービスを作成します。このサービスは `ecs-demo` タスク定義を使用し、そのタスクのインスタンスを 10 個保持します。  

```
New-ECSService -ServiceName ecs-simple-service -TaskDefinition ecs-demo -DesiredCount 10
```
例 2: このコマンド例では、デフォルトクラスター内で、ロードバランサーの背後に「ecs-simple-service」という名前のサービスを作成します。このサービスは `ecs-demo` タスク定義を使用し、そのタスクのインスタンスを 10 個保持します。  

```
$lb = @{
    LoadBalancerName = "EC2Contai-EcsElast-S06278JGSJCM"
    ContainerName = "simple-demo"
    ContainerPort = 80
}        
New-ECSService -ServiceName ecs-simple-service -TaskDefinition ecs-demo -DesiredCount 10 -LoadBalancer $lb
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateService](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ECSCluster`
<a name="ecs_DeleteCluster_powershell_5_topic"></a>

次のコード例は、`Remove-ECSCluster` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、指定された ECS クラスターを削除します。削除する前に、このクラスターからすべてのコンテナインスタンスを登録解除する必要があります。**  

```
Remove-ECSCluster -Cluster "LAB-ECS"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ECSCluster (DeleteCluster)" on target "LAB-ECS".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteCluster](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ECSService`
<a name="ecs_DeleteService_powershell_5_topic"></a>

次のコード例は、`Remove-ECSService` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: デフォルトクラスターで「my-http-service」という名前のサービスを削除します。サービスを削除する前に、必要数と実行中の数が 0 である必要があります。コマンドを続行する前に確認を求められます。確認を省略するには、-Force スイッチを追加します。**  

```
Remove-ECSService -Service my-http-service
```
**例 2: 名前付きクラスターで「my-http-service」という名前のサービスを削除します。**  

```
Remove-ECSService -Cluster myCluster -Service my-http-service
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteService](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-ECSClusterSetting`
<a name="ecs_UpdateClusterSettings_powershell_5_topic"></a>

次のコード例は、`Update-ECSClusterSetting` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、ECS クラスターに使用する設定を変更します。**  

```
Update-ECSClusterSetting -Cluster "LAB-ECS-CL" -Setting @{Name="containerInsights"; Value="disabled"}
```
**出力:**  

```
ActiveServicesCount               : 0
Attachments                       : {}
AttachmentsStatus                 :
CapacityProviders                 : {}
ClusterArn                        : arn:aws:ecs:us-west-2:012345678912:cluster/LAB-ECS-CL
ClusterName                       : LAB-ECS-CL
DefaultCapacityProviderStrategy   : {}
PendingTasksCount                 : 0
RegisteredContainerInstancesCount : 0
RunningTasksCount                 : 0
Settings                          : {containerInsights}
Statistics                        : {}
Status                            : ACTIVE
Tags                              : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateClusterSettings](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-ECSService`
<a name="ecs_UpdateService_powershell_5_topic"></a>

次のコード例は、`Update-ECSService` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンド例では、「my-http-service」サービスを更新して「amazon-ecs-sample」タスク定義を使用します。**  

```
Update-ECSService -Service my-http-service -TaskDefinition amazon-ecs-sample
```
**例 2: このコマンド例では、`my-http-service` サービスの必要数を 10 に更新します。**  

```
Update-ECSService -Service my-http-service -DesiredCount 10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateService](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Amazon EFS の例
<a name="powershell_5_efs_code_examples"></a>

次のコード例は、Amazon EFS で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Edit-EFSMountTargetSecurityGroup`
<a name="efs_ModifyMountTargetSecurityGroups_powershell_5_topic"></a>

次のコード例は、`Edit-EFSMountTargetSecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたマウントターゲットに対して有効なセキュリティグループを更新します。「sg-xxxxxxxx」の形式で最大 5 つ指定できます。**  

```
Edit-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d -SecurityGroup sg-group1,sg-group3
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EFSFileSystem`
<a name="efs_DescribeFileSystems_powershell_5_topic"></a>

次のコード例は、`Get-EFSFileSystem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: リージョン内の発信者のアカウントが所有するすべてのファイルシステムのコレクションを返します。**  

```
Get-EFSFileSystem
```
**出力:**  

```
CreationTime         : 5/26/2015 4:02:38 PM
CreationToken        : 1a2bff54-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-1a2b3c4d
LifeCycleState       : available
Name                 :
NumberOfMountTargets : 0
OwnerId              : 123456789012
SizeInBytes          : Amazon.ElasticFileSystem.Model.FileSystemSize

CreationTime         : 5/26/2015 4:06:23 PM
CreationToken        : 2b4daa14-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-4d3c2b1a
...
```
**例 2: 指定されたファイルシステムの詳細を返します。**  

```
Get-EFSFileSystem -FileSystemId fs-1a2b3c4d
```
**例 3: ファイルシステムの作成時に指定されたべき等性作成トークンを使用して、ファイルシステムの詳細を返します。**  

```
Get-EFSFileSystem -CreationToken 1a2bff54-85e0-4747-bd95-7bc172c4f555
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeFileSystems](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EFSMountTarget`
<a name="efs_DescribeMountTargets_powershell_5_topic"></a>

次のコード例は、`Get-EFSMountTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたファイルシステムに関連付けられたマウントターゲットのコレクションを返します。**  

```
Get-EFSMountTarget -FileSystemId fs-1a2b3c4d
```
**出力:**  

```
FileSystemId       : fs-1a2b3c4d
IpAddress          : 10.0.0.131
LifeCycleState     : available
MountTargetId      : fsmt-1a2b3c4d
NetworkInterfaceId : eni-1a2b3c4d
OwnerId            : 123456789012
SubnetId           : subnet-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeMountTargets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EFSMountTargetSecurityGroup`
<a name="efs_DescribeMountTargetSecurityGroups_powershell_5_topic"></a>

次のコード例は、`Get-EFSMountTargetSecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: マウントターゲットに関連付けられたネットワークインターフェイスに現在割り当てられているセキュリティグループの ID を返します。**  

```
Get-EFSMountTargetSecurityGroup -MountTargetId fsmt-1a2b3c4d
```
**出力:**  

```
sg-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeMountTargetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EFSTag`
<a name="efs_DescribeTags_powershell_5_topic"></a>

次のコード例は、`Get-EFSTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたファイルシステムに現在関連付けられているタグのコレクションを返します。**  

```
Get-EFSTag -FileSystemId fs-1a2b3c4d
```
**出力:**  

```
Key         Value
---         -----
Name        My File System
tagkey1     tagvalue1
tagkey2     tagvalue2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-EFSFileSystem`
<a name="efs_CreateFileSystem_powershell_5_topic"></a>

次のコード例は、`New-EFSFileSystem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 新しい空のファイルシステムを作成します。作成のべき等性を保証するために使用されるトークンは自動的に生成され、返されたオブジェクトの `CreationToken` メンバーからアクセスできます。**  

```
New-EFSFileSystem
```
**出力:**  

```
CreationTime         : 5/26/2015 4:02:38 PM
CreationToken        : 1a2bff54-85e0-4747-bd95-7bc172c4f555
FileSystemId         : fs-1a2b3c4d
LifeCycleState       : creating
Name                 :
NumberOfMountTargets : 0
OwnerId              : 123456789012
SizeInBytes          : Amazon.ElasticFileSystem.Model.FileSystemSize
```
**例 2: カスタムトークンを使用して新しい空のファイルシステムを作成し、作成のべき等性を保証します。**  

```
New-EFSFileSystem -CreationToken "MyUniqueToken"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EFSMountTarget`
<a name="efs_CreateMountTarget_powershell_5_topic"></a>

次のコード例は、`New-EFSMountTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ファイルシステムのマウントターゲットを新規に作成します。指定されたサブネットを使用して、マウントターゲットが作成される仮想プライベートクラウド (VPC) と、(サブネットのアドレス範囲から) 自動割り当てされる IP アドレスを決定します。割り当てられた IP アドレスを使用して、このファイルシステムを Amazon EC2 インスタンスにマウントできます。セキュリティグループが指定されていないため、ターゲット用に作成されたネットワークインターフェイスは、サブネットの VPC のデフォルトのセキュリティグループに関連付けられます。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d
```
**出力:**  

```
FileSystemId       : fs-1a2b3c4d
IpAddress          : 10.0.0.131
LifeCycleState     : creating
MountTargetId      : fsmt-1a2b3c4d
NetworkInterfaceId : eni-1a2b3c4d
OwnerId            : 123456789012
SubnetId           : subnet-1a2b3c4d
```
**例 2: 自動割り当て IP アドレスを使用して、指定されたファイルシステムの新しいマウントターゲットを作成します。マウントターゲット用に作成されたネットワークインターフェイスは、指定されたセキュリティグループに関連付けられます (「sg-xxxxxxxx」の形式で最大 5 つまで指定できます)。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d -SecurityGroup sg-group1,sg-group2,sg-group3
```
**例 3: 指定された IP アドレスを使用して、指定されたファイルシステムの新しいマウントターゲットを作成します。**  

```
New-EFSMountTarget -FileSystemId fs-1a2b3c4d -SubnetId subnet-1a2b3c4d -IpAddress 10.0.0.131
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateMountTarget](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EFSTag`
<a name="efs_CreateTags_powershell_5_topic"></a>

次のコード例は、`New-EFSTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定ファイルシステムにタグのコレクションを適用します。指定キーを持つタグが既にファイルシステムに存在する場合、タグの値は更新されます。**  

```
New-EFSTag -FileSystemId fs-1a2b3c4d -Tag @{Key="tagkey1";Value="tagvalue1"},@{Key="tagkey2";Value="tagvalue2"}
```
**例 2: 指定ファイルシステムの名前タグを設定します。この値は、Get-EFSFileSystem コマンドレットを使用するときに、他のファイルシステムの詳細とともに返されます。**  

```
New-EFSTag -FileSystemId fs-1a2b3c4d -Tag @{Key="Name";Value="My File System"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EFSFileSystem`
<a name="efs_DeleteFileSystem_powershell_5_topic"></a>

次のコード例は、`Remove-EFSFileSystem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 使用されなくなった指定ファイルシステムを削除します (ファイルシステムにマウントターゲットがある場合は、最初に削除する必要があります)。コマンドレットが続行される前に確認を求めるプロンプトが表示されます。プロンプトを表示しないようにするには、`-Force` スイッチを使用します。**  

```
Remove-EFSFileSystem -FileSystemId fs-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EFSMountTarget`
<a name="efs_DeleteMountTarget_powershell_5_topic"></a>

次のコード例は、`Remove-EFSMountTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたマウントターゲットを削除します。操作を続行する前に確認画面が表示されます。プロンプトを表示しないようにするには、`-Force` スイッチを使用します。このオペレーションでは、ターゲットを介してファイルシステムのマウントが強制的に中断されることに注意してください。可能であれば、このコマンドを実行する前にファイルシステムのアンマウントを検討してください。**  

```
Remove-EFSMountTarget -MountTargetId fsmt-1a2b3c4d
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteMountTarget](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EFSTag`
<a name="efs_DeleteTags_powershell_5_topic"></a>

次のコード例は、`Remove-EFSTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ファイルシステムから 1 つ以上のタグのコレクションを削除します。コマンドレットが続行される前に確認を求めるプロンプトが表示されます。プロンプトを表示しないようにするには、`-Force` スイッチを使用します。**  

```
Remove-EFSTag -FileSystemId fs-1a2b3c4d -TagKey "tagkey1","tagkey2"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Amazon EKS の例
<a name="powershell_5_eks_code_examples"></a>

次のコード例は、Amazon EKS で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-EKSResourceTag`
<a name="eks_TagResource_powershell_5_topic"></a>

次のコード例は、`Add-EKSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、指定されたタグを、指定された resourceArn を持つリソースに関連付けます。**  

```
Add-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD" -Tag @{Name = "EKSPRODCLUSTER"}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[TagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSCluster`
<a name="eks_DescribeCluster_powershell_5_topic"></a>

次のコード例は、`Get-EKSCluster` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS クラスターに関する詳細情報を返します。**  

```
Get-EKSCluster -Name "PROD"
```
**出力:**  

```
Arn                  : arn:aws:eks:us-west-2:012345678912:cluster/PROD
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/25/2019 6:46:17 AM
Endpoint             : https://669608765450FBBE54D1D78A3D71B72C.gr8.us-west-2.eks.amazonaws.com
Identity             : Amazon.EKS.Model.Identity
Logging              : Amazon.EKS.Model.Logging
Name                 : PROD
PlatformVersion      : eks.7
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678912:role/eks-iam-role
Status               : ACTIVE
Tags                 : {}
Version              : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeCluster](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSClusterList`
<a name="eks_ListClusters_powershell_5_topic"></a>

次のコード例は、`Get-EKSClusterList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、指定されたリージョン AWS アカウント の にある Amazon EKS クラスターを一覧表示します。**  

```
Get-EKSClusterList
```
**出力:**  

```
 PROD
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListClusters](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSFargateProfile`
<a name="eks_DescribeFargateProfile_powershell_5_topic"></a>

次のコード例は、`Get-EKSFargateProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、 AWS Fargate プロファイルに関する説明情報を返します。**  

```
Get-EKSFargateProfile -FargateProfileName "EKSFargate" -ClusterName "TEST"
```
**出力:**  

```
ClusterName         : TEST
CreatedAt           : 12/26/2019 12:34:47 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargate/42b7a119-e16b-a279-ce97-bdf303adec92
FargateProfileName  : EKSFargate
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : ACTIVE
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSFargateProfileList`
<a name="eks_ListFargateProfiles_powershell_5_topic"></a>

次のコード例は、`Get-EKSFargateProfileList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、指定されたリージョンの 内の指定されたクラスターに関連付けられた AWS Fargate プロファイル AWS アカウント を一覧表示します。**  

```
Get-EKSFargateProfileList -ClusterName "TEST"
```
**出力:**  

```
EKSFargate
EKSFargateProfile
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListFargateProfiles](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSNodegroup`
<a name="eks_DescribeNodegroup_powershell_5_topic"></a>

次のコード例は、`Get-EKSNodegroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS ノードグループに関する詳細情報を返します。**  

```
Get-EKSNodegroup -NodegroupName "ProdEKSNodeGroup" -ClusterName "PROD"
```
**出力:**  

```
AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 10:16:45 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      :
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : CREATING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSNodegroupList`
<a name="eks_ListNodegroups_powershell_5_topic"></a>

次のコード例は、`Get-EKSNodegroupList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、指定されたリージョンの 内の指定されたクラスターに関連付けられた Amazon EKS ノードグループ AWS アカウント を一覧表示します。 **  

```
Get-EKSNodegroupList -ClusterName PROD
```
**出力:**  

```
 ProdEKSNodeGroup
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListNodegroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSResourceTag`
<a name="eks_ListTagsForResource_powershell_5_topic"></a>

次のコード例は、`Get-EKSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS リソースのタグを一覧表示します。 **  

```
Get-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD"
```
**出力:**  

```
Key  Value
---  -----
Name EKSPRODCLUSTER
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-EKSUpdate`
<a name="eks_DescribeUpdate_powershell_5_topic"></a>

次のコード例は、`Get-EKSUpdate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS クラスターまたは関連するマネージドノードグループに対する更新に関する詳細情報を返します。**  

```
Get-EKSUpdate -Name "PROD" -UpdateId "ee708232-7d2e-4ed7-9270-d0b5176f0726"
```
**出力:**  

```
CreatedAt : 12/25/2019 5:03:07 PM
Errors    : {}
Id        : ee708232-7d2e-4ed7-9270-d0b5176f0726
Params    : {Amazon.EKS.Model.UpdateParam}
Status    : Successful
Type      : LoggingUpdate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeUpdate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-EKSUpdateList`
<a name="eks_ListUpdates_powershell_5_topic"></a>

次のコード例は、`Get-EKSUpdateList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、指定されたリージョンの 内の Amazon EKS クラスターまたはマネージドノードグループに関連付けられた更新 AWS アカウントを一覧表示します。**  

```
Get-EKSUpdateList -Name "PROD"
```
**出力:**  

```
ee708232-7d2e-4ed7-9270-d0b5176f0726
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ListUpdates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EKSCluster`
<a name="eks_CreateCluster_powershell_5_topic"></a>

次のコード例は、`New-EKSCluster` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「prod」という新しいクラスターを作成します。**  

```
New-EKSCluster -Name prod -ResourcesVpcConfig @{SubnetIds=@("subnet-0a1b2c3d","subnet-3a2b1c0d");SecurityGroupIds="sg-6979fe18"} -RoleArn "arn:aws:iam::012345678901:role/eks-service-role"
```
**出力:**  

```
Arn                  : arn:aws:eks:us-west-2:012345678901:cluster/prod
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/10/2018 9:25:31 PM
Endpoint             :
Name                 : prod
PlatformVersion      : eks.3
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678901:role/eks-service-role
Status               : CREATING
Version              : 1.10
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateCluster](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EKSFargateProfile`
<a name="eks_CreateFargateProfile_powershell_5_topic"></a>

次のコード例は、`New-EKSFargateProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS クラスターの AWS Fargate プロファイルを作成します。Fargate インフラストラクチャでポッドをスケジュールできるようにするには、クラスター内に少なくとも 1 つの Fargate プロファイルが必要です。**  

```
New-EKSFargateProfile -FargateProfileName EKSFargateProfile -ClusterName TEST -Subnet "subnet-02f6ff500ff2067a0", "subnet-0cd976f08d5fbfaae" -PodExecutionRoleArn arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole -Selector @{Namespace="default"}
```
**出力:**  

```
ClusterName         : TEST
CreatedAt           : 12/26/2019 12:38:21 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargateProfile/20b7a11b-8292-41c1-bc56-ffa5e60f6224
FargateProfileName  : EKSFargateProfile
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : CREATING
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-EKSNodeGroup`
<a name="eks_CreateNodegroup_powershell_5_topic"></a>

次のコード例は、`New-EKSNodeGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS クラスターのマネージド型ワーカーノードグループを作成します。クラスターの現在の Kubernetes バージョンと同じクラスター対してのみノードグループを作成できます。すべてのノードグループは、クラスターのそれぞれのマイナー Kubernetes バージョンの最新の AMI リリースバージョンで作成されます。**  

```
New-EKSNodeGroup -NodeGroupName "ProdEKSNodeGroup" -AmiType "AL2_x86_64" -DiskSize 40 -ClusterName "PROD" -ScalingConfig_DesiredSize 2 -ScalingConfig_MinSize 2 -ScalingConfig_MaxSize 5 -InstanceType t3.large -NodeRole "arn:aws:iam::012345678912:role/NodeInstanceRole" -Subnet "subnet-0d1a9fff35efa7691","subnet-0a3f4928edbc224d4"
```
**出力:**  

```
AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 10:16:45 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      :
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : CREATING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EKSCluster`
<a name="eks_DeleteCluster_powershell_5_topic"></a>

次のコード例は、`Remove-EKSCluster` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS クラスターコントロールプレーンを削除します。**  

```
Remove-EKSCluster -Name "DEV-KUBE-CL"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSCluster (DeleteCluster)" on target "DEV-KUBE-CL".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Arn                  : arn:aws:eks:us-west-2:012345678912:cluster/DEV-KUBE-CL
CertificateAuthority : Amazon.EKS.Model.Certificate
ClientRequestToken   :
CreatedAt            : 12/25/2019 9:33:25 AM
Endpoint             : https://02E6D31E3E4F8C15D7BE7F58D527776A.yl4.us-west-2.eks.amazonaws.com
Identity             : Amazon.EKS.Model.Identity
Logging              : Amazon.EKS.Model.Logging
Name                 : DEV-KUBE-CL
PlatformVersion      : eks.7
ResourcesVpcConfig   : Amazon.EKS.Model.VpcConfigResponse
RoleArn              : arn:aws:iam::012345678912:role/eks-iam-role
Status               : DELETING
Tags                 : {}
Version              : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteCluster](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EKSFargateProfile`
<a name="eks_DeleteFargateProfile_powershell_5_topic"></a>

次のコード例は、`Remove-EKSFargateProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは AWS Fargate プロファイルを削除します。Fargate プロファイルを削除すると、そのプロファイルで Fargate で作成された Fargate 上で実行中のポッドは削除されます。**  

```
Remove-EKSFargateProfile -FargateProfileName "EKSFargate" -ClusterName "TEST"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSFargateProfile (DeleteFargateProfile)" on target "EKSFargate".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

ClusterName         : TEST
CreatedAt           : 12/26/2019 12:34:47 PM
FargateProfileArn   : arn:aws:eks:us-east-2:012345678912:fargateprofile/TEST/EKSFargate/42b7a119-e16b-a279-ce97-bdf303adec92
FargateProfileName  : EKSFargate
PodExecutionRoleArn : arn:aws:iam::012345678912:role/AmazonEKSFargatePodExecutionRole
Selectors           : {Amazon.EKS.Model.FargateProfileSelector}
Status              : DELETING
Subnets             : {subnet-0cd976f08d5fbfaae, subnet-02f6ff500ff2067a0}
Tags                : {}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteFargateProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EKSNodegroup`
<a name="eks_DeleteNodegroup_powershell_5_topic"></a>

次のコード例は、`Remove-EKSNodegroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、クラスターの Amazon EKS ノードグループを削除します。**  

```
Remove-EKSNodegroup -NodegroupName "ProdEKSNodeGroup" -ClusterName "PROD"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSNodegroup (DeleteNodegroup)" on target "ProdEKSNodeGroup".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

AmiType        : AL2_x86_64
ClusterName    : PROD
CreatedAt      : 12/25/2019 10:16:45 AM
DiskSize       : 40
Health         : Amazon.EKS.Model.NodegroupHealth
InstanceTypes  : {t3.large}
Labels         : {}
ModifiedAt     : 12/25/2019 11:01:16 AM
NodegroupArn   : arn:aws:eks:us-west-2:012345678912:nodegroup/PROD/ProdEKSNodeGroup/7eb79e47-82b6-04d9-e984-95110db6fa85
NodegroupName  : ProdEKSNodeGroup
NodeRole       : arn:aws:iam::012345678912:role/NodeInstanceRole
ReleaseVersion : 1.14.7-20190927
RemoteAccess   :
Resources      : Amazon.EKS.Model.NodegroupResources
ScalingConfig  : Amazon.EKS.Model.NodegroupScalingConfig
Status         : DELETING
Subnets        : {subnet-0d1a9fff35efa7691, subnet-0a3f4928edbc224d4}
Tags           : {}
Version        : 1.14
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteNodegroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-EKSResourceTag`
<a name="eks_UntagResource_powershell_5_topic"></a>

次のコード例は、`Remove-EKSResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、EKS リソースから指定されたタグを削除します。**  

```
Remove-EKSResourceTag -ResourceArn "arn:aws:eks:us-west-2:012345678912:cluster/PROD" -TagKey "Name"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-EKSResourceTag (UntagResource)" on target "arn:aws:eks:us-west-2:012345678912:cluster/PROD".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-EKSClusterConfig`
<a name="eks_UpdateClusterConfig_powershell_5_topic"></a>

次のコード例は、`Update-EKSClusterConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: Amazon EKS クラスター設定を更新します。更新中もクラスターは引き続き機能します。**  

```
Update-EKSClusterConfig -Name "PROD" -Logging_ClusterLogging @{Types="api","audit","authenticator","controllerManager","scheduler",Enabled="True"}
```
**出力:**  

```
CreatedAt : 12/25/2019 5:03:07 PM
Errors    : {}
Id        : ee708232-7d2e-4ed7-9270-d0b5176f0726
Params    : {Amazon.EKS.Model.UpdateParam}
Status    : InProgress
Type      : LoggingUpdate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateClusterConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Update-EKSClusterVersion`
<a name="eks_UpdateClusterVersion_powershell_5_topic"></a>

次のコード例は、`Update-EKSClusterVersion` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドレットは、Amazon EKS クラスターを指定された Kubernetes バージョンに更新します。更新中もクラスターは引き続き機能します。**  

```
Update-EKSClusterVersion -Name "PROD-KUBE-CL" -Version 1.14
```
**出力:**  

```
CreatedAt : 12/26/2019 9:50:37 AM
Errors    : {}
Id        : ef186eff-3b3a-4c25-bcfc-3dcdf9e898a8
Params    : {Amazon.EKS.Model.UpdateParam, Amazon.EKS.Model.UpdateParam}
Status    : InProgress
Type      : VersionUpdate
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[UpdateClusterVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Elastic Load Balancing - バージョン 1 の例
<a name="powershell_5_elastic-load-balancing_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 1 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ELBLoadBalancerToSubnet`
<a name="elastic-load-balancing_AttachLoadBalancerToSubnets_powershell_5_topic"></a>

次のコード例は、`Add-ELBLoadBalancerToSubnet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーに設定された一連のサブネットのセットに、指定されたサブネットを追加します。出力にはサブネットの完全なリストが含まれます。**  

```
Add-ELBLoadBalancerToSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**出力:**  

```
subnet-12345678
subnet-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AttachLoadBalancerToSubnets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-ELBResourceTag`
<a name="elastic-load-balancing_AddTags_powershell_5_topic"></a>

次のコード例は、`Add-ELBResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーにタグを追加します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Add-ELBResourceTag -LoadBalancerName my-load-balancer -Tag @{ Key="project";Value="lima" },@{ Key="department";Value="digital-media" }
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.ElasticLoadBalancing.Model.Tag
$tag.Key = "project"
$tag.Value = "lima"
Add-ELBResourceTag -LoadBalancerName my-load-balancer -Tag $tag
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AddTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Disable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_DisableAvailabilityZonesForLoadBalancer_powershell_5_topic"></a>

次のコード例は、`Disable-ELBAvailabilityZoneForLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーからを指定されたアベイラビリティーゾーンを削除します。出力には残りのアベイラビリティーゾーンが含まれます。**  

```
Disable-ELBAvailabilityZoneForLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a
```
**出力:**  

```
us-west-2b
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DisableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Dismount-ELBLoadBalancerFromSubnet`
<a name="elastic-load-balancing_DetachLoadBalancerFromSubnets_powershell_5_topic"></a>

次のコード例は、`Dismount-ELBLoadBalancerFromSubnet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーに設定されたサブネットのセットから、指定されたサブネットを削除します。出力には残りのサブネットが含まれます。**  

```
Dismount-ELBLoadBalancerFromSubnet -LoadBalancerName my-load-balancer -Subnet subnet-12345678
```
**出力:**  

```
subnet-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DetachLoadBalancerFromSubnets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_ModifyLoadBalancerAttributes_powershell_5_topic"></a>

次のコード例は、`Edit-ELBLoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーのクロスゾーン負荷分散を有効にします。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer -CrossZoneLoadBalancing_Enabled $true
```
**例 2: この例では、指定されたロードバランサーの Connection Draining を無効にします。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer -ConnectionDraining_Enabled $false
```
**例 3: この例では、指定されたロードバランサーのアクセスログ記録を有効にします。**  

```
Edit-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer `
>> -AccessLog_Enabled $true `
>> -AccessLog_S3BucketName amzn-s3-demo-logging-bucket `
>> -AccessLog_S3BucketPrefix my-app/prod `
>> -AccessLog_EmitInterval 60
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Enable-ELBAvailabilityZoneForLoadBalancer`
<a name="elastic-load-balancing_EnableAvailabilityZonesForLoadBalancer_powershell_5_topic"></a>

次のコード例は、`Enable-ELBAvailabilityZoneForLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアベイラビリティーゾーンを指定されたロードバランサーに追加します。出力には、アベイラビリティーゾーンの完全なリストが含まれます。**  

```
Enable-ELBAvailabilityZoneForLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a
```
**出力:**  

```
us-west-2a
us-west-2b
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[EnableAvailabilityZonesForLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELBInstanceHealth`
<a name="elastic-load-balancing_DescribeInstanceHealth_powershell_5_topic"></a>

次のコード例は、`Get-ELBInstanceHealth` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーに登録されているインスタンスの状態を記述します。**  

```
Get-ELBInstanceHealth -LoadBalancerName my-load-balancer
```
**出力:**  

```
Description                   InstanceId                    ReasonCode                    State
-----------                   ----------                    ----------                    -----
N/A                           i-87654321                    N/A                           InService
Instance has failed at lea... i-12345678                    Instance                      OutOfService
```
**例 2: この例では、指定されたロードバランサーに登録されている指定されたインスタンスの状態を記述します。**  

```
Get-ELBInstanceHealth -LoadBalancerName my-load-balancer -Instance i-12345678
```
**例 3: この例では、指定されたインスタンスの状態の完全な説明を表示します。**  

```
(Get-ELBInstanceHealth -LoadBalancerName my-load-balancer -Instance i-12345678).Description
```
**出力:**  

```
Instance has failed at least the UnhealthyThreshold number of health checks consecutively.
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeInstanceHealth](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELBLoadBalancer`
<a name="elastic-load-balancing_DescribeLoadBalancers_powershell_5_topic"></a>

次のコード例は、`Get-ELBLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ロードバランサーの名前を一覧表示します。**  

```
Get-ELBLoadBalancer | format-table -property LoadBalancerName
```
**出力:**  

```
LoadBalancerName
----------------
my-load-balancer
my-other-load-balancer
my-internal-load-balancer
```
**例 2: この例では、指定されたロードバランサーを記述します。**  

```
Get-ELBLoadBalancer -LoadBalancerName my-load-balancer
```
**出力:**  

```
AvailabilityZones         : {us-west-2a, us-west-2b}
BackendServerDescriptions : {Amazon.ElasticLoadBalancing.Model.BackendServerDescription}
CanonicalHostedZoneName   : my-load-balancer-1234567890.us-west-2.elb.amazonaws.com
CanonicalHostedZoneNameID : Z3DZXE0EXAMPLE
CreatedTime               : 4/11/2015 12:12:45 PM
DNSName                   : my-load-balancer-1234567890.us-west-2.elb.amazonaws.com
HealthCheck               : Amazon.ElasticLoadBalancing.Model.HealthCheck
Instances                 : {i-207d9717, i-afefb49b}
ListenerDescriptions      : {Amazon.ElasticLoadBalancing.Model.ListenerDescription}
LoadBalancerName          : my-load-balancer
Policies                  : Amazon.ElasticLoadBalancing.Model.Policies
Scheme                    : internet-facing
SecurityGroups            : {sg-a61988c3}
SourceSecurityGroup       : Amazon.ElasticLoadBalancing.Model.SourceSecurityGroup
Subnets                   : {subnet-15aaab61}
VPCId                     : vpc-a01106c2
```
**例 3: この例では、現在の AWS リージョンのすべてのロードバランサーについて説明します。**  

```
Get-ELBLoadBalancer
```
**例 4: この例では、使用可能なすべての AWS リージョンのすべてのロードバランサーを記述します。**  

```
Get-AWSRegion | % { Get-ELBLoadBalancer -Region $_ }
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELBLoadBalancerAttribute`
<a name="elastic-load-balancing_DescribeLoadBalancerAttributes_powershell_5_topic"></a>

次のコード例は、`Get-ELBLoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーの属性を記述します。**  

```
Get-ELBLoadBalancerAttribute -LoadBalancerName my-load-balancer
```
**出力:**  

```
AccessLog              : Amazon.ElasticLoadBalancing.Model.AccessLog
AdditionalAttributes   : {}
ConnectionDraining     : Amazon.ElasticLoadBalancing.Model.ConnectionDraining
ConnectionSettings     : Amazon.ElasticLoadBalancing.Model.ConnectionSettings
CrossZoneLoadBalancing : Amazon.ElasticLoadBalancing.Model.CrossZoneLoadBalancing
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicies_powershell_5_topic"></a>

次のコード例は、`Get-ELBLoadBalancerPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーに関連付けられたポリシーを記述します。**  

```
Get-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer
```
**出力:**  

```
PolicyAttributeDescriptions             PolicyName                              PolicyTypeName
---------------------------             ----------                              --------------
{ProxyProtocol}                         my-ProxyProtocol-policy                 ProxyProtocolPolicyType
{CookieName}                            my-app-cookie-policy                    AppCookieStickinessPolicyType
```
**例 2: この例では、指定されたポリシーの属性を記述します。**  

```
(Get-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-ProxyProtocol-policy).PolicyAttributeDescriptions
```
**出力:**  

```
AttributeName    AttributeValue
-------------    --------------
ProxyProtocol    true
```
**例 3: この例では、サンプルポリシーを含む事前定義されたポリシーを記述します。サンプルポリシーの名前には ELBSample- プレフィックスが付いています。**  

```
Get-ELBLoadBalancerPolicy
```
**出力:**  

```
PolicyAttributeDescriptions             PolicyName                              PolicyTypeName
---------------------------             ----------                              --------------
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-05               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-03               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2015-02               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2014-10               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2014-01               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSecurityPolicy-2011-08               SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSample-ELBDefaultCipherPolicy        SSLNegotiationPolicyType
{Protocol-SSLv2, Protocol-TLSv1, Pro... ELBSample-OpenSSLDefaultCipherPolicy    SSLNegotiationPolicyType
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLoadBalancerPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELBLoadBalancerPolicyType`
<a name="elastic-load-balancing_DescribeLoadBalancerPolicyTypes_powershell_5_topic"></a>

次のコード例は、`Get-ELBLoadBalancerPolicyType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Elastic Load Balancing でサポートされているポリシータイプを取得します。**  

```
Get-ELBLoadBalancerPolicyType
```
**出力:**  

```
Description                             PolicyAttributeTypeDescriptions         PolicyTypeName
-----------                             -------------------------------         --------------
Stickiness policy with session lifet... {CookieExpirationPeriod}                LBCookieStickinessPolicyType
Policy that controls authentication ... {PublicKeyPolicyName}                   BackendServerAuthenticationPolicyType
Listener policy that defines the cip... {Protocol-SSLv2, Protocol-TLSv1, Pro... SSLNegotiationPolicyType
Policy containing a list of public k... {PublicKey}                             PublicKeyPolicyType
Stickiness policy with session lifet... {CookieName}                            AppCookieStickinessPolicyType
Policy that controls whether to incl... {ProxyProtocol}                         ProxyProtocolPolicyType
```
**例 2: この例では、指定されたポリシータイプを記述します。**  

```
Get-ELBLoadBalancerPolicyType -PolicyTypeName ProxyProtocolPolicyType
```
**出力:**  

```
Description                             PolicyAttributeTypeDescriptions         PolicyTypeName
-----------                             -------------------------------         --------------
Policy that controls whether to incl... {ProxyProtocol}                         ProxyProtocolPolicyType
```
**例 3: この例では、指定されたポリシータイプの完全な説明を表示します。**  

```
(Get-ELBLoadBalancerPolicyType -PolicyTypeName).Description
```
**出力:**  

```
Policy that controls whether to include the IP address and port of the originating request for TCP messages. 
This policy operates on TCP/SSL listeners only
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeLoadBalancerPolicyTypes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELBResourceTag`
<a name="elastic-load-balancing_DescribeTags_powershell_5_topic"></a>

次のコード例は、`Get-ELBResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーのタグを一覧表示します。**  

```
Get-ELBResourceTag -LoadBalancerName @("my-load-balancer","my-internal-load-balancer")
```
**出力:**  

```
LoadBalancerName             Tags
----------------             ----
my-load-balancer             {project, department}
my-internal-load-balancer    {project, department}
```
**例 2: この例では、指定されたロードバランサーのタグを記述します。**  

```
(Get-ELBResourceTag -LoadBalancerName my-load-balancer).Tags
```
**出力:**  

```
Key           Value
---           -----
project       lima
department    digital-media
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Join-ELBSecurityGroupToLoadBalancer`
<a name="elastic-load-balancing_ApplySecurityGroupsToLoadBalancer_powershell_5_topic"></a>

次のコード例は、`Join-ELBSecurityGroupToLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーの現在のセキュリティグループを、指定されたセキュリティグループに置き換えます。**  

```
Join-ELBSecurityGroupToLoadBalancer -LoadBalancerName my-load-balancer -SecurityGroup sg-87654321
```
**出力:**  

```
sg-87654321
```
**例 2: 現在のセキュリティグループを保持し、追加のセキュリティグループを指定するには、既存のセキュリティグループと新しいセキュリティグループの両方を指定します。**  

```
Join-ELBSecurityGroupToLoadBalancer -LoadBalancerName my-load-balancer -SecurityGroup @("sg-12345678", "sg-87654321")
```
**出力:**  

```
sg-12345678
sg-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ApplySecurityGroupsToLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ELBAppCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateAppCookieStickinessPolicy_powershell_5_topic"></a>

次のコード例は、`New-ELBAppCookieStickinessPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたアプリケーション生成 Cookie のスティッキーセッション存続期間に従うスティッキーポリシーを生成します。**  

```
New-ELBAppCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-app-cookie-policy -CookieName my-app-cookie
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateAppCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ELBLBCookieStickinessPolicy`
<a name="elastic-load-balancing_CreateLbCookieStickinessPolicy_powershell_5_topic"></a>

次のコード例は、`New-ELBLBCookieStickinessPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された有効期間 (秒) によって制御されたスティッキーセッションの存続期間を持つスティッキーポリシーを生成します。**  

```
New-ELBLBCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy -CookieExpirationPeriod 60
```
**例 2: この例では、ブラウザ (user-agent) の有効期間によって制御されるスティッキーセッションの有効期間を持つスティッキーポリシーを作成します。**  

```
New-ELBLBCookieStickinessPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateLbCookieStickinessPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ELBLoadBalancer`
<a name="elastic-load-balancing_CreateLoadBalancer_powershell_5_topic"></a>

次のコード例は、`New-ELBLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、VPC に HTTP リスナーを持つロードバランサーを作成します。**  

```
$httpListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpListener.Protocol = "http"
$httpListener.LoadBalancerPort = 80
$httpListener.InstanceProtocol = "http"
$httpListener.InstancePort = 80
New-ELBLoadBalancer -LoadBalancerName my-vpc-load-balancer -SecurityGroup sg-a61988c3 -Subnet subnet-15aaab61 -Listener $httpListener

my-vpc-load-balancer-1234567890.us-west-2.elb.amazonaws.com
```
**例 2: この例では、EC2-Classic に HTTP リスナーを持つロードバランサーを作成します。**  

```
New-ELBLoadBalancer -LoadBalancerName my-classic-load-balancer -AvailabilityZone us-west-2a` -Listener $httpListener
```
**出力:**  

```
my-classic-load-balancer-123456789.us-west-2.elb.amazonaws.com
```
**例 3: この例では、HTTP リスナーを持つロードバランサーを作成します。**  

```
$httpsListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpsListener.Protocol = "https"
$httpsListener.LoadBalancerPort = 443
$httpsListener.InstanceProtocol = "http"
$httpsListener.InstancePort = 80 
$httpsListener.SSLCertificateId="arn:aws:iam::123456789012:server-certificate/my-server-cert"
New-ELBLoadBalancer -LoadBalancerName my-load-balancer -AvailabilityZone us-west-2a -Listener $httpsListener

my-load-balancer-123456789.us-west-2.elb.amazonaws.com
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ELBLoadBalancerListener`
<a name="elastic-load-balancing_CreateLoadBalancerListeners_powershell_5_topic"></a>

次のコード例は、`New-ELBLoadBalancerListener` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したロードバランサーに HTTPS リスナーを追加します。**  

```
$httpsListener = New-Object Amazon.ElasticLoadBalancing.Model.Listener
$httpsListener.Protocol = "https"
$httpsListener.LoadBalancerPort = 443
$httpsListener.InstanceProtocol = "https"
$httpsListener.InstancePort = 443 
$httpsListener.SSLCertificateId="arn:aws:iam::123456789012:server-certificate/my-server-cert"
New-ELBLoadBalancerListener -LoadBalancerName my-load-balancer -Listener $httpsListener
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_CreateLoadBalancerPolicy_powershell_5_topic"></a>

次のコード例は、`New-ELBLoadBalancerPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーのプロキシプロトコルポリシーを作成します。**  

```
$attribute = New-Object Amazon.ElasticLoadBalancing.Model.PolicyAttribute -Property @{
         AttributeName="ProxyProtocol"
         AttributeValue="True"
    }
New-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-ProxyProtocol-policy -PolicyTypeName ProxyProtocolPolicyType -PolicyAttribute $attribute
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[CreateLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Register-ELBInstanceWithLoadBalancer`
<a name="elastic-load-balancing_RegisterInstancesWithLoadBalancer_powershell_5_topic"></a>

次のコード例は、`Register-ELBInstanceWithLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された EC2 インスタンスを指定されたロードバランサーに登録します。**  

```
Register-ELBInstanceWithLoadBalancer -LoadBalancerName my-load-balancer -Instance i-12345678
```
**出力:**  

```
InstanceId
----------
i-12345678
i-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RegisterInstancesWithLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ELBInstanceFromLoadBalancer`
<a name="elastic-load-balancing_DeregisterInstancesFromLoadBalancer_powershell_5_topic"></a>

次のコード例は、`Remove-ELBInstanceFromLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーから指定された EC2 インスタンスを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBInstanceFromLoadBalancer -LoadBalancerName my-load-balancer -Instance i-12345678
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBInstanceFromLoadBalancer (DeregisterInstancesFromLoadBalancer)" on Target
"Amazon.ElasticLoadBalancing.Model.Instance".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):

InstanceId
----------
i-87654321
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)*の「[DeregisterInstancesFromLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ELBLoadBalancer`
<a name="elastic-load-balancing_DeleteLoadBalancer_powershell_5_topic"></a>

次のコード例は、`Remove-ELBLoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBLoadBalancer -LoadBalancerName my-load-balancer
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancer (DeleteLoadBalancer)" on Target "my-load-balancer".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-ELBLoadBalancerListener`
<a name="elastic-load-balancing_DeleteLoadBalancerListeners_powershell_5_topic"></a>

次のコード例は、`Remove-ELBLoadBalancerListener` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーのポート 80 のリスナーを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBLoadBalancerListener -LoadBalancerName my-load-balancer -LoadBalancerPort 80
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancerListener (DeleteLoadBalancerListeners)" on Target "80".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteLoadBalancerListeners](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ELBLoadBalancerPolicy`
<a name="elastic-load-balancing_DeleteLoadBalancerPolicy_powershell_5_topic"></a>

次のコード例は、`Remove-ELBLoadBalancerPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーから指定されたポリシーを削除します。Force パラメータも指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。**  

```
Remove-ELBLoadBalancerPolicy -LoadBalancerName my-load-balancer -PolicyName my-duration-cookie-policy
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing operation "Remove-ELBLoadBalancerPolicy (DeleteLoadBalancerPolicy)" on Target "my-duration-cookie-policy".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DeleteLoadBalancerPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-ELBResourceTag`
<a name="elastic-load-balancing_RemoveTags_powershell_5_topic"></a>

次のコード例は、`Remove-ELBResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーから指定されたタグを削除します。Force パラメータを指定しない限り、操作を続行する前に確認を求めるプロンプトが表示されます。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
Remove-ELBResourceTag -LoadBalancerName my-load-balancer -Tag @{ Key="project" }
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELBResourceTag (RemoveTags)" on target "Amazon.ElasticLoadBalancing.Model.TagKeyOnly".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"):
```
**例 2: PowerShell バージョン 2 では、New-Object を使用してタグパラメータのタグを作成する必要があります。**  

```
$tag = New-Object Amazon.ElasticLoadBalancing.Model.TagKeyOnly
$tag.Key = "project"
Remove-ELBResourceTag -Tag $tag -Force
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[RemoveTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-ELBHealthCheck`
<a name="elastic-load-balancing_ConfigureHealthCheck_powershell_5_topic"></a>

次のコード例は、`Set-ELBHealthCheck` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーのヘルスチェック設定を構成します。**  

```
Set-ELBHealthCheck -LoadBalancerName my-load-balancer `
>> -HealthCheck_HealthyThreshold 2 `
>> -HealthCheck_UnhealthyThreshold 2 `
>> -HealthCheck_Target "HTTP:80/ping" `
>> -HealthCheck_Interval 30 `
>> -HealthCheck_Timeout 3
```
**出力:**  

```
HealthyThreshold   : 2
Interval           : 30
Target             : HTTP:80/ping
Timeout            : 3
UnhealthyThreshold : 2
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ConfigureHealthCheck](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-ELBLoadBalancerListenerSSLCertificate`
<a name="elastic-load-balancing_SetLoadBalancerListenerSslCertificate_powershell_5_topic"></a>

次のコード例は、`Set-ELBLoadBalancerListenerSSLCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナーの SSL 接続を終了する証明書を置き換えます。**  

```
Set-ELBLoadBalancerListenerSSLCertificate -LoadBalancerName my-load-balancer `
>> -LoadBalancerPort 443 `
>> -SSLCertificateId "arn:aws:iam::123456789012:server-certificate/new-server-cert"
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* 「[SetLoadBalancerListenerSslCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-ELBLoadBalancerPolicyForBackendServer`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesForBackendServer_powershell_5_topic"></a>

次のコード例は、`Set-ELBLoadBalancerPolicyForBackendServer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたポートのポリシーを指定されたポリシーに置き換えます。**  

```
Set-ELBLoadBalancerPolicyForBackendServer -LoadBalancerName my-load-balancer -InstancePort 80 -PolicyName my-ProxyProtocol-policy
```
**例 2: この例では、指定されたポートに関連付けられているすべてのポリシーを削除します。**  

```
Set-ELBLoadBalancerPolicyForBackendServer -LoadBalancerName my-load-balancer -InstancePort 80
```
+  API の詳細については、AWS Tools for PowerShell コマンドリファレンス (V5) の「[SetLoadBalancerPoliciesForBackendServer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-ELBLoadBalancerPolicyOfListener`
<a name="elastic-load-balancing_SetLoadBalancerPoliciesOfListener_powershell_5_topic"></a>

次のコード例は、`Set-ELBLoadBalancerPolicyOfListener` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナーのポリシーを指定されたポリシーに置き換えます。**  

```
Set-ELBLoadBalancerPolicyOfListener -LoadBalancerName my-load-balancer -LoadBalancerPort 443 -PolicyName my-SSLNegotiation-policy
```
**例 2: この例では、指定されたリスナーに関連付けられているすべてのポリシーを削除します。**  

```
Set-ELBLoadBalancerPolicyOfListener -LoadBalancerName my-load-balancer -LoadBalancerPort 443
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[SetLoadBalancerPoliciesOfListener](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# Tools for PowerShell V5 を使用した Elastic Load Balancing - バージョン 2 の例
<a name="powershell_5_elastic-load-balancing-v2_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 2 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_AddListenerCertificates_powershell_5_topic"></a>

次のコード例は、`Add-ELB2ListenerCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナーに証明書を追加します。**  

```
Add-ELB2ListenerCertificate -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618' -Certificate @{CertificateArn = 'arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97'}
```
**出力:**  

```
CertificateArn                                                                      IsDefault
--------------                                                                      ---------
arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97 False
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AddListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Add-ELB2Tag`
<a name="elastic-load-balancing-v2_AddTags_powershell_5_topic"></a>

次のコード例は、`Add-ELB2Tag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された `AWS.Tools.ElasticLoadBalancingV2` リソースに新しいタグを追加します。**  

```
Add-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Tag @{Key = 'productVersion'; Value = '1.0.0'}
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[AddTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-ELB2Listener`
<a name="elastic-load-balancing-v2_ModifyListener_powershell_5_topic"></a>

次のコード例は、`Edit-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナーのデフォルトアクションを固定レスポンスに変更します。**  

```
$newDefaultAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{
    "FixedResponseConfig" = @{
    "ContentType" = "text/plain"
    "MessageBody" = "Hello World"
    "StatusCode" = "200"
  }
  "Type" = [Amazon.ElasticLoadBalancingV2.ActionTypeEnum]::FixedResponse
}

Edit-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/d19f2f14974db685' -Port 8080 -DefaultAction $newDefaultAction
```
**出力:**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/d19f2f14974db685
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676
Port            : 8080
Protocol        : HTTP
SslPolicy       :
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyListener](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_ModifyLoadBalancerAttributes_powershell_5_topic"></a>

次のコード例は、`Edit-ELB2LoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーの属性を変更します。**  

```
Edit-ELB2LoadBalancerAttribute -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Attribute @{Key = 'deletion_protection.enabled'; Value = 'true'}
```
**出力:**  

```
Key                                             Value
---                                             -----
deletion_protection.enabled                     true
access_logs.s3.enabled                          false
access_logs.s3.bucket
access_logs.s3.prefix
idle_timeout.timeout_seconds                    60
routing.http2.enabled                           true
routing.http.drop_invalid_header_fields.enabled false
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-ELB2Rule`
<a name="elastic-load-balancing-v2_ModifyRule_powershell_5_topic"></a>

次のコード例は、`Edit-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナールール設定を変更します。**  

```
$newRuleCondition = [Amazon.ElasticLoadBalancingV2.Model.RuleCondition]@{
    "PathPatternConfig" = @{
    "Values" = "/login1","/login2","/login3" 
  }
  "Field" = "path-pattern"
}

Edit-ELB2Rule -RuleArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc' -Condition $newRuleCondition
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 10
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc
```
+  API の詳細については、AWS Tools for PowerShell * コマンドレットリファレンス (V5)* の「[ModifyRule](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_ModifyTargetGroup_powershell_5_topic"></a>

次のコード例は、`Edit-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたターゲットグループのプロパティを変更します。**  

```
Edit-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -HealthCheckIntervalSecond 60 -HealthCheckPath '/index.html' -HealthCheckPort 8080
```
**出力:**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 60
HealthCheckPath            : /index.html
HealthCheckPort            : 8080
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 5
LoadBalancerArns           : {}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970
TargetGroupName            : test-tg
TargetType                 : instance
UnhealthyThresholdCount    : 2
VpcId                      : vpc-2cfd7000
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_ModifyTargetGroupAttributes_powershell_5_topic"></a>

次のコード例は、`Edit-ELB2TargetGroupAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたターゲットグループの deregistration\$1delay 属性を変更します。**  

```
Edit-ELB2TargetGroupAttribute -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -Attribute @{Key = 'deregistration_delay.timeout_seconds'; Value = 600}
```
**出力:**  

```
Key                                   Value
---                                   -----
stickiness.enabled                    false
deregistration_delay.timeout_seconds  600
stickiness.type                       lb_cookie
stickiness.lb_cookie.duration_seconds 86400
slow_start.duration_seconds           0
load_balancing.algorithm.type         round_robin
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[ModifyTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELB2AccountLimit`
<a name="elastic-load-balancing-v2_DescribeAccountLimits_powershell_5_topic"></a>

次のコード例は、`Get-ELB2AccountLimit` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、特定のリージョンの ELB2 アカウント制限を一覧表示します。**  

```
Get-ELB2AccountLimit
```
**出力:**  

```
Max  Name
---  ----
3000 target-groups
1000 targets-per-application-load-balancer
50   listeners-per-application-load-balancer
100  rules-per-application-load-balancer
50   network-load-balancers
3000 targets-per-network-load-balancer
500  targets-per-availability-zone-per-network-load-balancer
50   listeners-per-network-load-balancer
5    condition-values-per-alb-rule
5    condition-wildcards-per-alb-rule
100  target-groups-per-application-load-balancer
5    target-groups-per-action-on-application-load-balancer
1    target-groups-per-action-on-network-load-balancer
50   application-load-balancers
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeAccountLimits](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELB2Listener`
<a name="elastic-load-balancing-v2_DescribeListeners_powershell_5_topic"></a>

次のコード例は、`Get-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された ALB/NLB のリスナーを記述します。**  

```
Get-ELB2Listener -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**出力:**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/1dac07c21187d41e
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f
Port            : 80
Protocol        : HTTP
SslPolicy       : 

Certificates    : {Amazon.ElasticLoadBalancingV2.Model.Certificate}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f
Port            : 443
Protocol        : HTTPS
SslPolicy       : ELBSecurityPolicy-2016-08
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeListeners](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_DescribeListenerCertificates_powershell_5_topic"></a>

次のコード例は、`Get-ELB2ListenerCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナーの証明書を記述します。**  

```
Get-ELB2ListenerCertificate -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**出力:**  

```
CertificateArn                                                                      IsDefault
--------------                                                                      ---------
arn:aws:acm:us-east-1:123456789012:certificate/5fc7c092-68bf-4862-969c-22fd48b6e17c True
```
+  API の詳細については、*AWS Tools for PowerShell コマンドレットリファレンス (V5)* の「[DescribeListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_powershell_5_topic"></a>

次のコード例は、`Get-ELB2LoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定されたリージョンのすべてのロードバランサーを表示します。**  

```
Get-ELB2LoadBalancer
```
**出力:**  

```
AvailabilityZones     : {us-east-1c}
CanonicalHostedZoneId : Z26RNL4JYFTOTI
CreatedTime           : 6/22/18 11:21:50 AM
DNSName               : test-elb1234567890-238d34ad8d94bc2e.elb.us-east-1.amazonaws.com
IpAddressType         : ipv4
LoadBalancerArn       : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/test-elb1234567890/238d34ad8d94bc2e
LoadBalancerName      : test-elb1234567890
Scheme                : internet-facing
SecurityGroups        : {}
State                 : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState
Type                  : network
VpcId                 : vpc-2cf00000
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeLoadBalancers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELB2LoadBalancerAttribute`
<a name="elastic-load-balancing-v2_DescribeLoadBalancerAttributes_powershell_5_topic"></a>

次のコード例は、`Get-ELB2LoadBalancerAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定されたロードバランサーの属性を記述します。**  

```
Get-ELB2LoadBalancerAttribute -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/net/test-elb/238d34ad8d94bc2e'
```
**出力:**  

```
Key                               Value
---                               -----
access_logs.s3.enabled            false
load_balancing.cross_zone.enabled true
access_logs.s3.prefix             
deletion_protection.enabled       false
access_logs.s3.bucket
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeLoadBalancerAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELB2Rule`
<a name="elastic-load-balancing-v2_DescribeRules_powershell_5_topic"></a>

次のコード例は、`Get-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナー ARN のリスナールールを記述します。**  

```
Get-ELB2Rule -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 1
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/2286fff5055e0f79

Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 2
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/14e7b036567623ba

Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {}
IsDefault  : True
Priority   : default
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b/853948cf3aa9b2bf
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeRules](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELB2SSLPolicy`
<a name="elastic-load-balancing-v2_DescribeSslPolicies_powershell_5_topic"></a>

次のコード例は、`Get-ELB2SSLPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ElasticLoadBalancingV2 で使用可能なすべてのリスナーポリシーを一覧表示します。**  

```
Get-ELB2SSLPolicy
```
**出力:**  

```
Ciphers                                                                                                           Name                                  SslProtocols
-------                                                                                                           ----                                  ------------
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-2016-08             {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-2-2017-01     {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-1-2017-01     {TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-2-Ext-2018-06 {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-2018-06          {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-2015-05             {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-TLS-1-0-2015-04     {TLSv1, TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-2-Res-2019-08  {TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-1-2019-08      {TLSv1.1, TLSv1.2}
{ECDHE-ECDSA-AES128-GCM-SHA256, ECDHE-RSA-AES128-GCM-SHA256, ECDHE-ECDSA-AES128-SHA256, ECDHE-RSA-AES128-SHA256} ELBSecurityPolicy-FS-1-2-2019-08      {TLSv1.2}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeSslPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELB2Tag`
<a name="elastic-load-balancing-v2_DescribeTags_powershell_5_topic"></a>

次のコード例は、`Get-ELB2Tag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリソースのタグを一覧表示します。**  

```
Get-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**出力:**  

```
ResourceArn                                                                                    Tags
-----------                                                                                    ----
arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f {stage, internalName, version}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DescribeTargetGroups_powershell_5_topic"></a>

次のコード例は、`Get-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたターゲットグループを記述します。**  

```
Get-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**出力:**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 30
HealthCheckPath            : /
HealthCheckPort            : traffic-port
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 5
LoadBalancerArns           : {arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970
TargetGroupName            : test-tg
TargetType                 : instance
UnhealthyThresholdCount    : 2
VpcId                      : vpc-2cfd7000
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTargetGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELB2TargetGroupAttribute`
<a name="elastic-load-balancing-v2_DescribeTargetGroupAttributes_powershell_5_topic"></a>

次のコード例は、`Get-ELB2TargetGroupAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたターゲットグループの属性を記述します。**  

```
Get-ELB2TargetGroupAttribute -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**出力:**  

```
Key                                   Value
---                                   -----
stickiness.enabled                    false
deregistration_delay.timeout_seconds  300
stickiness.type                       lb_cookie
stickiness.lb_cookie.duration_seconds 86400
slow_start.duration_seconds           0
load_balancing.algorithm.type         round_robin
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTargetGroupAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ELB2TargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_powershell_5_topic"></a>

次のコード例は、`Get-ELB2TargetHealth` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたターゲットグループに存在するターゲットのヘルスステータスを返します。**  

```
Get-ELB2TargetHealth -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
**出力:**  

```
HealthCheckPort Target                                                TargetHealth
--------------- ------                                                ------------
80              Amazon.ElasticLoadBalancingV2.Model.TargetDescription Amazon.ElasticLoadBalancingV2.Model.TargetHealth
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTargetHealth](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-ELB2Listener`
<a name="elastic-load-balancing-v2_CreateListener_powershell_5_topic"></a>

次のコード例は、`New-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたターゲットグループにトラフィックを送信するデフォルトのアクション「Forward」を持つ新しい ALB リスナーを作成します。**  

```
$defaultAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{
  ForwardConfig = @{
    TargetGroups = @(
      @{ TargetGroupArn = "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testAlbTG/3d61c2f20aa5bccb" }
    )
    TargetGroupStickinessConfig = @{
      DurationSeconds = 900
      Enabled = $true
    }
  }
  Type = "Forward"
}

New-ELB2Listener -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676' -Port 8001 -Protocol "HTTP" -DefaultAction $defaultAction
```
**出力:**  

```
Certificates    : {}
DefaultActions  : {Amazon.ElasticLoadBalancingV2.Model.Action}
ListenerArn     : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/1c84f02aec143e80
LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/testALB/3e2f03b558e19676
Port            : 8001
Protocol        : HTTP
SslPolicy       :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateListener](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_powershell_5_topic"></a>

次のコード例は、`New-ELB2LoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、2 つのサブネットを持つインターネット向けの新しい Application Load Balancer を作成します。**  

```
New-ELB2LoadBalancer -Type application -Scheme internet-facing -IpAddressType ipv4 -Name 'New-Test-ALB' -SecurityGroup 'sg-07c3414abb8811cbd' -subnet 'subnet-c37a67a6','subnet-fc02eea0'
```
**出力:**  

```
AvailabilityZones     : {us-east-1b, us-east-1a}
CanonicalHostedZoneId : Z35SXDOTRQ7X7K
CreatedTime           : 12/28/19 2:58:03 PM
DNSName               : New-Test-ALB-1391502222.us-east-1.elb.amazonaws.com
IpAddressType         : ipv4
LoadBalancerArn       : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/New-Test-ALB/dab2e4d90eb51493
LoadBalancerName      : New-Test-ALB
Scheme                : internet-facing
SecurityGroups        : {sg-07c3414abb8811cbd}
State                 : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState
Type                  : application
VpcId                 : vpc-2cfd7000
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-ELB2Rule`
<a name="elastic-load-balancing-v2_CreateRule_powershell_5_topic"></a>

次のコード例は、`New-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナーに対し、顧客ヘッダー値に基づいた固定レスポンスアクションを持つ新しいリスナールールを作成します。**  

```
$newRuleAction = [Amazon.ElasticLoadBalancingV2.Model.Action]@{           
  "FixedResponseConfig" = @{
    "ContentType" = "text/plain"
    "MessageBody" = "Hello World"
    "StatusCode" = "200"
  }
  "Type" = [Amazon.ElasticLoadBalancingV2.ActionTypeEnum]::FixedResponse
}

$newRuleCondition = [Amazon.ElasticLoadBalancingV2.Model.RuleCondition]@{
  "httpHeaderConfig" = @{
    "HttpHeaderName" = "customHeader"
    "Values" = "header2","header1" 
  }         
  "Field" = "http-header"
}

New-ELB2Rule -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/testALB/3e2f03b558e19676/1c84f02aec143e80' -Action $newRuleAction -Condition $newRuleCondition -Priority 10
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 10
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/testALB/3e2f03b558e19676/1c84f02aec143e80/f4f51dfaa033a8cc
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateRule](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_powershell_5_topic"></a>

次のコード例は、`New-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたパラメータを使用して新しいターゲットグループを作成します。**  

```
New-ELB2TargetGroup -HealthCheckEnabled 1 -HealthCheckIntervalSeconds 30 -HealthCheckPath '/index.html' -HealthCheckPort 80 -HealthCheckTimeoutSecond 5 -HealthyThresholdCount 2 -UnhealthyThresholdCount 5 -Port 80 -Protocol 'HTTP' -TargetType instance -VpcId 'vpc-2cfd7000' -Name 'NewTargetGroup'
```
**出力:**  

```
HealthCheckEnabled         : True
HealthCheckIntervalSeconds : 30
HealthCheckPath            : /index.html
HealthCheckPort            : 80
HealthCheckProtocol        : HTTP
HealthCheckTimeoutSeconds  : 5
HealthyThresholdCount      : 2
LoadBalancerArns           : {}
Matcher                    : Amazon.ElasticLoadBalancingV2.Model.Matcher
Port                       : 80
Protocol                   : HTTP
TargetGroupArn             : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/NewTargetGroup/534e484681d801bf
TargetGroupName            : NewTargetGroup
TargetType                 : instance
UnhealthyThresholdCount    : 5
VpcId                      : vpc-2cfd7000
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-ELB2Target`
<a name="elastic-load-balancing-v2_RegisterTargets_powershell_5_topic"></a>

次のコード例は、`Register-ELB2Target` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、「i-0672a4c4cdeae3111」インスタンスを指定されたターゲットグループに登録します。**  

```
Register-ELB2Target -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970' -Target @{Port = 80; Id = 'i-0672a4c4cdeae3111'}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RegisterTargets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-ELB2Listener`
<a name="elastic-load-balancing-v2_DeleteListener_powershell_5_topic"></a>

次のコード例は、`Remove-ELB2Listener` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナーを削除します。**  

```
Remove-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Listener (DeleteListener)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/66e10e3aaf5b6d9b".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
**例 2: この例では、ロードバランサーから指定されたリスナーを削除します。**  

```
Remove-ELB2Listener -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Listener (DeleteListener)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteListener](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-ELB2ListenerCertificate`
<a name="elastic-load-balancing-v2_RemoveListenerCertificates_powershell_5_topic"></a>

次のコード例は、`Remove-ELB2ListenerCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したターゲットグループから指定した証明書を削除します。**  

```
Remove-ELB2ListenerCertificate -Certificate @{CertificateArn = 'arn:aws:acm:us-east-1:123456789012:certificate/19478bd5-491d-47d4-b1d7-5217feba1d97'} -ListenerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2ListenerCertificate (RemoveListenerCertificates)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener/app/test-alb/3651b4394dd9a24f/3873f123b98f7618".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemoveListenerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-ELB2LoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_powershell_5_topic"></a>

次のコード例は、`Remove-ELB2LoadBalancer` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーを削除します。**  

```
Remove-ELB2LoadBalancer -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2LoadBalancer (DeleteLoadBalancer)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteLoadBalancer](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-ELB2Rule`
<a name="elastic-load-balancing-v2_DeleteRule_powershell_5_topic"></a>

次のコード例は、`Remove-ELB2Rule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リスナーから指定されたルールを削除します。**  

```
Remove-ELB2Rule -RuleArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/3873f123b98f7618/4b25eb10a42e33ab'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Rule (DeleteRule)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/3873f123b98f7618/4b25eb10a42e33ab".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteRule](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-ELB2Tag`
<a name="elastic-load-balancing-v2_RemoveTags_powershell_5_topic"></a>

次のコード例は、`Remove-ELB2Tag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたキーのタグを削除します。**  

```
Remove-ELB2Tag -ResourceArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -TagKey 'productVersion'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2Tag (RemoveTags)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemoveTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-ELB2TargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_powershell_5_topic"></a>

次のコード例は、`Remove-ELB2TargetGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたターゲットグループを削除します。**  

```
Remove-ELB2TargetGroup -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testsssss/4e0b6076bc6483a7'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-ELB2TargetGroup (DeleteTargetGroup)" on target "arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/testsssss/4e0b6076bc6483a7".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteTargetGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-ELB2IpAddressType`
<a name="elastic-load-balancing-v2_SetIpAddressType_powershell_5_topic"></a>

次のコード例は、`Set-ELB2IpAddressType` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ロードバランサーの IP アドレスタイプを「IPv4」から「DualStack」に変更します。**  

```
Set-ELB2IpAddressType -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -IpAddressType dualstack
```
**出力:**  

```
Value
-----
dualstack
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SetIpAddressType](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-ELB2RulePriority`
<a name="elastic-load-balancing-v2_SetRulePriorities_powershell_5_topic"></a>

次のコード例は、`Set-ELB2RulePriority` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリスナールールの優先度を変更します。**  

```
Set-ELB2RulePriority -RulePriority -RulePriority @{Priority = 11; RuleArn = 'arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/a4eb199fa5046f80/dbf4c6dcef3ec6f8'}
```
**出力:**  

```
Actions    : {Amazon.ElasticLoadBalancingV2.Model.Action}
Conditions : {Amazon.ElasticLoadBalancingV2.Model.RuleCondition}
IsDefault  : False
Priority   : 11
RuleArn    : arn:aws:elasticloadbalancing:us-east-1:123456789012:listener-rule/app/test-alb/3651b4394dd9a24f/a4eb199fa5046f80/dbf4c6dcef3ec6f8
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SetRulePriorities](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-ELB2SecurityGroup`
<a name="elastic-load-balancing-v2_SetSecurityGroups_powershell_5_topic"></a>

次のコード例は、`Set-ELB2SecurityGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、セキュリティグループ「sg-07c3414abb8811cbd」を指定されたロードバランサーに追加します。**  

```
Set-ELB2SecurityGroup -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -SecurityGroup 'sg-07c3414abb8811cbd'
```
**出力:**  

```
sg-07c3414abb8811cbd
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SetSecurityGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-ELB2Subnet`
<a name="elastic-load-balancing-v2_SetSubnets_powershell_5_topic"></a>

次のコード例は、`Set-ELB2Subnet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたロードバランサーのサブネットを変更します。**  

```
Set-ELB2Subnet -LoadBalancerArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/test-alb/3651b4394dd9a24f' -Subnet 'subnet-7d8a0a51','subnet-c37a67a6'
```
**出力:**  

```
LoadBalancerAddresses SubnetId        ZoneName
--------------------- --------        --------
{}                    subnet-7d8a0a51 us-east-1c
{}                    subnet-c37a67a6 us-east-1b
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SetSubnets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-ELB2Target`
<a name="elastic-load-balancing-v2_DeregisterTargets_powershell_5_topic"></a>

次のコード例は、`Unregister-ELB2Target` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンス「i-0672a4c4cdeae3111」を指定されたターゲットグループから登録解除します。**  

```
$targetDescription = New-Object Amazon.ElasticLoadBalancingV2.Model.TargetDescription
$targetDescription.Id = 'i-0672a4c4cdeae3111'
Unregister-ELB2Target -Target $targetDescription -TargetGroupArn 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/test-tg/a4e04b3688be1970'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeregisterTargets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon FSx の例
<a name="powershell_5_fsx_code_examples"></a>

次のコード例は、Amazon FSx で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-FSXResourceTag`
<a name="fsx_TagResource_powershell_5_topic"></a>

次のコード例は、`Add-FSXResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定リソースにタグを追加します。**  

```
Add-FSXResourceTag -ResourceARN "arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a" -Tag @{Key="Users";Value="Test"}
```
**出力:**  

```
arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-FSXBackup`
<a name="fsx_DescribeBackups_powershell_5_topic"></a>

次のコード例は、`Get-FSXBackup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ファイルシステム ID に対して昨日以降に作成されたバックアップを取得します。**  

```
Get-FSXBackup -Filter @{Name="file-system-id";Values=$fsx.FileSystemId} | Where-Object CreationTime -gt (Get-Date).AddDays(-1)
```
**出力:**  

```
BackupId        : backup-01dac234e56782bcc
CreationTime    : 6/14/2019 3:35:14 AM
FailureDetails  :
FileSystem      : Amazon.FSx.Model.FileSystem
KmsKeyId        : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f1-e1234c5af123
Lifecycle       : AVAILABLE
ProgressPercent : 100
ResourceARN     : arn:aws:fsx:eu-west-1:123456789012:backup/backup-01dac234e56782bcc
Tags            : {}
Type            : AUTOMATIC
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeBackups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-FSXFileSystem`
<a name="fsx_DescribeFileSystems_powershell_5_topic"></a>

次のコード例は、`Get-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定の filesystemId の説明を返します。**  

```
Get-FSXFileSystem -FileSystemId fs-01cd23bc4bdf5678a
```
**出力:**  

```
CreationTime         : 1/17/2019 9:55:30 AM
DNSName              : fs-01cd23bc4bdf5678a.ktmsad.local
FailureDetails       :
FileSystemId         : fs-01cd23bc4bdf5678a
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-5b67-8bde-a9f0-e1234c5af678
Lifecycle            : AVAILABLE
LustreConfiguration  :
NetworkInterfaceIds  : {eni-07d1dda1322b7e209}
OwnerId              : 123456789012
ResourceARN          : arn:aws:fsx:eu-west-1:123456789012:file-system/fs-01cd23bc4bdf5678a
StorageCapacity      : 300
SubnetIds            : {subnet-7d123456}
Tags                 : {FSx-Service}
VpcId                : vpc-41cf2b3f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeFileSystems](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-FSXResourceTagList`
<a name="fsx_ListTagsForResource_powershell_5_topic"></a>

次のコード例は、`Get-FSXResourceTagList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定リソース ARN のタグを一覧表示します。**  

```
Get-FSXResourceTagList -ResourceARN $fsx.ResourceARN
```
**出力:**  

```
Key         Value
---         -----
FSx-Service Windows
Users       Dev
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-FSXBackup`
<a name="fsx_CreateBackup_powershell_5_topic"></a>

次のコード例は、`New-FSXBackup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ファイルシステムのバックアップを作成します。**  

```
New-FSXBackup -FileSystemId fs-0b1fac2345623456ba
```
**出力:**  

```
BackupId        : backup-0b1fac2345623456ba
CreationTime    : 6/14/2019 5:37:17 PM
FailureDetails  :
FileSystem      : Amazon.FSx.Model.FileSystem
KmsKeyId        : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f3-e1234c5af678
Lifecycle       : CREATING
ProgressPercent : 0
ResourceARN     : arn:aws:fsx:eu-west-1:123456789012:backup/backup-0b1fac2345623456ba
Tags            : {}
Type            : USER_INITIATED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateBackup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-FSXFileSystem`
<a name="fsx_CreateFileSystem_powershell_5_topic"></a>

次のコード例は、`New-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定サブネットからのアクセスを許可し、1 秒あたり最大 8 メガバイトのスループットをサポートする新しい 300GB のWindows ファイルシステムを作成します。新しいファイルシステムは、指定の Microsoft Active Directory に自動的に結合されます。**  

```
New-FSXFileSystem -FileSystemType WINDOWS -StorageCapacity 300 -SubnetId subnet-1a2b3c4d5e6f -WindowsConfiguration @{ThroughputCapacity=8;ActiveDirectoryId='d-1a2b3c4d'}
```
**出力:**  

```
CreationTime         : 12/10/2018 6:06:59 PM
DNSName              : fs-abcdef01234567890.example.com
FailureDetails       :
FileSystemId         : fs-abcdef01234567890
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:us-west-2:123456789012:key/a1234567-252c-45e9-afaa-123456789abc
Lifecycle            : CREATING
LustreConfiguration  :
NetworkInterfaceIds  : {}
OwnerId              : 123456789012
ResourceARN          : arn:aws:fsx:us-west-2:123456789012:file-system/fs-abcdef01234567890
StorageCapacity      : 300
SubnetIds            : {subnet-1a2b3c4d5e6f}
Tags                 : {}
VpcId                : vpc-1a2b3c4d5e6f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-FSXFileSystemFromBackup`
<a name="fsx_CreateFileSystemFromBackup_powershell_5_topic"></a>

次のコード例は、`New-FSXFileSystemFromBackup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、既存の Amazon FSx for Windows File Server バックアップから新しい Amazon FSx ファイルシステムを作成します。**  

```
New-FSXFileSystemFromBackup -BackupId $backupID -Tag @{Key="tag:Name";Value="from-manual-backup"} -SubnetId $SubnetID -SecurityGroupId $SG_ID -WindowsConfiguration @{ThroughputCapacity=8;ActiveDirectoryId=$DirectoryID}
```
**出力:**  

```
CreationTime         : 8/8/2019 12:59:58 PM
DNSName              : fs-012ff34e56789120.ktmsad.local
FailureDetails       :
FileSystemId         : fs-012ff34e56789120
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-5b67-1bde-a2f3-e4567c8a9321
Lifecycle            : CREATING
LustreConfiguration  :
NetworkInterfaceIds  : {}
OwnerId              : 933303704102
ResourceARN          : arn:aws:fsx:eu-west-1:123456789012:file-system/fs-012ff34e56789120
StorageCapacity      : 300
SubnetIds            : {subnet-fa1ae23c}
Tags                 : {tag:Name}
VpcId                : vpc-12cf3b4f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateFileSystemFromBackup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-FSXBackup`
<a name="fsx_DeleteBackup_powershell_5_topic"></a>

次のコード例は、`Remove-FSXBackup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 backup-id を削除します。**  

```
Remove-FSXBackup -BackupId $backupID
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXBackup (DeleteBackup)" on target "backup-0bbca1e2345678e12".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

BackupId                 Lifecycle
--------                 ---------
backup-0bbca1e2345678e12 DELETED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBackup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-FSXFileSystem`
<a name="fsx_DeleteFileSystem_powershell_5_topic"></a>

次のコード例は、`Remove-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 FSX ファイルシステム ID を削除します。**  

```
Remove-FSXFileSystem -FileSystemId fs-012ff34e567890120
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXFileSystem (DeleteFileSystem)" on target "fs-012ff34e567890120".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

FileSystemId         Lifecycle WindowsResponse
------------         --------- ---------------
fs-012ff34e567890120 DELETING  Amazon.FSx.Model.DeleteFileSystemWindowsResponse
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-FSXResourceTag`
<a name="fsx_UntagResource_powershell_5_topic"></a>

次のコード例は、`Remove-FSXResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 FSX ファイルシステムリソース ARN のリソースタグを削除します。**  

```
Remove-FSXResourceTag -ResourceARN $FSX.ResourceARN -TagKey Users
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-FSXResourceTag (UntagResource)" on target "arn:aws:fsx:eu-west-1:933303704102:file-system/fs-07cd45bc6bdf2674a".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-FSXFileSystem`
<a name="fsx_UpdateFileSystem_powershell_5_topic"></a>

次のコード例は、`Update-FSXFileSystem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、UpdateFileSystemWindowsConfiguration を介して FSX ファイルシステムの自動バックアップ保持日数を更新します。**  

```
$UpdateFSXWinConfig = [Amazon.FSx.Model.UpdateFileSystemWindowsConfiguration]::new()
	$UpdateFSXWinConfig.AutomaticBackupRetentionDays = 35
	Update-FSXFileSystem -FileSystemId $FSX.FileSystemId -WindowsConfiguration $UpdateFSXWinConfig
```
**出力:**  

```
CreationTime         : 1/17/2019 9:55:30 AM
DNSName              : fs-01cd23bc4bdf5678a.ktmsad.local
FailureDetails       :
FileSystemId         : fs-01cd23bc4bdf5678a
FileSystemType       : WINDOWS
KmsKeyId             : arn:aws:kms:eu-west-1:123456789012:key/f1af23c4-1b23-1bde-a1f2-e1234c5af678
Lifecycle            : AVAILABLE
LustreConfiguration  :
NetworkInterfaceIds  : {eni-01cd23bc4bdf5678a}
OwnerId              : 933303704102
ResourceARN          : arn:aws:fsx:eu-west-1:933303704102:file-system/fs-07cd45bc6bdf2674a
StorageCapacity      : 300
SubnetIds            : {subnet-1d234567}
Tags                 : {FSx-Service}
VpcId                : vpc-23cf4b5f
WindowsConfiguration : Amazon.FSx.Model.WindowsFileSystemConfiguration
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateFileSystem](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon Glacier の例
<a name="powershell_5_glacier_code_examples"></a>

次のコード例は、Amazon Glacier で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-GLCJob`
<a name="glacier_DescribeJob_powershell_5_topic"></a>

次のコード例は、`Get-GLCJob` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定したジョブの詳細を返します。ジョブが正常に完了したら、Read-GCJobOutput コマンドレットを使用して、ジョブの内容 (アーカイブまたはインベントリのリスト) をローカルファイルシステムに取得できます。**  

```
Get-GLCJob -VaultName myvault -JobId "op1x...JSbthM"
```
**出力:**  

```
Action                       : ArchiveRetrieval
ArchiveId                    : o9O9j...X-TpIhQJw
ArchiveSHA256TreeHash        : 79f3ea754c02f58...dc57bf4395b
ArchiveSizeInBytes           : 38034480
Completed                    : False
CompletionDate               : 1/1/0001 12:00:00 AM
CreationDate                 : 12/13/2018 11:00:14 AM
InventoryRetrievalParameters :
InventorySizeInBytes         : 0
JobDescription               :
JobId                        : op1x...JSbthM
JobOutputPath                :
OutputLocation               :
RetrievalByteRange           : 0-38034479
SelectParameters             :
SHA256TreeHash               : 79f3ea754c02f58...dc57bf4395b
SNSTopic                     :
StatusCode                   : InProgress
StatusMessage                :
Tier                         : Standard
VaultARN                     : arn:aws:glacier:us-west-2:012345678912:vaults/test
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeJob](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-GLCVault`
<a name="glacier_CreateVault_powershell_5_topic"></a>

次のコード例は、`New-GLCVault` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ユーザーアカウント用に新しいボールトを作成します。-AccountId パラメータに値が指定されていないため、コマンドレットは現在のアカウントを示すデフォルトの「-」を使用します。**  

```
New-GLCVault -VaultName myvault
```
**出力:**  

```
/01234567812/vaults/myvault
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateVault](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Read-GLCJobOutput`
<a name="glacier_GetJobOutput_powershell_5_topic"></a>

次のコード例は、`Read-GLCJobOutput` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定したジョブで取得がスケジュールされているアーカイブコンテンツをダウンロードし、コンテンツをディスク上のファイルに保存します。ダウンロード時に、チェックサムがある場合は自動的に検証されます。必要に応じて `-Select '*'` を指定すると、チェックサムを含むレスポンス全体を返すことができます。**  

```
Read-GLCJobOutput -VaultName myvault -JobId "HSWjArc...Zq2XLiW" -FilePath "c:\temp\blue.bin"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetJobOutput](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Start-GLCJob`
<a name="glacier_InitiateJob_powershell_5_topic"></a>

次のコード例は、`Start-GLCJob` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定したユーザー所有のボールトからアーカイブを取得するジョブを開始します。ジョブのステータスは、Get-GLCJob コマンドレットを使用して確認できます。ジョブが正常に完了したら、Read-GCJobOutput コマンドレットを使用して、アーカイブの内容をローカルファイルシステムに取得できます。**  

```
Start-GLCJob -VaultName myvault -JobType "archive-retrieval" -JobDescription "archive retrieval" -ArchiveId "o9O9j...TX-TpIhQJw"
```
**出力:**  

```
JobId            JobOutputPath Location
-----            ------------- --------
op1x...JSbthM                  /012345678912/vaults/test/jobs/op1xe...I4HqCHkSJSbthM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[InitiateJob](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-GLCArchive`
<a name="glacier_UploadArchive_powershell_5_topic"></a>

次のコード例は、`Write-GLCArchive` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定したボールトに単一のファイルをアップロードし、アーカイブ ID と計算されたチェックサムを返します。**  

```
Write-GLCArchive -VaultName myvault -FilePath c:\temp\blue.bin
```
**出力:**  

```
FilePath                    ArchiveId              Checksum
--------                    ---------              --------
C:\temp\blue.bin            o9O9jUUs...TTX-TpIhQJw 79f3e...f4395b
```
**例 2: フォルダ階層の内容を、ユーザーアカウント内の指定したボールトにアップロードします。アップロードされたファイルごとに、コマンドレットはファイル名、対応するアーカイブ ID、アーカイブの計算されたチェックサムを出力します。**  

```
Write-GLCArchive -VaultName myvault -FolderPath . -Recurse
```
**出力:**  

```
FilePath                    ArchiveId              Checksum
--------                    ---------              --------
C:\temp\blue.bin            o9O9jUUs...TTX-TpIhQJw 79f3e...f4395b
C:\temp\green.bin           qXAfOdSG...czo729UHXrw d50a1...9184b9
C:\temp\lum.bin             39aNifP3...q9nb8nZkFIg 28886...5c3e27
C:\temp\red.bin             vp7E6rU_...Ejk_HhjAxKA e05f7...4e34f5
C:\temp\Folder1\file1.txt   _eRINlip...5Sxy7dD2BaA d0d2a...c8a3ba
C:\temp\Folder2\file2.iso   -Ix3jlmu...iXiDh-XfOPA 7469e...3e86f1
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[UploadArchive](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# AWS Glue Tools for PowerShell V5 を使用した の例
<a name="powershell_5_glue_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-GLUEJob`
<a name="glue_CreateJob_powershell_5_topic"></a>

次のコード例は、`New-GLUEJob` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 Glue AWS で新しいジョブを作成します。コマンド名の値は常に です`glueetl`。 AWS Glue は Python または Scala で記述されたジョブスクリプトの実行をサポートしています。この例では、ジョブスクリプト (MyTestGlueJob.py) は Python で記述されています。Python パラメータは `$DefArgs` 変数で指定され、ハッシュテーブルを受け入れる `DefaultArguments` パラメータで PowerShell コマンドに渡されます。`$JobParams`変数のパラメータは、 Glue API リファレンスのジョブ (https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api-jobs-job.html) トピックに記載されている CreateJob API AWS から取得されます。**  

```
$Command = New-Object Amazon.Glue.Model.JobCommand
$Command.Name = 'glueetl'
$Command.ScriptLocation = 's3://amzn-s3-demo-source-bucket/admin/MyTestGlueJob.py'
$Command

$Source = "source_test_table"
$Target = "target_test_table"
$Connections = $Source, $Target

$DefArgs = @{
     '--TempDir' = 's3://amzn-s3-demo-bucket/admin'
     '--job-bookmark-option' = 'job-bookmark-disable'
     '--job-language' = 'python'
     }
$DefArgs

$ExecutionProp = New-Object Amazon.Glue.Model.ExecutionProperty
$ExecutionProp.MaxConcurrentRuns = 1
$ExecutionProp

$JobParams = @{
    "AllocatedCapacity"    = "5"
    "Command"              = $Command
    "Connections_Connection" = $Connections
    "DefaultArguments"  = $DefArgs
    "Description"       = "This is a test"
    "ExecutionProperty" = $ExecutionProp
    "MaxRetries"        = "1"
    "Name"              = "MyOregonTestGlueJob"
    "Role"              = "Amazon-GlueServiceRoleForSSM"
    "Timeout"           = "20"
     }

New-GlueJob @JobParams
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateJob](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# AWS Health Tools for PowerShell V5 を使用した の例
<a name="powershell_5_health_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Health。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-HLTHEvent`
<a name="health_DescribeEvents_powershell_5_topic"></a>

次のコード例は、`Get-HLTHEvent` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは AWS Personal Health Dashboard からイベントを返します。ユーザーは -Region パラメータを追加して、米国東部 (バージニア北部) リージョンでサービスに対して使用可能なイベントを表示しますが、-Filter\$1Region パラメータは、欧州 (ロンドン) および米国西部 (オレゴン) リージョン (eu-west-2 および us-west-2) でログされたイベントをフィルタリングします。-Filter\$1StartTime パラメータはイベントが開始できる時間の範囲をフィルタリングし、-Filter\$1EndTime パラメータはイベントが終了する時間の範囲をフィルタリングします。その結果、指定された -Filter\$1StartTime 範囲内で開始し、スケジュールされた -Filter\$1EndTime 範囲内で終了する RDS の定期メンテナンスイベントが表示されます。**  

```
Get-HLTHEvent -Region us-east-1 -Filter_Region "eu-west-2","us-west-2" -Filter_StartTime @{from="3/14/2019 6:30:00AM";to="3/15/2019 5:00:00PM"} -Filter_EndTime @{from="3/21/2019 7:00:00AM";to="3/21/2019 5:00:00PM"}
```
**出力:**  

```
Arn               : arn:aws:health:us-west-2::event/RDS/AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED/AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED_USW2_20190314_20190321
AvailabilityZone  : 
EndTime           : 3/21/2019 2:00:00 PM
EventTypeCategory : scheduledChange
EventTypeCode     : AWS_RDS_HARDWARE_MAINTENANCE_SCHEDULED
LastUpdatedTime   : 2/28/2019 2:26:07 PM
Region            : us-west-2
Service           : RDS
StartTime         : 3/14/2019 2:00:00 PM
StatusCode        : open
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeEvents](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した IAM の例
<a name="powershell_5_iam_code_examples"></a>

次のコード例は、IAM で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-IAMClientIDToOpenIDConnectProvider`
<a name="iam_AddClientIdToOpenIdConnectProvider_powershell_5_topic"></a>

次のコード例は、`Add-IAMClientIDToOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、クライアント ID (または対象者) `my-application-ID` を `server.example.com` という名前の既存の OIDC プロバイダーに追加します。**  

```
Add-IAMClientIDToOpenIDConnectProvider -ClientID "my-application-ID" -OpenIDConnectProviderARN "arn:aws:iam::123456789012:oidc-provider/server.example.com"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AddClientIdToOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Add-IAMRoleTag`
<a name="iam_TagRole_powershell_5_topic"></a>

次のコード例は、`Add-IAMRoleTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ID 管理サービスのロールにタグを追加します。**  

```
Add-IAMRoleTag -RoleName AdminRoleacess -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TagRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Add-IAMRoleToInstanceProfile`
<a name="iam_AddRoleToInstanceProfile_powershell_5_topic"></a>

次のコード例は、`Add-IAMRoleToInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、`S3Access` という名前のロールを `webserver` という名前の既存のインスタンスプロファイルに追加します。インスタンスプロファイルを作成するには、`New-IAMInstanceProfile` コマンドを使用します。このコマンドを使用してインスタンスプロファイルを作成し、ロールに関連付けると、EC2 インスタンスにアタッチできます。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile-Name` パラメータと共に使用して、新しいインスタンスを起動します。**  

```
Add-IAMRoleToInstanceProfile -RoleName "S3Access" -InstanceProfileName "webserver"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AddRoleToInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Add-IAMUserTag`
<a name="iam_TagUser_powershell_5_topic"></a>

次のコード例は、`Add-IAMUserTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ID 管理サービスのユーザーにタグを追加します。**  

```
Add-IAMUserTag -UserName joe -Tag @{ Key = 'abac'; Value = 'testing'}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TagUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Add-IAMUserToGroup`
<a name="iam_AddUserToGroup_powershell_5_topic"></a>

次のコード例は、`Add-IAMUserToGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、`Bob` という名前のユーザーを `Admins` という名前のグループに追加します。**  

```
Add-IAMUserToGroup -UserName "Bob" -GroupName "Admins"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AddUserToGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Disable-IAMMFADevice`
<a name="iam_DeactivateMfaDevice_powershell_5_topic"></a>

次のコード例は、`Disable-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、シリアル番号 `123456789012` を持つユーザー `Bob` に関連付けられているハードウェア MFA デバイスを無効にします。**  

```
Disable-IAMMFADevice -UserName "Bob" -SerialNumber "123456789012"
```
**例 2: このコマンドは、ARN `arn:aws:iam::210987654321:mfa/David` を持つユーザー `David` に関連付けられている仮想 MFA デバイスを無効にします。仮想 MFA デバイスはアカウントから削除されないことに注意してください。仮想デバイスはまだ存在し、`Get-IAMVirtualMFADevice` コマンドの出力に表示されます。同じユーザーに対して新しい仮想 MFA デバイスを作成する前に、`Remove-IAMVirtualMFADevice` コマンドを使用して、古い仮想 MFA デバイスを削除する必要があります。**  

```
Disable-IAMMFADevice -UserName "David" -SerialNumber "arn:aws:iam::210987654321:mfa/David"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeactivateMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-IAMPassword`
<a name="iam_ChangePassword_powershell_5_topic"></a>

次のコード例は、`Edit-IAMPassword` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、コマンドを実行しているユーザーのパスワードを変更します。このコマンドは、IAM ユーザーのみが呼び出すことができます。 AWS アカウント (ルート) 認証情報でサインインしたときにこのコマンドが呼び出された場合、コマンドは`InvalidUserType`エラーを返します。**  

```
Edit-IAMPassword -OldPassword "MyOldP@ssw0rd" -NewPassword "MyNewP@ssw0rd"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ChangePassword](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Enable-IAMMFADevice`
<a name="iam_EnableMfaDevice_powershell_5_topic"></a>

次のコード例は、`Enable-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、シリアル番号 `987654321098` を持つハードウェア MFA デバイスを有効にし、このデバイスをユーザー `Bob` に関連付けます。また、このコマンドは、デバイスからの最初の 2 つのコードを順番に含めます。**  

```
Enable-IAMMFADevice -UserName "Bob" -SerialNumber "987654321098" -AuthenticationCode1 "12345678" -AuthenticationCode2 "87654321"
```
**例 2: この例では、仮想 MFA デバイスを作成して有効にします。最初のコマンドは仮想デバイスを作成し、そのデバイスのオブジェクト表現を変数 `$MFADevice` に返します。`.Base32StringSeed` または `QRCodePng` プロパティを使用して、ユーザーのソフトウェアアプリケーションを設定できます。最後のコマンドはデバイスをユーザー `David` に割り当て、デバイスをシリアル番号で識別します。コマンドは、仮想 MFA デバイスからの最初の 2 つのコードを順番に含める AWS ことで、デバイスを と同期します。**  

```
$MFADevice = New-IAMVirtualMFADevice -VirtualMFADeviceName "MyMFADevice"
# see example for New-IAMVirtualMFADevice to see how to configure the software program with PNG or base32 seed code
Enable-IAMMFADevice -UserName "David" -SerialNumber -SerialNumber $MFADevice.SerialNumber -AuthenticationCode1 "24681357" -AuthenticationCode2 "13572468"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[EnableMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAccessKey`
<a name="iam_ListAccessKeys_powershell_5_topic"></a>

次のコード例は、`Get-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、`Bob` という名前の IAM ユーザーのアクセスキーを一覧表示します。IAM ユーザーのシークレットアクセスキーを一覧表示できないことに注意してください。シークレットアクセスキーを紛失した場合は、`New-IAMAccessKey` コマンドレットを使用して新しいアクセスキーを作成する必要があります。**  

```
Get-IAMAccessKey -UserName "Bob"
```
**出力:**  

```
AccessKeyId                CreateDate                   Status              UserName
-----------                ----------                   ------              --------
AKIAIOSFODNN7EXAMPLE       12/3/2014 10:53:41 AM        Active              Bob
AKIAI44QH8DHBEXAMPLE       6/6/2013 8:42:26 PM          Inactive            Bob
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListAccessKeys](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_powershell_5_topic"></a>

次のコード例は、`Get-IAMAccessKeyLastUsed` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたアクセスキーの所有ユーザー名と最終使用情報を返します。**  

```
Get-IAMAccessKeyLastUsed -AccessKeyId ABCDEXAMPLE
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAccessKeyLastUsed](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAccountAlias`
<a name="iam_ListAccountAliases_powershell_5_topic"></a>

次のコード例は、`Get-IAMAccountAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、 AWS アカウントのアカウントエイリアスを返します。**  

```
Get-IAMAccountAlias
```
**出力:**  

```
ExampleCo
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListAccountAliases](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAccountAuthorizationDetail`
<a name="iam_GetAccountAuthorizationDetails_powershell_5_topic"></a>

次のコード例は、`Get-IAMAccountAuthorizationDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウント内の ID に関する認可の詳細を取得し、返されたオブジェクトの要素リスト (ユーザー、グループ、ロールを含む) を表示します。例えば、`UserDetailList` プロパティには、ユーザーに関する詳細が表示されます。同様の情報は、`RoleDetailList` および `GroupDetailList` プロパティで入手可能です。**  

```
$Details=Get-IAMAccountAuthorizationDetail
$Details
```
**出力:**  

```
GroupDetailList : {Administrators, Developers, Testers, Backup}
IsTruncated     : False
Marker          : 
RoleDetailList  : {TestRole1, AdminRole, TesterRole, clirole...}
UserDetailList  : {Administrator, Bob, BackupToS3, }
```

```
$Details.UserDetailList
```
**出力:**  

```
Arn            : arn:aws:iam::123456789012:user/Administrator
CreateDate     : 10/16/2014 9:03:09 AM
GroupList      : {Administrators}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE1
UserName       : Administrator
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/Bob
CreateDate     : 4/6/2015 12:54:42 PM
GroupList      : {Developers}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE2
UserName       : bab
UserPolicyList : {}

Arn            : arn:aws:iam::123456789012:user/BackupToS3
CreateDate     : 1/27/2015 10:15:08 AM
GroupList      : {Backup}
Path           : /
UserId         : AIDACKCEVSQ6CEXAMPLE3
UserName       : BackupToS3
UserPolicyList : {BackupServicePermissionsToS3Buckets}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAccountAuthorizationDetails](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMAccountPasswordPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在のアカウントのパスワードポリシーに関する詳細を返します。アカウントのためにパスワードポリシーが定義されていない場合、コマンドは `NoSuchEntity` エラーを返します。**  

```
Get-IAMAccountPasswordPolicy
```
**出力:**  

```
AllowUsersToChangePassword : True
ExpirePasswords            : True
HardExpiry                 : False
MaxPasswordAge             : 90
MinimumPasswordLength      : 8
PasswordReusePrevention    : 20
RequireLowercaseCharacters : True
RequireNumbers             : True
RequireSymbols             : False
RequireUppercaseCharacters : True
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAccountSummary`
<a name="iam_GetAccountSummary_powershell_5_topic"></a>

次のコード例は、`Get-IAMAccountSummary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウント内の現在の IAM エンティティの使用状況と現在の IAM エンティティのクォータに関する情報を返します。**  

```
Get-IAMAccountSummary
```
**出力:**  

```
Key                                        Value
Users                                      7
GroupPolicySizeQuota                       5120
PolicyVersionsInUseQuota                   10000
ServerCertificatesQuota                    20
AccountSigningCertificatesPresent          0
AccountAccessKeysPresent                   0
Groups                                     3
UsersQuota                                 5000
RolePolicySizeQuota                        10240
UserPolicySizeQuota                        2048
GroupsPerUserQuota                         10
AssumeRolePolicySizeQuota                  2048
AttachedPoliciesPerGroupQuota              2
Roles                                      9
VersionsPerPolicyQuota                     5
GroupsQuota                                100
PolicySizeQuota                            5120
Policies                                   5
RolesQuota                                 250
ServerCertificates                         0
AttachedPoliciesPerRoleQuota               2
MFADevicesInUse                            2
PoliciesQuota                              1000
AccountMFAEnabled                          1
Providers                                  2
InstanceProfilesQuota                      100
MFADevices                                 4
AccessKeysPerUserQuota                     2
AttachedPoliciesPerUserQuota               2
SigningCertificatesPerUserQuota            2
PolicyVersionsInUse                        4
InstanceProfiles                           1
...
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAccountSummary](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAttachedGroupPolicyList`
<a name="iam_ListAttachedGroupPolicies_powershell_5_topic"></a>

次のコード例は、`Get-IAMAttachedGroupPolicyList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、 AWS アカウント`Admins`内の という名前の IAM グループにアタッチされている管理ポリシーの名前と ARNs を返します。グループに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMGroupPolicyList` コマンドを使用します。**  

```
Get-IAMAttachedGroupPolicyList -GroupName "Admins"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
arn:aws:iam::aws:policy/AdministratorAccess               AdministratorAccess
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListAttachedGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAttachedRolePolicyList`
<a name="iam_ListAttachedRolePolicies_powershell_5_topic"></a>

次のコード例は、`Get-IAMAttachedRolePolicyList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、 AWS アカウントの `SecurityAuditRole` という名前の IAM ロールにアタッチされている管理ポリシーの名前と ARN を返します。ロールに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMRolePolicyList` コマンドを使用します。**  

```
Get-IAMAttachedRolePolicyList -RoleName "SecurityAuditRole"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/SecurityAudit                     SecurityAudit
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMAttachedUserPolicyList`
<a name="iam_ListAttachedUserPolicies_powershell_5_topic"></a>

次のコード例は、`Get-IAMAttachedUserPolicyList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、 AWS アカウント`Bob`で という名前の IAM ユーザー用の管理ポリシーの名前と ARNs を返します。IAM ユーザーに埋め込まれているインラインポリシーのリストを表示するには、`Get-IAMUserPolicyList` コマンドを使用します。**  

```
Get-IAMAttachedUserPolicyList -UserName "Bob"
```
**出力:**  

```
PolicyArn                                                 PolicyName
---------                                                 ----------
arn:aws:iam::aws:policy/TesterPolicy                      TesterPolicy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListAttachedUserPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMContextKeysForCustomPolicy`
<a name="iam_GetContextKeysForCustomPolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMContextKeysForCustomPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、提供されたポリシー JSON に含まれるすべてのコンテキストキーを取得します。複数のポリシーを指定するには、値のカンマ区切りリストとして指定できます。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForCustomPolicy -PolicyInputList $policy1,$policy2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetContextKeysForCustomPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMContextKeysForPrincipalPolicy`
<a name="iam_GetContextKeysForPrincipalPolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMContextKeysForPrincipalPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、提供されたポリシー JSON に含まれるすべてのコンテキストキーと IAM エンティティ (ユーザー/ロールなど) にアタッチされたポリシーを取得します。-PolicyInputList では、複数の値リストをカンマ区切り値として指定できます。**  

```
$policy1 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/","Condition":{"DateGreaterThan":{"aws:CurrentTime":"2015-08-16T12:00:00Z"}}}}'
$policy2 = '{"Version":"2012-10-17",		 	 	 "Statement":{"Effect":"Allow","Action":"dynamodb:*","Resource":"arn:aws:dynamodb:us-west-2:123456789012:table/"}}'
Get-IAMContextKeysForPrincipalPolicy -PolicyInputList $policy1,$policy2 -PolicySourceArn arn:aws:iam::852640994763:user/TestUser
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetContextKeysForPrincipalPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMCredentialReport`
<a name="iam_GetCredentialReport_powershell_5_topic"></a>

次のコード例は、`Get-IAMCredentialReport` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、返されたレポートを開き、それをテキスト行の配列としてパイプラインに出力します。最初の行は、カンマで区切られた列名のヘッダーです。連続する各行は 1 人のユーザーの詳細行で、各フィールドはカンマで区切られています。レポートを表示するには、`Request-IAMCredentialReport` コマンドレットを使用してレポートを生成する必要があります。レポートを 1 つの文字列として取得するには、`-AsTextArray` ではなく `-Raw` を使用します。`-AsTextArray` スイッチには、エイリアス `-SplitLines` も使用できます。出力の列の完全なリストについては、サービス API リファレンスを参照してください。`-AsTextArray` または `-SplitLines` を使用しない場合は、.NET `StreamReader` クラスを使用して、`.Content` プロパティからテキストを抽出する必要があることに注意してください。**  

```
Request-IAMCredentialReport
```
**出力:**  

```
Description                                                         State
-----------                                                         -----
No report exists. Starting a new report generation task             STARTED
```

```
Get-IAMCredentialReport -AsTextArray
```
**出力:**  

```
      user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed,password_next_rotation,mfa_active,access_key_1_active,access_key_1_last_rotated,access_key_2_active,access_key_2_last_rotated,cert_1_active,cert_1_last_rotated,cert_2_active,cert_2_last_rotated root_account,arn:aws:iam::123456789012:root,2014-10-15T16:31:25+00:00,not_supported,2015-04-20T17:41:10+00:00,not_supported,not_supported,true,false,N/A,false,N/A,false,N/A,false,N/A
Administrator,arn:aws:iam::123456789012:user/Administrator,2014-10-16T16:03:09+00:00,true,2015-04-20T15:18:32+00:00,2014-10-16T16:06:00+00:00,N/A,false,true,2014-12-03T18:53:41+00:00,true,2015-03-25T20:38:14+00:00,false,N/A,false,N/A
Bill,arn:aws:iam::123456789012:user/Bill,2015-04-15T18:27:44+00:00,false,N/A,N/A,N/A,false,false,N/A,false,N/A,false,2015-04-20T20:00:12+00:00,false,N/A
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetCredentialReport](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMEntitiesForPolicy`
<a name="iam_ListEntitiesForPolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMEntitiesForPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ポリシー `arn:aws:iam::123456789012:policy/TestPolicy` がアタッチされている IAM グループ、ロール、ユーザーのリストを返します。**  

```
Get-IAMEntitiesForPolicy -PolicyArn "arn:aws:iam::123456789012:policy/TestPolicy"
```
**出力:**  

```
IsTruncated  : False
Marker       : 
PolicyGroups : {}
PolicyRoles  : {testRole}
PolicyUsers  : {Bob, Theresa}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListEntitiesForPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMGroup`
<a name="iam_GetGroup_powershell_5_topic"></a>

次のコード例は、`Get-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、グループに属するすべての IAM ユーザーのコレクションを含む、IAM グループ `Testers` に関する詳細を返します。**  

```
$results = Get-IAMGroup -GroupName "Testers"
$results
```
**出力:**  

```
Group                                     IsTruncated           Marker                Users
-----                                     -----------           ------                -----
Amazon.IdentityManagement.Model.Group     False                                       {Theresa, David}
```

```
$results.Group
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : 3RHNZZGQJ7QHMAEXAMPLE1
GroupName  : Testers
Path       : /
```

```
$results.Users
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/Theresa
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : 4OSVDDJJTF4XEEXAMPLE2
UserName         : Theresa

Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE3
UserName         : David
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMGroupForUser`
<a name="iam_ListGroupsForUser_powershell_5_topic"></a>

次のコード例は、`Get-IAMGroupForUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ユーザー `David` が属する IAM グループのリストを返します。**  

```
Get-IAMGroupForUser -UserName David
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE2
GroupName  : Testers
Path       : /
      
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE3
GroupName  : Developers
Path       : /
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListGroupsForUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMGroupList`
<a name="iam_ListGroups_powershell_5_topic"></a>

次のコード例は、`Get-IAMGroupList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の で定義されているすべての IAM グループのコレクションを返します AWS アカウント。**  

```
Get-IAMGroupList
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Administrators
CreateDate : 10/20/2014 10:06:24 AM
GroupId    : 6WCH4TRY3KIHIEXAMPLE1
GroupName  : Administrators
Path       : /

Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 12/10/2014 3:38:55 PM
GroupId    : ZU2EOWMK6WBZOEXAMPLE2
GroupName  : Developers
Path       : /

Arn        : arn:aws:iam::123456789012:group/Testers
CreateDate : 12/10/2014 3:39:11 PM
GroupId    : RHNZZGQJ7QHMAEXAMPLE3
GroupName  : Testers
Path       : /
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMGroupPolicy`
<a name="iam_GetGroupPolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、グループ `Testers` の `PowerUserAccess-Testers` という名前の埋め込みインラインポリシーに関する詳細を返します。`PolicyDocument` プロパティは URL エンコードされています。この例では、`UrlDecode` .NET メソッドを使用してデコードされています。**  

```
$results = Get-IAMGroupPolicy -GroupName Testers -PolicyName PowerUserAccess-Testers
$results
```
**出力:**  

```
GroupName     PolicyDocument                                              PolicyName
---------     --------------                                              ----------
Testers       %7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%0A%20... PowerUserAccess-Testers

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
  ]
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMGroupPolicyList`
<a name="iam_ListGroupPolicies_powershell_5_topic"></a>

次のコード例は、`Get-IAMGroupPolicyList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、グループ `Testers` に埋め込まれているインラインポリシーのリストを返します。グループにアタッチされている管理ポリシーを取得するには、コマンド `Get-IAMAttachedGroupPolicyList` を使用します。**  

```
Get-IAMGroupPolicyList -GroupName Testers
```
**出力:**  

```
Deny-Assume-S3-Role-In-Production
PowerUserAccess-Testers
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListGroupPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMInstanceProfile`
<a name="iam_GetInstanceProfile_powershell_5_topic"></a>

次のコード例は、`Get-IAMInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントで定義されている `ec2instancerole` という名前のインスタンスプロファイルの詳細を返します。**  

```
Get-IAMInstanceProfile -InstanceProfileName ec2instancerole
```
**出力:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMInstanceProfileForRole`
<a name="iam_ListInstanceProfilesForRole_powershell_5_topic"></a>

次のコード例は、`Get-IAMInstanceProfileForRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ロール `ec2instancerole` に関連付けられているインスタンスプロファイルの詳細を返します。**  

```
Get-IAMInstanceProfileForRole -RoleName ec2instancerole
```
**出力:**  

```
      Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
      CreateDate          : 2/17/2015 2:49:04 PM
      InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
      InstanceProfileName : ec2instancerole
      Path                : /
      Roles               : {ec2instancerole}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListInstanceProfilesForRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMInstanceProfileList`
<a name="iam_ListInstanceProfiles_powershell_5_topic"></a>

次のコード例は、`Get-IAMInstanceProfileList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の で定義されているインスタンスプロファイルのコレクションを返します AWS アカウント。**  

```
Get-IAMInstanceProfileList
```
**出力:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ec2instancerole
CreateDate          : 2/17/2015 2:49:04 PM
InstanceProfileId   : HH36PTZQJUR32EXAMPLE1
InstanceProfileName : ec2instancerole
Path                : /
Roles               : {ec2instancerole}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListInstanceProfiles](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMLoginProfile`
<a name="iam_GetLoginProfile_powershell_5_topic"></a>

次のコード例は、`Get-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パスワードの作成日と、IAM ユーザー `David` のパスワードのリセットが必要かどうかを返します。**  

```
Get-IAMLoginProfile -UserName David
```
**出力:**  

```
CreateDate                   PasswordResetRequired                 UserName
----------                   ---------------------                 --------
12/10/2014 3:39:44 PM        False                                 David
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMMFADevice`
<a name="iam_ListMfaDevices_powershell_5_topic"></a>

次のコード例は、`Get-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ユーザー `David` に割り当てられた MFA デバイスに関する詳細を返します。この例では、`SerialNumber` は物理デバイスの実際のシリアル番号ではなく ARN であるため、仮想デバイスであることがわかります。**  

```
Get-IAMMFADevice -UserName David
```
**出力:**  

```
EnableDate                  SerialNumber                           UserName
----------                  ------------                           --------
4/8/2015 9:41:10 AM         arn:aws:iam::123456789012:mfa/David    David
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMOpenIDConnectProvider`
<a name="iam_GetOpenIdConnectProvider_powershell_5_topic"></a>

次のコード例は、`Get-IAMOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/accounts.google.com` である OpenID Connect プロバイダーに関する詳細を返します。`ClientIDList` プロパティは、このプロバイダーに定義されているすべてのクライアント ID を含むコレクションです。**  

```
Get-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/oidc.example.com
```
**出力:**  

```
ClientIDList         CreateDate                ThumbprintList                               Url
------------         ----------                --------------                               ---
{MyOIDCApp}          2/3/2015 3:00:30 PM       {12345abcdefghijk67890lmnopqrst98765uvwxy}   oidc.example.com
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMOpenIDConnectProviderList`
<a name="iam_ListOpenIdConnectProviders_powershell_5_topic"></a>

次のコード例は、`Get-IAMOpenIDConnectProviderList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントで定義されているすべての OpenID Connect プロバイダーの ARN のリストを返します。**  

```
Get-IAMOpenIDConnectProviderList
```
**出力:**  

```
Arn
---
arn:aws:iam::123456789012:oidc-provider/server.example.com
arn:aws:iam::123456789012:oidc-provider/another.provider.com
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListOpenIdConnectProviders](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMPolicy`
<a name="iam_GetPolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` である管理ポリシーに関する詳細を返します。**  

```
Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**出力:**  

```
Arn              : arn:aws:iam::aws:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 2/6/2015 10:40:08 AM
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[GetPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-IAMPolicyList`
<a name="iam_ListPolicies_powershell_5_topic"></a>

次のコード例は、`Get-IAMPolicyList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントで使用できる最初の 3 つの管理ポリシーのコレクションを返します。`-scope`が指定されていないため、デフォルトで に設定`all`され、 AWS 管理ポリシーとカスタマー管理ポリシーの両方が含まれます。**  

```
Get-IAMPolicyList -MaxItem 3
```
**出力:**  

```
Arn              : arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:08 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : Z27SI6FQMGNQ2EXAMPLE1
PolicyName       : AWSDirectConnectReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:08 AM
      
Arn              : arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess
AttachmentCount  : 0
CreateDate       : 2/6/2015 10:40:27 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : NJKMU274MET4EEXAMPLE2
PolicyName       : AmazonGlacierReadOnlyAccess
UpdateDate       : 2/6/2015 10:40:27 AM
      
Arn              : arn:aws:iam::aws:policy/AWSMarketplaceFullAccess
AttachmentCount  : 0
CreateDate       : 2/11/2015 9:21:45 AM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : 5ULJSO2FYVPYGEXAMPLE3
PolicyName       : AWSMarketplaceFullAccess
UpdateDate       : 2/11/2015 9:21:45 AM
```
**例 2: この例では、現在の AWS アカウントで使用できる最初の 2 つのカスタマー管理ポリシーのコレクションを返します。`-Scope local` を使用して、出力をカスタマー管理ポリシーのみに制限します。**  

```
Get-IAMPolicyList -Scope local -MaxItem 2
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:policy/MyLocalPolicy
AttachmentCount  : 0
CreateDate       : 2/12/2015 9:39:09 AM
DefaultVersionId : v2
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : SQVCBLC4VAOUCEXAMPLE4
PolicyName       : MyLocalPolicy
UpdateDate       : 2/12/2015 9:39:53 AM

Arn              : arn:aws:iam::123456789012:policy/policyforec2instancerole
AttachmentCount  : 1
CreateDate       : 2/17/2015 2:51:38 PM
DefaultVersionId : v11
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : X5JPBLJH2Z2SOEXAMPLE5
PolicyName       : policyforec2instancerole
UpdateDate       : 2/18/2015 8:52:31 AM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMPolicyVersion`
<a name="iam_GetPolicyVersion_powershell_5_topic"></a>

次のコード例は、`Get-IAMPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MyManagedPolicy` であるポリシーの `v2` バージョンのポリシードキュメントを返します。`Document` プロパティ内のポリシードキュメントは URL でエンコードされ、この例では `UrlDecode` .NET メソッドを使用してデコードされます。**  

```
$results = Get-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy -VersionId v2
$results
```
**出力:**  

```
CreateDate             Document                                        IsDefaultVersion     VersionId
----------             --------                                        ----------------     ---------
2/12/2015 9:39:53 AM   %7B%0A%20%20%22Version%22%3A%20%222012-10...    True                 v2

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
$policy = [System.Web.HttpUtility]::UrlDecode($results.Document)
$policy
{
  "Version":"2012-10-17",		 	 	 
  "Statement": 
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances"
      ],
      "Resource": [
        "arn:aws:ec2:us-east-1:555555555555:instance/i-b188560f"
      ]
    }
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetPolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMPolicyVersionList`
<a name="iam_ListPolicyVersions_powershell_5_topic"></a>

次のコード例は、`Get-IAMPolicyVersionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MyManagedPolicy` であるポリシーの使用可能なバージョンのリストを返します。特定のバージョンのポリシードキュメントを取得するには、`Get-IAMPolicyVersion` コマンドを使用して、必要なバージョンの `VersionId` を指定します。**  

```
Get-IAMPolicyVersionList -PolicyArn arn:aws:iam::123456789012:policy/MyManagedPolicy
```
**出力:**  

```
CreateDate                   Document                 IsDefaultVersion                  VersionId
----------                   --------                 ----------------                  ---------
2/12/2015 9:39:53 AM                                  True                              v2
2/12/2015 9:39:09 AM                                  False                             v1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListPolicyVersions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMRole`
<a name="iam_GetRole_powershell_5_topic"></a>

次のコード例は、`Get-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`lamda_exec_role` の詳細を返します。これには、このロールの引き受け先を指定する信頼ポリシードキュメントが含まれています。ポリシードキュメントは URL でエンコードされており、.NET `UrlDecode` メソッドを使用してデコードできます。この例では、元のポリシーは、ポリシーにアップロードされる前にすべての空白が削除されています。ロールを引き受けるユーザーが実行できる操作を決定するアクセス許可ポリシードキュメントを確認するには、インラインポリシーには `Get-IAMRolePolicy` を使用し、アタッチされた管理ポリシーには `Get-IAMPolicyVersion` を使用します。**  

```
$results = Get-IamRole -RoleName lambda_exec_role
$results | Format-List
```
**出力:**  

```
Arn                      : arn:aws:iam::123456789012:role/lambda_exec_role
AssumeRolePolicyDocument : %7B%22Version%22%3A%222012-10-17%22%2C%22Statement%22%3A%5B%7B%22Sid%22
                           %3A%22%22%2C%22Effect%22%3A%22Allow%22%2C%22Principal%22%3A%7B%22Service
                           %22%3A%22lambda.amazonaws.com%22%7D%2C%22Action%22%3A%22sts%3AAssumeRole
                           %22%7D%5D%7D
CreateDate               : 4/2/2015 9:16:11 AM
Path                     : /
RoleId                   : 2YBIKAIBHNKB4EXAMPLE1
RoleName                 : lambda_exec_role
```

```
$policy = [System.Web.HttpUtility]::UrlDecode($results.AssumeRolePolicyDocument)
$policy
```
**出力:**  

```
{"Version":"2012-10-17",		 	 	 "Statement":[{"Sid":"","Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMRoleList`
<a name="iam_ListRoles_powershell_5_topic"></a>

次のコード例は、`Get-IAMRoleList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウント内のすべての IAM ロールのリストを取得します。**  

```
Get-IAMRoleList
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListRoles](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMRolePolicy`
<a name="iam_GetRolePolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ロール `lamda_exec_role` に埋め込まれている `oneClick_lambda_exec_role_policy` という名前のポリシーのアクセス許可ポリシードキュメントを返します。結果のポリシードキュメントは URL エンコードされます。この例では、`UrlDecode` .NET メソッドを使用してデコードされています。**  

```
$results = Get-IAMRolePolicy -RoleName lambda_exec_role -PolicyName oneClick_lambda_exec_role_policy
$results
```
**出力:**  

```
PolicyDocument                                            PolicyName                           UserName
--------------                                            ----------                           --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    oneClick_lambda_exec_role_policy     lambda_exec_role
```

```
[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
```
**出力:**  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:*"
      ],
      "Resource": "arn:aws:logs:us-east-1:555555555555:log-group:/aws/lambda/aws-example-function:*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "s3:GetObject",
        "s3:PutObject"
      ],
      "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/*"
      ]
    }
  ]
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMRolePolicyList`
<a name="iam_ListRolePolicies_powershell_5_topic"></a>

次のコード例は、`Get-IAMRolePolicyList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ロール `lamda_exec_role` に埋め込まれているインラインポリシーの名前のリストを返します。インラインポリシーの詳細を表示するには、`Get-IAMRolePolicy` コマンドを使用します。**  

```
Get-IAMRolePolicyList -RoleName lambda_exec_role
```
**出力:**  

```
oneClick_lambda_exec_role_policy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListRolePolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMRoleTagList`
<a name="iam_ListRoleTags_powershell_5_topic"></a>

次のコード例は、`Get-IAMRoleTagList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ロールに関連付けられているタグを取得します。**  

```
Get-IAMRoleTagList -RoleName MyRoleName
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListRoleTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMSAMLProvider`
<a name="iam_GetSamlProvider_powershell_5_topic"></a>

次のコード例は、`Get-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARM が arn:aws:iam::123456789012:saml-provider/SAMLADFS である SAML 2.0 プロバイダーに関する詳細を取得します。レスポンスには、SAML プロバイダーエンティティを作成するために ID AWS プロバイダーから取得したメタデータドキュメントと、作成日と有効期限が含まれます。**  

```
Get-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS
```
**出力:**  

```
CreateDate                 SAMLMetadataDocument                                          ValidUntil
----------                 --------------------                                          ----------
12/23/2014 12:16:55 PM    <EntityDescriptor ID="_12345678-1234-5678-9012-example1...    12/23/2114 12:16:54 PM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMSAMLProviderList`
<a name="iam_ListSAMLProviders_powershell_5_topic"></a>

次のコード例は、`Get-IAMSAMLProviderList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントで作成された SAML 2.0 プロバイダーのリストを取得します。これは、各 SAML プロバイダーの ARN、作成日、有効期限を返します。**  

```
Get-IAMSAMLProviderList
```
**出力:**  

```
Arn                                                 CreateDate                      ValidUntil
---                                                 ----------                      ----------
arn:aws:iam::123456789012:saml-provider/SAMLADFS    12/23/2014 12:16:55 PM          12/23/2114 12:16:54 PM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListSAMLProviders](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMServerCertificate`
<a name="iam_GetServerCertificate_powershell_5_topic"></a>

次のコード例は、`Get-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`MyServerCertificate` という名前のサーバー証明書に関する詳細を取得します。証明書の詳細は、`CertificateBody` および `ServerCertificateMetadata` プロパティで確認できます。**  

```
$result = Get-IAMServerCertificate -ServerCertificateName MyServerCertificate
$result | format-list
```
**出力:**  

```
CertificateBody           : -----BEGIN CERTIFICATE-----
                            MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                            VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                            b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                            BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                            MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                            VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                            b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                            YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                            21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                            rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                            Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                            nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                            FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                            NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                            -----END CERTIFICATE-----
CertificateChain          : 
ServerCertificateMetadata : Amazon.IdentityManagement.Model.ServerCertificateMetadata
```

```
$result.ServerCertificateMetadata
```
**出力:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMServerCertificateList`
<a name="iam_ListServerCertificates_powershell_5_topic"></a>

次のコード例は、`Get-IAMServerCertificateList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントにアップロードされたサーバー証明書のリストを取得します。**  

```
Get-IAMServerCertificateList
```
**出力:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /Org1/Org2/
ServerCertificateId   : ASCAJIFEXAMPLE17HQZYW
ServerCertificateName : MyServerCertificate
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListServerCertificates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMServiceLastAccessedDetail`
<a name="iam_GetServiceLastAccessedDetails_powershell_5_topic"></a>

次のコード例は、`Get-IAMServiceLastAccessedDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リクエスト呼び出しに関連付けられた IAM エンティティ (ユーザー、グループ、ロール、またはポリシー) が最後にアクセスしたサービスの詳細が表示されます。**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
**出力:**  

```
f0b7a819-eab0-929b-dc26-ca598911cb9f
```

```
Get-IAMServiceLastAccessedDetail -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMServiceLastAccessedDetailWithEntity`
<a name="iam_GetServiceLastAccessedDetailsWithEntities_powershell_5_topic"></a>

次のコード例は、`Get-IAMServiceLastAccessedDetailWithEntity` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、それぞれの IAM エンティティによるリクエスト内のサービスの最終アクセスタイムスタンプを提供します。**  

```
$results = Get-IAMServiceLastAccessedDetailWithEntity -JobId f0b7a819-eab0-929b-dc26-ca598911cb9f -ServiceNamespace ec2
$results
```
**出力:**  

```
EntityDetailsList : {Amazon.IdentityManagement.Model.EntityDetails}
Error             : 
IsTruncated       : False
JobCompletionDate : 12/29/19 11:19:31 AM
JobCreationDate   : 12/29/19 11:19:31 AM
JobStatus         : COMPLETED
Marker            :
```

```
$results.EntityDetailsList
```
**出力:**  

```
EntityInfo                                 LastAuthenticated
----------                                 -----------------
Amazon.IdentityManagement.Model.EntityInfo 11/16/19 3:47:00 PM
```

```
$results.EntityInfo
```
**出力:**  

```
Arn  : arn:aws:iam::123456789012:user/TestUser
Id   : AIDA4NBK5CXF5TZHU1234
Name : TestUser
Path : /
Type : USER
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetServiceLastAccessedDetailsWithEntities](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMSigningCertificate`
<a name="iam_ListSigningCertificates_powershell_5_topic"></a>

次のコード例は、`Get-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前のユーザーに関連付けられている署名証明書に関する詳細を取得します。**  

```
Get-IAMSigningCertificate -UserName Bob
```
**出力:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListSigningCertificates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMUser`
<a name="iam_GetUser_powershell_5_topic"></a>

次のコード例は、`Get-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`David` という名前のユーザーに関する詳細を取得します。**  

```
Get-IAMUser -UserName David
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/David
CreateDate       : 12/10/2014 3:39:27 PM
PasswordLastUsed : 3/19/2015 8:44:04 AM
Path             : /
UserId           : Y4FKWQCXTA52QEXAMPLE1
UserName         : David
```
**例 2: この例では、現在サインインしている IAM ユーザーに関する詳細を取得します。**  

```
Get-IAMUser
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 10/16/2014 9:03:09 AM
PasswordLastUsed : 3/4/2015 12:12:33 PM
Path             : /
UserId           : 7K3GJEANSKZF2EXAMPLE2
UserName         : Bob
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMUserList`
<a name="iam_ListUsers_powershell_5_topic"></a>

次のコード例は、`Get-IAMUserList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の のユーザーのコレクションを取得します AWS アカウント。**  

```
Get-IAMUserList
```
**出力:**  

```
      Arn              : arn:aws:iam::123456789012:user/Administrator
      CreateDate       : 10/16/2014 9:03:09 AM
      PasswordLastUsed : 3/4/2015 12:12:33 PM
      Path             : /
      UserId           : 7K3GJEANSKZF2EXAMPLE1
      UserName         : Administrator
      
      Arn              : arn:aws:iam::123456789012:user/Bob
      CreateDate       : 4/6/2015 12:54:42 PM
      PasswordLastUsed : 1/1/0001 12:00:00 AM
      Path             : /
      UserId           : L3EWNONDOM3YUEXAMPLE2
      UserName         : bab
      
      Arn              : arn:aws:iam::123456789012:user/David
      CreateDate       : 12/10/2014 3:39:27 PM
      PasswordLastUsed : 3/19/2015 8:44:04 AM
      Path             : /
      UserId           : Y4FKWQCXTA52QEXAMPLE3
      UserName         : David
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListUsers](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMUserPolicy`
<a name="iam_GetUserPolicy_powershell_5_topic"></a>

次のコード例は、`Get-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`David` という名前の IAM ユーザーに埋め込まれている `Davids_IAM_Admin_Policy` という名前のインラインポリシーの詳細を取得します。ポリシードキュメントは URL エンコードされています。**  

```
$results = Get-IAMUserPolicy -PolicyName Davids_IAM_Admin_Policy -UserName David
$results
```
**出力:**  

```
PolicyDocument                                            PolicyName                    UserName
--------------                                            ----------                    --------
%7B%0A%20%20%22Version%22%3A%20%222012-10-17%22%2C%...    Davids_IAM_Admin_Policy       David

[System.Reflection.Assembly]::LoadWithPartialName("System.Web.HttpUtility")
[System.Web.HttpUtility]::UrlDecode($results.PolicyDocument)
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "iam:GetUser",
        "iam:ListUsers"
      ],
      "Resource": [
        "arn:aws:iam::111122223333:user/*"
      ]
    }
  ]
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMUserPolicyList`
<a name="iam_ListUserPolicies_powershell_5_topic"></a>

次のコード例は、`Get-IAMUserPolicyList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`David` という名前の IAM ユーザーに埋め込まれているインラインポリシーの名前のリストを取得します。**  

```
Get-IAMUserPolicyList -UserName David
```
**出力:**  

```
Davids_IAM_Admin_Policy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListUserPolicies](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMUserTagList`
<a name="iam_ListUserTags_powershell_5_topic"></a>

次のコード例は、`Get-IAMUserTagList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ユーザーに関連付けられているタグを取得します。**  

```
Get-IAMUserTagList -UserName joe
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListUserTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-IAMVirtualMFADevice`
<a name="iam_ListVirtualMfaDevices_powershell_5_topic"></a>

次のコード例は、`Get-IAMVirtualMFADevice` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS アカウントのユーザーに割り当てられた仮想 MFA デバイスのコレクションを取得します。それぞれの `User` プロパティは、デバイスが割り当てられている IAM ユーザーの詳細を含むオブジェクトです。**  

```
Get-IAMVirtualMFADevice -AssignmentStatus Assigned
```
**出力:**  

```
Base32StringSeed : 
EnableDate       : 4/13/2015 12:03:42 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/David
User             : Amazon.IdentityManagement.Model.User

Base32StringSeed : 
EnableDate       : 4/13/2015 12:06:41 PM
QRCodePNG        : 
SerialNumber     : arn:aws:iam::123456789012:mfa/root-account-mfa-device
User             : Amazon.IdentityManagement.Model.User
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListVirtualMfaDevices](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMAccessKey`
<a name="iam_CreateAccessKey_powershell_5_topic"></a>

次のコード例は、`New-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しいアクセスキーとシークレットアクセスキーのペアを作成し、それをユーザー `David` に割り当てます。`SecretAccessKey` を取得できるのはこのときだけなので、`AccessKeyId` と `SecretAccessKey` の値は必ずファイルに保存してください。後で取得することはできません。シークレットアクセスキーを紛失した場合は、新しいアクセスキーペアを作成する必要があります。**  

```
New-IAMAccessKey -UserName David
```
**出力:**  

```
AccessKeyId     : AKIAIOSFODNN7EXAMPLE
CreateDate      : 4/13/2015 1:00:42 PM
SecretAccessKey : wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
Status          : Active
UserName        : David
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMAccountAlias`
<a name="iam_CreateAccountAlias_powershell_5_topic"></a>

次のコード例は、`New-IAMAccountAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントのアカウントエイリアス AWS を に変更します`mycompanyaws`。ユーザーログオンページのアドレスが、https://mycompanyaws.signin.aws.amazon.com/console に変わります。エイリアスの代わりにアカウント ID 番号を使用する元の URL (https://<accountidnumber>.signin.aws.amazon.com/console) は引き続き機能します。ただし、以前に定義したエイリアスベースの URL は機能しなくなります。**  

```
New-IAMAccountAlias -AccountAlias mycompanyaws
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateAccountAlias](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMGroup`
<a name="iam_CreateGroup_powershell_5_topic"></a>

次のコード例は、`New-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Developers` という名前の新しい IAM グループを作成します。**  

```
New-IAMGroup -GroupName Developers
```
**出力:**  

```
Arn        : arn:aws:iam::123456789012:group/Developers
CreateDate : 4/14/2015 11:21:31 AM
GroupId    : QNEJ5PM4NFSQCEXAMPLE1
GroupName  : Developers
Path       : /
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMInstanceProfile`
<a name="iam_CreateInstanceProfile_powershell_5_topic"></a>

次のコード例は、`New-IAMInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`ProfileForDevEC2Instance` という名前の新しい IAM インスタンスプロファイルを作成します。`Add-IAMRoleToInstanceProfile` コマンドを個別に実行して、インスタンスにアクセス許可を与える既存の IAM ロールにインスタンスプロファイルを関連付ける必要があります。最後に、EC2 インスタンスを起動する際に、インスタンスプロファイルを EC2 インスタンスにアタッチします。そのためには、`New-EC2Instance` コマンドレットを `InstanceProfile_Arn` または `InstanceProfile_Name` パラメータと共に使用します。**  

```
New-IAMInstanceProfile -InstanceProfileName ProfileForDevEC2Instance
```
**出力:**  

```
Arn                 : arn:aws:iam::123456789012:instance-profile/ProfileForDevEC2Instance
CreateDate          : 4/14/2015 11:31:39 AM
InstanceProfileId   : DYMFXL556EY46EXAMPLE1
InstanceProfileName : ProfileForDevEC2Instance
Path                : /
Roles               : {}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMLoginProfile`
<a name="iam_CreateLoginProfile_powershell_5_topic"></a>

次のコード例は、`New-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Bob という名前の IAM ユーザーの (一時的な) パスワードを作成し、次回 `Bob` がサインインしたときに、ユーザーにパスワードを変更するように要求するフラグを設定しています。**  

```
New-IAMLoginProfile -UserName Bob -Password P@ssw0rd -PasswordResetRequired $true
```
**出力:**  

```
CreateDate                    PasswordResetRequired                UserName
----------                    ---------------------                --------
4/14/2015 12:26:30 PM         True                                 Bob
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMOpenIDConnectProvider`
<a name="iam_CreateOpenIdConnectProvider_powershell_5_topic"></a>

次のコード例は、`New-IAMOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、URL `https://example.oidcprovider.com` とクライアント ID `my-testapp-1` にある OIDC 互換プロバイダーサービスに関連付けられた IAM OIDC プロバイダーを作成します。OIDC プロバイダーがサムプリントを提供します。サムプリントを認証するには、http://docs.aws.amazon.com/IAM/latest/UserGuide/identity-providers-oidc-obtain-thumbprint.html にある手順に従ってください。**  

```
New-IAMOpenIDConnectProvider -Url https://example.oidcprovider.com -ClientIDList my-testapp-1 -ThumbprintList 990F419EXAMPLEECF12DDEDA5EXAMPLE52F20D9E
```
**出力:**  

```
arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMPolicy`
<a name="iam_CreatePolicy_powershell_5_topic"></a>

次のコード例は、`New-IAMPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 という名前の現在の AWS アカウントに新しい IAM `MySamplePolicy` ポリシーを作成します。 ファイルはポリシーコンテンツ`MySamplePolicy.json`を提供します。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。**  

```
New-IAMPolicy -PolicyName MySamplePolicy -PolicyDocument (Get-Content -Raw MySamplePolicy.json)
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:policy/MySamplePolicy
AttachmentCount  : 0
CreateDate       : 4/14/2015 2:45:59 PM
DefaultVersionId : v1
Description      : 
IsAttachable     : True
Path             : /
PolicyId         : LD4KP6HVFE7WGEXAMPLE1
PolicyName       : MySamplePolicy
UpdateDate       : 4/14/2015 2:45:59 PM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreatePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMPolicyVersion`
<a name="iam_CreatePolicyVersion_powershell_5_topic"></a>

次のコード例は、`New-IAMPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MyPolicy` である IAM ポリシーの新しい「v2」バージョンを作成し、それをデフォルトのバージョンにします。`NewPolicyVersion.json` ファイルは、ポリシーの内容を提供します。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。**  

```
New-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -PolicyDocument (Get-content -Raw NewPolicyVersion.json) -SetAsDefault $true
```
**出力:**  

```
CreateDate                           Document                  IsDefaultVersion             VersionId
----------                           --------                  ----------------             ---------
4/15/2015 10:54:54 AM                                          True                         v2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreatePolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMRole`
<a name="iam_CreateRole_powershell_5_topic"></a>

次のコード例は、`New-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`MyNewRole` という名前の新しいロールを作成し、`NewRoleTrustPolicy.json` ファイルにあるポリシーをそのロールにアタッチします。JSON ポリシーファイルを正常に処理するには、`-Raw` switch パラメータを使用する必要があることに注意してください。出力に表示されるポリシードキュメントは、URL でエンコードされています。この例では、`UrlDecode` .NET メソッドを使用してデコードされています。**  

```
$results = New-IAMRole -AssumeRolePolicyDocument (Get-Content -raw NewRoleTrustPolicy.json) -RoleName MyNewRole
$results
```
**出力:**  

```
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"
    }
  ]
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMSAMLProvider`
<a name="iam_CreateSAMLProvider_powershell_5_topic"></a>

次のコード例は、`New-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM に新しい SAML プロバイダーエンティティを作成します。これは `MySAMLProvider` という名前で、SAML サービスプロバイダーのウェブサイトから個別にダウンロードされた `SAMLMetaData.xml` ファイルにある SAML メタデータドキュメントによって記述されます。**  

```
New-IAMSAMLProvider -Name MySAMLProvider -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
**出力:**  

```
arn:aws:iam::123456789012:saml-provider/MySAMLProvider
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateSAMLProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_powershell_5_topic"></a>

次のコード例は、`New-IAMServiceLinkedRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、自動スケーリングサービスのサービスにリンクされたロールを作成します。**  

```
New-IAMServiceLinkedRole -AWSServiceName autoscaling.amazonaws.com -CustomSuffix RoleNameEndsWithThis -Description "My service-linked role to support autoscaling"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMUser`
<a name="iam_CreateUser_powershell_5_topic"></a>

次のコード例は、`New-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前の IAM ユーザーを作成します。Bob が AWS コンソールにサインインする必要がある場合は、 コマンドを個別に実行`New-IAMLoginProfile`して、パスワードでサインインプロファイルを作成する必要があります。Bob が AWS PowerShell またはクロスプラットフォーム CLI コマンドを実行したり、 AWS API コールを実行したりする必要がある場合は、 `New-IAMAccessKey` コマンドを個別に実行してアクセスキーを作成する必要があります。**  

```
New-IAMUser -UserName Bob
```
**出力:**  

```
Arn              : arn:aws:iam::123456789012:user/Bob
CreateDate       : 4/22/2015 12:02:11 PM
PasswordLastUsed : 1/1/0001 12:00:00 AM
Path             : /
UserId           : AIDAJWGEFDMEMEXAMPLE1
UserName         : Bob
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-IAMVirtualMFADevice`
<a name="iam_CreateVirtualMfaDevice_powershell_5_topic"></a>

次のコード例は、`New-IAMVirtualMFADevice` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しい仮想 MFA デバイスを作成します。2 行目と 3 行目は、仮想 MFA ソフトウェアプログラムが (QR コードの代わりに) アカウントを作成するのに必要な `Base32StringSeed` 値を抽出します。この値でプログラムを設定したら、プログラムから 2 つの連続した認証コードを取得します。最後に、最後のコマンドを使用して仮想 MFA デバイスを IAM ユーザー `Bob` にリンクし、アカウントを 2 つの認証コードと同期します。**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$SR = New-Object System.IO.StreamReader($Device.Base32StringSeed)
$base32stringseed = $SR.ReadToEnd()
$base32stringseed   
CZWZMCQNW4DEXAMPLE3VOUGXJFZYSUW7EXAMPLECR4NJFD65GX2SLUDW2EXAMPLE
```
**出力:**  

```
-- Pause here to enter base-32 string seed code into virtual MFA program to register account. --

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
**例 2: この例では、新しい仮想 MFA デバイスを作成します。2 行目と 3 行目は、`QRCodePNG` 値を抽出してファイルに書き込みます。(Base32StringSeed 値を手動で入力する代わりに) このイメージを仮想 MFA ソフトウェアプログラムでスキャンして、アカウントを作成できます。仮想 MFA プログラムでアカウントを作成したら、2 つの連続した認証コードを取得して最後のコマンドに入力し、仮想 MFA デバイスを IAM ユーザー `Bob` にリンクして、アカウントを同期します。**  

```
$Device = New-IAMVirtualMFADevice -VirtualMFADeviceName BobsMFADevice
$BR = New-Object System.IO.BinaryReader($Device.QRCodePNG)
$BR.ReadBytes($BR.BaseStream.Length) | Set-Content -Encoding Byte -Path QRCode.png
```
**出力:**  

```
 -- Pause here to scan PNG with virtual MFA program to register account. -- 

Enable-IAMMFADevice -SerialNumber $Device.SerialNumber -UserName Bob -AuthenticationCode1 123456 -AuthenticationCode2 789012
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Publish-IAMServerCertificate`
<a name="iam_UploadServerCertificate_powershell_5_topic"></a>

次のコード例は、`Publish-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しいサーバー証明書を IAM アカウントにアップロードします。証明書本文、プライベートキー、および (オプションで) 証明書チェーンを含むファイルは、すべて PEM エンコードされる必要があります。パラメータにはファイル名ではなくファイルの実際の内容が必要であることに注意してください。ファイルの内容を正常に処理するには、`-Raw` スイッチパラメータを使用する必要があります。**  

```
Publish-IAMServerCertificate -ServerCertificateName MyTestCert -CertificateBody (Get-Content -Raw server.crt) -PrivateKey (Get-Content -Raw server.key)
```
**出力:**  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/MyTestCert
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /
ServerCertificateId   : ASCAJIEXAMPLE7J7HQZYW
ServerCertificateName : MyTestCert
UploadDate            : 4/21/2015 11:14:16 AM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UploadServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Publish-IAMSigningCertificate`
<a name="iam_UploadSigningCertificate_powershell_5_topic"></a>

次のコード例は、`Publish-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しい X.509 署名証明書をアップロードし、`Bob` という名前の IAM ユーザーに関連付けます。証明書の本文を含むファイルは PEM でエンコードされています。`CertificateBody` パラメータには、ファイル名ではなく証明書ファイルの実際の内容が必要です。ファイルを正常に処理するには、`-Raw` スイッチパラメータを使用する必要があります。**  

```
Publish-IAMSigningCertificate -UserName Bob -CertificateBody (Get-Content -Raw SampleSigningCert.pem)
```
**出力:**  

```
CertificateBody : -----BEGIN CERTIFICATE-----
                  MIICiTCCAfICCQD6m7oRw0uXOjANBgkqhkiG9w0BAQUFADCBiDELMAkGA1UEBhMC
                  VVMxCzAJBgNVBAgTAldBMRAwDgYDVQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6
                  b24xFDASBgNVBAsTC0lBTSBDb25zb2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAd
                  BgkqhkiG9w0BCQEWEG5vb25lQGFtYXpvbi5jb20wHhcNMTEwNDI1MjA0NTIxWhcN
                  MTIwNDI0MjA0NTIxWjCBiDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAldBMRAwDgYD
                  VQQHEwdTZWF0dGxlMQ8wDQYDVQQKEwZBbWF6b24xFDASBgNVBAsTC0lBTSBDb25z
                  b2xlMRIwEAYDVQQDEwlUZXN0Q2lsYWMxHzAdBgkqhkiG9w0BCQEWEG5vb25lQGFt
                  YXpvbi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMaK0dn+a4GmWIWJ
                  21uUSfwfEvySWtC2XADZ4nB+BLYgVIk60CpiwsZ3G93vUEIO3IyNoH/f0wYK8m9T
                  rDHudUZg3qX4waLG5M43q7Wgc/MbQITxOUSQv7c7ugFFDzQGBzZswY6786m86gpE
                  Ibb3OhjZnzcvQAaRHhdlQWIMm2nrAgMBAAEwDQYJKoZIhvcNAQEFBQADgYEAtCu4
                  nUhVVxYUntneD9+h8Mg9q6q+auNKyExzyLwaxlAoo7TJHidbtS4J5iNmZgXL0Fkb
                  FFBjvSfpJIlJ00zbhNYS5f6GuoEDmFJl0ZxBHjJnyp378OD8uTs7fLvjx79LjSTb
                  NYiytVbZPQUQ5Yaxu2jXnimvw3rrszlaEXAMPLE=
                  -----END CERTIFICATE-----
CertificateId   : Y3EK7RMEXAMPLESV33FCEXAMPLEHMJLU
Status          : Active
UploadDate      : 4/20/2015 1:26:01 PM
UserName        : Bob
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UploadSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-IAMGroupPolicy`
<a name="iam_AttachGroupPolicy_powershell_5_topic"></a>

次のコード例は、`Register-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`TesterPolicy` という名前のカスタマー管理ポリシーを IAM グループ `Testers` にアタッチします。そのグループのユーザーは、そのポリシーのデフォルトバージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**例 2: この例では、 という名前 AWS の管理ポリシーを IAM グループ `AdministratorAccess`にアタッチします`Admins`。そのグループのユーザーは、そのポリシーの最新バージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMGroupPolicy -GroupName Admins -PolicyArn arn:aws:iam::aws:policy/AdministratorAccess
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AttachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-IAMRolePolicy`
<a name="iam_AttachRolePolicy_powershell_5_topic"></a>

次のコード例は、`Register-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 という名前 AWS の管理ポリシーを IAM ロール `SecurityAudit`にアタッチします`CoSecurityAuditors`。そのロールを引き受けるユーザーは、そのポリシーの最新バージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMRolePolicy -RoleName CoSecurityAuditors -PolicyArn arn:aws:iam::aws:policy/SecurityAudit
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AttachRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-IAMUserPolicy`
<a name="iam_AttachUserPolicy_powershell_5_topic"></a>

次のコード例は、`Register-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 という名前 AWS の管理ポリシーを IAM ユーザー `AmazonCognitoPowerUser`にアタッチします`Bob`。ユーザーは、そのポリシーの最新バージョンで定義されているアクセス権限の影響をすぐに受けます。**  

```
Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AttachUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMAccessKey`
<a name="iam_DeleteAccessKey_powershell_5_topic"></a>

次のコード例は、`Remove-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 という名前のユーザー`AKIAIOSFODNN7EXAMPLE`からキー ID を持つ AWS アクセスキーペアを削除します`Bob`。**  

```
Remove-IAMAccessKey -AccessKeyId AKIAIOSFODNN7EXAMPLE -UserName Bob -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMAccountAlias`
<a name="iam_DeleteAccountAlias_powershell_5_topic"></a>

次のコード例は、`Remove-IAMAccountAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 からアカウントエイリアスを削除します AWS アカウント。https://mycompanyaws.signin.aws.amazon.com/console で、エイリアスを持つユーザーサインインページは機能しなくなりました。代わりに、https://<accountidnumber>.signin.aws.amazon.com/console の AWS アカウント ID 番号で元の URL を使用する必要があります。**  

```
Remove-IAMAccountAlias -AccountAlias mycompanyaws
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteAccountAlias](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMAccountPasswordPolicy`
<a name="iam_DeleteAccountPasswordPolicy_powershell_5_topic"></a>

次のコード例は、`Remove-IAMAccountPasswordPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 のパスワードポリシーを削除 AWS アカウント し、すべての値を元のデフォルトにリセットします。パスワードポリシーが現在存在しない場合、次のエラーメッセージが表示されます。The account policy with name PasswordPolicy cannot be found.**  

```
Remove-IAMAccountPasswordPolicy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMClientIDFromOpenIDConnectProvider`
<a name="iam_RemoveClientIdFromOpenIdConnectProvider_powershell_5_topic"></a>

次のコード例は、`Remove-IAMClientIDFromOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` である IAM OIDC プロバイダーに関連付けられているクライアント ID のリストから、クライアント ID `My-TestApp-3` を削除します。**  

```
Remove-IAMClientIDFromOpenIDConnectProvider -ClientID My-TestApp-3 -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemoveClientIdFromOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMGroup`
<a name="iam_DeleteGroup_powershell_5_topic"></a>

次のコード例は、`Remove-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`MyTestGroup` という名前の IAM グループを削除します。最初のコマンドはグループのメンバーであるすべての IAM ユーザーを削除し、2 番目のコマンドは IAM グループを削除します。どちらのコマンドも、確認を求めるプロンプトが表示されなくても機能します。**  

```
(Get-IAMGroup -GroupName MyTestGroup).Users | Remove-IAMUserFromGroup -GroupName MyTestGroup -Force
Remove-IAMGroup -GroupName MyTestGroup -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMGroupPolicy`
<a name="iam_DeleteGroupPolicy_powershell_5_topic"></a>

次のコード例は、`Remove-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`TesterPolicy` という名前のインラインポリシーを IAM グループ `Testers` から削除します。そのグループのユーザーは、そのポリシーで定義されているアクセス権限をすぐに失います。**  

```
Remove-IAMGroupPolicy -GroupName Testers -PolicyName TestPolicy
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMInstanceProfile`
<a name="iam_DeleteInstanceProfile_powershell_5_topic"></a>

次のコード例は、`Remove-IAMInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`MyAppInstanceProfile` という名前の EC2 インスタンスプロファイルを削除します。最初のコマンドはインスタンスプロファイルからすべてのロールをデタッチし、2 番目のコマンドはインスタンスプロファイルを削除します。**  

```
(Get-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile).Roles | Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyAppInstanceProfile
Remove-IAMInstanceProfile -InstanceProfileName MyAppInstanceProfile
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMLoginProfile`
<a name="iam_DeleteLoginProfile_powershell_5_topic"></a>

次のコード例は、`Remove-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前の IAM ユーザーからログインプロファイルを削除します。これにより、ユーザーは AWS コンソールにサインインできなくなります。ユーザーアカウントにアタッチされている可能性のある AWS アクセスキーを使用して、ユーザーが AWS CLI、PowerShell、または API コールを実行できないようにします。**  

```
Remove-IAMLoginProfile -UserName Bob
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMOpenIDConnectProvider`
<a name="iam_DeleteOpenIdConnectProvider_powershell_5_topic"></a>

次のコード例は、`Remove-IAMOpenIDConnectProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、プロバイダー `example.oidcprovider.com` に接続する IAM OIDC プロバイダーを削除します。ロールの信頼ポリシーの `Principal` 要素で、このプロバイダーを参照するロールをすべて更新または削除してください。**  

```
Remove-IAMOpenIDConnectProvider -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteOpenIdConnectProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMPolicy`
<a name="iam_DeletePolicy_powershell_5_topic"></a>

次のコード例は、`Remove-IAMPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーを削除します。ポリシーを削除する前に、`Remove-IAMPolicyVersion` を実行して、デフォルト以外のすべてのバージョンを削除する必要があります。また、すべての IAM ユーザー、グループ、またはロールからポリシーをデタッチする必要があります。**  

```
Remove-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
```
**例 2: この例では、最初にデフォルト以外のポリシーバージョンをすべて削除し、アタッチされているすべての IAM エンティティからデタッチして、最後にポリシー自体を削除することでポリシーを削除します。1 行目では、ポリシーオブジェクトを取得します。2 行目では、デフォルトバージョンとしてフラグが立てられていないすべてのポリシーバージョンをコレクションに取得し、コレクション内の各ポリシーを削除します。3 行目では、ポリシーがアタッチされているすべての IAM ユーザー、グループ、およびロールを取得します。4 行目から 6 行目では、アタッチされている各エンティティからポリシーをデタッチします。最後の行では、このコマンドを使用して管理ポリシーと残りのデフォルトバージョンを削除します。この例には、確認を求めるプロンプトを非表示にするための `-Force` switch パラメータが、このパラメータを必要とする行に含まれています。**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
$attached = Get-IAMEntitiesForPolicy -PolicyArn $pol.Arn
$attached.PolicyGroups | Unregister-IAMGroupPolicy -PolicyArn $pol.arn
$attached.PolicyRoles | Unregister-IAMRolePolicy -PolicyArn $pol.arn
$attached.PolicyUsers | Unregister-IAMUserPolicy -PolicyArn $pol.arn
Remove-IAMPolicy $pol.Arn -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeletePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMPolicyVersion`
<a name="iam_DeletePolicyVersion_powershell_5_topic"></a>

次のコード例は、`Remove-IAMPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`v2` と識別されたバージョンを ARN が `arn:aws:iam::123456789012:policy/MySamplePolicy` であるポリシーから削除します。**  

```
Remove-IAMPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy -VersionID v2
```
**例 2: この例では、最初にデフォルト以外のポリシーバージョンをすべて削除し、次にポリシー自体を削除することでポリシーを削除します。1 行目では、ポリシーオブジェクトを取得します。2 行目では、デフォルトとしてフラグが立てられていないすべてのポリシーバージョンをコレクションに取得し、このコマンドを使用してコレクション内の各ポリシーを削除します。最後の行では、ポリシー自体と残りのデフォルトバージョンを削除します。管理ポリシーを正常に削除するには、`Unregister-IAMUserPolicy`、`Unregister-IAMGroupPolicy`、`Unregister-IAMRolePolicy` コマンドを使用して、ユーザー、グループ、またはロールからポリシーをデタッチする必要があることに注意してください。`Remove-IAMPolicy` コマンドレットの例を参照してください。**  

```
$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy
Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force
Remove-IAMPolicy -PolicyArn $pol.Arn -force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeletePolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMRole`
<a name="iam_DeleteRole_powershell_5_topic"></a>

次のコード例は、`Remove-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の IAM アカウントから `MyNewRole` という名前のロールを削除します。ロールを削除する前に、まず `Unregister-IAMRolePolicy` コマンドを使用して、管理ポリシーをデタッチする必要があります。インラインポリシーは、ロールと共に削除されます。**  

```
Remove-IAMRole -RoleName MyNewRole
```
**例 2: この例では、`MyNewRole` という名前のロールから管理ポリシーをすべてデタッチして、ロールを削除します。最初の行では、ロールにアタッチされているすべての管理ポリシーをコレクションとして取得し、コレクション内の各ポリシーをロールからデタッチします。2 行目では、ロール自体を削除します。インラインポリシーは、ロールと共に削除されます。**  

```
Get-IAMAttachedRolePolicyList -RoleName MyNewRole | Unregister-IAMRolePolicy -RoleName MyNewRole
Remove-IAMRole -RoleName MyNewRole
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMRoleFromInstanceProfile`
<a name="iam_RemoveRoleFromInstanceProfile_powershell_5_topic"></a>

次のコード例は、`Remove-IAMRoleFromInstanceProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`MyNewRole` という名前の EC2 インスタンスプロファイルから `MyNewRole` という名前のロールを削除します。IAM コンソールで作成されたインスタンスプロファイルは、この例のように、常にロールと同じ名前になります。API または CLI で作成する場合、名前は異なる場合があります。**  

```
Remove-IAMRoleFromInstanceProfile -InstanceProfileName MyNewRole -RoleName MyNewRole -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemoveRoleFromInstanceProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMRolePermissionsBoundary`
<a name="iam_DeleteRolePermissionsBoundary_powershell_5_topic"></a>

次のコード例は、`Remove-IAMRolePermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は、IAM ロールにアタッチされたアクセス許可の境界を削除する方法を示しています。**  

```
Remove-IAMRolePermissionsBoundary -RoleName MyRoleName
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMRolePolicy`
<a name="iam_DeleteRolePolicy_powershell_5_topic"></a>

次のコード例は、`Remove-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ロール `S3BackupRole` に埋め込まれているインラインポリシー `S3AccessPolicy` を削除します。**  

```
Remove-IAMRolePolicy -PolicyName S3AccessPolicy -RoleName S3BackupRole
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMRoleTag`
<a name="iam_UntagRole_powershell_5_topic"></a>

次のコード例は、`Remove-IAMRoleTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、タグキーが「abac」の「MyRoleName」という名前のロールからタグを削除します。複数のタグを削除するには、カンマで区切ったタグキーリストを指定します。**  

```
Remove-IAMRoleTag -RoleName MyRoleName -TagKey "abac","xyzw"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UntagRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMSAMLProvider`
<a name="iam_DeleteSAMLProvider_powershell_5_topic"></a>

次のコード例は、`Remove-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider` である IAM SAML 2.0 プロバイダーを削除します。**  

```
Remove-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFSProvider
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteSAMLProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMServerCertificate`
<a name="iam_DeleteServerCertificate_powershell_5_topic"></a>

次のコード例は、`Remove-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`MyServerCert` という名前のサーバー証明書を削除します。**  

```
Remove-IAMServerCertificate -ServerCertificateName MyServerCert
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_powershell_5_topic"></a>

次のコード例は、`Remove-IAMServiceLinkedRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、サービスにリンクされたロールを削除しました。サービスがこのロールをまだ使用している場合、このコマンドは失敗することに注意してください。**  

```
Remove-IAMServiceLinkedRole -RoleName AWSServiceRoleForAutoScaling_RoleNameEndsWithThis
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteServiceLinkedRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMSigningCertificate`
<a name="iam_DeleteSigningCertificate_powershell_5_topic"></a>

次のコード例は、`Remove-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前の IAM ユーザーから ID `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` の付いた署名証明書を削除します。**  

```
Remove-IAMSigningCertificate -UserName Bob -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMUser`
<a name="iam_DeleteUser_powershell_5_topic"></a>

次のコード例は、`Remove-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前の IAM ユーザーを削除します。**  

```
Remove-IAMUser -UserName Bob
```
**例 2: この例では、`Theresa` という名前の IAM ユーザーと、最初に削除する必要がある要素をすべて削除します。**  

```
$name = "Theresa"

# find any groups and remove user from them
$groups = Get-IAMGroupForUser -UserName $name
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName $name -Force }

# find any inline policies and delete them
$inlinepols = Get-IAMUserPolicies -UserName $name
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName $name -Force}

# find any managed polices and detach them
$managedpols = Get-IAMAttachedUserPolicies -UserName $name
foreach ($pol in $managedpols) { Unregister-IAMUserPolicy -PolicyArn $pol.PolicyArn -UserName $name }

# find any signing certificates and delete them
$certs = Get-IAMSigningCertificate -UserName $name
foreach ($cert in $certs) { Remove-IAMSigningCertificate -CertificateId $cert.CertificateId -UserName $name -Force }

# find any access keys and delete them
$keys = Get-IAMAccessKey -UserName $name
foreach ($key in $keys) { Remove-IAMAccessKey -AccessKeyId $key.AccessKeyId -UserName $name -Force }

# delete the user's login profile, if one exists - note: need to use try/catch to suppress not found error
try { $prof = Get-IAMLoginProfile -UserName $name -ea 0 } catch { out-null }
if ($prof) { Remove-IAMLoginProfile -UserName $name -Force }

# find any MFA device, detach it, and if virtual, delete it.
$mfa = Get-IAMMFADevice -UserName $name
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}

# finally, remove the user
Remove-IAMUser -UserName $name -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMUserFromGroup`
<a name="iam_RemoveUserFromGroup_powershell_5_topic"></a>

次のコード例は、`Remove-IAMUserFromGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ユーザー `Bob` をグループ `Testers` から削除します。**  

```
Remove-IAMUserFromGroup -GroupName Testers -UserName Bob
```
**例 2: この例では、IAM ユーザー `Theresa` がメンバーとなっているグループをすべて検索し、それらのグループから `Theresa` を削除します。**  

```
$groups = Get-IAMGroupForUser -UserName Theresa 
foreach ($group in $groups) { Remove-IAMUserFromGroup -GroupName $group.GroupName -UserName Theresa -Force }
```
**例 3: この例は、IAM ユーザー `Bob` を `Testers` グループから削除する別の方法を示しています。**  

```
Get-IAMGroupForUser -UserName Bob | Remove-IAMUserFromGroup -UserName Bob -GroupName Testers -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemoveUserFromGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMUserPermissionsBoundary`
<a name="iam_DeleteUserPermissionsBoundary_powershell_5_topic"></a>

次のコード例は、`Remove-IAMUserPermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は、IAM ユーザーにアタッチされたアクセス許可の境界を削除する方法を示しています。**  

```
Remove-IAMUserPermissionsBoundary -UserName joe
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMUserPolicy`
<a name="iam_DeleteUserPolicy_powershell_5_topic"></a>

次のコード例は、`Remove-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前の IAM ユーザーに埋め込まれている `AccessToEC2Policy` という名前のインラインポリシーを削除します。**  

```
Remove-IAMUserPolicy -PolicyName AccessToEC2Policy -UserName Bob
```
**例 2: この例では、`Theresa` という名前の IAM ユーザーに埋め込まれているすべてのインラインポリシーを検索し、削除します。**  

```
$inlinepols = Get-IAMUserPolicies -UserName Theresa
foreach ($pol in $inlinepols) { Remove-IAMUserPolicy -PolicyName $pol -UserName Theresa -Force}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMUserTag`
<a name="iam_UntagUser_powershell_5_topic"></a>

次のコード例は、`Remove-IAMUserTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、タグキーが「abac」と「xyzw」の「joe」という名前のユーザーからタグを削除します。複数のタグを削除するには、カンマで区切ったタグキーリストを指定します。**  

```
Remove-IAMUserTag -UserName joe -TagKey "abac","xyzw"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UntagUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-IAMVirtualMFADevice`
<a name="iam_DeleteVirtualMfaDevice_powershell_5_topic"></a>

次のコード例は、`Remove-IAMVirtualMFADevice` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:mfa/bob` である IAM 仮想 MFA デバイスを削除します。**  

```
Remove-IAMVirtualMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/bob
```
**例 2: この例では、IAM ユーザー Theresa に MFA デバイスが割り当てられているかどうかを確認します。割り当てられているデバイスが見つかった場合、そのデバイスはその IAM ユーザーに対して無効になります。デバイスが仮想の場合は、そのデバイスも削除されます。**  

```
$mfa = Get-IAMMFADevice -UserName Theresa
if ($mfa) { 
    Disable-IAMMFADevice -SerialNumber $mfa.SerialNumber -UserName $name 
    if ($mfa.SerialNumber -like "arn:*") { Remove-IAMVirtualMFADevice -SerialNumber $mfa.SerialNumber }
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteVirtualMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Request-IAMCredentialReport`
<a name="iam_GenerateCredentialReport_powershell_5_topic"></a>

次のコード例は、`Request-IAMCredentialReport` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、4 時間ごとに実行できる新しいレポートの生成を要求しています。最新のレポートがまだ新しい場合、[状態] フィールドには `COMPLETE` と表示されます。`Get-IAMCredentialReport` を使用して、完成したレポートを表示します。**  

```
Request-IAMCredentialReport
```
**出力:**  

```
Description                                                    State
-----------                                                    -----
No report exists. Starting a new report generation task        STARTED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GenerateCredentialReport](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Request-IAMServiceLastAccessedDetail`
<a name="iam_GenerateServiceLastAccessedDetails_powershell_5_topic"></a>

次のコード例は、`Request-IAMServiceLastAccessedDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は GenerateServiceLastAccessedDetails API と同等のコマンドレットです。これにより、Get-IAMServiceLastAccessedDetail と Get-IAMServiceLastAccessedDetailWithEntity で使用できるジョブ ID が提供されます。**  

```
Request-IAMServiceLastAccessedDetail -Arn arn:aws:iam::123456789012:user/TestUser
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GenerateServiceLastAccessedDetails](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-IAMDefaultPolicyVersion`
<a name="iam_SetDefaultPolicyVersion_powershell_5_topic"></a>

次のコード例は、`Set-IAMDefaultPolicyVersion` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ARN が `arn:aws:iam::123456789012:policy/MyPolicy` であるポリシーの `v2` バージョンをデフォルトのアクティブなバージョンとして設定します。**  

```
Set-IAMDefaultPolicyVersion -PolicyArn arn:aws:iam::123456789012:policy/MyPolicy -VersionId v2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SetDefaultPolicyVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-IAMRolePermissionsBoundary`
<a name="iam_PutRolePermissionsBoundary_powershell_5_topic"></a>

次のコード例は、`Set-IAMRolePermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は、IAM ロールのアクセス許可の境界を設定する方法を示しています。 AWS 管理ポリシーまたはカスタムポリシーをアクセス許可の境界として設定できます。**  

```
Set-IAMRolePermissionsBoundary -RoleName MyRoleName -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutRolePermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-IAMUserPermissionsBoundary`
<a name="iam_PutUserPermissionsBoundary_powershell_5_topic"></a>

次のコード例は、`Set-IAMUserPermissionsBoundary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例は、ユーザーのアクセス許可の境界を設定する方法を示しています。 AWS 管理ポリシーまたはカスタムポリシーをアクセス許可の境界として設定できます。 **  

```
Set-IAMUserPermissionsBoundary -UserName joe -PermissionsBoundary arn:aws:iam::123456789012:policy/intern-boundary
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutUserPermissionsBoundary](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Sync-IAMMFADevice`
<a name="iam_ResyncMfaDevice_powershell_5_topic"></a>

次のコード例は、`Sync-IAMMFADevice` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ユーザー `Bob` に関連付けられていて、ARN が `arn:aws:iam::123456789012:mfa/bob` である MFA デバイスを、2 つの認証コードを提供した認証プログラムと同期します。**  

```
Sync-IAMMFADevice -SerialNumber arn:aws:iam::123456789012:mfa/theresa -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Bob
```
**例 2: この例では、IAM ユーザー `Theresa` に関連付けられている IAM MFA デバイスを、シリアル番号が `ABCD12345678` であり、2 つの認証コードを提供した物理デバイスと同期します。**  

```
Sync-IAMMFADevice -SerialNumber ABCD12345678 -AuthenticationCode1 123456 -AuthenticationCode2 987654 -UserName Theresa
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ResyncMfaDevice](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-IAMGroupPolicy`
<a name="iam_DetachGroupPolicy_powershell_5_topic"></a>

次のコード例は、`Unregister-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/TesterAccessPolicy` である管理グループポリシーを `Testers` という名前のグループからデタッチします。**  

```
Unregister-IAMGroupPolicy -GroupName Testers -PolicyArn arn:aws:iam::123456789012:policy/TesterAccessPolicy
```
**例 2: この例では、`Testers` という名前のグループにアタッチされているすべての管理ポリシーを検索し、グループからデタッチします。**  

```
Get-IAMAttachedGroupPolicies -GroupName Testers | Unregister-IAMGroupPolicy -Groupname Testers
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DetachGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-IAMRolePolicy`
<a name="iam_DetachRolePolicy_powershell_5_topic"></a>

次のコード例は、`Unregister-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy` である管理グループポリシーを `FedTesterRole` という名前のロールからデタッチします。**  

```
Unregister-IAMRolePolicy -RoleName FedTesterRole -PolicyArn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy
```
**例 2: この例では、`FedTesterRole` という名前のロールにアタッチされているすべての管理ポリシーを検索し、ロールからデタッチします。**  

```
Get-IAMAttachedRolePolicyList -RoleName FedTesterRole | Unregister-IAMRolePolicy -Rolename FedTesterRole
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DetachRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-IAMUserPolicy`
<a name="iam_DetachUserPolicy_powershell_5_topic"></a>

次のコード例は、`Unregister-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:policy/TesterPolicy` である管理ポリシーを `Bob` という名前の IAM ユーザーからデタッチします。**  

```
Unregister-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::123456789012:policy/TesterPolicy
```
**例 2: この例では、`Theresa` という名前の IAM ユーザーにアタッチされているすべての管理ポリシーを検索し、それらのポリシーをユーザーからデタッチします。**  

```
Get-IAMAttachedUserPolicyList -UserName Theresa | Unregister-IAMUserPolicy -Username Theresa
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DetachUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMAccessKey`
<a name="iam_UpdateAccessKey_powershell_5_topic"></a>

次のコード例は、`Update-IAMAccessKey` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前の IAM ユーザーのアクセスキー `AKIAIOSFODNN7EXAMPLE` のステータスを `Inactive` に変更します。**  

```
Update-IAMAccessKey -UserName Bob -AccessKeyId AKIAIOSFODNN7EXAMPLE -Status Inactive
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateAccessKey](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMAccountPasswordPolicy`
<a name="iam_UpdateAccountPasswordPolicy_powershell_5_topic"></a>

次のコード例は、`Update-IAMAccountPasswordPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した設定でアカウントのパスワードポリシーを更新します。コマンドに含まれていないパラメータは変更されないままにはならないことに注意してください。代わりに、デフォルト値にリセットされます。**  

```
Update-IAMAccountPasswordPolicy -AllowUsersToChangePasswords $true -HardExpiry $false -MaxPasswordAge 90 -MinimumPasswordLength 8 -PasswordReusePrevention 20 -RequireLowercaseCharacters $true -RequireNumbers $true -RequireSymbols $true -RequireUppercaseCharacters $true
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateAccountPasswordPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMAssumeRolePolicy`
<a name="iam_UpdateAssumeRolePolicy_powershell_5_topic"></a>

次のコード例は、`Update-IAMAssumeRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`ClientRole` という名前の IAM ロールを新しい信頼ポリシーで更新します。その内容は、ファイル `ClientRolePolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` スイッチパラメータを使用する必要があることに注意してください。**  

```
Update-IAMAssumeRolePolicy -RoleName ClientRole -PolicyDocument (Get-Content -raw ClientRolePolicy.json)
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateAssumeRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMGroup`
<a name="iam_UpdateGroup_powershell_5_topic"></a>

次のコード例は、`Update-IAMGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM グループ `Testers` の名前を `AppTesters` に変更します。**  

```
Update-IAMGroup -GroupName Testers -NewGroupName AppTesters
```
**例 2: この例では、IAM グループ `AppTesters` のパスを `/Org1/Org2/` に変更します。これにより、グループの ARN が `arn:aws:iam::123456789012:group/Org1/Org2/AppTesters` に変更されます。**  

```
Update-IAMGroup -GroupName AppTesters -NewPath /Org1/Org2/
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMLoginProfile`
<a name="iam_UpdateLoginProfile_powershell_5_topic"></a>

次のコード例は、`Update-IAMLoginProfile` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ユーザー `Bob` に新しい一時パスワードを設定し、ユーザーが次回サインインしたときにパスワードを変更するようユーザーに要求します。**  

```
Update-IAMLoginProfile -UserName Bob -Password "P@ssw0rd1234" -PasswordResetRequired $true
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateLoginProfile](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMOpenIDConnectProviderThumbprint`
<a name="iam_UpdateOpenIdConnectProviderThumbprint_powershell_5_topic"></a>

次のコード例は、`Update-IAMOpenIDConnectProviderThumbprint` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com` である OIDC プロバイダーの証明書サムプリントリストを更新して、新しいサムプリントを使用します。OIDC プロバイダーは、プロバイダーに関連付けられている証明書が変更されると、新しい値を共有します。**  

```
Update-IAMOpenIDConnectProviderThumbprint -OpenIDConnectProviderArn arn:aws:iam::123456789012:oidc-provider/example.oidcprovider.com -ThumbprintList 7359755EXAMPLEabc3060bce3EXAMPLEec4542a3
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateOpenIdConnectProviderThumbprint](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMRole`
<a name="iam_UpdateRole_powershell_5_topic"></a>

次のコード例は、`Update-IAMRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ロールの説明と、ロールのセッションをリクエストできる最大セッション期間の値 (秒単位) を更新します。**  

```
Update-IAMRole -RoleName MyRoleName -Description "My testing role" -MaxSessionDuration 43200
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMRoleDescription`
<a name="iam_UpdateRoleDescription_powershell_5_topic"></a>

次のコード例は、`Update-IAMRoleDescription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントの IAM ロールの説明を更新します。**  

```
Update-IAMRoleDescription -RoleName MyRoleName -Description "My testing role"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateRoleDescription](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMSAMLProvider`
<a name="iam_UpdateSamlProvider_powershell_5_topic"></a>

次のコード例は、`Update-IAMSAMLProvider` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ARN が `arn:aws:iam::123456789012:saml-provider/SAMLADFS` である IAM の SAML プロバイダーを、ファイル `SAMLMetaData.xml` の新しい SAML メタデータドキュメントで更新します。JSON ファイルの内容を正常に処理するには、`-Raw` スイッチパラメータを使用する必要があることに注意してください。**  

```
Update-IAMSAMLProvider -SAMLProviderArn arn:aws:iam::123456789012:saml-provider/SAMLADFS -SAMLMetadataDocument (Get-Content -Raw SAMLMetaData.xml)
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateSamlProvider](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMServerCertificate`
<a name="iam_UpdateServerCertificate_powershell_5_topic"></a>

次のコード例は、`Update-IAMServerCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`MyServerCertificate` という証明書の名前を `MyRenamedServerCertificate` に変更します。**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewServerCertificateName MyRenamedServerCertificate
```
**例 2: この例では、`MyServerCertificate` という証明書を /Org1/Org2/ というパスに移動します。これにより、リソースの ARN が `arn:aws:iam::123456789012:server-certificate/Org1/Org2/MyServerCertificate` に変更されます。**  

```
Update-IAMServerCertificate -ServerCertificateName MyServerCertificate -NewPath /Org1/Org2/
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMSigningCertificate`
<a name="iam_UpdateSigningCertificate_powershell_5_topic"></a>

次のコード例は、`Update-IAMSigningCertificate` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`Bob` という名前の IAM ユーザーに関連付けられ、証明書 ID が `Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU` である証明書を更新し、無効としてマークされるようにします。**  

```
Update-IAMSigningCertificate -CertificateId Y3EK7RMEXAMPLESV33FCREXAMPLEMJLU -UserName Bob -Status Inactive
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateSigningCertificate](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-IAMUser`
<a name="iam_UpdateUser_powershell_5_topic"></a>

次のコード例は、`Update-IAMUser` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、IAM ユーザー `Bob` の名前を `Robert` に変更します。**  

```
Update-IAMUser -UserName Bob -NewUserName Robert
```
**例 2: この例では、IAM ユーザー `Bob` のパスを `/Org1/Org2/` に変更します。これにより、ユーザーの ARN は実質的に `arn:aws:iam::123456789012:user/Org1/Org2/bob` に変更されます。**  

```
Update-IAMUser -UserName Bob -NewPath /Org1/Org2/
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateUser](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-IAMGroupPolicy`
<a name="iam_PutGroupPolicy_powershell_5_topic"></a>

次のコード例は、`Write-IAMGroupPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`AppTesterPolicy` という名前のインラインポリシーを作成し、IAM グループ `AppTesters` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容がファイル `apptesterpolicy.json` に送られます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMGroupPolicy -GroupName AppTesters -PolicyName AppTesterPolicy -PolicyDocument (Get-Content -Raw apptesterpolicy.json)
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutGroupPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-IAMRolePolicy`
<a name="iam_PutRolePolicy_powershell_5_topic"></a>

次のコード例は、`Write-IAMRolePolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`FedTesterRolePolicy` という名前のインラインポリシーを作成し、IAM ロール `FedTesterRole` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容は、ファイル `FedTesterPolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMRolePolicy -RoleName FedTesterRole -PolicyName FedTesterRolePolicy -PolicyDocument (Get-Content -Raw FedTesterPolicy.json)
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutRolePolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-IAMUserPolicy`
<a name="iam_PutUserPolicy_powershell_5_topic"></a>

次のコード例は、`Write-IAMUserPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`EC2AccessPolicy` という名前のインラインポリシーを作成し、IAM ユーザー `Bob` に埋め込みます。同じ名前のインラインポリシーが既に存在する場合、上書きされます。JSON ポリシーの内容は、ファイル `EC2AccessPolicy.json` から取得されます。JSON ファイルの内容を正常に処理するには、`-Raw` パラメータを使用する必要があることに注意してください。**  

```
Write-IAMUserPolicy -UserName Bob -PolicyName EC2AccessPolicy -PolicyDocument (Get-Content -Raw EC2AccessPolicy.json)
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutUserPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Kinesis の例
<a name="powershell_5_kinesis_code_examples"></a>

次のコード例は、Kinesis で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-KINRecord`
<a name="kinesis_GetRecords_powershell_5_topic"></a>

次のコード例は、`Get-KINRecord` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、一連の 1 つ以上のレコードからデータを返して抽出する方法を示しています。Get-KINRecord に供給されたイテレータは、この例で変数 \$1records にキャプチャされるレコードの開始位置を決定します。その後、\$1records コレクションにインデックスを付けることで、個々のレコードにアクセスできます。レコード内のデータが UTF-8 でエンコードされたテキストであると仮定すると、最終コマンドは、オブジェクト内の MemoryStream からデータを抽出してテキストとしてコンソールに返す方法を示します。**  

```
$records
$records = Get-KINRecord -ShardIterator "AAAAAAAAAAGIc....9VnbiRNaP"
```
**出力:**  

```
MillisBehindLatest NextShardIterator            Records
------------------ -----------------            -------
0                  AAAAAAAAAAERNIq...uDn11HuUs  {Key1, Key2}
```

```
$records.Records[0]
```
**出力:**  

```
ApproximateArrivalTimestamp Data                   PartitionKey SequenceNumber
--------------------------- ----                   ------------ --------------
3/7/2016 5:14:33 PM         System.IO.MemoryStream Key1         4955986459776...931586
```

```
[Text.Encoding]::UTF8.GetString($records.Records[0].Data.ToArray())
```
**出力:**  

```
test data from string
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetRecords](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-KINShardIterator`
<a name="kinesis_GetShardIterator_powershell_5_topic"></a>

次のコード例は、`Get-KINShardIterator` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたシャードと開始位置のシャードイテレータを返します。シャード識別子とシーケンス番号の詳細は、返されたストリームオブジェクトのシャードコレクションを参照することで、Get-KINStream コマンドレットの出力から取得できます。返されたイテレータを Get-KINRecord コマンドレットとともに使用して、シャード内のデータレコードをプルできます。**  

```
Get-KINShardIterator -StreamName "mystream" -ShardId "shardId-000000000000" -ShardIteratorType AT_SEQUENCE_NUMBER -StartingSequenceNumber "495598645..."
```
**出力:**  

```
AAAAAAAAAAGIc....9VnbiRNaP
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetShardIterator](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-KINStream`
<a name="kinesis_DescribeStream_powershell_5_topic"></a>

次のコード例は、`Get-KINStream` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたストリームの詳細を返します。**  

```
Get-KINStream -StreamName "mystream"
```
**出力:**  

```
HasMoreShards        : False
RetentionPeriodHours : 24
Shards               : {}
StreamARN            : arn:aws:kinesis:us-west-2:123456789012:stream/mystream
StreamName           : mystream
StreamStatus         : ACTIVE
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeStream](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-KINStream`
<a name="kinesis_CreateStream_powershell_5_topic"></a>

次のコード例は、`New-KINStream` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 新しいストリームを作成します。**  

```
New-KINStream -StreamName "mystream" -ShardCount 1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateStream](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-KINStream`
<a name="kinesis_DeleteStream_powershell_5_topic"></a>

次のコード例は、`Remove-KINStream` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたストリームを削除します。コマンドを実行する前に確認を求められます。確認メッセージを非表示にするには -Force スイッチを使用します。**  

```
Remove-KINStream -StreamName "mystream"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteStream](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-KINRecord`
<a name="kinesis_PutRecord_powershell_5_topic"></a>

次のコード例は、`Write-KINRecord` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: -Text パラメータに指定された文字列を含むレコードを書き込みます。**  

```
Write-KINRecord -Text "test data from string" -StreamName "mystream" -PartitionKey "Key1"
```
**例 2: 指定されたファイルに含まれるデータを含むレコードを書き込みます。ファイルはバイトのシーケンスとして扱われるため、テキストが含まれている場合は、このコマンドレットで使用する前に、必要なエンコードで記述する必要があります。**  

```
Write-KINRecord -FilePath "C:\TestData.txt" -StreamName "mystream" -PartitionKey "Key2"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutRecord](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Lambda の例
<a name="powershell_5_lambda_code_examples"></a>

次のコード例は、Lambda で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-LMResourceTag`
<a name="lambda_TagResource_powershell_5_topic"></a>

次のコード例は、`Add-LMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 3 つのタグ (Washington、Oregon、California) およびそれぞれに関連付けされた値を、ARN で識別される指定の関数に追加します。**  

```
Add-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -Tag @{ "Washington" = "Olympia"; "Oregon" = "Salem"; "California" = "Sacramento" }
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMAccountSetting`
<a name="lambda_GetAccountSettings_powershell_5_topic"></a>

次のコード例は、`Get-LMAccountSetting` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントの制限値と使用量を比較するための情報を表示します。**  

```
Get-LMAccountSetting | Select-Object @{Name="TotalCodeSizeLimit";Expression={$_.AccountLimit.TotalCodeSize}}, @{Name="TotalCodeSizeUsed";Expression={$_.AccountUsage.TotalCodeSize}}
```
**出力:**  

```
TotalCodeSizeLimit TotalCodeSizeUsed
------------------ -----------------
       80530636800          15078795
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAccountSettings](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMAlias`
<a name="lambda_GetAlias_powershell_5_topic"></a>

次のコード例は、`Get-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、特定の Lambda 関数エイリアスのルーティング設定の重点を取得します。**  

```
Get-LMAlias -FunctionName "MylambdaFunction123" -Name "newlabel1" -Select RoutingConfig
```
**出力:**  

```
AdditionalVersionWeights
------------------------
{[1, 0.6]}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAlias](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMFunctionConcurrency`
<a name="lambda_GetFunctionConcurrency_powershell_5_topic"></a>

次のコード例は、`Get-LMFunctionConcurrency` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数の予約済み同時実行数が取得されます**  

```
Get-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -Select *
```
**出力:**  

```
ReservedConcurrentExecutions
----------------------------
100
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMFunctionConfiguration`
<a name="lambda_GetFunctionConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-LMFunctionConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数のバージョン固有設定を返します。**  

```
Get-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Qualifier "PowershellAlias"
```
**出力:**  

```
CodeSha256                 : uWOW0R7z+f0VyLuUg7+/D08hkMFsq0SF4seuyUZJ/R8=
CodeSize                   : 1426
DeadLetterConfig           : Amazon.Lambda.Model.DeadLetterConfig
Description                : Verson 3 to test Aliases
Environment                : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn                : arn:aws:lambda:us-east-1:123456789012:function:MylambdaFunction123
                             :PowershellAlias
FunctionName               : MylambdaFunction123
Handler                    : lambda_function.launch_instance
KMSKeyArn                  : 
LastModified               : 2019-12-25T09:52:59.872+0000
LastUpdateStatus           : Successful
LastUpdateStatusReason     : 
LastUpdateStatusReasonCode : 
Layers                     : {}
MasterArn                  : 
MemorySize                 : 128
RevisionId                 : 5d7de38b-87f2-4260-8f8a-e87280e10c33
Role                       : arn:aws:iam::123456789012:role/service-role/lambda
Runtime                    : python3.8
State                      : Active
StateReason                : 
StateReasonCode            : 
Timeout                    : 600
TracingConfig              : Amazon.Lambda.Model.TracingConfigResponse
Version                    : 4
VpcConfig                  : Amazon.Lambda.Model.VpcConfigDetail
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetFunctionConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMFunctionList`
<a name="lambda_ListFunctions_powershell_5_topic"></a>

次のコード例は、`Get-LMFunctionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、コードサイズ順にすべての Lambda 関数を表示します**  

```
Get-LMFunctionList | Sort-Object -Property CodeSize | Select-Object FunctionName, RunTime, Timeout, CodeSize
```
**出力:**  

```
FunctionName                                                 Runtime   Timeout CodeSize
------------                                                 -------   ------- --------
test                                                         python2.7       3      243
MylambdaFunction123                                          python3.8     600      659
myfuncpython1                                                python3.8     303      675
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListFunctions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMPolicy`
<a name="lambda_GetPolicy_powershell_5_topic"></a>

次のコード例は、`Get-LMPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した Lambda 関数の関数ポリシーを表示します**  

```
Get-LMPolicy -FunctionName test -Select Policy
```
**出力:**  

```
{"Version":"2012-10-17",		 	 	 "Id":"default","Statement":[{"Sid":"xxxx","Effect":"Allow","Principal":{"Service":"sns.amazonaws.com"},"Action":"lambda:InvokeFunction","Resource":"arn:aws:lambda:us-east-1:123456789102:function:test"}]}
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[GetPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-LMProvisionedConcurrencyConfig`
<a name="lambda_GetProvisionedConcurrencyConfig_powershell_5_topic"></a>

次のコード例は、`Get-LMProvisionedConcurrencyConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数の指定されたエイリアスにプロビジョニングされた同時実行設定を取得します。**  

```
C:\>Get-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
**出力:**  

```
AllocatedProvisionedConcurrentExecutions : 0
AvailableProvisionedConcurrentExecutions : 0
LastModified                             : 2020-01-15T03:21:26+0000
RequestedProvisionedConcurrentExecutions : 70
Status                                   : IN_PROGRESS
StatusReason                             :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMProvisionedConcurrencyConfigList`
<a name="lambda_ListProvisionedConcurrencyConfigs_powershell_5_topic"></a>

次のコード例は、`Get-LMProvisionedConcurrencyConfigList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数にプロビジョニングされた同時実行設定のリストを取得します。**  

```
Get-LMProvisionedConcurrencyConfigList -FunctionName "MylambdaFunction123"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListProvisionedConcurrencyConfigs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMResourceTag`
<a name="lambda_ListTags_powershell_5_topic"></a>

次のコード例は、`Get-LMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定した関数に現在設定されているタグとその値を取得します。**  

```
Get-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
**出力:**  

```
Key        Value
---        -----
California Sacramento
Oregon     Salem
Washington Olympia
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-LMVersionsByFunction`
<a name="lambda_ListVersionsByFunction_powershell_5_topic"></a>

次のコード例は、`Get-LMVersionsByFunction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数の各バージョンのバージョン固有設定に関するリストを返します。**  

```
Get-LMVersionsByFunction -FunctionName "MylambdaFunction123"
```
**出力:**  

```
FunctionName        Runtime   MemorySize Timeout CodeSize LastModified                 RoleName
------------        -------   ---------- ------- -------- ------------                 --------
MylambdaFunction123 python3.8        128     600      659 2020-01-10T03:20:56.390+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:19:02.238+0000 lambda
MylambdaFunction123 python3.8        128       5     1426 2019-12-25T09:39:36.779+0000 lambda
MylambdaFunction123 python3.8        128     600     1426 2019-12-25T09:52:59.872+0000 lambda
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListVersionsByFunction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-LMAlias`
<a name="lambda_CreateAlias_powershell_5_topic"></a>

次のコード例は、`New-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたバージョンおよびルーティング設定の新しい Lambda エイリアスを作成し、受信する呼び出しリクエストの割合を指定します。**  

```
New-LMAlias -FunctionName "MylambdaFunction123" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6} -Description "Alias for version 4" -FunctionVersion 4 -Name "PowershellAlias"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateAlias](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Publish-LMFunction`
<a name="lambda_CreateFunction_powershell_5_topic"></a>

次のコード例は、`Publish-LMFunction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、 AWS Lambda で MyFunction という名前の新しい C\$1 (dotnetcore1.0 ランタイム) 関数を作成し、ローカルファイルシステムの zip ファイルから関数のコンパイルされたバイナリを提供します (相対パスまたは絶対パスを使用できます）。C\$1 Lambda 関数は、AssemblyName::Namespace.ClassName::MethodName の指定を使用して関数のハンドラーを指定します。ハンドラー仕様のアセンブリ名 (.dll サフィックスなし)、名前空間、クラス名、メソッド名の部分を適切に置き換える必要があります。新しい関数には、指定された値で「envvar1」および「envvar2」の環境変数が設定されます。**  

```
Publish-LMFunction -Description "My C# Lambda Function" `
        -FunctionName MyFunction `
        -ZipFilename .\MyFunctionBinaries.zip `
        -Handler "AssemblyName::Namespace.ClassName::MethodName" `
        -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" `
        -Runtime dotnetcore1.0 `
        -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
```
**出力:**  

```
CodeSha256       : /NgBMd...gq71I=
CodeSize         : 214784
DeadLetterConfig :
Description      : My C# Lambda Function
Environment      : Amazon.Lambda.Model.EnvironmentResponse
FunctionArn      : arn:aws:lambda:us-west-2:123456789012:function:ToUpper
FunctionName     : MyFunction
Handler          : AssemblyName::Namespace.ClassName::MethodName
KMSKeyArn        :
LastModified     : 2016-12-29T23:50:14.207+0000
MemorySize       : 128
Role             : arn:aws:iam::123456789012:role/LambdaFullExecRole
Runtime          : dotnetcore1.0
Timeout          : 3
Version          : $LATEST
VpcConfig        :
```
**例 2: この例は前の例と似ていますが、関数バイナリが最初に Amazon S3 バケット (目的の Lambda 関数と同じリージョンにある必要がある) にアップロードされ、結果の S3 オブジェクトが関数の作成時に参照される点が異なります。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key MyFunctionBinaries.zip -File .\MyFunctionBinaries.zip    
Publish-LMFunction -Description "My C# Lambda Function" `
        -FunctionName MyFunction `
        -BucketName amzn-s3-demo-bucket `
        -Key MyFunctionBinaries.zip `
        -Handler "AssemblyName::Namespace.ClassName::MethodName" `
        -Role "arn:aws:iam::123456789012:role/LambdaFullExecRole" `
        -Runtime dotnetcore1.0 `
        -Environment_Variable @{ "envvar1"="value";"envvar2"="value" }
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateFunction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Publish-LMVersion`
<a name="lambda_PublishVersion_powershell_5_topic"></a>

次のコード例は、`Publish-LMVersion` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数コードの既存のスナップショットのバージョンを作成します**  

```
Publish-LMVersion -FunctionName "MylambdaFunction123" -Description "Publishing Existing Snapshot of function code as a  new version through Powershell"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PublishVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-LMAlias`
<a name="lambda_DeleteAlias_powershell_5_topic"></a>

次のコード例は、`Remove-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、コマンドに記述された Lambda 関数のエイリアスを削除します。**  

```
Remove-LMAlias -FunctionName "MylambdaFunction123" -Name "NewAlias"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteAlias](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-LMFunction`
<a name="lambda_DeleteFunction_powershell_5_topic"></a>

次のコード例は、`Remove-LMFunction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数の特定のバージョンを削除します。**  

```
Remove-LMFunction -FunctionName "MylambdaFunction123" -Qualifier '3'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteFunction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-LMFunctionConcurrency`
<a name="lambda_DeleteFunctionConcurrency_powershell_5_topic"></a>

次のコード例は、`Remove-LMFunctionConcurrency` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数の関数同時実行数を削除します。**  

```
Remove-LMFunctionConcurrency -FunctionName "MylambdaFunction123"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-LMPermission`
<a name="lambda_RemovePermission_powershell_5_topic"></a>

次のコード例は、`Remove-LMPermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Lambda 関数の指定された StatementId の関数ポリシーを削除します。**  

```
$policy =  Get-LMPolicy -FunctionName "MylambdaFunction123" -Select Policy | ConvertFrom-Json| Select-Object -ExpandProperty Statement
Remove-LMPermission -FunctionName "MylambdaFunction123" -StatementId $policy[0].Sid
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemovePermission](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-LMProvisionedConcurrencyConfig`
<a name="lambda_DeleteProvisionedConcurrencyConfig_powershell_5_topic"></a>

次のコード例は、`Remove-LMProvisionedConcurrencyConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、特定のエイリアスのプロビジョニングされた同時実行設定を削除します。**  

```
Remove-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -Qualifier "NewAlias1"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-LMResourceTag`
<a name="lambda_UntagResource_powershell_5_topic"></a>

次のコード例は、`Remove-LMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 提供されたタグを関数から削除します。-Force スイッチが指定されていない限り、cmdlet は続行する前に確認を求めます。タグを削除するため、サービスが 1 回呼び出されます。**  

```
Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction" -TagKey "Washington","Oregon","California"
```
**例 2: 提供されたタグを関数から削除します。-Force スイッチが指定されていない限り、cmdlet は続行する前に確認を求めます。提供されたタグにつき、サービスに 1 回呼び出しが行われます。**  

```
"Washington","Oregon","California" | Remove-LMResourceTag -Resource "arn:aws:lambda:us-west-2:123456789012:function:MyFunction"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UntagResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-LMAlias`
<a name="lambda_UpdateAlias_powershell_5_topic"></a>

次のコード例は、`Update-LMAlias` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、既存の Lambda 関数エイリアスの設定を更新します。RoutingConfiguration の値を更新し、トラフィックの 60% (0.6) をバージョン 1 に変換します。**  

```
Update-LMAlias -FunctionName "MylambdaFunction123" -Description " Alias for version 2" -FunctionVersion 2 -Name "newlabel1" -RoutingConfig_AdditionalVersionWeight @{Name="1";Value="0.6}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateAlias](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-LMFunctionCode`
<a name="lambda_UpdateFunctionCode_powershell_5_topic"></a>

次のコード例は、`Update-LMFunctionCode` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「MyFunction」という名前の関数を、指定された zip ファイルに含まれる新しいコンテンツで更新します。C\$1 .NET Core Lambda 関数には、zip ファイルはコンパイルされたアセンブリが含まれている必要があります。**  

```
Update-LMFunctionCode -FunctionName MyFunction -ZipFilename .\UpdatedCode.zip
```
**例 2: この例は前の例と似ていますが、更新されたコードを含む Amazon S3 オブジェクトを使用して関数を更新します。**  

```
Update-LMFunctionCode -FunctionName MyFunction -BucketName amzn-s3-demo-bucket -Key UpdatedCode.zip
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateFunctionCode](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-LMFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_powershell_5_topic"></a>

次のコード例は、`Update-LMFunctionConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、既存の Lambda 関数の設定を更新します**  

```
Update-LMFunctionConfiguration -FunctionName "MylambdaFunction123" -Handler "lambda_function.launch_instance" -Timeout 600 -Environment_Variable @{ "envvar1"="value";"envvar2"="value" } -Role arn:aws:iam::123456789101:role/service-role/lambda -DeadLetterConfig_TargetArn arn:aws:sns:us-east-1: 123456789101:MyfirstTopic
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-LMFunctionConcurrency`
<a name="lambda_PutFunctionConcurrency_powershell_5_topic"></a>

次のコード例は、`Write-LMFunctionConcurrency` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、関数全体の同時実行設定を適用します。**  

```
Write-LMFunctionConcurrency -FunctionName "MylambdaFunction123" -ReservedConcurrentExecution 100
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[PutFunctionConcurrency](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-LMProvisionedConcurrencyConfig`
<a name="lambda_PutProvisionedConcurrencyConfig_powershell_5_topic"></a>

次のコード例は、`Write-LMProvisionedConcurrencyConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、プロビジョニングされた同時実行設定を関数のエイリアスに追加します。**  

```
Write-LMProvisionedConcurrencyConfig -FunctionName "MylambdaFunction123" -ProvisionedConcurrentExecution 20 -Qualifier "NewAlias1"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutProvisionedConcurrencyConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon ML の例
<a name="powershell_5_machine-learning_code_examples"></a>

次のコード例は、Amazon ML で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-MLBatchPrediction`
<a name="machine-learning_GetBatchPrediction_powershell_5_topic"></a>

次のコード例は、`Get-MLBatchPrediction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: id ID を含むバッチ予測の詳細なメタデータを返します。**  

```
Get-MLBatchPrediction -BatchPredictionId ID
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBatchPrediction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLBatchPredictionList`
<a name="machine-learning_DescribeBatchPredictions_powershell_5_topic"></a>

次のコード例は、`Get-MLBatchPredictionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: リクエストで指定された検索条件に一致するすべての BatchPredictions および関連するデータレコードのリストを返します。**  

```
Get-MLBatchPredictionList
```
**例 2: ステータスが COMPLETED であるすべての BatchPredictions のリストを返します。**  

```
Get-MLBatchPredictionList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeBatchPredictions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLDataSource`
<a name="machine-learning_GetDataSource_powershell_5_topic"></a>

次のコード例は、`Get-MLDataSource` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ID を含む DataSource のメタデータ、ステータス、データファイル情報を返します。**  

```
Get-MLDataSource -DataSourceId ID
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetDataSource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLDataSourceList`
<a name="machine-learning_DescribeDataSources_powershell_5_topic"></a>

次のコード例は、`Get-MLDataSourceList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべての DataSourcesとそれに関連するデータレコードのリストを返します。**  

```
Get-MLDataSourceList
```
**例 2: ステータスが COMPLETED であるすべての DataSources のリストを返します。**  

```
Get-MLDataDourceList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeDataSources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLEvaluation`
<a name="machine-learning_GetEvaluation_powershell_5_topic"></a>

次のコード例は、`Get-MLEvaluation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ID を含む Evaluation のメタデータとステータスを返します。**  

```
Get-MLEvaluation -EvaluationId ID
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetEvaluation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLEvaluationList`
<a name="machine-learning_DescribeEvaluations_powershell_5_topic"></a>

次のコード例は、`Get-MLEvaluationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべての Evaluation リソースのリストを返します**  

```
Get-MLEvaluationList
```
**例 2: ステータスが COMPLETED であるすべての Evaulation のリストを返します。**  

```
Get-MLEvaluationList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeEvaluations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLModel`
<a name="machine-learning_GetMLModel_powershell_5_topic"></a>

次のコード例は、`Get-MLModel` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ID を含む MLModel の詳細メタデータ、ステータス、スキーマ、データファイル情報を返します。**  

```
Get-MLModel -ModelId ID
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetMLModel](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLModelList`
<a name="machine-learning_DescribeMLModels_powershell_5_topic"></a>

次のコード例は、`Get-MLModelList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべての Model とそれに関連するデータレコードのリストを返します。 **  

```
Get-MLModelList
```
**例 2: ステータスが COMPLETED であるすべての Model のリストを返します。**  

```
Get-MLModelList -FilterVariable Status -EQ COMPLETED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeMLModels](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-MLPrediction`
<a name="machine-learning_Predict_powershell_5_topic"></a>

次のコード例は、`Get-MLPrediction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ID を含むモデルのリアルタイム予測エンドポイント URL にレコードを送信します。**  

```
Get-MLPrediction -ModelId ID -PredictEndpoint URL -Record @{"A" = "B"; "C" = "D";}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[Predict](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-MLBatchPrediction`
<a name="machine-learning_CreateBatchPrediction_powershell_5_topic"></a>

次のコード例は、`New-MLBatchPrediction` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ID を含むモデルの新しいバッチ予測リクエストを作成し、指定 S3 の場所に出力を配置します。**  

```
New-MLBatchPrediction -ModelId ID -Name NAME -OutputURI s3://...
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateBatchPrediction](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-MLDataSourceFromS3`
<a name="machine-learning_CreateDataSourceFromS3_powershell_5_topic"></a>

次のコード例は、`New-MLDataSourceFromS3` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 名前が NAME、スキーマが SCHEMA である S3 の場所のデータを使用してデータソースを作成します。**  

```
New-MLDataSourceFromS3 -Name NAME -ComputeStatistics $true -DataSpec_DataLocationS3 "s3://BUCKET/KEY" -DataSchema SCHEMA
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateDataSourceFromS3](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-MLEvaluation`
<a name="machine-learning_CreateEvaluation_powershell_5_topic"></a>

次のコード例は、`New-MLEvaluation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定のデータソース ID とモデル ID の評価を作成します**  

```
New-MLEvaluation -Name NAME -DataSourceId DSID -ModelId MID
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateEvaluation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-MLModel`
<a name="machine-learning_CreateMLModel_powershell_5_topic"></a>

次のコード例は、`New-MLModel` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: トレーニングデータを使用して新しいモデルを作成します。**  

```
New-MLModel -Name NAME -ModelType BINARY -Parameter @{...} -TrainingDataSourceId ID
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateMLModel](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-MLRealtimeEndpoint`
<a name="machine-learning_CreateRealtimeEndpoint_powershell_5_topic"></a>

次のコード例は、`New-MLRealtimeEndpoint` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定モデル ID の新しいリアルタイム予測エンドポイントを作成します。**  

```
New-MLRealtimeEndpoint -ModelId ID
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateRealtimeEndpoint](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Macie の例
<a name="powershell_5_macie2_code_examples"></a>

次のコード例は、Macie で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-MAC2FindingList`
<a name="macie2_ListFindings_powershell_5_topic"></a>

次のコード例は、`Get-MAC2FindingList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「CREDIT\$1CARD\$1NUMBER」または「US\$1SOCIAL\$1SECURITY\$1NUMBER」タイプの機密データ検出を含む検出結果の FindingIds のリストを返します。**  

```
$criterionAddProperties = New-Object Amazon.Macie2.Model.CriterionAdditionalProperties

$criterionAddProperties.Eq = @(
"CREDIT_CARD_NUMBER"
"US_SOCIAL_SECURITY_NUMBER"
)

$FindingCriterion = @{
'classificationDetails.result.sensitiveData.detections.type' = [Amazon.Macie2.Model.CriterionAdditionalProperties]$criterionAddProperties
}

Get-MAC2FindingList -FindingCriteria_Criterion $FindingCriterion -MaxResult 5
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListFindings](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# AWS の料金表 Tools for PowerShell V5 を使用した の例
<a name="powershell_5_pricing_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS の料金表。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-PLSAttributeValue`
<a name="pricing_GetAttributeValues_powershell_5_topic"></a>

次のコード例は、`Get-PLSAttributeValue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: us-east-1 リージョンの Amazon EC2 の属性「volumeType」の値を返します。**  

```
Get-PLSAttributeValue -ServiceCode AmazonEC2 -AttributeName "volumeType" -region us-east-1
```
**出力:**  

```
Value
-----
Cold HDD
General Purpose
Magnetic
Provisioned IOPS
Throughput Optimized HDD
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAttributeValues](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-PLSProduct`
<a name="pricing_GetProducts_powershell_5_topic"></a>

次のコード例は、`Get-PLSProduct` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: Amazon EC2 のすべての製品の詳細を返します。**  

```
Get-PLSProduct -ServiceCode AmazonEC2 -Region us-east-1
```
**出力:**  

```
{"product":{"productFamily":"Compute Instance","attributes":{"enhancedNetworkingSupported":"Yes","memory":"30.5 GiB","dedicatedEbsThroughput":"800 Mbps","vcpu":"4","locationType":"AWS Region","storage":"EBS only","instanceFamily":"Memory optimized","operatingSystem":"SUSE","physicalProcessor":"Intel Xeon E5-2686 v4 (Broadwell)","clockSpeed":"2.3 GHz","ecu":"Variable","networkPerformance":"Up to 10 Gigabit","servicename":"Amazon Elastic Compute Cloud","instanceType":"r4.xlarge","tenancy":"Shared","usagetype":"USW2-BoxUsage:r4.xlarge","normalizationSizeFactor":"8","processorFeatures":"Intel AVX, Intel AVX2, Intel Turbo","servicecode":"AmazonEC2","licenseModel":"No License required","currentGeneration":"Yes","preInstalledSw":"NA","location":"US West (Oregon)","processorArchitecture":"64-bit","operation":"RunInstances:000g"},...
```
**例 2: us-east-1 リージョン内の Amazon EC2 のデータのうち、SSD ベースの「General Purpose」のボリュームタイプでフィルタリングされたデータを返します。**  

```
Get-PLSProduct -ServiceCode AmazonEC2 -Filter @{Type="TERM_MATCH";Field="volumeType";Value="General Purpose"},@{Type="TERM_MATCH";Field="storageMedia";Value="SSD-backed"} -Region us-east-1
```
**出力:**  

```
{"product":{"productFamily":"Storage","attributes":{"storageMedia":"SSD-backed","maxThroughputvolume":"160 MB/sec","volumeType":"General Purpose","maxIopsvolume":"10000",...
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetProducts](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-PLSService`
<a name="pricing_DescribeServices_powershell_5_topic"></a>

次のコード例は、`Get-PLSService` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: us-east-1 リージョンで使用可能なすべてのサービスコードのメタデータを返します。**  

```
Get-PLSService -Region us-east-1
```
**出力:**  

```
AttributeNames                                                  ServiceCode
--------------                                                  -----------
{productFamily, servicecode, groupDescription, termType...}     AWSBudgets
{productFamily, servicecode, termType, usagetype...}            AWSCloudTrail
{productFamily, servicecode, termType, usagetype...}            AWSCodeCommit
{productFamily, servicecode, termType, usagetype...}            AWSCodeDeploy
{productFamily, servicecode, termType, usagetype...}            AWSCodePipeline
{productFamily, servicecode, termType, usagetype...}            AWSConfig
...
```
**例 2: us-east-1 リージョンの Amazon EC2 サービスのメタデータを返します。**  

```
Get-PLSService -ServiceCode AmazonEC2 -Region us-east-1
```
**出力:**  

```
AttributeNames                                                         ServiceCode
--------------                                                         -----------
{volumeType, maxIopsvolume, instanceCapacity10xlarge, locationType...} AmazonEC2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Resource Groups の例
<a name="powershell_5_resource-groups_code_examples"></a>

次のコード例は、Resource Groups で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-RGResourceTag`
<a name="resource-groups_Tag_powershell_5_topic"></a>

次のコード例は、`Add-RGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリソースグループ ARN に値「workboxes」を持つタグキー「Instances」を追加します。**  

```
Add-RGResourceTag -Tag @{Instances="workboxes"} -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes
```
**出力:**  

```
Arn                                                            Tags
---                                                            ----
arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes {[Instances, workboxes]}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[Tag](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Find-RGResource`
<a name="resource-groups_SearchResources_powershell_5_topic"></a>

次のコード例は、`Find-RGResource` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、タグフィルターを使用してインスタンスリソースタイプの ResourceQuery を作成し、リソースを検索します。**  

```
$query = [Amazon.ResourceGroups.Model.ResourceQuery]::new()
$query.Type = [Amazon.ResourceGroups.QueryType]::TAG_FILTERS_1_0
$query.Query = ConvertTo-Json -Compress -Depth 4 -InputObject @{
  ResourceTypeFilters = @('AWS::EC2::Instance')
  TagFilters = @(@{
    Key = 'auto'
    Values = @('no')
  })
 }

Find-RGResource -ResourceQuery $query | Select-Object -ExpandProperty ResourceIdentifiers
```
**出力:**  

```
ResourceArn                                                     ResourceType
-----------                                                     ------------
arn:aws:ec2:eu-west-1:123456789012:instance/i-0123445b6cb7bd67b AWS::EC2::Instance
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SearchResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGGroup`
<a name="resource-groups_GetGroup_powershell_5_topic"></a>

次のコード例は、`Get-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、グループ名に従ってリソースグループを取得します。**  

```
Get-RGGroup -GroupName auto-no
```
**出力:**  

```
Description GroupArn                                                     Name
----------- --------                                                     ----
            arn:aws:resource-groups:eu-west-1:123456789012:group/auto-no auto-no
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGGroupList`
<a name="resource-groups_ListGroups_powershell_5_topic"></a>

次のコード例は、`Get-RGGroupList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、既に作成されたリソースグループを一覧表示します。**  

```
Get-RGGroupList
```
**出力:**  

```
GroupArn                                                                  GroupName
--------                                                                  ---------
arn:aws:resource-groups:eu-west-1:123456789012:group/auto-no              auto-no
arn:aws:resource-groups:eu-west-1:123456789012:group/auto-yes             auto-yes
arn:aws:resource-groups:eu-west-1:123456789012:group/build600             build600
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGGroupQuery`
<a name="resource-groups_GetGroupQuery_powershell_5_topic"></a>

次のコード例は、`Get-RGGroupQuery` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリソースグループのリソースクエリを取得します。**  

```
Get-RGGroupQuery -GroupName auto-no | Select-Object -ExpandProperty ResourceQuery
```
**出力:**  

```
Query                                                                                        Type
-----                                                                                        ----
{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"auto","Values":["no"]}]} TAG_FILTERS_1_0
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetGroupQuery](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGGroupResourceList`
<a name="resource-groups_ListGroupResources_powershell_5_topic"></a>

次のコード例は、`Get-RGGroupResourceList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リソースタイプでフィルタリングされたグループリソースを一覧表示します。**  

```
Get-RGGroupResourceList -Filter @{Name="resource-type";Values="AWS::EC2::Instance"} -GroupName auto-yes | Select-Object -ExpandProperty ResourceIdentifiers
```
**出力:**  

```
ResourceArn                                                     ResourceType
-----------                                                     ------------
arn:aws:ec2:eu-west-1:123456789012:instance/i-0123bc45b567890e1 AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-0a1caf2345f67d8dc AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-012e3cb4df567e8aa AWS::EC2::Instance
arn:aws:ec2:eu-west-1:123456789012:instance/i-0fd12dd3456789012 AWS::EC2::Instance
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListGroupResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGResourceTag`
<a name="resource-groups_GetTags_powershell_5_topic"></a>

次のコード例は、`Get-RGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定されたリソースグループ ARN のタグを一覧表示します。**  

```
Get-RGResourceTag -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes
```
**出力:**  

```
Key       Value
---       -----
Instances workboxes
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-RGGroup`
<a name="resource-groups_CreateGroup_powershell_5_topic"></a>

次のコード例は、`New-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、TestPowerShellGroup という名前の新しいタグベースの AWS Resource Groups リソースグループを作成します。グループには、タグキー「Name」とタグ値「test2」でタグ付けされた現在のリージョンの Amazon EC2 インスタンスが含まれます。コマンドは、クエリとグループのタイプ、および操作の結果を返します。**  

```
$ResourceQuery = New-Object -TypeName Amazon.ResourceGroups.Model.ResourceQuery
$ResourceQuery.Type = "TAG_FILTERS_1_0"
$ResourceQuery.Query = '{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"Name","Values":["test2"]}]}'
$ResourceQuery

New-RGGroup -Name TestPowerShellGroup -ResourceQuery $ResourceQuery -Description "Test resource group."
```
**出力:**  

```
Query                                                                                           Type           
-----                                                                                           ----           
{"ResourceTypeFilters":["AWS::EC2::Instance"],"TagFilters":[{"Key":"Name","Values":["test2"]}]} TAG_FILTERS_1_0

LoggedAt         : 11/20/2018 2:40:59 PM
Group            : Amazon.ResourceGroups.Model.Group
ResourceQuery    : Amazon.ResourceGroups.Model.ResourceQuery
Tags             : {}
ResponseMetadata : Amazon.Runtime.ResponseMetadata
ContentLength    : 338
HttpStatusCode   : OK
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-RGGroup`
<a name="resource-groups_DeleteGroup_powershell_5_topic"></a>

次のコード例は、`Remove-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、名前付きリソースグループを削除します。**  

```
Remove-RGGroup -GroupName non-tag-cfn-elbv2
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-RGGroup (DeleteGroup)" on target "non-tag-cfn-elbv2".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Description GroupArn                                                               Name
----------- --------                                                               ----
            arn:aws:resource-groups:eu-west-1:123456789012:group/non-tag-cfn-elbv2 non-tag-cfn-elbv2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-RGResourceTag`
<a name="resource-groups_Untag_powershell_5_topic"></a>

次のコード例は、`Remove-RGResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リソースグループから指定されたタグを削除します。**  

```
Remove-RGResourceTag -Arn arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes -Key Instances
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-RGResourceTag (Untag)" on target "arn:aws:resource-groups:eu-west-1:933303704102:group/workboxes".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y

Arn                                                            Keys
---                                                            ----
arn:aws:resource-groups:eu-west-1:123456789012:group/workboxes {Instances}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[Untag](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-RGGroup`
<a name="resource-groups_UpdateGroup_powershell_5_topic"></a>

次のコード例は、`Update-RGGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、グループの説明を更新します。**  

```
Update-RGGroup -GroupName auto-yes -Description "Instances auto-remove"
```
**出力:**  

```
Description             GroupArn                                                      Name
-----------             --------                                                      ----
Instances to be cleaned arn:aws:resource-groups:eu-west-1:123456789012:group/auto-yes auto-yes
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-RGGroupQuery`
<a name="resource-groups_UpdateGroupQuery_powershell_5_topic"></a>

次のコード例は、`Update-RGGroupQuery` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、クエリオブジェクトを作成し、グループのクエリを更新します。**  

```
$query = [Amazon.ResourceGroups.Model.ResourceQuery]::new()
$query.Type = [Amazon.ResourceGroups.QueryType]::TAG_FILTERS_1_0
$query.Query = @{
  ResourceTypeFilters = @('AWS::EC2::Instance')
  TagFilters = @(@{
  Key='Environment'
  Values='Build600.11'
  })
} | ConvertTo-Json -Compress -Depth 4

Update-RGGroupQuery -GroupName build600 -ResourceQuery $query
```
**出力:**  

```
GroupName ResourceQuery
--------- -------------
build600  Amazon.ResourceGroups.Model.ResourceQuery
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateGroupQuery](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用したリソースグループタグ付け API の例
<a name="powershell_5_resource-groups-tagging-api_code_examples"></a>

次のコード例は、Resource Groups Tagging API で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-RGTResourceTag`
<a name="resource-groups-tagging-api_TagResources_powershell_5_topic"></a>

次のコード例は、`Add-RGTResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、値「beta」と「preprod\$1test」を含むタグキー「stage」と「version」を Amazon S3 バケットと Amazon DynamoDB テーブルに追加します。タグを適用するため、サービスが 1 回呼び出されます。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

Add-RGTResourceTag -ResourceARNList $arn1,$arn2 -Tag @{ "stage"="beta"; "version"="preprod_test" }
```
**例 2: この例では、指定されたタグと値を Amazon S3 バケットと Amazon DynamoDB テーブルに追加します。コマンドレットにパイプされたリソース ARN ごとに 1 回ずつ、2 回サービスが呼び出されます。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

$arn1,$arn2 | Add-RGTResourceTag -Tag @{ "stage"="beta"; "version"="preprod_test" }
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TagResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGTResource`
<a name="resource-groups-tagging-api_GetResources_powershell_5_topic"></a>

次のコード例は、`Get-RGTResource` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: リージョン内のすべてのタグ付けされたリソースと、リソースに関連付けられたタグキーを返します。コマンドレットに -Region パラメータが指定されていない場合、シェルまたは EC2 インスタンスメタデータからリージョンを推測しようとします。**  

```
Get-RGTResource
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}   
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 2: リージョン内の指定されたタイプのタグ付けされたリソースをすべて返します。各サービス名とリソースタイプの文字列は、リソースの Amazon リソースネーム (ARN) に埋め込まれている文字列と同じです。**  

```
Get-RGTResource -ResourceType "s3"
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 3: リージョン内の指定されたタイプのタグ付けされたリソースをすべて返します。リソースタイプをコマンドレットにパイプすると、指定されたリソースタイプごとにサービスへの呼び出しが 1 回行われることに注意してください。**  

```
"dynamodb","s3" | Get-RGTResource
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}   
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 4: 指定されたフィルターに一致するタグ付けされたすべてのリソースを返します。**  

```
Get-RGTResource -TagFilter @{ Key="stage" }
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:s3:::amzn-s3-demo-bucket                                            {stage, version, othertag}
```
**例 5: 指定されたフィルターとリソースタイプに一致するタグ付けされたすべてのリソースを返します。**  

```
Get-RGTResource -TagFilter @{ Key="stage" } -ResourceType "dynamodb"
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}
```
**例 6: 指定されたフィルターに一致するタグ付けされたすべてのリソースを返します。**  

```
Get-RGTResource -TagFilter @{ Key="stage"; Values=@("beta","gamma") }
```
**出力:**  

```
ResourceARN                                                      Tags          
-----------                                                      ----            
arn:aws:dynamodb:us-west-2:123456789012:table/mytable            {stage, version}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGTTagKey`
<a name="resource-groups-tagging-api_GetTagKeys_powershell_5_topic"></a>

次のコード例は、`Get-RGTTagKey` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたリージョンのすべてのタグキーを返します。-Region パラメータが指定されていない場合、コマンドレットはデフォルトのシェルリージョンまたは EC2 インスタンスメタデータからリージョンを推測しようとします。タグキーは特定の順序では返されないことに注意してください。**  

```
Get-RGTTagKey -region us-west-2
```
**出力:**  

```
version
stage
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetTagKeys](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-RGTTagValue`
<a name="resource-groups-tagging-api_GetTagValues_powershell_5_topic"></a>

次のコード例は、`Get-RGTTagValue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: リージョン内の指定されたタグの値を返します。-Region パラメータが指定されていない場合、コマンドレットはデフォルトのシェルリージョンまたは EC2 インスタンスメタデータからリージョンを推測しようとします。**  

```
Get-RGTTagValue -Key "stage" -Region us-west-2
```
**出力:**  

```
beta
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetTagValues](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-RGTResourceTag`
<a name="resource-groups-tagging-api_UntagResources_powershell_5_topic"></a>

次のコード例は、`Remove-RGTResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: Amazon S3 バケットと Amazon DynamoDB テーブルからタグキー「stage」と「version」、および関連する値を削除します。タグを削除するために、サービスが 1 回呼び出されます。タグを削除する前に、コマンドレットで確認を求められます。確認を表示しないようにするには、-Force パラメータを追加します。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

Remove-RGTResourceTag -ResourceARNList $arn1,$arn2 -TagKey "stage","version"
```
**例 2: Amazon S3 バケットと Amazon DynamoDB テーブルからタグキー「stage」と「version」、および関連する値を削除します。コマンドレットにパイプされたリソース ARN ごとに 1 回ずつ、2 回サービスが呼び出されます。各呼び出しの前に、コマンドレットで確認を求められます。確認を表示しないようにするには、-Force パラメータを追加します。**  

```
$arn1 = "arn:aws:s3:::amzn-s3-demo-bucket"
$arn2 = "arn:aws:dynamodb:us-west-2:123456789012:table/mytable"

$arn1,$arn2 | Remove-RGTResourceTag -TagKey "stage","version"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UntagResources](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Route 53 の例
<a name="powershell_5_route-53_code_examples"></a>

次のコード例は、Route AWS Tools for PowerShell V5 5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Edit-R53ResourceRecordSet`
<a name="route-53_ChangeResourceRecordSets_powershell_5_topic"></a>

次のコード例は、`Edit-R53ResourceRecordSet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、www.example.com の A レコードを作成し、test.example.com の A レコードを 192.0.2.3 から 192.0.2.1 に変更します。変更 TXT タイプのレコードの値は二重引用符で囲む必要があることに注意してください。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "TXT"
$change1.ResourceRecordSet.TTL = 600
$change1.ResourceRecordSet.ResourceRecords = @()
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="item 1 item 2 item 3"})

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "DELETE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "test.example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.TTL = 600
$change2.ResourceRecordSet.ResourceRecords = @()
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.3"})

$change3 = New-Object Amazon.Route53.Model.Change
$change3.Action = "CREATE"
$change3.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change3.ResourceRecordSet.Name = "test.example.com"
$change3.ResourceRecordSet.Type = "A"
$change3.ResourceRecordSet.TTL = 600
$change3.ResourceRecordSet.ResourceRecords = @()
$change3.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.1"})

$params = @{
    HostedZoneId="Z1PA6795UKMFR9"
	ChangeBatch_Comment="This change batch creates a TXT record for www.example.com. and changes the A record for test.example.com. from 192.0.2.3 to 192.0.2.1."
	ChangeBatch_Change=$change1,$change2,$change3
}

Edit-R53ResourceRecordSet @params
```
**例 2: この例は、エイリアスリソースレコードセットの作成方法を示します。「Z222222222」は、エイリアスリソースレコードセットを作成する Amazon Route 53 ホストゾーンの ID です。「example.com」は、エイリアスを作成するゾーン頂点 Zone Apex で、「www.example.com」は、エイリアスを作成するサブドメインです。「Z1111111111111」はロードバランサーのホストゾーン ID の例で、「example-load-balancer-1111111111.us-east-1.elb.amazonaws.com」は Amazon Route 53 が example.com および www.example.com のクエリに応答するロードバランサードメイン名の例です。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $false

$params = @{
    HostedZoneId="Z222222222"
	ChangeBatch_Comment="This change batch creates two alias resource record sets, one for the zone apex, example.com, and one for www.example.com, that both point to example-load-balancer-1111111111.us-east-1.elb.amazonaws.com."
	ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**例 3: この例では、www.example.com の A レコードを 2 つ作成します。割合が 4 分の 1 (1/(1\$13)) の Amazon Route 53 は、最初のリソースレコードセット (192.0.2.9 と 192.0.2.10) の 2 つの値を使用して www.example.com のクエリに応答します。割合が 4 分の 3 (3/(1\$13)) の Amazon Route 53 は、2 番目のリソースレコードセット (192.0.2.11 と 192.0.2.12) の 2 つの値を使用して www.example.com のクエリに応答します。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "www.example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "Rack 2, Positions 4 and 5"
$change1.ResourceRecordSet.Weight = 1
$change1.ResourceRecordSet.TTL = 600
$change1.ResourceRecordSet.ResourceRecords = @()
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.9"})
$change1.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.10"})

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "www.example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "Rack 5, Positions 1 and 2"
$change2.ResourceRecordSet.Weight = 3
$change2.ResourceRecordSet.TTL = 600
$change2.ResourceRecordSet.ResourceRecords = @()
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.11"})
$change2.ResourceRecordSet.ResourceRecords.Add(@{Value="192.0.2.12"})

$params = @{
    HostedZoneId="Z1PA6795UKMFR9"
    ChangeBatch_Comment="This change creates two weighted resource record sets, each of which has two values."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**例 4: この例は、example.com が加重エイリアスリソースレコードセットを作成するドメインであると仮定した、加重エイリアスリソースレコードセットの作成方法を示します。SetIdentifier は、2 つの加重エイリアスリソースレコードセットを相互に区別します。Name 要素と Type 要素が両方のリソースレコードセットに同じ値を持つため、この要素は必要です。Z1111111111111 および Z3333333333333 は、DNSName の値で指定された ELB ロードバランサーのホストゾーン ID の例です。example-load-balancer-2222222222.us-east-1.elb.amazonaws.com および example-load-balancer-4444444444.us-east-1.elb.amazonaws.com は Amazon Route 53 が example.com のクエリに応答する Elastic Load Balancing ドメインの例です。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "1"
$change1.ResourceRecordSet.Weight = 3
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-2222222222.us-east-1.elb.amazonaws.com."
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "2"
$change2.ResourceRecordSet.Weight = 1
$change2.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change2.ResourceRecordSet.AliasTarget.HostedZoneId = "Z3333333333333"
$change2.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-4444444444.us-east-1.elb.amazonaws.com."
$change2.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $false

$params = @{
    HostedZoneId="Z5555555555"
    ChangeBatch_Comment="This change batch creates two weighted alias resource record sets. Amazon Route 53 responds to queries for example.com with the first ELB domain 3/4ths of the times and the second one 1/4th of the time."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
**例 5: この例では、レイテンシーエイリアスリソースレコードセットを 2 つ作成します。1 つは米国西部 (オレゴン) リージョン (us-west-2) の ELB ロードバランサー用で、もう 1 つはアジアパシフィック (シンガポール) リージョン (ap-southeast-1) のロードバランサー用です。詳細については、Amazon Route 53 のドキュメントを参照してください。Get-R53Change コマンドレットを使用してポーリングし、変更が完了したタイミングを確認できます。**  

```
$change1 = New-Object Amazon.Route53.Model.Change
$change1.Action = "CREATE"
$change1.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change1.ResourceRecordSet.Name = "example.com"
$change1.ResourceRecordSet.Type = "A"
$change1.ResourceRecordSet.SetIdentifier = "Oregon load balancer 1"
$change1.ResourceRecordSet.Region = us-west-2
$change1.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change1.ResourceRecordSet.AliasTarget.HostedZoneId = "Z1111111111111"
$change1.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-2222222222.us-west-2.elb.amazonaws.com"
$change1.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$change2 = New-Object Amazon.Route53.Model.Change
$change2.Action = "CREATE"
$change2.ResourceRecordSet = New-Object Amazon.Route53.Model.ResourceRecordSet
$change2.ResourceRecordSet.Name = "example.com"
$change2.ResourceRecordSet.Type = "A"
$change2.ResourceRecordSet.SetIdentifier = "Singapore load balancer 1"
$change2.ResourceRecordSet.Region = ap-southeast-1
$change2.ResourceRecordSet.AliasTarget = New-Object Amazon.Route53.Model.AliasTarget
$change2.ResourceRecordSet.AliasTarget.HostedZoneId = "Z2222222222222"
$change2.ResourceRecordSet.AliasTarget.DNSName = "example-load-balancer-1111111111.ap-southeast-1.elb.amazonaws.com"
$change2.ResourceRecordSet.AliasTarget.EvaluateTargetHealth = $true

$params = @{
    HostedZoneId="Z5555555555"
    ChangeBatch_Comment="This change batch creates two latency resource record sets, one for the US West (Oregon) region and one for the Asia Pacific (Singapore) region."
    ChangeBatch_Change=$change1,$change2
}

Edit-R53ResourceRecordSet @params
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ChangeResourceRecordSets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53AccountLimit`
<a name="route-53_GetAccountLimit_powershell_5_topic"></a>

次のコード例は、`Get-R53AccountLimit` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在のアカウントを使用して作成できるホストゾーンの最大数を返します。**  

```
Get-R53AccountLimit -Type MAX_HOSTED_ZONES_BY_OWNER
```
**出力:**  

```
15
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAccountLimit](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53CheckerIpRanges`
<a name="route-53_GetCheckerIpRanges_powershell_5_topic"></a>

次のコード例は、`Get-R53CheckerIpRanges` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Route53 ヘルスチェッカーの CIDR を返します。**  

```
Get-R53CheckerIpRanges
```
**出力:**  

```
15.177.2.0/23
15.177.6.0/23
15.177.10.0/23
15.177.14.0/23
15.177.18.0/23
15.177.22.0/23
15.177.26.0/23
15.177.30.0/23
15.177.34.0/23
15.177.38.0/23
15.177.42.0/23
15.177.46.0/23
15.177.50.0/23
15.177.54.0/23
15.177.58.0/23
15.177.62.0/23
54.183.255.128/26
54.228.16.0/26
54.232.40.64/26
54.241.32.64/26
54.243.31.192/26
54.244.52.192/26
54.245.168.0/26
54.248.220.0/26
54.250.253.192/26
54.251.31.128/26
54.252.79.128/26
54.252.254.192/26
54.255.254.192/26
107.23.255.0/26
176.34.159.192/26
177.71.207.128/26
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetCheckerIpRanges](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53HostedZone`
<a name="route-53_GetHostedZone_powershell_5_topic"></a>

次のコード例は、`Get-R53HostedZone` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ID Z1D633PJN98FT9 を持つホストゾーンの詳細を返します。**  

```
Get-R53HostedZone -Id Z1D633PJN98FT9
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53HostedZoneCount`
<a name="route-53_GetHostedZoneCount_powershell_5_topic"></a>

次のコード例は、`Get-R53HostedZoneCount` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 現在のパブリックホストゾーンとプライベートホストゾーンの合計数を返します AWS アカウント。**  

```
Get-R53HostedZoneCount
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetHostedZoneCount](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53HostedZoneLimit`
<a name="route-53_GetHostedZoneLimit_powershell_5_topic"></a>

次のコード例は、`Get-R53HostedZoneLimit` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ホストゾーンで作成できるレコードの数の上限を返します。**  

```
Get-R53HostedZoneLimit -HostedZoneId Z3MEQ8T7HAAAAF -Type MAX_RRSETS_BY_ZONE
```
**出力:**  

```
5
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetHostedZoneLimit](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53HostedZoneList`
<a name="route-53_ListHostedZones_powershell_5_topic"></a>

次のコード例は、`Get-R53HostedZoneList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべてのパブリックホストゾーンとプライベートホストゾーンを出力します。**  

```
Get-R53HostedZoneList
```
**例 2: ID NZ8X2CISAMPLE を持つ再利用可能な委託セットに関連付けられているすべてのホストゾーンを出力します**  

```
Get-R53HostedZoneList -DelegationSetId NZ8X2CISAMPLE
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListHostedZones](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53HostedZonesByName`
<a name="route-53_ListHostedZonesByName_powershell_5_topic"></a>

次のコード例は、`Get-R53HostedZonesByName` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべてのパブリックホストゾーンとプライベートホストゾーンを、ドメイン名で ASCII 順に返します。**  

```
Get-R53HostedZonesByName
```
**例 2: パブリックホストゾーンとプライベートホストゾーンを、ドメイン名で ASCII 順に指定した DNS 名から返します。**  

```
Get-R53HostedZonesByName -DnsName example2.com
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListHostedZonesByName](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53QueryLoggingConfigList`
<a name="route-53_ListQueryLoggingConfigs_powershell_5_topic"></a>

次のコード例は、`Get-R53QueryLoggingConfigList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、現在の AWS アカウントに関連付けられている DNS クエリのログ記録のすべての設定を返します。**  

```
Get-R53QueryLoggingConfigList
```
**出力:**  

```
Id                                   HostedZoneId   CloudWatchLogsLogGroupArn
--                                   ------------   -------------------------
59b0fa33-4fea-4471-a88c-926476aaa40d Z385PDS6EAAAZR arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example1.com:*
ee528e95-4e03-4fdc-9d28-9e24ddaaa063 Z94SJHBV1AAAAZ arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example2.com:*
e38dddda-ceb6-45c1-8cb7-f0ae56aaaa2b Z3MEQ8T7AAA1BF arn:aws:logs:us-east-1:111111111112:log-group:/aws/route53/example3.com:*
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListQueryLoggingConfigs](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-R53ReusableDelegationSet`
<a name="route-53_GetReusableDelegationSet_powershell_5_topic"></a>

次のコード例は、`Get-R53ReusableDelegationSet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、委任セットに割り当てられた 4 つのネームサーバーを含む、指定委任セットに関する情報を取得します。**  

```
Get-R53ReusableDelegationSet -Id N23DS9X4AYEAAA
```
**出力:**  

```
Id                            CallerReference NameServers
--                            --------------- -----------
/delegationset/N23DS9X4AYEAAA testcaller      {ns-545.awsdns-04.net, ns-1264.awsdns-30.org, ns-2004.awsdns-58.co.uk, ns-240.awsdns-30.com}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-R53HostedZone`
<a name="route-53_CreateHostedZone_powershell_5_topic"></a>

次のコード例は、`New-R53HostedZone` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 再利用可能な委託セットに関連付けられた「example.com」という名前の新しいホストゾーンを作成します。CallerReference パラメータの値を指定する必要があります。それによって、必要に応じて再試行が必要なリクエストのオペレーションを 2 回実行するリスクがなくなります。ホストゾーンは VPC で作成され、自動的にプライベートになるため、-HostedZoneConfig\$1PrivateZone パラメータは設定しないでください。**  

```
$params = @{
    Name="example.com"
    CallerReference="myUniqueIdentifier"
    HostedZoneConfig_Comment="This is my first hosted zone"
    DelegationSetId="NZ8X2CISAMPLE"
    VPC_VPCId="vpc-1a2b3c4d"
    VPC_VPCRegion="us-east-1"
}

New-R53HostedZone @params
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-R53QueryLoggingConfig`
<a name="route-53_CreateQueryLoggingConfig_powershell_5_topic"></a>

次のコード例は、`New-R53QueryLoggingConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ホストゾーンの新しい Route53 DNS クエリのログ記録設定を作成します。Amazon Route53 は、指定 Cloudwatch ロググループに DNS クエリログを発行します。**  

```
New-R53QueryLoggingConfig -HostedZoneId Z3MEQ8T7HAAAAF -CloudWatchLogsLogGroupArn arn:aws:logs:us-east-1:111111111111:log-group:/aws/route53/example.com:*
```
**出力:**  

```
QueryLoggingConfig                      Location
------------------                      --------
Amazon.Route53.Model.QueryLoggingConfig https://route53.amazonaws.com/2013-04-01/queryloggingconfig/ee5aaa95-4e03-4fdc-9d28-9e24ddaaaaa3
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-R53ReusableDelegationSet`
<a name="route-53_CreateReusableDelegationSet_powershell_5_topic"></a>

次のコード例は、`New-R53ReusableDelegationSet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、複数のホストゾーンで再利用できる 4 つのネームサーバーの再利用可能な委任セットを作成します。**  

```
New-R53ReusableDelegationSet -CallerReference testcallerreference
```
**出力:**  

```
DelegationSet                      Location
-------------                      --------
Amazon.Route53.Model.DelegationSet https://route53.amazonaws.com/2013-04-01/delegationset/N23DS9XAAAAAXM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-R53VPCWithHostedZone`
<a name="route-53_AssociateVPCWithHostedZone_powershell_5_topic"></a>

次のコード例は、`Register-R53VPCWithHostedZone` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 VPC をプライベートホストゾーンに関連付けます。**  

```
Register-R53VPCWithHostedZone -HostedZoneId Z3MEQ8T7HAAAAF -VPC_VPCId vpc-f1b9aaaa -VPC_VPCRegion us-east-1
```
**出力:**  

```
Id                     Status  SubmittedAt         Comment
--                     ------  -----------         -------
/change/C3SCAAA633Z6DX PENDING 01/28/2020 19:32:02
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AssociateVPCWithHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-R53HostedZone`
<a name="route-53_DeleteHostedZone_powershell_5_topic"></a>

次のコード例は、`Remove-R53HostedZone` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された ID を持つホストゾーンを削除します。-Force スイッチパラメータを追加しない限り、コマンドを進める前に確認を求められます。**  

```
Remove-R53HostedZone -Id Z1PA6795UKMFR9
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-R53QueryLoggingConfig`
<a name="route-53_DeleteQueryLoggingConfig_powershell_5_topic"></a>

次のコード例は、`Remove-R53QueryLoggingConfig` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、DNS クエリログ記録の指定された設定を削除します。**  

```
Remove-R53QueryLoggingConfig -Id ee528e95-4e03-4fdc-9d28-9e24daaa20063
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteQueryLoggingConfig](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-R53ReusableDelegationSet`
<a name="route-53_DeleteReusableDelegationSet_powershell_5_topic"></a>

次のコード例は、`Remove-R53ReusableDelegationSet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、再利用可能な指定委任セットを削除します。**  

```
Remove-R53ReusableDelegationSet -Id N23DS9X4AYAAAM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteReusableDelegationSet](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-R53VPCFromHostedZone`
<a name="route-53_DisassociateVPCFromHostedZone_powershell_5_topic"></a>

次のコード例は、`Unregister-R53VPCFromHostedZone` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 VPC とプライベートホストゾーンの関連付けを解除します。**  

```
Unregister-R53VPCFromHostedZone -HostedZoneId Z3MEQ8T7HAAAAF -VPC_VPCId vpc-f1b9aaaa -VPC_VPCRegion us-east-1
```
**出力:**  

```
Id                     Status  SubmittedAt         Comment
--                     ------  -----------         -------
/change/C2XFCAAAA9HKZG PENDING 01/28/2020 10:35:55
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DisassociateVPCFromHostedZone](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-R53HostedZoneComment`
<a name="route-53_UpdateHostedZoneComment_powershell_5_topic"></a>

次のコード例は、`Update-R53HostedZoneComment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定ホストゾーンのコメントを更新します。**  

```
Update-R53HostedZoneComment -Id Z385PDS6AAAAAR -Comment "This is my first hosted zone"
```
**出力:**  

```
Id                     : /hostedzone/Z385PDS6AAAAAR
Name                   : example.com.
CallerReference        : C5B55555-7147-EF04-8341-69131E805C89
Config                 : Amazon.Route53.Model.HostedZoneConfig
ResourceRecordSetCount : 9
LinkedService          :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateHostedZoneComment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon S3 の例
<a name="powershell_5_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Copy-S3Object`
<a name="s3_CopyObject_powershell_5_topic"></a>

次のコード例は、`Copy-S3Object` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、オブジェクト「sample.txt」をバケット「test-files」から同じバケットにコピーします。ただし、新しいキー「sample-copy.txt」を使用します。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -DestinationKey sample-copy.txt
```
**例 2: このコマンドは、オブジェクト「sample.txt」をバケット「test-files」からバケット「backup-files」にコピーします。ただし、キーは「sample-copy.txt」を使用します。**  

```
Copy-S3Object -BucketName amzn-s3-demo-source-bucket -Key sample.txt -DestinationKey sample-copy.txt -DestinationBucket amzn-s3-demo-destination-bucket
```
**例 3: このコマンドは、オブジェクト「sample.txt」をバケット「test-files」からダウンロードして、「local-sample.txt」という名前のローカルファイルに保存します。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -LocalFile local-sample.txt
```
**例 4: 指定したファイルに 1 つのオブジェクトをダウンロードします。ダウンロードしたファイルは c:\$1downloads\$1data\$1archive.zip に保存されます。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -Key data/archive.zip -LocalFolder c:\downloads
```
**例 5: 指定した key prefix と一致するすべてのオブジェクトをローカルフォルダにダウンロードします。相対的なキー階層は、ダウンロードの場所全体のサブフォルダとして保存されます。**  

```
Copy-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix data -LocalFolder c:\downloads
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CopyObject](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3Bucket`
<a name="s3_ListBuckets_powershell_5_topic"></a>

次のコード例は、`Get-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドはすべての S3 バケットを返します。**  

```
Get-S3Bucket
```
**例 2: このコマンドは「test-files」という名前のバケットを返します。**  

```
Get-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListBuckets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketACL`
<a name="s3_GetBucketAcl_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketACL` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: コマンドは、S3 オブジェクトのオブジェクト所有者の詳細を取得します。**  

```
(Get-S3BucketACL -BucketName 'amzn-s3-demo-bucket' -Select *).Owner
```
**出力:**  

```
DisplayName Id
----------- --
testusername      9988776a6554433d22f1100112e334acb45566778899009e9887bd7f66c5f544
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketAcl](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketAccelerateConfiguration`
<a name="s3_GetBucketAccelerateConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketAccelerateConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定したバケットで転送加速設定が有効になっている場合、このコマンドは Enabled の値を返します。**  

```
Get-S3BucketAccelerateConfiguration -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Value                                  
-----                                    
Enabled
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketAnalyticsConfiguration`
<a name="s3_GetBucketAnalyticsConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketAnalyticsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケット内の「testfilter」という名前の分析フィルターの詳細を返します。**  

```
Get-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketAnalyticsConfigurationList`
<a name="s3_ListBucketAnalyticsConfigurations_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketAnalyticsConfigurationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットの最初の 100 つの分析設定を返します。**  

```
Get-S3BucketAnalyticsConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListBucketAnalyticsConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketEncryption`
<a name="s3_GetBucketEncryption_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketEncryption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: のコマンドは、指定したバケットに関連付けられたすべてのサーバー側暗号化ルールを返します。**  

```
Get-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketInventoryConfiguration`
<a name="s3_GetBucketInventoryConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketInventoryConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケット内の「testinventory」という名前のインベントリの詳細を返します。**  

```
Get-S3BucketInventoryConfiguration -BucketName 'amzn-s3-demo-bucket' -InventoryId 'testinventory'
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-S3BucketInventoryConfigurationList`
<a name="s3_ListBucketInventoryConfigurations_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketInventoryConfigurationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットの最初の 100 つのインベントリ設定を返します。**  

```
Get-S3BucketInventoryConfigurationList -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListBucketInventoryConfigurations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-S3BucketLocation`
<a name="s3_GetBucketLocation_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketLocation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、制約が存在する場合、バケット「amzn-s3-demo-bucket」の場所の制約を返します。**  

```
Get-S3BucketLocation -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Value
-----
ap-south-1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketLocation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketLogging`
<a name="s3_GetBucketLogging_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketLogging` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定したバケットのログ記録ステータスを返します。**  

```
Get-S3BucketLogging -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
TargetBucketName   Grants TargetPrefix
----------------   ------ ------------
testbucket1        {}     testprefix
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketLogging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketMetricsConfiguration`
<a name="s3_GetBucketMetricsConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketMetricsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットの「testfilter」という名前のメトリクスフィルターに関する詳細を返します。**  

```
Get-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testfilter'
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-S3BucketNotification`
<a name="s3_GetBucketNotification_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketNotification` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したバケットの通知設定を取得します。**  

```
Get-S3BucketNotification -BucketName amzn-s3-demo-bucket | select -ExpandProperty TopicConfigurations
```
**出力:**  

```
Id   Topic
--   -----
mimo arn:aws:sns:eu-west-1:123456789012:topic-1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketNotification](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketPolicy`
<a name="s3_GetBucketPolicy_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットに関連付けられたバケットポリシーを出力します。**  

```
Get-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketPolicyStatus`
<a name="s3_GetBucketPolicyStatus_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketPolicyStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットのポリシーステータスを返し、バケットがパブリックかどうかを示します。**  

```
Get-S3BucketPolicyStatus -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketPolicyStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketReplication`
<a name="s3_GetBucketReplication_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketReplication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットに設定されているレプリケーション設定の情報を返します。**  

```
Get-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketRequestPayment`
<a name="s3_GetBucketRequestPayment_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketRequestPayment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットのリクエストの支払い設定を返します。デフォルトでは、バケット所有者はバケットからのダウンロード料金を支払います。**  

```
Get-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketRequestPayment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketTagging`
<a name="s3_GetBucketTagging_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketTagging` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定バケットに関連付けられたすべてのタグを返します。**  

```
Get-S3BucketTagging -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketVersioning`
<a name="s3_GetBucketVersioning_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketVersioning` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定バケットに関するバージョニングステータスを返します。**  

```
Get-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketVersioning](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3BucketWebsite`
<a name="s3_GetBucketWebsite_powershell_5_topic"></a>

次のコード例は、`Get-S3BucketWebsite` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 S3 バケットの静的ウェブサイトの設定の詳細を返します。**  

```
Get-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3CORSConfiguration`
<a name="s3_GetCORSConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-S3CORSConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 S3 バケットに対応するすべての CORS 設定ルールを含むオブジェクトを返します。**  

```
Get-S3CORSConfiguration -BucketName 'amzn-s3-demo-bucket' -Select Configuration.Rules
```
**出力:**  

```
AllowedMethods : {PUT, POST, DELETE}
AllowedOrigins : {http://www.example1.com}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {*}

AllowedMethods : {PUT, POST, DELETE}
AllowedOrigins : {http://www.example2.com}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {*}

AllowedMethods : {GET}
AllowedOrigins : {*}
Id             : 
ExposeHeaders  : {}
MaxAgeSeconds  : 0
AllowedHeaders : {}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetCORSConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3HeadBucket`
<a name="s3_HeadBucket_powershell_5_topic"></a>

次のコード例は、`Get-S3HeadBucket` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、ユーザーがバケットにアクセスするアクセス許可を持っている場合に、既存のバケットに対して HTTP ステータスコード 200 OK の出力を返します。BucketArn パラメータは S3 ディレクトリバケットでのみサポートされています。**  

```
Get-S3HeadBucket -BucketName amzn-s3-demo-bucket
```
**出力:**  

```
AccessPointAlias   : False
BucketArn          :
BucketLocationName : 
BucketLocationType : 
BucketRegion       : us-east-2
ResponseMetadata   : Amazon.Runtime.ResponseMetadata
ContentLength      : 0
HttpStatusCode     : OK
```
**例 2: このコマンドは、存在しないバケットに対して HTTP ステータスコード NotFound でエラーをスローします。**  

```
Get-S3HeadBucket -BucketName amzn-s3-non-existing-bucket
```
**出力:**  

```
Get-S3HeadBucket: Error making request with Error Code NotFound and Http Status Code NotFound. No further error information was returned by the service.
```
**例 3: このコマンドは、ユーザーがアクセス許可を持たない既存のバケットに対して HTTP ステータスコード Forbidden でエラーをスローします。**  

```
Get-S3HeadBucket -BucketName amzn-s3-no-access-bucket
```
**出力:**  

```
Get-S3HeadBucket: Error making request with Error Code Forbidden and Http Status Code Forbidden. No further error information was returned by the service.
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[HeadBucket](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3LifecycleConfiguration`
<a name="s3_GetLifecycleConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-S3LifecycleConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、バケットのライフサイクル設定を取得します。**  

```
Get-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket
```
**出力:**  

```
Rules
-----
{Remove-in-150-days, Archive-to-Glacier-in-30-days}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3Object`
<a name="s3_ListObjects_powershell_5_topic"></a>

次のコード例は、`Get-S3Object` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、バケット「test-files」内のすべての項目に関する情報を取得します。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket
```
**例 2: このコマンドは、バケット「test-files」内の項目「sample.txt」に関する情報を取得します。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt
```
**例 3: このコマンドは、バケット「test-files」からプレフィックス「sample」を持つすべての項目に関する情報を取得します。**  

```
Get-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix sample
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListObjects](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3ObjectACL`
<a name="s3_GetObjectAcl_powershell_5_topic"></a>

次のコード例は、`Get-S3ObjectACL` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: コマンドは、S3 オブジェクトのオブジェクト所有者の詳細を取得します。**  

```
(Get-S3ObjectACL -BucketName 'amzn-s3-demo-bucket' -key 'initialize.ps1' -Select *).Owner
```
**出力:**  

```
DisplayName Id
----------- --
testusername      9988776a6554433d22f1100112e334acb45566778899009e9887bd7f66c5f544
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetObjectAcl](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3ObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_powershell_5_topic"></a>

次のコード例は、`Get-S3ObjectLockConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定した S3 バケットのオブジェクトロック設定が有効になっている場合、このコマンドは値「Enabled」を返しま。**  

```
Get-S3ObjectLockConfiguration -BucketName 'amzn-s3-demo-bucket' -Select ObjectLockConfiguration.ObjectLockEnabled
```
**出力:**  

```
Value
-----
Enabled
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetObjectLockConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-S3ObjectMetadata`
<a name="s3_GetObjectMetadata_powershell_5_topic"></a>

次のコード例は、`Get-S3ObjectMetadata` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定された S3 バケット内のキー 「ListTrusts.txt」を含むオブジェクトのメタデータを返します。**  

```
Get-S3ObjectMetadata -BucketName 'amzn-s3-demo-bucket' -Key 'ListTrusts.txt'
```
**出力:**  

```
Headers                                       : Amazon.S3.Model.HeadersCollection
Metadata                                      : Amazon.S3.Model.MetadataCollection
DeleteMarker                                  : 
AcceptRanges                                  : bytes
ContentRange                                  : 
Expiration                                    : 
RestoreExpiration                             : 
RestoreInProgress                             : False
LastModified                                  : 01/01/2020 08:02:05
ETag                                          : "d000011112a222e333e3bb4ee5d43d21"
MissingMeta                                   : 0
VersionId                                     : null
Expires                                       : 01/01/0001 00:00:00
WebsiteRedirectLocation                       : 
ServerSideEncryptionMethod                    : AES256
ServerSideEncryptionCustomerMethod            : 
ServerSideEncryptionKeyManagementServiceKeyId : 
ReplicationStatus                             : 
PartsCount                                    : 
ObjectLockLegalHoldStatus                     : 
ObjectLockMode                                : 
ObjectLockRetainUntilDate                     : 01/01/0001 00:00:00
StorageClass                                  : 
RequestCharged                                :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetObjectMetadata](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3ObjectRetention`
<a name="s3_GetObjectRetention_powershell_5_topic"></a>

次のコード例は、`Get-S3ObjectRetention` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、オブジェクトが保持されるまでのモードと日付を返します。**  

```
Get-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetObjectRetention](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3ObjectTagSet`
<a name="s3_GetObjectTagging_powershell_5_topic"></a>

次のコード例は、`Get-S3ObjectTagSet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した S3 バケット上に存在するオブジェクトに関連付けられたタグを返します。**  

```
Get-S3ObjectTagSet -Key 'testfile.txt' -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Key  Value
---  -----
test value
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetObjectTagging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3PreSignedURL`
<a name="s3_GetPreSignedURL_powershell_5_topic"></a>

次のコード例は、`Get-S3PreSignedURL` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: コマンドは、指定キーと有効期限の署名付き URL を返します。**  

```
Get-S3PreSignedURL -BucketName 'amzn-s3-demo-bucket' -Key 'testkey' -Expires '2023-11-16'
```
**例 2: コマンドは、指定キーと有効期限を持つディレクトリバケットの署名付き URL を返します。**  

```
[Amazon.AWSConfigsS3]::UseSignatureVersion4 = $true
      Get-S3PreSignedURL -BucketName amzn-s3-demo-bucket--usw2-az1--x-s3 -Key 'testkey' -Expire '2023-11-17'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetPreSignedURL](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3PublicAccessBlock`
<a name="s3_GetPublicAccessBlock_powershell_5_topic"></a>

次のコード例は、`Get-S3PublicAccessBlock` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 S3 バケットのパブリックアクセスブロック設定を返します。**  

```
Get-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetPublicAccessBlock](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-S3Version`
<a name="s3_ListVersions_powershell_5_topic"></a>

次のコード例は、`Get-S3Version` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 S3 バケット内のすべてのバージョンのオブジェクトに関するメタデータを返します。**  

```
Get-S3Version -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
IsTruncated         : False
KeyMarker           : 
VersionIdMarker     : 
NextKeyMarker       : 
NextVersionIdMarker : 
Versions            : {EC2.txt, EC2MicrosoftWindowsGuide.txt, ListDirectories.json, ListTrusts.json}
Name                : amzn-s3-demo-bucket
Prefix              : 
MaxKeys             : 1000
CommonPrefixes      : {}
Delimiter           :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListVersions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-S3Bucket`
<a name="s3_PutBucket_powershell_5_topic"></a>

次のコード例は、`New-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、「sample-bucket」という名前の新しいプライベートバケットを作成します。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket
```
**例 2: このコマンドは、読み取り/書き込みアクセス許可を持つ「sample-bucket」という名前の新しいバケットを作成します。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket -PublicReadWrite
```
**例 3: このコマンドは、読み取り専用アクセス許可を持つ「sample-bucket」という名前の新しいバケットを作成します。**  

```
New-S3Bucket -BucketName amzn-s3-demo-bucket -PublicReadOnly
```
**例 4: このコマンドは、PutBucketConfiguration を使用して「amzn-s3-demo-bucket--use1-az5--x-s3」という名前の新しいディレクトリバケットを作成します。**  

```
$bucketConfiguration = @{
      BucketInfo = @{
          DataRedundancy = 'SingleAvailabilityZone'
          Type = 'Directory'
      }
      Location = @{
          Name = 'usw2-az1'
          Type = 'AvailabilityZone'
      }
    }
New-S3Bucket -BucketName amzn-s3-demo-bucket--usw2-az1--x-s3 -BucketConfiguration $bucketConfiguration -Region us-west-2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucket](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Read-S3Object`
<a name="s3_GetObject_powershell_5_topic"></a>

次のコード例は、`Read-S3Object` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、バケット「amzn-s3-demo-bucket」から項目「sample.txt」を取得し、現在の場所の「local-sample.txt」という名前のファイルに保存します。このコマンドを呼び出す前にファイル「local-sample.txt」が存在していなくても構いません。**  

```
Read-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -File local-sample.txt
```
**例 2: このコマンドは、バケット「amzn-s3-demo-bucket」から仮想ディレクトリ「DIR」を取得し、現在の場所の「Local-DIR」という名前のフォルダに保存します。このコマンドを呼び出す前に、フォルダー「Local-DIR」が存在していなくても構いません。**  

```
Read-S3Object -BucketName amzn-s3-demo-bucket -KeyPrefix DIR -Folder Local-DIR
```
**例 3: バケット名に「config」を含むバケットから、キーが「.json」で終わるすべてのオブジェクトを、指定したフォルダ内のファイルにダウンロードします。オブジェクトキーはファイル名の設定に使用されます。**  

```
Get-S3Bucket | ? { $_.BucketName -like '*config*' } | Get-S3Object | ? { $_.Key -like '*.json' } | Read-S3Object -Folder C:\ConfigObjects
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetObject](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3Bucket`
<a name="s3_DeleteBucket_powershell_5_topic"></a>

次のコード例は、`Remove-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、バケット「test-files」からすべてのオブジェクトとオブジェクトバージョンを削除してから、バケットを削除します。このコマンドは、続行する前に確認を求めるプロンプトを表示します。-Force スイッチを追加すると、確認メッセージが表示されなくなります。空でないバケットは削除できないことに注意が必要です。**  

```
Remove-S3Bucket -BucketName amzn-s3-demo-bucket -DeleteBucketContent
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucket](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3BucketAnalyticsConfiguration`
<a name="s3_DeleteBucketAnalyticsConfiguration_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketAnalyticsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケット内の「testfilter」という名前の分析フィルターを削除します。**  

```
Remove-S3BucketAnalyticsConfiguration -BucketName 'amzn-s3-demo-bucket' -AnalyticsId 'testfilter'
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketAnalyticsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-S3BucketEncryption`
<a name="s3_DeleteBucketEncryption_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketEncryption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: これは、指定した S3 バケットで有効になっている暗号化を無効にします。**  

```
Remove-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketEncryption (DeleteBucketEncryption)" on target "s3casetestbucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3BucketInventoryConfiguration`
<a name="s3_DeleteBucketInventoryConfiguration_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketInventoryConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットに対応する「testInventoryName」という名前のインベントリを削除します。**  

```
Remove-S3BucketInventoryConfiguration -BucketName 'amzn-s3-demo-bucket' -InventoryId 'testInventoryName'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketInventoryConfiguration (DeleteBucketInventoryConfiguration)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketInventoryConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-S3BucketMetricsConfiguration`
<a name="s3_DeleteBucketMetricsConfiguration_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketMetricsConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケット内の「testmetrics」という名前のメトリクスフィルターを削除します。**  

```
Remove-S3BucketMetricsConfiguration -BucketName 'amzn-s3-demo-bucket' -MetricsId 'testmetrics'
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketMetricsConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-S3BucketPolicy`
<a name="s3_DeleteBucketPolicy_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketPolicy` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットに関連付けられたバケットポリシーを削除します。**  

```
Remove-S3BucketPolicy -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketPolicy](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3BucketReplication`
<a name="s3_DeleteBucketReplication_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketReplication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットに関連付けられているレプリケーションの設定を削除します。なお、このオペレーションには s3:DeleteReplicationConfiguration アクションに対するアクセス許可が必要です。オペレーションを続行する前に確認を求めるプロンプトが表示されます。プロンプトを表示しないようにするには、-Force スイッチを使用します。**  

```
Remove-S3BucketReplication -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3BucketTagging`
<a name="s3_DeleteBucketTagging_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketTagging` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットに関連付けられたすべてのタグを削除します。**  

```
Remove-S3BucketTagging -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketTagging (DeleteBucketTagging)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3BucketWebsite`
<a name="s3_DeleteBucketWebsite_powershell_5_topic"></a>

次のコード例は、`Remove-S3BucketWebsite` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットの静的ウェブサイトホスティングのプロパティを無効にします。**  

```
Remove-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3BucketWebsite (DeleteBucketWebsite)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3CORSConfiguration`
<a name="s3_DeleteCORSConfiguration_powershell_5_topic"></a>

次のコード例は、`Remove-S3CORSConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットの CORS 設定を削除します。**  

```
Remove-S3CORSConfiguration -BucketName 'amzn-s3-demo-bucket'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3CORSConfiguration (DeleteCORSConfiguration)" on target "amzn-s3-demo-bucket".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteCORSConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3LifecycleConfiguration`
<a name="s3_DeleteLifecycleConfiguration_powershell_5_topic"></a>

次のコード例は、`Remove-S3LifecycleConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: コマンドは、指定 S3 バケットのすべてのライフサイクルルールを削除します。**  

```
Remove-S3LifecycleConfiguration -BucketName 'amzn-s3-demo-bucket'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3MultipartUpload`
<a name="s3_AbortMultipartUpload_powershell_5_topic"></a>

次のコード例は、`Remove-S3MultipartUpload` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、5 日より前に作成されたマルチパートアップロードを中止します。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -DaysBefore 5
```
**例 2: このコマンドは、2014 年 1 月 2 日より前に作成されたマルチパートアップロードを中止します。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -InitiatedDate "Thursday, January 02, 2014"
```
**例 3: このコマンドは、2014 年 1 月 2 日 10:45:37 より前に作成されたマルチパートアップロードを中止します。**  

```
Remove-S3MultipartUpload -BucketName amzn-s3-demo-bucket -InitiatedDate "2014/01/02 10:45:37"
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AbortMultipartUpload](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Remove-S3Object`
<a name="s3_DeleteObjects_powershell_5_topic"></a>

次のコード例は、`Remove-S3Object` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、バケット「test-files」からオブジェクト「sample.txt」を削除します。コマンドを実行する前に、確認を求めるプロンプトが表示されます。-Force スイッチを追加すると、確認メッセージが表示されなくなります。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt
```
**例 2: このコマンドは、指定されたバージョンのオブジェクト「sample.txt」をバケット「test-files」から削除します。これは、バケットがオブジェクトバージョンを有効にするように設定されていることを前提としています。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -Key sample.txt -VersionId HLbxnx6V9omT6AQYVpks8mmFKQcejpqt
```
**例 3: このコマンドは、バケット「test-files」からオブジェクト「sample1.txt」、「sample2.txt」、「sample3.txt」を 1 回のバッチ操作で削除します。このサービスの応答では、削除の成功またはエラーのステータスを問わず、処理されたすべてのキーがリスト表示されます。このサービスで処理できなかったキーのエラーのみを取得するには、-ReportErrorsOnly パラメータを追加します (このパラメータは -Quiet というエイリアスを使用して指定することもできます)。**  

```
Remove-S3Object -BucketName amzn-s3-demo-bucket -KeyCollection @( "sample1.txt", "sample2.txt", "sample3.txt" )
```
**例 4: この例では、-KeyCollection パラメータを指定したインライン式を使用して、削除するオブジェクトのキーを取得します。Get-S3Object は Amazon.S3.Model.S3Object インスタンスのコレクションを返します。各インスタンスには、オブジェクトを識別する文字列型の Key メンバーがあります。**  

```
Remove-S3Object -bucketname "amzn-s3-demo-bucket" -KeyCollection (Get-S3Object "test-files" -KeyPrefix "prefix/subprefix" | select -ExpandProperty Key)
```
**例 5: この例では、バケット内のキープレフィックス「prefix/subprefix」を持つすべてのオブジェクトを取得して削除します。受け取るオブジェクトは一度に 1 つずつ処理されることに注意が必要です。大規模なコレクションの場合は、コレクションをコマンドレットの -InputObject (エイリアスは -S3ObjectCollection) パラメータに渡して、サービスを 1 回呼び出すだけでバッチで削除できるようにすることを検討してください。**  

```
Get-S3Object -BucketName "amzn-s3-demo-bucket" -KeyPrefix "prefix/subprefix" | Remove-S3Object -Force
```
**例 6: この例では、削除マーカーを表す Amazon.S3.Model.S3ObjectVersion インスタンスのコレクションを、削除コマンドレットにパイプします。受け取るオブジェクトは一度に 1 つずつ処理されることに注意が必要です。大規模なコレクションの場合は、コレクションをコマンドレットの -InputObject (エイリアスは -S3ObjectCollection) パラメータに渡して、サービスを 1 回呼び出すだけでバッチで削除できるようにすることを検討してください。**  

```
(Get-S3Version -BucketName "amzn-s3-demo-bucket").Versions | Where {$_.IsDeleteMarker -eq "True"} | Remove-S3Object -Force
```
**例 7: このスクリプトは、-KeyAndVersionCollection パラメータで使用するオブジェクトの配列を作成することで、オブジェクトセット (この場合は削除マーカー) をバッチで削除する方法を示しています。**  

```
$keyVersions = @()
$markers = (Get-S3Version -BucketName $BucketName).Versions | Where {$_.IsDeleteMarker -eq "True"}
foreach ($marker in $markers) { $keyVersions += @{ Key = $marker.Key; VersionId = $marker.VersionId } }
Remove-S3Object -BucketName $BucketName -KeyAndVersionCollection $keyVersions -Force
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteObjects](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3ObjectTagSet`
<a name="s3_DeleteObjectTagging_powershell_5_topic"></a>

次のコード例は、`Remove-S3ObjectTagSet` を使用する方法を示しています。

**Tools for PowerShell V5**  
**このコマンドは、指定した S3 バケット内のキー「testfile.txt」を持つオブジェクトに関連付けられたすべてのタグを削除します。**  

```
Remove-S3ObjectTagSet -Key 'testfile.txt' -BucketName 'amzn-s3-demo-bucket' -Select '^Key'
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-S3ObjectTagSet (DeleteObjectTagging)" on target "testfile.txt".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
testfile.txt
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteObjectTagging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-S3PublicAccessBlock`
<a name="s3_DeletePublicAccessBlock_powershell_5_topic"></a>

次のコード例は、`Remove-S3PublicAccessBlock` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定したバケットのブロックパブリックアクセス設定をオフにします。**  

```
Remove-S3PublicAccessBlock -BucketName 'amzn-s3-demo-bucket' -Force -Select '^BucketName'
```
**出力:**  

```
amzn-s3-demo-bucket
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeletePublicAccessBlock](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Set-S3BucketEncryption`
<a name="s3_PutBucketEncryption_powershell_5_topic"></a>

次のコード例は、`Set-S3BucketEncryption` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定したバケットで Amazon S3 マネージドキー (SSE-S3) を使用したデフォルトの AES256 サーバー側暗号化を有効にします。**  

```
$Encryptionconfig = @{ServerSideEncryptionByDefault = @{ServerSideEncryptionAlgorithm = "AES256"}}
Set-S3BucketEncryption -BucketName 'amzn-s3-demo-bucket' -ServerSideEncryptionConfiguration_ServerSideEncryptionRule $Encryptionconfig
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketEncryption](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Test-S3Bucket`
<a name="s3_Test-S3Bucket_powershell_5_topic"></a>

次のコード例は、`Test-S3Bucket` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、バケットが存在する場合は True を返し、存在しない場合は False を返します。コマンドは、バケットがユーザーに属していない場合でも True を返します。**  

```
Test-S3Bucket -BucketName amzn-s3-demo-bucket
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[Test-S3Bucket](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3BucketAccelerateConfiguration`
<a name="s3_PutBucketAccelerateConfiguration_powershell_5_topic"></a>

次のコード例は、`Write-S3BucketAccelerateConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定 S3 バケットの転送加速を有効にします。**  

```
$statusVal = New-Object Amazon.S3.BucketAccelerateStatus('Enabled')
Write-S3BucketAccelerateConfiguration -BucketName 'amzn-s3-demo-bucket' -AccelerateConfiguration_Status $statusVal
```
+  API の詳細については、**AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketAccelerateConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-S3BucketNotification`
<a name="s3_PutBucketNotification_powershell_5_topic"></a>

次のコード例は、`Write-S3BucketNotification` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、S3 イベント ObjectRemovedDelete の SNS トピック設定を設定して、指定した S3 バケットの通知を有効にします。**  

```
$topic =  [Amazon.S3.Model.TopicConfiguration] @{
  Id = "delete-event"
  Topic = "arn:aws:sns:eu-west-1:123456789012:topic-1"
  Event = [Amazon.S3.EventType]::ObjectRemovedDelete
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -TopicConfiguration $topic
```
**例 2: この例では、指定したバケットの ObjectCreatedAll の通知を有効にして、Lambda 関数に送信します。**  

```
$lambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = "s3:ObjectCreated:*"
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:rdplock"
  Id = "ObjectCreated-Lambda"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".pem"}
      )
    }
  }
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -LambdaFunctionConfiguration $lambdaConfig
```
**例 3: この例では、異なるキーサフィックスに基づいて 2 つの異なる Lambda 設定を作成し、両方を 1 つのコマンドで設定します。**  

```
#Lambda Config 1

$firstLambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = "s3:ObjectCreated:*"
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifynet"
  Id = "ObjectCreated-dada-ps1"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".ps1"}
      )
    }
  }
}

#Lambda Config 2

$secondlambdaConfig = [Amazon.S3.Model.LambdaFunctionConfiguration] @{
  Events = [Amazon.S3.EventType]::ObjectCreatedAll
  FunctionArn = "arn:aws:lambda:eu-west-1:123456789012:function:verifyssm"
  Id = "ObjectCreated-dada-json"
  Filter = @{
    S3KeyFilter = @{
      FilterRules = @(
        @{Name="Prefix";Value="dada"}
        @{Name="Suffix";Value=".json"}
      )
    }
  }
}

Write-S3BucketNotification -BucketName amzn-s3-demo-bucket -LambdaFunctionConfiguration $firstLambdaConfig,$secondlambdaConfig
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketNotification](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3BucketReplication`
<a name="s3_PutBucketReplication_powershell_5_topic"></a>

次のコード例は、`Write-S3BucketReplication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、バケット「amzn-s3-demo-bucket」内のキー名プレフィックス「TaxDocs」で作成された新しいオブジェクトの「amzn-s3-demo-bucket」バケットへのレプリケーションを有効にする単一のルールを使用してレプリケーション設定を指定します。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Enabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1
}

Write-S3BucketReplication @params
```
**例 2: この例では、キー名のプレフィックスが「TaxDocs」または「OtherDocs」の新しく作成されたオブジェクトを、バケット「amzn-s3-demo-bucket」にレプリケートするための複数のルールを使用して、レプリケーション設定を指定します。キーのプレフィックスの重複は許可されません。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Enabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$rule2 = New-Object Amazon.S3.Model.ReplicationRule
$rule2.ID = "Rule-2"
$rule2.Status = "Enabled"
$rule2.Prefix = "OtherDocs"
$rule2.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1,$rule2
}

Write-S3BucketReplication @params
```
**例 3: この例では、指定されたバケットのレプリケーション設定を更新して、「TaxDocs」というキー名のプレフィックスを持つオブジェクトのバケット「amzn-s3-demo-bucket」へのレプリケーションを制御するルールを無効にします。**  

```
$rule1 = New-Object Amazon.S3.Model.ReplicationRule
$rule1.ID = "Rule-1"
$rule1.Status = "Disabled"
$rule1.Prefix = "TaxDocs"
$rule1.Destination = @{ BucketArn = "arn:aws:s3:::amzn-s3-demo-destination-bucket" }
    
$params = @{
    BucketName = "amzn-s3-demo-bucket"
    Configuration_Role = "arn:aws:iam::35667example:role/CrossRegionReplicationRoleForS3"
    Configuration_Rule = $rule1
}

Write-S3BucketReplication @params
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketReplication](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3BucketRequestPayment`
<a name="s3_PutBucketRequestPayment_powershell_5_topic"></a>

次のコード例は、`Write-S3BucketRequestPayment` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「amzn-s3-demo-bucket」という名前のバケットのリクエスト支払い設定を更新して、バケットからのダウンロードをリクエストしたユーザーにダウンロード料金が請求されるようにします。デフォルトでは、バケット所有者がダウンロード料金を支払います。リクエストの支払いをデフォルトに戻すには、RequestPaymentConfiguration\$1Payer パラメーターに「BucketOwner」を使用します。**  

```
Write-S3BucketRequestPayment -BucketName amzn-s3-demo-bucket -RequestPaymentConfiguration_Payer Requester
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketRequestPayment](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3BucketTagging`
<a name="s3_PutBucketTagging_powershell_5_topic"></a>

次のコード例は、`Write-S3BucketTagging` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、`cloudtrail-test-2018` という名前のバケットに 2 つのタグを適用します。1 つは Stage のキーと値が Test のタグで、もう 1 つはキーが Environment で、値は Alpha のタグです。タグがバケットに追加されたことを確認するには、`Get-S3BucketTagging -BucketName bucket_name` を実行します。結果では、最初のコマンドでバケットに適用したタグが表示されるはずです。`Write-S3BucketTagging` は、バケットに設定されている既存のタグセット全体を上書きすることに注意が必要です。個別のタグを追加または削除するには、リソースグループとタグ付けの API コマンドレット、`Add-RGTResourceTag`、`Remove-RGTResourceTag` を実行します。または、 AWS マネジメントコンソールのタグエディタを使用して S3 バケットタグを管理します。**  

```
Write-S3BucketTagging -BucketName amzn-s3-demo-bucket -TagSet @( @{ Key="Stage"; Value="Test" }, @{ Key="Environment"; Value="Alpha" } )
```
**例 2: このコマンドは、バケット `cloudtrail-test-2018` を `Write-S3BucketTagging` コマンドレットにパイプします。これにより、Stage:Production と Department:Finance というタグがバケットに適用されます。`Write-S3BucketTagging` は、バケットに設定されている既存のタグセット全体を上書きすることに注意が必要です。**  

```
Get-S3Bucket -BucketName amzn-s3-demo-bucket | Write-S3BucketTagging -TagSet @( @{ Key="Stage"; Value="Production" }, @{ Key="Department"; Value="Finance" } )
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketTagging](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3BucketVersioning`
<a name="s3_PutBucketVersioning_powershell_5_topic"></a>

次のコード例は、`Write-S3BucketVersioning` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケットのバージョニングを有効にします。**  

```
Write-S3BucketVersioning -BucketName 'amzn-s3-demo-bucket' -VersioningConfig_Status Enabled
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketVersioning](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3BucketWebsite`
<a name="s3_PutBucketWebsite_powershell_5_topic"></a>

次のコード例は、`Write-S3BucketWebsite` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定したバケットのウェブサイトのホスティングを有効にして、インデックスドキュメントを「index.html」、エラードキュメントを「error.html」と指定します。**  

```
Write-S3BucketWebsite -BucketName 'amzn-s3-demo-bucket' -WebsiteConfiguration_IndexDocumentSuffix 'index.html' -WebsiteConfiguration_ErrorDocument 'error.html'
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutBucketWebsite](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3LifecycleConfiguration`
<a name="s3_PutLifecycleConfiguration_powershell_5_topic"></a>

次のコード例は、`Write-S3LifecycleConfiguration` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、\$1NewRule で指定されている設定を書き込み/置き換えます。この設定では、指定のプレフィックスとタグ値を持つスコープオブジェクトを制限します。**  

```
$NewRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  @{
			Days=  50
		}
		Id =  "Test-From-Write-cmdlet-1"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands=  @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "non-use"
							"Value" = "yes"
						}
					}
				)
			}
		}
		"Status"= 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 75
		}
	}
    
	Write-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket -Configuration_Rule $NewRule
```
**例 2: この例では、フィルタリングを使用して複数のルールを設定します。\$1ArchiveRule は、オブジェクトを 30 日後に Glacier にアーカイブし、120 日後に DeepArchive にアーカイブするように設定します。\$1ExpireRule は、「py」プレフィックスと tag:key「archieved」が「yes」に設定されているオブジェクトについて、現在のバージョンと以前のバージョンの両方を 150 日で期限切れにします。**  

```
$ExpireRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  @{
			Days=  150
		}
		Id =  "Remove-in-150-days"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands=  @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "archived"
							"Value" = "yes"
						}
					}
				)
			}
		}
		Status= 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 150
		}
	}

	$ArchiveRule = [Amazon.S3.Model.LifecycleRule] @{
		Expiration =  $null
		Id =  "Archive-to-Glacier-in-30-days"
		Filter=  @{
			LifecycleFilterPredicate =  [Amazon.S3.Model.LifecycleAndOperator]@{
				Operands= @(
					[Amazon.S3.Model.LifecyclePrefixPredicate] @{
						"Prefix" =  "py"
					},
					[Amazon.S3.Model.LifecycleTagPredicate] @{
						"Tag"=  @{
							"Key" =  "reviewed"
							"Value" = "yes"
						}
					}
				)
			}
		}
		Status = 'Enabled'
		NoncurrentVersionExpiration = @{
			NoncurrentDays = 75
		}
		Transitions = @(
			@{
				Days = 30
				"StorageClass"= 'Glacier'
			},
			@{
				Days = 120
				"StorageClass"= [Amazon.S3.S3StorageClass]::DeepArchive
			}
		)
	}

	Write-S3LifecycleConfiguration -BucketName amzn-s3-demo-bucket -Configuration_Rule $ExpireRule,$ArchiveRule
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutLifecycleConfiguration](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3Object`
<a name="s3_PutObject_powershell_5_topic"></a>

次のコード例は、`Write-S3Object` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、単一のファイル「local-sample.txt」を Amazon S3 にアップロードして、バケット「test-files」に「sample.txt」というキーを持つオブジェクトを作成します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "sample.txt" -File .\local-sample.txt
```
**例 2: このコマンドは、単一のファイル「sample.txt」を Amazon S3 にアップロードして、バケット「test-files」に「sample.txt」というキーを持つオブジェクトを作成します。-Key パラメータを指定しない場合、ファイル名が S3 オブジェクトキーとして使用されます。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -File .\sample.txt
```
**例 3: このコマンドは、単一のファイル「local-sample.txt」を Amazon S3 にアップロードして、バケット「test-files」に「prefix/to/sample.txt」というキーを持つオブジェクトを作成します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "prefix/to/sample.txt" -File .\local-sample.txt
```
**例 4: このコマンドは、サブディレクトリ「Scripts」内のすべてのファイルをバケット「test-files」にアップロードして、共通のキープレフィックス「SampleScripts」を各オブジェクトに適用します。アップロードされた各ファイルは「SampleScripts/filename」というキーを持ちます。ただし、「filename」の部分はそれぞれ異なります。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder .\Scripts -KeyPrefix SampleScripts\
```
**例 5: このコマンドは、ローカルディレクトリ「Scripts」内のすべての \$1.ps1 ファイルをバケット「test-files」にアップロードして、共通のキープレフィックス「SampleScripts」を各オブジェクトに適用します。アップロードされた各ファイルは「SampleScripts/filename.ps1」というキーを持ちます。ただし、「filename」の部分はそれぞれ異なります。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder .\Scripts -KeyPrefix SampleScripts\ -SearchPattern *.ps1
```
**例 6: このコマンドは、「sample.txt」というキーを持つ、指定されたコンテンツ文字列を含む新しい S3 オブジェクトを作成します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Key "sample.txt" -Content "object contents"
```
**例 7: このコマンドは、指定したファイル (ファイル名をキーとして使用) をアップロードして、指定したタグを新しいオブジェクトに適用します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -File "sample.txt" -TagSet @{Key="key1";Value="value1"},@{Key="key2";Value="value2"}
```
**例 8: このコマンドは、指定したフォルダを再帰的にアップロードして、指定したタグをすべての新しいオブジェクトに適用します。**  

```
Write-S3Object -BucketName amzn-s3-demo-bucket -Folder . -KeyPrefix "TaggedFiles" -Recurse -TagSet @{Key="key1";Value="value1"},@{Key="key2";Value="value2"}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutObject](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-S3ObjectRetention`
<a name="s3_PutObjectRetention_powershell_5_topic"></a>

次のコード例は、`Write-S3ObjectRetention` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、指定した S3 バケット内の「testfile.txt」オブジェクトの期限日「2019 年 12 月 31 日 00:00:00」までガバナンス保持モードを有効にします。**  

```
Write-S3ObjectRetention -BucketName 'amzn-s3-demo-bucket' -Key 'testfile.txt' -Retention_Mode GOVERNANCE -Retention_RetainUntilDate "2019-12-31T00:00:00"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutObjectRetention](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Security Hub CSPM の例
<a name="powershell_5_securityhub_code_examples"></a>

次のコード例は、Security Hub CSPM で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-SHUBFinding`
<a name="securityhub_GetSHUBFinding_powershell_5_topic"></a>

次のコード例は、`Get-SHUBFinding` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、Amazon EC2; サービスから Security Hub の検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.ResourceType = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'PREFIX'
    Value = 'AwsEc2'
}
Get-SHUBFinding -Filter $filter
```
**例 2: このコマンドは、 AWS アカウント ID 123456789012 から Security Hub の検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.AwsAccountId = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = '123456789012'
}
Get-SHUBFinding -Filter $filter
```
**例 3: このコマンドは、標準の「pci-dss」用に生成された Security Hub の検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.GeneratorId = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'PREFIX'
    Value = 'pci-dss'
}
Get-SHUBFinding -Filter $filter
```
**例 4: このコマンドは、ワークフローステータスが NOTIFIED である Security Hub の、重要度が重大である検出結果を取得します。**  

```
$filter = New-Object -TypeName Amazon.SecurityHub.Model.AwsSecurityFindingFilters
$filter.SeverityLabel = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = 'CRITICAL'
}
$filter.WorkflowStatus = New-Object -TypeName Amazon.SecurityHub.Model.StringFilter -Property @{
    Comparison = 'EQUALS'
    Value = 'NOTIFIED'
}
Get-SHUBFinding -Filter $filter
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetFindings](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon SES の例
<a name="powershell_5_ses_code_examples"></a>

次のコード例は、Amazon SES で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Get-SESIdentity`
<a name="ses_ListIdentities_powershell_5_topic"></a>

次のコード例は、`Get-SESIdentity` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、検証ステータスに関係なく、特定の AWS アカウントのすべての ID (E メールアドレスとドメイン) を含むリストを返します。**  

```
Get-SESIdentity
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListIdentities](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SESSendQuota`
<a name="ses_GetSendQuota_powershell_5_topic"></a>

次のコード例は、`Get-SESSendQuota` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、ユーザーの現在の送信制限を返します。**  

```
Get-SESSendQuota
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetSendQuota](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SESSendStatistic`
<a name="ses_GetSendStatistics_powershell_5_topic"></a>

次のコード例は、`Get-SESSendStatistic` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、ユーザーの統計の送信を返します。結果は、送信アクティビティの最新の 2 週間を示すデータポイントのリストです。このリスト内の各データポイントには、15 分間隔の統計が含まれます。**  

```
Get-SESSendStatistic
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetSendStatistics](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon SES API v2 の例
<a name="powershell_5_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Send-SES2Email`
<a name="sesv2_SendSES2Email_powershell_5_topic"></a>

次のコード例は、`Send-SES2Email` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、標準の E メールメッセージを送信する方法を示します。**  

```
Send-SES2Email -FromEmailAddress "sender@example.com" -Destination_ToAddress "recipient@example.com" -Subject_Data "Email Subject" -Text_Data "Email Body"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SendEmail](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon SNS の例
<a name="powershell_5_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Publish-SNSMessage`
<a name="sns_Publish_powershell_5_topic"></a>

次のコード例は、`Publish-SNSMessage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インラインで宣言された単一の MessageAttribute を使用してメッセージを発行しています。**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**例 2: この例では、事前に宣言された複数の MessageAttribute を使用してメッセージを発行しています。**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[Publish](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon SQS の例
<a name="powershell_5_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-SQSPermission`
<a name="sqs_AddPermission_powershell_5_topic"></a>

次のコード例は、`Add-SQSPermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された が指定されたキューからメッセージを送信 AWS アカウント することを許可します。**  

```
Add-SQSPermission -Action SendMessage -AWSAccountId 80398EXAMPLE -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AddPermission](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Clear-SQSQueue`
<a name="sqs_PurgeQueue_powershell_5_topic"></a>

次のコード例は、`Clear-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したキューからすべてのメッセージを削除します。**  

```
Clear-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PurgeQueue](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-SQSMessageVisibility`
<a name="sqs_ChangeMessageVisibility_powershell_5_topic"></a>

次のコード例は、`Edit-SQSMessageVisibility` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したキュー内の指定した受信ハンドルを持つメッセージの可視性タイムアウトを 10 時間 (10 時間 × 60 分 × 60 秒 = 36,000 秒) に変更します。**  

```
Edit-SQSMessageVisibility -QueueUrl https://sqs.us-east-1.amazonaws.com/8039EXAMPLE/MyQueue -ReceiptHandle AQEBgGDh...J/Iqww== -VisibilityTimeout 36000
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ChangeMessageVisibility](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-SQSMessageVisibilityBatch`
<a name="sqs_ChangeMessageVisibilityBatch_powershell_5_topic"></a>

次のコード例は、`Edit-SQSMessageVisibilityBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したキュー内の指定した受信ハンドルを持つ 2 つのメッセージの可視性タイムアウトを変更します。最初のメッセージの可視性タイムアウトを 10 時間 (10 時間 × 60 分 × 60 秒 = 36,000 秒) に変更します。2 番目のメッセージの可視性タイムアウトを 5 時間 (5 時間 × 60 分 × 60 秒 = 18,000 秒) に変更します。**  

```
$changeVisibilityRequest1 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry
$changeVisibilityRequest1.Id = "Request1"
$changeVisibilityRequest1.ReceiptHandle = "AQEBd329...v6gl8Q=="
$changeVisibilityRequest1.VisibilityTimeout = 36000

$changeVisibilityRequest2 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry
$changeVisibilityRequest2.Id = "Request2"
$changeVisibilityRequest2.ReceiptHandle = "AQEBgGDh...J/Iqww=="
$changeVisibilityRequest2.VisibilityTimeout = 18000

Edit-SQSMessageVisibilityBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $changeVisibilityRequest1, $changeVisibilityRequest2
```
**出力:**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {Request2, Request1}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ChangeMessageVisibilityBatch](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SQSDeadLetterSourceQueue`
<a name="sqs_ListDeadLetterSourceQueues_powershell_5_topic"></a>

次のコード例は、`Get-SQSDeadLetterSourceQueue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、デッドレターキューとして指定したキューに依存するすべてのキューの URL を一覧表示します。**  

```
Get-SQSDeadLetterSourceQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListDeadLetterSourceQueues](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SQSQueue`
<a name="sqs_ListQueues_powershell_5_topic"></a>

次のコード例は、`Get-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべてのキューを一覧表示します。**  

```
Get-SQSQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/AnotherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/DeadLetterQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
**例 2: この例では、指定した名前で始まるすべてのキューを一覧表示します。**  

```
Get-SQSQueue -QueueNamePrefix My
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListQueues](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SQSQueueAttribute`
<a name="sqs_GetQueueAttributes_powershell_5_topic"></a>

次のコード例は、`Get-SQSQueueAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したキューのすべての属性を一覧表示します。**  

```
Get-SQSQueueAttribute -AttributeName All -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
VisibilityTimeout                     : 30
DelaySeconds                          : 0
MaximumMessageSize                    : 262144
MessageRetentionPeriod                : 345600
ApproximateNumberOfMessages           : 0
ApproximateNumberOfMessagesNotVisible : 0
ApproximateNumberOfMessagesDelayed    : 0
CreatedTimestamp                      : 2/11/2015 5:53:35 PM
LastModifiedTimestamp                 : 12/29/2015 2:23:17 PM
QueueARN                              : arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue
Policy                                : {"Version":"2012-10-17",		 	 	 "Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/SQSDefaultPolicy","Statement":[{"Sid":"Sid14
                                        495134224EX","Effect":"Allow","Principal":{"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80
                                        398EXAMPLE:MyQueue","Condition":{"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}},{"Sid":
                                        "SendMessagesFromMyQueue","Effect":"Allow","Principal":{"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":"
                                        arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue"}]}
Attributes                            : {[QueueArn, arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue], [ApproximateNumberOfMessages, 0], 
                                        [ApproximateNumberOfMessagesNotVisible, 0], [ApproximateNumberOfMessagesDelayed, 0]...}
```
**例 2: この例では、指定したキューの指定した属性のみを別個に一覧表示します。**  

```
Get-SQSQueueAttribute -AttributeName MaximumMessageSize, VisibilityTimeout -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
VisibilityTimeout                     : 30
DelaySeconds                          : 0
MaximumMessageSize                    : 262144
MessageRetentionPeriod                : 345600
ApproximateNumberOfMessages           : 0
ApproximateNumberOfMessagesNotVisible : 0
ApproximateNumberOfMessagesDelayed    : 0
CreatedTimestamp                      : 2/11/2015 5:53:35 PM
LastModifiedTimestamp                 : 12/29/2015 2:23:17 PM
QueueARN                              : arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue
Policy                                : {"Version":"2012-10-17",		 	 	 "Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/SQSDefaultPolicy","Statement":[{"Sid":"Sid14
                                        495134224EX","Effect":"Allow","Principal":{"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80
                                        398EXAMPLE:MyQueue","Condition":{"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}},{"Sid":
                                        "SendMessagesFromMyQueue","Effect":"Allow","Principal":{"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":"
                                        arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue"}]}
Attributes                            : {[MaximumMessageSize, 262144], [VisibilityTimeout, 30]}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetQueueAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SQSQueueUrl`
<a name="sqs_GetQueueUrl_powershell_5_topic"></a>

次のコード例は、`Get-SQSQueueUrl` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した名前のキューの URL を表示します。**  

```
Get-SQSQueueUrl -QueueName MyQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetQueueUrl](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-SQSQueue`
<a name="sqs_CreateQueue_powershell_5_topic"></a>

次のコード例は、`New-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した名前でキューを作成します。**  

```
New-SQSQueue -QueueName MyQueue
```
**出力:**  

```
https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateQueue](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Receive-SQSMessage`
<a name="sqs_ReceiveMessage_powershell_5_topic"></a>

次のコード例は、`Receive-SQSMessage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したキューで次に受信する 10 件までのメッセージに関する情報を表示します。情報には、指定したメッセージ属性 (存在する場合) の値が含まれます。**  

```
Receive-SQSMessage -AttributeName SenderId, SentTimestamp -MessageAttributeName StudentName, StudentGrade -MessageCount 10 -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
Attributes             : {[SenderId, AIDAIAZKMSNQ7TEXAMPLE], [SentTimestamp, 1451495923744]}
Body                   : Information about John Doe's grade.
MD5OfBody              : ea572796e3c231f974fe75d89EXAMPLE
MD5OfMessageAttributes : 48c1ee811f0fe7c4e88fbe0f5EXAMPLE
MessageAttributes      : {[StudentGrade, Amazon.SQS.Model.MessageAttributeValue], [StudentName, Amazon.SQS.Model.MessageAttributeValue]}
MessageId              : 53828c4b-631b-469b-8833-c093cEXAMPLE
ReceiptHandle          : AQEBpfGp...20Q5cg==
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ReceiveMessage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SQSMessage`
<a name="sqs_DeleteMessage_powershell_5_topic"></a>

次のコード例は、`Remove-SQSMessage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した受信ハンドルを持つメッセージを指定したキューから削除します。**  

```
Remove-SQSMessage -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -ReceiptHandle AQEBd329...v6gl8Q==
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteMessage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SQSMessageBatch`
<a name="sqs_DeleteMessageBatch_powershell_5_topic"></a>

次のコード例は、`Remove-SQSMessageBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した受信ハンドルを持つ 2 つのメッセージを指定したキューから削除します。**  

```
$deleteMessageRequest1 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry
$deleteMessageRequest1.Id = "Request1"
$deleteMessageRequest1.ReceiptHandle = "AQEBX2g4...wtJSQg=="

$deleteMessageRequest2 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry
$deleteMessageRequest2.Id = "Request2"
$deleteMessageRequest2.ReceiptHandle = "AQEBqOVY...KTsLYg=="

Remove-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $deleteMessageRequest1, $deleteMessageRequest2
```
**出力:**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {Request1, Request2}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteMessageBatch](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SQSPermission`
<a name="sqs_RemovePermission_powershell_5_topic"></a>

次のコード例は、`Remove-SQSPermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定したラベルを持つアクセス許可設定を、指定したキューから削除します。**  

```
Remove-SQSPermission -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemovePermission](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SQSQueue`
<a name="sqs_DeleteQueue_powershell_5_topic"></a>

次のコード例は、`Remove-SQSQueue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: こので例は、指定したキューを削除します。**  

```
Remove-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteQueue](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Send-SQSMessage`
<a name="sqs_SendMessage_powershell_5_topic"></a>

次のコード例は、`Send-SQSMessage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した属性とメッセージ本文を持つメッセージを指定したキューに送信し、メッセージの配信を 10 秒遅延させます。**  

```
$cityAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Send-SQSMessage -DelayInSeconds 10 -MessageAttributes $messageAttributes -MessageBody "Information about the largest city in Any Region." -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
**出力:**  

```
MD5OfMessageAttributes              MD5OfMessageBody                    MessageId                                          
----------------------              ----------------                    ---------                                          
1d3e51347bc042efbdf6dda31EXAMPLE    51b0a3256d59467f973009b73EXAMPLE    c35fed8f-c739-4d0c-818b-1820eEXAMPLE
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SendMessage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Send-SQSMessageBatch`
<a name="sqs_SendMessageBatch_powershell_5_topic"></a>

次のコード例は、`Send-SQSMessageBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定した属性とメッセージ本文を持つ 2 つのメッセージを指定したキューに送信します。最初のメッセージでは配信を 15 秒遅延させ、2 番目のメッセージでは配信を 10 秒遅延させます。**  

```
$student1NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student1NameAttributeValue.DataType = "String"
$student1NameAttributeValue.StringValue = "John Doe"

$student1GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student1GradeAttributeValue.DataType = "Number"
$student1GradeAttributeValue.StringValue = "89"

$student2NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student2NameAttributeValue.DataType = "String"
$student2NameAttributeValue.StringValue = "Jane Doe"

$student2GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue
$student2GradeAttributeValue.DataType = "Number"
$student2GradeAttributeValue.StringValue = "93"

$message1 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry 
$message1.DelaySeconds = 15
$message1.Id = "FirstMessage"
$message1.MessageAttributes.Add("StudentName", $student1NameAttributeValue)
$message1.MessageAttributes.Add("StudentGrade", $student1GradeAttributeValue)
$message1.MessageBody = "Information about John Doe's grade."

$message2 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry 
$message2.DelaySeconds = 10
$message2.Id = "SecondMessage"
$message2.MessageAttributes.Add("StudentName", $student2NameAttributeValue)
$message2.MessageAttributes.Add("StudentGrade", $student2GradeAttributeValue)
$message2.MessageBody = "Information about Jane Doe's grade."

Send-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $message1, $message2
```
**出力:**  

```
Failed    Successful                                                                    
------    ----------                                                                    
{}        {FirstMessage, SecondMessage}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SendMessageBatch](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Set-SQSQueueAttribute`
<a name="sqs_SetQueueAttributes_powershell_5_topic"></a>

次のコード例は、`Set-SQSQueueAttribute` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、キューを SNS トピックにサブスクライブするポリシーを設定する方法を示します。メッセージをトピックに発行すると、メッセージはサブスクライブしたキューに送信されます。**  

```
# create the queue and topic to be associated
$qurl = New-SQSQueue -QueueName "myQueue"
$topicarn = New-SNSTopic -Name "myTopic"

# get the queue ARN to inject into the policy; it will be returned
# in the output's QueueARN member but we need to put it into a variable
# so text expansion in the policy string takes effect
$qarn = (Get-SQSQueueAttribute -QueueUrl $qurl -AttributeName "QueueArn").QueueARN

# construct the policy and inject arns
$policy = @"
{
  "Version":"2012-10-17",		 	 	 
  "Id": "$qarn/SQSPOLICY",
  "Statement": [
      {
      "Sid": "1",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "SQS:SendMessage",
      "Resource": "$qarn",
      "Condition": {
        "ArnEquals": {
          "aws:SourceArn": "$topicarn"
          }
      }
    }
  ]
}
"@

# set the policy
Set-SQSQueueAttribute -QueueUrl $qurl -Attribute @{ Policy=$policy }
```
**例 2: この例では、指定したキューに指定した属性を設定します。**  

```
Set-SQSQueueAttribute -Attribute @{"DelaySeconds" = "10"; "MaximumMessageSize" = "131072"} -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[SetQueueAttributes](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

# AWS STS Tools for PowerShell V5 を使用した の例
<a name="powershell_5_sts_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Convert-STSAuthorizationMessage`
<a name="sts_DecodeAuthorizationMessage_powershell_5_topic"></a>

次のコード例は、`Convert-STSAuthorizationMessage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: リクエストへの応答として返された、指定されたエンコード済みメッセージコンテンツに含まれる追加情報をデコードします。承認ステータスの詳細は、アクションをリクエストしたユーザーが見てはならない特権情報である可能性があるため、追加情報はエンコードされます。**  

```
Convert-STSAuthorizationMessage -EncodedMessage "...encoded message..."
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DecodeAuthorizationMessage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-STSFederationToken`
<a name="sts_GetFederationToken_powershell_5_topic"></a>

次のコード例は、`Get-STSFederationToken` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 「Bob」をフェデレーションユーザーの名前として使用して、1 時間有効なフェデレーショントークンをリクエストします。この名前は、リソースベースのポリシー (Amazon S3 バケットポリシーなど) のフェデレーションユーザー名を参照するために使用できます。提供される JSON 形式の IAM ポリシーを使用して、IAM ユーザーが利用できるアクセス権限の範囲を絞り込みます。指定されたポリシーでは、リクエストしたユーザーに付与されたアクセス権限よりも多くのアクセス権限を付与することはできません。フェデレーションユーザーの最終的なアクセス権限は、渡されたポリシーと IAM ユーザーポリシーの共通部分に基づいて最も制限の厳しい一式となります。**  

```
Get-STSFederationToken -Name "Bob" -Policy "...JSON policy..." -DurationInSeconds 3600
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetFederationToken](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-STSSessionToken`
<a name="sts_GetSessionToken_powershell_5_topic"></a>

次のコード例は、`Get-STSSessionToken` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 一定期間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。一時的な認証情報をリクエストするために使用される認証情報は、現在のシェルのデフォルトから推測されます。他の認証情報を指定するには、-ProfileName または-AccessKey/-SecretKey パラメータを使用します。**  

```
Get-STSSessionToken
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 2: 1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。リクエストを行うために使用される認証情報は、指定されたプロファイルから取得されます。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
**例 3: プロファイル「myprofilename」で認証情報が指定されているアカウントに関連付けられた MFA デバイスの識別番号とデバイスから提供された値を使用して、1 時間有効な一時的な認証情報を含む `Amazon.RuntimeAWSCredentials` インスタンスを返します。**  

```
Get-STSSessionToken -DurationInSeconds 3600 -ProfileName myprofile -SerialNumber YourMFADeviceSerialNumber -TokenCode 123456
```
**出力:**  

```
AccessKeyId                             Expiration                              SecretAccessKey                        SessionToken
-----------                             ----------                              ---------------                        ------------
EXAMPLEACCESSKEYID                      2/16/2015 9:12:28 PM                    examplesecretaccesskey...              SamPleTokeN.....
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetSessionToken](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Use-STSRole`
<a name="sts_AssumeRole_powershell_5_topic"></a>

次のコード例は、`Use-STSRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: リクエスト元のユーザーが通常アクセスできない AWS リソースにアクセスするために 1 時間使用できる一時的な認証情報 (アクセスキー、シークレットキー、セッショントークン) のセットを返します。返される認証情報には、引き受けているロールのアクセスポリシーと提供されたポリシーで許可されている権限があります (提供されたポリシーを使用して、引き受けているロールのアクセスポリシーで定義されている権限を超える権限を付与することはできません)。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -Policy "...JSON policy..." -DurationInSeconds 3600
```
**例 2: 引き受けているロールのアクセスポリシーで定義されているのと同じ権限を持つ、1 時間有効の一時的な認証情報を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600
```
**例 3: コマンドレットの実行に使用されるユーザー認証情報に関連付けられている MFA からシリアル番号と生成されたトークンを提供する一時的な認証情報一式を返します。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -SerialNumber "GAHT12345678" -TokenCode "123456"
```
**例 4: 顧客アカウントで定義されているロールを引き受けた一時的な認証情報一式を返します。第三者が引き受けることができるロールごとに、顧客アカウントは、ロールを引き受けるたび、-ExternalId パラメータで渡す必要がある識別子を使用してロールを作成する必要があります。**  

```
Use-STSRole -RoleSessionName "Bob" -RoleArn "arn:aws:iam::123456789012:role/demo" -DurationInSeconds 3600 -ExternalId "ABC123"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AssumeRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Use-STSWebIdentityRole`
<a name="sts_AssumeRoleWithWebIdentity_powershell_5_topic"></a>

次のコード例は、`Use-STSWebIdentityRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: Login with Amazon ID プロバイダーで認証されたユーザーの一時的な認証情報一式 (1 時間有効) を返します。認証情報は、ロール ARN によって識別されるロールに関連付けられたアクセスポリシーを引き受けます。オプションで、JSON ポリシーを-Policy パラメータに渡して、アクセス権限をさらに絞り込むことができます (ロールに関連付けられている権限で使用可能な権限よりも多くの権限を付与することはできません)。-WebIdentityToken に渡される値は、ID プロバイダーから返された一意のユーザー識別子です。**  

```
Use-STSWebIdentityRole -DurationInSeconds 3600 -ProviderId "www.amazon.com" -RoleSessionName "app1" -RoleArn "arn:aws:iam::123456789012:role/FederatedWebIdentityRole" -WebIdentityToken "Atza...DVI0r1"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AssumeRoleWithWebIdentity](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# サポート Tools for PowerShell V5 を使用した の例
<a name="powershell_5_support_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-ASACommunicationToCase`
<a name="support_AddCommunicationToCase_powershell_5_topic"></a>

次のコード例は、`Add-ASACommunicationToCase` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定したケースに E メールの本文を追加します。**  

```
Add-ASACommunicationToCase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -CommunicationBody "Some text about the case"
```
**例 2: 指定されたケースに E メールの本文と、E メールの CC 行に含まれる 1 つ以上の E メールアドレスを追加します。**  

```
Add-ASACommunicationToCase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -CcEmailAddress @("email1@address.com", "email2@address.com") -CommunicationBody "Some text about the case"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AddCommunicationToCase](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASACase`
<a name="support_DescribeCases_powershell_5_topic"></a>

次のコード例は、`Get-ASACase` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべてのサポートケースの詳細を返します。**  

```
Get-ASACase
```
**例 2: 指定された日時以降のすべてのサポートケースの詳細を返します。**  

```
Get-ASACase -AfterTime "2013-09-10T03:06Z"
```
**例 3: 解決済みのサポートケースを含め、最初の 10 件のサポートケースの詳細を返します。**  

```
Get-ASACase -MaxResult 10 -IncludeResolvedCases $true
```
**例 4: 単一の指定されたサポートケースの詳細を返します。**  

```
Get-ASACase -CaseIdList "case-12345678910-2013-c4c1d2bf33c5cf47"
```
**例 5: 指定されたサポートケースの詳細を返します。**  

```
Get-ASACase -CaseIdList @("case-12345678910-2013-c4c1d2bf33c5cf47", "case-18929034710-2011-c4fdeabf33c5cf47")
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeCases](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASACommunication`
<a name="support_DescribeCommunications_powershell_5_topic"></a>

次のコード例は、`Get-ASACommunication` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたケースのすべてのコミュニケーションを返します。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
**例 2: 指定されたケースについて、2012 年 1 月 1 日の午前 0 時 (UTC) 以降のすべてのコミュニケーションを返します。**  

```
Get-ASACommunication -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47" -AfterTime "2012-01-10T00:00Z"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeCommunications](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASAService`
<a name="support_DescribeServices_powershell_5_topic"></a>

次のコード例は、`Get-ASAService` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 使用可能なすべてのサービスコード、名前、カテゴリを返します。**  

```
Get-ASAService
```
**例 2: 指定されたコードを持つサービスの名前とカテゴリを返します。**  

```
Get-ASAService -ServiceCodeList "amazon-cloudfront"
```
**例 3: 指定されたサービスコードの名前とカテゴリを返します。**  

```
Get-ASAService -ServiceCodeList @("amazon-cloudfront", "amazon-cloudwatch")
```
**例 4: 指定されたサービスコードの名前とカテゴリ (日本語) を返します。現在、英語 (「en」) と日本語 (「ja」) の言語コードがサポートされています。**  

```
Get-ASAService -ServiceCodeList @("amazon-cloudfront", "amazon-cloudwatch") -Language "ja"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeServices](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASASeverityLevel`
<a name="support_DescribeSeverityLevels_powershell_5_topic"></a>

次のコード例は、`Get-ASASeverityLevel` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: AWS サポートケースに割り当てることができる重要度レベルのリストを返します。**  

```
Get-ASASeverityLevel
```
**例 2: AWS サポートケースに割り当てることができる重要度レベルのリストを返します。レベルの名前は日本語で返されます。**  

```
Get-ASASeverityLevel -Language "ja"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeSeverityLevels](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASATrustedAdvisorCheck`
<a name="support_DescribeTrustedAdvisorChecks_powershell_5_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheck` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: Trusted Advisor チェックのコレクションを返します。英語出力の場合は「en」、日本語出力の場合は「ja」のいずれかを使用できる Language パラメータを指定する必要があります。**  

```
Get-ASATrustedAdvisorCheck -Language "en"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTrustedAdvisorChecks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASATrustedAdvisorCheckRefreshStatus`
<a name="support_DescribeTrustedAdvisorCheckRefreshStatuses_powershell_5_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheckRefreshStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたチェックの更新リクエストの現在のステータスを返します。Request-ASATrustedAdvisorCheckRefresh を使用して、チェックのステータス情報の更新をリクエストできます。**  

```
Get-ASATrustedAdvisorCheckRefreshStatus -CheckId @("checkid1", "checkid2")
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTrustedAdvisorCheckRefreshStatuses](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASATrustedAdvisorCheckResult`
<a name="support_DescribeTrustedAdvisorCheckResult_powershell_5_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheckResult` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: Trusted Advisor チェックの結果を返します。利用可能な Trusted Advisor チェックのリストは、Get-ASATrustedAdvisorChecks を使用して取得できます。出力は、チェックの全体的なステータス、最後のチェック実行時のタイムスタンプ、および特定のチェックの一意のチェック ID です。結果を日本語で出力するには、-Language「ja」パラメータを追加します。**  

```
Get-ASATrustedAdvisorCheckResult -CheckId "checkid1"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTrustedAdvisorCheckResult](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-ASATrustedAdvisorCheckSummary`
<a name="support_DescribeTrustedAdvisorCheckSummaries_powershell_5_topic"></a>

次のコード例は、`Get-ASATrustedAdvisorCheckSummary` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された Trusted Advisor チェックの最新の概要を返します。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId "checkid1"
```
**例 2: 指定された Trusted Advisor チェックの最新の概要を返します。**  

```
Get-ASATrustedAdvisorCheckSummary -CheckId @("checkid1", "checkid2")
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTrustedAdvisorCheckSummaries](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-ASACase`
<a name="support_CreateCase_powershell_5_topic"></a>

次のコード例は、`New-ASACase` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: AWS サポートセンターで新しいケースを作成します。-ServiceCode および -CategoryCode パラメータの値は、Get-ASAService コマンドレットを使用して取得できます。-SeverityCode パラメータの値は、Get-ASASeverityLevel コマンドレットを使用して取得できます。-IssueType パラメータ値は、「customer-service」または「technical」のいずれかです。成功すると、 AWS サポートケース番号が出力されます。デフォルトでは、ケースは英語で処理され、日本語を使用するには、-Language「ja」パラメータを追加します。-ServiceCode、-CategoryCode、-Subject、-CommunicationBody パラメータは必須です。**  

```
New-ASACase -ServiceCode "amazon-cloudfront" -CategoryCode "APIs" -SeverityCode "low" -Subject "subject text" -CommunicationBody "description of the case" -CcEmailAddress @("email1@domain.com", "email2@domain.com") -IssueType "technical"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateCase](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Request-ASATrustedAdvisorCheckRefresh`
<a name="support_RefreshTrustedAdvisorCheck_powershell_5_topic"></a>

次のコード例は、`Request-ASATrustedAdvisorCheckRefresh` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された Trusted Advisor チェックの更新をリクエストします。**  

```
Request-ASATrustedAdvisorCheckRefresh -CheckId "checkid1"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RefreshTrustedAdvisorCheck](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Resolve-ASACase`
<a name="support_ResolveCase_powershell_5_topic"></a>

次のコード例は、`Resolve-ASACase` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたケースの初期状態と、解決のための呼び出しが完了した後の現在の状態を返します。**  

```
Resolve-ASACase -CaseId "case-12345678910-2013-c4c1d2bf33c5cf47"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ResolveCase](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Systems Manager の例
<a name="powershell_5_ssm_code_examples"></a>

次のコード例は、Systems Manager で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Add-SSMResourceTag`
<a name="ssm_AddTagsToResource_powershell_5_topic"></a>

次のコード例は、`Add-SSMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しいタグを使用してメンテナンスウィンドウを更新します。コマンドが成功した場合、出力はありません。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$option1 = @{Key="Stack";Value=@("Production")}
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $option1
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して各タグを作成する必要があります。コマンドが成功した場合、出力はありません。**  

```
$tag1 = New-Object Amazon.SimpleSystemsManagement.Model.Tag
$tag1.Key = "Stack"
$tag1.Value = "Production"
		
Add-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -Tag $tag1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AddTagsToResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Edit-SSMDocumentPermission`
<a name="ssm_ModifyDocumentPermission_powershell_5_topic"></a>

次のコード例は、`Edit-SSMDocumentPermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ドキュメントのすべてのアカウントに「共有」アクセス許可を追加します。コマンドが成功した場合、出力はありません。**  

```
Edit-SSMDocumentPermission -Name "RunShellScript" -PermissionType "Share" -AccountIdsToAdd all
```
**例 2: この例では、ドキュメントの特定のアカウントに「共有」アクセス許可を追加します。コマンドが成功した場合、出力はありません。**  

```
Edit-SSMDocumentPermission -Name "RunShellScriptNew" -PermissionType "Share" -AccountIdsToAdd "123456789012"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ModifyDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMActivation`
<a name="ssm_DescribeActivations_powershell_5_topic"></a>

次のコード例は、`Get-SSMActivation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントのアクティベーションに関する詳細情報を示します。**  

```
Get-SSMActivation
```
**出力:**  

```
ActivationId        : 08e51e79-1e36-446c-8e63-9458569c1363
CreatedDate         : 3/1/2017 12:01:51 AM
DefaultInstanceName : MyWebServers
Description         :
ExpirationDate      : 3/2/2017 12:01:51 AM
Expired             : False
IamRole             : AutomationRole
RegistrationLimit   : 10
RegistrationsCount  : 0
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeActivations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAssociation`
<a name="ssm_DescribeAssociation_powershell_5_topic"></a>

次のコード例は、`Get-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスとドキュメントの関連付けを記述します。**  

```
Get-SSMAssociation -InstanceId "i-0000293ffd8c57862" -Name "AWS-UpdateSSMAgent"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temp_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeAssociation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAssociationExecution`
<a name="ssm_DescribeAssociationExecutions_powershell_5_topic"></a>

次のコード例は、`Get-SSMAssociationExecution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された関連付け ID の実行を返します。**  

```
Get-SSMAssociationExecution -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**出力:**  

```
AssociationId         : 123a45a0-c678-9012-3456-78901234db5e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 123a45a0-c678-9012-3456-78901234db5e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=4}
Status                : Success
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeAssociationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAssociationExecutionTarget`
<a name="ssm_DescribeAssociationExecutionTargets_powershell_5_topic"></a>

次のコード例は、`Get-SSMAssociationExecutionTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、関連付けの実行ターゲットの一部であるリソース ID とその実行ステータスを表示します。**  

```
Get-SSMAssociationExecutionTarget -AssociationId 123a45a0-c678-9012-3456-78901234db5e -ExecutionId 123a45a0-c678-9012-3456-78901234db5e | Select-Object ResourceId, Status
```
**出力:**  

```
ResourceId           Status
----------           ------
i-0b1b2a3456f7a890b  Success
i-01c12a45d6fc7a89f  Success
i-0a1caf234f56d7dc8  Success
i-012a3fd45af6dbcfe  Failed
i-0ddc1df23c4a5fb67  Success
```
**例 2: このコマンドは、コマンドドキュメントが関連付けられている昨日以降の特定のオートメーションにおける、特定の実行をチェックします。さらに、関連付けの実行が失敗したかどうかを確認し、失敗した場合は、実行のコマンド呼び出しの詳細情報とインスタンス ID が表示されます。**  

```
$AssociationExecution= Get-SSMAssociationExecutionTarget -AssociationId 1c234567-890f-1aca-a234-5a678d901cb0 -ExecutionId 12345ca12-3456-2345-2b45-23456789012 | 
    Where-Object {$_.LastExecutionDate -gt (Get-Date -Hour 00 -Minute 00).AddDays(-1)} 

foreach ($execution in $AssociationExecution) {
    if($execution.Status -ne 'Success'){
        Write-Output "There was an issue executing the association $($execution.AssociationId) on $($execution.ResourceId)"
        Get-SSMCommandInvocation -CommandId $execution.OutputSource.OutputSourceId -Detail:$true | Select-Object -ExpandProperty CommandPlugins
    }
}
```
**出力:**  

```
There was an issue executing the association 1c234567-890f-1aca-a234-5a678d901cb0 on i-0a1caf234f56d7dc8


Name                   : aws:runPowerShellScript
Output                 : 
                         ----------ERROR-------
                         failed to run commands: exit status 1
OutputS3BucketName     : 
OutputS3KeyPrefix      : 
OutputS3Region         : eu-west-1
ResponseCode           : 1
ResponseFinishDateTime : 5/29/2019 11:04:49 AM
ResponseStartDateTime  : 5/29/2019 11:04:49 AM
StandardErrorUrl       : 
StandardOutputUrl      : 
Status                 : Failed
StatusDetails          : Failed
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeAssociationExecutionTargets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAssociationList`
<a name="ssm_ListAssociations_powershell_5_topic"></a>

次のコード例は、`Get-SSMAssociationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスのすべての関連付けを一覧表示します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="InstanceId";Value=@("i-0000293ffd8c57862")}
Get-SSMAssociationList -AssociationFilterList $filter1
```
**出力:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**例 2: この例では、設定ドキュメントのすべての関連付けを一覧表示します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter2 = @{Key="Name";Value=@("AWS-UpdateSSMAgent")}
Get-SSMAssociationList -AssociationFilterList $filter2
```
**出力:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
**例 3: PowerShell バージョン 2 では、New-Object を使用して各フィルターを作成する必要があります。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.AssociationFilter
$filter1.Key = "InstanceId"
$filter1.Value = "i-0000293ffd8c57862"

Get-SSMAssociationList -AssociationFilterList $filter1
```
**出力:**  

```
AssociationId      : d8617c07-2079-4c18-9847-1655fc2698b0
DocumentVersion    :
InstanceId         : i-0000293ffd8c57862
LastExecutionDate  : 2/20/2015 8:31:11 AM
Name               : AWS-UpdateSSMAgent
Overview           : Amazon.SimpleSystemsManagement.Model.AssociationOverview
ScheduleExpression :
Targets            : {InstanceIds}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListAssociations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAssociationVersionList`
<a name="ssm_ListAssociationVersions_powershell_5_topic"></a>

次のコード例は、`Get-SSMAssociationVersionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定された関連付けのすべてのバージョンを取得します。**  

```
Get-SSMAssociationVersionList -AssociationId 123a45a0-c678-9012-3456-78901234db5e
```
**出力:**  

```
AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    :
AssociationVersion : 2
ComplianceSeverity :
CreatedDate        : 3/12/2019 9:21:01 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression :
Targets            : {InstanceIds}

AssociationId      : 123a45a0-c678-9012-3456-78901234db5e
AssociationName    : test-case-1234567890
AssociationVersion : 1
ComplianceSeverity :
CreatedDate        : 3/2/2019 8:53:29 AM
DocumentVersion    :
MaxConcurrency     :
MaxErrors          :
Name               : AWS-GatherSoftwareInventory
OutputLocation     :
Parameters         : {}
ScheduleExpression : rate(30minutes)
Targets            : {InstanceIds}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListAssociationVersions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAutomationExecution`
<a name="ssm_GetAutomationExecution_powershell_5_topic"></a>

次のコード例は、`Get-SSMAutomationExecution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、オートメーションの実行に関する詳細を表示します。**  

```
Get-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
**出力:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
FailureMessage            : Step launchInstance failed maximum allowed times. You are not authorized to perform this operation. Encoded
                            authorization failure message: B_V2QyyN7NhSZQYpmVzpEc4oSnj2GLTNYnXUHsTbqJkNMoDgubmbtthLmZyaiUYekORIrA42-fv1x-04q5Fjff6glh
                            Yb6TI5b0GQeeNrpwNvpDzmO-PSR1swlAbg9fdM9BcNjyrznspUkWpuKu9EC1Ou6v3OXU1KC9nZ7mPlWMFZNkSioQqpwWEvMw-GZktsQzm67qOhUhBNOLWYhbS
                            pkfiqzY-5nw3S0obx30fhd3EJa5O_-GjV_a0nFXQJa70ik40bFOrEh3MtCSbrQT6--DvFy_FQ8TKvkIXadyVskeJI84XOF5WmA60f1pi5GI08i-nRfZS6oDeU
                            gELBjjoFKD8s3L2aI0B6umWVxnQOjqhQRxwJ53b54sZJ2PW3v_mtg9-q0CK0ezS3xfh_y0ilaUGOAZG-xjQFuvU_JZedWpla3xi-MZsmblAifBI
                            (Service: AmazonEC2; Status Code: 403; Error Code: UnauthorizedOperation; Request ID:
                            6a002f94-ba37-43fd-99e6-39517715fce5)
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
Parameters                : {[AutomationAssumeRole, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [InstanceIamRole,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]], [SourceAmiId,
                            Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
StepExecutions            : {launchInstance, updateOSSoftware, stopInstance, createImage...}
```
**例 2: この例では、指定されたオートメーションの実行 ID におけるステップの詳細情報を一覧表示します。**  

```
Get-SSMAutomationExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object -ExpandProperty StepExecutions | Select-Object StepName, Action, StepStatus, ValidNextSteps
```
**出力:**  

```
StepName                  Action                  StepStatus ValidNextSteps
--------                  ------                  ---------- --------------
LaunchInstance            aws:runInstances        Success    {OSCompatibilityCheck}
OSCompatibilityCheck      aws:runCommand          Success    {RunPreUpdateScript}
RunPreUpdateScript        aws:runCommand          Success    {UpdateEC2Config}
UpdateEC2Config           aws:runCommand          Cancelled  {}
UpdateSSMAgent            aws:runCommand          Pending    {}
UpdateAWSPVDriver         aws:runCommand          Pending    {}
UpdateAWSEnaNetworkDriver aws:runCommand          Pending    {}
UpdateAWSNVMe             aws:runCommand          Pending    {}
InstallWindowsUpdates     aws:runCommand          Pending    {}
RunPostUpdateScript       aws:runCommand          Pending    {}
RunSysprepGeneralize      aws:runCommand          Pending    {}
StopInstance              aws:changeInstanceState Pending    {}
CreateImage               aws:createImage         Pending    {}
TerminateInstance         aws:changeInstanceState Pending    {}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAutomationExecutionList`
<a name="ssm_DescribeAutomationExecutions_powershell_5_topic"></a>

次のコード例は、`Get-SSMAutomationExecutionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントに関連付けられているすべてのアクティブなオートメーションの実行と、終了したオートメーションの実行を記述します。**  

```
Get-SSMAutomationExecutionList
```
**出力:**  

```
AutomationExecutionId     : 4105a4fc-f944-11e6-9d32-8fb2db27a909
AutomationExecutionStatus : Failed
DocumentName              : AWS-UpdateLinuxAmi
DocumentVersion           : 1
ExecutedBy                : admin
ExecutionEndTime          : 2/22/2017 9:17:08 PM
ExecutionStartTime        : 2/22/2017 9:17:02 PM
LogFile                   :
Outputs                   : {[createImage.ImageId, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
```
**例 2: この例では、AutomationExecutionStatus の「Success」以外の実行について、ExecutionID、ドキュメント、実行開始/終了タイムスタンプを表示します。**  

```
Get-SSMAutomationExecutionList | Where-Object AutomationExecutionStatus -ne "Success" | Select-Object AutomationExecutionId, DocumentName, AutomationExecutionStatus, ExecutionStartTime, ExecutionEndTime | Format-Table -AutoSize
```
**出力:**  

```
AutomationExecutionId                DocumentName                            AutomationExecutionStatus ExecutionStartTime   ExecutionEndTime
---------------------                ------------                            ------------------------- ------------------   ----------------
e1d2bad3-4567-8901-ae23-456c7c8901be AWS-UpdateWindowsAmi                    Cancelled                 4/16/2019 5:37:04 AM 4/16/2019 5:47:29 AM
61234567-a7f8-90e1-2b34-567b8bf9012c Fixed-UpdateAmi                         Cancelled                 4/16/2019 5:33:04 AM 4/16/2019 5:40:15 AM
91234d56-7e89-0ac1-2aee-34ea5d6a7c89 AWS-UpdateWindowsAmi                    Failed                    4/16/2019 5:22:46 AM 4/16/2019 5:27:29 AM
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeAutomationExecutions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-SSMAutomationStepExecution`
<a name="ssm_DescribeAutomationStepExecutions_powershell_5_topic"></a>

次のコード例は、`Get-SSMAutomationStepExecution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、オートメーションワークフローにおけるすべてのアクティブなステップの実行と、終了したステップの実行に関する情報を表示します。**  

```
Get-SSMAutomationStepExecution -AutomationExecutionId e1d2bad3-4567-8901-ae23-456c7c8901be | Select-Object StepName, Action, StepStatus
```
**出力:**  

```
StepName                  Action                  StepStatus
--------                  ------                  ----------
LaunchInstance            aws:runInstances        Success
OSCompatibilityCheck      aws:runCommand          Success
RunPreUpdateScript        aws:runCommand          Success
UpdateEC2Config           aws:runCommand          Cancelled
UpdateSSMAgent            aws:runCommand          Pending
UpdateAWSPVDriver         aws:runCommand          Pending
UpdateAWSEnaNetworkDriver aws:runCommand          Pending
UpdateAWSNVMe             aws:runCommand          Pending
InstallWindowsUpdates     aws:runCommand          Pending
RunPostUpdateScript       aws:runCommand          Pending
RunSysprepGeneralize      aws:runCommand          Pending
StopInstance              aws:changeInstanceState Pending
CreateImage               aws:createImage         Pending
TerminateInstance         aws:changeInstanceState Pending
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeAutomationStepExecutions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMAvailablePatch`
<a name="ssm_DescribeAvailablePatches_powershell_5_topic"></a>

次のコード例は、`Get-SSMAvailablePatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Windows Server 2012 で利用でき、MSRC 重要度が「緊急」のすべてのパッチを取得します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="PRODUCT";Values=@("WindowsServer2012")}
$filter2 = @{Key="MSRC_SEVERITY";Values=@("Critical")}

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**出力:**  

```
Classification : SecurityUpdates
ContentUrl     : https://support.microsoft.com/en-us/kb/2727528
Description    : A security issue has been identified that could allow an unauthenticated remote attacker to compromise your system and gain control
                 over it. You can help protect your system by installing this update from Microsoft. After you install this update, you may have to
                 restart your system.
Id             : 1eb507be-2040-4eeb-803d-abc55700b715
KbNumber       : KB2727528
Language       : All
MsrcNumber     : MS12-072
MsrcSeverity   : Critical
Product        : WindowsServer2012
ProductFamily  : Windows
ReleaseDate    : 11/13/2012 6:00:00 PM
Title          : Security Update for Windows Server 2012 (KB2727528)
Vendor         : Microsoft
...
```
**例 2: PowerShell バージョン 2 では、New-Object を使用して各フィルターを作成する必要があります。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "PRODUCT"
$filter1.Values = "WindowsServer2012"
$filter2 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter2.Key = "MSRC_SEVERITY"
$filter2.Values = "Critical"

Get-SSMAvailablePatch -Filter $filter1,$filter2
```
**例 3: この例では、過去 20 日間にリリースされた、Windows Server 2019 に一致する製品に適用されるすべてのパッチの更新情報を取得します。**  

```
Get-SSMAvailablePatch | Where-Object ReleaseDate -ge (Get-Date).AddDays(-20) | Where-Object Product -eq "WindowsServer2019" | Select-Object ReleaseDate, Product, Title
```
**出力:**  

```
ReleaseDate         Product           Title
-----------         -------           -----
4/9/2019 5:00:12 PM WindowsServer2019 2019-04 Security Update for Adobe Flash Player for Windows Server 2019 for x64-based Systems (KB4493478)
4/9/2019 5:00:06 PM WindowsServer2019 2019-04 Cumulative Update for Windows Server 2019 for x64-based Systems (KB4493509)
4/2/2019 5:00:06 PM WindowsServer2019 2019-03 Servicing Stack Update for Windows Server 2019 for x64-based Systems (KB4493510)
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeAvailablePatches](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMCommand`
<a name="ssm_ListCommands_powershell_5_topic"></a>

次のコード例は、`Get-SSMCommand` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リクエストされたすべてのコマンドを一覧表示します。**  

```
Get-SSMCommand
```
**出力:**  

```
CommandId          : 4b75a163-d39a-4d97-87c9-98ae52c6be35
Comment            : Apply association with id at update time: 4cc73e42-d5ae-4879-84f8-57e09c0efcd0
CompletedCount     : 1
DocumentName       : AWS-RefreshAssociation
ErrorCount         : 0
ExpiresAfter       : 2/24/2017 3:19:08 AM
InstanceIds        : {i-0cb2b964d3e14fd9f}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName :
OutputS3KeyPrefix  :
OutputS3Region     :
Parameters         : {[associationIds, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 2/24/2017 3:18:08 AM
ServiceRole        :
Status             : Success
StatusDetails      : Success
TargetCount        : 1
Targets            : {}
```
**例 2: この例では、特定のコマンドのステータスを取得します。**  

```
Get-SSMCommand -CommandId "4b75a163-d39a-4d97-87c9-98ae52c6be35"
```
**例 3: この例では、2019-04-01T00:00:00Z より後に呼び出されたすべての SSM コマンドを取得します。 **  

```
Get-SSMCommand -Filter @{Key="InvokedAfter";Value="2019-04-01T00:00:00Z"} | Select-Object CommandId, DocumentName, Status, RequestedDateTime | Sort-Object -Property RequestedDateTime -Descending
```
**出力:**  

```
CommandId                            DocumentName               Status    RequestedDateTime
---------                            ------------               ------    -----------------
edb1b23e-456a-7adb-aef8-90e-012ac34f AWS-RunPowerShellScript    Cancelled 4/16/2019 5:45:23 AM
1a2dc3fb-4567-890d-a1ad-234b5d6bc7d9 AWS-ConfigureAWSPackage    Success   4/6/2019 9:19:42 AM
12c3456c-7e90-4f12-1232-1234f5b67893 KT-Retrieve-Cloud-Type-Win Failed    4/2/2019 4:13:07 AM
fe123b45-240c-4123-a2b3-234bdd567ecf AWS-RunInspecChecks        Failed    4/1/2019 2:27:31 PM
1eb23aa4-567d-4123-12a3-4c1c2ab34561 AWS-RunPowerShellScript    Success   4/1/2019 1:05:55 PM
1c2f3bb4-ee12-4bc1-1a23-12345eea123e AWS-RunInspecChecks        Failed    4/1/2019 11:13:09 AM
```
+  API の詳細については、「AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListCommands](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMCommandInvocation`
<a name="ssm_ListCommandInvocations_powershell_5_topic"></a>

次のコード例は、`Get-SSMCommandInvocation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、コマンドのすべての呼び出しを一覧表示します。**  

```
Get-SSMCommandInvocation -CommandId "b8eac879-0541-439d-94ec-47a80d554f44" -Detail $true
```
**出力:**  

```
CommandId          : b8eac879-0541-439d-94ec-47a80d554f44
CommandPlugins     : {aws:runShellScript}
Comment            : IP config
DocumentName       : AWS-RunShellScript
InstanceId         : i-0cb2b964d3e14fd9f
InstanceName       :
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
RequestedDateTime  : 2/22/2017 8:13:16 PM
ServiceRole        :
StandardErrorUrl   :
StandardOutputUrl  :
Status             : Success
StatusDetails      : Success
TraceOutput        :
```
**例 2: この例では、コマンド ID e1eb2e3c-ed4c-5123-45c1-234f5612345f の呼び出し用の CommandPlugins を一覧表示します。**  

```
Get-SSMCommandInvocation -CommandId e1eb2e3c-ed4c-5123-45c1-234f5612345f -Detail:$true | Select-Object -ExpandProperty CommandPlugins
```
**出力:**  

```
Name                   : aws:runPowerShellScript
Output                 : Completed 17.7 KiB/17.7 KiB (40.1 KiB/s) with 1 file(s) remainingdownload: s3://dd-aess-r-ctmer/KUMO.png to ..\..\programdata\KUMO.png
                         kumo available

OutputS3BucketName     :
OutputS3KeyPrefix      :
OutputS3Region         : eu-west-1
ResponseCode           : 0
ResponseFinishDateTime : 4/3/2019 11:53:23 AM
ResponseStartDateTime  : 4/3/2019 11:53:21 AM
StandardErrorUrl       :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListCommandInvocations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMCommandInvocationDetail`
<a name="ssm_GetCommandInvocation_powershell_5_topic"></a>

次のコード例は、`Get-SSMCommandInvocationDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスで実行されたコマンドの詳細情報を表示します。**  

```
Get-SSMCommandInvocationDetail -InstanceId "i-0cb2b964d3e14fd9f" -CommandId "b8eac879-0541-439d-94ec-47a80d554f44"
```
**出力:**  

```
CommandId              : b8eac879-0541-439d-94ec-47a80d554f44
Comment                : IP config
DocumentName           : AWS-RunShellScript
ExecutionElapsedTime   : PT0.004S
ExecutionEndDateTime   : 2017-02-22T20:13:16.651Z
ExecutionStartDateTime : 2017-02-22T20:13:16.651Z
InstanceId             : i-0cb2b964d3e14fd9f
PluginName             : aws:runShellScript
ResponseCode           : 0
StandardErrorContent   :
StandardErrorUrl       :
StandardOutputContent  :
StandardOutputUrl      :
Status                 : Success
StatusDetails          : Success
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetCommandInvocation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMComplianceItemList`
<a name="ssm_ListComplianceItems_powershell_5_topic"></a>

次のコード例は、`Get-SSMComplianceItemList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、任意のリソース ID とタイプのコンプライアンス項目リストを一覧表示し、コンプライアンスタイプを「関連付け」でフィルタリングします。**  

```
Get-SSMComplianceItemList -ResourceId i-1a2caf345f67d0dc2 -ResourceType ManagedInstance -Filter @{Key="ComplianceType";Values="Association"}
```
**出力:**  

```
ComplianceType   : Association
Details          : {[DocumentName, AWS-GatherSoftwareInventory], [DocumentVersion, 1]}
ExecutionSummary : Amazon.SimpleSystemsManagement.Model.ComplianceExecutionSummary
Id               : 123a45a1-c234-1234-1245-67891236db4e
ResourceId       : i-1a2caf345f67d0dc2
ResourceType     : ManagedInstance
Severity         : UNSPECIFIED
Status           : COMPLIANT
Title            :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMComplianceSummaryList`
<a name="ssm_ListComplianceSummaries_powershell_5_topic"></a>

次のコード例は、`Get-SSMComplianceSummaryList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべてのコンプライアンスタイプの準拠リソースと非準拠リソースの集計カウントを返します。**  

```
Get-SSMComplianceSummaryList
```
**出力:**  

```
ComplianceType CompliantSummary                                      NonCompliantSummary
-------------- ----------------                                      -------------------
FleetTotal     Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Association    Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Custom:InSpec  Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
Patch          Amazon.SimpleSystemsManagement.Model.CompliantSummary Amazon.SimpleSystemsManagement.Model.NonCompliantSummary
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMConnectionStatus`
<a name="ssm_GetConnectionStatus_powershell_5_topic"></a>

次のコード例は、`Get-SSMConnectionStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスが接続され、Session Manager 接続を受信する準備ができているかどうかを判断するため、インスタンスの Session Manager 接続ステータスを取得します。**  

```
Get-SSMConnectionStatus -Target i-0a1caf234f12d3dc4
```
**出力:**  

```
Status    Target
------    ------
Connected i-0a1caf234f12d3dc4
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMDefaultPatchBaseline`
<a name="ssm_GetDefaultPatchBaseline_powershell_5_topic"></a>

次のコード例は、`Get-SSMDefaultPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、デフォルトのパッチベースラインを表示します。**  

```
Get-SSMDefaultPatchBaseline
```
**出力:**  

```
arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMDeployablePatchSnapshotForInstance`
<a name="ssm_GetDeployablePatchSnapshotForInstance_powershell_5_topic"></a>

次のコード例は、`Get-SSMDeployablePatchSnapshotForInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスで使用されるパッチベースラインの現在のスナップショットを表示します。このコマンドは、インスタンス認証情報を使用してインスタンスから実行する必要があります。この例では、インスタンス認証情報が使用されるようにするため、Credentials パラメータに `Amazon.Runtime.InstanceProfileAWSCredentials` オブジェクトを渡します。**  

```
$credentials = [Amazon.Runtime.InstanceProfileAWSCredentials]::new()
Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f" -Credentials $credentials
```
**出力:**  

```
InstanceId          SnapshotDownloadUrl
----------          -------------------
i-0cb2b964d3e14fd9f https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...1692/4681775b-098f-4435...
```
**例 2: この例は、完全な SnapshotDownloadUrl を取得する方法を示しています。このコマンドは、インスタンス認証情報を使用してインスタンスから実行する必要があります。この例では、インスタンス認証情報が使用されるようにするため PowerShell セッションが `Amazon.Runtime.InstanceProfileAWSCredentials` オブジェクトを使用するように設定しています。**  

```
Set-AWSCredential -Credential ([Amazon.Runtime.InstanceProfileAWSCredentials]::new())
(Get-SSMDeployablePatchSnapshotForInstance -SnapshotId "4681775b-098f-4435-a956-0ef33373ac11" -InstanceId "i-0cb2b964d3e14fd9f").SnapshotDownloadUrl
```
**出力:**  

```
https://patch-baseline-snapshot-us-west-2.s3-us-west-2.amazonaws.com/853d0d3db0f0cafe...
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetDeployablePatchSnapshotForInstance](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMDocument`
<a name="ssm_GetDocument_powershell_5_topic"></a>

次のコード例は、`Get-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ドキュメントのコンテンツを返します。**  

```
Get-SSMDocument -Name "RunShellScript"
```
**出力:**  

```
Content
-------
{...
```
**例 2: この例では、ドキュメントの完全なコンテンツを表示します。**  

```
(Get-SSMDocument -Name "RunShellScript").Content
{
   "schemaVersion":"2.0",
   "description":"Run an updated script",
   "parameters":{
      "commands":{
         "type":"StringList",
         "description":"(Required) Specify a shell script or a command to run.",
         "minItems":1,
         "displayType":"textarea"
      }
   },
   "mainSteps":[
      {
         "action":"aws:runShellScript",
         "name":"runShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      },
      {
         "action":"aws:runPowerShellScript",
         "name":"runPowerShellScript",
         "inputs":{
            "commands":"{{ commands }}"
         }
      }
   ]
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetDocument](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMDocumentDescription`
<a name="ssm_DescribeDocument_powershell_5_topic"></a>

次のコード例は、`Get-SSMDocumentDescription` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ドキュメントに関する情報を返します。**  

```
Get-SSMDocumentDescription -Name "RunShellScript"
```
**出力:**  

```
CreatedDate     : 2/24/2017 5:25:13 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : f775e5df4904c6fa46686c4722fae9de1950dace25cd9608ff8d622046b68d9b
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 123456789012
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Active
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeDocument](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMDocumentList`
<a name="ssm_ListDocuments_powershell_5_topic"></a>

次のコード例は、`Get-SSMDocumentList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: アカウント内のすべての設定ドキュメントを一覧表示します。**  

```
Get-SSMDocumentList
```
**出力:**  

```
DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ApplyPatchBaseline
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureAWSPackage
Owner           : Amazon
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 2.0

DocumentType    : Command
DocumentVersion : 1
Name            : AWS-ConfigureCloudWatch
Owner           : Amazon
PlatformTypes   : {Windows}
SchemaVersion   : 1.2
...
```
**例 2: この例では、名前が「プラットフォーム」と一致するすべてのオートメーションドキュメントを取得します。**  

```
Get-SSMDocumentList -DocumentFilterList @{Key="DocumentType";Value="Automation"} | Where-Object Name -Match "Platform"
```
**出力:**  

```
DocumentFormat  : JSON
DocumentType    : Automation
DocumentVersion : 7
Name            : KT-Get-Platform
Owner           : 987654123456
PlatformTypes   : {Windows, Linux}
SchemaVersion   : 0.3
Tags            : {}
TargetType      :
VersionName     :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListDocuments](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMDocumentPermission`
<a name="ssm_DescribeDocumentPermission_powershell_5_topic"></a>

次のコード例は、`Get-SSMDocumentPermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ドキュメントのすべてのバージョンを一覧表示します。**  

```
Get-SSMDocumentVersionList -Name "RunShellScript"
```
**出力:**  

```
CreatedDate          DocumentVersion IsDefaultVersion Name
-----------          --------------- ---------------- ----
2/24/2017 5:25:13 AM 1               True             RunShellScript
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeDocumentPermission](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-SSMDocumentVersionList`
<a name="ssm_ListDocumentVersions_powershell_5_topic"></a>

次のコード例は、`Get-SSMDocumentVersionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ドキュメントのすべてのバージョンを一覧表示します。**  

```
Get-SSMDocumentVersionList -Name "AWS-UpdateSSMAgent"
```
**出力:**  

```
CreatedDate       : 6/1/2021 5:19:10 PM
DocumentFormat    : JSON
DocumentVersion   : 1
IsDefaultVersion  : True
Name              : AWS-UpdateSSMAgent
Status            : Active
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListDocumentVersions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMEffectiveInstanceAssociationList`
<a name="ssm_DescribeEffectiveInstanceAssociations_powershell_5_topic"></a>

次のコード例は、`Get-SSMEffectiveInstanceAssociationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスの有効な関連付けを記述します。**  

```
Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5
```
**出力:**  

```
AssociationId                        Content
-------------                        -------
d8617c07-2079-4c18-9847-1655fc2698b0 {...
```
**例 2: この例では、インスタンスの有効な関連付けの内容を記述します。**  

```
(Get-SSMEffectiveInstanceAssociationList -InstanceId "i-0000293ffd8c57862" -MaxResult 5).Content
```
**出力:**  

```
{
    "schemaVersion": "1.2",
    "description": "Update the Amazon SSM Agent to the latest version or specified version.",
    "parameters": {
        "version": {
            "default": "",
            "description": "(Optional) A specific version of the Amazon SSM Agent to install. If not specified, the agen
t will be updated to the latest version.",
            "type": "String"
        },
        "allowDowngrade": {
            "default": "false",
            "description": "(Optional) Allow the Amazon SSM Agent service to be downgraded to an earlier version. If set
 to false, the service can be upgraded to newer versions only (default). If set to true, specify the earlier version.",
            "type": "String",
            "allowedValues": [
                "true",
                "false"
            ]
        }
    },
    "runtimeConfig": {
        "aws:updateSsmAgent": {
            "properties": [
                {
                "agentName": "amazon-ssm-agent",
                "source": "https://s3.{Region}.amazonaws.com/amazon-ssm-{Region}/ssm-agent-manifest.json",
                "allowDowngrade": "{{ allowDowngrade }}",
                "targetVersion": "{{ version }}"
                }
            ]
        }
    }
}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeEffectiveInstanceAssociations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMEffectivePatchesForPatchBaseline`
<a name="ssm_DescribeEffectivePatchesForPatchBaseline_powershell_5_topic"></a>

次のコード例は、`Get-SSMEffectivePatchesForPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべてのパッチベースラインを一覧表示します。結果の最大表示件数は 1 です。**  

```
Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1
```
**出力:**  

```
Patch                                      PatchStatus
-----                                      -----------
Amazon.SimpleSystemsManagement.Model.Patch Amazon.SimpleSystemsManagement.Model.PatchStatus
```
**例 2: この例では、すべてのパッチベースラインのパッチステータスを表示します。結果の最大表示件数は 1 です。**  

```
(Get-SSMEffectivePatchesForPatchBaseline -BaselineId "pb-0a2f1059b670ebd31" -MaxResult 1).PatchStatus
```
**出力:**  

```
ApprovalDate          DeploymentStatus
------------          ----------------
12/21/2010 6:00:00 PM APPROVED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeEffectivePatchesForPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInstanceAssociationsStatus`
<a name="ssm_DescribeInstanceAssociationsStatus_powershell_5_topic"></a>

次のコード例は、`Get-SSMInstanceAssociationsStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスの関連付けの詳細情報を表示します。**  

```
Get-SSMInstanceAssociationsStatus -InstanceId "i-0000293ffd8c57862"
```
**出力:**  

```
AssociationId    : d8617c07-2079-4c18-9847-1655fc2698b0
DetailedStatus   : Pending
DocumentVersion  : 1
ErrorCode        :
ExecutionDate    : 2/20/2015 8:31:11 AM
ExecutionSummary : temp_status_change
InstanceId       : i-0000293ffd8c57862
Name             : AWS-UpdateSSMAgent
OutputUrl        :
Status           : Pending
```
**例 2: この例では、指定されたインスタンス ID におけるインスタンスの関連付けのステータスを確認し、それらの関連付けの実行ステータスを表示します。**  

```
Get-SSMInstanceAssociationsStatus -InstanceId i-012e3cb4df567e8aa | ForEach-Object {Get-SSMAssociationExecution -AssociationId .AssociationId}
```
**出力:**  

```
AssociationId         : 512a34a5-c678-1234-1234-12345678db9e
AssociationVersion    : 2
CreatedTime           : 3/2/2019 8:53:29 AM
DetailedStatus        :
ExecutionId           : 512a34a5-c678-1234-1234-12345678db9e
LastExecutionDate     : 1/1/0001 12:00:00 AM
ResourceCountByStatus : {Success=9}
Status                : Success
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeInstanceAssociationsStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Get-SSMInstanceInformation`
<a name="ssm_DescribeInstanceInformation_powershell_5_topic"></a>

次のコード例は、`Get-SSMInstanceInformation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、各インスタンスの詳細情報を表示します。**  

```
Get-SSMInstanceInformation
```
**出力:**  

```
ActivationId                           :
AgentVersion                           : 2.0.672.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : ip-172-31-44-222.us-west-2.compute.internal
IamRole                                :
InstanceId                             : i-0cb2b964d3e14fd9f
IPAddress                              : 172.31.44.222
IsLatestVersion                        : True
LastAssociationExecutionDate           : 2/24/2017 3:18:09 AM
LastPingDateTime                       : 2/24/2017 3:35:03 AM
LastSuccessfulAssociationExecutionDate : 2/24/2017 3:18:09 AM
Name                                   :
PingStatus                             : ConnectionLost
PlatformName                           : Amazon Linux AMI
PlatformType                           : Linux
PlatformVersion                        : 2016.09
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**例 2: この例では、-Filter パラメータを使用して、 `AgentVersion`が `us-east-1`のリージョン内の AWS Systems Manager インスタンスのみに結果をフィルタリングする方法を示します`2.2.800.0`。有効な -Filter キー値のリストは、InstanceInformation の API リファレンストピック (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformation.html\$1systemsmanager-Type-InstanceInformation-ActivationId) で確認できます。**  

```
$Filters = @{
    Key="AgentVersion"
    Values="2.2.800.0"
}
Get-SSMInstanceInformation -Region us-east-1 -Filter $Filters
```
**出力:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.01
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.02
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**例 3: この例では、-InstanceInformationFilterList パラメータを使用して、 `Windows`または `us-east-1``PlatformTypes`を持つリージョン内の AWS Systems Manager インスタンスのみに結果をフィルタリングする方法を示します`Linux`。有効な -InstanceInformationFilterList キー値のリストは、InstanceInformationFilter の API リファレンストピック (https://docs.aws.amazon.com/systems-manager/latest/APIReference/API\$1InstanceInformationFilter.html) で確認できます。**  

```
$Filters = @{
   Key="PlatformTypes"
   ValueSet=("Windows","Linux")
}
Get-SSMInstanceInformation -Region us-east-1 -InstanceInformationFilterList $Filters
```
**出力:**  

```
ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEb0792d98ce
IPAddress                              : 10.0.0.27
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:02:50 AM
LastPingDateTime                       : 8/16/2018 7:40:27 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:02:50 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Ubuntu Server 18.04 LTS
PlatformType                           : Linux
PlatformVersion                        : 18.04
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance

ActivationId                           : 
AgentVersion                           : 2.2.800.0
AssociationOverview                    : Amazon.SimpleSystemsManagement.Model.InstanceAggregatedAssociationOverview
AssociationStatus                      : Success
ComputerName                           : EXAMPLE-EXAMPLE.WORKGROUP
IamRole                                : 
InstanceId                             : i-EXAMPLEac7501d023
IPAddress                              : 10.0.0.100
IsLatestVersion                        : False
LastAssociationExecutionDate           : 8/16/2018 12:00:20 AM
LastPingDateTime                       : 8/16/2018 7:40:35 PM
LastSuccessfulAssociationExecutionDate : 8/16/2018 12:00:20 AM
Name                                   : 
PingStatus                             : Online
PlatformName                           : Microsoft Windows Server 2016 Datacenter
PlatformType                           : Windows
PlatformVersion                        : 10.0.14393
RegistrationDate                       : 1/1/0001 12:00:00 AM
ResourceType                           : EC2Instance
```
**例 4: この例では、ssm マネージドインスタンスを一覧表示し、InstanceId、PingStatus、LastPingDateTime、PlatformName を csv ファイルにエクスポートします。**  

```
Get-SSMInstanceInformation | Select-Object InstanceId, PingStatus, LastPingDateTime, PlatformName | Export-Csv Instance-details.csv -NoTypeInformation
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeInstanceInformation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInstancePatch`
<a name="ssm_DescribeInstancePatches_powershell_5_topic"></a>

次のコード例は、`Get-SSMInstancePatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスのパッチコンプライアンスの詳細を取得します。**  

```
Get-SSMInstancePatch -InstanceId "i-08ee91c0b17045407"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeInstancePatches](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInstancePatchState`
<a name="ssm_DescribeInstancePatchStates_powershell_5_topic"></a>

次のコード例は、`Get-SSMInstancePatchState` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスのパッチの概要状態を取得します。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407"
```
**例 2: この例では、2 つのインスタンスにおけるパッチの概要状態を取得します。**  

```
Get-SSMInstancePatchState -InstanceId "i-08ee91c0b17045407","i-09a618aec652973a9"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeInstancePatchStates](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInstancePatchStatesForPatchGroup`
<a name="ssm_DescribeInstancePatchStatesForPatchGroup_powershell_5_topic"></a>

次のコード例は、`Get-SSMInstancePatchStatesForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチグループにおけるインスタンスごとのパッチの概要状態を取得します。**  

```
Get-SSMInstancePatchStatesForPatchGroup -PatchGroup "Production"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeInstancePatchStatesForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInventory`
<a name="ssm_GetInventory_powershell_5_topic"></a>

次のコード例は、`Get-SSMInventory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インベントリのカスタムメタデータを取得します。**  

```
Get-SSMInventory
```
**出力:**  

```
Data                                                                                  Id
----                                                                                  --
{[AWS:InstanceInformation, Amazon.SimpleSystemsManagement.Model.InventoryResultItem]} i-0cb2b964d3e14fd9f
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetInventory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInventoryEntriesList`
<a name="ssm_ListInventoryEntries_powershell_5_topic"></a>

次のコード例は、`Get-SSMInventoryEntriesList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスのすべてのカスタムインベントリエントリを一覧表示します。**  

```
Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo"
```
**出力:**  

```
CaptureTime   : 2016-08-22T10:01:01Z
Entries       : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,System.String]}
InstanceId    : i-0cb2b964d3e14fd9f
NextToken     :
SchemaVersion : 1.0
TypeName      : Custom:RackInfo
```
**例 2: この例では詳細を一覧表示します。**  

```
(Get-SSMInventoryEntriesList -InstanceId "i-0cb2b964d3e14fd9f" -TypeName "Custom:RackInfo").Entries
```
**出力:**  

```
Key          Value
---          -----
RackLocation Bay B/Row C/Rack D/Shelf E
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListInventoryEntries](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInventoryEntryList`
<a name="ssm_Get-SSMInventoryEntryList_powershell_5_topic"></a>

次のコード例は、`Get-SSMInventoryEntryList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスの `AWS:Network` タイプのインベントリエントリを取得します。**  

```
Get-SSMInventoryEntryList -InstanceId mi-088dcb0ecea37b076 -TypeName AWS:Network | Select-Object -ExpandProperty Entries
```
**出力:**  

```
Key        Value
---        -----
DHCPServer 172.31.11.2
DNSServer  172.31.0.1
Gateway    172.31.11.2
IPV4       172.31.11.222
IPV6       fe12::3456:7da8:901a:12a3
MacAddress 1A:23:4E:5B:FB:67
Name       Amazon Elastic Network Adapter
SubnetMask 255.255.240.0
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[Get-SSMInventoryEntryList](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMInventorySchema`
<a name="ssm_GetInventorySchema_powershell_5_topic"></a>

次のコード例は、`Get-SSMInventorySchema` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントのインベントリタイプ名のリストを返します。**  

```
Get-SSMInventorySchema
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetInventorySchema](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMLatestEC2Image`
<a name="ssm_Get-SSMLatestEC2Image_powershell_5_topic"></a>

次のコード例は、`Get-SSMLatestEC2Image` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、最新の Windows AMI をすべて一覧表示します。**  

```
PS Get-SSMLatestEC2Image -Path ami-windows-latest
```
**出力:**  

```
Name                                                                    Value
----                                                                    -----
Windows_Server-2008-R2_SP1-English-64Bit-SQL_2012_SP4_Express           ami-0e5ddd288daff4fab
Windows_Server-2012-R2_RTM-Chinese_Simplified-64Bit-Base                ami-0c5ea64e6bec1cb50
Windows_Server-2012-R2_RTM-Chinese_Traditional-64Bit-Base               ami-09775eff0bf8c113d
Windows_Server-2012-R2_RTM-Dutch-64Bit-Base                             ami-025064b67e28cf5df
...
```
**例 2: この例では、us-west-2 リージョンの特定の Amazon Linux イメージの AMI ID を取得します。**  

```
PS Get-SSMLatestEC2Image -Path ami-amazon-linux-latest -ImageName amzn-ami-hvm-x86_64-ebs -Region us-west-2
```
**出力:**  

```
ami-09b92cd132204c704
```
**例 3: この例では、指定されたワイルドカード表現に一致する最新の Windows AMI をすべて一覧表示します。**  

```
Get-SSMLatestEC2Image -Path ami-windows-latest -ImageName *Windows*2019*English*
```
**出力:**  

```
Name                                                     Value
----                                                     -----
Windows_Server-2019-English-Full-SQL_2017_Web            ami-085e9d27da5b73a42
Windows_Server-2019-English-STIG-Core                    ami-0bfd85c29148c7f80
Windows_Server-2019-English-Full-SQL_2019_Web            ami-02099560d7fb11f20
Windows_Server-2019-English-Full-SQL_2016_SP2_Standard   ami-0d7ae2d81c07bd598
...
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[Get-SSMLatestEC2Image](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindow`
<a name="ssm_GetMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウの詳細を取得します。**  

```
Get-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d"
```
**出力:**  

```
AllowUnassociatedTargets : False
CreatedDate              : 2/20/2017 6:14:05 PM
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
ModifiedDate             : 2/20/2017 6:14:05 PM
Name                     : TestMaintWin
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowExecution`
<a name="ssm_GetMaintenanceWindowExecution_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウの実行の一部として実行されるタスクに関する情報を一覧表示します。**  

```
Get-SSMMaintenanceWindowExecution -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
TaskIds           : {ac0c6ae1-daa3-4a89-832e-d384503b6586}
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetMaintenanceWindowExecution](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowExecutionList`
<a name="ssm_DescribeMaintenanceWindowExecutions_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウにおけるすべての実行を一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d"
```
**出力:**  

```
EndTime           : 2/20/2017 6:30:17 PM
StartTime         : 2/20/2017 6:30:16 PM
Status            : FAILED
StatusDetails     : One or more tasks in the orchestration failed.
WindowExecutionId : 6f3215cf-4101-4fa0-9b7b-9523269599c7
WindowId          : mw-03eb9db42890fb82d
```
**例 2: この例では、指定されたメンテナンスウィンドウにおける指定された日付より前のすべての実行を一覧表示します。**  

```
$option1 = @{Key="ExecutedBefore";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
**例 3: この例では、指定されたメンテナンスウィンドウにおける指定された日付より後のすべての実行を一覧表示します。**  

```
$option1 = @{Key="ExecutedAfter";Values=@("2016-11-04T05:00:00Z")}
Get-SSMMaintenanceWindowExecutionList -WindowId "mw-03eb9db42890fb82d" -Filter $option1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeMaintenanceWindowExecutions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowExecutionTask`
<a name="ssm_GetMaintenanceWindowExecutionTask_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionTask` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウの実行の一部であったタスクに関する情報を一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionTask -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:35 PM
MaxConcurrency    : 1
MaxErrors         : 1
Priority          : 10
ServiceRole       : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The maximum error count was exceeded.
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskParameters    : {Amazon.Runtime.Internal.Util.AlwaysSendDictionary`2[System.String,Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskPara
                    meterValueExpression]}
Type              : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetMaintenanceWindowExecutionTask](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowExecutionTaskInvocationList`
<a name="ssm_DescribeMaintenanceWindowExecutionTaskInvocations_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionTaskInvocationList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウの実行の一部として実行される、タスクの呼び出しを一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionTaskInvocationList -TaskId "ac0c6ae1-daa3-4a89-832e-d384503b6586" -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:34 PM
ExecutionId       :
InvocationId      : e274b6e1-fe56-4e32-bd2a-8073c6381d8b
OwnerInformation  :
Parameters        : {"documentName":"AWS-RunShellScript","instanceIds":["i-0000293ffd8c57862"],"parameters":{"commands":["df"]},"maxConcurrency":"1",
                    "maxErrors":"1"}
StartTime         : 2/21/2017 4:00:34 PM
Status            : FAILED
StatusDetails     : The instance IDs list contains an invalid entry.
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
WindowTargetId    :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeMaintenanceWindowExecutionTaskInvocations](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowExecutionTaskList`
<a name="ssm_DescribeMaintenanceWindowExecutionTasks_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowExecutionTaskList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウの実行に関連するタスクを一覧表示します。**  

```
Get-SSMMaintenanceWindowExecutionTaskList -WindowExecutionId "518d5565-5969-4cca-8f0e-da3b2a638355"
```
**出力:**  

```
EndTime           : 2/21/2017 4:00:35 PM
StartTime         : 2/21/2017 4:00:34 PM
Status            : SUCCESS
TaskArn           : AWS-RunShellScript
TaskExecutionId   : ac0c6ae1-daa3-4a89-832e-d384503b6586
TaskType          : RUN_COMMAND
WindowExecutionId : 518d5565-5969-4cca-8f0e-da3b2a638355
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeMaintenanceWindowExecutionTasks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowList`
<a name="ssm_DescribeMaintenanceWindows_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントにおけるすべてのメンテナンスウィンドウを一覧表示します。**  

```
Get-SSMMaintenanceWindowList
```
**出力:**  

```
Cutoff   : 1
Duration : 4
Enabled  : True
Name     : My-First-Maintenance-Window
WindowId : mw-06d59c1a07c022145
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeMaintenanceWindows](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowTarget`
<a name="ssm_DescribeMaintenanceWindowTargets_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowTarget` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウのすべてのターゲットを一覧表示します。**  

```
Get-SSMMaintenanceWindowTarget -WindowId "mw-06cf17cbefcb4bf4f"
```
**出力:**  

```
OwnerInformation : Single instance
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : 350d44e6-28cc-44e2-951f-4b2c985838f6

OwnerInformation : Two instances in a list
ResourceType     : INSTANCE
Targets          : {InstanceIds}
WindowId         : mw-06cf17cbefcb4bf4f
WindowTargetId   : e078a987-2866-47be-bedd-d9cf49177d3a
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeMaintenanceWindowTargets](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMMaintenanceWindowTaskList`
<a name="ssm_DescribeMaintenanceWindowTasks_powershell_5_topic"></a>

次のコード例は、`Get-SSMMaintenanceWindowTaskList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウのすべてのタスクを一覧表示します。**  

```
Get-SSMMaintenanceWindowTaskList -WindowId "mw-06cf17cbefcb4bf4f"
```
**出力:**  

```
LoggingInfo    :
MaxConcurrency : 1
MaxErrors      : 1
Priority       : 10
ServiceRoleArn : arn:aws:iam::123456789012:role/MaintenanceWindowsRole
Targets        : {InstanceIds}
TaskArn        : AWS-RunShellScript
TaskParameters : {[commands, Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression]}
Type           : RUN_COMMAND
WindowId       : mw-06cf17cbefcb4bf4f
WindowTaskId   : a23e338d-ff30-4398-8aa3-09cd052ebf17
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeMaintenanceWindowTasks](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMParameterHistory`
<a name="ssm_GetParameterHistory_powershell_5_topic"></a>

次のコード例は、`Get-SSMParameterHistory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パラメータの値の履歴を一覧表示します。**  

```
Get-SSMParameterHistory -Name "Welcome"
```
**出力:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:55:25 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
Value            : helloWorld
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetParameterHistory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMParameterList`
<a name="ssm_DescribeParameters_powershell_5_topic"></a>

次のコード例は、`Get-SSMParameterList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべてのパラメータを一覧表示します。**  

```
Get-SSMParameterList
```
**出力:**  

```
Description      :
KeyId            :
LastModifiedDate : 3/3/2017 6:58:23 PM
LastModifiedUser : arn:aws:iam::123456789012:user/admin
Name             : Welcome
Type             : String
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeParameters](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMParameterValue`
<a name="ssm_GetParameters_powershell_5_topic"></a>

次のコード例は、`Get-SSMParameterValue` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パラメータの値を一覧表示します。**  

```
Get-SSMParameterValue -Name "Welcome"
```
**出力:**  

```
InvalidParameters Parameters
----------------- ----------
{}                {Welcome}
```
**例 2: この例では、値の詳細を一覧表示します。**  

```
(Get-SSMParameterValue -Name "Welcome").Parameters
```
**出力:**  

```
Name    Type   Value
----    ----   -----
Welcome String Good day, Sunshine!
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetParameters](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMPatchBaseline`
<a name="ssm_DescribePatchBaselines_powershell_5_topic"></a>

次のコード例は、`Get-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、すべてのパッチベースラインを一覧表示します。**  

```
Get-SSMPatchBaseline
```
**出力:**  

```
BaselineDescription                                             BaselineId                                                            BaselineName
-------------------                                             ----------                                                            ------------
Default Patch Baseline Provided by AWS.                         arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultP...
Baseline containing all updates approved for production systems pb-045f10b4f382baeda                                                  Production-B...
Baseline containing all updates approved for production systems pb-0a2f1059b670ebd31                                                  Production-B...
```
**例 2: この例では、 が提供するすべてのパッチベースラインを一覧表示します AWS。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="OWNER";Values=@("AWS")}
```
**出力:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**例 3: この例では、所有者しているすべてのパッチベースラインを一覧表示します。この例で使用される構文には、PowerShell バージョン 3 以降が必要です。**  

```
$filter1 = @{Key="OWNER";Values=@("Self")}
```
**出力:**  

```
Get-SSMPatchBaseline -Filter $filter1
```
**例 4: PowerShell バージョン 2 では、New-Object を使用して各タグを作成する必要があります。**  

```
$filter1 = New-Object Amazon.SimpleSystemsManagement.Model.PatchOrchestratorFilter
$filter1.Key = "OWNER"
$filter1.Values = "AWS"

Get-SSMPatchBaseline -Filter $filter1
```
**出力:**  

```
BaselineDescription                     BaselineId                                                            BaselineName             DefaultBaselin
                                                                                                                                       e
-------------------                     ----------                                                            ------------             --------------
Default Patch Baseline Provided by AWS. arn:aws:ssm:us-west-2:123456789012:patchbaseline/pb-04fb4ae6142167966 AWS-DefaultPatchBaseline True
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribePatchBaselines](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMPatchBaselineDetail`
<a name="ssm_GetPatchBaseline_powershell_5_topic"></a>

次のコード例は、`Get-SSMPatchBaselineDetail` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチベースラインの詳細を表示します。**  

```
Get-SSMPatchBaselineDetail -BaselineId "pb-03da896ca3b68b639"
```
**出力:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:02:19 PM
Name            : Production-Baseline
PatchGroups     : {}
RejectedPatches : {}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMPatchBaselineForPatchGroup`
<a name="ssm_GetPatchBaselineForPatchGroup_powershell_5_topic"></a>

次のコード例は、`Get-SSMPatchBaselineForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチグループのパッチベースラインを表示します。**  

```
Get-SSMPatchBaselineForPatchGroup -PatchGroup "Production"
```
**出力:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[GetPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMPatchGroup`
<a name="ssm_DescribePatchGroups_powershell_5_topic"></a>

次のコード例は、`Get-SSMPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチグループの登録を一覧表示します。**  

```
Get-SSMPatchGroup
```
**出力:**  

```
BaselineIdentity                                           PatchGroup
----------------                                           ----------
Amazon.SimpleSystemsManagement.Model.PatchBaselineIdentity Production
```
+  API の詳細については、「AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribePatchGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMPatchGroupState`
<a name="ssm_DescribePatchGroupState_powershell_5_topic"></a>

次のコード例は、`Get-SSMPatchGroupState` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチグループのパッチコンプライアンスの概要を取得します。**  

```
Get-SSMPatchGroupState -PatchGroup "Production"
```
**出力:**  

```
Instances                          : 4
InstancesWithFailedPatches         : 1
InstancesWithInstalledOtherPatches : 4
InstancesWithInstalledPatches      : 3
InstancesWithMissingPatches        : 0
InstancesWithNotApplicablePatches  : 0
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribePatchGroupState](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMResourceComplianceSummaryList`
<a name="ssm_ListResourceComplianceSummaries_powershell_5_topic"></a>

次のコード例は、`Get-SSMResourceComplianceSummaryList` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リソースレベルの概要数を取得します。概要には、「Windows10」に一致する製品の準拠ステータスと非準拠ステータス、および詳細なコンプライアンス項目の重要度数に関する情報が含まれます。MaxResult のデフォルトは、パラメータが指定されていない場合は 100 であり、この値は有効ではないため、MaxResult パラメータが追加され、値は 50 に設定されます。**  

```
$FilterValues = @{
		"Key"="Product"
        "Type"="EQUAL"
        "Values"="Windows10"
}
        Get-SSMResourceComplianceSummaryList -Filter $FilterValues -MaxResult 50
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListResourceComplianceSummaries](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-SSMResourceTag`
<a name="ssm_ListTagsForResource_powershell_5_topic"></a>

次のコード例は、`Get-SSMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウのタグを一覧表示します。**  

```
Get-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow"
```
**出力:**  

```
Key   Value
---   -----
Stack Production
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ListTagsForResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-SSMActivation`
<a name="ssm_CreateActivation_powershell_5_topic"></a>

次のコード例は、`New-SSMActivation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、マネージドインスタンスを作成します。**  

```
New-SSMActivation -DefaultInstanceName "MyWebServers" -IamRole "SSMAutomationRole" -RegistrationLimit 10
```
**出力:**  

```
ActivationCode       ActivationId
--------------       ------------
KWChhOxBTiwDcKE9BlKC 08e51e79-1e36-446c-8e63-9458569c1363
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateActivation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-SSMAssociation`
<a name="ssm_CreateAssociation_powershell_5_topic"></a>

次のコード例は、`New-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンス ID を使用して、設定ドキュメントをインスタンスに関連付けます。**  

```
New-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Associated
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : Associated with AWS-UpdateSSMAgent
Status.AdditionalInfo :
```
**例 2: この例では、ターゲットを使用して、設定ドキュメントをインスタンスに関連付けます。**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
New-SSMAssociation -Name "AWS-UpdateSSMAgent" -Target $target
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**例 3: この例では、ターゲットとパラメータを使用して、設定ドキュメントをインスタンスに関連付けます。**  

```
$target = @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
$params = @{
  "action"="configure"
  "mode"="ec2"
  "optionalConfigurationSource"="ssm"
  "optionalConfigurationLocation"=""
  "optionalRestart"="yes"
}
New-SSMAssociation -Name "Configure-CloudWatch" -AssociationName "CWConfiguration" -Target $target -Parameter $params
```
**出力:**  

```
Name                  : Configure-CloudWatch
InstanceId            :
Date                  : 5/17/2018 3:17:44 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
**例 4: この例では、`AWS-GatherSoftwareInventory` を使用して、リージョン内におけるすべてのインスタンスとの関連付けを作成します。また、収集するパラメータにカスタムファイルとレジストリの場所を指定します。**  

```
$params = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$params["windowsRegistry"] ='[{"Path":"HKEY_LOCAL_MACHINE\SOFTWARE\Amazon\MachineImage","Recursive":false,"ValueNames":["AMIName"]}]'
$params["files"] = '[{"Path":"C:\Program Files","Pattern":["*.exe"],"Recursive":true}, {"Path":"C:\ProgramData","Pattern":["*.log"],"Recursive":true}]' 
New-SSMAssociation -AssociationName new-in-mum -Name AWS-GatherSoftwareInventory -Target @{Key="instanceids";Values="*"} -Parameter $params -region ap-south-1 -ScheduleExpression "rate(720 minutes)"
```
**出力:**  

```
Name                  : AWS-GatherSoftwareInventory
InstanceId            :
Date                  : 6/9/2019 8:57:56 AM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-SSMAssociationFromBatch`
<a name="ssm_CreateAssociationBatch_powershell_5_topic"></a>

次のコード例は、`New-SSMAssociationFromBatch` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、設定ドキュメントを複数のインスタンスに関連付けます。出力では、成功したオペレーションと失敗したオペレーションのリストが返されます (該当する場合)。**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
New-SSMAssociationFromBatch -Entry $option1,$option2
```
**出力:**  

```
Failed  Successful
------  ----------
{}      {Amazon.SimpleSystemsManagement.Model.FailedCreateAssociation, Amazon.SimpleSystemsManagement.Model.FailedCreateAsso...
```
**例 2: この例では、成功したオペレーションの詳細を表示します。**  

```
$option1 = @{InstanceId="i-0cb2b964d3e14fd9f";Name=@("AWS-UpdateSSMAgent")}
$option2 = @{InstanceId="i-0000293ffd8c57862";Name=@("AWS-UpdateSSMAgent")}
(New-SSMAssociationFromBatch -Entry $option1,$option2).Successful
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateAssociationBatch](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-SSMDocument`
<a name="ssm_CreateDocument_powershell_5_topic"></a>

次のコード例は、`New-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アカウントにドキュメントを作成します。ドキュメントは JSON 形式である必要があります。設定ドキュメントの記述については、「SSM API Reference」の「Configuration Document」を参照してください。**  

```
New-SSMDocument -Content (Get-Content -Raw "c:\temp\RunShellScript.json") -Name "RunShellScript" -DocumentType "Command"
```
**出力:**  

```
CreatedDate     : 3/1/2017 1:21:33 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 1
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 1
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Creating
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateDocument](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-SSMMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`New-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、そのウィンドウは、毎週火曜日の午後 4 時に 4 時間実行され (カットオフは 1 時間)、関連付けられていないターゲットを許可する、指定された名前の新しいメンテナンスウィンドウを作成します。**  

```
New-SSMMaintenanceWindow -Name "MyMaintenanceWindow" -Duration 4 -Cutoff 1 -AllowUnassociatedTarget $true -Schedule "cron(0 16 ? * TUE *)"
```
**出力:**  

```
mw-03eb53e1ea7383998
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-SSMPatchBaseline`
<a name="ssm_CreatePatchBaseline_powershell_5_topic"></a>

次のコード例は、`New-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、本番環境で Windows Server 2019 を実行しているマネージドインスタンスに対して、Microsoft からリリースされてから 7 日後にパッチを承認するパッチベースラインを作成します。**  

```
$rule = New-Object Amazon.SimpleSystemsManagement.Model.PatchRule
$rule.ApproveAfterDays = 7

$ruleFilters = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilterGroup

$patchFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$patchFilter.Key="PRODUCT"
$patchFilter.Values="WindowsServer2019"

$severityFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$severityFilter.Key="MSRC_SEVERITY"
$severityFilter.Values.Add("Critical")
$severityFilter.Values.Add("Important")
$severityFilter.Values.Add("Moderate")

$classificationFilter = New-Object Amazon.SimpleSystemsManagement.Model.PatchFilter
$classificationFilter.Key = "CLASSIFICATION"
$classificationFilter.Values.Add( "SecurityUpdates" )
$classificationFilter.Values.Add( "Updates" )
$classificationFilter.Values.Add( "UpdateRollups" )
$classificationFilter.Values.Add( "CriticalUpdates" )

$ruleFilters.PatchFilters.Add($severityFilter)
$ruleFilters.PatchFilters.Add($classificationFilter)
$ruleFilters.PatchFilters.Add($patchFilter)
$rule.PatchFilterGroup = $ruleFilters

New-SSMPatchBaseline -Name "Production-Baseline-Windows2019" -Description "Baseline containing all updates approved for production systems" -ApprovalRules_PatchRule $rule
```
**出力:**  

```
pb-0z4z6221c4296b23z
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-SSMDefaultPatchBaseline`
<a name="ssm_RegisterDefaultPatchBaseline_powershell_5_topic"></a>

次のコード例は、`Register-SSMDefaultPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチベースラインをデフォルトのパッチベースラインとして登録します。**  

```
Register-SSMDefaultPatchBaseline -BaselineId "pb-03da896ca3b68b639"
```
**出力:**  

```
pb-03da896ca3b68b639
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RegisterDefaultPatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-SSMPatchBaselineForPatchGroup`
<a name="ssm_RegisterPatchBaselineForPatchGroup_powershell_5_topic"></a>

次のコード例は、`Register-SSMPatchBaselineForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチグループのパッチベースラインを登録します。**  

```
Register-SSMPatchBaselineForPatchGroup -BaselineId "pb-03da896ca3b68b639" -PatchGroup "Production"
```
**出力:**  

```
BaselineId           PatchGroup
----------           ----------
pb-03da896ca3b68b639 Production
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RegisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-SSMTargetWithMaintenanceWindow`
<a name="ssm_RegisterTargetWithMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`Register-SSMTargetWithMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスをメンテナンスウィンドウに登録します。**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**出力:**  

```
d8e47760-23ed-46a5-9f28-927337725398
```
**例 2: この例では、複数のインスタンスをメンテナンスウィンドウに登録します。**  

```
$option1 = @{Key="InstanceIds";Values=@("i-0000293ffd8c57862","i-0cb2b964d3e14fd9f")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Single instance" -ResourceType "INSTANCE"
```
**出力:**  

```
6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
**例 3: この例では、EC2 タグを使用して、インスタンスをメンテナンスウィンドウに登録します。**  

```
$option1 = @{Key="tag:Environment";Values=@("Production")}
Register-SSMTargetWithMaintenanceWindow -WindowId "mw-06cf17cbefcb4bf4f" -Target $option1 -OwnerInformation "Production Web Servers" -ResourceType "INSTANCE"
```
**出力:**  

```
2994977e-aefb-4a71-beac-df620352f184
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RegisterTargetWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-SSMTaskWithMaintenanceWindow`
<a name="ssm_RegisterTaskWithMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`Register-SSMTaskWithMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンス ID を使用して、タスクをメンテナンスウィンドウに登録します。出力はタスク ID です。**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

Register-SSMTaskWithMaintenanceWindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="InstanceIds";Values="i-0000293ffd8c57862" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**出力:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**例 2: この例では、ターゲット ID を使用して、タスクをメンテナンスウィンドウに登録します。出力はタスク ID です。**  

```
$parameters = @{}
$parameterValues = New-Object Amazon.SimpleSystemsManagement.Model.MaintenanceWindowTaskParameterValueExpression
$parameterValues.Values = @("Install")
$parameters.Add("Operation", $parameterValues)

register-ssmtaskwithmaintenancewindow -WindowId "mw-03a342e62c96d31b0" -ServiceRoleArn "arn:aws:iam::123456789012:role/MaintenanceWindowsRole" -MaxConcurrency 1 -MaxError 1 -TaskArn "AWS-RunShellScript" -Target @{ Key="WindowTargetIds";Values="350d44e6-28cc-44e2-951f-4b2c985838f6" } -TaskType "RUN_COMMAND" -Priority 10 -TaskParameter $parameters
```
**出力:**  

```
f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
**例 3: この例では、run コマンドドキュメント `AWS-RunPowerShellScript` のパラメータオブジェクトを作成し、ターゲット ID を使用して任意のメンテナンスウィンドウを持つタスクを作成します。返される出力はタスク ID です。**  

```
$parameters = [Collections.Generic.Dictionary[String,Collections.Generic.List[String]]]::new()
$parameters.Add("commands",@("ipconfig","dir env:\computername"))
$parameters.Add("executionTimeout",@(3600))

$props = @{
    WindowId = "mw-0123e4cce56ff78ae"
    ServiceRoleArn = "arn:aws:iam::123456789012:role/MaintenanceWindowsRole"
    MaxConcurrency = 1
    MaxError = 1
    TaskType = "RUN_COMMAND"
    TaskArn = "AWS-RunPowerShellScript"
    Target = @{Key="WindowTargetIds";Values="fe1234ea-56d7-890b-12f3-456b789bee0f"}
    Priority = 1
    RunCommand_Parameter = $parameters
    Name = "set-via-cmdlet"
}

Register-SSMTaskWithMaintenanceWindow @props
```
**出力:**  

```
f1e2ef34-5678-12e3-456a-12334c5c6cbe
```
**例 4: この例では、 という名前のドキュメントを使用して AWS Systems Manager Automation タスクを登録します`Create-Snapshots`。**  

```
$automationParameters = @{}
$automationParameters.Add( "instanceId", @("{{ TARGET_ID }}") )
$automationParameters.Add( "AutomationAssumeRole", @("{arn:aws:iam::111111111111:role/AutomationRole}") )
$automationParameters.Add( "SnapshotTimeout", @("PT20M") )
Register-SSMTaskWithMaintenanceWindow -WindowId mw-123EXAMPLE456`
    -ServiceRoleArn "arn:aws:iam::123456789012:role/MW-Role"`
    -MaxConcurrency 1 -MaxError 1 -TaskArn "CreateVolumeSnapshots"`
    -Target @{ Key="WindowTargetIds";Values="4b5acdf4-946c-4355-bd68-4329a43a5fd1" }`
    -TaskType "AUTOMATION"`
    -Priority 4`
    -Automation_DocumentVersion '$DEFAULT' -Automation_Parameter $automationParameters -Name "Create-Snapshots"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RegisterTaskWithMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SSMActivation`
<a name="ssm_DeleteActivation_powershell_5_topic"></a>

次のコード例は、`Remove-SSMActivation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、アクティベーションを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMActivation -ActivationId "08e51e79-1e36-446c-8e63-9458569c1363"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteActivation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SSMAssociation`
<a name="ssm_DeleteAssociation_powershell_5_topic"></a>

次のコード例は、`Remove-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスとドキュメント間の関連付けを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMAssociation -InstanceId "i-0cb2b964d3e14fd9f" -Name "AWS-UpdateSSMAgent"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteAssociation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SSMDocument`
<a name="ssm_DeleteDocument_powershell_5_topic"></a>

次のコード例は、`Remove-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ドキュメントを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMDocument -Name "RunShellScript"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteDocument](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SSMMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`Remove-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウを削除します。**  

```
Remove-SSMMaintenanceWindow -WindowId "mw-06d59c1a07c022145"
```
**出力:**  

```
mw-06d59c1a07c022145
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SSMParameter`
<a name="ssm_DeleteParameter_powershell_5_topic"></a>

次のコード例は、`Remove-SSMParameter` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例ではパラメータを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMParameter -Name "helloWorld"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteParameter](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SSMPatchBaseline`
<a name="ssm_DeletePatchBaseline_powershell_5_topic"></a>

次のコード例は、`Remove-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチベースラインを削除します。**  

```
Remove-SSMPatchBaseline -BaselineId "pb-045f10b4f382baeda"
```
**出力:**  

```
pb-045f10b4f382baeda
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeletePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-SSMResourceTag`
<a name="ssm_RemoveTagsFromResource_powershell_5_topic"></a>

次のコード例は、`Remove-SSMResourceTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウからタグを削除します。コマンドが成功した場合、出力はありません。**  

```
Remove-SSMResourceTag -ResourceId "mw-03eb9db42890fb82d" -ResourceType "MaintenanceWindow" -TagKey "Production"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RemoveTagsFromResource](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Send-SSMCommand`
<a name="ssm_SendCommand_powershell_5_topic"></a>

次のコード例は、`Send-SSMCommand` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ターゲットインスタンスで echo コマンドを実行します。**  

```
Send-SSMCommand -DocumentName "AWS-RunPowerShellScript" -Parameter @{commands = "echo helloWorld"} -Target @{Key="instanceids";Values=@("i-0cb2b964d3e14fd9f")}
```
**出力:**  

```
CommandId          : d8d190fc-32c1-4d65-a0df-ff5ff3965524
Comment            : 
CompletedCount     : 0
DocumentName       : AWS-RunPowerShellScript
ErrorCount         : 0
ExpiresAfter       : 3/7/2017 10:48:37 PM
InstanceIds        : {}
MaxConcurrency     : 50
MaxErrors          : 0
NotificationConfig : Amazon.SimpleSystemsManagement.Model.NotificationConfig
OutputS3BucketName : 
OutputS3KeyPrefix  : 
OutputS3Region     : 
Parameters         : {[commands, Amazon.Runtime.Internal.Util.AlwaysSendList`1[System.String]]}
RequestedDateTime  : 3/7/2017 9:48:37 PM
ServiceRole        : 
Status             : Pending
StatusDetails      : Pending
TargetCount        : 0
Targets            : {instanceids}
```
**例 2: この例は、ネストされたパラメータを受け入れるコマンドを実行する方法を示しています。**  

```
Send-SSMCommand -DocumentName "AWS-RunRemoteScript" -Parameter @{ sourceType="GitHub";sourceInfo='{"owner": "me","repository": "amazon-ssm","path": "Examples/Install-Win32OpenSSH"}'; "commandLine"=".\Install-Win32OpenSSH.ps1"} -InstanceId i-0cb2b964d3e14fd9f
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[SendCommand](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Start-SSMAutomationExecution`
<a name="ssm_StartAutomationExecution_powershell_5_topic"></a>

次のコード例は、`Start-SSMAutomationExecution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、オートメーションロール、AMI ソース ID、および Amazon EC2 インスタンスロールを指定するドキュメントを実行します。**  

```
Start-SSMAutomationExecution -DocumentName AWS-UpdateLinuxAmi -Parameter @{'AutomationAssumeRole'='arn:aws:iam::123456789012:role/SSMAutomationRole';'SourceAmiId'='ami-f173cc91';'InstanceIamRole'='EC2InstanceRole'}
```
**出力:**  

```
3a532a4f-0382-11e7-9df7-6f11185f6dd1
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[StartAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Start-SSMSession`
<a name="ssm_StartSession_powershell_5_topic"></a>

次のコード例は、`Start-SSMSession` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、Session Manager のセッションのターゲットへの接続を開始し、ポート転送を有効にします。注: AWSCredentials を使用して設定していない場合は、Region パラメータを追加する必要があります。**  

```
Start-SSMSession -Target 'i-064578e5e7454488f' -DocumentName 'AWS-StartPortForwardingSession' -Parameter @{ localPortNumber = '8080'; portNumber = '80' } -Region 'us-west-1'
```
**出力:**  

```
Starting session with SessionId: testUser-xi4glew849asyeryde34u4dfsdfy
Port 8080 opened for sessionId testUser-xi4glew849asyeryde34u4dfsdfy.
Waiting for connections...
```
**例 2: この例では、Session Manager セッションに指定されたインスタンスを使用してインタラクティブセッションを作成します。**  

```
Start-SSMSession -Target 'i-1234567890abcdef0' -Region 'us-west-1'
```
**出力:**  

```
Starting session with SessionId : testUser-xi4glew849asyeryde34u4dfsdfy
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
                                                                                                                                                                                                
Install the latest PowerShell for new features and improvements!
                                                                                                                                                      
PS C:\Windows\system32> whoami
ec2amaz-fnsdrwv\ec2-test-user
PS C:\Windows\system32>
```
**例 3: この例では、セッションに接続せずにセッションを作成し、セッションへの接続に必要な SessionId、StreamUrl、TokenValue のプロパティを返します。**  

```
Start-SSMSession -Target 'i-1234567890abcdef0' -Region 'us-west-1' -DisablePluginInvocation
```
**出力:**  

```
SessionId        : testUser-xi4glew849asyeryde34u4dfsdfy
StreamUrl        : {StreamUrl value redacted}
TokenValue       : {Token value redacted}
ContentLength    : 1207
HttpStatusCode   : OK
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[StartSession](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Stop-SSMAutomationExecution`
<a name="ssm_StopAutomationExecution_powershell_5_topic"></a>

次のコード例は、`Stop-SSMAutomationExecution` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、オートメーションの実行を停止します。コマンドが成功した場合、出力はありません。**  

```
Stop-SSMAutomationExecution -AutomationExecutionId "4105a4fc-f944-11e6-9d32-8fb2db27a909"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[StopAutomationExecution](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Stop-SSMCommand`
<a name="ssm_CancelCommand_powershell_5_topic"></a>

次のコード例は、`Stop-SSMCommand` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、コマンドのキャンセルを試みます。オペレーションが成功した場合、出力はありません。**  

```
Stop-SSMCommand -CommandId "9ded293e-e792-4440-8e3e-7b8ec5feaa38"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CancelCommand](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-SSMManagedInstance`
<a name="ssm_DeregisterManagedInstance_powershell_5_topic"></a>

次のコード例は、`Unregister-SSMManagedInstance` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、マネージドインスタンスを登録解除します。コマンドが成功した場合、出力はありません。**  

```
Unregister-SSMManagedInstance -InstanceId "mi-08ab247cdf1046573"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeregisterManagedInstance](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-SSMPatchBaselineForPatchGroup`
<a name="ssm_DeregisterPatchBaselineForPatchGroup_powershell_5_topic"></a>

次のコード例は、`Unregister-SSMPatchBaselineForPatchGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、パッチグループをパッチベースラインから登録解除します。**  

```
Unregister-SSMPatchBaselineForPatchGroup -BaselineId "pb-045f10b4f382baeda" -PatchGroup "Production"
```
**出力:**  

```
BaselineId           PatchGroup
----------           ----------
pb-045f10b4f382baeda Production
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeregisterPatchBaselineForPatchGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-SSMTargetFromMaintenanceWindow`
<a name="ssm_DeregisterTargetFromMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`Unregister-SSMTargetFromMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウからターゲットを削除します。**  

```
Unregister-SSMTargetFromMaintenanceWindow -WindowTargetId "6ab5c208-9fc4-4697-84b7-b02a6cc25f7d" -WindowId "mw-06cf17cbefcb4bf4f"
```
**出力:**  

```
WindowId             WindowTargetId
--------             --------------
mw-06cf17cbefcb4bf4f 6ab5c208-9fc4-4697-84b7-b02a6cc25f7d
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeregisterTargetFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-SSMTaskFromMaintenanceWindow`
<a name="ssm_DeregisterTaskFromMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`Unregister-SSMTaskFromMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウからタスクを削除します。**  

```
Unregister-SSMTaskFromMaintenanceWindow -WindowTaskId "f34a2c47-ddfd-4c85-a88d-72366b69af1b" -WindowId "mw-03a342e62c96d31b0"
```
**出力:**  

```
WindowId             WindowTaskId
--------             ------------
mw-03a342e62c96d31b0 f34a2c47-ddfd-4c85-a88d-72366b69af1b
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeregisterTaskFromMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-SSMAssociation`
<a name="ssm_UpdateAssociation_powershell_5_topic"></a>

次のコード例は、`Update-SSMAssociation` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、新しいドキュメントバージョンとの関連付けを更新します。**  

```
Update-SSMAssociation -AssociationId "93285663-92df-44cb-9f26-2292d4ecc439" -DocumentVersion "1"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            :
Date                  : 3/1/2017 6:22:21 PM
Status.Name           :
Status.Date           :
Status.Message        :
Status.AdditionalInfo :
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateAssociation](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-SSMAssociationStatus`
<a name="ssm_UpdateAssociationStatus_powershell_5_topic"></a>

次のコード例は、`Update-SSMAssociationStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、インスタンスと設定ドキュメント間の関連付けのステータスを更新します。**  

```
Update-SSMAssociationStatus -Name "AWS-UpdateSSMAgent" -InstanceId "i-0000293ffd8c57862" -AssociationStatus_Date "2015-02-20T08:31:11Z" -AssociationStatus_Name "Pending" -AssociationStatus_Message "temporary_status_change" -AssociationStatus_AdditionalInfo "Additional-Config-Needed"
```
**出力:**  

```
Name                  : AWS-UpdateSSMAgent
InstanceId            : i-0000293ffd8c57862
Date                  : 2/23/2017 6:55:22 PM
Status.Name           : Pending
Status.Date           : 2/20/2015 8:31:11 AM
Status.Message        : temporary_status_change
Status.AdditionalInfo : Additional-Config-Needed
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateAssociationStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-SSMDocument`
<a name="ssm_UpdateDocument_powershell_5_topic"></a>

次のコード例は、`Update-SSMDocument` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: これは、指定した JSON ファイルの更新内容を含むドキュメントの新しいバージョンを作成するためのものです。ドキュメントは JSON 形式である必要があります。ドキュメントバージョンは、「Get-SSMDocumentVersionList」コマンドレットで取得できます。**  

```
Update-SSMDocument -Name RunShellScript -DocumentVersion "1" -Content (Get-Content -Raw "c:\temp\RunShellScript.json")
```
**出力:**  

```
CreatedDate     : 3/1/2017 2:59:17 AM
DefaultVersion  : 1
Description     : Run an updated script
DocumentType    : Command
DocumentVersion : 2
Hash            : 1d5ce820e999ff051eb4841ed887593daf77120fd76cae0d18a53cc42e4e22c1
HashType        : Sha256
LatestVersion   : 2
Name            : RunShellScript
Owner           : 809632081692
Parameters      : {commands}
PlatformTypes   : {Linux}
SchemaVersion   : 2.0
Sha1            :
Status          : Updating
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateDocument](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-SSMDocumentDefaultVersion`
<a name="ssm_UpdateDocumentDefaultVersion_powershell_5_topic"></a>

次のコード例は、`Update-SSMDocumentDefaultVersion` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: ここではドキュメントのデフォルトバージョンを更新します。利用可能なドキュメントバージョンは、「Get-SSMDocumentVersionList」コマンドレットで取得できます。**  

```
Update-SSMDocumentDefaultVersion -Name "RunShellScript" -DocumentVersion "2"
```
**出力:**  

```
DefaultVersion Name
-------------- ----
2              RunShellScript
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateDocumentDefaultVersion](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-SSMMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_powershell_5_topic"></a>

次のコード例は、`Update-SSMMaintenanceWindow` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、メンテナンスウィンドウの名前を更新します。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Name "My-Renamed-MW"
```
**出力:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**例 2: この例では、メンテナンスウィンドウを有効にします。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $true
```
**出力:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : True
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
**例 3: この例では、メンテナンスウィンドウを無効にします。**  

```
Update-SSMMaintenanceWindow -WindowId "mw-03eb9db42890fb82d" -Enabled $false
```
**出力:**  

```
AllowUnassociatedTargets : False
Cutoff                   : 1
Duration                 : 2
Enabled                  : False
Name                     : My-Renamed-MW
Schedule                 : cron(0 */30 * * * ? *)
WindowId                 : mw-03eb9db42890fb82d
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateMaintenanceWindow](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-SSMManagedInstanceRole`
<a name="ssm_UpdateManagedInstanceRole_powershell_5_topic"></a>

次のコード例は、`Update-SSMManagedInstanceRole` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、マネージドインスタンスのロールを更新します。コマンドが成功した場合、出力はありません。**  

```
Update-SSMManagedInstanceRole -InstanceId "mi-08ab247cdf1046573" -IamRole "AutomationRole"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdateManagedInstanceRole](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Update-SSMPatchBaseline`
<a name="ssm_UpdatePatchBaseline_powershell_5_topic"></a>

次のコード例は、`Update-SSMPatchBaseline` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、2 つのパッチを拒否済み、1 つのパッチを承認済みとして既存のパッチベースラインに追加します。**  

```
Update-SSMPatchBaseline -BaselineId "pb-03da896ca3b68b639" -RejectedPatch "KB2032276","MS10-048" -ApprovedPatch "KB2124261"
```
**出力:**  

```
ApprovalRules   : Amazon.SimpleSystemsManagement.Model.PatchRuleGroup
ApprovedPatches : {KB2124261}
BaselineId      : pb-03da896ca3b68b639
CreatedDate     : 3/3/2017 5:02:19 PM
Description     : Baseline containing all updates approved for production systems
GlobalFilters   : Amazon.SimpleSystemsManagement.Model.PatchFilterGroup
ModifiedDate    : 3/3/2017 5:22:10 PM
Name            : Production-Baseline
RejectedPatches : {KB2032276, MS10-048}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[UpdatePatchBaseline](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-SSMComplianceItem`
<a name="ssm_PutComplianceItems_powershell_5_topic"></a>

次のコード例は、`Write-SSMComplianceItem` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、任意のマネージドインスタンスのカスタムコンプライアンス項目を書き込みます。**  

```
$item = [Amazon.SimpleSystemsManagement.Model.ComplianceItemEntry]::new()
$item.Id = "07Jun2019-3"
$item.Severity="LOW"
$item.Status="COMPLIANT"
$item.Title="Fin-test-1 - custom"
Write-SSMComplianceItem -ResourceId mi-012dcb3ecea45b678 -ComplianceType Custom:VSSCompliant2 -ResourceType ManagedInstance -Item $item -ExecutionSummary_ExecutionTime "07-Jun-2019"
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutComplianceItems](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `Write-SSMInventory`
<a name="ssm_PutInventory_powershell_5_topic"></a>

次のコード例は、`Write-SSMInventory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、ラックの場所情報をインスタンスに割り当てます。コマンドが成功した場合、出力はありません。**  

```
$data = New-Object "System.Collections.Generic.Dictionary[System.String,System.String]"
$data.Add("RackLocation", "Bay B/Row C/Rack D/Shelf F")

$items = New-Object "System.Collections.Generic.List[System.Collections.Generic.Dictionary[System.String, System.String]]"
$items.Add($data)

$customInventoryItem = New-Object Amazon.SimpleSystemsManagement.Model.InventoryItem
$customInventoryItem.CaptureTime = "2016-08-22T10:01:01Z"
$customInventoryItem.Content = $items
$customInventoryItem.TypeName = "Custom:TestRackInfo2"
$customInventoryItem.SchemaVersion = "1.0"

$inventoryItems = @($customInventoryItem)

Write-SSMInventory -InstanceId "i-0cb2b964d3e14fd9f" -Item $inventoryItems
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutInventory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Write-SSMParameter`
<a name="ssm_PutParameter_powershell_5_topic"></a>

次のコード例は、`Write-SSMParameter` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例ではパラメータを作成します。コマンドが成功した場合、出力はありません。**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "helloWorld"
```
**例 2: この例ではパラメータを変更します。コマンドが成功した場合、出力はありません。**  

```
Write-SSMParameter -Name "Welcome" -Type "String" -Value "Good day, Sunshine!" -Overwrite $true
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[PutParameter](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した Amazon Translate の例
<a name="powershell_5_translate_code_examples"></a>

次のコード例は、Amazon Translate で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ConvertTo-TRNTargetLanguage`
<a name="translate_TranslateText_powershell_5_topic"></a>

次のコード例は、`ConvertTo-TRNTargetLanguage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された英語テキストをフランス語に変換します。変換するテキストは、-Text パラメータとして渡すこともできます。**  

```
"Hello World" | ConvertTo-TRNTargetLanguage -SourceLanguageCode en -TargetLanguageCode fr
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TranslateText](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# AWS WAFV2 Tools for PowerShell V5 を使用した の例
<a name="powershell_5_wafv2_code_examples"></a>

次のコード例は、 で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS WAFV2。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `New-WAF2WebACL`
<a name="wafv2_CreateWebAcl_powershell_5_topic"></a>

次のコード例は、`New-WAF2WebACL` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このコマンドは、「waf-test」という名前の新しいウェブ ACL を作成します。サービス API ドキュメントによると、「DefaultAction」は必須プロパティです。したがって、「-DefaultAction\$1Allow」または「-DefaultAction\$1Block」の値を指定する必要があります。「-DefaultAction\$1Allow」と「-DefaultAction\$1Block」は必須プロパティではないため、上記の例に示すように、値「@\$1\$1」をプレースホルダーとして使用できます。**  

```
New-WAF2WebACL -Name "waf-test" -Scope REGIONAL -Region eu-west-1 -VisibilityConfig_CloudWatchMetricsEnabled $true -VisibilityConfig_SampledRequestsEnabled $true -VisibilityConfig_MetricName "waf-test" -Description "Test" -DefaultAction_Allow @{}
```
**出力:**  

```
ARN         : arn:aws:wafv2:eu-west-1:139480602983:regional/webacl/waf-test/19460b3f-db14-4b9a-8e23-a417e1eb007f
Description : Test
Id          : 19460b3f-db14-4b9a-8e23-a417e1eb007f
LockToken   : 5a0cd5eb-d911-4341-b313-b429e6d6b6ab
Name        : waf-test
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateWebAcl](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# Tools for PowerShell V5 を使用した WorkSpaces の例
<a name="powershell_5_workspaces_code_examples"></a>

次のコード例は、WorkSpaces で AWS Tools for PowerShell V5 を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `Approve-WKSIpRule`
<a name="workspaces_AuthorizeIpRules_powershell_5_topic"></a>

次のコード例は、`Approve-WKSIpRule` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、既存の IP グループにルールを追加します。**  

```
$Rule = @(
@{IPRule = "10.1.0.0/0"; RuleDesc = "First Rule Added"},
@{IPRule = "10.2.0.0/0"; RuleDesc = "Second Rule Added"}
)

Approve-WKSIpRule -GroupId wsipg-abcnx2fcw -UserRule $Rule
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AuthorizeIpRules](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Copy-WKSWorkspaceImage`
<a name="workspaces_CopyWorkspaceImage_powershell_5_topic"></a>

次のコード例は、`Copy-WKSWorkspaceImage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 ID を持つワークスペースイメージを、us-west-2 から「CopiedImageTest」という名前の現在のリージョンにコピーします。**  

```
Copy-WKSWorkspaceImage -Name CopiedImageTest -SourceRegion us-west-2 -SourceImageId wsi-djfoedhw6
```
**出力:**  

```
wsi-456abaqfe
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5)」の[CopyWorkspaceImage](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-WKSClientProperty`
<a name="workspaces_ModifyClientProperties_powershell_5_topic"></a>

次のコード例は、`Edit-WKSClientProperty` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、WorkSpaces クライアントの再接続を有効にします**  

```
Edit-WKSClientProperty -Region us-west-2 -ClientProperties_ReconnectEnabled "ENABLED" -ResourceId d-123414a369
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ModifyClientProperties](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-WKSSelfServicePermission`
<a name="workspaces_ModifySelfservicePermissions_powershell_5_topic"></a>

次のコード例は、`Edit-WKSSelfServicePermission` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、セルフサービスのアクセス許可を有効にして、指定ディレクトリのコンピューティングタイプを変更し、ボリュームサイズを増やせるようにします。**  

```
Edit-WKSSelfservicePermission -Region us-west-2 -ResourceId d-123454a369 -SelfservicePermissions_ChangeComputeType ENABLED -SelfservicePermissions_IncreaseVolumeSize ENABLED
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ModifySelfservicePermissions](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-WKSWorkspaceAccessProperty`
<a name="workspaces_ModifyWorkspaceAccessProperties_powershell_5_topic"></a>

次のコード例は、`Edit-WKSWorkspaceAccessProperty` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ディレクトリの Android と Chrome OS で Workspace アクセスを有効にします。**  

```
Edit-WKSWorkspaceAccessProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceAccessProperties_DeviceTypeAndroid ALLOW -WorkspaceAccessProperties_DeviceTypeChromeOs ALLOW
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ModifyWorkspaceAccessProperties](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-WKSWorkspaceCreationProperty`
<a name="workspaces_ModifyWorkspaceCreationProperties_powershell_5_topic"></a>

次のコード例は、`Edit-WKSWorkspaceCreationProperty` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルでは、Workspace の作成中にインターネットアクセスとメンテナンスモードをデフォルト値として true に設定します。**  

```
Edit-WKSWorkspaceCreationProperty -Region us-west-2 -ResourceId d-123454a369 -WorkspaceCreationProperties_EnableInternetAccess $true -WorkspaceCreationProperties_EnableMaintenanceMode $true
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ModifyWorkspaceCreationProperties](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-WKSWorkspaceProperty`
<a name="workspaces_ModifyWorkspaceProperties_powershell_5_topic"></a>

次のコード例は、`Edit-WKSWorkspaceProperty` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定された Workspace の Workspace 実行モードプロパティを Auto Stop に変更します。**  

```
Edit-WKSWorkspaceProperty -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceProperties_RunningMode AUTO_STOP
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ModifyWorkspaceProperties](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Edit-WKSWorkspaceState`
<a name="workspaces_ModifyWorkspaceState_powershell_5_topic"></a>

次のコード例は、`Edit-WKSWorkspaceState` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定された Workspace の状態を Available に変更します。**  

```
Edit-WKSWorkspaceState -WorkspaceId ws-w361s100v -Region us-west-2 -WorkspaceState AVAILABLE
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[ModifyWorkspaceState](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSClientProperty`
<a name="workspaces_DescribeClientProperties_powershell_5_topic"></a>

次のコード例は、`Get-WKSClientProperty` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ディレクトリのワークスペースクライアントのクライアントプロパティを取得します。**  

```
Get-WKSClientProperty -ResourceId d-223562a123
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeClientProperties](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSIpGroup`
<a name="workspaces_DescribeIpGroups_powershell_5_topic"></a>

次のコード例は、`Get-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定リージョン内の指定 IP グループの詳細を取得します。**  

```
Get-WKSIpGroup -Region us-east-1 -GroupId wsipg-8m1234v45
```
**出力:**  

```
GroupDesc GroupId         GroupName UserRules
--------- -------         --------- ---------
          wsipg-8m1234v45 TestGroup {Amazon.WorkSpaces.Model.IpRuleItem, Amazon.WorkSpaces.Model.IpRuleItem}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSTag`
<a name="workspaces_DescribeTags_powershell_5_topic"></a>

次のコード例は、`Get-WKSTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定された Workspace のタグを取得します。**  

```
Get-WKSTag -WorkspaceId ws-w361s234r -Region us-west-2
```
**出力:**  

```
Key         Value
---         -----
auto-delete no
purpose     Workbench
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSWorkspace`
<a name="workspaces_DescribeWorkspaces_powershell_5_topic"></a>

次のコード例は、`Get-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: すべての WorkSpaces の詳細をパイプラインに取得します。**  

```
Get-WKSWorkspace
```
**出力:**  

```
BundleId                    : wsb-1a2b3c4d
ComputerName                :
DirectoryId                 : d-1a2b3c4d
ErrorCode                   :
ErrorMessage                :
IpAddress                   :
RootVolumeEncryptionEnabled : False
State                       : PENDING
SubnetId                    :
UserName                    : myuser
UserVolumeEncryptionEnabled : False
VolumeEncryptionKey         :
WorkspaceId                 : ws-1a2b3c4d
WorkspaceProperties         : Amazon.WorkSpaces.Model.WorkspaceProperties
```
**例 2: このコマンドは、`us-west-2` リージョンのワークスペースの `WorkSpaceProperties` の子プロパティの値を表示します。`WorkSpaceProperties` の子プロパティの詳細については、https://docs.aws.amazon.com/workspaces/latest/api/API\$1WorkspaceProperties.html を参照してください。**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties
```
**出力:**  

```
        ComputeTypeName                     : STANDARD
        RootVolumeSizeGib                   : 80
        RunningMode                         : AUTO_STOP
        RunningModeAutoStopTimeoutInMinutes : 60
        UserVolumeSizeGib                   : 50
```
**例 3: このコマンドは、`us-west-2` リージョン内のワークスペースにおける `WorkSpaceProperties` の子プロパティ `RootVolumeSizeGib` の値を表示します。GiB 単位のルートボリュームサイズは 80 です。**  

```
(Get-WKSWorkspace -Region us-west-2 -WorkSpaceId ws-xdaf7hc9s).WorkspaceProperties.RootVolumeSizeGib
```
**出力:**  

```
        80
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSWorkspaceBundle`
<a name="workspaces_DescribeWorkspaceBundles_powershell_5_topic"></a>

次のコード例は、`Get-WKSWorkspaceBundle` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、現在のリージョンのすべての Workspace バンドルの詳細を取得します。**  

```
Get-WKSWorkspaceBundle
```
**出力:**  

```
BundleId        : wsb-sfhdgv342
ComputeType     : Amazon.WorkSpaces.Model.ComputeType
Description     : This bundle is custom
ImageId         : wsi-235aeqges
LastUpdatedTime : 12/26/2019 06:44:07
Name            : CustomBundleTest
Owner           : 233816212345
RootStorage     : Amazon.WorkSpaces.Model.RootStorage
UserStorage     : Amazon.WorkSpaces.Model.UserStorage
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeWorkspaceBundles](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSWorkspaceDirectory`
<a name="workspaces_DescribeWorkspaceDirectories_powershell_5_topic"></a>

次のコード例は、`Get-WKSWorkspaceDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、登録されたディレクトリの詳細を一覧表示します。**  

```
Get-WKSWorkspaceDirectory
```
**出力:**  

```
Alias                       : TestWorkspace
CustomerUserName            : Administrator
DirectoryId                 : d-123414a369
DirectoryName               : TestDirectory.com
DirectoryType               : MicrosoftAD
DnsIpAddresses              : {172.31.43.45, 172.31.2.97}
IamRoleId                   : arn:aws:iam::761234567801:role/workspaces_RoleDefault
IpGroupIds                  : {}
RegistrationCode            : WSpdx+4RRT43
SelfservicePermissions      : Amazon.WorkSpaces.Model.SelfservicePermissions
State                       : REGISTERED
SubnetIds                   : {subnet-1m3m7b43, subnet-ard11aba}
Tenancy                     : SHARED
WorkspaceAccessProperties   : Amazon.WorkSpaces.Model.WorkspaceAccessProperties
WorkspaceCreationProperties : Amazon.WorkSpaces.Model.DefaultWorkspaceCreationProperties
WorkspaceSecurityGroupId    : sg-0ed2441234a123c43
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeWorkspaceDirectories](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSWorkspaceImage`
<a name="workspaces_DescribeWorkspaceImages_powershell_5_topic"></a>

次のコード例は、`Get-WKSWorkspaceImage` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、リージョン内のすべてのイメージの詳細をすべて取得します。**  

```
Get-WKSWorkspaceImage
```
**出力:**  

```
Description     :This image is copied from another image
ErrorCode       :
ErrorMessage    :
ImageId         : wsi-345ahdjgo
Name            : CopiedImageTest
OperatingSystem : Amazon.WorkSpaces.Model.OperatingSystem
RequiredTenancy : DEFAULT
State           : AVAILABLE
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeWorkspaceImages](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSWorkspaceSnapshot`
<a name="workspaces_DescribeWorkspaceSnapshots_powershell_5_topic"></a>

次のコード例は、`Get-WKSWorkspaceSnapshot` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定ワークスペース用に作成された最新のスナップショットのタイムスタンプを示します。**  

```
Get-WKSWorkspaceSnapshot -WorkspaceId ws-w361s100v
```
**出力:**  

```
RebuildSnapshots                   RestoreSnapshots
----------------                   ----------------
{Amazon.WorkSpaces.Model.Snapshot} {Amazon.WorkSpaces.Model.Snapshot}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeWorkspaceSnapshots](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Get-WKSWorkspacesConnectionStatus`
<a name="workspaces_DescribeWorkspacesConnectionStatus_powershell_5_topic"></a>

次のコード例は、`Get-WKSWorkspacesConnectionStatus` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定された Workspace の接続ステータスを取得します。**  

```
Get-WKSWorkspacesConnectionStatus -WorkspaceId ws-w123s234r
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DescribeWorkspacesConnectionStatus](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

### `New-WKSIpGroup`
<a name="workspaces_CreateIpGroup_powershell_5_topic"></a>

次のコード例は、`New-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、FreshEmptyIpGroup という名前の空の IP グループを作成します**  

```
New-WKSIpGroup -GroupName "FreshNewIPGroup"
```
**出力:**  

```
wsipg-w45rty4ty
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateIpGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-WKSTag`
<a name="workspaces_CreateTags_powershell_5_topic"></a>

次のコード例は、`New-WKSTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、`ws-wsname` という名前のワークスペースに新しいタグを追加します。タグのキーは「Name」で、キー値は `AWS_Workspace` です。**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag
```
**例 2: この例では、`ws-wsname` という名前のワークスペースに複数のタグを追加します。1 つのタグには「Name」のキーと `AWS_Workspace` のキー値があり、もう 1 つのタグには「Stage」のタグキーと「Test」のキー値があります。**  

```
$tag = New-Object Amazon.WorkSpaces.Model.Tag
$tag.Key = "Name"
$tag.Value = "AWS_Workspace"

$tag2 = New-Object Amazon.WorkSpaces.Model.Tag
$tag2.Key = "Stage"
$tag2.Value = "Test"
New-WKSTag -Region us-west-2 -WorkspaceId ws-wsname -Tag $tag,$tag2
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `New-WKSWorkspace`
<a name="workspaces_CreateWorkspaces_powershell_5_topic"></a>

次のコード例は、`New-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定されたバンドル、ディレクトリ、ユーザーの WorkSpace を作成します。**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME"}
```
**例 2: この例では、複数の WorkSpaces を作成します。**  

```
New-WKSWorkspace -Workspace @{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_1"},@{"BundleID" = "wsb-1a2b3c4d"; "DirectoryId" = "d-1a2b3c4d"; "UserName" = "USERNAME_2"}
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[CreateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-WKSIpGroup`
<a name="workspaces_AssociateIpGroups_powershell_5_topic"></a>

次のコード例は、`Register-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定 IP グループを指定ディレクトリに登録します。**  

```
Register-WKSIpGroup -GroupId wsipg-23ahsdres -DirectoryId d-123412e123
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[AssociateIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Register-WKSWorkspaceDirectory`
<a name="workspaces_RegisterWorkspaceDirectory_powershell_5_topic"></a>

次のコード例は、`Register-WKSWorkspaceDirectory` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、Workspaces Service の指定されたディレクトリを登録します。**  

```
Register-WKSWorkspaceDirectory -DirectoryId d-123412a123 -EnableWorkDoc $false
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RegisterWorkspaceDirectory](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-WKSIpGroup`
<a name="workspaces_DeleteIpGroup_powershell_5_topic"></a>

次のコード例は、`Remove-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: この例では、指定 IP グループを削除します。**  

```
Remove-WKSIpGroup -GroupId wsipg-32fhgtred
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSIpGroup (DeleteIpGroup)" on target "wsipg-32fhgtred".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteIpGroup](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-WKSTag`
<a name="workspaces_DeleteTags_powershell_5_topic"></a>

次のコード例は、`Remove-WKSTag` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、Workspace に関連付けられたタグを削除します。**  

```
Remove-WKSTag -ResourceId ws-w10b3abcd -TagKey "Type"
```
**出力:**  

```
Confirm
Are you sure you want to perform this action?
Performing the operation "Remove-WKSTag (DeleteTags)" on target "ws-w10b3abcd".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help (default is "Y"): Y
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DeleteTags](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Remove-WKSWorkspace`
<a name="workspaces_TerminateWorkspaces_powershell_5_topic"></a>

次のコード例は、`Remove-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 複数の WorkSpaces を終了します。-Force スイッチを使用すると、コマンドレットの確認を求めるプロンプトが表示されなくなります。**  

```
Remove-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0" -Force
```
**例 2: すべての WorkSpaces のコレクションを取得し、Remove-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、すべての WorkSpaces を終了します。コマンドレットは、各 WorkSpace が終了する前にプロンプトを表示します。確認を非表示にするには、-Force スイッチを追加します。**  

```
Get-WKSWorkspaces | Remove-WKSWorkspace
```
**例 3: この例では、終了する WorkSpaces を定義する TerminateRequest オブジェクトを渡す方法を示します。-Force スイッチが指定されていない限り、コマンドレットは続行する前に確認を求めます。**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.TerminateRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Remove-WKSWorkspace -Request $arrRequest
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[TerminateWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Reset-WKSWorkspace`
<a name="workspaces_RebuildWorkspaces_powershell_5_topic"></a>

次のコード例は、`Reset-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された WorkSpace を再構築します。**  

```
Reset-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**例 2: すべての WorkSpaces のコレクションを取得し、Reset-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、WorkSpaces を再構築します。**  

```
Get-WKSWorkspaces | Reset-WKSWorkspace
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RebuildWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Restart-WKSWorkspace`
<a name="workspaces_RebootWorkspaces_powershell_5_topic"></a>

次のコード例は、`Restart-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 指定された WorkSpace を再起動します。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d"
```
**例 2: 複数の WorkSpaces を再起動します。**  

```
Restart-WKSWorkspace -WorkspaceId "ws-1a2b3c4d","ws-5a6b7c8d"
```
**例 3: すべての WorkSpaces のコレクションを取得し、Restart-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、WorkSpaces を再起動します。**  

```
Get-WKSWorkspaces | Restart-WKSWorkspace
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[RebootWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Stop-WKSWorkspace`
<a name="workspaces_StopWorkspaces_powershell_5_topic"></a>

次のコード例は、`Stop-WKSWorkspace` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: 複数の WorkSpaces を停止します。**  

```
Stop-WKSWorkspace -WorkspaceId "ws-1a2b3c4d5","ws-6a7b8c9d0"
```
**例 2: すべての WorkSpaces のコレクションを取得し、Stop-WKSWorkspace の -WorkSpaceId パラメータに ID をパイプして、WorkSpaces を停止します。**  

```
Get-WKSWorkspaces | Stop-WKSWorkspace
```
**例 3: この例では、停止する WorkSpaces を定義する StopRequest オブジェクトを渡す方法を示します。**  

```
$arrRequest = @()
$request1 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request1.WorkspaceId = 'ws-12345678'
$arrRequest += $request1
$request2 = New-Object Amazon.WorkSpaces.Model.StopRequest
$request2.WorkspaceId = 'ws-abcdefgh'
$arrRequest += $request2
Stop-WKSWorkspace -Request $arrRequest
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[StopWorkspaces](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

### `Unregister-WKSIpGroup`
<a name="workspaces_DisassociateIpGroups_powershell_5_topic"></a>

次のコード例は、`Unregister-WKSIpGroup` を使用する方法を示しています。

**Tools for PowerShell V5**  
**例 1: このサンプルは、指定ディレクトリから指定 IP グループを登録解除します。**  

```
Unregister-WKSIpGroup -GroupId wsipg-12abcdphq -DirectoryId d-123454b123
```
+  API の詳細については、AWS Tools for PowerShell コマンドレットリファレンス (V5) の「[DisassociateIpGroups](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。**

# SDK for Python (Boto3) のコード例
<a name="python_3_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for Python (Boto3) デベロッパーガイド ](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) ** – で Python を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23python)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](python_3_acm_code_examples.md)
+ [API ゲートウェイ](python_3_api-gateway_code_examples.md)
+ [Application Recovery Controller](python_3_route53-recovery-cluster_code_examples.md)
+ [Audit Manager](python_3_auditmanager_code_examples.md)
+ [Aurora](python_3_aurora_code_examples.md)
+ [Auto Scaling](python_3_auto-scaling_code_examples.md)
+ [Amazon Bedrock](python_3_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](python_3_bedrock-runtime_code_examples.md)
+ [Amazon Bedrock エージェント](python_3_bedrock-agent_code_examples.md)
+ [Amazon Bedrock エージェントランタイム](python_3_bedrock-agent-runtime_code_examples.md)
+ [CloudFormation](python_3_cloudformation_code_examples.md)
+ [CloudFront](python_3_cloudfront_code_examples.md)
+ [CloudWatch](python_3_cloudwatch_code_examples.md)
+ [CloudWatch Logs](python_3_cloudwatch-logs_code_examples.md)
+ [Amazon Cognito ID](python_3_cognito-identity_code_examples.md)
+ [Amazon Cognito ID プロバイダー](python_3_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](python_3_comprehend_code_examples.md)
+ [AWS Config](python_3_config-service_code_examples.md)
+ [AWS Control Tower](python_3_controltower_code_examples.md)
+ [Firehose](python_3_firehose_code_examples.md)
+ [Device Farm](python_3_device-farm_code_examples.md)
+ [Amazon DocumentDB](python_3_docdb_code_examples.md)
+ [DynamoDB](python_3_dynamodb_code_examples.md)
+ [Amazon EC2](python_3_ec2_code_examples.md)
+ [Amazon ECR](python_3_ecr_code_examples.md)
+ [Elastic Load Balancing - バージョン 2](python_3_elastic-load-balancing-v2_code_examples.md)
+ [Amazon EMR](python_3_emr_code_examples.md)
+ [EventBridge](python_3_eventbridge_code_examples.md)
+ [EventBridge スケジューラ](python_3_scheduler_code_examples.md)
+ [Amazon Glacier](python_3_glacier_code_examples.md)
+ [AWS Glue](python_3_glue_code_examples.md)
+ [HealthImaging](python_3_medical-imaging_code_examples.md)
+ [HealthLake](python_3_healthlake_code_examples.md)
+ [IAM](python_3_iam_code_examples.md)
+ [AWS IoT](python_3_iot_code_examples.md)
+ [AWS IoT data](python_3_iot-data-plane_code_examples.md)
+ [AWS IoT SiteWise](python_3_iotsitewise_code_examples.md)
+ [Amazon Keyspaces](python_3_keyspaces_code_examples.md)
+ [Kinesis](python_3_kinesis_code_examples.md)
+ [AWS KMS](python_3_kms_code_examples.md)
+ [Lambda](python_3_lambda_code_examples.md)
+ [Managed Service for Apache Flink](python_3_kinesis-analytics-v2_code_examples.md)
+ [AWS Marketplace カタログ API](python_3_marketplace-catalog_code_examples.md)
+ [AWS Marketplace 契約 API](python_3_marketplace-agreement_code_examples.md)
+ [Amazon MSK](python_3_kafka_code_examples.md)
+ [Neptune](python_3_neptune_code_examples.md)
+ [組織](python_3_organizations_code_examples.md)
+ [パートナーセントラル](python_3_partnercentral-selling_code_examples.md)
+ [Amazon Pinpoint](python_3_pinpoint_code_examples.md)
+ [Amazon Pinpoint SMS および音声 API](python_3_pinpoint-sms-voice_code_examples.md)
+ [Amazon Polly](python_3_polly_code_examples.md)
+ [Amazon RDS](python_3_rds_code_examples.md)
+ [Amazon RDS データサービス](python_3_rds-data_code_examples.md)
+ [Amazon Redshift](python_3_redshift_code_examples.md)
+ [Amazon Rekognition](python_3_rekognition_code_examples.md)
+ [Amazon S3](python_3_s3_code_examples.md)
+ [Amazon S3 Control](python_3_s3-control_code_examples.md)
+ [S3 ディレクトリバケット](python_3_s3-directory-buckets_code_examples.md)
+ [Secrets Manager](python_3_secrets-manager_code_examples.md)
+ [Amazon SES](python_3_ses_code_examples.md)
+ [Amazon SES API v2](python_3_sesv2_code_examples.md)
+ [Amazon SNS](python_3_sns_code_examples.md)
+ [Amazon SQS](python_3_sqs_code_examples.md)
+ [ステップ関数](python_3_sfn_code_examples.md)
+ [AWS STS](python_3_sts_code_examples.md)
+ [サポート](python_3_support_code_examples.md)
+ [Systems Manager](python_3_ssm_code_examples.md)
+ [Amazon Textract](python_3_textract_code_examples.md)
+ [Amazon Transcribe](python_3_transcribe_code_examples.md)

# SDK for Python (Boto3) を使用した ACM の例
<a name="python_3_acm_code_examples"></a>

次のコード例は、ACM AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="acm_Usage_ImportListRemove_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ACM から証明書をリクエストします。
+ 自己署名証明書をインポートします。
+ 証明書を一覧表示して記述します。
+ 証明書を削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。
ACM オペレーションをラップするクラスを作成します。  

```
import logging
from pprint import pprint

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def request_validation(
        self, domain, alternate_domains, method, validation_domains=None
    ):
        """
        Starts a validation request that results in a new certificate being issued
        by ACM. DNS validation requires that you add CNAME records to your DNS
        provider. Email validation sends email to a list of email addresses that
        are associated with the domain.

        For more information, see _Issuing and managing certificates_ in the ACM
        user guide.
            https://docs.aws.amazon.com/acm/latest/userguide/gs.html

        :param domain: The primary domain to associate with the certificate.
        :param alternate_domains: Subject Alternate Names (SANs) for the certificate.
        :param method: The validation method, either DNS or EMAIL.
        :param validation_domains: Alternate domains to use for email validation, when
                                   the email domain differs from the primary domain of
                                   the certificate.
        :return: The ARN of the requested certificate.
        """
        try:
            kwargs = {
                "DomainName": domain,
                "ValidationMethod": method,
                "SubjectAlternativeNames": alternate_domains,
            }
            if validation_domains is not None:
                kwargs["DomainValidationOptions"] = [
                    {"DomainName": key, "ValidationDomain": value}
                    for key, value in validation_domains.items()
                ]
            response = self.acm_client.request_certificate(**kwargs)
            certificate_arn = response["CertificateArn"]
            logger.info(
                "Requested %s validation for domain %s. Certificate ARN is %s.",
                method,
                domain,
                certificate_arn,
            )
        except ClientError:
            logger.exception(
                "Request for %s validation of domain %s failed.", method, domain
            )
            raise
        else:
            return certificate_arn


    def import_certificate(self, certificate_body, private_key):
        """
        Imports a self-signed certificate to ACM.

        :param certificate_body: The body of the certificate, in PEM format.
        :param private_key: The unencrypted private key of the certificate, in PEM
                            format.
        :return: The ARN of the imported certificate.
        """
        try:
            response = self.acm_client.import_certificate(
                Certificate=certificate_body, PrivateKey=private_key
            )
            certificate_arn = response["CertificateArn"]
            logger.info("Imported certificate.")
        except ClientError:
            logger.exception("Couldn't import certificate.")
            raise
        else:
            return certificate_arn


    def list(
        self,
        max_items,
        statuses=None,
        key_usage=None,
        extended_key_usage=None,
        key_types=None,
    ):
        """
        Lists the certificates for the current account.

        :param max_items: The maximum number of certificates to list.
        :param statuses: Filters the results to the specified statuses. If None, all
                         certificates are included.
        :param key_usage: Filters the results to the specified key usages. If None,
                          all key usages are included.
        :param extended_key_usage: Filters the results to the specified extended key
                                   usages. If None, all extended key usages are
                                   included.
        :param key_types: Filters the results to the specified key types. If None, all
                          key types are included.
        :return: The list of certificates.
        """
        try:
            kwargs = {"MaxItems": max_items}
            if statuses is not None:
                kwargs["CertificateStatuses"] = statuses
            includes = {}
            if key_usage is not None:
                includes["keyUsage"] = key_usage
            if extended_key_usage is not None:
                includes["extendedKeyUsage"] = extended_key_usage
            if key_types is not None:
                includes["keyTypes"] = key_types
            if includes:
                kwargs["Includes"] = includes
            response = self.acm_client.list_certificates(**kwargs)
            certificates = response["CertificateSummaryList"]
            logger.info("Got %s certificates.", len(certificates))
        except ClientError:
            logger.exception("Couldn't get certificates.")
            raise
        else:
            return certificates


    def describe(self, certificate_arn):
        """
        Gets certificate metadata.

        :param certificate_arn: The Amazon Resource Name (ARN) of the certificate.
        :return: Metadata about the certificate.
        """
        try:
            response = self.acm_client.describe_certificate(
                CertificateArn=certificate_arn
            )
            certificate = response["Certificate"]
            logger.info(
                "Got metadata for certificate for domain %s.", certificate["DomainName"]
            )
        except ClientError:
            logger.exception("Couldn't get data for certificate %s.", certificate_arn)
            raise
        else:
            return certificate


    def get(self, certificate_arn):
        """
        Gets the body and certificate chain of a certificate.

        :param certificate_arn: The ARN of the certificate.
        :return: The body and chain of a certificate.
        """
        try:
            response = self.acm_client.get_certificate(CertificateArn=certificate_arn)
            logger.info("Got certificate %s and its chain.", certificate_arn)
        except ClientError:
            logger.exception("Couldn't get certificate %s.", certificate_arn)
            raise
        else:
            return response


    def add_tags(self, certificate_arn, tags):
        """
        Adds tags to a certificate. Tags are key-value pairs that contain custom
        metadata.

        :param certificate_arn: The ARN of the certificate.
        :param tags: A dictionary of key-value tags to add to the certificate.
        """
        try:
            self.acm_client.add_tags_to_certificate(
                CertificateArn=certificate_arn,
                Tags=[{"Key": key, "Value": value} for key, value in tags.items()],
            )
            logger.info("Added %s tags to certificate %s.", len(tags), certificate_arn)
        except ClientError:
            logger.exception("Couldn't add tags to certificate %s.", certificate_arn)
            raise


    def list_tags(self, certificate_arn):
        """
        Lists the tags attached to a certificate.

        :param certificate_arn: The ARN of the certificate.
        :return: The dictionary of certificate tags.
        """
        try:
            response = self.acm_client.list_tags_for_certificate(
                CertificateArn=certificate_arn
            )
            tags = {tag["Key"]: tag["Value"] for tag in response["Tags"]}
            logger.info("Got %s tags for certificates %s.", len(tags), certificate_arn)
        except ClientError:
            logger.exception("Couldn't get tags for certificate %s.", certificate_arn)
            raise
        else:
            return tags


    def remove_tags(self, certificate_arn, tags):
        """
        Removes tags from a certificate. If the value of a tag is specified, the tag is
        removed only when the value matches the value of the certificate's tag.
        Otherwise, the tag is removed regardless of its value.

        :param certificate_arn: The ARN of the certificate.
        :param tags: The dictionary of tags to remove.
        """
        try:
            cert_tags = []
            for key, value in tags.items():
                tag = {"Key": key}
                if value is not None:
                    tag["Value"] = value
                cert_tags.append(tag)
            self.acm_client.remove_tags_from_certificate(
                CertificateArn=certificate_arn, Tags=cert_tags
            )
            logger.info(
                "Removed %s tags from certificate %s.", len(tags), certificate_arn
            )
        except ClientError:
            logger.exception(
                "Couldn't remove tags from certificate %s.", certificate_arn
            )
            raise


    def remove(self, certificate_arn):
        """
        Removes a certificate.

        :param certificate_arn: The ARN of the certificate to remove.
        """
        try:
            self.acm_client.delete_certificate(CertificateArn=certificate_arn)
            logger.info("Removed certificate %s.", certificate_arn)
        except ClientError:
            logger.exception("Couldn't remove certificate %s.", certificate_arn)
            raise
```
ラッパークラスを使用してアカウントの証明書を管理します。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the AWS Certificate Manager (ACM) demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    acm_certificate = AcmCertificate(boto3.client("acm"))
    domain = "example.com"
    sub_domains = [f"{sub}.{domain}" for sub in ["test", "dev"]]
    print(f"Request a certificate for {domain}.")
    certificate_arn = acm_certificate.request_validation(domain, sub_domains, "DNS")
    print(f"Started validation, got certificate ARN: {certificate_arn}.")

    import_cert_arn = None
    cert_file_name = input(
        "Enter the file name for a self-signed certificate in PEM format. "
        "This certificate will be imported to ACM. Press Enter to skip: "
    )
    if cert_file_name:
        pk_file_name = input(
            "Enter the file name for the unencrypted private key of the certificate. "
            "This file must also be in PEM format: "
        )
        if pk_file_name:
            with open(cert_file_name, "rb") as cert_file:
                import_cert = cert_file.read()
            with open(pk_file_name, "rb") as pk_file:
                import_pk = pk_file.read()
            import_cert_arn = acm_certificate.import_certificate(import_cert, import_pk)
            print(f"Certificate imported, got ARN: {import_cert_arn}")
        else:
            print("No private key file entered. Skipping certificate import.")
    else:
        print("Skipping self-signed certificate import.")

    print("Getting the first 10 issued certificates.")
    certificates = acm_certificate.list(10, statuses=["ISSUED"])
    print(f"Found {len(certificates)} issued certificates.")

    print(f"Getting metadata for certificate {certificate_arn}")
    cert_metadata = acm_certificate.describe(certificate_arn)
    pprint(cert_metadata)

    if import_cert_arn is not None:
        print(f"Getting certificate for imported certificate {import_cert_arn}")
        import_cert_data = acm_certificate.get(import_cert_arn)
        pprint(import_cert_data)

    print(f"Adding tags to certificate {certificate_arn}.")
    acm_certificate.add_tags(certificate_arn, {"purpose": "acm demo", "color": "green"})
    tags = acm_certificate.list_tags(certificate_arn)
    print(f"Found tags: {tags}")
    acm_certificate.remove_tags(certificate_arn, {key: None for key in tags})
    print("Removed tags.")

    print("Removing certificates added during the demo.")
    acm_certificate.remove(certificate_arn)
    if import_cert_arn is not None:
        acm_certificate.remove(import_cert_arn)

    print("Thanks for watching!")
    print("-" * 88)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AddTagsToCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/AddTagsToCertificate)
  + [DeleteCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/DeleteCertificate)
  + [DescribeCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/DescribeCertificate)
  + [GetCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/GetCertificate)
  + [ImportCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ImportCertificate)
  + [ListCertificates](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ListCertificates)
  + [ListTagsForCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ListTagsForCertificate)
  + [RemoveTagsFromCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/RemoveTagsFromCertificate)
  + [RequestCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/RequestCertificate)
  + [ResendValidationEmail](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ResendValidationEmail)

## アクション
<a name="actions"></a>

### `AddTagsToCertificate`
<a name="acm_AddTagsToCertificate_python_3_topic"></a>

次のコード例は、`AddTagsToCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def add_tags(self, certificate_arn, tags):
        """
        Adds tags to a certificate. Tags are key-value pairs that contain custom
        metadata.

        :param certificate_arn: The ARN of the certificate.
        :param tags: A dictionary of key-value tags to add to the certificate.
        """
        try:
            self.acm_client.add_tags_to_certificate(
                CertificateArn=certificate_arn,
                Tags=[{"Key": key, "Value": value} for key, value in tags.items()],
            )
            logger.info("Added %s tags to certificate %s.", len(tags), certificate_arn)
        except ClientError:
            logger.exception("Couldn't add tags to certificate %s.", certificate_arn)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AddTagsToCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/AddTagsToCertificate)」を参照してください。

### `DeleteCertificate`
<a name="acm_DeleteCertificate_python_3_topic"></a>

次のコード例は、`DeleteCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def remove(self, certificate_arn):
        """
        Removes a certificate.

        :param certificate_arn: The ARN of the certificate to remove.
        """
        try:
            self.acm_client.delete_certificate(CertificateArn=certificate_arn)
            logger.info("Removed certificate %s.", certificate_arn)
        except ClientError:
            logger.exception("Couldn't remove certificate %s.", certificate_arn)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/DeleteCertificate)」を参照してください。

### `DescribeCertificate`
<a name="acm_DescribeCertificate_python_3_topic"></a>

次のコード例は、`DescribeCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def describe(self, certificate_arn):
        """
        Gets certificate metadata.

        :param certificate_arn: The Amazon Resource Name (ARN) of the certificate.
        :return: Metadata about the certificate.
        """
        try:
            response = self.acm_client.describe_certificate(
                CertificateArn=certificate_arn
            )
            certificate = response["Certificate"]
            logger.info(
                "Got metadata for certificate for domain %s.", certificate["DomainName"]
            )
        except ClientError:
            logger.exception("Couldn't get data for certificate %s.", certificate_arn)
            raise
        else:
            return certificate
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/DescribeCertificate)」を参照してください。

### `GetCertificate`
<a name="acm_GetCertificate_python_3_topic"></a>

次のコード例は、`GetCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def get(self, certificate_arn):
        """
        Gets the body and certificate chain of a certificate.

        :param certificate_arn: The ARN of the certificate.
        :return: The body and chain of a certificate.
        """
        try:
            response = self.acm_client.get_certificate(CertificateArn=certificate_arn)
            logger.info("Got certificate %s and its chain.", certificate_arn)
        except ClientError:
            logger.exception("Couldn't get certificate %s.", certificate_arn)
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/GetCertificate)」を参照してください。

### `ImportCertificate`
<a name="acm_ImportCertificate_python_3_topic"></a>

次のコード例は、`ImportCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def import_certificate(self, certificate_body, private_key):
        """
        Imports a self-signed certificate to ACM.

        :param certificate_body: The body of the certificate, in PEM format.
        :param private_key: The unencrypted private key of the certificate, in PEM
                            format.
        :return: The ARN of the imported certificate.
        """
        try:
            response = self.acm_client.import_certificate(
                Certificate=certificate_body, PrivateKey=private_key
            )
            certificate_arn = response["CertificateArn"]
            logger.info("Imported certificate.")
        except ClientError:
            logger.exception("Couldn't import certificate.")
            raise
        else:
            return certificate_arn
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ImportCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ImportCertificate)」を参照してください。

### `ListCertificates`
<a name="acm_ListCertificates_python_3_topic"></a>

次のコード例は、`ListCertificates` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def list(
        self,
        max_items,
        statuses=None,
        key_usage=None,
        extended_key_usage=None,
        key_types=None,
    ):
        """
        Lists the certificates for the current account.

        :param max_items: The maximum number of certificates to list.
        :param statuses: Filters the results to the specified statuses. If None, all
                         certificates are included.
        :param key_usage: Filters the results to the specified key usages. If None,
                          all key usages are included.
        :param extended_key_usage: Filters the results to the specified extended key
                                   usages. If None, all extended key usages are
                                   included.
        :param key_types: Filters the results to the specified key types. If None, all
                          key types are included.
        :return: The list of certificates.
        """
        try:
            kwargs = {"MaxItems": max_items}
            if statuses is not None:
                kwargs["CertificateStatuses"] = statuses
            includes = {}
            if key_usage is not None:
                includes["keyUsage"] = key_usage
            if extended_key_usage is not None:
                includes["extendedKeyUsage"] = extended_key_usage
            if key_types is not None:
                includes["keyTypes"] = key_types
            if includes:
                kwargs["Includes"] = includes
            response = self.acm_client.list_certificates(**kwargs)
            certificates = response["CertificateSummaryList"]
            logger.info("Got %s certificates.", len(certificates))
        except ClientError:
            logger.exception("Couldn't get certificates.")
            raise
        else:
            return certificates
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[ListCertificates](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ListCertificates)」を参照してください。

### `ListTagsForCertificate`
<a name="acm_ListTagsForCertificate_python_3_topic"></a>

次のコード例は、`ListTagsForCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def list_tags(self, certificate_arn):
        """
        Lists the tags attached to a certificate.

        :param certificate_arn: The ARN of the certificate.
        :return: The dictionary of certificate tags.
        """
        try:
            response = self.acm_client.list_tags_for_certificate(
                CertificateArn=certificate_arn
            )
            tags = {tag["Key"]: tag["Value"] for tag in response["Tags"]}
            logger.info("Got %s tags for certificates %s.", len(tags), certificate_arn)
        except ClientError:
            logger.exception("Couldn't get tags for certificate %s.", certificate_arn)
            raise
        else:
            return tags
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListTagsForCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ListTagsForCertificate)」を参照してください。

### `RemoveTagsFromCertificate`
<a name="acm_RemoveTagsFromCertificate_python_3_topic"></a>

次のコード例は、`RemoveTagsFromCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def remove_tags(self, certificate_arn, tags):
        """
        Removes tags from a certificate. If the value of a tag is specified, the tag is
        removed only when the value matches the value of the certificate's tag.
        Otherwise, the tag is removed regardless of its value.

        :param certificate_arn: The ARN of the certificate.
        :param tags: The dictionary of tags to remove.
        """
        try:
            cert_tags = []
            for key, value in tags.items():
                tag = {"Key": key}
                if value is not None:
                    tag["Value"] = value
                cert_tags.append(tag)
            self.acm_client.remove_tags_from_certificate(
                CertificateArn=certificate_arn, Tags=cert_tags
            )
            logger.info(
                "Removed %s tags from certificate %s.", len(tags), certificate_arn
            )
        except ClientError:
            logger.exception(
                "Couldn't remove tags from certificate %s.", certificate_arn
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[RemoveTagsFromCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/RemoveTagsFromCertificate)」を参照してください。

### `RequestCertificate`
<a name="acm_RequestCertificate_python_3_topic"></a>

次のコード例は、`RequestCertificate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def request_validation(
        self, domain, alternate_domains, method, validation_domains=None
    ):
        """
        Starts a validation request that results in a new certificate being issued
        by ACM. DNS validation requires that you add CNAME records to your DNS
        provider. Email validation sends email to a list of email addresses that
        are associated with the domain.

        For more information, see _Issuing and managing certificates_ in the ACM
        user guide.
            https://docs.aws.amazon.com/acm/latest/userguide/gs.html

        :param domain: The primary domain to associate with the certificate.
        :param alternate_domains: Subject Alternate Names (SANs) for the certificate.
        :param method: The validation method, either DNS or EMAIL.
        :param validation_domains: Alternate domains to use for email validation, when
                                   the email domain differs from the primary domain of
                                   the certificate.
        :return: The ARN of the requested certificate.
        """
        try:
            kwargs = {
                "DomainName": domain,
                "ValidationMethod": method,
                "SubjectAlternativeNames": alternate_domains,
            }
            if validation_domains is not None:
                kwargs["DomainValidationOptions"] = [
                    {"DomainName": key, "ValidationDomain": value}
                    for key, value in validation_domains.items()
                ]
            response = self.acm_client.request_certificate(**kwargs)
            certificate_arn = response["CertificateArn"]
            logger.info(
                "Requested %s validation for domain %s. Certificate ARN is %s.",
                method,
                domain,
                certificate_arn,
            )
        except ClientError:
            logger.exception(
                "Request for %s validation of domain %s failed.", method, domain
            )
            raise
        else:
            return certificate_arn
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[RequestCertificate](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/RequestCertificate)」を参照してください。**

### `ResendValidationEmail`
<a name="acm_ResendValidationEmail_python_3_topic"></a>

次のコード例は、`ResendValidationEmail` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/acm#code-examples)での設定と実行の方法を確認してください。

```
class AcmCertificate:
    """
    Encapsulates ACM functions.
    """

    def __init__(self, acm_client):
        """
        :param acm_client: A Boto3 ACM client.
        """
        self.acm_client = acm_client


    def resend_validation_email(self, certificate_arn, domain, validation_domain):
        """
        Request that validation email is sent again, for a certificate that was
        previously requested with email validation.

        :param certificate_arn: The ARN of the certificate.
        :param domain: The primary domain of the certificate.
        :param validation_domain: Alternate domain to use for determining email
                                  addresses to use for validation.
        """
        try:
            self.acm_client.resend_validation_email(
                CertificateArn=certificate_arn,
                Domain=domain,
                ValidationDomain=validation_domain,
            )
            logger.info(
                "Validation email resent to validation domain %s.", validation_domain
            )
        except ClientError:
            logger.exception(
                "Couldn't resend validation email to %s.", validation_domain
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ResendValidationEmail](https://docs.aws.amazon.com/goto/boto3/acm-2015-12-08/ResendValidationEmail)」を参照してください。

# SDK for Python (Boto3) を使用した API Gateway の例
<a name="python_3_api-gateway_code_examples"></a>

次のコード例は、API Gateway AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateDeployment`
<a name="api-gateway_CreateDeployment_python_3_topic"></a>

次のコード例は、`CreateDeployment` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def deploy_api(self, stage_name):
        """
        Deploys a REST API. After a REST API is deployed, it can be called from any
        REST client, such as the Python Requests package or Postman.

        :param stage_name: The stage of the API to deploy, such as 'test'.
        :return: The base URL of the deployed REST API.
        """
        try:
            self.apig_client.create_deployment(
                restApiId=self.api_id, stageName=stage_name
            )
            self.stage = stage_name
            logger.info("Deployed stage %s.", stage_name)
        except ClientError:
            logger.exception("Couldn't deploy stage %s.", stage_name)
            raise
        else:
            return self.api_url()



    def api_url(self, resource=None):
        """
        Builds the REST API URL from its parts.

        :param resource: The resource path to append to the base URL.
        :return: The REST URL to the specified resource.
        """
        url = (
            f"https://{self.api_id}.execute-api.{self.apig_client.meta.region_name}"
            f".amazonaws.com/{self.stage}"
        )
        if resource is not None:
            url = f"{url}/{resource}"
        return url
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDeployment](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/CreateDeployment)」を参照してください。

### `CreateResource`
<a name="api-gateway_CreateResource_python_3_topic"></a>

次のコード例は、`CreateResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def add_rest_resource(self, parent_id, resource_path):
        """
        Adds a resource to a REST API.

        :param parent_id: The ID of the parent resource.
        :param resource_path: The path of the new resource, relative to the parent.
        :return: The ID of the new resource.
        """
        try:
            result = self.apig_client.create_resource(
                restApiId=self.api_id, parentId=parent_id, pathPart=resource_path
            )
            resource_id = result["id"]
            logger.info("Created resource %s.", resource_path)
        except ClientError:
            logger.exception("Couldn't create resource %s.", resource_path)
            raise
        else:
            return resource_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateResource](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/CreateResource)」を参照してください。

### `CreateRestApi`
<a name="api-gateway_CreateRestApi_python_3_topic"></a>

次のコード例は、`CreateRestApi` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def create_rest_api(self, api_name):
        """
        Creates a REST API on API Gateway. The default API has only a root resource
        and no HTTP methods.

        :param api_name: The name of the API. This descriptive name is not used in
                         the API path.
        :return: The ID of the newly created API.
        """
        try:
            result = self.apig_client.create_rest_api(name=api_name)
            self.api_id = result["id"]
            logger.info("Created REST API %s with ID %s.", api_name, self.api_id)
        except ClientError:
            logger.exception("Couldn't create REST API %s.", api_name)
            raise

        try:
            result = self.apig_client.get_resources(restApiId=self.api_id)
            self.root_id = next(
                item for item in result["items"] if item["path"] == "/"
            )["id"]
        except ClientError:
            logger.exception("Couldn't get resources for API %s.", self.api_id)
            raise
        except StopIteration as err:
            logger.exception("No root resource found in API %s.", self.api_id)
            raise ValueError from err

        return self.api_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateRestApi](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/CreateRestApi)」を参照してください。

### `DeleteRestApi`
<a name="api-gateway_DeleteRestApi_python_3_topic"></a>

次のコード例は、`DeleteRestApi` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def delete_rest_api(self):
        """
        Deletes a REST API, including all of its resources and configuration.
        """
        try:
            self.apig_client.delete_rest_api(restApiId=self.api_id)
            logger.info("Deleted REST API %s.", self.api_id)
            self.api_id = None
        except ClientError:
            logger.exception("Couldn't delete REST API %s.", self.api_id)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteRestApi](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/DeleteRestApi)」を参照してください。

### `GetResources`
<a name="api-gateway_GetResources_python_3_topic"></a>

次のコード例は、`GetResources` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def create_rest_api(self, api_name):
        """
        Creates a REST API on API Gateway. The default API has only a root resource
        and no HTTP methods.

        :param api_name: The name of the API. This descriptive name is not used in
                         the API path.
        :return: The ID of the newly created API.
        """
        try:
            result = self.apig_client.create_rest_api(name=api_name)
            self.api_id = result["id"]
            logger.info("Created REST API %s with ID %s.", api_name, self.api_id)
        except ClientError:
            logger.exception("Couldn't create REST API %s.", api_name)
            raise

        try:
            result = self.apig_client.get_resources(restApiId=self.api_id)
            self.root_id = next(
                item for item in result["items"] if item["path"] == "/"
            )["id"]
        except ClientError:
            logger.exception("Couldn't get resources for API %s.", self.api_id)
            raise
        except StopIteration as err:
            logger.exception("No root resource found in API %s.", self.api_id)
            raise ValueError from err

        return self.api_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetResources](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/GetResources)」を参照してください。

### `GetRestApis`
<a name="api-gateway_GetRestApis_python_3_topic"></a>

次のコード例は、`GetRestApis` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def get_rest_api_id(self, api_name):
        """
        Gets the ID of a REST API from its name by searching the list of REST APIs
        for the current account. Because names need not be unique, this returns only
        the first API with the specified name.

        :param api_name: The name of the API to look up.
        :return: The ID of the specified API.
        """
        try:
            rest_api = None
            paginator = self.apig_client.get_paginator("get_rest_apis")
            for page in paginator.paginate():
                rest_api = next(
                    (item for item in page["items"] if item["name"] == api_name), None
                )
                if rest_api is not None:
                    break
            self.api_id = rest_api["id"]
            logger.info("Found ID %s for API %s.", rest_api["id"], api_name)
        except ClientError:
            logger.exception("Couldn't find ID for API %s.", api_name)
            raise
        else:
            return rest_api["id"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetRestApis](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/GetRestApis)」を参照してください。

### `PutIntegration`
<a name="api-gateway_PutIntegration_python_3_topic"></a>

次のコード例は、`PutIntegration` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def add_integration_method(
        self,
        resource_id,
        rest_method,
        service_endpoint_prefix,
        service_action,
        service_method,
        role_arn,
        mapping_template,
    ):
        """
        Adds an integration method to a REST API. An integration method is a REST
        resource, such as '/users', and an HTTP verb, such as GET. The integration
        method is backed by an AWS service, such as Amazon DynamoDB.

        :param resource_id: The ID of the REST resource.
        :param rest_method: The HTTP verb used with the REST resource.
        :param service_endpoint_prefix: The service endpoint that is integrated with
                                        this method, such as 'dynamodb'.
        :param service_action: The action that is called on the service, such as
                               'GetItem'.
        :param service_method: The HTTP method of the service request, such as POST.
        :param role_arn: The Amazon Resource Name (ARN) of a role that grants API
                         Gateway permission to use the specified action with the
                         service.
        :param mapping_template: A mapping template that is used to translate REST
                                 elements, such as query parameters, to the request
                                 body format required by the service.
        """
        service_uri = (
            f"arn:aws:apigateway:{self.apig_client.meta.region_name}"
            f":{service_endpoint_prefix}:action/{service_action}"
        )
        try:
            self.apig_client.put_method(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                authorizationType="NONE",
            )
            self.apig_client.put_method_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseModels={"application/json": "Empty"},
            )
            logger.info("Created %s method for resource %s.", rest_method, resource_id)
        except ClientError:
            logger.exception(
                "Couldn't create %s method for resource %s.", rest_method, resource_id
            )
            raise

        try:
            self.apig_client.put_integration(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                type="AWS",
                integrationHttpMethod=service_method,
                credentials=role_arn,
                requestTemplates={"application/json": json.dumps(mapping_template)},
                uri=service_uri,
                passthroughBehavior="WHEN_NO_TEMPLATES",
            )
            self.apig_client.put_integration_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseTemplates={"application/json": ""},
            )
            logger.info(
                "Created integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
        except ClientError:
            logger.exception(
                "Couldn't create integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutIntegration](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutIntegration)」を参照してください。

### `PutIntegrationResponse`
<a name="api-gateway_PutIntegrationResponse_python_3_topic"></a>

次のコード例は、`PutIntegrationResponse` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def add_integration_method(
        self,
        resource_id,
        rest_method,
        service_endpoint_prefix,
        service_action,
        service_method,
        role_arn,
        mapping_template,
    ):
        """
        Adds an integration method to a REST API. An integration method is a REST
        resource, such as '/users', and an HTTP verb, such as GET. The integration
        method is backed by an AWS service, such as Amazon DynamoDB.

        :param resource_id: The ID of the REST resource.
        :param rest_method: The HTTP verb used with the REST resource.
        :param service_endpoint_prefix: The service endpoint that is integrated with
                                        this method, such as 'dynamodb'.
        :param service_action: The action that is called on the service, such as
                               'GetItem'.
        :param service_method: The HTTP method of the service request, such as POST.
        :param role_arn: The Amazon Resource Name (ARN) of a role that grants API
                         Gateway permission to use the specified action with the
                         service.
        :param mapping_template: A mapping template that is used to translate REST
                                 elements, such as query parameters, to the request
                                 body format required by the service.
        """
        service_uri = (
            f"arn:aws:apigateway:{self.apig_client.meta.region_name}"
            f":{service_endpoint_prefix}:action/{service_action}"
        )
        try:
            self.apig_client.put_method(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                authorizationType="NONE",
            )
            self.apig_client.put_method_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseModels={"application/json": "Empty"},
            )
            logger.info("Created %s method for resource %s.", rest_method, resource_id)
        except ClientError:
            logger.exception(
                "Couldn't create %s method for resource %s.", rest_method, resource_id
            )
            raise

        try:
            self.apig_client.put_integration(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                type="AWS",
                integrationHttpMethod=service_method,
                credentials=role_arn,
                requestTemplates={"application/json": json.dumps(mapping_template)},
                uri=service_uri,
                passthroughBehavior="WHEN_NO_TEMPLATES",
            )
            self.apig_client.put_integration_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseTemplates={"application/json": ""},
            )
            logger.info(
                "Created integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
        except ClientError:
            logger.exception(
                "Couldn't create integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutIntegrationResponse](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutIntegrationResponse)」を参照してください。

### `PutMethod`
<a name="api-gateway_PutMethod_python_3_topic"></a>

次のコード例は、`PutMethod` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def add_integration_method(
        self,
        resource_id,
        rest_method,
        service_endpoint_prefix,
        service_action,
        service_method,
        role_arn,
        mapping_template,
    ):
        """
        Adds an integration method to a REST API. An integration method is a REST
        resource, such as '/users', and an HTTP verb, such as GET. The integration
        method is backed by an AWS service, such as Amazon DynamoDB.

        :param resource_id: The ID of the REST resource.
        :param rest_method: The HTTP verb used with the REST resource.
        :param service_endpoint_prefix: The service endpoint that is integrated with
                                        this method, such as 'dynamodb'.
        :param service_action: The action that is called on the service, such as
                               'GetItem'.
        :param service_method: The HTTP method of the service request, such as POST.
        :param role_arn: The Amazon Resource Name (ARN) of a role that grants API
                         Gateway permission to use the specified action with the
                         service.
        :param mapping_template: A mapping template that is used to translate REST
                                 elements, such as query parameters, to the request
                                 body format required by the service.
        """
        service_uri = (
            f"arn:aws:apigateway:{self.apig_client.meta.region_name}"
            f":{service_endpoint_prefix}:action/{service_action}"
        )
        try:
            self.apig_client.put_method(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                authorizationType="NONE",
            )
            self.apig_client.put_method_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseModels={"application/json": "Empty"},
            )
            logger.info("Created %s method for resource %s.", rest_method, resource_id)
        except ClientError:
            logger.exception(
                "Couldn't create %s method for resource %s.", rest_method, resource_id
            )
            raise

        try:
            self.apig_client.put_integration(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                type="AWS",
                integrationHttpMethod=service_method,
                credentials=role_arn,
                requestTemplates={"application/json": json.dumps(mapping_template)},
                uri=service_uri,
                passthroughBehavior="WHEN_NO_TEMPLATES",
            )
            self.apig_client.put_integration_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseTemplates={"application/json": ""},
            )
            logger.info(
                "Created integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
        except ClientError:
            logger.exception(
                "Couldn't create integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutMethod](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutMethod)」を参照してください。

### `PutMethodResponse`
<a name="api-gateway_PutMethodResponse_python_3_topic"></a>

次のコード例は、`PutMethodResponse` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。

```
class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def add_integration_method(
        self,
        resource_id,
        rest_method,
        service_endpoint_prefix,
        service_action,
        service_method,
        role_arn,
        mapping_template,
    ):
        """
        Adds an integration method to a REST API. An integration method is a REST
        resource, such as '/users', and an HTTP verb, such as GET. The integration
        method is backed by an AWS service, such as Amazon DynamoDB.

        :param resource_id: The ID of the REST resource.
        :param rest_method: The HTTP verb used with the REST resource.
        :param service_endpoint_prefix: The service endpoint that is integrated with
                                        this method, such as 'dynamodb'.
        :param service_action: The action that is called on the service, such as
                               'GetItem'.
        :param service_method: The HTTP method of the service request, such as POST.
        :param role_arn: The Amazon Resource Name (ARN) of a role that grants API
                         Gateway permission to use the specified action with the
                         service.
        :param mapping_template: A mapping template that is used to translate REST
                                 elements, such as query parameters, to the request
                                 body format required by the service.
        """
        service_uri = (
            f"arn:aws:apigateway:{self.apig_client.meta.region_name}"
            f":{service_endpoint_prefix}:action/{service_action}"
        )
        try:
            self.apig_client.put_method(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                authorizationType="NONE",
            )
            self.apig_client.put_method_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseModels={"application/json": "Empty"},
            )
            logger.info("Created %s method for resource %s.", rest_method, resource_id)
        except ClientError:
            logger.exception(
                "Couldn't create %s method for resource %s.", rest_method, resource_id
            )
            raise

        try:
            self.apig_client.put_integration(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                type="AWS",
                integrationHttpMethod=service_method,
                credentials=role_arn,
                requestTemplates={"application/json": json.dumps(mapping_template)},
                uri=service_uri,
                passthroughBehavior="WHEN_NO_TEMPLATES",
            )
            self.apig_client.put_integration_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseTemplates={"application/json": ""},
            )
            logger.info(
                "Created integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
        except ClientError:
            logger.exception(
                "Couldn't create integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutMethodResponse](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutMethodResponse)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### COVID-19 データを追跡する REST API を作成する
<a name="cross_ApiGatewayDataTracker_python_3_topic"></a>

次のコード例は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートする REST API を作成する方法を示しています。

**SDK for Python (Boto3)**  
 で AWS Chalice を使用して AWS SDK for Python (Boto3) 、Amazon API Gateway AWS Lambda、および Amazon DynamoDB を使用するサーバーレス REST API を作成する方法を示します。REST API は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートします。以下ではその方法を説明しています。  
+  AWS Chalice を使用して、API Gateway 経由で送信される REST リクエストを処理するために呼び出される Lambda 関数のルートを定義します。
+ Lambda 関数を使用して、DynamoDB テーブルにデータを取得して保存し、REST リクエストを処理します。
+  AWS CloudFormation テンプレートでテーブル構造とセキュリティロールリソースを定義します。
+  AWS Chalice と CloudFormation を使用して、必要なすべてのリソースをパッケージ化してデプロイします。
+ CloudFormation を使用して、作成されたすべてのリソースをクリーンアップします。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_covid-19_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ CloudFormation
+ DynamoDB
+ Lambda

### 貸出ライブラリ REST API を作成する
<a name="cross_AuroraRestLendingLibrary_python_3_topic"></a>

以下のコード例は、Amazon Aurora データベースでバックアップされた REST API を使用して、常連客が書籍の貸出と返却できる貸出ライブラリを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Relational Database Service (Amazon RDS) API と AWS Chalice AWS SDK for Python (Boto3) で を使用して、Amazon Aurora データベースにバックアップされた REST API を作成する方法を示します。Web サービスは完全にサーバーレスであり、常連客が本を借りたり返却したりできるシンプルな貸し出しライブラリを表しています。以下ではその方法を説明しています。  
+ サーバーレス Aurora データベースクラスターを作成および管理します。
+  AWS Secrets Manager を使用してデータベース認証情報を管理します。
+ Amazon RDS を使用してデータをデータベースに出し入れするデータストレージレイヤーを実装します。
+  AWS Chalice を使用して、サーバーレス REST API を Amazon API Gateway および にデプロイします AWS Lambda。
+ リクエストパッケージを使用して、Web サービスにリクエストを送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_rest_lending_library) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ Aurora
+ Lambda
+ Secrets Manager

### WebSocket チャットアプリケーションを作成する
<a name="cross_ApiGatewayWebsocketChat_python_3_topic"></a>

次のコード例は、Amazon API Gateway 上に構築された WebSocket API によって提供されるチャットアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon API Gateway V2 AWS SDK for Python (Boto3) で を使用して、 AWS Lambda および Amazon DynamoDB と統合する WebSocket API を作成する方法を示します。  
+ API Gateway で提供される WebSocket API を作成します。
+ DynamoDB に接続を保存し、他のチャット参加者にメッセージを投稿する Lambda ハンドラを定義します。
+ WebSocket チャットアプリケーションに接続し、WebSockets パッケージを使用してメッセージを送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_websocket_chat) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

### REST API を作成してデプロイする
<a name="api-gateway_Usage_CreateDeployRest_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ API Gateway で提供される REST API を作成します。
+ ユーザープロファイルを表すリソースを REST API に追加します。
+ REST API が DynamoDB テーブルを使用してユーザープロファイルデータを保存するように、統合メソッドを追加します。
+ HTTP リクエストを REST API に送信して、ユーザープロファイルを追加および取得します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/api-gateway#code-examples)での設定と実行の方法を確認してください。
API Gateway オペレーションをラップするクラスを作成します。  

```
import argparse
import json
import logging
from pprint import pprint
import boto3
from botocore.exceptions import ClientError
import requests

logger = logging.getLogger(__name__)


class ApiGatewayToService:
    """
    Encapsulates Amazon API Gateway functions that are used to create a REST API that
    integrates with another AWS service.
    """

    def __init__(self, apig_client):
        """
        :param apig_client: A Boto3 API Gateway client.
        """
        self.apig_client = apig_client
        self.api_id = None
        self.root_id = None
        self.stage = None


    def create_rest_api(self, api_name):
        """
        Creates a REST API on API Gateway. The default API has only a root resource
        and no HTTP methods.

        :param api_name: The name of the API. This descriptive name is not used in
                         the API path.
        :return: The ID of the newly created API.
        """
        try:
            result = self.apig_client.create_rest_api(name=api_name)
            self.api_id = result["id"]
            logger.info("Created REST API %s with ID %s.", api_name, self.api_id)
        except ClientError:
            logger.exception("Couldn't create REST API %s.", api_name)
            raise

        try:
            result = self.apig_client.get_resources(restApiId=self.api_id)
            self.root_id = next(
                item for item in result["items"] if item["path"] == "/"
            )["id"]
        except ClientError:
            logger.exception("Couldn't get resources for API %s.", self.api_id)
            raise
        except StopIteration as err:
            logger.exception("No root resource found in API %s.", self.api_id)
            raise ValueError from err

        return self.api_id


    def add_rest_resource(self, parent_id, resource_path):
        """
        Adds a resource to a REST API.

        :param parent_id: The ID of the parent resource.
        :param resource_path: The path of the new resource, relative to the parent.
        :return: The ID of the new resource.
        """
        try:
            result = self.apig_client.create_resource(
                restApiId=self.api_id, parentId=parent_id, pathPart=resource_path
            )
            resource_id = result["id"]
            logger.info("Created resource %s.", resource_path)
        except ClientError:
            logger.exception("Couldn't create resource %s.", resource_path)
            raise
        else:
            return resource_id


    def add_integration_method(
        self,
        resource_id,
        rest_method,
        service_endpoint_prefix,
        service_action,
        service_method,
        role_arn,
        mapping_template,
    ):
        """
        Adds an integration method to a REST API. An integration method is a REST
        resource, such as '/users', and an HTTP verb, such as GET. The integration
        method is backed by an AWS service, such as Amazon DynamoDB.

        :param resource_id: The ID of the REST resource.
        :param rest_method: The HTTP verb used with the REST resource.
        :param service_endpoint_prefix: The service endpoint that is integrated with
                                        this method, such as 'dynamodb'.
        :param service_action: The action that is called on the service, such as
                               'GetItem'.
        :param service_method: The HTTP method of the service request, such as POST.
        :param role_arn: The Amazon Resource Name (ARN) of a role that grants API
                         Gateway permission to use the specified action with the
                         service.
        :param mapping_template: A mapping template that is used to translate REST
                                 elements, such as query parameters, to the request
                                 body format required by the service.
        """
        service_uri = (
            f"arn:aws:apigateway:{self.apig_client.meta.region_name}"
            f":{service_endpoint_prefix}:action/{service_action}"
        )
        try:
            self.apig_client.put_method(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                authorizationType="NONE",
            )
            self.apig_client.put_method_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseModels={"application/json": "Empty"},
            )
            logger.info("Created %s method for resource %s.", rest_method, resource_id)
        except ClientError:
            logger.exception(
                "Couldn't create %s method for resource %s.", rest_method, resource_id
            )
            raise

        try:
            self.apig_client.put_integration(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                type="AWS",
                integrationHttpMethod=service_method,
                credentials=role_arn,
                requestTemplates={"application/json": json.dumps(mapping_template)},
                uri=service_uri,
                passthroughBehavior="WHEN_NO_TEMPLATES",
            )
            self.apig_client.put_integration_response(
                restApiId=self.api_id,
                resourceId=resource_id,
                httpMethod=rest_method,
                statusCode="200",
                responseTemplates={"application/json": ""},
            )
            logger.info(
                "Created integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
        except ClientError:
            logger.exception(
                "Couldn't create integration for resource %s to service URI %s.",
                resource_id,
                service_uri,
            )
            raise


    def deploy_api(self, stage_name):
        """
        Deploys a REST API. After a REST API is deployed, it can be called from any
        REST client, such as the Python Requests package or Postman.

        :param stage_name: The stage of the API to deploy, such as 'test'.
        :return: The base URL of the deployed REST API.
        """
        try:
            self.apig_client.create_deployment(
                restApiId=self.api_id, stageName=stage_name
            )
            self.stage = stage_name
            logger.info("Deployed stage %s.", stage_name)
        except ClientError:
            logger.exception("Couldn't deploy stage %s.", stage_name)
            raise
        else:
            return self.api_url()



    def api_url(self, resource=None):
        """
        Builds the REST API URL from its parts.

        :param resource: The resource path to append to the base URL.
        :return: The REST URL to the specified resource.
        """
        url = (
            f"https://{self.api_id}.execute-api.{self.apig_client.meta.region_name}"
            f".amazonaws.com/{self.stage}"
        )
        if resource is not None:
            url = f"{url}/{resource}"
        return url
```
REST API をデプロイし、リクエストパッケージで呼び出します。  

```
def usage_demo(table_name, role_name, rest_api_name):
    """
    Demonstrates how to used API Gateway to create and deploy a REST API, and how
    to use the Requests package to call it.

    :param table_name: The name of the demo DynamoDB table.
    :param role_name: The name of the demo role that grants API Gateway permission to
                      call DynamoDB.
    :param rest_api_name: The name of the demo REST API created by the demo.
    """
    gateway = ApiGatewayToService(boto3.client("apigateway"))
    role = boto3.resource("iam").Role(role_name)

    print("Creating REST API in API Gateway.")
    gateway.create_rest_api(rest_api_name)

    print("Adding resources to the REST API.")
    profiles_id = gateway.add_rest_resource(gateway.root_id, "profiles")
    username_id = gateway.add_rest_resource(profiles_id, "{username}")

    # The DynamoDB service requires that all integration requests use POST.
    print("Adding integration methods to read and write profiles in Amazon DynamoDB.")
    gateway.add_integration_method(
        profiles_id,
        "GET",
        "dynamodb",
        "Scan",
        "POST",
        role.arn,
        {"TableName": table_name},
    )
    gateway.add_integration_method(
        profiles_id,
        "POST",
        "dynamodb",
        "PutItem",
        "POST",
        role.arn,
        {
            "TableName": table_name,
            "Item": {
                "username": {"S": "$input.path('$.username')"},
                "name": {"S": "$input.path('$.name')"},
                "title": {"S": "$input.path('$.title')"},
            },
        },
    )
    gateway.add_integration_method(
        username_id,
        "GET",
        "dynamodb",
        "GetItem",
        "POST",
        role.arn,
        {
            "TableName": table_name,
            "Key": {"username": {"S": "$method.request.path.username"}},
        },
    )

    stage = "test"
    print(f"Deploying the {stage} stage.")
    gateway.deploy_api(stage)

    profiles_url = gateway.api_url("profiles")
    print(
        f"Using the Requests package to post some people to the profiles REST API at "
        f"{profiles_url}."
    )
    requests.post(
        profiles_url,
        json={"username": "will", "name": "William Shakespeare", "title": "playwright"},
    )
    requests.post(
        profiles_url,
        json={
            "username": "ludwig",
            "name": "Ludwig van Beethoven",
            "title": "composer",
        },
    )
    requests.post(
        profiles_url,
        json={"username": "jane", "name": "Jane Austen", "title": "author"},
    )
    print("Getting the list of profiles from the REST API.")
    profiles = requests.get(profiles_url).json()
    pprint(profiles)
    print(f"Getting just the profile for username 'jane' (URL: {profiles_url}/jane).")
    jane = requests.get(f"{profiles_url}/jane").json()
    pprint(jane)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateDeployment](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/CreateDeployment)
  + [CreateResource](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/CreateResource)
  + [CreateRestApi](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/CreateRestApi)
  + [DeleteRestApi](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/DeleteRestApi)
  + [GetResources](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/GetResources)
  + [GetRestApis](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/GetRestApis)
  + [PutIntegration](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutIntegration)
  + [PutIntegrationResponse](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutIntegrationResponse)
  + [PutMethod](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutMethod)
  + [PutMethodResponse](https://docs.aws.amazon.com/goto/boto3/apigateway-2015-07-09/PutMethodResponse)

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_python_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例は、 AWS Lambda 関数を対象とする Amazon API Gateway REST API を作成して使用する方法を示しています。Lambda ハンドラーは、HTTP メソッドに基づいてルーティングする方法を示します。クエリ文字列、ヘッダー、および本文からデータを取得する方法。そして、JSON 応答を返す方法。  
+ Lambda 関数をデプロイします。
+ API ゲートウェイ REST API を作成します。
+ Lambda 関数をターゲットとする REST リソースを作成します。
+ API Gateway に Lambda 関数を呼び出す権限を付与します。
+ リクエストパッケージを使用して、REST API にリクエストを送信します。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

# SDK for Python (Boto3) を使用した Application Recovery Controller の例
<a name="python_3_route53-recovery-cluster_code_examples"></a>

次のコード例は、Application Recovery Controller AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetRoutingControlState`
<a name="route53-recovery-cluster_GetRoutingControlState_python_3_topic"></a>

次のコード例は、`GetRoutingControlState` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/route53-recovery-cluster#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def create_recovery_client(cluster_endpoint):
    """
    Creates a Boto3 Route 53 Application Recovery Controller client for the specified
    cluster endpoint URL and AWS Region.

    :param cluster_endpoint: The cluster endpoint URL and Region.
    :return: The Boto3 client.
    """
    return boto3.client(
        "route53-recovery-cluster",
        endpoint_url=cluster_endpoint["Endpoint"],
        region_name=cluster_endpoint["Region"],
    )



def get_routing_control_state(routing_control_arn, cluster_endpoints):
    """
    Gets the state of a routing control. Cluster endpoints are tried in
    sequence until the first successful response is received.

    :param routing_control_arn: The ARN of the routing control to look up.
    :param cluster_endpoints: The list of cluster endpoints to query.
    :return: The routing control state response.
    """

    # As a best practice, we recommend choosing a random cluster endpoint to get or set routing control states.
    # For more information, see https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-practices.html#route53-arc-best-practices.regional
    random.shuffle(cluster_endpoints)
    for cluster_endpoint in cluster_endpoints:
        try:
            recovery_client = create_recovery_client(cluster_endpoint)
            response = recovery_client.get_routing_control_state(
                RoutingControlArn=routing_control_arn
            )
            return response
        except Exception as error:
            print(error)
            raise error
```
+  API の詳細については、「AWS SDK for Python (Boto3) API Reference」の「[GetRoutingControlState](https://docs.aws.amazon.com/goto/boto3/route53-recovery-cluster-2019-12-02/GetRoutingControlState)」を参照してください。**

### `UpdateRoutingControlState`
<a name="route53-recovery-cluster_UpdateRoutingControlState_python_3_topic"></a>

次のコード例は、`UpdateRoutingControlState` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/route53-recovery-cluster#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def create_recovery_client(cluster_endpoint):
    """
    Creates a Boto3 Route 53 Application Recovery Controller client for the specified
    cluster endpoint URL and AWS Region.

    :param cluster_endpoint: The cluster endpoint URL and Region.
    :return: The Boto3 client.
    """
    return boto3.client(
        "route53-recovery-cluster",
        endpoint_url=cluster_endpoint["Endpoint"],
        region_name=cluster_endpoint["Region"],
    )



def update_routing_control_state(
    routing_control_arn, cluster_endpoints, routing_control_state
):
    """
    Updates the state of a routing control. Cluster endpoints are tried in
    sequence until the first successful response is received.

    :param routing_control_arn: The ARN of the routing control to update the state for.
    :param cluster_endpoints: The list of cluster endpoints to try.
    :param routing_control_state: The new routing control state.
    :return: The routing control update response.
    """

    # As a best practice, we recommend choosing a random cluster endpoint to get or set routing control states.
    # For more information, see https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-practices.html#route53-arc-best-practices.regional
    random.shuffle(cluster_endpoints)
    for cluster_endpoint in cluster_endpoints:
        try:
            recovery_client = create_recovery_client(cluster_endpoint)
            response = recovery_client.update_routing_control_state(
                RoutingControlArn=routing_control_arn,
                RoutingControlState=routing_control_state,
            )
            return response
        except Exception as error:
            print(error)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateRoutingControlState](https://docs.aws.amazon.com/goto/boto3/route53-recovery-cluster-2019-12-02/UpdateRoutingControlState)」を参照してください。

# SDK for Python (Boto3) を使用した Audit Manager の例
<a name="python_3_auditmanager_code_examples"></a>

次のコード例は、Audit Manager AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### AWS Config コンフォーマンスパックからカスタムフレームワークを作成する
<a name="auditmanager_Scenario_CustomFrameworkFromConformancePack_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS Config コンフォーマンスパックのリストを取得します。
+ コンフォーマンスパック内のマネージドルールごとに Audit Manager カスタムコントロールを作成します。
+ コントロールを含む Audit Manager カスタムフレームワークを作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auditmanager#code-examples)での設定と実行の方法を確認してください。

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class ConformancePack:
    def __init__(self, config_client, auditmanager_client):
        self.config_client = config_client
        self.auditmanager_client = auditmanager_client

    def get_conformance_pack(self):
        """
        Return a selected conformance pack from the list of conformance packs.

        :return: selected conformance pack
        """
        try:
            conformance_packs = self.config_client.describe_conformance_packs()
            print(
                "Number of conformance packs fetched: ",
                len(conformance_packs.get("ConformancePackDetails")),
            )
            print("Fetched the following conformance packs: ")
            all_cpack_names = {
                cp["ConformancePackName"]
                for cp in conformance_packs.get("ConformancePackDetails")
            }
            for pack in all_cpack_names:
                print(f"\t{pack}")
            cpack_name = input(
                "Provide ConformancePackName that you want to create a custom "
                "framework for: "
            )
            if cpack_name not in all_cpack_names:
                print(f"{cpack_name} is not in the list of conformance packs!")
                print(
                    "Provide a conformance pack name from the available list of "
                    "conformance packs."
                )
                raise Exception("Invalid conformance pack")
            print("-" * 88)
        except ClientError:
            logger.exception("Couldn't select conformance pack.")
            raise
        else:
            return cpack_name

    def create_custom_controls(self, cpack_name):
        """
        Create custom controls for all managed AWS Config rules in a conformance pack.

        :param cpack_name: The name of the conformance pack to create controls for.
        :return: The list of custom control IDs.
        """
        try:
            rules_in_pack = self.config_client.describe_conformance_pack_compliance(
                ConformancePackName=cpack_name
            )
            print(
                "Number of rules in the conformance pack: ",
                len(rules_in_pack.get("ConformancePackRuleComplianceList")),
            )
            for rule in rules_in_pack.get("ConformancePackRuleComplianceList"):
                print(f"\t{rule.get('ConfigRuleName')}")
            print("-" * 88)
            print(
                "Creating a custom control for each rule and a custom framework "
                "consisting of these rules in Audit Manager."
            )
            am_controls = []
            for rule in rules_in_pack.get("ConformancePackRuleComplianceList"):
                config_rule = self.config_client.describe_config_rules(
                    ConfigRuleNames=[rule.get("ConfigRuleName")]
                )
                source_id = (
                    config_rule.get("ConfigRules")[0]
                    .get("Source", {})
                    .get("SourceIdentifier")
                )
                custom_control = self.auditmanager_client.create_control(
                    name="Config-" + rule.get("ConfigRuleName"),
                    controlMappingSources=[
                        {
                            "sourceName": "ConfigRule",
                            "sourceSetUpOption": "System_Controls_Mapping",
                            "sourceType": "AWS_Config",
                            "sourceKeyword": {
                                "keywordInputType": "SELECT_FROM_LIST",
                                "keywordValue": source_id,
                            },
                        }
                    ],
                ).get("control", {})
                am_controls.append({"id": custom_control.get("id")})
            print("Successfully created a control for each config rule.")
            print("-" * 88)
        except ClientError:
            logger.exception("Failed to create custom controls.")
            raise
        else:
            return am_controls

    def create_custom_framework(self, cpack_name, am_control_ids):
        """
        Create a custom Audit Manager framework from a selected AWS Config conformance
        pack.

        :param cpack_name: The name of the conformance pack to create a framework from.
        :param am_control_ids: The IDs of the custom controls created from the
                               conformance pack.
        """
        try:
            print("Creating custom framework...")
            custom_framework = self.auditmanager_client.create_assessment_framework(
                name="Config-Conformance-pack-" + cpack_name,
                controlSets=[{"name": cpack_name, "controls": am_control_ids}],
            )
            print(
                f"Successfully created the custom framework: ",
                f"{custom_framework.get('framework').get('name')}: ",
                f"{custom_framework.get('framework').get('id')}",
            )
            print("-" * 88)
        except ClientError:
            logger.exception("Failed to create custom framework.")
            raise


def run_demo():
    print("-" * 88)
    print("Welcome to the AWS Audit Manager custom framework demo!")
    print("-" * 88)
    print(
        "You can use this sample to select a conformance pack from AWS Config and "
        "use AWS Audit Manager to create a custom control for all the managed "
        "rules under the conformance pack. A custom framework is also created "
        "with these controls."
    )
    print("-" * 88)
    conf_pack = ConformancePack(boto3.client("config"), boto3.client("auditmanager"))
    cpack_name = conf_pack.get_conformance_pack()
    am_controls = conf_pack.create_custom_controls(cpack_name)
    conf_pack.create_custom_framework(cpack_name, am_controls)


if __name__ == "__main__":
    run_demo()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateAssessmentFramework](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/CreateAssessmentFramework)
  + [CreateControl](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/CreateControl)

### Security Hub CSPM コントロールを含むカスタムフレームワークを作成する
<a name="auditmanager_Scenario_CustomFrameworkFromSecurityHub_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Security Hub CSPM をデータソースとするすべての標準コントロールのリストを取得します。
+ コントロールを含む Audit Manager カスタムフレームワークを作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auditmanager#code-examples)での設定と実行の方法を確認してください。

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class SecurityHub:
    def __init__(self, auditmanager_client):
        self.auditmanager_client = auditmanager_client

    def get_sechub_controls(self):
        """
        Gets the list of controls that use Security Hub as their data source.

        :return: The list of Security Hub controls.
        """
        print("-" * 88)
        next_token = None
        page = 1
        sechub_control_list = []
        while True:
            print("Page [" + str(page) + "]")
            if next_token is None:
                control_list = self.auditmanager_client.list_controls(
                    controlType="Standard", maxResults=100
                )
            else:
                control_list = self.auditmanager_client.list_controls(
                    controlType="Standard", nextToken=next_token, maxResults=100
                )
            print("Total controls found:", len(control_list.get("controlMetadataList")))
            for control in control_list.get("controlMetadataList"):
                control_details = self.auditmanager_client.get_control(
                    controlId=control.get("id")
                ).get("control", {})
                if "AWS Security Hub" in control_details.get("controlSources"):
                    sechub_control_list.append({"id": control_details.get("id")})
            next_token = control_list.get("nextToken")
            if not next_token:
                break
            page += 1
        print("Number of Security Hub controls found: ", len(sechub_control_list))
        return sechub_control_list

    def create_custom_framework(self, am_controls):
        """
        Create a custom framework with a list of controls.

        :param am_controls: The list of controls to include in the framework.
        """
        try:
            print("Creating custom framework...")
            custom_framework = self.auditmanager_client.create_assessment_framework(
                name="All Security Hub Controls Framework",
                controlSets=[{"name": "Security-Hub", "controls": am_controls}],
            )
            print(
                f"Successfully created the custom framework: "
                f"{custom_framework.get('framework').get('name')}: "
                f"{custom_framework.get('framework').get('id')}"
            )
            print("-" * 88)
        except ClientError:
            logger.exception("Failed to create custom framework.")
            raise


def run_demo():
    print("-" * 88)
    print("Welcome to the AWS Audit Manager Security Hub demo!")
    print("-" * 88)
    print(" This script creates a custom framework with all Security Hub controls.")
    print("-" * 88)
    sechub = SecurityHub(boto3.client("auditmanager"))
    am_controls = sechub.get_sechub_controls()
    sechub.create_custom_framework(am_controls)


if __name__ == "__main__":
    run_demo()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateAssessmentFramework](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/CreateAssessmentFramework)
  + [GetControl](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/GetControl)
  + [ListControls](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/ListControls)

### 評価レポートを生成する
<a name="auditmanager_Scenario_CreateAssessmentReport_python_3_topic"></a>

次のコード例は、1 日分の証拠を含む Audit Manager 評価レポートを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auditmanager#code-examples)での設定と実行の方法を確認してください。

```
import dateutil.parser
import logging
import time
import urllib.request
import uuid
import boto3
from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)


class AuditReport:
    def __init__(self, auditmanager_client):
        self.auditmanager_client = auditmanager_client

    def get_input(self):
        print("-" * 40)
        try:
            assessment_id = input("Provide assessment id [uuid]: ").lower()
            try:
                assessment_uuid = uuid.UUID(assessment_id)
            except ValueError:
                logger.error("Assessment Id is not a valid UUID: %s", assessment_id)
                raise
            evidence_folder = input("Provide evidence date [yyyy-mm-dd]: ")
            try:
                evidence_date = dateutil.parser.parse(evidence_folder).date()
            except ValueError:
                logger.error("Invalid date : %s", evidence_folder)
                raise
            try:
                self.auditmanager_client.get_assessment(
                    assessmentId=str(assessment_uuid)
                )
            except ClientError:
                logger.exception("Couldn't get assessment %s.", assessment_uuid)
                raise
        except (ValueError, ClientError):
            return None, None
        else:
            return assessment_uuid, evidence_date

    def clear_staging(self, assessment_uuid, evidence_date):
        """
        Find all the evidence in the report and clear it.
        """
        next_token = None
        page = 1
        interested_folder_id_list = []
        while True:
            print(f"Page [{page}]")
            if next_token is None:
                folder_list = (
                    self.auditmanager_client.get_evidence_folders_by_assessment(
                        assessmentId=str(assessment_uuid), maxResults=1000
                    )
                )
            else:
                folder_list = (
                    self.auditmanager_client.get_evidence_folders_by_assessment(
                        assessmentId=str(assessment_uuid),
                        nextToken=next_token,
                        maxResults=1000,
                    )
                )
            folders = folder_list.get("evidenceFolders")
            print(f"Got {len(folders)} folders.")
            for folder in folders:
                folder_id = folder.get("id")
                if folder.get("name") == str(evidence_date):
                    interested_folder_id_list.append(folder_id)
                if folder.get("assessmentReportSelectionCount") == folder.get(
                    "totalEvidence"
                ):
                    print(
                        f"Removing folder from report selection : {folder.get('name')} "
                        f"{folder_id} {folder.get('controlId')}"
                    )
                    self.auditmanager_client.disassociate_assessment_report_evidence_folder(
                        assessmentId=str(assessment_uuid), evidenceFolderId=folder_id
                    )
                elif folder.get("assessmentReportSelectionCount") > 0:
                    # Get all evidence in the folder and
                    # add selected evidence in the selected_evidence_list.
                    evidence_list = (
                        self.auditmanager_client.get_evidence_by_evidence_folder(
                            assessmentId=str(assessment_uuid),
                            controlSetId=folder_id,
                            evidenceFolderId=folder_id,
                            maxResults=1000,
                        )
                    )
                    selected_evidence_list = []
                    for evidence in evidence_list.get("evidence"):
                        if evidence.get("assessmentReportSelection") == "Yes":
                            selected_evidence_list.append(evidence.get("id"))
                    print(
                        f"Removing evidence report selection : {folder.get('name')} "
                        f"{len(selected_evidence_list)}"
                    )
                    self.auditmanager_client.batch_disassociate_assessment_report_evidence(
                        assessmentId=str(assessment_uuid),
                        evidenceFolderId=folder_id,
                        evidenceIds=selected_evidence_list,
                    )
            next_token = folder_list.get("nextToken")
            if not next_token:
                break
            page += 1
        return interested_folder_id_list

    def add_folder_to_staging(self, assessment_uuid, folder_id_list):
        print(f"Adding folders to report : {folder_id_list}")
        for folder in folder_id_list:
            self.auditmanager_client.associate_assessment_report_evidence_folder(
                assessmentId=str(assessment_uuid), evidenceFolderId=folder
            )

    def get_report(self, assessment_uuid):
        report = self.auditmanager_client.create_assessment_report(
            name="ReportViaScript",
            description="testing",
            assessmentId=str(assessment_uuid),
        )
        if self._is_report_generated(report.get("assessmentReport").get("id")):
            report_url = self.auditmanager_client.get_assessment_report_url(
                assessmentReportId=report.get("assessmentReport").get("id"),
                assessmentId=str(assessment_uuid),
            )
            print(report_url.get("preSignedUrl"))
            urllib.request.urlretrieve(
                report_url.get("preSignedUrl").get("link"),
                report_url.get("preSignedUrl").get("hyperlinkName"),
            )
            print(
                f"Report saved as {report_url.get('preSignedUrl').get('hyperlinkName')}."
            )
        else:
            print("Report generation did not finish in 15 minutes.")
            print(
                "Failed to download report. Go to the console and manually download "
                "the report."
            )

    def _is_report_generated(self, assessment_report_id):
        max_wait_time = 0
        while max_wait_time < 900:
            print(f"Checking status of the report {assessment_report_id}")
            report_list = self.auditmanager_client.list_assessment_reports(maxResults=1)
            if (
                report_list.get("assessmentReports")[0].get("id")
                == assessment_report_id
                and report_list.get("assessmentReports")[0].get("status") == "COMPLETE"
            ):
                return True
            print("Sleeping for 5 seconds...")
            time.sleep(5)
            max_wait_time += 5


def run_demo():
    print("-" * 88)
    print("Welcome to the AWS Audit Manager samples demo!")
    print("-" * 88)
    print(
        "This script creates an assessment report for an assessment with all the "
        "evidence collected on the provided date."
    )
    print("-" * 88)

    report = AuditReport(boto3.client("auditmanager"))
    assessment_uuid, evidence_date = report.get_input()
    if assessment_uuid is not None and evidence_date is not None:
        folder_id_list = report.clear_staging(assessment_uuid, evidence_date)
        report.add_folder_to_staging(assessment_uuid, folder_id_list)
        report.get_report(assessment_uuid)


if __name__ == "__main__":
    run_demo()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AssociateAssessmentReportEvidenceFolder](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/AssociateAssessmentReportEvidenceFolder)
  + [BatchDisassociateAssessmentReportEvidence](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/BatchDisassociateAssessmentReportEvidence)
  + [CreateAssessmentReport](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/CreateAssessmentReport)
  + [DisassociateAssessmentReportEvidenceFolder](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/DisassociateAssessmentReportEvidenceFolder)
  + [GetAssessment](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/GetAssessment)
  + [GetAssessmentReportUrl](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/GetAssessmentReportUrl)
  + [GetEvidenceByEvidenceFolder](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/GetEvidenceByEvidenceFolder)
  + [GetEvidenceFoldersByAssessment](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/GetEvidenceFoldersByAssessment)
  + [ListAssessmentReports](https://docs.aws.amazon.com/goto/boto3/auditmanager-2017-07-25/ListAssessmentReports)

# SDK for Python (Boto3) を使用した Aurora の例
<a name="python_3_aurora_code_examples"></a>

次のコード例は、Aurora AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Aurora
<a name="aurora_Hello_python_3_topic"></a>

次のコード例は、Aurora の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
import boto3

# Create an RDS client
rds = boto3.client("rds")

# Create a paginator for the describe_db_clusters operation
paginator = rds.get_paginator("describe_db_clusters")

# Use the paginator to get a list of DB clusters
response_iterator = paginator.paginate(
    PaginationConfig={
        "PageSize": 50,  # Adjust PageSize as needed
        "StartingToken": None,
    }
)

# Iterate through the pages of the response
clusters_found = False
for page in response_iterator:
    if "DBClusters" in page and page["DBClusters"]:
        clusters_found = True
        print("Here are your RDS Aurora clusters:")
        for cluster in page["DBClusters"]:
            print(
                f"Cluster ID: {cluster['DBClusterIdentifier']}, Engine: {cluster['Engine']}"
            )

if not clusters_found:
    print("No clusters found!")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="aurora_Scenario_GetStartedClusters_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム Aurora DB クラスターパラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用する DB クラスターを作成する
+ データベースを含む DB インスタンスを作成します。
+ DB クラスターのスナップショットを作成して、リソースをクリーンアップします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class AuroraClusterScenario:
    """Runs a scenario that shows how to get started using Aurora DB clusters."""

    def __init__(self, aurora_wrapper):
        """
        :param aurora_wrapper: An object that wraps Aurora DB cluster actions.
        """
        self.aurora_wrapper = aurora_wrapper

    def create_parameter_group(self, db_engine, parameter_group_name):
        """
        Shows how to get available engine versions for a specified database engine and
        create a DB cluster parameter group that is compatible with a selected engine family.

        :param db_engine: The database engine to use as a basis.
        :param parameter_group_name: The name given to the newly created parameter group.
        :return: The newly created parameter group.
        """
        print(
            f"Checking for an existing DB cluster parameter group named {parameter_group_name}."
        )
        parameter_group = self.aurora_wrapper.get_parameter_group(parameter_group_name)
        if parameter_group is None:
            print(f"Getting available database engine versions for {db_engine}.")
            engine_versions = self.aurora_wrapper.get_engine_versions(db_engine)
            families = list({ver["DBParameterGroupFamily"] for ver in engine_versions})
            family_index = q.choose("Which family do you want to use? ", families)
            print(f"Creating a DB cluster parameter group.")
            self.aurora_wrapper.create_parameter_group(
                parameter_group_name, families[family_index], "Example parameter group."
            )
            parameter_group = self.aurora_wrapper.get_parameter_group(
                parameter_group_name
            )
        print(f"Parameter group {parameter_group['DBClusterParameterGroupName']}:")
        pp(parameter_group)
        print("-" * 88)
        return parameter_group

    def set_user_parameters(self, parameter_group_name):
        """
        Shows how to get the parameters contained in a custom parameter group and
        update some of the parameter values in the group.

        :param parameter_group_name: The name of the parameter group to query and modify.
        """
        print("Let's set some parameter values in your parameter group.")
        auto_inc_parameters = self.aurora_wrapper.get_parameters(
            parameter_group_name, name_prefix="auto_increment"
        )
        update_params = []
        for auto_inc in auto_inc_parameters:
            if auto_inc["IsModifiable"] and auto_inc["DataType"] == "integer":
                print(f"The {auto_inc['ParameterName']} parameter is described as:")
                print(f"\t{auto_inc['Description']}")
                param_range = auto_inc["AllowedValues"].split("-")
                auto_inc["ParameterValue"] = str(
                    q.ask(
                        f"Enter a value between {param_range[0]} and {param_range[1]}: ",
                        q.is_int,
                        q.in_range(int(param_range[0]), int(param_range[1])),
                    )
                )
                update_params.append(auto_inc)
        self.aurora_wrapper.update_parameters(parameter_group_name, update_params)
        print(
            "You can get a list of parameters you've set by specifying a source of 'user'."
        )
        user_parameters = self.aurora_wrapper.get_parameters(
            parameter_group_name, source="user"
        )
        pp(user_parameters)
        print("-" * 88)

    def create_cluster(self, cluster_name, db_engine, db_name, parameter_group):
        """
        Shows how to create an Aurora DB cluster that contains a database of a specified
        type. The database is also configured to use a custom DB cluster parameter group.

        :param cluster_name: The name given to the newly created DB cluster.
        :param db_engine: The engine of the created database.
        :param db_name: The name given to the created database.
        :param parameter_group: The parameter group that is associated with the DB cluster.
        :return: The newly created DB cluster.
        """
        print("Checking for an existing DB cluster.")
        cluster = self.aurora_wrapper.get_db_cluster(cluster_name)
        if cluster is None:
            admin_username = q.ask(
                "Enter an administrator user name for the database: ", q.non_empty
            )
            admin_password = q.ask(
                "Enter a password for the administrator (at least 8 characters): ",
                q.non_empty,
            )
            engine_versions = self.aurora_wrapper.get_engine_versions(
                db_engine, parameter_group["DBParameterGroupFamily"]
            )
            engine_choices = [
                ver["EngineVersionDescription"] for ver in engine_versions
            ]
            print("The available engines for your parameter group are:")
            engine_index = q.choose("Which engine do you want to use? ", engine_choices)
            print(
                f"Creating DB cluster {cluster_name} and database {db_name}.\n"
                f"The DB cluster is configured to use\n"
                f"your custom parameter group {parameter_group['DBClusterParameterGroupName']}\n"
                f"and selected engine {engine_choices[engine_index]}.\n"
                f"This typically takes several minutes."
            )
            cluster = self.aurora_wrapper.create_db_cluster(
                cluster_name,
                parameter_group["DBClusterParameterGroupName"],
                db_name,
                db_engine,
                engine_versions[engine_index]["EngineVersion"],
                admin_username,
                admin_password,
            )
            while cluster.get("Status") != "available":
                wait(30)
                cluster = self.aurora_wrapper.get_db_cluster(cluster_name)
            print("Cluster created and available.\n")
        print("Cluster data:")
        pp(cluster)
        print("-" * 88)
        return cluster

    def create_instance(self, cluster):
        """
        Shows how to create a DB instance in an existing Aurora DB cluster. A new DB cluster
        contains no DB instances, so you must add one. The first DB instance that is added
        to a DB cluster defaults to a read-write DB instance.

        :param cluster: The DB cluster where the DB instance is added.
        :return: The newly created DB instance.
        """
        print("Checking for an existing database instance.")
        cluster_name = cluster["DBClusterIdentifier"]
        db_inst = self.aurora_wrapper.get_db_instance(cluster_name)
        if db_inst is None:
            print("Let's create a database instance in your DB cluster.")
            print("First, choose a DB instance type:")
            inst_opts = self.aurora_wrapper.get_orderable_instances(
                cluster["Engine"], cluster["EngineVersion"]
            )
            inst_choices = list(
                {
                    opt["DBInstanceClass"] + ", storage type: " + opt["StorageType"]
                    for opt in inst_opts
                }
            )
            inst_index = q.choose(
                "Which DB instance class do you want to use? ", inst_choices
            )
            print(
                f"Creating a database instance. This typically takes several minutes."
            )
            db_inst = self.aurora_wrapper.create_instance_in_cluster(
                cluster_name,
                cluster_name,
                cluster["Engine"],
                inst_opts[inst_index]["DBInstanceClass"],
            )
            while db_inst.get("DBInstanceStatus") != "available":
                wait(30)
                db_inst = self.aurora_wrapper.get_db_instance(cluster_name)
        print("Instance data:")
        pp(db_inst)
        print("-" * 88)
        return db_inst

    @staticmethod
    def display_connection(cluster):
        """
        Displays connection information about an Aurora DB cluster and tips on how to
        connect to it.

        :param cluster: The DB cluster to display.
        """
        print(
            "You can now connect to your database using your favorite MySql client.\n"
            "One way to connect is by using the 'mysql' shell on an Amazon EC2 instance\n"
            "that is running in the same VPC as your database cluster. Pass the endpoint,\n"
            "port, and administrator user name to 'mysql' and enter your password\n"
            "when prompted:\n"
        )
        print(
            f"\n\tmysql -h {cluster['Endpoint']} -P {cluster['Port']} -u {cluster['MasterUsername']} -p\n"
        )
        print(
            "For more information, see the User Guide for Aurora:\n"
            "\thttps://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/CHAP_GettingStartedAurora.CreatingConnecting.Aurora.html#CHAP_GettingStartedAurora.Aurora.Connect"
        )
        print("-" * 88)

    def create_snapshot(self, cluster_name):
        """
        Shows how to create a DB cluster snapshot and wait until it's available.

        :param cluster_name: The name of a DB cluster to snapshot.
        """
        if q.ask(
            "Do you want to create a snapshot of your DB cluster (y/n)? ", q.is_yesno
        ):
            snapshot_id = f"{cluster_name}-{uuid.uuid4()}"
            print(
                f"Creating a snapshot named {snapshot_id}. This typically takes a few minutes."
            )
            snapshot = self.aurora_wrapper.create_cluster_snapshot(
                snapshot_id, cluster_name
            )
            while snapshot.get("Status") != "available":
                wait(30)
                snapshot = self.aurora_wrapper.get_cluster_snapshot(snapshot_id)
            pp(snapshot)
            print("-" * 88)

    def cleanup(self, db_inst, cluster, parameter_group):
        """
        Shows how to clean up a DB instance, DB cluster, and DB cluster parameter group.
        Before the DB cluster parameter group can be deleted, all associated DB instances and
        DB clusters must first be deleted.

        :param db_inst: The DB instance to delete.
        :param cluster: The DB cluster to delete.
        :param parameter_group: The DB cluster parameter group to delete.
        """
        cluster_name = cluster["DBClusterIdentifier"]
        parameter_group_name = parameter_group["DBClusterParameterGroupName"]
        if q.ask(
            "\nDo you want to delete the database instance, DB cluster, and parameter "
            "group (y/n)? ",
            q.is_yesno,
        ):
            print(f"Deleting database instance {db_inst['DBInstanceIdentifier']}.")
            self.aurora_wrapper.delete_db_instance(db_inst["DBInstanceIdentifier"])
            print(f"Deleting database cluster {cluster_name}.")
            self.aurora_wrapper.delete_db_cluster(cluster_name)
            print(
                "Waiting for the DB instance and DB cluster to delete.\n"
                "This typically takes several minutes."
            )
            while db_inst is not None or cluster is not None:
                wait(30)
                if db_inst is not None:
                    db_inst = self.aurora_wrapper.get_db_instance(
                        db_inst["DBInstanceIdentifier"]
                    )
                if cluster is not None:
                    cluster = self.aurora_wrapper.get_db_cluster(
                        cluster["DBClusterIdentifier"]
                    )
            print(f"Deleting parameter group {parameter_group_name}.")
            self.aurora_wrapper.delete_parameter_group(parameter_group_name)

    def run_scenario(self, db_engine, parameter_group_name, cluster_name, db_name):
        print("-" * 88)
        print(
            "Welcome to the Amazon Relational Database Service (Amazon RDS) get started\n"
            "with Aurora DB clusters demo."
        )
        print("-" * 88)

        parameter_group = self.create_parameter_group(db_engine, parameter_group_name)
        self.set_user_parameters(parameter_group_name)
        cluster = self.create_cluster(cluster_name, db_engine, db_name, parameter_group)
        wait(5)
        db_inst = self.create_instance(cluster)
        self.display_connection(cluster)
        self.create_snapshot(cluster_name)
        self.cleanup(db_inst, cluster, parameter_group)

        print("\nThanks for watching!")
        print("-" * 88)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    try:
        scenario = AuroraClusterScenario(AuroraWrapper.from_client())
        scenario.run_scenario(
            "aurora-mysql",
            "doc-example-cluster-parameter-group",
            "doc-example-aurora",
            "docexampledb",
        )
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
Aurora アクションを管理するためにシナリオによって呼び出される関数を定義します。  

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_parameter_group(self, parameter_group_name):
        """
        Gets a DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to retrieve.
        :return: The requested parameter group.
        """
        try:
            response = self.rds_client.describe_db_cluster_parameter_groups(
                DBClusterParameterGroupName=parameter_group_name
            )
            parameter_group = response["DBClusterParameterGroups"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBParameterGroupNotFound":
                logger.info("Parameter group %s does not exist.", parameter_group_name)
            else:
                logger.error(
                    "Couldn't get parameter group %s. Here's why: %s: %s",
                    parameter_group_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return parameter_group


    def create_parameter_group(
        self, parameter_group_name, parameter_group_family, description
    ):
        """
        Creates a DB cluster parameter group that is based on the specified parameter group
        family.

        :param parameter_group_name: The name of the newly created parameter group.
        :param parameter_group_family: The family that is used as the basis of the new
                                       parameter group.
        :param description: A description given to the parameter group.
        :return: Data about the newly created parameter group.
        """
        try:
            response = self.rds_client.create_db_cluster_parameter_group(
                DBClusterParameterGroupName=parameter_group_name,
                DBParameterGroupFamily=parameter_group_family,
                Description=description,
            )
        except ClientError as err:
            logger.error(
                "Couldn't create parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def delete_parameter_group(self, parameter_group_name):
        """
        Deletes a DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to delete.
        :return: Data about the parameter group.
        """
        try:
            response = self.rds_client.delete_db_cluster_parameter_group(
                DBClusterParameterGroupName=parameter_group_name
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def get_parameters(self, parameter_group_name, name_prefix="", source=None):
        """
        Gets the parameters that are contained in a DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to query.
        :param name_prefix: When specified, the retrieved list of parameters is filtered
                            to contain only parameters that start with this prefix.
        :param source: When specified, only parameters from this source are retrieved.
                       For example, a source of 'user' retrieves only parameters that
                       were set by a user.
        :return: The list of requested parameters.
        """
        try:
            kwargs = {"DBClusterParameterGroupName": parameter_group_name}
            if source is not None:
                kwargs["Source"] = source
            parameters = []
            paginator = self.rds_client.get_paginator("describe_db_cluster_parameters")
            for page in paginator.paginate(**kwargs):
                parameters += [
                    p
                    for p in page["Parameters"]
                    if p["ParameterName"].startswith(name_prefix)
                ]
        except ClientError as err:
            logger.error(
                "Couldn't get parameters for %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return parameters


    def update_parameters(self, parameter_group_name, update_parameters):
        """
        Updates parameters in a custom DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to update.
        :param update_parameters: The parameters to update in the group.
        :return: Data about the modified parameter group.
        """
        try:
            response = self.rds_client.modify_db_cluster_parameter_group(
                DBClusterParameterGroupName=parameter_group_name,
                Parameters=update_parameters,
            )
        except ClientError as err:
            logger.error(
                "Couldn't update parameters in %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def get_db_cluster(self, cluster_name):
        """
        Gets data about an Aurora DB cluster.

        :param cluster_name: The name of the DB cluster to retrieve.
        :return: The retrieved DB cluster.
        """
        try:
            response = self.rds_client.describe_db_clusters(
                DBClusterIdentifier=cluster_name
            )
            cluster = response["DBClusters"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBClusterNotFoundFault":
                logger.info("Cluster %s does not exist.", cluster_name)
            else:
                logger.error(
                    "Couldn't verify the existence of DB cluster %s. Here's why: %s: %s",
                    cluster_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return cluster


    def create_db_cluster(
        self,
        cluster_name,
        parameter_group_name,
        db_name,
        db_engine,
        db_engine_version,
        admin_name,
        admin_password,
    ):
        """
        Creates a DB cluster that is configured to use the specified parameter group.
        The newly created DB cluster contains a database that uses the specified engine and
        engine version.

        :param cluster_name: The name of the DB cluster to create.
        :param parameter_group_name: The name of the parameter group to associate with
                                     the DB cluster.
        :param db_name: The name of the database to create.
        :param db_engine: The database engine of the database that is created, such as MySql.
        :param db_engine_version: The version of the database engine.
        :param admin_name: The user name of the database administrator.
        :param admin_password: The password of the database administrator.
        :return: The newly created DB cluster.
        """
        try:
            response = self.rds_client.create_db_cluster(
                DatabaseName=db_name,
                DBClusterIdentifier=cluster_name,
                DBClusterParameterGroupName=parameter_group_name,
                Engine=db_engine,
                EngineVersion=db_engine_version,
                MasterUsername=admin_name,
                MasterUserPassword=admin_password,
            )
            cluster = response["DBCluster"]
        except ClientError as err:
            logger.error(
                "Couldn't create database %s. Here's why: %s: %s",
                db_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return cluster


    def delete_db_cluster(self, cluster_name):
        """
        Deletes a DB cluster.

        :param cluster_name: The name of the DB cluster to delete.
        """
        try:
            self.rds_client.delete_db_cluster(
                DBClusterIdentifier=cluster_name, SkipFinalSnapshot=True
            )
            logger.info("Deleted DB cluster %s.", cluster_name)
        except ClientError:
            logger.exception("Couldn't delete DB cluster %s.", cluster_name)
            raise


    def create_cluster_snapshot(self, snapshot_id, cluster_id):
        """
        Creates a snapshot of a DB cluster.

        :param snapshot_id: The ID to give the created snapshot.
        :param cluster_id: The DB cluster to snapshot.
        :return: Data about the newly created snapshot.
        """
        try:
            response = self.rds_client.create_db_cluster_snapshot(
                DBClusterSnapshotIdentifier=snapshot_id, DBClusterIdentifier=cluster_id
            )
            snapshot = response["DBClusterSnapshot"]
        except ClientError as err:
            logger.error(
                "Couldn't create snapshot of %s. Here's why: %s: %s",
                cluster_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot


    def get_cluster_snapshot(self, snapshot_id):
        """
        Gets a DB cluster snapshot.

        :param snapshot_id: The ID of the snapshot to retrieve.
        :return: The retrieved snapshot.
        """
        try:
            response = self.rds_client.describe_db_cluster_snapshots(
                DBClusterSnapshotIdentifier=snapshot_id
            )
            snapshot = response["DBClusterSnapshots"][0]
        except ClientError as err:
            logger.error(
                "Couldn't get DB cluster snapshot %s. Here's why: %s: %s",
                snapshot_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot


    def create_instance_in_cluster(
        self, instance_id, cluster_id, db_engine, instance_class
    ):
        """
        Creates a database instance in an existing DB cluster. The first database that is
        created defaults to a read-write DB instance.

        :param instance_id: The ID to give the newly created DB instance.
        :param cluster_id: The ID of the DB cluster where the DB instance is created.
        :param db_engine: The database engine of a database to create in the DB instance.
                          This must be compatible with the configured parameter group
                          of the DB cluster.
        :param instance_class: The DB instance class for the newly created DB instance.
        :return: Data about the newly created DB instance.
        """
        try:
            response = self.rds_client.create_db_instance(
                DBInstanceIdentifier=instance_id,
                DBClusterIdentifier=cluster_id,
                Engine=db_engine,
                DBInstanceClass=instance_class,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't create DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst


    def get_engine_versions(self, engine, parameter_group_family=None):
        """
        Gets database engine versions that are available for the specified engine
        and parameter group family.

        :param engine: The database engine to look up.
        :param parameter_group_family: When specified, restricts the returned list of
                                       engine versions to those that are compatible with
                                       this parameter group family.
        :return: The list of database engine versions.
        """
        try:
            kwargs = {"Engine": engine}
            if parameter_group_family is not None:
                kwargs["DBParameterGroupFamily"] = parameter_group_family
            response = self.rds_client.describe_db_engine_versions(**kwargs)
            versions = response["DBEngineVersions"]
        except ClientError as err:
            logger.error(
                "Couldn't get engine versions for %s. Here's why: %s: %s",
                engine,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return versions


    def get_orderable_instances(self, db_engine, db_engine_version):
        """
        Gets DB instance options that can be used to create DB instances that are
        compatible with a set of specifications.

        :param db_engine: The database engine that must be supported by the DB instance.
        :param db_engine_version: The engine version that must be supported by the DB instance.
        :return: The list of DB instance options that can be used to create a compatible DB instance.
        """
        try:
            inst_opts = []
            paginator = self.rds_client.get_paginator(
                "describe_orderable_db_instance_options"
            )
            for page in paginator.paginate(
                Engine=db_engine, EngineVersion=db_engine_version
            ):
                inst_opts += page["OrderableDBInstanceOptions"]
        except ClientError as err:
            logger.error(
                "Couldn't get orderable DB instances. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return inst_opts


    def get_db_instance(self, instance_id):
        """
        Gets data about a DB instance.

        :param instance_id: The ID of the DB instance to retrieve.
        :return: The retrieved DB instance.
        """
        try:
            response = self.rds_client.describe_db_instances(
                DBInstanceIdentifier=instance_id
            )
            db_inst = response["DBInstances"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBInstanceNotFound":
                logger.info("Instance %s does not exist.", instance_id)
            else:
                logger.error(
                    "Couldn't get DB instance %s. Here's why: %s: %s",
                    instance_id,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return db_inst


    def delete_db_instance(self, instance_id):
        """
        Deletes a DB instance.

        :param instance_id: The ID of the DB instance to delete.
        :return: Data about the deleted DB instance.
        """
        try:
            response = self.rds_client.delete_db_instance(
                DBInstanceIdentifier=instance_id,
                SkipFinalSnapshot=True,
                DeleteAutomatedBackups=True,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't delete DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBCluster](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBCluster)
  + [CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBClusterParameterGroup)
  + [CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBClusterSnapshot)
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBInstance)
  + [DeleteDBCluster](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBCluster)
  + [DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBClusterParameterGroup)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBInstance)
  + [DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusterParameterGroups)
  + [DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusterParameters)
  + [DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusterSnapshots)
  + [DescribeDBClusters](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusters)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBInstances)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/ModifyDBClusterParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="aurora_CreateDBCluster_python_3_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def create_db_cluster(
        self,
        cluster_name,
        parameter_group_name,
        db_name,
        db_engine,
        db_engine_version,
        admin_name,
        admin_password,
    ):
        """
        Creates a DB cluster that is configured to use the specified parameter group.
        The newly created DB cluster contains a database that uses the specified engine and
        engine version.

        :param cluster_name: The name of the DB cluster to create.
        :param parameter_group_name: The name of the parameter group to associate with
                                     the DB cluster.
        :param db_name: The name of the database to create.
        :param db_engine: The database engine of the database that is created, such as MySql.
        :param db_engine_version: The version of the database engine.
        :param admin_name: The user name of the database administrator.
        :param admin_password: The password of the database administrator.
        :return: The newly created DB cluster.
        """
        try:
            response = self.rds_client.create_db_cluster(
                DatabaseName=db_name,
                DBClusterIdentifier=cluster_name,
                DBClusterParameterGroupName=parameter_group_name,
                Engine=db_engine,
                EngineVersion=db_engine_version,
                MasterUsername=admin_name,
                MasterUserPassword=admin_password,
            )
            cluster = response["DBCluster"]
        except ClientError as err:
            logger.error(
                "Couldn't create database %s. Here's why: %s: %s",
                db_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return cluster
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBCluster](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBCluster)」を参照してください。

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_python_3_topic"></a>

次のコード例は、`CreateDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def create_parameter_group(
        self, parameter_group_name, parameter_group_family, description
    ):
        """
        Creates a DB cluster parameter group that is based on the specified parameter group
        family.

        :param parameter_group_name: The name of the newly created parameter group.
        :param parameter_group_family: The family that is used as the basis of the new
                                       parameter group.
        :param description: A description given to the parameter group.
        :return: Data about the newly created parameter group.
        """
        try:
            response = self.rds_client.create_db_cluster_parameter_group(
                DBClusterParameterGroupName=parameter_group_name,
                DBParameterGroupFamily=parameter_group_family,
                Description=description,
            )
        except ClientError as err:
            logger.error(
                "Couldn't create parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBClusterParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBClusterParameterGroup)」を参照してください。

### `CreateDBClusterSnapshot`
<a name="aurora_CreateDBClusterSnapshot_python_3_topic"></a>

次のコード例は、`CreateDBClusterSnapshot` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def create_cluster_snapshot(self, snapshot_id, cluster_id):
        """
        Creates a snapshot of a DB cluster.

        :param snapshot_id: The ID to give the created snapshot.
        :param cluster_id: The DB cluster to snapshot.
        :return: Data about the newly created snapshot.
        """
        try:
            response = self.rds_client.create_db_cluster_snapshot(
                DBClusterSnapshotIdentifier=snapshot_id, DBClusterIdentifier=cluster_id
            )
            snapshot = response["DBClusterSnapshot"]
        except ClientError as err:
            logger.error(
                "Couldn't create snapshot of %s. Here's why: %s: %s",
                cluster_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBClusterSnapshot](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBClusterSnapshot)」を参照してください。

### `CreateDBInstance`
<a name="aurora_CreateDBInstance_python_3_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def create_instance_in_cluster(
        self, instance_id, cluster_id, db_engine, instance_class
    ):
        """
        Creates a database instance in an existing DB cluster. The first database that is
        created defaults to a read-write DB instance.

        :param instance_id: The ID to give the newly created DB instance.
        :param cluster_id: The ID of the DB cluster where the DB instance is created.
        :param db_engine: The database engine of a database to create in the DB instance.
                          This must be compatible with the configured parameter group
                          of the DB cluster.
        :param instance_class: The DB instance class for the newly created DB instance.
        :return: Data about the newly created DB instance.
        """
        try:
            response = self.rds_client.create_db_instance(
                DBInstanceIdentifier=instance_id,
                DBClusterIdentifier=cluster_id,
                Engine=db_engine,
                DBInstanceClass=instance_class,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't create DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `DeleteDBCluster`
<a name="aurora_DeleteDBCluster_python_3_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def delete_db_cluster(self, cluster_name):
        """
        Deletes a DB cluster.

        :param cluster_name: The name of the DB cluster to delete.
        """
        try:
            self.rds_client.delete_db_cluster(
                DBClusterIdentifier=cluster_name, SkipFinalSnapshot=True
            )
            logger.info("Deleted DB cluster %s.", cluster_name)
        except ClientError:
            logger.exception("Couldn't delete DB cluster %s.", cluster_name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDBCluster](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBCluster)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_python_3_topic"></a>

次のコード例は、`DeleteDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def delete_parameter_group(self, parameter_group_name):
        """
        Deletes a DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to delete.
        :return: Data about the parameter group.
        """
        try:
            response = self.rds_client.delete_db_cluster_parameter_group(
                DBClusterParameterGroupName=parameter_group_name
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」で「[DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBClusterParameterGroup)」を参照してください。

### `DeleteDBInstance`
<a name="aurora_DeleteDBInstance_python_3_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def delete_db_instance(self, instance_id):
        """
        Deletes a DB instance.

        :param instance_id: The ID of the DB instance to delete.
        :return: Data about the deleted DB instance.
        """
        try:
            response = self.rds_client.delete_db_instance(
                DBInstanceIdentifier=instance_id,
                SkipFinalSnapshot=True,
                DeleteAutomatedBackups=True,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't delete DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DescribeDBClusterParameterGroups`
<a name="aurora_DescribeDBClusterParameterGroups_python_3_topic"></a>

次のコード例は、`DescribeDBClusterParameterGroups` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_parameter_group(self, parameter_group_name):
        """
        Gets a DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to retrieve.
        :return: The requested parameter group.
        """
        try:
            response = self.rds_client.describe_db_cluster_parameter_groups(
                DBClusterParameterGroupName=parameter_group_name
            )
            parameter_group = response["DBClusterParameterGroups"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBParameterGroupNotFound":
                logger.info("Parameter group %s does not exist.", parameter_group_name)
            else:
                logger.error(
                    "Couldn't get parameter group %s. Here's why: %s: %s",
                    parameter_group_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return parameter_group
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusterParameterGroups)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_python_3_topic"></a>

次のコード例は、`DescribeDBClusterParameters` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_parameters(self, parameter_group_name, name_prefix="", source=None):
        """
        Gets the parameters that are contained in a DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to query.
        :param name_prefix: When specified, the retrieved list of parameters is filtered
                            to contain only parameters that start with this prefix.
        :param source: When specified, only parameters from this source are retrieved.
                       For example, a source of 'user' retrieves only parameters that
                       were set by a user.
        :return: The list of requested parameters.
        """
        try:
            kwargs = {"DBClusterParameterGroupName": parameter_group_name}
            if source is not None:
                kwargs["Source"] = source
            parameters = []
            paginator = self.rds_client.get_paginator("describe_db_cluster_parameters")
            for page in paginator.paginate(**kwargs):
                parameters += [
                    p
                    for p in page["Parameters"]
                    if p["ParameterName"].startswith(name_prefix)
                ]
        except ClientError as err:
            logger.error(
                "Couldn't get parameters for %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return parameters
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBClusterParameters](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusterParameters)」を参照してください。

### `DescribeDBClusterSnapshots`
<a name="aurora_DescribeDBClusterSnapshots_python_3_topic"></a>

次のコード例は、`DescribeDBClusterSnapshots` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_cluster_snapshot(self, snapshot_id):
        """
        Gets a DB cluster snapshot.

        :param snapshot_id: The ID of the snapshot to retrieve.
        :return: The retrieved snapshot.
        """
        try:
            response = self.rds_client.describe_db_cluster_snapshots(
                DBClusterSnapshotIdentifier=snapshot_id
            )
            snapshot = response["DBClusterSnapshots"][0]
        except ClientError as err:
            logger.error(
                "Couldn't get DB cluster snapshot %s. Here's why: %s: %s",
                snapshot_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBClusterSnapshots](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusterSnapshots)」を参照してください。

### `DescribeDBClusters`
<a name="aurora_DescribeDBClusters_python_3_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_db_cluster(self, cluster_name):
        """
        Gets data about an Aurora DB cluster.

        :param cluster_name: The name of the DB cluster to retrieve.
        :return: The retrieved DB cluster.
        """
        try:
            response = self.rds_client.describe_db_clusters(
                DBClusterIdentifier=cluster_name
            )
            cluster = response["DBClusters"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBClusterNotFoundFault":
                logger.info("Cluster %s does not exist.", cluster_name)
            else:
                logger.error(
                    "Couldn't verify the existence of DB cluster %s. Here's why: %s: %s",
                    cluster_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return cluster
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBClusters)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_python_3_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_engine_versions(self, engine, parameter_group_family=None):
        """
        Gets database engine versions that are available for the specified engine
        and parameter group family.

        :param engine: The database engine to look up.
        :param parameter_group_family: When specified, restricts the returned list of
                                       engine versions to those that are compatible with
                                       this parameter group family.
        :return: The list of database engine versions.
        """
        try:
            kwargs = {"Engine": engine}
            if parameter_group_family is not None:
                kwargs["DBParameterGroupFamily"] = parameter_group_family
            response = self.rds_client.describe_db_engine_versions(**kwargs)
            versions = response["DBEngineVersions"]
        except ClientError as err:
            logger.error(
                "Couldn't get engine versions for %s. Here's why: %s: %s",
                engine,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return versions
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="aurora_DescribeDBInstances_python_3_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_db_instance(self, instance_id):
        """
        Gets data about a DB instance.

        :param instance_id: The ID of the DB instance to retrieve.
        :return: The retrieved DB instance.
        """
        try:
            response = self.rds_client.describe_db_instances(
                DBInstanceIdentifier=instance_id
            )
            db_inst = response["DBInstances"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBInstanceNotFound":
                logger.info("Instance %s does not exist.", instance_id)
            else:
                logger.error(
                    "Couldn't get DB instance %s. Here's why: %s: %s",
                    instance_id,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return db_inst
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="aurora_DescribeOrderableDBInstanceOptions_python_3_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_orderable_instances(self, db_engine, db_engine_version):
        """
        Gets DB instance options that can be used to create DB instances that are
        compatible with a set of specifications.

        :param db_engine: The database engine that must be supported by the DB instance.
        :param db_engine_version: The engine version that must be supported by the DB instance.
        :return: The list of DB instance options that can be used to create a compatible DB instance.
        """
        try:
            inst_opts = []
            paginator = self.rds_client.get_paginator(
                "describe_orderable_db_instance_options"
            )
            for page in paginator.paginate(
                Engine=db_engine, EngineVersion=db_engine_version
            ):
                inst_opts += page["OrderableDBInstanceOptions"]
        except ClientError as err:
            logger.error(
                "Couldn't get orderable DB instances. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return inst_opts
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_python_3_topic"></a>

次のコード例は、`ModifyDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
class AuroraWrapper:
    """Encapsulates Aurora DB cluster actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon Relational Database Service (Amazon RDS) client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def update_parameters(self, parameter_group_name, update_parameters):
        """
        Updates parameters in a custom DB cluster parameter group.

        :param parameter_group_name: The name of the parameter group to update.
        :param update_parameters: The parameters to update in the group.
        :return: Data about the modified parameter group.
        """
        try:
            response = self.rds_client.modify_db_cluster_parameter_group(
                DBClusterParameterGroupName=parameter_group_name,
                Parameters=update_parameters,
            )
        except ClientError as err:
            logger.error(
                "Couldn't update parameters in %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/ModifyDBClusterParameterGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 貸出ライブラリ REST API を作成する
<a name="cross_AuroraRestLendingLibrary_python_3_topic"></a>

以下のコード例は、Amazon Aurora データベースでバックアップされた REST API を使用して、常連客が書籍の貸出と返却できる貸出ライブラリを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Relational Database Service (Amazon RDS) API と AWS Chalice AWS SDK for Python (Boto3) で を使用して、Amazon Aurora データベースにバックアップされた REST API を作成する方法を示します。Web サービスは完全にサーバーレスであり、常連客が本を借りたり返却したりできるシンプルな貸し出しライブラリを表しています。以下ではその方法を説明しています。  
+ サーバーレス Aurora データベースクラスターを作成および管理します。
+  AWS Secrets Manager を使用してデータベース認証情報を管理します。
+ Amazon RDS を使用してデータをデータベースに出し入れするデータストレージレイヤーを実装します。
+  AWS Chalice を使用して、サーバーレス REST API を Amazon API Gateway および にデプロイします AWS Lambda。
+ リクエストパッケージを使用して、Web サービスにリクエストを送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_rest_lending_library) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ Aurora
+ Lambda
+ Secrets Manager

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_python_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して Amazon Aurora Serverless データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信する REST サービス AWS SDK for Python (Boto3) を作成する方法を示します。この例では、Flask ウェブフレームワークを使用して HTTP ルーティングを処理し、React ウェブページと統合して完全に機能するウェブアプリケーションを提供しています。  
+ と統合する Flask REST サービスを構築します AWS のサービス。
+ Aurora Serverless データベースに保存されている作業項目の読み取り、書き込み、更新を行います。
+ データベース認証情報を含む AWS Secrets Manager シークレットを作成し、それを使用してデータベースへの呼び出しを認証します。
+ Amazon SES を使用して作業項目のレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for Python (Boto3) を使用した Auto Scaling の例
<a name="python_3_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### こんにちは、Auto Scaling
<a name="auto-scaling_Hello_python_3_topic"></a>

次のコード例は、Auto Scaling の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_autoscaling(autoscaling_client):
    """
    Use the AWS SDK for Python (Boto3) to create an Amazon EC2 Auto Scaling client and list
    some of the Auto Scaling groups in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client object.
    """
    print(
        "Hello, Amazon EC2 Auto Scaling! Let's list up to ten of you Auto Scaling groups:"
    )
    response = autoscaling_client.describe_auto_scaling_groups()
    groups = response.get("AutoScalingGroups", [])
    if groups:
        for group in groups:
            print(f"\t{group['AutoScalingGroupName']}: {group['AvailabilityZones']}")
    else:
        print("There are no Auto Scaling groups in your account.")


if __name__ == "__main__":
    hello_autoscaling(boto3.client("autoscaling"))
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="auto-scaling_Scenario_GroupsAndInstances_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 起動テンプレートとアベイラビリティーゾーンを使用して、Amazon EC2 Auto Scaling グループを作成し、実行中のインスタンスに関する情報を取得します。
+ Amazon CloudWatch メトリクスの収集を有効にします。
+ グループの希望するキャパシティを更新し、インスタンスが起動するのを待ちます。
+  グループ内の最も古いインスタンスを削除します。
+ ユーザーのリクエストやキャパシティの変更に応じて発生するスケーリングアクティビティを一覧表示します。
+ CloudWatch メトリクスの統計を取得して、リソースをクリーンアップします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
def run_scenario(as_wrapper: AutoScalingWrapper, svc_helper: ServiceHelper) -> None:
    """
    Runs the scenario demonstrating the management of Auto Scaling groups and instances.

    :param as_wrapper: An instance of the AutoScalingWrapper that manages Auto Scaling groups.
    :param svc_helper: An instance of the ServiceHelper that interacts with AWS services.
    :return: None
    """
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    logger.info("Starting the Amazon EC2 Auto Scaling demo.")

    print("-" * 88)
    print(
        "Welcome to the Amazon EC2 Auto Scaling demo for managing groups and instances."
    )
    print("-" * 88)

    print(
        "This example requires a launch template that specifies how to create "
        "EC2 instances. You can use an existing template or create a new one."
    )
    template_name = q.ask(
        "Enter the name of an existing launch template or press Enter to create a new one: "
    )
    template = None
    if template_name:
        template = svc_helper.get_template(template_name)
    if template is None:
        inst_type = "t1.micro"
        ami_id = "ami-0ca285d4c2cda3300"
        print("Let's create a launch template with the following specifications:")
        print(f"\tInstanceType: {inst_type}")
        print(f"\tAMI ID: {ami_id}")
        template_name = q.ask("Enter a name for the template: ", q.non_empty)
        template = svc_helper.create_template(template_name, inst_type, ami_id)
    print("-" * 88)

    print("Let's create an Auto Scaling group.")
    group_name = q.ask("Enter a name for the group: ", q.non_empty)
    zones = svc_helper.get_availability_zones()
    print("EC2 instances can be created in the following Availability Zones:")
    for index, zone in enumerate(zones):
        print(f"\t{index+1}. {zone}")
    print(f"\t{len(zones)+1}. All zones")
    zone_sel = q.ask(
        "Which zone do you want to use? ", q.is_int, q.in_range(1, len(zones) + 1)
    )
    group_zones = [zones[zone_sel - 1]] if zone_sel <= len(zones) else zones
    print(f"Creating group {group_name}...")
    as_wrapper.create_autoscaling_group(group_name, group_zones, template_name, 1, 1)
    wait(10)
    group = as_wrapper.describe_group(group_name)
    logger.info("Created Auto Scaling group %s.", group_name)
    print("Created group:")
    pp(group)
    print("Waiting for instance to start...")
    wait_for_group(group_name, as_wrapper)
    print("-" * 88)

    use_metrics = q.ask(
        "Do you want to collect metrics about Amazon EC2 Auto Scaling during this demo (y/n)? ",
        q.is_yesno,
    )
    if use_metrics:
        as_wrapper.enable_metrics(
            group_name,
            [
                "GroupMinSize",
                "GroupMaxSize",
                "GroupDesiredCapacity",
                "GroupInServiceInstances",
                "GroupTotalInstances",
            ],
        )
        logger.info("Enabled metrics for Auto Scaling group %s.", group_name)
        print(f"Metrics enabled for {group_name}.")
    print("-" * 88)

    print(f"Let's update the maximum number of instances in {group_name} from 1 to 3.")
    q.ask("Press Enter when you're ready.")
    as_wrapper.update_group(group_name, MaxSize=3)
    group = as_wrapper.describe_group(group_name)
    logger.info("Updated maximum size for group %s to 3.", group_name)
    print("The group still has one running instance, but can have up to three:")
    print_simplified_group(group)
    print("-" * 88)

    print(f"Let's update the desired capacity of {group_name} from 1 to 2.")
    q.ask("Press Enter when you're ready.")
    as_wrapper.set_desired_capacity(group_name, 2)
    wait(10)
    group = as_wrapper.describe_group(group_name)
    logger.info("Set desired capacity for group %s to 2.", group_name)
    print("Here's the current state of the group:")
    print_simplified_group(group)
    print("-" * 88)
    print("Waiting for the new instance to start...")
    instance_ids = wait_for_group(group_name, as_wrapper)
    print("-" * 88)

    print(f"Let's terminate one of the instances in {group_name}.")
    print("Because the desired capacity is 2, another instance will start.")
    print("The currently running instances are:")
    for index, inst_id in enumerate(instance_ids):
        print(f"\t{index+1}. {inst_id}")
    inst_sel = q.ask(
        "Which instance do you want to stop? ",
        q.is_int,
        q.in_range(1, len(instance_ids) + 1),
    )
    print(f"Stopping {instance_ids[inst_sel-1]}...")
    as_wrapper.terminate_instance(instance_ids[inst_sel - 1], False)
    wait(10)
    group = as_wrapper.describe_group(group_name)
    logger.info(
        "Terminated instance %s in group %s.", instance_ids[inst_sel - 1], group_name
    )
    print(f"Here's the state of {group_name}:")
    print_simplified_group(group)
    print("Waiting for the scaling activities to complete...")
    wait_for_group(group_name, as_wrapper)
    print("-" * 88)

    print(f"Let's get a report of scaling activities for {group_name}.")
    q.ask("Press Enter when you're ready.")
    activities = as_wrapper.describe_scaling_activities(group_name)
    logger.info(
        "Retrieved %d scaling activities for group %s.", len(activities), group_name
    )
    print(
        f"Found {len(activities)} activities.\n"
        f"Activities are ordered with the most recent one first:"
    )
    for act in activities:
        pp(act)
    print("-" * 88)

    if use_metrics:
        print("Let's look at CloudWatch metrics.")
        metric_namespace = "AWS/AutoScaling"
        metric_dimensions = [{"Name": "AutoScalingGroupName", "Value": group_name}]
        print(f"The following metrics are enabled for {group_name}:")
        done = False
        while not done:
            metrics = svc_helper.get_metrics(metric_namespace, metric_dimensions)
            for index, metric in enumerate(metrics):
                print(f"\t{index+1}. {metric.name}")
            print(f"\t{len(metrics)+1}. None")
            metric_sel = q.ask(
                "Which metric do you want to see? ",
                q.is_int,
                q.in_range(1, len(metrics) + 1),
            )
            if metric_sel < len(metrics) + 1:
                span = 5
                metric = metrics[metric_sel - 1]
                print(f"Over the last {span} minutes, {metric.name} recorded:")
                # CloudWatch metric times are in the UTC+0 time zone.
                now = datetime.now(timezone.utc)
                metric_data = svc_helper.get_metric_statistics(
                    metric_dimensions, metric, now - timedelta(minutes=span), now
                )
                pp(metric_data)
                if not q.ask("Do you want to see another metric (y/n)? ", q.is_yesno):
                    done = True
            else:
                done = True

    print(f"Let's clean up.")
    q.ask("Press Enter when you're ready.")
    if use_metrics:
        print(f"Stopping metrics collection for {group_name}.")
        as_wrapper.disable_metrics(group_name)
        logger.info("Disabled metrics collection for group %s.", group_name)

    print(
        "You must terminate all instances in the group before you can delete the group."
    )
    print("Set minimum size to 0.")
    as_wrapper.update_group(group_name, MinSize=0)
    group = as_wrapper.describe_group(group_name)
    instance_ids = [inst["InstanceId"] for inst in group["Instances"]]
    for inst_id in instance_ids:
        print(f"Stopping {inst_id}.")
        as_wrapper.terminate_instance(inst_id, True)
        logger.info("Terminated instance %s in group %s.", inst_id, group_name)
    print("Waiting for instances to stop...")
    wait_for_instances(instance_ids, as_wrapper)
    print(f"Deleting {group_name}.")
    as_wrapper.delete_autoscaling_group(group_name)
    logger.info("Deleted Auto Scaling group %s.", group_name)
    print("-" * 88)

    if template is not None:
        if q.ask(
            f"Do you want to delete launch template {template_name} used in this demo (y/n)? "
        ):
            svc_helper.delete_template(template_name)
            logger.info("Deleted launch template %s.", template_name)
            print("Template deleted.")

    print("\nThanks for watching!")
    print("-" * 88)


if __name__ == "__main__":
    try:
        wrapper = AutoScalingWrapper(boto3.client("autoscaling"))
        helper = ServiceHelper(boto3.client("ec2"), boto3.resource("cloudwatch"))
        run_scenario(wrapper, helper)
    except Exception:
        logger.exception("Something went wrong with the demo!")
```
起動テンプレートとメトリクスを管理するためにシナリオによって呼び出される関数を定義します。これらの関数は、Amazon EC2 および CloudWatch アクションをラップします。  

```
class ServiceHelper:
    """Encapsulates Amazon EC2 and CloudWatch actions for the example."""

    def __init__(self, ec2_client, cloudwatch_resource):
        """
        :param ec2_client: A Boto3 Amazon EC2 client.
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.ec2_client = ec2_client
        self.cloudwatch_resource = cloudwatch_resource

    def get_template(self, template_name: str) -> dict:
        """
        Gets a launch template. Launch templates specify configuration for instances
        that are launched by Amazon EC2 Auto Scaling.

        :param template_name: The name of the template to look up.
        :return: The template, if it exists.
        :raises ClientError: If there is an error retrieving the launch template.
        """
        try:
            response = self.ec2_client.describe_launch_templates(
                LaunchTemplateNames=[template_name]
            )
            template = response["LaunchTemplates"][0]
            logger.info("Launch template %s retrieved successfully.", template_name)
            return template
        except ClientError as err:
            if (
                err.response["Error"]["Code"]
                == "InvalidLaunchTemplateName.NotFoundException"
            ):
                logger.warning("Launch template %s does not exist.", template_name)
            else:
                logger.error(
                    "Couldn't verify launch template %s. Error: %s: %s",
                    template_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise

    def create_template(self, template_name: str, inst_type: str, ami_id: str) -> dict:
        """
        Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling.

        :param template_name: The name to give to the template.
        :param inst_type: The type of the instance, such as t1.micro.
        :param ami_id: The ID of the Amazon Machine Image (AMI) to use when creating
                       an instance.
        :return: Information about the newly created template.
        :raises ClientError: If there is an error creating the launch template.
        """
        try:
            response = self.ec2_client.create_launch_template(
                LaunchTemplateName=template_name,
                LaunchTemplateData={"InstanceType": inst_type, "ImageId": ami_id},
            )
            template = response["LaunchTemplate"]
            logger.info(
                "Created launch template %s with instance type %s and AMI ID %s.",
                template_name,
                inst_type,
                ami_id,
            )
            return template
        except ClientError as err:
            logger.error(
                "Couldn't create launch template %s. Error: %s: %s",
                template_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

    def delete_template(self, template_name: str) -> None:
        """
        Deletes a launch template.

        :param template_name: The name of the template to delete.
        :raises ClientError: If there is an error deleting the launch template.
        """
        try:
            self.ec2_client.delete_launch_template(LaunchTemplateName=template_name)
            logger.info("Deleted launch template %s.", template_name)
        except ClientError as err:
            logger.error(
                "Couldn't delete launch template %s. Error: %s: %s",
                template_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

    def get_availability_zones(self) -> list:
        """
        Gets a list of Availability Zones in the AWS Region of the Amazon EC2 client.

        :return: The list of Availability Zones for the client Region.
        :raises ClientError: If there is an error retrieving availability zones.
        """
        try:
            response = self.ec2_client.describe_availability_zones()
            zones = [zone["ZoneName"] for zone in response["AvailabilityZones"]]
            logger.info("Retrieved availability zones: %s.", ", ".join(zones))
            return zones
        except ClientError as err:
            logger.error(
                "Couldn't get availability zones. Error: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

    def get_metrics(self, namespace: str, dimensions: list) -> list:
        """
        Gets a list of CloudWatch metrics filtered by namespace and dimensions.

        :param namespace: The namespace of the metrics to look up.
        :param dimensions: The dimensions of the metrics to look up.
        :return: The list of metrics.
        :raises ClientError: If there is an error retrieving CloudWatch metrics.
        """
        try:
            metrics = list(
                self.cloudwatch_resource.metrics.filter(
                    Namespace=namespace, Dimensions=dimensions
                )
            )
            logger.info(
                "Retrieved metrics for namespace %s with dimensions %s.",
                namespace,
                dimensions,
            )
            return metrics
        except ClientError as err:
            logger.error(
                "Couldn't get metrics for %s, %s. Error: %s: %s",
                namespace,
                dimensions,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

    @staticmethod
    def get_metric_statistics(
        dimensions: list, metric, start: datetime, end: datetime
    ) -> list:
        """
        Gets statistics for a CloudWatch metric within a specified time span.

        :param dimensions: The dimensions of the metric.
        :param metric: The metric to look up.
        :param start: The start of the time span for retrieved metrics.
        :param end: The end of the time span for retrieved metrics.
        :return: The list of data points found for the specified metric.
        :raises ClientError: If there is an error retrieving metric statistics.
        """
        try:
            response = metric.get_statistics(
                Dimensions=dimensions,
                StartTime=start,
                EndTime=end,
                Period=60,
                Statistics=["Sum"],
            )
            data = response["Datapoints"]
            logger.info("Retrieved statistics for metric %s.", metric.name)
            return data
        except ClientError as err:
            logger.error(
                "Couldn't get statistics for metric %s. Error: %s: %s",
                metric.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


def print_simplified_group(group: dict) -> None:
    """
    Prints a subset of data for an Auto Scaling group.

    :param group: The Auto Scaling group data to print.
    :return: None
    """
    print(group["AutoScalingGroupName"])
    print(f"\tLaunch template: {group['LaunchTemplate']['LaunchTemplateName']}")
    print(
        f"\tMin: {group['MinSize']}, Max: {group['MaxSize']}, Desired: {group['DesiredCapacity']}"
    )
    if group["Instances"]:
        print(f"\tInstances:")
        for inst in group["Instances"]:
            print(f"\t\t{inst['InstanceId']}: {inst['LifecycleState']}")


def wait_for_group(group_name: str, as_wrapper: AutoScalingWrapper) -> list:
    """
    Waits for instances to start or stop in an Auto Scaling group.
    Prints the data for each instance after scaling activities are complete.

    :param group_name: The name of the Auto Scaling group.
    :param as_wrapper: The AutoScalingWrapper that manages Auto Scaling groups.
    :return: A list of instance IDs in the group.
    """
    group = as_wrapper.describe_group(group_name)
    instance_ids = [i["InstanceId"] for i in group["Instances"]]
    return wait_for_instances(instance_ids, as_wrapper)


def wait_for_instances(instance_ids: list, as_wrapper: AutoScalingWrapper) -> list:
    """
    Waits for instances to start or stop in an Auto Scaling group.
    Prints the data for each instance after scaling activities are complete.

    :param instance_ids: A list of instance IDs to wait for.
    :param as_wrapper: The AutoScalingWrapper that manages Auto Scaling groups.
    :return: A list of instance IDs that were waited on.
    """
    ready = False
    instances = []
    while not ready:
        instances = as_wrapper.describe_instances(instance_ids) if instance_ids else []
        if all([x["LifecycleState"] in ["Terminated", "InService"] for x in instances]):
            ready = True
        else:
            wait(10)
    if instances:
        print(
            f"Here are the details of the instance{'s' if len(instances) > 1 else ''}:"
        )
        for instance in instances:
            pp(instance)
    return instance_ids
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingInstances)
  + [DescribeScalingActivities](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeScalingActivities)
  + [DisableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DisableMetricsCollection)
  + [EnableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/EnableMetricsCollection)
  + [SetDesiredCapacity](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/SetDesiredCapacity)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

## アクション
<a name="actions"></a>

### `AttachLoadBalancerTargetGroups`
<a name="auto-scaling_AttachLoadBalancerTargetGroups_python_3_topic"></a>

次のコード例は、`AttachLoadBalancerTargetGroups` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def attach_load_balancer_target_group(
        self, lb_target_group: Dict[str, Any]
    ) -> None:
        """
        Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
        The target group specifies how the load balancer forwards requests to the instances
        in the group.

        :param lb_target_group: Data about the ELB target group to attach.
        """
        try:
            self.autoscaling_client.attach_load_balancer_target_groups(
                AutoScalingGroupName=self.group_name,
                TargetGroupARNs=[lb_target_group["TargetGroupArn"]],
            )
            log.info(
                "Attached load balancer target group %s to auto scaling group %s.",
                lb_target_group["TargetGroupName"],
                self.group_name,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to attach load balancer target group '{lb_target_group['TargetGroupName']}'."
            )
            if error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            elif error_code == "ServiceLinkedRoleFailure":
                log.error(
                    "The operation failed because the service-linked role is not ready or does not exist. "
                    "Check that the service-linked role exists and is correctly configured."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)」を参照してください。

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_python_3_topic"></a>

次のコード例は、`CreateAutoScalingGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def create_group(
        self,
        group_name: str,
        group_zones: List[str],
        launch_template_name: str,
        min_size: int,
        max_size: int,
    ) -> None:
        """
        Creates an Auto Scaling group.

        :param group_name: The name to give to the group.
        :param group_zones: The Availability Zones in which instances can be created.
        :param launch_template_name: The name of an existing Amazon EC2 launch template.
                                     The launch template specifies the configuration of
                                     instances that are created by auto scaling activities.
        :param min_size: The minimum number of active instances in the group.
        :param max_size: The maximum number of active instances in the group.
        :return: None
        :raises ClientError: If there is an error creating the Auto Scaling group.
        """
        try:
            self.autoscaling_client.create_auto_scaling_group(
                AutoScalingGroupName=group_name,
                AvailabilityZones=group_zones,
                LaunchTemplate={
                    "LaunchTemplateName": launch_template_name,
                    "Version": "$Default",
                },
                MinSize=min_size,
                MaxSize=max_size,
            )

            # Wait for the group to exist.
            waiter = self.autoscaling_client.get_waiter("group_exists")
            waiter.wait(AutoScalingGroupNames=[group_name])

            logger.info(f"Successfully created Auto Scaling group {group_name}.")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to create Auto Scaling group {group_name}.")
            if error_code == "AlreadyExistsFault":
                logger.error(
                    f"An Auto Scaling group with the name '{group_name}' already exists. "
                    "Please use a different name or update the existing group.",
                )
            elif error_code == "LimitExceededFault":
                logger.error(
                    "The request failed because you have reached the limit "
                    "on the number of Auto Scaling groups or launch configurations. "
                    "Consider deleting unused resources or request a limit increase. "
                    "\nSee Auto Scaling Service Quota documentation here:"
                    "\n\thttps://docs.aws.amazon.com/autoscaling/ec2/userguide/ec2-auto-scaling-quotas.html"
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_python_3_topic"></a>

次のコード例は、`DeleteAutoScalingGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。
Auto Scaling グループの最小サイズをゼロに更新し、グループ内のすべてのインスタンスを終了して、グループを削除します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def delete_autoscaling_group(self, group_name: str) -> None:
        """
        Terminates all instances in the group, then deletes the EC2 Auto Scaling group.

        :param group_name: The name of the group to delete.
        """
        try:
            response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[group_name]
            )
            groups = response.get("AutoScalingGroups", [])
            if len(groups) > 0:
                self.autoscaling_client.update_auto_scaling_group(
                    AutoScalingGroupName=group_name, MinSize=0
                )
                instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]]
                for inst_id in instance_ids:
                    self.terminate_instance(inst_id)

                # Wait for all instances to be terminated
                if instance_ids:
                    waiter = self.ec2_client.get_waiter("instance_terminated")
                    log.info("Waiting for all instances to be terminated...")
                    waiter.wait(InstanceIds=instance_ids)
                    log.info("All instances have been terminated.")
            else:
                log.info(f"No groups found named '{group_name}'! Nothing to do.")
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete Auto Scaling group '{group_name}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to delete the group again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the group."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_python_3_topic"></a>

次のコード例は、`DescribeAutoScalingGroups` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def describe_group(self, group_name: str) -> Optional[Dict[str, Any]]:
        """
        Gets information about an Auto Scaling group.

        :param group_name: The name of the group to look up.
        :return: A dictionary with information about the group if found, otherwise None.
        :raises ClientError: If there is an error describing the Auto Scaling group.
        """
        try:
            paginator = self.autoscaling_client.get_paginator(
                "describe_auto_scaling_groups"
            )
            response_iterator = paginator.paginate(AutoScalingGroupNames=[group_name])
            groups = []
            for response in response_iterator:
                groups.extend(response.get("AutoScalingGroups", []))

            logger.info(
                f"Successfully retrieved information for Auto Scaling group {group_name}."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to describe Auto Scaling group {group_name}.")
            if error_code == "ResourceContentionFault":
                logger.error(
                    "There is a conflict with another operation that is modifying the "
                    f"Auto Scaling group '{group_name}' Please try again later."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
        else:
            return groups[0] if len(groups) > 0 else None
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_python_3_topic"></a>

次のコード例は、`DescribeAutoScalingInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def describe_instances(self, instance_ids: List[str]) -> List[Dict[str, Any]]:
        """
        Gets information about instances.

        :param instance_ids: A list of instance IDs to look up.
        :return: A list of dictionaries with information about each instance,
                 or an empty list if none are found.
        :raises ClientError: If there is an error describing the instances.
        """
        try:
            paginator = self.autoscaling_client.get_paginator(
                "describe_auto_scaling_instances"
            )
            response_iterator = paginator.paginate(InstanceIds=instance_ids)

            instances = []
            for response in response_iterator:
                instances.extend(response.get("AutoScalingInstances", []))

            logger.info(f"Successfully described instances: {instance_ids}")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Couldn't describe instances {instance_ids}. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )
            raise
        else:
            return instances
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingInstances)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_python_3_topic"></a>

次のコード例は、`DescribeScalingActivities` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def describe_scaling_activities(self, group_name: str) -> List[Dict[str, Any]]:
        """
        Gets information about scaling activities for the group. Scaling activities
        are things like instances stopping or starting in response to user requests
        or capacity changes.

        :param group_name: The name of the group to look up.
        :return: A list of dictionaries representing the scaling activities for the
                 group, ordered with the most recent activity first.
        :raises ClientError: If there is an error describing the scaling activities.
        """
        try:
            paginator = self.autoscaling_client.get_paginator(
                "describe_scaling_activities"
            )
            response_iterator = paginator.paginate(AutoScalingGroupName=group_name)
            activities = []
            for response in response_iterator:
                activities.extend(response.get("Activities", []))

            logger.info(
                f"Successfully described scaling activities for group '{group_name}'."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Couldn't describe scaling activities for group '{group_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "ResourceContentionFault":
                logger.error(
                    f"There is a conflict with another operation that is modifying the Auto Scaling group '{group_name}'. "
                    "Please try again later."
                )
            raise
        else:
            return activities
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeScalingActivities](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeScalingActivities)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_python_3_topic"></a>

次のコード例は、`DisableMetricsCollection` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def disable_metrics(self, group_name: str) -> Dict[str, Any]:
        """
        Stops CloudWatch metric collection for the Auto Scaling group.

        :param group_name: The name of the group.
        :return: A dictionary with the response from disabling the metrics collection.
        :raises ClientError: If there is an error disabling metrics collection.
        """
        try:
            response = self.autoscaling_client.disable_metrics_collection(
                AutoScalingGroupName=group_name
            )
            logger.info(
                f"Successfully disabled metrics collection for group '{group_name}'."
            )
            return response
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Couldn't disable metrics for group '{group_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "ResourceContentionFault":
                logger.error(
                    f"There is a conflict with another operation that is modifying the Auto Scaling group '{group_name}'. "
                    "Please try again later."
                )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DisableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DisableMetricsCollection)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_python_3_topic"></a>

次のコード例は、`EnableMetricsCollection` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def enable_metrics(self, group_name: str, metrics: List[str]) -> Dict[str, Any]:
        """
        Enables CloudWatch metric collection for Amazon EC2 Auto Scaling activities.

        :param group_name: The name of the group to enable.
        :param metrics: A list of metrics to collect.
        :return: A dictionary with the response from enabling the metrics collection.
        :raises ClientError: If there is an error enabling metrics collection.
        """
        try:
            response = self.autoscaling_client.enable_metrics_collection(
                AutoScalingGroupName=group_name, Metrics=metrics, Granularity="1Minute"
            )
            logger.info(
                f"Successfully enabled metrics for Auto Scaling group '{group_name}'."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Couldn't enable metrics on '{group_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "ResourceContentionFault":
                logger.error(
                    f"There is a conflict with another operation that is modifying the Auto Scaling group '{group_name}'. "
                    "Please try again later."
                )
            elif error_code == "InvalidParameterCombination":
                logger.error(
                    f"The combination of parameters provided for enabling metrics on '{group_name}' is not valid. "
                    "Please check the parameters and try again."
                )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[EnableMetricsCollection](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/EnableMetricsCollection)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_python_3_topic"></a>

次のコード例は、`SetDesiredCapacity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def set_desired_capacity(self, group_name: str, capacity: int) -> None:
        """
        Sets the desired capacity of the group. Amazon EC2 Auto Scaling tries to keep the
        number of running instances equal to the desired capacity.

        :param group_name: The name of the group to update.
        :param capacity: The desired number of running instances.
        :return: None
        :raises ClientError: If there is an error setting the desired capacity.
        """
        try:
            self.autoscaling_client.set_desired_capacity(
                AutoScalingGroupName=group_name,
                DesiredCapacity=capacity,
                HonorCooldown=False,
            )
            logger.info(
                f"Successfully set desired capacity of {capacity} for Auto Scaling group '{group_name}'."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(
                f"Failed to set desired capacity for Auto Scaling group '{group_name}'."
            )
            if error_code == "ScalingActivityInProgress":
                logger.error(
                    f"A scaling activity is currently in progress for the Auto Scaling group '{group_name}'. "
                    "Please wait for the activity to complete before attempting to set the desired capacity."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SetDesiredCapacity](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/SetDesiredCapacity)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_python_3_topic"></a>

次のコード例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def terminate_instance(
        self, instance_id: str, decrease_capacity: bool
    ) -> Dict[str, Any]:
        """
        Stops an instance.

        :param instance_id: The ID of the instance to stop.
        :param decrease_capacity: Specifies whether to decrease the desired capacity
                                  of the group. When passing True for this parameter,
                                  you can stop an instance without having a replacement
                                  instance start when the desired capacity threshold is
                                  crossed.
        :return: A dictionary containing details of the scaling activity that occurs
                 in response to this action.
        :raises ClientError: If there is an error terminating the instance.
        """
        try:
            response = self.autoscaling_client.terminate_instance_in_auto_scaling_group(
                InstanceId=instance_id, ShouldDecrementDesiredCapacity=decrease_capacity
            )
            logger.info(f"Successfully terminated instance {instance_id}.")
            return response["Activity"]

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to terminate instance {instance_id}.")
            if error_code == "ScalingActivityInProgress":
                logger.error(
                    "A scaling activity is currently in progress for the Auto Scaling group "
                    f"associated with instance '{instance_id}'. "
                    "Please wait for the activity to complete before attempting to terminate the instance."
                )
            elif error_code == "ResourceInUse":
                logger.error(
                    f"The instance '{instance_id}' or an associated resource is currently in use "
                    "and cannot be terminated. "
                    "Ensure the instance is not involved in any ongoing processes and try again."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」**の「[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_python_3_topic"></a>

次のコード例は、`UpdateAutoScalingGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """Encapsulates Amazon EC2 Auto Scaling actions."""

    def __init__(self, autoscaling_client):
        """
        :param autoscaling_client: A Boto3 Amazon EC2 Auto Scaling client.
        """
        self.autoscaling_client = autoscaling_client


    def update_group(self, group_name: str, **kwargs: Any) -> None:
        """
        Updates an Auto Scaling group.

        :param group_name: The name of the group to update.
        :param kwargs: Keyword arguments to pass through to the service.
        :return: None
        :raises ClientError: If there is an error updating the Auto Scaling group.
        """
        try:
            self.autoscaling_client.update_auto_scaling_group(
                AutoScalingGroupName=group_name, **kwargs
            )
            logger.info(f"Successfully updated Auto Scaling group {group_name}.")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            logger.error(f"Failed to update Auto Scaling group {group_name}.")
            if error_code == "ResourceInUse":
                logger.error(
                    "The Auto Scaling group '%s' is currently in use and cannot be modified. Please try again later.",
                    group_name,
                )
            elif error_code == "ScalingActivityInProgress":
                logger.error(
                    f"A scaling activity is currently in progress for the Auto Scaling group '{group_name}'."
                    "Please wait for the activity to complete before attempting to update the group."
                )
            logger.error(f"Full error:\n\t{err}")
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_python_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class Runner:
    """
    Manages the deployment, demonstration, and destruction of resources for the resilient service.
    """

    def __init__(
        self,
        resource_path: str,
        recommendation: RecommendationService,
        autoscaler: AutoScalingWrapper,
        loadbalancer: ElasticLoadBalancerWrapper,
        param_helper: ParameterHelper,
    ):
        """
        Initializes the Runner class with the necessary parameters.

        :param resource_path: The path to resource files used by this example, such as IAM policies and instance scripts.
        :param recommendation: An instance of the RecommendationService class.
        :param autoscaler: An instance of the AutoScaler class.
        :param loadbalancer: An instance of the LoadBalancer class.
        :param param_helper: An instance of the ParameterHelper class.
        """
        self.resource_path = resource_path
        self.recommendation = recommendation
        self.autoscaler = autoscaler
        self.loadbalancer = loadbalancer
        self.param_helper = param_helper
        self.protocol = "HTTP"
        self.port = 80
        self.ssh_port = 22

        prefix = "doc-example-resilience"
        self.target_group_name = f"{prefix}-tg"
        self.load_balancer_name = f"{prefix}-lb"

    def deploy(self) -> None:
        """
        Deploys the resources required for the resilient service, including the DynamoDB table,
        EC2 instances, Auto Scaling group, and load balancer.
        """
        recommendations_path = f"{self.resource_path}/recommendations.json"
        startup_script = f"{self.resource_path}/server_startup_script.sh"
        instance_policy = f"{self.resource_path}/instance_policy.json"

        logging.info("Starting deployment of resources for the resilient service.")

        logging.info(
            "Creating and populating DynamoDB table '%s'.",
            self.recommendation.table_name,
        )
        self.recommendation.create()
        self.recommendation.populate(recommendations_path)

        logging.info(
            "Creating an EC2 launch template with the startup script '%s'.",
            startup_script,
        )
        self.autoscaler.create_template(startup_script, instance_policy)

        logging.info(
            "Creating an EC2 Auto Scaling group across multiple Availability Zones."
        )
        zones = self.autoscaler.create_autoscaling_group(3)

        logging.info("Creating variables that control the flow of the demo.")
        self.param_helper.reset()

        logging.info("Creating Elastic Load Balancing target group and load balancer.")

        vpc = self.autoscaler.get_default_vpc()
        subnets = self.autoscaler.get_subnets(vpc["VpcId"], zones)
        target_group = self.loadbalancer.create_target_group(
            self.target_group_name, self.protocol, self.port, vpc["VpcId"]
        )
        self.loadbalancer.create_load_balancer(
            self.load_balancer_name, [subnet["SubnetId"] for subnet in subnets]
        )
        self.loadbalancer.create_listener(self.load_balancer_name, target_group)

        self.autoscaler.attach_load_balancer_target_group(target_group)

        logging.info("Verifying access to the load balancer endpoint.")
        endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
        lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)
        current_ip_address = requests.get("http://checkip.amazonaws.com").text.strip()

        if not lb_success:
            logging.warning(
                "Couldn't connect to the load balancer. Verifying that the port is open..."
            )
            sec_group, port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.port, current_ip_address
            )
            sec_group, ssh_port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.ssh_port, current_ip_address
            )
            if not port_is_open:
                logging.warning(
                    "The default security group for your VPC must allow access from this computer."
                )
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound traffic on port {self.port} from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.port, current_ip_address
                    )
            if not ssh_port_is_open:
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound SSH traffic on port {self.ssh_port} for debugging from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.ssh_port, current_ip_address
                    )
            lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)

        if lb_success:
            logging.info(
                "Load balancer is ready. Access it at: http://%s", current_ip_address
            )
        else:
            logging.error(
                "Couldn't get a successful response from the load balancer endpoint. Please verify your VPC and security group settings."
            )

    def demo_choices(self) -> None:
        """
        Presents choices for interacting with the deployed service, such as sending requests to
        the load balancer or checking the health of the targets.
        """
        actions = [
            "Send a GET request to the load balancer endpoint.",
            "Check the health of load balancer targets.",
            "Go to the next part of the demo.",
        ]
        choice = 0
        while choice != 2:
            logging.info("Choose an action to interact with the service.")
            choice = q.choose("Which action would you like to take? ", actions)
            if choice == 0:
                logging.info("Sending a GET request to the load balancer endpoint.")
                endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
                logging.info("GET http://%s", endpoint)
                response = requests.get(f"http://{endpoint}")
                logging.info("Response: %s", response.status_code)
                if response.headers.get("content-type") == "application/json":
                    pp(response.json())
            elif choice == 1:
                logging.info("Checking the health of load balancer targets.")
                health = self.loadbalancer.check_target_health(self.target_group_name)
                for target in health:
                    state = target["TargetHealth"]["State"]
                    logging.info(
                        "Target %s on port %d is %s",
                        target["Target"]["Id"],
                        target["Target"]["Port"],
                        state,
                    )
                    if state != "healthy":
                        logging.warning(
                            "%s: %s",
                            target["TargetHealth"]["Reason"],
                            target["TargetHealth"]["Description"],
                        )
                logging.info(
                    "Note that it can take a minute or two for the health check to update."
                )
            elif choice == 2:
                logging.info("Proceeding to the next part of the demo.")

    def demo(self) -> None:
        """
        Runs the demonstration, showing how the service responds to different failure scenarios
        and how a resilient architecture can keep the service running.
        """
        ssm_only_policy = f"{self.resource_path}/ssm_only_policy.json"

        logging.info("Resetting parameters to starting values for the demo.")
        self.param_helper.reset()

        logging.info(
            "Starting demonstration of the service's resilience under various failure conditions."
        )
        self.demo_choices()

        logging.info(
            "Simulating failure by changing the Systems Manager parameter to a non-existent table."
        )
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info("Sending GET requests will now return failure codes.")
        self.demo_choices()

        logging.info("Switching to static response mode to mitigate failure.")
        self.param_helper.put(self.param_helper.failure_response, "static")
        logging.info("Sending GET requests will now return static responses.")
        self.demo_choices()

        logging.info("Restoring normal operation of the recommendation service.")
        self.param_helper.put(self.param_helper.table, self.recommendation.table_name)

        logging.info(
            "Introducing a failure by assigning bad credentials to one of the instances."
        )
        self.autoscaler.create_instance_profile(
            ssm_only_policy,
            self.autoscaler.bad_creds_policy_name,
            self.autoscaler.bad_creds_role_name,
            self.autoscaler.bad_creds_profile_name,
            ["AmazonSSMManagedInstanceCore"],
        )
        instances = self.autoscaler.get_instances()
        bad_instance_id = instances[0]
        instance_profile = self.autoscaler.get_instance_profile(bad_instance_id)
        logging.info(
            "Replacing instance profile with bad credentials for instance %s.",
            bad_instance_id,
        )
        self.autoscaler.replace_instance_profile(
            bad_instance_id,
            self.autoscaler.bad_creds_profile_name,
            instance_profile["AssociationId"],
        )
        logging.info(
            "Sending GET requests may return either a valid recommendation or a static response."
        )
        self.demo_choices()

        logging.info("Implementing deep health checks to detect unhealthy instances.")
        self.param_helper.put(self.param_helper.health_check, "deep")
        logging.info("Checking the health of the load balancer targets.")
        self.demo_choices()

        logging.info(
            "Terminating the unhealthy instance to let the auto scaler replace it."
        )
        self.autoscaler.terminate_instance(bad_instance_id)
        logging.info("The service remains resilient during instance replacement.")
        self.demo_choices()

        logging.info("Simulating a complete failure of the recommendation service.")
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info(
            "All instances will report as unhealthy, but the service will still return static responses."
        )
        self.demo_choices()
        self.param_helper.reset()

    def destroy(self, automation=False) -> None:
        """
        Destroys all resources created for the demo, including the load balancer, Auto Scaling group,
        EC2 instances, and DynamoDB table.
        """
        logging.info(
            "This concludes the demo. Preparing to clean up all AWS resources created during the demo."
        )
        if automation:
            cleanup = True
        else:
            cleanup = q.ask(
                "Do you want to clean up all demo resources? (y/n) ", q.is_yesno
            )

        if cleanup:
            logging.info("Deleting load balancer and related resources.")
            self.loadbalancer.delete_load_balancer(self.load_balancer_name)
            self.loadbalancer.delete_target_group(self.target_group_name)
            self.autoscaler.delete_autoscaling_group(self.autoscaler.group_name)
            self.autoscaler.delete_key_pair()
            self.autoscaler.delete_template()
            self.autoscaler.delete_instance_profile(
                self.autoscaler.bad_creds_profile_name,
                self.autoscaler.bad_creds_role_name,
            )
            logging.info("Deleting DynamoDB table and other resources.")
            self.recommendation.destroy()
        else:
            logging.warning(
                "Resources have not been deleted. Ensure you clean them up manually to avoid unexpected charges."
            )


def main() -> None:
    """
    Main function to parse arguments and run the appropriate actions for the demo.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--action",
        required=True,
        choices=["all", "deploy", "demo", "destroy"],
        help="The action to take for the demo. When 'all' is specified, resources are\n"
        "deployed, the demo is run, and resources are destroyed.",
    )
    parser.add_argument(
        "--resource_path",
        default="../../../scenarios/features/resilient_service/resources",
        help="The path to resource files used by this example, such as IAM policies and\n"
        "instance scripts.",
    )
    args = parser.parse_args()

    logging.info("Starting the Resilient Service demo.")

    prefix = "doc-example-resilience"

    # Service Clients
    ddb_client = boto3.client("dynamodb")
    elb_client = boto3.client("elbv2")
    autoscaling_client = boto3.client("autoscaling")
    ec2_client = boto3.client("ec2")
    ssm_client = boto3.client("ssm")
    iam_client = boto3.client("iam")

    # Wrapper instantiations
    recommendation = RecommendationService(
        "doc-example-recommendation-service", ddb_client
    )
    autoscaling_wrapper = AutoScalingWrapper(
        prefix,
        "t3.micro",
        "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
        autoscaling_client,
        ec2_client,
        ssm_client,
        iam_client,
    )
    elb_wrapper = ElasticLoadBalancerWrapper(elb_client)
    param_helper = ParameterHelper(recommendation.table_name, ssm_client)

    # Demo invocation
    runner = Runner(
        args.resource_path,
        recommendation,
        autoscaling_wrapper,
        elb_wrapper,
        param_helper,
    )
    actions = [args.action] if args.action != "all" else ["deploy", "demo", "destroy"]
    for action in actions:
        if action == "deploy":
            runner.deploy()
        elif action == "demo":
            runner.demo()
        elif action == "destroy":
            runner.destroy()

    logging.info("Demo completed successfully.")


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    main()
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_policy(self, policy_file: str, policy_name: str) -> str:
        """
        Creates a new IAM policy or retrieves the ARN of an existing policy.

        :param policy_file: The path to a JSON file that contains the policy definition.
        :param policy_name: The name to give the created policy.
        :return: The ARN of the created or existing policy.
        """
        with open(policy_file) as file:
            policy_doc = file.read()

        try:
            response = self.iam_client.create_policy(
                PolicyName=policy_name, PolicyDocument=policy_doc
            )
            policy_arn = response["Policy"]["Arn"]
            log.info(f"Policy '{policy_name}' created successfully. ARN: {policy_arn}")
            return policy_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the policy already exists, get its ARN
                response = self.iam_client.get_policy(
                    PolicyArn=f"arn:aws:iam::{self.account_id}:policy/{policy_name}"
                )
                policy_arn = response["Policy"]["Arn"]
                log.info(f"Policy '{policy_name}' already exists. ARN: {policy_arn}")
                return policy_arn
            log.error(f"Full error:\n\t{err}")

    def create_role(self, role_name: str, assume_role_doc: dict) -> str:
        """
        Creates a new IAM role or retrieves the ARN of an existing role.

        :param role_name: The name to give the created role.
        :param assume_role_doc: The assume role policy document that specifies which
                                entities can assume the role.
        :return: The ARN of the created or existing role.
        """
        try:
            response = self.iam_client.create_role(
                RoleName=role_name, AssumeRolePolicyDocument=json.dumps(assume_role_doc)
            )
            role_arn = response["Role"]["Arn"]
            log.info(f"Role '{role_name}' created successfully. ARN: {role_arn}")
            return role_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the role already exists, get its ARN
                response = self.iam_client.get_role(RoleName=role_name)
                role_arn = response["Role"]["Arn"]
                log.info(f"Role '{role_name}' already exists. ARN: {role_arn}")
                return role_arn
            log.error(f"Full error:\n\t{err}")

    def attach_policy(
        self,
        role_name: str,
        policy_arn: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> None:
        """
        Attaches an IAM policy to a role and optionally attaches additional AWS-managed policies.

        :param role_name: The name of the role to attach the policy to.
        :param policy_arn: The ARN of the policy to attach.
        :param aws_managed_policies: A tuple of AWS-managed policy names to attach to the role.
        """
        try:
            self.iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn)
            for aws_policy in aws_managed_policies:
                self.iam_client.attach_role_policy(
                    RoleName=role_name,
                    PolicyArn=f"arn:aws:iam::aws:policy/{aws_policy}",
                )
            log.info(f"Attached policy {policy_arn} to role {role_name}.")
        except ClientError as err:
            log.error(f"Failed to attach policy {policy_arn} to role {role_name}.")
            log.error(f"Full error:\n\t{err}")

    def create_instance_profile(
        self,
        policy_file: str,
        policy_name: str,
        role_name: str,
        profile_name: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> str:
        """
        Creates a policy, role, and profile that is associated with instances created by
        this class. An instance's associated profile defines a role that is assumed by the
        instance. The role has attached policies that specify the AWS permissions granted to
        clients that run on the instance.

        :param policy_file: The name of a JSON file that contains the policy definition to
                            create and attach to the role.
        :param policy_name: The name to give the created policy.
        :param role_name: The name to give the created role.
        :param profile_name: The name to the created profile.
        :param aws_managed_policies: Additional AWS-managed policies that are attached to
                                     the role, such as AmazonSSMManagedInstanceCore to grant
                                     use of Systems Manager to send commands to the instance.
        :return: The ARN of the profile that is created.
        """
        assume_role_doc = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"Service": "ec2.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        policy_arn = self.create_policy(policy_file, policy_name)
        self.create_role(role_name, assume_role_doc)
        self.attach_policy(role_name, policy_arn, aws_managed_policies)

        try:
            profile_response = self.iam_client.create_instance_profile(
                InstanceProfileName=profile_name
            )
            waiter = self.iam_client.get_waiter("instance_profile_exists")
            waiter.wait(InstanceProfileName=profile_name)
            time.sleep(10)  # wait a little longer
            profile_arn = profile_response["InstanceProfile"]["Arn"]
            self.iam_client.add_role_to_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            log.info("Created profile %s and added role %s.", profile_name, role_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                prof_response = self.iam_client.get_instance_profile(
                    InstanceProfileName=profile_name
                )
                profile_arn = prof_response["InstanceProfile"]["Arn"]
                log.info(
                    "Instance profile %s already exists, nothing to do.", profile_name
                )
            log.error(f"Full error:\n\t{err}")
        return profile_arn


    def get_instance_profile(self, instance_id: str) -> Dict[str, Any]:
        """
        Gets data about the profile associated with an instance.

        :param instance_id: The ID of the instance to look up.
        :return: The profile data.
        """
        try:
            response = self.ec2_client.describe_iam_instance_profile_associations(
                Filters=[{"Name": "instance-id", "Values": [instance_id]}]
            )
            if not response["IamInstanceProfileAssociations"]:
                log.info(f"No instance profile found for instance {instance_id}.")
            profile_data = response["IamInstanceProfileAssociations"][0]
            log.info(f"Retrieved instance profile for instance {instance_id}.")
            return profile_data
        except ClientError as err:
            log.error(
                f"Failed to retrieve instance profile for instance {instance_id}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                log.error(f"The instance ID '{instance_id}' does not exist.")
            log.error(f"Full error:\n\t{err}")


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_instance_profile(self, profile_name: str, role_name: str) -> None:
        """
        Detaches a role from an instance profile, detaches policies from the role,
        and deletes all the resources.

        :param profile_name: The name of the profile to delete.
        :param role_name: The name of the role to delete.
        """
        try:
            self.iam_client.remove_role_from_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            self.iam_client.delete_instance_profile(InstanceProfileName=profile_name)
            log.info("Deleted instance profile %s.", profile_name)
            attached_policies = self.iam_client.list_attached_role_policies(
                RoleName=role_name
            )
            for pol in attached_policies["AttachedPolicies"]:
                self.iam_client.detach_role_policy(
                    RoleName=role_name, PolicyArn=pol["PolicyArn"]
                )
                if not pol["PolicyArn"].startswith("arn:aws:iam::aws"):
                    self.iam_client.delete_policy(PolicyArn=pol["PolicyArn"])
                log.info("Detached and deleted policy %s.", pol["PolicyName"])
            self.iam_client.delete_role(RoleName=role_name)
            log.info("Deleted role %s.", role_name)
        except ClientError as err:
            log.error(
                f"Couldn't delete instance profile {profile_name} or detach "
                f"policies and delete role {role_name}: {err}"
            )
            if err.response["Error"]["Code"] == "NoSuchEntity":
                log.info(
                    "Instance profile %s doesn't exist, nothing to do.", profile_name
                )


    def create_key_pair(self, key_pair_name: str) -> None:
        """
        Creates a new key pair.

        :param key_pair_name: The name of the key pair to create.
        """
        try:
            response = self.ec2_client.create_key_pair(KeyName=key_pair_name)
            with open(f"{key_pair_name}.pem", "w") as file:
                file.write(response["KeyMaterial"])
            chmod(f"{key_pair_name}.pem", 0o600)
            log.info("Created key pair %s.", key_pair_name)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to create key pair {key_pair_name}.")
            if error_code == "InvalidKeyPair.Duplicate":
                log.error(f"A key pair with the name '{key_pair_name}' already exists.")
            log.error(f"Full error:\n\t{err}")


    def delete_key_pair(self) -> None:
        """
        Deletes a key pair.
        """
        try:
            self.ec2_client.delete_key_pair(KeyName=self.key_pair_name)
            remove(f"{self.key_pair_name}.pem")
            log.info("Deleted key pair %s.", self.key_pair_name)
        except ClientError as err:
            log.error(f"Couldn't delete key pair '{self.key_pair_name}'.")
            log.error(f"Full error:\n\t{err}")
        except FileNotFoundError as err:
            log.info("Key pair %s doesn't exist, nothing to do.", self.key_pair_name)
            log.error(f"Full error:\n\t{err}")


    def create_template(
        self, server_startup_script_file: str, instance_policy_file: str
    ) -> Dict[str, Any]:
        """
        Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. The
        launch template specifies a Bash script in its user data field that runs after
        the instance is started. This script installs Python packages and starts a
        Python web server on the instance.

        :param server_startup_script_file: The path to a Bash script file that is run
                                           when an instance starts.
        :param instance_policy_file: The path to a file that defines a permissions policy
                                     to create and attach to the instance profile.
        :return: Information about the newly created template.
        """
        template = {}
        try:
            # Create key pair and instance profile
            self.create_key_pair(self.key_pair_name)
            self.create_instance_profile(
                instance_policy_file,
                self.instance_policy_name,
                self.instance_role_name,
                self.instance_profile_name,
            )

            # Read the startup script
            with open(server_startup_script_file) as file:
                start_server_script = file.read()

            # Get the latest AMI ID
            ami_latest = self.ssm_client.get_parameter(Name=self.ami_param)
            ami_id = ami_latest["Parameter"]["Value"]

            # Create the launch template
            lt_response = self.ec2_client.create_launch_template(
                LaunchTemplateName=self.launch_template_name,
                LaunchTemplateData={
                    "InstanceType": self.inst_type,
                    "ImageId": ami_id,
                    "IamInstanceProfile": {"Name": self.instance_profile_name},
                    "UserData": base64.b64encode(
                        start_server_script.encode(encoding="utf-8")
                    ).decode(encoding="utf-8"),
                    "KeyName": self.key_pair_name,
                },
            )
            template = lt_response["LaunchTemplate"]
            log.info(
                f"Created launch template {self.launch_template_name} for AMI {ami_id} on {self.inst_type}."
            )
        except ClientError as err:
            log.error(f"Failed to create launch template {self.launch_template_name}.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidLaunchTemplateName.AlreadyExistsException":
                log.info(
                    f"Launch template {self.launch_template_name} already exists, nothing to do."
                )
            log.error(f"Full error:\n\t{err}")
        return template


    def delete_template(self):
        """
        Deletes a launch template.
        """
        try:
            self.ec2_client.delete_launch_template(
                LaunchTemplateName=self.launch_template_name
            )
            self.delete_instance_profile(
                self.instance_profile_name, self.instance_role_name
            )
            log.info("Launch template %s deleted.", self.launch_template_name)
        except ClientError as err:
            if (
                err.response["Error"]["Code"]
                == "InvalidLaunchTemplateName.NotFoundException"
            ):
                log.info(
                    "Launch template %s does not exist, nothing to do.",
                    self.launch_template_name,
                )
            log.error(f"Full error:\n\t{err}")


    def get_availability_zones(self) -> List[str]:
        """
        Gets a list of Availability Zones in the AWS Region of the Amazon EC2 client.

        :return: The list of Availability Zones for the client Region.
        """
        try:
            response = self.ec2_client.describe_availability_zones()
            zones = [zone["ZoneName"] for zone in response["AvailabilityZones"]]
            log.info(f"Retrieved {len(zones)} availability zones: {zones}.")
        except ClientError as err:
            log.error("Failed to retrieve availability zones.")
            log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def create_autoscaling_group(self, group_size: int) -> List[str]:
        """
        Creates an EC2 Auto Scaling group with the specified size.

        :param group_size: The number of instances to set for the minimum and maximum in
                           the group.
        :return: The list of Availability Zones specified for the group.
        """
        try:
            zones = self.get_availability_zones()
            self.autoscaling_client.create_auto_scaling_group(
                AutoScalingGroupName=self.group_name,
                AvailabilityZones=zones,
                LaunchTemplate={
                    "LaunchTemplateName": self.launch_template_name,
                    "Version": "$Default",
                },
                MinSize=group_size,
                MaxSize=group_size,
            )
            log.info(
                f"Created EC2 Auto Scaling group {self.group_name} with availability zones {zones}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            if error_code == "AlreadyExists":
                log.info(
                    f"EC2 Auto Scaling group {self.group_name} already exists, nothing to do."
                )
            else:
                log.error(f"Failed to create EC2 Auto Scaling group {self.group_name}.")
                log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def get_instances(self) -> List[str]:
        """
        Gets data about the instances in the EC2 Auto Scaling group.

        :return: A list of instance IDs in the Auto Scaling group.
        """
        try:
            as_response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[self.group_name]
            )
            instance_ids = [
                i["InstanceId"]
                for i in as_response["AutoScalingGroups"][0]["Instances"]
            ]
            log.info(
                f"Retrieved {len(instance_ids)} instances for Auto Scaling group {self.group_name}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to retrieve instances for Auto Scaling group {self.group_name}."
            )
            if error_code == "ResourceNotFound":
                log.error(f"The Auto Scaling group '{self.group_name}' does not exist.")
            log.error(f"Full error:\n\t{err}")
        else:
            return instance_ids


    def terminate_instance(self, instance_id: str, decrementsetting=False) -> None:
        """
        Terminates an instance in an EC2 Auto Scaling group. After an instance is
        terminated, it can no longer be accessed.

        :param instance_id: The ID of the instance to terminate.
        :param decrementsetting: If True, do not replace terminated instances.
        """
        try:
            self.autoscaling_client.terminate_instance_in_auto_scaling_group(
                InstanceId=instance_id,
                ShouldDecrementDesiredCapacity=decrementsetting,
            )
            log.info("Terminated instance %s.", instance_id)

            # Adding a waiter to ensure the instance is terminated
            waiter = self.ec2_client.get_waiter("instance_terminated")
            log.info("Waiting for instance %s to be terminated...", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info(
                f"Instance '{instance_id}' has been terminated and will be replaced."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to terminate instance '{instance_id}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to terminate the instance again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            log.error(f"Full error:\n\t{err}")

    def attach_load_balancer_target_group(
        self, lb_target_group: Dict[str, Any]
    ) -> None:
        """
        Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
        The target group specifies how the load balancer forwards requests to the instances
        in the group.

        :param lb_target_group: Data about the ELB target group to attach.
        """
        try:
            self.autoscaling_client.attach_load_balancer_target_groups(
                AutoScalingGroupName=self.group_name,
                TargetGroupARNs=[lb_target_group["TargetGroupArn"]],
            )
            log.info(
                "Attached load balancer target group %s to auto scaling group %s.",
                lb_target_group["TargetGroupName"],
                self.group_name,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to attach load balancer target group '{lb_target_group['TargetGroupName']}'."
            )
            if error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            elif error_code == "ServiceLinkedRoleFailure":
                log.error(
                    "The operation failed because the service-linked role is not ready or does not exist. "
                    "Check that the service-linked role exists and is correctly configured."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_autoscaling_group(self, group_name: str) -> None:
        """
        Terminates all instances in the group, then deletes the EC2 Auto Scaling group.

        :param group_name: The name of the group to delete.
        """
        try:
            response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[group_name]
            )
            groups = response.get("AutoScalingGroups", [])
            if len(groups) > 0:
                self.autoscaling_client.update_auto_scaling_group(
                    AutoScalingGroupName=group_name, MinSize=0
                )
                instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]]
                for inst_id in instance_ids:
                    self.terminate_instance(inst_id)

                # Wait for all instances to be terminated
                if instance_ids:
                    waiter = self.ec2_client.get_waiter("instance_terminated")
                    log.info("Waiting for all instances to be terminated...")
                    waiter.wait(InstanceIds=instance_ids)
                    log.info("All instances have been terminated.")
            else:
                log.info(f"No groups found named '{group_name}'! Nothing to do.")
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete Auto Scaling group '{group_name}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to delete the group again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_default_vpc(self) -> Dict[str, Any]:
        """
        Gets the default VPC for the account.

        :return: Data about the default VPC.
        """
        try:
            response = self.ec2_client.describe_vpcs(
                Filters=[{"Name": "is-default", "Values": ["true"]}]
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error("Failed to retrieve the default VPC.")
            if error_code == "UnauthorizedOperation":
                log.error(
                    "You do not have the necessary permissions to describe VPCs. "
                    "Ensure that your AWS IAM user or role has the correct permissions."
                )
            elif error_code == "InvalidParameterValue":
                log.error(
                    "One or more parameters are invalid. Check the request parameters."
                )

            log.error(f"Full error:\n\t{err}")
        else:
            if "Vpcs" in response and response["Vpcs"]:
                log.info(f"Retrieved default VPC: {response['Vpcs'][0]['VpcId']}")
                return response["Vpcs"][0]
            else:
                pass


    def verify_inbound_port(
        self, vpc: Dict[str, Any], port: int, ip_address: str
    ) -> Tuple[Dict[str, Any], bool]:
        """
        Verify the default security group of the specified VPC allows ingress from this
        computer. This can be done by allowing ingress from this computer's IP
        address. In some situations, such as connecting from a corporate network, you
        must instead specify a prefix list ID. You can also temporarily open the port to
        any IP address while running this example. If you do, be sure to remove public
        access when you're done.

        :param vpc: The VPC used by this example.
        :param port: The port to verify.
        :param ip_address: This computer's IP address.
        :return: The default security group of the specified VPC, and a value that indicates
                 whether the specified port is open.
        """
        try:
            response = self.ec2_client.describe_security_groups(
                Filters=[
                    {"Name": "group-name", "Values": ["default"]},
                    {"Name": "vpc-id", "Values": [vpc["VpcId"]]},
                ]
            )
            sec_group = response["SecurityGroups"][0]
            port_is_open = False
            log.info(f"Found default security group {sec_group['GroupId']}.")

            for ip_perm in sec_group["IpPermissions"]:
                if ip_perm.get("FromPort", 0) == port:
                    log.info(f"Found inbound rule: {ip_perm}")
                    for ip_range in ip_perm["IpRanges"]:
                        cidr = ip_range.get("CidrIp", "")
                        if cidr.startswith(ip_address) or cidr == "0.0.0.0/0":
                            port_is_open = True
                    if ip_perm["PrefixListIds"]:
                        port_is_open = True
                    if not port_is_open:
                        log.info(
                            f"The inbound rule does not appear to be open to either this computer's IP "
                            f"address of {ip_address}, to all IP addresses (0.0.0.0/0), or to a prefix list ID."
                        )
                    else:
                        break
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to verify inbound rule for port {port} for VPC {vpc['VpcId']}."
            )
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    f"The specified VPC ID '{vpc['VpcId']}' does not exist. Please check the VPC ID."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return sec_group, port_is_open


    def open_inbound_port(self, sec_group_id: str, port: int, ip_address: str) -> None:
        """
        Add an ingress rule to the specified security group that allows access on the
        specified port from the specified IP address.

        :param sec_group_id: The ID of the security group to modify.
        :param port: The port to open.
        :param ip_address: The IP address that is granted access.
        """
        try:
            self.ec2_client.authorize_security_group_ingress(
                GroupId=sec_group_id,
                CidrIp=f"{ip_address}/32",
                FromPort=port,
                ToPort=port,
                IpProtocol="tcp",
            )
            log.info(
                "Authorized ingress to %s on port %s from %s.",
                sec_group_id,
                port,
                ip_address,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to authorize ingress to security group '{sec_group_id}' on port {port} from {ip_address}."
            )
            if error_code == "InvalidGroupId.Malformed":
                log.error(
                    "The security group ID is malformed. "
                    "Please verify that the security group ID is correct."
                )
            elif error_code == "InvalidPermission.Duplicate":
                log.error(
                    "The specified rule already exists in the security group. "
                    "Check the existing rules for this security group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_subnets(self, vpc_id: str, zones: List[str] = None) -> List[Dict[str, Any]]:
        """
        Gets the default subnets in a VPC for a specified list of Availability Zones.

        :param vpc_id: The ID of the VPC to look up.
        :param zones: The list of Availability Zones to look up.
        :return: The list of subnets found.
        """
        # Ensure that 'zones' is a list, even if None is passed
        if zones is None:
            zones = []
        try:
            paginator = self.ec2_client.get_paginator("describe_subnets")
            page_iterator = paginator.paginate(
                Filters=[
                    {"Name": "vpc-id", "Values": [vpc_id]},
                    {"Name": "availability-zone", "Values": zones},
                    {"Name": "default-for-az", "Values": ["true"]},
                ]
            )

            subnets = []
            for page in page_iterator:
                subnets.extend(page["Subnets"])

            log.info("Found %s subnets for the specified zones.", len(subnets))
            return subnets
        except ClientError as err:
            log.error(
                f"Failed to retrieve subnets for VPC '{vpc_id}' in zones {zones}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    "The specified VPC ID does not exist. "
                    "Please check the VPC ID and try again."
                )
            # Add more error-specific handling as needed
            log.error(f"Full error:\n\t{err}")
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def create_target_group(
        self, target_group_name: str, protocol: str, port: int, vpc_id: str
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing target group. The target group specifies how
        the load balancer forwards requests to instances in the group and how instance
        health is checked.

        To speed up this demo, the health check is configured with shortened times and
        lower thresholds. In production, you might want to decrease the sensitivity of
        your health checks to avoid unwanted failures.

        :param target_group_name: The name of the target group to create.
        :param protocol: The protocol to use to forward requests, such as 'HTTP'.
        :param port: The port to use to forward requests, such as 80.
        :param vpc_id: The ID of the VPC in which the load balancer exists.
        :return: Data about the newly created target group.
        """
        try:
            response = self.elb_client.create_target_group(
                Name=target_group_name,
                Protocol=protocol,
                Port=port,
                HealthCheckPath="/healthcheck",
                HealthCheckIntervalSeconds=10,
                HealthCheckTimeoutSeconds=5,
                HealthyThresholdCount=2,
                UnhealthyThresholdCount=2,
                VpcId=vpc_id,
            )
            target_group = response["TargetGroups"][0]
            log.info(f"Created load balancing target group '{target_group_name}'.")
            return target_group
        except ClientError as err:
            log.error(
                f"Couldn't create load balancing target group '{target_group_name}'."
            )
            error_code = err.response["Error"]["Code"]

            if error_code == "DuplicateTargetGroupName":
                log.error(
                    f"Target group name {target_group_name} already exists. "
                    "Check if the target group already exists."
                    "Consider using a different name or deleting the existing target group if appropriate."
                )
            elif error_code == "TooManyTargetGroups":
                log.error(
                    "Too many target groups exist in the account. "
                    "Consider deleting unused target groups to create space for new ones."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_target_group(self, target_group_name) -> None:
        """
        Deletes the target group.
        """
        try:
            # Describe the target group to get its ARN
            response = self.elb_client.describe_target_groups(Names=[target_group_name])
            tg_arn = response["TargetGroups"][0]["TargetGroupArn"]

            # Delete the target group
            self.elb_client.delete_target_group(TargetGroupArn=tg_arn)
            log.info("Deleted load balancing target group %s.", target_group_name)

            # Use a custom waiter to wait until the target group is no longer available
            self.wait_for_target_group_deletion(self.elb_client, tg_arn)
            log.info("Target group %s successfully deleted.", target_group_name)

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete target group '{target_group_name}'.")
            if error_code == "TargetGroupNotFound":
                log.error(
                    "Load balancer target group either already deleted or never existed. "
                    "Verify the name and check that the resource exists in the AWS Console."
                )
            elif error_code == "ResourceInUseException":
                log.error(
                    "Target group still in use by another resource. "
                    "Ensure that the target group is no longer associated with any load balancers or resources.",
                )
            log.error(f"Full error:\n\t{err}")

    def wait_for_target_group_deletion(
        self, elb_client, target_group_arn, max_attempts=10, delay=30
    ):
        for attempt in range(max_attempts):
            try:
                elb_client.describe_target_groups(TargetGroupArns=[target_group_arn])
                print(
                    f"Attempt {attempt + 1}: Target group {target_group_arn} still exists."
                )
            except ClientError as e:
                if e.response["Error"]["Code"] == "TargetGroupNotFound":
                    print(
                        f"Target group {target_group_arn} has been successfully deleted."
                    )
                    return
                else:
                    raise
            time.sleep(delay)
        raise TimeoutError(
            f"Target group {target_group_arn} was not deleted after {max_attempts * delay} seconds."
        )


    def create_load_balancer(
        self,
        load_balancer_name: str,
        subnet_ids: List[str],
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing load balancer that uses the specified subnets
        and forwards requests to the specified target group.

        :param load_balancer_name: The name of the load balancer to create.
        :param subnet_ids: A list of subnets to associate with the load balancer.
        :return: Data about the newly created load balancer.
        """
        try:
            response = self.elb_client.create_load_balancer(
                Name=load_balancer_name, Subnets=subnet_ids
            )
            load_balancer = response["LoadBalancers"][0]
            log.info(f"Created load balancer '{load_balancer_name}'.")

            waiter = self.elb_client.get_waiter("load_balancer_available")
            log.info(
                f"Waiting for load balancer '{load_balancer_name}' to be available..."
            )
            waiter.wait(Names=[load_balancer_name])
            log.info(f"Load balancer '{load_balancer_name}' is now available!")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to create load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "DuplicateLoadBalancerNameException":
                log.error(
                    f"A load balancer with the name '{load_balancer_name}' already exists. "
                    "Load balancer names must be unique within the AWS region. "
                    "Please choose a different name and try again."
                )
            if error_code == "TooManyLoadBalancersException":
                log.error(
                    "The maximum number of load balancers has been reached in this account and region. "
                    "You can delete unused load balancers or request an increase in the service quota from AWS Support."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return load_balancer


    def create_listener(
        self,
        load_balancer_name: str,
        target_group: Dict[str, Any],
    ) -> Dict[str, Any]:
        """
        Creates a listener for the specified load balancer that forwards requests to the
        specified target group.

        :param load_balancer_name: The name of the load balancer to create a listener for.
        :param target_group: An existing target group that is added as a listener to the
                             load balancer.
        :return: Data about the newly created listener.
        """
        try:
            # Retrieve the load balancer ARN
            load_balancer_response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            load_balancer_arn = load_balancer_response["LoadBalancers"][0][
                "LoadBalancerArn"
            ]

            # Create the listener
            response = self.elb_client.create_listener(
                LoadBalancerArn=load_balancer_arn,
                Protocol=target_group["Protocol"],
                Port=target_group["Port"],
                DefaultActions=[
                    {
                        "Type": "forward",
                        "TargetGroupArn": target_group["TargetGroupArn"],
                    }
                ],
            )
            log.info(
                f"Created listener to forward traffic from load balancer '{load_balancer_name}' to target group '{target_group['TargetGroupName']}'."
            )
            return response["Listeners"][0]
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to add a listener on '{load_balancer_name}' for target group '{target_group['TargetGroupName']}'."
            )

            if error_code == "ListenerNotFoundException":
                log.error(
                    f"The listener could not be found for the load balancer '{load_balancer_name}'. "
                    "Please check the load balancer name and target group configuration."
                )
            if error_code == "InvalidConfigurationRequestException":
                log.error(
                    f"The configuration provided for the listener on load balancer '{load_balancer_name}' is invalid. "
                    "Please review the provided protocol, port, and target group settings."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_load_balancer(self, load_balancer_name) -> None:
        """
        Deletes a load balancer.

        :param load_balancer_name: The name of the load balancer to delete.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            lb_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
            self.elb_client.delete_load_balancer(LoadBalancerArn=lb_arn)
            log.info("Deleted load balancer %s.", load_balancer_name)
            waiter = self.elb_client.get_waiter("load_balancers_deleted")
            log.info("Waiting for load balancer to be deleted...")
            waiter.wait(Names=[load_balancer_name])
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Couldn't delete load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    f"The load balancer '{load_balancer_name}' does not exist. "
                    "Please check the name and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def get_endpoint(self, load_balancer_name) -> str:
        """
        Gets the HTTP endpoint of the load balancer.

        :return: The endpoint.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            return response["LoadBalancers"][0]["DNSName"]
        except ClientError as err:
            log.error(
                f"Couldn't get the endpoint for load balancer {load_balancer_name}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Verify load balancer name and ensure it exists in the AWS console."
                )
            log.error(f"Full error:\n\t{err}")

    @staticmethod
    def verify_load_balancer_endpoint(endpoint) -> bool:
        """
        Verify this computer can successfully send a GET request to the load balancer endpoint.

        :param endpoint: The endpoint to verify.
        :return: True if the GET request is successful, False otherwise.
        """
        retries = 3
        verified = False
        while not verified and retries > 0:
            try:
                lb_response = requests.get(f"http://{endpoint}")
                log.info(
                    "Got response %s from load balancer endpoint.",
                    lb_response.status_code,
                )
                if lb_response.status_code == 200:
                    verified = True
                else:
                    retries = 0
            except requests.exceptions.ConnectionError:
                log.info(
                    "Got connection error from load balancer endpoint, retrying..."
                )
                retries -= 1
                time.sleep(10)
        return verified

    def check_target_health(self, target_group_name: str) -> List[Dict[str, Any]]:
        """
        Checks the health of the instances in the target group.

        :return: The health status of the target group.
        """
        try:
            tg_response = self.elb_client.describe_target_groups(
                Names=[target_group_name]
            )
            health_response = self.elb_client.describe_target_health(
                TargetGroupArn=tg_response["TargetGroups"][0]["TargetGroupArn"]
            )
        except ClientError as err:
            log.error(f"Couldn't check health of {target_group_name} target(s).")
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Load balancer associated with the target group was not found. "
                    "Ensure the load balancer exists, is in the correct AWS region, and "
                    "that you have the necessary permissions to access it.",
                )
            elif error_code == "TargetGroupNotFoundException":
                log.error(
                    "Target group was not found. "
                    "Verify the target group name, check that it exists in the correct region, "
                    "and ensure it has not been deleted or created in a different account.",
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return health_response["TargetHealthDescriptions"]
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
class RecommendationService:
    """
    Encapsulates a DynamoDB table to use as a service that recommends books, movies,
    and songs.
    """

    def __init__(self, table_name: str, dynamodb_client: boto3.client):
        """
        Initializes the RecommendationService class with the necessary parameters.

        :param table_name: The name of the DynamoDB recommendations table.
        :param dynamodb_client: A Boto3 DynamoDB client.
        """
        self.table_name = table_name
        self.dynamodb_client = dynamodb_client

    def create(self) -> Dict[str, Any]:
        """
        Creates a DynamoDB table to use as a recommendation service. The table has a
        hash key named 'MediaType' that defines the type of media recommended, such as
        Book or Movie, and a range key named 'ItemId' that, combined with the MediaType,
        forms a unique identifier for the recommended item.

        :return: Data about the newly created table.
        :raises RecommendationServiceError: If the table creation fails.
        """
        try:
            response = self.dynamodb_client.create_table(
                TableName=self.table_name,
                AttributeDefinitions=[
                    {"AttributeName": "MediaType", "AttributeType": "S"},
                    {"AttributeName": "ItemId", "AttributeType": "N"},
                ],
                KeySchema=[
                    {"AttributeName": "MediaType", "KeyType": "HASH"},
                    {"AttributeName": "ItemId", "KeyType": "RANGE"},
                ],
                ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
            )
            log.info("Creating table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s created.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceInUseException":
                log.info("Table %s exists, nothing to be done.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when creating table: {err}."
                )
        else:
            return response

    def populate(self, data_file: str) -> None:
        """
        Populates the recommendations table from a JSON file.

        :param data_file: The path to the data file.
        :raises RecommendationServiceError: If the table population fails.
        """
        try:
            with open(data_file) as data:
                items = json.load(data)
            batch = [{"PutRequest": {"Item": item}} for item in items]
            self.dynamodb_client.batch_write_item(RequestItems={self.table_name: batch})
            log.info(
                "Populated table %s with items from %s.", self.table_name, data_file
            )
        except ClientError as err:
            raise RecommendationServiceError(
                self.table_name, f"Couldn't populate table from {data_file}: {err}"
            )

    def destroy(self) -> None:
        """
        Deletes the recommendations table.

        :raises RecommendationServiceError: If the table deletion fails.
        """
        try:
            self.dynamodb_client.delete_table(TableName=self.table_name)
            log.info("Deleting table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_not_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s deleted.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                log.info("Table %s does not exist, nothing to do.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when deleting table: {err}."
                )
```
Systems Manager のアクションをラップするクラスを作成します。  

```
class ParameterHelper:
    """
    Encapsulates Systems Manager parameters. This example uses these parameters to drive
    the demonstration of resilient architecture, such as failure of a dependency or
    how the service responds to a health check.
    """

    table: str = "doc-example-resilient-architecture-table"
    failure_response: str = "doc-example-resilient-architecture-failure-response"
    health_check: str = "doc-example-resilient-architecture-health-check"

    def __init__(self, table_name: str, ssm_client: boto3.client):
        """
        Initializes the ParameterHelper class with the necessary parameters.

        :param table_name: The name of the DynamoDB table that is used as a recommendation
                           service.
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.table_name = table_name

    def reset(self) -> None:
        """
        Resets the Systems Manager parameters to starting values for the demo.
        These are the name of the DynamoDB recommendation table, no response when a
        dependency fails, and shallow health checks.
        """
        self.put(self.table, self.table_name)
        self.put(self.failure_response, "none")
        self.put(self.health_check, "shallow")

    def put(self, name: str, value: str) -> None:
        """
        Sets the value of a named Systems Manager parameter.

        :param name: The name of the parameter.
        :param value: The new value of the parameter.
        :raises ParameterHelperError: If the parameter value cannot be set.
        """
        try:
            self.ssm_client.put_parameter(
                Name=name, Value=value, Overwrite=True, Type="String"
            )
            log.info("Setting parameter %s to '%s'.", name, value)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to set parameter {name}.")
            if error_code == "ParameterLimitExceeded":
                log.error(
                    "The parameter limit has been exceeded. "
                    "Consider deleting unused parameters or request a limit increase."
                )
            elif error_code == "ParameterAlreadyExists":
                log.error(
                    "The parameter already exists and overwrite is set to False. "
                    "Use Overwrite=True to update the parameter."
                )
            log.error(f"Full error:\n\t{err}")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# SDK for Python (Boto3) を使用する Amazon Bedrock の例
<a name="python_3_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Bedrock
<a name="bedrock_Hello_python_3_topic"></a>

次のコード例は、Amazon Bedrock の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。

```
"""
Lists the available Amazon Bedrock models.
"""
import logging
import json
import boto3


from botocore.exceptions import ClientError


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def list_foundation_models(bedrock_client):
    """
    Gets a list of available Amazon Bedrock foundation models.

    :return: The list of available bedrock foundation models.
    """

    try:
        response = bedrock_client.list_foundation_models()
        models = response["modelSummaries"]
        logger.info("Got %s foundation models.", len(models))
        return models

    except ClientError:
        logger.error("Couldn't list foundation models.")
        raise


def main():
    """Entry point for the example. Uses the AWS SDK for Python (Boto3)
    to create an Amazon Bedrock client. Then lists the available Bedrock models
    in the region set in the callers profile and credentials.
    """

    bedrock_client = boto3.client(service_name="bedrock")

    fm_models = list_foundation_models(bedrock_client)
    for model in fm_models:
        print(f"Model: {model['modelName']}")
        print(json.dumps(model, indent=2))
        print("---------------------------\n")

    logger.info("Done.")


if __name__ == "__main__":
    main()
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListFoundationModels](https://docs.aws.amazon.com/goto/boto3/bedrock-2023-04-20/ListFoundationModels)」を参照してください。

## アクション
<a name="actions"></a>

### `GetFoundationModel`
<a name="bedrock_GetFoundationModel_python_3_topic"></a>

次のコード例は、`GetFoundationModel` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。
基盤モデルに関する詳細を取得します。  

```
    def get_foundation_model(self, model_identifier):
        """
        Get details about an Amazon Bedrock foundation model.

        :return: The foundation model's details.
        """

        try:
            return self.bedrock_client.get_foundation_model(
                modelIdentifier=model_identifier
            )["modelDetails"]
        except ClientError:
            logger.error(
                f"Couldn't get foundation models details for {model_identifier}"
            )
            raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetFoundationModel](https://docs.aws.amazon.com/goto/boto3/bedrock-2023-04-20/GetFoundationModel)」を参照してください。**

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_python_3_topic"></a>

次のコード例は、`ListFoundationModels` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。
利用可能な Amazon Bedrock 基盤モデルを一覧表示します。  

```
    def list_foundation_models(self):
        """
        List the available Amazon Bedrock foundation models.

        :return: The list of available bedrock foundation models.
        """

        try:
            response = self.bedrock_client.list_foundation_models()
            models = response["modelSummaries"]
            logger.info("Got %s foundation models.", len(models))
            return models

        except ClientError:
            logger.error("Couldn't list foundation models.")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListFoundationModels](https://docs.aws.amazon.com/goto/boto3/bedrock-2023-04-20/ListFoundationModels)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Step Functions を使用して生成 AI アプリケーションをオーケストレーションする
<a name="cross_ServerlessPromptChaining_python_3_topic"></a>

次のコード例は、Amazon Bedrock と Step Functions を使用して生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Bedrock Serverless のプロンプトチェイニングシナリオは、[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)、[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)、および [https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) を使用して、複雑でサーバーレス、高度にスケーラブルな生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。これには、次の実際の例が含まれています。  
+  文学ブログの特定の小説の分析を行う。この例では、プロンプトのシンプルでシーケンシャルなチェーンを示しています。
+  特定のトピックに関する短いストーリーを生成する。この例では、AI が以前に生成した項目のリストを繰り返し処理する方法を示しています。
+  特定の目的地への週末の旅程を作成する。この例では、複数の個別のプロンプトを並列化する方法を示しています。
+  映画のプロデューサーに映画のアイデアを提案する。この例では、異なる推論パラメータを使用して同じプロンプトを並列化する方法、チェーン内の前のステップにバックトラックする方法、ワークフローの一部として人間の入力を含める方法を示しています。
+  ユーザーの手元にある材料に基づいて料理を計画する。この例では、プロンプトチェーンが 2 つの異なる AI 会話を組み込んで、2 つの AI ペルソナが相互に議論を行い、最終的な結果を改善する方法を示しています。
+  当日中で最も人気のある GitHub リポジトリを検索して要約する。この例では、外部 API とやり取りする複数の AI エージェントをチェーンさせる方法を示しています。
 完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/aws-samples/amazon-bedrock-serverless-prompt-chaining) で完全なプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock
+ Amazon Bedrock ランタイム
+ Amazon Bedrock エージェント
+ Amazon Bedrock エージェントランタイム
+ ステップ関数

# SDK for Python (Boto3) を使用する Amazon Bedrock ランタイムの例
<a name="python_3_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイム AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)
+ [Amazon Nova](#amazon_nova)
+ [Amazon Nova Canvas](#amazon_nova_canvas)
+ [Amazon Nova Reel](#amazon_nova_reel)
+ [Amazon Titan Image Generator](#amazon_titan_image_generator)
+ [Amazon Titan Text](#amazon_titan_text)
+ [Amazon Titan Text Embeddings](#amazon_titan_text_embeddings)
+ [Anthropic Claude](#anthropic_claude)
+ [Cohere Command](#cohere_command)
+ [DeepSeek](#deepseek)
+ [Meta Llama](#meta_llama)
+ [Mistral AI](#mistral_ai)
+ [Stable Diffusion](#stable_diffusion)

## シナリオ
<a name="scenarios"></a>

### Amazon Bedrock 基盤モデルとやりとりするためのプレイグラウンドアプリケーションを作成します。
<a name="cross_FMPlayground_python_3_topic"></a>

次のコード例は、さまざまな方法で Amazon Bedrock 基盤モデルと相互作用するプレイグラウンドを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Python 基盤モデル (FM) プレイグラウンドは Python/FastAPI のサンプルアプリケーションで、Python で Amazon Bedrock を使用する方法を紹介しています。この例は、Python 開発者が Amazon Bedrock を使用して生成 AI 対応アプリケーションを構築する方法を示しています。次の 3 つのプレイグラウンドを使用して Amazon Bedrock 基盤モデルをテストしたり操作したりできます。  
+ テキストプレイグラウンド。
+ チャットプレイグラウンド。
+ イメージプレイグラウンド。
この例には、アクセスできる基盤モデルとその特性が一覧表示されています。ソースコードとデプロイ手順については、[GitHub](https://github.com/build-on-aws/python-fm-playground) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock ランタイム

### マネージドプロンプトを作成して呼び出す
<a name="bedrock-agent_GettingStartedWithBedrockPrompts_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ マネージドプロンプトを作成する。
+ プロンプトのバージョンを作成する。
+ バージョンを使用してプロンプトを呼び出す。
+ リソースをクリーンアップする (オプション)。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
マネージドプロンプトを作成して呼び出します。  

```
import argparse
import boto3
import logging
import time

# Now import the modules
from prompt import create_prompt, create_prompt_version, delete_prompt
from run_prompt import invoke_prompt

logging.basicConfig(
    level=logging.INFO,
    format='%(levelname)s: %(message)s'
)
logger = logging.getLogger(__name__)



def run_scenario(bedrock_client, bedrock_runtime_client, model_id, cleanup=True):
    """
    Runs the Amazon Bedrock managed prompt scenario.
    
    Args:
        bedrock_client: The Amazon Bedrock Agent client.
        bedrock_runtime_client: The Amazon Bedrock Runtime client.
        model_id (str): The model ID to use for the prompt.
        cleanup (bool): Whether to clean up resources at the end of the scenario.
        
    Returns:
        dict: A dictionary containing the created resources.
    """
    prompt_id = None
    
    try:
        # Step 1: Create a prompt
        print("\n=== Step 1: Creating a prompt ===")
        prompt_name = f"PlaylistGenerator-{int(time.time())}"
        prompt_description = "Playlist generator"
        prompt_template = """
          Make me a {{genre}} playlist consisting of the following number of songs: {{number}}."""
        
        create_response = create_prompt(
            bedrock_client,
            prompt_name,
            prompt_description,
            prompt_template,
            model_id
        )
        
        prompt_id = create_response['id']
        print(f"Created prompt: {prompt_name} with ID: {prompt_id}")
        
        # Create a version of the prompt
        print("\n=== Creating a version of the prompt ===")
        version_response = create_prompt_version(
            bedrock_client,
            prompt_id,
            description="Initial version of the product description generator"
        )
        
        prompt_version_arn = version_response['arn']
        prompt_version = version_response['version']

        print(f"Created prompt version: {prompt_version}")
        print(f"Prompt version ARN: {prompt_version_arn}")
        
        # Step 2: Invoke the prompt directly
        print("\n=== Step 2: Invoking the prompt ===")
        input_variables = {
            "genre": "pop",
            "number": "2",
           }
        
        # Use the ARN from the create_prompt_version response
        result = invoke_prompt(
            bedrock_runtime_client,
            prompt_version_arn,  
            input_variables
        )
        # Display the playlist
        print(f"\n{result}")
    
        
        # Step 3: Clean up resources (optional)
        if cleanup:
            print("\n=== Step 3: Cleaning up resources ===")
            
            # Delete the prompt
            print(f"Deleting prompt {prompt_id}...")
            delete_prompt(bedrock_client, prompt_id)
            
            print("Cleanup complete")
        else:
            print("\n=== Resources were not cleaned up ===")
            print(f"Prompt ID: {prompt_id}")
        
   
        
    except Exception as e:
        logger.exception("Error in scenario: %s", str(e))
        
        # Attempt to clean up if an error occurred and cleanup was requested
        if cleanup and prompt_id:
            try:
                print("\nCleaning up resources after error...")
                
                # Delete the prompt
                try:
                    delete_prompt(bedrock_client, prompt_id)
                    print("Cleanup after error complete")
                except Exception as cleanup_error:
                    logger.error("Error during cleanup: %s", str(cleanup_error))
            except Exception as final_error:
                logger.error("Final error during cleanup: %s", str(final_error))
        
        # Re-raise the original exception
        raise

def main():
    """
    Entry point for the Amazon Bedrock managed prompt scenario.
    """
    parser = argparse.ArgumentParser(
        description="Run the Amazon Bedrock managed prompt scenario."
    )
    parser.add_argument(
        '--region',
        default='us-east-1',
        help="The AWS Region to use."
    )
    parser.add_argument(
        '--model-id',
        default='anthropic.claude-v2',
        help="The model ID to use for the prompt."
    )
    parser.add_argument(
        '--cleanup',
        action='store_true',
        default=True,
        help="Clean up resources at the end of the scenario."
    )
    parser.add_argument(
        '--no-cleanup',
        action='store_false',
        dest='cleanup',
        help="Don't clean up resources at the end of the scenario."
    )
    args = parser.parse_args()

    bedrock_client = boto3.client('bedrock-agent', region_name=args.region)
    bedrock_runtime_client = boto3.client('bedrock-runtime', region_name=args.region)
    
    print("=== Amazon Bedrock Managed Prompt Scenario ===")
    print(f"Region: {args.region}")
    print(f"Model ID: {args.model_id}")
    print(f"Cleanup resources: {args.cleanup}")
    
    try:
        run_scenario(
            bedrock_client,
            bedrock_runtime_client,
            args.model_id,
            args.cleanup
        )
        
    except Exception as e:
        logger.exception("Error running scenario: %s", str(e))
        
if __name__ == "__main__":
    main()
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)
  + [CreatePrompt](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreatePrompt)
  + [CreatePromptVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreatePromptVersion)
  + [DeletePrompt](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeletePrompt)

### Step Functions を使用して生成 AI アプリケーションをオーケストレーションする
<a name="cross_ServerlessPromptChaining_python_3_topic"></a>

次のコード例は、Amazon Bedrock と Step Functions を使用して生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Bedrock Serverless のプロンプトチェイニングシナリオは、[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)、[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)、および [https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) を使用して、複雑でサーバーレス、高度にスケーラブルな生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。これには、次の実際の例が含まれています。  
+  文学ブログの特定の小説の分析を行う。この例では、プロンプトのシンプルでシーケンシャルなチェーンを示しています。
+  特定のトピックに関する短いストーリーを生成する。この例では、AI が以前に生成した項目のリストを繰り返し処理する方法を示しています。
+  特定の目的地への週末の旅程を作成する。この例では、複数の個別のプロンプトを並列化する方法を示しています。
+  映画のプロデューサーに映画のアイデアを提案する。この例では、異なる推論パラメータを使用して同じプロンプトを並列化する方法、チェーン内の前のステップにバックトラックする方法、ワークフローの一部として人間の入力を含める方法を示しています。
+  ユーザーの手元にある材料に基づいて料理を計画する。この例では、プロンプトチェーンが 2 つの異なる AI 会話を組み込んで、2 つの AI ペルソナが相互に議論を行い、最終的な結果を改善する方法を示しています。
+  当日中で最も人気のある GitHub リポジトリを検索して要約する。この例では、外部 API とやり取りする複数の AI エージェントをチェーンさせる方法を示しています。
 完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/aws-samples/amazon-bedrock-serverless-prompt-chaining) で完全なプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock
+ Amazon Bedrock ランタイム
+ Amazon Bedrock エージェント
+ Amazon Bedrock エージェントランタイム
+ ステップ関数

### Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUse_python_3_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
デモのプライマリ実行スクリプト。このスクリプトは、ユーザー、Amazon Bedrock Converse API、および気象ツール間の会話を調整します。  

```
"""
This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user
input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.
"""

import boto3
import logging
from enum import Enum

import utils.tool_use_print_utils as output
import weather_tool

logging.basicConfig(level=logging.INFO, format="%(message)s")

AWS_REGION = "us-east-1"


# For the most recent list of models supported by the Converse API's tool use functionality, visit:
# https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html
class SupportedModels(Enum):
    CLAUDE_OPUS = "anthropic.claude-3-opus-20240229-v1:0"
    CLAUDE_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0"
    CLAUDE_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0"
    COHERE_COMMAND_R = "cohere.command-r-v1:0"
    COHERE_COMMAND_R_PLUS = "cohere.command-r-plus-v1:0"


# Set the model ID, e.g., Claude 3 Haiku.
MODEL_ID = SupportedModels.CLAUDE_HAIKU.value

SYSTEM_PROMPT = """
You are a weather assistant that provides current weather data for user-specified locations using only
the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
If the user provides coordinates, infer the approximate location and refer to it in your response.
To use the tool, you strictly apply the provided tool specification.

- Explain your step-by-step process, and give brief updates before each step.
- Only use the Weather_Tool for data. Never guess or make up information. 
- Repeat the tool use for subsequent requests if necessary.
- If the tool errors, apologize, explain weather is unavailable, and suggest other options.
- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
  emojis where appropriate.
- Only respond to weather queries. Remind off-topic users of your purpose. 
- Never claim to search online, access external data, or use tools besides Weather_Tool.
- Complete the entire process until you have all required data before sending the complete response.
"""

# The maximum number of recursive calls allowed in the tool_use_demo function.
# This helps prevent infinite loops and potential performance issues.
MAX_RECURSIONS = 5


class ToolUseDemo:
    """
    Demonstrates the tool use feature with the Amazon Bedrock Converse API.
    """

    def __init__(self):
        # Prepare the system prompt
        self.system_prompt = [{"text": SYSTEM_PROMPT}]

        # Prepare the tool configuration with the weather tool's specification
        self.tool_config = {"tools": [weather_tool.get_tool_spec()]}

        # Create a Bedrock Runtime client in the specified AWS Region.
        self.bedrockRuntimeClient = boto3.client(
            "bedrock-runtime", region_name=AWS_REGION
        )

    def run(self):
        """
        Starts the conversation with the user and handles the interaction with Bedrock.
        """
        # Print the greeting and a short user guide
        output.header()

        # Start with an emtpy conversation
        conversation = []

        # Get the first user input
        user_input = self._get_user_input()

        while user_input is not None:
            # Create a new message with the user input and append it to the conversation
            message = {"role": "user", "content": [{"text": user_input}]}
            conversation.append(message)

            # Send the conversation to Amazon Bedrock
            bedrock_response = self._send_conversation_to_bedrock(conversation)

            # Recursively handle the model's response until the model has returned
            # its final response or the recursion counter has reached 0
            self._process_model_response(
                bedrock_response, conversation, max_recursion=MAX_RECURSIONS
            )

            # Repeat the loop until the user decides to exit the application
            user_input = self._get_user_input()

        output.footer()

    def _send_conversation_to_bedrock(self, conversation):
        """
        Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response.

        :param conversation: The conversation history including the next message to send.
        :return: The response from Amazon Bedrock.
        """
        output.call_to_bedrock(conversation)

        # Send the conversation, system prompt, and tool configuration, and return the response
        return self.bedrockRuntimeClient.converse(
            modelId=MODEL_ID,
            messages=conversation,
            system=self.system_prompt,
            toolConfig=self.tool_config,
        )

    def _process_model_response(
        self, model_response, conversation, max_recursion=MAX_RECURSIONS
    ):
        """
        Processes the response received via Amazon Bedrock and performs the necessary actions
        based on the stop reason.

        :param model_response: The model's response returned via Amazon Bedrock.
        :param conversation: The conversation history.
        :param max_recursion: The maximum number of recursive calls allowed.
        """

        if max_recursion <= 0:
            # Stop the process, the number of recursive calls could indicate an infinite loop
            logging.warning(
                "Warning: Maximum number of recursions reached. Please try again."
            )
            exit(1)

        # Append the model's response to the ongoing conversation
        message = model_response["output"]["message"]
        conversation.append(message)

        if model_response["stopReason"] == "tool_use":
            # If the stop reason is "tool_use", forward everything to the tool use handler
            self._handle_tool_use(message, conversation, max_recursion)

        if model_response["stopReason"] == "end_turn":
            # If the stop reason is "end_turn", print the model's response text, and finish the process
            output.model_response(message["content"][0]["text"])
            return

    def _handle_tool_use(
        self, model_response, conversation, max_recursion=MAX_RECURSIONS
    ):
        """
        Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock.
        The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing.

        :param model_response: The model's response containing the tool use request.
        :param conversation: The conversation history.
        :param max_recursion: The maximum number of recursive calls allowed.
        """

        # Initialize an empty list of tool results
        tool_results = []

        # The model's response can consist of multiple content blocks
        for content_block in model_response["content"]:
            if "text" in content_block:
                # If the content block contains text, print it to the console
                output.model_response(content_block["text"])

            if "toolUse" in content_block:
                # If the content block is a tool use request, forward it to the tool
                tool_response = self._invoke_tool(content_block["toolUse"])

                # Add the tool use ID and the tool's response to the list of results
                tool_results.append(
                    {
                        "toolResult": {
                            "toolUseId": (tool_response["toolUseId"]),
                            "content": [{"json": tool_response["content"]}],
                        }
                    }
                )

        # Embed the tool results in a new user message
        message = {"role": "user", "content": tool_results}

        # Append the new message to the ongoing conversation
        conversation.append(message)

        # Send the conversation to Amazon Bedrock
        response = self._send_conversation_to_bedrock(conversation)

        # Recursively handle the model's response until the model has returned
        # its final response or the recursion counter has reached 0
        self._process_model_response(response, conversation, max_recursion - 1)

    def _invoke_tool(self, payload):
        """
        Invokes the specified tool with the given payload and returns the tool's response.
        If the requested tool does not exist, an error message is returned.

        :param payload: The payload containing the tool name and input data.
        :return: The tool's response or an error message.
        """
        tool_name = payload["name"]

        if tool_name == "Weather_Tool":
            input_data = payload["input"]
            output.tool_use(tool_name, input_data)

            # Invoke the weather tool with the input data provided by
            response = weather_tool.fetch_weather_data(input_data)
        else:
            error_message = (
                f"The requested tool with name '{tool_name}' does not exist."
            )
            response = {"error": "true", "message": error_message}

        return {"toolUseId": payload["toolUseId"], "content": response}

    @staticmethod
    def _get_user_input(prompt="Your weather info request"):
        """
        Prompts the user for input and returns the user's response.
        Returns None if the user enters 'x' to exit.

        :param prompt: The prompt to display to the user.
        :return: The user's input or None if the user chooses to exit.
        """
        output.separator()
        user_input = input(f"{prompt} (x to exit): ")

        if user_input == "":
            prompt = "Please enter your weather info request, e.g. the name of a city"
            return ToolUseDemo._get_user_input(prompt)

        elif user_input.lower() == "x":
            return None

        else:
            return user_input


if __name__ == "__main__":
    tool_use_demo = ToolUseDemo()
    tool_use_demo.run()
```
デモで使用される気象ツール。このスクリプトは、ツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
import requests
from requests.exceptions import RequestException


def get_tool_spec():
    """
    Returns the JSON Schema specification for the Weather tool. The tool specification
    defines the input schema and describes the tool's functionality.
    For more information, see https://json-schema.org/understanding-json-schema/reference.

    :return: The tool specification for the Weather tool.
    """
    return {
        "toolSpec": {
            "name": "Weather_Tool",
            "description": "Get the current weather for a given location, based on its WGS84 coordinates.",
            "inputSchema": {
                "json": {
                    "type": "object",
                    "properties": {
                        "latitude": {
                            "type": "string",
                            "description": "Geographical WGS84 latitude of the location.",
                        },
                        "longitude": {
                            "type": "string",
                            "description": "Geographical WGS84 longitude of the location.",
                        },
                    },
                    "required": ["latitude", "longitude"],
                }
            },
        }
    }


def fetch_weather_data(input_data):
    """
    Fetches weather data for the given latitude and longitude using the Open-Meteo API.
    Returns the weather data or an error message if the request fails.

    :param input_data: The input data containing the latitude and longitude.
    :return: The weather data or an error message.
    """
    endpoint = "https://api.open-meteo.com/v1/forecast"
    latitude = input_data.get("latitude")
    longitude = input_data.get("longitude", "")
    params = {"latitude": latitude, "longitude": longitude, "current_weather": True}

    try:
        response = requests.get(endpoint, params=params)
        weather_data = {"weather_data": response.json()}
        response.raise_for_status()
        return weather_data
    except RequestException as e:
        return e.response.json()
    except Exception as e:
        return {"error": type(e), "message": str(e)}
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Amazon Nova
<a name="amazon_nova"></a>

### Converse
<a name="bedrock-runtime_Converse_AmazonNovaText_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
# Use the Conversation API to send a text message to Amazon Nova.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Amazon Nova Lite.
model_id = "amazon.nova-lite-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AmazonNovaText_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the Conversation API to send a text message to Amazon Nova Text
# and print the response stream.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Amazon Nova Lite.
model_id = "amazon.nova-lite-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    streaming_response = client.converse_stream(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the streamed response text in real-time.
    for chunk in streaming_response["stream"]:
        if "contentBlockDelta" in chunk:
            text = chunk["contentBlockDelta"]["delta"]["text"]
            print(text, end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### ドキュメント理解
<a name="bedrock-runtime_DocumentUnderstanding_AmazonNova_python_3_topic"></a>

次のコード例は、Amazon Bedrock で Amazon Nova を使用してドキュメントを送信および処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で Amazon Nova を使用してドキュメントを送信して処理します。  

```
# Send and process a document with Amazon Nova on Amazon Bedrock.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g. Amazon Nova Lite.
model_id = "amazon.nova-lite-v1:0"

# Load the document
with open("example-data/amazon-nova-service-cards.pdf", "rb") as file:
    document_bytes = file.read()

# Start a conversation with a user message and the document
conversation = [
    {
        "role": "user",
        "content": [
            {"text": "Briefly compare the models described in this document"},
            {
                "document": {
                    # Available formats: html, md, pdf, doc/docx, xls/xlsx, csv, and txt
                    "format": "pdf",
                    "name": "Amazon Nova Service Cards",
                    "source": {"bytes": document_bytes},
                }
            },
        ],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 500, "temperature": 0.3},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Amazon Nova Canvas
<a name="amazon_nova_canvas"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AmazonNovaImageGeneration_python_3_topic"></a>

以下のコード例は、Amazon Bedrock で Amazon Nova Canvas を呼び出して画像を生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Nova Canvas で画像を作成します。  

```
# Use the native inference API to create an image with Amazon Nova Canvas

import base64
import json
import os
import random

import boto3

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID.
model_id = "amazon.nova-canvas-v1:0"

# Define the image generation prompt for the model.
prompt = "A stylized picture of a cute old steampunk robot."

# Generate a random seed between 0 and 858,993,459
seed = random.randint(0, 858993460)

# Format the request payload using the model's native structure.
native_request = {
    "taskType": "TEXT_IMAGE",
    "textToImageParams": {"text": prompt},
    "imageGenerationConfig": {
        "seed": seed,
        "quality": "standard",
        "height": 512,
        "width": 512,
        "numberOfImages": 1,
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

# Invoke the model with the request.
response = client.invoke_model(modelId=model_id, body=request)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract the image data.
base64_image_data = model_response["images"][0]

# Save the generated image to a local folder.
i, output_dir = 1, "output"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
while os.path.exists(os.path.join(output_dir, f"nova_canvas_{i}.png")):
    i += 1

image_data = base64.b64decode(base64_image_data)

image_path = os.path.join(output_dir, f"nova_canvas_{i}.png")
with open(image_path, "wb") as file:
    file.write(image_data)

print(f"The generated image has been saved to {image_path}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Amazon Nova Reel
<a name="amazon_nova_reel"></a>

### Text-to-video
<a name="bedrock-runtime_Scenario_AmazonNova_TextToVideo_python_3_topic"></a>

次のコード例では、Amazon Nova Reel を使用してテキストプロンプトで動画を生成する方法について示します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Nova Reel を使用してテキストプロンプトで動画を生成します。  

```
"""
This example demonstrates how to use Amazon Nova Reel to generate a video from a text prompt.

It shows how to:
- Set up the Amazon Bedrock runtime client
- Configure a text-to-video request
- Submit an asynchronous job for video generation
- Poll for job completion status
- Access the generated video from S3
"""

import random
import time

import boto3

# Replace with your own S3 bucket to store the generated video
# Format: s3://your-bucket-name
OUTPUT_S3_URI = "s3://REPLACE-WITH-YOUR-S3-BUCKET-NAME"


def start_text_to_video_generation_job(bedrock_runtime, prompt, output_s3_uri):
    """
    Starts an asynchronous text-to-video generation job using Amazon Nova Reel.

    :param bedrock_runtime: The Bedrock runtime client
    :param prompt: The text description of the video to generate
    :param output_s3_uri: S3 URI where the generated video will be stored

    :return: The invocation ARN of the async job
    """
    # Specify the model ID for text-to-video generation
    model_id = "amazon.nova-reel-v1:0"

    # Generate a random seed between 0 and 2,147,483,646
    # This helps ensure unique video generation results
    seed = random.randint(0, 2147483646)

    # Configure the video generation request with additional parameters
    model_input = {
        "taskType": "TEXT_VIDEO",
        "textToVideoParams": {"text": prompt},
        "videoGenerationConfig": {
            "fps": 24,
            "durationSeconds": 6,
            "dimension": "1280x720",
            "seed": seed,
        },
    }

    # Specify the S3 location for the output video
    output_config = {"s3OutputDataConfig": {"s3Uri": output_s3_uri}}

    # Invoke the model asynchronously
    response = bedrock_runtime.start_async_invoke(
        modelId=model_id, modelInput=model_input, outputDataConfig=output_config
    )

    invocation_arn = response["invocationArn"]

    return invocation_arn


def query_job_status(bedrock_runtime, invocation_arn):
    """
    Queries the status of an asynchronous video generation job.

    :param bedrock_runtime: The Bedrock runtime client
    :param invocation_arn: The ARN of the async invocation to check

    :return: The runtime response containing the job status and details
    """
    return bedrock_runtime.get_async_invoke(invocationArn=invocation_arn)


def main():
    """
    Main function that demonstrates the complete workflow for generating
    a video from a text prompt using Amazon Nova Reel.
    """
    # Create a Bedrock Runtime client
    # Note: Credentials will be loaded from the environment or AWS CLI config
    bedrock_runtime = boto3.client("bedrock-runtime", region_name="us-east-1")

    # Configure the text prompt and output location
    prompt = "Closeup of a cute old steampunk robot. Camera zoom in."

    # Verify the S3 URI has been set to a valid bucket
    if "REPLACE-WITH-YOUR-S3-BUCKET-NAME" in OUTPUT_S3_URI:
        print("ERROR: You must replace the OUTPUT_S3_URI with your own S3 bucket URI")
        return

    print("Submitting video generation job...")
    invocation_arn = start_text_to_video_generation_job(
        bedrock_runtime, prompt, OUTPUT_S3_URI
    )
    print(f"Job started with invocation ARN: {invocation_arn}")

    # Poll for job completion
    while True:
        print("\nPolling job status...")
        job = query_job_status(bedrock_runtime, invocation_arn)
        status = job["status"]

        if status == "Completed":
            bucket_uri = job["outputDataConfig"]["s3OutputDataConfig"]["s3Uri"]
            print(f"\nSuccess! The video is available at: {bucket_uri}/output.mp4")
            break
        elif status == "Failed":
            print(
                f"\nVideo generation failed: {job.get('failureMessage', 'Unknown error')}"
            )
            break
        else:
            print("In progress. Waiting 15 seconds...")
            time.sleep(15)


if __name__ == "__main__":
    main()
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [GetAsyncInvoke](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/GetAsyncInvoke)
  + [StartAsyncInvoke](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/StartAsyncInvoke)

## Amazon Titan Image Generator
<a name="amazon_titan_image_generator"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_TitanImageGenerator_python_3_topic"></a>

次のコード例は、Amazon Bedrock で Amazon Titan Image を呼び出して画像を生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Titan Image Generator を使用して画像を作成します。  

```
# Use the native inference API to create an image with Amazon Titan Image Generator

import base64
import boto3
import json
import os
import random

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Titan Image Generator G1.
model_id = "amazon.titan-image-generator-v2:0"

# Define the image generation prompt for the model.
prompt = "A stylized picture of a cute old steampunk robot."

# Generate a random seed.
seed = random.randint(0, 2147483647)

# Format the request payload using the model's native structure.
native_request = {
    "taskType": "TEXT_IMAGE",
    "textToImageParams": {"text": prompt},
    "imageGenerationConfig": {
        "numberOfImages": 1,
        "quality": "standard",
        "cfgScale": 8.0,
        "height": 512,
        "width": 512,
        "seed": seed,
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

# Invoke the model with the request.
response = client.invoke_model(modelId=model_id, body=request)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract the image data.
base64_image_data = model_response["images"][0]

# Save the generated image to a local folder.
i, output_dir = 1, "output"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
while os.path.exists(os.path.join(output_dir, f"titan_{i}.png")):
    i += 1

image_data = base64.b64decode(base64_image_data)

image_path = os.path.join(output_dir, f"titan_{i}.png")
with open(image_path, "wb") as file:
    file.write(image_data)

print(f"The generated image has been saved to {image_path}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Amazon Titan Text
<a name="amazon_titan_text"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_TitanText_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Amazon Titan Text にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
# Use the native inference API to send a text message to Amazon Titan Text.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Titan Text Premier.
model_id = "amazon.titan-text-premier-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Format the request payload using the model's native structure.
native_request = {
    "inputText": prompt,
    "textGenerationConfig": {
        "maxTokenCount": 512,
        "temperature": 0.5,
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = client.invoke_model(modelId=model_id, body=request)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract and print the response text.
response_text = model_response["results"][0]["outputText"]
print(response_text)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Amazon Titan Text Embeddings
<a name="amazon_titan_text_embeddings"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModelWithResponseStream_TitanTextEmbeddings_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 最初の埋め込みの作成を開始します。
+ ディメンションの数と正規化を設定する埋め込みを作成します (V2 のみ)。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Titan Text Embeddings で最初の埋め込みを作成します。  

```
# Generate and print an embedding with Amazon Titan Text Embeddings V2.

import boto3
import json

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Titan Text Embeddings V2.
model_id = "amazon.titan-embed-text-v2:0"

# The text to convert to an embedding.
input_text = "Please recommend books with a theme similar to the movie 'Inception'."

# Create the request for the model.
native_request = {"inputText": input_text}

# Convert the native request to JSON.
request = json.dumps(native_request)

# Invoke the model with the request.
response = client.invoke_model(modelId=model_id, body=request)

# Decode the model's native response body.
model_response = json.loads(response["body"].read())

# Extract and print the generated embedding and the input text token count.
embedding = model_response["embedding"]
input_token_count = model_response["inputTextTokenCount"]

print("\nYour input:")
print(input_text)
print(f"Number of input tokens: {input_token_count}")
print(f"Size of the generated embedding: {len(embedding)}")
print("Embedding:")
print(embedding)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

## Anthropic Claude
<a name="anthropic_claude"></a>

### Converse
<a name="bedrock-runtime_Converse_AnthropicClaude_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。  

```
# Use the Conversation API to send a text message to Anthropic Claude.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Claude 3 Haiku.
model_id = "anthropic.claude-3-haiku-20240307-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AnthropicClaude_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the Conversation API to send a text message to Anthropic Claude
# and print the response stream.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Claude 3 Haiku.
model_id = "anthropic.claude-3-haiku-20240307-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    streaming_response = client.converse_stream(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the streamed response text in real-time.
    for chunk in streaming_response["stream"]:
        if "contentBlockDelta" in chunk:
            text = chunk["contentBlockDelta"]["delta"]["text"]
            print(text, end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### ドキュメント理解
<a name="bedrock-runtime_DocumentUnderstanding_AnthropicClaude_python_3_topic"></a>

次のコード例は、Amazon Bedrock で Anthropic Claude を使用してドキュメントを送信して処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で Anthropic Claude を使用してドキュメントを送信して処理します。  

```
# Send and process a document with Anthropic Claude on Amazon Bedrock.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g. Claude 3 Haiku.
model_id = "anthropic.claude-3-haiku-20240307-v1:0"

# Load the document
with open("example-data/amazon-nova-service-cards.pdf", "rb") as file:
    document_bytes = file.read()

# Start a conversation with a user message and the document
conversation = [
    {
        "role": "user",
        "content": [
            {"text": "Briefly compare the models described in this document"},
            {
                "document": {
                    # Available formats: html, md, pdf, doc/docx, xls/xlsx, csv, and txt
                    "format": "pdf",
                    "name": "Amazon Nova Service Cards",
                    "source": {"bytes": document_bytes},
                }
            },
        ],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 500, "temperature": 0.3},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AnthropicClaude_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
# Use the native inference API to send a text message to Anthropic Claude.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Claude 3 Haiku.
model_id = "anthropic.claude-3-haiku-20240307-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Format the request payload using the model's native structure.
native_request = {
    "anthropic_version": "bedrock-2023-05-31",
    "max_tokens": 512,
    "temperature": 0.5,
    "messages": [
        {
            "role": "user",
            "content": [{"type": "text", "text": prompt}],
        }
    ],
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = client.invoke_model(modelId=model_id, body=request)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract and print the response text.
response_text = model_response["content"][0]["text"]
print(response_text)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_AnthropicClaude_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the native inference API to send a text message to Anthropic Claude
# and print the response stream.

import boto3
import json

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Claude 3 Haiku.
model_id = "anthropic.claude-3-haiku-20240307-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Format the request payload using the model's native structure.
native_request = {
    "anthropic_version": "bedrock-2023-05-31",
    "max_tokens": 512,
    "temperature": 0.5,
    "messages": [
        {
            "role": "user",
            "content": [{"type": "text", "text": prompt}],
        }
    ],
}

# Convert the native request to JSON.
request = json.dumps(native_request)

# Invoke the model with the request.
streaming_response = client.invoke_model_with_response_stream(
    modelId=model_id, body=request
)

# Extract and print the response text in real-time.
for event in streaming_response["body"]:
    chunk = json.loads(event["chunk"]["bytes"])
    if chunk["type"] == "content_block_delta":
        print(chunk["delta"].get("text", ""), end="")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

### シナリオ: Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUseDemo_AnthropicClaude_python_3_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
デモのプライマリ実行スクリプト。このスクリプトは、ユーザー、Amazon Bedrock Converse API、および気象ツール間の会話を調整します。  

```
"""
This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user
input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.
"""

import boto3
import logging
from enum import Enum

import utils.tool_use_print_utils as output
import weather_tool

logging.basicConfig(level=logging.INFO, format="%(message)s")

AWS_REGION = "us-east-1"


# For the most recent list of models supported by the Converse API's tool use functionality, visit:
# https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html
class SupportedModels(Enum):
    CLAUDE_OPUS = "anthropic.claude-3-opus-20240229-v1:0"
    CLAUDE_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0"
    CLAUDE_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0"
    COHERE_COMMAND_R = "cohere.command-r-v1:0"
    COHERE_COMMAND_R_PLUS = "cohere.command-r-plus-v1:0"


# Set the model ID, e.g., Claude 3 Haiku.
MODEL_ID = SupportedModels.CLAUDE_HAIKU.value

SYSTEM_PROMPT = """
You are a weather assistant that provides current weather data for user-specified locations using only
the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
If the user provides coordinates, infer the approximate location and refer to it in your response.
To use the tool, you strictly apply the provided tool specification.

- Explain your step-by-step process, and give brief updates before each step.
- Only use the Weather_Tool for data. Never guess or make up information. 
- Repeat the tool use for subsequent requests if necessary.
- If the tool errors, apologize, explain weather is unavailable, and suggest other options.
- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
  emojis where appropriate.
- Only respond to weather queries. Remind off-topic users of your purpose. 
- Never claim to search online, access external data, or use tools besides Weather_Tool.
- Complete the entire process until you have all required data before sending the complete response.
"""

# The maximum number of recursive calls allowed in the tool_use_demo function.
# This helps prevent infinite loops and potential performance issues.
MAX_RECURSIONS = 5


class ToolUseDemo:
    """
    Demonstrates the tool use feature with the Amazon Bedrock Converse API.
    """

    def __init__(self):
        # Prepare the system prompt
        self.system_prompt = [{"text": SYSTEM_PROMPT}]

        # Prepare the tool configuration with the weather tool's specification
        self.tool_config = {"tools": [weather_tool.get_tool_spec()]}

        # Create a Bedrock Runtime client in the specified AWS Region.
        self.bedrockRuntimeClient = boto3.client(
            "bedrock-runtime", region_name=AWS_REGION
        )

    def run(self):
        """
        Starts the conversation with the user and handles the interaction with Bedrock.
        """
        # Print the greeting and a short user guide
        output.header()

        # Start with an emtpy conversation
        conversation = []

        # Get the first user input
        user_input = self._get_user_input()

        while user_input is not None:
            # Create a new message with the user input and append it to the conversation
            message = {"role": "user", "content": [{"text": user_input}]}
            conversation.append(message)

            # Send the conversation to Amazon Bedrock
            bedrock_response = self._send_conversation_to_bedrock(conversation)

            # Recursively handle the model's response until the model has returned
            # its final response or the recursion counter has reached 0
            self._process_model_response(
                bedrock_response, conversation, max_recursion=MAX_RECURSIONS
            )

            # Repeat the loop until the user decides to exit the application
            user_input = self._get_user_input()

        output.footer()

    def _send_conversation_to_bedrock(self, conversation):
        """
        Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response.

        :param conversation: The conversation history including the next message to send.
        :return: The response from Amazon Bedrock.
        """
        output.call_to_bedrock(conversation)

        # Send the conversation, system prompt, and tool configuration, and return the response
        return self.bedrockRuntimeClient.converse(
            modelId=MODEL_ID,
            messages=conversation,
            system=self.system_prompt,
            toolConfig=self.tool_config,
        )

    def _process_model_response(
        self, model_response, conversation, max_recursion=MAX_RECURSIONS
    ):
        """
        Processes the response received via Amazon Bedrock and performs the necessary actions
        based on the stop reason.

        :param model_response: The model's response returned via Amazon Bedrock.
        :param conversation: The conversation history.
        :param max_recursion: The maximum number of recursive calls allowed.
        """

        if max_recursion <= 0:
            # Stop the process, the number of recursive calls could indicate an infinite loop
            logging.warning(
                "Warning: Maximum number of recursions reached. Please try again."
            )
            exit(1)

        # Append the model's response to the ongoing conversation
        message = model_response["output"]["message"]
        conversation.append(message)

        if model_response["stopReason"] == "tool_use":
            # If the stop reason is "tool_use", forward everything to the tool use handler
            self._handle_tool_use(message, conversation, max_recursion)

        if model_response["stopReason"] == "end_turn":
            # If the stop reason is "end_turn", print the model's response text, and finish the process
            output.model_response(message["content"][0]["text"])
            return

    def _handle_tool_use(
        self, model_response, conversation, max_recursion=MAX_RECURSIONS
    ):
        """
        Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock.
        The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing.

        :param model_response: The model's response containing the tool use request.
        :param conversation: The conversation history.
        :param max_recursion: The maximum number of recursive calls allowed.
        """

        # Initialize an empty list of tool results
        tool_results = []

        # The model's response can consist of multiple content blocks
        for content_block in model_response["content"]:
            if "text" in content_block:
                # If the content block contains text, print it to the console
                output.model_response(content_block["text"])

            if "toolUse" in content_block:
                # If the content block is a tool use request, forward it to the tool
                tool_response = self._invoke_tool(content_block["toolUse"])

                # Add the tool use ID and the tool's response to the list of results
                tool_results.append(
                    {
                        "toolResult": {
                            "toolUseId": (tool_response["toolUseId"]),
                            "content": [{"json": tool_response["content"]}],
                        }
                    }
                )

        # Embed the tool results in a new user message
        message = {"role": "user", "content": tool_results}

        # Append the new message to the ongoing conversation
        conversation.append(message)

        # Send the conversation to Amazon Bedrock
        response = self._send_conversation_to_bedrock(conversation)

        # Recursively handle the model's response until the model has returned
        # its final response or the recursion counter has reached 0
        self._process_model_response(response, conversation, max_recursion - 1)

    def _invoke_tool(self, payload):
        """
        Invokes the specified tool with the given payload and returns the tool's response.
        If the requested tool does not exist, an error message is returned.

        :param payload: The payload containing the tool name and input data.
        :return: The tool's response or an error message.
        """
        tool_name = payload["name"]

        if tool_name == "Weather_Tool":
            input_data = payload["input"]
            output.tool_use(tool_name, input_data)

            # Invoke the weather tool with the input data provided by
            response = weather_tool.fetch_weather_data(input_data)
        else:
            error_message = (
                f"The requested tool with name '{tool_name}' does not exist."
            )
            response = {"error": "true", "message": error_message}

        return {"toolUseId": payload["toolUseId"], "content": response}

    @staticmethod
    def _get_user_input(prompt="Your weather info request"):
        """
        Prompts the user for input and returns the user's response.
        Returns None if the user enters 'x' to exit.

        :param prompt: The prompt to display to the user.
        :return: The user's input or None if the user chooses to exit.
        """
        output.separator()
        user_input = input(f"{prompt} (x to exit): ")

        if user_input == "":
            prompt = "Please enter your weather info request, e.g. the name of a city"
            return ToolUseDemo._get_user_input(prompt)

        elif user_input.lower() == "x":
            return None

        else:
            return user_input


if __name__ == "__main__":
    tool_use_demo = ToolUseDemo()
    tool_use_demo.run()
```
デモで使用される気象ツール。このスクリプトは、ツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
import requests
from requests.exceptions import RequestException


def get_tool_spec():
    """
    Returns the JSON Schema specification for the Weather tool. The tool specification
    defines the input schema and describes the tool's functionality.
    For more information, see https://json-schema.org/understanding-json-schema/reference.

    :return: The tool specification for the Weather tool.
    """
    return {
        "toolSpec": {
            "name": "Weather_Tool",
            "description": "Get the current weather for a given location, based on its WGS84 coordinates.",
            "inputSchema": {
                "json": {
                    "type": "object",
                    "properties": {
                        "latitude": {
                            "type": "string",
                            "description": "Geographical WGS84 latitude of the location.",
                        },
                        "longitude": {
                            "type": "string",
                            "description": "Geographical WGS84 longitude of the location.",
                        },
                    },
                    "required": ["latitude", "longitude"],
                }
            },
        }
    }


def fetch_weather_data(input_data):
    """
    Fetches weather data for the given latitude and longitude using the Open-Meteo API.
    Returns the weather data or an error message if the request fails.

    :param input_data: The input data containing the latitude and longitude.
    :return: The weather data or an error message.
    """
    endpoint = "https://api.open-meteo.com/v1/forecast"
    latitude = input_data.get("latitude")
    longitude = input_data.get("longitude", "")
    params = {"latitude": latitude, "longitude": longitude, "current_weather": True}

    try:
        response = requests.get(endpoint, params=params)
        weather_data = {"weather_data": response.json()}
        response.raise_for_status()
        return weather_data
    except RequestException as e:
        return e.response.json()
    except Exception as e:
        return {"error": type(e), "message": str(e)}
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Cohere Command
<a name="cohere_command"></a>

### Converse
<a name="bedrock-runtime_Converse_CohereCommand_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信します。  

```
# Use the Conversation API to send a text message to Cohere Command.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Command R.
model_id = "cohere.command-r-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_CohereCommand_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the Conversation API to send a text message to Cohere Command
# and print the response stream.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Command R.
model_id = "cohere.command-r-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    streaming_response = client.converse_stream(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the streamed response text in real-time.
    for chunk in streaming_response["stream"]:
        if "contentBlockDelta" in chunk:
            text = chunk["contentBlockDelta"]["delta"]["text"]
            print(text, end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### ドキュメント理解
<a name="bedrock-runtime_DocumentUnderstanding_CohereCommand_python_3_topic"></a>

次のコード例は、Amazon Bedrock で Cohere コマンドモデルを使用してドキュメントを送信して処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で Cohere Command モデルを使用してドキュメントを送信して処理します。  

```
# Send and process a document with Cohere Command models on Amazon Bedrock.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g. Command R+.
model_id = "cohere.command-r-plus-v1:0"

# Load the document
with open("example-data/amazon-nova-service-cards.pdf", "rb") as file:
    document_bytes = file.read()

# Start a conversation with a user message and the document
conversation = [
    {
        "role": "user",
        "content": [
            {"text": "Briefly compare the models described in this document"},
            {
                "document": {
                    # Available formats: html, md, pdf, doc/docx, xls/xlsx, csv, and txt
                    "format": "pdf",
                    "name": "Amazon Nova Service Cards",
                    "source": {"bytes": document_bytes},
                }
            },
        ],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 500, "temperature": 0.3},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### InvokeModel: コマンド R および R\$1
<a name="bedrock-runtime_InvokeModel_CohereCommandR_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Cohere Command R および R\$1 にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
# Use the native inference API to send a text message to Cohere Command R and R+.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Command R.
model_id = "cohere.command-r-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Format the request payload using the model's native structure.
native_request = {
    "message": prompt,
    "max_tokens": 512,
    "temperature": 0.5,
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = client.invoke_model(modelId=model_id, body=request)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract and print the response text.
response_text = model_response["text"]
print(response_text)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream: コマンド R および R\$1
<a name="bedrock-runtime_InvokeModelWithResponseStream_CohereCommandR_python_3_topic"></a>

次のコード例は、レスポンスストリームで Invoke Model API を使用して、Cohere Command にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the native inference API to send a text message to Cohere Command R and R+
# and print the response stream.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Command R.
model_id = "cohere.command-r-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Format the request payload using the model's native structure.
native_request = {
    "message": prompt,
    "max_tokens": 512,
    "temperature": 0.5,
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    streaming_response = client.invoke_model_with_response_stream(
        modelId=model_id, body=request
    )

    # Extract and print the response text in real-time.
    for event in streaming_response["body"]:
        chunk = json.loads(event["chunk"]["bytes"])
        if "generations" in chunk:
            print(chunk["generations"][0]["text"], end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### シナリオ: Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUseDemo_CohereCommand_python_3_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
デモのプライマリ実行スクリプト。このスクリプトは、ユーザー、Amazon Bedrock Converse API、および気象ツール間の会話を調整します。  

```
"""
This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool.
The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user
input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location.
"""

import boto3
import logging
from enum import Enum

import utils.tool_use_print_utils as output
import weather_tool

logging.basicConfig(level=logging.INFO, format="%(message)s")

AWS_REGION = "us-east-1"


# For the most recent list of models supported by the Converse API's tool use functionality, visit:
# https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html
class SupportedModels(Enum):
    CLAUDE_OPUS = "anthropic.claude-3-opus-20240229-v1:0"
    CLAUDE_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0"
    CLAUDE_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0"
    COHERE_COMMAND_R = "cohere.command-r-v1:0"
    COHERE_COMMAND_R_PLUS = "cohere.command-r-plus-v1:0"


# Set the model ID, e.g., Claude 3 Haiku.
MODEL_ID = SupportedModels.CLAUDE_HAIKU.value

SYSTEM_PROMPT = """
You are a weather assistant that provides current weather data for user-specified locations using only
the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
If the user provides coordinates, infer the approximate location and refer to it in your response.
To use the tool, you strictly apply the provided tool specification.

- Explain your step-by-step process, and give brief updates before each step.
- Only use the Weather_Tool for data. Never guess or make up information. 
- Repeat the tool use for subsequent requests if necessary.
- If the tool errors, apologize, explain weather is unavailable, and suggest other options.
- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
  emojis where appropriate.
- Only respond to weather queries. Remind off-topic users of your purpose. 
- Never claim to search online, access external data, or use tools besides Weather_Tool.
- Complete the entire process until you have all required data before sending the complete response.
"""

# The maximum number of recursive calls allowed in the tool_use_demo function.
# This helps prevent infinite loops and potential performance issues.
MAX_RECURSIONS = 5


class ToolUseDemo:
    """
    Demonstrates the tool use feature with the Amazon Bedrock Converse API.
    """

    def __init__(self):
        # Prepare the system prompt
        self.system_prompt = [{"text": SYSTEM_PROMPT}]

        # Prepare the tool configuration with the weather tool's specification
        self.tool_config = {"tools": [weather_tool.get_tool_spec()]}

        # Create a Bedrock Runtime client in the specified AWS Region.
        self.bedrockRuntimeClient = boto3.client(
            "bedrock-runtime", region_name=AWS_REGION
        )

    def run(self):
        """
        Starts the conversation with the user and handles the interaction with Bedrock.
        """
        # Print the greeting and a short user guide
        output.header()

        # Start with an emtpy conversation
        conversation = []

        # Get the first user input
        user_input = self._get_user_input()

        while user_input is not None:
            # Create a new message with the user input and append it to the conversation
            message = {"role": "user", "content": [{"text": user_input}]}
            conversation.append(message)

            # Send the conversation to Amazon Bedrock
            bedrock_response = self._send_conversation_to_bedrock(conversation)

            # Recursively handle the model's response until the model has returned
            # its final response or the recursion counter has reached 0
            self._process_model_response(
                bedrock_response, conversation, max_recursion=MAX_RECURSIONS
            )

            # Repeat the loop until the user decides to exit the application
            user_input = self._get_user_input()

        output.footer()

    def _send_conversation_to_bedrock(self, conversation):
        """
        Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response.

        :param conversation: The conversation history including the next message to send.
        :return: The response from Amazon Bedrock.
        """
        output.call_to_bedrock(conversation)

        # Send the conversation, system prompt, and tool configuration, and return the response
        return self.bedrockRuntimeClient.converse(
            modelId=MODEL_ID,
            messages=conversation,
            system=self.system_prompt,
            toolConfig=self.tool_config,
        )

    def _process_model_response(
        self, model_response, conversation, max_recursion=MAX_RECURSIONS
    ):
        """
        Processes the response received via Amazon Bedrock and performs the necessary actions
        based on the stop reason.

        :param model_response: The model's response returned via Amazon Bedrock.
        :param conversation: The conversation history.
        :param max_recursion: The maximum number of recursive calls allowed.
        """

        if max_recursion <= 0:
            # Stop the process, the number of recursive calls could indicate an infinite loop
            logging.warning(
                "Warning: Maximum number of recursions reached. Please try again."
            )
            exit(1)

        # Append the model's response to the ongoing conversation
        message = model_response["output"]["message"]
        conversation.append(message)

        if model_response["stopReason"] == "tool_use":
            # If the stop reason is "tool_use", forward everything to the tool use handler
            self._handle_tool_use(message, conversation, max_recursion)

        if model_response["stopReason"] == "end_turn":
            # If the stop reason is "end_turn", print the model's response text, and finish the process
            output.model_response(message["content"][0]["text"])
            return

    def _handle_tool_use(
        self, model_response, conversation, max_recursion=MAX_RECURSIONS
    ):
        """
        Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock.
        The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing.

        :param model_response: The model's response containing the tool use request.
        :param conversation: The conversation history.
        :param max_recursion: The maximum number of recursive calls allowed.
        """

        # Initialize an empty list of tool results
        tool_results = []

        # The model's response can consist of multiple content blocks
        for content_block in model_response["content"]:
            if "text" in content_block:
                # If the content block contains text, print it to the console
                output.model_response(content_block["text"])

            if "toolUse" in content_block:
                # If the content block is a tool use request, forward it to the tool
                tool_response = self._invoke_tool(content_block["toolUse"])

                # Add the tool use ID and the tool's response to the list of results
                tool_results.append(
                    {
                        "toolResult": {
                            "toolUseId": (tool_response["toolUseId"]),
                            "content": [{"json": tool_response["content"]}],
                        }
                    }
                )

        # Embed the tool results in a new user message
        message = {"role": "user", "content": tool_results}

        # Append the new message to the ongoing conversation
        conversation.append(message)

        # Send the conversation to Amazon Bedrock
        response = self._send_conversation_to_bedrock(conversation)

        # Recursively handle the model's response until the model has returned
        # its final response or the recursion counter has reached 0
        self._process_model_response(response, conversation, max_recursion - 1)

    def _invoke_tool(self, payload):
        """
        Invokes the specified tool with the given payload and returns the tool's response.
        If the requested tool does not exist, an error message is returned.

        :param payload: The payload containing the tool name and input data.
        :return: The tool's response or an error message.
        """
        tool_name = payload["name"]

        if tool_name == "Weather_Tool":
            input_data = payload["input"]
            output.tool_use(tool_name, input_data)

            # Invoke the weather tool with the input data provided by
            response = weather_tool.fetch_weather_data(input_data)
        else:
            error_message = (
                f"The requested tool with name '{tool_name}' does not exist."
            )
            response = {"error": "true", "message": error_message}

        return {"toolUseId": payload["toolUseId"], "content": response}

    @staticmethod
    def _get_user_input(prompt="Your weather info request"):
        """
        Prompts the user for input and returns the user's response.
        Returns None if the user enters 'x' to exit.

        :param prompt: The prompt to display to the user.
        :return: The user's input or None if the user chooses to exit.
        """
        output.separator()
        user_input = input(f"{prompt} (x to exit): ")

        if user_input == "":
            prompt = "Please enter your weather info request, e.g. the name of a city"
            return ToolUseDemo._get_user_input(prompt)

        elif user_input.lower() == "x":
            return None

        else:
            return user_input


if __name__ == "__main__":
    tool_use_demo = ToolUseDemo()
    tool_use_demo.run()
```
デモで使用される気象ツール。このスクリプトは、ツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
import requests
from requests.exceptions import RequestException


def get_tool_spec():
    """
    Returns the JSON Schema specification for the Weather tool. The tool specification
    defines the input schema and describes the tool's functionality.
    For more information, see https://json-schema.org/understanding-json-schema/reference.

    :return: The tool specification for the Weather tool.
    """
    return {
        "toolSpec": {
            "name": "Weather_Tool",
            "description": "Get the current weather for a given location, based on its WGS84 coordinates.",
            "inputSchema": {
                "json": {
                    "type": "object",
                    "properties": {
                        "latitude": {
                            "type": "string",
                            "description": "Geographical WGS84 latitude of the location.",
                        },
                        "longitude": {
                            "type": "string",
                            "description": "Geographical WGS84 longitude of the location.",
                        },
                    },
                    "required": ["latitude", "longitude"],
                }
            },
        }
    }


def fetch_weather_data(input_data):
    """
    Fetches weather data for the given latitude and longitude using the Open-Meteo API.
    Returns the weather data or an error message if the request fails.

    :param input_data: The input data containing the latitude and longitude.
    :return: The weather data or an error message.
    """
    endpoint = "https://api.open-meteo.com/v1/forecast"
    latitude = input_data.get("latitude")
    longitude = input_data.get("longitude", "")
    params = {"latitude": latitude, "longitude": longitude, "current_weather": True}

    try:
        response = requests.get(endpoint, params=params)
        weather_data = {"weather_data": response.json()}
        response.raise_for_status()
        return weather_data
    except RequestException as e:
        return e.response.json()
    except Exception as e:
        return {"error": type(e), "message": str(e)}
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## DeepSeek
<a name="deepseek"></a>

### ドキュメント理解
<a name="bedrock-runtime_DocumentUnderstanding_DeepSeek_python_3_topic"></a>

次のコード例は、Amazon Bedrock で DeepSeek を使用してドキュメントを送信および処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で DeepSeek を使用してドキュメントを送信して処理します。  

```
# Send and process a document with DeepSeek on Amazon Bedrock.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g. DeepSeek-R1
model_id = "us.deepseek.r1-v1:0"

# Load the document
with open("example-data/amazon-nova-service-cards.pdf", "rb") as file:
    document_bytes = file.read()

# Start a conversation with a user message and the document
conversation = [
    {
        "role": "user",
        "content": [
            {"text": "Briefly compare the models described in this document"},
            {
                "document": {
                    # Available formats: html, md, pdf, doc/docx, xls/xlsx, csv, and txt
                    "format": "pdf",
                    "name": "Amazon Nova Service Cards",
                    "source": {"bytes": document_bytes},
                }
            },
        ],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 2000, "temperature": 0.3},
    )

    # Extract and print the reasoning and response text.
    reasoning, response_text = "", ""
    for item in response["output"]["message"]["content"]:
        for key, value in item.items():
            if key == "reasoningContent":
                reasoning = value["reasoningText"]["text"]
            elif key == "text":
                response_text = value

    print(f"\nReasoning:\n{reasoning}")
    print(f"\nResponse:\n{response_text}")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

## Meta Llama
<a name="meta_llama"></a>

### Converse
<a name="bedrock-runtime_Converse_MetaLlama_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信します。  

```
# Use the Conversation API to send a text message to Meta Llama.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Llama 3 8b Instruct.
model_id = "meta.llama3-8b-instruct-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_MetaLlama_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the Conversation API to send a text message to Meta Llama
# and print the response stream.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Llama 3 8b Instruct.
model_id = "meta.llama3-8b-instruct-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    streaming_response = client.converse_stream(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the streamed response text in real-time.
    for chunk in streaming_response["stream"]:
        if "contentBlockDelta" in chunk:
            text = chunk["contentBlockDelta"]["delta"]["text"]
            print(text, end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### ドキュメント理解
<a name="bedrock-runtime_DocumentUnderstanding_MetaLlama_python_3_topic"></a>

次のコード例は、Amazon Bedrock で Llama を使用してドキュメントを送信して処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で Llama を使用してドキュメントを送信して処理します。  

```
# Send and process a document with Llama on Amazon Bedrock.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g. Llama 3.1 8B Instruct.
model_id = "us.meta.llama3-1-8b-instruct-v1:0"

# Load the document
with open("example-data/amazon-nova-service-cards.pdf", "rb") as file:
    document_bytes = file.read()

# Start a conversation with a user message and the document
conversation = [
    {
        "role": "user",
        "content": [
            {"text": "Briefly compare the models described in this document"},
            {
                "document": {
                    # Available formats: html, md, pdf, doc/docx, xls/xlsx, csv, and txt
                    "format": "pdf",
                    "name": "Amazon Nova Service Cards",
                    "source": {"bytes": document_bytes},
                }
            },
        ],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 500, "temperature": 0.3},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MetaLlama3_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
# Use the native inference API to send a text message to Meta Llama 3.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-west-2")

# Set the model ID, e.g., Llama 3 70b Instruct.
model_id = "meta.llama3-70b-instruct-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Embed the prompt in Llama 3's instruction format.
formatted_prompt = f"""
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
{prompt}
<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
"""

# Format the request payload using the model's native structure.
native_request = {
    "prompt": formatted_prompt,
    "max_gen_len": 512,
    "temperature": 0.5,
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = client.invoke_model(modelId=model_id, body=request)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract and print the response text.
response_text = model_response["generation"]
print(response_text)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_MetaLlama3_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the native inference API to send a text message to Meta Llama 3
# and print the response stream.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-west-2")

# Set the model ID, e.g., Llama 3 70b Instruct.
model_id = "meta.llama3-70b-instruct-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Embed the prompt in Llama 3's instruction format.
formatted_prompt = f"""
<|begin_of_text|><|start_header_id|>user<|end_header_id|>
{prompt}
<|eot_id|>
<|start_header_id|>assistant<|end_header_id|>
"""

# Format the request payload using the model's native structure.
native_request = {
    "prompt": formatted_prompt,
    "max_gen_len": 512,
    "temperature": 0.5,
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    streaming_response = client.invoke_model_with_response_stream(
        modelId=model_id, body=request
    )

    # Extract and print the response text in real-time.
    for event in streaming_response["body"]:
        chunk = json.loads(event["chunk"]["bytes"])
        if "generation" in chunk:
            print(chunk["generation"], end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

## Mistral AI
<a name="mistral_ai"></a>

### Converse
<a name="bedrock-runtime_Converse_Mistral_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信します。  

```
# Use the Conversation API to send a text message to Mistral.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Mistral Large.
model_id = "mistral.mistral-large-2402-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_Mistral_python_3_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the Conversation API to send a text message to Mistral
# and print the response stream.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Mistral Large.
model_id = "mistral.mistral-large-2402-v1:0"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    streaming_response = client.converse_stream(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the streamed response text in real-time.
    for chunk in streaming_response["stream"]:
        if "contentBlockDelta" in chunk:
            text = chunk["contentBlockDelta"]["delta"]["text"]
            print(text, end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ConverseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/ConverseStream)」を参照してください。

### ドキュメント理解
<a name="bedrock-runtime_DocumentUnderstanding_Mistral_python_3_topic"></a>

次のコード例は、Amazon Bedrock で Mistral モデルを使用してドキュメントを送信して処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock で Mistral モデルを使用してドキュメントを送信して処理します。  

```
# Send and process a document with Mistral models on Amazon Bedrock.

import boto3
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region you want to use.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Mistral Large.
model_id = "mistral.mistral-large-2402-v1:0"

# Load the document
with open("example-data/amazon-nova-service-cards.pdf", "rb") as file:
    document_bytes = file.read()

# Start a conversation with a user message and the document
conversation = [
    {
        "role": "user",
        "content": [
            {"text": "Briefly compare the models described in this document"},
            {
                "document": {
                    # Available formats: html, md, pdf, doc/docx, xls/xlsx, csv, and txt
                    "format": "pdf",
                    "name": "Amazon Nova Service Cards",
                    "source": {"bytes": document_bytes},
                }
            },
        ],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = client.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 500, "temperature": 0.3},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)」を参照してください。

### InvokeModel
<a name="bedrock-runtime_InvokeModel_MistralAi_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Mistral モデルにテキストメッセージを送信する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信します。  

```
# Use the native inference API to send a text message to Mistral.

import boto3
import json
from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Mistral Large.
model_id = "mistral.mistral-large-2402-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Embed the prompt in Mistral's instruction format.
formatted_prompt = f"<s>[INST] {prompt} [/INST]"

# Format the request payload using the model's native structure.
native_request = {
    "prompt": formatted_prompt,
    "max_tokens": 512,
    "temperature": 0.5,
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = client.invoke_model(modelId=model_id, body=request)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract and print the response text.
response_text = model_response["outputs"][0]["text"]
print(response_text)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

### InvokeModelWithResponseStream
<a name="bedrock-runtime_InvokeModelWithResponseStream_MistralAi_python_3_topic"></a>

次のコード例は、Invoke Model API を使用して Mistral AI モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Invoke Model API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
# Use the native inference API to send a text message to Mistral
# and print the response stream.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Mistral Large.
model_id = "mistral.mistral-large-2402-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Embed the prompt in Mistral's instruction format.
formatted_prompt = f"<s>[INST] {prompt} [/INST]"

# Format the request payload using the model's native structure.
native_request = {
    "prompt": formatted_prompt,
    "max_tokens": 512,
    "temperature": 0.5,
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    streaming_response = client.invoke_model_with_response_stream(
        modelId=model_id, body=request
    )

    # Extract and print the response text in real-time.
    for event in streaming_response["body"]:
        chunk = json.loads(event["chunk"]["bytes"])
        if "outputs" in chunk:
            print(chunk["outputs"][0].get("text"), end="")

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}''. Reason: {e}")
    exit(1)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModelWithResponseStream](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModelWithResponseStream)」を参照してください。

## Stable Diffusion
<a name="stable_diffusion"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_StableDiffusion_python_3_topic"></a>

次のコード例は、Amazon Bedrock で Stability.ai Stable Diffusion XL を呼び出して画像を生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Stable Diffusion で画像を作成します。  

```
# Use the native inference API to create an image with Stability.ai Stable Diffusion

import base64
import boto3
import json
import os
import random

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Stable Diffusion XL 1.
model_id = "stability.stable-diffusion-xl-v1"

# Define the image generation prompt for the model.
prompt = "A stylized picture of a cute old steampunk robot."

# Generate a random seed.
seed = random.randint(0, 4294967295)

# Format the request payload using the model's native structure.
native_request = {
    "text_prompts": [{"text": prompt}],
    "style_preset": "photographic",
    "seed": seed,
    "cfg_scale": 10,
    "steps": 30,
}

# Convert the native request to JSON.
request = json.dumps(native_request)

# Invoke the model with the request.
response = client.invoke_model(modelId=model_id, body=request)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract the image data.
base64_image_data = model_response["artifacts"][0]["base64"]

# Save the generated image to a local folder.
i, output_dir = 1, "output"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
while os.path.exists(os.path.join(output_dir, f"stability_{i}.png")):
    i += 1

image_data = base64.b64decode(base64_image_data)

image_path = os.path.join(output_dir, f"stability_{i}.png")
with open(image_path, "wb") as file:
    file.write(image_data)

print(f"The generated image has been saved to {image_path}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)」を参照してください。

# SDK for Python (Boto3) を使用する Amazon Bedrock エージェントの例
<a name="python_3_bedrock-agent_code_examples"></a>

次のコード例は、Amazon Bedrock エージェント AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateAgent`
<a name="bedrock-agent_CreateAgent_python_3_topic"></a>

次のコード例は、`CreateAgent` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
 エージェントを作成します。  

```
    def create_agent(self, agent_name, foundation_model, role_arn, instruction):
        """
        Creates an agent that orchestrates interactions between foundation models,
        data sources, software applications, user conversations, and APIs to carry
        out tasks to help customers.

        :param agent_name: A name for the agent.
        :param foundation_model: The foundation model to be used for orchestration by the agent.
        :param role_arn: The ARN of the IAM role with permissions needed by the agent.
        :param instruction: Instructions that tell the agent what it should do and how it should
                            interact with users.
        :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception.
        """
        try:
            response = self.client.create_agent(
                agentName=agent_name,
                foundationModel=foundation_model,
                agentResourceRoleArn=role_arn,
                instruction=instruction,
            )
        except ClientError as e:
            logger.error(f"Error: Couldn't create agent. Here's why: {e}")
            raise
        else:
            return response["agent"]
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[CreateAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateAgent)」を参照してください。

### `CreateAgentActionGroup`
<a name="bedrock-agent_CreateAgentActionGroup_python_3_topic"></a>

次のコード例は、`CreateAgentActionGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントアクショングループを作成します。  

```
    def create_agent_action_group(
            self, name, description, agent_id, agent_version, function_arn, api_schema
    ):
        """
        Creates an action group for an agent. An action group defines a set of actions that an
        agent should carry out for the customer.

        :param name: The name to give the action group.
        :param description: The description of the action group.
        :param agent_id: The unique identifier of the agent for which to create the action group.
        :param agent_version: The version of the agent for which to create the action group.
        :param function_arn: The ARN of the Lambda function containing the business logic that is
                             carried out upon invoking the action.
        :param api_schema: Contains the OpenAPI schema for the action group.
        :return: Details about the action group that was created.
        """
        try:
            response = self.client.create_agent_action_group(
                actionGroupName=name,
                description=description,
                agentId=agent_id,
                agentVersion=agent_version,
                actionGroupExecutor={"lambda": function_arn},
                apiSchema={"payload": api_schema},
            )
            agent_action_group = response["agentActionGroup"]
        except ClientError as e:
            logger.error(f"Error: Couldn't create agent action group. Here's why: {e}")
            raise
        else:
            return agent_action_group
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[CreateAgentActionGroup](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateAgentActionGroup)」を参照してください。**

### `CreateAgentAlias`
<a name="bedrock-agent_CreateAgentAlias_python_3_topic"></a>

次のコード例は、`CreateAgentAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントエイリアスを作成します。  

```
    def create_agent_alias(self, name, agent_id):
        """
        Creates an alias of an agent that can be used to deploy the agent.

        :param name: The name of the alias.
        :param agent_id: The unique identifier of the agent.
        :return: Details about the alias that was created.
        """
        try:
            response = self.client.create_agent_alias(
                agentAliasName=name, agentId=agent_id
            )
            agent_alias = response["agentAlias"]
        except ClientError as e:
            logger.error(f"Couldn't create agent alias. {e}")
            raise
        else:
            return agent_alias
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[CreateAgentAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateAgentAlias)」を参照してください。

### `CreateFlow`
<a name="bedrock-agent_CreateFlow_python_3_topic"></a>

次のコード例は、`CreateFlow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローを作成します。  

```
def create_flow(client, flow_name, flow_description, role_arn, flow_def):
    """
    Creates an Amazon Bedrock flow.

    Args:
    client: Amazon Bedrock agent boto3 client.
    flow_name (str): The name for the new flow.
    role_arn (str):  The ARN for the IAM role that use flow uses.
    flow_def (json): The JSON definition of the flow that you want to create.

    Returns:
        dict: The response from CreateFlow.
    """
    try:

        logger.info("Creating flow: %s.", flow_name)

        response = client.create_flow(
            name=flow_name,
            description=flow_description,
            executionRoleArn=role_arn,
            definition=flow_def
        )

        logger.info("Successfully created flow: %s. ID: %s",
                    flow_name,
                    {response['id']})

        return response

    except ClientError as e:
        logger.exception("Client error creating flow: %s", {str(e)})
        raise

    except Exception as e:
        logger.exception("Unexepcted error creating flow: %s", {str(e)})
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンス**の「[CreateFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlow)」を参照してください。

### `CreateFlowAlias`
<a name="bedrock-agent_CreateFlowAlias_python_3_topic"></a>

次のコード例は、`CreateFlowAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのエイリアスを作成します。  

```
def create_flow_alias(client, flow_id, flow_version, name, description):
    """
    Creates an alias for an Amazon Bedrock flow.

    Args:
        client: bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.

    Returns:
        str: The ID for the flow alias.
    """

    try:
        logger.info("Creating flow alias for flow: %s.", flow_id)

        response = client.create_flow_alias(
            flowIdentifier=flow_id,
            name=name,
            description=description,
            routingConfiguration=[
                {
                    "flowVersion": flow_version
                }
            ]
        )
        logger.info("Successfully created flow alias for %s.", flow_id)

        return response['id']

    except ClientError as e:
        logging.exception("Client error creating alias for flow: %s - %s",
                flow_id, str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected error creating alias for flow : %s - %s",
                flow_id, str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlowAlias)」を参照してください。**

### `CreateFlowVersion`
<a name="bedrock-agent_CreateFlowVersion_python_3_topic"></a>

次のコード例は、`CreateFlowVersion` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのバージョンを作成します。  

```
def create_flow_version(client, flow_id, description):
    """
    Creates a version of an Amazon Bedrock flow.

    Args:
        client: Amazon Bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.
        description (str) : A description for the flow.

    Returns:
        str: The version for the flow.
    """
    try:

        logger.info("Creating flow version for flow: %s.", flow_id)

        # Call CreateFlowVersion operation
        response = client.create_flow_version(
            flowIdentifier=flow_id,
            description=description
        )

        logging.info("Successfully created flow version %s for flow %s.",
            response['version'], flow_id)
        
        return response['version']

    except ClientError as e:
        logging.exception("Client error creating flow: %s", str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected error creating flow : %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlowVersion)」を参照してください。**

### `CreateKnowledgeBase`
<a name="bedrock-agent_CreateKnowledgeBase_python_3_topic"></a>

次のコード例は、`CreateKnowledgeBase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock ナレッジベースを作成します。  

```
def create_knowledge_base(bedrock_agent_client, name, role_arn, description=None):
    """
    Creates a new knowledge base.

    Args:
        bedrock_agent_client: The Boto3 Bedrock Agent client.
        name (str): The name of the knowledge base.
        role_arn (str): The ARN of the IAM role that the knowledge base assumes to access resources.
        description (str, optional): A description of the knowledge base.

    Returns:
        dict: The details of the created knowledge base.
    """
    try:
        kwargs = {
            "name": name,
            "roleArn": role_arn,
            "knowledgeBaseConfiguration": {
                "type": "VECTOR",
                "vectorKnowledgeBaseConfiguration": {
                    "embeddingModelArn": "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v1"
                }
            },
            "storageConfiguration": {
                "type": "OPENSEARCH_SERVERLESS",
                # Note: You will need to create an OpenSearch Serverless collection first and replace this ARN
                # with your actual collection ARN from the OpenSearch console. If you use the console instead,
                # you can use the quick-create flow to have Knowledge Bases create the collection for you.
                "opensearchServerlessConfiguration": {
                    "collectionArn": "arn:aws:aoss:us-east-1::123456789012:collection/abcdefgh12345678defgh",
                        "fieldMapping": {
                        "metadataField": "metadata",
                        "textField": "text",
                        "vectorField": "vector"
                        },
                    "vectorIndexName": "test-uuid"
                    },
                },
            "clientToken": "test-client-token-" + str(uuid.uuid4())
        }
        
        if description:
            kwargs["description"] = description
            
        response = bedrock_agent_client.create_knowledge_base(**kwargs)
        
        logger.info("Created knowledge base with ID: %s", response["knowledgeBase"]["knowledgeBaseId"])
        return response["knowledgeBase"]
    
    except ClientError as err:
        logger.error(
            "Couldn't create knowledge base. Here's why: %s: %s",
            err.response["Error"]["Code"],
            err.response["Error"]["Message"],
        )
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateKnowledgeBase](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateKnowledgeBase)」を参照してください。**

### `CreatePrompt`
<a name="bedrock-agent_CreatePrompt_python_3_topic"></a>

次のコード例は、`CreatePrompt` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock マネージドプロンプトを作成します。  

```
def create_prompt(client, prompt_name, prompt_description, prompt_template, model_id=None):
    """
    Creates an Amazon Bedrock managed prompt.

    Args:
    client: Amazon Bedrock Agent boto3 client.
    prompt_name (str): The name for the new prompt.
    prompt_description (str): The description for the new prompt.
    prompt_template (str): The template for the prompt.
    model_id (str, optional): The model ID to associate with the prompt.

    Returns:
        dict: The response from CreatePrompt.
    """
    try:
        logger.info("Creating prompt: %s.", prompt_name)
        
        # Create a variant with the template
        variant = {
            "name": "default",
            "templateType": "TEXT",
            "templateConfiguration": {
                "text": {
                    "text": prompt_template,
                    "inputVariables": []
                }
            }
        }
        
        # Extract input variables from the template
        # Look for patterns like {{variable_name}}

        variables = re.findall(r'{{(.*?)}}', prompt_template)
        for var in variables:
            variant["templateConfiguration"]["text"]["inputVariables"].append({"name": var.strip()})
        
        # Add model ID if provided
        if model_id:
            variant["modelId"] = model_id
        
        # Create the prompt with the variant
        create_params = {
            'name': prompt_name,
            'description': prompt_description,
            'variants': [variant]
        }
            
        response = client.create_prompt(**create_params)

        logger.info("Successfully created prompt: %s. ID: %s",
                    prompt_name,
                    response['id'])

        return response

    except ClientError as e:
        logger.exception("Client error creating prompt: %s", str(e))
        raise

    except Exception as e:
        logger.exception("Unexpected error creating prompt: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreatePrompt](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreatePrompt)」を参照してください。**

### `CreatePromptVersion`
<a name="bedrock-agent_CreatePromptVersion_python_3_topic"></a>

次のコード例は、`CreatePromptVersion` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock マネージドプロンプトのバージョンを作成します。  

```
def create_prompt_version(client, prompt_id, description=None):
    """
    Creates a version of an Amazon Bedrock managed prompt.

    Args:
    client: Amazon Bedrock Agent boto3 client.
    prompt_id (str): The identifier of the prompt to create a version for.
    description (str, optional): A description for the version.

    Returns:
        dict: The response from CreatePromptVersion.
    """
    try:
        logger.info("Creating version for prompt ID: %s.", prompt_id)
        
        create_params = {
            'promptIdentifier': prompt_id
        }
        
        if description:
            create_params['description'] = description
            
        response = client.create_prompt_version(**create_params)

        logger.info("Successfully created prompt version: %s", response['version'])
        logger.info("Prompt version ARN: %s", response['arn'])

        return response


    except ClientError as e:
        logger.exception("Client error creating prompt version: %s", str(e))
        raise

    except Exception as e:
        logger.exception("Unexpected error creating prompt version: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreatePromptVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreatePromptVersion)」を参照してください。**

### `DeleteAgent`
<a name="bedrock-agent_DeleteAgent_python_3_topic"></a>

次のコード例は、`DeleteAgent` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントを削除します。  

```
    def delete_agent(self, agent_id):
        """
        Deletes an Amazon Bedrock agent.

        :param agent_id: The unique identifier of the agent to delete.
        :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception.
        """

        try:
            response = self.client.delete_agent(
                agentId=agent_id, skipResourceInUseCheck=False
            )
        except ClientError as e:
            logger.error(f"Couldn't delete agent. {e}")
            raise
        else:
            return response
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[DeleteAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteAgent)」を参照してください。

### `DeleteAgentAlias`
<a name="bedrock-agent_DeleteAgentAlias_python_3_topic"></a>

次のコード例は、`DeleteAgentAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントエイリアスを削除します。  

```
    def delete_agent_alias(self, agent_id, agent_alias_id):
        """
        Deletes an alias of an Amazon Bedrock agent.

        :param agent_id: The unique identifier of the agent that the alias belongs to.
        :param agent_alias_id: The unique identifier of the alias to delete.
        :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception.
        """

        try:
            response = self.client.delete_agent_alias(
                agentId=agent_id, agentAliasId=agent_alias_id
            )
        except ClientError as e:
            logger.error(f"Couldn't delete agent alias. {e}")
            raise
        else:
            return response
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[DeleteAgentAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteAgentAlias)」を参照してください。

### `DeleteFlow`
<a name="bedrock-agent_DeleteFlow_python_3_topic"></a>

次のコード例は、`DeleteFlow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローを削除します。  

```
def delete_flow(client, flow_id):
    """
    Deletes an Amazon Bedrock flow.

    Args:
    client: Amazon Bedrock agent boto3 client.
    flow_id (str): The identifier of the flow that you want to delete.

    Returns:
        dict: The response from the DeleteFLow operation.
    """
    try:

        logger.info("Deleting flow ID: %s.",
                    flow_id)

        # Call DeleteFlow operation
        response = client.delete_flow(
            flowIdentifier=flow_id,
            skipResourceInUseCheck=True
        )

        logger.info("Finished deleting flow ID: %s", flow_id)

        return response

    except ClientError as e:
        logger.exception("Client error deleting flow: %s", {str(e)})
        raise

    except Exception as e:
        logger.exception("Unexepcted error deleting flow: %s", {str(e)})
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlow)」を参照してください。**

### `DeleteFlowAlias`
<a name="bedrock-agent_DeleteFlowAlias_python_3_topic"></a>

次のコード例は、`DeleteFlowAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのエイリアスを削除します。  

```
def delete_flow_alias(client, flow_id, flow_alias_id):
    """
    Deletes an Amazon Bedrock flow alias.

    Args:
        client: bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.

    Returns:
        dict: The response from the call to DetectFLowAlias
    """
    try:

        logger.info("Deleting flow alias %s for flow: %s.", flow_alias_id, flow_id)

        # Delete the flow alias.
        response = client.delete_flow_alias(
            aliasIdentifier=flow_alias_id,
            flowIdentifier=flow_id
        )

        logging.info("Successfully deleted flow version for %s.", flow_id)
        return response

    except ClientError as e:
        logging.exception("Client error deleting flow version: %s", str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected deleting flow version: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlowAlias)」を参照してください。**

### `DeleteFlowVersion`
<a name="bedrock-agent_DeleteFlowVersion_python_3_topic"></a>

次のコード例は、`DeleteFlowVersion` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのバージョンを削除します。  

```
def delete_flow_version(client, flow_id, flow_version):
    """
    Deletes a version of an Amazon Bedrock flow.

    Args:
        client: Amazon Bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.

    Returns:
        dict: The response from DeleteFlowVersion.
    """
    try:

        logger.info("Deleting flow version %s for flow: %s.",flow_version, flow_id)

        # Call DeleteFlowVersion operation
        response = client.delete_flow_version(
            flowIdentifier=flow_id,
            flowVersion=flow_version
        )

        logging.info("Successfully deleted flow version %s for %s.",
                flow_version,
                flow_id)
        return response

    except ClientError as e:
        logging.exception("Client error deleting flow version: %s ", str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected deleting flow version: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlowVersion)」を参照してください。**

### `DeleteKnowledgeBase`
<a name="bedrock-agent_DeleteKnowledgeBase_python_3_topic"></a>

次のコード例は、`DeleteKnowledgeBase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock ナレッジベースを削除します。  

```
def delete_knowledge_base(bedrock_agent_client, knowledge_base_id):
    """
    Deletes a knowledge base.

    Args:
        bedrock_agent_client: The Boto3 Bedrock Agent client.
        knowledge_base_id (str): The ID of the knowledge base to delete.

    Returns:
        bool: True if the deletion was successful.
    """
    try:
        bedrock_agent_client.delete_knowledge_base(
            knowledgeBaseId=knowledge_base_id
        )
        
        logger.info("Deleted knowledge base: %s", knowledge_base_id)
        return True
    except ClientError as err:
        logger.error(
            "Couldn't delete knowledge base %s. Here's why: %s: %s",
            knowledge_base_id,
            err.response["Error"]["Code"],
            err.response["Error"]["Message"],
        )
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteKnowledgeBase](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteKnowledgeBase)」を参照してください。**

### `DeletePrompt`
<a name="bedrock-agent_DeletePrompt_python_3_topic"></a>

次のコード例は、`DeletePrompt` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock マネージドプロンプトを削除します。  

```
def delete_prompt(client, prompt_id):
    """
    Deletes an Amazon Bedrock managed prompt.

    Args:
    client: Amazon Bedrock Agent boto3 client.
    prompt_id (str): The identifier of the prompt that you want to delete.

    Returns:
        dict: The response from the DeletePrompt operation.
    """
    try:
        logger.info("Deleting prompt ID: %s.", prompt_id)

        response = client.delete_prompt(
            promptIdentifier=prompt_id
        )

        logger.info("Finished deleting prompt ID: %s", prompt_id)

        return response

    except ClientError as e:
        logger.exception("Client error deleting prompt: %s", str(e))
        raise

    except Exception as e:
        logger.exception("Unexpected error deleting prompt: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeletePrompt](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeletePrompt)」を参照してください。**

### `GetAgent`
<a name="bedrock-agent_GetAgent_python_3_topic"></a>

次のコード例は、`GetAgent` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントを取得します。  

```
    def get_agent(self, agent_id, log_error=True):
        """
        Gets information about an agent.

        :param agent_id: The unique identifier of the agent.
        :param log_error: Whether to log any errors that occur when getting the agent.
                          If True, errors will be logged to the logger. If False, errors
                          will still be raised, but not logged.
        :return: The information about the requested agent.
        """

        try:
            response = self.client.get_agent(agentId=agent_id)
            agent = response["agent"]
        except ClientError as e:
            if log_error:
                logger.error(f"Couldn't get agent {agent_id}. {e}")
            raise
        else:
            return agent
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス**」の「[GetAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetAgent)」を参照してください。

### `GetFlow`
<a name="bedrock-agent_GetFlow_python_3_topic"></a>

次のコード例は、`GetFlow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローを取得します。  

```
def get_flow(client, flow_id):
    """
    Gets an Amazon Bedrock flow.

    Args:
    client: bedrock agent boto3 client.
        flow_id (str): The identifier of the flow that you want to get.

    Returns:
        dict: The response from the GetFlow operation.
    """
    try:

        logger.info("Getting flow ID: %s.",
                    flow_id)

        # Call GetFlow operation.
        response = client.get_flow(
            flowIdentifier=flow_id
        )

        logger.info("Retrieved flow ID: %s. Name: %s", flow_id,
                    response['name'])

        return response

    except ClientError as e:
        logger.exception("Client error getting flow: %s", {str(e)})
        raise

    except Exception as e:
        logger.exception("Unexepcted error getting flow: %s", {str(e)})
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlow)」を参照してください。**

### `GetFlowVersion`
<a name="bedrock-agent_GetFlowVersion_python_3_topic"></a>

次のコード例は、`GetFlowVersion` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのバージョンを取得します。  

```
def get_flow_version(client, flow_id, flow_version):
    """
    Gets information about a version of an Amazon Bedrock flow.

    Args:
        client: Amazon Bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.
        flow_version (str): The flow version of the flow.

    Returns:
        dict: The response from the call to GetFlowVersion.
    """
    try:

        logger.info("Deleting flow version for flow: %s.", flow_id)

        # Call GetFlowVersion operation
        response = client.get_flow_version(
            flowIdentifier=flow_id,
            flowVersion=flow_version
        )

        logging.info("Successfully got flow version %s information for flow %s.",
                    flow_version,
                    flow_id)
        
        return response

    except ClientError as e:
        logging.exception("Client error getting flow version: %s", str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected error getting flow version: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlowVersion)」を参照してください。**

### `GetKnowledgeBase`
<a name="bedrock-agent_GetKnowledgeBase_python_3_topic"></a>

次のコード例は、`GetKnowledgeBase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock ナレッジベースを取得します。  

```
def get_knowledge_base(bedrock_agent_client, knowledge_base_id):
    """
    Gets details about a specific knowledge base.

    Args:
        bedrock_agent_client: The Boto3 Bedrock Agent client.
        knowledge_base_id (str): The ID of the knowledge base.

    Returns:
        dict: The details of the knowledge base.
    """
    try:
        response = bedrock_agent_client.get_knowledge_base(
            knowledgeBaseId=knowledge_base_id
        )
        
        logger.info("Retrieved knowledge base: %s", knowledge_base_id)
        return response["knowledgeBase"]
    except ClientError as err:
        logger.error(
            "Couldn't get knowledge base %s. Here's why: %s: %s",
            knowledge_base_id,
            err.response["Error"]["Code"],
            err.response["Error"]["Message"],
        )
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetKnowledgeBase](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetKnowledgeBase)」を参照してください。**

### `GetPrompt`
<a name="bedrock-agent_GetPrompt_python_3_topic"></a>

次のコード例は、`GetPrompt` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock マネージドプロンプトを取得します。  

```
def get_prompt(client, prompt_id):
    """
    Gets an Amazon Bedrock managed prompt.

    Args:
    client: Amazon Bedrock Agent boto3 client.
    prompt_id (str): The identifier of the prompt that you want to get.

    Returns:
        dict: The response from the GetPrompt operation.
    """
    try:
        logger.info("Getting prompt ID: %s.", prompt_id)

        response = client.get_prompt(
            promptIdentifier=prompt_id
        )

        logger.info("Retrieved prompt ID: %s. Name: %s", 
                    prompt_id,
                    response['name'])

        return response

    except ClientError as e:
        logger.exception("Client error getting prompt: %s", str(e))
        raise

    except Exception as e:
        logger.exception("Unexpected error getting prompt: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetPrompt](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetPrompt)」を参照してください。**

### `ListAgentActionGroups`
<a name="bedrock-agent_ListAgentActionGroups_python_3_topic"></a>

次のコード例は、`ListAgentActionGroups` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントのアクショングループを一覧表示します。  

```
    def list_agent_action_groups(self, agent_id, agent_version):
        """
        List the action groups for a version of an Amazon Bedrock Agent.

        :param agent_id: The unique identifier of the agent.
        :param agent_version: The version of the agent.
        :return: The list of action group summaries for the version of the agent.
        """

        try:
            action_groups = []

            paginator = self.client.get_paginator("list_agent_action_groups")
            for page in paginator.paginate(
                    agentId=agent_id,
                    agentVersion=agent_version,
                    PaginationConfig={"PageSize": 10},
            ):
                action_groups.extend(page["actionGroupSummaries"])

        except ClientError as e:
            logger.error(f"Couldn't list action groups. {e}")
            raise
        else:
            return action_groups
```
+  API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の「[ListAgentActionGroups](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListAgentActionGroups)」を参照してください。

### `ListAgentKnowledgeBases`
<a name="bedrock-agent_ListAgentKnowledgeBases_python_3_topic"></a>

次のコード例は、`ListAgentKnowledgeBases` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントに関連するナレッジベースを一覧表示します。  

```
    def list_agent_knowledge_bases(self, agent_id, agent_version):
        """
        List the knowledge bases associated with a version of an Amazon Bedrock Agent.

        :param agent_id: The unique identifier of the agent.
        :param agent_version: The version of the agent.
        :return: The list of knowledge base summaries for the version of the agent.
        """

        try:
            knowledge_bases = []

            paginator = self.client.get_paginator("list_agent_knowledge_bases")
            for page in paginator.paginate(
                    agentId=agent_id,
                    agentVersion=agent_version,
                    PaginationConfig={"PageSize": 10},
            ):
                knowledge_bases.extend(page["agentKnowledgeBaseSummaries"])

        except ClientError as e:
            logger.error(f"Couldn't list knowledge bases. {e}")
            raise
        else:
            return knowledge_bases
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[ListAgentKnowledgeBases](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListAgentKnowledgeBases)」を参照してください。

### `ListAgents`
<a name="bedrock-agent_ListAgents_python_3_topic"></a>

次のコード例は、`ListAgents` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
アカウントに属するエージェントを一覧表示します。  

```
    def list_agents(self):
        """
        List the available Amazon Bedrock Agents.

        :return: The list of available bedrock agents.
        """

        try:
            all_agents = []

            paginator = self.client.get_paginator("list_agents")
            for page in paginator.paginate(PaginationConfig={"PageSize": 10}):
                all_agents.extend(page["agentSummaries"])

        except ClientError as e:
            logger.error(f"Couldn't list agents. {e}")
            raise
        else:
            return all_agents
```
+  API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の「[ListAgents](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListAgents)」を参照してください。

### `ListFlowAliases`
<a name="bedrock-agent_ListFlowAliases_python_3_topic"></a>

次のコード例は、`ListFlowAliases` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのエイリアスを一覧表示します。  

```
def list_flow_aliases(client, flow_id):
    """
    Lists the aliases of an Amazon Bedrock flow.

    Args:
        client: bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.

    Returns:
        dict: The response from ListFlowAliases.
    """
    try:

        finished = False

        logger.info("Listing flow aliases for flow: %s.", flow_id)

        print(f"Aliases for flow: {flow_id}")

        response = client.list_flow_aliases(
            flowIdentifier=flow_id,
            maxResults=10)

        while finished is False:

            for alias in response['flowAliasSummaries']:
                print(f"Alias Name: {alias['name']}")
                print(f"ID: {alias['id']}")
                print(f"Description: {alias.get('description', 'No description')}\n") 

                if 'nextToken' in response:
                    next_token = response['nextToken']
                    response = client.list_flow_aliases(maxResults=10,
                                                nextToken=next_token)
                else:
                    finished = True

        logging.info("Successfully listed flow aliases for flow %s.",
                flow_id)
        
        return response

    except ClientError as e:
        logging.exception("Client error listing flow aliases: %s", str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected error listing flow aliases: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListFlowAliases](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListFlowAliases)」を参照してください。**

### `ListFlowVersions`
<a name="bedrock-agent_ListFlowVersions_python_3_topic"></a>

次のコード例は、`ListFlowVersions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのバージョンを一覧表示します。  

```
def list_flow_versions(client, flow_id):
    """
    Lists the versions of an Amazon Bedrock flow.

    Args:
        client: Amazon bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.

    Returns:
        dict: The response from ListFlowVersions.
    """
    try:

        finished = False

        logger.info("Listing flow versions for flow: %s.", flow_id)

        response = client.list_flow_versions(
            flowIdentifier=flow_id,
            maxResults=10)

        while finished is False:

            print(f"Versions for flow:{flow_id}")
            for version in response['flowVersionSummaries']:
                print(f"Version: {version['version']}")
                print(f"Status: {version['status']}\n")

                if 'nextToken' in response:
                    next_token = response['nextToken']
                    response = client.list_flow_versions(maxResults=10,
                                                nextToken=next_token)
                else:
                    finished = True


        logging.info("Successfully listed flow versions for flow %s.",
                flow_id)
        
        return response

    except ClientError as e:
        logging.exception("Client error listing flow versions: %s", str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected error listing flow versions: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListFlowVersions](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListFlowVersions)」を参照してください。**

### `ListFlows`
<a name="bedrock-agent_ListFlows_python_3_topic"></a>

次のコード例は、`ListFlows` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローを一覧表示します。  

```
def list_flows(client):
    """
    Lists versions of an Amazon Bedrock flow.

    Args:
        client: Amazon Bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.

    Returns:
        Nothing.
    """
    try:
        finished = False

        logger.info("Listing flows:")

        response = client.list_flows(maxResults=10)

        while finished is False:

            for flow in response['flowSummaries']:
                print(f"ID: {flow['id']}")
                print(f"Name: {flow['name']}")
                print(
                    f"Description: {flow.get('description', 'No description')}")
                print(f"Latest version: {flow['version']}")
                print(f"Status: {flow['status']}\n")

            if 'nextToken' in response:
                next_token = response['nextToken']
                response = client.list_flows(maxResults=10,
                                             nextToken=next_token)
            else:
                finished = True

        logging.info("Successfully listed flows.")


    except ClientError as e:
        logging.exception("Client error listing flow versions: %s", str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected error listing flow versions: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListFlows](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListFlows)」を参照してください。**

### `ListKnowledgeBases`
<a name="bedrock-agent_ListKnowledgeBases_python_3_topic"></a>

次のコード例は、`ListKnowledgeBases` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock ナレッジベースを一覧表示します。  

```
def list_knowledge_bases(bedrock_agent_client, max_results=None):
    """
    Lists the knowledge bases in your AWS account.

    Args:
        bedrock_agent_client: The Boto3 Bedrock Agent client.
        max_results (int, optional): The maximum number of knowledge bases to return.

    Returns:
        list: A list of knowledge base details.
    """
    try:
        kwargs = {}
        if max_results is not None:
            kwargs["maxResults"] = max_results

        # Initialize an empty list to store all knowledge bases
        all_knowledge_bases = []
        
        # Use paginator to handle pagination automatically
        paginator = bedrock_agent_client.get_paginator('list_knowledge_bases')
        page_iterator = paginator.paginate(**kwargs)
        
        # Iterate through each page of results
        for page in page_iterator:
            all_knowledge_bases.extend(page.get('knowledgeBaseSummaries', []))
            
        logger.info("Found %s knowledge bases.", len(all_knowledge_bases))
        return all_knowledge_bases
    except ClientError as err:
        logger.error(
            "Couldn't list knowledge bases. Here's why: %s: %s",
            err.response["Error"]["Code"],
            err.response["Error"]["Message"],
        )
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListKnowledgeBases](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListKnowledgeBases)」を参照してください。**

### `ListPrompts`
<a name="bedrock-agent_ListPrompts_python_3_topic"></a>

次のコード例は、`ListPrompts` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock マネージドプロンプトを一覧表示します。  

```
def list_prompts(client, max_results=10):
    """
    Lists Amazon Bedrock managed prompts.

    Args:
        client: Amazon Bedrock Agent boto3 client.
        max_results (int): Maximum number of results to return per page.

    Returns:
        list: A list of prompt summaries.
    """
    try:
        logger.info("Listing prompts:")
        
        # Create a paginator for the list_prompts operation
        paginator = client.get_paginator('list_prompts')
        
        # Create the pagination parameters
        pagination_config = {
            'maxResults': max_results
        }
        
        # Initialize an empty list to store all prompts
        all_prompts = []
        
        # Iterate through all pages
        for page in paginator.paginate(**pagination_config):
            all_prompts.extend(page.get('promptSummaries', []))
            
        logger.info("Successfully listed %s prompts.", len(all_prompts))
        return all_prompts
        
    except ClientError as e:
        logger.exception("Client error listing prompts: %s", str(e))
        raise
    except Exception as e:
        logger.exception("Unexpected error listing prompts: %s", str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListPrompts](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListPrompts)」を参照してください。**

### `PrepareAgent`
<a name="bedrock-agent_PrepareAgent_python_3_topic"></a>

次のコード例は、`PrepareAgent` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
内部テスト用のエージェントを準備します。  

```
    def prepare_agent(self, agent_id):
        """
        Creates a DRAFT version of the agent that can be used for internal testing.

        :param agent_id: The unique identifier of the agent to prepare.
        :return: The response from Amazon Bedrock Agents if successful, otherwise raises an exception.
        """
        try:
            prepared_agent_details = self.client.prepare_agent(agentId=agent_id)
        except ClientError as e:
            logger.error(f"Couldn't prepare agent. {e}")
            raise
        else:
            return prepared_agent_details
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[PrepareAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/PrepareAgent)」を参照してください。

### `PrepareFlow`
<a name="bedrock-agent_PrepareFlow_python_3_topic"></a>

次のコード例は、`PrepareFlow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローを準備します。  

```
def prepare_flow(client, flow_id):
    """
    Prepares an Amazon Bedrock Flow.

    Args:
        client: Amazon Bedrock agent boto3 client.
        flow_id (str): The identifier of the flow that you want to prepare.

    Returns:
        str: The status of the flow preparation
    """
    try:

        # Prepare the flow.
        logger.info("Preparing flow ID: %s",
                    flow_id)

        response = client.prepare_flow(
            flowIdentifier=flow_id
        )

        status = response.get('status')

        while status == "Preparing":
            logger.info("Preparing flow ID: %s. Status %s",
                        flow_id, status)

            sleep(5)
            response = client.get_flow(
                flowIdentifier=flow_id
            )
            status = response.get('status')
            print(f"Flow Status: {status}")

        if status == "Prepared":
            logger.info("Finished preparing flow ID: %s. Status %s",
                        flow_id, status)
        else:
            logger.warning("flow ID: %s not prepared. Status %s",
                           flow_id, status)

        return status

    except ClientError as e:
        logger.exception("Client error preparing flow: %s", {str(e)})
        raise

    except Exception as e:
        logger.exception("Unexepcted error preparing flow: %s", {str(e)})
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[PrepareFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/PrepareFlow)」を参照してください。**

### `UpdateFlow`
<a name="bedrock-agent_UpdateFlow_python_3_topic"></a>

次のコード例は、`UpdateFlow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローを更新します。  

```
def update_flow(client, flow_id, flow_name, flow_description, role_arn, flow_def):
    """
    Updates an Amazon Bedrock flow.

    Args:
    client: bedrock agent boto3 client.
    flow_id (str): The ID for the flow that you want to update.
    flow_name (str): The name for the flow.
    role_arn (str):  The ARN for the IAM role that use flow uses.
    flow_def (json): The JSON definition of the flow that you want to create.

    Returns:
        dict: Flow information if successful.
    """
    try:

        logger.info("Updating flow: %s.", flow_id)

        response = client.update_flow(
            flowIdentifier=flow_id,
            name=flow_name,
            description=flow_description,
            executionRoleArn=role_arn,
            definition=flow_def
        )

        logger.info("Successfully updated flow: %s. ID: %s",
                    flow_name,
                    {response['id']})

        return response

    except ClientError as e:
        logger.exception("Client error updating flow: %s", {str(e)})
        raise

    except Exception as e:
        logger.exception("Unexepcted error updating flow: %s", {str(e)})
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[UpdateFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/UpdateFlow)」を参照してください。**

### `UpdateFlowAlias`
<a name="bedrock-agent_UpdateFlowAlias_python_3_topic"></a>

次のコード例は、`UpdateFlowAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock フローのエイリアスを更新します。  

```
def update_flow_alias(client, flow_id, alias_id, flow_version, name, description):
    """
    Updates an alias for an Amazon Bedrock flow.

    Args:
        client: bedrock agent boto3 client.
        flow_id (str): The identifier of the flow.

    Returns:
        str: The response from UpdateFlowAlias.
    """

    try:
        logger.info("Updating flow alias %s for flow: %s.", alias_id, flow_id)

        response = client.update_flow_alias(
            aliasIdentifier=alias_id,
            flowIdentifier=flow_id,
            name=name,
            description=description,
            routingConfiguration=[
                {
                    "flowVersion": flow_version
                }
            ]
        )
        logger.info("Successfully updated flow alias %s for %s.", alias_id, flow_id)

        return response

    except ClientError as e:
        logging.exception("Client error updating alias %s for flow: %s - %s",
                alias_id, flow_id, str(e))
        raise
    except Exception as e:
        logging.exception("Unexpected error updating alias %s for flow : %s - %s",
                alias_id, flow_id, str(e))
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[UpdateFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/UpdateFlowAlias)」を参照してください。**

### `UpdateKnowledgeBase`
<a name="bedrock-agent_UpdateKnowledgeBase_python_3_topic"></a>

次のコード例は、`UpdateKnowledgeBase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
Amazon Bedrock ナレッジベースを更新します。  

```
def update_knowledge_base(bedrock_agent_client, knowledge_base_id, name=None, description=None, role_arn=None):
    """
    Updates an existing knowledge base.

    Args:
        bedrock_agent_client: The Boto3 Bedrock Agent client.
        knowledge_base_id (str): The ID of the knowledge base to update.
        name (str, optional): The new name for the knowledge base.
        description (str, optional): The new description for the knowledge base.
        role_arn (str, optional): The new IAM role ARN for the knowledge base.

    Returns:
        dict: The details of the updated knowledge base.
    """
    try:
        kwargs = {
            "knowledgeBaseId": knowledge_base_id,
            "knowledgeBaseConfiguration": {
                "type": "VECTOR",
                "vectorKnowledgeBaseConfiguration": {
                    "embeddingModelArn": "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v1"
                }
            }
        }
        
        if name:
            kwargs["name"] = name
        if description:
            kwargs["description"] = description
        if role_arn:
            kwargs["roleArn"] = role_arn
            
        response = bedrock_agent_client.update_knowledge_base(**kwargs)
        
        logger.info("Updated knowledge base: %s", knowledge_base_id)
        return response["knowledgeBase"]
    
    except ClientError as err:
        logger.error(
            "Couldn't update knowledge base %s. Here's why: %s: %s",
            knowledge_base_id,
            err.response["Error"]["Code"],
            err.response["Error"]["Message"],
        )
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの[UpdateKnowledgeBase](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/UpdateKnowledgeBase)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### フローを作成して呼び出す
<a name="bedrock-agent_GettingStartedWithBedrockFlows_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ フローの実行ロールを作成します。
+ フローを作成します。
+ 完全に設定されたフローをデプロイします。
+ ユーザー指定のプロンプトでフローを呼び出します。
+ すべての作成されたリソースを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
ユーザーが指定したジャンルと曲数に基づいて音楽プレイリストを生成します。  

```
from datetime import datetime
import logging
import boto3

from botocore.exceptions import ClientError

from roles import create_flow_role, delete_flow_role, update_role_policy
from flow import create_flow, prepare_flow, delete_flow
from run_flow import run_playlist_flow
from flow_version import create_flow_version, delete_flow_version
from flow_alias import create_flow_alias, delete_flow_alias

logging.basicConfig(
    level=logging.INFO
)
logger = logging.getLogger(__name__)

def create_input_node(name):
    """
    Creates an input node configuration for an Amazon Bedrock flow.

    The input node serves as the entry point for the flow and defines
    the initial document structure that will be passed to subsequent nodes.

    Args:
        name (str): The name of the input node.

    Returns:
        dict: The input node configuration.

    """
    return {
        "type": "Input",
        "name": name,
        "outputs": [
            {
                "name": "document",
                "type": "Object"
            }
        ]
    }


def create_prompt_node(name, model_id):
    """
    Creates a prompt node configuration for a Bedrock flow that generates music playlists.

    The prompt node defines an inline prompt template that creates a music playlist based on
    a specified genre and number of songs. The prompt uses two variables that are mapped from
    the input JSON object:
    - {{genre}}: The genre of music to create a playlist for
    - {{number}}: The number of songs to include in the playlist

    Args:
        name (str): The name of the prompt node.
        model_id (str): The identifier of the foundation model to use for the prompt.

    Returns:
        dict: The prompt node.

    """

    return {
        "type": "Prompt",
        "name": name,
        "configuration": {
            "prompt": {
                "sourceConfiguration": {
                    "inline": {
                        "modelId": model_id,
                        "templateType": "TEXT",
                        "inferenceConfiguration": {
                            "text": {
                                "temperature": 0.8
                            }
                        },
                        "templateConfiguration": {
                            "text": {
                                "text": "Make me a {{genre}} playlist consisting of the following number of songs: {{number}}."
                            }
                        }
                    }
                }
            }
        },
        "inputs": [
            {
                "name": "genre",
                "type": "String",
                "expression": "$.data.genre"
            },
            {
                "name": "number",
                "type": "Number",
                "expression": "$.data.number"
            }
        ],
        "outputs": [
            {
                "name": "modelCompletion",
                "type": "String"
            }
        ]
    }


def create_output_node(name):
    """
    Creates an output node configuration for a Bedrock flow.

    The output node validates that the output from the last node is a string
    and returns it unmodified. The input name must be "document".

    Args:
        name (str): The name of the output node.

    Returns:
        dict: The output node configuration containing the output node:

    """

    return {
        "type": "Output",
        "name": name,
        "inputs": [
            {
                "name": "document",
                "type": "String",
                "expression": "$.data"
            }
        ]
    }




def create_playlist_flow(client, flow_name, flow_description, role_arn, prompt_model_id):
    """
    Creates the playlist generator flow.
    Args:
        client: bedrock agent boto3 client.
        role_arn (str): Name for the new IAM role.
        prompt_model_id (str): The id of the model to use in the prompt node.
    Returns:
        dict: The response from the create_flow operation.
    """

    input_node = create_input_node("FlowInput")
    prompt_node = create_prompt_node("MakePlaylist", prompt_model_id)
    output_node = create_output_node("FlowOutput")

    # Create connections between the nodes
    connections = []

    #  First, create connections between the output of the flow 
    # input node and each input of the prompt node.
    for prompt_node_input in prompt_node["inputs"]:
        connections.append(
            {
                "name": "_".join([input_node["name"], prompt_node["name"],
                                   prompt_node_input["name"]]),
                "source": input_node["name"],
                "target": prompt_node["name"],
                "type": "Data",
                "configuration": {
                    "data": {
                        "sourceOutput": input_node["outputs"][0]["name"],
                        "targetInput": prompt_node_input["name"]
                    }
                }
            }
        )

    # Then, create a connection between the output of the prompt node and the input of the flow output node
    connections.append(
        {
            "name": "_".join([prompt_node["name"], output_node["name"]]),
            "source": prompt_node["name"],
            "target": output_node["name"],
            "type": "Data",
            "configuration": {
                "data": {
                    "sourceOutput": prompt_node["outputs"][0]["name"],
                    "targetInput": output_node["inputs"][0]["name"]
                }
            }
        }
    )

    flow_def = {
        "nodes": [input_node, prompt_node, output_node],
        "connections": connections
    }

    # Create the flow.

    response = create_flow(
        client, flow_name, flow_description, role_arn, flow_def)

    return response



def get_model_arn(client, model_id):
    """
    Gets the Amazon Resource Name (ARN) for a model.
    Args:
        client (str): Amazon Bedrock boto3 client.
        model_id (str): The id of the model.
    Returns:
        str: The ARN of the model.
    """

    try:
        # Call GetFoundationModelDetails operation
        response = client.get_foundation_model(modelIdentifier=model_id)

        # Extract model ARN from the response
        model_arn = response['modelDetails']['modelArn']

        return model_arn

    except ClientError as e:
        logger.exception("Client error getting model ARN: %s", {str(e)})
        raise

    except Exception as e:
        logger.exception("Unexpected error getting model ARN: %s", {str(e)})
        raise


def prepare_flow_version_and_alias(bedrock_agent_client,
                                   flow_id):
    """
    Prepares the flow and then creates a flow version and flow alias.
    Args:
        bedrock_agent_client: Amazon Bedrock Agent boto3 client.
        flowd_id (str): The ID of the flow that you want to prepare.
    Returns: The flow_version and flow_alias. 

    """

    status = prepare_flow(bedrock_agent_client, flow_id)

    flow_version = None
    flow_alias = None

    if status == 'Prepared':

        # Create the flow version and alias.
        flow_version = create_flow_version(bedrock_agent_client,
                                           flow_id,
                                           f"flow version for flow {flow_id}.")

        flow_alias = create_flow_alias(bedrock_agent_client,
                                       flow_id,
                                       flow_version,
                                       "latest",
                                       f"Alias for flow {flow_id}, version {flow_version}")

    return flow_version, flow_alias



def delete_role_resources(bedrock_agent_client,
                          iam_client,
                          role_name,
                          flow_id,
                          flow_version,
                          flow_alias):
    """
    Deletes the flow, flow alias, flow version, and IAM roles.
    Args:
        bedrock_agent_client: Amazon Bedrock Agent boto3 client.
        iam_client: Amazon IAM boto3 client.
        role_name (str): The name of the IAM role.
        flow_id (str): The id of the flow.
        flow_version (str): The version of the flow.
        flow_alias (str): The alias of the flow.
    """

    if flow_id is not None:
        if flow_alias is not None:
            delete_flow_alias(bedrock_agent_client, flow_id, flow_alias)
        if flow_version is not None:
            delete_flow_version(bedrock_agent_client,
                        flow_id, flow_version)
        delete_flow(bedrock_agent_client, flow_id)
    
    if role_name is not None:
        delete_flow_role(iam_client, role_name)



def main():
    """
    Creates, runs, and optionally deletes a Bedrock flow for generating music playlists.

    Note:
        Requires valid AWS credentials in the default profile
    """

    delete_choice = "y"
    try:

        # Get various boto3 clients.
        session = boto3.Session(profile_name='default')
        bedrock_agent_runtime_client = session.client('bedrock-agent-runtime')
        bedrock_agent_client = session.client('bedrock-agent')
        bedrock_client = session.client('bedrock')
        iam_client = session.client('iam')
        
        role_name = None
        flow_id = None
        flow_version = None
        flow_alias = None

        #Change the model as needed.
        prompt_model_id = "amazon.nova-pro-v1:0"

        # Base the flow name on the current date and time
        current_time = datetime.now()
        timestamp = current_time.strftime("%Y-%m-%d-%H-%M-%S")
        flow_name = f"FlowPlayList_{timestamp}"
        flow_description = "A flow to generate a music playlist."

        # Create a role for the flow.
        role_name = f"BedrockFlowRole-{flow_name}"
        role = create_flow_role(iam_client, role_name)
        role_arn = role['Arn']

        # Create the flow.
        response = create_playlist_flow(
            bedrock_agent_client, flow_name, flow_description, role_arn, prompt_model_id)
        flow_id = response.get('id')

        if flow_id:
            # Update accessible resources in the role.
            model_arn = get_model_arn(bedrock_client, prompt_model_id)
            update_role_policy(iam_client, role_name, [
                               response.get('arn'), model_arn])

            # Prepare the flow and flow version.
            flow_version, flow_alias = prepare_flow_version_and_alias(
                bedrock_agent_client, flow_id)

            # Run the flow.
            if flow_version and flow_alias:
                run_playlist_flow(bedrock_agent_runtime_client,
                                  flow_id, flow_alias)

                delete_choice = input("Delete flow? y or n : ").lower()


            else:
                print("Couldn't run. Deleting flow and role.")
                delete_flow(bedrock_agent_client, flow_id)
                delete_flow_role(iam_client, role_name)
        else:
            print("Couldn't create flow.")


    except Exception as e:
        print(f"Fatal error: {str(e)}")
    
    finally:
        if delete_choice == 'y':
                delete_role_resources(bedrock_agent_client,
                                          iam_client,
                                          role_name,
                                          flow_id,
                                          flow_version,
                                          flow_alias)
        else:
            print("Flow not deleted. ")
            print(f"\tFlow ID: {flow_id}")
            print(f"\tFlow version: {flow_version}")
            print(f"\tFlow alias: {flow_alias}")
            print(f"\tRole ARN: {role_arn}")
       
        print("Done!")
 
if __name__ == "__main__":
    main()


def invoke_flow(client, flow_id, flow_alias_id, input_data):
    """
    Invoke an Amazon Bedrock flow and handle the response stream.

    Args:
        client: Boto3 client for Amazon Bedrock agent runtime.
        flow_id: The ID of the flow to invoke.
        flow_alias_id: The alias ID of the flow.
        input_data: Input data for the flow.

    Returns:
        Dict containing flow status and flow output.
    """

    response = None
    request_params = None

    request_params = {
            "flowIdentifier": flow_id,
            "flowAliasIdentifier": flow_alias_id,
            "inputs": [input_data],
            "enableTrace": True
        }


    response = client.invoke_flow(**request_params)

    flow_status = ""
    output= ""

    # Process the streaming response
    for event in response['responseStream']:

        # Check if flow is complete.
        if 'flowCompletionEvent' in event:
            flow_status = event['flowCompletionEvent']['completionReason']

        # Save the model output.
        elif 'flowOutputEvent' in event:
            output = event['flowOutputEvent']['content']['document']
            logger.info("Output : %s", output)

        # Log trace events.
        elif 'flowTraceEvent' in event:
            logger.info("Flow trace:  %s", event['flowTraceEvent'])
    
    return {
        "flow_status": flow_status,
        "output": output

    }




def run_playlist_flow(bedrock_agent_client, flow_id, flow_alias_id):
    """
    Runs the playlist generator flow.

    Args:
        bedrock_agent_client: Boto3 client for Amazon Bedrock agent runtime.
        flow_id: The ID of the flow to run.
        flow_alias_id: The alias ID of the flow.

    """


    print ("Welcome to the playlist generator flow.")
    # Get the initial prompt from the user.
    genre = input("Enter genre: ")
    number_of_songs = int(input("Enter number of songs: "))


    # Use prompt to create input data for the input node.
    flow_input_data = {
        "content": {
            "document": {
                "genre" : genre,
                "number" : number_of_songs
            }
        },
        "nodeName": "FlowInput",
        "nodeOutputName": "document"
    }

    try:

        result = invoke_flow(
                bedrock_agent_client, flow_id, flow_alias_id, flow_input_data)

        status = result['flow_status']
  
        if status == "SUCCESS":
                # The flow completed successfully.
                logger.info("The flow %s successfully completed.", flow_id)
                print(result['output'])
        else:
            logger.warning("Flow status: %s",status)

    except ClientError as e:
        print(f"Client error: {str(e)}")
        logger.error("Client error: %s", {str(e)})
        raise

    except Exception as e:
        logger.error("An error occurred: %s", {str(e)})
        logger.error("Error type: %s", {type(e)})
        raise



def create_flow_role(client, role_name):
    """
    Creates an IAM role for Amazon Bedrock with permissions to run a flow.
    
    Args:
        role_name (str): Name for the new IAM role.
    Returns:
        str: The role Amazon Resource Name.
    """

    
    # Trust relationship policy - allows Amazon Bedrock service to assume this role.
    trust_policy = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{
            "Effect": "Allow",
            "Principal": {
                "Service": "bedrock.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }]
    }
    
    # Basic inline policy for for running a flow.

    resources = "*"

    bedrock_policy = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "bedrock:InvokeModel",
                    "bedrock:Retrieve",
                    "bedrock:RetrieveAndGenerate"
                ],
                # Using * as placeholder - Later you update with specific ARNs.
                "Resource": resources
            }
        ]
    }


    
    try:
        # Create the IAM role with trust policy
        logging.info("Creating role: %s",role_name)
        role = client.create_role(
            RoleName=role_name,
            AssumeRolePolicyDocument=json.dumps(trust_policy),
            Description="Role for Amazon Bedrock operations"
        )
        
        # Attach inline policy to the role
        print("Attaching inline policy")
        client.put_role_policy(
            RoleName=role_name,
            PolicyName=f"{role_name}-policy",
            PolicyDocument=json.dumps(bedrock_policy)
        )
        
        logging.info("Create Role ARN: %s", role['Role']['Arn'])
        return role['Role']
        
    except ClientError as e:
        logging.warning("Error creating role: %s", str(e))
        raise
    except Exception as e:
        logging.warning("Unexpected error: %s", str(e))
        raise


def update_role_policy(client, role_name, resource_arns):
    """
    Updates an IAM role's inline policy with specific resource ARNs.
    
    Args:
        role_name (str): Name of the existing role.
        resource_arns (list): List of resource ARNs to allow access to.
    """

    
    updated_policy = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "bedrock:GetFlow",
                    "bedrock:InvokeModel",
                    "bedrock:Retrieve",
                    "bedrock:RetrieveAndGenerate"
                ],
                "Resource": resource_arns
            }
        ]
    }
    
    try:
        client.put_role_policy(
            RoleName=role_name,
            PolicyName=f"{role_name}-policy",
            PolicyDocument=json.dumps(updated_policy)
        )
        logging.info("Updated policy for role: %s",role_name)
        
    except ClientError as e:
        logging.warning("Error updating role policy: %s", str(e))
        raise


def delete_flow_role(client, role_name):
    """
    Deletes an IAM role.

    Args:
        role_name (str): Name of the role to delete.
    """



    try:
        # Detach and delete inline policies
        policies = client.list_role_policies(RoleName=role_name)['PolicyNames']
        for policy_name in policies:
            client.delete_role_policy(RoleName=role_name, PolicyName=policy_name)

        # Delete the role
        client.delete_role(RoleName=role_name)
        logging.info("Deleted role: %s", role_name)


    except ClientError as e:
        logging.info("Error Deleting role: %s", str(e))
        raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlow)
  + [CreateFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlowAlias)
  + [CreateFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlowVersion)
  + [DeleteFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlow)
  + [DeleteFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlowAlias)
  + [DeleteFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlowVersion)
  + [GetFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlow)
  + [GetFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlowAlias)
  + [GetFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlowVersion)
  + [InvokeFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-runtime-2023-12-12/InvokeFlow)
  + [PrepareFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/PrepareFlow)

### マネージドプロンプトを作成して呼び出す
<a name="bedrock-agent_GettingStartedWithBedrockPrompts_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ マネージドプロンプトを作成する。
+ プロンプトのバージョンを作成する。
+ バージョンを使用してプロンプトを呼び出す。
+ リソースをクリーンアップする (オプション)。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
マネージドプロンプトを作成して呼び出します。  

```
import argparse
import boto3
import logging
import time

# Now import the modules
from prompt import create_prompt, create_prompt_version, delete_prompt
from run_prompt import invoke_prompt

logging.basicConfig(
    level=logging.INFO,
    format='%(levelname)s: %(message)s'
)
logger = logging.getLogger(__name__)



def run_scenario(bedrock_client, bedrock_runtime_client, model_id, cleanup=True):
    """
    Runs the Amazon Bedrock managed prompt scenario.
    
    Args:
        bedrock_client: The Amazon Bedrock Agent client.
        bedrock_runtime_client: The Amazon Bedrock Runtime client.
        model_id (str): The model ID to use for the prompt.
        cleanup (bool): Whether to clean up resources at the end of the scenario.
        
    Returns:
        dict: A dictionary containing the created resources.
    """
    prompt_id = None
    
    try:
        # Step 1: Create a prompt
        print("\n=== Step 1: Creating a prompt ===")
        prompt_name = f"PlaylistGenerator-{int(time.time())}"
        prompt_description = "Playlist generator"
        prompt_template = """
          Make me a {{genre}} playlist consisting of the following number of songs: {{number}}."""
        
        create_response = create_prompt(
            bedrock_client,
            prompt_name,
            prompt_description,
            prompt_template,
            model_id
        )
        
        prompt_id = create_response['id']
        print(f"Created prompt: {prompt_name} with ID: {prompt_id}")
        
        # Create a version of the prompt
        print("\n=== Creating a version of the prompt ===")
        version_response = create_prompt_version(
            bedrock_client,
            prompt_id,
            description="Initial version of the product description generator"
        )
        
        prompt_version_arn = version_response['arn']
        prompt_version = version_response['version']

        print(f"Created prompt version: {prompt_version}")
        print(f"Prompt version ARN: {prompt_version_arn}")
        
        # Step 2: Invoke the prompt directly
        print("\n=== Step 2: Invoking the prompt ===")
        input_variables = {
            "genre": "pop",
            "number": "2",
           }
        
        # Use the ARN from the create_prompt_version response
        result = invoke_prompt(
            bedrock_runtime_client,
            prompt_version_arn,  
            input_variables
        )
        # Display the playlist
        print(f"\n{result}")
    
        
        # Step 3: Clean up resources (optional)
        if cleanup:
            print("\n=== Step 3: Cleaning up resources ===")
            
            # Delete the prompt
            print(f"Deleting prompt {prompt_id}...")
            delete_prompt(bedrock_client, prompt_id)
            
            print("Cleanup complete")
        else:
            print("\n=== Resources were not cleaned up ===")
            print(f"Prompt ID: {prompt_id}")
        
   
        
    except Exception as e:
        logger.exception("Error in scenario: %s", str(e))
        
        # Attempt to clean up if an error occurred and cleanup was requested
        if cleanup and prompt_id:
            try:
                print("\nCleaning up resources after error...")
                
                # Delete the prompt
                try:
                    delete_prompt(bedrock_client, prompt_id)
                    print("Cleanup after error complete")
                except Exception as cleanup_error:
                    logger.error("Error during cleanup: %s", str(cleanup_error))
            except Exception as final_error:
                logger.error("Final error during cleanup: %s", str(final_error))
        
        # Re-raise the original exception
        raise

def main():
    """
    Entry point for the Amazon Bedrock managed prompt scenario.
    """
    parser = argparse.ArgumentParser(
        description="Run the Amazon Bedrock managed prompt scenario."
    )
    parser.add_argument(
        '--region',
        default='us-east-1',
        help="The AWS Region to use."
    )
    parser.add_argument(
        '--model-id',
        default='anthropic.claude-v2',
        help="The model ID to use for the prompt."
    )
    parser.add_argument(
        '--cleanup',
        action='store_true',
        default=True,
        help="Clean up resources at the end of the scenario."
    )
    parser.add_argument(
        '--no-cleanup',
        action='store_false',
        dest='cleanup',
        help="Don't clean up resources at the end of the scenario."
    )
    args = parser.parse_args()

    bedrock_client = boto3.client('bedrock-agent', region_name=args.region)
    bedrock_runtime_client = boto3.client('bedrock-runtime', region_name=args.region)
    
    print("=== Amazon Bedrock Managed Prompt Scenario ===")
    print(f"Region: {args.region}")
    print(f"Model ID: {args.model_id}")
    print(f"Cleanup resources: {args.cleanup}")
    
    try:
        run_scenario(
            bedrock_client,
            bedrock_runtime_client,
            args.model_id,
            args.cleanup
        )
        
    except Exception as e:
        logger.exception("Error running scenario: %s", str(e))
        
if __name__ == "__main__":
    main()
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [Converse](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/Converse)
  + [CreatePrompt](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreatePrompt)
  + [CreatePromptVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreatePromptVersion)
  + [DeletePrompt](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeletePrompt)

### エージェントを作成して呼び出す
<a name="bedrock-agent_GettingStartedWithBedrockAgents_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ エージェントの実行ロールを作成します。
+ エージェントを作成し、ドラフトバージョンをデプロイします。
+ エージェントの機能を実装する Lambda 関数を作成します。
+ エージェントを Lambda 関数に接続するアクショングループを作成します。
+ 完全に設定されたエージェントをデプロイします。
+ ユーザー指定のプロンプトでエージェントを呼び出します。
+ すべての作成されたリソースを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
エージェントを作成して呼び出します。  

```
REGION = "us-east-1"
ROLE_POLICY_NAME = "agent_permissions"


class BedrockAgentScenarioWrapper:
    """Runs a scenario that shows how to get started using Amazon Bedrock Agents."""

    def __init__(
            self, bedrock_agent_client, runtime_client, lambda_client, iam_resource, postfix
    ):
        self.iam_resource = iam_resource
        self.lambda_client = lambda_client
        self.bedrock_agent_runtime_client = runtime_client
        self.postfix = postfix

        self.bedrock_wrapper = BedrockAgentWrapper(bedrock_agent_client)

        self.agent = None
        self.agent_alias = None
        self.agent_role = None
        self.prepared_agent_details = None
        self.lambda_role = None
        self.lambda_function = None

    def run_scenario(self):
        print("=" * 88)
        print("Welcome to the Amazon Bedrock Agents demo.")
        print("=" * 88)

        # Query input from user
        print("Let's start with creating an agent:")
        print("-" * 40)
        name, foundation_model = self._request_name_and_model_from_user()
        print("-" * 40)

        # Create an execution role for the agent
        self.agent_role = self._create_agent_role(foundation_model)

        # Create the agent
        self.agent = self._create_agent(name, foundation_model)

        # Prepare a DRAFT version of the agent
        self.prepared_agent_details = self._prepare_agent()

        # Create the agent's Lambda function
        self.lambda_function = self._create_lambda_function()

        # Configure permissions for the agent to invoke the Lambda function
        self._allow_agent_to_invoke_function()
        self._let_function_accept_invocations_from_agent()

        # Create an action group to connect the agent with the Lambda function
        self._create_agent_action_group()

        # If the agent has been modified or any components have been added, prepare the agent again
        components = [self._get_agent()]
        components += self._get_agent_action_groups()
        components += self._get_agent_knowledge_bases()

        latest_update = max(component["updatedAt"] for component in components)
        if latest_update > self.prepared_agent_details["preparedAt"]:
            self.prepared_agent_details = self._prepare_agent()

        # Create an agent alias
        self.agent_alias = self._create_agent_alias()

        # Test the agent
        self._chat_with_agent(self.agent_alias)

        print("=" * 88)
        print("Thanks for running the demo!\n")

        if q.ask("Do you want to delete the created resources? [y/N] ", q.is_yesno):
            self._delete_resources()
            print("=" * 88)
            print(
                "All demo resources have been deleted. Thanks again for running the demo!"
            )
        else:
            self._list_resources()
            print("=" * 88)
            print("Thanks again for running the demo!")

    def _request_name_and_model_from_user(self):
        existing_agent_names = [
            agent["agentName"] for agent in self.bedrock_wrapper.list_agents()
        ]

        while True:
            name = q.ask("Enter an agent name: ", self.is_valid_agent_name)
            if name.lower() not in [n.lower() for n in existing_agent_names]:
                break
            print(
                f"Agent {name} conflicts with an existing agent. Please use a different name."
            )

        models = ["anthropic.claude-instant-v1", "anthropic.claude-v2"]
        model_id = models[
            q.choose("Which foundation model would you like to use? ", models)
        ]

        return name, model_id

    def _create_agent_role(self, model_id):
        role_name = f"AmazonBedrockExecutionRoleForAgents_{self.postfix}"
        model_arn = f"arn:aws:bedrock:{REGION}::foundation-model/{model_id}*"

        print("Creating an an execution role for the agent...")

        try:
            role = self.iam_resource.create_role(
                RoleName=role_name,
                AssumeRolePolicyDocument=json.dumps(
                    {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {"Service": "bedrock.amazonaws.com"},
                                "Action": "sts:AssumeRole",
                            }
                        ],
                    }
                ),
            )

            role.Policy(ROLE_POLICY_NAME).put(
                PolicyDocument=json.dumps(
                    {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Action": "bedrock:InvokeModel",
                                "Resource": model_arn,
                            }
                        ],
                    }
                )
            )
        except ClientError as e:
            logger.error(f"Couldn't create role {role_name}. Here's why: {e}")
            raise

        return role

    def _create_agent(self, name, model_id):
        print("Creating the agent...")

        instruction = """
            You are a friendly chat bot. You have access to a function called that returns
            information about the current date and time. When responding with date or time,
            please make sure to add the timezone UTC.
            """
        agent = self.bedrock_wrapper.create_agent(
            agent_name=name,
            foundation_model=model_id,
            instruction=instruction,
            role_arn=self.agent_role.arn,
        )
        self._wait_for_agent_status(agent["agentId"], "NOT_PREPARED")

        return agent

    def _prepare_agent(self):
        print("Preparing the agent...")

        agent_id = self.agent["agentId"]
        prepared_agent_details = self.bedrock_wrapper.prepare_agent(agent_id)
        self._wait_for_agent_status(agent_id, "PREPARED")

        return prepared_agent_details

    def _create_lambda_function(self):
        print("Creating the Lambda function...")

        function_name = f"AmazonBedrockExampleFunction_{self.postfix}"

        self.lambda_role = self._create_lambda_role()

        try:
            deployment_package = self._create_deployment_package(function_name)

            lambda_function = self.lambda_client.create_function(
                FunctionName=function_name,
                Description="Lambda function for Amazon Bedrock example",
                Runtime="python3.11",
                Role=self.lambda_role.arn,
                Handler=f"{function_name}.lambda_handler",
                Code={"ZipFile": deployment_package},
                Publish=True,
            )

            waiter = self.lambda_client.get_waiter("function_active_v2")
            waiter.wait(FunctionName=function_name)

        except ClientError as e:
            logger.error(
                f"Couldn't create Lambda function {function_name}. Here's why: {e}"
            )
            raise

        return lambda_function

    def _create_lambda_role(self):
        print("Creating an execution role for the Lambda function...")

        role_name = f"AmazonBedrockExecutionRoleForLambda_{self.postfix}"

        try:
            role = self.iam_resource.create_role(
                RoleName=role_name,
                AssumeRolePolicyDocument=json.dumps(
                    {
                        "Version":"2012-10-17",		 	 	 
                        "Statement": [
                            {
                                "Effect": "Allow",
                                "Principal": {"Service": "lambda.amazonaws.com"},
                                "Action": "sts:AssumeRole",
                            }
                        ],
                    }
                ),
            )
            role.attach_policy(
                PolicyArn="arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
            )
            print(f"Created role {role_name}")
        except ClientError as e:
            logger.error(f"Couldn't create role {role_name}. Here's why: {e}")
            raise

        print("Waiting for the execution role to be fully propagated...")
        wait(10)

        return role

    def _allow_agent_to_invoke_function(self):
        policy = self.iam_resource.RolePolicy(
            self.agent_role.role_name, ROLE_POLICY_NAME
        )
        doc = policy.policy_document
        doc["Statement"].append(
            {
                "Effect": "Allow",
                "Action": "lambda:InvokeFunction",
                "Resource": self.lambda_function["FunctionArn"],
            }
        )
        self.agent_role.Policy(ROLE_POLICY_NAME).put(PolicyDocument=json.dumps(doc))

    def _let_function_accept_invocations_from_agent(self):
        try:
            self.lambda_client.add_permission(
                FunctionName=self.lambda_function["FunctionName"],
                SourceArn=self.agent["agentArn"],
                StatementId="BedrockAccess",
                Action="lambda:InvokeFunction",
                Principal="bedrock.amazonaws.com",
            )
        except ClientError as e:
            logger.error(
                f"Couldn't grant Bedrock permission to invoke the Lambda function. Here's why: {e}"
            )
            raise

    def _create_agent_action_group(self):
        print("Creating an action group for the agent...")

        try:
            with open("./scenario_resources/api_schema.yaml") as file:
                self.bedrock_wrapper.create_agent_action_group(
                    name="current_date_and_time",
                    description="Gets the current date and time.",
                    agent_id=self.agent["agentId"],
                    agent_version=self.prepared_agent_details["agentVersion"],
                    function_arn=self.lambda_function["FunctionArn"],
                    api_schema=json.dumps(yaml.safe_load(file)),
                )
        except ClientError as e:
            logger.error(f"Couldn't create agent action group. Here's why: {e}")
            raise

    def _get_agent(self):
        return self.bedrock_wrapper.get_agent(self.agent["agentId"])

    def _get_agent_action_groups(self):
        return self.bedrock_wrapper.list_agent_action_groups(
            self.agent["agentId"], self.prepared_agent_details["agentVersion"]
        )

    def _get_agent_knowledge_bases(self):
        return self.bedrock_wrapper.list_agent_knowledge_bases(
            self.agent["agentId"], self.prepared_agent_details["agentVersion"]
        )

    def _create_agent_alias(self):
        print("Creating an agent alias...")

        agent_alias_name = "test_agent_alias"
        agent_alias = self.bedrock_wrapper.create_agent_alias(
            agent_alias_name, self.agent["agentId"]
        )

        self._wait_for_agent_status(self.agent["agentId"], "PREPARED")

        return agent_alias

    def _wait_for_agent_status(self, agent_id, status):
        while self.bedrock_wrapper.get_agent(agent_id)["agentStatus"] != status:
            wait(2)

    def _chat_with_agent(self, agent_alias):
        print("-" * 88)
        print("The agent is ready to chat.")
        print("Try asking for the date or time. Type 'exit' to quit.")

        # Create a unique session ID for the conversation
        session_id = uuid.uuid4().hex

        while True:
            prompt = q.ask("Prompt: ", q.non_empty)

            if prompt == "exit":
                break

            response = asyncio.run(self._invoke_agent(agent_alias, prompt, session_id))

            print(f"Agent: {response}")

    async def _invoke_agent(self, agent_alias, prompt, session_id):
        response = self.bedrock_agent_runtime_client.invoke_agent(
            agentId=self.agent["agentId"],
            agentAliasId=agent_alias["agentAliasId"],
            sessionId=session_id,
            inputText=prompt,
        )

        completion = ""

        for event in response.get("completion"):
            chunk = event["chunk"]
            completion += chunk["bytes"].decode()

        return completion

    def _delete_resources(self):
        if self.agent:
            agent_id = self.agent["agentId"]

            if self.agent_alias:
                agent_alias_id = self.agent_alias["agentAliasId"]
                print("Deleting agent alias...")
                self.bedrock_wrapper.delete_agent_alias(agent_id, agent_alias_id)

            print("Deleting agent...")
            agent_status = self.bedrock_wrapper.delete_agent(agent_id)["agentStatus"]
            while agent_status == "DELETING":
                wait(5)
                try:
                    agent_status = self.bedrock_wrapper.get_agent(
                        agent_id, log_error=False
                    )["agentStatus"]
                except ClientError as err:
                    if err.response["Error"]["Code"] == "ResourceNotFoundException":
                        agent_status = "DELETED"

        if self.lambda_function:
            name = self.lambda_function["FunctionName"]
            print(f"Deleting function '{name}'...")
            self.lambda_client.delete_function(FunctionName=name)

        if self.agent_role:
            print(f"Deleting role '{self.agent_role.role_name}'...")
            self.agent_role.Policy(ROLE_POLICY_NAME).delete()
            self.agent_role.delete()

        if self.lambda_role:
            print(f"Deleting role '{self.lambda_role.role_name}'...")
            for policy in self.lambda_role.attached_policies.all():
                policy.detach_role(RoleName=self.lambda_role.role_name)
            self.lambda_role.delete()

    def _list_resources(self):
        print("-" * 40)
        print(f"Here is the list of created resources in '{REGION}'.")
        print("Make sure you delete them once you're done to avoid unnecessary costs.")
        if self.agent:
            print(f"Bedrock Agent:   {self.agent['agentName']}")
        if self.lambda_function:
            print(f"Lambda function: {self.lambda_function['FunctionName']}")
        if self.agent_role:
            print(f"IAM role:        {self.agent_role.role_name}")
        if self.lambda_role:
            print(f"IAM role:        {self.lambda_role.role_name}")

    @staticmethod
    def is_valid_agent_name(answer):
        valid_regex = r"^[a-zA-Z0-9_-]{1,100}$"
        return (
            answer
            if answer and len(answer) <= 100 and re.match(valid_regex, answer)
            else None,
            "I need a name for the agent, please. Valid characters are a-z, A-Z, 0-9, _ (underscore) and - (hyphen).",
        )

    @staticmethod
    def _create_deployment_package(function_name):
        buffer = io.BytesIO()
        with zipfile.ZipFile(buffer, "w") as zipped:
            zipped.write(
                "./scenario_resources/lambda_function.py", f"{function_name}.py"
            )
        buffer.seek(0)
        return buffer.read()


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    postfix = "".join(
        random.choice(string.ascii_lowercase + "0123456789") for _ in range(8)
    )
    scenario = BedrockAgentScenarioWrapper(
        bedrock_agent_client=boto3.client(
            service_name="bedrock-agent", region_name=REGION
        ),
        runtime_client=boto3.client(
            service_name="bedrock-agent-runtime", region_name=REGION
        ),
        lambda_client=boto3.client(service_name="lambda", region_name=REGION),
        iam_resource=boto3.resource("iam"),
        postfix=postfix,
    )
    try:
        scenario.run_scenario()
    except Exception as e:
        logging.exception(f"Something went wrong with the demo. Here's what: {e}")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateAgent)
  + [CreateAgentActionGroup](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateAgentActionGroup)
  + [CreateAgentAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateAgentAlias)
  + [DeleteAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteAgent)
  + [DeleteAgentAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteAgentAlias)
  + [GetAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetAgent)
  + [ListAgentActionGroups](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListAgentActionGroups)
  + [ListAgentKnowledgeBases](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListAgentKnowledgeBases)
  + [ListAgents](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/ListAgents)
  + [PrepareAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/PrepareAgent)

### Step Functions を使用して生成 AI アプリケーションをオーケストレーションする
<a name="cross_ServerlessPromptChaining_python_3_topic"></a>

次のコード例は、Amazon Bedrock と Step Functions を使用して生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Bedrock Serverless のプロンプトチェイニングシナリオは、[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)、[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)、および [https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) を使用して、複雑でサーバーレス、高度にスケーラブルな生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。これには、次の実際の例が含まれています。  
+  文学ブログの特定の小説の分析を行う。この例では、プロンプトのシンプルでシーケンシャルなチェーンを示しています。
+  特定のトピックに関する短いストーリーを生成する。この例では、AI が以前に生成した項目のリストを繰り返し処理する方法を示しています。
+  特定の目的地への週末の旅程を作成する。この例では、複数の個別のプロンプトを並列化する方法を示しています。
+  映画のプロデューサーに映画のアイデアを提案する。この例では、異なる推論パラメータを使用して同じプロンプトを並列化する方法、チェーン内の前のステップにバックトラックする方法、ワークフローの一部として人間の入力を含める方法を示しています。
+  ユーザーの手元にある材料に基づいて料理を計画する。この例では、プロンプトチェーンが 2 つの異なる AI 会話を組み込んで、2 つの AI ペルソナが相互に議論を行い、最終的な結果を改善する方法を示しています。
+  当日中で最も人気のある GitHub リポジトリを検索して要約する。この例では、外部 API とやり取りする複数の AI エージェントをチェーンさせる方法を示しています。
 完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/aws-samples/amazon-bedrock-serverless-prompt-chaining) で完全なプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock
+ Amazon Bedrock ランタイム
+ Amazon Bedrock エージェント
+ Amazon Bedrock エージェントランタイム
+ ステップ関数

# SDK for Python (Boto3) を使用した Amazon Bedrock エージェントランタイムの例
<a name="python_3_bedrock-agent-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock エージェントランタイム AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="bedrock-agent-runtime_Scenario_ConverseWithFlow_python_3_topic"></a>

次のコード例は、InvokeFlow を使用して、エージェントノードを含む Amazon Bedrock フローと会話する方法を示しています。

詳細については、「[Converse with an Amazon Bedrock flow](https://docs.aws.amazon.com/bedrock/latest/userguide/flows-multi-turn-invocation.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent-runtime#code-examples)での設定と実行の方法を確認してください。

```
"""
Shows how to run an Amazon Bedrock flow with InvokeFlow and handle muli-turn interaction
for a single conversation.
For more information, see https://docs.aws.amazon.com/bedrock/latest/userguide/flows-multi-turn-invocation.html.

"""
import logging
import boto3
import botocore

import botocore.exceptions

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def invoke_flow(client, flow_id, flow_alias_id, input_data, execution_id):
    """
    Invoke an Amazon Bedrock flow and handle the response stream.

    Args:
        client: Boto3 client for Amazon Bedrock agent runtime.
        flow_id: The ID of the flow to invoke.
        flow_alias_id: The alias ID of the flow.
        input_data: Input data for the flow.
        execution_id: Execution ID for continuing a flow. Use the value None on first run.

    Returns:
        Dict containing flow_complete status, input_required info, and execution_id
    """

    response = None
    request_params = None

    if execution_id is None:
        # Don't pass execution ID for first run.
        request_params = {
            "flowIdentifier": flow_id,
            "flowAliasIdentifier": flow_alias_id,
            "inputs": [input_data],
            "enableTrace": True
        }
    else:
        request_params = {
            "flowIdentifier": flow_id,
            "flowAliasIdentifier": flow_alias_id,
            "executionId": execution_id,
            "inputs": [input_data],
            "enableTrace": True
        }

    response = client.invoke_flow(**request_params)

    if "executionId" not in request_params:
        execution_id = response['executionId']

    input_required = None
    flow_status = ""

    # Process the streaming response
    for event in response['responseStream']:

        # Check if flow is complete.
        if 'flowCompletionEvent' in event:
            flow_status = event['flowCompletionEvent']['completionReason']

        # Check if more input us needed from user.
        elif 'flowMultiTurnInputRequestEvent' in event:
            input_required = event

        # Print the model output.
        elif 'flowOutputEvent' in event:
            print(event['flowOutputEvent']['content']['document'])

        # Log trace events.
        elif 'flowTraceEvent' in event:
            logger.info("Flow trace:  %s", event['flowTraceEvent'])

    return {
        "flow_status": flow_status,
        "input_required": input_required,
        "execution_id": execution_id
    }


def converse_with_flow(bedrock_agent_client, flow_id, flow_alias_id):
    """
    Run a conversation with the supplied flow.

    Args:
        bedrock_agent_client: Boto3 client for Amazon Bedrock agent runtime.
        flow_id: The ID of the flow to run.
        flow_alias_id: The alias ID of the flow.

    """

    flow_execution_id = None
    finished = False

    # Get the intial prompt from the user.
    user_input = input("Enter input: ")

    # Use prompt to create input data.
    flow_input_data = {
        "content": {
            "document": user_input
        },
        "nodeName": "FlowInputNode",
        "nodeOutputName": "document"
    }

    try:
        while not finished:
            # Invoke the flow until successfully finished.

            result = invoke_flow(
                bedrock_agent_client, flow_id, flow_alias_id, flow_input_data, flow_execution_id)

            status = result['flow_status']
            flow_execution_id = result['execution_id']
            more_input = result['input_required']
            if status == "INPUT_REQUIRED":
                # The flow needs more information from the user.
                logger.info("The flow %s requires more input", flow_id)
                user_input = input(
                    more_input['flowMultiTurnInputRequestEvent']['content']['document'] + ": ")
                flow_input_data = {
                    "content": {
                        "document": user_input
                    },
                    "nodeName": more_input['flowMultiTurnInputRequestEvent']['nodeName'],
                    "nodeInputName": "agentInputText"

                }
            elif status == "SUCCESS":
                # The flow completed successfully.
                finished = True
                logger.info("The flow %s successfully completed.", flow_id)

    except botocore.exceptions.ClientError as e:
        print(f"Client error: {str(e)}")
        logger.error("Client error: %s", {str(e)})

    except Exception as e:
        print(f"An error occurred: {str(e)}")
        logger.error("An error occurred: %s", {str(e)})
        logger.error("Error type: %s", {type(e)})


def main():
    """
    Main entry point for the script.
    """

    # Replace these with your actual flow ID and flow alias ID.
    FLOW_ID = 'YOUR_FLOW_ID'
    FLOW_ALIAS_ID = 'YOUR_FLOW_ALIAS_ID'

    logger.info("Starting conversation with FLOW: %s ID: %s",
                FLOW_ID, FLOW_ALIAS_ID)

    # Get the Bedrock agent runtime client.
    session = boto3.Session(profile_name='default')
    bedrock_agent_client = session.client('bedrock-agent-runtime')

    # Start the conversation.
    converse_with_flow(bedrock_agent_client, FLOW_ID, FLOW_ALIAS_ID)

    logger.info("Conversation with FLOW: %s ID: %s finished",
                FLOW_ID, FLOW_ALIAS_ID)


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[InvokeFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-runtime-2023-12-12/InvokeFlow)」を参照してください。**

## アクション
<a name="actions"></a>

### `InvokeAgent`
<a name="bedrock-agent-runtime_InvokeAgent_python_3_topic"></a>

次のコード例は、`InvokeAgent` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent-runtime#code-examples)での設定と実行の方法を確認してください。
エージェントを呼び出します。  

```
    def invoke_agent(self, agent_id, agent_alias_id, session_id, prompt):
        """
        Sends a prompt for the agent to process and respond to.

        :param agent_id: The unique identifier of the agent to use.
        :param agent_alias_id: The alias of the agent to use.
        :param session_id: The unique identifier of the session. Use the same value across requests
                           to continue the same conversation.
        :param prompt: The prompt that you want Claude to complete.
        :return: Inference response from the model.
        """

        try:
            # Note: The execution time depends on the foundation model, complexity of the agent,
            # and the length of the prompt. In some cases, it can take up to a minute or more to
            # generate a response.
            response = self.agents_runtime_client.invoke_agent(
                agentId=agent_id,
                agentAliasId=agent_alias_id,
                sessionId=session_id,
                inputText=prompt,
            )

            completion = ""

            for event in response.get("completion"):
                chunk = event["chunk"]
                completion = completion + chunk["bytes"].decode()

        except ClientError as e:
            logger.error(f"Couldn't invoke agent. {e}")
            raise

        return completion
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[InvokeAgent](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-runtime-2023-12-12/InvokeAgent)」を参照してください。

### `InvokeFlow`
<a name="bedrock-agent-runtime_InvokeFlow_python_3_topic"></a>

次のコード例は、`InvokeFlow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent-runtime#code-examples)での設定と実行の方法を確認してください。
フローを呼び出します。  

```
    def invoke_flow(self, flow_id, flow_alias_id, input_data, execution_id):
        """
        Invoke an Amazon Bedrock flow and handle the response stream.

        Args:
            param flow_id: The ID of the flow to invoke.
            param flow_alias_id: The alias ID of the flow.
            param input_data: Input data for the flow.
            param execution_id: Execution ID for continuing a flow. Use the value None on first run.

        Return: Response from the flow.
        """
        try:
      
            request_params = None

            if execution_id is None:
                # Don't pass execution ID for first run.
                request_params = {
                    "flowIdentifier": flow_id,
                    "flowAliasIdentifier": flow_alias_id,
                    "inputs": input_data,
                    "enableTrace": True
                }
            else:
                request_params = {
                    "flowIdentifier": flow_id,
                    "flowAliasIdentifier": flow_alias_id,
                    "executionId": execution_id,
                    "inputs": input_data,
                    "enableTrace": True
                }

            response = self.agents_runtime_client.invoke_flow(**request_params)

            if "executionId" not in request_params:
                execution_id = response['executionId']

            result = ""

            # Get the streaming response
            for event in response['responseStream']:
                result = result + str(event) + '\n'
            print(result)

        except ClientError as e:
            logger.error("Couldn't invoke flow %s.", {e})
            raise

        return result
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[InvokeFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-runtime-2023-12-12/InvokeFlow)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### フローを作成して呼び出す
<a name="bedrock-agent_GettingStartedWithBedrockFlows_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ フローの実行ロールを作成します。
+ フローを作成します。
+ 完全に設定されたフローをデプロイします。
+ ユーザー指定のプロンプトでフローを呼び出します。
+ すべての作成されたリソースを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-agent#code-examples)での設定と実行の方法を確認してください。
ユーザーが指定したジャンルと曲数に基づいて音楽プレイリストを生成します。  

```
from datetime import datetime
import logging
import boto3

from botocore.exceptions import ClientError

from roles import create_flow_role, delete_flow_role, update_role_policy
from flow import create_flow, prepare_flow, delete_flow
from run_flow import run_playlist_flow
from flow_version import create_flow_version, delete_flow_version
from flow_alias import create_flow_alias, delete_flow_alias

logging.basicConfig(
    level=logging.INFO
)
logger = logging.getLogger(__name__)

def create_input_node(name):
    """
    Creates an input node configuration for an Amazon Bedrock flow.

    The input node serves as the entry point for the flow and defines
    the initial document structure that will be passed to subsequent nodes.

    Args:
        name (str): The name of the input node.

    Returns:
        dict: The input node configuration.

    """
    return {
        "type": "Input",
        "name": name,
        "outputs": [
            {
                "name": "document",
                "type": "Object"
            }
        ]
    }


def create_prompt_node(name, model_id):
    """
    Creates a prompt node configuration for a Bedrock flow that generates music playlists.

    The prompt node defines an inline prompt template that creates a music playlist based on
    a specified genre and number of songs. The prompt uses two variables that are mapped from
    the input JSON object:
    - {{genre}}: The genre of music to create a playlist for
    - {{number}}: The number of songs to include in the playlist

    Args:
        name (str): The name of the prompt node.
        model_id (str): The identifier of the foundation model to use for the prompt.

    Returns:
        dict: The prompt node.

    """

    return {
        "type": "Prompt",
        "name": name,
        "configuration": {
            "prompt": {
                "sourceConfiguration": {
                    "inline": {
                        "modelId": model_id,
                        "templateType": "TEXT",
                        "inferenceConfiguration": {
                            "text": {
                                "temperature": 0.8
                            }
                        },
                        "templateConfiguration": {
                            "text": {
                                "text": "Make me a {{genre}} playlist consisting of the following number of songs: {{number}}."
                            }
                        }
                    }
                }
            }
        },
        "inputs": [
            {
                "name": "genre",
                "type": "String",
                "expression": "$.data.genre"
            },
            {
                "name": "number",
                "type": "Number",
                "expression": "$.data.number"
            }
        ],
        "outputs": [
            {
                "name": "modelCompletion",
                "type": "String"
            }
        ]
    }


def create_output_node(name):
    """
    Creates an output node configuration for a Bedrock flow.

    The output node validates that the output from the last node is a string
    and returns it unmodified. The input name must be "document".

    Args:
        name (str): The name of the output node.

    Returns:
        dict: The output node configuration containing the output node:

    """

    return {
        "type": "Output",
        "name": name,
        "inputs": [
            {
                "name": "document",
                "type": "String",
                "expression": "$.data"
            }
        ]
    }




def create_playlist_flow(client, flow_name, flow_description, role_arn, prompt_model_id):
    """
    Creates the playlist generator flow.
    Args:
        client: bedrock agent boto3 client.
        role_arn (str): Name for the new IAM role.
        prompt_model_id (str): The id of the model to use in the prompt node.
    Returns:
        dict: The response from the create_flow operation.
    """

    input_node = create_input_node("FlowInput")
    prompt_node = create_prompt_node("MakePlaylist", prompt_model_id)
    output_node = create_output_node("FlowOutput")

    # Create connections between the nodes
    connections = []

    #  First, create connections between the output of the flow 
    # input node and each input of the prompt node.
    for prompt_node_input in prompt_node["inputs"]:
        connections.append(
            {
                "name": "_".join([input_node["name"], prompt_node["name"],
                                   prompt_node_input["name"]]),
                "source": input_node["name"],
                "target": prompt_node["name"],
                "type": "Data",
                "configuration": {
                    "data": {
                        "sourceOutput": input_node["outputs"][0]["name"],
                        "targetInput": prompt_node_input["name"]
                    }
                }
            }
        )

    # Then, create a connection between the output of the prompt node and the input of the flow output node
    connections.append(
        {
            "name": "_".join([prompt_node["name"], output_node["name"]]),
            "source": prompt_node["name"],
            "target": output_node["name"],
            "type": "Data",
            "configuration": {
                "data": {
                    "sourceOutput": prompt_node["outputs"][0]["name"],
                    "targetInput": output_node["inputs"][0]["name"]
                }
            }
        }
    )

    flow_def = {
        "nodes": [input_node, prompt_node, output_node],
        "connections": connections
    }

    # Create the flow.

    response = create_flow(
        client, flow_name, flow_description, role_arn, flow_def)

    return response



def get_model_arn(client, model_id):
    """
    Gets the Amazon Resource Name (ARN) for a model.
    Args:
        client (str): Amazon Bedrock boto3 client.
        model_id (str): The id of the model.
    Returns:
        str: The ARN of the model.
    """

    try:
        # Call GetFoundationModelDetails operation
        response = client.get_foundation_model(modelIdentifier=model_id)

        # Extract model ARN from the response
        model_arn = response['modelDetails']['modelArn']

        return model_arn

    except ClientError as e:
        logger.exception("Client error getting model ARN: %s", {str(e)})
        raise

    except Exception as e:
        logger.exception("Unexpected error getting model ARN: %s", {str(e)})
        raise


def prepare_flow_version_and_alias(bedrock_agent_client,
                                   flow_id):
    """
    Prepares the flow and then creates a flow version and flow alias.
    Args:
        bedrock_agent_client: Amazon Bedrock Agent boto3 client.
        flowd_id (str): The ID of the flow that you want to prepare.
    Returns: The flow_version and flow_alias. 

    """

    status = prepare_flow(bedrock_agent_client, flow_id)

    flow_version = None
    flow_alias = None

    if status == 'Prepared':

        # Create the flow version and alias.
        flow_version = create_flow_version(bedrock_agent_client,
                                           flow_id,
                                           f"flow version for flow {flow_id}.")

        flow_alias = create_flow_alias(bedrock_agent_client,
                                       flow_id,
                                       flow_version,
                                       "latest",
                                       f"Alias for flow {flow_id}, version {flow_version}")

    return flow_version, flow_alias



def delete_role_resources(bedrock_agent_client,
                          iam_client,
                          role_name,
                          flow_id,
                          flow_version,
                          flow_alias):
    """
    Deletes the flow, flow alias, flow version, and IAM roles.
    Args:
        bedrock_agent_client: Amazon Bedrock Agent boto3 client.
        iam_client: Amazon IAM boto3 client.
        role_name (str): The name of the IAM role.
        flow_id (str): The id of the flow.
        flow_version (str): The version of the flow.
        flow_alias (str): The alias of the flow.
    """

    if flow_id is not None:
        if flow_alias is not None:
            delete_flow_alias(bedrock_agent_client, flow_id, flow_alias)
        if flow_version is not None:
            delete_flow_version(bedrock_agent_client,
                        flow_id, flow_version)
        delete_flow(bedrock_agent_client, flow_id)
    
    if role_name is not None:
        delete_flow_role(iam_client, role_name)



def main():
    """
    Creates, runs, and optionally deletes a Bedrock flow for generating music playlists.

    Note:
        Requires valid AWS credentials in the default profile
    """

    delete_choice = "y"
    try:

        # Get various boto3 clients.
        session = boto3.Session(profile_name='default')
        bedrock_agent_runtime_client = session.client('bedrock-agent-runtime')
        bedrock_agent_client = session.client('bedrock-agent')
        bedrock_client = session.client('bedrock')
        iam_client = session.client('iam')
        
        role_name = None
        flow_id = None
        flow_version = None
        flow_alias = None

        #Change the model as needed.
        prompt_model_id = "amazon.nova-pro-v1:0"

        # Base the flow name on the current date and time
        current_time = datetime.now()
        timestamp = current_time.strftime("%Y-%m-%d-%H-%M-%S")
        flow_name = f"FlowPlayList_{timestamp}"
        flow_description = "A flow to generate a music playlist."

        # Create a role for the flow.
        role_name = f"BedrockFlowRole-{flow_name}"
        role = create_flow_role(iam_client, role_name)
        role_arn = role['Arn']

        # Create the flow.
        response = create_playlist_flow(
            bedrock_agent_client, flow_name, flow_description, role_arn, prompt_model_id)
        flow_id = response.get('id')

        if flow_id:
            # Update accessible resources in the role.
            model_arn = get_model_arn(bedrock_client, prompt_model_id)
            update_role_policy(iam_client, role_name, [
                               response.get('arn'), model_arn])

            # Prepare the flow and flow version.
            flow_version, flow_alias = prepare_flow_version_and_alias(
                bedrock_agent_client, flow_id)

            # Run the flow.
            if flow_version and flow_alias:
                run_playlist_flow(bedrock_agent_runtime_client,
                                  flow_id, flow_alias)

                delete_choice = input("Delete flow? y or n : ").lower()


            else:
                print("Couldn't run. Deleting flow and role.")
                delete_flow(bedrock_agent_client, flow_id)
                delete_flow_role(iam_client, role_name)
        else:
            print("Couldn't create flow.")


    except Exception as e:
        print(f"Fatal error: {str(e)}")
    
    finally:
        if delete_choice == 'y':
                delete_role_resources(bedrock_agent_client,
                                          iam_client,
                                          role_name,
                                          flow_id,
                                          flow_version,
                                          flow_alias)
        else:
            print("Flow not deleted. ")
            print(f"\tFlow ID: {flow_id}")
            print(f"\tFlow version: {flow_version}")
            print(f"\tFlow alias: {flow_alias}")
            print(f"\tRole ARN: {role_arn}")
       
        print("Done!")
 
if __name__ == "__main__":
    main()


def invoke_flow(client, flow_id, flow_alias_id, input_data):
    """
    Invoke an Amazon Bedrock flow and handle the response stream.

    Args:
        client: Boto3 client for Amazon Bedrock agent runtime.
        flow_id: The ID of the flow to invoke.
        flow_alias_id: The alias ID of the flow.
        input_data: Input data for the flow.

    Returns:
        Dict containing flow status and flow output.
    """

    response = None
    request_params = None

    request_params = {
            "flowIdentifier": flow_id,
            "flowAliasIdentifier": flow_alias_id,
            "inputs": [input_data],
            "enableTrace": True
        }


    response = client.invoke_flow(**request_params)

    flow_status = ""
    output= ""

    # Process the streaming response
    for event in response['responseStream']:

        # Check if flow is complete.
        if 'flowCompletionEvent' in event:
            flow_status = event['flowCompletionEvent']['completionReason']

        # Save the model output.
        elif 'flowOutputEvent' in event:
            output = event['flowOutputEvent']['content']['document']
            logger.info("Output : %s", output)

        # Log trace events.
        elif 'flowTraceEvent' in event:
            logger.info("Flow trace:  %s", event['flowTraceEvent'])
    
    return {
        "flow_status": flow_status,
        "output": output

    }




def run_playlist_flow(bedrock_agent_client, flow_id, flow_alias_id):
    """
    Runs the playlist generator flow.

    Args:
        bedrock_agent_client: Boto3 client for Amazon Bedrock agent runtime.
        flow_id: The ID of the flow to run.
        flow_alias_id: The alias ID of the flow.

    """


    print ("Welcome to the playlist generator flow.")
    # Get the initial prompt from the user.
    genre = input("Enter genre: ")
    number_of_songs = int(input("Enter number of songs: "))


    # Use prompt to create input data for the input node.
    flow_input_data = {
        "content": {
            "document": {
                "genre" : genre,
                "number" : number_of_songs
            }
        },
        "nodeName": "FlowInput",
        "nodeOutputName": "document"
    }

    try:

        result = invoke_flow(
                bedrock_agent_client, flow_id, flow_alias_id, flow_input_data)

        status = result['flow_status']
  
        if status == "SUCCESS":
                # The flow completed successfully.
                logger.info("The flow %s successfully completed.", flow_id)
                print(result['output'])
        else:
            logger.warning("Flow status: %s",status)

    except ClientError as e:
        print(f"Client error: {str(e)}")
        logger.error("Client error: %s", {str(e)})
        raise

    except Exception as e:
        logger.error("An error occurred: %s", {str(e)})
        logger.error("Error type: %s", {type(e)})
        raise



def create_flow_role(client, role_name):
    """
    Creates an IAM role for Amazon Bedrock with permissions to run a flow.
    
    Args:
        role_name (str): Name for the new IAM role.
    Returns:
        str: The role Amazon Resource Name.
    """

    
    # Trust relationship policy - allows Amazon Bedrock service to assume this role.
    trust_policy = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{
            "Effect": "Allow",
            "Principal": {
                "Service": "bedrock.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }]
    }
    
    # Basic inline policy for for running a flow.

    resources = "*"

    bedrock_policy = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "bedrock:InvokeModel",
                    "bedrock:Retrieve",
                    "bedrock:RetrieveAndGenerate"
                ],
                # Using * as placeholder - Later you update with specific ARNs.
                "Resource": resources
            }
        ]
    }


    
    try:
        # Create the IAM role with trust policy
        logging.info("Creating role: %s",role_name)
        role = client.create_role(
            RoleName=role_name,
            AssumeRolePolicyDocument=json.dumps(trust_policy),
            Description="Role for Amazon Bedrock operations"
        )
        
        # Attach inline policy to the role
        print("Attaching inline policy")
        client.put_role_policy(
            RoleName=role_name,
            PolicyName=f"{role_name}-policy",
            PolicyDocument=json.dumps(bedrock_policy)
        )
        
        logging.info("Create Role ARN: %s", role['Role']['Arn'])
        return role['Role']
        
    except ClientError as e:
        logging.warning("Error creating role: %s", str(e))
        raise
    except Exception as e:
        logging.warning("Unexpected error: %s", str(e))
        raise


def update_role_policy(client, role_name, resource_arns):
    """
    Updates an IAM role's inline policy with specific resource ARNs.
    
    Args:
        role_name (str): Name of the existing role.
        resource_arns (list): List of resource ARNs to allow access to.
    """

    
    updated_policy = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "bedrock:GetFlow",
                    "bedrock:InvokeModel",
                    "bedrock:Retrieve",
                    "bedrock:RetrieveAndGenerate"
                ],
                "Resource": resource_arns
            }
        ]
    }
    
    try:
        client.put_role_policy(
            RoleName=role_name,
            PolicyName=f"{role_name}-policy",
            PolicyDocument=json.dumps(updated_policy)
        )
        logging.info("Updated policy for role: %s",role_name)
        
    except ClientError as e:
        logging.warning("Error updating role policy: %s", str(e))
        raise


def delete_flow_role(client, role_name):
    """
    Deletes an IAM role.

    Args:
        role_name (str): Name of the role to delete.
    """



    try:
        # Detach and delete inline policies
        policies = client.list_role_policies(RoleName=role_name)['PolicyNames']
        for policy_name in policies:
            client.delete_role_policy(RoleName=role_name, PolicyName=policy_name)

        # Delete the role
        client.delete_role(RoleName=role_name)
        logging.info("Deleted role: %s", role_name)


    except ClientError as e:
        logging.info("Error Deleting role: %s", str(e))
        raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlow)
  + [CreateFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlowAlias)
  + [CreateFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/CreateFlowVersion)
  + [DeleteFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlow)
  + [DeleteFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlowAlias)
  + [DeleteFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/DeleteFlowVersion)
  + [GetFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlow)
  + [GetFlowAlias](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlowAlias)
  + [GetFlowVersion](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/GetFlowVersion)
  + [InvokeFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-runtime-2023-12-12/InvokeFlow)
  + [PrepareFlow](https://docs.aws.amazon.com/goto/boto3/bedrock-agent-2023-12-12/PrepareFlow)

### Step Functions を使用して生成 AI アプリケーションをオーケストレーションする
<a name="cross_ServerlessPromptChaining_python_3_topic"></a>

次のコード例は、Amazon Bedrock と Step Functions を使用して生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Bedrock Serverless のプロンプトチェイニングシナリオは、[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)、[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)、および [https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) を使用して、複雑でサーバーレス、高度にスケーラブルな生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。これには、次の実際の例が含まれています。  
+  文学ブログの特定の小説の分析を行う。この例では、プロンプトのシンプルでシーケンシャルなチェーンを示しています。
+  特定のトピックに関する短いストーリーを生成する。この例では、AI が以前に生成した項目のリストを繰り返し処理する方法を示しています。
+  特定の目的地への週末の旅程を作成する。この例では、複数の個別のプロンプトを並列化する方法を示しています。
+  映画のプロデューサーに映画のアイデアを提案する。この例では、異なる推論パラメータを使用して同じプロンプトを並列化する方法、チェーン内の前のステップにバックトラックする方法、ワークフローの一部として人間の入力を含める方法を示しています。
+  ユーザーの手元にある材料に基づいて料理を計画する。この例では、プロンプトチェーンが 2 つの異なる AI 会話を組み込んで、2 つの AI ペルソナが相互に議論を行い、最終的な結果を改善する方法を示しています。
+  当日中で最も人気のある GitHub リポジトリを検索して要約する。この例では、外部 API とやり取りする複数の AI エージェントをチェーンさせる方法を示しています。
 完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/aws-samples/amazon-bedrock-serverless-prompt-chaining) で完全なプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock
+ Amazon Bedrock ランタイム
+ Amazon Bedrock エージェント
+ Amazon Bedrock エージェントランタイム
+ ステップ関数

# CloudFormation SDK for Python を使用した例 (Boto3)
<a name="python_3_cloudformation_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています CloudFormation。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### COVID-19 データを追跡する REST API を作成する
<a name="cross_ApiGatewayDataTracker_python_3_topic"></a>

次のコード例は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートする REST API を作成する方法を示しています。

**SDK for Python (Boto3)**  
 で AWS Chalice を使用して AWS SDK for Python (Boto3) 、Amazon API Gateway AWS Lambda、および Amazon DynamoDB を使用するサーバーレス REST API を作成する方法を示します。REST API は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートします。以下ではその方法を説明しています。  
+  AWS Chalice を使用して、API Gateway 経由で送信される REST リクエストを処理するために呼び出される Lambda 関数のルートを定義します。
+ Lambda 関数を使用して、DynamoDB テーブルにデータを取得して保存し、REST リクエストを処理します。
+  AWS CloudFormation テンプレートでテーブル構造とセキュリティロールリソースを定義します。
+  AWS Chalice と CloudFormation を使用して、必要なすべてのリソースをパッケージ化してデプロイします。
+ CloudFormation を使用して、作成されたすべてのリソースをクリーンアップします。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_covid-19_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ CloudFormation
+ DynamoDB
+ Lambda

# SDK for Python (Boto3) を使用した CloudFront の例
<a name="python_3_cloudfront_code_examples"></a>

次のコード例は、CloudFront AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetDistributionConfig`
<a name="cloudfront_GetDistributionConfig_python_3_topic"></a>

次のコード例は、`GetDistributionConfig` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。

```
class CloudFrontWrapper:
    """Encapsulates Amazon CloudFront operations."""

    def __init__(self, cloudfront_client):
        """
        :param cloudfront_client: A Boto3 CloudFront client
        """
        self.cloudfront_client = cloudfront_client


    def update_distribution(self):
        distribution_id = input(
            "This script updates the comment for a CloudFront distribution.\n"
            "Enter a CloudFront distribution ID: "
        )

        distribution_config_response = self.cloudfront_client.get_distribution_config(
            Id=distribution_id
        )
        distribution_config = distribution_config_response["DistributionConfig"]
        distribution_etag = distribution_config_response["ETag"]

        distribution_config["Comment"] = input(
            f"\nThe current comment for distribution {distribution_id} is "
            f"'{distribution_config['Comment']}'.\n"
            f"Enter a new comment: "
        )
        self.cloudfront_client.update_distribution(
            DistributionConfig=distribution_config,
            Id=distribution_id,
            IfMatch=distribution_etag,
        )
        print("Done!")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetDistributionConfig](https://docs.aws.amazon.com/goto/boto3/cloudfront-2020-05-31/GetDistributionConfig)」を参照してください。

### `ListDistributions`
<a name="cloudfront_ListDistributions_python_3_topic"></a>

次のコード例は、`ListDistributions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。

```
class CloudFrontWrapper:
    """Encapsulates Amazon CloudFront operations."""

    def __init__(self, cloudfront_client):
        """
        :param cloudfront_client: A Boto3 CloudFront client
        """
        self.cloudfront_client = cloudfront_client


    def list_distributions(self):
        print("CloudFront distributions:\n")
        distributions = self.cloudfront_client.list_distributions()
        if distributions["DistributionList"]["Quantity"] > 0:
            for distribution in distributions["DistributionList"]["Items"]:
                print(f"Domain: {distribution['DomainName']}")
                print(f"Distribution Id: {distribution['Id']}")
                print(
                    f"Certificate Source: "
                    f"{distribution['ViewerCertificate']['CertificateSource']}"
                )
                if distribution["ViewerCertificate"]["CertificateSource"] == "acm":
                    print(
                        f"Certificate: {distribution['ViewerCertificate']['Certificate']}"
                    )
                print("")
        else:
            print("No CloudFront distributions detected.")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListDistributions](https://docs.aws.amazon.com/goto/boto3/cloudfront-2020-05-31/ListDistributions)」を参照してください。

### `UpdateDistribution`
<a name="cloudfront_UpdateDistribution_python_3_topic"></a>

次のコード例は、`UpdateDistribution` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudfront#code-examples)での設定と実行の方法を確認してください。

```
class CloudFrontWrapper:
    """Encapsulates Amazon CloudFront operations."""

    def __init__(self, cloudfront_client):
        """
        :param cloudfront_client: A Boto3 CloudFront client
        """
        self.cloudfront_client = cloudfront_client


    def update_distribution(self):
        distribution_id = input(
            "This script updates the comment for a CloudFront distribution.\n"
            "Enter a CloudFront distribution ID: "
        )

        distribution_config_response = self.cloudfront_client.get_distribution_config(
            Id=distribution_id
        )
        distribution_config = distribution_config_response["DistributionConfig"]
        distribution_etag = distribution_config_response["ETag"]

        distribution_config["Comment"] = input(
            f"\nThe current comment for distribution {distribution_id} is "
            f"'{distribution_config['Comment']}'.\n"
            f"Enter a new comment: "
        )
        self.cloudfront_client.update_distribution(
            DistributionConfig=distribution_config,
            Id=distribution_id,
            IfMatch=distribution_etag,
        )
        print("Done!")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateDistribution](https://docs.aws.amazon.com/goto/boto3/cloudfront-2020-05-31/UpdateDistribution)」を参照してください。

# SDK for Python (Boto3) を使用する CloudWatch の例
<a name="python_3_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_python_3_topic"></a>

次のコード例は、`DeleteAlarms` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def delete_metric_alarms(self, metric_namespace, metric_name):
        """
        Deletes all of the alarms that are currently watching the specified metric.

        :param metric_namespace: The namespace of the metric.
        :param metric_name: The name of the metric.
        """
        try:
            metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name)
            metric.alarms.delete()
            logger.info(
                "Deleted alarms for metric %s.%s.", metric_namespace, metric_name
            )
        except ClientError:
            logger.exception(
                "Couldn't delete alarms for metric %s.%s.",
                metric_namespace,
                metric_name,
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteAlarms](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/DeleteAlarms)」を参照してください。

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_python_3_topic"></a>

次のコード例は、`DescribeAlarmsForMetric` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def get_metric_alarms(self, metric_namespace, metric_name):
        """
        Gets the alarms that are currently watching the specified metric.

        :param metric_namespace: The namespace of the metric.
        :param metric_name: The name of the metric.
        :returns: An iterator that yields the alarms.
        """
        metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name)
        alarm_iter = metric.alarms.all()
        logger.info("Got alarms for metric %s.%s.", metric_namespace, metric_name)
        return alarm_iter
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/DescribeAlarmsForMetric)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_python_3_topic"></a>

次のコード例は、`DisableAlarmActions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def enable_alarm_actions(self, alarm_name, enable):
        """
        Enables or disables actions on the specified alarm. Alarm actions can be
        used to send notifications or automate responses when an alarm enters a
        particular state.

        :param alarm_name: The name of the alarm.
        :param enable: When True, actions are enabled for the alarm. Otherwise, they
                       disabled.
        """
        try:
            alarm = self.cloudwatch_resource.Alarm(alarm_name)
            if enable:
                alarm.enable_actions()
            else:
                alarm.disable_actions()
            logger.info(
                "%s actions for alarm %s.",
                "Enabled" if enable else "Disabled",
                alarm_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't %s actions alarm %s.",
                "enable" if enable else "disable",
                alarm_name,
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DisableAlarmActions](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/DisableAlarmActions)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_python_3_topic"></a>

次のコード例は、`EnableAlarmActions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def enable_alarm_actions(self, alarm_name, enable):
        """
        Enables or disables actions on the specified alarm. Alarm actions can be
        used to send notifications or automate responses when an alarm enters a
        particular state.

        :param alarm_name: The name of the alarm.
        :param enable: When True, actions are enabled for the alarm. Otherwise, they
                       disabled.
        """
        try:
            alarm = self.cloudwatch_resource.Alarm(alarm_name)
            if enable:
                alarm.enable_actions()
            else:
                alarm.disable_actions()
            logger.info(
                "%s actions for alarm %s.",
                "Enabled" if enable else "Disabled",
                alarm_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't %s actions alarm %s.",
                "enable" if enable else "disable",
                alarm_name,
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[EnableAlarmActions](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/EnableAlarmActions)」を参照してください。

### `GetMetricStatistics`
<a name="cloudwatch_GetMetricStatistics_python_3_topic"></a>

次のコード例は、`GetMetricStatistics` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def get_metric_statistics(self, namespace, name, start, end, period, stat_types):
        """
        Gets statistics for a metric within a specified time span. Metrics are grouped
        into the specified period.

        :param namespace: The namespace of the metric.
        :param name: The name of the metric.
        :param start: The UTC start time of the time span to retrieve.
        :param end: The UTC end time of the time span to retrieve.
        :param period: The period, in seconds, in which to group metrics. The period
                       must match the granularity of the metric, which depends on
                       the metric's age. For example, metrics that are older than
                       three hours have a one-minute granularity, so the period must
                       be at least 60 and must be a multiple of 60.
        :param stat_types: The type of statistics to retrieve, such as average value
                           or maximum value.
        :return: The retrieved statistics for the metric.
        """
        try:
            metric = self.cloudwatch_resource.Metric(namespace, name)
            stats = metric.get_statistics(
                StartTime=start, EndTime=end, Period=period, Statistics=stat_types
            )
            logger.info(
                "Got %s statistics for %s.", len(stats["Datapoints"]), stats["Label"]
            )
        except ClientError:
            logger.exception("Couldn't get statistics for %s.%s.", namespace, name)
            raise
        else:
            return stats
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetMetricStatistics](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/GetMetricStatistics)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_python_3_topic"></a>

次のコード例は、`ListMetrics` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def list_metrics(self, namespace, name, recent=False):
        """
        Gets the metrics within a namespace that have the specified name.
        If the metric has no dimensions, a single metric is returned.
        Otherwise, metrics for all dimensions are returned.

        :param namespace: The namespace of the metric.
        :param name: The name of the metric.
        :param recent: When True, only metrics that have been active in the last
                       three hours are returned.
        :return: An iterator that yields the retrieved metrics.
        """
        try:
            kwargs = {"Namespace": namespace, "MetricName": name}
            if recent:
                kwargs["RecentlyActive"] = "PT3H"  # List past 3 hours only
            metric_iter = self.cloudwatch_resource.metrics.filter(**kwargs)
            logger.info("Got metrics for %s.%s.", namespace, name)
        except ClientError:
            logger.exception("Couldn't get metrics for %s.%s.", namespace, name)
            raise
        else:
            return metric_iter
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListMetrics](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/ListMetrics)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_python_3_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def create_metric_alarm(
        self,
        metric_namespace,
        metric_name,
        alarm_name,
        stat_type,
        period,
        eval_periods,
        threshold,
        comparison_op,
    ):
        """
        Creates an alarm that watches a metric.

        :param metric_namespace: The namespace of the metric.
        :param metric_name: The name of the metric.
        :param alarm_name: The name of the alarm.
        :param stat_type: The type of statistic the alarm watches.
        :param period: The period in which metric data are grouped to calculate
                       statistics.
        :param eval_periods: The number of periods that the metric must be over the
                             alarm threshold before the alarm is set into an alarmed
                             state.
        :param threshold: The threshold value to compare against the metric statistic.
        :param comparison_op: The comparison operation used to compare the threshold
                              against the metric.
        :return: The newly created alarm.
        """
        try:
            metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name)
            alarm = metric.put_alarm(
                AlarmName=alarm_name,
                Statistic=stat_type,
                Period=period,
                EvaluationPeriods=eval_periods,
                Threshold=threshold,
                ComparisonOperator=comparison_op,
            )
            logger.info(
                "Added alarm %s to track metric %s.%s.",
                alarm_name,
                metric_namespace,
                metric_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't add alarm %s to metric %s.%s",
                alarm_name,
                metric_namespace,
                metric_name,
            )
            raise
        else:
            return alarm
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutMetricAlarm](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/PutMetricAlarm)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_python_3_topic"></a>

次のコード例は、`PutMetricData` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def put_metric_data(self, namespace, name, value, unit):
        """
        Sends a single data value to CloudWatch for a metric. This metric is given
        a timestamp of the current UTC time.

        :param namespace: The namespace of the metric.
        :param name: The name of the metric.
        :param value: The value of the metric.
        :param unit: The unit of the metric.
        """
        try:
            metric = self.cloudwatch_resource.Metric(namespace, name)
            metric.put_data(
                Namespace=namespace,
                MetricData=[{"MetricName": name, "Value": value, "Unit": unit}],
            )
            logger.info("Put data for metric %s.%s", namespace, name)
        except ClientError:
            logger.exception("Couldn't put data for metric %s.%s", namespace, name)
            raise
```
一連のデータを CloudWatch メトリクスに配置します。  

```
class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def put_metric_data_set(self, namespace, name, timestamp, unit, data_set):
        """
        Sends a set of data to CloudWatch for a metric. All of the data in the set
        have the same timestamp and unit.

        :param namespace: The namespace of the metric.
        :param name: The name of the metric.
        :param timestamp: The UTC timestamp for the metric.
        :param unit: The unit of the metric.
        :param data_set: The set of data to send. This set is a dictionary that
                         contains a list of values and a list of corresponding counts.
                         The value and count lists must be the same length.
        """
        try:
            metric = self.cloudwatch_resource.Metric(namespace, name)
            metric.put_data(
                Namespace=namespace,
                MetricData=[
                    {
                        "MetricName": name,
                        "Timestamp": timestamp,
                        "Values": data_set["values"],
                        "Counts": data_set["counts"],
                        "Unit": unit,
                    }
                ],
            )
            logger.info("Put data set for metric %s.%s.", namespace, name)
        except ClientError:
            logger.exception("Couldn't put data set for metric %s.%s.", namespace, name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutMetricData](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/PutMetricData)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メトリクスとアラームを管理する
<a name="cloudwatch_Usage_MetricsAlarms_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ アラームを作成して CloudWatch メトリクスを監視します。
+ メトリクスにデータを配置し、アラームをトリガーします。
+ アラームからデータを取得します。
+ アラームを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。
CloudWatch オペレーションをラップするクラスを作成します。  

```
from datetime import datetime, timedelta
import logging
from pprint import pprint
import random
import time
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class CloudWatchWrapper:
    """Encapsulates Amazon CloudWatch functions."""

    def __init__(self, cloudwatch_resource):
        """
        :param cloudwatch_resource: A Boto3 CloudWatch resource.
        """
        self.cloudwatch_resource = cloudwatch_resource


    def put_metric_data_set(self, namespace, name, timestamp, unit, data_set):
        """
        Sends a set of data to CloudWatch for a metric. All of the data in the set
        have the same timestamp and unit.

        :param namespace: The namespace of the metric.
        :param name: The name of the metric.
        :param timestamp: The UTC timestamp for the metric.
        :param unit: The unit of the metric.
        :param data_set: The set of data to send. This set is a dictionary that
                         contains a list of values and a list of corresponding counts.
                         The value and count lists must be the same length.
        """
        try:
            metric = self.cloudwatch_resource.Metric(namespace, name)
            metric.put_data(
                Namespace=namespace,
                MetricData=[
                    {
                        "MetricName": name,
                        "Timestamp": timestamp,
                        "Values": data_set["values"],
                        "Counts": data_set["counts"],
                        "Unit": unit,
                    }
                ],
            )
            logger.info("Put data set for metric %s.%s.", namespace, name)
        except ClientError:
            logger.exception("Couldn't put data set for metric %s.%s.", namespace, name)
            raise


    def create_metric_alarm(
        self,
        metric_namespace,
        metric_name,
        alarm_name,
        stat_type,
        period,
        eval_periods,
        threshold,
        comparison_op,
    ):
        """
        Creates an alarm that watches a metric.

        :param metric_namespace: The namespace of the metric.
        :param metric_name: The name of the metric.
        :param alarm_name: The name of the alarm.
        :param stat_type: The type of statistic the alarm watches.
        :param period: The period in which metric data are grouped to calculate
                       statistics.
        :param eval_periods: The number of periods that the metric must be over the
                             alarm threshold before the alarm is set into an alarmed
                             state.
        :param threshold: The threshold value to compare against the metric statistic.
        :param comparison_op: The comparison operation used to compare the threshold
                              against the metric.
        :return: The newly created alarm.
        """
        try:
            metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name)
            alarm = metric.put_alarm(
                AlarmName=alarm_name,
                Statistic=stat_type,
                Period=period,
                EvaluationPeriods=eval_periods,
                Threshold=threshold,
                ComparisonOperator=comparison_op,
            )
            logger.info(
                "Added alarm %s to track metric %s.%s.",
                alarm_name,
                metric_namespace,
                metric_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't add alarm %s to metric %s.%s",
                alarm_name,
                metric_namespace,
                metric_name,
            )
            raise
        else:
            return alarm


    def put_metric_data(self, namespace, name, value, unit):
        """
        Sends a single data value to CloudWatch for a metric. This metric is given
        a timestamp of the current UTC time.

        :param namespace: The namespace of the metric.
        :param name: The name of the metric.
        :param value: The value of the metric.
        :param unit: The unit of the metric.
        """
        try:
            metric = self.cloudwatch_resource.Metric(namespace, name)
            metric.put_data(
                Namespace=namespace,
                MetricData=[{"MetricName": name, "Value": value, "Unit": unit}],
            )
            logger.info("Put data for metric %s.%s", namespace, name)
        except ClientError:
            logger.exception("Couldn't put data for metric %s.%s", namespace, name)
            raise


    def get_metric_statistics(self, namespace, name, start, end, period, stat_types):
        """
        Gets statistics for a metric within a specified time span. Metrics are grouped
        into the specified period.

        :param namespace: The namespace of the metric.
        :param name: The name of the metric.
        :param start: The UTC start time of the time span to retrieve.
        :param end: The UTC end time of the time span to retrieve.
        :param period: The period, in seconds, in which to group metrics. The period
                       must match the granularity of the metric, which depends on
                       the metric's age. For example, metrics that are older than
                       three hours have a one-minute granularity, so the period must
                       be at least 60 and must be a multiple of 60.
        :param stat_types: The type of statistics to retrieve, such as average value
                           or maximum value.
        :return: The retrieved statistics for the metric.
        """
        try:
            metric = self.cloudwatch_resource.Metric(namespace, name)
            stats = metric.get_statistics(
                StartTime=start, EndTime=end, Period=period, Statistics=stat_types
            )
            logger.info(
                "Got %s statistics for %s.", len(stats["Datapoints"]), stats["Label"]
            )
        except ClientError:
            logger.exception("Couldn't get statistics for %s.%s.", namespace, name)
            raise
        else:
            return stats


    def get_metric_alarms(self, metric_namespace, metric_name):
        """
        Gets the alarms that are currently watching the specified metric.

        :param metric_namespace: The namespace of the metric.
        :param metric_name: The name of the metric.
        :returns: An iterator that yields the alarms.
        """
        metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name)
        alarm_iter = metric.alarms.all()
        logger.info("Got alarms for metric %s.%s.", metric_namespace, metric_name)
        return alarm_iter


    def delete_metric_alarms(self, metric_namespace, metric_name):
        """
        Deletes all of the alarms that are currently watching the specified metric.

        :param metric_namespace: The namespace of the metric.
        :param metric_name: The name of the metric.
        """
        try:
            metric = self.cloudwatch_resource.Metric(metric_namespace, metric_name)
            metric.alarms.delete()
            logger.info(
                "Deleted alarms for metric %s.%s.", metric_namespace, metric_name
            )
        except ClientError:
            logger.exception(
                "Couldn't delete alarms for metric %s.%s.",
                metric_namespace,
                metric_name,
            )
            raise
```
このラッパークラスを使用して、メトリクスにデータを配置し、メトリクスを監視するアラームをトリガーし、そのアラームからデータを取得します。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the Amazon CloudWatch metrics and alarms demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    cw_wrapper = CloudWatchWrapper(boto3.resource("cloudwatch"))

    minutes = 20
    metric_namespace = "doc-example-metric"
    metric_name = "page_views"
    start = datetime.utcnow() - timedelta(minutes=minutes)
    print(
        f"Putting data into metric {metric_namespace}.{metric_name} spanning the "
        f"last {minutes} minutes."
    )
    for offset in range(0, minutes):
        stamp = start + timedelta(minutes=offset)
        cw_wrapper.put_metric_data_set(
            metric_namespace,
            metric_name,
            stamp,
            "Count",
            {
                "values": [
                    random.randint(bound, bound * 2)
                    for bound in range(offset + 1, offset + 11)
                ],
                "counts": [random.randint(1, offset + 1) for _ in range(10)],
            },
        )

    alarm_name = "high_page_views"
    period = 60
    eval_periods = 2
    print(f"Creating alarm {alarm_name} for metric {metric_name}.")
    alarm = cw_wrapper.create_metric_alarm(
        metric_namespace,
        metric_name,
        alarm_name,
        "Maximum",
        period,
        eval_periods,
        100,
        "GreaterThanThreshold",
    )
    print(f"Alarm ARN is {alarm.alarm_arn}.")
    print(f"Current alarm state is: {alarm.state_value}.")

    print(
        f"Sending data to trigger the alarm. This requires data over the threshold "
        f"for {eval_periods} periods of {period} seconds each."
    )
    while alarm.state_value == "INSUFFICIENT_DATA":
        print("Sending data for the metric.")
        cw_wrapper.put_metric_data(
            metric_namespace, metric_name, random.randint(100, 200), "Count"
        )
        alarm.load()
        print(f"Current alarm state is: {alarm.state_value}.")
        if alarm.state_value == "INSUFFICIENT_DATA":
            print(f"Waiting for {period} seconds...")
            time.sleep(period)
        else:
            print("Wait for a minute for eventual consistency of metric data.")
            time.sleep(period)
            if alarm.state_value == "OK":
                alarm.load()
                print(f"Current alarm state is: {alarm.state_value}.")

    print(
        f"Getting data for metric {metric_namespace}.{metric_name} during timespan "
        f"of {start} to {datetime.utcnow()} (times are UTC)."
    )
    stats = cw_wrapper.get_metric_statistics(
        metric_namespace,
        metric_name,
        start,
        datetime.utcnow(),
        60,
        ["Average", "Minimum", "Maximum"],
    )
    print(
        f"Got {len(stats['Datapoints'])} data points for metric "
        f"{metric_namespace}.{metric_name}."
    )
    pprint(sorted(stats["Datapoints"], key=lambda x: x["Timestamp"]))

    print(f"Getting alarms for metric {metric_name}.")
    alarms = cw_wrapper.get_metric_alarms(metric_namespace, metric_name)
    for alarm in alarms:
        print(f"Alarm {alarm.name} is currently in state {alarm.state_value}.")

    print(f"Deleting alarms for metric {metric_name}.")
    cw_wrapper.delete_metric_alarms(metric_namespace, metric_name)

    print("Thanks for watching!")
    print("-" * 88)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [DeleteAlarms](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/DeleteAlarms)
  + [DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/DescribeAlarmsForMetric)
  + [DisableAlarmActions](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/DisableAlarmActions)
  + [EnableAlarmActions](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/EnableAlarmActions)
  + [GetMetricStatistics](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/GetMetricStatistics)
  + [ListMetrics](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/ListMetrics)
  + [PutMetricAlarm](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/PutMetricAlarm)
  + [PutMetricData](https://docs.aws.amazon.com/goto/boto3/monitoring-2010-08-01/PutMetricData)

# SDK for Python (Boto3) を使用する CloudWatch Logs の例
<a name="python_3_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `GetQueryResults`
<a name="cloudwatch-logs_GetQueryResults_python_3_topic"></a>

次のコード例は、`GetQueryResults` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
    def _wait_for_query_results(self, client, query_id):
        """
        Waits for the query to complete and retrieves the results.

        :param query_id: The ID of the initiated query.
        :type query_id: str
        :return: A list containing the results of the query.
        :rtype: list
        """
        while True:
            time.sleep(1)
            results = client.get_query_results(queryId=query_id)
            if results["status"] in [
                "Complete",
                "Failed",
                "Cancelled",
                "Timeout",
                "Unknown",
            ]:
                return results.get("results", [])
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API Reference*」の「[GetQueryResults](https://docs.aws.amazon.com/goto/boto3/logs-2014-03-28/GetQueryResults)」を参照してください。

### `StartLiveTail`
<a name="cloudwatch-logs_StartLiveTail_python_3_topic"></a>

次のコード例は、`StartLiveTail` を使用する方法を示しています。

**SDK for Python (Boto3)**  
必要なファイルを含めます。  

```
import boto3 
import time
from datetime import datetime
```
Live Tail セッションを開始します。  

```
    # Initialize the client
    client = boto3.client('logs')

    start_time = time.time()

    try:
        response = client.start_live_tail(
            logGroupIdentifiers=log_group_identifiers,
            logStreamNames=log_streams,
            logEventFilterPattern=filter_pattern
        )
        event_stream = response['responseStream']
        # Handle the events streamed back in the response
        for event in event_stream:
            # Set a timeout to close the stream.
            # This will end the Live Tail session.
            if (time.time() - start_time >= 10):
                event_stream.close()
                break
            # Handle when session is started
            if 'sessionStart' in event:
                session_start_event = event['sessionStart']
                print(session_start_event)
            # Handle when log event is given in a session update
            elif 'sessionUpdate' in event:
                log_events = event['sessionUpdate']['sessionResults']
                for log_event in log_events:
                    print('[{date}] {log}'.format(date=datetime.fromtimestamp(log_event['timestamp']/1000),log=log_event['message']))
            else:
                # On-stream exceptions are captured here
                raise RuntimeError(str(event))
    except Exception as e:
        print(e)
```
+  API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の「[StartLiveTail](https://docs.aws.amazon.com/goto/boto3/logs-2014-03-28/StartLiveTail)」を参照してください。

### `StartQuery`
<a name="cloudwatch-logs_StartQuery_python_3_topic"></a>

次のコード例は、`StartQuery` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch-logs#code-examples)での設定と実行の方法を確認してください。

```
    def perform_query(self, date_range):
        """
        Performs the actual CloudWatch log query.

        :param date_range: A tuple representing the start and end datetime for the query.
        :type date_range: tuple
        :return: A list containing the query results.
        :rtype: list
        """
        client = boto3.client("logs")
        try:
            try:
                start_time = round(
                    self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[0])
                )
                end_time = round(
                    self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[1])
                )
                response = client.start_query(
                    logGroupName=self.log_group,
                    startTime=start_time,
                    endTime=end_time,
                    queryString=self.query_string,
                    limit=self.limit,
                )
                query_id = response["queryId"]
            except client.exceptions.ResourceNotFoundException as e:
                raise DateOutOfBoundsError(f"Resource not found: {e}")
            while True:
                time.sleep(1)
                results = client.get_query_results(queryId=query_id)
                if results["status"] in [
                    "Complete",
                    "Failed",
                    "Cancelled",
                    "Timeout",
                    "Unknown",
                ]:
                    return results.get("results", [])
        except DateOutOfBoundsError:
            return []

    def _initiate_query(self, client, date_range, max_logs):
        """
        Initiates the CloudWatch logs query.

        :param date_range: A tuple representing the start and end datetime for the query.
        :type date_range: tuple
        :param max_logs: The maximum number of logs to retrieve.
        :type max_logs: int
        :return: The query ID as a string.
        :rtype: str
        """
        try:
            start_time = round(
                self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[0])
            )
            end_time = round(
                self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[1])
            )
            response = client.start_query(
                logGroupName=self.log_group,
                startTime=start_time,
                endTime=end_time,
                queryString=self.query_string,
                limit=max_logs,
            )
            return response["queryId"]
        except client.exceptions.ResourceNotFoundException as e:
            raise DateOutOfBoundsError(f"Resource not found: {e}")
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartQuery](https://docs.aws.amazon.com/goto/boto3/logs-2014-03-28/StartQuery)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 大規模なクエリを実行する
<a name="cloudwatch-logs_Scenario_BigQuery_python_3_topic"></a>

次のコード例は、CloudWatch Logs を使用して 10,000 を超えるレコードをクエリする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cloudwatch-logs/scenarios/large-query#code-examples)での設定と実行の方法を確認してください。
このファイルは、10,000 を超える結果の CloudWatch クエリを管理するためのサンプルモジュールを呼び出します。  

```
import logging
import os
import sys

import boto3
from botocore.config import Config

from cloudwatch_query import CloudWatchQuery
from date_utilities import DateUtilities

# Configure logging at the module level.
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s",
)

DEFAULT_QUERY_LOG_GROUP = "/workflows/cloudwatch-logs/large-query"


class CloudWatchLogsQueryRunner:
    def __init__(self):
        """
        Initializes the CloudWatchLogsQueryRunner class by setting up date utilities
        and creating a CloudWatch Logs client with retry configuration.
        """
        self.date_utilities = DateUtilities()
        self.cloudwatch_logs_client = self.create_cloudwatch_logs_client()

    def create_cloudwatch_logs_client(self):
        """
        Creates and returns a CloudWatch Logs client with a specified retry configuration.

        :return: A CloudWatch Logs client instance.
        :rtype: boto3.client
        """
        try:
            return boto3.client("logs", config=Config(retries={"max_attempts": 10}))
        except Exception as e:
            logging.error(f"Failed to create CloudWatch Logs client: {e}")
            sys.exit(1)

    def fetch_environment_variables(self):
        """
        Fetches and validates required environment variables for query start and end dates.
        Fetches the environment variable for log group, returning the default value if it
        does not exist.

        :return: Tuple of query start date and end date as integers and the log group.
        :rtype: tuple
        :raises SystemExit: If required environment variables are missing or invalid.
        """
        try:
            query_start_date = int(os.environ["QUERY_START_DATE"])
            query_end_date = int(os.environ["QUERY_END_DATE"])
        except KeyError:
            logging.error(
                "Both QUERY_START_DATE and QUERY_END_DATE environment variables are required."
            )
            sys.exit(1)
        except ValueError as e:
            logging.error(f"Error parsing date environment variables: {e}")
            sys.exit(1)
        
        try:
            log_group = os.environ["QUERY_LOG_GROUP"]
        except KeyError:
            logging.warning("No QUERY_LOG_GROUP environment variable, using default value")
            log_group = DEFAULT_QUERY_LOG_GROUP

        return query_start_date, query_end_date, log_group

    def convert_dates_to_iso8601(self, start_date, end_date):
        """
        Converts UNIX timestamp dates to ISO 8601 format using DateUtilities.

        :param start_date: The start date in UNIX timestamp.
        :type start_date: int
        :param end_date: The end date in UNIX timestamp.
        :type end_date: int
        :return: Start and end dates in ISO 8601 format.
        :rtype: tuple
        """
        start_date_iso8601 = self.date_utilities.convert_unix_timestamp_to_iso8601(
            start_date
        )
        end_date_iso8601 = self.date_utilities.convert_unix_timestamp_to_iso8601(
            end_date
        )
        return start_date_iso8601, end_date_iso8601

    def execute_query(
        self,
        start_date_iso8601,
        end_date_iso8601,
        log_group="/workflows/cloudwatch-logs/large-query",
        query="fields @timestamp, @message | sort @timestamp asc"
    ):
        """
        Creates a CloudWatchQuery instance and executes the query with provided date range.

        :param start_date_iso8601: The start date in ISO 8601 format.
        :type start_date_iso8601: str
        :param end_date_iso8601: The end date in ISO 8601 format.
        :type end_date_iso8601: str
        :param log_group: Log group to search: "/workflows/cloudwatch-logs/large-query"
        :type log_group: str
        :param query: Query string to pass to the CloudWatchQuery instance
        :type query: str
        """
        cloudwatch_query = CloudWatchQuery(
            log_group=log_group,
            query_string=query
        )
        cloudwatch_query.query_logs((start_date_iso8601, end_date_iso8601))
        logging.info("Query executed successfully.")
        logging.info(
            f"Queries completed in {cloudwatch_query.query_duration} seconds. Total logs found: {len(cloudwatch_query.query_results)}"
        )


def main():
    """
    Main function to start a recursive CloudWatch logs query.
    Fetches required environment variables, converts dates, and executes the query.
    """
    logging.info("Starting a recursive CloudWatch logs query...")
    runner = CloudWatchLogsQueryRunner()
    query_start_date, query_end_date, log_group = runner.fetch_environment_variables()
    start_date_iso8601 = DateUtilities.convert_unix_timestamp_to_iso8601(
        query_start_date
    )
    end_date_iso8601 = DateUtilities.convert_unix_timestamp_to_iso8601(query_end_date)
    runner.execute_query(start_date_iso8601, end_date_iso8601, log_group=log_group)


if __name__ == "__main__":
    main()
```
このモジュールは、10,000 を超える結果の CloudWatch クエリを処理します。  

```
import logging
import time
from datetime import datetime
import threading
import boto3

from date_utilities import DateUtilities

DEFAULT_QUERY = "fields @timestamp, @message | sort @timestamp asc"
DEFAULT_LOG_GROUP = "/workflows/cloudwatch-logs/large-query"

class DateOutOfBoundsError(Exception):
    """Exception raised when the date range for a query is out of bounds."""

    pass


class CloudWatchQuery:
    """
    A class to query AWS CloudWatch logs within a specified date range.

    :vartype date_range: tuple
    :ivar limit: Maximum number of log entries to return.
    :vartype limit: int
    :log_group str: Name of the log group to query
    :query_string str: query
    """

    def __init__(self, log_group: str = DEFAULT_LOG_GROUP, query_string: str=DEFAULT_QUERY) -> None:
        self.lock = threading.Lock()
        self.log_group = log_group
        self.query_string = query_string
        self.query_results = []
        self.query_duration = None
        self.datetime_format = "%Y-%m-%d %H:%M:%S.%f"
        self.date_utilities = DateUtilities()
        self.limit = 10000

    def query_logs(self, date_range):
        """
        Executes a CloudWatch logs query for a specified date range and calculates the execution time of the query.

        :return: A batch of logs retrieved from the CloudWatch logs query.
        :rtype: list
        """
        start_time = datetime.now()

        start_date, end_date = self.date_utilities.normalize_date_range_format(
            date_range, from_format="unix_timestamp", to_format="datetime"
        )

        logging.info(
            f"Original query:"
            f"\n       START:     {start_date}"
            f"\n       END:       {end_date}"
            f"\n       LOG GROUP: {self.log_group}"
        )
        self.recursive_query((start_date, end_date))
        end_time = datetime.now()
        self.query_duration = (end_time - start_time).total_seconds()

    def recursive_query(self, date_range):
        """
        Processes logs within a given date range, fetching batches of logs recursively if necessary.

        :param date_range: The date range to fetch logs for, specified as a tuple (start_timestamp, end_timestamp).
        :type date_range: tuple
        :return: None if the recursive fetching is continued or stops when the final batch of logs is processed.
                 Although it doesn't explicitly return the query results, this method accumulates all fetched logs
                 in the `self.query_results` attribute.
        :rtype: None
        """
        batch_of_logs = self.perform_query(date_range)
        # Add the batch to the accumulated logs
        with self.lock:
            self.query_results.extend(batch_of_logs)
        if len(batch_of_logs) == self.limit:
            logging.info(f"Fetched {self.limit}, checking for more...")
            most_recent_log = self.find_most_recent_log(batch_of_logs)
            most_recent_log_timestamp = next(
                item["value"]
                for item in most_recent_log
                if item["field"] == "@timestamp"
            )
            new_range = (most_recent_log_timestamp, date_range[1])
            midpoint = self.date_utilities.find_middle_time(new_range)

            first_half_thread = threading.Thread(
                target=self.recursive_query,
                args=((most_recent_log_timestamp, midpoint),),
            )
            second_half_thread = threading.Thread(
                target=self.recursive_query, args=((midpoint, date_range[1]),)
            )

            first_half_thread.start()
            second_half_thread.start()

            first_half_thread.join()
            second_half_thread.join()

    def find_most_recent_log(self, logs):
        """
        Search a list of log items and return most recent log entry.
        :param logs: A list of logs to analyze.
        :return: log
        :type :return List containing log item details
        """
        most_recent_log = None
        most_recent_date = "1970-01-01 00:00:00.000"

        for log in logs:
            for item in log:
                if item["field"] == "@timestamp":
                    logging.debug(f"Compared: {item['value']} to {most_recent_date}")
                    if (
                        self.date_utilities.compare_dates(
                            item["value"], most_recent_date
                        )
                        == item["value"]
                    ):
                        logging.debug(f"New most recent: {item['value']}")
                        most_recent_date = item["value"]
                        most_recent_log = log
        logging.info(f"Most recent log date of batch: {most_recent_date}")
        return most_recent_log

    def perform_query(self, date_range):
        """
        Performs the actual CloudWatch log query.

        :param date_range: A tuple representing the start and end datetime for the query.
        :type date_range: tuple
        :return: A list containing the query results.
        :rtype: list
        """
        client = boto3.client("logs")
        try:
            try:
                start_time = round(
                    self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[0])
                )
                end_time = round(
                    self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[1])
                )
                response = client.start_query(
                    logGroupName=self.log_group,
                    startTime=start_time,
                    endTime=end_time,
                    queryString=self.query_string,
                    limit=self.limit,
                )
                query_id = response["queryId"]
            except client.exceptions.ResourceNotFoundException as e:
                raise DateOutOfBoundsError(f"Resource not found: {e}")
            while True:
                time.sleep(1)
                results = client.get_query_results(queryId=query_id)
                if results["status"] in [
                    "Complete",
                    "Failed",
                    "Cancelled",
                    "Timeout",
                    "Unknown",
                ]:
                    return results.get("results", [])
        except DateOutOfBoundsError:
            return []

    def _initiate_query(self, client, date_range, max_logs):
        """
        Initiates the CloudWatch logs query.

        :param date_range: A tuple representing the start and end datetime for the query.
        :type date_range: tuple
        :param max_logs: The maximum number of logs to retrieve.
        :type max_logs: int
        :return: The query ID as a string.
        :rtype: str
        """
        try:
            start_time = round(
                self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[0])
            )
            end_time = round(
                self.date_utilities.convert_iso8601_to_unix_timestamp(date_range[1])
            )
            response = client.start_query(
                logGroupName=self.log_group,
                startTime=start_time,
                endTime=end_time,
                queryString=self.query_string,
                limit=max_logs,
            )
            return response["queryId"]
        except client.exceptions.ResourceNotFoundException as e:
            raise DateOutOfBoundsError(f"Resource not found: {e}")


    def _wait_for_query_results(self, client, query_id):
        """
        Waits for the query to complete and retrieves the results.

        :param query_id: The ID of the initiated query.
        :type query_id: str
        :return: A list containing the results of the query.
        :rtype: list
        """
        while True:
            time.sleep(1)
            results = client.get_query_results(queryId=query_id)
            if results["status"] in [
                "Complete",
                "Failed",
                "Cancelled",
                "Timeout",
                "Unknown",
            ]:
                return results.get("results", [])
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [GetQueryResults](https://docs.aws.amazon.com/goto/boto3/logs-2014-03-28/GetQueryResults)
  + [StartQuery](https://docs.aws.amazon.com/goto/boto3/logs-2014-03-28/StartQuery)

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_python_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例では、スケジュールされた Amazon EventBridge イベントのターゲットとして AWS Lambda 関数を登録する方法を示します。Lambda ハンドラーは、後で取得するために Amazon CloudWatch Logs にわかりやすいメッセージと完全なイベントデータを書き込みます。  
+ Lambda 関数をデプロイします。
+ EventBridge スケジュールイベントを作成し、Lambda 関数をターゲットにします。
+ EventBridge に Lambda 関数を呼び出す許可を付与します
+ CloudWatch Logs から最新のデータを出力して、スケジュールされた呼び出しの結果を表示しています。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

# SDK for Python (Boto3) を使用する Amazon Cognito ID の例
<a name="python_3_cognito-identity_code_examples"></a>

次のコード例は、Amazon Cognito Identity AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_python_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Textract AWS SDK for Python (Boto3) で を使用して、ドキュメントイメージ内のテキスト、フォーム、テーブル要素を検出する方法を示します。入力イメージと Amazon Textract 出力は、検出された要素を探索できる Tkinter アプリケーションに表示されます。  
+ Amazon Textract にドキュメントイメージを送信し、検出された要素の出力を調べます。
+ Amazon Textract に直接イメージを送信するか、Amazon Simple Storage Service (Amazon S3) バケットを通じてイメージを送信します。
+ 非同期 API を使用して、ジョブの完了時に Amazon Simple Notification Service (Amazon SNS) トピックに通知を発行するジョブを開始します。
+ Amazon Simple Queue Service (Amazon SQS) キューにジョブ完了メッセージについてポーリングし、結果を表示します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_explorer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

# SDK for Python (Boto3) を使用する Amazon Cognito ID プロバイダーの例
<a name="python_3_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダー AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon Cognito
<a name="cognito-identity-provider_Hello_python_3_topic"></a>

次のコード例は、Amazon Cognito の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
import boto3

# Create a Cognito Identity Provider client
cognitoidp = boto3.client("cognito-idp")

# Initialize a paginator for the list_user_pools operation
paginator = cognitoidp.get_paginator("list_user_pools")

# Create a PageIterator from the paginator
page_iterator = paginator.paginate(MaxResults=10)

# Initialize variables for pagination
user_pools = []

# Handle pagination
for page in page_iterator:
    user_pools.extend(page.get("UserPools", []))

# Print the list of user pools
print("User Pools for the account:")
if user_pools:
    for pool in user_pools:
        print(f"Name: {pool['Name']}, ID: {pool['Id']}")
else:
    print("No user pools found.")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListUserPools](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ListUserPools)」を参照してください。

## アクション
<a name="actions"></a>

### `AdminGetUser`
<a name="cognito-identity-provider_AdminGetUser_python_3_topic"></a>

次のコード例は、`AdminGetUser` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def sign_up_user(self, user_name, password, user_email):
        """
        Signs up a new user with Amazon Cognito. This action prompts Amazon Cognito
        to send an email to the specified email address. The email contains a code that
        can be used to confirm the user.

        When the user already exists, the user status is checked to determine whether
        the user has been confirmed.

        :param user_name: The user name that identifies the new user.
        :param password: The password for the new user.
        :param user_email: The email address for the new user.
        :return: True when the user is already confirmed with Amazon Cognito.
                 Otherwise, false.
        """
        try:
            kwargs = {
                "ClientId": self.client_id,
                "Username": user_name,
                "Password": password,
                "UserAttributes": [{"Name": "email", "Value": user_email}],
            }
            if self.client_secret is not None:
                kwargs["SecretHash"] = self._secret_hash(user_name)
            response = self.cognito_idp_client.sign_up(**kwargs)
            confirmed = response["UserConfirmed"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "UsernameExistsException":
                response = self.cognito_idp_client.admin_get_user(
                    UserPoolId=self.user_pool_id, Username=user_name
                )
                logger.warning(
                    "User %s exists and is %s.", user_name, response["UserStatus"]
                )
                confirmed = response["UserStatus"] == "CONFIRMED"
            else:
                logger.error(
                    "Couldn't sign up %s. Here's why: %s: %s",
                    user_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return confirmed
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AdminGetUser](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AdminGetUser)」を参照してください。

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_python_3_topic"></a>

次のコード例は、`AdminInitiateAuth` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def start_sign_in(self, user_name, password):
        """
        Starts the sign-in process for a user by using administrator credentials.
        This method of signing in is appropriate for code running on a secure server.

        If the user pool is configured to require MFA and this is the first sign-in
        for the user, Amazon Cognito returns a challenge response to set up an
        MFA application. When this occurs, this function gets an MFA secret from
        Amazon Cognito and returns it to the caller.

        :param user_name: The name of the user to sign in.
        :param password: The user's password.
        :return: The result of the sign-in attempt. When sign-in is successful, this
                 returns an access token that can be used to get AWS credentials. Otherwise,
                 Amazon Cognito returns a challenge to set up an MFA application,
                 or a challenge to enter an MFA code from a registered MFA application.
        """
        try:
            kwargs = {
                "UserPoolId": self.user_pool_id,
                "ClientId": self.client_id,
                "AuthFlow": "ADMIN_USER_PASSWORD_AUTH",
                "AuthParameters": {"USERNAME": user_name, "PASSWORD": password},
            }
            if self.client_secret is not None:
                kwargs["AuthParameters"]["SECRET_HASH"] = self._secret_hash(user_name)
            response = self.cognito_idp_client.admin_initiate_auth(**kwargs)
            challenge_name = response.get("ChallengeName", None)
            if challenge_name == "MFA_SETUP":
                if (
                    "SOFTWARE_TOKEN_MFA"
                    in response["ChallengeParameters"]["MFAS_CAN_SETUP"]
                ):
                    response.update(self.get_mfa_secret(response["Session"]))
                else:
                    raise RuntimeError(
                        "The user pool requires MFA setup, but the user pool is not "
                        "configured for TOTP MFA. This example requires TOTP MFA."
                    )
        except ClientError as err:
            logger.error(
                "Couldn't start sign in for %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            response.pop("ResponseMetadata", None)
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AdminInitiateAuth](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AdminInitiateAuth)」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_python_3_topic"></a>

次のコード例は、`AdminRespondToAuthChallenge` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。
MFA のチャレンジに応答するには、関連する MFA アプリケーションによって生成されたコードを入手します。  

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def respond_to_mfa_challenge(self, user_name, session, mfa_code):
        """
        Responds to a challenge for an MFA code. This completes the second step of
        a two-factor sign-in. When sign-in is successful, it returns an access token
        that can be used to get AWS credentials from Amazon Cognito.

        :param user_name: The name of the user who is signing in.
        :param session: Session information returned from a previous call to initiate
                        authentication.
        :param mfa_code: A code generated by the associated MFA application.
        :return: The result of the authentication. When successful, this contains an
                 access token for the user.
        """
        try:
            kwargs = {
                "UserPoolId": self.user_pool_id,
                "ClientId": self.client_id,
                "ChallengeName": "SOFTWARE_TOKEN_MFA",
                "Session": session,
                "ChallengeResponses": {
                    "USERNAME": user_name,
                    "SOFTWARE_TOKEN_MFA_CODE": mfa_code,
                },
            }
            if self.client_secret is not None:
                kwargs["ChallengeResponses"]["SECRET_HASH"] = self._secret_hash(
                    user_name
                )
            response = self.cognito_idp_client.admin_respond_to_auth_challenge(**kwargs)
            auth_result = response["AuthenticationResult"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ExpiredCodeException":
                logger.warning(
                    "Your MFA code has expired or has been used already. You might have "
                    "to wait a few seconds until your app shows you a new code."
                )
            else:
                logger.error(
                    "Couldn't respond to mfa challenge for %s. Here's why: %s: %s",
                    user_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return auth_result
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)」を参照してください。

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_python_3_topic"></a>

次のコード例は、`AssociateSoftwareToken` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def get_mfa_secret(self, session):
        """
        Gets a token that can be used to associate an MFA application with the user.

        :param session: Session information returned from a previous call to initiate
                        authentication.
        :return: An MFA token that can be used to set up an MFA application.
        """
        try:
            response = self.cognito_idp_client.associate_software_token(Session=session)
        except ClientError as err:
            logger.error(
                "Couldn't get MFA secret. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            response.pop("ResponseMetadata", None)
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AssociateSoftwareToken](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AssociateSoftwareToken)」を参照してください。

### `ConfirmDevice`
<a name="cognito-identity-provider_ConfirmDevice_python_3_topic"></a>

次のコード例は、`ConfirmDevice` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def confirm_mfa_device(
        self,
        user_name,
        device_key,
        device_group_key,
        device_password,
        access_token,
        aws_srp,
    ):
        """
        Confirms an MFA device to be tracked by Amazon Cognito. When a device is
        tracked, its key and password can be used to sign in without requiring a new
        MFA code from the MFA application.

        :param user_name: The user that is associated with the device.
        :param device_key: The key of the device, returned by Amazon Cognito.
        :param device_group_key: The group key of the device, returned by Amazon Cognito.
        :param device_password: The password that is associated with the device.
        :param access_token: The user's access token.
        :param aws_srp: A class that helps with Secure Remote Password (SRP)
                        calculations. The scenario associated with this example uses
                        the warrant package.
        :return: True when the user must confirm the device. Otherwise, False. When
                 False, the device is automatically confirmed and tracked.
        """
        srp_helper = aws_srp.AWSSRP(
            username=user_name,
            password=device_password,
            pool_id="_",
            client_id=self.client_id,
            client_secret=None,
            client=self.cognito_idp_client,
        )
        device_and_pw = f"{device_group_key}{device_key}:{device_password}"
        device_and_pw_hash = aws_srp.hash_sha256(device_and_pw.encode("utf-8"))
        salt = aws_srp.pad_hex(aws_srp.get_random(16))
        x_value = aws_srp.hex_to_long(aws_srp.hex_hash(salt + device_and_pw_hash))
        verifier = aws_srp.pad_hex(pow(srp_helper.val_g, x_value, srp_helper.big_n))
        device_secret_verifier_config = {
            "PasswordVerifier": base64.standard_b64encode(
                bytearray.fromhex(verifier)
            ).decode("utf-8"),
            "Salt": base64.standard_b64encode(bytearray.fromhex(salt)).decode("utf-8"),
        }
        try:
            response = self.cognito_idp_client.confirm_device(
                AccessToken=access_token,
                DeviceKey=device_key,
                DeviceSecretVerifierConfig=device_secret_verifier_config,
            )
            user_confirm = response["UserConfirmationNecessary"]
        except ClientError as err:
            logger.error(
                "Couldn't confirm mfa device %s. Here's why: %s: %s",
                device_key,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return user_confirm
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ConfirmDevice](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ConfirmDevice)」を参照してください。

### `ConfirmSignUp`
<a name="cognito-identity-provider_ConfirmSignUp_python_3_topic"></a>

次のコード例は、`ConfirmSignUp` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def confirm_user_sign_up(self, user_name, confirmation_code):
        """
        Confirms a previously created user. A user must be confirmed before they
        can sign in to Amazon Cognito.

        :param user_name: The name of the user to confirm.
        :param confirmation_code: The confirmation code sent to the user's registered
                                  email address.
        :return: True when the confirmation succeeds.
        """
        try:
            kwargs = {
                "ClientId": self.client_id,
                "Username": user_name,
                "ConfirmationCode": confirmation_code,
            }
            if self.client_secret is not None:
                kwargs["SecretHash"] = self._secret_hash(user_name)
            self.cognito_idp_client.confirm_sign_up(**kwargs)
        except ClientError as err:
            logger.error(
                "Couldn't confirm sign up for %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return True
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ConfirmSignUp](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ConfirmSignUp)」を参照してください。

### `InitiateAuth`
<a name="cognito-identity-provider_InitiateAuth_python_3_topic"></a>

次のコード例は、`InitiateAuth` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。
この例は、トラッキング対象デバイスを使用して認証を開始する方法を示しています。サインインを完了するには、クライアントはセキュアリモートパスワード (SRP) チャレンジに正しく応答する必要があります。  

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def sign_in_with_tracked_device(
        self,
        user_name,
        password,
        device_key,
        device_group_key,
        device_password,
        aws_srp,
    ):
        """
        Signs in to Amazon Cognito as a user who has a tracked device. Signing in
        with a tracked device lets a user sign in without entering a new MFA code.

        Signing in with a tracked device requires that the client respond to the SRP
        protocol. The scenario associated with this example uses the warrant package
        to help with SRP calculations.

        For more information on SRP, see https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol.

        :param user_name: The user that is associated with the device.
        :param password: The user's password.
        :param device_key: The key of a tracked device.
        :param device_group_key: The group key of a tracked device.
        :param device_password: The password that is associated with the device.
        :param aws_srp: A class that helps with SRP calculations. The scenario
                        associated with this example uses the warrant package.
        :return: The result of the authentication. When successful, this contains an
                 access token for the user.
        """
        try:
            srp_helper = aws_srp.AWSSRP(
                username=user_name,
                password=device_password,
                pool_id="_",
                client_id=self.client_id,
                client_secret=None,
                client=self.cognito_idp_client,
            )

            response_init = self.cognito_idp_client.initiate_auth(
                ClientId=self.client_id,
                AuthFlow="USER_PASSWORD_AUTH",
                AuthParameters={
                    "USERNAME": user_name,
                    "PASSWORD": password,
                    "DEVICE_KEY": device_key,
                },
            )
            if response_init["ChallengeName"] != "DEVICE_SRP_AUTH":
                raise RuntimeError(
                    f"Expected DEVICE_SRP_AUTH challenge but got {response_init['ChallengeName']}."
                )

            auth_params = srp_helper.get_auth_params()
            auth_params["DEVICE_KEY"] = device_key
            response_auth = self.cognito_idp_client.respond_to_auth_challenge(
                ClientId=self.client_id,
                ChallengeName="DEVICE_SRP_AUTH",
                ChallengeResponses=auth_params,
            )
            if response_auth["ChallengeName"] != "DEVICE_PASSWORD_VERIFIER":
                raise RuntimeError(
                    f"Expected DEVICE_PASSWORD_VERIFIER challenge but got "
                    f"{response_init['ChallengeName']}."
                )

            challenge_params = response_auth["ChallengeParameters"]
            challenge_params["USER_ID_FOR_SRP"] = device_group_key + device_key
            cr = srp_helper.process_challenge(challenge_params, {"USERNAME": user_name})
            cr["USERNAME"] = user_name
            cr["DEVICE_KEY"] = device_key
            response_verifier = self.cognito_idp_client.respond_to_auth_challenge(
                ClientId=self.client_id,
                ChallengeName="DEVICE_PASSWORD_VERIFIER",
                ChallengeResponses=cr,
            )
            auth_tokens = response_verifier["AuthenticationResult"]
        except ClientError as err:
            logger.error(
                "Couldn't start client sign in for %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return auth_tokens
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[InitiateAuth](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/InitiateAuth)」を参照してください。

### `ListUsers`
<a name="cognito-identity-provider_ListUsers_python_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def list_users(self):
        """
        Returns a list of the users in the current user pool.

        :return: The list of users.
        """
        try:
            response = self.cognito_idp_client.list_users(UserPoolId=self.user_pool_id)
            users = response["Users"]
        except ClientError as err:
            logger.error(
                "Couldn't list users for %s. Here's why: %s: %s",
                self.user_pool_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return users
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListUsers](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ListUsers)」を参照してください。

### `ResendConfirmationCode`
<a name="cognito-identity-provider_ResendConfirmationCode_python_3_topic"></a>

次のコード例は、`ResendConfirmationCode` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def resend_confirmation(self, user_name):
        """
        Prompts Amazon Cognito to resend an email with a new confirmation code.

        :param user_name: The name of the user who will receive the email.
        :return: Delivery information about where the email is sent.
        """
        try:
            kwargs = {"ClientId": self.client_id, "Username": user_name}
            if self.client_secret is not None:
                kwargs["SecretHash"] = self._secret_hash(user_name)
            response = self.cognito_idp_client.resend_confirmation_code(**kwargs)
            delivery = response["CodeDeliveryDetails"]
        except ClientError as err:
            logger.error(
                "Couldn't resend confirmation to %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return delivery
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ResendConfirmationCode](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ResendConfirmationCode)」を参照してください。

### `RespondToAuthChallenge`
<a name="cognito-identity-provider_RespondToAuthChallenge_python_3_topic"></a>

次のコード例は、`RespondToAuthChallenge` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。
追跡対象デバイスでサインインします。サインインを完了するには、クライアントはセキュアリモートパスワード (SRP) チャレンジに正しく応答する必要があります。  

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def sign_in_with_tracked_device(
        self,
        user_name,
        password,
        device_key,
        device_group_key,
        device_password,
        aws_srp,
    ):
        """
        Signs in to Amazon Cognito as a user who has a tracked device. Signing in
        with a tracked device lets a user sign in without entering a new MFA code.

        Signing in with a tracked device requires that the client respond to the SRP
        protocol. The scenario associated with this example uses the warrant package
        to help with SRP calculations.

        For more information on SRP, see https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol.

        :param user_name: The user that is associated with the device.
        :param password: The user's password.
        :param device_key: The key of a tracked device.
        :param device_group_key: The group key of a tracked device.
        :param device_password: The password that is associated with the device.
        :param aws_srp: A class that helps with SRP calculations. The scenario
                        associated with this example uses the warrant package.
        :return: The result of the authentication. When successful, this contains an
                 access token for the user.
        """
        try:
            srp_helper = aws_srp.AWSSRP(
                username=user_name,
                password=device_password,
                pool_id="_",
                client_id=self.client_id,
                client_secret=None,
                client=self.cognito_idp_client,
            )

            response_init = self.cognito_idp_client.initiate_auth(
                ClientId=self.client_id,
                AuthFlow="USER_PASSWORD_AUTH",
                AuthParameters={
                    "USERNAME": user_name,
                    "PASSWORD": password,
                    "DEVICE_KEY": device_key,
                },
            )
            if response_init["ChallengeName"] != "DEVICE_SRP_AUTH":
                raise RuntimeError(
                    f"Expected DEVICE_SRP_AUTH challenge but got {response_init['ChallengeName']}."
                )

            auth_params = srp_helper.get_auth_params()
            auth_params["DEVICE_KEY"] = device_key
            response_auth = self.cognito_idp_client.respond_to_auth_challenge(
                ClientId=self.client_id,
                ChallengeName="DEVICE_SRP_AUTH",
                ChallengeResponses=auth_params,
            )
            if response_auth["ChallengeName"] != "DEVICE_PASSWORD_VERIFIER":
                raise RuntimeError(
                    f"Expected DEVICE_PASSWORD_VERIFIER challenge but got "
                    f"{response_init['ChallengeName']}."
                )

            challenge_params = response_auth["ChallengeParameters"]
            challenge_params["USER_ID_FOR_SRP"] = device_group_key + device_key
            cr = srp_helper.process_challenge(challenge_params, {"USERNAME": user_name})
            cr["USERNAME"] = user_name
            cr["DEVICE_KEY"] = device_key
            response_verifier = self.cognito_idp_client.respond_to_auth_challenge(
                ClientId=self.client_id,
                ChallengeName="DEVICE_PASSWORD_VERIFIER",
                ChallengeResponses=cr,
            )
            auth_tokens = response_verifier["AuthenticationResult"]
        except ClientError as err:
            logger.error(
                "Couldn't start client sign in for %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return auth_tokens
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[RespondToAuthChallenge](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/RespondToAuthChallenge)」を参照してください。

### `SignUp`
<a name="cognito-identity-provider_SignUp_python_3_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def sign_up_user(self, user_name, password, user_email):
        """
        Signs up a new user with Amazon Cognito. This action prompts Amazon Cognito
        to send an email to the specified email address. The email contains a code that
        can be used to confirm the user.

        When the user already exists, the user status is checked to determine whether
        the user has been confirmed.

        :param user_name: The user name that identifies the new user.
        :param password: The password for the new user.
        :param user_email: The email address for the new user.
        :return: True when the user is already confirmed with Amazon Cognito.
                 Otherwise, false.
        """
        try:
            kwargs = {
                "ClientId": self.client_id,
                "Username": user_name,
                "Password": password,
                "UserAttributes": [{"Name": "email", "Value": user_email}],
            }
            if self.client_secret is not None:
                kwargs["SecretHash"] = self._secret_hash(user_name)
            response = self.cognito_idp_client.sign_up(**kwargs)
            confirmed = response["UserConfirmed"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "UsernameExistsException":
                response = self.cognito_idp_client.admin_get_user(
                    UserPoolId=self.user_pool_id, Username=user_name
                )
                logger.warning(
                    "User %s exists and is %s.", user_name, response["UserStatus"]
                )
                confirmed = response["UserStatus"] == "CONFIRMED"
            else:
                logger.error(
                    "Couldn't sign up %s. Here's why: %s: %s",
                    user_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return confirmed
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SignUp](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/SignUp)」を参照してください。

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_python_3_topic"></a>

次のコード例は、`VerifySoftwareToken` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def verify_mfa(self, session, user_code):
        """
        Verify a new MFA application that is associated with a user.

        :param session: Session information returned from a previous call to initiate
                        authentication.
        :param user_code: A code generated by the associated MFA application.
        :return: Status that indicates whether the MFA application is verified.
        """
        try:
            response = self.cognito_idp_client.verify_software_token(
                Session=session, UserCode=user_code
            )
        except ClientError as err:
            logger.error(
                "Couldn't verify MFA. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            response.pop("ResponseMetadata", None)
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[VerifySoftwareToken](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/VerifySoftwareToken)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### MFA を必要とするユーザープールでユーザーをサインアップする
<a name="cognito-identity-provider_Scenario_SignUpUserWithMfa_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。
+ MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。
+ パスワードと MFA コードを使用してサインインします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito#code-examples)での設定と実行の方法を確認してください。
シナリオで使用される Amazon Cognito 関数をラップするクラスを作成します。  

```
class CognitoIdentityProviderWrapper:
    """Encapsulates Amazon Cognito actions"""

    def __init__(self, cognito_idp_client, user_pool_id, client_id, client_secret=None):
        """
        :param cognito_idp_client: A Boto3 Amazon Cognito Identity Provider client.
        :param user_pool_id: The ID of an existing Amazon Cognito user pool.
        :param client_id: The ID of a client application registered with the user pool.
        :param client_secret: The client secret, if the client has a secret.
        """
        self.cognito_idp_client = cognito_idp_client
        self.user_pool_id = user_pool_id
        self.client_id = client_id
        self.client_secret = client_secret


    def _secret_hash(self, user_name):
        """
        Calculates a secret hash from a user name and a client secret.

        :param user_name: The user name to use when calculating the hash.
        :return: The secret hash.
        """
        key = self.client_secret.encode()
        msg = bytes(user_name + self.client_id, "utf-8")
        secret_hash = base64.b64encode(
            hmac.new(key, msg, digestmod=hashlib.sha256).digest()
        ).decode()
        logger.info("Made secret hash for %s: %s.", user_name, secret_hash)
        return secret_hash

    def sign_up_user(self, user_name, password, user_email):
        """
        Signs up a new user with Amazon Cognito. This action prompts Amazon Cognito
        to send an email to the specified email address. The email contains a code that
        can be used to confirm the user.

        When the user already exists, the user status is checked to determine whether
        the user has been confirmed.

        :param user_name: The user name that identifies the new user.
        :param password: The password for the new user.
        :param user_email: The email address for the new user.
        :return: True when the user is already confirmed with Amazon Cognito.
                 Otherwise, false.
        """
        try:
            kwargs = {
                "ClientId": self.client_id,
                "Username": user_name,
                "Password": password,
                "UserAttributes": [{"Name": "email", "Value": user_email}],
            }
            if self.client_secret is not None:
                kwargs["SecretHash"] = self._secret_hash(user_name)
            response = self.cognito_idp_client.sign_up(**kwargs)
            confirmed = response["UserConfirmed"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "UsernameExistsException":
                response = self.cognito_idp_client.admin_get_user(
                    UserPoolId=self.user_pool_id, Username=user_name
                )
                logger.warning(
                    "User %s exists and is %s.", user_name, response["UserStatus"]
                )
                confirmed = response["UserStatus"] == "CONFIRMED"
            else:
                logger.error(
                    "Couldn't sign up %s. Here's why: %s: %s",
                    user_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return confirmed


    def resend_confirmation(self, user_name):
        """
        Prompts Amazon Cognito to resend an email with a new confirmation code.

        :param user_name: The name of the user who will receive the email.
        :return: Delivery information about where the email is sent.
        """
        try:
            kwargs = {"ClientId": self.client_id, "Username": user_name}
            if self.client_secret is not None:
                kwargs["SecretHash"] = self._secret_hash(user_name)
            response = self.cognito_idp_client.resend_confirmation_code(**kwargs)
            delivery = response["CodeDeliveryDetails"]
        except ClientError as err:
            logger.error(
                "Couldn't resend confirmation to %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return delivery


    def confirm_user_sign_up(self, user_name, confirmation_code):
        """
        Confirms a previously created user. A user must be confirmed before they
        can sign in to Amazon Cognito.

        :param user_name: The name of the user to confirm.
        :param confirmation_code: The confirmation code sent to the user's registered
                                  email address.
        :return: True when the confirmation succeeds.
        """
        try:
            kwargs = {
                "ClientId": self.client_id,
                "Username": user_name,
                "ConfirmationCode": confirmation_code,
            }
            if self.client_secret is not None:
                kwargs["SecretHash"] = self._secret_hash(user_name)
            self.cognito_idp_client.confirm_sign_up(**kwargs)
        except ClientError as err:
            logger.error(
                "Couldn't confirm sign up for %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return True


    def list_users(self):
        """
        Returns a list of the users in the current user pool.

        :return: The list of users.
        """
        try:
            response = self.cognito_idp_client.list_users(UserPoolId=self.user_pool_id)
            users = response["Users"]
        except ClientError as err:
            logger.error(
                "Couldn't list users for %s. Here's why: %s: %s",
                self.user_pool_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return users


    def start_sign_in(self, user_name, password):
        """
        Starts the sign-in process for a user by using administrator credentials.
        This method of signing in is appropriate for code running on a secure server.

        If the user pool is configured to require MFA and this is the first sign-in
        for the user, Amazon Cognito returns a challenge response to set up an
        MFA application. When this occurs, this function gets an MFA secret from
        Amazon Cognito and returns it to the caller.

        :param user_name: The name of the user to sign in.
        :param password: The user's password.
        :return: The result of the sign-in attempt. When sign-in is successful, this
                 returns an access token that can be used to get AWS credentials. Otherwise,
                 Amazon Cognito returns a challenge to set up an MFA application,
                 or a challenge to enter an MFA code from a registered MFA application.
        """
        try:
            kwargs = {
                "UserPoolId": self.user_pool_id,
                "ClientId": self.client_id,
                "AuthFlow": "ADMIN_USER_PASSWORD_AUTH",
                "AuthParameters": {"USERNAME": user_name, "PASSWORD": password},
            }
            if self.client_secret is not None:
                kwargs["AuthParameters"]["SECRET_HASH"] = self._secret_hash(user_name)
            response = self.cognito_idp_client.admin_initiate_auth(**kwargs)
            challenge_name = response.get("ChallengeName", None)
            if challenge_name == "MFA_SETUP":
                if (
                    "SOFTWARE_TOKEN_MFA"
                    in response["ChallengeParameters"]["MFAS_CAN_SETUP"]
                ):
                    response.update(self.get_mfa_secret(response["Session"]))
                else:
                    raise RuntimeError(
                        "The user pool requires MFA setup, but the user pool is not "
                        "configured for TOTP MFA. This example requires TOTP MFA."
                    )
        except ClientError as err:
            logger.error(
                "Couldn't start sign in for %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            response.pop("ResponseMetadata", None)
            return response


    def get_mfa_secret(self, session):
        """
        Gets a token that can be used to associate an MFA application with the user.

        :param session: Session information returned from a previous call to initiate
                        authentication.
        :return: An MFA token that can be used to set up an MFA application.
        """
        try:
            response = self.cognito_idp_client.associate_software_token(Session=session)
        except ClientError as err:
            logger.error(
                "Couldn't get MFA secret. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            response.pop("ResponseMetadata", None)
            return response


    def verify_mfa(self, session, user_code):
        """
        Verify a new MFA application that is associated with a user.

        :param session: Session information returned from a previous call to initiate
                        authentication.
        :param user_code: A code generated by the associated MFA application.
        :return: Status that indicates whether the MFA application is verified.
        """
        try:
            response = self.cognito_idp_client.verify_software_token(
                Session=session, UserCode=user_code
            )
        except ClientError as err:
            logger.error(
                "Couldn't verify MFA. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            response.pop("ResponseMetadata", None)
            return response


    def respond_to_mfa_challenge(self, user_name, session, mfa_code):
        """
        Responds to a challenge for an MFA code. This completes the second step of
        a two-factor sign-in. When sign-in is successful, it returns an access token
        that can be used to get AWS credentials from Amazon Cognito.

        :param user_name: The name of the user who is signing in.
        :param session: Session information returned from a previous call to initiate
                        authentication.
        :param mfa_code: A code generated by the associated MFA application.
        :return: The result of the authentication. When successful, this contains an
                 access token for the user.
        """
        try:
            kwargs = {
                "UserPoolId": self.user_pool_id,
                "ClientId": self.client_id,
                "ChallengeName": "SOFTWARE_TOKEN_MFA",
                "Session": session,
                "ChallengeResponses": {
                    "USERNAME": user_name,
                    "SOFTWARE_TOKEN_MFA_CODE": mfa_code,
                },
            }
            if self.client_secret is not None:
                kwargs["ChallengeResponses"]["SECRET_HASH"] = self._secret_hash(
                    user_name
                )
            response = self.cognito_idp_client.admin_respond_to_auth_challenge(**kwargs)
            auth_result = response["AuthenticationResult"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ExpiredCodeException":
                logger.warning(
                    "Your MFA code has expired or has been used already. You might have "
                    "to wait a few seconds until your app shows you a new code."
                )
            else:
                logger.error(
                    "Couldn't respond to mfa challenge for %s. Here's why: %s: %s",
                    user_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return auth_result


    def confirm_mfa_device(
        self,
        user_name,
        device_key,
        device_group_key,
        device_password,
        access_token,
        aws_srp,
    ):
        """
        Confirms an MFA device to be tracked by Amazon Cognito. When a device is
        tracked, its key and password can be used to sign in without requiring a new
        MFA code from the MFA application.

        :param user_name: The user that is associated with the device.
        :param device_key: The key of the device, returned by Amazon Cognito.
        :param device_group_key: The group key of the device, returned by Amazon Cognito.
        :param device_password: The password that is associated with the device.
        :param access_token: The user's access token.
        :param aws_srp: A class that helps with Secure Remote Password (SRP)
                        calculations. The scenario associated with this example uses
                        the warrant package.
        :return: True when the user must confirm the device. Otherwise, False. When
                 False, the device is automatically confirmed and tracked.
        """
        srp_helper = aws_srp.AWSSRP(
            username=user_name,
            password=device_password,
            pool_id="_",
            client_id=self.client_id,
            client_secret=None,
            client=self.cognito_idp_client,
        )
        device_and_pw = f"{device_group_key}{device_key}:{device_password}"
        device_and_pw_hash = aws_srp.hash_sha256(device_and_pw.encode("utf-8"))
        salt = aws_srp.pad_hex(aws_srp.get_random(16))
        x_value = aws_srp.hex_to_long(aws_srp.hex_hash(salt + device_and_pw_hash))
        verifier = aws_srp.pad_hex(pow(srp_helper.val_g, x_value, srp_helper.big_n))
        device_secret_verifier_config = {
            "PasswordVerifier": base64.standard_b64encode(
                bytearray.fromhex(verifier)
            ).decode("utf-8"),
            "Salt": base64.standard_b64encode(bytearray.fromhex(salt)).decode("utf-8"),
        }
        try:
            response = self.cognito_idp_client.confirm_device(
                AccessToken=access_token,
                DeviceKey=device_key,
                DeviceSecretVerifierConfig=device_secret_verifier_config,
            )
            user_confirm = response["UserConfirmationNecessary"]
        except ClientError as err:
            logger.error(
                "Couldn't confirm mfa device %s. Here's why: %s: %s",
                device_key,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return user_confirm


    def sign_in_with_tracked_device(
        self,
        user_name,
        password,
        device_key,
        device_group_key,
        device_password,
        aws_srp,
    ):
        """
        Signs in to Amazon Cognito as a user who has a tracked device. Signing in
        with a tracked device lets a user sign in without entering a new MFA code.

        Signing in with a tracked device requires that the client respond to the SRP
        protocol. The scenario associated with this example uses the warrant package
        to help with SRP calculations.

        For more information on SRP, see https://en.wikipedia.org/wiki/Secure_Remote_Password_protocol.

        :param user_name: The user that is associated with the device.
        :param password: The user's password.
        :param device_key: The key of a tracked device.
        :param device_group_key: The group key of a tracked device.
        :param device_password: The password that is associated with the device.
        :param aws_srp: A class that helps with SRP calculations. The scenario
                        associated with this example uses the warrant package.
        :return: The result of the authentication. When successful, this contains an
                 access token for the user.
        """
        try:
            srp_helper = aws_srp.AWSSRP(
                username=user_name,
                password=device_password,
                pool_id="_",
                client_id=self.client_id,
                client_secret=None,
                client=self.cognito_idp_client,
            )

            response_init = self.cognito_idp_client.initiate_auth(
                ClientId=self.client_id,
                AuthFlow="USER_PASSWORD_AUTH",
                AuthParameters={
                    "USERNAME": user_name,
                    "PASSWORD": password,
                    "DEVICE_KEY": device_key,
                },
            )
            if response_init["ChallengeName"] != "DEVICE_SRP_AUTH":
                raise RuntimeError(
                    f"Expected DEVICE_SRP_AUTH challenge but got {response_init['ChallengeName']}."
                )

            auth_params = srp_helper.get_auth_params()
            auth_params["DEVICE_KEY"] = device_key
            response_auth = self.cognito_idp_client.respond_to_auth_challenge(
                ClientId=self.client_id,
                ChallengeName="DEVICE_SRP_AUTH",
                ChallengeResponses=auth_params,
            )
            if response_auth["ChallengeName"] != "DEVICE_PASSWORD_VERIFIER":
                raise RuntimeError(
                    f"Expected DEVICE_PASSWORD_VERIFIER challenge but got "
                    f"{response_init['ChallengeName']}."
                )

            challenge_params = response_auth["ChallengeParameters"]
            challenge_params["USER_ID_FOR_SRP"] = device_group_key + device_key
            cr = srp_helper.process_challenge(challenge_params, {"USERNAME": user_name})
            cr["USERNAME"] = user_name
            cr["DEVICE_KEY"] = device_key
            response_verifier = self.cognito_idp_client.respond_to_auth_challenge(
                ClientId=self.client_id,
                ChallengeName="DEVICE_PASSWORD_VERIFIER",
                ChallengeResponses=cr,
            )
            auth_tokens = response_verifier["AuthenticationResult"]
        except ClientError as err:
            logger.error(
                "Couldn't start client sign in for %s. Here's why: %s: %s",
                user_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return auth_tokens
```
シナリオを実行するクラスを作成します。この例では Amazon Cognito で追跡する MFA デバイスを登録し、追跡対象デバイスのパスワードと情報を使用してサインインする方法も示します。これにより、新しい MFA コードを入力する必要がなくなります。  

```
def run_scenario(cognito_idp_client, user_pool_id, client_id):
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Welcome to the Amazon Cognito user signup with MFA demo.")
    print("-" * 88)

    cog_wrapper = CognitoIdentityProviderWrapper(
        cognito_idp_client, user_pool_id, client_id
    )

    user_name = q.ask("Let's sign up a new user. Enter a user name: ", q.non_empty)
    password = q.ask("Enter a password for the user: ", q.non_empty)
    email = q.ask("Enter a valid email address that you own: ", q.non_empty)
    confirmed = cog_wrapper.sign_up_user(user_name, password, email)
    while not confirmed:
        print(
            f"User {user_name} requires confirmation. Check {email} for "
            f"a verification code."
        )
        confirmation_code = q.ask("Enter the confirmation code from the email: ")
        if not confirmation_code:
            if q.ask("Do you need another confirmation code (y/n)? ", q.is_yesno):
                delivery = cog_wrapper.resend_confirmation(user_name)
                print(
                    f"Confirmation code sent by {delivery['DeliveryMedium']} "
                    f"to {delivery['Destination']}."
                )
        else:
            confirmed = cog_wrapper.confirm_user_sign_up(user_name, confirmation_code)
    print(f"User {user_name} is confirmed and ready to use.")
    print("-" * 88)

    print("Let's get a list of users in the user pool.")
    q.ask("Press Enter when you're ready.")
    users = cog_wrapper.list_users()
    if users:
        print(f"Found {len(users)} users:")
        pp(users)
    else:
        print("No users found.")
    print("-" * 88)

    print("Let's sign in and get an access token.")
    auth_tokens = None
    challenge = "ADMIN_USER_PASSWORD_AUTH"
    response = {}
    while challenge is not None:
        if challenge == "ADMIN_USER_PASSWORD_AUTH":
            response = cog_wrapper.start_sign_in(user_name, password)
            challenge = response["ChallengeName"]
        elif response["ChallengeName"] == "MFA_SETUP":
            print("First, we need to set up an MFA application.")
            qr_img = qrcode.make(
                f"otpauth://totp/{user_name}?secret={response['SecretCode']}"
            )
            qr_img.save("qr.png")
            q.ask(
                "Press Enter to see a QR code on your screen. Scan it into an MFA "
                "application, such as Google Authenticator."
            )
            webbrowser.open("qr.png")
            mfa_code = q.ask(
                "Enter the verification code from your MFA application: ", q.non_empty
            )
            response = cog_wrapper.verify_mfa(response["Session"], mfa_code)
            print(f"MFA device setup {response['Status']}")
            print("Now that an MFA application is set up, let's sign in again.")
            print(
                "You might have to wait a few seconds for a new MFA code to appear in "
                "your MFA application."
            )
            challenge = "ADMIN_USER_PASSWORD_AUTH"
        elif response["ChallengeName"] == "SOFTWARE_TOKEN_MFA":
            auth_tokens = None
            while auth_tokens is None:
                mfa_code = q.ask(
                    "Enter a verification code from your MFA application: ", q.non_empty
                )
                auth_tokens = cog_wrapper.respond_to_mfa_challenge(
                    user_name, response["Session"], mfa_code
                )
            print(f"You're signed in as {user_name}.")
            print("Here's your access token:")
            pp(auth_tokens["AccessToken"])
            print("And your device information:")
            pp(auth_tokens["NewDeviceMetadata"])
            challenge = None
        else:
            raise Exception(f"Got unexpected challenge {response['ChallengeName']}")
    print("-" * 88)

    device_group_key = auth_tokens["NewDeviceMetadata"]["DeviceGroupKey"]
    device_key = auth_tokens["NewDeviceMetadata"]["DeviceKey"]
    device_password = base64.standard_b64encode(os.urandom(40)).decode("utf-8")

    print("Let's confirm your MFA device so you don't have re-enter MFA tokens for it.")
    q.ask("Press Enter when you're ready.")
    cog_wrapper.confirm_mfa_device(
        user_name,
        device_key,
        device_group_key,
        device_password,
        auth_tokens["AccessToken"],
        aws_srp,
    )
    print(f"Your device {device_key} is confirmed.")
    print("-" * 88)

    print(
        f"Now let's sign in as {user_name} from your confirmed device {device_key}.\n"
        f"Because this device is tracked by Amazon Cognito, you won't have to re-enter an MFA code."
    )
    q.ask("Press Enter when ready.")
    auth_tokens = cog_wrapper.sign_in_with_tracked_device(
        user_name, password, device_key, device_group_key, device_password, aws_srp
    )
    print("You're signed in. Your access token is:")
    pp(auth_tokens["AccessToken"])
    print("-" * 88)

    print("Don't forget to delete your user pool when you're done with this example.")
    print("\nThanks for watching!")
    print("-" * 88)


def main():
    parser = argparse.ArgumentParser(
        description="Shows how to sign up a new user with Amazon Cognito and associate "
        "the user with an MFA application for multi-factor authentication."
    )
    parser.add_argument(
        "user_pool_id", help="The ID of the user pool to use for the example."
    )
    parser.add_argument(
        "client_id", help="The ID of the client application to use for the example."
    )
    args = parser.parse_args()
    try:
        run_scenario(boto3.client("cognito-idp"), args.user_pool_id, args.client_id)
    except Exception:
        logging.exception("Something went wrong with the demo.")


if __name__ == "__main__":
    main()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AdminGetUser](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AdminGetUser)
  + [AdminInitiateAuth](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AdminInitiateAuth)
  + [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AdminRespondToAuthChallenge)
  + [AssociateSoftwareToken](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/AssociateSoftwareToken)
  + [ConfirmDevice](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ConfirmDevice)
  + [ConfirmSignUp](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ConfirmSignUp)
  + [InitiateAuth](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/InitiateAuth)
  + [ListUsers](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ListUsers)
  + [ResendConfirmationCode](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/ResendConfirmationCode)
  + [RespondToAuthChallenge](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/RespondToAuthChallenge)
  + [SignUp](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/SignUp)
  + [VerifySoftwareToken](https://docs.aws.amazon.com/goto/boto3/cognito-idp-2016-04-18/VerifySoftwareToken)

### Amazon Cognito のアイデンティティプールを使用する
<a name="cross_CognitoFlows_python_3_topic"></a>

次のコード例は、アイデンティティプールの認証フローを示すウェブベースのデモアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Cognito アイデンティティプールの認証フローを示すウェブベースのデモアプリケーションを通じて、ユーザーがさまざまな ID プロバイダーで拡張認証フローと基本認証フローの両方をインタラクティブに参照できるようにします。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito/scenarios/identity_pools_example_demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID プロバイダー

# SDK for Python (Boto3) を使用する Amazon Comprehend の例
<a name="python_3_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateDocumentClassifier`
<a name="comprehend_CreateDocumentClassifier_python_3_topic"></a>

次のコード例は、`CreateDocumentClassifier` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def create(
        self,
        name,
        language_code,
        training_bucket,
        training_key,
        data_access_role_arn,
        mode,
    ):
        """
        Creates a custom classifier. After the classifier is created, it immediately
        starts training on the data found in the specified Amazon S3 bucket. Training
        can take 30 minutes or longer. The `describe_document_classifier` function
        can be used to get training status and returns a status of TRAINED when the
        classifier is ready to use.

        :param name: The name of the classifier.
        :param language_code: The language the classifier can operate on.
        :param training_bucket: The Amazon S3 bucket that contains the training data.
        :param training_key: The prefix used to find training data in the training
                             bucket. If multiple objects have the same prefix, all
                             of them are used.
        :param data_access_role_arn: The Amazon Resource Name (ARN) of a role that
                                     grants Comprehend permission to read from the
                                     training bucket.
        :return: The ARN of the newly created classifier.
        """
        try:
            response = self.comprehend_client.create_document_classifier(
                DocumentClassifierName=name,
                LanguageCode=language_code,
                InputDataConfig={"S3Uri": f"s3://{training_bucket}/{training_key}"},
                DataAccessRoleArn=data_access_role_arn,
                Mode=mode.value,
            )
            self.classifier_arn = response["DocumentClassifierArn"]
            logger.info("Started classifier creation. Arn is: %s.", self.classifier_arn)
        except ClientError:
            logger.exception("Couldn't create classifier %s.", name)
            raise
        else:
            return self.classifier_arn
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDocumentClassifier](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/CreateDocumentClassifier)」を参照してください。

### `DeleteDocumentClassifier`
<a name="comprehend_DeleteDocumentClassifier_python_3_topic"></a>

次のコード例は、`DeleteDocumentClassifier` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def delete(self):
        """
        Deletes the classifier.
        """
        try:
            self.comprehend_client.delete_document_classifier(
                DocumentClassifierArn=self.classifier_arn
            )
            logger.info("Deleted classifier %s.", self.classifier_arn)
            self.classifier_arn = None
        except ClientError:
            logger.exception("Couldn't deleted classifier %s.", self.classifier_arn)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDocumentClassifier](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DeleteDocumentClassifier)」を参照してください。

### `DescribeDocumentClassificationJob`
<a name="comprehend_DescribeDocumentClassificationJob_python_3_topic"></a>

次のコード例は、`DescribeDocumentClassificationJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def describe_job(self, job_id):
        """
        Gets metadata about a classification job.

        :param job_id: The ID of the job to look up.
        :return: Metadata about the job.
        """
        try:
            response = self.comprehend_client.describe_document_classification_job(
                JobId=job_id
            )
            job = response["DocumentClassificationJobProperties"]
            logger.info("Got classification job %s.", job["JobName"])
        except ClientError:
            logger.exception("Couldn't get classification job %s.", job_id)
            raise
        else:
            return job
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDocumentClassificationJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DescribeDocumentClassificationJob)」を参照してください。

### `DescribeDocumentClassifier`
<a name="comprehend_DescribeDocumentClassifier_python_3_topic"></a>

次のコード例は、`DescribeDocumentClassifier` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def describe(self, classifier_arn=None):
        """
        Gets metadata about a custom classifier, including its current status.

        :param classifier_arn: The ARN of the classifier to look up.
        :return: Metadata about the classifier.
        """
        if classifier_arn is not None:
            self.classifier_arn = classifier_arn
        try:
            response = self.comprehend_client.describe_document_classifier(
                DocumentClassifierArn=self.classifier_arn
            )
            classifier = response["DocumentClassifierProperties"]
            logger.info("Got classifier %s.", self.classifier_arn)
        except ClientError:
            logger.exception("Couldn't get classifier %s.", self.classifier_arn)
            raise
        else:
            return classifier
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDocumentClassifier](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DescribeDocumentClassifier)」を参照してください。

### `DescribeTopicsDetectionJob`
<a name="comprehend_DescribeTopicsDetectionJob_python_3_topic"></a>

次のコード例は、`DescribeTopicsDetectionJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendTopicModeler:
    """Encapsulates a Comprehend topic modeler."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def describe_job(self, job_id):
        """
        Gets metadata about a topic modeling job.

        :param job_id: The ID of the job to look up.
        :return: Metadata about the job.
        """
        try:
            response = self.comprehend_client.describe_topics_detection_job(
                JobId=job_id
            )
            job = response["TopicsDetectionJobProperties"]
            logger.info("Got topic detection job %s.", job_id)
        except ClientError:
            logger.exception("Couldn't get topic detection job %s.", job_id)
            raise
        else:
            return job
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeTopicsDetectionJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DescribeTopicsDetectionJob)」を参照してください。

### `DetectDominantLanguage`
<a name="comprehend_DetectDominantLanguage_python_3_topic"></a>

次のコード例は、`DetectDominantLanguage` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendDetect:
    """Encapsulates Comprehend detection functions."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def detect_languages(self, text):
        """
        Detects languages used in a document.

        :param text: The document to inspect.
        :return: The list of languages along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_dominant_language(Text=text)
            languages = response["Languages"]
            logger.info("Detected %s languages.", len(languages))
        except ClientError:
            logger.exception("Couldn't detect languages.")
            raise
        else:
            return languages
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」**の「[DetectDominantLanguage](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectDominantLanguage)」を参照してください。

### `DetectEntities`
<a name="comprehend_DetectEntities_python_3_topic"></a>

次のコード例は、`DetectEntities` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendDetect:
    """Encapsulates Comprehend detection functions."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def detect_entities(self, text, language_code):
        """
        Detects entities in a document. Entities can be things like people and places
        or other common terms.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of entities along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_entities(
                Text=text, LanguageCode=language_code
            )
            entities = response["Entities"]
            logger.info("Detected %s entities.", len(entities))
        except ClientError:
            logger.exception("Couldn't detect entities.")
            raise
        else:
            return entities
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[DetectEntities](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectEntities)」を参照してください。

### `DetectKeyPhrases`
<a name="comprehend_DetectKeyPhrases_python_3_topic"></a>

次のコード例は、`DetectKeyPhrases` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendDetect:
    """Encapsulates Comprehend detection functions."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def detect_key_phrases(self, text, language_code):
        """
        Detects key phrases in a document. A key phrase is typically a noun and its
        modifiers.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of key phrases along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_key_phrases(
                Text=text, LanguageCode=language_code
            )
            phrases = response["KeyPhrases"]
            logger.info("Detected %s phrases.", len(phrases))
        except ClientError:
            logger.exception("Couldn't detect phrases.")
            raise
        else:
            return phrases
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DetectKeyPhrases](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectKeyPhrases)」を参照してください。

### `DetectPiiEntities`
<a name="comprehend_DetectPiiEntities_python_3_topic"></a>

次のコード例は、`DetectPiiEntities` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendDetect:
    """Encapsulates Comprehend detection functions."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def detect_pii(self, text, language_code):
        """
        Detects personally identifiable information (PII) in a document. PII can be
        things like names, account numbers, or addresses.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of PII entities along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_pii_entities(
                Text=text, LanguageCode=language_code
            )
            entities = response["Entities"]
            logger.info("Detected %s PII entities.", len(entities))
        except ClientError:
            logger.exception("Couldn't detect PII entities.")
            raise
        else:
            return entities
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DetectPiiEntities](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectPiiEntities)」を参照してください。

### `DetectSentiment`
<a name="comprehend_DetectSentiment_python_3_topic"></a>

次のコード例は、`DetectSentiment` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendDetect:
    """Encapsulates Comprehend detection functions."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def detect_sentiment(self, text, language_code):
        """
        Detects the overall sentiment expressed in a document. Sentiment can
        be positive, negative, neutral, or a mixture.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The sentiments along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_sentiment(
                Text=text, LanguageCode=language_code
            )
            logger.info("Detected primary sentiment %s.", response["Sentiment"])
        except ClientError:
            logger.exception("Couldn't detect sentiment.")
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DetectSentiment](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectSentiment)」を参照してください。

### `DetectSyntax`
<a name="comprehend_DetectSyntax_python_3_topic"></a>

次のコード例は、`DetectSyntax` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendDetect:
    """Encapsulates Comprehend detection functions."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def detect_syntax(self, text, language_code):
        """
        Detects syntactical elements of a document. Syntax tokens are portions of
        text along with their use as parts of speech, such as nouns, verbs, and
        interjections.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of syntax tokens along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_syntax(
                Text=text, LanguageCode=language_code
            )
            tokens = response["SyntaxTokens"]
            logger.info("Detected %s syntax tokens.", len(tokens))
        except ClientError:
            logger.exception("Couldn't detect syntax.")
            raise
        else:
            return tokens
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectSyntax) の「*DetectSyntax*」を参照してください。

### `ListDocumentClassificationJobs`
<a name="comprehend_ListDocumentClassificationJobs_python_3_topic"></a>

次のコード例は、`ListDocumentClassificationJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def list_jobs(self):
        """
        Lists the classification jobs for the current account.

        :return: The list of jobs.
        """
        try:
            response = self.comprehend_client.list_document_classification_jobs()
            jobs = response["DocumentClassificationJobPropertiesList"]
            logger.info("Got %s document classification jobs.", len(jobs))
        except ClientError:
            logger.exception(
                "Couldn't get document classification jobs.",
            )
            raise
        else:
            return jobs
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListDocumentClassificationJobs](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/ListDocumentClassificationJobs)」を参照してください。

### `ListDocumentClassifiers`
<a name="comprehend_ListDocumentClassifiers_python_3_topic"></a>

次のコード例は、`ListDocumentClassifiers` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def list(self):
        """
        Lists custom classifiers for the current account.

        :return: The list of classifiers.
        """
        try:
            response = self.comprehend_client.list_document_classifiers()
            classifiers = response["DocumentClassifierPropertiesList"]
            logger.info("Got %s classifiers.", len(classifiers))
        except ClientError:
            logger.exception(
                "Couldn't get classifiers.",
            )
            raise
        else:
            return classifiers
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListDocumentClassifiers](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/ListDocumentClassifiers)」を参照してください。

### `ListTopicsDetectionJobs`
<a name="comprehend_ListTopicsDetectionJobs_python_3_topic"></a>

次のコード例は、`ListTopicsDetectionJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendTopicModeler:
    """Encapsulates a Comprehend topic modeler."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def list_jobs(self):
        """
        Lists topic modeling jobs for the current account.

        :return: The list of jobs.
        """
        try:
            response = self.comprehend_client.list_topics_detection_jobs()
            jobs = response["TopicsDetectionJobPropertiesList"]
            logger.info("Got %s topic detection jobs.", len(jobs))
        except ClientError:
            logger.exception("Couldn't get topic detection jobs.")
            raise
        else:
            return jobs
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListTopicsDetectionJobs](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/ListTopicsDetectionJobs)」を参照してください。

### `StartDocumentClassificationJob`
<a name="comprehend_StartDocumentClassificationJob_python_3_topic"></a>

次のコード例は、`StartDocumentClassificationJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def start_job(
        self,
        job_name,
        input_bucket,
        input_key,
        input_format,
        output_bucket,
        output_key,
        data_access_role_arn,
    ):
        """
        Starts a classification job. The classifier must be trained or the job
        will fail. Input is read from the specified Amazon S3 input bucket and
        written to the specified output bucket. Output data is stored in a tar
        archive compressed in gzip format. The job runs asynchronously, so you can
        call `describe_document_classification_job` to get job status until it
        returns a status of SUCCEEDED.

        :param job_name: The name of the job.
        :param input_bucket: The Amazon S3 bucket that contains input data.
        :param input_key: The prefix used to find input data in the input
                          bucket. If multiple objects have the same prefix, all
                          of them are used.
        :param input_format: The format of the input data, either one document per
                             file or one document per line.
        :param output_bucket: The Amazon S3 bucket where output data is written.
        :param output_key: The prefix prepended to the output data.
        :param data_access_role_arn: The Amazon Resource Name (ARN) of a role that
                                     grants Comprehend permission to read from the
                                     input bucket and write to the output bucket.
        :return: Information about the job, including the job ID.
        """
        try:
            response = self.comprehend_client.start_document_classification_job(
                DocumentClassifierArn=self.classifier_arn,
                JobName=job_name,
                InputDataConfig={
                    "S3Uri": f"s3://{input_bucket}/{input_key}",
                    "InputFormat": input_format.value,
                },
                OutputDataConfig={"S3Uri": f"s3://{output_bucket}/{output_key}"},
                DataAccessRoleArn=data_access_role_arn,
            )
            logger.info(
                "Document classification job %s is %s.", job_name, response["JobStatus"]
            )
        except ClientError:
            logger.exception("Couldn't start classification job %s.", job_name)
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartDocumentClassificationJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/StartDocumentClassificationJob)」を参照してください。

### `StartTopicsDetectionJob`
<a name="comprehend_StartTopicsDetectionJob_python_3_topic"></a>

次のコード例は、`StartTopicsDetectionJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。

```
class ComprehendTopicModeler:
    """Encapsulates a Comprehend topic modeler."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def start_job(
        self,
        job_name,
        input_bucket,
        input_key,
        input_format,
        output_bucket,
        output_key,
        data_access_role_arn,
    ):
        """
        Starts a topic modeling job. Input is read from the specified Amazon S3
        input bucket and written to the specified output bucket. Output data is stored
        in a tar archive compressed in gzip format. The job runs asynchronously, so you
        can call `describe_topics_detection_job` to get job status until it
        returns a status of SUCCEEDED.

        :param job_name: The name of the job.
        :param input_bucket: An Amazon S3 bucket that contains job input.
        :param input_key: The prefix used to find input data in the input
                             bucket. If multiple objects have the same prefix, all
                             of them are used.
        :param input_format: The format of the input data, either one document per
                             file or one document per line.
        :param output_bucket: The Amazon S3 bucket where output data is written.
        :param output_key: The prefix prepended to the output data.
        :param data_access_role_arn: The Amazon Resource Name (ARN) of a role that
                                     grants Comprehend permission to read from the
                                     input bucket and write to the output bucket.
        :return: Information about the job, including the job ID.
        """
        try:
            response = self.comprehend_client.start_topics_detection_job(
                JobName=job_name,
                DataAccessRoleArn=data_access_role_arn,
                InputDataConfig={
                    "S3Uri": f"s3://{input_bucket}/{input_key}",
                    "InputFormat": input_format.value,
                },
                OutputDataConfig={"S3Uri": f"s3://{output_bucket}/{output_key}"},
            )
            logger.info("Started topic modeling job %s.", response["JobId"])
        except ClientError:
            logger.exception("Couldn't start topic modeling job.")
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartTopicsDetectionJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/StartTopicsDetectionJob)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ドキュメント要素を検出する
<a name="comprehend_Usage_DetectApis_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ドキュメント内の言語、エンティティ、キーフレーズを検出する。
+ ドキュメントから個人を特定できる情報 (PII)を検出する。
+ ドキュメントのセンチメントを検出する。
+ ドキュメントの構文要素を検出します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。
Amazon Comprehend のアクションをラップするクラスを作成します。  

```
import logging
from pprint import pprint
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

class ComprehendDetect:
    """Encapsulates Comprehend detection functions."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def detect_languages(self, text):
        """
        Detects languages used in a document.

        :param text: The document to inspect.
        :return: The list of languages along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_dominant_language(Text=text)
            languages = response["Languages"]
            logger.info("Detected %s languages.", len(languages))
        except ClientError:
            logger.exception("Couldn't detect languages.")
            raise
        else:
            return languages


    def detect_entities(self, text, language_code):
        """
        Detects entities in a document. Entities can be things like people and places
        or other common terms.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of entities along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_entities(
                Text=text, LanguageCode=language_code
            )
            entities = response["Entities"]
            logger.info("Detected %s entities.", len(entities))
        except ClientError:
            logger.exception("Couldn't detect entities.")
            raise
        else:
            return entities


    def detect_key_phrases(self, text, language_code):
        """
        Detects key phrases in a document. A key phrase is typically a noun and its
        modifiers.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of key phrases along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_key_phrases(
                Text=text, LanguageCode=language_code
            )
            phrases = response["KeyPhrases"]
            logger.info("Detected %s phrases.", len(phrases))
        except ClientError:
            logger.exception("Couldn't detect phrases.")
            raise
        else:
            return phrases


    def detect_pii(self, text, language_code):
        """
        Detects personally identifiable information (PII) in a document. PII can be
        things like names, account numbers, or addresses.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of PII entities along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_pii_entities(
                Text=text, LanguageCode=language_code
            )
            entities = response["Entities"]
            logger.info("Detected %s PII entities.", len(entities))
        except ClientError:
            logger.exception("Couldn't detect PII entities.")
            raise
        else:
            return entities


    def detect_sentiment(self, text, language_code):
        """
        Detects the overall sentiment expressed in a document. Sentiment can
        be positive, negative, neutral, or a mixture.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The sentiments along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_sentiment(
                Text=text, LanguageCode=language_code
            )
            logger.info("Detected primary sentiment %s.", response["Sentiment"])
        except ClientError:
            logger.exception("Couldn't detect sentiment.")
            raise
        else:
            return response


    def detect_syntax(self, text, language_code):
        """
        Detects syntactical elements of a document. Syntax tokens are portions of
        text along with their use as parts of speech, such as nouns, verbs, and
        interjections.

        :param text: The document to inspect.
        :param language_code: The language of the document.
        :return: The list of syntax tokens along with their confidence scores.
        """
        try:
            response = self.comprehend_client.detect_syntax(
                Text=text, LanguageCode=language_code
            )
            tokens = response["SyntaxTokens"]
            logger.info("Detected %s syntax tokens.", len(tokens))
        except ClientError:
            logger.exception("Couldn't detect syntax.")
            raise
        else:
            return tokens
```
Wrapper クラスの関数を呼び出して、ドキュメント内のエンティティ、フレーズなどを検出します。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the Amazon Comprehend detection demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    comp_detect = ComprehendDetect(boto3.client("comprehend"))
    with open("detect_sample.txt") as sample_file:
        sample_text = sample_file.read()

    demo_size = 3

    print("Sample text used for this demo:")
    print("-" * 88)
    print(sample_text)
    print("-" * 88)

    print("Detecting languages.")
    languages = comp_detect.detect_languages(sample_text)
    pprint(languages)
    lang_code = languages[0]["LanguageCode"]

    print("Detecting entities.")
    entities = comp_detect.detect_entities(sample_text, lang_code)
    print(f"The first {demo_size} are:")
    pprint(entities[:demo_size])

    print("Detecting key phrases.")
    phrases = comp_detect.detect_key_phrases(sample_text, lang_code)
    print(f"The first {demo_size} are:")
    pprint(phrases[:demo_size])

    print("Detecting personally identifiable information (PII).")
    pii_entities = comp_detect.detect_pii(sample_text, lang_code)
    print(f"The first {demo_size} are:")
    pprint(pii_entities[:demo_size])

    print("Detecting sentiment.")
    sentiment = comp_detect.detect_sentiment(sample_text, lang_code)
    print(f"Sentiment: {sentiment['Sentiment']}")
    print("SentimentScore:")
    pprint(sentiment["SentimentScore"])

    print("Detecting syntax elements.")
    syntax_tokens = comp_detect.detect_syntax(sample_text, lang_code)
    print(f"The first {demo_size} are:")
    pprint(syntax_tokens[:demo_size])

    print("Thanks for watching!")
    print("-" * 88)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [DetectDominantLanguage](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectDominantLanguage)
  + [DetectEntities](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectEntities)
  + [DetectKeyPhrases](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectKeyPhrases)
  + [DetectPiiEntities](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectPiiEntities)
  + [DetectSentiment](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectSentiment)
  + [DetectSyntax](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DetectSyntax)

### 画像から抽出されたテキスト内のエンティティを検出する
<a name="cross_TextractComprehendDetectEntities_python_3_topic"></a>

次のコード例は、Amazon Comprehend を使用して、Amazon S3 に格納されている画像から Amazon Textract によって抽出されたテキスト内のエンティティを検出する方法を示しています。

**SDK for Python (Boto3)**  
 Jupyter ノートブック AWS SDK for Python (Boto3) で を使用して、イメージから抽出されたテキスト内のエンティティを検出する方法を示します。この例では、Amazon Textract を使用して Amazon Simple Storage Service (Amazon S3) に保存されている画像からテキストを抽出し、Amazon Comprehend を使用して、抽出されたテキスト内のエンティティを検出します。  
 この例は Jupyter Notebook であり、ノートブックをホストできる環境で実行する必要があります。Amazon SageMaker AI を使用してサンプルを実行する方法については、「[TextractAndComprehendNotebook.ipynb](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_comprehend_notebook/TextractAndComprehendNotebook.ipynb)」の手順を参照してください。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_comprehend_notebook#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon S3
+ Amazon Textract

### サンプルデータに対してトピックモデリングジョブを実行する
<a name="comprehend_Usage_TopicModeler_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Comprehend トピックモデリングジョブをサンプルデータに対して実行します。
+ ジョブに関する情報｡
+ Amazon S3 からジョブ出力データを抽出します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。
Amazon Comprehend トピックモデリングアクションを呼び出すラッパークラスを作成します。  

```
class ComprehendTopicModeler:
    """Encapsulates a Comprehend topic modeler."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client


    def start_job(
        self,
        job_name,
        input_bucket,
        input_key,
        input_format,
        output_bucket,
        output_key,
        data_access_role_arn,
    ):
        """
        Starts a topic modeling job. Input is read from the specified Amazon S3
        input bucket and written to the specified output bucket. Output data is stored
        in a tar archive compressed in gzip format. The job runs asynchronously, so you
        can call `describe_topics_detection_job` to get job status until it
        returns a status of SUCCEEDED.

        :param job_name: The name of the job.
        :param input_bucket: An Amazon S3 bucket that contains job input.
        :param input_key: The prefix used to find input data in the input
                             bucket. If multiple objects have the same prefix, all
                             of them are used.
        :param input_format: The format of the input data, either one document per
                             file or one document per line.
        :param output_bucket: The Amazon S3 bucket where output data is written.
        :param output_key: The prefix prepended to the output data.
        :param data_access_role_arn: The Amazon Resource Name (ARN) of a role that
                                     grants Comprehend permission to read from the
                                     input bucket and write to the output bucket.
        :return: Information about the job, including the job ID.
        """
        try:
            response = self.comprehend_client.start_topics_detection_job(
                JobName=job_name,
                DataAccessRoleArn=data_access_role_arn,
                InputDataConfig={
                    "S3Uri": f"s3://{input_bucket}/{input_key}",
                    "InputFormat": input_format.value,
                },
                OutputDataConfig={"S3Uri": f"s3://{output_bucket}/{output_key}"},
            )
            logger.info("Started topic modeling job %s.", response["JobId"])
        except ClientError:
            logger.exception("Couldn't start topic modeling job.")
            raise
        else:
            return response


    def describe_job(self, job_id):
        """
        Gets metadata about a topic modeling job.

        :param job_id: The ID of the job to look up.
        :return: Metadata about the job.
        """
        try:
            response = self.comprehend_client.describe_topics_detection_job(
                JobId=job_id
            )
            job = response["TopicsDetectionJobProperties"]
            logger.info("Got topic detection job %s.", job_id)
        except ClientError:
            logger.exception("Couldn't get topic detection job %s.", job_id)
            raise
        else:
            return job


    def list_jobs(self):
        """
        Lists topic modeling jobs for the current account.

        :return: The list of jobs.
        """
        try:
            response = self.comprehend_client.list_topics_detection_jobs()
            jobs = response["TopicsDetectionJobPropertiesList"]
            logger.info("Got %s topic detection jobs.", len(jobs))
        except ClientError:
            logger.exception("Couldn't get topic detection jobs.")
            raise
        else:
            return jobs
```
ラッパークラスを使用してトピックモデリングジョブを実行し、ジョブデータを取得します。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the Amazon Comprehend topic modeling demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    input_prefix = "input/"
    output_prefix = "output/"
    demo_resources = ComprehendDemoResources(
        boto3.resource("s3"), boto3.resource("iam")
    )
    topic_modeler = ComprehendTopicModeler(boto3.client("comprehend"))

    print("Setting up storage and security resources needed for the demo.")
    demo_resources.setup("comprehend-topic-modeler-demo")
    print("Copying sample data from public bucket into input bucket.")
    demo_resources.bucket.copy(
        {"Bucket": "public-sample-us-west-2", "Key": "TopicModeling/Sample.txt"},
        f"{input_prefix}sample.txt",
    )

    print("Starting topic modeling job on sample data.")
    job_info = topic_modeler.start_job(
        "demo-topic-modeling-job",
        demo_resources.bucket.name,
        input_prefix,
        JobInputFormat.per_line,
        demo_resources.bucket.name,
        output_prefix,
        demo_resources.data_access_role.arn,
    )

    print(
        f"Waiting for job {job_info['JobId']} to complete. This typically takes "
        f"20 - 30 minutes."
    )
    job_waiter = JobCompleteWaiter(topic_modeler.comprehend_client)
    job_waiter.wait(job_info["JobId"])

    job = topic_modeler.describe_job(job_info["JobId"])
    print(f"Job {job['JobId']} complete:")
    pprint(job)

    print(
        f"Getting job output data from the output Amazon S3 bucket: "
        f"{job['OutputDataConfig']['S3Uri']}."
    )
    job_output = demo_resources.extract_job_output(job)
    lines = 10
    print(f"First {lines} lines of document topics output:")
    pprint(job_output["doc-topics.csv"]["data"][:lines])
    print(f"First {lines} lines of terms output:")
    pprint(job_output["topic-terms.csv"]["data"][:lines])

    print("Cleaning up resources created for the demo.")
    demo_resources.cleanup()

    print("Thanks for watching!")
    print("-" * 88)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [DescribeTopicsDetectionJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DescribeTopicsDetectionJob)
  + [ListTopicsDetectionJobs](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/ListTopicsDetectionJobs)
  + [StartTopicsDetectionJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/StartTopicsDetectionJob)

### カスタム分類子のトレーニングとドキュメントの分類
<a name="comprehend_Usage_ComprehendClassifier_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Comprehend マルチラベル分類子を作成します。
+ 分類子をサンプルデータに基づいてトレーニングします。
+ 2 番目のデータセットで分類ジョブを実行します。
+ Amazon S3 からジョブ出力データを抽出します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/comprehend#code-examples)での設定と実行の方法を確認してください。
Amazon Comprehend ドキュメント分類子アクションを呼び出すラッパークラスを作成します。  

```
class ComprehendClassifier:
    """Encapsulates an Amazon Comprehend custom classifier."""

    def __init__(self, comprehend_client):
        """
        :param comprehend_client: A Boto3 Comprehend client.
        """
        self.comprehend_client = comprehend_client
        self.classifier_arn = None


    def create(
        self,
        name,
        language_code,
        training_bucket,
        training_key,
        data_access_role_arn,
        mode,
    ):
        """
        Creates a custom classifier. After the classifier is created, it immediately
        starts training on the data found in the specified Amazon S3 bucket. Training
        can take 30 minutes or longer. The `describe_document_classifier` function
        can be used to get training status and returns a status of TRAINED when the
        classifier is ready to use.

        :param name: The name of the classifier.
        :param language_code: The language the classifier can operate on.
        :param training_bucket: The Amazon S3 bucket that contains the training data.
        :param training_key: The prefix used to find training data in the training
                             bucket. If multiple objects have the same prefix, all
                             of them are used.
        :param data_access_role_arn: The Amazon Resource Name (ARN) of a role that
                                     grants Comprehend permission to read from the
                                     training bucket.
        :return: The ARN of the newly created classifier.
        """
        try:
            response = self.comprehend_client.create_document_classifier(
                DocumentClassifierName=name,
                LanguageCode=language_code,
                InputDataConfig={"S3Uri": f"s3://{training_bucket}/{training_key}"},
                DataAccessRoleArn=data_access_role_arn,
                Mode=mode.value,
            )
            self.classifier_arn = response["DocumentClassifierArn"]
            logger.info("Started classifier creation. Arn is: %s.", self.classifier_arn)
        except ClientError:
            logger.exception("Couldn't create classifier %s.", name)
            raise
        else:
            return self.classifier_arn


    def describe(self, classifier_arn=None):
        """
        Gets metadata about a custom classifier, including its current status.

        :param classifier_arn: The ARN of the classifier to look up.
        :return: Metadata about the classifier.
        """
        if classifier_arn is not None:
            self.classifier_arn = classifier_arn
        try:
            response = self.comprehend_client.describe_document_classifier(
                DocumentClassifierArn=self.classifier_arn
            )
            classifier = response["DocumentClassifierProperties"]
            logger.info("Got classifier %s.", self.classifier_arn)
        except ClientError:
            logger.exception("Couldn't get classifier %s.", self.classifier_arn)
            raise
        else:
            return classifier


    def list(self):
        """
        Lists custom classifiers for the current account.

        :return: The list of classifiers.
        """
        try:
            response = self.comprehend_client.list_document_classifiers()
            classifiers = response["DocumentClassifierPropertiesList"]
            logger.info("Got %s classifiers.", len(classifiers))
        except ClientError:
            logger.exception(
                "Couldn't get classifiers.",
            )
            raise
        else:
            return classifiers


    def delete(self):
        """
        Deletes the classifier.
        """
        try:
            self.comprehend_client.delete_document_classifier(
                DocumentClassifierArn=self.classifier_arn
            )
            logger.info("Deleted classifier %s.", self.classifier_arn)
            self.classifier_arn = None
        except ClientError:
            logger.exception("Couldn't deleted classifier %s.", self.classifier_arn)
            raise


    def start_job(
        self,
        job_name,
        input_bucket,
        input_key,
        input_format,
        output_bucket,
        output_key,
        data_access_role_arn,
    ):
        """
        Starts a classification job. The classifier must be trained or the job
        will fail. Input is read from the specified Amazon S3 input bucket and
        written to the specified output bucket. Output data is stored in a tar
        archive compressed in gzip format. The job runs asynchronously, so you can
        call `describe_document_classification_job` to get job status until it
        returns a status of SUCCEEDED.

        :param job_name: The name of the job.
        :param input_bucket: The Amazon S3 bucket that contains input data.
        :param input_key: The prefix used to find input data in the input
                          bucket. If multiple objects have the same prefix, all
                          of them are used.
        :param input_format: The format of the input data, either one document per
                             file or one document per line.
        :param output_bucket: The Amazon S3 bucket where output data is written.
        :param output_key: The prefix prepended to the output data.
        :param data_access_role_arn: The Amazon Resource Name (ARN) of a role that
                                     grants Comprehend permission to read from the
                                     input bucket and write to the output bucket.
        :return: Information about the job, including the job ID.
        """
        try:
            response = self.comprehend_client.start_document_classification_job(
                DocumentClassifierArn=self.classifier_arn,
                JobName=job_name,
                InputDataConfig={
                    "S3Uri": f"s3://{input_bucket}/{input_key}",
                    "InputFormat": input_format.value,
                },
                OutputDataConfig={"S3Uri": f"s3://{output_bucket}/{output_key}"},
                DataAccessRoleArn=data_access_role_arn,
            )
            logger.info(
                "Document classification job %s is %s.", job_name, response["JobStatus"]
            )
        except ClientError:
            logger.exception("Couldn't start classification job %s.", job_name)
            raise
        else:
            return response


    def describe_job(self, job_id):
        """
        Gets metadata about a classification job.

        :param job_id: The ID of the job to look up.
        :return: Metadata about the job.
        """
        try:
            response = self.comprehend_client.describe_document_classification_job(
                JobId=job_id
            )
            job = response["DocumentClassificationJobProperties"]
            logger.info("Got classification job %s.", job["JobName"])
        except ClientError:
            logger.exception("Couldn't get classification job %s.", job_id)
            raise
        else:
            return job


    def list_jobs(self):
        """
        Lists the classification jobs for the current account.

        :return: The list of jobs.
        """
        try:
            response = self.comprehend_client.list_document_classification_jobs()
            jobs = response["DocumentClassificationJobPropertiesList"]
            logger.info("Got %s document classification jobs.", len(jobs))
        except ClientError:
            logger.exception(
                "Couldn't get document classification jobs.",
            )
            raise
        else:
            return jobs
```
シナリオを実行するクラスを作成します。  

```
class ClassifierDemo:
    """
    Encapsulates functions used to run the demonstration.
    """

    def __init__(self, demo_resources):
        """
        :param demo_resources: A ComprehendDemoResources class that manages resources
                               for the demonstration.
        """
        self.demo_resources = demo_resources
        self.training_prefix = "training/"
        self.input_prefix = "input/"
        self.input_format = JobInputFormat.per_line
        self.output_prefix = "output/"

    def setup(self):
        """Creates AWS resources used by the demo."""
        self.demo_resources.setup("comprehend-classifier-demo")

    def cleanup(self):
        """Deletes AWS resources used by the demo."""
        self.demo_resources.cleanup()

    @staticmethod
    def _sanitize_text(text):
        """Removes characters that cause errors for the document parser."""
        return text.replace("\r", " ").replace("\n", " ").replace(",", ";")

    @staticmethod
    def _get_issues(query, issue_count):
        """
        Gets issues from GitHub using the specified query parameters.

        :param query: The query string used to request issues from the GitHub API.
        :param issue_count: The number of issues to retrieve.
        :return: The list of issues retrieved from GitHub.
        """
        issues = []
        logger.info("Requesting issues from %s?%s.", GITHUB_SEARCH_URL, query)
        response = requests.get(f"{GITHUB_SEARCH_URL}?{query}&per_page={issue_count}")
        if response.status_code == 200:
            issue_page = response.json()["items"]
            logger.info("Got %s issues.", len(issue_page))
            issues = [
                {
                    "title": ClassifierDemo._sanitize_text(issue["title"]),
                    "body": ClassifierDemo._sanitize_text(issue["body"]),
                    "labels": {label["name"] for label in issue["labels"]},
                }
                for issue in issue_page
            ]
        else:
            logger.error(
                "GitHub returned error code %s with message %s.",
                response.status_code,
                response.json(),
            )
        logger.info("Found %s issues.", len(issues))
        return issues

    def get_training_issues(self, training_labels):
        """
        Gets issues used for training the custom classifier. Training issues are
        closed issues from the Boto3 repo that have known labels. Comprehend
        requires a minimum of ten training issues per label.

        :param training_labels: The issue labels to use for training.
        :return: The set of issues used for training.
        """
        issues = []
        per_label_count = 15
        for label in training_labels:
            issues += self._get_issues(
                f"q=type:issue+repo:boto/boto3+state:closed+label:{label}",
                per_label_count,
            )
            for issue in issues:
                issue["labels"] = issue["labels"].intersection(training_labels)
        return issues

    def get_input_issues(self, training_labels):
        """
        Gets input issues from GitHub. For demonstration purposes, input issues
        are open issues from the Boto3 repo with known labels, though in practice
        any issue could be submitted to the classifier for labeling.

        :param training_labels: The set of labels to query for.
        :return: The set of issues used for input.
        """
        issues = []
        per_label_count = 5
        for label in training_labels:
            issues += self._get_issues(
                f"q=type:issue+repo:boto/boto3+state:open+label:{label}",
                per_label_count,
            )
        return issues

    def upload_issue_data(self, issues, training=False):
        """
        Uploads issue data to an Amazon S3 bucket, either for training or for input.
        The data is first put into the format expected by Comprehend. For training,
        the set of pipe-delimited labels is prepended to each document. For
        input, labels are not sent.

        :param issues: The set of issues to upload to Amazon S3.
        :param training: Indicates whether the issue data is used for training or
                         input.
        """
        try:
            obj_key = (
                self.training_prefix if training else self.input_prefix
            ) + "issues.txt"
            if training:
                issue_strings = [
                    f"{'|'.join(issue['labels'])},{issue['title']} {issue['body']}"
                    for issue in issues
                ]
            else:
                issue_strings = [
                    f"{issue['title']} {issue['body']}" for issue in issues
                ]
            issue_bytes = BytesIO("\n".join(issue_strings).encode("utf-8"))
            self.demo_resources.bucket.upload_fileobj(issue_bytes, obj_key)
            logger.info(
                "Uploaded data as %s to bucket %s.",
                obj_key,
                self.demo_resources.bucket.name,
            )
        except ClientError:
            logger.exception(
                "Couldn't upload data to bucket %s.", self.demo_resources.bucket.name
            )
            raise

    def extract_job_output(self, job):
        """Extracts job output from Amazon S3."""
        return self.demo_resources.extract_job_output(job)

    @staticmethod
    def reconcile_job_output(input_issues, output_dict):
        """
        Reconciles job output with the list of input issues. Because the input issues
        have known labels, these can be compared with the labels added by the
        classifier to judge the accuracy of the output.

        :param input_issues: The list of issues used as input.
        :param output_dict: The dictionary of data that is output by the classifier.
        :return: The list of reconciled input and output data.
        """
        reconciled = []
        for archive in output_dict.values():
            for line in archive["data"]:
                in_line = int(line["Line"])
                in_labels = input_issues[in_line]["labels"]
                out_labels = {
                    label["Name"]
                    for label in line["Labels"]
                    if float(label["Score"]) > 0.3
                }
                reconciled.append(
                    f"{line['File']}, line {in_line} has labels {in_labels}.\n"
                    f"\tClassifier assigned {out_labels}."
                )
        logger.info("Reconciled input and output labels.")
        return reconciled
```
ラベルがわかっている一連の GitHub 課題について分類子をトレーニングし、次に 2 つ目の GitHub 課題セットを分類子に送信してラベル付けできるようにします。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the Amazon Comprehend custom document classifier demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    comp_demo = ClassifierDemo(
        ComprehendDemoResources(boto3.resource("s3"), boto3.resource("iam"))
    )
    comp_classifier = ComprehendClassifier(boto3.client("comprehend"))
    classifier_trained_waiter = ClassifierTrainedWaiter(
        comp_classifier.comprehend_client
    )
    training_labels = {"bug", "feature-request", "dynamodb", "s3"}

    print("Setting up storage and security resources needed for the demo.")
    comp_demo.setup()

    print("Getting training data from GitHub and uploading it to Amazon S3.")
    training_issues = comp_demo.get_training_issues(training_labels)
    comp_demo.upload_issue_data(training_issues, True)

    classifier_name = "doc-example-classifier"
    print(f"Creating document classifier {classifier_name}.")
    comp_classifier.create(
        classifier_name,
        "en",
        comp_demo.demo_resources.bucket.name,
        comp_demo.training_prefix,
        comp_demo.demo_resources.data_access_role.arn,
        ClassifierMode.multi_label,
    )
    print(
        f"Waiting until {classifier_name} is trained. This typically takes "
        f"30–40 minutes."
    )
    classifier_trained_waiter.wait(comp_classifier.classifier_arn)

    print(f"Classifier {classifier_name} is trained:")
    pprint(comp_classifier.describe())

    print("Getting input data from GitHub and uploading it to Amazon S3.")
    input_issues = comp_demo.get_input_issues(training_labels)
    comp_demo.upload_issue_data(input_issues)

    print("Starting classification job on input data.")
    job_info = comp_classifier.start_job(
        "issue_classification_job",
        comp_demo.demo_resources.bucket.name,
        comp_demo.input_prefix,
        comp_demo.input_format,
        comp_demo.demo_resources.bucket.name,
        comp_demo.output_prefix,
        comp_demo.demo_resources.data_access_role.arn,
    )
    print(f"Waiting for job {job_info['JobId']} to complete.")
    job_waiter = JobCompleteWaiter(comp_classifier.comprehend_client)
    job_waiter.wait(job_info["JobId"])

    job = comp_classifier.describe_job(job_info["JobId"])
    print(f"Job {job['JobId']} complete:")
    pprint(job)

    print(
        f"Getting job output data from Amazon S3: "
        f"{job['OutputDataConfig']['S3Uri']}."
    )
    job_output = comp_demo.extract_job_output(job)
    print("Job output:")
    pprint(job_output)

    print("Reconciling job output with labels from GitHub:")
    reconciled_output = comp_demo.reconcile_job_output(input_issues, job_output)
    print(*reconciled_output, sep="\n")

    answer = input(f"Do you want to delete the classifier {classifier_name} (y/n)? ")
    if answer.lower() == "y":
        print(f"Deleting {classifier_name}.")
        comp_classifier.delete()

    print("Cleaning up resources created for the demo.")
    comp_demo.cleanup()

    print("Thanks for watching!")
    print("-" * 88)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateDocumentClassifier](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/CreateDocumentClassifier)
  + [DeleteDocumentClassifier](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DeleteDocumentClassifier)
  + [DescribeDocumentClassificationJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DescribeDocumentClassificationJob)
  + [DescribeDocumentClassifier](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/DescribeDocumentClassifier)
  + [ListDocumentClassificationJobs](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/ListDocumentClassificationJobs)
  + [ListDocumentClassifiers](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/ListDocumentClassifiers)
  + [StartDocumentClassificationJob](https://docs.aws.amazon.com/goto/boto3/comprehend-2017-11-27/StartDocumentClassificationJob)

# AWS Config SDK for Python (Boto3) を使用した例
<a name="python_3_config-service_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Config。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteConfigRule`
<a name="config-service_DeleteConfigRule_python_3_topic"></a>

次のコード例は、`DeleteConfigRule` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/config#code-examples)での設定と実行の方法を確認してください。

```
class ConfigWrapper:
    """
    Encapsulates AWS Config functions.
    """

    def __init__(self, config_client):
        """
        :param config_client: A Boto3 AWS Config client.
        """
        self.config_client = config_client


    def delete_config_rule(self, rule_name):
        """
        Delete the specified rule.

        :param rule_name: The name of the rule to delete.
        """
        try:
            self.config_client.delete_config_rule(ConfigRuleName=rule_name)
            logger.info("Deleted rule %s.", rule_name)
        except ClientError:
            logger.exception("Couldn't delete rule %s.", rule_name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteConfigRule](https://docs.aws.amazon.com/goto/boto3/config-2014-11-12/DeleteConfigRule)」を参照してください。

### `DescribeConfigRules`
<a name="config-service_DescribeConfigRules_python_3_topic"></a>

次のコード例は、`DescribeConfigRules` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/config#code-examples)での設定と実行の方法を確認してください。

```
class ConfigWrapper:
    """
    Encapsulates AWS Config functions.
    """

    def __init__(self, config_client):
        """
        :param config_client: A Boto3 AWS Config client.
        """
        self.config_client = config_client


    def describe_config_rule(self, rule_name):
        """
        Gets data for the specified rule.

        :param rule_name: The name of the rule to retrieve.
        :return: The rule data.
        """
        try:
            response = self.config_client.describe_config_rules(
                ConfigRuleNames=[rule_name]
            )
            rule = response["ConfigRules"]
            logger.info("Got data for rule %s.", rule_name)
        except ClientError:
            logger.exception("Couldn't get data for rule %s.", rule_name)
            raise
        else:
            return rule
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API Reference*」の「[DescribeConfigRules](https://docs.aws.amazon.com/goto/boto3/config-2014-11-12/DescribeConfigRules)」を参照してください。

### `PutConfigRule`
<a name="config-service_PutConfigRule_python_3_topic"></a>

次のコード例は、`PutConfigRule` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/config#code-examples)での設定と実行の方法を確認してください。

```
class ConfigWrapper:
    """
    Encapsulates AWS Config functions.
    """

    def __init__(self, config_client):
        """
        :param config_client: A Boto3 AWS Config client.
        """
        self.config_client = config_client


    def put_config_rule(self, rule_name):
        """
        Sets a configuration rule that prohibits making Amazon S3 buckets publicly
        readable.

        :param rule_name: The name to give the rule.
        """
        try:
            self.config_client.put_config_rule(
                ConfigRule={
                    "ConfigRuleName": rule_name,
                    "Description": "S3 Public Read Prohibited Bucket Rule",
                    "Scope": {
                        "ComplianceResourceTypes": [
                            "AWS::S3::Bucket",
                        ],
                    },
                    "Source": {
                        "Owner": "AWS",
                        "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED",
                    },
                    "InputParameters": "{}",
                    "ConfigRuleState": "ACTIVE",
                }
            )
            logger.info("Created configuration rule %s.", rule_name)
        except ClientError:
            logger.exception("Couldn't create configuration rule %s.", rule_name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutConfigRule](https://docs.aws.amazon.com/goto/boto3/config-2014-11-12/PutConfigRule)」を参照してください。

# AWS Control Tower SDK for Python (Boto3) を使用した例
<a name="python_3_controltower_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Control Tower。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Control Towerは
<a name="controltower_Hello_python_3_topic"></a>

次のコード例は、 AWS Control Towerの使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
import boto3
from typing import Any, List


def hello_controltower(controltower_client: Any) -> None:
    """
    Use the AWS SDK for Python (Boto3) to create an AWS Control Tower client
    and list all available baselines.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param controltower_client: A Boto3 AWS Control Tower Client object. This object wraps
                               the low-level AWS Control Tower service API.
    """
    print("Hello, AWS Control Tower! Let's list available baselines:\n")
    paginator = controltower_client.get_paginator("list_baselines")
    page_iterator = paginator.paginate()

    baseline_names: List[str] = []
    try:
        for page in page_iterator:
            for baseline in page["baselines"]:
                baseline_names.append(baseline["name"])

        print(f"{len(baseline_names)} baseline(s) retrieved.")
        for baseline_name in baseline_names:
            print(f"\t{baseline_name}")

    except controltower_client.exceptions.AccessDeniedException:
        print("Access denied. Please ensure you have the necessary permissions.")
    except Exception as e:
        print(f"An error occurred: {str(e)}")


if __name__ == "__main__":
    hello_controltower(boto3.client("controltower"))
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListBaselines](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListBaselines)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="controltower_Scenario_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ランディングゾーンを一覧表示します。
+ ベースラインを一覧表示、有効化、取得、リセット、無効化する。
+ コントロールを一覧表示、有効化、取得、無効化します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。
 AWS Control Tower 機能を示すインタラクティブなシナリオを実行します。  

```
class ControlTowerScenario:
    IDENTITY_CENTER_BASELINE = "baseline/LN25R72TTG6IGPTQ"
    stack_name = ""

    def __init__(
        self, controltower_wrapper: ControlTowerWrapper, org_client: boto3.client
    ):
        """
        :param controltower_wrapper: An instance of the ControlTowerWrapper class.
        :param org_client: A Boto3 Organization client.
        """
        self.controltower_wrapper = controltower_wrapper
        self.org_client = org_client
        self.stack = None
        self.ou_id = None
        self.ou_arn = None
        self.account_id = None
        self.landing_zone_id = None
        self.use_landing_zone = False

    def run_scenario(self) -> None:
        print("-" * 88)
        print(
            "\tWelcome to the AWS Control Tower with ControlCatalog example scenario."
        )
        print("-" * 88)

        print(
            "This demo will walk you through working with AWS Control Tower for landing zones,\n"
            "managing baselines, and working with controls."
        )

        self.account_id = boto3.client("sts").get_caller_identity()["Account"]

        print(
            "Some demo operations require the use of a landing zone. "
            "\nYou can use an existing landing zone or opt out of these operations in the demo."
            "\nFor instructions on how to set up a landing zone, "
            "\nsee https://docs.aws.amazon.com/controltower/latest/userguide/getting-started-from-console.html"
        )
        # List available landing zones
        landing_zones = self.controltower_wrapper.list_landing_zones()
        if landing_zones:
            print("\nAvailable Landing Zones:")
            for i, lz in enumerate(landing_zones, 1):
                print(f"{i} {lz['arn']})")

            # Ask if user wants to use the first landing zone in the list
            if q.ask(
                f"Do you want to use the first landing zone in the list ({landing_zones[0]['arn']})? (y/n) ",
                q.is_yesno,
            ):
                self.use_landing_zone = True
                self.landing_zone_id = landing_zones[0]["arn"]
                print(f"Using landing zone ID: {self.landing_zone_id})")
                # Set up organization and get Sandbox OU ID.
                sandbox_ou_id = self.setup_organization()
                # Store the OU ID for use in the CloudFormation template.
                self.ou_id = sandbox_ou_id
            elif q.ask(
                f"Do you want to use a different existing Landing Zone for this demo? (y/n) ",
                q.is_yesno,
            ):
                self.use_landing_zone = True
                self.landing_zone_id = q.ask("Enter landing zone id: ", q.non_empty)
                # Set up organization and get Sandbox OU ID.
                sandbox_ou_id = self.setup_organization()
                # Store the OU ID for use in the CloudFormation template.
                self.ou_id = sandbox_ou_id

        # List and Enable Baseline.
        print("\nManaging Baselines:")
        control_tower_baseline = None
        identity_center_baseline = None
        baselines = self.controltower_wrapper.list_baselines()
        print("\nListing available Baselines:")
        for baseline in baselines:
            if baseline["name"] == "AWSControlTowerBaseline":
                control_tower_baseline = baseline
            print(f"{baseline['name']}")

        if self.use_landing_zone:
            print("\nListing enabled baselines:")
            enabled_baselines = self.controltower_wrapper.list_enabled_baselines()
            for baseline in enabled_baselines:
                # If the Identity Center baseline is enabled, the identifier must be used for other baselines.
                if self.IDENTITY_CENTER_BASELINE in baseline["baselineIdentifier"]:
                    identity_center_baseline = baseline
                print(f"{baseline['baselineIdentifier']}")

            if q.ask(
                f"Do you want to enable the Control Tower Baseline? (y/n) ",
                q.is_yesno,
            ):
                print("\nEnabling Control Tower Baseline.")
                ic_baseline_arn = (
                    identity_center_baseline["arn"]
                    if identity_center_baseline
                    else None
                )
                baseline_arn = self.controltower_wrapper.enable_baseline(
                    self.ou_arn, ic_baseline_arn, control_tower_baseline["arn"], "5.0"
                )
                if baseline_arn:
                    print(f"Enabled baseline ARN: {baseline_arn}")
                else:
                    # Find the enabled baseline so we can reset it.
                    for enabled_baseline in enabled_baselines:
                        if (
                            enabled_baseline["baselineIdentifier"]
                            == control_tower_baseline["arn"]
                        ):
                            baseline_arn = enabled_baseline["arn"]
                    if baseline_arn:
                        print("No change, the selected baseline was already enabled.")

                if baseline_arn and q.ask(
                    f"Do you want to reset the Control Tower Baseline? (y/n) ",
                    q.is_yesno,
                ):
                    print(f"\nResetting Control Tower Baseline. {baseline_arn}")
                    operation_id = self.controltower_wrapper.reset_enabled_baseline(
                        baseline_arn
                    )
                    print(f"\nReset baseline operation id {operation_id}.")

                if baseline_arn and q.ask(
                    f"Do you want to disable the Control Tower Baseline? (y/n) ",
                    q.is_yesno,
                ):
                    print(f"Disabling baseline ARN: {baseline_arn}")
                    operation_id = self.controltower_wrapper.disable_baseline(
                        baseline_arn
                    )
                    print(f"\nDisabled baseline operation id {operation_id}.")

                    # Re-enable the baseline for the next step.
                    print("\nEnabling Control Tower Baseline.")
                    self.controltower_wrapper.enable_baseline(
                        self.ou_arn,
                        ic_baseline_arn,
                        control_tower_baseline["arn"],
                        "5.0",
                    )

        # List and Enable Controls.
        print("\nManaging Controls:")
        controls = self.controltower_wrapper.list_controls()
        print("\nListing first 5 available Controls:")
        for i, control in enumerate(controls[:5], 1):
            print(f"{i}. {control['Name']} - {control['Arn']}")

        if self.use_landing_zone:
            target_ou = self.ou_arn
            enabled_controls = self.controltower_wrapper.list_enabled_controls(
                target_ou
            )
            print("\nListing enabled controls:")
            for i, control in enumerate(enabled_controls, 1):
                print(f"{i}. {control['controlIdentifier']}")

            # Enable first non-enabled control as an example.
            enabled_control_arns = [control["arn"] for control in enabled_controls]
            control_arn = next(
                control["Arn"]
                for control in controls
                if control["Arn"] not in enabled_control_arns
            )

            if control_arn and q.ask(
                f"Do you want to enable the control {control_arn}? (y/n) ",
                q.is_yesno,
            ):
                print(f"\nEnabling control: {control_arn}")
                operation_id = self.controltower_wrapper.enable_control(
                    control_arn, target_ou
                )

                if operation_id:
                    print(f"Enabled control with operation id {operation_id}")

            if control_arn and q.ask(
                f"Do you want to disable the control? (y/n) ",
                q.is_yesno,
            ):
                print("\nDisabling the control...")
                operation_id = self.controltower_wrapper.disable_control(
                    control_arn, target_ou
                )
                print(f"Disable operation ID: {operation_id}")

        print("\nThis concludes the example scenario.")

        print("Thanks for watching!")
        print("-" * 88)

    def setup_organization(self):
        """
        Checks if the current account is part of an organization and creates one if needed.
        Also ensures a Sandbox OU exists and returns its ID.

        :return: The ID of the Sandbox OU
        """
        print("\nChecking organization status...")

        try:
            # Check if account is part of an organization
            org_response = self.org_client.describe_organization()
            org_id = org_response["Organization"]["Id"]
            print(f"Account is part of organization: {org_id}")

        except ClientError as error:
            if error.response["Error"]["Code"] == "AWSOrganizationsNotInUseException":
                print("No organization found. Creating a new organization...")
                try:
                    create_response = self.org_client.create_organization(
                        FeatureSet="ALL"
                    )
                    org_id = create_response["Organization"]["Id"]
                    print(f"Created new organization: {org_id}")

                    # Wait for organization to be available.
                    waiter = self.org_client.get_waiter("organization_active")
                    waiter.wait(
                        Organization=org_id,
                        WaiterConfig={"Delay": 5, "MaxAttempts": 12},
                    )

                except ClientError as create_error:
                    logger.error(
                        "Couldn't create organization. Here's why: %s: %s",
                        create_error.response["Error"]["Code"],
                        create_error.response["Error"]["Message"],
                    )
                    raise
            else:
                logger.error(
                    "Couldn't describe organization. Here's why: %s: %s",
                    error.response["Error"]["Code"],
                    error.response["Error"]["Message"],
                )
                raise

        # Look for Sandbox OU.
        sandbox_ou_id = None
        paginator = self.org_client.get_paginator(
            "list_organizational_units_for_parent"
        )

        try:
            # Get root ID first.
            roots = self.org_client.list_roots()["Roots"]
            if not roots:
                raise ValueError("No root found in organization")
            root_id = roots[0]["Id"]

            # Search for existing Sandbox OU.
            print("Checking for Sandbox OU...")
            for page in paginator.paginate(ParentId=root_id):
                for ou in page["OrganizationalUnits"]:
                    if ou["Name"] == "Sandbox":
                        sandbox_ou_id = ou["Id"]
                        self.ou_arn = ou["Arn"]
                        print(f"Found existing Sandbox OU: {sandbox_ou_id}")
                        break
                if sandbox_ou_id:
                    break

            # Create Sandbox OU if it doesn't exist.
            if not sandbox_ou_id:
                print("Creating Sandbox OU...")
                create_ou_response = self.org_client.create_organizational_unit(
                    ParentId=root_id, Name="Sandbox"
                )
                sandbox_ou_id = create_ou_response["OrganizationalUnit"]["Id"]
                print(f"Created new Sandbox OU: {sandbox_ou_id}")

                # Wait for OU to be available.
                waiter = self.org_client.get_waiter("organizational_unit_active")
                waiter.wait(
                    OrganizationalUnitId=sandbox_ou_id,
                    WaiterConfig={"Delay": 5, "MaxAttempts": 12},
                )

        except ClientError as error:
            logger.error(
                "Couldn't set up Sandbox OU. Here's why: %s: %s",
                error.response["Error"]["Code"],
                error.response["Error"]["Message"],
            )
            raise

        return sandbox_ou_id


if __name__ == "__main__":
    try:
        org = boto3.client("organizations")
        control_tower_wrapper = ControlTowerWrapper.from_client()

        scenario = ControlTowerScenario(control_tower_wrapper, org)
        scenario.run_scenario()
    except Exception:
        logging.exception("Something went wrong with the scenario.")



class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def list_baselines(self):
        """
        Lists all baselines.

        :return: List of baselines.
        :raises ClientError: If the listing operation fails.
        """
        try:
            paginator = self.controltower_client.get_paginator("list_baselines")
            baselines = []
            for page in paginator.paginate():
                baselines.extend(page["baselines"])
            return baselines

        except ClientError as err:
            if err.response["Error"]["Code"] == "AccessDeniedException":
                logger.error(
                    "Access denied. Please ensure you have the necessary permissions."
                )
            else:
                logger.error(
                    "Couldn't list baselines. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def enable_baseline(
        self,
        target_identifier: str,
        identity_center_baseline: str,
        baseline_identifier: str,
        baseline_version: str,
    ):
        """
        Enables a baseline for the specified target if it's not already enabled.

        :param target_identifier: The ARN of the target.
        :param baseline_identifier: The identifier of baseline to enable.
        :param identity_center_baseline: The identifier of identity center baseline if it is enabled.
        :param baseline_version: The version of baseline to enable.
        :return: The enabled baseline ARN or None if already enabled.
        :raises ClientError: If enabling the baseline fails for reasons other than it being already enabled.
        """
        try:
            # Only include parameters if identity_center_baseline is not empty
            parameters = []
            if identity_center_baseline:
                parameters = [
                    {
                        "key": "IdentityCenterEnabledBaselineArn",
                        "value": identity_center_baseline,
                    }
                ]
            
            response = self.controltower_client.enable_baseline(
                baselineIdentifier=baseline_identifier,
                baselineVersion=baseline_version,
                targetIdentifier=target_identifier,
                parameters=parameters,
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_baseline_operation(operation_id)
                print(f"Baseline operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return response["arn"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ValidationException":
                if "already enabled" in err.response["Error"]["Message"]:
                    print("Baseline is already enabled for this target")
                else:
                    print(
                        "Unable to enable baseline due to validation exception: %s: %s",
                        err.response["Error"]["Code"],
                        err.response["Error"]["Message"],
                    )
            logger.error(
                "Couldn't enable baseline. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            return None


    def list_controls(self):
        """
        Lists all controls in the Control Tower control catalog.

        :return: List of controls.
        :raises ClientError: If the listing operation fails.
        """
        try:
            paginator = self.controlcatalog_client.get_paginator("list_controls")
            controls = []
            for page in paginator.paginate():
                controls.extend(page["Controls"])
            return controls

        except ClientError as err:
            if err.response["Error"]["Code"] == "AccessDeniedException":
                logger.error(
                    "Access denied. Please ensure you have the necessary permissions."
                )
            else:
                logger.error(
                    "Couldn't list controls. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def enable_control(self, control_arn: str, target_identifier: str):
        """
        Enables a control for a specified target.

        :param control_arn: The ARN of the control to enable.
        :param target_identifier: The identifier of the target (e.g., OU ARN).
        :return: The operation ID.
        :raises ClientError: If enabling the control fails.
        """
        try:
            print(control_arn)
            print(target_identifier)
            response = self.controltower_client.enable_control(
                controlIdentifier=control_arn, targetIdentifier=target_identifier
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_control_operation(operation_id)
                print(f"Control operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return operation_id

        except ClientError as err:
            if (
                err.response["Error"]["Code"] == "ValidationException"
                and "already enabled" in err.response["Error"]["Message"]
            ):
                logger.info("Control is already enabled for this target")
                return None
            elif (
                err.response["Error"]["Code"] == "ResourceNotFoundException"
                and "not registered with AWS Control Tower"
                in err.response["Error"]["Message"]
            ):
                logger.error("Control Tower must be enabled to work with controls.")
                return None
            logger.error(
                "Couldn't enable control. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def get_control_operation(self, operation_id: str):
        """
        Gets the status of a control operation.

        :param operation_id: The ID of the control operation.
        :return: The operation status.
        :raises ClientError: If getting the operation status fails.
        """
        try:
            response = self.controltower_client.get_control_operation(
                operationIdentifier=operation_id
            )
            return response["controlOperation"]["status"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Operation not found.")
            else:
                logger.error(
                    "Couldn't get control operation status. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def get_baseline_operation(self, operation_id: str):
        """
        Gets the status of a baseline operation.

        :param operation_id: The ID of the baseline operation.
        :return: The operation status.
        :raises ClientError: If getting the operation status fails.
        """
        try:
            response = self.controltower_client.get_baseline_operation(
                operationIdentifier=operation_id
            )
            return response["baselineOperation"]["status"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Operation not found.")
            else:
                logger.error(
                    "Couldn't get baseline operation status. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def disable_control(self, control_arn: str, target_identifier: str):
        """
        Disables a control for a specified target.

        :param control_arn: The ARN of the control to disable.
        :param target_identifier: The identifier of the target (e.g., OU ARN).
        :return: The operation ID.
        :raises ClientError: If disabling the control fails.
        """
        try:
            response = self.controltower_client.disable_control(
                controlIdentifier=control_arn, targetIdentifier=target_identifier
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_control_operation(operation_id)
                print(f"Control operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return operation_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Control not found.")
            else:
                logger.error(
                    "Couldn't disable control. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def list_landing_zones(self):
        """
        Lists all landing zones.

        :return: List of landing zones.
        :raises ClientError: If the listing operation fails.
        """
        try:
            paginator = self.controltower_client.get_paginator("list_landing_zones")
            landing_zones = []
            for page in paginator.paginate():
                landing_zones.extend(page["landingZones"])
            return landing_zones

        except ClientError as err:
            if err.response["Error"]["Code"] == "AccessDeniedException":
                logger.error(
                    "Access denied. Please ensure you have the necessary permissions."
                )
            else:
                logger.error(
                    "Couldn't list landing zones. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def list_enabled_baselines(self):
        """
        Lists all enabled baselines.

        :return: List of enabled baselines.
        :raises ClientError: If the listing operation fails.
        """
        try:
            paginator = self.controltower_client.get_paginator("list_enabled_baselines")
            enabled_baselines = []
            for page in paginator.paginate():
                enabled_baselines.extend(page["enabledBaselines"])
            return enabled_baselines

        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Target not found.")
            else:
                logger.error(
                    "Couldn't list enabled baselines. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def reset_enabled_baseline(self, enabled_baseline_identifier: str):
        """
        Resets an enabled baseline for a specific target.

        :param enabled_baseline_identifier: The identifier of the enabled baseline to reset.
        :return: The operation ID.
        :raises ClientError: If resetting the baseline fails.
        """
        try:
            response = self.controltower_client.reset_enabled_baseline(
                enabledBaselineIdentifier=enabled_baseline_identifier
            )
            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_baseline_operation(operation_id)
                print(f"Baseline operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)
            return operation_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Target not found.")
            else:
                logger.error(
                    "Couldn't reset enabled baseline. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def disable_baseline(self, enabled_baseline_identifier: str):
        """
        Disables a baseline for a specific target and waits for the operation to complete.

        :param enabled_baseline_identifier: The identifier of the baseline to disable.
        :return: The operation ID.
        :raises ClientError: If disabling the baseline fails.
        """
        try:
            response = self.controltower_client.disable_baseline(
                enabledBaselineIdentifier=enabled_baseline_identifier
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_baseline_operation(operation_id)
                print(f"Baseline operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return response["operationIdentifier"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConflictException":
                print(
                    f"Conflict disabling baseline: {err.response['Error']['Message']}. Skipping disable step."
                )
                return None
            else:
                logger.error(
                    "Couldn't disable baseline. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise


    def list_enabled_controls(self, target_identifier: str):
        """
        Lists all enabled controls for a specific target.

        :param target_identifier: The identifier of the target (e.g., OU ARN).
        :return: List of enabled controls.
        :raises ClientError: If the listing operation fails.
        """
        enabled_controls = []
        try:
            paginator = self.controltower_client.get_paginator("list_enabled_controls")

            for page in paginator.paginate(targetIdentifier=target_identifier):
                enabled_controls.extend(page["enabledControls"])
            return enabled_controls

        except ClientError as err:
            if err.response["Error"]["Code"] == "AccessDeniedException":
                logger.error(
                    "Access denied. Please ensure you have the necessary permissions."
                )
                return enabled_controls
            elif (
                err.response["Error"]["Code"] == "ResourceNotFoundException"
                and "not registered with AWS Control Tower"
                in err.response["Error"]["Message"]
            ):
                logger.error("Control Tower must be enabled to work with controls.")
                return enabled_controls
            else:
                logger.error(
                    "Couldn't list enabled controls. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateLandingZone](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/CreateLandingZone)
  + [DeleteLandingZone](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/DeleteLandingZone)
  + [DisableBaseline](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/DisableBaseline)
  + [DisableControl](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/DisableControl)
  + [EnableBaseline](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/EnableBaseline)
  + [EnableControl](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/EnableControl)
  + [GetControlOperation](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/GetControlOperation)
  + [GetLandingZoneOperation](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/GetLandingZoneOperation)
  + [ListBaselines](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListBaselines)
  + [ListEnabledBaselines](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListEnabledBaselines)
  + [ListEnabledControls](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListEnabledControls)
  + [ListLandingZones](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListLandingZones)
  + [ResetEnabledBaseline](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ResetEnabledBaseline)

## アクション
<a name="actions"></a>

### `DisableBaseline`
<a name="controltower_DisableBaseline_python_3_topic"></a>

次のコード例は、`DisableBaseline` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def disable_baseline(self, enabled_baseline_identifier: str):
        """
        Disables a baseline for a specific target and waits for the operation to complete.

        :param enabled_baseline_identifier: The identifier of the baseline to disable.
        :return: The operation ID.
        :raises ClientError: If disabling the baseline fails.
        """
        try:
            response = self.controltower_client.disable_baseline(
                enabledBaselineIdentifier=enabled_baseline_identifier
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_baseline_operation(operation_id)
                print(f"Baseline operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return response["operationIdentifier"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConflictException":
                print(
                    f"Conflict disabling baseline: {err.response['Error']['Message']}. Skipping disable step."
                )
                return None
            else:
                logger.error(
                    "Couldn't disable baseline. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DisableBaseline](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/DisableBaseline)」を参照してください。**

### `DisableControl`
<a name="controltower_DisableControl_python_3_topic"></a>

次のコード例は、`DisableControl` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def disable_control(self, control_arn: str, target_identifier: str):
        """
        Disables a control for a specified target.

        :param control_arn: The ARN of the control to disable.
        :param target_identifier: The identifier of the target (e.g., OU ARN).
        :return: The operation ID.
        :raises ClientError: If disabling the control fails.
        """
        try:
            response = self.controltower_client.disable_control(
                controlIdentifier=control_arn, targetIdentifier=target_identifier
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_control_operation(operation_id)
                print(f"Control operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return operation_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Control not found.")
            else:
                logger.error(
                    "Couldn't disable control. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DisableControl](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/DisableControl)」を参照してください。**

### `EnableBaseline`
<a name="controltower_EnableBaseline_python_3_topic"></a>

次のコード例は、`EnableBaseline` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def enable_baseline(
        self,
        target_identifier: str,
        identity_center_baseline: str,
        baseline_identifier: str,
        baseline_version: str,
    ):
        """
        Enables a baseline for the specified target if it's not already enabled.

        :param target_identifier: The ARN of the target.
        :param baseline_identifier: The identifier of baseline to enable.
        :param identity_center_baseline: The identifier of identity center baseline if it is enabled.
        :param baseline_version: The version of baseline to enable.
        :return: The enabled baseline ARN or None if already enabled.
        :raises ClientError: If enabling the baseline fails for reasons other than it being already enabled.
        """
        try:
            # Only include parameters if identity_center_baseline is not empty
            parameters = []
            if identity_center_baseline:
                parameters = [
                    {
                        "key": "IdentityCenterEnabledBaselineArn",
                        "value": identity_center_baseline,
                    }
                ]
            
            response = self.controltower_client.enable_baseline(
                baselineIdentifier=baseline_identifier,
                baselineVersion=baseline_version,
                targetIdentifier=target_identifier,
                parameters=parameters,
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_baseline_operation(operation_id)
                print(f"Baseline operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return response["arn"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ValidationException":
                if "already enabled" in err.response["Error"]["Message"]:
                    print("Baseline is already enabled for this target")
                else:
                    print(
                        "Unable to enable baseline due to validation exception: %s: %s",
                        err.response["Error"]["Code"],
                        err.response["Error"]["Message"],
                    )
            logger.error(
                "Couldn't enable baseline. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            return None
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[EnableBaseline](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/EnableBaseline)」を参照してください。**

### `EnableControl`
<a name="controltower_EnableControl_python_3_topic"></a>

次のコード例は、`EnableControl` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def enable_control(self, control_arn: str, target_identifier: str):
        """
        Enables a control for a specified target.

        :param control_arn: The ARN of the control to enable.
        :param target_identifier: The identifier of the target (e.g., OU ARN).
        :return: The operation ID.
        :raises ClientError: If enabling the control fails.
        """
        try:
            print(control_arn)
            print(target_identifier)
            response = self.controltower_client.enable_control(
                controlIdentifier=control_arn, targetIdentifier=target_identifier
            )

            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_control_operation(operation_id)
                print(f"Control operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)

            return operation_id

        except ClientError as err:
            if (
                err.response["Error"]["Code"] == "ValidationException"
                and "already enabled" in err.response["Error"]["Message"]
            ):
                logger.info("Control is already enabled for this target")
                return None
            elif (
                err.response["Error"]["Code"] == "ResourceNotFoundException"
                and "not registered with AWS Control Tower"
                in err.response["Error"]["Message"]
            ):
                logger.error("Control Tower must be enabled to work with controls.")
                return None
            logger.error(
                "Couldn't enable control. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[EnableControl](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/EnableControl)」を参照してください。**

### `GetBaselineOperation`
<a name="controltower_GetBaselineOperation_python_3_topic"></a>

次のコード例は、`GetBaselineOperation` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def get_baseline_operation(self, operation_id: str):
        """
        Gets the status of a baseline operation.

        :param operation_id: The ID of the baseline operation.
        :return: The operation status.
        :raises ClientError: If getting the operation status fails.
        """
        try:
            response = self.controltower_client.get_baseline_operation(
                operationIdentifier=operation_id
            )
            return response["baselineOperation"]["status"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Operation not found.")
            else:
                logger.error(
                    "Couldn't get baseline operation status. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetBaselineOperation](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/GetBaselineOperation)」を参照してください。**

### `GetControlOperation`
<a name="controltower_GetControlOperation_python_3_topic"></a>

次のコード例は、`GetControlOperation` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def get_control_operation(self, operation_id: str):
        """
        Gets the status of a control operation.

        :param operation_id: The ID of the control operation.
        :return: The operation status.
        :raises ClientError: If getting the operation status fails.
        """
        try:
            response = self.controltower_client.get_control_operation(
                operationIdentifier=operation_id
            )
            return response["controlOperation"]["status"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Operation not found.")
            else:
                logger.error(
                    "Couldn't get control operation status. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetControlOperation](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/GetControlOperation)」を参照してください。**

### `ListBaselines`
<a name="controltower_ListBaselines_python_3_topic"></a>

次のコード例は、`ListBaselines` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def list_baselines(self):
        """
        Lists all baselines.

        :return: List of baselines.
        :raises ClientError: If the listing operation fails.
        """
        try:
            paginator = self.controltower_client.get_paginator("list_baselines")
            baselines = []
            for page in paginator.paginate():
                baselines.extend(page["baselines"])
            return baselines

        except ClientError as err:
            if err.response["Error"]["Code"] == "AccessDeniedException":
                logger.error(
                    "Access denied. Please ensure you have the necessary permissions."
                )
            else:
                logger.error(
                    "Couldn't list baselines. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListBaselines](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListBaselines)」を参照してください。**

### `ListEnabledBaselines`
<a name="controltower_ListEnabledBaselines_python_3_topic"></a>

次のコード例は、`ListEnabledBaselines` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def list_enabled_baselines(self):
        """
        Lists all enabled baselines.

        :return: List of enabled baselines.
        :raises ClientError: If the listing operation fails.
        """
        try:
            paginator = self.controltower_client.get_paginator("list_enabled_baselines")
            enabled_baselines = []
            for page in paginator.paginate():
                enabled_baselines.extend(page["enabledBaselines"])
            return enabled_baselines

        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Target not found.")
            else:
                logger.error(
                    "Couldn't list enabled baselines. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListEnabledBaselines](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListEnabledBaselines)」を参照してください。**

### `ListEnabledControls`
<a name="controltower_ListEnabledControls_python_3_topic"></a>

次のコード例は、`ListEnabledControls` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def list_enabled_controls(self, target_identifier: str):
        """
        Lists all enabled controls for a specific target.

        :param target_identifier: The identifier of the target (e.g., OU ARN).
        :return: List of enabled controls.
        :raises ClientError: If the listing operation fails.
        """
        enabled_controls = []
        try:
            paginator = self.controltower_client.get_paginator("list_enabled_controls")

            for page in paginator.paginate(targetIdentifier=target_identifier):
                enabled_controls.extend(page["enabledControls"])
            return enabled_controls

        except ClientError as err:
            if err.response["Error"]["Code"] == "AccessDeniedException":
                logger.error(
                    "Access denied. Please ensure you have the necessary permissions."
                )
                return enabled_controls
            elif (
                err.response["Error"]["Code"] == "ResourceNotFoundException"
                and "not registered with AWS Control Tower"
                in err.response["Error"]["Message"]
            ):
                logger.error("Control Tower must be enabled to work with controls.")
                return enabled_controls
            else:
                logger.error(
                    "Couldn't list enabled controls. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListEnabledControls](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListEnabledControls)」を参照してください。**

### `ListLandingZones`
<a name="controltower_ListLandingZones_python_3_topic"></a>

次のコード例は、`ListLandingZones` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def list_landing_zones(self):
        """
        Lists all landing zones.

        :return: List of landing zones.
        :raises ClientError: If the listing operation fails.
        """
        try:
            paginator = self.controltower_client.get_paginator("list_landing_zones")
            landing_zones = []
            for page in paginator.paginate():
                landing_zones.extend(page["landingZones"])
            return landing_zones

        except ClientError as err:
            if err.response["Error"]["Code"] == "AccessDeniedException":
                logger.error(
                    "Access denied. Please ensure you have the necessary permissions."
                )
            else:
                logger.error(
                    "Couldn't list landing zones. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListLandingZones](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ListLandingZones)」を参照してください。**

### `ResetEnabledBaseline`
<a name="controltower_ResetEnabledBaseline_python_3_topic"></a>

次のコード例は、`ResetEnabledBaseline` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/controltower#code-examples)での設定と実行の方法を確認してください。

```
class ControlTowerWrapper:
    """Encapsulates AWS Control Tower and Control Catalog functionality."""

    def __init__(
        self, controltower_client: boto3.client, controlcatalog_client: boto3.client
    ):
        """
        :param controltower_client: A Boto3 Amazon ControlTower client.
        :param controlcatalog_client: A Boto3 Amazon ControlCatalog client.
        """
        self.controltower_client = controltower_client
        self.controlcatalog_client = controlcatalog_client

    @classmethod
    def from_client(cls):
        controltower_client = boto3.client("controltower")
        controlcatalog_client = boto3.client("controlcatalog")
        return cls(controltower_client, controlcatalog_client)


    def reset_enabled_baseline(self, enabled_baseline_identifier: str):
        """
        Resets an enabled baseline for a specific target.

        :param enabled_baseline_identifier: The identifier of the enabled baseline to reset.
        :return: The operation ID.
        :raises ClientError: If resetting the baseline fails.
        """
        try:
            response = self.controltower_client.reset_enabled_baseline(
                enabledBaselineIdentifier=enabled_baseline_identifier
            )
            operation_id = response["operationIdentifier"]
            while True:
                status = self.get_baseline_operation(operation_id)
                print(f"Baseline operation status: {status}")
                if status in ["SUCCEEDED", "FAILED"]:
                    break
                time.sleep(30)
            return operation_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Target not found.")
            else:
                logger.error(
                    "Couldn't reset enabled baseline. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの[ResetEnabledBaseline](https://docs.aws.amazon.com/goto/boto3/controltower-2018-05-10/ResetEnabledBaseline)」を参照してください。**

# SDK for Python (Boto3) を使用した Firehose の例
<a name="python_3_firehose_code_examples"></a>

次のコード例は、Firehose AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `PutRecord`
<a name="firehose_PutRecord_python_3_topic"></a>

次のコード例は、`PutRecord` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/firehose#code-examples)での設定と実行の方法を確認してください。

```
class FirehoseClient:
    """
    AWS Firehose client to send records and monitor metrics.

    Attributes:
        config (object): Configuration object with delivery stream name and region.
        delivery_stream_name (str): Name of the Firehose delivery stream.
        region (str): AWS region for Firehose and CloudWatch clients.
        firehose (boto3.client): Boto3 Firehose client.
        cloudwatch (boto3.client): Boto3 CloudWatch client.
    """

    def __init__(self, config):
        """
        Initialize the FirehoseClient.

        Args:
            config (object): Configuration object with delivery stream name and region.
        """
        self.config = config
        self.delivery_stream_name = config.delivery_stream_name
        self.region = config.region
        self.firehose = boto3.client("firehose", region_name=self.region)
        self.cloudwatch = boto3.client("cloudwatch", region_name=self.region)


    @backoff.on_exception(
        backoff.expo, Exception, max_tries=5, jitter=backoff.full_jitter
    )
    def put_record(self, record: dict):
        """
        Put individual records to Firehose with backoff and retry.

        Args:
            record (dict): The data record to be sent to Firehose.

        This method attempts to send an individual record to the Firehose delivery stream.
        It retries with exponential backoff in case of exceptions.
        """
        try:
            entry = self._create_record_entry(record)
            response = self.firehose.put_record(
                DeliveryStreamName=self.delivery_stream_name, Record=entry
            )
            self._log_response(response, entry)
        except Exception:
            logger.info(f"Fail record: {record}.")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutRecord](https://docs.aws.amazon.com/goto/boto3/firehose-2015-08-04/PutRecord)」を参照してください。

### `PutRecordBatch`
<a name="firehose_PutRecordBatch_python_3_topic"></a>

次のコード例は、`PutRecordBatch` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/firehose#code-examples)での設定と実行の方法を確認してください。

```
class FirehoseClient:
    """
    AWS Firehose client to send records and monitor metrics.

    Attributes:
        config (object): Configuration object with delivery stream name and region.
        delivery_stream_name (str): Name of the Firehose delivery stream.
        region (str): AWS region for Firehose and CloudWatch clients.
        firehose (boto3.client): Boto3 Firehose client.
        cloudwatch (boto3.client): Boto3 CloudWatch client.
    """

    def __init__(self, config):
        """
        Initialize the FirehoseClient.

        Args:
            config (object): Configuration object with delivery stream name and region.
        """
        self.config = config
        self.delivery_stream_name = config.delivery_stream_name
        self.region = config.region
        self.firehose = boto3.client("firehose", region_name=self.region)
        self.cloudwatch = boto3.client("cloudwatch", region_name=self.region)


    @backoff.on_exception(
        backoff.expo, Exception, max_tries=5, jitter=backoff.full_jitter
    )
    def put_record_batch(self, data: list, batch_size: int = 500):
        """
        Put records in batches to Firehose with backoff and retry.

        Args:
            data (list): List of data records to be sent to Firehose.
            batch_size (int): Number of records to send in each batch. Default is 500.

        This method attempts to send records in batches to the Firehose delivery stream.
        It retries with exponential backoff in case of exceptions.
        """
        for i in range(0, len(data), batch_size):
            batch = data[i : i + batch_size]
            record_dicts = [{"Data": json.dumps(record)} for record in batch]
            try:
                response = self.firehose.put_record_batch(
                    DeliveryStreamName=self.delivery_stream_name, Records=record_dicts
                )
                self._log_batch_response(response, len(batch))
            except Exception as e:
                logger.info(f"Failed to send batch of {len(batch)} records. Error: {e}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutRecordBatch](https://docs.aws.amazon.com/goto/boto3/firehose-2015-08-04/PutRecordBatch)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Firehose にレコードを配置する
<a name="firehose_Scenario_PutRecords_python_3_topic"></a>

次のコード例は、Firehose を使用して個別レコードとバッチレコードを処理する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/firehose/scenarios/firehose-put-actions#code-examples)での設定と実行の方法を確認してください。
このスクリプトは、個別レコードとバッチレコードを Firehose に配置します。  

```
import json
import logging
import random
from datetime import datetime, timedelta

import backoff
import boto3

from config import get_config


def load_sample_data(path: str) -> dict:
    """
    Load sample data from a JSON file.

    Args:
        path (str): The file path to the JSON file containing sample data.

    Returns:
        dict: The loaded sample data as a dictionary.
    """
    with open(path, "r") as f:
        return json.load(f)


# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class FirehoseClient:
    """
    AWS Firehose client to send records and monitor metrics.

    Attributes:
        config (object): Configuration object with delivery stream name and region.
        delivery_stream_name (str): Name of the Firehose delivery stream.
        region (str): AWS region for Firehose and CloudWatch clients.
        firehose (boto3.client): Boto3 Firehose client.
        cloudwatch (boto3.client): Boto3 CloudWatch client.
    """

    def __init__(self, config):
        """
        Initialize the FirehoseClient.

        Args:
            config (object): Configuration object with delivery stream name and region.
        """
        self.config = config
        self.delivery_stream_name = config.delivery_stream_name
        self.region = config.region
        self.firehose = boto3.client("firehose", region_name=self.region)
        self.cloudwatch = boto3.client("cloudwatch", region_name=self.region)


    @backoff.on_exception(
        backoff.expo, Exception, max_tries=5, jitter=backoff.full_jitter
    )
    def put_record(self, record: dict):
        """
        Put individual records to Firehose with backoff and retry.

        Args:
            record (dict): The data record to be sent to Firehose.

        This method attempts to send an individual record to the Firehose delivery stream.
        It retries with exponential backoff in case of exceptions.
        """
        try:
            entry = self._create_record_entry(record)
            response = self.firehose.put_record(
                DeliveryStreamName=self.delivery_stream_name, Record=entry
            )
            self._log_response(response, entry)
        except Exception:
            logger.info(f"Fail record: {record}.")
            raise


    @backoff.on_exception(
        backoff.expo, Exception, max_tries=5, jitter=backoff.full_jitter
    )
    def put_record_batch(self, data: list, batch_size: int = 500):
        """
        Put records in batches to Firehose with backoff and retry.

        Args:
            data (list): List of data records to be sent to Firehose.
            batch_size (int): Number of records to send in each batch. Default is 500.

        This method attempts to send records in batches to the Firehose delivery stream.
        It retries with exponential backoff in case of exceptions.
        """
        for i in range(0, len(data), batch_size):
            batch = data[i : i + batch_size]
            record_dicts = [{"Data": json.dumps(record)} for record in batch]
            try:
                response = self.firehose.put_record_batch(
                    DeliveryStreamName=self.delivery_stream_name, Records=record_dicts
                )
                self._log_batch_response(response, len(batch))
            except Exception as e:
                logger.info(f"Failed to send batch of {len(batch)} records. Error: {e}")


    def get_metric_statistics(
        self,
        metric_name: str,
        start_time: datetime,
        end_time: datetime,
        period: int,
        statistics: list = ["Sum"],
    ) -> list:
        """
        Retrieve metric statistics from CloudWatch.

        Args:
            metric_name (str): The name of the metric.
            start_time (datetime): The start time for the metric statistics.
            end_time (datetime): The end time for the metric statistics.
            period (int): The granularity, in seconds, of the returned data points.
            statistics (list): A list of statistics to retrieve. Default is ['Sum'].

        Returns:
            list: List of datapoints containing the metric statistics.
        """
        response = self.cloudwatch.get_metric_statistics(
            Namespace="AWS/Firehose",
            MetricName=metric_name,
            Dimensions=[
                {"Name": "DeliveryStreamName", "Value": self.delivery_stream_name},
            ],
            StartTime=start_time,
            EndTime=end_time,
            Period=period,
            Statistics=statistics,
        )
        return response["Datapoints"]

    def monitor_metrics(self):
        """
        Monitor Firehose metrics for the last 5 minutes.

        This method retrieves and logs the 'IncomingBytes', 'IncomingRecords', and 'FailedPutCount' metrics
        from CloudWatch for the last 5 minutes.
        """
        end_time = datetime.utcnow()
        start_time = end_time - timedelta(minutes=10)
        period = int((end_time - start_time).total_seconds())

        metrics = {
            "IncomingBytes": self.get_metric_statistics(
                "IncomingBytes", start_time, end_time, period
            ),
            "IncomingRecords": self.get_metric_statistics(
                "IncomingRecords", start_time, end_time, period
            ),
            "FailedPutCount": self.get_metric_statistics(
                "FailedPutCount", start_time, end_time, period
            ),
        }

        for metric, datapoints in metrics.items():
            if datapoints:
                total_sum = sum(datapoint["Sum"] for datapoint in datapoints)
                if metric == "IncomingBytes":
                    logger.info(
                        f"{metric}: {round(total_sum)} ({total_sum / (1024 * 1024):.2f} MB)"
                    )
                else:
                    logger.info(f"{metric}: {round(total_sum)}")
            else:
                logger.info(f"No data found for {metric} over the last 5 minutes")


    def _create_record_entry(self, record: dict) -> dict:
        """
        Create a record entry for Firehose.

        Args:
            record (dict): The data record to be sent.

        Returns:
            dict: The record entry formatted for Firehose.

        Raises:
            Exception: If a simulated network error occurs.
        """
        if random.random() < 0.2:
            raise Exception("Simulated network error")
        elif random.random() < 0.1:
            return {"Data": '{"malformed": "data"'}
        else:
            return {"Data": json.dumps(record)}

    def _log_response(self, response: dict, entry: dict):
        """
        Log the response from Firehose.

        Args:
            response (dict): The response from the Firehose put_record API call.
            entry (dict): The record entry that was sent.
        """
        if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            logger.info(f"Sent record: {entry}")
        else:
            logger.info(f"Fail record: {entry}")

    def _log_batch_response(self, response: dict, batch_size: int):
        """
        Log the batch response from Firehose.

        Args:
            response (dict): The response from the Firehose put_record_batch API call.
            batch_size (int): The number of records in the batch.
        """
        if response.get("FailedPutCount", 0) > 0:
            logger.info(
                f'Failed to send {response["FailedPutCount"]} records in batch of {batch_size}'
            )
        else:
            logger.info(f"Successfully sent batch of {batch_size} records")


if __name__ == "__main__":
    config = get_config()
    data = load_sample_data(config.sample_data_file)
    client = FirehoseClient(config)

    # Process the first 100 sample network records
    for record in data[:100]:
        try:
            client.put_record(record)
        except Exception as e:
            logger.info(f"Put record failed after retries and backoff: {e}")
    client.monitor_metrics()

    # Process remaining records using the batch method
    try:
        client.put_record_batch(data[100:])
    except Exception as e:
        logger.info(f"Put record batch failed after retries and backoff: {e}")
    client.monitor_metrics()
```
このファイルには、上記のスクリプトの設定が含まれています。  

```
class Config:
    def __init__(self):
        self.delivery_stream_name = "ENTER YOUR DELIVERY STREAM NAME HERE"
        self.region = "us-east-1"
        self.sample_data_file = (
            "../../../../../scenarios/features/firehose/resources/sample_records.json"
        )


def get_config():
    return Config()
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [PutRecord](https://docs.aws.amazon.com/goto/boto3/firehose-2015-08-04/PutRecord)
  + [PutRecordBatch](https://docs.aws.amazon.com/goto/boto3/firehose-2015-08-04/PutRecordBatch)

# SDK for Python (Boto3) を使用した Device Farm の例
<a name="python_3_device-farm_code_examples"></a>

次のコード例は、Device Farm AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### ブラウザテストを実行し、スクリーンショットを撮る
<a name="device-farm_Scenario_BrowserTesting_python_3_topic"></a>

次のコード例は、Device Farm でブラウザテストを実行し、スクリーンショットを取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/devicefarm/browser_testing#code-examples)での設定と実行の方法を確認してください。
PyTest と Selenium を使用して、指定した ウェブサイトを閲覧したり、スクリーンショットを撮ったり、実際のウェブサイトのコンテンツを予想されるコンテンツと比較したりします。  

```
import datetime
import os
import subprocess
import boto3
import pytest
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


def get_git_hash():
    """
    Get the short Git hash of the current commit of the repository
    """
    try:
        return (
            subprocess.check_output(["git", "rev-parse", "--short", "HEAD"])
            .decode("utf-8")
            .strip()
        )
    except:
        return "norepo"


class TestHelloSuite:
    """
    Our test suite.

    This style of test suite allows us to use setup_method and teardown_method.

    """

    def save_screenshot(self, name):
        self.driver.save_screenshot(os.path.join(self.screenshot_path, name))

    def setup_method(self, method):
        """
        Set up a test.

        This makes sure that the session for an individual test is ready.

        The AWS credentials are read from the default ~/.aws/credentials or from the
        command line by setting the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment
        variables.

        The project Amazon Resource Name (ARN) is determined by the PROJECT_ARN
        environment variable.
        """
        devicefarm_client = boto3.client("devicefarm")
        project_arn = os.environ.get("PROJECT_ARN", None)
        if project_arn is None:
            raise ValueError("Must set PROJECT_ARN")
        # Request a driver hub URL for the Selenium client
        testgrid_url_response = devicefarm_client.create_test_grid_url(
            projectArn=project_arn, expiresInSeconds=300
        )

        # We want a directory to save our files into. We're going to make a directory
        # in the current directory that holds our results.
        self.screenshot_path = os.path.join(
            ".", "results", get_git_hash() + "-" + (datetime.date.today().isoformat())
        )
        if not os.path.exists(self.screenshot_path):
            os.makedirs(self.screenshot_path, exist_ok=True)

        # We want a Firefox instance on Windows
        desired_cap = DesiredCapabilities.FIREFOX
        desired_cap["platform"] = "windows"
        desired_cap["BrowserVersion"] = "latest"

        # Configure the webdriver with the appropriate remote endpoint.
        self.driver = webdriver.Remote(testgrid_url_response["url"], desired_cap)

        #
        # Auto-Tagging
        #

        # In order to get the Session ARN, we need to look up the session by the
        # Project ARN and session ID (from the driver).
        testgrid_session_arn_response = devicefarm_client.get_test_grid_session(
            projectArn=project_arn, sessionId=self.driver.session_id
        )

        # Save the session's ARN so we can tag the session.
        self.session_arn = testgrid_session_arn_response["testGridSession"]["arn"]

        # In order to tag it, we're going to use the resourcegroupstaggingapi client to
        # add a tag to the session ARN that we just got.
        tag_client = boto3.client("resourcegroupstaggingapi")
        tag_client.tag_resources(
            ResourceARNList=[self.session_arn],
            Tags={"TestSuite": f"testsuite {method.__name__}", "GitId": get_git_hash()},
        )

    def teardown_method(self, method):
        """
        Clean up resources used by each method.
        """
        # End the Selenium session so we're off the clock.
        self.driver.quit()

    @pytest.mark.parametrize(
        "query,leading",
        [
            pytest.param(
                "Seattle",
                "Seattle (/siˈætəl/ (listen) see-AT-əl) is a seaport city on the West Coast of the United States.",
            ),
            pytest.param(
                "Selenium",
                "Selenium is a chemical element with the symbol Se and atomic number 34.",
            ),
            pytest.param(
                "Amazon Locker",
                "Amazon Locker is a self-service package delivery service offered by online retailer Amazon.",
            ),
            pytest.param(
                "Kootenai Falls",
                "Kootenai Falls is a waterfall on the Kootenay River located in Lincoln County, Montana, just off U.S. Route 2.",
            ),
            pytest.param(
                "Dorayaki",
                "Dorayaki (どら焼き, どらやき, 銅鑼焼き, ドラ焼き) is a type of Japanese confection.",
            ),
            pytest.param("Robot Face", "<|°_°|> (also known as Robot Face or Robot)"),
        ],
    )
    def test_first_paragraph_text(self, query, leading):
        """
        This test looks at the first paragraph of a page on Wikipedia, comparing it to
        a known leading sentence.

        If the leading sentence matches, the test passes. A screenshot is taken before
        the final assertion is made, letting us debug if something isn't right.
        """
        # Open the main page of Wikipedia
        self.driver.get("https://en.wikipedia.org/wiki/Main_Page")
        # Find the search box, enter a query, and press enter
        search_input = self.driver.find_element(By.ID, "searchInput")
        search_input.click()
        search_input.send_keys(query)
        search_input.send_keys(Keys.ENTER)
        # Wait for the search box to go stale -- This means we've navigated fully.
        WebDriverWait(self.driver, 5).until(
            expected_conditions.staleness_of(search_input)
        )
        # Get the leading paragraph of the article.
        lead = leading.lower()
        # Find the element...
        lead_para = self.driver.find_element(
            By.XPATH, "//div[@class='mw-parser-output']//p[not(@class)]"
        )
        # ... and copy out its text.
        our_text = lead_para.text.lower()
        our_text = our_text[: len(lead)]
        # Take a screenshot and compare the strings.
        self.save_screenshot(f"leadingpara_{query}.png")
        assert our_text.startswith(lead)

    @pytest.mark.parametrize(
        "query,expected",
        [
            pytest.param("Automation Testing", "Test Automation"),
            pytest.param("DevOps", "DevOps"),
            pytest.param("Jackdaws Love My Big Sphinx Of Quartz", "Pangram"),
            pytest.param("EarthBound", "EarthBound"),
            pytest.param("Covered Bridges Today", "Covered Bridges Today"),
            pytest.param("Kurt Godel", "Kurt Gödel"),
            pytest.param("N//ng language", "Nǁng language"),
            pytest.param(
                "Who the Frick Is Jackson Pollock?", "Who the $&% Is Jackson Pollock?"
            ),
        ],
    )
    def test_redirect_titles(self, query, expected):
        """
        A test comparing pages we expect to (or not to) redirect on Wikipedia.

        This test checks to see that the page ("query") redirects (or doesn't) to the
        "expected" page title. Several of these are common synonyms ("Jackdaws...")
        while others are because of characters untypable by most keyboards ("Nǁng language")

        A screenshot is taken just before the final assertion is made to aid in
        debugging and verification.
        """
        # Open the main page of Wikipedia
        self.driver.get("https://en.wikipedia.org/wiki/Main_Page")
        # Find the search box, enter some text into it, and send an enter key.
        search_input = self.driver.find_element(By.ID, "searchInput")
        search_input.click()
        search_input.send_keys(query)
        search_input.send_keys(Keys.ENTER)
        # wait until the page has rolled over -- once the search input handle is stale,
        # the browser has navigated.
        WebDriverWait(self.driver, 5).until(
            expected_conditions.staleness_of(search_input)
        )
        # Get the first heading & take a screenshot
        our_text = self.driver.find_element(By.ID, "firstHeading").text.lower()
        self.save_screenshot(f"redirect_{query}.png")
        # did it match?
        assert our_text == expected.lower()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateTestGridUrl](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/CreateTestGridUrl)
  + [GetTestGridSession](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/GetTestGridSession)

### デバイスパッケージをアップロードしてテストする
<a name="device-farm_Scenario_DeviceTesting_python_3_topic"></a>

次のコード例は、Device Farm でモバイルデバイスパッケージをアップロードしてテストする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/devicefarm/device_testing#code-examples)での設定と実行の方法を確認してください。
コンパイルされた Android アプリケーションとテストパッケージを Device Farm にアップロードし、テストを開始し、テストの完了を待って、結果を報告します。  

```
import boto3
import os
import requests
import string
import random
import datetime
import time

# Update this dict with your own values before you run the example:
config = {
    # This is our app under test.
    "appFilePath": "app-debug.apk",
    "projectArn": "arn:aws:devicefarm:us-west-2:111222333444:project:581f5703-e040-4ac9-b7ae-0ba007bfb8e6",
    # Since we care about the most popular devices, we'll use a curated pool.
    "testSpecArn": "arn:aws:devicefarm:us-west-2::upload:20fcf771-eae3-4137-aa76-92e17fb3131b",
    "poolArn": "arn:aws:devicefarm:us-west-2::devicepool:4a869d91-6f17-491f-9a95-0a601aee2406",
    "namePrefix": "MyAppTest",
    # This is our test package. This tutorial won't go into how to make these.
    "testPackage": "tests.zip",
}

client = boto3.client("devicefarm")

unique = (
    config["namePrefix"]
    + "-"
    + (datetime.date.today().isoformat())
    + ("".join(random.sample(string.ascii_letters, 8)))
)

print(
    f"The unique identifier for this run is '{unique}'. All uploads will be prefixed "
    f"with this."
)


def upload_df_file(filename, type_, mime="application/octet-stream"):
    upload_response = client.create_upload(
        projectArn=config["projectArn"],
        name=unique + "_" + os.path.basename(filename),
        type=type_,
        contentType=mime,
    )
    upload_arn = upload_response["upload"]["arn"]
    # Extract the URL of the upload and use Requests to upload it.
    upload_url = upload_response["upload"]["url"]
    with open(filename, "rb") as file_stream:
        print(
            f"Uploading {filename} to Device Farm as "
            f"{upload_response['upload']['name']}... ",
            end="",
        )
        put_req = requests.put(
            upload_url, data=file_stream, headers={"content-type": mime}
        )
        print(" done")
        if not put_req.ok:
            raise Exception(f"Couldn't upload. Requests says: {put_req.reason}")
    started = datetime.datetime.now()
    while True:
        print(
            f"Upload of {filename} in state {upload_response['upload']['status']} "
            f"after " + str(datetime.datetime.now() - started)
        )
        if upload_response["upload"]["status"] == "FAILED":
            raise Exception(
                f"The upload failed processing. Device Farm says the reason is: \n"
                f"{+upload_response['upload']['message']}"
            )
        if upload_response["upload"]["status"] == "SUCCEEDED":
            break
        time.sleep(5)
        upload_response = client.get_upload(arn=upload_arn)
    print("")
    return upload_arn


our_upload_arn = upload_df_file(config["appFilePath"], "ANDROID_APP")
our_test_package_arn = upload_df_file(
    config["testPackage"], "APPIUM_PYTHON_TEST_PACKAGE"
)
print(our_upload_arn, our_test_package_arn)

response = client.schedule_run(
    projectArn=config["projectArn"],
    appArn=our_upload_arn,
    devicePoolArn=config["poolArn"],
    name=unique,
    test={
        "type": "APPIUM_PYTHON",
        "testSpecArn": config["testSpecArn"],
        "testPackageArn": our_test_package_arn,
    },
)
run_arn = response["run"]["arn"]
start_time = datetime.datetime.now()
print(f"Run {unique} is scheduled as arn {run_arn} ")

state = "UNKNOWN"
try:
    while True:
        response = client.get_run(arn=run_arn)
        state = response["run"]["status"]
        if state == "COMPLETED" or state == "ERRORED":
            break
        else:
            print(
                f" Run {unique} in state {state}, total "
                f"time {datetime.datetime.now() - start_time}"
            )
            time.sleep(10)
except:
    client.stop_run(arn=run_arn)
    exit(1)

print(f"Tests finished in state {state} after {datetime.datetime.now() - start_time}")
# Pull all the logs.
jobs_response = client.list_jobs(arn=run_arn)
# Save the output somewhere, using the unique value.
save_path = os.path.join(os.getcwd(), "results", unique)
os.mkdir(save_path)
# Save the last run information.
for job in jobs_response["jobs"]:
    job_name = job["name"]
    os.makedirs(os.path.join(save_path, job_name), exist_ok=True)
    # Get each suite within the job.
    suites = client.list_suites(arn=job["arn"])["suites"]
    for suite in suites:
        for test in client.list_tests(arn=suite["arn"])["tests"]:
            # Get the artifacts.
            for artifact_type in ["FILE", "SCREENSHOT", "LOG"]:
                artifacts = client.list_artifacts(type=artifact_type, arn=test["arn"])[
                    "artifacts"
                ]
                for artifact in artifacts:
                    # Replace `:` because it has a special meaning in Windows & macOS.
                    path_to = os.path.join(
                        save_path,
                        job_name,
                        suite["name"],
                        test["name"].replace(":", "_"),
                    )
                    os.makedirs(path_to, exist_ok=True)
                    filename = (
                        artifact["type"]
                        + "_"
                        + artifact["name"]
                        + "."
                        + artifact["extension"]
                    )
                    artifact_save_path = os.path.join(path_to, filename)
                    print(f"Downloading {artifact_save_path}")
                    with open(artifact_save_path, "wb") as fn:
                        with requests.get(
                            artifact["url"], allow_redirects=True
                        ) as request:
                            fn.write(request.content)
print("Finished")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateUpload](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/CreateUpload)
  + [GetRun](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/GetRun)
  + [GetUpload](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/GetUpload)
  + [ListArtifacts](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/ListArtifacts)
  + [ListJobs](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/ListJobs)
  + [ListSuites](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/ListSuites)
  + [ListTests](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/ListTests)
  + [ScheduleRun](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/ScheduleRun)
  + [StopRun](https://docs.aws.amazon.com/goto/boto3/devicefarm-2015-06-23/StopRun)

# SDK for Python (Boto3) を使用した Amazon DocumentDB の例
<a name="python_3_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_python_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
import json

def lambda_handler(event, context):
    for record in event.get('events', []):
        log_document_db_event(record)
    return 'OK'

def log_document_db_event(record):
    event_data = record.get('event', {})
    operation_type = event_data.get('operationType', 'Unknown')
    db = event_data.get('ns', {}).get('db', 'Unknown')
    collection = event_data.get('ns', {}).get('coll', 'Unknown')
    full_document = event_data.get('fullDocument', {})

    print(f"Operation type: {operation_type}")
    print(f"db: {db}")
    print(f"collection: {collection}")
    print("Full document:", json.dumps(full_document, indent=2))
```

# SDK for Python (Boto3) を使用した DynamoDB の例
<a name="python_3_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello DynamoDB
<a name="dynamodb_Hello_python_3_topic"></a>

次のコード例は、DynamoDB の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import boto3

# Create a DynamoDB client using the default credentials and region
dynamodb = boto3.client("dynamodb")

# Initialize a paginator for the list_tables operation
paginator = dynamodb.get_paginator("list_tables")

# Create a PageIterator from the paginator
page_iterator = paginator.paginate(Limit=10)

# List the tables in the current AWS account
print("Here are the DynamoDB tables in your account:")

# Use pagination to list all tables
table_names = []

for page in page_iterator:
    for table_name in page.get("TableNames", []):
        print(f"- {table_name}")
        table_names.append(table_name)

if not table_names:
    print("You don't have any DynamoDB tables in your account.")
else:
    print(f"\nFound {len(table_names)} tables.")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListTables](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/ListTables)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
DynamoDB テーブルをカプセル化するクラスを作成します。  

```
from decimal import Decimal
from io import BytesIO
import json
import logging
import os
from pprint import pprint
import requests
from zipfile import ZipFile
import boto3
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError
from question import Question

logger = logging.getLogger(__name__)

class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def exists(self, table_name):
        """
        Determines whether a table exists. As a side effect, stores the table in
        a member variable.

        :param table_name: The name of the table to check.
        :return: True when the table exists; otherwise, False.
        """
        try:
            table = self.dyn_resource.Table(table_name)
            table.load()
            exists = True
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                exists = False
            else:
                logger.error(
                    "Couldn't check for existence of %s. Here's why: %s: %s",
                    table_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            self.table = table
        return exists


    def create_table(self, table_name):
        """
        Creates an Amazon DynamoDB table that can be used to store movie data.
        The table uses the release year of the movie as the partition key and the
        title as the sort key.

        :param table_name: The name of the table to create.
        :return: The newly created table.
        """
        try:
            self.table = self.dyn_resource.create_table(
                TableName=table_name,
                KeySchema=[
                    {"AttributeName": "year", "KeyType": "HASH"},  # Partition key
                    {"AttributeName": "title", "KeyType": "RANGE"},  # Sort key
                ],
                AttributeDefinitions=[
                    {"AttributeName": "year", "AttributeType": "N"},
                    {"AttributeName": "title", "AttributeType": "S"},
                ],
                BillingMode='PAY_PER_REQUEST',
            )
            self.table.wait_until_exists()
        except ClientError as err:
            logger.error(
                "Couldn't create table %s. Here's why: %s: %s",
                table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return self.table


    def list_tables(self):
        """
        Lists the Amazon DynamoDB tables for the current account.

        :return: The list of tables.
        """
        try:
            tables = []
            for table in self.dyn_resource.tables.all():
                print(table.name)
                tables.append(table)
        except ClientError as err:
            logger.error(
                "Couldn't list tables. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return tables


    def write_batch(self, movies):
        """
        Fills an Amazon DynamoDB table with the specified data, using the Boto3
        Table.batch_writer() function to put the items in the table.
        Inside the context manager, Table.batch_writer builds a list of
        requests. On exiting the context manager, Table.batch_writer starts sending
        batches of write requests to Amazon DynamoDB and automatically
        handles chunking, buffering, and retrying.

        :param movies: The data to put in the table. Each item must contain at least
                       the keys required by the schema that was specified when the
                       table was created.
        """
        try:
            with self.table.batch_writer() as writer:
                for movie in movies:
                    writer.put_item(Item=movie)
        except ClientError as err:
            logger.error(
                "Couldn't load data into table %s. Here's why: %s: %s",
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def add_movie(self, title, year, plot, rating):
        """
        Adds a movie to the table.

        :param title: The title of the movie.
        :param year: The release year of the movie.
        :param plot: The plot summary of the movie.
        :param rating: The quality rating of the movie.
        """
        try:
            self.table.put_item(
                Item={
                    "year": year,
                    "title": title,
                    "info": {"plot": plot, "rating": Decimal(str(rating))},
                }
            )
        except ClientError as err:
            logger.error(
                "Couldn't add movie %s to table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def get_movie(self, title, year):
        """
        Gets movie data from the table for a specific movie.

        :param title: The title of the movie.
        :param year: The release year of the movie.
        :return: The data about the requested movie.
        """
        try:
            response = self.table.get_item(Key={"year": year, "title": title})
        except ClientError as err:
            logger.error(
                "Couldn't get movie %s from table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Item"]


    def update_movie(self, title, year, rating, plot):
        """
        Updates rating and plot data for a movie in the table.

        :param title: The title of the movie to update.
        :param year: The release year of the movie to update.
        :param rating: The updated rating to the give the movie.
        :param plot: The updated plot summary to give the movie.
        :return: The fields that were updated, with their new values.
        """
        try:
            response = self.table.update_item(
                Key={"year": year, "title": title},
                UpdateExpression="set info.rating=:r, info.plot=:p",
                ExpressionAttributeValues={":r": Decimal(str(rating)), ":p": plot},
                ReturnValues="UPDATED_NEW",
            )
        except ClientError as err:
            logger.error(
                "Couldn't update movie %s in table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Attributes"]


    def query_movies(self, year):
        """
        Queries for movies that were released in the specified year.

        :param year: The year to query.
        :return: The list of movies that were released in the specified year.
        """
        try:
            response = self.table.query(KeyConditionExpression=Key("year").eq(year))
        except ClientError as err:
            logger.error(
                "Couldn't query for movies released in %s. Here's why: %s: %s",
                year,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Items"]


    def scan_movies(self, year_range):
        """
        Scans for movies that were released in a range of years.
        Uses a projection expression to return a subset of data for each movie.

        :param year_range: The range of years to retrieve.
        :return: The list of movies released in the specified years.
        """
        movies = []
        scan_kwargs = {
            "FilterExpression": Key("year").between(
                year_range["first"], year_range["second"]
            ),
            "ProjectionExpression": "#yr, title, info.rating",
            "ExpressionAttributeNames": {"#yr": "year"},
        }
        try:
            done = False
            start_key = None
            while not done:
                if start_key:
                    scan_kwargs["ExclusiveStartKey"] = start_key
                response = self.table.scan(**scan_kwargs)
                movies.extend(response.get("Items", []))
                start_key = response.get("LastEvaluatedKey", None)
                done = start_key is None
        except ClientError as err:
            logger.error(
                "Couldn't scan for movies. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

        return movies


    def delete_movie(self, title, year):
        """
        Deletes a movie from the table.

        :param title: The title of the movie to delete.
        :param year: The release year of the movie to delete.
        """
        try:
            self.table.delete_item(Key={"year": year, "title": title})
        except ClientError as err:
            logger.error(
                "Couldn't delete movie %s. Here's why: %s: %s",
                title,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_table(self):
        """
        Deletes the table.
        """
        try:
            self.table.delete()
            self.table = None
        except ClientError as err:
            logger.error(
                "Couldn't delete table. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
サンプルの JSON ファイルをダウンロードして抽出するヘルパー関数を作成します。  

```
def get_sample_movie_data(movie_file_name):
    """
    Gets sample movie data, either from a local file or by first downloading it from
    the Amazon DynamoDB developer guide.

    :param movie_file_name: The local file name where the movie data is stored in JSON format.
    :return: The movie data as a dict.
    """
    if not os.path.isfile(movie_file_name):
        print(f"Downloading {movie_file_name}...")
        movie_content = requests.get(
            "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/samples/moviedata.zip"
        )
        movie_zip = ZipFile(BytesIO(movie_content.content))
        movie_zip.extractall()

    try:
        with open(movie_file_name) as movie_file:
            movie_data = json.load(movie_file, parse_float=Decimal)
    except FileNotFoundError:
        print(
            f"File {movie_file_name} not found. You must first download the file to "
            "run this demo. See the README for instructions."
        )
        raise
    else:
        # The sample file lists over 4000 movies, return only the first 250.
        return movie_data[:250]
```
対話型シナリオを実行してテーブルを作成し、そのテーブルに対してアクションを実行します。  

```
def run_scenario(table_name, movie_file_name, dyn_resource):
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Welcome to the Amazon DynamoDB getting started demo.")
    print("-" * 88)

    movies = Movies(dyn_resource)
    movies_exists = movies.exists(table_name)
    if not movies_exists:
        print(f"\nCreating table {table_name}...")
        movies.create_table(table_name)
        print(f"\nCreated table {movies.table.name}.")

    my_movie = Question.ask_questions(
        [
            Question(
                "title", "Enter the title of a movie you want to add to the table: "
            ),
            Question("year", "What year was it released? ", Question.is_int),
            Question(
                "rating",
                "On a scale of 1 - 10, how do you rate it? ",
                Question.is_float,
                Question.in_range(1, 10),
            ),
            Question("plot", "Summarize the plot for me: "),
        ]
    )
    movies.add_movie(**my_movie)
    print(f"\nAdded '{my_movie['title']}' to '{movies.table.name}'.")
    print("-" * 88)

    movie_update = Question.ask_questions(
        [
            Question(
                "rating",
                f"\nLet's update your movie.\nYou rated it {my_movie['rating']}, what new "
                f"rating would you give it? ",
                Question.is_float,
                Question.in_range(1, 10),
            ),
            Question(
                "plot",
                f"You summarized the plot as '{my_movie['plot']}'.\nWhat would you say now? ",
            ),
        ]
    )
    my_movie.update(movie_update)
    updated = movies.update_movie(**my_movie)
    print(f"\nUpdated '{my_movie['title']}' with new attributes:")
    pprint(updated)
    print("-" * 88)

    if not movies_exists:
        movie_data = get_sample_movie_data(movie_file_name)
        print(f"\nReading data from '{movie_file_name}' into your table.")
        movies.write_batch(movie_data)
        print(f"\nWrote {len(movie_data)} movies into {movies.table.name}.")
    print("-" * 88)

    title = "The Lord of the Rings: The Fellowship of the Ring"
    if Question.ask_question(
        f"Let's move on...do you want to get info about '{title}'? (y/n) ",
        Question.is_yesno,
    ):
        movie = movies.get_movie(title, 2001)
        print("\nHere's what I found:")
        pprint(movie)
    print("-" * 88)

    ask_for_year = True
    while ask_for_year:
        release_year = Question.ask_question(
            f"\nLet's get a list of movies released in a given year. Enter a year between "
            f"1972 and 2018: ",
            Question.is_int,
            Question.in_range(1972, 2018),
        )
        releases = movies.query_movies(release_year)
        if releases:
            print(f"There were {len(releases)} movies released in {release_year}:")
            for release in releases:
                print(f"\t{release['title']}")
            ask_for_year = False
        else:
            print(f"I don't know about any movies released in {release_year}!")
            ask_for_year = Question.ask_question(
                "Try another year? (y/n) ", Question.is_yesno
            )
    print("-" * 88)

    years = Question.ask_questions(
        [
            Question(
                "first",
                f"\nNow let's scan for movies released in a range of years. Enter a year: ",
                Question.is_int,
                Question.in_range(1972, 2018),
            ),
            Question(
                "second",
                "Now enter another year: ",
                Question.is_int,
                Question.in_range(1972, 2018),
            ),
        ]
    )
    releases = movies.scan_movies(years)
    if releases:
        count = Question.ask_question(
            f"\nFound {len(releases)} movies. How many do you want to see? ",
            Question.is_int,
            Question.in_range(1, len(releases)),
        )
        print(f"\nHere are your {count} movies:\n")
        pprint(releases[:count])
    else:
        print(
            f"I don't know about any movies released between {years['first']} "
            f"and {years['second']}."
        )
    print("-" * 88)

    if Question.ask_question(
        f"\nLet's remove your movie from the table. Do you want to remove "
        f"'{my_movie['title']}'? (y/n)",
        Question.is_yesno,
    ):
        movies.delete_movie(my_movie["title"], my_movie["year"])
        print(f"\nRemoved '{my_movie['title']}' from the table.")
    print("-" * 88)

    if Question.ask_question(f"\nDelete the table? (y/n) ", Question.is_yesno):
        movies.delete_table()
        print(f"Deleted {table_name}.")
    else:
        print(
            "Don't forget to delete the table when you're done or you might incur "
            "charges on your account."
        )

    print("\nThanks for watching!")
    print("-" * 88)


if __name__ == "__main__":
    try:
        run_scenario(
            "doc-example-table-movies", "moviedata.json", boto3.resource("dynamodb")
        )
    except Exception as e:
        print(f"Something went wrong with the demo! Here's what: {e}")
```
このシナリオでは、次のヘルパークラスを使用してコマンドプロンプトで質問します。  

```
class Question:
    """
    A helper class to ask questions at a command prompt and validate and convert
    the answers.
    """

    def __init__(self, key, question, *validators):
        """
        :param key: The key that is used for storing the answer in a dict, when
                    multiple questions are asked in a set.
        :param question: The question to ask.
        :param validators: The answer is passed through the list of validators until
                           one fails or they all pass. Validators may also convert the
                           answer to another form, such as from a str to an int.
        """
        self.key = key
        self.question = question
        self.validators = Question.non_empty, *validators

    @staticmethod
    def ask_questions(questions):
        """
        Asks a set of questions and stores the answers in a dict.

        :param questions: The list of questions to ask.
        :return: A dict of answers.
        """
        answers = {}
        for question in questions:
            answers[question.key] = Question.ask_question(
                question.question, *question.validators
            )
        return answers

    @staticmethod
    def ask_question(question, *validators):
        """
        Asks a single question and validates it against a list of validators.
        When an answer fails validation, the complaint is printed and the question
        is asked again.

        :param question: The question to ask.
        :param validators: The list of validators that the answer must pass.
        :return: The answer, converted to its final form by the validators.
        """
        answer = None
        while answer is None:
            answer = input(question)
            for validator in validators:
                answer, complaint = validator(answer)
                if answer is None:
                    print(complaint)
                    break
        return answer

    @staticmethod
    def non_empty(answer):
        """
        Validates that the answer is not empty.
        :return: The non-empty answer, or None.
        """
        return answer if answer != "" else None, "I need an answer. Please?"

    @staticmethod
    def is_yesno(answer):
        """
        Validates a yes/no answer.
        :return: True when the answer is 'y'; otherwise, False.
        """
        return answer.lower() == "y", ""

    @staticmethod
    def is_int(answer):
        """
        Validates that the answer can be converted to an int.
        :return: The int answer; otherwise, None.
        """
        try:
            int_answer = int(answer)
        except ValueError:
            int_answer = None
        return int_answer, f"{answer} must be a valid integer."

    @staticmethod
    def is_letter(answer):
        """
        Validates that the answer is a letter.
        :return The letter answer, converted to uppercase; otherwise, None.
        """
        return (
            answer.upper() if answer.isalpha() else None,
            f"{answer} must be a single letter.",
        )

    @staticmethod
    def is_float(answer):
        """
        Validate that the answer can be converted to a float.
        :return The float answer; otherwise, None.
        """
        try:
            float_answer = float(answer)
        except ValueError:
            float_answer = None
        return float_answer, f"{answer} must be a valid float."

    @staticmethod
    def in_range(lower, upper):
        """
        Validate that the answer is within a range. The answer must be of a type that can
        be compared to the lower and upper bounds.
        :return: The answer, if it is within the range; otherwise, None.
        """

        def _validate(answer):
            return (
                answer if lower <= answer <= upper else None,
                f"{answer} must be between {lower} and {upper}.",
            )

        return _validate
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/BatchWriteItem)
  + [CreateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable)
  + [DeleteItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteItem)
  + [DeleteTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Scan)
  + [UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)

## アクション
<a name="actions"></a>

### `BatchExecuteStatement`
<a name="dynamodb_BatchExecuteStatement_python_3_topic"></a>

次のコード例は、`BatchExecuteStatement` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class PartiQLBatchWrapper:
    """
    Encapsulates a DynamoDB resource to run PartiQL statements.
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource


    def run_partiql(self, statements, param_list):
        """
        Runs a PartiQL statement. A Boto3 resource is used even though
        `execute_statement` is called on the underlying `client` object because the
        resource transforms input and output from plain old Python objects (POPOs) to
        the DynamoDB format. If you create the client directly, you must do these
        transforms yourself.

        :param statements: The batch of PartiQL statements.
        :param param_list: The batch of PartiQL parameters that are associated with
                           each statement. This list must be in the same order as the
                           statements.
        :return: The responses returned from running the statements, if any.
        """
        try:
            output = self.dyn_resource.meta.client.batch_execute_statement(
                Statements=[
                    {"Statement": statement, "Parameters": params}
                    for statement, params in zip(statements, param_list)
                ]
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Couldn't execute batch of PartiQL statements because the table "
                    "does not exist."
                )
            else:
                logger.error(
                    "Couldn't execute batch of PartiQL statements. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return output
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_python_3_topic"></a>

次のコード例は、`BatchGetItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import decimal
import json
import logging
import os
import pprint
import time
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)
dynamodb = boto3.resource("dynamodb")

MAX_GET_SIZE = 100  # Amazon DynamoDB rejects a get batch larger than 100 items.


def do_batch_get(batch_keys):
    """
    Gets a batch of items from Amazon DynamoDB. Batches can contain keys from
    more than one table.

    When Amazon DynamoDB cannot process all items in a batch, a set of unprocessed
    keys is returned. This function uses an exponential backoff algorithm to retry
    getting the unprocessed keys until all are retrieved or the specified
    number of tries is reached.

    :param batch_keys: The set of keys to retrieve. A batch can contain at most 100
                       keys. Otherwise, Amazon DynamoDB returns an error.
    :return: The dictionary of retrieved items grouped under their respective
             table names.
    """
    tries = 0
    max_tries = 5
    sleepy_time = 1  # Start with 1 second of sleep, then exponentially increase.
    retrieved = {key: [] for key in batch_keys}
    while tries < max_tries:
        response = dynamodb.batch_get_item(RequestItems=batch_keys)
        # Collect any retrieved items and retry unprocessed keys.
        for key in response.get("Responses", []):
            retrieved[key] += response["Responses"][key]
        unprocessed = response["UnprocessedKeys"]
        if len(unprocessed) > 0:
            batch_keys = unprocessed
            unprocessed_count = sum(
                [len(batch_key["Keys"]) for batch_key in batch_keys.values()]
            )
            logger.info(
                "%s unprocessed keys returned. Sleep, then retry.", unprocessed_count
            )
            tries += 1
            if tries < max_tries:
                logger.info("Sleeping for %s seconds.", sleepy_time)
                time.sleep(sleepy_time)
                sleepy_time = min(sleepy_time * 2, 32)
        else:
            break

    return retrieved
```
+  API の詳細については、**AWS SDK for Python (Boto3) API リファレンスの「[BatchGetItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/BatchGetItem)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_python_3_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def write_batch(self, movies):
        """
        Fills an Amazon DynamoDB table with the specified data, using the Boto3
        Table.batch_writer() function to put the items in the table.
        Inside the context manager, Table.batch_writer builds a list of
        requests. On exiting the context manager, Table.batch_writer starts sending
        batches of write requests to Amazon DynamoDB and automatically
        handles chunking, buffering, and retrying.

        :param movies: The data to put in the table. Each item must contain at least
                       the keys required by the schema that was specified when the
                       table was created.
        """
        try:
            with self.table.batch_writer() as writer:
                for movie in movies:
                    writer.put_item(Item=movie)
        except ClientError as err:
            logger.error(
                "Couldn't load data into table %s. Here's why: %s: %s",
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[BatchWriteItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。

### `CreateTable`
<a name="dynamodb_CreateTable_python_3_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
映画データを格納するためのテーブルを作成します。  

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def create_table(self, table_name):
        """
        Creates an Amazon DynamoDB table that can be used to store movie data.
        The table uses the release year of the movie as the partition key and the
        title as the sort key.

        :param table_name: The name of the table to create.
        :return: The newly created table.
        """
        try:
            self.table = self.dyn_resource.create_table(
                TableName=table_name,
                KeySchema=[
                    {"AttributeName": "year", "KeyType": "HASH"},  # Partition key
                    {"AttributeName": "title", "KeyType": "RANGE"},  # Sort key
                ],
                AttributeDefinitions=[
                    {"AttributeName": "year", "AttributeType": "N"},
                    {"AttributeName": "title", "AttributeType": "S"},
                ],
                BillingMode='PAY_PER_REQUEST',
            )
            self.table.wait_until_exists()
        except ClientError as err:
            logger.error(
                "Couldn't create table %s. Here's why: %s: %s",
                table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return self.table
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_python_3_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def delete_movie(self, title, year):
        """
        Deletes a movie from the table.

        :param title: The title of the movie to delete.
        :param year: The release year of the movie to delete.
        """
        try:
            self.table.delete_item(Key={"year": year, "title": title})
        except ClientError as err:
            logger.error(
                "Couldn't delete movie %s. Here's why: %s: %s",
                title,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
項目が特定の条件を満たす場合にのみ削除されるように条件を指定できます。  

```
class UpdateQueryWrapper:
    def __init__(self, table):
        self.table = table


    def delete_underrated_movie(self, title, year, rating):
        """
        Deletes a movie only if it is rated below a specified value. By using a
        condition expression in a delete operation, you can specify that an item is
        deleted only when it meets certain criteria.

        :param title: The title of the movie to delete.
        :param year: The release year of the movie to delete.
        :param rating: The rating threshold to check before deleting the movie.
        """
        try:
            self.table.delete_item(
                Key={"year": year, "title": title},
                ConditionExpression="info.rating <= :val",
                ExpressionAttributeValues={":val": Decimal(str(rating))},
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
                logger.warning(
                    "Didn't delete %s because its rating is greater than %s.",
                    title,
                    rating,
                )
            else:
                logger.error(
                    "Couldn't delete movie %s. Here's why: %s: %s",
                    title,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DeleteItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteItem)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_python_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def delete_table(self):
        """
        Deletes the table.
        """
        try:
            self.table.delete()
            self.table = None
        except ClientError as err:
            logger.error(
                "Couldn't delete table. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[DeleteTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_python_3_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def exists(self, table_name):
        """
        Determines whether a table exists. As a side effect, stores the table in
        a member variable.

        :param table_name: The name of the table to check.
        :return: True when the table exists; otherwise, False.
        """
        try:
            table = self.dyn_resource.Table(table_name)
            table.load()
            exists = True
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                exists = False
            else:
                logger.error(
                    "Couldn't check for existence of %s. Here's why: %s: %s",
                    table_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            self.table = table
        return exists
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DescribeTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DescribeTable)」を参照してください。

### `DescribeTimeToLive`
<a name="dynamodb_DescribeTimeToLive_python_3_topic"></a>

次のコード例は、`DescribeTimeToLive` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3)を使用して既存の DynamoDB テーブルの TTL 設定を記述します。  

```
import boto3


def describe_ttl(table_name, region):
    """
    Describes TTL on an existing table, as well as a region.

    :param table_name: String representing the name of the table
    :param region: AWS Region of the table - example `us-east-1`
    :return: Time to live description.
    """
    try:
        dynamodb = boto3.resource("dynamodb", region_name=region)
        ttl_description = dynamodb.describe_time_to_live(TableName=table_name)
        print(
            f"TimeToLive for table {table_name} is status {ttl_description['TimeToLiveDescription']['TimeToLiveStatus']}"
        )

        return ttl_description
    except Exception as e:
        print(f"Error describing table: {e}")
        raise


# Enter your own table name and AWS region
describe_ttl("your-table-name", "us-east-1")
```
+  API の詳細については、「**AWS SDK for Python (Boto3) API Reference」の「[DescribeTimeToLive](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DescribeTimeToLive)」を参照してください。

### `ExecuteStatement`
<a name="dynamodb_ExecuteStatement_python_3_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class PartiQLWrapper:
    """
    Encapsulates a DynamoDB resource to run PartiQL statements.
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource


    def run_partiql(self, statement, params):
        """
        Runs a PartiQL statement. A Boto3 resource is used even though
        `execute_statement` is called on the underlying `client` object because the
        resource transforms input and output from plain old Python objects (POPOs) to
        the DynamoDB format. If you create the client directly, you must do these
        transforms yourself.

        :param statement: The PartiQL statement.
        :param params: The list of PartiQL parameters. These are applied to the
                       statement in the order they are listed.
        :return: The items returned from the statement, if any.
        """
        try:
            output = self.dyn_resource.meta.client.execute_statement(
                Statement=statement, Parameters=params
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Couldn't execute PartiQL '%s' because the table does not exist.",
                    statement,
                )
            else:
                logger.error(
                    "Couldn't execute PartiQL '%s'. Here's why: %s: %s",
                    statement,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return output
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ExecuteStatement](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_python_3_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def get_movie(self, title, year):
        """
        Gets movie data from the table for a specific movie.

        :param title: The title of the movie.
        :param year: The release year of the movie.
        :return: The data about the requested movie.
        """
        try:
            response = self.table.get_item(Key={"year": year, "title": title})
        except ClientError as err:
            logger.error(
                "Couldn't get movie %s from table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Item"]
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/GetItem)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_python_3_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def list_tables(self):
        """
        Lists the Amazon DynamoDB tables for the current account.

        :return: The list of tables.
        """
        try:
            tables = []
            for table in self.dyn_resource.tables.all():
                print(table.name)
                tables.append(table)
        except ClientError as err:
            logger.error(
                "Couldn't list tables. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return tables
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListTables](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_python_3_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def add_movie(self, title, year, plot, rating):
        """
        Adds a movie to the table.

        :param title: The title of the movie.
        :param year: The release year of the movie.
        :param plot: The plot summary of the movie.
        :param rating: The quality rating of the movie.
        """
        try:
            self.table.put_item(
                Item={
                    "year": year,
                    "title": title,
                    "info": {"plot": plot, "rating": Decimal(str(rating))},
                }
            )
        except ClientError as err:
            logger.error(
                "Couldn't add movie %s to table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)」を参照してください。

### `Query`
<a name="dynamodb_Query_python_3_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
キー条件式を使用して項目に対してクエリを実行します。  

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def query_movies(self, year):
        """
        Queries for movies that were released in the specified year.

        :param year: The year to query.
        :return: The list of movies that were released in the specified year.
        """
        try:
            response = self.table.query(KeyConditionExpression=Key("year").eq(year))
        except ClientError as err:
            logger.error(
                "Couldn't query for movies released in %s. Here's why: %s: %s",
                year,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Items"]
```
項目に対してクエリを実行し、データのサブセットを返すように射影します。  

```
class UpdateQueryWrapper:
    def __init__(self, table):
        self.table = table


    def query_and_project_movies(self, year, title_bounds):
        """
        Query for movies that were released in a specified year and that have titles
        that start within a range of letters. A projection expression is used
        to return a subset of data for each movie.

        :param year: The release year to query.
        :param title_bounds: The range of starting letters to query.
        :return: The list of movies.
        """
        try:
            response = self.table.query(
                ProjectionExpression="#yr, title, info.genres, info.actors[0]",
                ExpressionAttributeNames={"#yr": "year"},
                KeyConditionExpression=(
                    Key("year").eq(year)
                    & Key("title").between(
                        title_bounds["first"], title_bounds["second"]
                    )
                ),
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ValidationException":
                logger.warning(
                    "There's a validation error. Here's the message: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Couldn't query for movies. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return response["Items"]
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_python_3_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def scan_movies(self, year_range):
        """
        Scans for movies that were released in a range of years.
        Uses a projection expression to return a subset of data for each movie.

        :param year_range: The range of years to retrieve.
        :return: The list of movies released in the specified years.
        """
        movies = []
        scan_kwargs = {
            "FilterExpression": Key("year").between(
                year_range["first"], year_range["second"]
            ),
            "ProjectionExpression": "#yr, title, info.rating",
            "ExpressionAttributeNames": {"#yr": "year"},
        }
        try:
            done = False
            start_key = None
            while not done:
                if start_key:
                    scan_kwargs["ExclusiveStartKey"] = start_key
                response = self.table.scan(**scan_kwargs)
                movies.extend(response.get("Items", []))
                start_key = response.get("LastEvaluatedKey", None)
                done = start_key is None
        except ClientError as err:
            logger.error(
                "Couldn't scan for movies. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

        return movies
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Scan](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Scan)」を参照してください。

### `UpdateItem`
<a name="dynamodb_UpdateItem_python_3_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
更新式を使用して項目を更新します。  

```
class Movies:
    """Encapsulates an Amazon DynamoDB table of movie data.

    Example data structure for a movie record in this table:
        {
            "year": 1999,
            "title": "For Love of the Game",
            "info": {
                "directors": ["Sam Raimi"],
                "release_date": "1999-09-15T00:00:00Z",
                "rating": 6.3,
                "plot": "A washed up pitcher flashes through his career.",
                "rank": 4987,
                "running_time_secs": 8220,
                "actors": [
                    "Kevin Costner",
                    "Kelly Preston",
                    "John C. Reilly"
                ]
            }
        }
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource
        # The table variable is set during the scenario in the call to
        # 'exists' if the table exists. Otherwise, it is set by 'create_table'.
        self.table = None


    def update_movie(self, title, year, rating, plot):
        """
        Updates rating and plot data for a movie in the table.

        :param title: The title of the movie to update.
        :param year: The release year of the movie to update.
        :param rating: The updated rating to the give the movie.
        :param plot: The updated plot summary to give the movie.
        :return: The fields that were updated, with their new values.
        """
        try:
            response = self.table.update_item(
                Key={"year": year, "title": title},
                UpdateExpression="set info.rating=:r, info.plot=:p",
                ExpressionAttributeValues={":r": Decimal(str(rating)), ":p": plot},
                ReturnValues="UPDATED_NEW",
            )
        except ClientError as err:
            logger.error(
                "Couldn't update movie %s in table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Attributes"]
```
算術演算を含む更新式を使用して、項目を更新します。  

```
class UpdateQueryWrapper:
    def __init__(self, table):
        self.table = table


    def update_rating(self, title, year, rating_change):
        """
        Updates the quality rating of a movie in the table by using an arithmetic
        operation in the update expression. By specifying an arithmetic operation,
        you can adjust a value in a single request, rather than first getting its
        value and then setting its new value.

        :param title: The title of the movie to update.
        :param year: The release year of the movie to update.
        :param rating_change: The amount to add to the current rating for the movie.
        :return: The updated rating.
        """
        try:
            response = self.table.update_item(
                Key={"year": year, "title": title},
                UpdateExpression="set info.rating = info.rating + :val",
                ExpressionAttributeValues={":val": Decimal(str(rating_change))},
                ReturnValues="UPDATED_NEW",
            )
        except ClientError as err:
            logger.error(
                "Couldn't update movie %s in table %s. Here's why: %s: %s",
                title,
                self.table.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Attributes"]
```
特定の条件を満たす場合にのみ、項目を更新します。  

```
class UpdateQueryWrapper:
    def __init__(self, table):
        self.table = table


    def remove_actors(self, title, year, actor_threshold):
        """
        Removes an actor from a movie, but only when the number of actors is greater
        than a specified threshold. If the movie does not list more than the threshold,
        no actors are removed.

        :param title: The title of the movie to update.
        :param year: The release year of the movie to update.
        :param actor_threshold: The threshold of actors to check.
        :return: The movie data after the update.
        """
        try:
            response = self.table.update_item(
                Key={"year": year, "title": title},
                UpdateExpression="remove info.actors[0]",
                ConditionExpression="size(info.actors) > :num",
                ExpressionAttributeValues={":num": actor_threshold},
                ReturnValues="ALL_NEW",
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
                logger.warning(
                    "Didn't update %s because it has fewer than %s actors.",
                    title,
                    actor_threshold + 1,
                )
            else:
                logger.error(
                    "Couldn't update movie %s. Here's why: %s: %s",
                    title,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response["Attributes"]
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### `UpdateTimeToLive`
<a name="dynamodb_UpdateTimeToLive_python_3_topic"></a>

次のコード例は、`UpdateTimeToLive` を使用する方法を示しています。

**SDK for Python (Boto3)**  
既存の DynamoDB テーブルの TTL を有効にします。  

```
import boto3


def enable_ttl(table_name, ttl_attribute_name):
    """
    Enables TTL on DynamoDB table for a given attribute name
        on success, returns a status code of 200
        on error, throws an exception

    :param table_name: Name of the DynamoDB table
    :param ttl_attribute_name: The name of the TTL attribute being provided to the table.
    """
    try:
        dynamodb = boto3.client("dynamodb")

        # Enable TTL on an existing DynamoDB table
        response = dynamodb.update_time_to_live(
            TableName=table_name,
            TimeToLiveSpecification={"Enabled": True, "AttributeName": ttl_attribute_name},
        )

        # In the returned response, check for a successful status code.
        if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            print("TTL has been enabled successfully.")
        else:
            print(
                f"Failed to enable TTL, status code {response['ResponseMetadata']['HTTPStatusCode']}"
            )
        return response
    except Exception as ex:
        print("Couldn't enable TTL in table %s. Here's why: %s" % (table_name, ex))
        raise


# your values
enable_ttl("your-table-name", "expireAt")
```
既存の DynamoDB テーブルの TTL を無効にします。  

```
import boto3


def disable_ttl(table_name, ttl_attribute_name):
    """
    Disables TTL on DynamoDB table for a given attribute name
        on success, returns a status code of 200
        on error, throws an exception

    :param table_name: Name of the DynamoDB table being modified
    :param ttl_attribute_name: The name of the TTL attribute being provided to the table.
    """
    try:
        dynamodb = boto3.client("dynamodb")

        # Enable TTL on an existing DynamoDB table
        response = dynamodb.update_time_to_live(
            TableName=table_name,
            TimeToLiveSpecification={"Enabled": False, "AttributeName": ttl_attribute_name},
        )

        # In the returned response, check for a successful status code.
        if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
            print("TTL has been disabled successfully.")
        else:
            print(
                f"Failed to disable TTL, status code {response['ResponseMetadata']['HTTPStatusCode']}"
            )
    except Exception as ex:
        print("Couldn't disable TTL in table %s. Here's why: %s" % (table_name, ex))
        raise


# your values
disable_ttl("your-table-name", "expireAt")
```
+  API の詳細については、「**AWS SDK for Python (Boto3) API Reference」の「[UpdateTimeToLive](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateTimeToLive)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### DAX で読み取りを高速化
<a name="dynamodb_Usage_DaxDemo_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ DAX クライアントと SDK クライアントの両方でデータを作成してテーブルに書き込みます。
+ 両方のクライアントでテーブルを取得、クエリ、スキャンし、パフォーマンスを比較します。

詳細については、「[DynamoDB Accelerator クライアントで開発する](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DAX.client.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb/TryDax#code-examples)での設定と実行の方法を確認してください。
DAX または Boto3 クライアントでテーブルを作成します。  

```
import boto3


def create_dax_table(dyn_resource=None):
    """
    Creates a DynamoDB table.

    :param dyn_resource: Either a Boto3 or DAX resource.
    :return: The newly created table.
    """
    if dyn_resource is None:
        dyn_resource = boto3.resource("dynamodb")

    table_name = "TryDaxTable"
    params = {
        "TableName": table_name,
        "KeySchema": [
            {"AttributeName": "partition_key", "KeyType": "HASH"},
            {"AttributeName": "sort_key", "KeyType": "RANGE"},
        ],
        "AttributeDefinitions": [
            {"AttributeName": "partition_key", "AttributeType": "N"},
            {"AttributeName": "sort_key", "AttributeType": "N"},
        ],
        "BillingMode": "PAY_PER_REQUEST",
    }
    table = dyn_resource.create_table(**params)
    print(f"Creating {table_name}...")
    table.wait_until_exists()
    return table


if __name__ == "__main__":
    dax_table = create_dax_table()
    print(f"Created table.")
```
テーブルにテストデータを書き込みます。  

```
import boto3


def write_data_to_dax_table(key_count, item_size, dyn_resource=None):
    """
    Writes test data to the demonstration table.

    :param key_count: The number of partition and sort keys to use to populate the
                      table. The total number of items is key_count * key_count.
    :param item_size: The size of non-key data for each test item.
    :param dyn_resource: Either a Boto3 or DAX resource.
    """
    if dyn_resource is None:
        dyn_resource = boto3.resource("dynamodb")

    table = dyn_resource.Table("TryDaxTable")
    some_data = "X" * item_size

    for partition_key in range(1, key_count + 1):
        for sort_key in range(1, key_count + 1):
            table.put_item(
                Item={
                    "partition_key": partition_key,
                    "sort_key": sort_key,
                    "some_data": some_data,
                }
            )
            print(f"Put item ({partition_key}, {sort_key}) succeeded.")


if __name__ == "__main__":
    write_key_count = 10
    write_item_size = 1000
    print(
        f"Writing {write_key_count*write_key_count} items to the table. "
        f"Each item is {write_item_size} characters."
    )
    write_data_to_dax_table(write_key_count, write_item_size)
```
DAX クライアントと Boto3 クライアントの両方について、いくつかのイテレーションの項目を取得し、それぞれに費やした時間を報告します。  

```
import argparse
import sys
import time
import amazondax
import boto3


def get_item_test(key_count, iterations, dyn_resource=None):
    """
    Gets items from the table a specified number of times. The time before the
    first iteration and the time after the last iteration are both captured
    and reported.

    :param key_count: The number of items to get from the table in each iteration.
    :param iterations: The number of iterations to run.
    :param dyn_resource: Either a Boto3 or DAX resource.
    :return: The start and end times of the test.
    """
    if dyn_resource is None:
        dyn_resource = boto3.resource("dynamodb")

    table = dyn_resource.Table("TryDaxTable")
    start = time.perf_counter()
    for _ in range(iterations):
        for partition_key in range(1, key_count + 1):
            for sort_key in range(1, key_count + 1):
                table.get_item(
                    Key={"partition_key": partition_key, "sort_key": sort_key}
                )
                print(".", end="")
                sys.stdout.flush()
    print()
    end = time.perf_counter()
    return start, end


if __name__ == "__main__":
    # pylint: disable=not-context-manager
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "endpoint_url",
        nargs="?",
        help="When specified, the DAX cluster endpoint. Otherwise, DAX is not used.",
    )
    args = parser.parse_args()

    test_key_count = 10
    test_iterations = 50
    if args.endpoint_url:
        print(
            f"Getting each item from the table {test_iterations} times, "
            f"using the DAX client."
        )
        # Use a with statement so the DAX client closes the cluster after completion.
        with amazondax.AmazonDaxClient.resource(endpoint_url=args.endpoint_url) as dax:
            test_start, test_end = get_item_test(
                test_key_count, test_iterations, dyn_resource=dax
            )
    else:
        print(
            f"Getting each item from the table {test_iterations} times, "
            f"using the Boto3 client."
        )
        test_start, test_end = get_item_test(test_key_count, test_iterations)
    print(
        f"Total time: {test_end - test_start:.4f} sec. Average time: "
        f"{(test_end - test_start)/ test_iterations}."
    )
```
DAX クライアントと Boto3 クライアントの両方について、いくつかのイテレーションのテーブルに対してクエリを実行し、それぞれに費やした時間を報告します。  

```
import argparse
import time
import sys
import amazondax
import boto3
from boto3.dynamodb.conditions import Key


def query_test(partition_key, sort_keys, iterations, dyn_resource=None):
    """
    Queries the table a specified number of times. The time before the
    first iteration and the time after the last iteration are both captured
    and reported.

    :param partition_key: The partition key value to use in the query. The query
                          returns items that have partition keys equal to this value.
    :param sort_keys: The range of sort key values for the query. The query returns
                      items that have sort key values between these two values.
    :param iterations: The number of iterations to run.
    :param dyn_resource: Either a Boto3 or DAX resource.
    :return: The start and end times of the test.
    """
    if dyn_resource is None:
        dyn_resource = boto3.resource("dynamodb")

    table = dyn_resource.Table("TryDaxTable")
    key_condition_expression = Key("partition_key").eq(partition_key) & Key(
        "sort_key"
    ).between(*sort_keys)

    start = time.perf_counter()
    for _ in range(iterations):
        table.query(KeyConditionExpression=key_condition_expression)
        print(".", end="")
        sys.stdout.flush()
    print()
    end = time.perf_counter()
    return start, end


if __name__ == "__main__":
    # pylint: disable=not-context-manager
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "endpoint_url",
        nargs="?",
        help="When specified, the DAX cluster endpoint. Otherwise, DAX is not used.",
    )
    args = parser.parse_args()

    test_partition_key = 5
    test_sort_keys = (2, 9)
    test_iterations = 100
    if args.endpoint_url:
        print(f"Querying the table {test_iterations} times, using the DAX client.")
        # Use a with statement so the DAX client closes the cluster after completion.
        with amazondax.AmazonDaxClient.resource(endpoint_url=args.endpoint_url) as dax:
            test_start, test_end = query_test(
                test_partition_key, test_sort_keys, test_iterations, dyn_resource=dax
            )
    else:
        print(f"Querying the table {test_iterations} times, using the Boto3 client.")
        test_start, test_end = query_test(
            test_partition_key, test_sort_keys, test_iterations
        )

    print(
        f"Total time: {test_end - test_start:.4f} sec. Average time: "
        f"{(test_end - test_start)/test_iterations}."
    )
```
DAX クライアントと Boto3 クライアントの両方について、いくつかのイテレーションのテーブルをスキャンし、それぞれに費やした時間を報告します。  

```
import argparse
import time
import sys
import amazondax
import boto3


def scan_test(iterations, dyn_resource=None):
    """
    Scans the table a specified number of times. The time before the
    first iteration and the time after the last iteration are both captured
    and reported.

    :param iterations: The number of iterations to run.
    :param dyn_resource: Either a Boto3 or DAX resource.
    :return: The start and end times of the test.
    """
    if dyn_resource is None:
        dyn_resource = boto3.resource("dynamodb")

    table = dyn_resource.Table("TryDaxTable")
    start = time.perf_counter()
    for _ in range(iterations):
        table.scan()
        print(".", end="")
        sys.stdout.flush()
    print()
    end = time.perf_counter()
    return start, end


if __name__ == "__main__":
    # pylint: disable=not-context-manager
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "endpoint_url",
        nargs="?",
        help="When specified, the DAX cluster endpoint. Otherwise, DAX is not used.",
    )
    args = parser.parse_args()

    test_iterations = 100
    if args.endpoint_url:
        print(f"Scanning the table {test_iterations} times, using the DAX client.")
        # Use a with statement so the DAX client closes the cluster after completion.
        with amazondax.AmazonDaxClient.resource(endpoint_url=args.endpoint_url) as dax:
            test_start, test_end = scan_test(test_iterations, dyn_resource=dax)
    else:
        print(f"Scanning the table {test_iterations} times, using the Boto3 client.")
        test_start, test_end = scan_test(test_iterations)
    print(
        f"Total time: {test_end - test_start:.4f} sec. Average time: "
        f"{(test_end - test_start)/test_iterations}."
    )
```
テーブルを削除する。  

```
import boto3


def delete_dax_table(dyn_resource=None):
    """
    Deletes the demonstration table.

    :param dyn_resource: Either a Boto3 or DAX resource.
    """
    if dyn_resource is None:
        dyn_resource = boto3.resource("dynamodb")

    table = dyn_resource.Table("TryDaxTable")
    table.delete()

    print(f"Deleting {table.name}...")
    table.wait_until_not_exists()


if __name__ == "__main__":
    delete_dax_table()
    print("Table deleted!")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable)
  + [DeleteTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteTable)
  + [GetItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Scan)

### 複数の値を 1 つの属性と比較する
<a name="dynamodb_Scenario_CompareMultipleValues_python_3_topic"></a>

次のコード例は、DynamoDB で複数の値を 1 つの属性と比較する方法を示しています。
+ IN 演算子を使用して、複数の値を 1 つの属性と比較します。
+ IN 演算子を複数の OR 条件と比較します。
+ IN の使用によるパフォーマンスと式の複雑さのメリットを理解します。

**SDK for Python (Boto3)**  
を使用して、複数の値を単一の属性と比較します AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Attr, Key
from typing import Any, Dict, List, Optional


def compare_multiple_values(
    table_name: str,
    attribute_name: str,
    values_list: List[Any],
    partition_key_name: Optional[str] = None,
    partition_key_value: Optional[str] = None,
) -> Dict[str, Any]:
    """
    Query or scan a DynamoDB table to find items where an attribute matches any value from a list.

    This function demonstrates the use of the IN operator to compare a single attribute
    against multiple possible values, which is more efficient than using multiple OR conditions.

    Args:
        table_name (str): The name of the DynamoDB table.
        attribute_name (str): The name of the attribute to compare against the values list.
        values_list (List[Any]): List of values to compare the attribute against.
        partition_key_name (Optional[str]): The name of the partition key attribute for query operations.
        partition_key_value (Optional[str]): The value of the partition key to query.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the matching items.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Create the filter expression using the is_in method
    filter_expression = Attr(attribute_name).is_in(values_list)

    # If partition key is provided, perform a query operation
    if partition_key_name and partition_key_value:
        key_condition = Key(partition_key_name).eq(partition_key_value)
        response = table.query(
            KeyConditionExpression=key_condition, FilterExpression=filter_expression
        )
    else:
        # Otherwise, perform a scan operation
        response = table.scan(FilterExpression=filter_expression)

    # Handle pagination if there are more results
    items = response.get("Items", [])
    while "LastEvaluatedKey" in response:
        if partition_key_name and partition_key_value:
            response = table.query(
                KeyConditionExpression=key_condition,
                FilterExpression=filter_expression,
                ExclusiveStartKey=response["LastEvaluatedKey"],
            )
        else:
            response = table.scan(
                FilterExpression=filter_expression, ExclusiveStartKey=response["LastEvaluatedKey"]
            )
        items.extend(response.get("Items", []))

    # Return the complete result
    return {"Items": items, "Count": len(items)}


def compare_with_or_conditions(
    table_name: str,
    attribute_name: str,
    values_list: List[Any],
    partition_key_name: Optional[str] = None,
    partition_key_value: Optional[str] = None,
) -> Dict[str, Any]:
    """
    Alternative implementation using multiple OR conditions instead of the IN operator.

    This function is provided for comparison to show why using the IN operator is preferable.
    With many values, this approach becomes verbose and less efficient.

    Args:
        table_name (str): The name of the DynamoDB table.
        attribute_name (str): The name of the attribute to compare against the values list.
        values_list (List[Any]): List of values to compare the attribute against.
        partition_key_name (Optional[str]): The name of the partition key attribute for query operations.
        partition_key_value (Optional[str]): The value of the partition key to query.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the matching items.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Create a filter expression with multiple OR conditions
    filter_expression = None
    for value in values_list:
        condition = Attr(attribute_name).eq(value)
        if filter_expression is None:
            filter_expression = condition
        else:
            filter_expression = filter_expression | condition

    # If partition key is provided, perform a query operation
    if partition_key_name and partition_key_value and filter_expression:
        key_condition = Key(partition_key_name).eq(partition_key_value)
        response = table.query(
            KeyConditionExpression=key_condition, FilterExpression=filter_expression
        )
    elif filter_expression:
        # Otherwise, perform a scan operation
        response = table.scan(FilterExpression=filter_expression)
    else:
        # Return empty response if no values provided
        return {"Items": [], "Count": 0}

    # Handle pagination if there are more results
    items = response.get("Items", [])
    while "LastEvaluatedKey" in response:
        if partition_key_name and partition_key_value:
            response = table.query(
                KeyConditionExpression=key_condition,
                FilterExpression=filter_expression,
                ExclusiveStartKey=response["LastEvaluatedKey"],
            )
        else:
            response = table.scan(
                FilterExpression=filter_expression, ExclusiveStartKey=response["LastEvaluatedKey"]
            )
        items.extend(response.get("Items", []))

    # Return the complete result
    return {"Items": items, "Count": len(items)}
```
複数の値と を比較する使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use the compare_multiple_values function."""
    # Example parameters
    table_name = "Products"
    attribute_name = "Category"
    values_list = ["Electronics", "Computers", "Accessories"]

    print(f"Searching for products in any of these categories: {values_list}")

    # Using the IN operator (recommended approach)
    print("\nApproach 1: Using the IN operator")
    response = compare_multiple_values(
        table_name=table_name, attribute_name=attribute_name, values_list=values_list
    )

    print(f"Found {response['Count']} products in the specified categories")

    # Using multiple OR conditions (alternative approach)
    print("\nApproach 2: Using multiple OR conditions")
    response2 = compare_with_or_conditions(
        table_name=table_name, attribute_name=attribute_name, values_list=values_list
    )

    print(f"Found {response2['Count']} products in the specified categories")

    # Example with a query operation
    print("\nQuerying a specific manufacturer's products in multiple categories")
    partition_key_name = "Manufacturer"
    partition_key_value = "Acme"

    response3 = compare_multiple_values(
        table_name=table_name,
        attribute_name=attribute_name,
        values_list=values_list,
        partition_key_name=partition_key_name,
        partition_key_value=partition_key_value,
    )

    print(f"Found {response3['Count']} Acme products in the specified categories")

    # Explain the benefits of using the IN operator
    print("\nBenefits of using the IN operator:")
    print("1. More concise expression compared to multiple OR conditions")
    print("2. Better readability and maintainability")
    print("3. Potentially better performance with large value lists")
    print("4. Simpler code that's less prone to errors")
    print("5. Easier to modify when adding or removing values")
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Scan)

### 項目の TTL を条件付きで更新する
<a name="dynamodb_UpdateItemConditionalTTL_python_3_topic"></a>

以下のコード例は、項目の TTL を条件付きで更新する方法を示しています。

**SDK for Python (Boto3)**  
条件を指定して、テーブル内の既存の DynamoDB 項目の TTL を更新します。  

```
from datetime import datetime, timedelta

import boto3
from botocore.exceptions import ClientError


def update_dynamodb_item_ttl(table_name, region, primary_key, sort_key, ttl_attribute):
    """
    Updates an existing record in a DynamoDB table with a new or updated TTL attribute.

    :param table_name: Name of the DynamoDB table
    :param region: AWS Region of the table - example `us-east-1`
    :param primary_key: one attribute known as the partition key.
    :param sort_key: Also known as a range attribute.
    :param ttl_attribute: name of the TTL attribute in the target DynamoDB table
    :return:
    """
    try:
        dynamodb = boto3.resource("dynamodb", region_name=region)
        table = dynamodb.Table(table_name)

        # Generate updated TTL in epoch second format
        updated_expiration_time = int((datetime.now() + timedelta(days=90)).timestamp())

        # Define the update expression for adding/updating a new attribute
        update_expression = "SET newAttribute = :val1"

        # Define the condition expression for checking if 'expireAt' is not expired
        condition_expression = "expireAt > :val2"

        # Define the expression attribute values
        expression_attribute_values = {":val1": ttl_attribute, ":val2": updated_expiration_time}

        response = table.update_item(
            Key={"primaryKey": primary_key, "sortKey": sort_key},
            UpdateExpression=update_expression,
            ConditionExpression=condition_expression,
            ExpressionAttributeValues=expression_attribute_values,
        )

        print("Item updated successfully.")
        return response["ResponseMetadata"]["HTTPStatusCode"]  # Ideally a 200 OK
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            print("Condition check failed: Item's 'expireAt' is expired.")
        else:
            print(f"Error updating item: {e}")
    except Exception as e:
        print(f"Error updating item: {e}")


# replace with your values
update_dynamodb_item_ttl(
    "your-table-name",
    "us-east-1",
    "your-partition-key-value",
    "your-sort-key-value",
    "your-ttl-attribute-value",
)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### 式演算子をカウントする
<a name="dynamodb_Scenario_ExpressionOperatorCounting_python_3_topic"></a>

次のコード例は、DynamoDB で式演算子をカウントする方法を示しています。
+ DynamoDB の演算子の制限数が 300 であることを理解します。
+ 複雑な式での演算子をカウントする。
+ 式を最適化して制限内に収まるようにします。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3)を使用して式演算子のカウントをデモンストレーションします。  

```
import boto3
from botocore.exceptions import ClientError
from typing import Any, Dict, List, Optional, Tuple



def create_complex_filter_expression(
    attribute_name: str, values: List[Any], use_or: bool = True
) -> Tuple[str, Dict[str, Any], Dict[str, str], int]:
    """
    Create a complex filter expression with multiple conditions.

    This function demonstrates how to build a complex filter expression
    and count the number of operators used.

    Args:
        attribute_name (str): The name of the attribute to filter on.
        values (List[Any]): List of values to compare against.
        use_or (bool, optional): Whether to use OR between conditions. Defaults to True.

    Returns:
        Tuple[str, Dict[str, Any], Dict[str, str], int]: A tuple containing:
            - The filter expression string
            - Expression attribute values
            - Expression attribute names
            - The number of operators used
    """
    if not values:
        return "", {}, {}, 0

    # Initialize expression components
    filter_expression = ""
    expression_attribute_values = {}
    expression_attribute_names = {"#attr": attribute_name}
    operator_count = 0

    # Build the filter expression
    for i, value in enumerate(values):
        value_placeholder = f":val{i}"
        expression_attribute_values[value_placeholder] = value

        if i > 0:
            # Add OR or AND operator between conditions
            filter_expression += " OR " if use_or else " AND "
            operator_count += 1  # Count the OR/AND operator

        # Add the condition
        filter_expression += f"#attr = {value_placeholder}"
        operator_count += 1  # Count the = operator

    return (
        filter_expression,
        expression_attribute_values,
        expression_attribute_names,
        operator_count,
    )


def create_nested_filter_expression(
    depth: int, conditions_per_level: int
) -> Tuple[str, Dict[str, Any], Dict[str, str], int]:
    """
    Create a deeply nested filter expression with multiple conditions.

    This function demonstrates how to build a complex nested filter expression
    and count the number of operators used.

    Args:
        depth (int): The depth of nesting.
        conditions_per_level (int): Number of conditions at each level.

    Returns:
        Tuple[str, Dict[str, Any], Dict[str, str], int]: A tuple containing:
            - The filter expression string
            - Expression attribute values
            - Expression attribute names
            - The number of operators used
    """
    if depth <= 0 or conditions_per_level <= 0:
        return "", {}, {}, 0

    # Initialize expression components
    expression_attribute_values = {}
    expression_attribute_names = {}
    operator_count = 0

    def build_nested_expression(current_depth: int, prefix: str) -> str:
        nonlocal operator_count

        if current_depth <= 0:
            return ""

        # Build conditions at this level
        conditions = []
        for i in range(conditions_per_level):
            attr_name = f"attr{prefix}_{i}"
            attr_placeholder = f"#attr{prefix}_{i}"
            val_placeholder = f":val{prefix}_{i}"

            expression_attribute_names[attr_placeholder] = attr_name
            expression_attribute_values[val_placeholder] = i

            conditions.append(f"{attr_placeholder} = {val_placeholder}")
            operator_count += 1  # Count the = operator

        # Join conditions with AND
        level_expression = " AND ".join(conditions)
        operator_count += max(0, len(conditions) - 1)  # Count the AND operators

        # If not at the deepest level, add nested expressions
        if current_depth > 1:
            nested_expr = build_nested_expression(current_depth - 1, f"{prefix}_{current_depth}")
            if nested_expr:
                level_expression = f"({level_expression}) OR ({nested_expr})"
                operator_count += 1  # Count the OR operator

        return level_expression

    # Build the expression starting from the top level
    filter_expression = build_nested_expression(depth, "1")

    return (
        filter_expression,
        expression_attribute_values,
        expression_attribute_names,
        operator_count,
    )


def count_operators_in_update_expression(update_expression: str) -> int:
    """
    Count the number of operators in an update expression.

    This function demonstrates how to count operators in an update expression
    based on DynamoDB's rules.

    Args:
        update_expression (str): The update expression to analyze.

    Returns:
        int: The number of operators in the expression.
    """
    operator_count = 0

    # Count SET operations
    if "SET" in update_expression:
        set_section = (
            update_expression.split("SET")[1].split("REMOVE")[0].split("ADD")[0].split("DELETE")[0]
        )

        # Count assignment operators (=)
        operator_count += set_section.count("=")

        # Count arithmetic operators (+, -)
        operator_count += set_section.count("+")
        operator_count += set_section.count("-")

        # Count list_append function calls (each counts as 1 operator)
        operator_count += set_section.lower().count("list_append")

        # Count if_not_exists function calls (each counts as 1 operator)
        operator_count += set_section.lower().count("if_not_exists")

    # Count REMOVE operations (no additional operators)

    # Count ADD operations (each ADD counts as 1 operator)
    if "ADD" in update_expression:
        add_section = (
            update_expression.split("ADD")[1].split("DELETE")[0].split("SET")[0].split("REMOVE")[0]
        )
        operator_count += add_section.count(",") + 1

    # Count DELETE operations (each DELETE counts as 1 operator)
    if "DELETE" in update_expression:
        delete_section = (
            update_expression.split("DELETE")[1].split("SET")[0].split("ADD")[0].split("REMOVE")[0]
        )
        operator_count += delete_section.count(",") + 1

    return operator_count


def count_operators_in_condition_expression(condition_expression: str) -> int:
    """
    Count the number of operators in a condition expression.

    This function demonstrates how to count operators in a condition expression
    based on DynamoDB's rules.

    Args:
        condition_expression (str): The condition expression to analyze.

    Returns:
        int: The number of operators in the expression.
    """
    operator_count = 0

    # Count comparison operators
    comparison_operators = ["=", "<>", "<", "<=", ">", ">="]
    for op in comparison_operators:
        operator_count += condition_expression.count(op)

    # Count logical operators
    operator_count += condition_expression.upper().count(" AND ")
    operator_count += condition_expression.upper().count(" OR ")
    operator_count += condition_expression.upper().count("NOT ")

    # Count BETWEEN operator (counts as 2: BETWEEN + AND)
    between_count = condition_expression.upper().count(" BETWEEN ")
    operator_count += between_count * 2

    # Count IN operator (counts as 1 regardless of number of values)
    operator_count += condition_expression.upper().count(" IN ")

    # Count functions (each counts as 1 operator)
    functions = [
        "attribute_exists",
        "attribute_not_exists",
        "attribute_type",
        "begins_with",
        "contains",
        "size",
    ]
    for func in functions:
        operator_count += condition_expression.lower().count(func)

    return operator_count


# Note: This function is for demonstration purposes only and should be called from example_usage()
# It's not meant to be used directly as a test function
def _test_expression_limit(
    table_name: str, key: Dict[str, Any], operator_count: int, attribute_name: str = "TestAttribute"
) -> Tuple[bool, Optional[str]]:
    """
    Test if an expression with a specific number of operators exceeds the limit.

    This function demonstrates how to test the 300 operator limit by creating
    an expression with a specified number of operators.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        operator_count (int): The number of operators to include in the expression.
        attribute_name (str, optional): The name of the attribute to update. Defaults to "TestAttribute".

    Returns:
        Tuple[bool, Optional[str]]: A tuple containing:
            - A boolean indicating if the operation succeeded
            - The error message if it failed, None otherwise
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Create an update expression with the specified number of operators
    update_expression = f"SET #{attribute_name} = :val0"
    expression_attribute_names = {f"#{attribute_name}": attribute_name}
    expression_attribute_values = {":val0": 0}

    # Add additional SET operations to reach the desired operator count
    # Each assignment adds 1 operator
    for i in range(1, operator_count):
        attr_name = f"{attribute_name}{i}"
        attr_placeholder = f"#attr{i}"
        val_placeholder = f":val{i}"

        update_expression += f", {attr_placeholder} = {val_placeholder}"
        expression_attribute_names[attr_placeholder] = attr_name
        expression_attribute_values[val_placeholder] = i

    try:
        # Attempt the update operation
        table.update_item(
            Key=key,
            UpdateExpression=update_expression,
            ExpressionAttributeNames=expression_attribute_names,
            ExpressionAttributeValues=expression_attribute_values,
        )
        return True, None
    except ClientError as e:
        error_message = e.response["Error"]["Message"]

        if "expression contains too many operators" in error_message.lower():
            return False, error_message
        else:
            # Other error occurred
            raise
```
でカウントする式演算子の使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use the expression operator counting functions."""

    print("Example 1: Creating a complex filter expression with multiple conditions")
    attribute_name = "Status"
    values = ["Active", "Pending", "Processing", "Shipped", "Delivered"]

    filter_expr, expr_attr_vals, expr_attr_names, op_count = create_complex_filter_expression(
        attribute_name=attribute_name, values=values, use_or=True
    )

    print(f"Filter Expression: {filter_expr}")
    print(f"Expression Attribute Values: {expr_attr_vals}")
    print(f"Expression Attribute Names: {expr_attr_names}")
    print(f"Operator Count: {op_count}")

    print("\nExample 2: Creating a nested filter expression")
    nested_expr, nested_vals, nested_names, nested_count = create_nested_filter_expression(
        depth=3, conditions_per_level=2
    )

    print(f"Nested Filter Expression: {nested_expr}")
    print(f"Operator Count: {nested_count}")

    print("\nExample 3: Counting operators in an update expression")
    update_expression = "SET #name = :name, #age = :age + :increment, #address.#city = :city, #status = if_not_exists(#status, :default_status) REMOVE #old_field ADD #counter :value DELETE #set_attr :set_val"
    update_op_count = count_operators_in_update_expression(update_expression)

    print(f"Update Expression: {update_expression}")
    print(f"Operator Count: {update_op_count}")

    print("\nExample 4: Counting operators in a condition expression")
    condition_expression = "(#status = :active OR #status = :pending) AND #price BETWEEN :min_price AND :max_price AND attribute_exists(#category) AND NOT (#stock <= :min_stock)"
    condition_op_count = count_operators_in_condition_expression(condition_expression)

    print(f"Condition Expression: {condition_expression}")
    print(f"Operator Count: {condition_op_count}")

    print("\nExample 5: Testing the 300 operator limit")

    # This is just for demonstration - in a real application, you would use your actual table
    # Note: This function is renamed to _test_expression_limit to avoid pytest trying to run it
    print("In a real application, you would test with _test_expression_limit function")
    print("Expression with 250 operators would be under the limit")
    print("Expression with 350 operators would exceed the 300 operator limit")

    print("\nOperator Counting Rules in DynamoDB:")
    print("1. Comparison Operators (=, <>, <, <=, >, >=): 1 operator each")
    print("2. Logical Operators (AND, OR, NOT): 1 operator each")
    print("3. BETWEEN: 2 operators (BETWEEN + AND)")
    print("4. IN: 1 operator (regardless of number of values)")
    print("5. Functions (attribute_exists, begins_with, etc.): 1 operator each")
    print("6. Arithmetic Operators (+, -): 1 operator each")
    print("7. SET assignments (=): 1 operator each")
    print("8. ADD and DELETE operations: 1 operator each")

    print("\nStrategies for Working Within the 300 Operator Limit:")
    print("1. Break operations into multiple requests")
    print("2. Use DynamoDB Transactions for complex operations")
    print("3. Optimize data model to reduce query complexity")
    print("4. Use application-side filtering for less critical filters")
    print("5. Consider using IN operator instead of multiple OR conditions")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### COVID-19 データを追跡する REST API を作成する
<a name="cross_ApiGatewayDataTracker_python_3_topic"></a>

次のコード例は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートする REST API を作成する方法を示しています。

**SDK for Python (Boto3)**  
 で AWS Chalice を使用して AWS SDK for Python (Boto3) 、Amazon API Gateway AWS Lambda、および Amazon DynamoDB を使用するサーバーレス REST API を作成する方法を示します。REST API は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートします。以下ではその方法を説明しています。  
+  AWS Chalice を使用して、API Gateway 経由で送信される REST リクエストを処理するために呼び出される Lambda 関数のルートを定義します。
+ Lambda 関数を使用して、DynamoDB テーブルにデータを取得して保存し、REST リクエストを処理します。
+  AWS CloudFormation テンプレートでテーブル構造とセキュリティロールリソースを定義します。
+  AWS Chalice と CloudFormation を使用して、必要なすべてのリソースをパッケージ化してデプロイします。
+ CloudFormation を使用して、作成されたすべてのリソースをクリーンアップします。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_covid-19_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ CloudFormation
+ DynamoDB
+ Lambda

### メッセンジャーアプリケーションを作成する
<a name="cross_StepFunctionsMessenger_python_3_topic"></a>

次のコード例は、データベーステーブルからメッセージレコードを取得する AWS Step Functions メッセンジャーアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3) で を使用して AWS Step Functions 、Amazon DynamoDB テーブルからメッセージレコードを取得し、Amazon Simple Queue Service (Amazon SQS) で送信するメッセンジャーアプリケーションを作成する方法を示します。ステートマシンは AWS Lambda 関数と統合して、未送信メッセージがないかデータベースをスキャンします。  
+ Amazon DynamoDB テーブルからメッセージレコードを取得および更新するステートマシンを作成します。
+ ステートマシンの定義を更新して、Amazon Simple Queue Service (Amazon SQS) にもメッセージを送信します。
+ ステートマシンの実行を開始および停止します。
+ サービス統合を使用して、ステートマシンから Lambda、DynamoDB、および Amazon SQS に接続します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/stepfunctions_messenger) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SQS
+ ステップ関数

### ウォームスループットを有効にしたテーブルを作成する
<a name="dynamodb_CreateTableWarmThroughput_python_3_topic"></a>

次のコード例は、ウォームスループットを有効にしたテーブルを作成する方法を示しています。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3)を使用してウォームスループット設定を含む DynamoDB テーブルを作成します。  

```
from boto3 import client
from botocore.exceptions import ClientError


def create_dynamodb_table_warm_throughput(
    table_name,
    partition_key,
    sort_key,
    misc_key_attr,
    non_key_attr,
    table_provisioned_read_units,
    table_provisioned_write_units,
    table_warm_reads,
    table_warm_writes,
    gsi_name,
    gsi_provisioned_read_units,
    gsi_provisioned_write_units,
    gsi_warm_reads,
    gsi_warm_writes,
    region_name="us-east-1",
):
    """
    Creates a DynamoDB table with a warm throughput setting configured.

    :param table_name: The name of the table to be created.
    :param partition_key: The partition key for the table being created.
    :param sort_key: The sort key for the table being created.
    :param misc_key_attr: A miscellaneous key attribute for the table being created.
    :param non_key_attr: A non-key attribute for the table being created.
    :param table_provisioned_read_units: The newly created table's provisioned read capacity units.
    :param table_provisioned_write_units: The newly created table's provisioned write capacity units.
    :param table_warm_reads: The read units per second setting for the table's warm throughput.
    :param table_warm_writes: The write units per second setting for the table's warm throughput.
    :param gsi_name: The name of the Global Secondary Index (GSI) to be created on the table.
    :param gsi_provisioned_read_units: The configured Global Secondary Index (GSI) provisioned read capacity units.
    :param gsi_provisioned_write_units: The configured Global Secondary Index (GSI) provisioned write capacity units.
    :param gsi_warm_reads: The read units per second setting for the Global Secondary Index (GSI)'s warm throughput.
    :param gsi_warm_writes: The write units per second setting for the Global Secondary Index (GSI)'s warm throughput.
    :param region_name: The AWS Region name to target. defaults to us-east-1
    """
    try:
        ddb = client("dynamodb", region_name=region_name)

        # Define the table attributes
        attribute_definitions = [
            {"AttributeName": partition_key, "AttributeType": "S"},
            {"AttributeName": sort_key, "AttributeType": "S"},
            {"AttributeName": misc_key_attr, "AttributeType": "N"},
        ]

        # Define the table key schema
        key_schema = [
            {"AttributeName": partition_key, "KeyType": "HASH"},
            {"AttributeName": sort_key, "KeyType": "RANGE"},
        ]

        # Define the provisioned throughput for the table
        provisioned_throughput = {
            "ReadCapacityUnits": table_provisioned_read_units,
            "WriteCapacityUnits": table_provisioned_write_units,
        }

        # Define the global secondary index
        gsi_key_schema = [
            {"AttributeName": sort_key, "KeyType": "HASH"},
            {"AttributeName": misc_key_attr, "KeyType": "RANGE"},
        ]
        gsi_projection = {"ProjectionType": "INCLUDE", "NonKeyAttributes": [non_key_attr]}
        gsi_provisioned_throughput = {
            "ReadCapacityUnits": gsi_provisioned_read_units,
            "WriteCapacityUnits": gsi_provisioned_write_units,
        }
        gsi_warm_throughput = {
            "ReadUnitsPerSecond": gsi_warm_reads,
            "WriteUnitsPerSecond": gsi_warm_writes,
        }
        global_secondary_indexes = [
            {
                "IndexName": gsi_name,
                "KeySchema": gsi_key_schema,
                "Projection": gsi_projection,
                "ProvisionedThroughput": gsi_provisioned_throughput,
                "WarmThroughput": gsi_warm_throughput,
            }
        ]

        # Define the warm throughput for the table
        warm_throughput = {
            "ReadUnitsPerSecond": table_warm_reads,
            "WriteUnitsPerSecond": table_warm_writes,
        }

        # Create the DynamoDB client and create the table
        response = ddb.create_table(
            TableName=table_name,
            AttributeDefinitions=attribute_definitions,
            KeySchema=key_schema,
            ProvisionedThroughput=provisioned_throughput,
            GlobalSecondaryIndexes=global_secondary_indexes,
            WarmThroughput=warm_throughput,
        )

        print(response)
        return response
    except ClientError as e:
        print(f"Error creating table: {e}")
        raise e
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/CreateTable)」を参照してください。

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_python_3_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して AWS SDK for Python (Boto3) Amazon DynamoDB の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信する REST サービスを作成する方法を示します。この例では、Flask ウェブフレームワークを使用して HTTP ルーティングを処理し、React ウェブページと統合して完全に機能するウェブアプリケーションを提供しています。  
+ と統合する Flask REST サービスを構築します AWS のサービス。
+ DynamoDB テーブルに保存されている作業項目の読み取り、書き込み、更新を行います。
+ Amazon SES を使用して作業項目のレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、GitHub の「[AWS コード例のレポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/dynamodb_item_tracker)」で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### WebSocket チャットアプリケーションを作成する
<a name="cross_ApiGatewayWebsocketChat_python_3_topic"></a>

次のコード例は、Amazon API Gateway 上に構築された WebSocket API によって提供されるチャットアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon API Gateway V2 AWS SDK for Python (Boto3) で を使用して、 AWS Lambda および Amazon DynamoDB と統合する WebSocket API を作成する方法を示します。  
+ API Gateway で提供される WebSocket API を作成します。
+ DynamoDB に接続を保存し、他のチャット参加者にメッセージを投稿する Lambda ハンドラを定義します。
+ WebSocket チャットアプリケーションに接続し、WebSockets パッケージを使用してメッセージを送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_websocket_chat) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

### TTL を含む項目を作成する
<a name="dynamodb_PutItemTTL_python_3_topic"></a>

次のコード例は、TTL を含む項目の作成方法を示しています。

**SDK for Python (Boto3)**  

```
from datetime import datetime, timedelta

import boto3


def create_dynamodb_item(table_name, region, primary_key, sort_key):
    """
    Creates a DynamoDB item with an attached expiry attribute.

    :param table_name: Table name for the boto3 resource to target when creating an item
    :param region: string representing the AWS region. Example: `us-east-1`
    :param primary_key: one attribute known as the partition key.
    :param sort_key: Also known as a range attribute.
    :return: Void (nothing)
    """
    try:
        dynamodb = boto3.resource("dynamodb", region_name=region)
        table = dynamodb.Table(table_name)

        # Get the current time in epoch second format
        current_time = int(datetime.now().timestamp())

        # Calculate the expiration time (90 days from now) in epoch second format
        expiration_time = int((datetime.now() + timedelta(days=90)).timestamp())

        item = {
            "primaryKey": primary_key,
            "sortKey": sort_key,
            "creationDate": current_time,
            "expireAt": expiration_time,
        }
        response = table.put_item(Item=item)

        print("Item created successfully.")
        return response
    except Exception as e:
        print(f"Error creating item: {e}")
        raise e


# Use your own values
create_dynamodb_item(
    "your-table-name", "us-west-2", "your-partition-key-value", "your-sort-key-value"
)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)」を参照してください。

### 高度なクエリオペレーションを実行する
<a name="dynamodb_Scenario_AdvancedQueryTechniques_python_3_topic"></a>

次のコード例は、DynamoDB で高度なクエリオペレーションを実行する方法を示しています。
+ さまざまなフィルタリングと条件の手法を使用してテーブルをクエリします。
+ 大きな結果セットのページ分割を実装します。
+ 代替アクセスパターンにはグローバルセカンダリインデックスを使用します。
+ アプリケーション要件に基づいて整合性コントロールを適用します。

**SDK for Python (Boto3)**  
を使用した強力な整合性のある読み取りによるクエリ AWS SDK for Python (Boto3)。  

```
import time

import boto3
from boto3.dynamodb.conditions import Key


def query_with_consistent_read(
    table_name,
    partition_key_name,
    partition_key_value,
    sort_key_name=None,
    sort_key_value=None,
    consistent_read=True,
):
    """
    Query a DynamoDB table with the option for strongly consistent reads.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str, optional): The name of the sort key attribute.
        sort_key_value (str, optional): The value of the sort key to query.
        consistent_read (bool, optional): Whether to use strongly consistent reads. Defaults to True.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    if sort_key_name and sort_key_value:
        key_condition = key_condition & Key(sort_key_name).eq(sort_key_value)

    # Perform the query with the consistent read option
    response = table.query(KeyConditionExpression=key_condition, ConsistentRead=consistent_read)

    return response
```
でグローバルセカンダリインデックスを使用してクエリを実行します AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Key


def query_table(table_name, partition_key_name, partition_key_value):
    """
    Query a DynamoDB table using its primary key.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Perform the query on the table's primary key
    response = table.query(KeyConditionExpression=Key(partition_key_name).eq(partition_key_value))

    return response


def query_gsi(table_name, index_name, partition_key_name, partition_key_value):
    """
    Query a Global Secondary Index (GSI) on a DynamoDB table.

    Args:
        table_name (str): The name of the DynamoDB table.
        index_name (str): The name of the Global Secondary Index.
        partition_key_name (str): The name of the GSI's partition key attribute.
        partition_key_value (str): The value of the GSI's partition key to query.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Perform the query on the GSI
    response = table.query(
        IndexName=index_name, KeyConditionExpression=Key(partition_key_name).eq(partition_key_value)
    )

    return response
```
を使用してページ分割でクエリを実行します AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Key


def query_with_pagination(
    table_name, partition_key_name, partition_key_value, page_size=25, max_pages=None
):
    """
    Query a DynamoDB table with pagination to handle large result sets.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        page_size (int, optional): The number of items to return per page. Defaults to 25.
        max_pages (int, optional): The maximum number of pages to retrieve. If None, retrieves all pages.

    Returns:
        list: All items retrieved from the query across all pages.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Initialize variables for pagination
    last_evaluated_key = None
    page_count = 0
    all_items = []

    # Paginate through the results
    while True:
        # Check if we've reached the maximum number of pages
        if max_pages is not None and page_count >= max_pages:
            break

        # Prepare the query parameters
        query_params = {
            "KeyConditionExpression": Key(partition_key_name).eq(partition_key_value),
            "Limit": page_size,
        }

        # Add the ExclusiveStartKey if we have a LastEvaluatedKey from a previous query
        if last_evaluated_key:
            query_params["ExclusiveStartKey"] = last_evaluated_key

        # Execute the query
        response = table.query(**query_params)

        # Process the current page of results
        items = response.get("Items", [])
        all_items.extend(items)

        # Update pagination tracking
        page_count += 1

        # Get the LastEvaluatedKey for the next page, if any
        last_evaluated_key = response.get("LastEvaluatedKey")

        # If there's no LastEvaluatedKey, we've reached the end of the results
        if not last_evaluated_key:
            break

    return all_items


def query_with_pagination_generator(
    table_name, partition_key_name, partition_key_value, page_size=25
):
    """
    Query a DynamoDB table with pagination using a generator to handle large result sets.
    This approach is memory-efficient as it yields one page at a time.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        page_size (int, optional): The number of items to return per page. Defaults to 25.

    Yields:
        tuple: A tuple containing (items, page_number, last_page) where:
            - items is a list of items for the current page
            - page_number is the current page number (starting from 1)
            - last_page is a boolean indicating if this is the last page
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Initialize variables for pagination
    last_evaluated_key = None
    page_number = 0

    # Paginate through the results
    while True:
        # Prepare the query parameters
        query_params = {
            "KeyConditionExpression": Key(partition_key_name).eq(partition_key_value),
            "Limit": page_size,
        }

        # Add the ExclusiveStartKey if we have a LastEvaluatedKey from a previous query
        if last_evaluated_key:
            query_params["ExclusiveStartKey"] = last_evaluated_key

        # Execute the query
        response = table.query(**query_params)

        # Get the current page of results
        items = response.get("Items", [])
        page_number += 1

        # Get the LastEvaluatedKey for the next page, if any
        last_evaluated_key = response.get("LastEvaluatedKey")

        # Determine if this is the last page
        is_last_page = last_evaluated_key is None

        # Yield the current page of results
        yield (items, page_number, is_last_page)

        # If there's no LastEvaluatedKey, we've reached the end of the results
        if is_last_page:
            break
```
を使用して複雑なフィルターでクエリを実行します AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Attr, Key


def query_with_complex_filter(
    table_name,
    partition_key_name,
    partition_key_value,
    min_rating=None,
    status_list=None,
    max_price=None,
):
    """
    Query a DynamoDB table with a complex filter expression.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        min_rating (float, optional): Minimum rating value for filtering.
        status_list (list, optional): List of status values to include.
        max_price (float, optional): Maximum price value for filtering.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Start with the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Initialize the filter expression and expression attribute values
    filter_expression = None
    expression_attribute_values = {}

    # Build the filter expression based on provided parameters
    if min_rating is not None:
        filter_expression = Attr("rating").gte(min_rating)
        expression_attribute_values[":min_rating"] = min_rating

    if status_list and len(status_list) > 0:
        status_condition = None
        for i, status in enumerate(status_list):
            status_value_name = f":status{i}"
            expression_attribute_values[status_value_name] = status

            if status_condition is None:
                status_condition = Attr("status").eq(status)
            else:
                status_condition = status_condition | Attr("status").eq(status)

        if filter_expression is None:
            filter_expression = status_condition
        else:
            filter_expression = filter_expression & status_condition

    if max_price is not None:
        price_condition = Attr("price").lte(max_price)
        expression_attribute_values[":max_price"] = max_price

        if filter_expression is None:
            filter_expression = price_condition
        else:
            filter_expression = filter_expression & price_condition

    # Prepare the query parameters
    query_params = {"KeyConditionExpression": key_condition}

    if filter_expression:
        query_params["FilterExpression"] = filter_expression
        if expression_attribute_values:
            query_params["ExpressionAttributeValues"] = expression_attribute_values

    # Execute the query
    response = table.query(**query_params)
    return response


def query_with_complex_filter_and_or(
    table_name,
    partition_key_name,
    partition_key_value,
    category=None,
    min_rating=None,
    max_price=None,
):
    """
    Query a DynamoDB table with a complex filter expression using AND and OR operators.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        category (str, optional): Category value for filtering.
        min_rating (float, optional): Minimum rating value for filtering.
        max_price (float, optional): Maximum price value for filtering.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Start with the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Build a complex filter expression with AND and OR operators
    filter_expression = None
    expression_attribute_values = {}

    # Build the category condition
    if category:
        filter_expression = Attr("category").eq(category)
        expression_attribute_values[":category"] = category

    # Build the rating and price condition (rating >= min_rating OR price <= max_price)
    rating_price_condition = None

    if min_rating is not None:
        rating_price_condition = Attr("rating").gte(min_rating)
        expression_attribute_values[":min_rating"] = min_rating

    if max_price is not None:
        price_condition = Attr("price").lte(max_price)
        expression_attribute_values[":max_price"] = max_price

        if rating_price_condition is None:
            rating_price_condition = price_condition
        else:
            rating_price_condition = rating_price_condition | price_condition

    # Combine the conditions
    if rating_price_condition:
        if filter_expression is None:
            filter_expression = rating_price_condition
        else:
            filter_expression = filter_expression & rating_price_condition

    # Prepare the query parameters
    query_params = {"KeyConditionExpression": key_condition}

    if filter_expression:
        query_params["FilterExpression"] = filter_expression
        if expression_attribute_values:
            query_params["ExpressionAttributeValues"] = expression_attribute_values

    # Execute the query
    response = table.query(**query_params)
    return response
```
を使用して動的に構築されたフィルター式でクエリを実行します AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Attr, Key


def query_with_dynamic_filter(
    table_name, partition_key_name, partition_key_value, filter_conditions=None
):
    """
    Query a DynamoDB table with a dynamically constructed filter expression.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        filter_conditions (dict, optional): A dictionary of filter conditions where
            keys are attribute names and values are dictionaries with 'operator' and 'value'.
            Example: {'rating': {'operator': '>=', 'value': 4}, 'status': {'operator': '=', 'value': 'active'}}

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Start with the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Initialize variables for the filter expression and attribute values
    filter_expression = None
    expression_attribute_values = {":pk_val": partition_key_value}

    # Dynamically build the filter expression if filter conditions are provided
    if filter_conditions:
        for attr_name, condition in filter_conditions.items():
            operator = condition.get("operator")
            value = condition.get("value")
            attr_value_name = f":{attr_name}"
            expression_attribute_values[attr_value_name] = value

            # Create the appropriate filter expression based on the operator
            current_condition = None
            if operator == "=":
                current_condition = Attr(attr_name).eq(value)
            elif operator == "!=":
                current_condition = Attr(attr_name).ne(value)
            elif operator == ">":
                current_condition = Attr(attr_name).gt(value)
            elif operator == ">=":
                current_condition = Attr(attr_name).gte(value)
            elif operator == "<":
                current_condition = Attr(attr_name).lt(value)
            elif operator == "<=":
                current_condition = Attr(attr_name).lte(value)
            elif operator == "contains":
                current_condition = Attr(attr_name).contains(value)
            elif operator == "begins_with":
                current_condition = Attr(attr_name).begins_with(value)

            # Combine with existing filter expression using AND
            if current_condition:
                if filter_expression is None:
                    filter_expression = current_condition
                else:
                    filter_expression = filter_expression & current_condition

    # Perform the query with the dynamically built filter expression
    query_params = {"KeyConditionExpression": key_condition}

    if filter_expression:
        query_params["FilterExpression"] = filter_expression

    response = table.query(**query_params)
    return response
```
フィルター式を使用してクエリを実行し、 を使用して制限します AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Attr, Key


def query_with_filter_and_limit(
    table_name,
    partition_key_name,
    partition_key_value,
    filter_attribute=None,
    filter_value=None,
    limit=10,
):
    """
    Query a DynamoDB table with a filter expression and limit the number of results.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        filter_attribute (str, optional): The attribute name to filter on.
        filter_value (any, optional): The value to compare against in the filter.
        limit (int, optional): The maximum number of items to evaluate. Defaults to 10.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Prepare the query parameters
    query_params = {"KeyConditionExpression": key_condition, "Limit": limit}

    # Add the filter expression if filter attributes are provided
    if filter_attribute and filter_value is not None:
        query_params["FilterExpression"] = Attr(filter_attribute).gt(filter_value)
        query_params["ExpressionAttributeValues"] = {":filter_value": filter_value}

    # Execute the query
    response = table.query(**query_params)
    return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### リストオペレーションを実行する
<a name="dynamodb_Scenario_ListOperations_python_3_topic"></a>

次のコード例は、DynamoDB でリストオペレーションを実行する方法を示しています。
+ リスト属性に要素を追加します。
+ リスト属性から要素を削除します。
+ インデックスでリスト内の特定の要素を更新します。
+ リスト追加関数およびリストインデックス関数を使用します。

**SDK for Python (Boto3)**  
を使用してリストオペレーションをデモンストレーションします AWS SDK for Python (Boto3)。  

```
import boto3
import json
from typing import Any, Dict, List, Optional, Union


def create_list_attribute(
    table_name: str, key: Dict[str, Any], list_name: str, list_values: List[Any]
) -> Dict[str, Any]:
    """
    Create a new list attribute or replace an existing one.

    This function demonstrates how to create a new list attribute or replace
    an existing list with new values.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        list_name (str): The name of the list attribute.
        list_values (List[Any]): The values to set in the list.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use the SET operation to create or replace the list
    response = table.update_item(
        Key=key,
        UpdateExpression=f"SET {list_name} = :list_values",
        ExpressionAttributeValues={":list_values": list_values},
        ReturnValues="UPDATED_NEW",
    )

    return response


def append_to_list(
    table_name: str, key: Dict[str, Any], list_name: str, values_to_append: List[Any]
) -> Dict[str, Any]:
    """
    Append values to the end of a list attribute.

    This function demonstrates how to use the list_append function to add elements
    to the end of a list attribute.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        list_name (str): The name of the list attribute.
        values_to_append (List[Any]): The values to append to the list.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use list_append to add values to the end of the list
    response = table.update_item(
        Key=key,
        UpdateExpression=f"SET {list_name} = list_append({list_name}, :values)",
        ExpressionAttributeValues={":values": values_to_append},
        ReturnValues="UPDATED_NEW",
    )

    return response


def prepend_to_list(
    table_name: str, key: Dict[str, Any], list_name: str, values_to_prepend: List[Any]
) -> Dict[str, Any]:
    """
    Prepend values to the beginning of a list attribute.

    This function demonstrates how to use the list_append function to add elements
    to the beginning of a list attribute.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        list_name (str): The name of the list attribute.
        values_to_prepend (List[Any]): The values to prepend to the list.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use list_append with reversed order to add values to the beginning of the list
    response = table.update_item(
        Key=key,
        UpdateExpression=f"SET {list_name} = list_append(:values, {list_name})",
        ExpressionAttributeValues={":values": values_to_prepend},
        ReturnValues="UPDATED_NEW",
    )

    return response


def update_list_element(
    table_name: str, key: Dict[str, Any], list_name: str, index: int, new_value: Any
) -> Dict[str, Any]:
    """
    Update a specific element in a list attribute.

    This function demonstrates how to update a specific element in a list attribute
    using the index notation.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        list_name (str): The name of the list attribute.
        index (int): The zero-based index of the element to update.
        new_value (Any): The new value for the element.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use the index notation to update a specific element
    response = table.update_item(
        Key=key,
        UpdateExpression=f"SET {list_name}[{index}] = :value",
        ExpressionAttributeValues={":value": new_value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def remove_list_element(
    table_name: str, key: Dict[str, Any], list_name: str, index: int
) -> Dict[str, Any]:
    """
    Remove a specific element from a list attribute.

    This function demonstrates how to remove a specific element from a list attribute
    using the REMOVE action with index notation.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        list_name (str): The name of the list attribute.
        index (int): The zero-based index of the element to remove.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use the REMOVE action with index notation to remove a specific element
    response = table.update_item(
        Key=key, UpdateExpression=f"REMOVE {list_name}[{index}]", ReturnValues="UPDATED_NEW"
    )

    return response


def update_nested_list_element(
    table_name: str, key: Dict[str, Any], path: str, new_value: Any
) -> Dict[str, Any]:
    """
    Update an element in a nested list structure.

    This function demonstrates how to update an element in a nested list structure
    using expression attribute names for the path components.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        path (str): The path to the nested element (e.g., "parent[0].child[1]").
        new_value (Any): The new value for the element.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Define a type for path parts
    path_part = Dict[str, Union[str, int]]
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Parse the path to extract attribute names and indices
    path_parts: List[path_part] = []
    current_part = ""
    in_bracket = False

    for char in path:
        if char == "[":
            if current_part:
                path_parts.append({"type": "attribute", "value": current_part})
                current_part = ""
            in_bracket = True
        elif char == "]":
            if current_part:
                # Fix for mypy: Use a properly typed dictionary with Union type
                path_parts.append({"type": "index", "value": int(current_part)})
                current_part = ""
            in_bracket = False
        elif char == "." and not in_bracket:
            if current_part:
                path_parts.append({"type": "attribute", "value": current_part})
                current_part = ""
        else:
            current_part += char

    if current_part:
        path_parts.append({"type": "attribute", "value": current_part})

    # Build the update expression and attribute names
    update_expression = "SET "
    expression_attribute_names = {}

    # Build the path expression
    path_expression = ""
    for i, part in enumerate(path_parts):
        if part["type"] == "attribute":
            name_placeholder = f"#attr{i}"
            expression_attribute_names[name_placeholder] = part["value"]

            if path_expression:
                path_expression += "."
            path_expression += name_placeholder
        elif part["type"] == "index":
            path_expression += f"[{part['value']}]"

    # Complete the update expression
    update_expression += f"{path_expression} = :value"

    # Execute the update
    response = table.update_item(
        Key=key,
        UpdateExpression=update_expression,
        ExpressionAttributeNames=expression_attribute_names,
        ExpressionAttributeValues={":value": new_value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def create_list_if_not_exists(
    table_name: str, key: Dict[str, Any], list_name: str, default_values: List[Any]
) -> Dict[str, Any]:
    """
    Create a list attribute if it doesn't exist.

    This function demonstrates how to use if_not_exists to create a list attribute
    with default values if it doesn't already exist.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        list_name (str): The name of the list attribute.
        default_values (List[Any]): The default values for the list.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use if_not_exists to create the list if it doesn't exist
    response = table.update_item(
        Key=key,
        UpdateExpression=f"SET {list_name} = if_not_exists({list_name}, :default)",
        ExpressionAttributeValues={":default": default_values},
        ReturnValues="UPDATED_NEW",
    )

    return response


def append_to_list_safely(
    table_name: str,
    key: Dict[str, Any],
    list_name: str,
    values_to_append: List[Any],
    default_values: Optional[List[Any]] = None,
) -> Dict[str, Any]:
    """
    Append values to a list, creating it if it doesn't exist.

    This function demonstrates how to safely append values to a list attribute,
    creating the list with default values if it doesn't exist.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        list_name (str): The name of the list attribute.
        values_to_append (List[Any]): The values to append to the list.
        default_values (Optional[List[Any]]): The default values if the list doesn't exist.
            If not provided, values_to_append will be used as the default.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # If default_values is not provided, use values_to_append
    if default_values is None:
        default_values = values_to_append

    # Use if_not_exists with list_append to safely append to the list
    response = table.update_item(
        Key=key,
        UpdateExpression=f"SET {list_name} = list_append(if_not_exists({list_name}, :default), :values)",
        ExpressionAttributeValues={
            ":default": default_values if default_values else [],
            ":values": values_to_append,
        },
        ReturnValues="UPDATED_NEW",
    )

    return response
```
でのリストオペレーションの使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use list operations in DynamoDB."""
    # Example parameters
    table_name = "UserData"
    key = {"UserId": "user123"}

    print("Example 1: Creating a list attribute")
    try:
        response = create_list_attribute(
            table_name=table_name,
            key=key,
            list_name="Interests",
            list_values=["Reading", "Hiking", "Photography"],
        )
        print(
            f"List attribute created successfully: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error creating list attribute: {e}")

    print("\nExample 2: Appending values to a list")
    try:
        response = append_to_list(
            table_name=table_name,
            key=key,
            list_name="Interests",
            values_to_append=["Cooking", "Gardening"],
        )
        print(
            f"Values appended to list successfully: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error appending to list: {e}")

    print("\nExample 3: Prepending values to a list")
    try:
        response = prepend_to_list(
            table_name=table_name,
            key=key,
            list_name="Interests",
            values_to_prepend=["Travel", "Music"],
        )
        print(
            f"Values prepended to list successfully: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error prepending to list: {e}")

    print("\nExample 4: Updating a specific list element")
    try:
        response = update_list_element(
            table_name=table_name,
            key=key,
            list_name="Interests",
            index=2,
            new_value="Mountain Hiking",
        )
        print(
            f"List element updated successfully: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error updating list element: {e}")

    print("\nExample 5: Removing a list element")
    try:
        response = remove_list_element(
            table_name=table_name, key=key, list_name="Interests", index=0
        )
        print(
            f"List element removed successfully: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error removing list element: {e}")

    print("\nExample 6: Working with nested lists")
    try:
        # First, create an item with a nested structure
        dynamodb = boto3.resource("dynamodb")
        table = dynamodb.Table(table_name)

        table.update_item(
            Key={"UserId": "user456"},
            UpdateExpression="SET #skills = :skills",
            ExpressionAttributeNames={"#skills": "Skills"},
            ExpressionAttributeValues={
                ":skills": [
                    {"Category": "Programming", "Languages": ["Python", "Java", "JavaScript"]},
                    {"Category": "Database", "Systems": ["DynamoDB", "MongoDB", "PostgreSQL"]},
                ]
            },
        )

        # Now update a nested element
        response = update_nested_list_element(
            table_name=table_name,
            key={"UserId": "user456"},
            path="Skills[0].Languages[1]",
            new_value="TypeScript",
        )
        print(
            f"Nested list element updated successfully: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error working with nested lists: {e}")

    print("\nExample 7: Creating a list if it doesn't exist")
    try:
        response = create_list_if_not_exists(
            table_name=table_name,
            key={"UserId": "user789"},
            list_name="Preferences",
            default_values=["Default1", "Default2", "Default3"],
        )
        print(
            f"List created with default values: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error creating list with default values: {e}")

    print("\nExample 8: Safely appending to a list")
    try:
        response = append_to_list_safely(
            table_name=table_name,
            key={"UserId": "user789"},
            list_name="Notifications",
            values_to_append=["New message received"],
            default_values=[],
        )
        print(f"Safely appended to list: {json.dumps(response.get('Attributes', {}), default=str)}")
    except Exception as e:
        print(f"Error safely appending to list: {e}")

    print("\nKey Points About Working with Lists in DynamoDB:")
    print("1. Lists are ordered collections of elements that can be of different types")
    print("2. Use the SET operation with direct assignment to create or replace a list")
    print("3. Use list_append() to add elements to a list without replacing the entire list")
    print("4. To append to the end: list_append(list_name, :values)")
    print("5. To prepend to the beginning: list_append(:values, list_name)")
    print("6. Use index notation list_name[index] to access or update specific elements")
    print("7. Use the REMOVE action with index notation to remove specific elements")
    print("8. Lists can contain nested structures like maps and other lists")
    print("9. Use if_not_exists() to create a list with default values if it doesn't exist")
    print("10. List indices are zero-based (the first element is at index 0)")
    print("11. Attempting to access an index beyond the list bounds will result in an error")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### マップオペレーションを実行する
<a name="dynamodb_Scenario_MapOperations_python_3_topic"></a>

次のコード例は、DynamoDB でマップオペレーションを実行する方法を示しています。
+ マップ構造にネストされた属性を追加および更新します。
+ マップから特定のフィールドを削除します。
+ 深くネストされたマップ属性を操作します。

**SDK for Python (Boto3)**  
を使用してマップオペレーションをデモンストレーションします AWS SDK for Python (Boto3)。  

```
"""
Example of updating map attributes in DynamoDB.

This module demonstrates how to update map attributes in DynamoDB, including
handling cases where the map attribute might not exist yet.
"""


import boto3
from typing import Any, Dict, Optional



def update_map_attribute_safe(
    table_name: str, key: Dict[str, Any], map_name: str, map_key: str, value: Any
) -> Dict[str, Any]:
    """
    Update a specific key in a map attribute, creating the map if it doesn't exist.

    This function demonstrates how to safely update a key within a map attribute,
    even if the map doesn't exist yet in the item.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        map_name (str): The name of the map attribute.
        map_key (str): The key within the map to update.
        value (Any): The value to set for the map key.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use SET with attribute_not_exists to safely update the map
    response = table.update_item(
        Key=key,
        UpdateExpression="SET #map.#key = :value",
        ExpressionAttributeNames={"#map": map_name, "#key": map_key},
        ExpressionAttributeValues={":value": value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def add_to_nested_map(
    table_name: str, key: Dict[str, Any], path: str, value: Any
) -> Dict[str, Any]:
    """
    Add or update a value in a deeply nested map structure.

    This function demonstrates how to update a value at a specific path in a
    nested map structure, creating any intermediate maps as needed.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        path (str): The path to the nested attribute (e.g., "user.preferences.theme").
        value (Any): The value to set at the specified path.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Split the path into components
    path_parts = path.split(".")

    # Build the update expression and attribute names
    update_expression = "SET "
    expression_attribute_names = {}

    # Build the path expression
    path_expression = ""
    for i, part in enumerate(path_parts):
        name_placeholder = f"#attr{i}"
        expression_attribute_names[name_placeholder] = part

        if i == 0:
            path_expression = name_placeholder
        else:
            path_expression += f".{name_placeholder}"

    # Complete the update expression
    update_expression += f"{path_expression} = :value"

    # Execute the update
    response = table.update_item(
        Key=key,
        UpdateExpression=update_expression,
        ExpressionAttributeNames=expression_attribute_names,
        ExpressionAttributeValues={":value": value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def update_map_with_if_not_exists(
    table_name: str,
    key: Dict[str, Any],
    map_name: str,
    map_key: str,
    value: Any,
    default_map: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Update a key in a map, creating the map with default values if it doesn't exist.

    This function demonstrates how to use if_not_exists to initialize a map with
    default values if it doesn't exist yet, and then update a specific key.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        map_name (str): The name of the map attribute.
        map_key (str): The key within the map to update.
        value (Any): The value to set for the map key.
        default_map (Optional[Dict[str, Any]]): Default map values if the map doesn't exist.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Set default map if not provided
    if default_map is None:
        default_map = {}

    # Create a map with the new key-value pair
    updated_map = default_map.copy()
    updated_map[map_key] = value

    # Use if_not_exists to initialize the map if it doesn't exist
    response = table.update_item(
        Key=key,
        UpdateExpression="SET #map = if_not_exists(#map, :default_map)",
        ExpressionAttributeNames={"#map": map_name},
        ExpressionAttributeValues={":default_map": updated_map},
        ReturnValues="UPDATED_NEW",
    )

    return response


def merge_into_map(
    table_name: str, key: Dict[str, Any], map_name: str, values_to_merge: Dict[str, Any]
) -> Dict[str, Any]:
    """
    Merge multiple key-value pairs into a map attribute.

    This function demonstrates how to update multiple keys in a map attribute
    in a single operation, without overwriting the entire map.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        map_name (str): The name of the map attribute.
        values_to_merge (Dict[str, Any]): Key-value pairs to merge into the map.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the update expression for each key-value pair
    update_expression = "SET "
    expression_attribute_names = {"#map": map_name}
    expression_attribute_values = {}

    # Add each key-value pair to the update expression
    for i, (k, v) in enumerate(values_to_merge.items()):
        key_placeholder = f"#key{i}"
        value_placeholder = f":value{i}"

        expression_attribute_names[key_placeholder] = k
        expression_attribute_values[value_placeholder] = v

        if i > 0:
            update_expression += ", "
        update_expression += f"#map.{key_placeholder} = {value_placeholder}"

    # Execute the update
    response = table.update_item(
        Key=key,
        UpdateExpression=update_expression,
        ExpressionAttributeNames=expression_attribute_names,
        ExpressionAttributeValues=expression_attribute_values,
        ReturnValues="UPDATED_NEW",
    )

    return response




def example_usage():
    """Example of how to use the map attribute update functions."""
    # Example parameters
    table_name = "UserProfiles"
    key = {"UserId": "user123"}

    print("Example 1: Updating a specific key in a map attribute")
    try:
        response = update_map_attribute_safe(
            table_name=table_name, key=key, map_name="Preferences", map_key="Theme", value="Dark"
        )
        print(f"Map attribute updated successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error updating map attribute: {e}")

    print("\nExample 2: Adding a value to a deeply nested map")
    try:
        response = add_to_nested_map(
            table_name=table_name, key=key, path="Settings.Notifications.Email", value=True
        )
        print(f"Nested map updated successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error updating nested map: {e}")

    print("\nExample 3: Initializing a map with default values if it doesn't exist")
    try:
        default_map = {"Language": "English", "Currency": "USD", "TimeZone": "UTC"}

        response = update_map_with_if_not_exists(
            table_name=table_name,
            key={"UserId": "newuser456"},
            map_name="Preferences",
            map_key="Theme",
            value="Light",
            default_map=default_map,
        )
        print(f"Map initialized with defaults: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error initializing map: {e}")

    print("\nExample 4: Merging multiple values into a map")
    try:
        values_to_merge = {
            "NotificationsEnabled": True,
            "EmailFrequency": "Daily",
            "PushNotifications": False,
        }

        response = merge_into_map(
            table_name=table_name,
            key=key,
            map_name="NotificationSettings",
            values_to_merge=values_to_merge,
        )
        print(f"Multiple values merged into map: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error merging values into map: {e}")

    print("\nBest practices for working with map attributes in DynamoDB:")
    print("1. Use dot notation to access and update nested attributes")
    print("2. Use ExpressionAttributeNames to handle reserved words and special characters")
    print("3. Use if_not_exists() to handle cases where attributes might not exist")
    print("4. Update specific map keys rather than overwriting the entire map")
    print("5. Use a single update operation to modify multiple map keys for better performance")
    print("6. Consider your data model carefully to minimize the need for deeply nested attributes")



if __name__ == "__main__":
    example_usage()
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### セットオペレーションを実行する
<a name="dynamodb_Scenario_SetOperations_python_3_topic"></a>

次のコード例は、DynamoDB でセットオペレーションを実行する方法を示しています。
+ セット属性に要素を追加します。
+ セット属性から要素を削除します。
+ セットで ADD および DELETE オペレーションを使用します。

**SDK for Python (Boto3)**  
を使用してセットオペレーションをデモンストレーションします AWS SDK for Python (Boto3)。  

```
import boto3
from typing import Any, Dict, List


def create_set_attribute(
    table_name: str,
    key: Dict[str, Any],
    set_name: str,
    set_values: List[Any],
    set_type: str = "string",
) -> Dict[str, Any]:
    """
    Create a new set attribute or add elements to an existing set.

    This function demonstrates how to use the ADD operation to create a new set
    or add elements to an existing set.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        set_name (str): The name of the set attribute.
        set_values (List[Any]): The values to add to the set.
        set_type (str, optional): The type of set to create: "string", "number", or "binary".
            Defaults to "string".

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Convert the list to a DynamoDB set based on the specified type
    if set_type == "string":
        dynamo_set = set(str(value) for value in set_values)
    elif set_type == "number":
        # We need to use actual float values for the DynamoDB API
        # but mypy expects strings in sets, so we need to use type: ignore
        dynamo_set = set(float(value) for value in set_values)  # type: ignore
    else:  # binary set is not directly supported in high-level API, handled differently
        raise ValueError("Binary sets are not supported in this example")

    # Use the ADD operation to create or update the set
    response = table.update_item(
        Key=key,
        UpdateExpression="ADD #set_attr :set_values",
        ExpressionAttributeNames={"#set_attr": set_name},
        ExpressionAttributeValues={":set_values": dynamo_set},
        ReturnValues="UPDATED_NEW",
    )

    return response


def add_to_set(
    table_name: str, key: Dict[str, Any], set_name: str, values_to_add: List[Any]
) -> Dict[str, Any]:
    """
    Add elements to an existing set attribute.

    This function demonstrates how to use the ADD operation to add elements to an existing set.
    If the set doesn't exist, it will be created.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        set_name (str): The name of the set attribute.
        values_to_add (List[Any]): The values to add to the set.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Convert the list to a set (assuming string set for simplicity)
    dynamo_set = set(str(value) for value in values_to_add)

    # Use the ADD operation to add values to the set
    response = table.update_item(
        Key=key,
        UpdateExpression="ADD #set_attr :values_to_add",
        ExpressionAttributeNames={"#set_attr": set_name},
        ExpressionAttributeValues={":values_to_add": dynamo_set},
        ReturnValues="UPDATED_NEW",
    )

    return response


def remove_from_set(
    table_name: str, key: Dict[str, Any], set_name: str, values_to_remove: List[Any]
) -> Dict[str, Any]:
    """
    Remove elements from a set attribute.

    This function demonstrates how to use the DELETE operation to remove elements from a set.
    If the last element is removed, the attribute will be deleted entirely.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        set_name (str): The name of the set attribute.
        values_to_remove (List[Any]): The values to remove from the set.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Convert the list to a set (assuming string set for simplicity)
    dynamo_set = set(str(value) for value in values_to_remove)

    # Use the DELETE operation to remove values from the set
    response = table.update_item(
        Key=key,
        UpdateExpression="DELETE #set_attr :values_to_remove",
        ExpressionAttributeNames={"#set_attr": set_name},
        ExpressionAttributeValues={":values_to_remove": dynamo_set},
        ReturnValues="UPDATED_NEW",
    )

    return response


def check_if_set_exists(table_name: str, key: Dict[str, Any], set_name: str) -> bool:
    """
    Check if a set attribute exists in an item.

    This function demonstrates how to check if a set attribute exists after
    potentially removing all elements from it.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to check.
        set_name (str): The name of the set attribute.

    Returns:
        bool: True if the set attribute exists, False otherwise.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Get the item
    response = table.get_item(
        Key=key, ProjectionExpression="#set_attr", ExpressionAttributeNames={"#set_attr": set_name}
    )

    # Check if the item exists and has the set attribute
    return "Item" in response and set_name in response["Item"]


def demonstrate_last_element_removal(
    table_name: str, key: Dict[str, Any], set_name: str
) -> Dict[str, Any]:
    """
    Demonstrate what happens when you remove the last element from a set.

    This function creates a set with a single element, then removes that element,
    showing that the attribute is completely removed when the last element is deleted.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        set_name (str): The name of the set attribute.

    Returns:
        Dict[str, Any]: A dictionary containing the results of the demonstration.
    """
    # Step 1: Create a set with a single element
    create_response = create_set_attribute(
        table_name=table_name,
        key=key,
        set_name=set_name,
        set_values=["last_element"],
        set_type="string",
    )

    # Step 2: Check that the set exists
    exists_before = check_if_set_exists(table_name, key, set_name)

    # Step 3: Remove the last element
    delete_response = remove_from_set(
        table_name=table_name, key=key, set_name=set_name, values_to_remove=["last_element"]
    )

    # Step 4: Check if the set still exists
    exists_after = check_if_set_exists(table_name, key, set_name)

    # Return the results
    return {
        "create_response": create_response,
        "exists_before": exists_before,
        "delete_response": delete_response,
        "exists_after": exists_after,
    }


def work_with_number_set(
    table_name: str,
    key: Dict[str, Any],
    set_name: str,
    initial_values: List[float],
    values_to_add: List[float],
    values_to_remove: List[float],
) -> Dict[str, Any]:
    """
    Demonstrate working with a number set in DynamoDB.

    This function shows how to create and manipulate a set of numbers.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        set_name (str): The name of the set attribute.
        initial_values (List[float]): The initial values for the set.
        values_to_add (List[float]): Values to add to the set.
        values_to_remove (List[float]): Values to remove from the set.

    Returns:
        Dict[str, Any]: A dictionary containing the responses from each operation.
    """
    # Step 1: Create the number set
    create_response = create_set_attribute(
        table_name=table_name,
        key=key,
        set_name=set_name,
        set_values=initial_values,
        set_type="number",
    )

    # Step 2: Add more numbers to the set
    add_response = add_to_set(
        table_name=table_name, key=key, set_name=set_name, values_to_add=values_to_add
    )

    # Step 3: Remove some numbers from the set
    remove_response = remove_from_set(
        table_name=table_name, key=key, set_name=set_name, values_to_remove=values_to_remove
    )

    # Step 4: Get the final state
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    get_response = table.get_item(
        Key=key,
        ProjectionExpression=f"#{set_name}",
        ExpressionAttributeNames={f"#{set_name}": set_name},
    )

    # Return all responses
    return {
        "create_response": create_response,
        "add_response": add_response,
        "remove_response": remove_response,
        "final_state": get_response.get("Item", {}),
    }
```
でのセットオペレーションの使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use the set operations functions."""
    # Example parameters
    table_name = "UserPreferences"
    key = {"UserId": "user123"}

    print("Example 1: Creating a string set attribute")
    try:
        response = create_set_attribute(
            table_name=table_name,
            key=key,
            set_name="FavoriteTags",
            set_values=["AWS", "DynamoDB", "NoSQL"],
            set_type="string",
        )
        print(f"Set attribute created successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error creating set attribute: {e}")

    print("\nExample 2: Adding elements to an existing set")
    try:
        response = add_to_set(
            table_name=table_name,
            key=key,
            set_name="FavoriteTags",
            values_to_add=["Database", "Serverless"],
        )
        print(f"Elements added to set successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error adding to set: {e}")

    print("\nExample 3: Removing elements from a set")
    try:
        response = remove_from_set(
            table_name=table_name, key=key, set_name="FavoriteTags", values_to_remove=["NoSQL"]
        )
        print(f"Elements removed from set successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error removing from set: {e}")

    print("\nExample 4: Demonstrating what happens when you remove the last element from a set")
    try:
        results = demonstrate_last_element_removal(
            table_name=table_name, key={"UserId": "tempUser"}, set_name="SingleElementSet"
        )

        print(f"Set exists before removal: {results['exists_before']}")
        print(f"Set exists after removal: {results['exists_after']}")

        if not results["exists_after"]:
            print("The set attribute was completely removed when the last element was deleted.")
        else:
            print("The set attribute still exists after removing the last element.")
    except Exception as e:
        print(f"Error in last element removal demonstration: {e}")

    print("\nExample 5: Working with a number set")
    try:
        results = work_with_number_set(
            table_name=table_name,
            key={"UserId": "user456"},
            set_name="LuckyNumbers",
            initial_values=[7, 13, 42],
            values_to_add=[99, 100],
            values_to_remove=[13],
        )

        print(f"Initial number set: {results['create_response'].get('Attributes', {})}")
        print(f"After adding numbers: {results['add_response'].get('Attributes', {})}")
        print(f"After removing numbers: {results['remove_response'].get('Attributes', {})}")
        print(f"Final state: {results['final_state']}")
    except Exception as e:
        print(f"Error working with number set: {e}")

    print("\nKey Points About DynamoDB Sets:")
    print("1. Sets can only contain elements of the same type (string, number, or binary)")
    print("2. Sets automatically eliminate duplicate values")
    print("3. The ADD operation creates a set if it doesn't exist")
    print("4. The DELETE operation removes specified elements from a set")
    print("5. When the last element is removed from a set, the entire attribute is deleted")
    print("6. Empty sets are not allowed in DynamoDB")
    print("7. Sets are unordered collections")
    print("8. The ADD operation is atomic for sets")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_python_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
PartiQL ステートメントのバッチを実行できるクラスを作成します。  

```
from datetime import datetime
from decimal import Decimal
import logging
from pprint import pprint

import boto3
from botocore.exceptions import ClientError

from scaffold import Scaffold

logger = logging.getLogger(__name__)

class PartiQLBatchWrapper:
    """
    Encapsulates a DynamoDB resource to run PartiQL statements.
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource


    def run_partiql(self, statements, param_list):
        """
        Runs a PartiQL statement. A Boto3 resource is used even though
        `execute_statement` is called on the underlying `client` object because the
        resource transforms input and output from plain old Python objects (POPOs) to
        the DynamoDB format. If you create the client directly, you must do these
        transforms yourself.

        :param statements: The batch of PartiQL statements.
        :param param_list: The batch of PartiQL parameters that are associated with
                           each statement. This list must be in the same order as the
                           statements.
        :return: The responses returned from running the statements, if any.
        """
        try:
            output = self.dyn_resource.meta.client.batch_execute_statement(
                Statements=[
                    {"Statement": statement, "Parameters": params}
                    for statement, params in zip(statements, param_list)
                ]
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Couldn't execute batch of PartiQL statements because the table "
                    "does not exist."
                )
            else:
                logger.error(
                    "Couldn't execute batch of PartiQL statements. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return output
```
テーブルを作成し、PartiQL クエリをバッチで実行するシナリオを実行します。  

```
def run_scenario(scaffold, wrapper, table_name):
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Welcome to the Amazon DynamoDB PartiQL batch statement demo.")
    print("-" * 88)

    print(f"Creating table '{table_name}' for the demo...")
    scaffold.create_table(table_name)
    print("-" * 88)

    movie_data = [
        {
            "title": f"House PartiQL",
            "year": datetime.now().year - 5,
            "info": {
                "plot": "Wacky high jinks result from querying a mysterious database.",
                "rating": Decimal("8.5"),
            },
        },
        {
            "title": f"House PartiQL 2",
            "year": datetime.now().year - 3,
            "info": {
                "plot": "Moderate high jinks result from querying another mysterious database.",
                "rating": Decimal("6.5"),
            },
        },
        {
            "title": f"House PartiQL 3",
            "year": datetime.now().year - 1,
            "info": {
                "plot": "Tepid high jinks result from querying yet another mysterious database.",
                "rating": Decimal("2.5"),
            },
        },
    ]

    print(f"Inserting a batch of movies into table '{table_name}.")
    statements = [
        f'INSERT INTO "{table_name}" ' f"VALUE {{'title': ?, 'year': ?, 'info': ?}}"
    ] * len(movie_data)
    params = [list(movie.values()) for movie in movie_data]
    wrapper.run_partiql(statements, params)
    print("Success!")
    print("-" * 88)

    print(f"Getting data for a batch of movies.")
    statements = [f'SELECT * FROM "{table_name}" WHERE title=? AND year=?'] * len(
        movie_data
    )
    params = [[movie["title"], movie["year"]] for movie in movie_data]
    output = wrapper.run_partiql(statements, params)
    for item in output["Responses"]:
        print(f"\n{item['Item']['title']}, {item['Item']['year']}")
        pprint(item["Item"])
    print("-" * 88)

    ratings = [Decimal("7.7"), Decimal("5.5"), Decimal("1.3")]
    print(f"Updating a batch of movies with new ratings.")
    statements = [
        f'UPDATE "{table_name}" SET info.rating=? ' f"WHERE title=? AND year=?"
    ] * len(movie_data)
    params = [
        [rating, movie["title"], movie["year"]]
        for rating, movie in zip(ratings, movie_data)
    ]
    wrapper.run_partiql(statements, params)
    print("Success!")
    print("-" * 88)

    print(f"Getting projected data from the table to verify our update.")
    output = wrapper.dyn_resource.meta.client.execute_statement(
        Statement=f'SELECT title, info.rating FROM "{table_name}"'
    )
    pprint(output["Items"])
    print("-" * 88)

    print(f"Deleting a batch of movies from the table.")
    statements = [f'DELETE FROM "{table_name}" WHERE title=? AND year=?'] * len(
        movie_data
    )
    params = [[movie["title"], movie["year"]] for movie in movie_data]
    wrapper.run_partiql(statements, params)
    print("Success!")
    print("-" * 88)

    print(f"Deleting table '{table_name}'...")
    scaffold.delete_table()
    print("-" * 88)

    print("\nThanks for watching!")
    print("-" * 88)


if __name__ == "__main__":
    try:
        dyn_res = boto3.resource("dynamodb")
        scaffold = Scaffold(dyn_res)
        movies = PartiQLBatchWrapper(dyn_res)
        run_scenario(scaffold, movies, "doc-example-table-partiql-movies")
    except Exception as e:
        print(f"Something went wrong with the demo! Here's what: {e}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_python_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
PartiQL ステートメントを実行できるクラスを作成します。  

```
from datetime import datetime
from decimal import Decimal
import logging
from pprint import pprint

import boto3
from botocore.exceptions import ClientError

from scaffold import Scaffold

logger = logging.getLogger(__name__)

class PartiQLWrapper:
    """
    Encapsulates a DynamoDB resource to run PartiQL statements.
    """

    def __init__(self, dyn_resource):
        """
        :param dyn_resource: A Boto3 DynamoDB resource.
        """
        self.dyn_resource = dyn_resource


    def run_partiql(self, statement, params):
        """
        Runs a PartiQL statement. A Boto3 resource is used even though
        `execute_statement` is called on the underlying `client` object because the
        resource transforms input and output from plain old Python objects (POPOs) to
        the DynamoDB format. If you create the client directly, you must do these
        transforms yourself.

        :param statement: The PartiQL statement.
        :param params: The list of PartiQL parameters. These are applied to the
                       statement in the order they are listed.
        :return: The items returned from the statement, if any.
        """
        try:
            output = self.dyn_resource.meta.client.execute_statement(
                Statement=statement, Parameters=params
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Couldn't execute PartiQL '%s' because the table does not exist.",
                    statement,
                )
            else:
                logger.error(
                    "Couldn't execute PartiQL '%s'. Here's why: %s: %s",
                    statement,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return output
```
テーブルを作成し、PartiQL クエリを実行するシナリオを実行します。  

```
def run_scenario(scaffold, wrapper, table_name):
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Welcome to the Amazon DynamoDB PartiQL single statement demo.")
    print("-" * 88)

    print(f"Creating table '{table_name}' for the demo...")
    scaffold.create_table(table_name)
    print("-" * 88)

    title = "24 Hour PartiQL People"
    year = datetime.now().year
    plot = "A group of data developers discover a new query language they can't stop using."
    rating = Decimal("9.9")

    print(f"Inserting movie '{title}' released in {year}.")
    wrapper.run_partiql(
        f"INSERT INTO \"{table_name}\" VALUE {{'title': ?, 'year': ?, 'info': ?}}",
        [title, year, {"plot": plot, "rating": rating}],
    )
    print("Success!")
    print("-" * 88)

    print(f"Getting data for movie '{title}' released in {year}.")
    output = wrapper.run_partiql(
        f'SELECT * FROM "{table_name}" WHERE title=? AND year=?', [title, year]
    )
    for item in output["Items"]:
        print(f"\n{item['title']}, {item['year']}")
        pprint(output["Items"])
    print("-" * 88)

    rating = Decimal("2.4")
    print(f"Updating movie '{title}' with a rating of {float(rating)}.")
    wrapper.run_partiql(
        f'UPDATE "{table_name}" SET info.rating=? WHERE title=? AND year=?',
        [rating, title, year],
    )
    print("Success!")
    print("-" * 88)

    print(f"Getting data again to verify our update.")
    output = wrapper.run_partiql(
        f'SELECT * FROM "{table_name}" WHERE title=? AND year=?', [title, year]
    )
    for item in output["Items"]:
        print(f"\n{item['title']}, {item['year']}")
        pprint(output["Items"])
    print("-" * 88)

    print(f"Deleting movie '{title}' released in {year}.")
    wrapper.run_partiql(
        f'DELETE FROM "{table_name}" WHERE title=? AND year=?', [title, year]
    )
    print("Success!")
    print("-" * 88)

    print(f"Deleting table '{table_name}'...")
    scaffold.delete_table()
    print("-" * 88)

    print("\nThanks for watching!")
    print("-" * 88)


if __name__ == "__main__":
    try:
        dyn_res = boto3.resource("dynamodb")
        scaffold = Scaffold(dyn_res)
        movies = PartiQLWrapper(dyn_res)
        run_scenario(scaffold, movies, "doc-example-table-partiql-movies")
    except Exception as e:
        print(f"Something went wrong with the demo! Here's what: {e}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ExecuteStatement](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### グローバルセカンダリインデックスを使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithGlobalSecondaryIndex_python_3_topic"></a>

以下のコード例は、グローバルセカンダリインデックスを使用してテーブルをクエリする方法を示しています。
+ プライマリキーを使用して DynamoDB テーブルをクエリします。
+ 代替アクセスパターンのグローバルセカンダリインデックス (GSI) をクエリします。
+ テーブルクエリと GSI クエリを比較します。

**SDK for Python (Boto3)**  
プライマリキーと グローバルセカンダリインデックス (GSI) を使用して DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Key


def query_table(table_name, partition_key_name, partition_key_value):
    """
    Query a DynamoDB table using its primary key.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Perform the query on the table's primary key
    response = table.query(KeyConditionExpression=Key(partition_key_name).eq(partition_key_value))

    return response


def query_gsi(table_name, index_name, partition_key_name, partition_key_value):
    """
    Query a Global Secondary Index (GSI) on a DynamoDB table.

    Args:
        table_name (str): The name of the DynamoDB table.
        index_name (str): The name of the Global Secondary Index.
        partition_key_name (str): The name of the GSI's partition key attribute.
        partition_key_value (str): The value of the GSI's partition key to query.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Perform the query on the GSI
    response = table.query(
        IndexName=index_name, KeyConditionExpression=Key(partition_key_name).eq(partition_key_value)
    )

    return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### begins\$1with 条件を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithBeginsWithCondition_python_3_topic"></a>

以下のコード例は、begins\$1with 条件を使用してテーブルをクエリする方法を示しています。
+ キー条件式で begins\$1with 関数を使用します。
+ ソートキーのプレフィックスパターンに基づいて項目をフィルタリングします。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3)でソートキーの begins\$1with 条件を使用して DynamoDB テーブルをクエリします。  

```
import boto3
from boto3.dynamodb.conditions import Key


def query_with_begins_with(
    table_name, partition_key_name, partition_key_value, sort_key_name, prefix
):
    """
    Query a DynamoDB table with a begins_with condition on the sort key.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str): The name of the sort key attribute.
        prefix (str): The prefix to match at the beginning of the sort key.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Perform the query with a begins_with condition on the sort key
    key_condition = Key(partition_key_name).eq(partition_key_value) & Key(
        sort_key_name
    ).begins_with(prefix)
    response = table.query(KeyConditionExpression=key_condition)

    return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### 日付範囲を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithDateRange_python_3_topic"></a>

以下のコード例は、ソートキーの日付範囲を使用してテーブルをクエリする方法を示しています。
+ 特定の日付範囲内の項目をクエリします。
+ 日付形式のソートキーで比較演算子を使用します。

**SDK for Python (Boto3)**  
で日付範囲内の項目について DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
from datetime import datetime, timedelta

import boto3
from boto3.dynamodb.conditions import Key


def query_with_date_range(
    table_name, partition_key_name, partition_key_value, sort_key_name, start_date, end_date
):
    """
    Query a DynamoDB table with a date range on the sort key.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str): The name of the sort key attribute (containing date values).
        start_date (datetime): The start date for the query range.
        end_date (datetime): The end date for the query range.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Format the date values as ISO 8601 strings
    # DynamoDB works well with ISO format for date values
    start_date_str = start_date.isoformat()
    end_date_str = end_date.isoformat()

    # Perform the query with a date range on the sort key using BETWEEN operator
    key_condition = Key(partition_key_name).eq(partition_key_value) & Key(sort_key_name).between(
        start_date_str, end_date_str
    )

    response = table.query(
        KeyConditionExpression=key_condition,
        ExpressionAttributeValues={
            ":pk_val": partition_key_value,
            ":start_date": start_date_str,
            ":end_date": end_date_str,
        },
    )

    return response


def query_with_date_range_by_month(
    table_name, partition_key_name, partition_key_value, sort_key_name, year, month
):
    """
    Query a DynamoDB table for a specific month's data.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str): The name of the sort key attribute (containing date values).
        year (int): The year to query.
        month (int): The month to query (1-12).

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Calculate the start and end dates for the specified month
    if month == 12:
        next_year = year + 1
        next_month = 1
    else:
        next_year = year
        next_month = month + 1

    start_date = datetime(year, month, 1)
    end_date = datetime(next_year, next_month, 1) - timedelta(microseconds=1)

    # Format the date values as ISO 8601 strings
    start_date_str = start_date.isoformat()
    end_date_str = end_date.isoformat()

    # Perform the query with a date range on the sort key
    key_condition = Key(partition_key_name).eq(partition_key_value) & Key(sort_key_name).between(
        start_date_str, end_date_str
    )

    response = table.query(KeyConditionExpression=key_condition)

    return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### 複雑なフィルター式を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithComplexFilter_python_3_topic"></a>

次のコード例は、複雑なフィルター式を使用してテーブルをクエリする方法を示しています。
+ 複雑なフィルター式をクエリ結果に適用します。
+ 論理演算子を使用して複数の条件を組み合わせます。
+ キー以外の属性に基づいて項目をフィルタリングします。

**SDK for Python (Boto3)**  
を使用して、複雑なフィルター式で DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Attr, Key


def query_with_complex_filter(
    table_name,
    partition_key_name,
    partition_key_value,
    min_rating=None,
    status_list=None,
    max_price=None,
):
    """
    Query a DynamoDB table with a complex filter expression.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        min_rating (float, optional): Minimum rating value for filtering.
        status_list (list, optional): List of status values to include.
        max_price (float, optional): Maximum price value for filtering.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Start with the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Initialize the filter expression and expression attribute values
    filter_expression = None
    expression_attribute_values = {}

    # Build the filter expression based on provided parameters
    if min_rating is not None:
        filter_expression = Attr("rating").gte(min_rating)
        expression_attribute_values[":min_rating"] = min_rating

    if status_list and len(status_list) > 0:
        status_condition = None
        for i, status in enumerate(status_list):
            status_value_name = f":status{i}"
            expression_attribute_values[status_value_name] = status

            if status_condition is None:
                status_condition = Attr("status").eq(status)
            else:
                status_condition = status_condition | Attr("status").eq(status)

        if filter_expression is None:
            filter_expression = status_condition
        else:
            filter_expression = filter_expression & status_condition

    if max_price is not None:
        price_condition = Attr("price").lte(max_price)
        expression_attribute_values[":max_price"] = max_price

        if filter_expression is None:
            filter_expression = price_condition
        else:
            filter_expression = filter_expression & price_condition

    # Prepare the query parameters
    query_params = {"KeyConditionExpression": key_condition}

    if filter_expression:
        query_params["FilterExpression"] = filter_expression
        if expression_attribute_values:
            query_params["ExpressionAttributeValues"] = expression_attribute_values

    # Execute the query
    response = table.query(**query_params)
    return response


def query_with_complex_filter_and_or(
    table_name,
    partition_key_name,
    partition_key_value,
    category=None,
    min_rating=None,
    max_price=None,
):
    """
    Query a DynamoDB table with a complex filter expression using AND and OR operators.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        category (str, optional): Category value for filtering.
        min_rating (float, optional): Minimum rating value for filtering.
        max_price (float, optional): Maximum price value for filtering.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Start with the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Build a complex filter expression with AND and OR operators
    filter_expression = None
    expression_attribute_values = {}

    # Build the category condition
    if category:
        filter_expression = Attr("category").eq(category)
        expression_attribute_values[":category"] = category

    # Build the rating and price condition (rating >= min_rating OR price <= max_price)
    rating_price_condition = None

    if min_rating is not None:
        rating_price_condition = Attr("rating").gte(min_rating)
        expression_attribute_values[":min_rating"] = min_rating

    if max_price is not None:
        price_condition = Attr("price").lte(max_price)
        expression_attribute_values[":max_price"] = max_price

        if rating_price_condition is None:
            rating_price_condition = price_condition
        else:
            rating_price_condition = rating_price_condition | price_condition

    # Combine the conditions
    if rating_price_condition:
        if filter_expression is None:
            filter_expression = rating_price_condition
        else:
            filter_expression = filter_expression & rating_price_condition

    # Prepare the query parameters
    query_params = {"KeyConditionExpression": key_condition}

    if filter_expression:
        query_params["FilterExpression"] = filter_expression
        if expression_attribute_values:
            query_params["ExpressionAttributeValues"] = expression_attribute_values

    # Execute the query
    response = table.query(**query_params)
    return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### 動的フィルター式を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithDynamicFilter_python_3_topic"></a>

以下のコード例は、動的フィルター式を使用してテーブルをクエリする方法を示しています。
+ ランタイムにフィルター式を動的に構築します。
+ ユーザー入力またはアプリケーション状態に基づいてフィルター条件を構築します。
+ 条件付きでフィルター条件を追加または削除します。

**SDK for Python (Boto3)**  
を使用して動的に構築されたフィルター式を使用して DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Attr, Key


def query_with_dynamic_filter(
    table_name, partition_key_name, partition_key_value, filter_conditions=None
):
    """
    Query a DynamoDB table with a dynamically constructed filter expression.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        filter_conditions (dict, optional): A dictionary of filter conditions where
            keys are attribute names and values are dictionaries with 'operator' and 'value'.
            Example: {'rating': {'operator': '>=', 'value': 4}, 'status': {'operator': '=', 'value': 'active'}}

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Start with the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Initialize variables for the filter expression and attribute values
    filter_expression = None
    expression_attribute_values = {":pk_val": partition_key_value}

    # Dynamically build the filter expression if filter conditions are provided
    if filter_conditions:
        for attr_name, condition in filter_conditions.items():
            operator = condition.get("operator")
            value = condition.get("value")
            attr_value_name = f":{attr_name}"
            expression_attribute_values[attr_value_name] = value

            # Create the appropriate filter expression based on the operator
            current_condition = None
            if operator == "=":
                current_condition = Attr(attr_name).eq(value)
            elif operator == "!=":
                current_condition = Attr(attr_name).ne(value)
            elif operator == ">":
                current_condition = Attr(attr_name).gt(value)
            elif operator == ">=":
                current_condition = Attr(attr_name).gte(value)
            elif operator == "<":
                current_condition = Attr(attr_name).lt(value)
            elif operator == "<=":
                current_condition = Attr(attr_name).lte(value)
            elif operator == "contains":
                current_condition = Attr(attr_name).contains(value)
            elif operator == "begins_with":
                current_condition = Attr(attr_name).begins_with(value)

            # Combine with existing filter expression using AND
            if current_condition:
                if filter_expression is None:
                    filter_expression = current_condition
                else:
                    filter_expression = filter_expression & current_condition

    # Perform the query with the dynamically built filter expression
    query_params = {"KeyConditionExpression": key_condition}

    if filter_expression:
        query_params["FilterExpression"] = filter_expression

    response = table.query(**query_params)
    return response
```
で動的フィルター式を使用する方法を示します AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use the query_with_dynamic_filter function."""
    # Example parameters
    table_name = "Products"
    partition_key_name = "Category"
    partition_key_value = "Electronics"

    # Define dynamic filter conditions based on user input or runtime conditions
    user_min_rating = 4  # This could come from user input
    user_status_filter = "active"  # This could come from user input

    filter_conditions = {}

    # Only add conditions that are actually specified
    if user_min_rating is not None:
        filter_conditions["rating"] = {"operator": ">=", "value": user_min_rating}

    if user_status_filter:
        filter_conditions["status"] = {"operator": "=", "value": user_status_filter}

    print(
        f"Querying products in category '{partition_key_value}' with filter conditions: {filter_conditions}"
    )

    # Execute the query with dynamic filter
    response = query_with_dynamic_filter(
        table_name, partition_key_name, partition_key_value, filter_conditions
    )

    # Process the results
    items = response.get("Items", [])
    print(f"Found {len(items)} items")

    for item in items:
        print(f"Product: {item}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### フィルター式と制限を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithFilterAndLimit_python_3_topic"></a>

以下のコード例は、フィルター式と制限を使用してテーブルをクエリする方法を示しています。
+ 評価対象項目を制限してクエリ結果にフィルター式を適用します。
+ フィルタリングされたクエリ結果に制限がどのように影響するかを理解します。
+ クエリで処理される項目の最大数を制御します。

**SDK for Python (Boto3)**  
を使用して、フィルター式と制限を使用して DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Attr, Key


def query_with_filter_and_limit(
    table_name,
    partition_key_name,
    partition_key_value,
    filter_attribute=None,
    filter_value=None,
    limit=10,
):
    """
    Query a DynamoDB table with a filter expression and limit the number of results.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        filter_attribute (str, optional): The attribute name to filter on.
        filter_value (any, optional): The value to compare against in the filter.
        limit (int, optional): The maximum number of items to evaluate. Defaults to 10.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Prepare the query parameters
    query_params = {"KeyConditionExpression": key_condition, "Limit": limit}

    # Add the filter expression if filter attributes are provided
    if filter_attribute and filter_value is not None:
        query_params["FilterExpression"] = Attr(filter_attribute).gt(filter_value)
        query_params["ExpressionAttributeValues"] = {":filter_value": filter_value}

    # Execute the query
    response = table.query(**query_params)
    return response
```
制限があるフィルター式を使用する方法を示します AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use the query_with_filter_and_limit function."""
    # Example parameters
    table_name = "ProductReviews"
    partition_key_name = "ProductId"
    partition_key_value = "P123456"
    filter_attribute = "Rating"
    filter_value = 3  # Filter for ratings > 3
    limit = 5

    print(f"Querying reviews for product '{partition_key_value}' with rating > {filter_value}")
    print(f"Limiting to {limit} evaluated items")

    # Execute the query with filter and limit
    response = query_with_filter_and_limit(
        table_name, partition_key_name, partition_key_value, filter_attribute, filter_value, limit
    )

    # Process the results
    items = response.get("Items", [])
    print(f"\nReturned {len(items)} items that passed the filter")

    for item in items:
        print(f"Review: {item}")

    # Explain the difference between Limit and actual results
    explain_limit_vs_results(response)

    # Check if there are more results
    if "LastEvaluatedKey" in response:
        print("\nThere are more results available. Use the LastEvaluatedKey for pagination.")
    else:
        print("\nAll matching results have been retrieved.")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### ネストされた属性を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithNestedAttributes_python_3_topic"></a>

以下のコード例は、ネストされた属性を使用してテーブルをクエリする方法を示しています。
+ DynamoDB 項目のネストされた属性を使用してアクセスおよびフィルタリングします。
+ ネストされた要素を参照するには、ドキュメントパス式を使用します。

**SDK for Python (Boto3)**  
を使用して、ネストされた属性を持つ DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
from typing import Any, Dict, List

import boto3
from boto3.dynamodb.conditions import Attr, Key


def query_with_nested_attributes(
    table_name: str,
    partition_key_name: str,
    partition_key_value: str,
    nested_path: str,
    comparison_operator: str,
    comparison_value: Any,
) -> Dict[str, Any]:
    """
    Query a DynamoDB table and filter by nested attributes.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        nested_path (str): The path to the nested attribute (e.g., 'specs.weight').
        comparison_operator (str): The comparison operator to use ('=', '!=', '<', '<=', '>', '>=').
        comparison_value (any): The value to compare against.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Build the filter expression based on the nested attribute path and comparison operator
    filter_expression = None
    if comparison_operator == "=":
        filter_expression = Attr(nested_path).eq(comparison_value)
    elif comparison_operator == "!=":
        filter_expression = Attr(nested_path).ne(comparison_value)
    elif comparison_operator == "<":
        filter_expression = Attr(nested_path).lt(comparison_value)
    elif comparison_operator == "<=":
        filter_expression = Attr(nested_path).lte(comparison_value)
    elif comparison_operator == ">":
        filter_expression = Attr(nested_path).gt(comparison_value)
    elif comparison_operator == ">=":
        filter_expression = Attr(nested_path).gte(comparison_value)
    elif comparison_operator == "contains":
        filter_expression = Attr(nested_path).contains(comparison_value)
    elif comparison_operator == "begins_with":
        filter_expression = Attr(nested_path).begins_with(comparison_value)

    # Execute the query with the filter expression
    response = table.query(KeyConditionExpression=key_condition, FilterExpression=filter_expression)

    return response


def query_with_multiple_nested_attributes(
    table_name: str,
    partition_key_name: str,
    partition_key_value: str,
    nested_conditions: List[Dict[str, Any]],
) -> Dict[str, Any]:
    """
    Query a DynamoDB table and filter by multiple nested attributes.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        nested_conditions (list): A list of dictionaries, each containing:
            - path (str): The path to the nested attribute
            - operator (str): The comparison operator
            - value (any): The value to compare against

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    # Build the combined filter expression for all nested attributes
    combined_filter = None

    for condition in nested_conditions:
        if not isinstance(condition, dict):
            continue
        path = condition.get("path", "")
        operator = condition.get("operator", "")
        value = condition.get("value")

        if not path or not operator:
            continue

        # Build the individual filter expression
        current_filter = None
        if operator == "=":
            current_filter = Attr(path).eq(value)
        elif operator == "!=":
            current_filter = Attr(path).ne(value)
        elif operator == "<":
            current_filter = Attr(path).lt(value)
        elif operator == "<=":
            current_filter = Attr(path).lte(value)
        elif operator == ">":
            current_filter = Attr(path).gt(value)
        elif operator == ">=":
            current_filter = Attr(path).gte(value)
        elif operator == "contains":
            current_filter = Attr(path).contains(value)
        elif operator == "begins_with":
            current_filter = Attr(path).begins_with(value)

        # Combine with the existing filter using AND
        if current_filter:
            if combined_filter is None:
                combined_filter = current_filter
            else:
                combined_filter = combined_filter & current_filter

    # Execute the query with the combined filter expression
    response = table.query(KeyConditionExpression=key_condition, FilterExpression=combined_filter)

    return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### ページ分割を使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithPagination_python_3_topic"></a>

以下のコード例は、ページ分割を使用してテーブルをクエリする方法を示しています。
+ DynamoDB クエリ結果のページ分割を実装します。
+ LastEvaluatedKey を使用して後続のページを取得します。
+ Limit パラメータを使用して、ページあたりの項目数を制御します。

**SDK for Python (Boto3)**  
を使用してページ分割で DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
import boto3
from boto3.dynamodb.conditions import Key


def query_with_pagination(
    table_name, partition_key_name, partition_key_value, page_size=25, max_pages=None
):
    """
    Query a DynamoDB table with pagination to handle large result sets.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        page_size (int, optional): The number of items to return per page. Defaults to 25.
        max_pages (int, optional): The maximum number of pages to retrieve. If None, retrieves all pages.

    Returns:
        list: All items retrieved from the query across all pages.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Initialize variables for pagination
    last_evaluated_key = None
    page_count = 0
    all_items = []

    # Paginate through the results
    while True:
        # Check if we've reached the maximum number of pages
        if max_pages is not None and page_count >= max_pages:
            break

        # Prepare the query parameters
        query_params = {
            "KeyConditionExpression": Key(partition_key_name).eq(partition_key_value),
            "Limit": page_size,
        }

        # Add the ExclusiveStartKey if we have a LastEvaluatedKey from a previous query
        if last_evaluated_key:
            query_params["ExclusiveStartKey"] = last_evaluated_key

        # Execute the query
        response = table.query(**query_params)

        # Process the current page of results
        items = response.get("Items", [])
        all_items.extend(items)

        # Update pagination tracking
        page_count += 1

        # Get the LastEvaluatedKey for the next page, if any
        last_evaluated_key = response.get("LastEvaluatedKey")

        # If there's no LastEvaluatedKey, we've reached the end of the results
        if not last_evaluated_key:
            break

    return all_items


def query_with_pagination_generator(
    table_name, partition_key_name, partition_key_value, page_size=25
):
    """
    Query a DynamoDB table with pagination using a generator to handle large result sets.
    This approach is memory-efficient as it yields one page at a time.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        page_size (int, optional): The number of items to return per page. Defaults to 25.

    Yields:
        tuple: A tuple containing (items, page_number, last_page) where:
            - items is a list of items for the current page
            - page_number is the current page number (starting from 1)
            - last_page is a boolean indicating if this is the last page
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Initialize variables for pagination
    last_evaluated_key = None
    page_number = 0

    # Paginate through the results
    while True:
        # Prepare the query parameters
        query_params = {
            "KeyConditionExpression": Key(partition_key_name).eq(partition_key_value),
            "Limit": page_size,
        }

        # Add the ExclusiveStartKey if we have a LastEvaluatedKey from a previous query
        if last_evaluated_key:
            query_params["ExclusiveStartKey"] = last_evaluated_key

        # Execute the query
        response = table.query(**query_params)

        # Get the current page of results
        items = response.get("Items", [])
        page_number += 1

        # Get the LastEvaluatedKey for the next page, if any
        last_evaluated_key = response.get("LastEvaluatedKey")

        # Determine if this is the last page
        is_last_page = last_evaluated_key is None

        # Yield the current page of results
        yield (items, page_number, is_last_page)

        # If there's no LastEvaluatedKey, we've reached the end of the results
        if is_last_page:
            break
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### 強力な整合性のある読み込みを使用してテーブルをクエリする
<a name="dynamodb_Scenarios_QueryWithStronglyConsistentReads_python_3_topic"></a>

次のコード例は、強力な整合性のある読み込みを使用してテーブルをクエリする方法を示しています。
+ DynamoDB クエリの整合性レベルを設定します。
+ 強力な整合性のある読み込みを使用して最新のデータを取得します。
+ 結果整合性と強力な整合性のトレードオフを理解します。

**SDK for Python (Boto3)**  
を使用して、強力な整合性のある読み取りのための オプションを使用して DynamoDB テーブルをクエリします AWS SDK for Python (Boto3)。  

```
import time

import boto3
from boto3.dynamodb.conditions import Key


def query_with_consistent_read(
    table_name,
    partition_key_name,
    partition_key_value,
    sort_key_name=None,
    sort_key_value=None,
    consistent_read=True,
):
    """
    Query a DynamoDB table with the option for strongly consistent reads.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str, optional): The name of the sort key attribute.
        sort_key_value (str, optional): The value of the sort key to query.
        consistent_read (bool, optional): Whether to use strongly consistent reads. Defaults to True.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the key condition expression
    key_condition = Key(partition_key_name).eq(partition_key_value)

    if sort_key_name and sort_key_value:
        key_condition = key_condition & Key(sort_key_name).eq(sort_key_value)

    # Perform the query with the consistent read option
    response = table.query(KeyConditionExpression=key_condition, ConsistentRead=consistent_read)

    return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### TTL 項目のクエリ
<a name="dynamodb_QueryFilteredTTL_python_3_topic"></a>

次のコード例は、TTL 項目をクエリする方法を示しています。

**SDK for Python (Boto3)**  
を使用して DynamoDB テーブルで TTL 項目を収集するためにフィルタリングされた式をクエリします AWS SDK for Python (Boto3)。  

```
from datetime import datetime

import boto3


def query_dynamodb_items(table_name, partition_key):
    """

    :param table_name: Name of the DynamoDB table
    :param partition_key:
    :return:
    """
    try:
        # Initialize a DynamoDB resource
        dynamodb = boto3.resource("dynamodb", region_name="us-east-1")

        # Specify your table
        table = dynamodb.Table(table_name)

        # Get the current time in epoch format
        current_time = int(datetime.now().timestamp())

        # Perform the query operation with a filter expression to exclude expired items
        # response = table.query(
        #    KeyConditionExpression=boto3.dynamodb.conditions.Key('partitionKey').eq(partition_key),
        #    FilterExpression=boto3.dynamodb.conditions.Attr('expireAt').gt(current_time)
        # )
        response = table.query(
            KeyConditionExpression=dynamodb.conditions.Key("partitionKey").eq(partition_key),
            FilterExpression=dynamodb.conditions.Attr("expireAt").gt(current_time),
        )

        # Print the items that are not expired
        for item in response["Items"]:
            print(item)

    except Exception as e:
        print(f"Error querying items: {e}")


# Call the function with your values
query_dynamodb_items("Music", "your-partition-key-value")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### 日付と時刻のパターンを使用してテーブルをクエリする
<a name="dynamodb_Scenario_DateTimeQueries_python_3_topic"></a>

次のコード例は、日付と時刻のパターンを使用してテーブルをクエリする方法を示しています。
+ DynamoDB に日付/時刻値を保存してクエリします。
+ ソートキーを使用して日付範囲クエリを実装します。
+ 有効なクエリを行うために日付文字列をフォーマットします。

**SDK for Python (Boto3)**  
でソートキーの日付範囲を使用してクエリを実行します AWS SDK for Python (Boto3)。  

```
from datetime import datetime, timedelta

import boto3
from boto3.dynamodb.conditions import Key


def query_with_date_range(
    table_name, partition_key_name, partition_key_value, sort_key_name, start_date, end_date
):
    """
    Query a DynamoDB table with a date range on the sort key.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str): The name of the sort key attribute (containing date values).
        start_date (datetime): The start date for the query range.
        end_date (datetime): The end date for the query range.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Format the date values as ISO 8601 strings
    # DynamoDB works well with ISO format for date values
    start_date_str = start_date.isoformat()
    end_date_str = end_date.isoformat()

    # Perform the query with a date range on the sort key using BETWEEN operator
    key_condition = Key(partition_key_name).eq(partition_key_value) & Key(sort_key_name).between(
        start_date_str, end_date_str
    )

    response = table.query(
        KeyConditionExpression=key_condition,
        ExpressionAttributeValues={
            ":pk_val": partition_key_value,
            ":start_date": start_date_str,
            ":end_date": end_date_str,
        },
    )

    return response


def query_with_date_range_by_month(
    table_name, partition_key_name, partition_key_value, sort_key_name, year, month
):
    """
    Query a DynamoDB table for a specific month's data.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str): The name of the sort key attribute (containing date values).
        year (int): The year to query.
        month (int): The month to query (1-12).

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Calculate the start and end dates for the specified month
    if month == 12:
        next_year = year + 1
        next_month = 1
    else:
        next_year = year
        next_month = month + 1

    start_date = datetime(year, month, 1)
    end_date = datetime(next_year, next_month, 1) - timedelta(microseconds=1)

    # Format the date values as ISO 8601 strings
    start_date_str = start_date.isoformat()
    end_date_str = end_date.isoformat()

    # Perform the query with a date range on the sort key
    key_condition = Key(partition_key_name).eq(partition_key_value) & Key(sort_key_name).between(
        start_date_str, end_date_str
    )

    response = table.query(KeyConditionExpression=key_condition)

    return response
```
で日時変数を使用してクエリを実行します AWS SDK for Python (Boto3)。  

```
from datetime import datetime, timedelta

import boto3
from boto3.dynamodb.conditions import Key


def query_with_datetime(
    table_name, partition_key_name, partition_key_value, sort_key_name, start_date, end_date
):
    """
    Query a DynamoDB table with a date range filter on the sort key.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        sort_key_name (str): The name of the sort key attribute (containing date/time values).
        start_date (datetime): The start date/time for the query range.
        end_date (datetime): The end date/time for the query range.

    Returns:
        dict: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Format the date/time values as ISO 8601 strings
    # DynamoDB works well with ISO format for date/time values
    start_date_str = start_date.isoformat()
    end_date_str = end_date.isoformat()

    # Perform the query with a date range on the sort key
    key_condition = Key(partition_key_name).eq(partition_key_value) & Key(sort_key_name).between(
        start_date_str, end_date_str
    )

    response = table.query(
        KeyConditionExpression=key_condition,
        ExpressionAttributeValues={
            ":pk_val": partition_key_value,
            ":start_date": start_date_str,
            ":end_date": end_date_str,
        },
    )

    return response



def example_usage():
    """Example of how to use the query_with_datetime function."""
    # Example parameters
    table_name = "Events"
    partition_key_name = "EventType"
    partition_key_value = "UserLogin"
    sort_key_name = "Timestamp"

    # Create date/time variables for the query
    end_date = datetime.now()
    start_date = end_date - timedelta(days=7)  # Query events from the last 7 days

    print(f"Querying events from {start_date.isoformat()} to {end_date.isoformat()}")

    # Execute the query
    response = query_with_datetime(
        table_name, partition_key_name, partition_key_value, sort_key_name, start_date, end_date
    )

    # Process the results
    items = response.get("Items", [])
    print(f"Found {len(items)} items")

    for item in items:
        print(f"Event: {item}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Query](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)」を参照してください。

### 式順序の更新を理解する
<a name="dynamodb_Scenario_UpdateExpressionOrder_python_3_topic"></a>

次のコード例は、式順序の更新を理解する方法を示しています。
+ DynamoDB が更新式を処理する方法について説明します。
+ 更新式のオペレーションの順序を理解します。
+ 式の評価を理解することで、予期しない結果を回避できます。

**SDK for Python (Boto3)**  
を使用して、式の更新順序をデモンストレーションします AWS SDK for Python (Boto3)。  

```
import boto3
import json
from typing import Any, Dict, Optional


def update_with_multiple_actions(
    table_name: str,
    key: Dict[str, Any],
    update_expression: str,
    expression_attribute_names: Optional[Dict[str, str]] = None,
    expression_attribute_values: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Update an item with multiple actions in a single update expression.

    This function demonstrates how to use multiple actions in a single update expression
    and how DynamoDB processes these actions.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        update_expression (str): The update expression with multiple actions.
        expression_attribute_names (Optional[Dict[str, str]]): Expression attribute name placeholders.
        expression_attribute_values (Optional[Dict[str, Any]]): Expression attribute value placeholders.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Prepare the update parameters
    update_params = {
        "Key": key,
        "UpdateExpression": update_expression,
        "ReturnValues": "UPDATED_NEW",
    }

    # Add expression attribute names if provided
    if expression_attribute_names:
        update_params["ExpressionAttributeNames"] = expression_attribute_names

    # Add expression attribute values if provided
    if expression_attribute_values:
        update_params["ExpressionAttributeValues"] = expression_attribute_values

    # Execute the update
    response = table.update_item(**update_params)

    return response


def demonstrate_value_copying(table_name: str, key: Dict[str, Any]) -> Dict[str, Any]:
    """
    Demonstrate that variables hold copies of existing values before modifications.

    This function creates an item with initial values, then updates it with an expression
    that uses the values of attributes before they are modified in the same expression.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to create and update.

    Returns:
        Dict[str, Any]: A dictionary containing the results of the demonstration.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Step 1: Create an item with initial values
    initial_item = key.copy()
    initial_item.update({"a": 1, "b": 2, "c": 3})

    table.put_item(Item=initial_item)

    # Step 2: Get the item to verify initial state
    response_before = table.get_item(Key=key)
    item_before = response_before.get("Item", {})

    # Step 3: Update the item with an expression that uses values before they are modified
    # This expression removes 'a', then sets 'b' to the value of 'a', and 'c' to the value of 'b'
    update_response = table.update_item(
        Key=key, UpdateExpression="REMOVE a SET b = a, c = b", ReturnValues="UPDATED_NEW"
    )

    # Step 4: Get the item to verify final state
    response_after = table.get_item(Key=key)
    item_after = response_after.get("Item", {})

    # Return the results
    return {
        "initial_state": item_before,
        "update_response": update_response,
        "final_state": item_after,
    }


def demonstrate_action_order(table_name: str, key: Dict[str, Any]) -> Dict[str, Any]:
    """
    Demonstrate the order in which different action types are processed.

    This function creates an item with initial values, then updates it with an expression
    that includes multiple action types (SET, REMOVE, ADD, DELETE) to show the order
    in which they are processed.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to create and update.

    Returns:
        Dict[str, Any]: A dictionary containing the results of the demonstration.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Step 1: Create an item with initial values
    initial_item = key.copy()
    initial_item.update(
        {
            "counter": 10,
            "set_attr": set(["A", "B", "C"]),
            "to_remove": "This will be removed",
            "to_modify": "Original value",
        }
    )

    table.put_item(Item=initial_item)

    # Step 2: Get the item to verify initial state
    response_before = table.get_item(Key=key)
    item_before = response_before.get("Item", {})

    # Step 3: Update the item with multiple action types
    # The actions will be processed in this order: REMOVE, SET, ADD, DELETE
    update_response = table.update_item(
        Key=key,
        UpdateExpression="REMOVE to_remove SET to_modify = :new_value ADD counter :increment DELETE set_attr :elements",
        ExpressionAttributeValues={
            ":new_value": "Updated value",
            ":increment": 5,
            ":elements": set(["B"]),
        },
        ReturnValues="UPDATED_NEW",
    )

    # Step 4: Get the item to verify final state
    response_after = table.get_item(Key=key)
    item_after = response_after.get("Item", {})

    # Return the results
    return {
        "initial_state": item_before,
        "update_response": update_response,
        "final_state": item_after,
    }


def update_with_multiple_set_actions(
    table_name: str, key: Dict[str, Any], attributes: Dict[str, Any]
) -> Dict[str, Any]:
    """
    Update multiple attributes with a single SET action.

    This function demonstrates how to update multiple attributes in a single SET action,
    which is more efficient than using multiple separate update operations.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        attributes (Dict[str, Any]): The attributes to update and their new values.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Build the update expression and expression attribute values
    update_expression = "SET "
    expression_attribute_values = {}

    # Add each attribute to the update expression
    for i, (attr_name, attr_value) in enumerate(attributes.items()):
        value_placeholder = f":val{i}"

        if i > 0:
            update_expression += ", "
        update_expression += f"{attr_name} = {value_placeholder}"

        expression_attribute_values[value_placeholder] = attr_value

    # Execute the update
    response = table.update_item(
        Key=key,
        UpdateExpression=update_expression,
        ExpressionAttributeValues=expression_attribute_values,
        ReturnValues="UPDATED_NEW",
    )

    return response


def update_with_conditional_value_copying(
    table_name: str,
    key: Dict[str, Any],
    source_attribute: str,
    target_attribute: str,
    default_value: Any,
) -> Dict[str, Any]:
    """
    Update an attribute with a value from another attribute or a default value.

    This function demonstrates how to use if_not_exists to conditionally copy a value
    from one attribute to another, or use a default value if the source doesn't exist.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        source_attribute (str): The attribute to copy the value from.
        target_attribute (str): The attribute to update.
        default_value (Any): The default value to use if the source attribute doesn't exist.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use if_not_exists to conditionally copy the value
    response = table.update_item(
        Key=key,
        UpdateExpression=f"SET {target_attribute} = if_not_exists({source_attribute}, :default)",
        ExpressionAttributeValues={":default": default_value},
        ReturnValues="UPDATED_NEW",
    )

    return response
```
での更新式の順序の使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use update expression order of operations in DynamoDB."""
    # Example parameters
    table_name = "OrderProcessing"
    key = {"OrderId": "order123"}

    print("Example 1: Demonstrating value copying in update expressions")
    try:
        results = demonstrate_value_copying(table_name=table_name, key=key)

        print(f"Initial state: {json.dumps(results['initial_state'], default=str)}")
        print(f"Update response: {json.dumps(results['update_response'], default=str)}")
        print(f"Final state: {json.dumps(results['final_state'], default=str)}")

        print("\nExplanation:")
        print("1. The initial state had a=1, b=2, c=3")
        print("2. The update expression 'REMOVE a SET b = a, c = b' did the following:")
        print("   - Copied the value of 'a' (which was 1) to be used for 'b'")
        print("   - Copied the value of 'b' (which was 2) to be used for 'c'")
        print("   - Removed the attribute 'a'")
        print("3. The final state has b=1, c=2, and 'a' is removed")
        print(
            "4. This demonstrates that DynamoDB uses the values of attributes as they were BEFORE any modifications"
        )
    except Exception as e:
        print(f"Error demonstrating value copying: {e}")

    print("\nExample 2: Demonstrating the order of different action types")
    try:
        results = demonstrate_action_order(table_name=table_name, key={"OrderId": "order456"})

        print(f"Initial state: {json.dumps(results['initial_state'], default=str)}")
        print(f"Update response: {json.dumps(results['update_response'], default=str)}")
        print(f"Final state: {json.dumps(results['final_state'], default=str)}")

        print("\nExplanation:")
        print("1. The update expression contained multiple action types: REMOVE, SET, ADD, DELETE")
        print("2. DynamoDB processes these actions in this order: REMOVE, SET, ADD, DELETE")
        print("3. First, 'to_remove' was removed")
        print("4. Then, 'to_modify' was set to a new value")
        print("5. Next, 'counter' was incremented by 5")
        print("6. Finally, 'B' was removed from the set attribute")
    except Exception as e:
        print(f"Error demonstrating action order: {e}")

    print("\nExample 3: Updating multiple attributes in a single SET action")
    try:
        response = update_with_multiple_set_actions(
            table_name=table_name,
            key={"OrderId": "order789"},
            attributes={
                "Status": "Shipped",
                "ShippingDate": "2025-05-14",
                "TrackingNumber": "1Z999AA10123456784",
            },
        )

        print(
            f"Multiple attributes updated successfully: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error updating multiple attributes: {e}")

    print("\nExample 4: Conditional value copying with if_not_exists")
    try:
        response = update_with_conditional_value_copying(
            table_name=table_name,
            key={"OrderId": "order101"},
            source_attribute="PreferredShippingMethod",
            target_attribute="ShippingMethod",
            default_value="Standard",
        )

        print(
            f"Conditional value copying result: {json.dumps(response.get('Attributes', {}), default=str)}"
        )
    except Exception as e:
        print(f"Error with conditional value copying: {e}")

    print("\nKey Points About Update Expression Order of Operations:")
    print(
        "1. Variables in expressions hold copies of attribute values as they existed BEFORE any modifications"
    )
    print(
        "2. Multiple actions in an update expression are processed in this order: REMOVE, SET, ADD, DELETE"
    )
    print("3. Within each action type, operations are processed from left to right")
    print("4. You can reference the same attribute multiple times in an expression")
    print("5. You can use if_not_exists() to conditionally set values based on attribute existence")
    print(
        "6. Using a single update expression with multiple actions is more efficient than multiple separate updates"
    )
    print("7. The update expression is atomic - either all actions succeed or none do")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### テーブルのウォームスループット設定を更新する
<a name="dynamodb_UpdateTableWarmThroughput_python_3_topic"></a>

次のコード例は、テーブルのウォームスループット設定を更新する方法を示しています。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3)を使用して既存の DynamoDB テーブルのウォームスループット設定を更新します。  

```
from boto3 import client
from botocore.exceptions import ClientError


def update_dynamodb_table_warm_throughput(
    table_name,
    table_read_units,
    table_write_units,
    gsi_name,
    gsi_read_units,
    gsi_write_units,
    region_name="us-east-1",
):
    """
    Updates the warm throughput of a DynamoDB table and a global secondary index.

    :param table_name: The name of the table to update.
    :param table_read_units: The new read units per second for the table's warm throughput.
    :param table_write_units: The new write units per second for the table's warm throughput.
    :param gsi_name: The name of the global secondary index to update.
    :param gsi_read_units: The new read units per second for the GSI's warm throughput.
    :param gsi_write_units: The new write units per second for the GSI's warm throughput.
    :param region_name: The AWS Region name to target. defaults to us-east-1
    :return: The response from the update_table operation
    """
    try:
        ddb = client("dynamodb", region_name=region_name)

        # Update the table's warm throughput
        table_warm_throughput = {
            "ReadUnitsPerSecond": table_read_units,
            "WriteUnitsPerSecond": table_write_units,
        }

        # Update the global secondary index's warm throughput
        gsi_warm_throughput = {
            "ReadUnitsPerSecond": gsi_read_units,
            "WriteUnitsPerSecond": gsi_write_units,
        }

        # Construct the global secondary index update
        global_secondary_index_update = [
            {"Update": {"IndexName": gsi_name, "WarmThroughput": gsi_warm_throughput}}
        ]

        # Construct the update table request
        update_table_request = {
            "TableName": table_name,
            "GlobalSecondaryIndexUpdates": global_secondary_index_update,
            "WarmThroughput": table_warm_throughput,
        }

        # Update the table
        response = ddb.update_table(**update_table_request)
        print("Table updated successfully!")
        return response  # Make sure to return the response
    except ClientError as e:
        print(f"Error updating table: {e}")
        raise e
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[UpdateTable](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateTable)」を参照してください。

### 項目の TTL を更新する
<a name="dynamodb_UpdateItemTTL_python_3_topic"></a>

次のコード例は、項目の TTL を更新する方法を示しています。

**SDK for Python (Boto3)**  

```
from datetime import datetime, timedelta

import boto3


def update_dynamodb_item(table_name, region, primary_key, sort_key):
    """
    Update an existing DynamoDB item with a TTL.
    :param table_name: Name of the DynamoDB table
    :param region: AWS Region of the table - example `us-east-1`
    :param primary_key: one attribute known as the partition key.
    :param sort_key: Also known as a range attribute.
    :return: Void (nothing)
    """
    try:
        # Create the DynamoDB resource.
        dynamodb = boto3.resource("dynamodb", region_name=region)
        table = dynamodb.Table(table_name)

        # Get the current time in epoch second format
        current_time = int(datetime.now().timestamp())

        # Calculate the expireAt time (90 days from now) in epoch second format
        expire_at = int((datetime.now() + timedelta(days=90)).timestamp())

        table.update_item(
            Key={"partitionKey": primary_key, "sortKey": sort_key},
            UpdateExpression="set updatedAt=:c, expireAt=:e",
            ExpressionAttributeValues={":c": current_time, ":e": expire_at},
        )

        print("Item updated successfully.")
    except Exception as e:
        print(f"Error updating item: {e}")


# Replace with your own values
update_dynamodb_item(
    "your-table-name", "us-west-2", "your-partition-key-value", "your-sort-key-value"
)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_python_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例は、 AWS Lambda 関数を対象とする Amazon API Gateway REST API を作成して使用する方法を示しています。Lambda ハンドラーは、HTTP メソッドに基づいてルーティングする方法を示します。クエリ文字列、ヘッダー、および本文からデータを取得する方法。そして、JSON 応答を返す方法。  
+ Lambda 関数をデプロイします。
+ API ゲートウェイ REST API を作成します。
+ Lambda 関数をターゲットとする REST リソースを作成します。
+ API Gateway に Lambda 関数を呼び出す権限を付与します。
+ リクエストパッケージを使用して、REST API にリクエストを送信します。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### アトミックカウンタオペレーションを使用する
<a name="dynamodb_Scenario_AtomicCounterOperations_python_3_topic"></a>

次のコード例は、DynamoDB でアトミックカウンタオペレーションを使用する方法を示しています。
+ ADD および SET オペレーションを使用してカウンタをアトミックに増分します。
+ 存在しない可能性のあるカウンターを安全に増分します。
+ カウンターオペレーションに楽観的ロックを実装します。

**SDK for Python (Boto3)**  
を使用してアトミックカウンターオペレーションをデモンストレーションします AWS SDK for Python (Boto3)。  

```
import boto3
from botocore.exceptions import ClientError
from typing import Any, Dict, Union


def increment_counter_with_add(
    table_name: str, key: Dict[str, Any], counter_name: str, increment_value: int = 1
) -> Dict[str, Any]:
    """
    Increment a counter attribute using the ADD operation.

    This function demonstrates the atomic ADD operation, which is ideal for
    incrementing counters without the risk of race conditions.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        counter_name (str): The name of the counter attribute.
        increment_value (int, optional): The value to increment by. Defaults to 1.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use the ADD operation to atomically increment the counter
    response = table.update_item(
        Key=key,
        UpdateExpression="ADD #counter :increment",
        ExpressionAttributeNames={"#counter": counter_name},
        ExpressionAttributeValues={":increment": increment_value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def increment_counter_with_set(
    table_name: str, key: Dict[str, Any], counter_name: str, increment_value: int = 1
) -> Dict[str, Any]:
    """
    Increment a counter attribute using the SET operation with an expression.

    This function demonstrates using SET with an expression to increment a counter.
    While this works, it's generally recommended to use ADD for simple increments.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        counter_name (str): The name of the counter attribute.
        increment_value (int, optional): The value to increment by. Defaults to 1.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use the SET operation with an expression to increment the counter
    response = table.update_item(
        Key=key,
        UpdateExpression="SET #counter = #counter + :increment",
        ExpressionAttributeNames={"#counter": counter_name},
        ExpressionAttributeValues={":increment": increment_value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def increment_counter_safely(
    table_name: str,
    key: Dict[str, Any],
    counter_name: str,
    increment_value: int = 1,
    initial_value: int = 0,
) -> Dict[str, Any]:
    """
    Increment a counter attribute safely, handling the case where it might not exist.

    This function demonstrates a best practice for incrementing counters by using
    the if_not_exists function to handle the case where the counter doesn't exist yet.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        counter_name (str): The name of the counter attribute.
        increment_value (int, optional): The value to increment by. Defaults to 1.
        initial_value (int, optional): The initial value if the counter doesn't exist. Defaults to 0.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use SET with if_not_exists to safely increment the counter
    response = table.update_item(
        Key=key,
        UpdateExpression="SET #counter = if_not_exists(#counter, :initial) + :increment",
        ExpressionAttributeNames={"#counter": counter_name},
        ExpressionAttributeValues={":increment": increment_value, ":initial": initial_value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def atomic_conditional_increment(
    table_name: str,
    key: Dict[str, Any],
    counter_name: str,
    condition_attribute: str,
    condition_value: Any,
    increment_value: int = 1,
) -> Union[Dict[str, Any], None]:
    """
    Atomically increment a counter only if a condition is met.

    This function demonstrates combining atomic counter operations with
    conditional expressions for more complex update scenarios.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        counter_name (str): The name of the counter attribute.
        condition_attribute (str): The attribute to check in the condition.
        condition_value (Any): The value to compare against.
        increment_value (int, optional): The value to increment by. Defaults to 1.

    Returns:
        Optional[Dict[str, Any]]: The response from DynamoDB if successful, None if condition failed.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    try:
        # Use ADD with a condition expression
        response = table.update_item(
            Key=key,
            UpdateExpression="ADD #counter :increment",
            ConditionExpression="#condition = :value",
            ExpressionAttributeNames={"#counter": counter_name, "#condition": condition_attribute},
            ExpressionAttributeValues={":increment": increment_value, ":value": condition_value},
            ReturnValues="UPDATED_NEW",
        )
        return response
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            # Condition was not met
            return None
        else:
            # Other error occurred
            raise
```
でのアトミックカウンターオペレーションの使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use the atomic counter operations functions."""
    # Example parameters
    table_name = "GameScores"
    key = {"UserId": "user123", "GameId": "game456"}
    counter_name = "Score"

    print("Example 1: Incrementing a counter with ADD operation")
    try:
        response = increment_counter_with_add(
            table_name=table_name, key=key, counter_name=counter_name, increment_value=10
        )
        print(
            f"Counter incremented successfully. New value: {response.get('Attributes', {}).get(counter_name)}"
        )
    except Exception as e:
        print(f"Error incrementing counter with ADD: {e}")

    print("\nExample 2: Incrementing a counter with SET operation")
    try:
        response = increment_counter_with_set(
            table_name=table_name, key=key, counter_name=counter_name, increment_value=5
        )
        print(
            f"Counter incremented successfully. New value: {response.get('Attributes', {}).get(counter_name)}"
        )
    except Exception as e:
        print(f"Error incrementing counter with SET: {e}")

    print("\nExample 3: Safely incrementing a counter that might not exist")
    try:
        new_key = {"UserId": "newuser789", "GameId": "game456"}
        response = increment_counter_safely(
            table_name=table_name,
            key=new_key,
            counter_name=counter_name,
            increment_value=15,
            initial_value=100,
        )
        print(
            f"Counter safely incremented. New value: {response.get('Attributes', {}).get(counter_name)}"
        )
    except Exception as e:
        print(f"Error safely incrementing counter: {e}")

    print("\nExample 4: Conditional counter increment")
    try:
        # Fix for mypy: Handle the case where response might be None
        result = atomic_conditional_increment(
            table_name=table_name,
            key=key,
            counter_name="Achievements",
            condition_attribute="Level",
            condition_value=5,
            increment_value=1,
        )

        if result is not None:
            print(
                f"Conditional increment succeeded. New value: {result.get('Attributes', {}).get('Achievements')}"
            )
        else:
            print("Conditional increment failed because condition was not met.")
        if response:
            print(
                f"Conditional increment succeeded. New value: {response.get('Attributes', {}).get('Achievements')}"
            )
        else:
            print("Conditional increment failed because condition was not met.")
    except Exception as e:
        print(f"Error with conditional increment: {e}")

    print("\nComparison of ADD vs SET for counter operations:")
    print("1. ADD is specifically designed for atomic numeric increments and set operations")
    print("2. SET with an expression can be used for more complex calculations")
    print("3. Both operations are atomic, preventing race conditions")
    print("4. ADD is more concise for simple increments")
    print("5. SET with if_not_exists() is recommended when the attribute might not exist")
    print("6. For counters, ADD is generally preferred for clarity and simplicity")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

### 条件付きオペレーションを使用する
<a name="dynamodb_Scenario_ConditionalOperations_python_3_topic"></a>

次のコード例は、DynamoDB で条件付きオペレーションを使用する方法を示しています。
+ データの上書きを防ぐため、条件付き書き込みを実装します。
+ 条件式を使用してビジネスルールを適用します。
+ 条件付きチェックの失敗を適切に処理します。

**SDK for Python (Boto3)**  
を使用して条件付きオペレーションをデモンストレーションします AWS SDK for Python (Boto3)。  

```
import boto3
from botocore.exceptions import ClientError
from typing import Any, Dict, Optional, Tuple, Union


def conditional_update(
    table_name: str,
    key: Dict[str, Any],
    condition_attribute: str,
    condition_value: Any,
    update_attribute: str,
    update_value: Any,
) -> Tuple[bool, Optional[Dict[str, Any]]]:
    """
    Update an item only if a condition is met.

    This function demonstrates how to perform a conditional update operation
    and determine if the condition was met.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        condition_attribute (str): The attribute to check in the condition.
        condition_value (Any): The value to compare against.
        update_attribute (str): The attribute to update.
        update_value (Any): The new value to set.

    Returns:
        Tuple[bool, Optional[Dict[str, Any]]]: A tuple containing:
            - A boolean indicating if the update succeeded
            - The response from DynamoDB if successful, None otherwise
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    try:
        # Perform the conditional update
        response = table.update_item(
            Key=key,
            UpdateExpression="SET #update_attr = :update_val",
            ConditionExpression="#cond_attr = :cond_val",
            ExpressionAttributeNames={
                "#update_attr": update_attribute,
                "#cond_attr": condition_attribute,
            },
            ExpressionAttributeValues={":update_val": update_value, ":cond_val": condition_value},
            ReturnValues="UPDATED_NEW",
        )
        # Update succeeded, condition was met
        return True, response
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            # Condition was not met
            return False, None
        else:
            # Other error occurred
            raise


def conditional_delete(
    table_name: str, key: Dict[str, Any], condition_attribute: str, condition_value: Any
) -> bool:
    """
    Delete an item only if a condition is met.

    This function demonstrates how to perform a conditional delete operation
    and determine if the condition was met.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to delete.
        condition_attribute (str): The attribute to check in the condition.
        condition_value (Any): The value to compare against.

    Returns:
        bool: True if the delete succeeded (condition was met), False otherwise.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    try:
        # Perform the conditional delete
        table.delete_item(
            Key=key,
            ConditionExpression="#attr = :val",
            ExpressionAttributeNames={"#attr": condition_attribute},
            ExpressionAttributeValues={":val": condition_value},
        )
        # Delete succeeded, condition was met
        return True
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            # Condition was not met
            return False
        else:
            # Other error occurred
            raise


def optimistic_locking_update(
    table_name: str,
    key: Dict[str, Any],
    version_attribute: str,
    update_attribute: str,
    update_value: Any,
) -> Tuple[bool, Optional[Dict[str, Any]]]:
    """
    Update an item using optimistic locking with a version attribute.

    This function demonstrates how to implement optimistic locking using
    a version attribute that is incremented with each update.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        version_attribute (str): The name of the version attribute.
        update_attribute (str): The attribute to update.
        update_value (Any): The new value to set.

    Returns:
        Tuple[bool, Optional[Dict[str, Any]]]: A tuple containing:
            - A boolean indicating if the update succeeded
            - The response from DynamoDB if successful, None otherwise
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # First, get the current version
    try:
        response = table.get_item(
            Key=key,
            ProjectionExpression=f"#{version_attribute}",
            ExpressionAttributeNames={f"#{version_attribute}": version_attribute},
        )

        item = response.get("Item", {})
        current_version = item.get(version_attribute, 0)

        # Now, try to update with a condition on the version
        try:
            update_response = table.update_item(
                Key=key,
                UpdateExpression=f"SET #{update_attribute} = :update_val, #{version_attribute} = :new_version",
                ConditionExpression=f"#{version_attribute} = :current_version",
                ExpressionAttributeNames={
                    f"#{update_attribute}": update_attribute,
                    f"#{version_attribute}": version_attribute,
                },
                ExpressionAttributeValues={
                    ":update_val": update_value,
                    ":current_version": current_version,
                    ":new_version": current_version + 1,
                },
                ReturnValues="UPDATED_NEW",
            )
            # Update succeeded
            return True, update_response
        except ClientError as e:
            if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
                # Version has changed, optimistic locking failed
                return False, None
            else:
                # Other error occurred
                raise
    except ClientError:
        # Error getting the item
        raise


def conditional_check_and_update(
    table_name: str,
    key: Dict[str, Any],
    check_attribute: str,
    check_value: Any,
    update_attribute: str,
    update_value: Any,
    create_if_not_exists: bool = False,
) -> Union[Dict[str, Any], None]:
    """
    Check if an attribute has a specific value and update another attribute if it does.

    This function demonstrates a more complex conditional update that can also
    create the item if it doesn't exist.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        check_attribute (str): The attribute to check in the condition.
        check_value (Any): The value to compare against.
        update_attribute (str): The attribute to update.
        update_value (Any): The new value to set.
        create_if_not_exists (bool, optional): Whether to create the item if it doesn't exist.

    Returns:
        Union[Dict[str, Any], None]: The response from DynamoDB if successful, None otherwise.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    try:
        if create_if_not_exists:
            # Use attribute_not_exists to create the item if it doesn't exist
            condition_expression = "attribute_not_exists(#pk) OR #check_attr = :check_val"
            update_expression = "SET #update_attr = :update_val, #check_attr = if_not_exists(#check_attr, :check_val)"

            # Get the partition key name from the key dictionary
            pk_name = next(iter(key))

            expression_attribute_names = {
                "#pk": pk_name,
                "#check_attr": check_attribute,
                "#update_attr": update_attribute,
            }
        else:
            # Only update if the check attribute has the expected value
            condition_expression = "#check_attr = :check_val"
            update_expression = "SET #update_attr = :update_val"

            expression_attribute_names = {
                "#check_attr": check_attribute,
                "#update_attr": update_attribute,
            }

        # Perform the conditional update
        response = table.update_item(
            Key=key,
            UpdateExpression=update_expression,
            ConditionExpression=condition_expression,
            ExpressionAttributeNames=expression_attribute_names,
            ExpressionAttributeValues={":check_val": check_value, ":update_val": update_value},
            ReturnValues="UPDATED_NEW",
        )
        return response
    except ClientError as e:
        if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
            # Condition was not met
            return None
        else:
            # Other error occurred
            raise
```
での条件付きオペレーションの使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use the conditional operations functions."""
    # Example parameters
    table_name = "Products"
    key = {"ProductId": "prod123"}

    print("Example 1: Conditional Update")
    try:
        # Update the price only if the current stock is greater than 10
        success, response = conditional_update(
            table_name=table_name,
            key=key,
            condition_attribute="Stock",
            condition_value=10,
            update_attribute="Price",
            update_value=99.99,
        )

        if success:
            # Fix for mypy: Handle the case where response might be None
            attributes = {} if response is None else response.get("Attributes", {})
            print(f"Update succeeded! New values: {attributes}")
        else:
            print("Update failed because the condition was not met.")
    except Exception as e:
        print(f"Error during conditional update: {e}")

    print("\nExample 2: Conditional Delete")
    try:
        # Delete the product only if it's discontinued
        success = conditional_delete(
            table_name=table_name,
            key=key,
            condition_attribute="Status",
            condition_value="Discontinued",
        )

        if success:
            print("Delete succeeded! The item was deleted.")
        else:
            print("Delete failed because the condition was not met.")
    except Exception as e:
        print(f"Error during conditional delete: {e}")

    print("\nExample 3: Optimistic Locking")
    try:
        # Update with optimistic locking using a version attribute
        success, response = optimistic_locking_update(
            table_name=table_name,
            key=key,
            version_attribute="Version",
            update_attribute="Description",
            update_value="Updated product description",
        )

        if success:
            # Fix for mypy: Handle the case where response might be None
            attributes = {} if response is None else response.get("Attributes", {})
            print(f"Optimistic locking update succeeded! New values: {attributes}")
        else:
            print("Optimistic locking update failed because the version has changed.")
    except Exception as e:
        print(f"Error during optimistic locking update: {e}")

    print("\nExample 4: Conditional Check and Update")
    try:
        # Update the featured status if the product is in stock
        response = conditional_check_and_update(
            table_name=table_name,
            key=key,
            check_attribute="InStock",
            check_value=True,
            update_attribute="Featured",
            update_value=True,
            create_if_not_exists=True,
        )

        if response:
            print(
                f"Conditional check and update succeeded! New values: {response.get('Attributes', {})}"
            )
        else:
            print("Conditional check and update failed because the condition was not met.")
    except Exception as e:
        print(f"Error during conditional check and update: {e}")

    print("\nUnderstanding Conditional Operations in DynamoDB:")
    print("1. Conditional operations help maintain data integrity")
    print("2. They prevent race conditions in concurrent environments")
    print("3. Failed conditions result in ConditionalCheckFailedException")
    print("4. No DynamoDB capacity is consumed when conditions fail")
    print("5. Optimistic locking is a common pattern using version attributes")
    print("6. Conditions can be combined with logical operators (AND, OR, NOT)")
    print("7. Conditions can use comparison operators (=, <>, <, <=, >, >=)")
    print(
        "8. attribute_exists() and attribute_not_exists() are useful for checking attribute presence"
    )
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [DeleteItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/DeleteItem)
  + [PutItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/PutItem)
  + [UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)

### 式の属性名を使用する
<a name="dynamodb_Scenario_ExpressionAttributeNames_python_3_topic"></a>

次のコード例は、DynamoDB で式の属性名を使用する方法を示しています。
+ DynamoDB 式で予約語を操作します。
+ 式の属性名のプレースホルダーを使用します。
+ 属性名の特殊文字を処理します。

**SDK for Python (Boto3)**  
を使用して式の属性名をデモンストレーションします AWS SDK for Python (Boto3)。  

```
import boto3
from botocore.exceptions import ClientError
from typing import Any, Dict, List


def use_reserved_word_attribute(
    table_name: str, key: Dict[str, Any], reserved_word: str, value: Any
) -> Dict[str, Any]:
    """
    Update an attribute whose name is a DynamoDB reserved word.

    This function demonstrates how to use expression attribute names to work with
    attributes that have names that are DynamoDB reserved words.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        reserved_word (str): The reserved word to use as an attribute name.
        value (Any): The value to set for the attribute.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use expression attribute names to handle the reserved word
    response = table.update_item(
        Key=key,
        UpdateExpression="SET #reserved_attr = :value",
        ExpressionAttributeNames={"#reserved_attr": reserved_word},
        ExpressionAttributeValues={":value": value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def use_special_character_attribute(
    table_name: str, key: Dict[str, Any], attribute_with_special_chars: str, value: Any
) -> Dict[str, Any]:
    """
    Update an attribute whose name contains special characters.

    This function demonstrates how to use expression attribute names to work with
    attributes that have names containing special characters like spaces, dots, or hyphens.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        attribute_with_special_chars (str): The attribute name with special characters.
        value (Any): The value to set for the attribute.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use expression attribute names to handle special characters
    response = table.update_item(
        Key=key,
        UpdateExpression="SET #special_attr = :value",
        ExpressionAttributeNames={"#special_attr": attribute_with_special_chars},
        ExpressionAttributeValues={":value": value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def query_with_attribute_names(
    table_name: str,
    partition_key_name: str,
    partition_key_value: str,
    filter_attribute_name: str,
    filter_value: Any,
) -> Dict[str, Any]:
    """
    Query a table using expression attribute names for both key and filter attributes.

    This function demonstrates how to use expression attribute names in a query operation
    for both the key condition expression and filter expression.

    Args:
        table_name (str): The name of the DynamoDB table.
        partition_key_name (str): The name of the partition key attribute.
        partition_key_value (str): The value of the partition key to query.
        filter_attribute_name (str): The name of the attribute to filter on.
        filter_value (Any): The value to compare against in the filter.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the query results.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Use expression attribute names for both key condition and filter
    response = table.query(
        KeyConditionExpression="#pk = :pk_val",
        FilterExpression="#filter_attr = :filter_val",
        ExpressionAttributeNames={"#pk": partition_key_name, "#filter_attr": filter_attribute_name},
        ExpressionAttributeValues={":pk_val": partition_key_value, ":filter_val": filter_value},
    )

    return response


def update_nested_attribute_with_dots(
    table_name: str, key: Dict[str, Any], path_with_dots: str, value: Any
) -> Dict[str, Any]:
    """
    Update a nested attribute using a path with dot notation.

    This function demonstrates how to use expression attribute names to work with
    nested attributes specified using dot notation.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.
        path_with_dots (str): The path to the nested attribute using dot notation (e.g., "a.b.c").
        value (Any): The value to set for the nested attribute.

    Returns:
        Dict[str, Any]: The response from DynamoDB containing the updated attribute values.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Split the path into components
    path_parts = path_with_dots.split(".")

    # Build the update expression and attribute names
    update_expression = "SET "
    expression_attribute_names = {}

    # Build the path expression
    path_expression = ""
    for i, part in enumerate(path_parts):
        name_placeholder = f"#attr{i}"
        expression_attribute_names[name_placeholder] = part

        if i == 0:
            path_expression = name_placeholder
        else:
            path_expression += f".{name_placeholder}"

    # Complete the update expression
    update_expression += f"{path_expression} = :value"

    # Execute the update
    response = table.update_item(
        Key=key,
        UpdateExpression=update_expression,
        ExpressionAttributeNames=expression_attribute_names,
        ExpressionAttributeValues={":value": value},
        ReturnValues="UPDATED_NEW",
    )

    return response


def demonstrate_attribute_name_requirements(table_name: str, key: Dict[str, Any]) -> Dict[str, Any]:
    """
    Demonstrate the requirements and allowed characters for attribute names.

    This function shows examples of valid and invalid attribute names and how to
    handle them using expression attribute names.

    Args:
        table_name (str): The name of the DynamoDB table.
        key (Dict[str, Any]): The primary key of the item to update.

    Returns:
        Dict[str, Any]: A dictionary containing the results of the demonstration.
    """
    # Initialize the DynamoDB resource
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table(table_name)

    # Examples of attribute names with different characteristics
    examples = {
        "valid_standard": "NormalAttribute",  # Standard attribute name (no placeholder needed)
        "valid_with_underscore": "Normal_Attribute",  # Underscore is allowed
        "valid_with_number": "Attribute123",  # Numbers are allowed
        "reserved_word": "Timestamp",  # Reserved word (requires placeholder)
        "starts_with_number": "123Attribute",  # Starts with number (valid but may need placeholder in some contexts)
        "with_space": "Attribute Name",  # Contains space (requires placeholder)
        "with_dot": "Attribute.Name",  # Contains dot (requires placeholder)
        "with_hyphen": "Attribute-Name",  # Contains hyphen (requires placeholder)
        "with_special_chars": "Attribute#$%",  # Contains special characters (requires placeholder)
    }

    results = {}

    # Try to update each attribute type
    for example_type, attr_name in examples.items():
        try:
            # For attributes that don't need placeholders, try direct reference
            if example_type in ["valid_standard", "valid_with_underscore", "valid_with_number"]:
                try:
                    # Try without expression attribute names first
                    response = table.update_item(
                        Key=key,
                        UpdateExpression=f"SET {attr_name} = :value",
                        ExpressionAttributeValues={":value": f"Value for {attr_name}"},
                        ReturnValues="UPDATED_NEW",
                    )
                    results[example_type] = {
                        "attribute_name": attr_name,
                        "success": True,
                        "needed_placeholder": False,
                        "response": response,
                    }
                except ClientError:
                    # If direct reference fails, try with placeholder
                    response = table.update_item(
                        Key=key,
                        UpdateExpression="SET #attr = :value",
                        ExpressionAttributeNames={"#attr": attr_name},
                        ExpressionAttributeValues={":value": f"Value for {attr_name}"},
                        ReturnValues="UPDATED_NEW",
                    )
                    results[example_type] = {
                        "attribute_name": attr_name,
                        "success": True,
                        "needed_placeholder": True,
                        "response": response,
                    }
            else:
                # For attributes that definitely need placeholders
                response = table.update_item(
                    Key=key,
                    UpdateExpression="SET #attr = :value",
                    ExpressionAttributeNames={"#attr": attr_name},
                    ExpressionAttributeValues={":value": f"Value for {attr_name}"},
                    ReturnValues="UPDATED_NEW",
                )
                results[example_type] = {
                    "attribute_name": attr_name,
                    "success": True,
                    "needed_placeholder": True,
                    "response": response,
                }
        except ClientError as e:
            results[example_type] = {"attribute_name": attr_name, "success": False, "error": str(e)}

    return results
```
を使用した式の属性名の使用例 AWS SDK for Python (Boto3)。  

```
def example_usage():
    """Example of how to use expression attribute names in DynamoDB."""
    # Example parameters
    table_name = "Products"
    key = {"ProductId": "prod123"}

    print("Example 1: Using a reserved word as an attribute name")
    try:
        response = use_reserved_word_attribute(
            table_name=table_name, key=key, reserved_word="Timestamp", value="2025-05-14T12:00:00Z"
        )
        print(f"Reserved word attribute updated successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error updating reserved word attribute: {e}")

    print("\nExample 2: Using an attribute name with special characters")
    try:
        response = use_special_character_attribute(
            table_name=table_name,
            key=key,
            attribute_with_special_chars="Product Info",
            value="Special product information",
        )
        print(f"Special character attribute updated successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error updating special character attribute: {e}")

    print("\nExample 3: Querying with expression attribute names")
    try:
        response = query_with_attribute_names(
            table_name=table_name,
            partition_key_name="Category",
            partition_key_value="Electronics",
            filter_attribute_name="Price",
            filter_value=500,
        )
        print(
            f"Query with expression attribute names returned {len(response.get('Items', []))} items"
        )
    except Exception as e:
        print(f"Error querying with expression attribute names: {e}")

    print("\nExample 4: Updating a nested attribute with dot notation")
    try:
        response = update_nested_attribute_with_dots(
            table_name=table_name,
            key=key,
            path_with_dots="Product.Details.Specifications",
            value={"Weight": "2.5 kg", "Dimensions": "30x20x10 cm"},
        )
        print(f"Nested attribute updated successfully: {response.get('Attributes', {})}")
    except Exception as e:
        print(f"Error updating nested attribute: {e}")

    print("\nExample 5: Demonstrating attribute name requirements")
    try:
        results = demonstrate_attribute_name_requirements(table_name=table_name, key=key)

        print("Attribute Name Requirements Results:")
        for example_type, result in results.items():
            if result.get("success", False):
                needed_placeholder = result.get("needed_placeholder", True)
                print(
                    f"  - {example_type}: '{result['attribute_name']}' - {'Requires' if needed_placeholder else 'Does not require'} placeholder"
                )
            else:
                print(
                    f"  - {example_type}: '{result['attribute_name']}' - Failed: {result.get('error', 'Unknown error')}"
                )
    except Exception as e:
        print(f"Error demonstrating attribute name requirements: {e}")

    print("\nCommon DynamoDB Reserved Words (sample):")
    reserved_words = get_common_reserved_words()
    print(", ".join(reserved_words[:20]) + "... (and many more)")

    print("\nWhen to Use Expression Attribute Names:")
    print("1. When the attribute name is a DynamoDB reserved word")
    print("2. When the attribute name contains special characters (spaces, dots, hyphens)")
    print("3. When the attribute name begins with a number")
    print("4. When working with nested attributes using dot notation")
    print("5. When you need to reference the same attribute multiple times in an expression")

    print("\nExpression Attribute Name Requirements:")
    print("1. Must begin with a pound sign (#)")
    print("2. After the pound sign, must contain at least one character")
    print("3. Can contain alphanumeric characters and underscore (_)")
    print("4. Are case-sensitive")
    print("5. Must be unique within a single expression")

    print("\nAttribute Name Requirements in DynamoDB:")
    print("1. Can begin with a-z, A-Z, or 0-9")
    print("2. Can contain a-z, A-Z, 0-9, underscore (_), dash (-), and dot (.)")
    print("3. Are case-sensitive")
    print("4. No length restrictions, but practical limits apply")
    print("5. Cannot be a DynamoDB reserved word if used directly in expressions")
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [クエリ](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/Query)
  + [UpdateItem](https://docs.aws.amazon.com/goto/boto3/dynamodb-2012-08-10/UpdateItem)

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_python_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例では、スケジュールされた Amazon EventBridge イベントのターゲットとして AWS Lambda 関数を登録する方法を示します。Lambda ハンドラーは、後で取得するために Amazon CloudWatch Logs にわかりやすいメッセージと完全なイベントデータを書き込みます。  
+ Lambda 関数をデプロイします。
+ EventBridge スケジュールイベントを作成し、Lambda 関数をターゲットにします。
+ EventBridge に Lambda 関数を呼び出す許可を付与します
+ CloudWatch Logs から最新のデータを出力して、スケジュールされた呼び出しの結果を表示しています。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_python_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で DynamoDB イベントの消費。  

```
import json

def lambda_handler(event, context):
    print(json.dumps(event, indent=2))

    for record in event['Records']:
        log_dynamodb_record(record)

def log_dynamodb_record(record):
    print(record['eventID'])
    print(record['eventName'])
    print(f"DynamoDB Record: {json.dumps(record['dynamodb'])}")
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_python_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def handler(event, context):
    records = event.get("Records")
    curRecordSequenceNumber = ""
    
    for record in records:
        try:
            # Process your record
            curRecordSequenceNumber = record["dynamodb"]["SequenceNumber"]
        except Exception as e:
            # Return failed record's sequence number
            return {"batchItemFailures":[{"itemIdentifier": curRecordSequenceNumber}]}

    return {"batchItemFailures":[]}
```

# SDK for Python (Boto3) を使用する Amazon EC2 の例
<a name="python_3_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_python_3_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
def hello_ec2(ec2_client):
    """
    Use the AWS SDK for Python (Boto3) to list the security groups in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param ec2_client: A Boto3 EC2 client. This client provides low-level
                       access to AWS EC2 services.
    """
    print("Hello, Amazon EC2! Let's list up to 10 of your security groups:")
    try:
        paginator = ec2_client.get_paginator("describe_security_groups")
        response_iterator = paginator.paginate(PaginationConfig={'MaxItems': 10}) # List only 10 security groups.
        logging.basicConfig(level=logging.INFO) # Enable logging.
        for page in response_iterator:
            for sg in page["SecurityGroups"]:
                logger.info(f"\t{sg['GroupId']}: {sg['GroupName']}")
    except ClientError as err:
        logger.error("Failed to list security groups.")
        if err.response["Error"]["Code"] == "AccessDeniedException":
            logger.error("You do not have permission to list security groups.")
        raise


if __name__ == "__main__":
    hello_ec2(boto3.client("ec2"))
```
+  API の詳細については、「*AWS  SDK for Python (Boto3) API リファレンス*」の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class EC2InstanceScenario:
    """
    A scenario that demonstrates how to use Boto3 to manage Amazon EC2 resources.
    Covers creating a key pair, security group, launching an instance, associating
    an Elastic IP, and cleaning up resources.
    """

    def __init__(
        self,
        inst_wrapper: EC2InstanceWrapper,
        key_wrapper: KeyPairWrapper,
        sg_wrapper: SecurityGroupWrapper,
        eip_wrapper: ElasticIpWrapper,
        ssm_client: boto3.client,
        remote_exec: bool = False,
    ):
        """
        Initializes the EC2InstanceScenario with the necessary AWS service wrappers.

        :param inst_wrapper: Wrapper for EC2 instance operations.
        :param key_wrapper: Wrapper for key pair operations.
        :param sg_wrapper: Wrapper for security group operations.
        :param eip_wrapper: Wrapper for Elastic IP operations.
        :param ssm_client: Boto3 client for accessing SSM to retrieve AMIs.
        :param remote_exec: Flag to indicate if the scenario is running in a remote execution
                            environment. Defaults to False. If True, the script won't prompt
                            for user interaction.
        """
        self.inst_wrapper = inst_wrapper
        self.key_wrapper = key_wrapper
        self.sg_wrapper = sg_wrapper
        self.eip_wrapper = eip_wrapper
        self.ssm_client = ssm_client
        self.remote_exec = remote_exec

    def create_and_list_key_pairs(self) -> None:
        """
        Creates an RSA key pair for SSH access to the EC2 instance and lists available key pairs.
        """
        console.print("**Step 1: Create a Secure Key Pair**", style="bold cyan")
        console.print(
            "Let's create a secure RSA key pair for connecting to your EC2 instance."
        )
        key_name = f"MyUniqueKeyPair-{uuid.uuid4().hex[:8]}"
        console.print(f"- **Key Pair Name**: {key_name}")

        # Create the key pair and simulate the process with a progress bar.
        with alive_bar(1, title="Creating Key Pair") as bar:
            self.key_wrapper.create(key_name)
            time.sleep(0.4)  # Simulate the delay in key creation
            bar()

        console.print(f"- **Private Key Saved to**: {self.key_wrapper.key_file_path}\n")

        # List key pairs (simulated) and show a progress bar.
        list_keys = True
        if list_keys:
            console.print("- Listing your key pairs...")
            start_time = time.time()
            with alive_bar(100, title="Listing Key Pairs") as bar:
                while time.time() - start_time < 2:
                    time.sleep(0.2)
                    bar(10)
                self.key_wrapper.list(5)
                if time.time() - start_time > 2:
                    console.print(
                        "Taking longer than expected! Please wait...",
                        style="bold yellow",
                    )

    def create_security_group(self) -> None:
        """
        Creates a security group that controls access to the EC2 instance and adds a rule
        to allow SSH access from the user's current public IP address.
        """
        console.print("**Step 2: Create a Security Group**", style="bold cyan")
        console.print(
            "Security groups manage access to your instance. Let's create one."
        )
        sg_name = f"MySecurityGroup-{uuid.uuid4().hex[:8]}"
        console.print(f"- **Security Group Name**: {sg_name}")

        # Create the security group and simulate the process with a progress bar.
        with alive_bar(1, title="Creating Security Group") as bar:
            self.sg_wrapper.create(
                sg_name, "Security group for example: get started with instances."
            )
            time.sleep(0.5)
            bar()

        console.print(f"- **Security Group ID**: {self.sg_wrapper.security_group}\n")

        # Get the current public IP to set up SSH access.
        ip_response = urllib.request.urlopen("http://checkip.amazonaws.com")
        current_ip_address = ip_response.read().decode("utf-8").strip()
        console.print(
            "Let's add a rule to allow SSH only from your current IP address."
        )
        console.print(f"- **Your Public IP Address**: {current_ip_address}")
        console.print("- Automatically adding SSH rule...")

        # Update security group rules to allow SSH and simulate with a progress bar.
        with alive_bar(1, title="Updating Security Group Rules") as bar:
            response = self.sg_wrapper.authorize_ingress(current_ip_address)
            time.sleep(0.4)
            if response and response.get("Return"):
                console.print("- **Security Group Rules Updated**.")
            else:
                console.print(
                    "- **Error**: Couldn't update security group rules.",
                    style="bold red",
                )
            bar()

        self.sg_wrapper.describe(self.sg_wrapper.security_group)

    def create_instance(self) -> None:
        """
        Launches an EC2 instance using an Amazon Linux 2 AMI and the created key pair
        and security group. Displays instance details and SSH connection information.
        """
        # Retrieve Amazon Linux 2 AMIs from SSM.
        ami_paginator = self.ssm_client.get_paginator("get_parameters_by_path")
        ami_options = []
        for page in ami_paginator.paginate(Path="/aws/service/ami-amazon-linux-latest"):
            ami_options += page["Parameters"]
        amzn2_images = self.inst_wrapper.get_images(
            [opt["Value"] for opt in ami_options if "amzn2" in opt["Name"]]
        )
        console.print("\n**Step 3: Launch Your Instance**", style="bold cyan")
        console.print(
            "Let's create an instance from an Amazon Linux 2 AMI. Here are some options:"
        )
        image_choice = 0
        console.print(f"- Selected AMI: {amzn2_images[image_choice]['ImageId']}\n")

        # Display instance types compatible with the selected AMI
        inst_types = self.inst_wrapper.get_instance_types(
            amzn2_images[image_choice]["Architecture"]
        )
        inst_type_choice = 0
        console.print(
            f"- Selected instance type: {inst_types[inst_type_choice]['InstanceType']}\n"
        )

        console.print("Creating your instance and waiting for it to start...")
        with alive_bar(1, title="Creating Instance") as bar:
            self.inst_wrapper.create(
                amzn2_images[image_choice]["ImageId"],
                inst_types[inst_type_choice]["InstanceType"],
                self.key_wrapper.key_pair["KeyName"],
                [self.sg_wrapper.security_group],
            )
            time.sleep(21)
            bar()

        console.print(f"**Success! Your instance is ready:**\n", style="bold green")
        self.inst_wrapper.display()

        console.print(
            "You can use SSH to connect to your instance. "
            "If the connection attempt times out, you might have to manually update "
            "the SSH ingress rule for your IP address in the AWS Management Console."
        )
        self._display_ssh_info()

    def _display_ssh_info(self) -> None:
        """
        Displays SSH connection information for the user to connect to the EC2 instance.
        Handles the case where the instance does or does not have an associated public IP address.
        """
        if (
            not self.eip_wrapper.elastic_ips
            or not self.eip_wrapper.elastic_ips[0].allocation_id
        ):
            if self.inst_wrapper.instances:
                instance = self.inst_wrapper.instances[0]
                instance_id = instance["InstanceId"]

                waiter = self.inst_wrapper.ec2_client.get_waiter("instance_running")
                console.print(
                    "Waiting for the instance to be in a running state with a public IP...",
                    style="bold cyan",
                )

                with alive_bar(1, title="Waiting for Instance to Start") as bar:
                    waiter.wait(InstanceIds=[instance_id])
                    time.sleep(20)
                    bar()

                instance = self.inst_wrapper.ec2_client.describe_instances(
                    InstanceIds=[instance_id]
                )["Reservations"][0]["Instances"][0]

                public_ip = instance.get("PublicIpAddress")
                if public_ip:
                    console.print(
                        "\nTo connect via SSH, open another command prompt and run the following command:",
                        style="bold cyan",
                    )
                    console.print(
                        f"\tssh -i {self.key_wrapper.key_file_path} ec2-user@{public_ip}"
                    )
                else:
                    console.print(
                        "Instance does not have a public IP address assigned.",
                        style="bold red",
                    )
            else:
                console.print(
                    "No instance available to retrieve public IP address.",
                    style="bold red",
                )
        else:
            elastic_ip = self.eip_wrapper.elastic_ips[0]
            elastic_ip_address = elastic_ip.public_ip
            console.print(
                f"\tssh -i {self.key_wrapper.key_file_path} ec2-user@{elastic_ip_address}"
            )

        if not self.remote_exec:
            console.print("\nOpen a new terminal tab to try the above SSH command.")
            input("Press Enter to continue...")

    def associate_elastic_ip(self) -> None:
        """
        Allocates an Elastic IP address and associates it with the EC2 instance.
        Displays the Elastic IP address and SSH connection information.
        """
        console.print("\n**Step 4: Allocate an Elastic IP Address**", style="bold cyan")
        console.print(
            "You can allocate an Elastic IP address and associate it with your instance\n"
            "to keep a consistent IP address even when your instance restarts."
        )

        with alive_bar(1, title="Allocating Elastic IP") as bar:
            elastic_ip = self.eip_wrapper.allocate()
            time.sleep(0.5)
            bar()

        console.print(
            f"- **Allocated Static Elastic IP Address**: {elastic_ip.public_ip}."
        )

        with alive_bar(1, title="Associating Elastic IP") as bar:
            self.eip_wrapper.associate(
                elastic_ip.allocation_id, self.inst_wrapper.instances[0]["InstanceId"]
            )
            time.sleep(2)
            bar()

        console.print(f"- **Associated Elastic IP with Your Instance**.")
        console.print(
            "You can now use SSH to connect to your instance by using the Elastic IP."
        )
        self._display_ssh_info()

    def stop_and_start_instance(self) -> None:
        """
        Stops and restarts the EC2 instance. Displays instance state and explains
        changes that occur when the instance is restarted, such as the potential change
        in the public IP address unless an Elastic IP is associated.
        """
        console.print("\n**Step 5: Stop and Start Your Instance**", style="bold cyan")
        console.print("Let's stop and start your instance to see what changes.")
        console.print("- **Stopping your instance and waiting until it's stopped...**")

        with alive_bar(1, title="Stopping Instance") as bar:
            self.inst_wrapper.stop()
            time.sleep(360)
            bar()

        console.print("- **Your instance is stopped. Restarting...**")

        with alive_bar(1, title="Starting Instance") as bar:
            self.inst_wrapper.start()
            time.sleep(20)
            bar()

        console.print("**Your instance is running.**", style="bold green")
        self.inst_wrapper.display()

        elastic_ip = (
            self.eip_wrapper.elastic_ips[0] if self.eip_wrapper.elastic_ips else None
        )

        if elastic_ip is None or elastic_ip.allocation_id is None:
            console.print(
                "- **Note**: Every time your instance is restarted, its public IP address changes."
            )
        else:
            console.print(
                f"Because you have associated an Elastic IP with your instance, you can \n"
                f"connect by using a consistent IP address after the instance restarts: {elastic_ip.public_ip}"
            )

        self._display_ssh_info()

    def cleanup(self) -> None:
        """
        Cleans up all the resources created during the scenario, including disassociating
        and releasing the Elastic IP, terminating the instance, deleting the security
        group, and deleting the key pair.
        """
        console.print("\n**Step 6: Clean Up Resources**", style="bold cyan")
        console.print("Cleaning up resources:")

        for elastic_ip in self.eip_wrapper.elastic_ips:
            console.print(f"- **Elastic IP**: {elastic_ip.public_ip}")

            with alive_bar(1, title="Disassociating Elastic IP") as bar:
                self.eip_wrapper.disassociate(elastic_ip.allocation_id)
                time.sleep(2)
                bar()

            console.print("\t- **Disassociated Elastic IP from the Instance**")

            with alive_bar(1, title="Releasing Elastic IP") as bar:
                self.eip_wrapper.release(elastic_ip.allocation_id)
                time.sleep(1)
                bar()

            console.print("\t- **Released Elastic IP**")

        console.print(f"- **Instance**: {self.inst_wrapper.instances[0]['InstanceId']}")

        with alive_bar(1, title="Terminating Instance") as bar:
            self.inst_wrapper.terminate()
            time.sleep(380)
            bar()

        console.print("\t- **Terminated Instance**")

        console.print(f"- **Security Group**: {self.sg_wrapper.security_group}")

        with alive_bar(1, title="Deleting Security Group") as bar:
            self.sg_wrapper.delete(self.sg_wrapper.security_group)
            time.sleep(1)
            bar()

        console.print("\t- **Deleted Security Group**")

        console.print(f"- **Key Pair**: {self.key_wrapper.key_pair['KeyName']}")

        with alive_bar(1, title="Deleting Key Pair") as bar:
            self.key_wrapper.delete(self.key_wrapper.key_pair["KeyName"])
            time.sleep(0.4)
            bar()

        console.print("\t- **Deleted Key Pair**")

    def run_scenario(self) -> None:
        """
        Executes the entire EC2 instance scenario: creates key pairs, security groups,
        launches an instance, associates an Elastic IP, and cleans up all resources.
        """
        logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

        console.print("-" * 88)
        console.print(
            "Welcome to the Amazon Elastic Compute Cloud (Amazon EC2) get started with instances demo.",
            style="bold magenta",
        )
        console.print("-" * 88)

        self.create_and_list_key_pairs()
        self.create_security_group()
        self.create_instance()
        self.stop_and_start_instance()
        self.associate_elastic_ip()
        self.stop_and_start_instance()
        self.cleanup()

        console.print("\nThanks for watching!", style="bold green")
        console.print("-" * 88)


if __name__ == "__main__":
    try:
        scenario = EC2InstanceScenario(
            EC2InstanceWrapper.from_client(),
            KeyPairWrapper.from_client(),
            SecurityGroupWrapper.from_client(),
            ElasticIpWrapper.from_client(),
            boto3.client("ssm"),
        )
        scenario.run_scenario()
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
キーペアアクションをラップするクラスを定義します。  

```
class KeyPairWrapper:
    """
    Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.
    This class provides methods to create, list, and delete EC2 key pairs.
    """

    def __init__(
        self,
        ec2_client: boto3.client,
        key_file_dir: Union[tempfile.TemporaryDirectory, str],
        key_pair: Optional[dict] = None,
    ):
        """
        Initializes the KeyPairWrapper with the specified EC2 client, key file directory,
        and an optional key pair.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param key_file_dir: The folder where the private key information is stored.
                             This should be a secure folder.
        :param key_pair: A dictionary representing the Boto3 KeyPair object.
                         This is a high-level object that wraps key pair actions. Optional.
        """
        self.ec2_client = ec2_client
        self.key_pair = key_pair
        self.key_file_path: Optional[str] = None
        self.key_file_dir = key_file_dir

    @classmethod
    def from_client(cls) -> "KeyPairWrapper":
        """
        Class method to create an instance of KeyPairWrapper using a new EC2 client
        and a temporary directory for storing key files.

        :return: An instance of KeyPairWrapper.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client, tempfile.TemporaryDirectory())


    def create(self, key_name: str) -> dict:
        """
        Creates a key pair that can be used to securely connect to an EC2 instance.
        The returned key pair contains private key information that cannot be retrieved
        again. The private key data is stored as a .pem file.

        :param key_name: The name of the key pair to create.
        :return: A dictionary representing the Boto3 KeyPair object that represents the newly created key pair.
        :raises ClientError: If there is an error in creating the key pair, for example, if a key pair with the same name already exists.
        """
        try:
            response = self.ec2_client.create_key_pair(KeyName=key_name)
            self.key_pair = response
            self.key_file_path = os.path.join(
                self.key_file_dir.name, f"{self.key_pair['KeyName']}.pem"
            )
            with open(self.key_file_path, "w") as key_file:
                key_file.write(self.key_pair["KeyMaterial"])
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidKeyPair.Duplicate":
                logger.error(
                    f"A key pair called {key_name} already exists. "
                    "Please choose a different name for your key pair "
                    "or delete the existing key pair before creating."
                )
            raise
        else:
            return self.key_pair


    def list(self, limit: Optional[int] = None) -> None:
        """
        Displays a list of key pairs for the current account.

        WARNING: Results are not paginated.

        :param limit: The maximum number of key pairs to list. If not specified,
                      all key pairs will be listed.
        :raises ClientError: If there is an error in listing the key pairs.
        """
        try:
            response = self.ec2_client.describe_key_pairs()
            key_pairs = response.get("KeyPairs", [])

            if limit:
                key_pairs = key_pairs[:limit]

            for key_pair in key_pairs:
                logger.info(
                    f"Found {key_pair['KeyType']} key '{key_pair['KeyName']}' with fingerprint:"
                )
                logger.info(f"\t{key_pair['KeyFingerprint']}")
        except ClientError as err:
            logger.error(f"Failed to list key pairs: {str(err)}")
            raise


    def delete(self, key_name: str) -> bool:
        """
        Deletes a key pair by its name.

        :param key_name: The name of the key pair to delete.
        :return: A boolean indicating whether the deletion was successful.
        :raises ClientError: If there is an error in deleting the key pair, for example,
                             if the key pair does not exist.
        """
        try:
            self.ec2_client.delete_key_pair(KeyName=key_name)
            logger.info(f"Successfully deleted key pair: {key_name}")
            self.key_pair = None
            return True
        except self.ec2_client.exceptions.ClientError as err:
            logger.error(f"Deletion failed for key pair: {key_name}")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidKeyPair.NotFound":
                logger.error(
                    f"The key pair '{key_name}' does not exist and cannot be deleted. "
                    "Please verify the key pair name and try again."
                )
            raise
```
セキュリティグループのアクションをラップするクラスを定義します。  

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(self, group_name: str, group_description: str) -> str:
        """
        Creates a security group in the default virtual private cloud (VPC) of the current account.

        :param group_name: The name of the security group to create.
        :param group_description: The description of the security group to create.
        :return: The ID of the newly created security group.
        :raise Handles AWS SDK service-level ClientError, with special handling for ResourceAlreadyExists
        """
        try:
            response = self.ec2_client.create_security_group(
                GroupName=group_name, Description=group_description
            )
            self.security_group = response["GroupId"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExists":
                logger.error(
                    f"Security group '{group_name}' already exists. Please choose a different name."
                )
            raise
        else:
            return self.security_group


    def authorize_ingress(self, ssh_ingress_ip: str) -> Optional[Dict[str, Any]]:
        """
        Adds a rule to the security group to allow access to SSH.

        :param ssh_ingress_ip: The IP address that is granted inbound access to connect
                               to port 22 over TCP, used for SSH.
        :return: The response to the authorization request. The 'Return' field of the
                 response indicates whether the request succeeded or failed, or None if no security group is set.
        :raise Handles AWS SDK service-level ClientError, with special handling for ResourceAlreadyExists
        """
        if self.security_group is None:
            logger.info("No security group to update.")
            return None

        try:
            ip_permissions = [
                {
                    # SSH ingress open to only the specified IP address.
                    "IpProtocol": "tcp",
                    "FromPort": 22,
                    "ToPort": 22,
                    "IpRanges": [{"CidrIp": f"{ssh_ingress_ip}/32"}],
                }
            ]
            response = self.ec2_client.authorize_security_group_ingress(
                GroupId=self.security_group, IpPermissions=ip_permissions
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidPermission.Duplicate":
                logger.error(
                    f"The SSH ingress rule for IP {ssh_ingress_ip} already exists"
                    f"in security group '{self.security_group}'."
                )
            raise
        else:
            return response


    def describe(self, security_group_id: Optional[str] = None) -> bool:
        """
        Displays information about the specified security group or all security groups if no ID is provided.

        :param security_group_id: The ID of the security group to describe.
                                  If None, an open search is performed to describe all security groups.
        :returns: True if the description is successful.
        :raises ClientError: If there is an error describing the security group(s), such as an invalid security group ID.
        """
        try:
            paginator = self.ec2_client.get_paginator("describe_security_groups")

            if security_group_id is None:
                # If no ID is provided, return all security groups.
                page_iterator = paginator.paginate()
            else:
                page_iterator = paginator.paginate(GroupIds=[security_group_id])

            for page in page_iterator:
                for security_group in page["SecurityGroups"]:
                    print(f"Security group: {security_group['GroupName']}")
                    print(f"\tID: {security_group['GroupId']}")
                    print(f"\tVPC: {security_group['VpcId']}")
                    if security_group["IpPermissions"]:
                        print("Inbound permissions:")
                        pp(security_group["IpPermissions"])

            return True
        except ClientError as err:
            logger.error("Failed to describe security group(s).")
            if err.response["Error"]["Code"] == "InvalidGroup.NotFound":
                logger.error(
                    f"Security group {security_group_id} does not exist "
                    f"because the specified security group ID was not found."
                )
            raise


    def delete(self, security_group_id: str) -> bool:
        """
        Deletes the specified security group.

        :param security_group_id: The ID of the security group to delete. Required.

        :returns: True if the deletion is successful.
        :raises ClientError: If the security group cannot be deleted due to an AWS service error.
        """
        try:
            self.ec2_client.delete_security_group(GroupId=security_group_id)
            logger.info(f"Successfully deleted security group '{security_group_id}'")
            return True
        except ClientError as err:
            logger.error(f"Deletion failed for security group '{security_group_id}'")
            error_code = err.response["Error"]["Code"]

            if error_code == "InvalidGroup.NotFound":
                logger.error(
                    f"Security group '{security_group_id}' cannot be deleted because it does not exist."
                )
            elif error_code == "DependencyViolation":
                logger.error(
                    f"Security group '{security_group_id}' cannot be deleted because it is still in use."
                    " Verify that it is:"
                    "\n\t- Detached from resources"
                    "\n\t- Removed from references in other groups"
                    "\n\t- Removed from VPC's as a default group"
                )
            raise
```
インスタンスアクションをラップするクラスを定義します。  

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(
        self,
        image_id: str,
        instance_type: str,
        key_pair_name: str,
        security_group_ids: Optional[List[str]] = None,
    ) -> List[Dict[str, Any]]:
        """
        Creates a new EC2 instance in the default VPC of the current account.

        The instance starts immediately after it is created.

        :param image_id: The ID of the Amazon Machine Image (AMI) to use for the instance.
        :param instance_type: The type of instance to create, such as 't2.micro'.
        :param key_pair_name: The name of the key pair to use for SSH access.
        :param security_group_ids: A list of security group IDs to associate with the instance.
                                   If not specified, the default security group of the VPC is used.
        :return: A list of dictionaries representing Boto3 Instance objects representing the newly created instances.
        """
        try:
            instance_params = {
                "ImageId": image_id,
                "InstanceType": instance_type,
                "KeyName": key_pair_name,
            }
            if security_group_ids is not None:
                instance_params["SecurityGroupIds"] = security_group_ids

            response = self.ec2_client.run_instances(
                **instance_params, MinCount=1, MaxCount=1
            )
            instance = response["Instances"][0]
            self.instances.append(instance)
            waiter = self.ec2_client.get_waiter("instance_running")
            waiter.wait(InstanceIds=[instance["InstanceId"]])
        except ClientError as err:
            params_str = "\n\t".join(
                f"{key}: {value}" for key, value in instance_params.items()
            )
            logger.error(
                f"Failed to complete instance creation request.\nRequest details:{params_str}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InstanceLimitExceeded":
                logger.error(
                    (
                        f"Insufficient capacity for instance type '{instance_type}'. "
                        "Terminate unused instances or contact AWS Support for a limit increase."
                    )
                )
            if error_code == "InsufficientInstanceCapacity":
                logger.error(
                    (
                        f"Insufficient capacity for instance type '{instance_type}'. "
                        "Select a different instance type or launch in a different availability zone."
                    )
                )
            raise
        return self.instances


    def display(self, state_filter: Optional[str] = "running") -> None:
        """
        Displays information about instances, filtering by the specified state.

        :param state_filter: The instance state to include in the output. Only instances in this state
                             will be displayed. Default is 'running'. Example states: 'running', 'stopped'.
        """
        if not self.instances:
            logger.info("No instances to display.")
            return

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        paginator = self.ec2_client.get_paginator("describe_instances")
        page_iterator = paginator.paginate(InstanceIds=instance_ids)

        try:
            for page in page_iterator:
                for reservation in page["Reservations"]:
                    for instance in reservation["Instances"]:
                        instance_state = instance["State"]["Name"]

                        # Apply the state filter (default is 'running')
                        if state_filter and instance_state != state_filter:
                            continue  # Skip this instance if it doesn't match the filter

                        # Create a formatted string with instance details
                        instance_info = (
                            f"• ID: {instance['InstanceId']}\n"
                            f"• Image ID: {instance['ImageId']}\n"
                            f"• Instance type: {instance['InstanceType']}\n"
                            f"• Key name: {instance['KeyName']}\n"
                            f"• VPC ID: {instance['VpcId']}\n"
                            f"• Public IP: {instance.get('PublicIpAddress', 'N/A')}\n"
                            f"• State: {instance_state}"
                        )
                        print(instance_info)

        except ClientError as err:
            logger.error(
                f"Failed to display instance(s). : {' '.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                logger.error(
                    "One or more instance IDs do not exist. "
                    "Please verify the instance IDs and try again."
                )
                raise


    def terminate(self) -> None:
        """
        Terminates instances and waits for them to reach the terminated state.
        """
        if not self.instances:
            logger.info("No instances to terminate.")
            return

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            self.ec2_client.terminate_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_terminated")
            waiter.wait(InstanceIds=instance_ids)
            self.instances.clear()
            for instance_id in instance_ids:
                print(f"• Instance ID: {instance_id}\n" f"• Action: Terminated")

        except ClientError as err:
            logger.error(
                f"Failed instance termination details:\n\t{str(self.instances)}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                logger.error(
                    "One or more instance IDs do not exist. "
                    "Please verify the instance IDs and try again."
                )
            raise


    def start(self) -> Optional[Dict[str, Any]]:
        """
        Starts instances and waits for them to be in a running state.

        :return: The response to the start request.
        """
        if not self.instances:
            logger.info("No instances to start.")
            return None

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            start_response = self.ec2_client.start_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_running")
            waiter.wait(InstanceIds=instance_ids)
            return start_response
        except ClientError as err:
            logger.error(
                f"Failed to start instance(s): {','.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "IncorrectInstanceState":
                logger.error(
                    "Couldn't start instance(s) because they are in an incorrect state. "
                    "Ensure the instances are in a stopped state before starting them."
                )
            raise


    def stop(self) -> Optional[Dict[str, Any]]:
        """
        Stops instances and waits for them to be in a stopped state.

        :return: The response to the stop request, or None if there are no instances to stop.
        """
        if not self.instances:
            logger.info("No instances to stop.")
            return None

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            # Attempt to stop the instances
            stop_response = self.ec2_client.stop_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_stopped")
            waiter.wait(InstanceIds=instance_ids)
        except ClientError as err:
            logger.error(
                f"Failed to stop instance(s): {','.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "IncorrectInstanceState":
                logger.error(
                    "Couldn't stop instance(s) because they are in an incorrect state. "
                    "Ensure the instances are in a running state before stopping them."
                )
            raise
        return stop_response


    def get_images(self, image_ids: List[str]) -> List[Dict[str, Any]]:
        """
        Gets information about Amazon Machine Images (AMIs) from a list of AMI IDs.

        :param image_ids: The list of AMI IDs to look up.
        :return: A list of dictionaries representing the requested AMIs.
        """
        try:
            response = self.ec2_client.describe_images(ImageIds=image_ids)
            images = response["Images"]
        except ClientError as err:
            logger.error(f"Failed to stop AMI(s): {','.join(map(str, image_ids))}")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAMIID.NotFound":
                logger.error("One or more of the AMI IDs does not exist.")
            raise
        return images


    def get_instance_types(
        self, architecture: str = "x86_64", sizes: List[str] = ["*.micro", "*.small"]
    ) -> List[Dict[str, Any]]:
        """
        Gets instance types that support the specified architecture and size.
        See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstanceTypes.html
        for a list of allowable parameters.

        :param architecture: The architecture supported by instance types. Default: 'x86_64'.
        :param sizes: The size of instance types. Default: '*.micro', '*.small',
        :return: A list of dictionaries representing instance types that support the specified architecture and size.
        """
        try:
            inst_types = []
            paginator = self.ec2_client.get_paginator("describe_instance_types")
            for page in paginator.paginate(
                Filters=[
                    {
                        "Name": "processor-info.supported-architecture",
                        "Values": [architecture],
                    },
                    {"Name": "instance-type", "Values": sizes},
                ]
            ):
                inst_types += page["InstanceTypes"]
        except ClientError as err:
            logger.error(
                f"Failed to get instance types: {architecture}, {','.join(map(str, sizes))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidParameterValue":
                logger.error(
                    "Parameters are invalid. "
                    "Ensure architecture and size strings conform to DescribeInstanceTypes API reference."
                )
            raise
        else:
            return inst_types
```
Elastic IP アクションをラップするクラスを定義します。  

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def allocate(self) -> "ElasticIpWrapper.ElasticIp":
        """
        Allocates an Elastic IP address that can be associated with an Amazon EC2
        instance. By using an Elastic IP address, you can keep the public IP address
        constant even when you restart the associated instance.

        :return: The ElasticIp object for the newly created Elastic IP address.
        :raises ClientError: If the allocation fails, such as reaching the maximum limit of Elastic IPs.
        """
        try:
            response = self.ec2_client.allocate_address(Domain="vpc")
            elastic_ip = self.ElasticIp(
                allocation_id=response["AllocationId"], public_ip=response["PublicIp"]
            )
            self.elastic_ips.append(elastic_ip)
        except ClientError as err:
            if err.response["Error"]["Code"] == "AddressLimitExceeded":
                logger.error(
                    "Max IP's reached. Release unused addresses or contact AWS Support for an increase."
                )
            raise err
        return elastic_ip


    def associate(
        self, allocation_id: str, instance_id: str
    ) -> Union[Dict[str, Any], None]:
        """
        Associates an Elastic IP address with an instance. When this association is
        created, the Elastic IP's public IP address is immediately used as the public
        IP address of the associated instance.

        :param allocation_id: The allocation ID of the Elastic IP.
        :param instance_id: The ID of the Amazon EC2 instance.
        :return: A response that contains the ID of the association, or None if no Elastic IP is found.
        :raises ClientError: If the association fails, such as when the instance ID is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None:
            logger.info(f"No Elastic IP found with allocation ID {allocation_id}.")
            return None

        try:
            response = self.ec2_client.associate_address(
                AllocationId=allocation_id, InstanceId=instance_id
            )
            elastic_ip.instance_id = (
                instance_id  # Track the instance associated with this Elastic IP.
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidInstanceID.NotFound":
                logger.error(
                    f"Failed to associate Elastic IP {allocation_id} with {instance_id} "
                    "because the specified instance ID does not exist or has not propagated fully. "
                    "Verify the instance ID and try again, or wait a few moments before attempting to "
                    "associate the Elastic IP address."
                )
            raise
        return response


    def disassociate(self, allocation_id: str) -> None:
        """
        Removes an association between an Elastic IP address and an instance. When the
        association is removed, the instance is assigned a new public IP address.

        :param allocation_id: The allocation ID of the Elastic IP to disassociate.
        :raises ClientError: If the disassociation fails, such as when the association ID is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None or elastic_ip.instance_id is None:
            logger.info(
                f"No association found for Elastic IP with allocation ID {allocation_id}."
            )
            return

        try:
            # Retrieve the association ID before disassociating
            response = self.ec2_client.describe_addresses(AllocationIds=[allocation_id])
            association_id = response["Addresses"][0].get("AssociationId")

            if association_id:
                self.ec2_client.disassociate_address(AssociationId=association_id)
                elastic_ip.instance_id = None  # Remove the instance association
            else:
                logger.info(
                    f"No Association ID found for Elastic IP with allocation ID {allocation_id}."
                )

        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidAssociationID.NotFound":
                logger.error(
                    f"Failed to disassociate Elastic IP {allocation_id} "
                    "because the specified association ID for the Elastic IP address was not found. "
                    "Verify the association ID and ensure the Elastic IP is currently associated with a "
                    "resource before attempting to disassociate it."
                )
            raise


    def release(self, allocation_id: str) -> None:
        """
        Releases an Elastic IP address. After the Elastic IP address is released,
        it can no longer be used.

        :param allocation_id: The allocation ID of the Elastic IP to release.
        :raises ClientError: If the release fails, such as when the Elastic IP address is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None:
            logger.info(f"No Elastic IP found with allocation ID {allocation_id}.")
            return

        try:
            self.ec2_client.release_address(AllocationId=allocation_id)
            self.elastic_ips.remove(elastic_ip)  # Remove the Elastic IP from the list
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidAddress.NotFound":
                logger.error(
                    f"Failed to release Elastic IP address {allocation_id} "
                    "because it could not be found. Verify the Elastic IP address "
                    "and ensure it is allocated to your account in the correct region "
                    "before attempting to release it."
                )
            raise


    @staticmethod
    def get_elastic_ip_by_allocation(
        elastic_ips: List["ElasticIpWrapper.ElasticIp"], allocation_id: str
    ) -> Optional["ElasticIpWrapper.ElasticIp"]:
        """
        Retrieves an Elastic IP object by its allocation ID from a given list of Elastic IPs.

        :param elastic_ips: A list of ElasticIp objects.
        :param allocation_id: The allocation ID of the Elastic IP to retrieve.
        :return: The ElasticIp object associated with the allocation ID, or None if not found.
        """
        return next(
            (ip for ip in elastic_ips if ip.allocation_id == allocation_id), None
        )
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AllocateAddress)
  + [AssociateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AssociateAddress)
  + [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AuthorizeSecurityGroupIngress)
  + [CreateKeyPair](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateKeyPair)
  + [CreateSecurityGroup](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateSecurityGroup)
  + [DeleteKeyPair](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteKeyPair)
  + [DeleteSecurityGroup](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteSecurityGroup)
  + [DescribeImages](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeImages)
  + [DescribeInstanceTypes](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstanceTypes)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstances)
  + [DescribeKeyPairs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeKeyPairs)
  + [DescribeSecurityGroups](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSecurityGroups)
  + [DisassociateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DisassociateAddress)
  + [ReleaseAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReleaseAddress)
  + [RunInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RunInstances)
  + [StartInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/StartInstances)
  + [StopInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/StopInstances)
  + [TerminateInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/TerminateInstances)
  + [UnmonitorInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/UnmonitorInstances)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_python_3_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def allocate(self) -> "ElasticIpWrapper.ElasticIp":
        """
        Allocates an Elastic IP address that can be associated with an Amazon EC2
        instance. By using an Elastic IP address, you can keep the public IP address
        constant even when you restart the associated instance.

        :return: The ElasticIp object for the newly created Elastic IP address.
        :raises ClientError: If the allocation fails, such as reaching the maximum limit of Elastic IPs.
        """
        try:
            response = self.ec2_client.allocate_address(Domain="vpc")
            elastic_ip = self.ElasticIp(
                allocation_id=response["AllocationId"], public_ip=response["PublicIp"]
            )
            self.elastic_ips.append(elastic_ip)
        except ClientError as err:
            if err.response["Error"]["Code"] == "AddressLimitExceeded":
                logger.error(
                    "Max IP's reached. Release unused addresses or contact AWS Support for an increase."
                )
            raise err
        return elastic_ip
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[AllocateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AllocateAddress)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_python_3_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def associate(
        self, allocation_id: str, instance_id: str
    ) -> Union[Dict[str, Any], None]:
        """
        Associates an Elastic IP address with an instance. When this association is
        created, the Elastic IP's public IP address is immediately used as the public
        IP address of the associated instance.

        :param allocation_id: The allocation ID of the Elastic IP.
        :param instance_id: The ID of the Amazon EC2 instance.
        :return: A response that contains the ID of the association, or None if no Elastic IP is found.
        :raises ClientError: If the association fails, such as when the instance ID is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None:
            logger.info(f"No Elastic IP found with allocation ID {allocation_id}.")
            return None

        try:
            response = self.ec2_client.associate_address(
                AllocationId=allocation_id, InstanceId=instance_id
            )
            elastic_ip.instance_id = (
                instance_id  # Track the instance associated with this Elastic IP.
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidInstanceID.NotFound":
                logger.error(
                    f"Failed to associate Elastic IP {allocation_id} with {instance_id} "
                    "because the specified instance ID does not exist or has not propagated fully. "
                    "Verify the instance ID and try again, or wait a few moments before attempting to "
                    "associate the Elastic IP address."
                )
            raise
        return response
```
+  API の詳細については、「*AWS  SDK for Python (Boto3) API リファレンス*」の「[AssociateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AssociateAddress)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_python_3_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def authorize_ingress(self, ssh_ingress_ip: str) -> Optional[Dict[str, Any]]:
        """
        Adds a rule to the security group to allow access to SSH.

        :param ssh_ingress_ip: The IP address that is granted inbound access to connect
                               to port 22 over TCP, used for SSH.
        :return: The response to the authorization request. The 'Return' field of the
                 response indicates whether the request succeeded or failed, or None if no security group is set.
        :raise Handles AWS SDK service-level ClientError, with special handling for ResourceAlreadyExists
        """
        if self.security_group is None:
            logger.info("No security group to update.")
            return None

        try:
            ip_permissions = [
                {
                    # SSH ingress open to only the specified IP address.
                    "IpProtocol": "tcp",
                    "FromPort": 22,
                    "ToPort": 22,
                    "IpRanges": [{"CidrIp": f"{ssh_ingress_ip}/32"}],
                }
            ]
            response = self.ec2_client.authorize_security_group_ingress(
                GroupId=self.security_group, IpPermissions=ip_permissions
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidPermission.Duplicate":
                logger.error(
                    f"The SSH ingress rule for IP {ssh_ingress_ip} already exists"
                    f"in security group '{self.security_group}'."
                )
            raise
        else:
            return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/AuthorizeSecurityGroupIngress)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_python_3_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class KeyPairWrapper:
    """
    Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.
    This class provides methods to create, list, and delete EC2 key pairs.
    """

    def __init__(
        self,
        ec2_client: boto3.client,
        key_file_dir: Union[tempfile.TemporaryDirectory, str],
        key_pair: Optional[dict] = None,
    ):
        """
        Initializes the KeyPairWrapper with the specified EC2 client, key file directory,
        and an optional key pair.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param key_file_dir: The folder where the private key information is stored.
                             This should be a secure folder.
        :param key_pair: A dictionary representing the Boto3 KeyPair object.
                         This is a high-level object that wraps key pair actions. Optional.
        """
        self.ec2_client = ec2_client
        self.key_pair = key_pair
        self.key_file_path: Optional[str] = None
        self.key_file_dir = key_file_dir

    @classmethod
    def from_client(cls) -> "KeyPairWrapper":
        """
        Class method to create an instance of KeyPairWrapper using a new EC2 client
        and a temporary directory for storing key files.

        :return: An instance of KeyPairWrapper.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client, tempfile.TemporaryDirectory())


    def create(self, key_name: str) -> dict:
        """
        Creates a key pair that can be used to securely connect to an EC2 instance.
        The returned key pair contains private key information that cannot be retrieved
        again. The private key data is stored as a .pem file.

        :param key_name: The name of the key pair to create.
        :return: A dictionary representing the Boto3 KeyPair object that represents the newly created key pair.
        :raises ClientError: If there is an error in creating the key pair, for example, if a key pair with the same name already exists.
        """
        try:
            response = self.ec2_client.create_key_pair(KeyName=key_name)
            self.key_pair = response
            self.key_file_path = os.path.join(
                self.key_file_dir.name, f"{self.key_pair['KeyName']}.pem"
            )
            with open(self.key_file_path, "w") as key_file:
                key_file.write(self.key_pair["KeyMaterial"])
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidKeyPair.Duplicate":
                logger.error(
                    f"A key pair called {key_name} already exists. "
                    "Please choose a different name for your key pair "
                    "or delete the existing key pair before creating."
                )
            raise
        else:
            return self.key_pair
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateKeyPair](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateKeyPair)」を参照してください。

### `CreateLaunchTemplate`
<a name="ec2_CreateLaunchTemplate_python_3_topic"></a>

次のコード例は、`CreateLaunchTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
この例では、インスタンスに特定のアクセス許可を付与するインスタンスプロファイルと、起動後にインスタンスで実行されるユーザーデータの Bash スクリプトを含む起動テンプレートを作成します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_template(
        self, server_startup_script_file: str, instance_policy_file: str
    ) -> Dict[str, Any]:
        """
        Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. The
        launch template specifies a Bash script in its user data field that runs after
        the instance is started. This script installs Python packages and starts a
        Python web server on the instance.

        :param server_startup_script_file: The path to a Bash script file that is run
                                           when an instance starts.
        :param instance_policy_file: The path to a file that defines a permissions policy
                                     to create and attach to the instance profile.
        :return: Information about the newly created template.
        """
        template = {}
        try:
            # Create key pair and instance profile
            self.create_key_pair(self.key_pair_name)
            self.create_instance_profile(
                instance_policy_file,
                self.instance_policy_name,
                self.instance_role_name,
                self.instance_profile_name,
            )

            # Read the startup script
            with open(server_startup_script_file) as file:
                start_server_script = file.read()

            # Get the latest AMI ID
            ami_latest = self.ssm_client.get_parameter(Name=self.ami_param)
            ami_id = ami_latest["Parameter"]["Value"]

            # Create the launch template
            lt_response = self.ec2_client.create_launch_template(
                LaunchTemplateName=self.launch_template_name,
                LaunchTemplateData={
                    "InstanceType": self.inst_type,
                    "ImageId": ami_id,
                    "IamInstanceProfile": {"Name": self.instance_profile_name},
                    "UserData": base64.b64encode(
                        start_server_script.encode(encoding="utf-8")
                    ).decode(encoding="utf-8"),
                    "KeyName": self.key_pair_name,
                },
            )
            template = lt_response["LaunchTemplate"]
            log.info(
                f"Created launch template {self.launch_template_name} for AMI {ami_id} on {self.inst_type}."
            )
        except ClientError as err:
            log.error(f"Failed to create launch template {self.launch_template_name}.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidLaunchTemplateName.AlreadyExistsException":
                log.info(
                    f"Launch template {self.launch_template_name} already exists, nothing to do."
                )
            log.error(f"Full error:\n\t{err}")
        return template
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateLaunchTemplate)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_python_3_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(self, group_name: str, group_description: str) -> str:
        """
        Creates a security group in the default virtual private cloud (VPC) of the current account.

        :param group_name: The name of the security group to create.
        :param group_description: The description of the security group to create.
        :return: The ID of the newly created security group.
        :raise Handles AWS SDK service-level ClientError, with special handling for ResourceAlreadyExists
        """
        try:
            response = self.ec2_client.create_security_group(
                GroupName=group_name, Description=group_description
            )
            self.security_group = response["GroupId"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExists":
                logger.error(
                    f"Security group '{group_name}' already exists. Please choose a different name."
                )
            raise
        else:
            return self.security_group
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateSecurityGroup](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateSecurityGroup)」を参照してください。

### `CreateVpc`
<a name="ec2_CreateVpc_python_3_topic"></a>

次のコード例は、`CreateVpc` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(self, cidr_block: str) -> str:
        """
        Creates a new Amazon VPC with the specified CIDR block.

        :param cidr_block: The CIDR block for the new VPC, such as '10.0.0.0/16'.
        :return: The ID of the new VPC.
        """
        try:
            response = self.ec2_client.create_vpc(CidrBlock=cidr_block)
            vpc_id = response["Vpc"]["VpcId"]

            waiter = self.ec2_client.get_waiter("vpc_available")
            waiter.wait(VpcIds=[vpc_id])
            return vpc_id
        except ClientError as client_error:
            logging.error(
                "Couldn't create the vpc. Here's why: %s",
                client_error.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateVpc](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateVpc)」を参照してください。**

### `CreateVpcEndpoint`
<a name="ec2_CreateVpcEndpoint_python_3_topic"></a>

次のコード例は、`CreateVpcEndpoint` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create_vpc_endpoint(
        self, vpc_id: str, service_name: str, route_table_ids: list[str]
    ) -> Dict[str, Any]:
        """
        Creates a new VPC endpoint for the specified service and associates it with the specified route tables.

        :param vpc_id: The ID of the VPC to create the endpoint in.
        :param service_name: The name of the service to create the endpoint for.
        :param route_table_ids: A list of IDs of the route tables to associate with the endpoint.
        :return: A dictionary representing the newly created VPC endpoint.
        """
        try:
            response = self.ec2_client.create_vpc_endpoint(
                VpcId=vpc_id,
                ServiceName=service_name,
                RouteTableIds=route_table_ids,
            )
            return response["VpcEndpoint"]
        except ClientError as err:
            logger.error(
                "Couldn't create VPC endpoint for service %s. Here's why: %s: %s",
                service_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateVpcEndpoint](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateVpcEndpoint)」を参照してください。**

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_python_3_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class KeyPairWrapper:
    """
    Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.
    This class provides methods to create, list, and delete EC2 key pairs.
    """

    def __init__(
        self,
        ec2_client: boto3.client,
        key_file_dir: Union[tempfile.TemporaryDirectory, str],
        key_pair: Optional[dict] = None,
    ):
        """
        Initializes the KeyPairWrapper with the specified EC2 client, key file directory,
        and an optional key pair.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param key_file_dir: The folder where the private key information is stored.
                             This should be a secure folder.
        :param key_pair: A dictionary representing the Boto3 KeyPair object.
                         This is a high-level object that wraps key pair actions. Optional.
        """
        self.ec2_client = ec2_client
        self.key_pair = key_pair
        self.key_file_path: Optional[str] = None
        self.key_file_dir = key_file_dir

    @classmethod
    def from_client(cls) -> "KeyPairWrapper":
        """
        Class method to create an instance of KeyPairWrapper using a new EC2 client
        and a temporary directory for storing key files.

        :return: An instance of KeyPairWrapper.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client, tempfile.TemporaryDirectory())


    def delete(self, key_name: str) -> bool:
        """
        Deletes a key pair by its name.

        :param key_name: The name of the key pair to delete.
        :return: A boolean indicating whether the deletion was successful.
        :raises ClientError: If there is an error in deleting the key pair, for example,
                             if the key pair does not exist.
        """
        try:
            self.ec2_client.delete_key_pair(KeyName=key_name)
            logger.info(f"Successfully deleted key pair: {key_name}")
            self.key_pair = None
            return True
        except self.ec2_client.exceptions.ClientError as err:
            logger.error(f"Deletion failed for key pair: {key_name}")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidKeyPair.NotFound":
                logger.error(
                    f"The key pair '{key_name}' does not exist and cannot be deleted. "
                    "Please verify the key pair name and try again."
                )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteKeyPair](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteKeyPair)」を参照してください。

### `DeleteLaunchTemplate`
<a name="ec2_DeleteLaunchTemplate_python_3_topic"></a>

次のコード例は、`DeleteLaunchTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def delete_template(self):
        """
        Deletes a launch template.
        """
        try:
            self.ec2_client.delete_launch_template(
                LaunchTemplateName=self.launch_template_name
            )
            self.delete_instance_profile(
                self.instance_profile_name, self.instance_role_name
            )
            log.info("Launch template %s deleted.", self.launch_template_name)
        except ClientError as err:
            if (
                err.response["Error"]["Code"]
                == "InvalidLaunchTemplateName.NotFoundException"
            ):
                log.info(
                    "Launch template %s does not exist, nothing to do.",
                    self.launch_template_name,
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteLaunchTemplate)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_python_3_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def delete(self, security_group_id: str) -> bool:
        """
        Deletes the specified security group.

        :param security_group_id: The ID of the security group to delete. Required.

        :returns: True if the deletion is successful.
        :raises ClientError: If the security group cannot be deleted due to an AWS service error.
        """
        try:
            self.ec2_client.delete_security_group(GroupId=security_group_id)
            logger.info(f"Successfully deleted security group '{security_group_id}'")
            return True
        except ClientError as err:
            logger.error(f"Deletion failed for security group '{security_group_id}'")
            error_code = err.response["Error"]["Code"]

            if error_code == "InvalidGroup.NotFound":
                logger.error(
                    f"Security group '{security_group_id}' cannot be deleted because it does not exist."
                )
            elif error_code == "DependencyViolation":
                logger.error(
                    f"Security group '{security_group_id}' cannot be deleted because it is still in use."
                    " Verify that it is:"
                    "\n\t- Detached from resources"
                    "\n\t- Removed from references in other groups"
                    "\n\t- Removed from VPC's as a default group"
                )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteSecurityGroup](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteSecurityGroup)」を参照してください。

### `DeleteVpc`
<a name="ec2_DeleteVpc_python_3_topic"></a>

次のコード例は、`DeleteVpc` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def delete(self, vpc_id: str) -> None:
        """
        Deletes the specified VPC.

        :param vpc_id: The ID of the VPC to delete.
        """
        try:
            self.ec2_client.delete_vpc(VpcId=vpc_id)
        except ClientError as err:
            logger.error(
                "Couldn't delete VPC %s. Here's why: %s: %s",
                vpc_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteVpc](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteVpc)」を参照してください。**

### `DeleteVpcEndpoints`
<a name="ec2_DeleteVpcEndpoints_python_3_topic"></a>

次のコード例は、`DeleteVpcEndpoints` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def delete_vpc_endpoints(self, vpc_endpoint_ids: list[str]) -> None:
        """
        Deletes the specified VPC endpoints.

        :param vpc_endpoint_ids: A list of IDs of the VPC endpoints to delete.
        """
        try:
            self.ec2_client.delete_vpc_endpoints(VpcEndpointIds=vpc_endpoint_ids)
        except ClientError as err:
            logger.error(
                "Couldn't delete VPC endpoints %s. Here's why: %s: %s",
                vpc_endpoint_ids,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteVpcEndpoints](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteVpcEndpoints)」を参照してください。**

### `DescribeAvailabilityZones`
<a name="ec2_DescribeAvailabilityZones_python_3_topic"></a>

次のコード例は、`DescribeAvailabilityZones` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_availability_zones(self) -> List[str]:
        """
        Gets a list of Availability Zones in the AWS Region of the Amazon EC2 client.

        :return: The list of Availability Zones for the client Region.
        """
        try:
            response = self.ec2_client.describe_availability_zones()
            zones = [zone["ZoneName"] for zone in response["AvailabilityZones"]]
            log.info(f"Retrieved {len(zones)} availability zones: {zones}.")
        except ClientError as err:
            log.error("Failed to retrieve availability zones.")
            log.error(f"Full error:\n\t{err}")
        else:
            return zones
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeAvailabilityZones)」を参照してください。

### `DescribeIamInstanceProfileAssociations`
<a name="ec2_DescribeIamInstanceProfileAssociations_python_3_topic"></a>

次のコード例は、`DescribeIamInstanceProfileAssociations` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_instance_profile(self, instance_id: str) -> Dict[str, Any]:
        """
        Gets data about the profile associated with an instance.

        :param instance_id: The ID of the instance to look up.
        :return: The profile data.
        """
        try:
            response = self.ec2_client.describe_iam_instance_profile_associations(
                Filters=[{"Name": "instance-id", "Values": [instance_id]}]
            )
            if not response["IamInstanceProfileAssociations"]:
                log.info(f"No instance profile found for instance {instance_id}.")
            profile_data = response["IamInstanceProfileAssociations"][0]
            log.info(f"Retrieved instance profile for instance {instance_id}.")
            return profile_data
        except ClientError as err:
            log.error(
                f"Failed to retrieve instance profile for instance {instance_id}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                log.error(f"The instance ID '{instance_id}' does not exist.")
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)」を参照してください。

### `DescribeImages`
<a name="ec2_DescribeImages_python_3_topic"></a>

次のコード例は、`DescribeImages` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def get_images(self, image_ids: List[str]) -> List[Dict[str, Any]]:
        """
        Gets information about Amazon Machine Images (AMIs) from a list of AMI IDs.

        :param image_ids: The list of AMI IDs to look up.
        :return: A list of dictionaries representing the requested AMIs.
        """
        try:
            response = self.ec2_client.describe_images(ImageIds=image_ids)
            images = response["Images"]
        except ClientError as err:
            logger.error(f"Failed to stop AMI(s): {','.join(map(str, image_ids))}")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAMIID.NotFound":
                logger.error("One or more of the AMI IDs does not exist.")
            raise
        return images
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeImages](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeImages)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_python_3_topic"></a>

次のコード例は、`DescribeInstanceTypes` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def get_instance_types(
        self, architecture: str = "x86_64", sizes: List[str] = ["*.micro", "*.small"]
    ) -> List[Dict[str, Any]]:
        """
        Gets instance types that support the specified architecture and size.
        See https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstanceTypes.html
        for a list of allowable parameters.

        :param architecture: The architecture supported by instance types. Default: 'x86_64'.
        :param sizes: The size of instance types. Default: '*.micro', '*.small',
        :return: A list of dictionaries representing instance types that support the specified architecture and size.
        """
        try:
            inst_types = []
            paginator = self.ec2_client.get_paginator("describe_instance_types")
            for page in paginator.paginate(
                Filters=[
                    {
                        "Name": "processor-info.supported-architecture",
                        "Values": [architecture],
                    },
                    {"Name": "instance-type", "Values": sizes},
                ]
            ):
                inst_types += page["InstanceTypes"]
        except ClientError as err:
            logger.error(
                f"Failed to get instance types: {architecture}, {','.join(map(str, sizes))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidParameterValue":
                logger.error(
                    "Parameters are invalid. "
                    "Ensure architecture and size strings conform to DescribeInstanceTypes API reference."
                )
            raise
        else:
            return inst_types
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeInstanceTypes](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstanceTypes)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_python_3_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def display(self, state_filter: Optional[str] = "running") -> None:
        """
        Displays information about instances, filtering by the specified state.

        :param state_filter: The instance state to include in the output. Only instances in this state
                             will be displayed. Default is 'running'. Example states: 'running', 'stopped'.
        """
        if not self.instances:
            logger.info("No instances to display.")
            return

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        paginator = self.ec2_client.get_paginator("describe_instances")
        page_iterator = paginator.paginate(InstanceIds=instance_ids)

        try:
            for page in page_iterator:
                for reservation in page["Reservations"]:
                    for instance in reservation["Instances"]:
                        instance_state = instance["State"]["Name"]

                        # Apply the state filter (default is 'running')
                        if state_filter and instance_state != state_filter:
                            continue  # Skip this instance if it doesn't match the filter

                        # Create a formatted string with instance details
                        instance_info = (
                            f"• ID: {instance['InstanceId']}\n"
                            f"• Image ID: {instance['ImageId']}\n"
                            f"• Instance type: {instance['InstanceType']}\n"
                            f"• Key name: {instance['KeyName']}\n"
                            f"• VPC ID: {instance['VpcId']}\n"
                            f"• Public IP: {instance.get('PublicIpAddress', 'N/A')}\n"
                            f"• State: {instance_state}"
                        )
                        print(instance_info)

        except ClientError as err:
            logger.error(
                f"Failed to display instance(s). : {' '.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                logger.error(
                    "One or more instance IDs do not exist. "
                    "Please verify the instance IDs and try again."
                )
                raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstances)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_python_3_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class KeyPairWrapper:
    """
    Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) key pair actions.
    This class provides methods to create, list, and delete EC2 key pairs.
    """

    def __init__(
        self,
        ec2_client: boto3.client,
        key_file_dir: Union[tempfile.TemporaryDirectory, str],
        key_pair: Optional[dict] = None,
    ):
        """
        Initializes the KeyPairWrapper with the specified EC2 client, key file directory,
        and an optional key pair.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param key_file_dir: The folder where the private key information is stored.
                             This should be a secure folder.
        :param key_pair: A dictionary representing the Boto3 KeyPair object.
                         This is a high-level object that wraps key pair actions. Optional.
        """
        self.ec2_client = ec2_client
        self.key_pair = key_pair
        self.key_file_path: Optional[str] = None
        self.key_file_dir = key_file_dir

    @classmethod
    def from_client(cls) -> "KeyPairWrapper":
        """
        Class method to create an instance of KeyPairWrapper using a new EC2 client
        and a temporary directory for storing key files.

        :return: An instance of KeyPairWrapper.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client, tempfile.TemporaryDirectory())


    def list(self, limit: Optional[int] = None) -> None:
        """
        Displays a list of key pairs for the current account.

        WARNING: Results are not paginated.

        :param limit: The maximum number of key pairs to list. If not specified,
                      all key pairs will be listed.
        :raises ClientError: If there is an error in listing the key pairs.
        """
        try:
            response = self.ec2_client.describe_key_pairs()
            key_pairs = response.get("KeyPairs", [])

            if limit:
                key_pairs = key_pairs[:limit]

            for key_pair in key_pairs:
                logger.info(
                    f"Found {key_pair['KeyType']} key '{key_pair['KeyName']}' with fingerprint:"
                )
                logger.info(f"\t{key_pair['KeyFingerprint']}")
        except ClientError as err:
            logger.error(f"Failed to list key pairs: {str(err)}")
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeKeyPairs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeKeyPairs)」を参照してください。

### `DescribeRouteTables`
<a name="ec2_DescribeRouteTables_python_3_topic"></a>

次のコード例は、`DescribeRouteTables` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class VpcWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Amazon Virtual Private Cloud actions."""

    def __init__(self, ec2_client: boto3.client):
        """
        Initializes the VpcWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client

    @classmethod
    def from_client(cls) -> "VpcWrapper":
        """
        Creates a VpcWrapper instance with a default EC2 client.

        :return: An instance of VpcWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def describe_route_tables(self, vpc_ids: list[str]) -> None:
        """
        Displays information about the route tables in the specified VPC.

        :param vpc_ids: A list of VPC IDs.
        """
        try:
            response = self.ec2_client.describe_route_tables(
                Filters=[{"Name": "vpc-id", "Values": vpc_ids}]
            )
            pp(response["RouteTables"])
        except ClientError as err:
            logger.error(
                "Couldn't describe route tables for VPCs %s. Here's why: %s: %s",
                vpc_ids,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeRouteTables](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeRouteTables)」を参照してください。**

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_python_3_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class SecurityGroupWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions."""

    def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None):
        """
        Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param security_group: The ID of a security group to manage. This is a high-level identifier
                               that represents the security group.
        """
        self.ec2_client = ec2_client
        self.security_group = security_group

    @classmethod
    def from_client(cls) -> "SecurityGroupWrapper":
        """
        Creates a SecurityGroupWrapper instance with a default EC2 client.

        :return: An instance of SecurityGroupWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def describe(self, security_group_id: Optional[str] = None) -> bool:
        """
        Displays information about the specified security group or all security groups if no ID is provided.

        :param security_group_id: The ID of the security group to describe.
                                  If None, an open search is performed to describe all security groups.
        :returns: True if the description is successful.
        :raises ClientError: If there is an error describing the security group(s), such as an invalid security group ID.
        """
        try:
            paginator = self.ec2_client.get_paginator("describe_security_groups")

            if security_group_id is None:
                # If no ID is provided, return all security groups.
                page_iterator = paginator.paginate()
            else:
                page_iterator = paginator.paginate(GroupIds=[security_group_id])

            for page in page_iterator:
                for security_group in page["SecurityGroups"]:
                    print(f"Security group: {security_group['GroupName']}")
                    print(f"\tID: {security_group['GroupId']}")
                    print(f"\tVPC: {security_group['VpcId']}")
                    if security_group["IpPermissions"]:
                        print("Inbound permissions:")
                        pp(security_group["IpPermissions"])

            return True
        except ClientError as err:
            logger.error("Failed to describe security group(s).")
            if err.response["Error"]["Code"] == "InvalidGroup.NotFound":
                logger.error(
                    f"Security group {security_group_id} does not exist "
                    f"because the specified security group ID was not found."
                )
            raise
```
+  API の詳細については、「*AWS  SDK for Python (Boto3) API リファレンス*」の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

### `DescribeSubnets`
<a name="ec2_DescribeSubnets_python_3_topic"></a>

次のコード例は、`DescribeSubnets` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_subnets(self, vpc_id: str, zones: List[str] = None) -> List[Dict[str, Any]]:
        """
        Gets the default subnets in a VPC for a specified list of Availability Zones.

        :param vpc_id: The ID of the VPC to look up.
        :param zones: The list of Availability Zones to look up.
        :return: The list of subnets found.
        """
        # Ensure that 'zones' is a list, even if None is passed
        if zones is None:
            zones = []
        try:
            paginator = self.ec2_client.get_paginator("describe_subnets")
            page_iterator = paginator.paginate(
                Filters=[
                    {"Name": "vpc-id", "Values": [vpc_id]},
                    {"Name": "availability-zone", "Values": zones},
                    {"Name": "default-for-az", "Values": ["true"]},
                ]
            )

            subnets = []
            for page in page_iterator:
                subnets.extend(page["Subnets"])

            log.info("Found %s subnets for the specified zones.", len(subnets))
            return subnets
        except ClientError as err:
            log.error(
                f"Failed to retrieve subnets for VPC '{vpc_id}' in zones {zones}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    "The specified VPC ID does not exist. "
                    "Please check the VPC ID and try again."
                )
            # Add more error-specific handling as needed
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeSubnets](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSubnets)」を参照してください。

### `DescribeVpcs`
<a name="ec2_DescribeVpcs_python_3_topic"></a>

次のコード例は、`DescribeVpcs` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def get_default_vpc(self) -> Dict[str, Any]:
        """
        Gets the default VPC for the account.

        :return: Data about the default VPC.
        """
        try:
            response = self.ec2_client.describe_vpcs(
                Filters=[{"Name": "is-default", "Values": ["true"]}]
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error("Failed to retrieve the default VPC.")
            if error_code == "UnauthorizedOperation":
                log.error(
                    "You do not have the necessary permissions to describe VPCs. "
                    "Ensure that your AWS IAM user or role has the correct permissions."
                )
            elif error_code == "InvalidParameterValue":
                log.error(
                    "One or more parameters are invalid. Check the request parameters."
                )

            log.error(f"Full error:\n\t{err}")
        else:
            if "Vpcs" in response and response["Vpcs"]:
                log.info(f"Retrieved default VPC: {response['Vpcs'][0]['VpcId']}")
                return response["Vpcs"][0]
            else:
                pass
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeVpcs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeVpcs)」を参照してください。

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_python_3_topic"></a>

次のコード例は、`DisassociateAddress` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def disassociate(self, allocation_id: str) -> None:
        """
        Removes an association between an Elastic IP address and an instance. When the
        association is removed, the instance is assigned a new public IP address.

        :param allocation_id: The allocation ID of the Elastic IP to disassociate.
        :raises ClientError: If the disassociation fails, such as when the association ID is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None or elastic_ip.instance_id is None:
            logger.info(
                f"No association found for Elastic IP with allocation ID {allocation_id}."
            )
            return

        try:
            # Retrieve the association ID before disassociating
            response = self.ec2_client.describe_addresses(AllocationIds=[allocation_id])
            association_id = response["Addresses"][0].get("AssociationId")

            if association_id:
                self.ec2_client.disassociate_address(AssociationId=association_id)
                elastic_ip.instance_id = None  # Remove the instance association
            else:
                logger.info(
                    f"No Association ID found for Elastic IP with allocation ID {allocation_id}."
                )

        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidAssociationID.NotFound":
                logger.error(
                    f"Failed to disassociate Elastic IP {allocation_id} "
                    "because the specified association ID for the Elastic IP address was not found. "
                    "Verify the association ID and ensure the Elastic IP is currently associated with a "
                    "resource before attempting to disassociate it."
                )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DisassociateAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DisassociateAddress)」を参照してください。

### `RebootInstances`
<a name="ec2_RebootInstances_python_3_topic"></a>

次のコード例は、`RebootInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[RebootInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RebootInstances)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_python_3_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class ElasticIpWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) Elastic IP address actions using the client interface."""

    class ElasticIp:
        """Represents an Elastic IP and its associated instance."""

        def __init__(
            self, allocation_id: str, public_ip: str, instance_id: Optional[str] = None
        ) -> None:
            """
            Initializes the ElasticIp object.

            :param allocation_id: The allocation ID of the Elastic IP.
            :param public_ip: The public IP address of the Elastic IP.
            :param instance_id: The ID of the associated EC2 instance, if any.
            """
            self.allocation_id = allocation_id
            self.public_ip = public_ip
            self.instance_id = instance_id

    def __init__(self, ec2_client: Any) -> None:
        """
        Initializes the ElasticIpWrapper with an EC2 client.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        """
        self.ec2_client = ec2_client
        self.elastic_ips: List[ElasticIpWrapper.ElasticIp] = []

    @classmethod
    def from_client(cls) -> "ElasticIpWrapper":
        """
        Creates an ElasticIpWrapper instance with a default EC2 client.

        :return: An instance of ElasticIpWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def release(self, allocation_id: str) -> None:
        """
        Releases an Elastic IP address. After the Elastic IP address is released,
        it can no longer be used.

        :param allocation_id: The allocation ID of the Elastic IP to release.
        :raises ClientError: If the release fails, such as when the Elastic IP address is not found.
        """
        elastic_ip = self.get_elastic_ip_by_allocation(self.elastic_ips, allocation_id)
        if elastic_ip is None:
            logger.info(f"No Elastic IP found with allocation ID {allocation_id}.")
            return

        try:
            self.ec2_client.release_address(AllocationId=allocation_id)
            self.elastic_ips.remove(elastic_ip)  # Remove the Elastic IP from the list
        except ClientError as err:
            if err.response["Error"]["Code"] == "InvalidAddress.NotFound":
                logger.error(
                    f"Failed to release Elastic IP address {allocation_id} "
                    "because it could not be found. Verify the Elastic IP address "
                    "and ensure it is allocated to your account in the correct region "
                    "before attempting to release it."
                )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ReleaseAddress](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReleaseAddress)」を参照してください。

### `ReplaceIamInstanceProfileAssociation`
<a name="ec2_ReplaceIamInstanceProfileAssociation_python_3_topic"></a>

次のコード例は、`ReplaceIamInstanceProfileAssociation` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
この例では、実行中のインスタンスのインスタンスプロファイルを置き換え、インスタンスを再起動し、起動後にインスタンスにコマンドを送信します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_python_3_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def create(
        self,
        image_id: str,
        instance_type: str,
        key_pair_name: str,
        security_group_ids: Optional[List[str]] = None,
    ) -> List[Dict[str, Any]]:
        """
        Creates a new EC2 instance in the default VPC of the current account.

        The instance starts immediately after it is created.

        :param image_id: The ID of the Amazon Machine Image (AMI) to use for the instance.
        :param instance_type: The type of instance to create, such as 't2.micro'.
        :param key_pair_name: The name of the key pair to use for SSH access.
        :param security_group_ids: A list of security group IDs to associate with the instance.
                                   If not specified, the default security group of the VPC is used.
        :return: A list of dictionaries representing Boto3 Instance objects representing the newly created instances.
        """
        try:
            instance_params = {
                "ImageId": image_id,
                "InstanceType": instance_type,
                "KeyName": key_pair_name,
            }
            if security_group_ids is not None:
                instance_params["SecurityGroupIds"] = security_group_ids

            response = self.ec2_client.run_instances(
                **instance_params, MinCount=1, MaxCount=1
            )
            instance = response["Instances"][0]
            self.instances.append(instance)
            waiter = self.ec2_client.get_waiter("instance_running")
            waiter.wait(InstanceIds=[instance["InstanceId"]])
        except ClientError as err:
            params_str = "\n\t".join(
                f"{key}: {value}" for key, value in instance_params.items()
            )
            logger.error(
                f"Failed to complete instance creation request.\nRequest details:{params_str}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InstanceLimitExceeded":
                logger.error(
                    (
                        f"Insufficient capacity for instance type '{instance_type}'. "
                        "Terminate unused instances or contact AWS Support for a limit increase."
                    )
                )
            if error_code == "InsufficientInstanceCapacity":
                logger.error(
                    (
                        f"Insufficient capacity for instance type '{instance_type}'. "
                        "Select a different instance type or launch in a different availability zone."
                    )
                )
            raise
        return self.instances
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[RunInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RunInstances)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_python_3_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def start(self) -> Optional[Dict[str, Any]]:
        """
        Starts instances and waits for them to be in a running state.

        :return: The response to the start request.
        """
        if not self.instances:
            logger.info("No instances to start.")
            return None

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            start_response = self.ec2_client.start_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_running")
            waiter.wait(InstanceIds=instance_ids)
            return start_response
        except ClientError as err:
            logger.error(
                f"Failed to start instance(s): {','.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "IncorrectInstanceState":
                logger.error(
                    "Couldn't start instance(s) because they are in an incorrect state. "
                    "Ensure the instances are in a stopped state before starting them."
                )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[StartInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/StartInstances)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_python_3_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def stop(self) -> Optional[Dict[str, Any]]:
        """
        Stops instances and waits for them to be in a stopped state.

        :return: The response to the stop request, or None if there are no instances to stop.
        """
        if not self.instances:
            logger.info("No instances to stop.")
            return None

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            # Attempt to stop the instances
            stop_response = self.ec2_client.stop_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_stopped")
            waiter.wait(InstanceIds=instance_ids)
        except ClientError as err:
            logger.error(
                f"Failed to stop instance(s): {','.join(map(str, instance_ids))}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "IncorrectInstanceState":
                logger.error(
                    "Couldn't stop instance(s) because they are in an incorrect state. "
                    "Ensure the instances are in a running state before stopping them."
                )
            raise
        return stop_response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[StopInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/StopInstances)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_python_3_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
class EC2InstanceWrapper:
    """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) instance actions using the client interface."""

    def __init__(
        self, ec2_client: Any, instances: Optional[List[Dict[str, Any]]] = None
    ) -> None:
        """
        Initializes the EC2InstanceWrapper with an EC2 client and optional instances.

        :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level
                           access to AWS EC2 services.
        :param instances: A list of dictionaries representing Boto3 Instance objects. These are high-level objects that
                          wrap instance actions.
        """
        self.ec2_client = ec2_client
        self.instances = instances or []

    @classmethod
    def from_client(cls) -> "EC2InstanceWrapper":
        """
        Creates an EC2InstanceWrapper instance with a default EC2 client.

        :return: An instance of EC2InstanceWrapper initialized with the default EC2 client.
        """
        ec2_client = boto3.client("ec2")
        return cls(ec2_client)


    def terminate(self) -> None:
        """
        Terminates instances and waits for them to reach the terminated state.
        """
        if not self.instances:
            logger.info("No instances to terminate.")
            return

        instance_ids = [instance["InstanceId"] for instance in self.instances]
        try:
            self.ec2_client.terminate_instances(InstanceIds=instance_ids)
            waiter = self.ec2_client.get_waiter("instance_terminated")
            waiter.wait(InstanceIds=instance_ids)
            self.instances.clear()
            for instance_id in instance_ids:
                print(f"• Instance ID: {instance_id}\n" f"• Action: Terminated")

        except ClientError as err:
            logger.error(
                f"Failed instance termination details:\n\t{str(self.instances)}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                logger.error(
                    "One or more instance IDs do not exist. "
                    "Please verify the instance IDs and try again."
                )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[TerminateInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/TerminateInstances)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_python_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class Runner:
    """
    Manages the deployment, demonstration, and destruction of resources for the resilient service.
    """

    def __init__(
        self,
        resource_path: str,
        recommendation: RecommendationService,
        autoscaler: AutoScalingWrapper,
        loadbalancer: ElasticLoadBalancerWrapper,
        param_helper: ParameterHelper,
    ):
        """
        Initializes the Runner class with the necessary parameters.

        :param resource_path: The path to resource files used by this example, such as IAM policies and instance scripts.
        :param recommendation: An instance of the RecommendationService class.
        :param autoscaler: An instance of the AutoScaler class.
        :param loadbalancer: An instance of the LoadBalancer class.
        :param param_helper: An instance of the ParameterHelper class.
        """
        self.resource_path = resource_path
        self.recommendation = recommendation
        self.autoscaler = autoscaler
        self.loadbalancer = loadbalancer
        self.param_helper = param_helper
        self.protocol = "HTTP"
        self.port = 80
        self.ssh_port = 22

        prefix = "doc-example-resilience"
        self.target_group_name = f"{prefix}-tg"
        self.load_balancer_name = f"{prefix}-lb"

    def deploy(self) -> None:
        """
        Deploys the resources required for the resilient service, including the DynamoDB table,
        EC2 instances, Auto Scaling group, and load balancer.
        """
        recommendations_path = f"{self.resource_path}/recommendations.json"
        startup_script = f"{self.resource_path}/server_startup_script.sh"
        instance_policy = f"{self.resource_path}/instance_policy.json"

        logging.info("Starting deployment of resources for the resilient service.")

        logging.info(
            "Creating and populating DynamoDB table '%s'.",
            self.recommendation.table_name,
        )
        self.recommendation.create()
        self.recommendation.populate(recommendations_path)

        logging.info(
            "Creating an EC2 launch template with the startup script '%s'.",
            startup_script,
        )
        self.autoscaler.create_template(startup_script, instance_policy)

        logging.info(
            "Creating an EC2 Auto Scaling group across multiple Availability Zones."
        )
        zones = self.autoscaler.create_autoscaling_group(3)

        logging.info("Creating variables that control the flow of the demo.")
        self.param_helper.reset()

        logging.info("Creating Elastic Load Balancing target group and load balancer.")

        vpc = self.autoscaler.get_default_vpc()
        subnets = self.autoscaler.get_subnets(vpc["VpcId"], zones)
        target_group = self.loadbalancer.create_target_group(
            self.target_group_name, self.protocol, self.port, vpc["VpcId"]
        )
        self.loadbalancer.create_load_balancer(
            self.load_balancer_name, [subnet["SubnetId"] for subnet in subnets]
        )
        self.loadbalancer.create_listener(self.load_balancer_name, target_group)

        self.autoscaler.attach_load_balancer_target_group(target_group)

        logging.info("Verifying access to the load balancer endpoint.")
        endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
        lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)
        current_ip_address = requests.get("http://checkip.amazonaws.com").text.strip()

        if not lb_success:
            logging.warning(
                "Couldn't connect to the load balancer. Verifying that the port is open..."
            )
            sec_group, port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.port, current_ip_address
            )
            sec_group, ssh_port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.ssh_port, current_ip_address
            )
            if not port_is_open:
                logging.warning(
                    "The default security group for your VPC must allow access from this computer."
                )
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound traffic on port {self.port} from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.port, current_ip_address
                    )
            if not ssh_port_is_open:
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound SSH traffic on port {self.ssh_port} for debugging from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.ssh_port, current_ip_address
                    )
            lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)

        if lb_success:
            logging.info(
                "Load balancer is ready. Access it at: http://%s", current_ip_address
            )
        else:
            logging.error(
                "Couldn't get a successful response from the load balancer endpoint. Please verify your VPC and security group settings."
            )

    def demo_choices(self) -> None:
        """
        Presents choices for interacting with the deployed service, such as sending requests to
        the load balancer or checking the health of the targets.
        """
        actions = [
            "Send a GET request to the load balancer endpoint.",
            "Check the health of load balancer targets.",
            "Go to the next part of the demo.",
        ]
        choice = 0
        while choice != 2:
            logging.info("Choose an action to interact with the service.")
            choice = q.choose("Which action would you like to take? ", actions)
            if choice == 0:
                logging.info("Sending a GET request to the load balancer endpoint.")
                endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
                logging.info("GET http://%s", endpoint)
                response = requests.get(f"http://{endpoint}")
                logging.info("Response: %s", response.status_code)
                if response.headers.get("content-type") == "application/json":
                    pp(response.json())
            elif choice == 1:
                logging.info("Checking the health of load balancer targets.")
                health = self.loadbalancer.check_target_health(self.target_group_name)
                for target in health:
                    state = target["TargetHealth"]["State"]
                    logging.info(
                        "Target %s on port %d is %s",
                        target["Target"]["Id"],
                        target["Target"]["Port"],
                        state,
                    )
                    if state != "healthy":
                        logging.warning(
                            "%s: %s",
                            target["TargetHealth"]["Reason"],
                            target["TargetHealth"]["Description"],
                        )
                logging.info(
                    "Note that it can take a minute or two for the health check to update."
                )
            elif choice == 2:
                logging.info("Proceeding to the next part of the demo.")

    def demo(self) -> None:
        """
        Runs the demonstration, showing how the service responds to different failure scenarios
        and how a resilient architecture can keep the service running.
        """
        ssm_only_policy = f"{self.resource_path}/ssm_only_policy.json"

        logging.info("Resetting parameters to starting values for the demo.")
        self.param_helper.reset()

        logging.info(
            "Starting demonstration of the service's resilience under various failure conditions."
        )
        self.demo_choices()

        logging.info(
            "Simulating failure by changing the Systems Manager parameter to a non-existent table."
        )
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info("Sending GET requests will now return failure codes.")
        self.demo_choices()

        logging.info("Switching to static response mode to mitigate failure.")
        self.param_helper.put(self.param_helper.failure_response, "static")
        logging.info("Sending GET requests will now return static responses.")
        self.demo_choices()

        logging.info("Restoring normal operation of the recommendation service.")
        self.param_helper.put(self.param_helper.table, self.recommendation.table_name)

        logging.info(
            "Introducing a failure by assigning bad credentials to one of the instances."
        )
        self.autoscaler.create_instance_profile(
            ssm_only_policy,
            self.autoscaler.bad_creds_policy_name,
            self.autoscaler.bad_creds_role_name,
            self.autoscaler.bad_creds_profile_name,
            ["AmazonSSMManagedInstanceCore"],
        )
        instances = self.autoscaler.get_instances()
        bad_instance_id = instances[0]
        instance_profile = self.autoscaler.get_instance_profile(bad_instance_id)
        logging.info(
            "Replacing instance profile with bad credentials for instance %s.",
            bad_instance_id,
        )
        self.autoscaler.replace_instance_profile(
            bad_instance_id,
            self.autoscaler.bad_creds_profile_name,
            instance_profile["AssociationId"],
        )
        logging.info(
            "Sending GET requests may return either a valid recommendation or a static response."
        )
        self.demo_choices()

        logging.info("Implementing deep health checks to detect unhealthy instances.")
        self.param_helper.put(self.param_helper.health_check, "deep")
        logging.info("Checking the health of the load balancer targets.")
        self.demo_choices()

        logging.info(
            "Terminating the unhealthy instance to let the auto scaler replace it."
        )
        self.autoscaler.terminate_instance(bad_instance_id)
        logging.info("The service remains resilient during instance replacement.")
        self.demo_choices()

        logging.info("Simulating a complete failure of the recommendation service.")
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info(
            "All instances will report as unhealthy, but the service will still return static responses."
        )
        self.demo_choices()
        self.param_helper.reset()

    def destroy(self, automation=False) -> None:
        """
        Destroys all resources created for the demo, including the load balancer, Auto Scaling group,
        EC2 instances, and DynamoDB table.
        """
        logging.info(
            "This concludes the demo. Preparing to clean up all AWS resources created during the demo."
        )
        if automation:
            cleanup = True
        else:
            cleanup = q.ask(
                "Do you want to clean up all demo resources? (y/n) ", q.is_yesno
            )

        if cleanup:
            logging.info("Deleting load balancer and related resources.")
            self.loadbalancer.delete_load_balancer(self.load_balancer_name)
            self.loadbalancer.delete_target_group(self.target_group_name)
            self.autoscaler.delete_autoscaling_group(self.autoscaler.group_name)
            self.autoscaler.delete_key_pair()
            self.autoscaler.delete_template()
            self.autoscaler.delete_instance_profile(
                self.autoscaler.bad_creds_profile_name,
                self.autoscaler.bad_creds_role_name,
            )
            logging.info("Deleting DynamoDB table and other resources.")
            self.recommendation.destroy()
        else:
            logging.warning(
                "Resources have not been deleted. Ensure you clean them up manually to avoid unexpected charges."
            )


def main() -> None:
    """
    Main function to parse arguments and run the appropriate actions for the demo.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--action",
        required=True,
        choices=["all", "deploy", "demo", "destroy"],
        help="The action to take for the demo. When 'all' is specified, resources are\n"
        "deployed, the demo is run, and resources are destroyed.",
    )
    parser.add_argument(
        "--resource_path",
        default="../../../scenarios/features/resilient_service/resources",
        help="The path to resource files used by this example, such as IAM policies and\n"
        "instance scripts.",
    )
    args = parser.parse_args()

    logging.info("Starting the Resilient Service demo.")

    prefix = "doc-example-resilience"

    # Service Clients
    ddb_client = boto3.client("dynamodb")
    elb_client = boto3.client("elbv2")
    autoscaling_client = boto3.client("autoscaling")
    ec2_client = boto3.client("ec2")
    ssm_client = boto3.client("ssm")
    iam_client = boto3.client("iam")

    # Wrapper instantiations
    recommendation = RecommendationService(
        "doc-example-recommendation-service", ddb_client
    )
    autoscaling_wrapper = AutoScalingWrapper(
        prefix,
        "t3.micro",
        "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
        autoscaling_client,
        ec2_client,
        ssm_client,
        iam_client,
    )
    elb_wrapper = ElasticLoadBalancerWrapper(elb_client)
    param_helper = ParameterHelper(recommendation.table_name, ssm_client)

    # Demo invocation
    runner = Runner(
        args.resource_path,
        recommendation,
        autoscaling_wrapper,
        elb_wrapper,
        param_helper,
    )
    actions = [args.action] if args.action != "all" else ["deploy", "demo", "destroy"]
    for action in actions:
        if action == "deploy":
            runner.deploy()
        elif action == "demo":
            runner.demo()
        elif action == "destroy":
            runner.destroy()

    logging.info("Demo completed successfully.")


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    main()
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_policy(self, policy_file: str, policy_name: str) -> str:
        """
        Creates a new IAM policy or retrieves the ARN of an existing policy.

        :param policy_file: The path to a JSON file that contains the policy definition.
        :param policy_name: The name to give the created policy.
        :return: The ARN of the created or existing policy.
        """
        with open(policy_file) as file:
            policy_doc = file.read()

        try:
            response = self.iam_client.create_policy(
                PolicyName=policy_name, PolicyDocument=policy_doc
            )
            policy_arn = response["Policy"]["Arn"]
            log.info(f"Policy '{policy_name}' created successfully. ARN: {policy_arn}")
            return policy_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the policy already exists, get its ARN
                response = self.iam_client.get_policy(
                    PolicyArn=f"arn:aws:iam::{self.account_id}:policy/{policy_name}"
                )
                policy_arn = response["Policy"]["Arn"]
                log.info(f"Policy '{policy_name}' already exists. ARN: {policy_arn}")
                return policy_arn
            log.error(f"Full error:\n\t{err}")

    def create_role(self, role_name: str, assume_role_doc: dict) -> str:
        """
        Creates a new IAM role or retrieves the ARN of an existing role.

        :param role_name: The name to give the created role.
        :param assume_role_doc: The assume role policy document that specifies which
                                entities can assume the role.
        :return: The ARN of the created or existing role.
        """
        try:
            response = self.iam_client.create_role(
                RoleName=role_name, AssumeRolePolicyDocument=json.dumps(assume_role_doc)
            )
            role_arn = response["Role"]["Arn"]
            log.info(f"Role '{role_name}' created successfully. ARN: {role_arn}")
            return role_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the role already exists, get its ARN
                response = self.iam_client.get_role(RoleName=role_name)
                role_arn = response["Role"]["Arn"]
                log.info(f"Role '{role_name}' already exists. ARN: {role_arn}")
                return role_arn
            log.error(f"Full error:\n\t{err}")

    def attach_policy(
        self,
        role_name: str,
        policy_arn: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> None:
        """
        Attaches an IAM policy to a role and optionally attaches additional AWS-managed policies.

        :param role_name: The name of the role to attach the policy to.
        :param policy_arn: The ARN of the policy to attach.
        :param aws_managed_policies: A tuple of AWS-managed policy names to attach to the role.
        """
        try:
            self.iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn)
            for aws_policy in aws_managed_policies:
                self.iam_client.attach_role_policy(
                    RoleName=role_name,
                    PolicyArn=f"arn:aws:iam::aws:policy/{aws_policy}",
                )
            log.info(f"Attached policy {policy_arn} to role {role_name}.")
        except ClientError as err:
            log.error(f"Failed to attach policy {policy_arn} to role {role_name}.")
            log.error(f"Full error:\n\t{err}")

    def create_instance_profile(
        self,
        policy_file: str,
        policy_name: str,
        role_name: str,
        profile_name: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> str:
        """
        Creates a policy, role, and profile that is associated with instances created by
        this class. An instance's associated profile defines a role that is assumed by the
        instance. The role has attached policies that specify the AWS permissions granted to
        clients that run on the instance.

        :param policy_file: The name of a JSON file that contains the policy definition to
                            create and attach to the role.
        :param policy_name: The name to give the created policy.
        :param role_name: The name to give the created role.
        :param profile_name: The name to the created profile.
        :param aws_managed_policies: Additional AWS-managed policies that are attached to
                                     the role, such as AmazonSSMManagedInstanceCore to grant
                                     use of Systems Manager to send commands to the instance.
        :return: The ARN of the profile that is created.
        """
        assume_role_doc = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"Service": "ec2.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        policy_arn = self.create_policy(policy_file, policy_name)
        self.create_role(role_name, assume_role_doc)
        self.attach_policy(role_name, policy_arn, aws_managed_policies)

        try:
            profile_response = self.iam_client.create_instance_profile(
                InstanceProfileName=profile_name
            )
            waiter = self.iam_client.get_waiter("instance_profile_exists")
            waiter.wait(InstanceProfileName=profile_name)
            time.sleep(10)  # wait a little longer
            profile_arn = profile_response["InstanceProfile"]["Arn"]
            self.iam_client.add_role_to_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            log.info("Created profile %s and added role %s.", profile_name, role_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                prof_response = self.iam_client.get_instance_profile(
                    InstanceProfileName=profile_name
                )
                profile_arn = prof_response["InstanceProfile"]["Arn"]
                log.info(
                    "Instance profile %s already exists, nothing to do.", profile_name
                )
            log.error(f"Full error:\n\t{err}")
        return profile_arn


    def get_instance_profile(self, instance_id: str) -> Dict[str, Any]:
        """
        Gets data about the profile associated with an instance.

        :param instance_id: The ID of the instance to look up.
        :return: The profile data.
        """
        try:
            response = self.ec2_client.describe_iam_instance_profile_associations(
                Filters=[{"Name": "instance-id", "Values": [instance_id]}]
            )
            if not response["IamInstanceProfileAssociations"]:
                log.info(f"No instance profile found for instance {instance_id}.")
            profile_data = response["IamInstanceProfileAssociations"][0]
            log.info(f"Retrieved instance profile for instance {instance_id}.")
            return profile_data
        except ClientError as err:
            log.error(
                f"Failed to retrieve instance profile for instance {instance_id}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                log.error(f"The instance ID '{instance_id}' does not exist.")
            log.error(f"Full error:\n\t{err}")


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_instance_profile(self, profile_name: str, role_name: str) -> None:
        """
        Detaches a role from an instance profile, detaches policies from the role,
        and deletes all the resources.

        :param profile_name: The name of the profile to delete.
        :param role_name: The name of the role to delete.
        """
        try:
            self.iam_client.remove_role_from_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            self.iam_client.delete_instance_profile(InstanceProfileName=profile_name)
            log.info("Deleted instance profile %s.", profile_name)
            attached_policies = self.iam_client.list_attached_role_policies(
                RoleName=role_name
            )
            for pol in attached_policies["AttachedPolicies"]:
                self.iam_client.detach_role_policy(
                    RoleName=role_name, PolicyArn=pol["PolicyArn"]
                )
                if not pol["PolicyArn"].startswith("arn:aws:iam::aws"):
                    self.iam_client.delete_policy(PolicyArn=pol["PolicyArn"])
                log.info("Detached and deleted policy %s.", pol["PolicyName"])
            self.iam_client.delete_role(RoleName=role_name)
            log.info("Deleted role %s.", role_name)
        except ClientError as err:
            log.error(
                f"Couldn't delete instance profile {profile_name} or detach "
                f"policies and delete role {role_name}: {err}"
            )
            if err.response["Error"]["Code"] == "NoSuchEntity":
                log.info(
                    "Instance profile %s doesn't exist, nothing to do.", profile_name
                )


    def create_key_pair(self, key_pair_name: str) -> None:
        """
        Creates a new key pair.

        :param key_pair_name: The name of the key pair to create.
        """
        try:
            response = self.ec2_client.create_key_pair(KeyName=key_pair_name)
            with open(f"{key_pair_name}.pem", "w") as file:
                file.write(response["KeyMaterial"])
            chmod(f"{key_pair_name}.pem", 0o600)
            log.info("Created key pair %s.", key_pair_name)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to create key pair {key_pair_name}.")
            if error_code == "InvalidKeyPair.Duplicate":
                log.error(f"A key pair with the name '{key_pair_name}' already exists.")
            log.error(f"Full error:\n\t{err}")


    def delete_key_pair(self) -> None:
        """
        Deletes a key pair.
        """
        try:
            self.ec2_client.delete_key_pair(KeyName=self.key_pair_name)
            remove(f"{self.key_pair_name}.pem")
            log.info("Deleted key pair %s.", self.key_pair_name)
        except ClientError as err:
            log.error(f"Couldn't delete key pair '{self.key_pair_name}'.")
            log.error(f"Full error:\n\t{err}")
        except FileNotFoundError as err:
            log.info("Key pair %s doesn't exist, nothing to do.", self.key_pair_name)
            log.error(f"Full error:\n\t{err}")


    def create_template(
        self, server_startup_script_file: str, instance_policy_file: str
    ) -> Dict[str, Any]:
        """
        Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. The
        launch template specifies a Bash script in its user data field that runs after
        the instance is started. This script installs Python packages and starts a
        Python web server on the instance.

        :param server_startup_script_file: The path to a Bash script file that is run
                                           when an instance starts.
        :param instance_policy_file: The path to a file that defines a permissions policy
                                     to create and attach to the instance profile.
        :return: Information about the newly created template.
        """
        template = {}
        try:
            # Create key pair and instance profile
            self.create_key_pair(self.key_pair_name)
            self.create_instance_profile(
                instance_policy_file,
                self.instance_policy_name,
                self.instance_role_name,
                self.instance_profile_name,
            )

            # Read the startup script
            with open(server_startup_script_file) as file:
                start_server_script = file.read()

            # Get the latest AMI ID
            ami_latest = self.ssm_client.get_parameter(Name=self.ami_param)
            ami_id = ami_latest["Parameter"]["Value"]

            # Create the launch template
            lt_response = self.ec2_client.create_launch_template(
                LaunchTemplateName=self.launch_template_name,
                LaunchTemplateData={
                    "InstanceType": self.inst_type,
                    "ImageId": ami_id,
                    "IamInstanceProfile": {"Name": self.instance_profile_name},
                    "UserData": base64.b64encode(
                        start_server_script.encode(encoding="utf-8")
                    ).decode(encoding="utf-8"),
                    "KeyName": self.key_pair_name,
                },
            )
            template = lt_response["LaunchTemplate"]
            log.info(
                f"Created launch template {self.launch_template_name} for AMI {ami_id} on {self.inst_type}."
            )
        except ClientError as err:
            log.error(f"Failed to create launch template {self.launch_template_name}.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidLaunchTemplateName.AlreadyExistsException":
                log.info(
                    f"Launch template {self.launch_template_name} already exists, nothing to do."
                )
            log.error(f"Full error:\n\t{err}")
        return template


    def delete_template(self):
        """
        Deletes a launch template.
        """
        try:
            self.ec2_client.delete_launch_template(
                LaunchTemplateName=self.launch_template_name
            )
            self.delete_instance_profile(
                self.instance_profile_name, self.instance_role_name
            )
            log.info("Launch template %s deleted.", self.launch_template_name)
        except ClientError as err:
            if (
                err.response["Error"]["Code"]
                == "InvalidLaunchTemplateName.NotFoundException"
            ):
                log.info(
                    "Launch template %s does not exist, nothing to do.",
                    self.launch_template_name,
                )
            log.error(f"Full error:\n\t{err}")


    def get_availability_zones(self) -> List[str]:
        """
        Gets a list of Availability Zones in the AWS Region of the Amazon EC2 client.

        :return: The list of Availability Zones for the client Region.
        """
        try:
            response = self.ec2_client.describe_availability_zones()
            zones = [zone["ZoneName"] for zone in response["AvailabilityZones"]]
            log.info(f"Retrieved {len(zones)} availability zones: {zones}.")
        except ClientError as err:
            log.error("Failed to retrieve availability zones.")
            log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def create_autoscaling_group(self, group_size: int) -> List[str]:
        """
        Creates an EC2 Auto Scaling group with the specified size.

        :param group_size: The number of instances to set for the minimum and maximum in
                           the group.
        :return: The list of Availability Zones specified for the group.
        """
        try:
            zones = self.get_availability_zones()
            self.autoscaling_client.create_auto_scaling_group(
                AutoScalingGroupName=self.group_name,
                AvailabilityZones=zones,
                LaunchTemplate={
                    "LaunchTemplateName": self.launch_template_name,
                    "Version": "$Default",
                },
                MinSize=group_size,
                MaxSize=group_size,
            )
            log.info(
                f"Created EC2 Auto Scaling group {self.group_name} with availability zones {zones}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            if error_code == "AlreadyExists":
                log.info(
                    f"EC2 Auto Scaling group {self.group_name} already exists, nothing to do."
                )
            else:
                log.error(f"Failed to create EC2 Auto Scaling group {self.group_name}.")
                log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def get_instances(self) -> List[str]:
        """
        Gets data about the instances in the EC2 Auto Scaling group.

        :return: A list of instance IDs in the Auto Scaling group.
        """
        try:
            as_response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[self.group_name]
            )
            instance_ids = [
                i["InstanceId"]
                for i in as_response["AutoScalingGroups"][0]["Instances"]
            ]
            log.info(
                f"Retrieved {len(instance_ids)} instances for Auto Scaling group {self.group_name}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to retrieve instances for Auto Scaling group {self.group_name}."
            )
            if error_code == "ResourceNotFound":
                log.error(f"The Auto Scaling group '{self.group_name}' does not exist.")
            log.error(f"Full error:\n\t{err}")
        else:
            return instance_ids


    def terminate_instance(self, instance_id: str, decrementsetting=False) -> None:
        """
        Terminates an instance in an EC2 Auto Scaling group. After an instance is
        terminated, it can no longer be accessed.

        :param instance_id: The ID of the instance to terminate.
        :param decrementsetting: If True, do not replace terminated instances.
        """
        try:
            self.autoscaling_client.terminate_instance_in_auto_scaling_group(
                InstanceId=instance_id,
                ShouldDecrementDesiredCapacity=decrementsetting,
            )
            log.info("Terminated instance %s.", instance_id)

            # Adding a waiter to ensure the instance is terminated
            waiter = self.ec2_client.get_waiter("instance_terminated")
            log.info("Waiting for instance %s to be terminated...", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info(
                f"Instance '{instance_id}' has been terminated and will be replaced."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to terminate instance '{instance_id}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to terminate the instance again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            log.error(f"Full error:\n\t{err}")

    def attach_load_balancer_target_group(
        self, lb_target_group: Dict[str, Any]
    ) -> None:
        """
        Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
        The target group specifies how the load balancer forwards requests to the instances
        in the group.

        :param lb_target_group: Data about the ELB target group to attach.
        """
        try:
            self.autoscaling_client.attach_load_balancer_target_groups(
                AutoScalingGroupName=self.group_name,
                TargetGroupARNs=[lb_target_group["TargetGroupArn"]],
            )
            log.info(
                "Attached load balancer target group %s to auto scaling group %s.",
                lb_target_group["TargetGroupName"],
                self.group_name,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to attach load balancer target group '{lb_target_group['TargetGroupName']}'."
            )
            if error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            elif error_code == "ServiceLinkedRoleFailure":
                log.error(
                    "The operation failed because the service-linked role is not ready or does not exist. "
                    "Check that the service-linked role exists and is correctly configured."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_autoscaling_group(self, group_name: str) -> None:
        """
        Terminates all instances in the group, then deletes the EC2 Auto Scaling group.

        :param group_name: The name of the group to delete.
        """
        try:
            response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[group_name]
            )
            groups = response.get("AutoScalingGroups", [])
            if len(groups) > 0:
                self.autoscaling_client.update_auto_scaling_group(
                    AutoScalingGroupName=group_name, MinSize=0
                )
                instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]]
                for inst_id in instance_ids:
                    self.terminate_instance(inst_id)

                # Wait for all instances to be terminated
                if instance_ids:
                    waiter = self.ec2_client.get_waiter("instance_terminated")
                    log.info("Waiting for all instances to be terminated...")
                    waiter.wait(InstanceIds=instance_ids)
                    log.info("All instances have been terminated.")
            else:
                log.info(f"No groups found named '{group_name}'! Nothing to do.")
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete Auto Scaling group '{group_name}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to delete the group again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_default_vpc(self) -> Dict[str, Any]:
        """
        Gets the default VPC for the account.

        :return: Data about the default VPC.
        """
        try:
            response = self.ec2_client.describe_vpcs(
                Filters=[{"Name": "is-default", "Values": ["true"]}]
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error("Failed to retrieve the default VPC.")
            if error_code == "UnauthorizedOperation":
                log.error(
                    "You do not have the necessary permissions to describe VPCs. "
                    "Ensure that your AWS IAM user or role has the correct permissions."
                )
            elif error_code == "InvalidParameterValue":
                log.error(
                    "One or more parameters are invalid. Check the request parameters."
                )

            log.error(f"Full error:\n\t{err}")
        else:
            if "Vpcs" in response and response["Vpcs"]:
                log.info(f"Retrieved default VPC: {response['Vpcs'][0]['VpcId']}")
                return response["Vpcs"][0]
            else:
                pass


    def verify_inbound_port(
        self, vpc: Dict[str, Any], port: int, ip_address: str
    ) -> Tuple[Dict[str, Any], bool]:
        """
        Verify the default security group of the specified VPC allows ingress from this
        computer. This can be done by allowing ingress from this computer's IP
        address. In some situations, such as connecting from a corporate network, you
        must instead specify a prefix list ID. You can also temporarily open the port to
        any IP address while running this example. If you do, be sure to remove public
        access when you're done.

        :param vpc: The VPC used by this example.
        :param port: The port to verify.
        :param ip_address: This computer's IP address.
        :return: The default security group of the specified VPC, and a value that indicates
                 whether the specified port is open.
        """
        try:
            response = self.ec2_client.describe_security_groups(
                Filters=[
                    {"Name": "group-name", "Values": ["default"]},
                    {"Name": "vpc-id", "Values": [vpc["VpcId"]]},
                ]
            )
            sec_group = response["SecurityGroups"][0]
            port_is_open = False
            log.info(f"Found default security group {sec_group['GroupId']}.")

            for ip_perm in sec_group["IpPermissions"]:
                if ip_perm.get("FromPort", 0) == port:
                    log.info(f"Found inbound rule: {ip_perm}")
                    for ip_range in ip_perm["IpRanges"]:
                        cidr = ip_range.get("CidrIp", "")
                        if cidr.startswith(ip_address) or cidr == "0.0.0.0/0":
                            port_is_open = True
                    if ip_perm["PrefixListIds"]:
                        port_is_open = True
                    if not port_is_open:
                        log.info(
                            f"The inbound rule does not appear to be open to either this computer's IP "
                            f"address of {ip_address}, to all IP addresses (0.0.0.0/0), or to a prefix list ID."
                        )
                    else:
                        break
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to verify inbound rule for port {port} for VPC {vpc['VpcId']}."
            )
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    f"The specified VPC ID '{vpc['VpcId']}' does not exist. Please check the VPC ID."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return sec_group, port_is_open


    def open_inbound_port(self, sec_group_id: str, port: int, ip_address: str) -> None:
        """
        Add an ingress rule to the specified security group that allows access on the
        specified port from the specified IP address.

        :param sec_group_id: The ID of the security group to modify.
        :param port: The port to open.
        :param ip_address: The IP address that is granted access.
        """
        try:
            self.ec2_client.authorize_security_group_ingress(
                GroupId=sec_group_id,
                CidrIp=f"{ip_address}/32",
                FromPort=port,
                ToPort=port,
                IpProtocol="tcp",
            )
            log.info(
                "Authorized ingress to %s on port %s from %s.",
                sec_group_id,
                port,
                ip_address,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to authorize ingress to security group '{sec_group_id}' on port {port} from {ip_address}."
            )
            if error_code == "InvalidGroupId.Malformed":
                log.error(
                    "The security group ID is malformed. "
                    "Please verify that the security group ID is correct."
                )
            elif error_code == "InvalidPermission.Duplicate":
                log.error(
                    "The specified rule already exists in the security group. "
                    "Check the existing rules for this security group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_subnets(self, vpc_id: str, zones: List[str] = None) -> List[Dict[str, Any]]:
        """
        Gets the default subnets in a VPC for a specified list of Availability Zones.

        :param vpc_id: The ID of the VPC to look up.
        :param zones: The list of Availability Zones to look up.
        :return: The list of subnets found.
        """
        # Ensure that 'zones' is a list, even if None is passed
        if zones is None:
            zones = []
        try:
            paginator = self.ec2_client.get_paginator("describe_subnets")
            page_iterator = paginator.paginate(
                Filters=[
                    {"Name": "vpc-id", "Values": [vpc_id]},
                    {"Name": "availability-zone", "Values": zones},
                    {"Name": "default-for-az", "Values": ["true"]},
                ]
            )

            subnets = []
            for page in page_iterator:
                subnets.extend(page["Subnets"])

            log.info("Found %s subnets for the specified zones.", len(subnets))
            return subnets
        except ClientError as err:
            log.error(
                f"Failed to retrieve subnets for VPC '{vpc_id}' in zones {zones}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    "The specified VPC ID does not exist. "
                    "Please check the VPC ID and try again."
                )
            # Add more error-specific handling as needed
            log.error(f"Full error:\n\t{err}")
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def create_target_group(
        self, target_group_name: str, protocol: str, port: int, vpc_id: str
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing target group. The target group specifies how
        the load balancer forwards requests to instances in the group and how instance
        health is checked.

        To speed up this demo, the health check is configured with shortened times and
        lower thresholds. In production, you might want to decrease the sensitivity of
        your health checks to avoid unwanted failures.

        :param target_group_name: The name of the target group to create.
        :param protocol: The protocol to use to forward requests, such as 'HTTP'.
        :param port: The port to use to forward requests, such as 80.
        :param vpc_id: The ID of the VPC in which the load balancer exists.
        :return: Data about the newly created target group.
        """
        try:
            response = self.elb_client.create_target_group(
                Name=target_group_name,
                Protocol=protocol,
                Port=port,
                HealthCheckPath="/healthcheck",
                HealthCheckIntervalSeconds=10,
                HealthCheckTimeoutSeconds=5,
                HealthyThresholdCount=2,
                UnhealthyThresholdCount=2,
                VpcId=vpc_id,
            )
            target_group = response["TargetGroups"][0]
            log.info(f"Created load balancing target group '{target_group_name}'.")
            return target_group
        except ClientError as err:
            log.error(
                f"Couldn't create load balancing target group '{target_group_name}'."
            )
            error_code = err.response["Error"]["Code"]

            if error_code == "DuplicateTargetGroupName":
                log.error(
                    f"Target group name {target_group_name} already exists. "
                    "Check if the target group already exists."
                    "Consider using a different name or deleting the existing target group if appropriate."
                )
            elif error_code == "TooManyTargetGroups":
                log.error(
                    "Too many target groups exist in the account. "
                    "Consider deleting unused target groups to create space for new ones."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_target_group(self, target_group_name) -> None:
        """
        Deletes the target group.
        """
        try:
            # Describe the target group to get its ARN
            response = self.elb_client.describe_target_groups(Names=[target_group_name])
            tg_arn = response["TargetGroups"][0]["TargetGroupArn"]

            # Delete the target group
            self.elb_client.delete_target_group(TargetGroupArn=tg_arn)
            log.info("Deleted load balancing target group %s.", target_group_name)

            # Use a custom waiter to wait until the target group is no longer available
            self.wait_for_target_group_deletion(self.elb_client, tg_arn)
            log.info("Target group %s successfully deleted.", target_group_name)

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete target group '{target_group_name}'.")
            if error_code == "TargetGroupNotFound":
                log.error(
                    "Load balancer target group either already deleted or never existed. "
                    "Verify the name and check that the resource exists in the AWS Console."
                )
            elif error_code == "ResourceInUseException":
                log.error(
                    "Target group still in use by another resource. "
                    "Ensure that the target group is no longer associated with any load balancers or resources.",
                )
            log.error(f"Full error:\n\t{err}")

    def wait_for_target_group_deletion(
        self, elb_client, target_group_arn, max_attempts=10, delay=30
    ):
        for attempt in range(max_attempts):
            try:
                elb_client.describe_target_groups(TargetGroupArns=[target_group_arn])
                print(
                    f"Attempt {attempt + 1}: Target group {target_group_arn} still exists."
                )
            except ClientError as e:
                if e.response["Error"]["Code"] == "TargetGroupNotFound":
                    print(
                        f"Target group {target_group_arn} has been successfully deleted."
                    )
                    return
                else:
                    raise
            time.sleep(delay)
        raise TimeoutError(
            f"Target group {target_group_arn} was not deleted after {max_attempts * delay} seconds."
        )


    def create_load_balancer(
        self,
        load_balancer_name: str,
        subnet_ids: List[str],
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing load balancer that uses the specified subnets
        and forwards requests to the specified target group.

        :param load_balancer_name: The name of the load balancer to create.
        :param subnet_ids: A list of subnets to associate with the load balancer.
        :return: Data about the newly created load balancer.
        """
        try:
            response = self.elb_client.create_load_balancer(
                Name=load_balancer_name, Subnets=subnet_ids
            )
            load_balancer = response["LoadBalancers"][0]
            log.info(f"Created load balancer '{load_balancer_name}'.")

            waiter = self.elb_client.get_waiter("load_balancer_available")
            log.info(
                f"Waiting for load balancer '{load_balancer_name}' to be available..."
            )
            waiter.wait(Names=[load_balancer_name])
            log.info(f"Load balancer '{load_balancer_name}' is now available!")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to create load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "DuplicateLoadBalancerNameException":
                log.error(
                    f"A load balancer with the name '{load_balancer_name}' already exists. "
                    "Load balancer names must be unique within the AWS region. "
                    "Please choose a different name and try again."
                )
            if error_code == "TooManyLoadBalancersException":
                log.error(
                    "The maximum number of load balancers has been reached in this account and region. "
                    "You can delete unused load balancers or request an increase in the service quota from AWS Support."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return load_balancer


    def create_listener(
        self,
        load_balancer_name: str,
        target_group: Dict[str, Any],
    ) -> Dict[str, Any]:
        """
        Creates a listener for the specified load balancer that forwards requests to the
        specified target group.

        :param load_balancer_name: The name of the load balancer to create a listener for.
        :param target_group: An existing target group that is added as a listener to the
                             load balancer.
        :return: Data about the newly created listener.
        """
        try:
            # Retrieve the load balancer ARN
            load_balancer_response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            load_balancer_arn = load_balancer_response["LoadBalancers"][0][
                "LoadBalancerArn"
            ]

            # Create the listener
            response = self.elb_client.create_listener(
                LoadBalancerArn=load_balancer_arn,
                Protocol=target_group["Protocol"],
                Port=target_group["Port"],
                DefaultActions=[
                    {
                        "Type": "forward",
                        "TargetGroupArn": target_group["TargetGroupArn"],
                    }
                ],
            )
            log.info(
                f"Created listener to forward traffic from load balancer '{load_balancer_name}' to target group '{target_group['TargetGroupName']}'."
            )
            return response["Listeners"][0]
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to add a listener on '{load_balancer_name}' for target group '{target_group['TargetGroupName']}'."
            )

            if error_code == "ListenerNotFoundException":
                log.error(
                    f"The listener could not be found for the load balancer '{load_balancer_name}'. "
                    "Please check the load balancer name and target group configuration."
                )
            if error_code == "InvalidConfigurationRequestException":
                log.error(
                    f"The configuration provided for the listener on load balancer '{load_balancer_name}' is invalid. "
                    "Please review the provided protocol, port, and target group settings."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_load_balancer(self, load_balancer_name) -> None:
        """
        Deletes a load balancer.

        :param load_balancer_name: The name of the load balancer to delete.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            lb_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
            self.elb_client.delete_load_balancer(LoadBalancerArn=lb_arn)
            log.info("Deleted load balancer %s.", load_balancer_name)
            waiter = self.elb_client.get_waiter("load_balancers_deleted")
            log.info("Waiting for load balancer to be deleted...")
            waiter.wait(Names=[load_balancer_name])
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Couldn't delete load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    f"The load balancer '{load_balancer_name}' does not exist. "
                    "Please check the name and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def get_endpoint(self, load_balancer_name) -> str:
        """
        Gets the HTTP endpoint of the load balancer.

        :return: The endpoint.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            return response["LoadBalancers"][0]["DNSName"]
        except ClientError as err:
            log.error(
                f"Couldn't get the endpoint for load balancer {load_balancer_name}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Verify load balancer name and ensure it exists in the AWS console."
                )
            log.error(f"Full error:\n\t{err}")

    @staticmethod
    def verify_load_balancer_endpoint(endpoint) -> bool:
        """
        Verify this computer can successfully send a GET request to the load balancer endpoint.

        :param endpoint: The endpoint to verify.
        :return: True if the GET request is successful, False otherwise.
        """
        retries = 3
        verified = False
        while not verified and retries > 0:
            try:
                lb_response = requests.get(f"http://{endpoint}")
                log.info(
                    "Got response %s from load balancer endpoint.",
                    lb_response.status_code,
                )
                if lb_response.status_code == 200:
                    verified = True
                else:
                    retries = 0
            except requests.exceptions.ConnectionError:
                log.info(
                    "Got connection error from load balancer endpoint, retrying..."
                )
                retries -= 1
                time.sleep(10)
        return verified

    def check_target_health(self, target_group_name: str) -> List[Dict[str, Any]]:
        """
        Checks the health of the instances in the target group.

        :return: The health status of the target group.
        """
        try:
            tg_response = self.elb_client.describe_target_groups(
                Names=[target_group_name]
            )
            health_response = self.elb_client.describe_target_health(
                TargetGroupArn=tg_response["TargetGroups"][0]["TargetGroupArn"]
            )
        except ClientError as err:
            log.error(f"Couldn't check health of {target_group_name} target(s).")
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Load balancer associated with the target group was not found. "
                    "Ensure the load balancer exists, is in the correct AWS region, and "
                    "that you have the necessary permissions to access it.",
                )
            elif error_code == "TargetGroupNotFoundException":
                log.error(
                    "Target group was not found. "
                    "Verify the target group name, check that it exists in the correct region, "
                    "and ensure it has not been deleted or created in a different account.",
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return health_response["TargetHealthDescriptions"]
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
class RecommendationService:
    """
    Encapsulates a DynamoDB table to use as a service that recommends books, movies,
    and songs.
    """

    def __init__(self, table_name: str, dynamodb_client: boto3.client):
        """
        Initializes the RecommendationService class with the necessary parameters.

        :param table_name: The name of the DynamoDB recommendations table.
        :param dynamodb_client: A Boto3 DynamoDB client.
        """
        self.table_name = table_name
        self.dynamodb_client = dynamodb_client

    def create(self) -> Dict[str, Any]:
        """
        Creates a DynamoDB table to use as a recommendation service. The table has a
        hash key named 'MediaType' that defines the type of media recommended, such as
        Book or Movie, and a range key named 'ItemId' that, combined with the MediaType,
        forms a unique identifier for the recommended item.

        :return: Data about the newly created table.
        :raises RecommendationServiceError: If the table creation fails.
        """
        try:
            response = self.dynamodb_client.create_table(
                TableName=self.table_name,
                AttributeDefinitions=[
                    {"AttributeName": "MediaType", "AttributeType": "S"},
                    {"AttributeName": "ItemId", "AttributeType": "N"},
                ],
                KeySchema=[
                    {"AttributeName": "MediaType", "KeyType": "HASH"},
                    {"AttributeName": "ItemId", "KeyType": "RANGE"},
                ],
                ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
            )
            log.info("Creating table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s created.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceInUseException":
                log.info("Table %s exists, nothing to be done.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when creating table: {err}."
                )
        else:
            return response

    def populate(self, data_file: str) -> None:
        """
        Populates the recommendations table from a JSON file.

        :param data_file: The path to the data file.
        :raises RecommendationServiceError: If the table population fails.
        """
        try:
            with open(data_file) as data:
                items = json.load(data)
            batch = [{"PutRequest": {"Item": item}} for item in items]
            self.dynamodb_client.batch_write_item(RequestItems={self.table_name: batch})
            log.info(
                "Populated table %s with items from %s.", self.table_name, data_file
            )
        except ClientError as err:
            raise RecommendationServiceError(
                self.table_name, f"Couldn't populate table from {data_file}: {err}"
            )

    def destroy(self) -> None:
        """
        Deletes the recommendations table.

        :raises RecommendationServiceError: If the table deletion fails.
        """
        try:
            self.dynamodb_client.delete_table(TableName=self.table_name)
            log.info("Deleting table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_not_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s deleted.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                log.info("Table %s does not exist, nothing to do.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when deleting table: {err}."
                )
```
Systems Manager のアクションをラップするクラスを作成します。  

```
class ParameterHelper:
    """
    Encapsulates Systems Manager parameters. This example uses these parameters to drive
    the demonstration of resilient architecture, such as failure of a dependency or
    how the service responds to a health check.
    """

    table: str = "doc-example-resilient-architecture-table"
    failure_response: str = "doc-example-resilient-architecture-failure-response"
    health_check: str = "doc-example-resilient-architecture-health-check"

    def __init__(self, table_name: str, ssm_client: boto3.client):
        """
        Initializes the ParameterHelper class with the necessary parameters.

        :param table_name: The name of the DynamoDB table that is used as a recommendation
                           service.
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.table_name = table_name

    def reset(self) -> None:
        """
        Resets the Systems Manager parameters to starting values for the demo.
        These are the name of the DynamoDB recommendation table, no response when a
        dependency fails, and shallow health checks.
        """
        self.put(self.table, self.table_name)
        self.put(self.failure_response, "none")
        self.put(self.health_check, "shallow")

    def put(self, name: str, value: str) -> None:
        """
        Sets the value of a named Systems Manager parameter.

        :param name: The name of the parameter.
        :param value: The new value of the parameter.
        :raises ParameterHelperError: If the parameter value cannot be set.
        """
        try:
            self.ssm_client.put_parameter(
                Name=name, Value=value, Overwrite=True, Type="String"
            )
            log.info("Setting parameter %s to '%s'.", name, value)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to set parameter {name}.")
            if error_code == "ParameterLimitExceeded":
                log.error(
                    "The parameter limit has been exceeded. "
                    "Consider deleting unused parameters or request a limit increase."
                )
            elif error_code == "ParameterAlreadyExists":
                log.error(
                    "The parameter already exists and overwrite is set to False. "
                    "Use Overwrite=True to update the parameter."
                )
            log.error(f"Full error:\n\t{err}")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# SDK for Python (Boto3) を使用する Amazon ECR の例
<a name="python_3_ecr_code_examples"></a>

次のコード例は、Amazon ECR AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon ECR
<a name="ecr_Hello_python_3_topic"></a>

次のコード例は、Amazon ECR の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
import boto3
import argparse
from boto3 import client


def hello_ecr(ecr_client: client, repository_name: str) -> None:
    """
    Use the AWS SDK for Python (Boto3) to create an Amazon Elastic Container Registry (Amazon ECR)
    client and list the images in a repository.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param ecr_client: A Boto3 Amazon ECR Client object. This object wraps
                             the low-level Amazon ECR service API.
    :param repository_name: The name of an Amazon ECR repository in your account.
    """
    print(
        f"Hello, Amazon ECR! Let's list some images in the repository '{repository_name}':\n"
    )
    paginator = ecr_client.get_paginator("list_images")
    page_iterator = paginator.paginate(
        repositoryName=repository_name, PaginationConfig={"MaxItems": 10}
    )

    image_names: [str] = []
    for page in page_iterator:
        for schedule in page["imageIds"]:
            image_names.append(schedule["imageTag"])

    print(f"{len(image_names)} image(s) retrieved.")
    for schedule_name in image_names:
        print(f"\t{schedule_name}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Run hello Amazon ECR.")
    parser.add_argument(
        "--repository-name",
        type=str,
        help="the name of an Amazon ECR repository in your account.",
        required=True,
    )
    args = parser.parse_args()

    hello_ecr(boto3.client("ecr"), args.repository_name)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[listImages](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/listImages)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ecr_Scenario_RepositoryManagement_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon ECR リポジトリを作成します。
+ リポジトリポリシーを設定します。
+ リポジトリ URI を取得します。
+ Amazon ECR 認可トークンを取得します。
+ Amazon ECR リポジトリのライフサイクルポリシーを設定します。
+ Docker イメージを Amazon ECR リポジトリにプッシュします。
+ Amazon ECR リポジトリにイメージが存在しているか確認します。
+ アカウントの Amazon ECR リポジトリをリストし、その詳細を取得します。
+ Amazon ECR リポジトリを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class ECRGettingStarted:
    """
    A scenario that demonstrates how to use Boto3 to perform basic operations using
    Amazon ECR.
    """

    def __init__(
        self,
        ecr_wrapper: ECRWrapper,
        docker_client: docker.DockerClient,
    ):
        self.ecr_wrapper = ecr_wrapper
        self.docker_client = docker_client
        self.tag = "echo-text"
        self.repository_name = "ecr-basics"
        self.docker_image = None
        self.full_tag_name = None
        self.repository = None

    def run(self, role_arn: str) -> None:
        """
        Runs the scenario.
        """
        print(
            """
The Amazon Elastic Container Registry (ECR) is a fully-managed Docker container registry
service provided by AWS. It allows developers and organizations to securely
store, manage, and deploy Docker container images.
ECR provides a simple and scalable way to manage container images throughout their lifecycle,
from building and testing to production deployment.

The `ECRWrapper' class is a wrapper for the Boto3 'ecr' client. The 'ecr' client provides a set of methods to
programmatically interact with the Amazon ECR service. This allows developers to
automate the storage, retrieval, and management of container images as part of their application
deployment pipelines. With ECR, teams can focus on building and deploying their
applications without having to worry about the underlying infrastructure required to
host and manage a container registry.

This scenario walks you through how to perform key operations for this service.
Let's get started...
        """
        )
        press_enter_to_continue()
        print_dashes()
        print(
            f"""
* Create an ECR repository.

An ECR repository is a private Docker container repository provided
by Amazon Web Services (AWS). It is a managed service that makes it easy
to store, manage, and deploy Docker container images.
        """
        )
        print(f"Creating a repository named {self.repository_name}")
        self.repository = self.ecr_wrapper.create_repository(self.repository_name)
        print(f"The ARN of the ECR repository is {self.repository['repositoryArn']}")
        repository_uri = self.repository["repositoryUri"]
        press_enter_to_continue()
        print_dashes()

        print(
            f"""
* Build a Docker image.

Create a local Docker image if it does not already exist.
A Python Docker client is used to execute Docker commands.
You must have Docker installed and running.
            """
        )
        print(f"Building a docker image from 'docker_files/Dockerfile'")
        self.full_tag_name = f"{repository_uri}:{self.tag}"
        self.docker_image = self.docker_client.images.build(
            path="docker_files", tag=self.full_tag_name
        )[0]
        print(f"Docker image {self.full_tag_name} successfully built.")
        press_enter_to_continue()
        print_dashes()

        if role_arn is None:
            print(
                """
* Because an IAM role ARN was not provided, a role policy will not be set for this repository.
            """
            )
        else:
            print(
                """
* Set an ECR repository policy.

Setting an ECR repository policy using the `setRepositoryPolicy` function is crucial for maintaining
the security and integrity of your container images. The repository policy allows you to
define specific rules and restrictions for accessing and managing the images stored within your ECR
repository.
        """
            )

            self.grant_role_download_access(role_arn)
            print(f"Download access granted to the IAM role ARN {role_arn}")
            press_enter_to_continue()
            print_dashes()

            print(
                """
* Display ECR repository policy.

Now we will retrieve the ECR policy to ensure it was successfully set.
            """
            )

            policy_text = self.ecr_wrapper.get_repository_policy(self.repository_name)
            print("Policy Text:")
            print(f"{policy_text}")
            press_enter_to_continue()
            print_dashes()

        print(
            """
* Retrieve an ECR authorization token.

You need an authorization token to securely access and interact with the Amazon ECR registry.
The `get_authorization_token` method of the `ecr` client is responsible for securely accessing
and interacting with an Amazon ECR repository. This operation is responsible for obtaining a
valid authorization token, which is required to authenticate your requests to the ECR service.

Without a valid authorization token, you would not be able to perform any operations on the
ECR repository, such as pushing, pulling, or managing your Docker images.
        """
        )

        authorization_token = self.ecr_wrapper.get_authorization_token()
        print("Authorization token retrieved.")
        press_enter_to_continue()
        print_dashes()
        print(
            """
* Get the ECR Repository URI.

The URI  of an Amazon ECR repository is important. When you want to deploy a container image to
a container orchestration platform like Amazon Elastic Kubernetes Service (EKS)
or Amazon Elastic Container Service (ECS), you need to specify the full image URI,
which includes the ECR repository URI. This allows the container runtime to pull the
correct container image from the ECR repository.
        """
        )
        repository_descriptions = self.ecr_wrapper.describe_repositories(
            [self.repository_name]
        )
        repository_uri = repository_descriptions[0]["repositoryUri"]
        print(f"Repository URI found: {repository_uri}")
        press_enter_to_continue()
        print_dashes()

        print(
            """
* Set an ECR Lifecycle Policy.

An ECR Lifecycle Policy is used to manage the lifecycle of Docker images stored in your ECR repositories.
These policies allow you to automatically remove old or unused Docker images from your repositories,
freeing up storage space and reducing costs.

This example policy helps to maintain the size and efficiency of the container registry
by automatically removing older and potentially unused images, ensuring that the
storage is optimized and the registry remains up-to-date.
            """
        )
        press_enter_to_continue()
        self.put_expiration_policy()
        print(f"An expiration policy was added to the repository.")
        print_dashes()

        print(
            """
* Push a docker image to the Amazon ECR Repository.

The Docker client uses the authorization token is used to authenticate the when pushing the image to the 
ECR repository.
        """
        )
        decoded_authorization = base64.b64decode(authorization_token).decode("utf-8")
        username, password = decoded_authorization.split(":")

        resp = self.docker_client.api.push(
            repository=repository_uri,
            auth_config={"username": username, "password": password},
            tag=self.tag,
            stream=True,
            decode=True,
        )
        for line in resp:
            print(line)

        print_dashes()

        print("* Verify if the image is in the ECR Repository.")
        image_descriptions = self.ecr_wrapper.describe_images(
            self.repository_name, [self.tag]
        )
        if len(image_descriptions) > 0:
            print("Image found in ECR Repository.")
        else:
            print("Image not found in ECR Repository.")
        press_enter_to_continue()
        print_dashes()

        print(
            "* As an optional step, you can interact with the image in Amazon ECR by using the CLI."
        )
        if q.ask(
            "Would you like to view instructions on how to use the CLI to run the image? (y/n)",
            q.is_yesno,
        ):
            print(
                f"""
1. Authenticate with ECR - Before you can pull the image from Amazon ECR, you need to authenticate with the registry. You can do this using the AWS CLI:

    aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin {repository_uri.split("/")[0]}

2. Describe the image using this command:

   aws ecr describe-images --repository-name {self.repository_name} --image-ids imageTag={self.tag}

3. Run the Docker container and view the output using this command:

   docker run --rm {self.full_tag_name}
"""
            )

        self.cleanup(True)

    def cleanup(self, ask: bool):
        """
        Deletes the resources created in this scenario.
        :param ask: If True, prompts the user to confirm before deleting the resources.
        """
        if self.repository is not None and (
            not ask
            or q.ask(
                f"Would you like to delete the ECR repository '{self.repository_name}? (y/n) "
            )
        ):
            print(f"Deleting the ECR repository '{self.repository_name}'.")
            self.ecr_wrapper.delete_repository(self.repository_name)

        if self.full_tag_name is not None and (
            not ask
            or q.ask(
                f"Would you like to delete the local Docker image '{self.full_tag_name}? (y/n) "
            )
        ):
            print(f"Deleting the docker image '{self.full_tag_name}'.")
            self.docker_client.images.remove(self.full_tag_name)

    def grant_role_download_access(self, role_arn: str):
        """
        Grants the specified role access to download images from the ECR repository.

        :param role_arn: The ARN of the role to grant access to.
        """
        policy_json = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Sid": "AllowDownload",
                    "Effect": "Allow",
                    "Principal": {"AWS": role_arn},
                    "Action": ["ecr:BatchGetImage"],
                }
            ],
        }

        self.ecr_wrapper.set_repository_policy(
            self.repository_name, json.dumps(policy_json)
        )


    def put_expiration_policy(self):
        """
        Puts an expiration policy on the ECR repository.
        """
        policy_json = {
            "rules": [
                {
                    "rulePriority": 1,
                    "description": "Expire images older than 14 days",
                    "selection": {
                        "tagStatus": "any",
                        "countType": "sinceImagePushed",
                        "countUnit": "days",
                        "countNumber": 14,
                    },
                    "action": {"type": "expire"},
                }
            ]
        }

        self.ecr_wrapper.put_lifecycle_policy(
            self.repository_name, json.dumps(policy_json)
        )



if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Run Amazon ECR getting started scenario."
    )
    parser.add_argument(
        "--iam-role-arn",
        type=str,
        default=None,
        help="an optional IAM role ARN that will be granted access to download images from a repository.",
        required=False,
    )
    parser.add_argument(
        "--no-art",
        action="store_true",
        help="accessibility setting that suppresses art in the console output.",
    )
    args = parser.parse_args()
    no_art = args.no_art
    iam_role_arn = args.iam_role_arn
    demo = None
    a_docker_client = None
    try:
        a_docker_client = docker.from_env()
        if not a_docker_client.ping():
            raise docker.errors.DockerException("Docker is not running.")
    except docker.errors.DockerException as err:
        logging.error(
            """
        The Python Docker client could not be created. 
        Do you have Docker installed and running?
        Here is the error message:
        %s
        """,
            err,
        )
        sys.exit("Error with Docker.")
    try:
        an_ecr_wrapper = ECRWrapper.from_client()
        demo = ECRGettingStarted(an_ecr_wrapper, a_docker_client)
        demo.run(iam_role_arn)

    except Exception as exception:
        logging.exception("Something went wrong with the demo!")
        if demo is not None:
            demo.cleanup(False)
```
Amazon ECR アクションをラップする ECRWrapper クラス。  

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def create_repository(self, repository_name: str) -> dict[str, any]:
        """
        Creates an ECR repository.

        :param repository_name: The name of the repository to create.
        :return: A dictionary of the created repository.
        """
        try:
            response = self.ecr_client.create_repository(repositoryName=repository_name)
            return response["repository"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "RepositoryAlreadyExistsException":
                print(f"Repository {repository_name} already exists.")
                response = self.ecr_client.describe_repositories(
                    repositoryNames=[repository_name]
                )
                return self.describe_repositories([repository_name])[0]
            else:
                logger.error(
                    "Error creating repository %s. Here's why %s",
                    repository_name,
                    err.response["Error"]["Message"],
                )
                raise


    def delete_repository(self, repository_name: str):
        """
        Deletes an ECR repository.

        :param repository_name: The name of the repository to delete.
        """
        try:
            self.ecr_client.delete_repository(
                repositoryName=repository_name, force=True
            )
            print(f"Deleted repository {repository_name}.")
        except ClientError as err:
            logger.error(
                "Couldn't delete repository %s.. Here's why %s",
                repository_name,
                err.response["Error"]["Message"],
            )
            raise


    def set_repository_policy(self, repository_name: str, policy_text: str):
        """
        Sets the policy for an ECR repository.

        :param repository_name: The name of the repository to set the policy for.
        :param policy_text: The policy text to set.
        """
        try:
            self.ecr_client.set_repository_policy(
                repositoryName=repository_name, policyText=policy_text
            )
            print(f"Set repository policy for repository {repository_name}.")
        except ClientError as err:
            if err.response["Error"]["Code"] == "RepositoryPolicyNotFoundException":
                logger.error("Repository does not exist. %s.", repository_name)
                raise
            else:
                logger.error(
                    "Couldn't set repository policy for repository %s. Here's why %s",
                    repository_name,
                    err.response["Error"]["Message"],
                )
                raise


    def get_repository_policy(self, repository_name: str) -> str:
        """
        Gets the policy for an ECR repository.

        :param repository_name: The name of the repository to get the policy for.
        :return: The policy text.
        """
        try:
            response = self.ecr_client.get_repository_policy(
                repositoryName=repository_name
            )
            return response["policyText"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "RepositoryPolicyNotFoundException":
                logger.error("Repository does not exist. %s.", repository_name)
                raise
            else:
                logger.error(
                    "Couldn't get repository policy for repository %s. Here's why %s",
                    repository_name,
                    err.response["Error"]["Message"],
                )
                raise


    def get_authorization_token(self) -> str:
        """
        Gets an authorization token for an ECR repository.

        :return: The authorization token.
        """
        try:
            response = self.ecr_client.get_authorization_token()
            return response["authorizationData"][0]["authorizationToken"]
        except ClientError as err:
            logger.error(
                "Couldn't get authorization token. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise


    def describe_repositories(self, repository_names: list[str]) -> list[dict]:
        """
        Describes ECR repositories.

        :param repository_names: The names of the repositories to describe.
        :return: The list of repository descriptions.
        """
        try:
            response = self.ecr_client.describe_repositories(
                repositoryNames=repository_names
            )
            return response["repositories"]
        except ClientError as err:
            logger.error(
                "Couldn't describe repositories. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise


    def put_lifecycle_policy(self, repository_name: str, lifecycle_policy_text: str):
        """
        Puts a lifecycle policy for an ECR repository.

        :param repository_name: The name of the repository to put the lifecycle policy for.
        :param lifecycle_policy_text: The lifecycle policy text to put.
        """
        try:
            self.ecr_client.put_lifecycle_policy(
                repositoryName=repository_name,
                lifecyclePolicyText=lifecycle_policy_text,
            )
            print(f"Put lifecycle policy for repository {repository_name}.")
        except ClientError as err:
            logger.error(
                "Couldn't put lifecycle policy for repository %s. Here's why %s",
                repository_name,
                err.response["Error"]["Message"],
            )
            raise


    def describe_images(
        self, repository_name: str, image_ids: list[str] = None
    ) -> list[dict]:
        """
        Describes ECR images.

        :param repository_name: The name of the repository to describe images for.
        :param image_ids: The optional IDs of images to describe.
        :return: The list of image descriptions.
        """
        try:
            params = {
                "repositoryName": repository_name,
            }
            if image_ids is not None:
                params["imageIds"] = [{"imageTag": tag} for tag in image_ids]

            paginator = self.ecr_client.get_paginator("describe_images")
            image_descriptions = []
            for page in paginator.paginate(**params):
                image_descriptions.extend(page["imageDetails"])
            return image_descriptions
        except ClientError as err:
            logger.error(
                "Couldn't describe images. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateRepository](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/CreateRepository)
  + [DeleteRepository](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/DeleteRepository)
  + [DescribeImages](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/DescribeImages)
  + [DescribeRepositories](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/DescribeRepositories)
  + [GetAuthorizationToken](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/GetAuthorizationToken)
  + [GetRepositoryPolicy](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/GetRepositoryPolicy)
  + [SetRepositoryPolicy](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/SetRepositoryPolicy)
  + [StartLifecyclePolicyPreview](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/StartLifecyclePolicyPreview)

## アクション
<a name="actions"></a>

### `CreateRepository`
<a name="ecr_CreateRepository_python_3_topic"></a>

次のコード例は、`CreateRepository` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def create_repository(self, repository_name: str) -> dict[str, any]:
        """
        Creates an ECR repository.

        :param repository_name: The name of the repository to create.
        :return: A dictionary of the created repository.
        """
        try:
            response = self.ecr_client.create_repository(repositoryName=repository_name)
            return response["repository"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "RepositoryAlreadyExistsException":
                print(f"Repository {repository_name} already exists.")
                response = self.ecr_client.describe_repositories(
                    repositoryNames=[repository_name]
                )
                return self.describe_repositories([repository_name])[0]
            else:
                logger.error(
                    "Error creating repository %s. Here's why %s",
                    repository_name,
                    err.response["Error"]["Message"],
                )
                raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateRepository](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/CreateRepository)」を参照してください。**

### `DeleteRepository`
<a name="ecr_DeleteRepository_python_3_topic"></a>

次のコード例は、`DeleteRepository` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def delete_repository(self, repository_name: str):
        """
        Deletes an ECR repository.

        :param repository_name: The name of the repository to delete.
        """
        try:
            self.ecr_client.delete_repository(
                repositoryName=repository_name, force=True
            )
            print(f"Deleted repository {repository_name}.")
        except ClientError as err:
            logger.error(
                "Couldn't delete repository %s.. Here's why %s",
                repository_name,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteRepository](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/DeleteRepository)」を参照してください。**

### `DescribeImages`
<a name="ecr_DescribeImages_python_3_topic"></a>

次のコード例は、`DescribeImages` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def describe_images(
        self, repository_name: str, image_ids: list[str] = None
    ) -> list[dict]:
        """
        Describes ECR images.

        :param repository_name: The name of the repository to describe images for.
        :param image_ids: The optional IDs of images to describe.
        :return: The list of image descriptions.
        """
        try:
            params = {
                "repositoryName": repository_name,
            }
            if image_ids is not None:
                params["imageIds"] = [{"imageTag": tag} for tag in image_ids]

            paginator = self.ecr_client.get_paginator("describe_images")
            image_descriptions = []
            for page in paginator.paginate(**params):
                image_descriptions.extend(page["imageDetails"])
            return image_descriptions
        except ClientError as err:
            logger.error(
                "Couldn't describe images. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeImages](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/DescribeImages)」を参照してください。

### `DescribeRepositories`
<a name="ecr_DescribeRepositories_python_3_topic"></a>

次のコード例は、`DescribeRepositories` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def describe_repositories(self, repository_names: list[str]) -> list[dict]:
        """
        Describes ECR repositories.

        :param repository_names: The names of the repositories to describe.
        :return: The list of repository descriptions.
        """
        try:
            response = self.ecr_client.describe_repositories(
                repositoryNames=repository_names
            )
            return response["repositories"]
        except ClientError as err:
            logger.error(
                "Couldn't describe repositories. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeRepositories](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/DescribeRepositories)」を参照してください。**

### `GetAuthorizationToken`
<a name="ecr_GetAuthorizationToken_python_3_topic"></a>

次のコード例は、`GetAuthorizationToken` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def get_authorization_token(self) -> str:
        """
        Gets an authorization token for an ECR repository.

        :return: The authorization token.
        """
        try:
            response = self.ecr_client.get_authorization_token()
            return response["authorizationData"][0]["authorizationToken"]
        except ClientError as err:
            logger.error(
                "Couldn't get authorization token. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAuthorizationToken](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/GetAuthorizationToken)」を参照してください。**

### `GetRepositoryPolicy`
<a name="ecr_GetRepositoryPolicy_python_3_topic"></a>

次のコード例は、`GetRepositoryPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def get_repository_policy(self, repository_name: str) -> str:
        """
        Gets the policy for an ECR repository.

        :param repository_name: The name of the repository to get the policy for.
        :return: The policy text.
        """
        try:
            response = self.ecr_client.get_repository_policy(
                repositoryName=repository_name
            )
            return response["policyText"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "RepositoryPolicyNotFoundException":
                logger.error("Repository does not exist. %s.", repository_name)
                raise
            else:
                logger.error(
                    "Couldn't get repository policy for repository %s. Here's why %s",
                    repository_name,
                    err.response["Error"]["Message"],
                )
                raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetRepositoryPolicy](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/GetRepositoryPolicy)」を参照してください。**

### `PutLifeCyclePolicy`
<a name="ecr_PutLifeCyclePolicy_python_3_topic"></a>

次のコード例は、`PutLifeCyclePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def put_lifecycle_policy(self, repository_name: str, lifecycle_policy_text: str):
        """
        Puts a lifecycle policy for an ECR repository.

        :param repository_name: The name of the repository to put the lifecycle policy for.
        :param lifecycle_policy_text: The lifecycle policy text to put.
        """
        try:
            self.ecr_client.put_lifecycle_policy(
                repositoryName=repository_name,
                lifecyclePolicyText=lifecycle_policy_text,
            )
            print(f"Put lifecycle policy for repository {repository_name}.")
        except ClientError as err:
            logger.error(
                "Couldn't put lifecycle policy for repository %s. Here's why %s",
                repository_name,
                err.response["Error"]["Message"],
            )
            raise
```
有効期限ポリシーを設定する例。  

```
    def put_expiration_policy(self):
        """
        Puts an expiration policy on the ECR repository.
        """
        policy_json = {
            "rules": [
                {
                    "rulePriority": 1,
                    "description": "Expire images older than 14 days",
                    "selection": {
                        "tagStatus": "any",
                        "countType": "sinceImagePushed",
                        "countUnit": "days",
                        "countNumber": 14,
                    },
                    "action": {"type": "expire"},
                }
            ]
        }

        self.ecr_wrapper.put_lifecycle_policy(
            self.repository_name, json.dumps(policy_json)
        )
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[PutLifeCyclePolicy](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/PutLifeCyclePolicy)」を参照してください。**

### `SetRepositoryPolicy`
<a name="ecr_SetRepositoryPolicy_python_3_topic"></a>

次のコード例は、`SetRepositoryPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ecr#code-examples)での設定と実行の方法を確認してください。

```
class ECRWrapper:
    def __init__(self, ecr_client: client):
        self.ecr_client = ecr_client

    @classmethod
    def from_client(cls) -> "ECRWrapper":
        """
        Creates a ECRWrapper instance with a default Amazon ECR client.

        :return: An instance of ECRWrapper initialized with the default Amazon ECR client.
        """
        ecr_client = boto3.client("ecr")
        return cls(ecr_client)


    def set_repository_policy(self, repository_name: str, policy_text: str):
        """
        Sets the policy for an ECR repository.

        :param repository_name: The name of the repository to set the policy for.
        :param policy_text: The policy text to set.
        """
        try:
            self.ecr_client.set_repository_policy(
                repositoryName=repository_name, policyText=policy_text
            )
            print(f"Set repository policy for repository {repository_name}.")
        except ClientError as err:
            if err.response["Error"]["Code"] == "RepositoryPolicyNotFoundException":
                logger.error("Repository does not exist. %s.", repository_name)
                raise
            else:
                logger.error(
                    "Couldn't set repository policy for repository %s. Here's why %s",
                    repository_name,
                    err.response["Error"]["Message"],
                )
                raise
```
IAM ロールにダウンロードアクセス権を付与する例。  

```
    def grant_role_download_access(self, role_arn: str):
        """
        Grants the specified role access to download images from the ECR repository.

        :param role_arn: The ARN of the role to grant access to.
        """
        policy_json = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Sid": "AllowDownload",
                    "Effect": "Allow",
                    "Principal": {"AWS": role_arn},
                    "Action": ["ecr:BatchGetImage"],
                }
            ],
        }

        self.ecr_wrapper.set_repository_policy(
            self.repository_name, json.dumps(policy_json)
        )
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SetRepositoryPolicy](https://docs.aws.amazon.com/goto/boto3/ecr-2015-09-21/SetRepositoryPolicy)」を参照してください。**

# SDK for Python (Boto3) を使用する Elastic Load Balancing - バージョン 2 の例
<a name="python_3_elastic-load-balancing-v2_code_examples"></a>

次のコード例は、Elastic Load Balancing - バージョン 2 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Elastic Load Balancing
<a name="elastic-load-balancing-v2_Hello_python_3_topic"></a>

次のコード例は、Elastic Load Balancing の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_elbv2(elbv2_client):
    """
    Use the AWS SDK for Python (Boto3) to create an Elastic Load Balancing V2 client and list
    up to ten of the load balancers for your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param elbv2_client: A Boto3 Elastic Load Balancing V2 client object.
    """
    print("Hello, Elastic Load Balancing! Let's list some of your load balancers:")
    load_balancers = elbv2_client.describe_load_balancers(PageSize=10).get(
        "LoadBalancers", []
    )
    if load_balancers:
        for lb in load_balancers:
            print(f"\t{lb['LoadBalancerName']}: {lb['DNSName']}")
    else:
        print("Your account doesn't have any load balancers.")


if __name__ == "__main__":
    hello_elbv2(boto3.client("elbv2"))
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeLoadBalancers](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateListener`
<a name="elastic-load-balancing-v2_CreateListener_python_3_topic"></a>

次のコード例は、`CreateListener` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def create_listener(
        self,
        load_balancer_name: str,
        target_group: Dict[str, Any],
    ) -> Dict[str, Any]:
        """
        Creates a listener for the specified load balancer that forwards requests to the
        specified target group.

        :param load_balancer_name: The name of the load balancer to create a listener for.
        :param target_group: An existing target group that is added as a listener to the
                             load balancer.
        :return: Data about the newly created listener.
        """
        try:
            # Retrieve the load balancer ARN
            load_balancer_response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            load_balancer_arn = load_balancer_response["LoadBalancers"][0][
                "LoadBalancerArn"
            ]

            # Create the listener
            response = self.elb_client.create_listener(
                LoadBalancerArn=load_balancer_arn,
                Protocol=target_group["Protocol"],
                Port=target_group["Port"],
                DefaultActions=[
                    {
                        "Type": "forward",
                        "TargetGroupArn": target_group["TargetGroupArn"],
                    }
                ],
            )
            log.info(
                f"Created listener to forward traffic from load balancer '{load_balancer_name}' to target group '{target_group['TargetGroupName']}'."
            )
            return response["Listeners"][0]
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to add a listener on '{load_balancer_name}' for target group '{target_group['TargetGroupName']}'."
            )

            if error_code == "ListenerNotFoundException":
                log.error(
                    f"The listener could not be found for the load balancer '{load_balancer_name}'. "
                    "Please check the load balancer name and target group configuration."
                )
            if error_code == "InvalidConfigurationRequestException":
                log.error(
                    f"The configuration provided for the listener on load balancer '{load_balancer_name}' is invalid. "
                    "Please review the provided protocol, port, and target group settings."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateListener](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateListener)」を参照してください。

### `CreateLoadBalancer`
<a name="elastic-load-balancing-v2_CreateLoadBalancer_python_3_topic"></a>

次のコード例は、`CreateLoadBalancer` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def create_load_balancer(
        self,
        load_balancer_name: str,
        subnet_ids: List[str],
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing load balancer that uses the specified subnets
        and forwards requests to the specified target group.

        :param load_balancer_name: The name of the load balancer to create.
        :param subnet_ids: A list of subnets to associate with the load balancer.
        :return: Data about the newly created load balancer.
        """
        try:
            response = self.elb_client.create_load_balancer(
                Name=load_balancer_name, Subnets=subnet_ids
            )
            load_balancer = response["LoadBalancers"][0]
            log.info(f"Created load balancer '{load_balancer_name}'.")

            waiter = self.elb_client.get_waiter("load_balancer_available")
            log.info(
                f"Waiting for load balancer '{load_balancer_name}' to be available..."
            )
            waiter.wait(Names=[load_balancer_name])
            log.info(f"Load balancer '{load_balancer_name}' is now available!")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to create load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "DuplicateLoadBalancerNameException":
                log.error(
                    f"A load balancer with the name '{load_balancer_name}' already exists. "
                    "Load balancer names must be unique within the AWS region. "
                    "Please choose a different name and try again."
                )
            if error_code == "TooManyLoadBalancersException":
                log.error(
                    "The maximum number of load balancers has been reached in this account and region. "
                    "You can delete unused load balancers or request an increase in the service quota from AWS Support."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return load_balancer
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)」を参照してください。

### `CreateTargetGroup`
<a name="elastic-load-balancing-v2_CreateTargetGroup_python_3_topic"></a>

次のコード例は、`CreateTargetGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def create_target_group(
        self, target_group_name: str, protocol: str, port: int, vpc_id: str
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing target group. The target group specifies how
        the load balancer forwards requests to instances in the group and how instance
        health is checked.

        To speed up this demo, the health check is configured with shortened times and
        lower thresholds. In production, you might want to decrease the sensitivity of
        your health checks to avoid unwanted failures.

        :param target_group_name: The name of the target group to create.
        :param protocol: The protocol to use to forward requests, such as 'HTTP'.
        :param port: The port to use to forward requests, such as 80.
        :param vpc_id: The ID of the VPC in which the load balancer exists.
        :return: Data about the newly created target group.
        """
        try:
            response = self.elb_client.create_target_group(
                Name=target_group_name,
                Protocol=protocol,
                Port=port,
                HealthCheckPath="/healthcheck",
                HealthCheckIntervalSeconds=10,
                HealthCheckTimeoutSeconds=5,
                HealthyThresholdCount=2,
                UnhealthyThresholdCount=2,
                VpcId=vpc_id,
            )
            target_group = response["TargetGroups"][0]
            log.info(f"Created load balancing target group '{target_group_name}'.")
            return target_group
        except ClientError as err:
            log.error(
                f"Couldn't create load balancing target group '{target_group_name}'."
            )
            error_code = err.response["Error"]["Code"]

            if error_code == "DuplicateTargetGroupName":
                log.error(
                    f"Target group name {target_group_name} already exists. "
                    "Check if the target group already exists."
                    "Consider using a different name or deleting the existing target group if appropriate."
                )
            elif error_code == "TooManyTargetGroups":
                log.error(
                    "Too many target groups exist in the account. "
                    "Consider deleting unused target groups to create space for new ones."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)」を参照してください。

### `DeleteLoadBalancer`
<a name="elastic-load-balancing-v2_DeleteLoadBalancer_python_3_topic"></a>

次のコード例は、`DeleteLoadBalancer` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def delete_load_balancer(self, load_balancer_name) -> None:
        """
        Deletes a load balancer.

        :param load_balancer_name: The name of the load balancer to delete.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            lb_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
            self.elb_client.delete_load_balancer(LoadBalancerArn=lb_arn)
            log.info("Deleted load balancer %s.", load_balancer_name)
            waiter = self.elb_client.get_waiter("load_balancers_deleted")
            log.info("Waiting for load balancer to be deleted...")
            waiter.wait(Names=[load_balancer_name])
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Couldn't delete load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    f"The load balancer '{load_balancer_name}' does not exist. "
                    "Please check the name and try again."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)」を参照してください。

### `DeleteTargetGroup`
<a name="elastic-load-balancing-v2_DeleteTargetGroup_python_3_topic"></a>

次のコード例は、`DeleteTargetGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def delete_target_group(self, target_group_name) -> None:
        """
        Deletes the target group.
        """
        try:
            # Describe the target group to get its ARN
            response = self.elb_client.describe_target_groups(Names=[target_group_name])
            tg_arn = response["TargetGroups"][0]["TargetGroupArn"]

            # Delete the target group
            self.elb_client.delete_target_group(TargetGroupArn=tg_arn)
            log.info("Deleted load balancing target group %s.", target_group_name)

            # Use a custom waiter to wait until the target group is no longer available
            self.wait_for_target_group_deletion(self.elb_client, tg_arn)
            log.info("Target group %s successfully deleted.", target_group_name)

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete target group '{target_group_name}'.")
            if error_code == "TargetGroupNotFound":
                log.error(
                    "Load balancer target group either already deleted or never existed. "
                    "Verify the name and check that the resource exists in the AWS Console."
                )
            elif error_code == "ResourceInUseException":
                log.error(
                    "Target group still in use by another resource. "
                    "Ensure that the target group is no longer associated with any load balancers or resources.",
                )
            log.error(f"Full error:\n\t{err}")

    def wait_for_target_group_deletion(
        self, elb_client, target_group_arn, max_attempts=10, delay=30
    ):
        for attempt in range(max_attempts):
            try:
                elb_client.describe_target_groups(TargetGroupArns=[target_group_arn])
                print(
                    f"Attempt {attempt + 1}: Target group {target_group_arn} still exists."
                )
            except ClientError as e:
                if e.response["Error"]["Code"] == "TargetGroupNotFound":
                    print(
                        f"Target group {target_group_arn} has been successfully deleted."
                    )
                    return
                else:
                    raise
            time.sleep(delay)
        raise TimeoutError(
            f"Target group {target_group_arn} was not deleted after {max_attempts * delay} seconds."
        )
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)」を参照してください。

### `DescribeLoadBalancers`
<a name="elastic-load-balancing-v2_DescribeLoadBalancers_python_3_topic"></a>

次のコード例は、`DescribeLoadBalancers` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def get_endpoint(self, load_balancer_name) -> str:
        """
        Gets the HTTP endpoint of the load balancer.

        :return: The endpoint.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            return response["LoadBalancers"][0]["DNSName"]
        except ClientError as err:
            log.error(
                f"Couldn't get the endpoint for load balancer {load_balancer_name}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Verify load balancer name and ensure it exists in the AWS console."
                )
            log.error(f"Full error:\n\t{err}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeLoadBalancers](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)」を参照してください。

### `DescribeTargetHealth`
<a name="elastic-load-balancing-v2_DescribeTargetHealth_python_3_topic"></a>

次のコード例は、`DescribeTargetHealth` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/elastic-load-balancing#code-examples)での設定と実行の方法を確認してください。

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def check_target_health(self, target_group_name: str) -> List[Dict[str, Any]]:
        """
        Checks the health of the instances in the target group.

        :return: The health status of the target group.
        """
        try:
            tg_response = self.elb_client.describe_target_groups(
                Names=[target_group_name]
            )
            health_response = self.elb_client.describe_target_health(
                TargetGroupArn=tg_response["TargetGroups"][0]["TargetGroupArn"]
            )
        except ClientError as err:
            log.error(f"Couldn't check health of {target_group_name} target(s).")
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Load balancer associated with the target group was not found. "
                    "Ensure the load balancer exists, is in the correct AWS region, and "
                    "that you have the necessary permissions to access it.",
                )
            elif error_code == "TargetGroupNotFoundException":
                log.error(
                    "Target group was not found. "
                    "Verify the target group name, check that it exists in the correct region, "
                    "and ensure it has not been deleted or created in a different account.",
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return health_response["TargetHealthDescriptions"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeTargetHealth](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_python_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class Runner:
    """
    Manages the deployment, demonstration, and destruction of resources for the resilient service.
    """

    def __init__(
        self,
        resource_path: str,
        recommendation: RecommendationService,
        autoscaler: AutoScalingWrapper,
        loadbalancer: ElasticLoadBalancerWrapper,
        param_helper: ParameterHelper,
    ):
        """
        Initializes the Runner class with the necessary parameters.

        :param resource_path: The path to resource files used by this example, such as IAM policies and instance scripts.
        :param recommendation: An instance of the RecommendationService class.
        :param autoscaler: An instance of the AutoScaler class.
        :param loadbalancer: An instance of the LoadBalancer class.
        :param param_helper: An instance of the ParameterHelper class.
        """
        self.resource_path = resource_path
        self.recommendation = recommendation
        self.autoscaler = autoscaler
        self.loadbalancer = loadbalancer
        self.param_helper = param_helper
        self.protocol = "HTTP"
        self.port = 80
        self.ssh_port = 22

        prefix = "doc-example-resilience"
        self.target_group_name = f"{prefix}-tg"
        self.load_balancer_name = f"{prefix}-lb"

    def deploy(self) -> None:
        """
        Deploys the resources required for the resilient service, including the DynamoDB table,
        EC2 instances, Auto Scaling group, and load balancer.
        """
        recommendations_path = f"{self.resource_path}/recommendations.json"
        startup_script = f"{self.resource_path}/server_startup_script.sh"
        instance_policy = f"{self.resource_path}/instance_policy.json"

        logging.info("Starting deployment of resources for the resilient service.")

        logging.info(
            "Creating and populating DynamoDB table '%s'.",
            self.recommendation.table_name,
        )
        self.recommendation.create()
        self.recommendation.populate(recommendations_path)

        logging.info(
            "Creating an EC2 launch template with the startup script '%s'.",
            startup_script,
        )
        self.autoscaler.create_template(startup_script, instance_policy)

        logging.info(
            "Creating an EC2 Auto Scaling group across multiple Availability Zones."
        )
        zones = self.autoscaler.create_autoscaling_group(3)

        logging.info("Creating variables that control the flow of the demo.")
        self.param_helper.reset()

        logging.info("Creating Elastic Load Balancing target group and load balancer.")

        vpc = self.autoscaler.get_default_vpc()
        subnets = self.autoscaler.get_subnets(vpc["VpcId"], zones)
        target_group = self.loadbalancer.create_target_group(
            self.target_group_name, self.protocol, self.port, vpc["VpcId"]
        )
        self.loadbalancer.create_load_balancer(
            self.load_balancer_name, [subnet["SubnetId"] for subnet in subnets]
        )
        self.loadbalancer.create_listener(self.load_balancer_name, target_group)

        self.autoscaler.attach_load_balancer_target_group(target_group)

        logging.info("Verifying access to the load balancer endpoint.")
        endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
        lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)
        current_ip_address = requests.get("http://checkip.amazonaws.com").text.strip()

        if not lb_success:
            logging.warning(
                "Couldn't connect to the load balancer. Verifying that the port is open..."
            )
            sec_group, port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.port, current_ip_address
            )
            sec_group, ssh_port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.ssh_port, current_ip_address
            )
            if not port_is_open:
                logging.warning(
                    "The default security group for your VPC must allow access from this computer."
                )
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound traffic on port {self.port} from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.port, current_ip_address
                    )
            if not ssh_port_is_open:
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound SSH traffic on port {self.ssh_port} for debugging from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.ssh_port, current_ip_address
                    )
            lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)

        if lb_success:
            logging.info(
                "Load balancer is ready. Access it at: http://%s", current_ip_address
            )
        else:
            logging.error(
                "Couldn't get a successful response from the load balancer endpoint. Please verify your VPC and security group settings."
            )

    def demo_choices(self) -> None:
        """
        Presents choices for interacting with the deployed service, such as sending requests to
        the load balancer or checking the health of the targets.
        """
        actions = [
            "Send a GET request to the load balancer endpoint.",
            "Check the health of load balancer targets.",
            "Go to the next part of the demo.",
        ]
        choice = 0
        while choice != 2:
            logging.info("Choose an action to interact with the service.")
            choice = q.choose("Which action would you like to take? ", actions)
            if choice == 0:
                logging.info("Sending a GET request to the load balancer endpoint.")
                endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
                logging.info("GET http://%s", endpoint)
                response = requests.get(f"http://{endpoint}")
                logging.info("Response: %s", response.status_code)
                if response.headers.get("content-type") == "application/json":
                    pp(response.json())
            elif choice == 1:
                logging.info("Checking the health of load balancer targets.")
                health = self.loadbalancer.check_target_health(self.target_group_name)
                for target in health:
                    state = target["TargetHealth"]["State"]
                    logging.info(
                        "Target %s on port %d is %s",
                        target["Target"]["Id"],
                        target["Target"]["Port"],
                        state,
                    )
                    if state != "healthy":
                        logging.warning(
                            "%s: %s",
                            target["TargetHealth"]["Reason"],
                            target["TargetHealth"]["Description"],
                        )
                logging.info(
                    "Note that it can take a minute or two for the health check to update."
                )
            elif choice == 2:
                logging.info("Proceeding to the next part of the demo.")

    def demo(self) -> None:
        """
        Runs the demonstration, showing how the service responds to different failure scenarios
        and how a resilient architecture can keep the service running.
        """
        ssm_only_policy = f"{self.resource_path}/ssm_only_policy.json"

        logging.info("Resetting parameters to starting values for the demo.")
        self.param_helper.reset()

        logging.info(
            "Starting demonstration of the service's resilience under various failure conditions."
        )
        self.demo_choices()

        logging.info(
            "Simulating failure by changing the Systems Manager parameter to a non-existent table."
        )
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info("Sending GET requests will now return failure codes.")
        self.demo_choices()

        logging.info("Switching to static response mode to mitigate failure.")
        self.param_helper.put(self.param_helper.failure_response, "static")
        logging.info("Sending GET requests will now return static responses.")
        self.demo_choices()

        logging.info("Restoring normal operation of the recommendation service.")
        self.param_helper.put(self.param_helper.table, self.recommendation.table_name)

        logging.info(
            "Introducing a failure by assigning bad credentials to one of the instances."
        )
        self.autoscaler.create_instance_profile(
            ssm_only_policy,
            self.autoscaler.bad_creds_policy_name,
            self.autoscaler.bad_creds_role_name,
            self.autoscaler.bad_creds_profile_name,
            ["AmazonSSMManagedInstanceCore"],
        )
        instances = self.autoscaler.get_instances()
        bad_instance_id = instances[0]
        instance_profile = self.autoscaler.get_instance_profile(bad_instance_id)
        logging.info(
            "Replacing instance profile with bad credentials for instance %s.",
            bad_instance_id,
        )
        self.autoscaler.replace_instance_profile(
            bad_instance_id,
            self.autoscaler.bad_creds_profile_name,
            instance_profile["AssociationId"],
        )
        logging.info(
            "Sending GET requests may return either a valid recommendation or a static response."
        )
        self.demo_choices()

        logging.info("Implementing deep health checks to detect unhealthy instances.")
        self.param_helper.put(self.param_helper.health_check, "deep")
        logging.info("Checking the health of the load balancer targets.")
        self.demo_choices()

        logging.info(
            "Terminating the unhealthy instance to let the auto scaler replace it."
        )
        self.autoscaler.terminate_instance(bad_instance_id)
        logging.info("The service remains resilient during instance replacement.")
        self.demo_choices()

        logging.info("Simulating a complete failure of the recommendation service.")
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info(
            "All instances will report as unhealthy, but the service will still return static responses."
        )
        self.demo_choices()
        self.param_helper.reset()

    def destroy(self, automation=False) -> None:
        """
        Destroys all resources created for the demo, including the load balancer, Auto Scaling group,
        EC2 instances, and DynamoDB table.
        """
        logging.info(
            "This concludes the demo. Preparing to clean up all AWS resources created during the demo."
        )
        if automation:
            cleanup = True
        else:
            cleanup = q.ask(
                "Do you want to clean up all demo resources? (y/n) ", q.is_yesno
            )

        if cleanup:
            logging.info("Deleting load balancer and related resources.")
            self.loadbalancer.delete_load_balancer(self.load_balancer_name)
            self.loadbalancer.delete_target_group(self.target_group_name)
            self.autoscaler.delete_autoscaling_group(self.autoscaler.group_name)
            self.autoscaler.delete_key_pair()
            self.autoscaler.delete_template()
            self.autoscaler.delete_instance_profile(
                self.autoscaler.bad_creds_profile_name,
                self.autoscaler.bad_creds_role_name,
            )
            logging.info("Deleting DynamoDB table and other resources.")
            self.recommendation.destroy()
        else:
            logging.warning(
                "Resources have not been deleted. Ensure you clean them up manually to avoid unexpected charges."
            )


def main() -> None:
    """
    Main function to parse arguments and run the appropriate actions for the demo.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--action",
        required=True,
        choices=["all", "deploy", "demo", "destroy"],
        help="The action to take for the demo. When 'all' is specified, resources are\n"
        "deployed, the demo is run, and resources are destroyed.",
    )
    parser.add_argument(
        "--resource_path",
        default="../../../scenarios/features/resilient_service/resources",
        help="The path to resource files used by this example, such as IAM policies and\n"
        "instance scripts.",
    )
    args = parser.parse_args()

    logging.info("Starting the Resilient Service demo.")

    prefix = "doc-example-resilience"

    # Service Clients
    ddb_client = boto3.client("dynamodb")
    elb_client = boto3.client("elbv2")
    autoscaling_client = boto3.client("autoscaling")
    ec2_client = boto3.client("ec2")
    ssm_client = boto3.client("ssm")
    iam_client = boto3.client("iam")

    # Wrapper instantiations
    recommendation = RecommendationService(
        "doc-example-recommendation-service", ddb_client
    )
    autoscaling_wrapper = AutoScalingWrapper(
        prefix,
        "t3.micro",
        "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
        autoscaling_client,
        ec2_client,
        ssm_client,
        iam_client,
    )
    elb_wrapper = ElasticLoadBalancerWrapper(elb_client)
    param_helper = ParameterHelper(recommendation.table_name, ssm_client)

    # Demo invocation
    runner = Runner(
        args.resource_path,
        recommendation,
        autoscaling_wrapper,
        elb_wrapper,
        param_helper,
    )
    actions = [args.action] if args.action != "all" else ["deploy", "demo", "destroy"]
    for action in actions:
        if action == "deploy":
            runner.deploy()
        elif action == "demo":
            runner.demo()
        elif action == "destroy":
            runner.destroy()

    logging.info("Demo completed successfully.")


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    main()
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_policy(self, policy_file: str, policy_name: str) -> str:
        """
        Creates a new IAM policy or retrieves the ARN of an existing policy.

        :param policy_file: The path to a JSON file that contains the policy definition.
        :param policy_name: The name to give the created policy.
        :return: The ARN of the created or existing policy.
        """
        with open(policy_file) as file:
            policy_doc = file.read()

        try:
            response = self.iam_client.create_policy(
                PolicyName=policy_name, PolicyDocument=policy_doc
            )
            policy_arn = response["Policy"]["Arn"]
            log.info(f"Policy '{policy_name}' created successfully. ARN: {policy_arn}")
            return policy_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the policy already exists, get its ARN
                response = self.iam_client.get_policy(
                    PolicyArn=f"arn:aws:iam::{self.account_id}:policy/{policy_name}"
                )
                policy_arn = response["Policy"]["Arn"]
                log.info(f"Policy '{policy_name}' already exists. ARN: {policy_arn}")
                return policy_arn
            log.error(f"Full error:\n\t{err}")

    def create_role(self, role_name: str, assume_role_doc: dict) -> str:
        """
        Creates a new IAM role or retrieves the ARN of an existing role.

        :param role_name: The name to give the created role.
        :param assume_role_doc: The assume role policy document that specifies which
                                entities can assume the role.
        :return: The ARN of the created or existing role.
        """
        try:
            response = self.iam_client.create_role(
                RoleName=role_name, AssumeRolePolicyDocument=json.dumps(assume_role_doc)
            )
            role_arn = response["Role"]["Arn"]
            log.info(f"Role '{role_name}' created successfully. ARN: {role_arn}")
            return role_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the role already exists, get its ARN
                response = self.iam_client.get_role(RoleName=role_name)
                role_arn = response["Role"]["Arn"]
                log.info(f"Role '{role_name}' already exists. ARN: {role_arn}")
                return role_arn
            log.error(f"Full error:\n\t{err}")

    def attach_policy(
        self,
        role_name: str,
        policy_arn: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> None:
        """
        Attaches an IAM policy to a role and optionally attaches additional AWS-managed policies.

        :param role_name: The name of the role to attach the policy to.
        :param policy_arn: The ARN of the policy to attach.
        :param aws_managed_policies: A tuple of AWS-managed policy names to attach to the role.
        """
        try:
            self.iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn)
            for aws_policy in aws_managed_policies:
                self.iam_client.attach_role_policy(
                    RoleName=role_name,
                    PolicyArn=f"arn:aws:iam::aws:policy/{aws_policy}",
                )
            log.info(f"Attached policy {policy_arn} to role {role_name}.")
        except ClientError as err:
            log.error(f"Failed to attach policy {policy_arn} to role {role_name}.")
            log.error(f"Full error:\n\t{err}")

    def create_instance_profile(
        self,
        policy_file: str,
        policy_name: str,
        role_name: str,
        profile_name: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> str:
        """
        Creates a policy, role, and profile that is associated with instances created by
        this class. An instance's associated profile defines a role that is assumed by the
        instance. The role has attached policies that specify the AWS permissions granted to
        clients that run on the instance.

        :param policy_file: The name of a JSON file that contains the policy definition to
                            create and attach to the role.
        :param policy_name: The name to give the created policy.
        :param role_name: The name to give the created role.
        :param profile_name: The name to the created profile.
        :param aws_managed_policies: Additional AWS-managed policies that are attached to
                                     the role, such as AmazonSSMManagedInstanceCore to grant
                                     use of Systems Manager to send commands to the instance.
        :return: The ARN of the profile that is created.
        """
        assume_role_doc = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"Service": "ec2.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        policy_arn = self.create_policy(policy_file, policy_name)
        self.create_role(role_name, assume_role_doc)
        self.attach_policy(role_name, policy_arn, aws_managed_policies)

        try:
            profile_response = self.iam_client.create_instance_profile(
                InstanceProfileName=profile_name
            )
            waiter = self.iam_client.get_waiter("instance_profile_exists")
            waiter.wait(InstanceProfileName=profile_name)
            time.sleep(10)  # wait a little longer
            profile_arn = profile_response["InstanceProfile"]["Arn"]
            self.iam_client.add_role_to_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            log.info("Created profile %s and added role %s.", profile_name, role_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                prof_response = self.iam_client.get_instance_profile(
                    InstanceProfileName=profile_name
                )
                profile_arn = prof_response["InstanceProfile"]["Arn"]
                log.info(
                    "Instance profile %s already exists, nothing to do.", profile_name
                )
            log.error(f"Full error:\n\t{err}")
        return profile_arn


    def get_instance_profile(self, instance_id: str) -> Dict[str, Any]:
        """
        Gets data about the profile associated with an instance.

        :param instance_id: The ID of the instance to look up.
        :return: The profile data.
        """
        try:
            response = self.ec2_client.describe_iam_instance_profile_associations(
                Filters=[{"Name": "instance-id", "Values": [instance_id]}]
            )
            if not response["IamInstanceProfileAssociations"]:
                log.info(f"No instance profile found for instance {instance_id}.")
            profile_data = response["IamInstanceProfileAssociations"][0]
            log.info(f"Retrieved instance profile for instance {instance_id}.")
            return profile_data
        except ClientError as err:
            log.error(
                f"Failed to retrieve instance profile for instance {instance_id}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                log.error(f"The instance ID '{instance_id}' does not exist.")
            log.error(f"Full error:\n\t{err}")


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_instance_profile(self, profile_name: str, role_name: str) -> None:
        """
        Detaches a role from an instance profile, detaches policies from the role,
        and deletes all the resources.

        :param profile_name: The name of the profile to delete.
        :param role_name: The name of the role to delete.
        """
        try:
            self.iam_client.remove_role_from_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            self.iam_client.delete_instance_profile(InstanceProfileName=profile_name)
            log.info("Deleted instance profile %s.", profile_name)
            attached_policies = self.iam_client.list_attached_role_policies(
                RoleName=role_name
            )
            for pol in attached_policies["AttachedPolicies"]:
                self.iam_client.detach_role_policy(
                    RoleName=role_name, PolicyArn=pol["PolicyArn"]
                )
                if not pol["PolicyArn"].startswith("arn:aws:iam::aws"):
                    self.iam_client.delete_policy(PolicyArn=pol["PolicyArn"])
                log.info("Detached and deleted policy %s.", pol["PolicyName"])
            self.iam_client.delete_role(RoleName=role_name)
            log.info("Deleted role %s.", role_name)
        except ClientError as err:
            log.error(
                f"Couldn't delete instance profile {profile_name} or detach "
                f"policies and delete role {role_name}: {err}"
            )
            if err.response["Error"]["Code"] == "NoSuchEntity":
                log.info(
                    "Instance profile %s doesn't exist, nothing to do.", profile_name
                )


    def create_key_pair(self, key_pair_name: str) -> None:
        """
        Creates a new key pair.

        :param key_pair_name: The name of the key pair to create.
        """
        try:
            response = self.ec2_client.create_key_pair(KeyName=key_pair_name)
            with open(f"{key_pair_name}.pem", "w") as file:
                file.write(response["KeyMaterial"])
            chmod(f"{key_pair_name}.pem", 0o600)
            log.info("Created key pair %s.", key_pair_name)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to create key pair {key_pair_name}.")
            if error_code == "InvalidKeyPair.Duplicate":
                log.error(f"A key pair with the name '{key_pair_name}' already exists.")
            log.error(f"Full error:\n\t{err}")


    def delete_key_pair(self) -> None:
        """
        Deletes a key pair.
        """
        try:
            self.ec2_client.delete_key_pair(KeyName=self.key_pair_name)
            remove(f"{self.key_pair_name}.pem")
            log.info("Deleted key pair %s.", self.key_pair_name)
        except ClientError as err:
            log.error(f"Couldn't delete key pair '{self.key_pair_name}'.")
            log.error(f"Full error:\n\t{err}")
        except FileNotFoundError as err:
            log.info("Key pair %s doesn't exist, nothing to do.", self.key_pair_name)
            log.error(f"Full error:\n\t{err}")


    def create_template(
        self, server_startup_script_file: str, instance_policy_file: str
    ) -> Dict[str, Any]:
        """
        Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. The
        launch template specifies a Bash script in its user data field that runs after
        the instance is started. This script installs Python packages and starts a
        Python web server on the instance.

        :param server_startup_script_file: The path to a Bash script file that is run
                                           when an instance starts.
        :param instance_policy_file: The path to a file that defines a permissions policy
                                     to create and attach to the instance profile.
        :return: Information about the newly created template.
        """
        template = {}
        try:
            # Create key pair and instance profile
            self.create_key_pair(self.key_pair_name)
            self.create_instance_profile(
                instance_policy_file,
                self.instance_policy_name,
                self.instance_role_name,
                self.instance_profile_name,
            )

            # Read the startup script
            with open(server_startup_script_file) as file:
                start_server_script = file.read()

            # Get the latest AMI ID
            ami_latest = self.ssm_client.get_parameter(Name=self.ami_param)
            ami_id = ami_latest["Parameter"]["Value"]

            # Create the launch template
            lt_response = self.ec2_client.create_launch_template(
                LaunchTemplateName=self.launch_template_name,
                LaunchTemplateData={
                    "InstanceType": self.inst_type,
                    "ImageId": ami_id,
                    "IamInstanceProfile": {"Name": self.instance_profile_name},
                    "UserData": base64.b64encode(
                        start_server_script.encode(encoding="utf-8")
                    ).decode(encoding="utf-8"),
                    "KeyName": self.key_pair_name,
                },
            )
            template = lt_response["LaunchTemplate"]
            log.info(
                f"Created launch template {self.launch_template_name} for AMI {ami_id} on {self.inst_type}."
            )
        except ClientError as err:
            log.error(f"Failed to create launch template {self.launch_template_name}.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidLaunchTemplateName.AlreadyExistsException":
                log.info(
                    f"Launch template {self.launch_template_name} already exists, nothing to do."
                )
            log.error(f"Full error:\n\t{err}")
        return template


    def delete_template(self):
        """
        Deletes a launch template.
        """
        try:
            self.ec2_client.delete_launch_template(
                LaunchTemplateName=self.launch_template_name
            )
            self.delete_instance_profile(
                self.instance_profile_name, self.instance_role_name
            )
            log.info("Launch template %s deleted.", self.launch_template_name)
        except ClientError as err:
            if (
                err.response["Error"]["Code"]
                == "InvalidLaunchTemplateName.NotFoundException"
            ):
                log.info(
                    "Launch template %s does not exist, nothing to do.",
                    self.launch_template_name,
                )
            log.error(f"Full error:\n\t{err}")


    def get_availability_zones(self) -> List[str]:
        """
        Gets a list of Availability Zones in the AWS Region of the Amazon EC2 client.

        :return: The list of Availability Zones for the client Region.
        """
        try:
            response = self.ec2_client.describe_availability_zones()
            zones = [zone["ZoneName"] for zone in response["AvailabilityZones"]]
            log.info(f"Retrieved {len(zones)} availability zones: {zones}.")
        except ClientError as err:
            log.error("Failed to retrieve availability zones.")
            log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def create_autoscaling_group(self, group_size: int) -> List[str]:
        """
        Creates an EC2 Auto Scaling group with the specified size.

        :param group_size: The number of instances to set for the minimum and maximum in
                           the group.
        :return: The list of Availability Zones specified for the group.
        """
        try:
            zones = self.get_availability_zones()
            self.autoscaling_client.create_auto_scaling_group(
                AutoScalingGroupName=self.group_name,
                AvailabilityZones=zones,
                LaunchTemplate={
                    "LaunchTemplateName": self.launch_template_name,
                    "Version": "$Default",
                },
                MinSize=group_size,
                MaxSize=group_size,
            )
            log.info(
                f"Created EC2 Auto Scaling group {self.group_name} with availability zones {zones}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            if error_code == "AlreadyExists":
                log.info(
                    f"EC2 Auto Scaling group {self.group_name} already exists, nothing to do."
                )
            else:
                log.error(f"Failed to create EC2 Auto Scaling group {self.group_name}.")
                log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def get_instances(self) -> List[str]:
        """
        Gets data about the instances in the EC2 Auto Scaling group.

        :return: A list of instance IDs in the Auto Scaling group.
        """
        try:
            as_response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[self.group_name]
            )
            instance_ids = [
                i["InstanceId"]
                for i in as_response["AutoScalingGroups"][0]["Instances"]
            ]
            log.info(
                f"Retrieved {len(instance_ids)} instances for Auto Scaling group {self.group_name}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to retrieve instances for Auto Scaling group {self.group_name}."
            )
            if error_code == "ResourceNotFound":
                log.error(f"The Auto Scaling group '{self.group_name}' does not exist.")
            log.error(f"Full error:\n\t{err}")
        else:
            return instance_ids


    def terminate_instance(self, instance_id: str, decrementsetting=False) -> None:
        """
        Terminates an instance in an EC2 Auto Scaling group. After an instance is
        terminated, it can no longer be accessed.

        :param instance_id: The ID of the instance to terminate.
        :param decrementsetting: If True, do not replace terminated instances.
        """
        try:
            self.autoscaling_client.terminate_instance_in_auto_scaling_group(
                InstanceId=instance_id,
                ShouldDecrementDesiredCapacity=decrementsetting,
            )
            log.info("Terminated instance %s.", instance_id)

            # Adding a waiter to ensure the instance is terminated
            waiter = self.ec2_client.get_waiter("instance_terminated")
            log.info("Waiting for instance %s to be terminated...", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info(
                f"Instance '{instance_id}' has been terminated and will be replaced."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to terminate instance '{instance_id}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to terminate the instance again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            log.error(f"Full error:\n\t{err}")

    def attach_load_balancer_target_group(
        self, lb_target_group: Dict[str, Any]
    ) -> None:
        """
        Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
        The target group specifies how the load balancer forwards requests to the instances
        in the group.

        :param lb_target_group: Data about the ELB target group to attach.
        """
        try:
            self.autoscaling_client.attach_load_balancer_target_groups(
                AutoScalingGroupName=self.group_name,
                TargetGroupARNs=[lb_target_group["TargetGroupArn"]],
            )
            log.info(
                "Attached load balancer target group %s to auto scaling group %s.",
                lb_target_group["TargetGroupName"],
                self.group_name,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to attach load balancer target group '{lb_target_group['TargetGroupName']}'."
            )
            if error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            elif error_code == "ServiceLinkedRoleFailure":
                log.error(
                    "The operation failed because the service-linked role is not ready or does not exist. "
                    "Check that the service-linked role exists and is correctly configured."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_autoscaling_group(self, group_name: str) -> None:
        """
        Terminates all instances in the group, then deletes the EC2 Auto Scaling group.

        :param group_name: The name of the group to delete.
        """
        try:
            response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[group_name]
            )
            groups = response.get("AutoScalingGroups", [])
            if len(groups) > 0:
                self.autoscaling_client.update_auto_scaling_group(
                    AutoScalingGroupName=group_name, MinSize=0
                )
                instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]]
                for inst_id in instance_ids:
                    self.terminate_instance(inst_id)

                # Wait for all instances to be terminated
                if instance_ids:
                    waiter = self.ec2_client.get_waiter("instance_terminated")
                    log.info("Waiting for all instances to be terminated...")
                    waiter.wait(InstanceIds=instance_ids)
                    log.info("All instances have been terminated.")
            else:
                log.info(f"No groups found named '{group_name}'! Nothing to do.")
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete Auto Scaling group '{group_name}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to delete the group again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_default_vpc(self) -> Dict[str, Any]:
        """
        Gets the default VPC for the account.

        :return: Data about the default VPC.
        """
        try:
            response = self.ec2_client.describe_vpcs(
                Filters=[{"Name": "is-default", "Values": ["true"]}]
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error("Failed to retrieve the default VPC.")
            if error_code == "UnauthorizedOperation":
                log.error(
                    "You do not have the necessary permissions to describe VPCs. "
                    "Ensure that your AWS IAM user or role has the correct permissions."
                )
            elif error_code == "InvalidParameterValue":
                log.error(
                    "One or more parameters are invalid. Check the request parameters."
                )

            log.error(f"Full error:\n\t{err}")
        else:
            if "Vpcs" in response and response["Vpcs"]:
                log.info(f"Retrieved default VPC: {response['Vpcs'][0]['VpcId']}")
                return response["Vpcs"][0]
            else:
                pass


    def verify_inbound_port(
        self, vpc: Dict[str, Any], port: int, ip_address: str
    ) -> Tuple[Dict[str, Any], bool]:
        """
        Verify the default security group of the specified VPC allows ingress from this
        computer. This can be done by allowing ingress from this computer's IP
        address. In some situations, such as connecting from a corporate network, you
        must instead specify a prefix list ID. You can also temporarily open the port to
        any IP address while running this example. If you do, be sure to remove public
        access when you're done.

        :param vpc: The VPC used by this example.
        :param port: The port to verify.
        :param ip_address: This computer's IP address.
        :return: The default security group of the specified VPC, and a value that indicates
                 whether the specified port is open.
        """
        try:
            response = self.ec2_client.describe_security_groups(
                Filters=[
                    {"Name": "group-name", "Values": ["default"]},
                    {"Name": "vpc-id", "Values": [vpc["VpcId"]]},
                ]
            )
            sec_group = response["SecurityGroups"][0]
            port_is_open = False
            log.info(f"Found default security group {sec_group['GroupId']}.")

            for ip_perm in sec_group["IpPermissions"]:
                if ip_perm.get("FromPort", 0) == port:
                    log.info(f"Found inbound rule: {ip_perm}")
                    for ip_range in ip_perm["IpRanges"]:
                        cidr = ip_range.get("CidrIp", "")
                        if cidr.startswith(ip_address) or cidr == "0.0.0.0/0":
                            port_is_open = True
                    if ip_perm["PrefixListIds"]:
                        port_is_open = True
                    if not port_is_open:
                        log.info(
                            f"The inbound rule does not appear to be open to either this computer's IP "
                            f"address of {ip_address}, to all IP addresses (0.0.0.0/0), or to a prefix list ID."
                        )
                    else:
                        break
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to verify inbound rule for port {port} for VPC {vpc['VpcId']}."
            )
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    f"The specified VPC ID '{vpc['VpcId']}' does not exist. Please check the VPC ID."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return sec_group, port_is_open


    def open_inbound_port(self, sec_group_id: str, port: int, ip_address: str) -> None:
        """
        Add an ingress rule to the specified security group that allows access on the
        specified port from the specified IP address.

        :param sec_group_id: The ID of the security group to modify.
        :param port: The port to open.
        :param ip_address: The IP address that is granted access.
        """
        try:
            self.ec2_client.authorize_security_group_ingress(
                GroupId=sec_group_id,
                CidrIp=f"{ip_address}/32",
                FromPort=port,
                ToPort=port,
                IpProtocol="tcp",
            )
            log.info(
                "Authorized ingress to %s on port %s from %s.",
                sec_group_id,
                port,
                ip_address,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to authorize ingress to security group '{sec_group_id}' on port {port} from {ip_address}."
            )
            if error_code == "InvalidGroupId.Malformed":
                log.error(
                    "The security group ID is malformed. "
                    "Please verify that the security group ID is correct."
                )
            elif error_code == "InvalidPermission.Duplicate":
                log.error(
                    "The specified rule already exists in the security group. "
                    "Check the existing rules for this security group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_subnets(self, vpc_id: str, zones: List[str] = None) -> List[Dict[str, Any]]:
        """
        Gets the default subnets in a VPC for a specified list of Availability Zones.

        :param vpc_id: The ID of the VPC to look up.
        :param zones: The list of Availability Zones to look up.
        :return: The list of subnets found.
        """
        # Ensure that 'zones' is a list, even if None is passed
        if zones is None:
            zones = []
        try:
            paginator = self.ec2_client.get_paginator("describe_subnets")
            page_iterator = paginator.paginate(
                Filters=[
                    {"Name": "vpc-id", "Values": [vpc_id]},
                    {"Name": "availability-zone", "Values": zones},
                    {"Name": "default-for-az", "Values": ["true"]},
                ]
            )

            subnets = []
            for page in page_iterator:
                subnets.extend(page["Subnets"])

            log.info("Found %s subnets for the specified zones.", len(subnets))
            return subnets
        except ClientError as err:
            log.error(
                f"Failed to retrieve subnets for VPC '{vpc_id}' in zones {zones}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    "The specified VPC ID does not exist. "
                    "Please check the VPC ID and try again."
                )
            # Add more error-specific handling as needed
            log.error(f"Full error:\n\t{err}")
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def create_target_group(
        self, target_group_name: str, protocol: str, port: int, vpc_id: str
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing target group. The target group specifies how
        the load balancer forwards requests to instances in the group and how instance
        health is checked.

        To speed up this demo, the health check is configured with shortened times and
        lower thresholds. In production, you might want to decrease the sensitivity of
        your health checks to avoid unwanted failures.

        :param target_group_name: The name of the target group to create.
        :param protocol: The protocol to use to forward requests, such as 'HTTP'.
        :param port: The port to use to forward requests, such as 80.
        :param vpc_id: The ID of the VPC in which the load balancer exists.
        :return: Data about the newly created target group.
        """
        try:
            response = self.elb_client.create_target_group(
                Name=target_group_name,
                Protocol=protocol,
                Port=port,
                HealthCheckPath="/healthcheck",
                HealthCheckIntervalSeconds=10,
                HealthCheckTimeoutSeconds=5,
                HealthyThresholdCount=2,
                UnhealthyThresholdCount=2,
                VpcId=vpc_id,
            )
            target_group = response["TargetGroups"][0]
            log.info(f"Created load balancing target group '{target_group_name}'.")
            return target_group
        except ClientError as err:
            log.error(
                f"Couldn't create load balancing target group '{target_group_name}'."
            )
            error_code = err.response["Error"]["Code"]

            if error_code == "DuplicateTargetGroupName":
                log.error(
                    f"Target group name {target_group_name} already exists. "
                    "Check if the target group already exists."
                    "Consider using a different name or deleting the existing target group if appropriate."
                )
            elif error_code == "TooManyTargetGroups":
                log.error(
                    "Too many target groups exist in the account. "
                    "Consider deleting unused target groups to create space for new ones."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_target_group(self, target_group_name) -> None:
        """
        Deletes the target group.
        """
        try:
            # Describe the target group to get its ARN
            response = self.elb_client.describe_target_groups(Names=[target_group_name])
            tg_arn = response["TargetGroups"][0]["TargetGroupArn"]

            # Delete the target group
            self.elb_client.delete_target_group(TargetGroupArn=tg_arn)
            log.info("Deleted load balancing target group %s.", target_group_name)

            # Use a custom waiter to wait until the target group is no longer available
            self.wait_for_target_group_deletion(self.elb_client, tg_arn)
            log.info("Target group %s successfully deleted.", target_group_name)

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete target group '{target_group_name}'.")
            if error_code == "TargetGroupNotFound":
                log.error(
                    "Load balancer target group either already deleted or never existed. "
                    "Verify the name and check that the resource exists in the AWS Console."
                )
            elif error_code == "ResourceInUseException":
                log.error(
                    "Target group still in use by another resource. "
                    "Ensure that the target group is no longer associated with any load balancers or resources.",
                )
            log.error(f"Full error:\n\t{err}")

    def wait_for_target_group_deletion(
        self, elb_client, target_group_arn, max_attempts=10, delay=30
    ):
        for attempt in range(max_attempts):
            try:
                elb_client.describe_target_groups(TargetGroupArns=[target_group_arn])
                print(
                    f"Attempt {attempt + 1}: Target group {target_group_arn} still exists."
                )
            except ClientError as e:
                if e.response["Error"]["Code"] == "TargetGroupNotFound":
                    print(
                        f"Target group {target_group_arn} has been successfully deleted."
                    )
                    return
                else:
                    raise
            time.sleep(delay)
        raise TimeoutError(
            f"Target group {target_group_arn} was not deleted after {max_attempts * delay} seconds."
        )


    def create_load_balancer(
        self,
        load_balancer_name: str,
        subnet_ids: List[str],
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing load balancer that uses the specified subnets
        and forwards requests to the specified target group.

        :param load_balancer_name: The name of the load balancer to create.
        :param subnet_ids: A list of subnets to associate with the load balancer.
        :return: Data about the newly created load balancer.
        """
        try:
            response = self.elb_client.create_load_balancer(
                Name=load_balancer_name, Subnets=subnet_ids
            )
            load_balancer = response["LoadBalancers"][0]
            log.info(f"Created load balancer '{load_balancer_name}'.")

            waiter = self.elb_client.get_waiter("load_balancer_available")
            log.info(
                f"Waiting for load balancer '{load_balancer_name}' to be available..."
            )
            waiter.wait(Names=[load_balancer_name])
            log.info(f"Load balancer '{load_balancer_name}' is now available!")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to create load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "DuplicateLoadBalancerNameException":
                log.error(
                    f"A load balancer with the name '{load_balancer_name}' already exists. "
                    "Load balancer names must be unique within the AWS region. "
                    "Please choose a different name and try again."
                )
            if error_code == "TooManyLoadBalancersException":
                log.error(
                    "The maximum number of load balancers has been reached in this account and region. "
                    "You can delete unused load balancers or request an increase in the service quota from AWS Support."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return load_balancer


    def create_listener(
        self,
        load_balancer_name: str,
        target_group: Dict[str, Any],
    ) -> Dict[str, Any]:
        """
        Creates a listener for the specified load balancer that forwards requests to the
        specified target group.

        :param load_balancer_name: The name of the load balancer to create a listener for.
        :param target_group: An existing target group that is added as a listener to the
                             load balancer.
        :return: Data about the newly created listener.
        """
        try:
            # Retrieve the load balancer ARN
            load_balancer_response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            load_balancer_arn = load_balancer_response["LoadBalancers"][0][
                "LoadBalancerArn"
            ]

            # Create the listener
            response = self.elb_client.create_listener(
                LoadBalancerArn=load_balancer_arn,
                Protocol=target_group["Protocol"],
                Port=target_group["Port"],
                DefaultActions=[
                    {
                        "Type": "forward",
                        "TargetGroupArn": target_group["TargetGroupArn"],
                    }
                ],
            )
            log.info(
                f"Created listener to forward traffic from load balancer '{load_balancer_name}' to target group '{target_group['TargetGroupName']}'."
            )
            return response["Listeners"][0]
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to add a listener on '{load_balancer_name}' for target group '{target_group['TargetGroupName']}'."
            )

            if error_code == "ListenerNotFoundException":
                log.error(
                    f"The listener could not be found for the load balancer '{load_balancer_name}'. "
                    "Please check the load balancer name and target group configuration."
                )
            if error_code == "InvalidConfigurationRequestException":
                log.error(
                    f"The configuration provided for the listener on load balancer '{load_balancer_name}' is invalid. "
                    "Please review the provided protocol, port, and target group settings."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_load_balancer(self, load_balancer_name) -> None:
        """
        Deletes a load balancer.

        :param load_balancer_name: The name of the load balancer to delete.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            lb_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
            self.elb_client.delete_load_balancer(LoadBalancerArn=lb_arn)
            log.info("Deleted load balancer %s.", load_balancer_name)
            waiter = self.elb_client.get_waiter("load_balancers_deleted")
            log.info("Waiting for load balancer to be deleted...")
            waiter.wait(Names=[load_balancer_name])
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Couldn't delete load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    f"The load balancer '{load_balancer_name}' does not exist. "
                    "Please check the name and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def get_endpoint(self, load_balancer_name) -> str:
        """
        Gets the HTTP endpoint of the load balancer.

        :return: The endpoint.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            return response["LoadBalancers"][0]["DNSName"]
        except ClientError as err:
            log.error(
                f"Couldn't get the endpoint for load balancer {load_balancer_name}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Verify load balancer name and ensure it exists in the AWS console."
                )
            log.error(f"Full error:\n\t{err}")

    @staticmethod
    def verify_load_balancer_endpoint(endpoint) -> bool:
        """
        Verify this computer can successfully send a GET request to the load balancer endpoint.

        :param endpoint: The endpoint to verify.
        :return: True if the GET request is successful, False otherwise.
        """
        retries = 3
        verified = False
        while not verified and retries > 0:
            try:
                lb_response = requests.get(f"http://{endpoint}")
                log.info(
                    "Got response %s from load balancer endpoint.",
                    lb_response.status_code,
                )
                if lb_response.status_code == 200:
                    verified = True
                else:
                    retries = 0
            except requests.exceptions.ConnectionError:
                log.info(
                    "Got connection error from load balancer endpoint, retrying..."
                )
                retries -= 1
                time.sleep(10)
        return verified

    def check_target_health(self, target_group_name: str) -> List[Dict[str, Any]]:
        """
        Checks the health of the instances in the target group.

        :return: The health status of the target group.
        """
        try:
            tg_response = self.elb_client.describe_target_groups(
                Names=[target_group_name]
            )
            health_response = self.elb_client.describe_target_health(
                TargetGroupArn=tg_response["TargetGroups"][0]["TargetGroupArn"]
            )
        except ClientError as err:
            log.error(f"Couldn't check health of {target_group_name} target(s).")
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Load balancer associated with the target group was not found. "
                    "Ensure the load balancer exists, is in the correct AWS region, and "
                    "that you have the necessary permissions to access it.",
                )
            elif error_code == "TargetGroupNotFoundException":
                log.error(
                    "Target group was not found. "
                    "Verify the target group name, check that it exists in the correct region, "
                    "and ensure it has not been deleted or created in a different account.",
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return health_response["TargetHealthDescriptions"]
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
class RecommendationService:
    """
    Encapsulates a DynamoDB table to use as a service that recommends books, movies,
    and songs.
    """

    def __init__(self, table_name: str, dynamodb_client: boto3.client):
        """
        Initializes the RecommendationService class with the necessary parameters.

        :param table_name: The name of the DynamoDB recommendations table.
        :param dynamodb_client: A Boto3 DynamoDB client.
        """
        self.table_name = table_name
        self.dynamodb_client = dynamodb_client

    def create(self) -> Dict[str, Any]:
        """
        Creates a DynamoDB table to use as a recommendation service. The table has a
        hash key named 'MediaType' that defines the type of media recommended, such as
        Book or Movie, and a range key named 'ItemId' that, combined with the MediaType,
        forms a unique identifier for the recommended item.

        :return: Data about the newly created table.
        :raises RecommendationServiceError: If the table creation fails.
        """
        try:
            response = self.dynamodb_client.create_table(
                TableName=self.table_name,
                AttributeDefinitions=[
                    {"AttributeName": "MediaType", "AttributeType": "S"},
                    {"AttributeName": "ItemId", "AttributeType": "N"},
                ],
                KeySchema=[
                    {"AttributeName": "MediaType", "KeyType": "HASH"},
                    {"AttributeName": "ItemId", "KeyType": "RANGE"},
                ],
                ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
            )
            log.info("Creating table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s created.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceInUseException":
                log.info("Table %s exists, nothing to be done.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when creating table: {err}."
                )
        else:
            return response

    def populate(self, data_file: str) -> None:
        """
        Populates the recommendations table from a JSON file.

        :param data_file: The path to the data file.
        :raises RecommendationServiceError: If the table population fails.
        """
        try:
            with open(data_file) as data:
                items = json.load(data)
            batch = [{"PutRequest": {"Item": item}} for item in items]
            self.dynamodb_client.batch_write_item(RequestItems={self.table_name: batch})
            log.info(
                "Populated table %s with items from %s.", self.table_name, data_file
            )
        except ClientError as err:
            raise RecommendationServiceError(
                self.table_name, f"Couldn't populate table from {data_file}: {err}"
            )

    def destroy(self) -> None:
        """
        Deletes the recommendations table.

        :raises RecommendationServiceError: If the table deletion fails.
        """
        try:
            self.dynamodb_client.delete_table(TableName=self.table_name)
            log.info("Deleting table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_not_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s deleted.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                log.info("Table %s does not exist, nothing to do.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when deleting table: {err}."
                )
```
Systems Manager のアクションをラップするクラスを作成します。  

```
class ParameterHelper:
    """
    Encapsulates Systems Manager parameters. This example uses these parameters to drive
    the demonstration of resilient architecture, such as failure of a dependency or
    how the service responds to a health check.
    """

    table: str = "doc-example-resilient-architecture-table"
    failure_response: str = "doc-example-resilient-architecture-failure-response"
    health_check: str = "doc-example-resilient-architecture-health-check"

    def __init__(self, table_name: str, ssm_client: boto3.client):
        """
        Initializes the ParameterHelper class with the necessary parameters.

        :param table_name: The name of the DynamoDB table that is used as a recommendation
                           service.
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.table_name = table_name

    def reset(self) -> None:
        """
        Resets the Systems Manager parameters to starting values for the demo.
        These are the name of the DynamoDB recommendation table, no response when a
        dependency fails, and shallow health checks.
        """
        self.put(self.table, self.table_name)
        self.put(self.failure_response, "none")
        self.put(self.health_check, "shallow")

    def put(self, name: str, value: str) -> None:
        """
        Sets the value of a named Systems Manager parameter.

        :param name: The name of the parameter.
        :param value: The new value of the parameter.
        :raises ParameterHelperError: If the parameter value cannot be set.
        """
        try:
            self.ssm_client.put_parameter(
                Name=name, Value=value, Overwrite=True, Type="String"
            )
            log.info("Setting parameter %s to '%s'.", name, value)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to set parameter {name}.")
            if error_code == "ParameterLimitExceeded":
                log.error(
                    "The parameter limit has been exceeded. "
                    "Consider deleting unused parameters or request a limit increase."
                )
            elif error_code == "ParameterAlreadyExists":
                log.error(
                    "The parameter already exists and overwrite is set to False. "
                    "Use Overwrite=True to update the parameter."
                )
            log.error(f"Full error:\n\t{err}")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

# SDK for Python (Boto3) を使用する Amazon EMR の例
<a name="python_3_emr_code_examples"></a>

次のコード例は、Amazon EMR AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AddJobFlowSteps`
<a name="emr_AddJobFlowSteps_python_3_topic"></a>

次のコード例は、`AddJobFlowSteps` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples)での設定と実行の方法を確認してください。
Spark ステップを追加します。このステップは、追加されるとすぐにクラスターによって実行されます。  

```
def add_step(cluster_id, name, script_uri, script_args, emr_client):
    """
    Adds a job step to the specified cluster. This example adds a Spark
    step, which is run by the cluster as soon as it is added.

    :param cluster_id: The ID of the cluster.
    :param name: The name of the step.
    :param script_uri: The URI where the Python script is stored.
    :param script_args: Arguments to pass to the Python script.
    :param emr_client: The Boto3 EMR client object.
    :return: The ID of the newly added step.
    """
    try:
        response = emr_client.add_job_flow_steps(
            JobFlowId=cluster_id,
            Steps=[
                {
                    "Name": name,
                    "ActionOnFailure": "CONTINUE",
                    "HadoopJarStep": {
                        "Jar": "command-runner.jar",
                        "Args": [
                            "spark-submit",
                            "--deploy-mode",
                            "cluster",
                            script_uri,
                            *script_args,
                        ],
                    },
                }
            ],
        )
        step_id = response["StepIds"][0]
        logger.info("Started step with ID %s", step_id)
    except ClientError:
        logger.exception("Couldn't start step %s with URI %s.", name, script_uri)
        raise
    else:
        return step_id
```
Amazon EMR ファイルシステム (EMRFS) コマンドをクラスターのジョブステップとして実行します。これを使用すると、SSH 接続を介して手動でコマンドを実行する代わりに、クラスターで EMRFS コマンドを自動化できます。  

```
import boto3
from botocore.exceptions import ClientError


def add_emrfs_step(command, bucket_url, cluster_id, emr_client):
    """
    Add an EMRFS command as a job flow step to an existing cluster.

    :param command: The EMRFS command to run.
    :param bucket_url: The URL of a bucket that contains tracking metadata.
    :param cluster_id: The ID of the cluster to update.
    :param emr_client: The Boto3 Amazon EMR client object.
    :return: The ID of the added job flow step. Status can be tracked by calling
             the emr_client.describe_step() function.
    """
    job_flow_step = {
        "Name": "Example EMRFS Command Step",
        "ActionOnFailure": "CONTINUE",
        "HadoopJarStep": {
            "Jar": "command-runner.jar",
            "Args": ["/usr/bin/emrfs", command, bucket_url],
        },
    }

    try:
        response = emr_client.add_job_flow_steps(
            JobFlowId=cluster_id, Steps=[job_flow_step]
        )
        step_id = response["StepIds"][0]
        print(f"Added step {step_id} to cluster {cluster_id}.")
    except ClientError:
        print(f"Couldn't add a step to cluster {cluster_id}.")
        raise
    else:
        return step_id


def usage_demo():
    emr_client = boto3.client("emr")
    # Assumes the first waiting cluster has EMRFS enabled and has created metadata
    # with the default name of 'EmrFSMetadata'.
    cluster = emr_client.list_clusters(ClusterStates=["WAITING"])["Clusters"][0]
    add_emrfs_step(
        "sync", "s3://elasticmapreduce/samples/cloudfront", cluster["Id"], emr_client
    )


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AddJobFlowSteps](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/AddJobFlowSteps)」を参照してください。

### `DescribeCluster`
<a name="emr_DescribeCluster_python_3_topic"></a>

次のコード例は、`DescribeCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples)での設定と実行の方法を確認してください。

```
def describe_cluster(cluster_id, emr_client):
    """
    Gets detailed information about a cluster.

    :param cluster_id: The ID of the cluster to describe.
    :param emr_client: The Boto3 EMR client object.
    :return: The retrieved cluster information.
    """
    try:
        response = emr_client.describe_cluster(ClusterId=cluster_id)
        cluster = response["Cluster"]
        logger.info("Got data for cluster %s.", cluster["Name"])
    except ClientError:
        logger.exception("Couldn't get data for cluster %s.", cluster_id)
        raise
    else:
        return cluster
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeCluster](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/DescribeCluster)」を参照してください。

### `DescribeStep`
<a name="emr_DescribeStep_python_3_topic"></a>

次のコード例は、`DescribeStep` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples)での設定と実行の方法を確認してください。

```
def describe_step(cluster_id, step_id, emr_client):
    """
    Gets detailed information about the specified step, including the current state of
    the step.

    :param cluster_id: The ID of the cluster.
    :param step_id: The ID of the step.
    :param emr_client: The Boto3 EMR client object.
    :return: The retrieved information about the specified step.
    """
    try:
        response = emr_client.describe_step(ClusterId=cluster_id, StepId=step_id)
        step = response["Step"]
        logger.info("Got data for step %s.", step_id)
    except ClientError:
        logger.exception("Couldn't get data for step %s.", step_id)
        raise
    else:
        return step
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeStep](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/DescribeStep)」を参照してください。

### `ListSteps`
<a name="emr_ListSteps_python_3_topic"></a>

次のコード例は、`ListSteps` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples)での設定と実行の方法を確認してください。

```
def list_steps(cluster_id, emr_client):
    """
    Gets a list of steps for the specified cluster. In this example, all steps are
    returned, including completed and failed steps.

    :param cluster_id: The ID of the cluster.
    :param emr_client: The Boto3 EMR client object.
    :return: The list of steps for the specified cluster.
    """
    try:
        response = emr_client.list_steps(ClusterId=cluster_id)
        steps = response["Steps"]
        logger.info("Got %s steps for cluster %s.", len(steps), cluster_id)
    except ClientError:
        logger.exception("Couldn't get steps for cluster %s.", cluster_id)
        raise
    else:
        return steps
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListSteps](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/ListSteps)」を参照してください。

### `RunJobFlow`
<a name="emr_RunJobFlow_python_3_topic"></a>

次のコード例は、`RunJobFlow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples)での設定と実行の方法を確認してください。

```
def run_job_flow(
    name,
    log_uri,
    keep_alive,
    applications,
    job_flow_role,
    service_role,
    security_groups,
    steps,
    emr_client,
):
    """
    Runs a job flow with the specified steps. A job flow creates a cluster of
    instances and adds steps to be run on the cluster. Steps added to the cluster
    are run as soon as the cluster is ready.

    This example uses the 'emr-5.30.1' release. A list of recent releases can be
    found here:
        https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-release-components.html.

    :param name: The name of the cluster.
    :param log_uri: The URI where logs are stored. This can be an Amazon S3 bucket URL,
                    such as 's3://my-log-bucket'.
    :param keep_alive: When True, the cluster is put into a Waiting state after all
                       steps are run. When False, the cluster terminates itself when
                       the step queue is empty.
    :param applications: The applications to install on each instance in the cluster,
                         such as Hive or Spark.
    :param job_flow_role: The IAM role assumed by the cluster.
    :param service_role: The IAM role assumed by the service.
    :param security_groups: The security groups to assign to the cluster instances.
                            Amazon EMR adds all needed rules to these groups, so
                            they can be empty if you require only the default rules.
    :param steps: The job flow steps to add to the cluster. These are run in order
                  when the cluster is ready.
    :param emr_client: The Boto3 EMR client object.
    :return: The ID of the newly created cluster.
    """
    try:
        response = emr_client.run_job_flow(
            Name=name,
            LogUri=log_uri,
            ReleaseLabel="emr-5.30.1",
            Instances={
                "MasterInstanceType": "m5.xlarge",
                "SlaveInstanceType": "m5.xlarge",
                "InstanceCount": 3,
                "KeepJobFlowAliveWhenNoSteps": keep_alive,
                "EmrManagedMasterSecurityGroup": security_groups["manager"].id,
                "EmrManagedSlaveSecurityGroup": security_groups["worker"].id,
            },
            Steps=[
                {
                    "Name": step["name"],
                    "ActionOnFailure": "CONTINUE",
                    "HadoopJarStep": {
                        "Jar": "command-runner.jar",
                        "Args": [
                            "spark-submit",
                            "--deploy-mode",
                            "cluster",
                            step["script_uri"],
                            *step["script_args"],
                        ],
                    },
                }
                for step in steps
            ],
            Applications=[{"Name": app} for app in applications],
            JobFlowRole=job_flow_role.name,
            ServiceRole=service_role.name,
            EbsRootVolumeSize=10,
            VisibleToAllUsers=True,
        )
        cluster_id = response["JobFlowId"]
        logger.info("Created cluster %s.", cluster_id)
    except ClientError:
        logger.exception("Couldn't create cluster.")
        raise
    else:
        return cluster_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[RunJobFlow](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/RunJobFlow)」を参照してください。

### `TerminateJobFlows`
<a name="emr_TerminateJobFlows_python_3_topic"></a>

次のコード例は、`TerminateJobFlows` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples)での設定と実行の方法を確認してください。

```
def terminate_cluster(cluster_id, emr_client):
    """
    Terminates a cluster. This terminates all instances in the cluster and cannot
    be undone. Any data not saved elsewhere, such as in an Amazon S3 bucket, is lost.

    :param cluster_id: The ID of the cluster to terminate.
    :param emr_client: The Boto3 EMR client object.
    """
    try:
        emr_client.terminate_job_flows(JobFlowIds=[cluster_id])
        logger.info("Terminated cluster %s.", cluster_id)
    except ClientError:
        logger.exception("Couldn't terminate cluster %s.", cluster_id)
        raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[TerminateJobFlows](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/TerminateJobFlows)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 短期運用する Amazon EMR クラスターを作成しステップを 1 つ実行する
<a name="emr_Scenario_ShortLivedEmrCluster_python_3_topic"></a>

次のコード例で、ステップを 1 つ実行し、それが完了すると自動的に終了する、短期運用する Amazon EMR クラスターを作成する方法を示します。

**SDK for Python (Boto3)**  
 Apache Spark を使用して多数の計算を並列化し pi の値を推定する、短期運用する Amazon EMR クラスターを作成します。このジョブの出力は、Amazon EMR ログと Amazon Simple Storage Service (Amazon S3) バケットに書き込まれます。このクラスターは、このジョブの完了後に自動的に終了します。  
+ Amazon S3 バケットを作成し、ジョブスクリプトをアップロードします。
+ Create AWS Identity and Access Management (IAM) ロール。
+ Amazon Elastic Compute Cloud (Amazon EC2) のセキュリティグループを作成します。
+ 短期運用するクラスターを作成し、ジョブステップを 1 つ実行します。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon EMR

### シェルスクリプトを実行してライブラリをインストールする
<a name="emr_Usage_InstallLibrariesWithSsm_python_3_topic"></a>

次のコード例は、 AWS Systems Manager を使用して、追加のライブラリをインストールする Amazon EMR インスタンスでシェルスクリプトを実行する方法を示しています。これにより、SSH 接続を介して手動でコマンドを実行する代わりに、インスタンス管理を自動化できます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/emr#code-examples)での設定と実行の方法を確認してください。

```
import argparse
import time
import boto3


def install_libraries_on_core_nodes(cluster_id, script_path, emr_client, ssm_client):
    """
    Copies and runs a shell script on the core nodes in the cluster.

    :param cluster_id: The ID of the cluster.
    :param script_path: The path to the script, typically an Amazon S3 object URL.
    :param emr_client: The Boto3 Amazon EMR client.
    :param ssm_client: The Boto3 AWS Systems Manager client.
    """
    core_nodes = emr_client.list_instances(
        ClusterId=cluster_id, InstanceGroupTypes=["CORE"]
    )["Instances"]
    core_instance_ids = [node["Ec2InstanceId"] for node in core_nodes]
    print(f"Found core instances: {core_instance_ids}.")

    commands = [
        # Copy the shell script from Amazon S3 to each node instance.
        f"aws s3 cp {script_path} /home/hadoop",
        # Run the shell script to install libraries on each node instance.
        "bash /home/hadoop/install_libraries.sh",
    ]
    for command in commands:
        print(f"Sending '{command}' to core instances...")
        command_id = ssm_client.send_command(
            InstanceIds=core_instance_ids,
            DocumentName="AWS-RunShellScript",
            Parameters={"commands": [command]},
            TimeoutSeconds=3600,
        )["Command"]["CommandId"]
        while True:
            # Verify the previous step succeeded before running the next step.
            cmd_result = ssm_client.list_commands(CommandId=command_id)["Commands"][0]
            if cmd_result["StatusDetails"] == "Success":
                print(f"Command succeeded.")
                break
            elif cmd_result["StatusDetails"] in ["Pending", "InProgress"]:
                print(f"Command status is {cmd_result['StatusDetails']}, waiting...")
                time.sleep(10)
            else:
                print(f"Command status is {cmd_result['StatusDetails']}, quitting.")
                raise RuntimeError(
                    f"Command {command} failed to run. "
                    f"Details: {cmd_result['StatusDetails']}"
                )


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("cluster_id", help="The ID of the cluster.")
    parser.add_argument("script_path", help="The path to the script in Amazon S3.")
    args = parser.parse_args()

    emr_client = boto3.client("emr")
    ssm_client = boto3.client("ssm")

    install_libraries_on_core_nodes(
        args.cluster_id, args.script_path, emr_client, ssm_client
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、*AWS  SDK for Python (Boto3) API リファレンス*の「[ListInstances](https://docs.aws.amazon.com/goto/boto3/elasticmapreduce-2009-03-31/ListInstances)」を参照してください。

# SDK for Python (Boto3) を使用する EventBridge の例
<a name="python_3_eventbridge_code_examples"></a>

次のコード例は、EventBridge AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_python_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例では、スケジュールされた Amazon EventBridge イベントのターゲットとして AWS Lambda 関数を登録する方法を示します。Lambda ハンドラーは、後で取得するために Amazon CloudWatch Logs にわかりやすいメッセージと完全なイベントデータを書き込みます。  
+ Lambda 関数をデプロイします。
+ EventBridge スケジュールイベントを作成し、Lambda 関数をターゲットにします。
+ EventBridge に Lambda 関数を呼び出す許可を付与します
+ CloudWatch Logs から最新のデータを出力して、スケジュールされた呼び出しの結果を表示しています。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

# SDK for Python (Boto3) を使用する EventBridge スケジューラの例
<a name="python_3_scheduler_code_examples"></a>

次のコード例は、EventBridge スケジューラ AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello EventBridge スケジューラ
<a name="scheduler_hello_python_3_topic"></a>

次のコード例は、EventBridge スケジューラの使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_scheduler(scheduler_client):
    """
    Use the AWS SDK for Python (Boto3) to create an Amazon EventBridge Scheduler
    client and list the schedules in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param scheduler_client: A Boto3 Amazon EventBridge Scheduler Client object. This object wraps
                             the low-level Amazon EventBridge Scheduler service API.
    """
    print("Hello, Amazon EventBridge Scheduler! Let's list some of your schedules:\n")
    paginator = scheduler_client.get_paginator("list_schedules")
    page_iterator = paginator.paginate(PaginationConfig={"MaxItems": 10})

    schedule_names: [str] = []
    for page in page_iterator:
        for schedule in page["Schedules"]:
            schedule_names.append(schedule["Name"])

    print(f"{len(schedule_names)} schedule(s) retrieved.")
    for schedule_name in schedule_names:
        print(f"\t{schedule_name}")


if __name__ == "__main__":
    hello_scheduler(boto3.client("scheduler"))
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListSchedules](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/ListSchedules)」を参照してください。**

## アクション
<a name="actions"></a>

### `CreateSchedule`
<a name="scheduler_CreateSchedule_python_3_topic"></a>

次のコード例は、`CreateSchedule` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
class SchedulerWrapper:
    def __init__(self, eventbridge_scheduler_client: client):
        self.scheduler_client = eventbridge_scheduler_client

    @classmethod
    def from_client(cls) -> "SchedulerWrapper":
        """
        Creates a SchedulerWrapper instance with a default EventBridge Scheduler client.

        :return: An instance of SchedulerWrapper initialized with the default EventBridge Scheduler client.
        """
        eventbridge_scheduler_client = boto3.client("scheduler")
        return cls(eventbridge_scheduler_client)


    def create_schedule(
        self,
        name: str,
        schedule_expression: str,
        schedule_group_name: str,
        target_arn: str,
        role_arn: str,
        input: str,
        delete_after_completion: bool = False,
        use_flexible_time_window: bool = False,
    ) -> str:
        """
        Creates a new schedule with the specified parameters.

        :param name: The name of the schedule.
        :param schedule_expression: The expression that defines when the schedule runs.
        :param schedule_group_name: The name of the schedule group.
        :param target_arn: The Amazon Resource Name (ARN) of the target.
        :param role_arn: The Amazon Resource Name (ARN) of the execution IAM role.
        :param input: The input for the target.
        :param delete_after_completion: Whether to delete the schedule after it completes.
        :param use_flexible_time_window: Whether to use a flexible time window.

        :return The ARN of the created schedule.
        """
        try:
            hours_to_run = 1
            flexible_time_window_minutes = 10
            parameters = {
                "Name": name,
                "ScheduleExpression": schedule_expression,
                "GroupName": schedule_group_name,
                "Target": {"Arn": target_arn, "RoleArn": role_arn, "Input": input},
                "StartDate": datetime.now(timezone.utc),
                "EndDate": datetime.now(timezone.utc) + timedelta(hours=hours_to_run),
            }

            if delete_after_completion:
                parameters["ActionAfterCompletion"] = "DELETE"

            if use_flexible_time_window:
                parameters["FlexibleTimeWindow"] = {
                    "Mode": "FLEXIBLE",
                    "MaximumWindowInMinutes": flexible_time_window_minutes,
                }
            else:
                parameters["FlexibleTimeWindow"] = {"Mode": "OFF"}

            response = self.scheduler_client.create_schedule(**parameters)
            return response["ScheduleArn"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConflictException":
                logger.error(
                    "Failed to create schedule '%s' due to a conflict. %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error creating schedule: %s", err.response["Error"]["Message"]
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateSchedule](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/CreateSchedule)」を参照してください。**

### `CreateScheduleGroup`
<a name="scheduler_CreateScheduleGroup_python_3_topic"></a>

次のコード例は、`CreateScheduleGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
class SchedulerWrapper:
    def __init__(self, eventbridge_scheduler_client: client):
        self.scheduler_client = eventbridge_scheduler_client

    @classmethod
    def from_client(cls) -> "SchedulerWrapper":
        """
        Creates a SchedulerWrapper instance with a default EventBridge Scheduler client.

        :return: An instance of SchedulerWrapper initialized with the default EventBridge Scheduler client.
        """
        eventbridge_scheduler_client = boto3.client("scheduler")
        return cls(eventbridge_scheduler_client)


    def create_schedule_group(self, name: str) -> str:
        """
        Creates a new schedule group with the specified name and description.

        :param name: The name of the schedule group.
        :param description: The description of the schedule group.

        :return: The ARN of the created schedule group.
        """
        try:
            response = self.scheduler_client.create_schedule_group(Name=name)
            return response["ScheduleGroupArn"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConflictException":
                logger.error(
                    "Failed to create schedule group '%s' due to a conflict. %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error creating schedule group: %s",
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateScheduleGroup](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/CreateScheduleGroup)」を参照してください。**

### `DeleteSchedule`
<a name="scheduler_DeleteSchedule_python_3_topic"></a>

次のコード例は、`DeleteSchedule` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
class SchedulerWrapper:
    def __init__(self, eventbridge_scheduler_client: client):
        self.scheduler_client = eventbridge_scheduler_client

    @classmethod
    def from_client(cls) -> "SchedulerWrapper":
        """
        Creates a SchedulerWrapper instance with a default EventBridge Scheduler client.

        :return: An instance of SchedulerWrapper initialized with the default EventBridge Scheduler client.
        """
        eventbridge_scheduler_client = boto3.client("scheduler")
        return cls(eventbridge_scheduler_client)


    def delete_schedule(self, name: str, schedule_group_name: str) -> None:
        """
        Deletes the schedule with the specified name and schedule group.

        :param name: The name of the schedule.
        :param schedule_group_name: The name of the schedule group.
        """
        try:
            self.scheduler_client.delete_schedule(
                Name=name, GroupName=schedule_group_name
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Failed to delete schedule with ID '%s' because the resource was not found: %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error deleting schedule: %s", err.response["Error"]["Message"]
                )
                raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteSchedule](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/DeleteSchedule)」を参照してください。**

### `DeleteScheduleGroup`
<a name="scheduler_DeleteScheduleGroup_python_3_topic"></a>

次のコード例は、`DeleteScheduleGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。

```
class SchedulerWrapper:
    def __init__(self, eventbridge_scheduler_client: client):
        self.scheduler_client = eventbridge_scheduler_client

    @classmethod
    def from_client(cls) -> "SchedulerWrapper":
        """
        Creates a SchedulerWrapper instance with a default EventBridge Scheduler client.

        :return: An instance of SchedulerWrapper initialized with the default EventBridge Scheduler client.
        """
        eventbridge_scheduler_client = boto3.client("scheduler")
        return cls(eventbridge_scheduler_client)


    def delete_schedule_group(self, name: str) -> None:
        """
        Deletes the schedule group with the specified name.

        :param name: The name of the schedule group.
        """
        try:
            self.scheduler_client.delete_schedule_group(Name=name)
            logger.info("Schedule group %s deleted successfully.", name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Failed to delete schedule group with ID '%s' because the resource was not found: %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error deleting schedule group: %s",
                    err.response["Error"]["Message"],
                )
                raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteScheduleGroup](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/DeleteScheduleGroup)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 予定されているイベント
<a name="scheduler_ScheduledEventsScenario_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 必要なリソースを使用して CloudFormation スタックをデプロイします。
+ EventBridge スケジューラのスケジュールグループを作成します。
+ 柔軟な時間枠で 1 回限りの EventBridge スケジューラのスケジュールを作成します。
+ 指定されたレートで定期的な EventBridge スケジューラのスケジュールを作成します。
+ EventBridge スケジューラのスケジュールとスケジュールグループを削除します。
+ リソースをクリーンアップしてスタックを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/scheduler#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class SchedulerScenario:
    """
    A scenario that demonstrates how to use Boto3 to schedule and receive events using
    the Amazon EventBridge Scheduler.
    """

    def __init__(
        self,
        scheduler_wrapper: SchedulerWrapper,
        cloud_formation_resource: ServiceResource,
    ):
        self.eventbridge_scheduler = scheduler_wrapper
        self.cloud_formation_resource = cloud_formation_resource
        self.stack: ServiceResource = None
        self.schedule_group_name = None
        self.sns_topic_arn = None
        self.role_arn = None

    def run(self) -> None:
        """
        Runs the scenario.
        """

        print(DASHES)
        print("Welcome to the Amazon EventBridge Scheduler Workflow.")
        print(DASHES)

        print(DASHES)
        self.prepare_application()
        print(DASHES)

        print(DASHES)
        self.create_one_time_schedule()
        print(DASHES)

        print(DASHES)
        self.create_recurring_schedule()
        print(DASHES)

        print(DASHES)
        if q.ask(
            "Do you want to delete all resources created by this workflow? (y/n) ",
            q.is_yesno,
        ):
            self.cleanup()
        print(DASHES)

        print("Amazon EventBridge Scheduler workflow completed.")

    def prepare_application(self) -> None:
        """
        Prepares the application by prompting the user setup information, deploying a CloudFormation stack and
        creating a schedule group.
        """
        print("Preparing the application...")
        print(
            "\nThis example creates resources in a CloudFormation stack, including an SNS topic"
            + "\nthat will be subscribed to the EventBridge Scheduler events. "
            + "\n\nYou will need to confirm the subscription in order to receive event emails. "
        )

        email_address = q.ask("Enter an email address to use for event subscriptions: ")
        stack_name = q.ask("Enter a name for the AWS Cloud Formation Stack: ")

        template_file = SchedulerScenario.get_template_as_string()

        parameters = [{"ParameterKey": "email", "ParameterValue": email_address}]

        self.stack = self.deploy_cloudformation_stack(
            stack_name, template_file, parameters
        )
        outputs = self.stack.outputs
        for output in outputs:
            if output.get("OutputKey") == "RoleARN":
                self.role_arn = output.get("OutputValue")
            elif output.get("OutputKey") == "SNStopicARN":
                self.sns_topic_arn = output.get("OutputValue")

        if not self.sns_topic_arn or not self.role_arn:
            error_string = f"""
            Failed to retrieve required outputs from CloudFormation stack.
            'sns_topic_arn'={self.sns_topic_arn}, 'role_arn'={self.role_arn}
            """
            logger.error(error_string)
            raise ValueError(error_string)

        print(f"Stack output RoleARN: {self.role_arn}")
        print(f"Stack output SNStopicARN: a")
        schedule_group_name = "scenario-schedules-group"
        schedule_group_arn = self.eventbridge_scheduler.create_schedule_group(
            schedule_group_name
        )
        print(
            f"Successfully created schedule group '{self.schedule_group_name}': {schedule_group_arn}."
        )
        self.schedule_group_name = schedule_group_name
        print("Application preparation complete.")

    def create_one_time_schedule(self) -> None:
        """
        Creates a one-time schedule to send an initial event.
        """
        schedule_name = q.ask("Enter a name for the one-time schedule:")

        scheduled_time = datetime.now(timezone.utc) + timedelta(minutes=1)
        formatted_scheduled_time = scheduled_time.strftime("%Y-%m-%dT%H:%M:%S")

        print(
            f"Creating a one-time schedule named '{schedule_name}' "
            + f"\nto send an initial event in 1 minute with a flexible time window..."
        )

        schedule_arn = self.eventbridge_scheduler.create_schedule(
            schedule_name,
            f"at({formatted_scheduled_time})",
            self.schedule_group_name,
            self.sns_topic_arn,
            self.role_arn,
            f"One time scheduled event test from schedule {schedule_name}.",
            delete_after_completion=True,
            use_flexible_time_window=True,
        )
        print(
            f"Successfully created schedule '{schedule_name}' in schedule group 'scenario-schedules-group': {schedule_arn}."
        )
        print(f"Subscription email will receive an email from this event.")
        print(f"You must confirm your subscription to receive event emails.")
        print(f"One-time schedule '{schedule_name}' created successfully.")

    def create_recurring_schedule(self) -> None:
        """
        Create a recurring schedule to send events at a specified rate in minutes.
        """

        print("Creating a recurring schedule to send events for one hour...")
        schedule_name = q.ask("Enter a name for the recurring schedule: ")
        schedule_rate_in_minutes = q.ask(
            "Enter the desired schedule rate (in minutes): ", q.is_int
        )

        schedule_arn = self.eventbridge_scheduler.create_schedule(
            schedule_name,
            f"rate({schedule_rate_in_minutes} minutes)",
            self.schedule_group_name,
            self.sns_topic_arn,
            self.role_arn,
            f"Recurrent event test from schedule {schedule_name}.",
        )

        print(
            f"Successfully created schedule '{schedule_name}' in schedule group 'scenario-schedules-group': {schedule_arn}."
        )
        print(f"Subscription email will receive an email from this event.")
        print(f"You must confirm your subscription to receive event emails.")

        if q.ask(
            f"Are you ready to delete the '{schedule_name}' schedule? (y/n)", q.is_yesno
        ):
            self.eventbridge_scheduler.delete_schedule(
                schedule_name, self.schedule_group_name
            )

    def deploy_cloudformation_stack(
        self, stack_name: str, cfn_template: str, parameters: [dict[str, str]]
    ) -> ServiceResource:
        """
        Deploys prerequisite resources used by the scenario. The resources are
        defined in the associated `cfn_template.yaml` AWS CloudFormation script and are deployed
        as a CloudFormation stack, so they can be easily managed and destroyed.

        :param stack_name: The name of the CloudFormation stack.
        :param cfn_template: The CloudFormation template as a string.
        :param parameters: The parameters for the CloudFormation stack.
        :return: The CloudFormation stack resource.
        """
        print(f"Deploying CloudFormation stack: {stack_name}.")
        stack = self.cloud_formation_resource.create_stack(
            StackName=stack_name,
            TemplateBody=cfn_template,
            Capabilities=["CAPABILITY_NAMED_IAM"],
            Parameters=parameters,
        )
        print(f"CloudFormation stack creation started: {stack_name}")
        print("Waiting for CloudFormation stack creation to complete...")
        waiter = self.cloud_formation_resource.meta.client.get_waiter(
            "stack_create_complete"
        )
        waiter.wait(StackName=stack.name)
        stack.load()
        print("CloudFormation stack creation complete.")

        return stack

    def destroy_cloudformation_stack(self, stack: ServiceResource) -> None:
        """
        Destroys the resources managed by the CloudFormation stack, and the CloudFormation
        stack itself.

        :param stack: The CloudFormation stack that manages the example resources.
        """
        print(
            f"CloudFormation stack '{stack.name}' is being deleted. This may take a few minutes."
        )
        stack.delete()
        waiter = self.cloud_formation_resource.meta.client.get_waiter(
            "stack_delete_complete"
        )
        waiter.wait(StackName=stack.name)
        print(f"CloudFormation stack '{stack.name}' has been deleted.")

    def cleanup(self) -> None:
        """
        Deletes the CloudFormation stack and the resources created for the demo.
        """

        if self.schedule_group_name:
            schedule_group_name = self.schedule_group_name
            self.schedule_group_name = None
            self.eventbridge_scheduler.delete_schedule_group(schedule_group_name)
            print(f"Successfully deleted schedule group '{schedule_group_name}'.")

        if self.stack is not None:
            stack = self.stack
            self.stack = None
            self.destroy_cloudformation_stack(stack)
        print("Stack deleted, demo complete.")

    @staticmethod
    def get_template_as_string() -> str:
        """
        Returns a string containing this scenario's CloudFormation template.
        """
        script_directory = os.path.dirname(os.path.abspath(__file__))
        template_file_path = os.path.join(script_directory, "cfn_template.yaml")
        file = open(template_file_path, "r")
        return file.read()


if __name__ == "__main__":
    demo: SchedulerScenario = None
    try:
        scheduler_wrapper = SchedulerWrapper.from_client()
        cloud_formation_resource = resource("cloudformation")
        demo = SchedulerScenario(scheduler_wrapper, cloud_formation_resource)
        demo.run()

    except Exception as exception:
        logging.exception("Something went wrong with the demo!")
        if demo is not None:
            demo.cleanup()
```
Amazon EventBridge スケジューラアクションをラップする SchedulerWrapper クラス。  

```
class SchedulerWrapper:
    def __init__(self, eventbridge_scheduler_client: client):
        self.scheduler_client = eventbridge_scheduler_client

    @classmethod
    def from_client(cls) -> "SchedulerWrapper":
        """
        Creates a SchedulerWrapper instance with a default EventBridge Scheduler client.

        :return: An instance of SchedulerWrapper initialized with the default EventBridge Scheduler client.
        """
        eventbridge_scheduler_client = boto3.client("scheduler")
        return cls(eventbridge_scheduler_client)


    def create_schedule(
        self,
        name: str,
        schedule_expression: str,
        schedule_group_name: str,
        target_arn: str,
        role_arn: str,
        input: str,
        delete_after_completion: bool = False,
        use_flexible_time_window: bool = False,
    ) -> str:
        """
        Creates a new schedule with the specified parameters.

        :param name: The name of the schedule.
        :param schedule_expression: The expression that defines when the schedule runs.
        :param schedule_group_name: The name of the schedule group.
        :param target_arn: The Amazon Resource Name (ARN) of the target.
        :param role_arn: The Amazon Resource Name (ARN) of the execution IAM role.
        :param input: The input for the target.
        :param delete_after_completion: Whether to delete the schedule after it completes.
        :param use_flexible_time_window: Whether to use a flexible time window.

        :return The ARN of the created schedule.
        """
        try:
            hours_to_run = 1
            flexible_time_window_minutes = 10
            parameters = {
                "Name": name,
                "ScheduleExpression": schedule_expression,
                "GroupName": schedule_group_name,
                "Target": {"Arn": target_arn, "RoleArn": role_arn, "Input": input},
                "StartDate": datetime.now(timezone.utc),
                "EndDate": datetime.now(timezone.utc) + timedelta(hours=hours_to_run),
            }

            if delete_after_completion:
                parameters["ActionAfterCompletion"] = "DELETE"

            if use_flexible_time_window:
                parameters["FlexibleTimeWindow"] = {
                    "Mode": "FLEXIBLE",
                    "MaximumWindowInMinutes": flexible_time_window_minutes,
                }
            else:
                parameters["FlexibleTimeWindow"] = {"Mode": "OFF"}

            response = self.scheduler_client.create_schedule(**parameters)
            return response["ScheduleArn"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConflictException":
                logger.error(
                    "Failed to create schedule '%s' due to a conflict. %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error creating schedule: %s", err.response["Error"]["Message"]
                )
            raise


    def delete_schedule(self, name: str, schedule_group_name: str) -> None:
        """
        Deletes the schedule with the specified name and schedule group.

        :param name: The name of the schedule.
        :param schedule_group_name: The name of the schedule group.
        """
        try:
            self.scheduler_client.delete_schedule(
                Name=name, GroupName=schedule_group_name
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Failed to delete schedule with ID '%s' because the resource was not found: %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error deleting schedule: %s", err.response["Error"]["Message"]
                )
                raise


    def create_schedule_group(self, name: str) -> str:
        """
        Creates a new schedule group with the specified name and description.

        :param name: The name of the schedule group.
        :param description: The description of the schedule group.

        :return: The ARN of the created schedule group.
        """
        try:
            response = self.scheduler_client.create_schedule_group(Name=name)
            return response["ScheduleGroupArn"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ConflictException":
                logger.error(
                    "Failed to create schedule group '%s' due to a conflict. %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error creating schedule group: %s",
                    err.response["Error"]["Message"],
                )
            raise


    def delete_schedule_group(self, name: str) -> None:
        """
        Deletes the schedule group with the specified name.

        :param name: The name of the schedule group.
        """
        try:
            self.scheduler_client.delete_schedule_group(Name=name)
            logger.info("Schedule group %s deleted successfully.", name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Failed to delete schedule group with ID '%s' because the resource was not found: %s",
                    name,
                    err.response["Error"]["Message"],
                )
            else:
                logger.error(
                    "Error deleting schedule group: %s",
                    err.response["Error"]["Message"],
                )
                raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateSchedule](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/CreateSchedule)
  + [CreateScheduleGroup](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/CreateScheduleGroup)
  + [DeleteSchedule](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/DeleteSchedule)
  + [DeleteScheduleGroups](https://docs.aws.amazon.com/goto/boto3/scheduler-2021-06-30/DeleteScheduleGroups)

# SDK for Python (Boto3) を使用した Amazon Glacier の例
<a name="python_3_glacier_code_examples"></a>

次のコード例は、Amazon Glacier AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateVault`
<a name="glacier_CreateVault_python_3_topic"></a>

次のコード例は、`CreateVault` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    def create_vault(self, vault_name):
        """
        Creates a vault.

        :param vault_name: The name to give the vault.
        :return: The newly created vault.
        """
        try:
            vault = self.glacier_resource.create_vault(vaultName=vault_name)
            logger.info("Created vault %s.", vault_name)
        except ClientError:
            logger.exception("Couldn't create vault %s.", vault_name)
            raise
        else:
            return vault
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateVault](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/CreateVault)」を参照してください。

### `DeleteArchive`
<a name="glacier_DeleteArchive_python_3_topic"></a>

次のコード例は、`DeleteArchive` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def delete_archive(archive):
        """
        Deletes an archive from a vault.

        :param archive: The archive to delete.
        """
        try:
            archive.delete()
            logger.info(
                "Deleted archive %s from vault %s.", archive.id, archive.vault_name
            )
        except ClientError:
            logger.exception("Couldn't delete archive %s.", archive.id)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteArchive](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/DeleteArchive)」を参照してください。

### `DeleteVault`
<a name="glacier_DeleteVault_python_3_topic"></a>

次のコード例は、`DeleteVault` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def delete_vault(vault):
        """
        Deletes a vault.

        :param vault: The vault to delete.
        """
        try:
            vault.delete()
            logger.info("Deleted vault %s.", vault.name)
        except ClientError:
            logger.exception("Couldn't delete vault %s.", vault.name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteVault](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/DeleteVault)」を参照してください。

### `DeleteVaultNotifications`
<a name="glacier_DeleteVaultNotifications_python_3_topic"></a>

次のコード例は、`DeleteVaultNotifications` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def stop_notifications(notification):
        """
        Stops notifications to the configured Amazon SNS topic.

        :param notification: The notification configuration to remove.
        """
        try:
            notification.delete()
            logger.info("Notifications stopped.")
        except ClientError:
            logger.exception("Couldn't stop notifications.")
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteVaultNotifications](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/DeleteVaultNotifications)」を参照してください。

### `DescribeJob`
<a name="glacier_DescribeJob_python_3_topic"></a>

次のコード例は、`DescribeJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def get_job_status(job):
        """
        Gets the status of a job.

        :param job: The job to query.
        :return: The current status of the job.
        """
        try:
            job.load()
            logger.info(
                "Job %s is performing action %s and has status %s.",
                job.id,
                job.action,
                job.status_code,
            )
        except ClientError:
            logger.exception("Couldn't get status for job %s.", job.id)
            raise
        else:
            return job.status_code
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeJob](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/DescribeJob)」を参照してください。

### `GetJobOutput`
<a name="glacier_GetJobOutput_python_3_topic"></a>

次のコード例は、`GetJobOutput` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def get_job_output(job):
        """
        Gets the output of a job, such as a vault inventory or the contents of an
        archive.

        :param job: The job to get output from.
        :return: The job output, in bytes.
        """
        try:
            response = job.get_output()
            out_bytes = response["body"].read()
            logger.info("Read %s bytes from job %s.", len(out_bytes), job.id)
            if "archiveDescription" in response:
                logger.info(
                    "These bytes are described as '%s'", response["archiveDescription"]
                )
        except ClientError:
            logger.exception("Couldn't get output for job %s.", job.id)
            raise
        else:
            return out_bytes
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetJobOutput](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/GetJobOutput)」を参照してください。

### `GetVaultNotifications`
<a name="glacier_GetVaultNotifications_python_3_topic"></a>

次のコード例は、`GetVaultNotifications` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def get_notification(vault):
        """
        Gets the currently notification configuration for a vault.

        :param vault: The vault to query.
        :return: The notification configuration for the specified vault.
        """
        try:
            notification = vault.Notification()
            logger.info(
                "Vault %s notifies %s on %s events.",
                vault.name,
                notification.sns_topic,
                notification.events,
            )
        except ClientError:
            logger.exception("Couldn't get notification data for %s.", vault.name)
            raise
        else:
            return notification
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetVaultNotifications](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/GetVaultNotifications)」を参照してください。

### `InitiateJob`
<a name="glacier_InitiateJob_python_3_topic"></a>

次のコード例は、`InitiateJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。
ボールトインベントリを取得します。  

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def initiate_inventory_retrieval(vault):
        """
        Initiates an inventory retrieval job. The inventory describes the contents
        of the vault. Standard retrievals typically complete within 3—5 hours.
        When the job completes, you can get the inventory by calling get_output().

        :param vault: The vault to inventory.
        :return: The inventory retrieval job.
        """
        try:
            job = vault.initiate_inventory_retrieval()
            logger.info("Started %s job with ID %s.", job.action, job.id)
        except ClientError:
            logger.exception("Couldn't start job on vault %s.", vault.name)
            raise
        else:
            return job
```
ボールトからアーカイブを取得します。  

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def initiate_archive_retrieval(archive):
        """
        Initiates an archive retrieval job. Standard retrievals typically complete
        within 3—5 hours. When the job completes, you can get the archive contents
        by calling get_output().

        :param archive: The archive to retrieve.
        :return: The archive retrieval job.
        """
        try:
            job = archive.initiate_archive_retrieval()
            logger.info("Started %s job with ID %s.", job.action, job.id)
        except ClientError:
            logger.exception("Couldn't start job on archive %s.", archive.id)
            raise
        else:
            return job
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[InitiateJob](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/InitiateJob)」を参照してください。

### `ListJobs`
<a name="glacier_ListJobs_python_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def list_jobs(vault, job_type):
        """
        Lists jobs by type for the specified vault.

        :param vault: The vault to query.
        :param job_type: The type of job to list.
        :return: The list of jobs of the requested type.
        """
        job_list = []
        try:
            if job_type == "all":
                jobs = vault.jobs.all()
            elif job_type == "in_progress":
                jobs = vault.jobs_in_progress.all()
            elif job_type == "completed":
                jobs = vault.completed_jobs.all()
            elif job_type == "succeeded":
                jobs = vault.succeeded_jobs.all()
            elif job_type == "failed":
                jobs = vault.failed_jobs.all()
            else:
                jobs = []
                logger.warning("%s isn't a type of job I can get.", job_type)
            for job in jobs:
                job_list.append(job)
                logger.info("Got %s %s job %s.", job_type, job.action, job.id)
        except ClientError:
            logger.exception("Couldn't get %s jobs from %s.", job_type, vault.name)
            raise
        else:
            return job_list
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[ListJobs](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/ListJobs)」を参照してください。

### `ListVaults`
<a name="glacier_ListVaults_python_3_topic"></a>

次のコード例は、`ListVaults` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    def list_vaults(self):
        """
        Lists vaults for the current account.
        """
        try:
            for vault in self.glacier_resource.vaults.all():
                logger.info("Got vault %s.", vault.name)
        except ClientError:
            logger.exception("Couldn't list vaults.")
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListVaults](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/ListVaults)」を参照してください。

### `SetVaultNotifications`
<a name="glacier_SetVaultNotifications_python_3_topic"></a>

次のコード例は、`SetVaultNotifications` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    def set_notifications(self, vault, sns_topic_arn):
        """
        Sets an Amazon Simple Notification Service (Amazon SNS) topic as a target
        for notifications. Amazon S3 Glacier publishes messages to this topic for
        the configured list of events.

        :param vault: The vault to set up to publish notifications.
        :param sns_topic_arn: The Amazon Resource Name (ARN) of the topic that
                              receives notifications.
        :return: Data about the new notification configuration.
        """
        try:
            notification = self.glacier_resource.Notification("-", vault.name)
            notification.set(
                vaultNotificationConfig={
                    "SNSTopic": sns_topic_arn,
                    "Events": [
                        "ArchiveRetrievalCompleted",
                        "InventoryRetrievalCompleted",
                    ],
                }
            )
            logger.info(
                "Notifications will be sent to %s for events %s from %s.",
                notification.sns_topic,
                notification.events,
                notification.vault_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't set notifications to %s on %s.", sns_topic_arn, vault.name
            )
            raise
        else:
            return notification
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[SetVaultNotification](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/SetVaultNotifications)」を参照してください。

### `UploadArchive`
<a name="glacier_UploadArchive_python_3_topic"></a>

次のコード例は、`UploadArchive` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。

```
class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def upload_archive(vault, archive_description, archive_file):
        """
        Uploads an archive to a vault.

        :param vault: The vault where the archive is put.
        :param archive_description: A description of the archive.
        :param archive_file: The archive file to put in the vault.
        :return: The uploaded archive.
        """
        try:
            archive = vault.upload_archive(
                archiveDescription=archive_description, body=archive_file
            )
            logger.info(
                "Uploaded %s with ID %s to vault %s.",
                archive_description,
                archive.id,
                vault.name,
            )
        except ClientError:
            logger.exception(
                "Couldn't upload %s to %s.", archive_description, vault.name
            )
            raise
        else:
            return archive
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UploadArchive](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/UploadArchive)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ファイルのアーカイブ、通知の取得、ジョブの開始
<a name="glacier_Usage_UploadNotifyInitiate_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Glacier ボールトを作成します。
+ ボールトを設定して、Amazon SNS トピックに通知を発行します。
+ ボールトにアーカイブファイルをアップロードします。
+ アーカイブの取得ジョブを開始します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。
Amazon Glacier オペレーションをラップするクラスを作成します。  

```
import argparse
import logging
import os
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    def create_vault(self, vault_name):
        """
        Creates a vault.

        :param vault_name: The name to give the vault.
        :return: The newly created vault.
        """
        try:
            vault = self.glacier_resource.create_vault(vaultName=vault_name)
            logger.info("Created vault %s.", vault_name)
        except ClientError:
            logger.exception("Couldn't create vault %s.", vault_name)
            raise
        else:
            return vault


    def list_vaults(self):
        """
        Lists vaults for the current account.
        """
        try:
            for vault in self.glacier_resource.vaults.all():
                logger.info("Got vault %s.", vault.name)
        except ClientError:
            logger.exception("Couldn't list vaults.")
            raise


    @staticmethod
    def upload_archive(vault, archive_description, archive_file):
        """
        Uploads an archive to a vault.

        :param vault: The vault where the archive is put.
        :param archive_description: A description of the archive.
        :param archive_file: The archive file to put in the vault.
        :return: The uploaded archive.
        """
        try:
            archive = vault.upload_archive(
                archiveDescription=archive_description, body=archive_file
            )
            logger.info(
                "Uploaded %s with ID %s to vault %s.",
                archive_description,
                archive.id,
                vault.name,
            )
        except ClientError:
            logger.exception(
                "Couldn't upload %s to %s.", archive_description, vault.name
            )
            raise
        else:
            return archive


    @staticmethod
    def initiate_archive_retrieval(archive):
        """
        Initiates an archive retrieval job. Standard retrievals typically complete
        within 3—5 hours. When the job completes, you can get the archive contents
        by calling get_output().

        :param archive: The archive to retrieve.
        :return: The archive retrieval job.
        """
        try:
            job = archive.initiate_archive_retrieval()
            logger.info("Started %s job with ID %s.", job.action, job.id)
        except ClientError:
            logger.exception("Couldn't start job on archive %s.", archive.id)
            raise
        else:
            return job


    @staticmethod
    def list_jobs(vault, job_type):
        """
        Lists jobs by type for the specified vault.

        :param vault: The vault to query.
        :param job_type: The type of job to list.
        :return: The list of jobs of the requested type.
        """
        job_list = []
        try:
            if job_type == "all":
                jobs = vault.jobs.all()
            elif job_type == "in_progress":
                jobs = vault.jobs_in_progress.all()
            elif job_type == "completed":
                jobs = vault.completed_jobs.all()
            elif job_type == "succeeded":
                jobs = vault.succeeded_jobs.all()
            elif job_type == "failed":
                jobs = vault.failed_jobs.all()
            else:
                jobs = []
                logger.warning("%s isn't a type of job I can get.", job_type)
            for job in jobs:
                job_list.append(job)
                logger.info("Got %s %s job %s.", job_type, job.action, job.id)
        except ClientError:
            logger.exception("Couldn't get %s jobs from %s.", job_type, vault.name)
            raise
        else:
            return job_list


    def set_notifications(self, vault, sns_topic_arn):
        """
        Sets an Amazon Simple Notification Service (Amazon SNS) topic as a target
        for notifications. Amazon S3 Glacier publishes messages to this topic for
        the configured list of events.

        :param vault: The vault to set up to publish notifications.
        :param sns_topic_arn: The Amazon Resource Name (ARN) of the topic that
                              receives notifications.
        :return: Data about the new notification configuration.
        """
        try:
            notification = self.glacier_resource.Notification("-", vault.name)
            notification.set(
                vaultNotificationConfig={
                    "SNSTopic": sns_topic_arn,
                    "Events": [
                        "ArchiveRetrievalCompleted",
                        "InventoryRetrievalCompleted",
                    ],
                }
            )
            logger.info(
                "Notifications will be sent to %s for events %s from %s.",
                notification.sns_topic,
                notification.events,
                notification.vault_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't set notifications to %s on %s.", sns_topic_arn, vault.name
            )
            raise
        else:
            return notification
```
ラッパークラスの関数を呼び出して、ボールトを作成してファイルをアップロードし、通知を公開し、アーカイブを取得するジョブを開始するようにボールトを設定します。  

```
def upload_demo(glacier, vault_name, topic_arn):
    """
    Shows how to:
    * Create a vault.
    * Configure the vault to publish notifications to an Amazon SNS topic.
    * Upload an archive.
    * Start a job to retrieve the archive.

    :param glacier: A Boto3 Amazon S3 Glacier resource.
    :param vault_name: The name of the vault to create.
    :param topic_arn: The ARN of an Amazon SNS topic that receives notification of
                      Amazon S3 Glacier events.
    """
    print(f"\nCreating vault {vault_name}.")
    vault = glacier.create_vault(vault_name)
    print("\nList of vaults in your account:")
    glacier.list_vaults()
    print(f"\nUploading glacier_basics.py to {vault.name}.")
    with open("glacier_basics.py", "rb") as upload_file:
        archive = glacier.upload_archive(vault, "glacier_basics.py", upload_file)
    print(
        "\nStarting an archive retrieval request to get the file back from the "
        "vault."
    )
    glacier.initiate_archive_retrieval(archive)
    print("\nListing in progress jobs:")
    glacier.list_jobs(vault, "in_progress")
    print(
        "\nBecause Amazon S3 Glacier is intended for infrequent retrieval, an "
        "archive request with Standard retrieval typically completes within 3–5 "
        "hours."
    )
    if topic_arn:
        notification = glacier.set_notifications(vault, topic_arn)
        print(
            f"\nVault {vault.name} is configured to notify the "
            f"{notification.sns_topic} topic when {notification.events} "
            f"events occur. You can subscribe to this topic to receive "
            f"a message when the archive retrieval completes.\n"
        )
    else:
        print(
            f"\nVault {vault.name} is not configured to notify an Amazon SNS topic "
            f"when the archive retrieval completes so wait a few hours."
        )
    print("\nRetrieve your job output by running this script with the --retrieve flag.")
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateVault](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/CreateVault)
  + [InitiateJob](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/InitiateJob)
  + [ListJobs](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/ListJobs)
  + [ListVaults](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/ListVaults)
  + [SetVaultNotifications](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/SetVaultNotifications)
  + [UploadArchive](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/UploadArchive)

### アーカイブコンテンツの取得とアーカイブの削除
<a name="glacier_Usage_RetrieveDelete_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Glacier ボールトのジョブをリストし、ジョブのステータスを取得します。
+ 完了したアーカイブの取得ジョブの出力を取得します。
+ アーカイブを削除します。
+ ボールトを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glacier#code-examples)での設定と実行の方法を確認してください。
Amazon Glacier オペレーションをラップするクラスを作成します。  

```
import argparse
import logging
import os
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class GlacierWrapper:
    """Encapsulates Amazon S3 Glacier API operations."""

    def __init__(self, glacier_resource):
        """
        :param glacier_resource: A Boto3 Amazon S3 Glacier resource.
        """
        self.glacier_resource = glacier_resource


    @staticmethod
    def list_jobs(vault, job_type):
        """
        Lists jobs by type for the specified vault.

        :param vault: The vault to query.
        :param job_type: The type of job to list.
        :return: The list of jobs of the requested type.
        """
        job_list = []
        try:
            if job_type == "all":
                jobs = vault.jobs.all()
            elif job_type == "in_progress":
                jobs = vault.jobs_in_progress.all()
            elif job_type == "completed":
                jobs = vault.completed_jobs.all()
            elif job_type == "succeeded":
                jobs = vault.succeeded_jobs.all()
            elif job_type == "failed":
                jobs = vault.failed_jobs.all()
            else:
                jobs = []
                logger.warning("%s isn't a type of job I can get.", job_type)
            for job in jobs:
                job_list.append(job)
                logger.info("Got %s %s job %s.", job_type, job.action, job.id)
        except ClientError:
            logger.exception("Couldn't get %s jobs from %s.", job_type, vault.name)
            raise
        else:
            return job_list


    @staticmethod
    def get_job_output(job):
        """
        Gets the output of a job, such as a vault inventory or the contents of an
        archive.

        :param job: The job to get output from.
        :return: The job output, in bytes.
        """
        try:
            response = job.get_output()
            out_bytes = response["body"].read()
            logger.info("Read %s bytes from job %s.", len(out_bytes), job.id)
            if "archiveDescription" in response:
                logger.info(
                    "These bytes are described as '%s'", response["archiveDescription"]
                )
        except ClientError:
            logger.exception("Couldn't get output for job %s.", job.id)
            raise
        else:
            return out_bytes


    @staticmethod
    def delete_archive(archive):
        """
        Deletes an archive from a vault.

        :param archive: The archive to delete.
        """
        try:
            archive.delete()
            logger.info(
                "Deleted archive %s from vault %s.", archive.id, archive.vault_name
            )
        except ClientError:
            logger.exception("Couldn't delete archive %s.", archive.id)
            raise


    @staticmethod
    def delete_vault(vault):
        """
        Deletes a vault.

        :param vault: The vault to delete.
        """
        try:
            vault.delete()
            logger.info("Deleted vault %s.", vault.name)
        except ClientError:
            logger.exception("Couldn't delete vault %s.", vault.name)
            raise
```
Wrapper クラスの関数を呼び出して、完了したジョブからアーカイブコンテンツを取得し、アーカイブを削除します。  

```
def retrieve_demo(glacier, vault_name):
    """
    Shows how to:
    * List jobs for a vault and get job status.
    * Get the output of a completed archive retrieval job.
    * Delete an archive.
    * Delete a vault.

    :param glacier: A Boto3 Amazon S3 Glacier resource.
    :param vault_name: The name of the vault to query for jobs.
    """
    vault = glacier.glacier_resource.Vault("-", vault_name)
    try:
        vault.load()
    except ClientError as err:
        if err.response["Error"]["Code"] == "ResourceNotFoundException":
            print(
                f"\nVault {vault_name} doesn't exist. You must first run this script "
                f"with the --upload flag to create the vault."
            )
            return
        else:
            raise

    print(f"\nGetting completed jobs for {vault.name}.")
    jobs = glacier.list_jobs(vault, "completed")
    if not jobs:
        print("\nNo completed jobs found. Give it some time and try again later.")
        return

    retrieval_job = None
    for job in jobs:
        if job.action == "ArchiveRetrieval" and job.status_code == "Succeeded":
            retrieval_job = job
            break
    if retrieval_job is None:
        print(
            "\nNo ArchiveRetrieval jobs found. Give it some time and try again "
            "later."
        )
        return

    print(f"\nGetting output from job {retrieval_job.id}.")
    archive_bytes = glacier.get_job_output(retrieval_job)
    archive_str = archive_bytes.decode("utf-8")
    print("\nGot archive data. Printing the first 10 lines.")
    print(os.linesep.join(archive_str.split(os.linesep)[:10]))

    print(f"\nDeleting the archive from {vault.name}.")
    archive = glacier.glacier_resource.Archive(
        "-", vault.name, retrieval_job.archive_id
    )
    glacier.delete_archive(archive)

    print(f"\nDeleting {vault.name}.")
    glacier.delete_vault(vault)
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [DeleteArchive](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/DeleteArchive)
  + [DeleteVault](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/DeleteVault)
  + [GetJobOutput](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/GetJobOutput)
  + [ListJobs](https://docs.aws.amazon.com/goto/boto3/glacier-2012-06-01/ListJobs)

# AWS Glue SDK for Python (Boto3) を使用した例
<a name="python_3_glue_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Glueは
<a name="glue_Hello_python_3_topic"></a>

次のコード例は、 AWS Glueの使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import boto3
from botocore.exceptions import ClientError


def hello_glue():
    """
    Lists the job definitions in your AWS Glue account, using the AWS SDK for Python (Boto3).
    """
    try:
        # Create the Glue client
        glue = boto3.client("glue")

        # List the jobs, limiting the results to 10 per page
        paginator = glue.get_paginator("get_jobs")
        response_iterator = paginator.paginate(
            PaginationConfig={"MaxItems": 10, "PageSize": 10}
        )

        # Print the job names
        print("Here are the jobs in your account:")
        for page in response_iterator:
            for job in page["Jobs"]:
                print(f"\t{job['Name']}")

    except ClientError as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    hello_glue()
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[ListJobs](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/ListJobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。
シナリオで使用される AWS Glue 関数をラップするクラスを作成します。  

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def get_crawler(self, name):
        """
        Gets information about a crawler.

        :param name: The name of the crawler to look up.
        :return: Data about the crawler.
        """
        crawler = None
        try:
            response = self.glue_client.get_crawler(Name=name)
            crawler = response["Crawler"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityNotFoundException":
                logger.info("Crawler %s doesn't exist.", name)
            else:
                logger.error(
                    "Couldn't get crawler %s. Here's why: %s: %s",
                    name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return crawler


    def create_crawler(self, name, role_arn, db_name, db_prefix, s3_target):
        """
        Creates a crawler that can crawl the specified target and populate a
        database in your AWS Glue Data Catalog with metadata that describes the data
        in the target.

        :param name: The name of the crawler.
        :param role_arn: The Amazon Resource Name (ARN) of an AWS Identity and Access
                         Management (IAM) role that grants permission to let AWS Glue
                         access the resources it needs.
        :param db_name: The name to give the database that is created by the crawler.
        :param db_prefix: The prefix to give any database tables that are created by
                          the crawler.
        :param s3_target: The URL to an S3 bucket that contains data that is
                          the target of the crawler.
        """
        try:
            self.glue_client.create_crawler(
                Name=name,
                Role=role_arn,
                DatabaseName=db_name,
                TablePrefix=db_prefix,
                Targets={"S3Targets": [{"Path": s3_target}]},
            )
        except ClientError as err:
            logger.error(
                "Couldn't create crawler. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def start_crawler(self, name):
        """
        Starts a crawler. The crawler crawls its configured target and creates
        metadata that describes the data it finds in the target data source.

        :param name: The name of the crawler to start.
        """
        try:
            self.glue_client.start_crawler(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't start crawler %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def get_database(self, name):
        """
        Gets information about a database in your Data Catalog.

        :param name: The name of the database to look up.
        :return: Information about the database.
        """
        try:
            response = self.glue_client.get_database(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't get database %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Database"]


    def get_tables(self, db_name):
        """
        Gets a list of tables in a Data Catalog database.

        :param db_name: The name of the database to query.
        :return: The list of tables in the database.
        """
        try:
            response = self.glue_client.get_tables(DatabaseName=db_name)
        except ClientError as err:
            logger.error(
                "Couldn't get tables %s. Here's why: %s: %s",
                db_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["TableList"]


    def create_job(self, name, description, role_arn, script_location):
        """
        Creates a job definition for an extract, transform, and load (ETL) job that can
        be run by AWS Glue.

        :param name: The name of the job definition.
        :param description: The description of the job definition.
        :param role_arn: The ARN of an IAM role that grants AWS Glue the permissions
                         it requires to run the job.
        :param script_location: The Amazon S3 URL of a Python ETL script that is run as
                                part of the job. The script defines how the data is
                                transformed.
        """
        try:
            self.glue_client.create_job(
                Name=name,
                Description=description,
                Role=role_arn,
                Command={
                    "Name": "glueetl",
                    "ScriptLocation": script_location,
                    "PythonVersion": "3",
                },
                GlueVersion="3.0",
            )
        except ClientError as err:
            logger.error(
                "Couldn't create job %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def start_job_run(self, name, input_database, input_table, output_bucket_name):
        """
        Starts a job run. A job run extracts data from the source, transforms it,
        and loads it to the output bucket.

        :param name: The name of the job definition.
        :param input_database: The name of the metadata database that contains tables
                               that describe the source data. This is typically created
                               by a crawler.
        :param input_table: The name of the table in the metadata database that
                            describes the source data.
        :param output_bucket_name: The S3 bucket where the output is written.
        :return: The ID of the job run.
        """
        try:
            # The custom Arguments that are passed to this function are used by the
            # Python ETL script to determine the location of input and output data.
            response = self.glue_client.start_job_run(
                JobName=name,
                Arguments={
                    "--input_database": input_database,
                    "--input_table": input_table,
                    "--output_bucket_url": f"s3://{output_bucket_name}/",
                },
            )
        except ClientError as err:
            logger.error(
                "Couldn't start job run %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobRunId"]


    def list_jobs(self):
        """
        Lists the names of job definitions in your account.

        :return: The list of job definition names.
        """
        try:
            response = self.glue_client.list_jobs()
        except ClientError as err:
            logger.error(
                "Couldn't list jobs. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobNames"]


    def get_job_runs(self, job_name):
        """
        Gets information about runs that have been performed for a specific job
        definition.

        :param job_name: The name of the job definition to look up.
        :return: The list of job runs.
        """
        try:
            response = self.glue_client.get_job_runs(JobName=job_name)
        except ClientError as err:
            logger.error(
                "Couldn't get job runs for %s. Here's why: %s: %s",
                job_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobRuns"]


    def get_job_run(self, name, run_id):
        """
        Gets information about a single job run.

        :param name: The name of the job definition for the run.
        :param run_id: The ID of the run.
        :return: Information about the run.
        """
        try:
            response = self.glue_client.get_job_run(JobName=name, RunId=run_id)
        except ClientError as err:
            logger.error(
                "Couldn't get job run %s/%s. Here's why: %s: %s",
                name,
                run_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobRun"]


    def delete_job(self, job_name):
        """
        Deletes a job definition. This also deletes data about all runs that are
        associated with this job definition.

        :param job_name: The name of the job definition to delete.
        """
        try:
            self.glue_client.delete_job(JobName=job_name)
        except ClientError as err:
            logger.error(
                "Couldn't delete job %s. Here's why: %s: %s",
                job_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_table(self, db_name, table_name):
        """
        Deletes a table from a metadata database.

        :param db_name: The name of the database that contains the table.
        :param table_name: The name of the table to delete.
        """
        try:
            self.glue_client.delete_table(DatabaseName=db_name, Name=table_name)
        except ClientError as err:
            logger.error(
                "Couldn't delete table %s. Here's why: %s: %s",
                table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_database(self, name):
        """
        Deletes a metadata database from your Data Catalog.

        :param name: The name of the database to delete.
        """
        try:
            self.glue_client.delete_database(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't delete database %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_crawler(self, name):
        """
        Deletes a crawler.

        :param name: The name of the crawler to delete.
        """
        try:
            self.glue_client.delete_crawler(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't delete crawler %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
シナリオを実行するクラスを作成します。  

```
class GlueCrawlerJobScenario:
    """
    Encapsulates a scenario that shows how to create an AWS Glue crawler and job and use
    them to transform data from CSV to JSON format.
    """

    def __init__(self, glue_client, glue_service_role, glue_bucket):
        """
        :param glue_client: A Boto3 AWS Glue client.
        :param glue_service_role: An AWS Identity and Access Management (IAM) role
                                  that AWS Glue can assume to gain access to the
                                  resources it requires.
        :param glue_bucket: An S3 bucket that can hold a job script and output data
                            from AWS Glue job runs.
        """
        self.glue_client = glue_client
        self.glue_service_role = glue_service_role
        self.glue_bucket = glue_bucket

    @staticmethod
    def wait(seconds, tick=12):
        """
        Waits for a specified number of seconds, while also displaying an animated
        spinner.

        :param seconds: The number of seconds to wait.
        :param tick: The number of frames per second used to animate the spinner.
        """
        progress = "|/-\\"
        waited = 0
        while waited < seconds:
            for frame in range(tick):
                sys.stdout.write(f"\r{progress[frame % len(progress)]}")
                sys.stdout.flush()
                time.sleep(1 / tick)
            waited += 1

    def upload_job_script(self, job_script):
        """
        Uploads a Python ETL script to an S3 bucket. The script is used by the AWS Glue
        job to transform data.

        :param job_script: The relative path to the job script.
        """
        try:
            self.glue_bucket.upload_file(Filename=job_script, Key=job_script)
            print(f"Uploaded job script '{job_script}' to the example bucket.")
        except S3UploadFailedError as err:
            logger.error("Couldn't upload job script. Here's why: %s", err)
            raise

    def run(self, crawler_name, db_name, db_prefix, data_source, job_script, job_name):
        """
        Runs the scenario. This is an interactive experience that runs at a command
        prompt and asks you for input throughout.

        :param crawler_name: The name of the crawler used in the scenario. If the
                             crawler does not exist, it is created.
        :param db_name: The name to give the metadata database created by the crawler.
        :param db_prefix: The prefix to give tables added to the database by the
                          crawler.
        :param data_source: The location of the data source that is targeted by the
                            crawler and extracted during job runs.
        :param job_script: The job script that is used to transform data during job
                           runs.
        :param job_name: The name to give the job definition that is created during the
                         scenario.
        """
        wrapper = GlueWrapper(self.glue_client)
        print(f"Checking for crawler {crawler_name}.")
        crawler = wrapper.get_crawler(crawler_name)
        if crawler is None:
            print(f"Creating crawler {crawler_name}.")
            wrapper.create_crawler(
                crawler_name,
                self.glue_service_role.arn,
                db_name,
                db_prefix,
                data_source,
            )
            print(f"Created crawler {crawler_name}.")
            crawler = wrapper.get_crawler(crawler_name)
        pprint(crawler)
        print("-" * 88)

        print(
            f"When you run the crawler, it crawls data stored in {data_source} and "
            f"creates a metadata database in the AWS Glue Data Catalog that describes "
            f"the data in the data source."
        )
        print("In this example, the source data is in CSV format.")
        ready = False
        while not ready:
            ready = Question.ask_question(
                "Ready to start the crawler? (y/n) ", Question.is_yesno
            )
        wrapper.start_crawler(crawler_name)
        print("Let's wait for the crawler to run. This typically takes a few minutes.")
        crawler_state = None
        while crawler_state != "READY":
            self.wait(10)
            crawler = wrapper.get_crawler(crawler_name)
            crawler_state = crawler["State"]
            print(f"Crawler is {crawler['State']}.")
        print("-" * 88)

        database = wrapper.get_database(db_name)
        print(f"The crawler created database {db_name}:")
        pprint(database)
        print(f"The database contains these tables:")
        tables = wrapper.get_tables(db_name)
        for index, table in enumerate(tables):
            print(f"\t{index + 1}. {table['Name']}")
        table_index = Question.ask_question(
            f"Enter the number of a table to see more detail: ",
            Question.is_int,
            Question.in_range(1, len(tables)),
        )
        pprint(tables[table_index - 1])
        print("-" * 88)

        print(f"Creating job definition {job_name}.")
        wrapper.create_job(
            job_name,
            "Getting started example job.",
            self.glue_service_role.arn,
            f"s3://{self.glue_bucket.name}/{job_script}",
        )
        print("Created job definition.")
        print(
            f"When you run the job, it extracts data from {data_source}, transforms it "
            f"by using the {job_script} script, and loads the output into "
            f"S3 bucket {self.glue_bucket.name}."
        )
        print(
            "In this example, the data is transformed from CSV to JSON, and only a few "
            "fields are included in the output."
        )
        job_run_status = None
        if Question.ask_question(f"Ready to run? (y/n) ", Question.is_yesno):
            job_run_id = wrapper.start_job_run(
                job_name, db_name, tables[0]["Name"], self.glue_bucket.name
            )
            print(f"Job {job_name} started. Let's wait for it to run.")
            while job_run_status not in ["SUCCEEDED", "STOPPED", "FAILED", "TIMEOUT"]:
                self.wait(10)
                job_run = wrapper.get_job_run(job_name, job_run_id)
                job_run_status = job_run["JobRunState"]
                print(f"Job {job_name}/{job_run_id} is {job_run_status}.")
        print("-" * 88)

        if job_run_status == "SUCCEEDED":
            print(
                f"Data from your job run is stored in your S3 bucket '{self.glue_bucket.name}':"
            )
            try:
                keys = [
                    obj.key for obj in self.glue_bucket.objects.filter(Prefix="run-")
                ]
                for index, key in enumerate(keys):
                    print(f"\t{index + 1}: {key}")
                lines = 4
                key_index = Question.ask_question(
                    f"Enter the number of a block to download it and see the first {lines} "
                    f"lines of JSON output in the block: ",
                    Question.is_int,
                    Question.in_range(1, len(keys)),
                )
                job_data = io.BytesIO()
                self.glue_bucket.download_fileobj(keys[key_index - 1], job_data)
                job_data.seek(0)
                for _ in range(lines):
                    print(job_data.readline().decode("utf-8"))
            except ClientError as err:
                logger.error(
                    "Couldn't get job run data. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
            print("-" * 88)

        job_names = wrapper.list_jobs()
        if job_names:
            print(f"Your account has {len(job_names)} jobs defined:")
            for index, job_name in enumerate(job_names):
                print(f"\t{index + 1}. {job_name}")
            job_index = Question.ask_question(
                f"Enter a number between 1 and {len(job_names)} to see the list of runs for "
                f"a job: ",
                Question.is_int,
                Question.in_range(1, len(job_names)),
            )
            job_runs = wrapper.get_job_runs(job_names[job_index - 1])
            if job_runs:
                print(f"Found {len(job_runs)} runs for job {job_names[job_index - 1]}:")
                for index, job_run in enumerate(job_runs):
                    print(
                        f"\t{index + 1}. {job_run['JobRunState']} on "
                        f"{job_run['CompletedOn']:%Y-%m-%d %H:%M:%S}"
                    )
                run_index = Question.ask_question(
                    f"Enter a number between 1 and {len(job_runs)} to see details for a run: ",
                    Question.is_int,
                    Question.in_range(1, len(job_runs)),
                )
                pprint(job_runs[run_index - 1])
            else:
                print(f"No runs found for job {job_names[job_index - 1]}")
        else:
            print("Your account doesn't have any jobs defined.")
        print("-" * 88)

        print(
            f"Let's clean up. During this example we created job definition '{job_name}'."
        )
        if Question.ask_question(
            "Do you want to delete the definition and all runs? (y/n) ",
            Question.is_yesno,
        ):
            wrapper.delete_job(job_name)
            print(f"Job definition '{job_name}' deleted.")
        tables = wrapper.get_tables(db_name)
        print(f"We also created database '{db_name}' that contains these tables:")
        for table in tables:
            print(f"\t{table['Name']}")
        if Question.ask_question(
            "Do you want to delete the tables and the database? (y/n) ",
            Question.is_yesno,
        ):
            for table in tables:
                wrapper.delete_table(db_name, table["Name"])
                print(f"Deleted table {table['Name']}.")
            wrapper.delete_database(db_name)
            print(f"Deleted database {db_name}.")
        print(f"We also created crawler '{crawler_name}'.")
        if Question.ask_question(
            "Do you want to delete the crawler? (y/n) ", Question.is_yesno
        ):
            wrapper.delete_crawler(crawler_name)
            print(f"Deleted crawler {crawler_name}.")
        print("-" * 88)


def parse_args(args):
    """
    Parse command line arguments.

    :param args: The command line arguments.
    :return: The parsed arguments.
    """
    parser = argparse.ArgumentParser(
        description="Runs the AWS Glue getting started with crawlers and jobs scenario. "
        "Before you run this scenario, set up scaffold resources by running "
        "'python scaffold.py deploy'."
    )
    parser.add_argument(
        "role_name",
        help="The name of an IAM role that AWS Glue can assume. This role must grant access "
        "to Amazon S3 and to the permissions granted by the AWSGlueServiceRole "
        "managed policy.",
    )
    parser.add_argument(
        "bucket_name",
        help="The name of an S3 bucket that AWS Glue can access to get the job script and "
        "put job results.",
    )
    parser.add_argument(
        "--job_script",
        default="flight_etl_job_script.py",
        help="The name of the job script file that is used in the scenario.",
    )
    return parser.parse_args(args)


def main():
    args = parse_args(sys.argv[1:])
    try:
        print("-" * 88)
        print(
            "Welcome to the AWS Glue getting started with crawlers and jobs scenario."
        )
        print("-" * 88)
        scenario = GlueCrawlerJobScenario(
            boto3.client("glue"),
            boto3.resource("iam").Role(args.role_name),
            boto3.resource("s3").Bucket(args.bucket_name),
        )
        scenario.upload_job_script(args.job_script)
        scenario.run(
            "doc-example-crawler",
            "doc-example-database",
            "doc-example-",
            "s3://crawler-public-us-east-1/flight/2016/csv",
            args.job_script,
            "doc-example-job",
        )
        print("-" * 88)
        print(
            "To destroy scaffold resources, including the IAM role and S3 bucket "
            "used in this scenario, run 'python scaffold.py destroy'."
        )
        print("\nThanks for watching!")
        print("-" * 88)
    except Exception:
        logging.exception("Something went wrong with the example.")
```
ジョブの実行中にデータを抽出、変換、ロード AWS Glue するために で使用される ETL スクリプトを作成します。  

```
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

"""
These custom arguments must be passed as Arguments to the StartJobRun request.
    --input_database    The name of a metadata database that is contained in your 
                        AWS Glue Data Catalog and that contains tables that describe 
                        the data to be processed.
    --input_table       The name of a table in the database that describes the data to
                        be processed.
    --output_bucket_url An S3 bucket that receives the transformed output data.  
"""
args = getResolvedOptions(
    sys.argv, ["JOB_NAME", "input_database", "input_table", "output_bucket_url"]
)
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args["JOB_NAME"], args)

# Script generated for node S3 Flight Data.
S3FlightData_node1 = glueContext.create_dynamic_frame.from_catalog(
    database=args["input_database"],
    table_name=args["input_table"],
    transformation_ctx="S3FlightData_node1",
)

# This mapping performs two main functions:
# 1. It simplifies the output by removing most of the fields from the data.
# 2. It renames some fields. For example, `fl_date` is renamed to `flight_date`.
ApplyMapping_node2 = ApplyMapping.apply(
    frame=S3FlightData_node1,
    mappings=[
        ("year", "long", "year", "long"),
        ("month", "long", "month", "tinyint"),
        ("day_of_month", "long", "day", "tinyint"),
        ("fl_date", "string", "flight_date", "string"),
        ("carrier", "string", "carrier", "string"),
        ("fl_num", "long", "flight_num", "long"),
        ("origin_city_name", "string", "origin_city_name", "string"),
        ("origin_state_abr", "string", "origin_state_abr", "string"),
        ("dest_city_name", "string", "dest_city_name", "string"),
        ("dest_state_abr", "string", "dest_state_abr", "string"),
        ("dep_time", "long", "departure_time", "long"),
        ("wheels_off", "long", "wheels_off", "long"),
        ("wheels_on", "long", "wheels_on", "long"),
        ("arr_time", "long", "arrival_time", "long"),
        ("mon", "string", "mon", "string"),
    ],
    transformation_ctx="ApplyMapping_node2",
)

# Script generated for node Revised Flight Data.
RevisedFlightData_node3 = glueContext.write_dynamic_frame.from_options(
    frame=ApplyMapping_node2,
    connection_type="s3",
    format="json",
    connection_options={"path": args["output_bucket_url"], "partitionKeys": []},
    transformation_ctx="RevisedFlightData_node3",
)

job.commit()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/CreateCrawler)
  + [CreateJob](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/CreateJob)
  + [DeleteCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteCrawler)
  + [DeleteDatabase](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteDatabase)
  + [DeleteJob](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteJob)
  + [DeleteTable](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteTable)
  + [GetCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetCrawler)
  + [GetDatabase](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetDatabase)
  + [GetDatabases](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetDatabases)
  + [GetJob](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetJob)
  + [GetJobRun](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetJobRun)
  + [GetJobRuns](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetJobRuns)
  + [GetTables](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetTables)
  + [ListJobs](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/ListJobs)
  + [StartCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/StartCrawler)
  + [StartJobRun](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/StartJobRun)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_python_3_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def create_crawler(self, name, role_arn, db_name, db_prefix, s3_target):
        """
        Creates a crawler that can crawl the specified target and populate a
        database in your AWS Glue Data Catalog with metadata that describes the data
        in the target.

        :param name: The name of the crawler.
        :param role_arn: The Amazon Resource Name (ARN) of an AWS Identity and Access
                         Management (IAM) role that grants permission to let AWS Glue
                         access the resources it needs.
        :param db_name: The name to give the database that is created by the crawler.
        :param db_prefix: The prefix to give any database tables that are created by
                          the crawler.
        :param s3_target: The URL to an S3 bucket that contains data that is
                          the target of the crawler.
        """
        try:
            self.glue_client.create_crawler(
                Name=name,
                Role=role_arn,
                DatabaseName=db_name,
                TablePrefix=db_prefix,
                Targets={"S3Targets": [{"Path": s3_target}]},
            )
        except ClientError as err:
            logger.error(
                "Couldn't create crawler. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[CreateCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/CreateCrawler)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_python_3_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def create_job(self, name, description, role_arn, script_location):
        """
        Creates a job definition for an extract, transform, and load (ETL) job that can
        be run by AWS Glue.

        :param name: The name of the job definition.
        :param description: The description of the job definition.
        :param role_arn: The ARN of an IAM role that grants AWS Glue the permissions
                         it requires to run the job.
        :param script_location: The Amazon S3 URL of a Python ETL script that is run as
                                part of the job. The script defines how the data is
                                transformed.
        """
        try:
            self.glue_client.create_job(
                Name=name,
                Description=description,
                Role=role_arn,
                Command={
                    "Name": "glueetl",
                    "ScriptLocation": script_location,
                    "PythonVersion": "3",
                },
                GlueVersion="3.0",
            )
        except ClientError as err:
            logger.error(
                "Couldn't create job %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[CreateJob](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/CreateJob)」を参照してください。

### `DeleteCrawler`
<a name="glue_DeleteCrawler_python_3_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def delete_crawler(self, name):
        """
        Deletes a crawler.

        :param name: The name of the crawler to delete.
        """
        try:
            self.glue_client.delete_crawler(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't delete crawler %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[DeleteCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteCrawler)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_python_3_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def delete_database(self, name):
        """
        Deletes a metadata database from your Data Catalog.

        :param name: The name of the database to delete.
        """
        try:
            self.glue_client.delete_database(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't delete database %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* で「[DeleteDatabase](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteDatabase)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_python_3_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def delete_job(self, job_name):
        """
        Deletes a job definition. This also deletes data about all runs that are
        associated with this job definition.

        :param job_name: The name of the job definition to delete.
        """
        try:
            self.glue_client.delete_job(JobName=job_name)
        except ClientError as err:
            logger.error(
                "Couldn't delete job %s. Here's why: %s: %s",
                job_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[DeleteJob](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteJob)」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_python_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def delete_table(self, db_name, table_name):
        """
        Deletes a table from a metadata database.

        :param db_name: The name of the database that contains the table.
        :param table_name: The name of the table to delete.
        """
        try:
            self.glue_client.delete_table(DatabaseName=db_name, Name=table_name)
        except ClientError as err:
            logger.error(
                "Couldn't delete table %s. Here's why: %s: %s",
                table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[DeleteTable](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/DeleteTable)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_python_3_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def get_crawler(self, name):
        """
        Gets information about a crawler.

        :param name: The name of the crawler to look up.
        :return: Data about the crawler.
        """
        crawler = None
        try:
            response = self.glue_client.get_crawler(Name=name)
            crawler = response["Crawler"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityNotFoundException":
                logger.info("Crawler %s doesn't exist.", name)
            else:
                logger.error(
                    "Couldn't get crawler %s. Here's why: %s: %s",
                    name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return crawler
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[GetCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetCrawler)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_python_3_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def get_database(self, name):
        """
        Gets information about a database in your Data Catalog.

        :param name: The name of the database to look up.
        :return: Information about the database.
        """
        try:
            response = self.glue_client.get_database(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't get database %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["Database"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[GetDatabase](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetDatabase)」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_python_3_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def get_job_run(self, name, run_id):
        """
        Gets information about a single job run.

        :param name: The name of the job definition for the run.
        :param run_id: The ID of the run.
        :return: Information about the run.
        """
        try:
            response = self.glue_client.get_job_run(JobName=name, RunId=run_id)
        except ClientError as err:
            logger.error(
                "Couldn't get job run %s/%s. Here's why: %s: %s",
                name,
                run_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobRun"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[GetJobRun](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetJobRun)」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_python_3_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def get_job_runs(self, job_name):
        """
        Gets information about runs that have been performed for a specific job
        definition.

        :param job_name: The name of the job definition to look up.
        :return: The list of job runs.
        """
        try:
            response = self.glue_client.get_job_runs(JobName=job_name)
        except ClientError as err:
            logger.error(
                "Couldn't get job runs for %s. Here's why: %s: %s",
                job_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobRuns"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[GetJobRuns](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetJobRuns)」を参照してください。

### `GetTables`
<a name="glue_GetTables_python_3_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def get_tables(self, db_name):
        """
        Gets a list of tables in a Data Catalog database.

        :param db_name: The name of the database to query.
        :return: The list of tables in the database.
        """
        try:
            response = self.glue_client.get_tables(DatabaseName=db_name)
        except ClientError as err:
            logger.error(
                "Couldn't get tables %s. Here's why: %s: %s",
                db_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["TableList"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[GetTables](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/GetTables)」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_python_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def list_jobs(self):
        """
        Lists the names of job definitions in your account.

        :return: The list of job definition names.
        """
        try:
            response = self.glue_client.list_jobs()
        except ClientError as err:
            logger.error(
                "Couldn't list jobs. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobNames"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[ListJobs](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/ListJobs)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_python_3_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def start_crawler(self, name):
        """
        Starts a crawler. The crawler crawls its configured target and creates
        metadata that describes the data it finds in the target data source.

        :param name: The name of the crawler to start.
        """
        try:
            self.glue_client.start_crawler(Name=name)
        except ClientError as err:
            logger.error(
                "Couldn't start crawler %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[StartCrawler](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/StartCrawler)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_python_3_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
class GlueWrapper:
    """Encapsulates AWS Glue actions."""

    def __init__(self, glue_client):
        """
        :param glue_client: A Boto3 Glue client.
        """
        self.glue_client = glue_client


    def start_job_run(self, name, input_database, input_table, output_bucket_name):
        """
        Starts a job run. A job run extracts data from the source, transforms it,
        and loads it to the output bucket.

        :param name: The name of the job definition.
        :param input_database: The name of the metadata database that contains tables
                               that describe the source data. This is typically created
                               by a crawler.
        :param input_table: The name of the table in the metadata database that
                            describes the source data.
        :param output_bucket_name: The S3 bucket where the output is written.
        :return: The ID of the job run.
        """
        try:
            # The custom Arguments that are passed to this function are used by the
            # Python ETL script to determine the location of input and output data.
            response = self.glue_client.start_job_run(
                JobName=name,
                Arguments={
                    "--input_database": input_database,
                    "--input_table": input_table,
                    "--output_bucket_url": f"s3://{output_bucket_name}/",
                },
            )
        except ClientError as err:
            logger.error(
                "Couldn't start job run %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["JobRunId"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[StartJobRun](https://docs.aws.amazon.com/goto/boto3/glue-2017-03-31/StartJobRun)」を参照してください。

# SDK for Python (Boto3) を使用した HealthImaging の例
<a name="python_3_medical-imaging_code_examples"></a>

次のコード例は、HealthImaging AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello HealthImaging
<a name="medical-imaging_Hello_python_3_topic"></a>

次のコード例は、HealthImaging の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def hello_medical_imaging(medical_imaging_client):
    """
    Use the AWS SDK for Python (Boto3) to create an AWS HealthImaging
    client and list the data stores in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param medical_imaging_client: A Boto3 AWS HealthImaging Client object.
    """
    print("Hello, Amazon Health Imaging! Let's list some of your data stores:\n")
    try:
        paginator = medical_imaging_client.get_paginator("list_datastores")
        page_iterator = paginator.paginate()
        datastore_summaries = []
        for page in page_iterator:
            datastore_summaries.extend(page["datastoreSummaries"])
        print("\tData Stores:")
        for ds in datastore_summaries:
            print(f"\t\tDatastore: {ds['datastoreName']} ID {ds['datastoreId']}")
    except ClientError as err:
        logger.error(
            "Couldn't list data stores. Here's why: %s: %s",
            err.response["Error"]["Code"],
            err.response["Error"]["Message"],
        )
        raise


if __name__ == "__main__":
    hello_medical_imaging(boto3.client("medical-imaging"))
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListDatastores](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/ListDatastores)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging/imaging_set_and_frames_workflow#code-examples)での設定と実行の方法を確認してください。

## アクション
<a name="actions"></a>

### `CopyImageSet`
<a name="medical-imaging_CopyImageSet_python_3_topic"></a>

次のコード例は、`CopyImageSet` を使用する方法を示しています。

**SDK for Python (Boto3)**  
イメージセットをコピーするためのユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def copy_image_set(
        self,
        datastore_id,
        image_set_id,
        version_id,
        destination_image_set_id=None,
        destination_version_id=None,
        force=False,
        subsets=[],
    ):
        """
        Copy an image set.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param version_id: The ID of the image set version.
        :param destination_image_set_id: The ID of the optional destination image set.
        :param destination_version_id: The ID of the optional destination image set version.
        :param force: Force the copy.
        :param subsets: The optional subsets to copy. For example: ["12345678901234567890123456789012"].
        :return: The copied image set ID.
        """
        try:
            copy_image_set_information = {
                "sourceImageSet": {"latestVersionId": version_id}
            }
            if destination_image_set_id and destination_version_id:
                copy_image_set_information["destinationImageSet"] = {
                    "imageSetId": destination_image_set_id,
                    "latestVersionId": destination_version_id,
                }
            if len(subsets) > 0:
                copySubsetsJson = {
                    "SchemaVersion": "1.1",
                    "Study": {"Series": {"imageSetId": {"Instances": {}}}},
                }

                for subset in subsets:
                    copySubsetsJson["Study"]["Series"]["imageSetId"]["Instances"][
                        subset
                    ] = {}

                copy_image_set_information["sourceImageSet"]["DICOMCopies"] = {
                    "copiableAttributes": json.dumps(copySubsetsJson)
                }
            copy_results = self.health_imaging_client.copy_image_set(
                datastoreId=datastore_id,
                sourceImageSetId=image_set_id,
                copyImageSetInformation=copy_image_set_information,
                force=force,
            )
        except ClientError as err:
            logger.error(
                "Couldn't copy image set. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return copy_results["destinationImageSetProperties"]["imageSetId"]
```
コピー先を指定せずにイメージセットをコピーします。  

```
            copy_image_set_information = {
                "sourceImageSet": {"latestVersionId": version_id}
            }

            copy_results = self.health_imaging_client.copy_image_set(
                datastoreId=datastore_id,
                sourceImageSetId=image_set_id,
                copyImageSetInformation=copy_image_set_information,
                force=force,
            )
```
コピー先を指定してイメージセットをコピーします。  

```
            copy_image_set_information = {
                "sourceImageSet": {"latestVersionId": version_id}
            }

            if destination_image_set_id and destination_version_id:
                copy_image_set_information["destinationImageSet"] = {
                    "imageSetId": destination_image_set_id,
                    "latestVersionId": destination_version_id,
                }

            copy_results = self.health_imaging_client.copy_image_set(
                datastoreId=datastore_id,
                sourceImageSetId=image_set_id,
                copyImageSetInformation=copy_image_set_information,
                force=force,
            )
```
イメージセットのサブセットをコピーします。  

```
            copy_image_set_information = {
                "sourceImageSet": {"latestVersionId": version_id}
            }

            if len(subsets) > 0:
                copySubsetsJson = {
                    "SchemaVersion": "1.1",
                    "Study": {"Series": {"imageSetId": {"Instances": {}}}},
                }

                for subset in subsets:
                    copySubsetsJson["Study"]["Series"]["imageSetId"]["Instances"][
                        subset
                    ] = {}

                copy_image_set_information["sourceImageSet"]["DICOMCopies"] = {
                    "copiableAttributes": json.dumps(copySubsetsJson)
                }

            copy_results = self.health_imaging_client.copy_image_set(
                datastoreId=datastore_id,
                sourceImageSetId=image_set_id,
                copyImageSetInformation=copy_image_set_information,
                force=force,
            )
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CopyImageSet](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/CopyImageSet)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `CreateDatastore`
<a name="medical-imaging_CreateDatastore_python_3_topic"></a>

次のコード例は、`CreateDatastore` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def create_datastore(self, name):
        """
        Create a data store.

        :param name: The name of the data store to create.
        :return: The data store ID.
        """
        try:
            data_store = self.health_imaging_client.create_datastore(datastoreName=name)
        except ClientError as err:
            logger.error(
                "Couldn't create data store %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return data_store["datastoreId"]
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDatastore](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/CreateDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `DeleteDatastore`
<a name="medical-imaging_DeleteDatastore_python_3_topic"></a>

次のコード例は、`DeleteDatastore` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def delete_datastore(self, datastore_id):
        """
        Delete a data store.

        :param datastore_id: The ID of the data store.
        """
        try:
            self.health_imaging_client.delete_datastore(datastoreId=datastore_id)
        except ClientError as err:
            logger.error(
                "Couldn't delete data store %s. Here's why: %s: %s",
                datastore_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDatastore](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/DeleteDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `DeleteImageSet`
<a name="medical-imaging_DeleteImageSet_python_3_topic"></a>

次のコード例は、`DeleteImageSet` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def delete_image_set(self, datastore_id, image_set_id):
        """
        Delete an image set.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :return: The delete results.
        """
        try:
            delete_results = self.health_imaging_client.delete_image_set(
                imageSetId=image_set_id, datastoreId=datastore_id
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete image set. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return delete_results
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteImageSet](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/DeleteImageSet)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetDICOMImportJob`
<a name="medical-imaging_GetDICOMImportJob_python_3_topic"></a>

次のコード例は、`GetDICOMImportJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def get_dicom_import_job(self, datastore_id, job_id):
        """
        Get the properties of a DICOM import job.

        :param datastore_id: The ID of the data store.
        :param job_id: The ID of the job.
        :return: The job properties.
        """
        try:
            job = self.health_imaging_client.get_dicom_import_job(
                jobId=job_id, datastoreId=datastore_id
            )
        except ClientError as err:
            logger.error(
                "Couldn't get DICOM import job. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return job["jobProperties"]
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetDICOMImportJob](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetDICOMImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetDatastore`
<a name="medical-imaging_GetDatastore_python_3_topic"></a>

次のコード例は、`GetDatastore` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def get_datastore_properties(self, datastore_id):
        """
        Get the properties of a data store.

        :param datastore_id: The ID of the data store.
        :return: The data store properties.
        """
        try:
            data_store = self.health_imaging_client.get_datastore(
                datastoreId=datastore_id
            )
        except ClientError as err:
            logger.error(
                "Couldn't get data store %s. Here's why: %s: %s",
                id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return data_store["datastoreProperties"]
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetDatastore](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageFrame`
<a name="medical-imaging_GetImageFrame_python_3_topic"></a>

次のコード例は、`GetImageFrame` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def get_pixel_data(
        self, file_path_to_write, datastore_id, image_set_id, image_frame_id
    ):
        """
        Get an image frame's pixel data.

        :param file_path_to_write: The path to write the image frame's HTJ2K encoded pixel data.
        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param image_frame_id: The ID of the image frame.
        """
        try:
            image_frame = self.health_imaging_client.get_image_frame(
                datastoreId=datastore_id,
                imageSetId=image_set_id,
                imageFrameInformation={"imageFrameId": image_frame_id},
            )
            with open(file_path_to_write, "wb") as f:
                for chunk in image_frame["imageFrameBlob"].iter_chunks():
                    if chunk:
                        f.write(chunk)
        except ClientError as err:
            logger.error(
                "Couldn't get image frame. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetImageFrame](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetImageFrame)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageSet`
<a name="medical-imaging_GetImageSet_python_3_topic"></a>

次のコード例は、`GetImageSet` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def get_image_set(self, datastore_id, image_set_id, version_id=None):
        """
        Get the properties of an image set.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param version_id: The optional version of the image set.
        :return: The image set properties.
        """
        try:
            if version_id:
                image_set = self.health_imaging_client.get_image_set(
                    imageSetId=image_set_id,
                    datastoreId=datastore_id,
                    versionId=version_id,
                )
            else:
                image_set = self.health_imaging_client.get_image_set(
                    imageSetId=image_set_id, datastoreId=datastore_id
                )
        except ClientError as err:
            logger.error(
                "Couldn't get image set. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return image_set
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetImageSet](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetImageSet)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `GetImageSetMetadata`
<a name="medical-imaging_GetImageSetMetadata_python_3_topic"></a>

次のコード例は、`GetImageSetMetadata` を使用する方法を示しています。

**SDK for Python (Boto3)**  
イメージセットのメタデータを取得するためのユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def get_image_set_metadata(
        self, metadata_file, datastore_id, image_set_id, version_id=None
    ):
        """
        Get the metadata of an image set.

        :param metadata_file: The file to store the JSON gzipped metadata.
        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param version_id: The version of the image set.
        """
        try:
            if version_id:
                image_set_metadata = self.health_imaging_client.get_image_set_metadata(
                    imageSetId=image_set_id,
                    datastoreId=datastore_id,
                    versionId=version_id,
                )
            else:

                image_set_metadata = self.health_imaging_client.get_image_set_metadata(
                    imageSetId=image_set_id, datastoreId=datastore_id
                )
            print(image_set_metadata)
            with open(metadata_file, "wb") as f:
                for chunk in image_set_metadata["imageSetMetadataBlob"].iter_chunks():
                    if chunk:
                        f.write(chunk)

        except ClientError as err:
            logger.error(
                "Couldn't get image metadata. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
イメージセットのメタデータをバージョンなしで取得します。  

```
                image_set_metadata = self.health_imaging_client.get_image_set_metadata(
                    imageSetId=image_set_id, datastoreId=datastore_id
                )
```
イメージセットのメタデータをバージョン付きで取得します。  

```
                image_set_metadata = self.health_imaging_client.get_image_set_metadata(
                    imageSetId=image_set_id,
                    datastoreId=datastore_id,
                    versionId=version_id,
                )
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetImageSetMetadata](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetImageSetMetadata)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListDICOMImportJobs`
<a name="medical-imaging_ListDICOMImportJobs_python_3_topic"></a>

次のコード例は、`ListDICOMImportJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def list_dicom_import_jobs(self, datastore_id):
        """
        List the DICOM import jobs.

        :param datastore_id: The ID of the data store.
        :return: The list of jobs.
        """
        try:
            paginator = self.health_imaging_client.get_paginator(
                "list_dicom_import_jobs"
            )
            page_iterator = paginator.paginate(datastoreId=datastore_id)
            job_summaries = []
            for page in page_iterator:
                job_summaries.extend(page["jobSummaries"])
        except ClientError as err:
            logger.error(
                "Couldn't list DICOM import jobs. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return job_summaries
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListDICOMImportJobs](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/ListDICOMImportJobs)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListDatastores`
<a name="medical-imaging_ListDatastores_python_3_topic"></a>

次のコード例は、`ListDatastores` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def list_datastores(self):
        """
        List the data stores.

        :return: The list of data stores.
        """
        try:
            paginator = self.health_imaging_client.get_paginator("list_datastores")
            page_iterator = paginator.paginate()
            datastore_summaries = []
            for page in page_iterator:
                datastore_summaries.extend(page["datastoreSummaries"])
        except ClientError as err:
            logger.error(
                "Couldn't list data stores. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return datastore_summaries
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListDatastores](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/ListDatastores)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListImageSetVersions`
<a name="medical-imaging_ListImageSetVersions_python_3_topic"></a>

次のコード例は、`ListImageSetVersions` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def list_image_set_versions(self, datastore_id, image_set_id):
        """
        List the image set versions.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :return: The list of image set versions.
        """
        try:
            paginator = self.health_imaging_client.get_paginator(
                "list_image_set_versions"
            )
            page_iterator = paginator.paginate(
                imageSetId=image_set_id, datastoreId=datastore_id
            )
            image_set_properties_list = []
            for page in page_iterator:
                image_set_properties_list.extend(page["imageSetPropertiesList"])
        except ClientError as err:
            logger.error(
                "Couldn't list image set versions. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return image_set_properties_list
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListImageSetVersions](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/ListImageSetVersions)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `ListTagsForResource`
<a name="medical-imaging_ListTagsForResource_python_3_topic"></a>

次のコード例は、`ListTagsForResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def list_tags_for_resource(self, resource_arn):
        """
        List the tags for a resource.

        :param resource_arn: The ARN of the resource.
        :return: The list of tags.
        """
        try:
            tags = self.health_imaging_client.list_tags_for_resource(
                resourceArn=resource_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't list tags for resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return tags["tags"]
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListTagsForResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/ListTagsForResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `SearchImageSets`
<a name="medical-imaging_SearchImageSets_python_3_topic"></a>

次のコード例は、`SearchImageSets` を使用する方法を示しています。

**SDK for Python (Boto3)**  
画像セットを検索するためのユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def search_image_sets(self, datastore_id, search_filter):
        """
        Search for image sets.

        :param datastore_id: The ID of the data store.
        :param search_filter: The search filter.
            For example: {"filters" : [{ "operator": "EQUAL", "values": [{"DICOMPatientId": "3524578"}]}]}.
        :return: The list of image sets.
        """
        try:
            paginator = self.health_imaging_client.get_paginator("search_image_sets")
            page_iterator = paginator.paginate(
                datastoreId=datastore_id, searchCriteria=search_filter
            )
            metadata_summaries = []
            for page in page_iterator:
                metadata_summaries.extend(page["imageSetsMetadataSummaries"])
        except ClientError as err:
            logger.error(
                "Couldn't search image sets. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return metadata_summaries
```
ユースケース \$11: EQUAL 演算子。  

```
        search_filter = {
            "filters": [
                {"operator": "EQUAL", "values": [{"DICOMPatientId": patient_id}]}
            ]
        }

        image_sets = self.search_image_sets(data_store_id, search_filter)
        print(f"Image sets found with EQUAL operator\n{image_sets}")
```
ユースケース \$12: DICOMStudyDate と DICOMStudyTime を使用する BETWEEN 演算子。  

```
        search_filter = {
            "filters": [
                {
                    "operator": "BETWEEN",
                    "values": [
                        {
                            "DICOMStudyDateAndTime": {
                                "DICOMStudyDate": "19900101",
                                "DICOMStudyTime": "000000",
                            }
                        },
                        {
                            "DICOMStudyDateAndTime": {
                                "DICOMStudyDate": "20230101",
                                "DICOMStudyTime": "000000",
                            }
                        },
                    ],
                }
            ]
        }

        image_sets = self.search_image_sets(data_store_id, search_filter)
        print(
            f"Image sets found with BETWEEN operator using DICOMStudyDate and DICOMStudyTime\n{image_sets}"
        )
```
ユースケース \$13: createdAt を使用する BETWEEN 演算子。タイムスタディは以前に永続化されています。  

```
        search_filter = {
            "filters": [
                {
                    "values": [
                        {
                            "createdAt": datetime.datetime(
                                2021, 8, 4, 14, 49, 54, 429000
                            )
                        },
                        {
                            "createdAt": datetime.datetime.now()
                            + datetime.timedelta(days=1)
                        },
                    ],
                    "operator": "BETWEEN",
                }
            ]
        }

        recent_image_sets = self.search_image_sets(data_store_id, search_filter)
        print(
            f"Image sets found with with BETWEEN operator using createdAt\n{recent_image_sets}"
        )
```
ユースケース 4: DICOMSeriesInstanceUID で EQUAL 演算子を使用し、updatedAt で BETWEEN 演算子を使用して、updatedAt フィールドで ASC 順序にレスポンスをソートします。  

```
        search_filter = {
            "filters": [
                {
                    "values": [
                        {
                            "updatedAt": datetime.datetime(
                                2021, 8, 4, 14, 49, 54, 429000
                            )
                        },
                        {
                            "updatedAt": datetime.datetime.now()
                            + datetime.timedelta(days=1)
                        },
                    ],
                    "operator": "BETWEEN",
                },
                {
                    "values": [{"DICOMSeriesInstanceUID": series_instance_uid}],
                    "operator": "EQUAL",
                },
            ],
            "sort": {
                "sortOrder": "ASC",
                "sortField": "updatedAt",
            },
        }

        image_sets = self.search_image_sets(data_store_id, search_filter)
        print(
            "Image sets found with EQUAL operator on DICOMSeriesInstanceUID and BETWEEN on updatedAt and"
        )
        print(f"sort response in ASC order on updatedAt field\n{image_sets}")
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SearchImageSets](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/SearchImageSets)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `StartDICOMImportJob`
<a name="medical-imaging_StartDICOMImportJob_python_3_topic"></a>

次のコード例は、`StartDICOMImportJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def start_dicom_import_job(
        self, job_name, datastore_id, role_arn, input_s3_uri, output_s3_uri
    ):
        """
        Start a DICOM import job.

        :param job_name: The name of the job.
        :param datastore_id: The ID of the data store.
        :param role_arn: The Amazon Resource Name (ARN) of the role to use for the job.
        :param input_s3_uri: The S3 bucket input prefix path containing the DICOM files.
        :param output_s3_uri: The S3 bucket output prefix path for the result.
        :return: The job ID.
        """
        try:
            job = self.health_imaging_client.start_dicom_import_job(
                jobName=job_name,
                datastoreId=datastore_id,
                dataAccessRoleArn=role_arn,
                inputS3Uri=input_s3_uri,
                outputS3Uri=output_s3_uri,
            )
        except ClientError as err:
            logger.error(
                "Couldn't start DICOM import job. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return job["jobId"]
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartDICOMImportJob](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/StartDICOMImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `TagResource`
<a name="medical-imaging_TagResource_python_3_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def tag_resource(self, resource_arn, tags):
        """
        Tag a resource.

        :param resource_arn: The ARN of the resource.
        :param tags: The tags to apply.
        """
        try:
            self.health_imaging_client.tag_resource(resourceArn=resource_arn, tags=tags)
        except ClientError as err:
            logger.error(
                "Couldn't tag resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/TagResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `UntagResource`
<a name="medical-imaging_UntagResource_python_3_topic"></a>

次のコード例は、`UntagResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def untag_resource(self, resource_arn, tag_keys):
        """
        Untag a resource.

        :param resource_arn: The ARN of the resource.
        :param tag_keys: The tag keys to remove.
        """
        try:
            self.health_imaging_client.untag_resource(
                resourceArn=resource_arn, tagKeys=tag_keys
            )
        except ClientError as err:
            logger.error(
                "Couldn't untag resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+  API の詳細については、*AWS  SDK for Python (Boto3) API リファレンス*の「[UntagResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/UntagResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### `UpdateImageSetMetadata`
<a name="medical-imaging_UpdateImageSetMetadata_python_3_topic"></a>

次のコード例は、`UpdateImageSetMetadata` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def update_image_set_metadata(
        self, datastore_id, image_set_id, version_id, metadata, force=False
    ):
        """
        Update the metadata of an image set.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param version_id: The ID of the image set version.
        :param metadata: The image set metadata as a dictionary.
            For example {"DICOMUpdates": {"updatableAttributes":
            "{\"SchemaVersion\":1.1,\"Patient\":{\"DICOM\":{\"PatientName\":\"Garcia^Gloria\"}}}"}}
        :param: force: Force the update.
        :return: The updated image set metadata.
        """
        try:
            updated_metadata = self.health_imaging_client.update_image_set_metadata(
                imageSetId=image_set_id,
                datastoreId=datastore_id,
                latestVersionId=version_id,
                updateImageSetMetadataUpdates=metadata,
                force=force,
            )
        except ClientError as err:
            logger.error(
                "Couldn't update image set metadata. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return updated_metadata
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
ユースケース 1: 属性を挿入または更新します。  

```
            attributes = """{
                    "SchemaVersion": 1.1,
                    "Study": {
                        "DICOM": {
                            "StudyDescription": "CT CHEST"
                        }
                    }
                }"""
            metadata = {"DICOMUpdates": {"updatableAttributes": attributes}}

            self.update_image_set_metadata(
                data_store_id, image_set_id, version_id, metadata, force
            )
```
ユースケース 2: 属性を削除します。  

```
            # Attribute key and value must match the existing attribute.
            attributes = """{
                    "SchemaVersion": 1.1,
                    "Study": {
                        "DICOM": {
                            "StudyDescription": "CT CHEST"
                        }
                    }
                }"""
            metadata = {"DICOMUpdates": {"removableAttributes": attributes}}

            self.update_image_set_metadata(
                data_store_id, image_set_id, version_id, metadata, force
            )
```
ユースケース 3: インスタンスを削除します。  

```
            attributes = """{
                    "SchemaVersion": 1.1,
                    "Study": {
                        "Series": {
                            "1.1.1.1.1.1.12345.123456789012.123.12345678901234.1": {
                                "Instances": {
                                    "1.1.1.1.1.1.12345.123456789012.123.12345678901234.1": {}
                                }
                            }
                        }
                    }
                }"""
            metadata = {"DICOMUpdates": {"removableAttributes": attributes}}

            self.update_image_set_metadata(
                data_store_id, image_set_id, version_id, metadata, force
            )
```
ユースケース 4: 以前のバージョンに戻します。  

```
            metadata = {"revertToVersionId": "1"}

            self.update_image_set_metadata(
                data_store_id, image_set_id, version_id, metadata, force
            )
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateImageSetMetadata](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/UpdateImageSetMetadata)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

## シナリオ
<a name="scenarios"></a>

### 画像セットと画像フレームを使い始める
<a name="medical-imaging_Scenario_ImageSetsAndFrames_python_3_topic"></a>

次のコード例は、HealthImaging で DICOM ファイルをインポートし、画像フレームをダウンロードする方法を示しています。

実装はコマンドラインアプリケーションとして構造化されています。
+ DICOM インポート用にリソースをセットアップします。
+ DICOM ファイルをデータストアへのインポート。
+ インポートジョブの画像セット ID の取得。
+ インポートジョブの画像フレーム ID の取得。
+ イメージフレームをダウンロード、デコード、および検証します。
+ リソースをクリーンアップします。

**SDK for Python (Boto3)**  
必要なリソースを持つ CloudFormation スタックを作成します。  

```
    def deploy(self):
        """
        Deploys prerequisite resources used by the scenario. The resources are
        defined in the associated `setup.yaml` AWS CloudFormation script and are deployed
        as a CloudFormation stack, so they can be easily managed and destroyed.
        """

        print("\t\tLet's deploy the stack for resource creation.")
        stack_name = q.ask("\t\tEnter a name for the stack: ", q.non_empty)

        data_store_name = q.ask(
            "\t\tEnter a name for the Health Imaging Data Store: ", q.non_empty
        )

        account_id = boto3.client("sts").get_caller_identity()["Account"]

        with open(
            "../../../../scenarios/features/healthimaging_image_sets/resources/cfn_template.yaml"
        ) as setup_file:
            setup_template = setup_file.read()
        print(f"\t\tCreating {stack_name}.")
        stack = self.cf_resource.create_stack(
            StackName=stack_name,
            TemplateBody=setup_template,
            Capabilities=["CAPABILITY_NAMED_IAM"],
            Parameters=[
                {
                    "ParameterKey": "datastoreName",
                    "ParameterValue": data_store_name,
                },
                {
                    "ParameterKey": "userAccountID",
                    "ParameterValue": account_id,
                },
            ],
        )
        print("\t\tWaiting for stack to deploy. This typically takes a minute or two.")
        waiter = self.cf_resource.meta.client.get_waiter("stack_create_complete")
        waiter.wait(StackName=stack.name)
        stack.load()
        print(f"\t\tStack status: {stack.stack_status}")

        outputs_dictionary = {
            output["OutputKey"]: output["OutputValue"] for output in stack.outputs
        }
        self.input_bucket_name = outputs_dictionary["BucketName"]
        self.output_bucket_name = outputs_dictionary["BucketName"]
        self.role_arn = outputs_dictionary["RoleArn"]
        self.data_store_id = outputs_dictionary["DatastoreID"]
        return stack
```
DICOM ファイルを Amazon S3 インポートバケットにコピーします。  

```
    def copy_single_object(self, key, source_bucket, target_bucket, target_directory):
        """
        Copies a single object from a source to a target bucket.

        :param key: The key of the object to copy.
        :param source_bucket: The source bucket for the copy.
        :param target_bucket: The target bucket for the copy.
        :param target_directory: The target directory for the copy.
        """
        new_key = target_directory + "/" + key
        copy_source = {"Bucket": source_bucket, "Key": key}
        self.s3_client.copy_object(
            CopySource=copy_source, Bucket=target_bucket, Key=new_key
        )
        print(f"\n\t\tCopying {key}.")

    def copy_images(
        self, source_bucket, source_directory, target_bucket, target_directory
    ):
        """
        Copies the images from the source to the target bucket using multiple threads.

        :param source_bucket: The source bucket for the images.
        :param source_directory: Directory within the source bucket.
        :param target_bucket: The target bucket for the images.
        :param target_directory: Directory within the target bucket.
        """

        # Get list of all objects in source bucket.
        list_response = self.s3_client.list_objects_v2(
            Bucket=source_bucket, Prefix=source_directory
        )
        objs = list_response["Contents"]
        keys = [obj["Key"] for obj in objs]

        # Copy the objects in the bucket.
        for key in keys:
            self.copy_single_object(key, source_bucket, target_bucket, target_directory)

        print("\t\tDone copying all objects.")
```
DICOM ファイルを Amazon S3 データストアのにインポートします。  

```
class MedicalImagingWrapper:
    """Encapsulates AWS HealthImaging functionality."""

    def __init__(self, medical_imaging_client, s3_client):
        """
        :param medical_imaging_client: A Boto3 Amazon MedicalImaging client.
        :param s3_client: A Boto3 S3 client.
        """
        self.medical_imaging_client = medical_imaging_client
        self.s3_client = s3_client

    @classmethod
    def from_client(cls):
        medical_imaging_client = boto3.client("medical-imaging")
        s3_client = boto3.client("s3")
        return cls(medical_imaging_client, s3_client)


    def start_dicom_import_job(
        self,
        data_store_id,
        input_bucket_name,
        input_directory,
        output_bucket_name,
        output_directory,
        role_arn,
    ):
        """
        Routine which starts a HealthImaging import job.

        :param data_store_id: The HealthImaging data store ID.
        :param input_bucket_name: The name of the Amazon S3 bucket containing the DICOM files.
        :param input_directory: The directory in the S3 bucket containing the DICOM files.
        :param output_bucket_name: The name of the S3 bucket for the output.
        :param output_directory: The directory in the S3 bucket to store the output.
        :param role_arn: The ARN of the IAM role with permissions for the import.
        :return: The job ID of the import.
        """

        input_uri = f"s3://{input_bucket_name}/{input_directory}/"
        output_uri = f"s3://{output_bucket_name}/{output_directory}/"
        try:
            job = self.medical_imaging_client.start_dicom_import_job(
                jobName="examplejob",
                datastoreId=data_store_id,
                dataAccessRoleArn=role_arn,
                inputS3Uri=input_uri,
                outputS3Uri=output_uri,
            )
        except ClientError as err:
            logger.error(
                "Couldn't start DICOM import job. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return job["jobId"]
```
DICOM インポートジョブによって作成された画像セットを取得します。  

```
class MedicalImagingWrapper:
    """Encapsulates AWS HealthImaging functionality."""

    def __init__(self, medical_imaging_client, s3_client):
        """
        :param medical_imaging_client: A Boto3 Amazon MedicalImaging client.
        :param s3_client: A Boto3 S3 client.
        """
        self.medical_imaging_client = medical_imaging_client
        self.s3_client = s3_client

    @classmethod
    def from_client(cls):
        medical_imaging_client = boto3.client("medical-imaging")
        s3_client = boto3.client("s3")
        return cls(medical_imaging_client, s3_client)


    def get_image_sets_for_dicom_import_job(self, datastore_id, import_job_id):
        """
        Retrieves the image sets created for an import job.

        :param datastore_id: The HealthImaging data store ID
        :param import_job_id: The import job ID
        :return: List of image set IDs
        """

        import_job = self.medical_imaging_client.get_dicom_import_job(
            datastoreId=datastore_id, jobId=import_job_id
        )

        output_uri = import_job["jobProperties"]["outputS3Uri"]

        bucket = output_uri.split("/")[2]
        key = "/".join(output_uri.split("/")[3:])

        # Try to get the manifest.
        retries = 3
        while retries > 0:
            try:
                obj = self.s3_client.get_object(
                    Bucket=bucket, Key=key + "job-output-manifest.json"
                )
                body = obj["Body"]
                break
            except ClientError as error:
                retries = retries - 1
                time.sleep(3)
        try:
            data = json.load(body)
            expression = jmespath.compile("jobSummary.imageSetsSummary[].imageSetId")
            image_sets = expression.search(data)
        except json.decoder.JSONDecodeError as error:
            image_sets = import_job["jobProperties"]

        return image_sets


    def get_image_set(self, datastore_id, image_set_id, version_id=None):
        """
        Get the properties of an image set.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param version_id: The optional version of the image set.
        :return: The image set properties.
        """
        try:
            if version_id:
                image_set = self.medical_imaging_client.get_image_set(
                    imageSetId=image_set_id,
                    datastoreId=datastore_id,
                    versionId=version_id,
                )
            else:
                image_set = self.medical_imaging_client.get_image_set(
                    imageSetId=image_set_id, datastoreId=datastore_id
                )
        except ClientError as err:
            logger.error(
                "Couldn't get image set. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return image_set
```
画像セットの画像フレーム情報を取得します。  

```
class MedicalImagingWrapper:
    """Encapsulates AWS HealthImaging functionality."""

    def __init__(self, medical_imaging_client, s3_client):
        """
        :param medical_imaging_client: A Boto3 Amazon MedicalImaging client.
        :param s3_client: A Boto3 S3 client.
        """
        self.medical_imaging_client = medical_imaging_client
        self.s3_client = s3_client

    @classmethod
    def from_client(cls):
        medical_imaging_client = boto3.client("medical-imaging")
        s3_client = boto3.client("s3")
        return cls(medical_imaging_client, s3_client)


    def get_image_frames_for_image_set(self, datastore_id, image_set_id, out_directory):
        """
        Get the image frames for an image set.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param out_directory: The directory to save the file.
        :return: The image frames.
        """
        image_frames = []
        file_name = os.path.join(out_directory, f"{image_set_id}_metadata.json.gzip")
        file_name = file_name.replace("/", "\\\\")
        self.get_image_set_metadata(file_name, datastore_id, image_set_id)
        try:
            with gzip.open(file_name, "rb") as f_in:
                doc = json.load(f_in)
            instances = jmespath.search("Study.Series.*.Instances[].*[]", doc)
            for instance in instances:
                rescale_slope = jmespath.search("DICOM.RescaleSlope", instance)
                rescale_intercept = jmespath.search("DICOM.RescaleIntercept", instance)
                image_frames_json = jmespath.search("ImageFrames[][]", instance)
                for image_frame in image_frames_json:
                    checksum_json = jmespath.search(
                        "max_by(PixelDataChecksumFromBaseToFullResolution, &Width)",
                        image_frame,
                    )
                    image_frame_info = {
                        "imageSetId": image_set_id,
                        "imageFrameId": image_frame["ID"],
                        "rescaleIntercept": rescale_intercept,
                        "rescaleSlope": rescale_slope,
                        "minPixelValue": image_frame["MinPixelValue"],
                        "maxPixelValue": image_frame["MaxPixelValue"],
                        "fullResolutionChecksum": checksum_json["Checksum"],
                    }
                    image_frames.append(image_frame_info)
            return image_frames
        except TypeError:
            return {}
        except ClientError as err:
            logger.error(
                "Couldn't get image frames for image set. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        return image_frames


    def get_image_set_metadata(
        self, metadata_file, datastore_id, image_set_id, version_id=None
    ):
        """
        Get the metadata of an image set.

        :param metadata_file: The file to store the JSON gzipped metadata.
        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param version_id: The version of the image set.
        """

        try:
            if version_id:
                image_set_metadata = self.medical_imaging_client.get_image_set_metadata(
                    imageSetId=image_set_id,
                    datastoreId=datastore_id,
                    versionId=version_id,
                )
            else:
                image_set_metadata = self.medical_imaging_client.get_image_set_metadata(
                    imageSetId=image_set_id, datastoreId=datastore_id
                )
            with open(metadata_file, "wb") as f:
                for chunk in image_set_metadata["imageSetMetadataBlob"].iter_chunks():
                    if chunk:
                        f.write(chunk)

        except ClientError as err:
            logger.error(
                "Couldn't get image metadata. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
画像フレームをダウンロード、デコード、および検証します。  

```
class MedicalImagingWrapper:
    """Encapsulates AWS HealthImaging functionality."""

    def __init__(self, medical_imaging_client, s3_client):
        """
        :param medical_imaging_client: A Boto3 Amazon MedicalImaging client.
        :param s3_client: A Boto3 S3 client.
        """
        self.medical_imaging_client = medical_imaging_client
        self.s3_client = s3_client

    @classmethod
    def from_client(cls):
        medical_imaging_client = boto3.client("medical-imaging")
        s3_client = boto3.client("s3")
        return cls(medical_imaging_client, s3_client)


    def get_pixel_data(
        self, file_path_to_write, datastore_id, image_set_id, image_frame_id
    ):
        """
        Get an image frame's pixel data.

        :param file_path_to_write: The path to write the image frame's HTJ2K encoded pixel data.
        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        :param image_frame_id: The ID of the image frame.
        """
        try:
            image_frame = self.medical_imaging_client.get_image_frame(
                datastoreId=datastore_id,
                imageSetId=image_set_id,
                imageFrameInformation={"imageFrameId": image_frame_id},
            )
            with open(file_path_to_write, "wb") as f:
                for chunk in image_frame["imageFrameBlob"].iter_chunks():
                    f.write(chunk)
        except ClientError as err:
            logger.error(
                "Couldn't get image frame. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def download_decode_and_check_image_frames(
        self, data_store_id, image_frames, out_directory
    ):
        """
        Downloads image frames, decodes them, and uses the checksum to validate
        the decoded images.

        :param data_store_id: The HealthImaging data store ID.
        :param image_frames: A list of dicts containing image frame information.
        :param out_directory: A directory for the downloaded images.
        :return: True if the function succeeded; otherwise, False.
        """
        total_result = True
        for image_frame in image_frames:
            image_file_path = f"{out_directory}/image_{image_frame['imageFrameId']}.jph"
            self.get_pixel_data(
                image_file_path,
                data_store_id,
                image_frame["imageSetId"],
                image_frame["imageFrameId"],
            )

            image_array = self.jph_image_to_opj_bitmap(image_file_path)
            crc32_checksum = image_frame["fullResolutionChecksum"]
            # Verify checksum.
            crc32_calculated = zlib.crc32(image_array)
            image_result = crc32_checksum == crc32_calculated
            print(
                f"\t\tImage checksum verified for {image_frame['imageFrameId']}: {image_result }"
            )
            total_result = total_result and image_result
        return total_result

    @staticmethod
    def jph_image_to_opj_bitmap(jph_file):
        """
        Decode the image to a bitmap using an OPENJPEG library.
        :param jph_file: The file to decode.
        :return: The decoded bitmap as an array.
        """
        # Use format 2 for the JPH file.
        params = openjpeg.utils.get_parameters(jph_file, 2)
        print(f"\n\t\tImage parameters for {jph_file}: \n\t\t{params}")

        image_array = openjpeg.utils.decode(jph_file, 2)

        return image_array
```
リソースをクリーンアップします。  

```
    def destroy(self, stack):
        """
        Destroys the resources managed by the CloudFormation stack, and the CloudFormation
        stack itself.

        :param stack: The CloudFormation stack that manages the example resources.
        """

        print(f"\t\tCleaning up resources and {stack.name}.")
        data_store_id = None
        for oput in stack.outputs:
            if oput["OutputKey"] == "DatastoreID":
                data_store_id = oput["OutputValue"]
        if data_store_id is not None:
            print(f"\t\tDeleting image sets in data store {data_store_id}.")
            image_sets = self.medical_imaging_wrapper.search_image_sets(
                data_store_id, {}
            )
            image_set_ids = [image_set["imageSetId"] for image_set in image_sets]

            for image_set_id in image_set_ids:
                self.medical_imaging_wrapper.delete_image_set(
                    data_store_id, image_set_id
                )
                print(f"\t\tDeleted image set with id : {image_set_id}")

        print(f"\t\tDeleting {stack.name}.")
        stack.delete()
        print("\t\tWaiting for stack removal. This may take a few minutes.")
        waiter = self.cf_resource.meta.client.get_waiter("stack_delete_complete")
        waiter.wait(StackName=stack.name)
        print("\t\tStack delete complete.")




class MedicalImagingWrapper:
    """Encapsulates AWS HealthImaging functionality."""

    def __init__(self, medical_imaging_client, s3_client):
        """
        :param medical_imaging_client: A Boto3 Amazon MedicalImaging client.
        :param s3_client: A Boto3 S3 client.
        """
        self.medical_imaging_client = medical_imaging_client
        self.s3_client = s3_client

    @classmethod
    def from_client(cls):
        medical_imaging_client = boto3.client("medical-imaging")
        s3_client = boto3.client("s3")
        return cls(medical_imaging_client, s3_client)


    def search_image_sets(self, datastore_id, search_filter):
        """
        Search for image sets.

        :param datastore_id: The ID of the data store.
        :param search_filter: The search filter.
            For example: {"filters" : [{ "operator": "EQUAL", "values": [{"DICOMPatientId": "3524578"}]}]}.
        :return: The list of image sets.
        """
        try:
            paginator = self.medical_imaging_client.get_paginator("search_image_sets")
            page_iterator = paginator.paginate(
                datastoreId=datastore_id, searchCriteria=search_filter
            )
            metadata_summaries = []
            for page in page_iterator:
                metadata_summaries.extend(page["imageSetsMetadataSummaries"])
        except ClientError as err:
            logger.error(
                "Couldn't search image sets. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return metadata_summaries


    def delete_image_set(self, datastore_id, image_set_id):
        """
        Delete an image set.

        :param datastore_id: The ID of the data store.
        :param image_set_id: The ID of the image set.
        """
        try:
            delete_results = self.medical_imaging_client.delete_image_set(
                imageSetId=image_set_id, datastoreId=datastore_id
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete image set. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [DeleteImageSet](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/DeleteImageSet)
  + [GetDICOMImportJob](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetDICOMImportJob)
  + [GetImageFrame](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetImageFrame)
  + [GetImageSetMetadata](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/GetImageSetMetadata)
  + [SearchImageSets](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/SearchImageSets)
  + [StartDICOMImportJob](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/StartDICOMImportJob)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/medical-imaging/imaging_set_and_frames_workflow#code-examples)での設定と実行の方法を確認してください。

### データストアにタグを付ける
<a name="medical-imaging_Scenario_TaggingDataStores_python_3_topic"></a>

次のコード例は、HealthImaging データストアにタグを付ける方法を示しています。

**SDK for Python (Boto3)**  
データストアにタグを付けるには  

```
    a_data_store_arn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012"

    medical_imaging_wrapper.tag_resource(data_store_arn, {"Deployment": "Development"})
```
リソースにタグを付けるためのユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def tag_resource(self, resource_arn, tags):
        """
        Tag a resource.

        :param resource_arn: The ARN of the resource.
        :param tags: The tags to apply.
        """
        try:
            self.health_imaging_client.tag_resource(resourceArn=resource_arn, tags=tags)
        except ClientError as err:
            logger.error(
                "Couldn't tag resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
データストアのタグを一覧表示します。  

```
    a_data_store_arn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012"

    medical_imaging_wrapper.list_tags_for_resource(data_store_arn)
```
リソースのタグを一覧表示するユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def list_tags_for_resource(self, resource_arn):
        """
        List the tags for a resource.

        :param resource_arn: The ARN of the resource.
        :return: The list of tags.
        """
        try:
            tags = self.health_imaging_client.list_tags_for_resource(
                resourceArn=resource_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't list tags for resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return tags["tags"]
```
データストアのタグを解除するには  

```
    a_data_store_arn = "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012"

    medical_imaging_wrapper.untag_resource(data_store_arn, ["Deployment"])
```
リソースのタグを解除するユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def untag_resource(self, resource_arn, tag_keys):
        """
        Untag a resource.

        :param resource_arn: The ARN of the resource.
        :param tag_keys: The tag keys to remove.
        """
        try:
            self.health_imaging_client.untag_resource(
                resourceArn=resource_arn, tagKeys=tag_keys
            )
        except ClientError as err:
            logger.error(
                "Couldn't untag resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [ListTagsForResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/ListTagsForResource)
  + [TagResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/TagResource)
  + [UntagResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/UntagResource)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

### イメージセットにタグを付ける
<a name="medical-imaging_Scenario_TaggingImageSets_python_3_topic"></a>

次のコード例は、HealthImaging イメージセットにタグを付ける方法を示しています。

**SDK for Python (Boto3)**  
イメージセットにタグを付けるには  

```
    an_image_set_arn = (
        "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/"
        "imageset/12345678901234567890123456789012"
    )

    medical_imaging_wrapper.tag_resource(image_set_arn, {"Deployment": "Development"})
```
リソースにタグを付けるためのユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def tag_resource(self, resource_arn, tags):
        """
        Tag a resource.

        :param resource_arn: The ARN of the resource.
        :param tags: The tags to apply.
        """
        try:
            self.health_imaging_client.tag_resource(resourceArn=resource_arn, tags=tags)
        except ClientError as err:
            logger.error(
                "Couldn't tag resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
イメージセットのタグを一覧表示します。  

```
    an_image_set_arn = (
        "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/"
        "imageset/12345678901234567890123456789012"
    )

    medical_imaging_wrapper.list_tags_for_resource(image_set_arn)
```
リソースのタグを一覧表示するユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def list_tags_for_resource(self, resource_arn):
        """
        List the tags for a resource.

        :param resource_arn: The ARN of the resource.
        :return: The list of tags.
        """
        try:
            tags = self.health_imaging_client.list_tags_for_resource(
                resourceArn=resource_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't list tags for resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return tags["tags"]
```
イメージセットのタグを解除します。  

```
    an_image_set_arn = (
        "arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012/"
        "imageset/12345678901234567890123456789012"
    )

    medical_imaging_wrapper.untag_resource(image_set_arn, ["Deployment"])
```
リソースのタグを解除するユーティリティ関数。  

```
class MedicalImagingWrapper:
    def __init__(self, health_imaging_client):
        self.health_imaging_client = health_imaging_client


    def untag_resource(self, resource_arn, tag_keys):
        """
        Untag a resource.

        :param resource_arn: The ARN of the resource.
        :param tag_keys: The tag keys to remove.
        """
        try:
            self.health_imaging_client.untag_resource(
                resourceArn=resource_arn, tagKeys=tag_keys
            )
        except ClientError as err:
            logger.error(
                "Couldn't untag resource. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは MedicalImagingWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("medical-imaging")
    medical_imaging_wrapper = MedicalImagingWrapper(client)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [ListTagsForResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/ListTagsForResource)
  + [TagResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/TagResource)
  + [UntagResource](https://docs.aws.amazon.com/goto/boto3/medical-imaging-2023-07-19/UntagResource)
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/medical-imaging#code-examples)での設定と実行の方法を確認してください。

# SDK for Python (Boto3) を使用する HealthLake の例
<a name="python_3_healthlake_code_examples"></a>

次のコード例は、HealthLake AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateFHIRDatastore`
<a name="healthlake_CreateFHIRDatastore_python_3_topic"></a>

次のコード例は、`CreateFHIRDatastore` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def create_fhir_datastore(
        self,
        datastore_name: str,
        sse_configuration: dict[str, any] = None,
        identity_provider_configuration: dict[str, any] = None,
    ) -> dict[str, str]:
        """
        Creates a new HealthLake data store.
        When creating a SMART on FHIR data store, the following parameters are required:
        - sse_configuration: The server-side encryption configuration for a SMART on FHIR-enabled data store.
        - identity_provider_configuration: The identity provider configuration for a SMART on FHIR-enabled data store.

        :param datastore_name: The name of the data store.
        :param sse_configuration: The server-side encryption configuration for a SMART on FHIR-enabled data store.
        :param identity_provider_configuration: The identity provider configuration for a SMART on FHIR-enabled data store.
        :return: A dictionary containing the data store information.
        """
        try:
            parameters = {"DatastoreName": datastore_name, "DatastoreTypeVersion": "R4"}
            if (
                sse_configuration is not None
                and identity_provider_configuration is not None
            ):
                # Creating a SMART on FHIR-enabled data store
                parameters["SseConfiguration"] = sse_configuration
                parameters[
                    "IdentityProviderConfiguration"
                ] = identity_provider_configuration

            response = self.health_lake_client.create_fhir_datastore(**parameters)
            return response
        except ClientError as err:
            logger.exception(
                "Couldn't create data store %s. Here's why %s",
                datastore_name,
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは、SMART on FHIR 対応 HealthLake データストアのパラメータの例を示しています。  

```
            sse_configuration = {
                "KmsEncryptionConfig": {"CmkType": "AWS_OWNED_KMS_KEY"}
            }
            # TODO: Update the metadata to match your environment.
            metadata = {
                "issuer": "https://ehr.example.com",
                "jwks_uri": "https://ehr.example.com/.well-known/jwks.json",
                "authorization_endpoint": "https://ehr.example.com/auth/authorize",
                "token_endpoint": "https://ehr.token.com/auth/token",
                "token_endpoint_auth_methods_supported": [
                    "client_secret_basic",
                    "foo",
                ],
                "grant_types_supported": ["client_credential", "foo"],
                "registration_endpoint": "https://ehr.example.com/auth/register",
                "scopes_supported": ["openId", "profile", "launch"],
                "response_types_supported": ["code"],
                "management_endpoint": "https://ehr.example.com/user/manage",
                "introspection_endpoint": "https://ehr.example.com/user/introspect",
                "revocation_endpoint": "https://ehr.example.com/user/revoke",
                "code_challenge_methods_supported": ["S256"],
                "capabilities": [
                    "launch-ehr",
                    "sso-openid-connect",
                    "client-public",
                ],
            }
            # TODO: Update the IdpLambdaArn.
            identity_provider_configuration = {
                "AuthorizationStrategy": "SMART_ON_FHIR_V1",
                "FineGrainedAuthorizationEnabled": True,
                "IdpLambdaArn": "arn:aws:lambda:your-region:your-account-id:function:your-lambda-name",
                "Metadata": json.dumps(metadata),
            }
            data_store = self.create_fhir_datastore(
                datastore_name, sse_configuration, identity_provider_configuration
            )
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateFHIRDatastore](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/CreateFHIRDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `DeleteFHIRDatastore`
<a name="healthlake_DeleteFHIRDatastore_python_3_topic"></a>

次のコード例は、`DeleteFHIRDatastore` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def delete_fhir_datastore(self, datastore_id: str) -> None:
        """
        Deletes a HealthLake data store.
        :param datastore_id: The data store ID.
        """
        try:
            self.health_lake_client.delete_fhir_datastore(DatastoreId=datastore_id)
        except ClientError as err:
            logger.exception(
                "Couldn't delete data store with ID %s. Here's why %s",
                datastore_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteFHIRDatastore](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/DeleteFHIRDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `DescribeFHIRDatastore`
<a name="healthlake_DescribeFHIRDatastore_python_3_topic"></a>

次のコード例は、`DescribeFHIRDatastore` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def describe_fhir_datastore(self, datastore_id: str) -> dict[str, any]:
        """
        Describes a HealthLake data store.
        :param datastore_id: The data store ID.
        :return: The data store description.
        """
        try:
            response = self.health_lake_client.describe_fhir_datastore(
                DatastoreId=datastore_id
            )
            return response["DatastoreProperties"]
        except ClientError as err:
            logger.exception(
                "Couldn't describe data store with ID %s. Here's why %s",
                datastore_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeFHIRDatastore](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/DescribeFHIRDatastore)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `DescribeFHIRExportJob`
<a name="healthlake_DescribeFHIRExportJob_python_3_topic"></a>

次のコード例は、`DescribeFHIRExportJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def describe_fhir_export_job(
        self, datastore_id: str, job_id: str
    ) -> dict[str, any]:
        """
        Describes a HealthLake export job.
        :param datastore_id: The data store ID.
        :param job_id: The export job ID.
        :return: The export job description.
        """
        try:
            response = self.health_lake_client.describe_fhir_export_job(
                DatastoreId=datastore_id, JobId=job_id
            )
            return response["ExportJobProperties"]
        except ClientError as err:
            logger.exception(
                "Couldn't describe export job with ID %s. Here's why %s",
                job_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeFHIRExportJob](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/DescribeFHIRExportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `DescribeFHIRImportJob`
<a name="healthlake_DescribeFHIRImportJob_python_3_topic"></a>

次のコード例は、`DescribeFHIRImportJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def describe_fhir_import_job(
        self, datastore_id: str, job_id: str
    ) -> dict[str, any]:
        """
        Describes a HealthLake import job.
        :param datastore_id: The data store ID.
        :param job_id: The import job ID.
        :return: The import job description.
        """
        try:
            response = self.health_lake_client.describe_fhir_import_job(
                DatastoreId=datastore_id, JobId=job_id
            )
            return response["ImportJobProperties"]
        except ClientError as err:
            logger.exception(
                "Couldn't describe import job with ID %s. Here's why %s",
                job_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeFHIRImportJob](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/DescribeFHIRImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `ListFHIRDatastores`
<a name="healthlake_ListFHIRDatastores_python_3_topic"></a>

次のコード例は、`ListFHIRDatastores` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def list_fhir_datastores(self) -> list[dict[str, any]]:
        """
        Lists all HealthLake data stores.
        :return: A list of data store descriptions.
        """
        try:
            next_token = None
            datastores = []

            # Loop through paginated results.
            while True:
                parameters = {}
                if next_token is not None:
                    parameters["NextToken"] = next_token
                response = self.health_lake_client.list_fhir_datastores(**parameters)
                datastores.extend(response["DatastorePropertiesList"])
                if "NextToken" in response:
                    next_token = response["NextToken"]
                else:
                    break

            return datastores
        except ClientError as err:
            logger.exception(
                "Couldn't list data stores. Here's why %s", err.response["Error"]["Message"]
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListFHIRDatastores](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/ListFHIRDatastores)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `ListFHIRExportJobs`
<a name="healthlake_ListFHIRExportJobs_python_3_topic"></a>

次のコード例は、`ListFHIRExportJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def list_fhir_export_jobs(
        self,
        datastore_id: str,
        job_name: str = None,
        job_status: str = None,
        submitted_before: datetime = None,
        submitted_after: datetime = None,
    ) -> list[dict[str, any]]:
        """
        Lists HealthLake export jobs satisfying the conditions.
        :param datastore_id: The data store ID.
        :param job_name: The export job name.
        :param job_status: The export job status.
        :param submitted_before: The export job submitted before the specified date.
        :param submitted_after: The export job submitted after the specified date.
        :return: A list of export jobs.
        """
        try:
            parameters = {"DatastoreId": datastore_id}
            if job_name is not None:
                parameters["JobName"] = job_name
            if job_status is not None:
                parameters["JobStatus"] = job_status
            if submitted_before is not None:
                parameters["SubmittedBefore"] = submitted_before
            if submitted_after is not None:
                parameters["SubmittedAfter"] = submitted_after
            next_token = None
            jobs = []
            # Loop through paginated results.
            while True:
                if next_token is not None:
                    parameters["NextToken"] = next_token
                response = self.health_lake_client.list_fhir_export_jobs(**parameters)
                jobs.extend(response["ExportJobPropertiesList"])
                if "NextToken" in response:
                    next_token = response["NextToken"]
                else:
                    break
            return jobs
        except ClientError as err:
            logger.exception(
                "Couldn't list export jobs. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListFHIRExportJobs](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/ListFHIRExportJobs)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `ListFHIRImportJobs`
<a name="healthlake_ListFHIRImportJobs_python_3_topic"></a>

次のコード例は、`ListFHIRImportJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def list_fhir_import_jobs(
        self,
        datastore_id: str,
        job_name: str = None,
        job_status: str = None,
        submitted_before: datetime = None,
        submitted_after: datetime = None,
    ) -> list[dict[str, any]]:
        """
        Lists HealthLake import jobs satisfying the conditions.
        :param datastore_id: The data store ID.
        :param job_name: The import job name.
        :param job_status: The import job status.
        :param submitted_before: The import job submitted before the specified date.
        :param submitted_after: The import job submitted after the specified date.
        :return: A list of import jobs.
        """
        try:
            parameters = {"DatastoreId": datastore_id}
            if job_name is not None:
                parameters["JobName"] = job_name
            if job_status is not None:
                parameters["JobStatus"] = job_status
            if submitted_before is not None:
                parameters["SubmittedBefore"] = submitted_before
            if submitted_after is not None:
                parameters["SubmittedAfter"] = submitted_after
            next_token = None
            jobs = []
            # Loop through paginated results.
            while True:
                if next_token is not None:
                    parameters["NextToken"] = next_token
                response = self.health_lake_client.list_fhir_import_jobs(**parameters)
                jobs.extend(response["ImportJobPropertiesList"])
                if "NextToken" in response:
                    next_token = response["NextToken"]
                else:
                    break
            return jobs
        except ClientError as err:
            logger.exception(
                "Couldn't list import jobs. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListFHIRImportJobs](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/ListFHIRImportJobs)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `ListTagsForResource`
<a name="healthlake_ListTagsForResource_python_3_topic"></a>

次のコード例は、`ListTagsForResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def list_tags_for_resource(self, resource_arn: str) -> dict[str, str]:
        """
        Lists the tags for a HealthLake resource.
        :param resource_arn: The resource ARN.
        :return: The tags for the resource.
        """
        try:
            response = self.health_lake_client.list_tags_for_resource(
                ResourceARN=resource_arn
            )
            return response["Tags"]
        except ClientError as err:
            logger.exception(
                "Couldn't list tags for resource %s. Here's why %s",
                resource_arn,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListTagsForResource](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/ListTagsForResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `StartFHIRExportJob`
<a name="healthlake_StartFHIRExportJob_python_3_topic"></a>

次のコード例は、`StartFHIRExportJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def start_fhir_export_job(
        self,
        job_name: str,
        datastore_id: str,
        output_s3_uri: str,
        kms_key_id: str,
        data_access_role_arn: str,
    ) -> dict[str, str]:
        """
        Starts a HealthLake export job.
        :param job_name: The export job name.
        :param datastore_id: The data store ID.
        :param output_s3_uri: The output S3 URI.
        :param kms_key_id: The KMS key ID associated with the output S3 bucket.
        :param data_access_role_arn: The data access role ARN.
        :return: The export job.
        """
        try:
            response = self.health_lake_client.start_fhir_export_job(
                OutputDataConfig={
                    "S3Configuration": {"S3Uri": output_s3_uri, "KmsKeyId": kms_key_id}
                },
                DataAccessRoleArn=data_access_role_arn,
                DatastoreId=datastore_id,
                JobName=job_name,
            )

            return response
        except ClientError as err:
            logger.exception(
                "Couldn't start export job. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[StartFHIRExportJob](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/StartFHIRExportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `StartFHIRImportJob`
<a name="healthlake_StartFHIRImportJob_python_3_topic"></a>

次のコード例は、`StartFHIRImportJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def start_fhir_import_job(
        self,
        job_name: str,
        datastore_id: str,
        input_s3_uri: str,
        job_output_s3_uri: str,
        kms_key_id: str,
        data_access_role_arn: str,
    ) -> dict[str, str]:
        """
        Starts a HealthLake import job.
        :param job_name: The import job name.
        :param datastore_id: The data store ID.
        :param input_s3_uri: The input S3 URI.
        :param job_output_s3_uri: The job output S3 URI.
        :param kms_key_id: The KMS key ID associated with the output S3 bucket.
        :param data_access_role_arn: The data access role ARN.
        :return: The import job.
        """
        try:
            response = self.health_lake_client.start_fhir_import_job(
                JobName=job_name,
                InputDataConfig={"S3Uri": input_s3_uri},
                JobOutputDataConfig={
                    "S3Configuration": {
                        "S3Uri": job_output_s3_uri,
                        "KmsKeyId": kms_key_id,
                    }
                },
                DataAccessRoleArn=data_access_role_arn,
                DatastoreId=datastore_id,
            )
            return response
        except ClientError as err:
            logger.exception(
                "Couldn't start import job. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[StartFHIRImportJob](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/StartFHIRImportJob)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `TagResource`
<a name="healthlake_TagResource_python_3_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def tag_resource(self, resource_arn: str, tags: list[dict[str, str]]) -> None:
        """
        Tags a HealthLake resource.
        :param resource_arn: The resource ARN.
        :param tags: The tags to add to the resource.
        """
        try:
            self.health_lake_client.tag_resource(ResourceARN=resource_arn, Tags=tags)
        except ClientError as err:
            logger.exception(
                "Couldn't tag resource %s. Here's why %s",
                resource_arn,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/TagResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

### `UntagResource`
<a name="healthlake_UntagResource_python_3_topic"></a>

次のコード例は、`UntagResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  

```
    @classmethod
    def from_client(cls) -> "HealthLakeWrapper":
        """
        Creates a HealthLakeWrapper instance with a default AWS HealthLake client.

        :return: An instance of HealthLakeWrapper initialized with the default HealthLake client.
        """
        health_lake_client = boto3.client("healthlake")
        return cls(health_lake_client)


    def untag_resource(self, resource_arn: str, tag_keys: list[str]) -> None:
        """
        Untags a HealthLake resource.
        :param resource_arn: The resource ARN.
        :param tag_keys: The tag keys to remove from the resource.
        """
        try:
            self.health_lake_client.untag_resource(
                ResourceARN=resource_arn, TagKeys=tag_keys
            )
        except ClientError as err:
            logger.exception(
                "Couldn't untag resource %s. Here's why %s",
                resource_arn,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS  SDK for Python (Boto3) API リファレンス*の「[UntagResource](https://docs.aws.amazon.com/goto/boto3/healthlake-2017-07-01/UntagResource)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/healthlake#code-examples)での設定と実行の方法を確認してください。

# SDK for Python (Boto3) を使用した IAM の例
<a name="python_3_iam_code_examples"></a>

次のコード例は、IAM AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_python_3_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def main():
    """
    Lists the managed policies in your AWS account using the AWS SDK for Python (Boto3).
    """
    iam = boto3.client("iam")

    try:
        # Get a paginator for the list_policies operation
        paginator = iam.get_paginator("list_policies")

        # Iterate through the pages of results
        for page in paginator.paginate(Scope="All", OnlyAttached=False):
            for policy in page["Policies"]:
                print(f"Policy name: {policy['PolicyName']}")
                print(f"  Policy ARN: {policy['Arn']}")
    except boto3.exceptions.BotoCoreError as e:
        print(f"Encountered an error while listing policies: {e}")


if __name__ == "__main__":
    main()
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListPolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListPolicies)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_python_3_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーと、Amazon S3 バケットを一覧表示するアクセス権限を付与するロールを作成します。ユーザーには、ロールの引き受けのみ権限があります。ロールを引き受けた後、一時的な認証情報を使用してアカウントのバケットを一覧表示します。  

```
import json
import sys
import time
from uuid import uuid4

import boto3
from botocore.exceptions import ClientError


def progress_bar(seconds):
    """Shows a simple progress bar in the command window."""
    for _ in range(seconds):
        time.sleep(1)
        print(".", end="")
        sys.stdout.flush()
    print()


def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates an access key pair for the user.
    Creates a role with a policy that lets the user assume the role.
    Creates a policy that allows listing Amazon S3 buckets.
    Attaches the policy to the role.
    Creates an inline policy for the user that lets the user assume the role.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource
                         that has permissions to create users, roles, and policies
                         in the account.
    :return: The newly created user, user key, and role.
    """
    try:
        user = iam_resource.create_user(UserName=f"demo-user-{uuid4()}")
        print(f"Created user {user.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a user for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user_key = user.create_access_key_pair()
        print(f"Created access key pair for user.")
    except ClientError as error:
        print(
            f"Couldn't create access keys for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    try:
        role = iam_resource.create_role(
            RoleName=f"demo-role-{uuid4()}",
            AssumeRolePolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {"AWS": user.arn},
                            "Action": "sts:AssumeRole",
                        }
                    ],
                }
            ),
        )
        print(f"Created role {role.name}.")
    except ClientError as error:
        print(
            f"Couldn't create a role for the demo. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        policy = iam_resource.create_policy(
            PolicyName=f"demo-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "s3:ListAllMyBuckets",
                            "Resource": "arn:aws:s3:::*",
                        }
                    ],
                }
            ),
        )
        role.attach_policy(PolicyArn=policy.arn)
        print(f"Created policy {policy.policy_name} and attached it to the role.")
    except ClientError as error:
        print(
            f"Couldn't create a policy and attach it to role {role.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        user.create_policy(
            PolicyName=f"demo-user-policy-{uuid4()}",
            PolicyDocument=json.dumps(
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Action": "sts:AssumeRole",
                            "Resource": role.arn,
                        }
                    ],
                }
            ),
        )
        print(
            f"Created an inline policy for {user.name} that lets the user assume "
            f"the role."
        )
    except ClientError as error:
        print(
            f"Couldn't create an inline policy for user {user.name}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, role


def show_access_denied_without_role(user_key):
    """
    Shows that listing buckets without first assuming the role is not allowed.

    :param user_key: The key of the user created during setup. This user does not
                     have permission to list buckets in the account.
    """
    print(f"Try to list buckets without first assuming the role.")
    s3_denied_resource = boto3.resource(
        "s3", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        for bucket in s3_denied_resource.buckets.all():
            print(bucket.name)
        raise RuntimeError("Expected to get AccessDenied error when listing buckets!")
    except ClientError as error:
        if error.response["Error"]["Code"] == "AccessDenied":
            print("Attempt to list buckets with no permissions: AccessDenied.")
        else:
            raise


def list_buckets_from_assumed_role(user_key, assume_role_arn, session_name):
    """
    Assumes a role that grants permission to list the Amazon S3 buckets in the account.
    Uses the temporary credentials from the role to list the buckets that are owned
    by the assumed role's account.

    :param user_key: The access key of a user that has permission to assume the role.
    :param assume_role_arn: The Amazon Resource Name (ARN) of the role that
                            grants access to list the other account's buckets.
    :param session_name: The name of the STS session.
    """
    sts_client = boto3.client(
        "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
    )
    try:
        response = sts_client.assume_role(
            RoleArn=assume_role_arn, RoleSessionName=session_name
        )
        temp_credentials = response["Credentials"]
        print(f"Assumed role {assume_role_arn} and got temporary credentials.")
    except ClientError as error:
        print(
            f"Couldn't assume role {assume_role_arn}. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    # Create an S3 resource that can access the account with the temporary credentials.
    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )
    print(f"Listing buckets for the assumed role's account:")
    try:
        for bucket in s3_resource.buckets.all():
            print(bucket.name)
    except ClientError as error:
        print(
            f"Couldn't list buckets for the account. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise




def teardown(user, role):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo role.
    """
    try:
        for attached in role.attached_policies.all():
            policy_name = attached.policy_name
            role.detach_policy(PolicyArn=attached.arn)
            attached.delete()
            print(f"Detached and deleted {policy_name}.")
        role.delete()
        print(f"Deleted {role.name}.")
    except ClientError as error:
        print(
            "Couldn't detach policy, delete policy, or delete role. Here's why: "
            f"{error.response['Error']['Message']}"
        )
        raise

    try:
        for user_pol in user.policies.all():
            user_pol.delete()
            print("Deleted inline user policy.")
        for key in user.access_keys.all():
            key.delete()
            print("Deleted user's access key.")
        user.delete()
        print(f"Deleted {user.name}.")
    except ClientError as error:
        print(
            "Couldn't delete user policy or delete user. Here's why: "
            f"{error.response['Error']['Message']}"
        )


def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(f"Welcome to the IAM create user and assume role demo.")
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user = None
    role = None
    try:
        user, user_key, role = setup(iam_resource)
        print(f"Created {user.name} and {role.name}.")
        show_access_denied_without_role(user_key)
        list_buckets_from_assumed_role(user_key, role.arn, "AssumeRoleDemoSession")
    except Exception:
        print("Something went wrong!")
    finally:
        if user is not None and role is not None:
            teardown(user, role)
        print("Thanks for watching!")


if __name__ == "__main__":
    usage_demo()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_python_3_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
Boto3 Policy オブジェクトを使用して、ロールにポリシーをアタッチします。  

```
def attach_to_role(role_name, policy_arn):
    """
    Attaches a policy to a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Policy(policy_arn).attach_role(RoleName=role_name)
        logger.info("Attached policy %s to role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name)
        raise
```
Boto3 Role オブジェクトを使用して、ロールにポリシーをアタッチします。  

```
def attach_policy(role_name, policy_arn):
    """
    Attaches a policy to a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Role(role_name).attach_policy(PolicyArn=policy_arn)
        logger.info("Attached policy %s to role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name)
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[AttachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachRolePolicy)」を参照してください。

### `AttachUserPolicy`
<a name="iam_AttachUserPolicy_python_3_topic"></a>

次のコード例は、`AttachUserPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def attach_policy(user_name, policy_arn):
    """
    Attaches a policy to a user.

    :param user_name: The name of the user.
    :param policy_arn: The Amazon Resource Name (ARN) of the policy.
    """
    try:
        iam.User(user_name).attach_policy(PolicyArn=policy_arn)
        logger.info("Attached policy %s to user %s.", policy_arn, user_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to user %s.", policy_arn, user_name)
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[AttachUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachUserPolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_python_3_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def create_key(user_name):
    """
    Creates an access key for the specified user. Each user can have a
    maximum of two keys.

    :param user_name: The name of the user.
    :return: The created access key.
    """
    try:
        key_pair = iam.User(user_name).create_access_key_pair()
        logger.info(
            "Created access key pair for %s. Key ID is %s.",
            key_pair.user_name,
            key_pair.id,
        )
    except ClientError:
        logger.exception("Couldn't create access key pair for %s.", user_name)
        raise
    else:
        return key_pair
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_python_3_topic"></a>

次のコード例は、`CreateAccountAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def create_alias(alias):
    """
    Creates an alias for the current account. The alias can be used in place of the
    account ID in the sign-in URL. An account can have only one alias. When a new
    alias is created, it replaces any existing alias.

    :param alias: The alias to assign to the account.
    """

    try:
        iam.create_account_alias(AccountAlias=alias)
        logger.info("Created an alias '%s' for your account.", alias)
    except ClientError:
        logger.exception("Couldn't create alias '%s' for your account.", alias)
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateAccountAlias](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccountAlias)」を参照してください。**

### `CreateInstanceProfile`
<a name="iam_CreateInstanceProfile_python_3_topic"></a>

次のコード例は、`CreateInstanceProfile` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
この例では、ポリシー、ロール、インスタンスプロファイルを作成し、それらをすべてリンクします。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_instance_profile(
        self,
        policy_file: str,
        policy_name: str,
        role_name: str,
        profile_name: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> str:
        """
        Creates a policy, role, and profile that is associated with instances created by
        this class. An instance's associated profile defines a role that is assumed by the
        instance. The role has attached policies that specify the AWS permissions granted to
        clients that run on the instance.

        :param policy_file: The name of a JSON file that contains the policy definition to
                            create and attach to the role.
        :param policy_name: The name to give the created policy.
        :param role_name: The name to give the created role.
        :param profile_name: The name to the created profile.
        :param aws_managed_policies: Additional AWS-managed policies that are attached to
                                     the role, such as AmazonSSMManagedInstanceCore to grant
                                     use of Systems Manager to send commands to the instance.
        :return: The ARN of the profile that is created.
        """
        assume_role_doc = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"Service": "ec2.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        policy_arn = self.create_policy(policy_file, policy_name)
        self.create_role(role_name, assume_role_doc)
        self.attach_policy(role_name, policy_arn, aws_managed_policies)

        try:
            profile_response = self.iam_client.create_instance_profile(
                InstanceProfileName=profile_name
            )
            waiter = self.iam_client.get_waiter("instance_profile_exists")
            waiter.wait(InstanceProfileName=profile_name)
            time.sleep(10)  # wait a little longer
            profile_arn = profile_response["InstanceProfile"]["Arn"]
            self.iam_client.add_role_to_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            log.info("Created profile %s and added role %s.", profile_name, role_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                prof_response = self.iam_client.get_instance_profile(
                    InstanceProfileName=profile_name
                )
                profile_arn = prof_response["InstanceProfile"]["Arn"]
                log.info(
                    "Instance profile %s already exists, nothing to do.", profile_name
                )
            log.error(f"Full error:\n\t{err}")
        return profile_arn
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[CreateInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateInstanceProfile)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_python_3_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def create_policy(name, description, actions, resource_arn):
    """
    Creates a policy that contains a single statement.

    :param name: The name of the policy to create.
    :param description: The description of the policy.
    :param actions: The actions allowed by the policy. These typically take the
                    form of service:action, such as s3:PutObject.
    :param resource_arn: The Amazon Resource Name (ARN) of the resource this policy
                         applies to. This ARN can contain wildcards, such as
                         'arn:aws:s3:::amzn-s3-demo-bucket/*' to allow actions on all objects
                         in the bucket named 'amzn-s3-demo-bucket'.
    :return: The newly created policy.
    """
    policy_doc = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}],
    }
    try:
        policy = iam.create_policy(
            PolicyName=name,
            Description=description,
            PolicyDocument=json.dumps(policy_doc),
        )
        logger.info("Created policy %s.", policy.arn)
    except ClientError:
        logger.exception("Couldn't create policy %s.", name)
        raise
    else:
        return policy
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreatePolicyVersion`
<a name="iam_CreatePolicyVersion_python_3_topic"></a>

次のコード例は、`CreatePolicyVersion` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def create_policy_version(policy_arn, actions, resource_arn, set_as_default):
    """
    Creates a policy version. Policies can have up to five versions. The default
    version is the one that is used for all resources that reference the policy.

    :param policy_arn: The ARN of the policy.
    :param actions: The actions to allow in the policy version.
    :param resource_arn: The ARN of the resource this policy version applies to.
    :param set_as_default: When True, this policy version is set as the default
                           version for the policy. Otherwise, the default
                           is not changed.
    :return: The newly created policy version.
    """
    policy_doc = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}],
    }
    try:
        policy = iam.Policy(policy_arn)
        policy_version = policy.create_version(
            PolicyDocument=json.dumps(policy_doc), SetAsDefault=set_as_default
        )
        logger.info(
            "Created policy version %s for policy %s.",
            policy_version.version_id,
            policy_version.arn,
        )
    except ClientError:
        logger.exception("Couldn't create a policy version for %s.", policy_arn)
        raise
    else:
        return policy_version
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[CreatePolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicyVersion)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_python_3_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
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 Reference*」の「[CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)」を参照してください。

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_python_3_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def create_service_linked_role(service_name, description):
    """
    Creates a service-linked role.

    :param service_name: The name of the service that owns the role.
    :param description: A description to give the role.
    :return: The newly created role.
    """
    try:
        response = iam.meta.client.create_service_linked_role(
            AWSServiceName=service_name, Description=description
        )
        role = iam.Role(response["Role"]["RoleName"])
        logger.info("Created service-linked role %s.", role.name)
    except ClientError:
        logger.exception("Couldn't create service-linked role for %s.", service_name)
        raise
    else:
        return role
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateServiceLinkedRole)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_python_3_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def create_user(user_name):
    """
    Creates a user. By default, a user has no permissions or access keys.

    :param user_name: The name of the user.
    :return: The newly created user.
    """
    try:
        user = iam.create_user(UserName=user_name)
        logger.info("Created user %s.", user.name)
    except ClientError:
        logger.exception("Couldn't create user %s.", user_name)
        raise
    else:
        return user
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[CreateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_python_3_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def delete_key(user_name, key_id):
    """
    Deletes a user's access key.

    :param user_name: The user that owns the key.
    :param key_id: The ID of the key to delete.
    """

    try:
        key = iam.AccessKey(user_name, key_id)
        key.delete()
        logger.info("Deleted access key %s for %s.", key.id, key.user_name)
    except ClientError:
        logger.exception("Couldn't delete key %s for %s", key_id, user_name)
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」で「[DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_python_3_topic"></a>

次のコード例は、`DeleteAccountAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def delete_alias(alias):
    """
    Removes the alias from the current account.

    :param alias: The alias to remove.
    """
    try:
        iam.meta.client.delete_account_alias(AccountAlias=alias)
        logger.info("Removed alias '%s' from your account.", alias)
    except ClientError:
        logger.exception("Couldn't remove alias '%s' from your account.", alias)
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスで「[DeleteAccountAlias](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccountAlias)」を参照してください。**

### `DeleteInstanceProfile`
<a name="iam_DeleteInstanceProfile_python_3_topic"></a>

次のコード例は、`DeleteInstanceProfile` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
この例では、インスタンスプロファイルからロールを削除し、ロールにアタッチされているすべてのポリシーをデタッチし、すべてのリソースを削除します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def delete_instance_profile(self, profile_name: str, role_name: str) -> None:
        """
        Detaches a role from an instance profile, detaches policies from the role,
        and deletes all the resources.

        :param profile_name: The name of the profile to delete.
        :param role_name: The name of the role to delete.
        """
        try:
            self.iam_client.remove_role_from_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            self.iam_client.delete_instance_profile(InstanceProfileName=profile_name)
            log.info("Deleted instance profile %s.", profile_name)
            attached_policies = self.iam_client.list_attached_role_policies(
                RoleName=role_name
            )
            for pol in attached_policies["AttachedPolicies"]:
                self.iam_client.detach_role_policy(
                    RoleName=role_name, PolicyArn=pol["PolicyArn"]
                )
                if not pol["PolicyArn"].startswith("arn:aws:iam::aws"):
                    self.iam_client.delete_policy(PolicyArn=pol["PolicyArn"])
                log.info("Detached and deleted policy %s.", pol["PolicyName"])
            self.iam_client.delete_role(RoleName=role_name)
            log.info("Deleted role %s.", role_name)
        except ClientError as err:
            log.error(
                f"Couldn't delete instance profile {profile_name} or detach "
                f"policies and delete role {role_name}: {err}"
            )
            if err.response["Error"]["Code"] == "NoSuchEntity":
                log.info(
                    "Instance profile %s doesn't exist, nothing to do.", profile_name
                )
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteInstanceProfile)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_python_3_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def delete_policy(policy_arn):
    """
    Deletes a policy.

    :param policy_arn: The ARN of the policy to delete.
    """
    try:
        iam.Policy(policy_arn).delete()
        logger.info("Deleted policy %s.", policy_arn)
    except ClientError:
        logger.exception("Couldn't delete policy %s.", policy_arn)
        raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_python_3_topic"></a>

次のコード例は、`DeleteRole` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def delete_role(role_name):
    """
    Deletes a role.

    :param role_name: The name of the role to delete.
    """
    try:
        iam.Role(role_name).delete()
        logger.info("Deleted role %s.", role_name)
    except ClientError:
        logger.exception("Couldn't delete role %s.", role_name)
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」で「[DeleteRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteRole)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_python_3_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def delete_user(user_name):
    """
    Deletes a user. Before a user can be deleted, all associated resources,
    such as access keys and policies, must be deleted or detached.

    :param user_name: The name of the user.
    """
    try:
        iam.User(user_name).delete()
        logger.info("Deleted user %s.", user_name)
    except ClientError:
        logger.exception("Couldn't delete user %s.", user_name)
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」で「[DeleteUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUser)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_python_3_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
Boto3 Policy オブジェクトを使用して、ロールからポリシーをデタッチします。  

```
def detach_from_role(role_name, policy_arn):
    """
    Detaches a policy from a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Policy(policy_arn).detach_role(RoleName=role_name)
        logger.info("Detached policy %s from role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from role %s.", policy_arn, role_name
        )
        raise
```
Boto3 Role オブジェクトを使用して、ロールからポリシーをデタッチします。  

```
def detach_policy(role_name, policy_arn):
    """
    Detaches a policy from a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Role(role_name).detach_policy(PolicyArn=policy_arn)
        logger.info("Detached policy %s from role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from role %s.", policy_arn, role_name
        )
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DetachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachRolePolicy)」を参照してください。

### `DetachUserPolicy`
<a name="iam_DetachUserPolicy_python_3_topic"></a>

次のコード例は、`DetachUserPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def detach_policy(user_name, policy_arn):
    """
    Detaches a policy from a user.

    :param user_name: The name of the user.
    :param policy_arn: The Amazon Resource Name (ARN) of the policy.
    """
    try:
        iam.User(user_name).detach_policy(PolicyArn=policy_arn)
        logger.info("Detached policy %s from user %s.", policy_arn, user_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from user %s.", policy_arn, user_name
        )
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DetachUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachUserPolicy)」を参照してください。

### `GenerateCredentialReport`
<a name="iam_GenerateCredentialReport_python_3_topic"></a>

次のコード例は、`GenerateCredentialReport` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def generate_credential_report():
    """
    Starts generation of a credentials report about the current account. After
    calling this function to generate the report, call get_credential_report
    to get the latest report. A new report can be generated a minimum of four hours
    after the last one was generated.
    """
    try:
        response = iam.meta.client.generate_credential_report()
        logger.info(
            "Generating credentials report for your account. " "Current state is %s.",
            response["State"],
        )
    except ClientError:
        logger.exception("Couldn't generate a credentials report for your account.")
        raise
    else:
        return response
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GenerateCredentialReport](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GenerateCredentialReport)」を参照してください。

### `GetAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_python_3_topic"></a>

次のコード例は、`GetAccessKeyLastUsed` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def get_last_use(key_id):
    """
    Gets information about when and how a key was last used.

    :param key_id: The ID of the key to look up.
    :return: Information about the key's last use.
    """
    try:
        response = iam.meta.client.get_access_key_last_used(AccessKeyId=key_id)
        last_used_date = response["AccessKeyLastUsed"].get("LastUsedDate", None)
        last_service = response["AccessKeyLastUsed"].get("ServiceName", None)
        logger.info(
            "Key %s was last used by %s on %s to access %s.",
            key_id,
            response["UserName"],
            last_used_date,
            last_service,
        )
    except ClientError:
        logger.exception("Couldn't get last use of key %s.", key_id)
        raise
    else:
        return response
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetAccessKeyLastUsed](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccessKeyLastUsed)」を参照してください。

### `GetAccountAuthorizationDetails`
<a name="iam_GetAccountAuthorizationDetails_python_3_topic"></a>

次のコード例は、`GetAccountAuthorizationDetails` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def get_authorization_details(response_filter):
    """
    Gets an authorization detail report for the current account.

    :param response_filter: A list of resource types to include in the report, such
                            as users or roles. When not specified, all resources
                            are included.
    :return: The authorization detail report.
    """
    try:
        account_details = iam.meta.client.get_account_authorization_details(
            Filter=response_filter
        )
        logger.debug(account_details)
    except ClientError:
        logger.exception("Couldn't get details for your account.")
        raise
    else:
        return account_details
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetAccountAuthorizationDetails](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountAuthorizationDetails)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_python_3_topic"></a>

次のコード例は、`GetAccountPasswordPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def print_password_policy():
    """
    Prints the password policy for the account.
    """
    try:
        pw_policy = iam.AccountPasswordPolicy()
        print("Current account password policy:")
        print(
            f"\tallow_users_to_change_password: {pw_policy.allow_users_to_change_password}"
        )
        print(f"\texpire_passwords: {pw_policy.expire_passwords}")
        print(f"\thard_expiry: {pw_policy.hard_expiry}")
        print(f"\tmax_password_age: {pw_policy.max_password_age}")
        print(f"\tminimum_password_length: {pw_policy.minimum_password_length}")
        print(f"\tpassword_reuse_prevention: {pw_policy.password_reuse_prevention}")
        print(
            f"\trequire_lowercase_characters: {pw_policy.require_lowercase_characters}"
        )
        print(f"\trequire_numbers: {pw_policy.require_numbers}")
        print(f"\trequire_symbols: {pw_policy.require_symbols}")
        print(
            f"\trequire_uppercase_characters: {pw_policy.require_uppercase_characters}"
        )
        printed = True
    except ClientError as error:
        if error.response["Error"]["Code"] == "NoSuchEntity":
            print("The account does not have a password policy set.")
        else:
            logger.exception("Couldn't get account password policy.")
            raise
    else:
        return printed
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountPasswordPolicy)」を参照してください。

### `GetAccountSummary`
<a name="iam_GetAccountSummary_python_3_topic"></a>

次のコード例は、`GetAccountSummary` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def get_summary():
    """
    Gets a summary of account usage.

    :return: The summary of account usage.
    """
    try:
        summary = iam.AccountSummary()
        logger.debug(summary.summary_map)
    except ClientError:
        logger.exception("Couldn't get a summary for your account.")
        raise
    else:
        return summary.summary_map
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetAccountSummary](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountSummary)」を参照してください。

### `GetCredentialReport`
<a name="iam_GetCredentialReport_python_3_topic"></a>

次のコード例は、`GetCredentialReport` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def get_credential_report():
    """
    Gets the most recently generated credentials report about the current account.

    :return: The credentials report.
    """
    try:
        response = iam.meta.client.get_credential_report()
        logger.debug(response["Content"])
    except ClientError:
        logger.exception("Couldn't get credentials report.")
        raise
    else:
        return response["Content"]
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetCredentialReport](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetCredentialReport)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_python_3_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def get_default_policy_statement(policy_arn):
    """
    Gets the statement of the default version of the specified policy.

    :param policy_arn: The ARN of the policy to look up.
    :return: The statement of the default policy version.
    """
    try:
        policy = iam.Policy(policy_arn)
        # To get an attribute of a policy, the SDK first calls get_policy.
        policy_doc = policy.default_version.document
        policy_statement = policy_doc.get("Statement", None)
        logger.info("Got default policy doc for %s.", policy.policy_name)
        logger.info(policy_doc)
    except ClientError:
        logger.exception("Couldn't get default policy statement for %s.", policy_arn)
        raise
    else:
        return policy_statement
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetPolicy)」を参照してください。

### `GetPolicyVersion`
<a name="iam_GetPolicyVersion_python_3_topic"></a>

次のコード例は、`GetPolicyVersion` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def get_default_policy_statement(policy_arn):
    """
    Gets the statement of the default version of the specified policy.

    :param policy_arn: The ARN of the policy to look up.
    :return: The statement of the default policy version.
    """
    try:
        policy = iam.Policy(policy_arn)
        # To get an attribute of a policy, the SDK first calls get_policy.
        policy_doc = policy.default_version.document
        policy_statement = policy_doc.get("Statement", None)
        logger.info("Got default policy doc for %s.", policy.policy_name)
        logger.info(policy_doc)
    except ClientError:
        logger.exception("Couldn't get default policy statement for %s.", policy_arn)
        raise
    else:
        return policy_statement
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetPolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetPolicyVersion)」を参照してください。

### `GetRole`
<a name="iam_GetRole_python_3_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def get_role(role_name):
    """
    Gets a role by name.

    :param role_name: The name of the role to retrieve.
    :return: The specified role.
    """
    try:
        role = iam.Role(role_name)
        role.load()  # calls GetRole to load attributes
        logger.info("Got role with arn %s.", role.arn)
    except ClientError:
        logger.exception("Couldn't get role named %s.", role_name)
        raise
    else:
        return role
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetRole)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_python_3_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_keys(user_name):
    """
    Lists the keys owned by the specified user.

    :param user_name: The name of the user.
    :return: The list of keys owned by the user.
    """
    try:
        keys = list(iam.User(user_name).access_keys.all())
        logger.info("Got %s access keys for %s.", len(keys), user_name)
    except ClientError:
        logger.exception("Couldn't get access keys for %s.", user_name)
        raise
    else:
        return keys
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[ListAccessKeys](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAccessKeys)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_python_3_topic"></a>

次のコード例は、`ListAccountAliases` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_aliases():
    """
    Gets the list of aliases for the current account. An account has at most one alias.

    :return: The list of aliases for the account.
    """
    try:
        response = iam.meta.client.list_account_aliases()
        aliases = response["AccountAliases"]
        if len(aliases) > 0:
            logger.info("Got aliases for your account: %s.", ",".join(aliases))
        else:
            logger.info("Got no aliases for your account.")
    except ClientError:
        logger.exception("Couldn't list aliases for your account.")
        raise
    else:
        return response["AccountAliases"]
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[ListAccountAliases](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAccountAliases)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_python_3_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_attached_policies(role_name):
    """
    Lists policies attached to a role.

    :param role_name: The name of the role to query.
    """
    try:
        role = iam.Role(role_name)
        for policy in role.attached_policies.all():
            logger.info("Got policy %s.", policy.arn)
    except ClientError:
        logger.exception("Couldn't list attached policies for %s.", role_name)
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAttachedRolePolicies)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_python_3_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_groups(count):
    """
    Lists the specified number of groups for the account.

    :param count: The number of groups to list.
    """
    try:
        for group in iam.groups.limit(count):
            logger.info("Group: %s", group.name)
    except ClientError:
        logger.exception("Couldn't list groups for the account.")
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[ListGroups](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListGroups)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_python_3_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_policies(scope):
    """
    Lists the policies in the current account.

    :param scope: Limits the kinds of policies that are returned. For example,
                  'Local' specifies that only locally managed policies are returned.
    :return: The list of policies.
    """
    try:
        policies = list(iam.policies.filter(Scope=scope))
        logger.info("Got %s policies in scope '%s'.", len(policies), scope)
    except ClientError:
        logger.exception("Couldn't get policies for scope '%s'.", scope)
        raise
    else:
        return policies
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListPolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListPolicies)」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_python_3_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_policies(role_name):
    """
    Lists inline policies for a role.

    :param role_name: The name of the role to query.
    """
    try:
        role = iam.Role(role_name)
        for policy in role.policies.all():
            logger.info("Got inline policy %s.", policy.name)
    except ClientError:
        logger.exception("Couldn't list inline policies for %s.", role_name)
        raise
```
+  API の詳細については、**「AWS SDK for Python (Boto3) APIリファレンス」の「[ListRolePolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListRolePolicies)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_python_3_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_roles(count):
    """
    Lists the specified number of roles for the account.

    :param count: The number of roles to list.
    """
    try:
        roles = list(iam.roles.limit(count=count))
        for role in roles:
            logger.info("Role: %s", role.name)
    except ClientError:
        logger.exception("Couldn't list roles for the account.")
        raise
    else:
        return roles
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[ListRoles](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListRoles)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_python_3_topic"></a>

次のコード例は、`ListSAMLProviders` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_saml_providers(count):
    """
    Lists the SAML providers for the account.

    :param count: The maximum number of providers to list.
    """
    try:
        found = 0
        for provider in iam.saml_providers.limit(count):
            logger.info("Got SAML provider %s.", provider.arn)
            found += 1
        if found == 0:
            logger.info("Your account has no SAML providers.")
    except ClientError:
        logger.exception("Couldn't list SAML providers.")
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[ListSAMLProviders](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListSAMLProviders)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_python_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def list_users():
    """
    Lists the users in the current account.

    :return: The list of users.
    """
    try:
        users = list(iam.users.all())
        logger.info("Got %s users.", len(users))
    except ClientError:
        logger.exception("Couldn't get users.")
        raise
    else:
        return users
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListUsers](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListUsers)」を参照してください。

### `UpdateAccessKey`
<a name="iam_UpdateAccessKey_python_3_topic"></a>

次のコード例は、`UpdateAccessKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def update_key(user_name, key_id, activate):
    """
    Updates the status of a key.

    :param user_name: The user that owns the key.
    :param key_id: The ID of the key to update.
    :param activate: When True, the key is activated. Otherwise, the key is deactivated.
    """

    try:
        key = iam.User(user_name).AccessKey(key_id)
        if activate:
            key.activate()
        else:
            key.deactivate()
        logger.info("%s key %s.", "Activated" if activate else "Deactivated", key_id)
    except ClientError:
        logger.exception(
            "Couldn't %s key %s.", "Activate" if activate else "Deactivate", key_id
        )
        raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/UpdateAccessKey)」を参照してください。**

### `UpdateUser`
<a name="iam_UpdateUser_python_3_topic"></a>

次のコード例は、`UpdateUser` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def update_user(user_name, new_user_name):
    """
    Updates a user's name.

    :param user_name: The current name of the user to update.
    :param new_user_name: The new name to assign to the user.
    :return: The updated user.
    """
    try:
        user = iam.User(user_name)
        user.update(NewUserName=new_user_name)
        logger.info("Renamed %s to %s.", user_name, new_user_name)
    except ClientError:
        logger.exception("Couldn't update name for user %s.", user_name)
        raise
    return user
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[UpdateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/UpdateUser)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### レジリエントなサービスの構築と管理
<a name="cross_ResilientService_python_3_topic"></a>

次のコード例は、本、映画、曲のレコメンデーションを返す負荷分散型ウェブサービスの作成方法を示しています。この例は、障害に対するサービスの対応方法と、障害発生時の耐障害性を高めるためにサービスを再構築する方法を示しています。
+ Amazon EC2 Auto Scaling グループを使用して、起動テンプレートに基づいて Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを作成し、インスタンス数を所定の範囲内に維持します。
+ Elastic Load Balancing で HTTP リクエストを処理して配信します。
+ Auto Scaling グループ内のインスタンスの状態を監視し、正常なインスタンスにのみリクエストを転送します。
+ 各 EC2 インスタンスで Python ウェブサーバーを実行して HTTP リクエストを処理します。ウェブサーバーはレコメンデーションとヘルスチェックを返します。
+ Amazon DynamoDB テーブルを使用してレコメンデーションサービスをシミュレートできます。
+  AWS Systems Manager パラメータを更新して、リクエストとヘルスチェックに対するウェブサーバーの応答を制御します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/resilient_service#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class Runner:
    """
    Manages the deployment, demonstration, and destruction of resources for the resilient service.
    """

    def __init__(
        self,
        resource_path: str,
        recommendation: RecommendationService,
        autoscaler: AutoScalingWrapper,
        loadbalancer: ElasticLoadBalancerWrapper,
        param_helper: ParameterHelper,
    ):
        """
        Initializes the Runner class with the necessary parameters.

        :param resource_path: The path to resource files used by this example, such as IAM policies and instance scripts.
        :param recommendation: An instance of the RecommendationService class.
        :param autoscaler: An instance of the AutoScaler class.
        :param loadbalancer: An instance of the LoadBalancer class.
        :param param_helper: An instance of the ParameterHelper class.
        """
        self.resource_path = resource_path
        self.recommendation = recommendation
        self.autoscaler = autoscaler
        self.loadbalancer = loadbalancer
        self.param_helper = param_helper
        self.protocol = "HTTP"
        self.port = 80
        self.ssh_port = 22

        prefix = "doc-example-resilience"
        self.target_group_name = f"{prefix}-tg"
        self.load_balancer_name = f"{prefix}-lb"

    def deploy(self) -> None:
        """
        Deploys the resources required for the resilient service, including the DynamoDB table,
        EC2 instances, Auto Scaling group, and load balancer.
        """
        recommendations_path = f"{self.resource_path}/recommendations.json"
        startup_script = f"{self.resource_path}/server_startup_script.sh"
        instance_policy = f"{self.resource_path}/instance_policy.json"

        logging.info("Starting deployment of resources for the resilient service.")

        logging.info(
            "Creating and populating DynamoDB table '%s'.",
            self.recommendation.table_name,
        )
        self.recommendation.create()
        self.recommendation.populate(recommendations_path)

        logging.info(
            "Creating an EC2 launch template with the startup script '%s'.",
            startup_script,
        )
        self.autoscaler.create_template(startup_script, instance_policy)

        logging.info(
            "Creating an EC2 Auto Scaling group across multiple Availability Zones."
        )
        zones = self.autoscaler.create_autoscaling_group(3)

        logging.info("Creating variables that control the flow of the demo.")
        self.param_helper.reset()

        logging.info("Creating Elastic Load Balancing target group and load balancer.")

        vpc = self.autoscaler.get_default_vpc()
        subnets = self.autoscaler.get_subnets(vpc["VpcId"], zones)
        target_group = self.loadbalancer.create_target_group(
            self.target_group_name, self.protocol, self.port, vpc["VpcId"]
        )
        self.loadbalancer.create_load_balancer(
            self.load_balancer_name, [subnet["SubnetId"] for subnet in subnets]
        )
        self.loadbalancer.create_listener(self.load_balancer_name, target_group)

        self.autoscaler.attach_load_balancer_target_group(target_group)

        logging.info("Verifying access to the load balancer endpoint.")
        endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
        lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)
        current_ip_address = requests.get("http://checkip.amazonaws.com").text.strip()

        if not lb_success:
            logging.warning(
                "Couldn't connect to the load balancer. Verifying that the port is open..."
            )
            sec_group, port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.port, current_ip_address
            )
            sec_group, ssh_port_is_open = self.autoscaler.verify_inbound_port(
                vpc, self.ssh_port, current_ip_address
            )
            if not port_is_open:
                logging.warning(
                    "The default security group for your VPC must allow access from this computer."
                )
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound traffic on port {self.port} from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.port, current_ip_address
                    )
            if not ssh_port_is_open:
                if q.ask(
                    f"Do you want to add a rule to security group {sec_group['GroupId']} to allow\n"
                    f"inbound SSH traffic on port {self.ssh_port} for debugging from your computer's IP address of {current_ip_address}? (y/n) ",
                    q.is_yesno,
                ):
                    self.autoscaler.open_inbound_port(
                        sec_group["GroupId"], self.ssh_port, current_ip_address
                    )
            lb_success = self.loadbalancer.verify_load_balancer_endpoint(endpoint)

        if lb_success:
            logging.info(
                "Load balancer is ready. Access it at: http://%s", current_ip_address
            )
        else:
            logging.error(
                "Couldn't get a successful response from the load balancer endpoint. Please verify your VPC and security group settings."
            )

    def demo_choices(self) -> None:
        """
        Presents choices for interacting with the deployed service, such as sending requests to
        the load balancer or checking the health of the targets.
        """
        actions = [
            "Send a GET request to the load balancer endpoint.",
            "Check the health of load balancer targets.",
            "Go to the next part of the demo.",
        ]
        choice = 0
        while choice != 2:
            logging.info("Choose an action to interact with the service.")
            choice = q.choose("Which action would you like to take? ", actions)
            if choice == 0:
                logging.info("Sending a GET request to the load balancer endpoint.")
                endpoint = self.loadbalancer.get_endpoint(self.load_balancer_name)
                logging.info("GET http://%s", endpoint)
                response = requests.get(f"http://{endpoint}")
                logging.info("Response: %s", response.status_code)
                if response.headers.get("content-type") == "application/json":
                    pp(response.json())
            elif choice == 1:
                logging.info("Checking the health of load balancer targets.")
                health = self.loadbalancer.check_target_health(self.target_group_name)
                for target in health:
                    state = target["TargetHealth"]["State"]
                    logging.info(
                        "Target %s on port %d is %s",
                        target["Target"]["Id"],
                        target["Target"]["Port"],
                        state,
                    )
                    if state != "healthy":
                        logging.warning(
                            "%s: %s",
                            target["TargetHealth"]["Reason"],
                            target["TargetHealth"]["Description"],
                        )
                logging.info(
                    "Note that it can take a minute or two for the health check to update."
                )
            elif choice == 2:
                logging.info("Proceeding to the next part of the demo.")

    def demo(self) -> None:
        """
        Runs the demonstration, showing how the service responds to different failure scenarios
        and how a resilient architecture can keep the service running.
        """
        ssm_only_policy = f"{self.resource_path}/ssm_only_policy.json"

        logging.info("Resetting parameters to starting values for the demo.")
        self.param_helper.reset()

        logging.info(
            "Starting demonstration of the service's resilience under various failure conditions."
        )
        self.demo_choices()

        logging.info(
            "Simulating failure by changing the Systems Manager parameter to a non-existent table."
        )
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info("Sending GET requests will now return failure codes.")
        self.demo_choices()

        logging.info("Switching to static response mode to mitigate failure.")
        self.param_helper.put(self.param_helper.failure_response, "static")
        logging.info("Sending GET requests will now return static responses.")
        self.demo_choices()

        logging.info("Restoring normal operation of the recommendation service.")
        self.param_helper.put(self.param_helper.table, self.recommendation.table_name)

        logging.info(
            "Introducing a failure by assigning bad credentials to one of the instances."
        )
        self.autoscaler.create_instance_profile(
            ssm_only_policy,
            self.autoscaler.bad_creds_policy_name,
            self.autoscaler.bad_creds_role_name,
            self.autoscaler.bad_creds_profile_name,
            ["AmazonSSMManagedInstanceCore"],
        )
        instances = self.autoscaler.get_instances()
        bad_instance_id = instances[0]
        instance_profile = self.autoscaler.get_instance_profile(bad_instance_id)
        logging.info(
            "Replacing instance profile with bad credentials for instance %s.",
            bad_instance_id,
        )
        self.autoscaler.replace_instance_profile(
            bad_instance_id,
            self.autoscaler.bad_creds_profile_name,
            instance_profile["AssociationId"],
        )
        logging.info(
            "Sending GET requests may return either a valid recommendation or a static response."
        )
        self.demo_choices()

        logging.info("Implementing deep health checks to detect unhealthy instances.")
        self.param_helper.put(self.param_helper.health_check, "deep")
        logging.info("Checking the health of the load balancer targets.")
        self.demo_choices()

        logging.info(
            "Terminating the unhealthy instance to let the auto scaler replace it."
        )
        self.autoscaler.terminate_instance(bad_instance_id)
        logging.info("The service remains resilient during instance replacement.")
        self.demo_choices()

        logging.info("Simulating a complete failure of the recommendation service.")
        self.param_helper.put(self.param_helper.table, "this-is-not-a-table")
        logging.info(
            "All instances will report as unhealthy, but the service will still return static responses."
        )
        self.demo_choices()
        self.param_helper.reset()

    def destroy(self, automation=False) -> None:
        """
        Destroys all resources created for the demo, including the load balancer, Auto Scaling group,
        EC2 instances, and DynamoDB table.
        """
        logging.info(
            "This concludes the demo. Preparing to clean up all AWS resources created during the demo."
        )
        if automation:
            cleanup = True
        else:
            cleanup = q.ask(
                "Do you want to clean up all demo resources? (y/n) ", q.is_yesno
            )

        if cleanup:
            logging.info("Deleting load balancer and related resources.")
            self.loadbalancer.delete_load_balancer(self.load_balancer_name)
            self.loadbalancer.delete_target_group(self.target_group_name)
            self.autoscaler.delete_autoscaling_group(self.autoscaler.group_name)
            self.autoscaler.delete_key_pair()
            self.autoscaler.delete_template()
            self.autoscaler.delete_instance_profile(
                self.autoscaler.bad_creds_profile_name,
                self.autoscaler.bad_creds_role_name,
            )
            logging.info("Deleting DynamoDB table and other resources.")
            self.recommendation.destroy()
        else:
            logging.warning(
                "Resources have not been deleted. Ensure you clean them up manually to avoid unexpected charges."
            )


def main() -> None:
    """
    Main function to parse arguments and run the appropriate actions for the demo.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--action",
        required=True,
        choices=["all", "deploy", "demo", "destroy"],
        help="The action to take for the demo. When 'all' is specified, resources are\n"
        "deployed, the demo is run, and resources are destroyed.",
    )
    parser.add_argument(
        "--resource_path",
        default="../../../scenarios/features/resilient_service/resources",
        help="The path to resource files used by this example, such as IAM policies and\n"
        "instance scripts.",
    )
    args = parser.parse_args()

    logging.info("Starting the Resilient Service demo.")

    prefix = "doc-example-resilience"

    # Service Clients
    ddb_client = boto3.client("dynamodb")
    elb_client = boto3.client("elbv2")
    autoscaling_client = boto3.client("autoscaling")
    ec2_client = boto3.client("ec2")
    ssm_client = boto3.client("ssm")
    iam_client = boto3.client("iam")

    # Wrapper instantiations
    recommendation = RecommendationService(
        "doc-example-recommendation-service", ddb_client
    )
    autoscaling_wrapper = AutoScalingWrapper(
        prefix,
        "t3.micro",
        "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2",
        autoscaling_client,
        ec2_client,
        ssm_client,
        iam_client,
    )
    elb_wrapper = ElasticLoadBalancerWrapper(elb_client)
    param_helper = ParameterHelper(recommendation.table_name, ssm_client)

    # Demo invocation
    runner = Runner(
        args.resource_path,
        recommendation,
        autoscaling_wrapper,
        elb_wrapper,
        param_helper,
    )
    actions = [args.action] if args.action != "all" else ["deploy", "demo", "destroy"]
    for action in actions:
        if action == "deploy":
            runner.deploy()
        elif action == "demo":
            runner.demo()
        elif action == "destroy":
            runner.destroy()

    logging.info("Demo completed successfully.")


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    main()
```
Auto Scaling と Amazon EC2 のアクションをラップするクラスを作成します。  

```
class AutoScalingWrapper:
    """
    Encapsulates Amazon EC2 Auto Scaling and EC2 management actions.
    """

    def __init__(
        self,
        resource_prefix: str,
        inst_type: str,
        ami_param: str,
        autoscaling_client: boto3.client,
        ec2_client: boto3.client,
        ssm_client: boto3.client,
        iam_client: boto3.client,
    ):
        """
        Initializes the AutoScaler class with the necessary parameters.

        :param resource_prefix: The prefix for naming AWS resources that are created by this class.
        :param inst_type: The type of EC2 instance to create, such as t3.micro.
        :param ami_param: The Systems Manager parameter used to look up the AMI that is created.
        :param autoscaling_client: A Boto3 EC2 Auto Scaling client.
        :param ec2_client: A Boto3 EC2 client.
        :param ssm_client: A Boto3 Systems Manager client.
        :param iam_client: A Boto3 IAM client.
        """
        self.inst_type = inst_type
        self.ami_param = ami_param
        self.autoscaling_client = autoscaling_client
        self.ec2_client = ec2_client
        self.ssm_client = ssm_client
        self.iam_client = iam_client
        sts_client = boto3.client("sts")
        self.account_id = sts_client.get_caller_identity()["Account"]

        self.key_pair_name = f"{resource_prefix}-key-pair"
        self.launch_template_name = f"{resource_prefix}-template-"
        self.group_name = f"{resource_prefix}-group"

        # Happy path
        self.instance_policy_name = f"{resource_prefix}-pol"
        self.instance_role_name = f"{resource_prefix}-role"
        self.instance_profile_name = f"{resource_prefix}-prof"

        # Failure mode
        self.bad_creds_policy_name = f"{resource_prefix}-bc-pol"
        self.bad_creds_role_name = f"{resource_prefix}-bc-role"
        self.bad_creds_profile_name = f"{resource_prefix}-bc-prof"


    def create_policy(self, policy_file: str, policy_name: str) -> str:
        """
        Creates a new IAM policy or retrieves the ARN of an existing policy.

        :param policy_file: The path to a JSON file that contains the policy definition.
        :param policy_name: The name to give the created policy.
        :return: The ARN of the created or existing policy.
        """
        with open(policy_file) as file:
            policy_doc = file.read()

        try:
            response = self.iam_client.create_policy(
                PolicyName=policy_name, PolicyDocument=policy_doc
            )
            policy_arn = response["Policy"]["Arn"]
            log.info(f"Policy '{policy_name}' created successfully. ARN: {policy_arn}")
            return policy_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the policy already exists, get its ARN
                response = self.iam_client.get_policy(
                    PolicyArn=f"arn:aws:iam::{self.account_id}:policy/{policy_name}"
                )
                policy_arn = response["Policy"]["Arn"]
                log.info(f"Policy '{policy_name}' already exists. ARN: {policy_arn}")
                return policy_arn
            log.error(f"Full error:\n\t{err}")

    def create_role(self, role_name: str, assume_role_doc: dict) -> str:
        """
        Creates a new IAM role or retrieves the ARN of an existing role.

        :param role_name: The name to give the created role.
        :param assume_role_doc: The assume role policy document that specifies which
                                entities can assume the role.
        :return: The ARN of the created or existing role.
        """
        try:
            response = self.iam_client.create_role(
                RoleName=role_name, AssumeRolePolicyDocument=json.dumps(assume_role_doc)
            )
            role_arn = response["Role"]["Arn"]
            log.info(f"Role '{role_name}' created successfully. ARN: {role_arn}")
            return role_arn

        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                # If the role already exists, get its ARN
                response = self.iam_client.get_role(RoleName=role_name)
                role_arn = response["Role"]["Arn"]
                log.info(f"Role '{role_name}' already exists. ARN: {role_arn}")
                return role_arn
            log.error(f"Full error:\n\t{err}")

    def attach_policy(
        self,
        role_name: str,
        policy_arn: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> None:
        """
        Attaches an IAM policy to a role and optionally attaches additional AWS-managed policies.

        :param role_name: The name of the role to attach the policy to.
        :param policy_arn: The ARN of the policy to attach.
        :param aws_managed_policies: A tuple of AWS-managed policy names to attach to the role.
        """
        try:
            self.iam_client.attach_role_policy(RoleName=role_name, PolicyArn=policy_arn)
            for aws_policy in aws_managed_policies:
                self.iam_client.attach_role_policy(
                    RoleName=role_name,
                    PolicyArn=f"arn:aws:iam::aws:policy/{aws_policy}",
                )
            log.info(f"Attached policy {policy_arn} to role {role_name}.")
        except ClientError as err:
            log.error(f"Failed to attach policy {policy_arn} to role {role_name}.")
            log.error(f"Full error:\n\t{err}")

    def create_instance_profile(
        self,
        policy_file: str,
        policy_name: str,
        role_name: str,
        profile_name: str,
        aws_managed_policies: Tuple[str, ...] = (),
    ) -> str:
        """
        Creates a policy, role, and profile that is associated with instances created by
        this class. An instance's associated profile defines a role that is assumed by the
        instance. The role has attached policies that specify the AWS permissions granted to
        clients that run on the instance.

        :param policy_file: The name of a JSON file that contains the policy definition to
                            create and attach to the role.
        :param policy_name: The name to give the created policy.
        :param role_name: The name to give the created role.
        :param profile_name: The name to the created profile.
        :param aws_managed_policies: Additional AWS-managed policies that are attached to
                                     the role, such as AmazonSSMManagedInstanceCore to grant
                                     use of Systems Manager to send commands to the instance.
        :return: The ARN of the profile that is created.
        """
        assume_role_doc = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"Service": "ec2.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        policy_arn = self.create_policy(policy_file, policy_name)
        self.create_role(role_name, assume_role_doc)
        self.attach_policy(role_name, policy_arn, aws_managed_policies)

        try:
            profile_response = self.iam_client.create_instance_profile(
                InstanceProfileName=profile_name
            )
            waiter = self.iam_client.get_waiter("instance_profile_exists")
            waiter.wait(InstanceProfileName=profile_name)
            time.sleep(10)  # wait a little longer
            profile_arn = profile_response["InstanceProfile"]["Arn"]
            self.iam_client.add_role_to_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            log.info("Created profile %s and added role %s.", profile_name, role_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "EntityAlreadyExists":
                prof_response = self.iam_client.get_instance_profile(
                    InstanceProfileName=profile_name
                )
                profile_arn = prof_response["InstanceProfile"]["Arn"]
                log.info(
                    "Instance profile %s already exists, nothing to do.", profile_name
                )
            log.error(f"Full error:\n\t{err}")
        return profile_arn


    def get_instance_profile(self, instance_id: str) -> Dict[str, Any]:
        """
        Gets data about the profile associated with an instance.

        :param instance_id: The ID of the instance to look up.
        :return: The profile data.
        """
        try:
            response = self.ec2_client.describe_iam_instance_profile_associations(
                Filters=[{"Name": "instance-id", "Values": [instance_id]}]
            )
            if not response["IamInstanceProfileAssociations"]:
                log.info(f"No instance profile found for instance {instance_id}.")
            profile_data = response["IamInstanceProfileAssociations"][0]
            log.info(f"Retrieved instance profile for instance {instance_id}.")
            return profile_data
        except ClientError as err:
            log.error(
                f"Failed to retrieve instance profile for instance {instance_id}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidInstanceID.NotFound":
                log.error(f"The instance ID '{instance_id}' does not exist.")
            log.error(f"Full error:\n\t{err}")


    def replace_instance_profile(
        self,
        instance_id: str,
        new_instance_profile_name: str,
        profile_association_id: str,
    ) -> None:
        """
        Replaces the profile associated with a running instance. After the profile is
        replaced, the instance is rebooted to ensure that it uses the new profile. When
        the instance is ready, Systems Manager is used to restart the Python web server.

        :param instance_id: The ID of the instance to restart.
        :param new_instance_profile_name: The name of the new profile to associate with
                                          the specified instance.
        :param profile_association_id: The ID of the existing profile association for the
                                       instance.
        """
        try:
            self.ec2_client.replace_iam_instance_profile_association(
                IamInstanceProfile={"Name": new_instance_profile_name},
                AssociationId=profile_association_id,
            )
            log.info(
                "Replaced instance profile for association %s with profile %s.",
                profile_association_id,
                new_instance_profile_name,
            )
            time.sleep(5)

            self.ec2_client.reboot_instances(InstanceIds=[instance_id])
            log.info("Rebooting instance %s.", instance_id)
            waiter = self.ec2_client.get_waiter("instance_running")
            log.info("Waiting for instance %s to be running.", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info("Instance %s is now running.", instance_id)

            self.ssm_client.send_command(
                InstanceIds=[instance_id],
                DocumentName="AWS-RunShellScript",
                Parameters={"commands": ["cd / && sudo python3 server.py 80"]},
            )
            log.info(f"Restarted the Python web server on instance '{instance_id}'.")
        except ClientError as err:
            log.error("Failed to replace instance profile.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidAssociationID.NotFound":
                log.error(
                    f"Association ID '{profile_association_id}' does not exist."
                    "Please check the association ID and try again."
                )
            if error_code == "InvalidInstanceId":
                log.error(
                    f"The specified instance ID '{instance_id}' does not exist or is not available for SSM. "
                    f"Please verify the instance ID and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_instance_profile(self, profile_name: str, role_name: str) -> None:
        """
        Detaches a role from an instance profile, detaches policies from the role,
        and deletes all the resources.

        :param profile_name: The name of the profile to delete.
        :param role_name: The name of the role to delete.
        """
        try:
            self.iam_client.remove_role_from_instance_profile(
                InstanceProfileName=profile_name, RoleName=role_name
            )
            self.iam_client.delete_instance_profile(InstanceProfileName=profile_name)
            log.info("Deleted instance profile %s.", profile_name)
            attached_policies = self.iam_client.list_attached_role_policies(
                RoleName=role_name
            )
            for pol in attached_policies["AttachedPolicies"]:
                self.iam_client.detach_role_policy(
                    RoleName=role_name, PolicyArn=pol["PolicyArn"]
                )
                if not pol["PolicyArn"].startswith("arn:aws:iam::aws"):
                    self.iam_client.delete_policy(PolicyArn=pol["PolicyArn"])
                log.info("Detached and deleted policy %s.", pol["PolicyName"])
            self.iam_client.delete_role(RoleName=role_name)
            log.info("Deleted role %s.", role_name)
        except ClientError as err:
            log.error(
                f"Couldn't delete instance profile {profile_name} or detach "
                f"policies and delete role {role_name}: {err}"
            )
            if err.response["Error"]["Code"] == "NoSuchEntity":
                log.info(
                    "Instance profile %s doesn't exist, nothing to do.", profile_name
                )


    def create_key_pair(self, key_pair_name: str) -> None:
        """
        Creates a new key pair.

        :param key_pair_name: The name of the key pair to create.
        """
        try:
            response = self.ec2_client.create_key_pair(KeyName=key_pair_name)
            with open(f"{key_pair_name}.pem", "w") as file:
                file.write(response["KeyMaterial"])
            chmod(f"{key_pair_name}.pem", 0o600)
            log.info("Created key pair %s.", key_pair_name)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to create key pair {key_pair_name}.")
            if error_code == "InvalidKeyPair.Duplicate":
                log.error(f"A key pair with the name '{key_pair_name}' already exists.")
            log.error(f"Full error:\n\t{err}")


    def delete_key_pair(self) -> None:
        """
        Deletes a key pair.
        """
        try:
            self.ec2_client.delete_key_pair(KeyName=self.key_pair_name)
            remove(f"{self.key_pair_name}.pem")
            log.info("Deleted key pair %s.", self.key_pair_name)
        except ClientError as err:
            log.error(f"Couldn't delete key pair '{self.key_pair_name}'.")
            log.error(f"Full error:\n\t{err}")
        except FileNotFoundError as err:
            log.info("Key pair %s doesn't exist, nothing to do.", self.key_pair_name)
            log.error(f"Full error:\n\t{err}")


    def create_template(
        self, server_startup_script_file: str, instance_policy_file: str
    ) -> Dict[str, Any]:
        """
        Creates an Amazon EC2 launch template to use with Amazon EC2 Auto Scaling. The
        launch template specifies a Bash script in its user data field that runs after
        the instance is started. This script installs Python packages and starts a
        Python web server on the instance.

        :param server_startup_script_file: The path to a Bash script file that is run
                                           when an instance starts.
        :param instance_policy_file: The path to a file that defines a permissions policy
                                     to create and attach to the instance profile.
        :return: Information about the newly created template.
        """
        template = {}
        try:
            # Create key pair and instance profile
            self.create_key_pair(self.key_pair_name)
            self.create_instance_profile(
                instance_policy_file,
                self.instance_policy_name,
                self.instance_role_name,
                self.instance_profile_name,
            )

            # Read the startup script
            with open(server_startup_script_file) as file:
                start_server_script = file.read()

            # Get the latest AMI ID
            ami_latest = self.ssm_client.get_parameter(Name=self.ami_param)
            ami_id = ami_latest["Parameter"]["Value"]

            # Create the launch template
            lt_response = self.ec2_client.create_launch_template(
                LaunchTemplateName=self.launch_template_name,
                LaunchTemplateData={
                    "InstanceType": self.inst_type,
                    "ImageId": ami_id,
                    "IamInstanceProfile": {"Name": self.instance_profile_name},
                    "UserData": base64.b64encode(
                        start_server_script.encode(encoding="utf-8")
                    ).decode(encoding="utf-8"),
                    "KeyName": self.key_pair_name,
                },
            )
            template = lt_response["LaunchTemplate"]
            log.info(
                f"Created launch template {self.launch_template_name} for AMI {ami_id} on {self.inst_type}."
            )
        except ClientError as err:
            log.error(f"Failed to create launch template {self.launch_template_name}.")
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidLaunchTemplateName.AlreadyExistsException":
                log.info(
                    f"Launch template {self.launch_template_name} already exists, nothing to do."
                )
            log.error(f"Full error:\n\t{err}")
        return template


    def delete_template(self):
        """
        Deletes a launch template.
        """
        try:
            self.ec2_client.delete_launch_template(
                LaunchTemplateName=self.launch_template_name
            )
            self.delete_instance_profile(
                self.instance_profile_name, self.instance_role_name
            )
            log.info("Launch template %s deleted.", self.launch_template_name)
        except ClientError as err:
            if (
                err.response["Error"]["Code"]
                == "InvalidLaunchTemplateName.NotFoundException"
            ):
                log.info(
                    "Launch template %s does not exist, nothing to do.",
                    self.launch_template_name,
                )
            log.error(f"Full error:\n\t{err}")


    def get_availability_zones(self) -> List[str]:
        """
        Gets a list of Availability Zones in the AWS Region of the Amazon EC2 client.

        :return: The list of Availability Zones for the client Region.
        """
        try:
            response = self.ec2_client.describe_availability_zones()
            zones = [zone["ZoneName"] for zone in response["AvailabilityZones"]]
            log.info(f"Retrieved {len(zones)} availability zones: {zones}.")
        except ClientError as err:
            log.error("Failed to retrieve availability zones.")
            log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def create_autoscaling_group(self, group_size: int) -> List[str]:
        """
        Creates an EC2 Auto Scaling group with the specified size.

        :param group_size: The number of instances to set for the minimum and maximum in
                           the group.
        :return: The list of Availability Zones specified for the group.
        """
        try:
            zones = self.get_availability_zones()
            self.autoscaling_client.create_auto_scaling_group(
                AutoScalingGroupName=self.group_name,
                AvailabilityZones=zones,
                LaunchTemplate={
                    "LaunchTemplateName": self.launch_template_name,
                    "Version": "$Default",
                },
                MinSize=group_size,
                MaxSize=group_size,
            )
            log.info(
                f"Created EC2 Auto Scaling group {self.group_name} with availability zones {zones}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            if error_code == "AlreadyExists":
                log.info(
                    f"EC2 Auto Scaling group {self.group_name} already exists, nothing to do."
                )
            else:
                log.error(f"Failed to create EC2 Auto Scaling group {self.group_name}.")
                log.error(f"Full error:\n\t{err}")
        else:
            return zones


    def get_instances(self) -> List[str]:
        """
        Gets data about the instances in the EC2 Auto Scaling group.

        :return: A list of instance IDs in the Auto Scaling group.
        """
        try:
            as_response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[self.group_name]
            )
            instance_ids = [
                i["InstanceId"]
                for i in as_response["AutoScalingGroups"][0]["Instances"]
            ]
            log.info(
                f"Retrieved {len(instance_ids)} instances for Auto Scaling group {self.group_name}."
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to retrieve instances for Auto Scaling group {self.group_name}."
            )
            if error_code == "ResourceNotFound":
                log.error(f"The Auto Scaling group '{self.group_name}' does not exist.")
            log.error(f"Full error:\n\t{err}")
        else:
            return instance_ids


    def terminate_instance(self, instance_id: str, decrementsetting=False) -> None:
        """
        Terminates an instance in an EC2 Auto Scaling group. After an instance is
        terminated, it can no longer be accessed.

        :param instance_id: The ID of the instance to terminate.
        :param decrementsetting: If True, do not replace terminated instances.
        """
        try:
            self.autoscaling_client.terminate_instance_in_auto_scaling_group(
                InstanceId=instance_id,
                ShouldDecrementDesiredCapacity=decrementsetting,
            )
            log.info("Terminated instance %s.", instance_id)

            # Adding a waiter to ensure the instance is terminated
            waiter = self.ec2_client.get_waiter("instance_terminated")
            log.info("Waiting for instance %s to be terminated...", instance_id)
            waiter.wait(InstanceIds=[instance_id])
            log.info(
                f"Instance '{instance_id}' has been terminated and will be replaced."
            )

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to terminate instance '{instance_id}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to terminate the instance again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            log.error(f"Full error:\n\t{err}")

    def attach_load_balancer_target_group(
        self, lb_target_group: Dict[str, Any]
    ) -> None:
        """
        Attaches an Elastic Load Balancing (ELB) target group to this EC2 Auto Scaling group.
        The target group specifies how the load balancer forwards requests to the instances
        in the group.

        :param lb_target_group: Data about the ELB target group to attach.
        """
        try:
            self.autoscaling_client.attach_load_balancer_target_groups(
                AutoScalingGroupName=self.group_name,
                TargetGroupARNs=[lb_target_group["TargetGroupArn"]],
            )
            log.info(
                "Attached load balancer target group %s to auto scaling group %s.",
                lb_target_group["TargetGroupName"],
                self.group_name,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to attach load balancer target group '{lb_target_group['TargetGroupName']}'."
            )
            if error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the resource."
                )
            elif error_code == "ServiceLinkedRoleFailure":
                log.error(
                    "The operation failed because the service-linked role is not ready or does not exist. "
                    "Check that the service-linked role exists and is correctly configured."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_autoscaling_group(self, group_name: str) -> None:
        """
        Terminates all instances in the group, then deletes the EC2 Auto Scaling group.

        :param group_name: The name of the group to delete.
        """
        try:
            response = self.autoscaling_client.describe_auto_scaling_groups(
                AutoScalingGroupNames=[group_name]
            )
            groups = response.get("AutoScalingGroups", [])
            if len(groups) > 0:
                self.autoscaling_client.update_auto_scaling_group(
                    AutoScalingGroupName=group_name, MinSize=0
                )
                instance_ids = [inst["InstanceId"] for inst in groups[0]["Instances"]]
                for inst_id in instance_ids:
                    self.terminate_instance(inst_id)

                # Wait for all instances to be terminated
                if instance_ids:
                    waiter = self.ec2_client.get_waiter("instance_terminated")
                    log.info("Waiting for all instances to be terminated...")
                    waiter.wait(InstanceIds=instance_ids)
                    log.info("All instances have been terminated.")
            else:
                log.info(f"No groups found named '{group_name}'! Nothing to do.")
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete Auto Scaling group '{group_name}'.")
            if error_code == "ScalingActivityInProgressFault":
                log.error(
                    "Scaling activity is currently in progress. "
                    "Wait for the scaling activity to complete before attempting to delete the group again."
                )
            elif error_code == "ResourceContentionFault":
                log.error(
                    "The request failed due to a resource contention issue. "
                    "Ensure that no conflicting operations are being performed on the group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_default_vpc(self) -> Dict[str, Any]:
        """
        Gets the default VPC for the account.

        :return: Data about the default VPC.
        """
        try:
            response = self.ec2_client.describe_vpcs(
                Filters=[{"Name": "is-default", "Values": ["true"]}]
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error("Failed to retrieve the default VPC.")
            if error_code == "UnauthorizedOperation":
                log.error(
                    "You do not have the necessary permissions to describe VPCs. "
                    "Ensure that your AWS IAM user or role has the correct permissions."
                )
            elif error_code == "InvalidParameterValue":
                log.error(
                    "One or more parameters are invalid. Check the request parameters."
                )

            log.error(f"Full error:\n\t{err}")
        else:
            if "Vpcs" in response and response["Vpcs"]:
                log.info(f"Retrieved default VPC: {response['Vpcs'][0]['VpcId']}")
                return response["Vpcs"][0]
            else:
                pass


    def verify_inbound_port(
        self, vpc: Dict[str, Any], port: int, ip_address: str
    ) -> Tuple[Dict[str, Any], bool]:
        """
        Verify the default security group of the specified VPC allows ingress from this
        computer. This can be done by allowing ingress from this computer's IP
        address. In some situations, such as connecting from a corporate network, you
        must instead specify a prefix list ID. You can also temporarily open the port to
        any IP address while running this example. If you do, be sure to remove public
        access when you're done.

        :param vpc: The VPC used by this example.
        :param port: The port to verify.
        :param ip_address: This computer's IP address.
        :return: The default security group of the specified VPC, and a value that indicates
                 whether the specified port is open.
        """
        try:
            response = self.ec2_client.describe_security_groups(
                Filters=[
                    {"Name": "group-name", "Values": ["default"]},
                    {"Name": "vpc-id", "Values": [vpc["VpcId"]]},
                ]
            )
            sec_group = response["SecurityGroups"][0]
            port_is_open = False
            log.info(f"Found default security group {sec_group['GroupId']}.")

            for ip_perm in sec_group["IpPermissions"]:
                if ip_perm.get("FromPort", 0) == port:
                    log.info(f"Found inbound rule: {ip_perm}")
                    for ip_range in ip_perm["IpRanges"]:
                        cidr = ip_range.get("CidrIp", "")
                        if cidr.startswith(ip_address) or cidr == "0.0.0.0/0":
                            port_is_open = True
                    if ip_perm["PrefixListIds"]:
                        port_is_open = True
                    if not port_is_open:
                        log.info(
                            f"The inbound rule does not appear to be open to either this computer's IP "
                            f"address of {ip_address}, to all IP addresses (0.0.0.0/0), or to a prefix list ID."
                        )
                    else:
                        break
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to verify inbound rule for port {port} for VPC {vpc['VpcId']}."
            )
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    f"The specified VPC ID '{vpc['VpcId']}' does not exist. Please check the VPC ID."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return sec_group, port_is_open


    def open_inbound_port(self, sec_group_id: str, port: int, ip_address: str) -> None:
        """
        Add an ingress rule to the specified security group that allows access on the
        specified port from the specified IP address.

        :param sec_group_id: The ID of the security group to modify.
        :param port: The port to open.
        :param ip_address: The IP address that is granted access.
        """
        try:
            self.ec2_client.authorize_security_group_ingress(
                GroupId=sec_group_id,
                CidrIp=f"{ip_address}/32",
                FromPort=port,
                ToPort=port,
                IpProtocol="tcp",
            )
            log.info(
                "Authorized ingress to %s on port %s from %s.",
                sec_group_id,
                port,
                ip_address,
            )
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to authorize ingress to security group '{sec_group_id}' on port {port} from {ip_address}."
            )
            if error_code == "InvalidGroupId.Malformed":
                log.error(
                    "The security group ID is malformed. "
                    "Please verify that the security group ID is correct."
                )
            elif error_code == "InvalidPermission.Duplicate":
                log.error(
                    "The specified rule already exists in the security group. "
                    "Check the existing rules for this security group."
                )
            log.error(f"Full error:\n\t{err}")


    def get_subnets(self, vpc_id: str, zones: List[str] = None) -> List[Dict[str, Any]]:
        """
        Gets the default subnets in a VPC for a specified list of Availability Zones.

        :param vpc_id: The ID of the VPC to look up.
        :param zones: The list of Availability Zones to look up.
        :return: The list of subnets found.
        """
        # Ensure that 'zones' is a list, even if None is passed
        if zones is None:
            zones = []
        try:
            paginator = self.ec2_client.get_paginator("describe_subnets")
            page_iterator = paginator.paginate(
                Filters=[
                    {"Name": "vpc-id", "Values": [vpc_id]},
                    {"Name": "availability-zone", "Values": zones},
                    {"Name": "default-for-az", "Values": ["true"]},
                ]
            )

            subnets = []
            for page in page_iterator:
                subnets.extend(page["Subnets"])

            log.info("Found %s subnets for the specified zones.", len(subnets))
            return subnets
        except ClientError as err:
            log.error(
                f"Failed to retrieve subnets for VPC '{vpc_id}' in zones {zones}."
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "InvalidVpcID.NotFound":
                log.error(
                    "The specified VPC ID does not exist. "
                    "Please check the VPC ID and try again."
                )
            # Add more error-specific handling as needed
            log.error(f"Full error:\n\t{err}")
```
Elastic Load Balancing のアクションをラップするクラスを作成します。  

```
class ElasticLoadBalancerWrapper:
    """Encapsulates Elastic Load Balancing (ELB) actions."""

    def __init__(self, elb_client: boto3.client):
        """
        Initializes the LoadBalancer class with the necessary parameters.
        """
        self.elb_client = elb_client


    def create_target_group(
        self, target_group_name: str, protocol: str, port: int, vpc_id: str
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing target group. The target group specifies how
        the load balancer forwards requests to instances in the group and how instance
        health is checked.

        To speed up this demo, the health check is configured with shortened times and
        lower thresholds. In production, you might want to decrease the sensitivity of
        your health checks to avoid unwanted failures.

        :param target_group_name: The name of the target group to create.
        :param protocol: The protocol to use to forward requests, such as 'HTTP'.
        :param port: The port to use to forward requests, such as 80.
        :param vpc_id: The ID of the VPC in which the load balancer exists.
        :return: Data about the newly created target group.
        """
        try:
            response = self.elb_client.create_target_group(
                Name=target_group_name,
                Protocol=protocol,
                Port=port,
                HealthCheckPath="/healthcheck",
                HealthCheckIntervalSeconds=10,
                HealthCheckTimeoutSeconds=5,
                HealthyThresholdCount=2,
                UnhealthyThresholdCount=2,
                VpcId=vpc_id,
            )
            target_group = response["TargetGroups"][0]
            log.info(f"Created load balancing target group '{target_group_name}'.")
            return target_group
        except ClientError as err:
            log.error(
                f"Couldn't create load balancing target group '{target_group_name}'."
            )
            error_code = err.response["Error"]["Code"]

            if error_code == "DuplicateTargetGroupName":
                log.error(
                    f"Target group name {target_group_name} already exists. "
                    "Check if the target group already exists."
                    "Consider using a different name or deleting the existing target group if appropriate."
                )
            elif error_code == "TooManyTargetGroups":
                log.error(
                    "Too many target groups exist in the account. "
                    "Consider deleting unused target groups to create space for new ones."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_target_group(self, target_group_name) -> None:
        """
        Deletes the target group.
        """
        try:
            # Describe the target group to get its ARN
            response = self.elb_client.describe_target_groups(Names=[target_group_name])
            tg_arn = response["TargetGroups"][0]["TargetGroupArn"]

            # Delete the target group
            self.elb_client.delete_target_group(TargetGroupArn=tg_arn)
            log.info("Deleted load balancing target group %s.", target_group_name)

            # Use a custom waiter to wait until the target group is no longer available
            self.wait_for_target_group_deletion(self.elb_client, tg_arn)
            log.info("Target group %s successfully deleted.", target_group_name)

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to delete target group '{target_group_name}'.")
            if error_code == "TargetGroupNotFound":
                log.error(
                    "Load balancer target group either already deleted or never existed. "
                    "Verify the name and check that the resource exists in the AWS Console."
                )
            elif error_code == "ResourceInUseException":
                log.error(
                    "Target group still in use by another resource. "
                    "Ensure that the target group is no longer associated with any load balancers or resources.",
                )
            log.error(f"Full error:\n\t{err}")

    def wait_for_target_group_deletion(
        self, elb_client, target_group_arn, max_attempts=10, delay=30
    ):
        for attempt in range(max_attempts):
            try:
                elb_client.describe_target_groups(TargetGroupArns=[target_group_arn])
                print(
                    f"Attempt {attempt + 1}: Target group {target_group_arn} still exists."
                )
            except ClientError as e:
                if e.response["Error"]["Code"] == "TargetGroupNotFound":
                    print(
                        f"Target group {target_group_arn} has been successfully deleted."
                    )
                    return
                else:
                    raise
            time.sleep(delay)
        raise TimeoutError(
            f"Target group {target_group_arn} was not deleted after {max_attempts * delay} seconds."
        )


    def create_load_balancer(
        self,
        load_balancer_name: str,
        subnet_ids: List[str],
    ) -> Dict[str, Any]:
        """
        Creates an Elastic Load Balancing load balancer that uses the specified subnets
        and forwards requests to the specified target group.

        :param load_balancer_name: The name of the load balancer to create.
        :param subnet_ids: A list of subnets to associate with the load balancer.
        :return: Data about the newly created load balancer.
        """
        try:
            response = self.elb_client.create_load_balancer(
                Name=load_balancer_name, Subnets=subnet_ids
            )
            load_balancer = response["LoadBalancers"][0]
            log.info(f"Created load balancer '{load_balancer_name}'.")

            waiter = self.elb_client.get_waiter("load_balancer_available")
            log.info(
                f"Waiting for load balancer '{load_balancer_name}' to be available..."
            )
            waiter.wait(Names=[load_balancer_name])
            log.info(f"Load balancer '{load_balancer_name}' is now available!")

        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to create load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "DuplicateLoadBalancerNameException":
                log.error(
                    f"A load balancer with the name '{load_balancer_name}' already exists. "
                    "Load balancer names must be unique within the AWS region. "
                    "Please choose a different name and try again."
                )
            if error_code == "TooManyLoadBalancersException":
                log.error(
                    "The maximum number of load balancers has been reached in this account and region. "
                    "You can delete unused load balancers or request an increase in the service quota from AWS Support."
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return load_balancer


    def create_listener(
        self,
        load_balancer_name: str,
        target_group: Dict[str, Any],
    ) -> Dict[str, Any]:
        """
        Creates a listener for the specified load balancer that forwards requests to the
        specified target group.

        :param load_balancer_name: The name of the load balancer to create a listener for.
        :param target_group: An existing target group that is added as a listener to the
                             load balancer.
        :return: Data about the newly created listener.
        """
        try:
            # Retrieve the load balancer ARN
            load_balancer_response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            load_balancer_arn = load_balancer_response["LoadBalancers"][0][
                "LoadBalancerArn"
            ]

            # Create the listener
            response = self.elb_client.create_listener(
                LoadBalancerArn=load_balancer_arn,
                Protocol=target_group["Protocol"],
                Port=target_group["Port"],
                DefaultActions=[
                    {
                        "Type": "forward",
                        "TargetGroupArn": target_group["TargetGroupArn"],
                    }
                ],
            )
            log.info(
                f"Created listener to forward traffic from load balancer '{load_balancer_name}' to target group '{target_group['TargetGroupName']}'."
            )
            return response["Listeners"][0]
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Failed to add a listener on '{load_balancer_name}' for target group '{target_group['TargetGroupName']}'."
            )

            if error_code == "ListenerNotFoundException":
                log.error(
                    f"The listener could not be found for the load balancer '{load_balancer_name}'. "
                    "Please check the load balancer name and target group configuration."
                )
            if error_code == "InvalidConfigurationRequestException":
                log.error(
                    f"The configuration provided for the listener on load balancer '{load_balancer_name}' is invalid. "
                    "Please review the provided protocol, port, and target group settings."
                )
            log.error(f"Full error:\n\t{err}")


    def delete_load_balancer(self, load_balancer_name) -> None:
        """
        Deletes a load balancer.

        :param load_balancer_name: The name of the load balancer to delete.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            lb_arn = response["LoadBalancers"][0]["LoadBalancerArn"]
            self.elb_client.delete_load_balancer(LoadBalancerArn=lb_arn)
            log.info("Deleted load balancer %s.", load_balancer_name)
            waiter = self.elb_client.get_waiter("load_balancers_deleted")
            log.info("Waiting for load balancer to be deleted...")
            waiter.wait(Names=[load_balancer_name])
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(
                f"Couldn't delete load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}"
            )

            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    f"The load balancer '{load_balancer_name}' does not exist. "
                    "Please check the name and try again."
                )
            log.error(f"Full error:\n\t{err}")


    def get_endpoint(self, load_balancer_name) -> str:
        """
        Gets the HTTP endpoint of the load balancer.

        :return: The endpoint.
        """
        try:
            response = self.elb_client.describe_load_balancers(
                Names=[load_balancer_name]
            )
            return response["LoadBalancers"][0]["DNSName"]
        except ClientError as err:
            log.error(
                f"Couldn't get the endpoint for load balancer {load_balancer_name}"
            )
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Verify load balancer name and ensure it exists in the AWS console."
                )
            log.error(f"Full error:\n\t{err}")

    @staticmethod
    def verify_load_balancer_endpoint(endpoint) -> bool:
        """
        Verify this computer can successfully send a GET request to the load balancer endpoint.

        :param endpoint: The endpoint to verify.
        :return: True if the GET request is successful, False otherwise.
        """
        retries = 3
        verified = False
        while not verified and retries > 0:
            try:
                lb_response = requests.get(f"http://{endpoint}")
                log.info(
                    "Got response %s from load balancer endpoint.",
                    lb_response.status_code,
                )
                if lb_response.status_code == 200:
                    verified = True
                else:
                    retries = 0
            except requests.exceptions.ConnectionError:
                log.info(
                    "Got connection error from load balancer endpoint, retrying..."
                )
                retries -= 1
                time.sleep(10)
        return verified

    def check_target_health(self, target_group_name: str) -> List[Dict[str, Any]]:
        """
        Checks the health of the instances in the target group.

        :return: The health status of the target group.
        """
        try:
            tg_response = self.elb_client.describe_target_groups(
                Names=[target_group_name]
            )
            health_response = self.elb_client.describe_target_health(
                TargetGroupArn=tg_response["TargetGroups"][0]["TargetGroupArn"]
            )
        except ClientError as err:
            log.error(f"Couldn't check health of {target_group_name} target(s).")
            error_code = err.response["Error"]["Code"]
            if error_code == "LoadBalancerNotFoundException":
                log.error(
                    "Load balancer associated with the target group was not found. "
                    "Ensure the load balancer exists, is in the correct AWS region, and "
                    "that you have the necessary permissions to access it.",
                )
            elif error_code == "TargetGroupNotFoundException":
                log.error(
                    "Target group was not found. "
                    "Verify the target group name, check that it exists in the correct region, "
                    "and ensure it has not been deleted or created in a different account.",
                )
            log.error(f"Full error:\n\t{err}")
        else:
            return health_response["TargetHealthDescriptions"]
```
DynamoDB を使用してレコメンデーションサービスをシミュレートするクラスを作成します。  

```
class RecommendationService:
    """
    Encapsulates a DynamoDB table to use as a service that recommends books, movies,
    and songs.
    """

    def __init__(self, table_name: str, dynamodb_client: boto3.client):
        """
        Initializes the RecommendationService class with the necessary parameters.

        :param table_name: The name of the DynamoDB recommendations table.
        :param dynamodb_client: A Boto3 DynamoDB client.
        """
        self.table_name = table_name
        self.dynamodb_client = dynamodb_client

    def create(self) -> Dict[str, Any]:
        """
        Creates a DynamoDB table to use as a recommendation service. The table has a
        hash key named 'MediaType' that defines the type of media recommended, such as
        Book or Movie, and a range key named 'ItemId' that, combined with the MediaType,
        forms a unique identifier for the recommended item.

        :return: Data about the newly created table.
        :raises RecommendationServiceError: If the table creation fails.
        """
        try:
            response = self.dynamodb_client.create_table(
                TableName=self.table_name,
                AttributeDefinitions=[
                    {"AttributeName": "MediaType", "AttributeType": "S"},
                    {"AttributeName": "ItemId", "AttributeType": "N"},
                ],
                KeySchema=[
                    {"AttributeName": "MediaType", "KeyType": "HASH"},
                    {"AttributeName": "ItemId", "KeyType": "RANGE"},
                ],
                ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
            )
            log.info("Creating table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s created.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceInUseException":
                log.info("Table %s exists, nothing to be done.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when creating table: {err}."
                )
        else:
            return response

    def populate(self, data_file: str) -> None:
        """
        Populates the recommendations table from a JSON file.

        :param data_file: The path to the data file.
        :raises RecommendationServiceError: If the table population fails.
        """
        try:
            with open(data_file) as data:
                items = json.load(data)
            batch = [{"PutRequest": {"Item": item}} for item in items]
            self.dynamodb_client.batch_write_item(RequestItems={self.table_name: batch})
            log.info(
                "Populated table %s with items from %s.", self.table_name, data_file
            )
        except ClientError as err:
            raise RecommendationServiceError(
                self.table_name, f"Couldn't populate table from {data_file}: {err}"
            )

    def destroy(self) -> None:
        """
        Deletes the recommendations table.

        :raises RecommendationServiceError: If the table deletion fails.
        """
        try:
            self.dynamodb_client.delete_table(TableName=self.table_name)
            log.info("Deleting table %s...", self.table_name)
            waiter = self.dynamodb_client.get_waiter("table_not_exists")
            waiter.wait(TableName=self.table_name)
            log.info("Table %s deleted.", self.table_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                log.info("Table %s does not exist, nothing to do.", self.table_name)
            else:
                raise RecommendationServiceError(
                    self.table_name, f"ClientError when deleting table: {err}."
                )
```
Systems Manager のアクションをラップするクラスを作成します。  

```
class ParameterHelper:
    """
    Encapsulates Systems Manager parameters. This example uses these parameters to drive
    the demonstration of resilient architecture, such as failure of a dependency or
    how the service responds to a health check.
    """

    table: str = "doc-example-resilient-architecture-table"
    failure_response: str = "doc-example-resilient-architecture-failure-response"
    health_check: str = "doc-example-resilient-architecture-health-check"

    def __init__(self, table_name: str, ssm_client: boto3.client):
        """
        Initializes the ParameterHelper class with the necessary parameters.

        :param table_name: The name of the DynamoDB table that is used as a recommendation
                           service.
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.table_name = table_name

    def reset(self) -> None:
        """
        Resets the Systems Manager parameters to starting values for the demo.
        These are the name of the DynamoDB recommendation table, no response when a
        dependency fails, and shallow health checks.
        """
        self.put(self.table, self.table_name)
        self.put(self.failure_response, "none")
        self.put(self.health_check, "shallow")

    def put(self, name: str, value: str) -> None:
        """
        Sets the value of a named Systems Manager parameter.

        :param name: The name of the parameter.
        :param value: The new value of the parameter.
        :raises ParameterHelperError: If the parameter value cannot be set.
        """
        try:
            self.ssm_client.put_parameter(
                Name=name, Value=value, Overwrite=True, Type="String"
            )
            log.info("Setting parameter %s to '%s'.", name, value)
        except ClientError as err:
            error_code = err.response["Error"]["Code"]
            log.error(f"Failed to set parameter {name}.")
            if error_code == "ParameterLimitExceeded":
                log.error(
                    "The parameter limit has been exceeded. "
                    "Consider deleting unused parameters or request a limit increase."
                )
            elif error_code == "ParameterAlreadyExists":
                log.error(
                    "The parameter already exists and overwrite is set to False. "
                    "Use Overwrite=True to update the parameter."
                )
            log.error(f"Full error:\n\t{err}")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AttachLoadBalancerTargetGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/AttachLoadBalancerTargetGroups)
  + [CreateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/CreateAutoScalingGroup)
  + [CreateInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateInstanceProfile)
  + [CreateLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/CreateLaunchTemplate)
  + [CreateListener](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateListener)
  + [CreateLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateLoadBalancer)
  + [CreateTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/CreateTargetGroup)
  + [DeleteAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DeleteAutoScalingGroup)
  + [DeleteInstanceProfile](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteInstanceProfile)
  + [DeleteLaunchTemplate](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DeleteLaunchTemplate)
  + [DeleteLoadBalancer](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteLoadBalancer)
  + [DeleteTargetGroup](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DeleteTargetGroup)
  + [DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/DescribeAutoScalingGroups)
  + [DescribeAvailabilityZones](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeAvailabilityZones)
  + [DescribeIamInstanceProfileAssociations](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeIamInstanceProfileAssociations)
  + [DescribeInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeInstances)
  + [DescribeLoadBalancers](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeLoadBalancers)
  + [DescribeSubnets](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeSubnets)
  + [DescribeTargetGroups](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetGroups)
  + [DescribeTargetHealth](https://docs.aws.amazon.com/goto/boto3/elasticloadbalancingv2-2015-12-01/DescribeTargetHealth)
  + [DescribeVpcs](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/DescribeVpcs)
  + [RebootInstances](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/RebootInstances)
  + [ReplaceIamInstanceProfileAssociation](https://docs.aws.amazon.com/goto/boto3/ec2-2016-11-15/ReplaceIamInstanceProfileAssociation)
  + [TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/TerminateInstanceInAutoScalingGroup)
  + [UpdateAutoScalingGroup](https://docs.aws.amazon.com/goto/boto3/autoscaling-2011-01-01/UpdateAutoScalingGroup)

### 読み取り専用ユーザーおよび読み取り/書き込みできるユーザーを作成する
<a name="iam_Scenario_UserPolicies_python_3_topic"></a>

次のコード例は、ユーザーを作成し、そのユーザーにポリシーをアタッチする方法を示します。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアの開発や実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ IAM ユーザーを 2 つ作成します。
+ Amazon S3 バケット内のオブジェクトを取得して格納するポリシーを 1 人のユーザーに割り当てます。
+ このバケットからオブジェクトを取得することを許可するポリシーを、セカンドユーザーにアタッチします。
+ ユーザーの認証情報に基づいて、バケットについてのさまざまなアクセス許可を取得します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーアクションをラップする関数を作成します。  

```
import logging
import time

import boto3
from botocore.exceptions import ClientError

import access_key_wrapper
import policy_wrapper

logger = logging.getLogger(__name__)
iam = boto3.resource("iam")

def create_user(user_name):
    """
    Creates a user. By default, a user has no permissions or access keys.

    :param user_name: The name of the user.
    :return: The newly created user.
    """
    try:
        user = iam.create_user(UserName=user_name)
        logger.info("Created user %s.", user.name)
    except ClientError:
        logger.exception("Couldn't create user %s.", user_name)
        raise
    else:
        return user



def update_user(user_name, new_user_name):
    """
    Updates a user's name.

    :param user_name: The current name of the user to update.
    :param new_user_name: The new name to assign to the user.
    :return: The updated user.
    """
    try:
        user = iam.User(user_name)
        user.update(NewUserName=new_user_name)
        logger.info("Renamed %s to %s.", user_name, new_user_name)
    except ClientError:
        logger.exception("Couldn't update name for user %s.", user_name)
        raise
    return user



def list_users():
    """
    Lists the users in the current account.

    :return: The list of users.
    """
    try:
        users = list(iam.users.all())
        logger.info("Got %s users.", len(users))
    except ClientError:
        logger.exception("Couldn't get users.")
        raise
    else:
        return users



def delete_user(user_name):
    """
    Deletes a user. Before a user can be deleted, all associated resources,
    such as access keys and policies, must be deleted or detached.

    :param user_name: The name of the user.
    """
    try:
        iam.User(user_name).delete()
        logger.info("Deleted user %s.", user_name)
    except ClientError:
        logger.exception("Couldn't delete user %s.", user_name)
        raise



def attach_policy(user_name, policy_arn):
    """
    Attaches a policy to a user.

    :param user_name: The name of the user.
    :param policy_arn: The Amazon Resource Name (ARN) of the policy.
    """
    try:
        iam.User(user_name).attach_policy(PolicyArn=policy_arn)
        logger.info("Attached policy %s to user %s.", policy_arn, user_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to user %s.", policy_arn, user_name)
        raise



def detach_policy(user_name, policy_arn):
    """
    Detaches a policy from a user.

    :param user_name: The name of the user.
    :param policy_arn: The Amazon Resource Name (ARN) of the policy.
    """
    try:
        iam.User(user_name).detach_policy(PolicyArn=policy_arn)
        logger.info("Detached policy %s from user %s.", policy_arn, user_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from user %s.", policy_arn, user_name
        )
        raise
```
IAM ポリシーアクションをラップする関数を作成します。  

```
import json
import logging
import operator
import pprint
import time

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)
iam = boto3.resource("iam")

def create_policy(name, description, actions, resource_arn):
    """
    Creates a policy that contains a single statement.

    :param name: The name of the policy to create.
    :param description: The description of the policy.
    :param actions: The actions allowed by the policy. These typically take the
                    form of service:action, such as s3:PutObject.
    :param resource_arn: The Amazon Resource Name (ARN) of the resource this policy
                         applies to. This ARN can contain wildcards, such as
                         'arn:aws:s3:::amzn-s3-demo-bucket/*' to allow actions on all objects
                         in the bucket named 'amzn-s3-demo-bucket'.
    :return: The newly created policy.
    """
    policy_doc = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}],
    }
    try:
        policy = iam.create_policy(
            PolicyName=name,
            Description=description,
            PolicyDocument=json.dumps(policy_doc),
        )
        logger.info("Created policy %s.", policy.arn)
    except ClientError:
        logger.exception("Couldn't create policy %s.", name)
        raise
    else:
        return policy



def delete_policy(policy_arn):
    """
    Deletes a policy.

    :param policy_arn: The ARN of the policy to delete.
    """
    try:
        iam.Policy(policy_arn).delete()
        logger.info("Deleted policy %s.", policy_arn)
    except ClientError:
        logger.exception("Couldn't delete policy %s.", policy_arn)
        raise
```
IAM アクセスキーのアクションをラップする関数を作成します。  

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

iam = boto3.resource("iam")

def create_key(user_name):
    """
    Creates an access key for the specified user. Each user can have a
    maximum of two keys.

    :param user_name: The name of the user.
    :return: The created access key.
    """
    try:
        key_pair = iam.User(user_name).create_access_key_pair()
        logger.info(
            "Created access key pair for %s. Key ID is %s.",
            key_pair.user_name,
            key_pair.id,
        )
    except ClientError:
        logger.exception("Couldn't create access key pair for %s.", user_name)
        raise
    else:
        return key_pair



def delete_key(user_name, key_id):
    """
    Deletes a user's access key.

    :param user_name: The user that owns the key.
    :param key_id: The ID of the key to delete.
    """

    try:
        key = iam.AccessKey(user_name, key_id)
        key.delete()
        logger.info("Deleted access key %s for %s.", key.id, key.user_name)
    except ClientError:
        logger.exception("Couldn't delete key %s for %s", key_id, user_name)
        raise
```
ラッパー関数を使用して、異なるポリシーを持つユーザーを作成し、その認証情報を使用して Amazon S3 バケットにアクセスします。  

```
def usage_demo():
    """
    Shows how to manage users, keys, and policies.
    This demonstration creates two users: one user who can put and get objects in an
    Amazon S3 bucket, and another user who can only get objects from the bucket.
    The demo then shows how the users can perform only the actions they are permitted
    to perform.
    """
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    print("-" * 88)
    print("Welcome to the AWS Identity and Account Management user demo.")
    print("-" * 88)
    print(
        "Users can have policies and roles attached to grant them specific "
        "permissions."
    )
    s3 = boto3.resource("s3")
    bucket = s3.create_bucket(
        Bucket=f"demo-iam-bucket-{time.time_ns()}",
        CreateBucketConfiguration={
            "LocationConstraint": s3.meta.client.meta.region_name
        },
    )
    print(f"Created an Amazon S3 bucket named {bucket.name}.")
    user_read_writer = create_user("demo-iam-read-writer")
    user_reader = create_user("demo-iam-reader")
    print(f"Created two IAM users: {user_read_writer.name} and {user_reader.name}")
    update_user(user_read_writer.name, "demo-iam-creator")
    update_user(user_reader.name, "demo-iam-getter")
    users = list_users()
    user_read_writer = next(
        user for user in users if user.user_id == user_read_writer.user_id
    )
    user_reader = next(user for user in users if user.user_id == user_reader.user_id)
    print(
        f"Changed the names of the users to {user_read_writer.name} "
        f"and {user_reader.name}."
    )

    read_write_policy = policy_wrapper.create_policy(
        "demo-iam-read-write-policy",
        "Grants rights to create and get an object in the demo bucket.",
        ["s3:PutObject", "s3:GetObject"],
        f"arn:aws:s3:::{bucket.name}/*",
    )
    print(
        f"Created policy {read_write_policy.policy_name} with ARN: {read_write_policy.arn}"
    )
    print(read_write_policy.description)
    read_policy = policy_wrapper.create_policy(
        "demo-iam-read-policy",
        "Grants rights to get an object from the demo bucket.",
        "s3:GetObject",
        f"arn:aws:s3:::{bucket.name}/*",
    )
    print(f"Created policy {read_policy.policy_name} with ARN: {read_policy.arn}")
    print(read_policy.description)
    attach_policy(user_read_writer.name, read_write_policy.arn)
    print(f"Attached {read_write_policy.policy_name} to {user_read_writer.name}.")
    attach_policy(user_reader.name, read_policy.arn)
    print(f"Attached {read_policy.policy_name} to {user_reader.name}.")

    user_read_writer_key = access_key_wrapper.create_key(user_read_writer.name)
    print(f"Created access key pair for {user_read_writer.name}.")
    user_reader_key = access_key_wrapper.create_key(user_reader.name)
    print(f"Created access key pair for {user_reader.name}.")

    s3_read_writer_resource = boto3.resource(
        "s3",
        aws_access_key_id=user_read_writer_key.id,
        aws_secret_access_key=user_read_writer_key.secret,
    )
    demo_object_key = f"object-{time.time_ns()}"
    demo_object = None
    while demo_object is None:
        try:
            demo_object = s3_read_writer_resource.Bucket(bucket.name).put_object(
                Key=demo_object_key, Body=b"AWS IAM demo object content!"
            )
        except ClientError as error:
            if error.response["Error"]["Code"] == "InvalidAccessKeyId":
                print("Access key not yet available. Waiting...")
                time.sleep(1)
            else:
                raise
    print(
        f"Put {demo_object_key} into {bucket.name} using "
        f"{user_read_writer.name}'s credentials."
    )

    read_writer_object = s3_read_writer_resource.Bucket(bucket.name).Object(
        demo_object_key
    )
    read_writer_content = read_writer_object.get()["Body"].read()
    print(f"Got object {read_writer_object.key} using read-writer user's credentials.")
    print(f"Object content: {read_writer_content}")

    s3_reader_resource = boto3.resource(
        "s3",
        aws_access_key_id=user_reader_key.id,
        aws_secret_access_key=user_reader_key.secret,
    )
    demo_content = None
    while demo_content is None:
        try:
            demo_object = s3_reader_resource.Bucket(bucket.name).Object(demo_object_key)
            demo_content = demo_object.get()["Body"].read()
            print(f"Got object {demo_object.key} using reader user's credentials.")
            print(f"Object content: {demo_content}")
        except ClientError as error:
            if error.response["Error"]["Code"] == "InvalidAccessKeyId":
                print("Access key not yet available. Waiting...")
                time.sleep(1)
            else:
                raise

    try:
        demo_object.delete()
    except ClientError as error:
        if error.response["Error"]["Code"] == "AccessDenied":
            print("-" * 88)
            print(
                "Tried to delete the object using the reader user's credentials. "
                "Got expected AccessDenied error because the reader is not "
                "allowed to delete objects."
            )
            print("-" * 88)

    access_key_wrapper.delete_key(user_reader.name, user_reader_key.id)
    detach_policy(user_reader.name, read_policy.arn)
    policy_wrapper.delete_policy(read_policy.arn)
    delete_user(user_reader.name)
    print(f"Deleted keys, detached and deleted policy, and deleted {user_reader.name}.")

    access_key_wrapper.delete_key(user_read_writer.name, user_read_writer_key.id)
    detach_policy(user_read_writer.name, read_write_policy.arn)
    policy_wrapper.delete_policy(read_write_policy.arn)
    delete_user(user_read_writer.name)
    print(
        f"Deleted keys, detached and deleted policy, and deleted {user_read_writer.name}."
    )

    bucket.objects.delete()
    bucket.delete()
    print(f"Emptied and deleted {bucket.name}.")
    print("Thanks for watching!")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AttachUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachUserPolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)
  + [CreateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)
  + [DeleteUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteUser)
  + [DetachUserPolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachUserPolicy)
  + [ListUsers](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListUsers)
  + [UpdateUser](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/UpdateUser)

### アクセスキーを管理する
<a name="iam_Scenario_ManageAccessKeys_python_3_topic"></a>

次のコード例は、アクセスキーの管理方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアの開発や実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ アクセスキーを作成して一覧表示します。
+ アクセスキーが最後に使用された時刻とその方法を検索します。
+ アクセスキーの更新や削除を行います。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM アクセスキーのアクションをラップする関数を作成します。  

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

iam = boto3.resource("iam")

def list_keys(user_name):
    """
    Lists the keys owned by the specified user.

    :param user_name: The name of the user.
    :return: The list of keys owned by the user.
    """
    try:
        keys = list(iam.User(user_name).access_keys.all())
        logger.info("Got %s access keys for %s.", len(keys), user_name)
    except ClientError:
        logger.exception("Couldn't get access keys for %s.", user_name)
        raise
    else:
        return keys



def create_key(user_name):
    """
    Creates an access key for the specified user. Each user can have a
    maximum of two keys.

    :param user_name: The name of the user.
    :return: The created access key.
    """
    try:
        key_pair = iam.User(user_name).create_access_key_pair()
        logger.info(
            "Created access key pair for %s. Key ID is %s.",
            key_pair.user_name,
            key_pair.id,
        )
    except ClientError:
        logger.exception("Couldn't create access key pair for %s.", user_name)
        raise
    else:
        return key_pair



def get_last_use(key_id):
    """
    Gets information about when and how a key was last used.

    :param key_id: The ID of the key to look up.
    :return: Information about the key's last use.
    """
    try:
        response = iam.meta.client.get_access_key_last_used(AccessKeyId=key_id)
        last_used_date = response["AccessKeyLastUsed"].get("LastUsedDate", None)
        last_service = response["AccessKeyLastUsed"].get("ServiceName", None)
        logger.info(
            "Key %s was last used by %s on %s to access %s.",
            key_id,
            response["UserName"],
            last_used_date,
            last_service,
        )
    except ClientError:
        logger.exception("Couldn't get last use of key %s.", key_id)
        raise
    else:
        return response



def update_key(user_name, key_id, activate):
    """
    Updates the status of a key.

    :param user_name: The user that owns the key.
    :param key_id: The ID of the key to update.
    :param activate: When True, the key is activated. Otherwise, the key is deactivated.
    """

    try:
        key = iam.User(user_name).AccessKey(key_id)
        if activate:
            key.activate()
        else:
            key.deactivate()
        logger.info("%s key %s.", "Activated" if activate else "Deactivated", key_id)
    except ClientError:
        logger.exception(
            "Couldn't %s key %s.", "Activate" if activate else "Deactivate", key_id
        )
        raise



def delete_key(user_name, key_id):
    """
    Deletes a user's access key.

    :param user_name: The user that owns the key.
    :param key_id: The ID of the key to delete.
    """

    try:
        key = iam.AccessKey(user_name, key_id)
        key.delete()
        logger.info("Deleted access key %s for %s.", key.id, key.user_name)
    except ClientError:
        logger.exception("Couldn't delete key %s for %s", key_id, user_name)
        raise
```
ラッパー関数を使用して、現在のユーザーのアクセスキーアクションを実行します。  

```
def usage_demo():
    """Shows how to create and manage access keys."""

    def print_keys():
        """Gets and prints the current keys for a user."""
        current_keys = list_keys(current_user_name)
        print("The current user's keys are now:")
        print(*[f"{key.id}: {key.status}" for key in current_keys], sep="\n")

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    print("-" * 88)
    print("Welcome to the AWS Identity and Account Management access key demo.")
    print("-" * 88)
    current_user_name = iam.CurrentUser().user_name
    print(
        f"This demo creates an access key for the current user "
        f"({current_user_name}), manipulates the key in a few ways, and then "
        f"deletes it."
    )
    all_keys = list_keys(current_user_name)
    if len(all_keys) == 2:
        print(
            "The current user already has the maximum of 2 access keys. To run "
            "this demo, either delete one of the access keys or use a user "
            "that has only 1 access key."
        )
    else:
        new_key = create_key(current_user_name)
        print(f"Created a new key with id {new_key.id} and secret {new_key.secret}.")
        print_keys()
        existing_key = next(key for key in all_keys if key != new_key)
        last_use = get_last_use(existing_key.id)["AccessKeyLastUsed"]
        print(
            f"Key {all_keys[0].id} was last used to access {last_use['ServiceName']} "
            f"on {last_use['LastUsedDate']}"
        )
        update_key(current_user_name, new_key.id, False)
        print(f"Key {new_key.id} is now deactivated.")
        print_keys()
        delete_key(current_user_name, new_key.id)
        print_keys()
        print("Thanks for watching!")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccessKey)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccessKey)
  + [GetAccessKeyLastUsed](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccessKeyLastUsed)
  + [ListAccessKeys](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAccessKeys)
  + [UpdateAccessKey](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/UpdateAccessKey)

### ポリシーを管理
<a name="iam_Scenario_PolicyManagement_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ポリシーを作成して一覧表示します。
+ ポリシーバージョンを作成して取得します。
+ ポリシーを以前のバージョンにロールバックします。
+ ポリシーを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM ポリシーアクションをラップする関数を作成します。  

```
import json
import logging
import operator
import pprint
import time

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)
iam = boto3.resource("iam")

def create_policy(name, description, actions, resource_arn):
    """
    Creates a policy that contains a single statement.

    :param name: The name of the policy to create.
    :param description: The description of the policy.
    :param actions: The actions allowed by the policy. These typically take the
                    form of service:action, such as s3:PutObject.
    :param resource_arn: The Amazon Resource Name (ARN) of the resource this policy
                         applies to. This ARN can contain wildcards, such as
                         'arn:aws:s3:::amzn-s3-demo-bucket/*' to allow actions on all objects
                         in the bucket named 'amzn-s3-demo-bucket'.
    :return: The newly created policy.
    """
    policy_doc = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}],
    }
    try:
        policy = iam.create_policy(
            PolicyName=name,
            Description=description,
            PolicyDocument=json.dumps(policy_doc),
        )
        logger.info("Created policy %s.", policy.arn)
    except ClientError:
        logger.exception("Couldn't create policy %s.", name)
        raise
    else:
        return policy



def list_policies(scope):
    """
    Lists the policies in the current account.

    :param scope: Limits the kinds of policies that are returned. For example,
                  'Local' specifies that only locally managed policies are returned.
    :return: The list of policies.
    """
    try:
        policies = list(iam.policies.filter(Scope=scope))
        logger.info("Got %s policies in scope '%s'.", len(policies), scope)
    except ClientError:
        logger.exception("Couldn't get policies for scope '%s'.", scope)
        raise
    else:
        return policies



def create_policy_version(policy_arn, actions, resource_arn, set_as_default):
    """
    Creates a policy version. Policies can have up to five versions. The default
    version is the one that is used for all resources that reference the policy.

    :param policy_arn: The ARN of the policy.
    :param actions: The actions to allow in the policy version.
    :param resource_arn: The ARN of the resource this policy version applies to.
    :param set_as_default: When True, this policy version is set as the default
                           version for the policy. Otherwise, the default
                           is not changed.
    :return: The newly created policy version.
    """
    policy_doc = {
        "Version":"2012-10-17",		 	 	 
        "Statement": [{"Effect": "Allow", "Action": actions, "Resource": resource_arn}],
    }
    try:
        policy = iam.Policy(policy_arn)
        policy_version = policy.create_version(
            PolicyDocument=json.dumps(policy_doc), SetAsDefault=set_as_default
        )
        logger.info(
            "Created policy version %s for policy %s.",
            policy_version.version_id,
            policy_version.arn,
        )
    except ClientError:
        logger.exception("Couldn't create a policy version for %s.", policy_arn)
        raise
    else:
        return policy_version



def get_default_policy_statement(policy_arn):
    """
    Gets the statement of the default version of the specified policy.

    :param policy_arn: The ARN of the policy to look up.
    :return: The statement of the default policy version.
    """
    try:
        policy = iam.Policy(policy_arn)
        # To get an attribute of a policy, the SDK first calls get_policy.
        policy_doc = policy.default_version.document
        policy_statement = policy_doc.get("Statement", None)
        logger.info("Got default policy doc for %s.", policy.policy_name)
        logger.info(policy_doc)
    except ClientError:
        logger.exception("Couldn't get default policy statement for %s.", policy_arn)
        raise
    else:
        return policy_statement



def rollback_policy_version(policy_arn):
    """
    Rolls back to the previous default policy, if it exists.

    1. Gets the list of policy versions in order by date.
    2. Finds the default.
    3. Makes the previous policy the default.
    4. Deletes the old default version.

    :param policy_arn: The ARN of the policy to roll back.
    :return: The default version of the policy after the rollback.
    """
    try:
        policy_versions = sorted(
            iam.Policy(policy_arn).versions.all(),
            key=operator.attrgetter("create_date"),
        )
        logger.info("Got %s versions for %s.", len(policy_versions), policy_arn)
    except ClientError:
        logger.exception("Couldn't get versions for %s.", policy_arn)
        raise

    default_version = None
    rollback_version = None
    try:
        while default_version is None:
            ver = policy_versions.pop()
            if ver.is_default_version:
                default_version = ver
        rollback_version = policy_versions.pop()
        rollback_version.set_as_default()
        logger.info("Set %s as the default version.", rollback_version.version_id)
        default_version.delete()
        logger.info("Deleted original default version %s.", default_version.version_id)
    except IndexError:
        if default_version is None:
            logger.warning("No default version found for %s.", policy_arn)
        elif rollback_version is None:
            logger.warning(
                "Default version %s found for %s, but no previous version exists, so "
                "nothing to roll back to.",
                default_version.version_id,
                policy_arn,
            )
    except ClientError:
        logger.exception("Couldn't roll back version for %s.", policy_arn)
        raise
    else:
        return rollback_version



def delete_policy(policy_arn):
    """
    Deletes a policy.

    :param policy_arn: The ARN of the policy to delete.
    """
    try:
        iam.Policy(policy_arn).delete()
        logger.info("Deleted policy %s.", policy_arn)
    except ClientError:
        logger.exception("Couldn't delete policy %s.", policy_arn)
        raise
```
ラッパー関数を使用して、ポリシーを作成し、バージョンを更新し、それらに関する情報を取得します。  

```
def usage_demo():
    """Shows how to use the policy functions."""
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    print("-" * 88)
    print("Welcome to the AWS Identity and Account Management policy demo.")
    print("-" * 88)
    print(
        "Policies let you define sets of permissions that can be attached to "
        "other IAM resources, like users and roles."
    )
    bucket_arn = f"arn:aws:s3:::amzn-s3-demo-bucket"
    policy = create_policy(
        "demo-iam-policy",
        "Policy for IAM demonstration.",
        ["s3:ListObjects"],
        bucket_arn,
    )
    print(f"Created policy {policy.policy_name}.")
    policies = list_policies("Local")
    print(f"Your account has {len(policies)} managed policies:")
    print(*[pol.policy_name for pol in policies], sep=", ")
    time.sleep(1)
    policy_version = create_policy_version(
        policy.arn, ["s3:PutObject"], bucket_arn, True
    )
    print(
        f"Added policy version {policy_version.version_id} to policy "
        f"{policy.policy_name}."
    )
    default_statement = get_default_policy_statement(policy.arn)
    print(f"The default policy statement for {policy.policy_name} is:")
    pprint.pprint(default_statement)
    rollback_version = rollback_policy_version(policy.arn)
    print(
        f"Rolled back to version {rollback_version.version_id} for "
        f"{policy.policy_name}."
    )
    default_statement = get_default_policy_statement(policy.arn)
    print(f"The default policy statement for {policy.policy_name} is now:")
    pprint.pprint(default_statement)
    delete_policy(policy.arn)
    print(f"Deleted policy {policy.policy_name}.")
    print("Thanks for watching!")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreatePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicy)
  + [CreatePolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreatePolicyVersion)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicy)
  + [DeletePolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicyVersion)
  + [GetPolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetPolicyVersion)
  + [ListPolicies](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListPolicies)
  + [ListPolicyVersions](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListPolicyVersions)
  + [SetDefaultPolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/SetDefaultPolicyVersion)

### ロールの管理
<a name="iam_Scenario_RoleManagement_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールを作成します。
+ ロールにポリシーをアタッチおよびデタッチします
+ ロールを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM ロールアクションをラップする関数を作成します。  

```
import json
import logging
import pprint

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)
iam = boto3.resource("iam")

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



def attach_policy(role_name, policy_arn):
    """
    Attaches a policy to a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Role(role_name).attach_policy(PolicyArn=policy_arn)
        logger.info("Attached policy %s to role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception("Couldn't attach policy %s to role %s.", policy_arn, role_name)
        raise



def detach_policy(role_name, policy_arn):
    """
    Detaches a policy from a role.

    :param role_name: The name of the role. **Note** this is the name, not the ARN.
    :param policy_arn: The ARN of the policy.
    """
    try:
        iam.Role(role_name).detach_policy(PolicyArn=policy_arn)
        logger.info("Detached policy %s from role %s.", policy_arn, role_name)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from role %s.", policy_arn, role_name
        )
        raise



def delete_role(role_name):
    """
    Deletes a role.

    :param role_name: The name of the role to delete.
    """
    try:
        iam.Role(role_name).delete()
        logger.info("Deleted role %s.", role_name)
    except ClientError:
        logger.exception("Couldn't delete role %s.", role_name)
        raise
```
ラッパー関数を使用してロールを作成し、ポリシーをアタッチおよびデタッチします。  

```
def usage_demo():
    """Shows how to use the role functions."""
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    print("-" * 88)
    print("Welcome to the AWS Identity and Account Management role demo.")
    print("-" * 88)
    print(
        "Roles let you define sets of permissions and can be assumed by "
        "other entities, like users and services."
    )
    print("The first 10 roles currently in your account are:")
    roles = list_roles(10)
    print(f"The inline policies for role {roles[0].name} are:")
    list_policies(roles[0].name)
    role = create_role(
        "demo-iam-role", ["lambda.amazonaws.com", "batchoperations.s3.amazonaws.com"]
    )
    print(f"Created role {role.name}, with trust policy:")
    pprint.pprint(role.assume_role_policy_document)
    policy_arn = "arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess"
    attach_policy(role.name, policy_arn)
    print(f"Attached policy {policy_arn} to {role.name}.")
    print(f"Policies attached to role {role.name} are:")
    list_attached_policies(role.name)
    detach_policy(role.name, policy_arn)
    print(f"Detached policy {policy_arn} from {role.name}.")
    delete_role(role.name)
    print(f"Deleted {role.name}.")
    print("Thanks for watching!")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/AttachRolePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateRole)
  + [DeleteRole](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteRole)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DetachRolePolicy)

### アカウントの管理
<a name="iam_Scenario_AccountManagement_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ アカウントエイリアスを取得して更新します。
+ ユーザーと認証情報に関するレポートを生成します。
+ アカウントの使用状況の概要を取得します。
+ アカウント内のユーザー、グループ、ロール、ポリシーについて、相互の関連付けなどの詳細を取得します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM アカウントのアクションをラップする関数を作成します。  

```
import logging
import pprint
import sys
import time
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)
iam = boto3.resource("iam")

def list_aliases():
    """
    Gets the list of aliases for the current account. An account has at most one alias.

    :return: The list of aliases for the account.
    """
    try:
        response = iam.meta.client.list_account_aliases()
        aliases = response["AccountAliases"]
        if len(aliases) > 0:
            logger.info("Got aliases for your account: %s.", ",".join(aliases))
        else:
            logger.info("Got no aliases for your account.")
    except ClientError:
        logger.exception("Couldn't list aliases for your account.")
        raise
    else:
        return response["AccountAliases"]



def create_alias(alias):
    """
    Creates an alias for the current account. The alias can be used in place of the
    account ID in the sign-in URL. An account can have only one alias. When a new
    alias is created, it replaces any existing alias.

    :param alias: The alias to assign to the account.
    """

    try:
        iam.create_account_alias(AccountAlias=alias)
        logger.info("Created an alias '%s' for your account.", alias)
    except ClientError:
        logger.exception("Couldn't create alias '%s' for your account.", alias)
        raise



def delete_alias(alias):
    """
    Removes the alias from the current account.

    :param alias: The alias to remove.
    """
    try:
        iam.meta.client.delete_account_alias(AccountAlias=alias)
        logger.info("Removed alias '%s' from your account.", alias)
    except ClientError:
        logger.exception("Couldn't remove alias '%s' from your account.", alias)
        raise



def generate_credential_report():
    """
    Starts generation of a credentials report about the current account. After
    calling this function to generate the report, call get_credential_report
    to get the latest report. A new report can be generated a minimum of four hours
    after the last one was generated.
    """
    try:
        response = iam.meta.client.generate_credential_report()
        logger.info(
            "Generating credentials report for your account. " "Current state is %s.",
            response["State"],
        )
    except ClientError:
        logger.exception("Couldn't generate a credentials report for your account.")
        raise
    else:
        return response



def get_credential_report():
    """
    Gets the most recently generated credentials report about the current account.

    :return: The credentials report.
    """
    try:
        response = iam.meta.client.get_credential_report()
        logger.debug(response["Content"])
    except ClientError:
        logger.exception("Couldn't get credentials report.")
        raise
    else:
        return response["Content"]



def get_summary():
    """
    Gets a summary of account usage.

    :return: The summary of account usage.
    """
    try:
        summary = iam.AccountSummary()
        logger.debug(summary.summary_map)
    except ClientError:
        logger.exception("Couldn't get a summary for your account.")
        raise
    else:
        return summary.summary_map



def get_authorization_details(response_filter):
    """
    Gets an authorization detail report for the current account.

    :param response_filter: A list of resource types to include in the report, such
                            as users or roles. When not specified, all resources
                            are included.
    :return: The authorization detail report.
    """
    try:
        account_details = iam.meta.client.get_account_authorization_details(
            Filter=response_filter
        )
        logger.debug(account_details)
    except ClientError:
        logger.exception("Couldn't get details for your account.")
        raise
    else:
        return account_details
```
ラッパー関数を呼び出して、アカウントのエイリアスを変更し、アカウントに関するレポートを取得します。  

```
def usage_demo():
    """Shows how to use the account functions."""
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    print("-" * 88)
    print("Welcome to the AWS Identity and Account Management account demo.")
    print("-" * 88)
    print(
        "Setting an account alias lets you use the alias in your sign-in URL "
        "instead of your account number."
    )
    old_aliases = list_aliases()
    if len(old_aliases) > 0:
        print(f"Your account currently uses '{old_aliases[0]}' as its alias.")
    else:
        print("Your account currently has no alias.")
    for index in range(1, 3):
        new_alias = f"alias-{index}-{time.time_ns()}"
        print(f"Setting your account alias to {new_alias}")
        create_alias(new_alias)
    current_aliases = list_aliases()
    print(f"Your account alias is now {current_aliases}.")
    delete_alias(current_aliases[0])
    print(f"Your account now has no alias.")
    if len(old_aliases) > 0:
        print(f"Restoring your original alias back to {old_aliases[0]}...")
        create_alias(old_aliases[0])

    print("-" * 88)
    print("You can get various reports about your account.")
    print("Let's generate a credentials report...")
    report_state = None
    while report_state != "COMPLETE":
        cred_report_response = generate_credential_report()
        old_report_state = report_state
        report_state = cred_report_response["State"]
        if report_state != old_report_state:
            print(report_state, sep="")
        else:
            print(".", sep="")
        sys.stdout.flush()
        time.sleep(1)
    print()
    cred_report = get_credential_report()
    col_count = 3
    print(f"Got credentials report. Showing only the first {col_count} columns.")
    cred_lines = [
        line.split(",")[:col_count] for line in cred_report.decode("utf-8").split("\n")
    ]
    col_width = max([len(item) for line in cred_lines for item in line]) + 2
    for line in cred_report.decode("utf-8").split("\n"):
        print(
            "".join(element.ljust(col_width) for element in line.split(",")[:col_count])
        )

    print("-" * 88)
    print("Let's get an account summary.")
    summary = get_summary()
    print("Here's your summary:")
    pprint.pprint(summary)

    print("-" * 88)
    print("Let's get authorization details!")
    details = get_authorization_details([])
    see_details = input("These are pretty long, do you want to see them (y/n)? ")
    if see_details.lower() == "y":
        pprint.pprint(details)

    print("-" * 88)
    pw_policy_created = None
    see_pw_policy = input("Want to see the password policy for the account (y/n)? ")
    if see_pw_policy.lower() == "y":
        while True:
            if print_password_policy():
                break
            else:
                answer = input(
                    "Do you want to create a default password policy (y/n)? "
                )
                if answer.lower() == "y":
                    pw_policy_created = iam.create_account_password_policy()
                else:
                    break
    if pw_policy_created is not None:
        answer = input("Do you want to delete the password policy (y/n)? ")
        if answer.lower() == "y":
            pw_policy_created.delete()
            print("Password policy deleted.")

    print("The SAML providers for your account are:")
    list_saml_providers(10)

    print("-" * 88)
    print("Thanks for watching.")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateAccountAlias](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/CreateAccountAlias)
  + [DeleteAccountAlias](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeleteAccountAlias)
  + [GenerateCredentialReport](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GenerateCredentialReport)
  + [GetAccountAuthorizationDetails](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountAuthorizationDetails)
  + [GetAccountSummary](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetAccountSummary)
  + [GetCredentialReport](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/GetCredentialReport)
  + [ListAccountAliases](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListAccountAliases)

### ポリシーを以前のバージョンにロールバックする
<a name="iam_Scenario_RollbackPolicyVersion_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ポリシーのバージョンの日付順リストを取得します。
+ デフォルトのポリシーバージョンを検索します。
+ デフォルト値を以前のポリシーバージョンにします。
+ 古いデフォルトバージョンを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
def rollback_policy_version(policy_arn):
    """
    Rolls back to the previous default policy, if it exists.

    1. Gets the list of policy versions in order by date.
    2. Finds the default.
    3. Makes the previous policy the default.
    4. Deletes the old default version.

    :param policy_arn: The ARN of the policy to roll back.
    :return: The default version of the policy after the rollback.
    """
    try:
        policy_versions = sorted(
            iam.Policy(policy_arn).versions.all(),
            key=operator.attrgetter("create_date"),
        )
        logger.info("Got %s versions for %s.", len(policy_versions), policy_arn)
    except ClientError:
        logger.exception("Couldn't get versions for %s.", policy_arn)
        raise

    default_version = None
    rollback_version = None
    try:
        while default_version is None:
            ver = policy_versions.pop()
            if ver.is_default_version:
                default_version = ver
        rollback_version = policy_versions.pop()
        rollback_version.set_as_default()
        logger.info("Set %s as the default version.", rollback_version.version_id)
        default_version.delete()
        logger.info("Deleted original default version %s.", default_version.version_id)
    except IndexError:
        if default_version is None:
            logger.warning("No default version found for %s.", policy_arn)
        elif rollback_version is None:
            logger.warning(
                "Default version %s found for %s, but no previous version exists, so "
                "nothing to roll back to.",
                default_version.version_id,
                policy_arn,
            )
    except ClientError:
        logger.exception("Couldn't roll back version for %s.", policy_arn)
        raise
    else:
        return rollback_version
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [DeletePolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/DeletePolicyVersion)
  + [ListPolicyVersions](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/ListPolicyVersions)
  + [SetDefaultPolicyVersion](https://docs.aws.amazon.com/goto/boto3/iam-2010-05-08/SetDefaultPolicyVersion)

# AWS IoT SDK for Python (Boto3) を使用した例
<a name="python_3_iot_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoTは
<a name="iot_Hello_python_3_topic"></a>

次のコード例は、 AWS IoTの使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
def hello_iot():
    """
    Use the AWS SDK for Python (Boto3) to create an AWS IoT client and list
    up to 10 things in your AWS IoT account.
    This example uses the default settings specified in your shared credentials
    and config files.
    """
    try:
        iot_client = boto3.client("iot")
        response = iot_client.list_things(maxResults=10)
        things = response.get("things", [])
        
        print("Hello, AWS IoT! Here are your things:")
        if things:
            for i, thing in enumerate(things, 1):
                print(f"{i}. {thing['thingName']}")
        else:
            print("No things found in your AWS IoT account.")
    except ClientError as e:
        if e.response["Error"]["Code"] == "UnauthorizedException":
            print("You don't have permission to access AWS IoT.")
        else:
            print(f"Couldn't access AWS IoT. Error: {e}")
    except NoCredentialsError:
        print("No AWS credentials found. Please configure your credentials.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[listThings](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/listThings)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iot_Scenario_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT モノを作成します。
+ デバイス証明書を生成します。
+ 属性を使用して AWS IoT モノを更新します。
+ 一意のエンドポイントを返します。
+  AWS IoT 証明書を一覧表示します。
+  AWS IoT シャドウを更新します。
+ 状態情報を書き込みます。
+ ルールを作成する｡
+ ルールを一覧表示します。
+ モノの名前を使用してモノを検索します。
+  AWS IoT モノを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。
オペレーションを管理する IoT ラッパークラスを作成します。  

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)
    

    def create_thing(self, thing_name):
        """
        Creates an AWS IoT thing.

        :param thing_name: The name of the thing to create.
        :return: The name and ARN of the created thing.
        """
        try:
            response = self.iot_client.create_thing(thingName=thing_name)
            logger.info("Created thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.info("Thing %s already exists. Skipping creation.", thing_name)
                return None
            logger.error(
                "Couldn't create thing %s. Here's why: %s: %s",
                thing_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def list_things(self):
        """
        Lists AWS IoT things.

        :return: The list of things.
        """
        try:
            things = []
            paginator = self.iot_client.get_paginator("list_things")
            for page in paginator.paginate():
                things.extend(page["things"])
            logger.info("Retrieved %s things.", len(things))
            return things
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't list things. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
            


    def create_keys_and_certificate(self):
        """
        Creates keys and a certificate for an AWS IoT thing.

        :return: The certificate ID, ARN, and PEM.
        """
        try:
            response = self.iot_client.create_keys_and_certificate(setAsActive=True)
            logger.info("Created certificate %s.", response["certificateId"])
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't create keys and certificate. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response


    def attach_thing_principal(self, thing_name, principal):
        """
        Attaches a certificate to an AWS IoT thing.

        :param thing_name: The name of the thing.
        :param principal: The ARN of the certificate.
        """
        try:
            self.iot_client.attach_thing_principal(
                thingName=thing_name, principal=principal
            )
            logger.info("Attached principal %s to thing %s.", principal, thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot attach principal. Resource not found.")
                return
            logger.error(
                "Couldn't attach principal to thing. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def describe_endpoint(self, endpoint_type="iot:Data-ATS"):
        """
        Gets the AWS IoT endpoint.

        :param endpoint_type: The endpoint type.
        :return: The endpoint.
        """
        try:
            response = self.iot_client.describe_endpoint(endpointType=endpoint_type)
            logger.info("Retrieved endpoint %s.", response["endpointAddress"])
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't describe endpoint. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response["endpointAddress"]


    def list_certificates(self):
        """
        Lists AWS IoT certificates.

        :return: The list of certificates.
        """
        try:
            certificates = []
            paginator = self.iot_client.get_paginator("list_certificates")
            for page in paginator.paginate():
                certificates.extend(page["certificates"])
            logger.info("Retrieved %s certificates.", len(certificates))
            return certificates
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't list certificates. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise


    def detach_thing_principal(self, thing_name, principal):
        """
        Detaches a certificate from an AWS IoT thing.

        :param thing_name: The name of the thing.
        :param principal: The ARN of the certificate.
        """
        try:
            self.iot_client.detach_thing_principal(
                thingName=thing_name, principal=principal
            )
            logger.info("Detached principal %s from thing %s.", principal, thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot detach principal. Resource not found.")
                return
            logger.error(
                "Couldn't detach principal from thing. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_certificate(self, certificate_id):
        """
        Deletes an AWS IoT certificate.

        :param certificate_id: The ID of the certificate to delete.
        """
        try:
            self.iot_client.update_certificate(
                certificateId=certificate_id, newStatus="INACTIVE"
            )
            self.iot_client.delete_certificate(certificateId=certificate_id)
            logger.info("Deleted certificate %s.", certificate_id)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot delete certificate. Resource not found.")
                return
            logger.error(
                "Couldn't delete certificate. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def create_topic_rule(self, rule_name, topic, sns_action_arn, role_arn):
        """
        Creates an AWS IoT topic rule.

        :param rule_name: The name of the rule.
        :param topic: The MQTT topic to subscribe to.
        :param sns_action_arn: The ARN of the SNS topic to publish to.
        :param role_arn: The ARN of the IAM role.
        """
        try:
            self.iot_client.create_topic_rule(
                ruleName=rule_name,
                topicRulePayload={
                    "sql": f"SELECT * FROM '{topic}'",
                    "actions": [
                        {"sns": {"targetArn": sns_action_arn, "roleArn": role_arn}}
                    ],
                },
            )
            logger.info("Created topic rule %s.", rule_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.info("Topic rule %s already exists. Skipping creation.", rule_name)
                return
            logger.error(
                "Couldn't create topic rule. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def list_topic_rules(self):
        """
        Lists AWS IoT topic rules.

        :return: The list of topic rules.
        """
        try:
            rules = []
            paginator = self.iot_client.get_paginator("list_topic_rules")
            for page in paginator.paginate():
                rules.extend(page["rules"])
            logger.info("Retrieved %s topic rules.", len(rules))
            return rules
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't list topic rules. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
            


    def search_index(self, query):
        """
        Searches the AWS IoT index.

        :param query: The search query.
        :return: The list of things found.
        """
        try:
            response = self.iot_client.search_index(queryString=query)
            logger.info("Found %s things.", len(response.get("things", [])))
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't search index. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response.get("things", [])


    def update_indexing_configuration(self):
        """
        Updates the AWS IoT indexing configuration to enable thing indexing.
        """
        try:
            self.iot_client.update_indexing_configuration(
                thingIndexingConfiguration={"thingIndexingMode": "REGISTRY"}
            )
            logger.info("Updated indexing configuration.")
        except ClientError as err:
            logger.error(
                "Couldn't update indexing configuration. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_thing(self, thing_name):
        """
        Deletes an AWS IoT thing.

        :param thing_name: The name of the thing to delete.
        """
        try:
            self.iot_client.delete_thing(thingName=thing_name)
            logger.info("Deleted thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot delete thing. Resource not found.")
                return
            logger.error(
                "Couldn't delete thing. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_topic_rule(self, rule_name):
        """
        Deletes an AWS IoT topic rule.

        :param rule_name: The name of the rule to delete.
        """
        try:
            self.iot_client.delete_topic_rule(ruleName=rule_name)
            logger.info("Deleted topic rule %s.", rule_name)
        except ClientError as err:
            logger.error(
                "Couldn't delete topic rule. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def update_thing_shadow(self, thing_name, shadow_state):
        """
        Updates the shadow for an AWS IoT thing.

        :param thing_name: The name of the thing.
        :param shadow_state: The shadow state as a dictionary.
        """
        import json
        try:
            self.iot_data_client.update_thing_shadow(
                thingName=thing_name, payload=json.dumps(shadow_state)
            )
            logger.info("Updated shadow for thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot update thing shadow. Resource not found.")
                return
            logger.error(
                "Couldn't update thing shadow. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def get_thing_shadow(self, thing_name):
        """
        Gets the shadow for an AWS IoT thing.

        :param thing_name: The name of the thing.
        :return: The shadow state as a dictionary.
        """
        import json
        try:
            response = self.iot_data_client.get_thing_shadow(thingName=thing_name)
            shadow = json.loads(response["payload"].read())
            logger.info("Retrieved shadow for thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot get thing shadow. Resource not found.")
                return None
            logger.error(
                "Couldn't get thing shadow. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return shadow
```
IoT の基本を示すインタラクティブなシナリオを実行します。  

```
class IoTScenario:
    """Runs an interactive scenario that shows how to use AWS IoT."""

    is_interactive = True

    def __init__(self, iot_wrapper, iot_data_client, cfn_client, stack_name="IoTBasicsStack", template_path=None):
        """
        :param iot_wrapper: An instance of the IoTWrapper class.
        :param iot_data_client: A Boto3 IoT Data Plane client.
        :param cfn_client: A Boto3 CloudFormation client.
        :param stack_name: Name for the CloudFormation stack.
        :param template_path: Path to the CloudFormation template file.
        """
        self.iot_wrapper = iot_wrapper
        self.iot_data_client = iot_data_client
        self.cfn_client = cfn_client
        self.thing_name = None
        self.certificate_arn = None
        self.certificate_id = None
        self.rule_name = None
        self.stack_name = stack_name
        self.template_path = template_path or "../../../scenarios/basics/iot/iot_usecase/resources/cfn_template.yaml"

    def _deploy_stack(self):
        """Deploy CloudFormation stack and return outputs."""
        with open(self.template_path, "r") as f:
            template_body = f.read()
        
        try:
            self.cfn_client.create_stack(
                StackName=self.stack_name,
                TemplateBody=template_body,
                Capabilities=["CAPABILITY_NAMED_IAM"]
            )
            
            waiter = self.cfn_client.get_waiter("stack_create_complete")
            waiter.wait(StackName=self.stack_name)
            
            response = self.cfn_client.describe_stacks(StackName=self.stack_name)
            outputs = {output["OutputKey"]: output["OutputValue"] 
                      for output in response["Stacks"][0]["Outputs"]}
            return outputs["SNSTopicArn"], outputs["RoleArn"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "AlreadyExistsException":
                response = self.cfn_client.describe_stacks(StackName=self.stack_name)
                outputs = {output["OutputKey"]: output["OutputValue"] 
                          for output in response["Stacks"][0]["Outputs"]}
                return outputs["SNSTopicArn"], outputs["RoleArn"]
            raise

    def _cleanup_stack(self):
        """Delete CloudFormation stack."""
        try:
            self.cfn_client.delete_stack(StackName=self.stack_name)
            waiter = self.cfn_client.get_waiter("stack_delete_complete")
            waiter.wait(StackName=self.stack_name)
            print("CloudFormation stack deleted successfully.")
        except ClientError as err:
            logger.error(f"Failed to delete stack: {err}")

    def run_scenario(self, thing_name, rule_name):
        """
        Runs the IoT basics scenario.

        :param thing_name: The name of the thing to create.
        :param rule_name: The name of the topic rule to create.
        """
        print("-" * 88)
        print("Welcome to the AWS IoT basics scenario!")
        print("-" * 88)
        print(
            "This scenario demonstrates how to interact with AWS IoT using the AWS SDK for Python (Boto3).\n"
            "AWS IoT provides secure, bi-directional communication between Internet-connected devices\n"
            "and the AWS cloud. You can manage device connections, process device data, and build IoT applications.\n"
        )

        self.thing_name = thing_name
        self.rule_name = rule_name

        try:
            print("\nDeploying CloudFormation stack...")
            sns_topic_arn, role_arn = self._deploy_stack()
            print(f"Stack deployed. SNS Topic: {sns_topic_arn}")

            input("\nNext, we'll create an AWS IoT thing. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("1. Create an AWS IoT thing")
            print("-" * 88)
            response = self.iot_wrapper.create_thing(thing_name)
            print(f"Created thing: {response['thingName']}")
            print(f"Thing ARN: {response['thingArn']}")

            input("\nNext, we'll list things. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("2. List things")
            print("-" * 88)
            things = self.iot_wrapper.list_things()
            print(f"Found {len(things)} thing(s) in your account")
            for thing in things[:5]:  # Show first 5
                print(f"  Thing name: {thing['thingName']}")

            input("\nNext, we'll generate a device certificate. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("3. Generate a device certificate")
            print("-" * 88)
            cert_response = self.iot_wrapper.create_keys_and_certificate()
            self.certificate_arn = cert_response["certificateArn"]
            self.certificate_id = cert_response["certificateId"]
            print(f"Created certificate: {self.certificate_id}")

            input("\nNext, we'll attach the certificate to the thing. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("4. Attach the certificate to the thing")
            print("-" * 88)
            self.iot_wrapper.attach_thing_principal(thing_name, self.certificate_arn)
            print(f"Attached certificate to thing: {thing_name}")

            input("\nNext, we'll update the thing shadow. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("5. Update the thing shadow")
            print("-" * 88)
            shadow_state = {"state": {"reported": {"temperature": 25, "humidity": 50}}}
            self.iot_wrapper.update_thing_shadow(thing_name, shadow_state)
            print(f"Updated shadow for thing: {thing_name}")

            input("\nNext, we'll get the thing shadow. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("6. Get the thing shadow")
            print("-" * 88)
            shadow = self.iot_wrapper.get_thing_shadow(thing_name)
            print(f"Shadow state: {json.dumps(shadow['state'], indent=2)}")

            input("\nNext, we'll get the AWS IoT endpoint. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("7. Get the AWS IoT endpoint")
            print("-" * 88)
            endpoint = self.iot_wrapper.describe_endpoint()
            print(f"IoT endpoint: {endpoint}")

            input("\nNext, we'll list certificates. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("8. List certificates")
            print("-" * 88)
            certificates = self.iot_wrapper.list_certificates()
            print(f"Found {len(certificates)} certificate(s)")
            for cert in certificates:
                print(f"  Certificate ID: {cert['certificateId']}")
                print(f"  Certificate ARN: {cert['certificateArn']}")
                print(f"  Status: {cert['status']}")

            input("\nNext, we'll create a topic rule. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("9. Create a topic rule")
            print("-" * 88)
            self.iot_wrapper.create_topic_rule(
                rule_name, f"device/{thing_name}/data", sns_topic_arn, role_arn
            )
            print(f"Created topic rule: {rule_name}")

            input("\nNext, we'll list topic rules. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("10. List topic rules")
            print("-" * 88)
            rules = self.iot_wrapper.list_topic_rules()
            print(f"Found {len(rules)} topic rule(s)")
            for rule in rules:
                print(f"  Rule name: {rule['ruleName']}")
                print(f"  Rule ARN: {rule['ruleArn']}")

            input("\nNext, we'll configure thing indexing. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("11. Configure thing indexing")
            print("-" * 88)
            self.iot_wrapper.update_indexing_configuration()
            print("Enabled thing indexing")
            print("Waiting for indexing to be ready...")
            time.sleep(10)

            input("\nNext, we'll search for things. Press Enter to continue...") if self.is_interactive else None
            print("\n" + "-" * 88)
            print("12. Search for things")
            print("-" * 88)
            try:
                things = self.iot_wrapper.search_index(f"thingName:{thing_name}")
                if things:
                    print(f"Found {len(things)} thing(s) matching the query")
                    for thing in things:
                        print(f"  Thing name: {thing.get('thingName', 'N/A')}")
                        print(f"  Thing ID: {thing.get('thingId', 'N/A')}")
                else:
                    print("No things found. Indexing may take a few minutes.")
            except ClientError as err:
                if err.response["Error"]["Code"] in [
                    "IndexNotReadyException",
                    "InvalidRequestException",
                ]:
                    print("Search index not ready yet. This is expected.")
                else:
                    raise

        except ClientError as err:
            logger.error(
                "Scenario failed: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        finally:
            self._cleanup()

    def _cleanup(self):
        """Cleans up resources created during the scenario."""
        if not self.thing_name:
            return

        print("\n" + "-" * 88)
        print("Cleanup")
        print("-" * 88)

        if q.ask("Do you want to delete the resources? (y/n) ", q.is_yesno):
            try:
                if self.certificate_arn:
                    print(f"Detaching certificate from thing: {self.thing_name}")
                    self.iot_wrapper.detach_thing_principal(
                        self.thing_name, self.certificate_arn
                    )

                if self.certificate_id:
                    print(f"Deleting certificate: {self.certificate_id}")
                    self.iot_wrapper.delete_certificate(self.certificate_id)

                if self.thing_name:
                    print(f"Deleting thing: {self.thing_name}")
                    self.iot_wrapper.delete_thing(self.thing_name)

                if self.rule_name:
                    print(f"Deleting topic rule: {self.rule_name}")
                    self.iot_wrapper.delete_topic_rule(self.rule_name)

                self._cleanup_stack()
                print("Resources deleted successfully.")
            except ClientError as err:
                logger.error(
                    "Cleanup failed: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
        else:
            print("Resources will remain in your account.")

        print("\n" + "-" * 88)
        print("Thanks for using AWS IoT!")
        print("-" * 88)
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [AttachThingPrincipal](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/AttachThingPrincipal)
  + [CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/CreateKeysAndCertificate)
  + [CreateThing](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/CreateThing)
  + [CreateTopicRule](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/CreateTopicRule)
  + [DeleteCertificate](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DeleteCertificate)
  + [DeleteThing](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DeleteThing)
  + [DeleteTopicRule](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DeleteTopicRule)
  + [DescribeEndpoint](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DescribeEndpoint)
  + [DescribeThing](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DescribeThing)
  + [DetachThingPrincipal](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DetachThingPrincipal)
  + [ListCertificates](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/ListCertificates)
  + [ListThings](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/ListThings)
  + [SearchIndex](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/SearchIndex)
  + [UpdateIndexingConfiguration](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/UpdateIndexingConfiguration)
  + [UpdateThing](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/UpdateThing)

## アクション
<a name="actions"></a>

### `AttachThingPrincipal`
<a name="iot_AttachThingPrincipal_python_3_topic"></a>

次の例は、`AttachThingPrincipal` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def attach_thing_principal(self, thing_name, principal):
        """
        Attaches a certificate to an AWS IoT thing.

        :param thing_name: The name of the thing.
        :param principal: The ARN of the certificate.
        """
        try:
            self.iot_client.attach_thing_principal(
                thingName=thing_name, principal=principal
            )
            logger.info("Attached principal %s to thing %s.", principal, thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot attach principal. Resource not found.")
                return
            logger.error(
                "Couldn't attach principal to thing. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*「[AttachThingPrincipal](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/AttachThingPrincipal)」を参照してください。

### `CreateKeysAndCertificate`
<a name="iot_CreateKeysAndCertificate_python_3_topic"></a>

次の例は、`CreateKeysAndCertificate` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def create_keys_and_certificate(self):
        """
        Creates keys and a certificate for an AWS IoT thing.

        :return: The certificate ID, ARN, and PEM.
        """
        try:
            response = self.iot_client.create_keys_and_certificate(setAsActive=True)
            logger.info("Created certificate %s.", response["certificateId"])
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't create keys and certificate. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*「[CreateKeysAndCertificate](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/CreateKeysAndCertificate)」を参照してください。

### `CreateThing`
<a name="iot_CreateThing_python_3_topic"></a>

次の例は、`CreateThing` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def create_thing(self, thing_name):
        """
        Creates an AWS IoT thing.

        :param thing_name: The name of the thing to create.
        :return: The name and ARN of the created thing.
        """
        try:
            response = self.iot_client.create_thing(thingName=thing_name)
            logger.info("Created thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.info("Thing %s already exists. Skipping creation.", thing_name)
                return None
            logger.error(
                "Couldn't create thing %s. Here's why: %s: %s",
                thing_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の「[CreateThing](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/CreateThing)」を参照してください。

### `CreateTopicRule`
<a name="iot_CreateTopicRule_python_3_topic"></a>

次の例は、`CreateTopicRule` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def create_topic_rule(self, rule_name, topic, sns_action_arn, role_arn):
        """
        Creates an AWS IoT topic rule.

        :param rule_name: The name of the rule.
        :param topic: The MQTT topic to subscribe to.
        :param sns_action_arn: The ARN of the SNS topic to publish to.
        :param role_arn: The ARN of the IAM role.
        """
        try:
            self.iot_client.create_topic_rule(
                ruleName=rule_name,
                topicRulePayload={
                    "sql": f"SELECT * FROM '{topic}'",
                    "actions": [
                        {"sns": {"targetArn": sns_action_arn, "roleArn": role_arn}}
                    ],
                },
            )
            logger.info("Created topic rule %s.", rule_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.info("Topic rule %s already exists. Skipping creation.", rule_name)
                return
            logger.error(
                "Couldn't create topic rule. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*「[CreateTopicRule](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/CreateTopicRule)」を参照してください。

### `DeleteCertificate`
<a name="iot_DeleteCertificate_python_3_topic"></a>

次の例は、`DeleteCertificate` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def delete_certificate(self, certificate_id):
        """
        Deletes an AWS IoT certificate.

        :param certificate_id: The ID of the certificate to delete.
        """
        try:
            self.iot_client.update_certificate(
                certificateId=certificate_id, newStatus="INACTIVE"
            )
            self.iot_client.delete_certificate(certificateId=certificate_id)
            logger.info("Deleted certificate %s.", certificate_id)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot delete certificate. Resource not found.")
                return
            logger.error(
                "Couldn't delete certificate. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteCertificate](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DeleteCertificate)」を参照してください。

### `DeleteThing`
<a name="iot_DeleteThing_python_3_topic"></a>

次の例は、`DeleteThing` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def delete_thing(self, thing_name):
        """
        Deletes an AWS IoT thing.

        :param thing_name: The name of the thing to delete.
        """
        try:
            self.iot_client.delete_thing(thingName=thing_name)
            logger.info("Deleted thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot delete thing. Resource not found.")
                return
            logger.error(
                "Couldn't delete thing. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[DeleteThing](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DeleteThing)」を参照してください。

### `DeleteTopicRule`
<a name="iot_DeleteTopicRule_python_3_topic"></a>

次の例は、`DeleteTopicRule` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def delete_topic_rule(self, rule_name):
        """
        Deletes an AWS IoT topic rule.

        :param rule_name: The name of the rule to delete.
        """
        try:
            self.iot_client.delete_topic_rule(ruleName=rule_name)
            logger.info("Deleted topic rule %s.", rule_name)
        except ClientError as err:
            logger.error(
                "Couldn't delete topic rule. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*[DeleteTopicRule](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DeleteTopicRule)」を参照してください。

### `DescribeEndpoint`
<a name="iot_DescribeEndpoint_python_3_topic"></a>

次の例は、`DescribeEndpoint` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def describe_endpoint(self, endpoint_type="iot:Data-ATS"):
        """
        Gets the AWS IoT endpoint.

        :param endpoint_type: The endpoint type.
        :return: The endpoint.
        """
        try:
            response = self.iot_client.describe_endpoint(endpointType=endpoint_type)
            logger.info("Retrieved endpoint %s.", response["endpointAddress"])
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't describe endpoint. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response["endpointAddress"]
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*「[DescribeEndpoint](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DescribeEndpoint)」を参照してください。

### `DetachThingPrincipal`
<a name="iot_DetachThingPrincipal_python_3_topic"></a>

次の例は、`DetachThingPrincipal` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def detach_thing_principal(self, thing_name, principal):
        """
        Detaches a certificate from an AWS IoT thing.

        :param thing_name: The name of the thing.
        :param principal: The ARN of the certificate.
        """
        try:
            self.iot_client.detach_thing_principal(
                thingName=thing_name, principal=principal
            )
            logger.info("Detached principal %s from thing %s.", principal, thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot detach principal. Resource not found.")
                return
            logger.error(
                "Couldn't detach principal from thing. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*[DetachThingPrincipal](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/DetachThingPrincipal)」を参照してください。

### `ListCertificates`
<a name="iot_ListCertificates_python_3_topic"></a>

次の例は、`ListCertificates` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def list_certificates(self):
        """
        Lists AWS IoT certificates.

        :return: The list of certificates.
        """
        try:
            certificates = []
            paginator = self.iot_client.get_paginator("list_certificates")
            for page in paginator.paginate():
                certificates.extend(page["certificates"])
            logger.info("Retrieved %s certificates.", len(certificates))
            return certificates
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't list certificates. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[ListCertificates](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/ListCertificates)」を参照してください。

### `ListThings`
<a name="iot_ListThings_python_3_topic"></a>

次の例は、`ListThings` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def list_things(self):
        """
        Lists AWS IoT things.

        :return: The list of things.
        """
        try:
            things = []
            paginator = self.iot_client.get_paginator("list_things")
            for page in paginator.paginate():
                things.extend(page["things"])
            logger.info("Retrieved %s things.", len(things))
            return things
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't list things. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[ListThings](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/ListThings)」を参照してください。

### `SearchIndex`
<a name="iot_SearchIndex_python_3_topic"></a>

次の例は、`SearchIndex` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def search_index(self, query):
        """
        Searches the AWS IoT index.

        :param query: The search query.
        :return: The list of things found.
        """
        try:
            response = self.iot_client.search_index(queryString=query)
            logger.info("Found %s things.", len(response.get("things", [])))
        except ClientError as err:
            if err.response["Error"]["Code"] == "ThrottlingException":
                logger.error("Request throttled. Please try again later.")
            else:
                logger.error(
                    "Couldn't search index. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
            raise
        else:
            return response.get("things", [])
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[SearchIndex](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/SearchIndex)」を参照してください。

### `UpdateIndexingConfiguration`
<a name="iot_UpdateIndexingConfiguration_python_3_topic"></a>

次の例は、`UpdateIndexingConfiguration` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def update_indexing_configuration(self):
        """
        Updates the AWS IoT indexing configuration to enable thing indexing.
        """
        try:
            self.iot_client.update_indexing_configuration(
                thingIndexingConfiguration={"thingIndexingMode": "REGISTRY"}
            )
            logger.info("Updated indexing configuration.")
        except ClientError as err:
            logger.error(
                "Couldn't update indexing configuration. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[UpdateIndexingConfiguration](https://docs.aws.amazon.com/goto/boto3/iot-2015-05-28/UpdateIndexingConfiguration)」を参照してください。

# AWS IoT data SDK for Python (Boto3) を使用した例
<a name="python_3_iot-data-plane_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT data。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetThingShadow`
<a name="iot-data-plane_GetThingShadow_python_3_topic"></a>

次の例は、`GetThingShadow` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def get_thing_shadow(self, thing_name):
        """
        Gets the shadow for an AWS IoT thing.

        :param thing_name: The name of the thing.
        :return: The shadow state as a dictionary.
        """
        import json
        try:
            response = self.iot_data_client.get_thing_shadow(thingName=thing_name)
            shadow = json.loads(response["payload"].read())
            logger.info("Retrieved shadow for thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot get thing shadow. Resource not found.")
                return None
            logger.error(
                "Couldn't get thing shadow. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return shadow
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[GetThingShadow](https://docs.aws.amazon.com/goto/boto3/iot-data-2015-05-28/GetThingShadow)」を参照してください。

### `UpdateThingShadow`
<a name="iot-data-plane_UpdateThingShadow_python_3_topic"></a>

次の例は、`UpdateThingShadow` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iot#code-examples)での設定と実行の方法を確認してください。

```
class IoTWrapper:
    """Encapsulates AWS IoT actions."""

    def __init__(self, iot_client, iot_data_client=None):
        """
        :param iot_client: A Boto3 AWS IoT client.
        :param iot_data_client: A Boto3 AWS IoT Data Plane client.
        """
        self.iot_client = iot_client
        self.iot_data_client = iot_data_client

    @classmethod
    def from_client(cls):
        iot_client = boto3.client("iot")
        iot_data_client = boto3.client("iot-data")
        return cls(iot_client, iot_data_client)

    def update_thing_shadow(self, thing_name, shadow_state):
        """
        Updates the shadow for an AWS IoT thing.

        :param thing_name: The name of the thing.
        :param shadow_state: The shadow state as a dictionary.
        """
        import json
        try:
            self.iot_data_client.update_thing_shadow(
                thingName=thing_name, payload=json.dumps(shadow_state)
            )
            logger.info("Updated shadow for thing %s.", thing_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Cannot update thing shadow. Resource not found.")
                return
            logger.error(
                "Couldn't update thing shadow. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[UpdateThingShadow](https://docs.aws.amazon.com/goto/boto3/iot-data-2015-05-28/UpdateThingShadow)」を参照してください。

# AWS IoT SiteWise SDK for Python (Boto3) を使用した例
<a name="python_3_iotsitewise_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT SiteWise。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoT SiteWiseは
<a name="iotsitewise_Hello_python_3_topic"></a>

次のコード例は、 AWS IoT SiteWiseの使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_iot_sitewise(iot_sitewise_client):
    """
    Use the AWS SDK for Python (Boto3) to create an AWS IoT SiteWise
    client and list the asset models in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param iot_sitewise_client: A Boto3 AWS IoT SiteWise Client object. This object wraps
                             the low-level AWS IoT SiteWise service API.
    """
    print("Hello, AWS IoT SiteWise! Let's list some of your asset models:\n")
    paginator = iot_sitewise_client.get_paginator("list_asset_models")
    page_iterator = paginator.paginate(PaginationConfig={"MaxItems": 10})

    asset_model_names: [str] = []
    for page in page_iterator:
        for asset_model in page["assetModelSummaries"]:
            asset_model_names.append(asset_model["name"])

    print(f"{len(asset_model_names)} asset model(s) retrieved.")
    for asset_model_name in asset_model_names:
        print(f"\t{asset_model_name}")


if __name__ == "__main__":
    hello_iot_sitewise(boto3.client("iotsitewise"))
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンス」の「[ListAssetModels](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/ListAssetModels)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iotsitewise_Scenario_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+  AWS IoT SiteWise アセットモデルを作成します。
+  AWS IoT SiteWise アセットを作成します。
+ プロパティ ID 値を取得します。
+  AWS IoT SiteWise アセットにデータを送信します。
+ Asset AWS IoT SiteWise プロパティの値を取得します。
+  AWS IoT SiteWise ポータルを作成します。
+  AWS IoT SiteWise ゲートウェイを作成します。
+  AWS IoT SiteWise ゲートウェイを記述します。
+  AWS IoT SiteWise アセットを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class IoTSitewiseGettingStarted:
    """
    A scenario that demonstrates how to use Boto3 to manage IoT physical assets using
    the AWS IoT SiteWise.
    """

    def __init__(
        self,
        iot_sitewise_wrapper: IoTSitewiseWrapper,
        cloud_formation_resource: ServiceResource,
    ):
        self.iot_sitewise_wrapper = iot_sitewise_wrapper
        self.cloud_formation_resource = cloud_formation_resource
        self.stack = None
        self.asset_model_id = None
        self.asset_id = None
        self.portal_id = None
        self.gateway_id = None

    def run(self) -> None:
        """
        Runs the scenario.
        """
        print(
            """
AWS IoT SiteWise is a fully managed software-as-a-service (SaaS) that
makes it easy to collect, store, organize, and monitor data from industrial equipment and processes.
It is designed to help industrial and manufacturing organizations collect data from their equipment and
processes, and use that data to make informed decisions about their operations.

One of the key features of AWS IoT SiteWise is its ability to connect to a wide range of industrial
equipment and systems, including programmable logic controllers (PLCs), sensors, and other
industrial devices. It can collect data from these devices and organize it into a unified data model,
making it easier to analyze and gain insights from the data. AWS IoT SiteWise also provides tools for
visualizing the data, setting up alarms and alerts, and generating reports.

Another key feature of AWS IoT SiteWise is its ability to scale to handle large volumes of data.
It can collect and store data from thousands of devices and process millions of data points per second,
making it suitable for large-scale industrial operations. Additionally, AWS IoT SiteWise is designed
to be secure and compliant, with features like role-based access controls, data encryption,
and integration with other AWS services for additional security and compliance features.

Let's get started...
        """
        )
        press_enter_to_continue()
        print_dashes()
        print(f"")
        print(
            f"Use AWS CloudFormation to create an IAM role that is required for this scenario."
        )
        template_file = IoTSitewiseGettingStarted.get_template_as_string()

        self.stack = self.deploy_cloudformation_stack(
            "python-iot-sitewise-basics", template_file
        )
        outputs = self.stack.outputs
        iam_role = None

        for output in outputs:
            if output.get("OutputKey") == "SitewiseRoleArn":
                iam_role = output.get("OutputValue")

        if iam_role is None:
            error_string = f"Failed to retrieve iam_role from CloudFormation stack."
            logger.error(error_string)
            raise ValueError(error_string)

        print(f"The ARN of the IAM role is {iam_role}")
        print_dashes()
        print_dashes()
        print(f"1. Create an AWS SiteWise Asset Model")
        print(
            """
An AWS IoT SiteWise Asset Model is a way to represent the physical assets, such as equipment,
processes, and systems, that exist in an industrial environment. This model provides a structured and
hierarchical representation of these assets, allowing users to define the relationships and values
of each asset.

This scenario creates two asset model values: temperature and humidity.
        """
        )
        press_enter_to_continue()
        asset_model_name = "MyAssetModel1"
        temperature_property_name = "temperature"
        humidity_property_name = "humidity"
        try:
            properties = [
                {
                    "name": temperature_property_name,
                    "dataType": "DOUBLE",
                    "type": {
                        "measurement": {},
                    },
                },
                {
                    "name": humidity_property_name,
                    "dataType": "DOUBLE",
                    "type": {
                        "measurement": {},
                    },
                },
            ]
            self.asset_model_id = self.iot_sitewise_wrapper.create_asset_model(
                asset_model_name, properties
            )
            print(
                f"Asset Model successfully created. Asset Model ID: {self.asset_model_id}. "
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                self.asset_model_id = self.get_model_id_for_model_name(asset_model_name)
                print(
                    f"Asset Model {asset_model_name} already exists. Asset Model ID: {self.asset_model_id}. "
                )
            else:
                raise

        press_enter_to_continue()
        print_dashes()
        print(f"2. Create an AWS IoT SiteWise Asset")
        print(
            """
The IoT SiteWise model that we just created defines the structure and metadata for your physical assets.
Now we create an asset from the asset model.
        
        """
        )
        press_enter_to_continue()

        self.asset_id = self.iot_sitewise_wrapper.create_asset(
            "MyAsset1", self.asset_model_id
        )

        print(f"Asset created with ID: {self.asset_id}")
        press_enter_to_continue()
        print_dashes()
        print_dashes()
        print(f"3. Retrieve the property ID values")
        print(
            """
To send data to an asset, we need to get the property ID values. In this scenario, we access the
temperature and humidity property ID values.
        """
        )
        press_enter_to_continue()
        property_ids = self.iot_sitewise_wrapper.list_asset_model_properties(
            self.asset_model_id
        )
        humidity_property_id = None
        temperature_property_id = None
        for property_id in property_ids:
            if property_id.get("name") == humidity_property_name:
                humidity_property_id = property_id.get("id")
            elif property_id.get("name") == temperature_property_name:
                temperature_property_id = property_id.get("id")
        if humidity_property_id is None or temperature_property_id is None:
            error_string = f"Failed to retrieve property IDs from Asset Model."
            logger.error(error_string)
            raise ValueError(error_string)

        print(f"The Humidity property Id is {humidity_property_id}")
        print(f"The Temperature property Id is {temperature_property_id}")
        press_enter_to_continue()
        print_dashes()
        print_dashes()

        print(f"4. Send data to an AWS IoT SiteWise Asset")
        print(
            """
By sending data to an IoT SiteWise Asset, you can aggregate data from
multiple sources, normalize the data into a standard format, and store it in a
centralized location. This makes it easier to analyze and gain insights from the data.

In this example, we generate sample temperature and humidity data and send it to the AWS IoT SiteWise asset.

        """
        )
        press_enter_to_continue()

        values = [
            {
                "propertyId": humidity_property_id,
                "valueType": "doubleValue",
                "value": 65.0,
            },
            {
                "propertyId": temperature_property_id,
                "valueType": "doubleValue",
                "value": 23.5,
            },
        ]
        self.iot_sitewise_wrapper.batch_put_asset_property_value(self.asset_id, values)
        print(f"Data sent successfully.")

        press_enter_to_continue()
        print_dashes()
        print_dashes()

        print(f"5. Retrieve the value of the IoT SiteWise Asset property")
        print(
            """
IoT SiteWise is an AWS service that allows you to collect, process, and analyze industrial data
from connected equipment and sensors. One of the key benefits of reading an IoT SiteWise property
is the ability to gain valuable insights from your industrial data.
        
        """
        )
        press_enter_to_continue()

        property_value = self.iot_sitewise_wrapper.get_asset_property_value(
            self.asset_id, temperature_property_id
        )
        print(f"The property name is '{temperature_property_name}'.")

        print(
            f"The value of this property is: {property_value['value']['doubleValue']}"
        )
        press_enter_to_continue()

        property_value = self.iot_sitewise_wrapper.get_asset_property_value(
            self.asset_id, humidity_property_id
        )
        print(f"The property name is '{humidity_property_name}'.")
        print(
            f"The value of this property is: {property_value['value']['doubleValue']}"
        )
        press_enter_to_continue()
        print_dashes()
        print_dashes()

        print(f"6. Create an IoT SiteWise Portal")
        print(
            """
An IoT SiteWise Portal allows you to aggregate data from multiple industrial sources,
such as sensors, equipment, and control systems, into a centralized platform.
        """
        )

        press_enter_to_continue()
        contact_email = q.ask("Enter a contact email for the portal:", q.non_empty)
        print("Creating the portal. The portal may take a while to become active.")
        self.portal_id = self.iot_sitewise_wrapper.create_portal(
            "MyPortal1", iam_role, contact_email
        )
        print(f"Portal created successfully. Portal ID {self.portal_id}")
        press_enter_to_continue()
        print_dashes()
        print_dashes()

        print(f"7. Describe the Portal")
        print(
            """
In this step, we get a description of the portal and display the portal URL.
        """
        )
        press_enter_to_continue()
        portal_description = self.iot_sitewise_wrapper.describe_portal(self.portal_id)
        print(f"Portal URL: {portal_description['portalStartUrl']}")
        press_enter_to_continue()
        print_dashes()
        print_dashes()

        print(f"8. Create an IoT SiteWise Gateway")
        press_enter_to_continue()
        self.gateway_id = self.iot_sitewise_wrapper.create_gateway(
            "MyGateway1", "MyThing1"
        )
        print(f"Gateway creation completed successfully. id is {self.gateway_id}")
        print_dashes()
        print_dashes()
        print(f"9. Describe the IoT SiteWise Gateway")
        press_enter_to_continue()

        gateway_description = self.iot_sitewise_wrapper.describe_gateway(
            self.gateway_id
        )
        print(f"Gateway Name: {gateway_description['gatewayName']}")
        print(f"Gateway ARN: {gateway_description['gatewayArn']}")
        print(f"Gateway Platform:\n{gateway_description['gatewayPlatform']}")
        print(f"Gateway Creation Date: {gateway_description['gatewayArn']}")
        print_dashes()
        print_dashes()

        print(f"10. Delete the AWS IoT SiteWise Assets")
        if q.ask("Would you like to delete the IoT SiteWise Assets? (y/n)", q.is_yesno):
            self.cleanup()
        else:
            print(f"The resources will not be deleted.")
        print_dashes()
        print_dashes()
        print(f"This concludes the AWS IoT SiteWise Scenario")

    def cleanup(self) -> None:
        """
        Deletes the CloudFormation stack and the resources created for the demo.
        """

        if self.gateway_id is not None:
            self.iot_sitewise_wrapper.delete_gateway(self.gateway_id)
            print(f"Deleted gateway with id {self.gateway_id}.")
            self.gateway_id = None
        if self.portal_id is not None:
            self.iot_sitewise_wrapper.delete_portal(self.portal_id)
            print(f"Deleted portal with id {self.portal_id}.")
            self.portal_id = None
        if self.asset_id is not None:
            self.iot_sitewise_wrapper.delete_asset(self.asset_id)
            print(f"Deleted asset with id {self.asset_id}.")
            self.iot_sitewise_wrapper.wait_asset_deleted(self.asset_id)
            self.asset_id = None
        if self.asset_model_id is not None:
            self.iot_sitewise_wrapper.delete_asset_model(self.asset_model_id)
            print(f"Deleted asset model with id {self.asset_model_id}.")
            self.asset_model_id = None
        if self.stack is not None:
            stack = self.stack
            self.stack = None
            self.destroy_cloudformation_stack(stack)

    def deploy_cloudformation_stack(
        self, stack_name: str, cfn_template: str
    ) -> ServiceResource:
        """
        Deploys prerequisite resources used by the scenario. The resources are
        defined in the associated `SitewiseRoles-template.yaml` AWS CloudFormation script and are deployed
        as a CloudFormation stack, so they can be easily managed and destroyed.

        :param stack_name: The name of the CloudFormation stack.
        :param cfn_template: The CloudFormation template as a string.
        :return: The CloudFormation stack resource.
        """
        print(f"Deploying CloudFormation stack: {stack_name}.")
        stack = self.cloud_formation_resource.create_stack(
            StackName=stack_name,
            TemplateBody=cfn_template,
            Capabilities=["CAPABILITY_NAMED_IAM"],
        )
        print(f"CloudFormation stack creation started: {stack_name}")
        print("Waiting for CloudFormation stack creation to complete...")
        waiter = self.cloud_formation_resource.meta.client.get_waiter(
            "stack_create_complete"
        )
        waiter.wait(StackName=stack.name)
        stack.load()
        print("CloudFormation stack creation complete.")

        return stack

    def destroy_cloudformation_stack(self, stack: ServiceResource) -> None:
        """
        Destroys the resources managed by the CloudFormation stack, and the CloudFormation
        stack itself.

        :param stack: The CloudFormation stack that manages the example resources.
        """
        print(
            f"CloudFormation stack '{stack.name}' is being deleted. This may take a few minutes."
        )
        stack.delete()
        waiter = self.cloud_formation_resource.meta.client.get_waiter(
            "stack_delete_complete"
        )
        waiter.wait(StackName=stack.name)
        print(f"CloudFormation stack '{stack.name}' has been deleted.")

    @staticmethod
    def get_template_as_string() -> str:
        """
        Returns a string containing this scenario's CloudFormation template.
        """
        template_file_path = os.path.join(script_dir, "SitewiseRoles-template.yaml")
        file = open(template_file_path, "r")
        return file.read()

    def get_model_id_for_model_name(self, model_name: str) -> str:
        """
        Returns the model ID for the given model name.

        :param model_name: The name of the model.
        :return: The model ID.
        """
        model_id = None
        asset_models = self.iot_sitewise_wrapper.list_asset_models()
        for asset_model in asset_models:
            if asset_model["name"] == model_name:
                model_id = asset_model["id"]
                break
        return model_id
```
 AWS IoT SiteWise アクションをラップする IoTSitewiseWrapper クラス。  

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def create_asset_model(
        self, asset_model_name: str, properties: List[Dict[str, Any]]
    ) -> str:
        """
        Creates an AWS IoT SiteWise Asset Model.

        :param asset_model_name: The name of the asset model to create.
        :param properties: The property definitions of the asset model.
        :return: The ID of the created asset model.
        """
        try:
            response = self.iotsitewise_client.create_asset_model(
                assetModelName=asset_model_name,
                assetModelDescription="This is a sample asset model description.",
                assetModelProperties=properties,
            )
            asset_model_id = response["assetModelId"]
            waiter = self.iotsitewise_client.get_waiter("asset_model_active")
            waiter.wait(assetModelId=asset_model_id)
            return asset_model_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.error("Asset model %s already exists.", asset_model_name)
            else:
                logger.error(
                    "Error creating asset model %s. Here's why %s",
                    asset_model_name,
                    err.response["Error"]["Message"],
                )
            raise


    def create_asset(self, asset_name: str, asset_model_id: str) -> str:
        """
        Creates an AWS IoT SiteWise Asset.

        :param asset_name: The name of the asset to create.
        :param asset_model_id: The ID of the asset model to associate with the asset.
        :return: The ID of the created asset.
        """
        try:
            response = self.iotsitewise_client.create_asset(
                assetName=asset_name, assetModelId=asset_model_id
            )
            asset_id = response["assetId"]
            waiter = self.iotsitewise_client.get_waiter("asset_active")
            waiter.wait(assetId=asset_id)
            return asset_id
        except ClientError as err:
            if err.response["Error"] == "ResourceNotFoundException":
                logger.error("Asset model %s does not exist.", asset_model_id)
            else:
                logger.error(
                    "Error creating asset %s. Here's why %s",
                    asset_name,
                    err.response["Error"]["Message"],
                )
            raise


    def list_asset_models(self) -> List[Dict[str, Any]]:
        """
        Lists all AWS IoT SiteWise Asset Models.

        :return: A list of dictionaries containing information about each asset model.

        """
        try:
            asset_models = []
            paginator = self.iotsitewise_client.get_paginator("list_asset_models")
            pages = paginator.paginate()
            for page in pages:
                asset_models.extend(page["assetModelSummaries"])
            return asset_models
        except ClientError as err:
            logger.error(
                "Error listing asset models. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise


    def list_asset_model_properties(self, asset_model_id: str) -> List[Dict[str, Any]]:
        """
        Lists all AWS IoT SiteWise Asset Model Properties.

        :param asset_model_id: The ID of the asset model to list values for.
        :return: A list of dictionaries containing information about each asset model property.
        """
        try:
            asset_model_properties = []
            paginator = self.iotsitewise_client.get_paginator(
                "list_asset_model_properties"
            )
            pages = paginator.paginate(assetModelId=asset_model_id)
            for page in pages:
                asset_model_properties.extend(page["assetModelPropertySummaries"])
            return asset_model_properties
        except ClientError as err:
            logger.error(
                "Error listing asset model values. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise


    def batch_put_asset_property_value(
        self, asset_id: str, values: List[Dict[str, str]]
    ) -> None:
        """
        Sends data to an AWS IoT SiteWise Asset.

        :param asset_id: The asset ID.
        :param values: A list of dictionaries containing the values in the form
                        {propertyId : property_id,
                        valueType : [stringValue|integerValue|doubleValue|booleanValue],
                        value : the_value}.
        """
        try:
            entries = self.properties_to_values(asset_id, values)
            self.iotsitewise_client.batch_put_asset_property_value(entries=entries)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Asset %s does not exist.", asset_id)
            else:
                logger.error(
                    "Error sending data to asset. Here's why %s",
                    err.response["Error"]["Message"],
                )
            raise


    def properties_to_values(
        self, asset_id: str, values: list[dict[str, Any]]
    ) -> list[dict[str, Any]]:
        """
        Utility function to convert a values list to the entries parameter for batch_put_asset_property_value.
        :param asset_id : The asset ID.
        :param values : A list of dictionaries containing the values in the form
                        {propertyId : property_id,
                        valueType : [stringValue|integerValue|doubleValue|booleanValue],
                        value : the_value}.
        :return: An entries list to pass as the 'entries' parameter to batch_put_asset_property_value.
        """
        entries = []
        for value in values:
            epoch_ns = time.time_ns()
            self.entry_id += 1
            if value["valueType"] == "stringValue":
                property_value = {"stringValue": value["value"]}
            elif value["valueType"] == "integerValue":
                property_value = {"integerValue": value["value"]}
            elif value["valueType"] == "booleanValue":
                property_value = {"booleanValue": value["value"]}
            elif value["valueType"] == "doubleValue":
                property_value = {"doubleValue": value["value"]}
            else:
                raise ValueError("Invalid valueType: %s", value["valueType"])
            entry = {
                "entryId": f"{self.entry_id}",
                "assetId": asset_id,
                "propertyId": value["propertyId"],
                "propertyValues": [
                    {
                        "value": property_value,
                        "timestamp": {
                            "timeInSeconds": int(epoch_ns / 1000000000),
                            "offsetInNanos": epoch_ns % 1000000000,
                        },
                    }
                ],
            }
            entries.append(entry)
        return entries


    def get_asset_property_value(
        self, asset_id: str, property_id: str
    ) -> Dict[str, Any]:
        """
        Gets the value of an AWS IoT SiteWise Asset Property.

        :param asset_id: The ID of the asset.
        :param property_id: The ID of the property.
        :return: A dictionary containing the value of the property.
        """
        try:
            response = self.iotsitewise_client.get_asset_property_value(
                assetId=asset_id, propertyId=property_id
            )
            return response["propertyValue"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Asset %s or property %s does not exist.", asset_id, property_id
                )
            else:
                logger.error(
                    "Error getting asset property value. Here's why %s",
                    err.response["Error"]["Message"],
                )
            raise


    def create_portal(
        self, portal_name: str, iam_role_arn: str, portal_contact_email: str
    ) -> str:
        """
        Creates an AWS IoT SiteWise Portal.

        :param portal_name: The name of the portal to create.
        :param iam_role_arn: The ARN of an IAM role.
        :param portal_contact_email: The contact email of the portal.
        :return: The ID of the created portal.
        """
        try:
            response = self.iotsitewise_client.create_portal(
                portalName=portal_name,
                roleArn=iam_role_arn,
                portalContactEmail=portal_contact_email,
            )
            portal_id = response["portalId"]
            waiter = self.iotsitewise_client.get_waiter("portal_active")
            waiter.wait(portalId=portal_id, WaiterConfig={"MaxAttempts": 40})
            return portal_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.error("Portal %s already exists.", portal_name)
            else:
                logger.error(
                    "Error creating portal %s. Here's why %s",
                    portal_name,
                    err.response["Error"]["Message"],
                )
            raise


    def describe_portal(self, portal_id: str) -> Dict[str, Any]:
        """
        Describes an AWS IoT SiteWise Portal.

        :param portal_id: The ID of the portal to describe.
        :return: A dictionary containing information about the portal.
        """
        try:
            response = self.iotsitewise_client.describe_portal(portalId=portal_id)
            return response
        except ClientError as err:
            logger.error(
                "Error describing portal %s. Here's why %s",
                portal_id,
                err.response["Error"]["Message"],
            )
            raise


    def create_gateway(self, gateway_name: str, my_thing: str) -> str:
        """
        Creates an AWS IoT SiteWise Gateway.

        :param gateway_name: The name of the gateway to create.
        :param my_thing: The core device thing name.
        :return: The ID of the created gateway.
        """
        try:
            response = self.iotsitewise_client.create_gateway(
                gatewayName=gateway_name,
                gatewayPlatform={
                    "greengrassV2": {"coreDeviceThingName": my_thing},
                },
                tags={"Environment": "Production"},
            )
            gateway_id = response["gatewayId"]
            return gateway_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.error("Gateway %s already exists.", gateway_name)
            else:
                logger.error(
                    "Error creating gateway %s. Here's why %s",
                    gateway_name,
                    err.response["Error"]["Message"],
                )
            raise


    def describe_gateway(self, gateway_id: str) -> Dict[str, Any]:
        """
        Describes an AWS IoT SiteWise Gateway.

        :param gateway_id: The ID of the gateway to describe.
        :return: A dictionary containing information about the gateway.
        """
        try:
            response = self.iotsitewise_client.describe_gateway(gatewayId=gateway_id)
            return response
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Gateway %s does not exist.", gateway_id)
            else:
                logger.error(
                    "Error describing gateway %s. Here's why %s",
                    gateway_id,
                    err.response["Error"]["Message"],
                )
            raise


    def delete_gateway(self, gateway_id: str) -> None:
        """
        Deletes an AWS IoT SiteWise Gateway.

        :param gateway_id: The ID of the gateway to delete.
        """
        try:
            self.iotsitewise_client.delete_gateway(gatewayId=gateway_id)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Gateway %s does not exist.", gateway_id)
            else:
                logger.error(
                    "Error deleting gateway %s. Here's why %s",
                    gateway_id,
                    err.response["Error"]["Message"],
                )
            raise


    def delete_portal(self, portal_id: str) -> None:
        """
        Deletes an AWS IoT SiteWise Portal.

        :param portal_id: The ID of the portal to delete.
        """
        try:
            self.iotsitewise_client.delete_portal(portalId=portal_id)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Portal %s does not exist.", portal_id)
            else:
                logger.error(
                    "Error deleting portal %s. Here's why %s",
                    portal_id,
                    err.response["Error"]["Message"],
                )
            raise


    def delete_asset(self, asset_id: str) -> None:
        """
        Deletes an AWS IoT SiteWise Asset.

        :param asset_id: The ID of the asset to delete.
        """
        try:
            self.iotsitewise_client.delete_asset(assetId=asset_id)
        except ClientError as err:
            logger.error(
                "Error deleting asset %s. Here's why %s",
                asset_id,
                err.response["Error"]["Message"],
            )
            raise


    def delete_asset_model(self, asset_model_id: str) -> None:
        """
        Deletes an AWS IoT SiteWise Asset Model.

        :param asset_model_id: The ID of the asset model to delete.
        """
        try:
            self.iotsitewise_client.delete_asset_model(assetModelId=asset_model_id)
        except ClientError as err:
            logger.error(
                "Error deleting asset model %s. Here's why %s",
                asset_model_id,
                err.response["Error"]["Message"],
            )
            raise


    def wait_asset_deleted(self, asset_id: str) -> None:
        """
        Waits for an AWS IoT SiteWise Asset to be deleted.

        :param asset_id: The ID of the asset to wait for.
        """
        try:
            waiter = self.iotsitewise_client.get_waiter("asset_not_exists")
            waiter.wait(assetId=asset_id)
        except ClientError as err:
            logger.error(
                "Error waiting for asset %s to be deleted. Here's why %s",
                asset_id,
                err.response["Error"]["Message"],
            )
            raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [BatchPutAssetPropertyValue](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/BatchPutAssetPropertyValue)
  + [CreateAsset](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/CreateAsset)
  + [CreateAssetModel](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/CreateAssetModel)
  + [CreateGateway](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/CreateGateway)
  + [DeleteAsset](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DeleteAsset)
  + [DeleteAssetModel](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DeleteAssetModel)
  + [DeleteGateway](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DeleteGateway)
  + [DescribeAssetModel](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DescribeAssetModel)
  + [DescribeGateway](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DescribeGateway)
  + [GetAssetPropertyValue](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/GetAssetPropertyValue)
  + [ListAssetModelProperties](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/ListAssetModelProperties)
  + [ListAssetModels](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/ListAssetModels)

## アクション
<a name="actions"></a>

### `BatchPutAssetPropertyValue`
<a name="iotsitewise_BatchPutAssetPropertyValue_python_3_topic"></a>

次のコード例は、`BatchPutAssetPropertyValue` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def batch_put_asset_property_value(
        self, asset_id: str, values: List[Dict[str, str]]
    ) -> None:
        """
        Sends data to an AWS IoT SiteWise Asset.

        :param asset_id: The asset ID.
        :param values: A list of dictionaries containing the values in the form
                        {propertyId : property_id,
                        valueType : [stringValue|integerValue|doubleValue|booleanValue],
                        value : the_value}.
        """
        try:
            entries = self.properties_to_values(asset_id, values)
            self.iotsitewise_client.batch_put_asset_property_value(entries=entries)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Asset %s does not exist.", asset_id)
            else:
                logger.error(
                    "Error sending data to asset. Here's why %s",
                    err.response["Error"]["Message"],
                )
            raise
```
値リストからエントリパラメータを生成するヘルパー関数。  

```
    def properties_to_values(
        self, asset_id: str, values: list[dict[str, Any]]
    ) -> list[dict[str, Any]]:
        """
        Utility function to convert a values list to the entries parameter for batch_put_asset_property_value.
        :param asset_id : The asset ID.
        :param values : A list of dictionaries containing the values in the form
                        {propertyId : property_id,
                        valueType : [stringValue|integerValue|doubleValue|booleanValue],
                        value : the_value}.
        :return: An entries list to pass as the 'entries' parameter to batch_put_asset_property_value.
        """
        entries = []
        for value in values:
            epoch_ns = time.time_ns()
            self.entry_id += 1
            if value["valueType"] == "stringValue":
                property_value = {"stringValue": value["value"]}
            elif value["valueType"] == "integerValue":
                property_value = {"integerValue": value["value"]}
            elif value["valueType"] == "booleanValue":
                property_value = {"booleanValue": value["value"]}
            elif value["valueType"] == "doubleValue":
                property_value = {"doubleValue": value["value"]}
            else:
                raise ValueError("Invalid valueType: %s", value["valueType"])
            entry = {
                "entryId": f"{self.entry_id}",
                "assetId": asset_id,
                "propertyId": value["propertyId"],
                "propertyValues": [
                    {
                        "value": property_value,
                        "timestamp": {
                            "timeInSeconds": int(epoch_ns / 1000000000),
                            "offsetInNanos": epoch_ns % 1000000000,
                        },
                    }
                ],
            }
            entries.append(entry)
        return entries
```
ヘルパー関数に渡す値リストの例を次に示します。  

```
        values = [
            {
                "propertyId": humidity_property_id,
                "valueType": "doubleValue",
                "value": 65.0,
            },
            {
                "propertyId": temperature_property_id,
                "valueType": "doubleValue",
                "value": 23.5,
            },
        ]
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[BatchPutAssetPropertyValue](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/BatchPutAssetPropertyValue)」を参照してください。**

### `CreateAsset`
<a name="iotsitewise_CreateAsset_python_3_topic"></a>

次のコード例は、`CreateAsset` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def create_asset(self, asset_name: str, asset_model_id: str) -> str:
        """
        Creates an AWS IoT SiteWise Asset.

        :param asset_name: The name of the asset to create.
        :param asset_model_id: The ID of the asset model to associate with the asset.
        :return: The ID of the created asset.
        """
        try:
            response = self.iotsitewise_client.create_asset(
                assetName=asset_name, assetModelId=asset_model_id
            )
            asset_id = response["assetId"]
            waiter = self.iotsitewise_client.get_waiter("asset_active")
            waiter.wait(assetId=asset_id)
            return asset_id
        except ClientError as err:
            if err.response["Error"] == "ResourceNotFoundException":
                logger.error("Asset model %s does not exist.", asset_model_id)
            else:
                logger.error(
                    "Error creating asset %s. Here's why %s",
                    asset_name,
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateAsset](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/CreateAsset)」を参照してください。**

### `CreateAssetModel`
<a name="iotsitewise_CreateAssetModel_python_3_topic"></a>

次のコード例は、`CreateAssetModel` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def create_asset_model(
        self, asset_model_name: str, properties: List[Dict[str, Any]]
    ) -> str:
        """
        Creates an AWS IoT SiteWise Asset Model.

        :param asset_model_name: The name of the asset model to create.
        :param properties: The property definitions of the asset model.
        :return: The ID of the created asset model.
        """
        try:
            response = self.iotsitewise_client.create_asset_model(
                assetModelName=asset_model_name,
                assetModelDescription="This is a sample asset model description.",
                assetModelProperties=properties,
            )
            asset_model_id = response["assetModelId"]
            waiter = self.iotsitewise_client.get_waiter("asset_model_active")
            waiter.wait(assetModelId=asset_model_id)
            return asset_model_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.error("Asset model %s already exists.", asset_model_name)
            else:
                logger.error(
                    "Error creating asset model %s. Here's why %s",
                    asset_model_name,
                    err.response["Error"]["Message"],
                )
            raise
```
関数に渡すプロパティリストの例を次に示します。  

```
            properties = [
                {
                    "name": temperature_property_name,
                    "dataType": "DOUBLE",
                    "type": {
                        "measurement": {},
                    },
                },
                {
                    "name": humidity_property_name,
                    "dataType": "DOUBLE",
                    "type": {
                        "measurement": {},
                    },
                },
            ]
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateAssetModel](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/CreateAssetModel)」を参照してください。**

### `CreateGateway`
<a name="iotsitewise_CreateGateway_python_3_topic"></a>

次のコード例は、`CreateGateway` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def create_gateway(self, gateway_name: str, my_thing: str) -> str:
        """
        Creates an AWS IoT SiteWise Gateway.

        :param gateway_name: The name of the gateway to create.
        :param my_thing: The core device thing name.
        :return: The ID of the created gateway.
        """
        try:
            response = self.iotsitewise_client.create_gateway(
                gatewayName=gateway_name,
                gatewayPlatform={
                    "greengrassV2": {"coreDeviceThingName": my_thing},
                },
                tags={"Environment": "Production"},
            )
            gateway_id = response["gatewayId"]
            return gateway_id
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceAlreadyExistsException":
                logger.error("Gateway %s already exists.", gateway_name)
            else:
                logger.error(
                    "Error creating gateway %s. Here's why %s",
                    gateway_name,
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateGateway](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/CreateGateway)」を参照してください。**

### `DeleteAsset`
<a name="iotsitewise_DeleteAsset_python_3_topic"></a>

次の例は、`DeleteAsset` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def delete_asset(self, asset_id: str) -> None:
        """
        Deletes an AWS IoT SiteWise Asset.

        :param asset_id: The ID of the asset to delete.
        """
        try:
            self.iotsitewise_client.delete_asset(assetId=asset_id)
        except ClientError as err:
            logger.error(
                "Error deleting asset %s. Here's why %s",
                asset_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteAsset](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DeleteAsset)」を参照してください。**

### `DeleteAssetModel`
<a name="iotsitewise_DeleteAssetModel_python_3_topic"></a>

次のコード例は、`DeleteAssetModel` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def delete_asset_model(self, asset_model_id: str) -> None:
        """
        Deletes an AWS IoT SiteWise Asset Model.

        :param asset_model_id: The ID of the asset model to delete.
        """
        try:
            self.iotsitewise_client.delete_asset_model(assetModelId=asset_model_id)
        except ClientError as err:
            logger.error(
                "Error deleting asset model %s. Here's why %s",
                asset_model_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteAssetModel](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DeleteAssetModel)」を参照してください。**

### `DeleteGateway`
<a name="iotsitewise_DeleteGateway_python_3_topic"></a>

次のコード例は、`DeleteGateway` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def delete_gateway(self, gateway_id: str) -> None:
        """
        Deletes an AWS IoT SiteWise Gateway.

        :param gateway_id: The ID of the gateway to delete.
        """
        try:
            self.iotsitewise_client.delete_gateway(gatewayId=gateway_id)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Gateway %s does not exist.", gateway_id)
            else:
                logger.error(
                    "Error deleting gateway %s. Here's why %s",
                    gateway_id,
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteGateway](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DeleteGateway)」を参照してください。**

### `DescribeGateway`
<a name="iotsitewise_DescribeGateway_python_3_topic"></a>

次の例は、`DescribeGateway` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def describe_gateway(self, gateway_id: str) -> Dict[str, Any]:
        """
        Describes an AWS IoT SiteWise Gateway.

        :param gateway_id: The ID of the gateway to describe.
        :return: A dictionary containing information about the gateway.
        """
        try:
            response = self.iotsitewise_client.describe_gateway(gatewayId=gateway_id)
            return response
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Gateway %s does not exist.", gateway_id)
            else:
                logger.error(
                    "Error describing gateway %s. Here's why %s",
                    gateway_id,
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeGateway](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/DescribeGateway)」を参照してください。**

### `GetAssetPropertyValue`
<a name="iotsitewise_GetAssetPropertyValue_python_3_topic"></a>

次の例は、`GetAssetPropertyValue` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def get_asset_property_value(
        self, asset_id: str, property_id: str
    ) -> Dict[str, Any]:
        """
        Gets the value of an AWS IoT SiteWise Asset Property.

        :param asset_id: The ID of the asset.
        :param property_id: The ID of the property.
        :return: A dictionary containing the value of the property.
        """
        try:
            response = self.iotsitewise_client.get_asset_property_value(
                assetId=asset_id, propertyId=property_id
            )
            return response["propertyValue"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error(
                    "Asset %s or property %s does not exist.", asset_id, property_id
                )
            else:
                logger.error(
                    "Error getting asset property value. Here's why %s",
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAssetPropertyValue](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/GetAssetPropertyValue)」を参照してください。**

### `ListAssetModels`
<a name="iotsitewise_ListAssetModels_python_3_topic"></a>

次のコード例は、`ListAssetModels` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/iotsitewise#code-examples)での設定と実行の方法を確認してください。

```
class IoTSitewiseWrapper:
    """Encapsulates AWS IoT SiteWise actions using the client interface."""

    def __init__(self, iotsitewise_client: client) -> None:
        """
        Initializes the IoTSitewiseWrapper with an AWS IoT SiteWise client.

        :param iotsitewise_client: A Boto3 AWS IoT SiteWise client. This client provides low-level
                           access to AWS IoT SiteWise services.
        """
        self.iotsitewise_client = iotsitewise_client
        self.entry_id = 0 # Incremented to generate unique entry IDs for batch_put_asset_property_value.

    @classmethod
    def from_client(cls) -> "IoTSitewiseWrapper":
        """
        Creates an IoTSitewiseWrapper instance with a default AWS IoT SiteWise client.

        :return: An instance of IoTSitewiseWrapper initialized with the default AWS IoT SiteWise client.
        """
        iotsitewise_client = boto3.client("iotsitewise")
        return cls(iotsitewise_client)


    def list_asset_models(self) -> List[Dict[str, Any]]:
        """
        Lists all AWS IoT SiteWise Asset Models.

        :return: A list of dictionaries containing information about each asset model.

        """
        try:
            asset_models = []
            paginator = self.iotsitewise_client.get_paginator("list_asset_models")
            pages = paginator.paginate()
            for page in pages:
                asset_models.extend(page["assetModelSummaries"])
            return asset_models
        except ClientError as err:
            logger.error(
                "Error listing asset models. Here's why %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListAssetModels](https://docs.aws.amazon.com/goto/boto3/iotsitewise-2019-12-02/ListAssetModels)」を参照してください。**

# SDK for Python (Boto3) を使用する Amazon Keyspaces の例
<a name="python_3_keyspaces_code_examples"></a>

次のコード例は、Amazon Keyspaces AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Keyspaces
<a name="keyspaces_Hello_python_3_topic"></a>

次のコード例は、Amazon Keyspaces の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_keyspaces(keyspaces_client):
    """
    Use the AWS SDK for Python (Boto3) to create an Amazon Keyspaces (for Apache Cassandra)
    client and list the keyspaces in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param keyspaces_client: A Boto3 Amazon Keyspaces Client object. This object wraps
                             the low-level Amazon Keyspaces service API.
    """
    print("Hello, Amazon Keyspaces! Let's list some of your keyspaces:\n")
    for ks in keyspaces_client.list_keyspaces(maxResults=5).get("keyspaces", []):
        print(ks["keyspaceName"])
        print(f"\t{ks['resourceArn']}")


if __name__ == "__main__":
    hello_keyspaces(boto3.client("keyspaces"))
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[ListKeyspaces](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/ListKeyspaces)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="keyspaces_Scenario_GetStartedKeyspaces_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キースペースとテーブルを作成する。テーブルスキーマにはムービーデータが保存され、ポイントインタイムリカバリが有効になっています。
+ SigV4 認証による安全な TLS 接続を使用してキースペースに接続します。
+ テーブルに対してクエリを実行します。ムービーデータを追加、取得、更新します。
+ テーブルを更新する。視聴したムービーを追跡する列を追加します。
+ テーブルを以前の状態に戻し、リソースをクリーンアップします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class KeyspaceScenario:
    """Runs an interactive scenario that shows how to get started using Amazon Keyspaces."""

    def __init__(self, ks_wrapper):
        """
        :param ks_wrapper: An object that wraps Amazon Keyspace actions.
        """
        self.ks_wrapper = ks_wrapper

    @demo_func
    def create_keyspace(self):
        """
        1. Creates a keyspace.
        2. Lists up to 10 keyspaces in your account.
        """
        print("Let's create a keyspace.")
        ks_name = q.ask(
            "Enter a name for your new keyspace.\nThe name can contain only letters, "
            "numbers and underscores: ",
            q.non_empty,
        )
        if self.ks_wrapper.exists_keyspace(ks_name):
            print(f"A keyspace named {ks_name} exists.")
        else:
            ks_arn = self.ks_wrapper.create_keyspace(ks_name)
            ks_exists = False
            while not ks_exists:
                wait(3)
                ks_exists = self.ks_wrapper.exists_keyspace(ks_name)
            print(f"Created a new keyspace.\n\t{ks_arn}.")
        print("The first 10 keyspaces in your account are:\n")
        self.ks_wrapper.list_keyspaces(10)

    @demo_func
    def create_table(self):
        """
        1. Creates a table in the keyspace. The table is configured with a schema to hold
           movie data and has point-in-time recovery enabled.
        2. Waits for the table to be in an active state.
        3. Displays schema information for the table.
        4. Lists tables in the keyspace.
        """
        print("Let's create a table for movies in your keyspace.")
        table_name = q.ask("Enter a name for your table: ", q.non_empty)
        table = self.ks_wrapper.get_table(table_name)
        if table is not None:
            print(
                f"A table named {table_name} already exists in keyspace "
                f"{self.ks_wrapper.ks_name}."
            )
        else:
            table_arn = self.ks_wrapper.create_table(table_name)
            print(f"Created table {table_name}:\n\t{table_arn}")
            table = {"status": None}
            print("Waiting for your table to be ready...")
            while table["status"] != "ACTIVE":
                wait(5)
                table = self.ks_wrapper.get_table(table_name)
        print(f"Your table is {table['status']}. Its schema is:")
        pp(table["schemaDefinition"])
        print("\nThe tables in your keyspace are:\n")
        self.ks_wrapper.list_tables()

    @demo_func
    def ensure_tls_cert(self):
        """
        Ensures you have a TLS certificate available to use to secure the connection
        to the keyspace. This function downloads a default certificate or lets you
        specify your own.
        """
        print("To connect to your keyspace, you must have a TLS certificate.")
        print("Checking for TLS certificate...")
        cert_path = os.path.join(
            os.path.dirname(__file__), QueryManager.DEFAULT_CERT_FILE
        )
        if not os.path.exists(cert_path):
            cert_choice = q.ask(
                f"Press enter to download a certificate from {QueryManager.CERT_URL} "
                f"or enter the full path to the certificate you want to use: "
            )
            if cert_choice:
                cert_path = cert_choice
            else:
                cert = requests.get(QueryManager.CERT_URL).text
                with open(cert_path, "w") as cert_file:
                    cert_file.write(cert)
        else:
            q.ask(f"Certificate {cert_path} found. Press Enter to continue.")
        print(
            f"Certificate {cert_path} will be used to secure the connection to your keyspace."
        )
        return cert_path

    @demo_func
    def query_table(self, qm, movie_file):
        """
        1. Adds movies to the table from a sample movie data file.
        2. Gets a list of movies from the table and lets you select one.
        3. Displays more information about the selected movie.
        """
        qm.add_movies(self.ks_wrapper.table_name, movie_file)
        movies = qm.get_movies(self.ks_wrapper.table_name)
        print(f"Added {len(movies)} movies to the table:")
        sel = q.choose("Pick one to learn more about it: ", [m.title for m in movies])
        movie_choice = qm.get_movie(
            self.ks_wrapper.table_name, movies[sel].title, movies[sel].year
        )
        print(movie_choice.title)
        print(f"\tReleased: {movie_choice.release_date}")
        print(f"\tPlot: {movie_choice.plot}")

    @demo_func
    def update_and_restore_table(self, qm):
        """
        1. Updates the table by adding a column to track watched movies.
        2. Marks some of the movies as watched.
        3. Gets the list of watched movies from the table.
        4. Restores to a movies_restored table at a previous point in time.
        5. Gets the list of movies from the restored table.
        """
        print("Let's add a column to record which movies you've watched.")
        pre_update_timestamp = datetime.utcnow()
        print(
            f"Recorded the current UTC time of {pre_update_timestamp} so we can restore the table later."
        )
        self.ks_wrapper.update_table()
        print("Waiting for your table to update...")
        table = {"status": "UPDATING"}
        while table["status"] != "ACTIVE":
            wait(5)
            table = self.ks_wrapper.get_table(self.ks_wrapper.table_name)
        print("Column 'watched' added to table.")
        q.ask(
            "Let's mark some of the movies as watched. Press Enter when you're ready.\n"
        )
        movies = qm.get_movies(self.ks_wrapper.table_name)
        for movie in movies[:10]:
            qm.watched_movie(self.ks_wrapper.table_name, movie.title, movie.year)
            print(f"Marked {movie.title} as watched.")
        movies = qm.get_movies(self.ks_wrapper.table_name, watched=True)
        print("-" * 88)
        print("The watched movies in our table are:\n")
        for movie in movies:
            print(movie.title)
        print("-" * 88)
        if q.ask(
            "Do you want to restore the table to the way it was before all of these\n"
            "updates? Keep in mind, this can take up to 20 minutes. (y/n) ",
            q.is_yesno,
        ):
            starting_table_name = self.ks_wrapper.table_name
            table_name_restored = self.ks_wrapper.restore_table(pre_update_timestamp)
            table = {"status": "RESTORING"}
            while table["status"] != "ACTIVE":
                wait(10)
                table = self.ks_wrapper.get_table(table_name_restored)
            print(
                f"Restored {starting_table_name} to {table_name_restored} "
                f"at a point in time of {pre_update_timestamp}."
            )
            movies = qm.get_movies(table_name_restored)
            print("Now the movies in our table are:")
            for movie in movies:
                print(movie.title)

    def cleanup(self, cert_path):
        """
        1. Deletes the table and waits for it to be removed.
        2. Deletes the keyspace.

        :param cert_path: The path of the TLS certificate used in the demo. If the
                          certificate was downloaded during the demo, it is removed.
        """
        if q.ask(
            f"Do you want to delete your {self.ks_wrapper.table_name} table and "
            f"{self.ks_wrapper.ks_name} keyspace? (y/n) ",
            q.is_yesno,
        ):
            table_name = self.ks_wrapper.table_name
            self.ks_wrapper.delete_table()
            table = self.ks_wrapper.get_table(table_name)
            print("Waiting for the table to be deleted.")
            while table is not None:
                wait(5)
                table = self.ks_wrapper.get_table(table_name)
            print("Table deleted.")
            self.ks_wrapper.delete_keyspace()
            print(
                "Keyspace deleted. If you chose to restore your table during the "
                "demo, the original table is also deleted."
            )
            if cert_path == os.path.join(
                os.path.dirname(__file__), QueryManager.DEFAULT_CERT_FILE
            ) and os.path.exists(cert_path):
                os.remove(cert_path)
                print("Removed certificate that was downloaded for this demo.")

    def run_scenario(self):
        logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

        print("-" * 88)
        print("Welcome to the Amazon Keyspaces (for Apache Cassandra) demo.")
        print("-" * 88)

        self.create_keyspace()
        self.create_table()
        cert_file_path = self.ensure_tls_cert()
        # Use a context manager to ensure the connection to the keyspace is closed.
        with QueryManager(
            cert_file_path, boto3.DEFAULT_SESSION, self.ks_wrapper.ks_name
        ) as qm:
            self.query_table(qm, "../../../resources/sample_files/movies.json")
            self.update_and_restore_table(qm)
        self.cleanup(cert_file_path)

        print("\nThanks for watching!")
        print("-" * 88)


if __name__ == "__main__":
    try:
        scenario = KeyspaceScenario(KeyspaceWrapper.from_client())
        scenario.run_scenario()
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
キースペースとテーブルアクションをラップするクラスを定義します。  

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def create_keyspace(self, name):
        """
        Creates a keyspace.

        :param name: The name to give the keyspace.
        :return: The Amazon Resource Name (ARN) of the new keyspace.
        """
        try:
            response = self.keyspaces_client.create_keyspace(keyspaceName=name)
            self.ks_name = name
            self.ks_arn = response["resourceArn"]
        except ClientError as err:
            logger.error(
                "Couldn't create %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return self.ks_arn


    def exists_keyspace(self, name):
        """
        Checks whether a keyspace exists.

        :param name: The name of the keyspace to look up.
        :return: True when the keyspace exists. Otherwise, False.
        """
        try:
            response = self.keyspaces_client.get_keyspace(keyspaceName=name)
            self.ks_name = response["keyspaceName"]
            self.ks_arn = response["resourceArn"]
            exists = True
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.info("Keyspace %s does not exist.", name)
                exists = False
            else:
                logger.error(
                    "Couldn't verify %s exists. Here's why: %s: %s",
                    name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return exists


    def list_keyspaces(self, limit):
        """
        Lists the keyspaces in your account.

        :param limit: The maximum number of keyspaces to list.
        """
        try:
            ks_paginator = self.keyspaces_client.get_paginator("list_keyspaces")
            for page in ks_paginator.paginate(PaginationConfig={"MaxItems": limit}):
                for ks in page["keyspaces"]:
                    print(ks["keyspaceName"])
                    print(f"\t{ks['resourceArn']}")
        except ClientError as err:
            logger.error(
                "Couldn't list keyspaces. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def create_table(self, table_name):
        """
        Creates a table in the  keyspace.
        The table is created with a schema for storing movie data
        and has point-in-time recovery enabled.

        :param table_name: The name to give the table.
        :return: The ARN of the new table.
        """
        try:
            response = self.keyspaces_client.create_table(
                keyspaceName=self.ks_name,
                tableName=table_name,
                schemaDefinition={
                    "allColumns": [
                        {"name": "title", "type": "text"},
                        {"name": "year", "type": "int"},
                        {"name": "release_date", "type": "timestamp"},
                        {"name": "plot", "type": "text"},
                    ],
                    "partitionKeys": [{"name": "year"}, {"name": "title"}],
                },
                pointInTimeRecovery={"status": "ENABLED"},
            )
        except ClientError as err:
            logger.error(
                "Couldn't create table %s. Here's why: %s: %s",
                table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["resourceArn"]


    def get_table(self, table_name):
        """
        Gets data about a table in the keyspace.

        :param table_name: The name of the table to look up.
        :return: Data about the table.
        """
        try:
            response = self.keyspaces_client.get_table(
                keyspaceName=self.ks_name, tableName=table_name
            )
            self.table_name = table_name
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.info("Table %s does not exist.", table_name)
                self.table_name = None
                response = None
            else:
                logger.error(
                    "Couldn't verify %s exists. Here's why: %s: %s",
                    table_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return response


    def list_tables(self):
        """
        Lists the tables in the keyspace.
        """
        try:
            table_paginator = self.keyspaces_client.get_paginator("list_tables")
            for page in table_paginator.paginate(keyspaceName=self.ks_name):
                for table in page["tables"]:
                    print(table["tableName"])
                    print(f"\t{table['resourceArn']}")
        except ClientError as err:
            logger.error(
                "Couldn't list tables in keyspace %s. Here's why: %s: %s",
                self.ks_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def update_table(self):
        """
        Updates the schema of the table.

        This example updates a table of movie data by adding a new column
        that tracks whether the movie has been watched.
        """
        try:
            self.keyspaces_client.update_table(
                keyspaceName=self.ks_name,
                tableName=self.table_name,
                addColumns=[{"name": "watched", "type": "boolean"}],
            )
        except ClientError as err:
            logger.error(
                "Couldn't update table %s. Here's why: %s: %s",
                self.table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def restore_table(self, restore_timestamp):
        """
        Restores the table to a previous point in time. The table is restored
        to a new table in the same keyspace.

        :param restore_timestamp: The point in time to restore the table. This time
                                  must be in UTC format.
        :return: The name of the restored table.
        """
        try:
            restored_table_name = f"{self.table_name}_restored"
            self.keyspaces_client.restore_table(
                sourceKeyspaceName=self.ks_name,
                sourceTableName=self.table_name,
                targetKeyspaceName=self.ks_name,
                targetTableName=restored_table_name,
                restoreTimestamp=restore_timestamp,
            )
        except ClientError as err:
            logger.error(
                "Couldn't restore table %s. Here's why: %s: %s",
                restore_timestamp,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return restored_table_name


    def delete_table(self):
        """
        Deletes the table from the keyspace.
        """
        try:
            self.keyspaces_client.delete_table(
                keyspaceName=self.ks_name, tableName=self.table_name
            )
            self.table_name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete table %s. Here's why: %s: %s",
                self.table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_keyspace(self):
        """
        Deletes the keyspace.
        """
        try:
            self.keyspaces_client.delete_keyspace(keyspaceName=self.ks_name)
            self.ks_name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete keyspace %s. Here's why: %s: %s",
                self.ks_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
キースペースへの TLS 接続を作成し、SigV4 で認証し、キースペース内のテーブルに CQL クエリーを送信するクラスを定義します。  

```
class QueryManager:
    """
    Manages queries to an Amazon Keyspaces (for Apache Cassandra) keyspace.
    Queries are secured by TLS and authenticated by using the Signature V4 (SigV4)
    AWS signing protocol. This is more secure than sending username and password
    with a plain-text authentication provider.

    This example downloads a default certificate to secure TLS, or lets you specify
    your own.

    This example uses a table of movie data to demonstrate basic queries.
    """

    DEFAULT_CERT_FILE = "sf-class2-root.crt"
    CERT_URL = f"https://certs.secureserver.net/repository/sf-class2-root.crt"

    def __init__(self, cert_file_path, boto_session, keyspace_name):
        """
        :param cert_file_path: The path and file name of the certificate used for TLS.
        :param boto_session: A Boto3 session. This is used to acquire your AWS credentials.
        :param keyspace_name: The name of the keyspace to connect.
        """
        self.cert_file_path = cert_file_path
        self.boto_session = boto_session
        self.ks_name = keyspace_name
        self.cluster = None
        self.session = None

    def __enter__(self):
        """
        Creates a session connection to the keyspace that is secured by TLS and
        authenticated by SigV4.
        """
        ssl_context = SSLContext(PROTOCOL_TLSv1_2)
        ssl_context.load_verify_locations(self.cert_file_path)
        ssl_context.verify_mode = CERT_REQUIRED
        auth_provider = SigV4AuthProvider(self.boto_session)
        contact_point = f"cassandra.{self.boto_session.region_name}.amazonaws.com"
        exec_profile = ExecutionProfile(
            consistency_level=ConsistencyLevel.LOCAL_QUORUM,
            load_balancing_policy=DCAwareRoundRobinPolicy(),
        )
        self.cluster = Cluster(
            [contact_point],
            ssl_context=ssl_context,
            auth_provider=auth_provider,
            port=9142,
            execution_profiles={EXEC_PROFILE_DEFAULT: exec_profile},
            protocol_version=4,
        )
        self.cluster.__enter__()
        self.session = self.cluster.connect(self.ks_name)
        return self

    def __exit__(self, *args):
        """
        Exits the cluster. This shuts down all existing session connections.
        """
        self.cluster.__exit__(*args)

    def add_movies(self, table_name, movie_file_path):
        """
        Gets movies from a JSON file and adds them to a table in the keyspace.

        :param table_name: The name of the table.
        :param movie_file_path: The path and file name of a JSON file that contains movie data.
        """
        with open(movie_file_path, "r") as movie_file:
            movies = json.loads(movie_file.read())
        stmt = self.session.prepare(
            f"INSERT INTO {table_name} (year, title, release_date, plot) VALUES (?, ?, ?, ?);"
        )
        for movie in movies[:20]:
            self.session.execute(
                stmt,
                parameters=[
                    movie["year"],
                    movie["title"],
                    date.fromisoformat(movie["info"]["release_date"].partition("T")[0]),
                    movie["info"]["plot"],
                ],
            )

    def get_movies(self, table_name, watched=None):
        """
        Gets the title and year of the full list of movies from the table.

        :param table_name: The name of the movie table.
        :param watched: When specified, the returned list of movies is filtered to
                        either movies that have been watched or movies that have not
                        been watched. Otherwise, all movies are returned.
        :return: A list of movies in the table.
        """
        if watched is None:
            stmt = SimpleStatement(f"SELECT title, year from {table_name}")
            params = None
        else:
            stmt = SimpleStatement(
                f"SELECT title, year from {table_name} WHERE watched = %s ALLOW FILTERING"
            )
            params = [watched]
        return self.session.execute(stmt, parameters=params).all()

    def get_movie(self, table_name, title, year):
        """
        Gets a single movie from the table, by title and year.

        :param table_name: The name of the movie table.
        :param title: The title of the movie.
        :param year: The year of the movie's release.
        :return: The requested movie.
        """
        return self.session.execute(
            SimpleStatement(
                f"SELECT * from {table_name} WHERE title = %s AND year = %s"
            ),
            parameters=[title, year],
        ).one()

    def watched_movie(self, table_name, title, year):
        """
        Updates a movie as having been watched.

        :param table_name: The name of the movie table.
        :param title: The title of the movie.
        :param year: The year of the movie's release.
        """
        self.session.execute(
            SimpleStatement(
                f"UPDATE {table_name} SET watched=true WHERE title = %s AND year = %s"
            ),
            parameters=[title, year],
        )
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateKeyspace](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/CreateKeyspace)
  + [CreateTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/CreateTable)
  + [DeleteKeyspace](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/DeleteKeyspace)
  + [DeleteTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/DeleteTable)
  + [GetKeyspace](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/GetKeyspace)
  + [GetTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/GetTable)
  + [ListKeyspaces](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/ListKeyspaces)
  + [ListTables](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/ListTables)
  + [RestoreTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/RestoreTable)
  + [UpdateTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/UpdateTable)

## アクション
<a name="actions"></a>

### `CreateKeyspace`
<a name="keyspaces_CreateKeyspace_python_3_topic"></a>

次のコード例は、`CreateKeyspace` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def create_keyspace(self, name):
        """
        Creates a keyspace.

        :param name: The name to give the keyspace.
        :return: The Amazon Resource Name (ARN) of the new keyspace.
        """
        try:
            response = self.keyspaces_client.create_keyspace(keyspaceName=name)
            self.ks_name = name
            self.ks_arn = response["resourceArn"]
        except ClientError as err:
            logger.error(
                "Couldn't create %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return self.ks_arn
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateKeyspace](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/CreateKeyspace)」を参照してください。

### `CreateTable`
<a name="keyspaces_CreateTable_python_3_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def create_table(self, table_name):
        """
        Creates a table in the  keyspace.
        The table is created with a schema for storing movie data
        and has point-in-time recovery enabled.

        :param table_name: The name to give the table.
        :return: The ARN of the new table.
        """
        try:
            response = self.keyspaces_client.create_table(
                keyspaceName=self.ks_name,
                tableName=table_name,
                schemaDefinition={
                    "allColumns": [
                        {"name": "title", "type": "text"},
                        {"name": "year", "type": "int"},
                        {"name": "release_date", "type": "timestamp"},
                        {"name": "plot", "type": "text"},
                    ],
                    "partitionKeys": [{"name": "year"}, {"name": "title"}],
                },
                pointInTimeRecovery={"status": "ENABLED"},
            )
        except ClientError as err:
            logger.error(
                "Couldn't create table %s. Here's why: %s: %s",
                table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["resourceArn"]
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[CreateTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/CreateTable)」を参照してください。

### `DeleteKeyspace`
<a name="keyspaces_DeleteKeyspace_python_3_topic"></a>

次のコード例は、`DeleteKeyspace` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def delete_keyspace(self):
        """
        Deletes the keyspace.
        """
        try:
            self.keyspaces_client.delete_keyspace(keyspaceName=self.ks_name)
            self.ks_name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete keyspace %s. Here's why: %s: %s",
                self.ks_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[DeleteKeyspace](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/DeleteKeyspace)」を参照してください。

### `DeleteTable`
<a name="keyspaces_DeleteTable_python_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def delete_table(self):
        """
        Deletes the table from the keyspace.
        """
        try:
            self.keyspaces_client.delete_table(
                keyspaceName=self.ks_name, tableName=self.table_name
            )
            self.table_name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete table %s. Here's why: %s: %s",
                self.table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[DeleteTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/DeleteTable)」を参照してください。

### `GetKeyspace`
<a name="keyspaces_GetKeyspace_python_3_topic"></a>

次のコード例は、`GetKeyspace` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def exists_keyspace(self, name):
        """
        Checks whether a keyspace exists.

        :param name: The name of the keyspace to look up.
        :return: True when the keyspace exists. Otherwise, False.
        """
        try:
            response = self.keyspaces_client.get_keyspace(keyspaceName=name)
            self.ks_name = response["keyspaceName"]
            self.ks_arn = response["resourceArn"]
            exists = True
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.info("Keyspace %s does not exist.", name)
                exists = False
            else:
                logger.error(
                    "Couldn't verify %s exists. Here's why: %s: %s",
                    name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return exists
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[GetKeyspace](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/GetKeyspace)」を参照してください。

### `GetTable`
<a name="keyspaces_GetTable_python_3_topic"></a>

次のコード例は、`GetTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def get_table(self, table_name):
        """
        Gets data about a table in the keyspace.

        :param table_name: The name of the table to look up.
        :return: Data about the table.
        """
        try:
            response = self.keyspaces_client.get_table(
                keyspaceName=self.ks_name, tableName=table_name
            )
            self.table_name = table_name
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.info("Table %s does not exist.", table_name)
                self.table_name = None
                response = None
            else:
                logger.error(
                    "Couldn't verify %s exists. Here's why: %s: %s",
                    table_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return response
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[GetTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/GetTable)」を参照してください。

### `ListKeyspaces`
<a name="keyspaces_ListKeyspaces_python_3_topic"></a>

次のコード例は、`ListKeyspaces` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def list_keyspaces(self, limit):
        """
        Lists the keyspaces in your account.

        :param limit: The maximum number of keyspaces to list.
        """
        try:
            ks_paginator = self.keyspaces_client.get_paginator("list_keyspaces")
            for page in ks_paginator.paginate(PaginationConfig={"MaxItems": limit}):
                for ks in page["keyspaces"]:
                    print(ks["keyspaceName"])
                    print(f"\t{ks['resourceArn']}")
        except ClientError as err:
            logger.error(
                "Couldn't list keyspaces. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[ListKeyspaces](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/ListKeyspaces)」を参照してください。

### `ListTables`
<a name="keyspaces_ListTables_python_3_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def list_tables(self):
        """
        Lists the tables in the keyspace.
        """
        try:
            table_paginator = self.keyspaces_client.get_paginator("list_tables")
            for page in table_paginator.paginate(keyspaceName=self.ks_name):
                for table in page["tables"]:
                    print(table["tableName"])
                    print(f"\t{table['resourceArn']}")
        except ClientError as err:
            logger.error(
                "Couldn't list tables in keyspace %s. Here's why: %s: %s",
                self.ks_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListTables](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/ListTables)」を参照してください。

### `RestoreTable`
<a name="keyspaces_RestoreTable_python_3_topic"></a>

次のコード例は、`RestoreTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def restore_table(self, restore_timestamp):
        """
        Restores the table to a previous point in time. The table is restored
        to a new table in the same keyspace.

        :param restore_timestamp: The point in time to restore the table. This time
                                  must be in UTC format.
        :return: The name of the restored table.
        """
        try:
            restored_table_name = f"{self.table_name}_restored"
            self.keyspaces_client.restore_table(
                sourceKeyspaceName=self.ks_name,
                sourceTableName=self.table_name,
                targetKeyspaceName=self.ks_name,
                targetTableName=restored_table_name,
                restoreTimestamp=restore_timestamp,
            )
        except ClientError as err:
            logger.error(
                "Couldn't restore table %s. Here's why: %s: %s",
                restore_timestamp,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return restored_table_name
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[RestoreTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/RestoreTable)」を参照してください。

### `UpdateTable`
<a name="keyspaces_UpdateTable_python_3_topic"></a>

次のコード例は、`UpdateTable` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/keyspaces#code-examples)での設定と実行の方法を確認してください。

```
class KeyspaceWrapper:
    """Encapsulates Amazon Keyspaces (for Apache Cassandra) keyspace and table actions."""

    def __init__(self, keyspaces_client):
        """
        :param keyspaces_client: A Boto3 Amazon Keyspaces client.
        """
        self.keyspaces_client = keyspaces_client
        self.ks_name = None
        self.ks_arn = None
        self.table_name = None

    @classmethod
    def from_client(cls):
        keyspaces_client = boto3.client("keyspaces")
        return cls(keyspaces_client)


    def update_table(self):
        """
        Updates the schema of the table.

        This example updates a table of movie data by adding a new column
        that tracks whether the movie has been watched.
        """
        try:
            self.keyspaces_client.update_table(
                keyspaceName=self.ks_name,
                tableName=self.table_name,
                addColumns=[{"name": "watched", "type": "boolean"}],
            )
        except ClientError as err:
            logger.error(
                "Couldn't update table %s. Here's why: %s: %s",
                self.table_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の「[UpdateTable](https://docs.aws.amazon.com/goto/boto3/keyspaces-2022-02-10/UpdateTable)」を参照してください。

# SDK for Python (Boto3) を使用した Kinesis の例
<a name="python_3_kinesis_code_examples"></a>

次のコード例は、Kinesis AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateStream`
<a name="kinesis_CreateStream_python_3_topic"></a>

次のコード例は、`CreateStream` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
class KinesisStream:
    """Encapsulates a Kinesis stream."""

    def __init__(self, kinesis_client):
        """
        :param kinesis_client: A Boto3 Kinesis client.
        """
        self.kinesis_client = kinesis_client
        self.name = None
        self.details = None
        self.stream_exists_waiter = kinesis_client.get_waiter("stream_exists")


    def create(self, name, wait_until_exists=True):
        """
        Creates a stream.

        :param name: The name of the stream.
        :param wait_until_exists: When True, waits until the service reports that
                                  the stream exists, then queries for its metadata.
        """
        try:
            self.kinesis_client.create_stream(StreamName=name, ShardCount=1)
            self.name = name
            logger.info("Created stream %s.", name)
            if wait_until_exists:
                logger.info("Waiting until exists.")
                self.stream_exists_waiter.wait(StreamName=name)
                self.describe(name)
        except ClientError:
            logger.exception("Couldn't create stream %s.", name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateStream](https://docs.aws.amazon.com/goto/boto3/kinesis-2013-12-02/CreateStream)」を参照してください。

### `DeleteStream`
<a name="kinesis_DeleteStream_python_3_topic"></a>

次のコード例は、`DeleteStream` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
class KinesisStream:
    """Encapsulates a Kinesis stream."""

    def __init__(self, kinesis_client):
        """
        :param kinesis_client: A Boto3 Kinesis client.
        """
        self.kinesis_client = kinesis_client
        self.name = None
        self.details = None
        self.stream_exists_waiter = kinesis_client.get_waiter("stream_exists")


    def delete(self):
        """
        Deletes a stream.
        """
        try:
            self.kinesis_client.delete_stream(StreamName=self.name)
            self._clear()
            logger.info("Deleted stream %s.", self.name)
        except ClientError:
            logger.exception("Couldn't delete stream %s.", self.name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteStream](https://docs.aws.amazon.com/goto/boto3/kinesis-2013-12-02/DeleteStream)」を参照してください。

### `DescribeStream`
<a name="kinesis_DescribeStream_python_3_topic"></a>

次のコード例は、`DescribeStream` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
class KinesisStream:
    """Encapsulates a Kinesis stream."""

    def __init__(self, kinesis_client):
        """
        :param kinesis_client: A Boto3 Kinesis client.
        """
        self.kinesis_client = kinesis_client
        self.name = None
        self.details = None
        self.stream_exists_waiter = kinesis_client.get_waiter("stream_exists")


    def describe(self, name):
        """
        Gets metadata about a stream.

        :param name: The name of the stream.
        :return: Metadata about the stream.
        """
        try:
            response = self.kinesis_client.describe_stream(StreamName=name)
            self.name = name
            self.details = response["StreamDescription"]
            logger.info("Got stream %s.", name)
        except ClientError:
            logger.exception("Couldn't get %s.", name)
            raise
        else:
            return self.details
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeStream](https://docs.aws.amazon.com/goto/boto3/kinesis-2013-12-02/DescribeStream)」を参照してください。

### `GetRecords`
<a name="kinesis_GetRecords_python_3_topic"></a>

次のコード例は、`GetRecords` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
class KinesisStream:
    """Encapsulates a Kinesis stream."""

    def __init__(self, kinesis_client):
        """
        :param kinesis_client: A Boto3 Kinesis client.
        """
        self.kinesis_client = kinesis_client
        self.name = None
        self.details = None
        self.stream_exists_waiter = kinesis_client.get_waiter("stream_exists")


    def get_records(self, max_records):
        """
        Gets records from the stream. This function is a generator that first gets
        a shard iterator for the stream, then uses the shard iterator to get records
        in batches from the stream. The shard iterator can be accessed through the
        'details' property, which is populated using the 'describe' function of this class.
        Each batch of records is yielded back to the caller until the specified
        maximum number of records has been retrieved.

        :param max_records: The maximum number of records to retrieve.
        :return: Yields the current batch of retrieved records.
        """
        try:
            response = self.kinesis_client.get_shard_iterator(
                StreamName=self.name,
                ShardId=self.details["Shards"][0]["ShardId"],
                ShardIteratorType="LATEST",
            )
            shard_iter = response["ShardIterator"]
            record_count = 0
            while record_count < max_records:
                response = self.kinesis_client.get_records(
                    ShardIterator=shard_iter, Limit=10
                )
                shard_iter = response["NextShardIterator"]
                records = response["Records"]
                logger.info("Got %s records.", len(records))
                record_count += len(records)
                yield records
        except ClientError:
            logger.exception("Couldn't get records from stream %s.", self.name)
            raise



    def describe(self, name):
        """
        Gets metadata about a stream.

        :param name: The name of the stream.
        :return: Metadata about the stream.
        """
        try:
            response = self.kinesis_client.describe_stream(StreamName=name)
            self.name = name
            self.details = response["StreamDescription"]
            logger.info("Got stream %s.", name)
        except ClientError:
            logger.exception("Couldn't get %s.", name)
            raise
        else:
            return self.details
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetRecords](https://docs.aws.amazon.com/goto/boto3/kinesis-2013-12-02/GetRecords)」を参照してください。**

### `PutRecord`
<a name="kinesis_PutRecord_python_3_topic"></a>

次のコード例は、`PutRecord` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
class KinesisStream:
    """Encapsulates a Kinesis stream."""

    def __init__(self, kinesis_client):
        """
        :param kinesis_client: A Boto3 Kinesis client.
        """
        self.kinesis_client = kinesis_client
        self.name = None
        self.details = None
        self.stream_exists_waiter = kinesis_client.get_waiter("stream_exists")


    def put_record(self, data, partition_key):
        """
        Puts data into the stream. The data is formatted as JSON before it is passed
        to the stream.

        :param data: The data to put in the stream.
        :param partition_key: The partition key to use for the data.
        :return: Metadata about the record, including its shard ID and sequence number.
        """
        try:
            response = self.kinesis_client.put_record(
                StreamName=self.name, Data=json.dumps(data), PartitionKey=partition_key
            )
            logger.info("Put record in stream %s.", self.name)
        except ClientError:
            logger.exception("Couldn't put record in stream %s.", self.name)
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutRecord](https://docs.aws.amazon.com/goto/boto3/kinesis-2013-12-02/PutRecord)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_python_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での Kinesis イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import base64
def lambda_handler(event, context):

    for record in event['Records']:
        try:
            print(f"Processed Kinesis Event - EventID: {record['eventID']}")
            record_data = base64.b64decode(record['kinesis']['data']).decode('utf-8')
            print(f"Record Data: {record_data}")
            # TODO: Do interesting work based on the new data
        except Exception as e:
            print(f"An error occurred {e}")
            raise e
    print(f"Successfully processed {len(event['Records'])} records.")
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_python_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def handler(event, context):
    records = event.get("Records")
    curRecordSequenceNumber = ""
    
    for record in records:
        try:
            # Process your record
            curRecordSequenceNumber = record["kinesis"]["sequenceNumber"]
        except Exception as e:
            # Return failed record's sequence number
            return {"batchItemFailures":[{"itemIdentifier": curRecordSequenceNumber}]}

    return {"batchItemFailures":[]}
```

# AWS KMS SDK for Python (Boto3) を使用した例
<a name="python_3_kms_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="kms_Scenario_Basics_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ KMS キーを作成します。
+ アカウントの KMS キーを一覧表示し、詳細を取得します。
+ KMS キーを有効および無効にします。
+ クライアント側の暗号化に使用できる対称データキーを生成します。
+ データのデジタル署名に使用する非対称キーを生成します。
+ キーをダグ付けします。
+ KMS キーを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KMSScenario:
    """Runs an interactive scenario that shows how to get started with KMS."""

    def __init__(
        self,
        key_manager: KeyManager,
        key_encryption: KeyEncrypt,
        alias_manager: AliasManager,
        grant_manager: GrantManager,
        key_policy: KeyPolicy,
    ):
        self.key_manager = key_manager
        self.key_encryption = key_encryption
        self.alias_manager = alias_manager
        self.grant_manager = grant_manager
        self.key_policy = key_policy
        self.key_id = ""
        self.alias_name = ""
        self.asymmetric_key_id = ""

    def kms_scenario(self):
        key_description = "Created by the AWS KMS API"

        print(DASHES)
        print(
            """
Welcome to the AWS Key Management SDK Basics scenario.

This program demonstrates how to interact with AWS Key Management using the AWS SDK for Python (Boto3).
The AWS Key Management Service (KMS) is a secure and highly available service that allows you to create
and manage AWS KMS keys and control their use across a wide range of AWS services and applications.
KMS provides a centralized and unified approach to managing encryption keys, making it easier to meet your
data protection and regulatory compliance requirements.

This Basics scenario creates two key types:

- A symmetric encryption key is used to encrypt and decrypt data.
- An asymmetric key used to digitally sign data.

Let's get started...
        """
        )
        q.ask("Press Enter to continue...")

        print(DASHES)
        print(f"1. Create a symmetric KMS key\n")
        print(
            f"First, the program will creates a symmetric KMS key that you can used to encrypt and decrypt data."
        )
        q.ask("Press Enter to continue...")
        self.key_id = self.key_manager.create_key(key_description)["KeyId"]
        print(f"A symmetric key was successfully created {self.key_id}.")
        q.ask("Press Enter to continue...")
        print(DASHES)
        print(
            """
2. Enable a KMS key

By default, when the SDK creates an AWS key, it is enabled. The next bit of code checks to
determine if the key is enabled.
        """
        )
        q.ask("Press Enter to continue...")
        is_enabled = self.is_key_enabled(self.key_id)
        print(f"Is the key enabled? {is_enabled}")
        if not is_enabled:
            self.key_manager.enable_key(self.key_id)
        q.ask("Press Enter to continue...")
        print(DASHES)
        print(f"3. Encrypt data using the symmetric KMS key")
        plain_text = "Hello, AWS KMS!"
        print(
            f"""
One of the main uses of symmetric keys is to encrypt and decrypt data.
Next, the code encrypts the string "{plain_text}" with the SYMMETRIC_DEFAULT encryption algorithm.
        """
        )
        q.ask("Press Enter to continue...")
        encrypted_text = self.key_encryption.encrypt(self.key_id, plain_text)
        print(DASHES)
        print(f"4. Create an alias")
        print(
            """
Now, the program will create an alias for the KMS key. An alias is a friendly name that you
can associate with a KMS key. The alias name should be prefixed with 'alias/'.
        """
        )
        alias_name = q.ask("Enter an alias name: ", q.non_empty)
        self.alias_manager.create_alias(self.key_id, alias_name)
        print(f"{alias_name} was successfully created.")
        self.alias_name = alias_name
        print(DASHES)
        print(f"5. List all of your aliases")
        q.ask("Press Enter to continue...")
        self.alias_manager.list_aliases(10)
        q.ask("Press Enter to continue...")
        print(DASHES)
        print(f"6. Enable automatic rotation of the KMS key")
        print(
            """

By default, when the SDK enables automatic rotation of a KMS key,
KMS rotates the key material of the KMS key one year (approximately 365 days) from the enable date and every year
thereafter.
        """
        )
        q.ask("Press Enter to continue...")
        self.key_manager.enable_key_rotation(self.key_id)
        print(DASHES)
        print(f"Key rotation has been enabled for key with id {self.key_id}")
        print(
            """
7. Create a grant

A grant is a policy instrument that allows Amazon Web Services principals to use KMS keys.
It also can allow them to view a KMS key (DescribeKey) and create and manage grants.
When authorizing access to a KMS key, grants are considered along with key policies and IAM policies.
        """
        )
        print(
            """
To create a grant you must specify a account_id. To specify the grantee account_id, use the Amazon Resource Name (ARN)
of an AWS account_id. Valid principals include AWS accounts, IAM users, IAM roles, federated users,
and assumed role users.
        """
        )
        account_id = q.ask(
            "Enter an account_id, or press enter to skip creating a grant... "
        )
        grant = None
        if account_id != "":
            grant = self.grant_manager.create_grant(
                self.key_id,
                account_id,
                [
                    "Encrypt",
                    "Decrypt",
                    "DescribeKey",
                ],
            )
            print(f"Grant created successfully with ID: {grant['GrantId']}")

        q.ask("Press Enter to continue...")
        print(DASHES)
        print(DASHES)
        print(f"8. List grants for the KMS key")
        q.ask("Press Enter to continue...")
        self.grant_manager.list_grants(self.key_id)
        q.ask("Press Enter to continue...")
        print(DASHES)
        print(f"9. Revoke the grant")
        print(
            """
The revocation of a grant immediately removes the permissions and access that the grant had provided.
This means that any account_id (user, role, or service) that was granted access to perform specific
KMS operations on a KMS key will no longer be able to perform those operations.
        """
        )
        q.ask("Press Enter to continue...")

        if grant is not None:
            self.grant_manager.revoke_grant(self.key_id, grant["GrantId"])
            print(f"Grant ID: {grant['GrantId']} was successfully revoked!")

        q.ask("Press Enter to continue...")
        print(DASHES)
        print(f"10. Decrypt the data\n")
        print(
            """
Lets decrypt the data that was encrypted in an early step.
The code uses the same key to decrypt the string that we encrypted earlier in the program.
        """
        )
        q.ask("Press Enter to continue...")
        decrypted_data = self.key_encryption.decrypt(self.key_id, encrypted_text)
        print(f"Data decrypted successfully for key ID: {self.key_id}")
        print(f"Decrypted data: {decrypted_data}")

        q.ask("Press Enter to continue...")
        print(DASHES)
        print(f"11. Replace a key policy\n")
        print(
            """
A key policy is a resource policy for a KMS key. Key policies are the primary way to control
access to KMS keys. Every KMS key must have exactly one key policy. The statements in the key policy
determine who has permission to use the KMS key and how they can use it.
You can also use IAM policies and grants to control access to the KMS key, but every KMS key
must have a key policy.

By default, when you create a key by using the SDK, a policy is created that
gives the AWS account that owns the KMS key full access to the KMS key.

Let's try to replace the automatically created policy with the following policy.
{
"Version":"2012-10-17",		 	 	 
"Statement": [{
"Effect": "Allow",
"Principal": {"AWS": "arn:aws:iam::0000000000:root"},
"Action": "kms:*",
"Resource": "*"
}]
}
        """
        )
        account_id = q.ask("Enter your account ID or press enter to skip: ")
        if account_id != "":
            policy = {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {"AWS": f"arn:aws:iam::{account_id}:root"},
                        "Action": "kms:*",
                        "Resource": "*",
                    }
                ],
            }

            self.key_policy.set_new_policy(self.key_id, policy)
            print("Key policy replacement succeeded.")
            q.ask("Press Enter to continue...")
        else:
            print("Skipping replacing the key policy.")

        print(DASHES)
        print(f"12. Get the key policy\n")
        print(
            f"The next bit of code that runs gets the key policy to make sure it exists."
        )
        q.ask("Press Enter to continue...")
        policy = self.key_policy.get_policy(self.key_id)
        print(f"The key policy is: {policy}")

        q.ask("Press Enter to continue...")
        print(DASHES)
        print(f"13. Create an asymmetric KMS key and sign your data\n")
        print(
            """
        Signing your data with an AWS key can provide several benefits that make it an attractive option
        for your data signing needs. By using an AWS KMS key, you can leverage the
        security controls and compliance features provided by AWS,
        which can help you meet various regulatory requirements and enhance the overall security posture
        of your organization.
        """
        )
        q.ask("Press Enter to continue...")
        print(f"Sign and verify data operation succeeded.")
        self.asymmetric_key_id = self.key_manager.create_asymmetric_key()
        message = "Here is the message that will be digitally signed"
        signature = self.key_encryption.sign(self.asymmetric_key_id, message)
        if self.key_encryption.verify(self.asymmetric_key_id, message, signature):
            print("Signature verification succeeded.")
        else:
            print("Signature verification failed.")

        q.ask("Press Enter to continue...")
        print(DASHES)
        print(f"14. Tag your symmetric KMS Key\n")
        print(
            """
        By using tags, you can improve the overall management, security, and governance of your
        KMS keys, making it easier to organize, track, and control access to your encrypted data within
        your AWS environment
        """
        )
        q.ask("Press Enter to continue...")
        self.key_manager.tag_resource(self.key_id, "Environment", "Production")
        self.clean_up()

    def is_key_enabled(self, key_id: str) -> bool:
        """
        Check if the key is enabled or not.

        :param key_id: The key to check.
        :return: True if the key is enabled, otherwise False.
        """
        response = self.key_manager.describe_key(key_id)
        return response["Enabled"] is True

    def clean_up(self):
        """
        Delete resources created by this scenario.
        """
        if self.alias_name != "":
            print(f"Deleting the alias {self.alias_name}.")
            self.alias_manager.delete_alias(self.alias_name)
        window = 7  # The window in days for a scheduled deletion.
        if self.key_id != "":
            print(
                """
Warning:
Deleting a KMS key is a destructive and potentially dangerous operation. When a KMS key is deleted,
all data that was encrypted under the KMS key is unrecoverable.
                """
            )
            if q.ask(
                f"Do you want to delete the key with ID {self.key_id} (y/n)?",
                q.is_yesno,
            ):
                print(
                    f"The key {self.key_id} will be deleted with a window of {window} days. You can cancel the deletion before"
                )
                print("the window expires.")
                self.key_manager.delete_key(self.key_id, window)
                self.key_id = ""

        if self.asymmetric_key_id != "":
            if q.ask(
                f"Do you want to delete the asymmetric key with ID {self.asymmetric_key_id} (y/n)?",
                q.is_yesno,
            ):
                print(
                    f"The key {self.asymmetric_key_id} will be deleted with a window of {window} days. You can cancel the deletion before"
                )
                print("the window expires.")
                self.key_manager.delete_key(self.asymmetric_key_id, window)
                self.asymmetric_key_id = ""


if __name__ == "__main__":
    kms_scenario = None
    try:
        kms_client = boto3.client("kms")
        a_key_manager = KeyManager(kms_client)
        a_key_encrypt = KeyEncrypt(kms_client)
        an_alias_manager = AliasManager(kms_client)
        a_grant_manager = GrantManager(kms_client)
        a_key_policy = KeyPolicy(kms_client)
        kms_scenario = KMSScenario(
            key_manager=a_key_manager,
            key_encryption=a_key_encrypt,
            alias_manager=an_alias_manager,
            grant_manager=a_grant_manager,
            key_policy=a_key_policy,
        )
        kms_scenario.kms_scenario()
    except Exception:
        logging.exception("Something went wrong with the demo!")
        if kms_scenario is not None:
            kms_scenario.clean_up()
```
KMS キー管理のラッパークラスとメソッド。  

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def create_key(self, key_description: str) -> dict[str, any]:
        """
        Creates a key with a user-provided description.

        :param key_description: A description for the key.
        :return: The key ID.
        """
        try:
            key = self.kms_client.create_key(Description=key_description)["KeyMetadata"]
            self.created_keys.append(key)
            return key
        except ClientError as err:
            logging.error(
                "Couldn't create your key. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise


    def describe_key(self, key_id: str) -> dict[str, any]:
        """
        Describes a key.

        :param key_id: The ARN or ID of the key to describe.
        :return: Information about the key.
        """

        try:
            key = self.kms_client.describe_key(KeyId=key_id)["KeyMetadata"]
            return key
        except ClientError as err:
            logging.error(
                "Couldn't get key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise


    def enable_key_rotation(self, key_id: str) -> None:
        """
        Enables rotation for a key.

        :param key_id: The ARN or ID of the key to enable rotation for.
        """
        try:
            self.kms_client.enable_key_rotation(KeyId=key_id)
        except ClientError as err:
            logging.error(
                "Couldn't enable rotation for key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise


    def create_asymmetric_key(self) -> str:
        """
        Creates an asymmetric key in AWS KMS for signing messages.

        :return: The ID of the created key.
        """
        try:
            key = self.kms_client.create_key(
                KeySpec="RSA_2048", KeyUsage="SIGN_VERIFY", Origin="AWS_KMS"
            )["KeyMetadata"]
            self.created_keys.append(key)
            return key["KeyId"]
        except ClientError as err:
            logger.error(
                "Couldn't create your key. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise


    def tag_resource(self, key_id: str, tag_key: str, tag_value: str) -> None:
        """
        Add or edit tags on a customer managed key.

        :param key_id: The ARN or ID of the key to enable rotation for.
        :param tag_key: Key for the tag.
        :param tag_value: Value for the tag.
        """
        try:
            self.kms_client.tag_resource(
                KeyId=key_id, Tags=[{"TagKey": tag_key, "TagValue": tag_value}]
            )
        except ClientError as err:
            logging.error(
                "Couldn't add a tag for the key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise


    def delete_key(self, key_id: str, window: int) -> None:
        """
        Deletes a list of keys.

        Warning:
        Deleting a KMS key is a destructive and potentially dangerous operation. When a KMS key is deleted,
        all data that was encrypted under the KMS key is unrecoverable.

        :param key_id: The ARN or ID of the key to delete.
        :param window: The waiting period, in days, before the KMS key is deleted.
        """

        try:
            self.kms_client.schedule_key_deletion(
                KeyId=key_id, PendingWindowInDays=window
            )
        except ClientError as err:
            logging.error(
                "Couldn't delete key %s. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
KMS キーエイリアスのラッパークラスとメソッド。  

```
class AliasManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_key = None

    @classmethod
    def from_client(cls) -> "AliasManager":
        """
        Creates an AliasManager instance with a default KMS client.

        :return: An instance of AliasManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def create_alias(self, key_id: str, alias: str) -> None:
        """
        Creates an alias for the specified key.

        :param key_id: The ARN or ID of a key to give an alias.
        :param alias: The alias to assign to the key.
        """
        try:
            self.kms_client.create_alias(AliasName=alias, TargetKeyId=key_id)
        except ClientError as err:
            if err.response["Error"]["Code"] == "AlreadyExistsException":
                logger.error(
                    "Could not create the alias %s because it already exists.", key_id
                )
            else:
                logger.error(
                    "Couldn't encrypt text. Here's why: %s",
                    err.response["Error"]["Message"],
                )
                raise


    def list_aliases(self, page_size: int) -> None:
        """
        Lists aliases for the current account.
        :param page_size: The number of aliases to list per page.
        """
        try:
            alias_paginator = self.kms_client.get_paginator("list_aliases")
            for alias_page in alias_paginator.paginate(
                PaginationConfig={"PageSize": page_size}
            ):
                print(f"Here are {page_size} aliases:")
                pprint(alias_page["Aliases"])
                if alias_page["Truncated"]:
                    answer = input(
                        f"Do you want to see the next {page_size} aliases (y/n)? "
                    )
                    if answer.lower() != "y":
                        break
                else:
                    print("That's all your aliases!")
        except ClientError as err:
            logging.error(
                "Couldn't list your aliases. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise


    def delete_alias(self, alias: str) -> None:
        """
        Deletes an alias.

        :param alias: The alias to delete.
        """
        try:
            self.kms_client.delete_alias(AliasName=alias)
        except ClientError as err:
            logger.error(
                "Couldn't delete alias %s. Here's why: %s",
                alias,
                err.response["Error"]["Message"],
            )
            raise
```
KMS キー暗号化のラッパークラスとメソッド。  

```
class KeyEncrypt:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyEncrypt":
        """
        Creates a KeyEncrypt instance with a default KMS client.

        :return: An instance of KeyEncrypt initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def encrypt(self, key_id: str, text: str) -> bytes:
        """
        Encrypts text by using the specified key.

        :param key_id: The ARN or ID of the key to use for encryption.
        :param text: The text to encrypt.
        :return: The encrypted version of the text.
        """
        try:
            response = self.kms_client.encrypt(KeyId=key_id, Plaintext=text.encode())
            print(
                f"The string was encrypted with algorithm {response['EncryptionAlgorithm']}"
            )
            return response["CiphertextBlob"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DisabledException":
                logger.error(
                    "Could not encrypt because the key %s is disabled.", key_id
                )
            else:
                logger.error(
                    "Couldn't encrypt text. Here's why: %s",
                    err.response["Error"]["Message"],
                )
            raise


    def decrypt(self, key_id: str, cipher_text: bytes) -> str:
        """
        Decrypts text previously encrypted with a key.

        :param key_id: The ARN or ID of the key used to decrypt the data.
        :param cipher_text: The encrypted text to decrypt.
        :return: The decrypted text.
        """
        try:
            return self.kms_client.decrypt(KeyId=key_id, CiphertextBlob=cipher_text)[
                "Plaintext"
            ].decode()
        except ClientError as err:
            logger.error(
                "Couldn't decrypt your ciphertext. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise


    def sign(self, key_id: str, message: str) -> str:
        """
        Signs a message with a key.

        :param key_id: The ARN or ID of the key to use for signing.
        :param message: The message to sign.
        :return: The signature of the message.
        """
        try:
            return self.kms_client.sign(
                KeyId=key_id,
                Message=message.encode(),
                SigningAlgorithm="RSASSA_PSS_SHA_256",
            )["Signature"]
        except ClientError as err:
            logger.error(
                "Couldn't sign your message. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise


    def verify(self, key_id: str, message: str, signature: str) -> bool:
        """
        Verifies a signature against a message.

        :param key_id: The ARN or ID of the key used to sign the message.
        :param message: The message to verify.
        :param signature: The signature to verify.
        :return: True when the signature matches the message, otherwise False.
        """
        try:
            response = self.kms_client.verify(
                KeyId=key_id,
                Message=message.encode(),
                Signature=signature,
                SigningAlgorithm="RSASSA_PSS_SHA_256",
            )
            valid = response["SignatureValid"]
            print(f"The signature is {'valid' if valid else 'invalid'}.")
            return valid
        except ClientError as err:
            if err.response["Error"]["Code"] == "SignatureDoesNotMatchException":
                print("The signature is not valid.")
            else:
                logger.error(
                    "Couldn't verify your signature. Here's why: %s",
                    err.response["Error"]["Message"],
                )
            raise
```
KMS キー許可のラッパークラスとメソッド。  

```
class GrantManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "GrantManager":
        """
        Creates a GrantManager instance with a default KMS client.

        :return: An instance of GrantManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def create_grant(
        self, key_id: str, principal: str, operations: [str]
    ) -> dict[str, str]:
        """
        Creates a grant for a key that lets a principal generate a symmetric data
        encryption key.

        :param key_id: The ARN or ID of the key.
        :param principal: The principal to grant permission to.
        :param operations: The operations to grant permission for.
        :return: The grant that is created.
        """
        try:
            return self.kms_client.create_grant(
                KeyId=key_id,
                GranteePrincipal=principal,
                Operations=operations,
            )
        except ClientError as err:
            logger.error(
                "Couldn't create a grant on key %s. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise


    def list_grants(self, key_id):
        """
        Lists grants for a key.

        :param key_id: The ARN or ID of the key to query.
        :return: The grants for the key.
        """
        try:
            paginator = self.kms_client.get_paginator("list_grants")
            grants = []
            page_iterator = paginator.paginate(KeyId=key_id)
            for page in page_iterator:
                grants.extend(page["Grants"])

            print(f"Grants for key {key_id}:")
            pprint(grants)
            return grants
        except ClientError as err:
            logger.error(
                "Couldn't list grants for key %s. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise


    def revoke_grant(self, key_id: str, grant_id: str) -> None:
        """
        Revokes a grant so that it can no longer be used.

        :param key_id: The ARN or ID of the key associated with the grant.
        :param grant_id: The ID of the grant to revoke.
        """
        try:
            self.kms_client.revoke_grant(KeyId=key_id, GrantId=grant_id)
        except ClientError as err:
            logger.error(
                "Couldn't revoke grant %s. Here's why: %s",
                grant_id,
                err.response["Error"]["Message"],
            )
            raise
```
KMS キーポリシーのラッパークラスとメソッド。  

```
class KeyPolicy:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyPolicy":
        """
        Creates a KeyPolicy instance with a default KMS client.

        :return: An instance of KeyPolicy initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def set_new_policy(self, key_id: str, policy: dict[str, any]) -> None:
        """
        Sets the policy of a key. Setting a policy entirely overwrites the existing
        policy, so care is taken to add a statement to the existing list of statements
        rather than simply writing a new policy.

        :param key_id: The ARN or ID of the key to set the policy to.
        :param policy: A new key policy. The key policy must allow the calling principal to make a subsequent
                       PutKeyPolicy request on the KMS key. This reduces the risk that the KMS key becomes unmanageable
        """

        try:
            self.kms_client.put_key_policy(KeyId=key_id, Policy=json.dumps(policy))
        except ClientError as err:
            logger.error(
                "Couldn't set policy for key %s. Here's why %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise



    def get_policy(self, key_id: str) -> dict[str, str]:
        """
        Gets the policy of a key.

        :param key_id: The ARN or ID of the key to query.
        :return: The key policy as a dict.
        """
        if key_id != "":
            try:
                response = self.kms_client.get_key_policy(
                    KeyId=key_id,
                )
                policy = json.loads(response["Policy"])
            except ClientError as err:
                logger.error(
                    "Couldn't get policy for key %s. Here's why: %s",
                    key_id,
                    err.response["Error"]["Message"],
                )
                raise
            else:
                pprint(policy)
                return policy
        else:
            print("Skipping get policy demo.")
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateAlias](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/CreateAlias)
  + [CreateGrant](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/CreateGrant)
  + [CreateKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/CreateKey)
  + [Decrypt](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Decrypt)
  + [DescribeKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/DescribeKey)
  + [DisableKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/DisableKey)
  + [EnableKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/EnableKey)
  + [暗号化](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Encrypt)
  + [GetKeyPolicy](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/GetKeyPolicy)
  + [ListAliases](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ListAliases)
  + [ListGrants](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ListGrants)
  + [ListKeys](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ListKeys)
  + [RevokeGrant](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/RevokeGrant)
  + [ScheduleKeyDeletion](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ScheduleKeyDeletion)
  + [Sign](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Sign)
  + [TagResource](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/TagResource)

## アクション
<a name="actions"></a>

### `CreateAlias`
<a name="kms_CreateAlias_python_3_topic"></a>

次のコード例は、`CreateAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class AliasManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_key = None

    @classmethod
    def from_client(cls) -> "AliasManager":
        """
        Creates an AliasManager instance with a default KMS client.

        :return: An instance of AliasManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def create_alias(self, key_id: str, alias: str) -> None:
        """
        Creates an alias for the specified key.

        :param key_id: The ARN or ID of a key to give an alias.
        :param alias: The alias to assign to the key.
        """
        try:
            self.kms_client.create_alias(AliasName=alias, TargetKeyId=key_id)
        except ClientError as err:
            if err.response["Error"]["Code"] == "AlreadyExistsException":
                logger.error(
                    "Could not create the alias %s because it already exists.", key_id
                )
            else:
                logger.error(
                    "Couldn't encrypt text. Here's why: %s",
                    err.response["Error"]["Message"],
                )
                raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateAlias](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/CreateAlias)」を参照してください。

### `CreateGrant`
<a name="kms_CreateGrant_python_3_topic"></a>

次のコード例は、`CreateGrant` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class GrantManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "GrantManager":
        """
        Creates a GrantManager instance with a default KMS client.

        :return: An instance of GrantManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def create_grant(
        self, key_id: str, principal: str, operations: [str]
    ) -> dict[str, str]:
        """
        Creates a grant for a key that lets a principal generate a symmetric data
        encryption key.

        :param key_id: The ARN or ID of the key.
        :param principal: The principal to grant permission to.
        :param operations: The operations to grant permission for.
        :return: The grant that is created.
        """
        try:
            return self.kms_client.create_grant(
                KeyId=key_id,
                GranteePrincipal=principal,
                Operations=operations,
            )
        except ClientError as err:
            logger.error(
                "Couldn't create a grant on key %s. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateGrant](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/CreateGrant)」を参照してください。

### `CreateKey`
<a name="kms_CreateKey_python_3_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def create_key(self, key_description: str) -> dict[str, any]:
        """
        Creates a key with a user-provided description.

        :param key_description: A description for the key.
        :return: The key ID.
        """
        try:
            key = self.kms_client.create_key(Description=key_description)["KeyMetadata"]
            self.created_keys.append(key)
            return key
        except ClientError as err:
            logging.error(
                "Couldn't create your key. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/CreateKey)」を参照してください。

### `Decrypt`
<a name="kms_Decrypt_python_3_topic"></a>

次のコード例は、`Decrypt` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyEncrypt:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyEncrypt":
        """
        Creates a KeyEncrypt instance with a default KMS client.

        :return: An instance of KeyEncrypt initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def decrypt(self, key_id: str, cipher_text: bytes) -> str:
        """
        Decrypts text previously encrypted with a key.

        :param key_id: The ARN or ID of the key used to decrypt the data.
        :param cipher_text: The encrypted text to decrypt.
        :return: The decrypted text.
        """
        try:
            return self.kms_client.decrypt(KeyId=key_id, CiphertextBlob=cipher_text)[
                "Plaintext"
            ].decode()
        except ClientError as err:
            logger.error(
                "Couldn't decrypt your ciphertext. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[Decrypt](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Decrypt)」を参照してください。

### `DeleteAlias`
<a name="kms_DeleteAlias_python_3_topic"></a>

次のコード例は、`DeleteAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class AliasManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_key = None

    @classmethod
    def from_client(cls) -> "AliasManager":
        """
        Creates an AliasManager instance with a default KMS client.

        :return: An instance of AliasManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def delete_alias(self, alias: str) -> None:
        """
        Deletes an alias.

        :param alias: The alias to delete.
        """
        try:
            self.kms_client.delete_alias(AliasName=alias)
        except ClientError as err:
            logger.error(
                "Couldn't delete alias %s. Here's why: %s",
                alias,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteAlias](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/DeleteAlias)」を参照してください。

### `DescribeKey`
<a name="kms_DescribeKey_python_3_topic"></a>

次のコード例は、`DescribeKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def describe_key(self, key_id: str) -> dict[str, any]:
        """
        Describes a key.

        :param key_id: The ARN or ID of the key to describe.
        :return: Information about the key.
        """

        try:
            key = self.kms_client.describe_key(KeyId=key_id)["KeyMetadata"]
            return key
        except ClientError as err:
            logging.error(
                "Couldn't get key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/DescribeKey)」を参照してください。

### `DisableKey`
<a name="kms_DisableKey_python_3_topic"></a>

次のコード例は、`DisableKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def disable_key(self, key_id: str) -> None:
        try:
            self.kms_client.disable_key(KeyId=key_id)
        except ClientError as err:
            logging.error(
                "Couldn't disable key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DisableKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/DisableKey)」を参照してください。

### `EnableKey`
<a name="kms_EnableKey_python_3_topic"></a>

次のコード例は、`EnableKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def enable_key(self, key_id: str) -> None:
        """
        Enables a key. Gets the key state after each state change.

        :param key_id: The ARN or ID of the key to enable.
        """
        try:
            self.kms_client.enable_key(KeyId=key_id)
        except ClientError as err:
            logging.error(
                "Couldn't enable key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[EnableKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/EnableKey)」を参照してください。

### `EnableKeyRotation`
<a name="kms_EnableKeyRotation_python_3_topic"></a>

次のコード例は、`EnableKeyRotation` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def enable_key_rotation(self, key_id: str) -> None:
        """
        Enables rotation for a key.

        :param key_id: The ARN or ID of the key to enable rotation for.
        """
        try:
            self.kms_client.enable_key_rotation(KeyId=key_id)
        except ClientError as err:
            logging.error(
                "Couldn't enable rotation for key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[EnableKeyRotation](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/EnableKeyRotation)」を参照してください。

### `Encrypt`
<a name="kms_Encrypt_python_3_topic"></a>

次のコード例は、`Encrypt` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyEncrypt:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyEncrypt":
        """
        Creates a KeyEncrypt instance with a default KMS client.

        :return: An instance of KeyEncrypt initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def encrypt(self, key_id: str, text: str) -> bytes:
        """
        Encrypts text by using the specified key.

        :param key_id: The ARN or ID of the key to use for encryption.
        :param text: The text to encrypt.
        :return: The encrypted version of the text.
        """
        try:
            response = self.kms_client.encrypt(KeyId=key_id, Plaintext=text.encode())
            print(
                f"The string was encrypted with algorithm {response['EncryptionAlgorithm']}"
            )
            return response["CiphertextBlob"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DisabledException":
                logger.error(
                    "Could not encrypt because the key %s is disabled.", key_id
                )
            else:
                logger.error(
                    "Couldn't encrypt text. Here's why: %s",
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[Encrypt](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Encrypt)」を参照してください。

### `GenerateDataKey`
<a name="kms_GenerateDataKey_python_3_topic"></a>

次のコード例は、`GenerateDataKey` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def generate_data_key(self, key_id):
        """
        Generates a symmetric data key that can be used for client-side encryption.
        """
        answer = input(
            f"Do you want to generate a symmetric data key from key {key_id} (y/n)? "
        )
        if answer.lower() == "y":
            try:
                data_key = self.kms_client.generate_data_key(
                    KeyId=key_id, KeySpec="AES_256"
                )
            except ClientError as err:
                logger.error(
                    "Couldn't generate a data key for key %s. Here's why: %s",
                    key_id,
                    err.response["Error"]["Message"],
                )
            else:
                pprint(data_key)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GenerateDataKey](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/GenerateDataKey)」を参照してください。

### `GetKeyPolicy`
<a name="kms_GetKeyPolicy_python_3_topic"></a>

次のコード例は、`GetKeyPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyPolicy:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyPolicy":
        """
        Creates a KeyPolicy instance with a default KMS client.

        :return: An instance of KeyPolicy initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def get_policy(self, key_id: str) -> dict[str, str]:
        """
        Gets the policy of a key.

        :param key_id: The ARN or ID of the key to query.
        :return: The key policy as a dict.
        """
        if key_id != "":
            try:
                response = self.kms_client.get_key_policy(
                    KeyId=key_id,
                )
                policy = json.loads(response["Policy"])
            except ClientError as err:
                logger.error(
                    "Couldn't get policy for key %s. Here's why: %s",
                    key_id,
                    err.response["Error"]["Message"],
                )
                raise
            else:
                pprint(policy)
                return policy
        else:
            print("Skipping get policy demo.")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetKeyPolicy](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/GetKeyPolicy)」を参照してください。

### `ListAliases`
<a name="kms_ListAliases_python_3_topic"></a>

次のコード例は、`ListAliases` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class AliasManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_key = None

    @classmethod
    def from_client(cls) -> "AliasManager":
        """
        Creates an AliasManager instance with a default KMS client.

        :return: An instance of AliasManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def list_aliases(self, page_size: int) -> None:
        """
        Lists aliases for the current account.
        :param page_size: The number of aliases to list per page.
        """
        try:
            alias_paginator = self.kms_client.get_paginator("list_aliases")
            for alias_page in alias_paginator.paginate(
                PaginationConfig={"PageSize": page_size}
            ):
                print(f"Here are {page_size} aliases:")
                pprint(alias_page["Aliases"])
                if alias_page["Truncated"]:
                    answer = input(
                        f"Do you want to see the next {page_size} aliases (y/n)? "
                    )
                    if answer.lower() != "y":
                        break
                else:
                    print("That's all your aliases!")
        except ClientError as err:
            logging.error(
                "Couldn't list your aliases. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListAliases](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ListAliases)」を参照してください。

### `ListGrants`
<a name="kms_ListGrants_python_3_topic"></a>

次のコード例は、`ListGrants` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class GrantManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "GrantManager":
        """
        Creates a GrantManager instance with a default KMS client.

        :return: An instance of GrantManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def list_grants(self, key_id):
        """
        Lists grants for a key.

        :param key_id: The ARN or ID of the key to query.
        :return: The grants for the key.
        """
        try:
            paginator = self.kms_client.get_paginator("list_grants")
            grants = []
            page_iterator = paginator.paginate(KeyId=key_id)
            for page in page_iterator:
                grants.extend(page["Grants"])

            print(f"Grants for key {key_id}:")
            pprint(grants)
            return grants
        except ClientError as err:
            logger.error(
                "Couldn't list grants for key %s. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListGrants](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ListGrants)」を参照してください。

### `ListKeyPolicies`
<a name="kms_ListKeyPolicies_python_3_topic"></a>

次のコード例は、`ListKeyPolicies` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyPolicy:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyPolicy":
        """
        Creates a KeyPolicy instance with a default KMS client.

        :return: An instance of KeyPolicy initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def list_policies(self, key_id):
        """
        Lists the names of the policies for a key.

        :param key_id: The ARN or ID of the key to query.
        """
        try:
            policy_names = self.kms_client.list_key_policies(KeyId=key_id)[
                "PolicyNames"
            ]
        except ClientError as err:
            logging.error(
                "Couldn't list your policies. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise
        else:
            print(f"The policies for key {key_id} are:")
            pprint(policy_names)
```
+  API の詳細については、**「AWS SDK for Python (Boto3) APIリファレンス」の「[ListKeyPolicies](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ListKeyPolicies)」を参照してください。

### `ListKeys`
<a name="kms_ListKeys_python_3_topic"></a>

次のコード例は、`ListKeys` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def list_keys(self):
        """
        Lists the keys for the current account by using a paginator.
        """
        try:
            page_size = 10
            print("\nLet's list your keys.")
            key_paginator = self.kms_client.get_paginator("list_keys")
            for key_page in key_paginator.paginate(PaginationConfig={"PageSize": 10}):
                print(f"Here are {len(key_page['Keys'])} keys:")
                pprint(key_page["Keys"])
                if key_page["Truncated"]:
                    answer = input(
                        f"Do you want to see the next {page_size} keys (y/n)? "
                    )
                    if answer.lower() != "y":
                        break
                else:
                    print("That's all your keys!")
        except ClientError as err:
            logging.error(
                "Couldn't list your keys. Here's why: %s",
                err.response["Error"]["Message"],
            )
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListKeys](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ListKeys)」を参照してください。

### `PutKeyPolicy`
<a name="kms_PutKeyPolicy_python_3_topic"></a>

次のコード例は、`PutKeyPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyPolicy:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyPolicy":
        """
        Creates a KeyPolicy instance with a default KMS client.

        :return: An instance of KeyPolicy initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def set_policy(self, key_id: str, policy: dict[str, any]) -> None:
        """
        Sets the policy of a key. Setting a policy entirely overwrites the existing
        policy, so care is taken to add a statement to the existing list of statements
        rather than simply writing a new policy.

        :param key_id: The ARN or ID of the key to set the policy to.
        :param policy: The existing policy of the key.
        :return: None
        """
        principal = input(
            "Enter the ARN of an IAM role to set as the principal on the policy: "
        )
        if key_id != "" and principal != "":
            # The updated policy replaces the existing policy. Add a new statement to
            # the list along with the original policy statements.
            policy["Statement"].append(
                {
                    "Sid": "Allow access for ExampleRole",
                    "Effect": "Allow",
                    "Principal": {"AWS": principal},
                    "Action": [
                        "kms:Encrypt",
                        "kms:GenerateDataKey*",
                        "kms:Decrypt",
                        "kms:DescribeKey",
                        "kms:ReEncrypt*",
                    ],
                    "Resource": "*",
                }
            )
            try:
                self.kms_client.put_key_policy(KeyId=key_id, Policy=json.dumps(policy))
            except ClientError as err:
                logger.error(
                    "Couldn't set policy for key %s. Here's why %s",
                    key_id,
                    err.response["Error"]["Message"],
                )
                raise
            else:
                print(f"Set policy for key {key_id}.")
        else:
            print("Skipping set policy demo.")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[PutKeyPolicy](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/PutKeyPolicy)」を参照してください。

### `ReEncrypt`
<a name="kms_ReEncrypt_python_3_topic"></a>

次のコード例は、`ReEncrypt` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyEncrypt:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyEncrypt":
        """
        Creates a KeyEncrypt instance with a default KMS client.

        :return: An instance of KeyEncrypt initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def re_encrypt(self, source_key_id, cipher_text):
        """
        Takes ciphertext previously encrypted with one key and reencrypt it by using
        another key.

        :param source_key_id: The ARN or ID of the original key used to encrypt the
                              ciphertext.
        :param cipher_text: The encrypted ciphertext.
        :return: The ciphertext encrypted by the second key.
        """
        destination_key_id = input(
            f"Your ciphertext is currently encrypted with key {source_key_id}. "
            f"Enter another key ID or ARN to reencrypt it: "
        )
        if destination_key_id != "":
            try:
                cipher_text = self.kms_client.re_encrypt(
                    SourceKeyId=source_key_id,
                    DestinationKeyId=destination_key_id,
                    CiphertextBlob=cipher_text,
                )["CiphertextBlob"]
            except ClientError as err:
                logger.error(
                    "Couldn't reencrypt your ciphertext. Here's why: %s",
                    err.response["Error"]["Message"],
                )
            else:
                print(f"Reencrypted your ciphertext as: {cipher_text}")
                return cipher_text
        else:
            print("Skipping reencryption demo.")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ReEncrypt](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ReEncrypt)」を参照してください。

### `RetireGrant`
<a name="kms_RetireGrant_python_3_topic"></a>

次のコード例は、`RetireGrant` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class GrantManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "GrantManager":
        """
        Creates a GrantManager instance with a default KMS client.

        :return: An instance of GrantManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def retire_grant(self, grant):
        """
        Retires a grant so that it can no longer be used.

        :param grant: The grant to retire.
        """
        try:
            self.kms_client.retire_grant(GrantToken=grant["GrantToken"])
        except ClientError as err:
            logger.error(
                "Couldn't retire grant %s. Here's why: %s",
                grant["GrantId"],
                err.response["Error"]["Message"],
            )
        else:
            print(f"Grant {grant['GrantId']} retired.")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[RetireGrant](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/RetireGrant)」を参照してください。

### `RevokeGrant`
<a name="kms_RevokeGrant_python_3_topic"></a>

次のコード例は、`RevokeGrant` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class GrantManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "GrantManager":
        """
        Creates a GrantManager instance with a default KMS client.

        :return: An instance of GrantManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def revoke_grant(self, key_id: str, grant_id: str) -> None:
        """
        Revokes a grant so that it can no longer be used.

        :param key_id: The ARN or ID of the key associated with the grant.
        :param grant_id: The ID of the grant to revoke.
        """
        try:
            self.kms_client.revoke_grant(KeyId=key_id, GrantId=grant_id)
        except ClientError as err:
            logger.error(
                "Couldn't revoke grant %s. Here's why: %s",
                grant_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[RevokeGrant](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/RevokeGrant)」を参照してください。

### `ScheduleKeyDeletion`
<a name="kms_ScheduleKeyDeletion_python_3_topic"></a>

次のコード例は、`ScheduleKeyDeletion` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def delete_key(self, key_id: str, window: int) -> None:
        """
        Deletes a list of keys.

        Warning:
        Deleting a KMS key is a destructive and potentially dangerous operation. When a KMS key is deleted,
        all data that was encrypted under the KMS key is unrecoverable.

        :param key_id: The ARN or ID of the key to delete.
        :param window: The waiting period, in days, before the KMS key is deleted.
        """

        try:
            self.kms_client.schedule_key_deletion(
                KeyId=key_id, PendingWindowInDays=window
            )
        except ClientError as err:
            logging.error(
                "Couldn't delete key %s. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ScheduleKeyDeletion](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/ScheduleKeyDeletion)」を参照してください。

### `Sign`
<a name="kms_Sign_python_3_topic"></a>

次のコード例は、`Sign` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyEncrypt:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyEncrypt":
        """
        Creates a KeyEncrypt instance with a default KMS client.

        :return: An instance of KeyEncrypt initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def sign(self, key_id: str, message: str) -> str:
        """
        Signs a message with a key.

        :param key_id: The ARN or ID of the key to use for signing.
        :param message: The message to sign.
        :return: The signature of the message.
        """
        try:
            return self.kms_client.sign(
                KeyId=key_id,
                Message=message.encode(),
                SigningAlgorithm="RSASSA_PSS_SHA_256",
            )["Signature"]
        except ClientError as err:
            logger.error(
                "Couldn't sign your message. Here's why: %s",
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[署名](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Sign)」を参照してください。

### `TagResource`
<a name="kms_TagResource_python_3_topic"></a>

次のコード例は、`TagResource` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_keys = []

    @classmethod
    def from_client(cls) -> "KeyManager":
        """
        Creates a KeyManager instance with a default KMS client.

        :return: An instance of KeyManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def tag_resource(self, key_id: str, tag_key: str, tag_value: str) -> None:
        """
        Add or edit tags on a customer managed key.

        :param key_id: The ARN or ID of the key to enable rotation for.
        :param tag_key: Key for the tag.
        :param tag_value: Value for the tag.
        """
        try:
            self.kms_client.tag_resource(
                KeyId=key_id, Tags=[{"TagKey": tag_key, "TagValue": tag_value}]
            )
        except ClientError as err:
            logging.error(
                "Couldn't add a tag for the key '%s'. Here's why: %s",
                key_id,
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[TagResource](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/TagResource)」を参照してください。

### `UpdateAlias`
<a name="kms_UpdateAlias_python_3_topic"></a>

次のコード例は、`UpdateAlias` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class AliasManager:
    def __init__(self, kms_client):
        self.kms_client = kms_client
        self.created_key = None

    @classmethod
    def from_client(cls) -> "AliasManager":
        """
        Creates an AliasManager instance with a default KMS client.

        :return: An instance of AliasManager initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def update_alias(self, alias, current_key_id):
        """
        Updates an alias by assigning it to another key.

        :param alias: The alias to reassign.
        :param current_key_id: The ARN or ID of the key currently associated with the alias.
        """
        new_key_id = input(
            f"Alias {alias} is currently associated with {current_key_id}. "
            f"Enter another key ID or ARN that you want to associate with {alias}: "
        )
        if new_key_id != "":
            try:
                self.kms_client.update_alias(AliasName=alias, TargetKeyId=new_key_id)
            except ClientError as err:
                logger.error(
                    "Couldn't associate alias %s with key %s. Here's why: %s",
                    alias,
                    new_key_id,
                    err.response["Error"]["Message"],
                )
            else:
                print(f"Alias {alias} is now associated with key {new_key_id}.")
        else:
            print("Skipping alias update.")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateAlias](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/UpdateAlias)」を参照してください。

### `Verify`
<a name="kms_Verify_python_3_topic"></a>

次のコード例は、`Verify` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
class KeyEncrypt:
    def __init__(self, kms_client):
        self.kms_client = kms_client

    @classmethod
    def from_client(cls) -> "KeyEncrypt":
        """
        Creates a KeyEncrypt instance with a default KMS client.

        :return: An instance of KeyEncrypt initialized with the default KMS client.
        """
        kms_client = boto3.client("kms")
        return cls(kms_client)


    def verify(self, key_id: str, message: str, signature: str) -> bool:
        """
        Verifies a signature against a message.

        :param key_id: The ARN or ID of the key used to sign the message.
        :param message: The message to verify.
        :param signature: The signature to verify.
        :return: True when the signature matches the message, otherwise False.
        """
        try:
            response = self.kms_client.verify(
                KeyId=key_id,
                Message=message.encode(),
                Signature=signature,
                SigningAlgorithm="RSASSA_PSS_SHA_256",
            )
            valid = response["SignatureValid"]
            print(f"The signature is {'valid' if valid else 'invalid'}.")
            return valid
        except ClientError as err:
            if err.response["Error"]["Code"] == "SignatureDoesNotMatchException":
                print("The signature is not valid.")
            else:
                logger.error(
                    "Couldn't verify your signature. Here's why: %s",
                    err.response["Error"]["Message"],
                )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[Verify](https://docs.aws.amazon.com/goto/boto3/kms-2014-11-01/Verify)」を参照してください。

# SDK for Python (Boto3) を使用した Lambda の例
<a name="python_3_lambda_code_examples"></a>

次のコード例は、Lambda AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Lambda
<a name="lambda_Hello_python_3_topic"></a>

次のコード例は、Lambda の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def main():
    """
    List the Lambda functions in your AWS account.
    """
    # Create the Lambda client
    lambda_client = boto3.client("lambda")

    # Use the paginator to list the functions
    paginator = lambda_client.get_paginator("list_functions")
    response_iterator = paginator.paginate()

    print("Here are the Lambda functions in your account:")
    for page in response_iterator:
        for function in page["Functions"]:
            print(f"  {function['FunctionName']}")


if __name__ == "__main__":
    main()
```
+  API の詳細については、「*AWS SDK for Python (Boto3) の API リファレンス*」の「[ListFunctions](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListFunctions)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。
数値をインクリメントする Lambda ハンドラーを定義します。  

```
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    """
    Accepts an action and a single number, performs the specified action on the number,
    and returns the result. The only allowable action is 'increment'.

    :param event: The event dict that contains the parameters sent when the function
                  is invoked.
    :param context: The context in which the function is called.
    :return: The result of the action.
    """
    result = None
    action = event.get("action")
    if action == "increment":
        result = event.get("number", 0) + 1
        logger.info("Calculated result of %s", result)
    else:
        logger.error("%s is not a valid action.", action)

    response = {"result": result}
    return response
```
算術演算を実行する 2 番目の Lambda ハンドラーを定義します。  

```
import logging
import os


logger = logging.getLogger()

# Define a list of Python lambda functions that are called by this AWS Lambda function.
ACTIONS = {
    "plus": lambda x, y: x + y,
    "minus": lambda x, y: x - y,
    "times": lambda x, y: x * y,
    "divided-by": lambda x, y: x / y,
}


def lambda_handler(event, context):
    """
    Accepts an action and two numbers, performs the specified action on the numbers,
    and returns the result.

    :param event: The event dict that contains the parameters sent when the function
                  is invoked.
    :param context: The context in which the function is called.
    :return: The result of the specified action.
    """
    # Set the log level based on a variable configured in the Lambda environment.
    logger.setLevel(os.environ.get("LOG_LEVEL", logging.INFO))
    logger.debug("Event: %s", event)

    action = event.get("action")
    func = ACTIONS.get(action)
    x = event.get("x")
    y = event.get("y")
    result = None
    try:
        if func is not None and x is not None and y is not None:
            result = func(x, y)
            logger.info("%s %s %s is %s", x, action, y, result)
        else:
            logger.error("I can't calculate %s %s %s.", x, action, y)
    except ZeroDivisionError:
        logger.warning("I can't divide %s by 0!", x)

    response = {"result": result}
    return response
```
Lambda アクションをラップする関数を作成します。  

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    @staticmethod
    def create_deployment_package(source_file, destination_file):
        """
        Creates a Lambda deployment package in .zip format in an in-memory buffer. This
        buffer can be passed directly to Lambda when creating the function.

        :param source_file: The name of the file that contains the Lambda handler
                            function.
        :param destination_file: The name to give the file when it's deployed to Lambda.
        :return: The deployment package.
        """
        buffer = io.BytesIO()
        with zipfile.ZipFile(buffer, "w") as zipped:
            zipped.write(source_file, destination_file)
        buffer.seek(0)
        return buffer.read()

    def get_iam_role(self, iam_role_name):
        """
        Get an AWS Identity and Access Management (IAM) role.

        :param iam_role_name: The name of the role to retrieve.
        :return: The IAM role.
        """
        role = None
        try:
            temp_role = self.iam_resource.Role(iam_role_name)
            temp_role.load()
            role = temp_role
            logger.info("Got IAM role %s", role.name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "NoSuchEntity":
                logger.info("IAM role %s does not exist.", iam_role_name)
            else:
                logger.error(
                    "Couldn't get IAM role %s. Here's why: %s: %s",
                    iam_role_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return role

    def create_iam_role_for_lambda(self, iam_role_name):
        """
        Creates an IAM role that grants the Lambda function basic permissions. If a
        role with the specified name already exists, it is used for the demo.

        :param iam_role_name: The name of the role to create.
        :return: The role and a value that indicates whether the role is newly created.
        """
        role = self.get_iam_role(iam_role_name)
        if role is not None:
            return role, False

        lambda_assume_role_policy = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Effect": "Allow",
                    "Principal": {"Service": "lambda.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"

        try:
            role = self.iam_resource.create_role(
                RoleName=iam_role_name,
                AssumeRolePolicyDocument=json.dumps(lambda_assume_role_policy),
            )
            logger.info("Created role %s.", role.name)
            role.attach_policy(PolicyArn=policy_arn)
            logger.info("Attached basic execution policy to role %s.", role.name)
        except ClientError as error:
            if error.response["Error"]["Code"] == "EntityAlreadyExists":
                role = self.iam_resource.Role(iam_role_name)
                logger.warning("The role %s already exists. Using it.", iam_role_name)
            else:
                logger.exception(
                    "Couldn't create role %s or attach policy %s.",
                    iam_role_name,
                    policy_arn,
                )
                raise

        return role, True

    def get_function(self, function_name):
        """
        Gets data about a Lambda function.

        :param function_name: The name of the function.
        :return: The function data.
        """
        response = None
        try:
            response = self.lambda_client.get_function(FunctionName=function_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.info("Function %s does not exist.", function_name)
            else:
                logger.error(
                    "Couldn't get function %s. Here's why: %s: %s",
                    function_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return response


    def create_function(
        self, function_name, handler_name, iam_role, deployment_package
    ):
        """
        Deploys a Lambda function.

        :param function_name: The name of the Lambda function.
        :param handler_name: The fully qualified name of the handler function. This
                             must include the file name and the function name.
        :param iam_role: The IAM role to use for the function.
        :param deployment_package: The deployment package that contains the function
                                   code in .zip format.
        :return: The Amazon Resource Name (ARN) of the newly created function.
        """
        try:
            response = self.lambda_client.create_function(
                FunctionName=function_name,
                Description="AWS Lambda doc example",
                Runtime="python3.9",
                Role=iam_role.arn,
                Handler=handler_name,
                Code={"ZipFile": deployment_package},
                Publish=True,
            )
            function_arn = response["FunctionArn"]
            waiter = self.lambda_client.get_waiter("function_active_v2")
            waiter.wait(FunctionName=function_name)
            logger.info(
                "Created function '%s' with ARN: '%s'.",
                function_name,
                response["FunctionArn"],
            )
        except ClientError:
            logger.error("Couldn't create function %s.", function_name)
            raise
        else:
            return function_arn


    def delete_function(self, function_name):
        """
        Deletes a Lambda function.

        :param function_name: The name of the function to delete.
        """
        try:
            self.lambda_client.delete_function(FunctionName=function_name)
        except ClientError:
            logger.exception("Couldn't delete function %s.", function_name)
            raise


    def invoke_function(self, function_name, function_params, get_log=False):
        """
        Invokes a Lambda function.

        :param function_name: The name of the function to invoke.
        :param function_params: The parameters of the function as a dict. This dict
                                is serialized to JSON before it is sent to Lambda.
        :param get_log: When true, the last 4 KB of the execution log are included in
                        the response.
        :return: The response from the function invocation.
        """
        try:
            response = self.lambda_client.invoke(
                FunctionName=function_name,
                Payload=json.dumps(function_params),
                LogType="Tail" if get_log else "None",
            )
            logger.info("Invoked function %s.", function_name)
        except ClientError:
            logger.exception("Couldn't invoke function %s.", function_name)
            raise
        return response


    def update_function_code(self, function_name, deployment_package):
        """
        Updates the code for a Lambda function by submitting a .zip archive that contains
        the code for the function.

        :param function_name: The name of the function to update.
        :param deployment_package: The function code to update, packaged as bytes in
                                   .zip format.
        :return: Data about the update, including the status.
        """
        try:
            response = self.lambda_client.update_function_code(
                FunctionName=function_name, ZipFile=deployment_package
            )
        except ClientError as err:
            logger.error(
                "Couldn't update function %s. Here's why: %s: %s",
                function_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def update_function_configuration(self, function_name, env_vars):
        """
        Updates the environment variables for a Lambda function.

        :param function_name: The name of the function to update.
        :param env_vars: A dict of environment variables to update.
        :return: Data about the update, including the status.
        """
        try:
            response = self.lambda_client.update_function_configuration(
                FunctionName=function_name, Environment={"Variables": env_vars}
            )
        except ClientError as err:
            logger.error(
                "Couldn't update function configuration %s. Here's why: %s: %s",
                function_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def list_functions(self):
        """
        Lists the Lambda functions for the current account.
        """
        try:
            func_paginator = self.lambda_client.get_paginator("list_functions")
            for func_page in func_paginator.paginate():
                for func in func_page["Functions"]:
                    print(func["FunctionName"])
                    desc = func.get("Description")
                    if desc:
                        print(f"\t{desc}")
                    print(f"\t{func['Runtime']}: {func['Handler']}")
        except ClientError as err:
            logger.error(
                "Couldn't list functions. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
シナリオを実行する関数を作成します。  

```
class UpdateFunctionWaiter(CustomWaiter):
    """A custom waiter that waits until a function is successfully updated."""

    def __init__(self, client):
        super().__init__(
            "UpdateSuccess",
            "GetFunction",
            "Configuration.LastUpdateStatus",
            {"Successful": WaitState.SUCCESS, "Failed": WaitState.FAILURE},
            client,
        )

    def wait(self, function_name):
        self._wait(FunctionName=function_name)


def run_scenario(lambda_client, iam_resource, basic_file, calculator_file, lambda_name):
    """
    Runs the scenario.

    :param lambda_client: A Boto3 Lambda client.
    :param iam_resource: A Boto3 IAM resource.
    :param basic_file: The name of the file that contains the basic Lambda handler.
    :param calculator_file: The name of the file that contains the calculator Lambda handler.
    :param lambda_name: The name to give resources created for the scenario, such as the
                        IAM role and the Lambda function.
    """
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Welcome to the AWS Lambda getting started with functions demo.")
    print("-" * 88)

    wrapper = LambdaWrapper(lambda_client, iam_resource)

    print("Checking for IAM role for Lambda...")
    iam_role, should_wait = wrapper.create_iam_role_for_lambda(lambda_name)
    if should_wait:
        logger.info("Giving AWS time to create resources...")
        wait(10)

    print(f"Looking for function {lambda_name}...")
    function = wrapper.get_function(lambda_name)
    if function is None:
        print("Zipping the Python script into a deployment package...")
        deployment_package = wrapper.create_deployment_package(
            basic_file, f"{lambda_name}.py"
        )
        print(f"...and creating the {lambda_name} Lambda function.")
        wrapper.create_function(
            lambda_name, f"{lambda_name}.lambda_handler", iam_role, deployment_package
        )
    else:
        print(f"Function {lambda_name} already exists.")
    print("-" * 88)

    print(f"Let's invoke {lambda_name}. This function increments a number.")
    action_params = {
        "action": "increment",
        "number": q.ask("Give me a number to increment: ", q.is_int),
    }
    print(f"Invoking {lambda_name}...")
    response = wrapper.invoke_function(lambda_name, action_params)
    print(
        f"Incrementing {action_params['number']} resulted in "
        f"{json.load(response['Payload'])}"
    )
    print("-" * 88)

    print(f"Let's update the function to an arithmetic calculator.")
    q.ask("Press Enter when you're ready.")
    print("Creating a new deployment package...")
    deployment_package = wrapper.create_deployment_package(
        calculator_file, f"{lambda_name}.py"
    )
    print(f"...and updating the {lambda_name} Lambda function.")
    update_waiter = UpdateFunctionWaiter(lambda_client)
    wrapper.update_function_code(lambda_name, deployment_package)
    update_waiter.wait(lambda_name)
    print(f"This function uses an environment variable to control logging level.")
    print(f"Let's set it to DEBUG to get the most logging.")
    wrapper.update_function_configuration(
        lambda_name, {"LOG_LEVEL": logging.getLevelName(logging.DEBUG)}
    )

    actions = ["plus", "minus", "times", "divided-by"]
    want_invoke = True
    while want_invoke:
        print(f"Let's invoke {lambda_name}. You can invoke these actions:")
        for index, action in enumerate(actions):
            print(f"{index + 1}: {action}")
        action_params = {}
        action_index = q.ask(
            "Enter the number of the action you want to take: ",
            q.is_int,
            q.in_range(1, len(actions)),
        )
        action_params["action"] = actions[action_index - 1]
        print(f"You've chosen to invoke 'x {action_params['action']} y'.")
        action_params["x"] = q.ask("Enter a value for x: ", q.is_int)
        action_params["y"] = q.ask("Enter a value for y: ", q.is_int)
        print(f"Invoking {lambda_name}...")
        response = wrapper.invoke_function(lambda_name, action_params, True)
        print(
            f"Calculating {action_params['x']} {action_params['action']} {action_params['y']} "
            f"resulted in {json.load(response['Payload'])}"
        )
        q.ask("Press Enter to see the logs from the call.")
        print(base64.b64decode(response["LogResult"]).decode())
        want_invoke = q.ask("That was fun. Shall we do it again? (y/n) ", q.is_yesno)
    print("-" * 88)

    if q.ask(
        "Do you want to list all of the functions in your account? (y/n) ", q.is_yesno
    ):
        wrapper.list_functions()
    print("-" * 88)

    if q.ask("Ready to delete the function and role? (y/n) ", q.is_yesno):
        for policy in iam_role.attached_policies.all():
            policy.detach_role(RoleName=iam_role.name)
        iam_role.delete()
        print(f"Deleted role {lambda_name}.")
        wrapper.delete_function(lambda_name)
        print(f"Deleted function {lambda_name}.")

    print("\nThanks for watching!")
    print("-" * 88)


if __name__ == "__main__":
    try:
        run_scenario(
            boto3.client("lambda"),
            boto3.resource("iam"),
            "lambda_handler_basic.py",
            "lambda_handler_calculator.py",
            "doc_example_lambda_calculator",
        )
    except Exception:
        logging.exception("Something went wrong with the demo!")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/CreateFunction)
  + [DeleteFunction](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteFunction)
  + [GetFunction](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetFunction)
  + [Invoke](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/Invoke)
  + [ListFunctions](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListFunctions)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateFunctionCode)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateFunctionConfiguration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_python_3_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def create_function(
        self, function_name, handler_name, iam_role, deployment_package
    ):
        """
        Deploys a Lambda function.

        :param function_name: The name of the Lambda function.
        :param handler_name: The fully qualified name of the handler function. This
                             must include the file name and the function name.
        :param iam_role: The IAM role to use for the function.
        :param deployment_package: The deployment package that contains the function
                                   code in .zip format.
        :return: The Amazon Resource Name (ARN) of the newly created function.
        """
        try:
            response = self.lambda_client.create_function(
                FunctionName=function_name,
                Description="AWS Lambda doc example",
                Runtime="python3.9",
                Role=iam_role.arn,
                Handler=handler_name,
                Code={"ZipFile": deployment_package},
                Publish=True,
            )
            function_arn = response["FunctionArn"]
            waiter = self.lambda_client.get_waiter("function_active_v2")
            waiter.wait(FunctionName=function_name)
            logger.info(
                "Created function '%s' with ARN: '%s'.",
                function_name,
                response["FunctionArn"],
            )
        except ClientError:
            logger.error("Couldn't create function %s.", function_name)
            raise
        else:
            return function_arn
```
+  API の詳細については、「*AWS SDK for Python (Boto3) の API リファレンス*」の「[CreateFunction](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/CreateFunction)」を参照してください。

### `DeleteFunction`
<a name="lambda_DeleteFunction_python_3_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def delete_function(self, function_name):
        """
        Deletes a Lambda function.

        :param function_name: The name of the function to delete.
        """
        try:
            self.lambda_client.delete_function(FunctionName=function_name)
        except ClientError:
            logger.exception("Couldn't delete function %s.", function_name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) の API リファレンス*」の「[DeleteFunction](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/DeleteFunction)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_python_3_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def get_function(self, function_name):
        """
        Gets data about a Lambda function.

        :param function_name: The name of the function.
        :return: The function data.
        """
        response = None
        try:
            response = self.lambda_client.get_function(FunctionName=function_name)
        except ClientError as err:
            if err.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.info("Function %s does not exist.", function_name)
            else:
                logger.error(
                    "Couldn't get function %s. Here's why: %s: %s",
                    function_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetFunction](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/GetFunction)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_python_3_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def invoke_function(self, function_name, function_params, get_log=False):
        """
        Invokes a Lambda function.

        :param function_name: The name of the function to invoke.
        :param function_params: The parameters of the function as a dict. This dict
                                is serialized to JSON before it is sent to Lambda.
        :param get_log: When true, the last 4 KB of the execution log are included in
                        the response.
        :return: The response from the function invocation.
        """
        try:
            response = self.lambda_client.invoke(
                FunctionName=function_name,
                Payload=json.dumps(function_params),
                LogType="Tail" if get_log else "None",
            )
            logger.info("Invoked function %s.", function_name)
        except ClientError:
            logger.exception("Couldn't invoke function %s.", function_name)
            raise
        return response
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[Invoke](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/Invoke)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_python_3_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def list_functions(self):
        """
        Lists the Lambda functions for the current account.
        """
        try:
            func_paginator = self.lambda_client.get_paginator("list_functions")
            for func_page in func_paginator.paginate():
                for func in func_page["Functions"]:
                    print(func["FunctionName"])
                    desc = func.get("Description")
                    if desc:
                        print(f"\t{desc}")
                    print(f"\t{func['Runtime']}: {func['Handler']}")
        except ClientError as err:
            logger.error(
                "Couldn't list functions. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) の API リファレンス*」の「[ListFunctions](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/ListFunctions)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_python_3_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def update_function_code(self, function_name, deployment_package):
        """
        Updates the code for a Lambda function by submitting a .zip archive that contains
        the code for the function.

        :param function_name: The name of the function to update.
        :param deployment_package: The function code to update, packaged as bytes in
                                   .zip format.
        :return: Data about the update, including the status.
        """
        try:
            response = self.lambda_client.update_function_code(
                FunctionName=function_name, ZipFile=deployment_package
            )
        except ClientError as err:
            logger.error(
                "Couldn't update function %s. Here's why: %s: %s",
                function_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) の API リファレンス*」の「[UpdateFunctionCode](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateFunctionCode)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_python_3_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper:
    def __init__(self, lambda_client, iam_resource):
        self.lambda_client = lambda_client
        self.iam_resource = iam_resource


    def update_function_configuration(self, function_name, env_vars):
        """
        Updates the environment variables for a Lambda function.

        :param function_name: The name of the function to update.
        :param env_vars: A dict of environment variables to update.
        :return: Data about the update, including the status.
        """
        try:
            response = self.lambda_client.update_function_configuration(
                FunctionName=function_name, Environment={"Variables": env_vars}
            )
        except ClientError as err:
            logger.error(
                "Couldn't update function configuration %s. Here's why: %s: %s",
                function_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/boto3/lambda-2015-03-31/UpdateFunctionConfiguration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### COVID-19 データを追跡する REST API を作成する
<a name="cross_ApiGatewayDataTracker_python_3_topic"></a>

次のコード例は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートする REST API を作成する方法を示しています。

**SDK for Python (Boto3)**  
 で AWS Chalice を使用して AWS SDK for Python (Boto3) 、Amazon API Gateway AWS Lambda、および Amazon DynamoDB を使用するサーバーレス REST API を作成する方法を示します。REST API は、架空のデータを使用して、米国の COVID-19 の日常的なケースを追跡するシステムをシミュレートします。以下ではその方法を説明しています。  
+  AWS Chalice を使用して、API Gateway 経由で送信される REST リクエストを処理するために呼び出される Lambda 関数のルートを定義します。
+ Lambda 関数を使用して、DynamoDB テーブルにデータを取得して保存し、REST リクエストを処理します。
+  AWS CloudFormation テンプレートでテーブル構造とセキュリティロールリソースを定義します。
+  AWS Chalice と CloudFormation を使用して、必要なすべてのリソースをパッケージ化してデプロイします。
+ CloudFormation を使用して、作成されたすべてのリソースをクリーンアップします。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_covid-19_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ CloudFormation
+ DynamoDB
+ Lambda

### 貸出ライブラリ REST API を作成する
<a name="cross_AuroraRestLendingLibrary_python_3_topic"></a>

以下のコード例は、Amazon Aurora データベースでバックアップされた REST API を使用して、常連客が書籍の貸出と返却できる貸出ライブラリを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Relational Database Service (Amazon RDS) API と AWS Chalice AWS SDK for Python (Boto3) で を使用して、Amazon Aurora データベースにバックアップされた REST API を作成する方法を示します。Web サービスは完全にサーバーレスであり、常連客が本を借りたり返却したりできるシンプルな貸し出しライブラリを表しています。以下ではその方法を説明しています。  
+ サーバーレス Aurora データベースクラスターを作成および管理します。
+  AWS Secrets Manager を使用してデータベース認証情報を管理します。
+ Amazon RDS を使用してデータをデータベースに出し入れするデータストレージレイヤーを実装します。
+  AWS Chalice を使用して、サーバーレス REST API を Amazon API Gateway および にデプロイします AWS Lambda。
+ リクエストパッケージを使用して、Web サービスにリクエストを送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_rest_lending_library) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ Aurora
+ Lambda
+ Secrets Manager

### メッセンジャーアプリケーションを作成する
<a name="cross_StepFunctionsMessenger_python_3_topic"></a>

次のコード例は、データベーステーブルからメッセージレコードを取得する AWS Step Functions メッセンジャーアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3) で を使用して AWS Step Functions 、Amazon DynamoDB テーブルからメッセージレコードを取得し、Amazon Simple Queue Service (Amazon SQS) で送信するメッセンジャーアプリケーションを作成する方法を示します。ステートマシンは AWS Lambda 関数と統合して、未送信メッセージがないかデータベースをスキャンします。  
+ Amazon DynamoDB テーブルからメッセージレコードを取得および更新するステートマシンを作成します。
+ ステートマシンの定義を更新して、Amazon Simple Queue Service (Amazon SQS) にもメッセージを送信します。
+ ステートマシンの実行を開始および停止します。
+ サービス統合を使用して、ステートマシンから Lambda、DynamoDB、および Amazon SQS に接続します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/stepfunctions_messenger) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SQS
+ ステップ関数

### WebSocket チャットアプリケーションを作成する
<a name="cross_ApiGatewayWebsocketChat_python_3_topic"></a>

次のコード例は、Amazon API Gateway 上に構築された WebSocket API によって提供されるチャットアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon API Gateway V2 AWS SDK for Python (Boto3) で を使用して、 AWS Lambda および Amazon DynamoDB と統合する WebSocket API を作成する方法を示します。  
+ API Gateway で提供される WebSocket API を作成します。
+ DynamoDB に接続を保存し、他のチャット参加者にメッセージを投稿する Lambda ハンドラを定義します。
+ WebSocket チャットアプリケーションに接続し、WebSockets パッケージを使用してメッセージを送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_websocket_chat) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_python_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例は、 AWS Lambda 関数を対象とする Amazon API Gateway REST API を作成して使用する方法を示しています。Lambda ハンドラーは、HTTP メソッドに基づいてルーティングする方法を示します。クエリ文字列、ヘッダー、および本文からデータを取得する方法。そして、JSON 応答を返す方法。  
+ Lambda 関数をデプロイします。
+ API ゲートウェイ REST API を作成します。
+ Lambda 関数をターゲットとする REST リソースを作成します。
+ API Gateway に Lambda 関数を呼び出す権限を付与します。
+ リクエストパッケージを使用して、REST API にリクエストを送信します。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_python_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例では、スケジュールされた Amazon EventBridge イベントのターゲットとして AWS Lambda 関数を登録する方法を示します。Lambda ハンドラーは、後で取得するために Amazon CloudWatch Logs にわかりやすいメッセージと完全なイベントデータを書き込みます。  
+ Lambda 関数をデプロイします。
+ EventBridge スケジュールイベントを作成し、Lambda 関数をターゲットにします。
+ EventBridge に Lambda 関数を呼び出す許可を付与します
+ CloudWatch Logs から最新のデータを出力して、スケジュールされた呼び出しの結果を表示しています。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_python_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
import json
import os
import boto3
import pymysql

# RDS settings
proxy_host_name = os.environ['PROXY_HOST_NAME']
port = int(os.environ['PORT'])
db_name = os.environ['DB_NAME']
db_user_name = os.environ['DB_USER_NAME']
aws_region = os.environ['AWS_REGION']


# Fetch RDS Auth Token
def get_auth_token():
    client = boto3.client('rds')
    token = client.generate_db_auth_token(
        DBHostname=proxy_host_name,
        Port=port
        DBUsername=db_user_name
        Region=aws_region
    )
    return token

def lambda_handler(event, context):
    token = get_auth_token()
    try:
        connection = pymysql.connect(
            host=proxy_host_name,
            user=db_user_name,
            password=token,
            db=db_name,
            port=port,
            ssl={'ca': 'Amazon RDS'}  # Ensure you have the CA bundle for SSL connection
        )
        
        with connection.cursor() as cursor:
            cursor.execute('SELECT %s + %s AS sum', (3, 2))
            result = cursor.fetchone()

        return result
        
    except Exception as e:
        return (f"Error: {str(e)}")  # Return an error message if an exception occurs
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_python_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での Kinesis イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import base64
def lambda_handler(event, context):

    for record in event['Records']:
        try:
            print(f"Processed Kinesis Event - EventID: {record['eventID']}")
            record_data = base64.b64decode(record['kinesis']['data']).decode('utf-8')
            print(f"Record Data: {record_data}")
            # TODO: Do interesting work based on the new data
        except Exception as e:
            print(f"An error occurred {e}")
            raise e
    print(f"Successfully processed {len(event['Records'])} records.")
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_python_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で DynamoDB イベントの消費。  

```
import json

def lambda_handler(event, context):
    print(json.dumps(event, indent=2))

    for record in event['Records']:
        log_dynamodb_record(record)

def log_dynamodb_record(record):
    print(record['eventID'])
    print(record['eventName'])
    print(f"DynamoDB Record: {json.dumps(record['dynamodb'])}")
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_python_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
import json

def lambda_handler(event, context):
    for record in event.get('events', []):
        log_document_db_event(record)
    return 'OK'

def log_document_db_event(record):
    event_data = record.get('event', {})
    operation_type = event_data.get('operationType', 'Unknown')
    db = event_data.get('ns', {}).get('db', 'Unknown')
    collection = event_data.get('ns', {}).get('coll', 'Unknown')
    full_document = event_data.get('fullDocument', {})

    print(f"Operation type: {operation_type}")
    print(f"db: {db}")
    print(f"collection: {collection}")
    print("Full document:", json.dumps(full_document, indent=2))
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_python_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での Amazon MSK イベントの消費。  

```
import base64

def lambda_handler(event, context):
    # Iterate through keys
    for key in event['records']:
        print('Key:', key)
        # Iterate through records
        for record in event['records'][key]:
            print('Record:', record)
            # Decode base64
            msg = base64.b64decode(record['value']).decode('utf-8')
            print('Message:', msg)
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_python_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Python を使用して Lambda で S3 イベントを消費します。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import urllib.parse
import boto3

print('Loading function')

s3 = boto3.client('s3')


def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        print("CONTENT TYPE: " + response['ContentType'])
        return response['ContentType']
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_python_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で SNS イベントを消費します。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event, context):
    for record in event['Records']:
        process_message(record)
    print("done")

def process_message(record):
    try:
        message = record['Sns']['Message']
        print(f"Processed message {message}")
        # TODO; Process your record here
        
    except Exception as e:
        print("An error occurred")
        raise e
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_python_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での SQS イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event, context):
    for message in event['Records']:
        process_message(message)
    print("done")

def process_message(message):
    try:
        print(f"Processed message {message['body']}")
        # TODO: Do interesting work based on the new message
    except Exception as err:
        print("An error occurred")
        raise err
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_python_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def handler(event, context):
    records = event.get("Records")
    curRecordSequenceNumber = ""
    
    for record in records:
        try:
            # Process your record
            curRecordSequenceNumber = record["kinesis"]["sequenceNumber"]
        except Exception as e:
            # Return failed record's sequence number
            return {"batchItemFailures":[{"itemIdentifier": curRecordSequenceNumber}]}

    return {"batchItemFailures":[]}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_python_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def handler(event, context):
    records = event.get("Records")
    curRecordSequenceNumber = ""
    
    for record in records:
        try:
            # Process your record
            curRecordSequenceNumber = record["dynamodb"]["SequenceNumber"]
        except Exception as e:
            # Return failed record's sequence number
            return {"batchItemFailures":[{"itemIdentifier": curRecordSequenceNumber}]}

    return {"batchItemFailures":[]}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_python_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

def lambda_handler(event, context):
    if event:
        batch_item_failures = []
        sqs_batch_response = {}
     
        for record in event["Records"]:
            try:
                print(f"Processed message: {record['body']}")
            except Exception as e:
                batch_item_failures.append({"itemIdentifier": record['messageId']})
        
        sqs_batch_response["batchItemFailures"] = batch_item_failures
        return sqs_batch_response
```

# SDK for Python (Boto3) を使用したマネージドサービスの例
<a name="python_3_kinesis-analytics-v2_code_examples"></a>

次のコード例は、 Managed Service for Apache Flink AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [データジェネレーター](#data_generator)

## アクション
<a name="actions"></a>

### `AddApplicationInput`
<a name="kinesis-analytics-v2_AddApplicationInput_python_3_topic"></a>

次のコード例は、`AddApplicationInput` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def add_input(self, input_prefix, stream_arn, input_schema):
        """
        Adds an input stream to the application. The input stream data is mapped
        to an in-application stream that can be processed by your code running in
        Kinesis Data Analytics.

        :param input_prefix: The prefix prepended to in-application input stream names.
        :param stream_arn: The ARN of the input stream.
        :param input_schema: A schema that maps the data in the input stream to the
                             runtime environment. This can be automatically generated
                             by using `discover_input_schema` or you can create it
                             yourself.
        :return: Metadata about the newly added input.
        """
        try:
            response = self.analytics_client.add_application_input(
                ApplicationName=self.name,
                CurrentApplicationVersionId=self.version_id,
                Input={
                    "NamePrefix": input_prefix,
                    "KinesisStreamsInput": {"ResourceARN": stream_arn},
                    "InputSchema": input_schema,
                },
            )
            self.version_id = response["ApplicationVersionId"]
            logger.info("Add input stream %s to application %s.", stream_arn, self.name)
        except ClientError:
            logger.exception(
                "Couldn't add input stream %s to application %s.", stream_arn, self.name
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AddApplicationInput](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/AddApplicationInput)」を参照してください。

### `AddApplicationOutput`
<a name="kinesis-analytics-v2_AddApplicationOutput_python_3_topic"></a>

次のコード例は、`AddApplicationOutput` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def add_output(self, in_app_stream_name, output_arn):
        """
        Adds an output stream to the application. Kinesis Data Analytics maps data
        from the specified in-application stream to the output stream.

        :param in_app_stream_name: The name of the in-application stream to map
                                   to the output stream.
        :param output_arn: The ARN of the output stream.
        :return: A list of metadata about the output resources currently assigned
                 to the application.
        """
        try:
            response = self.analytics_client.add_application_output(
                ApplicationName=self.name,
                CurrentApplicationVersionId=self.version_id,
                Output={
                    "Name": in_app_stream_name,
                    "KinesisStreamsOutput": {"ResourceARN": output_arn},
                    "DestinationSchema": {"RecordFormatType": "JSON"},
                },
            )
            outputs = response["OutputDescriptions"]
            self.version_id = response["ApplicationVersionId"]
            logging.info(
                "Added output %s to %s, which now has %s outputs.",
                output_arn,
                self.name,
                len(outputs),
            )
        except ClientError:
            logger.exception("Couldn't add output %s to %s.", output_arn, self.name)
            raise
        else:
            return outputs
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AddApplicationOutput](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/AddApplicationOutput)」を参照してください。

### `CreateApplication`
<a name="kinesis-analytics-v2_CreateApplication_python_3_topic"></a>

次のコード例は、`CreateApplication` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def create(self, app_name, role_arn, env="SQL-1_0"):
        """
        Creates a Kinesis Data Analytics application.

        :param app_name: The name of the application.
        :param role_arn: The ARN of a role that can be assumed by Kinesis Data
                         Analytics and grants needed permissions.
        :param env: The runtime environment of the application, such as SQL. Code
                    uploaded to the application runs in this environment.
        :return: Metadata about the newly created application.
        """
        try:
            response = self.analytics_client.create_application(
                ApplicationName=app_name,
                RuntimeEnvironment=env,
                ServiceExecutionRole=role_arn,
            )
            details = response["ApplicationDetail"]
            self._update_details(details)
            logger.info("Application %s created.", app_name)
        except ClientError:
            logger.exception("Couldn't create application %s.", app_name)
            raise
        else:
            return details
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」**の「[CreateApplication](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/CreateApplication)」を参照してください。

### `DeleteApplication`
<a name="kinesis-analytics-v2_DeleteApplication_python_3_topic"></a>

次のコード例は、`DeleteApplication` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def delete(self):
        """
        Deletes an application.
        """
        try:
            self.analytics_client.delete_application(
                ApplicationName=self.name, CreateTimestamp=self.create_timestamp
            )
            logger.info("Deleted application %s.", self.name)
        except ClientError:
            logger.exception("Couldn't delete application %s.", self.name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteApplication](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/DeleteApplication)」を参照してください。

### `DescribeApplication`
<a name="kinesis-analytics-v2_DescribeApplication_python_3_topic"></a>

次のコード例は、`DescribeApplication` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def describe(self, name):
        """
        Gets metadata about an application.

        :param name: The name of the application to look up.
        :return: Metadata about the application.
        """
        try:
            response = self.analytics_client.describe_application(ApplicationName=name)
            details = response["ApplicationDetail"]
            self._update_details(details)
            logger.info("Got metadata for application %s.", name)
        except ClientError:
            logger.exception("Couldn't get metadata for application %s.", name)
            raise
        else:
            return details
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeApplication](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/DescribeApplication)」を参照してください。

### `DescribeApplicationSnapshot`
<a name="kinesis-analytics-v2_DescribeApplicationSnapshot_python_3_topic"></a>

次のコード例は、`DescribeApplicationSnapshot` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def describe_snapshot(self, application_name, snapshot_name):
        """
        Gets metadata about a previously saved application snapshot.

        :param application_name: The name of the application.
        :param snapshot_name: The name of the snapshot.
        :return: Metadata about the snapshot.
        """
        try:
            response = self.analytics_client.describe_application_snapshot(
                ApplicationName=application_name, SnapshotName=snapshot_name
            )
            snapshot = response["SnapshotDetails"]
            logger.info(
                "Got metadata for snapshot %s of application %s.",
                snapshot_name,
                application_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't get metadata for snapshot %s of application %s.",
                snapshot_name,
                application_name,
            )
            raise
        else:
            return snapshot
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeApplicationSnapshot](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/DescribeApplicationSnapshot)」を参照してください。

### `DiscoverInputSchema`
<a name="kinesis-analytics-v2_DiscoverInputSchema_python_3_topic"></a>

次のコード例は、`DiscoverInputSchema` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def discover_input_schema(self, stream_arn, role_arn):
        """
        Discovers a schema that maps data in a stream to a format that is usable by
        an application's runtime environment. The stream must be active and have
        enough data moving through it for the service to sample. The returned schema
        can be used when you add the stream as an input to the application or you can
        write your own schema.

        :param stream_arn: The ARN of the stream to map.
        :param role_arn: A role that lets Kinesis Data Analytics read from the stream.
        :return: The discovered schema of the data in the input stream.
        """
        try:
            response = self.analytics_client.discover_input_schema(
                ResourceARN=stream_arn,
                ServiceExecutionRole=role_arn,
                InputStartingPositionConfiguration={"InputStartingPosition": "NOW"},
            )
            schema = response["InputSchema"]
            logger.info("Discovered input schema for stream %s.", stream_arn)
        except ClientError:
            logger.exception(
                "Couldn't discover input schema for stream %s.", stream_arn
            )
            raise
        else:
            return schema
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DiscoverInputSchema](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/DiscoverInputSchema)」を参照してください。

### `StartApplication`
<a name="kinesis-analytics-v2_StartApplication_python_3_topic"></a>

次のコード例は、`StartApplication` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def start(self, input_id):
        """
        Starts an application. After the application is running, it reads from the
        specified input stream and runs the application code on the incoming data.

        :param input_id: The ID of the input to read.
        """
        try:
            self.analytics_client.start_application(
                ApplicationName=self.name,
                RunConfiguration={
                    "SqlRunConfigurations": [
                        {
                            "InputId": input_id,
                            "InputStartingPositionConfiguration": {
                                "InputStartingPosition": "NOW"
                            },
                        }
                    ]
                },
            )
            logger.info("Started application %s.", self.name)
        except ClientError:
            logger.exception("Couldn't start application %s.", self.name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartApplication](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/StartApplication)」を参照してください。

### `StopApplication`
<a name="kinesis-analytics-v2_StopApplication_python_3_topic"></a>

次のコード例は、`StopApplication` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def stop(self):
        """
        Stops an application. This stops the application from processing data but
        does not delete any resources.
        """
        try:
            self.analytics_client.stop_application(ApplicationName=self.name)
            logger.info("Stopping application %s.", self.name)
        except ClientError:
            logger.exception("Couldn't stop application %s.", self.name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StopApplication](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/StopApplication)」を参照してください。

### `UpdateApplication`
<a name="kinesis-analytics-v2_UpdateApplication_python_3_topic"></a>

次のコード例は、`UpdateApplication` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis-analytics-v2#code-examples)での設定と実行の方法を確認してください。
この例は、既存のアプリケーションで実行されるコードを更新します。  

```
class KinesisAnalyticsApplicationV2:
    """Encapsulates Kinesis Data Analytics application functions."""

    def __init__(self, analytics_client):
        """
        :param analytics_client: A Boto3 Kinesis Data Analytics v2 client.
        """
        self.analytics_client = analytics_client
        self.name = None
        self.arn = None
        self.version_id = None
        self.create_timestamp = None


    def update_code(self, code):
        """
        Updates the code that runs in the application. The code must run in the
        runtime environment of the application, such as SQL. Application code
        typically reads data from in-application streams and transforms it in some way.

        :param code: The code to upload. This completely replaces any existing code
                     in the application.
        :return: Metadata about the application.
        """
        try:
            response = self.analytics_client.update_application(
                ApplicationName=self.name,
                CurrentApplicationVersionId=self.version_id,
                ApplicationConfigurationUpdate={
                    "ApplicationCodeConfigurationUpdate": {
                        "CodeContentTypeUpdate": "PLAINTEXT",
                        "CodeContentUpdate": {"TextContentUpdate": code},
                    }
                },
            )
            details = response["ApplicationDetail"]
            self.version_id = details["ApplicationVersionId"]
            logger.info("Update code for application %s.", self.name)
        except ClientError:
            logger.exception("Couldn't update code for application %s.", self.name)
            raise
        else:
            return details
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateApplication](https://docs.aws.amazon.com/goto/boto3/kinesisanalyticsv2-2018-05-23/UpdateApplication)」を参照してください。

## データジェネレーター
<a name="data_generator"></a>

### リファラーを使用してストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_Referrer_python_3_topic"></a>

次のコード例は、リファラーで Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import json
import boto3

STREAM_NAME = "ExampleInputStream"


def get_data():
    return {"REFERRER": "http://www.amazon.com"}


def generate(stream_name, kinesis_client):
    while True:
        data = get_data()
        print(data)
        kinesis_client.put_record(
            StreamName=stream_name, Data=json.dumps(data), PartitionKey="partitionkey"
        )


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### 血圧異常でストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_AnomalyEx_python_3_topic"></a>

次のコード例は、血圧異常で Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
from enum import Enum
import json
import random
import boto3

STREAM_NAME = "ExampleInputStream"


class PressureType(Enum):
    low = "LOW"
    normal = "NORMAL"
    high = "HIGH"


def get_blood_pressure(pressure_type):
    pressure = {"BloodPressureLevel": pressure_type.value}
    if pressure_type == PressureType.low:
        pressure["Systolic"] = random.randint(50, 80)
        pressure["Diastolic"] = random.randint(30, 50)
    elif pressure_type == PressureType.normal:
        pressure["Systolic"] = random.randint(90, 120)
        pressure["Diastolic"] = random.randint(60, 80)
    elif pressure_type == PressureType.high:
        pressure["Systolic"] = random.randint(130, 200)
        pressure["Diastolic"] = random.randint(90, 150)
    else:
        raise TypeError
    return pressure


def generate(stream_name, kinesis_client):
    while True:
        rnd = random.random()
        pressure_type = (
            PressureType.low
            if rnd < 0.005
            else PressureType.high
            if rnd > 0.995
            else PressureType.normal
        )
        blood_pressure = get_blood_pressure(pressure_type)
        print(blood_pressure)
        kinesis_client.put_record(
            StreamName=stream_name,
            Data=json.dumps(blood_pressure),
            PartitionKey="partitionkey",
        )


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### 列のデータでストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_ColumnLog_python_3_topic"></a>

次のコード例は、列のデータで Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import json
import boto3

STREAM_NAME = "ExampleInputStream"


def get_data():
    return {"Col_A": "a", "Col_B": "b", "Col_C": "c", "Col_E_Unstructured": "x,y,z"}


def generate(stream_name, kinesis_client):
    while True:
        data = get_data()
        print(data)
        kinesis_client.put_record(
            StreamName=stream_name, Data=json.dumps(data), PartitionKey="partitionkey"
        )


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### 心拍数異常でストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_Anomaly_python_3_topic"></a>

次のコード例は、心拍数異常で Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
from enum import Enum
import json
import random
import boto3

STREAM_NAME = "ExampleInputStream"


class RateType(Enum):
    normal = "NORMAL"
    high = "HIGH"


def get_heart_rate(rate_type):
    if rate_type == RateType.normal:
        rate = random.randint(60, 100)
    elif rate_type == RateType.high:
        rate = random.randint(150, 200)
    else:
        raise TypeError
    return {"heartRate": rate, "rateType": rate_type.value}


def generate(stream_name, kinesis_client, output=True):
    while True:
        rnd = random.random()
        rate_type = RateType.high if rnd < 0.01 else RateType.normal
        heart_rate = get_heart_rate(rate_type)
        if output:
            print(heart_rate)
        kinesis_client.put_record(
            StreamName=stream_name,
            Data=json.dumps(heart_rate),
            PartitionKey="partitionkey",
        )


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### ホットスポットでストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_Hotspots_python_3_topic"></a>

次のコード例は、ホットスポットで Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import json
from pprint import pprint
import random
import time
import boto3

STREAM_NAME = "ExampleInputStream"


def get_hotspot(field, spot_size):
    hotspot = {
        "left": field["left"] + random.random() * (field["width"] - spot_size),
        "width": spot_size,
        "top": field["top"] + random.random() * (field["height"] - spot_size),
        "height": spot_size,
    }
    return hotspot


def get_record(field, hotspot, hotspot_weight):
    rectangle = hotspot if random.random() < hotspot_weight else field
    point = {
        "x": rectangle["left"] + random.random() * rectangle["width"],
        "y": rectangle["top"] + random.random() * rectangle["height"],
        "is_hot": "Y" if rectangle is hotspot else "N",
    }
    return {"Data": json.dumps(point), "PartitionKey": "partition_key"}


def generate(
    stream_name, field, hotspot_size, hotspot_weight, batch_size, kinesis_client
):
    """
    Generates points used as input to a hotspot detection algorithm.
    With probability hotspot_weight (20%), a point is drawn from the hotspot;
    otherwise, it is drawn from the base field. The location of the hotspot
    changes for every 1000 points generated.
    """
    points_generated = 0
    hotspot = None
    while True:
        if points_generated % 1000 == 0:
            hotspot = get_hotspot(field, hotspot_size)
        records = [
            get_record(field, hotspot, hotspot_weight) for _ in range(batch_size)
        ]
        points_generated += len(records)
        pprint(records)
        kinesis_client.put_records(StreamName=stream_name, Records=records)

        time.sleep(0.1)


if __name__ == "__main__":
    generate(
        stream_name=STREAM_NAME,
        field={"left": 0, "width": 10, "top": 0, "height": 10},
        hotspot_size=1,
        hotspot_weight=0.2,
        batch_size=10,
        kinesis_client=boto3.client("kinesis"),
    )
```

### ログエントリでストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_RegexLog_python_3_topic"></a>

次のコード例は、ログエントリで Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import json
import boto3

STREAM_NAME = "ExampleInputStream"


def get_data():
    return {
        "LOGENTRY": "203.0.113.24 - - [25/Mar/2018:15:25:37 -0700] "
        '"GET /index.php HTTP/1.1" 200 125 "-" '
        '"Mozilla/5.0 [en] Gecko/20100101 Firefox/52.0"'
    }


def generate(stream_name, kinesis_client):
    while True:
        data = get_data()
        print(data)
        kinesis_client.put_record(
            StreamName=stream_name, Data=json.dumps(data), PartitionKey="partitionkey"
        )


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### スタッガーデータでストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_Stagger_python_3_topic"></a>

次のコード例は、スタッガーデータで Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import datetime
import json
import random
import time
import boto3

STREAM_NAME = "ExampleInputStream"


def get_data():
    event_time = datetime.datetime.utcnow() - datetime.timedelta(seconds=10)
    return {
        "EVENT_TIME": event_time.isoformat(),
        "TICKER": random.choice(["AAPL", "AMZN", "MSFT", "INTC", "TBV"]),
    }


def generate(stream_name, kinesis_client):
    while True:
        data = get_data()
        # Send six records, ten seconds apart, with the same event time and ticker
        for _ in range(6):
            print(data)
            kinesis_client.put_record(
                StreamName=stream_name,
                Data=json.dumps(data),
                PartitionKey="partitionkey",
            )
            time.sleep(10)


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### 株価データでストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_StockTicker_python_3_topic"></a>

次のコード例は、株価データで Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import datetime
import json
import random
import boto3

STREAM_NAME = "ExampleInputStream"


def get_data():
    return {
        "EVENT_TIME": datetime.datetime.now().isoformat(),
        "TICKER": random.choice(["AAPL", "AMZN", "MSFT", "INTC", "TBV"]),
        "PRICE": round(random.random() * 100, 2),
    }


def generate(stream_name, kinesis_client):
    while True:
        data = get_data()
        print(data)
        kinesis_client.put_record(
            StreamName=stream_name, Data=json.dumps(data), PartitionKey="partitionkey"
        )


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### 2 つのデータ型でストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_TwoRecordTypes_python_3_topic"></a>

次のコード例は、2 つのデータ型でストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import json
import random
import boto3

STREAM_NAME = "OrdersAndTradesStream"
PARTITION_KEY = "partition_key"


def get_order(order_id, ticker):
    return {
        "RecordType": "Order",
        "Oid": order_id,
        "Oticker": ticker,
        "Oprice": random.randint(500, 10000),
        "Otype": "Sell",
    }


def get_trade(order_id, trade_id, ticker):
    return {
        "RecordType": "Trade",
        "Tid": trade_id,
        "Toid": order_id,
        "Tticker": ticker,
        "Tprice": random.randint(0, 3000),
    }


def generate(stream_name, kinesis_client):
    order_id = 1
    while True:
        ticker = random.choice(["AAAA", "BBBB", "CCCC"])
        order = get_order(order_id, ticker)
        print(order)
        kinesis_client.put_record(
            StreamName=stream_name, Data=json.dumps(order), PartitionKey=PARTITION_KEY
        )
        for trade_id in range(1, random.randint(0, 6)):
            trade = get_trade(order_id, trade_id, ticker)
            print(trade)
            kinesis_client.put_record(
                StreamName=stream_name,
                Data=json.dumps(trade),
                PartitionKey=PARTITION_KEY,
            )
        order_id += 1


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

### Web ログデータでストリームを生成する
<a name="kinesis-analytics-v2_DataGenerator_WebLog_python_3_topic"></a>

次のコード例は、Web ログデータを使用して Kinesis ストリームを生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/kinesis#code-examples)での設定と実行の方法を確認してください。

```
import json
import boto3

STREAM_NAME = "ExampleInputStream"


def get_data():
    return {
        "log": "192.168.254.30 - John [24/May/2004:22:01:02 -0700] "
        '"GET /icons/apache_pb.gif HTTP/1.1" 304 0'
    }


def generate(stream_name, kinesis_client):
    while True:
        data = get_data()
        print(data)
        kinesis_client.put_record(
            StreamName=stream_name, Data=json.dumps(data), PartitionKey="partitionkey"
        )


if __name__ == "__main__":
    generate(STREAM_NAME, boto3.client("kinesis"))
```

# AWS Marketplace SDK for Python (Boto3) を使用したカタログ API の例
<a name="python_3_marketplace-catalog_code_examples"></a>

次のコード例は、 AWS Marketplace Catalog API AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [AMI 製品](#ami_products)
+ [チャネルパートナーのオファー](#channel_partner_offers)
+ [コンテナ製品](#container_products)
+ [エンティティ](#entities)
+ [Offers](#offers)
+ [製品](#products)
+ [再販承認](#resale_authorization)
+ [SaaS 製品](#saas_products)
+ [Utilities](#utilities)

## AMI 製品
<a name="ami_products"></a>

### 既存の AMI 製品にディメンションを追加し、オファーの料金条件を更新する
<a name="marketplace-catalog_AddDimensionToAmiProductAndSetPriceInPublicOffer_python_3_topic"></a>

次のコード例は、既存の AMI 製品にディメンションを追加し、オファーの料金条件を更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Identifier": "prod-1111111111111",
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": [
                {
                    "Key": "m7g.8xlarge",
                    "Description": "m7g.8xlarge",
                    "Name": "m7g.8xlarge",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "m5.large",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "m7g.4xlarge",
                                        "Price": "0.45"
                                    },
                                    {
                                        "DimensionKey": "m7g.2xlarge",
                                        "Price": "0.45"
                                    },
                                    {
                                        "DimensionKey": "m7g.8xlarge",
                                        "Price": "0.55"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to add a dimension to an existing AMI product and update the offer pricing terms.
CAPI-23
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Add dimension for AMI product")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### AMI 製品をデプロイするリージョンを追加する
<a name="marketplace-catalog_AddRegionExistingAmiProduct_python_3_topic"></a>

次のコード例は、AMI 製品をデプロイするリージョンを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-2",
                    "us-west-2"
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to add a region where my
AMI product is deployed
CAPI-25A
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Add a region where my AMI product is deployed",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックまたは制限付き AMI 製品と、時間単位の年間料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedAmiProductAndPublicOfferWithHourlyAnnualPricing_python_3_topic"></a>

次のコード例は、パブリックまたは制限付き AMI 製品と、時間単位の年間料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Operating Systems"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-1"
                ]
            }
        },
        {
            "ChangeType": "AddInstanceTypes",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "InstanceTypes": [
                    "t2.micro"
                ]
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Version": {
                    "VersionTitle": "Test AMI Version1.0",
                    "ReleaseNotes": "Test AMI Version"
                },
                "DeliveryOptions": [
                    {
                        "Details": {
                            "AmiDeliveryOptionDetails": {
                                "AmiSource": {
                                    "AmiId": "ami-11111111111111111",
                                    "AccessRoleArn": "arn:aws:iam::111111111111:role/AWSMarketplaceAmiIngestion",
                                    "UserName": "ec2-user",
                                    "OperatingSystemName": "AMAZONLINUX",
                                    "OperatingSystemVersion": "10.0.14393",
                                    "ScanningPort": 22
                                },
                                "UsageInstructions": "Test AMI Version",
                                "RecommendedInstanceType": "t2.micro",
                                "SecurityGroups": [
                                    {
                                        "IpProtocol": "tcp",
                                        "IpRanges": [
                                            "0.0.0.0/0"
                                        ],
                                        "FromPort": 10,
                                        "ToPort": 22
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "t2.micro",
                    "Description": "t2.micro",
                    "Name": "t2.micro",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with hourly-annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P365D"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a public or limited AMI
product and public offer with hourly-annual pricing and standard or custom EULA
CAPI-06
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create limited AMI product and public offer with hourly-annual pricing and standard EULA",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックまたは制限付き AMI 製品と、時間単位の月額料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedAmiProductAndPublicOfferWithHourlyMonthlyPricing_python_3_topic"></a>

次のコード例は、パブリックまたは制限付き AMI 製品と、時間単位の月額料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Operating Systems"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-1"
                ]
            }
        },
        {
            "ChangeType": "AddInstanceTypes",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "InstanceTypes": [
                    "t2.micro"
                ]
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Version": {
                    "VersionTitle": "Test AMI Version1.0",
                    "ReleaseNotes": "Test AMI Version"
                },
                "DeliveryOptions": [
                    {
                        "Details": {
                            "AmiDeliveryOptionDetails": {
                                "AmiSource": {
                                    "AmiId": "ami-11111111111111111",
                                    "AccessRoleArn": "arn:aws:iam::111111111111:role/AWSMarketplaceAmiIngestion",
                                    "UserName": "ec2-user",
                                    "OperatingSystemName": "AMAZONLINUX",
                                    "OperatingSystemVersion": "10.0.14393",
                                    "ScanningPort": 22
                                },
                                "UsageInstructions": "Test AMI Version",
                                "RecommendedInstanceType": "t2.micro",
                                "SecurityGroups": [
                                    {
                                        "IpProtocol": "tcp",
                                        "IpRanges": [
                                            "0.0.0.0/0"
                                        ],
                                        "FromPort": 10,
                                        "ToPort": 22
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "t2.micro",
                    "Description": "t2.micro",
                    "Name": "t2.micro",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with hourly-monthly pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "RecurringPaymentTerm",
                        "CurrencyCode": "USD",
                        "BillingPeriod": "Monthly",
                        "Price": "15.0"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a public or limited AMI
product and public offer with hourly-monthly pricing and standard or custom EULA
CAPI-08
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "create limited AMI product and public offer with hourly-monthly pricing and standard EULA",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックまたは制限付き AMI 製品と、時間単位の料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedAmiProductAndPublicOfferWithHourlyPricing_python_3_topic"></a>

次のコード例は、パブリックまたは制限付き AMI 製品と、時間単位の料金でパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Operating Systems"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-east-1"
                ]
            }
        },
        {
            "ChangeType": "AddInstanceTypes",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "InstanceTypes": [
                    "t2.micro"
                ]
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Version": {
                    "VersionTitle": "Test AMI Version1.0",
                    "ReleaseNotes": "Test AMI Version"
                },
                "DeliveryOptions": [
                    {
                        "Details": {
                            "AmiDeliveryOptionDetails": {
                                "AmiSource": {
                                    "AmiId": "ami-11111111111111111",
                                    "AccessRoleArn": "arn:aws:iam::111111111111:role/AWSMarketplaceAmiIngestion",
                                    "UserName": "ec2-user",
                                    "OperatingSystemName": "AMAZONLINUX",
                                    "OperatingSystemVersion": "10.0.14393",
                                    "ScanningPort": 22
                                },
                                "UsageInstructions": "Test AMI Version",
                                "RecommendedInstanceType": "t2.micro",
                                "SecurityGroups": [
                                    {
                                        "IpProtocol": "tcp",
                                        "IpRanges": [
                                            "0.0.0.0/0"
                                        ],
                                        "FromPort": 10,
                                        "ToPort": 22
                                    }
                                ]
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "t2.micro",
                    "Description": "t2.micro",
                    "Name": "t2.micro",
                    "Types": [
                        "Metered"
                    ],
                    "Unit": "Hrs"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with hourly pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to Create a public or limited AMI product
and public offer with hourly pricing and standard or custom EULA
CAPI-07
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create limited AMI product and public offer with hourly pricing and standard EULA",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### ドラフトパブリックオファーを使用してドラフト AMI 製品を作成する
<a name="marketplace-catalog_CreateDraftAmiProductWithDraftPublicOffer_python_3_topic"></a>

次のコード例は、ドラフトパブリックオファーを使用してドラフト AMI 製品を作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "AmiProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier",
                "Name": "Test Offer"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create an AMI draft product
with a draft public offer.
CAPI-02
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "AMI draft product with draft public offer",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### AMI 製品をデプロイするリージョンを制限する
<a name="marketplace-catalog_RestrictRegionExistingAmiProduct_python_3_topic"></a>

次のコード例は、AMI 製品をデプロイするリージョンを制限する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "RestrictRegions",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "Regions": [
                    "us-west-2"
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to restrict a region where my
AMI product is deployed
CAPI-25B
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Add a region where my AMI product is deployed",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 製品の可視性を制限する
<a name="marketplace-catalog_RestrictExistingAmi_python_3_topic"></a>

次のコード例は、製品の可視性を制限する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateVisibility",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "TargetVisibility": "Restricted"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to change a product visibility to restricted
CAPI-17
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Restrict existing AMI")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### AMI アセットを新しいリージョンにデプロイするかどうかを指定する
<a name="marketplace-catalog_UpdateFutureRegionSupport_python_3_topic"></a>

次のコード例は、将来のリージョンをサポートするために によって構築された新しいリージョン AWS に AMI アセットをデプロイするかどうかを指定する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateFutureRegionSupport",
            "Entity": {
                "Type": "AmiProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": {
                "FutureRegionSupport": {
                    "SupportedRegions": [
                        "All"
                    ]
                }
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to modify a product to support all future regions
CAPI-26
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update future region support")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

## チャネルパートナーのオファー
<a name="channel_partner_offers"></a>

### 任意の製品タイプのドラフト CPPO を作成する
<a name="marketplace-catalog_CreateDraftCppoOffer_python_3_topic"></a>

次のコード例は、任意の製品タイプのドラフト CPPO を作成し、購入者に公開する前に内部で確認できるようにする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOfferUsingResaleAuthorization",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ResaleAuthorizationId": "11111111-1111-1111-1111-111111111111",
                "Name": "Test Offer name"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create “draft” CPPO
for any product type (AMI/SaaS/Container) that can be reviewed internally
before publishing to buyers
CAPI-60
"""
import os

import utils.start_changeset as sc  # noqa: E402
import utils.stringify_details as sd  # noqa: E402

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Create a draft CPPO offer for a product")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 契約料金を使用する再販承認の代替プライベートオファーを作成する
<a name="marketplace-catalog_CreateResaleAuthorizationReplacementOffer_python_3_topic"></a>

次のコード例は、既存の契約から契約料金を使用する再販承認代替プライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateReplacementOfferUsingResaleAuthorization",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateReplacementOfferResaleAuth",
            "DetailsDocument": {
                "AgreementId": "agmt-1111111111111111111111111",
                "ResaleAuthorizationId": "resaleauthz-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test replacement offer for SaaSProduct using AWS Marketplace API Reference Codes",
                "Description": "Test private resale replacement offer with contract pricing for SaaSProduct"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Duration": "P12M",
                        "Grants": [
                            {
                                "DimensionKey": "BasicService",
                                "MaxQuantity": 2
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementEndDate": "2024-01-30"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "0"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOfferResaleAuth.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a resale authorization replacement private offer
from an existing agreement with contract pricing
CAPI-96
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create resale authorization replacement private offer with contract pricing",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### チャネルパートナーが作成したすべての CPPO を一覧表示する
<a name="marketplace-catalog_ListAllCppoOffers_python_3_topic"></a>

次のコード例は、チャネルパートナーが作成したすべての CPPO を一覧表示する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to list all Channel Partner Offers
in an account

Program executed with no arguments:
ie. python3 list_all_cppo_offers.py

CAPI-93
"""

import json
import logging

import boto3
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-catalog")


def get_offer_entities():
    """
    Returns a list of all offers in the account
    """

    next_token = ""  # nosec: B105
    response_list = []

    try:
        response = mp_client.list_entities(Catalog="AWSMarketplace", EntityType="Offer")
    except ClientError as e:
        logging.exception(f"Couldn't list entities. {e}")
        raise

    response_list.append(response)

    # Results are paginated depending on number of entities returned
    while "NextToken" in response:
        next_token = response["NextToken"]

        try:
            response = mp_client.list_entities(
                Catalog="AWSMarketplace",
                EntityType="Offer",
                NextToken=next_token,
            )
        except ClientError as e:
            logging.exception(f"Couldn't list entities. {e}")
            raise

        if "NextToken" in response:
            response_list.append(response)

    return response_list


def build_offer_list(response_list):
    """
    Cleans up list_entities response list with just list of offer IDs
    """
    offer_list = []

    for response in response_list:
        for entity in response["EntitySummaryList"]:
            offer_list.append(entity["EntityId"])

    return offer_list


def check_offer_resaleauth(offer_id):
    """
    Checks to see if an offer is based on a resale authorization
    """
    offer_response = describe_entity(offer_id)
    offer_details = json.loads(offer_response["Details"])
    if offer_details is None:
        offer_details = offer_response["DetailsDocument"]
    if "ResaleAuthorizationId" in offer_details and offer_details["ResaleAuthorizationId"] is not None:
        return offer_id
    else:
        return None


def describe_entity(entity_id):
    """
    General purpose describe entity call
    """
    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace",
            EntityId=entity_id,
        )
    except ClientError as e:
        logging.exception(f"Couldn't describe entity. {e}")
        raise

    return response


def get_resaleauth_offers():
    """
    Returns a list of all offers in the account that are
    based on a resale authorization
    """
    resale_offer_list = []

    response_list = get_offer_entities()
    offer_list = build_offer_list(response_list)
    for offer in offer_list:
        print ("offer id " + offer)
        offer_info = check_offer_resaleauth(offer)
        if offer_info is not None:
            resale_offer_list.append(offer_info)

    return resale_offer_list


if __name__ == "__main__":
    print(get_resaleauth_offers())
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListEntities](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/ListEntities)」を参照してください。**

### チャネルパートナーが利用できるすべての共有再販承認を一覧表示する
<a name="marketplace-catalog_ListAllSharedResaleAuthorizations_python_3_topic"></a>

次のコード例は、チャネルパートナーが利用できるすべての共有再販承認を一覧表示する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to list all resale authorizations
shared to an account

Program executed with no arguments:
ie. python3 list_all_resale_authorizations.py

CAPI-94
"""

import logging

import boto3
import utils.helpers as hlp  # noqa: E402
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-catalog")


def get_shared_entities():
    next_token = ""  # nosec: B105
    response_list = []

    try:
        response = mp_client.list_entities(
            Catalog="AWSMarketplace",
            EntityType="ResaleAuthorization",
            OwnershipType="SHARED",
        )
    except ClientError as e:
        logging.exception(f"Couldn't list entities. {e}")
        raise

    response_list.append(response)

    # Results can be paginated depending on number of entities returned
    while "NextToken" in response:
        next_token = response["NextToken"]

        try:
            response = mp_client.list_entities(
                Catalog="AWSMarketplace",
                EntityType="ResaleAuthorization",
                OwnershipType="SHARED",
                NextToken=next_token,
            )
        except ClientError as e:
            logging.exception(f"Couldn't list entities. {e}")
            raise

        if "NextToken" in response:
            response_list.append(response)

    return response_list


if __name__ == "__main__":
    response_list = get_shared_entities()
    hlp.pretty_print_datetime(response_list)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListEntities](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/ListEntities)」を参照してください。**

### CPPO を発行し、購入者の EULA を追加する
<a name="marketplace-catalog_PublishCppoEula_python_3_topic"></a>

次のコード例は、CPPO を発行し、購入者の EULA を追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateOfferUsingResaleAuthorization",
            "Entity": {
            "Type": "Offer@1.0"
            },
            "ChangeName": "CreateCPPOoffer",
            "DetailsDocument": {
                "ResaleAuthorizationId":"resaleauthz-1111111111111", 
                "Name": "Test Offer",
                "Description":"Test product"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
        			{			
            			"Type": "LegalTerm",
            			"Documents": [
            				{
            					"Type": "CustomEula", 
            					"Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
            				}
            			]
        			}
    			]
        	}
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": ["222222222222"]
                    }
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-07-31"
                }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P450D"
                    }
                ]
             }
        },
        { 
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPOoffer.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to publish CPPO
for any product type (AMI/SaaS/Container) and append buyer EULA
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Publish CPPO for any product type and append buyer EULA",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 1 回限りの再販承認を使用して CPPO を発行し、価格マークアップを更新する
<a name="marketplace-catalog_PublishOneTimeCppoWithPriceMarkup_python_3_topic"></a>

次のコード例は、AMI、SaaS、またはコンテナ製品の 1 回限りの再販売認可を使用して CPPO を発行し、価格マークアップを更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateOfferUsingResaleAuthorization",
            "Entity": {
            "Type": "Offer@1.0"
            },
            "ChangeName": "CreateCPPO",
            "DetailsDocument": {
                "ResaleAuthorizationId":"resaleauthz-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test Offer name",
                "Description":"Test Offer description"
            }
        },
        {
            "ChangeType": "UpdateMarkup",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "Percentage" : "5.0"
        }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": ["111111111111"]
                    }
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
                }
        },
        {
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to Create CPPO using one-time resale
authorization on AMI, SaaS or Container products and update price markup
CAPI-63
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create CPPO using one-time resale authorization and update price markup"
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### ドラフト CPPO を発行し、価格マークアップを更新する
<a name="marketplace-catalog_PublishCppoPriceMarkup_python_3_topic"></a>

次のコード例は、CPPO ドラフトを発行し、価格マークアップを更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateOfferUsingResaleAuthorization",
            "Entity": {
            "Type": "Offer@1.0"
            },
            "ChangeName": "CreateCPPO",
            "DetailsDocument": {
                "ResaleAuthorizationId":"resaleauthz-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test Offer name",
                "Description":"Test Offer description"
            }
        },
        {
            "ChangeType": "UpdateMarkup",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "Percentage" : "5.0"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": ["111111111111"]
                    }
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
                }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P450D"
                    }
                ]
             }
        },
        {
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateCPPO.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to publish “draft” CPPO
for any product type (AMI/SaaS/Container) and update price markup
CAPI-72
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Publish draft CPPO for any product type adn update price markup"
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### CPPO の有効期限を更新する
<a name="marketplace-catalog_UpdateCppoExpiryDate_python_3_topic"></a>

次のコード例は、CPPO の有効期限を更新して、購入者がオファーを評価して承諾する時間を延長する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2025-07-31"
                }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update the expiry
date of a CPPO offer
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Update the expiry date of a CPPO offer"
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

## コンテナ製品
<a name="container_products"></a>

### ドラフトパブリックオファーを使用するドラフトコンテナ製品を作成する
<a name="marketplace-catalog_CreateDraftContainerProductWithDraftPublicOffer_python_3_topic"></a>

次のコード例は、ドラフトパブリックオファーを使用するドラフトコンテナ製品を作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog":"AWSMarketplace",
    "ChangeSet":[
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "ContainerProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier",
                "Name": "Test Offer"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create an container draft product
with a draft public offer.
CAPI-03
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create a draft container product with a draft public offer",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックオファーと契約料金を使用する限定コンテナ製品を作成する
<a name="marketplace-catalog_CreateLimitedContainerProductPublicOffer_python_3_topic"></a>

次のコード例は、パブリックオファー、契約料金、標準 EULA を使用する限定コンテナ製品を作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "ContainerProduct@1.0"
            },
            "DetailsDocument": {},
            "ChangeName": "CreateProductChange"
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "Categories": [
                    "Streaming solutions"
                ],
                "ProductTitle": "ContainerProduct",
                "AdditionalResources": [],
                "LongDescription": "Long description goes here",
                "SearchKeywords": [
                    "container streaming"
                ],
                "ShortDescription": "Description1",
                "Highlights": [
                    "Highlight 1",
                    "Highlight 2"
                ],
                "SupportDescription": "No support available",
                "VideoUrls": []
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "Cores",
                    "Description": "Cores per cluster",
                    "Name": "Cores",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddRepositories",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Repositories": [
                    {
                        "RepositoryName": "uniquerepositoryname",
                        "RepositoryType": "ECR"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "ContainerProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            },
            "ChangeName": "CreateOfferChange"
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "Constraints": {
                                    "MultipleDimensionSelection": "Disallowed",
                                    "QuantityConfiguration": "Disallowed"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "Cores",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "No refunds"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Some container offer Name",
                "Description": "Some interesting container offer description"
            }
        },
        {
            "ChangeType": "UpdateRenewalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "RenewalTerm"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create limited container
product with public offer, contract pricing and standard EULA
CAPI-15
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create limited container product with public offer contract pricing and standard EULA",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

## エンティティ
<a name="entities"></a>

### 1 回の呼び出しですべてのエンティティを記述する
<a name="marketplace-catalog_BatchDescribeEntities_python_3_topic"></a>

次のコード例は、1 回の呼び出しですべてのエンティティを記述する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to describe for multiple entities information in the AWS Marketplace Catalog
CAPI-98
"""

import json
import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

PRODUCT_ID = "prod-1111111111111"
OFFER_ID = "offer-1111111111111"
MARKETPLACE_CATALOG = "AWSMarketplace"


def pretty_print(response):
    json_object = json.dumps(response, indent=4)
    print(json_object)


def get_entities_information(mp_client):
    """
    Returns information about a given product
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of product information
    """

    entity_request_list_param = [
        {'EntityId': PRODUCT_ID, 'Catalog': MARKETPLACE_CATALOG},
        {'EntityId': OFFER_ID, 'Catalog': MARKETPLACE_CATALOG}
    ]
    try:
        response = mp_client.batch_describe_entities(
            EntityRequestList=entity_request_list_param
        )

        return response

    except ClientError as e:
        logger.exception("Unexpected error: %s", e)
        raise


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for entities in the AWS Marketplace Catalog.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-catalog")

    response = get_entities_information(mp_client)
    print("Successful entities response -")
    pretty_print(response["EntityDetails"])
    print("Failed entities response -")
    pretty_print(response["Errors"])


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[BatchDescribeEntities](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/BatchDescribeEntities)」を参照してください。

### 製品に関連付けられたすべてのオファーを一覧表示して記述する
<a name="marketplace-catalog_ListProductOffers_python_3_topic"></a>

次のコード例は、製品に関連付けられたすべてのオファーを一覧表示して記述する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to retrieve all offer information
related to a single product
CAPI-97
"""

import argparse
import logging

import boto3
from botocore.exceptions import ClientError
from utils import helpers

logger = logging.getLogger(__name__)

mp_client = boto3.client("marketplace-catalog")


def get_entity_information(entity_id):
    """
    Returns information about a given entity
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of entity information
    """

    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace",
            EntityId=entity_id,
        )

        return response

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Entity with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def list_entity_details(entity_type, entity_id):
    """
    Returns details about a given entity and entity type
    """

    entity_summary_list = []

    # filter will return details for given entity_id with BuyerAccounts targeting
    filter_list_param = {
        'OfferFilters':{
            'ProductId':{
                'ValueList':[entity_id]
            },
            'Targeting': {
                'ValueList': ["BuyerAccounts"]
            }
        }
    }

    try:
        response = mp_client.list_entities(
            Catalog="AWSMarketplace",
            EntityType=entity_type,
            EntityTypeFilters = filter_list_param,
            MaxResults=10
        )

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Entity ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)

    # add results to entity_summary_list
    entity_summary_list.extend(response["EntitySummaryList"])

    # if there are more than 10 offers, paginate through the results
    while "NextToken" in response and response["NextToken"] is not None:
        try:
            response = mp_client.list_entities(
                Catalog="AWSMarketplace",
                EntityType=entity_type,
                EntityTypeFilters = filter_list_param,
                NextToken=response["NextToken"],
                MaxResults=10
            )

        except ClientError as e:
            if e.response["Error"]["Code"] == "ResourceNotFoundException":
                logger.error("Entity ID %s not found.", entity_id)
            else:
                logger.error("Unexpected error: %s", e)

        # add results to entity_summary_list
        entity_summary_list.extend(response["EntitySummaryList"])

        return entity_summary_list

if __name__ == "__main__":
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--entity-id",
        "-eid",
        help="Provide Entity ID corresponding to a product to filter offers on",
        required=True,
    )

    args = parser.parse_args()

    # Gets a offers associated with the entity_id
    response = list_entity_details(
        "Offer",
        entity_id=args.entity_id
    )

    if response: # if response is not empty

        # list_entity_details returns a list of offers
        for offer in response:

            print("-"*128)
            print(f"Terms for Offer ID: {offer['EntityId']}")
            print("-"*128)

            #retrieve offer information for each offer
            entity_information = get_entity_information(offer["EntityId"])

            helpers.pretty_print_datetime(entity_information)

    else:
        print(f"No information found for Entity ID: {args.entity_id}")
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [DescribeEntity](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/DescribeEntity)
  + [ListEntities](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/ListEntities)

## Offers
<a name="offers"></a>

### SaaS 製品のカスタムディメンションを作成し、プライベートオファーを作成する
<a name="marketplace-catalog_CreateSaasProductCustomDimensionAndPrivateOffer_python_3_topic"></a>

次のコード例は、SaaS 製品のカスタムディメンションを作成し、プライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "prod-1111111111111"
            },
            "DetailsDocument": [
                {
                    "Types": [
                        "Entitled"
                    ],
                    "Description": "Custom Pricing 4 w/ terms and coverage to be defined in Private Offer",
                    "Unit": "Units",
                    "Key": "Custom4",
                    "Name": "Custom Pricing 4"
                }
            ]
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            },
            "ChangeName": "CreateOfferChange"
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Private Test Offer - SaaS Contract Product",
                "Description": "Private Test Offer - SaaS Contract Product"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "Custom4",
                                        "Price": "300.0"
                                    }
                                ],
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P36M"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ],
    "ChangeSetName": "PrivateOfferWithCustomDimension"
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a SaaS product custom dimension and private offer
CAPI-91
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set, "Create a SaaS product custom dimension and private offer"
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### AMI または SaaS 製品のドラフトプライベートオファーを作成する
<a name="marketplace-catalog_CreateDraftPrivateOffer_python_3_topic"></a>

次のコード例は、AMI または SaaS 製品のドラフトプライベートオファーを作成し、購入者に公開する前に内部で確認できるようにする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "Test Private Offer"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create “draft” Private Offer
for any AMI or SAAS product type that can be reviewed internally
before publishing to buyers
CAPI-30
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Private offer for AMI product")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 契約料金と従量制料金を使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractWithPayAsYouGoPricingForSaasProduct_python_3_topic"></a>

次のコード例は、契約料金と従量制料金を使用する、SaaS 製品のプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer with contract with PAYG pricing for my SaaS product
CAPI-34
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "Create private offer with contract with PAYG pricing for my SaaS product",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### 契約料金と柔軟な支払いスケジュールを使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractPricingWithFlexiblePaymentScheduleForSaasProduct_python_3_topic"></a>

次のコード例は、契約料金と柔軟な支払いスケジュールを使用する、SaaS 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Grants": [
                            {
                                "DimensionKey": "BasicService",
                                "MaxQuantity": 1
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P12M"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "200.00"
                            },
                            {
                                "ChargeDate": "2024-02-01",
                                "ChargeAmount": "170.00"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Some kind of refund policy description"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer
with contract pricing and flexible payment schedule for my SaaS product
CAPI-39
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create private offer with contract pricing and flexible payment schedule for my SaaS product",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 契約料金を使用する、コンテナ製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractPricingForContainerProduct_python_3_topic"></a>

次のコード例は、契約料金を使用する、コンテナ製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for Container product using AWS Marketplace API Reference Code",
                "Description": "Test private offer for Container product with contract pricing using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "Constraints": {
                                    "MultipleDimensionSelection": "Disallowed",
                                    "QuantityConfiguration": "Disallowed"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "ReqPerHour",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer (target buyers)
for my Container product with contract pricing
CAPI-36
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "publish a private offer for my Container product with contract pricing",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 契約料金を使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithContractPricingForAmiProduct_python_3_topic"></a>

次のコード例は、契約料金を使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "ReadOnlyUsers",
                                        "Price": "220.00"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer with contract pricing for my AMI product
CAPI-35
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set, "create private offer with contract pricing for my AMI product"
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 時間単位の年間料金と柔軟な支払いスケジュールを使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithHourlyAnnualPricingAndFlexiblePaymentScheduleForAmiProduct_python_3_topic"></a>

次のコード例は、時間単位の年間料金と柔軟な支払いスケジュールを使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.17"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Duration": "P365D",
                        "Grants": [
                            {
                                "DimensionKey": "t2.micro",
                                "MaxQuantity": 1
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P650D"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "200.00"
                            },
                            {
                                "ChargeDate": "2024-02-01",
                                "ChargeAmount": "170.00"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer with hourly annual pricing and flexible payment schedule for my AMI product
CAPI-XX
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "Create private offer with hourly annual pricing and flexible payment schedule for my AMI product",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 時間単位の年間料金を使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithHourlyAnnualPricingForAmiProduct_python_3_topic"></a>

次のコード例は、時間単位の年間料金を使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly annual pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.17"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P365D"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "220.00"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P650D"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer with hourly annual pricing for my AMI product
CAPI-31
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set, "create private offer with hourly annual pricing for my AMI product"
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 時間単位の料金を使用する、AMI 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithHourlyPricingForAmiProduct_python_3_topic"></a>

次のコード例は、時間単位の料金を使用する、AMI 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for AmiProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with hourly pricing for AmiProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2025-01-01"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "0.15"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P30D"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer with hourly pricing for my AMI product
CAPI-32
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set, "create private offer with hourly pricing for my AMI product"
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### サブスクリプション料金を使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithSubscriptionPricingForSaasProduct_python_3_topic"></a>

次のコード例は、サブスクリプション料金を使用する、SaaS 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.13"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.22"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementDuration": "P30D"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer with subscription pricing for my SaaS product
CAPI-33
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set, "Create private offer with subscription pricing for my SaaS product"
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 階層型契約料金を使用する、SaaS 製品向けのプライベートオファーを作成する
<a name="marketplace-catalog_CreatePrivateOfferWithTieredContractPricingForSaasProduct_python_3_topic"></a>

次のコード例は、階層型契約料金を使用する、SaaS 製品向けのプライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test private offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test private offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "120.00"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "200.00"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Disallowed",
                                    "QuantityConfiguration": "Disallowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a private offer with tiered contract pricing for my SaaS product
CAPI-XX
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "Create private offer with tiered contract pricing for my SaaS product",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### サブスクリプション料金を使用する、SaaS 製品向けのパブリック無料トライアルオファーを作成する
<a name="marketplace-catalog_CreatePublicFreeTrialOfferWithSubscriptionPricingForSaasProduct_python_3_topic"></a>

次のコード例は、サブスクリプション料金を使用する、SaaS 製品向けのパブリック無料トライアルオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "prod-1111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public free trial offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public free trial offer with subscription pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Free",
                "Terms": [
                    {
                        "Type": "FreeTrialPricingTerm",
                        "Duration": "P20D",
                        "Grants": [
                            {
                                "DimensionKey": "WorkloadSmall"
                            },
                            {
                                "DimensionKey": "WorkloadMedium"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a public free trial offer with subscription pricing for SaaS product
CAPI-13
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "Create public free trial offer with subscription pricing for SaaS product",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 契約料金を使用する代替プライベートオファーを作成する
<a name="marketplace-catalog_CreateReplacementPrivateOfferWithContractPricing_python_3_topic"></a>

次のコード例は、既存の契約から契約料金を使用する代替プライベートオファーを作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType" : "CreateReplacementOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateReplacementOffer",
            "DetailsDocument": {
                "AgreementId": "agmt-1111111111111111111111111"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test replacement offer for SaaSProduct using AWS Marketplace API Reference Codes",
                "Description": "Test private replacement offer with contract pricing for SaaSProduct"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "FixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.0",
                        "Grants": [
                            {
                                "DimensionKey": "BasicService",
                                "MaxQuantity": 2
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateValidityTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ValidityTerm",
                        "AgreementEndDate": "2024-01-30"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "PaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2024-01-01",
                                "ChargeAmount": "0"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateReplacementOffer.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a replacement private offer
from an existing agreement with contract pricing
CAPI-95
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create replacement private offer with contract pricing..",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックオファーの説明
<a name="marketplace-catalog_DescribeOffer_python_3_topic"></a>

以下のコード例は、パブリックオファーを記述する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) search for offer information in the AWS Marketplace Catalog
CAPI-29
"""

import json
import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

OFFER_ID = "offer-1111111111111"


def pretty_print(response):
    json_object = json.dumps(response, indent=4)
    print(json_object)


def get_offer_information(mp_client, entity_id):
    """
    Returns information about a given offer
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of offer information
    """

    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace",
            EntityId=entity_id,
        )

        return response

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Offer with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an offer in the AWS Marketplace Catalog.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-catalog")

    pretty_print(get_offer_information(mp_client, OFFER_ID))


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeEntity](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/DescribeEntity)」を参照してください。**

### ドラフトのプライベートオファーを期限切れにする
<a name="marketplace-catalog_ExpirePrivateOffer_python_3_topic"></a>

次のコード例は、購入者にオファーが表示されないように、プライベートオファーの有効期限を過去の日付に設定する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "Test Private Offer"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create “draft” Private Offer
for any AMI or SAAS product type that can be reviewed internally
before publishing to buyers
CAPI-30
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Private offer for AMI product")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### すべてのプライベートオファーを一覧表示する
<a name="marketplace-catalog_ListAllPrivateOffers_python_3_topic"></a>

次のコード例は、すべてのプライベートオファーを一覧表示する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) for listing offers in the AWS Marketplace Catalog
CAPI-40
"""
import json
import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# Constants
MAX_RESULTS = 10
CATALOG = "AWSMarketplace"
ENTITY_TYPE = "Offer"


def pretty_print(response):
    json_object = json.dumps(response, indent=4)
    print(json_object)


def list_private_offers(mp_client, return_all_private_offers):
    """
    This method retrieves list of all Private Offers for this account.
    """
    entity_summary_list = []
    filter_list_param = {
        'OfferFilters': {
            'Targeting': {
                'ValueList': ["BuyerAccounts"]
            }
        }
    }
    try:
        response = mp_client.list_entities(
            Catalog=CATALOG,
            EntityType=ENTITY_TYPE,
            EntityTypeFilters=filter_list_param,
            MaxResults=MAX_RESULTS
        )
    except ClientError as e:
        logger.error("Could not complete list_entities request: %s", e)
        raise

    entity_summary_list.extend(response["EntitySummaryList"])
    logger.info("Number of results in first iteration: %d " % len(entity_summary_list))

    # Get subsequent pages of results if previous response contained a NextToken
    while "NextToken" in response and return_all_private_offers:
        try:
            logger.info("Getting Next Token results: %s " % response["NextToken"])
            response = mp_client.list_entities(
                Catalog=CATALOG,
                EntityType=ENTITY_TYPE,
                EntityTypeFilters=filter_list_param,
                MaxResults=MAX_RESULTS,
                NextToken=response["NextToken"]
            )
        except ClientError as e:
            logger.error("Could not complete list_entities request: %s", e)
            raise

        entity_summary_list.extend(response["EntitySummaryList"])
        logger.info(
            "Number of results in the current iteration: %d "
            % len(response["EntitySummaryList"])
        )

    return entity_summary_list


def get_offer_details(mp_client, offer):
    """
    Describe the details of the Offer.
    """
    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace", EntityId=offer["EntityId"]
        )

        return response
    except ClientError:
        logger.exception("Error: Couldn't get details of the Offer.")
        raise


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Demo  - List Private offers.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-catalog")

    # Get list of all Offers.
    private_offers = list_private_offers(mp_client, False)
    count = len(private_offers)

    logger.info("Number of Offers: %d " % count)
    offer_counter = 0
    # Display details of each Offer.
    for offer in private_offers:
        print("-" * 88)
        offer_counter += 1
        print("Displaying Offer details for Offer# %d" % offer_counter)
        entity = get_offer_details(mp_client, offer)
        pretty_print(entity)

    print("-" * 88)


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### オファーを更新して従量制料金を使用する契約を適用する
<a name="marketplace-catalog_UpdateOfferWithContractAndPayAsYouGoPricing_python_3_topic"></a>

次のコード例は、オファーを更新して従量制料金を使用する契約を適用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update an offer to apply contract with PAYG pricing
CAPI-21
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update offer to apply contract with PAYG pricing")


if __name__ == "__main__":
    main()
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。

### オファーを更新して時間単位の年間料金を適用する
<a name="marketplace-catalog_UpdateOfferWithHourlyAnnualPricing_python_3_topic"></a>

次のコード例は、オファーを更新して時間単位の年間料金を適用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "m5.large",
                                        "Price": "0.13"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P365D"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "m5.large",
                                        "Price": "20.03"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update an offer to apply hourly annual pricing
CAPI-20
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update offer with hourly annual pricing")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### オファーを更新して特定の地理的リージョンにターゲティングを適用する
<a name="marketplace-catalog_UpdateOfferTargeting_python_3_topic"></a>

次のコード例は、オファーを更新して特定の地理的リージョンにターゲティングを適用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "CountryCodes": [
                        "US",
                        "ES",
                        "FR",
                        "AU"
                    ]
                }
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update an offer to apply targeting to certain geographic regions.
CAPI-19
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update offer targeting")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックオファーの名前と説明を更新する
<a name="marketplace-catalog_UpdateOfferNameAndDescription_python_3_topic"></a>

次のコード例は、パブリックオファーの名前と説明を更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "Name": "New offer name",
                "Description": "New offer description"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update name and description of my offer
CAPI-18
"""

import os

import utils.start_changeset as sc  # type: ignore
import utils.stringify_details as sd  # type: ignore

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update name and description of my offer")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### オファーの EULA を更新する
<a name="marketplace-catalog_UpdateEula_python_3_topic"></a>

次のコード例は、オファーの EULA を更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update EULA of my offer
CAPI-18
"""

import os

import utils.start_changeset as sc  # type: ignore
import utils.stringify_details as sd  # type: ignore

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update EULA of my offer")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### プライベートオファーの有効期限を将来の日付に更新する
<a name="marketplace-catalog_UpdateOfferExpirationDateOfPrivateOffer_python_3_topic"></a>

次のコード例は、プライベートオファーの有効期限を将来の日付に更新して、購入者がオファーを評価して承諾する時間を延長する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2026-01-01"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to set expiry date of a private offer to a date in the future so that my buyers get more time to evaluate and accept the offer.
CAPI-37
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update offer expiration date")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### SaaS 製品向けのパブリック無料トライアルオファーの無料トライアル期間を更新する
<a name="marketplace-catalog_UpdateFreeTrialDurationOfPublicFreeTrialOfferForSaasProduct_python_3_topic"></a>

次のコード例は、SaaS 製品向けのパブリック無料トライアルオファーの無料トライアル期間を更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "FreeTrialPricingTerm",
                        "Duration": "P21D",
                        "Grants": [
                            {
                                "DimensionKey": "WorkloadSmall"
                            },
                            {
                                "DimensionKey": "WorkloadMedium"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to change free trial duration for my SaaS product by modifying my free trial public offer
CAPI-14
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Change free trial duration for SaaS product")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### オファーの返金ポリシーを更新する
<a name="marketplace-catalog_UpdateRefundPolicy_python_3_topic"></a>

次のコード例は、オファーの返金ポリシーを更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "offer-1111111111111"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Updated refund policy description"
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update refund policy of my offer
CAPI-18
"""

import os

import utils.start_changeset as sc  # type: ignore
import utils.stringify_details as sd  # type: ignore

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Update refund policy of my public offer")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

## 製品
<a name="products"></a>

### AMI、SaaS、またはコンテナ製品を記述する
<a name="marketplace-catalog_DescribeProduct_python_3_topic"></a>

次のコード例は、AMI、SaaS、またはコンテナ製品を記述し、製品について知りたい情報がすべて含まれているかどうかを確認する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) search for product information in the AWS Marketplace Catalog
CAPI-28
"""

import json
import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

PRODUCT_ID = "prod-1111111111111"


def pretty_print(response):
    json_object = json.dumps(response, indent=4)
    print(json_object)


def get_product_information(mp_client, entity_id):
    """
    Returns information about a given product
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of product information
    """

    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace",
            EntityId=entity_id,
        )

        return response

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Product with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for a product in the AWS Marketplace Catalog.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-catalog")

    pretty_print(get_product_information(mp_client, PRODUCT_ID))


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeEntity](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/DescribeEntity)」を参照してください。**

### すべての AMI、SaaS、またはコンテナ製品と、関連するパブリックオファーを一覧表示する
<a name="marketplace-catalog_ListProducts_python_3_topic"></a>

次のコード例は、すべての AMI、SaaS、またはコンテナ製品と、関連するパブリックオファーを一覧表示する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to display information about AMI products and their associated offers in the AWS Marketplace Catalog
CAPI-27
"""

import json
import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

MAX_PAGE_RESULTS = 10

try:
    mp_client = boto3.client("marketplace-catalog")
except ClientError as e:
    logger.error("Could not create boto3 client.")
    raise


def pretty_print(response):
    json_object = json.dumps(response, indent=4)
    print(json_object)


def describe_entity(entity_id):
    """
    Returns entity details
    Args: entity_id str: The entity ID of the product or offer
    Returns: dict: The entity details
    """
    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace", EntityId=entity_id
        )
    except ClientError as e:
        logger.error("Could not complete describe_entity request.")
        raise

    # De-stringify the details
    response["Details"] = json.loads(response["Details"])

    return response


def get_entities(entity_type, visibility=None):
    """
    Returns list of entities for provided entity_type
    Args: entity_type str: Type of entity list to return, in our case AmiProduct or Offer
    Returns: list: Abbreviated list of entity information
    """
    EntitySummaryList = []

    # Get the first page of results
    try:
        response = mp_client.list_entities(
            Catalog="AWSMarketplace",
            EntityType=entity_type,
            MaxResults=MAX_PAGE_RESULTS,
        )
    except ClientError as e:
        logger.error("Could not complete list_entities request.")
        raise

    EntitySummaryList.extend(response["EntitySummaryList"])

    # Get subsequent pages of results if previous response contained a NextToken
    while "NextToken" in response:
        try:
            response = mp_client.list_entities(
                Catalog="AWSMarketplace",
                EntityType=entity_type,
                MaxResults=MAX_PAGE_RESULTS,
                NextToken=response["NextToken"],
            )
        except ClientError as e:
            logger.error("Could not complete list_entities request.")
            raise

        EntitySummaryList.extend(response["EntitySummaryList"])

    # if visibility is provided, filter the list to only include entities with that visibility
    if visibility is not None:
        EntitySummaryList = [
            entity for entity in EntitySummaryList if entity["Visibility"] == visibility
        ]

    return EntitySummaryList


def get_enhanced_product_list(entity_type):
    """
    Returns an enhanced list of products with product details and offer details
    Args: entity_type str: Type of entity list to return, in our case AmiProduct
    Returns: list: Enhanced list of dictionary objects containing product and offer details
    """

    product_list = get_entities(entity_type)

    # Loop through product list and append product details to each product
    for product in product_list:
        # appends product details to product dictionary
        product["ProductDetails"] = describe_entity(product["EntityId"])["Details"]
        # creating an empty list for offer details
        product["OfferDetailsList"] = []

    return product_list


def attach_offer_details(product_list):
    """
    Loops through offer information and appends offer details to product list
    Args: product_list list: List of product dictionaries
    Returns: list: Enhanced list of dictionary objects containing product and offer details
    """
    offer_list = get_entities("Offer", "Public")

    # Loop through offer list and append offer details to each product
    for offer in offer_list:
        offer["OfferDetails"] = describe_entity(offer["EntityId"])["Details"]

        # Extracts product-id from offer
        product_id = offer["OfferDetails"]["ProductId"]

        # Determines if product-id referenced in offer matches product-id in product list
        product_dict = next(
            filter(lambda product: product["EntityId"] == product_id, product_list),
            None,
        )

        # If product-id matches, appends offer details to product dictionary
        if product_dict is not None:
            # logger.info(f"Offer product Id {offer['OfferDetails']['ProductId']} found in product dictionary. Updating product dictionary with offer details")
            product_dict["OfferDetailsList"].append(offer["OfferDetails"])

        else:
            # logger.info("Offer product Id {offer['OfferDetails']['ProductId']} not found. Skipping offer details update")
            pass

    return product_list


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Retrieving products and public offer information....")
    print("-" * 88)

    # Builds a list of products and their details
    product_list = get_enhanced_product_list("AmiProduct")

    # Queries offer information and attaches it to the product list
    product_offer_list = attach_offer_details(product_list)

    pretty_print(product_offer_list)
    return product_offer_list


if __name__ == "__main__":
    usage_demo()
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [DescribeEntity](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/DescribeEntity)
  + [ListEntities](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/ListEntities)

## 再販承認
<a name="resale_authorization"></a>

### ドラフト再販承認を作成する
<a name="marketplace-catalog_DraftResaleauthAllproducttype_python_3_topic"></a>

次のコード例は、チャネルパートナーに公開する前に内部で確認できるように、任意の製品タイプのドラフト再販承認を作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a one-time resale authorization on my SaaS/AMI/Container product so my CP can use that to create Channel Partner Private Offer (CPPO)
CAPI-41
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "draft resale auth")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 再販承認を記述する
<a name="marketplace-catalog_DescribeResaleAuthorization_python_3_topic"></a>

次のコード例は、再販承認を記述する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) search for product information in the AWS Marketplace Catalog
"""

import json
import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

resaleAuthorizationId = "resaleauthz-1111111111111"


def pretty_print(response):
    json_object = json.dumps(response, indent=4)
    print(json_object)


def get_product_information(mp_client, entity_id):
    """
    Returns information about a given product
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of product information
    """

    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace",
            EntityId=entity_id,
        )

        return response

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Product with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for a product in the AWS Marketplace Catalog.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-catalog")

    pretty_print(get_product_information(mp_client, resaleAuthorizationId))


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeEntity](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/DescribeEntity)」を参照してください。**

### プライベートオファーを使用して 1 回限りの再販承認を発行する
<a name="marketplace-catalog_OnetimeResaleauthPrivateoffer_python_3_topic"></a>

次のコード例は、プライベートオファーを使用して 1 回限りの再販承認を発行し、チャネルパートナーがそれを使用してチャネルパートナープライベートオファー (CPPO) を作成できるようにする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a one-time resale authorization on my SaaS/AMI/Container product so my CP
can use that to create Channel Partner Private Offer (CPPO)
CAPI-42
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set, "onetime resale auth with private offer"
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限付きの複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthExpirydateCppo_python_3_topic"></a>

次のコード例は、時間単位の年間料金を使用して AMI 製品向けに有効期限付きの複数回使用可能な再販承認を発行し、チャネルパートナーがそれを使用してチャネルパートナープライベートオファー (CPPO) を作成できるようにする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a multi-use resale authorization with expiry date on my SaaS/AMI product so my CP can use that to create Channel Partner Private Offer (CPPO)
CAPI-48
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "multi-use resale auth with expiry date")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限と EULA を含む複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthExpirydateCustomEula_python_3_topic"></a>

次のコード例は、任意の製品タイプに対して有効期限付きの複数回使用可能な再販承認を公開し、購入者に送信するカスタム EULA を追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a multi-use resale authorization with expiry date on my SaaS/AMI/Container product and add custom EULA to be sent to the buyer
CAPI-56
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "multiuse resale auth with expiry date and custom EULA")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限と再販契約ドキュメントを含む複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthExpirydateCustomresellerContractdoc_python_3_topic"></a>

次のコード例は、任意の製品タイプに対して有効期限付きの複数回使用可能な再販承認を発行し、ISV とチャネルパートナー間の再販契約ドキュメントを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-12-31"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    },
                    {
                        "Type": "ResaleLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomResellerContract",
                                "Url": "https://s3.amazonaws.com/aws-mp-standard-contracts/Standard-Contact-for-AWS-Marketplace-2022-07-14.pdf"}
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleUsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.micro",
                                        "Price": "150"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a multi-use resale authorization with expiry date on my SaaS/AMI/Container product
and add reseller contract documentation between the ISV and channel partner
CAPI-57
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "multi use resale auth with contract doc",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限付きの複数回使用可能な再販承認を発行し、特定の購入者アカウントを追加する
<a name="marketplace-catalog_PublishMultiuseResaleAuthorizationExpirydateSpecificBuyer_python_3_topic"></a>

次のコード例は、任意の製品タイプについて、有効期限付きの複数回使用可能な再販承認を発行し、再販用の特定の購入者アカウントを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-05-31"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "111111111111"
                            ]
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish multi-use resale authorization with expiry date for any product type (AMI/SaaS/Container) and add specific buyer account for the resale
CAPI-82
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "Publish multi-use resale authorization with expiry date and add specific buyer account",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限なしの複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthNoExpirydateCppo_python_3_topic"></a>

次のコード例は、時間単位の年間料金を使用する AMI 製品に対して有効期限なしの複数回使用可能な再販承認を発行し、CP がこれを使用して CPPO を作成できるようにする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a multi-use resale authorization with no expiry date on my SaaS/AMI product so my CP can use that to create Channel Partner Private Offer (CPPO)
CAPI-52
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "multi use resale auth with no expiry date")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限と EULA のない複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthNoExpirydateCustomEula_python_3_topic"></a>

次のコード例は、任意の製品タイプ向けに有効期限のない複数回使用可能な再販承認を発行し、カスタム EULA を追加して購入者に送信できるようにする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a multi-use resale authorization with no expiry date on my SaaS/AMI/Container product and add custom EULA to be sent to the buyer
CAPI-58
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set, "multi use resale auth with no expiry date and custom EULA"
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限と再販契約ドキュメントのない複数回使用可能な再販承認を発行する
<a name="marketplace-catalog_MultiuseResaleauthNoExpirydateCustomresellerContractdoc_python_3_topic"></a>

次のコード例は、任意の製品タイプについて、有効期限なしの複数回使用可能な再販承認を発行し、ISV とチャネルパートナー間の再販契約ドキュメントを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    },
                    {
                        "Type": "ResaleLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomResellerContract",
                                "Url": "https://s3.amazonaws.com/aws-mp-standard-contracts/Standard-Contact-for-AWS-Marketplace-2022-07-14.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a multi-use resale authorization with no expiry date on my SaaS/AMI/Container product and add reseller contract documentation between the ISV and channel partner
CAPI-59
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set, "multi use resale auth with no expiry date and contract doc"
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 有効期限のない複数回使用可能な再販承認を発行し、特定の購入者アカウントを追加する
<a name="marketplace-catalog_PublishMultiuseResaleAuthorizationNoExpirydateSpecificBuyer_python_3_topic"></a>

次のコード例は、任意の製品タイプ向けに有効期限のない複数回使用可能な再販承認を発行し、再販用に特定の購入者アカウントを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "111111111111"
                            ]
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish multi-use resale authorization without expiry date for any product type (AMI/SaaS/Container) and add specific buyer account for the resale
CAPI-83
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "publish multi-use resale authorization without expiry date and add specific buyer account",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 1 回限りの再販承認を発行し、柔軟な支払いスケジュールを追加する
<a name="marketplace-catalog_PublishOnetimeResaleAuthorizationFlexiblePayment_python_3_topic"></a>

次のコード例は、任意の製品タイプ向けに 1 回限りの再販売承認を発行し、柔軟な支払いスケジュールを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleFixedUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "Price": "0.00",
                        "Duration": "P12M",
                        "Grants": [
                          {
                            "DimensionKey": "Users",
                            "MaxQuantity": 10
                          }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePaymentScheduleTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "ResalePaymentScheduleTerm",
                        "CurrencyCode": "USD",
                        "Schedule": [
                            {
                                "ChargeDate": "2023-09-01",
                                "ChargeAmount": "200.00"
                            },
                            {
                                "ChargeDate": "2023-12-01",
                                "ChargeAmount": "250.00"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "AvailabilityEndDate": "2023-06-30",
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish one-time resale authorization for any product type (AMI/SaaS/Container) and add Flexible payment schedule
CAPI-78
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "onetime resale auth with flexible payment schedule")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 1 回限りの再販売承認を発行し、EULA を追加する
<a name="marketplace-catalog_OnetimeResaleauthCustomEula_python_3_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販売認可を発行し、カスタム EULA を追加して購入者に送信できるようにする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a one-time resale authorization on my SaaS/AMI/Container product and add custom EULA to be sent to the buyer
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "onetime resale auth with custom EULA")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 1 回限りの再販承認を発行し、特定の購入者アカウントを追加する
<a name="marketplace-catalog_PublishOnetimeResaleAuthorizationSpecificBuyer_python_3_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販承認を発行し、再販用に特定の購入者アカウントを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "111111111111"
                            ]
                        }
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish one-time resale authorization for any product type (AMI/SaaS/Container) and add specific buyer account for the resale
CAPI-81
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "onetime resale authorization for specific buyer account")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 1 回限りの再販承認を発行し、リセラー契約ドキュメントを追加する
<a name="marketplace-catalog_OnetimeResaleauthCustomresellerContractdoc_python_3_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販売認可を発行し、ISV とチャネルパートナー間のリセラー契約ドキュメントを追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "ReleaseResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ResaleConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "t2.small",
                                        "Price": "150"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomEula",
                                "Url": "https://s3.amazonaws.com/sample-bucket/custom-eula.pdf"
                            }
                        ]
                    },
                    {
                        "Type": "ResaleLegalTerm",
                        "Documents": [
                            {
                                "Type": "CustomResellerContract",
                                "Url": "https://s3.amazonaws.com/aws-mp-standard-contracts/Standard-Contact-for-AWS-Marketplace-2022-07-14.pdf"
                            }
                        ]
                    }
                ]
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish a one-time resale authorization on my SaaS/AMI/Container product and add reseller contract documentation between the ISV and channel partner
CAPI-47
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "onetime resale auth with reseller contract doc")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 1 回限りの再販売承認を発行し、それが更新かどうかを追加表示する
<a name="marketplace-catalog_OnetimeResaleauthRenewal_python_3_topic"></a>

次のコード例は、任意の製品タイプ向けの 1 回限りの再販売認可を発行し、それが更新かどうかを追加表示する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateResaleAuthorization",
            "ChangeName": "ResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0"
            },
            "DetailsDocument": {
                "ProductId": "prod-1111111111111",
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "ResellerAccountId": "111111111111"
            }
        },
        {
            "ChangeType": "UpdateBuyerTargetingTerms",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "BuyerTargetingTerm",
                        "PositiveTargeting": {
                            "BuyerAccounts": [
                                "222222222222"
                            ]
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateAvailability",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "OffersMaxQuantity": 1
            }
        },
        {
            "ChangeType":"UpdateInformation",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "$ResaleAuthorization.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product",
                "PreExistingBuyerAgreement": {
                    "AcquisitionChannel": "AwsMarketplace",
                    "PricingModel": "Contract"
                }
             }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish one-time resale authorization for any product type (AMI/SaaS/Container)
and add whether it is renewal or not
CAPI-90
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(stringified_change_set, "onetime resale auth renewal")

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 再販承認を制限する
<a name="marketplace-catalog_RestrictResaleAuthorization_python_3_topic"></a>

次のコード例は、再販承認を制限する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "RestrictResaleAuthorization",
            "Entity": {
                "Type": "ResaleAuthorization@1.0",
                "Identifier": "resaleauthz-1111111111111"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Restrict a  authorization for any product type (AMI/SaaS/Container)
CAPI-84
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "Restrict resale authorization")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### 1 回限りまたは複数回使用可能な再販承認の名前と説明を更新する
<a name="marketplace-catalog_UpdateUnpublishedResaleAuthorization_python_3_topic"></a>

次のコード例は、任意の製品タイプに対して公開する前に、1 回限りまたは複数回使用可能な再販承認の名前と説明を更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType":"UpdateInformation",
            "Entity": {
            	"Type": "ResaleAuthorization@1.0",
            	"Identifier": "resaleauthz-1111111111111"
            },
            "DetailsDocument": {
            	"Name": "TestResaleAuthorization",
                "Description": "Worldwide ResaleAuthorization for Test Product"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Update name/description of one-time or multi-use resale authorization before publishing for any product type (AMI/SaaS/Container)
CAPI-77
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "update name and description of one-time or multi-use resale authorization before publishing",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

## SaaS 製品
<a name="saas_products"></a>

### ドラフトパブリックオファーを使用するドラフト SaaS 製品を作成する
<a name="marketplace-catalog_CreateDraftSaasProductWithDraftPublicOffer_python_3_topic"></a>

次のコード例は、ドラフトパブリックオファーを使用してドラフト SaaS 製品を作成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog":"AWSMarketplace",
    "ChangeSet":[
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier",
                "Name": "Test Offer"
            }
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create an SaaS draft product
with a draft public offer.
CAPI-04
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Create a draft saas product with a draft public offer",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックまたは制限付き SaaS 製品と、契約料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedSaasProductAndPublicOfferWithContractPricing_python_3_topic"></a>

次のコード例は、パブリックまたは制限付き SaaS 製品と、契約料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "ChangeName": "CreateProductChange",
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl":"https://sample.amazonaws.com/sample-saas-fulfillment-url"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Description": "Basic Service",
                    "Name": "Basic Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "PremiumService",
                    "Description": "Premium Service",
                    "Name": "Premium Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with contract pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P1M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "20"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "25"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            },
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateRenewalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "RenewalTerm"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a
public or limited SaaS product and public offer with contract pricing and standard EULA
CAPI-11
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "Create a limited saas product with a public offer with contract pricing",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックまたは制限付きの SaaS 製品と、従量制料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedSaasProductAndPublicOfferWithContractWithPayAsYouGoPricing_python_3_topic"></a>

次のコード例は、パブリックまたは制限付き SaaS 製品と、従量制料金の契約を使用するパブリックオファーを作成する方法を示しています。この例では、標準またはカスタム EULA を作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "ChangeName": "CreateProductChange",
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl":"https://sample.amazonaws.com/sample-saas-fulfillment-url"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Description": "Basic Service",
                    "Name": "Basic Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "PremiumService",
                    "Description": "Premium Service",
                    "Name": "Premium Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "WorkloadSmall",
                    "Description": "Workload: Per medium instance",
                    "Name": "Workload: Per medium instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "WorkloadMedium",
                    "Description": "Workload: Per large instance",
                    "Name": "Workload: Per large instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with contract pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateRenewalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "RenewalTerm"
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a
public or limited SaaS product and public offer with contract with PAYG pricing and standard EULA
CAPI-10
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(
        change_set,
        "Create limited SaaS product with public offer with contract with payg pricing",
    )


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### パブリックまたは制限付きの SaaS 製品と、サブスクリプション料金を使用するパブリックオファーを作成する
<a name="marketplace-catalog_CreateLimitedSaasProductAndPublicOfferWithSubscriptionPricing_python_3_topic"></a>

次のコード例は、パブリックまたは制限付き SaaS 製品と、サブスクリプション料金を使用するパブリックオファーを作成する方法を示しています。この例では、標準 EULA またはカスタム EULA を作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "CreateProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "ChangeName": "CreateProductChange",
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://s3.amazonaws.com/logos/sample.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "UpdateTargeting",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PositiveTargeting": {
                    "BuyerAccounts": [
                        "111111111111",
                        "222222222222"
                    ]
                }
            }
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl":"https://sample.amazonaws.com/sample-saas-fulfillment-url"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "WorkloadSmall",
                    "Description": "Workload: Per medium instance",
                    "Name": "Workload: Per medium instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "WorkloadMedium",
                    "Description": "Workload: Per large instance",
                    "Name": "Workload: Per large instance",
                    "Types": [
                        "ExternallyMetered"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "ChangeName": "CreateOfferChange",
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "Test public offer for SaaSProduct using AWS Marketplace API Reference Code",
                "Description": "Test public offer with contract pricing for SaaSProduct using AWS Marketplace API Reference Code"
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Usage",
                "Terms": [
                    {
                        "Type": "UsageBasedPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "RateCard": [
                                    {
                                        "DimensionKey": "WorkloadSmall",
                                        "Price": "0.15"
                                    },
                                    {
                                        "DimensionKey": "WorkloadMedium",
                                        "Price": "0.25"
                                    }
                                ]
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Absolutely no refund, period."
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseOffer",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to create a
public or limited SaaS product and public offer with subscription(usage) pricing and standard EULA
CAPI-09
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd

fname = "changeset.json"
change_set_file = os.path.join(os.path.dirname(__file__), fname)

change_set = sd.stringify_changeset(change_set_file)


def main():
    sc.usage_demo(change_set, "public saas public offer with subscription pricing")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### SaaS 製品および関連するパブリックオファーを公開する
<a name="marketplace-catalog_PublishSaasProductPublicOffer_python_3_topic"></a>

次のコード例は、SaaS 製品および関連するパブリックオファーを公開する方法を示しています。製品はデフォルトで制限付きの状態になります。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog":"AWSMarketplace",
    "ChangeSet":[
        {
            "ChangeType": "CreateProduct",
            "ChangeName": "CreateProductChange",
            "Entity": {
                "Type": "SaaSProduct@1.0"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "ProductTitle": "Sample product",
                "ShortDescription": "Brief description",
                "LongDescription": "Detailed description",
                "Highlights": [
                    "Sample highlight"
                ],
                "SearchKeywords": [
                    "Sample keyword"
                ],
                "Categories": [
                    "Data Catalogs"
                ],
                "LogoUrl": "https://bucketname.s3.amazonaws.com/logo.png",
                "VideoUrls": [
                    "https://sample.amazonaws.com/awsmp-video-1"
                ],
                "AdditionalResources": []
            }
        },
        {
            "ChangeType": "AddDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Description": "Basic Service",
                    "Name": "Basic Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                },
                {
                    "Key": "PremiumService",
                    "Description": "Premium Service",
                    "Name": "Premium Service",
                    "Types": [
                        "Entitled"
                    ],
                    "Unit": "Units"
                }
            ]
        },
        {
            "ChangeType": "AddDeliveryOptions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "DeliveryOptions": [
                    {
                        "Details": {
                            "SaaSUrlDeliveryOptionDetails": {
                                "FulfillmentUrl": "https://www.aws.amazon.com/marketplace/management"
                            }
                        }
                    }
                ]
            }
        },
        {
            "ChangeType": "ReleaseProduct",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "$CreateProductChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        },
        {
            "ChangeType": "CreateOffer",
            "ChangeName": "CreateOfferChange",
            "Entity": {
                "Type": "Offer@1.0"
            },
            "DetailsDocument": {
                "ProductId": "$CreateProductChange.Entity.Identifier"
            }
        },
        {
            "ChangeType": "UpdateInformation",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Name": "New Test Offer",
                "Description": "New offer description"
            }
        },
        {
            "ChangeType": "UpdateLegalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "LegalTerm",
                        "Documents": [
                            {
                                "Type": "StandardEula",
                                "Version": "2022-07-14"
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateSupportTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "SupportTerm",
                        "RefundPolicy": "Updated refund policy description"
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdatePricingTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "PricingModel": "Contract",
                "Terms": [
                    {
                        "Type": "ConfigurableUpfrontPricingTerm",
                        "CurrencyCode": "USD",
                        "RateCards": [
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P1M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "20"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "25"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            },
                            {
                                "Selector": {
                                    "Type": "Duration",
                                    "Value": "P12M"
                                },
                                "RateCard": [
                                    {
                                        "DimensionKey": "BasicService",
                                        "Price": "150"
                                    },
                                    {
                                        "DimensionKey": "PremiumService",
                                        "Price": "300"
                                    }
                                ],
                                "Constraints": {
                                    "MultipleDimensionSelection": "Allowed",
                                    "QuantityConfiguration": "Allowed"
                                }
                            }
                        ]
                    }
                ]
            }
        },
        {
            "ChangeType": "UpdateRenewalTerms",
            "Entity": {
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {
                "Terms": [
                    {
                        "Type": "RenewalTerm"
                    }
                ]
            }
        },
        {
            "ChangeType":"ReleaseOffer",
            "Entity":{
                "Type": "Offer@1.0",
                "Identifier": "$CreateOfferChange.Entity.Identifier"
            },
            "DetailsDocument": {}
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Publish my SaaS product and associated public offer (product will be in limited state by default)
CAPI-05A
"""

import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset1.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "publish saas product and associated public offer",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

### AMI または SaaS 製品のディメンションを更新する
<a name="marketplace-catalog_UpdateNameDimensionSaasProduct_python_3_topic"></a>

次のコード例は、AMI または SaaS 製品のディメンションを更新する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
{
    "Catalog": "AWSMarketplace",
    "ChangeSet": [
        {
            "ChangeType": "UpdateDimensions",
            "Entity": {
                "Type": "SaaSProduct@1.0",
                "Identifier": "prod-111111111111"
            },
            "DetailsDocument": [
                {
                    "Key": "BasicService",
                    "Types": [
                        "Entitled"
                    ],
                    "Name": "Some new name",
                    "Description": "Some new description"
                }
            ]
        }
    ]
}
```
このスクリプトを実行して、変更セットを開始します。ヘルパー関数は、「**Utilities**」セクションの「*Utilities to start a changeset*」で定義されています。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to update (e.g name) dimensions on my AMI or SaaS product
CAPI-24
"""


import os

import utils.start_changeset as sc
import utils.stringify_details as sd


def main(change_set=None):
    if change_set is None:
        fname = "changeset.json"
        change_set_file = os.path.join(os.path.dirname(__file__), fname)
        stringified_change_set = sd.stringify_changeset(change_set_file)

    else:
        stringified_change_set = change_set

    response = sc.usage_demo(
        stringified_change_set,
        "Update name dimensions on my AMI or SaaS product",
    )

    return response


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

## Utilities
<a name="utilities"></a>

### 変更セットを開始するユーティリティ
<a name="marketplace-catalog_ChangeSetUtilities_python_3_topic"></a>

次のコード例は、変更セットを開始するためのユーティリティを定義する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python##catalog-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
変更セットを開始するユーティリティ。  

```
"""
Purpose:

Generic function to start a changeset
"""

import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def generate_changeset(mp_client, change_set, change_set_name):
    """
    Start changeset
    """
    try:
        response = mp_client.start_change_set(
            Catalog="AWSMarketplace",
            ChangeSet=change_set,
            ChangeSetName=change_set_name,
        )
        logger.info("Changeset created!")
        logger.info("ChangeSet ID: %s", response["ChangeSetId"])
        logger.info("ChangeSet ARN: %s", response["ChangeSetArn"])

        return response

    except ClientError as e:
        logger.exception("Unexpected error: %s", e)
        raise


def usage_demo(change_set, change_set_name):
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Executing changeset: " + change_set_name)
    print("-" * 88)

    mp_client = boto3.client("marketplace-catalog")

    response = generate_changeset(mp_client, change_set, change_set_name)

    return response

    print("-" * 88)
```
JSON ファイルから変更セットをロードするユーティリティ。  

```
"""
Purpose:

This module will stringify the details sections of a changeset file.
"""

import json


def pretty_print(response):
    json_object = json.dumps(response, indent=4)
    print(json_object)


# open json file from path
def open_json_file(filename):
    with open(filename, "r") as f:
        return json.load(f)


def stringify_details_sections(json_object):
    """
    Loops through every change type in the changeset to look for non-empty
    details section and stringifies them
    """
    for change_type in json_object["ChangeSet"]:
        # Only stringify details section if it is not empty
        if "Details" in change_type and change_type["Details"] != "{}":
            string_details = json.dumps(change_type["Details"])
            change_type["Details"] = string_details
        else:
            pass

    return json_object["ChangeSet"]


def stringify_changeset(file_path):
    changeset_file = open_json_file(file_path)
    changeset_stringified = stringify_details_sections(changeset_file)

    return changeset_stringified
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartChangeSet](https://docs.aws.amazon.com/goto/boto3/marketplace-catalog-2018-09-17/StartChangeSet)」を参照してください。**

# AWS Marketplace SDK for Python (Boto3) を使用した契約 API の例
<a name="python_3_marketplace-agreement_code_examples"></a>

次のコード例は、 AWS Marketplace Agreement API AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [契約](#agreements)

## 契約
<a name="agreements"></a>

### すべての契約 ID を取得する
<a name="marketplace-agreement_GetAllAgreementsIds_python_3_topic"></a>

次のコード例は、すべての契約 ID を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to get all agreement ids
AG-09
"""

import logging

import boto3
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")

logger = logging.getLogger(__name__)

MAX_PAGE_RESULTS = 10


def get_agreements():
    AgreementSummaryList = []
    agreement_id_list = []

    try:
        agreements = mp_client.search_agreements(
            catalog="AWSMarketplace",
            maxResults=MAX_PAGE_RESULTS,
            filters=[
                {"name": "PartyType", "values": ["Proposer"]},
                {"name": "AgreementType", "values": ["PurchaseAgreement"]},
            ],
        )
    except ClientError as e:
        logger.error("Could not complete search_agreements request.")
        raise

    AgreementSummaryList.extend(agreements["agreementViewSummaries"])

    while "nextToken" in agreements and agreements["nextToken"] is not None:
        try:
            agreements = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                nextToken=agreements["nextToken"],
                filters=[
                    {"name": "PartyType", "values": ["Proposer"]},
                    {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                ],
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise

        AgreementSummaryList.extend(agreements["agreementViewSummaries"])

    for agreement in AgreementSummaryList:
        agreement_id_list.append(agreement["agreementId"])

    return agreement_id_list


if __name__ == "__main__":
    agreement_id_list = get_agreements()

    print(agreement_id_list)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

### すべての契約を取得する
<a name="marketplace-agreement_GetAllAgreements_python_3_topic"></a>

次のコード例は、すべての契約を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to get all agreements
AG-01
"""

import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")

logger = logging.getLogger(__name__)

MAX_PAGE_RESULTS = 10

party_type_list = ["Proposer"]
agreement_type_list = ["PurchaseAgreement"]

filter_list = [
    {"name": "PartyType", "values": party_type_list},
    {"name": "AgreementType", "values": agreement_type_list},
]

agreement_results_list = []


def get_agreements(filter_list=filter_list):
    try:
        agreements = mp_client.search_agreements(
            catalog="AWSMarketplace",
            maxResults=MAX_PAGE_RESULTS,
            filters=filter_list,
        )
    except ClientError as e:
        logger.error("Could not complete search_agreements request.")
        raise e

    agreement_results_list.extend(agreements["agreementViewSummaries"])

    while "nextToken" in agreements and agreements["nextToken"] is not None:
        try:
            agreements = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                nextToken=agreements["nextToken"],
                filters=filter_list,
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise e

        agreement_results_list.extend(agreements["agreementViewSummaries"])

    return agreement_results_list


if __name__ == "__main__":
    agreements_list = get_agreements(filter_list)
    helper.pretty_print_datetime(agreements_list)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンス の「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

### 契約から顧客 ID を取得する
<a name="marketplace-agreement_GetAgreementCustomer_python_3_topic"></a>

次のコード例は、契約から顧客 ID を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to get customer AWS account id
from a given agreement
AG-08
"""

import argparse
import logging

import boto3
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")

logger = logging.getLogger(__name__)


def get_agreement_information(agreement_id):
    try:
        response = mp_client.describe_agreement(agreementId=agreement_id)
    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", agreement_id)
            raise e
        else:
            logger.error("Unexpected error: %s", e)
            raise e

    return response


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--agreement-id",
        "-aid",
        help="Provide agreement ID to describe agreement status",
        required=True,
    )
    args = parser.parse_args()

    response = get_agreement_information(agreement_id=args.agreement_id)

    print(f"Customer account: {response['acceptor']['accountId']}")
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約から財務詳細を取得する
<a name="marketplace-agreement_GetAgreementFinancialDetails_python_3_topic"></a>

次のコード例は、契約から財務小h歳を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain financial details, such as Total Contract Value of the agreementfrom a given agreement
AG-14

Example Usage: python3 get_agreement_financial_details.py --agreement-id <agreement-id>
"""

import argparse
import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

mp_client = boto3.client("marketplace-agreement")


def get_agreement_information(agreement_id):
    try:
        agreement = mp_client.describe_agreement(agreementId=agreement_id)

        return agreement

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", agreement_id)
        else:
            logger.error("Unexpected error: %s", e)

    return None


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--agreement-id",
        "-aid",
        help="Provide agreement ID to describe agreement status",
        required=True,
    )
    args = parser.parse_args()

    agreement = get_agreement_information(args.agreement_id)

    if agreement is not None:
        print(f"Agreement Id: {args.agreement_id}")
        print(
            f"Agreement Value: {agreement['estimatedCharges']['currencyCode']} {agreement['estimatedCharges']['agreementValue']}"
        )

    else:
        print(f"Agreement with ID {args.agreement_id} is not found")
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約から無料トライアルの詳細を取得する
<a name="marketplace-agreement_GetAgreementTermsFreeTrialDetails_python_3_topic"></a>

次のコード例は、契約から無料トライアルの詳細を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the details from an agreement of a free trial I have provided to the customer
AG-20

Example Usage: python3 get_agreement_free_trial_details.py --agreement-id <agreement-id>
"""

import argparse
import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

mp_client = boto3.client("marketplace-agreement")


def get_agreement_terms(agreement_id):
    try:
        agreement = mp_client.get_agreement_terms(agreementId=agreement_id)
        return agreement

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", agreement_id)

        else:
            logger.error("Unexpected error: %s", e)

    return None


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--agreement-id",
        "-aid",
        help="Provide agreement ID to describe agreement status",
        required=True,
    )
    args = parser.parse_args()

    agreement = get_agreement_terms(agreement_id=args.agreement_id)

    if agreement is not None:
        freetrial_found = False

        for term in agreement["acceptedTerms"]:
            if "freeTrialPricingTerm" in term.keys():
                helper.pretty_print_datetime(term)
                freetrial_found = True

        if not freetrial_found:
            print(f"No free trial term found for agreement: {args.agreement_id}")
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約に関する情報を取得する
<a name="marketplace-agreement_DescribeAgreement_python_3_topic"></a>

次のコード例は、契約に関する情報を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to get agreement information
AG-07
"""

import argparse
import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")

logger = logging.getLogger(__name__)


def get_agreement_information(agreement_id):
    try:
        response = mp_client.describe_agreement(agreementId=agreement_id)
    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", agreement_id)
            raise e
        else:
            logger.error("Unexpected error: %s", e)
            raise e

    return response


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--agreement-id",
        "-aid",
        help="Provide agreement ID to describe agreement status",
        required=True,
    )
    args = parser.parse_args()

    response = get_agreement_information(agreement_id=args.agreement_id)

    helper.pretty_print_datetime(response)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約から製品とオファーの詳細を取得する
<a name="marketplace-agreement_GetProductAndOfferDetailFromAgreement_python_3_topic"></a>

次のコード例は、契約から製品とオファーの詳細を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to get product and offer details in a given agreement
AG-10
"""

import argparse
import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

mpa_client = boto3.client("marketplace-agreement")
mpc_client = boto3.client("marketplace-catalog")

logger = logging.getLogger(__name__)


def get_agreement_information(agreement_id):
    """
    Returns information about a given agreement
    Args: agreement_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        agreement = mpa_client.describe_agreement(agreementId=agreement_id)

        return agreement

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", agreement_id)
        else:
            logger.error("Unexpected error: %s", e)


def get_entity_information(entity_id):
    """
    Returns information about a given entity
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of entity information
    """

    try:
        response = mpc_client.describe_entity(
            Catalog="AWSMarketplace",
            EntityId=entity_id,
        )

        return response

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Entity with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def get_agreement_components(agreement_id):
    agreement_component_list = []

    agreement = get_agreement_information(agreement_id)

    if agreement is not None:
        productIds = []
        for resource in agreement["proposalSummary"]["resources"]:
            productIds.append(resource["id"])

        for product_id in productIds:
            product_document = get_entity_information(product_id)

            product_document_dict = {}
            product_document_dict["product_id"] = product_id
            product_document_dict["document"] = product_document
            agreement_component_list.append(product_document_dict)

        offerId = agreement["proposalSummary"]["offerId"]

        offer_document = get_entity_information(offerId)

        offer_document_dict = {}
        offer_document_dict["offer_id"] = offerId
        offer_document_dict["document"] = offer_document
        agreement_component_list.append(offer_document_dict)

        return agreement_component_list

    else:
        print("Agreement with ID " + args.agreement_id + " is not found")


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--agreement_id",
        "-aid",
        help="Provide agreement ID to search for product and offer detail",
        required=True,
    )
    args = parser.parse_args()

    product_offer_detail = get_agreement_components(agreement_id=args.agreement_id)

    helper.pretty_print_datetime(product_offer_detail)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約の EULA を取得する
<a name="marketplace-agreement_GetAgreementTermsEula_python_3_topic"></a>

次のコード例は、クエリの結果を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the EULA I have entered into with my customer via the agreement
AG-18
"""

import json
import logging
import os

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# agreement id
AGREEMENT_ID = "agmt-1111111111111111111111111"

# to use sample file or not
USE_SAMPLE_FILE = False
SAMPLE_FILE_NAME = "mockup_agreement_terms.json"

# attribute name
ROOT_ELEM = "acceptedTerms"
TERM_NAME = "legalTerm"
CONFIG_ELEM = "configuration"
ATTRIBUTE_NAME = "documents"


def get_agreement_information(mp_client, entity_id):
    """
    Returns customer AWS Account id about a given agreement
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        if USE_SAMPLE_FILE:
            sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME)
            terms = open_json_file(sample_file)
        else:
            terms = mp_client.get_agreement_terms(agreementId=entity_id)

        legalEulaArray = []
        for term in terms[ROOT_ELEM]:
            if TERM_NAME in term and ATTRIBUTE_NAME in term[TERM_NAME]:
                docs = term[TERM_NAME][ATTRIBUTE_NAME]
                for doc in docs:
                    if "type" in doc:
                        legalEulaArray.append(doc)
        return legalEulaArray

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID))

    # open json file from path


def open_json_file(filename):
    with open(filename, "r") as f:
        return json.load(f)


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAgreementTerms](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。**

### 契約の自動更新条件を取得する
<a name="marketplace-agreement_GetAgreementAutoRenewal_python_3_topic"></a>

次のコード例は、契約の自動更新条件を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the auto-renewal status of the agreement
AG-15
"""

import json
import logging
import os
import utils.helpers as helper


import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# agreement id
AGREEMENT_ID = "agmt-11111111111111111111"

# to use sample file or not
USE_SAMPLE_FILE = False
SAMPLE_FILE_NAME = "mockup_agreement_terms.json"

# attribute name
ROOT_ELEM = "acceptedTerms"
TERM_NAME = "renewalTerm"
CONFIG_ELEM = "configuration"
ATTRIBUTE_NAME = "enableAutoRenew"


def get_agreement_information(mp_client, entity_id):
    """
    Returns customer AWS Account id about a given agreement
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        if USE_SAMPLE_FILE:
            sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME)
            terms = open_json_file(sample_file)
        else:
            terms = mp_client.get_agreement_terms(agreementId=entity_id)

        auto_renewal = "No Auto Renewal"
        for term in terms[ROOT_ELEM]:
            if TERM_NAME in term:
                if CONFIG_ELEM in term[TERM_NAME]:
                    auto_renewal = term[TERM_NAME][CONFIG_ELEM][ATTRIBUTE_NAME]
                    break
        return auto_renewal

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    agreement = get_agreement_information(mp_client, AGREEMENT_ID)

    if agreement is not None:
        print(f"Auto Renewal is {agreement}")
    else:
        print("Agreement with ID " + AGREEMENT_ID + " is not found")


# open json file from path
def open_json_file(filename):
    with open(filename, "r") as f:
        return json.load(f)


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAgreementTerms](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。**

### 契約の購入済みディメンションを取得する
<a name="marketplace-agreement_GetAgreementTermsDimensionPurchased_python_3_topic"></a>

次のコード例は、契約の購入済みディメンションを取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the dimensions the buyer has purchased from me via the agreement
AG-28
"""

import json
import logging
import os

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# agreement id
AGREEMENT_ID = "agmt-1111111111111111111111111"

# to use sample file or not
USE_SAMPLE_FILE = False
SAMPLE_FILE_NAME = "mockup_agreement_terms.json"

# attribute name
ROOT_ELEM = "acceptedTerms"
TERM_NAME = "configurableUpfrontPricingTerm"
CONFIG_ELEM = "configuration"
ATTRIBUTE_NAME = "selectorValue"


def get_agreement_information(mp_client, entity_id):
    """
    Returns customer AWS Account id about a given agreement
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        if USE_SAMPLE_FILE:
            sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME)
            terms = open_json_file(sample_file)
        else:
            terms = mp_client.get_agreement_terms(agreementId=entity_id)

        dimensionKeys = []

        for term in terms[ROOT_ELEM]:
            if TERM_NAME in term:
                if CONFIG_ELEM in term[TERM_NAME]:
                    confParam = term[TERM_NAME][CONFIG_ELEM]
                    if ATTRIBUTE_NAME in confParam:
                        if "dimensions" in confParam:
                            for dimension in confParam["dimensions"]:
                                if "dimensionKey" in dimension:
                                    dimensionKey = dimension["dimensionKey"]
                                    print(f"Dimension Key: {dimensionKey}")
                                    dimensionKeys.append(dimensionKey)
        return dimensionKeys

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID))

    # open json file from path


def open_json_file(filename):
    with open(filename, "r") as f:
        return json.load(f)


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAgreementTerms](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。**

### 契約の購入済み各ディメンションのインスタンスを取得する
<a name="marketplace-agreement_GetAgreementTermsDimensionInstances_python_3_topic"></a>

次のコード例は、契約の購入済み各ディメンションのインスタンスを取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain instances of each dimension that buyer has purchased in the agreement
AG-30
"""

import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# agreement id
AGREEMENT_ID = "agmt-1111111111111111111111111"

# attribute name
ROOT_ELEM = "acceptedTerms"
TERM_NAME = "configurableUpfrontPricingTerm"
CONFIG_ELEM = "configuration"
ATTRIBUTE_NAME = "selectorValue"

logger = logging.getLogger(__name__)


def get_agreement_information(mp_client, entity_id):
    """
    Returns customer AWS Account id about a given agreement
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        terms = mp_client.get_agreement_terms(agreementId=entity_id)
        dimensionKeyValueMap = {}
        for term in terms[ROOT_ELEM]:
            if TERM_NAME in term:
                if CONFIG_ELEM in term[TERM_NAME]:
                    confParam = term[TERM_NAME][CONFIG_ELEM]
                    if ATTRIBUTE_NAME in confParam:
                        selectValue = confParam["selectorValue"]
                        dimensionKeyValueMap["selectorValue"] = selectValue
                        if "dimensions" in confParam:
                            dimensionKeyValueMap["dimensions"] = confParam["dimensions"]
                            """
                            for dimension in confParam['dimensions']:
                                if 'dimensionKey' in dimension:

                                    dimensionValue = dimension['dimensionValue']
                                    dimensionKey = dimension['dimensionKey']
                                    print(f"Selector: {selectValue}, Dimension Key: {dimensionKey}, Dimension Value: {dimensionValue}")
                                    dimensionKeyValueMap[dimensionKey] = dimensionValue
                            """
        return dimensionKeyValueMap

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID))


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAgreementTerms](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。**

### 契約の支払いスケジュールを取得する
<a name="marketplace-agreement_GetAgreementTermsPaymentSchedule_python_3_topic"></a>

次のコード例は、契約の支払いスケジュールを取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the payment schedule I have agreed to with the agreement, including the invoice date and invoice amount
AG-17
"""

import json
import logging
import os

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# agreement id
AGREEMENT_ID = "agmt-1111111111111111111111111"

# to use sample file or not
USE_SAMPLE_FILE = False
SAMPLE_FILE_NAME = "mockup_agreement_terms.json"

# attribute name
ROOT_ELEM = "acceptedTerms"
TERM_NAME = "paymentScheduleTerm"
CONFIG_ELEM = "configuration"
ATTRIBUTE_NAME = "selectorValue"


def get_agreement_information(mp_client, entity_id):
    """
    Returns customer AWS Account id about a given agreement
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        if USE_SAMPLE_FILE:
            sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME)
            terms = open_json_file(sample_file)
        else:
            terms = mp_client.get_agreement_terms(agreementId=entity_id)

        paymentScheduleArray = []
        currencyCode = ""
        for term in terms[ROOT_ELEM]:
            if TERM_NAME in term:
                paymentSchedule = term[TERM_NAME]
                if "currencyCode" in paymentSchedule:
                    currencyCode = paymentSchedule["currencyCode"]
                if "schedule" in paymentSchedule:
                    for sch in paymentSchedule["schedule"]:
                        if "chargeDate" in sch:
                            chargeDate = sch["chargeDate"]
                            chargeAmount = sch["chargeAmount"]
                            # print(f"chargeDate: {chargeDate}, chargeAmount: {chargeAmount}")
                            schedule = {
                                "currencyCode": currencyCode,
                                "chargeDate": chargeDate,
                                "chargeAmount": chargeAmount,
                            }
                            paymentScheduleArray.append(schedule)

        return paymentScheduleArray

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID))

    # open json file from path


def open_json_file(filename):
    with open(filename, "r") as f:
        return json.load(f)


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAgreementTerms](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。**

### 契約のディメンションあたりの料金を取得する
<a name="marketplace-agreement_GetAgreementTermsPricingEachDimension_python_3_topic"></a>

次のコード例は、契約のディメンションあたりの料金を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain pricing per each dimension in the agreement
AG-29
"""

import json
import logging
import os

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# agreement id
AGREEMENT_ID = "agmt-1111111111111111111111111"

# to use sample file or not
USE_SAMPLE_FILE = False
SAMPLE_FILE_NAME = "mockup_agreement_terms.json"

# attribute name
ROOT_ELEM = "acceptedTerms"
TERM_NAME = "configurableUpfrontPricingTerm"
CONFIG_ELEM = "configuration"
ATTRIBUTE_NAME = "selectorValue"

TERMS_TO_SEARCH = [
    "configurableUpfrontPricingTerm",
    "usageBasedPricingTerm",
    "fixedUpfrontPricingTerm",
]


def get_agreement_information(mp_client, entity_id):
    """
    Returns customer AWS Account id about a given agreement
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        if USE_SAMPLE_FILE:
            sample_file = os.path.join(os.path.dirname(__file__), SAMPLE_FILE_NAME)
            terms = open_json_file(sample_file)
        else:
            terms = mp_client.get_agreement_terms(agreementId=entity_id)

        dimentions = []
        for term in terms[ROOT_ELEM]:
            for t in TERMS_TO_SEARCH:
                rateInfo = []
                if t in term:
                    if "type" in term[t]:
                        rateInfo.append(term[t]["type"])
                    if "currencyCode" in term[t]:
                        rateInfo.append(term[t]["currencyCode"])
                    if "rateCards" in term[t]:
                        rateInfo.append(term[t]["rateCards"])
                    dimentions.append(rateInfo)
        return dimentions

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreement_information(mp_client, AGREEMENT_ID))

    # open json file from path


def open_json_file(filename):
    with open(filename, "r") as f:
        return json.load(f)


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAgreementTerms](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。**

### 契約の料金タイプを取得する
<a name="marketplace-agreement_GetAgreementPricingType_python_3_topic"></a>

次のコード例は、契約の料金タイプを取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the pricing type of the agreement (contract, FPS, metered, free etc.)
AG-16
"""

import json
import logging

import boto3
from botocore.exceptions import ClientError

# To search by offer id: OfferId; by product id: ResourceIdentifier; by product type: ResourceType
idType = "OfferId"

# replace id value as needed
idValue = "offer-1111111111111"

MAX_PAGE_RESULTS = 10

# catalog; switch to AWSMarketplace for release
AWSMPCATALOG = "AWSMarketplace"

# product types

SaaSProduct = "SaaSProduct"
AmiProduct = "AmiProduct"
MLProduct = "MachineLearningProduct"
ContainerProduct = "ContainerProduct"
DataProduct = "DataProduct"
ProServiceProduct = "ProfessionalServicesProduct"
AiqProduct = "AiqProduct"

# Define pricing types
CCP = "CCP"
Annual = "Annual"
Contract = "Contract"
SFT = "SaaS Freee Trial"
HMA = "Hourly and Monthly Agreements"
Hourly = "Hourly"
Monthly = "Monthly"
AFPS = "Annual FPS"
CFPS = "Contract FPS"
CCPFPS = "CCP with FPS"
BYOL = "BYOL"
Free = "Free"
FTH = "Free Trials and Hourly"

# Define Agreement Term Types
legal = ["LegalTerm"]
config = ["ConfigurableUpfrontPricingTerm"]
usage = ["UsageBasedPricingTerm"]
config_usage = ["ConfigurableUpfrontPricingTerm", "UsageBasedPricingTerm"]
freeTrial = ["FreeTrialPricingTerm"]
recur = ["RecurringPaymentTerm"]
usage_recur = ("UsageBasedPricingTerm", "RecurringPaymentTerm")
fixed_payment = ["FixedUpfrontPricingTerm", "PaymentScheduleTerm"]
fixed_payment_usage = [
    "FixedUpfrontPricingTerm",
    "PaymentScheduleTerm",
    "UsageBasedPricingTerm",
]
byol = ["ByolPricingTerm"]
freeTrial_usage = ("FreeTrialPricingTerm", "UsageBasedPricingTerm")
all_agreement_types_combination = (
    legal,
    config,
    usage,
    config_usage,
    freeTrial,
    recur,
    usage_recur,
    fixed_payment,
    fixed_payment_usage,
    byol,
    freeTrial_usage,
)


# get pricing type method given product type, agreement temr type and offer type if needed
def get_pricing_type(product_type, agreement_term_type, offer_type):
    pricing_types = {
        (SaaSProduct, frozenset(config_usage), frozenset("")): CCP,
        (DataProduct, frozenset(config_usage), frozenset("")): CCP,
        (ContainerProduct, frozenset(config), frozenset(config_usage)): Annual,
        (AmiProduct, frozenset(config), frozenset(config_usage)): Annual,
        (MLProduct, frozenset(config), frozenset(config_usage)): Annual,
        (ContainerProduct, frozenset(config), frozenset(config)): Contract,
        (AmiProduct, frozenset(config), frozenset(config)): Contract,
        (SaaSProduct, frozenset(config), frozenset("")): Contract,
        (DataProduct, frozenset(config), frozenset("")): Contract,
        (AiqProduct, frozenset(config), frozenset("")): Contract,
        (ProServiceProduct, frozenset(config), frozenset("")): Contract,
        (SaaSProduct, frozenset(freeTrial), frozenset("")): SFT,
        (AmiProduct, frozenset(usage_recur), frozenset("")): HMA,
        (SaaSProduct, frozenset(usage), frozenset("")): Hourly,
        (AmiProduct, frozenset(usage), frozenset("")): Hourly,
        (ContainerProduct, frozenset(usage), frozenset("")): Hourly,
        (MLProduct, frozenset(usage), frozenset("")): Hourly,
        (ContainerProduct, frozenset(recur), frozenset("")): Monthly,
        (AmiProduct, frozenset(recur), frozenset("")): Monthly,
        (
            ContainerProduct,
            frozenset(fixed_payment),
            frozenset(fixed_payment_usage),
        ): AFPS,
        (AmiProduct, frozenset(fixed_payment), frozenset(fixed_payment_usage)): AFPS,
        (MLProduct, frozenset(fixed_payment), frozenset("")): AFPS,
        (ContainerProduct, frozenset(fixed_payment), frozenset(fixed_payment)): CFPS,
        (AmiProduct, frozenset(fixed_payment), frozenset(fixed_payment)): CFPS,
        (SaaSProduct, frozenset(fixed_payment), frozenset("")): CFPS,
        (DataProduct, frozenset(fixed_payment), frozenset("")): CFPS,
        (AiqProduct, frozenset(fixed_payment), frozenset("")): CFPS,
        (ProServiceProduct, frozenset(fixed_payment), frozenset("")): CFPS,
        (SaaSProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS,
        (DataProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS,
        (AiqProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS,
        (ProServiceProduct, frozenset(fixed_payment_usage), frozenset("")): CCPFPS,
        (AmiProduct, frozenset(byol), frozenset("")): BYOL,
        (SaaSProduct, frozenset(byol), frozenset("")): BYOL,
        (ProServiceProduct, frozenset(byol), frozenset("")): BYOL,
        (AiqProduct, frozenset(byol), frozenset("")): BYOL,
        (MLProduct, frozenset(byol), frozenset("")): BYOL,
        (ContainerProduct, frozenset(byol), frozenset("")): BYOL,
        (DataProduct, frozenset(byol), frozenset("")): BYOL,
        (ContainerProduct, frozenset(legal), frozenset("")): Free,
        (AmiProduct, frozenset(freeTrial_usage), frozenset("")): FTH,
        (ContainerProduct, frozenset(freeTrial_usage), frozenset("")): FTH,
        (MLProduct, frozenset(freeTrial_usage), frozenset("")): FTH,
    }

    key = (product_type, agreement_term_type, offer_type)
    if key in pricing_types:
        return pricing_types[key]
    else:
        return "Unknown"


# Example usage for testing purpose
"""
product_type = SaaSProduct
agreement_term_type = frozenset(config_usage)
offer_type = frozenset('')
pricing_type = get_pricing_type(product_type, agreement_term_type, offer_type)
print("pricing type = " + pricing_type)  # Output: CCP
"""


# check if offer term types are needed; if Y, needed
def get_offer_term_type(product_type, agreement_term_type):
    offer_term_types = {
        (ContainerProduct, frozenset(config)): "Y",
        (AmiProduct, frozenset(config)): "Y",
        (ContainerProduct, frozenset(fixed_payment)): "Y",
        (AmiProduct, frozenset(fixed_payment)): "Y",
        (AmiProduct, frozenset(fixed_payment), frozenset(fixed_payment)): "Y",
    }

    key = (product_type, agreement_term_type)
    if key in offer_term_types:
        return offer_term_types[key]
    else:
        return


logger = logging.getLogger(__name__)


def get_agreements(mp_client):
    AgreementSummaryList = []
    partyTypes = ["Proposer"]
    for value in partyTypes:
        try:
            agreement = mp_client.search_agreements(
                catalog=AWSMPCATALOG,
                maxResults=MAX_PAGE_RESULTS,
                filters=[
                    {"name": "PartyType", "values": [value]},
                    {"name": idType, "values": [idValue]},
                    {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                ],
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise

        AgreementSummaryList.extend(agreement["agreementViewSummaries"])

        while "nextToken" in agreement and agreement["nextToken"] is not None:
            try:
                agreement = mp_client.search_agreements(
                    catalog=AWSMPCATALOG,
                    maxResults=MAX_PAGE_RESULTS,
                    nextToken=agreement["nextToken"],
                    filters=[
                        {"name": "PartyType", "values": [value]},
                        {"name": idType, "values": [idValue]},
                        {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                    ],
                )
            except ClientError as e:
                logger.error("Could not complete search_agreements request.")
                raise

            AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    return AgreementSummaryList


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace Catalog.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    # find all agreements matching the specified idType and idValue
    agreements = get_agreements(mp_client)

    for item in agreements:
        pricingType = ""
        agreement_id = item["agreementId"]

        # get term types inside offer
        offer_term_types = get_offer_term_types(item)

        # even though multiple product types are allowed for one agreement, only need the first one
        productType = item["resourceSummaries"][0]["resourceType"]

        # get agreement terms types
        agreementTerm = mp_client.get_agreement_terms(agreementId=agreement_id)

        agreementTermTypes = get_agreement_term_types(agreementTerm)

        # match with agreement term type group
        matchedTermType = getMatchedTermTypesCombination(agreementTermTypes)

        # check if offer term type is needed.
        offer_term_type_needed = get_offer_term_type(
            productType, frozenset(matchedTermType)
        )

        # get pricing type given product type, agreement term types and offer type if needed;
        # one excpetion is Container with Legal term. LegalTerm needs to be the only term present
        if offer_term_type_needed is not None:
            matchedOfferTermTypes = getMatchedTermTypesCombination(offer_term_types)
            print(f"matchedOfferTermType = {matchedOfferTermTypes}")
            pricingType = get_pricing_type(
                productType,
                frozenset(matchedTermType),
                frozenset(matchedOfferTermTypes),
            )
        elif set(matchedTermType) == set(legal):
            pricingType = Free
        else:
            pricingType = get_pricing_type(
                productType, frozenset(matchedTermType), frozenset("")
            )

        print(
            f"agreementId={agreement_id};productType={productType}; agreementTermTypes={agreementTermTypes}; matchedTermType={matchedTermType}; offerTermTypeNeeded={offer_term_type_needed}; offer_term_types={offer_term_types}"
        )
        print(f"pricing type={pricingType}")


def getMatchedTermTypesCombination(agreementTermTypes):
    matchedCombination = ()
    for element in all_agreement_types_combination:
        if check_elements(agreementTermTypes, element):
            matchedCombination = element
    return matchedCombination


def get_offer_term_types(item):
    offer_id = item["agreementTokenSummary"]["offerId"]
    mp_catalogAPI_client = boto3.client("marketplace-catalog")
    offer_document = get_entity_information(mp_catalogAPI_client, offer_id)
    offerDetail = offer_document["Details"]
    offerDetail_json_object = json.loads(offerDetail)
    offer_term_types = [term["Type"] for term in offerDetail_json_object["Terms"]]
    return offer_term_types


# make sure all elements in array2 exist in array1
def check_elements(array1, array2):
    for element in array2:
        if element not in array1:
            return False
    return True


def get_entity_information(mp_client, entity_id):
    """
    Returns information about a given entity
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of entity information
    """

    try:
        response = mp_client.describe_entity(
            Catalog="AWSMarketplace",
            EntityId=entity_id,
        )

        return response

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Entity with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def get_agreement_term_types(agreementTerm):
    types = []
    for term in agreementTerm["acceptedTerms"]:
        for value in term.values():
            if isinstance(value, dict) and "type" in value:
                types.append(value["type"])
    return types


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約の製品タイプを取得する
<a name="marketplace-agreement_GetAgreementProductType_python_3_topic"></a>

次のコード例は、契約の製品タイプを取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the Product Type of the product the agreement was created on
AG-11
"""

import logging

import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

# agreement id
AGREEMENT_ID = "agmt-1111111111111111111111111"


def get_agreement_information(mp_client, entity_id):
    """
    Returns information about a given agreement
    Args: entity_id str: Entity to return
    Returns: dict: Dictionary of agreement information
    """

    try:
        agreement = mp_client.describe_agreement(agreementId=entity_id)

        return agreement

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", entity_id)
        else:
            logger.error("Unexpected error: %s", e)


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for offer and product details in a given agreement by agreement id.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    agreement = get_agreement_information(mp_client, AGREEMENT_ID)

    if agreement is not None:
        productHash = {}
        for resource in agreement["resourceSummaries"]:
            productHash[resource["resourceId"]] = resource["resourceType"]

        for key, value in productHash.items():
            print(f"Product ID: {key}  |  Product Type: {value}")
    else:
        print("Agreement with ID " + AGREEMENT_ID + " is not found")


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約のステータスを取得する
<a name="marketplace-agreement_GetAgreementStatus_python_3_topic"></a>

次のコード例は、契約のステータスを取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to get all agreement status
AG-13

Example Usage: python3 get_agreement_status.py --agreement-id <agreement-id>
"""

import argparse
import logging

import boto3
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")

logger = logging.getLogger(__name__)


def get_agreement(agreement_id):
    try:
        response = mp_client.describe_agreement(agreementId=agreement_id)
        return response
    except ClientError as e:
        logger.error(f"Could not complete search_agreements request. {e}")

    return None


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--agreement-id",
        "-aid",
        help="Provide agreement ID to describe agreement status",
        required=True,
    )
    args = parser.parse_args()

    response = get_agreement(agreement_id=args.agreement_id)

    if response is not None:
        print(f"Agreement status: {response['status']}")
    else:
        print(f"No agreement found for {args.agreement_id}")
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeAgreement](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/DescribeAgreement)」を参照してください。**

### 契約のサポート条件を取得する
<a name="marketplace-agreement_GetAgreementTermsSupportTerm_python_3_topic"></a>

次のコード例は、 契約のサポート条件を取得する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Obtain the support and refund policy I have provided to the customer for an agreement
AG-19

Example Usage: python3 get_agreement_support_terms.py --agreement-id <agreement-id>
"""

import argparse
import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)

mp_client = boto3.client("marketplace-agreement")


def get_agreement_terms(agreement_id):
    try:
        agreement = mp_client.get_agreement_terms(agreementId=agreement_id)
        return agreement

    except ClientError as e:
        if e.response["Error"]["Code"] == "ResourceNotFoundException":
            logger.error("Agreement with ID %s not found.", agreement_id)

        else:
            logger.error("Unexpected error: %s", e)

    return None


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--agreement-id",
        "-aid",
        help="Provide agreement ID to describe agreement status",
        required=True,
    )
    args = parser.parse_args()

    agreement = get_agreement_terms(agreement_id=args.agreement_id)

    if agreement is not None:
        support_found = False

        for term in agreement["acceptedTerms"]:
            if "supportTerm" in term.keys():
                helper.pretty_print_datetime(term)
                support_found = True

        if not support_found:
            print(f"No support term found for agreement: {args.agreement_id}")
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAgreementTerms](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/GetAgreementTerms)」を参照してください。**

### アカウント ID で契約を検索する
<a name="marketplace-agreement_SearchAgreementsByAccountId_python_3_topic"></a>

次のコード例は、アカウント ID で契約を検索する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to get agreement by customer AWS account ID
AG-02
"""

import argparse
import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")
logger = logging.getLogger(__name__)

MAX_PAGE_RESULTS = 10


def get_agreements(account_id):
    AgreementSummaryList = []

    try:
        agreement = mp_client.search_agreements(
            catalog="AWSMarketplace",
            maxResults=MAX_PAGE_RESULTS,
            filters=[
                {"name": "PartyType", "values": ["Proposer"]},
                {"name": "AcceptorId", "values": [account_id]},
                {"name": "AgreementType", "values": ["PurchaseAgreement"]},
            ],
        )
    except ClientError as e:
        logger.error("Could not complete search_agreements request.")
        raise e

    AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    while "nextToken" in agreement and agreement["nextToken"] is not None:
        try:
            agreement = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                nextToken=agreement["nextToken"],
                filters=[
                    {"name": "PartyType", "values": ["Proposer"]},
                    {"name": "AcceptorId", "values": [account_id]},
                    {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                ],
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise e

        AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    return AgreementSummaryList


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--account_id",
        "-aid",
        help="Provide accepting account ID to search for agreements",
        required=True,
    )
    args = parser.parse_args()

    response = get_agreements(account_id=args.account_id)

    helper.pretty_print_datetime(response)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

### 契約 ID で契約を検索する
<a name="marketplace-agreement_SearchAgreementsById_python_3_topic"></a>

次のコード例は、契約 ID で契約を検索する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to search for agreements give id information
AG-02-A
"""


import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

# To search by offer id: OfferId; by product id: ResourceIdentifier; by product type: ResourceType
idType = "ResourceType"

# replace id value as needed
idValue = "SaaSProduct"

MAX_PAGE_RESULTS = 10

logger = logging.getLogger(__name__)


def get_agreements(mp_client):
    AgreementSummaryList = []
    partyTypes = ["Proposer"]
    for value in partyTypes:
        try:
            agreement = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                filters=[
                    {"name": "PartyType", "values": [value]},
                    {"name": idType, "values": [idValue]},
                    {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                ],
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise e

        AgreementSummaryList.extend(agreement["agreementViewSummaries"])

        while "nextToken" in agreement and agreement["nextToken"] is not None:
            try:
                agreement = mp_client.search_agreements(
                    catalog="AWSMarketplace",
                    maxResults=MAX_PAGE_RESULTS,
                    nextToken=agreement["nextToken"],
                    filters=[
                        {"name": "PartyType", "values": [value]},
                        {"name": idType, "values": [idValue]},
                        {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                    ],
                )
            except ClientError as e:
                logger.error("Could not complete search_agreements request.")
                raise e

            AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    return AgreementSummaryList


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace Catalog.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreements(mp_client))


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

### 終了日で契約を検索する
<a name="marketplace-agreement_SearchAgreementsByEndDate_python_3_topic"></a>

次のコード例は、終了日で契約を検索する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to search for agreement information before or after end date
AG-03
"""

import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")

# change to 'AfterEndTime' if after endtime is desired
beforeOrAfterEndtimeFilterName = "BeforeEndTime"

# Make sure to use the same date format as below
cutoffDate = "2322-11-18T00:00:00Z"

MAX_PAGE_RESULTS = 10

logger = logging.getLogger(__name__)


def get_agreements():
    AgreementSummaryList = []

    try:
        agreement = mp_client.search_agreements(
            catalog="AWSMarketplace",
            maxResults=MAX_PAGE_RESULTS,
            filters=[
                {"name": "PartyType", "values": ["Proposer"]},
                {"name": beforeOrAfterEndtimeFilterName, "values": [cutoffDate]},
                {"name": "AgreementType", "values": ["PurchaseAgreement"]},
            ],
        )
    except ClientError as e:
        logger.error("Could not complete search_agreements request.")
        raise

    AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    while "nextToken" in agreement:
        try:
            agreement = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                nextToken=agreement["nextToken"],
                filters=[
                    {"name": "PartyType", "values": ["Proposer"]},
                    {
                        "name": beforeOrAfterEndtimeFilterName,
                        "values": [cutoffDate],
                    },
                    {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                ],
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise

        AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    return AgreementSummaryList


if __name__ == "__main__":
    agreements = get_agreements()
    helper.pretty_print_datetime(agreements)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

### オファー ID で契約を検索する
<a name="marketplace-agreement_SearchAgreementsByOfferId_python_3_topic"></a>

次のコード例は、オファー ID で契約を検索する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to search for agreements by offer id
AG-0
"""

import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

# offer id to search by
offerId = "1111111111111111111111111"

MAX_PAGE_RESULTS = 10

logger = logging.getLogger(__name__)


def get_agreements(mp_client):
    AgreementSummaryList = []
    partyTypes = ["Proposer"]
    for value in partyTypes:
        try:
            agreement = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                filters=[
                    {"name": "PartyType", "values": [value]},
                    {"name": "OfferId", "values": [offerId]},
                    {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                ],
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise

        AgreementSummaryList.extend(agreement["agreementViewSummaries"])

        while "nextToken" in agreement and agreement["nextToken"] is not None:
            try:
                agreement = mp_client.search_agreements(
                    catalog="AWSMarketplace",
                    maxResults=MAX_PAGE_RESULTS,
                    nextToken=agreement["nextToken"],
                    filters=[
                        {"name": "PartyType", "values": [value]},
                        {"name": "OfferId", "values": [offerId]},
                        {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                    ],
                )
            except ClientError as e:
                logger.error("Could not complete search_agreements request.")
                raise

            AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    return AgreementSummaryList


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement by offer id.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreements(mp_client))


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

### 製品 ID で契約を検索する
<a name="marketplace-agreement_SearchAgreementsByProductId_python_3_topic"></a>

次のコード例は、製品 ID で契約を検索する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to search for agreement by product id
AG-02
"""

import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

# product id to search by
resourceId = "prod-1111111111111"

MAX_PAGE_RESULTS = 10

logger = logging.getLogger(__name__)


def get_agreements(mp_client):
    AgreementSummaryList = []
    partyTypes = ["Proposer"]
    for value in partyTypes:
        try:
            agreement = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                filters=[
                    {"name": "PartyType", "values": [value]},
                    {"name": "ResourceIdentifier", "values": [resourceId]},
                    {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                ],
            )
        except ClientError as e:
            logger.error("Could not complete list_entities request.")
            raise

        AgreementSummaryList.extend(agreement["agreementViewSummaries"])

        while "nextToken" in agreement:
            try:
                agreement = mp_client.search_agreements(
                    catalog="AWSMarketplace",
                    maxResults=MAX_PAGE_RESULTS,
                    nextToken=agreement["nextToken"],
                    filters=[
                        {"name": "PartyType", "values": [value]},
                        {"name": "ResourceIdentifier", "values": [resourceId]},
                        {"name": "AgreementType", "values": ["PurchaseAgreement"]},
                    ],
                )
            except ClientError as e:
                logger.error("Could not complete search_agreements request.")
                raise

            AgreementSummaryList.extend(agreement["agreementViewSummaries"])

    return AgreementSummaryList


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Looking for an agreement in the AWS Marketplace Catalog.")
    print("-" * 88)

    mp_client = boto3.client("marketplace-agreement")

    helper.pretty_print_datetime(get_agreements(mp_client))


if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

### ステータスで契約を検索する
<a name="marketplace-agreement_SearchAgreementsByByStatus_python_3_topic"></a>

次のコード例は、ステータスで契約を検索する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[AWS Marketplace API リファレンスコードライブラリ](https://github.com/aws-samples/aws-marketplace-reference-code/blob/main/python#agreement-api-reference-code)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) to filter agreements by status
AG-04

Example Usage: python3 search_agreements_by_status.py
"""

import logging

import boto3
import utils.helpers as helper
from botocore.exceptions import ClientError

mp_client = boto3.client("marketplace-agreement")

logger = logging.getLogger(__name__)

MAX_PAGE_RESULTS = 10

party_type_list = ["Proposer"]
agreement_type_list = ["PurchaseAgreement"]

# Accepted values: "ACTIVE", "TERMINATED", "CANCELED", "EXPIRED", "REPLACED", "RENEWED"
status_list = ["ACTIVE"]

filter_list = [
    {"name": "PartyType", "values": party_type_list},
    {"name": "AgreementType", "values": agreement_type_list},
    {"name": "Status", "values": status_list},
]

agreement_results_list = []


def get_agreements(filter_list=filter_list):
    try:
        agreements = mp_client.search_agreements(
            catalog="AWSMarketplace",
            maxResults=MAX_PAGE_RESULTS,
            filters=filter_list,
        )
    except ClientError as e:
        logger.error("Could not complete search_agreements request.")
        raise e

    agreement_results_list.extend(agreements["agreementViewSummaries"])

    while "nextToken" in agreements and agreements["nextToken"] is not None:
        try:
            agreements = mp_client.search_agreements(
                catalog="AWSMarketplace",
                maxResults=MAX_PAGE_RESULTS,
                nextToken=agreements["nextToken"],
                filters=filter_list,
            )
        except ClientError as e:
            logger.error("Could not complete search_agreements request.")
            raise e

        agreement_results_list.extend(agreements["agreementViewSummaries"])

    helper.pretty_print_datetime(agreement_results_list)
    return agreement_results_list


if __name__ == "__main__":
    agreements_list = get_agreements(filter_list)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[SearchAgreements](https://docs.aws.amazon.com/goto/boto3/marketplace-agreement-2020-03-01/SearchAgreements)」を参照してください。**

# SDK for Python (Boto3) を使用した Amazon MSK の例
<a name="python_3_kafka_code_examples"></a>

次のコード例は、Amazon MSK AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_python_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での Amazon MSK イベントの消費。  

```
import base64

def lambda_handler(event, context):
    # Iterate through keys
    for key in event['records']:
        print('Key:', key)
        # Iterate through records
        for record in event['records'][key]:
            print('Record:', record)
            # Decode base64
            msg = base64.b64decode(record['value']).decode('utf-8')
            print('Message:', msg)
```

# SDK for Python (Boto3) を使用した Neptune の例
<a name="python_3_neptune_code_examples"></a>

次のコード例は、Neptune AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Neptune
<a name="neptune_Hello_python_3_topic"></a>

次のコード例は、Neptune の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
import boto3
from botocore.exceptions import ClientError


def describe_db_clusters(neptune_client):
    """
    Describes the Amazon Neptune DB clusters using a paginator to handle multiple pages.
    Raises ClientError with 'ResourceNotFoundException' if no clusters are found.
    """
    paginator = neptune_client.get_paginator("describe_db_clusters")
    clusters_found = False

    for page in paginator.paginate():
        for cluster in page.get("DBClusters", []):
            clusters_found = True
            print(f"Cluster Identifier: {cluster['DBClusterIdentifier']}")
            print(f"Status: {cluster['Status']}")

    if not clusters_found:
        raise ClientError(
            {
                "Error": {
                    "Code": "ResourceNotFoundException",
                    "Message": "No Neptune DB clusters found."
                }
            },
            operation_name="DescribeDBClusters"
        )

def main():
    """
    Main entry point: creates the Neptune client and calls the describe operation.
    """
    neptune_client = boto3.client("neptune")
    try:
        describe_db_clusters(neptune_client)
    except ClientError as e:
        error_code = e.response["Error"]["Code"]
        if error_code == "ResourceNotFoundException":
            print(f"Resource not found: {e.response['Error']['Message']}")
        else:
            print(f"Unexpected ClientError: {e.response['Error']['Message']}")
    except Exception as e:
        print(f"Unexpected error: {str(e)}")

if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DescribeDBClustersPaginator](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DescribeDBClustersPaginator)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="neptune_Scenario_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Neptune サブネットグループを作成します。
+ Neptune クラスターを作成します。
+ Neptune インスタンスを作成します。
+ Neptune インスタンスのステータスをチェックします。
+ Neptune クラスターの詳細を表示します。
+ Neptune クラスターを停止します。
+ Neptune クラスターを起動します。
+ Neptune アセットを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
import boto3
import time
from botocore.exceptions import ClientError

# Constants used in this scenario
POLL_INTERVAL_SECONDS = 10
TIMEOUT_SECONDS = 1200  # 20 minutes

def delete_db_cluster(neptune_client, cluster_id: str):
    """
    Deletes a Neptune DB cluster and throws exceptions to the caller.

    Args:
        neptune_client (boto3.client): The Neptune client object.
        cluster_id (str): The ID of the Neptune DB cluster to be deleted.

    Raises:
        ClientError: If the delete operation fails.
    """
    request = {
        'DBClusterIdentifier': cluster_id,
        'SkipFinalSnapshot': True
    }

    try:
        print(f"Deleting DB Cluster: {cluster_id}")
        neptune_client.delete_db_cluster(**request)

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "DBClusterNotFoundFault":
            print(f"Cluster '{cluster_id}' not found or already deleted.")
        elif code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't delete DB cluster. {code}: {message}")
        raise

def format_elapsed_time(seconds: int) -> str:
    mins, secs = divmod(seconds, 60)
    hours, mins = divmod(mins, 60)
    return f"{hours:02}:{mins:02}:{secs:02}"


def delete_db_instance(neptune_client, instance_id: str):
    """
    Deletes a Neptune DB instance and waits for its deletion to complete.
    Raises exception to be handled by calling code.
    """
    print(f"Initiating deletion of DB Instance: {instance_id}")
    try:
        neptune_client.delete_db_instance(
            DBInstanceIdentifier=instance_id,
            SkipFinalSnapshot=True
        )

        print(f"Waiting for DB Instance '{instance_id}' to be deleted...")
        waiter = neptune_client.get_waiter('db_instance_deleted')
        waiter.wait(
            DBInstanceIdentifier=instance_id,
            WaiterConfig={
                'Delay': 30,
                'MaxAttempts': 40
            }
        )

        print(f"DB Instance '{instance_id}' successfully deleted.")

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "DBInstanceNotFoundFault":
            print(f"Instance '{instance_id}' not found or already deleted.")
        elif code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't delete DB instance. {code}: {message}")
        raise

def delete_db_subnet_group(neptune_client, subnet_group_name):
    """
    Deletes a Neptune DB subnet group synchronously using Boto3.

    Args:
        neptune_client (boto3.client): The Neptune client.
        subnet_group_name (str): The name of the DB subnet group to delete.

    Raises:
        ClientError: If the delete operation fails.
    """
    delete_group_request = {
        'DBSubnetGroupName': subnet_group_name
    }

    try:
        neptune_client.delete_db_subnet_group(**delete_group_request)
        print(f"️ Deleting Subnet Group: {subnet_group_name}")

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "DBSubnetGroupNotFoundFault":
            print(f"Subnet group '{subnet_group_name}' not found or already deleted.")
        elif code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't delete subnet group. {code}: {message}")
        raise

def wait_for_cluster_status(
        neptune_client,
        cluster_id: str,
        desired_status: str,
        timeout_seconds: int = TIMEOUT_SECONDS,
        poll_interval_seconds: int = POLL_INTERVAL_SECONDS
):
    """
    Waits for a Neptune DB cluster to reach a desired status.

    Args:
        neptune_client (boto3.client): The Amazon Neptune client.
        cluster_id (str): The identifier of the Neptune DB cluster.
        desired_status (str): The target status (e.g., "available", "stopped").
        timeout_seconds (int): Max time to wait in seconds (default: 1200).
        poll_interval_seconds (int): Polling interval in seconds (default: 10).

    Raises:
        RuntimeError: If the desired status is not reached before timeout.
    """
    print(f"Waiting for cluster '{cluster_id}' to reach status '{desired_status}'...")
    start_time = time.time()

    while True:
        # Prepare request object
        describe_cluster_request = {
            'DBClusterIdentifier': cluster_id
        }

        # Call the Neptune API
        response = neptune_client.describe_db_clusters(**describe_cluster_request)
        clusters = response.get('DBClusters', [])
        current_status = clusters[0].get('Status') if clusters else None
        elapsed_seconds = int(time.time() - start_time)

        status_str = current_status if current_status else "Unknown"
        print(
            f"\r Elapsed: {format_elapsed_time(elapsed_seconds):<20}  Cluster status: {status_str:<20}",
            end="", flush=True
        )

        if current_status and current_status.lower() == desired_status.lower():
            print(
                f"\nNeptune cluster reached desired status '{desired_status}' after {format_elapsed_time(elapsed_seconds)}."
            )
            return

        if elapsed_seconds > timeout_seconds:
            raise RuntimeError(f"Timeout waiting for Neptune cluster to reach status: {desired_status}")

        time.sleep(poll_interval_seconds)


def start_db_cluster(neptune_client, cluster_identifier: str):
    """
    Starts an Amazon Neptune DB cluster and waits until it reaches 'available'.

    Args:
        neptune_client (boto3.client): The Neptune client.
        cluster_identifier (str): The DB cluster identifier.

    Raises:
        ClientError: Propagates AWS API issues like resource not found.
        RuntimeError: If cluster doesn't reach 'available' within timeout.
    """
    try:
        # Initial wait in case the cluster was just stopped
        time.sleep(30)
        neptune_client.start_db_cluster(DBClusterIdentifier=cluster_identifier)
    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't start DB cluster. Here's why: {code}: {message}")
        raise

    start_time = time.time()
    paginator = neptune_client.get_paginator('describe_db_clusters')

    while True:
        try:
            pages = paginator.paginate(DBClusterIdentifier=cluster_identifier)
            clusters = []
            for page in pages:
                clusters.extend(page.get('DBClusters', []))
        except ClientError as err:
            code = err.response["Error"]["Code"]
            message = err.response["Error"]["Message"]

            if code == "DBClusterNotFound":
                print(f"Cluster '{cluster_identifier}' not found while polling. It may have been deleted.")
            else:
                print(f"Couldn't describe DB cluster. Here's why: {code}: {message}")
            raise

        status = clusters[0].get('Status') if clusters else None
        elapsed = time.time() - start_time

        print(f"\rElapsed: {int(elapsed)}s – Cluster status: {status}", end="", flush=True)

        if status and status.lower() == 'available':
            print(f"\n🎉 Cluster '{cluster_identifier}' is available.")
            return

        if elapsed > TIMEOUT_SECONDS:
            raise RuntimeError(f"Timeout waiting for cluster '{cluster_identifier}' to become available.")

        time.sleep(POLL_INTERVAL_SECONDS)


def stop_db_cluster(neptune_client, cluster_identifier: str):
    """
    Stops an Amazon Neptune DB cluster and waits until it's fully stopped.

    Args:
        neptune_client (boto3.client): The Neptune client.
        cluster_identifier (str): The DB cluster identifier.

    Raises:
        ClientError: For AWS API errors (e.g., resource not found).
        RuntimeError: If the cluster doesn't stop within the timeout.
    """
    try:
        neptune_client.stop_db_cluster(DBClusterIdentifier=cluster_identifier)
    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't stop DB cluster. Here's why: {code}: {message}")
        raise

    start_time = time.time()
    paginator = neptune_client.get_paginator('describe_db_clusters')

    while True:
        try:
            pages = paginator.paginate(DBClusterIdentifier=cluster_identifier)
            clusters = []
            for page in pages:
                clusters.extend(page.get('DBClusters', []))
        except ClientError as err:
            code = err.response["Error"]["Code"]
            message = err.response["Error"]["Message"]

            if code == "DBClusterNotFound":
                print(f"Cluster '{cluster_identifier}' not found while polling. It may have been deleted.")
            else:
                print(f"Couldn't describe DB cluster. Here's why: {code}: {message}")
            raise

        status = clusters[0].get('Status') if clusters else None
        elapsed = time.time() - start_time

        print(f"\rElapsed: {int(elapsed)}s – Cluster status: {status}", end="", flush=True)

        if status and status.lower() == 'stopped':
            print(f"\nCluster '{cluster_identifier}' is now stopped.")
            return

        if elapsed > TIMEOUT_SECONDS:
            raise RuntimeError(f"Timeout waiting for cluster '{cluster_identifier}' to stop.")

        time.sleep(POLL_INTERVAL_SECONDS)



def describe_db_clusters(neptune_client, cluster_id: str):
    """
    Describes details of a Neptune DB cluster, paginating if needed.

    Args:
        neptune_client (boto3.client): The Neptune client.
        cluster_id (str): The ID of the cluster to describe.

    Raises:
        ClientError: If there's an AWS API error (e.g., cluster not found).
    """
    paginator = neptune_client.get_paginator('describe_db_clusters')

    try:
        pages = paginator.paginate(DBClusterIdentifier=cluster_id)

        found = False
        for page in pages:
            for cluster in page.get('DBClusters', []):
                found = True
                print(f"Cluster Identifier: {cluster.get('DBClusterIdentifier')}")
                print(f"Status: {cluster.get('Status')}")
                print(f"Engine: {cluster.get('Engine')}")
                print(f"Engine Version: {cluster.get('EngineVersion')}")
                print(f"Endpoint: {cluster.get('Endpoint')}")
                print(f"Reader Endpoint: {cluster.get('ReaderEndpoint')}")
                print(f"Availability Zones: {cluster.get('AvailabilityZones')}")
                print(f"Subnet Group: {cluster.get('DBSubnetGroup')}")
                print("VPC Security Groups:")
                for vpc_group in cluster.get('VpcSecurityGroups', []):
                    print(f"  - {vpc_group.get('VpcSecurityGroupId')}")
                print(f"Storage Encrypted: {cluster.get('StorageEncrypted')}")
                print(f"IAM Auth Enabled: {cluster.get('IAMDatabaseAuthenticationEnabled')}")
                print(f"Backup Retention Period: {cluster.get('BackupRetentionPeriod')} days")
                print(f"Preferred Backup Window: {cluster.get('PreferredBackupWindow')}")
                print(f"Preferred Maintenance Window: {cluster.get('PreferredMaintenanceWindow')}")
                print("------")

        if not found:
            # Treat empty response as cluster not found
            raise ClientError(
                {"Error": {"Code": "DBClusterNotFound", "Message": f"No cluster found with ID '{cluster_id}'"}},
                "DescribeDBClusters"
            )

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        elif code == "DBClusterNotFound":
            print(f"Cluster '{cluster_id}' not found. Please verify the cluster ID.")
        else:
            print(f"Couldn't describe DB cluster. Here's why: {code}: {message}")
        raise

def check_instance_status(neptune_client, instance_id: str, desired_status: str):
    """
    Polls the status of a Neptune DB instance until it reaches desired_status.
    Uses pagination via describe_db_instances — even for a single instance.

    Raises:
      ClientError: If describe_db_instances fails (e.g., instance not found).
      RuntimeError: If timeout expires before reaching desired status.
    """
    paginator = neptune_client.get_paginator('describe_db_instances')
    start_time = time.time()

    while True:
        try:
            pages = paginator.paginate(DBInstanceIdentifier=instance_id)
            instances = []
            for page in pages:
                instances.extend(page.get('DBInstances', []))

        except ClientError as err:
            code = err.response["Error"]["Code"]
            message = err.response["Error"]["Message"]

            if code == "DBInstanceNotFound":
                print(f"Instance '{instance_id}' not found. Please verify the instance ID.")
            else:
                print(f"Failed to describe DB instance. {code}: {message}")
            raise

        current_status = instances[0].get('DBInstanceStatus') if instances else None
        elapsed = int(time.time() - start_time)

        print(f"\rElapsed: {format_elapsed_time(elapsed)}  Status: {current_status}", end="", flush=True)

        if current_status and current_status.lower() == desired_status.lower():
            print(f"\nInstance '{instance_id}' reached '{desired_status}' in {format_elapsed_time(elapsed)}.")
            return

        if elapsed > TIMEOUT_SECONDS:
            raise RuntimeError(f"Timeout waiting for '{instance_id}' to reach '{desired_status}'")

        time.sleep(POLL_INTERVAL_SECONDS)


def create_db_instance(neptune_client, db_instance_id: str, db_cluster_id: str) -> str:
    try:
        request = {
            'DBInstanceIdentifier': db_instance_id,
            'DBInstanceClass': 'db.r5.large',
            'Engine': 'neptune',
            'DBClusterIdentifier': db_cluster_id
        }

        print(f"Creating Neptune DB Instance: {db_instance_id}")
        response = neptune_client.create_db_instance(**request)

        instance = response.get('DBInstance')
        if not instance or 'DBInstanceIdentifier' not in instance:
            raise RuntimeError("Instance creation succeeded but no ID returned.")

        print(f"Waiting for DB Instance '{db_instance_id}' to become available...")
        waiter = neptune_client.get_waiter('db_instance_available')
        waiter.wait(
            DBInstanceIdentifier=db_instance_id,
            WaiterConfig={'Delay': 30, 'MaxAttempts': 40}
        )

        print(f"DB Instance '{db_instance_id}' is now available.")
        return instance['DBInstanceIdentifier']

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't create DB instance. Here's why: {code}: {message}")
        raise

    except Exception as e:
        print(f"Unexpected error creating DB instance '{db_instance_id}': {e}")
        raise RuntimeError(f"Unexpected error creating DB instance '{db_instance_id}': {e}") from e


def create_db_cluster(neptune_client, db_name: str) -> str:
    """
    Creates a Neptune DB cluster and returns its identifier.

    Args:
        neptune_client (boto3.client): The Neptune client object.
        db_name (str): The desired cluster identifier.

    Returns:
        str: The DB cluster identifier.

    Raises:
        RuntimeError: For any failure or AWS error, with a user-friendly message.
    """
    request = {
        'DBClusterIdentifier': db_name,
        'Engine': 'neptune',
        'DeletionProtection': False,
        'BackupRetentionPeriod': 1
    }

    try:
        response = neptune_client.create_db_cluster(**request)
        cluster = response.get('DBCluster') or {}

        cluster_id = cluster.get('DBClusterIdentifier')
        if not cluster_id:
            raise RuntimeError("Cluster created but no ID returned.")

        print(f"DB Cluster created: {cluster_id}")
        return cluster_id

    except ClientError as e:
        code = e.response["Error"]["Code"]
        message = e.response["Error"]["Message"]

        if code in ("ServiceQuotaExceededException", "DBClusterQuotaExceededFault"):
            raise RuntimeError("You have exceeded the quota for Neptune DB clusters.") from e
        else:
            raise RuntimeError(f"AWS error [{code}]: {message}") from e

    except Exception as e:
        raise RuntimeError(f"Unexpected error creating DB cluster '{db_name}': {e}") from e

def get_subnet_ids(vpc_id: str) -> list[str]:
    ec2_client = boto3.client('ec2')

    describe_subnets_request = {
        'Filters': [{'Name': 'vpc-id', 'Values': [vpc_id]}]
    }

    response = ec2_client.describe_subnets(**describe_subnets_request)
    subnets = response.get('Subnets', [])
    subnet_ids = [subnet['SubnetId'] for subnet in subnets if 'SubnetId' in subnet]
    return subnet_ids


def get_default_vpc_id() -> str:
    ec2_client = boto3.client('ec2')
    describe_vpcs_request = {
        'Filters': [{'Name': 'isDefault', 'Values': ['true']}]
    }

    response = ec2_client.describe_vpcs(**describe_vpcs_request)
    vpcs = response.get('Vpcs', [])
    if not vpcs:
        raise RuntimeError("No default VPC found in this region.")

    default_vpc_id = vpcs[0]['VpcId']
    print(f"Default VPC ID: {default_vpc_id}")
    return default_vpc_id


def create_subnet_group(neptune_client, group_name: str):
    """
    Creates a Neptune DB subnet group and returns its name and ARN.

    Args:
        neptune_client (boto3.client): The Neptune client object.
        group_name (str): The desired name of the subnet group.

    Returns:
        tuple(str, str): (subnet_group_name, subnet_group_arn)

    Raises:
        RuntimeError: For quota errors or other AWS-related failures.
    """
    vpc_id = get_default_vpc_id()
    subnet_ids = get_subnet_ids(vpc_id)

    request = {
        'DBSubnetGroupName': group_name,
        'DBSubnetGroupDescription': 'My Neptune subnet group',
        'SubnetIds': subnet_ids,
        'Tags': [{'Key': 'Environment', 'Value': 'Dev'}]
    }

    try:
        response = neptune_client.create_db_subnet_group(**request)
        sg = response.get("DBSubnetGroup", {})
        name = sg.get("DBSubnetGroupName")
        arn = sg.get("DBSubnetGroupArn")

        if not name or not arn:
            raise RuntimeError("Response missing subnet group name or ARN.")

        print(f"Subnet group created: {name}")
        print(f"ARN: {arn}")
        return name, arn

    except ClientError as e:
        code = e.response["Error"]["Code"]
        msg = e.response["Error"]["Message"]

        if code == "ServiceQuotaExceededException":
            print("Subnet group quota exceeded.")
            raise RuntimeError("Subnet group quota exceeded.") from e
        else:
            print(f"AWS error [{code}]: {msg}")
            raise RuntimeError(f"AWS error [{code}]: {msg}") from e

    except Exception as e:
        print(f"Unexpected error creating subnet group '{group_name}': {e}")
        raise RuntimeError(f"Unexpected error creating subnet group '{group_name}': {e}") from e

def wait_for_input_to_continue():
    input("\nPress <ENTER> to continue...")
    print("Continuing with the program...\n")


def run_scenario(neptune_client, subnet_group_name: str, db_instance_id: str, cluster_name: str):
    print("-" * 88)
    print("1. Create a Neptune DB Subnet Group")
    wait_for_input_to_continue()

    try:
        name, arn = create_subnet_group(neptune_client, subnet_group_name)
        print(f"Subnet group successfully created: {name}")

        print("-" * 88)
        print("2. Create a Neptune Cluster")
        wait_for_input_to_continue()
        db_cluster_id = create_db_cluster(neptune_client, cluster_name)

        print("-" * 88)
        print("3. Create a Neptune DB Instance")
        wait_for_input_to_continue()
        create_db_instance(neptune_client, db_instance_id, cluster_name)

        print("-" * 88)
        print("4. Check the status of the Neptune DB Instance")
        print("""
        Even though you're targeting a single DB instance, 
        describe_db_instances supports pagination and can return multiple pages. 

        Handling paginated responses ensures your method continues to work reliably 
        even if AWS returns large or paged results.
        """)
        wait_for_input_to_continue()
        check_instance_status(neptune_client, db_instance_id, "available")

        print("-" * 88)
        print("5. Show Neptune Cluster details")
        wait_for_input_to_continue()
        describe_db_clusters(neptune_client, db_cluster_id)

        print("-" * 88)
        print("6. Stop the Amazon Neptune cluster")
        print("""
            Boto3 doesn't currently offer a 
            built-in waiter for stop_db_cluster, 
            This example implements a custom polling 
            strategy until the cluster is in a stopped state.
        """)
        wait_for_input_to_continue()
        stop_db_cluster(neptune_client, db_cluster_id)
        check_instance_status(neptune_client, db_instance_id, "stopped")

        print("-" * 88)
        print("7. Start the Amazon Neptune cluster")
        print("""
            Boto3 doesn't currently offer a 
            built-in waiter for start_db_cluster, 
            This example implements a custom polling 
            strategy until the cluster is in an available state.
        """)
        wait_for_input_to_continue()
        start_db_cluster(neptune_client, db_cluster_id)
        wait_for_cluster_status(neptune_client, db_cluster_id, "available")
        check_instance_status(neptune_client, db_instance_id, "available")

        print("All Neptune resources are now available.")
        print("-" * 88)

        print("-" * 88)
        print("8. Delete the Neptune Assets")
        print("Would you like to delete the Neptune Assets? (y/n)")
        del_ans = input().strip().lower()

        if del_ans == "y":
            print("You selected to delete the Neptune assets.")

            delete_db_instance(neptune_client, db_instance_id)
            delete_db_cluster(neptune_client, db_cluster_id)
            delete_db_subnet_group(neptune_client, subnet_group_name)

            print("Neptune resources deleted successfully")

    except ClientError as ce:
        code = ce.response["Error"]["Code"]

        if code in ("DBInstanceNotFound", "DBInstanceNotFoundFault", "ResourceNotFound"):
            print(f"Instance '{db_instance_id}' not found.")
        elif code in ("DBClusterNotFound", "DBClusterNotFoundFault", "ResourceNotFoundFault"):
            print(f"Cluster '{cluster_name}' not found.")
        elif code == "DBSubnetGroupNotFoundFault":
            print(f"Subnet group '{subnet_group_name}' not found.")
        elif code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"AWS error [{code}]: {ce.response['Error']['Message']}")
            raise  # re-raise unexpected errors

    except RuntimeError as re:
        print(f"Runtime error or timeout: {re}")


def main():
    neptune_client = boto3.client('neptune')

    # Customize the following names to match your Neptune setup
    # (You must change these to unique values for your environment)
    subnet_group_name = "neptuneSubnetGroup111"
    cluster_name = "neptuneCluster111"
    db_instance_id = "neptuneDB111"

    print("""
    Amazon Neptune is a fully managed graph database service by AWS...
    Let's get started!
    """)
    wait_for_input_to_continue()
    run_scenario(neptune_client, subnet_group_name, db_instance_id, cluster_name)

    print("""
    Thank you for checking out the Amazon Neptune Service Use demo.
    For more AWS code examples, visit:
    https://docs.aws.amazon.com/code-library/latest/ug/what-is-code-library.html
    """)

if __name__ == "__main__":
    main()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateDBCluster)
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateDBInstance)
  + [CreateDBSubnetGroup](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateDBSubnetGroup)
  + [CreateGraph](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateGraph)
  + [DeleteDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DeleteDBCluster)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DeleteDBInstance)
  + [DeleteDBSubnetGroup](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DeleteDBSubnetGroup)
  + [DescribeDBClusters](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DescribeDBClusters)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DescribeDBInstances)
  + [ExecuteGremlinProfileQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteGremlinProfileQuery)
  + [ExecuteGremlinQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteGremlinQuery)
  + [ExecuteOpenCypherExplainQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteOpenCypherExplainQuery)
  + [ExecuteQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteQuery)
  + [StartDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/StartDBCluster)
  + [StopDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/StopDBCluster)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="neptune_CreateDBCluster_python_3_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def create_db_cluster(neptune_client, db_name: str) -> str:
    """
    Creates a Neptune DB cluster and returns its identifier.

    Args:
        neptune_client (boto3.client): The Neptune client object.
        db_name (str): The desired cluster identifier.

    Returns:
        str: The DB cluster identifier.

    Raises:
        RuntimeError: For any failure or AWS error, with a user-friendly message.
    """
    request = {
        'DBClusterIdentifier': db_name,
        'Engine': 'neptune',
        'DeletionProtection': False,
        'BackupRetentionPeriod': 1
    }

    try:
        response = neptune_client.create_db_cluster(**request)
        cluster = response.get('DBCluster') or {}

        cluster_id = cluster.get('DBClusterIdentifier')
        if not cluster_id:
            raise RuntimeError("Cluster created but no ID returned.")

        print(f"DB Cluster created: {cluster_id}")
        return cluster_id

    except ClientError as e:
        code = e.response["Error"]["Code"]
        message = e.response["Error"]["Message"]

        if code in ("ServiceQuotaExceededException", "DBClusterQuotaExceededFault"):
            raise RuntimeError("You have exceeded the quota for Neptune DB clusters.") from e
        else:
            raise RuntimeError(f"AWS error [{code}]: {message}") from e

    except Exception as e:
        raise RuntimeError(f"Unexpected error creating DB cluster '{db_name}': {e}") from e
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateDBCluster)」を参照してください。

### `CreateDBInstance`
<a name="neptune_CreateDBInstance_python_3_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def create_db_instance(neptune_client, db_instance_id: str, db_cluster_id: str) -> str:
    try:
        request = {
            'DBInstanceIdentifier': db_instance_id,
            'DBInstanceClass': 'db.r5.large',
            'Engine': 'neptune',
            'DBClusterIdentifier': db_cluster_id
        }

        print(f"Creating Neptune DB Instance: {db_instance_id}")
        response = neptune_client.create_db_instance(**request)

        instance = response.get('DBInstance')
        if not instance or 'DBInstanceIdentifier' not in instance:
            raise RuntimeError("Instance creation succeeded but no ID returned.")

        print(f"Waiting for DB Instance '{db_instance_id}' to become available...")
        waiter = neptune_client.get_waiter('db_instance_available')
        waiter.wait(
            DBInstanceIdentifier=db_instance_id,
            WaiterConfig={'Delay': 30, 'MaxAttempts': 40}
        )

        print(f"DB Instance '{db_instance_id}' is now available.")
        return instance['DBInstanceIdentifier']

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't create DB instance. Here's why: {code}: {message}")
        raise

    except Exception as e:
        print(f"Unexpected error creating DB instance '{db_instance_id}': {e}")
        raise RuntimeError(f"Unexpected error creating DB instance '{db_instance_id}': {e}") from e
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateDBInstance)」を参照してください。

### `CreateDBSubnetGroup`
<a name="neptune_CreateDBSubnetGroup_python_3_topic"></a>

次のコード例は、`CreateDBSubnetGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def create_subnet_group(neptune_client, group_name: str):
    """
    Creates a Neptune DB subnet group and returns its name and ARN.

    Args:
        neptune_client (boto3.client): The Neptune client object.
        group_name (str): The desired name of the subnet group.

    Returns:
        tuple(str, str): (subnet_group_name, subnet_group_arn)

    Raises:
        RuntimeError: For quota errors or other AWS-related failures.
    """
    vpc_id = get_default_vpc_id()
    subnet_ids = get_subnet_ids(vpc_id)

    request = {
        'DBSubnetGroupName': group_name,
        'DBSubnetGroupDescription': 'My Neptune subnet group',
        'SubnetIds': subnet_ids,
        'Tags': [{'Key': 'Environment', 'Value': 'Dev'}]
    }

    try:
        response = neptune_client.create_db_subnet_group(**request)
        sg = response.get("DBSubnetGroup", {})
        name = sg.get("DBSubnetGroupName")
        arn = sg.get("DBSubnetGroupArn")

        if not name or not arn:
            raise RuntimeError("Response missing subnet group name or ARN.")

        print(f"Subnet group created: {name}")
        print(f"ARN: {arn}")
        return name, arn

    except ClientError as e:
        code = e.response["Error"]["Code"]
        msg = e.response["Error"]["Message"]

        if code == "ServiceQuotaExceededException":
            print("Subnet group quota exceeded.")
            raise RuntimeError("Subnet group quota exceeded.") from e
        else:
            print(f"AWS error [{code}]: {msg}")
            raise RuntimeError(f"AWS error [{code}]: {msg}") from e

    except Exception as e:
        print(f"Unexpected error creating subnet group '{group_name}': {e}")
        raise RuntimeError(f"Unexpected error creating subnet group '{group_name}': {e}") from e
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateDBSubnetGroup](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateDBSubnetGroup)」を参照してください。**

### `CreateGraph`
<a name="neptune_CreateGraph_python_3_topic"></a>

次のコード例は、`CreateGraph` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
"""
Running this example.

----------------------------------------------------------------------------------
VPC Networking Requirement:
----------------------------------------------------------------------------------
Amazon Neptune must be accessed from **within the same VPC** as the Neptune cluster.
It does not expose a public endpoint, so this code must be executed from:

  - An **AWS Lambda function** configured to run inside the same VPC
  - An **EC2 instance** or **ECS task** running in the same VPC
  - A connected environment such as a **VPN**, **AWS Direct Connect**, or a **peered VPC**

"""

GRAPH_NAME = "sample-analytics-graph"

def main():
    config = Config(retries={"total_max_attempts": 1, "mode": "standard"}, read_timeout=None)
    client = boto3.client("neptune-graph", config=config)
    execute_create_graph(client, GRAPH_NAME)

def execute_create_graph(client, graph_name):
    try:
        print("Creating Neptune graph...")
        response = client.create_graph(
            graphName=graph_name,
            provisionedMemory = 16
        )

        created_graph_name = response.get("name")
        graph_arn = response.get("arn")
        graph_endpoint = response.get("endpoint")

        print("Graph created successfully!")
        print(f"Graph Name: {created_graph_name}")
        print(f"Graph ARN: {graph_arn}")
        print(f"Graph Endpoint: {graph_endpoint}")

    except ClientError as e:
        print(f"Failed to create graph: {e.response['Error']['Message']}")
    except BotoCoreError as e:
        print(f"Failed to create graph: {str(e)}")
    except Exception as e:
        print(f"Unexpected error: {str(e)}")

if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateGraph](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/CreateGraph)」を参照してください。**

### `DeleteDBCluster`
<a name="neptune_DeleteDBCluster_python_3_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def delete_db_cluster(neptune_client, cluster_id: str):
    """
    Deletes a Neptune DB cluster and throws exceptions to the caller.

    Args:
        neptune_client (boto3.client): The Neptune client object.
        cluster_id (str): The ID of the Neptune DB cluster to be deleted.

    Raises:
        ClientError: If the delete operation fails.
    """
    request = {
        'DBClusterIdentifier': cluster_id,
        'SkipFinalSnapshot': True
    }

    try:
        print(f"Deleting DB Cluster: {cluster_id}")
        neptune_client.delete_db_cluster(**request)

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "DBClusterNotFoundFault":
            print(f"Cluster '{cluster_id}' not found or already deleted.")
        elif code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't delete DB cluster. {code}: {message}")
        raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DeleteDBCluster)」を参照してください。

### `DeleteDBInstance`
<a name="neptune_DeleteDBInstance_python_3_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def delete_db_instance(neptune_client, instance_id: str):
    """
    Deletes a Neptune DB instance and waits for its deletion to complete.
    Raises exception to be handled by calling code.
    """
    print(f"Initiating deletion of DB Instance: {instance_id}")
    try:
        neptune_client.delete_db_instance(
            DBInstanceIdentifier=instance_id,
            SkipFinalSnapshot=True
        )

        print(f"Waiting for DB Instance '{instance_id}' to be deleted...")
        waiter = neptune_client.get_waiter('db_instance_deleted')
        waiter.wait(
            DBInstanceIdentifier=instance_id,
            WaiterConfig={
                'Delay': 30,
                'MaxAttempts': 40
            }
        )

        print(f"DB Instance '{instance_id}' successfully deleted.")

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "DBInstanceNotFoundFault":
            print(f"Instance '{instance_id}' not found or already deleted.")
        elif code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't delete DB instance. {code}: {message}")
        raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DeleteDBInstance)」を参照してください。

### `DeleteDBSubnetGroup`
<a name="neptune_DeleteDBSubnetGroup_python_3_topic"></a>

次のコード例は、`DeleteDBSubnetGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def delete_db_subnet_group(neptune_client, subnet_group_name):
    """
    Deletes a Neptune DB subnet group synchronously using Boto3.

    Args:
        neptune_client (boto3.client): The Neptune client.
        subnet_group_name (str): The name of the DB subnet group to delete.

    Raises:
        ClientError: If the delete operation fails.
    """
    delete_group_request = {
        'DBSubnetGroupName': subnet_group_name
    }

    try:
        neptune_client.delete_db_subnet_group(**delete_group_request)
        print(f"️ Deleting Subnet Group: {subnet_group_name}")

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "DBSubnetGroupNotFoundFault":
            print(f"Subnet group '{subnet_group_name}' not found or already deleted.")
        elif code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't delete subnet group. {code}: {message}")
        raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DeleteDBSubnetGroup](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DeleteDBSubnetGroup)」を参照してください。**

### `DescribeDBClusters`
<a name="neptune_DescribeDBClusters_python_3_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def describe_db_clusters(neptune_client, cluster_id: str):
    """
    Describes details of a Neptune DB cluster, paginating if needed.

    Args:
        neptune_client (boto3.client): The Neptune client.
        cluster_id (str): The ID of the cluster to describe.

    Raises:
        ClientError: If there's an AWS API error (e.g., cluster not found).
    """
    paginator = neptune_client.get_paginator('describe_db_clusters')

    try:
        pages = paginator.paginate(DBClusterIdentifier=cluster_id)

        found = False
        for page in pages:
            for cluster in page.get('DBClusters', []):
                found = True
                print(f"Cluster Identifier: {cluster.get('DBClusterIdentifier')}")
                print(f"Status: {cluster.get('Status')}")
                print(f"Engine: {cluster.get('Engine')}")
                print(f"Engine Version: {cluster.get('EngineVersion')}")
                print(f"Endpoint: {cluster.get('Endpoint')}")
                print(f"Reader Endpoint: {cluster.get('ReaderEndpoint')}")
                print(f"Availability Zones: {cluster.get('AvailabilityZones')}")
                print(f"Subnet Group: {cluster.get('DBSubnetGroup')}")
                print("VPC Security Groups:")
                for vpc_group in cluster.get('VpcSecurityGroups', []):
                    print(f"  - {vpc_group.get('VpcSecurityGroupId')}")
                print(f"Storage Encrypted: {cluster.get('StorageEncrypted')}")
                print(f"IAM Auth Enabled: {cluster.get('IAMDatabaseAuthenticationEnabled')}")
                print(f"Backup Retention Period: {cluster.get('BackupRetentionPeriod')} days")
                print(f"Preferred Backup Window: {cluster.get('PreferredBackupWindow')}")
                print(f"Preferred Maintenance Window: {cluster.get('PreferredMaintenanceWindow')}")
                print("------")

        if not found:
            # Treat empty response as cluster not found
            raise ClientError(
                {"Error": {"Code": "DBClusterNotFound", "Message": f"No cluster found with ID '{cluster_id}'"}},
                "DescribeDBClusters"
            )

    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        elif code == "DBClusterNotFound":
            print(f"Cluster '{cluster_id}' not found. Please verify the cluster ID.")
        else:
            print(f"Couldn't describe DB cluster. Here's why: {code}: {message}")
        raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBClusters](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DescribeDBClusters)」を参照してください。

### `DescribeDBInstances`
<a name="neptune_DescribeDBInstances_python_3_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def check_instance_status(neptune_client, instance_id: str, desired_status: str):
    """
    Polls the status of a Neptune DB instance until it reaches desired_status.
    Uses pagination via describe_db_instances — even for a single instance.

    Raises:
      ClientError: If describe_db_instances fails (e.g., instance not found).
      RuntimeError: If timeout expires before reaching desired status.
    """
    paginator = neptune_client.get_paginator('describe_db_instances')
    start_time = time.time()

    while True:
        try:
            pages = paginator.paginate(DBInstanceIdentifier=instance_id)
            instances = []
            for page in pages:
                instances.extend(page.get('DBInstances', []))

        except ClientError as err:
            code = err.response["Error"]["Code"]
            message = err.response["Error"]["Message"]

            if code == "DBInstanceNotFound":
                print(f"Instance '{instance_id}' not found. Please verify the instance ID.")
            else:
                print(f"Failed to describe DB instance. {code}: {message}")
            raise

        current_status = instances[0].get('DBInstanceStatus') if instances else None
        elapsed = int(time.time() - start_time)

        print(f"\rElapsed: {format_elapsed_time(elapsed)}  Status: {current_status}", end="", flush=True)

        if current_status and current_status.lower() == desired_status.lower():
            print(f"\nInstance '{instance_id}' reached '{desired_status}' in {format_elapsed_time(elapsed)}.")
            return

        if elapsed > TIMEOUT_SECONDS:
            raise RuntimeError(f"Timeout waiting for '{instance_id}' to reach '{desired_status}'")

        time.sleep(POLL_INTERVAL_SECONDS)
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/DescribeDBInstances)」を参照してください。

### `ExecuteGremlinProfileQuery`
<a name="neptune_ExecuteGremlinProfileQuery_python_3_topic"></a>

次のコード例は、`ExecuteGremlinProfileQuery` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
# Replace this with your actual Neptune endpoint
NEPTUNE_ENDPOINT = "https://[Specify Endpoint]:8182"

def main():
    """
    Entry point of the program. Initializes the Neptune client and executes the Gremlin query.
    """
    config = Config(connect_timeout=10, read_timeout=30, retries={'max_attempts': 3})

    neptune_client = boto3.client(
        "neptunedata",
        endpoint_url=NEPTUNE_ENDPOINT,
        config=config
    )

    execute_gremlin_query(neptune_client)


def execute_gremlin_query(neptune_client):
    """
    Executes a Gremlin query against an Amazon Neptune database.
    """
    try:
        print("Querying Neptune...")

        response = neptune_client.execute_gremlin_explain_query(
            gremlinQuery="g.V().has('code', 'ANC')"
        )

        print("Full Response:")
        print(response['output'].read().decode('UTF-8'))

    except ClientError as e:
        print(f"Error calling Neptune: {e.response['Error']['Message']}")
    except BotoCoreError as e:
        print(f"BotoCore error: {str(e)}")
    except Exception as e:
        print(f"Unexpected error: {str(e)}")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ExecuteGremlinProfileQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteGremlinProfileQuery)」を参照してください。**

### `ExecuteGremlinQuery`
<a name="neptune_ExecuteGremlinQuery_python_3_topic"></a>

次のコード例は、`ExecuteGremlinQuery` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
"""
Running this example.

----------------------------------------------------------------------------------
VPC Networking Requirement:
----------------------------------------------------------------------------------
Amazon Neptune must be accessed from **within the same VPC** as the Neptune cluster.
It does not expose a public endpoint, so this code must be executed from:

  - An **AWS Lambda function** configured to run inside the same VPC
  - An **EC2 instance** or **ECS task** running in the same VPC
  - A connected environment such as a **VPN**, **AWS Direct Connect**, or a **peered VPC**

"""

# Replace with your actual Neptune endpoint
NEPTUNE_ENDPOINT = "https://[Specify-Your-Endpoint]:8182"

def main():
    """
    Entry point of the program. Initializes the Neptune client and runs both EXPLAIN and PROFILE queries.
    """
    config = Config(connect_timeout=10, read_timeout=30, retries={'max_attempts': 3})

    neptune_client = boto3.client(
        "neptunedata",
        endpoint_url=NEPTUNE_ENDPOINT,
        config=config
    )

    try:
        run_profile_query(neptune_client)
    except ClientError as e:
        print(f"Neptune error: {e.response['Error']['Message']}")
    except BotoCoreError as e:
        print(f"BotoCore error: {str(e)}")
    except Exception as e:
        print(f"Unexpected error: {str(e)}")

def run_profile_query(neptune_client):
    """
    Runs a PROFILE query on the Neptune graph database.
    """
    print("Running Gremlin PROFILE query...")

    try:
        response = neptune_client.execute_gremlin_profile_query(
            gremlinQuery="g.V().has('code', 'ANC')"
        )
        print("Profile Query Result:")
        output = response.get("output")
        if output:
            print(output.read().decode('utf-8'))
        else:
            print("No explain output returned.")
    except Exception as e:
        print(f"Failed to execute PROFILE query: {str(e)}")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ExecuteGremlinQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteGremlinQuery)」を参照してください。**

### `ExecuteOpenCypherExplainQuery`
<a name="neptune_ExecuteOpenCypherExplainQuery_python_3_topic"></a>

次のコード例は、`ExecuteOpenCypherExplainQuery` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
# Replace with your actual Neptune endpoint URL
NEPTUNE_ENDPOINT = "https://<your-neptune-endpoint>:8182"

def main():
    """
    Entry point: Create Neptune client and execute different OpenCypher queries.
    """
    config = Config(connect_timeout=10, read_timeout=30, retries={'max_attempts': 3})

    neptune_client = boto3.client(
        "neptunedata",
        endpoint_url=NEPTUNE_ENDPOINT,
        config=config
    )

    execute_open_cypher_query_without_params(neptune_client)
    execute_open_cypher_query_with_params(neptune_client)
    execute_open_cypher_explain_query(neptune_client)

def execute_open_cypher_query_without_params(client):
    """
    Executes a simple OpenCypher query without parameters.
    """
    try:
        print("\nRunning OpenCypher query without parameters...")
        resp = client.execute_open_cypher_query(
            openCypherQuery="MATCH (n {code: 'ANC'}) RETURN n"
        )
        print("Results:")
        print(resp['results'])

    except Exception as e:
        print(f"Error in simple OpenCypher query: {str(e)}")


def execute_open_cypher_query_with_params(client):
    """
    Executes an OpenCypher query using parameters.
    """
    try:
        print("\nRunning OpenCypher query with parameters...")
        parameters = {'code': 'ANC'}
        resp = client.execute_open_cypher_query(
            openCypherQuery="MATCH (n {code: $code}) RETURN n",
            parameters=json.dumps(parameters)
        )
        print("Results:")
        print(resp['results'])

    except Exception as e:
        print(f"Error in parameterized OpenCypher query: {str(e)}")

def execute_open_cypher_explain_query(client):
    """
    Runs an OpenCypher EXPLAIN query in debug mode.
    """
    try:
        print("\nRunning OpenCypher EXPLAIN query (debug mode)...")
        resp = client.execute_open_cypher_explain_query(
            openCypherQuery="MATCH (n {code: 'ANC'}) RETURN n",
            explainMode="details"
        )
        results = resp.get('results')
        if results is None:
            print("No explain results returned.")
        else:
            try:
                print("Explain Results:")
                print(results.read().decode('UTF-8'))
            except Exception as e:
                print(f"Error in OpenCypher EXPLAIN query: {str(e)}")

    except ClientError as e:
        print(f"Neptune error: {e.response['Error']['Message']}")
    except BotoCoreError as e:
        print(f"BotoCore error: {str(e)}")
    except Exception as e:
        print(f"Unexpected error: {str(e)}")


if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ExecuteOpenCypherExplainQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteOpenCypherExplainQuery)」を参照してください。**

### `ExecuteQuery`
<a name="neptune_ExecuteQuery_python_3_topic"></a>

次のコード例は、`ExecuteQuery` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
"""
Running this example.

----------------------------------------------------------------------------------
VPC Networking Requirement:
----------------------------------------------------------------------------------
Amazon Neptune must be accessed from **within the same VPC** as the Neptune cluster.
It does not expose a public endpoint, so this code must be executed from:

  - An **AWS Lambda function** configured to run inside the same VPC
  - An **EC2 instance** or **ECS task** running in the same VPC
  - A connected environment such as a **VPN**, **AWS Direct Connect**, or a **peered VPC**
"""

GRAPH_ID = "<your-graph-id>"

def main():
    config = Config(retries={"total_max_attempts": 1, "mode": "standard"}, read_timeout=None)
    client = boto3.client("neptune-graph", config=config)

    try:
        print("\n--- Running OpenCypher query without parameters ---")
        run_open_cypher_query(client, GRAPH_ID)

        print("\n--- Running OpenCypher query with parameters ---")
        run_open_cypher_query_with_params(client, GRAPH_ID)

        print("\n--- Running OpenCypher explain query ---")
        run_open_cypher_explain_query(client, GRAPH_ID)

    except Exception as e:
        print(f"Unexpected error in main: {e}")

def run_open_cypher_query(client, graph_id):
    """
    Run an OpenCypher query without parameters.
    """
    try:
        resp = client.execute_query(
            graphIdentifier=graph_id,
            queryString="MATCH (n {code: 'ANC'}) RETURN n",
            language='OPEN_CYPHER'
        )
        print(resp['payload'].read().decode('UTF-8'))

    except client.exceptions.InternalServerException as e:
        print(f"InternalServerException: {e.response['Error']['Message']}")
    except ClientError as e:
        print(f"ClientError: {e.response['Error']['Message']}")
    except Exception as e:  # <--- ADD THIS BLOCK
        print(f"Unexpected error: {e}")

def run_open_cypher_query_with_params(client, graph_id):
    """
    Run an OpenCypher query with parameters.
    """
    try:
        parameters = {'code': 'ANC'}
        resp = client.execute_query(
            graphIdentifier=graph_id,
            queryString="MATCH (n {code: $code}) RETURN n",
            language='OPEN_CYPHER',
            parameters=parameters
        )
        print(resp['payload'].read().decode('UTF-8'))

    except client.exceptions.InternalServerException as e:
        print(f"InternalServerException: {e.response['Error']['Message']}")
    except ClientError as e:
        print(f"ClientError: {e.response['Error']['Message']}")
    except Exception as e:  # <--- ADD THIS BLOCK
        print(f"Unexpected error: {e}")

def run_open_cypher_explain_query(client, graph_id):
    """
    Run an OpenCypher explain query (explainMode = "debug").
    """
    try:
        resp = client.execute_query(
            graphIdentifier=graph_id,
            queryString="MATCH (n {code: 'ANC'}) RETURN n",
            language='OPEN_CYPHER',
            explainMode='DETAILS'
        )
        print(resp['payload'].read().decode('UTF-8'))

    except ClientError as e:
        print(f"Neptune error: {e.response['Error']['Message']}")
    except BotoCoreError as e:
        print(f"Unexpected Boto3 error: {str(e)}")
    except Exception as e:  # <-- Add this generic catch
        print(f"Unexpected error: {str(e)}")

if __name__ == "__main__":
    main()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ExecuteQuery](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/ExecuteQuery)」を参照してください。**

### `StartDBCluster`
<a name="neptune_StartDBCluster_python_3_topic"></a>

次のコード例は、`StartDBCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def start_db_cluster(neptune_client, cluster_identifier: str):
    """
    Starts an Amazon Neptune DB cluster and waits until it reaches 'available'.

    Args:
        neptune_client (boto3.client): The Neptune client.
        cluster_identifier (str): The DB cluster identifier.

    Raises:
        ClientError: Propagates AWS API issues like resource not found.
        RuntimeError: If cluster doesn't reach 'available' within timeout.
    """
    try:
        # Initial wait in case the cluster was just stopped
        time.sleep(30)
        neptune_client.start_db_cluster(DBClusterIdentifier=cluster_identifier)
    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't start DB cluster. Here's why: {code}: {message}")
        raise

    start_time = time.time()
    paginator = neptune_client.get_paginator('describe_db_clusters')

    while True:
        try:
            pages = paginator.paginate(DBClusterIdentifier=cluster_identifier)
            clusters = []
            for page in pages:
                clusters.extend(page.get('DBClusters', []))
        except ClientError as err:
            code = err.response["Error"]["Code"]
            message = err.response["Error"]["Message"]

            if code == "DBClusterNotFound":
                print(f"Cluster '{cluster_identifier}' not found while polling. It may have been deleted.")
            else:
                print(f"Couldn't describe DB cluster. Here's why: {code}: {message}")
            raise

        status = clusters[0].get('Status') if clusters else None
        elapsed = time.time() - start_time

        print(f"\rElapsed: {int(elapsed)}s – Cluster status: {status}", end="", flush=True)

        if status and status.lower() == 'available':
            print(f"\n🎉 Cluster '{cluster_identifier}' is available.")
            return

        if elapsed > TIMEOUT_SECONDS:
            raise RuntimeError(f"Timeout waiting for cluster '{cluster_identifier}' to become available.")

        time.sleep(POLL_INTERVAL_SECONDS)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/StartDBCluster)」を参照してください。**

### `StopDBCluster`
<a name="neptune_StopDBCluster_python_3_topic"></a>

次のコード例は、`StopDBCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/neptune#code-examples)での設定と実行の方法を確認してください。

```
def stop_db_cluster(neptune_client, cluster_identifier: str):
    """
    Stops an Amazon Neptune DB cluster and waits until it's fully stopped.

    Args:
        neptune_client (boto3.client): The Neptune client.
        cluster_identifier (str): The DB cluster identifier.

    Raises:
        ClientError: For AWS API errors (e.g., resource not found).
        RuntimeError: If the cluster doesn't stop within the timeout.
    """
    try:
        neptune_client.stop_db_cluster(DBClusterIdentifier=cluster_identifier)
    except ClientError as err:
        code = err.response["Error"]["Code"]
        message = err.response["Error"]["Message"]

        if code == "AccessDeniedException":
            print("Access denied. Please ensure you have the necessary permissions.")
        else:
            print(f"Couldn't stop DB cluster. Here's why: {code}: {message}")
        raise

    start_time = time.time()
    paginator = neptune_client.get_paginator('describe_db_clusters')

    while True:
        try:
            pages = paginator.paginate(DBClusterIdentifier=cluster_identifier)
            clusters = []
            for page in pages:
                clusters.extend(page.get('DBClusters', []))
        except ClientError as err:
            code = err.response["Error"]["Code"]
            message = err.response["Error"]["Message"]

            if code == "DBClusterNotFound":
                print(f"Cluster '{cluster_identifier}' not found while polling. It may have been deleted.")
            else:
                print(f"Couldn't describe DB cluster. Here's why: {code}: {message}")
            raise

        status = clusters[0].get('Status') if clusters else None
        elapsed = time.time() - start_time

        print(f"\rElapsed: {int(elapsed)}s – Cluster status: {status}", end="", flush=True)

        if status and status.lower() == 'stopped':
            print(f"\nCluster '{cluster_identifier}' is now stopped.")
            return

        if elapsed > TIMEOUT_SECONDS:
            raise RuntimeError(f"Timeout waiting for cluster '{cluster_identifier}' to stop.")

        time.sleep(POLL_INTERVAL_SECONDS)
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StopDBCluster](https://docs.aws.amazon.com/goto/boto3/neptune-2014-10-31/StopDBCluster)」を参照してください。**

# SDK for Python (Boto3) を使用した Organizations の例
<a name="python_3_organizations_code_examples"></a>

次のコード例は、Organizations AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AttachPolicy`
<a name="organizations_AttachPolicy_python_3_topic"></a>

次のコード例は、`AttachPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)での設定と実行の方法を確認してください。

```
def attach_policy(policy_id, target_id, orgs_client):
    """
    Attaches a policy to a target. The target is an organization root, account, or
    organizational unit.

    :param policy_id: The ID of the policy to attach.
    :param target_id: The ID of the resources to attach the policy to.
    :param orgs_client: The Boto3 Organizations client.
    """
    try:
        orgs_client.attach_policy(PolicyId=policy_id, TargetId=target_id)
        logger.info("Attached policy %s to target %s.", policy_id, target_id)
    except ClientError:
        logger.exception(
            "Couldn't attach policy %s to target %s.", policy_id, target_id
        )
        raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AttachPolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/AttachPolicy)」を参照してください。

### `CreatePolicy`
<a name="organizations_CreatePolicy_python_3_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)での設定と実行の方法を確認してください。

```
def create_policy(name, description, content, policy_type, orgs_client):
    """
    Creates a policy.

    :param name: The name of the policy.
    :param description: The description of the policy.
    :param content: The policy content as a dict. This is converted to JSON before
                    it is sent to AWS. The specific format depends on the policy type.
    :param policy_type: The type of the policy.
    :param orgs_client: The Boto3 Organizations client.
    :return: The newly created policy.
    """
    try:
        response = orgs_client.create_policy(
            Name=name,
            Description=description,
            Content=json.dumps(content),
            Type=policy_type,
        )
        policy = response["Policy"]
        logger.info("Created policy %s.", name)
    except ClientError:
        logger.exception("Couldn't create policy %s.", name)
        raise
    else:
        return policy
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreatePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/CreatePolicy)」を参照してください。

### `DeletePolicy`
<a name="organizations_DeletePolicy_python_3_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)での設定と実行の方法を確認してください。

```
def delete_policy(policy_id, orgs_client):
    """
    Deletes a policy.

    :param policy_id: The ID of the policy to delete.
    :param orgs_client: The Boto3 Organizations client.
    """
    try:
        orgs_client.delete_policy(PolicyId=policy_id)
        logger.info("Deleted policy %s.", policy_id)
    except ClientError:
        logger.exception("Couldn't delete policy %s.", policy_id)
        raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeletePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DeletePolicy)」を参照してください。

### `DescribePolicy`
<a name="organizations_DescribePolicy_python_3_topic"></a>

次のコード例は、`DescribePolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)での設定と実行の方法を確認してください。

```
def describe_policy(policy_id, orgs_client):
    """
    Describes a policy.

    :param policy_id: The ID of the policy to describe.
    :param orgs_client: The Boto3 Organizations client.
    :return: The description of the policy.
    """
    try:
        response = orgs_client.describe_policy(PolicyId=policy_id)
        policy = response["Policy"]
        logger.info("Got policy %s.", policy_id)
    except ClientError:
        logger.exception("Couldn't get policy %s.", policy_id)
        raise
    else:
        return policy
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribePolicy](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DescribePolicy)」を参照してください。

### `DetachPolicy`
<a name="organizations_DetachPolicy_python_3_topic"></a>

次のコード例は、`DetachPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)での設定と実行の方法を確認してください。

```
def detach_policy(policy_id, target_id, orgs_client):
    """
    Detaches a policy from a target.

    :param policy_id: The ID of the policy to detach.
    :param target_id: The ID of the resource where the policy is currently attached.
    :param orgs_client: The Boto3 Organizations client.
    """
    try:
        orgs_client.detach_policy(PolicyId=policy_id, TargetId=target_id)
        logger.info("Detached policy %s from target %s.", policy_id, target_id)
    except ClientError:
        logger.exception(
            "Couldn't detach policy %s from target %s.", policy_id, target_id
        )
        raise
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/DetachPolicy) の「*DetachPolicy*」を参照してください。

### `ListPolicies`
<a name="organizations_ListPolicies_python_3_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/organizations#code-examples)での設定と実行の方法を確認してください。

```
def list_policies(policy_filter, orgs_client):
    """
    Lists the policies for the account, limited to the specified filter.

    :param policy_filter: The kind of policies to return.
    :param orgs_client: The Boto3 Organizations client.
    :return: The list of policies found.
    """
    try:
        response = orgs_client.list_policies(Filter=policy_filter)
        policies = response["Policies"]
        logger.info("Found %s %s policies.", len(policies), policy_filter)
    except ClientError:
        logger.exception("Couldn't get %s policies.", policy_filter)
        raise
    else:
        return policies
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListPolicies](https://docs.aws.amazon.com/goto/boto3/organizations-2016-11-28/ListPolicies)」を参照してください。

# SDK for Python (Boto3) を使用したパートナーセントラルの例
<a name="python_3_partnercentral-selling_code_examples"></a>

次のコード例は、 Partner Central AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AssignOpportunity`
<a name="partnercentral-selling_AssignOpportunity_python_3_topic"></a>

次のコード例は、`AssignOpportunity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
既存のオポチュニティを他のユーザーに再割り当てします。  

```
#!/usr/bin/env python

"""
Purpose
PC-API-07 Assigning a new owner
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def assign_opportunity(identifier):
    assign_opportunity_request ={
        "Catalog": CATALOG_TO_USE,
	    "Identifier": identifier,
        "Assignee": { 
            "BusinessTitle": "OpportunityOwner",
            "Email": "test@test.com",
            "FirstName": "John",
            "LastName": "Doe"
        }
    }
    try:
        # Perform an API call
        response = partner_central_client.assign_opportunity(**assign_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    identifier = "O4236468"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Assigning a new owner to an opportunity.")
    print("-" * 88)

    helper.pretty_print_datetime(assign_opportunity(identifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[AssignOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/AssignOpportunity)」を参照してください。**

### `AssociateOpportunity`
<a name="partnercentral-selling_AssociateOpportunity_python_3_topic"></a>

次のコード例は、`AssociateOpportunity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
オポチュニティとさまざまな関連エンティティとの正式な関連付けを作成します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API -11 Associating a product
PC-API -12 Associating a solution
PC-API -13 Associating an offer
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def associate_opportunity(entity_type, entity_identifier, opportunityIdentifier):
    associate_opportunity_request ={
        "Catalog": CATALOG_TO_USE,
	    "OpportunityIdentifier" : opportunityIdentifier, 
        "RelatedEntityType" : entity_type, 
        "RelatedEntityIdentifier" : entity_identifier 
    }
    try:
        # Perform an API call
        response = partner_central_client.associate_opportunity(**associate_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    #entity_type = Solutions | AWSProducts | AWSMarketplaceOffers 
    entity_type = "Solutions"
    entity_identifier = "S-0059717"
    opportunityIdentifier = "O5465588"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Associate Opportunity.")
    print("-" * 88)

    helper.pretty_print_datetime(associate_opportunity(entity_type, entity_identifier, opportunityIdentifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[AssociateOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/AssociateOpportunity)」を参照してください。**

### `CreateOpportunity`
<a name="partnercentral-selling_CreateOpportunity_python_3_topic"></a>

次のコード例は、`CreateOpportunity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
オポチュニティを作成します。  

```
#!/usr/bin/env python
import boto3
import logging
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import utils.helpers as helper
import utils.stringify_details as sd
from botocore.client import ClientError
from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

def create_opportunity(partner_central_client):
    create_opportunity_request = helper.remove_nulls(sd.stringify_json("src/create_opportunity/createOpportunity.json"))
    try:
        # Perform an API call
        response = partner_central_client.create_opportunity(**create_opportunity_request)
        
        helper.pretty_print_datetime(response)

        # Retrieve the opportunity details
        get_response = partner_central_client.get_opportunity(
            Identifier=response["Id"],
            Catalog=CATALOG_TO_USE
        )
        helper.pretty_print_datetime(get_response)
        return response
    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Create Opportunity.")
    print("-" * 88)

    partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
    )

    create_opportunity(partner_central_client)

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/CreateOpportunity)」を参照してください。**

### `DisassociateOpportunity`
<a name="partnercentral-selling_DisassociateOpportunity_python_3_topic"></a>

次のコード例は、`DisassociateOpportunity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
オポチュニティと関連エンティティ間の既存の関連付けを削除します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API -14 Removing a Solution
PC-API -15 Removing an offer
PC-API -16 Removing a product
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def disassociate_opportunity(entity_type, entity_identifier, opportunityIdentifier):
    disassociate_opportunity_request ={
        "Catalog": CATALOG_TO_USE,
	    "OpportunityIdentifier" : opportunityIdentifier, 
        "RelatedEntityType" : entity_type, 
        "RelatedEntityIdentifier" : entity_identifier 
    }
    try:
        # Perform an API call
        response = partner_central_client.disassociate_opportunity(**disassociate_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    #entity_type = Solutions | AWSProducts | AWSMarketplaceOffers 
    entity_type = "Solutions"
    entity_identifier = "S-0049999"
    opportunityIdentifier = "O4397574"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Get updated Opportunity.")
    print("-" * 88)

    helper.pretty_print_datetime(disassociate_opportunity(entity_type, entity_identifier, opportunityIdentifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[DisassociateOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/DisassociateOpportunity)」を参照してください。**

### `GetAwsOpportunitySummary`
<a name="partnercentral-selling_GetAwsOpportunitySummary_python_3_topic"></a>

次のコード例は、`GetAwsOpportunitySummary` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 AWS オポチュニティの概要を取得します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API-25 Retrieves a summary of an AWS Opportunity. LifeCycle.ReviewStatus=Approved
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def get_opportunity(identifier):
    get_opportunity_request ={
        "Catalog": CATALOG_TO_USE,
	    "RelatedOpportunityIdentifier": identifier
    }
    try:
        # Perform an API call
        response = partner_central_client.get_aws_opportunity_summary(**get_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    identifier = "O5465588"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Get AWS Opportunity summary.")
    print("-" * 88)

    helper.pretty_print_datetime(get_opportunity(identifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetAwsOpportunitySummary](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/GetAwsOpportunitySummary)」を参照してください。**

### `GetEngagementInvitation`
<a name="partnercentral-selling_GetEngagementInvitation_python_3_topic"></a>

次のコード例は、`GetEngagementInvitation` を使用する方法を示しています。

**SDK for Python (Boto3)**  
がパートナー AWS と共有しているエンゲージメントの招待の詳細を取得します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API-22  GetOpportunityEngagementInvitation - Retrieves details of a specific engagement invitation. 
This operation allows partners to view the invitation and its associated information, 
such as the customer, project, and lifecycle details.
"""
import json
import logging
import boto3
import utils.helpers as helper

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def get_opportunity_engagement_invitation(identifier):
    get_opportunity_engagement_invitation_request ={
        "Catalog": CATALOG_TO_USE,
	    "Identifier": identifier
    }
    try:
        # Perform an API call
        response = partner_central_client.get_engagement_invitation(**get_opportunity_engagement_invitation_request)
        return response

    except Exception as err:
        # Catch all client exceptions
        print(json.dumps(err.response))

def usage_demo():
    identifier = "arn:aws:partnercentral-selling:us-east-1:aws:catalog/Sandbox/engagement-invitation/engi-0000000IS0Qga"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Given the ARN identifier, retrieve details of Opportunity Engagement Invitation.")
    print("-" * 88)

    helper.pretty_print_datetime(get_opportunity_engagement_invitation(identifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンス の「[GetEngagementInvitation](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/GetEngagementInvitation)」を参照してください。**

### `GetOpportunity`
<a name="partnercentral-selling_GetOpportunity_python_3_topic"></a>

次のコード例は、`GetOpportunity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
オポチュニティを取得します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API -08 Get updated Opportunity given opportunity id
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def get_opportunity(identifier):
    get_opportunity_request ={
        "Catalog": CATALOG_TO_USE,
	    "Identifier": identifier
    }
    try:
        # Perform an API call
        response = partner_central_client.get_opportunity(**get_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    identifier = "O5465588"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Get updated Opportunity.")
    print("-" * 88)

    helper.pretty_print_datetime(get_opportunity(identifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[GetOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/GetOpportunity)」を参照してください。**

### `ListEngagementInvitations`
<a name="partnercentral-selling_ListEngagementInvitations_python_3_topic"></a>

次のコード例は、`ListEngagementInvitations` を使用する方法を示しています。

**SDK for Python (Boto3)**  
パートナーに送信されたエンゲージメントの招待の一覧を取得します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API-21 ListEngagementInvitations - Retrieves a list of engagement invitations based on specified criteria. 
This operation allows partners to view all invitations to engagement.
"""
import json
import logging
import boto3
import utils.helpers as helper

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def list_engagement_invitations():
    list_engagement_invitations_request ={
        "Catalog": CATALOG_TO_USE,
        "MaxResults": 20
    }
    try:
        # Perform an API call
        response = partner_central_client.list_engagement_invitations(**list_engagement_invitations_request)
        return response

    except Exception as err:
        # Catch all client exceptions
        print(json.dumps(err.response))

def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Retrieve list of Engagement Invitations.")
    print("-" * 88)

    helper.pretty_print_datetime(list_engagement_invitations())

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListEngagementInvitations](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/ListEngagementInvitations)」を参照してください。**

### `ListOpportunities`
<a name="partnercentral-selling_ListOpportunities_python_3_topic"></a>

次のコード例は、`ListOpportunities` を使用する方法を示しています。

**SDK for Python (Boto3)**  
オポチュニティを一覧表示します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API -18 Getting list of Opportunities
"""
import json
import logging
import boto3
import utils.helpers as helper

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def get_list_of_opportunities():

    opportunity_list = []

    list_opportunities_request ={
        "Catalog": CATALOG_TO_USE,
	    "MaxResults": 20
    }
    try:
        # Perform an API call
        response = partner_central_client.list_opportunities(**list_opportunities_request)
        opportunity_list.extend(response["OpportunitySummaries"])

        while "NextToken" in response and response["NextToken"] is not None:
            list_opportunities_request["NextToken"] = response["NextToken"]
            response = partner_central_client.list_opportunities(**list_opportunities_request)
            opportunity_list.extend(response["OpportunitySummaries"])

        return opportunity_list

    except Exception as err:
        # Catch all client exceptions
        print(json.dumps(err.response))

def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Getting list of Opportunities.")
    print("-" * 88)

    helper.pretty_print_datetime(get_list_of_opportunities())

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListOpportunities](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/ListOpportunities)」を参照してください。

### `ListSolutions`
<a name="partnercentral-selling_ListSolutions_python_3_topic"></a>

次のコード例は、`ListSolutions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
パートナーがパートナーセントラルに登録したパートナーソリューションの一覧を取得します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API-10 Getting list of solutions
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def get_list_of_solutions():
    list_solutions_request ={
        "Catalog": CATALOG_TO_USE,
	    "MaxResults": 20
    }
    try:
        # Perform an API call
        response = partner_central_client.list_solutions(**list_solutions_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Getting list of solutions.")
    print("-" * 88)

    helper.pretty_print_datetime(get_list_of_solutions())

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[ListSolutions](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/ListSolutions)」を参照してください。**

### `RejectEngagementInvitation`
<a name="partnercentral-selling_RejectEngagementInvitation_python_3_topic"></a>

次のコード例は、`RejectEngagementInvitation` を使用する方法を示しています。

**SDK for Python (Boto3)**  
が AWS 共有した EngagementInvitation を拒否します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API-05 AWS Originated AO rejection - RejectOpportunityEngagementInvitation - Rejects a engagement invitation. 
This action indicates that the partner does not wish to participate in the engagement and 
provides a reason for the rejection.
Upon rejection, a OpportunityEngagementInvitationRejected event is triggered. 
Subsequently, the invitation will no longer be available for the partner to act on.
"""
import json
import logging
import boto3
import utils.helpers as helper

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def reject_opportunity_engagement_invitation(identifier, reject_reason):
    reject_opportunity_engagement_invitation_request ={
        "Catalog": CATALOG_TO_USE,
	    "Identifier": identifier,
        "RejectionReason": reject_reason
    }
    try:
        # Perform an API call
        response = partner_central_client.reject_engagement_invitation(**reject_opportunity_engagement_invitation_request)
        return response

    except Exception as err:
        # Catch all client exceptions
        print(json.dumps(err.response))

def usage_demo():
    identifier = "arn:aws:partnercentral:us-east-1::catalog/Sandbox/engagement-invitation/engi-0000002isviga"
    reject_reason = "Customer problem unclear"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Given the ARN identifier and reject reason, reject the Opportunity Engagement Invitation.")
    print("-" * 88)

    helper.pretty_print_datetime(reject_opportunity_engagement_invitation(identifier, reject_reason))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[RejectEngagementInvitation](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/RejectEngagementInvitation)」を参照してください。**

### `StartEngagementByAcceptingInvitationTask`
<a name="partnercentral-selling_StartEngagementByAcceptingInvitationTask_python_3_topic"></a>

次のコード例は、`StartEngagementByAcceptingInvitationTask` を使用する方法を示しています。

**SDK for Python (Boto3)**  
EngagementInvitation を受け入れることでエンゲージメントを開始します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API -11 Associating a product
PC-API -12 Associating a solution
PC-API -13 Associating an offer
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def get_opportunity(identifier):
    get_opportunity_request ={
	    "Identifier": identifier,
        "Catalog": CATALOG_TO_USE
    }
    try:
        # Perform an API call
        response = partner_central_client.get_engagement_invitation(**get_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def start_engagement_by_accepting_invitation_task(identifier):

    response = get_opportunity(identifier)

    if ( response['Status'] == 'PENDING') :
        accept_opportunity_engagement_invitation_request ={
            "Catalog": CATALOG_TO_USE,
	        "Identifier" : identifier,
            "ClientToken": "test-123456"
        }
        try:
            # Perform an API call
            response = partner_central_client.start_engagement_by_accepting_invitation_task(**accept_opportunity_engagement_invitation_request)
            return response

        except ClientError as err:
            # Catch all client exceptions
            print(err.response)
            return None
    else:
        return None

def usage_demo():
    identifier = "arn:aws:partnercentral:us-east-1::catalog/Sandbox/engagement-invitation/engi-0000002isusga"
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Get updated Opportunity.")
    print("-" * 88)

    helper.pretty_print_datetime(start_engagement_by_accepting_invitation_task(identifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartEngagementByAcceptingInvitationTask](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/StartEngagementByAcceptingInvitationTask)」を参照してください。**

### `StartEngagementFromOpportunityTask`
<a name="partnercentral-selling_StartEngagementFromOpportunityTask_python_3_topic"></a>

次のコード例は、`StartEngagementFromOpportunityTask` を使用する方法を示しています。

**SDK for Python (Boto3)**  
エンゲージメントの招待を受け入れ、パートナーのシステムで対応するオポチュニティを作成することで、既存のオポチュニティからエンゲージメントプロセスを開始します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API -11 Associating a product
PC-API -12 Associating a solution
PC-API -13 Associating an offer
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def start_engagement_from_opportunity_task(identifier):
    
    start_engagement_from_opportunity_task_request ={
            "AwsSubmission": { 
                "InvolvementType": "Co-Sell",
                "Visibility": "Full"
            },
            "Catalog": CATALOG_TO_USE,
	        "Identifier" : identifier,
            "ClientToken": "test-annjqwesdsd99"
    }
    try:
            # Perform an API call
            response = partner_central_client.start_engagement_from_opportunity_task(**start_engagement_from_opportunity_task_request)
            return response

    except ClientError as err:
            # Catch all client exceptions
            print(err.response)
            return None
   
def usage_demo():
    identifier = "O5465588"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Start Engagement from Opportunity Task.")
    print("-" * 88)

    helper.pretty_print_datetime(start_engagement_from_opportunity_task(identifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[StartEngagementFromOpportunityTask](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/StartEngagementFromOpportunityTask)」を参照してください。**

### `UpdateOpportunity`
<a name="partnercentral-selling_UpdateOpportunity_python_3_topic"></a>

次のコード例は、`UpdateOpportunity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
オポチュニティを更新します。  

```
#!/usr/bin/env python

"""
Purpose
PC-API-2  Updating Partner Originated Opportunity
"""
import logging
import boto3
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import utils.helpers as helper
from botocore.client import ClientError
import utils.stringify_details as sd
from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def get_opportunity(identifier):
    get_opportunity_request ={
	    "Identifier": identifier,
        "Catalog": CATALOG_TO_USE
    }
    try:
        # Perform an API call
        response = partner_central_client.get_opportunity(**get_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def update_opportunity():
    update_opportunity_request_orig = sd.stringify_json("src/update_opportunity/update_opportunity_technical_validation.json")
    update_opportunity_request = helper.remove_nulls(update_opportunity_request_orig)
    
    try:
        # Perform an API call
        response = partner_central_client.update_opportunity(**update_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def update_opportunity_if_eligible(identifier):
    response = get_opportunity(identifier)
    if response is not None:
        return update_opportunity()
    else:
        print("Failed to retrieve opportunity details")

def usage_demo():
    identifier = "O5465588"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Updating opportunity.")
    print("-" * 88)

    helper.pretty_print_datetime(update_opportunity_if_eligible(identifier))

if __name__ == "__main__":
    usage_demo()
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[UpdateOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/UpdateOpportunity)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### オポチュニティの関連エンティティを更新する
<a name="partnercentral-selling__UpdateAssociatedEntity_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 古いエンティティの関連付けを解除します。
+ 新しいエンティティを関連付けます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/partner-central-api-sample-codes/python_preview/#code-examples)での設定と実行の方法を確認してください。
オポチュニティの関連エンティティを更新する  

```
#!/usr/bin/env python

"""
Purpose
PC-API -17 Replacing a solution
"""
import logging
import boto3
import utils.helpers as helper
from botocore.client import ClientError

from utils.constants import CATALOG_TO_USE

serviceName = "partnercentral-selling"

partner_central_client = boto3.client(
        service_name=serviceName,
        region_name='us-east-1'
)

def replace_solution(original_entity_identifier, new_entity_identifier, opportunityIdentifier):
    disassociate_opportunity_request ={
        "Catalog": CATALOG_TO_USE,
	    "OpportunityIdentifier" : opportunityIdentifier, 
        "RelatedEntityType" : "Solutions", 
        "RelatedEntityIdentifier" : original_entity_identifier 
    }

    associate_opportunity_request ={
        "Catalog": CATALOG_TO_USE,
	    "OpportunityIdentifier" : opportunityIdentifier, 
        "RelatedEntityType" : "Solutions", 
        "RelatedEntityIdentifier" : new_entity_identifier 
    }
    try:
        # Perform an API call
        response = partner_central_client.disassociate_opportunity(**disassociate_opportunity_request)
        response = partner_central_client.associate_opportunity(**associate_opportunity_request)
        return response

    except ClientError as err:
        # Catch all client exceptions
        print(err.response)

def usage_demo():
    original_entity_identifier = "S-0049999"
    new_entity_identifier = "S-0050014"
    opportunityIdentifier = "O4397574"

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Replacing a solution.")
    print("-" * 88)

    helper.pretty_print_datetime(replace_solution(original_entity_identifier, new_entity_identifier, opportunityIdentifier))

if __name__ == "__main__":
    usage_demo()
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [AssociateOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/AssociateOpportunity)
  + [DisassociateOpportunity](https://docs.aws.amazon.com/goto/boto3/partnercentral-selling-2022-07-26/DisassociateOpportunity)

# SDK for Python (Boto3) を使用する Amazon Pinpoint の例
<a name="python_3_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendMessages`
<a name="pinpoint_SendMessages_python_3_topic"></a>

次のコード例は、`SendMessages` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/pinpoint#code-examples)での設定と実行の方法を確認してください。
E メールメッセージを送信します。  

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_email_message(
    pinpoint_client,
    app_id,
    sender,
    to_addresses,
    char_set,
    subject,
    html_message,
    text_message,
):
    """
    Sends an email message with HTML and plain text versions.

    :param pinpoint_client: A Boto3 Pinpoint client.
    :param app_id: The Amazon Pinpoint project ID to use when you send this message.
    :param sender: The "From" address. This address must be verified in
                   Amazon Pinpoint in the AWS Region you're using to send email.
    :param to_addresses: The addresses on the "To" line. If your Amazon Pinpoint account
                         is in the sandbox, these addresses must be verified.
    :param char_set: The character encoding to use for the subject line and message
                     body of the email.
    :param subject: The subject line of the email.
    :param html_message: The body of the email for recipients whose email clients can
                         display HTML content.
    :param text_message: The body of the email for recipients whose email clients
                         don't support HTML content.
    :return: A dict of to_addresses and their message IDs.
    """
    try:
        response = pinpoint_client.send_messages(
            ApplicationId=app_id,
            MessageRequest={
                "Addresses": {
                    to_address: {"ChannelType": "EMAIL"} for to_address in to_addresses
                },
                "MessageConfiguration": {
                    "EmailMessage": {
                        "FromAddress": sender,
                        "SimpleEmail": {
                            "Subject": {"Charset": char_set, "Data": subject},
                            "HtmlPart": {"Charset": char_set, "Data": html_message},
                            "TextPart": {"Charset": char_set, "Data": text_message},
                        },
                    }
                },
            },
        )
    except ClientError:
        logger.exception("Couldn't send email.")
        raise
    else:
        return {
            to_address: message["MessageId"]
            for to_address, message in response["MessageResponse"]["Result"].items()
        }


def main():
    app_id = "ce796be37f32f178af652b26eexample"
    sender = "sender@example.com"
    to_address = "recipient@example.com"
    char_set = "UTF-8"
    subject = "Amazon Pinpoint Test (SDK for Python (Boto3))"
    text_message = """Amazon Pinpoint Test (SDK for Python)
    -------------------------------------
    This email was sent with Amazon Pinpoint using the AWS SDK for Python (Boto3).
    For more information, see https://aws.amazon.com/sdk-for-python/
                """
    html_message = """<html>
    <head></head>
    <body>
      <h1>Amazon Pinpoint Test (SDK for Python (Boto3)</h1>
      <p>This email was sent with
        <a href='https://aws.amazon.com/pinpoint/'>Amazon Pinpoint</a> using the
        <a href='https://aws.amazon.com/sdk-for-python/'>
          AWS SDK for Python (Boto3)</a>.</p>
    </body>
    </html>
                """

    print("Sending email.")
    message_ids = send_email_message(
        boto3.client("pinpoint"),
        app_id,
        sender,
        [to_address],
        char_set,
        subject,
        html_message,
        text_message,
    )
    print(f"Message sent! Message IDs: {message_ids}")


if __name__ == "__main__":
    main()
```
SMS メッセージを送信します。  

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_sms_message(
    pinpoint_client,
    app_id,
    origination_number,
    destination_number,
    message,
    message_type,
):
    """
    Sends an SMS message with Amazon Pinpoint.

    :param pinpoint_client: A Boto3 Pinpoint client.
    :param app_id: The Amazon Pinpoint project/application ID to use when you send
                   this message. The SMS channel must be enabled for the project or
                   application.
    :param destination_number: The recipient's phone number in E.164 format.
    :param origination_number: The phone number to send the message from. This phone
                               number must be associated with your Amazon Pinpoint
                               account and be in E.164 format.
    :param message: The content of the SMS message.
    :param message_type: The type of SMS message that you want to send. If you send
                         time-sensitive content, specify TRANSACTIONAL. If you send
                         marketing-related content, specify PROMOTIONAL.
    :return: The ID of the message.
    """
    try:
        response = pinpoint_client.send_messages(
            ApplicationId=app_id,
            MessageRequest={
                "Addresses": {destination_number: {"ChannelType": "SMS"}},
                "MessageConfiguration": {
                    "SMSMessage": {
                        "Body": message,
                        "MessageType": message_type,
                        "OriginationNumber": origination_number,
                    }
                },
            },
        )
    except ClientError:
        logger.exception("Couldn't send message.")
        raise
    else:
        return response["MessageResponse"]["Result"][destination_number]["MessageId"]


def main():
    app_id = "ce796be37f32f178af652b26eexample"
    origination_number = "+12065550199"
    destination_number = "+14255550142"
    message = (
        "This is a sample message sent from Amazon Pinpoint by using the AWS SDK for "
        "Python (Boto 3)."
    )
    message_type = "TRANSACTIONAL"

    print("Sending SMS message.")
    message_id = send_sms_message(
        boto3.client("pinpoint"),
        app_id,
        origination_number,
        destination_number,
        message,
        message_type,
    )
    print(f"Message sent! Message ID: {message_id}.")


if __name__ == "__main__":
    main()
```
既存の E メールテンプレートを使用して E メールメッセージを送信します。  

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_templated_email_message(
    pinpoint_client, project_id, sender, to_addresses, template_name, template_version
):
    """
    Sends an email message with HTML and plain text versions.

    :param pinpoint_client: A Boto3 Pinpoint client.
    :param project_id: The Amazon Pinpoint project ID to use when you send this message.
    :param sender: The "From" address. This address must be verified in
                   Amazon Pinpoint in the AWS Region you're using to send email.
    :param to_addresses: The addresses on the "To" line. If your Amazon Pinpoint
                         account is in the sandbox, these addresses must be verified.
    :param template_name: The name of the email template to use when sending the message.
    :param template_version: The version number of the message template.

    :return: A dict of to_addresses and their message IDs.
    """
    try:
        response = pinpoint_client.send_messages(
            ApplicationId=project_id,
            MessageRequest={
                "Addresses": {
                    to_address: {"ChannelType": "EMAIL"} for to_address in to_addresses
                },
                "MessageConfiguration": {"EmailMessage": {"FromAddress": sender}},
                "TemplateConfiguration": {
                    "EmailTemplate": {
                        "Name": template_name,
                        "Version": template_version,
                    }
                },
            },
        )
    except ClientError:
        logger.exception("Couldn't send email.")
        raise
    else:
        return {
            to_address: message["MessageId"]
            for to_address, message in response["MessageResponse"]["Result"].items()
        }


def main():
    project_id = "296b04b342374fceb661bf494example"
    sender = "sender@example.com"
    to_addresses = ["recipient@example.com"]
    template_name = "My_Email_Template"
    template_version = "1"

    print("Sending email.")
    message_ids = send_templated_email_message(
        boto3.client("pinpoint"),
        project_id,
        sender,
        to_addresses,
        template_name,
        template_version,
    )
    print(f"Message sent! Message IDs: {message_ids}")


if __name__ == "__main__":
    main()
```
既存の SMS テンプレートを使用してテキストメッセージを送信します。  

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_templated_sms_message(
    pinpoint_client,
    project_id,
    destination_number,
    message_type,
    origination_number,
    template_name,
    template_version,
):
    """
    Sends an SMS message to a specific phone number using a pre-defined template.

    :param pinpoint_client: A Boto3 Pinpoint client.
    :param project_id: An Amazon Pinpoint project (application) ID.
    :param destination_number: The phone number to send the message to.
    :param message_type: The type of SMS message (promotional or transactional).
    :param origination_number: The phone number that the message is sent from.
    :param template_name: The name of the SMS template to use when sending the message.
    :param template_version: The version number of the message template.

    :return The ID of the message.
    """
    try:
        response = pinpoint_client.send_messages(
            ApplicationId=project_id,
            MessageRequest={
                "Addresses": {destination_number: {"ChannelType": "SMS"}},
                "MessageConfiguration": {
                    "SMSMessage": {
                        "MessageType": message_type,
                        "OriginationNumber": origination_number,
                    }
                },
                "TemplateConfiguration": {
                    "SMSTemplate": {"Name": template_name, "Version": template_version}
                },
            },
        )

    except ClientError:
        logger.exception("Couldn't send message.")
        raise
    else:
        return response["MessageResponse"]["Result"][destination_number]["MessageId"]


def main():
    region = "us-east-1"
    origination_number = "+18555550001"
    destination_number = "+14255550142"
    project_id = "7353f53e6885409fa32d07cedexample"
    message_type = "TRANSACTIONAL"
    template_name = "My_SMS_Template"
    template_version = "1"
    message_id = send_templated_sms_message(
        boto3.client("pinpoint", region_name=region),
        project_id,
        destination_number,
        message_type,
        origination_number,
        template_name,
        template_version,
    )
    print(f"Message sent! Message ID: {message_id}.")


if __name__ == "__main__":
    main()
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[SendMessage](https://docs.aws.amazon.com/goto/boto3/pinpoint-2016-12-01/SendMessages)」を参照してください。

# SDK for Python (Boto3) を使用する Amazon Pinpoint および音声 API の例
<a name="python_3_pinpoint-sms-voice_code_examples"></a>

次のコード例は、Amazon Pinpoint SMS および音声 API AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendVoiceMessage`
<a name="pinpoint-sms-voice_SendVoiceMessage_python_3_topic"></a>

次のコード例は、`SendVoiceMessage` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/pinpoint-sms-voice#code-examples)での設定と実行の方法を確認してください。

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def send_voice_message(
    sms_voice_client,
    origination_number,
    caller_id,
    destination_number,
    language_code,
    voice_id,
    ssml_message,
):
    """
    Sends a voice message using speech synthesis provided by Amazon Polly.

    :param sms_voice_client: A Boto3 PinpointSMSVoice client.
    :param origination_number: The phone number that the message is sent from.
                               The phone number must be associated with your Amazon
                               Pinpoint account and be in E.164 format.
    :param caller_id: The phone number that you want to appear on the recipient's
                      device. The phone number must be associated with your Amazon
                      Pinpoint account and be in E.164 format.
    :param destination_number: The recipient's phone number. Specify the phone
                               number in E.164 format.
    :param language_code: The language to use when sending the message.
    :param voice_id: The Amazon Polly voice that you want to use to send the message.
    :param ssml_message: The content of the message. This example uses SSML to control
                         certain aspects of the message, such as the volume and the
                         speech rate. The message must not contain line breaks.
    :return: The ID of the message.
    """
    try:
        response = sms_voice_client.send_voice_message(
            DestinationPhoneNumber=destination_number,
            OriginationPhoneNumber=origination_number,
            CallerId=caller_id,
            Content={
                "SSMLMessage": {
                    "LanguageCode": language_code,
                    "VoiceId": voice_id,
                    "Text": ssml_message,
                }
            },
        )
    except ClientError:
        logger.exception(
            "Couldn't send message from %s to %s.",
            origination_number,
            destination_number,
        )
        raise
    else:
        return response["MessageId"]


def main():
    origination_number = "+12065550110"
    caller_id = "+12065550199"
    destination_number = "+12065550142"
    language_code = "en-US"
    voice_id = "Matthew"
    ssml_message = (
        "<speak>"
        "This is a test message sent from <emphasis>Amazon Pinpoint</emphasis> "
        "using the <break strength='weak'/>AWS SDK for Python (Boto3). "
        "<amazon:effect phonation='soft'>Thank you for listening."
        "</amazon:effect>"
        "</speak>"
    )
    print(f"Sending voice message from {origination_number} to {destination_number}.")
    message_id = send_voice_message(
        boto3.client("pinpoint-sms-voice"),
        origination_number,
        caller_id,
        destination_number,
        language_code,
        voice_id,
        ssml_message,
    )
    print(f"Message sent!\nMessage ID: {message_id}")


if __name__ == "__main__":
    main()
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[SendVoiceMessage](https://docs.aws.amazon.com/goto/boto3/pinpoint-sms-voice-2018-09-05/SendVoiceMessage)」を参照してください。

# SDK for Python (Boto3) を使用する Amazon Polly の例
<a name="python_3_polly_code_examples"></a>

次のコード例は、Amazon Polly AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DescribeVoices`
<a name="polly_DescribeVoices_python_3_topic"></a>

次のコード例は、`DescribeVoices` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
class PollyWrapper:
    """Encapsulates Amazon Polly functions."""

    def __init__(self, polly_client, s3_resource):
        """
        :param polly_client: A Boto3 Amazon Polly client.
        :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource.
        """
        self.polly_client = polly_client
        self.s3_resource = s3_resource
        self.voice_metadata = None


    def describe_voices(self):
        """
        Gets metadata about available voices.

        :return: The list of voice metadata.
        """
        try:
            response = self.polly_client.describe_voices()
            self.voice_metadata = response["Voices"]
            logger.info("Got metadata about %s voices.", len(self.voice_metadata))
        except ClientError:
            logger.exception("Couldn't get voice metadata.")
            raise
        else:
            return self.voice_metadata
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeVoices](https://docs.aws.amazon.com/goto/boto3/polly-2016-06-10/DescribeVoices)」を参照してください。

### `GetLexicon`
<a name="polly_GetLexicon_python_3_topic"></a>

次のコード例は、`GetLexicon` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
class PollyWrapper:
    """Encapsulates Amazon Polly functions."""

    def __init__(self, polly_client, s3_resource):
        """
        :param polly_client: A Boto3 Amazon Polly client.
        :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource.
        """
        self.polly_client = polly_client
        self.s3_resource = s3_resource
        self.voice_metadata = None


    def get_lexicon(self, name):
        """
        Gets metadata and contents of an existing lexicon.

        :param name: The name of the lexicon to retrieve.
        :return: The retrieved lexicon.
        """
        try:
            response = self.polly_client.get_lexicon(Name=name)
            logger.info("Got lexicon %s.", name)
        except ClientError:
            logger.exception("Couldn't get lexicon %s.", name)
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetLexicon](https://docs.aws.amazon.com/goto/boto3/polly-2016-06-10/GetLexicon)」を参照してください。

### `GetSpeechSynthesisTask`
<a name="polly_GetSpeechSynthesisTask_python_3_topic"></a>

次のコード例は、`GetSpeechSynthesisTask` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
class PollyWrapper:
    """Encapsulates Amazon Polly functions."""

    def __init__(self, polly_client, s3_resource):
        """
        :param polly_client: A Boto3 Amazon Polly client.
        :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource.
        """
        self.polly_client = polly_client
        self.s3_resource = s3_resource
        self.voice_metadata = None


    def get_speech_synthesis_task(self, task_id):
        """
        Gets metadata about an asynchronous speech synthesis task, such as its status.

        :param task_id: The ID of the task to retrieve.
        :return: Metadata about the task.
        """
        try:
            response = self.polly_client.get_speech_synthesis_task(TaskId=task_id)
            task = response["SynthesisTask"]
            logger.info("Got synthesis task. Status is %s.", task["TaskStatus"])
        except ClientError:
            logger.exception("Couldn't get synthesis task %s.", task_id)
            raise
        else:
            return task
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetSpeechSynthesisTask](https://docs.aws.amazon.com/goto/boto3/polly-2016-06-10/GetSpeechSynthesisTask)」を参照してください。

### `ListLexicons`
<a name="polly_ListLexicons_python_3_topic"></a>

次のコード例は、`ListLexicons` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
class PollyWrapper:
    """Encapsulates Amazon Polly functions."""

    def __init__(self, polly_client, s3_resource):
        """
        :param polly_client: A Boto3 Amazon Polly client.
        :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource.
        """
        self.polly_client = polly_client
        self.s3_resource = s3_resource
        self.voice_metadata = None


    def list_lexicons(self):
        """
        Lists lexicons in the current account.

        :return: The list of lexicons.
        """
        try:
            response = self.polly_client.list_lexicons()
            lexicons = response["Lexicons"]
            logger.info("Got %s lexicons.", len(lexicons))
        except ClientError:
            logger.exception(
                "Couldn't get  %s.",
            )
            raise
        else:
            return lexicons
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListLexicons](https://docs.aws.amazon.com/goto/boto3/polly-2016-06-10/ListLexicons)」を参照してください。

### `PutLexicon`
<a name="polly_PutLexicon_python_3_topic"></a>

次のコード例は、`PutLexicon` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
class PollyWrapper:
    """Encapsulates Amazon Polly functions."""

    def __init__(self, polly_client, s3_resource):
        """
        :param polly_client: A Boto3 Amazon Polly client.
        :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource.
        """
        self.polly_client = polly_client
        self.s3_resource = s3_resource
        self.voice_metadata = None


    def create_lexicon(self, name, content):
        """
        Creates a lexicon with the specified content. A lexicon contains custom
        pronunciations.

        :param name: The name of the lexicon.
        :param content: The content of the lexicon.
        """
        try:
            self.polly_client.put_lexicon(Name=name, Content=content)
            logger.info("Created lexicon %s.", name)
        except ClientError:
            logger.exception("Couldn't create lexicon %s.")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[PutLexicon](https://docs.aws.amazon.com/goto/boto3/polly-2016-06-10/PutLexicon)」を参照してください。

### `StartSpeechSynthesisTask`
<a name="polly_StartSpeechSynthesisTask_python_3_topic"></a>

次のコード例は、`StartSpeechSynthesisTask` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
class PollyWrapper:
    """Encapsulates Amazon Polly functions."""

    def __init__(self, polly_client, s3_resource):
        """
        :param polly_client: A Boto3 Amazon Polly client.
        :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource.
        """
        self.polly_client = polly_client
        self.s3_resource = s3_resource
        self.voice_metadata = None


    def do_synthesis_task(
        self,
        text,
        engine,
        voice,
        audio_format,
        s3_bucket,
        lang_code=None,
        include_visemes=False,
        wait_callback=None,
    ):
        """
        Start an asynchronous task to synthesize speech or speech marks, wait for
        the task to complete, retrieve the output from Amazon S3, and return the
        data.

        An asynchronous task is required when the text is too long for near-real time
        synthesis.

        :param text: The text to synthesize.
        :param engine: The kind of engine used. Can be standard or neural.
        :param voice: The ID of the voice to use.
        :param audio_format: The audio format to return for synthesized speech. When
                             speech marks are synthesized, the output format is JSON.
        :param s3_bucket: The name of an existing Amazon S3 bucket that you have
                          write access to. Synthesis output is written to this bucket.
        :param lang_code: The language code of the voice to use. This has an effect
                          only when a bilingual voice is selected.
        :param include_visemes: When True, a second request is made to Amazon Polly
                                to synthesize a list of visemes, using the specified
                                text and voice. A viseme represents the visual position
                                of the face and mouth when saying part of a word.
        :param wait_callback: A callback function that is called periodically during
                              task processing, to give the caller an opportunity to
                              take action, such as to display status.
        :return: The audio stream that contains the synthesized speech and a list
                 of visemes that are associated with the speech audio.
        """
        try:
            kwargs = {
                "Engine": engine,
                "OutputFormat": audio_format,
                "OutputS3BucketName": s3_bucket,
                "Text": text,
                "VoiceId": voice,
            }
            if lang_code is not None:
                kwargs["LanguageCode"] = lang_code
            response = self.polly_client.start_speech_synthesis_task(**kwargs)
            speech_task = response["SynthesisTask"]
            logger.info("Started speech synthesis task %s.", speech_task["TaskId"])

            viseme_task = None
            if include_visemes:
                kwargs["OutputFormat"] = "json"
                kwargs["SpeechMarkTypes"] = ["viseme"]
                response = self.polly_client.start_speech_synthesis_task(**kwargs)
                viseme_task = response["SynthesisTask"]
                logger.info("Started viseme synthesis task %s.", viseme_task["TaskId"])
        except ClientError:
            logger.exception("Couldn't start synthesis task.")
            raise
        else:
            bucket = self.s3_resource.Bucket(s3_bucket)
            audio_stream = self._wait_for_task(
                10, speech_task["TaskId"], "speech", wait_callback, bucket
            )

            visemes = None
            if include_visemes:
                viseme_data = self._wait_for_task(
                    10, viseme_task["TaskId"], "viseme", wait_callback, bucket
                )
                visemes = [
                    json.loads(v) for v in viseme_data.read().decode().split() if v
                ]

            return audio_stream, visemes
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartSpeechSynthesisTask](https://docs.aws.amazon.com/goto/boto3/polly-2016-06-10/StartSpeechSynthesisTask)」を参照してください。

### `SynthesizeSpeech`
<a name="polly_SynthesizeSpeech_python_3_topic"></a>

次のコード例は、`SynthesizeSpeech` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
class PollyWrapper:
    """Encapsulates Amazon Polly functions."""

    def __init__(self, polly_client, s3_resource):
        """
        :param polly_client: A Boto3 Amazon Polly client.
        :param s3_resource: A Boto3 Amazon Simple Storage Service (Amazon S3) resource.
        """
        self.polly_client = polly_client
        self.s3_resource = s3_resource
        self.voice_metadata = None


    def synthesize(
        self, text, engine, voice, audio_format, lang_code=None, include_visemes=False
    ):
        """
        Synthesizes speech or speech marks from text, using the specified voice.

        :param text: The text to synthesize.
        :param engine: The kind of engine used. Can be standard or neural.
        :param voice: The ID of the voice to use.
        :param audio_format: The audio format to return for synthesized speech. When
                             speech marks are synthesized, the output format is JSON.
        :param lang_code: The language code of the voice to use. This has an effect
                          only when a bilingual voice is selected.
        :param include_visemes: When True, a second request is made to Amazon Polly
                                to synthesize a list of visemes, using the specified
                                text and voice. A viseme represents the visual position
                                of the face and mouth when saying part of a word.
        :return: The audio stream that contains the synthesized speech and a list
                 of visemes that are associated with the speech audio.
        """
        try:
            kwargs = {
                "Engine": engine,
                "OutputFormat": audio_format,
                "Text": text,
                "VoiceId": voice,
            }
            if lang_code is not None:
                kwargs["LanguageCode"] = lang_code
            response = self.polly_client.synthesize_speech(**kwargs)
            audio_stream = response["AudioStream"]
            logger.info("Got audio stream spoken by %s.", voice)
            visemes = None
            if include_visemes:
                kwargs["OutputFormat"] = "json"
                kwargs["SpeechMarkTypes"] = ["viseme"]
                response = self.polly_client.synthesize_speech(**kwargs)
                visemes = [
                    json.loads(v)
                    for v in response["AudioStream"].read().decode().split()
                    if v
                ]
                logger.info("Got %s visemes.", len(visemes))
        except ClientError:
            logger.exception("Couldn't get audio stream.")
            raise
        else:
            return audio_stream, visemes
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SynthesizeSpeech](https://docs.aws.amazon.com/goto/boto3/polly-2016-06-10/SynthesizeSpeech)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### リップシンクアプリケーションを作成する
<a name="polly_LipSync_python_3_topic"></a>

次のコード例は、Amazon Polly でリップシンクアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Polly と Tkinter を使用して、Amazon Polly で合成された音声とともに音声をアニメーション表示するリップシンクアプリケーションを作成する方法を説明します。リップシンクは、合成された音声と一致する口形素のリストを Amazon Polly にリクエストすることで実現されます。  
+ Amazon Polly から音声メタデータを取得し、Tkinter アプリケーションに表示します。
+ Amazon Polly から合成音声とそれに対応する口形素の音声記号を取得できます。
+ 口の動きが同期した音声を、アニメーション化された顔で再生します。
+ 長いテキストに対する非同期合成タスクを送信し、Amazon Simple Storage Service (Amazon S3) バケットから出力を取得します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/polly#code-examples) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Polly

# SDK for Python (Boto3) を使用する Amazon RDS の例
<a name="python_3_rds_code_examples"></a>

次のコード例は、Amazon RDS AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon RDS
<a name="rds_Hello_python_3_topic"></a>

次のコード例は、Amazon RDS の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
"""
Purpose

Shows how to use the AWS SDK for Python (Boto3) with the Amazon Relational Database Service
(Amazon RDS) to list the databases in your account.
"""

import boto3
from botocore.exceptions import ClientError

# Create an RDS client
rds_client = boto3.client("rds")

# Create a paginator for the describe_db_instances operation
paginator = rds_client.get_paginator("describe_db_instances")

try:
    # Use the paginator to get a list of DB instances
    response_iterator = paginator.paginate(
        PaginationConfig={
            "MaxItems": 123,
            "PageSize": 50,  # Adjust PageSize as needed
            "StartingToken": None,
        }
    )

    # Iterate through the pages of the response
    instances_found = False
    for page in response_iterator:
        if "DBInstances" in page and page["DBInstances"]:
            instances_found = True
            print("Your RDS instances are:")
            for db in page["DBInstances"]:
                print(db["DBInstanceIdentifier"])

    if not instances_found:
        print("No RDS instances found!")

except ClientError as e:
    print(f"Couldn't list RDS instances. Here's why: {e.response['Error']['Message']}")
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="rds_Scenario_GetStartedInstances_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム DB パラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用するように設定した DB インスタンスを作成します。DB インスタンスにはデータベースも含まれています。
+ インスタンスのスナップショットを取得します。
+ インスタンスとパラメータグループを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class RdsInstanceScenario:
    """Runs a scenario that shows how to get started using Amazon RDS DB instances."""

    def __init__(self, instance_wrapper):
        """
        :param instance_wrapper: An object that wraps Amazon RDS DB instance actions.
        """
        self.instance_wrapper = instance_wrapper

    def create_parameter_group(self, parameter_group_name, db_engine):
        """
        Shows how to get available engine versions for a specified database engine and
        create a DB parameter group that is compatible with a selected engine family.

        :param parameter_group_name: The name given to the newly created parameter group.
        :param db_engine: The database engine to use as a basis.
        :return: The newly created parameter group.
        """
        print(
            f"Checking for an existing DB instance parameter group named {parameter_group_name}."
        )
        parameter_group = self.instance_wrapper.get_parameter_group(
            parameter_group_name
        )
        if parameter_group is None:
            print(f"Getting available database engine versions for {db_engine}.")
            engine_versions = self.instance_wrapper.get_engine_versions(db_engine)
            families = list({ver["DBParameterGroupFamily"] for ver in engine_versions})
            family_index = q.choose("Which family do you want to use? ", families)
            print(f"Creating a parameter group.")
            self.instance_wrapper.create_parameter_group(
                parameter_group_name, families[family_index], "Example parameter group."
            )
            parameter_group = self.instance_wrapper.get_parameter_group(
                parameter_group_name
            )
        print(f"Parameter group {parameter_group['DBParameterGroupName']}:")
        pp(parameter_group)
        print("-" * 88)
        return parameter_group

    def update_parameters(self, parameter_group_name):
        """
        Shows how to get the parameters contained in a custom parameter group and
        update some of the parameter values in the group.

        :param parameter_group_name: The name of the parameter group to query and modify.
        """
        print("Let's set some parameter values in your parameter group.")
        auto_inc_parameters = self.instance_wrapper.get_parameters(
            parameter_group_name, name_prefix="auto_increment"
        )
        update_params = []
        for auto_inc in auto_inc_parameters:
            if auto_inc["IsModifiable"] and auto_inc["DataType"] == "integer":
                print(f"The {auto_inc['ParameterName']} parameter is described as:")
                print(f"\t{auto_inc['Description']}")
                param_range = auto_inc["AllowedValues"].split("-")
                auto_inc["ParameterValue"] = str(
                    q.ask(
                        f"Enter a value between {param_range[0]} and {param_range[1]}: ",
                        q.is_int,
                        q.in_range(int(param_range[0]), int(param_range[1])),
                    )
                )
                update_params.append(auto_inc)
        self.instance_wrapper.update_parameters(parameter_group_name, update_params)
        print(
            "You can get a list of parameters you've set by specifying a source of 'user'."
        )
        user_parameters = self.instance_wrapper.get_parameters(
            parameter_group_name, source="user"
        )
        pp(user_parameters)
        print("-" * 88)

    def create_instance(self, instance_name, db_name, db_engine, parameter_group):
        """
        Shows how to create a DB instance that contains a database of a specified
        type and is configured to use a custom DB parameter group.

        :param instance_name: The name given to the newly created DB instance.
        :param db_name: The name given to the created database.
        :param db_engine: The engine of the created database.
        :param parameter_group: The parameter group that is associated with the DB instance.
        :return: The newly created DB instance.
        """
        print("Checking for an existing DB instance.")
        db_inst = self.instance_wrapper.get_db_instance(instance_name)
        if db_inst is None:
            print("Let's create a DB instance.")
            admin_username = q.ask(
                "Enter an administrator user name for the database: ", q.non_empty
            )
            admin_password = q.ask(
                "Enter a password for the administrator (at least 8 characters): ",
                q.non_empty,
            )
            engine_versions = self.instance_wrapper.get_engine_versions(
                db_engine, parameter_group["DBParameterGroupFamily"]
            )
            engine_choices = [ver["EngineVersion"] for ver in engine_versions]
            print("The available engines for your parameter group are:")
            engine_index = q.choose("Which engine do you want to use? ", engine_choices)
            engine_selection = engine_versions[engine_index]
            print(
                "The available micro DB instance classes for your database engine are:"
            )
            inst_opts = self.instance_wrapper.get_orderable_instances(
                engine_selection["Engine"], engine_selection["EngineVersion"]
            )
            inst_choices = list(
                {
                    opt["DBInstanceClass"]
                    for opt in inst_opts
                    if "micro" in opt["DBInstanceClass"]
                }
            )
            inst_index = q.choose(
                "Which micro DB instance class do you want to use? ", inst_choices
            )
            group_name = parameter_group["DBParameterGroupName"]
            storage_type = "standard"
            allocated_storage = 5
            print(
                f"Creating a DB instance named {instance_name} and database {db_name}.\n"
                f"The DB instance is configured to use your custom parameter group {group_name},\n"
                f"selected engine {engine_selection['EngineVersion']},\n"
                f"selected DB instance class {inst_choices[inst_index]},"
                f"and {allocated_storage} GiB of {storage_type} storage.\n"
                f"This typically takes several minutes."
            )
            db_inst = self.instance_wrapper.create_db_instance(
                db_name,
                instance_name,
                group_name,
                engine_selection["Engine"],
                engine_selection["EngineVersion"],
                inst_choices[inst_index],
                storage_type,
                allocated_storage,
                admin_username,
                admin_password,
            )
            while db_inst.get("DBInstanceStatus") != "available":
                wait(10)
                db_inst = self.instance_wrapper.get_db_instance(instance_name)
        print("Instance data:")
        pp(db_inst)
        print("-" * 88)
        return db_inst

    @staticmethod
    def display_connection(db_inst):
        """
        Displays connection information about a DB instance and tips on how to
        connect to it.

        :param db_inst: The DB instance to display.
        """
        print(
            "You can now connect to your database using your favorite MySql client.\n"
            "One way to connect is by using the 'mysql' shell on an Amazon EC2 instance\n"
            "that is running in the same VPC as your DB instance. Pass the endpoint,\n"
            "port, and administrator user name to 'mysql' and enter your password\n"
            "when prompted:\n"
        )
        print(
            f"\n\tmysql -h {db_inst['Endpoint']['Address']} -P {db_inst['Endpoint']['Port']} "
            f"-u {db_inst['MasterUsername']} -p\n"
        )
        print(
            "For more information, see the User Guide for Amazon RDS:\n"
            "\thttps://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html#CHAP_GettingStarted.Connecting.MySQL"
        )
        print("-" * 88)

    def create_snapshot(self, instance_name):
        """
        Shows how to create a DB instance snapshot and wait until it's available.

        :param instance_name: The name of a DB instance to snapshot.
        """
        if q.ask(
            "Do you want to create a snapshot of your DB instance (y/n)? ", q.is_yesno
        ):
            snapshot_id = f"{instance_name}-{uuid.uuid4()}"
            print(
                f"Creating a snapshot named {snapshot_id}. This typically takes a few minutes."
            )
            snapshot = self.instance_wrapper.create_snapshot(snapshot_id, instance_name)
            while snapshot.get("Status") != "available":
                wait(10)
                snapshot = self.instance_wrapper.get_snapshot(snapshot_id)
            pp(snapshot)
            print("-" * 88)

    def cleanup(self, db_inst, parameter_group_name):
        """
        Shows how to clean up a DB instance and parameter group.
        Before the parameter group can be deleted, all associated DB instances must first
        be deleted.

        :param db_inst: The DB instance to delete.
        :param parameter_group_name: The DB parameter group to delete.
        """
        if q.ask(
            "\nDo you want to delete the DB instance and parameter group (y/n)? ",
            q.is_yesno,
        ):
            print(f"Deleting DB instance {db_inst['DBInstanceIdentifier']}.")
            self.instance_wrapper.delete_db_instance(db_inst["DBInstanceIdentifier"])
            print(
                "Waiting for the DB instance to delete. This typically takes several minutes."
            )
            while db_inst is not None:
                wait(10)
                db_inst = self.instance_wrapper.get_db_instance(
                    db_inst["DBInstanceIdentifier"]
                )
            print(f"Deleting parameter group {parameter_group_name}.")
            self.instance_wrapper.delete_parameter_group(parameter_group_name)

    def run_scenario(self, db_engine, parameter_group_name, instance_name, db_name):
        logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

        print("-" * 88)
        print(
            "Welcome to the Amazon Relational Database Service (Amazon RDS)\n"
            "get started with DB instances demo."
        )
        print("-" * 88)

        parameter_group = self.create_parameter_group(parameter_group_name, db_engine)
        self.update_parameters(parameter_group_name)
        db_inst = self.create_instance(
            instance_name, db_name, db_engine, parameter_group
        )
        self.display_connection(db_inst)
        self.create_snapshot(instance_name)
        self.cleanup(db_inst, parameter_group_name)

        print("\nThanks for watching!")
        print("-" * 88)


if __name__ == "__main__":
    try:
        scenario = RdsInstanceScenario(InstanceWrapper.from_client())
        scenario.run_scenario(
            "mysql",
            "doc-example-parameter-group",
            "doc-example-instance",
            "docexampledb",
        )
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
Amazon RDS アクションを管理するためにシナリオによって呼び出される関数を定義します。  

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_parameter_group(self, parameter_group_name):
        """
        Gets a DB parameter group.

        :param parameter_group_name: The name of the parameter group to retrieve.
        :return: The parameter group.
        """
        try:
            response = self.rds_client.describe_db_parameter_groups(
                DBParameterGroupName=parameter_group_name
            )
            parameter_group = response["DBParameterGroups"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBParameterGroupNotFound":
                logger.info("Parameter group %s does not exist.", parameter_group_name)
            else:
                logger.error(
                    "Couldn't get parameter group %s. Here's why: %s: %s",
                    parameter_group_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return parameter_group


    def create_parameter_group(
        self, parameter_group_name, parameter_group_family, description
    ):
        """
        Creates a DB parameter group that is based on the specified parameter group
        family.

        :param parameter_group_name: The name of the newly created parameter group.
        :param parameter_group_family: The family that is used as the basis of the new
                                       parameter group.
        :param description: A description given to the parameter group.
        :return: Data about the newly created parameter group.
        """
        try:
            response = self.rds_client.create_db_parameter_group(
                DBParameterGroupName=parameter_group_name,
                DBParameterGroupFamily=parameter_group_family,
                Description=description,
            )
        except ClientError as err:
            logger.error(
                "Couldn't create parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def delete_parameter_group(self, parameter_group_name):
        """
        Deletes a DB parameter group.

        :param parameter_group_name: The name of the parameter group to delete.
        :return: Data about the parameter group.
        """
        try:
            self.rds_client.delete_db_parameter_group(
                DBParameterGroupName=parameter_group_name
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def get_parameters(self, parameter_group_name, name_prefix="", source=None):
        """
        Gets the parameters that are contained in a DB parameter group.

        :param parameter_group_name: The name of the parameter group to query.
        :param name_prefix: When specified, the retrieved list of parameters is filtered
                            to contain only parameters that start with this prefix.
        :param source: When specified, only parameters from this source are retrieved.
                       For example, a source of 'user' retrieves only parameters that
                       were set by a user.
        :return: The list of requested parameters.
        """
        try:
            kwargs = {"DBParameterGroupName": parameter_group_name}
            if source is not None:
                kwargs["Source"] = source
            parameters = []
            paginator = self.rds_client.get_paginator("describe_db_parameters")
            for page in paginator.paginate(**kwargs):
                parameters += [
                    p
                    for p in page["Parameters"]
                    if p["ParameterName"].startswith(name_prefix)
                ]
        except ClientError as err:
            logger.error(
                "Couldn't get parameters for %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return parameters


    def update_parameters(self, parameter_group_name, update_parameters):
        """
        Updates parameters in a custom DB parameter group.

        :param parameter_group_name: The name of the parameter group to update.
        :param update_parameters: The parameters to update in the group.
        :return: Data about the modified parameter group.
        """
        try:
            response = self.rds_client.modify_db_parameter_group(
                DBParameterGroupName=parameter_group_name, Parameters=update_parameters
            )
        except ClientError as err:
            logger.error(
                "Couldn't update parameters in %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def create_snapshot(self, snapshot_id, instance_id):
        """
        Creates a snapshot of a DB instance.

        :param snapshot_id: The ID to give the created snapshot.
        :param instance_id: The ID of the DB instance to snapshot.
        :return: Data about the newly created snapshot.
        """
        try:
            response = self.rds_client.create_db_snapshot(
                DBSnapshotIdentifier=snapshot_id, DBInstanceIdentifier=instance_id
            )
            snapshot = response["DBSnapshot"]
        except ClientError as err:
            logger.error(
                "Couldn't create snapshot of %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot


    def get_snapshot(self, snapshot_id):
        """
        Gets a DB instance snapshot.

        :param snapshot_id: The ID of the snapshot to retrieve.
        :return: The retrieved snapshot.
        """
        try:
            response = self.rds_client.describe_db_snapshots(
                DBSnapshotIdentifier=snapshot_id
            )
            snapshot = response["DBSnapshots"][0]
        except ClientError as err:
            logger.error(
                "Couldn't get snapshot %s. Here's why: %s: %s",
                snapshot_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot


    def get_engine_versions(self, engine, parameter_group_family=None):
        """
        Gets database engine versions that are available for the specified engine
        and parameter group family.

        :param engine: The database engine to look up.
        :param parameter_group_family: When specified, restricts the returned list of
                                       engine versions to those that are compatible with
                                       this parameter group family.
        :return: The list of database engine versions.
        """
        try:
            kwargs = {"Engine": engine}
            if parameter_group_family is not None:
                kwargs["DBParameterGroupFamily"] = parameter_group_family
            response = self.rds_client.describe_db_engine_versions(**kwargs)
            versions = response["DBEngineVersions"]
        except ClientError as err:
            logger.error(
                "Couldn't get engine versions for %s. Here's why: %s: %s",
                engine,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return versions


    def get_orderable_instances(self, db_engine, db_engine_version):
        """
        Gets DB instance options that can be used to create DB instances that are
        compatible with a set of specifications.

        :param db_engine: The database engine that must be supported by the DB instance.
        :param db_engine_version: The engine version that must be supported by the DB instance.
        :return: The list of DB instance options that can be used to create a compatible DB instance.
        """
        try:
            inst_opts = []
            paginator = self.rds_client.get_paginator(
                "describe_orderable_db_instance_options"
            )
            for page in paginator.paginate(
                Engine=db_engine, EngineVersion=db_engine_version
            ):
                inst_opts += page["OrderableDBInstanceOptions"]
        except ClientError as err:
            logger.error(
                "Couldn't get orderable DB instances. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return inst_opts


    def get_db_instance(self, instance_id):
        """
        Gets data about a DB instance.

        :param instance_id: The ID of the DB instance to retrieve.
        :return: The retrieved DB instance.
        """
        try:
            response = self.rds_client.describe_db_instances(
                DBInstanceIdentifier=instance_id
            )
            db_inst = response["DBInstances"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBInstanceNotFound":
                logger.info("Instance %s does not exist.", instance_id)
            else:
                logger.error(
                    "Couldn't get DB instance %s. Here's why: %s: %s",
                    instance_id,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return db_inst


    def create_db_instance(
        self,
        db_name,
        instance_id,
        parameter_group_name,
        db_engine,
        db_engine_version,
        instance_class,
        storage_type,
        allocated_storage,
        admin_name,
        admin_password,
    ):
        """
        Creates a DB instance.

        :param db_name: The name of the database that is created in the DB instance.
        :param instance_id: The ID to give the newly created DB instance.
        :param parameter_group_name: A parameter group to associate with the DB instance.
        :param db_engine: The database engine of a database to create in the DB instance.
        :param db_engine_version: The engine version for the created database.
        :param instance_class: The DB instance class for the newly created DB instance.
        :param storage_type: The storage type of the DB instance.
        :param allocated_storage: The amount of storage allocated on the DB instance, in GiBs.
        :param admin_name: The name of the admin user for the created database.
        :param admin_password: The admin password for the created database.
        :return: Data about the newly created DB instance.
        """
        try:
            response = self.rds_client.create_db_instance(
                DBName=db_name,
                DBInstanceIdentifier=instance_id,
                DBParameterGroupName=parameter_group_name,
                Engine=db_engine,
                EngineVersion=db_engine_version,
                DBInstanceClass=instance_class,
                StorageType=storage_type,
                AllocatedStorage=allocated_storage,
                MasterUsername=admin_name,
                MasterUserPassword=admin_password,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't create DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst


    def delete_db_instance(self, instance_id):
        """
        Deletes a DB instance.

        :param instance_id: The ID of the DB instance to delete.
        :return: Data about the deleted DB instance.
        """
        try:
            response = self.rds_client.delete_db_instance(
                DBInstanceIdentifier=instance_id,
                SkipFinalSnapshot=True,
                DeleteAutomatedBackups=True,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't delete DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBInstance)
  + [CreateDBParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBParameterGroup)
  + [CreateDBSnapshot](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBSnapshot)
  + [DeleteDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBInstance)
  + [DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBParameterGroup)
  + [DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBEngineVersions)
  + [DescribeDBInstances](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBInstances)
  + [DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBParameterGroups)
  + [DescribeDBParameters](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBParameters)
  + [DescribeDBSnapshots](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBSnapshots)
  + [DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeOrderableDBInstanceOptions)
  + [ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/ModifyDBParameterGroup)

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_python_3_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def create_db_instance(
        self,
        db_name,
        instance_id,
        parameter_group_name,
        db_engine,
        db_engine_version,
        instance_class,
        storage_type,
        allocated_storage,
        admin_name,
        admin_password,
    ):
        """
        Creates a DB instance.

        :param db_name: The name of the database that is created in the DB instance.
        :param instance_id: The ID to give the newly created DB instance.
        :param parameter_group_name: A parameter group to associate with the DB instance.
        :param db_engine: The database engine of a database to create in the DB instance.
        :param db_engine_version: The engine version for the created database.
        :param instance_class: The DB instance class for the newly created DB instance.
        :param storage_type: The storage type of the DB instance.
        :param allocated_storage: The amount of storage allocated on the DB instance, in GiBs.
        :param admin_name: The name of the admin user for the created database.
        :param admin_password: The admin password for the created database.
        :return: Data about the newly created DB instance.
        """
        try:
            response = self.rds_client.create_db_instance(
                DBName=db_name,
                DBInstanceIdentifier=instance_id,
                DBParameterGroupName=parameter_group_name,
                Engine=db_engine,
                EngineVersion=db_engine_version,
                DBInstanceClass=instance_class,
                StorageType=storage_type,
                AllocatedStorage=allocated_storage,
                MasterUsername=admin_name,
                MasterUserPassword=admin_password,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't create DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBInstance)」を参照してください。

### `CreateDBParameterGroup`
<a name="rds_CreateDBParameterGroup_python_3_topic"></a>

次のコード例は、`CreateDBParameterGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def create_parameter_group(
        self, parameter_group_name, parameter_group_family, description
    ):
        """
        Creates a DB parameter group that is based on the specified parameter group
        family.

        :param parameter_group_name: The name of the newly created parameter group.
        :param parameter_group_family: The family that is used as the basis of the new
                                       parameter group.
        :param description: A description given to the parameter group.
        :return: Data about the newly created parameter group.
        """
        try:
            response = self.rds_client.create_db_parameter_group(
                DBParameterGroupName=parameter_group_name,
                DBParameterGroupFamily=parameter_group_family,
                Description=description,
            )
        except ClientError as err:
            logger.error(
                "Couldn't create parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBParameterGroup)」を参照してください。

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_python_3_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def create_snapshot(self, snapshot_id, instance_id):
        """
        Creates a snapshot of a DB instance.

        :param snapshot_id: The ID to give the created snapshot.
        :param instance_id: The ID of the DB instance to snapshot.
        :return: Data about the newly created snapshot.
        """
        try:
            response = self.rds_client.create_db_snapshot(
                DBSnapshotIdentifier=snapshot_id, DBInstanceIdentifier=instance_id
            )
            snapshot = response["DBSnapshot"]
        except ClientError as err:
            logger.error(
                "Couldn't create snapshot of %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateDBSnapshot](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/CreateDBSnapshot)」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_python_3_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def delete_db_instance(self, instance_id):
        """
        Deletes a DB instance.

        :param instance_id: The ID of the DB instance to delete.
        :return: Data about the deleted DB instance.
        """
        try:
            response = self.rds_client.delete_db_instance(
                DBInstanceIdentifier=instance_id,
                SkipFinalSnapshot=True,
                DeleteAutomatedBackups=True,
            )
            db_inst = response["DBInstance"]
        except ClientError as err:
            logger.error(
                "Couldn't delete DB instance %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return db_inst
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDBInstance](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBInstance)」を参照してください。

### `DeleteDBParameterGroup`
<a name="rds_DeleteDBParameterGroup_python_3_topic"></a>

次のコード例は、`DeleteDBParameterGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def delete_parameter_group(self, parameter_group_name):
        """
        Deletes a DB parameter group.

        :param parameter_group_name: The name of the parameter group to delete.
        :return: Data about the parameter group.
        """
        try:
            self.rds_client.delete_db_parameter_group(
                DBParameterGroupName=parameter_group_name
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete parameter group %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteDBParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DeleteDBParameterGroup)」を参照してください。

### `DescribeDBEngineVersions`
<a name="rds_DescribeDBEngineVersions_python_3_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_engine_versions(self, engine, parameter_group_family=None):
        """
        Gets database engine versions that are available for the specified engine
        and parameter group family.

        :param engine: The database engine to look up.
        :param parameter_group_family: When specified, restricts the returned list of
                                       engine versions to those that are compatible with
                                       this parameter group family.
        :return: The list of database engine versions.
        """
        try:
            kwargs = {"Engine": engine}
            if parameter_group_family is not None:
                kwargs["DBParameterGroupFamily"] = parameter_group_family
            response = self.rds_client.describe_db_engine_versions(**kwargs)
            versions = response["DBEngineVersions"]
        except ClientError as err:
            logger.error(
                "Couldn't get engine versions for %s. Here's why: %s: %s",
                engine,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return versions
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBEngineVersions)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_python_3_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_db_instance(self, instance_id):
        """
        Gets data about a DB instance.

        :param instance_id: The ID of the DB instance to retrieve.
        :return: The retrieved DB instance.
        """
        try:
            response = self.rds_client.describe_db_instances(
                DBInstanceIdentifier=instance_id
            )
            db_inst = response["DBInstances"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBInstanceNotFound":
                logger.info("Instance %s does not exist.", instance_id)
            else:
                logger.error(
                    "Couldn't get DB instance %s. Here's why: %s: %s",
                    instance_id,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return db_inst
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_python_3_topic"></a>

次のコード例は、`DescribeDBParameterGroups` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_parameter_group(self, parameter_group_name):
        """
        Gets a DB parameter group.

        :param parameter_group_name: The name of the parameter group to retrieve.
        :return: The parameter group.
        """
        try:
            response = self.rds_client.describe_db_parameter_groups(
                DBParameterGroupName=parameter_group_name
            )
            parameter_group = response["DBParameterGroups"][0]
        except ClientError as err:
            if err.response["Error"]["Code"] == "DBParameterGroupNotFound":
                logger.info("Parameter group %s does not exist.", parameter_group_name)
            else:
                logger.error(
                    "Couldn't get parameter group %s. Here's why: %s: %s",
                    parameter_group_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return parameter_group
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBParameterGroups)」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_python_3_topic"></a>

次のコード例は、`DescribeDBParameters` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_parameters(self, parameter_group_name, name_prefix="", source=None):
        """
        Gets the parameters that are contained in a DB parameter group.

        :param parameter_group_name: The name of the parameter group to query.
        :param name_prefix: When specified, the retrieved list of parameters is filtered
                            to contain only parameters that start with this prefix.
        :param source: When specified, only parameters from this source are retrieved.
                       For example, a source of 'user' retrieves only parameters that
                       were set by a user.
        :return: The list of requested parameters.
        """
        try:
            kwargs = {"DBParameterGroupName": parameter_group_name}
            if source is not None:
                kwargs["Source"] = source
            parameters = []
            paginator = self.rds_client.get_paginator("describe_db_parameters")
            for page in paginator.paginate(**kwargs):
                parameters += [
                    p
                    for p in page["Parameters"]
                    if p["ParameterName"].startswith(name_prefix)
                ]
        except ClientError as err:
            logger.error(
                "Couldn't get parameters for %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return parameters
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBParameters](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBParameters)」を参照してください。

### `DescribeDBSnapshots`
<a name="rds_DescribeDBSnapshots_python_3_topic"></a>

次のコード例は、`DescribeDBSnapshots` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_snapshot(self, snapshot_id):
        """
        Gets a DB instance snapshot.

        :param snapshot_id: The ID of the snapshot to retrieve.
        :return: The retrieved snapshot.
        """
        try:
            response = self.rds_client.describe_db_snapshots(
                DBSnapshotIdentifier=snapshot_id
            )
            snapshot = response["DBSnapshots"][0]
        except ClientError as err:
            logger.error(
                "Couldn't get snapshot %s. Here's why: %s: %s",
                snapshot_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return snapshot
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeDBSnapshots](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeDBSnapshots)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="rds_DescribeOrderableDBInstanceOptions_python_3_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def get_orderable_instances(self, db_engine, db_engine_version):
        """
        Gets DB instance options that can be used to create DB instances that are
        compatible with a set of specifications.

        :param db_engine: The database engine that must be supported by the DB instance.
        :param db_engine_version: The engine version that must be supported by the DB instance.
        :return: The list of DB instance options that can be used to create a compatible DB instance.
        """
        try:
            inst_opts = []
            paginator = self.rds_client.get_paginator(
                "describe_orderable_db_instance_options"
            )
            for page in paginator.paginate(
                Engine=db_engine, EngineVersion=db_engine_version
            ):
                inst_opts += page["OrderableDBInstanceOptions"]
        except ClientError as err:
            logger.error(
                "Couldn't get orderable DB instances. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return inst_opts
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/DescribeOrderableDBInstanceOptions)」を参照してください。

### `ModifyDBParameterGroup`
<a name="rds_ModifyDBParameterGroup_python_3_topic"></a>

次のコード例は、`ModifyDBParameterGroup` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
class InstanceWrapper:
    """Encapsulates Amazon RDS DB instance actions."""

    def __init__(self, rds_client):
        """
        :param rds_client: A Boto3 Amazon RDS client.
        """
        self.rds_client = rds_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        rds_client = boto3.client("rds")
        return cls(rds_client)


    def update_parameters(self, parameter_group_name, update_parameters):
        """
        Updates parameters in a custom DB parameter group.

        :param parameter_group_name: The name of the parameter group to update.
        :param update_parameters: The parameters to update in the group.
        :return: Data about the modified parameter group.
        """
        try:
            response = self.rds_client.modify_db_parameter_group(
                DBParameterGroupName=parameter_group_name, Parameters=update_parameters
            )
        except ClientError as err:
            logger.error(
                "Couldn't update parameters in %s. Here's why: %s: %s",
                parameter_group_name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ModifyDBParameterGroup](https://docs.aws.amazon.com/goto/boto3/rds-2014-10-31/ModifyDBParameterGroup)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_python_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して Amazon Aurora Serverless データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信する REST サービス AWS SDK for Python (Boto3) を作成する方法を示します。この例では、Flask ウェブフレームワークを使用して HTTP ルーティングを処理し、React ウェブページと統合して完全に機能するウェブアプリケーションを提供しています。  
+ と統合する Flask REST サービスを構築します AWS のサービス。
+ Aurora Serverless データベースに保存されている作業項目の読み取り、書き込み、更新を行います。
+ データベース認証情報を含む AWS Secrets Manager シークレットを作成し、それを使用してデータベースへの呼び出しを認証します。
+ Amazon SES を使用して作業項目のレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_python_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
import json
import os
import boto3
import pymysql

# RDS settings
proxy_host_name = os.environ['PROXY_HOST_NAME']
port = int(os.environ['PORT'])
db_name = os.environ['DB_NAME']
db_user_name = os.environ['DB_USER_NAME']
aws_region = os.environ['AWS_REGION']


# Fetch RDS Auth Token
def get_auth_token():
    client = boto3.client('rds')
    token = client.generate_db_auth_token(
        DBHostname=proxy_host_name,
        Port=port
        DBUsername=db_user_name
        Region=aws_region
    )
    return token

def lambda_handler(event, context):
    token = get_auth_token()
    try:
        connection = pymysql.connect(
            host=proxy_host_name,
            user=db_user_name,
            password=token,
            db=db_name,
            port=port,
            ssl={'ca': 'Amazon RDS'}  # Ensure you have the CA bundle for SSL connection
        )
        
        with connection.cursor() as cursor:
            cursor.execute('SELECT %s + %s AS sum', (3, 2))
            result = cursor.fetchone()

        return result
        
    except Exception as e:
        return (f"Error: {str(e)}")  # Return an error message if an exception occurs
```

# SDK for Python (Boto3) を使用する Amazon RDS データサービスの例
<a name="python_3_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_python_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して Amazon Aurora Serverless データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信する REST サービス AWS SDK for Python (Boto3) を作成する方法を示します。この例では、Flask ウェブフレームワークを使用して HTTP ルーティングを処理し、React ウェブページと統合して完全に機能するウェブアプリケーションを提供しています。  
+ と統合する Flask REST サービスを構築します AWS のサービス。
+ Aurora Serverless データベースに保存されている作業項目の読み取り、書き込み、更新を行います。
+ データベース認証情報を含む AWS Secrets Manager シークレットを作成し、それを使用してデータベースへの呼び出しを認証します。
+ Amazon SES を使用して作業項目のレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

# SDK for Python (Boto3) を使用する Amazon Redshift の例
<a name="python_3_redshift_code_examples"></a>

次のコード例は、Amazon Redshift AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Redshift
<a name="redshift_Hello_python_3_topic"></a>

次のコード例は、Amazon Redshift の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_redshift(redshift_client):
    """
    Use the AWS SDK for Python (Boto3) to create an Amazon Redshift client and list
    the clusters in your account. This list might be empty if you haven't created
    any clusters.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param redshift_client: A Boto3 Redshift Client object.
    """
    print("Hello, Redshift! Let's list your clusters:")
    paginator = redshift_client.get_paginator("describe_clusters")
    clusters = []
    for page in paginator.paginate():
        clusters.extend(page["Clusters"])

    print(f"{len(clusters)} cluster(s) were found.")

    for cluster in clusters:
        print(f"  {cluster['ClusterIdentifier']}")


if __name__ == "__main__":
    hello_redshift(boto3.client("redshift"))
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DescribeClusters](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/DescribeClusters)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="redshift_Scenario_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Redshift クラスターを作成します。
+ クラスター内のデータベースを一覧表示します。
+ Movies という名前のテーブルを作成します。
+ Movies テーブルにデータを入力します。
+ Movies テーブルに対して年に基づくクエリを実行します。
+ Redshift クラスターを変更します。
+ Amazon Redshift クラスターを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
class RedshiftScenario:
    """Runs an interactive scenario that shows how to get started with Redshift."""

    def __init__(self, redshift_wrapper, redshift_data_wrapper):
        self.redshift_wrapper = redshift_wrapper
        self.redshift_data_wrapper = redshift_data_wrapper

    def redhift_scenario(self, json_file_path):
        database_name = "dev"

        print(DASHES)
        print("Welcome to the Amazon Redshift SDK Getting Started example.")
        print(
            """
      This Python program demonstrates how to interact with Amazon Redshift 
      using the AWS SDK for Python (Boto3).
      
      Amazon Redshift is a fully managed, petabyte-scale data warehouse 
      service hosted in the cloud.
      
      The program's primary functionalities include cluster creation, 
      verification of cluster readiness, listing databases, table creation, 
      populating data within the table, and executing SQL statements.
      
      It also demonstrates querying data from the Movies table.
      
      Upon completion, all AWS resources are cleaned up.
    """
        )
        if not os.path.isfile(json_file_path):
            logging.error(f"The file {json_file_path} does not exist.")
            return

        print("Let's get started...")
        user_name = q.ask("Please enter your user name (default is awsuser):")
        user_name = user_name if user_name else "awsuser"

        print(DASHES)
        user_password = q.ask(
            "Please enter your user password (default is AwsUser1000):"
        )
        user_password = user_password if user_password else "AwsUser1000"

        print(DASHES)
        print(
            """A Redshift cluster refers to the collection of computing resources and storage that work 
            together to process and analyze large volumes of data."""
        )
        cluster_id = q.ask(
            "Enter a cluster identifier value (default is redshift-cluster-movies): "
        )
        cluster_id = cluster_id if cluster_id else "redshift-cluster-movies"

        self.redshift_wrapper.create_cluster(
            cluster_id, "ra3.4xlarge", user_name, user_password, True, 2
        )

        print(DASHES)
        print(f"Wait until {cluster_id} is available. This may take a few minutes...")
        q.ask("Press Enter to continue...")

        self.wait_cluster_available(cluster_id)

        print(DASHES)

        print(
            f"""
       When you created {cluster_id}, the dev database is created by default and used in this scenario.

       To create a custom database, you need to have a CREATEDB privilege.
       For more information, see the documentation here: 
       https://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_DATABASE.html.
      """
        )
        q.ask("Press Enter to continue...")
        print(DASHES)

        print(DASHES)
        print(f"List databases in {cluster_id}")
        q.ask("Press Enter to continue...")
        databases = self.redshift_data_wrapper.list_databases(
            cluster_id, database_name, user_name
        )
        print(f"The cluster contains {len(databases)} database(s).")
        for database in databases:
            print(f"    Database: {database}")
        print(DASHES)

        print(DASHES)
        print("Now you will create a table named Movies.")
        q.ask("Press Enter to continue...")

        self.create_table(cluster_id, database_name, user_name)

        print(DASHES)

        print("Populate the Movies table using the Movies.json file.")
        print(
            "Specify the number of records you would like to add to the Movies Table."
        )
        print("Please enter a value between 50 and 200.")

        while True:
            try:
                num_records = int(q.ask("Enter a value: ", q.is_int))
                if 50 <= num_records <= 200:
                    break
                else:
                    print("Invalid input. Please enter a value between 50 and 200.")
            except ValueError:
                print("Invalid input. Please enter a value between 50 and 200.")

        self.populate_table(
            cluster_id, database_name, user_name, json_file_path, num_records
        )

        print(DASHES)
        print("Query the Movies table by year. Enter a value between 2012-2014.")

        while True:
            movie_year = int(q.ask("Enter a year: ", q.is_int))
            if 2012 <= movie_year <= 2014:
                break
            else:
                print("Invalid input. Please enter a valid year between 2012 and 2014.")

        # Function to query database
        sql_id = self.query_movies_by_year(
            database_name, user_name, movie_year, cluster_id
        )

        print(f"The identifier of the statement is {sql_id}")

        print("Checking statement status...")
        self.wait_statement_finished(sql_id)
        result = self.redshift_data_wrapper.get_statement_result(sql_id)

        self.display_movies(result)

        print(DASHES)

        print(DASHES)
        print("Now you will modify the Redshift cluster.")
        q.ask("Press Enter to continue...")

        preferred_maintenance_window = "wed:07:30-wed:08:00"
        self.redshift_wrapper.modify_cluster(cluster_id, preferred_maintenance_window)

        print(DASHES)

        print(DASHES)
        delete = q.ask("Do you want to delete the cluster? (y/n) ", q.is_yesno)

        if delete:
            print(f"You selected to delete {cluster_id}")
            q.ask("Press Enter to continue...")
            self.redshift_wrapper.delete_cluster(cluster_id)
        else:
            print(f"Cluster {cluster_id}cluster_id was not deleted")

        print(DASHES)
        print("This concludes the Amazon Redshift SDK Getting Started scenario.")
        print(DASHES)

    def create_table(self, cluster_id, database, username):
        self.redshift_data_wrapper.execute_statement(
            cluster_identifier=cluster_id,
            database_name=database,
            user_name=username,
            sql="CREATE TABLE Movies (statement_id INT PRIMARY KEY, title VARCHAR(100), year INT)",
        )

        print("Table created: Movies")


    def populate_table(self, cluster_id, database, username, file_name, number):
        with open(file_name) as f:
            data = json.load(f)

        i = 0
        for record in data:
            if i == number:
                break

            statement_id = i
            title = record["title"]
            year = record["year"]
            i = i + 1
            parameters = [
                {"name": "statement_id", "value": str(statement_id)},
                {"name": "title", "value": title},
                {"name": "year", "value": str(year)},
            ]

            self.redshift_data_wrapper.execute_statement(
                cluster_identifier=cluster_id,
                database_name=database,
                user_name=username,
                sql="INSERT INTO Movies VALUES(:statement_id, :title, :year)",
                parameter_list=parameters,
            )

        print(f"{i} records inserted into Movies table")

    def wait_cluster_available(self, cluster_id):
        """
        Waits for a cluster to be available.

        :param cluster_id: The cluster identifier.

        Note: The cluster_available waiter can also be used.
        It is not used in this case to allow an elapsed time message.
        """
        cluster_ready = False
        start_time = time.time()

        while not cluster_ready:
            time.sleep(30)
            cluster = self.redshift_wrapper.describe_clusters(cluster_id)
            status = cluster[0]["ClusterStatus"]
            if status == "available":
                cluster_ready = True
            elif status != "creating":
                raise Exception(
                    f"Cluster {cluster_id} creation failed with status {status}."
                )

            elapsed_seconds = int(round(time.time() - start_time))
            minutes = int(elapsed_seconds // 60)
            seconds = int(elapsed_seconds % 60)

            print(f"Elapsed Time: {minutes}:{seconds:02d} - status {status}...")

            if minutes > 30:
                raise Exception(
                    f"Cluster {cluster_id} is not available after 30 minutes."
                )

    def query_movies_by_year(self, database, username, year, cluster_id):
        sql = "SELECT * FROM Movies WHERE year = :year"

        params = [{"name": "year", "value": str(year)}]

        response = self.redshift_data_wrapper.execute_statement(
            cluster_identifier=cluster_id,
            database_name=database,
            user_name=username,
            sql=sql,
            parameter_list=params,
        )

        return response["Id"]

    @staticmethod
    def display_movies(response):
        metadata = response["ColumnMetadata"]
        records = response["Records"]

        title_column_index = None
        for i in range(len(metadata)):
            if metadata[i]["name"] == "title":
                title_column_index = i
                break

        if title_column_index is None:
            print("No title column found.")
            return

        print(f"Found {len(records)} movie(s).")
        for record in records:
            print(f"   {record[title_column_index]['stringValue']}")

    def wait_statement_finished(self, sql_id):
        while True:
            time.sleep(1)
            response = self.redshift_data_wrapper.describe_statement(sql_id)
            status = response["Status"]
            print(f"Statement status is {status}.")

            if status == "FAILED":
                print(f"The query failed because {response['Error']}. Ending program")
                raise Exception("The Query Failed. Ending program")
            elif status == "FINISHED":
                break
```
シナリオの実装を示すメイン関数。  

```
def main():
    redshift_client = boto3.client("redshift")
    redshift_data_client = boto3.client("redshift-data")
    redshift_wrapper = RedshiftWrapper(redshift_client)
    redshift_data_wrapper = RedshiftDataWrapper(redshift_data_client)
    redshift_scenario = RedshiftScenario(redshift_wrapper, redshift_data_wrapper)
    redshift_scenario.redhift_scenario(
        f"{os.path.dirname(__file__)}/../../../resources/sample_files/movies.json"
    )
```
シナリオで使用するラッパー関数。  

```
    def create_cluster(
        self,
        cluster_identifier,
        node_type,
        master_username,
        master_user_password,
        publicly_accessible,
        number_of_nodes,
    ):
        """
        Creates a cluster.

        :param cluster_identifier: The name of the cluster.
        :param node_type: The type of node in the cluster.
        :param master_username: The master username.
        :param master_user_password: The master user password.
        :param publicly_accessible: Whether the cluster is publicly accessible.
        :param number_of_nodes: The number of nodes in the cluster.
        :return: The cluster.
        """

        try:
            cluster = self.client.create_cluster(
                ClusterIdentifier=cluster_identifier,
                NodeType=node_type,
                MasterUsername=master_username,
                MasterUserPassword=master_user_password,
                PubliclyAccessible=publicly_accessible,
                NumberOfNodes=number_of_nodes,
            )
            return cluster
        except ClientError as err:
            logging.error(
                "Couldn't create a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def describe_clusters(self, cluster_identifier):
        """
        Describes a cluster.

        :param cluster_identifier: The cluster identifier.
        :return: A list of clusters.
        """
        try:
            kwargs = {}
            if cluster_identifier:
                kwargs["ClusterIdentifier"] = cluster_identifier

            paginator = self.client.get_paginator("describe_clusters")
            clusters = []
            for page in paginator.paginate(**kwargs):
                clusters.extend(page["Clusters"])

            return clusters

        except ClientError as err:
            logging.error(
                "Couldn't describe a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def execute_statement(
        self, cluster_identifier, database_name, user_name, sql, parameter_list=None
    ):
        """
        Executes a SQL statement.

        :param cluster_identifier: The cluster identifier.
        :param database_name: The database name.
        :param user_name: The user's name.
        :param sql: The SQL statement.
        :param parameter_list: The optional SQL statement parameters.
        :return: The SQL statement result.
        """

        try:
            kwargs = {
                "ClusterIdentifier": cluster_identifier,
                "Database": database_name,
                "DbUser": user_name,
                "Sql": sql,
            }
            if parameter_list:
                kwargs["Parameters"] = parameter_list
            response = self.client.execute_statement(**kwargs)
            return response
        except ClientError as err:
            logging.error(
                "Couldn't execute statement. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def describe_statement(self, statement_id):
        """
        Describes a SQL statement.

        :param statement_id: The SQL statement identifier.
        :return: The SQL statement result.
        """
        try:
            response = self.client.describe_statement(Id=statement_id)
            return response
        except ClientError as err:
            logging.error(
                "Couldn't describe statement. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def get_statement_result(self, statement_id):
        """
        Gets the result of a SQL statement.

        :param statement_id: The SQL statement identifier.
        :return: The SQL statement result.
        """
        try:
            result = {
                "Records": [],
            }
            paginator = self.client.get_paginator("get_statement_result")
            for page in paginator.paginate(Id=statement_id):
                if "ColumnMetadata" not in result:
                    result["ColumnMetadata"] = page["ColumnMetadata"]
                result["Records"].extend(page["Records"])
            return result
        except ClientError as err:
            logging.error(
                "Couldn't get statement result. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def modify_cluster(self, cluster_identifier, preferred_maintenance_window):
        """
        Modifies a cluster.

        :param cluster_identifier: The cluster identifier.
        :param preferred_maintenance_window: The preferred maintenance window.
        """
        try:
            self.client.modify_cluster(
                ClusterIdentifier=cluster_identifier,
                PreferredMaintenanceWindow=preferred_maintenance_window,
            )
        except ClientError as err:
            logging.error(
                "Couldn't modify a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def list_databases(self, cluster_identifier, database_name, database_user):
        """
        Lists databases in a cluster.

        :param cluster_identifier: The cluster identifier.
        :param database_name: The database name.
        :param database_user: The database user.
        :return: The list of databases.
        """
        try:
            paginator = self.client.get_paginator("list_databases")
            databases = []
            for page in paginator.paginate(
                ClusterIdentifier=cluster_identifier,
                Database=database_name,
                DbUser=database_user,
            ):
                databases.extend(page["Databases"])

            return databases
        except ClientError as err:
            logging.error(
                "Couldn't list databases. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete_cluster(self, cluster_identifier):
        """
        Deletes a cluster.

        :param cluster_identifier: The cluster identifier.
        """
        try:
            self.client.delete_cluster(
                ClusterIdentifier=cluster_identifier, SkipFinalClusterSnapshot=True
            )
        except ClientError as err:
            logging.error(
                "Couldn't delete a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateCluster](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/CreateCluster)
  + [DescribeClusters](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/DescribeClusters)
  + [DescribeStatement](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/DescribeStatement)
  + [ExecuteStatement](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/ExecuteStatement)
  + [GetStatementResult](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/GetStatementResult)
  + [ListDatabasesPaginator](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/ListDatabasesPaginator)
  + [ModifyCluster](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/ModifyCluster)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="redshift_CreateCluster_python_3_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
class RedshiftWrapper:
    """
    Encapsulates Amazon Redshift cluster operations.
    """

    def __init__(self, redshift_client):
        """
        :param redshift_client: A Boto3 Redshift client.
        """
        self.client = redshift_client


    def create_cluster(
        self,
        cluster_identifier,
        node_type,
        master_username,
        master_user_password,
        publicly_accessible,
        number_of_nodes,
    ):
        """
        Creates a cluster.

        :param cluster_identifier: The name of the cluster.
        :param node_type: The type of node in the cluster.
        :param master_username: The master username.
        :param master_user_password: The master user password.
        :param publicly_accessible: Whether the cluster is publicly accessible.
        :param number_of_nodes: The number of nodes in the cluster.
        :return: The cluster.
        """

        try:
            cluster = self.client.create_cluster(
                ClusterIdentifier=cluster_identifier,
                NodeType=node_type,
                MasterUsername=master_username,
                MasterUserPassword=master_user_password,
                PubliclyAccessible=publicly_accessible,
                NumberOfNodes=number_of_nodes,
            )
            return cluster
        except ClientError as err:
            logging.error(
                "Couldn't create a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは RedShiftWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("redshift")
    redhift_wrapper = RedshiftWrapper(client)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[CreateCluster](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/CreateCluster)」を参照してください。**

### `DeleteCluster`
<a name="redshift_DeleteCluster_python_3_topic"></a>

次のコード例は、`DeleteCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
class RedshiftWrapper:
    """
    Encapsulates Amazon Redshift cluster operations.
    """

    def __init__(self, redshift_client):
        """
        :param redshift_client: A Boto3 Redshift client.
        """
        self.client = redshift_client


    def delete_cluster(self, cluster_identifier):
        """
        Deletes a cluster.

        :param cluster_identifier: The cluster identifier.
        """
        try:
            self.client.delete_cluster(
                ClusterIdentifier=cluster_identifier, SkipFinalClusterSnapshot=True
            )
        except ClientError as err:
            logging.error(
                "Couldn't delete a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは RedShiftWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("redshift")
    redhift_wrapper = RedshiftWrapper(client)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DeleteCluster](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/DeleteCluster)」を参照してください。**

### `DescribeClusters`
<a name="redshift_DescribeClusters_python_3_topic"></a>

次のコード例は、`DescribeClusters` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
class RedshiftWrapper:
    """
    Encapsulates Amazon Redshift cluster operations.
    """

    def __init__(self, redshift_client):
        """
        :param redshift_client: A Boto3 Redshift client.
        """
        self.client = redshift_client


    def describe_clusters(self, cluster_identifier):
        """
        Describes a cluster.

        :param cluster_identifier: The cluster identifier.
        :return: A list of clusters.
        """
        try:
            kwargs = {}
            if cluster_identifier:
                kwargs["ClusterIdentifier"] = cluster_identifier

            paginator = self.client.get_paginator("describe_clusters")
            clusters = []
            for page in paginator.paginate(**kwargs):
                clusters.extend(page["Clusters"])

            return clusters

        except ClientError as err:
            logging.error(
                "Couldn't describe a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは RedShiftWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("redshift")
    redhift_wrapper = RedshiftWrapper(client)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DescribeClusters](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/DescribeClusters)」を参照してください。**

### `DescribeStatement`
<a name="redshift_DescribeStatement_python_3_topic"></a>

次のコード例は、`DescribeStatement` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
class RedshiftDataWrapper:
    """Encapsulates Amazon Redshift data."""

    def __init__(self, client):
        """
        :param client: A Boto3 RedshiftDataWrapper client.
        """
        self.client = client


    def describe_statement(self, statement_id):
        """
        Describes a SQL statement.

        :param statement_id: The SQL statement identifier.
        :return: The SQL statement result.
        """
        try:
            response = self.client.describe_statement(Id=statement_id)
            return response
        except ClientError as err:
            logging.error(
                "Couldn't describe statement. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは RedShiftDataWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("redshift-data")
    redshift_data_wrapper = RedshiftDataWrapper(client)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DescribeStatement](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/DescribeStatement)」を参照してください。**

### `GetStatementResult`
<a name="redshift_GetStatementResult_python_3_topic"></a>

次のコード例は、`GetStatementResult` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
class RedshiftDataWrapper:
    """Encapsulates Amazon Redshift data."""

    def __init__(self, client):
        """
        :param client: A Boto3 RedshiftDataWrapper client.
        """
        self.client = client


    def get_statement_result(self, statement_id):
        """
        Gets the result of a SQL statement.

        :param statement_id: The SQL statement identifier.
        :return: The SQL statement result.
        """
        try:
            result = {
                "Records": [],
            }
            paginator = self.client.get_paginator("get_statement_result")
            for page in paginator.paginate(Id=statement_id):
                if "ColumnMetadata" not in result:
                    result["ColumnMetadata"] = page["ColumnMetadata"]
                result["Records"].extend(page["Records"])
            return result
        except ClientError as err:
            logging.error(
                "Couldn't get statement result. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは RedShiftDataWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("redshift-data")
    redshift_data_wrapper = RedshiftDataWrapper(client)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetStatementResult](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/GetStatementResult)」を参照してください。**

### `ModifyCluster`
<a name="redshift_ModifyCluster_python_3_topic"></a>

次のコード例は、`ModifyCluster` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/redshift#code-examples)での設定と実行の方法を確認してください。

```
class RedshiftWrapper:
    """
    Encapsulates Amazon Redshift cluster operations.
    """

    def __init__(self, redshift_client):
        """
        :param redshift_client: A Boto3 Redshift client.
        """
        self.client = redshift_client


    def modify_cluster(self, cluster_identifier, preferred_maintenance_window):
        """
        Modifies a cluster.

        :param cluster_identifier: The cluster identifier.
        :param preferred_maintenance_window: The preferred maintenance window.
        """
        try:
            self.client.modify_cluster(
                ClusterIdentifier=cluster_identifier,
                PreferredMaintenanceWindow=preferred_maintenance_window,
            )
        except ClientError as err:
            logging.error(
                "Couldn't modify a cluster. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
次のコードは RedShiftWrapper オブジェクトをインスタンス化します。  

```
    client = boto3.client("redshift")
    redhift_wrapper = RedshiftWrapper(client)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[ModifyCluster](https://docs.aws.amazon.com/goto/boto3/redshift-2012-12-01/ModifyCluster)」を参照してください。**

# SDK for Python (Boto3) を使用する Amazon Rekognition の例
<a name="python_3_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CompareFaces`
<a name="rekognition_CompareFaces_python_3_topic"></a>

次のコード例は、`CompareFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を比較する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    def compare_faces(self, target_image, similarity):
        """
        Compares faces in the image with the largest face in the target image.

        :param target_image: The target image to compare against.
        :param similarity: Faces in the image must have a similarity value greater
                           than this value to be included in the results.
        :return: A tuple. The first element is the list of faces that match the
                 reference image. The second element is the list of faces that have
                 a similarity value below the specified threshold.
        """
        try:
            response = self.rekognition_client.compare_faces(
                SourceImage=self.image,
                TargetImage=target_image.image,
                SimilarityThreshold=similarity,
            )
            matches = [
                RekognitionFace(match["Face"]) for match in response["FaceMatches"]
            ]
            unmatches = [RekognitionFace(face) for face in response["UnmatchedFaces"]]
            logger.info(
                "Found %s matched faces and %s unmatched faces.",
                len(matches),
                len(unmatches),
            )
        except ClientError:
            logger.exception(
                "Couldn't match faces from %s to %s.",
                self.image_name,
                target_image.image_name,
            )
            raise
        else:
            return matches, unmatches
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/CompareFaces)の「*CompareFaces*」を参照してください。

### `CreateCollection`
<a name="rekognition_CreateCollection_python_3_topic"></a>

次のコード例は、`CreateCollection` を使用する方法を示しています。

詳細については、「[コレクションを作成する](https://docs.aws.amazon.com/rekognition/latest/dg/create-collection-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollectionManager:
    """
    Encapsulates Amazon Rekognition collection management functions.
    This class is a thin wrapper around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, rekognition_client):
        """
        Initializes the collection manager object.

        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.rekognition_client = rekognition_client


    def create_collection(self, collection_id):
        """
        Creates an empty collection.

        :param collection_id: Text that identifies the collection.
        :return: The newly created collection.
        """
        try:
            response = self.rekognition_client.create_collection(
                CollectionId=collection_id
            )
            response["CollectionId"] = collection_id
            collection = RekognitionCollection(response, self.rekognition_client)
            logger.info("Created collection %s.", collection_id)
        except ClientError:
            logger.exception("Couldn't create collection %s.", collection_id)
            raise
        else:
            return collection
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/CreateCollection) の「*CreateCollection*」を参照してください。

### `DeleteCollection`
<a name="rekognition_DeleteCollection_python_3_topic"></a>

次のコード例は、`DeleteCollection` を使用する方法を示しています。

詳細については、「[コレクションを削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-collection-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def delete_collection(self):
        """
        Deletes the collection.
        """
        try:
            self.rekognition_client.delete_collection(CollectionId=self.collection_id)
            logger.info("Deleted collection %s.", self.collection_id)
            self.collection_id = None
        except ClientError:
            logger.exception("Couldn't delete collection %s.", self.collection_id)
            raise
```
+  API の詳細については、 [AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DeleteCollection) で「*DeleteCollection*」を参照してください。

### `DeleteFaces`
<a name="rekognition_DeleteFaces_python_3_topic"></a>

次のコード例は、`DeleteFaces` を使用する方法を示しています。

詳細については、「[コレクションから顔を削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-faces-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def delete_faces(self, face_ids):
        """
        Deletes faces from the collection.

        :param face_ids: The list of IDs of faces to delete.
        :return: The list of IDs of faces that were deleted.
        """
        try:
            response = self.rekognition_client.delete_faces(
                CollectionId=self.collection_id, FaceIds=face_ids
            )
            deleted_ids = response["DeletedFaces"]
            logger.info(
                "Deleted %s faces from %s.", len(deleted_ids), self.collection_id
            )
        except ClientError:
            logger.exception("Couldn't delete faces from %s.", self.collection_id)
            raise
        else:
            return deleted_ids
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DeleteFaces) で「*DeleteFaces*」を参照してください。

### `DescribeCollection`
<a name="rekognition_DescribeCollection_python_3_topic"></a>

次のコード例は、`DescribeCollection` を使用する方法を示しています。

詳細については、「[コレクションを定義する](https://docs.aws.amazon.com/rekognition/latest/dg/describe-collection-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def describe_collection(self):
        """
        Gets data about the collection from the Amazon Rekognition service.

        :return: The collection rendered as a dict.
        """
        try:
            response = self.rekognition_client.describe_collection(
                CollectionId=self.collection_id
            )
            # Work around capitalization of Arn vs. ARN
            response["CollectionArn"] = response.get("CollectionARN")
            (
                self.collection_arn,
                self.face_count,
                self.created,
            ) = self._unpack_collection(response)
            logger.info("Got data for collection %s.", self.collection_id)
        except ClientError:
            logger.exception("Couldn't get data for collection %s.", self.collection_id)
            raise
        else:
            return self.to_dict()
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DescribeCollection)の「*DescribeCollection*」を参照してください。

### `DetectFaces`
<a name="rekognition_DetectFaces_python_3_topic"></a>

次のコード例は、`DetectFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を検出する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    def detect_faces(self):
        """
        Detects faces in the image.

        :return: The list of faces found in the image.
        """
        try:
            response = self.rekognition_client.detect_faces(
                Image=self.image, Attributes=["ALL"]
            )
            faces = [RekognitionFace(face) for face in response["FaceDetails"]]
            logger.info("Detected %s faces.", len(faces))
        except ClientError:
            logger.exception("Couldn't detect faces in %s.", self.image_name)
            raise
        else:
            return faces
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DetectFaces) の「*DetectFaces*」を参照してください。

### `DetectLabels`
<a name="rekognition_DetectLabels_python_3_topic"></a>

次のコード例は、`DetectLabels` を使用する方法を示しています。

詳細については、「[イメージ内のラベルを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    def detect_labels(self, max_labels):
        """
        Detects labels in the image. Labels are objects and people.

        :param max_labels: The maximum number of labels to return.
        :return: The list of labels detected in the image.
        """
        try:
            response = self.rekognition_client.detect_labels(
                Image=self.image, MaxLabels=max_labels
            )
            labels = [RekognitionLabel(label) for label in response["Labels"]]
            logger.info("Found %s labels in %s.", len(labels), self.image_name)
        except ClientError:
            logger.info("Couldn't detect labels in %s.", self.image_name)
            raise
        else:
            return labels
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DetectLabels) の「*DetectLabels*」を参照してください。

### `DetectModerationLabels`
<a name="rekognition_DetectModerationLabels_python_3_topic"></a>

次のコード例は、`DetectModerationLabels` を使用する方法を示しています。

詳細については、「[不適切なイメージを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-images.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    def detect_moderation_labels(self):
        """
        Detects moderation labels in the image. Moderation labels identify content
        that may be inappropriate for some audiences.

        :return: The list of moderation labels found in the image.
        """
        try:
            response = self.rekognition_client.detect_moderation_labels(
                Image=self.image
            )
            labels = [
                RekognitionModerationLabel(label)
                for label in response["ModerationLabels"]
            ]
            logger.info(
                "Found %s moderation labels in %s.", len(labels), self.image_name
            )
        except ClientError:
            logger.exception(
                "Couldn't detect moderation labels in %s.", self.image_name
            )
            raise
        else:
            return labels
```
+  API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の「[DetectModerationLabels](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DetectModerationLabels)」を参照してください。

### `DetectText`
<a name="rekognition_DetectText_python_3_topic"></a>

次のコード例は、`DetectText` を使用する方法を示しています。

詳細については、「[イメージ内のテキストを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/text-detecting-text-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    def detect_text(self):
        """
        Detects text in the image.

        :return The list of text elements found in the image.
        """
        try:
            response = self.rekognition_client.detect_text(Image=self.image)
            texts = [RekognitionText(text) for text in response["TextDetections"]]
            logger.info("Found %s texts in %s.", len(texts), self.image_name)
        except ClientError:
            logger.exception("Couldn't detect text in %s.", self.image_name)
            raise
        else:
            return texts
```
+  API の詳細については、[https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DetectText](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/DetectText) SDK for Python (Boto3) API リファレンス* の「AWS DetectText*」を参照してください。

### `IndexFaces`
<a name="rekognition_IndexFaces_python_3_topic"></a>

次の例は、`IndexFaces` を使用する方法を説明しています。

詳細については、「[コレクションに顔を追加する](https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def index_faces(self, image, max_faces):
        """
        Finds faces in the specified image, indexes them, and stores them in the
        collection.

        :param image: The image to index.
        :param max_faces: The maximum number of faces to index.
        :return: A tuple. The first element is a list of indexed faces.
                 The second element is a list of faces that couldn't be indexed.
        """
        try:
            response = self.rekognition_client.index_faces(
                CollectionId=self.collection_id,
                Image=image.image,
                ExternalImageId=image.image_name,
                MaxFaces=max_faces,
                DetectionAttributes=["ALL"],
            )
            indexed_faces = [
                RekognitionFace({**face["Face"], **face["FaceDetail"]})
                for face in response["FaceRecords"]
            ]
            unindexed_faces = [
                RekognitionFace(face["FaceDetail"])
                for face in response["UnindexedFaces"]
            ]
            logger.info(
                "Indexed %s faces in %s. Could not index %s faces.",
                len(indexed_faces),
                image.image_name,
                len(unindexed_faces),
            )
        except ClientError:
            logger.exception("Couldn't index faces in image %s.", image.image_name)
            raise
        else:
            return indexed_faces, unindexed_faces
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/IndexFaces)の「*IndexFaces*」を参照してください。

### `ListCollections`
<a name="rekognition_ListCollections_python_3_topic"></a>

次のコード例は、`ListCollections` を使用する方法を示しています。

コレクションの詳細については、「[コレクションを一覧表示する](https://docs.aws.amazon.com/rekognition/latest/dg/list-collection-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollectionManager:
    """
    Encapsulates Amazon Rekognition collection management functions.
    This class is a thin wrapper around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, rekognition_client):
        """
        Initializes the collection manager object.

        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.rekognition_client = rekognition_client


    def list_collections(self, max_results):
        """
        Lists collections for the current account.

        :param max_results: The maximum number of collections to return.
        :return: The list of collections for the current account.
        """
        try:
            response = self.rekognition_client.list_collections(MaxResults=max_results)
            collections = [
                RekognitionCollection({"CollectionId": col_id}, self.rekognition_client)
                for col_id in response["CollectionIds"]
            ]
        except ClientError:
            logger.exception("Couldn't list collections.")
            raise
        else:
            return collections
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/ListCollections)の「*ListCollections*」を参照してください。

### `ListFaces`
<a name="rekognition_ListFaces_python_3_topic"></a>

次のコード例は、`ListFaces` を使用する方法を示しています。

詳細については、「[コレクションに顔を保存する](https://docs.aws.amazon.com/rekognition/latest/dg/list-faces-in-collection-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def list_faces(self, max_results):
        """
        Lists the faces currently indexed in the collection.

        :param max_results: The maximum number of faces to return.
        :return: The list of faces in the collection.
        """
        try:
            response = self.rekognition_client.list_faces(
                CollectionId=self.collection_id, MaxResults=max_results
            )
            faces = [RekognitionFace(face) for face in response["Faces"]]
            logger.info(
                "Found %s faces in collection %s.", len(faces), self.collection_id
            )
        except ClientError:
            logger.exception(
                "Couldn't list faces in collection %s.", self.collection_id
            )
            raise
        else:
            return faces
```
+  API の詳細については、[https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/ListFaces](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/ListFaces) SDK for Python (Boto3) API リファレンス* で「AWS ListFaces*」を参照してください。

### `RecognizeCelebrities`
<a name="rekognition_RecognizeCelebrities_python_3_topic"></a>

次のコード例は、`RecognizeCelebrities` を使用する方法を示しています。

詳細については、「[イメージ内で有名人を認識する](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-procedure-image.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    def recognize_celebrities(self):
        """
        Detects celebrities in the image.

        :return: A tuple. The first element is the list of celebrities found in
                 the image. The second element is the list of faces that were
                 detected but did not match any known celebrities.
        """
        try:
            response = self.rekognition_client.recognize_celebrities(Image=self.image)
            celebrities = [
                RekognitionCelebrity(celeb) for celeb in response["CelebrityFaces"]
            ]
            other_faces = [
                RekognitionFace(face) for face in response["UnrecognizedFaces"]
            ]
            logger.info(
                "Found %s celebrities and %s other faces in %s.",
                len(celebrities),
                len(other_faces),
                self.image_name,
            )
        except ClientError:
            logger.exception("Couldn't detect celebrities in %s.", self.image_name)
            raise
        else:
            return celebrities, other_faces
```
+  API の詳細については、「[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/RecognizeCelebrities)の *RecognizeCelebrities*」を参照してください。

### `SearchFaces`
<a name="rekognition_SearchFaces_python_3_topic"></a>

次のコード例は、`SearchFaces` を使用する方法を示しています。

詳細については、[顔 (フェイス ID) を検索する](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-id-procedure.html) を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def search_faces(self, face_id, threshold, max_faces):
        """
        Searches for faces in the collection that match another face from the
        collection.

        :param face_id: The ID of the face in the collection to search for.
        :param threshold: The match confidence must be greater than this value
                          for a face to be included in the results.
        :param max_faces: The maximum number of faces to return.
        :return: The list of matching faces found in the collection. This list does
                 not contain the face specified by `face_id`.
        """
        try:
            response = self.rekognition_client.search_faces(
                CollectionId=self.collection_id,
                FaceId=face_id,
                FaceMatchThreshold=threshold,
                MaxFaces=max_faces,
            )
            faces = [RekognitionFace(face["Face"]) for face in response["FaceMatches"]]
            logger.info(
                "Found %s faces in %s that match %s.",
                len(faces),
                self.collection_id,
                face_id,
            )
        except ClientError:
            logger.exception(
                "Couldn't search for faces in %s that match %s.",
                self.collection_id,
                face_id,
            )
            raise
        else:
            return faces
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/SearchFaces) の「*SearchFaces*」を参照してください。

### `SearchFacesByImage`
<a name="rekognition_SearchFacesByImage_python_3_topic"></a>

次のコード例は、`SearchFacesByImage` を使用する方法を示しています。

詳細については、「[顔を検索する (イメージ)](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-image-procedure.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。

```
class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def search_faces_by_image(self, image, threshold, max_faces):
        """
        Searches for faces in the collection that match the largest face in the
        reference image.

        :param image: The image that contains the reference face to search for.
        :param threshold: The match confidence must be greater than this value
                          for a face to be included in the results.
        :param max_faces: The maximum number of faces to return.
        :return: A tuple. The first element is the face found in the reference image.
                 The second element is the list of matching faces found in the
                 collection.
        """
        try:
            response = self.rekognition_client.search_faces_by_image(
                CollectionId=self.collection_id,
                Image=image.image,
                FaceMatchThreshold=threshold,
                MaxFaces=max_faces,
            )
            image_face = RekognitionFace(
                {
                    "BoundingBox": response["SearchedFaceBoundingBox"],
                    "Confidence": response["SearchedFaceConfidence"],
                }
            )
            collection_faces = [
                RekognitionFace(face["Face"]) for face in response["FaceMatches"]
            ]
            logger.info(
                "Found %s faces in the collection that match the largest "
                "face in %s.",
                len(collection_faces),
                image.image_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't search for faces in %s that match %s.",
                self.collection_id,
                image.image_name,
            )
            raise
        else:
            return image_face, collection_faces
```
+  API の詳細については、[AWS SDK for Python (Boto3) API リファレンス](https://docs.aws.amazon.com/goto/boto3/rekognition-2016-06-27/SearchFacesByImage) の「*SearchFacesByImage*」を参照してください。

## シナリオ
<a name="scenarios"></a>

### コレクションを構築し、その中に顔を検索します。
<a name="rekognition_Usage_FindFacesInCollection_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Rekognition コレクションを作成します。
+ このコレクションにイメージを追加し、その中から顔を検出します。
+ 参照イメージに一致する顔をコレクション内で検索します。
+ コレクションを削除します。

詳細については、[コレクション内の顔を検索するには](https://docs.aws.amazon.com/rekognition/latest/dg/collections.html) を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。
Amazon Rekognition 関数をラップするクラスを作成します。  

```
import logging
from pprint import pprint
import boto3
from botocore.exceptions import ClientError
from rekognition_objects import RekognitionFace
from rekognition_image_detection import RekognitionImage

logger = logging.getLogger(__name__)


class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    @classmethod
    def from_file(cls, image_file_name, rekognition_client, image_name=None):
        """
        Creates a RekognitionImage object from a local file.

        :param image_file_name: The file name of the image. The file is opened and its
                                bytes are read.
        :param rekognition_client: A Boto3 Rekognition client.
        :param image_name: The name of the image. If this is not specified, the
                           file name is used as the image name.
        :return: The RekognitionImage object, initialized with image bytes from the
                 file.
        """
        with open(image_file_name, "rb") as img_file:
            image = {"Bytes": img_file.read()}
        name = image_file_name if image_name is None else image_name
        return cls(image, name, rekognition_client)


class RekognitionCollectionManager:
    """
    Encapsulates Amazon Rekognition collection management functions.
    This class is a thin wrapper around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, rekognition_client):
        """
        Initializes the collection manager object.

        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.rekognition_client = rekognition_client


    def create_collection(self, collection_id):
        """
        Creates an empty collection.

        :param collection_id: Text that identifies the collection.
        :return: The newly created collection.
        """
        try:
            response = self.rekognition_client.create_collection(
                CollectionId=collection_id
            )
            response["CollectionId"] = collection_id
            collection = RekognitionCollection(response, self.rekognition_client)
            logger.info("Created collection %s.", collection_id)
        except ClientError:
            logger.exception("Couldn't create collection %s.", collection_id)
            raise
        else:
            return collection


    def list_collections(self, max_results):
        """
        Lists collections for the current account.

        :param max_results: The maximum number of collections to return.
        :return: The list of collections for the current account.
        """
        try:
            response = self.rekognition_client.list_collections(MaxResults=max_results)
            collections = [
                RekognitionCollection({"CollectionId": col_id}, self.rekognition_client)
                for col_id in response["CollectionIds"]
            ]
        except ClientError:
            logger.exception("Couldn't list collections.")
            raise
        else:
            return collections



class RekognitionCollection:
    """
    Encapsulates an Amazon Rekognition collection. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, collection, rekognition_client):
        """
        Initializes a collection object.

        :param collection: Collection data in the format returned by a call to
                           create_collection.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.collection_id = collection["CollectionId"]
        self.collection_arn, self.face_count, self.created = self._unpack_collection(
            collection
        )
        self.rekognition_client = rekognition_client

    @staticmethod
    def _unpack_collection(collection):
        """
        Unpacks optional parts of a collection that can be returned by
        describe_collection.

        :param collection: The collection data.
        :return: A tuple of the data in the collection.
        """
        return (
            collection.get("CollectionArn"),
            collection.get("FaceCount", 0),
            collection.get("CreationTimestamp"),
        )


    def to_dict(self):
        """
        Renders parts of the collection data to a dict.

        :return: The collection data as a dict.
        """
        rendering = {
            "collection_id": self.collection_id,
            "collection_arn": self.collection_arn,
            "face_count": self.face_count,
            "created": self.created,
        }
        return rendering


    def describe_collection(self):
        """
        Gets data about the collection from the Amazon Rekognition service.

        :return: The collection rendered as a dict.
        """
        try:
            response = self.rekognition_client.describe_collection(
                CollectionId=self.collection_id
            )
            # Work around capitalization of Arn vs. ARN
            response["CollectionArn"] = response.get("CollectionARN")
            (
                self.collection_arn,
                self.face_count,
                self.created,
            ) = self._unpack_collection(response)
            logger.info("Got data for collection %s.", self.collection_id)
        except ClientError:
            logger.exception("Couldn't get data for collection %s.", self.collection_id)
            raise
        else:
            return self.to_dict()


    def delete_collection(self):
        """
        Deletes the collection.
        """
        try:
            self.rekognition_client.delete_collection(CollectionId=self.collection_id)
            logger.info("Deleted collection %s.", self.collection_id)
            self.collection_id = None
        except ClientError:
            logger.exception("Couldn't delete collection %s.", self.collection_id)
            raise


    def index_faces(self, image, max_faces):
        """
        Finds faces in the specified image, indexes them, and stores them in the
        collection.

        :param image: The image to index.
        :param max_faces: The maximum number of faces to index.
        :return: A tuple. The first element is a list of indexed faces.
                 The second element is a list of faces that couldn't be indexed.
        """
        try:
            response = self.rekognition_client.index_faces(
                CollectionId=self.collection_id,
                Image=image.image,
                ExternalImageId=image.image_name,
                MaxFaces=max_faces,
                DetectionAttributes=["ALL"],
            )
            indexed_faces = [
                RekognitionFace({**face["Face"], **face["FaceDetail"]})
                for face in response["FaceRecords"]
            ]
            unindexed_faces = [
                RekognitionFace(face["FaceDetail"])
                for face in response["UnindexedFaces"]
            ]
            logger.info(
                "Indexed %s faces in %s. Could not index %s faces.",
                len(indexed_faces),
                image.image_name,
                len(unindexed_faces),
            )
        except ClientError:
            logger.exception("Couldn't index faces in image %s.", image.image_name)
            raise
        else:
            return indexed_faces, unindexed_faces


    def list_faces(self, max_results):
        """
        Lists the faces currently indexed in the collection.

        :param max_results: The maximum number of faces to return.
        :return: The list of faces in the collection.
        """
        try:
            response = self.rekognition_client.list_faces(
                CollectionId=self.collection_id, MaxResults=max_results
            )
            faces = [RekognitionFace(face) for face in response["Faces"]]
            logger.info(
                "Found %s faces in collection %s.", len(faces), self.collection_id
            )
        except ClientError:
            logger.exception(
                "Couldn't list faces in collection %s.", self.collection_id
            )
            raise
        else:
            return faces


    def search_faces(self, face_id, threshold, max_faces):
        """
        Searches for faces in the collection that match another face from the
        collection.

        :param face_id: The ID of the face in the collection to search for.
        :param threshold: The match confidence must be greater than this value
                          for a face to be included in the results.
        :param max_faces: The maximum number of faces to return.
        :return: The list of matching faces found in the collection. This list does
                 not contain the face specified by `face_id`.
        """
        try:
            response = self.rekognition_client.search_faces(
                CollectionId=self.collection_id,
                FaceId=face_id,
                FaceMatchThreshold=threshold,
                MaxFaces=max_faces,
            )
            faces = [RekognitionFace(face["Face"]) for face in response["FaceMatches"]]
            logger.info(
                "Found %s faces in %s that match %s.",
                len(faces),
                self.collection_id,
                face_id,
            )
        except ClientError:
            logger.exception(
                "Couldn't search for faces in %s that match %s.",
                self.collection_id,
                face_id,
            )
            raise
        else:
            return faces


    def search_faces_by_image(self, image, threshold, max_faces):
        """
        Searches for faces in the collection that match the largest face in the
        reference image.

        :param image: The image that contains the reference face to search for.
        :param threshold: The match confidence must be greater than this value
                          for a face to be included in the results.
        :param max_faces: The maximum number of faces to return.
        :return: A tuple. The first element is the face found in the reference image.
                 The second element is the list of matching faces found in the
                 collection.
        """
        try:
            response = self.rekognition_client.search_faces_by_image(
                CollectionId=self.collection_id,
                Image=image.image,
                FaceMatchThreshold=threshold,
                MaxFaces=max_faces,
            )
            image_face = RekognitionFace(
                {
                    "BoundingBox": response["SearchedFaceBoundingBox"],
                    "Confidence": response["SearchedFaceConfidence"],
                }
            )
            collection_faces = [
                RekognitionFace(face["Face"]) for face in response["FaceMatches"]
            ]
            logger.info(
                "Found %s faces in the collection that match the largest "
                "face in %s.",
                len(collection_faces),
                image.image_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't search for faces in %s that match %s.",
                self.collection_id,
                image.image_name,
            )
            raise
        else:
            return image_face, collection_faces


class RekognitionFace:
    """Encapsulates an Amazon Rekognition face."""

    def __init__(self, face, timestamp=None):
        """
        Initializes the face object.

        :param face: Face data, in the format returned by Amazon Rekognition
                     functions.
        :param timestamp: The time when the face was detected, if the face was
                          detected in a video.
        """
        self.bounding_box = face.get("BoundingBox")
        self.confidence = face.get("Confidence")
        self.landmarks = face.get("Landmarks")
        self.pose = face.get("Pose")
        self.quality = face.get("Quality")
        age_range = face.get("AgeRange")
        if age_range is not None:
            self.age_range = (age_range.get("Low"), age_range.get("High"))
        else:
            self.age_range = None
        self.smile = face.get("Smile", {}).get("Value")
        self.eyeglasses = face.get("Eyeglasses", {}).get("Value")
        self.sunglasses = face.get("Sunglasses", {}).get("Value")
        self.gender = face.get("Gender", {}).get("Value", None)
        self.beard = face.get("Beard", {}).get("Value")
        self.mustache = face.get("Mustache", {}).get("Value")
        self.eyes_open = face.get("EyesOpen", {}).get("Value")
        self.mouth_open = face.get("MouthOpen", {}).get("Value")
        self.emotions = [
            emo.get("Type")
            for emo in face.get("Emotions", [])
            if emo.get("Confidence", 0) > 50
        ]
        self.face_id = face.get("FaceId")
        self.image_id = face.get("ImageId")
        self.timestamp = timestamp

    def to_dict(self):
        """
        Renders some of the face data to a dict.

        :return: A dict that contains the face data.
        """
        rendering = {}
        if self.bounding_box is not None:
            rendering["bounding_box"] = self.bounding_box
        if self.age_range is not None:
            rendering["age"] = f"{self.age_range[0]} - {self.age_range[1]}"
        if self.gender is not None:
            rendering["gender"] = self.gender
        if self.emotions:
            rendering["emotions"] = self.emotions
        if self.face_id is not None:
            rendering["face_id"] = self.face_id
        if self.image_id is not None:
            rendering["image_id"] = self.image_id
        if self.timestamp is not None:
            rendering["timestamp"] = self.timestamp
        has = []
        if self.smile:
            has.append("smile")
        if self.eyeglasses:
            has.append("eyeglasses")
        if self.sunglasses:
            has.append("sunglasses")
        if self.beard:
            has.append("beard")
        if self.mustache:
            has.append("mustache")
        if self.eyes_open:
            has.append("open eyes")
        if self.mouth_open:
            has.append("open mouth")
        if has:
            rendering["has"] = has
        return rendering
```
ラッパークラスを使用して、一連のイメージから顔のコレクションを作成し、コレクション内の顔を検索します。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the Amazon Rekognition face collection demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    rekognition_client = boto3.client("rekognition")
    images = [
        RekognitionImage.from_file(
            ".media/pexels-agung-pandit-wiguna-1128316.jpg",
            rekognition_client,
            image_name="sitting",
        ),
        RekognitionImage.from_file(
            ".media/pexels-agung-pandit-wiguna-1128317.jpg",
            rekognition_client,
            image_name="hopping",
        ),
        RekognitionImage.from_file(
            ".media/pexels-agung-pandit-wiguna-1128318.jpg",
            rekognition_client,
            image_name="biking",
        ),
    ]

    collection_mgr = RekognitionCollectionManager(rekognition_client)
    collection = collection_mgr.create_collection("doc-example-collection-demo")
    print(f"Created collection {collection.collection_id}:")
    pprint(collection.describe_collection())

    print("Indexing faces from three images:")
    for image in images:
        collection.index_faces(image, 10)
    print("Listing faces in collection:")
    faces = collection.list_faces(10)
    for face in faces:
        pprint(face.to_dict())
    input("Press Enter to continue.")

    print(
        f"Searching for faces in the collection that match the first face in the "
        f"list (Face ID: {faces[0].face_id}."
    )
    found_faces = collection.search_faces(faces[0].face_id, 80, 10)
    print(f"Found {len(found_faces)} matching faces.")
    for face in found_faces:
        pprint(face.to_dict())
    input("Press Enter to continue.")

    print(
        f"Searching for faces in the collection that match the largest face in "
        f"{images[0].image_name}."
    )
    image_face, match_faces = collection.search_faces_by_image(images[0], 80, 10)
    print(f"The largest face in {images[0].image_name} is:")
    pprint(image_face.to_dict())
    print(f"Found {len(match_faces)} matching faces.")
    for face in match_faces:
        pprint(face.to_dict())
    input("Press Enter to continue.")

    collection.delete_collection()
    print("Thanks for watching!")
    print("-" * 88)
```

### イメージ内の要素の検出と表示
<a name="rekognition_Usage_DetectAndDisplayImage_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Rekognition を使用してイメージから要素を検出します。
+ イメージを表示し、検出された要素の周囲に境界ボックスを描画します。

詳細については、[境界ボックスの表示](https://docs.aws.amazon.com/rekognition/latest/dg/images-displaying-bounding-boxes.html) を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition#code-examples)での設定と実行の方法を確認してください。
Amazon Rekognition 関数をラップするクラスを作成します。  

```
import logging
from pprint import pprint
import boto3
from botocore.exceptions import ClientError
import requests

from rekognition_objects import (
    RekognitionFace,
    RekognitionCelebrity,
    RekognitionLabel,
    RekognitionModerationLabel,
    RekognitionText,
    show_bounding_boxes,
    show_polygons,
)

logger = logging.getLogger(__name__)


class RekognitionImage:
    """
    Encapsulates an Amazon Rekognition image. This class is a thin wrapper
    around parts of the Boto3 Amazon Rekognition API.
    """

    def __init__(self, image, image_name, rekognition_client):
        """
        Initializes the image object.

        :param image: Data that defines the image, either the image bytes or
                      an Amazon S3 bucket and object key.
        :param image_name: The name of the image.
        :param rekognition_client: A Boto3 Rekognition client.
        """
        self.image = image
        self.image_name = image_name
        self.rekognition_client = rekognition_client


    @classmethod
    def from_file(cls, image_file_name, rekognition_client, image_name=None):
        """
        Creates a RekognitionImage object from a local file.

        :param image_file_name: The file name of the image. The file is opened and its
                                bytes are read.
        :param rekognition_client: A Boto3 Rekognition client.
        :param image_name: The name of the image. If this is not specified, the
                           file name is used as the image name.
        :return: The RekognitionImage object, initialized with image bytes from the
                 file.
        """
        with open(image_file_name, "rb") as img_file:
            image = {"Bytes": img_file.read()}
        name = image_file_name if image_name is None else image_name
        return cls(image, name, rekognition_client)


    @classmethod
    def from_bucket(cls, s3_object, rekognition_client):
        """
        Creates a RekognitionImage object from an Amazon S3 object.

        :param s3_object: An Amazon S3 object that identifies the image. The image
                          is not retrieved until needed for a later call.
        :param rekognition_client: A Boto3 Rekognition client.
        :return: The RekognitionImage object, initialized with Amazon S3 object data.
        """
        image = {"S3Object": {"Bucket": s3_object.bucket_name, "Name": s3_object.key}}
        return cls(image, s3_object.key, rekognition_client)


    def detect_faces(self):
        """
        Detects faces in the image.

        :return: The list of faces found in the image.
        """
        try:
            response = self.rekognition_client.detect_faces(
                Image=self.image, Attributes=["ALL"]
            )
            faces = [RekognitionFace(face) for face in response["FaceDetails"]]
            logger.info("Detected %s faces.", len(faces))
        except ClientError:
            logger.exception("Couldn't detect faces in %s.", self.image_name)
            raise
        else:
            return faces


    def detect_labels(self, max_labels):
        """
        Detects labels in the image. Labels are objects and people.

        :param max_labels: The maximum number of labels to return.
        :return: The list of labels detected in the image.
        """
        try:
            response = self.rekognition_client.detect_labels(
                Image=self.image, MaxLabels=max_labels
            )
            labels = [RekognitionLabel(label) for label in response["Labels"]]
            logger.info("Found %s labels in %s.", len(labels), self.image_name)
        except ClientError:
            logger.info("Couldn't detect labels in %s.", self.image_name)
            raise
        else:
            return labels


    def recognize_celebrities(self):
        """
        Detects celebrities in the image.

        :return: A tuple. The first element is the list of celebrities found in
                 the image. The second element is the list of faces that were
                 detected but did not match any known celebrities.
        """
        try:
            response = self.rekognition_client.recognize_celebrities(Image=self.image)
            celebrities = [
                RekognitionCelebrity(celeb) for celeb in response["CelebrityFaces"]
            ]
            other_faces = [
                RekognitionFace(face) for face in response["UnrecognizedFaces"]
            ]
            logger.info(
                "Found %s celebrities and %s other faces in %s.",
                len(celebrities),
                len(other_faces),
                self.image_name,
            )
        except ClientError:
            logger.exception("Couldn't detect celebrities in %s.", self.image_name)
            raise
        else:
            return celebrities, other_faces



    def compare_faces(self, target_image, similarity):
        """
        Compares faces in the image with the largest face in the target image.

        :param target_image: The target image to compare against.
        :param similarity: Faces in the image must have a similarity value greater
                           than this value to be included in the results.
        :return: A tuple. The first element is the list of faces that match the
                 reference image. The second element is the list of faces that have
                 a similarity value below the specified threshold.
        """
        try:
            response = self.rekognition_client.compare_faces(
                SourceImage=self.image,
                TargetImage=target_image.image,
                SimilarityThreshold=similarity,
            )
            matches = [
                RekognitionFace(match["Face"]) for match in response["FaceMatches"]
            ]
            unmatches = [RekognitionFace(face) for face in response["UnmatchedFaces"]]
            logger.info(
                "Found %s matched faces and %s unmatched faces.",
                len(matches),
                len(unmatches),
            )
        except ClientError:
            logger.exception(
                "Couldn't match faces from %s to %s.",
                self.image_name,
                target_image.image_name,
            )
            raise
        else:
            return matches, unmatches


    def detect_moderation_labels(self):
        """
        Detects moderation labels in the image. Moderation labels identify content
        that may be inappropriate for some audiences.

        :return: The list of moderation labels found in the image.
        """
        try:
            response = self.rekognition_client.detect_moderation_labels(
                Image=self.image
            )
            labels = [
                RekognitionModerationLabel(label)
                for label in response["ModerationLabels"]
            ]
            logger.info(
                "Found %s moderation labels in %s.", len(labels), self.image_name
            )
        except ClientError:
            logger.exception(
                "Couldn't detect moderation labels in %s.", self.image_name
            )
            raise
        else:
            return labels


    def detect_text(self):
        """
        Detects text in the image.

        :return The list of text elements found in the image.
        """
        try:
            response = self.rekognition_client.detect_text(Image=self.image)
            texts = [RekognitionText(text) for text in response["TextDetections"]]
            logger.info("Found %s texts in %s.", len(texts), self.image_name)
        except ClientError:
            logger.exception("Couldn't detect text in %s.", self.image_name)
            raise
        else:
            return texts
```
境界ボックスとポリゴンを描画するヘルパー関数を作成します。  

```
import io
import logging
from PIL import Image, ImageDraw

logger = logging.getLogger(__name__)


def show_bounding_boxes(image_bytes, box_sets, colors):
    """
    Draws bounding boxes on an image and shows it with the default image viewer.

    :param image_bytes: The image to draw, as bytes.
    :param box_sets: A list of lists of bounding boxes to draw on the image.
    :param colors: A list of colors to use to draw the bounding boxes.
    """
    image = Image.open(io.BytesIO(image_bytes))
    draw = ImageDraw.Draw(image)
    for boxes, color in zip(box_sets, colors):
        for box in boxes:
            left = image.width * box["Left"]
            top = image.height * box["Top"]
            right = (image.width * box["Width"]) + left
            bottom = (image.height * box["Height"]) + top
            draw.rectangle([left, top, right, bottom], outline=color, width=3)
    image.show()



def show_polygons(image_bytes, polygons, color):
    """
    Draws polygons on an image and shows it with the default image viewer.

    :param image_bytes: The image to draw, as bytes.
    :param polygons: The list of polygons to draw on the image.
    :param color: The color to use to draw the polygons.
    """
    image = Image.open(io.BytesIO(image_bytes))
    draw = ImageDraw.Draw(image)
    for polygon in polygons:
        draw.polygon(
            [
                (image.width * point["X"], image.height * point["Y"])
                for point in polygon
            ],
            outline=color,
        )
    image.show()
```
Amazon Rekognition から返されたオブジェクトを解析するクラスを作成します。  

```
class RekognitionFace:
    """Encapsulates an Amazon Rekognition face."""

    def __init__(self, face, timestamp=None):
        """
        Initializes the face object.

        :param face: Face data, in the format returned by Amazon Rekognition
                     functions.
        :param timestamp: The time when the face was detected, if the face was
                          detected in a video.
        """
        self.bounding_box = face.get("BoundingBox")
        self.confidence = face.get("Confidence")
        self.landmarks = face.get("Landmarks")
        self.pose = face.get("Pose")
        self.quality = face.get("Quality")
        age_range = face.get("AgeRange")
        if age_range is not None:
            self.age_range = (age_range.get("Low"), age_range.get("High"))
        else:
            self.age_range = None
        self.smile = face.get("Smile", {}).get("Value")
        self.eyeglasses = face.get("Eyeglasses", {}).get("Value")
        self.sunglasses = face.get("Sunglasses", {}).get("Value")
        self.gender = face.get("Gender", {}).get("Value", None)
        self.beard = face.get("Beard", {}).get("Value")
        self.mustache = face.get("Mustache", {}).get("Value")
        self.eyes_open = face.get("EyesOpen", {}).get("Value")
        self.mouth_open = face.get("MouthOpen", {}).get("Value")
        self.emotions = [
            emo.get("Type")
            for emo in face.get("Emotions", [])
            if emo.get("Confidence", 0) > 50
        ]
        self.face_id = face.get("FaceId")
        self.image_id = face.get("ImageId")
        self.timestamp = timestamp

    def to_dict(self):
        """
        Renders some of the face data to a dict.

        :return: A dict that contains the face data.
        """
        rendering = {}
        if self.bounding_box is not None:
            rendering["bounding_box"] = self.bounding_box
        if self.age_range is not None:
            rendering["age"] = f"{self.age_range[0]} - {self.age_range[1]}"
        if self.gender is not None:
            rendering["gender"] = self.gender
        if self.emotions:
            rendering["emotions"] = self.emotions
        if self.face_id is not None:
            rendering["face_id"] = self.face_id
        if self.image_id is not None:
            rendering["image_id"] = self.image_id
        if self.timestamp is not None:
            rendering["timestamp"] = self.timestamp
        has = []
        if self.smile:
            has.append("smile")
        if self.eyeglasses:
            has.append("eyeglasses")
        if self.sunglasses:
            has.append("sunglasses")
        if self.beard:
            has.append("beard")
        if self.mustache:
            has.append("mustache")
        if self.eyes_open:
            has.append("open eyes")
        if self.mouth_open:
            has.append("open mouth")
        if has:
            rendering["has"] = has
        return rendering



class RekognitionCelebrity:
    """Encapsulates an Amazon Rekognition celebrity."""

    def __init__(self, celebrity, timestamp=None):
        """
        Initializes the celebrity object.

        :param celebrity: Celebrity data, in the format returned by Amazon Rekognition
                          functions.
        :param timestamp: The time when the celebrity was detected, if the celebrity
                          was detected in a video.
        """
        self.info_urls = celebrity.get("Urls")
        self.name = celebrity.get("Name")
        self.id = celebrity.get("Id")
        self.face = RekognitionFace(celebrity.get("Face"))
        self.confidence = celebrity.get("MatchConfidence")
        self.bounding_box = celebrity.get("BoundingBox")
        self.timestamp = timestamp

    def to_dict(self):
        """
        Renders some of the celebrity data to a dict.

        :return: A dict that contains the celebrity data.
        """
        rendering = self.face.to_dict()
        if self.name is not None:
            rendering["name"] = self.name
        if self.info_urls:
            rendering["info URLs"] = self.info_urls
        if self.timestamp is not None:
            rendering["timestamp"] = self.timestamp
        return rendering



class RekognitionPerson:
    """Encapsulates an Amazon Rekognition person."""

    def __init__(self, person, timestamp=None):
        """
        Initializes the person object.

        :param person: Person data, in the format returned by Amazon Rekognition
                       functions.
        :param timestamp: The time when the person was detected, if the person
                          was detected in a video.
        """
        self.index = person.get("Index")
        self.bounding_box = person.get("BoundingBox")
        face = person.get("Face")
        self.face = RekognitionFace(face) if face is not None else None
        self.timestamp = timestamp

    def to_dict(self):
        """
        Renders some of the person data to a dict.

        :return: A dict that contains the person data.
        """
        rendering = self.face.to_dict() if self.face is not None else {}
        if self.index is not None:
            rendering["index"] = self.index
        if self.bounding_box is not None:
            rendering["bounding_box"] = self.bounding_box
        if self.timestamp is not None:
            rendering["timestamp"] = self.timestamp
        return rendering



class RekognitionLabel:
    """Encapsulates an Amazon Rekognition label."""

    def __init__(self, label, timestamp=None):
        """
        Initializes the label object.

        :param label: Label data, in the format returned by Amazon Rekognition
                      functions.
        :param timestamp: The time when the label was detected, if the label
                          was detected in a video.
        """
        self.name = label.get("Name")
        self.confidence = label.get("Confidence")
        self.instances = label.get("Instances")
        self.parents = label.get("Parents")
        self.timestamp = timestamp

    def to_dict(self):
        """
        Renders some of the label data to a dict.

        :return: A dict that contains the label data.
        """
        rendering = {}
        if self.name is not None:
            rendering["name"] = self.name
        if self.timestamp is not None:
            rendering["timestamp"] = self.timestamp
        return rendering



class RekognitionModerationLabel:
    """Encapsulates an Amazon Rekognition moderation label."""

    def __init__(self, label, timestamp=None):
        """
        Initializes the moderation label object.

        :param label: Label data, in the format returned by Amazon Rekognition
                      functions.
        :param timestamp: The time when the moderation label was detected, if the
                          label was detected in a video.
        """
        self.name = label.get("Name")
        self.confidence = label.get("Confidence")
        self.parent_name = label.get("ParentName")
        self.timestamp = timestamp

    def to_dict(self):
        """
        Renders some of the moderation label data to a dict.

        :return: A dict that contains the moderation label data.
        """
        rendering = {}
        if self.name is not None:
            rendering["name"] = self.name
        if self.parent_name is not None:
            rendering["parent_name"] = self.parent_name
        if self.timestamp is not None:
            rendering["timestamp"] = self.timestamp
        return rendering



class RekognitionText:
    """Encapsulates an Amazon Rekognition text element."""

    def __init__(self, text_data):
        """
        Initializes the text object.

        :param text_data: Text data, in the format returned by Amazon Rekognition
                          functions.
        """
        self.text = text_data.get("DetectedText")
        self.kind = text_data.get("Type")
        self.id = text_data.get("Id")
        self.parent_id = text_data.get("ParentId")
        self.confidence = text_data.get("Confidence")
        self.geometry = text_data.get("Geometry")

    def to_dict(self):
        """
        Renders some of the text data to a dict.

        :return: A dict that contains the text data.
        """
        rendering = {}
        if self.text is not None:
            rendering["text"] = self.text
        if self.kind is not None:
            rendering["kind"] = self.kind
        if self.geometry is not None:
            rendering["polygon"] = self.geometry.get("Polygon")
        return rendering
```
ラッパークラスを使用して、イメージ内の要素を検出し、その境界ボックスを表示します。この例で使用されているイメージは GitHub で、指示やコードとともに確認できます。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the Amazon Rekognition image detection demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    rekognition_client = boto3.client("rekognition")
    street_scene_file_name = ".media/pexels-kaique-rocha-109919.jpg"
    celebrity_file_name = ".media/pexels-pixabay-53370.jpg"
    one_girl_url = "https://dhei5unw3vrsx.cloudfront.net/images/source3_resized.jpg"
    three_girls_url = "https://dhei5unw3vrsx.cloudfront.net/images/target3_resized.jpg"
    swimwear_object = boto3.resource("s3").Object(
        "console-sample-images-pdx", "yoga_swimwear.jpg"
    )
    book_file_name = ".media/pexels-christina-morillo-1181671.jpg"

    street_scene_image = RekognitionImage.from_file(
        street_scene_file_name, rekognition_client
    )
    print(f"Detecting faces in {street_scene_image.image_name}...")
    faces = street_scene_image.detect_faces()
    print(f"Found {len(faces)} faces, here are the first three.")
    for face in faces[:3]:
        pprint(face.to_dict())
    show_bounding_boxes(
        street_scene_image.image["Bytes"],
        [[face.bounding_box for face in faces]],
        ["aqua"],
    )
    input("Press Enter to continue.")

    print(f"Detecting labels in {street_scene_image.image_name}...")
    labels = street_scene_image.detect_labels(100)
    print(f"Found {len(labels)} labels.")
    for label in labels:
        pprint(label.to_dict())
    names = []
    box_sets = []
    colors = ["aqua", "red", "white", "blue", "yellow", "green"]
    for label in labels:
        if label.instances:
            names.append(label.name)
            box_sets.append([inst["BoundingBox"] for inst in label.instances])
    print(f"Showing bounding boxes for {names} in {colors[:len(names)]}.")
    show_bounding_boxes(
        street_scene_image.image["Bytes"], box_sets, colors[: len(names)]
    )
    input("Press Enter to continue.")

    celebrity_image = RekognitionImage.from_file(
        celebrity_file_name, rekognition_client
    )
    print(f"Detecting celebrities in {celebrity_image.image_name}...")
    celebs, others = celebrity_image.recognize_celebrities()
    print(f"Found {len(celebs)} celebrities.")
    for celeb in celebs:
        pprint(celeb.to_dict())
    show_bounding_boxes(
        celebrity_image.image["Bytes"],
        [[celeb.face.bounding_box for celeb in celebs]],
        ["aqua"],
    )
    input("Press Enter to continue.")

    girl_image_response = requests.get(one_girl_url)
    girl_image = RekognitionImage(
        {"Bytes": girl_image_response.content}, "one-girl", rekognition_client
    )
    group_image_response = requests.get(three_girls_url)
    group_image = RekognitionImage(
        {"Bytes": group_image_response.content}, "three-girls", rekognition_client
    )
    print("Comparing reference face to group of faces...")
    matches, unmatches = girl_image.compare_faces(group_image, 80)
    print(f"Found {len(matches)} face matching the reference face.")
    show_bounding_boxes(
        group_image.image["Bytes"],
        [[match.bounding_box for match in matches]],
        ["aqua"],
    )
    input("Press Enter to continue.")

    swimwear_image = RekognitionImage.from_bucket(swimwear_object, rekognition_client)
    print(f"Detecting suggestive content in {swimwear_object.key}...")
    labels = swimwear_image.detect_moderation_labels()
    print(f"Found {len(labels)} moderation labels.")
    for label in labels:
        pprint(label.to_dict())
    input("Press Enter to continue.")

    book_image = RekognitionImage.from_file(book_file_name, rekognition_client)
    print(f"Detecting text in {book_image.image_name}...")
    texts = book_image.detect_text()
    print(f"Found {len(texts)} text instances. Here are the first seven:")
    for text in texts[:7]:
        pprint(text.to_dict())
    show_polygons(
        book_image.image["Bytes"], [text.geometry["Polygon"] for text in texts], "aqua"
    )

    print("Thanks for watching!")
    print("-" * 88)
```

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_python_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して AWS SDK for Python (Boto3) 、以下を可能にするウェブアプリケーションを作成する方法を示します。  
+ Amazon Simple Storage Service (Amazon S3) バケットに、写真をアップロードします。
+ Amazon Rekognition を使用して、写真を分析およびラベル付けします。
+ Amazon Simple Email Service (Amazon SES) を使用して、イメージ分析の E メールレポートを送信します。
 この例には、React で構築された JavaScript で記述されたウェブページと、Flask-RESTful で構築された Python で記述された REST サービスの 2 つの主要なコンポーネントが含まれています。  
React ウェブページを使用すると、次のことができます。  
+ S3 バケットに保存されているイメージのリストを表示します。
+ イメージを S3 バケットにアップロードします。
+ イメージ内で検出された項目を識別するイメージとラベルを表示します。
+ S3 バケット内のすべてのイメージのレポートを取得し、レポートの E メールを送信します。
ウェブページが REST サービスを呼び出します。サービスはリクエストを AWS に送信して、以下のアクションを実行します。  
+ S3 バケット内のイメージのリストを取得し、フィルタリングします。
+ Amazon S3 バケットに写真をアップロードします。
+ Amazon Rekognition を使用して個々の写真を分析し、写真で検出された項目を識別するラベルのリストを取得します。
+ S3 バケット内のすべての写真を分析し、Amazon SES を使用してレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/photo_analyzer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_python_3_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Python (Boto3)**  
 Amazon Rekognition を使用して、非同期検出ジョブを開始して、動画内の顔、オブジェクト、人を検出します。この例では、ジョブが完了し、Amazon Simple Queue Service (Amazon SQS) キューをトピックにサブスクライブしたときに、Amazon Simple Notification Service (Amazon SNS) トピックに通知するように Amazon Rekognition を設定します。キューがジョブに関するメッセージを受信すると、ジョブが取得され、結果が出力されます。  
 この例は GitHub で最もよく見られます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

# SDK for Python (Boto3) を使用する Amazon S3 の例
<a name="python_3_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_python_3_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_s3():
    """
    Use the AWS SDK for Python (Boto3) to create an Amazon Simple Storage Service
    (Amazon S3) client and list the buckets in your account.
    This example uses the default settings specified in your shared credentials
    and config files.
    """

    # Create an S3 client.
    s3_client = boto3.client("s3")

    print("Hello, Amazon S3! Let's list your buckets:")

    # Create a paginator for the list_buckets operation.
    paginator = s3_client.get_paginator("list_buckets")

    # Use the paginator to get a list of all buckets.
    response_iterator = paginator.paginate(
        PaginationConfig={
            "PageSize": 50,  # Adjust PageSize as needed.
            "StartingToken": None,
        }
    )

    # Iterate through the pages of the response.
    buckets_found = False
    for page in response_iterator:
        if "Buckets" in page and page["Buckets"]:
            buckets_found = True
            for bucket in page["Buckets"]:
                print(f"\t{bucket['Name']}")

    if not buckets_found:
        print("No buckets found!")


if __name__ == "__main__":
    hello_s3()
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListBuckets](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/ListBuckets)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
import io
import os
import uuid

import boto3
from boto3.s3.transfer import S3UploadFailedError
from botocore.exceptions import ClientError


def do_scenario(s3_resource):
    print("-" * 88)
    print("Welcome to the Amazon S3 getting started demo!")
    print("-" * 88)

    bucket_name = f"amzn-s3-demo-bucket-{uuid.uuid4()}"
    bucket = s3_resource.Bucket(bucket_name)
    try:
        bucket.create(
            CreateBucketConfiguration={
                "LocationConstraint": s3_resource.meta.client.meta.region_name
            }
        )
        print(f"Created demo bucket named {bucket.name}.")
    except ClientError as err:
        print(f"Tried and failed to create demo bucket {bucket_name}.")
        print(f"\t{err.response['Error']['Code']}:{err.response['Error']['Message']}")
        print(f"\nCan't continue the demo without a bucket!")
        return

    file_name = None
    while file_name is None:
        file_name = input("\nEnter a file you want to upload to your bucket: ")
        if not os.path.exists(file_name):
            print(f"Couldn't find file {file_name}. Are you sure it exists?")
            file_name = None

    obj = bucket.Object(os.path.basename(file_name))
    try:
        obj.upload_file(file_name)
        print(
            f"Uploaded file {file_name} into bucket {bucket.name} with key {obj.key}."
        )
    except S3UploadFailedError as err:
        print(f"Couldn't upload file {file_name} to {bucket.name}.")
        print(f"\t{err}")

    answer = input(f"\nDo you want to download {obj.key} into memory (y/n)? ")
    if answer.lower() == "y":
        data = io.BytesIO()
        try:
            obj.download_fileobj(data)
            data.seek(0)
            print(f"Got your object. Here are the first 20 bytes:\n")
            print(f"\t{data.read(20)}")
        except ClientError as err:
            print(f"Couldn't download {obj.key}.")
            print(
                f"\t{err.response['Error']['Code']}:{err.response['Error']['Message']}"
            )

    answer = input(
        f"\nDo you want to copy {obj.key} to a subfolder in your bucket (y/n)? "
    )
    if answer.lower() == "y":
        dest_obj = bucket.Object(f"demo-folder/{obj.key}")
        try:
            dest_obj.copy({"Bucket": bucket.name, "Key": obj.key})
            print(f"Copied {obj.key} to {dest_obj.key}.")
        except ClientError as err:
            print(f"Couldn't copy {obj.key} to {dest_obj.key}.")
            print(
                f"\t{err.response['Error']['Code']}:{err.response['Error']['Message']}"
            )

    print("\nYour bucket contains the following objects:")
    try:
        for o in bucket.objects.all():
            print(f"\t{o.key}")
    except ClientError as err:
        print(f"Couldn't list the objects in bucket {bucket.name}.")
        print(f"\t{err.response['Error']['Code']}:{err.response['Error']['Message']}")

    answer = input(
        "\nDo you want to delete all of the objects as well as the bucket (y/n)? "
    )
    if answer.lower() == "y":
        try:
            bucket.objects.delete()
            bucket.delete()
            print(f"Emptied and deleted bucket {bucket.name}.\n")
        except ClientError as err:
            print(f"Couldn't empty and delete bucket {bucket.name}.")
            print(
                f"\t{err.response['Error']['Code']}:{err.response['Error']['Message']}"
            )

    print("Thanks for watching!")
    print("-" * 88)


if __name__ == "__main__":
    do_scenario(boto3.resource("s3"))
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetObject)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/ListObjectsV2)
  + [PutObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_python_3_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    def copy(self, dest_object):
        """
        Copies the object to another bucket.

        :param dest_object: The destination object initialized with a bucket and key.
                            This is a Boto3 Object resource.
        """
        try:
            dest_object.copy_from(
                CopySource={"Bucket": self.object.bucket_name, "Key": self.object.key}
            )
            dest_object.wait_until_exists()
            logger.info(
                "Copied object from %s:%s to %s:%s.",
                self.object.bucket_name,
                self.object.key,
                dest_object.bucket_name,
                dest_object.key,
            )
        except ClientError:
            logger.exception(
                "Couldn't copy object from %s/%s to %s/%s.",
                self.object.bucket_name,
                self.object.key,
                dest_object.bucket_name,
                dest_object.key,
            )
            raise
```
条件付きリクエストを使用してオブジェクトをコピーします。  

```
class S3ConditionalRequests:
    """Encapsulates S3 conditional request operations."""

    def __init__(self, s3_client):
        self.s3 = s3_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        s3_client = boto3.client("s3")
        return cls(s3_client)


    def copy_object_conditional(
        self,
        source_key: str,
        dest_key: str,
        source_bucket: str,
        dest_bucket: str,
        condition_type: str,
        condition_value: str,
    ):
        """
        Copies an object from one Amazon S3 bucket to another with a conditional request.

        :param source_key: The key of the source object to copy.
        :param dest_key: The key of the destination object.
        :param source_bucket: The source bucket of the object.
        :param dest_bucket: The destination bucket of the object.
        :param condition_type: The type of condition to apply, e.g.
        'CopySourceIfMatch', 'CopySourceIfNoneMatch', 'CopySourceIfModifiedSince', 'CopySourceIfUnmodifiedSince'.
        :param condition_value: The value to use for the condition.
        """
        try:
            self.s3.copy_object(
                Bucket=dest_bucket,
                Key=dest_key,
                CopySource={"Bucket": source_bucket, "Key": source_key},
                **{condition_type: condition_value},
            )
            print(
                f"\tConditional copy successful for key {dest_key} in bucket {dest_bucket}."
            )
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "PreconditionFailed":
                print("\tConditional copy failed: Precondition failed")
            elif error_code == "304":  # Not modified error code.
                print("\tConditional copy failed: Object not modified")
            else:
                logger.error(f"Unexpected error: {error_code}")
                raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CopyObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CopyObject)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_python_3_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。
デフォルトの設定でバケットを作成します。  

```
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
```
ライフサイクル設定を使用してバージョン対応バケットを作成します。  

```
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
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CreateBucket)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_python_3_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 delete(self):
        """
        Delete the bucket. The bucket must be empty or an error is raised.
        """
        try:
            self.bucket.delete()
            self.bucket.wait_until_not_exists()
            logger.info("Bucket %s successfully deleted.", self.bucket.name)
        except ClientError:
            logger.exception("Couldn't delete bucket %s.", self.bucket.name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteBucket)」を参照してください。

### `DeleteBucketCors`
<a name="s3_DeleteBucketCors_python_3_topic"></a>

次のコード例は、`DeleteBucketCors` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 delete_cors(self):
        """
        Delete the CORS rules from the bucket.

        :param bucket_name: The name of the bucket to update.
        """
        try:
            self.bucket.Cors().delete()
            logger.info("Deleted CORS from bucket '%s'.", self.bucket.name)
        except ClientError:
            logger.exception("Couldn't delete CORS from bucket '%s'.", self.bucket.name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteBucketCors](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteBucketCors)」を参照してください。

### `DeleteBucketLifecycle`
<a name="s3_DeleteBucketLifecycle_python_3_topic"></a>

次のコード例は、`DeleteBucketLifecycle` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 delete_lifecycle_configuration(self):
        """
        Remove the lifecycle configuration from the specified bucket.
        """
        try:
            self.bucket.LifecycleConfiguration().delete()
            logger.info(
                "Deleted lifecycle configuration for bucket '%s'.", self.bucket.name
            )
        except ClientError:
            logger.exception(
                "Couldn't delete lifecycle configuration for bucket '%s'.",
                self.bucket.name,
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteBucketLifecycle](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteBucketLifecycle)」を参照してください。

### `DeleteBucketPolicy`
<a name="s3_DeleteBucketPolicy_python_3_topic"></a>

次のコード例は、`DeleteBucketPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 delete_policy(self):
        """
        Delete the security policy from the bucket.
        """
        try:
            self.bucket.Policy().delete()
            logger.info("Deleted policy for bucket '%s'.", self.bucket.name)
        except ClientError:
            logger.exception(
                "Couldn't delete policy for bucket '%s'.", self.bucket.name
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteBucketPolicy](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteBucketPolicy)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_python_3_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。
オブジェクトを削除します。  

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    def delete(self):
        """
        Deletes the object.
        """
        try:
            self.object.delete()
            self.object.wait_until_not_exists()
            logger.info(
                "Deleted object '%s' from bucket '%s'.",
                self.object.key,
                self.object.bucket_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't delete object '%s' from bucket '%s'.",
                self.object.key,
                self.object.bucket_name,
            )
            raise
```
オブジェクトの新しいバージョンを削除して、オブジェクトを以前のバージョンにロールバックします。  

```
def rollback_object(bucket, object_key, version_id):
    """
    Rolls back an object to an earlier version by deleting all versions that
    occurred after the specified rollback version.

    Usage is shown in the usage_demo_single_object function at the end of this module.

    :param bucket: The bucket that holds the object to roll back.
    :param object_key: The object to roll back.
    :param version_id: The version ID to roll back to.
    """
    # Versions must be sorted by last_modified date because delete markers are
    # at the end of the list even when they are interspersed in time.
    versions = sorted(
        bucket.object_versions.filter(Prefix=object_key),
        key=attrgetter("last_modified"),
        reverse=True,
    )

    logger.debug(
        "Got versions:\n%s",
        "\n".join(
            [
                f"\t{version.version_id}, last modified {version.last_modified}"
                for version in versions
            ]
        ),
    )

    if version_id in [ver.version_id for ver in versions]:
        print(f"Rolling back to version {version_id}")
        for version in versions:
            if version.version_id != version_id:
                version.delete()
                print(f"Deleted version {version.version_id}")
            else:
                break

        print(f"Active version is now {bucket.Object(object_key).version_id}")
    else:
        raise KeyError(
            f"{version_id} was not found in the list of versions for " f"{object_key}."
        )
```
オブジェクトのアクティブな削除マーカーを削除して、削除されたオブジェクトを復活させます。  

```
def revive_object(bucket, object_key):
    """
    Revives a versioned object that was deleted by removing the object's active
    delete marker.
    A versioned object presents as deleted when its latest version is a delete marker.
    By removing the delete marker, we make the previous version the latest version
    and the object then presents as *not* deleted.

    Usage is shown in the usage_demo_single_object function at the end of this module.

    :param bucket: The bucket that contains the object.
    :param object_key: The object to revive.
    """
    # Get the latest version for the object.
    response = s3.meta.client.list_object_versions(
        Bucket=bucket.name, Prefix=object_key, MaxKeys=1
    )

    if "DeleteMarkers" in response:
        latest_version = response["DeleteMarkers"][0]
        if latest_version["IsLatest"]:
            logger.info(
                "Object %s was indeed deleted on %s. Let's revive it.",
                object_key,
                latest_version["LastModified"],
            )
            obj = bucket.Object(object_key)
            obj.Version(latest_version["VersionId"]).delete()
            logger.info(
                "Revived %s, active version is now %s  with body '%s'",
                object_key,
                obj.version_id,
                obj.get()["Body"].read(),
            )
        else:
            logger.warning(
                "Delete marker is not the latest version for %s!", object_key
            )
    elif "Versions" in response:
        logger.warning("Got an active version for %s, nothing to do.", object_key)
    else:
        logger.error("Couldn't get any version info for %s.", object_key)
```
S3 オブジェクトから削除マーカーを削除する Lambda ハンドラを作成します。このハンドラを使用して、バージョン管理されたバケット内の余分な削除マーカーを効率的にクリーンアップできます。  

```
import logging
from urllib import parse
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)
logger.setLevel("INFO")

s3 = boto3.client("s3")


def lambda_handler(event, context):
    """
    Removes a delete marker from the specified versioned object.

    :param event: The S3 batch event that contains the ID of the delete marker
                  to remove.
    :param context: Context about the event.
    :return: A result structure that Amazon S3 uses to interpret the result of the
             operation. When the result code is TemporaryFailure, S3 retries the
             operation.
    """
    # Parse job parameters from Amazon S3 batch operations
    invocation_id = event["invocationId"]
    invocation_schema_version = event["invocationSchemaVersion"]

    results = []
    result_code = None
    result_string = None

    task = event["tasks"][0]
    task_id = task["taskId"]

    try:
        obj_key = parse.unquote_plus(task["s3Key"], encoding="utf-8")
        obj_version_id = task["s3VersionId"]
        bucket_name = task["s3BucketArn"].split(":")[-1]

        logger.info(
            "Got task: remove delete marker %s from object %s.", obj_version_id, obj_key
        )

        try:
            # If this call does not raise an error, the object version is not a delete
            # marker and should not be deleted.
            response = s3.head_object(
                Bucket=bucket_name, Key=obj_key, VersionId=obj_version_id
            )
            result_code = "PermanentFailure"
            result_string = (
                f"Object {obj_key}, ID {obj_version_id} is not " f"a delete marker."
            )

            logger.debug(response)
            logger.warning(result_string)
        except ClientError as error:
            delete_marker = error.response["ResponseMetadata"]["HTTPHeaders"].get(
                "x-amz-delete-marker", "false"
            )
            if delete_marker == "true":
                logger.info(
                    "Object %s, version %s is a delete marker.", obj_key, obj_version_id
                )
                try:
                    s3.delete_object(
                        Bucket=bucket_name, Key=obj_key, VersionId=obj_version_id
                    )
                    result_code = "Succeeded"
                    result_string = (
                        f"Successfully removed delete marker "
                        f"{obj_version_id} from object {obj_key}."
                    )
                    logger.info(result_string)
                except ClientError as error:
                    # Mark request timeout as a temporary failure so it will be retried.
                    if error.response["Error"]["Code"] == "RequestTimeout":
                        result_code = "TemporaryFailure"
                        result_string = (
                            f"Attempt to remove delete marker from  "
                            f"object {obj_key} timed out."
                        )
                        logger.info(result_string)
                    else:
                        raise
            else:
                raise ValueError(
                    f"The x-amz-delete-marker header is either not "
                    f"present or is not 'true'."
                )
    except Exception as error:
        # Mark all other exceptions as permanent failures.
        result_code = "PermanentFailure"
        result_string = str(error)
        logger.exception(error)
    finally:
        results.append(
            {
                "taskId": task_id,
                "resultCode": result_code,
                "resultString": result_string,
            }
        )
    return {
        "invocationSchemaVersion": invocation_schema_version,
        "treatMissingKeysAs": "PermanentFailure",
        "invocationId": invocation_id,
        "results": results,
    }
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteObject)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_python_3_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。
オブジェクト キーのリストからオブジェクトのセットを削除します。  

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    @staticmethod
    def delete_objects(bucket, object_keys):
        """
        Removes a list of objects from a bucket.
        This operation is done as a batch in a single request.

        :param bucket: The bucket that contains the objects. This is a Boto3 Bucket
                       resource.
        :param object_keys: The list of keys that identify the objects to remove.
        :return: The response that contains data about which objects were deleted
                 and any that could not be deleted.
        """
        try:
            response = bucket.delete_objects(
                Delete={"Objects": [{"Key": key} for key in object_keys]}
            )
            if "Deleted" in response:
                logger.info(
                    "Deleted objects '%s' from bucket '%s'.",
                    [del_obj["Key"] for del_obj in response["Deleted"]],
                    bucket.name,
                )
            if "Errors" in response:
                logger.warning(
                    "Could not delete objects '%s' from bucket '%s'.",
                    [
                        f"{del_obj['Key']}: {del_obj['Code']}"
                        for del_obj in response["Errors"]
                    ],
                    bucket.name,
                )
        except ClientError:
            logger.exception("Couldn't delete any objects from bucket %s.", bucket.name)
            raise
        else:
            return response
```
バケット内のすべてのオブジェクトを削除します。  

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    @staticmethod
    def empty_bucket(bucket):
        """
        Remove all objects from a bucket.

        :param bucket: The bucket to empty. This is a Boto3 Bucket resource.
        """
        try:
            bucket.objects.delete()
            logger.info("Emptied bucket '%s'.", bucket.name)
        except ClientError:
            logger.exception("Couldn't empty bucket '%s'.", bucket.name)
            raise
```
すべてのバージョンを削除することによって、バージョン管理されているオブジェクトを完全に削除します。  

```
def permanently_delete_object(bucket, object_key):
    """
    Permanently deletes a versioned object by deleting all of its versions.

    Usage is shown in the usage_demo_single_object function at the end of this module.

    :param bucket: The bucket that contains the object.
    :param object_key: The object to delete.
    """
    try:
        bucket.object_versions.filter(Prefix=object_key).delete()
        logger.info("Permanently deleted all versions of object %s.", object_key)
    except ClientError:
        logger.exception("Couldn't delete all versions of %s.", object_key)
        raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteObjects](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteObjects)」を参照してください。

### `GetBucketAcl`
<a name="s3_GetBucketAcl_python_3_topic"></a>

次のコード例は、`GetBucketAcl` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 get_acl(self):
        """
        Get the ACL of the bucket.

        :return: The ACL of the bucket.
        """
        try:
            acl = self.bucket.Acl()
            logger.info(
                "Got ACL for bucket %s. Owner is %s.", self.bucket.name, acl.owner
            )
        except ClientError:
            logger.exception("Couldn't get ACL for bucket %s.", self.bucket.name)
            raise
        else:
            return acl
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetBucketAcl](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetBucketAcl)」を参照してください。

### `GetBucketCors`
<a name="s3_GetBucketCors_python_3_topic"></a>

次のコード例は、`GetBucketCors` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 get_cors(self):
        """
        Get the CORS rules for the bucket.

        :return The CORS rules for the specified bucket.
        """
        try:
            cors = self.bucket.Cors()
            logger.info(
                "Got CORS rules %s for bucket '%s'.", cors.cors_rules, self.bucket.name
            )
        except ClientError:
            logger.exception(("Couldn't get CORS for bucket %s.", self.bucket.name))
            raise
        else:
            return cors
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetBucketCors](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetBucketCors)」を参照してください。

### `GetBucketLifecycleConfiguration`
<a name="s3_GetBucketLifecycleConfiguration_python_3_topic"></a>

次のコード例は、`GetBucketLifecycleConfiguration` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 get_lifecycle_configuration(self):
        """
        Get the lifecycle configuration of the bucket.

        :return: The lifecycle rules of the specified bucket.
        """
        try:
            config = self.bucket.LifecycleConfiguration()
            logger.info(
                "Got lifecycle rules %s for bucket '%s'.",
                config.rules,
                self.bucket.name,
            )
        except:
            logger.exception(
                "Couldn't get lifecycle rules for bucket '%s'.", self.bucket.name
            )
            raise
        else:
            return config.rules
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetBucketLifecycleConfiguration)」を参照してください。

### `GetBucketPolicy`
<a name="s3_GetBucketPolicy_python_3_topic"></a>

次のコード例は、`GetBucketPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 get_policy(self):
        """
        Get the security policy of the bucket.

        :return: The security policy of the specified bucket, in JSON format.
        """
        try:
            policy = self.bucket.Policy()
            logger.info(
                "Got policy %s for bucket '%s'.", policy.policy, self.bucket.name
            )
        except ClientError:
            logger.exception("Couldn't get policy for bucket '%s'.", self.bucket.name)
            raise
        else:
            return json.loads(policy.policy)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetBucketPolicy](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetBucketPolicy)」を参照してください。

### `GetObject`
<a name="s3_GetObject_python_3_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    def get(self):
        """
        Gets the object.

        :return: The object data in bytes.
        """
        try:
            body = self.object.get()["Body"].read()
            logger.info(
                "Got object '%s' from bucket '%s'.",
                self.object.key,
                self.object.bucket_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't get object '%s' from bucket '%s'.",
                self.object.key,
                self.object.bucket_name,
            )
            raise
        else:
            return body
```
条件付きリクエストを使用してオブジェクトを取得します。  

```
class S3ConditionalRequests:
    """Encapsulates S3 conditional request operations."""

    def __init__(self, s3_client):
        self.s3 = s3_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        s3_client = boto3.client("s3")
        return cls(s3_client)



    def get_object_conditional(
        self,
        object_key: str,
        source_bucket: str,
        condition_type: str,
        condition_value: str,
    ):
        """
        Retrieves an object from Amazon S3 with a conditional request.

        :param object_key: The key of the object to retrieve.
        :param source_bucket: The source bucket of the object.
        :param condition_type: The type of condition: 'IfMatch', 'IfNoneMatch', 'IfModifiedSince', 'IfUnmodifiedSince'.
        :param condition_value: The value to use for the condition.
        """
        try:
            response = self.s3.get_object(
                Bucket=source_bucket,
                Key=object_key,
                **{condition_type: condition_value},
            )
            sample_bytes = response["Body"].read(20)
            print(
                f"\tConditional read successful. Here are the first 20 bytes of the object:\n"
            )
            print(f"\t{sample_bytes}")
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "PreconditionFailed":
                print("\tConditional read failed: Precondition failed")
            elif error_code == "304":  # Not modified error code.
                print("\tConditional read failed: Object not modified")
            else:
                logger.error(f"Unexpected error: {error_code}")
                raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetObject)」を参照してください。

### `GetObjectAcl`
<a name="s3_GetObjectAcl_python_3_topic"></a>

次のコード例は、`GetObjectAcl` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    def get_acl(self):
        """
        Gets the ACL of the object.

        :return: The ACL of the object.
        """
        try:
            acl = self.object.Acl()
            logger.info(
                "Got ACL for object %s owned by %s.",
                self.object.key,
                acl.owner["DisplayName"],
            )
        except ClientError:
            logger.exception("Couldn't get ACL for object %s.", self.object.key)
            raise
        else:
            return acl
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetObjectAcl](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetObjectAcl)」を参照してください。

### `GetObjectLegalHold`
<a name="s3_GetObjectLegalHold_python_3_topic"></a>

次のコード例は、`GetObjectLegalHold` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/object-locking#code-examples)での設定と実行の方法を確認してください。
オブジェクトにリーガルホールドを適用します。  

```
def get_legal_hold(s3_client, bucket: str, key: str) -> None:
    """
    Get the legal hold status of a specific file in a bucket.

    Args:
        s3_client: Boto3 S3 client.
        bucket: The name of the bucket containing the file.
        key: The key of the file to get the legal hold status of.
    """
    print()
    logger.info("Getting legal hold status of file [%s] in bucket [%s]", key, bucket)
    try:
        response = s3_client.get_object_legal_hold(Bucket=bucket, Key=key)
        legal_hold_status = response["LegalHold"]["Status"]
        logger.debug(
            "Legal hold status of file [%s] in bucket [%s] is [%s]",
            key,
            bucket,
            legal_hold_status,
        )
    except Exception as e:
        logger.error(
            "Failed to get legal hold status of file [%s] in bucket [%s]: %s",
            key,
            bucket,
            e,
        )
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetObjectLegalHold](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetObjectLegalHold)」を参照してください。**

### `GetObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_python_3_topic"></a>

次のコード例は、`GetObjectLockConfiguration` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/object-locking#code-examples)での設定と実行の方法を確認してください。
オブジェクトロック設定を取得します。  

```
def is_object_lock_enabled(s3_client, bucket: str) -> bool:
    """
    Check if object lock is enabled for a bucket.

    Args:
        s3_client: Boto3 S3 client.
        bucket: The name of the bucket to check.

    Returns:
        True if object lock is enabled, False otherwise.
    """
    try:
        response = s3_client.get_object_lock_configuration(Bucket=bucket)
        return (
            "ObjectLockConfiguration" in response
            and response["ObjectLockConfiguration"]["ObjectLockEnabled"] == "Enabled"
        )
    except s3_client.exceptions.ClientError as e:
        if e.response["Error"]["Code"] == "ObjectLockConfigurationNotFoundError":
            return False
        else:
            raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetObjectLockConfiguration](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetObjectLockConfiguration)」を参照してください。**

### `HeadBucket`
<a name="s3_HeadBucket_python_3_topic"></a>

次のコード例は、`HeadBucket` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 exists(self):
        """
        Determine whether the bucket exists and you have access to it.

        :return: True when the bucket exists; otherwise, False.
        """
        try:
            self.bucket.meta.client.head_bucket(Bucket=self.bucket.name)
            logger.info("Bucket %s exists.", self.bucket.name)
            exists = True
        except ClientError:
            logger.warning(
                "Bucket %s doesn't exist or you don't have access to it.",
                self.bucket.name,
            )
            exists = False
        return exists
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[HeadBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/HeadBucket)」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_python_3_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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


    @staticmethod
    def list(s3_resource):
        """
        Get the buckets in all Regions for the current account.

        :param s3_resource: A Boto3 S3 resource. This is a high-level resource in Boto3
                            that contains collections and factory methods to create
                            other high-level S3 sub-resources.
        :return: The list of buckets.
        """
        try:
            buckets = list(s3_resource.buckets.all())
            logger.info("Got buckets: %s.", buckets)
        except ClientError:
            logger.exception("Couldn't get buckets.")
            raise
        else:
            return buckets
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListBuckets](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/ListBuckets)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_python_3_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    @staticmethod
    def list(bucket, prefix=None):
        """
        Lists the objects in a bucket, optionally filtered by a prefix.

        :param bucket: The bucket to query. This is a Boto3 Bucket resource.
        :param prefix: When specified, only objects that start with this prefix are listed.
        :return: The list of objects.
        """
        try:
            if not prefix:
                objects = list(bucket.objects.all())
            else:
                objects = list(bucket.objects.filter(Prefix=prefix))
            logger.info(
                "Got objects %s from bucket '%s'", [o.key for o in objects], bucket.name
            )
        except ClientError:
            logger.exception("Couldn't get objects for bucket '%s'.", bucket.name)
            raise
        else:
            return objects
```
+  API の詳細については、「AWS  SDK for Python (Boto3) API リファレンス」の「[ListObjectsV2](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/ListObjectsV2)」を参照してください。**

### `PutBucketAcl`
<a name="s3_PutBucketAcl_python_3_topic"></a>

次のコード例は、`PutBucketAcl` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 grant_log_delivery_access(self):
        """
        Grant the AWS Log Delivery group write access to the bucket so that
        Amazon S3 can deliver access logs to the bucket. This is the only recommended
        use of an S3 bucket ACL.
        """
        try:
            acl = self.bucket.Acl()
            # Putting an ACL overwrites the existing ACL. If you want to preserve
            # existing grants, append new grants to the list of existing grants.
            grants = acl.grants if acl.grants else []
            grants.append(
                {
                    "Grantee": {
                        "Type": "Group",
                        "URI": "http://acs.amazonaws.com/groups/s3/LogDelivery",
                    },
                    "Permission": "WRITE",
                }
            )
            acl.put(AccessControlPolicy={"Grants": grants, "Owner": acl.owner})
            logger.info("Granted log delivery access to bucket '%s'", self.bucket.name)
        except ClientError:
            logger.exception("Couldn't add ACL to bucket '%s'.", self.bucket.name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutBucketAcl](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutBucketAcl)」を参照してください。

### `PutBucketCors`
<a name="s3_PutBucketCors_python_3_topic"></a>

次のコード例は、`PutBucketCors` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 put_cors(self, cors_rules):
        """
        Apply CORS rules to the bucket. CORS rules specify the HTTP actions that are
        allowed from other domains.

        :param cors_rules: The CORS rules to apply.
        """
        try:
            self.bucket.Cors().put(CORSConfiguration={"CORSRules": cors_rules})
            logger.info(
                "Put CORS rules %s for bucket '%s'.", cors_rules, self.bucket.name
            )
        except ClientError:
            logger.exception("Couldn't put CORS rules for bucket %s.", self.bucket.name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutBucketCors](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutBucketCors)」を参照してください。

### `PutBucketLifecycleConfiguration`
<a name="s3_PutBucketLifecycleConfiguration_python_3_topic"></a>

次のコード例は、`PutBucketLifecycleConfiguration` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 put_lifecycle_configuration(self, lifecycle_rules):
        """
        Apply a lifecycle configuration to the bucket. The lifecycle configuration can
        be used to archive or delete the objects in the bucket according to specified
        parameters, such as a number of days.

        :param lifecycle_rules: The lifecycle rules to apply.
        """
        try:
            self.bucket.LifecycleConfiguration().put(
                LifecycleConfiguration={"Rules": lifecycle_rules}
            )
            logger.info(
                "Put lifecycle rules %s for bucket '%s'.",
                lifecycle_rules,
                self.bucket.name,
            )
        except ClientError:
            logger.exception(
                "Couldn't put lifecycle rules for bucket '%s'.", self.bucket.name
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutBucketLifecycleConfiguration)」を参照してください。

### `PutBucketPolicy`
<a name="s3_PutBucketPolicy_python_3_topic"></a>

次のコード例は、`PutBucketPolicy` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
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 put_policy(self, policy):
        """
        Apply a security policy to the bucket. Policies control users' ability
        to perform specific actions, such as listing the objects in the bucket.

        :param policy: The policy to apply to the bucket.
        """
        try:
            self.bucket.Policy().put(Policy=json.dumps(policy))
            logger.info("Put policy %s for bucket '%s'.", policy, self.bucket.name)
        except ClientError:
            logger.exception("Couldn't apply policy to bucket '%s'.", self.bucket.name)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutBucketPolicy](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutBucketPolicy)」を参照してください。

### `PutObject`
<a name="s3_PutObject_python_3_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    def put(self, data):
        """
        Upload data to the object.

        :param data: The data to upload. This can either be bytes or a string. When this
                     argument is a string, it is interpreted as a file name, which is
                     opened in read bytes mode.
        """
        put_data = data
        if isinstance(data, str):
            try:
                put_data = open(data, "rb")
            except IOError:
                logger.exception("Expected file name or binary data, got '%s'.", data)
                raise

        try:
            self.object.put(Body=put_data)
            self.object.wait_until_exists()
            logger.info(
                "Put object '%s' to bucket '%s'.",
                self.object.key,
                self.object.bucket_name,
            )
        except ClientError:
            logger.exception(
                "Couldn't put object '%s' to bucket '%s'.",
                self.object.key,
                self.object.bucket_name,
            )
            raise
        finally:
            if getattr(put_data, "close", None):
                put_data.close()
```
条件付きリクエストを使用してオブジェクトをアップロードします。  

```
class S3ConditionalRequests:
    """Encapsulates S3 conditional request operations."""

    def __init__(self, s3_client):
        self.s3 = s3_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        s3_client = boto3.client("s3")
        return cls(s3_client)



    def put_object_conditional(self, object_key: str, source_bucket: str, data: bytes):
        """
        Uploads an object to Amazon S3 with a conditional request. Prevents overwrite
        using an IfNoneMatch condition for the object key.

        :param object_key: The key of the object to upload.
        :param source_bucket: The source bucket of the object.
        :param data: The data to upload.
        """
        try:
            self.s3.put_object(
                Bucket=source_bucket, Key=object_key, Body=data, IfNoneMatch="*"
            )
            print(
                f"\tConditional write successful for key {object_key} in bucket {source_bucket}."
            )
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "PreconditionFailed":
                print("\tConditional write failed: Precondition failed")
            else:
                logger.error(f"Unexpected error: {error_code}")
                raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObject)」を参照してください。

### `PutObjectAcl`
<a name="s3_PutObjectAcl_python_3_topic"></a>

次のコード例は、`PutObjectAcl` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。

```
class ObjectWrapper:
    """Encapsulates S3 object actions."""

    def __init__(self, s3_object):
        """
        :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3
                          that wraps object actions in a class-like structure.
        """
        self.object = s3_object
        self.key = self.object.key


    def put_acl(self, email):
        """
        Applies an ACL to the object that grants read access to an AWS user identified
        by email address.

        :param email: The email address of the user to grant access.
        """
        try:
            acl = self.object.Acl()
            # Putting an ACL overwrites the existing ACL, so append new grants
            # if you want to preserve existing grants.
            grants = acl.grants if acl.grants else []
            grants.append(
                {
                    "Grantee": {"Type": "AmazonCustomerByEmail", "EmailAddress": email},
                    "Permission": "READ",
                }
            )
            acl.put(AccessControlPolicy={"Grants": grants, "Owner": acl.owner})
            logger.info("Granted read access to %s.", email)
        except ClientError:
            logger.exception("Couldn't add ACL to object '%s'.", self.object.key)
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[PutObjectAcl](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObjectAcl)」を参照してください。

### `PutObjectLegalHold`
<a name="s3_PutObjectLegalHold_python_3_topic"></a>

次のコード例は、`PutObjectLegalHold` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/object-locking#code-examples)での設定と実行の方法を確認してください。
オブジェクトにリーガルホールドを適用します。  

```
def set_legal_hold(s3_client, bucket: str, key: str) -> None:
    """
    Set a legal hold on a specific file in a bucket.

    Args:
        s3_client: Boto3 S3 client.
        bucket: The name of the bucket containing the file.
        key: The key of the file to set the legal hold on.
    """
    print()
    logger.info("Setting legal hold on file [%s] in bucket [%s]", key, bucket)
    try:
        before_status = "OFF"
        after_status = "ON"
        s3_client.put_object_legal_hold(
            Bucket=bucket, Key=key, LegalHold={"Status": after_status}
        )
        logger.debug(
            "Legal hold set successfully on file [%s] in bucket [%s]", key, bucket
        )
        _print_legal_hold_update(bucket, key, before_status, after_status)
    except Exception as e:
        logger.error(
            "Failed to set legal hold on file [%s] in bucket [%s]: %s", key, bucket, e
        )
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[PutObjectLegalHold](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObjectLegalHold)」を参照してください。**

### `PutObjectLockConfiguration`
<a name="s3_PutObjectLockConfiguration_python_3_topic"></a>

次のコード例は、`PutObjectLockConfiguration` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/object-locking#code-examples)での設定と実行の方法を確認してください。
オブジェクトロック設定を適用します。  

```
        s3_client.put_object_lock_configuration(
            Bucket=bucket,
            ObjectLockConfiguration={"ObjectLockEnabled": "Disabled", "Rule": {}},
        )
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[PutObjectLockConfiguration](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObjectLockConfiguration)」を参照してください。**

### `PutObjectRetention`
<a name="s3_PutObjectRetention_python_3_topic"></a>

次のコード例は、`PutObjectRetention` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/object-locking#code-examples)での設定と実行の方法を確認してください。
オブジェクト保持を適用します。  

```
            s3_client.put_object_retention(
                Bucket=bucket,
                Key=key,
                VersionId=version_id,
                Retention={"Mode": "GOVERNANCE", "RetainUntilDate": far_future_date},
                BypassGovernanceRetention=True,
            )
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[PutObjectRetention](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObjectRetention)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_python_3_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_basics#code-examples)での設定と実行の方法を確認してください。
S3 アクションを期間限定で実行できる署名付き URL を生成します。Requests パッケージを使用して、URL でリクエストを行います。  

```
import argparse
import logging
import boto3
from botocore.exceptions import ClientError
import requests

logger = logging.getLogger(__name__)


def generate_presigned_url(s3_client, client_method, method_parameters, expires_in):
    """
    Generate a presigned Amazon S3 URL that can be used to perform an action.

    :param s3_client: A Boto3 Amazon S3 client.
    :param client_method: The name of the client method that the URL performs.
    :param method_parameters: The parameters of the specified client method.
    :param expires_in: The number of seconds the presigned URL is valid for.
    :return: The presigned URL.
    """
    try:
        url = s3_client.generate_presigned_url(
            ClientMethod=client_method, Params=method_parameters, ExpiresIn=expires_in
        )
        logger.info("Got presigned URL: %s", url)
    except ClientError:
        logger.exception(
            "Couldn't get a presigned URL for client method '%s'.", client_method
        )
        raise
    return url


def usage_demo():
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print("Welcome to the Amazon S3 presigned URL demo.")
    print("-" * 88)

    parser = argparse.ArgumentParser()
    parser.add_argument("bucket", help="The name of the bucket.")
    parser.add_argument(
        "key",
        help="For a GET operation, the key of the object in Amazon S3. For a "
        "PUT operation, the name of a file to upload.",
    )
    parser.add_argument("action", choices=("get", "put"), help="The action to perform.")
    args = parser.parse_args()

    s3_client = boto3.client("s3")
    client_action = "get_object" if args.action == "get" else "put_object"
    url = generate_presigned_url(
        s3_client, client_action, {"Bucket": args.bucket, "Key": args.key}, 1000
    )

    print("Using the Requests package to send a request to the URL.")
    response = None
    if args.action == "get":
        response = requests.get(url)
        if response.status_code == 200:
            with open(args.key.split("/")[-1], 'wb') as object_file:
                object_file.write(response.content)
    elif args.action == "put":
        print("Putting data to the URL.")
        try:
            with open(args.key, "rb") as object_file:
                object_text = object_file.read()
            response = requests.put(url, data=object_text)
        except FileNotFoundError:
            print(
                f"Couldn't find {args.key}. For a PUT operation, the key must be the "
                f"name of a file that exists on your computer."
            )

    if response is not None:
        print(f"Status: {response.status_code}\nReason: {response.reason}")

    print("-" * 88)


if __name__ == "__main__":
    usage_demo()
```
署名付き POST リクエストを生成して、ファイルをアップロードします。  

```
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 generate_presigned_post(self, object_key, expires_in):
        """
        Generate a presigned Amazon S3 POST request to upload a file.
        A presigned POST can be used for a limited time to let someone without an AWS
        account upload a file to a bucket.

        :param object_key: The object key to identify the uploaded object.
        :param expires_in: The number of seconds the presigned POST is valid.
        :return: A dictionary that contains the URL and form fields that contain
                 required access data.
        """
        try:
            response = self.bucket.meta.client.generate_presigned_post(
                Bucket=self.bucket.name, Key=object_key, ExpiresIn=expires_in
            )
            logger.info("Got presigned POST URL: %s", response["url"])
        except ClientError:
            logger.exception(
                "Couldn't get a presigned POST URL for bucket '%s' and object '%s'",
                self.bucket.name,
                object_key,
            )
            raise
        return response
```

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_python_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Textract AWS SDK for Python (Boto3) で を使用して、ドキュメントイメージ内のテキスト、フォーム、テーブル要素を検出する方法を示します。入力イメージと Amazon Textract 出力は、検出された要素を探索できる Tkinter アプリケーションに表示されます。  
+ Amazon Textract にドキュメントイメージを送信し、検出された要素の出力を調べます。
+ Amazon Textract に直接イメージを送信するか、Amazon Simple Storage Service (Amazon S3) バケットを通じてイメージを送信します。
+ 非同期 API を使用して、ジョブの完了時に Amazon Simple Notification Service (Amazon SNS) トピックに通知を発行するジョブを開始します。
+ Amazon Simple Queue Service (Amazon SQS) キューにジョブ完了メッセージについてポーリングし、結果を表示します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_explorer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### 画像から抽出されたテキスト内のエンティティを検出する
<a name="cross_TextractComprehendDetectEntities_python_3_topic"></a>

次のコード例は、Amazon Comprehend を使用して、Amazon S3 に格納されている画像から Amazon Textract によって抽出されたテキスト内のエンティティを検出する方法を示しています。

**SDK for Python (Boto3)**  
 Jupyter ノートブック AWS SDK for Python (Boto3) で を使用して、イメージから抽出されたテキスト内のエンティティを検出する方法を示します。この例では、Amazon Textract を使用して Amazon Simple Storage Service (Amazon S3) に保存されている画像からテキストを抽出し、Amazon Comprehend を使用して、抽出されたテキスト内のエンティティを検出します。  
 この例は Jupyter Notebook であり、ノートブックをホストできる環境で実行する必要があります。Amazon SageMaker AI を使用してサンプルを実行する方法については、「[TextractAndComprehendNotebook.ipynb](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_comprehend_notebook/TextractAndComprehendNotebook.ipynb)」の手順を参照してください。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_comprehend_notebook#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon S3
+ Amazon Textract

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_python_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して AWS SDK for Python (Boto3) 、以下を可能にするウェブアプリケーションを作成する方法を示します。  
+ Amazon Simple Storage Service (Amazon S3) バケットに、写真をアップロードします。
+ Amazon Rekognition を使用して、写真を分析およびラベル付けします。
+ Amazon Simple Email Service (Amazon SES) を使用して、イメージ分析の E メールレポートを送信します。
 この例には、React で構築された JavaScript で記述されたウェブページと、Flask-RESTful で構築された Python で記述された REST サービスの 2 つの主要なコンポーネントが含まれています。  
React ウェブページを使用すると、次のことができます。  
+ S3 バケットに保存されているイメージのリストを表示します。
+ イメージを S3 バケットにアップロードします。
+ イメージ内で検出された項目を識別するイメージとラベルを表示します。
+ S3 バケット内のすべてのイメージのレポートを取得し、レポートの E メールを送信します。
ウェブページが REST サービスを呼び出します。サービスはリクエストを AWS に送信して、以下のアクションを実行します。  
+ S3 バケット内のイメージのリストを取得し、フィルタリングします。
+ Amazon S3 バケットに写真をアップロードします。
+ Amazon Rekognition を使用して個々の写真を分析し、写真で検出された項目を識別するラベルのリストを取得します。
+ S3 バケット内のすべての写真を分析し、Amazon SES を使用してレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/photo_analyzer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_python_3_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Python (Boto3)**  
 Amazon Rekognition を使用して、非同期検出ジョブを開始して、動画内の顔、オブジェクト、人を検出します。この例では、ジョブが完了し、Amazon Simple Queue Service (Amazon SQS) キューをトピックにサブスクライブしたときに、Amazon Simple Notification Service (Amazon SNS) トピックに通知するように Amazon Rekognition を設定します。キューがジョブに関するメッセージを受信すると、ジョブが取得され、結果が出力されます。  
 この例は GitHub で最もよく見られます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### 条件付きリクエストの実行
<a name="s3_Scenario_ConditionalRequests_python_3_topic"></a>

次のコード例は、Amazon S3 リクエストに前提条件を追加する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/conditional_requests#code-examples)での設定と実行の方法を確認してください。
Amazon S3 の条件付きリクエストを示すインタラクティブなシナリオを実行します。  

```
"""
Purpose

Shows how to use AWS SDK for Python (Boto3) to get started using conditional requests for
Amazon Simple Storage Service (Amazon S3).

"""

import logging
import random
import sys
import datetime

import boto3
from botocore.exceptions import ClientError

from s3_conditional_requests import S3ConditionalRequests

# Add relative path to include demo_tools in this code example without need for setup.
sys.path.append("../../../..")
import demo_tools.question as q  # noqa

# Constants
FILE_CONTENT = "This is a test file for S3 conditional requests."
RANDOM_SUFFIX = str(random.randint(100, 999))

logger = logging.getLogger(__name__)


class ConditionalRequestsScenario:
    """Runs a scenario that shows how to use S3 Conditional Requests."""

    def __init__(self, conditional_requests, s3_client):
        """
        :param conditional_requests: An object that wraps S3 conditional request actions.
        :param s3_client: A Boto3 S3 client for setup and cleanup operations.
        """
        self.conditional_requests = conditional_requests
        self.s3_client = s3_client

    def setup_scenario(self, source_bucket: str, dest_bucket: str, object_key: str):
        """
        Sets up the scenario by creating a source and destination bucket.
        Prompts the user to provide a bucket name prefix.

        :param source_bucket: The name of the source bucket.
        :param dest_bucket: The name of the destination bucket.
        :param object_key: The name of a test file to add to the source bucket.
        """

        # Create the buckets.
        try:
            self.s3_client.create_bucket(Bucket=source_bucket)
            self.s3_client.create_bucket(Bucket=dest_bucket)
            print(
                f"Created source bucket: {source_bucket} and destination bucket: {dest_bucket}"
            )
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            logger.error(f"Error creating buckets: {error_code}")
            raise

        # Upload test file into the source bucket.
        try:
            print(f"Uploading file {object_key} to bucket {source_bucket}")
            response = self.s3_client.put_object(
                Bucket=source_bucket, Key=object_key, Body=FILE_CONTENT
            )
            object_etag = response["ETag"]
            return object_etag

        except Exception as e:
            logger.error(
                f"Failed to upload file {object_key} to bucket {source_bucket}: {e}"
            )


    def cleanup_scenario(self, source_bucket: str, dest_bucket: str):
        """
        Cleans up the scenario by deleting the source and destination buckets.

        :param source_bucket: The name of the source bucket.
        :param dest_bucket: The name of the destination bucket.
        """
        self.cleanup_bucket(source_bucket)
        self.cleanup_bucket(dest_bucket)

    def cleanup_bucket(self, bucket_name: str):
        """
        Cleans up the bucket by deleting all objects and then the bucket itself.

        :param bucket_name: The name of the bucket.
        """
        try:
            # Get list of all objects in the bucket.
            list_response = self.s3_client.list_objects_v2(Bucket=bucket_name)
            objs = list_response.get("Contents", [])
            for obj in objs:
                key = obj["Key"]
                self.s3_client.delete_object(Bucket=bucket_name, Key=key)
            self.s3_client.delete_bucket(Bucket=bucket_name)
            print(f"Cleaned up bucket: {bucket_name}.")
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "NoSuchBucket":
                logger.info(f"Bucket {bucket_name} does not exist, skipping cleanup.")
            else:
                logger.error(f"Error deleting bucket: {error_code}")
                raise


    def display_buckets(self, source_bucket: str, dest_bucket: str):
        """
        Display a list of the objects in the test buckets.

        :param source_bucket: The name of the source bucket.
        :param dest_bucket: The name of the destination bucket.
        """
        self.list_bucket_contents(source_bucket)
        self.list_bucket_contents(dest_bucket)

    def list_bucket_contents(self, bucket_name):
        """
        Display a list of the objects in the bucket.

        :param bucket_name: The name of the bucket.
        """
        try:
            # Get list of all objects in the bucket.
            print(f"\t Items in bucket {bucket_name}")
            list_response = self.s3_client.list_objects_v2(Bucket=bucket_name)
            objs = list_response.get("Contents", [])
            if not objs:
                print("\t\tNo objects found.")
            for obj in objs:
                key = obj["Key"]
                print(f"\t\t object: {key} ETag {obj['ETag']}")
            return objs
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "NoSuchBucket":
                logger.info(f"Bucket {bucket_name} does not exist.")
            else:
                logger.error(f"Error listing bucket and objects: {error_code}")
                raise


    def display_menu(
        self, source_bucket: str, dest_bucket: str, object_key: str, etag: str
    ):
        """
        Displays the menu of conditional request options for the user.

        :param source_bucket: The name of the source bucket.
        :param dest_bucket: The name of the destination bucket.
        :param object_key: The key of the test object in the source bucket.
        :param etag: The etag of the test object in the source bucket.
        """

        actions = [
            "Print list of bucket items.",
            "Perform a conditional read.",
            "Perform a conditional copy.",
            "Perform a conditional write.",
            "Clean up and exit.",
        ]

        conditions = [
            "If-Match: using the object's ETag. This condition should succeed.",
            "If-None-Match: using the object's ETag. This condition should fail.",
            "If-Modified-Since: using yesterday's date. This condition should succeed.",
            "If-Unmodified-Since: using yesterday's date. This condition should fail.",
        ]

        condition_types = [
            "IfMatch",
            "IfNoneMatch",
            "IfModifiedSince",
            "IfUnmodifiedSince",
        ]
        copy_condition_types = [
            "CopySourceIfMatch",
            "CopySourceIfNoneMatch",
            "CopySourceIfModifiedSince",
            "CopySourceIfUnmodifiedSince",
        ]

        yesterday_date = datetime.datetime.utcnow() - datetime.timedelta(days=1)

        choice = 0
        while choice != 4:
            print("-" * 88)
            print("Choose an action to explore some example conditional requests.")
            choice = q.choose("Which action would you like to take? ", actions)
            if choice == 0:
                print("Listing the objects and buckets.")
                self.display_buckets(source_bucket, dest_bucket)
            elif choice == 1:
                print("Perform a conditional read.")
                condition_type = q.choose("Enter the condition type : ", conditions)
                if condition_type == 0 or condition_type == 1:
                    self.conditional_requests.get_object_conditional(
                        object_key, source_bucket, condition_types[condition_type], etag
                    )
                elif condition_type == 2 or condition_type == 3:
                    self.conditional_requests.get_object_conditional(
                        object_key,
                        source_bucket,
                        condition_types[condition_type],
                        yesterday_date,
                    )
            elif choice == 2:
                print("Perform a conditional copy.")
                condition_type = q.choose("Enter the condition type : ", conditions)
                dest_key = q.ask("Enter an object key: ", q.non_empty)
                if condition_type == 0 or condition_type == 1:
                    self.conditional_requests.copy_object_conditional(
                        object_key,
                        dest_key,
                        source_bucket,
                        dest_bucket,
                        copy_condition_types[condition_type],
                        etag,
                    )
                elif condition_type == 2 or condition_type == 3:
                    self.conditional_requests.copy_object_conditional(
                        object_key,
                        dest_key,
                        copy_condition_types[condition_type],
                        yesterday_date,
                    )
            elif choice == 3:
                print(
                    "Perform a conditional write using IfNoneMatch condition on the object key."
                )
                print("If the key is a duplicate, the write will fail.")
                object_key = q.ask("Enter an object key: ", q.non_empty)
                self.conditional_requests.put_object_conditional(
                    object_key, source_bucket, b"Conditional write example data."
                )
            elif choice == 4:
                print("Proceeding to cleanup.")


    def run_scenario(self):
        """
        Runs the interactive scenario.
        """
        print("-" * 88)
        print("Welcome to the Amazon S3 conditional requests example.")
        print("-" * 88)

        print(
            f"""\
        This example demonstrates the use of conditional requests for S3 operations.
        You can use conditional requests to add preconditions to S3 read requests to return or copy
        an object based on its Entity tag (ETag), or last modified date. 
        You can use a conditional write requests to prevent overwrites by ensuring 
        there is no existing object with the same key. 
        
        This example will allow you to perform conditional reads
        and writes that will succeed or fail based on your selected options.
        
        Sample buckets and a sample object will be created as part of the example.
        """
        )

        bucket_prefix = q.ask("Enter a bucket name prefix: ", q.non_empty)
        source_bucket_name = f"{bucket_prefix}-source-{RANDOM_SUFFIX}"
        dest_bucket_name = f"{bucket_prefix}-dest-{RANDOM_SUFFIX}"
        object_key = "test-upload-file.txt"

        try:
            etag = self.setup_scenario(source_bucket_name, dest_bucket_name, object_key)
            self.display_menu(source_bucket_name, dest_bucket_name, object_key, etag)
        finally:
            self.cleanup_scenario(source_bucket_name, dest_bucket_name)

        print("-" * 88)
        print("Thanks for watching.")
        print("-" * 88)


if __name__ == "__main__":
    scenario = ConditionalRequestsScenario(
        S3ConditionalRequests.from_client(), boto3.client("s3")
    )
    scenario.run_scenario()
```
条件付きリクエストオペレーションを定義するラッパークラス。  

```
import boto3
import logging

from botocore.exceptions import ClientError

# Configure logging
logger = logging.getLogger(__name__)


class S3ConditionalRequests:
    """Encapsulates S3 conditional request operations."""

    def __init__(self, s3_client):
        self.s3 = s3_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        s3_client = boto3.client("s3")
        return cls(s3_client)



    def get_object_conditional(
        self,
        object_key: str,
        source_bucket: str,
        condition_type: str,
        condition_value: str,
    ):
        """
        Retrieves an object from Amazon S3 with a conditional request.

        :param object_key: The key of the object to retrieve.
        :param source_bucket: The source bucket of the object.
        :param condition_type: The type of condition: 'IfMatch', 'IfNoneMatch', 'IfModifiedSince', 'IfUnmodifiedSince'.
        :param condition_value: The value to use for the condition.
        """
        try:
            response = self.s3.get_object(
                Bucket=source_bucket,
                Key=object_key,
                **{condition_type: condition_value},
            )
            sample_bytes = response["Body"].read(20)
            print(
                f"\tConditional read successful. Here are the first 20 bytes of the object:\n"
            )
            print(f"\t{sample_bytes}")
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "PreconditionFailed":
                print("\tConditional read failed: Precondition failed")
            elif error_code == "304":  # Not modified error code.
                print("\tConditional read failed: Object not modified")
            else:
                logger.error(f"Unexpected error: {error_code}")
                raise



    def put_object_conditional(self, object_key: str, source_bucket: str, data: bytes):
        """
        Uploads an object to Amazon S3 with a conditional request. Prevents overwrite
        using an IfNoneMatch condition for the object key.

        :param object_key: The key of the object to upload.
        :param source_bucket: The source bucket of the object.
        :param data: The data to upload.
        """
        try:
            self.s3.put_object(
                Bucket=source_bucket, Key=object_key, Body=data, IfNoneMatch="*"
            )
            print(
                f"\tConditional write successful for key {object_key} in bucket {source_bucket}."
            )
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "PreconditionFailed":
                print("\tConditional write failed: Precondition failed")
            else:
                logger.error(f"Unexpected error: {error_code}")
                raise


    def copy_object_conditional(
        self,
        source_key: str,
        dest_key: str,
        source_bucket: str,
        dest_bucket: str,
        condition_type: str,
        condition_value: str,
    ):
        """
        Copies an object from one Amazon S3 bucket to another with a conditional request.

        :param source_key: The key of the source object to copy.
        :param dest_key: The key of the destination object.
        :param source_bucket: The source bucket of the object.
        :param dest_bucket: The destination bucket of the object.
        :param condition_type: The type of condition to apply, e.g.
        'CopySourceIfMatch', 'CopySourceIfNoneMatch', 'CopySourceIfModifiedSince', 'CopySourceIfUnmodifiedSince'.
        :param condition_value: The value to use for the condition.
        """
        try:
            self.s3.copy_object(
                Bucket=dest_bucket,
                Key=dest_key,
                CopySource={"Bucket": source_bucket, "Key": source_key},
                **{condition_type: condition_value},
            )
            print(
                f"\tConditional copy successful for key {dest_key} in bucket {dest_bucket}."
            )
        except ClientError as e:
            error_code = e.response["Error"]["Code"]
            if error_code == "PreconditionFailed":
                print("\tConditional copy failed: Precondition failed")
            elif error_code == "304":  # Not modified error code.
                print("\tConditional copy failed: Object not modified")
            else:
                logger.error(f"Unexpected error: {error_code}")
                raise
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CopyObject)
  + [GetObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetObject)
  + [PutObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObject)

### バージョン管理されているオブジェクトを Lambda 関数でバッチで管理する
<a name="s3_Scenario_BatchObjectVersioning_python_3_topic"></a>

次のコード例は、バージョン管理されている S3 オブジェクトを Lambda 関数でバッチで管理する方法を示しています。

**SDK for Python (Boto3)**  
 AWS Lambda 関数を呼び出して処理を実行するジョブを作成して、Amazon Simple Storage Service (Amazon S3) バージョンのオブジェクトをバッチで操作する方法を示します。この例では、バージョン対応のバケットを作成し、Lewis Carroll の詩「*You Are Old, Father William*」からスタンザをアップロードし、Amazon S3 のバッチジョブを使用して、さまざまな方法で詩をひねります。  

**以下ではその方法を説明しています。**
+ バージョン管理されたオブジェクトを操作する Lambda 関数を作成します。
+ 更新するオブジェクトのマニフェストを作成します。
+ Lambda 関数を呼び出してオブジェクトを更新するバッチジョブを作成します。
+ Lambda 関数を削除します。
+ バージョン管理されているバケットを空にして削除します。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_versioning#batch-operation-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon S3

### 大きなファイルをアップロードまたはダウンロードする
<a name="s3_Scenario_UsingLargeFiles_python_3_topic"></a>

次のコード例は、Amazon S3 との間で大きなファイルをアップロードまたはダウンロードする方法を示しています。

詳細については、「[マルチパートアップロードを使用したオブジェクトのアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-upload-object.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/file_transfer#code-examples)での設定と実行の方法を確認してください。
使用可能な転送マネージャの設定を使用して、ファイルを転送する関数を作成します。コールバッククラスを使用して、ファイル転送中にコールバックの進行状況を書き込みます。  

```
import sys
import threading

import boto3
from boto3.s3.transfer import TransferConfig


MB = 1024 * 1024
s3 = boto3.resource("s3")


class TransferCallback:
    """
    Handle callbacks from the transfer manager.

    The transfer manager periodically calls the __call__ method throughout
    the upload and download process so that it can take action, such as
    displaying progress to the user and collecting data about the transfer.
    """

    def __init__(self, target_size):
        self._target_size = target_size
        self._total_transferred = 0
        self._lock = threading.Lock()
        self.thread_info = {}

    def __call__(self, bytes_transferred):
        """
        The callback method that is called by the transfer manager.

        Display progress during file transfer and collect per-thread transfer
        data. This method can be called by multiple threads, so shared instance
        data is protected by a thread lock.
        """
        thread = threading.current_thread()
        with self._lock:
            self._total_transferred += bytes_transferred
            if thread.ident not in self.thread_info.keys():
                self.thread_info[thread.ident] = bytes_transferred
            else:
                self.thread_info[thread.ident] += bytes_transferred

            target = self._target_size * MB
            sys.stdout.write(
                f"\r{self._total_transferred} of {target} transferred "
                f"({(self._total_transferred / target) * 100:.2f}%)."
            )
            sys.stdout.flush()


def upload_with_default_configuration(
    local_file_path, bucket_name, object_key, file_size_mb
):
    """
    Upload a file from a local folder to an Amazon S3 bucket, using the default
    configuration.
    """
    transfer_callback = TransferCallback(file_size_mb)
    s3.Bucket(bucket_name).upload_file(
        local_file_path, object_key, Callback=transfer_callback
    )
    return transfer_callback.thread_info


def upload_with_chunksize_and_meta(
    local_file_path, bucket_name, object_key, file_size_mb, metadata=None
):
    """
    Upload a file from a local folder to an Amazon S3 bucket, setting a
    multipart chunk size and adding metadata to the Amazon S3 object.

    The multipart chunk size controls the size of the chunks of data that are
    sent in the request. A smaller chunk size typically results in the transfer
    manager using more threads for the upload.

    The metadata is a set of key-value pairs that are stored with the object
    in Amazon S3.
    """
    transfer_callback = TransferCallback(file_size_mb)

    config = TransferConfig(multipart_chunksize=1 * MB)
    extra_args = {"Metadata": metadata} if metadata else None
    s3.Bucket(bucket_name).upload_file(
        local_file_path,
        object_key,
        Config=config,
        ExtraArgs=extra_args,
        Callback=transfer_callback,
    )
    return transfer_callback.thread_info


def upload_with_high_threshold(local_file_path, bucket_name, object_key, file_size_mb):
    """
    Upload a file from a local folder to an Amazon S3 bucket, setting a
    multipart threshold larger than the size of the file.

    Setting a multipart threshold larger than the size of the file results
    in the transfer manager sending the file as a standard upload instead of
    a multipart upload.
    """
    transfer_callback = TransferCallback(file_size_mb)
    config = TransferConfig(multipart_threshold=file_size_mb * 2 * MB)
    s3.Bucket(bucket_name).upload_file(
        local_file_path, object_key, Config=config, Callback=transfer_callback
    )
    return transfer_callback.thread_info


def upload_with_sse(
    local_file_path, bucket_name, object_key, file_size_mb, sse_key=None
):
    """
    Upload a file from a local folder to an Amazon S3 bucket, adding server-side
    encryption with customer-provided encryption keys to the object.

    When this kind of encryption is specified, Amazon S3 encrypts the object
    at rest and allows downloads only when the expected encryption key is
    provided in the download request.
    """
    transfer_callback = TransferCallback(file_size_mb)
    if sse_key:
        extra_args = {"SSECustomerAlgorithm": "AES256", "SSECustomerKey": sse_key}
    else:
        extra_args = None
    s3.Bucket(bucket_name).upload_file(
        local_file_path, object_key, ExtraArgs=extra_args, Callback=transfer_callback
    )
    return transfer_callback.thread_info


def download_with_default_configuration(
    bucket_name, object_key, download_file_path, file_size_mb
):
    """
    Download a file from an Amazon S3 bucket to a local folder, using the
    default configuration.
    """
    transfer_callback = TransferCallback(file_size_mb)
    s3.Bucket(bucket_name).Object(object_key).download_file(
        download_file_path, Callback=transfer_callback
    )
    return transfer_callback.thread_info


def download_with_single_thread(
    bucket_name, object_key, download_file_path, file_size_mb
):
    """
    Download a file from an Amazon S3 bucket to a local folder, using a
    single thread.
    """
    transfer_callback = TransferCallback(file_size_mb)
    config = TransferConfig(use_threads=False)
    s3.Bucket(bucket_name).Object(object_key).download_file(
        download_file_path, Config=config, Callback=transfer_callback
    )
    return transfer_callback.thread_info


def download_with_high_threshold(
    bucket_name, object_key, download_file_path, file_size_mb
):
    """
    Download a file from an Amazon S3 bucket to a local folder, setting a
    multipart threshold larger than the size of the file.

    Setting a multipart threshold larger than the size of the file results
    in the transfer manager sending the file as a standard download instead
    of a multipart download.
    """
    transfer_callback = TransferCallback(file_size_mb)
    config = TransferConfig(multipart_threshold=file_size_mb * 2 * MB)
    s3.Bucket(bucket_name).Object(object_key).download_file(
        download_file_path, Config=config, Callback=transfer_callback
    )
    return transfer_callback.thread_info


def download_with_sse(
    bucket_name, object_key, download_file_path, file_size_mb, sse_key
):
    """
    Download a file from an Amazon S3 bucket to a local folder, adding a
    customer-provided encryption key to the request.

    When this kind of encryption is specified, Amazon S3 encrypts the object
    at rest and allows downloads only when the expected encryption key is
    provided in the download request.
    """
    transfer_callback = TransferCallback(file_size_mb)

    if sse_key:
        extra_args = {"SSECustomerAlgorithm": "AES256", "SSECustomerKey": sse_key}
    else:
        extra_args = None
    s3.Bucket(bucket_name).Object(object_key).download_file(
        download_file_path, ExtraArgs=extra_args, Callback=transfer_callback
    )
    return transfer_callback.thread_info
```
転送マネージャの機能とレポート結果のデモンストレーションを行います。  

```
import hashlib
import os
import platform
import shutil
import time

import boto3
from boto3.s3.transfer import TransferConfig
from botocore.exceptions import ClientError
from botocore.exceptions import ParamValidationError
from botocore.exceptions import NoCredentialsError

import file_transfer

MB = 1024 * 1024
# These configuration attributes affect both uploads and downloads.
CONFIG_ATTRS = (
    "multipart_threshold",
    "multipart_chunksize",
    "max_concurrency",
    "use_threads",
)
# These configuration attributes affect only downloads.
DOWNLOAD_CONFIG_ATTRS = ("max_io_queue", "io_chunksize", "num_download_attempts")


class TransferDemoManager:
    """
    Manages the demonstration. Collects user input from a command line, reports
    transfer results, maintains a list of artifacts created during the
    demonstration, and cleans them up after the demonstration is completed.
    """

    def __init__(self):
        self._s3 = boto3.resource("s3")
        self._chore_list = []
        self._create_file_cmd = None
        self._size_multiplier = 0
        self.file_size_mb = 30
        self.demo_folder = None
        self.demo_bucket = None
        self._setup_platform_specific()
        self._terminal_width = shutil.get_terminal_size(fallback=(80, 80))[0]

    def collect_user_info(self):
        """
        Collect local folder and Amazon S3 bucket name from the user. These
        locations are used to store files during the demonstration.
        """
        while not self.demo_folder:
            self.demo_folder = input(
                "Which file folder do you want to use to store " "demonstration files? "
            )
            if not os.path.isdir(self.demo_folder):
                print(f"{self.demo_folder} isn't a folder!")
                self.demo_folder = None

        while not self.demo_bucket:
            self.demo_bucket = input(
                "Which Amazon S3 bucket do you want to use to store "
                "demonstration files? "
            )
            try:
                self._s3.meta.client.head_bucket(Bucket=self.demo_bucket)
            except ParamValidationError as err:
                print(err)
                self.demo_bucket = None
            except ClientError as err:
                print(err)
                print(
                    f"Either {self.demo_bucket} doesn't exist or you don't "
                    f"have access to it."
                )
                self.demo_bucket = None

    def demo(
        self, question, upload_func, download_func, upload_args=None, download_args=None
    ):
        """Run a demonstration.

        Ask the user if they want to run this specific demonstration.
        If they say yes, create a file on the local path, upload it
        using the specified upload function, then download it using the
        specified download function.
        """
        if download_args is None:
            download_args = {}
        if upload_args is None:
            upload_args = {}
        question = question.format(self.file_size_mb)
        answer = input(f"{question} (y/n)")
        if answer.lower() == "y":
            local_file_path, object_key, download_file_path = self._create_demo_file()

            file_transfer.TransferConfig = self._config_wrapper(
                TransferConfig, CONFIG_ATTRS
            )
            self._report_transfer_params(
                "Uploading", local_file_path, object_key, **upload_args
            )
            start_time = time.perf_counter()
            thread_info = upload_func(
                local_file_path,
                self.demo_bucket,
                object_key,
                self.file_size_mb,
                **upload_args,
            )
            end_time = time.perf_counter()
            self._report_transfer_result(thread_info, end_time - start_time)

            file_transfer.TransferConfig = self._config_wrapper(
                TransferConfig, CONFIG_ATTRS + DOWNLOAD_CONFIG_ATTRS
            )
            self._report_transfer_params(
                "Downloading", object_key, download_file_path, **download_args
            )
            start_time = time.perf_counter()
            thread_info = download_func(
                self.demo_bucket,
                object_key,
                download_file_path,
                self.file_size_mb,
                **download_args,
            )
            end_time = time.perf_counter()
            self._report_transfer_result(thread_info, end_time - start_time)

    def last_name_set(self):
        """Get the name set used for the last demo."""
        return self._chore_list[-1]

    def cleanup(self):
        """
        Remove files from the demo folder, and uploaded objects from the
        Amazon S3 bucket.
        """
        print("-" * self._terminal_width)
        for local_file_path, s3_object_key, downloaded_file_path in self._chore_list:
            print(f"Removing {local_file_path}")
            try:
                os.remove(local_file_path)
            except FileNotFoundError as err:
                print(err)

            print(f"Removing {downloaded_file_path}")
            try:
                os.remove(downloaded_file_path)
            except FileNotFoundError as err:
                print(err)

            if self.demo_bucket:
                print(f"Removing {self.demo_bucket}:{s3_object_key}")
                try:
                    self._s3.Bucket(self.demo_bucket).Object(s3_object_key).delete()
                except ClientError as err:
                    print(err)

    def _setup_platform_specific(self):
        """Set up platform-specific command used to create a large file."""
        if platform.system() == "Windows":
            self._create_file_cmd = "fsutil file createnew {} {}"
            self._size_multiplier = MB
        elif platform.system() == "Linux" or platform.system() == "Darwin":
            self._create_file_cmd = f"dd if=/dev/urandom of={{}} " f"bs={MB} count={{}}"
            self._size_multiplier = 1
        else:
            raise EnvironmentError(
                f"Demo of platform {platform.system()} isn't supported."
            )

    def _create_demo_file(self):
        """
        Create a file in the demo folder specified by the user. Store the local
        path, object name, and download path for later cleanup.

        Only the local file is created by this method. The Amazon S3 object and
        download file are created later during the demonstration.

        Returns:
        A tuple that contains the local file path, object name, and download
        file path.
        """
        file_name_template = "TestFile{}-{}.demo"
        local_suffix = "local"
        object_suffix = "s3object"
        download_suffix = "downloaded"
        file_tag = len(self._chore_list) + 1

        local_file_path = os.path.join(
            self.demo_folder, file_name_template.format(file_tag, local_suffix)
        )

        s3_object_key = file_name_template.format(file_tag, object_suffix)

        downloaded_file_path = os.path.join(
            self.demo_folder, file_name_template.format(file_tag, download_suffix)
        )

        filled_cmd = self._create_file_cmd.format(
            local_file_path, self.file_size_mb * self._size_multiplier
        )

        print(
            f"Creating file of size {self.file_size_mb} MB "
            f"in {self.demo_folder} by running:"
        )
        print(f"{'':4}{filled_cmd}")
        os.system(filled_cmd)

        chore = (local_file_path, s3_object_key, downloaded_file_path)
        self._chore_list.append(chore)
        return chore

    def _report_transfer_params(self, verb, source_name, dest_name, **kwargs):
        """Report configuration and extra arguments used for a file transfer."""
        print("-" * self._terminal_width)
        print(f"{verb} {source_name} ({self.file_size_mb} MB) to {dest_name}")
        if kwargs:
            print("With extra args:")
            for arg, value in kwargs.items():
                print(f'{"":4}{arg:<20}: {value}')

    @staticmethod
    def ask_user(question):
        """
        Ask the user a yes or no question.

        Returns:
        True when the user answers 'y' or 'Y'; otherwise, False.
        """
        answer = input(f"{question} (y/n) ")
        return answer.lower() == "y"

    @staticmethod
    def _config_wrapper(func, config_attrs):
        def wrapper(*args, **kwargs):
            config = func(*args, **kwargs)
            print("With configuration:")
            for attr in config_attrs:
                print(f'{"":4}{attr:<20}: {getattr(config, attr)}')
            return config

        return wrapper

    @staticmethod
    def _report_transfer_result(thread_info, elapsed):
        """Report the result of a transfer, including per-thread data."""
        print(f"\nUsed {len(thread_info)} threads.")
        for ident, byte_count in thread_info.items():
            print(f"{'':4}Thread {ident} copied {byte_count} bytes.")
        print(f"Your transfer took {elapsed:.2f} seconds.")


def main():
    """
    Run the demonstration script for s3_file_transfer.
    """
    demo_manager = TransferDemoManager()
    demo_manager.collect_user_info()

    # Upload and download with default configuration. Because the file is 30 MB
    # and the default multipart_threshold is 8 MB, both upload and download are
    # multipart transfers.
    demo_manager.demo(
        "Do you want to upload and download a {} MB file "
        "using the default configuration?",
        file_transfer.upload_with_default_configuration,
        file_transfer.download_with_default_configuration,
    )

    # Upload and download with multipart_threshold set higher than the size of
    # the file. This causes the transfer manager to use standard transfers
    # instead of multipart transfers.
    demo_manager.demo(
        "Do you want to upload and download a {} MB file "
        "as a standard (not multipart) transfer?",
        file_transfer.upload_with_high_threshold,
        file_transfer.download_with_high_threshold,
    )

    # Upload with specific chunk size and additional metadata.
    # Download with a single thread.
    demo_manager.demo(
        "Do you want to upload a {} MB file with a smaller chunk size and "
        "then download the same file using a single thread?",
        file_transfer.upload_with_chunksize_and_meta,
        file_transfer.download_with_single_thread,
        upload_args={
            "metadata": {
                "upload_type": "chunky",
                "favorite_color": "aqua",
                "size": "medium",
            }
        },
    )

    # Upload using server-side encryption with customer-provided
    # encryption keys.
    # Generate a 256-bit key from a passphrase.
    sse_key = hashlib.sha256("demo_passphrase".encode("utf-8")).digest()
    demo_manager.demo(
        "Do you want to upload and download a {} MB file using "
        "server-side encryption?",
        file_transfer.upload_with_sse,
        file_transfer.download_with_sse,
        upload_args={"sse_key": sse_key},
        download_args={"sse_key": sse_key},
    )

    # Download without specifying an encryption key to show that the
    # encryption key must be included to download an encrypted object.
    if demo_manager.ask_user(
        "Do you want to try to download the encrypted "
        "object without sending the required key?"
    ):
        try:
            _, object_key, download_file_path = demo_manager.last_name_set()
            file_transfer.download_with_default_configuration(
                demo_manager.demo_bucket,
                object_key,
                download_file_path,
                demo_manager.file_size_mb,
            )
        except ClientError as err:
            print(
                "Got expected error when trying to download an encrypted "
                "object without specifying encryption info:"
            )
            print(f"{'':4}{err}")

    # Remove all created and downloaded files, remove all objects from
    # S3 storage.
    if demo_manager.ask_user(
        "Demonstration complete. Do you want to remove local files " "and S3 objects?"
    ):
        demo_manager.cleanup()


if __name__ == "__main__":
    try:
        main()
    except NoCredentialsError as error:
        print(error)
        print(
            "To run this example, you must have valid credentials in "
            "a shared credential file or set in environment variables."
        )
```

### バージョン管理されたオブジェクトを操作する
<a name="s3_Scenario_ObjectVersioningUsage_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バージョニングされた S3 バケットを作成します。
+ オブジェクトのすべてのバージョンを取得します。
+ オブジェクトを以前のバージョンにロールバックします。
+ バージョニングされたオブジェクトを削除して復元します。
+ オブジェクトのバージョンを完全に削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/s3_versioning#code-examples)での設定と実行の方法を確認してください。
S3 アクションをラップする関数を作成します。  

```
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



def rollback_object(bucket, object_key, version_id):
    """
    Rolls back an object to an earlier version by deleting all versions that
    occurred after the specified rollback version.

    Usage is shown in the usage_demo_single_object function at the end of this module.

    :param bucket: The bucket that holds the object to roll back.
    :param object_key: The object to roll back.
    :param version_id: The version ID to roll back to.
    """
    # Versions must be sorted by last_modified date because delete markers are
    # at the end of the list even when they are interspersed in time.
    versions = sorted(
        bucket.object_versions.filter(Prefix=object_key),
        key=attrgetter("last_modified"),
        reverse=True,
    )

    logger.debug(
        "Got versions:\n%s",
        "\n".join(
            [
                f"\t{version.version_id}, last modified {version.last_modified}"
                for version in versions
            ]
        ),
    )

    if version_id in [ver.version_id for ver in versions]:
        print(f"Rolling back to version {version_id}")
        for version in versions:
            if version.version_id != version_id:
                version.delete()
                print(f"Deleted version {version.version_id}")
            else:
                break

        print(f"Active version is now {bucket.Object(object_key).version_id}")
    else:
        raise KeyError(
            f"{version_id} was not found in the list of versions for " f"{object_key}."
        )



def revive_object(bucket, object_key):
    """
    Revives a versioned object that was deleted by removing the object's active
    delete marker.
    A versioned object presents as deleted when its latest version is a delete marker.
    By removing the delete marker, we make the previous version the latest version
    and the object then presents as *not* deleted.

    Usage is shown in the usage_demo_single_object function at the end of this module.

    :param bucket: The bucket that contains the object.
    :param object_key: The object to revive.
    """
    # Get the latest version for the object.
    response = s3.meta.client.list_object_versions(
        Bucket=bucket.name, Prefix=object_key, MaxKeys=1
    )

    if "DeleteMarkers" in response:
        latest_version = response["DeleteMarkers"][0]
        if latest_version["IsLatest"]:
            logger.info(
                "Object %s was indeed deleted on %s. Let's revive it.",
                object_key,
                latest_version["LastModified"],
            )
            obj = bucket.Object(object_key)
            obj.Version(latest_version["VersionId"]).delete()
            logger.info(
                "Revived %s, active version is now %s  with body '%s'",
                object_key,
                obj.version_id,
                obj.get()["Body"].read(),
            )
        else:
            logger.warning(
                "Delete marker is not the latest version for %s!", object_key
            )
    elif "Versions" in response:
        logger.warning("Got an active version for %s, nothing to do.", object_key)
    else:
        logger.error("Couldn't get any version info for %s.", object_key)



def permanently_delete_object(bucket, object_key):
    """
    Permanently deletes a versioned object by deleting all of its versions.

    Usage is shown in the usage_demo_single_object function at the end of this module.

    :param bucket: The bucket that contains the object.
    :param object_key: The object to delete.
    """
    try:
        bucket.object_versions.filter(Prefix=object_key).delete()
        logger.info("Permanently deleted all versions of object %s.", object_key)
    except ClientError:
        logger.exception("Couldn't delete all versions of %s.", object_key)
        raise
```
詩のスタンザをバージョニングされたオブジェクトにアップロードし、一連のアクションを実行します。  

```
def usage_demo_single_object(obj_prefix="demo-versioning/"):
    """
    Demonstrates usage of versioned object functions. This demo uploads a stanza
    of a poem and performs a series of revisions, deletions, and revivals on it.

    :param obj_prefix: The prefix to assign to objects created by this demo.
    """
    with open("father_william.txt") as file:
        stanzas = file.read().split("\n\n")

    width = get_terminal_size((80, 20))[0]
    print("-" * width)
    print("Welcome to the usage demonstration of Amazon S3 versioning.")
    print(
        "This demonstration uploads a single stanza of a poem to an Amazon "
        "S3 bucket and then applies various revisions to it."
    )
    print("-" * width)
    print("Creating a version-enabled bucket for the demo...")
    bucket = create_versioned_bucket("bucket-" + str(uuid.uuid1()), obj_prefix)

    print("\nThe initial version of our stanza:")
    print(stanzas[0])

    # Add the first stanza and revise it a few times.
    print("\nApplying some revisions to the stanza...")
    obj_stanza_1 = bucket.Object(f"{obj_prefix}stanza-1")
    obj_stanza_1.put(Body=bytes(stanzas[0], "utf-8"))
    obj_stanza_1.put(Body=bytes(stanzas[0].upper(), "utf-8"))
    obj_stanza_1.put(Body=bytes(stanzas[0].lower(), "utf-8"))
    obj_stanza_1.put(Body=bytes(stanzas[0][::-1], "utf-8"))
    print(
        "The latest version of the stanza is now:",
        obj_stanza_1.get()["Body"].read().decode("utf-8"),
        sep="\n",
    )

    # Versions are returned in order, most recent first.
    obj_stanza_1_versions = bucket.object_versions.filter(Prefix=obj_stanza_1.key)
    print(
        "The version data of the stanza revisions:",
        *[
            f"    {version.version_id}, last modified {version.last_modified}"
            for version in obj_stanza_1_versions
        ],
        sep="\n",
    )

    # Rollback two versions.
    print("\nRolling back two versions...")
    rollback_object(bucket, obj_stanza_1.key, list(obj_stanza_1_versions)[2].version_id)
    print(
        "The latest version of the stanza:",
        obj_stanza_1.get()["Body"].read().decode("utf-8"),
        sep="\n",
    )

    # Delete the stanza
    print("\nDeleting the stanza...")
    obj_stanza_1.delete()
    try:
        obj_stanza_1.get()
    except ClientError as error:
        if error.response["Error"]["Code"] == "NoSuchKey":
            print("The stanza is now deleted (as expected).")
        else:
            raise

    # Revive the stanza
    print("\nRestoring the stanza...")
    revive_object(bucket, obj_stanza_1.key)
    print(
        "The stanza is restored! The latest version is again:",
        obj_stanza_1.get()["Body"].read().decode("utf-8"),
        sep="\n",
    )

    # Permanently delete all versions of the object. This cannot be undone!
    print("\nPermanently deleting all versions of the stanza...")
    permanently_delete_object(bucket, obj_stanza_1.key)
    obj_stanza_1_versions = bucket.object_versions.filter(Prefix=obj_stanza_1.key)
    if len(list(obj_stanza_1_versions)) == 0:
        print("The stanza has been permanently deleted and now has no versions.")
    else:
        print("Something went wrong. The stanza still exists!")

    print(f"\nRemoving {bucket.name}...")
    bucket.delete()
    print(f"{bucket.name} deleted.")
    print("Demo done!")
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CreateBucket)
  + [DeleteObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteObject)
  + [ListObjectVersions](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/ListObjectVersions)
  + [PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutBucketLifecycleConfiguration)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_python_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Python を使用して Lambda で S3 イベントを消費します。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import json
import urllib.parse
import boto3

print('Loading function')

s3 = boto3.client('s3')


def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    # Get the object from the event and show its content type
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        print("CONTENT TYPE: " + response['ContentType'])
        return response['ContentType']
    except Exception as e:
        print(e)
        print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        raise e
```

# SDK for Python (Boto3) を使用した Amazon S3 Control の例
<a name="python_3_s3-control_code_examples"></a>

次のコード例は、Amazon S3 Control AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3 Control
<a name="s3-control_Hello_python_3_topic"></a>

次のコード例は、Amazon S3 Control の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def list_jobs(self, account_id: str) -> None:
        """
        List all batch jobs for the account.

        Args:
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.list_jobs(
                AccountId=account_id,
                JobStatuses=['Active', 'Complete', 'Cancelled', 'Failed', 'New', 'Paused', 'Pausing', 'Preparing', 'Ready', 'Suspended']
            )
            jobs = response.get('Jobs', [])
            for job in jobs:
                print(f"The job id is {job['JobId']}")
                print(f"The job priority is {job['Priority']}")
        except ClientError as e:
            print(f"Error listing jobs: {e}")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[ListJobs](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/ListJobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3-control_Basics_python_3_topic"></a>

次のコード例は、Amazon S3 Control のコアオペレーションを学ぶ方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。
S3 バッチの基本シナリオについて説明します。  

```
class S3BatchWrapper:
    """Wrapper class for managing S3 Batch Operations."""

    def __init__(self, s3_client: Any, s3control_client: Any, sts_client: Any) -> None:
        """
        Initializes the S3BatchWrapper with AWS service clients.
        
        :param s3_client: A Boto3 Amazon S3 client. This client provides low-level
                         access to AWS S3 services.
        :param s3control_client: A Boto3 Amazon S3 Control client. This client provides
                               low-level access to AWS S3 Control services.
        :param sts_client: A Boto3 AWS STS client. This client provides low-level
                          access to AWS STS services.
        """
        self.s3_client = s3_client
        self.s3control_client = s3control_client
        self.sts_client = sts_client
        # Get region from the client for bucket creation logic
        self.region_name = self.s3_client.meta.region_name

    def get_account_id(self) -> str:
        """
        Get AWS account ID.

        Returns:
            str: AWS account ID
        """
        return self.sts_client.get_caller_identity()["Account"]

    def create_bucket(self, bucket_name: str) -> None:
        """
        Create an S3 bucket.

        Args:
            bucket_name (str): Name of the bucket to create

        Raises:
            ClientError: If bucket creation fails
        """
        try:
            if self.region_name and self.region_name != 'us-east-1':
                self.s3_client.create_bucket(
                    Bucket=bucket_name,
                    CreateBucketConfiguration={
                        'LocationConstraint': self.region_name
                    }
                )
            else:
                self.s3_client.create_bucket(Bucket=bucket_name)
            print(f"Created bucket: {bucket_name}")
        except ClientError as e:
            print(f"Error creating bucket: {e}")
            raise

    def upload_files_to_bucket(self, bucket_name: str, file_names: List[str]) -> str:
        """
        Upload files to S3 bucket including manifest file.

        Args:
            bucket_name (str): Target bucket name
            file_names (list): List of file names to upload

        Returns:
            str: ETag of the manifest file

        Raises:
            ClientError: If file upload fails
        """
        try:
            for file_name in file_names:
                if file_name != "job-manifest.csv":
                    content = f"Content for {file_name}"
                    self.s3_client.put_object(
                        Bucket=bucket_name,
                        Key=file_name,
                        Body=content.encode('utf-8')
                    )
                    print(f"Uploaded {file_name} to {bucket_name}")

            manifest_content = ""
            for file_name in file_names:
                if file_name != "job-manifest.csv":
                    manifest_content += f"{bucket_name},{file_name}\n"

            manifest_response = self.s3_client.put_object(
                Bucket=bucket_name,
                Key="job-manifest.csv",
                Body=manifest_content.encode('utf-8')
            )
            print(f"Uploaded manifest file to {bucket_name}")
            print(f"Manifest content:\n{manifest_content}")
            return manifest_response['ETag'].strip('"')

        except ClientError as e:
            print(f"Error uploading files: {e}")
            raise

    def create_s3_batch_job(self, account_id: str, role_arn: str, manifest_location: str,
                           report_bucket_name: str) -> str:
        """
        Create an S3 batch operation job.

        Args:
            account_id (str): AWS account ID
            role_arn (str): IAM role ARN for batch operations
            manifest_location (str): Location of the manifest file
            report_bucket_name (str): Bucket for job reports

        Returns:
            str: Job ID

        Raises:
            ClientError: If job creation fails
        """
        try:
            bucket_name = manifest_location.split(':::')[1].split('/')[0]
            manifest_key = 'job-manifest.csv'
            manifest_obj = self.s3_client.head_object(
                Bucket=bucket_name,
                Key=manifest_key
            )
            etag = manifest_obj['ETag'].strip('"')
            
            response = self.s3control_client.create_job(
                AccountId=account_id,
                Operation={
                    'S3PutObjectTagging': {
                        'TagSet': [
                            {
                                'Key': 'BatchTag',
                                'Value': 'BatchValue'
                            },
                        ]
                    }
                },
                Report={
                    'Bucket': report_bucket_name,
                    'Format': 'Report_CSV_20180820',
                    'Enabled': True,
                    'Prefix': 'batch-op-reports',
                    'ReportScope': 'AllTasks'
                },
                Manifest={
                    'Spec': {
                        'Format': 'S3BatchOperations_CSV_20180820',
                        'Fields': ['Bucket', 'Key']
                    },
                    'Location': {
                        'ObjectArn': manifest_location,
                        'ETag': etag
                    }
                },
                Priority=10,
                RoleArn=role_arn,
                Description='Batch job for tagging objects',
                ConfirmationRequired=True
            )
            job_id = response['JobId']
            print(f"The Job id is {job_id}")
            return job_id
        except ClientError as e:
            print(f"Error creating batch job: {e}")
            if 'Message' in str(e):
                print(f"Detailed error message: {e.response['Message']}")
            raise

    def check_job_failure_reasons(self, job_id: str, account_id: str) -> List[Dict[str, Any]]:
        """
        Check for any failure reasons of a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID

        Returns:
            list: List of failure reasons

        Raises:
            ClientError: If checking job failure reasons fails
        """
        try:
            response = self.s3control_client.describe_job(
                AccountId=account_id,
                JobId=job_id
            )
            if 'FailureReasons' in response['Job']:
                for reason in response['Job']['FailureReasons']:
                    print(f"- {reason}")
            return response['Job'].get('FailureReasons', [])
        except ClientError as e:
            print(f"Error checking job failure reasons: {e}")
            raise

    def wait_for_job_ready(self, job_id: str, account_id: str, desired_status: str = 'Ready') -> bool:
        """
        Wait for a job to reach the desired status.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
            desired_status (str): Target status to wait for

        Returns:
            bool: True if desired status is reached, False otherwise

        Raises:
            ClientError: If checking job status fails
        """
        print(f"Waiting for job to become {desired_status}...")
        max_attempts = 60
        attempt = 0
        while attempt < max_attempts:
            try:
                response = self.s3control_client.describe_job(
                    AccountId=account_id,
                    JobId=job_id
                )
                current_status = response['Job']['Status']
                print(f"Current job status: {current_status}")
                if current_status == desired_status:
                    return True
                if current_status == 'Suspended':
                    print("Job is in Suspended state, can proceed with activation")
                    return True
                if current_status in ['Active', 'Failed', 'Cancelled', 'Complete']:
                    print(f"Job is in {current_status} state, cannot reach {desired_status} status")
                    if 'FailureReasons' in response['Job']:
                        print("Failure reasons:")
                        for reason in response['Job']['FailureReasons']:
                            print(f"- {reason}")
                    return False

                time.sleep(20)
                attempt += 1
            except ClientError as e:
                print(f"Error checking job status: {e}")
                raise
        print(f"Timeout waiting for job to become {desired_status}")
        return False

    def update_job_priority(self, job_id: str, account_id: str) -> None:
        """
        Update the priority of a batch job and start it.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.describe_job(
                AccountId=account_id,
                JobId=job_id
            )
            current_status = response['Job']['Status']
            print(f"Current job status: {current_status}")
            
            if current_status in ['Ready', 'Suspended']:
                self.s3control_client.update_job_priority(
                    AccountId=account_id,
                    JobId=job_id,
                    Priority=60
                )
                print("The job priority was updated")
                
                try:
                    self.s3control_client.update_job_status(
                        AccountId=account_id,
                        JobId=job_id,
                        RequestedJobStatus='Ready'
                    )
                    print("Job activated successfully")
                except ClientError as activation_error:
                    print(f"Note: Could not activate job automatically: {activation_error}")
                    print("Job priority was updated successfully. Job may need manual activation in the console.")
            elif current_status in ['Active', 'Completing', 'Complete']:
                print(f"Job is in '{current_status}' state - priority cannot be updated")
                if current_status == 'Completing':
                    print("Job is finishing up and will complete soon.")
                elif current_status == 'Complete':
                    print("Job has already completed successfully.")
                else:
                    print("Job is currently running.")
            else:
                print(f"Job is in '{current_status}' state - priority update not allowed")
                
        except ClientError as e:
            print(f"Error updating job priority: {e}")
            print("Continuing with the scenario...")
            return

    def cancel_job(self, job_id: str, account_id: str) -> None:
        """
        Cancel an S3 batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.describe_job(
                AccountId=account_id,
                JobId=job_id
            )
            current_status = response['Job']['Status']
            print(f"Current job status: {current_status}")

            if current_status in ['Ready', 'Suspended', 'Active']:
                self.s3control_client.update_job_status(
                    AccountId=account_id,
                    JobId=job_id,
                    RequestedJobStatus='Cancelled'
                )
                print(f"Job {job_id} was successfully canceled.")
            elif current_status in ['Completing', 'Complete']:
                print(f"Job is in '{current_status}' state - cannot be cancelled")
                if current_status == 'Completing':
                    print("Job is finishing up and will complete soon.")
                elif current_status == 'Complete':
                    print("Job has already completed successfully.")
            else:
                print(f"Job is in '{current_status}' state - cancel not allowed")
        except ClientError as e:
            print(f"Error canceling job: {e}")
            raise

    def describe_job_details(self, job_id: str, account_id: str) -> None:
        """
        Describe detailed information about a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.describe_job(
                AccountId=account_id,
                JobId=job_id
            )
            job = response['Job']
            print(f"Job ID: {job['JobId']}")
            print(f"Description: {job.get('Description', 'N/A')}")
            print(f"Status: {job['Status']}")
            print(f"Role ARN: {job['RoleArn']}")
            print(f"Priority: {job['Priority']}")
            if 'ProgressSummary' in job:
                progress = job['ProgressSummary']
                print(f"Progress Summary: Total={progress.get('TotalNumberOfTasks', 0)}, "
                      f"Succeeded={progress.get('NumberOfTasksSucceeded', 0)}, "
                      f"Failed={progress.get('NumberOfTasksFailed', 0)}")
        except ClientError as e:
            print(f"Error describing job: {e}")
            raise
    
    def get_job_tags(self, job_id: str, account_id: str) -> None:
        """
        Get tags associated with a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.get_job_tagging(
                AccountId=account_id,
                JobId=job_id
            )
            tags = response.get('Tags', [])
            if tags:
                print(f"Tags for job {job_id}:")
                for tag in tags:
                    print(f"  {tag['Key']}: {tag['Value']}")
            else:
                print(f"No tags found for job ID: {job_id}")
        except ClientError as e:
            print(f"Error getting job tags: {e}")
            raise
    
    def put_job_tags(self, job_id: str, account_id: str) -> None:
        """
        Add tags to a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            self.s3control_client.put_job_tagging(
                AccountId=account_id,
                JobId=job_id,
                Tags=[
                    {'Key': 'Environment', 'Value': 'Development'},
                    {'Key': 'Team', 'Value': 'DataProcessing'}
                ]
            )
            print(f"Additional tags were added to job {job_id}")
        except ClientError as e:
            print(f"Error adding job tags: {e}")
            raise
    
    def list_jobs(self, account_id: str) -> None:
        """
        List all batch jobs for the account.

        Args:
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.list_jobs(
                AccountId=account_id,
                JobStatuses=['Active', 'Complete', 'Cancelled', 'Failed', 'New', 'Paused', 'Pausing', 'Preparing', 'Ready', 'Suspended']
            )
            jobs = response.get('Jobs', [])
            for job in jobs:
                print(f"The job id is {job['JobId']}")
                print(f"The job priority is {job['Priority']}")
        except ClientError as e:
            print(f"Error listing jobs: {e}")
            raise
    
    def delete_job_tags(self, job_id: str, account_id: str) -> None:
        """
        Delete all tags from a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            self.s3control_client.delete_job_tagging(
                AccountId=account_id,
                JobId=job_id
            )
            print(f"You have successfully deleted {job_id} tagging.")
        except ClientError as e:
            print(f"Error deleting job tags: {e}")
            raise

    def cleanup_resources(self, bucket_name: str, file_names: List[str]) -> None:
        """
        Clean up all resources created during the scenario.

        Args:
            bucket_name (str): Name of the bucket to clean up
            file_names (list): List of files to delete

        Raises:
            ClientError: If cleanup fails
        """
        try:
            for file_name in file_names:
                self.s3_client.delete_object(Bucket=bucket_name, Key=file_name)
                print(f"Deleted {file_name}")

            response = self.s3_client.list_objects_v2(
                Bucket=bucket_name,
                Prefix='batch-op-reports/'
            )
            if 'Contents' in response:
                for obj in response['Contents']:
                    self.s3_client.delete_object(
                        Bucket=bucket_name,
                        Key=obj['Key']
                    )
                    print(f"Deleted {obj['Key']}")

            self.s3_client.delete_bucket(Bucket=bucket_name)
            print(f"Deleted bucket {bucket_name}")
        except ClientError as e:
            print(f"Error in cleanup: {e}")
            raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateJob](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/CreateJob)
  + [DeleteJobTagging](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/DeleteJobTagging)
  + [DescribeJob](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/DescribeJob)
  + [GetJobTagging](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/GetJobTagging)
  + [ListJobs](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/ListJobs)
  + [PutJobTagging](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/PutJobTagging)
  + [UpdateJobPriority](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/UpdateJobPriority)
  + [UpdateJobStatus](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/UpdateJobStatus)

## アクション
<a name="actions"></a>

### `CreateJob`
<a name="s3-control_CreateJob_python_3_topic"></a>

次の例は、`CreateJob` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def create_s3_batch_job(self, account_id: str, role_arn: str, manifest_location: str,
                           report_bucket_name: str) -> str:
        """
        Create an S3 batch operation job.

        Args:
            account_id (str): AWS account ID
            role_arn (str): IAM role ARN for batch operations
            manifest_location (str): Location of the manifest file
            report_bucket_name (str): Bucket for job reports

        Returns:
            str: Job ID

        Raises:
            ClientError: If job creation fails
        """
        try:
            bucket_name = manifest_location.split(':::')[1].split('/')[0]
            manifest_key = 'job-manifest.csv'
            manifest_obj = self.s3_client.head_object(
                Bucket=bucket_name,
                Key=manifest_key
            )
            etag = manifest_obj['ETag'].strip('"')
            
            response = self.s3control_client.create_job(
                AccountId=account_id,
                Operation={
                    'S3PutObjectTagging': {
                        'TagSet': [
                            {
                                'Key': 'BatchTag',
                                'Value': 'BatchValue'
                            },
                        ]
                    }
                },
                Report={
                    'Bucket': report_bucket_name,
                    'Format': 'Report_CSV_20180820',
                    'Enabled': True,
                    'Prefix': 'batch-op-reports',
                    'ReportScope': 'AllTasks'
                },
                Manifest={
                    'Spec': {
                        'Format': 'S3BatchOperations_CSV_20180820',
                        'Fields': ['Bucket', 'Key']
                    },
                    'Location': {
                        'ObjectArn': manifest_location,
                        'ETag': etag
                    }
                },
                Priority=10,
                RoleArn=role_arn,
                Description='Batch job for tagging objects',
                ConfirmationRequired=True
            )
            job_id = response['JobId']
            print(f"The Job id is {job_id}")
            return job_id
        except ClientError as e:
            print(f"Error creating batch job: {e}")
            if 'Message' in str(e):
                print(f"Detailed error message: {e.response['Message']}")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス* の「[CreateJob](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/CreateJob)」を参照してください。

### `DeleteJobTagging`
<a name="s3-control_DeleteJobTagging_python_3_topic"></a>

次の例は、`DeleteJobTagging` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def delete_job_tags(self, job_id: str, account_id: str) -> None:
        """
        Delete all tags from a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            self.s3control_client.delete_job_tagging(
                AccountId=account_id,
                JobId=job_id
            )
            print(f"You have successfully deleted {job_id} tagging.")
        except ClientError as e:
            print(f"Error deleting job tags: {e}")
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[DeleteJobTagging](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/DeleteJobTagging)」を参照してください。

### `DescribeJob`
<a name="s3-control_DescribeJob_python_3_topic"></a>

次の例は、`DescribeJob` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def describe_job_details(self, job_id: str, account_id: str) -> None:
        """
        Describe detailed information about a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.describe_job(
                AccountId=account_id,
                JobId=job_id
            )
            job = response['Job']
            print(f"Job ID: {job['JobId']}")
            print(f"Description: {job.get('Description', 'N/A')}")
            print(f"Status: {job['Status']}")
            print(f"Role ARN: {job['RoleArn']}")
            print(f"Priority: {job['Priority']}")
            if 'ProgressSummary' in job:
                progress = job['ProgressSummary']
                print(f"Progress Summary: Total={progress.get('TotalNumberOfTasks', 0)}, "
                      f"Succeeded={progress.get('NumberOfTasksSucceeded', 0)}, "
                      f"Failed={progress.get('NumberOfTasksFailed', 0)}")
        except ClientError as e:
            print(f"Error describing job: {e}")
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeJob](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/DescribeJob)」を参照してください。

### `GetJobTagging`
<a name="s3-control_GetJobTagging_python_3_topic"></a>

次の例は、`GetJobTagging` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def get_job_tags(self, job_id: str, account_id: str) -> None:
        """
        Get tags associated with a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.get_job_tagging(
                AccountId=account_id,
                JobId=job_id
            )
            tags = response.get('Tags', [])
            if tags:
                print(f"Tags for job {job_id}:")
                for tag in tags:
                    print(f"  {tag['Key']}: {tag['Value']}")
            else:
                print(f"No tags found for job ID: {job_id}")
        except ClientError as e:
            print(f"Error getting job tags: {e}")
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*「[GetJobTagging](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/GetJobTagging)」を参照してください。

### `PutJobTagging`
<a name="s3-control_PutJobTagging_python_3_topic"></a>

次の例は、`PutJobTagging` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def put_job_tags(self, job_id: str, account_id: str) -> None:
        """
        Add tags to a batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            self.s3control_client.put_job_tagging(
                AccountId=account_id,
                JobId=job_id,
                Tags=[
                    {'Key': 'Environment', 'Value': 'Development'},
                    {'Key': 'Team', 'Value': 'DataProcessing'}
                ]
            )
            print(f"Additional tags were added to job {job_id}")
        except ClientError as e:
            print(f"Error adding job tags: {e}")
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*「[PutJobTagging](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/PutJobTagging)」を参照してください。

### `UpdateJobPriority`
<a name="s3-control_UpdateJobPriority_python_3_topic"></a>

次の例は、`UpdateJobPriority` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def update_job_priority(self, job_id: str, account_id: str) -> None:
        """
        Update the priority of a batch job and start it.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.describe_job(
                AccountId=account_id,
                JobId=job_id
            )
            current_status = response['Job']['Status']
            print(f"Current job status: {current_status}")
            
            if current_status in ['Ready', 'Suspended']:
                self.s3control_client.update_job_priority(
                    AccountId=account_id,
                    JobId=job_id,
                    Priority=60
                )
                print("The job priority was updated")
                
                try:
                    self.s3control_client.update_job_status(
                        AccountId=account_id,
                        JobId=job_id,
                        RequestedJobStatus='Ready'
                    )
                    print("Job activated successfully")
                except ClientError as activation_error:
                    print(f"Note: Could not activate job automatically: {activation_error}")
                    print("Job priority was updated successfully. Job may need manual activation in the console.")
            elif current_status in ['Active', 'Completing', 'Complete']:
                print(f"Job is in '{current_status}' state - priority cannot be updated")
                if current_status == 'Completing':
                    print("Job is finishing up and will complete soon.")
                elif current_status == 'Complete':
                    print("Job has already completed successfully.")
                else:
                    print("Job is currently running.")
            else:
                print(f"Job is in '{current_status}' state - priority update not allowed")
                
        except ClientError as e:
            print(f"Error updating job priority: {e}")
            print("Continuing with the scenario...")
            return
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*[UpdateJobPriority](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/UpdateJobPriority)」を参照してください。

### `UpdateJobStatus`
<a name="s3-control_UpdateJobStatus_python_3_topic"></a>

次の例は、`UpdateJobStatus` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3/scenarios/batch#code-examples)での設定と実行の方法を確認してください。

```
    def cancel_job(self, job_id: str, account_id: str) -> None:
        """
        Cancel an S3 batch job.

        Args:
            job_id (str): ID of the batch job
            account_id (str): AWS account ID
        """
        try:
            response = self.s3control_client.describe_job(
                AccountId=account_id,
                JobId=job_id
            )
            current_status = response['Job']['Status']
            print(f"Current job status: {current_status}")

            if current_status in ['Ready', 'Suspended', 'Active']:
                self.s3control_client.update_job_status(
                    AccountId=account_id,
                    JobId=job_id,
                    RequestedJobStatus='Cancelled'
                )
                print(f"Job {job_id} was successfully canceled.")
            elif current_status in ['Completing', 'Complete']:
                print(f"Job is in '{current_status}' state - cannot be cancelled")
                if current_status == 'Completing':
                    print("Job is finishing up and will complete soon.")
                elif current_status == 'Complete':
                    print("Job has already completed successfully.")
            else:
                print(f"Job is in '{current_status}' state - cancel not allowed")
        except ClientError as e:
            print(f"Error canceling job: {e}")
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*[UpdateJobStatus](https://docs.aws.amazon.com/goto/boto3/s3control-2018-08-20/UpdateJobStatus)」を参照してください。

# SDK for Python (Boto3) を使用した S3 ディレクトリバケットの例
<a name="python_3_s3-directory-buckets_code_examples"></a>

次のコード例は、S3 ディレクトリバケット AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3-directory-buckets_Scenario_ExpressBasics_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ VPC と VPC エンドポイントをセットアップします。
+ S3 ディレクトリバケットと S3 Express One Zone ストレージクラスを操作するようにポリシー、ロール、ユーザーを設定します。
+ 2 つの S3 クライアントを作成します。
+ バケットを 2 つ作成します。
+ オブジェクトを作成し、それをコピーします。
+ パフォーマンスの違いを示します。
+ 辞書順の違いを示すために、バケットをデータを追加します。
+ ユーザーにリソースをクリーンアップするかどうかを確認するプロンプトを表示します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3-directory-buckets/#code-examples)での設定と実行の方法を確認してください。
Amazon S3 ディレクトリバケットと S3 Express One Zone の基本を示すシナリオを実行します。  

```
class S3ExpressScenario:
    """Runs an interactive scenario that shows how to get started with S3 Express."""

    def __init__(
        self,
        cloud_formation_resource: ServiceResource,
        ec2_client: client,
        iam_client: client,
    ):
        self.cloud_formation_resource = cloud_formation_resource
        self.ec2_client = ec2_client
        self.iam_client = iam_client
        self.region = ec2_client.meta.region_name
        self.stack = None
        self.vpc_id = None
        self.vpc_endpoint_id = None
        self.regular_bucket_name = None
        self.directory_bucket_name = None
        self.s3_express_wrapper = None
        self.s3_regular_wrapper = None

    def s3_express_scenario(self):
        """
        Runs the scenario.
        """
        print("")
        print_dashes()
        print("Welcome to the Amazon S3 Express Basics demo using Python (Boto 3)!")
        print_dashes()
        print(
            """
Let's get started! First, please note that S3 Express One Zone works best when working within the AWS infrastructure,
specifically when working in the same Availability Zone. To see the best results in this example and when you implement
Directory buckets into your infrastructure, it is best to put your compute resources in the same AZ as your Directory
bucket.
    """
        )
        press_enter_to_continue()

        # Create an optional VPC and create 2 IAM users.
        express_user_name, regular_user_name = self.create_vpc_and_users()

        # Set up two S3 clients, one regular and one express, and two buckets, one regular and one express.
        self.setup_clients_and_buckets(express_user_name, regular_user_name)

        # Create an S3 session for the express S3 client and add objects to the buckets.
        bucket_object = self.create_session_and_add_objects()

        # Demonstrate performance differences between regular and express buckets.
        self.demonstrate_performance(bucket_object)

        # Populate the buckets to show the lexicographical difference between regular and express buckets.
        self.show_lexicographical_differences(bucket_object)

        print("")
        print("That's it for our tour of the basic operations for S3 Express One Zone.")

        if q.ask(
            "Would you like to delete all the resources created during this demo (y/n)? ",
            q.is_yesno,
        ):
            self.cleanup()

    def create_vpc_and_users(self) -> None:
        """
        Optionally create a VPC.
        Create two IAM users, one with S3 Express One Zone permissions and one without.
        """
        # Configure a gateway VPC endpoint. This is the recommended method to allow S3 Express One Zone traffic without
        # the need to pass through an internet gateway or NAT device.
        print(
            """
1. First, we'll set up a new VPC and VPC Endpoint if this program is running in an EC2 instance in the same AZ as your 
Directory buckets will be. Are you running this in an EC2 instance located in the same AZ as your intended Directory buckets?
"""
        )
        if q.ask("Do you want to setup a VPC Endpoint? (y/n) ", q.is_yesno):
            print(
                "Great! Let's set up a VPC, retrieve the Route Table from it, and create a VPC Endpoint to connect the S3 Client to."
            )
            self.setup_vpc()
            press_enter_to_continue()
        else:
            print("Skipping the VPC setup. Don't forget to use this in production!")
        print(
            """            
2. Policies, users, and roles with CDK.
Now, we'll set up some policies, roles, and a user. This user will only have permissions to do S3 Express One Zone actions.
            """
        )
        press_enter_to_continue()
        stack_name = f"cfn-stack-s3-express-basics--{uuid.uuid4()}"
        template_as_string = S3ExpressScenario.get_template_as_string()
        self.stack = self.deploy_cloudformation_stack(stack_name, template_as_string)
        regular_user_name = None
        express_user_name = None
        outputs = self.stack.outputs
        for output in outputs:
            if output.get("OutputKey") == "RegularUser":
                regular_user_name = output.get("OutputValue")
            elif output.get("OutputKey") == "ExpressUser":
                express_user_name = output.get("OutputValue")
        if not regular_user_name or not express_user_name:
            error_string = f"""
            Failed to retrieve required outputs from CloudFormation stack.
            'regular_user_name'={regular_user_name}, 'express_user_name'={express_user_name}
            """
            logger.error(error_string)
            raise ValueError(error_string)
        return express_user_name, regular_user_name

    def setup_clients_and_buckets(
        self, express_user_name: str, regular_user_name: str
    ) -> None:
        """
        Set up two S3 clients, one regular and one express, and two buckets, one regular and one express.
        :param express_user_name: The name of the user with S3 Express permissions.
        :param regular_user_name: The name of the user with regular S3 permissions.
        """
        regular_credentials = self.create_access_key(regular_user_name)
        express_credentials = self.create_access_key(express_user_name)
        # 3. Create an additional client using the credentials with S3 Express permissions.
        print(
            """            
3. Create an additional client using the credentials with S3 Express permissions. This client is created with the 
credentials associated with the user account with the S3 Express policy attached, so it can perform S3 Express operations.
"""
        )
        press_enter_to_continue()
        s3_regular_client = self.create_s3__client_with_access_key_credentials(
            regular_credentials
        )
        self.s3_regular_wrapper = S3ExpressWrapper(s3_regular_client)
        s3_express_client = self.create_s3__client_with_access_key_credentials(
            express_credentials
        )
        self.s3_express_wrapper = S3ExpressWrapper(s3_express_client)
        print(
            """
All the roles and policies were created and attached to the user. Then a new S3 Client were created using 
that user's credentials. We can now use this client to make calls to S3 Express operations. Keeping permissions in mind
(and adhering to least-privilege) is crucial to S3 Express.
 """
        )
        press_enter_to_continue()
        # 4. Create two buckets.
        print(
            """
3. Create two buckets.
Now we will create a Directory bucket which is the linchpin of the S3 Express One Zone service. Directory buckets 
behave in different ways from regular S3 buckets which we will explore here. We'll also create a normal bucket, put 
an object into the normal bucket, and copy it over to the Directory bucket.
"""
        )

        # Create a directory bucket. These are different from normal S3 buckets in subtle ways.
        bucket_prefix = q.ask(
            "Enter a bucket name prefix that will be used for both buckets: ",
            q.re_match(r"[a-z0-9](?:[a-z0-9-\.]*)[a-z0-9]$"),
        )

        # Some availability zones are not supported for Directory buckets. We'll choose one that is supported.
        print(
            "Now, let's choose an availability zone for the Directory bucket. We'll choose one that is supported."
        )
        while True:
            availability_zone = self.select_availability_zone_id(self.region)
            # Construct the parts of a directory bucket name that is made unique with a UUID string.
            directory_bucket_suffix = f"--{availability_zone['ZoneId']}--x-s3"
            max_uuid_length = 63 - len(bucket_prefix) - len(directory_bucket_suffix) - 1
            bucket_uuid = str(uuid.uuid4()).replace("-", "")[:max_uuid_length]
            directory_bucket_name = (
                f"{bucket_prefix}-{bucket_uuid}{directory_bucket_suffix}"
            )
            regular_bucket_name = f"{bucket_prefix}-regular-{bucket_uuid}"
            configuration = {
                "Bucket": {
                    "Type": "Directory",
                    "DataRedundancy": "SingleAvailabilityZone",
                },
                "Location": {
                    "Name": availability_zone["ZoneId"],
                    "Type": "AvailabilityZone",
                },
            }
            press_enter_to_continue()
            print(
                "Now, let's create the actual Directory bucket, as well as a regular bucket."
            )
            press_enter_to_continue()
            try:
                self.s3_express_wrapper.create_bucket(
                    directory_bucket_name, configuration
                )
                break
            except ClientError as client_error:
                if client_error.response["Error"]["Code"] == "InvalidBucketName":
                    print(
                        f"Bucket '{directory_bucket_name}' is invalid. This may be because of selected availability zone."
                    )
                    if q.ask(
                        "Would you like to select a different availability zone? ",
                        q.is_yesno,
                    ):
                        continue
                    else:
                        raise
                else:
                    raise
        print(f"Created directory bucket, '{directory_bucket_name}'")
        self.directory_bucket_name = directory_bucket_name

        self.s3_regular_wrapper.create_bucket(regular_bucket_name)
        print(f"Created regular bucket, '{regular_bucket_name}'")
        self.regular_bucket_name = regular_bucket_name
        print("Great! Both buckets were created.")
        press_enter_to_continue()

    def create_session_and_add_objects(self) -> None:
        """
        Create a session for the express S3 client and add objects to the buckets.
        """
        print(
            """    
5. Create an object and copy it over.
We'll create a basic object consisting of some text and upload it to the normal bucket. Next we'll copy the object 
into the Directory bucket using the regular client. This works fine because copy operations are not restricted for 
Directory buckets.
        """
        )
        press_enter_to_continue()
        bucket_object = "basic-text-object"
        self.s3_regular_wrapper.put_object(
            self.regular_bucket_name, bucket_object, "Look Ma, I'm a bucket!"
        )
        self.s3_express_wrapper.create_session(self.directory_bucket_name)
        self.s3_express_wrapper.copy_object(
            self.regular_bucket_name,
            bucket_object,
            self.directory_bucket_name,
            bucket_object,
        )
        print(
            """
It worked! It's important to remember the user permissions when interacting with Directory buckets. Instead of validating
permissions on every call as normal buckets do, Directory buckets utilize the user credentials and session token to validate.
This allows for much faster connection speeds on every call. For single calls, this is low, but for many concurrent calls 
this adds up to a lot of time saved.
"""
        )
        press_enter_to_continue()
        return bucket_object

    def demonstrate_performance(self, bucket_object: str) -> None:
        """
        Demonstrate performance differences between regular and Directory buckets.
        :param bucket_object: The name of the object to download from each bucket.
        """
        print("")
        print("6. Demonstrate performance difference.")
        print(
            """
Now, let's do a performance test. We'll download the same object from each bucket 'downloads' times 
and compare the total time needed. Note: the performance difference will be much more pronounced if this
example is run in an EC2 instance in the same Availability Zone as the bucket.
"""
        )
        downloads = 1000
        print(
            f"The number of downloads of the same object for this example is set at {downloads}."
        )
        if q.ask("Would you like to download a different number? (y/n) ", q.is_yesno):
            max_downloads = 1000000
            downloads = q.ask(
                f"Enter a number between 1 and {max_downloads} for the number of downloads: ",
                q.is_int,
                q.in_range(1, max_downloads),
            )
        # Download the object 'downloads' times from each bucket and time it to demonstrate the speed difference.
        print("Downloading from the Directory bucket.")
        directory_time_start = time.time_ns()

        for index in range(downloads):
            if index % 10 == 0:
                print(f"Download {index} of {downloads}")

            self.s3_express_wrapper.get_object(
                self.directory_bucket_name, bucket_object
            )

        directory_time_difference = time.time_ns() - directory_time_start
        print("Downloading from the normal bucket.")
        normal_time_start = time.time_ns()

        for index in range(downloads):
            if index % 10 == 0:
                print(f"Download {index} of {downloads}")
            self.s3_regular_wrapper.get_object(self.regular_bucket_name, bucket_object)

        normal_time_difference = time.time_ns() - normal_time_start
        print(
            f"The directory bucket took {directory_time_difference} nanoseconds, while the normal bucket took {normal_time_difference}."
        )
        difference = normal_time_difference - directory_time_difference
        print(f"That's a difference of {difference} nanoseconds, or")
        print(f"{(difference) / 1000000000} seconds.")
        if difference < 0:
            print(
                "The directory buckets were slower. This can happen if you are not running on the cloud within a vpc."
            )
        press_enter_to_continue()

    def show_lexicographical_differences(self, bucket_object: str) -> None:
        """
        Show the lexicographical difference between Directory buckets and regular buckets.
        This is done by creating a few objects in each bucket and listing them to show the difference.
        :param bucket_object: The object to use for the listing operations.
        """
        print(
            """
7. Populate the buckets to show the lexicographical difference.
Now let's explore how Directory buckets store objects in a different manner to regular buckets. The key is in the name 
"Directory". Where regular buckets store their key/value pairs in a flat manner, Directory buckets use actual 
directories/folders. This allows for more rapid indexing, traversing, and therefore retrieval times! The more segmented 
your bucket is, with lots of directories, sub-directories, and objects, the more efficient it becomes. This structural 
difference also causes ListObjects to behave differently, which can cause unexpected results. Let's add a few more 
objects with layered directories to see how the output of ListObjects changes.
        """
        )
        press_enter_to_continue()
        # Populate a few more files in each bucket so that we can use ListObjects and show the difference.
        other_object = f"other/{bucket_object}"
        alt_object = f"alt/{bucket_object}"
        other_alt_object = f"other/alt/{bucket_object}"
        self.s3_regular_wrapper.put_object(self.regular_bucket_name, other_object, "")
        self.s3_express_wrapper.put_object(self.directory_bucket_name, other_object, "")
        self.s3_regular_wrapper.put_object(self.regular_bucket_name, alt_object, "")
        self.s3_express_wrapper.put_object(self.directory_bucket_name, alt_object, "")
        self.s3_regular_wrapper.put_object(
            self.regular_bucket_name, other_alt_object, ""
        )
        self.s3_express_wrapper.put_object(
            self.directory_bucket_name, other_alt_object, ""
        )
        directory_bucket_objects = self.s3_express_wrapper.list_objects(
            self.directory_bucket_name
        )

        regular_bucket_objects = self.s3_regular_wrapper.list_objects(
            self.regular_bucket_name
        )

        print("Directory bucket content")
        for bucket_object in directory_bucket_objects:
            print(f"   {bucket_object['Key']}")
        print("Normal bucket content")
        for bucket_object in regular_bucket_objects:
            print(f"   {bucket_object['Key']}")
        print(
            """
Notice how the normal bucket lists objects in lexicographical order, while the directory bucket does not. This is 
because the normal bucket considers the whole "key" to be the object identifier, while the directory bucket actually 
creates directories and uses the object "key" as a path to the object.
            """
        )
        press_enter_to_continue()

    def cleanup(self) -> None:
        """
        Delete resources created by this scenario.
        """
        if self.directory_bucket_name is not None:
            self.s3_express_wrapper.delete_bucket_and_objects(
                self.directory_bucket_name
            )
            print(f"Deleted directory bucket, '{self.directory_bucket_name}'")
            self.directory_bucket_name = None

        if self.regular_bucket_name is not None:
            self.s3_regular_wrapper.delete_bucket_and_objects(self.regular_bucket_name)
            print(f"Deleted regular bucket, '{self.regular_bucket_name}'")
            self.regular_bucket_name = None

        if self.stack is not None:
            self.destroy_cloudformation_stack(self.stack)
            self.stack = None

        self.tear_done_vpc()

    def create_access_key(self, user_name: str) -> dict[str, any]:
        """
        Creates an access key for the user.
        :param user_name: The name of the user.
        :return: The access key for the user.
        """
        try:
            access_key = self.iam_client.create_access_key(UserName=user_name)
            return access_key["AccessKey"]
        except ClientError as client_error:
            logging.error(
                "Couldn't create the access key. Here's why: %s",
                client_error.response["Error"]["Message"],
            )
            raise

    def create_s3__client_with_access_key_credentials(
        self, access_key: dict[str, any]
    ) -> client:
        """
        Creates an S3 client with access key credentials.
        :param access_key: The access key for the user.
        :return: The S3 Express One Zone client.
        """
        try:
            s3_express_client = boto3.client(
                "s3",
                aws_access_key_id=access_key["AccessKeyId"],
                aws_secret_access_key=access_key["SecretAccessKey"],
                region_name=self.region,
            )
            return s3_express_client
        except ClientError as client_error:
            logging.error(
                "Couldn't create the S3 Express One Zone client. Here's why: %s",
                client_error.response["Error"]["Message"],
            )
            raise

    def select_availability_zone_id(self, region: str) -> dict[str, any]:
        """
        Selects an availability zone.
        :param region: The region to select the availability zone from.
        :return: The availability zone dictionary.
        """
        try:
            response = self.ec2_client.describe_availability_zones(
                Filters=[{"Name": "region-name", "Values": [region]}]
            )
            availability_zones = response["AvailabilityZones"]
            zone_names = [zone["ZoneName"] for zone in availability_zones]
            index = q.choose("Select an availability zone: ", zone_names)
            return availability_zones[index]
        except ClientError as client_error:
            logging.error(
                "Couldn't describe availability zones. Here's why: %s",
                client_error.response["Error"]["Message"],
            )
            raise

    def deploy_cloudformation_stack(
        self, stack_name: str, cfn_template: str
    ) -> ServiceResource:
        """
        Deploys prerequisite resources used by the scenario. The resources are
        defined in the associated `cfn_template.yaml` AWS CloudFormation script and are deployed
        as a CloudFormation stack, so they can be easily managed and destroyed.

        :param stack_name: The name of the CloudFormation stack.
        :param cfn_template: The CloudFormation template as a string.
        :return: The CloudFormation stack resource.
        """
        print(f"Deploying CloudFormation stack: {stack_name}.")
        stack = self.cloud_formation_resource.create_stack(
            StackName=stack_name,
            TemplateBody=cfn_template,
            Capabilities=["CAPABILITY_NAMED_IAM"],
        )
        print(f"CloudFormation stack creation started: {stack_name}")
        print("Waiting for CloudFormation stack creation to complete...")
        waiter = self.cloud_formation_resource.meta.client.get_waiter(
            "stack_create_complete"
        )
        waiter.wait(StackName=stack.name)
        stack.load()
        print("CloudFormation stack creation complete.")

        return stack

    def destroy_cloudformation_stack(self, stack: ServiceResource) -> None:
        """
        Destroys the resources managed by the CloudFormation stack, and the CloudFormation
        stack itself.

        :param stack: The CloudFormation stack that manages the example resources.
        """
        try:
            print(
                f"CloudFormation stack '{stack.name}' is being deleted. This may take a few minutes."
            )
            stack.delete()
            waiter = self.cloud_formation_resource.meta.client.get_waiter(
                "stack_delete_complete"
            )
            waiter.wait(StackName=stack.name)
            print(f"CloudFormation stack '{stack.name}' has been deleted.")
        except ClientError as client_error:
            logging.error(
                "Couldn't delete the CloudFormation stack. Here's why: %s",
                client_error.response["Error"]["Message"],
            )

    @staticmethod
    def get_template_as_string() -> str:
        """
        Returns a string containing this scenario's CloudFormation template.
        """
        script_directory = os.path.dirname(os.path.abspath(__file__))
        template_file_path = os.path.join(script_directory, "s3_express_template.yaml")
        file = open(template_file_path, "r")
        return file.read()

    def setup_vpc(self):
        cidr = "10.0.0.0/16"
        try:
            response = self.ec2_client.create_vpc(CidrBlock=cidr)
            self.vpc_id = response["Vpc"]["VpcId"]

            waiter = self.ec2_client.get_waiter("vpc_available")
            waiter.wait(VpcIds=[self.vpc_id])
            print(f"Created vpc {self.vpc_id}")

        except ClientError as client_error:
            logging.error(
                "Couldn't create the vpc. Here's why: %s",
                client_error.response["Error"]["Message"],
            )
            raise
        try:
            response = self.ec2_client.describe_route_tables(
                Filters=[{"Name": "vpc-id", "Values": [self.vpc_id]}]
            )
            route_table_id = response["RouteTables"][0]["RouteTableId"]
            service_name = f"com.amazonaws.{self.ec2_client.meta.region_name}.s3express"

            response = self.ec2_client.create_vpc_endpoint(
                VpcId=self.vpc_id,
                RouteTableIds=[route_table_id],
                ServiceName=service_name,
            )
            self.vpc_endpoint_id = response["VpcEndpoint"]["VpcEndpointId"]
            print(f"Created vpc endpoint {self.vpc_endpoint_id}")

        except ClientError as client_error:
            logging.error(
                "Couldn't create the vpc endpoint. Here's why: %s",
                client_error.response["Error"]["Message"],
            )
            raise

    def tear_done_vpc(self) -> None:
        if self.vpc_endpoint_id is not None:
            try:
                self.ec2_client.delete_vpc_endpoints(
                    VpcEndpointIds=[self.vpc_endpoint_id]
                )
                print(f"Deleted vpc endpoint {self.vpc_endpoint_id}.")
                self.vpc_endpoint_id = None
            except ClientError as client_error:
                logging.error(
                    "Couldn't delete the vpc endpoint %s. Here's why: %s",
                    self.vpc_endpoint_id,
                    client_error.response["Error"]["Message"],
                )
        if self.vpc_id is not None:
            try:
                self.ec2_client.delete_vpc(VpcId=self.vpc_id)
                print(f"Deleted vpc {self.vpc_id}")
                self.vpc_id = None
            except ClientError as client_error:
                logging.error(
                    "Couldn't delete the vpc %s. Here's why: %s",
                    self.vpc_id,
                    client_error.response["Error"]["Message"],
                )
```
Amazon S3 Express SDK 関数のラッパークラス。  

```
class S3ExpressWrapper:
    """Encapsulates Amazon S3 Express One Zone actions using the client interface."""

    def __init__(self, s3_client: Any) -> None:
        """
        Initializes the S3ExpressWrapper with an S3 client.

        :param s3_client: A Boto3 Amazon S3 client. This client provides low-level
                           access to AWS S3 services.
        """
        self.s3_client = s3_client

    @classmethod
    def from_client(cls) -> "S3ExpressWrapper":
        """
        Creates an S3ExpressWrapper instance with a default s3 client.

        :return: An instance of S3ExpressWrapper initialized with the default S3 client.
        """
        s3_client = boto3.client("s3")
        return cls(s3_client)


    def create_bucket(
        self, bucket_name: str, bucket_configuration: dict[str, any] = None
    ) -> None:
        """
        Creates a bucket.
        :param bucket_name: The name of the bucket.
        :param bucket_configuration: The optional configuration for the bucket.
        """
        try:
            params = {"Bucket": bucket_name}
            if bucket_configuration:
                params["CreateBucketConfiguration"] = bucket_configuration

            self.s3_client.create_bucket(**params)
        except ClientError as client_error:
            # Do not log InvalidBucketName error because it is logged elsewhere.
            if client_error.response["Error"]["Code"] != "InvalidBucketName":
                logging.error(
                    "Couldn't create the bucket %s. Here's why: %s",
                    bucket_name,
                    client_error.response["Error"]["Message"],
                )
            raise

    def delete_bucket_and_objects(self, bucket_name: str) -> None:
        """
        Deletes a bucket and its objects.
         :param bucket_name: The name of the bucket.
        """
        try:
            # Delete the objects in the bucket first. This is required for a bucket to be deleted.
            paginator = self.s3_client.get_paginator("list_objects_v2")
            page_iterator = paginator.paginate(Bucket=bucket_name)
            for page in page_iterator:
                if "Contents" in page:
                    delete_keys = {
                        "Objects": [{"Key": obj["Key"]} for obj in page["Contents"]]
                    }
                    response = self.s3_client.delete_objects(
                        Bucket=bucket_name, Delete=delete_keys
                    )
                    if "Errors" in response:
                        for error in response["Errors"]:
                            logging.error(
                                "Couldn't delete object %s. Here's why: %s",
                                error["Key"],
                                error["Message"],
                            )

            self.s3_client.delete_bucket(Bucket=bucket_name)
        except ClientError as client_error:
            logging.error(
                "Couldn't delete the bucket %s. Here's why: %s",
                bucket_name,
                client_error.response["Error"]["Message"],
            )

    def put_object(self, bucket_name: str, object_key: str, content: str) -> None:
        """
        Puts an object into a bucket.
        :param bucket_name: The name of the bucket.
        :param object_key: The key of the object.
        :param content: The content of the object.
        """
        try:
            self.s3_client.put_object(Body=content, Bucket=bucket_name, Key=object_key)
        except ClientError as client_error:
            logging.error(
                "Couldn't put the object %s into bucket %s. Here's why: %s",
                object_key,
                bucket_name,
                client_error.response["Error"]["Message"],
            )
            raise

    def list_objects(self, bucket: str) -> list[str]:
        """
        Lists objects in a bucket.
        :param bucket: The name of the bucket.
        :return: The list of objects in the bucket.
        """
        try:
            response = self.s3_client.list_objects_v2(Bucket=bucket)
            return response.get("Contents", [])
        except ClientError as client_error:
            logging.error(
                "Couldn't list objects in bucket %s. Here's why: %s",
                bucket,
                client_error.response["Error"]["Message"],
            )
            raise

    def copy_object(
        self,
        source_bucket: str,
        source_key: str,
        destination_bucket: str,
        destination_key: str,
    ) -> None:
        """
        Copies an object from one bucket to another.
        :param source_bucket: The source bucket.
        :param source_key: The source key.
        :param destination_bucket: The destination bucket.
        :param destination_key: The destination key.
        :return: None
        """
        try:
            self.s3_client.copy_object(
                CopySource={"Bucket": source_bucket, "Key": source_key},
                Bucket=destination_bucket,
                Key=destination_key,
            )
        except ClientError as client_error:
            logging.error(
                "Couldn't copy object %s from bucket %s to bucket %s. Here's why: %s",
                source_key,
                source_bucket,
                destination_bucket,
                client_error.response["Error"]["Message"],
            )
            raise

    def create_session(self, bucket_name: str) -> None:
        """
        Creates an express session.
        :param bucket_name: The name of the bucket.
        """
        try:
            self.s3_client.create_session(Bucket=bucket_name)
        except ClientError as client_error:
            logging.error(
                "Couldn't create the express session for bucket %s. Here's why: %s",
                bucket_name,
                client_error.response["Error"]["Message"],
            )
            raise


    def get_object(self, bucket_name: str, object_key: str) -> None:
        """
        Gets an object from a bucket.
        :param bucket_name: The name of the bucket.
        :param object_key: The key of the object.
        """
        try:
            self.s3_client.get_object(Bucket=bucket_name, Key=object_key)
        except ClientError as client_error:
            logging.error(
                "Couldn't get the object %s from bucket %s. Here's why: %s",
                object_key,
                bucket_name,
                client_error.response["Error"]["Message"],
            )
            raise
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteBucket)
  + [DeleteObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/DeleteObject)
  + [GetObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/GetObject)
  + [ListObjects](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/ListObjects)
  + [PutObject](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `CreateSession`
<a name="s3-directory-buckets_CreateSession_python_3_topic"></a>

次のコード例は、`CreateSession` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/s3-directory-buckets#code-examples)での設定と実行の方法を確認してください。

```
class S3ExpressWrapper:
    """Encapsulates Amazon S3 Express One Zone actions using the client interface."""

    def __init__(self, s3_client: Any) -> None:
        """
        Initializes the S3ExpressWrapper with an S3 client.

        :param s3_client: A Boto3 Amazon S3 client. This client provides low-level
                           access to AWS S3 services.
        """
        self.s3_client = s3_client

    @classmethod
    def from_client(cls) -> "S3ExpressWrapper":
        """
        Creates an S3ExpressWrapper instance with a default s3 client.

        :return: An instance of S3ExpressWrapper initialized with the default S3 client.
        """
        s3_client = boto3.client("s3")
        return cls(s3_client)


    def create_session(self, bucket_name: str) -> None:
        """
        Creates an express session.
        :param bucket_name: The name of the bucket.
        """
        try:
            self.s3_client.create_session(Bucket=bucket_name)
        except ClientError as client_error:
            logging.error(
                "Couldn't create the express session for bucket %s. Here's why: %s",
                bucket_name,
                client_error.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateSession](https://docs.aws.amazon.com/goto/boto3/s3-2006-03-01/CreateSession)」を参照してください。**

# SDK for Python (Boto3) を使用した Secrets Manager の例
<a name="python_3_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `BatchGetSecretValue`
<a name="secrets-manager_BatchGetSecretValue_python_3_topic"></a>

次のコード例は、`BatchGetSecretValue` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/secretsmanager#code-examples)での設定と実行の方法を確認してください。

```
class BatchGetSecretsWrapper:
    def __init__(self, secretsmanager_client):
        self.client = secretsmanager_client


    def batch_get_secrets(self, filter_name):
        """
        Retrieve multiple secrets from AWS Secrets Manager using the batch_get_secret_value API.
        This function assumes the stack mentioned in the source code README has been successfully deployed.
        This stack includes 7 secrets, all of which have names beginning with "mySecret".

        :param filter_name: The full or partial name of secrets to be fetched.
        :type filter_name: str
        """
        try:
            secrets = []
            response = self.client.batch_get_secret_value(
                Filters=[{"Key": "name", "Values": [f"{filter_name}"]}]
            )
            for secret in response["SecretValues"]:
                secrets.append(json.loads(secret["SecretString"]))
            if secrets:
                logger.info("Secrets retrieved successfully.")
            else:
                logger.info("Zero secrets returned without error.")
            return secrets
        except self.client.exceptions.ResourceNotFoundException:
            msg = f"One or more requested secrets were not found with filter: {filter_name}"
            logger.info(msg)
            return msg
        except Exception as e:
            logger.error(f"An unknown error occurred:\n{str(e)}.")
            raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[BatchGetSecretValue](https://docs.aws.amazon.com/goto/boto3/secretsmanager-2017-10-17/BatchGetSecretValue)」を参照してください。**

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_python_3_topic"></a>

次のコード例は、`GetSecretValue` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/secretsmanager#code-examples)での設定と実行の方法を確認してください。

```
class GetSecretWrapper:
    def __init__(self, secretsmanager_client):
        self.client = secretsmanager_client


    def get_secret(self, secret_name):
        """
        Retrieve individual secrets from AWS Secrets Manager using the get_secret_value API.
        This function assumes the stack mentioned in the source code README has been successfully deployed.
        This stack includes 7 secrets, all of which have names beginning with "mySecret".

        :param secret_name: The name of the secret fetched.
        :type secret_name: str
        """
        try:
            get_secret_value_response = self.client.get_secret_value(
                SecretId=secret_name
            )
            logging.info("Secret retrieved successfully.")
            return get_secret_value_response["SecretString"]
        except self.client.exceptions.ResourceNotFoundException:
            msg = f"The requested secret {secret_name} was not found."
            logger.info(msg)
            return msg
        except Exception as e:
            logger.error(f"An unknown error occurred: {str(e)}.")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetSecretValue](https://docs.aws.amazon.com/goto/boto3/secretsmanager-2017-10-17/GetSecretValue)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 貸出ライブラリ REST API を作成する
<a name="cross_AuroraRestLendingLibrary_python_3_topic"></a>

以下のコード例は、Amazon Aurora データベースでバックアップされた REST API を使用して、常連客が書籍の貸出と返却できる貸出ライブラリを作成する方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Relational Database Service (Amazon RDS) API と AWS Chalice AWS SDK for Python (Boto3) で を使用して、Amazon Aurora データベースにバックアップされた REST API を作成する方法を示します。Web サービスは完全にサーバーレスであり、常連客が本を借りたり返却したりできるシンプルな貸し出しライブラリを表しています。以下ではその方法を説明しています。  
+ サーバーレス Aurora データベースクラスターを作成および管理します。
+  AWS Secrets Manager を使用してデータベース認証情報を管理します。
+ Amazon RDS を使用してデータをデータベースに出し入れするデータストレージレイヤーを実装します。
+  AWS Chalice を使用して、サーバーレス REST API を Amazon API Gateway および にデプロイします AWS Lambda。
+ リクエストパッケージを使用して、Web サービスにリクエストを送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_rest_lending_library) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ Aurora
+ Lambda
+ Secrets Manager

# SDK for Python (Boto3) を使用する Amazon SES の例
<a name="python_3_ses_code_examples"></a>

次のコード例は、Amazon SES AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateReceiptFilter`
<a name="ses_CreateReceiptFilter_python_3_topic"></a>

次のコード例は、`CreateReceiptFilter` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def create_receipt_filter(self, filter_name, ip_address_or_range, allow):
        """
        Creates a filter that allows or blocks incoming mail from an IP address or
        range.

        :param filter_name: The name to give the filter.
        :param ip_address_or_range: The IP address or range to block or allow.
        :param allow: When True, incoming mail is allowed from the specified IP
                      address or range; otherwise, it is blocked.
        """
        try:
            policy = "Allow" if allow else "Block"
            self.ses_client.create_receipt_filter(
                Filter={
                    "Name": filter_name,
                    "IpFilter": {"Cidr": ip_address_or_range, "Policy": policy},
                }
            )
            logger.info(
                "Created receipt filter %s to %s IP of %s.",
                filter_name,
                policy,
                ip_address_or_range,
            )
        except ClientError:
            logger.exception("Couldn't create receipt filter %s.", filter_name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateReceiptFilter](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/CreateReceiptFilter)」を参照してください。

### `CreateReceiptRule`
<a name="ses_CreateReceiptRule_python_3_topic"></a>

次のコード例は、`CreateReceiptRule` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。
Amazon SES が受信 E メールのコピーを配置できる Amazon S3 バケットを作成し、特定の受信者のリストに対して受信 E メールをバケットにコピーするルールを作成します。  

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def create_bucket_for_copy(self, bucket_name):
        """
        Creates a bucket that can receive copies of emails from Amazon SES. This
        includes adding a policy to the bucket that grants Amazon SES permission
        to put objects in the bucket.

        :param bucket_name: The name of the bucket to create.
        :return: The newly created bucket.
        """
        allow_ses_put_policy = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Sid": "AllowSESPut",
                    "Effect": "Allow",
                    "Principal": {"Service": "ses.amazonaws.com"},
                    "Action": "s3:PutObject",
                    "Resource": f"arn:aws:s3:::{bucket_name}/*",
                }
            ],
        }
        bucket = None
        try:
            bucket = self.s3_resource.create_bucket(
                Bucket=bucket_name,
                CreateBucketConfiguration={
                    "LocationConstraint": self.s3_resource.meta.client.meta.region_name
                },
            )
            bucket.wait_until_exists()
            bucket.Policy().put(Policy=json.dumps(allow_ses_put_policy))
            logger.info("Created bucket %s to receive copies of emails.", bucket_name)
        except ClientError:
            logger.exception("Couldn't create bucket to receive copies of emails.")
            if bucket is not None:
                bucket.delete()
            raise
        else:
            return bucket


    def create_s3_copy_rule(
        self, rule_set_name, rule_name, recipients, bucket_name, prefix
    ):
        """
        Creates a rule so that all emails received by the specified recipients are
        copied to an Amazon S3 bucket.

        :param rule_set_name: The name of a previously created rule set to contain
                              this rule.
        :param rule_name: The name to give the rule.
        :param recipients: When an email is received by one of these recipients, it
                           is copied to the Amazon S3 bucket.
        :param bucket_name: The name of the bucket to receive email copies. This
                            bucket must allow Amazon SES to put objects into it.
        :param prefix: An object key prefix to give the emails copied to the bucket.
        """
        try:
            self.ses_client.create_receipt_rule(
                RuleSetName=rule_set_name,
                Rule={
                    "Name": rule_name,
                    "Enabled": True,
                    "Recipients": recipients,
                    "Actions": [
                        {
                            "S3Action": {
                                "BucketName": bucket_name,
                                "ObjectKeyPrefix": prefix,
                            }
                        }
                    ],
                },
            )
            logger.info(
                "Created rule %s to copy mail received by %s to bucket %s.",
                rule_name,
                recipients,
                bucket_name,
            )
        except ClientError:
            logger.exception("Couldn't create rule %s.", rule_name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateReceiptRule](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/CreateReceiptRule)」を参照してください。

### `CreateReceiptRuleSet`
<a name="ses_CreateReceiptRuleSet_python_3_topic"></a>

次のコード例は、`CreateReceiptRuleSet` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def create_receipt_rule_set(self, rule_set_name):
        """
        Creates an empty rule set. Rule sets contain individual rules and can be
        used to organize rules.

        :param rule_set_name: The name to give the rule set.
        """
        try:
            self.ses_client.create_receipt_rule_set(RuleSetName=rule_set_name)
            logger.info("Created receipt rule set %s.", rule_set_name)
        except ClientError:
            logger.exception("Couldn't create receipt rule set %s.", rule_set_name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateReceiptRuleSet](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/CreateReceiptRuleSet)」を参照してください。

### `CreateTemplate`
<a name="ses_CreateTemplate_python_3_topic"></a>

次のコード例は、`CreateTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesTemplate:
    """Encapsulates Amazon SES template functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client
        self.template = None
        self.template_tags = set()

    def _extract_tags(self, subject, text, html):
        """
        Extracts tags from a template as a set of unique values.

        :param subject: The subject of the email.
        :param text: The text version of the email.
        :param html: The html version of the email.
        """
        self.template_tags = set(re.findall(TEMPLATE_REGEX, subject + text + html))
        logger.info("Extracted template tags: %s", self.template_tags)


    def create_template(self, name, subject, text, html):
        """
        Creates an email template.

        :param name: The name of the template.
        :param subject: The subject of the email.
        :param text: The plain text version of the email.
        :param html: The HTML version of the email.
        """
        try:
            template = {
                "TemplateName": name,
                "SubjectPart": subject,
                "TextPart": text,
                "HtmlPart": html,
            }
            self.ses_client.create_template(Template=template)
            logger.info("Created template %s.", name)
            self.template = template
            self._extract_tags(subject, text, html)
        except ClientError:
            logger.exception("Couldn't create template %s.", name)
            raise
```
+  API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「[CreateTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/CreateTemplate)」を参照してください。**

### `DeleteIdentity`
<a name="ses_DeleteIdentity_python_3_topic"></a>

次のコード例は、`DeleteIdentity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesIdentity:
    """Encapsulates Amazon SES identity functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def delete_identity(self, identity):
        """
        Deletes an identity.

        :param identity: The identity to remove.
        """
        try:
            self.ses_client.delete_identity(Identity=identity)
            logger.info("Deleted identity %s.", identity)
        except ClientError:
            logger.exception("Couldn't delete identity %s.", identity)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DeleteIdentity)」を参照してください。

### `DeleteReceiptFilter`
<a name="ses_DeleteReceiptFilter_python_3_topic"></a>

次のコード例は、`DeleteReceiptFilter` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def delete_receipt_filter(self, filter_name):
        """
        Deletes a receipt filter.

        :param filter_name: The name of the filter to delete.
        """
        try:
            self.ses_client.delete_receipt_filter(FilterName=filter_name)
            logger.info("Deleted receipt filter %s.", filter_name)
        except ClientError:
            logger.exception("Couldn't delete receipt filter %s.", filter_name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteReceiptFilter](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DeleteReceiptFilter)」を参照してください。

### `DeleteReceiptRule`
<a name="ses_DeleteReceiptRule_python_3_topic"></a>

次のコード例は、`DeleteReceiptRule` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def delete_receipt_rule(self, rule_set_name, rule_name):
        """
        Deletes a rule.

        :param rule_set_name: The rule set that contains the rule to delete.
        :param rule_name: The rule to delete.
        """
        try:
            self.ses_client.delete_receipt_rule(
                RuleSetName=rule_set_name, RuleName=rule_name
            )
            logger.info("Removed rule %s from rule set %s.", rule_name, rule_set_name)
        except ClientError:
            logger.exception(
                "Couldn't remove rule %s from rule set %s.", rule_name, rule_set_name
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteReceiptRule](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DeleteReceiptRule)」を参照してください。

### `DeleteReceiptRuleSet`
<a name="ses_DeleteReceiptRuleSet_python_3_topic"></a>

次のコード例は、`DeleteReceiptRuleSet` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def delete_receipt_rule_set(self, rule_set_name):
        """
        Deletes a rule set. When a rule set is deleted, all of the rules it contains
        are also deleted.

        :param rule_set_name: The name of the rule set to delete.
        """
        try:
            self.ses_client.delete_receipt_rule_set(RuleSetName=rule_set_name)
            logger.info("Deleted rule set %s.", rule_set_name)
        except ClientError:
            logger.exception("Couldn't delete rule set %s.", rule_set_name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteReceiptRuleSet](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DeleteReceiptRuleSet)」を参照してください。

### `DeleteTemplate`
<a name="ses_DeleteTemplate_python_3_topic"></a>

次のコード例は、`DeleteTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesTemplate:
    """Encapsulates Amazon SES template functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client
        self.template = None
        self.template_tags = set()

    def _extract_tags(self, subject, text, html):
        """
        Extracts tags from a template as a set of unique values.

        :param subject: The subject of the email.
        :param text: The text version of the email.
        :param html: The html version of the email.
        """
        self.template_tags = set(re.findall(TEMPLATE_REGEX, subject + text + html))
        logger.info("Extracted template tags: %s", self.template_tags)


    def delete_template(self):
        """
        Deletes an email template.
        """
        try:
            self.ses_client.delete_template(TemplateName=self.template["TemplateName"])
            logger.info("Deleted template %s.", self.template["TemplateName"])
            self.template = None
            self.template_tags = None
        except ClientError:
            logger.exception(
                "Couldn't delete template %s.", self.template["TemplateName"]
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DeleteTemplate)」を参照してください。

### `DescribeReceiptRuleSet`
<a name="ses_DescribeReceiptRuleSet_python_3_topic"></a>

次のコード例は、`DescribeReceiptRuleSet` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def describe_receipt_rule_set(self, rule_set_name):
        """
        Gets data about a rule set.

        :param rule_set_name: The name of the rule set to retrieve.
        :return: Data about the rule set.
        """
        try:
            response = self.ses_client.describe_receipt_rule_set(
                RuleSetName=rule_set_name
            )
            logger.info("Got data for rule set %s.", rule_set_name)
        except ClientError:
            logger.exception("Couldn't get data for rule set %s.", rule_set_name)
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeReceiptRuleSet](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DescribeReceiptRuleSet)」を参照してください。

### `GetIdentityVerificationAttributes`
<a name="ses_GetIdentityVerificationAttributes_python_3_topic"></a>

次のコード例は、`GetIdentityVerificationAttributes` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesIdentity:
    """Encapsulates Amazon SES identity functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def get_identity_status(self, identity):
        """
        Gets the status of an identity. This can be used to discover whether
        an identity has been successfully verified.

        :param identity: The identity to query.
        :return: The status of the identity.
        """
        try:
            response = self.ses_client.get_identity_verification_attributes(
                Identities=[identity]
            )
            status = response["VerificationAttributes"].get(
                identity, {"VerificationStatus": "NotFound"}
            )["VerificationStatus"]
            logger.info("Got status of %s for %s.", status, identity)
        except ClientError:
            logger.exception("Couldn't get status for %s.", identity)
            raise
        else:
            return status
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetIdentityVerificationAttributes](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/GetIdentityVerificationAttributes)」を参照してください。

### `GetTemplate`
<a name="ses_GetTemplate_python_3_topic"></a>

次のコード例は、`GetTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesTemplate:
    """Encapsulates Amazon SES template functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client
        self.template = None
        self.template_tags = set()

    def _extract_tags(self, subject, text, html):
        """
        Extracts tags from a template as a set of unique values.

        :param subject: The subject of the email.
        :param text: The text version of the email.
        :param html: The html version of the email.
        """
        self.template_tags = set(re.findall(TEMPLATE_REGEX, subject + text + html))
        logger.info("Extracted template tags: %s", self.template_tags)


    def get_template(self, name):
        """
        Gets a previously created email template.

        :param name: The name of the template to retrieve.
        :return: The retrieved email template.
        """
        try:
            response = self.ses_client.get_template(TemplateName=name)
            self.template = response["Template"]
            logger.info("Got template %s.", name)
            self._extract_tags(
                self.template["SubjectPart"],
                self.template["TextPart"],
                self.template["HtmlPart"],
            )
        except ClientError:
            logger.exception("Couldn't get template %s.", name)
            raise
        else:
            return self.template
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/GetTemplate)」を参照してください。

### `ListIdentities`
<a name="ses_ListIdentities_python_3_topic"></a>

次のコード例は、`ListIdentities` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesIdentity:
    """Encapsulates Amazon SES identity functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def list_identities(self, identity_type, max_items):
        """
        Gets the identities of the specified type for the current account.

        :param identity_type: The type of identity to retrieve, such as EmailAddress.
        :param max_items: The maximum number of identities to retrieve.
        :return: The list of retrieved identities.
        """
        try:
            response = self.ses_client.list_identities(
                IdentityType=identity_type, MaxItems=max_items
            )
            identities = response["Identities"]
            logger.info("Got %s identities for the current account.", len(identities))
        except ClientError:
            logger.exception("Couldn't list identities for the current account.")
            raise
        else:
            return identities
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListIdentities](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/ListIdentities)」を参照してください。

### `ListReceiptFilters`
<a name="ses_ListReceiptFilters_python_3_topic"></a>

次のコード例は、`ListReceiptFilters` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesReceiptHandler:
    """Encapsulates Amazon SES receipt handling functions."""

    def __init__(self, ses_client, s3_resource):
        """
        :param ses_client: A Boto3 Amazon SES client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        """
        self.ses_client = ses_client
        self.s3_resource = s3_resource


    def list_receipt_filters(self):
        """
        Gets the list of receipt filters for the current account.

        :return: The list of receipt filters.
        """
        try:
            response = self.ses_client.list_receipt_filters()
            filters = response["Filters"]
            logger.info("Got %s receipt filters.", len(filters))
        except ClientError:
            logger.exception("Couldn't get receipt filters.")
            raise
        else:
            return filters
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListReceiptFilters](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/ListReceiptFilters)」を参照してください。

### `ListTemplates`
<a name="ses_ListTemplates_python_3_topic"></a>

次のコード例は、`ListTemplates` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesTemplate:
    """Encapsulates Amazon SES template functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client
        self.template = None
        self.template_tags = set()

    def _extract_tags(self, subject, text, html):
        """
        Extracts tags from a template as a set of unique values.

        :param subject: The subject of the email.
        :param text: The text version of the email.
        :param html: The html version of the email.
        """
        self.template_tags = set(re.findall(TEMPLATE_REGEX, subject + text + html))
        logger.info("Extracted template tags: %s", self.template_tags)


    def list_templates(self):
        """
        Gets a list of all email templates for the current account.

        :return: The list of retrieved email templates.
        """
        try:
            response = self.ses_client.list_templates()
            templates = response["TemplatesMetadata"]
            logger.info("Got %s templates.", len(templates))
        except ClientError:
            logger.exception("Couldn't get templates.")
            raise
        else:
            return templates
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListTemplates](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/ListTemplates)」を参照してください。

### `SendEmail`
<a name="ses_SendEmail_python_3_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesMailSender:
    """Encapsulates functions to send emails with Amazon SES."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def send_email(self, source, destination, subject, text, html, reply_tos=None):
        """
        Sends an email.

        Note: If your account is in the Amazon SES  sandbox, the source and
        destination email accounts must both be verified.

        :param source: The source email account.
        :param destination: The destination email account.
        :param subject: The subject of the email.
        :param text: The plain text version of the body of the email.
        :param html: The HTML version of the body of the email.
        :param reply_tos: Email accounts that will receive a reply if the recipient
                          replies to the message.
        :return: The ID of the message, assigned by Amazon SES.
        """
        send_args = {
            "Source": source,
            "Destination": destination.to_service_format(),
            "Message": {
                "Subject": {"Data": subject},
                "Body": {"Text": {"Data": text}, "Html": {"Data": html}},
            },
        }
        if reply_tos is not None:
            send_args["ReplyToAddresses"] = reply_tos
        try:
            response = self.ses_client.send_email(**send_args)
            message_id = response["MessageId"]
            logger.info(
                "Sent mail %s from %s to %s.", message_id, source, destination.tos
            )
        except ClientError:
            logger.exception(
                "Couldn't send mail from %s to %s.", source, destination.tos
            )
            raise
        else:
            return message_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SendEmail](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/SendEmail)」を参照してください。

### `SendTemplatedEmail`
<a name="ses_SendTemplatedEmail_python_3_topic"></a>

次のコード例は、`SendTemplatedEmail` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesMailSender:
    """Encapsulates functions to send emails with Amazon SES."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def send_templated_email(
        self, source, destination, template_name, template_data, reply_tos=None
    ):
        """
        Sends an email based on a template. A template contains replaceable tags
        each enclosed in two curly braces, such as {{name}}. The template data passed
        in this function contains key-value pairs that define the values to insert
        in place of the template tags.

        Note: If your account is in the Amazon SES  sandbox, the source and
        destination email accounts must both be verified.

        :param source: The source email account.
        :param destination: The destination email account.
        :param template_name: The name of a previously created template.
        :param template_data: JSON-formatted key-value pairs of replacement values
                              that are inserted in the template before it is sent.
        :return: The ID of the message, assigned by Amazon SES.
        """
        send_args = {
            "Source": source,
            "Destination": destination.to_service_format(),
            "Template": template_name,
            "TemplateData": json.dumps(template_data),
        }
        if reply_tos is not None:
            send_args["ReplyToAddresses"] = reply_tos
        try:
            response = self.ses_client.send_templated_email(**send_args)
            message_id = response["MessageId"]
            logger.info(
                "Sent templated mail %s from %s to %s.",
                message_id,
                source,
                destination.tos,
            )
        except ClientError:
            logger.exception(
                "Couldn't send templated mail from %s to %s.", source, destination.tos
            )
            raise
        else:
            return message_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SendTemplatedEmail](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/SendTemplatedEmail)」を参照してください。

### `UpdateTemplate`
<a name="ses_UpdateTemplate_python_3_topic"></a>

次のコード例は、`UpdateTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesTemplate:
    """Encapsulates Amazon SES template functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client
        self.template = None
        self.template_tags = set()

    def _extract_tags(self, subject, text, html):
        """
        Extracts tags from a template as a set of unique values.

        :param subject: The subject of the email.
        :param text: The text version of the email.
        :param html: The html version of the email.
        """
        self.template_tags = set(re.findall(TEMPLATE_REGEX, subject + text + html))
        logger.info("Extracted template tags: %s", self.template_tags)


    def update_template(self, name, subject, text, html):
        """
        Updates a previously created email template.

        :param name: The name of the template.
        :param subject: The subject of the email.
        :param text: The plain text version of the email.
        :param html: The HTML version of the email.
        """
        try:
            template = {
                "TemplateName": name,
                "SubjectPart": subject,
                "TextPart": text,
                "HtmlPart": html,
            }
            self.ses_client.update_template(Template=template)
            logger.info("Updated template %s.", name)
            self.template = template
            self._extract_tags(subject, text, html)
        except ClientError:
            logger.exception("Couldn't update template %s.", name)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/UpdateTemplate)」を参照してください。

### `VerifyDomainIdentity`
<a name="ses_VerifyDomainIdentity_python_3_topic"></a>

次のコード例は、`VerifyDomainIdentity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesIdentity:
    """Encapsulates Amazon SES identity functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def verify_domain_identity(self, domain_name):
        """
        Starts verification of a domain identity. To complete verification, you must
        create a TXT record with a specific format through your DNS provider.

        For more information, see *Verifying a domain with Amazon SES* in the
        Amazon SES documentation:
            https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-domain-procedure.html

        :param domain_name: The name of the domain to verify.
        :return: The token to include in the TXT record with your DNS provider.
        """
        try:
            response = self.ses_client.verify_domain_identity(Domain=domain_name)
            token = response["VerificationToken"]
            logger.info("Got domain verification token for %s.", domain_name)
        except ClientError:
            logger.exception("Couldn't verify domain %s.", domain_name)
            raise
        else:
            return token
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[VerifyDomainIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/VerifyDomainIdentity)」を参照してください。

### `VerifyEmailIdentity`
<a name="ses_VerifyEmailIdentity_python_3_topic"></a>

次のコード例は、`VerifyEmailIdentity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
class SesIdentity:
    """Encapsulates Amazon SES identity functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def verify_email_identity(self, email_address):
        """
        Starts verification of an email identity. This function causes an email
        to be sent to the specified email address from Amazon SES. To complete
        verification, follow the instructions in the email.

        :param email_address: The email address to verify.
        """
        try:
            self.ses_client.verify_email_identity(EmailAddress=email_address)
            logger.info("Started verification of %s.", email_address)
        except ClientError:
            logger.exception("Couldn't start verification of %s.", email_address)
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[VerifyEmailIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/VerifyEmailIdentity)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### リージョン間で E メールとドメイン ID をコピーする
<a name="ses_Scenario_ReplicateIdentities_python_3_topic"></a>

次のコード例は、Amazon SES E メールとドメイン ID をあるリージョンから別の AWS リージョンにコピーする方法を示しています。ドメイン ID が Route 53 で管理されている場合、検証レコードはコピー先リージョンのドメインにコピーされます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
import argparse
import json
import logging
from pprint import pprint
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def get_identities(ses_client):
    """
    Gets the identities for the current Region. The Region is specified in the
    Boto3 Amazon SES client object.

    :param ses_client: A Boto3 Amazon SES client.
    :return: The list of email identities and the list of domain identities.
    """
    email_identities = []
    domain_identities = []
    try:
        identity_paginator = ses_client.get_paginator("list_identities")
        identity_iterator = identity_paginator.paginate(
            PaginationConfig={"PageSize": 20}
        )
        for identity_page in identity_iterator:
            for identity in identity_page["Identities"]:
                if "@" in identity:
                    email_identities.append(identity)
                else:
                    domain_identities.append(identity)
        logger.info(
            "Found %s email and %s domain identities.",
            len(email_identities),
            len(domain_identities),
        )
    except ClientError:
        logger.exception("Couldn't get identities.")
        raise
    else:
        return email_identities, domain_identities


def verify_emails(email_list, ses_client):
    """
    Starts verification of a list of email addresses. Verification causes an email
    to be sent to each address. To complete verification, the recipient must follow
    the instructions in the email.

    :param email_list: The list of email addresses to verify.
    :param ses_client: A Boto3 Amazon SES client.
    :return: The list of emails that were successfully submitted for verification.
    """
    verified_emails = []
    for email in email_list:
        try:
            ses_client.verify_email_identity(EmailAddress=email)
            verified_emails.append(email)
            logger.info("Started verification of %s.", email)
        except ClientError:
            logger.warning("Couldn't start verification of %s.", email)
    return verified_emails


def verify_domains(domain_list, ses_client):
    """
    Starts verification for a list of domain identities. This returns a token for
    each domain, which must be registered as a TXT record with the DNS provider for
    the domain.

    :param domain_list: The list of domains to verify.
    :param ses_client: A Boto3 Amazon SES client.
    :return: The generated domain tokens to use to completed verification.
    """
    domain_tokens = {}
    for domain in domain_list:
        try:
            response = ses_client.verify_domain_identity(Domain=domain)
            token = response["VerificationToken"]
            domain_tokens[domain] = token
            logger.info("Got verification token %s for domain %s.", token, domain)
        except ClientError:
            logger.warning("Couldn't get verification token for domain %s.", domain)
    return domain_tokens


def get_hosted_zones(route53_client):
    """
    Gets the Amazon Route 53 hosted zones for the current account.

    :param route53_client: A Boto3 Route 53 client.
    :return: The list of hosted zones.
    """
    zones = []
    try:
        zone_paginator = route53_client.get_paginator("list_hosted_zones")
        zone_iterator = zone_paginator.paginate(PaginationConfig={"PageSize": 20})
        zones = [
            zone for zone_page in zone_iterator for zone in zone_page["HostedZones"]
        ]
        logger.info("Found %s hosted zones.", len(zones))
    except ClientError:
        logger.warning("Couldn't get hosted zones.")
    return zones


def find_domain_zone_matches(domains, zones):
    """
    Finds matches between Amazon SES verified domains and Route 53 hosted zones.
    Subdomain matches are taken when found, otherwise root domain matches are taken.

    :param domains: The list of domains to match.
    :param zones: The list of hosted zones to match.
    :return: The set of matched domain-zone pairs. When a match is not found, the
             domain is included in the set with a zone value of None.
    """
    domain_zones = {}
    for domain in domains:
        domain_zones[domain] = None
        # Start at the most specific sub-domain and walk up to the root domain until a
        # zone match is found.
        domain_split = domain.split(".")
        for index in range(0, len(domain_split) - 1):
            sub_domain = ".".join(domain_split[index:])
            for zone in zones:
                # Normalize the zone name from Route 53 by removing the trailing '.'.
                zone_name = zone["Name"][:-1]
                if sub_domain == zone_name:
                    domain_zones[domain] = zone
                    break
            if domain_zones[domain] is not None:
                break
    return domain_zones


def add_route53_verification_record(domain, token, zone, route53_client):
    """
    Adds a domain verification TXT record to the specified Route 53 hosted zone.
    When a TXT record already exists in the hosted zone for the specified domain,
    the existing values are preserved and the new token is added to the list.

    :param domain: The domain to add.
    :param token: The verification token for the domain.
    :param zone: The hosted zone where the domain verification record is added.
    :param route53_client: A Boto3 Route 53 client.
    """
    domain_token_record_set_name = f"_amazonses.{domain}"
    record_set_paginator = route53_client.get_paginator("list_resource_record_sets")
    record_set_iterator = record_set_paginator.paginate(
        HostedZoneId=zone["Id"], PaginationConfig={"PageSize": 20}
    )
    records = []
    for record_set_page in record_set_iterator:
        try:
            txt_record_set = next(
                record_set
                for record_set in record_set_page["ResourceRecordSets"]
                if record_set["Name"][:-1] == domain_token_record_set_name
                and record_set["Type"] == "TXT"
            )
            records = txt_record_set["ResourceRecords"]
            logger.info(
                "Existing TXT record found in set %s for zone %s.",
                domain_token_record_set_name,
                zone["Name"],
            )
            break
        except StopIteration:
            pass
    records.append({"Value": json.dumps(token)})
    changes = [
        {
            "Action": "UPSERT",
            "ResourceRecordSet": {
                "Name": domain_token_record_set_name,
                "Type": "TXT",
                "TTL": 1800,
                "ResourceRecords": records,
            },
        }
    ]
    try:
        route53_client.change_resource_record_sets(
            HostedZoneId=zone["Id"], ChangeBatch={"Changes": changes}
        )
        logger.info(
            "Created or updated the TXT record in set %s for zone %s.",
            domain_token_record_set_name,
            zone["Name"],
        )
    except ClientError as err:
        logger.warning(
            "Got error %s. Couldn't create or update the TXT record for zone %s.",
            err.response["Error"]["Code"],
            zone["Name"],
        )


def generate_dkim_tokens(domain, ses_client):
    """
    Generates DKIM tokens for a domain. These must be added as CNAME records to the
    DNS provider for the domain.

    :param domain: The domain to generate tokens for.
    :param ses_client: A Boto3 Amazon SES client.
    :return: The list of generated DKIM tokens.
    """
    dkim_tokens = []
    try:
        dkim_tokens = ses_client.verify_domain_dkim(Domain=domain)["DkimTokens"]
        logger.info("Generated %s DKIM tokens for domain %s.", len(dkim_tokens), domain)
    except ClientError:
        logger.warning("Couldn't generate DKIM tokens for domain %s.", domain)
    return dkim_tokens


def add_dkim_domain_tokens(hosted_zone, domain, tokens, route53_client):
    """
    Adds DKIM domain token CNAME records to a Route 53 hosted zone.

    :param hosted_zone: The hosted zone where the records are added.
    :param domain: The domain to add.
    :param tokens: The DKIM tokens for the domain to add.
    :param route53_client: A Boto3 Route 53 client.
    """
    try:
        changes = [
            {
                "Action": "UPSERT",
                "ResourceRecordSet": {
                    "Name": f"{token}._domainkey.{domain}",
                    "Type": "CNAME",
                    "TTL": 1800,
                    "ResourceRecords": [{"Value": f"{token}.dkim.amazonses.com"}],
                },
            }
            for token in tokens
        ]
        route53_client.change_resource_record_sets(
            HostedZoneId=hosted_zone["Id"], ChangeBatch={"Changes": changes}
        )
        logger.info(
            "Added %s DKIM CNAME records to %s in zone %s.",
            len(tokens),
            domain,
            hosted_zone["Name"],
        )
    except ClientError:
        logger.warning(
            "Couldn't add DKIM CNAME records for %s to zone %s.",
            domain,
            hosted_zone["Name"],
        )


def configure_sns_topics(identity, topics, ses_client):
    """
    Configures Amazon Simple Notification Service (Amazon SNS) notifications for
    an identity. The Amazon SNS topics must already exist.

    :param identity: The identity to configure.
    :param topics: The list of topics to configure. The choices are Bounce, Delivery,
                   or Complaint.
    :param ses_client: A Boto3 Amazon SES client.
    """
    for topic in topics:
        topic_arn = input(
            f"Enter the Amazon Resource Name (ARN) of the {topic} topic or press "
            f"Enter to skip: "
        )
        if topic_arn != "":
            try:
                ses_client.set_identity_notification_topic(
                    Identity=identity, NotificationType=topic, SnsTopic=topic_arn
                )
                logger.info("Configured %s for %s notifications.", identity, topic)
            except ClientError:
                logger.warning(
                    "Couldn't configure %s for %s notifications.", identity, topic
                )


def replicate(source_client, destination_client, route53_client):
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    print("-" * 88)
    print(
        f"Replicating Amazon SES identities and other configuration from "
        f"{source_client.meta.region_name} to {destination_client.meta.region_name}."
    )
    print("-" * 88)

    print(f"Retrieving identities from {source_client.meta.region_name}.")
    source_emails, source_domains = get_identities(source_client)
    print("Email addresses found:")
    print(*source_emails)
    print("Domains found:")
    print(*source_domains)

    print("Starting verification for email identities.")
    dest_emails = verify_emails(source_emails, destination_client)
    print("Getting domain tokens for domain identities.")
    dest_domain_tokens = verify_domains(source_domains, destination_client)

    # Get Route 53 hosted zones and match them with Amazon SES domains.
    answer = input(
        "Is the DNS configuration for your domains managed by Amazon Route 53 (y/n)? "
    )
    use_route53 = answer.lower() == "y"
    hosted_zones = get_hosted_zones(route53_client) if use_route53 else []
    if use_route53:
        print("Adding or updating Route 53 TXT records for your domains.")
        domain_zones = find_domain_zone_matches(dest_domain_tokens.keys(), hosted_zones)
        for domain in domain_zones:
            add_route53_verification_record(
                domain, dest_domain_tokens[domain], domain_zones[domain], route53_client
            )
    else:
        print(
            "Use these verification tokens to create TXT records through your DNS "
            "provider:"
        )
        pprint(dest_domain_tokens)

    answer = input("Do you want to configure DKIM signing for your identities (y/n)? ")
    if answer.lower() == "y":
        # Build a set of unique domains from email and domain identities.
        domains = {email.split("@")[1] for email in dest_emails}
        domains.update(dest_domain_tokens)
        domain_zones = find_domain_zone_matches(domains, hosted_zones)
        for domain, zone in domain_zones.items():
            answer = input(
                f"Do you want to configure DKIM signing for {domain} (y/n)? "
            )
            if answer.lower() == "y":
                dkim_tokens = generate_dkim_tokens(domain, destination_client)
                if use_route53 and zone is not None:
                    add_dkim_domain_tokens(zone, domain, dkim_tokens, route53_client)
                else:
                    print(
                        "Add the following DKIM tokens as CNAME records through your "
                        "DNS provider:"
                    )
                    print(*dkim_tokens, sep="\n")

    answer = input(
        "Do you want to configure Amazon SNS notifications for your identities (y/n)? "
    )
    if answer.lower() == "y":
        for identity in dest_emails + list(dest_domain_tokens.keys()):
            answer = input(
                f"Do you want to configure Amazon SNS topics for {identity} (y/n)? "
            )
            if answer.lower() == "y":
                configure_sns_topics(
                    identity, ["Bounce", "Delivery", "Complaint"], destination_client
                )

    print(f"Replication complete for {destination_client.meta.region_name}.")
    print("-" * 88)


def main():
    boto3_session = boto3.Session()
    ses_regions = boto3_session.get_available_regions("ses")
    parser = argparse.ArgumentParser(
        description="Copies email address and domain identities from one AWS Region to "
        "another. Optionally adds records for domain verification and DKIM "
        "signing to domains that are managed by Amazon Route 53, "
        "and sets up Amazon SNS notifications for events of interest."
    )
    parser.add_argument(
        "source_region", choices=ses_regions, help="The region to copy from."
    )
    parser.add_argument(
        "destination_region", choices=ses_regions, help="The region to copy to."
    )
    args = parser.parse_args()
    source_client = boto3.client("ses", region_name=args.source_region)
    destination_client = boto3.client("ses", region_name=args.destination_region)
    route53_client = boto3.client("route53")
    replicate(source_client, destination_client, route53_client)


if __name__ == "__main__":
    main()
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [ListIdentities](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/ListIdentities)
  + [SetIdentityNotificationTopic](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/SetIdentityNotificationTopic)
  + [VerifyDomainDkim](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/VerifyDomainDkim)
  + [VerifyDomainIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/VerifyDomainIdentity)
  + [VerifyEmailIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/VerifyEmailIdentity)

### DynamoDB データを追跡するウェブアプリケーションを作成する
<a name="cross_DynamoDBDataTracker_python_3_topic"></a>

次のコード例は、Amazon DynamoDB テーブルの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して AWS SDK for Python (Boto3) Amazon DynamoDB の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信する REST サービスを作成する方法を示します。この例では、Flask ウェブフレームワークを使用して HTTP ルーティングを処理し、React ウェブページと統合して完全に機能するウェブアプリケーションを提供しています。  
+ と統合する Flask REST サービスを構築します AWS のサービス。
+ DynamoDB テーブルに保存されている作業項目の読み取り、書き込み、更新を行います。
+ Amazon SES を使用して作業項目のレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、GitHub の「[AWS コード例のレポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/dynamodb_item_tracker)」で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon SES

### Aurora Serverless 作業項目トラッカーの作成
<a name="cross_RDSDataTracker_python_3_topic"></a>

次のコード例は、Amazon Aurora Serverless データベースの作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを送信するウェブアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して Amazon Aurora Serverless データベース内の作業項目を追跡し、Amazon Simple Email Service (Amazon SES) を使用してレポートを E メールで送信する REST サービス AWS SDK for Python (Boto3) を作成する方法を示します。この例では、Flask ウェブフレームワークを使用して HTTP ルーティングを処理し、React ウェブページと統合して完全に機能するウェブアプリケーションを提供しています。  
+ と統合する Flask REST サービスを構築します AWS のサービス。
+ Aurora Serverless データベースに保存されている作業項目の読み取り、書き込み、更新を行います。
+ データベース認証情報を含む AWS Secrets Manager シークレットを作成し、それを使用してデータベースへの呼び出しを認証します。
+ Amazon SES を使用して作業項目のレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/aurora_item_tracker) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Aurora
+ Amazon RDS
+ Amazon RDS データサービス
+ Amazon SES

### 画像内のオブジェクトを検出する
<a name="cross_RekognitionPhotoAnalyzer_python_3_topic"></a>

次のコード例は、Amazon Rekognition を使用して画像内でカテゴリ別にオブジェクトを検出するアプリケーションを構築する方法を示しています。

**SDK for Python (Boto3)**  
 を使用して AWS SDK for Python (Boto3) 、以下を可能にするウェブアプリケーションを作成する方法を示します。  
+ Amazon Simple Storage Service (Amazon S3) バケットに、写真をアップロードします。
+ Amazon Rekognition を使用して、写真を分析およびラベル付けします。
+ Amazon Simple Email Service (Amazon SES) を使用して、イメージ分析の E メールレポートを送信します。
 この例には、React で構築された JavaScript で記述されたウェブページと、Flask-RESTful で構築された Python で記述された REST サービスの 2 つの主要なコンポーネントが含まれています。  
React ウェブページを使用すると、次のことができます。  
+ S3 バケットに保存されているイメージのリストを表示します。
+ イメージを S3 バケットにアップロードします。
+ イメージ内で検出された項目を識別するイメージとラベルを表示します。
+ S3 バケット内のすべてのイメージのレポートを取得し、レポートの E メールを送信します。
ウェブページが REST サービスを呼び出します。サービスはリクエストを AWS に送信して、以下のアクションを実行します。  
+ S3 バケット内のイメージのリストを取得し、フィルタリングします。
+ Amazon S3 バケットに写真をアップロードします。
+ Amazon Rekognition を使用して個々の写真を分析し、写真で検出された項目を識別するラベルのリストを取得します。
+ S3 バケット内のすべての写真を分析し、Amazon SES を使用してレポートを E メールで送信します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/photo_analyzer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_python_3_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Python (Boto3)**  
 Amazon Rekognition を使用して、非同期検出ジョブを開始して、動画内の顔、オブジェクト、人を検出します。この例では、ジョブが完了し、Amazon Simple Queue Service (Amazon SQS) キューをトピックにサブスクライブしたときに、Amazon Simple Notification Service (Amazon SNS) トピックに通知するように Amazon Rekognition を設定します。キューがジョブに関するメッセージを受信すると、ジョブが取得され、結果が出力されます。  
 この例は GitHub で最もよく見られます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### SMTP エンドポイントに接続するための認証情報を生成する
<a name="ses_Scenario_GenerateSmtpCredentials_python_3_topic"></a>

次のコード例は、Amazon SES SMTP エンドポイントに接続するための認証情報を生成する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。

```
#!/usr/bin/env python3

import hmac
import hashlib
import base64
import argparse

SMTP_REGIONS = [
    "us-east-2",  # US East (Ohio)
    "us-east-1",  # US East (N. Virginia)
    "us-west-2",  # US West (Oregon)
    "ap-south-1",  # Asia Pacific (Mumbai)
    "ap-northeast-2",  # Asia Pacific (Seoul)
    "ap-southeast-1",  # Asia Pacific (Singapore)
    "ap-southeast-2",  # Asia Pacific (Sydney)
    "ap-northeast-1",  # Asia Pacific (Tokyo)
    "ca-central-1",  # Canada (Central)
    "eu-central-1",  # Europe (Frankfurt)
    "eu-west-1",  # Europe (Ireland)
    "eu-west-2",  # Europe (London)
    "eu-south-1",  # Europe (Milan)
    "eu-north-1",  # Europe (Stockholm)
    "sa-east-1",  # South America (Sao Paulo)
    "us-gov-west-1",  # AWS GovCloud (US)
    "us-gov-east-1",  # AWS GovCloud (US)
]

# These values are required to calculate the signature. Do not change them.
DATE = "11111111"
SERVICE = "ses"
MESSAGE = "SendRawEmail"
TERMINAL = "aws4_request"
VERSION = 0x04


def sign(key, msg):
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()


def calculate_key(secret_access_key, region):
    if region not in SMTP_REGIONS:
        raise ValueError(f"The {region} Region doesn't have an SMTP endpoint.")

    signature = sign(("AWS4" + secret_access_key).encode("utf-8"), DATE)
    signature = sign(signature, region)
    signature = sign(signature, SERVICE)
    signature = sign(signature, TERMINAL)
    signature = sign(signature, MESSAGE)
    signature_and_version = bytes([VERSION]) + signature
    smtp_password = base64.b64encode(signature_and_version)
    return smtp_password.decode("utf-8")


def main():
    parser = argparse.ArgumentParser(
        description="Convert a Secret Access Key to an SMTP password."
    )
    parser.add_argument("secret", help="The Secret Access Key to convert.")
    parser.add_argument(
        "region",
        help="The AWS Region where the SMTP password will be used.",
        choices=SMTP_REGIONS,
    )
    args = parser.parse_args()
    print(calculate_key(args.secret, args.region))


if __name__ == "__main__":
    main()
```

### E メール ID を検証してメッセージを送信する
<a name="ses_Scenario_SendEmail_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon SES で E メールアドレスを追加し、検証します。
+ 標準の E メールメッセージを送信します。
+ テンプレートを作成し、テンプレート化された E メールメッセージを送信します。
+ Amazon SES SMTP サーバーを使用してメッセージを送信します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ses#code-examples)での設定と実行の方法を確認してください。
Amazon SES で E メールアドレスを検証し、メッセージを送信します。  

```
def usage_demo():
    print("-" * 88)
    print("Welcome to the Amazon Simple Email Service (Amazon SES) email demo!")
    print("-" * 88)

    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    ses_client = boto3.client("ses")
    ses_identity = SesIdentity(ses_client)
    ses_mail_sender = SesMailSender(ses_client)
    ses_template = SesTemplate(ses_client)
    email = input("Enter an email address to send mail with Amazon SES: ")
    status = ses_identity.get_identity_status(email)
    verified = status == "Success"
    if not verified:
        answer = input(
            f"The address '{email}' is not verified with Amazon SES. Unless your "
            f"Amazon SES account is out of sandbox, you can send mail only from "
            f"and to verified accounts. Do you want to verify this account for use "
            f"with Amazon SES? If yes, the address will receive a verification "
            f"email (y/n): "
        )
        if answer.lower() == "y":
            ses_identity.verify_email_identity(email)
            print(f"Follow the steps in the email to {email} to complete verification.")
            print("Waiting for verification...")
            try:
                ses_identity.wait_until_identity_exists(email)
                print(f"Identity verified for {email}.")
                verified = True
            except WaiterError:
                print(
                    f"Verification timeout exceeded. You must complete the "
                    f"steps in the email sent to {email} to verify the address."
                )

    if verified:
        test_message_text = "Hello from the Amazon SES mail demo!"
        test_message_html = "<p>Hello!</p><p>From the <b>Amazon SES</b> mail demo!</p>"

        print(f"Sending mail from {email} to {email}.")
        ses_mail_sender.send_email(
            email,
            SesDestination([email]),
            "Amazon SES demo",
            test_message_text,
            test_message_html,
        )
        input("Mail sent. Check your inbox and press Enter to continue.")

        template = {
            "name": "doc-example-template",
            "subject": "Example of an email template.",
            "text": "This is what {{name}} will {{action}} if {{name}} can't display "
            "HTML.",
            "html": "<p><i>This</i> is what {{name}} will {{action}} if {{name}} "
            "<b>can</b> display HTML.</p>",
        }
        print("Creating a template and sending a templated email.")
        ses_template.create_template(**template)
        template_data = {"name": email.split("@")[0], "action": "read"}
        if ses_template.verify_tags(template_data):
            ses_mail_sender.send_templated_email(
                email, SesDestination([email]), ses_template.name(), template_data
            )
            input("Mail sent. Check your inbox and press Enter to continue.")

        print("Sending mail through the Amazon SES SMTP server.")
        boto3_session = boto3.Session()
        region = boto3_session.region_name
        credentials = boto3_session.get_credentials()
        port = 587
        smtp_server = f"email-smtp.{region}.amazonaws.com"
        password = calculate_key(credentials.secret_key, region)
        message = """
Subject: Hi there

This message is sent from the Amazon SES SMTP mail demo."""
        context = ssl.create_default_context()
        with smtplib.SMTP(smtp_server, port) as server:
            server.starttls(context=context)
            server.login(credentials.access_key, password)
            server.sendmail(email, email, message)
        print("Mail sent. Check your inbox!")

    if ses_template.template is not None:
        print("Deleting demo template.")
        ses_template.delete_template()
    if verified:
        answer = input(f"Do you want to remove {email} from Amazon SES (y/n)? ")
        if answer.lower() == "y":
            ses_identity.delete_identity(email)
    print("Thanks for watching!")
    print("-" * 88)
```
Amazon SES の ID アクションをラップする関数を作成します。  

```
class SesIdentity:
    """Encapsulates Amazon SES identity functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def verify_domain_identity(self, domain_name):
        """
        Starts verification of a domain identity. To complete verification, you must
        create a TXT record with a specific format through your DNS provider.

        For more information, see *Verifying a domain with Amazon SES* in the
        Amazon SES documentation:
            https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-domain-procedure.html

        :param domain_name: The name of the domain to verify.
        :return: The token to include in the TXT record with your DNS provider.
        """
        try:
            response = self.ses_client.verify_domain_identity(Domain=domain_name)
            token = response["VerificationToken"]
            logger.info("Got domain verification token for %s.", domain_name)
        except ClientError:
            logger.exception("Couldn't verify domain %s.", domain_name)
            raise
        else:
            return token


    def verify_email_identity(self, email_address):
        """
        Starts verification of an email identity. This function causes an email
        to be sent to the specified email address from Amazon SES. To complete
        verification, follow the instructions in the email.

        :param email_address: The email address to verify.
        """
        try:
            self.ses_client.verify_email_identity(EmailAddress=email_address)
            logger.info("Started verification of %s.", email_address)
        except ClientError:
            logger.exception("Couldn't start verification of %s.", email_address)
            raise


    def wait_until_identity_exists(self, identity):
        """
        Waits until an identity exists. The waiter polls Amazon SES until the
        identity has been successfully verified or until it exceeds its maximum time.

        :param identity: The identity to wait for.
        """
        try:
            waiter = self.ses_client.get_waiter("identity_exists")
            logger.info("Waiting until %s exists.", identity)
            waiter.wait(Identities=[identity])
        except WaiterError:
            logger.error("Waiting for identity %s failed or timed out.", identity)
            raise


    def get_identity_status(self, identity):
        """
        Gets the status of an identity. This can be used to discover whether
        an identity has been successfully verified.

        :param identity: The identity to query.
        :return: The status of the identity.
        """
        try:
            response = self.ses_client.get_identity_verification_attributes(
                Identities=[identity]
            )
            status = response["VerificationAttributes"].get(
                identity, {"VerificationStatus": "NotFound"}
            )["VerificationStatus"]
            logger.info("Got status of %s for %s.", status, identity)
        except ClientError:
            logger.exception("Couldn't get status for %s.", identity)
            raise
        else:
            return status


    def delete_identity(self, identity):
        """
        Deletes an identity.

        :param identity: The identity to remove.
        """
        try:
            self.ses_client.delete_identity(Identity=identity)
            logger.info("Deleted identity %s.", identity)
        except ClientError:
            logger.exception("Couldn't delete identity %s.", identity)
            raise


    def list_identities(self, identity_type, max_items):
        """
        Gets the identities of the specified type for the current account.

        :param identity_type: The type of identity to retrieve, such as EmailAddress.
        :param max_items: The maximum number of identities to retrieve.
        :return: The list of retrieved identities.
        """
        try:
            response = self.ses_client.list_identities(
                IdentityType=identity_type, MaxItems=max_items
            )
            identities = response["Identities"]
            logger.info("Got %s identities for the current account.", len(identities))
        except ClientError:
            logger.exception("Couldn't list identities for the current account.")
            raise
        else:
            return identities
```
Amazon SES テンプレートのアクションをラップする関数を作成します。  

```
class SesTemplate:
    """Encapsulates Amazon SES template functions."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client
        self.template = None
        self.template_tags = set()

    def _extract_tags(self, subject, text, html):
        """
        Extracts tags from a template as a set of unique values.

        :param subject: The subject of the email.
        :param text: The text version of the email.
        :param html: The html version of the email.
        """
        self.template_tags = set(re.findall(TEMPLATE_REGEX, subject + text + html))
        logger.info("Extracted template tags: %s", self.template_tags)


    def create_template(self, name, subject, text, html):
        """
        Creates an email template.

        :param name: The name of the template.
        :param subject: The subject of the email.
        :param text: The plain text version of the email.
        :param html: The HTML version of the email.
        """
        try:
            template = {
                "TemplateName": name,
                "SubjectPart": subject,
                "TextPart": text,
                "HtmlPart": html,
            }
            self.ses_client.create_template(Template=template)
            logger.info("Created template %s.", name)
            self.template = template
            self._extract_tags(subject, text, html)
        except ClientError:
            logger.exception("Couldn't create template %s.", name)
            raise


    def delete_template(self):
        """
        Deletes an email template.
        """
        try:
            self.ses_client.delete_template(TemplateName=self.template["TemplateName"])
            logger.info("Deleted template %s.", self.template["TemplateName"])
            self.template = None
            self.template_tags = None
        except ClientError:
            logger.exception(
                "Couldn't delete template %s.", self.template["TemplateName"]
            )
            raise


    def get_template(self, name):
        """
        Gets a previously created email template.

        :param name: The name of the template to retrieve.
        :return: The retrieved email template.
        """
        try:
            response = self.ses_client.get_template(TemplateName=name)
            self.template = response["Template"]
            logger.info("Got template %s.", name)
            self._extract_tags(
                self.template["SubjectPart"],
                self.template["TextPart"],
                self.template["HtmlPart"],
            )
        except ClientError:
            logger.exception("Couldn't get template %s.", name)
            raise
        else:
            return self.template


    def list_templates(self):
        """
        Gets a list of all email templates for the current account.

        :return: The list of retrieved email templates.
        """
        try:
            response = self.ses_client.list_templates()
            templates = response["TemplatesMetadata"]
            logger.info("Got %s templates.", len(templates))
        except ClientError:
            logger.exception("Couldn't get templates.")
            raise
        else:
            return templates


    def update_template(self, name, subject, text, html):
        """
        Updates a previously created email template.

        :param name: The name of the template.
        :param subject: The subject of the email.
        :param text: The plain text version of the email.
        :param html: The HTML version of the email.
        """
        try:
            template = {
                "TemplateName": name,
                "SubjectPart": subject,
                "TextPart": text,
                "HtmlPart": html,
            }
            self.ses_client.update_template(Template=template)
            logger.info("Updated template %s.", name)
            self.template = template
            self._extract_tags(subject, text, html)
        except ClientError:
            logger.exception("Couldn't update template %s.", name)
            raise
```
Amazon SES の E メールアクションをラップする関数を作成します。  

```
class SesDestination:
    """Contains data about an email destination."""

    def __init__(self, tos, ccs=None, bccs=None):
        """
        :param tos: The list of recipients on the 'To:' line.
        :param ccs: The list of recipients on the 'CC:' line.
        :param bccs: The list of recipients on the 'BCC:' line.
        """
        self.tos = tos
        self.ccs = ccs
        self.bccs = bccs

    def to_service_format(self):
        """
        :return: The destination data in the format expected by Amazon SES.
        """
        svc_format = {"ToAddresses": self.tos}
        if self.ccs is not None:
            svc_format["CcAddresses"] = self.ccs
        if self.bccs is not None:
            svc_format["BccAddresses"] = self.bccs
        return svc_format



class SesMailSender:
    """Encapsulates functions to send emails with Amazon SES."""

    def __init__(self, ses_client):
        """
        :param ses_client: A Boto3 Amazon SES client.
        """
        self.ses_client = ses_client


    def send_email(self, source, destination, subject, text, html, reply_tos=None):
        """
        Sends an email.

        Note: If your account is in the Amazon SES  sandbox, the source and
        destination email accounts must both be verified.

        :param source: The source email account.
        :param destination: The destination email account.
        :param subject: The subject of the email.
        :param text: The plain text version of the body of the email.
        :param html: The HTML version of the body of the email.
        :param reply_tos: Email accounts that will receive a reply if the recipient
                          replies to the message.
        :return: The ID of the message, assigned by Amazon SES.
        """
        send_args = {
            "Source": source,
            "Destination": destination.to_service_format(),
            "Message": {
                "Subject": {"Data": subject},
                "Body": {"Text": {"Data": text}, "Html": {"Data": html}},
            },
        }
        if reply_tos is not None:
            send_args["ReplyToAddresses"] = reply_tos
        try:
            response = self.ses_client.send_email(**send_args)
            message_id = response["MessageId"]
            logger.info(
                "Sent mail %s from %s to %s.", message_id, source, destination.tos
            )
        except ClientError:
            logger.exception(
                "Couldn't send mail from %s to %s.", source, destination.tos
            )
            raise
        else:
            return message_id


    def send_templated_email(
        self, source, destination, template_name, template_data, reply_tos=None
    ):
        """
        Sends an email based on a template. A template contains replaceable tags
        each enclosed in two curly braces, such as {{name}}. The template data passed
        in this function contains key-value pairs that define the values to insert
        in place of the template tags.

        Note: If your account is in the Amazon SES  sandbox, the source and
        destination email accounts must both be verified.

        :param source: The source email account.
        :param destination: The destination email account.
        :param template_name: The name of a previously created template.
        :param template_data: JSON-formatted key-value pairs of replacement values
                              that are inserted in the template before it is sent.
        :return: The ID of the message, assigned by Amazon SES.
        """
        send_args = {
            "Source": source,
            "Destination": destination.to_service_format(),
            "Template": template_name,
            "TemplateData": json.dumps(template_data),
        }
        if reply_tos is not None:
            send_args["ReplyToAddresses"] = reply_tos
        try:
            response = self.ses_client.send_templated_email(**send_args)
            message_id = response["MessageId"]
            logger.info(
                "Sent templated mail %s from %s to %s.",
                message_id,
                source,
                destination.tos,
            )
        except ClientError:
            logger.exception(
                "Couldn't send templated mail from %s to %s.", source, destination.tos
            )
            raise
        else:
            return message_id
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/CreateTemplate)
  + [DeleteIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DeleteIdentity)
  + [DeleteTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/DeleteTemplate)
  + [GetIdentityVerificationAttributes](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/GetIdentityVerificationAttributes)
  + [GetTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/GetTemplate)
  + [ListIdentities](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/ListIdentities)
  + [ListTemplates](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/ListTemplates)
  + [SendEmail](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/SendEmail)
  + [SendTemplatedEmail](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/SendTemplatedEmail)
  + [UpdateTemplate](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/UpdateTemplate)
  + [VerifyDomainIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/VerifyDomainIdentity)
  + [VerifyEmailIdentity](https://docs.aws.amazon.com/goto/boto3/email-2010-12-01/VerifyEmailIdentity)

# SDK for Python (Boto3) を使用する Amazon SES API v2 の例
<a name="python_3_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateContact`
<a name="sesv2_CreateContact_python_3_topic"></a>

次のコード例は、`CreateContact` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


            try:
                # Create a new contact
                self.ses_client.create_contact(
                    ContactListName=CONTACT_LIST_NAME, EmailAddress=email
                )
                print(f"Contact with email '{email}' created successfully.")

                # Send the welcome email
                self.ses_client.send_email(
                    FromEmailAddress=self.verified_email,
                    Destination={"ToAddresses": [email]},
                    Content={
                        "Simple": {
                            "Subject": {
                                "Data": "Welcome to the Weekly Coupons Newsletter"
                            },
                            "Body": {
                                "Text": {"Data": welcome_text},
                                "Html": {"Data": welcome_html},
                            },
                        }
                    },
                )
                print(f"Welcome email sent to '{email}'.")
                if self.sleep:
                    # 1 email per second in sandbox mode, remove in production.
                    sleep(1.1)
            except ClientError as e:
                # If the contact already exists, skip and proceed
                if e.response["Error"]["Code"] == "AlreadyExistsException":
                    print(f"Contact with email '{email}' already exists. Skipping...")
                else:
                    raise e
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateContact](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateContact)」を参照してください。

### `CreateContactList`
<a name="sesv2_CreateContactList_python_3_topic"></a>

次のコード例は、`CreateContactList` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


        try:
            self.ses_client.create_contact_list(ContactListName=CONTACT_LIST_NAME)
            print(f"Contact list '{CONTACT_LIST_NAME}' created successfully.")
        except ClientError as e:
            # If the contact list already exists, skip and proceed
            if e.response["Error"]["Code"] == "AlreadyExistsException":
                print(f"Contact list '{CONTACT_LIST_NAME}' already exists.")
            else:
                raise e
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateContactList](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateContactList)」を参照してください。

### `CreateEmailIdentity`
<a name="sesv2_CreateEmailIdentity_python_3_topic"></a>

次のコード例は、`CreateEmailIdentity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


        try:
            self.ses_client.create_email_identity(EmailIdentity=self.verified_email)
            print(f"Email identity '{self.verified_email}' created successfully.")
        except ClientError as e:
            # If the email identity already exists, skip and proceed
            if e.response["Error"]["Code"] == "AlreadyExistsException":
                print(f"Email identity '{self.verified_email}' already exists.")
            else:
                raise e
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateEmailIdentity](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateEmailIdentity)」を参照してください。

### `CreateEmailTemplate`
<a name="sesv2_CreateEmailTemplate_python_3_topic"></a>

次のコード例は、`CreateEmailTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


        try:
            template_content = {
                "Subject": "Weekly Coupons Newsletter",
                "Html": load_file_content("coupon-newsletter.html"),
                "Text": load_file_content("coupon-newsletter.txt"),
            }
            self.ses_client.create_email_template(
                TemplateName=TEMPLATE_NAME, TemplateContent=template_content
            )
            print(f"Email template '{TEMPLATE_NAME}' created successfully.")
        except ClientError as e:
            # If the template already exists, skip and proceed
            if e.response["Error"]["Code"] == "AlreadyExistsException":
                print(f"Email template '{TEMPLATE_NAME}' already exists.")
            else:
                raise e
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateEmailTemplate](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateEmailTemplate)」を参照してください。

### `DeleteContactList`
<a name="sesv2_DeleteContactList_python_3_topic"></a>

次のコード例は、`DeleteContactList` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


        try:
            self.ses_client.delete_contact_list(ContactListName=CONTACT_LIST_NAME)
            print(f"Contact list '{CONTACT_LIST_NAME}' deleted successfully.")
        except ClientError as e:
            # If the contact list doesn't exist, skip and proceed
            if e.response["Error"]["Code"] == "NotFoundException":
                print(f"Contact list '{CONTACT_LIST_NAME}' does not exist.")
            else:
                print(e)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteContactList](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/DeleteContactList)」を参照してください。

### `DeleteEmailIdentity`
<a name="sesv2_DeleteEmailIdentity_python_3_topic"></a>

次のコード例は、`DeleteEmailIdentity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


            try:
                self.ses_client.delete_email_identity(EmailIdentity=self.verified_email)
                print(f"Email identity '{self.verified_email}' deleted successfully.")
            except ClientError as e:
                # If the email identity doesn't exist, skip and proceed
                if e.response["Error"]["Code"] == "NotFoundException":
                    print(f"Email identity '{self.verified_email}' does not exist.")
                else:
                    print(e)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteEmailIdentity](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/DeleteEmailIdentity)」を参照してください。

### `DeleteEmailTemplate`
<a name="sesv2_DeleteEmailTemplate_python_3_topic"></a>

次のコード例は、`DeleteEmailTemplate` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


        try:
            self.ses_client.delete_email_template(TemplateName=TEMPLATE_NAME)
            print(f"Email template '{TEMPLATE_NAME}' deleted successfully.")
        except ClientError as e:
            # If the email template doesn't exist, skip and proceed
            if e.response["Error"]["Code"] == "NotFoundException":
                print(f"Email template '{TEMPLATE_NAME}' does not exist.")
            else:
                print(e)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteEmailTemplate](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/DeleteEmailTemplate)」を参照してください。

### `ListContacts`
<a name="sesv2_ListContacts_python_3_topic"></a>

次のコード例は、`ListContacts` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


        try:
            contacts_response = self.ses_client.list_contacts(
                ContactListName=CONTACT_LIST_NAME
            )
        except ClientError as e:
            if e.response["Error"]["Code"] == "NotFoundException":
                print(f"Contact list '{CONTACT_LIST_NAME}' does not exist.")
                return
            else:
                raise e
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListContacts](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/ListContacts)」を参照してください。

### `SendEmail`
<a name="sesv2_SendEmail_python_3_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。
連絡先リストのすべてのメンバーにメッセージを送信します。  

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


                self.ses_client.send_email(
                    FromEmailAddress=self.verified_email,
                    Destination={"ToAddresses": [email]},
                    Content={
                        "Simple": {
                            "Subject": {
                                "Data": "Welcome to the Weekly Coupons Newsletter"
                            },
                            "Body": {
                                "Text": {"Data": welcome_text},
                                "Html": {"Data": welcome_html},
                            },
                        }
                    },
                )
                print(f"Welcome email sent to '{email}'.")
```
テンプレートを使用して、連絡先リストのメンバー全員にメッセージを送信します。  

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


                self.ses_client.send_email(
                    FromEmailAddress=self.verified_email,
                    Destination={"ToAddresses": [email_address]},
                    Content={
                        "Template": {
                            "TemplateName": TEMPLATE_NAME,
                            "TemplateData": coupon_items,
                        }
                    },
                    ListManagementOptions={"ContactListName": CONTACT_LIST_NAME},
                )
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SendEmail](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/SendEmail)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ニュースレターのシナリオ
<a name="sesv2_NewsletterWorkflow_python_3_topic"></a>

以下のコード例は、Amazon SES API v2 のニュースレターのシナリオを実行する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sesv2#code-examples)での設定と実行の方法を確認してください。

```
def main():
    """
    The main function that orchestrates the execution of the workflow.
    """
    print(INTRO)
    ses_client = boto3.client("sesv2")
    workflow = SESv2Workflow(ses_client)
    try:
        workflow.prepare_application()
        workflow.gather_subscriber_email_addresses()
        workflow.send_coupon_newsletter()
        workflow.monitor_and_review()
    except ClientError as e:
        print_error(e)
    workflow.clean_up()



class SESv2Workflow:
    """
    A class to manage the SES v2 Coupon Newsletter Workflow.
    """

    def __init__(self, ses_client, sleep=True):
        self.ses_client = ses_client
        self.sleep = sleep


        try:
            self.ses_client.create_contact_list(ContactListName=CONTACT_LIST_NAME)
            print(f"Contact list '{CONTACT_LIST_NAME}' created successfully.")
        except ClientError as e:
            # If the contact list already exists, skip and proceed
            if e.response["Error"]["Code"] == "AlreadyExistsException":
                print(f"Contact list '{CONTACT_LIST_NAME}' already exists.")
            else:
                raise e

            try:
                # Create a new contact
                self.ses_client.create_contact(
                    ContactListName=CONTACT_LIST_NAME, EmailAddress=email
                )
                print(f"Contact with email '{email}' created successfully.")

                # Send the welcome email
                self.ses_client.send_email(
                    FromEmailAddress=self.verified_email,
                    Destination={"ToAddresses": [email]},
                    Content={
                        "Simple": {
                            "Subject": {
                                "Data": "Welcome to the Weekly Coupons Newsletter"
                            },
                            "Body": {
                                "Text": {"Data": welcome_text},
                                "Html": {"Data": welcome_html},
                            },
                        }
                    },
                )
                print(f"Welcome email sent to '{email}'.")
                if self.sleep:
                    # 1 email per second in sandbox mode, remove in production.
                    sleep(1.1)
            except ClientError as e:
                # If the contact already exists, skip and proceed
                if e.response["Error"]["Code"] == "AlreadyExistsException":
                    print(f"Contact with email '{email}' already exists. Skipping...")
                else:
                    raise e

        try:
            contacts_response = self.ses_client.list_contacts(
                ContactListName=CONTACT_LIST_NAME
            )
        except ClientError as e:
            if e.response["Error"]["Code"] == "NotFoundException":
                print(f"Contact list '{CONTACT_LIST_NAME}' does not exist.")
                return
            else:
                raise e

                self.ses_client.send_email(
                    FromEmailAddress=self.verified_email,
                    Destination={"ToAddresses": [email]},
                    Content={
                        "Simple": {
                            "Subject": {
                                "Data": "Welcome to the Weekly Coupons Newsletter"
                            },
                            "Body": {
                                "Text": {"Data": welcome_text},
                                "Html": {"Data": welcome_html},
                            },
                        }
                    },
                )
                print(f"Welcome email sent to '{email}'.")

                self.ses_client.send_email(
                    FromEmailAddress=self.verified_email,
                    Destination={"ToAddresses": [email_address]},
                    Content={
                        "Template": {
                            "TemplateName": TEMPLATE_NAME,
                            "TemplateData": coupon_items,
                        }
                    },
                    ListManagementOptions={"ContactListName": CONTACT_LIST_NAME},
                )

        try:
            self.ses_client.create_email_identity(EmailIdentity=self.verified_email)
            print(f"Email identity '{self.verified_email}' created successfully.")
        except ClientError as e:
            # If the email identity already exists, skip and proceed
            if e.response["Error"]["Code"] == "AlreadyExistsException":
                print(f"Email identity '{self.verified_email}' already exists.")
            else:
                raise e

        try:
            template_content = {
                "Subject": "Weekly Coupons Newsletter",
                "Html": load_file_content("coupon-newsletter.html"),
                "Text": load_file_content("coupon-newsletter.txt"),
            }
            self.ses_client.create_email_template(
                TemplateName=TEMPLATE_NAME, TemplateContent=template_content
            )
            print(f"Email template '{TEMPLATE_NAME}' created successfully.")
        except ClientError as e:
            # If the template already exists, skip and proceed
            if e.response["Error"]["Code"] == "AlreadyExistsException":
                print(f"Email template '{TEMPLATE_NAME}' already exists.")
            else:
                raise e

        try:
            self.ses_client.delete_contact_list(ContactListName=CONTACT_LIST_NAME)
            print(f"Contact list '{CONTACT_LIST_NAME}' deleted successfully.")
        except ClientError as e:
            # If the contact list doesn't exist, skip and proceed
            if e.response["Error"]["Code"] == "NotFoundException":
                print(f"Contact list '{CONTACT_LIST_NAME}' does not exist.")
            else:
                print(e)

            try:
                self.ses_client.delete_email_identity(EmailIdentity=self.verified_email)
                print(f"Email identity '{self.verified_email}' deleted successfully.")
            except ClientError as e:
                # If the email identity doesn't exist, skip and proceed
                if e.response["Error"]["Code"] == "NotFoundException":
                    print(f"Email identity '{self.verified_email}' does not exist.")
                else:
                    print(e)

        try:
            self.ses_client.delete_email_template(TemplateName=TEMPLATE_NAME)
            print(f"Email template '{TEMPLATE_NAME}' deleted successfully.")
        except ClientError as e:
            # If the email template doesn't exist, skip and proceed
            if e.response["Error"]["Code"] == "NotFoundException":
                print(f"Email template '{TEMPLATE_NAME}' does not exist.")
            else:
                print(e)
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateContact](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateContact)
  + [CreateContactList](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateContactList)
  + [CreateEmailIdentity](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateEmailIdentity)
  + [CreateEmailTemplate](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/CreateEmailTemplate)
  + [DeleteContactList](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/DeleteContactList)
  + [DeleteEmailIdentity](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/DeleteEmailIdentity)
  + [DeleteEmailTemplate](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/DeleteEmailTemplate)
  + [ListContacts](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/ListContacts)
  + [SendEmail.simple](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/SendEmail.simple)
  + [SendEmail.template](https://docs.aws.amazon.com/goto/boto3/sesv2-2019-09-27/SendEmail.template)

# SDK for Python (Boto3) を使用する Amazon SNS の例
<a name="python_3_sns_code_examples"></a>

次のコード例は、Amazon SNS AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_python_3_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def create_topic(
        self, 
        topic_name: str, 
        is_fifo: bool = False, 
        content_based_deduplication: bool = False
    ) -> str:
        """
        Create an SNS topic.

        :param topic_name: The name of the topic to create.
        :param is_fifo: Whether to create a FIFO topic.
        :param content_based_deduplication: Whether to use content-based deduplication for FIFO topics.
        :return: The ARN of the created topic.
        :raises ClientError: If the topic creation fails.
        """
        try:
            # Add .fifo suffix for FIFO topics
            if is_fifo and not topic_name.endswith('.fifo'):
                topic_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoTopic'] = 'true'
                if content_based_deduplication:
                    attributes['ContentBasedDeduplication'] = 'true'

            response = self.sns_client.create_topic(
                Name=topic_name,
                Attributes=attributes
            )

            topic_arn = response['TopicArn']
            logger.info(f"Created topic: {topic_name} with ARN: {topic_arn}")
            return topic_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating topic {topic_name}: {error_code} - {e}")
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_python_3_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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


    @staticmethod
    def delete_topic(topic):
        """
        Deletes a topic. All subscriptions to the topic are also deleted.
        """
        try:
            topic.delete()
            logger.info("Deleted topic %s.", topic.arn)
        except ClientError:
            logger.exception("Couldn't delete topic %s.", topic.arn)
            raise
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def delete_topic(self, topic_arn: str) -> bool:
        """
        Delete an SNS topic.

        :param topic_arn: The ARN of the topic to delete.
        :return: True if successful.
        :raises ClientError: If the topic deletion fails.
        """
        try:
            self.sns_client.delete_topic(TopicArn=topic_arn)
            
            logger.info(f"Deleted topic: {topic_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'NotFound':
                logger.warning(f"Topic not found: {topic_arn}")
                return True  # Already deleted
            else:
                logger.error(f"Error deleting topic: {error_code} - {e}")
                raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/DeleteTopic)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_python_3_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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 list_subscriptions(self, topic=None):
        """
        Lists subscriptions for the current account, optionally limited to a
        specific topic.

        :param topic: When specified, only subscriptions to this topic are returned.
        :return: An iterator that yields the subscriptions.
        """
        try:
            if topic is None:
                subs_iter = self.sns_resource.subscriptions.all()
            else:
                subs_iter = topic.subscriptions.all()
            logger.info("Got subscriptions.")
        except ClientError:
            logger.exception("Couldn't get subscriptions.")
            raise
        else:
            return subs_iter
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListSubscriptions](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/ListSubscriptions)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_python_3_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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 list_topics(self):
        """
        Lists topics for the current account.

        :return: An iterator that yields the topics.
        """
        try:
            topics_iter = self.sns_resource.topics.all()
            logger.info("Got topics.")
        except ClientError:
            logger.exception("Couldn't get topics.")
            raise
        else:
            return topics_iter
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListTopics](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/ListTopics)」を参照してください。

### `Publish`
<a name="sns_Publish_python_3_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。
サブスクリプションが属性に基づいてフィルター処理できるように、属性を含むメッセージを発行します。  

```
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


    @staticmethod
    def publish_message(topic, message, attributes):
        """
        Publishes a message, with attributes, to a topic. Subscriptions can be filtered
        based on message attributes so that a subscription receives messages only
        when specified attributes are present.

        :param topic: The topic to publish to.
        :param message: The message to publish.
        :param attributes: The key-value attributes to attach to the message. Values
                           must be either `str` or `bytes`.
        :return: The ID of the message.
        """
        try:
            att_dict = {}
            for key, value in attributes.items():
                if isinstance(value, str):
                    att_dict[key] = {"DataType": "String", "StringValue": value}
                elif isinstance(value, bytes):
                    att_dict[key] = {"DataType": "Binary", "BinaryValue": value}
            response = topic.publish(Message=message, MessageAttributes=att_dict)
            message_id = response["MessageId"]
            logger.info(
                "Published message with attributes %s to topic %s.",
                attributes,
                topic.arn,
            )
        except ClientError:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise
        else:
            return message_id
```
サブスクライバーのプロトコルに基づいて異なる形式のメッセージを発行します。  

```
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


    @staticmethod
    def publish_multi_message(
        topic, subject, default_message, sms_message, email_message
    ):
        """
        Publishes a multi-format message to a topic. A multi-format message takes
        different forms based on the protocol of the subscriber. For example,
        an SMS subscriber might receive a short version of the message
        while an email subscriber could receive a longer version.

        :param topic: The topic to publish to.
        :param subject: The subject of the message.
        :param default_message: The default version of the message. This version is
                                sent to subscribers that have protocols that are not
                                otherwise specified in the structured message.
        :param sms_message: The version of the message sent to SMS subscribers.
        :param email_message: The version of the message sent to email subscribers.
        :return: The ID of the message.
        """
        try:
            message = {
                "default": default_message,
                "sms": sms_message,
                "email": email_message,
            }
            response = topic.publish(
                Message=json.dumps(message), Subject=subject, MessageStructure="json"
            )
            message_id = response["MessageId"]
            logger.info("Published multi-format message to topic %s.", topic.arn)
        except ClientError:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise
        else:
            return message_id
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def publish_message(
        self,
        topic_arn: str,
        message: str,
        tone_attribute: Optional[str] = None,
        deduplication_id: Optional[str] = None,
        message_group_id: Optional[str] = None
    ) -> str:
        """
        Publish a message to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param message: The message content to publish.
        :param tone_attribute: Optional tone attribute for message filtering.
        :param deduplication_id: Optional deduplication ID for FIFO topics.
        :param message_group_id: Optional message group ID for FIFO topics.
        :return: The message ID of the published message.
        :raises ClientError: If the message publication fails.
        """
        try:
            publish_args = {
                'TopicArn': topic_arn,
                'Message': message
            }

            # Add message attributes if tone is specified
            if tone_attribute:
                publish_args['MessageAttributes'] = {
                    'tone': {
                        'DataType': 'String',
                        'StringValue': tone_attribute
                    }
                }

            # Add FIFO-specific parameters
            if message_group_id:
                publish_args['MessageGroupId'] = message_group_id

            if deduplication_id:
                publish_args['MessageDeduplicationId'] = deduplication_id

            response = self.sns_client.publish(**publish_args)

            message_id = response['MessageId']
            logger.info(f"Published message to topic {topic_arn} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error publishing message to topic: {error_code} - {e}")
            raise
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)」を参照してください。

### `SetSubscriptionAttributes`
<a name="sns_SetSubscriptionAttributes_python_3_topic"></a>

次のコード例は、`SetSubscriptionAttributes` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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


    @staticmethod
    def add_subscription_filter(subscription, attributes):
        """
        Adds a filter policy to a subscription. A filter policy is a key and a
        list of values that are allowed. When a message is published, it must have an
        attribute that passes the filter or it will not be sent to the subscription.

        :param subscription: The subscription the filter policy is attached to.
        :param attributes: A dictionary of key-value pairs that define the filter.
        """
        try:
            att_policy = {key: [value] for key, value in attributes.items()}
            subscription.set_attributes(
                AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy)
            )
            logger.info("Added filter to subscription %s.", subscription.arn)
        except ClientError:
            logger.exception(
                "Couldn't add filter to subscription %s.", subscription.arn
            )
            raise
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[SetSubscriptionAttributes](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/SetSubscriptionAttributes)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_python_3_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
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


    @staticmethod
    def subscribe(topic, protocol, endpoint):
        """
        Subscribes an endpoint to the topic. Some endpoint types, such as email,
        must be confirmed before their subscriptions are active. When a subscription
        is not confirmed, its Amazon Resource Number (ARN) is set to
        'PendingConfirmation'.

        :param topic: The topic to subscribe to.
        :param protocol: The protocol of the endpoint, such as 'sms' or 'email'.
        :param endpoint: The endpoint that receives messages, such as a phone number
                         (in E.164 format) for SMS messages, or an email address for
                         email messages.
        :return: The newly added subscription.
        """
        try:
            subscription = topic.subscribe(
                Protocol=protocol, Endpoint=endpoint, ReturnSubscriptionArn=True
            )
            logger.info("Subscribed %s %s to topic %s.", protocol, endpoint, topic.arn)
        except ClientError:
            logger.exception(
                "Couldn't subscribe %s %s to topic %s.", protocol, endpoint, topic.arn
            )
            raise
        else:
            return subscription
```
オプションのフィルターでトピックにキューをサブスクライブします。  

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def subscribe_queue_to_topic(
        self, 
        topic_arn: str, 
        queue_arn: str, 
        filter_policy: Optional[str] = None
    ) -> str:
        """
        Subscribe an SQS queue to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param queue_arn: The ARN of the SQS queue.
        :param filter_policy: Optional JSON filter policy for message filtering.
        :return: The ARN of the subscription.
        :raises ClientError: If the subscription fails.
        """
        try:
            attributes = {}
            if filter_policy:
                attributes['FilterPolicy'] = filter_policy

            response = self.sns_client.subscribe(
                TopicArn=topic_arn,
                Protocol='sqs',
                Endpoint=queue_arn,
                Attributes=attributes
            )

            subscription_arn = response['SubscriptionArn']
            logger.info(f"Subscribed queue {queue_arn} to topic {topic_arn}")
            return subscription_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error subscribing queue to topic: {error_code} - {e}")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[Subscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Subscribe)」を参照してください。

### `Unsubscribe`
<a name="sns_Unsubscribe_python_3_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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


    @staticmethod
    def delete_subscription(subscription):
        """
        Unsubscribes and deletes a subscription.
        """
        try:
            subscription.delete()
            logger.info("Deleted subscription %s.", subscription.arn)
        except ClientError:
            logger.exception("Couldn't delete subscription %s.", subscription.arn)
            raise
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def unsubscribe(self, subscription_arn: str) -> bool:
        """
        Unsubscribe from an SNS topic.

        :param subscription_arn: The ARN of the subscription to remove.
        :return: True if successful.
        :raises ClientError: If the unsubscribe operation fails.
        """
        try:
            self.sns_client.unsubscribe(SubscriptionArn=subscription_arn)
            
            logger.info(f"Unsubscribed: {subscription_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'NotFound':
                logger.warning(f"Subscription not found: {subscription_arn}")
                return True  # Already unsubscribed
            else:
                logger.error(f"Error unsubscribing: {error_code} - {e}")
                raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[Unsubscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Unsubscribe)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_python_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Textract AWS SDK for Python (Boto3) で を使用して、ドキュメントイメージ内のテキスト、フォーム、テーブル要素を検出する方法を示します。入力イメージと Amazon Textract 出力は、検出された要素を探索できる Tkinter アプリケーションに表示されます。  
+ Amazon Textract にドキュメントイメージを送信し、検出された要素の出力を調べます。
+ Amazon Textract に直接イメージを送信するか、Amazon Simple Storage Service (Amazon S3) バケットを通じてイメージを送信します。
+ 非同期 API を使用して、ジョブの完了時に Amazon Simple Notification Service (Amazon SNS) トピックに通知を発行するジョブを開始します。
+ Amazon Simple Queue Service (Amazon SQS) キューにジョブ完了メッセージについてポーリングし、結果を表示します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_explorer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### FIFO トピックを作成して発行する
<a name="sns_PublishFifoTopic_python_3_topic"></a>

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。
FIFO トピックを作成し、そのトピックに Amazon SQS FIFO キューと標準キューをサブスクライブして、メッセージを Amazon SNS トピックに発行します。  

```
def usage_demo():
    """Shows how to subscribe queues to a FIFO topic."""
    print("-" * 88)
    print("Welcome to the `Subscribe queues to a FIFO topic` demo!")
    print("-" * 88)

    sns = boto3.resource("sns")
    sqs = boto3.resource("sqs")
    fifo_topic_wrapper = FifoTopicWrapper(sns)
    sns_wrapper = SnsWrapper(sns)

    prefix = "sqs-subscribe-demo-"
    queues = set()
    subscriptions = set()

    wholesale_queue = sqs.create_queue(
        QueueName=prefix + "wholesale.fifo",
        Attributes={
            "MaximumMessageSize": str(4096),
            "ReceiveMessageWaitTimeSeconds": str(10),
            "VisibilityTimeout": str(300),
            "FifoQueue": str(True),
            "ContentBasedDeduplication": str(True),
        },
    )
    queues.add(wholesale_queue)
    print(f"Created FIFO queue with URL: {wholesale_queue.url}.")

    retail_queue = sqs.create_queue(
        QueueName=prefix + "retail.fifo",
        Attributes={
            "MaximumMessageSize": str(4096),
            "ReceiveMessageWaitTimeSeconds": str(10),
            "VisibilityTimeout": str(300),
            "FifoQueue": str(True),
            "ContentBasedDeduplication": str(True),
        },
    )
    queues.add(retail_queue)
    print(f"Created FIFO queue with URL: {retail_queue.url}.")

    analytics_queue = sqs.create_queue(QueueName=prefix + "analytics", Attributes={})
    queues.add(analytics_queue)
    print(f"Created standard queue with URL: {analytics_queue.url}.")

    topic = fifo_topic_wrapper.create_fifo_topic("price-updates-topic.fifo")
    print(f"Created FIFO topic: {topic.attributes['TopicArn']}.")

    for q in queues:
        fifo_topic_wrapper.add_access_policy(q, topic.attributes["TopicArn"])

    print(f"Added access policies for topic: {topic.attributes['TopicArn']}.")

    for q in queues:
        sub = fifo_topic_wrapper.subscribe_queue_to_topic(
            topic, q.attributes["QueueArn"]
        )
        subscriptions.add(sub)

    print(f"Subscribed queues to topic: {topic.attributes['TopicArn']}.")

    input("Press Enter to publish a message to the topic.")

    message_id = fifo_topic_wrapper.publish_price_update(
        topic, '{"product": 214, "price": 79.99}', "Consumables"
    )

    print(f"Published price update with message ID: {message_id}.")

    # Clean up the subscriptions, queues, and topic.
    input("Press Enter to clean up resources.")
    for s in subscriptions:
        sns_wrapper.delete_subscription(s)

    sns_wrapper.delete_topic(topic)

    for q in queues:
        fifo_topic_wrapper.delete_queue(q)

    print(f"Deleted subscriptions, queues, and topic.")

    print("Thanks for watching!")
    print("-" * 88)



class FifoTopicWrapper:
    """Encapsulates Amazon SNS FIFO topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource

    def create_fifo_topic(self, topic_name):
        """
        Create a FIFO topic.
        Topic names must be made up of only uppercase and lowercase ASCII letters,
        numbers, underscores, and hyphens, and must be between 1 and 256 characters long.
        For a FIFO topic, the name must end with the .fifo suffix.

        :param topic_name: The name for the topic.
        :return: The new topic.
        """
        try:
            topic = self.sns_resource.create_topic(
                Name=topic_name,
                Attributes={
                    "FifoTopic": str(True),
                    "ContentBasedDeduplication": str(False),
                    "FifoThroughputScope": "MessageGroup",
                },
            )
            logger.info("Created FIFO topic with name=%s.", topic_name)
            return topic
        except ClientError as error:
            logger.exception("Couldn't create topic with name=%s!", topic_name)
            raise error


    @staticmethod
    def add_access_policy(queue, topic_arn):
        """
        Add the necessary access policy to a queue, so
        it can receive messages from a topic.

        :param queue: The queue resource.
        :param topic_arn: The ARN of the topic.
        :return: None.
        """
        try:
            queue.set_attributes(
                Attributes={
                    "Policy": json.dumps(
                        {
                            "Version":"2012-10-17",		 	 	 
                            "Statement": [
                                {
                                    "Sid": "test-sid",
                                    "Effect": "Allow",
                                    "Principal": {"AWS": "*"},
                                    "Action": "SQS:SendMessage",
                                    "Resource": queue.attributes["QueueArn"],
                                    "Condition": {
                                        "ArnLike": {"aws:SourceArn": topic_arn}
                                    },
                                }
                            ],
                        }
                    )
                }
            )
            logger.info("Added trust policy to the queue.")
        except ClientError as error:
            logger.exception("Couldn't add trust policy to the queue!")
            raise error


    @staticmethod
    def subscribe_queue_to_topic(topic, queue_arn):
        """
        Subscribe a queue to a topic.

        :param topic: The topic resource.
        :param queue_arn: The ARN of the queue.
        :return: The subscription resource.
        """
        try:
            subscription = topic.subscribe(
                Protocol="sqs",
                Endpoint=queue_arn,
            )
            logger.info("The queue is subscribed to the topic.")
            return subscription
        except ClientError as error:
            logger.exception("Couldn't subscribe queue to topic!")
            raise error


    @staticmethod
    def publish_price_update(topic, payload, group_id):
        """
        Compose and publish a message that updates the wholesale price.

        :param topic: The topic to publish to.
        :param payload: The message to publish.
        :param group_id: The group ID for the message.
        :return: The ID of the message.
        """
        try:
            att_dict = {"business": {"DataType": "String", "StringValue": "wholesale"}}
            dedup_id = uuid.uuid4()
            response = topic.publish(
                Subject="Price Update",
                Message=payload,
                MessageAttributes=att_dict,
                MessageGroupId=group_id,
                MessageDeduplicationId=str(dedup_id),
            )
            message_id = response["MessageId"]
            logger.info("Published message to topic %s.", topic.arn)
        except ClientError as error:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise error
        return message_id


    @staticmethod
    def delete_queue(queue):
        """
        Removes an SQS queue. When run against an AWS account, it can take up to
        60 seconds before the queue is actually deleted.

        :param queue: The queue to delete.
        :return: None
        """
        try:
            queue.delete()
            logger.info("Deleted queue with URL=%s.", queue.url)
        except ClientError as error:
            logger.exception("Couldn't delete queue with URL=%s!", queue.url)
            raise error
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)
  + [Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)
  + [Subscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Subscribe)

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_python_3_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Python (Boto3)**  
 Amazon Rekognition を使用して、非同期検出ジョブを開始して、動画内の顔、オブジェクト、人を検出します。この例では、ジョブが完了し、Amazon Simple Queue Service (Amazon SQS) キューをトピックにサブスクライブしたときに、Amazon Simple Notification Service (Amazon SNS) トピックに通知するように Amazon Rekognition を設定します。キューがジョブに関するメッセージを受信すると、ジョブが取得され、結果が出力されます。  
 この例は GitHub で最もよく見られます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### SMS テキストメッセージを発行する
<a name="sns_PublishTextSMS_python_3_topic"></a>

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
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 publish_text_message(self, phone_number, message):
        """
        Publishes a text message directly to a phone number without need for a
        subscription.

        :param phone_number: The phone number that receives the message. This must be
                             in E.164 format. For example, a United States phone
                             number might be +12065550101.
        :param message: The message to send.
        :return: The ID of the message.
        """
        try:
            response = self.sns_resource.meta.client.publish(
                PhoneNumber=phone_number, Message=message
            )
            message_id = response["MessageId"]
            logger.info("Published message to %s.", phone_number)
        except ClientError:
            logger.exception("Couldn't publish message to %s.", phone_number)
            raise
        else:
            return message_id
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)」を参照してください。

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/topics_and_queues#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class TopicsAndQueuesScenario:
    """Manages the Topics and Queues feature scenario."""

    DASHES = "-" * 80

    def __init__(self, sns_wrapper: SnsWrapper, sqs_wrapper: SqsWrapper) -> None:
        """
        Initialize the Topics and Queues scenario.

        :param sns_wrapper: SnsWrapper instance for SNS operations.
        :param sqs_wrapper: SqsWrapper instance for SQS operations.
        """
        self.sns_wrapper = sns_wrapper
        self.sqs_wrapper = sqs_wrapper
        
        # Scenario state
        self.use_fifo_topic = False
        self.use_content_based_deduplication = False
        self.topic_name = None
        self.topic_arn = None
        self.queue_count = 2
        self.queue_urls = []
        self.subscription_arns = []
        self.tones = ["cheerful", "funny", "serious", "sincere"]

    def run_scenario(self) -> None:
        """Run the Topics and Queues feature scenario."""
        print(self.DASHES)
        print("Welcome to messaging with topics and queues.")
        print(self.DASHES)
        print(f"""
    In this scenario, you will create an SNS topic and subscribe {self.queue_count} SQS queues to the topic.
    You can select from several options for configuring the topic and the subscriptions for the queues.
    You can then post to the topic and see the results in the queues.
        """)

        try:
            # Setup Phase
            print(self.DASHES)
            self._setup_topic()
            print(self.DASHES)

            self._setup_queues()
            print(self.DASHES)

            # Demonstration Phase
            self._publish_messages()
            print(self.DASHES)

            # Examination Phase
            self._poll_queues_for_messages()
            print(self.DASHES)

            # Cleanup Phase
            self._cleanup_resources()
            print(self.DASHES)

        except Exception as e:
            logger.error(f"Scenario failed: {e}")
            print(f"There was a problem with the scenario: {e}")
            print("\nInitiating cleanup...")
            try:
                self._cleanup_resources()
            except Exception as cleanup_error:
                logger.error(f"Error during cleanup: {cleanup_error}")

        print("Messaging with topics and queues scenario is complete.")
        print(self.DASHES)

    def _setup_topic(self) -> None:
        """Set up the SNS topic to be used with the queues."""
        print("SNS topics can be configured as FIFO (First-In-First-Out).")
        print("FIFO topics deliver messages in order and support deduplication and message filtering.")
        print()

        self.use_fifo_topic = q.ask("Would you like to work with FIFO topics? (y/n): ", q.is_yesno)

        if self.use_fifo_topic:
            print(self.DASHES)
            self.topic_name = q.ask("Enter a name for your SNS topic: ", q.non_empty)
            print("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.")
            print()

            print(self.DASHES)
            print("""
    Because you have chosen a FIFO topic, deduplication is supported.
    Deduplication IDs are either set in the message or automatically generated 
    from content using a hash function.
    
    If a message is successfully published to an SNS FIFO topic, any message 
    published and determined to have the same deduplication ID, 
    within the five-minute deduplication interval, is accepted but not delivered.
    
    For more information about deduplication, 
    see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.
            """)

            self.use_content_based_deduplication = q.ask(
                "Use content-based deduplication instead of entering a deduplication ID? (y/n): ", 
                q.is_yesno
            )
        else:
            self.topic_name = q.ask("Enter a name for your SNS topic: ", q.non_empty)

        print(self.DASHES)

        # Create the topic
        self.topic_arn = self.sns_wrapper.create_topic(
            self.topic_name, 
            self.use_fifo_topic, 
            self.use_content_based_deduplication
        )

        print(f"Your new topic with the name {self.topic_name}")
        print(f"  and Amazon Resource Name (ARN) {self.topic_arn}")
        print(f"  has been created.")
        print()

    def _setup_queues(self) -> None:
        """Set up the SQS queues and subscribe them to the topic."""
        print(f"Now you will create {self.queue_count} Amazon Simple Queue Service (Amazon SQS) queues to subscribe to the topic.")

        for i in range(self.queue_count):
            queue_name = q.ask(f"Enter a name for SQS queue #{i+1}: ", q.non_empty)
            
            if self.use_fifo_topic and i == 0:
                print("Because you have selected a FIFO topic, '.fifo' must be appended to the queue name.")

            # Create the queue
            queue_url = self.sqs_wrapper.create_queue(queue_name, self.use_fifo_topic)
            self.queue_urls.append(queue_url)

            print(f"Your new queue with the name {queue_name}")
            print(f"  and queue URL {queue_url}")
            print(f"  has been created.")
            print()

            if i == 0:
                print("The queue URL is used to retrieve the queue ARN,")
                print("which is used to create a subscription.")
                print(self.DASHES)

            # Get queue ARN
            queue_arn = self.sqs_wrapper.get_queue_arn(queue_url)

            if i == 0:
                print("An AWS Identity and Access Management (IAM) policy must be attached to an SQS queue,")
                print("enabling it to receive messages from an SNS topic.")

            # Set queue policy to allow SNS to send messages
            self.sqs_wrapper.set_queue_policy_for_topic(queue_arn, self.topic_arn, queue_url)

            # Set up message filtering if using FIFO
            subscription_arn = self._setup_subscription_with_filter(i, queue_arn, queue_name)
            self.subscription_arns.append(subscription_arn)

    def _setup_subscription_with_filter(self, queue_index: int, queue_arn: str, queue_name: str) -> str:
        """Set up subscription with optional message filtering."""
        filter_policy = None
        
        if self.use_fifo_topic:
            print(self.DASHES)
            if queue_index == 0:
                print("Subscriptions to a FIFO topic can have filters.")
                print("If you add a filter to this subscription, then only the filtered messages")
                print("will be received in the queue.")
                print()
                print("For information about message filtering,")
                print("see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html")
                print()
                print("For this example, you can filter messages by a TONE attribute.")

            use_filter = q.ask(f"Filter messages for {queue_name}'s subscription to the topic? (y/n): ", q.is_yesno)
            
            if use_filter:
                filter_policy = self._create_filter_policy()

        subscription_arn = self.sns_wrapper.subscribe_queue_to_topic(
            self.topic_arn, queue_arn, filter_policy
        )

        print(f"The queue {queue_name} has been subscribed to the topic {self.topic_name}")
        print(f"  with the subscription ARN {subscription_arn}")

        return subscription_arn

    def _create_filter_policy(self) -> str:
        """Create a message filter policy based on user selections."""
        print(self.DASHES)
        print("You can filter messages by one or more of the following TONE attributes.")

        filter_selections = []
        selection_number = 0

        while True:
            print("Enter a number to add a TONE filter, or enter 0 to stop adding filters.")
            for i, tone in enumerate(self.tones, 1):
                print(f"  {i}. {tone}")

            selection = q.ask("Your choice: ", q.is_int, q.in_range(0, len(self.tones)))
            
            if selection == 0:
                break
            elif selection > 0 and self.tones[selection - 1] not in filter_selections:
                filter_selections.append(self.tones[selection - 1])
                print(f"Added '{self.tones[selection - 1]}' to filter list.")

        if filter_selections:
            filters = {"tone": filter_selections}
            return json.dumps(filters)
        return None

    def _publish_messages(self) -> None:
        """Publish messages to the topic with various options."""
        print("Now we can publish messages.")

        keep_sending = True
        while keep_sending:
            print()
            message = q.ask("Enter a message to publish: ", q.non_empty)

            message_group_id = None
            deduplication_id = None
            tone_attribute = None

            if self.use_fifo_topic:
                print("Because you are using a FIFO topic, you must set a message group ID.")
                print("All messages within the same group will be received in the order they were published.")
                print()
                message_group_id = q.ask("Enter a message group ID for this message: ", q.non_empty)

                if not self.use_content_based_deduplication:
                    print("Because you are not using content-based deduplication,")
                    print("you must enter a deduplication ID.")
                    deduplication_id = q.ask("Enter a deduplication ID for this message: ", q.non_empty)

                # Ask about tone attribute
                add_attribute = q.ask("Add an attribute to this message? (y/n): ", q.is_yesno)
                if add_attribute:
                    print("Enter a number for an attribute:")
                    for i, tone in enumerate(self.tones, 1):
                        print(f"  {i}. {tone}")
                    
                    selection = q.ask("Your choice: ", q.is_int, q.in_range(1, len(self.tones)))
                    if 1 <= selection <= len(self.tones):
                        tone_attribute = self.tones[selection - 1]

            # Publish the message
            message_id = self.sns_wrapper.publish_message(
                self.topic_arn,
                message,
                tone_attribute,
                deduplication_id,
                message_group_id
            )

            print(f"Message published with ID: {message_id}")

            keep_sending = q.ask("Send another message? (y/n): ", q.is_yesno)

    def _poll_queues_for_messages(self) -> None:
        """Poll all queues for messages and display results."""
        for i, queue_url in enumerate(self.queue_urls):
            print(f"Polling queue #{i+1} at {queue_url} for messages...")
            
            q.ask("Press Enter to continue...")

            messages = self._poll_queue_for_messages(queue_url)
            
            if messages:
                print(f"{len(messages)} message(s) were received by queue #{i+1}")
                for j, message in enumerate(messages, 1):
                    print(f"  Message {j}:")
                    # Parse the SNS message body to get the actual message
                    try:
                        sns_message = json.loads(message['Body'])
                        actual_message = sns_message.get('Message', message['Body'])
                        print(f"    {actual_message}")
                    except (json.JSONDecodeError, KeyError):
                        print(f"    {message['Body']}")

                # Delete the messages
                self.sqs_wrapper.delete_messages(queue_url, messages)
                print(f"Messages deleted from queue #{i+1}")
            else:
                print(f"No messages received by queue #{i+1}")
            
            print(self.DASHES)

    def _poll_queue_for_messages(self, queue_url: str) -> List[Dict[str, Any]]:
        """Poll a single queue for messages."""
        all_messages = []
        max_polls = 3  # Limit polling to avoid infinite loops
        
        for poll_count in range(max_polls):
            messages = self.sqs_wrapper.receive_messages(queue_url, 10)
            
            if messages:
                all_messages.extend(messages)
                print(f"  Received {len(messages)} messages in poll {poll_count + 1}")
                # Small delay between polls
                time.sleep(1)
            else:
                print(f"  No messages in poll {poll_count + 1}")
                break
                
        return all_messages

    def _cleanup_resources(self) -> None:
        """Clean up all resources created during the scenario."""
        print("Cleaning up resources...")

        # Delete queues
        for i, queue_url in enumerate(self.queue_urls):
            if queue_url:
                delete_queue = q.ask(f"Delete queue #{i+1} with URL {queue_url}? (y/n): ", q.is_yesno)
                if delete_queue:
                    try:
                        self.sqs_wrapper.delete_queue(queue_url)
                        print(f"Deleted queue #{i+1}")
                    except Exception as e:
                        print(f"Error deleting queue #{i+1}: {e}")

        # Unsubscribe from topic
        for i, subscription_arn in enumerate(self.subscription_arns):
            if subscription_arn:
                try:
                    self.sns_wrapper.unsubscribe(subscription_arn)
                    print(f"Unsubscribed subscription #{i+1}")
                except Exception as e:
                    print(f"Error unsubscribing #{i+1}: {e}")

        # Delete topic
        if self.topic_arn:
            delete_topic = q.ask(f"Delete topic {self.topic_name}? (y/n): ", q.is_yesno)
            if delete_topic:
                try:
                    self.sns_wrapper.delete_topic(self.topic_arn)
                    print(f"Deleted topic {self.topic_name}")
                except Exception as e:
                    print(f"Error deleting topic: {e}")

        print("Resource cleanup complete.")
```
シナリオで使用する Amazon SNS および Amazon SQS オペレーションをラップするクラスを作成します。  

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def create_topic(
        self, 
        topic_name: str, 
        is_fifo: bool = False, 
        content_based_deduplication: bool = False
    ) -> str:
        """
        Create an SNS topic.

        :param topic_name: The name of the topic to create.
        :param is_fifo: Whether to create a FIFO topic.
        :param content_based_deduplication: Whether to use content-based deduplication for FIFO topics.
        :return: The ARN of the created topic.
        :raises ClientError: If the topic creation fails.
        """
        try:
            # Add .fifo suffix for FIFO topics
            if is_fifo and not topic_name.endswith('.fifo'):
                topic_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoTopic'] = 'true'
                if content_based_deduplication:
                    attributes['ContentBasedDeduplication'] = 'true'

            response = self.sns_client.create_topic(
                Name=topic_name,
                Attributes=attributes
            )

            topic_arn = response['TopicArn']
            logger.info(f"Created topic: {topic_name} with ARN: {topic_arn}")
            return topic_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating topic {topic_name}: {error_code} - {e}")
            raise


    def subscribe_queue_to_topic(
        self, 
        topic_arn: str, 
        queue_arn: str, 
        filter_policy: Optional[str] = None
    ) -> str:
        """
        Subscribe an SQS queue to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param queue_arn: The ARN of the SQS queue.
        :param filter_policy: Optional JSON filter policy for message filtering.
        :return: The ARN of the subscription.
        :raises ClientError: If the subscription fails.
        """
        try:
            attributes = {}
            if filter_policy:
                attributes['FilterPolicy'] = filter_policy

            response = self.sns_client.subscribe(
                TopicArn=topic_arn,
                Protocol='sqs',
                Endpoint=queue_arn,
                Attributes=attributes
            )

            subscription_arn = response['SubscriptionArn']
            logger.info(f"Subscribed queue {queue_arn} to topic {topic_arn}")
            return subscription_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error subscribing queue to topic: {error_code} - {e}")
            raise


    def publish_message(
        self,
        topic_arn: str,
        message: str,
        tone_attribute: Optional[str] = None,
        deduplication_id: Optional[str] = None,
        message_group_id: Optional[str] = None
    ) -> str:
        """
        Publish a message to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param message: The message content to publish.
        :param tone_attribute: Optional tone attribute for message filtering.
        :param deduplication_id: Optional deduplication ID for FIFO topics.
        :param message_group_id: Optional message group ID for FIFO topics.
        :return: The message ID of the published message.
        :raises ClientError: If the message publication fails.
        """
        try:
            publish_args = {
                'TopicArn': topic_arn,
                'Message': message
            }

            # Add message attributes if tone is specified
            if tone_attribute:
                publish_args['MessageAttributes'] = {
                    'tone': {
                        'DataType': 'String',
                        'StringValue': tone_attribute
                    }
                }

            # Add FIFO-specific parameters
            if message_group_id:
                publish_args['MessageGroupId'] = message_group_id

            if deduplication_id:
                publish_args['MessageDeduplicationId'] = deduplication_id

            response = self.sns_client.publish(**publish_args)

            message_id = response['MessageId']
            logger.info(f"Published message to topic {topic_arn} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error publishing message to topic: {error_code} - {e}")
            raise


    def unsubscribe(self, subscription_arn: str) -> bool:
        """
        Unsubscribe from an SNS topic.

        :param subscription_arn: The ARN of the subscription to remove.
        :return: True if successful.
        :raises ClientError: If the unsubscribe operation fails.
        """
        try:
            self.sns_client.unsubscribe(SubscriptionArn=subscription_arn)
            
            logger.info(f"Unsubscribed: {subscription_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'NotFound':
                logger.warning(f"Subscription not found: {subscription_arn}")
                return True  # Already unsubscribed
            else:
                logger.error(f"Error unsubscribing: {error_code} - {e}")
                raise


    def delete_topic(self, topic_arn: str) -> bool:
        """
        Delete an SNS topic.

        :param topic_arn: The ARN of the topic to delete.
        :return: True if successful.
        :raises ClientError: If the topic deletion fails.
        """
        try:
            self.sns_client.delete_topic(TopicArn=topic_arn)
            
            logger.info(f"Deleted topic: {topic_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'NotFound':
                logger.warning(f"Topic not found: {topic_arn}")
                return True  # Already deleted
            else:
                logger.error(f"Error deleting topic: {error_code} - {e}")
                raise


    def list_topics(self) -> list:
        """
        List all SNS topics in the account using pagination.

        :return: List of topic ARNs.
        :raises ClientError: If listing topics fails.
        """
        try:
            topics = []
            paginator = self.sns_client.get_paginator('list_topics')
            
            for page in paginator.paginate():
                topics.extend([topic['TopicArn'] for topic in page.get('Topics', [])])
            
            logger.info(f"Found {len(topics)} topics")
            return topics

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            if error_code == 'AuthorizationError':
                logger.error("Authorization error listing topics - check IAM permissions")
            else:
                logger.error(f"Error listing topics: {error_code} - {e}")
            raise


class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def create_queue(self, queue_name: str, is_fifo: bool = False) -> str:
        """
        Create an SQS queue.

        :param queue_name: The name of the queue to create.
        :param is_fifo: Whether to create a FIFO queue.
        :return: The URL of the created queue.
        :raises ClientError: If the queue creation fails.
        """
        try:
            # Add .fifo suffix for FIFO queues
            if is_fifo and not queue_name.endswith('.fifo'):
                queue_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoQueue'] = 'true'

            response = self.sqs_client.create_queue(
                QueueName=queue_name,
                Attributes=attributes
            )

            queue_url = response['QueueUrl']
            logger.info(f"Created queue: {queue_name} with URL: {queue_url}")
            return queue_url

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating queue {queue_name}: {error_code} - {e}")
            raise


    def get_queue_arn(self, queue_url: str) -> str:
        """
        Get the ARN of an SQS queue.

        :param queue_url: The URL of the queue.
        :return: The ARN of the queue.
        :raises ClientError: If getting queue attributes fails.
        """
        try:
            response = self.sqs_client.get_queue_attributes(
                QueueUrl=queue_url,
                AttributeNames=['QueueArn']
            )

            queue_arn = response['Attributes']['QueueArn']
            logger.info(f"Queue ARN for {queue_url}: {queue_arn}")
            return queue_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error getting queue ARN: {error_code} - {e}")
            raise


    def set_queue_policy_for_topic(self, queue_arn: str, topic_arn: str, queue_url: str) -> bool:
        """
        Set the queue policy to allow SNS to send messages to the queue.

        :param queue_arn: The ARN of the SQS queue.
        :param topic_arn: The ARN of the SNS topic.
        :param queue_url: The URL of the SQS queue.
        :return: True if successful.
        :raises ClientError: If setting the queue policy fails.
        """
        try:
            # Create policy that allows SNS to send messages to the queue
            policy = {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "sns.amazonaws.com"
                        },
                        "Action": "sqs:SendMessage",
                        "Resource": queue_arn,
                        "Condition": {
                            "ArnEquals": {
                                "aws:SourceArn": topic_arn
                            }
                        }
                    }
                ]
            }

            self.sqs_client.set_queue_attributes(
                QueueUrl=queue_url,
                Attributes={
                    'Policy': json.dumps(policy)
                }
            )

            logger.info(f"Set queue policy for {queue_url} to allow messages from {topic_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error setting queue policy: {error_code} - {e}")
            raise


    def receive_messages(self, queue_url: str, max_messages: int = 10) -> List[Dict[str, Any]]:
        """
        Receive messages from an SQS queue.

        :param queue_url: The URL of the queue to receive messages from.
        :param max_messages: Maximum number of messages to receive (1-10).
        :return: List of received messages.
        :raises ClientError: If receiving messages fails.
        """
        try:
            # Ensure max_messages is within valid range
            max_messages = max(1, min(10, max_messages))

            response = self.sqs_client.receive_message(
                QueueUrl=queue_url,
                MaxNumberOfMessages=max_messages,
                WaitTimeSeconds=2,  # Short polling
                MessageAttributeNames=['All']
            )

            messages = response.get('Messages', [])
            logger.info(f"Received {len(messages)} messages from {queue_url}")
            return messages

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error receiving messages: {error_code} - {e}")
            raise


    def delete_messages(self, queue_url: str, messages: List[Dict[str, Any]]) -> bool:
        """
        Delete messages from an SQS queue in batches.

        :param queue_url: The URL of the queue.
        :param messages: List of messages to delete.
        :return: True if successful.
        :raises ClientError: If deleting messages fails.
        """
        try:
            if not messages:
                return True

            # Build delete entries for batch delete
            delete_entries = []
            for i, message in enumerate(messages):
                delete_entries.append({
                    'Id': str(i),
                    'ReceiptHandle': message['ReceiptHandle']
                })

            # Delete messages in batches of 10 (SQS limit)
            batch_size = 10
            for i in range(0, len(delete_entries), batch_size):
                batch = delete_entries[i:i + batch_size]
                
                response = self.sqs_client.delete_message_batch(
                    QueueUrl=queue_url,
                    Entries=batch
                )

                # Check for failures
                if 'Failed' in response and response['Failed']:
                    for failed in response['Failed']:
                        logger.warning(f"Failed to delete message: {failed}")

            logger.info(f"Deleted {len(messages)} messages from {queue_url}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error deleting messages: {error_code} - {e}")
            raise


    def delete_queue(self, queue_url: str) -> bool:
        """
        Delete an SQS queue.

        :param queue_url: The URL of the queue to delete.
        :return: True if successful.
        :raises ClientError: If the queue deletion fails.
        """
        try:
            self.sqs_client.delete_queue(QueueUrl=queue_url)
            
            logger.info(f"Deleted queue: {queue_url}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'AWS.SimpleQueueService.NonExistentQueue':
                logger.warning(f"Queue not found: {queue_url}")
                return True  # Already deleted
            else:
                logger.error(f"Error deleting queue: {error_code} - {e}")
                raise


    def list_queues(self, queue_name_prefix: Optional[str] = None) -> List[str]:
        """
        List all SQS queues in the account using pagination.

        :param queue_name_prefix: Optional prefix to filter queue names.
        :return: List of queue URLs.
        :raises ClientError: If listing queues fails.
        """
        try:
            queue_urls = []
            paginator = self.sqs_client.get_paginator('list_queues')
            
            page_params = {}
            if queue_name_prefix:
                page_params['QueueNamePrefix'] = queue_name_prefix

            for page in paginator.paginate(**page_params):
                queue_urls.extend(page.get('QueueUrls', []))
            
            logger.info(f"Found {len(queue_urls)} queues")
            return queue_urls

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            if error_code == 'AccessDenied':
                logger.error("Access denied listing queues - check IAM permissions")
            else:
                logger.error(f"Error listing queues: {error_code} - {e}")
            raise

    def send_message(self, queue_url: str, message_body: str, **kwargs) -> str:
        """
        Send a message to an SQS queue.

        :param queue_url: The URL of the queue.
        :param message_body: The message content.
        :param kwargs: Additional message parameters (DelaySeconds, MessageAttributes, etc.).
        :return: The message ID.
        :raises ClientError: If sending the message fails.
        """
        try:
            send_params = {
                'QueueUrl': queue_url,
                'MessageBody': message_body,
                **kwargs
            }

            response = self.sqs_client.send_message(**send_params)
            
            message_id = response['MessageId']
            logger.info(f"Sent message to {queue_url} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error sending message: {error_code} - {e}")
            raise
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Unsubscribe)

### API Gateway を使用して Lambda 関数を呼び出す
<a name="cross_LambdaAPIGateway_python_3_topic"></a>

次のコード例は、Amazon API Gateway によって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例は、 AWS Lambda 関数を対象とする Amazon API Gateway REST API を作成して使用する方法を示しています。Lambda ハンドラーは、HTTP メソッドに基づいてルーティングする方法を示します。クエリ文字列、ヘッダー、および本文からデータを取得する方法。そして、JSON 応答を返す方法。  
+ Lambda 関数をデプロイします。
+ API ゲートウェイ REST API を作成します。
+ Lambda 関数をターゲットとする REST リソースを作成します。
+ API Gateway に Lambda 関数を呼び出す権限を付与します。
+ リクエストパッケージを使用して、REST API にリクエストを送信します。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon SNS

### スケジュールされたイベントを使用した Lambda 関数の呼び出し
<a name="cross_LambdaScheduledEvents_python_3_topic"></a>

次のコード例は、Amazon EventBridge スケジュールされたイベントによって呼び出される AWS Lambda 関数を作成する方法を示しています。

**SDK for Python (Boto3)**  
 この例では、スケジュールされた Amazon EventBridge イベントのターゲットとして AWS Lambda 関数を登録する方法を示します。Lambda ハンドラーは、後で取得するために Amazon CloudWatch Logs にわかりやすいメッセージと完全なイベントデータを書き込みます。  
+ Lambda 関数をデプロイします。
+ EventBridge スケジュールイベントを作成し、Lambda 関数をターゲットにします。
+ EventBridge に Lambda 関数を呼び出す許可を付与します
+ CloudWatch Logs から最新のデータを出力して、スケジュールされた呼び出しの結果を表示しています。
+ デモ中に作成されたすべてのリソースをクリーンアップします。
 この例は GitHub で最もよく確認できます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/lambda#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ CloudWatch Logs
+ DynamoDB
+ EventBridge
+ Lambda
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_python_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用して Lambda で SNS イベントを消費します。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event, context):
    for record in event['Records']:
        process_message(record)
    print("done")

def process_message(record):
    try:
        message = record['Sns']['Message']
        print(f"Processed message {message}")
        # TODO; Process your record here
        
    except Exception as e:
        print("An error occurred")
        raise e
```

# SDK for Python (Boto3) を使用する Amazon SQS の例
<a name="python_3_sqs_code_examples"></a>

次のコード例は、Amazon SQS AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateQueue`
<a name="sqs_CreateQueue_python_3_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def create_queue(name, attributes=None):
    """
    Creates an Amazon SQS queue.

    :param name: The name of the queue. This is part of the URL assigned to the queue.
    :param attributes: The attributes of the queue, such as maximum message size or
                       whether it's a FIFO queue.
    :return: A Queue object that contains metadata about the queue and that can be used
             to perform queue operations like sending and receiving messages.
    """
    if not attributes:
        attributes = {}

    try:
        queue = sqs.create_queue(QueueName=name, Attributes=attributes)
        logger.info("Created queue '%s' with URL=%s", name, queue.url)
    except ClientError as error:
        logger.exception("Couldn't create queue named '%s'.", name)
        raise error
    else:
        return queue
```

```
class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def create_queue(self, queue_name: str, is_fifo: bool = False) -> str:
        """
        Create an SQS queue.

        :param queue_name: The name of the queue to create.
        :param is_fifo: Whether to create a FIFO queue.
        :return: The URL of the created queue.
        :raises ClientError: If the queue creation fails.
        """
        try:
            # Add .fifo suffix for FIFO queues
            if is_fifo and not queue_name.endswith('.fifo'):
                queue_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoQueue'] = 'true'

            response = self.sqs_client.create_queue(
                QueueName=queue_name,
                Attributes=attributes
            )

            queue_url = response['QueueUrl']
            logger.info(f"Created queue: {queue_name} with URL: {queue_url}")
            return queue_url

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating queue {queue_name}: {error_code} - {e}")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/CreateQueue)」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_python_3_topic"></a>

次のコード例は、`DeleteMessage` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def delete_message(message):
    """
    Delete a message from a queue. Clients must delete messages after they
    are received and processed to remove them from the queue.

    :param message: The message to delete. The message's queue URL is contained in
                    the message's metadata.
    :return: None
    """
    try:
        message.delete()
        logger.info("Deleted message: %s", message.message_id)
    except ClientError as error:
        logger.exception("Couldn't delete message: %s", message.message_id)
        raise error
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteMessage)」を参照してください。

### `DeleteMessageBatch`
<a name="sqs_DeleteMessageBatch_python_3_topic"></a>

次のコード例は、`DeleteMessageBatch` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def delete_messages(queue, messages):
    """
    Delete a batch of messages from a queue in a single request.

    :param queue: The queue from which to delete the messages.
    :param messages: The list of messages to delete.
    :return: The response from SQS that contains the list of successful and failed
             message deletions.
    """
    try:
        entries = [
            {"Id": str(ind), "ReceiptHandle": msg.receipt_handle}
            for ind, msg in enumerate(messages)
        ]
        response = queue.delete_messages(Entries=entries)
        if "Successful" in response:
            for msg_meta in response["Successful"]:
                logger.info("Deleted %s", messages[int(msg_meta["Id"])].receipt_handle)
        if "Failed" in response:
            for msg_meta in response["Failed"]:
                logger.warning(
                    "Could not delete %s", messages[int(msg_meta["Id"])].receipt_handle
                )
    except ClientError:
        logger.exception("Couldn't delete messages from queue %s", queue)
    else:
        return response
```

```
class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def delete_messages(self, queue_url: str, messages: List[Dict[str, Any]]) -> bool:
        """
        Delete messages from an SQS queue in batches.

        :param queue_url: The URL of the queue.
        :param messages: List of messages to delete.
        :return: True if successful.
        :raises ClientError: If deleting messages fails.
        """
        try:
            if not messages:
                return True

            # Build delete entries for batch delete
            delete_entries = []
            for i, message in enumerate(messages):
                delete_entries.append({
                    'Id': str(i),
                    'ReceiptHandle': message['ReceiptHandle']
                })

            # Delete messages in batches of 10 (SQS limit)
            batch_size = 10
            for i in range(0, len(delete_entries), batch_size):
                batch = delete_entries[i:i + batch_size]
                
                response = self.sqs_client.delete_message_batch(
                    QueueUrl=queue_url,
                    Entries=batch
                )

                # Check for failures
                if 'Failed' in response and response['Failed']:
                    for failed in response['Failed']:
                        logger.warning(f"Failed to delete message: {failed}")

            logger.info(f"Deleted {len(messages)} messages from {queue_url}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error deleting messages: {error_code} - {e}")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteMessageBatch](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteMessageBatch)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_python_3_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def remove_queue(queue):
    """
    Removes an SQS queue. When run against an AWS account, it can take up to
    60 seconds before the queue is actually deleted.

    :param queue: The queue to delete.
    :return: None
    """
    try:
        queue.delete()
        logger.info("Deleted queue with URL=%s.", queue.url)
    except ClientError as error:
        logger.exception("Couldn't delete queue with URL=%s!", queue.url)
        raise error
```

```
class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def delete_queue(self, queue_url: str) -> bool:
        """
        Delete an SQS queue.

        :param queue_url: The URL of the queue to delete.
        :return: True if successful.
        :raises ClientError: If the queue deletion fails.
        """
        try:
            self.sqs_client.delete_queue(QueueUrl=queue_url)
            
            logger.info(f"Deleted queue: {queue_url}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'AWS.SimpleQueueService.NonExistentQueue':
                logger.warning(f"Queue not found: {queue_url}")
                return True  # Already deleted
            else:
                logger.error(f"Error deleting queue: {error_code} - {e}")
                raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteQueue)」を参照してください。

### `GetQueueAttributes`
<a name="sqs_GetQueueAttributes_python_3_topic"></a>

次の例は、`GetQueueAttributes` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def get_queue_arn(self, queue_url: str) -> str:
        """
        Get the ARN of an SQS queue.

        :param queue_url: The URL of the queue.
        :return: The ARN of the queue.
        :raises ClientError: If getting queue attributes fails.
        """
        try:
            response = self.sqs_client.get_queue_attributes(
                QueueUrl=queue_url,
                AttributeNames=['QueueArn']
            )

            queue_arn = response['Attributes']['QueueArn']
            logger.info(f"Queue ARN for {queue_url}: {queue_arn}")
            return queue_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error getting queue ARN: {error_code} - {e}")
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンス*の[GetQueueAttributes](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/GetQueueAttributes)」を参照してください。

### `GetQueueUrl`
<a name="sqs_GetQueueUrl_python_3_topic"></a>

次の例は、`GetQueueUrl` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def get_queue(name):
    """
    Gets an SQS queue by name.

    :param name: The name that was used to create the queue.
    :return: A Queue object.
    """
    try:
        queue = sqs.get_queue_by_name(QueueName=name)
        logger.info("Got queue '%s' with URL=%s", name, queue.url)
    except ClientError as error:
        logger.exception("Couldn't get queue named %s.", name)
        raise error
    else:
        return queue
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetQueueUrl](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/GetQueueUrl)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_python_3_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def get_queues(prefix=None):
    """
    Gets a list of SQS queues. When a prefix is specified, only queues with names
    that start with the prefix are returned.

    :param prefix: The prefix used to restrict the list of returned queues.
    :return: A list of Queue objects.
    """
    if prefix:
        queue_iter = sqs.queues.filter(QueueNamePrefix=prefix)
    else:
        queue_iter = sqs.queues.all()
    queues = list(queue_iter)
    if queues:
        logger.info("Got queues: %s", ", ".join([q.url for q in queues]))
    else:
        logger.warning("No queues found.")
    return queues
```
+  API の詳細については、* SDK for Python (Boto3) API リファレンス*の「[ListQueues](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/ListQueues)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_python_3_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def receive_messages(queue, max_number, wait_time):
    """
    Receive a batch of messages in a single request from an SQS queue.

    :param queue: The queue from which to receive messages.
    :param max_number: The maximum number of messages to receive. The actual number
                       of messages received might be less.
    :param wait_time: The maximum time to wait (in seconds) before returning. When
                      this number is greater than zero, long polling is used. This
                      can result in reduced costs and fewer false empty responses.
    :return: The list of Message objects received. These each contain the body
             of the message and metadata and custom attributes.
    """
    try:
        messages = queue.receive_messages(
            MessageAttributeNames=["All"],
            MaxNumberOfMessages=max_number,
            WaitTimeSeconds=wait_time,
        )
        for msg in messages:
            logger.info("Received message: %s: %s", msg.message_id, msg.body)
    except ClientError as error:
        logger.exception("Couldn't receive messages from queue: %s", queue)
        raise error
    else:
        return messages
```

```
class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def receive_messages(self, queue_url: str, max_messages: int = 10) -> List[Dict[str, Any]]:
        """
        Receive messages from an SQS queue.

        :param queue_url: The URL of the queue to receive messages from.
        :param max_messages: Maximum number of messages to receive (1-10).
        :return: List of received messages.
        :raises ClientError: If receiving messages fails.
        """
        try:
            # Ensure max_messages is within valid range
            max_messages = max(1, min(10, max_messages))

            response = self.sqs_client.receive_message(
                QueueUrl=queue_url,
                MaxNumberOfMessages=max_messages,
                WaitTimeSeconds=2,  # Short polling
                MessageAttributeNames=['All']
            )

            messages = response.get('Messages', [])
            logger.info(f"Received {len(messages)} messages from {queue_url}")
            return messages

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error receiving messages: {error_code} - {e}")
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ReceiveMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/ReceiveMessage)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_python_3_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def send_message(queue, message_body, message_attributes=None):
    """
    Send a message to an Amazon SQS queue.

    :param queue: The queue that receives the message.
    :param message_body: The body text of the message.
    :param message_attributes: Custom attributes of the message. These are key-value
                               pairs that can be whatever you want.
    :return: The response from SQS that contains the assigned message ID.
    """
    if not message_attributes:
        message_attributes = {}

    try:
        response = queue.send_message(
            MessageBody=message_body, MessageAttributes=message_attributes
        )
    except ClientError as error:
        logger.exception("Send message failed: %s", message_body)
        raise error
    else:
        return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SendMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/SendMessage)」を参照してください。

### `SendMessageBatch`
<a name="sqs_SendMessageBatch_python_3_topic"></a>

次のコード例は、`SendMessageBatch` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
def send_messages(queue, messages):
    """
    Send a batch of messages in a single request to an SQS queue.
    This request may return overall success even when some messages were not sent.
    The caller must inspect the Successful and Failed lists in the response and
    resend any failed messages.

    :param queue: The queue to receive the messages.
    :param messages: The messages to send to the queue. These are simplified to
                     contain only the message body and attributes.
    :return: The response from SQS that contains the list of successful and failed
             messages.
    """
    try:
        entries = [
            {
                "Id": str(ind),
                "MessageBody": msg["body"],
                "MessageAttributes": msg["attributes"],
            }
            for ind, msg in enumerate(messages)
        ]
        response = queue.send_messages(Entries=entries)
        if "Successful" in response:
            for msg_meta in response["Successful"]:
                logger.info(
                    "Message sent: %s: %s",
                    msg_meta["MessageId"],
                    messages[int(msg_meta["Id"])]["body"],
                )
        if "Failed" in response:
            for msg_meta in response["Failed"]:
                logger.warning(
                    "Failed to send: %s: %s",
                    msg_meta["MessageId"],
                    messages[int(msg_meta["Id"])]["body"],
                )
    except ClientError as error:
        logger.exception("Send messages failed to queue: %s", queue)
        raise error
    else:
        return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SendMessageBatch](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/SendMessageBatch)」を参照してください。

### `SetQueueAttributes`
<a name="sqs_SetQueueAttributes_python_3_topic"></a>

次の例は、`SetQueueAttributes` を使用する方法を説明しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/topics_and_queues#code-examples)での設定と実行の方法を確認してください。
トピックのキューのポリシー属性を設定します。  

```
class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def set_queue_policy_for_topic(self, queue_arn: str, topic_arn: str, queue_url: str) -> bool:
        """
        Set the queue policy to allow SNS to send messages to the queue.

        :param queue_arn: The ARN of the SQS queue.
        :param topic_arn: The ARN of the SNS topic.
        :param queue_url: The URL of the SQS queue.
        :return: True if successful.
        :raises ClientError: If setting the queue policy fails.
        """
        try:
            # Create policy that allows SNS to send messages to the queue
            policy = {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "sns.amazonaws.com"
                        },
                        "Action": "sqs:SendMessage",
                        "Resource": queue_arn,
                        "Condition": {
                            "ArnEquals": {
                                "aws:SourceArn": topic_arn
                            }
                        }
                    }
                ]
            }

            self.sqs_client.set_queue_attributes(
                QueueUrl=queue_url,
                Attributes={
                    'Policy': json.dumps(policy)
                }
            )

            logger.info(f"Set queue policy for {queue_url} to allow messages from {topic_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error setting queue policy: {error_code} - {e}")
            raise
```
+  API の詳細については、 *AWS SDK for Python (Boto3) API リファレンスの*「[SetQueueAttributes](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/SetQueueAttributes)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセンジャーアプリケーションを作成する
<a name="cross_StepFunctionsMessenger_python_3_topic"></a>

次のコード例は、データベーステーブルからメッセージレコードを取得する AWS Step Functions メッセンジャーアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3) で を使用して AWS Step Functions 、Amazon DynamoDB テーブルからメッセージレコードを取得し、Amazon Simple Queue Service (Amazon SQS) で送信するメッセンジャーアプリケーションを作成する方法を示します。ステートマシンは AWS Lambda 関数と統合して、未送信メッセージがないかデータベースをスキャンします。  
+ Amazon DynamoDB テーブルからメッセージレコードを取得および更新するステートマシンを作成します。
+ ステートマシンの定義を更新して、Amazon Simple Queue Service (Amazon SQS) にもメッセージを送信します。
+ ステートマシンの実行を開始および停止します。
+ サービス統合を使用して、ステートマシンから Lambda、DynamoDB、および Amazon SQS に接続します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/stepfunctions_messenger) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SQS
+ ステップ関数

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_python_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Textract AWS SDK for Python (Boto3) で を使用して、ドキュメントイメージ内のテキスト、フォーム、テーブル要素を検出する方法を示します。入力イメージと Amazon Textract 出力は、検出された要素を探索できる Tkinter アプリケーションに表示されます。  
+ Amazon Textract にドキュメントイメージを送信し、検出された要素の出力を調べます。
+ Amazon Textract に直接イメージを送信するか、Amazon Simple Storage Service (Amazon S3) バケットを通じてイメージを送信します。
+ 非同期 API を使用して、ジョブの完了時に Amazon Simple Notification Service (Amazon SNS) トピックに通知を発行するジョブを開始します。
+ Amazon Simple Queue Service (Amazon SQS) キューにジョブ完了メッセージについてポーリングし、結果を表示します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_explorer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### FIFO トピックを作成して発行する
<a name="sns_PublishFifoTopic_python_3_topic"></a>

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

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。
FIFO トピックを作成し、そのトピックに Amazon SQS FIFO キューと標準キューをサブスクライブして、メッセージを Amazon SNS トピックに発行します。  

```
def usage_demo():
    """Shows how to subscribe queues to a FIFO topic."""
    print("-" * 88)
    print("Welcome to the `Subscribe queues to a FIFO topic` demo!")
    print("-" * 88)

    sns = boto3.resource("sns")
    sqs = boto3.resource("sqs")
    fifo_topic_wrapper = FifoTopicWrapper(sns)
    sns_wrapper = SnsWrapper(sns)

    prefix = "sqs-subscribe-demo-"
    queues = set()
    subscriptions = set()

    wholesale_queue = sqs.create_queue(
        QueueName=prefix + "wholesale.fifo",
        Attributes={
            "MaximumMessageSize": str(4096),
            "ReceiveMessageWaitTimeSeconds": str(10),
            "VisibilityTimeout": str(300),
            "FifoQueue": str(True),
            "ContentBasedDeduplication": str(True),
        },
    )
    queues.add(wholesale_queue)
    print(f"Created FIFO queue with URL: {wholesale_queue.url}.")

    retail_queue = sqs.create_queue(
        QueueName=prefix + "retail.fifo",
        Attributes={
            "MaximumMessageSize": str(4096),
            "ReceiveMessageWaitTimeSeconds": str(10),
            "VisibilityTimeout": str(300),
            "FifoQueue": str(True),
            "ContentBasedDeduplication": str(True),
        },
    )
    queues.add(retail_queue)
    print(f"Created FIFO queue with URL: {retail_queue.url}.")

    analytics_queue = sqs.create_queue(QueueName=prefix + "analytics", Attributes={})
    queues.add(analytics_queue)
    print(f"Created standard queue with URL: {analytics_queue.url}.")

    topic = fifo_topic_wrapper.create_fifo_topic("price-updates-topic.fifo")
    print(f"Created FIFO topic: {topic.attributes['TopicArn']}.")

    for q in queues:
        fifo_topic_wrapper.add_access_policy(q, topic.attributes["TopicArn"])

    print(f"Added access policies for topic: {topic.attributes['TopicArn']}.")

    for q in queues:
        sub = fifo_topic_wrapper.subscribe_queue_to_topic(
            topic, q.attributes["QueueArn"]
        )
        subscriptions.add(sub)

    print(f"Subscribed queues to topic: {topic.attributes['TopicArn']}.")

    input("Press Enter to publish a message to the topic.")

    message_id = fifo_topic_wrapper.publish_price_update(
        topic, '{"product": 214, "price": 79.99}', "Consumables"
    )

    print(f"Published price update with message ID: {message_id}.")

    # Clean up the subscriptions, queues, and topic.
    input("Press Enter to clean up resources.")
    for s in subscriptions:
        sns_wrapper.delete_subscription(s)

    sns_wrapper.delete_topic(topic)

    for q in queues:
        fifo_topic_wrapper.delete_queue(q)

    print(f"Deleted subscriptions, queues, and topic.")

    print("Thanks for watching!")
    print("-" * 88)



class FifoTopicWrapper:
    """Encapsulates Amazon SNS FIFO topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource

    def create_fifo_topic(self, topic_name):
        """
        Create a FIFO topic.
        Topic names must be made up of only uppercase and lowercase ASCII letters,
        numbers, underscores, and hyphens, and must be between 1 and 256 characters long.
        For a FIFO topic, the name must end with the .fifo suffix.

        :param topic_name: The name for the topic.
        :return: The new topic.
        """
        try:
            topic = self.sns_resource.create_topic(
                Name=topic_name,
                Attributes={
                    "FifoTopic": str(True),
                    "ContentBasedDeduplication": str(False),
                    "FifoThroughputScope": "MessageGroup",
                },
            )
            logger.info("Created FIFO topic with name=%s.", topic_name)
            return topic
        except ClientError as error:
            logger.exception("Couldn't create topic with name=%s!", topic_name)
            raise error


    @staticmethod
    def add_access_policy(queue, topic_arn):
        """
        Add the necessary access policy to a queue, so
        it can receive messages from a topic.

        :param queue: The queue resource.
        :param topic_arn: The ARN of the topic.
        :return: None.
        """
        try:
            queue.set_attributes(
                Attributes={
                    "Policy": json.dumps(
                        {
                            "Version":"2012-10-17",		 	 	 
                            "Statement": [
                                {
                                    "Sid": "test-sid",
                                    "Effect": "Allow",
                                    "Principal": {"AWS": "*"},
                                    "Action": "SQS:SendMessage",
                                    "Resource": queue.attributes["QueueArn"],
                                    "Condition": {
                                        "ArnLike": {"aws:SourceArn": topic_arn}
                                    },
                                }
                            ],
                        }
                    )
                }
            )
            logger.info("Added trust policy to the queue.")
        except ClientError as error:
            logger.exception("Couldn't add trust policy to the queue!")
            raise error


    @staticmethod
    def subscribe_queue_to_topic(topic, queue_arn):
        """
        Subscribe a queue to a topic.

        :param topic: The topic resource.
        :param queue_arn: The ARN of the queue.
        :return: The subscription resource.
        """
        try:
            subscription = topic.subscribe(
                Protocol="sqs",
                Endpoint=queue_arn,
            )
            logger.info("The queue is subscribed to the topic.")
            return subscription
        except ClientError as error:
            logger.exception("Couldn't subscribe queue to topic!")
            raise error


    @staticmethod
    def publish_price_update(topic, payload, group_id):
        """
        Compose and publish a message that updates the wholesale price.

        :param topic: The topic to publish to.
        :param payload: The message to publish.
        :param group_id: The group ID for the message.
        :return: The ID of the message.
        """
        try:
            att_dict = {"business": {"DataType": "String", "StringValue": "wholesale"}}
            dedup_id = uuid.uuid4()
            response = topic.publish(
                Subject="Price Update",
                Message=payload,
                MessageAttributes=att_dict,
                MessageGroupId=group_id,
                MessageDeduplicationId=str(dedup_id),
            )
            message_id = response["MessageId"]
            logger.info("Published message to topic %s.", topic.arn)
        except ClientError as error:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise error
        return message_id


    @staticmethod
    def delete_queue(queue):
        """
        Removes an SQS queue. When run against an AWS account, it can take up to
        60 seconds before the queue is actually deleted.

        :param queue: The queue to delete.
        :return: None
        """
        try:
            queue.delete()
            logger.info("Deleted queue with URL=%s.", queue.url)
        except ClientError as error:
            logger.exception("Couldn't delete queue with URL=%s!", queue.url)
            raise error
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)
  + [Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)
  + [Subscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Subscribe)

### 動画内の人物や物体を検出する
<a name="cross_RekognitionVideoDetection_python_3_topic"></a>

次のコード例は、Amazon Rekognition で動画内の人やオブジェクトを検出する方法を示します。

**SDK for Python (Boto3)**  
 Amazon Rekognition を使用して、非同期検出ジョブを開始して、動画内の顔、オブジェクト、人を検出します。この例では、ジョブが完了し、Amazon Simple Queue Service (Amazon SQS) キューをトピックにサブスクライブしたときに、Amazon Simple Notification Service (Amazon SNS) トピックに通知するように Amazon Rekognition を設定します。キューがジョブに関するメッセージを受信すると、ジョブが取得され、結果が出力されます。  
 この例は GitHub で最もよく見られます。完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/rekognition) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3
+ Amazon SES
+ Amazon SNS
+ Amazon SQS

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/topics_and_queues#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class TopicsAndQueuesScenario:
    """Manages the Topics and Queues feature scenario."""

    DASHES = "-" * 80

    def __init__(self, sns_wrapper: SnsWrapper, sqs_wrapper: SqsWrapper) -> None:
        """
        Initialize the Topics and Queues scenario.

        :param sns_wrapper: SnsWrapper instance for SNS operations.
        :param sqs_wrapper: SqsWrapper instance for SQS operations.
        """
        self.sns_wrapper = sns_wrapper
        self.sqs_wrapper = sqs_wrapper
        
        # Scenario state
        self.use_fifo_topic = False
        self.use_content_based_deduplication = False
        self.topic_name = None
        self.topic_arn = None
        self.queue_count = 2
        self.queue_urls = []
        self.subscription_arns = []
        self.tones = ["cheerful", "funny", "serious", "sincere"]

    def run_scenario(self) -> None:
        """Run the Topics and Queues feature scenario."""
        print(self.DASHES)
        print("Welcome to messaging with topics and queues.")
        print(self.DASHES)
        print(f"""
    In this scenario, you will create an SNS topic and subscribe {self.queue_count} SQS queues to the topic.
    You can select from several options for configuring the topic and the subscriptions for the queues.
    You can then post to the topic and see the results in the queues.
        """)

        try:
            # Setup Phase
            print(self.DASHES)
            self._setup_topic()
            print(self.DASHES)

            self._setup_queues()
            print(self.DASHES)

            # Demonstration Phase
            self._publish_messages()
            print(self.DASHES)

            # Examination Phase
            self._poll_queues_for_messages()
            print(self.DASHES)

            # Cleanup Phase
            self._cleanup_resources()
            print(self.DASHES)

        except Exception as e:
            logger.error(f"Scenario failed: {e}")
            print(f"There was a problem with the scenario: {e}")
            print("\nInitiating cleanup...")
            try:
                self._cleanup_resources()
            except Exception as cleanup_error:
                logger.error(f"Error during cleanup: {cleanup_error}")

        print("Messaging with topics and queues scenario is complete.")
        print(self.DASHES)

    def _setup_topic(self) -> None:
        """Set up the SNS topic to be used with the queues."""
        print("SNS topics can be configured as FIFO (First-In-First-Out).")
        print("FIFO topics deliver messages in order and support deduplication and message filtering.")
        print()

        self.use_fifo_topic = q.ask("Would you like to work with FIFO topics? (y/n): ", q.is_yesno)

        if self.use_fifo_topic:
            print(self.DASHES)
            self.topic_name = q.ask("Enter a name for your SNS topic: ", q.non_empty)
            print("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.")
            print()

            print(self.DASHES)
            print("""
    Because you have chosen a FIFO topic, deduplication is supported.
    Deduplication IDs are either set in the message or automatically generated 
    from content using a hash function.
    
    If a message is successfully published to an SNS FIFO topic, any message 
    published and determined to have the same deduplication ID, 
    within the five-minute deduplication interval, is accepted but not delivered.
    
    For more information about deduplication, 
    see https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.
            """)

            self.use_content_based_deduplication = q.ask(
                "Use content-based deduplication instead of entering a deduplication ID? (y/n): ", 
                q.is_yesno
            )
        else:
            self.topic_name = q.ask("Enter a name for your SNS topic: ", q.non_empty)

        print(self.DASHES)

        # Create the topic
        self.topic_arn = self.sns_wrapper.create_topic(
            self.topic_name, 
            self.use_fifo_topic, 
            self.use_content_based_deduplication
        )

        print(f"Your new topic with the name {self.topic_name}")
        print(f"  and Amazon Resource Name (ARN) {self.topic_arn}")
        print(f"  has been created.")
        print()

    def _setup_queues(self) -> None:
        """Set up the SQS queues and subscribe them to the topic."""
        print(f"Now you will create {self.queue_count} Amazon Simple Queue Service (Amazon SQS) queues to subscribe to the topic.")

        for i in range(self.queue_count):
            queue_name = q.ask(f"Enter a name for SQS queue #{i+1}: ", q.non_empty)
            
            if self.use_fifo_topic and i == 0:
                print("Because you have selected a FIFO topic, '.fifo' must be appended to the queue name.")

            # Create the queue
            queue_url = self.sqs_wrapper.create_queue(queue_name, self.use_fifo_topic)
            self.queue_urls.append(queue_url)

            print(f"Your new queue with the name {queue_name}")
            print(f"  and queue URL {queue_url}")
            print(f"  has been created.")
            print()

            if i == 0:
                print("The queue URL is used to retrieve the queue ARN,")
                print("which is used to create a subscription.")
                print(self.DASHES)

            # Get queue ARN
            queue_arn = self.sqs_wrapper.get_queue_arn(queue_url)

            if i == 0:
                print("An AWS Identity and Access Management (IAM) policy must be attached to an SQS queue,")
                print("enabling it to receive messages from an SNS topic.")

            # Set queue policy to allow SNS to send messages
            self.sqs_wrapper.set_queue_policy_for_topic(queue_arn, self.topic_arn, queue_url)

            # Set up message filtering if using FIFO
            subscription_arn = self._setup_subscription_with_filter(i, queue_arn, queue_name)
            self.subscription_arns.append(subscription_arn)

    def _setup_subscription_with_filter(self, queue_index: int, queue_arn: str, queue_name: str) -> str:
        """Set up subscription with optional message filtering."""
        filter_policy = None
        
        if self.use_fifo_topic:
            print(self.DASHES)
            if queue_index == 0:
                print("Subscriptions to a FIFO topic can have filters.")
                print("If you add a filter to this subscription, then only the filtered messages")
                print("will be received in the queue.")
                print()
                print("For information about message filtering,")
                print("see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html")
                print()
                print("For this example, you can filter messages by a TONE attribute.")

            use_filter = q.ask(f"Filter messages for {queue_name}'s subscription to the topic? (y/n): ", q.is_yesno)
            
            if use_filter:
                filter_policy = self._create_filter_policy()

        subscription_arn = self.sns_wrapper.subscribe_queue_to_topic(
            self.topic_arn, queue_arn, filter_policy
        )

        print(f"The queue {queue_name} has been subscribed to the topic {self.topic_name}")
        print(f"  with the subscription ARN {subscription_arn}")

        return subscription_arn

    def _create_filter_policy(self) -> str:
        """Create a message filter policy based on user selections."""
        print(self.DASHES)
        print("You can filter messages by one or more of the following TONE attributes.")

        filter_selections = []
        selection_number = 0

        while True:
            print("Enter a number to add a TONE filter, or enter 0 to stop adding filters.")
            for i, tone in enumerate(self.tones, 1):
                print(f"  {i}. {tone}")

            selection = q.ask("Your choice: ", q.is_int, q.in_range(0, len(self.tones)))
            
            if selection == 0:
                break
            elif selection > 0 and self.tones[selection - 1] not in filter_selections:
                filter_selections.append(self.tones[selection - 1])
                print(f"Added '{self.tones[selection - 1]}' to filter list.")

        if filter_selections:
            filters = {"tone": filter_selections}
            return json.dumps(filters)
        return None

    def _publish_messages(self) -> None:
        """Publish messages to the topic with various options."""
        print("Now we can publish messages.")

        keep_sending = True
        while keep_sending:
            print()
            message = q.ask("Enter a message to publish: ", q.non_empty)

            message_group_id = None
            deduplication_id = None
            tone_attribute = None

            if self.use_fifo_topic:
                print("Because you are using a FIFO topic, you must set a message group ID.")
                print("All messages within the same group will be received in the order they were published.")
                print()
                message_group_id = q.ask("Enter a message group ID for this message: ", q.non_empty)

                if not self.use_content_based_deduplication:
                    print("Because you are not using content-based deduplication,")
                    print("you must enter a deduplication ID.")
                    deduplication_id = q.ask("Enter a deduplication ID for this message: ", q.non_empty)

                # Ask about tone attribute
                add_attribute = q.ask("Add an attribute to this message? (y/n): ", q.is_yesno)
                if add_attribute:
                    print("Enter a number for an attribute:")
                    for i, tone in enumerate(self.tones, 1):
                        print(f"  {i}. {tone}")
                    
                    selection = q.ask("Your choice: ", q.is_int, q.in_range(1, len(self.tones)))
                    if 1 <= selection <= len(self.tones):
                        tone_attribute = self.tones[selection - 1]

            # Publish the message
            message_id = self.sns_wrapper.publish_message(
                self.topic_arn,
                message,
                tone_attribute,
                deduplication_id,
                message_group_id
            )

            print(f"Message published with ID: {message_id}")

            keep_sending = q.ask("Send another message? (y/n): ", q.is_yesno)

    def _poll_queues_for_messages(self) -> None:
        """Poll all queues for messages and display results."""
        for i, queue_url in enumerate(self.queue_urls):
            print(f"Polling queue #{i+1} at {queue_url} for messages...")
            
            q.ask("Press Enter to continue...")

            messages = self._poll_queue_for_messages(queue_url)
            
            if messages:
                print(f"{len(messages)} message(s) were received by queue #{i+1}")
                for j, message in enumerate(messages, 1):
                    print(f"  Message {j}:")
                    # Parse the SNS message body to get the actual message
                    try:
                        sns_message = json.loads(message['Body'])
                        actual_message = sns_message.get('Message', message['Body'])
                        print(f"    {actual_message}")
                    except (json.JSONDecodeError, KeyError):
                        print(f"    {message['Body']}")

                # Delete the messages
                self.sqs_wrapper.delete_messages(queue_url, messages)
                print(f"Messages deleted from queue #{i+1}")
            else:
                print(f"No messages received by queue #{i+1}")
            
            print(self.DASHES)

    def _poll_queue_for_messages(self, queue_url: str) -> List[Dict[str, Any]]:
        """Poll a single queue for messages."""
        all_messages = []
        max_polls = 3  # Limit polling to avoid infinite loops
        
        for poll_count in range(max_polls):
            messages = self.sqs_wrapper.receive_messages(queue_url, 10)
            
            if messages:
                all_messages.extend(messages)
                print(f"  Received {len(messages)} messages in poll {poll_count + 1}")
                # Small delay between polls
                time.sleep(1)
            else:
                print(f"  No messages in poll {poll_count + 1}")
                break
                
        return all_messages

    def _cleanup_resources(self) -> None:
        """Clean up all resources created during the scenario."""
        print("Cleaning up resources...")

        # Delete queues
        for i, queue_url in enumerate(self.queue_urls):
            if queue_url:
                delete_queue = q.ask(f"Delete queue #{i+1} with URL {queue_url}? (y/n): ", q.is_yesno)
                if delete_queue:
                    try:
                        self.sqs_wrapper.delete_queue(queue_url)
                        print(f"Deleted queue #{i+1}")
                    except Exception as e:
                        print(f"Error deleting queue #{i+1}: {e}")

        # Unsubscribe from topic
        for i, subscription_arn in enumerate(self.subscription_arns):
            if subscription_arn:
                try:
                    self.sns_wrapper.unsubscribe(subscription_arn)
                    print(f"Unsubscribed subscription #{i+1}")
                except Exception as e:
                    print(f"Error unsubscribing #{i+1}: {e}")

        # Delete topic
        if self.topic_arn:
            delete_topic = q.ask(f"Delete topic {self.topic_name}? (y/n): ", q.is_yesno)
            if delete_topic:
                try:
                    self.sns_wrapper.delete_topic(self.topic_arn)
                    print(f"Deleted topic {self.topic_name}")
                except Exception as e:
                    print(f"Error deleting topic: {e}")

        print("Resource cleanup complete.")
```
シナリオで使用する Amazon SNS および Amazon SQS オペレーションをラップするクラスを作成します。  

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def create_topic(
        self, 
        topic_name: str, 
        is_fifo: bool = False, 
        content_based_deduplication: bool = False
    ) -> str:
        """
        Create an SNS topic.

        :param topic_name: The name of the topic to create.
        :param is_fifo: Whether to create a FIFO topic.
        :param content_based_deduplication: Whether to use content-based deduplication for FIFO topics.
        :return: The ARN of the created topic.
        :raises ClientError: If the topic creation fails.
        """
        try:
            # Add .fifo suffix for FIFO topics
            if is_fifo and not topic_name.endswith('.fifo'):
                topic_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoTopic'] = 'true'
                if content_based_deduplication:
                    attributes['ContentBasedDeduplication'] = 'true'

            response = self.sns_client.create_topic(
                Name=topic_name,
                Attributes=attributes
            )

            topic_arn = response['TopicArn']
            logger.info(f"Created topic: {topic_name} with ARN: {topic_arn}")
            return topic_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating topic {topic_name}: {error_code} - {e}")
            raise


    def subscribe_queue_to_topic(
        self, 
        topic_arn: str, 
        queue_arn: str, 
        filter_policy: Optional[str] = None
    ) -> str:
        """
        Subscribe an SQS queue to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param queue_arn: The ARN of the SQS queue.
        :param filter_policy: Optional JSON filter policy for message filtering.
        :return: The ARN of the subscription.
        :raises ClientError: If the subscription fails.
        """
        try:
            attributes = {}
            if filter_policy:
                attributes['FilterPolicy'] = filter_policy

            response = self.sns_client.subscribe(
                TopicArn=topic_arn,
                Protocol='sqs',
                Endpoint=queue_arn,
                Attributes=attributes
            )

            subscription_arn = response['SubscriptionArn']
            logger.info(f"Subscribed queue {queue_arn} to topic {topic_arn}")
            return subscription_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error subscribing queue to topic: {error_code} - {e}")
            raise


    def publish_message(
        self,
        topic_arn: str,
        message: str,
        tone_attribute: Optional[str] = None,
        deduplication_id: Optional[str] = None,
        message_group_id: Optional[str] = None
    ) -> str:
        """
        Publish a message to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param message: The message content to publish.
        :param tone_attribute: Optional tone attribute for message filtering.
        :param deduplication_id: Optional deduplication ID for FIFO topics.
        :param message_group_id: Optional message group ID for FIFO topics.
        :return: The message ID of the published message.
        :raises ClientError: If the message publication fails.
        """
        try:
            publish_args = {
                'TopicArn': topic_arn,
                'Message': message
            }

            # Add message attributes if tone is specified
            if tone_attribute:
                publish_args['MessageAttributes'] = {
                    'tone': {
                        'DataType': 'String',
                        'StringValue': tone_attribute
                    }
                }

            # Add FIFO-specific parameters
            if message_group_id:
                publish_args['MessageGroupId'] = message_group_id

            if deduplication_id:
                publish_args['MessageDeduplicationId'] = deduplication_id

            response = self.sns_client.publish(**publish_args)

            message_id = response['MessageId']
            logger.info(f"Published message to topic {topic_arn} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error publishing message to topic: {error_code} - {e}")
            raise


    def unsubscribe(self, subscription_arn: str) -> bool:
        """
        Unsubscribe from an SNS topic.

        :param subscription_arn: The ARN of the subscription to remove.
        :return: True if successful.
        :raises ClientError: If the unsubscribe operation fails.
        """
        try:
            self.sns_client.unsubscribe(SubscriptionArn=subscription_arn)
            
            logger.info(f"Unsubscribed: {subscription_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'NotFound':
                logger.warning(f"Subscription not found: {subscription_arn}")
                return True  # Already unsubscribed
            else:
                logger.error(f"Error unsubscribing: {error_code} - {e}")
                raise


    def delete_topic(self, topic_arn: str) -> bool:
        """
        Delete an SNS topic.

        :param topic_arn: The ARN of the topic to delete.
        :return: True if successful.
        :raises ClientError: If the topic deletion fails.
        """
        try:
            self.sns_client.delete_topic(TopicArn=topic_arn)
            
            logger.info(f"Deleted topic: {topic_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'NotFound':
                logger.warning(f"Topic not found: {topic_arn}")
                return True  # Already deleted
            else:
                logger.error(f"Error deleting topic: {error_code} - {e}")
                raise


    def list_topics(self) -> list:
        """
        List all SNS topics in the account using pagination.

        :return: List of topic ARNs.
        :raises ClientError: If listing topics fails.
        """
        try:
            topics = []
            paginator = self.sns_client.get_paginator('list_topics')
            
            for page in paginator.paginate():
                topics.extend([topic['TopicArn'] for topic in page.get('Topics', [])])
            
            logger.info(f"Found {len(topics)} topics")
            return topics

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            if error_code == 'AuthorizationError':
                logger.error("Authorization error listing topics - check IAM permissions")
            else:
                logger.error(f"Error listing topics: {error_code} - {e}")
            raise


class SqsWrapper:
    """Wrapper class for managing Amazon SQS operations."""

    def __init__(self, sqs_client: Any) -> None:
        """
        Initialize the SqsWrapper.

        :param sqs_client: A Boto3 Amazon SQS client.
        """
        self.sqs_client = sqs_client

    @classmethod
    def from_client(cls) -> 'SqsWrapper':
        """
        Create an SqsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sqs_client = boto3.client('sqs')
        return cls(sqs_client)


    def create_queue(self, queue_name: str, is_fifo: bool = False) -> str:
        """
        Create an SQS queue.

        :param queue_name: The name of the queue to create.
        :param is_fifo: Whether to create a FIFO queue.
        :return: The URL of the created queue.
        :raises ClientError: If the queue creation fails.
        """
        try:
            # Add .fifo suffix for FIFO queues
            if is_fifo and not queue_name.endswith('.fifo'):
                queue_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoQueue'] = 'true'

            response = self.sqs_client.create_queue(
                QueueName=queue_name,
                Attributes=attributes
            )

            queue_url = response['QueueUrl']
            logger.info(f"Created queue: {queue_name} with URL: {queue_url}")
            return queue_url

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating queue {queue_name}: {error_code} - {e}")
            raise


    def get_queue_arn(self, queue_url: str) -> str:
        """
        Get the ARN of an SQS queue.

        :param queue_url: The URL of the queue.
        :return: The ARN of the queue.
        :raises ClientError: If getting queue attributes fails.
        """
        try:
            response = self.sqs_client.get_queue_attributes(
                QueueUrl=queue_url,
                AttributeNames=['QueueArn']
            )

            queue_arn = response['Attributes']['QueueArn']
            logger.info(f"Queue ARN for {queue_url}: {queue_arn}")
            return queue_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error getting queue ARN: {error_code} - {e}")
            raise


    def set_queue_policy_for_topic(self, queue_arn: str, topic_arn: str, queue_url: str) -> bool:
        """
        Set the queue policy to allow SNS to send messages to the queue.

        :param queue_arn: The ARN of the SQS queue.
        :param topic_arn: The ARN of the SNS topic.
        :param queue_url: The URL of the SQS queue.
        :return: True if successful.
        :raises ClientError: If setting the queue policy fails.
        """
        try:
            # Create policy that allows SNS to send messages to the queue
            policy = {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {
                            "Service": "sns.amazonaws.com"
                        },
                        "Action": "sqs:SendMessage",
                        "Resource": queue_arn,
                        "Condition": {
                            "ArnEquals": {
                                "aws:SourceArn": topic_arn
                            }
                        }
                    }
                ]
            }

            self.sqs_client.set_queue_attributes(
                QueueUrl=queue_url,
                Attributes={
                    'Policy': json.dumps(policy)
                }
            )

            logger.info(f"Set queue policy for {queue_url} to allow messages from {topic_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error setting queue policy: {error_code} - {e}")
            raise


    def receive_messages(self, queue_url: str, max_messages: int = 10) -> List[Dict[str, Any]]:
        """
        Receive messages from an SQS queue.

        :param queue_url: The URL of the queue to receive messages from.
        :param max_messages: Maximum number of messages to receive (1-10).
        :return: List of received messages.
        :raises ClientError: If receiving messages fails.
        """
        try:
            # Ensure max_messages is within valid range
            max_messages = max(1, min(10, max_messages))

            response = self.sqs_client.receive_message(
                QueueUrl=queue_url,
                MaxNumberOfMessages=max_messages,
                WaitTimeSeconds=2,  # Short polling
                MessageAttributeNames=['All']
            )

            messages = response.get('Messages', [])
            logger.info(f"Received {len(messages)} messages from {queue_url}")
            return messages

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error receiving messages: {error_code} - {e}")
            raise


    def delete_messages(self, queue_url: str, messages: List[Dict[str, Any]]) -> bool:
        """
        Delete messages from an SQS queue in batches.

        :param queue_url: The URL of the queue.
        :param messages: List of messages to delete.
        :return: True if successful.
        :raises ClientError: If deleting messages fails.
        """
        try:
            if not messages:
                return True

            # Build delete entries for batch delete
            delete_entries = []
            for i, message in enumerate(messages):
                delete_entries.append({
                    'Id': str(i),
                    'ReceiptHandle': message['ReceiptHandle']
                })

            # Delete messages in batches of 10 (SQS limit)
            batch_size = 10
            for i in range(0, len(delete_entries), batch_size):
                batch = delete_entries[i:i + batch_size]
                
                response = self.sqs_client.delete_message_batch(
                    QueueUrl=queue_url,
                    Entries=batch
                )

                # Check for failures
                if 'Failed' in response and response['Failed']:
                    for failed in response['Failed']:
                        logger.warning(f"Failed to delete message: {failed}")

            logger.info(f"Deleted {len(messages)} messages from {queue_url}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error deleting messages: {error_code} - {e}")
            raise


    def delete_queue(self, queue_url: str) -> bool:
        """
        Delete an SQS queue.

        :param queue_url: The URL of the queue to delete.
        :return: True if successful.
        :raises ClientError: If the queue deletion fails.
        """
        try:
            self.sqs_client.delete_queue(QueueUrl=queue_url)
            
            logger.info(f"Deleted queue: {queue_url}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'AWS.SimpleQueueService.NonExistentQueue':
                logger.warning(f"Queue not found: {queue_url}")
                return True  # Already deleted
            else:
                logger.error(f"Error deleting queue: {error_code} - {e}")
                raise


    def list_queues(self, queue_name_prefix: Optional[str] = None) -> List[str]:
        """
        List all SQS queues in the account using pagination.

        :param queue_name_prefix: Optional prefix to filter queue names.
        :return: List of queue URLs.
        :raises ClientError: If listing queues fails.
        """
        try:
            queue_urls = []
            paginator = self.sqs_client.get_paginator('list_queues')
            
            page_params = {}
            if queue_name_prefix:
                page_params['QueueNamePrefix'] = queue_name_prefix

            for page in paginator.paginate(**page_params):
                queue_urls.extend(page.get('QueueUrls', []))
            
            logger.info(f"Found {len(queue_urls)} queues")
            return queue_urls

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            if error_code == 'AccessDenied':
                logger.error("Access denied listing queues - check IAM permissions")
            else:
                logger.error(f"Error listing queues: {error_code} - {e}")
            raise

    def send_message(self, queue_url: str, message_body: str, **kwargs) -> str:
        """
        Send a message to an SQS queue.

        :param queue_url: The URL of the queue.
        :param message_body: The message content.
        :param kwargs: Additional message parameters (DelaySeconds, MessageAttributes, etc.).
        :return: The message ID.
        :raises ClientError: If sending the message fails.
        """
        try:
            send_params = {
                'QueueUrl': queue_url,
                'MessageBody': message_body,
                **kwargs
            }

            response = self.sqs_client.send_message(**send_params)
            
            message_id = response['MessageId']
            logger.info(f"Sent message to {queue_url} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error sending message: {error_code} - {e}")
            raise
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/CreateQueue)
  + [CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteQueue)
  + [DeleteTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/DeleteTopic)
  + [GetQueueAttributes](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/GetQueueAttributes)
  + [Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/ReceiveMessage)
  + [SetQueueAttributes](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/SetQueueAttributes)
  + [Subscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Subscribe)
  + [Unsubscribe](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Unsubscribe)

### バッチメッセージを送受信する
<a name="sqs_Scenario_SendReceiveBatch_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon SQS キューを作成します。
+ キューにバッチメッセージを送信します。
+ キューからバッチメッセージを受信します。
+ キューからバッチメッセージを受信します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS メッセージ関数をラップする関数を作成します。  

```
import logging
import sys

import boto3
from botocore.exceptions import ClientError

import queue_wrapper

logger = logging.getLogger(__name__)
sqs = boto3.resource("sqs")

def send_messages(queue, messages):
    """
    Send a batch of messages in a single request to an SQS queue.
    This request may return overall success even when some messages were not sent.
    The caller must inspect the Successful and Failed lists in the response and
    resend any failed messages.

    :param queue: The queue to receive the messages.
    :param messages: The messages to send to the queue. These are simplified to
                     contain only the message body and attributes.
    :return: The response from SQS that contains the list of successful and failed
             messages.
    """
    try:
        entries = [
            {
                "Id": str(ind),
                "MessageBody": msg["body"],
                "MessageAttributes": msg["attributes"],
            }
            for ind, msg in enumerate(messages)
        ]
        response = queue.send_messages(Entries=entries)
        if "Successful" in response:
            for msg_meta in response["Successful"]:
                logger.info(
                    "Message sent: %s: %s",
                    msg_meta["MessageId"],
                    messages[int(msg_meta["Id"])]["body"],
                )
        if "Failed" in response:
            for msg_meta in response["Failed"]:
                logger.warning(
                    "Failed to send: %s: %s",
                    msg_meta["MessageId"],
                    messages[int(msg_meta["Id"])]["body"],
                )
    except ClientError as error:
        logger.exception("Send messages failed to queue: %s", queue)
        raise error
    else:
        return response



def receive_messages(queue, max_number, wait_time):
    """
    Receive a batch of messages in a single request from an SQS queue.

    :param queue: The queue from which to receive messages.
    :param max_number: The maximum number of messages to receive. The actual number
                       of messages received might be less.
    :param wait_time: The maximum time to wait (in seconds) before returning. When
                      this number is greater than zero, long polling is used. This
                      can result in reduced costs and fewer false empty responses.
    :return: The list of Message objects received. These each contain the body
             of the message and metadata and custom attributes.
    """
    try:
        messages = queue.receive_messages(
            MessageAttributeNames=["All"],
            MaxNumberOfMessages=max_number,
            WaitTimeSeconds=wait_time,
        )
        for msg in messages:
            logger.info("Received message: %s: %s", msg.message_id, msg.body)
    except ClientError as error:
        logger.exception("Couldn't receive messages from queue: %s", queue)
        raise error
    else:
        return messages



def delete_messages(queue, messages):
    """
    Delete a batch of messages from a queue in a single request.

    :param queue: The queue from which to delete the messages.
    :param messages: The list of messages to delete.
    :return: The response from SQS that contains the list of successful and failed
             message deletions.
    """
    try:
        entries = [
            {"Id": str(ind), "ReceiptHandle": msg.receipt_handle}
            for ind, msg in enumerate(messages)
        ]
        response = queue.delete_messages(Entries=entries)
        if "Successful" in response:
            for msg_meta in response["Successful"]:
                logger.info("Deleted %s", messages[int(msg_meta["Id"])].receipt_handle)
        if "Failed" in response:
            for msg_meta in response["Failed"]:
                logger.warning(
                    "Could not delete %s", messages[int(msg_meta["Id"])].receipt_handle
                )
    except ClientError:
        logger.exception("Couldn't delete messages from queue %s", queue)
    else:
        return response
```
ラッパー関数を使用してメッセージをバッチで送受信します。  

```
def usage_demo():
    """
    Shows how to:
    * Read the lines from this Python file and send the lines in
      batches of 10 as messages to a queue.
    * Receive the messages in batches until the queue is empty.
    * Reassemble the lines of the file and verify they match the original file.
    """

    def pack_message(msg_path, msg_body, msg_line):
        return {
            "body": msg_body,
            "attributes": {
                "path": {"StringValue": msg_path, "DataType": "String"},
                "line": {"StringValue": str(msg_line), "DataType": "String"},
            },
        }

    def unpack_message(msg):
        return (
            msg.message_attributes["path"]["StringValue"],
            msg.body,
            int(msg.message_attributes["line"]["StringValue"]),
        )

    print("-" * 88)
    print("Welcome to the Amazon Simple Queue Service (Amazon SQS) demo!")
    print("-" * 88)

    queue = queue_wrapper.create_queue("sqs-usage-demo-message-wrapper")

    with open(__file__) as file:
        lines = file.readlines()

    line = 0
    batch_size = 10
    received_lines = [None] * len(lines)
    print(f"Sending file lines in batches of {batch_size} as messages.")
    while line < len(lines):
        messages = [
            pack_message(__file__, lines[index], index)
            for index in range(line, min(line + batch_size, len(lines)))
        ]
        line = line + batch_size
        send_messages(queue, messages)
        print(".", end="")
        sys.stdout.flush()
    print(f"Done. Sent {len(lines) - 1} messages.")

    print(f"Receiving, handling, and deleting messages in batches of {batch_size}.")
    more_messages = True
    while more_messages:
        received_messages = receive_messages(queue, batch_size, 2)
        print(".", end="")
        sys.stdout.flush()
        for message in received_messages:
            path, body, line = unpack_message(message)
            received_lines[line] = body
        if received_messages:
            delete_messages(queue, received_messages)
        else:
            more_messages = False
    print("Done.")

    if all([lines[index] == received_lines[index] for index in range(len(lines))]):
        print(f"Successfully reassembled all file lines!")
    else:
        print(f"Uh oh, some lines were missed!")

    queue.delete()

    print("Thanks for watching!")
    print("-" * 88)
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/CreateQueue)
  + [DeleteMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteMessage)
  + [DeleteMessageBatch](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteMessageBatch)
  + [DeleteQueue](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/DeleteQueue)
  + [ReceiveMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/ReceiveMessage)
  + [SendMessage](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/SendMessage)
  + [SendMessageBatch](https://docs.aws.amazon.com/goto/boto3/sqs-2012-11-05/SendMessageBatch)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_python_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での SQS イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event, context):
    for message in event['Records']:
        process_message(message)
    print("done")

def process_message(message):
    try:
        print(f"Processed message {message['body']}")
        # TODO: Do interesting work based on the new message
    except Exception as err:
        print("An error occurred")
        raise err
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_python_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Python を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

def lambda_handler(event, context):
    if event:
        batch_item_failures = []
        sqs_batch_response = {}
     
        for record in event["Records"]:
            try:
                print(f"Processed message: {record['body']}")
            except Exception as e:
                batch_item_failures.append({"itemIdentifier": record['messageId']})
        
        sqs_batch_response["batchItemFailures"] = batch_item_failures
        return sqs_batch_response
```

# SDK for Python (Boto3) を使用した Step Functions の例
<a name="python_3_sfn_code_examples"></a>

次のコード例は、Step Functions AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Step Functions
<a name="sfn_Hello_python_3_topic"></a>

次のコード例は、Step Functions の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
import boto3


def hello_stepfunctions(stepfunctions_client):
    """
    Use the AWS SDK for Python (Boto3) to create an AWS Step Functions client and list
    the state machines in your account. This list might be empty if you haven't created
    any state machines.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param stepfunctions_client: A Boto3 Step Functions Client object.
    """
    print("Hello, Step Functions! Let's list up to 10 of your state machines:")
    state_machines = stepfunctions_client.list_state_machines(maxResults=10)
    for sm in state_machines["stateMachines"]:
        print(f"\t{sm['name']}: {sm['stateMachineArn']}")


if __name__ == "__main__":
    hello_stepfunctions(boto3.client("stepfunctions"))
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListStateMachines](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/ListStateMachines)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="sfn_Scenario_GetStartedStateMachines_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ アクティビティを作成します。
+ 以前に作成したアクティビティをステップとして含む Amazon States Language 定義からステートマシンを作成します。
+ ステートマシンを実行し、ユーザー入力でアクティビティに応答します。
+ 実行が完了したら最終ステータスと出力を取得して、リソースをクリーンアップします。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class StateMachineScenario:
    """Runs an interactive scenario that shows how to get started using Step Functions."""

    def __init__(self, activity, state_machine, iam_client):
        """
        :param activity: An object that wraps activity actions.
        :param state_machine: An object that wraps state machine actions.
        :param iam_client: A Boto3 AWS Identity and Access Management (IAM) client.
        """
        self.activity = activity
        self.state_machine = state_machine
        self.iam_client = iam_client
        self.state_machine_role = None

    def prerequisites(self, state_machine_role_name):
        """
        Finds or creates an IAM role that can be assumed by Step Functions.
        A role of this kind is required to create a state machine.
        The state machine used in this example does not call any additional services,
        so it needs no additional permissions.

        :param state_machine_role_name: The name of the role.
        :return: Data about the role.
        """
        trust_policy = {
            "Version":"2012-10-17",		 	 	 
            "Statement": [
                {
                    "Sid": "",
                    "Effect": "Allow",
                    "Principal": {"Service": "states.amazonaws.com"},
                    "Action": "sts:AssumeRole",
                }
            ],
        }
        try:
            role = self.iam_client.get_role(RoleName=state_machine_role_name)
            print(f"Prerequisite IAM role {state_machine_role_name} already exists.")
        except ClientError as err:
            if err.response["Error"]["Code"] == "NoSuchEntity":
                role = None
            else:
                logger.error(
                    "Couldn't get prerequisite IAM role %s. Here's why: %s: %s",
                    state_machine_role_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        if role is None:
            try:
                role = self.iam_client.create_role(
                    RoleName=state_machine_role_name,
                    AssumeRolePolicyDocument=json.dumps(trust_policy),
                )
            except ClientError as err:
                logger.error(
                    "Couldn't create prerequisite IAM role %s. Here's why: %s: %s",
                    state_machine_role_name,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        self.state_machine_role = role["Role"]

    def find_or_create_activity(self, activity_name):
        """
        Finds or creates a Step Functions activity.

        :param activity_name: The name of the activity.
        :return: The Amazon Resource Name (ARN) of the activity.
        """
        print("First, let's set up an activity and state machine.")
        activity_arn = self.activity.find(activity_name)
        if activity_arn is None:
            activity_arn = self.activity.create(activity_name)
            print(
                f"Activity {activity_name} created. Its Amazon Resource Name (ARN) is "
                f"{activity_arn}."
            )
        else:
            print(f"Activity {activity_name} already exists.")
        return activity_arn

    def find_or_create_state_machine(
        self, state_machine_name, activity_arn, state_machine_file
    ):
        """
        Finds or creates a Step Functions state machine.

        :param state_machine_name: The name of the state machine.
        :param activity_arn: The ARN of an activity that is used as a step in the state
                             machine. This ARN is injected into the state machine
                             definition that's used to create the state machine.
        :param state_machine_file: The path to a file containing the state machine
                                   definition.
        :return: The ARN of the state machine.
        """
        state_machine_arn = self.state_machine.find(state_machine_name)
        if state_machine_arn is None:
            with open(state_machine_file) as state_machine_file:
                state_machine_def = state_machine_file.read().replace(
                    "{{DOC_EXAMPLE_ACTIVITY_ARN}}", activity_arn
                )
                state_machine_arn = self.state_machine.create(
                    state_machine_name,
                    state_machine_def,
                    self.state_machine_role["Arn"],
                )
            print(f"State machine {state_machine_name} created.")
        else:
            print(f"State machine {state_machine_name} already exists.")
        print("-" * 88)
        print(f"Here's some information about state machine {state_machine_name}:")
        state_machine_info = self.state_machine.describe(state_machine_arn)
        for field in ["name", "status", "stateMachineArn", "roleArn"]:
            print(f"\t{field}: {state_machine_info[field]}")
        return state_machine_arn

    def run_state_machine(self, state_machine_arn, activity_arn):
        """
        Run the state machine. The state machine used in this example is a simple
        chat simulation. It contains an activity step in a loop that is used for user
        interaction. When the state machine gets to the activity step, it waits for
        an external application to get task data and submit a response. This function
        acts as the activity application by getting task input and responding with
        user input.

        :param state_machine_arn: The ARN of the state machine.
        :param activity_arn: The ARN of the activity used as a step in the state machine.
        :return: The ARN of the run.
        """
        print(
            f"Let's run the state machine. It's a simplistic, non-AI chat simulator "
            f"we'll call ChatSFN."
        )
        user_name = q.ask("What should ChatSFN call you? ", q.non_empty)
        run_input = {"name": user_name}
        print("Starting state machine...")
        run_arn = self.state_machine.start(state_machine_arn, json.dumps(run_input))
        action = None
        while action != "done":
            activity_task = self.activity.get_task(activity_arn)
            task_input = json.loads(activity_task["input"])
            print(f"ChatSFN: {task_input['message']}")
            action = task_input["actions"][
                q.choose("What now? ", task_input["actions"])
            ]
            task_response = {"action": action}
            self.activity.send_task_success(
                activity_task["taskToken"], json.dumps(task_response)
            )
        return run_arn

    def finish_state_machine_run(self, run_arn):
        """
        Wait for the state machine run to finish, then print final status and output.

        :param run_arn: The ARN of the run to retrieve.
        """
        print(f"Let's get the final output from the state machine:")
        status = "RUNNING"
        while status == "RUNNING":
            run_output = self.state_machine.describe_run(run_arn)
            status = run_output["status"]
            if status == "RUNNING":
                print(
                    "The state machine is still running, let's wait for it to finish."
                )
                wait(1)
            elif status == "SUCCEEDED":
                print(f"ChatSFN: {json.loads(run_output['output'])['message']}")
            else:
                print(f"Run status: {status}.")

    def cleanup(
        self,
        state_machine_name,
        state_machine_arn,
        activity_name,
        activity_arn,
        state_machine_role_name,
    ):
        """
        Clean up resources created by this example.

        :param state_machine_name: The name of the state machine.
        :param state_machine_arn: The ARN of the state machine.
        :param activity_name: The name of the activity.
        :param activity_arn: The ARN of the activity.
        :param state_machine_role_name: The name of the role used by the state machine.
        """
        if q.ask(
            "Do you want to delete the state machine, activity, and role created for this "
            "example? (y/n) ",
            q.is_yesno,
        ):
            self.state_machine.delete(state_machine_arn)
            print(f"Deleted state machine {state_machine_name}.")
            self.activity.delete(activity_arn)
            print(f"Deleted activity {activity_name}.")
            self.iam_client.delete_role(RoleName=state_machine_role_name)
            print(f"Deleted role {state_machine_role_name}.")

    def run_scenario(self, activity_name, state_machine_name):
        print("-" * 88)
        print("Welcome to the AWS Step Functions state machines demo.")
        print("-" * 88)

        activity_arn = self.find_or_create_activity(activity_name)
        state_machine_arn = self.find_or_create_state_machine(
            state_machine_name,
            activity_arn,
            "../../../resources/sample_files/chat_sfn_state_machine.json",
        )
        print("-" * 88)
        run_arn = self.run_state_machine(state_machine_arn, activity_arn)
        print("-" * 88)
        self.finish_state_machine_run(run_arn)
        print("-" * 88)
        self.cleanup(
            state_machine_name,
            state_machine_arn,
            activity_name,
            activity_arn,
            self.state_machine_role["RoleName"],
        )

        print("-" * 88)
        print("\nThanks for watching!")
        print("-" * 88)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
    try:
        stepfunctions_client = boto3.client("stepfunctions")
        iam_client = boto3.client("iam")
        scenario = StateMachineScenario(
            Activity(stepfunctions_client),
            StateMachine(stepfunctions_client),
            iam_client,
        )
        scenario.prerequisites("doc-example-state-machine-chat")
        scenario.run_scenario("doc-example-activity", "doc-example-state-machine")
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
ステートマシンアクションをラップするクラスを定義します。  

```
class StateMachine:
    """Encapsulates Step Functions state machine actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def create(self, name, definition, role_arn):
        """
        Creates a state machine with the specific definition. The state machine assumes
        the provided role before it starts a run.

        :param name: The name to give the state machine.
        :param definition: The Amazon States Language definition of the steps in the
                           the state machine.
        :param role_arn: The Amazon Resource Name (ARN) of the role that is assumed by
                         Step Functions when the state machine is run.
        :return: The ARN of the newly created state machine.
        """
        try:
            response = self.stepfunctions_client.create_state_machine(
                name=name, definition=definition, roleArn=role_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't create state machine %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["stateMachineArn"]


    def find(self, name):
        """
        Find a state machine by name. This requires listing the state machines until
        one is found with a matching name.

        :param name: The name of the state machine to search for.
        :return: The ARN of the state machine if found; otherwise, None.
        """
        try:
            paginator = self.stepfunctions_client.get_paginator("list_state_machines")
            for page in paginator.paginate():
                for state_machine in page.get("stateMachines", []):
                    if state_machine["name"] == name:
                        return state_machine["stateMachineArn"]
        except ClientError as err:
            logger.error(
                "Couldn't list state machines. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def describe(self, state_machine_arn):
        """
        Get data about a state machine.

        :param state_machine_arn: The ARN of the state machine to look up.
        :return: The retrieved state machine data.
        """
        try:
            response = self.stepfunctions_client.describe_state_machine(
                stateMachineArn=state_machine_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't describe state machine %s. Here's why: %s: %s",
                state_machine_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def start(self, state_machine_arn, run_input):
        """
        Start a run of a state machine with a specified input. A run is also known
        as an "execution" in Step Functions.

        :param state_machine_arn: The ARN of the state machine to run.
        :param run_input: The input to the state machine, in JSON format.
        :return: The ARN of the run. This can be used to get information about the run,
                 including its current status and final output.
        """
        try:
            response = self.stepfunctions_client.start_execution(
                stateMachineArn=state_machine_arn, input=run_input
            )
        except ClientError as err:
            logger.error(
                "Couldn't start state machine %s. Here's why: %s: %s",
                state_machine_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["executionArn"]


    def describe_run(self, run_arn):
        """
        Get data about a state machine run, such as its current status or final output.

        :param run_arn: The ARN of the run to look up.
        :return: The retrieved run data.
        """
        try:
            response = self.stepfunctions_client.describe_execution(
                executionArn=run_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't describe run %s. Here's why: %s: %s",
                run_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def delete(self, state_machine_arn):
        """
        Delete a state machine and all of its run data.

        :param state_machine_arn: The ARN of the state machine to delete.
        """
        try:
            response = self.stepfunctions_client.delete_state_machine(
                stateMachineArn=state_machine_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete state machine %s. Here's why: %s: %s",
                state_machine_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
アクティビティアクションをラップするクラスを定義します。  

```
class Activity:
    """Encapsulates Step Function activity actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def create(self, name):
        """
        Create an activity.

        :param name: The name of the activity to create.
        :return: The Amazon Resource Name (ARN) of the newly created activity.
        """
        try:
            response = self.stepfunctions_client.create_activity(name=name)
        except ClientError as err:
            logger.error(
                "Couldn't create activity %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["activityArn"]


    def find(self, name):
        """
        Find an activity by name. This requires listing activities until one is found
        with a matching name.

        :param name: The name of the activity to search for.
        :return: If found, the ARN of the activity; otherwise, None.
        """
        try:
            paginator = self.stepfunctions_client.get_paginator("list_activities")
            for page in paginator.paginate():
                for activity in page.get("activities", []):
                    if activity["name"] == name:
                        return activity["activityArn"]
        except ClientError as err:
            logger.error(
                "Couldn't list activities. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def get_task(self, activity_arn):
        """
        Gets task data for an activity. When a state machine is waiting for the
        specified activity, a response is returned with data from the state machine.
        When a state machine is not waiting, this call blocks for 60 seconds.

        :param activity_arn: The ARN of the activity to get task data for.
        :return: The task data for the activity.
        """
        try:
            response = self.stepfunctions_client.get_activity_task(
                activityArn=activity_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't get a task for activity %s. Here's why: %s: %s",
                activity_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response


    def send_task_success(self, task_token, task_response):
        """
        Sends a success response to a waiting activity step. A state machine with an
        activity step waits for the activity to get task data and then respond with
        either success or failure before it resumes processing.

        :param task_token: The token associated with the task. This is included in the
                           response to the get_activity_task action and must be sent
                           without modification.
        :param task_response: The response data from the activity. This data is
                              received and processed by the state machine.
        """
        try:
            self.stepfunctions_client.send_task_success(
                taskToken=task_token, output=task_response
            )
        except ClientError as err:
            logger.error(
                "Couldn't send task success. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete(self, activity_arn):
        """
        Delete an activity.

        :param activity_arn: The ARN of the activity to delete.
        """
        try:
            response = self.stepfunctions_client.delete_activity(
                activityArn=activity_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete activity %s. Here's why: %s: %s",
                activity_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [CreateActivity](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/CreateActivity)
  + [CreateStateMachine](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/CreateStateMachine)
  + [DeleteActivity](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DeleteActivity)
  + [DeleteStateMachine](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DeleteStateMachine)
  + [DescribeExecution](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DescribeExecution)
  + [DescribeStateMachine](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DescribeStateMachine)
  + [GetActivityTask](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/GetActivityTask)
  + [ListActivities](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/ListActivities)
  + [ListStateMachines](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/ListStateMachines)
  + [SendTaskSuccess](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/SendTaskSuccess)
  + [StartExecution](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/StartExecution)
  + [StopExecution](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/StopExecution)

## アクション
<a name="actions"></a>

### `CreateActivity`
<a name="sfn_CreateActivity_python_3_topic"></a>

次のコード例は、`CreateActivity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class Activity:
    """Encapsulates Step Function activity actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def create(self, name):
        """
        Create an activity.

        :param name: The name of the activity to create.
        :return: The Amazon Resource Name (ARN) of the newly created activity.
        """
        try:
            response = self.stepfunctions_client.create_activity(name=name)
        except ClientError as err:
            logger.error(
                "Couldn't create activity %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["activityArn"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateActivity](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/CreateActivity)」を参照してください。

### `CreateStateMachine`
<a name="sfn_CreateStateMachine_python_3_topic"></a>

次のコード例は、`CreateStateMachine` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class StateMachine:
    """Encapsulates Step Functions state machine actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def create(self, name, definition, role_arn):
        """
        Creates a state machine with the specific definition. The state machine assumes
        the provided role before it starts a run.

        :param name: The name to give the state machine.
        :param definition: The Amazon States Language definition of the steps in the
                           the state machine.
        :param role_arn: The Amazon Resource Name (ARN) of the role that is assumed by
                         Step Functions when the state machine is run.
        :return: The ARN of the newly created state machine.
        """
        try:
            response = self.stepfunctions_client.create_state_machine(
                name=name, definition=definition, roleArn=role_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't create state machine %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["stateMachineArn"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateStateMachine](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/CreateStateMachine)」を参照してください。

### `DeleteActivity`
<a name="sfn_DeleteActivity_python_3_topic"></a>

次のコード例は、`DeleteActivity` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class Activity:
    """Encapsulates Step Function activity actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def delete(self, activity_arn):
        """
        Delete an activity.

        :param activity_arn: The ARN of the activity to delete.
        """
        try:
            response = self.stepfunctions_client.delete_activity(
                activityArn=activity_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete activity %s. Here's why: %s: %s",
                activity_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteActivity](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DeleteActivity)」を参照してください。

### `DeleteStateMachine`
<a name="sfn_DeleteStateMachine_python_3_topic"></a>

次のコード例は、`DeleteStateMachine` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class StateMachine:
    """Encapsulates Step Functions state machine actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def delete(self, state_machine_arn):
        """
        Delete a state machine and all of its run data.

        :param state_machine_arn: The ARN of the state machine to delete.
        """
        try:
            response = self.stepfunctions_client.delete_state_machine(
                stateMachineArn=state_machine_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't delete state machine %s. Here's why: %s: %s",
                state_machine_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteStateMachine](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DeleteStateMachine)」を参照してください。

### `DescribeExecution`
<a name="sfn_DescribeExecution_python_3_topic"></a>

次のコード例は、`DescribeExecution` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
    def describe_run(self, run_arn):
        """
        Get data about a state machine run, such as its current status or final output.

        :param run_arn: The ARN of the run to look up.
        :return: The retrieved run data.
        """
        try:
            response = self.stepfunctions_client.describe_execution(
                executionArn=run_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't describe run %s. Here's why: %s: %s",
                run_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeExecution](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DescribeExecution)」を参照してください。

### `DescribeStateMachine`
<a name="sfn_DescribeStateMachine_python_3_topic"></a>

次のコード例は、`DescribeStateMachine` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class StateMachine:
    """Encapsulates Step Functions state machine actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def describe(self, state_machine_arn):
        """
        Get data about a state machine.

        :param state_machine_arn: The ARN of the state machine to look up.
        :return: The retrieved state machine data.
        """
        try:
            response = self.stepfunctions_client.describe_state_machine(
                stateMachineArn=state_machine_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't describe state machine %s. Here's why: %s: %s",
                state_machine_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DescribeStateMachine](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/DescribeStateMachine)」を参照してください。

### `GetActivityTask`
<a name="sfn_GetActivityTask_python_3_topic"></a>

次のコード例は、`GetActivityTask` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class Activity:
    """Encapsulates Step Function activity actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def get_task(self, activity_arn):
        """
        Gets task data for an activity. When a state machine is waiting for the
        specified activity, a response is returned with data from the state machine.
        When a state machine is not waiting, this call blocks for 60 seconds.

        :param activity_arn: The ARN of the activity to get task data for.
        :return: The task data for the activity.
        """
        try:
            response = self.stepfunctions_client.get_activity_task(
                activityArn=activity_arn
            )
        except ClientError as err:
            logger.error(
                "Couldn't get a task for activity %s. Here's why: %s: %s",
                activity_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetActivityTask](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/GetActivityTask)」を参照してください。

### `ListActivities`
<a name="sfn_ListActivities_python_3_topic"></a>

次のコード例は、`ListActivities` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class Activity:
    """Encapsulates Step Function activity actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def find(self, name):
        """
        Find an activity by name. This requires listing activities until one is found
        with a matching name.

        :param name: The name of the activity to search for.
        :return: If found, the ARN of the activity; otherwise, None.
        """
        try:
            paginator = self.stepfunctions_client.get_paginator("list_activities")
            for page in paginator.paginate():
                for activity in page.get("activities", []):
                    if activity["name"] == name:
                        return activity["activityArn"]
        except ClientError as err:
            logger.error(
                "Couldn't list activities. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListActivities](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/ListActivities)」を参照してください。

### `ListStateMachines`
<a name="sfn_ListStateMachines_python_3_topic"></a>

次のコード例は、`ListStateMachines` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。
アカウントのステートマシンのリストを検索して、ステートマシンを名前で検索します。  

```
class StateMachine:
    """Encapsulates Step Functions state machine actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def find(self, name):
        """
        Find a state machine by name. This requires listing the state machines until
        one is found with a matching name.

        :param name: The name of the state machine to search for.
        :return: The ARN of the state machine if found; otherwise, None.
        """
        try:
            paginator = self.stepfunctions_client.get_paginator("list_state_machines")
            for page in paginator.paginate():
                for state_machine in page.get("stateMachines", []):
                    if state_machine["name"] == name:
                        return state_machine["stateMachineArn"]
        except ClientError as err:
            logger.error(
                "Couldn't list state machines. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[ListStateMachines](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/ListStateMachines)」を参照してください。

### `SendTaskSuccess`
<a name="sfn_SendTaskSuccess_python_3_topic"></a>

次のコード例は、`SendTaskSuccess` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class Activity:
    """Encapsulates Step Function activity actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def send_task_success(self, task_token, task_response):
        """
        Sends a success response to a waiting activity step. A state machine with an
        activity step waits for the activity to get task data and then respond with
        either success or failure before it resumes processing.

        :param task_token: The token associated with the task. This is included in the
                           response to the get_activity_task action and must be sent
                           without modification.
        :param task_response: The response data from the activity. This data is
                              received and processed by the state machine.
        """
        try:
            self.stepfunctions_client.send_task_success(
                taskToken=task_token, output=task_response
            )
        except ClientError as err:
            logger.error(
                "Couldn't send task success. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[SendTaskSuccess](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/SendTaskSuccess)」を参照してください。

### `StartExecution`
<a name="sfn_StartExecution_python_3_topic"></a>

次のコード例は、`StartExecution` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/stepfunctions#code-examples)での設定と実行の方法を確認してください。

```
class StateMachine:
    """Encapsulates Step Functions state machine actions."""

    def __init__(self, stepfunctions_client):
        """
        :param stepfunctions_client: A Boto3 Step Functions client.
        """
        self.stepfunctions_client = stepfunctions_client


    def start(self, state_machine_arn, run_input):
        """
        Start a run of a state machine with a specified input. A run is also known
        as an "execution" in Step Functions.

        :param state_machine_arn: The ARN of the state machine to run.
        :param run_input: The input to the state machine, in JSON format.
        :return: The ARN of the run. This can be used to get information about the run,
                 including its current status and final output.
        """
        try:
            response = self.stepfunctions_client.start_execution(
                stateMachineArn=state_machine_arn, input=run_input
            )
        except ClientError as err:
            logger.error(
                "Couldn't start state machine %s. Here's why: %s: %s",
                state_machine_arn,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        else:
            return response["executionArn"]
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartExecution](https://docs.aws.amazon.com/goto/boto3/states-2016-11-23/StartExecution)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### メッセンジャーアプリケーションを作成する
<a name="cross_StepFunctionsMessenger_python_3_topic"></a>

次のコード例は、データベーステーブルからメッセージレコードを取得する AWS Step Functions メッセンジャーアプリケーションを作成する方法を示しています。

**SDK for Python (Boto3)**  
 AWS SDK for Python (Boto3) で を使用して AWS Step Functions 、Amazon DynamoDB テーブルからメッセージレコードを取得し、Amazon Simple Queue Service (Amazon SQS) で送信するメッセンジャーアプリケーションを作成する方法を示します。ステートマシンは AWS Lambda 関数と統合して、未送信メッセージがないかデータベースをスキャンします。  
+ Amazon DynamoDB テーブルからメッセージレコードを取得および更新するステートマシンを作成します。
+ ステートマシンの定義を更新して、Amazon Simple Queue Service (Amazon SQS) にもメッセージを送信します。
+ ステートマシンの実行を開始および停止します。
+ サービス統合を使用して、ステートマシンから Lambda、DynamoDB、および Amazon SQS に接続します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/stepfunctions_messenger) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Lambda
+ Amazon SQS
+ ステップ関数

### Step Functions を使用して生成 AI アプリケーションをオーケストレーションする
<a name="cross_ServerlessPromptChaining_python_3_topic"></a>

次のコード例は、Amazon Bedrock と Step Functions を使用して生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Bedrock Serverless のプロンプトチェイニングシナリオは、[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)、[Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)、および [https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html](https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html) を使用して、複雑でサーバーレス、高度にスケーラブルな生成 AI アプリケーションを構築およびオーケストレーションする方法を示しています。これには、次の実際の例が含まれています。  
+  文学ブログの特定の小説の分析を行う。この例では、プロンプトのシンプルでシーケンシャルなチェーンを示しています。
+  特定のトピックに関する短いストーリーを生成する。この例では、AI が以前に生成した項目のリストを繰り返し処理する方法を示しています。
+  特定の目的地への週末の旅程を作成する。この例では、複数の個別のプロンプトを並列化する方法を示しています。
+  映画のプロデューサーに映画のアイデアを提案する。この例では、異なる推論パラメータを使用して同じプロンプトを並列化する方法、チェーン内の前のステップにバックトラックする方法、ワークフローの一部として人間の入力を含める方法を示しています。
+  ユーザーの手元にある材料に基づいて料理を計画する。この例では、プロンプトチェーンが 2 つの異なる AI 会話を組み込んで、2 つの AI ペルソナが相互に議論を行い、最終的な結果を改善する方法を示しています。
+  当日中で最も人気のある GitHub リポジトリを検索して要約する。この例では、外部 API とやり取りする複数の AI エージェントをチェーンさせる方法を示しています。
 完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/aws-samples/amazon-bedrock-serverless-prompt-chaining) で完全なプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Bedrock
+ Amazon Bedrock ランタイム
+ Amazon Bedrock エージェント
+ Amazon Bedrock エージェントランタイム
+ ステップ関数

# AWS STS SDK for Python を使用した例 (Boto3)
<a name="python_3_sts_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_python_3_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)での設定と実行の方法を確認してください。
MFA トークンを必要とする IAM ロールを想定し、一時的な認証情報を使用してアカウントの Amazon S3 バケットを一覧表示します。  

```
def list_buckets_from_assumed_role_with_mfa(
    assume_role_arn, session_name, mfa_serial_number, mfa_totp, sts_client
):
    """
    Assumes a role from another account and uses the temporary credentials from
    that role to list the Amazon S3 buckets that are owned by the other account.
    Requires an MFA device serial number and token.

    The assumed role must grant permission to list the buckets in the other account.

    :param assume_role_arn: The Amazon Resource Name (ARN) of the role that
                            grants access to list the other account's buckets.
    :param session_name: The name of the STS session.
    :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
                              device, this is an ARN.
    :param mfa_totp: A time-based, one-time password issued by the MFA device.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    response = sts_client.assume_role(
        RoleArn=assume_role_arn,
        RoleSessionName=session_name,
        SerialNumber=mfa_serial_number,
        TokenCode=mfa_totp,
    )
    temp_credentials = response["Credentials"]
    print(f"Assumed role {assume_role_arn} and got temporary credentials.")

    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )

    print(f"Listing buckets for the assumed role's account:")
    for bucket in s3_resource.buckets.all():
        print(bucket.name)
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[AssumeRole](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/AssumeRole)」を参照してください。

### `GetSessionToken`
<a name="sts_GetSessionToken_python_3_topic"></a>

次のコード例は、`GetSessionToken` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)での設定と実行の方法を確認してください。
MFA トークンを渡してセッショントークンを取得し、それを使用してアカウントの Amazon S3 バケットを一覧表示します。  

```
def list_buckets_with_session_token_with_mfa(mfa_serial_number, mfa_totp, sts_client):
    """
    Gets a session token with MFA credentials and uses the temporary session
    credentials to list Amazon S3 buckets.

    Requires an MFA device serial number and token.

    :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
                              device, this is an Amazon Resource Name (ARN).
    :param mfa_totp: A time-based, one-time password issued by the MFA device.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    if mfa_serial_number is not None:
        response = sts_client.get_session_token(
            SerialNumber=mfa_serial_number, TokenCode=mfa_totp
        )
    else:
        response = sts_client.get_session_token()
    temp_credentials = response["Credentials"]

    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )

    print(f"Buckets for the account:")
    for bucket in s3_resource.buckets.all():
        print(bucket.name)
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetSessionToken](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/GetSessionToken)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### MFA トークンを必要とする IAM ロールを割り当てる
<a name="sts_Scenario_AssumeRoleMfa_python_3_topic"></a>

次のコード例は、MFA トークンを必要とするロールを引き受ける方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアの開発や実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ Amazon S3 バケットを一覧表示するためのアクセス許可を付与する、IAM ロールを作成します。
+ MFA 認証情報が指定された場合にのみロールを引き受けることが許可された、IAM ユーザーを作成します。
+ ユーザーのための MFA デバイスを登録します。
+ ロールを引き受け、Amazon S3 バケットを一覧表示するために一時的な認証情報を使用します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーを作成し、MFA デバイスを登録し、Amazon S3 バケットを一覧表示するアクセス許可を付与するためのロールを作成します。ユーザーには、ロールの引き受けのみ権限があります。  

```
def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates a new virtual MFA device.
    Displays the QR code to seed the device.
    Asks for two codes from the MFA device.
    Registers the MFA device for the user.
    Creates an access key pair for the user.
    Creates a role with a policy that lets the user assume the role and requires MFA.
    Creates a policy that allows listing Amazon S3 buckets.
    Attaches the policy to the role.
    Creates an inline policy for the user that lets the user assume the role.

    For demonstration purposes, the user is created in the same account as the role,
    but in practice the user would likely be from another account.

    Any MFA device that can scan a QR code will work with this demonstration.
    Common choices are mobile apps like LastPass Authenticator,
    Microsoft Authenticator, or Google Authenticator.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource
                         that has permissions to create users, roles, and policies
                         in the account.
    :return: The newly created user, user key, virtual MFA device, and role.
    """
    user = iam_resource.create_user(UserName=unique_name("user"))
    print(f"Created user {user.name}.")

    virtual_mfa_device = iam_resource.create_virtual_mfa_device(
        VirtualMFADeviceName=unique_name("mfa")
    )
    print(f"Created virtual MFA device {virtual_mfa_device.serial_number}")

    print(
        f"Showing the QR code for the device. Scan this in the MFA app of your "
        f"choice."
    )
    with open("qr.png", "wb") as qr_file:
        qr_file.write(virtual_mfa_device.qr_code_png)
    webbrowser.open(qr_file.name)

    print(f"Enter two consecutive code from your MFA device.")
    mfa_code_1 = input("Enter the first code: ")
    mfa_code_2 = input("Enter the second code: ")
    user.enable_mfa(
        SerialNumber=virtual_mfa_device.serial_number,
        AuthenticationCode1=mfa_code_1,
        AuthenticationCode2=mfa_code_2,
    )
    os.remove(qr_file.name)
    print(f"MFA device is registered with the user.")

    user_key = user.create_access_key_pair()
    print(f"Created access key pair for user.")

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    role = iam_resource.create_role(
        RoleName=unique_name("role"),
        AssumeRolePolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {"AWS": user.arn},
                        "Action": "sts:AssumeRole",
                        "Condition": {"Bool": {"aws:MultiFactorAuthPresent": True}},
                    }
                ],
            }
        ),
    )
    print(f"Created role {role.name} that requires MFA.")

    policy = iam_resource.create_policy(
        PolicyName=unique_name("policy"),
        PolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": "s3:ListAllMyBuckets",
                        "Resource": "arn:aws:s3:::*",
                    }
                ],
            }
        ),
    )
    role.attach_policy(PolicyArn=policy.arn)
    print(f"Created policy {policy.policy_name} and attached it to the role.")

    user.create_policy(
        PolicyName=unique_name("user-policy"),
        PolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": "sts:AssumeRole",
                        "Resource": role.arn,
                    }
                ],
            }
        ),
    )
    print(
        f"Created an inline policy for {user.name} that lets the user assume "
        f"the role."
    )

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, virtual_mfa_device, role
```
MFA トークンなしでロールを引き受けることは許可されていないことを示します。  

```
def try_to_assume_role_without_mfa(assume_role_arn, session_name, sts_client):
    """
    Shows that attempting to assume the role without sending MFA credentials results
    in an AccessDenied error.

    :param assume_role_arn: The Amazon Resource Name (ARN) of the role to assume.
    :param session_name: The name of the STS session.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    print(f"Trying to assume the role without sending MFA credentials...")
    try:
        sts_client.assume_role(RoleArn=assume_role_arn, RoleSessionName=session_name)
        raise RuntimeError("Expected AccessDenied error.")
    except ClientError as error:
        if error.response["Error"]["Code"] == "AccessDenied":
            print("Got AccessDenied.")
        else:
            raise
```
Amazon S3 バケットを一覧表示するためのアクセス許可を付与するロールを引き受け、必要な MFA トークンを渡して、バケットが一覧表示可能なことを出力します。  

```
def list_buckets_from_assumed_role_with_mfa(
    assume_role_arn, session_name, mfa_serial_number, mfa_totp, sts_client
):
    """
    Assumes a role from another account and uses the temporary credentials from
    that role to list the Amazon S3 buckets that are owned by the other account.
    Requires an MFA device serial number and token.

    The assumed role must grant permission to list the buckets in the other account.

    :param assume_role_arn: The Amazon Resource Name (ARN) of the role that
                            grants access to list the other account's buckets.
    :param session_name: The name of the STS session.
    :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
                              device, this is an ARN.
    :param mfa_totp: A time-based, one-time password issued by the MFA device.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    response = sts_client.assume_role(
        RoleArn=assume_role_arn,
        RoleSessionName=session_name,
        SerialNumber=mfa_serial_number,
        TokenCode=mfa_totp,
    )
    temp_credentials = response["Credentials"]
    print(f"Assumed role {assume_role_arn} and got temporary credentials.")

    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )

    print(f"Listing buckets for the assumed role's account:")
    for bucket in s3_resource.buckets.all():
        print(bucket.name)
```
デモ用に作成されたリソースを破棄します。  

```
def teardown(user, virtual_mfa_device, role):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo role.
    """
    for attached in role.attached_policies.all():
        policy_name = attached.policy_name
        role.detach_policy(PolicyArn=attached.arn)
        attached.delete()
        print(f"Detached and deleted {policy_name}.")
    role.delete()
    print(f"Deleted {role.name}.")
    for user_pol in user.policies.all():
        user_pol.delete()
        print("Deleted inline user policy.")
    for key in user.access_keys.all():
        key.delete()
        print("Deleted user's access key.")
    for mfa in user.mfa_devices.all():
        mfa.disassociate()
    virtual_mfa_device.delete()
    user.delete()
    print(f"Deleted {user.name}.")
```
このシナリオは、前に定義した関数を使用して実行します。  

```
def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(
        f"Welcome to the AWS Security Token Service assume role demo, "
        f"starring multi-factor authentication (MFA)!"
    )
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user, user_key, virtual_mfa_device, role = setup(iam_resource)
    print(f"Created {user.name} and {role.name}.")
    try:
        sts_client = boto3.client(
            "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
        )
        try_to_assume_role_without_mfa(role.arn, "demo-sts-session", sts_client)
        mfa_totp = input("Enter the code from your registered MFA device: ")
        list_buckets_from_assumed_role_with_mfa(
            role.arn,
            "demo-sts-session",
            virtual_mfa_device.serial_number,
            mfa_totp,
            sts_client,
        )
    finally:
        teardown(user, virtual_mfa_device, role)
        print("Thanks for watching!")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[AssumeRole](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/AssumeRole)」を参照してください。

### フェデレーションユーザー向け URL の作成
<a name="sts_Scenario_ConstructFederatedUrl_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 現在のアカウントの Amazon S3 リソースに対する読み取り専用のアクセス権限を付与する IAM ロールを作成します。
+  AWS フェデレーションエンドポイントからセキュリティトークンを取得します。
+ フェデレーションされた認証情報を使用して、コンソールにアクセスする際に使用する URL を作成します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)での設定と実行の方法を確認してください。
現在のアカウントの Amazon S3 リソースに対する読み取り専用アクセス権限を付与するロールを作成します。  

```
def setup(iam_resource):
    """
    Creates a role that can be assumed by the current user.
    Attaches a policy that allows only Amazon S3 read-only access.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) instance
                         that has the permission to create a role.
    :return: The newly created role.
    """
    role = iam_resource.create_role(
        RoleName=unique_name("role"),
        AssumeRolePolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Principal": {"AWS": iam_resource.CurrentUser().arn},
                        "Action": "sts:AssumeRole",
                    }
                ],
            }
        ),
    )
    role.attach_policy(PolicyArn="arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess")
    print(f"Created role {role.name}.")

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return role
```
 AWS フェデレーションエンドポイントからセキュリティトークンを取得し、フェデレーション認証情報を使用してコンソールにアクセスするために使用できる URL を作成します。  

```
def construct_federated_url(assume_role_arn, session_name, issuer, sts_client):
    """
    Constructs a URL that gives federated users direct access to the AWS Management
    Console.

    1. Acquires temporary credentials from AWS Security Token Service (AWS STS) that
       can be used to assume a role with limited permissions.
    2. Uses the temporary credentials to request a sign-in token from the
       AWS federation endpoint.
    3. Builds a URL that can be used in a browser to navigate to the AWS federation
       endpoint, includes the sign-in token for authentication, and redirects to
       the AWS Management Console with permissions defined by the role that was
       specified in step 1.

    :param assume_role_arn: The role that specifies the permissions that are granted.
                            The current user must have permission to assume the role.
    :param session_name: The name for the STS session.
    :param issuer: The organization that issues the URL.
    :param sts_client: A Boto3 STS instance that can assume the role.
    :return: The federated URL.
    """
    response = sts_client.assume_role(
        RoleArn=assume_role_arn, RoleSessionName=session_name
    )
    temp_credentials = response["Credentials"]
    print(f"Assumed role {assume_role_arn} and got temporary credentials.")

    session_data = {
        "sessionId": temp_credentials["AccessKeyId"],
        "sessionKey": temp_credentials["SecretAccessKey"],
        "sessionToken": temp_credentials["SessionToken"],
    }
    aws_federated_signin_endpoint = "https://signin.aws.amazon.com/federation"

    # Make a request to the AWS federation endpoint to get a sign-in token.
    # The requests.get function URL-encodes the parameters and builds the query string
    # before making the request.
    response = requests.get(
        aws_federated_signin_endpoint,
        params={
            "Action": "getSigninToken",
            "SessionDuration": str(datetime.timedelta(hours=12).seconds),
            "Session": json.dumps(session_data),
        },
    )
    signin_token = json.loads(response.text)
    print(f"Got a sign-in token from the AWS sign-in federation endpoint.")

    # Make a federated URL that can be used to sign into the AWS Management Console.
    query_string = urllib.parse.urlencode(
        {
            "Action": "login",
            "Issuer": issuer,
            "Destination": "https://console.aws.amazon.com/",
            "SigninToken": signin_token["SigninToken"],
        }
    )
    federated_url = f"{aws_federated_signin_endpoint}?{query_string}"
    return federated_url
```
デモ用に作成されたリソースを破棄します。  

```
def teardown(role):
    """
    Removes all resources created during setup.

    :param role: The demo role.
    """
    for attached in role.attached_policies.all():
        role.detach_policy(PolicyArn=attached.arn)
        print(f"Detached {attached.policy_name}.")
    role.delete()
    print(f"Deleted {role.name}.")
```
このシナリオは、前に定義した関数を使用して実行します。  

```
def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(f"Welcome to the AWS Security Token Service federated URL demo.")
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    role = setup(iam_resource)
    sts_client = boto3.client("sts")
    try:
        federated_url = construct_federated_url(
            role.arn, "AssumeRoleDemoSession", "example.org", sts_client
        )
        print(
            "Constructed a federated URL that can be used to connect to the "
            "AWS Management Console with role-defined permissions:"
        )
        print("-" * 88)
        print(federated_url)
        print("-" * 88)
        _ = input(
            "Copy and paste the above URL into a browser to open the AWS "
            "Management Console with limited permissions. When done, press "
            "Enter to clean up and complete this demo."
        )
    finally:
        teardown(role)
        print("Thanks for watching!")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[AssumeRole](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/AssumeRole)」を参照してください。

### MFA トークンを必要とするセッショントークンの取得
<a name="sts_Scenario_SessionTokenMfa_python_3_topic"></a>

次のコード例では、MFA トークンを必要とするセッショントークンを取得する方法を示します。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアの開発や実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ Amazon S3 バケットを一覧表示するためのアクセス許可を付与する、IAM ロールを作成します。
+ MFA 認証情報が指定された場合にのみロールを引き受けることが許可された、IAM ユーザーを作成します。
+ ユーザーのための MFA デバイスを登録します。
+ セッショントークンを取得するための MFA 認証情報を指定し、一時的な認証情報により S3 バケットを一覧表示します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sts#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーの作成と MFA デバイスの登録を行い、ユーザーが Amazon S3 バケットを一覧表示できるようにするアクセス許可を、MFA 認証情報が使用されている場合にのみ付与するロールを作成します。  

```
def setup(iam_resource):
    """
    Creates a new user with no permissions.
    Creates a new virtual multi-factor authentication (MFA) device.
    Displays the QR code to seed the device.
    Asks for two codes from the MFA device.
    Registers the MFA device for the user.
    Creates an access key pair for the user.
    Creates an inline policy for the user that lets the user list Amazon S3 buckets,
    but only when MFA credentials are used.

    Any MFA device that can scan a QR code will work with this demonstration.
    Common choices are mobile apps like LastPass Authenticator,
    Microsoft Authenticator, or Google Authenticator.

    :param iam_resource: A Boto3 AWS Identity and Access Management (IAM) resource
                         that has permissions to create users, MFA devices, and
                         policies in the account.
    :return: The newly created user, user key, and virtual MFA device.
    """
    user = iam_resource.create_user(UserName=unique_name("user"))
    print(f"Created user {user.name}.")

    virtual_mfa_device = iam_resource.create_virtual_mfa_device(
        VirtualMFADeviceName=unique_name("mfa")
    )
    print(f"Created virtual MFA device {virtual_mfa_device.serial_number}")

    print(
        f"Showing the QR code for the device. Scan this in the MFA app of your "
        f"choice."
    )
    with open("qr.png", "wb") as qr_file:
        qr_file.write(virtual_mfa_device.qr_code_png)
    webbrowser.open(qr_file.name)

    print(f"Enter two consecutive code from your MFA device.")
    mfa_code_1 = input("Enter the first code: ")
    mfa_code_2 = input("Enter the second code: ")
    user.enable_mfa(
        SerialNumber=virtual_mfa_device.serial_number,
        AuthenticationCode1=mfa_code_1,
        AuthenticationCode2=mfa_code_2,
    )
    os.remove(qr_file.name)
    print(f"MFA device is registered with the user.")

    user_key = user.create_access_key_pair()
    print(f"Created access key pair for user.")

    print(f"Wait for user to be ready.", end="")
    progress_bar(10)

    user.create_policy(
        PolicyName=unique_name("user-policy"),
        PolicyDocument=json.dumps(
            {
                "Version":"2012-10-17",		 	 	 
                "Statement": [
                    {
                        "Effect": "Allow",
                        "Action": "s3:ListAllMyBuckets",
                        "Resource": "arn:aws:s3:::*",
                        "Condition": {"Bool": {"aws:MultiFactorAuthPresent": True}},
                    }
                ],
            }
        ),
    )
    print(
        f"Created an inline policy for {user.name} that lets the user list buckets, "
        f"but only when MFA credentials are present."
    )

    print("Give AWS time to propagate these new resources and connections.", end="")
    progress_bar(10)

    return user, user_key, virtual_mfa_device
```
MFA トークンを渡して一時的なセッション認証情報を取得し、その認証情報を使用してアカウントの S3 バケットを一覧表示します。  

```
def list_buckets_with_session_token_with_mfa(mfa_serial_number, mfa_totp, sts_client):
    """
    Gets a session token with MFA credentials and uses the temporary session
    credentials to list Amazon S3 buckets.

    Requires an MFA device serial number and token.

    :param mfa_serial_number: The serial number of the MFA device. For a virtual MFA
                              device, this is an Amazon Resource Name (ARN).
    :param mfa_totp: A time-based, one-time password issued by the MFA device.
    :param sts_client: A Boto3 STS instance that has permission to assume the role.
    """
    if mfa_serial_number is not None:
        response = sts_client.get_session_token(
            SerialNumber=mfa_serial_number, TokenCode=mfa_totp
        )
    else:
        response = sts_client.get_session_token()
    temp_credentials = response["Credentials"]

    s3_resource = boto3.resource(
        "s3",
        aws_access_key_id=temp_credentials["AccessKeyId"],
        aws_secret_access_key=temp_credentials["SecretAccessKey"],
        aws_session_token=temp_credentials["SessionToken"],
    )

    print(f"Buckets for the account:")
    for bucket in s3_resource.buckets.all():
        print(bucket.name)
```
デモ用に作成されたリソースを破棄します。  

```
def teardown(user, virtual_mfa_device):
    """
    Removes all resources created during setup.

    :param user: The demo user.
    :param role: The demo MFA device.
    """
    for user_pol in user.policies.all():
        user_pol.delete()
        print("Deleted inline user policy.")
    for key in user.access_keys.all():
        key.delete()
        print("Deleted user's access key.")
    for mfa in user.mfa_devices.all():
        mfa.disassociate()
    virtual_mfa_device.delete()
    user.delete()
    print(f"Deleted {user.name}.")
```
このシナリオは、前に定義した関数を使用して実行します。  

```
def usage_demo():
    """Drives the demonstration."""
    print("-" * 88)
    print(
        f"Welcome to the AWS Security Token Service assume role demo, "
        f"starring multi-factor authentication (MFA)!"
    )
    print("-" * 88)
    iam_resource = boto3.resource("iam")
    user, user_key, virtual_mfa_device = setup(iam_resource)
    try:
        sts_client = boto3.client(
            "sts", aws_access_key_id=user_key.id, aws_secret_access_key=user_key.secret
        )
        try:
            print("Listing buckets without specifying MFA credentials.")
            list_buckets_with_session_token_with_mfa(None, None, sts_client)
        except ClientError as error:
            if error.response["Error"]["Code"] == "AccessDenied":
                print("Got expected AccessDenied error.")
        mfa_totp = input("Enter the code from your registered MFA device: ")
        list_buckets_with_session_token_with_mfa(
            virtual_mfa_device.serial_number, mfa_totp, sts_client
        )
    finally:
        teardown(user, virtual_mfa_device)
        print("Thanks for watching!")
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[GetSessionToken](https://docs.aws.amazon.com/goto/boto3/sts-2011-06-15/GetSessionToken)」を参照してください。

# サポート SDK for Python (Boto3) を使用した例
<a name="python_3_support_code_examples"></a>

次のコード例は、 AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています サポート。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち サポートは
<a name="support_Hello_python_3_topic"></a>

次のコード例は、 サポートの使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
import logging
import boto3
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


def hello_support(support_client):
    """
    Use the AWS SDK for Python (Boto3) to create an AWS Support client and count
    the available services in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param support_client: A Boto3 Support Client object.
    """
    try:
        print("Hello, AWS Support! Let's count the available Support services:")
        response = support_client.describe_services()
        print(f"There are {len(response['services'])} services available.")
    except ClientError as err:
        if err.response["Error"]["Code"] == "SubscriptionRequiredException":
            logger.info(
                "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                "examples."
            )
        else:
            logger.error(
                "Couldn't count services. Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


if __name__ == "__main__":
    hello_support(boto3.client("support"))
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeServices](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeServices)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="support_Scenario_GetStartedSupportCases_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ケースの利用可能なサービスと重要度レベルを取得して表示します。
+ 選択したサービス、カテゴリ、重要度レベルを使用してサポートケースを作成する方法
+ 当日のオープンケースのリストを取得して表示する方法
+ 新しいケースに添付セットとコミュニケーションを追加する方法
+ ケースの新しい添付ファイルとコミュニケーションについて説明する方法
+ ケースを解決する方法
+ 当日の解決済みケースのリストを取得して表示します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class SupportCasesScenario:
    """Runs an interactive scenario that shows how to get started using AWS Support."""

    def __init__(self, support_wrapper):
        """
        :param support_wrapper: An object that wraps AWS Support actions.
        """
        self.support_wrapper = support_wrapper

    def display_and_select_service(self):
        """
        Lists support services and prompts the user to select one.

        :return: The support service selected by the user.
        """
        print("-" * 88)
        services_list = self.support_wrapper.describe_services("en")
        print(f"AWS Support client returned {len(services_list)} services.")
        print("Displaying first 10 services:")

        service_choices = [svc["name"] for svc in services_list[:10]]
        selected_index = q.choose(
            "Select an example support service by entering a number from the preceding list:",
            service_choices,
        )
        selected_service = services_list[selected_index]
        print("-" * 88)
        return selected_service

    def display_and_select_category(self, service):
        """
        Lists categories for a support service and prompts the user to select one.

        :param service: The service of the categories.
        :return: The selected category.
        """
        print("-" * 88)
        print(
            f"Available support categories for Service {service['name']} {len(service['categories'])}:"
        )
        categories_choices = [category["name"] for category in service["categories"]]
        selected_index = q.choose(
            "Select an example support category by entering a number from the preceding list:",
            categories_choices,
        )
        selected_category = service["categories"][selected_index]
        print("-" * 88)
        return selected_category

    def display_and_select_severity(self):
        """
        Lists available severity levels and prompts the user to select one.

        :return: The selected severity level.
        """
        print("-" * 88)
        severity_levels_list = self.support_wrapper.describe_severity_levels("en")
        print(f"Available severity levels:")
        severity_choices = [level["name"] for level in severity_levels_list]
        selected_index = q.choose(
            "Select an example severity level by entering a number from the preceding list:",
            severity_choices,
        )
        selected_severity = severity_levels_list[selected_index]
        print("-" * 88)
        return selected_severity

    def create_example_case(self, service, category, severity_level):
        """
        Creates an example support case with the user's selections.

        :param service: The service for the new case.
        :param category: The category for the new case.
        :param severity_level: The severity level for the new case.
        :return: The caseId of the new support case.
        """
        print("-" * 88)
        print(f"Creating new case for service {service['name']}.")
        case_id = self.support_wrapper.create_case(service, category, severity_level)
        print(f"\tNew case created with ID {case_id}.")
        print("-" * 88)
        return case_id

    def list_open_cases(self):
        """
        List the open cases for the current day.
        """
        print("-" * 88)
        print("Let's list the open cases for the current day.")
        start_time = str(datetime.utcnow().date())
        end_time = str(datetime.utcnow().date() + timedelta(days=1))
        open_cases = self.support_wrapper.describe_cases(start_time, end_time, False)
        for case in open_cases:
            print(f"\tCase: {case['caseId']}: status {case['status']}.")
        print("-" * 88)

    def create_attachment_set(self):
        """
        Create an attachment set with a sample file.

        :return: The attachment set ID of the new attachment set.
        """
        print("-" * 88)
        print("Creating attachment set with a sample file.")
        attachment_set_id = self.support_wrapper.add_attachment_to_set()
        print(f"\tNew attachment set created with ID {attachment_set_id}.")
        print("-" * 88)
        return attachment_set_id

    def add_communication(self, case_id, attachment_set_id):
        """
        Add a communication with an attachment set to the case.

        :param case_id: The ID of the case for the communication.
        :param attachment_set_id: The ID of the attachment set to
        add to the communication.
        """
        print("-" * 88)
        print(f"Adding a communication and attachment set to the case.")
        self.support_wrapper.add_communication_to_case(attachment_set_id, case_id)
        print(
            f"Added a communication and attachment set {attachment_set_id} to the case {case_id}."
        )
        print("-" * 88)

    def list_communications(self, case_id):
        """
        List the communications associated with a case.

        :param case_id: The ID of the case.
        :return: The attachment ID of an attachment.
        """
        print("-" * 88)
        print("Let's list the communications for our case.")
        attachment_id = ""
        communications = self.support_wrapper.describe_all_case_communications(case_id)
        for communication in communications:
            print(
                f"\tCommunication created on {communication['timeCreated']} "
                f"has {len(communication['attachmentSet'])} attachments."
            )
            if len(communication["attachmentSet"]) > 0:
                attachment_id = communication["attachmentSet"][0]["attachmentId"]
        print("-" * 88)
        return attachment_id

    def describe_case_attachment(self, attachment_id):
        """
        Describe an attachment associated with a case.

        :param attachment_id: The ID of the attachment.
        """
        print("-" * 88)
        print("Let's list the communications for our case.")
        attached_file = self.support_wrapper.describe_attachment(attachment_id)
        print(f"\tAttachment includes file {attached_file}.")
        print("-" * 88)

    def resolve_case(self, case_id):
        """
        Shows how to resolve an AWS Support case by its ID.

        :param case_id: The ID of the case to resolve.
        """
        print("-" * 88)
        print(f"Resolving case with ID {case_id}.")
        case_status = self.support_wrapper.resolve_case(case_id)
        print(f"\tFinal case status is {case_status}.")
        print("-" * 88)

    def list_resolved_cases(self):
        """
        List the resolved cases for the current day.
        """
        print("-" * 88)
        print("Let's list the resolved cases for the current day.")
        start_time = str(datetime.utcnow().date())
        end_time = str(datetime.utcnow().date() + timedelta(days=1))
        resolved_cases = self.support_wrapper.describe_cases(start_time, end_time, True)
        for case in resolved_cases:
            print(f"\tCase: {case['caseId']}: status {case['status']}.")
        print("-" * 88)

    def run_scenario(self):
        logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

        print("-" * 88)
        print("Welcome to the AWS Support get started with support cases demo.")
        print("-" * 88)

        selected_service = self.display_and_select_service()
        selected_category = self.display_and_select_category(selected_service)
        selected_severity = self.display_and_select_severity()
        new_case_id = self.create_example_case(
            selected_service, selected_category, selected_severity
        )
        wait(10)
        self.list_open_cases()
        new_attachment_set_id = self.create_attachment_set()
        self.add_communication(new_case_id, new_attachment_set_id)
        new_attachment_id = self.list_communications(new_case_id)
        self.describe_case_attachment(new_attachment_id)
        self.resolve_case(new_case_id)
        wait(10)
        self.list_resolved_cases()

        print("\nThanks for watching!")
        print("-" * 88)


if __name__ == "__main__":
    try:
        scenario = SupportCasesScenario(SupportWrapper.from_client())
        scenario.run_scenario()
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
サポートされるクライアントアクションをラップするクラスを定義します。  

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def describe_services(self, language):
        """
        Get the descriptions of AWS services available for support for a language.

        :param language: The language for support services.
        Currently, only "en" (English) and "ja" (Japanese) are supported.
        :return: The list of AWS service descriptions.
        """
        try:
            response = self.support_client.describe_services(language=language)
            services = response["services"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't get Support services for language %s. Here's why: %s: %s",
                    language,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return services


    def describe_severity_levels(self, language):
        """
        Get the descriptions of available severity levels for support cases for a language.

        :param language: The language for support severity levels.
        Currently, only "en" (English) and "ja" (Japanese) are supported.
        :return: The list of severity levels.
        """
        try:
            response = self.support_client.describe_severity_levels(language=language)
            severity_levels = response["severityLevels"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't get severity levels for language %s. Here's why: %s: %s",
                    language,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return severity_levels


    def create_case(self, service, category, severity):
        """
        Create a new support case.

        :param service: The service to use for the new case.
        :param category: The category to use for the new case.
        :param severity: The severity to use for the new case.
        :return: The caseId of the new case.
        """
        try:
            response = self.support_client.create_case(
                subject="Example case for testing, ignore.",
                serviceCode=service["code"],
                severityCode=severity["code"],
                categoryCode=category["code"],
                communicationBody="Example support case body.",
                language="en",
                issueType="customer-service",
            )
            case_id = response["caseId"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't create case. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return case_id


    def add_attachment_to_set(self):
        """
        Add an attachment to a set, or create a new attachment set if one does not exist.

        :return: The attachment set ID.
        """
        try:
            response = self.support_client.add_attachments_to_set(
                attachments=[
                    {
                        "fileName": "attachment_file.txt",
                        "data": b"This is a sample file for attachment to a support case.",
                    }
                ]
            )
            new_set_id = response["attachmentSetId"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't add attachment. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return new_set_id


    def add_communication_to_case(self, attachment_set_id, case_id):
        """
        Add a communication and an attachment set to a case.

        :param attachment_set_id: The ID of an existing attachment set.
        :param case_id: The ID of the case.
        """
        try:
            self.support_client.add_communication_to_case(
                caseId=case_id,
                communicationBody="This is an example communication added to a support case.",
                attachmentSetId=attachment_set_id,
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't add communication. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise


    def describe_all_case_communications(self, case_id):
        """
        Describe all the communications for a case using a paginator.

        :param case_id: The ID of the case.
        :return: The communications for the case.
        """
        try:
            communications = []
            paginator = self.support_client.get_paginator("describe_communications")
            for page in paginator.paginate(caseId=case_id):
                communications += page["communications"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't describe communications. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return communications


    def describe_attachment(self, attachment_id):
        """
        Get information about an attachment by its attachmentID.

        :param attachment_id: The ID of the attachment.
        :return: The name of the attached file.
        """
        try:
            response = self.support_client.describe_attachment(
                attachmentId=attachment_id
            )
            attached_file = response["attachment"]["fileName"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't get attachment description. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return attached_file


    def resolve_case(self, case_id):
        """
        Resolve a support case by its caseId.

        :param case_id: The ID of the case to resolve.
        :return: The final status of the case.
        """
        try:
            response = self.support_client.resolve_case(caseId=case_id)
            final_status = response["finalCaseStatus"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't resolve case. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return final_status


    def describe_cases(self, after_time, before_time, resolved):
        """
        Describe support cases over a period of time, optionally filtering
        by status.

        :param after_time: The start time to include for cases.
        :param before_time: The end time to include for cases.
        :param resolved: True to include resolved cases in the results,
            otherwise results are open cases.
        :return: The final status of the case.
        """
        try:
            cases = []
            paginator = self.support_client.get_paginator("describe_cases")
            for page in paginator.paginate(
                afterTime=after_time,
                beforeTime=before_time,
                includeResolvedCases=resolved,
                language="en",
            ):
                cases += page["cases"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't describe cases. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            if resolved:
                cases = filter(lambda case: case["status"] == "resolved", cases)
            return cases
```
+ API の詳細については、「**AWS SDK for Python (Boto3) API リファレンス」の以下のトピックを参照してください。
  + [AddAttachmentsToSet](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/AddAttachmentsToSet)
  + [AddCommunicationToCase](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/AddCommunicationToCase)
  + [CreateCase](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/CreateCase)
  + [DescribeAttachment](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeAttachment)
  + [DescribeCases](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeCases)
  + [DescribeCommunications](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeCommunications)
  + [DescribeServices](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeServices)
  + [DescribeSeverityLevels](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeSeverityLevels)
  + [ResolveCase](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/ResolveCase)

## アクション
<a name="actions"></a>

### `AddAttachmentsToSet`
<a name="support_AddAttachmentsToSet_python_3_topic"></a>

次のコード例は、`AddAttachmentsToSet` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def add_attachment_to_set(self):
        """
        Add an attachment to a set, or create a new attachment set if one does not exist.

        :return: The attachment set ID.
        """
        try:
            response = self.support_client.add_attachments_to_set(
                attachments=[
                    {
                        "fileName": "attachment_file.txt",
                        "data": b"This is a sample file for attachment to a support case.",
                    }
                ]
            )
            new_set_id = response["attachmentSetId"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't add attachment. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return new_set_id
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[AddAttachmentsToSet](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/AddAttachmentsToSet)」を参照してください。

### `AddCommunicationToCase`
<a name="support_AddCommunicationToCase_python_3_topic"></a>

次のコード例は、`AddCommunicationToCase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def add_communication_to_case(self, attachment_set_id, case_id):
        """
        Add a communication and an attachment set to a case.

        :param attachment_set_id: The ID of an existing attachment set.
        :param case_id: The ID of the case.
        """
        try:
            self.support_client.add_communication_to_case(
                caseId=case_id,
                communicationBody="This is an example communication added to a support case.",
                attachmentSetId=attachment_set_id,
            )
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't add communication. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[AddCommunicationToCase](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/AddCommunicationToCase)」を参照してください。

### `CreateCase`
<a name="support_CreateCase_python_3_topic"></a>

次のコード例は、`CreateCase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def create_case(self, service, category, severity):
        """
        Create a new support case.

        :param service: The service to use for the new case.
        :param category: The category to use for the new case.
        :param severity: The severity to use for the new case.
        :return: The caseId of the new case.
        """
        try:
            response = self.support_client.create_case(
                subject="Example case for testing, ignore.",
                serviceCode=service["code"],
                severityCode=severity["code"],
                categoryCode=category["code"],
                communicationBody="Example support case body.",
                language="en",
                issueType="customer-service",
            )
            case_id = response["caseId"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't create case. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return case_id
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateCase](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/CreateCase)」を参照してください。

### `DescribeAttachment`
<a name="support_DescribeAttachment_python_3_topic"></a>

次のコード例は、`DescribeAttachment` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def describe_attachment(self, attachment_id):
        """
        Get information about an attachment by its attachmentID.

        :param attachment_id: The ID of the attachment.
        :return: The name of the attached file.
        """
        try:
            response = self.support_client.describe_attachment(
                attachmentId=attachment_id
            )
            attached_file = response["attachment"]["fileName"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't get attachment description. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return attached_file
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeAttachment](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeAttachment)」を参照してください。

### `DescribeCases`
<a name="support_DescribeCases_python_3_topic"></a>

次のコード例は、`DescribeCases` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def describe_cases(self, after_time, before_time, resolved):
        """
        Describe support cases over a period of time, optionally filtering
        by status.

        :param after_time: The start time to include for cases.
        :param before_time: The end time to include for cases.
        :param resolved: True to include resolved cases in the results,
            otherwise results are open cases.
        :return: The final status of the case.
        """
        try:
            cases = []
            paginator = self.support_client.get_paginator("describe_cases")
            for page in paginator.paginate(
                afterTime=after_time,
                beforeTime=before_time,
                includeResolvedCases=resolved,
                language="en",
            ):
                cases += page["cases"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't describe cases. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            if resolved:
                cases = filter(lambda case: case["status"] == "resolved", cases)
            return cases
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeCases](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeCases)」を参照してください。

### `DescribeCommunications`
<a name="support_DescribeCommunications_python_3_topic"></a>

次のコード例は、`DescribeCommunications` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def describe_all_case_communications(self, case_id):
        """
        Describe all the communications for a case using a paginator.

        :param case_id: The ID of the case.
        :return: The communications for the case.
        """
        try:
            communications = []
            paginator = self.support_client.get_paginator("describe_communications")
            for page in paginator.paginate(caseId=case_id):
                communications += page["communications"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't describe communications. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return communications
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeCommunications](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeCommunications)」を参照してください。

### `DescribeServices`
<a name="support_DescribeServices_python_3_topic"></a>

次のコード例は、`DescribeServices` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def describe_services(self, language):
        """
        Get the descriptions of AWS services available for support for a language.

        :param language: The language for support services.
        Currently, only "en" (English) and "ja" (Japanese) are supported.
        :return: The list of AWS service descriptions.
        """
        try:
            response = self.support_client.describe_services(language=language)
            services = response["services"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't get Support services for language %s. Here's why: %s: %s",
                    language,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return services
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeServices](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeServices)」を参照してください。

### `DescribeSeverityLevels`
<a name="support_DescribeSeverityLevels_python_3_topic"></a>

次のコード例は、`DescribeSeverityLevels` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def describe_severity_levels(self, language):
        """
        Get the descriptions of available severity levels for support cases for a language.

        :param language: The language for support severity levels.
        Currently, only "en" (English) and "ja" (Japanese) are supported.
        :return: The list of severity levels.
        """
        try:
            response = self.support_client.describe_severity_levels(language=language)
            severity_levels = response["severityLevels"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't get severity levels for language %s. Here's why: %s: %s",
                    language,
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return severity_levels
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeSeverityLevels](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/DescribeSeverityLevels)」を参照してください。

### `ResolveCase`
<a name="support_ResolveCase_python_3_topic"></a>

次のコード例は、`ResolveCase` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/support#code-examples)での設定と実行の方法を確認してください。

```
class SupportWrapper:
    """Encapsulates Support actions."""

    def __init__(self, support_client):
        """
        :param support_client: A Boto3 Support client.
        """
        self.support_client = support_client

    @classmethod
    def from_client(cls):
        """
        Instantiates this class from a Boto3 client.
        """
        support_client = boto3.client("support")
        return cls(support_client)


    def resolve_case(self, case_id):
        """
        Resolve a support case by its caseId.

        :param case_id: The ID of the case to resolve.
        :return: The final status of the case.
        """
        try:
            response = self.support_client.resolve_case(caseId=case_id)
            final_status = response["finalCaseStatus"]
        except ClientError as err:
            if err.response["Error"]["Code"] == "SubscriptionRequiredException":
                logger.info(
                    "You must have a Business, Enterprise On-Ramp, or Enterprise Support "
                    "plan to use the AWS Support API. \n\tPlease upgrade your subscription to run these "
                    "examples."
                )
            else:
                logger.error(
                    "Couldn't resolve case. Here's why: %s: %s",
                    err.response["Error"]["Code"],
                    err.response["Error"]["Message"],
                )
                raise
        else:
            return final_status
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[resolve\$1case](https://docs.aws.amazon.com/goto/boto3/support-2013-04-15/ResolveCase)」を参照してください。

# SDK for Python (Boto3) を使用した Systems Manager の例
<a name="python_3_ssm_code_examples"></a>

次のコード例は、Systems Manager AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにちは、Systems Manager
<a name="ssm_Hello_python_3_topic"></a>

次のコード例は、Systems Manager の使用を開始する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
import boto3
from botocore.exceptions import ClientError


def hello_systems_manager(ssm_client):
    """
    Use the AWS SDK for Python (Boto3) to create an AWS Systems Manager
    client and list the first 5 documents in your account.
    This example uses the default settings specified in your shared credentials
    and config files.

    :param ssm_client: A Boto3 AWS Systems Manager Client object. This object wraps
                             the low-level AWS Systems Manager service API.
    """
    print("Hello, AWS Systems Manager! Let's list some of your documents:\n")

    paginator = ssm_client.get_paginator("list_documents")
    page_iterator = paginator.paginate(PaginationConfig={"MaxItems": 5})
    for page in page_iterator:
        for document in page["DocumentIdentifiers"]:
            print(f"  {document['Name']}")


if __name__ == "__main__":
    try:
        hello_systems_manager(boto3.client("ssm"))
    except ClientError as err:
        print("Hello systems manager had an error.")
        print(err.response["Error"]["Code"])
        print(err.response["Error"]["Message"])
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListDocuments](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/ListDocuments)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ssm_Scenario_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ メンテナンスウィンドウを作成します。
+ メンテナンスウィンドウのスケジュールを変更します。
+ ドキュメントを作成します。
+ 指定された EC2 インスタンスにコマンドを送信します。
+ 新しい OpsItem を作成します。
+ OpsItem を更新して解決します。
+ メンテナンスウィンドウ、OpsItem、ドキュメントを削除します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。
コマンドプロンプトからインタラクティブなシナリオを実行します。  

```
class SystemsManagerScenario:
    """Runs an interactive scenario that shows how to get started using Amazon Systems Manager."""

    def __init__(self, document_wrapper, maintenance_window_wrapper, ops_item_wrapper):
        """
        :param document_wrapper: An object that wraps Systems Manager document functions.
        :param maintenance_window_wrapper: An object that wraps Systems Manager maintenance window functions.
        :param ops_item_wrapper: An object that wraps Systems Manager OpsItem functions.
        """
        self.document_wrapper = document_wrapper
        self.maintenance_window_wrapper = maintenance_window_wrapper
        self.ops_item_wrapper = ops_item_wrapper

    def run(self):
        """Demonstrates how to use the AWS SDK for Python (Boto3) to get started with Systems Manager."""
        try:
            print("-" * 88)
            print(
                """
Welcome to the AWS Systems Manager SDK Getting Started scenario.
This program demonstrates how to interact with Systems Manager using the AWS SDK for Python (Boto3).
Systems Manager is the operations hub for your AWS applications and resources and a secure end-to-end management 
solution. The program's primary functions include creating a maintenance window, creating a document, sending a 
command to a document, listing documents, listing commands, creating an OpsItem, modifying an OpsItem, and deleting 
Systems Manager resources. Upon completion of the program, all AWS resources are cleaned up.
Let's get started..."""
            )
            q.ask("Please hit Enter")

            print("-" * 88)
            print("Create a Systems Manager maintenance window.")
            maintenance_window_name = q.ask(
                "Please enter the maintenance window name (default is ssm-maintenance-window):",
            )
            if not maintenance_window_name:
                maintenance_window_name = "ssm-maintenance-window"

            self.maintenance_window_wrapper.create(
                name=maintenance_window_name,
                schedule="cron(0 10 ? * MON-FRI *)",
                duration=2,
                cutoff=1,
                allow_unassociated_targets=True,
            )

            print("-" * 88)
            print("Modify the maintenance window by changing the schedule")
            q.ask("Please hit Enter")

            self.maintenance_window_wrapper.update(
                name=maintenance_window_name,
                schedule="cron(0 0 ? * MON *)",
                duration=24,
                cutoff=1,
                allow_unassociated_targets=True,
                enabled=True,
            )

            print("-" * 88)
            print(
                "Create a document that defines the actions that Systems Manager performs on your EC2 instance."
            )
            document_name = q.ask(
                "Please enter the document name (default is ssmdocument):"
            )

            if not document_name:
                document_name = "ssmdocument"

            self.document_wrapper.create(
                name=document_name,
                content="""
{
    "schemaVersion": "2.2",
    "description": "Run a simple shell command",
    "mainSteps": [
        {
            "action": "aws:runShellScript",
            "name": "runEchoCommand",
            "inputs": {
              "runCommand": [
                "echo 'Hello, world!'"
              ]
            }
        }
    ]
}
            """,
            )

            self.document_wrapper.wait_until_active()

            print(
                """
Now you have the option of running a command on an EC2 instance that echoes 'Hello, world!'.
In order to run this command, you must provide the instance ID of a Linux EC2 instance. If you do
not already have a running Linux EC2 instance in your account, you can create one using the AWS console.
For information about creating an EC2 instance, see 
https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html.
            """
            )

            if q.ask(
                "Would you like to run a command on an EC2 instance? (y/n)",
                q.is_yesno,
            ):
                instance_id = q.ask(
                    "Please enter the instance ID of the EC2 instance:", q.non_empty
                )
                command_id = self.document_wrapper.send_command(
                    instance_ids=[instance_id]
                )

                self.document_wrapper.wait_command_executed(
                    command_id=command_id, instance_id=instance_id
                )

                print("-" * 88)
                print(
                    "Lets get the time when the specific command was sent to the specific managed node"
                )
                q.ask("Please hit Enter")

                self.document_wrapper.list_command_invocations(instance_id=instance_id)

            print("-" * 88)
            print("-" * 88)
            print(
                """
Now we will create a  Systems Manager OpsItem.
An OpsItem is a feature provided by the Systems Manager service.
It is a type of operational data item that allows you to manage and track various operational issues,
events, or tasks within your AWS environment.

You can create OpsItems to track and manage operational issues as they arise.
For example, you could create an OpsItem whenever your application detects a critical error
or an anomaly in your infrastructure.
            """
            )
            q.ask("Please hit Enter")

            self.ops_item_wrapper.create(
                title="Disk Space Alert",
                description="Created by the Systems Manager Python (Boto3) API",
                source="EC2",
                category="Performance",
                severity="2",
            )

            print("-" * 88)
            print("-" * 88)
            print(f"Now we will update  the OpsItem {self.ops_item_wrapper.id}")
            q.ask("Please hit Enter")

            self.ops_item_wrapper.update(
                title="Disk Space Alert",
                description=f"An update to {self.ops_item_wrapper.id}",
            )

            print(
                f"Now we will get the status of the OpsItem {self.ops_item_wrapper.id}"
            )
            q.ask("Please hit Enter")

            # It may take a second for the ops item to be available
            counter = 0
            while not self.ops_item_wrapper.describe() and counter < 5:
                counter += 1
                time.sleep(1)

            print(f"Now we will resolve the OpsItem {self.ops_item_wrapper.id}")
            q.ask("Please hit Enter")

            self.ops_item_wrapper.update(status="Resolved")

            print("-" * 88)
            print("-" * 88)
            if q.ask(
                "Would you like to delete the Systems Manager resources? (y/n)",
                q.is_yesno,
            ):
                print("You selected to delete the resources.")
                self.cleanup()
            else:
                print("The Systems Manager resources will not be deleted")

            print("-" * 88)
            print("This concludes the Systems Manager SDK Getting Started scenario.")
            print("-" * 88)

        except Exception:
            self.cleanup()
            raise

    def cleanup(self):
        self.maintenance_window_wrapper.delete()
        self.ops_item_wrapper.delete()
        self.document_wrapper.delete()


if __name__ == "__main__":
    try:
        scenario = SystemsManagerScenario(
            DocumentWrapper.from_client(),
            MaintenanceWindowWrapper.from_client(),
            OpsItemWrapper.from_client(),
        )
        scenario.run()
    except Exception:
        logging.exception("Something went wrong with the demo.")
```
ドキュメントとコマンドのアクションをラップするクラスを定義します。  

```
class DocumentWrapper:
    """Encapsulates AWS Systems Manager Document actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, content, name):
        """
        Creates a document.

        :param content: The content of the document.
        :param name: The name of the document.
        """
        try:
            self.ssm_client.create_document(
                Name=name, Content=content, DocumentType="Command"
            )
            self.name = name
        except self.ssm_client.exceptions.DocumentAlreadyExists:
            print(f"Document {name} already exists.")
            self.name = name
        except ClientError as err:
            logger.error(
                "Couldn't create %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete(self):
        """
        Deletes an AWS Systems Manager document.
        """
        if self.name is None:
            return

        try:
            self.ssm_client.delete_document(Name=self.name)
            print(f"Deleted document {self.name}.")
            self.name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def send_command(self, instance_ids):
        """
        Sends a command to one or more instances.

        :param instance_ids: The IDs of the instances to send the command to.
        :return: The ID of the command.
        """
        try:
            response = self.ssm_client.send_command(
                InstanceIds=instance_ids, DocumentName=self.name, TimeoutSeconds=3600
            )
            return response["Command"]["CommandId"]
        except ClientError as err:
            logger.error(
                "Couldn't send command to %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def describe(self):
        """
        Describes the document.

        :return: Document status.
        """
        try:
            response = self.ssm_client.describe_document(Name=self.name)
            return response["Document"]["Status"]
        except ClientError as err:
            logger.error(
                "Couldn't get %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def wait_until_active(self, max_attempts=20, delay=5):
        """
        Waits until the document is active.

        :param max_attempts: The maximum number of attempts for checking the status.
        :param delay: The delay in seconds between each check.
        """
        attempt = 0
        status = ""
        while attempt <= max_attempts:
            status = self.describe()
            if status == "Active":
                break
            attempt += 1
            time.sleep(delay)

        if status != "Active":
            logger.error("Document is not active.")
        else:
            logger.info("Document is active.")

    def wait_command_executed(self, command_id, instance_id):
        """
        Waits until the command is executed on the instance.

        :param command_id: The ID of the command.
        :param instance_id: The ID of the instance.
        """

        waiter = self.ssm_client.get_waiter("command_executed")
        waiter.wait(CommandId=command_id, InstanceId=instance_id)

    def list_command_invocations(self, instance_id):
        """
        Lists the commands for an instance.

        :param instance_id: The ID of the instance.
        :return: The list of commands.
        """
        try:
            paginator = self.ssm_client.get_paginator("list_command_invocations")
            command_invocations = []
            for page in paginator.paginate(InstanceId=instance_id):
                command_invocations.extend(page["CommandInvocations"])
            num_of_commands = len(command_invocations)
            print(
                f"{num_of_commands} command invocation(s) found for instance {instance_id}."
            )

            if num_of_commands > 10:
                print("Displaying the first 10 commands:")
                num_of_commands = 10
            date_format = "%A, %d %B %Y %I:%M%p"
            for command in command_invocations[:num_of_commands]:
                print(
                    f"   The time of command invocation is {command['RequestedDateTime'].strftime(date_format)}"
                )
        except ClientError as err:
            logger.error(
                "Couldn't list commands for %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
Ops 項目のアクションをラップするクラスを定義します。  

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, title, source, category, severity, description):
        """
        Create an OpsItem

        :param title: The OpsItem title.
        :param source: The OpsItem source.
        :param category: The OpsItem category.
        :param severity: The OpsItem severity.
        :param description: The OpsItem description.

        """
        try:
            response = self.ssm_client.create_ops_item(
                Title=title,
                Source=source,
                Category=category,
                Severity=severity,
                Description=description,
            )
            self.id = response["OpsItemId"]
        except self.ssm_client.exceptions.OpsItemLimitExceededException as err:
            logger.error(
                "Couldn't create ops item because you have exceeded your open OpsItem limit. "
                "Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create ops item %s. Here's why: %s: %s",
                title,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise

    def delete(self):
        """
        Delete the OpsItem.
        """
        if self.id is None:
            return
        try:
            self.ssm_client.delete_ops_item(OpsItemId=self.id)
            print(f"Deleted ops item with id {self.id}")
            self.id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def describe(self):
        """
        Describe an OpsItem.
        """
        try:
            paginator = self.ssm_client.get_paginator("describe_ops_items")
            ops_items = []
            for page in paginator.paginate(
                OpsItemFilters=[
                    {"Key": "OpsItemId", "Values": [self.id], "Operator": "Equal"}
                ]
            ):
                ops_items.extend(page["OpsItemSummaries"])

            for item in ops_items:
                print(
                    f"The item title is {item['Title']} and the status is {item['Status']}"
                )
            return len(ops_items) > 0
        except ClientError as err:
            logger.error(
                "Couldn't describe ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def update(self, title=None, description=None, status=None):
        """
        Update an OpsItem.

        :param title: The new OpsItem title.
        :param description: The new OpsItem description.
        :param status: The new OpsItem status.
        :return:
        """
        args = dict(OpsItemId=self.id)
        if title is not None:
            args["Title"] = title
        if description is not None:
            args["Description"] = description
        if status is not None:
            args["Status"] = status
        try:
            self.ssm_client.update_ops_item(**args)
        except ClientError as err:
            logger.error(
                "Couldn't update ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
メンテナンスウィンドウのアクションをラップするクラスを定義します。  

```
class MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, name, schedule, duration, cutoff, allow_unassociated_targets):
        """
        Create an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            response = self.ssm_client.create_maintenance_window(
                Name=name,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.window_id = response["WindowId"]
            self.name = name
            logger.info("Created maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to create maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create maintenance window %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def delete(self):
        """
        Delete the associated AWS Systems Manager maintenance window.
        """
        if self.window_id is None:
            return

        try:
            self.ssm_client.delete_maintenance_window(WindowId=self.window_id)
            logger.info("Deleted maintenance window %s.", self.window_id)
            print(f"Deleted maintenance window {self.name}")
            self.window_id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete maintenance window %s. Here's why: %s: %s",
                self.window_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise


    def update(
        self, name, enabled, schedule, duration, cutoff, allow_unassociated_targets
    ):
        """
        Update an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param enabled: Whether the maintenance window is enabled to run on managed nodes.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            self.ssm_client.update_maintenance_window(
                WindowId=self.window_id,
                Name=name,
                Enabled=enabled,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.name = name
            logger.info("Updated maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to update maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't update maintenance window %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+ API の詳細については、『*AWS SDK for Python (Boto3) API リファレンス*』の以下のトピックを参照してください。
  + [CreateDocument](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateDocument)
  + [CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateMaintenanceWindow)
  + [CreateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateOpsItem)
  + [DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteMaintenanceWindow)
  + [ListCommandInvocations](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/ListCommandInvocations)
  + [SendCommand](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/SendCommand)
  + [UpdateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/UpdateOpsItem)

## アクション
<a name="actions"></a>

### `CreateDocument`
<a name="ssm_CreateDocument_python_3_topic"></a>

次のコード例は、`CreateDocument` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class DocumentWrapper:
    """Encapsulates AWS Systems Manager Document actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, content, name):
        """
        Creates a document.

        :param content: The content of the document.
        :param name: The name of the document.
        """
        try:
            self.ssm_client.create_document(
                Name=name, Content=content, DocumentType="Command"
            )
            self.name = name
        except self.ssm_client.exceptions.DocumentAlreadyExists:
            print(f"Document {name} already exists.")
            self.name = name
        except ClientError as err:
            logger.error(
                "Couldn't create %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateDocument](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateDocument)」を参照してください。

### `CreateMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_python_3_topic"></a>

次のコード例は、`CreateMaintenanceWindow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, name, schedule, duration, cutoff, allow_unassociated_targets):
        """
        Create an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            response = self.ssm_client.create_maintenance_window(
                Name=name,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.window_id = response["WindowId"]
            self.name = name
            logger.info("Created maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to create maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create maintenance window %s. Here's why: %s: %s",
                name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateMaintenanceWindow)」を参照してください。

### `CreateOpsItem`
<a name="ssm_CreateOpsItem_python_3_topic"></a>

次のコード例は、`CreateOpsItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def create(self, title, source, category, severity, description):
        """
        Create an OpsItem

        :param title: The OpsItem title.
        :param source: The OpsItem source.
        :param category: The OpsItem category.
        :param severity: The OpsItem severity.
        :param description: The OpsItem description.

        """
        try:
            response = self.ssm_client.create_ops_item(
                Title=title,
                Source=source,
                Category=category,
                Severity=severity,
                Description=description,
            )
            self.id = response["OpsItemId"]
        except self.ssm_client.exceptions.OpsItemLimitExceededException as err:
            logger.error(
                "Couldn't create ops item because you have exceeded your open OpsItem limit. "
                "Here's why: %s: %s",
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't create ops item %s. Here's why: %s: %s",
                title,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[CreateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/CreateOpsItem)」を参照してください。

### `DeleteDocument`
<a name="ssm_DeleteDocument_python_3_topic"></a>

次のコード例は、`DeleteDocument` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class DocumentWrapper:
    """Encapsulates AWS Systems Manager Document actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def delete(self):
        """
        Deletes an AWS Systems Manager document.
        """
        if self.name is None:
            return

        try:
            self.ssm_client.delete_document(Name=self.name)
            print(f"Deleted document {self.name}.")
            self.name = None
        except ClientError as err:
            logger.error(
                "Couldn't delete %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteDocument](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteDocument)」を参照してください。

### `DeleteMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_python_3_topic"></a>

次のコード例は、`DeleteMaintenanceWindow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def delete(self):
        """
        Delete the associated AWS Systems Manager maintenance window.
        """
        if self.window_id is None:
            return

        try:
            self.ssm_client.delete_maintenance_window(WindowId=self.window_id)
            logger.info("Deleted maintenance window %s.", self.window_id)
            print(f"Deleted maintenance window {self.name}")
            self.window_id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete maintenance window %s. Here's why: %s: %s",
                self.window_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteMaintenanceWindow)」を参照してください。

### `DeleteOpsItem`
<a name="ssm_DeleteOpsItem_python_3_topic"></a>

次のコード例は、`DeleteOpsItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def delete(self):
        """
        Delete the OpsItem.
        """
        if self.id is None:
            return
        try:
            self.ssm_client.delete_ops_item(OpsItemId=self.id)
            print(f"Deleted ops item with id {self.id}")
            self.id = None
        except ClientError as err:
            logger.error(
                "Couldn't delete ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「AWS SDK for Python (Boto3) API リファレンス」の「[DeleteOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DeleteOpsItem)」を参照してください。

### `DescribeOpsItems`
<a name="ssm_DescribeOpsItems_python_3_topic"></a>

次のコード例は、`DescribeOpsItems` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def describe(self):
        """
        Describe an OpsItem.
        """
        try:
            paginator = self.ssm_client.get_paginator("describe_ops_items")
            ops_items = []
            for page in paginator.paginate(
                OpsItemFilters=[
                    {"Key": "OpsItemId", "Values": [self.id], "Operator": "Equal"}
                ]
            ):
                ops_items.extend(page["OpsItemSummaries"])

            for item in ops_items:
                print(
                    f"The item title is {item['Title']} and the status is {item['Status']}"
                )
            return len(ops_items) > 0
        except ClientError as err:
            logger.error(
                "Couldn't describe ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DescribeOpsItems](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/DescribeOpsItems)」を参照してください。

### `ListCommandInvocations`
<a name="ssm_ListCommandInvocations_python_3_topic"></a>

次のコード例は、`ListCommandInvocations` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class DocumentWrapper:
    """Encapsulates AWS Systems Manager Document actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def list_command_invocations(self, instance_id):
        """
        Lists the commands for an instance.

        :param instance_id: The ID of the instance.
        :return: The list of commands.
        """
        try:
            paginator = self.ssm_client.get_paginator("list_command_invocations")
            command_invocations = []
            for page in paginator.paginate(InstanceId=instance_id):
                command_invocations.extend(page["CommandInvocations"])
            num_of_commands = len(command_invocations)
            print(
                f"{num_of_commands} command invocation(s) found for instance {instance_id}."
            )

            if num_of_commands > 10:
                print("Displaying the first 10 commands:")
                num_of_commands = 10
            date_format = "%A, %d %B %Y %I:%M%p"
            for command in command_invocations[:num_of_commands]:
                print(
                    f"   The time of command invocation is {command['RequestedDateTime'].strftime(date_format)}"
                )
        except ClientError as err:
            logger.error(
                "Couldn't list commands for %s. Here's why: %s: %s",
                instance_id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListCommandInvocations](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/ListCommandInvocations)」を参照してください。

### `SendCommand`
<a name="ssm_SendCommand_python_3_topic"></a>

次のコード例は、`SendCommand` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class DocumentWrapper:
    """Encapsulates AWS Systems Manager Document actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def send_command(self, instance_ids):
        """
        Sends a command to one or more instances.

        :param instance_ids: The IDs of the instances to send the command to.
        :return: The ID of the command.
        """
        try:
            response = self.ssm_client.send_command(
                InstanceIds=instance_ids, DocumentName=self.name, TimeoutSeconds=3600
            )
            return response["Command"]["CommandId"]
        except ClientError as err:
            logger.error(
                "Couldn't send command to %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[SendCommand](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/SendCommand)」を参照してください。

### `UpdateMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_python_3_topic"></a>

次のコード例は、`UpdateMaintenanceWindow` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class MaintenanceWindowWrapper:
    """Encapsulates AWS Systems Manager maintenance window actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.window_id = None
        self.name = None

    @classmethod
    def from_client(cls):
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def update(
        self, name, enabled, schedule, duration, cutoff, allow_unassociated_targets
    ):
        """
        Update an AWS Systems Manager maintenance window.

        :param name: The name of the maintenance window.
        :param enabled: Whether the maintenance window is enabled to run on managed nodes.
        :param schedule: The schedule of the maintenance window.
        :param duration: The duration of the maintenance window.
        :param cutoff: The cutoff time of the maintenance window.
        :param allow_unassociated_targets: Allow the maintenance window to run on managed nodes, even
                                           if you haven't registered those nodes as targets.
        """
        try:
            self.ssm_client.update_maintenance_window(
                WindowId=self.window_id,
                Name=name,
                Enabled=enabled,
                Schedule=schedule,
                Duration=duration,
                Cutoff=cutoff,
                AllowUnassociatedTargets=allow_unassociated_targets,
            )
            self.name = name
            logger.info("Updated maintenance window %s.", self.window_id)
        except ParamValidationError as error:
            logger.error(
                "Parameter validation error when trying to update maintenance window %s. Here's why: %s",
                self.window_id,
                error,
            )
            raise
        except ClientError as err:
            logger.error(
                "Couldn't update maintenance window %s. Here's why: %s: %s",
                self.name,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[UpdateMaintenanceWindow](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/UpdateMaintenanceWindow)」を参照してください。

### `UpdateOpsItem`
<a name="ssm_UpdateOpsItem_python_3_topic"></a>

次のコード例は、`UpdateOpsItem` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/ssm#code-examples)での設定と実行の方法を確認してください。

```
class OpsItemWrapper:
    """Encapsulates AWS Systems Manager OpsItem actions."""

    def __init__(self, ssm_client):
        """
        :param ssm_client: A Boto3 Systems Manager client.
        """
        self.ssm_client = ssm_client
        self.id = None

    @classmethod
    def from_client(cls):
        """
        :return: A OpsItemWrapper instance.
        """
        ssm_client = boto3.client("ssm")
        return cls(ssm_client)


    def update(self, title=None, description=None, status=None):
        """
        Update an OpsItem.

        :param title: The new OpsItem title.
        :param description: The new OpsItem description.
        :param status: The new OpsItem status.
        :return:
        """
        args = dict(OpsItemId=self.id)
        if title is not None:
            args["Title"] = title
        if description is not None:
            args["Description"] = description
        if status is not None:
            args["Status"] = status
        try:
            self.ssm_client.update_ops_item(**args)
        except ClientError as err:
            logger.error(
                "Couldn't update ops item %s. Here's why: %s: %s",
                self.id,
                err.response["Error"]["Code"],
                err.response["Error"]["Message"],
            )
            raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[UpdateOpsItem](https://docs.aws.amazon.com/goto/boto3/ssm-2014-11-06/UpdateOpsItem)」を参照してください。

# SDK for Python (Boto3) を使用する Amazon Textract の例
<a name="python_3_textract_code_examples"></a>

次のコード例は、Amazon Textract AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AnalyzeDocument`
<a name="textract_AnalyzeDocument_python_3_topic"></a>

次のコード例は、`AnalyzeDocument` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/textract#code-examples)での設定と実行の方法を確認してください。

```
class TextractWrapper:
    """Encapsulates Textract functions."""

    def __init__(self, textract_client, s3_resource, sqs_resource):
        """
        :param textract_client: A Boto3 Textract client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        :param sqs_resource: A Boto3 Amazon SQS resource.
        """
        self.textract_client = textract_client
        self.s3_resource = s3_resource
        self.sqs_resource = sqs_resource


    def analyze_file(
        self, feature_types, *, document_file_name=None, document_bytes=None
    ):
        """
        Detects text and additional elements, such as forms or tables, in a local image
        file or from in-memory byte data.
        The image must be in PNG or JPG format.

        :param feature_types: The types of additional document features to detect.
        :param document_file_name: The name of a document image file.
        :param document_bytes: In-memory byte data of a document image.
        :return: The response from Amazon Textract, including a list of blocks
                 that describe elements detected in the image.
        """
        if document_file_name is not None:
            with open(document_file_name, "rb") as document_file:
                document_bytes = document_file.read()
        try:
            response = self.textract_client.analyze_document(
                Document={"Bytes": document_bytes}, FeatureTypes=feature_types
            )
            logger.info("Detected %s blocks.", len(response["Blocks"]))
        except ClientError:
            logger.exception("Couldn't detect text.")
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[AnalyzeDocument](https://docs.aws.amazon.com/goto/boto3/textract-2018-06-27/AnalyzeDocument)」を参照してください。

### `DetectDocumentText`
<a name="textract_DetectDocumentText_python_3_topic"></a>

次のコード例は、`DetectDocumentText` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/textract#code-examples)での設定と実行の方法を確認してください。

```
class TextractWrapper:
    """Encapsulates Textract functions."""

    def __init__(self, textract_client, s3_resource, sqs_resource):
        """
        :param textract_client: A Boto3 Textract client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        :param sqs_resource: A Boto3 Amazon SQS resource.
        """
        self.textract_client = textract_client
        self.s3_resource = s3_resource
        self.sqs_resource = sqs_resource


    def detect_file_text(self, *, document_file_name=None, document_bytes=None):
        """
        Detects text elements in a local image file or from in-memory byte data.
        The image must be in PNG or JPG format.

        :param document_file_name: The name of a document image file.
        :param document_bytes: In-memory byte data of a document image.
        :return: The response from Amazon Textract, including a list of blocks
                 that describe elements detected in the image.
        """
        if document_file_name is not None:
            with open(document_file_name, "rb") as document_file:
                document_bytes = document_file.read()
        try:
            response = self.textract_client.detect_document_text(
                Document={"Bytes": document_bytes}
            )
            logger.info("Detected %s blocks.", len(response["Blocks"]))
        except ClientError:
            logger.exception("Couldn't detect text.")
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DetectDocumentText](https://docs.aws.amazon.com/goto/boto3/textract-2018-06-27/DetectDocumentText)」を参照してください。

### `GetDocumentAnalysis`
<a name="textract_GetDocumentAnalysis_python_3_topic"></a>

次のコード例は、`GetDocumentAnalysis` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/textract#code-examples)での設定と実行の方法を確認してください。

```
class TextractWrapper:
    """Encapsulates Textract functions."""

    def __init__(self, textract_client, s3_resource, sqs_resource):
        """
        :param textract_client: A Boto3 Textract client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        :param sqs_resource: A Boto3 Amazon SQS resource.
        """
        self.textract_client = textract_client
        self.s3_resource = s3_resource
        self.sqs_resource = sqs_resource


    def get_analysis_job(self, job_id):
        """
        Gets data for a previously started detection job that includes additional
        elements.

        :param job_id: The ID of the job to retrieve.
        :return: The job data, including a list of blocks that describe elements
                 detected in the image.
        """
        try:
            response = self.textract_client.get_document_analysis(JobId=job_id)
            job_status = response["JobStatus"]
            logger.info("Job %s status is %s.", job_id, job_status)
        except ClientError:
            logger.exception("Couldn't get data for job %s.", job_id)
            raise
        else:
            return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[GetDocumentAnalysis](https://docs.aws.amazon.com/goto/boto3/textract-2018-06-27/GetDocumentAnalysis)」を参照してください。

### `StartDocumentAnalysis`
<a name="textract_StartDocumentAnalysis_python_3_topic"></a>

次のコード例は、`StartDocumentAnalysis` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/textract#code-examples)での設定と実行の方法を確認してください。
非同期ジョブを開始してドキュメントを分析します。  

```
class TextractWrapper:
    """Encapsulates Textract functions."""

    def __init__(self, textract_client, s3_resource, sqs_resource):
        """
        :param textract_client: A Boto3 Textract client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        :param sqs_resource: A Boto3 Amazon SQS resource.
        """
        self.textract_client = textract_client
        self.s3_resource = s3_resource
        self.sqs_resource = sqs_resource


    def start_analysis_job(
        self,
        bucket_name,
        document_file_name,
        feature_types,
        sns_topic_arn,
        sns_role_arn,
    ):
        """
        Starts an asynchronous job to detect text and additional elements, such as
        forms or tables, in an image stored in an Amazon S3 bucket. Textract publishes
        a notification to the specified Amazon SNS topic when the job completes.
        The image must be in PNG, JPG, or PDF format.

        :param bucket_name: The name of the Amazon S3 bucket that contains the image.
        :param document_file_name: The name of the document image stored in Amazon S3.
        :param feature_types: The types of additional document features to detect.
        :param sns_topic_arn: The Amazon Resource Name (ARN) of an Amazon SNS topic
                              where job completion notification is published.
        :param sns_role_arn: The ARN of an AWS Identity and Access Management (IAM)
                             role that can be assumed by Textract and grants permission
                             to publish to the Amazon SNS topic.
        :return: The ID of the job.
        """
        try:
            response = self.textract_client.start_document_analysis(
                DocumentLocation={
                    "S3Object": {"Bucket": bucket_name, "Name": document_file_name}
                },
                NotificationChannel={
                    "SNSTopicArn": sns_topic_arn,
                    "RoleArn": sns_role_arn,
                },
                FeatureTypes=feature_types,
            )
            job_id = response["JobId"]
            logger.info(
                "Started text analysis job %s on %s.", job_id, document_file_name
            )
        except ClientError:
            logger.exception("Couldn't analyze text in %s.", document_file_name)
            raise
        else:
            return job_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartDocumentAnalysis](https://docs.aws.amazon.com/goto/boto3/textract-2018-06-27/StartDocumentAnalysis)」を参照してください。

### `StartDocumentTextDetection`
<a name="textract_StartDocumentTextDetection_python_3_topic"></a>

次のコード例は、`StartDocumentTextDetection` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/textract#code-examples)での設定と実行の方法を確認してください。
ドキュメント内のテキストを検出する非同期ジョブを開始します。  

```
class TextractWrapper:
    """Encapsulates Textract functions."""

    def __init__(self, textract_client, s3_resource, sqs_resource):
        """
        :param textract_client: A Boto3 Textract client.
        :param s3_resource: A Boto3 Amazon S3 resource.
        :param sqs_resource: A Boto3 Amazon SQS resource.
        """
        self.textract_client = textract_client
        self.s3_resource = s3_resource
        self.sqs_resource = sqs_resource


    def start_detection_job(
        self, bucket_name, document_file_name, sns_topic_arn, sns_role_arn
    ):
        """
        Starts an asynchronous job to detect text elements in an image stored in an
        Amazon S3 bucket. Textract publishes a notification to the specified Amazon SNS
        topic when the job completes.
        The image must be in PNG, JPG, or PDF format.

        :param bucket_name: The name of the Amazon S3 bucket that contains the image.
        :param document_file_name: The name of the document image stored in Amazon S3.
        :param sns_topic_arn: The Amazon Resource Name (ARN) of an Amazon SNS topic
                              where the job completion notification is published.
        :param sns_role_arn: The ARN of an AWS Identity and Access Management (IAM)
                             role that can be assumed by Textract and grants permission
                             to publish to the Amazon SNS topic.
        :return: The ID of the job.
        """
        try:
            response = self.textract_client.start_document_text_detection(
                DocumentLocation={
                    "S3Object": {"Bucket": bucket_name, "Name": document_file_name}
                },
                NotificationChannel={
                    "SNSTopicArn": sns_topic_arn,
                    "RoleArn": sns_role_arn,
                },
            )
            job_id = response["JobId"]
            logger.info(
                "Started text detection job %s on %s.", job_id, document_file_name
            )
        except ClientError:
            logger.exception("Couldn't detect text in %s.", document_file_name)
            raise
        else:
            return job_id
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[StartDocumentTextDetection](https://docs.aws.amazon.com/goto/boto3/textract-2018-06-27/StartDocumentTextDetection)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### Amazon Textract エクスプローラーアプリケーションを作成する
<a name="cross_TextractExplorer_python_3_topic"></a>

次のコード例は、インタラクティブアプリケーションで Amazon Textract の出力を調べる方法を示しています。

**SDK for Python (Boto3)**  
 Amazon Textract AWS SDK for Python (Boto3) で を使用して、ドキュメントイメージ内のテキスト、フォーム、テーブル要素を検出する方法を示します。入力イメージと Amazon Textract 出力は、検出された要素を探索できる Tkinter アプリケーションに表示されます。  
+ Amazon Textract にドキュメントイメージを送信し、検出された要素の出力を調べます。
+ Amazon Textract に直接イメージを送信するか、Amazon Simple Storage Service (Amazon S3) バケットを通じてイメージを送信します。
+ 非同期 API を使用して、ジョブの完了時に Amazon Simple Notification Service (Amazon SNS) トピックに通知を発行するジョブを開始します。
+ Amazon Simple Queue Service (Amazon SQS) キューにジョブ完了メッセージについてポーリングし、結果を表示します。
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_explorer) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Cognito ID
+ Amazon S3
+ Amazon SNS
+ Amazon SQS
+ Amazon Textract

### 画像から抽出されたテキスト内のエンティティを検出する
<a name="cross_TextractComprehendDetectEntities_python_3_topic"></a>

次のコード例は、Amazon Comprehend を使用して、Amazon S3 に格納されている画像から Amazon Textract によって抽出されたテキスト内のエンティティを検出する方法を示しています。

**SDK for Python (Boto3)**  
 Jupyter ノートブック AWS SDK for Python (Boto3) で を使用して、イメージから抽出されたテキスト内のエンティティを検出する方法を示します。この例では、Amazon Textract を使用して Amazon Simple Storage Service (Amazon S3) に保存されている画像からテキストを抽出し、Amazon Comprehend を使用して、抽出されたテキスト内のエンティティを検出します。  
 この例は Jupyter Notebook であり、ノートブックをホストできる環境で実行する必要があります。Amazon SageMaker AI を使用してサンプルを実行する方法については、「[TextractAndComprehendNotebook.ipynb](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_comprehend_notebook/TextractAndComprehendNotebook.ipynb)」の手順を参照してください。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/textract_comprehend_notebook#readme) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Amazon S3
+ Amazon Textract

# SDK for Python (Boto3) を使用する Amazon Transcribe の例
<a name="python_3_transcribe_code_examples"></a>

次のコード例は、Amazon Transcribe AWS SDK for Python (Boto3) で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateVocabulary`
<a name="transcribe_CreateVocabulary_python_3_topic"></a>

次のコード例は、`CreateVocabulary` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def create_vocabulary(
    vocabulary_name, language_code, transcribe_client, phrases=None, table_uri=None
):
    """
    Creates a custom vocabulary that can be used to improve the accuracy of
    transcription jobs. This function returns as soon as the vocabulary processing
    is started. Call get_vocabulary to get the current status of the vocabulary.
    The vocabulary is ready to use when its status is 'READY'.

    :param vocabulary_name: The name of the custom vocabulary.
    :param language_code: The language code of the vocabulary.
                          For example, en-US or nl-NL.
    :param transcribe_client: The Boto3 Transcribe client.
    :param phrases: A list of comma-separated phrases to include in the vocabulary.
    :param table_uri: A table of phrases and pronunciation hints to include in the
                      vocabulary.
    :return: Information about the newly created vocabulary.
    """
    try:
        vocab_args = {"VocabularyName": vocabulary_name, "LanguageCode": language_code}
        if phrases is not None:
            vocab_args["Phrases"] = phrases
        elif table_uri is not None:
            vocab_args["VocabularyFileUri"] = table_uri
        response = transcribe_client.create_vocabulary(**vocab_args)
        logger.info("Created custom vocabulary %s.", response["VocabularyName"])
    except ClientError:
        logger.exception("Couldn't create custom vocabulary %s.", vocabulary_name)
        raise
    else:
        return response
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[CreateVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/CreateVocabulary)」を参照してください。

### `DeleteTranscriptionJob`
<a name="transcribe_DeleteTranscriptionJob_python_3_topic"></a>

次のコード例は、`DeleteTranscriptionJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def delete_job(job_name, transcribe_client):
    """
    Deletes a transcription job. This also deletes the transcript associated with
    the job.

    :param job_name: The name of the job to delete.
    :param transcribe_client: The Boto3 Transcribe client.
    """
    try:
        transcribe_client.delete_transcription_job(TranscriptionJobName=job_name)
        logger.info("Deleted job %s.", job_name)
    except ClientError:
        logger.exception("Couldn't delete job %s.", job_name)
        raise
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[DeleteTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/DeleteTranscriptionJob)」を参照してください。

### `DeleteVocabulary`
<a name="transcribe_DeleteVocabulary_python_3_topic"></a>

次のコード例は、`DeleteVocabulary` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def delete_vocabulary(vocabulary_name, transcribe_client):
    """
    Deletes a custom vocabulary.

    :param vocabulary_name: The name of the vocabulary to delete.
    :param transcribe_client: The Boto3 Transcribe client.
    """
    try:
        transcribe_client.delete_vocabulary(VocabularyName=vocabulary_name)
        logger.info("Deleted vocabulary %s.", vocabulary_name)
    except ClientError:
        logger.exception("Couldn't delete vocabulary %s.", vocabulary_name)
        raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[DeleteVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/DeleteVocabulary)」を参照してください。

### `GetTranscriptionJob`
<a name="transcribe_GetTranscriptionJob_python_3_topic"></a>

次のコード例は、`GetTranscriptionJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def get_job(job_name, transcribe_client):
    """
    Gets details about a transcription job.

    :param job_name: The name of the job to retrieve.
    :param transcribe_client: The Boto3 Transcribe client.
    :return: The retrieved transcription job.
    """
    try:
        response = transcribe_client.get_transcription_job(
            TranscriptionJobName=job_name
        )
        job = response["TranscriptionJob"]
        logger.info("Got job %s.", job["TranscriptionJobName"])
    except ClientError:
        logger.exception("Couldn't get job %s.", job_name)
        raise
    else:
        return job
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/GetTranscriptionJob)」を参照してください。

### `GetVocabulary`
<a name="transcribe_GetVocabulary_python_3_topic"></a>

次のコード例は、`GetVocabulary` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def get_vocabulary(vocabulary_name, transcribe_client):
    """
    Gets information about a custom vocabulary.

    :param vocabulary_name: The name of the vocabulary to retrieve.
    :param transcribe_client: The Boto3 Transcribe client.
    :return: Information about the vocabulary.
    """
    try:
        response = transcribe_client.get_vocabulary(VocabularyName=vocabulary_name)
        logger.info("Got vocabulary %s.", response["VocabularyName"])
    except ClientError:
        logger.exception("Couldn't get vocabulary %s.", vocabulary_name)
        raise
    else:
        return response
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[GetVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/GetVocabulary)」を参照してください。

### `ListTranscriptionJobs`
<a name="transcribe_ListTranscriptionJobs_python_3_topic"></a>

次のコード例は、`ListTranscriptionJobs` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def list_jobs(job_filter, transcribe_client):
    """
    Lists summaries of the transcription jobs for the current AWS account.

    :param job_filter: The list of returned jobs must contain this string in their
                       names.
    :param transcribe_client: The Boto3 Transcribe client.
    :return: The list of retrieved transcription job summaries.
    """
    try:
        response = transcribe_client.list_transcription_jobs(JobNameContains=job_filter)
        jobs = response["TranscriptionJobSummaries"]
        next_token = response.get("NextToken")
        while next_token is not None:
            response = transcribe_client.list_transcription_jobs(
                JobNameContains=job_filter, NextToken=next_token
            )
            jobs += response["TranscriptionJobSummaries"]
            next_token = response.get("NextToken")
        logger.info("Got %s jobs with filter %s.", len(jobs), job_filter)
    except ClientError:
        logger.exception("Couldn't get jobs with filter %s.", job_filter)
        raise
    else:
        return jobs
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListTranscriptionJobs](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/ListTranscriptionJobs)」を参照してください。

### `ListVocabularies`
<a name="transcribe_ListVocabularies_python_3_topic"></a>

次のコード例は、`ListVocabularies` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def list_vocabularies(vocabulary_filter, transcribe_client):
    """
    Lists the custom vocabularies created for this AWS account.

    :param vocabulary_filter: The returned vocabularies must contain this string in
                              their names.
    :param transcribe_client: The Boto3 Transcribe client.
    :return: The list of retrieved vocabularies.
    """
    try:
        response = transcribe_client.list_vocabularies(NameContains=vocabulary_filter)
        vocabs = response["Vocabularies"]
        next_token = response.get("NextToken")
        while next_token is not None:
            response = transcribe_client.list_vocabularies(
                NameContains=vocabulary_filter, NextToken=next_token
            )
            vocabs += response["Vocabularies"]
            next_token = response.get("NextToken")
        logger.info(
            "Got %s vocabularies with filter %s.", len(vocabs), vocabulary_filter
        )
    except ClientError:
        logger.exception(
            "Couldn't list vocabularies with filter %s.", vocabulary_filter
        )
        raise
    else:
        return vocabs
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[ListVocabularies](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/ListVocabularies)」を参照してください。

### `StartTranscriptionJob`
<a name="transcribe_StartTranscriptionJob_python_3_topic"></a>

次のコード例は、`StartTranscriptionJob` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def start_job(
    job_name,
    media_uri,
    media_format,
    language_code,
    transcribe_client,
    vocabulary_name=None,
):
    """
    Starts a transcription job. This function returns as soon as the job is started.
    To get the current status of the job, call get_transcription_job. The job is
    successfully completed when the job status is 'COMPLETED'.

    :param job_name: The name of the transcription job. This must be unique for
                     your AWS account.
    :param media_uri: The URI where the audio file is stored. This is typically
                      in an Amazon S3 bucket.
    :param media_format: The format of the audio file. For example, mp3 or wav.
    :param language_code: The language code of the audio file.
                          For example, en-US or ja-JP
    :param transcribe_client: The Boto3 Transcribe client.
    :param vocabulary_name: The name of a custom vocabulary to use when transcribing
                            the audio file.
    :return: Data about the job.
    """
    try:
        job_args = {
            "TranscriptionJobName": job_name,
            "Media": {"MediaFileUri": media_uri},
            "MediaFormat": media_format,
            "LanguageCode": language_code,
        }
        if vocabulary_name is not None:
            job_args["Settings"] = {"VocabularyName": vocabulary_name}
        response = transcribe_client.start_transcription_job(**job_args)
        job = response["TranscriptionJob"]
        logger.info("Started transcription job %s.", job_name)
    except ClientError:
        logger.exception("Couldn't start transcription job %s.", job_name)
        raise
    else:
        return job
```
+  API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の「[StartTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/StartTranscriptionJob)」を参照してください。

### `UpdateVocabulary`
<a name="transcribe_UpdateVocabulary_python_3_topic"></a>

次のコード例は、`UpdateVocabulary` を使用する方法を示しています。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
def update_vocabulary(
    vocabulary_name, language_code, transcribe_client, phrases=None, table_uri=None
):
    """
    Updates an existing custom vocabulary. The entire vocabulary is replaced with
    the contents of the update.

    :param vocabulary_name: The name of the vocabulary to update.
    :param language_code: The language code of the vocabulary.
    :param transcribe_client: The Boto3 Transcribe client.
    :param phrases: A list of comma-separated phrases to include in the vocabulary.
    :param table_uri: A table of phrases and pronunciation hints to include in the
                      vocabulary.
    """
    try:
        vocab_args = {"VocabularyName": vocabulary_name, "LanguageCode": language_code}
        if phrases is not None:
            vocab_args["Phrases"] = phrases
        elif table_uri is not None:
            vocab_args["VocabularyFileUri"] = table_uri
        response = transcribe_client.update_vocabulary(**vocab_args)
        logger.info("Updated custom vocabulary %s.", response["VocabularyName"])
    except ClientError:
        logger.exception("Couldn't update custom vocabulary %s.", vocabulary_name)
        raise
```
+  API の詳細については、*AWS SDK for Python (Boto3) API リファレンス*の「[UpdateVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/UpdateVocabulary)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### カスタム語彙を作成し改良する
<a name="transcribe_Scenario_CustomVocabulary_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon S3 に音声ファイルをアップロードします。
+ Amazon Transcribe ジョブを実行してファイルを文字起こしし、結果を取得します。
+ カスタム語彙を作成して改良し、文字起こしの精度を向上させます。
+ カスタム語彙を使ってジョブを実行し、結果を取得します。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。
ルイス キャロルによる「ジャバウォッキー」の朗読を収録した音声ファイルを文字起こしします。まず、Amazon Transcribe アクションをラップする関数を作成します。  

```
def start_job(
    job_name,
    media_uri,
    media_format,
    language_code,
    transcribe_client,
    vocabulary_name=None,
):
    """
    Starts a transcription job. This function returns as soon as the job is started.
    To get the current status of the job, call get_transcription_job. The job is
    successfully completed when the job status is 'COMPLETED'.

    :param job_name: The name of the transcription job. This must be unique for
                     your AWS account.
    :param media_uri: The URI where the audio file is stored. This is typically
                      in an Amazon S3 bucket.
    :param media_format: The format of the audio file. For example, mp3 or wav.
    :param language_code: The language code of the audio file.
                          For example, en-US or ja-JP
    :param transcribe_client: The Boto3 Transcribe client.
    :param vocabulary_name: The name of a custom vocabulary to use when transcribing
                            the audio file.
    :return: Data about the job.
    """
    try:
        job_args = {
            "TranscriptionJobName": job_name,
            "Media": {"MediaFileUri": media_uri},
            "MediaFormat": media_format,
            "LanguageCode": language_code,
        }
        if vocabulary_name is not None:
            job_args["Settings"] = {"VocabularyName": vocabulary_name}
        response = transcribe_client.start_transcription_job(**job_args)
        job = response["TranscriptionJob"]
        logger.info("Started transcription job %s.", job_name)
    except ClientError:
        logger.exception("Couldn't start transcription job %s.", job_name)
        raise
    else:
        return job



def get_job(job_name, transcribe_client):
    """
    Gets details about a transcription job.

    :param job_name: The name of the job to retrieve.
    :param transcribe_client: The Boto3 Transcribe client.
    :return: The retrieved transcription job.
    """
    try:
        response = transcribe_client.get_transcription_job(
            TranscriptionJobName=job_name
        )
        job = response["TranscriptionJob"]
        logger.info("Got job %s.", job["TranscriptionJobName"])
    except ClientError:
        logger.exception("Couldn't get job %s.", job_name)
        raise
    else:
        return job



def delete_job(job_name, transcribe_client):
    """
    Deletes a transcription job. This also deletes the transcript associated with
    the job.

    :param job_name: The name of the job to delete.
    :param transcribe_client: The Boto3 Transcribe client.
    """
    try:
        transcribe_client.delete_transcription_job(TranscriptionJobName=job_name)
        logger.info("Deleted job %s.", job_name)
    except ClientError:
        logger.exception("Couldn't delete job %s.", job_name)
        raise



def create_vocabulary(
    vocabulary_name, language_code, transcribe_client, phrases=None, table_uri=None
):
    """
    Creates a custom vocabulary that can be used to improve the accuracy of
    transcription jobs. This function returns as soon as the vocabulary processing
    is started. Call get_vocabulary to get the current status of the vocabulary.
    The vocabulary is ready to use when its status is 'READY'.

    :param vocabulary_name: The name of the custom vocabulary.
    :param language_code: The language code of the vocabulary.
                          For example, en-US or nl-NL.
    :param transcribe_client: The Boto3 Transcribe client.
    :param phrases: A list of comma-separated phrases to include in the vocabulary.
    :param table_uri: A table of phrases and pronunciation hints to include in the
                      vocabulary.
    :return: Information about the newly created vocabulary.
    """
    try:
        vocab_args = {"VocabularyName": vocabulary_name, "LanguageCode": language_code}
        if phrases is not None:
            vocab_args["Phrases"] = phrases
        elif table_uri is not None:
            vocab_args["VocabularyFileUri"] = table_uri
        response = transcribe_client.create_vocabulary(**vocab_args)
        logger.info("Created custom vocabulary %s.", response["VocabularyName"])
    except ClientError:
        logger.exception("Couldn't create custom vocabulary %s.", vocabulary_name)
        raise
    else:
        return response



def get_vocabulary(vocabulary_name, transcribe_client):
    """
    Gets information about a custom vocabulary.

    :param vocabulary_name: The name of the vocabulary to retrieve.
    :param transcribe_client: The Boto3 Transcribe client.
    :return: Information about the vocabulary.
    """
    try:
        response = transcribe_client.get_vocabulary(VocabularyName=vocabulary_name)
        logger.info("Got vocabulary %s.", response["VocabularyName"])
    except ClientError:
        logger.exception("Couldn't get vocabulary %s.", vocabulary_name)
        raise
    else:
        return response



def update_vocabulary(
    vocabulary_name, language_code, transcribe_client, phrases=None, table_uri=None
):
    """
    Updates an existing custom vocabulary. The entire vocabulary is replaced with
    the contents of the update.

    :param vocabulary_name: The name of the vocabulary to update.
    :param language_code: The language code of the vocabulary.
    :param transcribe_client: The Boto3 Transcribe client.
    :param phrases: A list of comma-separated phrases to include in the vocabulary.
    :param table_uri: A table of phrases and pronunciation hints to include in the
                      vocabulary.
    """
    try:
        vocab_args = {"VocabularyName": vocabulary_name, "LanguageCode": language_code}
        if phrases is not None:
            vocab_args["Phrases"] = phrases
        elif table_uri is not None:
            vocab_args["VocabularyFileUri"] = table_uri
        response = transcribe_client.update_vocabulary(**vocab_args)
        logger.info("Updated custom vocabulary %s.", response["VocabularyName"])
    except ClientError:
        logger.exception("Couldn't update custom vocabulary %s.", vocabulary_name)
        raise



def list_vocabularies(vocabulary_filter, transcribe_client):
    """
    Lists the custom vocabularies created for this AWS account.

    :param vocabulary_filter: The returned vocabularies must contain this string in
                              their names.
    :param transcribe_client: The Boto3 Transcribe client.
    :return: The list of retrieved vocabularies.
    """
    try:
        response = transcribe_client.list_vocabularies(NameContains=vocabulary_filter)
        vocabs = response["Vocabularies"]
        next_token = response.get("NextToken")
        while next_token is not None:
            response = transcribe_client.list_vocabularies(
                NameContains=vocabulary_filter, NextToken=next_token
            )
            vocabs += response["Vocabularies"]
            next_token = response.get("NextToken")
        logger.info(
            "Got %s vocabularies with filter %s.", len(vocabs), vocabulary_filter
        )
    except ClientError:
        logger.exception(
            "Couldn't list vocabularies with filter %s.", vocabulary_filter
        )
        raise
    else:
        return vocabs



def delete_vocabulary(vocabulary_name, transcribe_client):
    """
    Deletes a custom vocabulary.

    :param vocabulary_name: The name of the vocabulary to delete.
    :param transcribe_client: The Boto3 Transcribe client.
    """
    try:
        transcribe_client.delete_vocabulary(VocabularyName=vocabulary_name)
        logger.info("Deleted vocabulary %s.", vocabulary_name)
    except ClientError:
        logger.exception("Couldn't delete vocabulary %s.", vocabulary_name)
        raise
```
ラッパー関数を呼び出して、カスタム語彙なしで音声を文字起こししてから、カスタム語彙の異なるバージョンで文字起こしを行うと、よりよい結果が取得できます。  

```
def usage_demo():
    """Shows how to use the Amazon Transcribe service."""
    logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")

    s3_resource = boto3.resource("s3")
    transcribe_client = boto3.client("transcribe")

    print("-" * 88)
    print("Welcome to the Amazon Transcribe demo!")
    print("-" * 88)

    bucket_name = f"jabber-bucket-{time.time_ns()}"
    print(f"Creating bucket {bucket_name}.")
    bucket = s3_resource.create_bucket(
        Bucket=bucket_name,
        CreateBucketConfiguration={
            "LocationConstraint": transcribe_client.meta.region_name
        },
    )
    media_file_name = ".media/Jabberwocky.mp3"
    media_object_key = "Jabberwocky.mp3"
    print(f"Uploading media file {media_file_name}.")
    bucket.upload_file(media_file_name, media_object_key)
    media_uri = f"s3://{bucket.name}/{media_object_key}"

    job_name_simple = f"Jabber-{time.time_ns()}"
    print(f"Starting transcription job {job_name_simple}.")
    start_job(
        job_name_simple,
        f"s3://{bucket_name}/{media_object_key}",
        "mp3",
        "en-US",
        transcribe_client,
    )
    transcribe_waiter = TranscribeCompleteWaiter(transcribe_client)
    transcribe_waiter.wait(job_name_simple)
    job_simple = get_job(job_name_simple, transcribe_client)
    transcript_simple = requests.get(
        job_simple["Transcript"]["TranscriptFileUri"]
    ).json()
    print(f"Transcript for job {transcript_simple['jobName']}:")
    print(transcript_simple["results"]["transcripts"][0]["transcript"])

    print("-" * 88)
    print(
        "Creating a custom vocabulary that lists the nonsense words to try to "
        "improve the transcription."
    )
    vocabulary_name = f"Jabber-vocabulary-{time.time_ns()}"
    create_vocabulary(
        vocabulary_name,
        "en-US",
        transcribe_client,
        phrases=[
            "brillig",
            "slithy",
            "borogoves",
            "mome",
            "raths",
            "Jub-Jub",
            "frumious",
            "manxome",
            "Tumtum",
            "uffish",
            "whiffling",
            "tulgey",
            "thou",
            "frabjous",
            "callooh",
            "callay",
            "chortled",
        ],
    )
    vocabulary_ready_waiter = VocabularyReadyWaiter(transcribe_client)
    vocabulary_ready_waiter.wait(vocabulary_name)

    job_name_vocabulary_list = f"Jabber-vocabulary-list-{time.time_ns()}"
    print(f"Starting transcription job {job_name_vocabulary_list}.")
    start_job(
        job_name_vocabulary_list,
        media_uri,
        "mp3",
        "en-US",
        transcribe_client,
        vocabulary_name,
    )
    transcribe_waiter.wait(job_name_vocabulary_list)
    job_vocabulary_list = get_job(job_name_vocabulary_list, transcribe_client)
    transcript_vocabulary_list = requests.get(
        job_vocabulary_list["Transcript"]["TranscriptFileUri"]
    ).json()
    print(f"Transcript for job {transcript_vocabulary_list['jobName']}:")
    print(transcript_vocabulary_list["results"]["transcripts"][0]["transcript"])

    print("-" * 88)
    print(
        "Updating the custom vocabulary with table data that provides additional "
        "pronunciation hints."
    )
    table_vocab_file = "jabber-vocabulary-table.txt"
    bucket.upload_file(table_vocab_file, table_vocab_file)
    update_vocabulary(
        vocabulary_name,
        "en-US",
        transcribe_client,
        table_uri=f"s3://{bucket.name}/{table_vocab_file}",
    )
    vocabulary_ready_waiter.wait(vocabulary_name)

    job_name_vocab_table = f"Jabber-vocab-table-{time.time_ns()}"
    print(f"Starting transcription job {job_name_vocab_table}.")
    start_job(
        job_name_vocab_table,
        media_uri,
        "mp3",
        "en-US",
        transcribe_client,
        vocabulary_name=vocabulary_name,
    )
    transcribe_waiter.wait(job_name_vocab_table)
    job_vocab_table = get_job(job_name_vocab_table, transcribe_client)
    transcript_vocab_table = requests.get(
        job_vocab_table["Transcript"]["TranscriptFileUri"]
    ).json()
    print(f"Transcript for job {transcript_vocab_table['jobName']}:")
    print(transcript_vocab_table["results"]["transcripts"][0]["transcript"])

    print("-" * 88)
    print("Getting data for jobs and vocabularies.")
    jabber_jobs = list_jobs("Jabber", transcribe_client)
    print(f"Found {len(jabber_jobs)} jobs:")
    for job_sum in jabber_jobs:
        job = get_job(job_sum["TranscriptionJobName"], transcribe_client)
        print(
            f"\t{job['TranscriptionJobName']}, {job['Media']['MediaFileUri']}, "
            f"{job['Settings'].get('VocabularyName')}"
        )

    jabber_vocabs = list_vocabularies("Jabber", transcribe_client)
    print(f"Found {len(jabber_vocabs)} vocabularies:")
    for vocab_sum in jabber_vocabs:
        vocab = get_vocabulary(vocab_sum["VocabularyName"], transcribe_client)
        vocab_content = requests.get(vocab["DownloadUri"]).text
        print(f"\t{vocab['VocabularyName']} contents:")
        print(vocab_content)

    print("-" * 88)
    print("Deleting demo jobs.")
    for job_name in [job_name_simple, job_name_vocabulary_list, job_name_vocab_table]:
        delete_job(job_name, transcribe_client)
    print("Deleting demo vocabulary.")
    delete_vocabulary(vocabulary_name, transcribe_client)
    print("Deleting demo bucket.")
    bucket.objects.delete()
    bucket.delete()
    print("Thanks for watching!")
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [CreateVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/CreateVocabulary)
  + [DeleteTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/DeleteTranscriptionJob)
  + [DeleteVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/DeleteVocabulary)
  + [GetTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/GetTranscriptionJob)
  + [GetVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/GetVocabulary)
  + [ListVocabularies](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/ListVocabularies)
  + [StartTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/StartTranscriptionJob)
  + [UpdateVocabulary](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/UpdateVocabulary)

### 音声の文字起こしとジョブデータを取得する
<a name="transcribe_Scenario_GettingStartedTranscriptionJobs_python_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Transcribe で文字起こしジョブを開始します。
+  ジョブが完了するまで待ちます。
+ 書き起こしが保存されている URI を取得します。

詳細については、「[Amazon Transcribe の開始方法](https://docs.aws.amazon.com/transcribe/latest/dg/getting-started.html)」を参照してください。

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/transcribe#code-examples)での設定と実行の方法を確認してください。

```
import time
import boto3


def transcribe_file(job_name, file_uri, transcribe_client):
    transcribe_client.start_transcription_job(
        TranscriptionJobName=job_name,
        Media={"MediaFileUri": file_uri},
        MediaFormat="wav",
        LanguageCode="en-US",
    )

    max_tries = 60
    while max_tries > 0:
        max_tries -= 1
        job = transcribe_client.get_transcription_job(TranscriptionJobName=job_name)
        job_status = job["TranscriptionJob"]["TranscriptionJobStatus"]
        if job_status in ["COMPLETED", "FAILED"]:
            print(f"Job {job_name} is {job_status}.")
            if job_status == "COMPLETED":
                print(
                    f"Download the transcript from\n"
                    f"\t{job['TranscriptionJob']['Transcript']['TranscriptFileUri']}."
                )
            break
        else:
            print(f"Waiting for {job_name}. Current status is {job_status}.")
        time.sleep(10)


def main():
    transcribe_client = boto3.client("transcribe")
    file_uri = "s3://test-transcribe/answer2.wav"
    transcribe_file("Example-job", file_uri, transcribe_client)


if __name__ == "__main__":
    main()
```
+ API の詳細については、「*AWS SDK for Python (Boto3) API リファレンス*」の以下のトピックを参照してください。
  + [GetTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/GetTranscriptionJob)
  + [StartTranscriptionJob](https://docs.aws.amazon.com/goto/boto3/transcribe-2017-10-26/StartTranscriptionJob)

# SDK for Ruby のコード例
<a name="ruby_3_code_examples"></a>

次のコード例は、 AWS SDK for Ruby で を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for Ruby デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/welcome.html) ** – で Ruby を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23ruby)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [Aurora](ruby_3_aurora_code_examples.md)
+ [Auto Scaling](ruby_3_auto-scaling_code_examples.md)
+ [CloudTrail](ruby_3_cloudtrail_code_examples.md)
+ [CloudWatch](ruby_3_cloudwatch_code_examples.md)
+ [Amazon Cognito ID プロバイダー](ruby_3_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](ruby_3_comprehend_code_examples.md)
+ [Amazon DocumentDB](ruby_3_docdb_code_examples.md)
+ [DynamoDB](ruby_3_dynamodb_code_examples.md)
+ [Amazon EC2](ruby_3_ec2_code_examples.md)
+ [(Elastic Beanstalk)](ruby_3_elastic-beanstalk_code_examples.md)
+ [EventBridge](ruby_3_eventbridge_code_examples.md)
+ [AWS Glue](ruby_3_glue_code_examples.md)
+ [IAM](ruby_3_iam_code_examples.md)
+ [Kinesis](ruby_3_kinesis_code_examples.md)
+ [AWS KMS](ruby_3_kms_code_examples.md)
+ [Lambda](ruby_3_lambda_code_examples.md)
+ [Amazon MSK](ruby_3_kafka_code_examples.md)
+ [Amazon Polly](ruby_3_polly_code_examples.md)
+ [Amazon RDS](ruby_3_rds_code_examples.md)
+ [Amazon S3](ruby_3_s3_code_examples.md)
+ [Amazon SES](ruby_3_ses_code_examples.md)
+ [Amazon SES API v2](ruby_3_sesv2_code_examples.md)
+ [Amazon SNS](ruby_3_sns_code_examples.md)
+ [Amazon SQS](ruby_3_sqs_code_examples.md)
+ [AWS STS](ruby_3_sts_code_examples.md)
+ [Amazon Textract](ruby_3_textract_code_examples.md)
+ [Amazon Translate](ruby_3_translate_code_examples.md)

# SDK for Ruby を使用した Aurora の例
<a name="ruby_3_aurora_code_examples"></a>

次のコード例は、Aurora AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)

## はじめに
<a name="get_started"></a>

### Hello Aurora
<a name="aurora_Hello_ruby_3_topic"></a>

次のコード例は、Aurora の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/aurora#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-rds'

# Creates an Amazon RDS client for the AWS Region
rds = Aws::RDS::Client.new

puts 'Listing clusters in this AWS account...'

# Calls the describe_db_clusters method to get information about clusters
resp = rds.describe_db_clusters(max_records: 20)

# Checks if any clusters are found and prints the appropriate message
if resp.db_clusters.empty?
  puts 'No clusters found!'
else
  # Loops through the array of cluster objects and prints the cluster identifier
  resp.db_clusters.each do |cluster|
    puts "Cluster identifier: #{cluster.db_cluster_identifier}"
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[DescribeDBClusters](https://docs.aws.amazon.com/goto/SdkForRubyV3/rds-2014-10-31/DescribeDBClusters)」を参照してください。

# SDK for Ruby を使用した自動スケーリングの例
<a name="ruby_3_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)

## はじめに
<a name="get_started"></a>

### こんにちは、Auto Scaling
<a name="auto-scaling_Hello_ruby_3_topic"></a>

次のコード例は、Auto Scaling の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-autoscaling'
require 'logger'

# AutoScalingManager is a class responsible for managing AWS Auto Scaling operations
# such as listing all Auto Scaling groups in the current AWS account.
class AutoScalingManager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Gets and prints a list of Auto Scaling groups for the account.
  def list_auto_scaling_groups
    paginator = @client.describe_auto_scaling_groups
    auto_scaling_groups = []
    paginator.each_page do |page|
      auto_scaling_groups.concat(page.auto_scaling_groups)
    end

    if auto_scaling_groups.empty?
      @logger.info('No Auto Scaling groups found for this account.')
    else
      auto_scaling_groups.each do |group|
        @logger.info("Auto Scaling group name: #{group.auto_scaling_group_name}")
        @logger.info("  Group ARN:             #{group.auto_scaling_group_arn}")
        @logger.info("  Min/max/desired:       #{group.min_size}/#{group.max_size}/#{group.desired_capacity}")
        @logger.info("\n")
      end
    end
  end
end

if $PROGRAM_NAME == __FILE__
  autoscaling_client = Aws::AutoScaling::Client.new
  manager = AutoScalingManager.new(autoscaling_client)
  manager.list_auto_scaling_groups
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/goto/SdkForRubyV3/autoscaling-2011-01-01/DescribeAutoScalingGroups)」を参照してください。**

# SDK for Ruby を使用した CloudTrail の例
<a name="ruby_3_cloudtrail_code_examples"></a>

次のコード例は、CloudTrail AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateTrail`
<a name="cloudtrail_CreateTrail_ruby_3_topic"></a>

次のコード例は、`CreateTrail` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'
require 'aws-sdk-s3'
require 'aws-sdk-sts'

def create_trail_example(s3_client, sts_client, cloudtrail_client, trail_name, bucket_name)
  resp = sts_client.get_caller_identity({})
  account_id = resp.account

  # Attach policy to an Amazon Simple Storage Service (S3) bucket.
  s3_client.create_bucket(bucket: bucket_name)
  begin
    policy = {
      'Version' => '2012-10-17',
      'Statement' => [
        {
          'Sid' => 'AWSCloudTrailAclCheck20150319',
          'Effect' => 'Allow',
          'Principal' => {
            'Service' => 'cloudtrail.amazonaws.com'
          },
          'Action' => 's3:GetBucketAcl',
          'Resource' => "arn:aws:s3:::#{bucket_name}"
        },
        {
          'Sid' => 'AWSCloudTrailWrite20150319',
          'Effect' => 'Allow',
          'Principal' => {
            'Service' => 'cloudtrail.amazonaws.com'
          },
          'Action' => 's3:PutObject',
          'Resource' => "arn:aws:s3:::#{bucket_name}/AWSLogs/#{account_id}/*",
          'Condition' => {
            'StringEquals' => {
              's3:x-amz-acl' => 'bucket-owner-full-control'
            }
          }
        }
      ]
    }.to_json

    s3_client.put_bucket_policy(
      bucket: bucket_name,
      policy: policy
    )
    puts "Successfully added policy to bucket #{bucket_name}"
  end

  begin
    cloudtrail_client.create_trail({
                                     name: trail_name, # required
                                     s3_bucket_name: bucket_name # required
                                   })

    puts "Successfully created trail: #{trail_name}."
  rescue StandardError => e
    puts "Got error trying to create trail #{trail_name}:\n #{e}"
    puts e
    exit 1
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[CreateTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/CreateTrail)」を参照してください。

### `DeleteTrail`
<a name="cloudtrail_DeleteTrail_ruby_3_topic"></a>

次のコード例は、`DeleteTrail` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
  client.delete_trail({
                        name: trail_name # required
                      })
  puts "Successfully deleted trail: #{trail_name}"
rescue StandardError => e
  puts "Got error trying to delete trail: #{trail_name}:"
  puts e
  exit 1
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteTrail](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/DeleteTrail)」を参照してください。

### `ListTrails`
<a name="cloudtrail_ListTrails_ruby_3_topic"></a>

次のコード例は、`ListTrails` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'

def describe_trails_example(client)
  resp = client.describe_trails({})
  puts "Found #{resp.trail_list.count} trail(s)."

  resp.trail_list.each do |trail|
    puts "Name:           #{trail.name}"
    puts "S3 bucket name: #{trail.s3_bucket_name}"
    puts
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListTrails](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/ListTrails)」を参照してください。**

### `LookupEvents`
<a name="cloudtrail_LookupEvents_ruby_3_topic"></a>

次のコード例は、`LookupEvents` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudtrail#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-cloudtrail' # v2: require 'aws-sdk'

# @param [Object] client
def lookup_events_example(client)
  resp = client.lookup_events
  puts "Found #{resp.events.count} events:"
  resp.events.each do |e|
    puts "Event name:   #{e.event_name}"
    puts "Event ID:     #{e.event_id}"
    puts "Event time:   #{e.event_time}"
    puts 'Resources:'

    e.resources.each do |r|
      puts "  Name:       #{r.resource_name}"
      puts "  Type:       #{r.resource_type}"
      puts ''
    end
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[LookupEvents](https://docs.aws.amazon.com/goto/SdkForRubyV3/cloudtrail-2013-11-01/LookupEvents)」を参照してください。

# SDK for Ruby を使用した CloudWatch の例
<a name="ruby_3_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeAlarms`
<a name="cloudwatch_DescribeAlarms_ruby_3_topic"></a>

次のコード例は、`DescribeAlarms` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-cloudwatch'

# Lists the names of available Amazon CloudWatch alarms.
#
# @param cloudwatch_client [Aws::CloudWatch::Client]
#   An initialized CloudWatch client.
# @example
#   list_alarms(Aws::CloudWatch::Client.new(region: 'us-east-1'))
def list_alarms(cloudwatch_client)
  response = cloudwatch_client.describe_alarms
  if response.metric_alarms.count.positive?
    response.metric_alarms.each do |alarm|
      puts alarm.alarm_name
    end
  else
    puts 'No alarms found.'
  end
rescue StandardError => e
  puts "Error getting information about alarms: #{e.message}"
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[DescribeAlarms](https://docs.aws.amazon.com/goto/SdkForRubyV3/monitoring-2010-08-01/DescribeAlarms)」を参照してください。**

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_ruby_3_topic"></a>

次のコード例は、`DescribeAlarmsForMetric` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
#
# @param cloudwatch_client [Aws::CloudWatch::Client]
#   An initialized CloudWatch client.
# @example
#   describe_metric_alarms(Aws::CloudWatch::Client.new(region: 'us-east-1'))
def describe_metric_alarms(cloudwatch_client)
  response = cloudwatch_client.describe_alarms

  if response.metric_alarms.count.positive?
    response.metric_alarms.each do |alarm|
      puts '-' * 16
      puts "Name:           #{alarm.alarm_name}"
      puts "State value:    #{alarm.state_value}"
      puts "State reason:   #{alarm.state_reason}"
      puts "Metric:         #{alarm.metric_name}"
      puts "Namespace:      #{alarm.namespace}"
      puts "Statistic:      #{alarm.statistic}"
      puts "Period:         #{alarm.period}"
      puts "Unit:           #{alarm.unit}"
      puts "Eval. periods:  #{alarm.evaluation_periods}"
      puts "Threshold:      #{alarm.threshold}"
      puts "Comp. operator: #{alarm.comparison_operator}"

      if alarm.key?(:ok_actions) && alarm.ok_actions.count.positive?
        puts 'OK actions:'
        alarm.ok_actions.each do |a|
          puts "  #{a}"
        end
      end

      if alarm.key?(:alarm_actions) && alarm.alarm_actions.count.positive?
        puts 'Alarm actions:'
        alarm.alarm_actions.each do |a|
          puts "  #{a}"
        end
      end

      if alarm.key?(:insufficient_data_actions) &&
         alarm.insufficient_data_actions.count.positive?
        puts 'Insufficient data actions:'
        alarm.insufficient_data_actions.each do |a|
          puts "  #{a}"
        end
      end

      puts 'Dimensions:'
      if alarm.key?(:dimensions) && alarm.dimensions.count.positive?
        alarm.dimensions.each do |d|
          puts "  Name: #{d.name}, Value: #{d.value}"
        end
      else
        puts '  None for this alarm.'
      end
    end
  else
    puts 'No alarms found.'
  end
rescue StandardError => e
  puts "Error getting information about alarms: #{e.message}"
end

# Example usage:
def run_me
  region = ''

  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby cw-ruby-example-show-alarms.rb REGION'
    puts 'Example: ruby cw-ruby-example-show-alarms.rb us-east-1'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  elsif ARGV.count.zero?
    region = 'us-east-1'
  # Otherwise, use the values as specified at the command prompt.
  else
    region = ARGV[0]
  end

  cloudwatch_client = Aws::CloudWatch::Client.new(region: region)
  puts 'Available alarms:'
  describe_metric_alarms(cloudwatch_client)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/goto/SdkForRubyV3/monitoring-2010-08-01/DescribeAlarmsForMetric)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_ruby_3_topic"></a>

次のコード例は、`DisableAlarmActions` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
# Disables an alarm in Amazon CloudWatch.
#
# Prerequisites.
#
# - The alarm to disable.
#
# @param cloudwatch_client [Aws::CloudWatch::Client]
#   An initialized CloudWatch client.
# @param alarm_name [String] The name of the alarm to disable.
# @return [Boolean] true if the alarm was disabled; otherwise, false.
# @example
#   exit 1 unless alarm_actions_disabled?(
#     Aws::CloudWatch::Client.new(region: 'us-east-1'),
#     'ObjectsInBucket'
#   )
def alarm_actions_disabled?(cloudwatch_client, alarm_name)
  cloudwatch_client.disable_alarm_actions(alarm_names: [alarm_name])
  true
rescue StandardError => e
  puts "Error disabling alarm actions: #{e.message}"
  false
end

# Example usage:
def run_me
  alarm_name = 'ObjectsInBucket'
  alarm_description = 'Objects exist in this bucket for more than 1 day.'
  metric_name = 'NumberOfObjects'
  # Notify this Amazon Simple Notification Service (Amazon SNS) topic when
  # the alarm transitions to the ALARM state.
  alarm_actions = ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic']
  namespace = 'AWS/S3'
  statistic = 'Average'
  dimensions = [
    {
      name: "BucketName",
      value: "amzn-s3-demo-bucket"
    },
    {
      name: 'StorageType',
      value: 'AllStorageTypes'
    }
  ]
  period = 86_400 # Daily (24 hours * 60 minutes * 60 seconds = 86400 seconds).
  unit = 'Count'
  evaluation_periods = 1 # More than one day.
  threshold = 1 # One object.
  comparison_operator = 'GreaterThanThreshold' # More than one object.
  # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch.
  region = 'us-east-1'

  cloudwatch_client = Aws::CloudWatch::Client.new(region: region)

  if alarm_created_or_updated?(
    cloudwatch_client,
    alarm_name,
    alarm_description,
    metric_name,
    alarm_actions,
    namespace,
    statistic,
    dimensions,
    period,
    unit,
    evaluation_periods,
    threshold,
    comparison_operator
  )
    puts "Alarm '#{alarm_name}' created or updated."
  else
    puts "Could not create or update alarm '#{alarm_name}'."
  end

  if alarm_actions_disabled?(cloudwatch_client, alarm_name)
    puts "Alarm '#{alarm_name}' disabled."
  else
    puts "Could not disable alarm '#{alarm_name}'."
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API 詳細については、**AWS SDK for Ruby API リファレンスの「[DisableAlarmActions](https://docs.aws.amazon.com/goto/SdkForRubyV3/monitoring-2010-08-01/DisableAlarmActions)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_ruby_3_topic"></a>

次のコード例は、`ListMetrics` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
# Lists available metrics for a metric namespace in Amazon CloudWatch.
#
# @param cloudwatch_client [Aws::CloudWatch::Client]
#   An initialized CloudWatch client.
# @param metric_namespace [String] The namespace of the metric.
# @example
#   list_metrics_for_namespace(
#     Aws::CloudWatch::Client.new(region: 'us-east-1'),
#     'SITE/TRAFFIC'
#   )
def list_metrics_for_namespace(cloudwatch_client, metric_namespace)
  response = cloudwatch_client.list_metrics(namespace: metric_namespace)

  if response.metrics.count.positive?
    response.metrics.each do |metric|
      puts "  Metric name: #{metric.metric_name}"
      if metric.dimensions.count.positive?
        puts '    Dimensions:'
        metric.dimensions.each do |dimension|
          puts "      Name: #{dimension.name}, Value: #{dimension.value}"
        end
      else
        puts 'No dimensions found.'
      end
    end
  else
    puts "No metrics found for namespace '#{metric_namespace}'. " \
      'Note that it could take up to 15 minutes for recently-added metrics ' \
      'to become available.'
  end
end

# Example usage:
def run_me
  metric_namespace = 'SITE/TRAFFIC'
  # Replace us-west-2 with the AWS Region you're using for Amazon CloudWatch.
  region = 'us-east-1'

  cloudwatch_client = Aws::CloudWatch::Client.new(region: region)

  # Add three datapoints.
  puts 'Continuing...' unless datapoint_added_to_metric?(
    cloudwatch_client,
    metric_namespace,
    'UniqueVisitors',
    'SiteName',
    'example.com',
    5_885.0,
    'Count'
  )

  puts 'Continuing...' unless datapoint_added_to_metric?(
    cloudwatch_client,
    metric_namespace,
    'UniqueVisits',
    'SiteName',
    'example.com',
    8_628.0,
    'Count'
  )

  puts 'Continuing...' unless datapoint_added_to_metric?(
    cloudwatch_client,
    metric_namespace,
    'PageViews',
    'PageURL',
    'example.html',
    18_057.0,
    'Count'
  )

  puts "Metrics for namespace '#{metric_namespace}':"
  list_metrics_for_namespace(cloudwatch_client, metric_namespace)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[ListMetrics](https://docs.aws.amazon.com/goto/SdkForRubyV3/monitoring-2010-08-01/ListMetrics)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_ruby_3_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
# Creates or updates an alarm in Amazon CloudWatch.
#
# @param cloudwatch_client [Aws::CloudWatch::Client]
#   An initialized CloudWatch client.
# @param alarm_name [String] The name of the alarm.
# @param alarm_description [String] A description about the alarm.
# @param metric_name [String] The name of the metric associated with the alarm.
# @param alarm_actions [Array] A list of Strings representing the
#   Amazon Resource Names (ARNs) to execute when the alarm transitions to the
#   ALARM state.
# @param namespace [String] The namespace for the metric to alarm on.
# @param statistic [String] The statistic for the metric.
# @param dimensions [Array] A list of dimensions for the metric, specified as
#   Aws::CloudWatch::Types::Dimension.
# @param period [Integer] The number of seconds before re-evaluating the metric.
# @param unit [String] The unit of measure for the statistic.
# @param evaluation_periods [Integer] The number of periods over which data is
#   compared to the specified threshold.
# @param theshold [Float] The value against which the specified statistic is compared.
# @param comparison_operator [String] The arithmetic operation to use when
#   comparing the specified statistic and threshold.
# @return [Boolean] true if the alarm was created or updated; otherwise, false.
# @example
#   exit 1 unless alarm_created_or_updated?(
#     Aws::CloudWatch::Client.new(region: 'us-east-1'),
#     'ObjectsInBucket',
#     'Objects exist in this bucket for more than 1 day.',
#     'NumberOfObjects',
#     ['arn:aws:sns:us-east-1:111111111111:Default_CloudWatch_Alarms_Topic'],
#     'AWS/S3',
#     'Average',
#     [
#       {
#         name: 'BucketName',
#         value: 'amzn-s3-demo-bucket'
#       },
#       {
#         name: 'StorageType',
#         value: 'AllStorageTypes'
#       }
#     ],
#     86_400,
#     'Count',
#     1,
#     1,
#     'GreaterThanThreshold'
#   )
def alarm_created_or_updated?(
  cloudwatch_client,
  alarm_name,
  alarm_description,
  metric_name,
  alarm_actions,
  namespace,
  statistic,
  dimensions,
  period,
  unit,
  evaluation_periods,
  threshold,
  comparison_operator
)
  cloudwatch_client.put_metric_alarm(
    alarm_name: alarm_name,
    alarm_description: alarm_description,
    metric_name: metric_name,
    alarm_actions: alarm_actions,
    namespace: namespace,
    statistic: statistic,
    dimensions: dimensions,
    period: period,
    unit: unit,
    evaluation_periods: evaluation_periods,
    threshold: threshold,
    comparison_operator: comparison_operator
  )
  true
rescue StandardError => e
  puts "Error creating alarm: #{e.message}"
  false
end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[PutMetricAlarm](https://docs.aws.amazon.com/goto/SdkForRubyV3/monitoring-2010-08-01/PutMetricAlarm)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_ruby_3_topic"></a>

次のコード例は、`PutMetricData` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。完全な例を見つけて、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cloudwatch#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-cloudwatch'

# Adds a datapoint to a metric in Amazon CloudWatch.
#
# @param cloudwatch_client [Aws::CloudWatch::Client]
#   An initialized CloudWatch client.
# @param metric_namespace [String] The namespace of the metric to add the
#   datapoint to.
# @param metric_name [String] The name of the metric to add the datapoint to.
# @param dimension_name [String] The name of the dimension to add the
#   datapoint to.
# @param dimension_value [String] The value of the dimension to add the
#   datapoint to.
# @param metric_value [Float] The value of the datapoint.
# @param metric_unit [String] The unit of measurement for the datapoint.
# @return [Boolean]
# @example
#   exit 1 unless datapoint_added_to_metric?(
#     Aws::CloudWatch::Client.new(region: 'us-east-1'),
#     'SITE/TRAFFIC',
#     'UniqueVisitors',
#     'SiteName',
#     'example.com',
#     5_885.0,
#     'Count'
#   )
def datapoint_added_to_metric?(
  cloudwatch_client,
  metric_namespace,
  metric_name,
  dimension_name,
  dimension_value,
  metric_value,
  metric_unit
)
  cloudwatch_client.put_metric_data(
    namespace: metric_namespace,
    metric_data: [
      {
        metric_name: metric_name,
        dimensions: [
          {
            name: dimension_name,
            value: dimension_value
          }
        ],
        value: metric_value,
        unit: metric_unit
      }
    ]
  )
  puts "Added data about '#{metric_name}' to namespace " \
    "'#{metric_namespace}'."
  true
rescue StandardError => e
  puts "Error adding data about '#{metric_name}' to namespace " \
    "'#{metric_namespace}': #{e.message}"
  false
end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[PutMetricData](https://docs.aws.amazon.com/goto/SdkForRubyV3/monitoring-2010-08-01/PutMetricData)」を参照してください。

# SDK for Ruby を使用する Amazon Cognito ID プロバイダーの例
<a name="ruby_3_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダー AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)

## はじめに
<a name="get_started"></a>

### Hello Amazon Cognito
<a name="cognito-identity-provider_Hello_ruby_3_topic"></a>

次のコード例は、Amazon Cognito の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/cognito#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-cognitoidentityprovider'
require 'logger'

# CognitoManager is a class responsible for managing AWS Cognito operations
# such as listing all user pools in the current AWS account.
class CognitoManager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all user pools associated with the AWS account.
  def list_user_pools
    paginator = @client.list_user_pools(max_results: 10)
    user_pools = []
    paginator.each_page do |page|
      user_pools.concat(page.user_pools)
    end

    if user_pools.empty?
      @logger.info('No Cognito user pools found.')
    else
      user_pools.each do |user_pool|
        @logger.info("User pool ID: #{user_pool.id}")
        @logger.info("User pool name: #{user_pool.name}")
        @logger.info("User pool status: #{user_pool.status}")
        @logger.info('---')
      end
    end
  end
end

if $PROGRAM_NAME == __FILE__
  cognito_client = Aws::CognitoIdentityProvider::Client.new
  manager = CognitoManager.new(cognito_client)
  manager.list_user_pools
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListUserPools](https://docs.aws.amazon.com/goto/SdkForRubyV3/cognito-idp-2016-04-18/ListUserPools)」を参照してください。**

# SDK for Ruby を使用する Amazon Comprehend の例
<a name="ruby_3_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_ruby_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Ruby**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/cross_service_examples/feedback_sentiment_analyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Ruby を使用する Amazon DocumentDB の例
<a name="ruby_3_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_ruby_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
require 'json'

def lambda_handler(event:, context:)
  event['events'].each do |record|
    log_document_db_event(record)
  end
  'OK'
end

def log_document_db_event(record)
  event_data = record['event'] || {}
  operation_type = event_data['operationType'] || 'Unknown'
  db = event_data.dig('ns', 'db') || 'Unknown'
  collection = event_data.dig('ns', 'coll') || 'Unknown'
  full_document = event_data['fullDocument'] || {}

  puts "Operation type: #{operation_type}"
  puts "db: #{db}"
  puts "collection: #{collection}"
  puts "Full document: #{JSON.pretty_generate(full_document)}"
end
```

# SDK for Ruby を使用した DynamoDB の例
<a name="ruby_3_dynamodb_code_examples"></a>

次のコード例は、DynamoDB AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello DynamoDB
<a name="dynamodb_Hello_ruby_3_topic"></a>

次のコード例は、DynamoDB の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-dynamodb'
require 'logger'

# DynamoDBManager is a class responsible for managing DynamoDB operations
# such as listing all tables in the current AWS account.
class DynamoDBManager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all DynamoDB tables in the current AWS account.
  def list_tables
    @logger.info('Here are the DynamoDB tables in your account:')

    paginator = @client.list_tables(limit: 10)
    table_names = []

    paginator.each_page do |page|
      page.table_names.each do |table_name|
        @logger.info("- #{table_name}")
        table_names << table_name
      end
    end

    if table_names.empty?
      @logger.info("You don't have any DynamoDB tables in your account.")
    else
      @logger.info("\nFound #{table_names.length} tables.")
    end
  end
end

if $PROGRAM_NAME == __FILE__
  dynamodb_client = Aws::DynamoDB::Client.new
  manager = DynamoDBManager.new(dynamodb_client)
  manager.list_tables
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[ListTables](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/ListTables)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_ruby_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
DynamoDB テーブルをカプセル化するクラスを作成します。  

```
  # Creates an Amazon DynamoDB table that can be used to store movie data.
  # The table uses the release year of the movie as the partition key and the
  # title as the sort key.
  #
  # @param table_name [String] The name of the table to create.
  # @return [Aws::DynamoDB::Table] The newly created table.
  def create_table(table_name)
    @table = @dynamo_resource.create_table(
      table_name: table_name,
      key_schema: [
        { attribute_name: 'year', key_type: 'HASH' }, # Partition key
        { attribute_name: 'title', key_type: 'RANGE' } # Sort key
      ],
      attribute_definitions: [
        { attribute_name: 'year', attribute_type: 'N' },
        { attribute_name: 'title', attribute_type: 'S' }
      ],
      billing_mode: 'PAY_PER_REQUEST'
    )
    @dynamo_resource.client.wait_until(:table_exists, table_name: table_name)
    @table
  rescue Aws::DynamoDB::Errors::ServiceError => e
    @logger.error("Failed create table #{table_name}:\n#{e.code}: #{e.message}")
    raise
  end
```
サンプルの JSON ファイルをダウンロードして抽出するヘルパー関数を作成します。  

```
  # Gets sample movie data, either from a local file or by first downloading it from
  # the Amazon DynamoDB Developer Guide.
  #
  # @param movie_file_name [String] The local file name where the movie data is stored in JSON format.
  # @return [Hash] The movie data as a Hash.
  def fetch_movie_data(movie_file_name)
    if !File.file?(movie_file_name)
      @logger.debug("Downloading #{movie_file_name}...")
      movie_content = URI.open(
        'https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/samples/moviedata.zip'
      )
      movie_json = ''
      Zip::File.open_buffer(movie_content) do |zip|
        zip.each do |entry|
          movie_json = entry.get_input_stream.read
        end
      end
    else
      movie_json = File.read(movie_file_name)
    end
    movie_data = JSON.parse(movie_json)
    # The sample file lists over 4000 movies. This returns only the first 250.
    movie_data.slice(0, 250)
  rescue StandardError => e
    puts("Failure downloading movie data:\n#{e}")
    raise
  end
```
対話型シナリオを実行してテーブルを作成し、そのテーブルに対してアクションを実行します。  

```
  table_name = "doc-example-table-movies-#{rand(10**4)}"
  scaffold = Scaffold.new(table_name)
  dynamodb_wrapper = DynamoDBBasics.new(table_name)

  new_step(1, 'Create a new DynamoDB table if none already exists.')
  unless scaffold.exists?(table_name)
    puts("\nNo such table: #{table_name}. Creating it...")
    scaffold.create_table(table_name)
    print "Done!\n".green
  end

  new_step(2, 'Add a new record to the DynamoDB table.')
  my_movie = {}
  my_movie[:title] = CLI::UI::Prompt.ask('Enter the title of a movie to add to the table. E.g. The Matrix')
  my_movie[:year] = CLI::UI::Prompt.ask('What year was it released? E.g. 1989').to_i
  my_movie[:rating] = CLI::UI::Prompt.ask('On a scale of 1 - 10, how do you rate it? E.g. 7').to_i
  my_movie[:plot] = CLI::UI::Prompt.ask('Enter a brief summary of the plot. E.g. A man awakens to a new reality.')
  dynamodb_wrapper.add_item(my_movie)
  puts("\nNew record added:")
  puts JSON.pretty_generate(my_movie).green
  print "Done!\n".green

  new_step(3, 'Update a record in the DynamoDB table.')
  my_movie[:rating] = CLI::UI::Prompt.ask("Let's update the movie you added with a new rating, e.g. 3:").to_i
  response = dynamodb_wrapper.update_item(my_movie)
  puts("Updated '#{my_movie[:title]}' with new attributes:")
  puts JSON.pretty_generate(response).green
  print "Done!\n".green

  new_step(4, 'Get a record from the DynamoDB table.')
  puts("Searching for #{my_movie[:title]} (#{my_movie[:year]})...")
  response = dynamodb_wrapper.get_item(my_movie[:title], my_movie[:year])
  puts JSON.pretty_generate(response).green
  print "Done!\n".green

  new_step(5, 'Write a batch of items into the DynamoDB table.')
  download_file = 'moviedata.json'
  puts("Downloading movie database to #{download_file}...")
  movie_data = scaffold.fetch_movie_data(download_file)
  puts("Writing movie data from #{download_file} into your table...")
  scaffold.write_batch(movie_data)
  puts("Records added: #{movie_data.length}.")
  print "Done!\n".green

  new_step(5, 'Query for a batch of items by key.')
  loop do
    release_year = CLI::UI::Prompt.ask('Enter a year between 1972 and 2018, e.g. 1999:').to_i
    results = dynamodb_wrapper.query_items(release_year)
    if results.any?
      puts("There were #{results.length} movies released in #{release_year}:")
      results.each do |movie|
        print "\t #{movie['title']}".green
      end
      break
    else
      continue = CLI::UI::Prompt.ask("Found no movies released in #{release_year}! Try another year? (y/n)")
      break unless continue.eql?('y')
    end
  end
  print "\nDone!\n".green

  new_step(6, 'Scan for a batch of items using a filter expression.')
  years = {}
  years[:start] = CLI::UI::Prompt.ask('Enter a starting year between 1972 and 2018:')
  years[:end] = CLI::UI::Prompt.ask('Enter an ending year between 1972 and 2018:')
  releases = dynamodb_wrapper.scan_items(years)
  if !releases.empty?
    puts("Found #{releases.length} movies.")
    count = Question.ask(
      'How many do you want to see? ', method(:is_int), in_range(1, releases.length)
    )
    puts("Here are your #{count} movies:")
    releases.take(count).each do |release|
      puts("\t#{release['title']}")
    end
  else
    puts("I don't know about any movies released between #{years[:start]} "\
         "and #{years[:end]}.")
  end
  print "\nDone!\n".green

  new_step(7, 'Delete an item from the DynamoDB table.')
  answer = CLI::UI::Prompt.ask("Do you want to remove '#{my_movie[:title]}'? (y/n) ")
  if answer.eql?('y')
    dynamodb_wrapper.delete_item(my_movie[:title], my_movie[:year])
    puts("Removed '#{my_movie[:title]}' from the table.")
    print "\nDone!\n".green
  end

  new_step(8, 'Delete the DynamoDB table.')
  answer = CLI::UI::Prompt.ask('Delete the table? (y/n)')
  if answer.eql?('y')
    scaffold.delete_table
    puts("Deleted #{table_name}.")
  else
    puts("Don't forget to delete the table when you're done!")
  end
  print "\nThanks for watching!\n".green
rescue Aws::Errors::ServiceError
  puts('Something went wrong with the demo.')
rescue Errno::ENOENT
  true
end
```
+ API の詳細については、「AWS SDK for Ruby API リファレンス**」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/BatchWriteItem)
  + [CreateTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/CreateTable)
  + [DeleteItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteItem)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteTable)
  + [DescribeTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DescribeTable)
  + [GetItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/GetItem)
  + [PutItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/PutItem)
  + [Query](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Query)
  + [Scan](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Scan)
  + [UpdateItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/UpdateItem)

## アクション
<a name="actions"></a>

### `BatchExecuteStatement`
<a name="dynamodb_BatchExecuteStatement_ruby_3_topic"></a>

次のコード例は、`BatchExecuteStatement` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
PartiQL を使用して項目のバッチを読み取ります。  

```
class DynamoDBPartiQLBatch
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamodb = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamodb.table(table_name)
  end

  # Selects a batch of items from a table using PartiQL
  #
  # @param batch_titles [Array] Collection of movie titles
  # @return [Aws::DynamoDB::Types::BatchExecuteStatementOutput]
  def batch_execute_select(batch_titles)
    request_items = batch_titles.map do |title, year|
      {
        statement: "SELECT * FROM \"#{@table.name}\" WHERE title=? and year=?",
        parameters: [title, year]
      }
    end
    @dynamodb.client.batch_execute_statement({ statements: request_items })
  end
```
PartiQL を使用して項目のバッチを削除します。  

```
class DynamoDBPartiQLBatch
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamodb = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamodb.table(table_name)
  end

  # Deletes a batch of items from a table using PartiQL
  #
  # @param batch_titles [Array] Collection of movie titles
  # @return [Aws::DynamoDB::Types::BatchExecuteStatementOutput]
  def batch_execute_write(batch_titles)
    request_items = batch_titles.map do |title, year|
      {
        statement: "DELETE FROM \"#{@table.name}\" WHERE title=? and year=?",
        parameters: [title, year]
      }
    end
    @dynamodb.client.batch_execute_statement({ statements: request_items })
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_ruby_3_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Fills an Amazon DynamoDB table with the specified data. Items are sent in
  # batches of 25 until all items are written.
  #
  # @param movies [Enumerable] The data to put in the table. Each item must contain at least
  #                            the keys required by the schema that was specified when the
  #                            table was created.
  def write_batch(movies)
    index = 0
    slice_size = 25
    while index < movies.length
      movie_items = []
      movies[index, slice_size].each do |movie|
        movie_items.append({ put_request: { item: movie } })
      end
      @dynamo_resource.client.batch_write_item({ request_items: { @table.name => movie_items } })
      index += slice_size
    end
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts(
      "Couldn't load data into table #{@table.name}. Here's why:"
    )
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[BatchWriteItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/BatchWriteItem)」を参照してください。**

### `CreateTable`
<a name="dynamodb_CreateTable_ruby_3_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
# Encapsulates an Amazon DynamoDB table of movie data.
class Scaffold
  attr_reader :dynamo_resource, :table_name, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table_name = table_name
    @table = nil
    @logger = Logger.new($stdout)
    @logger.level = Logger::DEBUG
  end

  # Creates an Amazon DynamoDB table that can be used to store movie data.
  # The table uses the release year of the movie as the partition key and the
  # title as the sort key.
  #
  # @param table_name [String] The name of the table to create.
  # @return [Aws::DynamoDB::Table] The newly created table.
  def create_table(table_name)
    @table = @dynamo_resource.create_table(
      table_name: table_name,
      key_schema: [
        { attribute_name: 'year', key_type: 'HASH' }, # Partition key
        { attribute_name: 'title', key_type: 'RANGE' } # Sort key
      ],
      attribute_definitions: [
        { attribute_name: 'year', attribute_type: 'N' },
        { attribute_name: 'title', attribute_type: 'S' }
      ],
      billing_mode: 'PAY_PER_REQUEST'
    )
    @dynamo_resource.client.wait_until(:table_exists, table_name: table_name)
    @table
  rescue Aws::DynamoDB::Errors::ServiceError => e
    @logger.error("Failed create table #{table_name}:\n#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[CreateTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/CreateTable)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_ruby_3_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Deletes a movie from the table.
  #
  # @param title [String] The title of the movie to delete.
  # @param year [Integer] The release year of the movie to delete.
  def delete_item(title, year)
    @table.delete_item(key: { 'year' => year, 'title' => title })
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't delete movie #{title}. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[DeleteItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteItem)」を参照してください。**

### `DeleteTable`
<a name="dynamodb_DeleteTable_ruby_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
# Encapsulates an Amazon DynamoDB table of movie data.
class Scaffold
  attr_reader :dynamo_resource, :table_name, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table_name = table_name
    @table = nil
    @logger = Logger.new($stdout)
    @logger.level = Logger::DEBUG
  end

  # Deletes the table.
  def delete_table
    @table.delete
    @table = nil
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't delete table. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DeleteTable)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_ruby_3_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
# Encapsulates an Amazon DynamoDB table of movie data.
class Scaffold
  attr_reader :dynamo_resource, :table_name, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table_name = table_name
    @table = nil
    @logger = Logger.new($stdout)
    @logger.level = Logger::DEBUG
  end

  # Determines whether a table exists. As a side effect, stores the table in
  # a member variable.
  #
  # @param table_name [String] The name of the table to check.
  # @return [Boolean] True when the table exists; otherwise, False.
  def exists?(table_name)
    @dynamo_resource.client.describe_table(table_name: table_name)
    @logger.debug("Table #{table_name} exists")
  rescue Aws::DynamoDB::Errors::ResourceNotFoundException
    @logger.debug("Table #{table_name} doesn't exist")
    false
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't check for existence of #{table_name}:\n")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[DescribeTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/DescribeTable)」を参照してください。

### `ExecuteStatement`
<a name="dynamodb_ExecuteStatement_ruby_3_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
PartiQL を使用して項目を 1 つ選択します。  

```
class DynamoDBPartiQLSingle
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamodb = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamodb.table(table_name)
  end

  # Gets a single record from a table using PartiQL.
  # Note: To perform more fine-grained selects,
  # use the Client.query instance method instead.
  #
  # @param title [String] The title of the movie to search.
  # @return [Aws::DynamoDB::Types::ExecuteStatementOutput]
  def select_item_by_title(title)
    request = {
      statement: "SELECT * FROM \"#{@table.name}\" WHERE title=?",
      parameters: [title]
    }
    @dynamodb.client.execute_statement(request)
  end
```
PartiQL を使用して項目を更新します。  

```
class DynamoDBPartiQLSingle
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamodb = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamodb.table(table_name)
  end

  # Updates a single record from a table using PartiQL.
  #
  # @param title [String] The title of the movie to update.
  # @param year [Integer] The year the movie was released.
  # @param rating [Float] The new rating to assign the title.
  # @return [Aws::DynamoDB::Types::ExecuteStatementOutput]
  def update_rating_by_title(title, year, rating)
    request = {
      statement: "UPDATE \"#{@table.name}\" SET info.rating=? WHERE title=? and year=?",
      parameters: [{ "N": rating }, title, year]
    }
    @dynamodb.client.execute_statement(request)
  end
```
PartiQL を使用して項目を 1 つ追加します。  

```
class DynamoDBPartiQLSingle
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamodb = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamodb.table(table_name)
  end

  # Adds a single record to a table using PartiQL.
  #
  # @param title [String] The title of the movie to update.
  # @param year [Integer] The year the movie was released.
  # @param plot [String] The plot of the movie.
  # @param rating [Float] The new rating to assign the title.
  # @return [Aws::DynamoDB::Types::ExecuteStatementOutput]
  def insert_item(title, year, plot, rating)
    request = {
      statement: "INSERT INTO \"#{@table.name}\" VALUE {'title': ?, 'year': ?, 'info': ?}",
      parameters: [title, year, { 'plot': plot, 'rating': rating }]
    }
    @dynamodb.client.execute_statement(request)
  end
```
PartiQL を使用して項目を 1 つ削除します。  

```
class DynamoDBPartiQLSingle
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamodb = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamodb.table(table_name)
  end

  # Deletes a single record from a table using PartiQL.
  #
  # @param title [String] The title of the movie to update.
  # @param year [Integer] The year the movie was released.
  # @return [Aws::DynamoDB::Types::ExecuteStatementOutput]
  def delete_item_by_title(title, year)
    request = {
      statement: "DELETE FROM \"#{@table.name}\" WHERE title=? and year=?",
      parameters: [title, year]
    }
    @dynamodb.client.execute_statement(request)
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_ruby_3_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Gets movie data from the table for a specific movie.
  #
  # @param title [String] The title of the movie.
  # @param year [Integer] The release year of the movie.
  # @return [Hash] The data about the requested movie.
  def get_item(title, year)
    @table.get_item(key: { 'year' => year, 'title' => title })
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't get movie #{title} (#{year}) from table #{@table.name}:\n")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[GetItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/GetItem)」を参照してください。**

### `ListTables`
<a name="dynamodb_ListTables_ruby_3_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルが存在するかどうかを確認します。  

```
# Encapsulates an Amazon DynamoDB table of movie data.
class Scaffold
  attr_reader :dynamo_resource, :table_name, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table_name = table_name
    @table = nil
    @logger = Logger.new($stdout)
    @logger.level = Logger::DEBUG
  end

  # Determines whether a table exists. As a side effect, stores the table in
  # a member variable.
  #
  # @param table_name [String] The name of the table to check.
  # @return [Boolean] True when the table exists; otherwise, False.
  def exists?(table_name)
    @dynamo_resource.client.describe_table(table_name: table_name)
    @logger.debug("Table #{table_name} exists")
  rescue Aws::DynamoDB::Errors::ResourceNotFoundException
    @logger.debug("Table #{table_name} doesn't exist")
    false
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't check for existence of #{table_name}:\n")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[ListTables](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/ListTables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_ruby_3_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Adds a movie to the table.
  #
  # @param movie [Hash] The title, year, plot, and rating of the movie.
  def add_item(movie)
    @table.put_item(
      item: {
        'year' => movie[:year],
        'title' => movie[:title],
        'info' => { 'plot' => movie[:plot], 'rating' => movie[:rating] }
      }
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't add movie #{title} to table #{@table.name}. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[PutItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/PutItem)」を参照してください。**

### `Query`
<a name="dynamodb_Query_ruby_3_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Queries for movies that were released in the specified year.
  #
  # @param year [Integer] The year to query.
  # @return [Array] The list of movies that were released in the specified year.
  def query_items(year)
    response = @table.query(
      key_condition_expression: '#yr = :year',
      expression_attribute_names: { '#yr' => 'year' },
      expression_attribute_values: { ':year' => year }
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't query for movies released in #{year}. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    response.items
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[Query](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Query)」を参照してください。**

### `Scan`
<a name="dynamodb_Scan_ruby_3_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Scans for movies that were released in a range of years.
  # Uses a projection expression to return a subset of data for each movie.
  #
  # @param year_range [Hash] The range of years to retrieve.
  # @return [Array] The list of movies released in the specified years.
  def scan_items(year_range)
    movies = []
    scan_hash = {
      filter_expression: '#yr between :start_yr and :end_yr',
      projection_expression: '#yr, title, info.rating',
      expression_attribute_names: { '#yr' => 'year' },
      expression_attribute_values: {
        ':start_yr' => year_range[:start], ':end_yr' => year_range[:end]
      }
    }
    done = false
    start_key = nil
    until done
      scan_hash[:exclusive_start_key] = start_key unless start_key.nil?
      response = @table.scan(scan_hash)
      movies.concat(response.items) unless response.items.empty?
      start_key = response.last_evaluated_key
      done = start_key.nil?
    end
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't scan for movies. Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    movies
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[Scan](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/Scan)」を参照してください。**

### `UpdateItem`
<a name="dynamodb_UpdateItem_ruby_3_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
class DynamoDBBasics
  attr_reader :dynamo_resource, :table

  def initialize(table_name)
    client = Aws::DynamoDB::Client.new(region: 'us-east-1')
    @dynamo_resource = Aws::DynamoDB::Resource.new(client: client)
    @table = @dynamo_resource.table(table_name)
  end

  # Updates rating and plot data for a movie in the table.
  #
  # @param movie [Hash] The title, year, plot, rating of the movie.
  def update_item(movie)
    response = @table.update_item(
      key: { 'year' => movie[:year], 'title' => movie[:title] },
      update_expression: 'set info.rating=:r',
      expression_attribute_values: { ':r' => movie[:rating] },
      return_values: 'UPDATED_NEW'
    )
  rescue Aws::DynamoDB::Errors::ServiceError => e
    puts("Couldn't update movie #{movie[:title]} (#{movie[:year]}) in table #{@table.name}\n")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    response.attributes
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[UpdateItem](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/UpdateItem)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### PartiQL ステートメントのバッチを使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLBatch_ruby_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ 複数の SELECT ステートメントを実行して、項目のバッチを取得します。
+ 複数の INSERT ステートメントを実行して、項目のバッチを追加する。
+ 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。
+ 複数の DELETE ステートメントを実行して、項目のバッチを削除します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルを作成し、PartiQL クエリのバッチを実行するシナリオを実行します。  

```
  table_name = "doc-example-table-movies-partiql-#{rand(10**4)}"
  scaffold = Scaffold.new(table_name)
  sdk = DynamoDBPartiQLBatch.new(table_name)

  new_step(1, 'Create a new DynamoDB table if none already exists.')
  unless scaffold.exists?(table_name)
    puts("\nNo such table: #{table_name}. Creating it...")
    scaffold.create_table(table_name)
    print "Done!\n".green
  end

  new_step(2, 'Populate DynamoDB table with movie data.')
  download_file = 'moviedata.json'
  puts("Downloading movie database to #{download_file}...")
  movie_data = scaffold.fetch_movie_data(download_file)
  puts("Writing movie data from #{download_file} into your table...")
  scaffold.write_batch(movie_data)
  puts("Records added: #{movie_data.length}.")
  print "Done!\n".green

  new_step(3, 'Select a batch of items from the movies table.')
  puts "Let's select some popular movies for side-by-side comparison."
  response = sdk.batch_execute_select([['Mean Girls', 2004], ['Goodfellas', 1977], ['The Prancing of the Lambs', 2005]])
  puts("Items selected: #{response['responses'].length}\n")
  print "\nDone!\n".green

  new_step(4, 'Delete a batch of items from the movies table.')
  sdk.batch_execute_write([['Mean Girls', 2004], ['Goodfellas', 1977], ['The Prancing of the Lambs', 2005]])
  print "\nDone!\n".green

  new_step(5, 'Delete the table.')
  return unless scaffold.exists?(table_name)

  scaffold.delete_table
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[BatchExecuteStatement](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/BatchExecuteStatement)」を参照してください。

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_ruby_3_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
テーブルを作成し、PartiQL クエリを実行するシナリオを実行します。  

```
  table_name = "doc-example-table-movies-partiql-#{rand(10**8)}"
  scaffold = Scaffold.new(table_name)
  sdk = DynamoDBPartiQLSingle.new(table_name)

  new_step(1, 'Create a new DynamoDB table if none already exists.')
  unless scaffold.exists?(table_name)
    puts("\nNo such table: #{table_name}. Creating it...")
    scaffold.create_table(table_name)
    print "Done!\n".green
  end

  new_step(2, 'Populate DynamoDB table with movie data.')
  download_file = 'moviedata.json'
  puts("Downloading movie database to #{download_file}...")
  movie_data = scaffold.fetch_movie_data(download_file)
  puts("Writing movie data from #{download_file} into your table...")
  scaffold.write_batch(movie_data)
  puts("Records added: #{movie_data.length}.")
  print "Done!\n".green

  new_step(3, 'Select a single item from the movies table.')
  response = sdk.select_item_by_title('Star Wars')
  puts("Items selected for title 'Star Wars': #{response.items.length}\n")
  print response.items.first.to_s.yellow
  print "\n\nDone!\n".green

  new_step(4, 'Update a single item from the movies table.')
  puts "Let's correct the rating on The Big Lebowski to 10.0."
  sdk.update_rating_by_title('The Big Lebowski', 1998, 10.0)
  print "\nDone!\n".green

  new_step(5, 'Delete a single item from the movies table.')
  puts "Let's delete The Silence of the Lambs because it's just too scary."
  sdk.delete_item_by_title('The Silence of the Lambs', 1991)
  print "\nDone!\n".green

  new_step(6, 'Insert a new item into the movies table.')
  puts "Let's create a less-scary movie called The Prancing of the Lambs."
  sdk.insert_item('The Prancing of the Lambs', 2005, 'A movie about happy livestock.', 5.0)
  print "\nDone!\n".green

  new_step(7, 'Delete the table.')
  return unless scaffold.exists?(table_name)

  scaffold.delete_table
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[ExecuteStatement](https://docs.aws.amazon.com/goto/SdkForRubyV3/dynamodb-2012-08-10/ExecuteStatement)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_ruby_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で DynamoDB イベントの消費。  

```
def lambda_handler(event:, context:)
    return 'received empty event' if event['Records'].empty?
  
    event['Records'].each do |record|
      log_dynamodb_record(record)
    end
  
    "Records processed: #{event['Records'].length}"
  end
  
  def log_dynamodb_record(record)
    puts record['eventID']
    puts record['eventName']
    puts "DynamoDB Record: #{JSON.generate(record['dynamodb'])}"
  end
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_ruby_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
def lambda_handler(event:, context:)
    records = event["Records"]
    cur_record_sequence_number = ""
  
    records.each do |record|
      begin
        # Process your record
        cur_record_sequence_number = record["dynamodb"]["SequenceNumber"]
      rescue StandardError => e
        # Return failed record's sequence number
        return {"batchItemFailures" => [{"itemIdentifier" => cur_record_sequence_number}]}
      end
    end
  
    {"batchItemFailures" => []}
  end
```

# SDK for Ruby を使用した Amazon EC2 の例
<a name="ruby_3_ec2_code_examples"></a>

次のコード例は、Amazon EC2 AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_ruby_3_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'
require 'logger'

# EC2Manager is a class responsible for managing EC2 operations
# such as listing all EC2 instances in the current AWS account.
class EC2Manager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all EC2 instances in the current AWS account.
  def list_instances
    @logger.info('Listing instances')

    instances = fetch_instances

    if instances.empty?
      @logger.info('You have no instances')
    else
      print_instances(instances)
    end
  end

  private

  # Fetches all EC2 instances using pagination.
  #
  # @return [Array<Aws::EC2::Types::Instance>] List of EC2 instances.
  def fetch_instances
    paginator = @client.describe_instances
    instances = []

    paginator.each_page do |page|
      page.reservations.each do |reservation|
        reservation.instances.each do |instance|
          instances << instance
        end
      end
    end

    instances
  end

  # Prints details of the given EC2 instances.
  #
  # @param instances [Array<Aws::EC2::Types::Instance>] List of EC2 instances to print.
  def print_instances(instances)
    instances.each do |instance|
      @logger.info("Instance ID: #{instance.instance_id}")
      @logger.info("Instance Type: #{instance.instance_type}")
      @logger.info("Public IP: #{instance.public_ip_address}")
      @logger.info("Public DNS Name: #{instance.public_dns_name}")
      @logger.info("\n")
    end
  end
end

if $PROGRAM_NAME == __FILE__
  ec2_client = Aws::EC2::Client.new(region: 'us-west-2')
  manager = EC2Manager.new(ec2_client)
  manager.list_instances
end
```
+  API の詳細については、「AWS SDK for Ruby API リファレンス」**の「[DescribeSecurityGroups](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/DescribeSecurityGroups)」を参照してください。

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_ruby_3_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
# Creates an Elastic IP address in Amazon Virtual Private Cloud (Amazon VPC).
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @return [String] The allocation ID corresponding to the Elastic IP address.
# @example
#   puts allocate_elastic_ip_address(Aws::EC2::Client.new(region: 'us-west-2'))
def allocate_elastic_ip_address(ec2_client)
  response = ec2_client.allocate_address(domain: 'vpc')
  response.allocation_id
rescue StandardError => e
  puts "Error allocating Elastic IP address: #{e.message}"
  'Error'
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[AllocateAddress](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/AllocateAddress)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_ruby_3_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
# Associates an Elastic IP address with an Amazon Elastic Compute Cloud
# (Amazon EC2) instance.
#
# Prerequisites:
#
# - The allocation ID corresponding to the Elastic IP address.
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param allocation_id [String] The ID of the allocation corresponding to
#   the Elastic IP address.
# @param instance_id [String] The ID of the instance.
# @return [String] The assocation ID corresponding to the association of the
#   Elastic IP address to the instance.
# @example
#   puts allocate_elastic_ip_address(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'eipalloc-04452e528a66279EX',
#     'i-033c48ef067af3dEX')
def associate_elastic_ip_address_with_instance(
  ec2_client,
  allocation_id,
  instance_id
)
  response = ec2_client.associate_address(
    allocation_id: allocation_id,
    instance_id: instance_id
  )
  response.association_id
rescue StandardError => e
  puts "Error associating Elastic IP address with instance: #{e.message}"
  'Error'
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[AssociateAddress](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/AssociateAddress)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_ruby_3_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
# This code example does the following:
# 1. Creates a key pair in Amazon Elastic Compute Cloud (Amazon EC2).
# 2. Displays information about available key pairs.
# 3. Deletes the key pair.

require 'aws-sdk-ec2'

# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param key_pair_name [String] The name for the key pair and private
#   key file.
# @return [Boolean] true if the key pair and private key file were
#   created; otherwise, false.
# @example
#   exit 1 unless key_pair_created?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'my-key-pair'
#   )
def key_pair_created?(ec2_client, key_pair_name)
  key_pair = ec2_client.create_key_pair(key_name: key_pair_name)
  puts "Created key pair '#{key_pair.key_name}' with fingerprint " \
    "'#{key_pair.key_fingerprint}' and ID '#{key_pair.key_pair_id}'."
  filename = File.join(Dir.home, "#{key_pair_name}.pem")
  File.open(filename, 'w') { |file| file.write(key_pair.key_material) }
  puts "Private key file saved locally as '#{filename}'."
  true
rescue Aws::EC2::Errors::InvalidKeyPairDuplicate
  puts "Error creating key pair: a key pair named '#{key_pair_name}' " \
    'already exists.'
  false
rescue StandardError => e
  puts "Error creating key pair or saving private key file: #{e.message}"
  false
end

# Displays information about available key pairs in
# Amazon Elastic Compute Cloud (Amazon EC2).
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @example
#   describe_key_pairs(Aws::EC2::Client.new(region: 'us-west-2'))
def describe_key_pairs(ec2_client)
  result = ec2_client.describe_key_pairs
  if result.key_pairs.count.zero?
    puts 'No key pairs found.'
  else
    puts 'Key pair names:'
    result.key_pairs.each do |key_pair|
      puts key_pair.key_name
    end
  end
rescue StandardError => e
  puts "Error getting information about key pairs: #{e.message}"
end

# Deletes a key pair in Amazon Elastic Compute Cloud (Amazon EC2).
#
# Prerequisites:
#
# - The key pair to delete.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param key_pair_name [String] The name of the key pair to delete.
# @return [Boolean] true if the key pair was deleted; otherwise, false.
# @example
#   exit 1 unless key_pair_deleted?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'my-key-pair'
#   )
def key_pair_deleted?(ec2_client, key_pair_name)
  ec2_client.delete_key_pair(key_name: key_pair_name)
  true
rescue StandardError => e
  puts "Error deleting key pair: #{e.message}"
  false
end

# Example usage:
def run_me
  key_pair_name = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-key-pairs.rb KEY_PAIR_NAME REGION'
    puts 'Example: ruby ec2-ruby-example-key-pairs.rb my-key-pair us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    key_pair_name = 'my-key-pair'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    key_pair_name = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts 'Displaying existing key pair names before creating this key pair...'
  describe_key_pairs(ec2_client)

  puts '-' * 10
  puts 'Creating key pair...'
  unless key_pair_created?(ec2_client, key_pair_name)
    puts 'Stopping program.'
    exit 1
  end

  puts '-' * 10
  puts 'Displaying existing key pair names after creating this key pair...'
  describe_key_pairs(ec2_client)

  puts '-' * 10
  puts 'Deleting key pair...'
  unless key_pair_deleted?(ec2_client, key_pair_name)
    puts 'Stopping program. You must delete the key pair yourself.'
    exit 1
  end
  puts 'Key pair deleted.'

  puts '-' * 10
  puts 'Now that the key pair is deleted, ' \
    'also deleting the related private key pair file...'
  filename = File.join(Dir.home, "#{key_pair_name}.pem")
  File.delete(filename)
  if File.exist?(filename)
    puts "Could not delete file at '#{filename}'. You must delete it yourself."
  else
    puts 'File deleted.'
  end

  puts '-' * 10
  puts 'Displaying existing key pair names after deleting this key pair...'
  describe_key_pairs(ec2_client)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[CreateKeyPair](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateKeyPair)」を参照してください。

### `CreateRouteTable`
<a name="ec2_CreateRouteTable_ruby_3_topic"></a>

次のコード例は、`CreateRouteTable` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# Prerequisites:
#
# - A VPC in Amazon VPC.
# - A subnet in that VPC.
# - A gateway attached to that subnet.
#
# @param ec2_resource [Aws::EC2::Resource] An initialized
#   Amazon Elastic Compute Cloud (Amazon EC2) resource object.
# @param vpc_id [String] The ID of the VPC for the route table.
# @param subnet_id [String] The ID of the subnet for the route table.
# @param gateway_id [String] The ID of the gateway for the route.
# @param destination_cidr_block [String] The destination CIDR block
#   for the route.
# @param tag_key [String] The key portion of the tag for the route table.
# @param tag_value [String] The value portion of the tag for the route table.
# @return [Boolean] true if the route table was created and associated;
#   otherwise, false.
# @example
#   exit 1 unless route_table_created_and_associated?(
#     Aws::EC2::Resource.new(region: 'us-west-2'),
#     'vpc-0b6f769731EXAMPLE',
#     'subnet-03d9303b57EXAMPLE',
#     'igw-06ca90c011EXAMPLE',
#     '0.0.0.0/0',
#     'my-key',
#     'my-value'
#   )
def route_table_created_and_associated?(
  ec2_resource,
  vpc_id,
  subnet_id,
  gateway_id,
  destination_cidr_block,
  tag_key,
  tag_value
)
  route_table = ec2_resource.create_route_table(vpc_id: vpc_id)
  puts "Created route table with ID '#{route_table.id}'."
  route_table.create_tags(
    tags: [
      {
        key: tag_key,
        value: tag_value
      }
    ]
  )
  puts 'Added tags to route table.'
  route_table.create_route(
    destination_cidr_block: destination_cidr_block,
    gateway_id: gateway_id
  )
  puts 'Created route with destination CIDR block ' \
    "'#{destination_cidr_block}' and associated with gateway " \
    "with ID '#{gateway_id}'."
  route_table.associate_with_subnet(subnet_id: subnet_id)
  puts "Associated route table with subnet with ID '#{subnet_id}'."
  true
rescue StandardError => e
  puts "Error creating or associating route table: #{e.message}"
  puts 'If the route table was created but not associated, you should ' \
    'clean up by deleting the route table.'
  false
end

# Example usage:
def run_me
  vpc_id = ''
  subnet_id = ''
  gateway_id = ''
  destination_cidr_block = ''
  tag_key = ''
  tag_value = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage: ruby ec2-ruby-example-create-route-table.rb ' \
      'VPC_ID SUBNET_ID GATEWAY_ID DESTINATION_CIDR_BLOCK ' \
      'TAG_KEY TAG_VALUE REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-create-route-table.rb ' \
      'vpc-0b6f769731EXAMPLE subnet-03d9303b57EXAMPLE igw-06ca90c011EXAMPLE ' \
      "'0.0.0.0/0' my-key my-value us-west-2"
    exit 1
  # If no values are specified at the command prompt, use these default values.
  elsif ARGV.count.zero?
    vpc_id = 'vpc-0b6f769731EXAMPLE'
    subnet_id = 'subnet-03d9303b57EXAMPLE'
    gateway_id = 'igw-06ca90c011EXAMPLE'
    destination_cidr_block = '0.0.0.0/0'
    tag_key = 'my-key'
    tag_value = 'my-value'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    vpc_id = ARGV[0]
    subnet_id = ARGV[1]
    gateway_id = ARGV[2]
    destination_cidr_block = ARGV[3]
    tag_key = ARGV[4]
    tag_value = ARGV[5]
    region = ARGV[6]
  end

  ec2_resource = Aws::EC2::Resource.new(region: region)

  if route_table_created_and_associated?(
    ec2_resource,
    vpc_id,
    subnet_id,
    gateway_id,
    destination_cidr_block,
    tag_key,
    tag_value
  )
    puts 'Route table created and associated.'
  else
    puts 'Route table not created or not associated.'
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[CreateRouteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateRouteTable)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_ruby_3_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
# This code example does the following:
# 1. Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group.
# 2. Adds inbound rules to the security group.
# 3. Displays information about available security groups.
# 4. Deletes the security group.

require 'aws-sdk-ec2'

# Creates an Amazon Elastic Compute Cloud (Amazon EC2) security group.
#
# Prerequisites:
#
# - A VPC in Amazon Virtual Private Cloud (Amazon VPC).
#
# @param ec2_client [Aws::EC2::Client] An initialized
#   Amazon EC2 client.
# @param group_name [String] A name for the security group.
# @param description [String] A description for the security group.
# @param vpc_id [String] The ID of the VPC for the security group.
# @return [String] The ID of security group that was created.
# @example
#   puts create_security_group(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'my-security-group',
#     'This is my security group.',
#     'vpc-6713dfEX'
#   )
def create_security_group(ec2_client, group_name, description, vpc_id)
  security_group = ec2_client.create_security_group(
    group_name: group_name,
    description: description,
    vpc_id: vpc_id
  )
  puts "Created security group '#{group_name}' with ID " \
    "'#{security_group.group_id}' in VPC with ID '#{vpc_id}'."
  security_group.group_id
rescue StandardError => e
  puts "Error creating security group: #{e.message}"
  'Error'
end

# Adds an inbound rule to an Amazon Elastic Compute Cloud (Amazon EC2)
# security group.
#
# Prerequisites:
#
# - The security group.
#
# @param ec2_client [Aws::EC2::Client] An initialized Amazon EC2 client.
# @param security_group_id [String] The ID of the security group.
# @param ip_protocol [String] The network protocol for the inbound rule.
# @param from_port [String] The originating port for the inbound rule.
# @param to_port [String] The destination port for the inbound rule.
# @param cidr_ip_range [String] The CIDR IP range for the inbound rule.
# @return
# @example
#   exit 1 unless security_group_ingress_authorized?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'sg-030a858e078f1b9EX',
#     'tcp',
#     '80',
#     '80',
#     '0.0.0.0/0'
#   )
def security_group_ingress_authorized?(
  ec2_client, security_group_id, ip_protocol, from_port, to_port, cidr_ip_range
)
  ec2_client.authorize_security_group_ingress(
    group_id: security_group_id,
    ip_permissions: [
      {
        ip_protocol: ip_protocol,
        from_port: from_port,
        to_port: to_port,
        ip_ranges: [
          {
            cidr_ip: cidr_ip_range
          }
        ]
      }
    ]
  )
  puts "Added inbound rule to security group '#{security_group_id}' for protocol " \
    "'#{ip_protocol}' from port '#{from_port}' to port '#{to_port}' " \
    "with CIDR IP range '#{cidr_ip_range}'."
  true
rescue StandardError => e
  puts "Error adding inbound rule to security group: #{e.message}"
  false
end

# Refactored method to simplify complexity for describing security group permissions
def format_port_information(perm)
  from_port_str = perm.from_port == '-1' || perm.from_port == -1 ? 'All' : perm.from_port.to_s
  to_port_str = perm.to_port == '-1' || perm.to_port == -1 ? 'All' : perm.to_port.to_s
  { from_port: from_port_str, to_port: to_port_str }
end

# Displays information about a security group's IP permissions set in
# Amazon Elastic Compute Cloud (Amazon EC2).
def describe_security_group_permissions(perm)
  ports = format_port_information(perm)

  print "  Protocol: #{perm.ip_protocol == '-1' ? 'All' : perm.ip_protocol}"
  print ", From: #{ports[:from_port]}, To: #{ports[:to_port]}"

  print ", CIDR IPv6: #{perm.ipv_6_ranges[0].cidr_ipv_6}" if perm.key?(:ipv_6_ranges) && perm.ipv_6_ranges.count.positive?

  print ", CIDR IPv4: #{perm.ip_ranges[0].cidr_ip}" if perm.key?(:ip_ranges) && perm.ip_ranges.count.positive?
  print "\n"
end

# Displays information about available security groups in
# Amazon Elastic Compute Cloud (Amazon EC2).
def describe_security_groups(ec2_client)
  response = ec2_client.describe_security_groups

  if response.security_groups.count.positive?
    response.security_groups.each do |sg|
      display_group_details(sg)
    end
  else
    puts 'No security groups found.'
  end
rescue StandardError => e
  puts "Error getting information about security groups: #{e.message}"
end

# Helper method to display the details of security groups
def display_group_details(sg)
  puts '-' * (sg.group_name.length + 13)
  puts "Name:        #{sg.group_name}"
  puts "Description: #{sg.description}"
  puts "Group ID:    #{sg.group_id}"
  puts "Owner ID:    #{sg.owner_id}"
  puts "VPC ID:      #{sg.vpc_id}"

  display_group_tags(sg.tags) if sg.tags.count.positive?
  display_group_permissions(sg)
end

def display_group_tags(tags)
  puts 'Tags:'
  tags.each do |tag|
    puts "  Key: #{tag.key}, Value: #{tag.value}"
  end
end

def display_group_permissions(sg)
  if sg.ip_permissions.count.positive?
    puts 'Inbound rules:'
    sg.ip_permissions.each do |p|
      describe_security_group_permissions(p)
    end
  end

  return if sg.ip_permissions_egress.empty?

  puts 'Outbound rules:'
  sg.ip_permissions_egress.each do |p|
    describe_security_group_permissions(p)
  end
end

# Deletes an Amazon Elastic Compute Cloud (Amazon EC2)
# security group.
def security_group_deleted?(ec2_client, security_group_id)
  ec2_client.delete_security_group(group_id: security_group_id)
  puts "Deleted security group '#{security_group_id}'."
  true
rescue StandardError => e
  puts "Error deleting security group: #{e.message}"
  false
end

# Example usage with refactored run_me to reduce complexity
def run_me
  group_name, description, vpc_id, ip_protocol_http, from_port_http, to_port_http, \
  cidr_ip_range_http, ip_protocol_ssh, from_port_ssh, to_port_ssh, \
  cidr_ip_range_ssh, region = process_arguments
  ec2_client = Aws::EC2::Client.new(region: region)

  security_group_id = attempt_create_security_group(ec2_client, group_name, description, vpc_id)
  security_group_exists = security_group_id != 'Error'

  if security_group_exists
    add_inbound_rules(ec2_client, security_group_id, ip_protocol_http, from_port_http, to_port_http, cidr_ip_range_http)
    add_inbound_rules(ec2_client, security_group_id, ip_protocol_ssh, from_port_ssh, to_port_ssh, cidr_ip_range_ssh)
  end

  describe_security_groups(ec2_client)
  attempt_delete_security_group(ec2_client, security_group_id) if security_group_exists
end

def process_arguments
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    display_help
    exit 1
  elsif ARGV.count.zero?
    default_values
  else
    ARGV
  end
end

def attempt_create_security_group(ec2_client, group_name, description, vpc_id)
  puts 'Attempting to create security group...'
  security_group_id = create_security_group(ec2_client, group_name, description, vpc_id)
  puts 'Could not create security group. Skipping this step.' if security_group_id == 'Error'
  security_group_id
end

def add_inbound_rules(ec2_client, security_group_id, ip_protocol, from_port, to_port, cidr_ip_range)
  puts 'Attempting to add inbound rules to security group...'
  return if security_group_ingress_authorized?(ec2_client, security_group_id, ip_protocol, from_port, to_port,
                                               cidr_ip_range)

  puts 'Could not add inbound rule to security group. Skipping this step.'
end

def attempt_delete_security_group(ec2_client, security_group_id)
  puts "\nAttempting to delete security group..."
  return if security_group_deleted?(ec2_client, security_group_id)

  puts 'Could not delete security group. You must delete it yourself.'
end

def display_help
  puts 'Usage:   ruby ec2-ruby-example-security-group.rb ' \
    'GROUP_NAME DESCRIPTION VPC_ID IP_PROTOCOL_1 FROM_PORT_1 TO_PORT_1 ' \
    'CIDR_IP_RANGE_1 IP_PROTOCOL_2 FROM_PORT_2 TO_PORT_2 ' \
    'CIDR_IP_RANGE_2 REGION'
  puts 'Example: ruby ec2-ruby-example-security-group.rb ' \
    "my-security-group 'This is my security group.' vpc-6713dfEX " \
    "tcp 80 80 '0.0.0.0/0' tcp 22 22 '0.0.0.0/0' us-west-2"
end

def default_values
  [
    'my-security-group', 'This is my security group.', 'vpc-6713dfEX', 'tcp', '80', '80',
    '0.0.0.0/0', 'tcp', '22', '22', '0.0.0.0/0', 'us-west-2'
  ]
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[CreateSecurityGroup](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateSecurityGroup)」を参照してください。

### `CreateSubnet`
<a name="ec2_CreateSubnet_ruby_3_topic"></a>

次のコード例は、`CreateSubnet` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# Creates a subnet within a virtual private cloud (VPC) in
# Amazon Virtual Private Cloud (Amazon VPC) and then tags
# the subnet.
#
# Prerequisites:
#
# - A VPC in Amazon VPC.
#
# @param ec2_resource [Aws::EC2::Resource] An initialized
#   Amazon Elastic Compute Cloud (Amazon EC2) resource object.
# @param vpc_id [String] The ID of the VPC for the subnet.
# @param cidr_block [String] The IPv4 CIDR block for the subnet.
# @param availability_zone [String] The ID of the Availability Zone
#   for the subnet.
# @param tag_key [String] The key portion of the tag for the subnet.
# @param tag_vlue [String] The value portion of the tag for the subnet.
# @return [Boolean] true if the subnet was created and tagged;
#   otherwise, false.
# @example
#   exit 1 unless subnet_created_and_tagged?(
#     Aws::EC2::Resource.new(region: 'us-west-2'),
#     'vpc-6713dfEX',
#     '10.0.0.0/24',
#     'us-west-2a',
#     'my-key',
#     'my-value'
#   )
def subnet_created_and_tagged?(
  ec2_resource,
  vpc_id,
  cidr_block,
  availability_zone,
  tag_key,
  tag_value
)
  subnet = ec2_resource.create_subnet(
    vpc_id: vpc_id,
    cidr_block: cidr_block,
    availability_zone: availability_zone
  )
  subnet.create_tags(
    tags: [
      {
        key: tag_key,
        value: tag_value
      }
    ]
  )
  puts "Subnet created with ID '#{subnet.id}' in VPC with ID '#{vpc_id}' " \
    "and CIDR block '#{cidr_block}' in availability zone " \
    "'#{availability_zone}' and tagged with key '#{tag_key}' and " \
    "value '#{tag_value}'."
  true
rescue StandardError => e
  puts "Error creating or tagging subnet: #{e.message}"
  false
end

# Example usage:
def run_me
  vpc_id = ''
  cidr_block = ''
  availability_zone = ''
  tag_key = ''
  tag_value = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-create-subnet.rb ' \
      'VPC_ID CIDR_BLOCK AVAILABILITY_ZONE TAG_KEY TAG_VALUE REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-create-subnet.rb ' \
      'vpc-6713dfEX 10.0.0.0/24 us-west-2a my-key my-value us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  elsif ARGV.count.zero?
    vpc_id = 'vpc-6713dfEX'
    cidr_block = '10.0.0.0/24'
    availability_zone = 'us-west-2a'
    tag_key = 'my-key'
    tag_value = 'my-value'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    vpc_id = ARGV[0]
    cidr_block = ARGV[1]
    availability_zone = ARGV[2]
    tag_key = ARGV[3]
    tag_value = ARGV[4]
    region = ARGV[5]
  end

  ec2_resource = Aws::EC2::Resource.new(region: region)

  if subnet_created_and_tagged?(
    ec2_resource,
    vpc_id,
    cidr_block,
    availability_zone,
    tag_key,
    tag_value
  )
    puts 'Subnet created and tagged.'
  else
    puts 'Subnet not created or not tagged.'
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[CreateSubnet](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateSubnet)」を参照してください。

### `CreateVpc`
<a name="ec2_CreateVpc_ruby_3_topic"></a>

次のコード例は、`CreateVpc` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# Creates a virtual private cloud (VPC) in
# Amazon Virtual Private Cloud (Amazon VPC) and then tags
# the VPC.
#
# @param ec2_resource [Aws::EC2::Resource] An initialized
#   Amazon Elastic Compute Cloud (Amazon EC2) resource object.
# @param cidr_block [String] The IPv4 CIDR block for the subnet.
# @param tag_key [String] The key portion of the tag for the VPC.
# @param tag_value [String] The value portion of the tag for the VPC.
# @return [Boolean] true if the VPC was created and tagged;
#   otherwise, false.
# @example
#   exit 1 unless vpc_created_and_tagged?(
#     Aws::EC2::Resource.new(region: 'us-west-2'),
#     '10.0.0.0/24',
#     'my-key',
#     'my-value'
#   )
def vpc_created_and_tagged?(
  ec2_resource,
  cidr_block,
  tag_key,
  tag_value
)
  vpc = ec2_resource.create_vpc(cidr_block: cidr_block)

  # Create a public DNS by enabling DNS support and DNS hostnames.
  vpc.modify_attribute(enable_dns_support: { value: true })
  vpc.modify_attribute(enable_dns_hostnames: { value: true })

  vpc.create_tags(tags: [{ key: tag_key, value: tag_value }])

  puts "Created VPC with ID '#{vpc.id}' and tagged with key " \
    "'#{tag_key}' and value '#{tag_value}'."
  true
rescue StandardError => e
  puts e.message
  false
end

# Example usage:
def run_me
  cidr_block = ''
  tag_key = ''
  tag_value = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-create-vpc.rb ' \
      'CIDR_BLOCK TAG_KEY TAG_VALUE REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-create-vpc.rb ' \
      '10.0.0.0/24 my-key my-value us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  elsif ARGV.count.zero?
    cidr_block = '10.0.0.0/24'
    tag_key = 'my-key'
    tag_value = 'my-value'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    cidr_block = ARGV[0]
    tag_key = ARGV[1]
    tag_value = ARGV[2]
    region = ARGV[3]
  end

  ec2_resource = Aws::EC2::Resource.new(region: region)

  if vpc_created_and_tagged?(
    ec2_resource,
    cidr_block,
    tag_key,
    tag_value
  )
    puts 'VPC created and tagged.'
  else
    puts 'VPC not created or not tagged.'
  end
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[CreateVpc](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/CreateVpc)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_ruby_3_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# @param ec2_resource [Aws::EC2::Resource] An initialized EC2 resource object.
# @example
#   list_instance_ids_states(Aws::EC2::Resource.new(region: 'us-west-2'))
def list_instance_ids_states(ec2_resource)
  response = ec2_resource.instances
  if response.count.zero?
    puts 'No instances found.'
  else
    puts 'Instances -- ID, state:'
    response.each do |instance|
      puts "#{instance.id}, #{instance.state.name}"
    end
  end
rescue StandardError => e
  puts "Error getting information about instances: #{e.message}"
end

# Example usage:
def run_me
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-get-all-instance-info.rb REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-get-all-instance-info.rb us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    region = ARGV[0]
  end
  ec2_resource = Aws::EC2::Resource.new(region: region)
  list_instance_ids_states(ec2_resource)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[DescribeInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/DescribeInstances)」を参照してください。

### `DescribeRegions`
<a name="ec2_DescribeRegions_ruby_3_topic"></a>

次のコード例は、`DescribeRegions` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @example
#   list_regions_endpoints(Aws::EC2::Client.new(region: 'us-west-2'))
def list_regions_endpoints(ec2_client)
  result = ec2_client.describe_regions
  # Enable pretty printing.
  max_region_string_length = 16
  max_endpoint_string_length = 33
  # Print header.
  print 'Region'
  print ' ' * (max_region_string_length - 'Region'.length)
  print "  Endpoint\n"
  print '-' * max_region_string_length
  print '  '
  print '-' * max_endpoint_string_length
  print "\n"
  # Print Regions and their endpoints.
  result.regions.each do |region|
    print region.region_name
    print ' ' * (max_region_string_length - region.region_name.length)
    print '  '
    print region.endpoint
    print "\n"
  end
end

# Displays a list of Amazon Elastic Compute Cloud (Amazon EC2)
# Availability Zones available to you depending on the AWS Region
# of the Amazon EC2 client.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @example
#   list_availability_zones(Aws::EC2::Client.new(region: 'us-west-2'))
def list_availability_zones(ec2_client)
  result = ec2_client.describe_availability_zones
  # Enable pretty printing.
  max_region_string_length = 16
  max_zone_string_length = 18
  max_state_string_length = 9
  # Print header.
  print 'Region'
  print ' ' * (max_region_string_length - 'Region'.length)
  print '  Zone'
  print ' ' * (max_zone_string_length - 'Zone'.length)
  print "  State\n"
  print '-' * max_region_string_length
  print '  '
  print '-' * max_zone_string_length
  print '  '
  print '-' * max_state_string_length
  print "\n"
  # Print Regions, Availability Zones, and their states.
  result.availability_zones.each do |zone|
    print zone.region_name
    print ' ' * (max_region_string_length - zone.region_name.length)
    print '  '
    print zone.zone_name
    print ' ' * (max_zone_string_length - zone.zone_name.length)
    print '  '
    print zone.state
    # Print any messages for this Availability Zone.
    if zone.messages.count.positive?
      print "\n"
      puts '  Messages for this zone:'
      zone.messages.each do |message|
        print "    #{message.message}\n"
      end
    end
    print "\n"
  end
end

# Example usage:
def run_me
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-regions-availability-zones.rb REGION'
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-regions-availability-zones.rb us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    region = ARGV[0]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts 'AWS Regions for Amazon EC2 that are available to you:'
  list_regions_endpoints(ec2_client)
  puts "\n\nAmazon EC2 Availability Zones that are available to you for AWS Region '#{region}':"
  list_availability_zones(ec2_client)
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[DescribeRegions](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/DescribeRegions)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_ruby_3_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
# Releases an Elastic IP address from an
# Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Prerequisites:
#
# - An Amazon EC2 instance with an associated Elastic IP address.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param allocation_id [String] The ID of the allocation corresponding to
#   the Elastic IP address.
# @return [Boolean] true if the Elastic IP address was released;
#   otherwise, false.
# @example
#   exit 1 unless elastic_ip_address_released?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'eipalloc-04452e528a66279EX'
#   )
def elastic_ip_address_released?(ec2_client, allocation_id)
  ec2_client.release_address(allocation_id: allocation_id)
  true
rescue StandardError => e
  puts("Error releasing Elastic IP address: #{e.message}")
  false
end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[ReleaseAddress](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/ReleaseAddress)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_ruby_3_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# Attempts to start an Amazon Elastic Compute Cloud (Amazon EC2) instance.
#
# Prerequisites:
#
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param instance_id [String] The ID of the instance.
# @return [Boolean] true if the instance was started; otherwise, false.
# @example
#   exit 1 unless instance_started?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'i-123abc'
#   )
def instance_started?(ec2_client, instance_id)
  response = ec2_client.describe_instance_status(instance_ids: [instance_id])

  if response.instance_statuses.count.positive?
    state = response.instance_statuses[0].instance_state.name
    case state
    when 'pending'
      puts 'Error starting instance: the instance is pending. Try again later.'
      return false
    when 'running'
      puts 'The instance is already running.'
      return true
    when 'terminated'
      puts 'Error starting instance: ' \
        'the instance is terminated, so you cannot start it.'
      return false
    end
  end

  ec2_client.start_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_running, instance_ids: [instance_id])
  puts 'Instance started.'
  true
rescue StandardError => e
  puts "Error starting instance: #{e.message}"
  false
end

# Example usage:
def run_me
  instance_id = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-start-instance-i-123abc.rb ' \
      'INSTANCE_ID REGION '
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-start-instance-i-123abc.rb ' \
      'i-123abc us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    instance_id = 'i-123abc'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    instance_id = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts "Attempting to start instance '#{instance_id}' " \
    '(this might take a few minutes)...'
  return if instance_started?(ec2_client, instance_id)

  puts 'Could not start instance.'
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[StartInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/StartInstances)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_ruby_3_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# Prerequisites:
#
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param instance_id [String] The ID of the instance.
# @return [Boolean] true if the instance was stopped; otherwise, false.
# @example
#   exit 1 unless instance_stopped?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'i-123abc'
#   )
def instance_stopped?(ec2_client, instance_id)
  response = ec2_client.describe_instance_status(instance_ids: [instance_id])

  if response.instance_statuses.count.positive?
    state = response.instance_statuses[0].instance_state.name
    case state
    when 'stopping'
      puts 'The instance is already stopping.'
      return true
    when 'stopped'
      puts 'The instance is already stopped.'
      return true
    when 'terminated'
      puts 'Error stopping instance: ' \
        'the instance is terminated, so you cannot stop it.'
      return false
    end
  end

  ec2_client.stop_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_stopped, instance_ids: [instance_id])
  puts 'Instance stopped.'
  true
rescue StandardError => e
  puts "Error stopping instance: #{e.message}"
  false
end

# Example usage:
def run_me
  instance_id = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-stop-instance-i-123abc.rb ' \
      'INSTANCE_ID REGION '
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-start-instance-i-123abc.rb ' \
      'i-123abc us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    instance_id = 'i-123abc'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    instance_id = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts "Attempting to stop instance '#{instance_id}' " \
    '(this might take a few minutes)...'
  return if instance_stopped?(ec2_client, instance_id)

  puts 'Could not stop instance.'
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[StopInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/StopInstances)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_ruby_3_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ec2'

# Prerequisites:
#
# - The Amazon EC2 instance.
#
# @param ec2_client [Aws::EC2::Client] An initialized EC2 client.
# @param instance_id [String] The ID of the instance.
# @return [Boolean] true if the instance was terminated; otherwise, false.
# @example
#   exit 1 unless instance_terminated?(
#     Aws::EC2::Client.new(region: 'us-west-2'),
#     'i-123abc'
#   )
def instance_terminated?(ec2_client, instance_id)
  response = ec2_client.describe_instance_status(instance_ids: [instance_id])

  if response.instance_statuses.count.positive? &&
     response.instance_statuses[0].instance_state.name == 'terminated'

    puts 'The instance is already terminated.'
    return true
  end

  ec2_client.terminate_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_terminated, instance_ids: [instance_id])
  puts 'Instance terminated.'
  true
rescue StandardError => e
  puts "Error terminating instance: #{e.message}"
  false
end

# Example usage:
def run_me
  instance_id = ''
  region = ''
  # Print usage information and then stop.
  if ARGV[0] == '--help' || ARGV[0] == '-h'
    puts 'Usage:   ruby ec2-ruby-example-terminate-instance-i-123abc.rb ' \
      'INSTANCE_ID REGION '
    # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
    puts 'Example: ruby ec2-ruby-example-terminate-instance-i-123abc.rb ' \
      'i-123abc us-west-2'
    exit 1
  # If no values are specified at the command prompt, use these default values.
  # Replace us-west-2 with the AWS Region you're using for Amazon EC2.
  elsif ARGV.count.zero?
    instance_id = 'i-123abc'
    region = 'us-west-2'
  # Otherwise, use the values as specified at the command prompt.
  else
    instance_id = ARGV[0]
    region = ARGV[1]
  end

  ec2_client = Aws::EC2::Client.new(region: region)

  puts "Attempting to terminate instance '#{instance_id}' " \
    '(this might take a few minutes)...'
  return if instance_terminated?(ec2_client, instance_id)

  puts 'Could not terminate instance.'
end

run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[TerminateInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/ec2-2016-11-15/TerminateInstances)」を参照してください。

# SDK for Ruby を使用する Elastic Beanstalk の例
<a name="ruby_3_elastic-beanstalk_code_examples"></a>

次のコード例は、Elastic Beanstalk AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeApplications`
<a name="elastic-beanstalk_DescribeApplications_ruby_3_topic"></a>

次のコード例は、`DescribeApplications` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/elasticbeanstalk#code-examples)での設定と実行の方法を確認してください。

```
# Class to manage Elastic Beanstalk applications
class ElasticBeanstalkManager
  def initialize(eb_client, logger: Logger.new($stdout))
    @eb_client = eb_client
    @logger = logger
  end

  # Lists applications and their environments
  def list_applications
    @eb_client.describe_applications.applications.each do |application|
      log_application_details(application)
      list_environments(application.application_name)
    end
  rescue Aws::ElasticBeanstalk::Errors::ServiceError => e
    @logger.error("Elastic Beanstalk Service Error: #{e.message}")
  end

  private

  # Logs application details
  def log_application_details(application)
    @logger.info("Name:        #{application.application_name}")
    @logger.info("Description: #{application.description}")
  end

  # Lists and logs details of environments for a given application
  def list_environments(application_name)
    @eb_client.describe_environments(application_name: application_name).environments.each do |env|
      @logger.info("  Environment:  #{env.environment_name}")
      @logger.info("    URL:        #{env.cname}")
      @logger.info("    Health:     #{env.health}")
    end
  rescue Aws::ElasticBeanstalk::Errors::ServiceError => e
    @logger.error("Error listing environments for application #{application_name}: #{e.message}")
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[DescribeApplications](https://docs.aws.amazon.com/goto/SdkForRubyV3/elastic-beanstalk-2010-12-01/DescribeApplications)」を参照してください。**

### `ListAvailableSolutionStacks`
<a name="elastic-beanstalk_ListAvailableSolutionStacks_ruby_3_topic"></a>

次のコード例は、`ListAvailableSolutionStacks` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/elasticbeanstalk#code-examples)での設定と実行の方法を確認してください。

```
# Manages listing of AWS Elastic Beanstalk solution stacks
# @param [Aws::ElasticBeanstalk::Client] eb_client
# @param [String] filter - Returns subset of results based on match
# @param [Logger] logger
class StackLister
  # Initialize with AWS Elastic Beanstalk client
  def initialize(eb_client, filter, logger: Logger.new($stdout))
    @eb_client = eb_client
    @filter = filter.downcase
    @logger = logger
  end

  # Lists and logs Elastic Beanstalk solution stacks
  def list_stacks
    stacks = @eb_client.list_available_solution_stacks.solution_stacks
    orig_length = stacks.length
    filtered_length = 0

    stacks.each do |stack|
      if @filter.empty? || stack.downcase.include?(@filter)
        @logger.info(stack)
        filtered_length += 1
      end
    end

    log_summary(filtered_length, orig_length)
  rescue Aws::Errors::ServiceError => e
    @logger.error("Error listing solution stacks: #{e.message}")
  end

  private

  # Logs summary of listed stacks
  def log_summary(filtered_length, orig_length)
    if @filter.empty?
      @logger.info("Showed #{orig_length} stack(s)")
    else
      @logger.info("Showed #{filtered_length} stack(s) of #{orig_length}")
    end
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListAvailableSolutionStacks](https://docs.aws.amazon.com/goto/SdkForRubyV3/elastic-beanstalk-2010-12-01/ListAvailableSolutionStacks)」を参照してください。**

### `UpdateApplication`
<a name="elastic-beanstalk_UpdateApplication_ruby_3_topic"></a>

次のコード例は、`UpdateApplication` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/elasticbeanstalk#code-examples)での設定と実行の方法を確認してください。

```
# Manages deployment of Rails applications to AWS Elastic Beanstalk
class RailsAppDeployer
  def initialize(eb_client, s3_client, app_name, logger: Logger.new($stdout))
    @eb_client = eb_client
    @s3_client = s3_client
    @app_name = app_name
    @logger = logger
  end

  # Deploys the latest application version to Elastic Beanstalk
  def deploy
    create_storage_location
    zip_file_name = create_zip_file
    upload_zip_to_s3(zip_file_name)
    create_and_deploy_new_application_version(zip_file_name)
  end

  private

  # Creates a new S3 storage location for the application
  def create_storage_location
    resp = @eb_client.create_storage_location
    @logger.info("Created storage location in bucket #{resp.s3_bucket}")
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to create storage location: #{e.message}")
  end

  # Creates a ZIP file of the application using git
  def create_zip_file
    zip_file_basename = SecureRandom.urlsafe_base64
    zip_file_name = "#{zip_file_basename}.zip"
    `git archive --format=zip -o #{zip_file_name} HEAD`
    zip_file_name
  end

  # Uploads the ZIP file to the S3 bucket
  def upload_zip_to_s3(zip_file_name)
    zip_contents = File.read(zip_file_name)
    key = "#{@app_name}/#{zip_file_name}"
    @s3_client.put_object(body: zip_contents, bucket: fetch_bucket_name, key: key)
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to upload ZIP file to S3: #{e.message}")
  end

  # Fetches the S3 bucket name from Elastic Beanstalk application versions
  def fetch_bucket_name
    app_versions = @eb_client.describe_application_versions(application_name: @app_name)
    av = app_versions.application_versions.first
    av.source_bundle.s3_bucket
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to fetch bucket name: #{e.message}")
    raise
  end

  # Creates a new application version and deploys it
  def create_and_deploy_new_application_version(zip_file_name)
    version_label = File.basename(zip_file_name, '.zip')
    @eb_client.create_application_version(
      process: false,
      application_name: @app_name,
      version_label: version_label,
      source_bundle: {
        s3_bucket: fetch_bucket_name,
        s3_key: "#{@app_name}/#{zip_file_name}"
      },
      description: "Updated #{Time.now.strftime('%d/%m/%Y')}"
    )
    update_environment(version_label)
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to create or deploy application version: #{e.message}")
  end

  # Updates the environment to the new application version
  def update_environment(version_label)
    env_name = fetch_environment_name
    @eb_client.update_environment(
      environment_name: env_name,
      version_label: version_label
    )
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to update environment: #{e.message}")
  end

  # Fetches the environment name of the application
  def fetch_environment_name
    envs = @eb_client.describe_environments(application_name: @app_name)
    envs.environments.first.environment_name
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to fetch environment name: #{e.message}")
    raise
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[UpdateApplication](https://docs.aws.amazon.com/goto/SdkForRubyV3/elastic-beanstalk-2010-12-01/UpdateApplication)」を参照してください。**

# SDK for Ruby を使用した EventBridge の例
<a name="ruby_3_eventbridge_code_examples"></a>

次のコード例は、EventBridge AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### ルールを作成してトリガーする
<a name="eventbridge_Scenario_createAndTriggerARule_ruby_3_topic"></a>

次のコード例では、Amazon EventBridge でルールを作成し、トリガーする方法を示します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/eventbridge#code-examples)での設定と実行の方法を確認してください。
関数を正しい順序で呼び出します。  

```
require 'aws-sdk-sns'
require 'aws-sdk-iam'
require 'aws-sdk-cloudwatchevents'
require 'aws-sdk-ec2'
require 'aws-sdk-cloudwatch'
require 'aws-sdk-cloudwatchlogs'
require 'securerandom'
```
指定された Amazon Simple Notification Service (Amazon SNS) トピックがこの関数に提供されているトピックの中に存在するかどうかをチェックします。  

```
# Checks whether the specified Amazon SNS
# topic exists among those provided to this function.
# This is a helper function that is called by the topic_exists? function.
#
# @param topics [Array] An array of Aws::SNS::Types::Topic objects.
# @param topic_arn [String] The ARN of the topic to find.
# @return [Boolean] true if the topic ARN was found; otherwise, false.
# @example
#   sns_client = Aws::SNS::Client.new(region: 'us-east-1')
#   response = sns_client.list_topics
#   if topic_found?(
#     response.topics,
#     'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic'
#   )
#     puts 'Topic found.'
#   end
def topic_found?(topics, topic_arn)
  topics.each do |topic|
    return true if topic.topic_arn == topic_arn
  end
  false
end
```
Amazon SNS で発信者が利用できるトピックの中に指定されたトピックが存在するかどうかをチェックします。  

```
# Checks whether the specified topic exists among those available to the
# caller in Amazon SNS.
#
# @param sns_client [Aws::SNS::Client] An initialized Amazon SNS client.
# @param topic_arn [String] The ARN of the topic to find.
# @return [Boolean] true if the topic ARN was found; otherwise, false.
# @example
#   exit 1 unless topic_exists?(
#     Aws::SNS::Client.new(region: 'us-east-1'),
#     'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic'
#   )
def topic_exists?(sns_client, topic_arn)
  puts "Searching for topic with ARN '#{topic_arn}'..."
  response = sns_client.list_topics
  if response.topics.count.positive?
    if topic_found?(response.topics, topic_arn)
      puts 'Topic found.'
      return true
    end
    while response.next_page?
      response = response.next_page
      next unless response.topics.count.positive?

      if topic_found?(response.topics, topic_arn)
        puts 'Topic found.'
        return true
      end
    end
  end
  puts 'Topic not found.'
  false
rescue StandardError => e
  puts "Topic not found: #{e.message}"
  false
end
```
Amazon SNS でトピックを作成し、E メールアドレスをサブスクライブして、そのトピックに対する通知を受信します。  

```
# Creates a topic in Amazon SNS
# and then subscribes an email address to receive notifications to that topic.
#
# @param sns_client [Aws::SNS::Client] An initialized Amazon SNS client.
# @param topic_name [String] The name of the topic to create.
# @param email_address [String] The email address of the recipient to notify.
# @return [String] The ARN of the topic that was created.
# @example
#   puts create_topic(
#     Aws::SNS::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-topic',
#     'mary@example.com'
#   )
def create_topic(sns_client, topic_name, email_address)
  puts "Creating the topic named '#{topic_name}'..."
  topic_response = sns_client.create_topic(name: topic_name)
  puts "Topic created with ARN '#{topic_response.topic_arn}'."
  subscription_response = sns_client.subscribe(
    topic_arn: topic_response.topic_arn,
    protocol: 'email',
    endpoint: email_address,
    return_subscription_arn: true
  )
  puts 'Subscription created with ARN ' \
    "'#{subscription_response.subscription_arn}'. Have the owner of the " \
    "email address '#{email_address}' check their inbox in a few minutes " \
    'and confirm the subscription to start receiving notification emails.'
  topic_response.topic_arn
rescue StandardError => e
  puts "Error creating or subscribing to topic: #{e.message}"
  'Error'
end
```
指定された AWS Identity and Access Management (IAM) ロールがこの関数に提供されるロールの中に存在するかどうかを確認します。  

```
# Checks whether the specified AWS Identity and Access Management (IAM)
# role exists among those provided to this function.
# This is a helper function that is called by the role_exists? function.
#
# @param roles [Array] An array of Aws::IAM::Role objects.
# @param role_arn [String] The ARN of the role to find.
# @return [Boolean] true if the role ARN was found; otherwise, false.
# @example
#   iam_client = Aws::IAM::Client.new(region: 'us-east-1')
#   response = iam_client.list_roles
#   if role_found?(
#     response.roles,
#     'arn:aws:iam::111111111111:role/aws-doc-sdk-examples-ec2-state-change'
#   )
#     puts 'Role found.'
#   end
def role_found?(roles, role_arn)
  roles.each do |role|
    return true if role.arn == role_arn
  end
  false
end
```
IAM で発信者が利用できるロールの中に指定されたロールが存在するかどうかをチェックします。  

```
# Checks whether the specified role exists among those available to the
# caller in AWS Identity and Access Management (IAM).
#
# @param iam_client [Aws::IAM::Client] An initialized IAM client.
# @param role_arn [String] The ARN of the role to find.
# @return [Boolean] true if the role ARN was found; otherwise, false.
# @example
#   exit 1 unless role_exists?(
#     Aws::IAM::Client.new(region: 'us-east-1'),
#     'arn:aws:iam::111111111111:role/aws-doc-sdk-examples-ec2-state-change'
#   )
def role_exists?(iam_client, role_arn)
  puts "Searching for role with ARN '#{role_arn}'..."
  response = iam_client.list_roles
  if response.roles.count.positive?
    if role_found?(response.roles, role_arn)
      puts 'Role found.'
      return true
    end
    while response.next_page?
      response = response.next_page
      next unless response.roles.count.positive?

      if role_found?(response.roles, role_arn)
        puts 'Role found.'
        return true
      end
    end
  end
  puts 'Role not found.'
  false
rescue StandardError => e
  puts "Role not found: #{e.message}"
  false
end
```
IAM でロールを作成します。  

```
# Creates a role in AWS Identity and Access Management (IAM).
# This role is used by a rule in Amazon EventBridge to allow
# that rule to operate within the caller's account.
# This role is designed to be used specifically by this code example.
#
# @param iam_client [Aws::IAM::Client] An initialized IAM client.
# @param role_name [String] The name of the role to create.
# @return [String] The ARN of the role that was created.
# @example
#   puts create_role(
#     Aws::IAM::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-ec2-state-change'
#   )
def create_role(iam_client, role_name)
  puts "Creating the role named '#{role_name}'..."
  response = iam_client.create_role(
    assume_role_policy_document: {
      'Version': '2012-10-17',
      'Statement': [
        {
          'Sid': '',
          'Effect': 'Allow',
          'Principal': {
            'Service': 'events.amazonaws.com'
          },
          'Action': 'sts:AssumeRole'
        }
      ]
    }.to_json,
    path: '/',
    role_name: role_name
  )
  puts "Role created with ARN '#{response.role.arn}'."
  puts 'Adding access policy to role...'
  iam_client.put_role_policy(
    policy_document: {
      'Version': '2012-10-17',
      'Statement': [
        {
          'Sid': 'CloudWatchEventsFullAccess',
          'Effect': 'Allow',
          'Resource': '*',
          'Action': 'events:*'
        },
        {
          'Sid': 'IAMPassRoleForCloudWatchEvents',
          'Effect': 'Allow',
          'Resource': 'arn:aws:iam::*:role/AWS_Events_Invoke_Targets',
          'Action': 'iam:PassRole'
        }
      ]
    }.to_json,
    policy_name: 'CloudWatchEventsPolicy',
    role_name: role_name
  )
  puts 'Access policy added to role.'
  response.role.arn
rescue StandardError => e
  puts "Error creating role or adding policy to it: #{e.message}"
  puts 'If the role was created, you must add the access policy ' \
    'to the role yourself, or delete the role yourself and try again.'
  'Error'
end
```
この関数に提供されるルールの中に、指定された EventBridge ルールが存在するかどうかをチェックします。  

```
# Checks whether the specified Amazon EventBridge rule exists among
# those provided to this function.
# This is a helper function that is called by the rule_exists? function.
#
# @param rules [Array] An array of Aws::CloudWatchEvents::Types::Rule objects.
# @param rule_arn [String] The name of the rule to find.
# @return [Boolean] true if the name of the rule was found; otherwise, false.
# @example
#   cloudwatchevents_client = Aws::CloudWatch::Client.new(region: 'us-east-1')
#   response = cloudwatchevents_client.list_rules
#   if rule_found?(response.rules, 'aws-doc-sdk-examples-ec2-state-change')
#     puts 'Rule found.'
#   end
def rule_found?(rules, rule_name)
  rules.each do |rule|
    return true if rule.name == rule_name
  end
  false
end
```
EventBridge で発信者が利用できるルールの中に指定されたルールが存在するかどうかをチェックします。  

```
# Checks whether the specified rule exists among those available to the
# caller in Amazon EventBridge.
#
# @param cloudwatchevents_client [Aws::CloudWatchEvents::Client]
#   An initialized Amazon EventBridge client.
# @param rule_name [String] The name of the rule to find.
# @return [Boolean] true if the rule name was found; otherwise, false.
# @example
#   exit 1 unless rule_exists?(
#     Aws::CloudWatch::Client.new(region: 'us-east-1')
#     'aws-doc-sdk-examples-ec2-state-change'
#   )
def rule_exists?(cloudwatchevents_client, rule_name)
  puts "Searching for rule with name '#{rule_name}'..."
  response = cloudwatchevents_client.list_rules
  if response.rules.count.positive?
    if rule_found?(response.rules, rule_name)
      puts 'Rule found.'
      return true
    end
    while response.next_page?
      response = response.next_page
      next unless response.rules.count.positive?

      if rule_found?(response.rules, rule_name)
        puts 'Rule found.'
        return true
      end
    end
  end
  puts 'Rule not found.'
  false
rescue StandardError => e
  puts "Rule not found: #{e.message}"
  false
end
```
Amazon EventBridge でルールを作成します。  

```
# Creates a rule in Amazon EventBridge.
# This rule is triggered whenever an available instance in
# Amazon EC2 changes to the specified state.
# This rule is designed to be used specifically by this code example.
#
# Prerequisites:
#
# - A role in AWS Identity and Access Management (IAM) that is designed
#   to be used specifically by this code example.
# - A topic in Amazon SNS.
#
# @param cloudwatchevents_client [Aws::CloudWatchEvents::Client]
#   An initialized Amazon EventBridge client.
# @param rule_name [String] The name of the rule to create.
# @param rule_description [String] Some description for this rule.
# @param instance_state [String] The state that available instances in
#   Amazon EC2 must change to, to
#   trigger this rule.
# @param role_arn [String] The Amazon Resource Name (ARN) of the IAM role.
# @param target_id [String] Some identifying string for the rule's target.
# @param topic_arn [String] The ARN of the Amazon SNS topic.
# @return [Boolean] true if the rule was created; otherwise, false.
# @example
#   exit 1 unless rule_created?(
#     Aws::CloudWatch::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-ec2-state-change',
#     'Triggers when any available EC2 instance starts.',
#     'running',
#     'arn:aws:iam::111111111111:role/aws-doc-sdk-examples-ec2-state-change',
#     'sns-topic',
#     'arn:aws:sns:us-east-1:111111111111:aws-doc-sdk-examples-topic'
#   )
def rule_created?(
  cloudwatchevents_client,
  rule_name,
  rule_description,
  instance_state,
  role_arn,
  target_id,
  topic_arn
)
  puts "Creating rule with name '#{rule_name}'..."
  put_rule_response = cloudwatchevents_client.put_rule(
    name: rule_name,
    description: rule_description,
    event_pattern: {
      'source': [
        'aws.ec2'
      ],
      'detail-type': [
        'EC2 Instance State-change Notification'
      ],
      'detail': {
        'state': [
          instance_state
        ]
      }
    }.to_json,
    state: 'ENABLED',
    role_arn: role_arn
  )
  puts "Rule created with ARN '#{put_rule_response.rule_arn}'."

  put_targets_response = cloudwatchevents_client.put_targets(
    rule: rule_name,
    targets: [
      {
        id: target_id,
        arn: topic_arn
      }
    ]
  )
  if put_targets_response.key?(:failed_entry_count) &&
     put_targets_response.failed_entry_count.positive?
    puts 'Error(s) adding target to rule:'
    put_targets_response.failed_entries.each do |failure|
      puts failure.error_message
    end
    false
  else
    true
  end
rescue StandardError => e
  puts "Error creating rule or adding target to rule: #{e.message}"
  puts 'If the rule was created, you must add the target ' \
    'to the rule yourself, or delete the rule yourself and try again.'
  false
end
```
Amazon CloudWatch Logs で発信者が利用できるロググループの中に指定されたロググループが存在するかどうかをチェックします。  

```
# Checks to see whether the specified log group exists among those available
# to the caller in Amazon CloudWatch Logs.
#
# @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client] An initialized
#   Amazon CloudWatch Logs client.
# @param log_group_name [String] The name of the log group to find.
# @return [Boolean] true if the log group name was found; otherwise, false.
# @example
#   exit 1 unless log_group_exists?(
#     Aws::CloudWatchLogs::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-cloudwatch-log'
#   )
def log_group_exists?(cloudwatchlogs_client, log_group_name)
  puts "Searching for log group with name '#{log_group_name}'..."
  response = cloudwatchlogs_client.describe_log_groups(
    log_group_name_prefix: log_group_name
  )
  if response.log_groups.count.positive?
    response.log_groups.each do |log_group|
      if log_group.log_group_name == log_group_name
        puts 'Log group found.'
        return true
      end
    end
  end
  puts 'Log group not found.'
  false
rescue StandardError => e
  puts "Log group not found: #{e.message}"
  false
end
```
CloudWatch Logs にロググループを作成します。  

```
# Creates a log group in Amazon CloudWatch Logs.
#
# @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client] An initialized
#   Amazon CloudWatch Logs client.
# @param log_group_name [String] The name of the log group to create.
# @return [Boolean] true if the log group name was created; otherwise, false.
# @example
#   exit 1 unless log_group_created?(
#     Aws::CloudWatchLogs::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-cloudwatch-log'
#   )
def log_group_created?(cloudwatchlogs_client, log_group_name)
  puts "Attempting to create log group with the name '#{log_group_name}'..."
  cloudwatchlogs_client.create_log_group(log_group_name: log_group_name)
  puts 'Log group created.'
  true
rescue StandardError => e
  puts "Error creating log group: #{e.message}"
  false
end
```
CloudWatch Logs でログストリームにイベントを書き込みます。  

```
# Writes an event to a log stream in Amazon CloudWatch Logs.
#
# Prerequisites:
#
# - A log group in Amazon CloudWatch Logs.
# - A log stream within the log group.
#
# @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client] An initialized
#   Amazon CloudWatch Logs client.
# @param log_group_name [String] The name of the log group.
# @param log_stream_name [String] The name of the log stream within
#   the log group.
# @param message [String] The message to write to the log stream.
# @param sequence_token [String] If available, the sequence token from the
#   message that was written immediately before this message. This sequence
#   token is returned by Amazon CloudWatch Logs whenever you programmatically
#   write a message to the log stream.
# @return [String] The sequence token that is returned by
#   Amazon CloudWatch Logs after successfully writing the message to the
#   log stream.
# @example
#   puts log_event(
#     Aws::EC2::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-cloudwatch-log'
#     '2020/11/19/53f985be-199f-408e-9a45-fc242df41fEX',
#     "Instance 'i-033c48ef067af3dEX' restarted.",
#     '495426724868310740095796045676567882148068632824696073EX'
#   )
def log_event(
  cloudwatchlogs_client,
  log_group_name,
  log_stream_name,
  message,
  sequence_token
)
  puts "Attempting to log '#{message}' to log stream '#{log_stream_name}'..."
  event = {
    log_group_name: log_group_name,
    log_stream_name: log_stream_name,
    log_events: [
      {
        timestamp: (Time.now.utc.to_f.round(3) * 1_000).to_i,
        message: message
      }
    ]
  }
  event[:sequence_token] = sequence_token unless sequence_token.empty?

  response = cloudwatchlogs_client.put_log_events(event)
  puts 'Message logged.'
  response.next_sequence_token
rescue StandardError => e
  puts "Message not logged: #{e.message}"
end
```
Amazon Elastic Compute Cloud (Amazon EC2) インスタンスを再起動し、関連するアクティビティに関する情報を CloudWatch Logs 内のログストリームに追加します。  

```
# Restarts an Amazon EC2 instance
# and adds information about the related activity to a log stream
# in Amazon CloudWatch Logs.
#
# Prerequisites:
#
# - The Amazon EC2 instance to restart.
# - The log group in Amazon CloudWatch Logs to add related activity
#   information to.
#
# @param ec2_client [Aws::EC2::Client] An initialized Amazon EC2 client.
# @param cloudwatchlogs_client [Aws::CloudWatchLogs::Client]
#   An initialized Amazon CloudWatch Logs client.
# @param instance_id [String] The ID of the instance.
# @param log_group_name [String] The name of the log group.
# @return [Boolean] true if the instance was restarted and the information
#   was written to the log stream; otherwise, false.
# @example
#   exit 1 unless instance_restarted?(
#     Aws::EC2::Client.new(region: 'us-east-1'),
#     Aws::CloudWatchLogs::Client.new(region: 'us-east-1'),
#     'i-033c48ef067af3dEX',
#     'aws-doc-sdk-examples-cloudwatch-log'
#   )
def instance_restarted?(
  ec2_client,
  cloudwatchlogs_client,
  instance_id,
  log_group_name
)
  log_stream_name = "#{Time.now.year}/#{Time.now.month}/#{Time.now.day}/" \
    "#{SecureRandom.uuid}"
  cloudwatchlogs_client.create_log_stream(
    log_group_name: log_group_name,
    log_stream_name: log_stream_name
  )
  sequence_token = ''

  puts "Attempting to stop the instance with the ID '#{instance_id}'. " \
    'This might take a few minutes...'
  ec2_client.stop_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_stopped, instance_ids: [instance_id])
  puts 'Instance stopped.'
  sequence_token = log_event(
    cloudwatchlogs_client,
    log_group_name,
    log_stream_name,
    "Instance '#{instance_id}' stopped.",
    sequence_token
  )

  puts 'Attempting to restart the instance. This might take a few minutes...'
  ec2_client.start_instances(instance_ids: [instance_id])
  ec2_client.wait_until(:instance_running, instance_ids: [instance_id])
  puts 'Instance restarted.'
  sequence_token = log_event(
    cloudwatchlogs_client,
    log_group_name,
    log_stream_name,
    "Instance '#{instance_id}' restarted.",
    sequence_token
  )

  true
rescue StandardError => e
  puts 'Error creating log stream or stopping or restarting the instance: ' \
    "#{e.message}"
  log_event(
    cloudwatchlogs_client,
    log_group_name,
    log_stream_name,
    "Error stopping or starting instance '#{instance_id}': #{e.message}",
    sequence_token
  )
  false
end
```
EventBridge のルールのアクティビティに関する情報を表示しています。  

```
# Displays information about activity for a rule in Amazon EventBridge.
#
# Prerequisites:
#
# - A rule in Amazon EventBridge.
#
# @param cloudwatch_client [Amazon::CloudWatch::Client] An initialized
#   Amazon CloudWatch client.
# @param rule_name [String] The name of the rule.
# @param start_time [Time] The timestamp that determines the first datapoint
#   to return. Can also be expressed as DateTime, Date, Integer, or String.
# @param end_time [Time] The timestamp that determines the last datapoint
#   to return. Can also be expressed as DateTime, Date, Integer, or String.
# @param period [Integer] The interval, in seconds, to check for activity.
# @example
#   display_rule_activity(
#     Aws::CloudWatch::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-ec2-state-change',
#     Time.now - 600, # Start checking from 10 minutes ago.
#     Time.now, # Check up until now.
#     60 # Check every minute during those 10 minutes.
#   )
def display_rule_activity(
  cloudwatch_client,
  rule_name,
  start_time,
  end_time,
  period
)
  puts 'Attempting to display rule activity...'
  response = cloudwatch_client.get_metric_statistics(
    namespace: 'AWS/Events',
    metric_name: 'Invocations',
    dimensions: [
      {
        name: 'RuleName',
        value: rule_name
      }
    ],
    start_time: start_time,
    end_time: end_time,
    period: period,
    statistics: ['Sum'],
    unit: 'Count'
  )

  if response.key?(:datapoints) && response.datapoints.count.positive?
    puts "The event rule '#{rule_name}' was triggered:"
    response.datapoints.each do |datapoint|
      puts "  #{datapoint.sum} time(s) at #{datapoint.timestamp}"
    end
  else
    puts "The event rule '#{rule_name}' was not triggered during the " \
      'specified time period.'
  end
rescue StandardError => e
  puts "Error getting information about event rule activity: #{e.message}"
end
```
CloudWatch Logs ロググループ内のすべてのログストリームのログ情報を表示しています。  

```
# Displays log information for all of the log streams in a log group in
# Amazon CloudWatch Logs.
#
# Prerequisites:
#
# - A log group in Amazon CloudWatch Logs.
#
# @param cloudwatchlogs_client [Amazon::CloudWatchLogs::Client] An initialized
#   Amazon CloudWatch Logs client.
# @param log_group_name [String] The name of the log group.
# @example
#   display_log_data(
#     Amazon::CloudWatchLogs::Client.new(region: 'us-east-1'),
#     'aws-doc-sdk-examples-cloudwatch-log'
#   )
def display_log_data(cloudwatchlogs_client, log_group_name)
  puts 'Attempting to display log stream data for the log group ' \
    "named '#{log_group_name}'..."
  describe_log_streams_response = cloudwatchlogs_client.describe_log_streams(
    log_group_name: log_group_name,
    order_by: 'LastEventTime',
    descending: true
  )
  if describe_log_streams_response.key?(:log_streams) &&
     describe_log_streams_response.log_streams.count.positive?
    describe_log_streams_response.log_streams.each do |log_stream|
      get_log_events_response = cloudwatchlogs_client.get_log_events(
        log_group_name: log_group_name,
        log_stream_name: log_stream.log_stream_name
      )
      puts "\nLog messages for '#{log_stream.log_stream_name}':"
      puts '-' * (log_stream.log_stream_name.length + 20)
      if get_log_events_response.key?(:events) &&
         get_log_events_response.events.count.positive?
        get_log_events_response.events.each do |event|
          puts event.message
        end
      else
        puts 'No log messages for this log stream.'
      end
    end
  end
rescue StandardError => e
  puts 'Error getting information about the log streams or their messages: ' \
    "#{e.message}"
end
```
発信者にリマインダーを表示して、不要になった関連 AWS リソースを手動でクリーンアップします。  

```
# Displays a reminder to the caller to manually clean up any associated
# AWS resources that they no longer need.
#
# @param topic_name [String] The name of the Amazon SNS topic.
# @param role_name [String] The name of the IAM role.
# @param rule_name [String] The name of the Amazon EventBridge rule.
# @param log_group_name [String] The name of the Amazon CloudWatch Logs log group.
# @param instance_id [String] The ID of the Amazon EC2 instance.
# @example
#   manual_cleanup_notice(
#     'aws-doc-sdk-examples-topic',
#     'aws-doc-sdk-examples-cloudwatch-events-rule-role',
#     'aws-doc-sdk-examples-ec2-state-change',
#     'aws-doc-sdk-examples-cloudwatch-log',
#     'i-033c48ef067af3dEX'
#   )
def manual_cleanup_notice(
  topic_name, role_name, rule_name, log_group_name, instance_id
)
  puts '-' * 10
  puts 'Some of the following AWS resources might still exist in your account.'
  puts 'If you no longer want to use this code example, then to clean up'
  puts 'your AWS account and avoid unexpected costs, you might want to'
  puts 'manually delete any of the following resources if they exist:'
  puts "- The Amazon SNS topic named '#{topic_name}'."
  puts "- The IAM role named '#{role_name}'."
  puts "- The Amazon EventBridge rule named '#{rule_name}'."
  puts "- The Amazon CloudWatch Logs log group named '#{log_group_name}'."
  puts "- The Amazon EC2 instance with the ID '#{instance_id}'."
end
```
+ API の詳細については、「*AWS SDK for Ruby API リファレンス*」の以下のトピックを参照してください。
  + [PutEvents](https://docs.aws.amazon.com/goto/SdkForRubyV3/eventbridge-2015-10-07/PutEvents)
  + [PutRule](https://docs.aws.amazon.com/goto/SdkForRubyV3/eventbridge-2015-10-07/PutRule)

# AWS Glue SDK for Ruby を使用した の例
<a name="ruby_3_glue_code_examples"></a>

次のコード例は、 AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Glueは
<a name="glue_Hello_ruby_3_topic"></a>

次のコード例は、 AWS Glueの使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-glue'
require 'logger'

# GlueManager is a class responsible for managing AWS Glue operations
# such as listing all Glue jobs in the current AWS account.
class GlueManager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all Glue jobs in the current AWS account.
  def list_jobs
    @logger.info('Here are the Glue jobs in your account:')

    paginator = @client.get_jobs(max_results: 10)
    jobs = []

    paginator.each_page do |page|
      jobs.concat(page.jobs)
    end

    if jobs.empty?
      @logger.info("You don't have any Glue jobs.")
    else
      jobs.each do |job|
        @logger.info("- #{job.name}")
      end
    end
  end
end

if $PROGRAM_NAME == __FILE__
  glue_client = Aws::Glue::Client.new
  manager = GlueManager.new(glue_client)
  manager.list_jobs
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/ListJobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_ruby_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。
シナリオで使用される AWS Glue 関数をラップするクラスを作成します。  

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Retrieves information about a specific crawler.
  #
  # @param name [String] The name of the crawler to retrieve information about.
  # @return [Aws::Glue::Types::Crawler, nil] The crawler object if found, or nil if not found.
  def get_crawler(name)
    @glue_client.get_crawler(name: name)
  rescue Aws::Glue::Errors::EntityNotFoundException
    @logger.info("Crawler #{name} doesn't exist.")
    false
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get crawler #{name}: \n#{e.message}")
    raise
  end

  # Creates a new crawler with the specified configuration.
  #
  # @param name [String] The name of the crawler.
  # @param role_arn [String] The ARN of the IAM role to be used by the crawler.
  # @param db_name [String] The name of the database where the crawler stores its metadata.
  # @param db_prefix [String] The prefix to be added to the names of tables that the crawler creates.
  # @param s3_target [String] The S3 path that the crawler will crawl.
  # @return [void]
  def create_crawler(name, role_arn, db_name, _db_prefix, s3_target)
    @glue_client.create_crawler(
      name: name,
      role: role_arn,
      database_name: db_name,
      targets: {
        s3_targets: [
          {
            path: s3_target
          }
        ]
      }
    )
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not create crawler: \n#{e.message}")
    raise
  end

  # Starts a crawler with the specified name.
  #
  # @param name [String] The name of the crawler to start.
  # @return [void]
  def start_crawler(name)
    @glue_client.start_crawler(name: name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not start crawler #{name}: \n#{e.message}")
    raise
  end

  # Deletes a crawler with the specified name.
  #
  # @param name [String] The name of the crawler to delete.
  # @return [void]
  def delete_crawler(name)
    @glue_client.delete_crawler(name: name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete crawler #{name}: \n#{e.message}")
    raise
  end

  # Retrieves information about a specific database.
  #
  # @param name [String] The name of the database to retrieve information about.
  # @return [Aws::Glue::Types::Database, nil] The database object if found, or nil if not found.
  def get_database(name)
    response = @glue_client.get_database(name: name)
    response.database
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get database #{name}: \n#{e.message}")
    raise
  end

  # Retrieves a list of tables in the specified database.
  #
  # @param db_name [String] The name of the database to retrieve tables from.
  # @return [Array<Aws::Glue::Types::Table>]
  def get_tables(db_name)
    response = @glue_client.get_tables(database_name: db_name)
    response.table_list
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get tables #{db_name}: \n#{e.message}")
    raise
  end

  # Creates a new job with the specified configuration.
  #
  # @param name [String] The name of the job.
  # @param description [String] The description of the job.
  # @param role_arn [String] The ARN of the IAM role to be used by the job.
  # @param script_location [String] The location of the ETL script for the job.
  # @return [void]
  def create_job(name, description, role_arn, script_location)
    @glue_client.create_job(
      name: name,
      description: description,
      role: role_arn,
      command: {
        name: 'glueetl',
        script_location: script_location,
        python_version: '3'
      },
      glue_version: '3.0'
    )
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not create job #{name}: \n#{e.message}")
    raise
  end

  # Starts a job run for the specified job.
  #
  # @param name [String] The name of the job to start the run for.
  # @param input_database [String] The name of the input database for the job.
  # @param input_table [String] The name of the input table for the job.
  # @param output_bucket_name [String] The name of the output S3 bucket for the job.
  # @return [String] The ID of the started job run.
  def start_job_run(name, input_database, input_table, output_bucket_name)
    response = @glue_client.start_job_run(
      job_name: name,
      arguments: {
        '--input_database': input_database,
        '--input_table': input_table,
        '--output_bucket_url': "s3://#{output_bucket_name}/"
      }
    )
    response.job_run_id
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not start job run #{name}: \n#{e.message}")
    raise
  end

  # Retrieves a list of jobs in AWS Glue.
  #
  # @return [Aws::Glue::Types::ListJobsResponse]
  def list_jobs
    @glue_client.list_jobs
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not list jobs: \n#{e.message}")
    raise
  end

  # Retrieves a list of job runs for the specified job.
  #
  # @param job_name [String] The name of the job to retrieve job runs for.
  # @return [Array<Aws::Glue::Types::JobRun>]
  def get_job_runs(job_name)
    response = @glue_client.get_job_runs(job_name: job_name)
    response.job_runs
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get job runs: \n#{e.message}")
  end

  # Retrieves data for a specific job run.
  #
  # @param job_name [String] The name of the job run to retrieve data for.
  # @return [Glue::Types::GetJobRunResponse]
  def get_job_run(job_name, run_id)
    @glue_client.get_job_run(job_name: job_name, run_id: run_id)
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get job runs: \n#{e.message}")
  end

  # Deletes a job with the specified name.
  #
  # @param job_name [String] The name of the job to delete.
  # @return [void]
  def delete_job(job_name)
    @glue_client.delete_job(job_name: job_name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete job: \n#{e.message}")
  end

  # Deletes a table with the specified name.
  #
  # @param database_name [String] The name of the catalog database in which the table resides.
  # @param table_name [String] The name of the table to be deleted.
  # @return [void]
  def delete_table(database_name, table_name)
    @glue_client.delete_table(database_name: database_name, name: table_name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete job: \n#{e.message}")
  end

  # Removes a specified database from a Data Catalog.
  #
  # @param database_name [String] The name of the database to delete.
  # @return [void]
  def delete_database(database_name)
    @glue_client.delete_database(name: database_name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete database: \n#{e.message}")
  end

  # Uploads a job script file to an S3 bucket.
  #
  # @param file_path [String] The local path of the job script file.
  # @param bucket_resource [Aws::S3::Bucket] The S3 bucket resource to upload the file to.
  # @return [void]
  def upload_job_script(file_path, bucket_resource)
    File.open(file_path) do |file|
      bucket_resource.client.put_object({
                                          body: file,
                                          bucket: bucket_resource.name,
                                          key: file_path
                                        })
    end
  rescue Aws::S3::Errors::S3UploadFailedError => e
    @logger.error("S3 could not upload job script: \n#{e.message}")
    raise
  end
end
```
シナリオを実行するクラスを作成します。  

```
class GlueCrawlerJobScenario
  def initialize(glue_client, glue_service_role, glue_bucket, logger)
    @glue_client = glue_client
    @glue_service_role = glue_service_role
    @glue_bucket = glue_bucket
    @logger = logger
  end

  def run(crawler_name, db_name, db_prefix, data_source, job_script, job_name)
    wrapper = GlueWrapper.new(@glue_client, @logger)
    setup_crawler(wrapper, crawler_name, db_name, db_prefix, data_source)
    query_database(wrapper, crawler_name, db_name)
    create_and_run_job(wrapper, job_script, job_name, db_name)
  end

  private

  def setup_crawler(wrapper, crawler_name, db_name, db_prefix, data_source)
    new_step(1, 'Create a crawler')
    crawler = wrapper.get_crawler(crawler_name)
    unless crawler
      puts "Creating crawler #{crawler_name}."
      wrapper.create_crawler(crawler_name, @glue_service_role.arn, db_name, db_prefix, data_source)
      puts "Successfully created #{crawler_name}."
    end
    wrapper.start_crawler(crawler_name)
    monitor_crawler(wrapper, crawler_name)
  end

  def monitor_crawler(wrapper, crawler_name)
    new_step(2, 'Monitor Crawler')
    crawler_state = nil
    until crawler_state == 'READY'
      custom_wait(15)
      crawler = wrapper.get_crawler(crawler_name)
      crawler_state = crawler[0]['state']
      print "Crawler status: #{crawler_state}".yellow
    end
  end

  def query_database(wrapper, _crawler_name, db_name)
    new_step(3, 'Query the database.')
    wrapper.get_database(db_name)
    puts "The crawler created database #{db_name}:"
    puts "Database contains tables: #{wrapper.get_tables(db_name).map { |t| t['name'] }}"
  end

  def create_and_run_job(wrapper, job_script, job_name, db_name)
    new_step(4, 'Create and run job.')
    wrapper.upload_job_script(job_script, @glue_bucket)
    wrapper.create_job(job_name, 'ETL Job', @glue_service_role.arn, "s3://#{@glue_bucket.name}/#{job_script}")
    run_job(wrapper, job_name, db_name)
  end

  def run_job(wrapper, job_name, db_name)
    new_step(5, 'Run the job.')
    wrapper.start_job_run(job_name, db_name, wrapper.get_tables(db_name)[0]['name'], @glue_bucket.name)
    job_run_status = nil
    until %w[SUCCEEDED FAILED STOPPED].include?(job_run_status)
      custom_wait(10)
      job_run = wrapper.get_job_runs(job_name)
      job_run_status = job_run[0]['job_run_state']
      print "Job #{job_name} status: #{job_run_status}".yellow
    end
  end
end

def main
  banner('../../helpers/banner.txt')
  puts 'Starting AWS Glue demo...'

  # Load resource names from YAML.
  resource_names = YAML.load_file('resource_names.yaml')

  # Setup services and resources.
  iam_role = Aws::IAM::Resource.new(region: 'us-east-1').role(resource_names['glue_service_role'])
  s3_bucket = Aws::S3::Resource.new(region: 'us-east-1').bucket(resource_names['glue_bucket'])

  # Instantiate scenario and run.
  scenario = GlueCrawlerJobScenario.new(Aws::Glue::Client.new(region: 'us-east-1'), iam_role, s3_bucket, @logger)
  random_suffix = rand(10**4)
  scenario.run("crawler-#{random_suffix}", "db-#{random_suffix}", "prefix-#{random_suffix}-", 's3://data_source',
               'job_script.py', "job-#{random_suffix}")

  puts 'Demo complete.'
end
```
ジョブの実行中にデータを抽出、変換、ロード AWS Glue するために で使用される ETL スクリプトを作成します。  

```
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

"""
These custom arguments must be passed as Arguments to the StartJobRun request.
    --input_database    The name of a metadata database that is contained in your 
                        AWS Glue Data Catalog and that contains tables that describe 
                        the data to be processed.
    --input_table       The name of a table in the database that describes the data to
                        be processed.
    --output_bucket_url An S3 bucket that receives the transformed output data.  
"""
args = getResolvedOptions(
    sys.argv, ["JOB_NAME", "input_database", "input_table", "output_bucket_url"]
)
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args["JOB_NAME"], args)

# Script generated for node S3 Flight Data.
S3FlightData_node1 = glueContext.create_dynamic_frame.from_catalog(
    database=args["input_database"],
    table_name=args["input_table"],
    transformation_ctx="S3FlightData_node1",
)

# This mapping performs two main functions:
# 1. It simplifies the output by removing most of the fields from the data.
# 2. It renames some fields. For example, `fl_date` is renamed to `flight_date`.
ApplyMapping_node2 = ApplyMapping.apply(
    frame=S3FlightData_node1,
    mappings=[
        ("year", "long", "year", "long"),
        ("month", "long", "month", "tinyint"),
        ("day_of_month", "long", "day", "tinyint"),
        ("fl_date", "string", "flight_date", "string"),
        ("carrier", "string", "carrier", "string"),
        ("fl_num", "long", "flight_num", "long"),
        ("origin_city_name", "string", "origin_city_name", "string"),
        ("origin_state_abr", "string", "origin_state_abr", "string"),
        ("dest_city_name", "string", "dest_city_name", "string"),
        ("dest_state_abr", "string", "dest_state_abr", "string"),
        ("dep_time", "long", "departure_time", "long"),
        ("wheels_off", "long", "wheels_off", "long"),
        ("wheels_on", "long", "wheels_on", "long"),
        ("arr_time", "long", "arrival_time", "long"),
        ("mon", "string", "mon", "string"),
    ],
    transformation_ctx="ApplyMapping_node2",
)

# Script generated for node Revised Flight Data.
RevisedFlightData_node3 = glueContext.write_dynamic_frame.from_options(
    frame=ApplyMapping_node2,
    connection_type="s3",
    format="json",
    connection_options={"path": args["output_bucket_url"], "partitionKeys": []},
    transformation_ctx="RevisedFlightData_node3",
)

job.commit()
```
+ API の詳細については、「*AWS SDK for Ruby API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/CreateCrawler)
  + [CreateJob](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/CreateJob)
  + [DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteCrawler)
  + [DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteDatabase)
  + [DeleteJob](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteJob)
  + [DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteTable)
  + [GetCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetCrawler)
  + [GetDatabase](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetDatabase)
  + [GetDatabases](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetDatabases)
  + [GetJob](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetJob)
  + [GetJobRun](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetJobRun)
  + [GetJobRuns](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetJobRuns)
  + [GetTables](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetTables)
  + [ListJobs](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/ListJobs)
  + [StartCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/StartCrawler)
  + [StartJobRun](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/StartJobRun)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_ruby_3_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Creates a new crawler with the specified configuration.
  #
  # @param name [String] The name of the crawler.
  # @param role_arn [String] The ARN of the IAM role to be used by the crawler.
  # @param db_name [String] The name of the database where the crawler stores its metadata.
  # @param db_prefix [String] The prefix to be added to the names of tables that the crawler creates.
  # @param s3_target [String] The S3 path that the crawler will crawl.
  # @return [void]
  def create_crawler(name, role_arn, db_name, _db_prefix, s3_target)
    @glue_client.create_crawler(
      name: name,
      role: role_arn,
      database_name: db_name,
      targets: {
        s3_targets: [
          {
            path: s3_target
          }
        ]
      }
    )
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not create crawler: \n#{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[CreateCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/CreateCrawler)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_ruby_3_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Creates a new job with the specified configuration.
  #
  # @param name [String] The name of the job.
  # @param description [String] The description of the job.
  # @param role_arn [String] The ARN of the IAM role to be used by the job.
  # @param script_location [String] The location of the ETL script for the job.
  # @return [void]
  def create_job(name, description, role_arn, script_location)
    @glue_client.create_job(
      name: name,
      description: description,
      role: role_arn,
      command: {
        name: 'glueetl',
        script_location: script_location,
        python_version: '3'
      },
      glue_version: '3.0'
    )
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not create job #{name}: \n#{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[CreateJob](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/CreateJob)」を参照してください。**

### `DeleteCrawler`
<a name="glue_DeleteCrawler_ruby_3_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Deletes a crawler with the specified name.
  #
  # @param name [String] The name of the crawler to delete.
  # @return [void]
  def delete_crawler(name)
    @glue_client.delete_crawler(name: name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete crawler #{name}: \n#{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[DeleteCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteCrawler)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_ruby_3_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Removes a specified database from a Data Catalog.
  #
  # @param database_name [String] The name of the database to delete.
  # @return [void]
  def delete_database(database_name)
    @glue_client.delete_database(name: database_name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete database: \n#{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteDatabase](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteDatabase)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_ruby_3_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Deletes a job with the specified name.
  #
  # @param job_name [String] The name of the job to delete.
  # @return [void]
  def delete_job(job_name)
    @glue_client.delete_job(job_name: job_name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete job: \n#{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteJob](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteJob)」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_ruby_3_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Deletes a table with the specified name.
  #
  # @param database_name [String] The name of the catalog database in which the table resides.
  # @param table_name [String] The name of the table to be deleted.
  # @return [void]
  def delete_table(database_name, table_name)
    @glue_client.delete_table(database_name: database_name, name: table_name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not delete job: \n#{e.message}")
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[DeleteTable](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/DeleteTable)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_ruby_3_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Retrieves information about a specific crawler.
  #
  # @param name [String] The name of the crawler to retrieve information about.
  # @return [Aws::Glue::Types::Crawler, nil] The crawler object if found, or nil if not found.
  def get_crawler(name)
    @glue_client.get_crawler(name: name)
  rescue Aws::Glue::Errors::EntityNotFoundException
    @logger.info("Crawler #{name} doesn't exist.")
    false
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get crawler #{name}: \n#{e.message}")
    raise
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetCrawler)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_ruby_3_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Retrieves information about a specific database.
  #
  # @param name [String] The name of the database to retrieve information about.
  # @return [Aws::Glue::Types::Database, nil] The database object if found, or nil if not found.
  def get_database(name)
    response = @glue_client.get_database(name: name)
    response.database
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get database #{name}: \n#{e.message}")
    raise
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetDatabase](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetDatabase)」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_ruby_3_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Retrieves data for a specific job run.
  #
  # @param job_name [String] The name of the job run to retrieve data for.
  # @return [Glue::Types::GetJobRunResponse]
  def get_job_run(job_name, run_id)
    @glue_client.get_job_run(job_name: job_name, run_id: run_id)
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get job runs: \n#{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetJobRun](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetJobRun)」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_ruby_3_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Retrieves a list of job runs for the specified job.
  #
  # @param job_name [String] The name of the job to retrieve job runs for.
  # @return [Array<Aws::Glue::Types::JobRun>]
  def get_job_runs(job_name)
    response = @glue_client.get_job_runs(job_name: job_name)
    response.job_runs
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get job runs: \n#{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetJobRuns](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetJobRuns)」を参照してください。

### `GetTables`
<a name="glue_GetTables_ruby_3_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Retrieves a list of tables in the specified database.
  #
  # @param db_name [String] The name of the database to retrieve tables from.
  # @return [Array<Aws::Glue::Types::Table>]
  def get_tables(db_name)
    response = @glue_client.get_tables(database_name: db_name)
    response.table_list
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not get tables #{db_name}: \n#{e.message}")
    raise
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetTables](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/GetTables)」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_ruby_3_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Retrieves a list of jobs in AWS Glue.
  #
  # @return [Aws::Glue::Types::ListJobsResponse]
  def list_jobs
    @glue_client.list_jobs
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not list jobs: \n#{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[ListJobs](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/ListJobs)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_ruby_3_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Starts a crawler with the specified name.
  #
  # @param name [String] The name of the crawler to start.
  # @return [void]
  def start_crawler(name)
    @glue_client.start_crawler(name: name)
  rescue Aws::Glue::Errors::ServiceError => e
    @logger.error("Glue could not start crawler #{name}: \n#{e.message}")
    raise
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[StartCrawler](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/StartCrawler)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_ruby_3_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
# The `GlueWrapper` class serves as a wrapper around the AWS Glue API, providing a simplified interface for common operations.
# It encapsulates the functionality of the AWS SDK for Glue and provides methods for interacting with Glue crawlers, databases, tables, jobs, and S3 resources.
# The class initializes with a Glue client and a logger, allowing it to make API calls and log any errors or informational messages.
class GlueWrapper
  def initialize(glue_client, logger)
    @glue_client = glue_client
    @logger = logger
  end

  # Starts a job run for the specified job.
  #
  # @param name [String] The name of the job to start the run for.
  # @param input_database [String] The name of the input database for the job.
  # @param input_table [String] The name of the input table for the job.
  # @param output_bucket_name [String] The name of the output S3 bucket for the job.
  # @return [String] The ID of the started job run.
  def start_job_run(name, input_database, input_table, output_bucket_name)
    response = @glue_client.start_job_run(
      job_name: name,
      arguments: {
        '--input_database': input_database,
        '--input_table': input_table,
        '--output_bucket_url': "s3://#{output_bucket_name}/"
      }
    )
    response.job_run_id
  rescue Aws::Glue::Errors::GlueException => e
    @logger.error("Glue could not start job run #{name}: \n#{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[StartJobRun](https://docs.aws.amazon.com/goto/SdkForRubyV3/glue-2017-03-31/StartJobRun)」を参照してください。**

# SDK for Ruby を使用した IAM の例
<a name="ruby_3_iam_code_examples"></a>

次のコード例は、IAM AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_ruby_3_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-iam'
require 'logger'

# IAMManager is a class responsible for managing IAM operations
# such as listing all IAM policies in the current AWS account.
class IAMManager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all IAM policies in the current AWS account.
  def list_policies
    @logger.info('Here are the IAM policies in your account:')

    paginator = @client.list_policies
    policies = []

    paginator.each_page do |page|
      policies.concat(page.policies)
    end

    if policies.empty?
      @logger.info("You don't have any IAM policies.")
    else
      policies.each do |policy|
        @logger.info("- #{policy.policy_name}")
      end
    end
  end
end

if $PROGRAM_NAME == __FILE__
  iam_client = Aws::IAM::Client.new
  manager = IAMManager.new(iam_client)
  manager.list_policies
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListPolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListPolicies)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_ruby_3_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
IAM ユーザーと、Amazon S3 バケットを一覧表示するアクセス権限を付与するロールを作成します。ユーザーには、ロールの引き受けのみ権限があります。ロールを引き受けた後、一時的な認証情報を使用してアカウントのバケットを一覧表示します。  

```
# Wraps the scenario actions.
class ScenarioCreateUserAssumeRole
  attr_reader :iam_client

  # @param [Aws::IAM::Client] iam_client: The AWS IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Waits for the specified number of seconds.
  #
  # @param duration [Integer] The number of seconds to wait.
  def wait(duration)
    puts('Give AWS time to propagate resources...')
    sleep(duration)
  end

  # Creates a user.
  #
  # @param user_name [String] The name to give the user.
  # @return [Aws::IAM::User] The newly created user.
  def create_user(user_name)
    user = @iam_client.create_user(user_name: user_name).user
    @logger.info("Created demo user named #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info('Tried and failed to create demo user.')
    @logger.info("\t#{e.code}: #{e.message}")
    @logger.info("\nCan't continue the demo without a user!")
    raise
  else
    user
  end

  # Creates an access key for a user.
  #
  # @param user [Aws::IAM::User] The user that owns the key.
  # @return [Aws::IAM::AccessKeyPair] The newly created access key.
  def create_access_key_pair(user)
    user_key = @iam_client.create_access_key(user_name: user.user_name).access_key
    @logger.info("Created accesskey pair for user #{user.user_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create access keys for user #{user.user_name}.")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    user_key
  end

  # 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)
    trust_policy = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Principal: { 'AWS': user.arn },
        Action: 'sts:AssumeRole'
      }]
    }.to_json
    role = @iam_client.create_role(
      role_name: role_name,
      assume_role_policy_document: trust_policy
    ).role
    @logger.info("Created role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a role for the demo. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  else
    role
  end

  # Creates a policy that grants permission to list S3 buckets in the account, and
  # then attaches the policy to a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param role [Aws::IAM::Role] The role that the policy is attached to.
  # @return [Aws::IAM::Policy] The newly created policy.
  def create_and_attach_role_policy(policy_name, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 's3:ListAllMyBuckets',
        Resource: 'arn:aws:s3:::*'
      }]
    }.to_json
    policy = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document
    ).policy
    @iam_client.attach_role_policy(
      role_name: role.role_name,
      policy_arn: policy.arn
    )
    @logger.info("Created policy #{policy.policy_name} and attached it to role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create a policy and attach it to role #{role.role_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an inline policy for a user that lets the user assume a role.
  #
  # @param policy_name [String] The name to give the policy.
  # @param user [Aws::IAM::User] The user that owns the policy.
  # @param role [Aws::IAM::Role] The role that can be assumed.
  # @return [Aws::IAM::UserPolicy] The newly created policy.
  def create_user_policy(policy_name, user, role)
    policy_document = {
      Version: '2012-10-17',
      Statement: [{
        Effect: 'Allow',
        Action: 'sts:AssumeRole',
        Resource: role.arn
      }]
    }.to_json
    @iam_client.put_user_policy(
      user_name: user.user_name,
      policy_name: policy_name,
      policy_document: policy_document
    )
    puts("Created an inline policy for #{user.user_name} that lets the user assume role #{role.role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't create an inline policy for user #{user.user_name}. Here's why: ")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Creates an Amazon S3 resource with specified credentials. This is separated into a
  # factory function so that it can be mocked for unit testing.
  #
  # @param credentials [Aws::Credentials] The credentials used by the Amazon S3 resource.
  def create_s3_resource(credentials)
    Aws::S3::Resource.new(client: Aws::S3::Client.new(credentials: credentials))
  end

  # Lists the S3 buckets for the account, using the specified Amazon S3 resource.
  # Because the resource uses credentials with limited access, it may not be able to
  # list the S3 buckets.
  #
  # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource.
  def list_buckets(s3_resource)
    count = 10
    s3_resource.buckets.each do |bucket|
      @logger.info "\t#{bucket.name}"
      count -= 1
      break if count.zero?
    end
  rescue Aws::Errors::ServiceError => e
    if e.code == 'AccessDenied'
      puts('Attempt to list buckets with no permissions: AccessDenied.')
    else
      @logger.info("Couldn't list buckets for the account. Here's why: ")
      @logger.info("\t#{e.code}: #{e.message}")
      raise
    end
  end

  # Creates an AWS Security Token Service (AWS STS) client with specified credentials.
  # This is separated into a factory function so that it can be mocked for unit testing.
  #
  # @param key_id [String] The ID of the access key used by the STS client.
  # @param key_secret [String] The secret part of the access key used by the STS client.
  def create_sts_client(key_id, key_secret)
    Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret)
  end

  # Gets temporary credentials that can be used to assume a role.
  #
  # @param role_arn [String] The ARN of the role that is assumed when these credentials
  #                          are used.
  # @param sts_client [AWS::STS::Client] An AWS STS client.
  # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role.
  def assume_role(role_arn, sts_client)
    credentials = Aws::AssumeRoleCredentials.new(
      client: sts_client,
      role_arn: role_arn,
      role_session_name: 'create-use-assume-role-scenario'
    )
    @logger.info("Assumed role '#{role_arn}', got temporary credentials.")
    credentials
  end

  # Deletes a role. If the role has policies attached, they are detached and
  # deleted before the role is deleted.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_role(role_name)
    @iam_client.list_attached_role_policies(role_name: role_name).attached_policies.each do |policy|
      @iam_client.detach_role_policy(role_name: role_name, policy_arn: policy.policy_arn)
      @iam_client.delete_policy(policy_arn: policy.policy_arn)
      @logger.info("Detached and deleted policy #{policy.policy_name}.")
    end
    @iam_client.delete_role({ role_name: role_name })
    @logger.info("Role deleted: #{role_name}.")
  rescue Aws::Errors::ServiceError => e
    @logger.info("Couldn't detach policies and delete role #{role.name}. Here's why:")
    @logger.info("\t#{e.code}: #{e.message}")
    raise
  end

  # Deletes a user. If the user has inline policies or access keys, they are deleted
  # before the user is deleted.
  #
  # @param user [Aws::IAM::User] The user to delete.
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
end

# Runs the IAM create a user and assume a role scenario.
def run_scenario(scenario)
  puts('-' * 88)
  puts('Welcome to the IAM create a user and assume a role demo!')
  puts('-' * 88)
  user = scenario.create_user("doc-example-user-#{Random.uuid}")
  user_key = scenario.create_access_key_pair(user)
  scenario.wait(10)
  role = scenario.create_role("doc-example-role-#{Random.uuid}", user)
  scenario.create_and_attach_role_policy("doc-example-role-policy-#{Random.uuid}", role)
  scenario.create_user_policy("doc-example-user-policy-#{Random.uuid}", user, role)
  scenario.wait(10)
  puts('Try to list buckets with credentials for a user who has no permissions.')
  puts('Expect AccessDenied from this call.')
  scenario.list_buckets(
    scenario.create_s3_resource(Aws::Credentials.new(user_key.access_key_id, user_key.secret_access_key))
  )
  puts('Now, assume the role that grants permission.')
  temp_credentials = scenario.assume_role(
    role.arn, scenario.create_sts_client(user_key.access_key_id, user_key.secret_access_key)
  )
  puts('Here are your buckets:')
  scenario.list_buckets(scenario.create_s3_resource(temp_credentials))
  puts("Deleting role '#{role.role_name}' and attached policies.")
  scenario.delete_role(role.role_name)
  puts("Deleting user '#{user.user_name}', policies, and keys.")
  scenario.delete_user(user.user_name)
  puts('Thanks for watching!')
  puts('-' * 88)
rescue Aws::Errors::ServiceError => e
  puts('Something went wrong with the demo.')
  puts("\t#{e.code}: #{e.message}")
end

run_scenario(ScenarioCreateUserAssumeRole.new(Aws::IAM::Client.new)) if $PROGRAM_NAME == __FILE__
```
+ API の詳細については、「*AWS SDK for Ruby API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachRolePolicy)
  + [CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccessKey)
  + [CreatePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreatePolicy)
  + [CreateRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)
  + [CreateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateUser)
  + [DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccessKey)
  + [DeletePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeletePolicy)
  + [DeleteRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteRole)
  + [DeleteUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUser)
  + [DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUserPolicy)
  + [DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachRolePolicy)
  + [PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_ruby_3_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、ロールポリシーを一覧表示、作成、アタッチ、およびデタッチします。  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[AttachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachRolePolicy)」を参照してください。**

### `AttachUserPolicy`
<a name="iam_AttachUserPolicy_ruby_3_topic"></a>

次のコード例は、`AttachUserPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Attaches a policy to a user
  #
  # @param user_name [String] The name of the user
  # @param policy_arn [String] The Amazon Resource Name (ARN) of the policy
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_user(user_name, policy_arn)
    @iam_client.attach_user_policy(
      user_name: user_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to user: #{e.message}")
    false
  end
```
+  API の詳細については、「AWS SDK for Ruby API リファレンス」の「[AttachUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/AttachUserPolicy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_ruby_3_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、アクセスキーを一覧表示、作成、非アクティブ化、および削除します。  

```
# Manages access keys for IAM users
class AccessKeyManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'AccessKeyManager'
  end

  # Lists access keys for a user
  #
  # @param user_name [String] The name of the user.
  def list_access_keys(user_name)
    response = @iam_client.list_access_keys(user_name: user_name)
    if response.access_key_metadata.empty?
      @logger.info("No access keys found for user '#{user_name}'.")
    else
      response.access_key_metadata.map(&:access_key_id)
    end
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Error listing access keys: cannot find user '#{user_name}'.")
    []
  rescue StandardError => e
    @logger.error("Error listing access keys: #{e.message}")
    []
  end

  # Creates an access key for a user
  #
  # @param user_name [String] The name of the user.
  # @return [Boolean]
  def create_access_key(user_name)
    response = @iam_client.create_access_key(user_name: user_name)
    access_key = response.access_key
    @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}")
    access_key
  rescue Aws::IAM::Errors::LimitExceeded
    @logger.error('Error creating access key: limit exceeded. Cannot create more.')
    nil
  rescue StandardError => e
    @logger.error("Error creating access key: #{e.message}")
    nil
  end

  # Deactivates an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def deactivate_access_key(user_name, access_key_id)
    @iam_client.update_access_key(
      user_name: user_name,
      access_key_id: access_key_id,
      status: 'Inactive'
    )
    true
  rescue StandardError => e
    @logger.error("Error deactivating access key: #{e.message}")
    false
  end

  # Deletes an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def delete_access_key(user_name, access_key_id)
    @iam_client.delete_access_key(
      user_name: user_name,
      access_key_id: access_key_id
    )
    true
  rescue StandardError => e
    @logger.error("Error deleting access key: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[CreateAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccessKey)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_ruby_3_topic"></a>

次のコード例は、`CreateAccountAlias` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アカウントエイリアスを一覧表示、作成、および削除します。  

```
class IAMAliasManager
  # Initializes the IAM client and logger
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists available AWS account aliases.
  def list_aliases
    response = @iam_client.list_account_aliases

    if response.account_aliases.count.positive?
      @logger.info('Account aliases are:')
      response.account_aliases.each { |account_alias| @logger.info("  #{account_alias}") }
    else
      @logger.info('No account aliases found.')
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing account aliases: #{e.message}")
  end

  # Creates an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to create.
  # @return [Boolean] true if the account alias was created; otherwise, false.
  def create_account_alias(account_alias)
    @iam_client.create_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating account alias: #{e.message}")
    false
  end

  # Deletes an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to delete.
  # @return [Boolean] true if the account alias was deleted; otherwise, false.
  def delete_account_alias(account_alias)
    @iam_client.delete_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting account alias: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[CreateAccountAlias](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateAccountAlias)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_ruby_3_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、ロールポリシーを一覧表示、作成、アタッチ、およびデタッチします。  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[CreatePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreatePolicy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_ruby_3_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # 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](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateRole)」を参照してください。**

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_ruby_3_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Creates a service-linked role
  #
  # @param service_name [String] The service name to create the role for.
  # @param description [String] The description of the service-linked role.
  # @param suffix [String] Suffix for customizing role name.
  # @return [String] The name of the created role
  def create_service_linked_role(service_name, description, suffix)
    response = @iam_client.create_service_linked_role(
      aws_service_name: service_name, description: description, custom_suffix: suffix
    )
    role_name = response.role.role_name
    @logger.info("Created service-linked role #{role_name}.")
    role_name
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't create service-linked role for #{service_name}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateServiceLinkedRole)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_ruby_3_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Creates a user and their login profile
  #
  # @param user_name [String] The name of the user
  # @param initial_password [String] The initial password for the user
  # @return [String, nil] The ID of the user if created, or nil if an error occurred
  def create_user(user_name, initial_password)
    response = @iam_client.create_user(user_name: user_name)
    @iam_client.wait_until(:user_exists, user_name: user_name)
    @iam_client.create_login_profile(
      user_name: user_name,
      password: initial_password,
      password_reset_required: true
    )
    @logger.info("User '#{user_name}' created successfully.")
    response.user.user_id
  rescue Aws::IAM::Errors::EntityAlreadyExists
    @logger.error("Error creating user '#{user_name}': user already exists.")
    nil
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating user '#{user_name}': #{e.message}")
    nil
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[CreateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/CreateUser)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_ruby_3_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、アクセスキーを一覧表示、作成、非アクティブ化、および削除します。  

```
# Manages access keys for IAM users
class AccessKeyManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'AccessKeyManager'
  end

  # Lists access keys for a user
  #
  # @param user_name [String] The name of the user.
  def list_access_keys(user_name)
    response = @iam_client.list_access_keys(user_name: user_name)
    if response.access_key_metadata.empty?
      @logger.info("No access keys found for user '#{user_name}'.")
    else
      response.access_key_metadata.map(&:access_key_id)
    end
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Error listing access keys: cannot find user '#{user_name}'.")
    []
  rescue StandardError => e
    @logger.error("Error listing access keys: #{e.message}")
    []
  end

  # Creates an access key for a user
  #
  # @param user_name [String] The name of the user.
  # @return [Boolean]
  def create_access_key(user_name)
    response = @iam_client.create_access_key(user_name: user_name)
    access_key = response.access_key
    @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}")
    access_key
  rescue Aws::IAM::Errors::LimitExceeded
    @logger.error('Error creating access key: limit exceeded. Cannot create more.')
    nil
  rescue StandardError => e
    @logger.error("Error creating access key: #{e.message}")
    nil
  end

  # Deactivates an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def deactivate_access_key(user_name, access_key_id)
    @iam_client.update_access_key(
      user_name: user_name,
      access_key_id: access_key_id,
      status: 'Inactive'
    )
    true
  rescue StandardError => e
    @logger.error("Error deactivating access key: #{e.message}")
    false
  end

  # Deletes an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def delete_access_key(user_name, access_key_id)
    @iam_client.delete_access_key(
      user_name: user_name,
      access_key_id: access_key_id
    )
    true
  rescue StandardError => e
    @logger.error("Error deleting access key: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteAccessKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccessKey)」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_ruby_3_topic"></a>

次のコード例は、`DeleteAccountAlias` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アカウントエイリアスを一覧表示、作成、および削除します。  

```
class IAMAliasManager
  # Initializes the IAM client and logger
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists available AWS account aliases.
  def list_aliases
    response = @iam_client.list_account_aliases

    if response.account_aliases.count.positive?
      @logger.info('Account aliases are:')
      response.account_aliases.each { |account_alias| @logger.info("  #{account_alias}") }
    else
      @logger.info('No account aliases found.')
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing account aliases: #{e.message}")
  end

  # Creates an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to create.
  # @return [Boolean] true if the account alias was created; otherwise, false.
  def create_account_alias(account_alias)
    @iam_client.create_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating account alias: #{e.message}")
    false
  end

  # Deletes an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to delete.
  # @return [Boolean] true if the account alias was deleted; otherwise, false.
  def delete_account_alias(account_alias)
    @iam_client.delete_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting account alias: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteAccountAlias](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteAccountAlias)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_ruby_3_topic"></a>

次のコード例は、`DeleteRole` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Deletes a role and its attached policies.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_role(role_name)
    # Detach and delete attached policies
    @iam_client.list_attached_role_policies(role_name: role_name).each do |response|
      response.attached_policies.each do |policy|
        @iam_client.detach_role_policy({
                                         role_name: role_name,
                                         policy_arn: policy.policy_arn
                                       })
        # Check if the policy is a customer managed policy (not AWS managed)
        unless policy.policy_arn.include?('aws:policy/')
          @iam_client.delete_policy({ policy_arn: policy.policy_arn })
          @logger.info("Deleted customer managed policy #{policy.policy_name}.")
        end
      end
    end

    # Delete the role
    @iam_client.delete_role({ role_name: role_name })
    @logger.info("Deleted role #{role_name}.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't detach policies and delete role #{role_name}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[DeleteRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteRole)」を参照してください。

### `DeleteServerCertificate`
<a name="iam_DeleteServerCertificate_ruby_3_topic"></a>

次のコード例は、`DeleteServerCertificate` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
サーバー証明書を一覧表示、更新、および削除します。  

```
class ServerCertificateManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'ServerCertificateManager'
  end

  # Creates a new server certificate.
  # @param name [String] the name of the server certificate
  # @param certificate_body [String] the contents of the certificate
  # @param private_key [String] the private key contents
  # @return [Boolean] returns true if the certificate was successfully created
  def create_server_certificate(name, certificate_body, private_key)
    @iam_client.upload_server_certificate({
                                            server_certificate_name: name,
                                            certificate_body: certificate_body,
                                            private_key: private_key
                                          })
    true
  rescue Aws::IAM::Errors::ServiceError => e
    puts "Failed to create server certificate: #{e.message}"
    false
  end

  # Lists available server certificate names.
  def list_server_certificate_names
    response = @iam_client.list_server_certificates

    if response.server_certificate_metadata_list.empty?
      @logger.info('No server certificates found.')
      return
    end

    response.server_certificate_metadata_list.each do |certificate_metadata|
      @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}")
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing server certificates: #{e.message}")
  end

  # Updates the name of a server certificate.
  def update_server_certificate_name(current_name, new_name)
    @iam_client.update_server_certificate(
      server_certificate_name: current_name,
      new_server_certificate_name: new_name
    )
    @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error updating server certificate name: #{e.message}")
    false
  end

  # Deletes a server certificate.
  def delete_server_certificate(name)
    @iam_client.delete_server_certificate(server_certificate_name: name)
    @logger.info("Server certificate '#{name}' deleted.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting server certificate: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteServerCertificate](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteServerCertificate)」を参照してください。

### `DeleteServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_ruby_3_topic"></a>

次のコード例は、`DeleteServiceLinkedRole` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Deletes a service-linked role.
  #
  # @param role_name [String] The name of the role to delete.
  def delete_service_linked_role(role_name)
    response = @iam_client.delete_service_linked_role(role_name: role_name)
    task_id = response.deletion_task_id
    check_deletion_status(role_name, task_id)
  rescue Aws::Errors::ServiceError => e
    handle_deletion_error(e, role_name)
  end

  private

  # Checks the deletion status of a service-linked role
  #
  # @param role_name [String] The name of the role being deleted
  # @param task_id [String] The task ID for the deletion process
  def check_deletion_status(role_name, task_id)
    loop do
      response = @iam_client.get_service_linked_role_deletion_status(
        deletion_task_id: task_id
      )
      status = response.status
      @logger.info("Deletion of #{role_name} #{status}.")
      break if %w[SUCCEEDED FAILED].include?(status)

      sleep(3)
    end
  end

  # Handles deletion error
  #
  # @param e [Aws::Errors::ServiceError] The error encountered during deletion
  # @param role_name [String] The name of the role attempted to delete
  def handle_deletion_error(e, role_name)
    return if e.code == 'NoSuchEntity'

    @logger.error("Couldn't delete #{role_name}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteServiceLinkedRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteServiceLinkedRole)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_ruby_3_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Deletes a user and their associated resources
  #
  # @param user_name [String] The name of the user to delete
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUser)」を参照してください。

### `DeleteUserPolicy`
<a name="iam_DeleteUserPolicy_ruby_3_topic"></a>

次のコード例は、`DeleteUserPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Deletes a user and their associated resources
  #
  # @param user_name [String] The name of the user to delete
  def delete_user(user_name)
    user = @iam_client.list_access_keys(user_name: user_name).access_key_metadata
    user.each do |key|
      @iam_client.delete_access_key({ access_key_id: key.access_key_id, user_name: user_name })
      @logger.info("Deleted access key #{key.access_key_id} for user '#{user_name}'.")
    end

    @iam_client.delete_user(user_name: user_name)
    @logger.info("Deleted user '#{user_name}'.")
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting user '#{user_name}': #{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DeleteUserPolicy)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_ruby_3_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、ロールポリシーを一覧表示、作成、アタッチ、およびデタッチします。  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DetachRolePolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachRolePolicy)」を参照してください。

### `DetachUserPolicy`
<a name="iam_DetachUserPolicy_ruby_3_topic"></a>

次のコード例は、`DetachUserPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Detaches a policy from a user
  #
  # @param user_name [String] The name of the user
  # @param policy_arn [String] The ARN of the policy to detach
  # @return [Boolean] true if the policy was successfully detached, false otherwise
  def detach_user_policy(user_name, policy_arn)
    @iam_client.detach_user_policy(
      user_name: user_name,
      policy_arn: policy_arn
    )
    @logger.info("Policy '#{policy_arn}' detached from user '#{user_name}' successfully.")
    true
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error('Error detaching policy: Policy or user does not exist.')
    false
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from user '#{user_name}': #{e.message}")
    false
  end
```
+  API の詳細については、「AWS SDK for Ruby API リファレンス」の「[DetachUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/DetachUserPolicy)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_ruby_3_topic"></a>

次のコード例は、`GetAccountPasswordPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
# Class to manage IAM account password policies
class PasswordPolicyManager
  attr_accessor :iam_client, :logger

  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'IAMPolicyManager'
  end

  # Retrieves and logs the account password policy
  def print_account_password_policy
    response = @iam_client.get_account_password_policy
    @logger.info("The account password policy is: #{response.password_policy.to_h}")
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.info('The account does not have a password policy.')
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't print the account password policy. Error: #{e.code} - #{e.message}")
    raise
  end
end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetAccountPasswordPolicy)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_ruby_3_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetPolicy)」を参照してください。

### `GetRole`
<a name="iam_GetRole_ruby_3_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Gets data about a role.
  #
  # @param name [String] The name of the role to look up.
  # @return [Aws::IAM::Role] The retrieved role.
  def get_role(name)
    role = @iam_client.get_role({
                                  role_name: name
                                }).role
    puts("Got data for role '#{role.role_name}'. Its ARN is '#{role.arn}'.")
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't get data for role '#{name}' Here's why:")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    role
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[GetRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetRole)」を参照してください。

### `GetUser`
<a name="iam_GetUser_ruby_3_topic"></a>

次のコード例は、`GetUser` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Retrieves a user's details
  #
  # @param user_name [String] The name of the user to retrieve
  # @return [Aws::IAM::Types::User, nil] The user object if found, or nil if an error occurred
  def get_user(user_name)
    response = @iam_client.get_user(user_name: user_name)
    response.user
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("User '#{user_name}' not found.")
    nil
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error retrieving user '#{user_name}': #{e.message}")
    nil
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[GetUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/GetUser)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_ruby_3_topic"></a>

次のコード例は、`ListAccessKeys` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、アクセスキーを一覧表示、作成、非アクティブ化、および削除します。  

```
# Manages access keys for IAM users
class AccessKeyManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'AccessKeyManager'
  end

  # Lists access keys for a user
  #
  # @param user_name [String] The name of the user.
  def list_access_keys(user_name)
    response = @iam_client.list_access_keys(user_name: user_name)
    if response.access_key_metadata.empty?
      @logger.info("No access keys found for user '#{user_name}'.")
    else
      response.access_key_metadata.map(&:access_key_id)
    end
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Error listing access keys: cannot find user '#{user_name}'.")
    []
  rescue StandardError => e
    @logger.error("Error listing access keys: #{e.message}")
    []
  end

  # Creates an access key for a user
  #
  # @param user_name [String] The name of the user.
  # @return [Boolean]
  def create_access_key(user_name)
    response = @iam_client.create_access_key(user_name: user_name)
    access_key = response.access_key
    @logger.info("Access key created for user '#{user_name}': #{access_key.access_key_id}")
    access_key
  rescue Aws::IAM::Errors::LimitExceeded
    @logger.error('Error creating access key: limit exceeded. Cannot create more.')
    nil
  rescue StandardError => e
    @logger.error("Error creating access key: #{e.message}")
    nil
  end

  # Deactivates an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def deactivate_access_key(user_name, access_key_id)
    @iam_client.update_access_key(
      user_name: user_name,
      access_key_id: access_key_id,
      status: 'Inactive'
    )
    true
  rescue StandardError => e
    @logger.error("Error deactivating access key: #{e.message}")
    false
  end

  # Deletes an access key
  #
  # @param user_name [String] The name of the user.
  # @param access_key_id [String] The ID for the access key.
  # @return [Boolean]
  def delete_access_key(user_name, access_key_id)
    @iam_client.delete_access_key(
      user_name: user_name,
      access_key_id: access_key_id
    )
    true
  rescue StandardError => e
    @logger.error("Error deleting access key: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListAccessKeys](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListAccessKeys)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_ruby_3_topic"></a>

次のコード例は、`ListAccountAliases` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
アカウントエイリアスを一覧表示、作成、および削除します。  

```
class IAMAliasManager
  # Initializes the IAM client and logger
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client.
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists available AWS account aliases.
  def list_aliases
    response = @iam_client.list_account_aliases

    if response.account_aliases.count.positive?
      @logger.info('Account aliases are:')
      response.account_aliases.each { |account_alias| @logger.info("  #{account_alias}") }
    else
      @logger.info('No account aliases found.')
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing account aliases: #{e.message}")
  end

  # Creates an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to create.
  # @return [Boolean] true if the account alias was created; otherwise, false.
  def create_account_alias(account_alias)
    @iam_client.create_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating account alias: #{e.message}")
    false
  end

  # Deletes an AWS account alias.
  #
  # @param account_alias [String] The name of the account alias to delete.
  # @return [Boolean] true if the account alias was deleted; otherwise, false.
  def delete_account_alias(account_alias)
    @iam_client.delete_account_alias(account_alias: account_alias)
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting account alias: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListAccountAliases](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListAccountAliases)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_ruby_3_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、ロールポリシーを一覧表示、作成、アタッチ、およびデタッチします。  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListAttachedRolePolicies)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_ruby_3_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
# A class to manage IAM operations via the AWS SDK client
class IamGroupManager
  # Initializes the IamGroupManager class
  # @param iam_client [Aws::IAM::Client] An instance of the IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists up to a specified number of groups for the account.
  # @param count [Integer] The maximum number of groups to list.
  # @return [Aws::IAM::Client::Response]
  def list_groups(count)
    response = @iam_client.list_groups(max_items: count)
    response.groups.each do |group|
      @logger.info("\t#{group.group_name}")
    end
    response
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't list groups for the account. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[ListGroup](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListGroups)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_ruby_3_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
このサンプルモジュールは、ロールポリシーを一覧表示、作成、アタッチ、およびデタッチします。  

```
# Manages policies in AWS Identity and Access Management (IAM)
class RolePolicyManager
  # Initialize with an AWS IAM client
  #
  # @param iam_client [Aws::IAM::Client] An initialized IAM client
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'PolicyManager'
  end

  # Creates a policy
  #
  # @param policy_name [String] The name of the policy
  # @param policy_document [Hash] The policy document
  # @return [String] The policy ARN if successful, otherwise nil
  def create_policy(policy_name, policy_document)
    response = @iam_client.create_policy(
      policy_name: policy_name,
      policy_document: policy_document.to_json
    )
    response.policy.arn
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error creating policy: #{e.message}")
    nil
  end

  # Fetches an IAM policy by its ARN
  # @param policy_arn [String] the ARN of the IAM policy to retrieve
  # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found
  def get_policy(policy_arn)
    response = @iam_client.get_policy(policy_arn: policy_arn)
    policy = response.policy
    @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.")
    policy
  rescue Aws::IAM::Errors::NoSuchEntity
    @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.")
    raise
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}")
    raise
  end

  # Attaches a policy to a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def attach_policy_to_role(role_name, policy_arn)
    @iam_client.attach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error attaching policy to role: #{e.message}")
    false
  end

  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end

  # Detaches a policy from a role
  #
  # @param role_name [String] The name of the role
  # @param policy_arn [String] The policy ARN
  # @return [Boolean] true if successful, false otherwise
  def detach_policy_from_role(role_name, policy_arn)
    @iam_client.detach_role_policy(
      role_name: role_name,
      policy_arn: policy_arn
    )
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error detaching policy from role: #{e.message}")
    false
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListPolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListPolicies)」を参照してください。**

### `ListRolePolicies`
<a name="iam_ListRolePolicies_ruby_3_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Lists policy ARNs attached to a role
  #
  # @param role_name [String] The name of the role
  # @return [Array<String>] List of policy ARNs
  def list_attached_policy_arns(role_name)
    response = @iam_client.list_attached_role_policies(role_name: role_name)
    response.attached_policies.map(&:policy_arn)
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing policies attached to role: #{e.message}")
    []
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[ListRolePolicies](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListRolePolicies)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_ruby_3_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Lists IAM roles up to a specified count.
  # @param count [Integer] the maximum number of roles to list.
  # @return [Array<String>] the names of the roles.
  def list_roles(count)
    role_names = []
    roles_counted = 0

    @iam_client.list_roles.each_page do |page|
      page.roles.each do |role|
        break if roles_counted >= count

        @logger.info("\t#{roles_counted + 1}: #{role.role_name}")
        role_names << role.role_name
        roles_counted += 1
      end
      break if roles_counted >= count
    end

    role_names
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't list roles for the account. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[ListRoles](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListRoles)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_ruby_3_topic"></a>

次のコード例は、`ListSAMLProviders` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
class SamlProviderLister
  # Initializes the SamlProviderLister with IAM client and a logger.
  # @param iam_client [Aws::IAM::Client] The IAM client object.
  # @param logger [Logger] The logger object for logging output.
  def initialize(iam_client, logger = Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
  end

  # Lists up to a specified number of SAML providers for the account.
  # @param count [Integer] The maximum number of providers to list.
  # @return [Aws::IAM::Client::Response]
  def list_saml_providers(count)
    response = @iam_client.list_saml_providers
    response.saml_provider_list.take(count).each do |provider|
      @logger.info("\t#{provider.arn}")
    end
    response
  rescue Aws::Errors::ServiceError => e
    @logger.error("Couldn't list SAML providers. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    raise
  end
end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[ListSAMLProviders](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListSAMLProviders)」を参照してください。

### `ListServerCertificates`
<a name="iam_ListServerCertificates_ruby_3_topic"></a>

次のコード例は、`ListServerCertificates` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
サーバー証明書を一覧表示、更新、および削除します。  

```
class ServerCertificateManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'ServerCertificateManager'
  end

  # Creates a new server certificate.
  # @param name [String] the name of the server certificate
  # @param certificate_body [String] the contents of the certificate
  # @param private_key [String] the private key contents
  # @return [Boolean] returns true if the certificate was successfully created
  def create_server_certificate(name, certificate_body, private_key)
    @iam_client.upload_server_certificate({
                                            server_certificate_name: name,
                                            certificate_body: certificate_body,
                                            private_key: private_key
                                          })
    true
  rescue Aws::IAM::Errors::ServiceError => e
    puts "Failed to create server certificate: #{e.message}"
    false
  end

  # Lists available server certificate names.
  def list_server_certificate_names
    response = @iam_client.list_server_certificates

    if response.server_certificate_metadata_list.empty?
      @logger.info('No server certificates found.')
      return
    end

    response.server_certificate_metadata_list.each do |certificate_metadata|
      @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}")
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing server certificates: #{e.message}")
  end

  # Updates the name of a server certificate.
  def update_server_certificate_name(current_name, new_name)
    @iam_client.update_server_certificate(
      server_certificate_name: current_name,
      new_server_certificate_name: new_name
    )
    @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error updating server certificate name: #{e.message}")
    false
  end

  # Deletes a server certificate.
  def delete_server_certificate(name)
    @iam_client.delete_server_certificate(server_certificate_name: name)
    @logger.info("Server certificate '#{name}' deleted.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting server certificate: #{e.message}")
    false
  end
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListServerCertificates](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListServerCertificates)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_ruby_3_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Lists all users in the AWS account
  #
  # @return [Array<Aws::IAM::Types::User>] An array of user objects
  def list_users
    users = []
    @iam_client.list_users.each_page do |page|
      page.users.each do |user|
        users << user
      end
    end
    users
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing users: #{e.message}")
    []
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListUsers](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/ListUsers)」を参照してください。

### `PutUserPolicy`
<a name="iam_PutUserPolicy_ruby_3_topic"></a>

次のコード例は、`PutUserPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Creates an inline policy for a specified user.
  # @param username [String] The name of the IAM user.
  # @param policy_name [String] The name of the policy to create.
  # @param policy_document [String] The JSON policy document.
  # @return [Boolean]
  def create_user_policy(username, policy_name, policy_document)
    @iam_client.put_user_policy({
                                  user_name: username,
                                  policy_name: policy_name,
                                  policy_document: policy_document
                                })
    @logger.info("Policy #{policy_name} created for user #{username}.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Couldn't create policy #{policy_name} for user #{username}. Here's why:")
    @logger.error("\t#{e.code}: #{e.message}")
    false
  end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[PutUserPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/PutUserPolicy)」を参照してください。

### `UpdateServerCertificate`
<a name="iam_UpdateServerCertificate_ruby_3_topic"></a>

次のコード例は、`UpdateServerCertificate` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。
サーバー証明書を一覧表示、更新、および削除します。  

```
class ServerCertificateManager
  def initialize(iam_client, logger: Logger.new($stdout))
    @iam_client = iam_client
    @logger = logger
    @logger.progname = 'ServerCertificateManager'
  end

  # Creates a new server certificate.
  # @param name [String] the name of the server certificate
  # @param certificate_body [String] the contents of the certificate
  # @param private_key [String] the private key contents
  # @return [Boolean] returns true if the certificate was successfully created
  def create_server_certificate(name, certificate_body, private_key)
    @iam_client.upload_server_certificate({
                                            server_certificate_name: name,
                                            certificate_body: certificate_body,
                                            private_key: private_key
                                          })
    true
  rescue Aws::IAM::Errors::ServiceError => e
    puts "Failed to create server certificate: #{e.message}"
    false
  end

  # Lists available server certificate names.
  def list_server_certificate_names
    response = @iam_client.list_server_certificates

    if response.server_certificate_metadata_list.empty?
      @logger.info('No server certificates found.')
      return
    end

    response.server_certificate_metadata_list.each do |certificate_metadata|
      @logger.info("Certificate Name: #{certificate_metadata.server_certificate_name}")
    end
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error listing server certificates: #{e.message}")
  end

  # Updates the name of a server certificate.
  def update_server_certificate_name(current_name, new_name)
    @iam_client.update_server_certificate(
      server_certificate_name: current_name,
      new_server_certificate_name: new_name
    )
    @logger.info("Server certificate name updated from '#{current_name}' to '#{new_name}'.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error updating server certificate name: #{e.message}")
    false
  end

  # Deletes a server certificate.
  def delete_server_certificate(name)
    @iam_client.delete_server_certificate(server_certificate_name: name)
    @logger.info("Server certificate '#{name}' deleted.")
    true
  rescue Aws::IAM::Errors::ServiceError => e
    @logger.error("Error deleting server certificate: #{e.message}")
    false
  end
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[UpdateServerCertificate](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/UpdateServerCertificate)」を参照してください。**

### `UpdateUser`
<a name="iam_UpdateUser_ruby_3_topic"></a>

次のコード例は、`UpdateUser` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Updates an IAM user's name
  #
  # @param current_name [String] The current name of the user
  # @param new_name [String] The new name of the user
  def update_user_name(current_name, new_name)
    @iam_client.update_user(user_name: current_name, new_user_name: new_name)
    true
  rescue StandardError => e
    @logger.error("Error updating user name from '#{current_name}' to '#{new_name}': #{e.message}")
    false
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[UpdateUser](https://docs.aws.amazon.com/goto/SdkForRubyV3/iam-2010-05-08/UpdateUser)」を参照してください。**

# SDK for Ruby を使用する Kinesis の例
<a name="ruby_3_kinesis_code_examples"></a>

次のコード例は、Kinesis AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_ruby_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での Kinesis イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
require 'aws-sdk'

def lambda_handler(event:, context:)
  event['Records'].each do |record|
    begin
      puts "Processed Kinesis Event - EventID: #{record['eventID']}"
      record_data = get_record_data_async(record['kinesis'])
      puts "Record Data: #{record_data}"
      # TODO: Do interesting work based on the new data
    rescue => err
      $stderr.puts "An error occurred #{err}"
      raise err
    end
  end
  puts "Successfully processed #{event['Records'].length} records."
end

def get_record_data_async(payload)
  data = Base64.decode64(payload['data']).force_encoding('UTF-8')
  # Placeholder for actual async work
  # You can use Ruby's asynchronous programming tools like async/await or fibers here.
  return data
end
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_ruby_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で Kinesis バッチアイテム失敗のレポートをします。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
require 'aws-sdk'

def lambda_handler(event:, context:)
  batch_item_failures = []

  event['Records'].each do |record|
    begin
      puts "Processed Kinesis Event - EventID: #{record['eventID']}"
      record_data = get_record_data_async(record['kinesis'])
      puts "Record Data: #{record_data}"
      # TODO: Do interesting work based on the new data
    rescue StandardError => err
      puts "An error occurred #{err}"
      # Since we are working with streams, we can return the failed item immediately.
      # Lambda will immediately begin to retry processing from this failed item onwards.
      return { batchItemFailures: [{ itemIdentifier: record['kinesis']['sequenceNumber'] }] }
    end
  end

  puts "Successfully processed #{event['Records'].length} records."
  { batchItemFailures: batch_item_failures }
end

def get_record_data_async(payload)
  data = Base64.decode64(payload['data']).force_encoding('utf-8')
  # Placeholder for actual async work
  sleep(1)
  data
end
```

# AWS KMS SDK for Ruby を使用した の例
<a name="ruby_3_kms_code_examples"></a>

次のコード例は、 AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateKey`
<a name="kms_CreateKey_ruby_3_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-kms' # v2: require 'aws-sdk'

# Create a AWS KMS key.
# As long we are only encrypting small amounts of data (4 KiB or less) directly,
# a KMS key is fine for our purposes.
# For larger amounts of data,
# use the KMS key to encrypt a data encryption key (DEK).

client = Aws::KMS::Client.new

resp = client.create_key({
                           tags: [
                             {
                               tag_key: 'CreatedBy',
                               tag_value: 'ExampleUser'
                             }
                           ]
                         })

puts resp.key_metadata.key_id
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[CreateKey](https://docs.aws.amazon.com/goto/SdkForRubyV3/kms-2014-11-01/CreateKey)」を参照してください。

### `Decrypt`
<a name="kms_Decrypt_ruby_3_topic"></a>

次のコード例は、`Decrypt` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-kms' # v2: require 'aws-sdk'

# Decrypted blob

blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1'
blob_packed = [blob].pack('H*')

client = Aws::KMS::Client.new(region: 'us-west-2')

resp = client.decrypt({
                        ciphertext_blob: blob_packed
                      })

puts 'Raw text: '
puts resp.plaintext
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[Decrypt](https://docs.aws.amazon.com/goto/SdkForRubyV3/kms-2014-11-01/Decrypt)」を参照してください。**

### `Encrypt`
<a name="kms_Encrypt_ruby_3_topic"></a>

次のコード例は、`Encrypt` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-kms' # v2: require 'aws-sdk'

# ARN of the AWS KMS key.
#
# Replace the fictitious key ARN with a valid key ID

keyId = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'

text = '1234567890'

client = Aws::KMS::Client.new(region: 'us-west-2')

resp = client.encrypt({
                        key_id: keyId,
                        plaintext: text
                      })

# Display a readable version of the resulting encrypted blob.
puts 'Blob:'
puts resp.ciphertext_blob.unpack('H*')
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[Encrypt](https://docs.aws.amazon.com/goto/SdkForRubyV3/kms-2014-11-01/Encrypt)」を参照してください。**

### `ReEncrypt`
<a name="kms_ReEncrypt_ruby_3_topic"></a>

次のコード例は、`ReEncrypt` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/kms#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-kms' # v2: require 'aws-sdk'

# Human-readable version of the ciphertext of the data to reencrypt.

blob = '01020200785d68faeec386af1057904926253051eb2919d3c16078badf65b808b26dd057c101747cadf3593596e093d4ffbf22434a6d00000068306606092a864886f70d010706a0593057020100305206092a864886f70d010701301e060960864801650304012e3011040c9d629e573683972cdb7d94b30201108025b20b060591b02ca0deb0fbdfc2f86c8bfcb265947739851ad56f3adce91eba87c59691a9a1'
sourceCiphertextBlob = [blob].pack('H*')

# Replace the fictitious key ARN with a valid key ID

destinationKeyId = 'arn:aws:kms:us-west-2:111122223333:key/0987dcba-09fe-87dc-65ba-ab0987654321'

client = Aws::KMS::Client.new(region: 'us-west-2')

resp = client.re_encrypt({
                           ciphertext_blob: sourceCiphertextBlob,
                           destination_key_id: destinationKeyId
                         })

# Display a readable version of the resulting re-encrypted blob.
puts 'Blob:'
puts resp.ciphertext_blob.unpack('H*')
```
+  API の詳細については、**「AWS SDK for Ruby API リファレンス」の「[ReEncrypt](https://docs.aws.amazon.com/goto/SdkForRubyV3/kms-2014-11-01/ReEncrypt)」を参照してください。

# SDK for Ruby を使用した Lambda の例
<a name="ruby_3_lambda_code_examples"></a>

次のコード例は、Lambda AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Lambda
<a name="lambda_Hello_ruby_3_topic"></a>

次のコード例は、Lambda の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-lambda'

# Creates an AWS Lambda client using the default credentials and configuration
def lambda_client
  Aws::Lambda::Client.new
end

# Lists the Lambda functions in your AWS account, paginating the results if necessary
def list_lambda_functions
  lambda = lambda_client

  # Use a pagination iterator to list all functions
  functions = []
  lambda.list_functions.each_page do |page|
    functions.concat(page.functions)
  end

  # Print the name and ARN of each function
  functions.each do |function|
    puts "Function name: #{function.function_name}"
    puts "Function ARN: #{function.function_arn}"
    puts
  end

  puts "Total functions: #{functions.count}"
end

list_lambda_functions if __FILE__ == $PROGRAM_NAME
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListFunctions)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_ruby_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。
ログを書き込むことができる Lambda 関数に前提条件となる IAM アクセス権限を設定します。  

```
  # Get an AWS Identity and Access Management (IAM) role.
  #
  # @param iam_role_name: The name of the role to retrieve.
  # @param action: Whether to create or destroy the IAM apparatus.
  # @return: The IAM role.
  def manage_iam(iam_role_name, action)
    case action
    when 'create'
      create_iam_role(iam_role_name)
    when 'destroy'
      destroy_iam_role(iam_role_name)
    else
      raise "Incorrect action provided. Must provide 'create' or 'destroy'"
    end
  end

  private

  def create_iam_role(iam_role_name)
    role_policy = {
      'Version': '2012-10-17',
      'Statement': [
        {
          'Effect': 'Allow',
          'Principal': { 'Service': 'lambda.amazonaws.com' },
          'Action': 'sts:AssumeRole'
        }
      ]
    }
    role = @iam_client.create_role(
      role_name: iam_role_name,
      assume_role_policy_document: role_policy.to_json
    )
    @iam_client.attach_role_policy(
      {
        policy_arn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole',
        role_name: iam_role_name
      }
    )
    wait_for_role_to_exist(iam_role_name)
    @logger.debug("Successfully created IAM role: #{role['role']['arn']}")
    sleep(10)
    [role, role_policy.to_json]
  end

  def destroy_iam_role(iam_role_name)
    @iam_client.detach_role_policy(
      {
        policy_arn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole',
        role_name: iam_role_name
      }
    )
    @iam_client.delete_role(role_name: iam_role_name)
    @logger.debug("Detached policy & deleted IAM role: #{iam_role_name}")
  end

  def wait_for_role_to_exist(iam_role_name)
    @iam_client.wait_until(:role_exists, { role_name: iam_role_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
  end
```
呼び出しパラメータとして指定された数値を増やす Lambda ハンドラーを定義します。  

```
require 'logger'

# A function that increments a whole number by one (1) and logs the result.
# Requires a manually-provided runtime parameter, 'number', which must be Int
#
# @param event [Hash] Parameters sent when the function is invoked
# @param context [Hash] Methods and properties that provide information
# about the invocation, function, and execution environment.
# @return incremented_number [String] The incremented number.
def lambda_handler(event:, context:)
  logger = Logger.new($stdout)
  log_level = ENV['LOG_LEVEL']
  logger.level = case log_level
                 when 'debug'
                   Logger::DEBUG
                 when 'info'
                   Logger::INFO
                 else
                   Logger::ERROR
                 end
  logger.debug('This is a debug log message.')
  logger.info('This is an info log message. Code executed successfully!')
  number = event['number'].to_i
  incremented_number = number + 1
  logger.info("You provided #{number.round} and it was incremented to #{incremented_number.round}")
  incremented_number.round.to_s
end
```
Lambda 関数のデプロイパッケージを圧縮します。  

```
  # Creates a Lambda deployment package in .zip format.
  #
  # @param source_file: The name of the object, without suffix, for the Lambda file and zip.
  # @return: The deployment package.
  def create_deployment_package(source_file)
    Dir.chdir(File.dirname(__FILE__))
    if File.exist?('lambda_function.zip')
      File.delete('lambda_function.zip')
      @logger.debug('Deleting old zip: lambda_function.zip')
    end
    Zip::File.open('lambda_function.zip', create: true) do |zipfile|
      zipfile.add('lambda_function.rb', "#{source_file}.rb")
    end
    @logger.debug("Zipping #{source_file}.rb into: lambda_function.zip.")
    File.read('lambda_function.zip').to_s
  rescue StandardError => e
    @logger.error("There was an error creating deployment package:\n #{e.message}")
  end
```
新しい Lambda 関数の作成  

```
  # Deploys a Lambda function.
  #
  # @param function_name: The name of the Lambda function.
  # @param handler_name: The fully qualified name of the handler function.
  # @param role_arn: The IAM role to use for the function.
  # @param deployment_package: The deployment package that contains the function code in .zip format.
  # @return: The Amazon Resource Name (ARN) of the newly created function.
  def create_function(function_name, handler_name, role_arn, deployment_package)
    response = @lambda_client.create_function({
                                                role: role_arn.to_s,
                                                function_name: function_name,
                                                handler: handler_name,
                                                runtime: 'ruby2.7',
                                                code: {
                                                  zip_file: deployment_package
                                                },
                                                environment: {
                                                  variables: {
                                                    'LOG_LEVEL' => 'info'
                                                  }
                                                }
                                              })
    @lambda_client.wait_until(:function_active_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
    response
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error creating #{function_name}:\n #{e.message}")
  rescue Aws::Waiters::Errors::WaiterFailed => e
    @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}")
  end
```
オプションのランタイムパラメータを使用して Lambda 関数を呼び出します。  

```
  # Invokes a Lambda function.
  # @param function_name [String] The name of the function to invoke.
  # @param payload [nil] Payload containing runtime parameters.
  # @return [Object] The response from the function invocation.
  def invoke_function(function_name, payload = nil)
    params = { function_name: function_name }
    params[:payload] = payload unless payload.nil?
    @lambda_client.invoke(params)
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error executing #{function_name}:\n #{e.message}")
  end
```
Lambda 関数の設定を更新して、新しい環境変数を挿入します。  

```
  # Updates the environment variables for a Lambda function.
  # @param function_name: The name of the function to update.
  # @param log_level: The log level of the function.
  # @return: Data about the update, including the status.
  def update_function_configuration(function_name, log_level)
    @lambda_client.update_function_configuration({
                                                   function_name: function_name,
                                                   environment: {
                                                     variables: {
                                                       'LOG_LEVEL' => log_level
                                                     }
                                                   }
                                                 })
    @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error updating configurations for #{function_name}:\n #{e.message}")
  rescue Aws::Waiters::Errors::WaiterFailed => e
    @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}")
  end
```
Lambda 関数のコードを、別のコードを含む別のデプロイパッケージで更新します。  

```
  # Updates the code for a Lambda function by submitting a .zip archive that contains
  # the code for the function.
  #
  # @param function_name: The name of the function to update.
  # @param deployment_package: The function code to update, packaged as bytes in
  #                            .zip format.
  # @return: Data about the update, including the status.
  def update_function_code(function_name, deployment_package)
    @lambda_client.update_function_code(
      function_name: function_name,
      zip_file: deployment_package
    )
    @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error updating function code for: #{function_name}:\n #{e.message}")
    nil
  rescue Aws::Waiters::Errors::WaiterFailed => e
    @logger.error("Failed waiting for #{function_name} to update:\n #{e.message}")
  end
```
組み込みのペジネーターを使用して、既存のすべての Lambda 関数を一覧表示します。  

```
  # Lists the Lambda functions for the current account.
  def list_functions
    functions = []
    @lambda_client.list_functions.each do |response|
      response['functions'].each do |function|
        functions.append(function['function_name'])
      end
    end
    functions
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error listing functions:\n #{e.message}")
  end
```
特定の Lambda 関数を削除します。  

```
  # Deletes a Lambda function.
  # @param function_name: The name of the function to delete.
  def delete_function(function_name)
    print "Deleting function: #{function_name}..."
    @lambda_client.delete_function(
      function_name: function_name
    )
    print 'Done!'.green
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error deleting #{function_name}:\n #{e.message}")
  end
```
+ API の詳細については、「*AWS SDK for Ruby API リファレンス*」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/CreateFunction)
  + [DeleteFunction](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteFunction)
  + [GetFunction](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetFunction)
  + [Invoke](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/Invoke)
  + [ListFunctions](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListFunctions)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionCode)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionConfiguration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_ruby_3_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper
  attr_accessor :lambda_client, :cloudwatch_client, :iam_client

  def initialize
    @lambda_client = Aws::Lambda::Client.new
    @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')
    @iam_client = Aws::IAM::Client.new(region: 'us-east-1')
    @logger = Logger.new($stdout)
    @logger.level = Logger::WARN
  end

  # Deploys a Lambda function.
  #
  # @param function_name: The name of the Lambda function.
  # @param handler_name: The fully qualified name of the handler function.
  # @param role_arn: The IAM role to use for the function.
  # @param deployment_package: The deployment package that contains the function code in .zip format.
  # @return: The Amazon Resource Name (ARN) of the newly created function.
  def create_function(function_name, handler_name, role_arn, deployment_package)
    response = @lambda_client.create_function({
                                                role: role_arn.to_s,
                                                function_name: function_name,
                                                handler: handler_name,
                                                runtime: 'ruby2.7',
                                                code: {
                                                  zip_file: deployment_package
                                                },
                                                environment: {
                                                  variables: {
                                                    'LOG_LEVEL' => 'info'
                                                  }
                                                }
                                              })
    @lambda_client.wait_until(:function_active_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
    response
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error creating #{function_name}:\n #{e.message}")
  rescue Aws::Waiters::Errors::WaiterFailed => e
    @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}")
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[CreateFunction](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/CreateFunction)」を参照してください。**

### `DeleteFunction`
<a name="lambda_DeleteFunction_ruby_3_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper
  attr_accessor :lambda_client, :cloudwatch_client, :iam_client

  def initialize
    @lambda_client = Aws::Lambda::Client.new
    @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')
    @iam_client = Aws::IAM::Client.new(region: 'us-east-1')
    @logger = Logger.new($stdout)
    @logger.level = Logger::WARN
  end

  # Deletes a Lambda function.
  # @param function_name: The name of the function to delete.
  def delete_function(function_name)
    print "Deleting function: #{function_name}..."
    @lambda_client.delete_function(
      function_name: function_name
    )
    print 'Done!'.green
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error deleting #{function_name}:\n #{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteFunction](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/DeleteFunction)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_ruby_3_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper
  attr_accessor :lambda_client, :cloudwatch_client, :iam_client

  def initialize
    @lambda_client = Aws::Lambda::Client.new
    @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')
    @iam_client = Aws::IAM::Client.new(region: 'us-east-1')
    @logger = Logger.new($stdout)
    @logger.level = Logger::WARN
  end

  # Gets data about a Lambda function.
  #
  # @param function_name: The name of the function.
  # @return response: The function data, or nil if no such function exists.
  def get_function(function_name)
    @lambda_client.get_function(
      {
        function_name: function_name
      }
    )
  rescue Aws::Lambda::Errors::ResourceNotFoundException => e
    @logger.debug("Could not find function: #{function_name}:\n #{e.message}")
    nil
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetFunction](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/GetFunction)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_ruby_3_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper
  attr_accessor :lambda_client, :cloudwatch_client, :iam_client

  def initialize
    @lambda_client = Aws::Lambda::Client.new
    @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')
    @iam_client = Aws::IAM::Client.new(region: 'us-east-1')
    @logger = Logger.new($stdout)
    @logger.level = Logger::WARN
  end

  # Invokes a Lambda function.
  # @param function_name [String] The name of the function to invoke.
  # @param payload [nil] Payload containing runtime parameters.
  # @return [Object] The response from the function invocation.
  def invoke_function(function_name, payload = nil)
    params = { function_name: function_name }
    params[:payload] = payload unless payload.nil?
    @lambda_client.invoke(params)
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error executing #{function_name}:\n #{e.message}")
  end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[Invoke](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/Invoke)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_ruby_3_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper
  attr_accessor :lambda_client, :cloudwatch_client, :iam_client

  def initialize
    @lambda_client = Aws::Lambda::Client.new
    @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')
    @iam_client = Aws::IAM::Client.new(region: 'us-east-1')
    @logger = Logger.new($stdout)
    @logger.level = Logger::WARN
  end

  # Lists the Lambda functions for the current account.
  def list_functions
    functions = []
    @lambda_client.list_functions.each do |response|
      response['functions'].each do |function|
        functions.append(function['function_name'])
      end
    end
    functions
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error listing functions:\n #{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListFunctions](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/ListFunctions)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_ruby_3_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper
  attr_accessor :lambda_client, :cloudwatch_client, :iam_client

  def initialize
    @lambda_client = Aws::Lambda::Client.new
    @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')
    @iam_client = Aws::IAM::Client.new(region: 'us-east-1')
    @logger = Logger.new($stdout)
    @logger.level = Logger::WARN
  end

  # Updates the code for a Lambda function by submitting a .zip archive that contains
  # the code for the function.
  #
  # @param function_name: The name of the function to update.
  # @param deployment_package: The function code to update, packaged as bytes in
  #                            .zip format.
  # @return: Data about the update, including the status.
  def update_function_code(function_name, deployment_package)
    @lambda_client.update_function_code(
      function_name: function_name,
      zip_file: deployment_package
    )
    @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error updating function code for: #{function_name}:\n #{e.message}")
    nil
  rescue Aws::Waiters::Errors::WaiterFailed => e
    @logger.error("Failed waiting for #{function_name} to update:\n #{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[UpdateFunctionCode](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionCode)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_ruby_3_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/lambda#code-examples)での設定と実行の方法を確認してください。

```
class LambdaWrapper
  attr_accessor :lambda_client, :cloudwatch_client, :iam_client

  def initialize
    @lambda_client = Aws::Lambda::Client.new
    @cloudwatch_client = Aws::CloudWatchLogs::Client.new(region: 'us-east-1')
    @iam_client = Aws::IAM::Client.new(region: 'us-east-1')
    @logger = Logger.new($stdout)
    @logger.level = Logger::WARN
  end

  # Updates the environment variables for a Lambda function.
  # @param function_name: The name of the function to update.
  # @param log_level: The log level of the function.
  # @return: Data about the update, including the status.
  def update_function_configuration(function_name, log_level)
    @lambda_client.update_function_configuration({
                                                   function_name: function_name,
                                                   environment: {
                                                     variables: {
                                                       'LOG_LEVEL' => log_level
                                                     }
                                                   }
                                                 })
    @lambda_client.wait_until(:function_updated_v2, { function_name: function_name }) do |w|
      w.max_attempts = 5
      w.delay = 5
    end
  rescue Aws::Lambda::Errors::ServiceException => e
    @logger.error("There was an error updating configurations for #{function_name}:\n #{e.message}")
  rescue Aws::Waiters::Errors::WaiterFailed => e
    @logger.error("Failed waiting for #{function_name} to activate:\n #{e.message}")
  end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/goto/SdkForRubyV3/lambda-2015-03-31/UpdateFunctionConfiguration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_ruby_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Ruby**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/cross_service_examples/feedback_sentiment_analyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_ruby_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
# Ruby code here.

require 'aws-sdk-rds'
require 'json'
require 'mysql2'

def lambda_handler(event:, context:)
  endpoint = ENV['DBEndpoint'] # Add the endpoint without https"
  port = ENV['Port']           # 3306
  user = ENV['DBUser']
  region = ENV['DBRegion']     # 'us-east-1'
  db_name = ENV['DBName']

  credentials = Aws::Credentials.new(
    ENV['AWS_ACCESS_KEY_ID'],
    ENV['AWS_SECRET_ACCESS_KEY'],
    ENV['AWS_SESSION_TOKEN']
  )
  rds_client = Aws::RDS::AuthTokenGenerator.new(
    region: region, 
    credentials: credentials
  )

  token = rds_client.auth_token(
    endpoint: endpoint+ ':' + port,
    user_name: user,
    region: region
  )

  begin
    conn = Mysql2::Client.new(
      host: endpoint,
      username: user,
      password: token,
      port: port,
      database: db_name,
      sslca: '/var/task/global-bundle.pem', 
      sslverify: true,
      enable_cleartext_plugin: true
    )
    a = 3
    b = 2
    result = conn.query("SELECT #{a} + #{b} AS sum").first['sum']
    puts result
    conn.close
    {
      statusCode: 200,
      body: result.to_json
    }
  rescue => e
    puts "Database connection failed due to #{e}"
  end
end
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_ruby_3_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での Kinesis イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
require 'aws-sdk'

def lambda_handler(event:, context:)
  event['Records'].each do |record|
    begin
      puts "Processed Kinesis Event - EventID: #{record['eventID']}"
      record_data = get_record_data_async(record['kinesis'])
      puts "Record Data: #{record_data}"
      # TODO: Do interesting work based on the new data
    rescue => err
      $stderr.puts "An error occurred #{err}"
      raise err
    end
  end
  puts "Successfully processed #{event['Records'].length} records."
end

def get_record_data_async(payload)
  data = Base64.decode64(payload['data']).force_encoding('UTF-8')
  # Placeholder for actual async work
  # You can use Ruby's asynchronous programming tools like async/await or fibers here.
  return data
end
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_ruby_3_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で DynamoDB イベントの消費。  

```
def lambda_handler(event:, context:)
    return 'received empty event' if event['Records'].empty?
  
    event['Records'].each do |record|
      log_dynamodb_record(record)
    end
  
    "Records processed: #{event['Records'].length}"
  end
  
  def log_dynamodb_record(record)
    puts record['eventID']
    puts record['eventName']
    puts "DynamoDB Record: #{JSON.generate(record['dynamodb'])}"
  end
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_ruby_3_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
require 'json'

def lambda_handler(event:, context:)
  event['events'].each do |record|
    log_document_db_event(record)
  end
  'OK'
end

def log_document_db_event(record)
  event_data = record['event'] || {}
  operation_type = event_data['operationType'] || 'Unknown'
  db = event_data.dig('ns', 'db') || 'Unknown'
  collection = event_data.dig('ns', 'coll') || 'Unknown'
  full_document = event_data['fullDocument'] || {}

  puts "Operation type: #{operation_type}"
  puts "db: #{db}"
  puts "collection: #{collection}"
  puts "Full document: #{JSON.pretty_generate(full_document)}"
end
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_ruby_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での Amazon MSK イベントの消費。  

```
require 'base64'

def lambda_handler(event:, context:)
  # Iterate through keys
  event['records'].each do |key, records|
    puts "Key: #{key}"

    # Iterate through records
    records.each do |record|
      puts "Record: #{record}"

      # Decode base64
      msg = Base64.decode64(record['value'])
      puts "Message: #{msg}"
    end
  end
end
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_ruby_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda での S3 イベントの消費。  

```
require 'json'
require 'uri'
require 'aws-sdk'

puts 'Loading function'

def lambda_handler(event:, context:)
  s3 = Aws::S3::Client.new(region: 'region') # Your AWS region
  # puts "Received event: #{JSON.dump(event)}"

  # Get the object from the event and show its content type
  bucket = event['Records'][0]['s3']['bucket']['name']
  key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8)
  begin
    response = s3.get_object(bucket: bucket, key: key)
    puts "CONTENT TYPE: #{response.content_type}"
    return response.content_type
  rescue StandardError => e
    puts e.message
    puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function."
    raise e
  end
end
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_ruby_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での SNS イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event:, context:)
  event['Records'].map { |record| process_message(record) }
end

def process_message(record)
  message = record['Sns']['Message']
  puts("Processing message: #{message}")
rescue StandardError => e
  puts("Error processing message: #{e}")
  raise
end
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_ruby_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での SQS イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event:, context:)
  event['Records'].each do |message|
    process_message(message)
  end
  puts "done"
end

def process_message(message)
  begin
    puts "Processed message #{message['body']}"
    # TODO: Do interesting work based on the new message
  rescue StandardError => err
    puts "An error occurred"
    raise err
  end
end
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_ruby_3_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で Kinesis バッチアイテム失敗のレポートをします。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
require 'aws-sdk'

def lambda_handler(event:, context:)
  batch_item_failures = []

  event['Records'].each do |record|
    begin
      puts "Processed Kinesis Event - EventID: #{record['eventID']}"
      record_data = get_record_data_async(record['kinesis'])
      puts "Record Data: #{record_data}"
      # TODO: Do interesting work based on the new data
    rescue StandardError => err
      puts "An error occurred #{err}"
      # Since we are working with streams, we can return the failed item immediately.
      # Lambda will immediately begin to retry processing from this failed item onwards.
      return { batchItemFailures: [{ itemIdentifier: record['kinesis']['sequenceNumber'] }] }
    end
  end

  puts "Successfully processed #{event['Records'].length} records."
  { batchItemFailures: batch_item_failures }
end

def get_record_data_async(payload)
  data = Base64.decode64(payload['data']).force_encoding('utf-8')
  # Placeholder for actual async work
  sleep(1)
  data
end
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_ruby_3_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
def lambda_handler(event:, context:)
    records = event["Records"]
    cur_record_sequence_number = ""
  
    records.each do |record|
      begin
        # Process your record
        cur_record_sequence_number = record["dynamodb"]["SequenceNumber"]
      rescue StandardError => e
        # Return failed record's sequence number
        return {"batchItemFailures" => [{"itemIdentifier" => cur_record_sequence_number}]}
      end
    end
  
    {"batchItemFailures" => []}
  end
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_ruby_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
require 'json'

def lambda_handler(event:, context:)
  if event
    batch_item_failures = []
    sqs_batch_response = {}

    event["Records"].each do |record|
      begin
        # process message
      rescue StandardError => e
        batch_item_failures << {"itemIdentifier" => record['messageId']}
      end
    end

    sqs_batch_response["batchItemFailures"] = batch_item_failures
    return sqs_batch_response
  end
end
```

# SDK for Ruby を使用した Amazon MSK の例
<a name="ruby_3_kafka_code_examples"></a>

次のコード例は、Amazon MSK AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_ruby_3_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での Amazon MSK イベントの消費。  

```
require 'base64'

def lambda_handler(event:, context:)
  # Iterate through keys
  event['records'].each do |key, records|
    puts "Key: #{key}"

    # Iterate through records
    records.each do |record|
      puts "Record: #{record}"

      # Decode base64
      msg = Base64.decode64(record['value'])
      puts "Message: #{msg}"
    end
  end
end
```

# SDK for Ruby を使用した Amazon Polly の例
<a name="ruby_3_polly_code_examples"></a>

次のコード例は、Amazon Polly AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DescribeVoices`
<a name="polly_DescribeVoices_ruby_3_topic"></a>

次のコード例は、`DescribeVoices` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-polly' # In v2: require 'aws-sdk'

begin
  # Create an Amazon Polly client using
  # credentials from the shared credentials file ~/.aws/credentials
  # and the configuration (region) from the shared configuration file ~/.aws/config
  polly = Aws::Polly::Client.new

  # Get US English voices
  resp = polly.describe_voices(language_code: 'en-US')

  resp.voices.each do |v|
    puts v.name
    puts "  #{v.gender}"
    puts
  end
rescue StandardError => e
  puts 'Could not get voices'
  puts 'Error message:'
  puts e.message
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DescribeVoices](https://docs.aws.amazon.com/goto/SdkForRubyV3/polly-2016-06-10/DescribeVoices)」を参照してください。

### `ListLexicons`
<a name="polly_ListLexicons_ruby_3_topic"></a>

次のコード例は、`ListLexicons` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-polly' # In v2: require 'aws-sdk'

begin
  # Create an Amazon Polly client using
  # credentials from the shared credentials file ~/.aws/credentials
  # and the configuration (region) from the shared configuration file ~/.aws/config
  polly = Aws::Polly::Client.new

  resp = polly.list_lexicons

  resp.lexicons.each do |l|
    puts l.name
    puts "  Alphabet:#{l.attributes.alphabet}"
    puts "  Language:#{l.attributes.language}"
    puts
  end
rescue StandardError => e
  puts 'Could not get lexicons'
  puts 'Error message:'
  puts e.message
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[ListLexicons](https://docs.aws.amazon.com/goto/SdkForRubyV3/polly-2016-06-10/ListLexicons)」を参照してください。

### `SynthesizeSpeech`
<a name="polly_SynthesizeSpeech_ruby_3_topic"></a>

次のコード例は、`SynthesizeSpeech` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/polly#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-polly' # In v2: require 'aws-sdk'

begin
  # Get the filename from the command line
  if ARGV.empty?
    puts 'You must supply a filename'
    exit 1
  end

  filename = ARGV[0]

  # Open file and get the contents as a string
  if File.exist?(filename)
    contents = IO.read(filename)
  else
    puts "No such file: #{filename}"
    exit 1
  end

  # Create an Amazon Polly client using
  # credentials from the shared credentials file ~/.aws/credentials
  # and the configuration (region) from the shared configuration file ~/.aws/config
  polly = Aws::Polly::Client.new

  resp = polly.synthesize_speech({
                                   output_format: 'mp3',
                                   text: contents,
                                   voice_id: 'Joanna'
                                 })

  # Save output
  # Get just the file name
  #  abc/xyz.txt -> xyx.txt
  name = File.basename(filename)

  # Split up name so we get just the xyz part
  parts = name.split('.')
  first_part = parts[0]
  mp3_file = "#{first_part}.mp3"

  IO.copy_stream(resp.audio_stream, mp3_file)

  puts "Wrote MP3 content to: #{mp3_file}"
rescue StandardError => e
  puts 'Got error:'
  puts 'Error message:'
  puts e.message
end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[SynthesizeSpeech](https://docs.aws.amazon.com/goto/SdkForRubyV3/polly-2016-06-10/SynthesizeSpeech)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_ruby_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Ruby**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/cross_service_examples/feedback_sentiment_analyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Ruby を使用した Amazon RDS の例
<a name="ruby_3_rds_code_examples"></a>

次のコード例は、Amazon RDS AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon RDS
<a name="rds_Hello_ruby_3_topic"></a>

次のコード例は、Amazon RDS の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-rds'
require 'logger'

# RDSManager is a class responsible for managing RDS operations
# such as listing all RDS DB instances in the current AWS account.
class RDSManager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all RDS DB instances in the current AWS account.
  def list_db_instances
    @logger.info('Listing RDS DB instances')

    paginator = @client.describe_db_instances
    instances = []

    paginator.each_page do |page|
      instances.concat(page.db_instances)
    end

    if instances.empty?
      @logger.info('No instances found.')
    else
      @logger.info("Found #{instances.count} instance(s):")
      instances.each do |instance|
        @logger.info(" * #{instance.db_instance_identifier} (#{instance.db_instance_status})")
      end
    end
  end
end

if $PROGRAM_NAME == __FILE__
  rds_client = Aws::RDS::Client.new(region: 'us-west-2')
  manager = RDSManager.new(rds_client)
  manager.list_db_instances
end
```
+  API の詳細については、「**AWS SDK for Ruby API リファレンス」の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_ruby_3_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-rds' # v2: require 'aws-sdk'

# Create a snapshot for an Amazon Relational Database Service (Amazon RDS)
# DB instance.
#
# @param rds_resource [Aws::RDS::Resource] The resource containing SDK logic.
# @param db_instance_name [String] The name of the Amazon RDS DB instance.
# @return [Aws::RDS::DBSnapshot, nil] The snapshot created, or nil if error.
def create_snapshot(rds_resource, db_instance_name)
  id = "snapshot-#{rand(10**6)}"
  db_instance = rds_resource.db_instance(db_instance_name)
  db_instance.create_snapshot({
                                db_snapshot_identifier: id
                              })
rescue Aws::Errors::ServiceError => e
  puts "Couldn't create DB instance snapshot #{id}:\n #{e.message}"
end
```
+  API の詳細については、**「AWS SDK for Ruby API リファレンス」の「[CreateDBSnapshot](https://docs.aws.amazon.com/goto/SdkForRubyV3/rds-2014-10-31/CreateDBSnapshot)」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_ruby_3_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-rds' # v2: require 'aws-sdk'

# List all Amazon Relational Database Service (Amazon RDS) DB instances.
#
# @param rds_resource [Aws::RDS::Resource] An SDK for Ruby Amazon RDS resource.
# @return [Array, nil] List of all DB instances, or nil if error.
def list_instances(rds_resource)
  db_instances = []
  rds_resource.db_instances.each do |i|
    db_instances.append({
                          "name": i.id,
                          "status": i.db_instance_status
                        })
  end
  db_instances
rescue Aws::Errors::ServiceError => e
  puts "Couldn't list instances:\n#{e.message}"
end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DescribeDBInstances](https://docs.aws.amazon.com/goto/SdkForRubyV3/rds-2014-10-31/DescribeDBInstances)」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_ruby_3_topic"></a>

次のコード例は、`DescribeDBParameterGroups` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-rds' # v2: require 'aws-sdk'

# List all Amazon Relational Database Service (Amazon RDS) parameter groups.
#
# @param rds_resource [Aws::RDS::Resource] An SDK for Ruby Amazon RDS resource.
# @return [Array, nil] List of all parameter groups, or nil if error.
def list_parameter_groups(rds_resource)
  parameter_groups = []
  rds_resource.db_parameter_groups.each do |p|
    parameter_groups.append({
                              "name": p.db_parameter_group_name,
                              "description": p.description
                            })
  end
  parameter_groups
rescue Aws::Errors::ServiceError => e
  puts "Couldn't list parameter groups:\n #{e.message}"
end
```
+  API の詳細については、**「AWS SDK for Ruby API リファレンス」の「[DescribeDBParameterGroups](https://docs.aws.amazon.com/goto/SdkForRubyV3/rds-2014-10-31/DescribeDBParameterGroups)」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_ruby_3_topic"></a>

次のコード例は、`DescribeDBParameters` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-rds' # v2: require 'aws-sdk'

# List all Amazon Relational Database Service (Amazon RDS) parameter groups.
#
# @param rds_resource [Aws::RDS::Resource] An SDK for Ruby Amazon RDS resource.
# @return [Array, nil] List of all parameter groups, or nil if error.
def list_parameter_groups(rds_resource)
  parameter_groups = []
  rds_resource.db_parameter_groups.each do |p|
    parameter_groups.append({
                              "name": p.db_parameter_group_name,
                              "description": p.description
                            })
  end
  parameter_groups
rescue Aws::Errors::ServiceError => e
  puts "Couldn't list parameter groups:\n #{e.message}"
end
```
+  API の詳細については、**「AWS SDK for Ruby API リファレンス」の「[DescribeDBParameters](https://docs.aws.amazon.com/goto/SdkForRubyV3/rds-2014-10-31/DescribeDBParameters)」を参照してください。

### `DescribeDBSnapshots`
<a name="rds_DescribeDBSnapshots_ruby_3_topic"></a>

次のコード例は、`DescribeDBSnapshots` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-rds' # v2: require 'aws-sdk'

# List all Amazon Relational Database Service (Amazon RDS) DB instance
# snapshots.
#
# @param rds_resource [Aws::RDS::Resource] An SDK for Ruby Amazon RDS resource.
# @return instance_snapshots [Array, nil] All instance snapshots, or nil if error.
def list_instance_snapshots(rds_resource)
  instance_snapshots = []
  rds_resource.db_snapshots.each do |s|
    instance_snapshots.append({
                                "id": s.snapshot_id,
                                "status": s.status
                              })
  end
  instance_snapshots
rescue Aws::Errors::ServiceError => e
  puts "Couldn't list instance snapshots:\n #{e.message}"
end
```
+  API の詳細については、**「AWS SDK for Ruby API リファレンス」の「[DescribeDBSnapshots](https://docs.aws.amazon.com/goto/SdkForRubyV3/rds-2014-10-31/DescribeDBSnapshots)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_ruby_3_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
# Ruby code here.

require 'aws-sdk-rds'
require 'json'
require 'mysql2'

def lambda_handler(event:, context:)
  endpoint = ENV['DBEndpoint'] # Add the endpoint without https"
  port = ENV['Port']           # 3306
  user = ENV['DBUser']
  region = ENV['DBRegion']     # 'us-east-1'
  db_name = ENV['DBName']

  credentials = Aws::Credentials.new(
    ENV['AWS_ACCESS_KEY_ID'],
    ENV['AWS_SECRET_ACCESS_KEY'],
    ENV['AWS_SESSION_TOKEN']
  )
  rds_client = Aws::RDS::AuthTokenGenerator.new(
    region: region, 
    credentials: credentials
  )

  token = rds_client.auth_token(
    endpoint: endpoint+ ':' + port,
    user_name: user,
    region: region
  )

  begin
    conn = Mysql2::Client.new(
      host: endpoint,
      username: user,
      password: token,
      port: port,
      database: db_name,
      sslca: '/var/task/global-bundle.pem', 
      sslverify: true,
      enable_cleartext_plugin: true
    )
    a = 3
    b = 2
    result = conn.query("SELECT #{a} + #{b} AS sum").first['sum']
    puts result
    conn.close
    {
      statusCode: 200,
      body: result.to_json
    }
  rescue => e
    puts "Database connection failed due to #{e}"
  end
end
```

# SDK for Ruby を使用した Amazon S3 の例
<a name="ruby_3_s3_code_examples"></a>

次のコード例は、Amazon S3 AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_ruby_3_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
# frozen_string_literal: true

# S3Manager is a class responsible for managing S3 operations
# such as listing all S3 buckets in the current AWS account.
class S3Manager
  def initialize(client)
    @client = client
    @logger = Logger.new($stdout)
  end

  # Lists and prints all S3 buckets in the current AWS account.
  def list_buckets
    @logger.info('Here are the buckets in your account:')

    response = @client.list_buckets

    if response.buckets.empty?
      @logger.info("You don't have any S3 buckets yet.")
    else
      response.buckets.each do |bucket|
        @logger.info("- #{bucket.name}")
      end
    end
  rescue Aws::Errors::ServiceError => e
    @logger.error("Encountered an error while listing buckets: #{e.message}")
  end
end

if $PROGRAM_NAME == __FILE__
  s3_client = Aws::S3::Client.new
  manager = S3Manager.new(s3_client)
  manager.list_buckets
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/ListBuckets)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_ruby_3_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps the getting started scenario actions.
class ScenarioGettingStarted
  attr_reader :s3_resource

  # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource.
  def initialize(s3_resource)
    @s3_resource = s3_resource
  end

  # Creates a bucket with a random name in the currently configured account and
  # AWS Region.
  #
  # @return [Aws::S3::Bucket] The newly created bucket.
  def create_bucket
    bucket = @s3_resource.create_bucket(
      bucket: "amzn-s3-demo-bucket-#{Random.uuid}",
      create_bucket_configuration: {
        location_constraint: 'us-east-1' # NOTE: only certain regions permitted
      }
    )
    puts("Created demo bucket named #{bucket.name}.")
  rescue Aws::Errors::ServiceError => e
    puts('Tried and failed to create demo bucket.')
    puts("\t#{e.code}: #{e.message}")
    puts("\nCan't continue the demo without a bucket!")
    raise
  else
    bucket
  end

  # Requests a file name from the user.
  #
  # @return The name of the file.
  def create_file
    File.open('demo.txt', w) { |f| f.write('This is a demo file.') }
  end

  # Uploads a file to an Amazon S3 bucket.
  #
  # @param bucket [Aws::S3::Bucket] The bucket object representing the upload destination
  # @return [Aws::S3::Object] The Amazon S3 object that contains the uploaded file.
  def upload_file(bucket)
    File.open('demo.txt', 'w+') { |f| f.write('This is a demo file.') }
    s3_object = bucket.object(File.basename('demo.txt'))
    s3_object.upload_file('demo.txt')
    puts("Uploaded file demo.txt into bucket #{bucket.name} with key #{s3_object.key}.")
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't upload file demo.txt to #{bucket.name}.")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    s3_object
  end

  # Downloads an Amazon S3 object to a file.
  #
  # @param s3_object [Aws::S3::Object] The object to download.
  def download_file(s3_object)
    puts("\nDo you want to download #{s3_object.key} to a local file (y/n)? ")
    answer = gets.chomp.downcase
    if answer == 'y'
      puts('Enter a name for the downloaded file: ')
      file_name = gets.chomp
      s3_object.download_file(file_name)
      puts("Object #{s3_object.key} successfully downloaded to #{file_name}.")
    end
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't download #{s3_object.key}.")
    puts("\t#{e.code}: #{e.message}")
    raise
  end

  # Copies an Amazon S3 object to a subfolder within the same bucket.
  #
  # @param source_object [Aws::S3::Object] The source object to copy.
  # @return [Aws::S3::Object, nil] The destination object.
  def copy_object(source_object)
    dest_object = nil
    puts("\nDo you want to copy #{source_object.key} to a subfolder in your bucket (y/n)? ")
    answer = gets.chomp.downcase
    if answer == 'y'
      dest_object = source_object.bucket.object("demo-folder/#{source_object.key}")
      dest_object.copy_from(source_object)
      puts("Copied #{source_object.key} to #{dest_object.key}.")
    end
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't copy #{source_object.key}.")
    puts("\t#{e.code}: #{e.message}")
    raise
  else
    dest_object
  end

  # Lists the objects in an Amazon S3 bucket.
  #
  # @param bucket [Aws::S3::Bucket] The bucket to query.
  def list_objects(bucket)
    puts("\nYour bucket contains the following objects:")
    bucket.objects.each do |obj|
      puts("\t#{obj.key}")
    end
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't list the objects in bucket #{bucket.name}.")
    puts("\t#{e.code}: #{e.message}")
    raise
  end

  # Deletes the objects in an Amazon S3 bucket and deletes the bucket.
  #
  # @param bucket [Aws::S3::Bucket] The bucket to empty and delete.
  def delete_bucket(bucket)
    puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ")
    answer = gets.chomp.downcase
    if answer == 'y'
      bucket.objects.batch_delete!
      bucket.delete
      puts("Emptied and deleted bucket #{bucket.name}.\n")
    end
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't empty and delete bucket #{bucket.name}.")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
end

# Runs the Amazon S3 getting started scenario.
def run_scenario(scenario)
  puts('-' * 88)
  puts('Welcome to the Amazon S3 getting started demo!')
  puts('-' * 88)

  bucket = scenario.create_bucket
  s3_object = scenario.upload_file(bucket)
  scenario.download_file(s3_object)
  scenario.copy_object(s3_object)
  scenario.list_objects(bucket)
  scenario.delete_bucket(bucket)

  puts('Thanks for watching!')
  puts('-' * 88)
rescue Aws::Errors::ServiceError
  puts('Something went wrong with the demo!')
end

run_scenario(ScenarioGettingStarted.new(Aws::S3::Resource.new)) if $PROGRAM_NAME == __FILE__
```
+ API の詳細については、「*AWS SDK for Ruby API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/CopyObject)
  + [CreateBucket](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/CreateBucket)
  + [DeleteBucket](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/DeleteBucket)
  + [DeleteObjects](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/DeleteObjects)
  + [GetObject](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/GetObject)
  + [ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/ListObjectsV2)
  + [PutObject](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/PutObject)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_ruby_3_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトをコピーします。  

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectCopyWrapper
  attr_reader :source_object

  # @param source_object [Aws::S3::Object] An existing Amazon S3 object. This is used as the source object for
  #                                        copy actions.
  def initialize(source_object)
    @source_object = source_object
  end

  # Copy the source object to the specified target bucket and rename it with the target key.
  #
  # @param target_bucket [Aws::S3::Bucket] An existing Amazon S3 bucket where the object is copied.
  # @param target_object_key [String] The key to give the copy of the object.
  # @return [Aws::S3::Object, nil] The copied object when successful; otherwise, nil.
  def copy_object(target_bucket, target_object_key)
    @source_object.copy_to(bucket: target_bucket.name, key: target_object_key)
    target_bucket.object(target_object_key)
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't copy #{@source_object.key} to #{target_object_key}. Here's why: #{e.message}"
  end
end

# Example usage:
def run_demo
  source_bucket_name = "amzn-s3-demo-bucket1"
  source_key = "my-source-file.txt"
  target_bucket_name = "amzn-s3-demo-bucket2"
  target_key = "my-target-file.txt"

  source_bucket = Aws::S3::Bucket.new(source_bucket_name)
  wrapper = ObjectCopyWrapper.new(source_bucket.object(source_key))
  target_bucket = Aws::S3::Bucket.new(target_bucket_name)
  target_object = wrapper.copy_object(target_bucket, target_key)
  return unless target_object

  puts "Copied #{source_key} from #{source_bucket_name} to #{target_object.bucket_name}:#{target_object.key}."
end

run_demo if $PROGRAM_NAME == __FILE__
```
オブジェクトをコピーし、宛先オブジェクトにサーバー側の暗号化を追加します。  

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectCopyEncryptWrapper
  attr_reader :source_object

  # @param source_object [Aws::S3::Object] An existing Amazon S3 object. This is used as the source object for
  #                                        copy actions.
  def initialize(source_object)
    @source_object = source_object
  end

  # Copy the source object to the specified target bucket, rename it with the target key, and encrypt it.
  #
  # @param target_bucket [Aws::S3::Bucket] An existing Amazon S3 bucket where the object is copied.
  # @param target_object_key [String] The key to give the copy of the object.
  # @return [Aws::S3::Object, nil] The copied object when successful; otherwise, nil.
  def copy_object(target_bucket, target_object_key, encryption)
    @source_object.copy_to(bucket: target_bucket.name, key: target_object_key, server_side_encryption: encryption)
    target_bucket.object(target_object_key)
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't copy #{@source_object.key} to #{target_object_key}. Here's why: #{e.message}"
  end
end

# Example usage:
def run_demo
  source_bucket_name = "amzn-s3-demo-bucket1"
  source_key = "my-source-file.txt"
  target_bucket_name = "amzn-s3-demo-bucket2"
  target_key = "my-target-file.txt"
  target_encryption = "AES256"

  source_bucket = Aws::S3::Bucket.new(source_bucket_name)
  wrapper = ObjectCopyEncryptWrapper.new(source_bucket.object(source_key))
  target_bucket = Aws::S3::Bucket.new(target_bucket_name)
  target_object = wrapper.copy_object(target_bucket, target_key, target_encryption)
  return unless target_object

  puts "Copied #{source_key} from #{source_bucket_name} to #{target_object.bucket_name}:#{target_object.key} and "\
       "encrypted the target with #{target_object.server_side_encryption} encryption."
end

run_demo if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[CopyObject](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/CopyObject)」を参照してください。**

### `CreateBucket`
<a name="s3_CreateBucket_ruby_3_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
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("amzn-s3-demo-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__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[CreateBucket](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/CreateBucket)」を参照してください。**

### `DeleteBucket`
<a name="s3_DeleteBucket_ruby_3_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
  # Deletes the objects in an Amazon S3 bucket and deletes the bucket.
  #
  # @param bucket [Aws::S3::Bucket] The bucket to empty and delete.
  def delete_bucket(bucket)
    puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ")
    answer = gets.chomp.downcase
    if answer == 'y'
      bucket.objects.batch_delete!
      bucket.delete
      puts("Emptied and deleted bucket #{bucket.name}.\n")
    end
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't empty and delete bucket #{bucket.name}.")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[DeleteBucket](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/DeleteBucket)」を参照してください。**

### `DeleteBucketCors`
<a name="s3_DeleteBucketCors_ruby_3_topic"></a>

次のコード例は、`DeleteBucketCors` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 bucket CORS configuration.
class BucketCorsWrapper
  attr_reader :bucket_cors

  # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket.
  def initialize(bucket_cors)
    @bucket_cors = bucket_cors
  end

  # Deletes the CORS configuration of a bucket.
  #
  # @return [Boolean] True if the CORS rules were deleted; otherwise, false.
  def delete_cors
    @bucket_cors.delete
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't delete CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}"
    false
  end

end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[DeleteBucketCors](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/DeleteBucketCors)」を参照してください。**

### `DeleteBucketPolicy`
<a name="s3_DeleteBucketPolicy_ruby_3_topic"></a>

次のコード例は、`DeleteBucketPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
# Wraps an Amazon S3 bucket policy.
class BucketPolicyWrapper
  attr_reader :bucket_policy

  # @param bucket_policy [Aws::S3::BucketPolicy] A bucket policy object configured with an existing bucket.
  def initialize(bucket_policy)
    @bucket_policy = bucket_policy
  end

  def delete_policy
    @bucket_policy.delete
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't delete the policy from #{@bucket_policy.bucket.name}. Here's why: #{e.message}"
    false
  end

end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[DeleteBucketPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/DeleteBucketPolicy)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_ruby_3_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
  # Deletes the objects in an Amazon S3 bucket and deletes the bucket.
  #
  # @param bucket [Aws::S3::Bucket] The bucket to empty and delete.
  def delete_bucket(bucket)
    puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ")
    answer = gets.chomp.downcase
    if answer == 'y'
      bucket.objects.batch_delete!
      bucket.delete
      puts("Emptied and deleted bucket #{bucket.name}.\n")
    end
  rescue Aws::Errors::ServiceError => e
    puts("Couldn't empty and delete bucket #{bucket.name}.")
    puts("\t#{e.code}: #{e.message}")
    raise
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[DeleteObjects](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/DeleteObjects)」を参照してください。**

### `GetBucketCors`
<a name="s3_GetBucketCors_ruby_3_topic"></a>

次のコード例は、`GetBucketCors` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 bucket CORS configuration.
class BucketCorsWrapper
  attr_reader :bucket_cors

  # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket.
  def initialize(bucket_cors)
    @bucket_cors = bucket_cors
  end

  # Gets the CORS configuration of a bucket.
  #
  # @return [Aws::S3::Type::GetBucketCorsOutput, nil] The current CORS configuration for the bucket.
  def cors
    @bucket_cors.data
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't get CORS configuration for #{@bucket_cors.bucket.name}. Here's why: #{e.message}"
    nil
  end

end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[GetBucketCors](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/GetBucketCors)」を参照してください。**

### `GetBucketPolicy`
<a name="s3_GetBucketPolicy_ruby_3_topic"></a>

次のコード例は、`GetBucketPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
# Wraps an Amazon S3 bucket policy.
class BucketPolicyWrapper
  attr_reader :bucket_policy

  # @param bucket_policy [Aws::S3::BucketPolicy] A bucket policy object configured with an existing bucket.
  def initialize(bucket_policy)
    @bucket_policy = bucket_policy
  end

  # Gets the policy of a bucket.
  #
  # @return [Aws::S3::GetBucketPolicyOutput, nil] The current bucket policy.
  def policy
    policy = @bucket_policy.data.policy
    policy.respond_to?(:read) ? policy.read : policy
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't get the policy for #{@bucket_policy.bucket.name}. Here's why: #{e.message}"
    nil
  end

end
```
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[GetBucketPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/GetBucketPolicy)」を参照してください。

### `GetObject`
<a name="s3_GetObject_ruby_3_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。
オブジェクトを取得します。  

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectGetWrapper
  attr_reader :object

  # @param object [Aws::S3::Object] An existing Amazon S3 object.
  def initialize(object)
    @object = object
  end

  # Gets the object directly to a file.
  #
  # @param target_path [String] The path to the file where the object is downloaded.
  # @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil.
  def get_object(target_path)
    @object.get(response_target: target_path)
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't get object #{@object.key}. Here's why: #{e.message}"
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  object_key = "my-object.txt"
  target_path = "my-object-as-file.txt"

  wrapper = ObjectGetWrapper.new(Aws::S3::Object.new(bucket_name, object_key))
  obj_data = wrapper.get_object(target_path)
  return unless obj_data

  puts "Object #{object_key} (#{obj_data.content_length} bytes} downloaded to #{target_path}."
end

run_demo if $PROGRAM_NAME == __FILE__
```
オブジェクトを取得し、サーバー側の暗号化状態をレポートします。  

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectGetEncryptionWrapper
  attr_reader :object

  # @param object [Aws::S3::Object] An existing Amazon S3 object.
  def initialize(object)
    @object = object
  end

  # Gets the object into memory.
  #
  # @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil.
  def object
    @object.get
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't get object #{@object.key}. Here's why: #{e.message}"
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  object_key = "my-object.txt"

  wrapper = ObjectGetEncryptionWrapper.new(Aws::S3::Object.new(bucket_name, object_key))
  obj_data = wrapper.get_object
  return unless obj_data

  encryption = obj_data.server_side_encryption.nil? ? 'no' : obj_data.server_side_encryption
  puts "Object #{object_key} uses #{encryption} encryption."
end

run_demo if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[GetObject](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/GetObject)」を参照してください。**

### `HeadObject`
<a name="s3_HeadObject_ruby_3_topic"></a>

次のコード例は、`HeadObject` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectExistsWrapper
  attr_reader :object

  # @param object [Aws::S3::Object] An Amazon S3 object.
  def initialize(object)
    @object = object
  end

  # Checks whether the object exists.
  #
  # @return [Boolean] True if the object exists; otherwise false.
  def exists?
    @object.exists?
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't check existence of object #{@object.bucket.name}:#{@object.key}. Here's why: #{e.message}"
    false
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  object_key = "my-object.txt"

  wrapper = ObjectExistsWrapper.new(Aws::S3::Object.new(bucket_name, object_key))
  exists = wrapper.exists?

  puts "Object #{object_key} #{exists ? 'does' : 'does not'} exist."
end

run_demo if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[HeadObject](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/HeadObject)」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_ruby_3_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 resource actions.
class BucketListWrapper
  attr_reader :s3_resource

  # @param s3_resource [Aws::S3::Resource] An Amazon S3 resource.
  def initialize(s3_resource)
    @s3_resource = s3_resource
  end

  # Lists buckets for the current account.
  #
  # @param count [Integer] The maximum number of buckets to list.
  def list_buckets(count)
    puts 'Found these buckets:'
    @s3_resource.buckets.each do |bucket|
      puts "\t#{bucket.name}"
      count -= 1
      break if count.zero?
    end
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't list buckets. Here's why: #{e.message}"
    false
  end
end

# Example usage:
def run_demo
  wrapper = BucketListWrapper.new(Aws::S3::Resource.new)
  wrapper.list_buckets(25)
end

run_demo if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListBuckets](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/ListBuckets)」を参照してください。**

### `ListObjectsV2`
<a name="s3_ListObjectsV2_ruby_3_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 bucket actions.
class BucketListObjectsWrapper
  attr_reader :bucket

  # @param bucket [Aws::S3::Bucket] An existing Amazon S3 bucket.
  def initialize(bucket)
    @bucket = bucket
  end

  # Lists object in a bucket.
  #
  # @param max_objects [Integer] The maximum number of objects to list.
  # @return [Integer] The number of objects listed.
  def list_objects(max_objects)
    count = 0
    puts "The objects in #{@bucket.name} are:"
    @bucket.objects.each do |obj|
      puts "\t#{obj.key}"
      count += 1
      break if count == max_objects
    end
    count
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't list objects in bucket #{bucket.name}. Here's why: #{e.message}"
    0
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"

  wrapper = BucketListObjectsWrapper.new(Aws::S3::Bucket.new(bucket_name))
  count = wrapper.list_objects(25)
  puts "Listed #{count} objects."
end

run_demo if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListObjectsV2](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/ListObjectsV2)」を参照してください。**

### `PutBucketCors`
<a name="s3_PutBucketCors_ruby_3_topic"></a>

次のコード例は、`PutBucketCors` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 bucket CORS configuration.
class BucketCorsWrapper
  attr_reader :bucket_cors

  # @param bucket_cors [Aws::S3::BucketCors] A bucket CORS object configured with an existing bucket.
  def initialize(bucket_cors)
    @bucket_cors = bucket_cors
  end

  # Sets CORS rules on a bucket.
  #
  # @param allowed_methods [Array<String>] The types of HTTP requests to allow.
  # @param allowed_origins [Array<String>] The origins to allow.
  # @returns [Boolean] True if the CORS rules were set; otherwise, false.
  def set_cors(allowed_methods, allowed_origins)
    @bucket_cors.put(
      cors_configuration: {
        cors_rules: [
          {
            allowed_methods: allowed_methods,
            allowed_origins: allowed_origins,
            allowed_headers: %w[*],
            max_age_seconds: 3600
          }
        ]
      }
    )
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't set CORS rules for #{@bucket_cors.bucket.name}. Here's why: #{e.message}"
    false
  end

end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[PutBucketCors](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/PutBucketCors)」を参照してください。**

### `PutBucketPolicy`
<a name="s3_PutBucketPolicy_ruby_3_topic"></a>

次のコード例は、`PutBucketPolicy` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
# Wraps an Amazon S3 bucket policy.
class BucketPolicyWrapper
  attr_reader :bucket_policy

  # @param bucket_policy [Aws::S3::BucketPolicy] A bucket policy object configured with an existing bucket.
  def initialize(bucket_policy)
    @bucket_policy = bucket_policy
  end

  # Sets a policy on a bucket.
  #
  def policy(policy)
    @bucket_policy.put(policy: policy)
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't set the policy for #{@bucket_policy.bucket.name}. Here's why: #{e.message}"
    false
  end

end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[PutBucketPolicy](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/PutBucketPolicy)」を参照してください。**

### `PutBucketWebsite`
<a name="s3_PutBucketWebsite_ruby_3_topic"></a>

次のコード例は、`PutBucketWebsite` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'

# Wraps Amazon S3 bucket website actions.
class BucketWebsiteWrapper
  attr_reader :bucket_website

  # @param bucket_website [Aws::S3::BucketWebsite] A bucket website object configured with an existing bucket.
  def initialize(bucket_website)
    @bucket_website = bucket_website
  end

  # Sets a bucket as a static website.
  #
  # @param index_document [String] The name of the index document for the website.
  # @param error_document [String] The name of the error document to show for 4XX errors.
  # @return [Boolean] True when the bucket is configured as a website; otherwise, false.
  def set_website(index_document, error_document)
    @bucket_website.put(
      website_configuration: {
        index_document: { suffix: index_document },
        error_document: { key: error_document }
      }
    )
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't configure #{@bucket_website.bucket.name} as a website. Here's why: #{e.message}"
    false
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  index_document = "index.html"
  error_document = "404.html"

  wrapper = BucketWebsiteWrapper.new(Aws::S3::BucketWebsite.new(bucket_name))
  return unless wrapper.set_website(index_document, error_document)

  puts "Successfully configured bucket #{bucket_name} as a static website."
end

run_demo if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「*PutBucketWebsite*」を参照してください。[https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/PutBucketWebsite](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/PutBucketWebsite)

### `PutObject`
<a name="s3_PutObject_ruby_3_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。
マネージドアップローダー (Object.upload\$1file) を使用してファイルをアップロードします。  

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectUploadFileWrapper
  attr_reader :object

  # @param object [Aws::S3::Object] An existing Amazon S3 object.
  def initialize(object)
    @object = object
  end

  # Uploads a file to an Amazon S3 object by using a managed uploader.
  #
  # @param file_path [String] The path to the file to upload.
  # @return [Boolean] True when the file is uploaded; otherwise false.
  def upload_file(file_path)
    @object.upload_file(file_path)
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't upload file #{file_path} to #{@object.key}. Here's why: #{e.message}"
    false
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  object_key = "my-uploaded-file"
  file_path = "object_upload_file.rb"

  wrapper = ObjectUploadFileWrapper.new(Aws::S3::Object.new(bucket_name, object_key))
  return unless wrapper.upload_file(file_path)

  puts "File #{file_path} successfully uploaded to #{bucket_name}:#{object_key}."
end

run_demo if $PROGRAM_NAME == __FILE__
```
Object.put を使用してファイルをアップロードします。  

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectPutWrapper
  attr_reader :object

  # @param object [Aws::S3::Object] An existing Amazon S3 object.
  def initialize(object)
    @object = object
  end

  def put_object(source_file_path)
    File.open(source_file_path, 'rb') do |file|
      @object.put(body: file)
    end
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't put #{source_file_path} to #{object.key}. Here's why: #{e.message}"
    false
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  object_key = "my-object-key"
  file_path = "my-local-file.txt"

  wrapper = ObjectPutWrapper.new(Aws::S3::Object.new(bucket_name, object_key))
  success = wrapper.put_object(file_path)
  return unless success

  puts "Put file #{file_path} into #{object_key} in #{bucket_name}."
end

run_demo if $PROGRAM_NAME == __FILE__
```
Object.put を使用してファイルをアップロードし、サーバー側の暗号化を追加します。  

```
require 'aws-sdk-s3'

# Wraps Amazon S3 object actions.
class ObjectPutSseWrapper
  attr_reader :object

  # @param object [Aws::S3::Object] An existing Amazon S3 object.
  def initialize(object)
    @object = object
  end

  def put_object_encrypted(object_content, encryption)
    @object.put(body: object_content, server_side_encryption: encryption)
    true
  rescue Aws::Errors::ServiceError => e
    puts "Couldn't put your content to #{object.key}. Here's why: #{e.message}"
    false
  end
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  object_key = "my-encrypted-content"
  object_content = "This is my super-secret content."
  encryption = "AES256"

  wrapper = ObjectPutSseWrapper.new(Aws::S3::Object.new(bucket_name, object_content))
  return unless wrapper.put_object_encrypted(object_content, encryption)

  puts "Put your content into #{bucket_name}:#{object_key} and encrypted it with #{encryption}."
end

run_demo if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[PutObject](https://docs.aws.amazon.com/goto/SdkForRubyV3/s3-2006-03-01/PutObject)」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_ruby_3_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-s3'
require 'net/http'

# Creates a presigned URL that can be used to upload content to an object.
#
# @param bucket [Aws::S3::Bucket] An existing Amazon S3 bucket.
# @param object_key [String] The key to give the uploaded object.
# @return [URI, nil] The parsed URI if successful; otherwise nil.
def get_presigned_url(bucket, object_key)
  url = bucket.object(object_key).presigned_url(:put)
  puts "Created presigned URL: #{url}"
  URI(url)
rescue Aws::Errors::ServiceError => e
  puts "Couldn't create presigned URL for #{bucket.name}:#{object_key}. Here's why: #{e.message}"
end

# Example usage:
def run_demo
  bucket_name = "amzn-s3-demo-bucket"
  object_key = "my-file.txt"
  object_content = "This is the content of my-file.txt."

  bucket = Aws::S3::Bucket.new(bucket_name)
  presigned_url = get_presigned_url(bucket, object_key)
  return unless presigned_url

  response = Net::HTTP.start(presigned_url.host) do |http|
    http.send_request('PUT', presigned_url.request_uri, object_content, 'content_type' => '')
  end

  case response
  when Net::HTTPSuccess
    puts 'Content uploaded!'
  else
    puts response.value
  end
end

run_demo if $PROGRAM_NAME == __FILE__
```

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_ruby_3_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用して Lambda での S3 イベントの消費。  

```
require 'json'
require 'uri'
require 'aws-sdk'

puts 'Loading function'

def lambda_handler(event:, context:)
  s3 = Aws::S3::Client.new(region: 'region') # Your AWS region
  # puts "Received event: #{JSON.dump(event)}"

  # Get the object from the event and show its content type
  bucket = event['Records'][0]['s3']['bucket']['name']
  key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8)
  begin
    response = s3.get_object(bucket: bucket, key: key)
    puts "CONTENT TYPE: #{response.content_type}"
    return response.content_type
  rescue StandardError => e
    puts e.message
    puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function."
    raise e
  end
end
```

# SDK for Ruby を使用する Amazon SES の例
<a name="ruby_3_ses_code_examples"></a>

次のコード例は、Amazon SES AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetIdentityVerificationAttributes`
<a name="ses_GetIdentityVerificationAttributes_ruby_3_topic"></a>

次のコード例は、`GetIdentityVerificationAttributes` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ses/v1#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ses' # v2: require 'aws-sdk'

# Create client in us-west-2 region
# Replace us-west-2 with the AWS Region you're using for Amazon SES.
client = Aws::SES::Client.new(region: 'us-west-2')

# Get up to 1000 identities
ids = client.list_identities({
                               identity_type: 'EmailAddress'
                             })

ids.identities.each do |email|
  attrs = client.get_identity_verification_attributes({
                                                        identities: [email]
                                                      })

  status = attrs.verification_attributes[email].verification_status

  # Display email addresses that have been verified
  puts email if status == 'Success'
end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*.」の「[GetIdentityVerificationAttributes](https://docs.aws.amazon.com/goto/SdkForRubyV3/email-2010-12-01/GetIdentityVerificationAttributes)」を参照してください。

### `ListIdentities`
<a name="ses_ListIdentities_ruby_3_topic"></a>

次のコード例は、`ListIdentities` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ses/v1#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ses' # v2: require 'aws-sdk'

# Create client in us-west-2 region
# Replace us-west-2 with the AWS Region you're using for Amazon SES.
client = Aws::SES::Client.new(region: 'us-west-2')

# Get up to 1000 identities
ids = client.list_identities({
                               identity_type: 'EmailAddress'
                             })

ids.identities.each do |email|
  attrs = client.get_identity_verification_attributes({
                                                        identities: [email]
                                                      })

  status = attrs.verification_attributes[email].verification_status

  # Display email addresses that have been verified
  puts email if status == 'Success'
end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[ListIdentities](https://docs.aws.amazon.com/goto/SdkForRubyV3/email-2010-12-01/ListIdentities)」を参照してください。

### `SendEmail`
<a name="ses_SendEmail_ruby_3_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ses/v1#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ses' # v2: require 'aws-sdk'

# Replace sender@example.com with your "From" address.
# This address must be verified with Amazon SES.
sender = 'sender@example.com'

# Replace recipient@example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
recipient = 'recipient@example.com'

# Specify a configuration set. To use a configuration
# set, uncomment the next line and line 74.
#   configsetname = "ConfigSet"

# The subject line for the email.
subject = 'Amazon SES test (AWS SDK for Ruby)'

# The HTML body of the email.
htmlbody =
  '<h1>Amazon SES test (AWS SDK for Ruby)</h1>'\
  '<p>This email was sent with <a href="https://aws.amazon.com/ses/">'\
  'Amazon SES</a> using the <a href="https://aws.amazon.com/sdk-for-ruby/">'\
  'AWS SDK for Ruby</a>.'

# The email body for recipients with non-HTML email clients.
textbody = 'This email was sent with Amazon SES using the AWS SDK for Ruby.'

# Specify the text encoding scheme.
encoding = 'UTF-8'

# Create a new SES client in the us-west-2 region.
# Replace us-west-2 with the AWS Region you're using for Amazon SES.
ses = Aws::SES::Client.new(region: 'us-west-2')

# Try to send the email.
begin
  # Provide the contents of the email.
  ses.send_email(
    destination: {
      to_addresses: [
        recipient
      ]
    },
    message: {
      body: {
        html: {
          charset: encoding,
          data: htmlbody
        },
        text: {
          charset: encoding,
          data: textbody
        }
      },
      subject: {
        charset: encoding,
        data: subject
      }
    },
    source: sender
    # Uncomment the following line to use a configuration set.
    # configuration_set_name: configsetname,
  )

  puts "Email sent to #{recipient}"

# If something goes wrong, display an error message.
rescue Aws::SES::Errors::ServiceError => e
  puts "Email not sent. Error message: #{e}"
end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[SendEmail](https://docs.aws.amazon.com/goto/SdkForRubyV3/email-2010-12-01/SendEmail)」を参照してください。

### `VerifyEmailIdentity`
<a name="ses_VerifyEmailIdentity_ruby_3_topic"></a>

次のコード例は、`VerifyEmailIdentity` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ses/v1#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-ses' # v2: require 'aws-sdk'

# Replace recipient@example.com with a "To" address.
recipient = 'recipient@example.com'

# Create a new SES resource in the us-west-2 region.
# Replace us-west-2 with the AWS Region you're using for Amazon SES.
ses = Aws::SES::Client.new(region: 'us-west-2')

# Try to verify email address.
begin
  ses.verify_email_identity({
                              email_address: recipient
                            })

  puts "Email sent to #{recipient}"

# If something goes wrong, display an error message.
rescue Aws::SES::Errors::ServiceError => e
  puts "Email not sent. Error message: #{e}"
end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[VerifyEmailIdentity](https://docs.aws.amazon.com/goto/SdkForRubyV3/email-2010-12-01/VerifyEmailIdentity)」を参照してください。**

# SDK for Ruby を使用する Amazon SES API v2 の例
<a name="ruby_3_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendEmail`
<a name="sesv2_SendEmail_ruby_3_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/ses/v2#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sesv2'
require_relative 'config' # Recipient and sender email addresses.

# Set up the SESv2 client.
client = Aws::SESV2::Client.new(region: AWS_REGION)

def send_email(client, sender_email, recipient_email)
  response = client.send_email(
    {
      from_email_address: sender_email,
      destination: {
        to_addresses: [recipient_email]
      },
      content: {
        simple: {
          subject: {
            data: 'Test email subject'
          },
          body: {
            text: {
              data: 'Test email body'
            }
          }
        }
      }
    }
  )
  puts "Email sent from #{SENDER_EMAIL} to #{RECIPIENT_EMAIL} with message ID: #{response.message_id}"
end

send_email(client, SENDER_EMAIL, RECIPIENT_EMAIL)
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[SendEmail](https://docs.aws.amazon.com/goto/SdkForRubyV3/sesv2-2019-09-27/SendEmail)」を参照してください。

# SDK for Ruby を使用した Amazon SNS の例
<a name="ruby_3_sns_code_examples"></a>

次のコード例は、Amazon SNS AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_ruby_3_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
# 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
```
+  詳細については、「[AWS SDK for Ruby デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html)」を参照してください。
+  API の詳細については、AWS SDK for Ruby API リファレンスの**「[CreateTopic](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/CreateTopic)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_ruby_3_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
# This class demonstrates how to list subscriptions to an Amazon Simple Notification Service (SNS) topic
class SnsSubscriptionLister
  def initialize(sns_client)
    @sns_client = sns_client
    @logger = Logger.new($stdout)
  end

  # Lists subscriptions for a given SNS topic
  # @param topic_arn [String] The ARN of the SNS topic
  # @return [Types::ListSubscriptionsResponse] subscriptions: The response object
  def list_subscriptions(topic_arn)
    @logger.info("Listing subscriptions for topic: #{topic_arn}")
    subscriptions = @sns_client.list_subscriptions_by_topic(topic_arn: topic_arn)
    subscriptions.subscriptions.each do |subscription|
      @logger.info("Subscription endpoint: #{subscription.endpoint}")
    end
    subscriptions
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Error listing subscriptions: #{e.message}")
    raise
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  sns_client = Aws::SNS::Client.new
  topic_arn = 'SNS_TOPIC_ARN' # Replace with your SNS topic ARN
  lister = SnsSubscriptionLister.new(sns_client)

  begin
    lister.list_subscriptions(topic_arn)
  rescue StandardError => e
    puts "Failed to list subscriptions: #{e.message}"
    exit 1
  end
end
```
+  詳細については、「[AWS SDK for Ruby デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-show-subscriptions.html)」を参照してください。
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[ListSubscriptions](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/ListSubscriptions)」を参照してください。**

### `ListTopics`
<a name="sns_ListTopics_ruby_3_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sns' # v2: require 'aws-sdk'

def list_topics?(sns_client)
  sns_client.topics.each do |topic|
    puts topic.arn
  rescue StandardError => e
    puts "Error while listing the topics: #{e.message}"
  end
end

def run_me
  region = 'REGION'
  sns_client = Aws::SNS::Resource.new(region: region)

  puts 'Listing the topics.'

  return if list_topics?(sns_client)

  puts 'The bucket was not created. Stopping program.'
  exit 1
end

# Example usage:
run_me if $PROGRAM_NAME == __FILE__
```
+  詳細については、「[AWS SDK for Ruby デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-show-topics.html)」を参照してください。
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[ListTopics](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/ListTopics)」を参照してください。

### `Publish`
<a name="sns_Publish_ruby_3_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
# Service class for sending messages using Amazon Simple Notification Service (SNS)
class SnsMessageSender
  # Initializes the SnsMessageSender with an SNS client
  #
  # @param sns_client [Aws::SNS::Client] The SNS client
  def initialize(sns_client)
    @sns_client = sns_client
    @logger = Logger.new($stdout)
  end

  # Sends a message to a specified SNS topic
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param message [String] The message to send
  # @return [Boolean] true if message was successfully sent, false otherwise
  def send_message(topic_arn, message)
    @sns_client.publish(topic_arn: topic_arn, message: message)
    @logger.info("Message sent successfully to #{topic_arn}.")
    true
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Error while sending the message: #{e.message}")
    false
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_arn = 'SNS_TOPIC_ARN' # Should be replaced with a real topic ARN
  message = 'MESSAGE'         # Should be replaced with the actual message content

  sns_client = Aws::SNS::Client.new
  message_sender = SnsMessageSender.new(sns_client)

  @logger.info('Sending message.')
  unless message_sender.send_message(topic_arn, message)
    @logger.error('Message sending failed. Stopping program.')
    exit 1
  end
end
```
+  詳細については、「[AWS SDK for Ruby デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-send-message.html)」を参照してください。
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[Publish](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/Publish)」を参照してください。**

### `SetTopicAttributes`
<a name="sns_SetTopicAttributes_ruby_3_topic"></a>

次のコード例は、`SetTopicAttributes` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
# Service class to enable an SNS resource with a specified policy
class SnsResourceEnabler
  # Initializes the SnsResourceEnabler with an SNS resource client
  #
  # @param sns_resource [Aws::SNS::Resource] The SNS resource client
  def initialize(sns_resource)
    @sns_resource = sns_resource
    @logger = Logger.new($stdout)
  end

  # Sets a policy on a specified SNS topic
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param resource_arn [String] The ARN of the resource to include in the policy
  # @param policy_name [String] The name of the policy attribute to set
  def enable_resource(topic_arn, resource_arn, policy_name)
    policy = generate_policy(topic_arn, resource_arn)
    topic = @sns_resource.topic(topic_arn)

    topic.set_attributes({
                           attribute_name: policy_name,
                           attribute_value: policy
                         })
    @logger.info("Policy #{policy_name} set successfully for topic #{topic_arn}.")
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Failed to set policy: #{e.message}")
  end

  private

  # Generates a policy string with dynamic resource ARNs
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param resource_arn [String] The ARN of the resource
  # @return [String] The policy as a JSON string
  def generate_policy(topic_arn, resource_arn)
    {
      Version: '2008-10-17',
      Id: '__default_policy_ID',
      Statement: [{
        Sid: '__default_statement_ID',
        Effect: 'Allow',
        Principal: { "AWS": '*' },
        Action: ['SNS:Publish'],
        Resource: topic_arn,
        Condition: {
          ArnEquals: {
            "AWS:SourceArn": resource_arn
          }
        }
      }]
    }.to_json
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_arn = 'MY_TOPIC_ARN' # Should be replaced with a real topic ARN
  resource_arn = 'MY_RESOURCE_ARN' # Should be replaced with a real resource ARN
  policy_name = 'POLICY_NAME' # Typically, this is "Policy"

  sns_resource = Aws::SNS::Resource.new
  enabler = SnsResourceEnabler.new(sns_resource)

  enabler.enable_resource(topic_arn, resource_arn, policy_name)
end
```
+  詳細については、「[AWS SDK for Ruby デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-enable-resource.html)」を参照してください。
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[SetTopicAttributes](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/SetTopicAttributes)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_ruby_3_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
require 'aws-sdk-sns'
require 'logger'

# Represents a service for creating subscriptions in Amazon Simple Notification Service (SNS)
class SubscriptionService
  # Initializes the SubscriptionService with an SNS client
  #
  # @param sns_client [Aws::SNS::Client] The SNS client
  def initialize(sns_client)
    @sns_client = sns_client
    @logger = Logger.new($stdout)
  end

  # Attempts to create a subscription to a topic
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param protocol [String] The subscription protocol (e.g., email)
  # @param endpoint [String] The endpoint that receives the notifications (email address)
  # @return [Boolean] true if subscription was successfully created, false otherwise
  def create_subscription(topic_arn, protocol, endpoint)
    @sns_client.subscribe(topic_arn: topic_arn, protocol: protocol, endpoint: endpoint)
    @logger.info('Subscription created successfully.')
    true
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Error while creating the subscription: #{e.message}")
    false
  end
end

# Main execution if the script is run directly
if $PROGRAM_NAME == __FILE__
  protocol = 'email'
  endpoint = 'EMAIL_ADDRESS' # Should be replaced with a real email address
  topic_arn = 'TOPIC_ARN'    # Should be replaced with a real topic ARN

  sns_client = Aws::SNS::Client.new
  subscription_service = SubscriptionService.new(sns_client)

  @logger.info('Creating the subscription.')
  unless subscription_service.create_subscription(topic_arn, protocol, endpoint)
    @logger.error('Subscription creation failed. Stopping program.')
    exit 1
  end
end
```
+  詳細については、「[AWS SDK for Ruby デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-create-subscription.html)」を参照してください。
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[Subscribe](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/Subscribe)」を参照してください。**

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_ruby_3_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での SNS イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event:, context:)
  event['Records'].map { |record| process_message(record) }
end

def process_message(record)
  message = record['Sns']['Message']
  puts("Processing message: #{message}")
rescue StandardError => e
  puts("Error processing message: #{e}")
  raise
end
```

# SDK for Ruby を使用した Amazon SQS の例
<a name="ruby_3_sqs_code_examples"></a>

次のコード例は、Amazon SQS AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `ChangeMessageVisibility`
<a name="sqs_ChangeMessageVisibility_ruby_3_topic"></a>

次のコード例は、`ChangeMessageVisibility` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sqs' # v2: require 'aws-sdk'
# Replace us-west-2 with the AWS Region you're using for Amazon SQS.
sqs = Aws::SQS::Client.new(region: 'us-west-2')

begin
  queue_name = 'my-queue'
  queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url

  # Receive up to 10 messages
  receive_message_result_before = sqs.receive_message({
                                                        queue_url: queue_url,
                                                        max_number_of_messages: 10
                                                      })

  puts "Before attempting to change message visibility timeout: received #{receive_message_result_before.messages.count} message(s)."

  receive_message_result_before.messages.each do |message|
    sqs.change_message_visibility({
                                    queue_url: queue_url,
                                    receipt_handle: message.receipt_handle,
                                    visibility_timeout: 30 # This message will not be visible for 30 seconds after first receipt.
                                  })
  end

  # Try to retrieve the original messages after setting their visibility timeout.
  receive_message_result_after = sqs.receive_message({
                                                       queue_url: queue_url,
                                                       max_number_of_messages: 10
                                                     })

  puts "\nAfter attempting to change message visibility timeout: received #{receive_message_result_after.messages.count} message(s)."
rescue Aws::SQS::Errors::NonExistentQueue
  puts "Cannot receive messages for a queue named '#{queue_name}', as it does not exist."
end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[ChangeMessageVisibility](https://docs.aws.amazon.com/goto/SdkForRubyV3/sqs-2012-11-05/ChangeMessageVisibility)」を参照してください。

### `CreateQueue`
<a name="sqs_CreateQueue_ruby_3_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
# This code example demonstrates how to create a queue in Amazon Simple Queue Service (Amazon SQS).

require 'aws-sdk-sqs'

# @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client.
# @param queue_name [String] The name of the queue.
# @return [Boolean] true if the queue was created; otherwise, false.
# @example
#   exit 1 unless queue_created?(
#     Aws::SQS::Client.new(region: 'us-west-2'),
#     'my-queue'
#   )
def queue_created?(sqs_client, queue_name)
  sqs_client.create_queue(queue_name: queue_name)
  true
rescue StandardError => e
  puts "Error creating queue: #{e.message}"
  false
end

# Full example call:
# Replace us-west-2 with the AWS Region you're using for Amazon SQS.
def run_me
  region = 'us-west-2'
  queue_name = 'my-queue'
  sqs_client = Aws::SQS::Client.new(region: region)

  puts "Creating the queue named '#{queue_name}'..."

  if queue_created?(sqs_client, queue_name)
    puts 'Queue created.'
  else
    puts 'Queue not created.'
  end
end

# Example usage:
run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[CreateQueue](https://docs.aws.amazon.com/goto/SdkForRubyV3/sqs-2012-11-05/CreateQueue)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_ruby_3_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sqs' # v2: require 'aws-sdk'
# Replace us-west-2 with the AWS Region you're using for Amazon SQS.
sqs = Aws::SQS::Client.new(region: 'us-west-2')

sqs.delete_queue(queue_url: URL)
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[DeleteQueue](https://docs.aws.amazon.com/goto/SdkForRubyV3/sqs-2012-11-05/DeleteQueue)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_ruby_3_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sqs'
require 'aws-sdk-sts'

# @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client.
# @example
#   list_queue_urls(Aws::SQS::Client.new(region: 'us-west-2'))
def list_queue_urls(sqs_client)
  queues = sqs_client.list_queues

  queues.queue_urls.each do |url|
    puts url
  end
rescue StandardError => e
  puts "Error listing queue URLs: #{e.message}"
end

# Lists the attributes of a queue in Amazon Simple Queue Service (Amazon SQS).
#
# @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client.
# @param queue_url [String] The URL of the queue.
# @example
#   list_queue_attributes(
#     Aws::SQS::Client.new(region: 'us-west-2'),
#     'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue'
#   )
def list_queue_attributes(sqs_client, queue_url)
  attributes = sqs_client.get_queue_attributes(
    queue_url: queue_url,
    attribute_names: ['All']
  )

  attributes.attributes.each do |key, value|
    puts "#{key}: #{value}"
  end
rescue StandardError => e
  puts "Error getting queue attributes: #{e.message}"
end

# Full example call:
# Replace us-west-2 with the AWS Region you're using for Amazon SQS.
def run_me
  region = 'us-west-2'
  queue_name = 'my-queue'

  sqs_client = Aws::SQS::Client.new(region: region)

  puts 'Listing available queue URLs...'
  list_queue_urls(sqs_client)

  sts_client = Aws::STS::Client.new(region: region)

  # For example:
  # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue'
  queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}"

  puts "\nGetting information about queue '#{queue_name}'..."
  list_queue_attributes(sqs_client, queue_url)
end
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[ListQueues](https://docs.aws.amazon.com/goto/SdkForRubyV3/sqs-2012-11-05/ListQueues)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_ruby_3_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sqs'
require 'aws-sdk-sts'

# Receives messages in a queue in Amazon Simple Queue Service (Amazon SQS).
#
# @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client.
# @param queue_url [String] The URL of the queue.
# @param max_number_of_messages [Integer] The maximum number of messages
#   to receive. This number must be 10 or less. The default is 10.
# @example
#   receive_messages(
#     Aws::SQS::Client.new(region: 'us-west-2'),
#     'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue',
#     10
#   )
def receive_messages(sqs_client, queue_url, max_number_of_messages = 10)
  if max_number_of_messages > 10
    puts 'Maximum number of messages to receive must be 10 or less. ' \
      'Stopping program.'
    return
  end

  response = sqs_client.receive_message(
    queue_url: queue_url,
    max_number_of_messages: max_number_of_messages
  )

  if response.messages.count.zero?
    puts 'No messages to receive, or all messages have already ' \
      'been previously received.'
    return
  end

  response.messages.each do |message|
    puts '-' * 20
    puts "Message body: #{message.body}"
    puts "Message ID:   #{message.message_id}"
  end
rescue StandardError => e
  puts "Error receiving messages: #{e.message}"
end

# Full example call:
# Replace us-west-2 with the AWS Region you're using for Amazon SQS.
def run_me
  region = 'us-west-2'
  queue_name = 'my-queue'
  max_number_of_messages = 10

  sts_client = Aws::STS::Client.new(region: region)

  # For example:
  # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue'
  queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}"

  sqs_client = Aws::SQS::Client.new(region: region)

  puts "Receiving messages from queue '#{queue_name}'..."

  receive_messages(sqs_client, queue_url, max_number_of_messages)
end

# Example usage:
run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、**AWS SDK for Ruby API リファレンスの「[ReceiveMessage](https://docs.aws.amazon.com/goto/SdkForRubyV3/sqs-2012-11-05/ReceiveMessage)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_ruby_3_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sqs'
require 'aws-sdk-sts'

# @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client.
# @param queue_url [String] The URL of the queue.
# @param message_body [String] The contents of the message to be sent.
# @return [Boolean] true if the message was sent; otherwise, false.
# @example
#   exit 1 unless message_sent?(
#     Aws::SQS::Client.new(region: 'us-west-2'),
#     'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue',
#     'This is my message.'
#   )
def message_sent?(sqs_client, queue_url, message_body)
  sqs_client.send_message(
    queue_url: queue_url,
    message_body: message_body
  )
  true
rescue StandardError => e
  puts "Error sending message: #{e.message}"
  false
end

# Full example call:
# Replace us-west-2 with the AWS Region you're using for Amazon SQS.
def run_me
  region = 'us-west-2'
  queue_name = 'my-queue'
  message_body = 'This is my message.'

  sts_client = Aws::STS::Client.new(region: region)

  # For example:
  # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue'
  queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}"

  sqs_client = Aws::SQS::Client.new(region: region)

  puts "Sending a message to the queue named '#{queue_name}'..."

  if message_sent?(sqs_client, queue_url, message_body)
    puts 'Message sent.'
  else
    puts 'Message not sent.'
  end
end

# Example usage:
run_me if $PROGRAM_NAME == __FILE__
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[SendMessage](https://docs.aws.amazon.com/goto/SdkForRubyV3/sqs-2012-11-05/SendMessage)」を参照してください。**

### `SendMessageBatch`
<a name="sqs_SendMessageBatch_ruby_3_topic"></a>

次のコード例は、`SendMessageBatch` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
require 'aws-sdk-sqs'
require 'aws-sdk-sts'

#
# @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client.
# @param queue_url [String] The URL of the queue.
# @param entries [Hash] The contents of the messages to be sent,
#   in the correct format.
# @return [Boolean] true if the messages were sent; otherwise, false.
# @example
#   exit 1 unless messages_sent?(
#     Aws::SQS::Client.new(region: 'us-west-2'),
#     'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue',
#     [
#       {
#         id: 'Message1',
#         message_body: 'This is the first message.'
#       },
#       {
#         id: 'Message2',
#         message_body: 'This is the second message.'
#       }
#     ]
#   )
def messages_sent?(sqs_client, queue_url, entries)
  sqs_client.send_message_batch(
    queue_url: queue_url,
    entries: entries
  )
  true
rescue StandardError => e
  puts "Error sending messages: #{e.message}"
  false
end

# Full example call:
# Replace us-west-2 with the AWS Region you're using for Amazon SQS.
def run_me
  region = 'us-west-2'
  queue_name = 'my-queue'
  entries = [
    {
      id: 'Message1',
      message_body: 'This is the first message.'
    },
    {
      id: 'Message2',
      message_body: 'This is the second message.'
    }
  ]

  sts_client = Aws::STS::Client.new(region: region)

  # For example:
  # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue'
  queue_url = "https://sqs.#{region}.amazonaws.com/#{sts_client.get_caller_identity.account}/#{queue_name}"

  sqs_client = Aws::SQS::Client.new(region: region)

  puts "Sending messages to the queue named '#{queue_name}'..."

  if messages_sent?(sqs_client, queue_url, entries)
    puts 'Messages sent.'
  else
    puts 'Messages not sent.'
  end
end
```
+  API の詳細については、「*AWS SDK for Ruby API リファレンス*」の「[SendMessageBatch](https://docs.aws.amazon.com/goto/SdkForRubyV3/sqs-2012-11-05/SendMessageBatch)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_ruby_3_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での SQS イベントの消費。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
def lambda_handler(event:, context:)
  event['Records'].each do |message|
    process_message(message)
  end
  puts "done"
end

def process_message(message)
  begin
    puts "Processed message #{message['body']}"
    # TODO: Do interesting work based on the new message
  rescue StandardError => err
    puts "An error occurred"
    raise err
  end
end
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_ruby_3_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Ruby を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
require 'json'

def lambda_handler(event:, context:)
  if event
    batch_item_failures = []
    sqs_batch_response = {}

    event["Records"].each do |record|
      begin
        # process message
      rescue StandardError => e
        batch_item_failures << {"itemIdentifier" => record['messageId']}
      end
    end

    sqs_batch_response["batchItemFailures"] = batch_item_failures
    return sqs_batch_response
  end
end
```

# AWS STS SDK for Ruby を使用した の例
<a name="ruby_3_sts_code_examples"></a>

次のコード例は、 AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_ruby_3_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
  # Creates an AWS Security Token Service (AWS STS) client with specified credentials.
  # This is separated into a factory function so that it can be mocked for unit testing.
  #
  # @param key_id [String] The ID of the access key used by the STS client.
  # @param key_secret [String] The secret part of the access key used by the STS client.
  def create_sts_client(key_id, key_secret)
    Aws::STS::Client.new(access_key_id: key_id, secret_access_key: key_secret)
  end

  # Gets temporary credentials that can be used to assume a role.
  #
  # @param role_arn [String] The ARN of the role that is assumed when these credentials
  #                          are used.
  # @param sts_client [AWS::STS::Client] An AWS STS client.
  # @return [Aws::AssumeRoleCredentials] The credentials that can be used to assume the role.
  def assume_role(role_arn, sts_client)
    credentials = Aws::AssumeRoleCredentials.new(
      client: sts_client,
      role_arn: role_arn,
      role_session_name: 'create-use-assume-role-scenario'
    )
    @logger.info("Assumed role '#{role_arn}', got temporary credentials.")
    credentials
  end
```
+  API の詳細については、AWS SDK for Ruby API リファレンスの「[AssumeRole](https://docs.aws.amazon.com/goto/SdkForRubyV3/sts-2011-06-15/AssumeRole)」を参照してください。**

# SDK for Ruby を使用する Amazon Textract の例
<a name="ruby_3_textract_code_examples"></a>

次のコード例は、Amazon Textract AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_ruby_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Ruby**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/cross_service_examples/feedback_sentiment_analyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Ruby を使用する Amazon Translate の例
<a name="ruby_3_translate_code_examples"></a>

次のコード例は、Amazon Translate AWS SDK for Ruby で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### 顧客からのフィードバックを分析するアプリケーションの作成
<a name="cross_FSA_ruby_3_topic"></a>

次のコード例は、顧客のコメントカードを分析し、元の言語から翻訳し、顧客の感情を判断して、翻訳されたテキストから音声ファイルを生成するアプリケーションの作成方法を示しています。

**SDK for Ruby**  
 このサンプルアプリケーションは、顧客フィードバックカードを分析し、保存します。具体的には、ニューヨーク市の架空のホテルのニーズを満たします。このホテルでは、お客様からのフィードバックをさまざまな言語で書かれた実際のコメントカードの形で受け取ります。そのフィードバックは、ウェブクライアントを通じてアプリにアップロードされます。コメントカードの画像をアップロードされると、次の手順が発生します。  
+ テキストは Amazon Textract を使用して、画像から抽出されます。
+ Amazon Comprehend は、抽出したテキストの感情とその言語を分析します。
+ 抽出されたテキストは、Amazon Translate を使用して英語に翻訳されます。
+ Amazon Polly は抽出したテキストから音声ファイルを合成します。
 完全なアプリは  AWS CDK を使用してデプロイすることができます。ソースコードとデプロイ手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/cross_service_examples/feedback_sentiment_analyzer) のプロジェクトを参照してください。  

**この例で使用されているサービス**
+ Amazon Comprehend
+ Lambda
+ Amazon Polly
+ Amazon Textract
+ Amazon Translate

# SDK for Rust のコード例
<a name="rust_1_code_examples"></a>

次のコード例は、 で AWS SDK for Rust を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for Rust デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-rust/latest/dg/welcome.html) ** – で Rust を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23rust)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [API ゲートウェイ](rust_1_api-gateway_code_examples.md)
+ [API Gateway Management API](rust_1_apigatewaymanagementapi_code_examples.md)
+ [Application Auto Scaling](rust_1_application-auto-scaling_code_examples.md)
+ [Aurora](rust_1_aurora_code_examples.md)
+ [Auto Scaling](rust_1_auto-scaling_code_examples.md)
+ [Amazon Bedrock ランタイム](rust_1_bedrock-runtime_code_examples.md)
+ [Amazon Bedrock エージェントランタイム](rust_1_bedrock-agent-runtime_code_examples.md)
+ [Amazon Cognito ID プロバイダー](rust_1_cognito-identity-provider_code_examples.md)
+ [Amazon Cognito Sync](rust_1_cognito-sync_code_examples.md)
+ [Firehose](rust_1_firehose_code_examples.md)
+ [Amazon DocumentDB](rust_1_docdb_code_examples.md)
+ [DynamoDB](rust_1_dynamodb_code_examples.md)
+ [Amazon EBS](rust_1_ebs_code_examples.md)
+ [Amazon EC2](rust_1_ec2_code_examples.md)
+ [Amazon ECR](rust_1_ecr_code_examples.md)
+ [Amazon ECS](rust_1_ecs_code_examples.md)
+ [Amazon EKS](rust_1_eks_code_examples.md)
+ [AWS Glue](rust_1_glue_code_examples.md)
+ [IAM](rust_1_iam_code_examples.md)
+ [AWS IoT](rust_1_iot_code_examples.md)
+ [Kinesis](rust_1_kinesis_code_examples.md)
+ [AWS KMS](rust_1_kms_code_examples.md)
+ [Lambda](rust_1_lambda_code_examples.md)
+ [MediaLive](rust_1_medialive_code_examples.md)
+ [MediaPackage](rust_1_mediapackage_code_examples.md)
+ [Amazon MSK](rust_1_kafka_code_examples.md)
+ [Amazon Polly](rust_1_polly_code_examples.md)
+ [Amazon RDS](rust_1_rds_code_examples.md)
+ [Amazon RDS データサービス](rust_1_rds-data_code_examples.md)
+ [Amazon Rekognition](rust_1_rekognition_code_examples.md)
+ [Route 53](rust_1_route-53_code_examples.md)
+ [Amazon S3](rust_1_s3_code_examples.md)
+ [SageMaker AI](rust_1_sagemaker_code_examples.md)
+ [Secrets Manager](rust_1_secrets-manager_code_examples.md)
+ [Amazon SES API v2](rust_1_sesv2_code_examples.md)
+ [Amazon SNS](rust_1_sns_code_examples.md)
+ [Amazon SQS](rust_1_sqs_code_examples.md)
+ [AWS STS](rust_1_sts_code_examples.md)
+ [Systems Manager](rust_1_ssm_code_examples.md)
+ [Amazon Transcribe](rust_1_transcribe_code_examples.md)

# SDK for Rust を使用した API Gateway の例
<a name="rust_1_api-gateway_code_examples"></a>

次のコード例は、API Gateway で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## アクション
<a name="actions"></a>

### `GetRestApis`
<a name="api-gateway_GetRestApis_rust_1_topic"></a>

次のコード例は、`GetRestApis` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/apigateway#code-examples)での設定と実行の方法を確認してください。
リージョンの Amazon API Gateway REST API を表示します。  

```
async fn show_apis(client: &Client) -> Result<(), Error> {
    let resp = client.get_rest_apis().send().await?;

    for api in resp.items() {
        println!("ID:          {}", api.id().unwrap_or_default());
        println!("Name:        {}", api.name().unwrap_or_default());
        println!("Description: {}", api.description().unwrap_or_default());
        println!("Version:     {}", api.version().unwrap_or_default());
        println!(
            "Created:     {}",
            api.created_date().unwrap().to_chrono_utc()?
        );
        println!();
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[GetRestApis](https://docs.rs/aws-sdk-apigateway/latest/aws_sdk_apigateway/client/struct.Client.html#method.get_rest_apis)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_rust_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Rust**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/cross_service/photo_asset_management) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_rust_1_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Rust**  
 Rust SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-rust-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Rust を使用した API Gateway Management API の例
<a name="rust_1_apigatewaymanagementapi_code_examples"></a>

次のコード例は、API Gateway Management API で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PostToConnection`
<a name="apigatewaymanagementapi_PostToConnection_rust_1_topic"></a>

次のコード例は、`PostToConnection` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/apigatewaymanagement#code-examples)での設定と実行の方法を確認してください。

```
async fn send_data(
    client: &aws_sdk_apigatewaymanagement::Client,
    con_id: &str,
    data: &str,
) -> Result<(), aws_sdk_apigatewaymanagement::Error> {
    client
        .post_to_connection()
        .connection_id(con_id)
        .data(Blob::new(data))
        .send()
        .await?;

    Ok(())
}

    let endpoint_url = format!(
        "https://{api_id}.execute-api.{region}.amazonaws.com/{stage}",
        api_id = api_id,
        region = region,
        stage = stage
    );

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let api_management_config = config::Builder::from(&shared_config)
        .endpoint_url(endpoint_url)
        .build();
    let client = Client::from_conf(api_management_config);
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[PostToConnection](https://docs.rs/aws-sdk-apigatewaymanagementapi/latest/aws_sdk_apigatewaymanagementapi/client/struct.Client.html#method.post_to_connection)」を参照してください。

# SDK for Rust を使用した Auto Scaling の例
<a name="rust_1_application-auto-scaling_code_examples"></a>

次のコード例は、Application Auto Scaling で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeScalingPolicies`
<a name="application-auto-scaling_DescribeScalingPolicies_rust_1_topic"></a>

次のコード例は、`DescribeScalingPolicies` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/applicationautoscaling#code-examples)での設定と実行の方法を確認してください。

```
async fn show_policies(client: &Client) -> Result<(), Error> {
    let response = client
        .describe_scaling_policies()
        .service_namespace(ServiceNamespace::Ec2)
        .send()
        .await?;
    println!("Auto Scaling Policies:");
    for policy in response.scaling_policies() {
        println!("{:?}\n", policy);
    }
    println!("Next token: {:?}", response.next_token());

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeScalingPolicies](https://docs.rs/aws-sdk-applicationautoscaling/latest/aws_sdk_applicationautoscaling/client/struct.Client.html#method.describe_scaling_policies)」を参照してください。

# SDK for Rust を使用した Aurora の例
<a name="rust_1_aurora_code_examples"></a>

次のコード例は、Aurora で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Aurora
<a name="aurora_Hello_rust_1_topic"></a>

次のコード例は、Aurora の使用を開始する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
use aws_sdk_rds::Client;

#[derive(Debug)]
struct Error(String);
impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}
impl std::error::Error for Error {}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt::init();
    let sdk_config = aws_config::from_env().load().await;
    let client = Client::new(&sdk_config);

    let describe_db_clusters_output = client
        .describe_db_clusters()
        .send()
        .await
        .map_err(|e| Error(e.to_string()))?;
    println!(
        "Found {} clusters:",
        describe_db_clusters_output.db_clusters().len()
    );
    for cluster in describe_db_clusters_output.db_clusters() {
        let name = cluster.database_name().unwrap_or("Unknown");
        let engine = cluster.engine().unwrap_or("Unknown");
        let id = cluster.db_cluster_identifier().unwrap_or("Unknown");
        let class = cluster.db_cluster_instance_class().unwrap_or("Unknown");
        println!("\tDatabase: {name}",);
        println!("\t  Engine: {engine}",);
        println!("\t      ID: {id}",);
        println!("\tInstance: {class}",);
    }

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeDBClusters](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_clusters)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="aurora_Scenario_GetStartedClusters_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム Aurora DB クラスターパラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用する DB クラスターを作成する
+ データベースを含む DB インスタンスを作成します。
+ DB クラスターのスナップショットを作成して、リソースをクリーンアップします。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。
Aurora シナリオのシナリオ固有の関数を含むライブラリ。  

```
use phf::{phf_set, Set};
use secrecy::SecretString;
use std::{collections::HashMap, fmt::Display, time::Duration};

use aws_sdk_rds::{
    error::ProvideErrorMetadata,
    operation::create_db_cluster_parameter_group::CreateDbClusterParameterGroupOutput,
    types::{DbCluster, DbClusterParameterGroup, DbClusterSnapshot, DbInstance, Parameter},
};
use sdk_examples_test_utils::waiter::Waiter;
use tracing::{info, trace, warn};

const DB_ENGINE: &str = "aurora-mysql";
const DB_CLUSTER_PARAMETER_GROUP_NAME: &str = "RustSDKCodeExamplesDBParameterGroup";
const DB_CLUSTER_PARAMETER_GROUP_DESCRIPTION: &str =
    "Parameter Group created by Rust SDK Code Example";
const DB_CLUSTER_IDENTIFIER: &str = "RustSDKCodeExamplesDBCluster";
const DB_INSTANCE_IDENTIFIER: &str = "RustSDKCodeExamplesDBInstance";

static FILTER_PARAMETER_NAMES: Set<&'static str> = phf_set! {
    "auto_increment_offset",
    "auto_increment_increment",
};

#[derive(Debug, PartialEq, Eq)]
struct MetadataError {
    message: Option<String>,
    code: Option<String>,
}

impl MetadataError {
    fn from(err: &dyn ProvideErrorMetadata) -> Self {
        MetadataError {
            message: err.message().map(String::from),
            code: err.code().map(String::from),
        }
    }
}

impl Display for MetadataError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let display = match (&self.message, &self.code) {
            (None, None) => "Unknown".to_string(),
            (None, Some(code)) => format!("({code})"),
            (Some(message), None) => message.to_string(),
            (Some(message), Some(code)) => format!("{message} ({code})"),
        };
        write!(f, "{display}")
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct ScenarioError {
    message: String,
    context: Option<MetadataError>,
}

impl ScenarioError {
    pub fn with(message: impl Into<String>) -> Self {
        ScenarioError {
            message: message.into(),
            context: None,
        }
    }

    pub fn new(message: impl Into<String>, err: &dyn ProvideErrorMetadata) -> Self {
        ScenarioError {
            message: message.into(),
            context: Some(MetadataError::from(err)),
        }
    }
}

impl std::error::Error for ScenarioError {}
impl Display for ScenarioError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.context {
            Some(c) => write!(f, "{}: {}", self.message, c),
            None => write!(f, "{}", self.message),
        }
    }
}

// Parse the ParameterName, Description, and AllowedValues values and display them.
#[derive(Debug)]
pub struct AuroraScenarioParameter {
    name: String,
    allowed_values: String,
    current_value: String,
}

impl Display for AuroraScenarioParameter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: {} (allowed: {})",
            self.name, self.current_value, self.allowed_values
        )
    }
}

impl From<aws_sdk_rds::types::Parameter> for AuroraScenarioParameter {
    fn from(value: aws_sdk_rds::types::Parameter) -> Self {
        AuroraScenarioParameter {
            name: value.parameter_name.unwrap_or_default(),
            allowed_values: value.allowed_values.unwrap_or_default(),
            current_value: value.parameter_value.unwrap_or_default(),
        }
    }
}

pub struct AuroraScenario {
    rds: crate::rds::Rds,
    engine_family: Option<String>,
    engine_version: Option<String>,
    instance_class: Option<String>,
    db_cluster_parameter_group: Option<DbClusterParameterGroup>,
    db_cluster_identifier: Option<String>,
    db_instance_identifier: Option<String>,
    username: Option<String>,
    password: Option<SecretString>,
}

impl AuroraScenario {
    pub fn new(client: crate::rds::Rds) -> Self {
        AuroraScenario {
            rds: client,
            engine_family: None,
            engine_version: None,
            instance_class: None,
            db_cluster_parameter_group: None,
            db_cluster_identifier: None,
            db_instance_identifier: None,
            username: None,
            password: None,
        }
    }

    // Get available engine families for Aurora MySql. rds.DescribeDbEngineVersions(Engine='aurora-mysql') and build a set of the 'DBParameterGroupFamily' field values. I get {aurora-mysql8.0, aurora-mysql5.7}.
    pub async fn get_engines(&self) -> Result<HashMap<String, Vec<String>>, ScenarioError> {
        let describe_db_engine_versions = self.rds.describe_db_engine_versions(DB_ENGINE).await;
        trace!(versions=?describe_db_engine_versions, "full list of versions");

        if let Err(err) = describe_db_engine_versions {
            return Err(ScenarioError::new(
                "Failed to retrieve DB Engine Versions",
                &err,
            ));
        };

        let version_count = describe_db_engine_versions
            .as_ref()
            .map(|o| o.db_engine_versions().len())
            .unwrap_or_default();
        info!(version_count, "got list of versions");

        // Create a map of engine families to their available versions.
        let mut versions = HashMap::<String, Vec<String>>::new();
        describe_db_engine_versions
            .unwrap()
            .db_engine_versions()
            .iter()
            .filter_map(
                |v| match (&v.db_parameter_group_family, &v.engine_version) {
                    (Some(family), Some(version)) => Some((family.clone(), version.clone())),
                    _ => None,
                },
            )
            .for_each(|(family, version)| versions.entry(family).or_default().push(version));

        Ok(versions)
    }

    pub async fn get_instance_classes(&self) -> Result<Vec<String>, ScenarioError> {
        let describe_orderable_db_instance_options_items = self
            .rds
            .describe_orderable_db_instance_options(
                DB_ENGINE,
                self.engine_version
                    .as_ref()
                    .expect("engine version for db instance options")
                    .as_str(),
            )
            .await;

        describe_orderable_db_instance_options_items
            .map(|options| {
                options
                    .iter()
                    .filter(|o| o.storage_type() == Some("aurora"))
                    .map(|o| o.db_instance_class().unwrap_or_default().to_string())
                    .collect::<Vec<String>>()
            })
            .map_err(|err| ScenarioError::new("Could not get available instance classes", &err))
    }

    // Select an engine family and create a custom DB cluster parameter group. rds.CreateDbClusterParameterGroup(DBParameterGroupFamily='aurora-mysql8.0')
    pub async fn set_engine(&mut self, engine: &str, version: &str) -> Result<(), ScenarioError> {
        self.engine_family = Some(engine.to_string());
        self.engine_version = Some(version.to_string());
        let create_db_cluster_parameter_group = self
            .rds
            .create_db_cluster_parameter_group(
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                DB_CLUSTER_PARAMETER_GROUP_DESCRIPTION,
                engine,
            )
            .await;

        match create_db_cluster_parameter_group {
            Ok(CreateDbClusterParameterGroupOutput {
                db_cluster_parameter_group: None,
                ..
            }) => {
                return Err(ScenarioError::with(
                    "CreateDBClusterParameterGroup had empty response",
                ));
            }
            Err(error) => {
                if error.code() == Some("DBParameterGroupAlreadyExists") {
                    info!("Cluster Parameter Group already exists, nothing to do");
                } else {
                    return Err(ScenarioError::new(
                        "Could not create Cluster Parameter Group",
                        &error,
                    ));
                }
            }
            _ => {
                info!("Created Cluster Parameter Group");
            }
        }

        Ok(())
    }

    pub fn set_instance_class(&mut self, instance_class: Option<String>) {
        self.instance_class = instance_class;
    }

    pub fn set_login(&mut self, username: Option<String>, password: Option<SecretString>) {
        self.username = username;
        self.password = password;
    }

    pub async fn connection_string(&self) -> Result<String, ScenarioError> {
        let cluster = self.get_cluster().await?;
        let endpoint = cluster.endpoint().unwrap_or_default();
        let port = cluster.port().unwrap_or_default();
        let username = cluster.master_username().unwrap_or_default();
        Ok(format!("mysql -h {endpoint} -P {port} -u {username} -p"))
    }

    pub async fn get_cluster(&self) -> Result<DbCluster, ScenarioError> {
        let describe_db_clusters_output = self
            .rds
            .describe_db_clusters(
                self.db_cluster_identifier
                    .as_ref()
                    .expect("cluster identifier")
                    .as_str(),
            )
            .await;
        if let Err(err) = describe_db_clusters_output {
            return Err(ScenarioError::new("Failed to get cluster", &err));
        }

        let db_cluster = describe_db_clusters_output
            .unwrap()
            .db_clusters
            .and_then(|output| output.first().cloned());

        db_cluster.ok_or_else(|| ScenarioError::with("Did not find the cluster"))
    }

    // Get the parameter group. rds.DescribeDbClusterParameterGroups
    // Get parameters in the group. This is a long list so you will have to paginate. Find the auto_increment_offset and auto_increment_increment parameters (by ParameterName). rds.DescribeDbClusterParameters
    // Parse the ParameterName, Description, and AllowedValues values and display them.
    pub async fn cluster_parameters(&self) -> Result<Vec<AuroraScenarioParameter>, ScenarioError> {
        let parameters_output = self
            .rds
            .describe_db_cluster_parameters(DB_CLUSTER_PARAMETER_GROUP_NAME)
            .await;

        if let Err(err) = parameters_output {
            return Err(ScenarioError::new(
                format!("Failed to retrieve parameters for {DB_CLUSTER_PARAMETER_GROUP_NAME}"),
                &err,
            ));
        }

        let parameters = parameters_output
            .unwrap()
            .into_iter()
            .flat_map(|p| p.parameters.unwrap_or_default().into_iter())
            .filter(|p| FILTER_PARAMETER_NAMES.contains(p.parameter_name().unwrap_or_default()))
            .map(AuroraScenarioParameter::from)
            .collect::<Vec<_>>();

        Ok(parameters)
    }

    // Modify both the auto_increment_offset and auto_increment_increment parameters in one call in the custom parameter group. Set their ParameterValue fields to a new allowable value. rds.ModifyDbClusterParameterGroup.
    pub async fn update_auto_increment(
        &self,
        offset: u8,
        increment: u8,
    ) -> Result<(), ScenarioError> {
        let modify_db_cluster_parameter_group = self
            .rds
            .modify_db_cluster_parameter_group(
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                vec![
                    Parameter::builder()
                        .parameter_name("auto_increment_offset")
                        .parameter_value(format!("{offset}"))
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                    Parameter::builder()
                        .parameter_name("auto_increment_increment")
                        .parameter_value(format!("{increment}"))
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                ],
            )
            .await;

        if let Err(error) = modify_db_cluster_parameter_group {
            return Err(ScenarioError::new(
                "Failed to modify cluster parameter group",
                &error,
            ));
        }

        Ok(())
    }

    // Get a list of allowed engine versions. rds.DescribeDbEngineVersions(Engine='aurora-mysql', DBParameterGroupFamily=<the family used to create your parameter group in step 2>)
    // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created.
    // Wait for DB cluster to be ready. Call rds.DescribeDBClusters and check for Status == 'available'.
    // Get a list of instance classes available for the selected engine and engine version. rds.DescribeOrderableDbInstanceOptions(Engine='mysql', EngineVersion=).

    // Create a database instance in the cluster.
    // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'.
    pub async fn start_cluster_and_instance(&mut self) -> Result<(), ScenarioError> {
        if self.password.is_none() {
            return Err(ScenarioError::with(
                "Must set Secret Password before starting a cluster",
            ));
        }
        let create_db_cluster = self
            .rds
            .create_db_cluster(
                DB_CLUSTER_IDENTIFIER,
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                DB_ENGINE,
                self.engine_version.as_deref().expect("engine version"),
                self.username.as_deref().expect("username"),
                self.password
                    .replace(SecretString::new("".to_string()))
                    .expect("password"),
            )
            .await;
        if let Err(err) = create_db_cluster {
            return Err(ScenarioError::new(
                "Failed to create DB Cluster with cluster group",
                &err,
            ));
        }

        self.db_cluster_identifier = create_db_cluster
            .unwrap()
            .db_cluster
            .and_then(|c| c.db_cluster_identifier);

        if self.db_cluster_identifier.is_none() {
            return Err(ScenarioError::with("Created DB Cluster missing Identifier"));
        }

        info!(
            "Started a db cluster: {}",
            self.db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing ARN")
        );

        let create_db_instance = self
            .rds
            .create_db_instance(
                self.db_cluster_identifier.as_deref().expect("cluster name"),
                DB_INSTANCE_IDENTIFIER,
                self.instance_class.as_deref().expect("instance class"),
                DB_ENGINE,
            )
            .await;
        if let Err(err) = create_db_instance {
            return Err(ScenarioError::new(
                "Failed to create Instance in DB Cluster",
                &err,
            ));
        }

        self.db_instance_identifier = create_db_instance
            .unwrap()
            .db_instance
            .and_then(|i| i.db_instance_identifier);

        // Cluster creation can take up to 20 minutes to become available
        let cluster_max_wait = Duration::from_secs(20 * 60);
        let waiter = Waiter::builder().max(cluster_max_wait).build();
        while waiter.sleep().await.is_ok() {
            let cluster = self
                .rds
                .describe_db_clusters(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = cluster {
                warn!(?err, "Failed to describe cluster while waiting for ready");
                continue;
            }

            let instance = self
                .rds
                .describe_db_instance(
                    self.db_instance_identifier
                        .as_deref()
                        .expect("instance identifier"),
                )
                .await;
            if let Err(err) = instance {
                return Err(ScenarioError::new(
                    "Failed to find instance for cluster",
                    &err,
                ));
            }

            let instances_available = instance
                .unwrap()
                .db_instances()
                .iter()
                .all(|instance| instance.db_instance_status() == Some("Available"));

            let endpoints = self
                .rds
                .describe_db_cluster_endpoints(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = endpoints {
                return Err(ScenarioError::new(
                    "Failed to find endpoint for cluster",
                    &err,
                ));
            }

            let endpoints_available = endpoints
                .unwrap()
                .db_cluster_endpoints()
                .iter()
                .all(|endpoint| endpoint.status() == Some("available"));

            if instances_available && endpoints_available {
                return Ok(());
            }
        }

        Err(ScenarioError::with("timed out waiting for cluster"))
    }

    // Create a snapshot of the DB cluster. rds.CreateDbClusterSnapshot.
    // Wait for the snapshot to create. rds.DescribeDbClusterSnapshots until Status == 'available'.
    pub async fn snapshot(&self, name: &str) -> Result<DbClusterSnapshot, ScenarioError> {
        let id = self.db_cluster_identifier.as_deref().unwrap_or_default();
        let snapshot = self
            .rds
            .snapshot_cluster(id, format!("{id}_{name}").as_str())
            .await;
        match snapshot {
            Ok(output) => match output.db_cluster_snapshot {
                Some(snapshot) => Ok(snapshot),
                None => Err(ScenarioError::with("Missing Snapshot")),
            },
            Err(err) => Err(ScenarioError::new("Failed to create snapshot", &err)),
        }
    }

    pub async fn clean_up(self) -> Result<(), Vec<ScenarioError>> {
        let mut clean_up_errors: Vec<ScenarioError> = vec![];

        // Delete the instance. rds.DeleteDbInstance.
        let delete_db_instance = self
            .rds
            .delete_db_instance(
                self.db_instance_identifier
                    .as_deref()
                    .expect("instance identifier"),
            )
            .await;
        if let Err(err) = delete_db_instance {
            let identifier = self
                .db_instance_identifier
                .as_deref()
                .unwrap_or("Missing Instance Identifier");
            let message = format!("failed to delete db instance {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance to delete
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_instances = self.rds.describe_db_instances().await;
                if let Err(err) = describe_db_instances {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check instance state during deletion",
                        &err,
                    ));
                    break;
                }
                let db_instances = describe_db_instances
                    .unwrap()
                    .db_instances()
                    .iter()
                    .filter(|instance| instance.db_cluster_identifier == self.db_cluster_identifier)
                    .cloned()
                    .collect::<Vec<DbInstance>>();

                if db_instances.is_empty() {
                    trace!("Delete Instance waited and no instances were found");
                    break;
                }
                match db_instances.first().unwrap().db_instance_status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but instances is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB instance");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster. rds.DeleteDbCluster.
        let delete_db_cluster = self
            .rds
            .delete_db_cluster(
                self.db_cluster_identifier
                    .as_deref()
                    .expect("cluster identifier"),
            )
            .await;

        if let Err(err) = delete_db_cluster {
            let identifier = self
                .db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing DB Cluster Identifier");
            let message = format!("failed to delete db cluster {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance and cluster to fully delete. rds.DescribeDbInstances and rds.DescribeDbClusters until both are not found.
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_clusters = self
                    .rds
                    .describe_db_clusters(
                        self.db_cluster_identifier
                            .as_deref()
                            .expect("cluster identifier"),
                    )
                    .await;
                if let Err(err) = describe_db_clusters {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check cluster state during deletion",
                        &err,
                    ));
                    break;
                }
                let describe_db_clusters = describe_db_clusters.unwrap();
                let db_clusters = describe_db_clusters.db_clusters();
                if db_clusters.is_empty() {
                    trace!("Delete cluster waited and no clusters were found");
                    break;
                }
                match db_clusters.first().unwrap().status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but clusters is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB cluster");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster parameter group. rds.DeleteDbClusterParameterGroup.
        let delete_db_cluster_parameter_group = self
            .rds
            .delete_db_cluster_parameter_group(
                self.db_cluster_parameter_group
                    .map(|g| {
                        g.db_cluster_parameter_group_name
                            .unwrap_or_else(|| DB_CLUSTER_PARAMETER_GROUP_NAME.to_string())
                    })
                    .as_deref()
                    .expect("cluster parameter group name"),
            )
            .await;
        if let Err(error) = delete_db_cluster_parameter_group {
            clean_up_errors.push(ScenarioError::new(
                "Failed to delete the db cluster parameter group",
                &error,
            ))
        }

        if clean_up_errors.is_empty() {
            Ok(())
        } else {
            Err(clean_up_errors)
        }
    }
}

#[cfg(test)]
pub mod tests;
```
RDS Client ラッパーのオートモックを使用してライブラリをテストします。  

```
use crate::rds::MockRdsImpl;

use super::*;

use std::io::{Error, ErrorKind};

use assert_matches::assert_matches;
use aws_sdk_rds::{
    error::SdkError,
    operation::{
        create_db_cluster::{CreateDBClusterError, CreateDbClusterOutput},
        create_db_cluster_parameter_group::CreateDBClusterParameterGroupError,
        create_db_cluster_snapshot::{CreateDBClusterSnapshotError, CreateDbClusterSnapshotOutput},
        create_db_instance::{CreateDBInstanceError, CreateDbInstanceOutput},
        delete_db_cluster::DeleteDbClusterOutput,
        delete_db_cluster_parameter_group::DeleteDbClusterParameterGroupOutput,
        delete_db_instance::DeleteDbInstanceOutput,
        describe_db_cluster_endpoints::DescribeDbClusterEndpointsOutput,
        describe_db_cluster_parameters::{
            DescribeDBClusterParametersError, DescribeDbClusterParametersOutput,
        },
        describe_db_clusters::{DescribeDBClustersError, DescribeDbClustersOutput},
        describe_db_engine_versions::{
            DescribeDBEngineVersionsError, DescribeDbEngineVersionsOutput,
        },
        describe_db_instances::{DescribeDBInstancesError, DescribeDbInstancesOutput},
        describe_orderable_db_instance_options::DescribeOrderableDBInstanceOptionsError,
        modify_db_cluster_parameter_group::{
            ModifyDBClusterParameterGroupError, ModifyDbClusterParameterGroupOutput,
        },
    },
    types::{
        error::DbParameterGroupAlreadyExistsFault, DbClusterEndpoint, DbEngineVersion,
        OrderableDbInstanceOption,
    },
};
use aws_smithy_runtime_api::http::{Response, StatusCode};
use aws_smithy_types::body::SdkBody;
use mockall::predicate::eq;
use secrecy::ExposeSecret;

#[tokio::test]
async fn test_scenario_set_engine() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .with(
            eq("RustSDKCodeExamplesDBParameterGroup"),
            eq("Parameter Group created by Rust SDK Code Example"),
            eq("aurora-mysql"),
        )
        .return_once(|_, _, _| {
            Ok(CreateDbClusterParameterGroupOutput::builder()
                .db_cluster_parameter_group(DbClusterParameterGroup::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);

    let set_engine = scenario.set_engine("aurora-mysql", "aurora-mysql8.0").await;

    assert_eq!(set_engine, Ok(()));
    assert_eq!(Some("aurora-mysql"), scenario.engine_family.as_deref());
    assert_eq!(Some("aurora-mysql8.0"), scenario.engine_version.as_deref());
}

#[tokio::test]
async fn test_scenario_set_engine_not_create() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .with(
            eq("RustSDKCodeExamplesDBParameterGroup"),
            eq("Parameter Group created by Rust SDK Code Example"),
            eq("aurora-mysql"),
        )
        .return_once(|_, _, _| Ok(CreateDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);

    let set_engine = scenario.set_engine("aurora-mysql", "aurora-mysql8.0").await;

    assert!(set_engine.is_err());
}

#[tokio::test]
async fn test_scenario_set_engine_param_group_exists() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .withf(|_, _, _| true)
        .return_once(|_, _, _| {
            Err(SdkError::service_error(
                CreateDBClusterParameterGroupError::DbParameterGroupAlreadyExistsFault(
                    DbParameterGroupAlreadyExistsFault::builder().build(),
                ),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);

    let set_engine = scenario.set_engine("aurora-mysql", "aurora-mysql8.0").await;

    assert!(set_engine.is_err());
}

#[tokio::test]
async fn test_scenario_get_engines() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_engine_versions()
        .with(eq("aurora-mysql"))
        .return_once(|_| {
            Ok(DescribeDbEngineVersionsOutput::builder()
                .db_engine_versions(
                    DbEngineVersion::builder()
                        .db_parameter_group_family("f1")
                        .engine_version("f1a")
                        .build(),
                )
                .db_engine_versions(
                    DbEngineVersion::builder()
                        .db_parameter_group_family("f1")
                        .engine_version("f1b")
                        .build(),
                )
                .db_engine_versions(
                    DbEngineVersion::builder()
                        .db_parameter_group_family("f2")
                        .engine_version("f2a")
                        .build(),
                )
                .db_engine_versions(DbEngineVersion::builder().build())
                .build())
        });

    let scenario = AuroraScenario::new(mock_rds);

    let versions_map = scenario.get_engines().await;

    assert_eq!(
        versions_map,
        Ok(HashMap::from([
            ("f1".into(), vec!["f1a".into(), "f1b".into()]),
            ("f2".into(), vec!["f2a".into()])
        ]))
    );
}

#[tokio::test]
async fn test_scenario_get_engines_failed() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_engine_versions()
        .with(eq("aurora-mysql"))
        .return_once(|_| {
            Err(SdkError::service_error(
                DescribeDBEngineVersionsError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe_db_engine_versions error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let scenario = AuroraScenario::new(mock_rds);

    let versions_map = scenario.get_engines().await;
    assert_matches!(
        versions_map,
        Err(ScenarioError { message, context: _ }) if message == "Failed to retrieve DB Engine Versions"
    );
}

#[tokio::test]
async fn test_scenario_get_instance_classes() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .return_once(|_, _, _| {
            Ok(CreateDbClusterParameterGroupOutput::builder()
                .db_cluster_parameter_group(DbClusterParameterGroup::builder().build())
                .build())
        });

    mock_rds
        .expect_describe_orderable_db_instance_options()
        .with(eq("aurora-mysql"), eq("aurora-mysql8.0"))
        .return_once(|_, _| {
            Ok(vec![
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t1")
                    .storage_type("aurora")
                    .build(),
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t1")
                    .storage_type("aurora-iopt1")
                    .build(),
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t2")
                    .storage_type("aurora")
                    .build(),
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t3")
                    .storage_type("aurora")
                    .build(),
            ])
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario
        .set_engine("aurora-mysql", "aurora-mysql8.0")
        .await
        .expect("set engine");

    let instance_classes = scenario.get_instance_classes().await;

    assert_eq!(
        instance_classes,
        Ok(vec!["t1".into(), "t2".into(), "t3".into()])
    );
}

#[tokio::test]
async fn test_scenario_get_instance_classes_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_orderable_db_instance_options()
        .with(eq("aurora-mysql"), eq("aurora-mysql8.0"))
        .return_once(|_, _| {
            Err(SdkError::service_error(
                DescribeOrderableDBInstanceOptionsError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe_orderable_db_instance_options_error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_family = Some("aurora-mysql".into());
    scenario.engine_version = Some("aurora-mysql8.0".into());

    let instance_classes = scenario.get_instance_classes().await;

    assert_matches!(
        instance_classes,
        Err(ScenarioError {message, context: _}) if message == "Could not get available instance classes"
    );
}

#[tokio::test]
async fn test_scenario_get_cluster() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());
    let cluster = scenario.get_cluster().await;

    assert!(cluster.is_ok());
}

#[tokio::test]
async fn test_scenario_get_cluster_missing_cluster() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .return_once(|_, _, _| {
            Ok(CreateDbClusterParameterGroupOutput::builder()
                .db_cluster_parameter_group(DbClusterParameterGroup::builder().build())
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| Ok(DescribeDbClustersOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());
    let cluster = scenario.get_cluster().await;

    assert_matches!(cluster, Err(ScenarioError { message, context: _ }) if message == "Did not find the cluster");
}

#[tokio::test]
async fn test_scenario_get_cluster_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .return_once(|_, _, _| {
            Ok(CreateDbClusterParameterGroupOutput::builder()
                .db_cluster_parameter_group(DbClusterParameterGroup::builder().build())
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe_db_clusters_error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());
    let cluster = scenario.get_cluster().await;

    assert_matches!(cluster, Err(ScenarioError { message, context: _ }) if message == "Failed to get cluster");
}

#[tokio::test]
async fn test_scenario_connection_string() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .endpoint("test_endpoint")
                        .port(3306)
                        .master_username("test_username")
                        .build(),
                )
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());
    let connection_string = scenario.connection_string().await;

    assert_eq!(
        connection_string,
        Ok("mysql -h test_endpoint -P 3306 -u test_username -p".into())
    );
}

#[tokio::test]
async fn test_scenario_cluster_parameters() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_cluster_parameters()
        .with(eq("RustSDKCodeExamplesDBParameterGroup"))
        .return_once(|_| {
            Ok(vec![DescribeDbClusterParametersOutput::builder()
                .parameters(Parameter::builder().parameter_name("a").build())
                .parameters(Parameter::builder().parameter_name("b").build())
                .parameters(
                    Parameter::builder()
                        .parameter_name("auto_increment_offset")
                        .build(),
                )
                .parameters(Parameter::builder().parameter_name("c").build())
                .parameters(
                    Parameter::builder()
                        .parameter_name("auto_increment_increment")
                        .build(),
                )
                .parameters(Parameter::builder().parameter_name("d").build())
                .build()])
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());

    let params = scenario.cluster_parameters().await.expect("cluster params");
    let names: Vec<String> = params.into_iter().map(|p| p.name).collect();
    assert_eq!(
        names,
        vec!["auto_increment_offset", "auto_increment_increment"]
    );
}

#[tokio::test]
async fn test_scenario_cluster_parameters_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_cluster_parameters()
        .with(eq("RustSDKCodeExamplesDBParameterGroup"))
        .return_once(|_| {
            Err(SdkError::service_error(
                DescribeDBClusterParametersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe_db_cluster_parameters_error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());
    let params = scenario.cluster_parameters().await;
    assert_matches!(params, Err(ScenarioError { message, context: _ }) if message == "Failed to retrieve parameters for RustSDKCodeExamplesDBParameterGroup");
}

#[tokio::test]
async fn test_scenario_update_auto_increment() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_modify_db_cluster_parameter_group()
        .withf(|name, params| {
            assert_eq!(name, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(
                params,
                &vec![
                    Parameter::builder()
                        .parameter_name("auto_increment_offset")
                        .parameter_value("10")
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                    Parameter::builder()
                        .parameter_name("auto_increment_increment")
                        .parameter_value("20")
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                ]
            );
            true
        })
        .return_once(|_, _| Ok(ModifyDbClusterParameterGroupOutput::builder().build()));

    let scenario = AuroraScenario::new(mock_rds);

    scenario
        .update_auto_increment(10, 20)
        .await
        .expect("update auto increment");
}

#[tokio::test]
async fn test_scenario_update_auto_increment_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_modify_db_cluster_parameter_group()
        .return_once(|_, _| {
            Err(SdkError::service_error(
                ModifyDBClusterParameterGroupError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "modify_db_cluster_parameter_group_error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let scenario = AuroraScenario::new(mock_rds);

    let update = scenario.update_auto_increment(10, 20).await;
    assert_matches!(update, Err(ScenarioError { message, context: _}) if message == "Failed to modify cluster parameter group");
}

#[tokio::test]
async fn test_start_cluster_and_instance() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_describe_db_instance()
        .with(eq("RustSDKCodeExamplesDBInstance"))
        .return_once(|name| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_instance_identifier(name)
                        .db_instance_status("Available")
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
        assert!(scenario
            .password
            .replace(SecretString::new("BAD SECRET".into()))
            .unwrap()
            .expose_secret()
            .is_empty());
        assert_eq!(
            scenario.db_cluster_identifier,
            Some("RustSDKCodeExamplesDBCluster".into())
        );
    });
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Err(SdkError::service_error(
                CreateDBClusterError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _}) if message == "Failed to create DB Cluster with cluster group")
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_missing_id() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context:_ }) if message == "Created DB Cluster missing Identifier");
}

#[tokio::test]
async fn test_start_cluster_and_instance_instance_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .return_once(|_, _, _, _| {
            Err(SdkError::service_error(
                CreateDBInstanceError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db instance error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _ }) if message == "Failed to create Instance in DB Cluster")
}

#[tokio::test]
async fn test_start_cluster_and_instance_wait_hiccup() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        })
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds.expect_describe_db_instance().return_once(|name| {
        Ok(DescribeDbInstancesOutput::builder()
            .db_instances(
                DbInstance::builder()
                    .db_instance_identifier(name)
                    .db_instance_status("Available")
                    .build(),
            )
            .build())
    });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_scenario_clean_up() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| Ok(DescribeDbInstancesOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| Ok(DescribeDbClustersOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_scenario_clean_up_errors() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| {
            Err(SdkError::service_error(
                DescribeDBInstancesError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db instances error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db clusters error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_err());
        let errs = clean_up.unwrap_err();
        assert_eq!(errs.len(), 2);
        assert_matches!(errs.first(), Some(ScenarioError {message, context: _}) if message == "Failed to check instance state during deletion");
        assert_matches!(errs.get(1), Some(ScenarioError {message, context: _}) if message == "Failed to check cluster state during deletion");
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_scenario_snapshot() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_snapshot_cluster()
        .with(eq("MockCluster"), eq("MockCluster_MockSnapshot"))
        .times(1)
        .return_once(|_, _| {
            Ok(CreateDbClusterSnapshotOutput::builder()
                .db_cluster_snapshot(
                    DbClusterSnapshot::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_cluster_snapshot_identifier("MockCluster_MockSnapshot")
                        .build(),
                )
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("MockCluster".into());
    let create_snapshot = scenario.snapshot("MockSnapshot").await;
    assert!(create_snapshot.is_ok());
}

#[tokio::test]
async fn test_scenario_snapshot_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_snapshot_cluster()
        .with(eq("MockCluster"), eq("MockCluster_MockSnapshot"))
        .times(1)
        .return_once(|_, _| {
            Err(SdkError::service_error(
                CreateDBClusterSnapshotError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create snapshot error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("MockCluster".into());
    let create_snapshot = scenario.snapshot("MockSnapshot").await;
    assert_matches!(create_snapshot, Err(ScenarioError { message, context: _}) if message == "Failed to create snapshot");
}

#[tokio::test]
async fn test_scenario_snapshot_invalid() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_snapshot_cluster()
        .with(eq("MockCluster"), eq("MockCluster_MockSnapshot"))
        .times(1)
        .return_once(|_, _| Ok(CreateDbClusterSnapshotOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("MockCluster".into());
    let create_snapshot = scenario.snapshot("MockSnapshot").await;
    assert_matches!(create_snapshot, Err(ScenarioError { message, context: _}) if message == "Missing Snapshot");
}
```
ユーザーが一部の決定を下せるように inquirer を使用してシナリオを最初から最後まで実行するためのバイナリ。  

```
use std::fmt::Display;

use anyhow::anyhow;
use aurora_code_examples::{
    aurora_scenario::{AuroraScenario, ScenarioError},
    rds::Rds as RdsClient,
};
use aws_sdk_rds::Client;
use inquire::{validator::StringValidator, CustomUserError};
use secrecy::SecretString;
use tracing::warn;

#[derive(Default, Debug)]
struct Warnings(Vec<String>);

impl Warnings {
    fn new() -> Self {
        Warnings(Vec::with_capacity(5))
    }

    fn push(&mut self, warning: &str, error: ScenarioError) {
        let formatted = format!("{warning}: {error}");
        warn!("{formatted}");
        self.0.push(formatted);
    }

    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Display for Warnings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Warnings:")?;
        for warning in &self.0 {
            writeln!(f, "{: >4}- {warning}", "")?;
        }
        Ok(())
    }
}

fn select(
    prompt: &str,
    choices: Vec<String>,
    error_message: &str,
) -> Result<String, anyhow::Error> {
    inquire::Select::new(prompt, choices)
        .prompt()
        .map_err(|error| anyhow!("{error_message}: {error}"))
}

// Prepare the Aurora Scenario. Prompt for several settings that are optional to the Scenario, but that the user should choose for the demo.
// This includes the engine, engine version, and instance class.
async fn prepare_scenario(rds: RdsClient) -> Result<AuroraScenario, anyhow::Error> {
    let mut scenario = AuroraScenario::new(rds);

    // Get available engine families for Aurora MySql. rds.DescribeDbEngineVersions(Engine='aurora-mysql') and build a set of the 'DBParameterGroupFamily' field values. I get {aurora-mysql8.0, aurora-mysql5.7}.
    let available_engines = scenario.get_engines().await;
    if let Err(error) = available_engines {
        return Err(anyhow!("Failed to get available engines: {}", error));
    }
    let available_engines = available_engines.unwrap();

    // Select an engine family and create a custom DB cluster parameter group. rds.CreateDbClusterParameterGroup(DBParameterGroupFamily='aurora-mysql8.0')
    let engine = select(
        "Select an Aurora engine family",
        available_engines.keys().cloned().collect::<Vec<String>>(),
        "Invalid engine selection",
    )?;

    let version = select(
        format!("Select an Aurora engine version for {engine}").as_str(),
        available_engines.get(&engine).cloned().unwrap_or_default(),
        "Invalid engine version selection",
    )?;

    let set_engine = scenario.set_engine(engine.as_str(), version.as_str()).await;
    if let Err(error) = set_engine {
        return Err(anyhow!("Could not set engine: {}", error));
    }

    let instance_classes = scenario.get_instance_classes().await;
    match instance_classes {
        Ok(classes) => {
            let instance_class = select(
                format!("Select an Aurora instance class for {engine}").as_str(),
                classes,
                "Invalid instance class selection",
            )?;
            scenario.set_instance_class(Some(instance_class))
        }
        Err(err) => return Err(anyhow!("Failed to get instance classes for engine: {err}")),
    }

    Ok(scenario)
}

// Prepare the cluster, creating a custom parameter group overriding some group parameters based on user input.
async fn prepare_cluster(scenario: &mut AuroraScenario, warnings: &mut Warnings) -> Result<(), ()> {
    show_parameters(scenario, warnings).await;

    let offset = prompt_number_or_default(warnings, "auto_increment_offset", 5);
    let increment = prompt_number_or_default(warnings, "auto_increment_increment", 3);

    // Modify both the auto_increment_offset and auto_increment_increment parameters in one call in the custom parameter group. Set their ParameterValue fields to a new allowable value. rds.ModifyDbClusterParameterGroup.
    let update_auto_increment = scenario.update_auto_increment(offset, increment).await;

    if let Err(error) = update_auto_increment {
        warnings.push("Failed to update auto increment", error);
        return Err(());
    }

    // Get and display the updated parameters. Specify Source of 'user' to get just the modified parameters. rds.DescribeDbClusterParameters(Source='user')
    show_parameters(scenario, warnings).await;

    let username = inquire::Text::new("Username for the database (default 'testuser')")
        .with_default("testuser")
        .with_initial_value("testuser")
        .prompt();

    if let Err(error) = username {
        warnings.push(
            "Failed to get username, using default",
            ScenarioError::with(format!("Error from inquirer: {error}")),
        );
        return Err(());
    }
    let username = username.unwrap();

    let password = inquire::Text::new("Password for the database (minimum 8 characters)")
        .with_validator(|i: &str| {
            if i.len() >= 8 {
                Ok(inquire::validator::Validation::Valid)
            } else {
                Ok(inquire::validator::Validation::Invalid(
                    "Password must be at least 8 characters".into(),
                ))
            }
        })
        .prompt();

    let password: Option<SecretString> = match password {
        Ok(password) => Some(SecretString::from(password)),
        Err(error) => {
            warnings.push(
                "Failed to get password, using none (and not starting a DB)",
                ScenarioError::with(format!("Error from inquirer: {error}")),
            );
            return Err(());
        }
    };

    scenario.set_login(Some(username), password);

    Ok(())
}

// Start a single instance in the cluster,
async fn run_instance(scenario: &mut AuroraScenario) -> Result<(), ScenarioError> {
    // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created.
    // Create a database instance in the cluster.
    // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'.
    scenario.start_cluster_and_instance().await?;

    let connection_string = scenario.connection_string().await?;

    println!("Database ready: {connection_string}",);

    let _ = inquire::Text::new("Use the database with the connection string. When you're finished, press enter key to continue.").prompt();

    // Create a snapshot of the DB cluster. rds.CreateDbClusterSnapshot.
    // Wait for the snapshot to create. rds.DescribeDbClusterSnapshots until Status == 'available'.
    let snapshot_name = inquire::Text::new("Provide a name for the snapshot")
        .prompt()
        .unwrap_or(String::from("ScenarioRun"));
    let snapshot = scenario.snapshot(snapshot_name.as_str()).await?;
    println!(
        "Snapshot is available: {}",
        snapshot.db_cluster_snapshot_arn().unwrap_or("Missing ARN")
    );

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    tracing_subscriber::fmt::init();
    let sdk_config = aws_config::from_env().load().await;
    let client = Client::new(&sdk_config);
    let rds = RdsClient::new(client);
    let mut scenario = prepare_scenario(rds).await?;

    // At this point, the scenario has things in AWS and needs to get cleaned up.
    let mut warnings = Warnings::new();

    if prepare_cluster(&mut scenario, &mut warnings).await.is_ok() {
        println!("Configured database cluster, starting an instance.");
        if let Err(err) = run_instance(&mut scenario).await {
            warnings.push("Problem running instance", err);
        }
    }

    // Clean up the instance, cluster, and parameter group, waiting for the instance and cluster to delete before moving on.
    let clean_up = scenario.clean_up().await;
    if let Err(errors) = clean_up {
        for error in errors {
            warnings.push("Problem cleaning up scenario", error);
        }
    }

    if warnings.is_empty() {
        Ok(())
    } else {
        println!("There were problems running the scenario:");
        println!("{warnings}");
        Err(anyhow!("There were problems running the scenario"))
    }
}

#[derive(Clone)]
struct U8Validator {}
impl StringValidator for U8Validator {
    fn validate(&self, input: &str) -> Result<inquire::validator::Validation, CustomUserError> {
        if input.parse::<u8>().is_err() {
            Ok(inquire::validator::Validation::Invalid(
                "Can't parse input as number".into(),
            ))
        } else {
            Ok(inquire::validator::Validation::Valid)
        }
    }
}

async fn show_parameters(scenario: &AuroraScenario, warnings: &mut Warnings) {
    let parameters = scenario.cluster_parameters().await;

    match parameters {
        Ok(parameters) => {
            println!("Current parameters");
            for parameter in parameters {
                println!("\t{parameter}");
            }
        }
        Err(error) => warnings.push("Could not find cluster parameters", error),
    }
}

fn prompt_number_or_default(warnings: &mut Warnings, name: &str, default: u8) -> u8 {
    let input = inquire::Text::new(format!("Updated {name}:").as_str())
        .with_validator(U8Validator {})
        .prompt();

    match input {
        Ok(increment) => match increment.parse::<u8>() {
            Ok(increment) => increment,
            Err(error) => {
                warnings.push(
                    format!("Invalid updated {name} (using {default} instead)").as_str(),
                    ScenarioError::with(format!("{error}")),
                );
                default
            }
        },
        Err(error) => {
            warnings.push(
                format!("Invalid updated {name} (using {default} instead)").as_str(),
                ScenarioError::with(format!("{error}")),
            );
            default
        }
    }
}
```
テストのオートモッキングを可能にする Amazon RDS サービスのラッパー。  

```
use aws_sdk_rds::{
    error::SdkError,
    operation::{
        create_db_cluster::{CreateDBClusterError, CreateDbClusterOutput},
        create_db_cluster_parameter_group::CreateDBClusterParameterGroupError,
        create_db_cluster_parameter_group::CreateDbClusterParameterGroupOutput,
        create_db_cluster_snapshot::{CreateDBClusterSnapshotError, CreateDbClusterSnapshotOutput},
        create_db_instance::{CreateDBInstanceError, CreateDbInstanceOutput},
        delete_db_cluster::{DeleteDBClusterError, DeleteDbClusterOutput},
        delete_db_cluster_parameter_group::{
            DeleteDBClusterParameterGroupError, DeleteDbClusterParameterGroupOutput,
        },
        delete_db_instance::{DeleteDBInstanceError, DeleteDbInstanceOutput},
        describe_db_cluster_endpoints::{
            DescribeDBClusterEndpointsError, DescribeDbClusterEndpointsOutput,
        },
        describe_db_cluster_parameters::{
            DescribeDBClusterParametersError, DescribeDbClusterParametersOutput,
        },
        describe_db_clusters::{DescribeDBClustersError, DescribeDbClustersOutput},
        describe_db_engine_versions::{
            DescribeDBEngineVersionsError, DescribeDbEngineVersionsOutput,
        },
        describe_db_instances::{DescribeDBInstancesError, DescribeDbInstancesOutput},
        describe_orderable_db_instance_options::DescribeOrderableDBInstanceOptionsError,
        modify_db_cluster_parameter_group::{
            ModifyDBClusterParameterGroupError, ModifyDbClusterParameterGroupOutput,
        },
    },
    types::{OrderableDbInstanceOption, Parameter},
    Client as RdsClient,
};
use secrecy::{ExposeSecret, SecretString};

#[cfg(test)]
use mockall::automock;

#[cfg(test)]
pub use MockRdsImpl as Rds;
#[cfg(not(test))]
pub use RdsImpl as Rds;

pub struct RdsImpl {
    pub inner: RdsClient,
}

#[cfg_attr(test, automock)]
impl RdsImpl {
    pub fn new(inner: RdsClient) -> Self {
        RdsImpl { inner }
    }

    pub async fn describe_db_engine_versions(
        &self,
        engine: &str,
    ) -> Result<DescribeDbEngineVersionsOutput, SdkError<DescribeDBEngineVersionsError>> {
        self.inner
            .describe_db_engine_versions()
            .engine(engine)
            .send()
            .await
    }

    pub async fn describe_orderable_db_instance_options(
        &self,
        engine: &str,
        engine_version: &str,
    ) -> Result<Vec<OrderableDbInstanceOption>, SdkError<DescribeOrderableDBInstanceOptionsError>>
    {
        self.inner
            .describe_orderable_db_instance_options()
            .engine(engine)
            .engine_version(engine_version)
            .into_paginator()
            .items()
            .send()
            .try_collect()
            .await
    }

    pub async fn create_db_cluster_parameter_group(
        &self,
        name: &str,
        description: &str,
        family: &str,
    ) -> Result<CreateDbClusterParameterGroupOutput, SdkError<CreateDBClusterParameterGroupError>>
    {
        self.inner
            .create_db_cluster_parameter_group()
            .db_cluster_parameter_group_name(name)
            .description(description)
            .db_parameter_group_family(family)
            .send()
            .await
    }

    pub async fn describe_db_clusters(
        &self,
        id: &str,
    ) -> Result<DescribeDbClustersOutput, SdkError<DescribeDBClustersError>> {
        self.inner
            .describe_db_clusters()
            .db_cluster_identifier(id)
            .send()
            .await
    }

    pub async fn describe_db_cluster_parameters(
        &self,
        name: &str,
    ) -> Result<Vec<DescribeDbClusterParametersOutput>, SdkError<DescribeDBClusterParametersError>>
    {
        self.inner
            .describe_db_cluster_parameters()
            .db_cluster_parameter_group_name(name)
            .into_paginator()
            .send()
            .try_collect()
            .await
    }

    pub async fn modify_db_cluster_parameter_group(
        &self,
        name: &str,
        parameters: Vec<Parameter>,
    ) -> Result<ModifyDbClusterParameterGroupOutput, SdkError<ModifyDBClusterParameterGroupError>>
    {
        self.inner
            .modify_db_cluster_parameter_group()
            .db_cluster_parameter_group_name(name)
            .set_parameters(Some(parameters))
            .send()
            .await
    }

    pub async fn create_db_cluster(
        &self,
        name: &str,
        parameter_group: &str,
        engine: &str,
        version: &str,
        username: &str,
        password: SecretString,
    ) -> Result<CreateDbClusterOutput, SdkError<CreateDBClusterError>> {
        self.inner
            .create_db_cluster()
            .db_cluster_identifier(name)
            .db_cluster_parameter_group_name(parameter_group)
            .engine(engine)
            .engine_version(version)
            .master_username(username)
            .master_user_password(password.expose_secret())
            .send()
            .await
    }

    pub async fn create_db_instance(
        &self,
        cluster_name: &str,
        instance_name: &str,
        instance_class: &str,
        engine: &str,
    ) -> Result<CreateDbInstanceOutput, SdkError<CreateDBInstanceError>> {
        self.inner
            .create_db_instance()
            .db_cluster_identifier(cluster_name)
            .db_instance_identifier(instance_name)
            .db_instance_class(instance_class)
            .engine(engine)
            .send()
            .await
    }

    pub async fn describe_db_instance(
        &self,
        instance_identifier: &str,
    ) -> Result<DescribeDbInstancesOutput, SdkError<DescribeDBInstancesError>> {
        self.inner
            .describe_db_instances()
            .db_instance_identifier(instance_identifier)
            .send()
            .await
    }

    pub async fn snapshot_cluster(
        &self,
        db_cluster_identifier: &str,
        snapshot_name: &str,
    ) -> Result<CreateDbClusterSnapshotOutput, SdkError<CreateDBClusterSnapshotError>> {
        self.inner
            .create_db_cluster_snapshot()
            .db_cluster_identifier(db_cluster_identifier)
            .db_cluster_snapshot_identifier(snapshot_name)
            .send()
            .await
    }

    pub async fn describe_db_instances(
        &self,
    ) -> Result<DescribeDbInstancesOutput, SdkError<DescribeDBInstancesError>> {
        self.inner.describe_db_instances().send().await
    }

    pub async fn describe_db_cluster_endpoints(
        &self,
        cluster_identifier: &str,
    ) -> Result<DescribeDbClusterEndpointsOutput, SdkError<DescribeDBClusterEndpointsError>> {
        self.inner
            .describe_db_cluster_endpoints()
            .db_cluster_identifier(cluster_identifier)
            .send()
            .await
    }

    pub async fn delete_db_instance(
        &self,
        instance_identifier: &str,
    ) -> Result<DeleteDbInstanceOutput, SdkError<DeleteDBInstanceError>> {
        self.inner
            .delete_db_instance()
            .db_instance_identifier(instance_identifier)
            .skip_final_snapshot(true)
            .send()
            .await
    }

    pub async fn delete_db_cluster(
        &self,
        cluster_identifier: &str,
    ) -> Result<DeleteDbClusterOutput, SdkError<DeleteDBClusterError>> {
        self.inner
            .delete_db_cluster()
            .db_cluster_identifier(cluster_identifier)
            .skip_final_snapshot(true)
            .send()
            .await
    }

    pub async fn delete_db_cluster_parameter_group(
        &self,
        name: &str,
    ) -> Result<DeleteDbClusterParameterGroupOutput, SdkError<DeleteDBClusterParameterGroupError>>
    {
        self.inner
            .delete_db_cluster_parameter_group()
            .db_cluster_parameter_group_name(name)
            .send()
            .await
    }
}
```
このシナリオで使用した依存関係を含む Cargo.toml。  

```
[package]
name = "aurora-code-examples"
authors = [
  "David Souther <dpsouth@amazon.com>", 
]
edition = "2021"
version = "0.1.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
anyhow = "1.0.75"
assert_matches = "1.5.0"
aws-config = { version = "1.0.1", features = ["behavior-version-latest"] }
aws-smithy-types = { version = "1.0.1" }
aws-smithy-runtime-api = { version = "1.0.1" }
aws-sdk-rds = { version = "1.3.0" }
inquire = "0.6.2"
mockall = "0.11.4"
phf = { version = "0.11.2", features = ["std", "macros"] }
sdk-examples-test-utils = { path = "../../test-utils" }
secrecy = "0.8.0"
tokio = { version = "1.20.1", features = ["full", "test-util"] }
tracing = "0.1.37"
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
```
+ API の詳細については、「*AWS SDK for Rust API リファレンス*」の以下のトピックを参照してください。
  + [CreateDBCluster](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_cluster)
  + [CreateDBClusterParameterGroup](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_cluster_parameter_group)
  + [CreateDBClusterSnapshot](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_cluster_snapshot)
  + [CreateDBInstance](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_instance)
  + [DeleteDBCluster](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.delete_db_cluster)
  + [DeleteDBClusterParameterGroup](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.delete_db_cluster_parameter_group)
  + [DeleteDBInstance](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.delete_db_instance)
  + [DescribeDBClusterParameterGroups](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_cluster_parameter_groups)
  + [DescribeDBClusterParameters](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_cluster_parameters)
  + [DescribeDBClusterSnapshots](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_cluster_snapshots)
  + [DescribeDBClusters](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_clusters)
  + [DescribeDBEngineVersions](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_engine_versions)
  + [DescribeDBInstances](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_instances)
  + [DescribeOrderableDBInstanceOptions](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_orderable_db_instance_options)
  + [ModifyDBClusterParameterGroup](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.modify_db_cluster_parameter_group)

## アクション
<a name="actions"></a>

### `CreateDBCluster`
<a name="aurora_CreateDBCluster_rust_1_topic"></a>

次のコード例は、`CreateDBCluster` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Get a list of allowed engine versions. rds.DescribeDbEngineVersions(Engine='aurora-mysql', DBParameterGroupFamily=<the family used to create your parameter group in step 2>)
    // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created.
    // Wait for DB cluster to be ready. Call rds.DescribeDBClusters and check for Status == 'available'.
    // Get a list of instance classes available for the selected engine and engine version. rds.DescribeOrderableDbInstanceOptions(Engine='mysql', EngineVersion=).

    // Create a database instance in the cluster.
    // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'.
    pub async fn start_cluster_and_instance(&mut self) -> Result<(), ScenarioError> {
        if self.password.is_none() {
            return Err(ScenarioError::with(
                "Must set Secret Password before starting a cluster",
            ));
        }
        let create_db_cluster = self
            .rds
            .create_db_cluster(
                DB_CLUSTER_IDENTIFIER,
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                DB_ENGINE,
                self.engine_version.as_deref().expect("engine version"),
                self.username.as_deref().expect("username"),
                self.password
                    .replace(SecretString::new("".to_string()))
                    .expect("password"),
            )
            .await;
        if let Err(err) = create_db_cluster {
            return Err(ScenarioError::new(
                "Failed to create DB Cluster with cluster group",
                &err,
            ));
        }

        self.db_cluster_identifier = create_db_cluster
            .unwrap()
            .db_cluster
            .and_then(|c| c.db_cluster_identifier);

        if self.db_cluster_identifier.is_none() {
            return Err(ScenarioError::with("Created DB Cluster missing Identifier"));
        }

        info!(
            "Started a db cluster: {}",
            self.db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing ARN")
        );

        let create_db_instance = self
            .rds
            .create_db_instance(
                self.db_cluster_identifier.as_deref().expect("cluster name"),
                DB_INSTANCE_IDENTIFIER,
                self.instance_class.as_deref().expect("instance class"),
                DB_ENGINE,
            )
            .await;
        if let Err(err) = create_db_instance {
            return Err(ScenarioError::new(
                "Failed to create Instance in DB Cluster",
                &err,
            ));
        }

        self.db_instance_identifier = create_db_instance
            .unwrap()
            .db_instance
            .and_then(|i| i.db_instance_identifier);

        // Cluster creation can take up to 20 minutes to become available
        let cluster_max_wait = Duration::from_secs(20 * 60);
        let waiter = Waiter::builder().max(cluster_max_wait).build();
        while waiter.sleep().await.is_ok() {
            let cluster = self
                .rds
                .describe_db_clusters(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = cluster {
                warn!(?err, "Failed to describe cluster while waiting for ready");
                continue;
            }

            let instance = self
                .rds
                .describe_db_instance(
                    self.db_instance_identifier
                        .as_deref()
                        .expect("instance identifier"),
                )
                .await;
            if let Err(err) = instance {
                return Err(ScenarioError::new(
                    "Failed to find instance for cluster",
                    &err,
                ));
            }

            let instances_available = instance
                .unwrap()
                .db_instances()
                .iter()
                .all(|instance| instance.db_instance_status() == Some("Available"));

            let endpoints = self
                .rds
                .describe_db_cluster_endpoints(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = endpoints {
                return Err(ScenarioError::new(
                    "Failed to find endpoint for cluster",
                    &err,
                ));
            }

            let endpoints_available = endpoints
                .unwrap()
                .db_cluster_endpoints()
                .iter()
                .all(|endpoint| endpoint.status() == Some("available"));

            if instances_available && endpoints_available {
                return Ok(());
            }
        }

        Err(ScenarioError::with("timed out waiting for cluster"))
    }

    pub async fn create_db_cluster(
        &self,
        name: &str,
        parameter_group: &str,
        engine: &str,
        version: &str,
        username: &str,
        password: SecretString,
    ) -> Result<CreateDbClusterOutput, SdkError<CreateDBClusterError>> {
        self.inner
            .create_db_cluster()
            .db_cluster_identifier(name)
            .db_cluster_parameter_group_name(parameter_group)
            .engine(engine)
            .engine_version(version)
            .master_username(username)
            .master_user_password(password.expose_secret())
            .send()
            .await
    }

#[tokio::test]
async fn test_start_cluster_and_instance() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_describe_db_instance()
        .with(eq("RustSDKCodeExamplesDBInstance"))
        .return_once(|name| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_instance_identifier(name)
                        .db_instance_status("Available")
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
        assert!(scenario
            .password
            .replace(SecretString::new("BAD SECRET".into()))
            .unwrap()
            .expose_secret()
            .is_empty());
        assert_eq!(
            scenario.db_cluster_identifier,
            Some("RustSDKCodeExamplesDBCluster".into())
        );
    });
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Err(SdkError::service_error(
                CreateDBClusterError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _}) if message == "Failed to create DB Cluster with cluster group")
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_missing_id() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context:_ }) if message == "Created DB Cluster missing Identifier");
}

#[tokio::test]
async fn test_start_cluster_and_instance_instance_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .return_once(|_, _, _, _| {
            Err(SdkError::service_error(
                CreateDBInstanceError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db instance error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _ }) if message == "Failed to create Instance in DB Cluster")
}

#[tokio::test]
async fn test_start_cluster_and_instance_wait_hiccup() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        })
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds.expect_describe_db_instance().return_once(|name| {
        Ok(DescribeDbInstancesOutput::builder()
            .db_instances(
                DbInstance::builder()
                    .db_instance_identifier(name)
                    .db_instance_status("Available")
                    .build(),
            )
            .build())
    });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CreateDBCluster](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_cluster)」を参照してください。

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_rust_1_topic"></a>

次のコード例は、`CreateDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Select an engine family and create a custom DB cluster parameter group. rds.CreateDbClusterParameterGroup(DBParameterGroupFamily='aurora-mysql8.0')
    pub async fn set_engine(&mut self, engine: &str, version: &str) -> Result<(), ScenarioError> {
        self.engine_family = Some(engine.to_string());
        self.engine_version = Some(version.to_string());
        let create_db_cluster_parameter_group = self
            .rds
            .create_db_cluster_parameter_group(
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                DB_CLUSTER_PARAMETER_GROUP_DESCRIPTION,
                engine,
            )
            .await;

        match create_db_cluster_parameter_group {
            Ok(CreateDbClusterParameterGroupOutput {
                db_cluster_parameter_group: None,
                ..
            }) => {
                return Err(ScenarioError::with(
                    "CreateDBClusterParameterGroup had empty response",
                ));
            }
            Err(error) => {
                if error.code() == Some("DBParameterGroupAlreadyExists") {
                    info!("Cluster Parameter Group already exists, nothing to do");
                } else {
                    return Err(ScenarioError::new(
                        "Could not create Cluster Parameter Group",
                        &error,
                    ));
                }
            }
            _ => {
                info!("Created Cluster Parameter Group");
            }
        }

        Ok(())
    }

    pub async fn create_db_cluster_parameter_group(
        &self,
        name: &str,
        description: &str,
        family: &str,
    ) -> Result<CreateDbClusterParameterGroupOutput, SdkError<CreateDBClusterParameterGroupError>>
    {
        self.inner
            .create_db_cluster_parameter_group()
            .db_cluster_parameter_group_name(name)
            .description(description)
            .db_parameter_group_family(family)
            .send()
            .await
    }

#[tokio::test]
async fn test_scenario_set_engine() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .with(
            eq("RustSDKCodeExamplesDBParameterGroup"),
            eq("Parameter Group created by Rust SDK Code Example"),
            eq("aurora-mysql"),
        )
        .return_once(|_, _, _| {
            Ok(CreateDbClusterParameterGroupOutput::builder()
                .db_cluster_parameter_group(DbClusterParameterGroup::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);

    let set_engine = scenario.set_engine("aurora-mysql", "aurora-mysql8.0").await;

    assert_eq!(set_engine, Ok(()));
    assert_eq!(Some("aurora-mysql"), scenario.engine_family.as_deref());
    assert_eq!(Some("aurora-mysql8.0"), scenario.engine_version.as_deref());
}

#[tokio::test]
async fn test_scenario_set_engine_not_create() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .with(
            eq("RustSDKCodeExamplesDBParameterGroup"),
            eq("Parameter Group created by Rust SDK Code Example"),
            eq("aurora-mysql"),
        )
        .return_once(|_, _, _| Ok(CreateDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);

    let set_engine = scenario.set_engine("aurora-mysql", "aurora-mysql8.0").await;

    assert!(set_engine.is_err());
}

#[tokio::test]
async fn test_scenario_set_engine_param_group_exists() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .withf(|_, _, _| true)
        .return_once(|_, _, _| {
            Err(SdkError::service_error(
                CreateDBClusterParameterGroupError::DbParameterGroupAlreadyExistsFault(
                    DbParameterGroupAlreadyExistsFault::builder().build(),
                ),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);

    let set_engine = scenario.set_engine("aurora-mysql", "aurora-mysql8.0").await;

    assert!(set_engine.is_err());
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CreateDBClusterParameterGroup](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_cluster_parameter_group)」を参照してください。

### `CreateDBClusterSnapshot`
<a name="aurora_CreateDBClusterSnapshot_rust_1_topic"></a>

次のコード例は、`CreateDBClusterSnapshot` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Get a list of allowed engine versions. rds.DescribeDbEngineVersions(Engine='aurora-mysql', DBParameterGroupFamily=<the family used to create your parameter group in step 2>)
    // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created.
    // Wait for DB cluster to be ready. Call rds.DescribeDBClusters and check for Status == 'available'.
    // Get a list of instance classes available for the selected engine and engine version. rds.DescribeOrderableDbInstanceOptions(Engine='mysql', EngineVersion=).

    // Create a database instance in the cluster.
    // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'.
    pub async fn start_cluster_and_instance(&mut self) -> Result<(), ScenarioError> {
        if self.password.is_none() {
            return Err(ScenarioError::with(
                "Must set Secret Password before starting a cluster",
            ));
        }
        let create_db_cluster = self
            .rds
            .create_db_cluster(
                DB_CLUSTER_IDENTIFIER,
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                DB_ENGINE,
                self.engine_version.as_deref().expect("engine version"),
                self.username.as_deref().expect("username"),
                self.password
                    .replace(SecretString::new("".to_string()))
                    .expect("password"),
            )
            .await;
        if let Err(err) = create_db_cluster {
            return Err(ScenarioError::new(
                "Failed to create DB Cluster with cluster group",
                &err,
            ));
        }

        self.db_cluster_identifier = create_db_cluster
            .unwrap()
            .db_cluster
            .and_then(|c| c.db_cluster_identifier);

        if self.db_cluster_identifier.is_none() {
            return Err(ScenarioError::with("Created DB Cluster missing Identifier"));
        }

        info!(
            "Started a db cluster: {}",
            self.db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing ARN")
        );

        let create_db_instance = self
            .rds
            .create_db_instance(
                self.db_cluster_identifier.as_deref().expect("cluster name"),
                DB_INSTANCE_IDENTIFIER,
                self.instance_class.as_deref().expect("instance class"),
                DB_ENGINE,
            )
            .await;
        if let Err(err) = create_db_instance {
            return Err(ScenarioError::new(
                "Failed to create Instance in DB Cluster",
                &err,
            ));
        }

        self.db_instance_identifier = create_db_instance
            .unwrap()
            .db_instance
            .and_then(|i| i.db_instance_identifier);

        // Cluster creation can take up to 20 minutes to become available
        let cluster_max_wait = Duration::from_secs(20 * 60);
        let waiter = Waiter::builder().max(cluster_max_wait).build();
        while waiter.sleep().await.is_ok() {
            let cluster = self
                .rds
                .describe_db_clusters(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = cluster {
                warn!(?err, "Failed to describe cluster while waiting for ready");
                continue;
            }

            let instance = self
                .rds
                .describe_db_instance(
                    self.db_instance_identifier
                        .as_deref()
                        .expect("instance identifier"),
                )
                .await;
            if let Err(err) = instance {
                return Err(ScenarioError::new(
                    "Failed to find instance for cluster",
                    &err,
                ));
            }

            let instances_available = instance
                .unwrap()
                .db_instances()
                .iter()
                .all(|instance| instance.db_instance_status() == Some("Available"));

            let endpoints = self
                .rds
                .describe_db_cluster_endpoints(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = endpoints {
                return Err(ScenarioError::new(
                    "Failed to find endpoint for cluster",
                    &err,
                ));
            }

            let endpoints_available = endpoints
                .unwrap()
                .db_cluster_endpoints()
                .iter()
                .all(|endpoint| endpoint.status() == Some("available"));

            if instances_available && endpoints_available {
                return Ok(());
            }
        }

        Err(ScenarioError::with("timed out waiting for cluster"))
    }

    pub async fn snapshot_cluster(
        &self,
        db_cluster_identifier: &str,
        snapshot_name: &str,
    ) -> Result<CreateDbClusterSnapshotOutput, SdkError<CreateDBClusterSnapshotError>> {
        self.inner
            .create_db_cluster_snapshot()
            .db_cluster_identifier(db_cluster_identifier)
            .db_cluster_snapshot_identifier(snapshot_name)
            .send()
            .await
    }

#[tokio::test]
async fn test_start_cluster_and_instance() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_describe_db_instance()
        .with(eq("RustSDKCodeExamplesDBInstance"))
        .return_once(|name| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_instance_identifier(name)
                        .db_instance_status("Available")
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
        assert!(scenario
            .password
            .replace(SecretString::new("BAD SECRET".into()))
            .unwrap()
            .expose_secret()
            .is_empty());
        assert_eq!(
            scenario.db_cluster_identifier,
            Some("RustSDKCodeExamplesDBCluster".into())
        );
    });
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Err(SdkError::service_error(
                CreateDBClusterError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _}) if message == "Failed to create DB Cluster with cluster group")
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_missing_id() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context:_ }) if message == "Created DB Cluster missing Identifier");
}

#[tokio::test]
async fn test_start_cluster_and_instance_instance_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .return_once(|_, _, _, _| {
            Err(SdkError::service_error(
                CreateDBInstanceError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db instance error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _ }) if message == "Failed to create Instance in DB Cluster")
}

#[tokio::test]
async fn test_start_cluster_and_instance_wait_hiccup() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        })
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds.expect_describe_db_instance().return_once(|name| {
        Ok(DescribeDbInstancesOutput::builder()
            .db_instances(
                DbInstance::builder()
                    .db_instance_identifier(name)
                    .db_instance_status("Available")
                    .build(),
            )
            .build())
    });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CreateDBClusterSnapshot](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_cluster_snapshot)」を参照してください。

### `CreateDBInstance`
<a name="aurora_CreateDBInstance_rust_1_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Get a list of allowed engine versions. rds.DescribeDbEngineVersions(Engine='aurora-mysql', DBParameterGroupFamily=<the family used to create your parameter group in step 2>)
    // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created.
    // Wait for DB cluster to be ready. Call rds.DescribeDBClusters and check for Status == 'available'.
    // Get a list of instance classes available for the selected engine and engine version. rds.DescribeOrderableDbInstanceOptions(Engine='mysql', EngineVersion=).

    // Create a database instance in the cluster.
    // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'.
    pub async fn start_cluster_and_instance(&mut self) -> Result<(), ScenarioError> {
        if self.password.is_none() {
            return Err(ScenarioError::with(
                "Must set Secret Password before starting a cluster",
            ));
        }
        let create_db_cluster = self
            .rds
            .create_db_cluster(
                DB_CLUSTER_IDENTIFIER,
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                DB_ENGINE,
                self.engine_version.as_deref().expect("engine version"),
                self.username.as_deref().expect("username"),
                self.password
                    .replace(SecretString::new("".to_string()))
                    .expect("password"),
            )
            .await;
        if let Err(err) = create_db_cluster {
            return Err(ScenarioError::new(
                "Failed to create DB Cluster with cluster group",
                &err,
            ));
        }

        self.db_cluster_identifier = create_db_cluster
            .unwrap()
            .db_cluster
            .and_then(|c| c.db_cluster_identifier);

        if self.db_cluster_identifier.is_none() {
            return Err(ScenarioError::with("Created DB Cluster missing Identifier"));
        }

        info!(
            "Started a db cluster: {}",
            self.db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing ARN")
        );

        let create_db_instance = self
            .rds
            .create_db_instance(
                self.db_cluster_identifier.as_deref().expect("cluster name"),
                DB_INSTANCE_IDENTIFIER,
                self.instance_class.as_deref().expect("instance class"),
                DB_ENGINE,
            )
            .await;
        if let Err(err) = create_db_instance {
            return Err(ScenarioError::new(
                "Failed to create Instance in DB Cluster",
                &err,
            ));
        }

        self.db_instance_identifier = create_db_instance
            .unwrap()
            .db_instance
            .and_then(|i| i.db_instance_identifier);

        // Cluster creation can take up to 20 minutes to become available
        let cluster_max_wait = Duration::from_secs(20 * 60);
        let waiter = Waiter::builder().max(cluster_max_wait).build();
        while waiter.sleep().await.is_ok() {
            let cluster = self
                .rds
                .describe_db_clusters(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = cluster {
                warn!(?err, "Failed to describe cluster while waiting for ready");
                continue;
            }

            let instance = self
                .rds
                .describe_db_instance(
                    self.db_instance_identifier
                        .as_deref()
                        .expect("instance identifier"),
                )
                .await;
            if let Err(err) = instance {
                return Err(ScenarioError::new(
                    "Failed to find instance for cluster",
                    &err,
                ));
            }

            let instances_available = instance
                .unwrap()
                .db_instances()
                .iter()
                .all(|instance| instance.db_instance_status() == Some("Available"));

            let endpoints = self
                .rds
                .describe_db_cluster_endpoints(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = endpoints {
                return Err(ScenarioError::new(
                    "Failed to find endpoint for cluster",
                    &err,
                ));
            }

            let endpoints_available = endpoints
                .unwrap()
                .db_cluster_endpoints()
                .iter()
                .all(|endpoint| endpoint.status() == Some("available"));

            if instances_available && endpoints_available {
                return Ok(());
            }
        }

        Err(ScenarioError::with("timed out waiting for cluster"))
    }

    pub async fn create_db_instance(
        &self,
        cluster_name: &str,
        instance_name: &str,
        instance_class: &str,
        engine: &str,
    ) -> Result<CreateDbInstanceOutput, SdkError<CreateDBInstanceError>> {
        self.inner
            .create_db_instance()
            .db_cluster_identifier(cluster_name)
            .db_instance_identifier(instance_name)
            .db_instance_class(instance_class)
            .engine(engine)
            .send()
            .await
    }

#[tokio::test]
async fn test_start_cluster_and_instance() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_describe_db_instance()
        .with(eq("RustSDKCodeExamplesDBInstance"))
        .return_once(|name| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_instance_identifier(name)
                        .db_instance_status("Available")
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
        assert!(scenario
            .password
            .replace(SecretString::new("BAD SECRET".into()))
            .unwrap()
            .expose_secret()
            .is_empty());
        assert_eq!(
            scenario.db_cluster_identifier,
            Some("RustSDKCodeExamplesDBCluster".into())
        );
    });
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Err(SdkError::service_error(
                CreateDBClusterError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _}) if message == "Failed to create DB Cluster with cluster group")
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_missing_id() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context:_ }) if message == "Created DB Cluster missing Identifier");
}

#[tokio::test]
async fn test_start_cluster_and_instance_instance_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .return_once(|_, _, _, _| {
            Err(SdkError::service_error(
                CreateDBInstanceError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db instance error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _ }) if message == "Failed to create Instance in DB Cluster")
}

#[tokio::test]
async fn test_start_cluster_and_instance_wait_hiccup() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        })
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds.expect_describe_db_instance().return_once(|name| {
        Ok(DescribeDbInstancesOutput::builder()
            .db_instances(
                DbInstance::builder()
                    .db_instance_identifier(name)
                    .db_instance_status("Available")
                    .build(),
            )
            .build())
    });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[CreateDBInstance](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.create_db_instance)」を参照してください。**

### `DeleteDBCluster`
<a name="aurora_DeleteDBCluster_rust_1_topic"></a>

次のコード例は、`DeleteDBCluster` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn clean_up(self) -> Result<(), Vec<ScenarioError>> {
        let mut clean_up_errors: Vec<ScenarioError> = vec![];

        // Delete the instance. rds.DeleteDbInstance.
        let delete_db_instance = self
            .rds
            .delete_db_instance(
                self.db_instance_identifier
                    .as_deref()
                    .expect("instance identifier"),
            )
            .await;
        if let Err(err) = delete_db_instance {
            let identifier = self
                .db_instance_identifier
                .as_deref()
                .unwrap_or("Missing Instance Identifier");
            let message = format!("failed to delete db instance {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance to delete
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_instances = self.rds.describe_db_instances().await;
                if let Err(err) = describe_db_instances {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check instance state during deletion",
                        &err,
                    ));
                    break;
                }
                let db_instances = describe_db_instances
                    .unwrap()
                    .db_instances()
                    .iter()
                    .filter(|instance| instance.db_cluster_identifier == self.db_cluster_identifier)
                    .cloned()
                    .collect::<Vec<DbInstance>>();

                if db_instances.is_empty() {
                    trace!("Delete Instance waited and no instances were found");
                    break;
                }
                match db_instances.first().unwrap().db_instance_status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but instances is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB instance");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster. rds.DeleteDbCluster.
        let delete_db_cluster = self
            .rds
            .delete_db_cluster(
                self.db_cluster_identifier
                    .as_deref()
                    .expect("cluster identifier"),
            )
            .await;

        if let Err(err) = delete_db_cluster {
            let identifier = self
                .db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing DB Cluster Identifier");
            let message = format!("failed to delete db cluster {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance and cluster to fully delete. rds.DescribeDbInstances and rds.DescribeDbClusters until both are not found.
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_clusters = self
                    .rds
                    .describe_db_clusters(
                        self.db_cluster_identifier
                            .as_deref()
                            .expect("cluster identifier"),
                    )
                    .await;
                if let Err(err) = describe_db_clusters {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check cluster state during deletion",
                        &err,
                    ));
                    break;
                }
                let describe_db_clusters = describe_db_clusters.unwrap();
                let db_clusters = describe_db_clusters.db_clusters();
                if db_clusters.is_empty() {
                    trace!("Delete cluster waited and no clusters were found");
                    break;
                }
                match db_clusters.first().unwrap().status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but clusters is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB cluster");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster parameter group. rds.DeleteDbClusterParameterGroup.
        let delete_db_cluster_parameter_group = self
            .rds
            .delete_db_cluster_parameter_group(
                self.db_cluster_parameter_group
                    .map(|g| {
                        g.db_cluster_parameter_group_name
                            .unwrap_or_else(|| DB_CLUSTER_PARAMETER_GROUP_NAME.to_string())
                    })
                    .as_deref()
                    .expect("cluster parameter group name"),
            )
            .await;
        if let Err(error) = delete_db_cluster_parameter_group {
            clean_up_errors.push(ScenarioError::new(
                "Failed to delete the db cluster parameter group",
                &error,
            ))
        }

        if clean_up_errors.is_empty() {
            Ok(())
        } else {
            Err(clean_up_errors)
        }
    }

    pub async fn delete_db_cluster(
        &self,
        cluster_identifier: &str,
    ) -> Result<DeleteDbClusterOutput, SdkError<DeleteDBClusterError>> {
        self.inner
            .delete_db_cluster()
            .db_cluster_identifier(cluster_identifier)
            .skip_final_snapshot(true)
            .send()
            .await
    }

#[tokio::test]
async fn test_scenario_clean_up() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| Ok(DescribeDbInstancesOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| Ok(DescribeDbClustersOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_scenario_clean_up_errors() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| {
            Err(SdkError::service_error(
                DescribeDBInstancesError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db instances error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db clusters error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_err());
        let errs = clean_up.unwrap_err();
        assert_eq!(errs.len(), 2);
        assert_matches!(errs.first(), Some(ScenarioError {message, context: _}) if message == "Failed to check instance state during deletion");
        assert_matches!(errs.get(1), Some(ScenarioError {message, context: _}) if message == "Failed to check cluster state during deletion");
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DeleteDBCluster](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.delete_db_cluster)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_rust_1_topic"></a>

次のコード例は、`DeleteDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn clean_up(self) -> Result<(), Vec<ScenarioError>> {
        let mut clean_up_errors: Vec<ScenarioError> = vec![];

        // Delete the instance. rds.DeleteDbInstance.
        let delete_db_instance = self
            .rds
            .delete_db_instance(
                self.db_instance_identifier
                    .as_deref()
                    .expect("instance identifier"),
            )
            .await;
        if let Err(err) = delete_db_instance {
            let identifier = self
                .db_instance_identifier
                .as_deref()
                .unwrap_or("Missing Instance Identifier");
            let message = format!("failed to delete db instance {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance to delete
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_instances = self.rds.describe_db_instances().await;
                if let Err(err) = describe_db_instances {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check instance state during deletion",
                        &err,
                    ));
                    break;
                }
                let db_instances = describe_db_instances
                    .unwrap()
                    .db_instances()
                    .iter()
                    .filter(|instance| instance.db_cluster_identifier == self.db_cluster_identifier)
                    .cloned()
                    .collect::<Vec<DbInstance>>();

                if db_instances.is_empty() {
                    trace!("Delete Instance waited and no instances were found");
                    break;
                }
                match db_instances.first().unwrap().db_instance_status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but instances is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB instance");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster. rds.DeleteDbCluster.
        let delete_db_cluster = self
            .rds
            .delete_db_cluster(
                self.db_cluster_identifier
                    .as_deref()
                    .expect("cluster identifier"),
            )
            .await;

        if let Err(err) = delete_db_cluster {
            let identifier = self
                .db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing DB Cluster Identifier");
            let message = format!("failed to delete db cluster {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance and cluster to fully delete. rds.DescribeDbInstances and rds.DescribeDbClusters until both are not found.
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_clusters = self
                    .rds
                    .describe_db_clusters(
                        self.db_cluster_identifier
                            .as_deref()
                            .expect("cluster identifier"),
                    )
                    .await;
                if let Err(err) = describe_db_clusters {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check cluster state during deletion",
                        &err,
                    ));
                    break;
                }
                let describe_db_clusters = describe_db_clusters.unwrap();
                let db_clusters = describe_db_clusters.db_clusters();
                if db_clusters.is_empty() {
                    trace!("Delete cluster waited and no clusters were found");
                    break;
                }
                match db_clusters.first().unwrap().status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but clusters is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB cluster");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster parameter group. rds.DeleteDbClusterParameterGroup.
        let delete_db_cluster_parameter_group = self
            .rds
            .delete_db_cluster_parameter_group(
                self.db_cluster_parameter_group
                    .map(|g| {
                        g.db_cluster_parameter_group_name
                            .unwrap_or_else(|| DB_CLUSTER_PARAMETER_GROUP_NAME.to_string())
                    })
                    .as_deref()
                    .expect("cluster parameter group name"),
            )
            .await;
        if let Err(error) = delete_db_cluster_parameter_group {
            clean_up_errors.push(ScenarioError::new(
                "Failed to delete the db cluster parameter group",
                &error,
            ))
        }

        if clean_up_errors.is_empty() {
            Ok(())
        } else {
            Err(clean_up_errors)
        }
    }

    pub async fn delete_db_cluster_parameter_group(
        &self,
        name: &str,
    ) -> Result<DeleteDbClusterParameterGroupOutput, SdkError<DeleteDBClusterParameterGroupError>>
    {
        self.inner
            .delete_db_cluster_parameter_group()
            .db_cluster_parameter_group_name(name)
            .send()
            .await
    }

#[tokio::test]
async fn test_scenario_clean_up() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| Ok(DescribeDbInstancesOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| Ok(DescribeDbClustersOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_scenario_clean_up_errors() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| {
            Err(SdkError::service_error(
                DescribeDBInstancesError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db instances error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db clusters error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_err());
        let errs = clean_up.unwrap_err();
        assert_eq!(errs.len(), 2);
        assert_matches!(errs.first(), Some(ScenarioError {message, context: _}) if message == "Failed to check instance state during deletion");
        assert_matches!(errs.get(1), Some(ScenarioError {message, context: _}) if message == "Failed to check cluster state during deletion");
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、**「AWS SDK for Rust API リファレンス」の「[DeleteDBClusterParameterGroup](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.delete_db_cluster_parameter_group)」を参照してください。

### `DeleteDBInstance`
<a name="aurora_DeleteDBInstance_rust_1_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn clean_up(self) -> Result<(), Vec<ScenarioError>> {
        let mut clean_up_errors: Vec<ScenarioError> = vec![];

        // Delete the instance. rds.DeleteDbInstance.
        let delete_db_instance = self
            .rds
            .delete_db_instance(
                self.db_instance_identifier
                    .as_deref()
                    .expect("instance identifier"),
            )
            .await;
        if let Err(err) = delete_db_instance {
            let identifier = self
                .db_instance_identifier
                .as_deref()
                .unwrap_or("Missing Instance Identifier");
            let message = format!("failed to delete db instance {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance to delete
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_instances = self.rds.describe_db_instances().await;
                if let Err(err) = describe_db_instances {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check instance state during deletion",
                        &err,
                    ));
                    break;
                }
                let db_instances = describe_db_instances
                    .unwrap()
                    .db_instances()
                    .iter()
                    .filter(|instance| instance.db_cluster_identifier == self.db_cluster_identifier)
                    .cloned()
                    .collect::<Vec<DbInstance>>();

                if db_instances.is_empty() {
                    trace!("Delete Instance waited and no instances were found");
                    break;
                }
                match db_instances.first().unwrap().db_instance_status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but instances is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB instance");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster. rds.DeleteDbCluster.
        let delete_db_cluster = self
            .rds
            .delete_db_cluster(
                self.db_cluster_identifier
                    .as_deref()
                    .expect("cluster identifier"),
            )
            .await;

        if let Err(err) = delete_db_cluster {
            let identifier = self
                .db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing DB Cluster Identifier");
            let message = format!("failed to delete db cluster {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance and cluster to fully delete. rds.DescribeDbInstances and rds.DescribeDbClusters until both are not found.
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_clusters = self
                    .rds
                    .describe_db_clusters(
                        self.db_cluster_identifier
                            .as_deref()
                            .expect("cluster identifier"),
                    )
                    .await;
                if let Err(err) = describe_db_clusters {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check cluster state during deletion",
                        &err,
                    ));
                    break;
                }
                let describe_db_clusters = describe_db_clusters.unwrap();
                let db_clusters = describe_db_clusters.db_clusters();
                if db_clusters.is_empty() {
                    trace!("Delete cluster waited and no clusters were found");
                    break;
                }
                match db_clusters.first().unwrap().status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but clusters is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB cluster");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster parameter group. rds.DeleteDbClusterParameterGroup.
        let delete_db_cluster_parameter_group = self
            .rds
            .delete_db_cluster_parameter_group(
                self.db_cluster_parameter_group
                    .map(|g| {
                        g.db_cluster_parameter_group_name
                            .unwrap_or_else(|| DB_CLUSTER_PARAMETER_GROUP_NAME.to_string())
                    })
                    .as_deref()
                    .expect("cluster parameter group name"),
            )
            .await;
        if let Err(error) = delete_db_cluster_parameter_group {
            clean_up_errors.push(ScenarioError::new(
                "Failed to delete the db cluster parameter group",
                &error,
            ))
        }

        if clean_up_errors.is_empty() {
            Ok(())
        } else {
            Err(clean_up_errors)
        }
    }

    pub async fn delete_db_instance(
        &self,
        instance_identifier: &str,
    ) -> Result<DeleteDbInstanceOutput, SdkError<DeleteDBInstanceError>> {
        self.inner
            .delete_db_instance()
            .db_instance_identifier(instance_identifier)
            .skip_final_snapshot(true)
            .send()
            .await
    }

#[tokio::test]
async fn test_scenario_clean_up() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| Ok(DescribeDbInstancesOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| Ok(DescribeDbClustersOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_scenario_clean_up_errors() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| {
            Err(SdkError::service_error(
                DescribeDBInstancesError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db instances error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db clusters error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_err());
        let errs = clean_up.unwrap_err();
        assert_eq!(errs.len(), 2);
        assert_matches!(errs.first(), Some(ScenarioError {message, context: _}) if message == "Failed to check instance state during deletion");
        assert_matches!(errs.get(1), Some(ScenarioError {message, context: _}) if message == "Failed to check cluster state during deletion");
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DeleteDBInstance](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.delete_db_instance)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_rust_1_topic"></a>

次のコード例は、`DescribeDBClusterParameters` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Get the parameter group. rds.DescribeDbClusterParameterGroups
    // Get parameters in the group. This is a long list so you will have to paginate. Find the auto_increment_offset and auto_increment_increment parameters (by ParameterName). rds.DescribeDbClusterParameters
    // Parse the ParameterName, Description, and AllowedValues values and display them.
    pub async fn cluster_parameters(&self) -> Result<Vec<AuroraScenarioParameter>, ScenarioError> {
        let parameters_output = self
            .rds
            .describe_db_cluster_parameters(DB_CLUSTER_PARAMETER_GROUP_NAME)
            .await;

        if let Err(err) = parameters_output {
            return Err(ScenarioError::new(
                format!("Failed to retrieve parameters for {DB_CLUSTER_PARAMETER_GROUP_NAME}"),
                &err,
            ));
        }

        let parameters = parameters_output
            .unwrap()
            .into_iter()
            .flat_map(|p| p.parameters.unwrap_or_default().into_iter())
            .filter(|p| FILTER_PARAMETER_NAMES.contains(p.parameter_name().unwrap_or_default()))
            .map(AuroraScenarioParameter::from)
            .collect::<Vec<_>>();

        Ok(parameters)
    }

    pub async fn describe_db_cluster_parameters(
        &self,
        name: &str,
    ) -> Result<Vec<DescribeDbClusterParametersOutput>, SdkError<DescribeDBClusterParametersError>>
    {
        self.inner
            .describe_db_cluster_parameters()
            .db_cluster_parameter_group_name(name)
            .into_paginator()
            .send()
            .try_collect()
            .await
    }

#[tokio::test]
async fn test_scenario_cluster_parameters() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_cluster_parameters()
        .with(eq("RustSDKCodeExamplesDBParameterGroup"))
        .return_once(|_| {
            Ok(vec![DescribeDbClusterParametersOutput::builder()
                .parameters(Parameter::builder().parameter_name("a").build())
                .parameters(Parameter::builder().parameter_name("b").build())
                .parameters(
                    Parameter::builder()
                        .parameter_name("auto_increment_offset")
                        .build(),
                )
                .parameters(Parameter::builder().parameter_name("c").build())
                .parameters(
                    Parameter::builder()
                        .parameter_name("auto_increment_increment")
                        .build(),
                )
                .parameters(Parameter::builder().parameter_name("d").build())
                .build()])
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());

    let params = scenario.cluster_parameters().await.expect("cluster params");
    let names: Vec<String> = params.into_iter().map(|p| p.name).collect();
    assert_eq!(
        names,
        vec!["auto_increment_offset", "auto_increment_increment"]
    );
}

#[tokio::test]
async fn test_scenario_cluster_parameters_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_cluster_parameters()
        .with(eq("RustSDKCodeExamplesDBParameterGroup"))
        .return_once(|_| {
            Err(SdkError::service_error(
                DescribeDBClusterParametersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe_db_cluster_parameters_error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some("RustSDKCodeExamplesDBCluster".into());
    let params = scenario.cluster_parameters().await;
    assert_matches!(params, Err(ScenarioError { message, context: _ }) if message == "Failed to retrieve parameters for RustSDKCodeExamplesDBParameterGroup");
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeDBClusterParameters](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_cluster_parameters)」を参照してください。

### `DescribeDBClusters`
<a name="aurora_DescribeDBClusters_rust_1_topic"></a>

次のコード例は、`DescribeDBClusters` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Get a list of allowed engine versions. rds.DescribeDbEngineVersions(Engine='aurora-mysql', DBParameterGroupFamily=<the family used to create your parameter group in step 2>)
    // Create an Aurora DB cluster database cluster that contains a MySql database and uses the parameter group you created.
    // Wait for DB cluster to be ready. Call rds.DescribeDBClusters and check for Status == 'available'.
    // Get a list of instance classes available for the selected engine and engine version. rds.DescribeOrderableDbInstanceOptions(Engine='mysql', EngineVersion=).

    // Create a database instance in the cluster.
    // Wait for DB instance to be ready. Call rds.DescribeDbInstances and check for DBInstanceStatus == 'available'.
    pub async fn start_cluster_and_instance(&mut self) -> Result<(), ScenarioError> {
        if self.password.is_none() {
            return Err(ScenarioError::with(
                "Must set Secret Password before starting a cluster",
            ));
        }
        let create_db_cluster = self
            .rds
            .create_db_cluster(
                DB_CLUSTER_IDENTIFIER,
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                DB_ENGINE,
                self.engine_version.as_deref().expect("engine version"),
                self.username.as_deref().expect("username"),
                self.password
                    .replace(SecretString::new("".to_string()))
                    .expect("password"),
            )
            .await;
        if let Err(err) = create_db_cluster {
            return Err(ScenarioError::new(
                "Failed to create DB Cluster with cluster group",
                &err,
            ));
        }

        self.db_cluster_identifier = create_db_cluster
            .unwrap()
            .db_cluster
            .and_then(|c| c.db_cluster_identifier);

        if self.db_cluster_identifier.is_none() {
            return Err(ScenarioError::with("Created DB Cluster missing Identifier"));
        }

        info!(
            "Started a db cluster: {}",
            self.db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing ARN")
        );

        let create_db_instance = self
            .rds
            .create_db_instance(
                self.db_cluster_identifier.as_deref().expect("cluster name"),
                DB_INSTANCE_IDENTIFIER,
                self.instance_class.as_deref().expect("instance class"),
                DB_ENGINE,
            )
            .await;
        if let Err(err) = create_db_instance {
            return Err(ScenarioError::new(
                "Failed to create Instance in DB Cluster",
                &err,
            ));
        }

        self.db_instance_identifier = create_db_instance
            .unwrap()
            .db_instance
            .and_then(|i| i.db_instance_identifier);

        // Cluster creation can take up to 20 minutes to become available
        let cluster_max_wait = Duration::from_secs(20 * 60);
        let waiter = Waiter::builder().max(cluster_max_wait).build();
        while waiter.sleep().await.is_ok() {
            let cluster = self
                .rds
                .describe_db_clusters(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = cluster {
                warn!(?err, "Failed to describe cluster while waiting for ready");
                continue;
            }

            let instance = self
                .rds
                .describe_db_instance(
                    self.db_instance_identifier
                        .as_deref()
                        .expect("instance identifier"),
                )
                .await;
            if let Err(err) = instance {
                return Err(ScenarioError::new(
                    "Failed to find instance for cluster",
                    &err,
                ));
            }

            let instances_available = instance
                .unwrap()
                .db_instances()
                .iter()
                .all(|instance| instance.db_instance_status() == Some("Available"));

            let endpoints = self
                .rds
                .describe_db_cluster_endpoints(
                    self.db_cluster_identifier
                        .as_deref()
                        .expect("cluster identifier"),
                )
                .await;

            if let Err(err) = endpoints {
                return Err(ScenarioError::new(
                    "Failed to find endpoint for cluster",
                    &err,
                ));
            }

            let endpoints_available = endpoints
                .unwrap()
                .db_cluster_endpoints()
                .iter()
                .all(|endpoint| endpoint.status() == Some("available"));

            if instances_available && endpoints_available {
                return Ok(());
            }
        }

        Err(ScenarioError::with("timed out waiting for cluster"))
    }

    pub async fn describe_db_clusters(
        &self,
        id: &str,
    ) -> Result<DescribeDbClustersOutput, SdkError<DescribeDBClustersError>> {
        self.inner
            .describe_db_clusters()
            .db_cluster_identifier(id)
            .send()
            .await
    }

#[tokio::test]
async fn test_start_cluster_and_instance() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_describe_db_instance()
        .with(eq("RustSDKCodeExamplesDBInstance"))
        .return_once(|name| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_instance_identifier(name)
                        .db_instance_status("Available")
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
        assert!(scenario
            .password
            .replace(SecretString::new("BAD SECRET".into()))
            .unwrap()
            .expose_secret()
            .is_empty());
        assert_eq!(
            scenario.db_cluster_identifier,
            Some("RustSDKCodeExamplesDBCluster".into())
        );
    });
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Err(SdkError::service_error(
                CreateDBClusterError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _}) if message == "Failed to create DB Cluster with cluster group")
}

#[tokio::test]
async fn test_start_cluster_and_instance_cluster_create_missing_id() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .return_once(|_, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context:_ }) if message == "Created DB Cluster missing Identifier");
}

#[tokio::test]
async fn test_start_cluster_and_instance_instance_create_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .return_once(|_, _, _, _| {
            Err(SdkError::service_error(
                CreateDBInstanceError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "create db instance error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    let create = scenario.start_cluster_and_instance().await;
    assert_matches!(create, Err(ScenarioError { message, context: _ }) if message == "Failed to create Instance in DB Cluster")
}

#[tokio::test]
async fn test_start_cluster_and_instance_wait_hiccup() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster()
        .withf(|id, params, engine, version, username, password| {
            assert_eq!(id, "RustSDKCodeExamplesDBCluster");
            assert_eq!(params, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(engine, "aurora-mysql");
            assert_eq!(version, "aurora-mysql8.0");
            assert_eq!(username, "test username");
            assert_eq!(password.expose_secret(), "test password");
            true
        })
        .return_once(|id, _, _, _, _, _| {
            Ok(CreateDbClusterOutput::builder()
                .db_cluster(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds
        .expect_create_db_instance()
        .withf(|cluster, name, class, engine| {
            assert_eq!(cluster, "RustSDKCodeExamplesDBCluster");
            assert_eq!(name, "RustSDKCodeExamplesDBInstance");
            assert_eq!(class, "m5.large");
            assert_eq!(engine, "aurora-mysql");
            true
        })
        .return_once(|cluster, name, class, _| {
            Ok(CreateDbInstanceOutput::builder()
                .db_instance(
                    DbInstance::builder()
                        .db_cluster_identifier(cluster)
                        .db_instance_identifier(name)
                        .db_instance_class(class)
                        .build(),
                )
                .build())
        });

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe cluster error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        })
        .with(eq("RustSDKCodeExamplesDBCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(DbCluster::builder().db_cluster_identifier(id).build())
                .build())
        });

    mock_rds.expect_describe_db_instance().return_once(|name| {
        Ok(DescribeDbInstancesOutput::builder()
            .db_instances(
                DbInstance::builder()
                    .db_instance_identifier(name)
                    .db_instance_status("Available")
                    .build(),
            )
            .build())
    });

    mock_rds
        .expect_describe_db_cluster_endpoints()
        .return_once(|_| {
            Ok(DescribeDbClusterEndpointsOutput::builder()
                .db_cluster_endpoints(DbClusterEndpoint::builder().status("available").build())
                .build())
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_version = Some("aurora-mysql8.0".into());
    scenario.instance_class = Some("m5.large".into());
    scenario.username = Some("test username".into());
    scenario.password = Some(SecretString::new("test password".into()));

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let create = scenario.start_cluster_and_instance().await;
        assert!(create.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::advance(Duration::from_secs(1)).await;
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeDBClusters](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_clusters)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_rust_1_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Get available engine families for Aurora MySql. rds.DescribeDbEngineVersions(Engine='aurora-mysql') and build a set of the 'DBParameterGroupFamily' field values. I get {aurora-mysql8.0, aurora-mysql5.7}.
    pub async fn get_engines(&self) -> Result<HashMap<String, Vec<String>>, ScenarioError> {
        let describe_db_engine_versions = self.rds.describe_db_engine_versions(DB_ENGINE).await;
        trace!(versions=?describe_db_engine_versions, "full list of versions");

        if let Err(err) = describe_db_engine_versions {
            return Err(ScenarioError::new(
                "Failed to retrieve DB Engine Versions",
                &err,
            ));
        };

        let version_count = describe_db_engine_versions
            .as_ref()
            .map(|o| o.db_engine_versions().len())
            .unwrap_or_default();
        info!(version_count, "got list of versions");

        // Create a map of engine families to their available versions.
        let mut versions = HashMap::<String, Vec<String>>::new();
        describe_db_engine_versions
            .unwrap()
            .db_engine_versions()
            .iter()
            .filter_map(
                |v| match (&v.db_parameter_group_family, &v.engine_version) {
                    (Some(family), Some(version)) => Some((family.clone(), version.clone())),
                    _ => None,
                },
            )
            .for_each(|(family, version)| versions.entry(family).or_default().push(version));

        Ok(versions)
    }

    pub async fn describe_db_engine_versions(
        &self,
        engine: &str,
    ) -> Result<DescribeDbEngineVersionsOutput, SdkError<DescribeDBEngineVersionsError>> {
        self.inner
            .describe_db_engine_versions()
            .engine(engine)
            .send()
            .await
    }

#[tokio::test]
async fn test_scenario_get_engines() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_engine_versions()
        .with(eq("aurora-mysql"))
        .return_once(|_| {
            Ok(DescribeDbEngineVersionsOutput::builder()
                .db_engine_versions(
                    DbEngineVersion::builder()
                        .db_parameter_group_family("f1")
                        .engine_version("f1a")
                        .build(),
                )
                .db_engine_versions(
                    DbEngineVersion::builder()
                        .db_parameter_group_family("f1")
                        .engine_version("f1b")
                        .build(),
                )
                .db_engine_versions(
                    DbEngineVersion::builder()
                        .db_parameter_group_family("f2")
                        .engine_version("f2a")
                        .build(),
                )
                .db_engine_versions(DbEngineVersion::builder().build())
                .build())
        });

    let scenario = AuroraScenario::new(mock_rds);

    let versions_map = scenario.get_engines().await;

    assert_eq!(
        versions_map,
        Ok(HashMap::from([
            ("f1".into(), vec!["f1a".into(), "f1b".into()]),
            ("f2".into(), vec!["f2a".into()])
        ]))
    );
}

#[tokio::test]
async fn test_scenario_get_engines_failed() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_db_engine_versions()
        .with(eq("aurora-mysql"))
        .return_once(|_| {
            Err(SdkError::service_error(
                DescribeDBEngineVersionsError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe_db_engine_versions error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let scenario = AuroraScenario::new(mock_rds);

    let versions_map = scenario.get_engines().await;
    assert_matches!(
        versions_map,
        Err(ScenarioError { message, context: _ }) if message == "Failed to retrieve DB Engine Versions"
    );
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeDBEngineVersions](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_engine_versions)」を参照してください。

### `DescribeDBInstances`
<a name="aurora_DescribeDBInstances_rust_1_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn clean_up(self) -> Result<(), Vec<ScenarioError>> {
        let mut clean_up_errors: Vec<ScenarioError> = vec![];

        // Delete the instance. rds.DeleteDbInstance.
        let delete_db_instance = self
            .rds
            .delete_db_instance(
                self.db_instance_identifier
                    .as_deref()
                    .expect("instance identifier"),
            )
            .await;
        if let Err(err) = delete_db_instance {
            let identifier = self
                .db_instance_identifier
                .as_deref()
                .unwrap_or("Missing Instance Identifier");
            let message = format!("failed to delete db instance {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance to delete
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_instances = self.rds.describe_db_instances().await;
                if let Err(err) = describe_db_instances {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check instance state during deletion",
                        &err,
                    ));
                    break;
                }
                let db_instances = describe_db_instances
                    .unwrap()
                    .db_instances()
                    .iter()
                    .filter(|instance| instance.db_cluster_identifier == self.db_cluster_identifier)
                    .cloned()
                    .collect::<Vec<DbInstance>>();

                if db_instances.is_empty() {
                    trace!("Delete Instance waited and no instances were found");
                    break;
                }
                match db_instances.first().unwrap().db_instance_status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but instances is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB instance");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster. rds.DeleteDbCluster.
        let delete_db_cluster = self
            .rds
            .delete_db_cluster(
                self.db_cluster_identifier
                    .as_deref()
                    .expect("cluster identifier"),
            )
            .await;

        if let Err(err) = delete_db_cluster {
            let identifier = self
                .db_cluster_identifier
                .as_deref()
                .unwrap_or("Missing DB Cluster Identifier");
            let message = format!("failed to delete db cluster {identifier}");
            clean_up_errors.push(ScenarioError::new(message, &err));
        } else {
            // Wait for the instance and cluster to fully delete. rds.DescribeDbInstances and rds.DescribeDbClusters until both are not found.
            let waiter = Waiter::default();
            while waiter.sleep().await.is_ok() {
                let describe_db_clusters = self
                    .rds
                    .describe_db_clusters(
                        self.db_cluster_identifier
                            .as_deref()
                            .expect("cluster identifier"),
                    )
                    .await;
                if let Err(err) = describe_db_clusters {
                    clean_up_errors.push(ScenarioError::new(
                        "Failed to check cluster state during deletion",
                        &err,
                    ));
                    break;
                }
                let describe_db_clusters = describe_db_clusters.unwrap();
                let db_clusters = describe_db_clusters.db_clusters();
                if db_clusters.is_empty() {
                    trace!("Delete cluster waited and no clusters were found");
                    break;
                }
                match db_clusters.first().unwrap().status() {
                    Some("Deleting") => continue,
                    Some(status) => {
                        info!("Attempting to delete but clusters is in {status}");
                        continue;
                    }
                    None => {
                        warn!("No status for DB cluster");
                        break;
                    }
                }
            }
        }

        // Delete the DB cluster parameter group. rds.DeleteDbClusterParameterGroup.
        let delete_db_cluster_parameter_group = self
            .rds
            .delete_db_cluster_parameter_group(
                self.db_cluster_parameter_group
                    .map(|g| {
                        g.db_cluster_parameter_group_name
                            .unwrap_or_else(|| DB_CLUSTER_PARAMETER_GROUP_NAME.to_string())
                    })
                    .as_deref()
                    .expect("cluster parameter group name"),
            )
            .await;
        if let Err(error) = delete_db_cluster_parameter_group {
            clean_up_errors.push(ScenarioError::new(
                "Failed to delete the db cluster parameter group",
                &error,
            ))
        }

        if clean_up_errors.is_empty() {
            Ok(())
        } else {
            Err(clean_up_errors)
        }
    }

    pub async fn describe_db_instances(
        &self,
    ) -> Result<DescribeDbInstancesOutput, SdkError<DescribeDBInstancesError>> {
        self.inner.describe_db_instances().send().await
    }

#[tokio::test]
async fn test_scenario_clean_up() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| Ok(DescribeDbInstancesOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| Ok(DescribeDbClustersOutput::builder().build()));

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_ok());
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}

#[tokio::test]
async fn test_scenario_clean_up_errors() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_delete_db_instance()
        .with(eq("MockInstance"))
        .return_once(|_| Ok(DeleteDbInstanceOutput::builder().build()));

    mock_rds
        .expect_describe_db_instances()
        .with()
        .times(1)
        .returning(|| {
            Ok(DescribeDbInstancesOutput::builder()
                .db_instances(
                    DbInstance::builder()
                        .db_cluster_identifier("MockCluster")
                        .db_instance_status("Deleting")
                        .build(),
                )
                .build())
        })
        .with()
        .times(1)
        .returning(|| {
            Err(SdkError::service_error(
                DescribeDBInstancesError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db instances error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster()
        .with(eq("MockCluster"))
        .return_once(|_| Ok(DeleteDbClusterOutput::builder().build()));

    mock_rds
        .expect_describe_db_clusters()
        .with(eq("MockCluster"))
        .times(1)
        .returning(|id| {
            Ok(DescribeDbClustersOutput::builder()
                .db_clusters(
                    DbCluster::builder()
                        .db_cluster_identifier(id)
                        .status("Deleting")
                        .build(),
                )
                .build())
        })
        .with(eq("MockCluster"))
        .times(1)
        .returning(|_| {
            Err(SdkError::service_error(
                DescribeDBClustersError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe db clusters error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    mock_rds
        .expect_delete_db_cluster_parameter_group()
        .with(eq("MockParamGroup"))
        .return_once(|_| Ok(DeleteDbClusterParameterGroupOutput::builder().build()));

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.db_cluster_identifier = Some(String::from("MockCluster"));
    scenario.db_instance_identifier = Some(String::from("MockInstance"));
    scenario.db_cluster_parameter_group = Some(
        DbClusterParameterGroup::builder()
            .db_cluster_parameter_group_name("MockParamGroup")
            .build(),
    );

    tokio::time::pause();
    let assertions = tokio::spawn(async move {
        let clean_up = scenario.clean_up().await;
        assert!(clean_up.is_err());
        let errs = clean_up.unwrap_err();
        assert_eq!(errs.len(), 2);
        assert_matches!(errs.first(), Some(ScenarioError {message, context: _}) if message == "Failed to check instance state during deletion");
        assert_matches!(errs.get(1), Some(ScenarioError {message, context: _}) if message == "Failed to check cluster state during deletion");
    });

    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Instances
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for first Describe Cluster
    tokio::time::advance(Duration::from_secs(1)).await; // Wait for second Describe Cluster
    tokio::time::resume();
    let _ = assertions.await;
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeDBInstances](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_db_instances)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="aurora_DescribeOrderableDBInstanceOptions_rust_1_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn get_instance_classes(&self) -> Result<Vec<String>, ScenarioError> {
        let describe_orderable_db_instance_options_items = self
            .rds
            .describe_orderable_db_instance_options(
                DB_ENGINE,
                self.engine_version
                    .as_ref()
                    .expect("engine version for db instance options")
                    .as_str(),
            )
            .await;

        describe_orderable_db_instance_options_items
            .map(|options| {
                options
                    .iter()
                    .filter(|o| o.storage_type() == Some("aurora"))
                    .map(|o| o.db_instance_class().unwrap_or_default().to_string())
                    .collect::<Vec<String>>()
            })
            .map_err(|err| ScenarioError::new("Could not get available instance classes", &err))
    }

    pub async fn describe_orderable_db_instance_options(
        &self,
        engine: &str,
        engine_version: &str,
    ) -> Result<Vec<OrderableDbInstanceOption>, SdkError<DescribeOrderableDBInstanceOptionsError>>
    {
        self.inner
            .describe_orderable_db_instance_options()
            .engine(engine)
            .engine_version(engine_version)
            .into_paginator()
            .items()
            .send()
            .try_collect()
            .await
    }

#[tokio::test]
async fn test_scenario_get_instance_classes() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_create_db_cluster_parameter_group()
        .return_once(|_, _, _| {
            Ok(CreateDbClusterParameterGroupOutput::builder()
                .db_cluster_parameter_group(DbClusterParameterGroup::builder().build())
                .build())
        });

    mock_rds
        .expect_describe_orderable_db_instance_options()
        .with(eq("aurora-mysql"), eq("aurora-mysql8.0"))
        .return_once(|_, _| {
            Ok(vec![
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t1")
                    .storage_type("aurora")
                    .build(),
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t1")
                    .storage_type("aurora-iopt1")
                    .build(),
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t2")
                    .storage_type("aurora")
                    .build(),
                OrderableDbInstanceOption::builder()
                    .db_instance_class("t3")
                    .storage_type("aurora")
                    .build(),
            ])
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario
        .set_engine("aurora-mysql", "aurora-mysql8.0")
        .await
        .expect("set engine");

    let instance_classes = scenario.get_instance_classes().await;

    assert_eq!(
        instance_classes,
        Ok(vec!["t1".into(), "t2".into(), "t3".into()])
    );
}

#[tokio::test]
async fn test_scenario_get_instance_classes_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_describe_orderable_db_instance_options()
        .with(eq("aurora-mysql"), eq("aurora-mysql8.0"))
        .return_once(|_, _| {
            Err(SdkError::service_error(
                DescribeOrderableDBInstanceOptionsError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "describe_orderable_db_instance_options_error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let mut scenario = AuroraScenario::new(mock_rds);
    scenario.engine_family = Some("aurora-mysql".into());
    scenario.engine_version = Some("aurora-mysql8.0".into());

    let instance_classes = scenario.get_instance_classes().await;

    assert_matches!(
        instance_classes,
        Err(ScenarioError {message, context: _}) if message == "Could not get available instance classes"
    );
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.describe_orderable_db_instance_options)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_rust_1_topic"></a>

次のコード例は、`ModifyDBClusterParameterGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/aurora#code-examples)での設定と実行の方法を確認してください。

```
    // Modify both the auto_increment_offset and auto_increment_increment parameters in one call in the custom parameter group. Set their ParameterValue fields to a new allowable value. rds.ModifyDbClusterParameterGroup.
    pub async fn update_auto_increment(
        &self,
        offset: u8,
        increment: u8,
    ) -> Result<(), ScenarioError> {
        let modify_db_cluster_parameter_group = self
            .rds
            .modify_db_cluster_parameter_group(
                DB_CLUSTER_PARAMETER_GROUP_NAME,
                vec![
                    Parameter::builder()
                        .parameter_name("auto_increment_offset")
                        .parameter_value(format!("{offset}"))
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                    Parameter::builder()
                        .parameter_name("auto_increment_increment")
                        .parameter_value(format!("{increment}"))
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                ],
            )
            .await;

        if let Err(error) = modify_db_cluster_parameter_group {
            return Err(ScenarioError::new(
                "Failed to modify cluster parameter group",
                &error,
            ));
        }

        Ok(())
    }

    pub async fn modify_db_cluster_parameter_group(
        &self,
        name: &str,
        parameters: Vec<Parameter>,
    ) -> Result<ModifyDbClusterParameterGroupOutput, SdkError<ModifyDBClusterParameterGroupError>>
    {
        self.inner
            .modify_db_cluster_parameter_group()
            .db_cluster_parameter_group_name(name)
            .set_parameters(Some(parameters))
            .send()
            .await
    }

#[tokio::test]
async fn test_scenario_update_auto_increment() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_modify_db_cluster_parameter_group()
        .withf(|name, params| {
            assert_eq!(name, "RustSDKCodeExamplesDBParameterGroup");
            assert_eq!(
                params,
                &vec![
                    Parameter::builder()
                        .parameter_name("auto_increment_offset")
                        .parameter_value("10")
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                    Parameter::builder()
                        .parameter_name("auto_increment_increment")
                        .parameter_value("20")
                        .apply_method(aws_sdk_rds::types::ApplyMethod::Immediate)
                        .build(),
                ]
            );
            true
        })
        .return_once(|_, _| Ok(ModifyDbClusterParameterGroupOutput::builder().build()));

    let scenario = AuroraScenario::new(mock_rds);

    scenario
        .update_auto_increment(10, 20)
        .await
        .expect("update auto increment");
}

#[tokio::test]
async fn test_scenario_update_auto_increment_error() {
    let mut mock_rds = MockRdsImpl::default();

    mock_rds
        .expect_modify_db_cluster_parameter_group()
        .return_once(|_, _| {
            Err(SdkError::service_error(
                ModifyDBClusterParameterGroupError::unhandled(Box::new(Error::new(
                    ErrorKind::Other,
                    "modify_db_cluster_parameter_group_error",
                ))),
                Response::new(StatusCode::try_from(400).unwrap(), SdkBody::empty()),
            ))
        });

    let scenario = AuroraScenario::new(mock_rds);

    let update = scenario.update_auto_increment(10, 20).await;
    assert_matches!(update, Err(ScenarioError { message, context: _}) if message == "Failed to modify cluster parameter group");
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ModifyDBClusterParameterGroup](https://docs.rs/aws-sdk-rds/latest/aws_sdk_rds/client/struct.Client.html#method.modify_db_cluster_parameter_group)」を参照してください。

# SDK for Rust を使用した Auto Scaling の例
<a name="rust_1_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにちは、Auto Scaling
<a name="auto-scaling_Hello_rust_1_topic"></a>

次のコード例は、Auto Scaling の使用を開始する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
async fn list_groups(client: &Client) -> Result<(), Error> {
    let resp = client.describe_auto_scaling_groups().send().await?;

    println!("Groups:");

    let groups = resp.auto_scaling_groups();

    for group in groups {
        println!(
            "Name:  {}",
            group.auto_scaling_group_name().unwrap_or("Unknown")
        );
        println!(
            "Arn:   {}",
            group.auto_scaling_group_arn().unwrap_or("unknown"),
        );
        println!("Zones: {:?}", group.availability_zones(),);
        println!();
    }

    println!("Found {} group(s)", groups.len());

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_groups)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="auto-scaling_Scenario_GroupsAndInstances_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 起動テンプレートとアベイラビリティーゾーンを使用して、Amazon EC2 Auto Scaling グループを作成し、実行中のインスタンスに関する情報を取得します。
+ Amazon CloudWatch メトリクスの収集を有効にします。
+ グループの希望するキャパシティを更新し、インスタンスが起動するのを待ちます。
+  グループ内の最も古いインスタンスを削除します。
+ ユーザーのリクエストやキャパシティの変更に応じて発生するスケーリングアクティビティを一覧表示します。
+ CloudWatch メトリクスの統計を取得して、リソースをクリーンアップします。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
[package]
name = "autoscaling-code-examples"
version = "0.1.0"
authors = ["Doug Schwartz <dougsch@amazon.com>", "David Souther <dpsouth@amazon.com>"]
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
aws-config = { version = "1.0.1", features = ["behavior-version-latest"] }
aws-sdk-autoscaling = { version = "1.3.0" }
aws-sdk-ec2 = { version = "1.3.0" }
aws-types = { version = "1.0.1" }
tokio = { version = "1.20.1", features = ["full"] }
clap = { version = "4.4", features = ["derive"] }
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
anyhow = "1.0.75"
tracing = "0.1.37"
tokio-stream = "0.1.14"


use std::{collections::BTreeSet, fmt::Display};

use anyhow::anyhow;
use autoscaling_code_examples::scenario::{AutoScalingScenario, ScenarioError};
use tracing::{info, warn};

async fn show_scenario_description(scenario: &AutoScalingScenario, event: &str) {
    let description = scenario.describe_scenario().await;
    info!("DescribeAutoScalingInstances: {event}\n{description}");
}

#[derive(Default, Debug)]
struct Warnings(Vec<String>);

impl Warnings {
    pub fn push(&mut self, warning: &str, error: ScenarioError) {
        let formatted = format!("{warning}: {error}");
        warn!("{formatted}");
        self.0.push(formatted);
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Display for Warnings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Warnings:")?;
        for warning in &self.0 {
            writeln!(f, "{: >4}- {warning}", "")?;
        }
        Ok(())
    }
}

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
    tracing_subscriber::fmt::init();

    let shared_config = aws_config::from_env().load().await;

    let mut warnings = Warnings::default();

    // 1. Create an EC2 launch template that you'll use to create an auto scaling group. Bonus: use SDK with EC2.CreateLaunchTemplate to create the launch template.
    // 2. CreateAutoScalingGroup: pass it the launch template you created in step 0. Give it min/max of 1 instance.
    // 4. EnableMetricsCollection: enable all metrics or a subset.
    let scenario = match AutoScalingScenario::prepare_scenario(&shared_config).await {
        Ok(scenario) => scenario,
        Err(errs) => {
            let err_str = errs
                .into_iter()
                .map(|e| e.to_string())
                .collect::<Vec<String>>()
                .join(", ");
            return Err(anyhow!("Failed to initialize scenario: {err_str}"));
        }
    };

    info!("Prepared autoscaling scenario:\n{scenario}");

    let stable = scenario.wait_for_stable(1).await;
    if let Err(err) = stable {
        warnings.push(
            "There was a problem while waiting for group to be stable",
            err,
        );
    }

    // 3. DescribeAutoScalingInstances: show that one instance has launched.
    show_scenario_description(
        &scenario,
        "show that the group was created and one instance has launched",
    )
    .await;

    // 5. UpdateAutoScalingGroup: update max size to 3.
    let scale_max_size = scenario.scale_max_size(3).await;
    if let Err(err) = scale_max_size {
        warnings.push("There was a problem scaling max size", err);
    }

    // 6. DescribeAutoScalingGroups: the current state of the group
    show_scenario_description(
        &scenario,
        "show the current state of the group after setting max size",
    )
    .await;

    // 7. SetDesiredCapacity: set desired capacity to 2.
    let scale_desired_capacity = scenario.scale_desired_capacity(2).await;
    if let Err(err) = scale_desired_capacity {
        warnings.push("There was a problem setting desired capacity", err);
    }

    //   Wait for a second instance to launch.
    let stable = scenario.wait_for_stable(2).await;
    if let Err(err) = stable {
        warnings.push(
            "There was a problem while waiting for group to be stable",
            err,
        );
    }

    // 8. DescribeAutoScalingInstances: show that two instances are launched.
    show_scenario_description(
        &scenario,
        "show that two instances are launched after setting desired capacity",
    )
    .await;

    let ids_before = scenario
        .list_instances()
        .await
        .map(|v| v.into_iter().collect::<BTreeSet<_>>())
        .unwrap_or_default();

    // 9. TerminateInstanceInAutoScalingGroup: terminate one of the instances in the group.
    let terminate_some_instance = scenario.terminate_some_instance().await;
    if let Err(err) = terminate_some_instance {
        warnings.push("There was a problem replacing an instance", err);
    }

    let wait_after_terminate = scenario.wait_for_stable(1).await;
    if let Err(err) = wait_after_terminate {
        warnings.push(
            "There was a problem waiting after terminating an instance",
            err,
        );
    }

    let wait_scale_up_after_terminate = scenario.wait_for_stable(2).await;
    if let Err(err) = wait_scale_up_after_terminate {
        warnings.push(
            "There was a problem waiting for scale up after terminating an instance",
            err,
        );
    }

    let ids_after = scenario
        .list_instances()
        .await
        .map(|v| v.into_iter().collect::<BTreeSet<_>>())
        .unwrap_or_default();

    let difference = ids_after.intersection(&ids_before).count();
    if !(difference == 1 && ids_before.len() == 2 && ids_after.len() == 2) {
        warnings.push(
            "Before and after set not different",
            ScenarioError::with(format!("{difference}")),
        );
    }

    // 10. DescribeScalingActivities: list the scaling activities that have occurred for the group so far.
    show_scenario_description(
        &scenario,
        "list the scaling activities that have occurred for the group so far",
    )
    .await;

    // 11. DisableMetricsCollection
    let scale_group = scenario.scale_group_to_zero().await;
    if let Err(err) = scale_group {
        warnings.push("There was a problem scaling the group to 0", err);
    }
    show_scenario_description(&scenario, "Scenario scaled to 0").await;

    // 12. DeleteAutoScalingGroup (to delete the group you must stop all instances):
    // 13. Delete LaunchTemplate.
    let clean_scenario = scenario.clean_scenario().await;
    if let Err(errs) = clean_scenario {
        for err in errs {
            warnings.push("There was a problem cleaning the scenario", err);
        }
    } else {
        info!("The scenario has been cleaned up!");
    }

    if warnings.is_empty() {
        Ok(())
    } else {
        Err(anyhow!(
            "There were warnings during scenario execution:\n{warnings}"
        ))
    }
}

pub mod scenario;


use std::{
    error::Error,
    fmt::{Debug, Display},
    time::{Duration, SystemTime},
};

use anyhow::anyhow;
use aws_config::SdkConfig;
use aws_sdk_autoscaling::{
    error::{DisplayErrorContext, ProvideErrorMetadata},
    types::{Activity, AutoScalingGroup, LaunchTemplateSpecification},
};
use aws_sdk_ec2::types::RequestLaunchTemplateData;
use tracing::trace;

const LAUNCH_TEMPLATE_NAME: &str = "SDK_Code_Examples_EC2_Autoscaling_template_from_Rust_SDK";
const AUTOSCALING_GROUP_NAME: &str = "SDK_Code_Examples_EC2_Autoscaling_Group_from_Rust_SDK";
const MAX_WAIT: Duration = Duration::from_secs(5 * 60); // Wait at most 25 seconds.
const WAIT_TIME: Duration = Duration::from_millis(500); // Wait half a second at a time.

struct Waiter {
    start: SystemTime,
    max: Duration,
}

impl Waiter {
    fn new() -> Self {
        Waiter {
            start: SystemTime::now(),
            max: MAX_WAIT,
        }
    }

    async fn sleep(&self) -> Result<(), ScenarioError> {
        if SystemTime::now()
            .duration_since(self.start)
            .unwrap_or(Duration::MAX)
            > self.max
        {
            Err(ScenarioError::with(
                "Exceeded maximum wait duration for stable group",
            ))
        } else {
            tokio::time::sleep(WAIT_TIME).await;
            Ok(())
        }
    }
}

pub struct AutoScalingScenario {
    ec2: aws_sdk_ec2::Client,
    autoscaling: aws_sdk_autoscaling::Client,
    launch_template_arn: String,
    auto_scaling_group_name: String,
}

impl Display for AutoScalingScenario {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!(
            "\tLaunch Template ID: {}\n",
            self.launch_template_arn
        ))?;
        f.write_fmt(format_args!(
            "\tScaling Group Name: {}\n",
            self.auto_scaling_group_name
        ))?;

        Ok(())
    }
}

pub struct AutoScalingScenarioDescription {
    group: Result<Vec<String>, ScenarioError>,
    instances: Result<Vec<String>, anyhow::Error>,
    activities: Result<Vec<Activity>, anyhow::Error>,
}

impl Display for AutoScalingScenarioDescription {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "\t      Group status:")?;
        match &self.group {
            Ok(groups) => {
                for status in groups {
                    writeln!(f, "\t\t- {status}")?;
                }
            }
            Err(e) => writeln!(f, "\t\t! - {e}")?,
        }
        writeln!(f, "\t         Instances:")?;
        match &self.instances {
            Ok(instances) => {
                for instance in instances {
                    writeln!(f, "\t\t- {instance}")?;
                }
            }
            Err(e) => writeln!(f, "\t\t! {e}")?,
        }

        writeln!(f, "\t        Activities:")?;
        match &self.activities {
            Ok(activities) => {
                for activity in activities {
                    writeln!(
                        f,
                        "\t\t- {} Progress: {}% Status: {:?} End: {:?}",
                        activity.cause().unwrap_or("Unknown"),
                        activity.progress.unwrap_or(-1),
                        activity.status_code(),
                        // activity.status_message().unwrap_or_default()
                        activity.end_time(),
                    )?;
                }
            }
            Err(e) => writeln!(f, "\t\t! {e}")?,
        }

        Ok(())
    }
}

#[derive(Debug)]
struct MetadataError {
    message: Option<String>,
    code: Option<String>,
}

impl MetadataError {
    fn from(err: &dyn ProvideErrorMetadata) -> Self {
        MetadataError {
            message: err.message().map(|s| s.to_string()),
            code: err.code().map(|s| s.to_string()),
        }
    }
}

impl Display for MetadataError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let display = match (&self.message, &self.code) {
            (None, None) => "Unknown".to_string(),
            (None, Some(code)) => format!("({code})"),
            (Some(message), None) => message.to_string(),
            (Some(message), Some(code)) => format!("{message} ({code})"),
        };
        write!(f, "{display}")
    }
}

#[derive(Debug)]
pub struct ScenarioError {
    message: String,
    context: Option<MetadataError>,
}

impl ScenarioError {
    pub fn with(message: impl Into<String>) -> Self {
        ScenarioError {
            message: message.into(),
            context: None,
        }
    }

    pub fn new(message: impl Into<String>, err: &dyn ProvideErrorMetadata) -> Self {
        ScenarioError {
            message: message.into(),
            context: Some(MetadataError::from(err)),
        }
    }
}

impl Error for ScenarioError {
    // While `Error` can capture `source` information about the underlying error, for this example
    // the ScenarioError captures the underlying information in MetadataError and treats it as a
    // single Error from this Crate. In other contexts, it may be appropriate to model the error
    // as including the SdkError as its source.
}
impl Display for ScenarioError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.context {
            Some(c) => write!(f, "{}: {}", self.message, c),
            None => write!(f, "{}", self.message),
        }
    }
}

impl AutoScalingScenario {
    pub async fn prepare_scenario(sdk_config: &SdkConfig) -> Result<Self, Vec<ScenarioError>> {
        let ec2 = aws_sdk_ec2::Client::new(sdk_config);
        let autoscaling = aws_sdk_autoscaling::Client::new(sdk_config);

        let auto_scaling_group_name = String::from(AUTOSCALING_GROUP_NAME);

        // Before creating any resources, prepare the list of AZs
        let availablity_zones = ec2.describe_availability_zones().send().await;
        if let Err(err) = availablity_zones {
            return Err(vec![ScenarioError::new("Failed to find AZs", &err)]);
        }

        let availability_zones: Vec<String> = availablity_zones
            .unwrap()
            .availability_zones
            .unwrap_or_default()
            .iter()
            .take(3)
            .map(|z| z.zone_name.clone().unwrap())
            .collect();

        // 1. Create an EC2 launch template that you'll use to create an auto scaling group. Bonus: use SDK with EC2.CreateLaunchTemplate to create the launch template.
        //   * Recommended: InstanceType='t1.micro', ImageId='ami-0ca285d4c2cda3300'
        let create_launch_template = ec2
            .create_launch_template()
            .launch_template_name(LAUNCH_TEMPLATE_NAME)
            .launch_template_data(
                RequestLaunchTemplateData::builder()
                    .instance_type(aws_sdk_ec2::types::InstanceType::T1Micro)
                    .image_id("ami-0ca285d4c2cda3300")
                    .build(),
            )
            .send()
            .await
            .map_err(|err| vec![ScenarioError::new("Failed to create launch template", &err)])?;

        let launch_template_arn = match create_launch_template.launch_template {
            Some(launch_template) => launch_template.launch_template_id.unwrap_or_default(),
            None => {
                // Try to delete the launch template
                let _ = ec2
                    .delete_launch_template()
                    .launch_template_name(LAUNCH_TEMPLATE_NAME)
                    .send()
                    .await;
                return Err(vec![ScenarioError::with("Failed to load launch template")]);
            }
        };

        // 2. CreateAutoScalingGroup: pass it the launch template you created in step 0. Give it min/max of 1 instance.
        //   You can use EC2.describe_availability_zones() to get a list of AZs (you have to specify an AZ when you create the group).
        //   Wait for instance to launch. Use a waiter if you have one, otherwise DescribeAutoScalingInstances until LifecycleState='InService'
        if let Err(err) = autoscaling
            .create_auto_scaling_group()
            .auto_scaling_group_name(auto_scaling_group_name.as_str())
            .launch_template(
                LaunchTemplateSpecification::builder()
                    .launch_template_id(launch_template_arn.clone())
                    .version("$Latest")
                    .build(),
            )
            .max_size(1)
            .min_size(1)
            .set_availability_zones(Some(availability_zones))
            .send()
            .await
        {
            let mut errs = vec![ScenarioError::new(
                "Failed to create autoscaling group",
                &err,
            )];

            if let Err(err) = autoscaling
                .delete_auto_scaling_group()
                .auto_scaling_group_name(auto_scaling_group_name.as_str())
                .send()
                .await
            {
                errs.push(ScenarioError::new(
                    "Failed to clean up autoscaling group",
                    &err,
                ));
            }

            if let Err(err) = ec2
                .delete_launch_template()
                .launch_template_id(launch_template_arn.clone())
                .send()
                .await
            {
                errs.push(ScenarioError::new(
                    "Failed to clean up launch template",
                    &err,
                ));
            }
            return Err(errs);
        }

        let scenario = AutoScalingScenario {
            ec2,
            autoscaling: autoscaling.clone(), // Clients are cheap so cloning here to prevent a move is ok.
            auto_scaling_group_name: auto_scaling_group_name.clone(),
            launch_template_arn,
        };

        let enable_metrics_collection = autoscaling
            .enable_metrics_collection()
            .auto_scaling_group_name(auto_scaling_group_name.as_str())
            .granularity("1Minute")
            .set_metrics(Some(vec![
                String::from("GroupMinSize"),
                String::from("GroupMaxSize"),
                String::from("GroupDesiredCapacity"),
                String::from("GroupInServiceInstances"),
                String::from("GroupTotalInstances"),
            ]))
            .send()
            .await;

        match enable_metrics_collection {
            Ok(_) => Ok(scenario),
            Err(err) => {
                scenario.clean_scenario().await?;
                Err(vec![ScenarioError::new(
                    "Failed to enable metrics collections for group",
                    &err,
                )])
            }
        }
    }

    pub async fn clean_scenario(self) -> Result<(), Vec<ScenarioError>> {
        let _ = self.wait_for_no_scaling().await;
        let delete_group = self
            .autoscaling
            .delete_auto_scaling_group()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .send()
            .await;

        // 14. Delete LaunchTemplate.
        let delete_launch_template = self
            .ec2
            .delete_launch_template()
            .launch_template_id(self.launch_template_arn.clone())
            .send()
            .await;

        let early_exit = match (delete_group, delete_launch_template) {
            (Ok(_), Ok(_)) => Ok(()),
            (Ok(_), Err(e)) => Err(vec![ScenarioError::new(
                "There was an error cleaning the launch template",
                &e,
            )]),
            (Err(e), Ok(_)) => Err(vec![ScenarioError::new(
                "There was an error cleaning the scale group",
                &e,
            )]),
            (Err(e1), Err(e2)) => Err(vec![
                ScenarioError::new("Multiple error cleaning the scenario Scale Group", &e1),
                ScenarioError::new("Multiple error cleaning the scenario Launch Template", &e2),
            ]),
        };

        if early_exit.is_err() {
            early_exit
        } else {
            // Wait for delete_group to finish
            let waiter = Waiter::new();
            let mut errors = Vec::<ScenarioError>::new();
            while errors.len() < 3 {
                if let Err(e) = waiter.sleep().await {
                    errors.push(e);
                    continue;
                }
                let describe_group = self
                    .autoscaling
                    .describe_auto_scaling_groups()
                    .auto_scaling_group_names(self.auto_scaling_group_name.clone())
                    .send()
                    .await;
                match describe_group {
                    Ok(group) => match group.auto_scaling_groups().first() {
                        Some(group) => {
                            if group.status() != Some("Delete in progress") {
                                errors.push(ScenarioError::with(format!(
                                    "Group in an unknown state while deleting: {}",
                                    group.status().unwrap_or("unknown error")
                                )));
                                return Err(errors);
                            }
                        }
                        None => return Ok(()),
                    },
                    Err(err) => {
                        errors.push(ScenarioError::new("Failed to describe autoscaling group during cleanup 3 times, last error", &err));
                    }
                }
                if errors.len() > 3 {
                    return Err(errors);
                }
            }
            Err(vec![ScenarioError::with(
                "Exited cleanup wait loop without retuning success or failing after three rounds",
            )])
        }
    }

    pub async fn describe_scenario(&self) -> AutoScalingScenarioDescription {
        let group = self
            .autoscaling
            .describe_auto_scaling_groups()
            .auto_scaling_group_names(self.auto_scaling_group_name.clone())
            .send()
            .await
            .map(|s| {
                s.auto_scaling_groups()
                    .iter()
                    .map(|s| {
                        format!(
                            "{}: {}",
                            s.auto_scaling_group_name().unwrap_or("Unknown"),
                            s.status().unwrap_or("Unknown")
                        )
                    })
                    .collect::<Vec<String>>()
            })
            .map_err(|e| {
                ScenarioError::new("Failed to describe auto scaling groups for scenario", &e)
            });

        let instances = self
            .list_instances()
            .await
            .map_err(|e| anyhow!("There was an error listing instances: {e}",));

        // 10. DescribeScalingActivities: list the scaling activities that have occurred for the group so far.
        //   Bonus: use CloudWatch API to get and show some metrics collected for the group.
        //   CW.ListMetrics with Namespace='AWS/AutoScaling' and Dimensions=[{'Name': 'AutoScalingGroupName', 'Value': }]
        //   CW.GetMetricStatistics with Statistics='Sum'. Start and End times must be in UTC!
        let activities = self
            .autoscaling
            .describe_scaling_activities()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .into_paginator()
            .items()
            .send()
            .collect::<Result<Vec<_>, _>>()
            .await
            .map_err(|e| {
                anyhow!(
                    "There was an error retrieving scaling activities: {}",
                    DisplayErrorContext(&e)
                )
            });

        AutoScalingScenarioDescription {
            group,
            instances,
            activities,
        }
    }

    async fn get_group(&self) -> Result<AutoScalingGroup, ScenarioError> {
        let describe_auto_scaling_groups = self
            .autoscaling
            .describe_auto_scaling_groups()
            .auto_scaling_group_names(self.auto_scaling_group_name.clone())
            .send()
            .await;

        if let Err(err) = describe_auto_scaling_groups {
            return Err(ScenarioError::new(
                format!(
                    "Failed to get status of autoscaling group {}",
                    self.auto_scaling_group_name.clone()
                )
                .as_str(),
                &err,
            ));
        }

        let describe_auto_scaling_groups_output = describe_auto_scaling_groups.unwrap();
        let auto_scaling_groups = describe_auto_scaling_groups_output.auto_scaling_groups();
        let auto_scaling_group = auto_scaling_groups.first();

        if auto_scaling_group.is_none() {
            return Err(ScenarioError::with(format!(
                "Could not find autoscaling group {}",
                self.auto_scaling_group_name.clone()
            )));
        }

        Ok(auto_scaling_group.unwrap().clone())
    }

    pub async fn wait_for_no_scaling(&self) -> Result<(), ScenarioError> {
        let waiter = Waiter::new();
        let mut scaling = true;
        while scaling {
            waiter.sleep().await?;
            let describe_activities = self
                .autoscaling
                .describe_scaling_activities()
                .auto_scaling_group_name(self.auto_scaling_group_name.clone())
                .send()
                .await
                .map_err(|e| {
                    ScenarioError::new("Failed to get autoscaling activities for group", &e)
                })?;
            let activities = describe_activities.activities();
            trace!(
                "Waiting for no scaling found {} activities",
                activities.len()
            );
            scaling = activities.iter().any(|a| a.progress() < Some(100));
        }
        Ok(())
    }

    pub async fn wait_for_stable(&self, size: usize) -> Result<(), ScenarioError> {
        self.wait_for_no_scaling().await?;

        let mut group = self.get_group().await?;
        let mut count = count_group_instances(&group);

        let waiter = Waiter::new();
        while count != size {
            trace!("Waiting for stable {size} (current: {count})");
            waiter.sleep().await?;
            group = self.get_group().await?;
            count = count_group_instances(&group);
        }

        Ok(())
    }

    pub async fn list_instances(&self) -> Result<Vec<String>, ScenarioError> {
        // The direct way to list instances is by using DescribeAutoScalingGroup's instances property. However, this returns a Vec<Instance>, as opposed to a Vec<AutoScalingInstanceDetails>.
        // Ok(self.get_group().await?.instances.unwrap_or_default().map(|i| i.instance_id.clone().unwrap_or_default()).filter(|id| !id.is_empty()).collect())

        // Alternatively, and for the sake of example, DescribeAutoScalingInstances returns a list that can be filtered by the client.
        self.autoscaling
            .describe_auto_scaling_instances()
            .into_paginator()
            .items()
            .send()
            .try_collect()
            .await
            .map(|items| {
                items
                    .into_iter()
                    .filter(|i| {
                        i.auto_scaling_group_name.as_deref()
                            == Some(self.auto_scaling_group_name.as_str())
                    })
                    .map(|i| i.instance_id.unwrap_or_default())
                    .filter(|id| !id.is_empty())
                    .collect::<Vec<String>>()
            })
            .map_err(|err| ScenarioError::new("Failed to get list of auto scaling instances", &err))
    }

    pub async fn scale_min_size(&self, size: i32) -> Result<(), ScenarioError> {
        let update_group = self
            .autoscaling
            .update_auto_scaling_group()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .min_size(size)
            .send()
            .await;
        if let Err(err) = update_group {
            return Err(ScenarioError::new(
                format!("Failer to update group to min size ({size}))").as_str(),
                &err,
            ));
        }
        Ok(())
    }

    pub async fn scale_max_size(&self, size: i32) -> Result<(), ScenarioError> {
        // 5. UpdateAutoScalingGroup: update max size to 3.
        let update_group = self
            .autoscaling
            .update_auto_scaling_group()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .max_size(size)
            .send()
            .await;
        if let Err(err) = update_group {
            return Err(ScenarioError::new(
                format!("Failed to update group to max size ({size})").as_str(),
                &err,
            ));
        }
        Ok(())
    }

    pub async fn scale_desired_capacity(&self, capacity: i32) -> Result<(), ScenarioError> {
        // 7. SetDesiredCapacity: set desired capacity to 2.
        //   Wait for a second instance to launch.
        let update_group = self
            .autoscaling
            .set_desired_capacity()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .desired_capacity(capacity)
            .send()
            .await;
        if let Err(err) = update_group {
            return Err(ScenarioError::new(
                format!("Failed to update group to desired capacity ({capacity}))").as_str(),
                &err,
            ));
        }
        Ok(())
    }

    pub async fn scale_group_to_zero(&self) -> Result<(), ScenarioError> {
        // If this fails it's fine, just means there are extra cloudwatch metrics events for the scale-down.
        let _ = self
            .autoscaling
            .disable_metrics_collection()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .send()
            .await;

        // 12. DeleteAutoScalingGroup (to delete the group you must stop all instances):
        //   UpdateAutoScalingGroup with MinSize=0
        let update_group = self
            .autoscaling
            .update_auto_scaling_group()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .min_size(0)
            .desired_capacity(0)
            .send()
            .await;
        if let Err(err) = update_group {
            return Err(ScenarioError::new(
                "Failed to update group for scaling down&",
                &err,
            ));
        }

        let stable = self.wait_for_stable(0).await;
        if let Err(err) = stable {
            return Err(ScenarioError::with(format!(
                "Error while waiting for group to be stable on scale down: {err}"
            )));
        }

        Ok(())
    }

    pub async fn terminate_some_instance(&self) -> Result<(), ScenarioError> {
        // Retrieve a list of instances in the auto scaling group.
        let auto_scaling_group = self.get_group().await?;
        let instances = auto_scaling_group.instances();
        // Or use other logic to find an instance to terminate.
        let instance = instances.first();
        if let Some(instance) = instance {
            let instance_id = if let Some(instance_id) = instance.instance_id() {
                instance_id
            } else {
                return Err(ScenarioError::with("Missing instance id"));
            };
            let termination = self
                .ec2
                .terminate_instances()
                .instance_ids(instance_id)
                .send()
                .await;
            if let Err(err) = termination {
                Err(ScenarioError::new(
                    "There was a problem terminating an instance",
                    &err,
                ))
            } else {
                Ok(())
            }
        } else {
            Err(ScenarioError::with("There was no instance to terminate"))
        }
    }
}

fn count_group_instances(group: &AutoScalingGroup) -> usize {
    group.instances.as_ref().map(|i| i.len()).unwrap_or(0)
}
```
+ API の詳細については、「*AWS SDK for Rust API リファレンス*」の以下のトピックを参照してください。
  + [CreateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.create_auto_scaling_group)
  + [DeleteAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.delete_auto_scaling_group)
  + [DescribeAutoScalingGroups](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_groups)
  + [DescribeAutoScalingInstances](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_instances)
  + [DescribeScalingActivities](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_scaling_activities)
  + [DisableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.disable_metrics_collection)
  + [EnableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.enable_metrics_collection)
  + [SetDesiredCapacity](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.set_desired_capacity)
  + [TerminateInstanceInAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.terminate_instance_in_auto_scaling_group)
  + [UpdateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.update_auto_scaling_group)

## アクション
<a name="actions"></a>

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_rust_1_topic"></a>

次のコード例は、`CreateAutoScalingGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
async fn create_group(client: &Client, name: &str, id: &str) -> Result<(), Error> {
    client
        .create_auto_scaling_group()
        .auto_scaling_group_name(name)
        .instance_id(id)
        .min_size(1)
        .max_size(5)
        .send()
        .await?;

    println!("Created AutoScaling group");

    Ok(())
}
```
+  API の詳細については、「AWS SDK for Rust API リファレンス」の「[CreateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.create_auto_scaling_group)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_rust_1_topic"></a>

次のコード例は、`DeleteAutoScalingGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
async fn delete_group(client: &Client, name: &str, force: bool) -> Result<(), Error> {
    client
        .delete_auto_scaling_group()
        .auto_scaling_group_name(name)
        .set_force_delete(if force { Some(true) } else { None })
        .send()
        .await?;

    println!("Deleted Auto Scaling group");

    Ok(())
}
```
+  API の詳細については、「AWS SDK for Rust API リファレンス」の「[DeleteAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.delete_auto_scaling_group)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_rust_1_topic"></a>

次のコード例は、`DescribeAutoScalingGroups` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
async fn list_groups(client: &Client) -> Result<(), Error> {
    let resp = client.describe_auto_scaling_groups().send().await?;

    println!("Groups:");

    let groups = resp.auto_scaling_groups();

    for group in groups {
        println!(
            "Name:  {}",
            group.auto_scaling_group_name().unwrap_or("Unknown")
        );
        println!(
            "Arn:   {}",
            group.auto_scaling_group_arn().unwrap_or("unknown"),
        );
        println!("Zones: {:?}", group.availability_zones(),);
        println!();
    }

    println!("Found {} group(s)", groups.len());

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeAutoScalingGroups](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_groups)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_rust_1_topic"></a>

次のコード例は、`DescribeAutoScalingInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn list_instances(&self) -> Result<Vec<String>, ScenarioError> {
        // The direct way to list instances is by using DescribeAutoScalingGroup's instances property. However, this returns a Vec<Instance>, as opposed to a Vec<AutoScalingInstanceDetails>.
        // Ok(self.get_group().await?.instances.unwrap_or_default().map(|i| i.instance_id.clone().unwrap_or_default()).filter(|id| !id.is_empty()).collect())

        // Alternatively, and for the sake of example, DescribeAutoScalingInstances returns a list that can be filtered by the client.
        self.autoscaling
            .describe_auto_scaling_instances()
            .into_paginator()
            .items()
            .send()
            .try_collect()
            .await
            .map(|items| {
                items
                    .into_iter()
                    .filter(|i| {
                        i.auto_scaling_group_name.as_deref()
                            == Some(self.auto_scaling_group_name.as_str())
                    })
                    .map(|i| i.instance_id.unwrap_or_default())
                    .filter(|id| !id.is_empty())
                    .collect::<Vec<String>>()
            })
            .map_err(|err| ScenarioError::new("Failed to get list of auto scaling instances", &err))
    }
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeAutoScalingInstances](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_auto_scaling_instances)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_rust_1_topic"></a>

次のコード例は、`DescribeScalingActivities` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn describe_scenario(&self) -> AutoScalingScenarioDescription {
        let group = self
            .autoscaling
            .describe_auto_scaling_groups()
            .auto_scaling_group_names(self.auto_scaling_group_name.clone())
            .send()
            .await
            .map(|s| {
                s.auto_scaling_groups()
                    .iter()
                    .map(|s| {
                        format!(
                            "{}: {}",
                            s.auto_scaling_group_name().unwrap_or("Unknown"),
                            s.status().unwrap_or("Unknown")
                        )
                    })
                    .collect::<Vec<String>>()
            })
            .map_err(|e| {
                ScenarioError::new("Failed to describe auto scaling groups for scenario", &e)
            });

        let instances = self
            .list_instances()
            .await
            .map_err(|e| anyhow!("There was an error listing instances: {e}",));

        // 10. DescribeScalingActivities: list the scaling activities that have occurred for the group so far.
        //   Bonus: use CloudWatch API to get and show some metrics collected for the group.
        //   CW.ListMetrics with Namespace='AWS/AutoScaling' and Dimensions=[{'Name': 'AutoScalingGroupName', 'Value': }]
        //   CW.GetMetricStatistics with Statistics='Sum'. Start and End times must be in UTC!
        let activities = self
            .autoscaling
            .describe_scaling_activities()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .into_paginator()
            .items()
            .send()
            .collect::<Result<Vec<_>, _>>()
            .await
            .map_err(|e| {
                anyhow!(
                    "There was an error retrieving scaling activities: {}",
                    DisplayErrorContext(&e)
                )
            });

        AutoScalingScenarioDescription {
            group,
            instances,
            activities,
        }
    }
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeScalingActivities](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.describe_scaling_activities)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_rust_1_topic"></a>

次のコード例は、`DisableMetricsCollection` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
        // If this fails it's fine, just means there are extra cloudwatch metrics events for the scale-down.
        let _ = self
            .autoscaling
            .disable_metrics_collection()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .send()
            .await;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DisableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.disable_metrics_collection)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_rust_1_topic"></a>

次のコード例は、`EnableMetricsCollection` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
        let enable_metrics_collection = autoscaling
            .enable_metrics_collection()
            .auto_scaling_group_name(auto_scaling_group_name.as_str())
            .granularity("1Minute")
            .set_metrics(Some(vec![
                String::from("GroupMinSize"),
                String::from("GroupMaxSize"),
                String::from("GroupDesiredCapacity"),
                String::from("GroupInServiceInstances"),
                String::from("GroupTotalInstances"),
            ]))
            .send()
            .await;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[EnableMetricsCollection](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.enable_metrics_collection)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_rust_1_topic"></a>

次のコード例は、`SetDesiredCapacity` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn scale_desired_capacity(&self, capacity: i32) -> Result<(), ScenarioError> {
        // 7. SetDesiredCapacity: set desired capacity to 2.
        //   Wait for a second instance to launch.
        let update_group = self
            .autoscaling
            .set_desired_capacity()
            .auto_scaling_group_name(self.auto_scaling_group_name.clone())
            .desired_capacity(capacity)
            .send()
            .await;
        if let Err(err) = update_group {
            return Err(ScenarioError::new(
                format!("Failed to update group to desired capacity ({capacity}))").as_str(),
                &err,
            ));
        }
        Ok(())
    }
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[SetDesiredCapacity](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.set_desired_capacity)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_rust_1_topic"></a>

次のコード例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn terminate_some_instance(&self) -> Result<(), ScenarioError> {
        // Retrieve a list of instances in the auto scaling group.
        let auto_scaling_group = self.get_group().await?;
        let instances = auto_scaling_group.instances();
        // Or use other logic to find an instance to terminate.
        let instance = instances.first();
        if let Some(instance) = instance {
            let instance_id = if let Some(instance_id) = instance.instance_id() {
                instance_id
            } else {
                return Err(ScenarioError::with("Missing instance id"));
            };
            let termination = self
                .ec2
                .terminate_instances()
                .instance_ids(instance_id)
                .send()
                .await;
            if let Err(err) = termination {
                Err(ScenarioError::new(
                    "There was a problem terminating an instance",
                    &err,
                ))
            } else {
                Ok(())
            }
        } else {
            Err(ScenarioError::with("There was no instance to terminate"))
        }
    }

    async fn get_group(&self) -> Result<AutoScalingGroup, ScenarioError> {
        let describe_auto_scaling_groups = self
            .autoscaling
            .describe_auto_scaling_groups()
            .auto_scaling_group_names(self.auto_scaling_group_name.clone())
            .send()
            .await;

        if let Err(err) = describe_auto_scaling_groups {
            return Err(ScenarioError::new(
                format!(
                    "Failed to get status of autoscaling group {}",
                    self.auto_scaling_group_name.clone()
                )
                .as_str(),
                &err,
            ));
        }

        let describe_auto_scaling_groups_output = describe_auto_scaling_groups.unwrap();
        let auto_scaling_groups = describe_auto_scaling_groups_output.auto_scaling_groups();
        let auto_scaling_group = auto_scaling_groups.first();

        if auto_scaling_group.is_none() {
            return Err(ScenarioError::with(format!(
                "Could not find autoscaling group {}",
                self.auto_scaling_group_name.clone()
            )));
        }

        Ok(auto_scaling_group.unwrap().clone())
    }
```
+  API の詳細については、「AWS SDK for Rust API リファレンス」**の「[TerminateInstanceInAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.terminate_instance_in_auto_scaling_group)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_rust_1_topic"></a>

次のコード例は、`UpdateAutoScalingGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/auto-scaling#code-examples)での設定と実行の方法を確認してください。

```
async fn update_group(client: &Client, name: &str, size: i32) -> Result<(), Error> {
    client
        .update_auto_scaling_group()
        .auto_scaling_group_name(name)
        .max_size(size)
        .send()
        .await?;

    println!("Updated AutoScaling group");

    Ok(())
}
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[UpdateAutoScalingGroup](https://docs.rs/aws-sdk-autoscaling/latest/aws_sdk_autoscaling/client/struct.Client.html#method.update_auto_scaling_group)」を参照してください。**

# SDK for Rust を使用する Amazon Bedrock ランタイムの例
<a name="rust_1_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイムで AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)
+ [Anthropic Claude](#anthropic_claude)

## シナリオ
<a name="scenarios"></a>

### Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUse_rust_1_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
デモのプライマリシナリオとロジック。これは、ユーザー、Amazon Bedrock Converse API、および気象ツール間の会話を調整します。  

```
#[derive(Debug)]
#[allow(dead_code)]
struct InvokeToolResult(String, ToolResultBlock);
struct ToolUseScenario {
    client: Client,
    conversation: Vec<Message>,
    system_prompt: SystemContentBlock,
    tool_config: ToolConfiguration,
}

impl ToolUseScenario {
    fn new(client: Client) -> Self {
        let system_prompt = SystemContentBlock::Text(SYSTEM_PROMPT.into());
        let tool_config = ToolConfiguration::builder()
            .tools(Tool::ToolSpec(
                ToolSpecification::builder()
                    .name(TOOL_NAME)
                    .description(TOOL_DESCRIPTION)
                    .input_schema(ToolInputSchema::Json(make_tool_schema()))
                    .build()
                    .unwrap(),
            ))
            .build()
            .unwrap();

        ToolUseScenario {
            client,
            conversation: vec![],
            system_prompt,
            tool_config,
        }
    }

    async fn run(&mut self) -> Result<(), ToolUseScenarioError> {
        loop {
            let input = get_input().await?;
            if input.is_none() {
                break;
            }

            let message = Message::builder()
                .role(User)
                .content(ContentBlock::Text(input.unwrap()))
                .build()
                .map_err(ToolUseScenarioError::from)?;
            self.conversation.push(message);

            let response = self.send_to_bedrock().await?;

            self.process_model_response(response).await?;
        }

        Ok(())
    }

    async fn send_to_bedrock(&mut self) -> Result<ConverseOutput, ToolUseScenarioError> {
        debug!("Sending conversation to bedrock");
        self.client
            .converse()
            .model_id(MODEL_ID)
            .set_messages(Some(self.conversation.clone()))
            .system(self.system_prompt.clone())
            .tool_config(self.tool_config.clone())
            .send()
            .await
            .map_err(ToolUseScenarioError::from)
    }

    async fn process_model_response(
        &mut self,
        mut response: ConverseOutput,
    ) -> Result<(), ToolUseScenarioError> {
        let mut iteration = 0;

        while iteration < MAX_RECURSIONS {
            iteration += 1;
            let message = if let Some(ref output) = response.output {
                if output.is_message() {
                    Ok(output.as_message().unwrap().clone())
                } else {
                    Err(ToolUseScenarioError(
                        "Converse Output is not a message".into(),
                    ))
                }
            } else {
                Err(ToolUseScenarioError("Missing Converse Output".into()))
            }?;

            self.conversation.push(message.clone());

            match response.stop_reason {
                StopReason::ToolUse => {
                    response = self.handle_tool_use(&message).await?;
                }
                StopReason::EndTurn => {
                    print_model_response(&message.content[0])?;
                    return Ok(());
                }
                _ => (),
            }
        }

        Err(ToolUseScenarioError(
            "Exceeded MAX_ITERATIONS when calling tools".into(),
        ))
    }

    async fn handle_tool_use(
        &mut self,
        message: &Message,
    ) -> Result<ConverseOutput, ToolUseScenarioError> {
        let mut tool_results: Vec<ContentBlock> = vec![];

        for block in &message.content {
            match block {
                ContentBlock::Text(_) => print_model_response(block)?,
                ContentBlock::ToolUse(tool) => {
                    let tool_response = self.invoke_tool(tool).await?;
                    tool_results.push(ContentBlock::ToolResult(tool_response.1));
                }
                _ => (),
            };
        }

        let message = Message::builder()
            .role(User)
            .set_content(Some(tool_results))
            .build()?;
        self.conversation.push(message);

        self.send_to_bedrock().await
    }

    async fn invoke_tool(
        &mut self,
        tool: &ToolUseBlock,
    ) -> Result<InvokeToolResult, ToolUseScenarioError> {
        match tool.name() {
            TOOL_NAME => {
                println!(
                    "\x1b[0;90mExecuting tool: {TOOL_NAME} with input: {:?}...\x1b[0m",
                    tool.input()
                );
                let content = fetch_weather_data(tool).await?;
                println!(
                    "\x1b[0;90mTool responded with {:?}\x1b[0m",
                    content.content()
                );
                Ok(InvokeToolResult(tool.tool_use_id.clone(), content))
            }
            _ => Err(ToolUseScenarioError(format!(
                "The requested tool with name {} does not exist",
                tool.name()
            ))),
        }
    }
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let sdk_config = aws_config::defaults(BehaviorVersion::latest())
        .region(CLAUDE_REGION)
        .load()
        .await;
    let client = Client::new(&sdk_config);

    let mut scenario = ToolUseScenario::new(client);

    header();
    if let Err(err) = scenario.run().await {
        println!("There was an error running the scenario! {}", err.0)
    }
    footer();
}
```
デモで使用される気象ツール。このスクリプトは、ツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
const ENDPOINT: &str = "https://api.open-meteo.com/v1/forecast";
async fn fetch_weather_data(
    tool_use: &ToolUseBlock,
) -> Result<ToolResultBlock, ToolUseScenarioError> {
    let input = tool_use.input();
    let latitude = input
        .as_object()
        .unwrap()
        .get("latitude")
        .unwrap()
        .as_string()
        .unwrap();
    let longitude = input
        .as_object()
        .unwrap()
        .get("longitude")
        .unwrap()
        .as_string()
        .unwrap();
    let params = [
        ("latitude", latitude),
        ("longitude", longitude),
        ("current_weather", "true"),
    ];

    debug!("Calling {ENDPOINT} with {params:?}");

    let response = reqwest::Client::new()
        .get(ENDPOINT)
        .query(&params)
        .send()
        .await
        .map_err(|e| ToolUseScenarioError(format!("Error requesting weather: {e:?}")))?
        .error_for_status()
        .map_err(|e| ToolUseScenarioError(format!("Failed to request weather: {e:?}")))?;

    debug!("Response: {response:?}");

    let bytes = response
        .bytes()
        .await
        .map_err(|e| ToolUseScenarioError(format!("Error reading response: {e:?}")))?;

    let result = String::from_utf8(bytes.to_vec())
        .map_err(|_| ToolUseScenarioError("Response was not utf8".into()))?;

    Ok(ToolResultBlock::builder()
        .tool_use_id(tool_use.tool_use_id())
        .content(ToolResultContentBlock::Text(result))
        .build()?)
}
```
メッセージコンテンツブロックを出力するユーティリティ。  

```
fn print_model_response(block: &ContentBlock) -> Result<(), ToolUseScenarioError> {
    if block.is_text() {
        let text = block.as_text().unwrap();
        println!("\x1b[0;90mThe model's response:\x1b[0m\n{text}");
        Ok(())
    } else {
        Err(ToolUseScenarioError(format!(
            "Content block is not text ({block:?})"
        )))
    }
}
```
ステートメント、エラーユーティリティ、定数を使用します。  

```
use std::{collections::HashMap, io::stdin};

use aws_config::BehaviorVersion;
use aws_sdk_bedrockruntime::{
    error::{BuildError, SdkError},
    operation::converse::{ConverseError, ConverseOutput},
    types::{
        ContentBlock, ConversationRole::User, Message, StopReason, SystemContentBlock, Tool,
        ToolConfiguration, ToolInputSchema, ToolResultBlock, ToolResultContentBlock,
        ToolSpecification, ToolUseBlock,
    },
    Client,
};
use aws_smithy_runtime_api::http::Response;
use aws_smithy_types::Document;
use tracing::debug;

// Set the model ID, e.g., Claude 3 Haiku.
const MODEL_ID: &str = "anthropic.claude-3-haiku-20240307-v1:0";
const CLAUDE_REGION: &str = "us-east-1";

const SYSTEM_PROMPT: &str = "You are a weather assistant that provides current weather data for user-specified locations using only
the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
If the user provides coordinates, infer the approximate location and refer to it in your response.
To use the tool, you strictly apply the provided tool specification.

- Explain your step-by-step process, and give brief updates before each step.
- Only use the Weather_Tool for data. Never guess or make up information. 
- Repeat the tool use for subsequent requests if necessary.
- If the tool errors, apologize, explain weather is unavailable, and suggest other options.
- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
  emojis where appropriate.
- Only respond to weather queries. Remind off-topic users of your purpose. 
- Never claim to search online, access external data, or use tools besides Weather_Tool.
- Complete the entire process until you have all required data before sending the complete response.
";

// The maximum number of recursive calls allowed in the tool_use_demo function.
// This helps prevent infinite loops and potential performance issues.
const MAX_RECURSIONS: i8 = 5;

const TOOL_NAME: &str = "Weather_Tool";
const TOOL_DESCRIPTION: &str =
    "Get the current weather for a given location, based on its WGS84 coordinates.";
fn make_tool_schema() -> Document {
    Document::Object(HashMap::<String, Document>::from([
        ("type".into(), Document::String("object".into())),
        (
            "properties".into(),
            Document::Object(HashMap::from([
                (
                    "latitude".into(),
                    Document::Object(HashMap::from([
                        ("type".into(), Document::String("string".into())),
                        (
                            "description".into(),
                            Document::String("Geographical WGS84 latitude of the location.".into()),
                        ),
                    ])),
                ),
                (
                    "longitude".into(),
                    Document::Object(HashMap::from([
                        ("type".into(), Document::String("string".into())),
                        (
                            "description".into(),
                            Document::String(
                                "Geographical WGS84 longitude of the location.".into(),
                            ),
                        ),
                    ])),
                ),
            ])),
        ),
        (
            "required".into(),
            Document::Array(vec![
                Document::String("latitude".into()),
                Document::String("longitude".into()),
            ]),
        ),
    ]))
}

#[derive(Debug)]
struct ToolUseScenarioError(String);
impl std::fmt::Display for ToolUseScenarioError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Tool use error with '{}'. Reason: {}", MODEL_ID, self.0)
    }
}
impl From<&str> for ToolUseScenarioError {
    fn from(value: &str) -> Self {
        ToolUseScenarioError(value.into())
    }
}
impl From<BuildError> for ToolUseScenarioError {
    fn from(value: BuildError) -> Self {
        ToolUseScenarioError(value.to_string().clone())
    }
}
impl From<SdkError<ConverseError, Response>> for ToolUseScenarioError {
    fn from(value: SdkError<ConverseError, Response>) -> Self {
        ToolUseScenarioError(match value.as_service_error() {
            Some(value) => value.meta().message().unwrap_or("Unknown").into(),
            None => "Unknown".into(),
        })
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[Converse](https://docs.rs/aws-sdk-bedrockruntime/latest/aws_sdk_bedrockruntime/client/struct.Client.html#method.converse)」を参照してください。

## Anthropic Claude
<a name="anthropic_claude"></a>

### Converse
<a name="bedrock-runtime_Converse_AnthropicClaude_rust_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。  

```
#[tokio::main]
async fn main() -> Result<(), BedrockConverseError> {
    tracing_subscriber::fmt::init();
    let sdk_config = aws_config::defaults(BehaviorVersion::latest())
        .region(CLAUDE_REGION)
        .load()
        .await;
    let client = Client::new(&sdk_config);

    let response = client
        .converse()
        .model_id(MODEL_ID)
        .messages(
            Message::builder()
                .role(ConversationRole::User)
                .content(ContentBlock::Text(USER_MESSAGE.to_string()))
                .build()
                .map_err(|_| "failed to build message")?,
        )
        .send()
        .await;

    match response {
        Ok(output) => {
            let text = get_converse_output_text(output)?;
            println!("{}", text);
            Ok(())
        }
        Err(e) => Err(e
            .as_service_error()
            .map(BedrockConverseError::from)
            .unwrap_or_else(|| BedrockConverseError("Unknown service error".into()))),
    }
}

fn get_converse_output_text(output: ConverseOutput) -> Result<String, BedrockConverseError> {
    let text = output
        .output()
        .ok_or("no output")?
        .as_message()
        .map_err(|_| "output not a message")?
        .content()
        .first()
        .ok_or("no content in message")?
        .as_text()
        .map_err(|_| "content is not text")?
        .to_string();
    Ok(text)
}
```
ステートメント、エラーユーティリティ、定数を使用します。  

```
use aws_config::BehaviorVersion;
use aws_sdk_bedrockruntime::{
    operation::converse::{ConverseError, ConverseOutput},
    types::{ContentBlock, ConversationRole, Message},
    Client,
};

// Set the model ID, e.g., Claude 3 Haiku.
const MODEL_ID: &str = "anthropic.claude-3-haiku-20240307-v1:0";
const CLAUDE_REGION: &str = "us-east-1";

// Start a conversation with the user message.
const USER_MESSAGE: &str = "Describe the purpose of a 'hello world' program in one line.";

#[derive(Debug)]
struct BedrockConverseError(String);
impl std::fmt::Display for BedrockConverseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Can't invoke '{}'. Reason: {}", MODEL_ID, self.0)
    }
}
impl std::error::Error for BedrockConverseError {}
impl From<&str> for BedrockConverseError {
    fn from(value: &str) -> Self {
        BedrockConverseError(value.to_string())
    }
}
impl From<&ConverseError> for BedrockConverseError {
    fn from(value: &ConverseError) -> Self {
        BedrockConverseError::from(match value {
            ConverseError::ModelTimeoutException(_) => "Model took too long",
            ConverseError::ModelNotReadyException(_) => "Model is not ready",
            _ => "Unknown",
        })
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[Converse](https://docs.rs/aws-sdk-bedrockruntime/latest/aws_sdk_bedrockruntime/client/struct.Client.html#method.converse)」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AnthropicClaude_rust_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の ConverseStream API を使用して、Anthropic Claude にテキストメッセージを送信し、返信トークンをストリーミングします。  

```
#[tokio::main]
async fn main() -> Result<(), BedrockConverseStreamError> {
    tracing_subscriber::fmt::init();
    let sdk_config = aws_config::defaults(BehaviorVersion::latest())
        .region(CLAUDE_REGION)
        .load()
        .await;
    let client = Client::new(&sdk_config);

    let response = client
        .converse_stream()
        .model_id(MODEL_ID)
        .messages(
            Message::builder()
                .role(ConversationRole::User)
                .content(ContentBlock::Text(USER_MESSAGE.to_string()))
                .build()
                .map_err(|_| "failed to build message")?,
        )
        .send()
        .await;

    let mut stream = match response {
        Ok(output) => Ok(output.stream),
        Err(e) => Err(BedrockConverseStreamError::from(
            e.as_service_error().unwrap(),
        )),
    }?;

    loop {
        let token = stream.recv().await;
        match token {
            Ok(Some(text)) => {
                let next = get_converse_output_text(text)?;
                print!("{}", next);
                Ok(())
            }
            Ok(None) => break,
            Err(e) => Err(e
                .as_service_error()
                .map(BedrockConverseStreamError::from)
                .unwrap_or(BedrockConverseStreamError(
                    "Unknown error receiving stream".into(),
                ))),
        }?
    }

    println!();

    Ok(())
}

fn get_converse_output_text(
    output: ConverseStreamOutputType,
) -> Result<String, BedrockConverseStreamError> {
    Ok(match output {
        ConverseStreamOutputType::ContentBlockDelta(event) => match event.delta() {
            Some(delta) => delta.as_text().cloned().unwrap_or_else(|_| "".into()),
            None => "".into(),
        },
        _ => "".into(),
    })
}
```
ステートメント、エラーユーティリティ、定数を使用します。  

```
use aws_config::BehaviorVersion;
use aws_sdk_bedrockruntime::{
    error::ProvideErrorMetadata,
    operation::converse_stream::ConverseStreamError,
    types::{
        error::ConverseStreamOutputError, ContentBlock, ConversationRole,
        ConverseStreamOutput as ConverseStreamOutputType, Message,
    },
    Client,
};

// Set the model ID, e.g., Claude 3 Haiku.
const MODEL_ID: &str = "anthropic.claude-3-haiku-20240307-v1:0";
const CLAUDE_REGION: &str = "us-east-1";

// Start a conversation with the user message.
const USER_MESSAGE: &str = "Describe the purpose of a 'hello world' program in one line.";

#[derive(Debug)]
struct BedrockConverseStreamError(String);
impl std::fmt::Display for BedrockConverseStreamError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Can't invoke '{}'. Reason: {}", MODEL_ID, self.0)
    }
}
impl std::error::Error for BedrockConverseStreamError {}
impl From<&str> for BedrockConverseStreamError {
    fn from(value: &str) -> Self {
        BedrockConverseStreamError(value.into())
    }
}

impl From<&ConverseStreamError> for BedrockConverseStreamError {
    fn from(value: &ConverseStreamError) -> Self {
        BedrockConverseStreamError(
            match value {
                ConverseStreamError::ModelTimeoutException(_) => "Model took too long",
                ConverseStreamError::ModelNotReadyException(_) => "Model is not ready",
                _ => "Unknown",
            }
            .into(),
        )
    }
}

impl From<&ConverseStreamOutputError> for BedrockConverseStreamError {
    fn from(value: &ConverseStreamOutputError) -> Self {
        match value {
            ConverseStreamOutputError::ValidationException(ve) => BedrockConverseStreamError(
                ve.message().unwrap_or("Unknown ValidationException").into(),
            ),
            ConverseStreamOutputError::ThrottlingException(te) => BedrockConverseStreamError(
                te.message().unwrap_or("Unknown ThrottlingException").into(),
            ),
            value => BedrockConverseStreamError(
                value
                    .message()
                    .unwrap_or("Unknown StreamOutput exception")
                    .into(),
            ),
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ConverseStream](https://docs.rs/aws-sdk-bedrockruntime/latest/aws_sdk_bedrockruntime/client/struct.Client.html#method.converse_stream)」を参照してください。

### シナリオ: Converse API でのツールの使用
<a name="bedrock-runtime_Scenario_ToolUseDemo_AnthropicClaude_rust_1_topic"></a>

次のコード例は、アプリケーション、生成 AI モデル、接続されたツールまたは API 間の一般的なインタラクションを構築し、AI と外部世界のインタラクションを仲介する方法を示しています。外部気象 API を AI モデルに接続する例を使用して、ユーザー入力に基づいてリアルタイムの気象情報を提供します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
デモのプライマリシナリオとロジック。これは、ユーザー、Amazon Bedrock Converse API、および気象ツール間の会話を調整します。  

```
#[derive(Debug)]
#[allow(dead_code)]
struct InvokeToolResult(String, ToolResultBlock);
struct ToolUseScenario {
    client: Client,
    conversation: Vec<Message>,
    system_prompt: SystemContentBlock,
    tool_config: ToolConfiguration,
}

impl ToolUseScenario {
    fn new(client: Client) -> Self {
        let system_prompt = SystemContentBlock::Text(SYSTEM_PROMPT.into());
        let tool_config = ToolConfiguration::builder()
            .tools(Tool::ToolSpec(
                ToolSpecification::builder()
                    .name(TOOL_NAME)
                    .description(TOOL_DESCRIPTION)
                    .input_schema(ToolInputSchema::Json(make_tool_schema()))
                    .build()
                    .unwrap(),
            ))
            .build()
            .unwrap();

        ToolUseScenario {
            client,
            conversation: vec![],
            system_prompt,
            tool_config,
        }
    }

    async fn run(&mut self) -> Result<(), ToolUseScenarioError> {
        loop {
            let input = get_input().await?;
            if input.is_none() {
                break;
            }

            let message = Message::builder()
                .role(User)
                .content(ContentBlock::Text(input.unwrap()))
                .build()
                .map_err(ToolUseScenarioError::from)?;
            self.conversation.push(message);

            let response = self.send_to_bedrock().await?;

            self.process_model_response(response).await?;
        }

        Ok(())
    }

    async fn send_to_bedrock(&mut self) -> Result<ConverseOutput, ToolUseScenarioError> {
        debug!("Sending conversation to bedrock");
        self.client
            .converse()
            .model_id(MODEL_ID)
            .set_messages(Some(self.conversation.clone()))
            .system(self.system_prompt.clone())
            .tool_config(self.tool_config.clone())
            .send()
            .await
            .map_err(ToolUseScenarioError::from)
    }

    async fn process_model_response(
        &mut self,
        mut response: ConverseOutput,
    ) -> Result<(), ToolUseScenarioError> {
        let mut iteration = 0;

        while iteration < MAX_RECURSIONS {
            iteration += 1;
            let message = if let Some(ref output) = response.output {
                if output.is_message() {
                    Ok(output.as_message().unwrap().clone())
                } else {
                    Err(ToolUseScenarioError(
                        "Converse Output is not a message".into(),
                    ))
                }
            } else {
                Err(ToolUseScenarioError("Missing Converse Output".into()))
            }?;

            self.conversation.push(message.clone());

            match response.stop_reason {
                StopReason::ToolUse => {
                    response = self.handle_tool_use(&message).await?;
                }
                StopReason::EndTurn => {
                    print_model_response(&message.content[0])?;
                    return Ok(());
                }
                _ => (),
            }
        }

        Err(ToolUseScenarioError(
            "Exceeded MAX_ITERATIONS when calling tools".into(),
        ))
    }

    async fn handle_tool_use(
        &mut self,
        message: &Message,
    ) -> Result<ConverseOutput, ToolUseScenarioError> {
        let mut tool_results: Vec<ContentBlock> = vec![];

        for block in &message.content {
            match block {
                ContentBlock::Text(_) => print_model_response(block)?,
                ContentBlock::ToolUse(tool) => {
                    let tool_response = self.invoke_tool(tool).await?;
                    tool_results.push(ContentBlock::ToolResult(tool_response.1));
                }
                _ => (),
            };
        }

        let message = Message::builder()
            .role(User)
            .set_content(Some(tool_results))
            .build()?;
        self.conversation.push(message);

        self.send_to_bedrock().await
    }

    async fn invoke_tool(
        &mut self,
        tool: &ToolUseBlock,
    ) -> Result<InvokeToolResult, ToolUseScenarioError> {
        match tool.name() {
            TOOL_NAME => {
                println!(
                    "\x1b[0;90mExecuting tool: {TOOL_NAME} with input: {:?}...\x1b[0m",
                    tool.input()
                );
                let content = fetch_weather_data(tool).await?;
                println!(
                    "\x1b[0;90mTool responded with {:?}\x1b[0m",
                    content.content()
                );
                Ok(InvokeToolResult(tool.tool_use_id.clone(), content))
            }
            _ => Err(ToolUseScenarioError(format!(
                "The requested tool with name {} does not exist",
                tool.name()
            ))),
        }
    }
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let sdk_config = aws_config::defaults(BehaviorVersion::latest())
        .region(CLAUDE_REGION)
        .load()
        .await;
    let client = Client::new(&sdk_config);

    let mut scenario = ToolUseScenario::new(client);

    header();
    if let Err(err) = scenario.run().await {
        println!("There was an error running the scenario! {}", err.0)
    }
    footer();
}
```
デモで使用される気象ツール。このスクリプトは、ツールの仕様を定義し、Open-Meteo API を使用して気象データを取得するロジックを実装します。  

```
const ENDPOINT: &str = "https://api.open-meteo.com/v1/forecast";
async fn fetch_weather_data(
    tool_use: &ToolUseBlock,
) -> Result<ToolResultBlock, ToolUseScenarioError> {
    let input = tool_use.input();
    let latitude = input
        .as_object()
        .unwrap()
        .get("latitude")
        .unwrap()
        .as_string()
        .unwrap();
    let longitude = input
        .as_object()
        .unwrap()
        .get("longitude")
        .unwrap()
        .as_string()
        .unwrap();
    let params = [
        ("latitude", latitude),
        ("longitude", longitude),
        ("current_weather", "true"),
    ];

    debug!("Calling {ENDPOINT} with {params:?}");

    let response = reqwest::Client::new()
        .get(ENDPOINT)
        .query(&params)
        .send()
        .await
        .map_err(|e| ToolUseScenarioError(format!("Error requesting weather: {e:?}")))?
        .error_for_status()
        .map_err(|e| ToolUseScenarioError(format!("Failed to request weather: {e:?}")))?;

    debug!("Response: {response:?}");

    let bytes = response
        .bytes()
        .await
        .map_err(|e| ToolUseScenarioError(format!("Error reading response: {e:?}")))?;

    let result = String::from_utf8(bytes.to_vec())
        .map_err(|_| ToolUseScenarioError("Response was not utf8".into()))?;

    Ok(ToolResultBlock::builder()
        .tool_use_id(tool_use.tool_use_id())
        .content(ToolResultContentBlock::Text(result))
        .build()?)
}
```
メッセージコンテンツブロックを出力するユーティリティ。  

```
fn print_model_response(block: &ContentBlock) -> Result<(), ToolUseScenarioError> {
    if block.is_text() {
        let text = block.as_text().unwrap();
        println!("\x1b[0;90mThe model's response:\x1b[0m\n{text}");
        Ok(())
    } else {
        Err(ToolUseScenarioError(format!(
            "Content block is not text ({block:?})"
        )))
    }
}
```
ステートメント、エラーユーティリティ、定数を使用します。  

```
use std::{collections::HashMap, io::stdin};

use aws_config::BehaviorVersion;
use aws_sdk_bedrockruntime::{
    error::{BuildError, SdkError},
    operation::converse::{ConverseError, ConverseOutput},
    types::{
        ContentBlock, ConversationRole::User, Message, StopReason, SystemContentBlock, Tool,
        ToolConfiguration, ToolInputSchema, ToolResultBlock, ToolResultContentBlock,
        ToolSpecification, ToolUseBlock,
    },
    Client,
};
use aws_smithy_runtime_api::http::Response;
use aws_smithy_types::Document;
use tracing::debug;

// Set the model ID, e.g., Claude 3 Haiku.
const MODEL_ID: &str = "anthropic.claude-3-haiku-20240307-v1:0";
const CLAUDE_REGION: &str = "us-east-1";

const SYSTEM_PROMPT: &str = "You are a weather assistant that provides current weather data for user-specified locations using only
the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself.
If the user provides coordinates, infer the approximate location and refer to it in your response.
To use the tool, you strictly apply the provided tool specification.

- Explain your step-by-step process, and give brief updates before each step.
- Only use the Weather_Tool for data. Never guess or make up information. 
- Repeat the tool use for subsequent requests if necessary.
- If the tool errors, apologize, explain weather is unavailable, and suggest other options.
- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use
  emojis where appropriate.
- Only respond to weather queries. Remind off-topic users of your purpose. 
- Never claim to search online, access external data, or use tools besides Weather_Tool.
- Complete the entire process until you have all required data before sending the complete response.
";

// The maximum number of recursive calls allowed in the tool_use_demo function.
// This helps prevent infinite loops and potential performance issues.
const MAX_RECURSIONS: i8 = 5;

const TOOL_NAME: &str = "Weather_Tool";
const TOOL_DESCRIPTION: &str =
    "Get the current weather for a given location, based on its WGS84 coordinates.";
fn make_tool_schema() -> Document {
    Document::Object(HashMap::<String, Document>::from([
        ("type".into(), Document::String("object".into())),
        (
            "properties".into(),
            Document::Object(HashMap::from([
                (
                    "latitude".into(),
                    Document::Object(HashMap::from([
                        ("type".into(), Document::String("string".into())),
                        (
                            "description".into(),
                            Document::String("Geographical WGS84 latitude of the location.".into()),
                        ),
                    ])),
                ),
                (
                    "longitude".into(),
                    Document::Object(HashMap::from([
                        ("type".into(), Document::String("string".into())),
                        (
                            "description".into(),
                            Document::String(
                                "Geographical WGS84 longitude of the location.".into(),
                            ),
                        ),
                    ])),
                ),
            ])),
        ),
        (
            "required".into(),
            Document::Array(vec![
                Document::String("latitude".into()),
                Document::String("longitude".into()),
            ]),
        ),
    ]))
}

#[derive(Debug)]
struct ToolUseScenarioError(String);
impl std::fmt::Display for ToolUseScenarioError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Tool use error with '{}'. Reason: {}", MODEL_ID, self.0)
    }
}
impl From<&str> for ToolUseScenarioError {
    fn from(value: &str) -> Self {
        ToolUseScenarioError(value.into())
    }
}
impl From<BuildError> for ToolUseScenarioError {
    fn from(value: BuildError) -> Self {
        ToolUseScenarioError(value.to_string().clone())
    }
}
impl From<SdkError<ConverseError, Response>> for ToolUseScenarioError {
    fn from(value: SdkError<ConverseError, Response>) -> Self {
        ToolUseScenarioError(match value.as_service_error() {
            Some(value) => value.meta().message().unwrap_or("Unknown").into(),
            None => "Unknown".into(),
        })
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[Converse](https://docs.rs/aws-sdk-bedrockruntime/latest/aws_sdk_bedrockruntime/client/struct.Client.html#method.converse)」を参照してください。

# SDK for Rust を使用する Amazon Bedrock エージェントランタイムの例
<a name="rust_1_bedrock-agent-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock エージェントランタイムで AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `InvokeAgent`
<a name="bedrock-agent-runtime_InvokeAgent_rust_1_topic"></a>

次のコード例は、`InvokeAgent` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/bedrock-agent-runtime#code-examples)での設定と実行の方法を確認してください。

```
use aws_config::{BehaviorVersion, SdkConfig};
use aws_sdk_bedrockagentruntime::{
    self as bedrockagentruntime,
    types::{error::ResponseStreamError, ResponseStream},
};
#[allow(unused_imports)]
use mockall::automock;

const BEDROCK_AGENT_ID: &str = "AJBHXXILZN";
const BEDROCK_AGENT_ALIAS_ID: &str = "AVKP1ITZAA";
const BEDROCK_AGENT_REGION: &str = "us-east-1";

#[cfg(not(test))]
pub use EventReceiverImpl as EventReceiver;
#[cfg(test)]
pub use MockEventReceiverImpl as EventReceiver;

pub struct EventReceiverImpl {
    inner: aws_sdk_bedrockagentruntime::primitives::event_stream::EventReceiver<
        ResponseStream,
        ResponseStreamError,
    >,
}

#[cfg_attr(test, automock)]
impl EventReceiverImpl {
    #[allow(dead_code)]
    pub fn new(
        inner: aws_sdk_bedrockagentruntime::primitives::event_stream::EventReceiver<
            ResponseStream,
            ResponseStreamError,
        >,
    ) -> Self {
        Self { inner }
    }

    pub async fn recv(
        &mut self,
    ) -> Result<
        Option<ResponseStream>,
        aws_sdk_bedrockagentruntime::error::SdkError<
            ResponseStreamError,
            aws_smithy_types::event_stream::RawMessage,
        >,
    > {
        self.inner.recv().await
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<bedrockagentruntime::Error>> {
    let result = invoke_bedrock_agent("I need help.".to_string(), "123".to_string()).await?;
    println!("{}", result);
    Ok(())
}

async fn invoke_bedrock_agent(
    prompt: String,
    session_id: String,
) -> Result<String, bedrockagentruntime::Error> {
    let sdk_config: SdkConfig = aws_config::defaults(BehaviorVersion::latest())
        .region(BEDROCK_AGENT_REGION)
        .load()
        .await;
    let bedrock_client = bedrockagentruntime::Client::new(&sdk_config);

    let command_builder = bedrock_client
        .invoke_agent()
        .agent_id(BEDROCK_AGENT_ID)
        .agent_alias_id(BEDROCK_AGENT_ALIAS_ID)
        .session_id(session_id)
        .input_text(prompt);

    let response = command_builder.send().await?;

    let response_stream = response.completion;

    let event_receiver = EventReceiver::new(response_stream);

    process_agent_response_stream(event_receiver).await
}

async fn process_agent_response_stream(
    mut event_receiver: EventReceiver,
) -> Result<String, bedrockagentruntime::Error> {
    let mut full_agent_text_response = String::new();

    while let Some(event_result) = event_receiver.recv().await? {
        match event_result {
            ResponseStream::Chunk(chunk) => {
                if let Some(bytes) = chunk.bytes {
                    match String::from_utf8(bytes.into_inner()) {
                        Ok(text_chunk) => {
                            full_agent_text_response.push_str(&text_chunk);
                        }
                        Err(e) => {
                            eprintln!("UTF-8 decoding error for chunk: {}", e);
                        }
                    }
                }
            }
            _ => {
                panic!("received an unhandled event type from Bedrock stream",);
            }
        }
    }
    Ok(full_agent_text_response)
}

#[cfg(test)]
mod test {

    use super::*;

    #[tokio::test]
    async fn test_process_agent_response_stream() {
        let mut mock = MockEventReceiverImpl::default();
        mock.expect_recv().times(1).returning(|| {
            Ok(Some(
                aws_sdk_bedrockagentruntime::types::ResponseStream::Chunk(
                    aws_sdk_bedrockagentruntime::types::PayloadPart::builder()
                        .set_bytes(Some(aws_smithy_types::Blob::new(vec![
                            116, 101, 115, 116, 32, 99, 111, 109, 112, 108, 101, 116, 105, 111, 110,
                        ])))
                        .build(),
                ),
            ))
        });

        // end the stream
        mock.expect_recv().times(1).returning(|| Ok(None));

        let response = process_agent_response_stream(mock).await.unwrap();

        assert_eq!("test completion", response);
    }

    #[tokio::test]
    #[should_panic(expected = "received an unhandled event type from Bedrock stream")]
    async fn test_process_agent_response_stream_error() {
        let mut mock = MockEventReceiverImpl::default();
        mock.expect_recv().times(1).returning(|| {
            Ok(Some(
                aws_sdk_bedrockagentruntime::types::ResponseStream::Trace(
                    aws_sdk_bedrockagentruntime::types::TracePart::builder().build(),
                ),
            ))
        });

        let _ = process_agent_response_stream(mock).await.unwrap();
    }
}
```
+  API の詳細については、AWS SDK for Rust API リファレンスの**「[InvokeAgent](https://docs.rs/aws-sdk-bedrockagentruntime/latest/aws_sdk_bedrockagentruntime/client/struct.Client.html#method.invoke_agent)」を参照してください。

# SDK for Rust を使用する Amazon Cognito ID プロバイダーの例
<a name="rust_1_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListUserPools`
<a name="cognito-identity-provider_ListUserPools_rust_1_topic"></a>

次のコード例は、`ListUserPools` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/cognitoidentityprovider#code-examples)での設定と実行の方法を確認してください。

```
async fn show_pools(client: &Client) -> Result<(), Error> {
    let response = client.list_user_pools().max_results(10).send().await?;
    let pools = response.user_pools();
    println!("User pools:");
    for pool in pools {
        println!("  ID:              {}", pool.id().unwrap_or_default());
        println!("  Name:            {}", pool.name().unwrap_or_default());
        println!("  Lambda Config:   {:?}", pool.lambda_config().unwrap());
        println!(
            "  Last modified:   {}",
            pool.last_modified_date().unwrap().to_chrono_utc()?
        );
        println!(
            "  Creation date:   {:?}",
            pool.creation_date().unwrap().to_chrono_utc()
        );
        println!();
    }
    println!("Next token: {}", response.next_token().unwrap_or_default());

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListUserPools](https://docs.rs/aws-sdk-cognitoidentityprovider/latest/aws_sdk_cognitoidentityprovider/client/struct.Client.html#method.list_user_pools)」を参照してください。

# SDK for Rust を使用した Amazon Cognito Sync のコード例
<a name="rust_1_cognito-sync_code_examples"></a>

次のコード例は、Amazon Cognito Sync で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListIdentityPoolUsage`
<a name="cognito-sync_ListIdentityPoolUsage_rust_1_topic"></a>

次のコード例は、`ListIdentityPoolUsage` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/cognitosync#code-examples)での設定と実行の方法を確認してください。

```
async fn show_pools(client: &Client) -> Result<(), Error> {
    let response = client
        .list_identity_pool_usage()
        .max_results(10)
        .send()
        .await?;

    let pools = response.identity_pool_usages();
    println!("Identity pools:");

    for pool in pools {
        println!(
            "  Identity pool ID:    {}",
            pool.identity_pool_id().unwrap_or_default()
        );
        println!(
            "  Data storage:        {}",
            pool.data_storage().unwrap_or_default()
        );
        println!(
            "  Sync sessions count: {}",
            pool.sync_sessions_count().unwrap_or_default()
        );
        println!(
            "  Last modified:       {}",
            pool.last_modified_date().unwrap().to_chrono_utc()?
        );
        println!();
    }

    println!("Next token: {}", response.next_token().unwrap_or_default());

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListIdentityPoolUsage](https://docs.rs/aws-sdk-cognitosync/latest/aws_sdk_cognitosync/client/struct.Client.html#method.list_identity_pool_usage)」を参照してください。

# SDK for Rust を使用する Firehose の例
<a name="rust_1_firehose_code_examples"></a>

次のコード例は、Firehose で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutRecordBatch`
<a name="firehose_PutRecordBatch_rust_1_topic"></a>

次のコード例は、`PutRecordBatch` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/firehose#code-examples)での設定と実行の方法を確認してください。

```
async fn put_record_batch(
    client: &Client,
    stream: &str,
    data: Vec<Record>,
) -> Result<PutRecordBatchOutput, SdkError<PutRecordBatchError>> {
    client
        .put_record_batch()
        .delivery_stream_name(stream)
        .set_records(Some(data))
        .send()
        .await
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[PutRecordBatch](https://docs.rs/aws-sdk-firehose/latest/aws_sdk_firehose/client/struct.Client.html#method.put_record_batch)」を参照してください。

# SDK for Rust を使用した Amazon DocumentDB の例
<a name="rust_1_docdb_code_examples"></a>

次のコード例は、Amazon DocumentDB で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_rust_1_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
use lambda_runtime::{service_fn, tracing, Error, LambdaEvent};
use aws_lambda_events::{
    event::documentdb::{DocumentDbEvent, DocumentDbInnerEvent},
   };


// Built with the following dependencies:
//lambda_runtime = "0.11.1"
//serde_json = "1.0"
//tokio = { version = "1", features = ["macros"] }
//tracing = { version = "0.1", features = ["log"] }
//tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }
//aws_lambda_events = "0.15.0"

async fn function_handler(event: LambdaEvent<DocumentDbEvent>) ->Result<(), Error> {
    
    tracing::info!("Event Source ARN: {:?}", event.payload.event_source_arn);
    tracing::info!("Event Source: {:?}", event.payload.event_source);
  
    let records = &event.payload.events;
   
    if records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(());
    }

    for record in records{
        log_document_db_event(record);
    }

    tracing::info!("Document db records processed");

    // Prepare the response
    Ok(())

}

fn log_document_db_event(record: &DocumentDbInnerEvent)-> Result<(), Error>{
    tracing::info!("Change Event: {:?}", record.event);
    
    Ok(())

}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
    .with_max_level(tracing::Level::INFO)
    .with_target(false)
    .without_time()
    .init();

    let func = service_fn(function_handler);
    lambda_runtime::run(func).await?;
    Ok(())
    
}
```

# SDK for Rust を使用した DynamoDB の例
<a name="rust_1_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## アクション
<a name="actions"></a>

### `CreateTable`
<a name="dynamodb_CreateTable_rust_1_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
pub async fn create_table(
    client: &Client,
    table: &str,
    key: &str,
) -> Result<CreateTableOutput, Error> {
    let a_name: String = key.into();
    let table_name: String = table.into();

    let ad = AttributeDefinition::builder()
        .attribute_name(&a_name)
        .attribute_type(ScalarAttributeType::S)
        .build()
        .map_err(Error::BuildError)?;

    let ks = KeySchemaElement::builder()
        .attribute_name(&a_name)
        .key_type(KeyType::Hash)
        .build()
        .map_err(Error::BuildError)?;

    let create_table_response = client
        .create_table()
        .table_name(table_name)
        .key_schema(ks)
        .attribute_definitions(ad)
        .billing_mode(BillingMode::PayPerRequest)
        .send()
        .await;

    match create_table_response {
        Ok(out) => {
            println!("Added table {} with key {}", table, key);
            Ok(out)
        }
        Err(e) => {
            eprintln!("Got an error creating table:");
            eprintln!("{}", e);
            Err(Error::unhandled(e))
        }
    }
}
```
+  API の詳細については、**「AWS SDK for Rust API リファレンス」の「[CreateTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.create_table)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_rust_1_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_item(
    client: &Client,
    table: &str,
    key: &str,
    value: &str,
) -> Result<DeleteItemOutput, Error> {
    match client
        .delete_item()
        .table_name(table)
        .key(key, AttributeValue::S(value.into()))
        .send()
        .await
    {
        Ok(out) => {
            println!("Deleted item from table");
            Ok(out)
        }
        Err(e) => Err(Error::unhandled(e)),
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteItem](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.delete_item)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_rust_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_table(client: &Client, table: &str) -> Result<DeleteTableOutput, Error> {
    let resp = client.delete_table().table_name(table).send().await;

    match resp {
        Ok(out) => {
            println!("Deleted table");
            Ok(out)
        }
        Err(e) => Err(Error::Unhandled(e.into())),
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteTable](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.delete_table)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_rust_1_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_tables(client: &Client) -> Result<Vec<String>, Error> {
    let paginator = client.list_tables().into_paginator().items().send();
    let table_names = paginator.collect::<Result<Vec<_>, _>>().await?;

    println!("Tables:");

    for name in &table_names {
        println!("  {}", name);
    }

    println!("Found {} tables", table_names.len());
    Ok(table_names)
}
```
テーブルが存在するかどうかを確認します。  

```
pub async fn table_exists(client: &Client, table: &str) -> Result<bool, Error> {
    debug!("Checking for table: {table}");
    let table_list = client.list_tables().send().await;

    match table_list {
        Ok(list) => Ok(list.table_names().contains(&table.into())),
        Err(e) => Err(e.into()),
    }
}
```
+  API の詳細については、「AWS SDK for Rust API リファレンス」の「[ListTables](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.list_tables)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_rust_1_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
pub async fn add_item(client: &Client, item: Item, table: &String) -> Result<ItemOut, Error> {
    let user_av = AttributeValue::S(item.username);
    let type_av = AttributeValue::S(item.p_type);
    let age_av = AttributeValue::S(item.age);
    let first_av = AttributeValue::S(item.first);
    let last_av = AttributeValue::S(item.last);

    let request = client
        .put_item()
        .table_name(table)
        .item("username", user_av)
        .item("account_type", type_av)
        .item("age", age_av)
        .item("first_name", first_av)
        .item("last_name", last_av);

    println!("Executing request [{request:?}] to add item...");

    let resp = request.send().await?;

    let attributes = resp.attributes().unwrap();

    let username = attributes.get("username").cloned();
    let first_name = attributes.get("first_name").cloned();
    let last_name = attributes.get("last_name").cloned();
    let age = attributes.get("age").cloned();
    let p_type = attributes.get("p_type").cloned();

    println!(
        "Added user {:?}, {:?} {:?}, age {:?} as {:?} user",
        username, first_name, last_name, age, p_type
    );

    Ok(ItemOut {
        p_type,
        age,
        username,
        first_name,
        last_name,
    })
}
```
+  API の詳細については、「AWS SDK for Rust API リファレンス」の「[PutItem](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.put_item)」を参照してください。

### `Query`
<a name="dynamodb_Query_rust_1_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。
指定した年に作られた映画を検索します。  

```
pub async fn movies_in_year(
    client: &Client,
    table_name: &str,
    year: u16,
) -> Result<Vec<Movie>, MovieError> {
    let results = client
        .query()
        .table_name(table_name)
        .key_condition_expression("#yr = :yyyy")
        .expression_attribute_names("#yr", "year")
        .expression_attribute_values(":yyyy", AttributeValue::N(year.to_string()))
        .send()
        .await?;

    if let Some(items) = results.items {
        let movies = items.iter().map(|v| v.into()).collect();
        Ok(movies)
    } else {
        Ok(vec![])
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[Query](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.query)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_rust_1_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_items(client: &Client, table: &str, page_size: Option<i32>) -> Result<(), Error> {
    let page_size = page_size.unwrap_or(10);
    let items: Result<Vec<_>, _> = client
        .scan()
        .table_name(table)
        .limit(page_size)
        .into_paginator()
        .items()
        .send()
        .collect()
        .await;

    println!("Items in table (up to {page_size}):");
    for item in items? {
        println!("   {:?}", item);
    }

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[Scan](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.scan)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ローカルインスタンスに接続する
<a name="dynamodb_local_rust_1_topic"></a>

次のコード例は、エンドポイント URL を上書きして DynamoDB と AWS SDK のローカル開発デプロイに接続する方法を示しています。

詳細については、「[DynamoDB Local](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBLocal.html)」を参照してください。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
/// Lists your tables from a local DynamoDB instance by setting the SDK Config's
/// endpoint_url and test_credentials.
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let config = aws_config::defaults(aws_config::BehaviorVersion::latest())
        .test_credentials()
        // DynamoDB run locally uses port 8000 by default.
        .endpoint_url("http://localhost:8000")
        .load()
        .await;
    let dynamodb_local_config = aws_sdk_dynamodb::config::Builder::from(&config).build();

    let client = aws_sdk_dynamodb::Client::from_conf(dynamodb_local_config);

    let list_resp = client.list_tables().send().await;
    match list_resp {
        Ok(resp) => {
            println!("Found {} tables", resp.table_names().len());
            for name in resp.table_names() {
                println!("  {}", name);
            }
        }
        Err(err) => eprintln!("Failed to list local dynamodb tables: {err:?}"),
    }
}
```

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_rust_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Rust**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/cross_service/photo_asset_management) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### PartiQL を使用してテーブルに対してクエリを実行する
<a name="dynamodb_Scenario_PartiQLSingle_rust_1_topic"></a>

次のコードサンプルは、以下の操作方法を示しています。
+ SELECT ステートメントを実行して項目を取得します。
+ INSERT 文を実行して項目を追加する。
+ UPDATE ステートメントを使用して項目を更新する。
+ DELETE ステートメントを実行して項目を削除します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
async fn make_table(
    client: &Client,
    table: &str,
    key: &str,
) -> Result<(), SdkError<CreateTableError>> {
    let ad = AttributeDefinition::builder()
        .attribute_name(key)
        .attribute_type(ScalarAttributeType::S)
        .build()
        .expect("creating AttributeDefinition");

    let ks = KeySchemaElement::builder()
        .attribute_name(key)
        .key_type(KeyType::Hash)
        .build()
        .expect("creating KeySchemaElement");

    match client
        .create_table()
        .table_name(table)
        .key_schema(ks)
        .attribute_definitions(ad)
        .billing_mode(BillingMode::PayPerRequest)
        .send()
        .await
    {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}

async fn add_item(client: &Client, item: Item) -> Result<(), SdkError<ExecuteStatementError>> {
    match client
        .execute_statement()
        .statement(format!(
            r#"INSERT INTO "{}" VALUE {{
                "{}": ?,
                "acount_type": ?,
                "age": ?,
                "first_name": ?,
                "last_name": ?
        }} "#,
            item.table, item.key
        ))
        .set_parameters(Some(vec![
            AttributeValue::S(item.utype),
            AttributeValue::S(item.age),
            AttributeValue::S(item.first_name),
            AttributeValue::S(item.last_name),
        ]))
        .send()
        .await
    {
        Ok(_) => Ok(()),
        Err(e) => Err(e),
    }
}

async fn query_item(client: &Client, item: Item) -> bool {
    match client
        .execute_statement()
        .statement(format!(
            r#"SELECT * FROM "{}" WHERE "{}" = ?"#,
            item.table, item.key
        ))
        .set_parameters(Some(vec![AttributeValue::S(item.value)]))
        .send()
        .await
    {
        Ok(resp) => {
            if !resp.items().is_empty() {
                println!("Found a matching entry in the table:");
                println!("{:?}", resp.items.unwrap_or_default().pop());
                true
            } else {
                println!("Did not find a match.");
                false
            }
        }
        Err(e) => {
            println!("Got an error querying table:");
            println!("{}", e);
            process::exit(1);
        }
    }
}

async fn remove_item(client: &Client, table: &str, key: &str, value: String) -> Result<(), Error> {
    client
        .execute_statement()
        .statement(format!(r#"DELETE FROM "{table}" WHERE "{key}" = ?"#))
        .set_parameters(Some(vec![AttributeValue::S(value)]))
        .send()
        .await?;

    println!("Deleted item.");

    Ok(())
}

async fn remove_table(client: &Client, table: &str) -> Result<(), Error> {
    client.delete_table().table_name(table).send().await?;

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ExecuteStatement](https://docs.rs/aws-sdk-dynamodb/latest/aws_sdk_dynamodb/client/struct.Client.html#method.execute_statement)」を参照してください。

### EXIF およびその他のイメージ情報を保存します
<a name="cross_DetectLabels_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ JPG、JPEG、または PNG ファイルから EXIF 情報を取得します。
+ Amazon S3 バケットにイメージファイルをアップロードします。
+ Amazon Rekognition を使用して、ファイル内の 3 つの上位属性 (ラベル) を特定します。
+ EXIF およびラベル情報を、リージョンの Amazon DynamoDB テーブルに追加します。

**SDK for Rust**  
 JPG、JPEG、または PNG ファイルから EXIF 情報を取得し、イメージファイルを Amazon S3 バケットにアップロードし、Amazon Rekognition を使用してファイル内の 3 つの上位属性 (Amazon Rekognition の*ラベル*) を特定し、リージョンの Amazon DynamoDB テーブルに EXIF およびラベル情報を追加します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service/detect_labels/src/main.rs) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon Rekognition
+ Amazon S3

## サーバーレスサンプル
<a name="serverless_examples"></a>

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_rust_1_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で DynamoDB イベントを利用します。  

```
use lambda_runtime::{service_fn, tracing, Error, LambdaEvent};
use aws_lambda_events::{
    event::dynamodb::{Event, EventRecord},
   };


// Built with the following dependencies:
//lambda_runtime = "0.11.1"
//serde_json = "1.0"
//tokio = { version = "1", features = ["macros"] }
//tracing = { version = "0.1", features = ["log"] }
//tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }
//aws_lambda_events = "0.15.0"

async fn function_handler(event: LambdaEvent<Event>) ->Result<(), Error> {
    
    let records = &event.payload.records;
    tracing::info!("event payload: {:?}",records);
    if records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(());
    }

    for record in records{
        log_dynamo_dbrecord(record);
    }

    tracing::info!("Dynamo db records processed");

    // Prepare the response
    Ok(())

}

fn log_dynamo_dbrecord(record: &EventRecord)-> Result<(), Error>{
    tracing::info!("EventId: {}", record.event_id);
    tracing::info!("EventName: {}", record.event_name);
    tracing::info!("DynamoDB Record: {:?}", record.change );
    Ok(())

}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
    .with_max_level(tracing::Level::INFO)
    .with_target(false)
    .without_time()
    .init();

    let func = service_fn(function_handler);
    lambda_runtime::run(func).await?;
    Ok(())
    
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_rust_1_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
use aws_lambda_events::{
    event::dynamodb::{Event, EventRecord, StreamRecord},
    streams::{DynamoDbBatchItemFailure, DynamoDbEventResponse},
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

/// Process the stream record
fn process_record(record: &EventRecord) -> Result<(), Error> {
    let stream_record: &StreamRecord = &record.change;

    // process your stream record here...
    tracing::info!("Data: {:?}", stream_record);

    Ok(())
}

/// Main Lambda handler here...
async fn function_handler(event: LambdaEvent<Event>) -> Result<DynamoDbEventResponse, Error> {
    let mut response = DynamoDbEventResponse {
        batch_item_failures: vec![],
    };

    let records = &event.payload.records;

    if records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(response);
    }

    for record in records {
        tracing::info!("EventId: {}", record.event_id);

        // Couldn't find a sequence number
        if record.change.sequence_number.is_none() {
            response.batch_item_failures.push(DynamoDbBatchItemFailure {
                item_identifier: Some("".to_string()),
            });
            return Ok(response);
        }

        // Process your record here...
        if process_record(record).is_err() {
            response.batch_item_failures.push(DynamoDbBatchItemFailure {
                item_identifier: record.change.sequence_number.clone(),
            });
            /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
            return Ok(response);
        }
    }

    tracing::info!("Successfully processed {} record(s)", records.len());

    Ok(response)
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_rust_1_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Rust**  
 Rust SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-rust-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Rust を使用した Amazon EBS の例
<a name="rust_1_ebs_code_examples"></a>

次のコード例は、Amazon EBS で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CompleteSnapshot`
<a name="ebs_CompleteSnapshot_rust_1_topic"></a>

次のコード例は、`CompleteSnapshot` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ebs#code-examples)での設定と実行の方法を確認してください。

```
async fn finish(client: &Client, id: &str) -> Result<(), Error> {
    client
        .complete_snapshot()
        .changed_blocks_count(2)
        .snapshot_id(id)
        .send()
        .await?;

    println!("Snapshot ID {}", id);
    println!("The state is 'completed' when all of the modified blocks have been transferred to Amazon S3.");
    println!("Use the get-snapshot-state code example to get the state of the snapshot.");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CompleteSnapshot](https://docs.rs/aws-sdk-ebs/latest/aws_sdk_ebs/client/struct.Client.html#method.complete_snapshot)」を参照してください。

### `PutSnapshotBlock`
<a name="ebs_PutSnapshotBlock_rust_1_topic"></a>

次のコード例は、`PutSnapshotBlock` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ebs#code-examples)での設定と実行の方法を確認してください。

```
async fn add_block(
    client: &Client,
    id: &str,
    idx: usize,
    block: Vec<u8>,
    checksum: &str,
) -> Result<(), Error> {
    client
        .put_snapshot_block()
        .snapshot_id(id)
        .block_index(idx as i32)
        .block_data(ByteStream::from(block))
        .checksum(checksum)
        .checksum_algorithm(ChecksumAlgorithm::ChecksumAlgorithmSha256)
        .data_length(EBS_BLOCK_SIZE as i32)
        .send()
        .await?;

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[PutSnapshotBlock](https://docs.rs/aws-sdk-ebs/latest/aws_sdk_ebs/client/struct.Client.html#method.put_snapshot_block)」を参照してください。

### `StartSnapshot`
<a name="ebs_StartSnapshot_rust_1_topic"></a>

次のコード例は、`StartSnapshot` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ebs#code-examples)での設定と実行の方法を確認してください。

```
async fn start(client: &Client, description: &str) -> Result<String, Error> {
    let snapshot = client
        .start_snapshot()
        .description(description)
        .encrypted(false)
        .volume_size(1)
        .send()
        .await?;

    Ok(snapshot.snapshot_id.unwrap())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[StartSnapshot](https://docs.rs/aws-sdk-ebs/latest/aws_sdk_ebs/client/struct.Client.html#method.start_snapshot)」を参照してください。

# SDK for Rust を使用した Amazon EC2 の例
<a name="rust_1_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_rust_1_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
async fn show_security_groups(client: &aws_sdk_ec2::Client, group_ids: Vec<String>) {
    let response = client
        .describe_security_groups()
        .set_group_ids(Some(group_ids))
        .send()
        .await;

    match response {
        Ok(output) => {
            for group in output.security_groups() {
                println!(
                    "Found Security Group {} ({}), vpc id {} and description {}",
                    group.group_name().unwrap_or("unknown"),
                    group.group_id().unwrap_or("id-unknown"),
                    group.vpc_id().unwrap_or("vpcid-unknown"),
                    group.description().unwrap_or("(none)")
                );
            }
        }
        Err(err) => {
            let err = err.into_service_error();
            let meta = err.meta();
            let message = meta.message().unwrap_or("unknown");
            let code = meta.code().unwrap_or("unknown");
            eprintln!("Error listing EC2 Security Groups: ({code}) {message}");
        }
    }
}
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DescribeSecurityGroups](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_security_groups)」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。
EC2InstanceScenario 実装には、例全体を実行するロジックが含まれています。  

```
//! Scenario that uses the AWS SDK for Rust (the SDK) with Amazon Elastic Compute Cloud
//! (Amazon EC2) to do the following:
//!
//! * Create a key pair that is used to secure SSH communication between your computer and
//!   an EC2 instance.
//! * Create a security group that acts as a virtual firewall for your EC2 instances to
//!   control incoming and outgoing traffic.
//! * Find an Amazon Machine Image (AMI) and a compatible instance type.
//! * Create an instance that is created from the instance type and AMI you select, and
//!   is configured to use the security group and key pair created in this example.
//! * Stop and restart the instance.
//! * Create an Elastic IP address and associate it as a consistent IP address for your instance.
//! * Connect to your instance with SSH, using both its public IP address and your Elastic IP
//!   address.
//! * Clean up all of the resources created by this example.

use std::net::Ipv4Addr;

use crate::{
    ec2::{EC2Error, EC2},
    getting_started::{key_pair::KeyPairManager, util::Util},
    ssm::SSM,
};
use aws_sdk_ssm::types::Parameter;

use super::{
    elastic_ip::ElasticIpManager, instance::InstanceManager, security_group::SecurityGroupManager,
    util::ScenarioImage,
};

pub struct Ec2InstanceScenario {
    ec2: EC2,
    ssm: SSM,
    util: Util,
    key_pair_manager: KeyPairManager,
    security_group_manager: SecurityGroupManager,
    instance_manager: InstanceManager,
    elastic_ip_manager: ElasticIpManager,
}

impl Ec2InstanceScenario {
    pub fn new(ec2: EC2, ssm: SSM, util: Util) -> Self {
        Ec2InstanceScenario {
            ec2,
            ssm,
            util,
            key_pair_manager: Default::default(),
            security_group_manager: Default::default(),
            instance_manager: Default::default(),
            elastic_ip_manager: Default::default(),
        }
    }

    pub async fn run(&mut self) -> Result<(), EC2Error> {
        self.create_and_list_key_pairs().await?;
        self.create_security_group().await?;
        self.create_instance().await?;
        self.stop_and_start_instance().await?;
        self.associate_elastic_ip().await?;
        self.stop_and_start_instance().await?;
        Ok(())
    }

    /// 1. Creates an RSA key pair and saves its private key data as a .pem file in secure
    ///    temporary storage. The private key data is deleted after the example completes.
    /// 2. Optionally, lists the first five key pairs for the current account.
    pub async fn create_and_list_key_pairs(&mut self) -> Result<(), EC2Error> {
        println!( "Let's create an RSA key pair that you can be use to securely connect to your EC2 instance.");

        let key_name = self.util.prompt_key_name()?;

        self.key_pair_manager
            .create(&self.ec2, &self.util, key_name)
            .await?;

        println!(
            "Created a key pair {} and saved the private key to {:?}.",
            self.key_pair_manager
                .key_pair()
                .key_name()
                .ok_or_else(|| EC2Error::new("No key name after creating key"))?,
            self.key_pair_manager
                .key_file_path()
                .ok_or_else(|| EC2Error::new("No key file after creating key"))?
        );

        if self.util.should_list_key_pairs()? {
            for pair in self.key_pair_manager.list(&self.ec2).await? {
                println!(
                    "Found {:?} key {} with fingerprint:\t{:?}",
                    pair.key_type(),
                    pair.key_name().unwrap_or("Unknown"),
                    pair.key_fingerprint()
                );
            }
        }

        Ok(())
    }

    /// 1. Creates a security group for the default VPC.
    /// 2. Adds an inbound rule to allow SSH. The SSH rule allows only
    ///    inbound traffic from the current computer’s public IPv4 address.
    /// 3. Displays information about the security group.
    ///
    /// This function uses <http://checkip.amazonaws.com> to get the current public IP
    /// address of the computer that is running the example. This method works in most
    /// cases. However, depending on how your computer connects to the internet, you
    /// might have to manually add your public IP address to the security group by using
    /// the AWS Management Console.
    pub async fn create_security_group(&mut self) -> Result<(), EC2Error> {
        println!("Let's create a security group to manage access to your instance.");
        let group_name = self.util.prompt_security_group_name()?;

        self.security_group_manager
            .create(
                &self.ec2,
                &group_name,
                "Security group for example: get started with instances.",
            )
            .await?;

        println!(
            "Created security group {} in your default VPC {}.",
            self.security_group_manager.group_name(),
            self.security_group_manager
                .vpc_id()
                .unwrap_or("(unknown vpc)")
        );

        let check_ip = self.util.do_get("https://checkip.amazonaws.com").await?;
        let current_ip_address: Ipv4Addr = check_ip.trim().parse().map_err(|e| {
            EC2Error::new(format!(
                "Failed to convert response {} to IP Address: {e:?}",
                check_ip
            ))
        })?;

        println!("Your public IP address seems to be {current_ip_address}");
        if self.util.should_add_to_security_group() {
            match self
                .security_group_manager
                .authorize_ingress(&self.ec2, current_ip_address)
                .await
            {
                Ok(_) => println!("Security group rules updated"),
                Err(err) => eprintln!("Couldn't update security group rules: {err:?}"),
            }
        }
        println!("{}", self.security_group_manager);

        Ok(())
    }

    /// 1. Gets a list of Amazon Linux 2 AMIs from AWS Systems Manager. Specifying the
    ///    '/aws/service/ami-amazon-linux-latest' path returns only the latest AMIs.
    /// 2. Gets and displays information about the available AMIs and lets you select one.
    /// 3. Gets a list of instance types that are compatible with the selected AMI and
    ///    lets you select one.
    /// 4. Creates an instance with the previously created key pair and security group,
    ///    and the selected AMI and instance type.
    /// 5. Waits for the instance to be running and then displays its information.
    pub async fn create_instance(&mut self) -> Result<(), EC2Error> {
        let ami = self.find_image().await?;

        let instance_types = self
            .ec2
            .list_instance_types(&ami.0)
            .await
            .map_err(|e| e.add_message("Could not find instance types"))?;
        println!(
            "There are several instance types that support the {} architecture of the image.",
            ami.0
                .architecture
                .as_ref()
                .ok_or_else(|| EC2Error::new(format!("Missing architecture in {:?}", ami.0)))?
        );
        let instance_type = self.util.select_instance_type(instance_types)?;

        println!("Creating your instance and waiting for it to start...");
        self.instance_manager
            .create(
                &self.ec2,
                ami.0
                    .image_id()
                    .ok_or_else(|| EC2Error::new("Could not find image ID"))?,
                instance_type,
                self.key_pair_manager.key_pair(),
                self.security_group_manager
                    .security_group()
                    .map(|sg| vec![sg])
                    .ok_or_else(|| EC2Error::new("Could not find security group"))?,
            )
            .await
            .map_err(|e| e.add_message("Scenario failed to create instance"))?;

        while let Err(err) = self
            .ec2
            .wait_for_instance_ready(self.instance_manager.instance_id(), None)
            .await
        {
            println!("{err}");
            if !self.util.should_continue_waiting() {
                return Err(err);
            }
        }

        println!("Your instance is ready:\n{}", self.instance_manager);

        self.display_ssh_info();

        Ok(())
    }

    async fn find_image(&mut self) -> Result<ScenarioImage, EC2Error> {
        let params: Vec<Parameter> = self
            .ssm
            .list_path("/aws/service/ami-amazon-linux-latest")
            .await
            .map_err(|e| e.add_message("Could not find parameters for available images"))?
            .into_iter()
            .filter(|param| param.name().is_some_and(|name| name.contains("amzn2")))
            .collect();
        let amzn2_images: Vec<ScenarioImage> = self
            .ec2
            .list_images(params)
            .await
            .map_err(|e| e.add_message("Could not find images"))?
            .into_iter()
            .map(ScenarioImage::from)
            .collect();
        println!("We will now create an instance from an Amazon Linux 2 AMI");
        let ami = self.util.select_scenario_image(amzn2_images)?;
        Ok(ami)
    }

    // 1. Stops the instance and waits for it to stop.
    // 2. Starts the instance and waits for it to start.
    // 3. Displays information about the instance.
    // 4. Displays an SSH connection string. When an Elastic IP address is associated
    //    with the instance, the IP address stays consistent when the instance stops
    //    and starts.
    pub async fn stop_and_start_instance(&self) -> Result<(), EC2Error> {
        println!("Let's stop and start your instance to see what changes.");
        println!("Stopping your instance and waiting until it's stopped...");
        self.instance_manager.stop(&self.ec2).await?;
        println!("Your instance is stopped. Restarting...");
        self.instance_manager.start(&self.ec2).await?;
        println!("Your instance is running.");
        println!("{}", self.instance_manager);
        if self.elastic_ip_manager.public_ip() == "0.0.0.0" {
            println!("Every time your instance is restarted, its public IP address changes.");
        } else {
            println!(
                "Because you have associated an Elastic IP with your instance, you can connect by using a consistent IP address after the instance restarts."
            );
        }
        self.display_ssh_info();
        Ok(())
    }

    /// 1. Allocates an Elastic IP address and associates it with the instance.
    /// 2. Displays an SSH connection string that uses the Elastic IP address.
    async fn associate_elastic_ip(&mut self) -> Result<(), EC2Error> {
        self.elastic_ip_manager.allocate(&self.ec2).await?;
        println!(
            "Allocated static Elastic IP address: {}",
            self.elastic_ip_manager.public_ip()
        );

        self.elastic_ip_manager
            .associate(&self.ec2, self.instance_manager.instance_id())
            .await?;
        println!("Associated your Elastic IP with your instance.");
        println!("You can now use SSH to connect to your instance by using the Elastic IP.");
        self.display_ssh_info();
        Ok(())
    }

    /// Displays an SSH connection string that can be used to connect to a running
    /// instance.
    fn display_ssh_info(&self) {
        let ip_addr = if self.elastic_ip_manager.has_allocation() {
            self.elastic_ip_manager.public_ip()
        } else {
            self.instance_manager.instance_ip()
        };
        let key_file_path = self.key_pair_manager.key_file_path().unwrap();
        println!("To connect, open another command prompt and run the following command:");
        println!("\nssh -i {} ec2-user@{ip_addr}\n", key_file_path.display());
        let _ = self.util.enter_to_continue();
    }

    /// 1. Disassociate and delete the previously created Elastic IP.
    /// 2. Terminate the previously created instance.
    /// 3. Delete the previously created security group.
    /// 4. Delete the previously created key pair.
    pub async fn clean_up(self) {
        println!("Let's clean everything up. This example created these resources:");
        println!(
            "\tKey pair: {}",
            self.key_pair_manager
                .key_pair()
                .key_name()
                .unwrap_or("(unknown key pair)")
        );
        println!(
            "\tSecurity group: {}",
            self.security_group_manager.group_name()
        );
        println!(
            "\tInstance: {}",
            self.instance_manager.instance_display_name()
        );
        if self.util.should_clean_resources() {
            if let Err(err) = self.elastic_ip_manager.remove(&self.ec2).await {
                eprintln!("{err}")
            }
            if let Err(err) = self.instance_manager.delete(&self.ec2).await {
                eprintln!("{err}")
            }
            if let Err(err) = self.security_group_manager.delete(&self.ec2).await {
                eprintln!("{err}");
            }
            if let Err(err) = self.key_pair_manager.delete(&self.ec2, &self.util).await {
                eprintln!("{err}");
            }
        } else {
            println!("Ok, not cleaning up any resources!");
        }
    }
}

pub async fn run(mut scenario: Ec2InstanceScenario) {
    println!("--------------------------------------------------------------------------------");
    println!(
        "Welcome to the Amazon Elastic Compute Cloud (Amazon EC2) get started with instances demo."
    );
    println!("--------------------------------------------------------------------------------");

    if let Err(err) = scenario.run().await {
        eprintln!("There was an error running the scenario: {err}")
    }

    println!("--------------------------------------------------------------------------------");

    scenario.clean_up().await;

    println!("Thanks for running!");
    println!("--------------------------------------------------------------------------------");
}
```
EC2Impl 構造体はテスト用の自動モックポイントとして機能し、その関数は EC2 SDK 呼び出しをラップします。  

```
use std::{net::Ipv4Addr, time::Duration};

use aws_sdk_ec2::{
    client::Waiters,
    error::ProvideErrorMetadata,
    operation::{
        allocate_address::AllocateAddressOutput, associate_address::AssociateAddressOutput,
    },
    types::{
        DomainType, Filter, Image, Instance, InstanceType, IpPermission, IpRange, KeyPairInfo,
        SecurityGroup, Tag,
    },
    Client as EC2Client,
};
use aws_sdk_ssm::types::Parameter;
use aws_smithy_runtime_api::client::waiters::error::WaiterError;

#[cfg(test)]
use mockall::automock;

#[cfg(not(test))]
pub use EC2Impl as EC2;

#[cfg(test)]
pub use MockEC2Impl as EC2;

#[derive(Clone)]
pub struct EC2Impl {
    pub client: EC2Client,
}

#[cfg_attr(test, automock)]
impl EC2Impl {
    pub fn new(client: EC2Client) -> Self {
        EC2Impl { client }
    }

    pub async fn create_key_pair(&self, name: String) -> Result<(KeyPairInfo, String), EC2Error> {
        tracing::info!("Creating key pair {name}");
        let output = self.client.create_key_pair().key_name(name).send().await?;
        let info = KeyPairInfo::builder()
            .set_key_name(output.key_name)
            .set_key_fingerprint(output.key_fingerprint)
            .set_key_pair_id(output.key_pair_id)
            .build();
        let material = output
            .key_material
            .ok_or_else(|| EC2Error::new("Create Key Pair has no key material"))?;
        Ok((info, material))
    }

    pub async fn list_key_pair(&self) -> Result<Vec<KeyPairInfo>, EC2Error> {
        let output = self.client.describe_key_pairs().send().await?;
        Ok(output.key_pairs.unwrap_or_default())
    }

    pub async fn delete_key_pair(&self, key_name: &str) -> Result<(), EC2Error> {
        let key_name: String = key_name.into();
        tracing::info!("Deleting key pair {key_name}");
        self.client
            .delete_key_pair()
            .key_name(key_name)
            .send()
            .await?;
        Ok(())
    }

    pub async fn create_security_group(
        &self,
        name: &str,
        description: &str,
    ) -> Result<SecurityGroup, EC2Error> {
        tracing::info!("Creating security group {name}");
        let create_output = self
            .client
            .create_security_group()
            .group_name(name)
            .description(description)
            .send()
            .await
            .map_err(EC2Error::from)?;

        let group_id = create_output
            .group_id
            .ok_or_else(|| EC2Error::new("Missing security group id after creation"))?;

        let group = self
            .describe_security_group(&group_id)
            .await?
            .ok_or_else(|| {
                EC2Error::new(format!("Could not find security group with id {group_id}"))
            })?;

        tracing::info!("Created security group {name} as {group_id}");

        Ok(group)
    }

    /// Find a single security group, by ID. Returns Err if multiple groups are found.
    pub async fn describe_security_group(
        &self,
        group_id: &str,
    ) -> Result<Option<SecurityGroup>, EC2Error> {
        let group_id: String = group_id.into();
        let describe_output = self
            .client
            .describe_security_groups()
            .group_ids(&group_id)
            .send()
            .await?;

        let mut groups = describe_output.security_groups.unwrap_or_default();

        match groups.len() {
            0 => Ok(None),
            1 => Ok(Some(groups.remove(0))),
            _ => Err(EC2Error::new(format!(
                "Expected single group for {group_id}"
            ))),
        }
    }

    /// Add an ingress rule to a security group explicitly allowing IPv4 address
    /// as {ip}/32 over TCP port 22.
    pub async fn authorize_security_group_ssh_ingress(
        &self,
        group_id: &str,
        ingress_ips: Vec<Ipv4Addr>,
    ) -> Result<(), EC2Error> {
        tracing::info!("Authorizing ingress for security group {group_id}");
        self.client
            .authorize_security_group_ingress()
            .group_id(group_id)
            .set_ip_permissions(Some(
                ingress_ips
                    .into_iter()
                    .map(|ip| {
                        IpPermission::builder()
                            .ip_protocol("tcp")
                            .from_port(22)
                            .to_port(22)
                            .ip_ranges(IpRange::builder().cidr_ip(format!("{ip}/32")).build())
                            .build()
                    })
                    .collect(),
            ))
            .send()
            .await?;
        Ok(())
    }

    pub async fn delete_security_group(&self, group_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Deleting security group {group_id}");
        self.client
            .delete_security_group()
            .group_id(group_id)
            .send()
            .await?;
        Ok(())
    }

    pub async fn list_images(&self, ids: Vec<Parameter>) -> Result<Vec<Image>, EC2Error> {
        let image_ids = ids.into_iter().filter_map(|p| p.value).collect();
        let output = self
            .client
            .describe_images()
            .set_image_ids(Some(image_ids))
            .send()
            .await?;

        let images = output.images.unwrap_or_default();
        if images.is_empty() {
            Err(EC2Error::new("No images for selected AMIs"))
        } else {
            Ok(images)
        }
    }

    /// List instance types that match an image's architecture and are free tier eligible.
    pub async fn list_instance_types(&self, image: &Image) -> Result<Vec<InstanceType>, EC2Error> {
        let architecture = format!(
            "{}",
            image.architecture().ok_or_else(|| EC2Error::new(format!(
                "Image {:?} does not have a listed architecture",
                image.image_id()
            )))?
        );
        let free_tier_eligible_filter = Filter::builder()
            .name("free-tier-eligible")
            .values("false")
            .build();
        let supported_architecture_filter = Filter::builder()
            .name("processor-info.supported-architecture")
            .values(architecture)
            .build();
        let response = self
            .client
            .describe_instance_types()
            .filters(free_tier_eligible_filter)
            .filters(supported_architecture_filter)
            .send()
            .await?;

        Ok(response
            .instance_types
            .unwrap_or_default()
            .into_iter()
            .filter_map(|iti| iti.instance_type)
            .collect())
    }

    pub async fn create_instance<'a>(
        &self,
        image_id: &'a str,
        instance_type: InstanceType,
        key_pair: &'a KeyPairInfo,
        security_groups: Vec<&'a SecurityGroup>,
    ) -> Result<String, EC2Error> {
        let run_instances = self
            .client
            .run_instances()
            .image_id(image_id)
            .instance_type(instance_type)
            .key_name(
                key_pair
                    .key_name()
                    .ok_or_else(|| EC2Error::new("Missing key name when launching instance"))?,
            )
            .set_security_group_ids(Some(
                security_groups
                    .iter()
                    .filter_map(|sg| sg.group_id.clone())
                    .collect(),
            ))
            .min_count(1)
            .max_count(1)
            .send()
            .await?;

        if run_instances.instances().is_empty() {
            return Err(EC2Error::new("Failed to create instance"));
        }

        let instance_id = run_instances.instances()[0].instance_id().unwrap();
        let response = self
            .client
            .create_tags()
            .resources(instance_id)
            .tags(
                Tag::builder()
                    .key("Name")
                    .value("From SDK Examples")
                    .build(),
            )
            .send()
            .await;

        match response {
            Ok(_) => tracing::info!("Created {instance_id} and applied tags."),
            Err(err) => {
                tracing::info!("Error applying tags to {instance_id}: {err:?}");
                return Err(err.into());
            }
        }

        tracing::info!("Instance is created.");

        Ok(instance_id.to_string())
    }

    /// Wait for an instance to be ready and status ok (default wait 60 seconds)
    pub async fn wait_for_instance_ready(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_status_ok()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to start.",
                    exceeded.max_wait().as_secs()
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }

    pub async fn describe_instance(&self, instance_id: &str) -> Result<Instance, EC2Error> {
        let response = self
            .client
            .describe_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        let instance = response
            .reservations()
            .first()
            .ok_or_else(|| EC2Error::new(format!("No instance reservations for {instance_id}")))?
            .instances()
            .first()
            .ok_or_else(|| {
                EC2Error::new(format!("No instances in reservation for {instance_id}"))
            })?;

        Ok(instance.clone())
    }

    pub async fn start_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Starting instance {instance_id}");

        self.client
            .start_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        tracing::info!("Started instance.");

        Ok(())
    }

    pub async fn stop_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Stopping instance {instance_id}");

        self.client
            .stop_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        self.wait_for_instance_stopped(instance_id, None).await?;

        tracing::info!("Stopped instance.");

        Ok(())
    }

    pub async fn reboot_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Rebooting instance {instance_id}");

        self.client
            .reboot_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        Ok(())
    }

    pub async fn wait_for_instance_stopped(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_stopped()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to stop.",
                    exceeded.max_wait().as_secs(),
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }

    pub async fn delete_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Deleting instance with id {instance_id}");
        self.stop_instance(instance_id).await?;
        self.client
            .terminate_instances()
            .instance_ids(instance_id)
            .send()
            .await?;
        self.wait_for_instance_terminated(instance_id).await?;
        tracing::info!("Terminated instance with id {instance_id}");
        Ok(())
    }

    async fn wait_for_instance_terminated(&self, instance_id: &str) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_terminated()
            .instance_ids(instance_id)
            .wait(Duration::from_secs(60))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to terminate.",
                    exceeded.max_wait().as_secs(),
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }

    pub async fn allocate_ip_address(&self) -> Result<AllocateAddressOutput, EC2Error> {
        self.client
            .allocate_address()
            .domain(DomainType::Vpc)
            .send()
            .await
            .map_err(EC2Error::from)
    }

    pub async fn deallocate_ip_address(&self, allocation_id: &str) -> Result<(), EC2Error> {
        self.client
            .release_address()
            .allocation_id(allocation_id)
            .send()
            .await?;
        Ok(())
    }

    pub async fn associate_ip_address(
        &self,
        allocation_id: &str,
        instance_id: &str,
    ) -> Result<AssociateAddressOutput, EC2Error> {
        let response = self
            .client
            .associate_address()
            .allocation_id(allocation_id)
            .instance_id(instance_id)
            .send()
            .await?;
        Ok(response)
    }

    pub async fn disassociate_ip_address(&self, association_id: &str) -> Result<(), EC2Error> {
        self.client
            .disassociate_address()
            .association_id(association_id)
            .send()
            .await?;
        Ok(())
    }
}

#[derive(Debug)]
pub struct EC2Error(String);
impl EC2Error {
    pub fn new(value: impl Into<String>) -> Self {
        EC2Error(value.into())
    }

    pub fn add_message(self, message: impl Into<String>) -> Self {
        EC2Error(format!("{}: {}", message.into(), self.0))
    }
}

impl<T: ProvideErrorMetadata> From<T> for EC2Error {
    fn from(value: T) -> Self {
        EC2Error(format!(
            "{}: {}",
            value
                .code()
                .map(String::from)
                .unwrap_or("unknown code".into()),
            value
                .message()
                .map(String::from)
                .unwrap_or("missing reason".into()),
        ))
    }
}

impl std::error::Error for EC2Error {}

impl std::fmt::Display for EC2Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}
```
SSM 構造体はテスト用の自動モックポイントとして機能し、その関数は SSM SDK 呼び出しをラップします。  

```
use aws_sdk_ssm::{types::Parameter, Client};
use aws_smithy_async::future::pagination_stream::TryFlatMap;

use crate::ec2::EC2Error;

#[cfg(test)]
use mockall::automock;

#[cfg(not(test))]
pub use SSMImpl as SSM;

#[cfg(test)]
pub use MockSSMImpl as SSM;

pub struct SSMImpl {
    inner: Client,
}

#[cfg_attr(test, automock)]
impl SSMImpl {
    pub fn new(inner: Client) -> Self {
        SSMImpl { inner }
    }

    pub async fn list_path(&self, path: &str) -> Result<Vec<Parameter>, EC2Error> {
        let maybe_params: Vec<Result<Parameter, _>> = TryFlatMap::new(
            self.inner
                .get_parameters_by_path()
                .path(path)
                .into_paginator()
                .send(),
        )
        .flat_map(|item| item.parameters.unwrap_or_default())
        .collect()
        .await;
        // Fail on the first error
        let params = maybe_params
            .into_iter()
            .collect::<Result<Vec<Parameter>, _>>()?;
        Ok(params)
    }
}
```
このシナリオでは、シナリオ全体を通じて作成および削除されるリソースへのアクセスを管理するために、複数の「Manager」スタイルの構造体が使用されています。  

```
use aws_sdk_ec2::operation::{
    allocate_address::AllocateAddressOutput, associate_address::AssociateAddressOutput,
};

use crate::ec2::{EC2Error, EC2};

/// ElasticIpManager tracks the lifecycle of a public IP address, including its
/// allocation from the global pool and association with a specific instance.
#[derive(Debug, Default)]
pub struct ElasticIpManager {
    elastic_ip: Option<AllocateAddressOutput>,
    association: Option<AssociateAddressOutput>,
}

impl ElasticIpManager {
    pub fn has_allocation(&self) -> bool {
        self.elastic_ip.is_some()
    }

    pub fn public_ip(&self) -> &str {
        if let Some(allocation) = &self.elastic_ip {
            if let Some(addr) = allocation.public_ip() {
                return addr;
            }
        }
        "0.0.0.0"
    }

    pub async fn allocate(&mut self, ec2: &EC2) -> Result<(), EC2Error> {
        let allocation = ec2.allocate_ip_address().await?;
        self.elastic_ip = Some(allocation);
        Ok(())
    }

    pub async fn associate(&mut self, ec2: &EC2, instance_id: &str) -> Result<(), EC2Error> {
        if let Some(allocation) = &self.elastic_ip {
            if let Some(allocation_id) = allocation.allocation_id() {
                let association = ec2.associate_ip_address(allocation_id, instance_id).await?;
                self.association = Some(association);
                return Ok(());
            }
        }
        Err(EC2Error::new("No ip address allocation to associate"))
    }

    pub async fn remove(mut self, ec2: &EC2) -> Result<(), EC2Error> {
        if let Some(association) = &self.association {
            if let Some(association_id) = association.association_id() {
                ec2.disassociate_ip_address(association_id).await?;
            }
        }
        self.association = None;
        if let Some(allocation) = &self.elastic_ip {
            if let Some(allocation_id) = allocation.allocation_id() {
                ec2.deallocate_ip_address(allocation_id).await?;
            }
        }
        self.elastic_ip = None;
        Ok(())
    }
}


use std::fmt::Display;

use aws_sdk_ec2::types::{Instance, InstanceType, KeyPairInfo, SecurityGroup};

use crate::ec2::{EC2Error, EC2};

/// InstanceManager wraps the lifecycle of an EC2 Instance.
#[derive(Debug, Default)]
pub struct InstanceManager {
    instance: Option<Instance>,
}

impl InstanceManager {
    pub fn instance_id(&self) -> &str {
        if let Some(instance) = &self.instance {
            if let Some(id) = instance.instance_id() {
                return id;
            }
        }
        "Unknown"
    }

    pub fn instance_name(&self) -> &str {
        if let Some(instance) = &self.instance {
            if let Some(tag) = instance.tags().iter().find(|e| e.key() == Some("Name")) {
                if let Some(value) = tag.value() {
                    return value;
                }
            }
        }
        "Unknown"
    }

    pub fn instance_ip(&self) -> &str {
        if let Some(instance) = &self.instance {
            if let Some(public_ip_address) = instance.public_ip_address() {
                return public_ip_address;
            }
        }
        "0.0.0.0"
    }

    pub fn instance_display_name(&self) -> String {
        format!("{} ({})", self.instance_name(), self.instance_id())
    }

    /// Create an EC2 instance with the given ID on a given type, using a
    /// generated KeyPair and applying a list of security groups.
    pub async fn create(
        &mut self,
        ec2: &EC2,
        image_id: &str,
        instance_type: InstanceType,
        key_pair: &KeyPairInfo,
        security_groups: Vec<&SecurityGroup>,
    ) -> Result<(), EC2Error> {
        let instance_id = ec2
            .create_instance(image_id, instance_type, key_pair, security_groups)
            .await?;
        let instance = ec2.describe_instance(&instance_id).await?;
        self.instance = Some(instance);
        Ok(())
    }

    /// Start the managed EC2 instance, if present.
    pub async fn start(&self, ec2: &EC2) -> Result<(), EC2Error> {
        if self.instance.is_some() {
            ec2.start_instance(self.instance_id()).await?;
        }
        Ok(())
    }

    /// Stop the managed EC2 instance, if present.
    pub async fn stop(&self, ec2: &EC2) -> Result<(), EC2Error> {
        if self.instance.is_some() {
            ec2.stop_instance(self.instance_id()).await?;
        }
        Ok(())
    }

    pub async fn reboot(&self, ec2: &EC2) -> Result<(), EC2Error> {
        if self.instance.is_some() {
            ec2.reboot_instance(self.instance_id()).await?;
            ec2.wait_for_instance_stopped(self.instance_id(), None)
                .await?;
            ec2.wait_for_instance_ready(self.instance_id(), None)
                .await?;
        }
        Ok(())
    }

    /// Terminate and delete the managed EC2 instance, if present.
    pub async fn delete(self, ec2: &EC2) -> Result<(), EC2Error> {
        if self.instance.is_some() {
            ec2.delete_instance(self.instance_id()).await?;
        }
        Ok(())
    }
}

impl Display for InstanceManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(instance) = &self.instance {
            writeln!(f, "\tID: {}", instance.instance_id().unwrap_or("(Unknown)"))?;
            writeln!(
                f,
                "\tImage ID: {}",
                instance.image_id().unwrap_or("(Unknown)")
            )?;
            writeln!(
                f,
                "\tInstance type: {}",
                instance
                    .instance_type()
                    .map(|it| format!("{it}"))
                    .unwrap_or("(Unknown)".to_string())
            )?;
            writeln!(
                f,
                "\tKey name: {}",
                instance.key_name().unwrap_or("(Unknown)")
            )?;
            writeln!(f, "\tVPC ID: {}", instance.vpc_id().unwrap_or("(Unknown)"))?;
            writeln!(
                f,
                "\tPublic IP: {}",
                instance.public_ip_address().unwrap_or("(Unknown)")
            )?;
            let instance_state = instance
                .state
                .as_ref()
                .map(|is| {
                    is.name()
                        .map(|isn| format!("{isn}"))
                        .unwrap_or("(Unknown)".to_string())
                })
                .unwrap_or("(Unknown)".to_string());
            writeln!(f, "\tState: {instance_state}")?;
        } else {
            writeln!(f, "\tNo loaded instance")?;
        }
        Ok(())
    }
}


use std::{env, path::PathBuf};

use aws_sdk_ec2::types::KeyPairInfo;

use crate::ec2::{EC2Error, EC2};

use super::util::Util;

/// KeyPairManager tracks a KeyPairInfo and the path the private key has been
/// written to, if it's been created.
#[derive(Debug)]
pub struct KeyPairManager {
    key_pair: KeyPairInfo,
    key_file_path: Option<PathBuf>,
    key_file_dir: PathBuf,
}

impl KeyPairManager {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn key_pair(&self) -> &KeyPairInfo {
        &self.key_pair
    }

    pub fn key_file_path(&self) -> Option<&PathBuf> {
        self.key_file_path.as_ref()
    }

    pub fn key_file_dir(&self) -> &PathBuf {
        &self.key_file_dir
    }

    /// Creates a key pair that can be used to securely connect to an EC2 instance.
    /// The returned key pair contains private key information that cannot be retrieved
    /// again. The private key data is stored as a .pem file.
    ///
    /// :param key_name: The name of the key pair to create.
    pub async fn create(
        &mut self,
        ec2: &EC2,
        util: &Util,
        key_name: String,
    ) -> Result<KeyPairInfo, EC2Error> {
        let (key_pair, material) = ec2.create_key_pair(key_name.clone()).await.map_err(|e| {
            self.key_pair = KeyPairInfo::builder().key_name(key_name.clone()).build();
            e.add_message(format!("Couldn't create key {key_name}"))
        })?;

        let path = self.key_file_dir.join(format!("{key_name}.pem"));

        // Save the key_pair information immediately, so it can get cleaned up if write_secure fails.
        self.key_file_path = Some(path.clone());
        self.key_pair = key_pair.clone();

        util.write_secure(&key_name, &path, material)?;

        Ok(key_pair)
    }

    pub async fn delete(self, ec2: &EC2, util: &Util) -> Result<(), EC2Error> {
        if let Some(key_name) = self.key_pair.key_name() {
            ec2.delete_key_pair(key_name).await?;
            if let Some(key_path) = self.key_file_path() {
                if let Err(err) = util.remove(key_path) {
                    eprintln!("Failed to remove {key_path:?} ({err:?})");
                }
            }
        }
        Ok(())
    }

    pub async fn list(&self, ec2: &EC2) -> Result<Vec<KeyPairInfo>, EC2Error> {
        ec2.list_key_pair().await
    }
}

impl Default for KeyPairManager {
    fn default() -> Self {
        KeyPairManager {
            key_pair: KeyPairInfo::builder().build(),
            key_file_path: Default::default(),
            key_file_dir: env::temp_dir(),
        }
    }
}


use std::net::Ipv4Addr;

use aws_sdk_ec2::types::SecurityGroup;

use crate::ec2::{EC2Error, EC2};

/// SecurityGroupManager tracks the lifecycle of a SecurityGroup for an instance,
/// including adding a rule to allow SSH from a public IP address.
#[derive(Debug, Default)]
pub struct SecurityGroupManager {
    group_name: String,
    group_description: String,
    security_group: Option<SecurityGroup>,
}

impl SecurityGroupManager {
    pub async fn create(
        &mut self,
        ec2: &EC2,
        group_name: &str,
        group_description: &str,
    ) -> Result<(), EC2Error> {
        self.group_name = group_name.into();
        self.group_description = group_description.into();

        self.security_group = Some(
            ec2.create_security_group(group_name, group_description)
                .await
                .map_err(|e| e.add_message("Couldn't create security group"))?,
        );

        Ok(())
    }

    pub async fn authorize_ingress(&self, ec2: &EC2, ip_address: Ipv4Addr) -> Result<(), EC2Error> {
        if let Some(sg) = &self.security_group {
            ec2.authorize_security_group_ssh_ingress(
                sg.group_id()
                    .ok_or_else(|| EC2Error::new("Missing security group ID"))?,
                vec![ip_address],
            )
            .await?;
        };

        Ok(())
    }

    pub async fn delete(self, ec2: &EC2) -> Result<(), EC2Error> {
        if let Some(sg) = &self.security_group {
            ec2.delete_security_group(
                sg.group_id()
                    .ok_or_else(|| EC2Error::new("Missing security group ID"))?,
            )
            .await?;
        };

        Ok(())
    }

    pub fn group_name(&self) -> &str {
        &self.group_name
    }

    pub fn vpc_id(&self) -> Option<&str> {
        self.security_group.as_ref().and_then(|sg| sg.vpc_id())
    }

    pub fn security_group(&self) -> Option<&SecurityGroup> {
        self.security_group.as_ref()
    }
}

impl std::fmt::Display for SecurityGroupManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.security_group {
            Some(sg) => {
                writeln!(
                    f,
                    "Security group: {}",
                    sg.group_name().unwrap_or("(unknown group)")
                )?;
                writeln!(f, "\tID: {}", sg.group_id().unwrap_or("(unknown group id)"))?;
                writeln!(f, "\tVPC: {}", sg.vpc_id().unwrap_or("(unknown group vpc)"))?;
                if !sg.ip_permissions().is_empty() {
                    writeln!(f, "\tInbound Permissions:")?;
                    for permission in sg.ip_permissions() {
                        writeln!(f, "\t\t{permission:?}")?;
                    }
                }
                Ok(())
            }
            None => writeln!(f, "No security group loaded."),
        }
    }
}
```
シナリオの主なエントリポイント。  

```
use ec2_code_examples::{
    ec2::EC2,
    getting_started::{
        scenario::{run, Ec2InstanceScenario},
        util::UtilImpl,
    },
    ssm::SSM,
};

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();
    let sdk_config = aws_config::load_from_env().await;
    let ec2 = EC2::new(aws_sdk_ec2::Client::new(&sdk_config));
    let ssm = SSM::new(aws_sdk_ssm::Client::new(&sdk_config));
    let util = UtilImpl {};
    let scenario = Ec2InstanceScenario::new(ec2, ssm, util);
    run(scenario).await;
}
```
+ API の詳細については、「*AWS SDK for Rust API リファレンス*」の以下のトピックを参照してください。
  + [AllocateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.allocate_address)
  + [AssociateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.associate_address)
  + [AuthorizeSecurityGroupIngress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.authorize_security_group_ingress)
  + [CreateKeyPair](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_key_pair)
  + [CreateSecurityGroup](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_security_group)
  + [DeleteKeyPair](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_key_pair)
  + [DeleteSecurityGroup](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_security_group)
  + [DescribeImages](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_images)
  + [DescribeInstanceTypes](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instance_types)
  + [DescribeInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instances)
  + [DescribeKeyPairs](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_key_pairs)
  + [DescribeSecurityGroups](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_security_groups)
  + [DisassociateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.disassociate_address)
  + [ReleaseAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.release_address)
  + [RunInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.run_instances)
  + [StartInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.start_instances)
  + [StopInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.stop_instances)
  + [TerminateInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.terminate_instances)
  + [UnmonitorInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.unmonitor_instances)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_rust_1_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn allocate_ip_address(&self) -> Result<AllocateAddressOutput, EC2Error> {
        self.client
            .allocate_address()
            .domain(DomainType::Vpc)
            .send()
            .await
            .map_err(EC2Error::from)
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[AllocateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.allocate_address)」を参照してください。**

### `AssociateAddress`
<a name="ec2_AssociateAddress_rust_1_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn associate_ip_address(
        &self,
        allocation_id: &str,
        instance_id: &str,
    ) -> Result<AssociateAddressOutput, EC2Error> {
        let response = self
            .client
            .associate_address()
            .allocation_id(allocation_id)
            .instance_id(instance_id)
            .send()
            .await?;
        Ok(response)
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[AssociateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.associate_address)」を参照してください。**

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_rust_1_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /// Add an ingress rule to a security group explicitly allowing IPv4 address
    /// as {ip}/32 over TCP port 22.
    pub async fn authorize_security_group_ssh_ingress(
        &self,
        group_id: &str,
        ingress_ips: Vec<Ipv4Addr>,
    ) -> Result<(), EC2Error> {
        tracing::info!("Authorizing ingress for security group {group_id}");
        self.client
            .authorize_security_group_ingress()
            .group_id(group_id)
            .set_ip_permissions(Some(
                ingress_ips
                    .into_iter()
                    .map(|ip| {
                        IpPermission::builder()
                            .ip_protocol("tcp")
                            .from_port(22)
                            .to_port(22)
                            .ip_ranges(IpRange::builder().cidr_ip(format!("{ip}/32")).build())
                            .build()
                    })
                    .collect(),
            ))
            .send()
            .await?;
        Ok(())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[AuthorizeSecurityGroupIngress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.authorize_security_group_ingress)」を参照してください。**

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_rust_1_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。
EC2 クライアントの create\$1key\$1pair を呼び出し、返されたマテリアルを抽出する Rust 実装。  

```
    pub async fn create_key_pair(&self, name: String) -> Result<(KeyPairInfo, String), EC2Error> {
        tracing::info!("Creating key pair {name}");
        let output = self.client.create_key_pair().key_name(name).send().await?;
        let info = KeyPairInfo::builder()
            .set_key_name(output.key_name)
            .set_key_fingerprint(output.key_fingerprint)
            .set_key_pair_id(output.key_pair_id)
            .build();
        let material = output
            .key_material
            .ok_or_else(|| EC2Error::new("Create Key Pair has no key material"))?;
        Ok((info, material))
    }
```
create\$1key impl を呼び出し、PEM プライベートキーを安全に保存する関数。  

```
    /// Creates a key pair that can be used to securely connect to an EC2 instance.
    /// The returned key pair contains private key information that cannot be retrieved
    /// again. The private key data is stored as a .pem file.
    ///
    /// :param key_name: The name of the key pair to create.
    pub async fn create(
        &mut self,
        ec2: &EC2,
        util: &Util,
        key_name: String,
    ) -> Result<KeyPairInfo, EC2Error> {
        let (key_pair, material) = ec2.create_key_pair(key_name.clone()).await.map_err(|e| {
            self.key_pair = KeyPairInfo::builder().key_name(key_name.clone()).build();
            e.add_message(format!("Couldn't create key {key_name}"))
        })?;

        let path = self.key_file_dir.join(format!("{key_name}.pem"));

        // Save the key_pair information immediately, so it can get cleaned up if write_secure fails.
        self.key_file_path = Some(path.clone());
        self.key_pair = key_pair.clone();

        util.write_secure(&key_name, &path, material)?;

        Ok(key_pair)
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[CreateKeyPair](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_key_pair)」を参照してください。**

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_rust_1_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn create_security_group(
        &self,
        name: &str,
        description: &str,
    ) -> Result<SecurityGroup, EC2Error> {
        tracing::info!("Creating security group {name}");
        let create_output = self
            .client
            .create_security_group()
            .group_name(name)
            .description(description)
            .send()
            .await
            .map_err(EC2Error::from)?;

        let group_id = create_output
            .group_id
            .ok_or_else(|| EC2Error::new("Missing security group id after creation"))?;

        let group = self
            .describe_security_group(&group_id)
            .await?
            .ok_or_else(|| {
                EC2Error::new(format!("Could not find security group with id {group_id}"))
            })?;

        tracing::info!("Created security group {name} as {group_id}");

        Ok(group)
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[CreateSecurityGroup](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_security_group)」を参照してください。**

### `CreateTags`
<a name="ec2_CreateTags_rust_1_topic"></a>

次のコード例は、`CreateTags` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。
この例では、インスタンスの作成後に名前タグを適用します。  

```
    pub async fn create_instance<'a>(
        &self,
        image_id: &'a str,
        instance_type: InstanceType,
        key_pair: &'a KeyPairInfo,
        security_groups: Vec<&'a SecurityGroup>,
    ) -> Result<String, EC2Error> {
        let run_instances = self
            .client
            .run_instances()
            .image_id(image_id)
            .instance_type(instance_type)
            .key_name(
                key_pair
                    .key_name()
                    .ok_or_else(|| EC2Error::new("Missing key name when launching instance"))?,
            )
            .set_security_group_ids(Some(
                security_groups
                    .iter()
                    .filter_map(|sg| sg.group_id.clone())
                    .collect(),
            ))
            .min_count(1)
            .max_count(1)
            .send()
            .await?;

        if run_instances.instances().is_empty() {
            return Err(EC2Error::new("Failed to create instance"));
        }

        let instance_id = run_instances.instances()[0].instance_id().unwrap();
        let response = self
            .client
            .create_tags()
            .resources(instance_id)
            .tags(
                Tag::builder()
                    .key("Name")
                    .value("From SDK Examples")
                    .build(),
            )
            .send()
            .await;

        match response {
            Ok(_) => tracing::info!("Created {instance_id} and applied tags."),
            Err(err) => {
                tracing::info!("Error applying tags to {instance_id}: {err:?}");
                return Err(err.into());
            }
        }

        tracing::info!("Instance is created.");

        Ok(instance_id.to_string())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの**「[CreateTags](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.create_tags)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_rust_1_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。
バッキングプライベート PEM キーも削除する delete\$1key のラッパー。  

```
    pub async fn delete(self, ec2: &EC2, util: &Util) -> Result<(), EC2Error> {
        if let Some(key_name) = self.key_pair.key_name() {
            ec2.delete_key_pair(key_name).await?;
            if let Some(key_path) = self.key_file_path() {
                if let Err(err) = util.remove(key_path) {
                    eprintln!("Failed to remove {key_path:?} ({err:?})");
                }
            }
        }
        Ok(())
    }
```

```
    pub async fn delete_key_pair(&self, key_name: &str) -> Result<(), EC2Error> {
        let key_name: String = key_name.into();
        tracing::info!("Deleting key pair {key_name}");
        self.client
            .delete_key_pair()
            .key_name(key_name)
            .send()
            .await?;
        Ok(())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DeleteKeyPair](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_key_pair)」を参照してください。**

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_rust_1_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn delete_security_group(&self, group_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Deleting security group {group_id}");
        self.client
            .delete_security_group()
            .group_id(group_id)
            .send()
            .await?;
        Ok(())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DeleteSecurityGroup](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_security_group)」を参照してください。**

### `DeleteSnapshot`
<a name="ec2_DeleteSnapshot_rust_1_topic"></a>

次のコード例は、`DeleteSnapshot` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ebs#code-examples)での設定と実行の方法を確認してください。

```
async fn delete_snapshot(client: &Client, id: &str) -> Result<(), Error> {
    client.delete_snapshot().snapshot_id(id).send().await?;

    println!("Deleted");

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteSnapshot](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.delete_snapshot)」を参照してください。

### `DescribeImages`
<a name="ec2_DescribeImages_rust_1_topic"></a>

次のコード例は、`DescribeImages` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn list_images(&self, ids: Vec<Parameter>) -> Result<Vec<Image>, EC2Error> {
        let image_ids = ids.into_iter().filter_map(|p| p.value).collect();
        let output = self
            .client
            .describe_images()
            .set_image_ids(Some(image_ids))
            .send()
            .await?;

        let images = output.images.unwrap_or_default();
        if images.is_empty() {
            Err(EC2Error::new("No images for selected AMIs"))
        } else {
            Ok(images)
        }
    }
```
SSM で list\$1images 関数を使用して、環境に基づいて制限します。SSM の詳細については、https://docs.aws.amazon.com/systems-manager/latest/userguide/example\$1ssm\$1GetParameters\$1section.html を参照してください。  

```
    async fn find_image(&mut self) -> Result<ScenarioImage, EC2Error> {
        let params: Vec<Parameter> = self
            .ssm
            .list_path("/aws/service/ami-amazon-linux-latest")
            .await
            .map_err(|e| e.add_message("Could not find parameters for available images"))?
            .into_iter()
            .filter(|param| param.name().is_some_and(|name| name.contains("amzn2")))
            .collect();
        let amzn2_images: Vec<ScenarioImage> = self
            .ec2
            .list_images(params)
            .await
            .map_err(|e| e.add_message("Could not find images"))?
            .into_iter()
            .map(ScenarioImage::from)
            .collect();
        println!("We will now create an instance from an Amazon Linux 2 AMI");
        let ami = self.util.select_scenario_image(amzn2_images)?;
        Ok(ami)
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DescribeImages](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_images)」を参照してください。**

### `DescribeInstanceStatus`
<a name="ec2_DescribeInstanceStatus_rust_1_topic"></a>

次のコード例は、`DescribeInstanceStatus` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
async fn show_all_events(client: &Client) -> Result<(), Error> {
    let resp = client.describe_regions().send().await.unwrap();

    for region in resp.regions.unwrap_or_default() {
        let reg: &'static str = Box::leak(Box::from(region.region_name().unwrap()));
        let region_provider = RegionProviderChain::default_provider().or_else(reg);
        let config = aws_config::from_env().region(region_provider).load().await;
        let new_client = Client::new(&config);

        let resp = new_client.describe_instance_status().send().await;

        println!("Instances in region {}:", reg);
        println!();

        for status in resp.unwrap().instance_statuses() {
            println!(
                "  Events scheduled for instance ID: {}",
                status.instance_id().unwrap_or_default()
            );
            for event in status.events() {
                println!("    Event ID:     {}", event.instance_event_id().unwrap());
                println!("    Description:  {}", event.description().unwrap());
                println!("    Event code:   {}", event.code().unwrap().as_ref());
                println!();
            }
        }
    }

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeInstanceStatus](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instance_status)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_rust_1_topic"></a>

次のコード例は、`DescribeInstanceTypes` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    /// List instance types that match an image's architecture and are free tier eligible.
    pub async fn list_instance_types(&self, image: &Image) -> Result<Vec<InstanceType>, EC2Error> {
        let architecture = format!(
            "{}",
            image.architecture().ok_or_else(|| EC2Error::new(format!(
                "Image {:?} does not have a listed architecture",
                image.image_id()
            )))?
        );
        let free_tier_eligible_filter = Filter::builder()
            .name("free-tier-eligible")
            .values("false")
            .build();
        let supported_architecture_filter = Filter::builder()
            .name("processor-info.supported-architecture")
            .values(architecture)
            .build();
        let response = self
            .client
            .describe_instance_types()
            .filters(free_tier_eligible_filter)
            .filters(supported_architecture_filter)
            .send()
            .await?;

        Ok(response
            .instance_types
            .unwrap_or_default()
            .into_iter()
            .filter_map(|iti| iti.instance_type)
            .collect())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DescribeInstanceTypes](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instance_types)」を参照してください。**

### `DescribeInstances`
<a name="ec2_DescribeInstances_rust_1_topic"></a>

次のコード例は、`DescribeInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。
EC2 インスタンスの詳細を取得します。  

```
    pub async fn describe_instance(&self, instance_id: &str) -> Result<Instance, EC2Error> {
        let response = self
            .client
            .describe_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        let instance = response
            .reservations()
            .first()
            .ok_or_else(|| EC2Error::new(format!("No instance reservations for {instance_id}")))?
            .instances()
            .first()
            .ok_or_else(|| {
                EC2Error::new(format!("No instances in reservation for {instance_id}"))
            })?;

        Ok(instance.clone())
    }
```
EC2 インスタンスを作成した後、その詳細を取得して保存します。  

```
    /// Create an EC2 instance with the given ID on a given type, using a
    /// generated KeyPair and applying a list of security groups.
    pub async fn create(
        &mut self,
        ec2: &EC2,
        image_id: &str,
        instance_type: InstanceType,
        key_pair: &KeyPairInfo,
        security_groups: Vec<&SecurityGroup>,
    ) -> Result<(), EC2Error> {
        let instance_id = ec2
            .create_instance(image_id, instance_type, key_pair, security_groups)
            .await?;
        let instance = ec2.describe_instance(&instance_id).await?;
        self.instance = Some(instance);
        Ok(())
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_instances)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_rust_1_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn list_key_pair(&self) -> Result<Vec<KeyPairInfo>, EC2Error> {
        let output = self.client.describe_key_pairs().send().await?;
        Ok(output.key_pairs.unwrap_or_default())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DescribeKeyPairs](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_key_pairs)」を参照してください。**

### `DescribeRegions`
<a name="ec2_DescribeRegions_rust_1_topic"></a>

次のコード例は、`DescribeRegions` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
async fn show_regions(client: &Client) -> Result<(), Error> {
    let rsp = client.describe_regions().send().await?;

    println!("Regions:");
    for region in rsp.regions() {
        println!("  {}", region.region_name().unwrap());
    }

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeRegions](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_regions)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_rust_1_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
async fn show_security_groups(client: &aws_sdk_ec2::Client, group_ids: Vec<String>) {
    let response = client
        .describe_security_groups()
        .set_group_ids(Some(group_ids))
        .send()
        .await;

    match response {
        Ok(output) => {
            for group in output.security_groups() {
                println!(
                    "Found Security Group {} ({}), vpc id {} and description {}",
                    group.group_name().unwrap_or("unknown"),
                    group.group_id().unwrap_or("id-unknown"),
                    group.vpc_id().unwrap_or("vpcid-unknown"),
                    group.description().unwrap_or("(none)")
                );
            }
        }
        Err(err) => {
            let err = err.into_service_error();
            let meta = err.meta();
            let message = meta.message().unwrap_or("unknown");
            let code = meta.code().unwrap_or("unknown");
            eprintln!("Error listing EC2 Security Groups: ({code}) {message}");
        }
    }
}
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DescribeSecurityGroups](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_security_groups)」を参照してください。**

### `DescribeSnapshots`
<a name="ec2_DescribeSnapshots_rust_1_topic"></a>

次のコード例は、`DescribeSnapshots` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ebs#code-examples)での設定と実行の方法を確認してください。
スナップショットの状態を表示します。  

```
async fn show_state(client: &Client, id: &str) -> Result<(), Error> {
    let resp = client
        .describe_snapshots()
        .filters(Filter::builder().name("snapshot-id").values(id).build())
        .send()
        .await?;

    println!(
        "State: {}",
        resp.snapshots().first().unwrap().state().unwrap().as_ref()
    );

    Ok(())
}
```

```
async fn show_snapshots(client: &Client) -> Result<(), Error> {
    // "self" represents your account ID.
    // You can list the snapshots for any account by replacing
    // "self" with that account ID.
    let resp = client.describe_snapshots().owner_ids("self").send().await?;
    let snapshots = resp.snapshots();
    let length = snapshots.len();

    for snapshot in snapshots {
        println!(
            "ID:          {}",
            snapshot.snapshot_id().unwrap_or_default()
        );
        println!(
            "Description: {}",
            snapshot.description().unwrap_or_default()
        );
        println!("State:       {}", snapshot.state().unwrap().as_ref());
        println!();
    }

    println!();
    println!("Found {} snapshot(s)", length);
    println!();

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DescribeSnapshots](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.describe_snapshots)」を参照してください。

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_rust_1_topic"></a>

次のコード例は、`DisassociateAddress` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn disassociate_ip_address(&self, association_id: &str) -> Result<(), EC2Error> {
        self.client
            .disassociate_address()
            .association_id(association_id)
            .send()
            .await?;
        Ok(())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[DisassociateAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.disassociate_address)」を参照してください。**

### `RebootInstances`
<a name="ec2_RebootInstances_rust_1_topic"></a>

次のコード例は、`RebootInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn reboot(&self, ec2: &EC2) -> Result<(), EC2Error> {
        if self.instance.is_some() {
            ec2.reboot_instance(self.instance_id()).await?;
            ec2.wait_for_instance_stopped(self.instance_id(), None)
                .await?;
            ec2.wait_for_instance_ready(self.instance_id(), None)
                .await?;
        }
        Ok(())
    }
```

```
    pub async fn reboot_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Rebooting instance {instance_id}");

        self.client
            .reboot_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        Ok(())
    }
```
Waiters API を使用して、インスタンスが停止状態および準備完了状態になるのを待ちます。Waiters API を使用するには、rust ファイルで `use aws\$1sdk\$1ec2::client::Waiters` を使用する必要があります。  

```
    /// Wait for an instance to be ready and status ok (default wait 60 seconds)
    pub async fn wait_for_instance_ready(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_status_ok()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to start.",
                    exceeded.max_wait().as_secs()
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }

    pub async fn wait_for_instance_stopped(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_stopped()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to stop.",
                    exceeded.max_wait().as_secs(),
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[RebootInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.reboot_instances)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_rust_1_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn deallocate_ip_address(&self, allocation_id: &str) -> Result<(), EC2Error> {
        self.client
            .release_address()
            .allocation_id(allocation_id)
            .send()
            .await?;
        Ok(())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[ReleaseAddress](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.release_address)」を参照してください。**

### `RunInstances`
<a name="ec2_RunInstances_rust_1_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn create_instance<'a>(
        &self,
        image_id: &'a str,
        instance_type: InstanceType,
        key_pair: &'a KeyPairInfo,
        security_groups: Vec<&'a SecurityGroup>,
    ) -> Result<String, EC2Error> {
        let run_instances = self
            .client
            .run_instances()
            .image_id(image_id)
            .instance_type(instance_type)
            .key_name(
                key_pair
                    .key_name()
                    .ok_or_else(|| EC2Error::new("Missing key name when launching instance"))?,
            )
            .set_security_group_ids(Some(
                security_groups
                    .iter()
                    .filter_map(|sg| sg.group_id.clone())
                    .collect(),
            ))
            .min_count(1)
            .max_count(1)
            .send()
            .await?;

        if run_instances.instances().is_empty() {
            return Err(EC2Error::new("Failed to create instance"));
        }

        let instance_id = run_instances.instances()[0].instance_id().unwrap();
        let response = self
            .client
            .create_tags()
            .resources(instance_id)
            .tags(
                Tag::builder()
                    .key("Name")
                    .value("From SDK Examples")
                    .build(),
            )
            .send()
            .await;

        match response {
            Ok(_) => tracing::info!("Created {instance_id} and applied tags."),
            Err(err) => {
                tracing::info!("Error applying tags to {instance_id}: {err:?}");
                return Err(err.into());
            }
        }

        tracing::info!("Instance is created.");

        Ok(instance_id.to_string())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[RunInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.run_instances)」を参照してください。**

### `StartInstances`
<a name="ec2_StartInstances_rust_1_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。
インスタンス ID で EC2 インスタンスを起動します。  

```
    pub async fn start_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Starting instance {instance_id}");

        self.client
            .start_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        tracing::info!("Started instance.");

        Ok(())
    }
```
Waiters API を使用して、インスタンスが準備完了状態およびステータス OK 状態になるまで待ちます。Waiters API を使用するには、rust ファイルで `use aws\$1sdk\$1ec2::client::Waiters` を使用する必要があります。  

```
    /// Wait for an instance to be ready and status ok (default wait 60 seconds)
    pub async fn wait_for_instance_ready(
        &self,
        instance_id: &str,
        duration: Option<Duration>,
    ) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_status_ok()
            .instance_ids(instance_id)
            .wait(duration.unwrap_or(Duration::from_secs(60)))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to start.",
                    exceeded.max_wait().as_secs()
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[StartInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.start_instances)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_rust_1_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn stop_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Stopping instance {instance_id}");

        self.client
            .stop_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        self.wait_for_instance_stopped(instance_id, None).await?;

        tracing::info!("Stopped instance.");

        Ok(())
    }
```
Waiters API を使用して、インスタンスが停止状態になるまで待ちます。Waiters API を使用するには、rust ファイルで `use aws\$1sdk\$1ec2::client::Waiters` を使用する必要があります。  

```
    pub async fn stop_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Stopping instance {instance_id}");

        self.client
            .stop_instances()
            .instance_ids(instance_id)
            .send()
            .await?;

        self.wait_for_instance_stopped(instance_id, None).await?;

        tracing::info!("Stopped instance.");

        Ok(())
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[StopInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.stop_instances)」を参照してください。

### `TerminateInstances`
<a name="ec2_TerminateInstances_rust_1_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ec2#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn delete_instance(&self, instance_id: &str) -> Result<(), EC2Error> {
        tracing::info!("Deleting instance with id {instance_id}");
        self.stop_instance(instance_id).await?;
        self.client
            .terminate_instances()
            .instance_ids(instance_id)
            .send()
            .await?;
        self.wait_for_instance_terminated(instance_id).await?;
        tracing::info!("Terminated instance with id {instance_id}");
        Ok(())
    }
```
Waiters API を使用して、インスタンスが終了状態になるまで待ちます。Waiters API を使用するには、rust ファイルで `use aws\$1sdk\$1ec2::client::Waiters` を使用する必要があります。  

```
    async fn wait_for_instance_terminated(&self, instance_id: &str) -> Result<(), EC2Error> {
        self.client
            .wait_until_instance_terminated()
            .instance_ids(instance_id)
            .wait(Duration::from_secs(60))
            .await
            .map_err(|err| match err {
                WaiterError::ExceededMaxWait(exceeded) => EC2Error(format!(
                    "Exceeded max time ({}s) waiting for instance to terminate.",
                    exceeded.max_wait().as_secs(),
                )),
                _ => EC2Error::from(err),
            })?;
        Ok(())
    }
```
+  API の詳細については、AWS SDK for Rust API リファレンスの「[TerminateInstances](https://docs.rs/aws-sdk-ec2/latest/aws_sdk_ec2/client/struct.Client.html#method.terminate_instances)」を参照してください。**

# SDK for Rust を使用した Amazon ECR の例
<a name="rust_1_ecr_code_examples"></a>

次のコード例は、Amazon ECR で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeRepositories`
<a name="ecr_DescribeRepositories_rust_1_topic"></a>

次のコード例は、`DescribeRepositories` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ecr#code-examples)での設定と実行の方法を確認してください。

```
async fn show_repos(client: &aws_sdk_ecr::Client) -> Result<(), aws_sdk_ecr::Error> {
    let rsp = client.describe_repositories().send().await?;

    let repos = rsp.repositories();

    println!("Found {} repositories:", repos.len());

    for repo in repos {
        println!("  ARN:  {}", repo.repository_arn().unwrap());
        println!("  Name: {}", repo.repository_name().unwrap());
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeRepositories](https://docs.rs/aws-sdk-ecr/latest/aws_sdk_ecr/client/struct.Client.html#method.describe_repositories)」を参照してください。

### `ListImages`
<a name="ecr_ListImages_rust_1_topic"></a>

次のコード例は、`ListImages` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ecr#code-examples)での設定と実行の方法を確認してください。

```
async fn show_images(
    client: &aws_sdk_ecr::Client,
    repository: &str,
) -> Result<(), aws_sdk_ecr::Error> {
    let rsp = client
        .list_images()
        .repository_name(repository)
        .send()
        .await?;

    let images = rsp.image_ids();

    println!("found {} images", images.len());

    for image in images {
        println!(
            "image: {}:{}",
            image.image_tag().unwrap(),
            image.image_digest().unwrap()
        );
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListImages](https://docs.rs/aws-sdk-ecr/latest/aws_sdk_ecr/client/struct.Client.html#method.list_images)」を参照してください。

# SDK for Rust を使用した Amazon ECS の例
<a name="rust_1_ecs_code_examples"></a>

次のコード例は、Amazon ECS で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="ecs_CreateCluster_rust_1_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ecs#code-examples)での設定と実行の方法を確認してください。

```
async fn make_cluster(client: &aws_sdk_ecs::Client, name: &str) -> Result<(), aws_sdk_ecs::Error> {
    let cluster = client.create_cluster().cluster_name(name).send().await?;
    println!("cluster created: {:?}", cluster);

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateCluster](https://docs.rs/aws-sdk-ecs/latest/aws_sdk_ecs/client/struct.Client.html#method.create_cluster)」を参照してください。

### `DeleteCluster`
<a name="ecs_DeleteCluster_rust_1_topic"></a>

次のコード例は、`DeleteCluster` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ecs#code-examples)での設定と実行の方法を確認してください。

```
async fn remove_cluster(
    client: &aws_sdk_ecs::Client,
    name: &str,
) -> Result<(), aws_sdk_ecs::Error> {
    let cluster_deleted = client.delete_cluster().cluster(name).send().await?;
    println!("cluster deleted: {:?}", cluster_deleted);

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteCluster](https://docs.rs/aws-sdk-ecs/latest/aws_sdk_ecs/client/struct.Client.html#method.delete_cluster)」を参照してください。

### `DescribeClusters`
<a name="ecs_DescribeClusters_rust_1_topic"></a>

次のコード例は、`DescribeClusters` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ecs#code-examples)での設定と実行の方法を確認してください。

```
async fn show_clusters(client: &aws_sdk_ecs::Client) -> Result<(), aws_sdk_ecs::Error> {
    let resp = client.list_clusters().send().await?;

    let cluster_arns = resp.cluster_arns();
    println!("Found {} clusters:", cluster_arns.len());

    let clusters = client
        .describe_clusters()
        .set_clusters(Some(cluster_arns.into()))
        .send()
        .await?;

    for cluster in clusters.clusters() {
        println!("  ARN:  {}", cluster.cluster_arn().unwrap());
        println!("  Name: {}", cluster.cluster_name().unwrap());
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeClusters](https://docs.rs/aws-sdk-ecs/latest/aws_sdk_ecs/client/struct.Client.html#method.describe_clusters)」を参照してください。

# SDK for Rust を使用した Amazon EKS の例
<a name="rust_1_eks_code_examples"></a>

次のコード例は、Amazon EKS で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="eks_CreateCluster_rust_1_topic"></a>

次のコード例は、`CreateCluster` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/eks#code-examples)での設定と実行の方法を確認してください。

```
async fn make_cluster(
    client: &aws_sdk_eks::Client,
    name: &str,
    arn: &str,
    subnet_ids: Vec<String>,
) -> Result<(), aws_sdk_eks::Error> {
    let cluster = client
        .create_cluster()
        .name(name)
        .role_arn(arn)
        .resources_vpc_config(
            VpcConfigRequest::builder()
                .set_subnet_ids(Some(subnet_ids))
                .build(),
        )
        .send()
        .await?;
    println!("cluster created: {:?}", cluster);

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateCluster](https://docs.rs/aws-sdk-eks/latest/aws_sdk_eks/client/struct.Client.html#method.create_cluster)」を参照してください。

### `DeleteCluster`
<a name="eks_DeleteCluster_rust_1_topic"></a>

次のコード例は、`DeleteCluster` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/eks#code-examples)での設定と実行の方法を確認してください。

```
async fn remove_cluster(
    client: &aws_sdk_eks::Client,
    name: &str,
) -> Result<(), aws_sdk_eks::Error> {
    let cluster_deleted = client.delete_cluster().name(name).send().await?;
    println!("cluster deleted: {:?}", cluster_deleted);

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteCluster](https://docs.rs/aws-sdk-eks/latest/aws_sdk_eks/client/struct.Client.html#method.delete_cluster)」を参照してください。

# AWS Glue SDK for Rust を使用した の例
<a name="rust_1_glue_code_examples"></a>

次のコード例は、 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS Glueは
<a name="glue_Hello_rust_1_topic"></a>

次のコード例は、 AWS Glueの使用を開始する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let mut list_jobs = glue.list_jobs().into_paginator().send();
        while let Some(list_jobs_output) = list_jobs.next().await {
            match list_jobs_output {
                Ok(list_jobs) => {
                    let names = list_jobs.job_names();
                    info!(?names, "Found these jobs")
                }
                Err(err) => return Err(GlueMvpError::from_glue_sdk(err)),
            }
        }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListJobs](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.list_jobs)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。
パブリックの Amazon Simple Storage Service (Amazon S3) バケットをクロールし、検出した CSV 形式データを記述するメタデータデータベースを生成するクローラーを作成して実行します。  

```
        let create_crawler = glue
            .create_crawler()
            .name(self.crawler())
            .database_name(self.database())
            .role(self.iam_role.expose_secret())
            .targets(
                CrawlerTargets::builder()
                    .s3_targets(S3Target::builder().path(CRAWLER_TARGET).build())
                    .build(),
            )
            .send()
            .await;

        match create_crawler {
            Err(err) => {
                let glue_err: aws_sdk_glue::Error = err.into();
                match glue_err {
                    aws_sdk_glue::Error::AlreadyExistsException(_) => {
                        info!("Using existing crawler");
                        Ok(())
                    }
                    _ => Err(GlueMvpError::GlueSdk(glue_err)),
                }
            }
            Ok(_) => Ok(()),
        }?;

        let start_crawler = glue.start_crawler().name(self.crawler()).send().await;

        match start_crawler {
            Ok(_) => Ok(()),
            Err(err) => {
                let glue_err: aws_sdk_glue::Error = err.into();
                match glue_err {
                    aws_sdk_glue::Error::CrawlerRunningException(_) => Ok(()),
                    _ => Err(GlueMvpError::GlueSdk(glue_err)),
                }
            }
        }?;
```
のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。  

```
        let database = glue
            .get_database()
            .name(self.database())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?
            .to_owned();
        let database = database
            .database()
            .ok_or_else(|| GlueMvpError::Unknown("Could not find database".into()))?;

        let tables = glue
            .get_tables()
            .database_name(self.database())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        let tables = tables.table_list();
```
ソース Amazon S3 バケットから CSV 形式データを抽出し、フィールドを削除して名前を変更することで変換し、JSON 形式の出力を別の Amazon S3 バケットにロードするジョブを作成して実行します。  

```
        let create_job = glue
            .create_job()
            .name(self.job())
            .role(self.iam_role.expose_secret())
            .command(
                JobCommand::builder()
                    .name("glueetl")
                    .python_version("3")
                    .script_location(format!("s3://{}/job.py", self.bucket()))
                    .build(),
            )
            .glue_version("3.0")
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        let job_name = create_job.name().ok_or_else(|| {
            GlueMvpError::Unknown("Did not get job name after creating job".into())
        })?;

        let job_run_output = glue
            .start_job_run()
            .job_name(self.job())
            .arguments("--input_database", self.database())
            .arguments(
                "--input_table",
                self.tables
                    .first()
                    .ok_or_else(|| GlueMvpError::Unknown("Missing crawler table".into()))?
                    .name(),
            )
            .arguments("--output_bucket_url", self.bucket())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        let job = job_run_output
            .job_run_id()
            .ok_or_else(|| GlueMvpError::Unknown("Missing run id from just started job".into()))?
            .to_string();
```
デモによって作成されたすべてのリソースを削除します。  

```
        glue.delete_job()
            .job_name(self.job())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        for t in &self.tables {
            glue.delete_table()
                .name(t.name())
                .database_name(self.database())
                .send()
                .await
                .map_err(GlueMvpError::from_glue_sdk)?;
        }

        glue.delete_database()
            .name(self.database())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        glue.delete_crawler()
            .name(self.crawler())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;
```
+ API の詳細については、「*AWS SDK for Rust API リファレンス*」の以下のトピックを参照してください。
  + [CreateCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.create_crawler)
  + [CreateJob](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.create_job)
  + [DeleteCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_crawler)
  + [DeleteDatabase](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_database)
  + [DeleteJob](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_job)
  + [DeleteTable](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_table)
  + [GetCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_crawler)
  + [GetDatabase](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_database)
  + [GetDatabases](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_databases)
  + [GetJob](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_job)
  + [GetJobRun](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_job_run)
  + [GetJobRuns](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_job_runs)
  + [GetTables](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_tables)
  + [ListJobs](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.list_jobs)
  + [StartCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.start_crawler)
  + [StartJobRun](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.start_job_run)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_rust_1_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let create_crawler = glue
            .create_crawler()
            .name(self.crawler())
            .database_name(self.database())
            .role(self.iam_role.expose_secret())
            .targets(
                CrawlerTargets::builder()
                    .s3_targets(S3Target::builder().path(CRAWLER_TARGET).build())
                    .build(),
            )
            .send()
            .await;

        match create_crawler {
            Err(err) => {
                let glue_err: aws_sdk_glue::Error = err.into();
                match glue_err {
                    aws_sdk_glue::Error::AlreadyExistsException(_) => {
                        info!("Using existing crawler");
                        Ok(())
                    }
                    _ => Err(GlueMvpError::GlueSdk(glue_err)),
                }
            }
            Ok(_) => Ok(()),
        }?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[CreateCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.create_crawler)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_rust_1_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let create_job = glue
            .create_job()
            .name(self.job())
            .role(self.iam_role.expose_secret())
            .command(
                JobCommand::builder()
                    .name("glueetl")
                    .python_version("3")
                    .script_location(format!("s3://{}/job.py", self.bucket()))
                    .build(),
            )
            .glue_version("3.0")
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        let job_name = create_job.name().ok_or_else(|| {
            GlueMvpError::Unknown("Did not get job name after creating job".into())
        })?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[CreateJob](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.create_job)」を参照してください。

### `DeleteCrawler`
<a name="glue_DeleteCrawler_rust_1_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        glue.delete_crawler()
            .name(self.crawler())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[DeleteCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_crawler)」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_rust_1_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        glue.delete_database()
            .name(self.database())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[DeleteDatabase](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_database)」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_rust_1_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        glue.delete_job()
            .job_name(self.job())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[DeleteJob](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_job)」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_rust_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        for t in &self.tables {
            glue.delete_table()
                .name(t.name())
                .database_name(self.database())
                .send()
                .await
                .map_err(GlueMvpError::from_glue_sdk)?;
        }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteTable](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.delete_table)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_rust_1_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
            let tmp_crawler = glue
                .get_crawler()
                .name(self.crawler())
                .send()
                .await
                .map_err(GlueMvpError::from_glue_sdk)?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[GetCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_crawler)」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_rust_1_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let database = glue
            .get_database()
            .name(self.database())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?
            .to_owned();
        let database = database
            .database()
            .ok_or_else(|| GlueMvpError::Unknown("Could not find database".into()))?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[GetDatabase](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_database)」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_rust_1_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let get_job_run = || async {
            Ok::<JobRun, GlueMvpError>(
                glue.get_job_run()
                    .job_name(self.job())
                    .run_id(job_run_id.to_string())
                    .send()
                    .await
                    .map_err(GlueMvpError::from_glue_sdk)?
                    .job_run()
                    .ok_or_else(|| GlueMvpError::Unknown("Failed to get job_run".into()))?
                    .to_owned(),
            )
        };

        let mut job_run = get_job_run().await?;
        let mut state = job_run.job_run_state().unwrap_or(&unknown_state).to_owned();

        while matches!(
            state,
            JobRunState::Starting | JobRunState::Stopping | JobRunState::Running
        ) {
            info!(?state, "Waiting for job to finish");
            tokio::time::sleep(self.wait_delay).await;

            job_run = get_job_run().await?;
            state = job_run.job_run_state().unwrap_or(&unknown_state).to_owned();
        }
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[GetJobRun](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_job_run)」を参照してください。

### `GetTables`
<a name="glue_GetTables_rust_1_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let tables = glue
            .get_tables()
            .database_name(self.database())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        let tables = tables.table_list();
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[GetTables](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.get_tables)」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_rust_1_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let mut list_jobs = glue.list_jobs().into_paginator().send();
        while let Some(list_jobs_output) = list_jobs.next().await {
            match list_jobs_output {
                Ok(list_jobs) => {
                    let names = list_jobs.job_names();
                    info!(?names, "Found these jobs")
                }
                Err(err) => return Err(GlueMvpError::from_glue_sdk(err)),
            }
        }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListJobs](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.list_jobs)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_rust_1_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let start_crawler = glue.start_crawler().name(self.crawler()).send().await;

        match start_crawler {
            Ok(_) => Ok(()),
            Err(err) => {
                let glue_err: aws_sdk_glue::Error = err.into();
                match glue_err {
                    aws_sdk_glue::Error::CrawlerRunningException(_) => Ok(()),
                    _ => Err(GlueMvpError::GlueSdk(glue_err)),
                }
            }
        }?;
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[StartCrawler](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.start_crawler)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_rust_1_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/glue#code-examples)での設定と実行の方法を確認してください。

```
        let job_run_output = glue
            .start_job_run()
            .job_name(self.job())
            .arguments("--input_database", self.database())
            .arguments(
                "--input_table",
                self.tables
                    .first()
                    .ok_or_else(|| GlueMvpError::Unknown("Missing crawler table".into()))?
                    .name(),
            )
            .arguments("--output_bucket_url", self.bucket())
            .send()
            .await
            .map_err(GlueMvpError::from_glue_sdk)?;

        let job = job_run_output
            .job_run_id()
            .ok_or_else(|| GlueMvpError::Unknown("Missing run id from just started job".into()))?
            .to_string();
```
+  API の詳細については、*AWS SDK for Rust API リファレンス* の「[StartJobRun](https://docs.rs/aws-sdk-glue/latest/aws_sdk_glue/client/struct.Client.html#method.start_job_run)」を参照してください。

# SDK for Rust を使用した IAM の例
<a name="rust_1_iam_code_examples"></a>

次のコード例は、IAM で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### IAM へようこそ
<a name="iam_Hello_rust_1_topic"></a>

次のコード例は、IAM の使用を開始する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。
From src/bin/hello.rs.  

```
use aws_sdk_iam::error::SdkError;
use aws_sdk_iam::operation::list_policies::ListPoliciesError;
use clap::Parser;

const PATH_PREFIX_HELP: &str = "The path prefix for filtering the results.";

#[derive(Debug, clap::Parser)]
#[command(about)]
struct HelloScenarioArgs {
    #[arg(long, default_value="/", help=PATH_PREFIX_HELP)]
    pub path_prefix: String,
}

#[tokio::main]
async fn main() -> Result<(), SdkError<ListPoliciesError>> {
    let sdk_config = aws_config::load_from_env().await;
    let client = aws_sdk_iam::Client::new(&sdk_config);

    let args = HelloScenarioArgs::parse();

    iam_service::list_policies(client, args.path_prefix).await?;

    Ok(())
}
```
From src/iam-service-lib.rs.  

```
pub async fn list_policies(
    client: iamClient,
    path_prefix: String,
) -> Result<Vec<String>, SdkError<ListPoliciesError>> {
    let list_policies = client
        .list_policies()
        .path_prefix(path_prefix)
        .scope(PolicyScopeType::Local)
        .into_paginator()
        .items()
        .send()
        .try_collect()
        .await?;

    let policy_names = list_policies
        .into_iter()
        .map(|p| {
            let name = p
                .policy_name
                .unwrap_or_else(|| "Missing Policy Name".to_string());
            println!("{}", name);
            name
        })
        .collect();

    Ok(policy_names)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListPolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_policies)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="iam_Scenario_CreateUserAssumeRole_rust_1_topic"></a>

次のコード例は、ユーザーを作成してロールを割り当てる方法を示しています。

**警告**  
セキュリティリスクを避けるため、専用ソフトウェアを開発するときや実際のデータを扱うときは、IAM ユーザーを認証に使用しないでください。代わりに、[AWS IAM アイデンティティセンター](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) などの ID プロバイダーとのフェデレーションを使用してください。
+ 権限のないユーザーを作成します。
+ アカウントの Amazon S3 バケットを一覧表示する権限を付与するロールを作成します。
+ ユーザーがロールを引き受けられるようにポリシーを追加します。
+ ロールを引き受け、一時的な認証情報を使用して S3 バケットを一覧表示し、リソースをクリーンアップします。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iam::Error as iamError;
use aws_sdk_iam::{config::Credentials as iamCredentials, config::Region, Client as iamClient};
use aws_sdk_s3::Client as s3Client;
use aws_sdk_sts::Client as stsClient;
use tokio::time::{sleep, Duration};
use uuid::Uuid;

#[tokio::main]
async fn main() -> Result<(), iamError> {
    let (client, uuid, list_all_buckets_policy_document, inline_policy_document) =
        initialize_variables().await;

    if let Err(e) = run_iam_operations(
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
    .await
    {
        println!("{:?}", e);
    };

    Ok(())
}

async fn initialize_variables() -> (iamClient, String, String, String) {
    let region_provider = RegionProviderChain::first_try(Region::new("us-west-2"));

    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = iamClient::new(&shared_config);
    let uuid = Uuid::new_v4().to_string();

    let list_all_buckets_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"s3:ListAllMyBuckets\",
                    \"Resource\": \"arn:aws:s3:::*\"}]
    }"
    .to_string();
    let inline_policy_document = "{
                \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Action\": \"sts:AssumeRole\",
                    \"Resource\": \"{}\"}]
    }"
    .to_string();

    (
        client,
        uuid,
        list_all_buckets_policy_document,
        inline_policy_document,
    )
}

async fn run_iam_operations(
    client: iamClient,
    uuid: String,
    list_all_buckets_policy_document: String,
    inline_policy_document: String,
) -> Result<(), iamError> {
    let user = iam_service::create_user(&client, &format!("{}{}", "iam_demo_user_", uuid)).await?;
    println!("Created the user with the name: {}", user.user_name());
    let key = iam_service::create_access_key(&client, user.user_name()).await?;

    let assume_role_policy_document = "{
        \"Version\": \"2012-10-17\",
                \"Statement\": [{
                    \"Effect\": \"Allow\",
                    \"Principal\": {\"AWS\": \"{}\"},
                    \"Action\": \"sts:AssumeRole\"
                }]
            }"
    .to_string()
    .replace("{}", user.arn());

    let assume_role_role = iam_service::create_role(
        &client,
        &format!("{}{}", "iam_demo_role_", uuid),
        &assume_role_policy_document,
    )
    .await?;
    println!("Created the role with the ARN: {}", assume_role_role.arn());

    let list_all_buckets_policy = iam_service::create_policy(
        &client,
        &format!("{}{}", "iam_demo_policy_", uuid),
        &list_all_buckets_policy_document,
    )
    .await?;
    println!(
        "Created policy: {}",
        list_all_buckets_policy.policy_name.as_ref().unwrap()
    );

    let attach_role_policy_result =
        iam_service::attach_role_policy(&client, &assume_role_role, &list_all_buckets_policy)
            .await?;
    println!(
        "Attached the policy to the role: {:?}",
        attach_role_policy_result
    );

    let inline_policy_name = format!("{}{}", "iam_demo_inline_policy_", uuid);
    let inline_policy_document = inline_policy_document.replace("{}", assume_role_role.arn());
    iam_service::create_user_policy(&client, &user, &inline_policy_name, &inline_policy_document)
        .await?;
    println!("Created inline policy.");

    //First, fail to list the buckets with the user.
    let creds = iamCredentials::from_keys(key.access_key_id(), key.secret_access_key(), None);
    let fail_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    println!("Fail config: {:?}", fail_config);
    let fail_client: s3Client = s3Client::new(&fail_config);
    match fail_client.list_buckets().send().await {
        Ok(e) => {
            println!("This should not run. {:?}", e);
        }
        Err(e) => {
            println!("Successfully failed with error: {:?}", e)
        }
    }

    let sts_config = aws_config::from_env()
        .credentials_provider(creds.clone())
        .load()
        .await;
    let sts_client: stsClient = stsClient::new(&sts_config);
    sleep(Duration::from_secs(10)).await;
    let assumed_role = sts_client
        .assume_role()
        .role_arn(assume_role_role.arn())
        .role_session_name(format!("iam_demo_assumerole_session_{uuid}"))
        .send()
        .await;
    println!("Assumed role: {:?}", assumed_role);
    sleep(Duration::from_secs(10)).await;

    let assumed_credentials = iamCredentials::from_keys(
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .access_key_id(),
        assumed_role
            .as_ref()
            .unwrap()
            .credentials
            .as_ref()
            .unwrap()
            .secret_access_key(),
        Some(
            assumed_role
                .as_ref()
                .unwrap()
                .credentials
                .as_ref()
                .unwrap()
                .session_token
                .clone(),
        ),
    );

    let succeed_config = aws_config::from_env()
        .credentials_provider(assumed_credentials)
        .load()
        .await;
    println!("succeed config: {:?}", succeed_config);
    let succeed_client: s3Client = s3Client::new(&succeed_config);
    sleep(Duration::from_secs(10)).await;
    match succeed_client.list_buckets().send().await {
        Ok(_) => {
            println!("This should now run successfully.")
        }
        Err(e) => {
            println!("This should not run. {:?}", e);
            panic!()
        }
    }

    //Clean up.
    iam_service::detach_role_policy(
        &client,
        assume_role_role.role_name(),
        list_all_buckets_policy.arn().unwrap_or_default(),
    )
    .await?;
    iam_service::delete_policy(&client, list_all_buckets_policy).await?;
    iam_service::delete_role(&client, &assume_role_role).await?;
    println!("Deleted role {}", assume_role_role.role_name());
    iam_service::delete_access_key(&client, &user, &key).await?;
    println!("Deleted key for {}", key.user_name());
    iam_service::delete_user_policy(&client, &user, &inline_policy_name).await?;
    println!("Deleted inline user policy: {}", inline_policy_name);
    iam_service::delete_user(&client, &user).await?;
    println!("Deleted user {}", user.user_name());

    Ok(())
}
```
+ API の詳細については、「*AWS SDK for Rust API リファレンス*」の以下のトピックを参照してください。
  + [AttachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_role_policy)
  + [CreateAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_access_key)
  + [CreatePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_policy)
  + [CreateRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)
  + [CreateUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_user)
  + [DeleteAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_access_key)
  + [DeletePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_policy)
  + [DeleteRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_role)
  + [DeleteUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user)
  + [DeleteUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user_policy)
  + [DetachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_role_policy)
  + [PutUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.put_user_policy)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_rust_1_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn attach_role_policy(
    client: &iamClient,
    role: &Role,
    policy: &Policy,
) -> Result<AttachRolePolicyOutput, SdkError<AttachRolePolicyError>> {
    client
        .attach_role_policy()
        .role_name(role.role_name())
        .policy_arn(policy.arn().unwrap_or_default())
        .send()
        .await
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[AttachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_role_policy)」を参照してください。

### `AttachUserPolicy`
<a name="iam_AttachUserPolicy_rust_1_topic"></a>

次のコード例は、`AttachUserPolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn attach_user_policy(
    client: &iamClient,
    user_name: &str,
    policy_arn: &str,
) -> Result<(), iamError> {
    client
        .attach_user_policy()
        .user_name(user_name)
        .policy_arn(policy_arn)
        .send()
        .await?;

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[AttachUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.attach_user_policy)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_rust_1_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn create_access_key(client: &iamClient, user_name: &str) -> Result<AccessKey, iamError> {
    let mut tries: i32 = 0;
    let max_tries: i32 = 10;

    let response: Result<CreateAccessKeyOutput, SdkError<CreateAccessKeyError>> = loop {
        match client.create_access_key().user_name(user_name).send().await {
            Ok(inner_response) => {
                break Ok(inner_response);
            }
            Err(e) => {
                tries += 1;
                if tries > max_tries {
                    break Err(e);
                }
                sleep(Duration::from_secs(2)).await;
            }
        }
    };

    Ok(response.unwrap().access_key.unwrap())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_access_key)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_rust_1_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn create_policy(
    client: &iamClient,
    policy_name: &str,
    policy_document: &str,
) -> Result<Policy, iamError> {
    let policy = client
        .create_policy()
        .policy_name(policy_name)
        .policy_document(policy_document)
        .send()
        .await?;
    Ok(policy.policy.unwrap())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreatePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_policy)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_rust_1_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
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](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_role)」を参照してください。

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_rust_1_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn create_service_linked_role(
    client: &iamClient,
    aws_service_name: String,
    custom_suffix: Option<String>,
    description: Option<String>,
) -> Result<CreateServiceLinkedRoleOutput, SdkError<CreateServiceLinkedRoleError>> {
    let response = client
        .create_service_linked_role()
        .aws_service_name(aws_service_name)
        .set_custom_suffix(custom_suffix)
        .set_description(description)
        .send()
        .await?;

    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateServiceLinkedRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_service_linked_role)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_rust_1_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn create_user(client: &iamClient, user_name: &str) -> Result<User, iamError> {
    let response = client.create_user().user_name(user_name).send().await?;

    Ok(response.user.unwrap())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.create_user)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_rust_1_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_access_key(
    client: &iamClient,
    user: &User,
    key: &AccessKey,
) -> Result<(), iamError> {
    loop {
        match client
            .delete_access_key()
            .user_name(user.user_name())
            .access_key_id(key.access_key_id())
            .send()
            .await
        {
            Ok(_) => {
                break;
            }
            Err(e) => {
                println!("Can't delete the access key: {:?}", e);
                sleep(Duration::from_secs(2)).await;
            }
        }
    }
    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteAccessKey](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_access_key)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_rust_1_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_policy(client: &iamClient, policy: Policy) -> Result<(), iamError> {
    client
        .delete_policy()
        .policy_arn(policy.arn.unwrap())
        .send()
        .await?;
    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeletePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_policy)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_rust_1_topic"></a>

次のコード例は、`DeleteRole` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_role(client: &iamClient, role: &Role) -> Result<(), iamError> {
    let role = role.clone();
    while client
        .delete_role()
        .role_name(role.role_name())
        .send()
        .await
        .is_err()
    {
        sleep(Duration::from_secs(2)).await;
    }
    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_role)」を参照してください。

### `DeleteServiceLinkedRole`
<a name="iam_DeleteServiceLinkedRole_rust_1_topic"></a>

次のコード例は、`DeleteServiceLinkedRole` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_service_linked_role(
    client: &iamClient,
    role_name: &str,
) -> Result<(), iamError> {
    client
        .delete_service_linked_role()
        .role_name(role_name)
        .send()
        .await?;

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteServiceLinkedRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_service_linked_role)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_rust_1_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_user(client: &iamClient, user: &User) -> Result<(), SdkError<DeleteUserError>> {
    let user = user.clone();
    let mut tries: i32 = 0;
    let max_tries: i32 = 10;

    let response: Result<(), SdkError<DeleteUserError>> = loop {
        match client
            .delete_user()
            .user_name(user.user_name())
            .send()
            .await
        {
            Ok(_) => {
                break Ok(());
            }
            Err(e) => {
                tries += 1;
                if tries > max_tries {
                    break Err(e);
                }
                sleep(Duration::from_secs(2)).await;
            }
        }
    };

    response
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteUser](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user)」を参照してください。

### `DeleteUserPolicy`
<a name="iam_DeleteUserPolicy_rust_1_topic"></a>

次のコード例は、`DeleteUserPolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_user_policy(
    client: &iamClient,
    user: &User,
    policy_name: &str,
) -> Result<(), SdkError<DeleteUserPolicyError>> {
    client
        .delete_user_policy()
        .user_name(user.user_name())
        .policy_name(policy_name)
        .send()
        .await?;

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.delete_user_policy)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_rust_1_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn detach_role_policy(
    client: &iamClient,
    role_name: &str,
    policy_arn: &str,
) -> Result<(), iamError> {
    client
        .detach_role_policy()
        .role_name(role_name)
        .policy_arn(policy_arn)
        .send()
        .await?;

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DetachRolePolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_role_policy)」を参照してください。

### `DetachUserPolicy`
<a name="iam_DetachUserPolicy_rust_1_topic"></a>

次のコード例は、`DetachUserPolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn detach_user_policy(
    client: &iamClient,
    user_name: &str,
    policy_arn: &str,
) -> Result<(), iamError> {
    client
        .detach_user_policy()
        .user_name(user_name)
        .policy_arn(policy_arn)
        .send()
        .await?;

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DetachUserPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.detach_user_policy)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_rust_1_topic"></a>

次のコード例は、`GetAccountPasswordPolicy` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn get_account_password_policy(
    client: &iamClient,
) -> Result<GetAccountPasswordPolicyOutput, SdkError<GetAccountPasswordPolicyError>> {
    let response = client.get_account_password_policy().send().await?;

    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[GetAccountPasswordPolicy](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.get_account_password_policy)」を参照してください。

### `GetRole`
<a name="iam_GetRole_rust_1_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn get_role(
    client: &iamClient,
    role_name: String,
) -> Result<GetRoleOutput, SdkError<GetRoleError>> {
    let response = client.get_role().role_name(role_name).send().await?;
    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[GetRole](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.get_role)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_rust_1_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_attached_role_policies(
    client: &iamClient,
    role_name: String,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListAttachedRolePoliciesOutput, SdkError<ListAttachedRolePoliciesError>> {
    let response = client
        .list_attached_role_policies()
        .role_name(role_name)
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;

    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListAttachedRolePolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_attached_role_policies)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_rust_1_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_groups(
    client: &iamClient,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListGroupsOutput, SdkError<ListGroupsError>> {
    let response = client
        .list_groups()
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;

    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListGroups](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_groups)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_rust_1_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_policies(
    client: iamClient,
    path_prefix: String,
) -> Result<Vec<String>, SdkError<ListPoliciesError>> {
    let list_policies = client
        .list_policies()
        .path_prefix(path_prefix)
        .scope(PolicyScopeType::Local)
        .into_paginator()
        .items()
        .send()
        .try_collect()
        .await?;

    let policy_names = list_policies
        .into_iter()
        .map(|p| {
            let name = p
                .policy_name
                .unwrap_or_else(|| "Missing Policy Name".to_string());
            println!("{}", name);
            name
        })
        .collect();

    Ok(policy_names)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListPolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_policies)」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_rust_1_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_role_policies(
    client: &iamClient,
    role_name: &str,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListRolePoliciesOutput, SdkError<ListRolePoliciesError>> {
    let response = client
        .list_role_policies()
        .role_name(role_name)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;

    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListRolePolicies](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_role_policies)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_rust_1_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_roles(
    client: &iamClient,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListRolesOutput, SdkError<ListRolesError>> {
    let response = client
        .list_roles()
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;
    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListRoles](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_roles)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_rust_1_topic"></a>

次のコード例は、`ListSAMLProviders` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_saml_providers(
    client: &Client,
) -> Result<ListSamlProvidersOutput, SdkError<ListSAMLProvidersError>> {
    let response = client.list_saml_providers().send().await?;

    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListSAMLProviders](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_saml_providers)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_rust_1_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iam#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_users(
    client: &iamClient,
    path_prefix: Option<String>,
    marker: Option<String>,
    max_items: Option<i32>,
) -> Result<ListUsersOutput, SdkError<ListUsersError>> {
    let response = client
        .list_users()
        .set_path_prefix(path_prefix)
        .set_marker(marker)
        .set_max_items(max_items)
        .send()
        .await?;
    Ok(response)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListUsers](https://docs.rs/aws-sdk-iam/latest/aws_sdk_iam/client/struct.Client.html#method.list_users)」を参照してください。

# AWS IoT SDK for Rust を使用した の例
<a name="rust_1_iot_code_examples"></a>

次のコード例は、 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeEndpoint`
<a name="iot_DescribeEndpoint_rust_1_topic"></a>

次のコード例は、`DescribeEndpoint` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iot#code-examples)での設定と実行の方法を確認してください。

```
async fn show_address(client: &Client, endpoint_type: &str) -> Result<(), Error> {
    let resp = client
        .describe_endpoint()
        .endpoint_type(endpoint_type)
        .send()
        .await?;

    println!("Endpoint address: {}", resp.endpoint_address.unwrap());

    println!();

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeEndpoint](https://docs.rs/aws-sdk-iot/latest/aws_sdk_iot/client/struct.Client.html#method.describe_endpoint)」を参照してください。

### `ListThings`
<a name="iot_ListThings_rust_1_topic"></a>

次のコード例は、`ListThings` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/iot#code-examples)での設定と実行の方法を確認してください。

```
async fn show_things(client: &Client) -> Result<(), Error> {
    let resp = client.list_things().send().await?;

    println!("Things:");

    for thing in resp.things.unwrap() {
        println!(
            "  Name:  {}",
            thing.thing_name.as_deref().unwrap_or_default()
        );
        println!(
            "  Type:  {}",
            thing.thing_type_name.as_deref().unwrap_or_default()
        );
        println!(
            "  ARN:   {}",
            thing.thing_arn.as_deref().unwrap_or_default()
        );
        println!();
    }

    println!();

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListThings](https://docs.rs/aws-sdk-iot/latest/aws_sdk_iot/client/struct.Client.html#method.list_things)」を参照してください。

# SDK for Rust を使用した Kinesis の例
<a name="rust_1_kinesis_code_examples"></a>

次のコード例は、Kinesis で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateStream`
<a name="kinesis_CreateStream_rust_1_topic"></a>

次のコード例は、`CreateStream` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kinesis#code-examples)での設定と実行の方法を確認してください。

```
async fn make_stream(client: &Client, stream: &str) -> Result<(), Error> {
    client
        .create_stream()
        .stream_name(stream)
        .shard_count(4)
        .send()
        .await?;

    println!("Created stream");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CreateStream](https://docs.rs/aws-sdk-kinesis/latest/aws_sdk_kinesis/client/struct.Client.html#method.create_stream)」を参照してください。

### `DeleteStream`
<a name="kinesis_DeleteStream_rust_1_topic"></a>

次のコード例は、`DeleteStream` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kinesis#code-examples)での設定と実行の方法を確認してください。

```
async fn remove_stream(client: &Client, stream: &str) -> Result<(), Error> {
    client.delete_stream().stream_name(stream).send().await?;

    println!("Deleted stream.");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DeleteStream](https://docs.rs/aws-sdk-kinesis/latest/aws_sdk_kinesis/client/struct.Client.html#method.delete_stream)」を参照してください。

### `DescribeStream`
<a name="kinesis_DescribeStream_rust_1_topic"></a>

次のコード例は、`DescribeStream` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kinesis#code-examples)での設定と実行の方法を確認してください。

```
async fn show_stream(client: &Client, stream: &str) -> Result<(), Error> {
    let resp = client.describe_stream().stream_name(stream).send().await?;

    let desc = resp.stream_description.unwrap();

    println!("Stream description:");
    println!("  Name:              {}:", desc.stream_name());
    println!("  Status:            {:?}", desc.stream_status());
    println!("  Open shards:       {:?}", desc.shards.len());
    println!("  Retention (hours): {}", desc.retention_period_hours());
    println!("  Encryption:        {:?}", desc.encryption_type.unwrap());

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeStream](https://docs.rs/aws-sdk-kinesis/latest/aws_sdk_kinesis/client/struct.Client.html#method.describe_stream)」を参照してください。

### `ListStreams`
<a name="kinesis_ListStreams_rust_1_topic"></a>

次のコード例は、`ListStreams` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kinesis#code-examples)での設定と実行の方法を確認してください。

```
async fn show_streams(client: &Client) -> Result<(), Error> {
    let resp = client.list_streams().send().await?;

    println!("Stream names:");

    let streams = resp.stream_names;
    for stream in &streams {
        println!("  {}", stream);
    }

    println!("Found {} stream(s)", streams.len());

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListStreams](https://docs.rs/aws-sdk-kinesis/latest/aws_sdk_kinesis/client/struct.Client.html#method.list_streams)」を参照してください。

### `PutRecord`
<a name="kinesis_PutRecord_rust_1_topic"></a>

次のコード例は、`PutRecord` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kinesis#code-examples)での設定と実行の方法を確認してください。

```
async fn add_record(client: &Client, stream: &str, key: &str, data: &str) -> Result<(), Error> {
    let blob = Blob::new(data);

    client
        .put_record()
        .data(blob)
        .partition_key(key)
        .stream_name(stream)
        .send()
        .await?;

    println!("Put data into stream.");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[PutRecord](https://docs.rs/aws-sdk-kinesis/latest/aws_sdk_kinesis/client/struct.Client.html#method.put_record)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_rust_1_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::kinesis::KinesisEvent;
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn function_handler(event: LambdaEvent<KinesisEvent>) -> Result<(), Error> {
    if event.payload.records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(());
    }

    event.payload.records.iter().for_each(|record| {
        tracing::info!("EventId: {}",record.event_id.as_deref().unwrap_or_default());

        let record_data = std::str::from_utf8(&record.kinesis.data);

        match record_data {
            Ok(data) => {
                // log the record data
                tracing::info!("Data: {}", data);
            }
            Err(e) => {
                tracing::error!("Error: {}", e);
            }
        }
    });

    tracing::info!(
        "Successfully processed {} records",
        event.payload.records.len()
    );

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_rust_1_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::{
    event::kinesis::KinesisEvent,
    kinesis::KinesisEventRecord,
    streams::{KinesisBatchItemFailure, KinesisEventResponse},
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn function_handler(event: LambdaEvent<KinesisEvent>) -> Result<KinesisEventResponse, Error> {
    let mut response = KinesisEventResponse {
        batch_item_failures: vec![],
    };

    if event.payload.records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(response);
    }

    for record in &event.payload.records {
        tracing::info!(
            "EventId: {}",
            record.event_id.as_deref().unwrap_or_default()
        );

        let record_processing_result = process_record(record);

        if record_processing_result.is_err() {
            response.batch_item_failures.push(KinesisBatchItemFailure {
                item_identifier: record.kinesis.sequence_number.clone(),
            });
            /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
            return Ok(response);
        }
    }

    tracing::info!(
        "Successfully processed {} records",
        event.payload.records.len()
    );

    Ok(response)
}

fn process_record(record: &KinesisEventRecord) -> Result<(), Error> {
    let record_data = std::str::from_utf8(record.kinesis.data.as_slice());

    if let Some(err) = record_data.err() {
        tracing::error!("Error: {}", err);
        return Err(Error::from(err));
    }

    let record_data = record_data.unwrap_or_default();

    // do something interesting with the data
    tracing::info!("Data: {}", record_data);

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

# AWS KMS SDK for Rust を使用した の例
<a name="rust_1_kms_code_examples"></a>

次のコード例は、 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateKey`
<a name="kms_CreateKey_rust_1_topic"></a>

次のコード例は、`CreateKey` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn make_key(client: &Client) -> Result<(), Error> {
    let resp = client.create_key().send().await?;

    let id = resp.key_metadata.as_ref().unwrap().key_id();

    println!("Key: {}", id);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CreateKey](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.create_key)」を参照してください。

### `Decrypt`
<a name="kms_Decrypt_rust_1_topic"></a>

次のコード例は、`Decrypt` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn decrypt_key(client: &Client, key: &str, filename: &str) -> Result<(), Error> {
    // Open input text file and get contents as a string
    // input is a base-64 encoded string, so decode it:
    let data = fs::read_to_string(filename)
        .map(|input| {
            base64::decode(input).expect("Input file does not contain valid base 64 characters.")
        })
        .map(Blob::new);

    let resp = client
        .decrypt()
        .key_id(key)
        .ciphertext_blob(data.unwrap())
        .send()
        .await?;

    let inner = resp.plaintext.unwrap();
    let bytes = inner.as_ref();

    let s = String::from_utf8(bytes.to_vec()).expect("Could not convert to UTF-8");

    println!();
    println!("Decoded string:");
    println!("{}", s);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[Decrypt](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.decrypt)」を参照してください。

### `Encrypt`
<a name="kms_Encrypt_rust_1_topic"></a>

次のコード例は、`Encrypt` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn encrypt_string(
    verbose: bool,
    client: &Client,
    text: &str,
    key: &str,
    out_file: &str,
) -> Result<(), Error> {
    let blob = Blob::new(text.as_bytes());

    let resp = client.encrypt().key_id(key).plaintext(blob).send().await?;

    // Did we get an encrypted blob?
    let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
    let bytes = blob.as_ref();

    let s = base64::encode(bytes);

    let mut ofile = File::create(out_file).expect("unable to create file");
    ofile.write_all(s.as_bytes()).expect("unable to write");

    if verbose {
        println!("Wrote the following to {:?}", out_file);
        println!("{}", s);
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[Encrypt](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.encrypt)」を参照してください。

### `GenerateDataKey`
<a name="kms_GenerateDataKey_rust_1_topic"></a>

次のコード例は、`GenerateDataKey` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn make_key(client: &Client, key: &str) -> Result<(), Error> {
    let resp = client
        .generate_data_key()
        .key_id(key)
        .key_spec(DataKeySpec::Aes256)
        .send()
        .await?;

    // Did we get an encrypted blob?
    let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
    let bytes = blob.as_ref();

    let s = base64::encode(bytes);

    println!();
    println!("Data key:");
    println!("{}", s);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[GenerateDataKey](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.generate_data_key)」を参照してください。

### `GenerateDataKeyWithoutPlaintext`
<a name="kms_GenerateDataKeyWithoutPlaintext_rust_1_topic"></a>

次のコード例は、`GenerateDataKeyWithoutPlaintext` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn make_key(client: &Client, key: &str) -> Result<(), Error> {
    let resp = client
        .generate_data_key_without_plaintext()
        .key_id(key)
        .key_spec(DataKeySpec::Aes256)
        .send()
        .await?;

    // Did we get an encrypted blob?
    let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
    let bytes = blob.as_ref();

    let s = base64::encode(bytes);

    println!();
    println!("Data key:");
    println!("{}", s);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[GenerateDataKeyWithoutPlaintext](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.generate_data_key_without_plaintext)」を参照してください。

### `GenerateRandom`
<a name="kms_GenerateRandom_rust_1_topic"></a>

次のコード例は、`GenerateRandom` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn make_string(client: &Client, length: i32) -> Result<(), Error> {
    let resp = client
        .generate_random()
        .number_of_bytes(length)
        .send()
        .await?;

    // Did we get an encrypted blob?
    let blob = resp.plaintext.expect("Could not get encrypted text");
    let bytes = blob.as_ref();

    let s = base64::encode(bytes);

    println!();
    println!("Data key:");
    println!("{}", s);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[GenerateRandom](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.generate_random)」を参照してください。

### `ListKeys`
<a name="kms_ListKeys_rust_1_topic"></a>

次のコード例は、`ListKeys` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn show_keys(client: &Client) -> Result<(), Error> {
    let resp = client.list_keys().send().await?;

    let keys = resp.keys.unwrap_or_default();

    let len = keys.len();

    for key in keys {
        println!("Key ARN: {}", key.key_arn.as_deref().unwrap_or_default());
    }

    println!();
    println!("Found {} keys", len);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListKeys](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.list_keys)」を参照してください。

### `ReEncrypt`
<a name="kms_ReEncrypt_rust_1_topic"></a>

次のコード例は、`ReEncrypt` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/kms#code-examples)での設定と実行の方法を確認してください。

```
async fn reencrypt_string(
    verbose: bool,
    client: &Client,
    input_file: &str,
    output_file: &str,
    first_key: &str,
    new_key: &str,
) -> Result<(), Error> {
    // Get blob from input file
    // Open input text file and get contents as a string
    // input is a base-64 encoded string, so decode it:
    let data = fs::read_to_string(input_file)
        .map(|input_file| base64::decode(input_file).expect("invalid base 64"))
        .map(Blob::new);

    let resp = client
        .re_encrypt()
        .ciphertext_blob(data.unwrap())
        .source_key_id(first_key)
        .destination_key_id(new_key)
        .send()
        .await?;

    // Did we get an encrypted blob?
    let blob = resp.ciphertext_blob.expect("Could not get encrypted text");
    let bytes = blob.as_ref();

    let s = base64::encode(bytes);
    let o = &output_file;

    let mut ofile = File::create(o).expect("unable to create file");
    ofile.write_all(s.as_bytes()).expect("unable to write");

    if verbose {
        println!("Wrote the following to {}:", output_file);
        println!("{}", s);
    } else {
        println!("Wrote base64-encoded output to {}", output_file);
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ReEncrypt](https://docs.rs/aws-sdk-kms/latest/aws_sdk_kms/client/struct.Client.html#method.re_encrypt)」を参照してください。

# SDK for Rust を使用した Lambda の例
<a name="rust_1_lambda_code_examples"></a>

次のコード例は、Lambda で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

*AWS コミュニティへの貢献*は、複数のチームが作成し、維持している例です AWS。フィードバックを提供するには、リンクされたリポジトリで提供されているメカニズムを使用します。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)
+ [AWS コミュニティへの貢献](#aws_community_contributions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。
このシナリオで使用した依存関係を含む Cargo.toml。  

```
[package]
name = "lambda-code-examples"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
aws-config = { version = "1.0.1", features = ["behavior-version-latest"] }
aws-sdk-ec2 = { version = "1.3.0" }
aws-sdk-iam = { version = "1.3.0" }
aws-sdk-lambda = { version = "1.3.0" }
aws-sdk-s3 = { version = "1.4.0" }
aws-smithy-types = { version = "1.0.1" }
aws-types = { version = "1.0.1" }
clap = { version = "4.4", features = ["derive"] }
tokio = { version = "1.20.1", features = ["full"] }
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }
tracing = "0.1.37"
serde_json = "1.0.94"
anyhow = "1.0.71"
uuid = { version = "1.3.3", features = ["v4"] }
lambda_runtime = "0.8.0"
serde = "1.0.164"
```
このシナリオの Lambda 呼び出しを効率化するユーティリティのコレクション。このファイルはクレート内の src/ations.rs というファイルです。  

```
use anyhow::anyhow;
use aws_sdk_iam::operation::{create_role::CreateRoleError, delete_role::DeleteRoleOutput};
use aws_sdk_lambda::{
    operation::{
        delete_function::DeleteFunctionOutput, get_function::GetFunctionOutput,
        invoke::InvokeOutput, list_functions::ListFunctionsOutput,
        update_function_code::UpdateFunctionCodeOutput,
        update_function_configuration::UpdateFunctionConfigurationOutput,
    },
    primitives::ByteStream,
    types::{Environment, FunctionCode, LastUpdateStatus, State},
};
use aws_sdk_s3::{
    error::ErrorMetadata,
    operation::{delete_bucket::DeleteBucketOutput, delete_object::DeleteObjectOutput},
    types::CreateBucketConfiguration,
};
use aws_smithy_types::Blob;
use serde::{ser::SerializeMap, Serialize};
use std::{fmt::Display, path::PathBuf, str::FromStr, time::Duration};
use tracing::{debug, info, warn};

/* Operation describes  */
#[derive(Clone, Copy, Debug, Serialize)]
pub enum Operation {
    #[serde(rename = "plus")]
    Plus,
    #[serde(rename = "minus")]
    Minus,
    #[serde(rename = "times")]
    Times,
    #[serde(rename = "divided-by")]
    DividedBy,
}

impl FromStr for Operation {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "plus" => Ok(Operation::Plus),
            "minus" => Ok(Operation::Minus),
            "times" => Ok(Operation::Times),
            "divided-by" => Ok(Operation::DividedBy),
            _ => Err(anyhow!("Unknown operation {s}")),
        }
    }
}

impl Display for Operation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Operation::Plus => write!(f, "plus"),
            Operation::Minus => write!(f, "minus"),
            Operation::Times => write!(f, "times"),
            Operation::DividedBy => write!(f, "divided-by"),
        }
    }
}

/**
 * InvokeArgs will be serialized as JSON and sent to the AWS Lambda handler.
 */
#[derive(Debug)]
pub enum InvokeArgs {
    Increment(i32),
    Arithmetic(Operation, i32, i32),
}

impl Serialize for InvokeArgs {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            InvokeArgs::Increment(i) => serializer.serialize_i32(*i),
            InvokeArgs::Arithmetic(o, i, j) => {
                let mut map: S::SerializeMap = serializer.serialize_map(Some(3))?;
                map.serialize_key(&"op".to_string())?;
                map.serialize_value(&o.to_string())?;
                map.serialize_key(&"i".to_string())?;
                map.serialize_value(&i)?;
                map.serialize_key(&"j".to_string())?;
                map.serialize_value(&j)?;
                map.end()
            }
        }
    }
}

/** A policy document allowing Lambda to execute this function on the account's behalf. */
const ROLE_POLICY_DOCUMENT: &str = r#"{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": { "Service": "lambda.amazonaws.com" },
            "Action": "sts:AssumeRole"
        }
    ]
}"#;

/**
 * A LambdaManager gathers all the resources necessary to run the Lambda example scenario.
 * This includes instantiated aws_sdk clients and details of resource names.
 */
pub struct LambdaManager {
    iam_client: aws_sdk_iam::Client,
    lambda_client: aws_sdk_lambda::Client,
    s3_client: aws_sdk_s3::Client,
    lambda_name: String,
    role_name: String,
    bucket: String,
    own_bucket: bool,
}

// These unit type structs provide nominal typing on top of String parameters for LambdaManager::new
pub struct LambdaName(pub String);
pub struct RoleName(pub String);
pub struct Bucket(pub String);
pub struct OwnBucket(pub bool);

impl LambdaManager {
    pub fn new(
        iam_client: aws_sdk_iam::Client,
        lambda_client: aws_sdk_lambda::Client,
        s3_client: aws_sdk_s3::Client,
        lambda_name: LambdaName,
        role_name: RoleName,
        bucket: Bucket,
        own_bucket: OwnBucket,
    ) -> Self {
        Self {
            iam_client,
            lambda_client,
            s3_client,
            lambda_name: lambda_name.0,
            role_name: role_name.0,
            bucket: bucket.0,
            own_bucket: own_bucket.0,
        }
    }

    /**
     * Load the AWS configuration from the environment.
     * Look up lambda_name and bucket if none are given, or generate a random name if not present in the environment.
     * If the bucket name is provided, the caller needs to have created the bucket.
     * If the bucket name is generated, it will be created.
     */
    pub async fn load_from_env(lambda_name: Option<String>, bucket: Option<String>) -> Self {
        let sdk_config = aws_config::load_from_env().await;
        let lambda_name = LambdaName(lambda_name.unwrap_or_else(|| {
            std::env::var("LAMBDA_NAME").unwrap_or_else(|_| "rust_lambda_example".to_string())
        }));
        let role_name = RoleName(format!("{}_role", lambda_name.0));
        let (bucket, own_bucket) =
            match bucket {
                Some(bucket) => (Bucket(bucket), false),
                None => (
                    Bucket(std::env::var("LAMBDA_BUCKET").unwrap_or_else(|_| {
                        format!("rust-lambda-example-{}", uuid::Uuid::new_v4())
                    })),
                    true,
                ),
            };

        let s3_client = aws_sdk_s3::Client::new(&sdk_config);

        if own_bucket {
            info!("Creating bucket for demo: {}", bucket.0);
            s3_client
                .create_bucket()
                .bucket(bucket.0.clone())
                .create_bucket_configuration(
                    CreateBucketConfiguration::builder()
                        .location_constraint(aws_sdk_s3::types::BucketLocationConstraint::from(
                            sdk_config.region().unwrap().as_ref(),
                        ))
                        .build(),
                )
                .send()
                .await
                .unwrap();
        }

        Self::new(
            aws_sdk_iam::Client::new(&sdk_config),
            aws_sdk_lambda::Client::new(&sdk_config),
            s3_client,
            lambda_name,
            role_name,
            bucket,
            OwnBucket(own_bucket),
        )
    }

    /**
     * Upload function code from a path to a zip file.
     * The zip file must have an AL2 Linux-compatible binary called `bootstrap`.
     * The easiest way to create such a zip is to use `cargo lambda build --output-format Zip`.
     */
    async fn prepare_function(
        &self,
        zip_file: PathBuf,
        key: Option<String>,
    ) -> Result<FunctionCode, anyhow::Error> {
        let body = ByteStream::from_path(zip_file).await?;

        let key = key.unwrap_or_else(|| format!("{}_code", self.lambda_name));

        info!("Uploading function code to s3://{}/{}", self.bucket, key);
        let _ = self
            .s3_client
            .put_object()
            .bucket(self.bucket.clone())
            .key(key.clone())
            .body(body)
            .send()
            .await?;

        Ok(FunctionCode::builder()
            .s3_bucket(self.bucket.clone())
            .s3_key(key)
            .build())
    }

    /**
     * Create a function, uploading from a zip file.
     */
    pub async fn create_function(&self, zip_file: PathBuf) -> Result<String, anyhow::Error> {
        let code = self.prepare_function(zip_file, None).await?;

        let key = code.s3_key().unwrap().to_string();

        let role = self.create_role().await.map_err(|e| anyhow!(e))?;

        info!("Created iam role, waiting 15s for it to become active");
        tokio::time::sleep(Duration::from_secs(15)).await;

        info!("Creating lambda function {}", self.lambda_name);
        let _ = self
            .lambda_client
            .create_function()
            .function_name(self.lambda_name.clone())
            .code(code)
            .role(role.arn())
            .runtime(aws_sdk_lambda::types::Runtime::Providedal2)
            .handler("_unused")
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        self.lambda_client
            .publish_version()
            .function_name(self.lambda_name.clone())
            .send()
            .await?;

        Ok(key)
    }

    /**
     * Create an IAM execution role for the managed Lambda function.
     * If the role already exists, use that instead.
     */
    async fn create_role(&self) -> Result<aws_sdk_iam::types::Role, CreateRoleError> {
        info!("Creating execution role for function");
        let get_role = self
            .iam_client
            .get_role()
            .role_name(self.role_name.clone())
            .send()
            .await;
        if let Ok(get_role) = get_role {
            if let Some(role) = get_role.role {
                return Ok(role);
            }
        }

        let create_role = self
            .iam_client
            .create_role()
            .role_name(self.role_name.clone())
            .assume_role_policy_document(ROLE_POLICY_DOCUMENT)
            .send()
            .await;

        match create_role {
            Ok(create_role) => match create_role.role {
                Some(role) => Ok(role),
                None => Err(CreateRoleError::generic(
                    ErrorMetadata::builder()
                        .message("CreateRole returned empty success")
                        .build(),
                )),
            },
            Err(err) => Err(err.into_service_error()),
        }
    }

    /**
     * Poll `is_function_ready` with a 1-second delay. It returns when the function is ready or when there's an error checking the function's state.
     */
    pub async fn wait_for_function_ready(&self) -> Result<(), anyhow::Error> {
        info!("Waiting for function");
        while !self.is_function_ready(None).await? {
            info!("Function is not ready, sleeping 1s");
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
        Ok(())
    }

    /**
     * Check if a Lambda function is ready to be invoked.
     * A Lambda function is ready for this scenario when its state is active and its LastUpdateStatus is Successful.
     * Additionally, if a sha256 is provided, the function must have that as its current code hash.
     * Any missing properties or failed requests will be reported as an Err.
     */
    async fn is_function_ready(
        &self,
        expected_code_sha256: Option<&str>,
    ) -> Result<bool, anyhow::Error> {
        match self.get_function().await {
            Ok(func) => {
                if let Some(config) = func.configuration() {
                    if let Some(state) = config.state() {
                        info!(?state, "Checking if function is active");
                        if !matches!(state, State::Active) {
                            return Ok(false);
                        }
                    }
                    match config.last_update_status() {
                        Some(last_update_status) => {
                            info!(?last_update_status, "Checking if function is ready");
                            match last_update_status {
                                LastUpdateStatus::Successful => {
                                    // continue
                                }
                                LastUpdateStatus::Failed | LastUpdateStatus::InProgress => {
                                    return Ok(false);
                                }
                                unknown => {
                                    warn!(
                                        status_variant = unknown.as_str(),
                                        "LastUpdateStatus unknown"
                                    );
                                    return Err(anyhow!(
                                        "Unknown LastUpdateStatus, fn config is {config:?}"
                                    ));
                                }
                            }
                        }
                        None => {
                            warn!("Missing last update status");
                            return Ok(false);
                        }
                    };
                    if expected_code_sha256.is_none() {
                        return Ok(true);
                    }
                    if let Some(code_sha256) = config.code_sha256() {
                        return Ok(code_sha256 == expected_code_sha256.unwrap_or_default());
                    }
                }
            }
            Err(e) => {
                warn!(?e, "Could not get function while waiting");
            }
        }
        Ok(false)
    }

    /** Get the Lambda function with this Manager's name. */
    pub async fn get_function(&self) -> Result<GetFunctionOutput, anyhow::Error> {
        info!("Getting lambda function");
        self.lambda_client
            .get_function()
            .function_name(self.lambda_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from)
    }

    /** List all Lambda functions in the current Region. */
    pub async fn list_functions(&self) -> Result<ListFunctionsOutput, anyhow::Error> {
        info!("Listing lambda functions");
        self.lambda_client
            .list_functions()
            .send()
            .await
            .map_err(anyhow::Error::from)
    }

    /** Invoke the lambda function using calculator InvokeArgs. */
    pub async fn invoke(&self, args: InvokeArgs) -> Result<InvokeOutput, anyhow::Error> {
        info!(?args, "Invoking {}", self.lambda_name);
        let payload = serde_json::to_string(&args)?;
        debug!(?payload, "Sending payload");
        self.lambda_client
            .invoke()
            .function_name(self.lambda_name.clone())
            .payload(Blob::new(payload))
            .send()
            .await
            .map_err(anyhow::Error::from)
    }

    /** Given a Path to a zip file, update the function's code and wait for the update to finish. */
    pub async fn update_function_code(
        &self,
        zip_file: PathBuf,
        key: String,
    ) -> Result<UpdateFunctionCodeOutput, anyhow::Error> {
        let function_code = self.prepare_function(zip_file, Some(key)).await?;

        info!("Updating code for {}", self.lambda_name);
        let update = self
            .lambda_client
            .update_function_code()
            .function_name(self.lambda_name.clone())
            .s3_bucket(self.bucket.clone())
            .s3_key(function_code.s3_key().unwrap().to_string())
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        Ok(update)
    }

    /** Update the environment for a function. */
    pub async fn update_function_configuration(
        &self,
        environment: Environment,
    ) -> Result<UpdateFunctionConfigurationOutput, anyhow::Error> {
        info!(
            ?environment,
            "Updating environment for {}", self.lambda_name
        );
        let updated = self
            .lambda_client
            .update_function_configuration()
            .function_name(self.lambda_name.clone())
            .environment(environment)
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        Ok(updated)
    }

    /** Delete a function and its role, and if possible or necessary, its associated code object and bucket. */
    pub async fn delete_function(
        &self,
        location: Option<String>,
    ) -> (
        Result<DeleteFunctionOutput, anyhow::Error>,
        Result<DeleteRoleOutput, anyhow::Error>,
        Option<Result<DeleteObjectOutput, anyhow::Error>>,
    ) {
        info!("Deleting lambda function {}", self.lambda_name);
        let delete_function = self
            .lambda_client
            .delete_function()
            .function_name(self.lambda_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from);

        info!("Deleting iam role {}", self.role_name);
        let delete_role = self
            .iam_client
            .delete_role()
            .role_name(self.role_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from);

        let delete_object: Option<Result<DeleteObjectOutput, anyhow::Error>> =
            if let Some(location) = location {
                info!("Deleting object {location}");
                Some(
                    self.s3_client
                        .delete_object()
                        .bucket(self.bucket.clone())
                        .key(location)
                        .send()
                        .await
                        .map_err(anyhow::Error::from),
                )
            } else {
                info!(?location, "Skipping delete object");
                None
            };

        (delete_function, delete_role, delete_object)
    }

    pub async fn cleanup(
        &self,
        location: Option<String>,
    ) -> (
        (
            Result<DeleteFunctionOutput, anyhow::Error>,
            Result<DeleteRoleOutput, anyhow::Error>,
            Option<Result<DeleteObjectOutput, anyhow::Error>>,
        ),
        Option<Result<DeleteBucketOutput, anyhow::Error>>,
    ) {
        let delete_function = self.delete_function(location).await;

        let delete_bucket = if self.own_bucket {
            info!("Deleting bucket {}", self.bucket);
            if delete_function.2.is_none() || delete_function.2.as_ref().unwrap().is_ok() {
                Some(
                    self.s3_client
                        .delete_bucket()
                        .bucket(self.bucket.clone())
                        .send()
                        .await
                        .map_err(anyhow::Error::from),
                )
            } else {
                None
            }
        } else {
            info!("No bucket to clean up");
            None
        };

        (delete_function, delete_bucket)
    }
}

/**
 * Testing occurs primarily as an integration test running the `scenario` bin successfully.
 * Each action relies deeply on the internal workings and state of Amazon Simple Storage Service (Amazon S3), Lambda, and IAM working together.
 * It is therefore infeasible to mock the clients to test the individual actions.
 */
#[cfg(test)]
mod test {
    use super::{InvokeArgs, Operation};
    use serde_json::json;

    /** Make sure that the JSON output of serializing InvokeArgs is what's expected by the calculator. */
    #[test]
    fn test_serialize() {
        assert_eq!(json!(InvokeArgs::Increment(5)), 5);
        assert_eq!(
            json!(InvokeArgs::Arithmetic(Operation::Plus, 5, 7)).to_string(),
            r#"{"op":"plus","i":5,"j":7}"#.to_string(),
        );
    }
}
```
コマンドラインフラグを使用して一部の動作を制御し、シナリオを最初から最後まで実行するためのバイナリ。このファイルはクレート内の src/bin/scenario.rs というファイルです。  

```
/*
## Service actions

Service actions wrap the SDK call, taking a client and any specific parameters necessary for the call.

* CreateFunction
* GetFunction
* ListFunctions
* Invoke
* UpdateFunctionCode
* UpdateFunctionConfiguration
* DeleteFunction

## Scenario
A scenario runs at a command prompt and prints output to the user on the result of each service action. A scenario can run in one of two ways: straight through, printing out progress as it goes, or as an interactive question/answer script.

## Getting started with functions

Use an SDK to manage AWS Lambda functions: create a function, invoke it, update its code, invoke it again, view its output and logs, and delete it.

This scenario uses two Lambda handlers:
_Note: Handlers don't use AWS SDK API calls._

The increment handler is straightforward:

1. It accepts a number, increments it, and returns the new value.
2. It performs simple logging of the result.

The arithmetic handler is more complex:
1. It accepts a set of actions ['plus', 'minus', 'times', 'divided-by'] and two numbers, and returns the result of the calculation.
2. It uses an environment variable to control log level (such as DEBUG, INFO, WARNING, ERROR).
It logs a few things at different levels, such as:
    * DEBUG: Full event data.
    * INFO: The calculation result.
    * WARN~ING~: When a divide by zero error occurs.
    * This will be the typical `RUST_LOG` variable.


The steps of the scenario are:

1. Create an AWS Identity and Access Management (IAM) role that meets the following requirements:
    * Has an assume_role policy that grants 'lambda.amazonaws.com' the 'sts:AssumeRole' action.
    * Attaches the 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole' managed role.
    * _You must wait for ~10 seconds after the role is created before you can use it!_
2. Create a function (CreateFunction) for the increment handler by packaging it as a zip and doing one of the following:
    * Adding it with CreateFunction Code.ZipFile.
    * --or--
    * Uploading it to Amazon Simple Storage Service (Amazon S3) and adding it with CreateFunction Code.S3Bucket/S3Key.
    * _Note: Zipping the file does not have to be done in code._
    * If you have a waiter, use it to wait until the function is active. Otherwise, call GetFunction until State is Active.
3. Invoke the function with a number and print the result.
4. Update the function (UpdateFunctionCode) to the arithmetic handler by packaging it as a zip and doing one of the following:
    * Adding it with UpdateFunctionCode ZipFile.
    * --or--
    * Uploading it to Amazon S3 and adding it with UpdateFunctionCode S3Bucket/S3Key.
5. Call GetFunction until Configuration.LastUpdateStatus is 'Successful' (or 'Failed').
6. Update the environment variable by calling UpdateFunctionConfiguration and pass it a log level, such as:
    * Environment={'Variables': {'RUST_LOG': 'TRACE'}}
7. Invoke the function with an action from the list and a couple of values. Include LogType='Tail' to get logs in the result. Print the result of the calculation and the log.
8. [Optional] Invoke the function to provoke a divide-by-zero error and show the log result.
9. List all functions for the account, using pagination (ListFunctions).
10. Delete the function (DeleteFunction).
11. Delete the role.

Each step should use the function created in Service Actions to abstract calling the SDK.
 */

use aws_sdk_lambda::{operation::invoke::InvokeOutput, types::Environment};
use clap::Parser;
use std::{collections::HashMap, path::PathBuf};
use tracing::{debug, info, warn};
use tracing_subscriber::EnvFilter;

use lambda_code_examples::actions::{
    InvokeArgs::{Arithmetic, Increment},
    LambdaManager, Operation,
};

#[derive(Debug, Parser)]
pub struct Opt {
    /// The AWS Region.
    #[structopt(short, long)]
    pub region: Option<String>,

    // The bucket to use for the FunctionCode.
    #[structopt(short, long)]
    pub bucket: Option<String>,

    // The name of the Lambda function.
    #[structopt(short, long)]
    pub lambda_name: Option<String>,

    // The number to increment.
    #[structopt(short, long, default_value = "12")]
    pub inc: i32,

    // The left operand.
    #[structopt(long, default_value = "19")]
    pub num_a: i32,

    // The right operand.
    #[structopt(long, default_value = "23")]
    pub num_b: i32,

    // The arithmetic operation.
    #[structopt(short, long, default_value = "plus")]
    pub operation: Operation,

    #[structopt(long)]
    pub cleanup: Option<bool>,

    #[structopt(long)]
    pub no_cleanup: Option<bool>,
}

fn code_path(lambda: &str) -> PathBuf {
    PathBuf::from(format!("../target/lambda/{lambda}/bootstrap.zip"))
}

fn log_invoke_output(invoke: &InvokeOutput, message: &str) {
    if let Some(payload) = invoke.payload().cloned() {
        let payload = String::from_utf8(payload.into_inner());
        info!(?payload, message);
    } else {
        info!("Could not extract payload")
    }
    if let Some(logs) = invoke.log_result() {
        debug!(?logs, "Invoked function logs")
    } else {
        debug!("Invoked function had no logs")
    }
}

async fn main_block(
    opt: &Opt,
    manager: &LambdaManager,
    code_location: String,
) -> Result<(), anyhow::Error> {
    let invoke = manager.invoke(Increment(opt.inc)).await?;
    log_invoke_output(&invoke, "Invoked function configured as increment");

    let update_code = manager
        .update_function_code(code_path("arithmetic"), code_location.clone())
        .await?;

    let code_sha256 = update_code.code_sha256().unwrap_or("Unknown SHA");
    info!(?code_sha256, "Updated function code with arithmetic.zip");

    let arithmetic_args = Arithmetic(opt.operation, opt.num_a, opt.num_b);
    let invoke = manager.invoke(arithmetic_args).await?;
    log_invoke_output(&invoke, "Invoked function configured as arithmetic");

    let update = manager
        .update_function_configuration(
            Environment::builder()
                .set_variables(Some(HashMap::from([(
                    "RUST_LOG".to_string(),
                    "trace".to_string(),
                )])))
                .build(),
        )
        .await?;
    let updated_environment = update.environment();
    info!(?updated_environment, "Updated function configuration");

    let invoke = manager
        .invoke(Arithmetic(opt.operation, opt.num_a, opt.num_b))
        .await?;
    log_invoke_output(
        &invoke,
        "Invoked function configured as arithmetic with increased logging",
    );

    let invoke = manager
        .invoke(Arithmetic(Operation::DividedBy, opt.num_a, 0))
        .await?;
    log_invoke_output(
        &invoke,
        "Invoked function configured as arithmetic with divide by zero",
    );

    Ok::<(), anyhow::Error>(())
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .without_time()
        .with_file(true)
        .with_line_number(true)
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    let opt = Opt::parse();
    let manager = LambdaManager::load_from_env(opt.lambda_name.clone(), opt.bucket.clone()).await;

    let key = match manager.create_function(code_path("increment")).await {
        Ok(init) => {
            info!(?init, "Created function, initially with increment.zip");
            let run_block = main_block(&opt, &manager, init.clone()).await;
            info!(?run_block, "Finished running example, cleaning up");
            Some(init)
        }
        Err(err) => {
            warn!(?err, "Error happened when initializing function");
            None
        }
    };

    if Some(false) == opt.cleanup || Some(true) == opt.no_cleanup {
        info!("Skipping cleanup")
    } else {
        let delete = manager.cleanup(key).await;
        info!(?delete, "Deleted function & cleaned up resources");
    }
}
```
+ API の詳細については、「AWS SDK for Rust API リファレンス」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.create_function)
  + [DeleteFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.delete_function)
  + [GetFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.get_function)
  + [Invoke](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.invoke)
  + [ListFunctions](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.list_functions)
  + [UpdateFunctionCode](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.update_function_code)
  + [UpdateFunctionConfiguration](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.update_function_configuration)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_rust_1_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /**
     * Create a function, uploading from a zip file.
     */
    pub async fn create_function(&self, zip_file: PathBuf) -> Result<String, anyhow::Error> {
        let code = self.prepare_function(zip_file, None).await?;

        let key = code.s3_key().unwrap().to_string();

        let role = self.create_role().await.map_err(|e| anyhow!(e))?;

        info!("Created iam role, waiting 15s for it to become active");
        tokio::time::sleep(Duration::from_secs(15)).await;

        info!("Creating lambda function {}", self.lambda_name);
        let _ = self
            .lambda_client
            .create_function()
            .function_name(self.lambda_name.clone())
            .code(code)
            .role(role.arn())
            .runtime(aws_sdk_lambda::types::Runtime::Providedal2)
            .handler("_unused")
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        self.lambda_client
            .publish_version()
            .function_name(self.lambda_name.clone())
            .send()
            .await?;

        Ok(key)
    }

    /**
     * Upload function code from a path to a zip file.
     * The zip file must have an AL2 Linux-compatible binary called `bootstrap`.
     * The easiest way to create such a zip is to use `cargo lambda build --output-format Zip`.
     */
    async fn prepare_function(
        &self,
        zip_file: PathBuf,
        key: Option<String>,
    ) -> Result<FunctionCode, anyhow::Error> {
        let body = ByteStream::from_path(zip_file).await?;

        let key = key.unwrap_or_else(|| format!("{}_code", self.lambda_name));

        info!("Uploading function code to s3://{}/{}", self.bucket, key);
        let _ = self
            .s3_client
            .put_object()
            .bucket(self.bucket.clone())
            .key(key.clone())
            .body(body)
            .send()
            .await?;

        Ok(FunctionCode::builder()
            .s3_bucket(self.bucket.clone())
            .s3_key(key)
            .build())
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.create_function)」を参照してください。

### `DeleteFunction`
<a name="lambda_DeleteFunction_rust_1_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /** Delete a function and its role, and if possible or necessary, its associated code object and bucket. */
    pub async fn delete_function(
        &self,
        location: Option<String>,
    ) -> (
        Result<DeleteFunctionOutput, anyhow::Error>,
        Result<DeleteRoleOutput, anyhow::Error>,
        Option<Result<DeleteObjectOutput, anyhow::Error>>,
    ) {
        info!("Deleting lambda function {}", self.lambda_name);
        let delete_function = self
            .lambda_client
            .delete_function()
            .function_name(self.lambda_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from);

        info!("Deleting iam role {}", self.role_name);
        let delete_role = self
            .iam_client
            .delete_role()
            .role_name(self.role_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from);

        let delete_object: Option<Result<DeleteObjectOutput, anyhow::Error>> =
            if let Some(location) = location {
                info!("Deleting object {location}");
                Some(
                    self.s3_client
                        .delete_object()
                        .bucket(self.bucket.clone())
                        .key(location)
                        .send()
                        .await
                        .map_err(anyhow::Error::from),
                )
            } else {
                info!(?location, "Skipping delete object");
                None
            };

        (delete_function, delete_role, delete_object)
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.delete_function)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_rust_1_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /** Get the Lambda function with this Manager's name. */
    pub async fn get_function(&self) -> Result<GetFunctionOutput, anyhow::Error> {
        info!("Getting lambda function");
        self.lambda_client
            .get_function()
            .function_name(self.lambda_name.clone())
            .send()
            .await
            .map_err(anyhow::Error::from)
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[GetFunction](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.get_function)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_rust_1_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /** Invoke the lambda function using calculator InvokeArgs. */
    pub async fn invoke(&self, args: InvokeArgs) -> Result<InvokeOutput, anyhow::Error> {
        info!(?args, "Invoking {}", self.lambda_name);
        let payload = serde_json::to_string(&args)?;
        debug!(?payload, "Sending payload");
        self.lambda_client
            .invoke()
            .function_name(self.lambda_name.clone())
            .payload(Blob::new(payload))
            .send()
            .await
            .map_err(anyhow::Error::from)
    }

fn log_invoke_output(invoke: &InvokeOutput, message: &str) {
    if let Some(payload) = invoke.payload().cloned() {
        let payload = String::from_utf8(payload.into_inner());
        info!(?payload, message);
    } else {
        info!("Could not extract payload")
    }
    if let Some(logs) = invoke.log_result() {
        debug!(?logs, "Invoked function logs")
    } else {
        debug!("Invoked function had no logs")
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[Invoke](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.invoke)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_rust_1_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /** List all Lambda functions in the current Region. */
    pub async fn list_functions(&self) -> Result<ListFunctionsOutput, anyhow::Error> {
        info!("Listing lambda functions");
        self.lambda_client
            .list_functions()
            .send()
            .await
            .map_err(anyhow::Error::from)
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListFunctions](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.list_functions)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_rust_1_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /** Given a Path to a zip file, update the function's code and wait for the update to finish. */
    pub async fn update_function_code(
        &self,
        zip_file: PathBuf,
        key: String,
    ) -> Result<UpdateFunctionCodeOutput, anyhow::Error> {
        let function_code = self.prepare_function(zip_file, Some(key)).await?;

        info!("Updating code for {}", self.lambda_name);
        let update = self
            .lambda_client
            .update_function_code()
            .function_name(self.lambda_name.clone())
            .s3_bucket(self.bucket.clone())
            .s3_key(function_code.s3_key().unwrap().to_string())
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        Ok(update)
    }

    /**
     * Upload function code from a path to a zip file.
     * The zip file must have an AL2 Linux-compatible binary called `bootstrap`.
     * The easiest way to create such a zip is to use `cargo lambda build --output-format Zip`.
     */
    async fn prepare_function(
        &self,
        zip_file: PathBuf,
        key: Option<String>,
    ) -> Result<FunctionCode, anyhow::Error> {
        let body = ByteStream::from_path(zip_file).await?;

        let key = key.unwrap_or_else(|| format!("{}_code", self.lambda_name));

        info!("Uploading function code to s3://{}/{}", self.bucket, key);
        let _ = self
            .s3_client
            .put_object()
            .bucket(self.bucket.clone())
            .key(key.clone())
            .body(body)
            .send()
            .await?;

        Ok(FunctionCode::builder()
            .s3_bucket(self.bucket.clone())
            .s3_key(key)
            .build())
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[UpdateFunctionCode](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.update_function_code)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_rust_1_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/lambda#code-examples)での設定と実行の方法を確認してください。

```
    /** Update the environment for a function. */
    pub async fn update_function_configuration(
        &self,
        environment: Environment,
    ) -> Result<UpdateFunctionConfigurationOutput, anyhow::Error> {
        info!(
            ?environment,
            "Updating environment for {}", self.lambda_name
        );
        let updated = self
            .lambda_client
            .update_function_configuration()
            .function_name(self.lambda_name.clone())
            .environment(environment)
            .send()
            .await
            .map_err(anyhow::Error::from)?;

        self.wait_for_function_ready().await?;

        Ok(updated)
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[UpdateFunctionConfiguration](https://docs.rs/aws-sdk-lambda/latest/aws_sdk_lambda/client/struct.Client.html#method.update_function_configuration)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_rust_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Rust**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/cross_service/photo_asset_management) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_rust_1_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
use aws_config::BehaviorVersion;
use aws_credential_types::provider::ProvideCredentials;
use aws_sigv4::{
    http_request::{sign, SignableBody, SignableRequest, SigningSettings},
    sign::v4,
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};
use serde_json::{json, Value};
use sqlx::postgres::PgConnectOptions;
use std::env;
use std::time::{Duration, SystemTime};

const RDS_CERTS: &[u8] = include_bytes!("global-bundle.pem");

async fn generate_rds_iam_token(
    db_hostname: &str,
    port: u16,
    db_username: &str,
) -> Result<String, Error> {
    let config = aws_config::load_defaults(BehaviorVersion::v2024_03_28()).await;

    let credentials = config
        .credentials_provider()
        .expect("no credentials provider found")
        .provide_credentials()
        .await
        .expect("unable to load credentials");
    let identity = credentials.into();
    let region = config.region().unwrap().to_string();

    let mut signing_settings = SigningSettings::default();
    signing_settings.expires_in = Some(Duration::from_secs(900));
    signing_settings.signature_location = aws_sigv4::http_request::SignatureLocation::QueryParams;

    let signing_params = v4::SigningParams::builder()
        .identity(&identity)
        .region(&region)
        .name("rds-db")
        .time(SystemTime::now())
        .settings(signing_settings)
        .build()?;

    let url = format!(
        "https://{db_hostname}:{port}/?Action=connect&DBUser={db_user}",
        db_hostname = db_hostname,
        port = port,
        db_user = db_username
    );

    let signable_request =
        SignableRequest::new("GET", &url, std::iter::empty(), SignableBody::Bytes(&[]))
            .expect("signable request");

    let (signing_instructions, _signature) =
        sign(signable_request, &signing_params.into())?.into_parts();

    let mut url = url::Url::parse(&url).unwrap();
    for (name, value) in signing_instructions.params() {
        url.query_pairs_mut().append_pair(name, &value);
    }

    let response = url.to_string().split_off("https://".len());

    Ok(response)
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

async fn handler(_event: LambdaEvent<Value>) -> Result<Value, Error> {
    let db_host = env::var("DB_HOSTNAME").expect("DB_HOSTNAME must be set");
    let db_port = env::var("DB_PORT")
        .expect("DB_PORT must be set")
        .parse::<u16>()
        .expect("PORT must be a valid number");
    let db_name = env::var("DB_NAME").expect("DB_NAME must be set");
    let db_user_name = env::var("DB_USERNAME").expect("DB_USERNAME must be set");

    let token = generate_rds_iam_token(&db_host, db_port, &db_user_name).await?;

    let opts = PgConnectOptions::new()
        .host(&db_host)
        .port(db_port)
        .username(&db_user_name)
        .password(&token)
        .database(&db_name)
        .ssl_root_cert_from_pem(RDS_CERTS.to_vec())
        .ssl_mode(sqlx::postgres::PgSslMode::Require);

    let pool = sqlx::postgres::PgPoolOptions::new()
        .connect_with(opts)
        .await?;

    let result: i32 = sqlx::query_scalar("SELECT $1 + $2")
        .bind(3)
        .bind(2)
        .fetch_one(&pool)
        .await?;

    println!("Result: {:?}", result);

    Ok(json!({
        "statusCode": 200,
        "content-type": "text/plain",
        "body": format!("The selected sum is: {result}")
    }))
}
```

### Kinesis トリガーから Lambda 関数を呼び出す
<a name="serverless_Kinesis_Lambda_rust_1_topic"></a>

次のコード例では、Kinesis ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数は Kinesis ペイロードを取得し、それを Base64 からデコードして、そのレコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での Kinesis イベントの消費。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::kinesis::KinesisEvent;
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn function_handler(event: LambdaEvent<KinesisEvent>) -> Result<(), Error> {
    if event.payload.records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(());
    }

    event.payload.records.iter().for_each(|record| {
        tracing::info!("EventId: {}",record.event_id.as_deref().unwrap_or_default());

        let record_data = std::str::from_utf8(&record.kinesis.data);

        match record_data {
            Ok(data) => {
                // log the record data
                tracing::info!("Data: {}", data);
            }
            Err(e) => {
                tracing::error!("Error: {}", e);
            }
        }
    });

    tracing::info!(
        "Successfully processed {} records",
        event.payload.records.len()
    );

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

### DynamoDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DynamoDB_Lambda_rust_1_topic"></a>

次のコード例は、DynamoDB ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DynamoDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で DynamoDB イベントを利用します。  

```
use lambda_runtime::{service_fn, tracing, Error, LambdaEvent};
use aws_lambda_events::{
    event::dynamodb::{Event, EventRecord},
   };


// Built with the following dependencies:
//lambda_runtime = "0.11.1"
//serde_json = "1.0"
//tokio = { version = "1", features = ["macros"] }
//tracing = { version = "0.1", features = ["log"] }
//tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }
//aws_lambda_events = "0.15.0"

async fn function_handler(event: LambdaEvent<Event>) ->Result<(), Error> {
    
    let records = &event.payload.records;
    tracing::info!("event payload: {:?}",records);
    if records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(());
    }

    for record in records{
        log_dynamo_dbrecord(record);
    }

    tracing::info!("Dynamo db records processed");

    // Prepare the response
    Ok(())

}

fn log_dynamo_dbrecord(record: &EventRecord)-> Result<(), Error>{
    tracing::info!("EventId: {}", record.event_id);
    tracing::info!("EventName: {}", record.event_name);
    tracing::info!("DynamoDB Record: {:?}", record.change );
    Ok(())

}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
    .with_max_level(tracing::Level::INFO)
    .with_target(false)
    .without_time()
    .init();

    let func = service_fn(function_handler);
    lambda_runtime::run(func).await?;
    Ok(())
    
}
```

### Amazon DocumentDB トリガーから Lambda 関数を呼び出す
<a name="serverless_DocumentDB_Lambda_rust_1_topic"></a>

次のコードの例は、DocumentDB 変更ストリームからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は DocumentDB ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-docdb-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で Amazon DocumentDB イベントの消費。  

```
use lambda_runtime::{service_fn, tracing, Error, LambdaEvent};
use aws_lambda_events::{
    event::documentdb::{DocumentDbEvent, DocumentDbInnerEvent},
   };


// Built with the following dependencies:
//lambda_runtime = "0.11.1"
//serde_json = "1.0"
//tokio = { version = "1", features = ["macros"] }
//tracing = { version = "0.1", features = ["log"] }
//tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }
//aws_lambda_events = "0.15.0"

async fn function_handler(event: LambdaEvent<DocumentDbEvent>) ->Result<(), Error> {
    
    tracing::info!("Event Source ARN: {:?}", event.payload.event_source_arn);
    tracing::info!("Event Source: {:?}", event.payload.event_source);
  
    let records = &event.payload.events;
   
    if records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(());
    }

    for record in records{
        log_document_db_event(record);
    }

    tracing::info!("Document db records processed");

    // Prepare the response
    Ok(())

}

fn log_document_db_event(record: &DocumentDbInnerEvent)-> Result<(), Error>{
    tracing::info!("Change Event: {:?}", record.event);
    
    Ok(())

}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
    .with_max_level(tracing::Level::INFO)
    .with_target(false)
    .without_time()
    .init();

    let func = service_fn(function_handler);
    lambda_runtime::run(func).await?;
    Ok(())
    
}
```

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_rust_1_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での Amazon MSK イベントの消費。  

```
use aws_lambda_events::event::kafka::KafkaEvent;
use lambda_runtime::{run, service_fn, tracing, Error, LambdaEvent};
use base64::prelude::*;
use serde_json::{Value};
use tracing::{info};

/// Pre-Requisites:
/// 1. Install Cargo Lambda - see https://www.cargo-lambda.info/guide/getting-started.html
/// 2. Add packages tracing, tracing-subscriber, serde_json, base64
///
/// This is the main body for the function.
/// Write your code inside it.
/// There are some code example in the following URLs:
/// - https://github.com/awslabs/aws-lambda-rust-runtime/tree/main/examples
/// - https://github.com/aws-samples/serverless-rust-demo/

async fn function_handler(event: LambdaEvent<KafkaEvent>) -> Result<Value, Error> {

    let payload = event.payload.records;

    for (_name, records) in payload.iter() {

        for record in records {

         let record_text = record.value.as_ref().ok_or("Value is None")?;
         info!("Record: {}", &record_text);

         // perform Base64 decoding
         let record_bytes = BASE64_STANDARD.decode(record_text)?;
         let message = std::str::from_utf8(&record_bytes)?;
         
         info!("Message: {}", message);
        }

    }

    Ok(().into())
}

#[tokio::main]
async fn main() -> Result<(), Error> {

    // required to enable CloudWatch error logging by the runtime
    tracing::init_default_subscriber();
    info!("Setup CW subscriber!");

    run(service_fn(function_handler)).await
}
```

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_rust_1_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Rust を使用して Lambda で S3 イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::s3::S3Event;
use aws_sdk_s3::{Client};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};


/// Main function
#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .with_target(false)
        .without_time()
        .init();

    // Initialize the AWS SDK for Rust
    let config = aws_config::load_from_env().await;
    let s3_client = Client::new(&config);

    let res = run(service_fn(|request: LambdaEvent<S3Event>| {
        function_handler(&s3_client, request)
    })).await;

    res
}

async fn function_handler(
    s3_client: &Client,
    evt: LambdaEvent<S3Event>
) -> Result<(), Error> {
    tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS");

    if evt.payload.records.len() == 0 {
        tracing::info!("Empty S3 event received");
    }

    let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist");
    let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist");

    tracing::info!("Request is for {} and object {}", bucket, key);

    let s3_get_object_result = s3_client
        .get_object()
        .bucket(bucket)
        .key(key)
        .send()
        .await;

    match s3_get_object_result {
        Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"),
        Err(_) => tracing::info!("Failure with S3 Get Object request")
    }

    Ok(())
}
```

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_rust_1_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で SNS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::sns::SnsEvent;
use aws_lambda_events::sns::SnsRecord;
use lambda_runtime::{run, service_fn, Error, LambdaEvent};
use tracing::info;

// Built with the following dependencies:
//  aws_lambda_events = { version = "0.10.0", default-features = false, features = ["sns"] }
//  lambda_runtime = "0.8.1"
//  tokio = { version = "1", features = ["macros"] }
//  tracing = { version = "0.1", features = ["log"] }
//  tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }

async fn function_handler(event: LambdaEvent<SnsEvent>) -> Result<(), Error> {
    for event in event.payload.records {
        process_record(&event)?;
    }
    
    Ok(())
}

fn process_record(record: &SnsRecord) -> Result<(), Error> {
    info!("Processing SNS Message: {}", record.sns.message);

    // Implement your record handling code here.

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .with_target(false)
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_rust_1_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で SQS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::sqs::SqsEvent;
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn function_handler(event: LambdaEvent<SqsEvent>) -> Result<(), Error> {
    event.payload.records.iter().for_each(|record| {
        // process the record
        tracing::info!("Message body: {}", record.body.as_deref().unwrap_or_default())
    });

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

### Kinesis トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_Kinesis_Lambda_batch_item_failures_rust_1_topic"></a>

以下のコード例では、Kinesis ストリームからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-kinesis-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での Kinesis バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::{
    event::kinesis::KinesisEvent,
    kinesis::KinesisEventRecord,
    streams::{KinesisBatchItemFailure, KinesisEventResponse},
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn function_handler(event: LambdaEvent<KinesisEvent>) -> Result<KinesisEventResponse, Error> {
    let mut response = KinesisEventResponse {
        batch_item_failures: vec![],
    };

    if event.payload.records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(response);
    }

    for record in &event.payload.records {
        tracing::info!(
            "EventId: {}",
            record.event_id.as_deref().unwrap_or_default()
        );

        let record_processing_result = process_record(record);

        if record_processing_result.is_err() {
            response.batch_item_failures.push(KinesisBatchItemFailure {
                item_identifier: record.kinesis.sequence_number.clone(),
            });
            /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
            return Ok(response);
        }
    }

    tracing::info!(
        "Successfully processed {} records",
        event.payload.records.len()
    );

    Ok(response)
}

fn process_record(record: &KinesisEventRecord) -> Result<(), Error> {
    let record_data = std::str::from_utf8(record.kinesis.data.as_slice());

    if let Some(err) = record_data.err() {
        tracing::error!("Error: {}", err);
        return Err(Error::from(err));
    }

    let record_data = record_data.unwrap_or_default();

    // do something interesting with the data
    tracing::info!("Data: {}", record_data);

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

### DynamoDB トリガーで Lambda 関数のバッチアイテムの失敗をレポートする
<a name="serverless_DynamoDB_Lambda_batch_item_failures_rust_1_topic"></a>

次のコード例は、DynamoDB ストリームからイベントを受け取る Lambda 関数の部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-ddb-to-lambda-with-batch-item-handling)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で DynamoDB のバッチアイテム失敗のレポート。  

```
use aws_lambda_events::{
    event::dynamodb::{Event, EventRecord, StreamRecord},
    streams::{DynamoDbBatchItemFailure, DynamoDbEventResponse},
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

/// Process the stream record
fn process_record(record: &EventRecord) -> Result<(), Error> {
    let stream_record: &StreamRecord = &record.change;

    // process your stream record here...
    tracing::info!("Data: {:?}", stream_record);

    Ok(())
}

/// Main Lambda handler here...
async fn function_handler(event: LambdaEvent<Event>) -> Result<DynamoDbEventResponse, Error> {
    let mut response = DynamoDbEventResponse {
        batch_item_failures: vec![],
    };

    let records = &event.payload.records;

    if records.is_empty() {
        tracing::info!("No records found. Exiting.");
        return Ok(response);
    }

    for record in records {
        tracing::info!("EventId: {}", record.event_id);

        // Couldn't find a sequence number
        if record.change.sequence_number.is_none() {
            response.batch_item_failures.push(DynamoDbBatchItemFailure {
                item_identifier: Some("".to_string()),
            });
            return Ok(response);
        }

        // Process your record here...
        if process_record(record).is_err() {
            response.batch_item_failures.push(DynamoDbBatchItemFailure {
                item_identifier: record.change.sequence_number.clone(),
            });
            /* Since we are working with streams, we can return the failed item immediately.
            Lambda will immediately begin to retry processing from this failed item onwards. */
            return Ok(response);
        }
    }

    tracing::info!("Successfully processed {} record(s)", records.len());

    Ok(response)
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_rust_1_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::{
    event::sqs::{SqsBatchResponse, SqsEvent},
    sqs::{BatchItemFailure, SqsMessage},
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn process_record(_: &SqsMessage) -> Result<(), Error> {
    Err(Error::from("Error processing message"))
}

async fn function_handler(event: LambdaEvent<SqsEvent>) -> Result<SqsBatchResponse, Error> {
    let mut batch_item_failures = Vec::new();
    for record in event.payload.records {
        match process_record(&record).await {
            Ok(_) => (),
            Err(_) => batch_item_failures.push(BatchItemFailure {
                item_identifier: record.message_id.unwrap(),
            }),
        }
    }

    Ok(SqsBatchResponse {
        batch_item_failures,
    })
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(function_handler)).await
}
```

## AWS コミュニティへの貢献
<a name="aws_community_contributions"></a>

### サーバーレスアプリケーションの構築とテスト
<a name="tributary-lite_serverless-application_rust_1_topic"></a>

次のコード例は、Lambda および DynamoDB を備えた API Gateway を使用してサーバーレスアプリケーションを構築およびテストする方法を示しています。

**SDK for Rust**  
 Rust SDK を使用し、Lambda および DynamoDB を備えた API Gateway で構成されるサーバーレスアプリケーションを構築およびテストする方法が示されます。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/aws-samples/serverless-rust-demo) で完全な例を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda

# SDK for Rust を使用した MediaLive の例
<a name="rust_1_medialive_code_examples"></a>

次のコード例は、MediaLive で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListInputs`
<a name="medialive_ListInputs_rust_1_topic"></a>

次のコード例は、`ListInputs` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/medialive#code-examples)での設定と実行の方法を確認してください。
リージョン内の MediaLive 入力名と ARN を一覧表示します。  

```
async fn show_inputs(client: &Client) -> Result<(), Error> {
    let input_list = client.list_inputs().send().await?;

    for i in input_list.inputs() {
        let input_arn = i.arn().unwrap_or_default();
        let input_name = i.name().unwrap_or_default();

        println!("Input Name : {}", input_name);
        println!("Input ARN : {}", input_arn);
        println!();
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListInputs](https://docs.rs/aws-sdk-medialive/latest/aws_sdk_medialive/client/struct.Client.html#method.list_inputs)」を参照してください。

# SDK for Rust を使用する MediaPackage の例
<a name="rust_1_mediapackage_code_examples"></a>

次のコード例は、MediaPackage で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListChannels`
<a name="mediapackage_ListChannels_rust_1_topic"></a>

次のコード例は、`ListChannels` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/mediapackage#code-examples)での設定と実行の方法を確認してください。
チャネル ARN と説明を一覧表示する。  

```
async fn show_channels(client: &Client) -> Result<(), Error> {
    let list_channels = client.list_channels().send().await?;

    println!("Channels:");

    for c in list_channels.channels() {
        let description = c.description().unwrap_or_default();
        let arn = c.arn().unwrap_or_default();

        println!("  Description : {}", description);
        println!("  ARN :         {}", arn);
        println!();
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListChannels](https://docs.rs/aws-sdk-mediapackage/latest/aws_sdk_mediapackage/client/struct.Client.html#method.list_channels)」を参照してください。

### `ListOriginEndpoints`
<a name="mediapackage_ListOriginEndpoints_rust_1_topic"></a>

次のコード例は、`ListOriginEndpoints` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/mediapackage#code-examples)での設定と実行の方法を確認してください。
エンドポイント記述と URL を一覧表示します。  

```
async fn show_endpoints(client: &Client) -> Result<(), Error> {
    let or_endpoints = client.list_origin_endpoints().send().await?;

    println!("Endpoints:");

    for e in or_endpoints.origin_endpoints() {
        let endpoint_url = e.url().unwrap_or_default();
        let endpoint_description = e.description().unwrap_or_default();
        println!("  Description: {}", endpoint_description);
        println!("  URL :        {}", endpoint_url);
        println!();
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListOriginEndpoints](https://docs.rs/aws-sdk-mediapackage/latest/aws_sdk_mediapackage/client/struct.Client.html#method.list_origin_endpoints)」を参照してください。

# SDK for Rust を使用した Amazon MSK の例
<a name="rust_1_kafka_code_examples"></a>

次のコード例は、Amazon MSK で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon MSK トリガーから Lambda 関数を呼び出す
<a name="serverless_MSK_Lambda_rust_1_topic"></a>

次のコード例は、Amazon MSK クラスターからレコードを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。関数は MSK ペイロードを取得し、レコードの内容をログ記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-msk-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での Amazon MSK イベントの消費。  

```
use aws_lambda_events::event::kafka::KafkaEvent;
use lambda_runtime::{run, service_fn, tracing, Error, LambdaEvent};
use base64::prelude::*;
use serde_json::{Value};
use tracing::{info};

/// Pre-Requisites:
/// 1. Install Cargo Lambda - see https://www.cargo-lambda.info/guide/getting-started.html
/// 2. Add packages tracing, tracing-subscriber, serde_json, base64
///
/// This is the main body for the function.
/// Write your code inside it.
/// There are some code example in the following URLs:
/// - https://github.com/awslabs/aws-lambda-rust-runtime/tree/main/examples
/// - https://github.com/aws-samples/serverless-rust-demo/

async fn function_handler(event: LambdaEvent<KafkaEvent>) -> Result<Value, Error> {

    let payload = event.payload.records;

    for (_name, records) in payload.iter() {

        for record in records {

         let record_text = record.value.as_ref().ok_or("Value is None")?;
         info!("Record: {}", &record_text);

         // perform Base64 decoding
         let record_bytes = BASE64_STANDARD.decode(record_text)?;
         let message = std::str::from_utf8(&record_bytes)?;
         
         info!("Message: {}", message);
        }

    }

    Ok(().into())
}

#[tokio::main]
async fn main() -> Result<(), Error> {

    // required to enable CloudWatch error logging by the runtime
    tracing::init_default_subscriber();
    info!("Setup CW subscriber!");

    run(service_fn(function_handler)).await
}
```

# SDK for Rust を使用した Amazon Polly の例
<a name="rust_1_polly_code_examples"></a>

次のコード例は、Amazon Polly で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DescribeVoices`
<a name="polly_DescribeVoices_rust_1_topic"></a>

次のコード例は、`DescribeVoices` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/polly#code-examples)での設定と実行の方法を確認してください。

```
async fn list_voices(client: &Client) -> Result<(), Error> {
    let resp = client.describe_voices().send().await?;

    println!("Voices:");

    let voices = resp.voices();
    for voice in voices {
        println!("  Name:     {}", voice.name().unwrap_or("No name!"));
        println!(
            "  Language: {}",
            voice.language_name().unwrap_or("No language!")
        );

        println!();
    }

    println!("Found {} voices", voices.len());

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeVoices](https://docs.rs/aws-sdk-polly/latest/aws_sdk_polly/client/struct.Client.html#method.describe_voices)」を参照してください。

### `ListLexicons`
<a name="polly_ListLexicons_rust_1_topic"></a>

次のコード例は、`ListLexicons` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/polly#code-examples)での設定と実行の方法を確認してください。

```
async fn show_lexicons(client: &Client) -> Result<(), Error> {
    let resp = client.list_lexicons().send().await?;

    println!("Lexicons:");

    let lexicons = resp.lexicons();

    for lexicon in lexicons {
        println!("  Name:     {}", lexicon.name().unwrap_or_default());
        println!(
            "  Language: {:?}\n",
            lexicon
                .attributes()
                .as_ref()
                .map(|attrib| attrib
                    .language_code
                    .as_ref()
                    .expect("languages must have language codes"))
                .expect("languages must have attributes")
        );
    }

    println!();
    println!("Found {} lexicons.", lexicons.len());
    println!();

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListLexicons](https://docs.rs/aws-sdk-polly/latest/aws_sdk_polly/client/struct.Client.html#method.list_lexicons)」を参照してください。

### `PutLexicon`
<a name="polly_PutLexicon_rust_1_topic"></a>

次のコード例は、`PutLexicon` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/polly#code-examples)での設定と実行の方法を確認してください。

```
async fn make_lexicon(client: &Client, name: &str, from: &str, to: &str) -> Result<(), Error> {
    let content = format!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>
    <lexicon version=\"1.0\" xmlns=\"http://www.w3.org/2005/01/pronunciation-lexicon\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
    xsi:schemaLocation=\"http://www.w3.org/2005/01/pronunciation-lexicon http://www.w3.org/TR/2007/CR-pronunciation-lexicon-20071212/pls.xsd\"
    alphabet=\"ipa\" xml:lang=\"en-US\">
    <lexeme><grapheme>{}</grapheme><alias>{}</alias></lexeme>
    </lexicon>", from, to);

    client
        .put_lexicon()
        .name(name)
        .content(content)
        .send()
        .await?;

    println!("Added lexicon");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[PutLexicon](https://docs.rs/aws-sdk-polly/latest/aws_sdk_polly/client/struct.Client.html#method.put_lexicon)」を参照してください。

### `SynthesizeSpeech`
<a name="polly_SynthesizeSpeech_rust_1_topic"></a>

次のコード例は、`SynthesizeSpeech` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/polly#code-examples)での設定と実行の方法を確認してください。

```
async fn synthesize(client: &Client, filename: &str) -> Result<(), Error> {
    let content = fs::read_to_string(filename);

    let resp = client
        .synthesize_speech()
        .output_format(OutputFormat::Mp3)
        .text(content.unwrap())
        .voice_id(VoiceId::Joanna)
        .send()
        .await?;

    // Get MP3 data from response and save it
    let mut blob = resp
        .audio_stream
        .collect()
        .await
        .expect("failed to read data");

    let parts: Vec<&str> = filename.split('.').collect();
    let out_file = format!("{}{}", String::from(parts[0]), ".mp3");

    let mut file = tokio::fs::File::create(out_file)
        .await
        .expect("failed to create file");

    file.write_all_buf(&mut blob)
        .await
        .expect("failed to write to file");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[SynthesizeSpeech](https://docs.rs/aws-sdk-polly/latest/aws_sdk_polly/client/struct.Client.html#method.synthesize_speech)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### テキストを音声に変換し、テキストに戻す
<a name="cross_Telephone_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Polly を使用して、プレーンテキスト (UTF-8) 入力ファイルを音声ファイルに合成します。
+ Amazon S3 バケットに音声ファイルをアップロードします。
+ Amazon Transcribe を使用して、音声ファイルをテキストに変換します。
+ テキストを表示します。

**SDK for Rust**  
 Amazon Polly を使用して、プレーンテキスト (UTF-8) 入力ファイルを音声ファイルに合成し、音声ファイルを Amazon S3 バケットにアップロードし、Amazon Transcribe を使用して音声ファイルをテキストに変換し、テキストを表示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service#code-examples) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Polly
+ Amazon S3
+ Amazon Transcribe

# SDK for Rust を使用した Amazon RDS の例
<a name="rust_1_rds_code_examples"></a>

次のコード例は、Amazon RDS で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [サーバーレスサンプル](#serverless_examples)

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Lambda 関数での Amazon RDS データベースへの接続
<a name="serverless_connect_RDS_Lambda_rust_1_topic"></a>

次のコード例は、RDS データベースに接続する Lambda 関数を実装する方法を示しています。この関数は、シンプルなデータベースリクエストを実行し、結果を返します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-connect-rds-iam)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda 関数での Amazon RDS データベースへの接続  

```
use aws_config::BehaviorVersion;
use aws_credential_types::provider::ProvideCredentials;
use aws_sigv4::{
    http_request::{sign, SignableBody, SignableRequest, SigningSettings},
    sign::v4,
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};
use serde_json::{json, Value};
use sqlx::postgres::PgConnectOptions;
use std::env;
use std::time::{Duration, SystemTime};

const RDS_CERTS: &[u8] = include_bytes!("global-bundle.pem");

async fn generate_rds_iam_token(
    db_hostname: &str,
    port: u16,
    db_username: &str,
) -> Result<String, Error> {
    let config = aws_config::load_defaults(BehaviorVersion::v2024_03_28()).await;

    let credentials = config
        .credentials_provider()
        .expect("no credentials provider found")
        .provide_credentials()
        .await
        .expect("unable to load credentials");
    let identity = credentials.into();
    let region = config.region().unwrap().to_string();

    let mut signing_settings = SigningSettings::default();
    signing_settings.expires_in = Some(Duration::from_secs(900));
    signing_settings.signature_location = aws_sigv4::http_request::SignatureLocation::QueryParams;

    let signing_params = v4::SigningParams::builder()
        .identity(&identity)
        .region(&region)
        .name("rds-db")
        .time(SystemTime::now())
        .settings(signing_settings)
        .build()?;

    let url = format!(
        "https://{db_hostname}:{port}/?Action=connect&DBUser={db_user}",
        db_hostname = db_hostname,
        port = port,
        db_user = db_username
    );

    let signable_request =
        SignableRequest::new("GET", &url, std::iter::empty(), SignableBody::Bytes(&[]))
            .expect("signable request");

    let (signing_instructions, _signature) =
        sign(signable_request, &signing_params.into())?.into_parts();

    let mut url = url::Url::parse(&url).unwrap();
    for (name, value) in signing_instructions.params() {
        url.query_pairs_mut().append_pair(name, &value);
    }

    let response = url.to_string().split_off("https://".len());

    Ok(response)
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(handler)).await
}

async fn handler(_event: LambdaEvent<Value>) -> Result<Value, Error> {
    let db_host = env::var("DB_HOSTNAME").expect("DB_HOSTNAME must be set");
    let db_port = env::var("DB_PORT")
        .expect("DB_PORT must be set")
        .parse::<u16>()
        .expect("PORT must be a valid number");
    let db_name = env::var("DB_NAME").expect("DB_NAME must be set");
    let db_user_name = env::var("DB_USERNAME").expect("DB_USERNAME must be set");

    let token = generate_rds_iam_token(&db_host, db_port, &db_user_name).await?;

    let opts = PgConnectOptions::new()
        .host(&db_host)
        .port(db_port)
        .username(&db_user_name)
        .password(&token)
        .database(&db_name)
        .ssl_root_cert_from_pem(RDS_CERTS.to_vec())
        .ssl_mode(sqlx::postgres::PgSslMode::Require);

    let pool = sqlx::postgres::PgPoolOptions::new()
        .connect_with(opts)
        .await?;

    let result: i32 = sqlx::query_scalar("SELECT $1 + $2")
        .bind(3)
        .bind(2)
        .fetch_one(&pool)
        .await?;

    println!("Result: {:?}", result);

    Ok(json!({
        "statusCode": 200,
        "content-type": "text/plain",
        "body": format!("The selected sum is: {result}")
    }))
}
```

# SDK for Rust を使用した Amazon RDS データサービスの例
<a name="rust_1_rds-data_code_examples"></a>

次のコード例は、Amazon RDS Data Service で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ExecuteStatement`
<a name="rds-data_ExecuteStatement_rust_1_topic"></a>

次のコード例は、`ExecuteStatement` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/rdsdata#code-examples)での設定と実行の方法を確認してください。

```
async fn query_cluster(
    client: &Client,
    cluster_arn: &str,
    query: &str,
    secret_arn: &str,
) -> Result<(), Error> {
    let st = client
        .execute_statement()
        .resource_arn(cluster_arn)
        .database("postgres") // Do not confuse this with db instance name
        .sql(query)
        .secret_arn(secret_arn);

    let result = st.send().await?;

    println!("{:?}", result);
    println!();

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ExecuteStatement](https://docs.rs/aws-sdk-rdsdata/latest/aws_sdk_rdsdata/client/struct.Client.html#method.execute_statement)」を参照してください。

# SDK for Rust を使用する Amazon Rekognition の例
<a name="rust_1_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_rust_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Rust**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/cross_service/photo_asset_management) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### イメージ内の顔を検出します
<a name="cross_DetectFaces_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ イメージを Amazon S3 バケットに保存します。
+ Amazon Rekognition を使用して、年齢層、性別、感情 (笑顔など) などの顔の詳細を検出します。
+ これらの詳細を表示します。

**SDK for Rust**  
 **アップロード** プレフィックスを付け、Amazon S3 バケット内でイメージを保存し、Amazon Rekognition を使用して、年齢層、性別、感情 (笑顔など) などの顔の詳細を検出し、それらの詳細を表示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service/detect_faces/src/main.rs) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3

### EXIF およびその他のイメージ情報を保存します
<a name="cross_DetectLabels_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ JPG、JPEG、または PNG ファイルから EXIF 情報を取得します。
+ Amazon S3 バケットにイメージファイルをアップロードします。
+ Amazon Rekognition を使用して、ファイル内の 3 つの上位属性 (ラベル) を特定します。
+ EXIF およびラベル情報を、リージョンの Amazon DynamoDB テーブルに追加します。

**SDK for Rust**  
 JPG、JPEG、または PNG ファイルから EXIF 情報を取得し、イメージファイルを Amazon S3 バケットにアップロードし、Amazon Rekognition を使用してファイル内の 3 つの上位属性 (Amazon Rekognition の*ラベル*) を特定し、リージョンの Amazon DynamoDB テーブルに EXIF およびラベル情報を追加します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service/detect_labels/src/main.rs) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon Rekognition
+ Amazon S3

# SDK for Rust を使用した Route 53 の例
<a name="rust_1_route-53_code_examples"></a>

次のコード例は、Route 53 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListHostedZones`
<a name="route-53_ListHostedZones_rust_1_topic"></a>

次のコード例は、`ListHostedZones` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/route53#code-examples)での設定と実行の方法を確認してください。

```
async fn show_host_info(client: &aws_sdk_route53::Client) -> Result<(), aws_sdk_route53::Error> {
    let hosted_zone_count = client.get_hosted_zone_count().send().await?;

    println!(
        "Number of hosted zones in region : {}",
        hosted_zone_count.hosted_zone_count(),
    );

    let hosted_zones = client.list_hosted_zones().send().await?;

    println!("Zones:");

    for hz in hosted_zones.hosted_zones() {
        let zone_name = hz.name();
        let zone_id = hz.id();

        println!("  ID :   {}", zone_id);
        println!("  Name : {}", zone_name);
        println!();
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListHostedZones](https://docs.rs/aws-sdk-route53/latest/aws_sdk_route53/client/struct.Client.html#method.list_hosted_zones)」を参照してください。

# SDK for Rust を使用した Amazon S3 の例
<a name="rust_1_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [開始方法](#get_started)
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## はじめに
<a name="get_started"></a>

### Hello Amazon S3
<a name="s3_Hello_rust_1_topic"></a>

次のコード例は、Amazon S3 の使用を開始する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
/// S3 Hello World Example using the AWS SDK for Rust.
///
/// This example lists the objects in a bucket, uploads an object to that bucket,
/// and then retrieves the object and prints some S3 information about the object.
/// This shows a number of S3 features, including how to use built-in paginators
/// for large data sets.
///
/// # Arguments
///
/// * `client` - an S3 client configured appropriately for the environment.
/// * `bucket` - the bucket name that the object will be uploaded to. Must be present in the region the `client` is configured to use.
/// * `filename` - a reference to a path that will be read and uploaded to S3.
/// * `key` - the string key that the object will be uploaded as inside the bucket.
async fn list_bucket_and_upload_object(
    client: &aws_sdk_s3::Client,
    bucket: &str,
    filepath: &Path,
    key: &str,
) -> Result<(), S3ExampleError> {
    // List the buckets in this account
    let mut objects = client
        .list_objects_v2()
        .bucket(bucket)
        .into_paginator()
        .send();

    println!("key\tetag\tlast_modified\tstorage_class");
    while let Some(Ok(object)) = objects.next().await {
        for item in object.contents() {
            println!(
                "{}\t{}\t{}\t{}",
                item.key().unwrap_or_default(),
                item.e_tag().unwrap_or_default(),
                item.last_modified()
                    .map(|lm| format!("{lm}"))
                    .unwrap_or_default(),
                item.storage_class()
                    .map(|sc| format!("{sc}"))
                    .unwrap_or_default()
            );
        }
    }

    // Prepare a ByteStream around the file, and upload the object using that ByteStream.
    let body = aws_sdk_s3::primitives::ByteStream::from_path(filepath)
        .await
        .map_err(|err| {
            S3ExampleError::new(format!(
                "Failed to create bytestream for {filepath:?} ({err:?})"
            ))
        })?;
    let resp = client
        .put_object()
        .bucket(bucket)
        .key(key)
        .body(body)
        .send()
        .await?;

    println!(
        "Upload success. Version: {:?}",
        resp.version_id()
            .expect("S3 Object upload missing version ID")
    );

    // Retrieve the just-uploaded object.
    let resp = client.get_object().bucket(bucket).key(key).send().await?;
    println!("etag: {}", resp.e_tag().unwrap_or("(missing)"));
    println!("version: {}", resp.version_id().unwrap_or("(missing)"));

    Ok(())
}
```
S3ExampleError ユーティリティ。  

```
/// S3ExampleError provides a From<T: ProvideErrorMetadata> impl to extract
/// client-specific error details. This serves as a consistent backup to handling
/// specific service errors, depending on what is needed by the scenario.
/// It is used throughout the code examples for the AWS SDK for Rust.
#[derive(Debug)]
pub struct S3ExampleError(String);
impl S3ExampleError {
    pub fn new(value: impl Into<String>) -> Self {
        S3ExampleError(value.into())
    }

    pub fn add_message(self, message: impl Into<String>) -> Self {
        S3ExampleError(format!("{}: {}", message.into(), self.0))
    }
}

impl<T: aws_sdk_s3::error::ProvideErrorMetadata> From<T> for S3ExampleError {
    fn from(value: T) -> Self {
        S3ExampleError(format!(
            "{}: {}",
            value
                .code()
                .map(String::from)
                .unwrap_or("unknown code".into()),
            value
                .message()
                .map(String::from)
                .unwrap_or("missing reason".into()),
        ))
    }
}

impl std::error::Error for S3ExampleError {}

impl std::fmt::Display for S3ExampleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListBuckets](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.list_buckets)」を参照してください。

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。
シナリオを実行するバイナリクレートのコード。  

```
#![allow(clippy::result_large_err)]

//!  Purpose
//!  Shows how to use the AWS SDK for Rust to get started using
//!  Amazon Simple Storage Service (Amazon S3). Create a bucket, move objects into and out of it,
//!  and delete all resources at the end of the demo.
//!
//!  This example follows the steps in "Getting started with Amazon S3" in the Amazon S3
//!  user guide.
//!  - https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html

use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::{config::Region, Client};
use s3_code_examples::error::S3ExampleError;
use uuid::Uuid;

#[tokio::main]
async fn main() -> Result<(), S3ExampleError> {
    let region_provider = RegionProviderChain::first_try(Region::new("us-west-2"));
    let region = region_provider.region().await.unwrap();
    let shared_config = aws_config::from_env().region(region_provider).load().await;
    let client = Client::new(&shared_config);
    let bucket_name = format!("amzn-s3-demo-bucket-{}", Uuid::new_v4());
    let file_name = "s3/testfile.txt".to_string();
    let key = "test file key name".to_string();
    let target_key = "target_key".to_string();

    if let Err(e) = run_s3_operations(region, client, bucket_name, file_name, key, target_key).await
    {
        eprintln!("{:?}", e);
    };

    Ok(())
}

async fn run_s3_operations(
    region: Region,
    client: Client,
    bucket_name: String,
    file_name: String,
    key: String,
    target_key: String,
) -> Result<(), S3ExampleError> {
    s3_code_examples::create_bucket(&client, &bucket_name, &region).await?;
    let run_example: Result<(), S3ExampleError> = (async {
        s3_code_examples::upload_object(&client, &bucket_name, &file_name, &key).await?;
        let _object = s3_code_examples::download_object(&client, &bucket_name, &key).await;
        s3_code_examples::copy_object(&client, &bucket_name, &bucket_name, &key, &target_key)
            .await?;
        s3_code_examples::list_objects(&client, &bucket_name).await?;
        s3_code_examples::clear_bucket(&client, &bucket_name).await?;
        Ok(())
    })
    .await;
    if let Err(err) = run_example {
        eprintln!("Failed to complete getting-started example: {err:?}");
    }
    s3_code_examples::delete_bucket(&client, &bucket_name).await?;

    Ok(())
}
```
シナリオで使用される一般的なアクション。  

```
pub async fn create_bucket(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
    region: &aws_config::Region,
) -> Result<Option<aws_sdk_s3::operation::create_bucket::CreateBucketOutput>, S3ExampleError> {
    let constraint = aws_sdk_s3::types::BucketLocationConstraint::from(region.to_string().as_str());
    let cfg = aws_sdk_s3::types::CreateBucketConfiguration::builder()
        .location_constraint(constraint)
        .build();
    let create = client
        .create_bucket()
        .create_bucket_configuration(cfg)
        .bucket(bucket_name)
        .send()
        .await;

    // BucketAlreadyExists and BucketAlreadyOwnedByYou are not problems for this task.
    create.map(Some).or_else(|err| {
        if err
            .as_service_error()
            .map(|se| se.is_bucket_already_exists() || se.is_bucket_already_owned_by_you())
            == Some(true)
        {
            Ok(None)
        } else {
            Err(S3ExampleError::from(err))
        }
    })
}

pub async fn upload_object(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
    file_name: &str,
    key: &str,
) -> Result<aws_sdk_s3::operation::put_object::PutObjectOutput, S3ExampleError> {
    let body = aws_sdk_s3::primitives::ByteStream::from_path(std::path::Path::new(file_name)).await;
    client
        .put_object()
        .bucket(bucket_name)
        .key(key)
        .body(body.unwrap())
        .send()
        .await
        .map_err(S3ExampleError::from)
}

pub async fn download_object(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
    key: &str,
) -> Result<aws_sdk_s3::operation::get_object::GetObjectOutput, S3ExampleError> {
    client
        .get_object()
        .bucket(bucket_name)
        .key(key)
        .send()
        .await
        .map_err(S3ExampleError::from)
}

/// Copy an object from one bucket to another.
pub async fn copy_object(
    client: &aws_sdk_s3::Client,
    source_bucket: &str,
    destination_bucket: &str,
    source_object: &str,
    destination_object: &str,
) -> Result<(), S3ExampleError> {
    let source_key = format!("{source_bucket}/{source_object}");
    let response = client
        .copy_object()
        .copy_source(&source_key)
        .bucket(destination_bucket)
        .key(destination_object)
        .send()
        .await?;

    println!(
        "Copied from {source_key} to {destination_bucket}/{destination_object} with etag {}",
        response
            .copy_object_result
            .unwrap_or_else(|| aws_sdk_s3::types::CopyObjectResult::builder().build())
            .e_tag()
            .unwrap_or("missing")
    );
    Ok(())
}

pub async fn list_objects(client: &aws_sdk_s3::Client, bucket: &str) -> Result<(), S3ExampleError> {
    let mut response = client
        .list_objects_v2()
        .bucket(bucket.to_owned())
        .max_keys(10) // In this example, go 10 at a time.
        .into_paginator()
        .send();

    while let Some(result) = response.next().await {
        match result {
            Ok(output) => {
                for object in output.contents() {
                    println!(" - {}", object.key().unwrap_or("Unknown"));
                }
            }
            Err(err) => {
                eprintln!("{err:?}")
            }
        }
    }

    Ok(())
}

/// Given a bucket, remove all objects in the bucket, and then ensure no objects
/// remain in the bucket.
pub async fn clear_bucket(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
) -> Result<Vec<String>, S3ExampleError> {
    let objects = client.list_objects_v2().bucket(bucket_name).send().await?;

    // delete_objects no longer needs to be mutable.
    let objects_to_delete: Vec<String> = objects
        .contents()
        .iter()
        .filter_map(|obj| obj.key())
        .map(String::from)
        .collect();

    if objects_to_delete.is_empty() {
        return Ok(vec![]);
    }

    let return_keys = objects_to_delete.clone();

    delete_objects(client, bucket_name, objects_to_delete).await?;

    let objects = client.list_objects_v2().bucket(bucket_name).send().await?;

    eprintln!("{objects:?}");

    match objects.key_count {
        Some(0) => Ok(return_keys),
        _ => Err(S3ExampleError::new(
            "There were still objects left in the bucket.",
        )),
    }
}

pub async fn delete_bucket(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
) -> Result<(), S3ExampleError> {
    let resp = client.delete_bucket().bucket(bucket_name).send().await;
    match resp {
        Ok(_) => Ok(()),
        Err(err) => {
            if err
                .as_service_error()
                .and_then(aws_sdk_s3::error::ProvideErrorMetadata::code)
                == Some("NoSuchBucket")
            {
                Ok(())
            } else {
                Err(S3ExampleError::from(err))
            }
        }
    }
}
```
+ API の詳細については、「*AWS SDK for Rust API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.copy_object)
  + [CreateBucket](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.create_bucket)
  + [DeleteBucket](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.delete_bucket)
  + [DeleteObjects](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.delete_objects)
  + [GetObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.get_object)
  + [ListObjectsV2](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.list_objects_v2)
  + [PutObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.put_object)

## アクション
<a name="actions"></a>

### `CompleteMultipartUpload`
<a name="s3_CompleteMultipartUpload_rust_1_topic"></a>

次のコード例は、`CompleteMultipartUpload` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
    // upload_parts: Vec<aws_sdk_s3::types::CompletedPart>
    let completed_multipart_upload: CompletedMultipartUpload = CompletedMultipartUpload::builder()
        .set_parts(Some(upload_parts))
        .build();

    let _complete_multipart_upload_res = client
        .complete_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .multipart_upload(completed_multipart_upload)
        .upload_id(upload_id)
        .send()
        .await?;
```

```
    // Create a multipart upload. Use UploadPart and CompleteMultipartUpload to
    // upload the file.
    let multipart_upload_res: CreateMultipartUploadOutput = client
        .create_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .send()
        .await?;

    let upload_id = multipart_upload_res.upload_id().ok_or(S3ExampleError::new(
        "Missing upload_id after CreateMultipartUpload",
    ))?;
```

```
    let mut upload_parts: Vec<aws_sdk_s3::types::CompletedPart> = Vec::new();

    for chunk_index in 0..chunk_count {
        let this_chunk = if chunk_count - 1 == chunk_index {
            size_of_last_chunk
        } else {
            CHUNK_SIZE
        };
        let stream = ByteStream::read_from()
            .path(path)
            .offset(chunk_index * CHUNK_SIZE)
            .length(Length::Exact(this_chunk))
            .build()
            .await
            .unwrap();

        // Chunk index needs to start at 0, but part numbers start at 1.
        let part_number = (chunk_index as i32) + 1;
        let upload_part_res = client
            .upload_part()
            .key(&key)
            .bucket(&bucket_name)
            .upload_id(upload_id)
            .body(stream)
            .part_number(part_number)
            .send()
            .await?;

        upload_parts.push(
            CompletedPart::builder()
                .e_tag(upload_part_res.e_tag.unwrap_or_default())
                .part_number(part_number)
                .build(),
        );
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CompleteMultipartUpload](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.complete_multipart_upload)」を参照してください。

### `CopyObject`
<a name="s3_CopyObject_rust_1_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
/// Copy an object from one bucket to another.
pub async fn copy_object(
    client: &aws_sdk_s3::Client,
    source_bucket: &str,
    destination_bucket: &str,
    source_object: &str,
    destination_object: &str,
) -> Result<(), S3ExampleError> {
    let source_key = format!("{source_bucket}/{source_object}");
    let response = client
        .copy_object()
        .copy_source(&source_key)
        .bucket(destination_bucket)
        .key(destination_object)
        .send()
        .await?;

    println!(
        "Copied from {source_key} to {destination_bucket}/{destination_object} with etag {}",
        response
            .copy_object_result
            .unwrap_or_else(|| aws_sdk_s3::types::CopyObjectResult::builder().build())
            .e_tag()
            .unwrap_or("missing")
    );
    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CopyObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.copy_object)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_rust_1_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
pub async fn create_bucket(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
    region: &aws_config::Region,
) -> Result<Option<aws_sdk_s3::operation::create_bucket::CreateBucketOutput>, S3ExampleError> {
    let constraint = aws_sdk_s3::types::BucketLocationConstraint::from(region.to_string().as_str());
    let cfg = aws_sdk_s3::types::CreateBucketConfiguration::builder()
        .location_constraint(constraint)
        .build();
    let create = client
        .create_bucket()
        .create_bucket_configuration(cfg)
        .bucket(bucket_name)
        .send()
        .await;

    // BucketAlreadyExists and BucketAlreadyOwnedByYou are not problems for this task.
    create.map(Some).or_else(|err| {
        if err
            .as_service_error()
            .map(|se| se.is_bucket_already_exists() || se.is_bucket_already_owned_by_you())
            == Some(true)
        {
            Ok(None)
        } else {
            Err(S3ExampleError::from(err))
        }
    })
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateBucket](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.create_bucket)」を参照してください。

### `CreateMultipartUpload`
<a name="s3_CreateMultipartUpload_rust_1_topic"></a>

次のコード例は、`CreateMultipartUpload` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
    // Create a multipart upload. Use UploadPart and CompleteMultipartUpload to
    // upload the file.
    let multipart_upload_res: CreateMultipartUploadOutput = client
        .create_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .send()
        .await?;

    let upload_id = multipart_upload_res.upload_id().ok_or(S3ExampleError::new(
        "Missing upload_id after CreateMultipartUpload",
    ))?;
```

```
    let mut upload_parts: Vec<aws_sdk_s3::types::CompletedPart> = Vec::new();

    for chunk_index in 0..chunk_count {
        let this_chunk = if chunk_count - 1 == chunk_index {
            size_of_last_chunk
        } else {
            CHUNK_SIZE
        };
        let stream = ByteStream::read_from()
            .path(path)
            .offset(chunk_index * CHUNK_SIZE)
            .length(Length::Exact(this_chunk))
            .build()
            .await
            .unwrap();

        // Chunk index needs to start at 0, but part numbers start at 1.
        let part_number = (chunk_index as i32) + 1;
        let upload_part_res = client
            .upload_part()
            .key(&key)
            .bucket(&bucket_name)
            .upload_id(upload_id)
            .body(stream)
            .part_number(part_number)
            .send()
            .await?;

        upload_parts.push(
            CompletedPart::builder()
                .e_tag(upload_part_res.e_tag.unwrap_or_default())
                .part_number(part_number)
                .build(),
        );
    }
```

```
    // upload_parts: Vec<aws_sdk_s3::types::CompletedPart>
    let completed_multipart_upload: CompletedMultipartUpload = CompletedMultipartUpload::builder()
        .set_parts(Some(upload_parts))
        .build();

    let _complete_multipart_upload_res = client
        .complete_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .multipart_upload(completed_multipart_upload)
        .upload_id(upload_id)
        .send()
        .await?;
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateMultipartUpload](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.create_multipart_upload)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_rust_1_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
pub async fn delete_bucket(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
) -> Result<(), S3ExampleError> {
    let resp = client.delete_bucket().bucket(bucket_name).send().await;
    match resp {
        Ok(_) => Ok(()),
        Err(err) => {
            if err
                .as_service_error()
                .and_then(aws_sdk_s3::error::ProvideErrorMetadata::code)
                == Some("NoSuchBucket")
            {
                Ok(())
            } else {
                Err(S3ExampleError::from(err))
            }
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteBucket](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.delete_bucket)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_rust_1_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
/// Delete an object from a bucket.
pub async fn remove_object(
    client: &aws_sdk_s3::Client,
    bucket: &str,
    key: &str,
) -> Result<(), S3ExampleError> {
    client
        .delete_object()
        .bucket(bucket)
        .key(key)
        .send()
        .await?;

    // There are no modeled errors to handle when deleting an object.

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.delete_object)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_rust_1_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
/// Delete the objects in a bucket.
pub async fn delete_objects(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
    objects_to_delete: Vec<String>,
) -> Result<(), S3ExampleError> {
    // Push into a mut vector to use `?` early return errors while building object keys.
    let mut delete_object_ids: Vec<aws_sdk_s3::types::ObjectIdentifier> = vec![];
    for obj in objects_to_delete {
        let obj_id = aws_sdk_s3::types::ObjectIdentifier::builder()
            .key(obj)
            .build()
            .map_err(|err| {
                S3ExampleError::new(format!("Failed to build key for delete_object: {err:?}"))
            })?;
        delete_object_ids.push(obj_id);
    }

    client
        .delete_objects()
        .bucket(bucket_name)
        .delete(
            aws_sdk_s3::types::Delete::builder()
                .set_objects(Some(delete_object_ids))
                .build()
                .map_err(|err| {
                    S3ExampleError::new(format!("Failed to build delete_object input {err:?}"))
                })?,
        )
        .send()
        .await?;
    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteObjects](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.delete_objects)」を参照してください。

### `GetBucketLocation`
<a name="s3_GetBucketLocation_rust_1_topic"></a>

次のコード例は、`GetBucketLocation` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
async fn show_buckets(
    strict: bool,
    client: &Client,
    region: BucketLocationConstraint,
) -> Result<(), S3ExampleError> {
    let mut buckets = client.list_buckets().into_paginator().send();

    let mut num_buckets = 0;
    let mut in_region = 0;

    while let Some(Ok(output)) = buckets.next().await {
        for bucket in output.buckets() {
            num_buckets += 1;
            if strict {
                let r = client
                    .get_bucket_location()
                    .bucket(bucket.name().unwrap_or_default())
                    .send()
                    .await?;

                if r.location_constraint() == Some(&region) {
                    println!("{}", bucket.name().unwrap_or_default());
                    in_region += 1;
                }
            } else {
                println!("{}", bucket.name().unwrap_or_default());
            }
        }
    }

    println!();
    if strict {
        println!(
            "Found {} buckets in the {} region out of a total of {} buckets.",
            in_region, region, num_buckets
        );
    } else {
        println!("Found {} buckets in all regions.", num_buckets);
    }

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[GetBucketLocation](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.get_bucket_location)」を参照してください。

### `GetObject`
<a name="s3_GetObject_rust_1_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
async fn get_object(client: Client, opt: Opt) -> Result<usize, S3ExampleError> {
    trace!("bucket:      {}", opt.bucket);
    trace!("object:      {}", opt.object);
    trace!("destination: {}", opt.destination.display());

    let mut file = File::create(opt.destination.clone()).map_err(|err| {
        S3ExampleError::new(format!(
            "Failed to initialize file for saving S3 download: {err:?}"
        ))
    })?;

    let mut object = client
        .get_object()
        .bucket(opt.bucket)
        .key(opt.object)
        .send()
        .await?;

    let mut byte_count = 0_usize;
    while let Some(bytes) = object.body.try_next().await.map_err(|err| {
        S3ExampleError::new(format!("Failed to read from S3 download stream: {err:?}"))
    })? {
        let bytes_len = bytes.len();
        file.write_all(&bytes).map_err(|err| {
            S3ExampleError::new(format!(
                "Failed to write from S3 download stream to local file: {err:?}"
            ))
        })?;
        trace!("Intermediate write of {bytes_len}");
        byte_count += bytes_len;
    }

    Ok(byte_count)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[GetObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.get_object)」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_rust_1_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
async fn show_buckets(
    strict: bool,
    client: &Client,
    region: BucketLocationConstraint,
) -> Result<(), S3ExampleError> {
    let mut buckets = client.list_buckets().into_paginator().send();

    let mut num_buckets = 0;
    let mut in_region = 0;

    while let Some(Ok(output)) = buckets.next().await {
        for bucket in output.buckets() {
            num_buckets += 1;
            if strict {
                let r = client
                    .get_bucket_location()
                    .bucket(bucket.name().unwrap_or_default())
                    .send()
                    .await?;

                if r.location_constraint() == Some(&region) {
                    println!("{}", bucket.name().unwrap_or_default());
                    in_region += 1;
                }
            } else {
                println!("{}", bucket.name().unwrap_or_default());
            }
        }
    }

    println!();
    if strict {
        println!(
            "Found {} buckets in the {} region out of a total of {} buckets.",
            in_region, region, num_buckets
        );
    } else {
        println!("Found {} buckets in all regions.", num_buckets);
    }

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListBuckets](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.list_buckets)」を参照してください。

### `ListObjectVersions`
<a name="s3_ListObjectVersions_rust_1_topic"></a>

次のコード例は、`ListObjectVersions` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
async fn show_versions(client: &Client, bucket: &str) -> Result<(), Error> {
    let resp = client.list_object_versions().bucket(bucket).send().await?;

    for version in resp.versions() {
        println!("{}", version.key().unwrap_or_default());
        println!("  version ID: {}", version.version_id().unwrap_or_default());
        println!();
    }

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[ListObjectVersions](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.list_object_versions)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_rust_1_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
pub async fn list_objects(client: &aws_sdk_s3::Client, bucket: &str) -> Result<(), S3ExampleError> {
    let mut response = client
        .list_objects_v2()
        .bucket(bucket.to_owned())
        .max_keys(10) // In this example, go 10 at a time.
        .into_paginator()
        .send();

    while let Some(result) = response.next().await {
        match result {
            Ok(output) => {
                for object in output.contents() {
                    println!(" - {}", object.key().unwrap_or("Unknown"));
                }
            }
            Err(err) => {
                eprintln!("{err:?}")
            }
        }
    }

    Ok(())
}
```
+  API の詳細については、「AWS SDK for Rust API リファレンス」の「[ListObjectsV2](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.list_objects_v2)」を参照してください。**

### `PutObject`
<a name="s3_PutObject_rust_1_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
pub async fn upload_object(
    client: &aws_sdk_s3::Client,
    bucket_name: &str,
    file_name: &str,
    key: &str,
) -> Result<aws_sdk_s3::operation::put_object::PutObjectOutput, S3ExampleError> {
    let body = aws_sdk_s3::primitives::ByteStream::from_path(std::path::Path::new(file_name)).await;
    client
        .put_object()
        .bucket(bucket_name)
        .key(key)
        .body(body.unwrap())
        .send()
        .await
        .map_err(S3ExampleError::from)
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[PutObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.put_object)」を参照してください。

### `UploadPart`
<a name="s3_UploadPart_rust_1_topic"></a>

次のコード例は、`UploadPart` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
    let mut upload_parts: Vec<aws_sdk_s3::types::CompletedPart> = Vec::new();

    for chunk_index in 0..chunk_count {
        let this_chunk = if chunk_count - 1 == chunk_index {
            size_of_last_chunk
        } else {
            CHUNK_SIZE
        };
        let stream = ByteStream::read_from()
            .path(path)
            .offset(chunk_index * CHUNK_SIZE)
            .length(Length::Exact(this_chunk))
            .build()
            .await
            .unwrap();

        // Chunk index needs to start at 0, but part numbers start at 1.
        let part_number = (chunk_index as i32) + 1;
        let upload_part_res = client
            .upload_part()
            .key(&key)
            .bucket(&bucket_name)
            .upload_id(upload_id)
            .body(stream)
            .part_number(part_number)
            .send()
            .await?;

        upload_parts.push(
            CompletedPart::builder()
                .e_tag(upload_part_res.e_tag.unwrap_or_default())
                .part_number(part_number)
                .build(),
        );
    }
```

```
    // Create a multipart upload. Use UploadPart and CompleteMultipartUpload to
    // upload the file.
    let multipart_upload_res: CreateMultipartUploadOutput = client
        .create_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .send()
        .await?;

    let upload_id = multipart_upload_res.upload_id().ok_or(S3ExampleError::new(
        "Missing upload_id after CreateMultipartUpload",
    ))?;
```

```
    // upload_parts: Vec<aws_sdk_s3::types::CompletedPart>
    let completed_multipart_upload: CompletedMultipartUpload = CompletedMultipartUpload::builder()
        .set_parts(Some(upload_parts))
        .build();

    let _complete_multipart_upload_res = client
        .complete_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .multipart_upload(completed_multipart_upload)
        .upload_id(upload_id)
        .send()
        .await?;
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[UploadPart](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.upload_part)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### テキストを音声に変換し、テキストに戻す
<a name="cross_Telephone_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Polly を使用して、プレーンテキスト (UTF-8) 入力ファイルを音声ファイルに合成します。
+ Amazon S3 バケットに音声ファイルをアップロードします。
+ Amazon Transcribe を使用して、音声ファイルをテキストに変換します。
+ テキストを表示します。

**SDK for Rust**  
 Amazon Polly を使用して、プレーンテキスト (UTF-8) 入力ファイルを音声ファイルに合成し、音声ファイルを Amazon S3 バケットにアップロードし、Amazon Transcribe を使用して音声ファイルをテキストに変換し、テキストを表示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service#code-examples) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Polly
+ Amazon S3
+ Amazon Transcribe

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_rust_1_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。
GET S3 オブジェクトへの事前署名リクエストを作成します。  

```
/// Generate a URL for a presigned GET request.
async fn get_object(
    client: &Client,
    bucket: &str,
    object: &str,
    expires_in: u64,
) -> Result<(), Box<dyn Error>> {
    let expires_in = Duration::from_secs(expires_in);
    let presigned_request = client
        .get_object()
        .bucket(bucket)
        .key(object)
        .presigned(PresigningConfig::expires_in(expires_in)?)
        .await?;

    println!("Object URI: {}", presigned_request.uri());
    let valid_until = chrono::offset::Local::now() + expires_in;
    println!("Valid until: {valid_until}");

    Ok(())
}
```
PUT S3 オブジェクトへの事前署名リクエストを作成します。  

```
async fn put_object(
    client: &Client,
    bucket: &str,
    object: &str,
    expires_in: u64,
) -> Result<String, S3ExampleError> {
    let expires_in: std::time::Duration = std::time::Duration::from_secs(expires_in);
    let expires_in: aws_sdk_s3::presigning::PresigningConfig =
        PresigningConfig::expires_in(expires_in).map_err(|err| {
            S3ExampleError::new(format!(
                "Failed to convert expiration to PresigningConfig: {err:?}"
            ))
        })?;
    let presigned_request = client
        .put_object()
        .bucket(bucket)
        .key(object)
        .presigned(expires_in)
        .await?;

    Ok(presigned_request.uri().into())
}
```

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_rust_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Rust**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/cross_service/photo_asset_management) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

### イメージ内の顔を検出します
<a name="cross_DetectFaces_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ イメージを Amazon S3 バケットに保存します。
+ Amazon Rekognition を使用して、年齢層、性別、感情 (笑顔など) などの顔の詳細を検出します。
+ これらの詳細を表示します。

**SDK for Rust**  
 **アップロード** プレフィックスを付け、Amazon S3 バケット内でイメージを保存し、Amazon Rekognition を使用して、年齢層、性別、感情 (笑顔など) などの顔の詳細を検出し、それらの詳細を表示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service/detect_faces/src/main.rs) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Rekognition
+ Amazon S3

### バケットが変更されている場合、バケットからオブジェクトを取得する
<a name="s3_GetObject_IfModifiedSince_rust_1_topic"></a>

次のコード例は、S3 バケット内のオブジェクトからデータを読み取る方法を示しています。ただし、そのバケットが前回の取得時刻以降に変更されていない場合に限ります。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
use aws_sdk_s3::{
    error::SdkError,
    primitives::{ByteStream, DateTime, DateTimeFormat},
    Client,
};
use s3_code_examples::error::S3ExampleError;
use tracing::{error, warn};

const KEY: &str = "key";
const BODY: &str = "Hello, world!";

/// Demonstrate how `if-modified-since` reports that matching objects haven't
/// changed.
///
/// # Steps
/// - Create a bucket.
/// - Put an object in the bucket.
/// - Get the bucket headers.
/// - Get the bucket headers again but only if modified.
/// - Delete the bucket.
#[tokio::main]
async fn main() -> Result<(), S3ExampleError> {
    tracing_subscriber::fmt::init();

    // Get a new UUID to use when creating a unique bucket name.
    let uuid = uuid::Uuid::new_v4();

    // Load the AWS configuration from the environment.
    let client = Client::new(&aws_config::load_from_env().await);

    // Generate a unique bucket name using the previously generated UUID.
    // Then create a new bucket with that name.
    let bucket_name = format!("if-modified-since-{uuid}");
    client
        .create_bucket()
        .bucket(bucket_name.clone())
        .send()
        .await?;

    // Create a new object in the bucket whose name is `KEY` and whose
    // contents are `BODY`.
    let put_object_output = client
        .put_object()
        .bucket(bucket_name.as_str())
        .key(KEY)
        .body(ByteStream::from_static(BODY.as_bytes()))
        .send()
        .await;

    // If the `PutObject` succeeded, get the eTag string from it. Otherwise,
    // report an error and return an empty string.
    let e_tag_1 = match put_object_output {
        Ok(put_object) => put_object.e_tag.unwrap(),
        Err(err) => {
            error!("{err:?}");
            String::new()
        }
    };

    // Request the object's headers.
    let head_object_output = client
        .head_object()
        .bucket(bucket_name.as_str())
        .key(KEY)
        .send()
        .await;

    // If the `HeadObject` request succeeded, create a tuple containing the
    // values of the headers `last-modified` and `etag`. If the request
    // failed, return the error in a tuple instead.
    let (last_modified, e_tag_2) = match head_object_output {
        Ok(head_object) => (
            Ok(head_object.last_modified().cloned().unwrap()),
            head_object.e_tag.unwrap(),
        ),
        Err(err) => (Err(err), String::new()),
    };

    warn!("last modified: {last_modified:?}");
    assert_eq!(
        e_tag_1, e_tag_2,
        "PutObject and first GetObject had differing eTags"
    );

    println!("First value of last_modified: {last_modified:?}");
    println!("First tag: {}\n", e_tag_1);

    // Send a second `HeadObject` request. This time, the `if_modified_since`
    // option is specified, giving the `last_modified` value returned by the
    // first call to `HeadObject`.
    //
    // Since the object hasn't been changed, and there are no other objects in
    // the bucket, there should be no matching objects.

    let head_object_output = client
        .head_object()
        .bucket(bucket_name.as_str())
        .key(KEY)
        .if_modified_since(last_modified.unwrap())
        .send()
        .await;

    // If the `HeadObject` request succeeded, the result is a typle containing
    // the `last_modified` and `e_tag_1` properties. This is _not_ the expected
    // result.
    //
    // The _expected_ result of the second call to `HeadObject` is an
    // `SdkError::ServiceError` containing the HTTP error response. If that's
    // the case and the HTTP status is 304 (not modified), the output is a
    // tuple containing the values of the HTTP `last-modified` and `etag`
    // headers.
    //
    // If any other HTTP error occurred, the error is returned as an
    // `SdkError::ServiceError`.

    let (last_modified, e_tag_2) = match head_object_output {
        Ok(head_object) => (
            Ok(head_object.last_modified().cloned().unwrap()),
            head_object.e_tag.unwrap(),
        ),
        Err(err) => match err {
            SdkError::ServiceError(err) => {
                // Get the raw HTTP response. If its status is 304, the
                // object has not changed. This is the expected code path.
                let http = err.raw();
                match http.status().as_u16() {
                    // If the HTTP status is 304: Not Modified, return a
                    // tuple containing the values of the HTTP
                    // `last-modified` and `etag` headers.
                    304 => (
                        Ok(DateTime::from_str(
                            http.headers().get("last-modified").unwrap(),
                            DateTimeFormat::HttpDate,
                        )
                        .unwrap()),
                        http.headers().get("etag").map(|t| t.into()).unwrap(),
                    ),
                    // Any other HTTP status code is returned as an
                    // `SdkError::ServiceError`.
                    _ => (Err(SdkError::ServiceError(err)), String::new()),
                }
            }
            // Any other kind of error is returned in a tuple containing the
            // error and an empty string.
            _ => (Err(err), String::new()),
        },
    };

    warn!("last modified: {last_modified:?}");
    assert_eq!(
        e_tag_1, e_tag_2,
        "PutObject and second HeadObject had different eTags"
    );

    println!("Second value of last modified: {last_modified:?}");
    println!("Second tag: {}", e_tag_2);

    // Clean up by deleting the object and the bucket.
    client
        .delete_object()
        .bucket(bucket_name.as_str())
        .key(KEY)
        .send()
        .await?;

    client
        .delete_bucket()
        .bucket(bucket_name.as_str())
        .send()
        .await?;

    Ok(())
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[GetObject](https://docs.rs/aws-sdk-s3/latest/aws_sdk_s3/client/struct.Client.html#method.get_object)」を参照してください。

### EXIF およびその他のイメージ情報を保存します
<a name="cross_DetectLabels_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ JPG、JPEG、または PNG ファイルから EXIF 情報を取得します。
+ Amazon S3 バケットにイメージファイルをアップロードします。
+ Amazon Rekognition を使用して、ファイル内の 3 つの上位属性 (ラベル) を特定します。
+ EXIF およびラベル情報を、リージョンの Amazon DynamoDB テーブルに追加します。

**SDK for Rust**  
 JPG、JPEG、または PNG ファイルから EXIF 情報を取得し、イメージファイルを Amazon S3 バケットにアップロードし、Amazon Rekognition を使用してファイル内の 3 つの上位属性 (Amazon Rekognition の*ラベル*) を特定し、リージョンの Amazon DynamoDB テーブルに EXIF およびラベル情報を追加します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service/detect_labels/src/main.rs) で完全な例を参照してください。  

**この例で使用されているサービス**
+ DynamoDB
+ Amazon Rekognition
+ Amazon S3

### SDK による単体テストと統合テスト
<a name="cross_Testing_rust_1_topic"></a>

次のコード例は、 AWS SDK を使用してユニットテストと統合テストを記述する際のベストプラクティス手法の例を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/testing#code-examples)での設定と実行の方法を確認してください。
Cargo.toml はテストサンプル用です。  

```
[package]
name = "testing-examples"
version = "0.1.0"
authors = [
  "John Disanti <jdisanti@amazon.com>",
  "Doug Schwartz <dougsch@amazon.com>",
]
edition = "2021"

[dependencies]
async-trait = "0.1.51"
aws-config = { version = "1.0.1", features = ["behavior-version-latest"] }
aws-credential-types = { version = "1.0.1", features = [ "hardcoded-credentials", ] }
aws-sdk-s3 = { version = "1.4.0" }
aws-smithy-types = { version = "1.0.1" }
aws-smithy-runtime = { version = "1.0.1", features = ["test-util"] }
aws-smithy-runtime-api = { version = "1.0.1", features = ["test-util"] }
aws-types = { version = "1.0.1" }
clap = { version = "4.4", features = ["derive"] }
http = "0.2.9"
mockall = "0.11.4"
serde_json = "1"
tokio = { version = "1.20.1", features = ["full"] }
tracing-subscriber = { version = "0.3.15", features = ["env-filter"] }

[[bin]]
name = "main"
path = "src/main.rs"
```
オートモックとサービスラッパーを使ったユニットテストの例。  

```
use aws_sdk_s3 as s3;
#[allow(unused_imports)]
use mockall::automock;

use s3::operation::list_objects_v2::{ListObjectsV2Error, ListObjectsV2Output};

#[cfg(test)]
pub use MockS3Impl as S3;
#[cfg(not(test))]
pub use S3Impl as S3;

#[allow(dead_code)]
pub struct S3Impl {
    inner: s3::Client,
}

#[cfg_attr(test, automock)]
impl S3Impl {
    #[allow(dead_code)]
    pub fn new(inner: s3::Client) -> Self {
        Self { inner }
    }

    #[allow(dead_code)]
    pub async fn list_objects(
        &self,
        bucket: &str,
        prefix: &str,
        continuation_token: Option<String>,
    ) -> Result<ListObjectsV2Output, s3::error::SdkError<ListObjectsV2Error>> {
        self.inner
            .list_objects_v2()
            .bucket(bucket)
            .prefix(prefix)
            .set_continuation_token(continuation_token)
            .send()
            .await
    }
}

#[allow(dead_code)]
pub async fn determine_prefix_file_size(
    // Now we take a reference to our trait object instead of the S3 client
    // s3_list: ListObjectsService,
    s3_list: S3,
    bucket: &str,
    prefix: &str,
) -> Result<usize, s3::Error> {
    let mut next_token: Option<String> = None;
    let mut total_size_bytes = 0;
    loop {
        let result = s3_list
            .list_objects(bucket, prefix, next_token.take())
            .await?;

        // Add up the file sizes we got back
        for object in result.contents() {
            total_size_bytes += object.size().unwrap_or(0) as usize;
        }

        // Handle pagination, and break the loop if there are no more pages
        next_token = result.next_continuation_token.clone();
        if next_token.is_none() {
            break;
        }
    }
    Ok(total_size_bytes)
}

#[cfg(test)]
mod test {
    use super::*;
    use mockall::predicate::eq;

    #[tokio::test]
    async fn test_single_page() {
        let mut mock = MockS3Impl::default();
        mock.expect_list_objects()
            .with(eq("test-bucket"), eq("test-prefix"), eq(None))
            .return_once(|_, _, _| {
                Ok(ListObjectsV2Output::builder()
                    .set_contents(Some(vec![
                        // Mock content for ListObjectsV2 response
                        s3::types::Object::builder().size(5).build(),
                        s3::types::Object::builder().size(2).build(),
                    ]))
                    .build())
            });

        // Run the code we want to test with it
        let size = determine_prefix_file_size(mock, "test-bucket", "test-prefix")
            .await
            .unwrap();

        // Verify we got the correct total size back
        assert_eq!(7, size);
    }

    #[tokio::test]
    async fn test_multiple_pages() {
        // Create the Mock instance with two pages of objects now
        let mut mock = MockS3Impl::default();
        mock.expect_list_objects()
            .with(eq("test-bucket"), eq("test-prefix"), eq(None))
            .return_once(|_, _, _| {
                Ok(ListObjectsV2Output::builder()
                    .set_contents(Some(vec![
                        // Mock content for ListObjectsV2 response
                        s3::types::Object::builder().size(5).build(),
                        s3::types::Object::builder().size(2).build(),
                    ]))
                    .set_next_continuation_token(Some("next".to_string()))
                    .build())
            });
        mock.expect_list_objects()
            .with(
                eq("test-bucket"),
                eq("test-prefix"),
                eq(Some("next".to_string())),
            )
            .return_once(|_, _, _| {
                Ok(ListObjectsV2Output::builder()
                    .set_contents(Some(vec![
                        // Mock content for ListObjectsV2 response
                        s3::types::Object::builder().size(3).build(),
                        s3::types::Object::builder().size(9).build(),
                    ]))
                    .build())
            });

        // Run the code we want to test with it
        let size = determine_prefix_file_size(mock, "test-bucket", "test-prefix")
            .await
            .unwrap();

        assert_eq!(19, size);
    }
}
```
StaticReplayClient を使用した統合テストの例。  

```
use aws_sdk_s3 as s3;

#[allow(dead_code)]
pub async fn determine_prefix_file_size(
    // Now we take a reference to our trait object instead of the S3 client
    // s3_list: ListObjectsService,
    s3: s3::Client,
    bucket: &str,
    prefix: &str,
) -> Result<usize, s3::Error> {
    let mut next_token: Option<String> = None;
    let mut total_size_bytes = 0;
    loop {
        let result = s3
            .list_objects_v2()
            .prefix(prefix)
            .bucket(bucket)
            .set_continuation_token(next_token.take())
            .send()
            .await?;

        // Add up the file sizes we got back
        for object in result.contents() {
            total_size_bytes += object.size().unwrap_or(0) as usize;
        }

        // Handle pagination, and break the loop if there are no more pages
        next_token = result.next_continuation_token.clone();
        if next_token.is_none() {
            break;
        }
    }
    Ok(total_size_bytes)
}

#[allow(dead_code)]
fn make_s3_test_credentials() -> s3::config::Credentials {
    s3::config::Credentials::new(
        "ATESTCLIENT",
        "astestsecretkey",
        Some("atestsessiontoken".to_string()),
        None,
        "",
    )
}

#[cfg(test)]
mod test {
    use super::*;
    use aws_config::BehaviorVersion;
    use aws_sdk_s3 as s3;
    use aws_smithy_runtime::client::http::test_util::{ReplayEvent, StaticReplayClient};
    use aws_smithy_types::body::SdkBody;

    #[tokio::test]
    async fn test_single_page() {
        let page_1 = ReplayEvent::new(
                http::Request::builder()
                    .method("GET")
                    .uri("https://test-bucket.s3.us-east-1.amazonaws.com/?list-type=2&prefix=test-prefix")
                    .body(SdkBody::empty())
                    .unwrap(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(include_str!("./testing/response_1.xml")))
                    .unwrap(),
            );
        let replay_client = StaticReplayClient::new(vec![page_1]);
        let client: s3::Client = s3::Client::from_conf(
            s3::Config::builder()
                .behavior_version(BehaviorVersion::latest())
                .credentials_provider(make_s3_test_credentials())
                .region(s3::config::Region::new("us-east-1"))
                .http_client(replay_client.clone())
                .build(),
        );

        // Run the code we want to test with it
        let size = determine_prefix_file_size(client, "test-bucket", "test-prefix")
            .await
            .unwrap();

        // Verify we got the correct total size back
        assert_eq!(7, size);
        replay_client.assert_requests_match(&[]);
    }

    #[tokio::test]
    async fn test_multiple_pages() {
        let page_1 = ReplayEvent::new(
                http::Request::builder()
                    .method("GET")
                    .uri("https://test-bucket.s3.us-east-1.amazonaws.com/?list-type=2&prefix=test-prefix")
                    .body(SdkBody::empty())
                    .unwrap(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(include_str!("./testing/response_multi_1.xml")))
                    .unwrap(),
            );
        let page_2 = ReplayEvent::new(
                http::Request::builder()
                    .method("GET")
                    .uri("https://test-bucket.s3.us-east-1.amazonaws.com/?list-type=2&prefix=test-prefix&continuation-token=next")
                    .body(SdkBody::empty())
                    .unwrap(),
                http::Response::builder()
                    .status(200)
                    .body(SdkBody::from(include_str!("./testing/response_multi_2.xml")))
                    .unwrap(),
            );
        let replay_client = StaticReplayClient::new(vec![page_1, page_2]);
        let client: s3::Client = s3::Client::from_conf(
            s3::Config::builder()
                .behavior_version(BehaviorVersion::latest())
                .credentials_provider(make_s3_test_credentials())
                .region(s3::config::Region::new("us-east-1"))
                .http_client(replay_client.clone())
                .build(),
        );

        // Run the code we want to test with it
        let size = determine_prefix_file_size(client, "test-bucket", "test-prefix")
            .await
            .unwrap();

        assert_eq!(19, size);

        replay_client.assert_requests_match(&[]);
    }
}
```

### 大きなファイルをアップロードまたはダウンロードする
<a name="s3_Scenario_UsingLargeFiles_rust_1_topic"></a>

次のコード例は、Amazon S3 との間で大きなファイルをアップロードまたはダウンロードする方法を示しています。

詳細については、「[マルチパートアップロードを使用したオブジェクトのアップロード](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-upload-object.html)」を参照してください。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/s3#code-examples)での設定と実行の方法を確認してください。

```
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;

use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::error::DisplayErrorContext;
use aws_sdk_s3::operation::{
    create_multipart_upload::CreateMultipartUploadOutput, get_object::GetObjectOutput,
};
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
use aws_sdk_s3::{config::Region, Client as S3Client};
use aws_smithy_types::byte_stream::{ByteStream, Length};
use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};
use s3_code_examples::error::S3ExampleError;
use std::process;
use uuid::Uuid;

//In bytes, minimum chunk size of 5MB. Increase CHUNK_SIZE to send larger chunks.
const CHUNK_SIZE: u64 = 1024 * 1024 * 5;
const MAX_CHUNKS: u64 = 10000;

#[tokio::main]
pub async fn main() {
    if let Err(err) = run_example().await {
        eprintln!("Error: {}", DisplayErrorContext(err));
        process::exit(1);
    }
}

async fn run_example() -> Result<(), S3ExampleError> {
    let shared_config = aws_config::load_from_env().await;
    let client = S3Client::new(&shared_config);

    let bucket_name = format!("amzn-s3-demo-bucket-{}", Uuid::new_v4());
    let region_provider = RegionProviderChain::first_try(Region::new("us-west-2"));
    let region = region_provider.region().await.unwrap();
    s3_code_examples::create_bucket(&client, &bucket_name, &region).await?;

    let key = "sample.txt".to_string();
    // Create a multipart upload. Use UploadPart and CompleteMultipartUpload to
    // upload the file.
    let multipart_upload_res: CreateMultipartUploadOutput = client
        .create_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .send()
        .await?;

    let upload_id = multipart_upload_res.upload_id().ok_or(S3ExampleError::new(
        "Missing upload_id after CreateMultipartUpload",
    ))?;

    //Create a file of random characters for the upload.
    let mut file = File::create(&key).expect("Could not create sample file.");
    // Loop until the file is 5 chunks.
    while file.metadata().unwrap().len() <= CHUNK_SIZE * 4 {
        let rand_string: String = thread_rng()
            .sample_iter(&Alphanumeric)
            .take(256)
            .map(char::from)
            .collect();
        let return_string: String = "\n".to_string();
        file.write_all(rand_string.as_ref())
            .expect("Error writing to file.");
        file.write_all(return_string.as_ref())
            .expect("Error writing to file.");
    }

    let path = Path::new(&key);
    let file_size = tokio::fs::metadata(path)
        .await
        .expect("it exists I swear")
        .len();

    let mut chunk_count = (file_size / CHUNK_SIZE) + 1;
    let mut size_of_last_chunk = file_size % CHUNK_SIZE;
    if size_of_last_chunk == 0 {
        size_of_last_chunk = CHUNK_SIZE;
        chunk_count -= 1;
    }

    if file_size == 0 {
        return Err(S3ExampleError::new("Bad file size."));
    }
    if chunk_count > MAX_CHUNKS {
        return Err(S3ExampleError::new(
            "Too many chunks! Try increasing your chunk size.",
        ));
    }

    let mut upload_parts: Vec<aws_sdk_s3::types::CompletedPart> = Vec::new();

    for chunk_index in 0..chunk_count {
        let this_chunk = if chunk_count - 1 == chunk_index {
            size_of_last_chunk
        } else {
            CHUNK_SIZE
        };
        let stream = ByteStream::read_from()
            .path(path)
            .offset(chunk_index * CHUNK_SIZE)
            .length(Length::Exact(this_chunk))
            .build()
            .await
            .unwrap();

        // Chunk index needs to start at 0, but part numbers start at 1.
        let part_number = (chunk_index as i32) + 1;
        let upload_part_res = client
            .upload_part()
            .key(&key)
            .bucket(&bucket_name)
            .upload_id(upload_id)
            .body(stream)
            .part_number(part_number)
            .send()
            .await?;

        upload_parts.push(
            CompletedPart::builder()
                .e_tag(upload_part_res.e_tag.unwrap_or_default())
                .part_number(part_number)
                .build(),
        );
    }

    // upload_parts: Vec<aws_sdk_s3::types::CompletedPart>
    let completed_multipart_upload: CompletedMultipartUpload = CompletedMultipartUpload::builder()
        .set_parts(Some(upload_parts))
        .build();

    let _complete_multipart_upload_res = client
        .complete_multipart_upload()
        .bucket(&bucket_name)
        .key(&key)
        .multipart_upload(completed_multipart_upload)
        .upload_id(upload_id)
        .send()
        .await?;

    let data: GetObjectOutput =
        s3_code_examples::download_object(&client, &bucket_name, &key).await?;
    let data_length: u64 = data
        .content_length()
        .unwrap_or_default()
        .try_into()
        .unwrap();
    if file.metadata().unwrap().len() == data_length {
        println!("Data lengths match.");
    } else {
        println!("The data was not the same size!");
    }

    s3_code_examples::clear_bucket(&client, &bucket_name)
        .await
        .expect("Error emptying bucket.");
    s3_code_examples::delete_bucket(&client, &bucket_name)
        .await
        .expect("Error deleting bucket.");

    Ok(())
}
```

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon S3 トリガーから Lambda 関数を呼び出す
<a name="serverless_S3_Lambda_rust_1_topic"></a>

次のコード例は、S3 バケットにオブジェクトをアップロードすることによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数は、イベントパラメータから S3 バケット名とオブジェクトキーを取得し、Amazon S3 API を呼び出してオブジェクトのコンテンツタイプを取得してログに記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)リポジトリで完全な例を検索し、設定および実行の方法を確認してください。
Rust を使用して Lambda で S3 イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::s3::S3Event;
use aws_sdk_s3::{Client};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};


/// Main function
#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .with_target(false)
        .without_time()
        .init();

    // Initialize the AWS SDK for Rust
    let config = aws_config::load_from_env().await;
    let s3_client = Client::new(&config);

    let res = run(service_fn(|request: LambdaEvent<S3Event>| {
        function_handler(&s3_client, request)
    })).await;

    res
}

async fn function_handler(
    s3_client: &Client,
    evt: LambdaEvent<S3Event>
) -> Result<(), Error> {
    tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS");

    if evt.payload.records.len() == 0 {
        tracing::info!("Empty S3 event received");
    }

    let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist");
    let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist");

    tracing::info!("Request is for {} and object {}", bucket, key);

    let s3_get_object_result = s3_client
        .get_object()
        .bucket(bucket)
        .key(key)
        .send()
        .await;

    match s3_get_object_result {
        Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"),
        Err(_) => tracing::info!("Failure with S3 Get Object request")
    }

    Ok(())
}
```

# SDK for Rust を使用した SageMaker AI の例
<a name="rust_1_sagemaker_code_examples"></a>

次のコード例は、SageMaker AI で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListNotebookInstances`
<a name="sagemaker_ListNotebookInstances_rust_1_topic"></a>

次のコード例は、`ListNotebookInstances` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sagemaker#code-examples)での設定と実行の方法を確認してください。

```
async fn show_instances(client: &Client) -> Result<(), Error> {
    let notebooks = client.list_notebook_instances().send().await?;

    println!("Notebooks:");

    for n in notebooks.notebook_instances() {
        let n_instance_type = n.instance_type().unwrap();
        let n_status = n.notebook_instance_status().unwrap();
        let n_name = n.notebook_instance_name();

        println!("  Name :          {}", n_name.unwrap_or("Unknown"));
        println!("  Status :        {}", n_status.as_ref());
        println!("  Instance Type : {}", n_instance_type.as_ref());
        println!();
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListNotebookInstances](https://docs.rs/aws-sdk-sagemaker/latest/aws_sdk_sagemaker/client/struct.Client.html#method.list_notebook_instances)」を参照してください。

### `ListTrainingJobs`
<a name="sagemaker_ListTrainingJobs_rust_1_topic"></a>

次のコード例は、`ListTrainingJobs` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sagemaker#code-examples)での設定と実行の方法を確認してください。

```
async fn show_jobs(client: &Client) -> Result<(), Error> {
    let job_details = client.list_training_jobs().send().await?;

    println!("Jobs:");

    for j in job_details.training_job_summaries() {
        let name = j.training_job_name().unwrap_or("Unknown");
        let creation_time = j.creation_time().expect("creation time").to_chrono_utc()?;
        let training_end_time = j
            .training_end_time()
            .expect("Training end time")
            .to_chrono_utc()?;

        let status = j.training_job_status().expect("training status");
        let duration = training_end_time - creation_time;

        println!("  Name:               {}", name);
        println!(
            "  Creation date/time: {}",
            creation_time.format("%Y-%m-%d@%H:%M:%S")
        );
        println!("  Duration (seconds): {}", duration.num_seconds());
        println!("  Status:             {:?}", status);

        println!();
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListTrainingJobs](https://docs.rs/aws-sdk-sagemaker/latest/aws_sdk_sagemaker/client/struct.Client.html#method.list_training_jobs)」を参照してください。

# SDK for Rust を使用した Secrets Manager の例
<a name="rust_1_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_rust_1_topic"></a>

次のコード例は、`GetSecretValue` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/secretsmanager#code-examples)での設定と実行の方法を確認してください。

```
async fn show_secret(client: &Client, name: &str) -> Result<(), Error> {
    let resp = client.get_secret_value().secret_id(name).send().await?;

    println!("Value: {}", resp.secret_string().unwrap_or("No value!"));

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[GetSecretValue](https://docs.rs/aws-sdk-secretsmanager/latest/aws_sdk_secretsmanager/client/struct.Client.html#method.get_secret_value)」を参照してください。

# SDK for Rust を使用した Amazon SES API v2 の例
<a name="rust_1_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateContact`
<a name="sesv2_CreateContact_rust_1_topic"></a>

次のコード例は、`CreateContact` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
async fn add_contact(client: &Client, list: &str, email: &str) -> Result<(), Error> {
    client
        .create_contact()
        .contact_list_name(list)
        .email_address(email)
        .send()
        .await?;

    println!("Created contact");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CreateContact](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_contact)」を参照してください。

### `CreateContactList`
<a name="sesv2_CreateContactList_rust_1_topic"></a>

次のコード例は、`CreateContactList` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
async fn make_list(client: &Client, contact_list: &str) -> Result<(), Error> {
    client
        .create_contact_list()
        .contact_list_name(contact_list)
        .send()
        .await?;

    println!("Created contact list.");

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[CreateContactList](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_contact_list)」を参照してください。

### `CreateEmailIdentity`
<a name="sesv2_CreateEmailIdentity_rust_1_topic"></a>

次のコード例は、`CreateEmailIdentity` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
        match self
            .client
            .create_email_identity()
            .email_identity(self.verified_email.clone())
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Email identity created successfully.")?,
            Err(e) => match e.into_service_error() {
                CreateEmailIdentityError::AlreadyExistsException(_) => {
                    writeln!(
                        self.stdout,
                        "Email identity already exists, skipping creation."
                    )?;
                }
                e => return Err(anyhow!("Error creating email identity: {}", e)),
            },
        }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateEmailIdentity](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_email_identity)」を参照してください。

### `CreateEmailTemplate`
<a name="sesv2_CreateEmailTemplate_rust_1_topic"></a>

次のコード例は、`CreateEmailTemplate` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
        let template_html =
            std::fs::read_to_string("../resources/newsletter/coupon-newsletter.html")
                .unwrap_or_else(|_| "Missing coupon-newsletter.html".to_string());
        let template_text =
            std::fs::read_to_string("../resources/newsletter/coupon-newsletter.txt")
                .unwrap_or_else(|_| "Missing coupon-newsletter.txt".to_string());

        // Create the email template
        let template_content = EmailTemplateContent::builder()
            .subject("Weekly Coupons Newsletter")
            .html(template_html)
            .text(template_text)
            .build();

        match self
            .client
            .create_email_template()
            .template_name(TEMPLATE_NAME)
            .template_content(template_content)
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Email template created successfully.")?,
            Err(e) => match e.into_service_error() {
                CreateEmailTemplateError::AlreadyExistsException(_) => {
                    writeln!(
                        self.stdout,
                        "Email template already exists, skipping creation."
                    )?;
                }
                e => return Err(anyhow!("Error creating email template: {}", e)),
            },
        }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[CreateEmailTemplate](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_email_template)」を参照してください。

### `DeleteContactList`
<a name="sesv2_DeleteContactList_rust_1_topic"></a>

次のコード例は、`DeleteContactList` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
        match self
            .client
            .delete_contact_list()
            .contact_list_name(CONTACT_LIST_NAME)
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Contact list deleted successfully.")?,
            Err(e) => return Err(anyhow!("Error deleting contact list: {e}")),
        }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteContactList](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.delete_contact_list)」を参照してください。

### `DeleteEmailIdentity`
<a name="sesv2_DeleteEmailIdentity_rust_1_topic"></a>

次のコード例は、`DeleteEmailIdentity` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
            match self
                .client
                .delete_email_identity()
                .email_identity(self.verified_email.clone())
                .send()
                .await
            {
                Ok(_) => writeln!(self.stdout, "Email identity deleted successfully.")?,
                Err(e) => {
                    return Err(anyhow!("Error deleting email identity: {}", e));
                }
            }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteEmailIdentity](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.delete_email_identity)」を参照してください。

### `DeleteEmailTemplate`
<a name="sesv2_DeleteEmailTemplate_rust_1_topic"></a>

次のコード例は、`DeleteEmailTemplate` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
        match self
            .client
            .delete_email_template()
            .template_name(TEMPLATE_NAME)
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Email template deleted successfully.")?,
            Err(e) => {
                return Err(anyhow!("Error deleting email template: {e}"));
            }
        }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[DeleteEmailTemplate](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.delete_email_template)」を参照してください。

### `GetEmailIdentity`
<a name="sesv2_GetEmailIdentity_rust_1_topic"></a>

次のコード例は、`GetEmailIdentity` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。
E メールアドレスが検証されたかどうかを判定します。  

```
async fn is_verified(client: &Client, email: &str) -> Result<(), Error> {
    let resp = client
        .get_email_identity()
        .email_identity(email)
        .send()
        .await?;

    if resp.verified_for_sending_status() {
        println!("The address is verified");
    } else {
        println!("The address is not verified");
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[GetEmailIdentity](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.get_email_identity)」を参照してください。

### `ListContactLists`
<a name="sesv2_ListContactLists_rust_1_topic"></a>

次のコード例は、`ListContactLists` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
async fn show_lists(client: &Client) -> Result<(), Error> {
    let resp = client.list_contact_lists().send().await?;

    println!("Contact lists:");

    for list in resp.contact_lists() {
        println!("  {}", list.contact_list_name().unwrap_or_default());
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListContactLists](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.list_contact_lists)」を参照してください。

### `ListContacts`
<a name="sesv2_ListContacts_rust_1_topic"></a>

次のコード例は、`ListContacts` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
async fn show_contacts(client: &Client, list: &str) -> Result<(), Error> {
    let resp = client
        .list_contacts()
        .contact_list_name(list)
        .send()
        .await?;

    println!("Contacts:");

    for contact in resp.contacts() {
        println!("  {}", contact.email_address().unwrap_or_default());
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListContacts](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.list_contacts)」を参照してください。

### `SendEmail`
<a name="sesv2_SendEmail_rust_1_topic"></a>

次のコード例は、`SendEmail` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。
連絡先リストのすべてのメンバーにメッセージを送信します。  

```
async fn send_message(
    client: &Client,
    list: &str,
    from: &str,
    subject: &str,
    message: &str,
) -> Result<(), Error> {
    // Get list of email addresses from contact list.
    let resp = client
        .list_contacts()
        .contact_list_name(list)
        .send()
        .await?;

    let contacts = resp.contacts();

    let cs: Vec<String> = contacts
        .iter()
        .map(|i| i.email_address().unwrap_or_default().to_string())
        .collect();

    let mut dest: Destination = Destination::builder().build();
    dest.to_addresses = Some(cs);
    let subject_content = Content::builder()
        .data(subject)
        .charset("UTF-8")
        .build()
        .expect("building Content");
    let body_content = Content::builder()
        .data(message)
        .charset("UTF-8")
        .build()
        .expect("building Content");
    let body = Body::builder().text(body_content).build();

    let msg = Message::builder()
        .subject(subject_content)
        .body(body)
        .build();

    let email_content = EmailContent::builder().simple(msg).build();

    client
        .send_email()
        .from_email_address(from)
        .destination(dest)
        .content(email_content)
        .send()
        .await?;

    println!("Email sent to list");

    Ok(())
}
```
テンプレートを使用して、連絡先リストのメンバー全員にメッセージを送信します。  

```
            let coupons = std::fs::read_to_string("../resources/newsletter/sample_coupons.json")
                .unwrap_or_else(|_| r#"{"coupons":[]}"#.to_string());
            let email_content = EmailContent::builder()
                .template(
                    Template::builder()
                        .template_name(TEMPLATE_NAME)
                        .template_data(coupons)
                        .build(),
                )
                .build();

            match self
                .client
                .send_email()
                .from_email_address(self.verified_email.clone())
                .destination(Destination::builder().to_addresses(email.clone()).build())
                .content(email_content)
                .list_management_options(
                    ListManagementOptions::builder()
                        .contact_list_name(CONTACT_LIST_NAME)
                        .build()?,
                )
                .send()
                .await
            {
                Ok(output) => {
                    if let Some(message_id) = output.message_id {
                        writeln!(
                            self.stdout,
                            "Newsletter sent to {} with message ID {}",
                            email, message_id
                        )?;
                    } else {
                        writeln!(self.stdout, "Newsletter sent to {}", email)?;
                    }
                }
                Err(e) => return Err(anyhow!("Error sending newsletter to {}: {}", email, e)),
            }
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[SendEmail](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.send_email)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ニュースレターのシナリオ
<a name="sesv2_NewsletterWorkflow_rust_1_topic"></a>

以下のコード例は、Amazon SES API v2 のニュースレターのシナリオを実行する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ses#code-examples)での設定と実行の方法を確認してください。

```
        match self
            .client
            .create_contact_list()
            .contact_list_name(CONTACT_LIST_NAME)
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Contact list created successfully.")?,
            Err(e) => match e.into_service_error() {
                CreateContactListError::AlreadyExistsException(_) => {
                    writeln!(
                        self.stdout,
                        "Contact list already exists, skipping creation."
                    )?;
                }
                e => return Err(anyhow!("Error creating contact list: {}", e)),
            },
        }

            match self
                .client
                .create_contact()
                .contact_list_name(CONTACT_LIST_NAME)
                .email_address(email.clone())
                .send()
                .await
            {
                Ok(_) => writeln!(self.stdout, "Contact created for {}", email)?,
                Err(e) => match e.into_service_error() {
                    CreateContactError::AlreadyExistsException(_) => writeln!(
                        self.stdout,
                        "Contact already exists for {}, skipping creation.",
                        email
                    )?,
                    e => return Err(anyhow!("Error creating contact for {}: {}", email, e)),
                },
            }

        let contacts: Vec<Contact> = match self
            .client
            .list_contacts()
            .contact_list_name(CONTACT_LIST_NAME)
            .send()
            .await
        {
            Ok(list_contacts_output) => {
                list_contacts_output.contacts.unwrap().into_iter().collect()
            }
            Err(e) => {
                return Err(anyhow!(
                    "Error retrieving contact list {}: {}",
                    CONTACT_LIST_NAME,
                    e
                ))
            }
        };

            let coupons = std::fs::read_to_string("../resources/newsletter/sample_coupons.json")
                .unwrap_or_else(|_| r#"{"coupons":[]}"#.to_string());
            let email_content = EmailContent::builder()
                .template(
                    Template::builder()
                        .template_name(TEMPLATE_NAME)
                        .template_data(coupons)
                        .build(),
                )
                .build();

            match self
                .client
                .send_email()
                .from_email_address(self.verified_email.clone())
                .destination(Destination::builder().to_addresses(email.clone()).build())
                .content(email_content)
                .list_management_options(
                    ListManagementOptions::builder()
                        .contact_list_name(CONTACT_LIST_NAME)
                        .build()?,
                )
                .send()
                .await
            {
                Ok(output) => {
                    if let Some(message_id) = output.message_id {
                        writeln!(
                            self.stdout,
                            "Newsletter sent to {} with message ID {}",
                            email, message_id
                        )?;
                    } else {
                        writeln!(self.stdout, "Newsletter sent to {}", email)?;
                    }
                }
                Err(e) => return Err(anyhow!("Error sending newsletter to {}: {}", email, e)),
            }

        match self
            .client
            .create_email_identity()
            .email_identity(self.verified_email.clone())
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Email identity created successfully.")?,
            Err(e) => match e.into_service_error() {
                CreateEmailIdentityError::AlreadyExistsException(_) => {
                    writeln!(
                        self.stdout,
                        "Email identity already exists, skipping creation."
                    )?;
                }
                e => return Err(anyhow!("Error creating email identity: {}", e)),
            },
        }

        let template_html =
            std::fs::read_to_string("../resources/newsletter/coupon-newsletter.html")
                .unwrap_or_else(|_| "Missing coupon-newsletter.html".to_string());
        let template_text =
            std::fs::read_to_string("../resources/newsletter/coupon-newsletter.txt")
                .unwrap_or_else(|_| "Missing coupon-newsletter.txt".to_string());

        // Create the email template
        let template_content = EmailTemplateContent::builder()
            .subject("Weekly Coupons Newsletter")
            .html(template_html)
            .text(template_text)
            .build();

        match self
            .client
            .create_email_template()
            .template_name(TEMPLATE_NAME)
            .template_content(template_content)
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Email template created successfully.")?,
            Err(e) => match e.into_service_error() {
                CreateEmailTemplateError::AlreadyExistsException(_) => {
                    writeln!(
                        self.stdout,
                        "Email template already exists, skipping creation."
                    )?;
                }
                e => return Err(anyhow!("Error creating email template: {}", e)),
            },
        }

        match self
            .client
            .delete_contact_list()
            .contact_list_name(CONTACT_LIST_NAME)
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Contact list deleted successfully.")?,
            Err(e) => return Err(anyhow!("Error deleting contact list: {e}")),
        }

            match self
                .client
                .delete_email_identity()
                .email_identity(self.verified_email.clone())
                .send()
                .await
            {
                Ok(_) => writeln!(self.stdout, "Email identity deleted successfully.")?,
                Err(e) => {
                    return Err(anyhow!("Error deleting email identity: {}", e));
                }
            }

        match self
            .client
            .delete_email_template()
            .template_name(TEMPLATE_NAME)
            .send()
            .await
        {
            Ok(_) => writeln!(self.stdout, "Email template deleted successfully.")?,
            Err(e) => {
                return Err(anyhow!("Error deleting email template: {e}"));
            }
        }
```
+ API の詳細については、「*AWS SDK for Rust API リファレンス*」の以下のトピックを参照してください。
  + [CreateContact](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_contact)
  + [CreateContactList](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_contact_list)
  + [CreateEmailIdentity](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_email_identity)
  + [CreateEmailTemplate](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.create_email_template)
  + [DeleteContactList](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.delete_contact_list)
  + [DeleteEmailIdentity](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.delete_email_identity)
  + [DeleteEmailTemplate](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.delete_email_template)
  + [ListContacts](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.list_contacts)
  + [SendEmail.simple](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.send_email.simple)
  + [SendEmail.template](https://docs.rs/aws-sdk-sesv2/latest/aws_sdk_sesv2/client/struct.Client.html#method.send_email.template)

# SDK for Rust を使用した Amazon SNS の例
<a name="rust_1_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_rust_1_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)での設定と実行の方法を確認してください。

```
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](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.create_topic)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_rust_1_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)での設定と実行の方法を確認してください。

```
async fn show_topics(client: &Client) -> Result<(), Error> {
    let resp = client.list_topics().send().await?;

    println!("Topic ARNs:");

    for topic in resp.topics() {
        println!("{}", topic.topic_arn().unwrap_or_default());
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListTopics](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.list_topics)」を参照してください。

### `Publish`
<a name="sns_Publish_rust_1_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)での設定と実行の方法を確認してください。

```
async fn subscribe_and_publish(
    client: &Client,
    topic_arn: &str,
    email_address: &str,
) -> Result<(), Error> {
    println!("Receiving on topic with ARN: `{}`", topic_arn);

    let rsp = client
        .subscribe()
        .topic_arn(topic_arn)
        .protocol("email")
        .endpoint(email_address)
        .send()
        .await?;

    println!("Added a subscription: {:?}", rsp);

    let rsp = client
        .publish()
        .topic_arn(topic_arn)
        .message("hello sns!")
        .send()
        .await?;

    println!("Published message: {:?}", rsp);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[発行](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.publish)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_rust_1_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
async fn subscribe_and_publish(
    client: &Client,
    topic_arn: &str,
    email_address: &str,
) -> Result<(), Error> {
    println!("Receiving on topic with ARN: `{}`", topic_arn);

    let rsp = client
        .subscribe()
        .topic_arn(topic_arn)
        .protocol("email")
        .endpoint(email_address)
        .send()
        .await?;

    println!("Added a subscription: {:?}", rsp);

    let rsp = client
        .publish()
        .topic_arn(topic_arn)
        .message("hello sns!")
        .send()
        .await?;

    println!("Published message: {:?}", rsp);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[Subscribe](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.subscribe)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サーバーレスアプリケーションを作成して写真を管理する
<a name="cross_PAM_rust_1_topic"></a>

次のコード例では、ユーザーがラベルを使用して写真を管理できるサーバーレスアプリケーションを作成する方法について示しています。

**SDK for Rust**  
 Amazon Rekognition を使用して画像内のラベルを検出し、保存して後で取得できるようにする写真アセット管理アプリケーションの開発方法を示します。  
完全なソースコードと設定および実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/cross_service/photo_asset_management) で完全な例を参照してください。  
この例のソースについて詳しくは、[AWS  コミュニティ](https://community.aws/posts/cloud-journeys/01-serverless-image-recognition-app)でブログ投稿を参照してください。  

**この例で使用されているサービス**
+ API ゲートウェイ
+ DynamoDB
+ Lambda
+ Amazon Rekognition
+ Amazon S3
+ Amazon SNS

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SNS トリガーから Lambda 関数を呼び出す
<a name="serverless_SNS_Lambda_rust_1_topic"></a>

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sns-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で SNS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::sns::SnsEvent;
use aws_lambda_events::sns::SnsRecord;
use lambda_runtime::{run, service_fn, Error, LambdaEvent};
use tracing::info;

// Built with the following dependencies:
//  aws_lambda_events = { version = "0.10.0", default-features = false, features = ["sns"] }
//  lambda_runtime = "0.8.1"
//  tokio = { version = "1", features = ["macros"] }
//  tracing = { version = "0.1", features = ["log"] }
//  tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }

async fn function_handler(event: LambdaEvent<SnsEvent>) -> Result<(), Error> {
    for event in event.payload.records {
        process_record(&event)?;
    }
    
    Ok(())
}

fn process_record(record: &SnsRecord) -> Result<(), Error> {
    info!("Processing SNS Message: {}", record.sns.message);

    // Implement your record handling code here.

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        .with_target(false)
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

# SDK for Rust を使用した Amazon SQS の例
<a name="rust_1_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [サーバーレスサンプル](#serverless_examples)

## アクション
<a name="actions"></a>

### `ListQueues`
<a name="sqs_ListQueues_rust_1_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sqs#code-examples)での設定と実行の方法を確認してください。
リージョンにリストされている最初の Amazon SQS キューを取得します。  

```
async fn find_first_queue(client: &Client) -> Result<String, Error> {
    let queues = client.list_queues().send().await?;
    let queue_urls = queues.queue_urls();
    Ok(queue_urls
        .first()
        .expect("No queues in this account and Region. Create a queue to proceed.")
        .to_string())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ListQueues](https://docs.rs/aws-sdk-sqs/latest/aws_sdk_sqs/client/struct.Client.html#method.list_queues)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_rust_1_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sqs#code-examples)での設定と実行の方法を確認してください。

```
async fn receive(client: &Client, queue_url: &String) -> Result<(), Error> {
    let rcv_message_output = client.receive_message().queue_url(queue_url).send().await?;

    println!("Messages from queue with url: {}", queue_url);

    for message in rcv_message_output.messages.unwrap_or_default() {
        println!("Got the message: {:#?}", message);
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[ReceiveMessage](https://docs.rs/aws-sdk-sqs/latest/aws_sdk_sqs/client/struct.Client.html#method.receive_message)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_rust_1_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sqs#code-examples)での設定と実行の方法を確認してください。

```
async fn send(client: &Client, queue_url: &String, message: &SQSMessage) -> Result<(), Error> {
    println!("Sending message to queue with URL: {}", queue_url);

    let rsp = client
        .send_message()
        .queue_url(queue_url)
        .message_body(&message.body)
        // If the queue is FIFO, you need to set .message_deduplication_id
        // and message_group_id or configure the queue for ContentBasedDeduplication.
        .send()
        .await?;

    println!("Send message to the queue: {:#?}", rsp);

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[SendMessage](https://docs.rs/aws-sdk-sqs/latest/aws_sdk_sqs/client/struct.Client.html#method.send_message)」を参照してください。

## サーバーレスサンプル
<a name="serverless_examples"></a>

### Amazon SQS トリガーから Lambda 関数を呼び出す
<a name="serverless_SQS_Lambda_rust_1_topic"></a>

次のコード例では、SQS キューからメッセージを受信することによってトリガーされるイベントを受け取る、Lambda 関数の実装方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/integration-sqs-to-lambda)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用して Lambda で SQS イベントを消費します。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::event::sqs::SqsEvent;
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn function_handler(event: LambdaEvent<SqsEvent>) -> Result<(), Error> {
    event.payload.records.iter().for_each(|record| {
        // process the record
        tracing::info!("Message body: {}", record.body.as_deref().unwrap_or_default())
    });

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    tracing_subscriber::fmt()
        .with_max_level(tracing::Level::INFO)
        // disable printing the name of the module in every log line.
        .with_target(false)
        // disabling time is handy because CloudWatch will add the ingestion time.
        .without_time()
        .init();

    run(service_fn(function_handler)).await
}
```

### Amazon SQS トリガーを使用した Lambda 関数でのバッチアイテム失敗のレポート
<a name="serverless_SQS_Lambda_batch_item_failures_rust_1_topic"></a>

以下のコード例では、SQS キューからイベントを受け取る Lambda 関数のための、部分的なバッチレスポンスの実装方法を示しています。この関数は、レスポンスとしてバッチアイテムの失敗を報告し、対象のメッセージを後で再試行するよう Lambda に伝えます。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。[サーバーレスサンプル](https://github.com/aws-samples/serverless-snippets/tree/main/lambda-function-sqs-report-batch-item-failures)リポジトリで完全な例を見つけて、設定と実行の方法を確認してください。
Rust を使用した Lambda での SQS バッチアイテム失敗のレポート。  

```
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use aws_lambda_events::{
    event::sqs::{SqsBatchResponse, SqsEvent},
    sqs::{BatchItemFailure, SqsMessage},
};
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

async fn process_record(_: &SqsMessage) -> Result<(), Error> {
    Err(Error::from("Error processing message"))
}

async fn function_handler(event: LambdaEvent<SqsEvent>) -> Result<SqsBatchResponse, Error> {
    let mut batch_item_failures = Vec::new();
    for record in event.payload.records {
        match process_record(&record).await {
            Ok(_) => (),
            Err(_) => batch_item_failures.push(BatchItemFailure {
                item_identifier: record.message_id.unwrap(),
            }),
        }
    }

    Ok(SqsBatchResponse {
        batch_item_failures,
    })
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    run(service_fn(function_handler)).await
}
```

# AWS STS SDK for Rust を使用した の例
<a name="rust_1_sts_code_examples"></a>

次のコード例は、 で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_rust_1_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sts/#code-examples)での設定と実行の方法を確認してください。

```
async fn assume_role(config: &SdkConfig, role_name: String, session_name: Option<String>) {
    let provider = aws_config::sts::AssumeRoleProvider::builder(role_name)
        .session_name(session_name.unwrap_or("rust_sdk_example_session".into()))
        .configure(config)
        .build()
        .await;

    let local_config = aws_config::from_env()
        .credentials_provider(provider)
        .load()
        .await;
    let client = Client::new(&local_config);
    let req = client.get_caller_identity();
    let resp = req.send().await;
    match resp {
        Ok(e) => {
            println!("UserID :               {}", e.user_id().unwrap_or_default());
            println!("Account:               {}", e.account().unwrap_or_default());
            println!("Arn    :               {}", e.arn().unwrap_or_default());
        }
        Err(e) => println!("{:?}", e),
    }
}
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[AssumeRole](https://docs.rs/aws-sdk-sts/latest/aws_sdk_sts/client/struct.Client.html#method.assume_role)」を参照してください。

# SDK for Rust を使用した Systems Manager の例
<a name="rust_1_ssm_code_examples"></a>

次のコード例は、Systems Manager で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DescribeParameters`
<a name="ssm_DescribeParameters_rust_1_topic"></a>

次のコード例は、`DescribeParameters` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ssm#code-examples)での設定と実行の方法を確認してください。

```
async fn show_parameters(client: &Client) -> Result<(), Error> {
    let resp = client.describe_parameters().send().await?;

    for param in resp.parameters() {
        println!("  {}", param.name().unwrap_or_default());
    }

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[DescribeParameters](https://docs.rs/aws-sdk-ssm/latest/aws_sdk_ssm/client/struct.Client.html#method.describe_parameters)」を参照してください。

### `GetParameter`
<a name="ssm_GetParameter_rust_1_topic"></a>

次のコード例は、`GetParameter` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ssm#code-examples)での設定と実行の方法を確認してください。

```
    pub async fn list_path(&self, path: &str) -> Result<Vec<Parameter>, EC2Error> {
        let maybe_params: Vec<Result<Parameter, _>> = TryFlatMap::new(
            self.inner
                .get_parameters_by_path()
                .path(path)
                .into_paginator()
                .send(),
        )
        .flat_map(|item| item.parameters.unwrap_or_default())
        .collect()
        .await;
        // Fail on the first error
        let params = maybe_params
            .into_iter()
            .collect::<Result<Vec<Parameter>, _>>()?;
        Ok(params)
    }
```
+  API の詳細については、「*AWS SDK for Rust API リファレンス*」の「[GetParameter](https://docs.rs/aws-sdk-ssm/latest/aws_sdk_ssm/client/struct.Client.html#method.get_parameter)」を参照してください。

### `PutParameter`
<a name="ssm_PutParameter_rust_1_topic"></a>

次のコード例は、`PutParameter` を使用する方法を示しています。

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/ssm#code-examples)での設定と実行の方法を確認してください。

```
async fn make_parameter(
    client: &Client,
    name: &str,
    value: &str,
    description: &str,
) -> Result<(), Error> {
    let resp = client
        .put_parameter()
        .overwrite(true)
        .r#type(ParameterType::String)
        .name(name)
        .value(value)
        .description(description)
        .send()
        .await?;

    println!("Success! Parameter now has version: {}", resp.version());

    Ok(())
}
```
+  API の詳細については、*AWS SDK for Rust API リファレンス*の「[PutParameter](https://docs.rs/aws-sdk-ssm/latest/aws_sdk_ssm/client/struct.Client.html#method.put_parameter)」を参照してください。

# SDK for Rust を使用した Amazon Transcribe の例
<a name="rust_1_transcribe_code_examples"></a>

次のコード例は、Amazon Transcribe で AWS SDK for Rust を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [シナリオ](#scenarios)

## シナリオ
<a name="scenarios"></a>

### テキストを音声に変換し、テキストに戻す
<a name="cross_Telephone_rust_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon Polly を使用して、プレーンテキスト (UTF-8) 入力ファイルを音声ファイルに合成します。
+ Amazon S3 バケットに音声ファイルをアップロードします。
+ Amazon Transcribe を使用して、音声ファイルをテキストに変換します。
+ テキストを表示します。

**SDK for Rust**  
 Amazon Polly を使用して、プレーンテキスト (UTF-8) 入力ファイルを音声ファイルに合成し、音声ファイルを Amazon S3 バケットにアップロードし、Amazon Transcribe を使用して音声ファイルをテキストに変換し、テキストを表示します。  
 完全なソースコードとセットアップおよび実行の手順については、[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/rustv1/cross_service#code-examples) で完全な例を参照してください。  

**この例で使用されているサービス**
+ Amazon Polly
+ Amazon S3
+ Amazon Transcribe

# SDK for SAP ABAP のコード例
<a name="sap-abap_1_code_examples"></a>

次のコード例は、 で AWS SDK for SAP ABAP を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for SAP ABAP デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-sapabap/latest/developer-guide/home.html) ** – で SAP ABAP を使用する方法の詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23abap)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [ACM](sap-abap_1_acm_code_examples.md)
+ [API ゲートウェイ](sap-abap_1_api-gateway_code_examples.md)
+ [Application Recovery Controller](sap-abap_1_route53-recovery-cluster_code_examples.md)
+ [Aurora](sap-abap_1_aurora_code_examples.md)
+ [Auto Scaling](sap-abap_1_auto-scaling_code_examples.md)
+ [Amazon Bedrock ランタイム](sap-abap_1_bedrock-runtime_code_examples.md)
+ [Amazon Bedrock エージェントランタイム](sap-abap_1_bedrock-agent-runtime_code_examples.md)
+ [CloudFront](sap-abap_1_cloudfront_code_examples.md)
+ [CloudWatch](sap-abap_1_cloudwatch_code_examples.md)
+ [CloudWatch Logs](sap-abap_1_cloudwatch-logs_code_examples.md)
+ [Amazon Cognito ID プロバイダー](sap-abap_1_cognito-identity-provider_code_examples.md)
+ [Amazon Comprehend](sap-abap_1_comprehend_code_examples.md)
+ [AWS Config](sap-abap_1_config-service_code_examples.md)
+ [AWS Control Tower](sap-abap_1_controltower_code_examples.md)
+ [Firehose](sap-abap_1_firehose_code_examples.md)
+ [DynamoDB](sap-abap_1_dynamodb_code_examples.md)
+ [Amazon EC2](sap-abap_1_ec2_code_examples.md)
+ [Amazon ECR](sap-abap_1_ecr_code_examples.md)
+ [Amazon EMR](sap-abap_1_emr_code_examples.md)
+ [EventBridge スケジューラ](sap-abap_1_scheduler_code_examples.md)
+ [AWS Glue](sap-abap_1_glue_code_examples.md)
+ [HealthImaging](sap-abap_1_medical-imaging_code_examples.md)
+ [HealthLake](sap-abap_1_healthlake_code_examples.md)
+ [IAM](sap-abap_1_iam_code_examples.md)
+ [AWS IoT SiteWise](sap-abap_1_iotsitewise_code_examples.md)
+ [Amazon Keyspaces](sap-abap_1_keyspaces_code_examples.md)
+ [Kinesis](sap-abap_1_kinesis_code_examples.md)
+ [AWS KMS](sap-abap_1_kms_code_examples.md)
+ [Lambda](sap-abap_1_lambda_code_examples.md)
+ [組織](sap-abap_1_organizations_code_examples.md)
+ [Amazon Pinpoint](sap-abap_1_pinpoint_code_examples.md)
+ [Amazon Pinpoint SMS および音声 API](sap-abap_1_pinpoint-sms-voice_code_examples.md)
+ [Amazon Polly](sap-abap_1_polly_code_examples.md)
+ [Amazon RDS](sap-abap_1_rds_code_examples.md)
+ [Amazon Redshift](sap-abap_1_redshift_code_examples.md)
+ [Amazon Rekognition](sap-abap_1_rekognition_code_examples.md)
+ [Amazon S3](sap-abap_1_s3_code_examples.md)
+ [SageMaker AI](sap-abap_1_sagemaker_code_examples.md)
+ [Secrets Manager](sap-abap_1_secrets-manager_code_examples.md)
+ [Amazon SES](sap-abap_1_ses_code_examples.md)
+ [Amazon SES API v2](sap-abap_1_sesv2_code_examples.md)
+ [Amazon SNS](sap-abap_1_sns_code_examples.md)
+ [Amazon SQS](sap-abap_1_sqs_code_examples.md)
+ [ステップ関数](sap-abap_1_sfn_code_examples.md)
+ [Systems Manager](sap-abap_1_ssm_code_examples.md)
+ [Amazon Textract](sap-abap_1_textract_code_examples.md)
+ [Amazon Transcribe](sap-abap_1_transcribe_code_examples.md)
+ [Amazon Translate](sap-abap_1_translate_code_examples.md)

# SDK for SAP ABAP を使用した ACM の例
<a name="sap-abap_1_acm_code_examples"></a>

次のコード例は、ACM で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AddTagsToCertificate`
<a name="acm_AddTagsToCertificate_sap-abap_1_topic"></a>

次の例は、`AddTagsToCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_certificate_arn = 'arn:aws:acm:region:123456789012:certificate/certificate-id'
        lo_acm->addtagstocertificate(
          iv_certificatearn = iv_certificate_arn
          it_tags = it_tags
        ).
        MESSAGE 'Tags added to certificate successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidarnex.
        MESSAGE 'The certificate ARN is not valid.' TYPE 'I'.
      CATCH /aws1/cx_acmresourcenotfoundex.
        MESSAGE 'Certificate not found.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidtagex.
        MESSAGE 'Invalid tag provided.' TYPE 'I'.
      CATCH /aws1/cx_acmtoomanytagsex.
        MESSAGE 'Too many tags for certificate.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[AddTagsToCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteCertificate`
<a name="acm_DeleteCertificate_sap-abap_1_topic"></a>

次の例は、`DeleteCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_certificate_arn = 'arn:aws:acm:region:123456789012:certificate/certificate-id'
        lo_acm->deletecertificate( iv_certificatearn = iv_certificate_arn ).
        MESSAGE 'Certificate deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidarnex.
        MESSAGE 'The certificate ARN is not valid.' TYPE 'I'.
      CATCH /aws1/cx_acmresourcenotfoundex.
        MESSAGE 'Certificate not found.' TYPE 'I'.
      CATCH /aws1/cx_acmresourceinuseex.
        MESSAGE 'Certificate is in use and cannot be deleted.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeCertificate`
<a name="acm_DescribeCertificate_sap-abap_1_topic"></a>

次の例は、`DescribeCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_certificate_arn = 'arn:aws:acm:region:123456789012:certificate/certificate-id'
        oo_result = lo_acm->describecertificate( iv_certificatearn = iv_certificate_arn ).
        MESSAGE 'Certificate details retrieved.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidarnex.
        MESSAGE 'The certificate ARN is not valid.' TYPE 'I'.
      CATCH /aws1/cx_acmresourcenotfoundex.
        MESSAGE 'Certificate not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetCertificate`
<a name="acm_GetCertificate_sap-abap_1_topic"></a>

次の例は、`GetCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_certificate_arn = 'arn:aws:acm:region:123456789012:certificate/certificate-id'
        oo_result = lo_acm->getcertificate( iv_certificatearn = iv_certificate_arn ).
        MESSAGE 'Certificate body and chain retrieved.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidarnex.
        MESSAGE 'The certificate ARN is not valid.' TYPE 'I'.
      CATCH /aws1/cx_acmresourcenotfoundex.
        MESSAGE 'Certificate not found.' TYPE 'I'.
      CATCH /aws1/cx_acmrequestinprgssex.
        MESSAGE 'Certificate request is in progress.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ImportCertificate`
<a name="acm_ImportCertificate_sap-abap_1_topic"></a>

次の例は、`ImportCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Only pass certificate chain if it's provided (it's optional)
        IF iv_certificate_chain IS NOT INITIAL.
          DATA(lo_result) = lo_acm->importcertificate(
            iv_certificate = iv_certificate
            iv_privatekey = iv_private_key
            iv_certificatechain = iv_certificate_chain
          ).
        ELSE.
          lo_result = lo_acm->importcertificate(
            iv_certificate = iv_certificate
            iv_privatekey = iv_private_key
          ).
        ENDIF.
        ov_certificate_arn = lo_result->get_certificatearn( ).
        MESSAGE 'Certificate imported successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidparameterex.
        MESSAGE 'Invalid parameter provided.' TYPE 'I'.
      CATCH /aws1/cx_acmlimitexceededex.
        MESSAGE 'Certificate limit exceeded.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ImportCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListCertificates`
<a name="acm_ListCertificates_sap-abap_1_topic"></a>

次の例は、`ListCertificates` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_acm->listcertificates(
          iv_maxitems = iv_max_items
          it_certificatestatuses = it_statuses
          io_includes = io_includes
        ).
        MESSAGE 'Certificates listed successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidargsex.
        MESSAGE 'Invalid arguments provided.' TYPE 'I'.
      CATCH /aws1/cx_acmvalidationex.
        MESSAGE 'Validation error occurred.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListCertificates](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTagsForCertificate`
<a name="acm_ListTagsForCertificate_sap-abap_1_topic"></a>

次の例は、`ListTagsForCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_certificate_arn = 'arn:aws:acm:region:123456789012:certificate/certificate-id'
        DATA(lo_result) = lo_acm->listtagsforcertificate(
          iv_certificatearn = iv_certificate_arn
        ).
        ot_tags = lo_result->get_tags( ).
        MESSAGE 'Certificate tags retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidarnex.
        MESSAGE 'The certificate ARN is not valid.' TYPE 'I'.
      CATCH /aws1/cx_acmresourcenotfoundex.
        MESSAGE 'Certificate not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListTagsForCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RemoveTagsFromCertificate`
<a name="acm_RemoveTagsFromCertificate_sap-abap_1_topic"></a>

次の例は、`RemoveTagsFromCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_certificate_arn = 'arn:aws:acm:region:123456789012:certificate/certificate-id'
        lo_acm->removetagsfromcertificate(
          iv_certificatearn = iv_certificate_arn
          it_tags = it_tags
        ).
        MESSAGE 'Tags removed from certificate successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidarnex.
        MESSAGE 'The certificate ARN is not valid.' TYPE 'I'.
      CATCH /aws1/cx_acmresourcenotfoundex.
        MESSAGE 'Certificate not found.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidtagex.
        MESSAGE 'Invalid tag provided.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[RemoveTagsFromCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RequestCertificate`
<a name="acm_RequestCertificate_sap-abap_1_topic"></a>

次の例は、`RequestCertificate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_domain_name = 'example.com'
        " iv_validation_method = 'DNS' or 'EMAIL'
        DATA(lo_result) = lo_acm->requestcertificate(
          iv_domainname = iv_domain_name
          it_subjectalternativenames = COND #( WHEN it_alternate_domains IS NOT INITIAL 
                                                THEN it_alternate_domains )
          iv_validationmethod = iv_validation_method
        ).
        ov_certificate_arn = lo_result->get_certificatearn( ).
        MESSAGE 'Certificate requested successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidparameterex.
        MESSAGE 'Invalid parameter provided.' TYPE 'I'.
      CATCH /aws1/cx_acmlimitexceededex.
        MESSAGE 'Certificate limit exceeded.' TYPE 'I'.
      CATCH /aws1/cx_acminvdomvationoptsex.
        MESSAGE 'Invalid domain validation options.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[RequestCertificate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ResendValidationEmail`
<a name="acm_ResendValidationEmail_sap-abap_1_topic"></a>

次の例は、`ResendValidationEmail` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/acm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_certificate_arn = 'arn:aws:acm:region:123456789012:certificate/certificate-id'
        " iv_domain = 'example.com'
        " iv_validation_domain = 'example.com'
        lo_acm->resendvalidationemail(
          iv_certificatearn = iv_certificate_arn
          iv_domain = iv_domain
          iv_validationdomain = iv_validation_domain
        ).
        MESSAGE 'Validation email resent successfully.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidarnex.
        MESSAGE 'The certificate ARN is not valid.' TYPE 'I'.
      CATCH /aws1/cx_acmresourcenotfoundex.
        MESSAGE 'Certificate not found.' TYPE 'I'.
      CATCH /aws1/cx_acminvalidstateex.
        MESSAGE 'Certificate is not in a valid state.' TYPE 'I'.
      CATCH /aws1/cx_acminvdomvationoptsex.
        MESSAGE 'Invalid domain validation options.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ResendValidationEmail](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した API Gateway の例
<a name="sap-abap_1_api-gateway_code_examples"></a>

次のコード例は、API Gateway で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDeployment`
<a name="api-gateway_CreateDeployment_sap-abap_1_topic"></a>

次の例は、`CreateDeployment` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->createdeployment(
          iv_restapiid = iv_rest_api_id
          iv_stagename = iv_stage_name
          iv_description = 'Deployment created by ABAP SDK' ).
        DATA(lv_deployment_id) = oo_result->get_id( ).
        MESSAGE 'Deployment created with ID: ' && lv_deployment_id TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateDeployment](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateResource`
<a name="api-gateway_CreateResource_sap-abap_1_topic"></a>

次の例は、`CreateResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->createresource(
          iv_restapiid = iv_rest_api_id
          iv_parentid = iv_parent_id
          iv_pathpart = iv_resource_path ).
        DATA(lv_resource_id) = oo_result->get_id( ).
        MESSAGE 'Resource created with ID: ' && lv_resource_id TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateRestApi`
<a name="api-gateway_CreateRestApi_sap-abap_1_topic"></a>

次の例は、`CreateRestApi` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->createrestapi(
          iv_name = iv_api_name
          iv_description = 'Sample REST API created by ABAP SDK' ).
        DATA(lv_api_id) = oo_result->get_id( ).
        MESSAGE 'REST API created with ID: ' && lv_api_id TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
      CATCH /aws1/cx_agwunauthorizedex INTO DATA(lo_unauthorized).
        MESSAGE lo_unauthorized->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_unauthorized.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateRestApi](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteRestApi`
<a name="api-gateway_DeleteRestApi_sap-abap_1_topic"></a>

次の例は、`DeleteRestApi` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_agw->deleterestapi(
          iv_restapiid = iv_rest_api_id ).
        MESSAGE 'REST API deleted successfully' TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteRestApi](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetResources`
<a name="api-gateway_GetResources_sap-abap_1_topic"></a>

次の例は、`GetResources` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->getresources(
          iv_restapiid = iv_rest_api_id ).
        DATA(lt_resources) = oo_result->get_items( ).
        DATA(lv_count) = lines( lt_resources ).
        MESSAGE 'Found ' && lv_count && ' resources' TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetResources](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetRestApis`
<a name="api-gateway_GetRestApis_sap-abap_1_topic"></a>

次の例は、`GetRestApis` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->getrestapis( ).
        DATA(lt_apis) = oo_result->get_items( ).
        DATA(lv_count) = lines( lt_apis ).
        MESSAGE 'Found ' && lv_count && ' REST APIs' TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetRestApis](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutIntegration`
<a name="api-gateway_PutIntegration_sap-abap_1_topic"></a>

次の例は、`PutIntegration` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->putintegration(
          iv_restapiid = iv_rest_api_id
          iv_resourceid = iv_resource_id
          iv_httpmethod = iv_http_method
          iv_type = 'AWS_PROXY'
          iv_integrationhttpmethod = 'POST'
          iv_uri = iv_integration_uri ).
        MESSAGE 'Integration configured for method' TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutIntegration](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutIntegrationResponse`
<a name="api-gateway_PutIntegrationResponse_sap-abap_1_topic"></a>

次の例は、`PutIntegrationResponse` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->putintegrationresponse(
          iv_restapiid = iv_rest_api_id
          iv_resourceid = iv_resource_id
          iv_httpmethod = iv_http_method
          iv_statuscode = '200' ).
        MESSAGE 'Integration response configured for status 200' TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutIntegrationResponse](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutMethod`
<a name="api-gateway_PutMethod_sap-abap_1_topic"></a>

次の例は、`PutMethod` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->putmethod(
          iv_restapiid = iv_rest_api_id
          iv_resourceid = iv_resource_id
          iv_httpmethod = iv_http_method
          iv_authorizationtype = 'NONE' ).
        MESSAGE 'Method ' && iv_http_method && ' added to resource' TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutMethod](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutMethodResponse`
<a name="api-gateway_PutMethodResponse_sap-abap_1_topic"></a>

次の例は、`PutMethodResponse` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/agw#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_agw->putmethodresponse(
          iv_restapiid = iv_rest_api_id
          iv_resourceid = iv_resource_id
          iv_httpmethod = iv_http_method
          iv_statuscode = '200' ).
        MESSAGE 'Method response configured for status 200' TYPE 'I'.
      CATCH /aws1/cx_agwbadrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_agwnotfoundexception INTO DATA(lo_not_found).
        MESSAGE lo_not_found->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
      CATCH /aws1/cx_agwtoomanyrequestsex INTO DATA(lo_too_many).
        MESSAGE lo_too_many->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutMethodResponse](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Application Recovery Controller の例
<a name="sap-abap_1_route53-recovery-cluster_code_examples"></a>

次のコード例は、Application Recovery Controller で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetRoutingControlState`
<a name="route53-recovery-cluster_GetRoutingControlState_sap-abap_1_topic"></a>

次の例は、`GetRoutingControlState` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/r5v#code-examples)での設定と実行の方法を確認してください。

```
    CONSTANTS cv_pfl TYPE /aws1/rt_profile_id VALUE 'ZCODE_DEMO'.
    DATA lo_exception TYPE REF TO /aws1/cx_rt_generic.
    DATA lo_session TYPE REF TO /aws1/cl_rt_session_base.
    DATA lo_client TYPE REF TO /aws1/if_r5v.
    DATA lt_endpoints TYPE TABLE OF string.
    DATA lv_endpoint TYPE string.
    DATA lv_region TYPE /aws1/rt_region_id.

    " Parse the comma-separated cluster endpoints
    " Expected format: "https://endpoint1.com|us-west-2,https://endpoint2.com|us-east-1"
    SPLIT iv_cluster_endpoints AT ',' INTO TABLE lt_endpoints.

    " As a best practice, shuffle cluster endpoints to distribute load
    " For more information, see https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-practices.html#route53-arc-best-practices.regional
    " For simplicity, we'll try them in order (shuffling can be added if needed)

    " Try each endpoint in order
    LOOP AT lt_endpoints INTO lv_endpoint.
      TRY.
          " Parse endpoint and region from the format "url|region"
          DATA(lv_pos) = find( val = lv_endpoint sub = '|' ).
          IF lv_pos > 0.
            DATA(lv_url) = substring( val = lv_endpoint len = lv_pos ).
            lv_region = substring( val = lv_endpoint off = lv_pos + 1 ).
          ELSE.
            " If no region specified, use default
            lv_url = lv_endpoint.
            lv_region = 'us-east-1'.
          ENDIF.

          " Create session for this region
          lo_session = /aws1/cl_rt_session_aws=>create( cv_pfl ).

          " Create client with the specific endpoint
          lo_client = create_recovery_client(
            iv_endpoint = lv_url
            iv_region   = lv_region
            io_session  = lo_session ).

          " Try to get the routing control state
          oo_result = lo_client->getroutingcontrolstate(
            iv_routingcontrolarn = iv_routing_control_arn ).

          " If successful, return the result
          RETURN.

        CATCH /aws1/cx_r5vendpttmpyunavailex INTO DATA(lo_endpoint_ex).
          " This endpoint is temporarily unavailable, try the next one
          lo_exception = lo_endpoint_ex.
          CONTINUE.

        CATCH /aws1/cx_r5vaccessdeniedex
              /aws1/cx_r5vinternalserverex
              /aws1/cx_r5vresourcenotfoundex
              /aws1/cx_r5vthrottlingex
              /aws1/cx_r5vvalidationex
              /aws1/cx_rt_generic INTO lo_exception.
          " For other errors, re-raise immediately
          RAISE EXCEPTION lo_exception.
      ENDTRY.
    ENDLOOP.

    " If we get here, all endpoints failed - re-raise the last exception
    IF lo_exception IS BOUND.
      RAISE EXCEPTION lo_exception.
    ENDIF.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetRoutingControlState](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateRoutingControlState`
<a name="route53-recovery-cluster_UpdateRoutingControlState_sap-abap_1_topic"></a>

次の例は、`UpdateRoutingControlState` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/r5v#code-examples)での設定と実行の方法を確認してください。

```
    CONSTANTS cv_pfl TYPE /aws1/rt_profile_id VALUE 'ZCODE_DEMO'.
    DATA lo_exception TYPE REF TO /aws1/cx_rt_generic.
    DATA lo_session TYPE REF TO /aws1/cl_rt_session_base.
    DATA lo_client TYPE REF TO /aws1/if_r5v.
    DATA lt_endpoints TYPE TABLE OF string.
    DATA lv_endpoint TYPE string.
    DATA lv_region TYPE /aws1/rt_region_id.

    " Parse the comma-separated cluster endpoints
    " Expected format: "https://endpoint1.com|us-west-2,https://endpoint2.com|us-east-1"
    SPLIT iv_cluster_endpoints AT ',' INTO TABLE lt_endpoints.

    " As a best practice, shuffle cluster endpoints to distribute load
    " For more information, see https://docs.aws.amazon.com/r53recovery/latest/dg/route53-arc-best-practices.html#route53-arc-best-practices.regional
    " For simplicity, we'll try them in order (shuffling can be added if needed)

    " Try each endpoint in order
    LOOP AT lt_endpoints INTO lv_endpoint.
      TRY.
          " Parse endpoint and region from the format "url|region"
          DATA(lv_pos) = find( val = lv_endpoint sub = '|' ).
          IF lv_pos > 0.
            DATA(lv_url) = substring( val = lv_endpoint len = lv_pos ).
            lv_region = substring( val = lv_endpoint off = lv_pos + 1 ).
          ELSE.
            " If no region specified, use default
            lv_url = lv_endpoint.
            lv_region = 'us-east-1'.
          ENDIF.

          " Create session for this region
          lo_session = /aws1/cl_rt_session_aws=>create( cv_pfl ).

          " Create client with the specific endpoint
          lo_client = create_recovery_client(
            iv_endpoint = lv_url
            iv_region   = lv_region
            io_session  = lo_session ).

          " Try to update the routing control state
          oo_result = lo_client->updateroutingcontrolstate(
            iv_routingcontrolarn     = iv_routing_control_arn
            iv_routingcontrolstate   = iv_routing_control_state
            it_safetyrulestooverride = it_safety_rules_override ).

          " If successful, return the result
          RETURN.

        CATCH /aws1/cx_r5vendpttmpyunavailex INTO DATA(lo_endpoint_ex).
          " This endpoint is temporarily unavailable, try the next one
          lo_exception = lo_endpoint_ex.
          CONTINUE.

        CATCH /aws1/cx_r5vaccessdeniedex
              /aws1/cx_r5vconflictexception
              /aws1/cx_r5vinternalserverex
              /aws1/cx_r5vresourcenotfoundex
              /aws1/cx_r5vthrottlingex
              /aws1/cx_r5vvalidationex
              /aws1/cx_rt_generic INTO lo_exception.
          " For other errors, re-raise immediately
          RAISE EXCEPTION lo_exception.
      ENDTRY.
    ENDLOOP.

    " If we get here, all endpoints failed - re-raise the last exception
    IF lo_exception IS BOUND.
      RAISE EXCEPTION lo_exception.
    ENDIF.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateRoutingControlState](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Aurora の例
<a name="sap-abap_1_aurora_code_examples"></a>

次のコード例は、Aurora で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDBClusterParameterGroup`
<a name="aurora_CreateDBClusterParameterGroup_sap-abap_1_topic"></a>

次の例は、`CreateDBClusterParameterGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_output) = lo_rds->createdbclusterparamgroup(
          iv_dbclusterparamgroupname = iv_param_group_name
          iv_dbparametergroupfamily = iv_param_group_family
          iv_description = iv_description
        ).
        oo_result = lo_output->get_dbclusterparametergroup( ).
      CATCH /aws1/cx_rdsdbparmgralrexfault.
        " Re-raise exception - parameter group already exists
        RAISE EXCEPTION TYPE /aws1/cx_rdsdbparmgralrexfault.
      CATCH /aws1/cx_rdsdbprmgrquotaexcd00.
        " Re-raise exception - quota exceeded
        RAISE EXCEPTION TYPE /aws1/cx_rdsdbprmgrquotaexcd00.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateDBClusterParameterGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteDBClusterParameterGroup`
<a name="aurora_DeleteDBClusterParameterGroup_sap-abap_1_topic"></a>

次の例は、`DeleteDBClusterParameterGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_rds->deletedbclusterparamgroup(
          iv_dbclusterparamgroupname = iv_param_group_name
        ).
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
        " Re-raise exception - parameter group not found
        RAISE EXCEPTION TYPE /aws1/cx_rdsdbprmgrnotfndfault.
      CATCH /aws1/cx_rdsinvdbprmgrstatef00.
        " Re-raise exception - invalid state
        RAISE EXCEPTION TYPE /aws1/cx_rdsinvdbprmgrstatef00.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteDBClusterParameterGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDBClusterParameterGroups`
<a name="aurora_DescribeDBClusterParameterGroups_sap-abap_1_topic"></a>

次の例は、`DescribeDBClusterParameterGroups` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_output) = lo_rds->describedbclusterparamgroups(
          iv_dbclusterparamgroupname = iv_param_group_name
        ).
        DATA(lt_param_groups) = lo_output->get_dbclusterparametergroups( ).
        IF lines( lt_param_groups ) > 0.
          oo_result = lt_param_groups[ 1 ].
        ENDIF.
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeDBClusterParameterGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDBClusterParameters`
<a name="aurora_DescribeDBClusterParameters_sap-abap_1_topic"></a>

次の例は、`DescribeDBClusterParameters` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA lv_marker TYPE /aws1/rdsstring VALUE ''.
        DATA lt_all_parameters TYPE /aws1/cl_rdsparameter=>tt_parameterslist.

        DO.
          DATA(lo_output) = lo_rds->describedbclusterparameters(
            iv_dbclusterparamgroupname = iv_param_group_name
            iv_source = iv_source
            iv_marker = lv_marker
          ).

          LOOP AT lo_output->get_parameters( ) INTO DATA(lo_param).
            IF iv_name_prefix IS INITIAL OR
               lo_param->get_parametername( ) CP |{ iv_name_prefix }*|.
              APPEND lo_param TO lt_all_parameters.
            ENDIF.
          ENDLOOP.

          lv_marker = lo_output->get_marker( ).
          IF lv_marker IS INITIAL.
            EXIT.
          ENDIF.
        ENDDO.

        ot_parameters = lt_all_parameters.
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
        " Re-raise exception - parameter group not found
        RAISE EXCEPTION TYPE /aws1/cx_rdsdbprmgrnotfndfault.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeDBClusterParameters](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDBEngineVersions`
<a name="aurora_DescribeDBEngineVersions_sap-abap_1_topic"></a>

次の例は、`DescribeDBEngineVersions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_engine                 = 'mysql'
    " iv_dbparametergroupfamily = 'mysql8.0' (optional - filters by parameter group family)
    TRY.
        oo_result = lo_rds->describedbengineversions(
          iv_engine                 = iv_engine
          iv_dbparametergroupfamily = iv_dbparametergroupfamily ).
        DATA(lv_version_count) = lines( oo_result->get_dbengineversions( ) ).
        MESSAGE |Retrieved { lv_version_count } engine versions.| TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="aurora_DescribeOrderableDBInstanceOptions_sap-abap_1_topic"></a>

次の例は、`DescribeOrderableDBInstanceOptions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_engine        = 'mysql'
    " iv_engineversion = '8.0.35'
    TRY.
        oo_result = lo_rds->descrorderabledbinstoptions(
          iv_engine        = iv_engine
          iv_engineversion = iv_engineversion ).
        DATA(lv_option_count) = lines( oo_result->get_orderabledbinstoptions( ) ).
        MESSAGE |Retrieved { lv_option_count } orderable DB instance options.| TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ModifyDBClusterParameterGroup`
<a name="aurora_ModifyDBClusterParameterGroup_sap-abap_1_topic"></a>

次の例は、`ModifyDBClusterParameterGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_rds->modifydbclusterparamgroup(
          iv_dbclusterparamgroupname = iv_param_group_name
          it_parameters = it_update_parameters
        ).
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
        " Re-raise exception - parameter group not found
        RAISE EXCEPTION TYPE /aws1/cx_rdsdbprmgrnotfndfault.
      CATCH /aws1/cx_rdsinvdbprmgrstatef00.
        " Re-raise exception - invalid state
        RAISE EXCEPTION TYPE /aws1/cx_rdsinvdbprmgrstatef00.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ModifyDBClusterParameterGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Auto Scaling の例
<a name="sap-abap_1_auto-scaling_code_examples"></a>

次のコード例は、Auto Scaling で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateAutoScalingGroup`
<a name="auto-scaling_CreateAutoScalingGroup_sap-abap_1_topic"></a>

次の例は、`CreateAutoScalingGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    DATA lo_launch_template TYPE REF TO /aws1/cl_asclaunchtemplatespec.
    
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: iv_launch_template_name = 'my-launch-template'
    " Example: iv_min_size = 1
    " Example: iv_max_size = 3
    " Example: iv_vpc_zone_identifier = 'subnet-12345,subnet-67890' (for VPC)
    
    TRY.
        " Create launch template specification
        lo_launch_template = NEW /aws1/cl_asclaunchtemplatespec(
          iv_launchtemplatename = iv_launch_template_name
          iv_version = '$Default' ).

        " Create the Auto Scaling group
        " Use VPCZoneIdentifier for VPC subnets, or AvailabilityZones for EC2-Classic
        IF iv_vpc_zone_identifier IS NOT INITIAL.
          " VPC-based deployment - use subnet IDs
          ao_asc->createautoscalinggroup(
            iv_autoscalinggroupname = iv_group_name
            iv_vpczoneidentifier = iv_vpc_zone_identifier
            io_launchtemplate = lo_launch_template
            iv_minsize = iv_min_size
            iv_maxsize = iv_max_size ).
        ELSE.
          " EC2-Classic or default VPC - use availability zones
          ao_asc->createautoscalinggroup(
            iv_autoscalinggroupname = iv_group_name
            it_availabilityzones = it_group_zones
            io_launchtemplate = lo_launch_template
            iv_minsize = iv_min_size
            iv_maxsize = iv_max_size ).
        ENDIF.

        " Wait for the group to be created (simplified - in production use proper polling)
        WAIT UP TO 10 SECONDS.

        MESSAGE 'Auto Scaling group created successfully' TYPE 'I'.

      CATCH /aws1/cx_ascalreadyexistsfault INTO DATA(lo_already_exists).
        RAISE EXCEPTION lo_already_exists.
      CATCH /aws1/cx_asclimitexceededfault INTO DATA(lo_limit_exceeded).
        RAISE EXCEPTION lo_limit_exceeded.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteAutoScalingGroup`
<a name="auto-scaling_DeleteAutoScalingGroup_sap-abap_1_topic"></a>

次の例は、`DeleteAutoScalingGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        ao_asc->deleteautoscalinggroup(
          iv_autoscalinggroupname = iv_group_name ).

        " Wait for the group to be deleted (simplified - in production use proper polling)
        WAIT UP TO 10 SECONDS.

        MESSAGE 'Auto Scaling group deleted successfully' TYPE 'I'.

      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_ascresourceinusefault INTO DATA(lo_resource_in_use).
        RAISE EXCEPTION lo_resource_in_use.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeAutoScalingGroups`
<a name="auto-scaling_DescribeAutoScalingGroups_sap-abap_1_topic"></a>

次の例は、`DescribeAutoScalingGroups` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_group_names TYPE /aws1/cl_ascautoscgroupnames_w=>tt_autoscalinggroupnames.
    DATA lo_group_name TYPE REF TO /aws1/cl_ascautoscgroupnames_w.
    
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        " Build group names parameter
        CREATE OBJECT lo_group_name
          EXPORTING
            iv_value = iv_group_name.
        APPEND lo_group_name TO lt_group_names.

        " Describe the Auto Scaling group
        DATA(lo_output) = ao_asc->describeautoscalinggroups(
          it_autoscalinggroupnames = lt_group_names ).

        " Return the first (and only) group in the result
        DATA(lt_groups) = lo_output->get_autoscalinggroups( ).
        IF lines( lt_groups ) > 0.
          READ TABLE lt_groups INDEX 1 INTO DATA(lo_group).
          oo_output = lo_group.
        ENDIF.

        MESSAGE 'Auto Scaling group information retrieved successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeAutoScalingGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeAutoScalingInstances`
<a name="auto-scaling_DescribeAutoScalingInstances_sap-abap_1_topic"></a>

次の例は、`DescribeAutoScalingInstances` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: it_instance_ids contains a list of instance IDs
    
    TRY.
        DATA(lo_output) = ao_asc->describeautoscalinginstances(
          it_instanceids = it_instance_ids ).

        ot_output = lo_output->get_autoscalinginstances( ).

        MESSAGE 'Auto Scaling instances information retrieved successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeAutoScalingInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeScalingActivities`
<a name="auto-scaling_DescribeScalingActivities_sap-abap_1_topic"></a>

次の例は、`DescribeScalingActivities` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        DATA(lo_output) = ao_asc->describescalingactivities(
          iv_autoscalinggroupname = iv_group_name ).

        ot_output = lo_output->get_activities( ).

        MESSAGE 'Scaling activities retrieved successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeScalingActivities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DisableMetricsCollection`
<a name="auto-scaling_DisableMetricsCollection_sap-abap_1_topic"></a>

次の例は、`DisableMetricsCollection` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    
    TRY.
        ao_asc->disablemetricscollection(
          iv_autoscalinggroupname = iv_group_name ).

        MESSAGE 'Metrics collection disabled successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DisableMetricsCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `EnableMetricsCollection`
<a name="auto-scaling_EnableMetricsCollection_sap-abap_1_topic"></a>

次の例は、`EnableMetricsCollection` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: it_metrics contains list of metrics like 'GroupMinSize', 'GroupMaxSize', etc.
    
    TRY.
        ao_asc->enablemetricscollection(
          iv_autoscalinggroupname = iv_group_name
          it_metrics = it_metrics
          iv_granularity = '1Minute' ).

        MESSAGE 'Metrics collection enabled successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[EnableMetricsCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SetDesiredCapacity`
<a name="auto-scaling_SetDesiredCapacity_sap-abap_1_topic"></a>

次の例は、`SetDesiredCapacity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: iv_capacity = 2
    
    TRY.
        ao_asc->setdesiredcapacity(
          iv_autoscalinggroupname = iv_group_name
          iv_desiredcapacity = iv_capacity
          iv_honorcooldown = abap_false ).

        MESSAGE 'Desired capacity set successfully' TYPE 'I'.

      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[SetDesiredCapacity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `TerminateInstanceInAutoScalingGroup`
<a name="auto-scaling_TerminateInstanceInAutoScalingGroup_sap-abap_1_topic"></a>

次の例は、`TerminateInstanceInAutoScalingGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: iv_instance_id = 'i-1234567890abcdef0'
    " Example: iv_decrease_capacity = abap_true
    
    TRY.
        DATA(lo_output) = ao_asc->terminateinstinautoscgroup(
          iv_instanceid = iv_instance_id
          iv_shoulddecrementdesiredcap = iv_decrease_capacity ).

        oo_output = lo_output->get_activity( ).

        MESSAGE 'Instance terminated successfully' TYPE 'I'.

      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[TerminateInstanceInAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateAutoScalingGroup`
<a name="auto-scaling_UpdateAutoScalingGroup_sap-abap_1_topic"></a>

次の例は、`UpdateAutoScalingGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/asc#code-examples)での設定と実行の方法を確認してください。

```
    " Example: iv_group_name = 'my-auto-scaling-group'
    " Example: iv_max_size = 5
    
    TRY.
        ao_asc->updateautoscalinggroup(
          iv_autoscalinggroupname = iv_group_name
          iv_maxsize = iv_max_size
          iv_minsize = iv_min_size ).

        MESSAGE 'Auto Scaling group updated successfully' TYPE 'I'.

      CATCH /aws1/cx_ascresrccontionfault INTO DATA(lo_contention).
        RAISE EXCEPTION lo_contention.
      CATCH /aws1/cx_ascscaactivityinprg00 INTO DATA(lo_activity_in_progress).
        RAISE EXCEPTION lo_activity_in_progress.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_exception).
        RAISE EXCEPTION lo_generic_exception.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateAutoScalingGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Bedrock ランタイムの例
<a name="sap-abap_1_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイムで AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [Anthropic Claude](#anthropic_claude)
+ [Stable Diffusion](#stable_diffusion)

## Anthropic Claude
<a name="anthropic_claude"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AnthropicClaude_sap-abap_1_topic"></a>

次のコード例は、Invoke Model API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/bdr#code-examples)での設定と実行の方法を確認してください。
Anthropic Claude 2 基盤モデルを呼び出して、テキストを生成します。この例では、一部の NetWeaver バージョンでは使用できない場合がある /US2/CL\$1JSON の機能を使用しています。  

```
    "Claude V2 Input Parameters should be in a format like this:
*   {
*     "prompt":"\n\nHuman:\\nTell me a joke\n\nAssistant:\n",
*     "max_tokens_to_sample":2048,
*     "temperature":0.5,
*     "top_k":250,
*     "top_p":1.0,
*     "stop_sequences":[]
*   }

    DATA: BEGIN OF ls_input,
            prompt               TYPE string,
            max_tokens_to_sample TYPE /aws1/rt_shape_integer,
            temperature          TYPE /aws1/rt_shape_float,
            top_k                TYPE /aws1/rt_shape_integer,
            top_p                TYPE /aws1/rt_shape_float,
            stop_sequences       TYPE /aws1/rt_stringtab,
          END OF ls_input.

    "Leave ls_input-stop_sequences empty.
    ls_input-prompt = |\n\nHuman:\\n{ iv_prompt }\n\nAssistant:\n|.
    ls_input-max_tokens_to_sample = 2048.
    ls_input-temperature = '0.5'.
    ls_input-top_k = 250.
    ls_input-top_p = 1.

    "Serialize into JSON with /ui2/cl_json -- this assumes SAP_UI is installed.
    DATA(lv_json) = /ui2/cl_json=>serialize(
      data = ls_input
                pretty_name   = /ui2/cl_json=>pretty_mode-low_case ).

    TRY.
        DATA(lo_response) = lo_bdr->invokemodel(
          iv_body = /aws1/cl_rt_util=>string_to_xstring( lv_json )
          iv_modelid = 'anthropic.claude-v2'
          iv_accept = 'application/json'
          iv_contenttype = 'application/json' ).

        "Claude V2 Response format will be:
*       {
*         "completion": "Knock Knock...",
*         "stop_reason": "stop_sequence"
*       }
        DATA: BEGIN OF ls_response,
                completion  TYPE string,
                stop_reason TYPE string,
              END OF ls_response.

        /ui2/cl_json=>deserialize(
          EXPORTING jsonx = lo_response->get_body( )
                    pretty_name = /ui2/cl_json=>pretty_mode-camel_case
          CHANGING  data  = ls_response ).

        DATA(lv_answer) = ls_response-completion.
      CATCH /aws1/cx_bdraccessdeniedex INTO DATA(lo_ex).
        WRITE / lo_ex->get_text( ).
        WRITE / |Don't forget to enable model access at https://console.aws.amazon.com/bedrock/home?#/modelaccess|.

    ENDTRY.
```
Anthropic Claude 2 基盤モデルを呼び出し、L2 高レベルクライアントを使用してテキストを生成します。  

```
    TRY.
        DATA(lo_bdr_l2_claude) = /aws1/cl_bdr_l2_factory=>create_claude_2( lo_bdr ).
        " iv_prompt can contain a prompt like 'tell me a joke about Java programmers'.
        DATA(lv_answer) = lo_bdr_l2_claude->prompt_for_text( iv_prompt ).
      CATCH /aws1/cx_bdraccessdeniedex INTO DATA(lo_ex).
        WRITE / lo_ex->get_text( ).
        WRITE / |Don't forget to enable model access at https://console.aws.amazon.com/bedrock/home?#/modelaccess|.

    ENDTRY.
```
Anthropic Claude 3 基盤モデルを呼び出し、L2 高レベルクライアントを使用してテキストを生成します。  

```
    TRY.
        " Choose a model ID from Anthropic that supports the Messages API - currently this is
        " Claude v2, Claude v3 and v3.5.  For the list of model ID, see:
        " https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html

        " for the list of models that support the Messages API see:
        " https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-anthropic-claude-messages.html
        DATA(lo_bdr_l2_claude) = /aws1/cl_bdr_l2_factory=>create_anthropic_msg_api(
          io_bdr = lo_bdr
          iv_model_id = 'anthropic.claude-3-sonnet-20240229-v1:0' ).  " choosing Claude v3 Sonnet
        " iv_prompt can contain a prompt like 'tell me a joke about Java programmers'.
        DATA(lv_answer) = lo_bdr_l2_claude->prompt_for_text( iv_prompt = iv_prompt
                                                             iv_max_tokens = 100 ).
      CATCH /aws1/cx_bdraccessdeniedex INTO DATA(lo_ex).
        WRITE / lo_ex->get_text( ).
        WRITE / |Don't forget to enable model access at https://console.aws.amazon.com/bedrock/home?#/modelaccess|.

    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## Stable Diffusion
<a name="stable_diffusion"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_StableDiffusion_sap-abap_1_topic"></a>

次のコード例は、Amazon Bedrock で Stability.ai Stable Diffusion XL を呼び出して画像を生成する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/bdr#code-examples)での設定と実行の方法を確認してください。
Stable Diffusion で画像を作成します。  

```
    "Stable Diffusion Input Parameters should be in a format like this:
*   {
*     "text_prompts": [
*       {"text":"Draw a dolphin with a mustache"},
*       {"text":"Make it photorealistic"}
*     ],
*     "cfg_scale":10,
*     "seed":0,
*     "steps":50
*   }
    TYPES: BEGIN OF prompt_ts,
             text TYPE /aws1/rt_shape_string,
           END OF prompt_ts.

    DATA: BEGIN OF ls_input,
            text_prompts TYPE STANDARD TABLE OF prompt_ts,
            cfg_scale    TYPE /aws1/rt_shape_integer,
            seed         TYPE /aws1/rt_shape_integer,
            steps        TYPE /aws1/rt_shape_integer,
          END OF ls_input.

    APPEND VALUE prompt_ts( text = iv_prompt ) TO ls_input-text_prompts.
    ls_input-cfg_scale = 10.
    ls_input-seed = 0. "or better, choose a random integer.
    ls_input-steps = 50.

    DATA(lv_json) = /ui2/cl_json=>serialize(
      data = ls_input
                pretty_name   = /ui2/cl_json=>pretty_mode-low_case ).

    TRY.
        DATA(lo_response) = lo_bdr->invokemodel(
          iv_body = /aws1/cl_rt_util=>string_to_xstring( lv_json )
          iv_modelid = 'stability.stable-diffusion-xl-v1'
          iv_accept = 'application/json'
          iv_contenttype = 'application/json' ).

        "Stable Diffusion Result Format:
*       {
*         "result": "success",
*         "artifacts": [
*           {
*             "seed": 0,
*             "base64": "iVBORw0KGgoAAAANSUhEUgAAAgAAA....
*             "finishReason": "SUCCESS"
*           }
*         ]
*       }
        TYPES: BEGIN OF artifact_ts,
                 seed         TYPE /aws1/rt_shape_integer,
                 base64       TYPE /aws1/rt_shape_string,
                 finishreason TYPE /aws1/rt_shape_string,
               END OF artifact_ts.

        DATA: BEGIN OF ls_response,
                result    TYPE /aws1/rt_shape_string,
                artifacts TYPE STANDARD TABLE OF artifact_ts,
              END OF ls_response.

        /ui2/cl_json=>deserialize(
          EXPORTING jsonx = lo_response->get_body( )
                    pretty_name = /ui2/cl_json=>pretty_mode-camel_case
          CHANGING  data  = ls_response ).
        IF ls_response-artifacts IS NOT INITIAL.
          DATA(lv_image) = cl_http_utility=>if_http_utility~decode_x_base64( ls_response-artifacts[ 1 ]-base64 ).
        ENDIF.
      CATCH /aws1/cx_bdraccessdeniedex INTO DATA(lo_ex).
        WRITE / lo_ex->get_text( ).
        WRITE / |Don't forget to enable model access at https://console.aws.amazon.com/bedrock/home?#/modelaccess|.

    ENDTRY.
```
Stability.ai Stable Diffusion XL 基盤モデルを呼び出し、L2 高レベルクライアントを使用して画像を生成します。  

```
    TRY.
        DATA(lo_bdr_l2_sd) = /aws1/cl_bdr_l2_factory=>create_stable_diffusion_xl_1( lo_bdr ).
        " iv_prompt contains a prompt like 'Show me a picture of a unicorn reading an enterprise financial report'.
        DATA(lv_image) = lo_bdr_l2_sd->text_to_image( iv_prompt ).
      CATCH /aws1/cx_bdraccessdeniedex INTO DATA(lo_ex).
        WRITE / lo_ex->get_text( ).
        WRITE / |Don't forget to enable model access at https://console.aws.amazon.com/bedrock/home?#/modelaccess|.

    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[InvokeModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Bedrock エージェントランタイムの例
<a name="sap-abap_1_bedrock-agent-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock エージェントランタイムで AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `InvokeAgent`
<a name="bedrock-agent-runtime_InvokeAgent_sap-abap_1_topic"></a>

次のコード例は、`InvokeAgent` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/bdz#code-examples)での設定と実行の方法を確認してください。

```
    DATA(lo_result) = lo_bdz->invokeagent(
      iv_agentid      = iv_agentid
        iv_agentaliasid = iv_agentaliasid
        iv_enabletrace  = abap_true
        iv_sessionid    = CONV #( cl_system_uuid=>create_uuid_c26_static( ) )
        iv_inputtext    = |Let's play "rock, paper, scissors".  I choose rock.| ).
    DATA(lo_stream) = lo_result->get_completion( ).
    TRY.
        " loop while there are still events in the stream
        WHILE lo_stream->/aws1/if_rt_stream_reader~data_available( ) = abap_true.
          DATA(lo_evt) = lo_stream->read( ).
          " each /AWS1/CL_BDZRESPONSESTREAM_EV event contains exactly one member
          " all others are INITIAL.  For each event, process the non-initial
          " member if desired
          IF lo_evt->get_chunk( ) IS NOT INITIAL.
            " Process a Chunk event
            DATA(lv_xstr) = lo_evt->get_chunk( )->get_bytes( ).
            DATA(lv_answer) = /aws1/cl_rt_util=>xstring_to_string( lv_xstr ).
            " the answer says something like "I chose paper, so you lost"
          ELSEIF lo_evt->get_files( ) IS NOT INITIAL.
            " process a Files event if desired
          ELSEIF lo_evt->get_returncontrol( ) IS NOT INITIAL.
            " process a ReturnControl event if desired
          ELSEIF lo_evt->get_trace( ) IS NOT INITIAL.
            " process a Trace event if desired
          ENDIF.
        ENDWHILE.
        " the stream of events can possibly contain an exception
        " which will be raised to break the loop
        " catch /AWS1/CX_BDZACCESSDENIEDEX.
        " catch /AWS1/CX_BDZINTERNALSERVEREX.
        " catch /AWS1/CX_BDZMODELNOTREADYEX.
        " catch /AWS1/CX_BDZVALIDATIONEX.
        " catch /AWS1/CX_BDZTHROTTLINGEX.
        " catch /AWS1/CX_BDZDEPENDENCYFAILEDEX.
        " catch /AWS1/CX_BDZBADGATEWAYEX.
        " catch /AWS1/CX_BDZRESOURCENOTFOUNDEX.
        " catch /AWS1/CX_BDZSERVICEQUOTAEXCDEX.
        " catch /AWS1/CX_BDZCONFLICTEXCEPTION.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[InvokeAgent](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した CloudFront の例
<a name="sap-abap_1_cloudfront_code_examples"></a>

次のコード例は、CloudFront で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `ListDistributions`
<a name="cloudfront_ListDistributions_sap-abap_1_topic"></a>

次の例は、`ListDistributions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/fnt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_fnt->listdistributions( ). " oo_result is returned for testing purposes. "
        MESSAGE 'Retrieved list of CloudFront distributions.' TYPE 'I'.
      CATCH /aws1/cx_fntinvalidargument.
        MESSAGE 'Invalid argument provided.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListDistributions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateDistribution`
<a name="cloudfront_UpdateDistribution_sap-abap_1_topic"></a>

次の例は、`UpdateDistribution` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/fnt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Get the current distribution configuration and ETag "
        DATA(lo_distribution_config_result) = lo_fnt->getdistributionconfig( iv_id = iv_distribution_id ).
        DATA(lo_old_config) = lo_distribution_config_result->get_distributionconfig( ).
        DATA(lv_etag) = lo_distribution_config_result->get_etag( ).

        " Create a new distribution config with the updated comment "
        " Since the config object is immutable, we need to create a new one with all existing values "
        DATA(lo_new_config) = NEW /aws1/cl_fntdistributionconfig(
          iv_callerreference = lo_old_config->get_callerreference( )
          io_aliases = lo_old_config->get_aliases( )
          iv_defaultrootobject = lo_old_config->get_defaultrootobject( )
          io_origins = lo_old_config->get_origins( )
          io_origingroups = lo_old_config->get_origingroups( )
          io_defaultcachebehavior = lo_old_config->get_defaultcachebehavior( )
          io_cachebehaviors = lo_old_config->get_cachebehaviors( )
          io_customerrorresponses = lo_old_config->get_customerrorresponses( )
          iv_comment = iv_comment
          io_logging = lo_old_config->get_logging( )
          iv_priceclass = lo_old_config->get_priceclass( )
          iv_enabled = lo_old_config->get_enabled( )
          io_viewercertificate = lo_old_config->get_viewercertificate( )
          io_restrictions = lo_old_config->get_restrictions( )
          iv_webaclid = lo_old_config->get_webaclid( )
          iv_httpversion = lo_old_config->get_httpversion( )
          iv_isipv6enabled = lo_old_config->get_isipv6enabled( ) ).

        " Update the distribution with the modified configuration "
        lo_fnt->updatedistribution(
          io_distributionconfig = lo_new_config
          iv_id = iv_distribution_id
          iv_ifmatch = lv_etag ).
        MESSAGE 'CloudFront distribution updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_fntnosuchdistribution.
        MESSAGE 'Distribution does not exist.' TYPE 'E'.
      CATCH /aws1/cx_fntpreconditionfailed.
        MESSAGE 'Precondition failed - ETag mismatch.' TYPE 'E'.
      CATCH /aws1/cx_fntinvalidifmatchvrs.
        MESSAGE 'Invalid If-Match version.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[UpdateDistribution](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した CloudWatch の例
<a name="sap-abap_1_cloudwatch_code_examples"></a>

次のコード例は、CloudWatch で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DeleteAlarms`
<a name="cloudwatch_DeleteAlarms_sap-abap_1_topic"></a>

次のコード例は、`DeleteAlarms` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_cwt->deletealarms(
          it_alarmnames = it_alarm_names ).
        MESSAGE 'Alarms deleted.' TYPE 'I'.
      CATCH /aws1/cx_cwtresourcenotfound.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[DeleteAlarms](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeAlarms`
<a name="cloudwatch_DescribeAlarms_sap-abap_1_topic"></a>

次のコード例は、`DescribeAlarms` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cwt->describealarms(                 " oo_result is returned for testing purposes. "
          it_alarmnames = it_alarm_names ).
        MESSAGE 'Alarms retrieved.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[DescribeAlarms](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeAlarmsForMetric`
<a name="cloudwatch_DescribeAlarmsForMetric_sap-abap_1_topic"></a>

次の例は、`DescribeAlarmsForMetric` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cwt->describealarmsformetric(          " oo_result is returned for testing purposes. "
          iv_namespace   = iv_namespace
          iv_metricname  = iv_metric_name
          it_dimensions  = it_dimensions
          iv_statistic   = iv_statistic
          iv_period      = iv_period
          iv_unit        = iv_unit ).
        MESSAGE 'Alarms for metric retrieved.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeAlarmsForMetric](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DisableAlarmActions`
<a name="cloudwatch_DisableAlarmActions_sap-abap_1_topic"></a>

次の例は、`DisableAlarmActions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    "Disables actions on the specified alarm. "
    TRY.
        lo_cwt->disablealarmactions(
          it_alarmnames = it_alarm_names ).
        MESSAGE 'Alarm actions disabled.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[DisableAlarmActions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `EnableAlarmActions`
<a name="cloudwatch_EnableAlarmActions_sap-abap_1_topic"></a>

次のコード例は、`EnableAlarmActions` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    "Enable actions on the specified alarm."
    TRY.
        lo_cwt->enablealarmactions(
          it_alarmnames = it_alarm_names ).
        MESSAGE 'Alarm actions enabled.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[EnableAlarmActions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetMetricStatistics`
<a name="cloudwatch_GetMetricStatistics_sap-abap_1_topic"></a>

次の例は、`GetMetricStatistics` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cwt->getmetricstatistics(              " oo_result is returned for testing purposes. "
          iv_namespace   = iv_namespace
          iv_metricname  = iv_metric_name
          iv_starttime   = iv_start_time
          iv_endtime     = iv_end_time
          iv_period      = iv_period
          it_statistics  = it_statistics ).
        MESSAGE 'Metric statistics retrieved.' TYPE 'I'.
      CATCH /aws1/cx_cwtinvparamvalueex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetMetricStatistics](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListMetrics`
<a name="cloudwatch_ListMetrics_sap-abap_1_topic"></a>

次の例は、`ListMetrics` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    "The following list-metrics example displays the metrics for Amazon CloudWatch."
    TRY.
        oo_result = lo_cwt->listmetrics(            " oo_result is returned for testing purposes. "
          iv_namespace = iv_namespace ).
        DATA(lt_metrics) = oo_result->get_metrics( ).
        MESSAGE 'Metrics retrieved.' TYPE 'I'.
      CATCH /aws1/cx_cwtinvparamvalueex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[ListMetrics](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutMetricAlarm`
<a name="cloudwatch_PutMetricAlarm_sap-abap_1_topic"></a>

次のコード例は、`PutMetricAlarm` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_cwt->putmetricalarm(
          iv_alarmname                 = iv_alarm_name
          iv_comparisonoperator        = iv_comparison_operator
          iv_evaluationperiods         = iv_evaluation_periods
          iv_metricname                = iv_metric_name
          iv_namespace                 = iv_namespace
          iv_statistic                 = iv_statistic
          iv_threshold                 = iv_threshold
          iv_actionsenabled            = iv_actions_enabled
          iv_alarmdescription          = iv_alarm_description
          iv_unit                      = iv_unit
          iv_period                    = iv_period
          it_dimensions                = it_dimensions ).
        MESSAGE 'Alarm created.' TYPE 'I'.
      CATCH /aws1/cx_cwtlimitexceededfault.
        MESSAGE 'The request processing has exceeded the limit' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[PutMetricAlarm](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutMetricData`
<a name="cloudwatch_PutMetricData_sap-abap_1_topic"></a>

次の例は、`PutMetricData` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_metricdata TYPE /aws1/cl_cwtmetricdatum=>tt_metricdata.

    "Create metric data object.
    DATA(lo_metricdatum) = NEW /aws1/cl_cwtmetricdatum(
      iv_metricname = iv_metric_name
      iv_value      = iv_value
      iv_unit       = iv_unit ).

    INSERT lo_metricdatum INTO TABLE lt_metricdata.

    TRY.
        lo_cwt->putmetricdata(
          iv_namespace   = iv_namespace
          it_metricdata  = lt_metricdata ).
        MESSAGE 'Metric data added.' TYPE 'I'.
      CATCH /aws1/cx_cwtinvparamvalueex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
    ENDTRY.
```
一連のデータを CloudWatch メトリクスに配置します。  

```
    DATA lt_metricdata TYPE /aws1/cl_cwtmetricdatum=>tt_metricdata.

    "Create metric data object with values and counts.
    DATA(lo_metricdatum) = NEW /aws1/cl_cwtmetricdatum(
      iv_metricname = iv_metric_name
      iv_timestamp  = iv_timestamp
      iv_unit       = iv_unit
      it_values     = it_values
      it_counts     = it_counts ).

    INSERT lo_metricdatum INTO TABLE lt_metricdata.

    TRY.
        lo_cwt->putmetricdata(
          iv_namespace   = iv_namespace
          it_metricdata  = lt_metricdata ).
        MESSAGE 'Metric data set added.' TYPE 'I'.
      CATCH /aws1/cx_cwtinvparamvalueex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[PutMetricData](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### アラームの使用を開始
<a name="cloudwatch_Scenario_GettingStarted_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ アラームを作成します。
+ アラームアクションの無効化。
+ アラームの記述。
+ アラームの削除。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwt#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_alarmnames TYPE /aws1/cl_cwtalarmnames_w=>tt_alarmnames.
    DATA lo_alarmname TYPE REF TO /aws1/cl_cwtalarmnames_w.

    "Create an alarm"
    TRY.
        lo_cwt->putmetricalarm(
          iv_alarmname                 = iv_alarm_name
          iv_comparisonoperator        = iv_comparison_operator
          iv_evaluationperiods         = iv_evaluation_periods
          iv_metricname                = iv_metric_name
          iv_namespace                 = iv_namespace
          iv_statistic                 = iv_statistic
          iv_threshold                 = iv_threshold
          iv_actionsenabled            = iv_actions_enabled
          iv_alarmdescription          = iv_alarm_description
          iv_unit                      = iv_unit
          iv_period                    = iv_period
          it_dimensions                = it_dimensions ).
        MESSAGE 'Alarm created' TYPE 'I'.
      CATCH /aws1/cx_cwtlimitexceededfault.
        MESSAGE 'The request processing has exceeded the limit' TYPE 'E'.
    ENDTRY.

    "Create an ABAP internal table for the created alarm."
    lo_alarmname = NEW #( iv_value = iv_alarm_name ).
    INSERT lo_alarmname INTO TABLE lt_alarmnames.

    "Disable alarm actions."
    TRY.
        lo_cwt->disablealarmactions(
          it_alarmnames                = lt_alarmnames ).
        MESSAGE 'Alarm actions disabled' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_disablealarm_exception).
        DATA(lv_disablealarm_error) = |"{ lo_disablealarm_exception->av_err_code }" - { lo_disablealarm_exception->av_err_msg }|.
        MESSAGE lv_disablealarm_error TYPE 'E'.
    ENDTRY.

    "Describe alarm using the same ABAP internal table."
    TRY.
        oo_result = lo_cwt->describealarms(                       " oo_result is returned for testing purpose "
          it_alarmnames                = lt_alarmnames ).
        MESSAGE 'Alarms retrieved' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_describealarms_exception).
        DATA(lv_describealarms_error) = |"{ lo_describealarms_exception->av_err_code }" - { lo_describealarms_exception->av_err_msg }|.
        MESSAGE lv_describealarms_error TYPE 'E'.
    ENDTRY.

    "Delete alarm."
    TRY.
        lo_cwt->deletealarms(
          it_alarmnames = lt_alarmnames ).
        MESSAGE 'Alarms deleted' TYPE 'I'.
      CATCH /aws1/cx_cwtresourcenotfound.
        MESSAGE 'Resource being access is not found.' TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の次のトピックを参照してください。
  + [DeleteAlarms](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DescribeAlarms](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DisableAlarmActions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [PutMetricAlarm](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

# SDK for SAP ABAP を使用した CloudWatch Logs の例
<a name="sap-abap_1_cloudwatch-logs_code_examples"></a>

次のコード例は、CloudWatch Logs で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `GetQueryResults`
<a name="cloudwatch-logs_GetQueryResults_sap-abap_1_topic"></a>

次の例は、`GetQueryResults` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwl#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cwl->getqueryresults(
          iv_queryid = iv_query_id ).
        
        " Display query status and result count
        DATA(lv_status) = oo_result->get_status( ).
        DATA(lt_results) = oo_result->get_results( ).
        DATA(lv_result_count) = lines( lt_results ).
        
        MESSAGE |Query status: { lv_status }. Retrieved { lv_result_count } log event(s).| TYPE 'I'.
      CATCH /aws1/cx_cwlinvalidparameterex.
        MESSAGE 'Invalid parameter.' TYPE 'E'.
      CATCH /aws1/cx_cwlresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'E'.
      CATCH /aws1/cx_cwlserviceunavailex.
        MESSAGE 'Service unavailable.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetQueryResults](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartQuery`
<a name="cloudwatch-logs_StartQuery_sap-abap_1_topic"></a>

次の例は、`StartQuery` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cwl#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_log_group_name = '/aws/lambda/my-function'
        " iv_query_string = 'fields @timestamp, @message | sort @timestamp desc | limit 20'
        " iv_start_time and iv_end_time must be in Unix epoch milliseconds (ms since Jan 1, 1970 00:00:00 UTC)
        oo_result = lo_cwl->startquery(
          iv_loggroupname = iv_log_group_name
          iv_starttime    = iv_start_time
          iv_endtime      = iv_end_time
          iv_querystring  = iv_query_string
          iv_limit        = iv_limit ).
        
        " Display the query ID for tracking
        DATA(lv_query_id) = oo_result->get_queryid( ).
        MESSAGE |Query started successfully with ID: { lv_query_id }| TYPE 'I'.
      CATCH /aws1/cx_cwlinvalidparameterex.
        MESSAGE 'Invalid parameter.' TYPE 'E'.
      CATCH /aws1/cx_cwllimitexceededex.
        MESSAGE 'Limit exceeded.' TYPE 'E'.
      CATCH /aws1/cx_cwlmalformedqueryex.
        MESSAGE 'Malformed query.' TYPE 'E'.
      CATCH /aws1/cx_cwlresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'E'.
      CATCH /aws1/cx_cwlserviceunavailex.
        MESSAGE 'Service unavailable.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartQuery](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Cognito ID プロバイダーの例
<a name="sap-abap_1_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_sap-abap_1_topic"></a>

次の例は、`AdminInitiateAuth` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cgp#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Set up authentication parameters
        DATA(lt_auth_params) = VALUE /aws1/cl_cgpauthparamstype_w=>tt_authparameterstype(
          ( VALUE /aws1/cl_cgpauthparamstype_w=>ts_authparameterstype_maprow(
              key = 'USERNAME'
              value = NEW /aws1/cl_cgpauthparamstype_w( iv_user_name ) ) )
          ( VALUE /aws1/cl_cgpauthparamstype_w=>ts_authparameterstype_maprow(
              key = 'PASSWORD'
              value = NEW /aws1/cl_cgpauthparamstype_w( iv_password ) ) )
        ).

        " Add SECRET_HASH if provided
        IF iv_secret_hash IS NOT INITIAL.
          INSERT VALUE #(
            key = 'SECRET_HASH'
            value = NEW /aws1/cl_cgpauthparamstype_w( iv_secret_hash )
          ) INTO TABLE lt_auth_params.
        ENDIF.

        oo_result = lo_cgp->admininitiateauth(
          iv_userpoolid = iv_user_pool_id
          iv_clientid = iv_client_id
          iv_authflow = 'ADMIN_USER_PASSWORD_AUTH'
          it_authparameters = lt_auth_params
        ).

        DATA(lv_challenge) = oo_result->get_challengename( ).

        IF lv_challenge IS INITIAL.
          MESSAGE 'User successfully signed in.' TYPE 'I'.
        ELSE.
          MESSAGE |Authentication challenge required: { lv_challenge }.| TYPE 'I'.
        ENDIF.

      CATCH /aws1/cx_cgpusernotfoundex INTO DATA(lo_user_ex).
        MESSAGE |User { iv_user_name } not found.| TYPE 'E'.

      CATCH /aws1/cx_cgpnotauthorizedex INTO DATA(lo_auth_ex).
        MESSAGE 'Not authorized. Check credentials.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[AdminInitiateAuth](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_sap-abap_1_topic"></a>

次の例は、`AdminRespondToAuthChallenge` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cgp#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Build challenge responses
        DATA(lt_challenge_responses) = VALUE /aws1/cl_cgpchallengerspstyp00=>tt_challengeresponsestype(
          ( VALUE /aws1/cl_cgpchallengerspstyp00=>ts_challengerspstype_maprow(
              key = 'USERNAME'
              value = NEW /aws1/cl_cgpchallengerspstyp00( iv_user_name ) ) )
          ( VALUE /aws1/cl_cgpchallengerspstyp00=>ts_challengerspstype_maprow(
              key = 'SOFTWARE_TOKEN_MFA_CODE'
              value = NEW /aws1/cl_cgpchallengerspstyp00( iv_mfa_code ) ) )
        ).

        " Add SECRET_HASH if provided
        IF iv_secret_hash IS NOT INITIAL.
          INSERT VALUE #(
            key = 'SECRET_HASH'
            value = NEW /aws1/cl_cgpchallengerspstyp00( iv_secret_hash )
          ) INTO TABLE lt_challenge_responses.
        ENDIF.

        DATA(lo_result) = lo_cgp->adminrespondtoauthchallenge(
          iv_userpoolid = iv_user_pool_id
          iv_clientid = iv_client_id
          iv_challengename = 'SOFTWARE_TOKEN_MFA'
          it_challengeresponses = lt_challenge_responses
          iv_session = iv_session
        ).

        oo_auth_result = lo_result->get_authenticationresult( ).

        IF oo_auth_result IS BOUND.
          MESSAGE 'MFA challenge completed successfully.' TYPE 'I'.
        ELSE.
          " Another challenge might be required
          DATA(lv_next_challenge) = lo_result->get_challengename( ).
          MESSAGE |Additional challenge required: { lv_next_challenge }.| TYPE 'I'.
        ENDIF.

      CATCH /aws1/cx_cgpcodemismatchex INTO DATA(lo_code_ex).
        MESSAGE 'Invalid MFA code provided.' TYPE 'E'.

      CATCH /aws1/cx_cgpexpiredcodeex INTO DATA(lo_expired_ex).
        MESSAGE 'MFA code has expired.' TYPE 'E'.

      CATCH /aws1/cx_cgpnotauthorizedex INTO DATA(lo_auth_ex).
        MESSAGE 'Not authorized. Check MFA configuration.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_sap-abap_1_topic"></a>

次の例は、`AssociateSoftwareToken` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cgp#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_cgp->associatesoftwaretoken(
          iv_session = iv_session
        ).

        ov_secret_code = lo_result->get_secretcode( ).

        MESSAGE 'MFA secret code generated successfully.' TYPE 'I'.

      CATCH /aws1/cx_cgpresourcenotfoundex INTO DATA(lo_ex).
        MESSAGE 'Session not found or expired.' TYPE 'E'.

      CATCH /aws1/cx_cgpnotauthorizedex INTO DATA(lo_auth_ex).
        MESSAGE 'Not authorized to associate software token.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[AssociateSoftwareToken](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListUsers`
<a name="cognito-identity-provider_ListUsers_sap-abap_1_topic"></a>

次の例は、`ListUsers` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cgp#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_cgp->listusers(
          iv_userpoolid = iv_user_pool_id
        ).

        ot_users = lo_result->get_users( ).

        MESSAGE |Found { lines( ot_users ) } users in the pool.| TYPE 'I'.

      CATCH /aws1/cx_cgpresourcenotfoundex INTO DATA(lo_ex).
        MESSAGE |User pool { iv_user_pool_id } not found.| TYPE 'E'.

      CATCH /aws1/cx_cgpnotauthorizedex INTO DATA(lo_auth_ex).
        MESSAGE 'Not authorized to list users.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListUsers](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_sap-abap_1_topic"></a>

次の例は、`VerifySoftwareToken` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cgp#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_cgp->verifysoftwaretoken(
          iv_session = iv_session
          iv_usercode = iv_user_code
        ).

        ov_status = lo_result->get_status( ).

        IF ov_status = 'SUCCESS'.
          MESSAGE 'MFA token verified successfully.' TYPE 'I'.
        ELSE.
          MESSAGE |MFA verification status: { ov_status }.| TYPE 'I'.
        ENDIF.

      CATCH /aws1/cx_cgpcodemismatchex INTO DATA(lo_code_ex).
        MESSAGE 'Invalid MFA code provided.' TYPE 'E'.

      CATCH /aws1/cx_cgpenbsoftwaretokmf00 INTO DATA(lo_enabled_ex).
        MESSAGE 'Software token MFA is already enabled.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[VerifySoftwareToken](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Comprehend の例
<a name="sap-abap_1_comprehend_code_examples"></a>

次のコード例は、Amazon Comprehend で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDocumentClassifier`
<a name="comprehend_CreateDocumentClassifier_sap-abap_1_topic"></a>

次の例は、`CreateDocumentClassifier` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->createdocumentclassifier(
          iv_documentclassifiername = iv_classifier_name
          iv_languagecode = iv_language_code
          io_inputdataconfig = NEW /aws1/cl_cpddocclifierinpdat00(
            iv_s3uri = iv_training_s3_uri
          )
          iv_dataaccessrolearn = iv_data_access_role_arn
          iv_mode = iv_mode
        ).
        MESSAGE 'Document classifier creation started.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdresrclimitexcdex.
        MESSAGE 'Resource limit exceeded.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanytagsex.
        MESSAGE 'Too many tags.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateDocumentClassifier](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteDocumentClassifier`
<a name="comprehend_DeleteDocumentClassifier_sap-abap_1_topic"></a>

次の例は、`DeleteDocumentClassifier` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->deletedocumentclassifier(
          iv_documentclassifierarn = iv_classifier_arn
        ).
        MESSAGE 'Document classifier deleted.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'E'.
      CATCH /aws1/cx_cpdresourceinuseex.
        MESSAGE 'Resource in use.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteDocumentClassifier](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDocumentClassificationJob`
<a name="comprehend_DescribeDocumentClassificationJob_sap-abap_1_topic"></a>

次の例は、`DescribeDocumentClassificationJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->describedocclassificationjob(
          iv_jobid = iv_job_id
        ).
        MESSAGE 'Document classification job described.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdjobnotfoundex.
        MESSAGE 'Job not found.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeDocumentClassificationJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDocumentClassifier`
<a name="comprehend_DescribeDocumentClassifier_sap-abap_1_topic"></a>

次の例は、`DescribeDocumentClassifier` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->describedocumentclassifier(
          iv_documentclassifierarn = iv_classifier_arn
        ).
        MESSAGE 'Document classifier described.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeDocumentClassifier](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeTopicsDetectionJob`
<a name="comprehend_DescribeTopicsDetectionJob_sap-abap_1_topic"></a>

次の例は、`DescribeTopicsDetectionJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->describetopicsdetectionjob(
          iv_jobid = iv_job_id
        ).
        MESSAGE 'Topics detection job described.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdjobnotfoundex.
        MESSAGE 'Job not found.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeTopicsDetectionJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectDominantLanguage`
<a name="comprehend_DetectDominantLanguage_sap-abap_1_topic"></a>

次の例は、`DetectDominantLanguage` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->detectdominantlanguage( iv_text = iv_text ).
        MESSAGE 'Languages detected.' TYPE 'I'.
      CATCH /aws1/cx_cpdtextsizelmtexcdex.
        MESSAGE 'Text size exceeds limit.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectDominantLanguage](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectEntities`
<a name="comprehend_DetectEntities_sap-abap_1_topic"></a>

次の例は、`DetectEntities` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->detectentities(
          iv_text = iv_text
          iv_languagecode = iv_language_code
        ).
        MESSAGE 'Entities detected.' TYPE 'I'.
      CATCH /aws1/cx_cpdtextsizelmtexcdex.
        MESSAGE 'Text size exceeds limit.' TYPE 'E'.
      CATCH /aws1/cx_cpdunsuppedlanguageex.
        MESSAGE 'Unsupported language.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectEntities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectKeyPhrases`
<a name="comprehend_DetectKeyPhrases_sap-abap_1_topic"></a>

次の例は、`DetectKeyPhrases` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->detectkeyphrases(
          iv_text = iv_text
          iv_languagecode = iv_language_code
        ).
        MESSAGE 'Key phrases detected.' TYPE 'I'.
      CATCH /aws1/cx_cpdtextsizelmtexcdex.
        MESSAGE 'Text size exceeds limit.' TYPE 'E'.
      CATCH /aws1/cx_cpdunsuppedlanguageex.
        MESSAGE 'Unsupported language.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectKeyPhrases](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectPiiEntities`
<a name="comprehend_DetectPiiEntities_sap-abap_1_topic"></a>

次の例は、`DetectPiiEntities` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->detectpiientities(
          iv_text = iv_text
          iv_languagecode = iv_language_code
        ).
        MESSAGE 'PII entities detected.' TYPE 'I'.
      CATCH /aws1/cx_cpdtextsizelmtexcdex.
        MESSAGE 'Text size exceeds limit.' TYPE 'E'.
      CATCH /aws1/cx_cpdunsuppedlanguageex.
        MESSAGE 'Unsupported language.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectPiiEntities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectSentiment`
<a name="comprehend_DetectSentiment_sap-abap_1_topic"></a>

次の例は、`DetectSentiment` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->detectsentiment(
          iv_text = iv_text
          iv_languagecode = iv_language_code
        ).
        MESSAGE 'Sentiment detected.' TYPE 'I'.
      CATCH /aws1/cx_cpdtextsizelmtexcdex.
        MESSAGE 'Text size exceeds limit.' TYPE 'E'.
      CATCH /aws1/cx_cpdunsuppedlanguageex.
        MESSAGE 'Unsupported language.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectSentiment](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectSyntax`
<a name="comprehend_DetectSyntax_sap-abap_1_topic"></a>

次の例は、`DetectSyntax` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->detectsyntax(
          iv_text = iv_text
          iv_languagecode = iv_language_code
        ).
        MESSAGE 'Syntax tokens detected.' TYPE 'I'.
      CATCH /aws1/cx_cpdtextsizelmtexcdex.
        MESSAGE 'Text size exceeds limit.' TYPE 'E'.
      CATCH /aws1/cx_cpdunsuppedlanguageex.
        MESSAGE 'Unsupported language.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectSyntax](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListDocumentClassificationJobs`
<a name="comprehend_ListDocumentClassificationJobs_sap-abap_1_topic"></a>

次の例は、`ListDocumentClassificationJobs` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->listdocclassificationjobs( ).
        MESSAGE 'Document classification jobs listed.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidfilterex.
        MESSAGE 'Invalid filter.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListDocumentClassificationJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListDocumentClassifiers`
<a name="comprehend_ListDocumentClassifiers_sap-abap_1_topic"></a>

次の例は、`ListDocumentClassifiers` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->listdocumentclassifiers( ).
        MESSAGE 'Document classifiers listed.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidfilterex.
        MESSAGE 'Invalid filter.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListDocumentClassifiers](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTopicsDetectionJobs`
<a name="comprehend_ListTopicsDetectionJobs_sap-abap_1_topic"></a>

次の例は、`ListTopicsDetectionJobs` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->listtopicsdetectionjobs( ).
        MESSAGE 'Topics detection jobs listed.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdinvalidfilterex.
        MESSAGE 'Invalid filter.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListTopicsDetectionJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartDocumentClassificationJob`
<a name="comprehend_StartDocumentClassificationJob_sap-abap_1_topic"></a>

次の例は、`StartDocumentClassificationJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->startdocclassificationjob(
          iv_jobname = iv_job_name
          iv_documentclassifierarn = iv_classifier_arn
          io_inputdataconfig = NEW /aws1/cl_cpdinputdataconfig(
            iv_s3uri = iv_input_s3_uri
            iv_inputformat = iv_input_format
          )
          io_outputdataconfig = NEW /aws1/cl_cpdoutputdataconfig(
            iv_s3uri = iv_output_s3_uri
          )
          iv_dataaccessrolearn = iv_data_access_role_arn
        ).
        MESSAGE 'Document classification job started.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'E'.
      CATCH /aws1/cx_cpdresourceunavailex.
        MESSAGE 'Resource unavailable.' TYPE 'E'.
      CATCH /aws1/cx_cpdkmskeyvalidationex.
        MESSAGE 'KMS key validation error.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanytagsex.
        MESSAGE 'Too many tags.' TYPE 'E'.
      CATCH /aws1/cx_cpdresrclimitexcdex.
        MESSAGE 'Resource limit exceeded.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartDocumentClassificationJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartTopicsDetectionJob`
<a name="comprehend_StartTopicsDetectionJob_sap-abap_1_topic"></a>

次の例は、`StartTopicsDetectionJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cpd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_cpd->starttopicsdetectionjob(
          iv_jobname = iv_job_name
          io_inputdataconfig = NEW /aws1/cl_cpdinputdataconfig(
            iv_s3uri = iv_input_s3_uri
            iv_inputformat = iv_input_format
          )
          io_outputdataconfig = NEW /aws1/cl_cpdoutputdataconfig(
            iv_s3uri = iv_output_s3_uri
          )
          iv_dataaccessrolearn = iv_data_access_role_arn
        ).
        MESSAGE 'Topics detection job started.' TYPE 'I'.
      CATCH /aws1/cx_cpdinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanyrequestsex.
        MESSAGE 'Too many requests.' TYPE 'E'.
      CATCH /aws1/cx_cpdkmskeyvalidationex.
        MESSAGE 'KMS key validation error.' TYPE 'E'.
      CATCH /aws1/cx_cpdtoomanytagsex.
        MESSAGE 'Too many tags.' TYPE 'E'.
      CATCH /aws1/cx_cpdresrclimitexcdex.
        MESSAGE 'Resource limit exceeded.' TYPE 'E'.
      CATCH /aws1/cx_cpdinternalserverex.
        MESSAGE 'Internal server error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartTopicsDetectionJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# AWS Config SDK for SAP ABAP を使用した例
<a name="sap-abap_1_config-service_code_examples"></a>

次のコード例は、 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Config。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteConfigRule`
<a name="config-service_DeleteConfigRule_sap-abap_1_topic"></a>

次の例は、`DeleteConfigRule` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cfs#code-examples)での設定と実行の方法を確認してください。

```
    lo_cfs->deleteconfigrule( iv_rule_name ).
    MESSAGE 'Deleted AWS Config rule.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteConfigRule](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeConfigRules`
<a name="config-service_DescribeConfigRules_sap-abap_1_topic"></a>

次の例は、`DescribeConfigRules` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cfs#code-examples)での設定と実行の方法を確認してください。

```
    DATA(lo_result) = lo_cfs->describeconfigrules(
      it_configrulenames = VALUE /aws1/cl_cfsconfigrulenames_w=>tt_configrulenames(
        ( NEW /aws1/cl_cfsconfigrulenames_w( iv_rule_name ) )
      )
    ).
    ot_cfg_rules = lo_result->get_configrules( ).
    MESSAGE 'Retrieved AWS Config rule data.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeConfigRules](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutConfigRule`
<a name="config-service_PutConfigRule_sap-abap_1_topic"></a>

次の例は、`PutConfigRule` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cfs#code-examples)での設定と実行の方法を確認してください。

```
    " Create a config rule for S3 bucket public read prohibition
    lo_cfs->putconfigrule(
      io_configrule = NEW /aws1/cl_cfsconfigrule(
        iv_configrulename = iv_rule_name
        iv_description = |S3 Public Read Prohibited Bucket Rule|
        io_scope = NEW /aws1/cl_cfsscope(
          it_complianceresourcetypes = VALUE /aws1/cl_cfscplncresrctypes_w=>tt_complianceresourcetypes(
            ( NEW /aws1/cl_cfscplncresrctypes_w( |AWS::S3::Bucket| ) )
          )
        )
        io_source = NEW /aws1/cl_cfssource(
          iv_owner = |AWS|
          iv_sourceidentifier = |S3_BUCKET_PUBLIC_READ_PROHIBITED|
        )
        iv_inputparameters = '{}'
        iv_configrulestate = |ACTIVE|
      )
    ).
    MESSAGE 'Created AWS Config rule.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutConfigRule](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# AWS Control Tower SDK for SAP ABAP を使用した例
<a name="sap-abap_1_controltower_code_examples"></a>

次のコード例は、 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Control Tower。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DisableBaseline`
<a name="controltower_DisableBaseline_sap-abap_1_topic"></a>

次の例は、`DisableBaseline` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Disable the baseline
        DATA(lo_output) = io_ctt->disablebaseline(
          iv_enabledbaselineidentifier = iv_enabled_baseline_identifier
        ).

        DATA(lv_operation_id) = lo_output->get_operationidentifier( ).

        " Wait for operation to complete
        DATA lv_status TYPE /aws1/cttbaselineopstatus.
        DO 100 TIMES.
          lv_status = get_baseline_operation(
            io_ctt = io_ctt
            iv_operation_id = lv_operation_id
          ).

          DATA(lv_msg) = |Baseline operation status: { lv_status }|.
          MESSAGE lv_msg TYPE 'I'.

          IF lv_status = 'SUCCEEDED' OR lv_status = 'FAILED'.
            EXIT.
          ENDIF.

          " Wait 30 seconds
          WAIT UP TO 30 SECONDS.
        ENDDO.

        ov_operation_id = lv_operation_id.
        MESSAGE 'Baseline disabled successfully.' TYPE 'I'.
      CATCH /aws1/cx_cttconflictexception INTO DATA(lo_conflict).
        " Log conflict but don't fail - return empty operation ID
        DATA(lv_msg2) = |Conflict disabling baseline: { lo_conflict->get_text( ) }. Skipping disable step.|.
        MESSAGE lv_msg2 TYPE 'I'.
        CLEAR ov_operation_id.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DisableBaseline](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DisableControl`
<a name="controltower_DisableControl_sap-abap_1_topic"></a>

次の例は、`DisableControl` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    " Disable the control
    DATA(lo_output) = io_ctt->disablecontrol(
      iv_controlidentifier = iv_control_arn
      iv_targetidentifier  = iv_target_identifier
    ).

    DATA(lv_operation_id) = lo_output->get_operationidentifier( ).

    " Wait for operation to complete
    DATA lv_status TYPE /aws1/cttcontrolopstatus.
    DO 100 TIMES.
      lv_status = get_control_operation(
        io_ctt = io_ctt
        iv_operation_id = lv_operation_id
      ).

      DATA(lv_msg) = |Control operation status: { lv_status }|.
      MESSAGE lv_msg TYPE 'I'.

      IF lv_status = 'SUCCEEDED' OR lv_status = 'FAILED'.
        EXIT.
      ENDIF.

      " Wait 30 seconds
      WAIT UP TO 30 SECONDS.
    ENDDO.

    ov_operation_id = lv_operation_id.
    MESSAGE 'Control disabled successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DisableControl](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `EnableBaseline`
<a name="controltower_EnableBaseline_sap-abap_1_topic"></a>

次の例は、`EnableBaseline` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    " Prepare parameters for enabling baseline
    DATA lt_parameters TYPE /aws1/cl_cttenbdbaselineparam=>tt_enabledbaselineparameters.

    " Add Identity Center baseline parameter if provided
    IF iv_identity_center_baseline IS NOT INITIAL.
      " Create a JSON document with the baseline ARN value
      DATA(lv_json) = |\{ "IdentityCenterEnabledBaselineArn": "{ iv_identity_center_baseline }" \}|.
      DATA(lo_param) = NEW /aws1/cl_cttenbdbaselineparam(
        iv_key = 'IdentityCenterEnabledBaselineArn'
        io_value = /aws1/cl_rt_document=>from_json_str( lv_json )
      ).
      APPEND lo_param TO lt_parameters.
    ENDIF.

    " Enable the baseline
    DATA(lo_output) = io_ctt->enablebaseline(
      iv_baselineidentifier = iv_baseline_identifier
      iv_baselineversion    = iv_baseline_version
      iv_targetidentifier   = iv_target_identifier
      it_parameters         = lt_parameters
    ).

    DATA(lv_operation_id) = lo_output->get_operationidentifier( ).

    " Wait for operation to complete
    DATA lv_status TYPE /aws1/cttbaselineopstatus.
    DO 100 TIMES.
      lv_status = get_baseline_operation(
        io_ctt = io_ctt
        iv_operation_id = lv_operation_id
      ).

      DATA(lv_msg) = |Baseline operation status: { lv_status }|.
      MESSAGE lv_msg TYPE 'I'.

      IF lv_status = 'SUCCEEDED' OR lv_status = 'FAILED'.
        EXIT.
      ENDIF.

      " Wait 30 seconds
      WAIT UP TO 30 SECONDS.
    ENDDO.

    ov_enabled_baseline_arn = lo_output->get_arn( ).
    MESSAGE 'Baseline enabled successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[EnableBaseline](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `EnableControl`
<a name="controltower_EnableControl_sap-abap_1_topic"></a>

次の例は、`EnableControl` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    " Enable the control
    DATA(lo_output) = io_ctt->enablecontrol(
      iv_controlidentifier = iv_control_arn
      iv_targetidentifier  = iv_target_identifier
    ).

    DATA(lv_operation_id) = lo_output->get_operationidentifier( ).

    " Wait for operation to complete
    DATA lv_status TYPE /aws1/cttcontrolopstatus.
    DO 100 TIMES.
      lv_status = get_control_operation(
        io_ctt = io_ctt
        iv_operation_id = lv_operation_id
      ).

      DATA(lv_msg) = |Control operation status: { lv_status }|.
      MESSAGE lv_msg TYPE 'I'.

      IF lv_status = 'SUCCEEDED' OR lv_status = 'FAILED'.
        EXIT.
      ENDIF.

      " Wait 30 seconds
      WAIT UP TO 30 SECONDS.
    ENDDO.

    ov_operation_id = lv_operation_id.
    MESSAGE 'Control enabled successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[EnableControl](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetBaselineOperation`
<a name="controltower_GetBaselineOperation_sap-abap_1_topic"></a>

次の例は、`GetBaselineOperation` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    DATA(lo_output) = io_ctt->getbaselineoperation(
      iv_operationidentifier = iv_operation_id
    ).

    ov_status = lo_output->get_baselineoperation( )->get_status( ).
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetBaselineOperation](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetControlOperation`
<a name="controltower_GetControlOperation_sap-abap_1_topic"></a>

次の例は、`GetControlOperation` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    DATA(lo_output) = io_ctt->getcontroloperation(
      iv_operationidentifier = iv_operation_id
    ).

    ov_status = lo_output->get_controloperation( )->get_status( ).
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetControlOperation](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListBaselines`
<a name="controltower_ListBaselines_sap-abap_1_topic"></a>

次の例は、`ListBaselines` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_baselines TYPE /aws1/cl_cttbaselinesummary=>tt_baselines.
    DATA lv_nexttoken TYPE /aws1/cttstring.

    " List all baselines using pagination
    DO.
      DATA(lo_output) = io_ctt->listbaselines(
        iv_nexttoken = lv_nexttoken
      ).

      APPEND LINES OF lo_output->get_baselines( ) TO lt_baselines.

      lv_nexttoken = lo_output->get_nexttoken( ).
      IF lv_nexttoken IS INITIAL.
        EXIT.
      ENDIF.
    ENDDO.

    ot_baselines = lt_baselines.
    MESSAGE 'Listed baselines successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListBaselines](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListEnabledBaselines`
<a name="controltower_ListEnabledBaselines_sap-abap_1_topic"></a>

次の例は、`ListEnabledBaselines` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_enabled_baselines TYPE /aws1/cl_cttenbdbaselinesumm=>tt_enabledbaselines.
    DATA lv_nexttoken TYPE /aws1/cttlstenbdbaselinesnex00.

    " List all enabled baselines using pagination
    DO.
      DATA(lo_output) = io_ctt->listenabledbaselines(
        iv_nexttoken = lv_nexttoken
      ).

      APPEND LINES OF lo_output->get_enabledbaselines( ) TO lt_enabled_baselines.

      lv_nexttoken = lo_output->get_nexttoken( ).
      IF lv_nexttoken IS INITIAL.
        EXIT.
      ENDIF.
    ENDDO.

    ot_enabled_baselines = lt_enabled_baselines.
    MESSAGE 'Listed enabled baselines successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListEnabledBaselines](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListEnabledControls`
<a name="controltower_ListEnabledControls_sap-abap_1_topic"></a>

次の例は、`ListEnabledControls` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_enabled_controls TYPE /aws1/cl_cttenabledcontrolsumm=>tt_enabledcontrols.
    DATA lv_nexttoken TYPE /aws1/cttstring.

    " List all enabled controls using pagination
    DO.
      DATA(lo_output) = io_ctt->listenabledcontrols(
        iv_targetidentifier = iv_target_identifier
        iv_nexttoken        = lv_nexttoken
      ).

      APPEND LINES OF lo_output->get_enabledcontrols( ) TO lt_enabled_controls.

      lv_nexttoken = lo_output->get_nexttoken( ).
      IF lv_nexttoken IS INITIAL.
        EXIT.
      ENDIF.
    ENDDO.

    ot_enabled_controls = lt_enabled_controls.
    MESSAGE 'Listed enabled controls successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListEnabledControls](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListLandingZones`
<a name="controltower_ListLandingZones_sap-abap_1_topic"></a>

次の例は、`ListLandingZones` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_landing_zones TYPE /aws1/cl_cttlandingzonesummary=>tt_landingzonesummaries.
    DATA lv_nexttoken TYPE /aws1/cttstring.

    " List all landing zones using pagination
    DO.
      DATA(lo_output) = io_ctt->listlandingzones(
        iv_nexttoken = lv_nexttoken
      ).

      APPEND LINES OF lo_output->get_landingzones( ) TO lt_landing_zones.

      lv_nexttoken = lo_output->get_nexttoken( ).
      IF lv_nexttoken IS INITIAL.
        EXIT.
      ENDIF.
    ENDDO.

    ot_landing_zones = lt_landing_zones.
    MESSAGE 'Listed landing zones successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListLandingZones](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ResetEnabledBaseline`
<a name="controltower_ResetEnabledBaseline_sap-abap_1_topic"></a>

次の例は、`ResetEnabledBaseline` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ctt#code-examples)での設定と実行の方法を確認してください。

```
    " Reset the enabled baseline
    DATA(lo_output) = io_ctt->resetenabledbaseline(
      iv_enabledbaselineidentifier = iv_enabled_baseline_identifier
    ).

    DATA(lv_operation_id) = lo_output->get_operationidentifier( ).

    " Wait for operation to complete
    DATA lv_status TYPE /aws1/cttbaselineopstatus.
    DO 100 TIMES.
      lv_status = get_baseline_operation(
        io_ctt = io_ctt
        iv_operation_id = lv_operation_id
      ).

      DATA(lv_msg) = |Baseline operation status: { lv_status }|.
      MESSAGE lv_msg TYPE 'I'.

      IF lv_status = 'SUCCEEDED' OR lv_status = 'FAILED'.
        EXIT.
      ENDIF.

      " Wait 30 seconds
      WAIT UP TO 30 SECONDS.
    ENDDO.

    ov_operation_id = lv_operation_id.
    MESSAGE 'Baseline reset successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ResetEnabledBaseline](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Firehose の例
<a name="sap-abap_1_firehose_code_examples"></a>

次のコード例は、Firehose で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `PutRecord`
<a name="firehose_PutRecord_sap-abap_1_topic"></a>

次の例は、`PutRecord` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/frh#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_record) = NEW /aws1/cl_frhrecord( iv_data = iv_data ).

        DATA(lo_result) = lo_frh->putrecord(
          iv_deliverystreamname = iv_deliv_stream_name
          io_record             = lo_record ).

        MESSAGE 'Record sent to Firehose delivery stream.' TYPE 'I'.
      CATCH /aws1/cx_frhresourcenotfoundex.
        MESSAGE 'Delivery stream not found.' TYPE 'E'.
      CATCH /aws1/cx_frhinvalidargumentex.
        MESSAGE 'Invalid argument provided.' TYPE 'E'.
      CATCH /aws1/cx_frhserviceunavailex.
        MESSAGE 'Service temporarily unavailable.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[PutRecord](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutRecordBatch`
<a name="firehose_PutRecordBatch_sap-abap_1_topic"></a>

次の例は、`PutRecordBatch` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/frh#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_frh->putrecordbatch(
          iv_deliverystreamname = iv_deliv_stream_name
          it_records            = it_records ).

        DATA(lv_failed_count) = lo_result->get_failedputcount( ).

        IF lv_failed_count > 0.
          MESSAGE |{ lv_failed_count } records failed to send.| TYPE 'I'.
        ELSE.
          MESSAGE 'All records sent successfully to Firehose delivery stream.' TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_frhresourcenotfoundex.
        MESSAGE 'Delivery stream not found.' TYPE 'E'.
      CATCH /aws1/cx_frhinvalidargumentex.
        MESSAGE 'Invalid argument provided.' TYPE 'E'.
      CATCH /aws1/cx_frhserviceunavailex.
        MESSAGE 'Service temporarily unavailable.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[PutRecordBatch](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した DynamoDB の例
<a name="sap-abap_1_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    " Create an Amazon Dynamo DB table.

    TRY.
        DATA(lo_session) = /aws1/cl_rt_session_aws=>create( cv_pfl ).
        DATA(lo_dyn) = /aws1/cl_dyn_factory=>create( lo_session ).
        DATA(lt_keyschema) = VALUE /aws1/cl_dynkeyschemaelement=>tt_keyschema(
          ( NEW /aws1/cl_dynkeyschemaelement( iv_attributename = 'year'
                                              iv_keytype = 'HASH' ) )
          ( NEW /aws1/cl_dynkeyschemaelement( iv_attributename = 'title'
                                              iv_keytype = 'RANGE' ) ) ).
        DATA(lt_attributedefinitions) = VALUE /aws1/cl_dynattributedefn=>tt_attributedefinitions(
          ( NEW /aws1/cl_dynattributedefn( iv_attributename = 'year'
                                           iv_attributetype = 'N' ) )
          ( NEW /aws1/cl_dynattributedefn( iv_attributename = 'title'
                                           iv_attributetype = 'S' ) ) ).

        " Adjust read/write capacities as desired.
        DATA(lo_dynprovthroughput)  = NEW /aws1/cl_dynprovthroughput(
          iv_readcapacityunits = 5
          iv_writecapacityunits = 5 ).
        DATA(oo_result) = lo_dyn->createtable(
          it_keyschema = lt_keyschema
          iv_tablename = iv_table_name
          it_attributedefinitions = lt_attributedefinitions
          io_provisionedthroughput = lo_dynprovthroughput ).
        " Table creation can take some time. Wait till table exists before returning.
        lo_dyn->get_waiter( )->tableexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'DynamoDB Table' && iv_table_name && 'created.' TYPE 'I'.
        " It throws exception if the table already exists.
      CATCH /aws1/cx_dynresourceinuseex INTO DATA(lo_resourceinuseex).
        DATA(lv_error) = |"{ lo_resourceinuseex->av_err_code }" - { lo_resourceinuseex->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.

    " Describe table
    TRY.
        DATA(lo_table) = lo_dyn->describetable( iv_tablename = iv_table_name ).
        DATA(lv_tablename) = lo_table->get_table( )->ask_tablename( ).
        MESSAGE 'The table name is ' && lv_tablename TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table does not exist' TYPE 'E'.
    ENDTRY.

    " Put items into the table.
    TRY.
        DATA(lo_resp_putitem) = lo_dyn->putitem(
          iv_tablename = iv_table_name
          it_item      = VALUE /aws1/cl_dynattributevalue=>tt_putiteminputattributemap(
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'title' value = NEW /aws1/cl_dynattributevalue( iv_s = 'Jaws' ) ) )
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'year' value = NEW /aws1/cl_dynattributevalue( iv_n = |{ '1975' }| ) ) )
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'rating' value = NEW /aws1/cl_dynattributevalue( iv_n = |{ '7.5' }| ) ) )
          ) ).
        lo_resp_putitem = lo_dyn->putitem(
          iv_tablename = iv_table_name
          it_item      = VALUE /aws1/cl_dynattributevalue=>tt_putiteminputattributemap(
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'title' value = NEW /aws1/cl_dynattributevalue( iv_s = 'Star Wars' ) ) )
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'year' value = NEW /aws1/cl_dynattributevalue( iv_n = |{ '1978' }| ) ) )
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'rating' value = NEW /aws1/cl_dynattributevalue( iv_n = |{ '8.1' }| ) ) )
          ) ).
        lo_resp_putitem = lo_dyn->putitem(
          iv_tablename = iv_table_name
          it_item      = VALUE /aws1/cl_dynattributevalue=>tt_putiteminputattributemap(
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'title' value = NEW /aws1/cl_dynattributevalue( iv_s = 'Speed' ) ) )
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'year' value = NEW /aws1/cl_dynattributevalue( iv_n = |{ '1994' }| ) ) )
            ( VALUE /aws1/cl_dynattributevalue=>ts_putiteminputattrmap_maprow(
              key = 'rating' value = NEW /aws1/cl_dynattributevalue( iv_n = |{ '7.9' }| ) ) )
          ) ).
        " TYPE REF TO /AWSEX/CL_AWS1_dyn_PUT_ITEM_OUTPUT
        MESSAGE '3 rows inserted into DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.

    " Get item from table.
    TRY.
        DATA(lo_resp_getitem) = lo_dyn->getitem(
          iv_tablename                = iv_table_name
          it_key                      = VALUE /aws1/cl_dynattributevalue=>tt_key(
           ( VALUE /aws1/cl_dynattributevalue=>ts_key_maprow(
             key = 'title' value = NEW /aws1/cl_dynattributevalue( iv_s = 'Jaws' ) ) )
           ( VALUE /aws1/cl_dynattributevalue=>ts_key_maprow(
             key = 'year' value = NEW /aws1/cl_dynattributevalue( iv_n = '1975' ) ) )
          ) ).
        DATA(lt_attr) = lo_resp_getitem->get_item( ).
        DATA(lo_title) = lt_attr[ key = 'title' ]-value.
        DATA(lo_year) = lt_attr[ key = 'year' ]-value.
        DATA(lo_rating) = lt_attr[ key = 'year' ]-value.
        MESSAGE 'Movie name is: ' && lo_title->get_s( ) TYPE 'I'.
        MESSAGE 'Movie year is: ' && lo_year->get_n( ) TYPE 'I'.
        MESSAGE 'Movie rating is: ' && lo_rating->get_n( ) TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.

    " Query item from table.
    TRY.
        DATA(lt_attributelist) = VALUE /aws1/cl_dynattributevalue=>tt_attributevaluelist(
              ( NEW /aws1/cl_dynattributevalue( iv_n = '1975' ) ) ).
        DATA(lt_keyconditions) = VALUE /aws1/cl_dyncondition=>tt_keyconditions(
          ( VALUE /aws1/cl_dyncondition=>ts_keyconditions_maprow(
          key = 'year'
          value = NEW /aws1/cl_dyncondition(
            it_attributevaluelist = lt_attributelist
            iv_comparisonoperator = |EQ|
          ) ) ) ).
        DATA(lo_query_result) = lo_dyn->query(
          iv_tablename = iv_table_name
          it_keyconditions = lt_keyconditions ).
        DATA(lt_items) = lo_query_result->get_items( ).
        READ TABLE lo_query_result->get_items( ) INTO DATA(lt_item) INDEX 1.
        lo_title = lt_item[ key = 'title' ]-value.
        lo_year = lt_item[ key = 'year' ]-value.
        lo_rating = lt_item[ key = 'rating' ]-value.
        MESSAGE 'Movie name is: ' && lo_title->get_s( ) TYPE 'I'.
        MESSAGE 'Movie year is: ' && lo_year->get_n( ) TYPE 'I'.
        MESSAGE 'Movie rating is: ' && lo_rating->get_n( ) TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.

    " Scan items from table.
    TRY.
        DATA(lo_scan_result) = lo_dyn->scan( iv_tablename = iv_table_name ).
        lt_items = lo_scan_result->get_items( ).
        " Read the first item and display the attributes.
        READ TABLE lo_query_result->get_items( ) INTO lt_item INDEX 1.
        lo_title = lt_item[ key = 'title' ]-value.
        lo_year = lt_item[ key = 'year' ]-value.
        lo_rating = lt_item[ key = 'rating' ]-value.
        MESSAGE 'Movie name is: ' && lo_title->get_s( ) TYPE 'I'.
        MESSAGE 'Movie year is: ' && lo_year->get_n( ) TYPE 'I'.
        MESSAGE 'Movie rating is: ' && lo_rating->get_n( ) TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.

    " Update items from table.
    TRY.
        DATA(lt_attributeupdates) = VALUE /aws1/cl_dynattrvalueupdate=>tt_attributeupdates(
          ( VALUE /aws1/cl_dynattrvalueupdate=>ts_attributeupdates_maprow(
          key = 'rating' value = NEW /aws1/cl_dynattrvalueupdate(
            io_value  = NEW /aws1/cl_dynattributevalue( iv_n = '7.6' )
            iv_action = |PUT| ) ) ) ).
        DATA(lt_key) = VALUE /aws1/cl_dynattributevalue=>tt_key(
          ( VALUE /aws1/cl_dynattributevalue=>ts_key_maprow(
            key = 'year' value = NEW /aws1/cl_dynattributevalue( iv_n = '1975' ) ) )
          ( VALUE /aws1/cl_dynattributevalue=>ts_key_maprow(
            key = 'title' value = NEW /aws1/cl_dynattributevalue( iv_s = '1980' ) ) ) ).
        DATA(lo_resp) = lo_dyn->updateitem(
          iv_tablename        = iv_table_name
          it_key              = lt_key
          it_attributeupdates = lt_attributeupdates ).
        MESSAGE '1 item updated in DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.

    " Delete table.
    TRY.
        lo_dyn->deletetable( iv_tablename = iv_table_name ).
        lo_dyn->get_waiter( )->tablenotexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'DynamoDB Table deleted.' TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dynresourceinuseex.
        MESSAGE 'The table cannot be deleted as it is in use' TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [BatchWriteItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [CreateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DescribeTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [GetItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [PutItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [Query](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [Scan](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [UpdateItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateTable`
<a name="dynamodb_CreateTable_sap-abap_1_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lt_keyschema) = VALUE /aws1/cl_dynkeyschemaelement=>tt_keyschema(
          ( NEW /aws1/cl_dynkeyschemaelement( iv_attributename = 'year'
                                              iv_keytype = 'HASH' ) )
          ( NEW /aws1/cl_dynkeyschemaelement( iv_attributename = 'title'
                                              iv_keytype = 'RANGE' ) ) ).
        DATA(lt_attributedefinitions) = VALUE /aws1/cl_dynattributedefn=>tt_attributedefinitions(
          ( NEW /aws1/cl_dynattributedefn( iv_attributename = 'year'
                                           iv_attributetype = 'N' ) )
          ( NEW /aws1/cl_dynattributedefn( iv_attributename = 'title'
                                           iv_attributetype = 'S' ) ) ).

        " Adjust read/write capacities as desired.
        DATA(lo_dynprovthroughput)  = NEW /aws1/cl_dynprovthroughput(
          iv_readcapacityunits = 5
          iv_writecapacityunits = 5 ).
        oo_result = lo_dyn->createtable(
          it_keyschema = lt_keyschema
          iv_tablename = iv_table_name
          it_attributedefinitions = lt_attributedefinitions
          io_provisionedthroughput = lo_dynprovthroughput ).
        " Table creation can take some time. Wait till table exists before returning.
        lo_dyn->get_waiter( )->tableexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'DynamoDB Table' && iv_table_name && 'created.' TYPE 'I'.
        " This exception can happen if the table already exists.
      CATCH /aws1/cx_dynresourceinuseex INTO DATA(lo_resourceinuseex).
        DATA(lv_error) = |"{ lo_resourceinuseex->av_err_code }" - { lo_resourceinuseex->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_sap-abap_1_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_resp) = lo_dyn->deleteitem(
          iv_tablename                = iv_table_name
          it_key                      = it_key_input ).
        MESSAGE 'Deleted one item.' TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[DeleteItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_sap-abap_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_dyn->deletetable( iv_tablename = iv_table_name ).
        " Wait till the table is actually deleted.
        lo_dyn->get_waiter( )->tablenotexists(
          iv_max_wait_time = 200
          iv_tablename     = iv_table_name ).
        MESSAGE 'Table ' && iv_table_name && ' deleted.' TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table ' && iv_table_name && ' does not exist' TYPE 'E'.
      CATCH /aws1/cx_dynresourceinuseex.
        MESSAGE 'The table cannot be deleted since it is in use' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeTable`
<a name="dynamodb_DescribeTable_sap-abap_1_topic"></a>

次のコード例は、`DescribeTable` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_dyn->describetable( iv_tablename = iv_table_name ).
        DATA(lv_tablename) = oo_result->get_table( )->ask_tablename( ).
        DATA(lv_tablearn) = oo_result->get_table( )->ask_tablearn( ).
        DATA(lv_tablestatus) = oo_result->get_table( )->ask_tablestatus( ).
        DATA(lv_itemcount) = oo_result->get_table( )->ask_itemcount( ).
        MESSAGE 'The table name is ' && lv_tablename
            && '. The table ARN is ' && lv_tablearn
            && '. The tablestatus is ' && lv_tablestatus
            && '. Item count is ' && lv_itemcount TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table ' && lv_tablename && ' does not exist' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_sap-abap_1_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_item = lo_dyn->getitem(
          iv_tablename                = iv_table_name
          it_key                      = it_key ).
        DATA(lt_attr) = oo_item->get_item( ).
        DATA(lo_title) = lt_attr[ key = 'title' ]-value.
        DATA(lo_year) = lt_attr[ key = 'year' ]-value.
        DATA(lo_rating) = lt_attr[ key = 'rating' ]-value.
        MESSAGE 'Movie name is: ' && lo_title->get_s( )
          && 'Movie year is: ' && lo_year->get_n( )
          && 'Moving rating is: ' && lo_rating->get_n( ) TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_sap-abap_1_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_dyn->listtables( ).
        " You can loop over the oo_result to get table properties like this.
        LOOP AT oo_result->get_tablenames( ) INTO DATA(lo_table_name).
          DATA(lv_tablename) = lo_table_name->get_value( ).
        ENDLOOP.
        DATA(lv_tablecount) = lines( oo_result->get_tablenames( ) ).
        MESSAGE 'Found ' && lv_tablecount && ' tables' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[ListTables](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_sap-abap_1_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_resp) = lo_dyn->putitem(
          iv_tablename = iv_table_name
          it_item      = it_item ).
        MESSAGE '1 row inserted into DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[PutItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Query`
<a name="dynamodb_Query_sap-abap_1_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Query movies for a given year .
        DATA(lt_attributelist) = VALUE /aws1/cl_dynattributevalue=>tt_attributevaluelist(
            ( NEW /aws1/cl_dynattributevalue( iv_n = |{ iv_year }| ) ) ).
        DATA(lt_key_conditions) = VALUE /aws1/cl_dyncondition=>tt_keyconditions(
          ( VALUE /aws1/cl_dyncondition=>ts_keyconditions_maprow(
          key = 'year'
          value = NEW /aws1/cl_dyncondition(
          it_attributevaluelist = lt_attributelist
          iv_comparisonoperator = |EQ|
          ) ) ) ).
        oo_result = lo_dyn->query(
          iv_tablename = iv_table_name
          it_keyconditions = lt_key_conditions ).
        DATA(lt_items) = oo_result->get_items( ).
        "You can loop over the results to get item attributes.
        LOOP AT lt_items INTO DATA(lt_item).
          DATA(lo_title) = lt_item[ key = 'title' ]-value.
          DATA(lo_year) = lt_item[ key = 'year' ]-value.
        ENDLOOP.
        DATA(lv_count) = oo_result->get_count( ).
        MESSAGE 'Item count is: ' && lv_count TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[Query](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Scan`
<a name="dynamodb_Scan_sap-abap_1_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Scan movies for rating greater than or equal to the rating specified
        DATA(lt_attributelist) = VALUE /aws1/cl_dynattributevalue=>tt_attributevaluelist(
            ( NEW /aws1/cl_dynattributevalue( iv_n = |{ iv_rating }| ) ) ).
        DATA(lt_filter_conditions) = VALUE /aws1/cl_dyncondition=>tt_filterconditionmap(
          ( VALUE /aws1/cl_dyncondition=>ts_filterconditionmap_maprow(
          key = 'rating'
          value = NEW /aws1/cl_dyncondition(
          it_attributevaluelist = lt_attributelist
          iv_comparisonoperator = |GE|
          ) ) ) ).
        oo_scan_result = lo_dyn->scan( iv_tablename = iv_table_name
          it_scanfilter = lt_filter_conditions ).
        DATA(lt_items) = oo_scan_result->get_items( ).
        LOOP AT lt_items INTO DATA(lo_item).
          " You can loop over to get individual attributes.
          DATA(lo_title) = lo_item[ key = 'title' ]-value.
          DATA(lo_year) = lo_item[ key = 'year' ]-value.
        ENDLOOP.
        DATA(lv_count) = oo_scan_result->get_count( ).
        MESSAGE 'Found ' && lv_count && ' items' TYPE 'I'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[Scan](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateItem`
<a name="dynamodb_UpdateItem_sap-abap_1_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/dyn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_output = lo_dyn->updateitem(
          iv_tablename        = iv_table_name
          it_key              = it_item_key
          it_attributeupdates = it_attribute_updates ).
        MESSAGE '1 item updated in DynamoDB Table' && iv_table_name TYPE 'I'.
      CATCH /aws1/cx_dyncondalcheckfaile00.
        MESSAGE 'A condition specified in the operation could not be evaluated.' TYPE 'E'.
      CATCH /aws1/cx_dynresourcenotfoundex.
        MESSAGE 'The table or index does not exist' TYPE 'E'.
      CATCH /aws1/cx_dyntransactconflictex.
        MESSAGE 'Another transaction is using the item' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[UpdateItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon EC2 の例
<a name="sap-abap_1_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_sap-abap_1_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->allocateaddress( iv_domain = 'vpc' ).   " oo_result is returned for testing purposes. "
        MESSAGE 'Allocated an Elastic IP address.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[AllocateAddress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `AssociateAddress`
<a name="ec2_AssociateAddress_sap-abap_1_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->associateaddress(                         " oo_result is returned for testing purposes. "
            iv_allocationid = iv_allocation_id
            iv_instanceid = iv_instance_id ).
        MESSAGE 'Associated an Elastic IP address with an EC2 instance.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[AssociateAddress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_sap-abap_1_topic"></a>

次の例は、`AuthorizeSecurityGroupIngress` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    " Create IP permissions for SSH access (port 22)
    " iv_cidr_ip = '192.0.2.0/24'
    DATA lt_ip_permissions TYPE /aws1/cl_ec2ippermission=>tt_ippermissionlist.
    DATA(lo_ip_permission) = NEW /aws1/cl_ec2ippermission(
      iv_ipprotocol = 'tcp'
      iv_fromport = 22
      iv_toport = 22
      it_ipranges = VALUE /aws1/cl_ec2iprange=>tt_iprangelist(
        ( NEW /aws1/cl_ec2iprange( iv_cidrip = iv_cidr_ip ) )
      )
    ).
    APPEND lo_ip_permission TO lt_ip_permissions.

    TRY.
        oo_result = lo_ec2->authsecuritygroupingress(             " oo_result is returned for testing purposes. "
          iv_groupid = iv_group_id
          it_ippermissions = lt_ip_permissions ).
        MESSAGE 'Authorized ingress rule for security group.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_sap-abap_1_topic"></a>

次の例は、`CreateKeyPair` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->createkeypair( iv_keyname = iv_key_name ).                            " oo_result is returned for testing purposes. "
        MESSAGE 'Amazon EC2 key pair created.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateKeyPair](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_sap-abap_1_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->createsecuritygroup(                 " oo_result is returned for testing purposes. "
          iv_description = 'Security group example'
          iv_groupname = iv_security_group_name
          iv_vpcid = iv_vpc_id ).
        MESSAGE 'Security group created.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateSecurityGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateVpc`
<a name="ec2_CreateVpc_sap-abap_1_topic"></a>

次の例は、`CreateVpc` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    " iv_cidr_block = '10.0.0.0/16'
    TRY.
        oo_result = lo_ec2->createvpc( iv_cidrblock = iv_cidr_block ).             " oo_result is returned for testing purposes. "
        DATA(lv_vpc_id) = oo_result->get_vpc( )->get_vpcid( ).
        MESSAGE 'Created VPC.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateVpc](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateVpcEndpoint`
<a name="ec2_CreateVpcEndpoint_sap-abap_1_topic"></a>

次の例は、`CreateVpcEndpoint` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    " iv_vpc_id = 'vpc-abc123'
    " iv_service_name = 'com.amazonaws.region.service'
    TRY.
        oo_result = lo_ec2->createvpcendpoint(             " oo_result is returned for testing purposes. "
          iv_vpcid = iv_vpc_id
          iv_servicename = iv_service_name
          it_routetableids = it_route_table_ids ).
        DATA(lv_vpc_endpoint_id) = oo_result->get_vpcendpoint( )->get_vpcendpointid( ).
        MESSAGE 'Created VPC endpoint.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateVpcEndpoint](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_sap-abap_1_topic"></a>

次の例は、`DeleteKeyPair` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ec2->deletekeypair( iv_keyname = iv_key_name ).
        MESSAGE 'Amazon EC2 key pair deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteKeyPair](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_sap-abap_1_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ec2->deletesecuritygroup( iv_groupid = iv_security_group_id ).
        MESSAGE 'Security group deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteSecurityGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteVpc`
<a name="ec2_DeleteVpc_sap-abap_1_topic"></a>

次の例は、`DeleteVpc` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ec2->deletevpc( iv_vpcid = iv_vpc_id ).
        MESSAGE 'Deleted VPC.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteVpc](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteVpcEndpoints`
<a name="ec2_DeleteVpcEndpoints_sap-abap_1_topic"></a>

次の例は、`DeleteVpcEndpoints` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ec2->deletevpcendpoints( it_vpcendpointids = it_vpc_endpoint_ids ).
        MESSAGE 'Deleted VPC endpoint(s).' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteVpcEndpoints](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeAddresses`
<a name="ec2_DescribeAddresses_sap-abap_1_topic"></a>

次の例は、`DescribeAddresses` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->describeaddresses( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_addresses) = oo_result->get_addresses( ).
        MESSAGE 'Retrieved information about Elastic IP addresses.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeAddresses](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeAvailabilityZones`
<a name="ec2_DescribeAvailabilityZones_sap-abap_1_topic"></a>

次のコード例は、`DescribeAvailabilityZones` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->describeavailabilityzones( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_zones) = oo_result->get_availabilityzones( ).
        MESSAGE 'Retrieved information about Availability Zones.' TYPE 'I'.

      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeAvailabilityZones](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeImages`
<a name="ec2_DescribeImages_sap-abap_1_topic"></a>

次の例は、`DescribeImages` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->describeimages( it_imageids = it_image_ids ).             " oo_result is returned for testing purposes. "
        DATA(lt_images) = oo_result->get_images( ).
        MESSAGE 'Retrieved information about Amazon Machine Images (AMIs).' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeImages](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_sap-abap_1_topic"></a>

次の例は、`DescribeInstanceTypes` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    " Create filters for architecture and instance type patterns
    " iv_architecture = 'x86_64'
    DATA lt_filters TYPE /aws1/cl_ec2filter=>tt_filterlist.
    APPEND NEW /aws1/cl_ec2filter(
      iv_name = 'processor-info.supported-architecture'
      it_values = VALUE /aws1/cl_ec2valuestringlist_w=>tt_valuestringlist(
        ( NEW /aws1/cl_ec2valuestringlist_w( iv_architecture ) )
      )
    ) TO lt_filters.
    " Filter for instance type patterns like '*.micro', '*.small'
    APPEND NEW /aws1/cl_ec2filter(
      iv_name = 'instance-type'
      it_values = VALUE /aws1/cl_ec2valuestringlist_w=>tt_valuestringlist(
        ( NEW /aws1/cl_ec2valuestringlist_w( '*.micro' ) )
        ( NEW /aws1/cl_ec2valuestringlist_w( '*.small' ) )
      )
    ) TO lt_filters.

    TRY.
        oo_result = lo_ec2->describeinstancetypes( it_filters = lt_filters ).             " oo_result is returned for testing purposes. "
        DATA(lt_instance_types) = oo_result->get_instancetypes( ).
        MESSAGE 'Retrieved information about EC2 instance types.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeInstanceTypes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeInstances`
<a name="ec2_DescribeInstances_sap-abap_1_topic"></a>

次の例は、`DescribeInstances` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->describeinstances( ).                        " oo_result is returned for testing purposes. "

        " Retrieving details of EC2 instances. "
        DATA: lv_istance_id    TYPE /aws1/ec2string,
              lv_status        TYPE /aws1/ec2instancestatename,
              lv_instance_type TYPE /aws1/ec2instancetype,
              lv_image_id      TYPE /aws1/ec2string.
        LOOP AT oo_result->get_reservations( ) INTO DATA(lo_reservation).
          LOOP AT lo_reservation->get_instances( ) INTO DATA(lo_instance).
            lv_istance_id = lo_instance->get_instanceid( ).
            lv_status = lo_instance->get_state( )->get_name( ).
            lv_instance_type = lo_instance->get_instancetype( ).
            lv_image_id = lo_instance->get_imageid( ).
          ENDLOOP.
        ENDLOOP.
        MESSAGE 'Retrieved information about EC2 instances.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_sap-abap_1_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->describekeypairs( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_key_pairs) = oo_result->get_keypairs( ).
        MESSAGE 'Retrieved information about key pairs.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeKeyPairs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeRegions`
<a name="ec2_DescribeRegions_sap-abap_1_topic"></a>

次のコード例は、`DescribeRegions` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ec2->describeregions( ).                        " oo_result is returned for testing purposes. "
        DATA(lt_regions) = oo_result->get_regions( ).
        MESSAGE 'Retrieved information about Regions.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeRegions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeRouteTables`
<a name="ec2_DescribeRouteTables_sap-abap_1_topic"></a>

次の例は、`DescribeRouteTables` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    " Create filter for VPC ID
    " iv_vpc_id = 'vpc-abc123'
    DATA lt_filters TYPE /aws1/cl_ec2filter=>tt_filterlist.
    APPEND NEW /aws1/cl_ec2filter(
      iv_name = 'vpc-id'
      it_values = VALUE /aws1/cl_ec2valuestringlist_w=>tt_valuestringlist(
        ( NEW /aws1/cl_ec2valuestringlist_w( iv_vpc_id ) )
      )
    ) TO lt_filters.

    TRY.
        oo_result = lo_ec2->describeroutetables( it_filters = lt_filters ).             " oo_result is returned for testing purposes. "
        DATA(lt_route_tables) = oo_result->get_routetables( ).
        MESSAGE 'Retrieved information about route tables.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeRouteTables](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_sap-abap_1_topic"></a>

次の例は、`DescribeSecurityGroups` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA lt_group_ids TYPE /aws1/cl_ec2groupidstrlist_w=>tt_groupidstringlist.
        APPEND NEW /aws1/cl_ec2groupidstrlist_w( iv_value = iv_group_id ) TO lt_group_ids.
        oo_result = lo_ec2->describesecuritygroups( it_groupids = lt_group_ids ).         " oo_result is returned for testing purposes. "
        DATA(lt_security_groups) = oo_result->get_securitygroups( ).
        MESSAGE 'Retrieved information about security groups.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeSecurityGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `MonitorInstances`
<a name="ec2_MonitorInstances_sap-abap_1_topic"></a>

次のコード例は、`MonitorInstances` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to monitor the instance without actually making the request. "
        lo_ec2->monitorinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to monitor this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to enable detailed monitoring completed.' TYPE 'I'.
          " DryRun is set to false to enable detailed monitoring. "
          lo_ec2->monitorinstances(
            it_instanceids = lt_instance_ids
            iv_dryrun = abap_false ).
          MESSAGE 'Detailed monitoring enabled.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to monitor this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to enable detailed monitoring failed. User does not have the permissions to monitor the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[MonitorInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RebootInstances`
<a name="ec2_RebootInstances_sap-abap_1_topic"></a>

次のコード例は、`RebootInstances` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to reboot the instance without actually making the request. "
        lo_ec2->rebootinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to reboot this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to reboot instance completed.' TYPE 'I'.
          " DryRun is set to false to make a reboot request. "
          lo_ec2->rebootinstances(
             it_instanceids = lt_instance_ids
             iv_dryrun = abap_false ).
          MESSAGE 'Instance rebooted.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to reboot this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to reboot instance failed. User does not have permissions to reboot the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[RebootInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_sap-abap_1_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ec2->releaseaddress( iv_allocationid = iv_allocation_id ).
        MESSAGE 'Elastic IP address released.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ReleaseAddress](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RunInstances`
<a name="ec2_RunInstances_sap-abap_1_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    " Create tags for resource created during instance launch. "
    DATA lt_tagspecifications TYPE /aws1/cl_ec2tagspecification=>tt_tagspecificationlist.
    DATA ls_tagspecifications LIKE LINE OF lt_tagspecifications.
    ls_tagspecifications = NEW /aws1/cl_ec2tagspecification(
      iv_resourcetype = 'instance'
      it_tags = VALUE /aws1/cl_ec2tag=>tt_taglist(
        ( NEW /aws1/cl_ec2tag( iv_key = 'Name' iv_value = iv_tag_value ) )
      ) ).
    APPEND ls_tagspecifications TO lt_tagspecifications.

    TRY.
        " Create/launch Amazon Elastic Compute Cloud (Amazon EC2) instance. "
        oo_result = lo_ec2->runinstances(                           " oo_result is returned for testing purposes. "
          iv_imageid = iv_ami_id
          iv_instancetype = 't3.micro'
          iv_maxcount = 1
          iv_mincount = 1
          it_tagspecifications = lt_tagspecifications
          iv_subnetid = iv_subnet_id ).
        MESSAGE 'EC2 instance created.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[RunInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartInstances`
<a name="ec2_StartInstances_sap-abap_1_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to start the instance without actually making the request. "
        lo_ec2->startinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to start this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to start instance completed.' TYPE 'I'.
          " DryRun is set to false to start instance. "
          oo_result = lo_ec2->startinstances(           " oo_result is returned for testing purposes. "
            it_instanceids = lt_instance_ids
            iv_dryrun = abap_false ).
          MESSAGE 'Successfully started the EC2 instance.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to start this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to start instance failed. User does not have permissions to start the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StartInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StopInstances`
<a name="ec2_StopInstances_sap-abap_1_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ec2#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_instance_ids TYPE /aws1/cl_ec2instidstringlist_w=>tt_instanceidstringlist.
    APPEND NEW /aws1/cl_ec2instidstringlist_w( iv_value = iv_instance_id ) TO lt_instance_ids.

    "Perform dry run"
    TRY.
        " DryRun is set to true. This checks for the required permissions to stop the instance without actually making the request. "
        lo_ec2->stopinstances(
          it_instanceids = lt_instance_ids
          iv_dryrun = abap_true ).
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        " If the error code returned is `DryRunOperation`, then you have the required permissions to stop this instance. "
        IF lo_exception->av_err_code = 'DryRunOperation'.
          MESSAGE 'Dry run to stop instance completed.' TYPE 'I'.
          " DryRun is set to false to stop instance. "
          oo_result = lo_ec2->stopinstances(           " oo_result is returned for testing purposes. "
            it_instanceids = lt_instance_ids
            iv_dryrun = abap_false ).
          MESSAGE 'Successfully stopped the EC2 instance.' TYPE 'I'.
          " If the error code returned is `UnauthorizedOperation`, then you don't have the required permissions to stop this instance. "
        ELSEIF lo_exception->av_err_code = 'UnauthorizedOperation'.
          MESSAGE 'Dry run to stop instance failed. User does not have permissions to stop the instance.' TYPE 'E'.
        ELSE.
          DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
          MESSAGE lv_error TYPE 'E'.
        ENDIF.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StopInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon ECR の例
<a name="sap-abap_1_ecr_code_examples"></a>

次のコード例は、Amazon ECR で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateRepository`
<a name="ecr_CreateRepository_sap-abap_1_topic"></a>

次の例は、`CreateRepository` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_repository_name = 'my-repository'
        oo_result = lo_ecr->createrepository(
          iv_repositoryname = iv_repository_name ).
        DATA(lv_repository_uri) = oo_result->get_repository( )->get_repositoryuri( ).
        MESSAGE |Repository created with URI: { lv_repository_uri }| TYPE 'I'.
      CATCH /aws1/cx_ecrrepositoryalrexex.
        " If repository already exists, retrieve it
        DATA lt_repo_names TYPE /aws1/cl_ecrrepositorynamels00=>tt_repositorynamelist.
        APPEND NEW /aws1/cl_ecrrepositorynamels00( iv_value = iv_repository_name ) TO lt_repo_names.
        DATA(lo_describe_result) = lo_ecr->describerepositories( it_repositorynames = lt_repo_names ).
        DATA(lt_repos) = lo_describe_result->get_repositories( ).
        IF lines( lt_repos ) > 0.
          READ TABLE lt_repos INDEX 1 INTO DATA(lo_repo).
          oo_result = NEW /aws1/cl_ecrcrerepositoryrsp( io_repository = lo_repo ).
          MESSAGE |Repository { iv_repository_name } already exists.| TYPE 'I'.
        ENDIF.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateRepository](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteRepository`
<a name="ecr_DeleteRepository_sap-abap_1_topic"></a>

次の例は、`DeleteRepository` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_repository_name = 'my-repository'
        lo_ecr->deleterepository(
          iv_repositoryname = iv_repository_name
          iv_force = abap_true ).
        MESSAGE |Repository { iv_repository_name } deleted.| TYPE 'I'.
      CATCH /aws1/cx_ecrrepositorynotfndex.
        MESSAGE 'Repository not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteRepository](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeImages`
<a name="ecr_DescribeImages_sap-abap_1_topic"></a>

次の例は、`DescribeImages` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_repository_name = 'my-repository'
        " it_image_ids = VALUE #( ( NEW /aws1/cl_ecrimageidentifier( iv_imagetag = 'latest' ) ) )
        IF it_image_ids IS NOT INITIAL.
          oo_result = lo_ecr->describeimages(
            iv_repositoryname = iv_repository_name
            it_imageids = it_image_ids ).
        ELSE.
          oo_result = lo_ecr->describeimages(
            iv_repositoryname = iv_repository_name ).
        ENDIF.
        DATA(lt_image_details) = oo_result->get_imagedetails( ).
        MESSAGE |Found { lines( lt_image_details ) } images in repository.| TYPE 'I'.
      CATCH /aws1/cx_ecrrepositorynotfndex.
        MESSAGE 'Repository not found.' TYPE 'I'.
      CATCH /aws1/cx_ecrimagenotfoundex.
        MESSAGE 'Image not found.' TYPE 'I'.
      CATCH /aws1/cx_ecrinvalidparameterex.
        MESSAGE 'Invalid parameter provided.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeImages](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeRepositories`
<a name="ecr_DescribeRepositories_sap-abap_1_topic"></a>

次の例は、`DescribeRepositories` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " it_repository_names = VALUE #( ( NEW /aws1/cl_ecrrepositorynamels00( iv_value = 'my-repository' ) ) )
        oo_result = lo_ecr->describerepositories(
          it_repositorynames = it_repository_names ).
        DATA(lt_repositories) = oo_result->get_repositories( ).
        MESSAGE |Found { lines( lt_repositories ) } repositories.| TYPE 'I'.
      CATCH /aws1/cx_ecrrepositorynotfndex.
        MESSAGE 'Repository not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeRepositories](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetAuthorizationToken`
<a name="ecr_GetAuthorizationToken_sap-abap_1_topic"></a>

次の例は、`GetAuthorizationToken` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ecr->getauthorizationtoken( ).
        DATA(lt_auth_data) = oo_result->get_authorizationdata( ).
        IF lines( lt_auth_data ) > 0.
          READ TABLE lt_auth_data INDEX 1 INTO DATA(lo_auth_data).
          DATA(lv_token) = lo_auth_data->get_authorizationtoken( ).
          MESSAGE 'Authorization token retrieved.' TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_ecrserverexception.
        MESSAGE 'Server exception occurred.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetAuthorizationToken](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetRepositoryPolicy`
<a name="ecr_GetRepositoryPolicy_sap-abap_1_topic"></a>

次の例は、`GetRepositoryPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_repository_name = 'my-repository'
        oo_result = lo_ecr->getrepositorypolicy(
          iv_repositoryname = iv_repository_name ).
        DATA(lv_policy_text) = oo_result->get_policytext( ).
        MESSAGE 'Repository policy retrieved.' TYPE 'I'.
      CATCH /aws1/cx_ecrrepositorynotfndex.
        MESSAGE 'Repository not found.' TYPE 'I'.
      CATCH /aws1/cx_ecrrepositoryplynot00.
        MESSAGE 'Repository policy not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetRepositoryPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutLifeCyclePolicy`
<a name="ecr_PutLifeCyclePolicy_sap-abap_1_topic"></a>

次の例は、`PutLifeCyclePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_repository_name = 'my-repository'
        " iv_lifecycle_policy_text = '{"rules":[{"rulePriority":1,"description":"Expire images older than 14 days",...}]}'
        lo_ecr->putlifecyclepolicy(
          iv_repositoryname = iv_repository_name
          iv_lifecyclepolicytext = iv_lifecycle_policy_text ).
        MESSAGE |Lifecycle policy set for repository { iv_repository_name }.| TYPE 'I'.
      CATCH /aws1/cx_ecrrepositorynotfndex.
        MESSAGE 'Repository not found.' TYPE 'I'.
      CATCH /aws1/cx_ecrvalidationex.
        MESSAGE 'Invalid lifecycle policy format.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutLifeCyclePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SetRepositoryPolicy`
<a name="ecr_SetRepositoryPolicy_sap-abap_1_topic"></a>

次の例は、`SetRepositoryPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ecr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_repository_name = 'my-repository'
        " iv_policy_text = '{"Version":"2012-10-17",		 	 	 "Statement":[...]}'
        lo_ecr->setrepositorypolicy(
          iv_repositoryname = iv_repository_name
          iv_policytext = iv_policy_text ).
        MESSAGE |Policy set for repository { iv_repository_name }.| TYPE 'I'.
      CATCH /aws1/cx_ecrrepositorynotfndex.
        MESSAGE 'Repository not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[SetRepositoryPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon EMR の例
<a name="sap-abap_1_emr_code_examples"></a>

次のコード例は、Amazon EMR で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AddJobFlowSteps`
<a name="emr_AddJobFlowSteps_sap-abap_1_topic"></a>

次の例は、`AddJobFlowSteps` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/emr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Build args list for Spark submit
        DATA lt_args TYPE /aws1/cl_emrxmlstringlist_w=>tt_xmlstringlist.
        APPEND NEW /aws1/cl_emrxmlstringlist_w( 'spark-submit' ) TO lt_args.
        APPEND NEW /aws1/cl_emrxmlstringlist_w( '--deploy-mode' ) TO lt_args.
        APPEND NEW /aws1/cl_emrxmlstringlist_w( 'cluster' ) TO lt_args.
        APPEND NEW /aws1/cl_emrxmlstringlist_w( iv_script_uri ) TO lt_args.
        APPEND LINES OF it_script_args TO lt_args.

        " Create step configuration
        DATA(lo_hadoop_jar_step) = NEW /aws1/cl_emrhadoopjarstepcfg(
          iv_jar = 'command-runner.jar'
          it_args = lt_args
        ).

        DATA(lo_step_config) = NEW /aws1/cl_emrstepconfig(
          iv_name = iv_name
          iv_actiononfailure = 'CONTINUE'
          io_hadoopjarstep = lo_hadoop_jar_step
        ).

        DATA lt_steps TYPE /aws1/cl_emrstepconfig=>tt_stepconfiglist.
        APPEND lo_step_config TO lt_steps.

        DATA(lo_result) = lo_emr->addjobflowsteps(
          iv_jobflowid = iv_cluster_id
          it_steps = lt_steps
        ).

        " Get first step ID
        DATA(lt_step_ids) = lo_result->get_stepids( ).
        READ TABLE lt_step_ids INDEX 1 INTO DATA(lo_step_id_obj).
        IF sy-subrc = 0.
          ov_step_id = lo_step_id_obj->get_value( ).
          MESSAGE |Step added with ID { ov_step_id }| TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_emrinternalservererr INTO DATA(lo_internal_error).
        DATA(lv_error) = lo_internal_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[AddJobFlowSteps](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeCluster`
<a name="emr_DescribeCluster_sap-abap_1_topic"></a>

次の例は、`DescribeCluster` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/emr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_emr->describecluster(
          iv_clusterid = iv_cluster_id
        ).
        DATA(lo_cluster) = oo_result->get_cluster( ).
        DATA(lv_cluster_name) = lo_cluster->get_name( ).
        MESSAGE |Retrieved cluster information for { lv_cluster_name }| TYPE 'I'.
      CATCH /aws1/cx_emrinternalserverex INTO DATA(lo_internal_error).
        DATA(lv_error) = lo_internal_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
      CATCH /aws1/cx_emrinvalidrequestex INTO DATA(lo_invalid_error).
        lv_error = lo_invalid_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeCluster](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeStep`
<a name="emr_DescribeStep_sap-abap_1_topic"></a>

次の例は、`DescribeStep` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/emr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_emr->describestep(
          iv_clusterid = iv_cluster_id
          iv_stepid = iv_step_id
        ).
        DATA(lo_step) = oo_result->get_step( ).
        DATA(lv_step_name) = lo_step->get_name( ).
        MESSAGE |Retrieved step information for { lv_step_name }| TYPE 'I'.
      CATCH /aws1/cx_emrinternalserverex INTO DATA(lo_internal_error).
        DATA(lv_error) = lo_internal_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
      CATCH /aws1/cx_emrinvalidrequestex INTO DATA(lo_invalid_error).
        lv_error = lo_invalid_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeStep](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListSteps`
<a name="emr_ListSteps_sap-abap_1_topic"></a>

次の例は、`ListSteps` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/emr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_emr->liststeps(
          iv_clusterid = iv_cluster_id
        ).
        DATA(lt_steps) = oo_result->get_steps( ).
        DATA(lv_step_count) = lines( lt_steps ).
        MESSAGE |Retrieved { lv_step_count } steps for cluster| TYPE 'I'.
      CATCH /aws1/cx_emrinternalserverex INTO DATA(lo_internal_error).
        DATA(lv_error) = lo_internal_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
      CATCH /aws1/cx_emrinvalidrequestex INTO DATA(lo_invalid_error).
        lv_error = lo_invalid_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListSteps](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RunJobFlow`
<a name="emr_RunJobFlow_sap-abap_1_topic"></a>

次の例は、`RunJobFlow` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/emr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create instances configuration
        DATA(lo_instances) = NEW /aws1/cl_emrjobflowinstsconfig(
          iv_masterinstancetype = 'm5.xlarge'
          iv_slaveinstancetype = 'm5.xlarge'
          iv_instancecount = 3
          iv_keepjobflowalivewhennos00 = iv_keep_alive
          iv_emrmanagedmastersecgroup = iv_primary_sec_grp
          iv_emrmanagedslavesecgroup = iv_secondary_sec_grp
        ).

        DATA(lo_result) = lo_emr->runjobflow(
          iv_name = iv_name
          iv_loguri = iv_log_uri
          iv_releaselabel = 'emr-5.30.1'
          io_instances = lo_instances
          it_steps = it_steps
          it_applications = it_applications
          iv_jobflowrole = iv_job_flow_role
          iv_servicerole = iv_service_role
          iv_ebsrootvolumesize = 10
          iv_visibletoallusers = abap_true
        ).

        ov_cluster_id = lo_result->get_jobflowid( ).
        MESSAGE 'EMR cluster created successfully.' TYPE 'I'.
      CATCH /aws1/cx_emrinternalservererr INTO DATA(lo_internal_error).
        DATA(lv_error) = lo_internal_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
      CATCH /aws1/cx_emrclientexc INTO DATA(lo_client_error).
        lv_error = lo_client_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[RunJobFlow](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `TerminateJobFlows`
<a name="emr_TerminateJobFlows_sap-abap_1_topic"></a>

次の例は、`TerminateJobFlows` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/emr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA lt_cluster_ids TYPE /aws1/cl_emrxmlstringlist_w=>tt_xmlstringlist.
        APPEND NEW /aws1/cl_emrxmlstringlist_w( iv_cluster_id ) TO lt_cluster_ids.

        lo_emr->terminatejobflows(
          it_jobflowids = lt_cluster_ids
        ).
        MESSAGE 'EMR cluster terminated successfully.' TYPE 'I'.
      CATCH /aws1/cx_emrinternalservererr INTO DATA(lo_internal_error).
        DATA(lv_error) = lo_internal_error->if_message~get_text( ).
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[TerminateJobFlows](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した EventBridge スケジューラの例
<a name="sap-abap_1_scheduler_code_examples"></a>

次のコード例は、EventBridge スケジューラで AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateSchedule`
<a name="scheduler_CreateSchedule_sap-abap_1_topic"></a>

次の例は、`CreateSchedule` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/scd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Constants for time calculations
        DATA lv_start_date TYPE /aws1/scdstartdate.
        DATA lv_end_date TYPE /aws1/scdenddate.
        DATA lv_start_timestamp TYPE timestamp.
        DATA lv_end_timestamp TYPE timestamp.
        DATA lv_hours_to_run TYPE i VALUE 1.

        " Get current timestamp
        GET TIME STAMP FIELD lv_start_timestamp.
        
        " Add 1 hour to the current timestamp using CL_ABAP_TSTMP
        lv_end_timestamp = cl_abap_tstmp=>add(
          tstmp = lv_start_timestamp
          secs = lv_hours_to_run * 3600 ).

        " Convert timestamps to decimal format for AWS API
        lv_start_date = lv_start_timestamp.
        lv_end_date = lv_end_timestamp.

        " Prepare flexible time window configuration
        DATA lo_flexible_time_window TYPE REF TO /aws1/cl_scdflexibletimewindow.
        IF iv_use_flexible_time_win = abap_true.
          " iv_use_flexible_time_win = ABAP_TRUE
          " Example: Set MaximumWindowInMinutes to 10 for flexible window
          lo_flexible_time_window = NEW /aws1/cl_scdflexibletimewindow(
            iv_mode = 'FLEXIBLE'
            iv_maximumwindowinminutes = 10 ).
        ELSE.
          lo_flexible_time_window = NEW /aws1/cl_scdflexibletimewindow(
            iv_mode = 'OFF' ).
        ENDIF.

        " Prepare target configuration
        " Example iv_target_arn = 'arn:aws:sqs:us-east-1:123456789012:my-queue'
        " Example iv_role_arn = 'arn:aws:iam::123456789012:role/SchedulerRole'
        " Example iv_input = '{"message": "Hello from EventBridge Scheduler"}'
        DATA(lo_target) = NEW /aws1/cl_scdtarget(
          iv_arn = iv_target_arn
          iv_rolearn = iv_role_arn
          iv_input = iv_input ).

        " Set action after completion if needed
        DATA lv_action_after_completion TYPE /aws1/scdactionaftercompletion.
        IF iv_delete_after_completion = abap_true.
          " iv_delete_after_completion = ABAP_TRUE
          lv_action_after_completion = 'DELETE'.
        ELSE.
          lv_action_after_completion = 'NONE'.
        ENDIF.

        " Create the schedule
        " Example iv_name = 'my-schedule'
        " Example iv_schedule_expression = 'rate(15 minutes)'
        " Example iv_schedule_group_name = 'my-schedule-group'
        DATA(lo_result) = lo_scd->createschedule(
          iv_name = iv_name
          iv_scheduleexpression = iv_schedule_expression
          iv_groupname = iv_schedule_group_name
          io_target = lo_target
          io_flexibletimewindow = lo_flexible_time_window
          iv_startdate = lv_start_date
          iv_enddate = lv_end_date
          iv_actionaftercompletion = lv_action_after_completion ).

        ov_schedule_arn = lo_result->get_schedulearn( ).
        MESSAGE 'Schedule created successfully.' TYPE 'I'.

      CATCH /aws1/cx_scdconflictexception INTO DATA(lo_conflict_ex).
        DATA(lv_error) = |Conflict creating schedule: { lo_conflict_ex->if_message~get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_ex).
        DATA(lv_generic_error) = |Error creating schedule: { lo_generic_ex->if_message~get_text( ) }|.
        MESSAGE lv_generic_error TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [CreateSchedule](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateScheduleGroup`
<a name="scheduler_CreateScheduleGroup_sap-abap_1_topic"></a>

次の例は、`CreateScheduleGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/scd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example iv_name = 'my-schedule-group'
        DATA(lo_result) = lo_scd->createschedulegroup(
          iv_name = iv_name ).

        ov_schedule_group_arn = lo_result->get_schedulegrouparn( ).
        MESSAGE 'Schedule group created successfully.' TYPE 'I'.

      CATCH /aws1/cx_scdconflictexception INTO DATA(lo_conflict_ex).
        DATA(lv_error) = |Conflict creating schedule group: { lo_conflict_ex->if_message~get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_ex).
        DATA(lv_generic_error) = |Error creating schedule group: { lo_generic_ex->if_message~get_text( ) }|.
        MESSAGE lv_generic_error TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateScheduleGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteSchedule`
<a name="scheduler_DeleteSchedule_sap-abap_1_topic"></a>

次の例は、`DeleteSchedule` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/scd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example iv_name = 'my-schedule'
        " Example iv_schedule_group_name = 'my-schedule-group'
        lo_scd->deleteschedule(
          iv_name = iv_name
          iv_groupname = iv_schedule_group_name ).
        MESSAGE 'Schedule deleted successfully.' TYPE 'I'.

      CATCH /aws1/cx_scdresourcenotfoundex INTO DATA(lo_not_found_ex).
        DATA(lv_error) = |Schedule not found: { lo_not_found_ex->if_message~get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_ex).
        DATA(lv_generic_error) = |Error deleting schedule: { lo_generic_ex->if_message~get_text( ) }|.
        MESSAGE lv_generic_error TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteSchedule](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteScheduleGroup`
<a name="scheduler_DeleteScheduleGroup_sap-abap_1_topic"></a>

次の例は、`DeleteScheduleGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/scd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example iv_name = 'my-schedule-group'
        lo_scd->deleteschedulegroup(
          iv_name = iv_name ).
        MESSAGE 'Schedule group deleted successfully.' TYPE 'I'.

      CATCH /aws1/cx_scdresourcenotfoundex INTO DATA(lo_not_found_ex).
        DATA(lv_error) = |Schedule group not found: { lo_not_found_ex->if_message~get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_generic_ex).
        DATA(lv_generic_error) = |Error deleting schedule group: { lo_generic_ex->if_message~get_text( ) }|.
        MESSAGE lv_generic_error TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteScheduleGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# AWS Glue SDK for SAP ABAP を使用した例
<a name="sap-abap_1_glue_code_examples"></a>

次のコード例は、 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_sap-abap_1_topic"></a>

次の例は、`CreateCrawler` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_crawler_name = 'my-crawler'
        " iv_role_arn = 'arn:aws:iam::123456789012:role/AWSGlueServiceRole-Test'
        " iv_database_name = 'my-database'
        " iv_table_prefix = 'test_'
        " iv_s3_target = 's3://example-bucket/data/'

        DATA(lt_s3_targets) = VALUE /aws1/cl_glus3target=>tt_s3targetlist(
          ( NEW /aws1/cl_glus3target( iv_path = iv_s3_target ) ) ).

        DATA(lo_targets) = NEW /aws1/cl_glucrawlertargets(
          it_s3targets = lt_s3_targets ).

        lo_glu->createcrawler(
          iv_name = iv_crawler_name
          iv_role = iv_role_arn
          iv_databasename = iv_database_name
          iv_tableprefix = iv_table_prefix
          io_targets = lo_targets ).
        MESSAGE 'Crawler created successfully.' TYPE 'I'.
      CATCH /aws1/cx_glualreadyexistsex.
        MESSAGE 'Crawler already exists.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
      CATCH /aws1/cx_gluresrcnumlmtexcdex INTO DATA(lo_limit_ex).
        DATA(lv_limit_error) = lo_limit_ex->if_message~get_longtext( ).
        MESSAGE lv_limit_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateCrawler](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_sap-abap_1_topic"></a>

次の例は、`CreateJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_job_name = 'my-etl-job'
        " iv_description = 'ETL job for data transformation'
        " iv_role_arn = 'arn:aws:iam::123456789012:role/AWSGlueServiceRole-Test'
        " iv_script_location = 's3://example-bucket/scripts/my-script.py'

        DATA(lo_command) = NEW /aws1/cl_glujobcommand(
          iv_name = 'glueetl'
          iv_scriptlocation = iv_script_location
          iv_pythonversion = '3' ).

        lo_glu->createjob(
          iv_name = iv_job_name
          iv_description = iv_description
          iv_role = iv_role_arn
          io_command = lo_command
          iv_glueversion = '3.0' ).
        MESSAGE 'Job created successfully.' TYPE 'I'.
      CATCH /aws1/cx_glualreadyexistsex.
        MESSAGE 'Job already exists.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
      CATCH /aws1/cx_gluresrcnumlmtexcdex INTO DATA(lo_limit_ex).
        DATA(lv_limit_error) = lo_limit_ex->if_message~get_longtext( ).
        MESSAGE lv_limit_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteCrawler`
<a name="glue_DeleteCrawler_sap-abap_1_topic"></a>

次の例は、`DeleteCrawler` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_crawler_name = 'my-crawler'
        lo_glu->deletecrawler( iv_name = iv_crawler_name ).
        MESSAGE 'Crawler deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_glucrawlerrunningex.
        MESSAGE 'Crawler is currently running.' TYPE 'E'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Crawler does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
      CATCH /aws1/cx_gluschdrtransingex.
        MESSAGE 'Scheduler is transitioning.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DeleteCrawler](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `DeleteDatabase`
<a name="glue_DeleteDatabase_sap-abap_1_topic"></a>

次の例は、`DeleteDatabase` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_database_name = 'my-database'
        lo_glu->deletedatabase( iv_name = iv_database_name ).
        MESSAGE 'Database deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Database does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DeleteDatabase](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `DeleteJob`
<a name="glue_DeleteJob_sap-abap_1_topic"></a>

次の例は、`DeleteJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_job_name = 'my-etl-job'
        lo_glu->deletejob( iv_jobname = iv_job_name ).
        MESSAGE 'Job deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_sap-abap_1_topic"></a>

次の例は、`DeleteTable` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_database_name = 'my-database'
        " iv_table_name = 'my-table'
        lo_glu->deletetable(
          iv_databasename = iv_database_name
          iv_name = iv_table_name ).
        MESSAGE 'Table deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Table or database does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_sap-abap_1_topic"></a>

次の例は、`GetCrawler` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_crawler_name = 'my-crawler'
        oo_result = lo_glu->getcrawler( iv_name = iv_crawler_name ).
        DATA(lo_crawler) = oo_result->get_crawler( ).
        MESSAGE 'Crawler information retrieved.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Crawler does not exist.' TYPE 'I'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[GetCrawler](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `GetDatabase`
<a name="glue_GetDatabase_sap-abap_1_topic"></a>

次の例は、`GetDatabase` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_database_name = 'my-database'
        oo_result = lo_glu->getdatabase( iv_name = iv_database_name ).
        DATA(lo_database) = oo_result->get_database( ).
        MESSAGE 'Database information retrieved.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Database does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[GetDatabase](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `GetJobRun`
<a name="glue_GetJobRun_sap-abap_1_topic"></a>

次の例は、`GetJobRun` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_job_name = 'my-etl-job'
        " iv_run_id = 'jr_abcd1234567890abcdef1234567890abcdef12345678'
        oo_result = lo_glu->getjobrun(
          iv_jobname = iv_job_name
          iv_runid = iv_run_id ).
        DATA(lo_job_run) = oo_result->get_jobrun( ).
        MESSAGE 'Job run information retrieved.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Job or job run does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[GetJobRun](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `GetJobRuns`
<a name="glue_GetJobRuns_sap-abap_1_topic"></a>

次の例は、`GetJobRuns` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_job_name = 'my-etl-job'
        oo_result = lo_glu->getjobruns( iv_jobname = iv_job_name ).
        DATA(lt_job_runs) = oo_result->get_jobruns( ).
        MESSAGE 'Job runs retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Job does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[GetJobRuns](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `GetTables`
<a name="glue_GetTables_sap-abap_1_topic"></a>

次の例は、`GetTables` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_database_name = 'my-database'
        oo_result = lo_glu->gettables( iv_databasename = iv_database_name ).
        DATA(lt_tables) = oo_result->get_tablelist( ).
        MESSAGE 'Tables retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Database does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[GetTables](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `ListJobs`
<a name="glue_ListJobs_sap-abap_1_topic"></a>

次の例は、`ListJobs` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_glu->listjobs( ).
        DATA(lt_job_names) = oo_result->get_jobnames( ).
        MESSAGE 'Job list retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'No jobs found.' TYPE 'I'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_sap-abap_1_topic"></a>

次の例は、`StartCrawler` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_crawler_name = 'my-crawler'
        lo_glu->startcrawler( iv_name = iv_crawler_name ).
        MESSAGE 'Crawler started successfully.' TYPE 'I'.
      CATCH /aws1/cx_glucrawlerrunningex.
        MESSAGE 'Crawler is already running.' TYPE 'I'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Crawler does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StartCrawler](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_sap-abap_1_topic"></a>

次の例は、`StartJobRun` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/glu#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_job_name = 'my-etl-job'
        " iv_input_database = 'my-database'
        " iv_input_table = 'my-table'
        " iv_output_bucket_url = 's3://example-output-bucket/'

        DATA lt_arguments TYPE /aws1/cl_glugenericmap_w=>tt_genericmap.
        lt_arguments = VALUE #(
          ( VALUE /aws1/cl_glugenericmap_w=>ts_genericmap_maprow(
            key = '--input_database'
            value = NEW /aws1/cl_glugenericmap_w( iv_value = iv_input_database ) ) )
          ( VALUE /aws1/cl_glugenericmap_w=>ts_genericmap_maprow(
            key = '--input_table'
            value = NEW /aws1/cl_glugenericmap_w( iv_value = iv_input_table ) ) )
          ( VALUE /aws1/cl_glugenericmap_w=>ts_genericmap_maprow(
            key = '--output_bucket_url'
            value = NEW /aws1/cl_glugenericmap_w( iv_value = iv_output_bucket_url ) ) ) ).

        DATA(oo_result) = lo_glu->startjobrun(
          iv_jobname = iv_job_name
          it_arguments = lt_arguments ).
        ov_job_run_id = oo_result->get_jobrunid( ).
        MESSAGE 'Job run started successfully.' TYPE 'I'.
      CATCH /aws1/cx_gluconcurrentrunsex00.
        MESSAGE 'Maximum concurrent runs exceeded.' TYPE 'E'.
      CATCH /aws1/cx_gluentitynotfoundex.
        MESSAGE 'Job does not exist.' TYPE 'E'.
      CATCH /aws1/cx_gluinvalidinputex INTO DATA(lo_invalid_ex).
        DATA(lv_invalid_error) = lo_invalid_ex->if_message~get_longtext( ).
        MESSAGE lv_invalid_error TYPE 'E'.
      CATCH /aws1/cx_gluinternalserviceex INTO DATA(lo_internal_ex).
        DATA(lv_internal_error) = lo_internal_ex->if_message~get_longtext( ).
        MESSAGE lv_internal_error TYPE 'E'.
      CATCH /aws1/cx_gluoperationtimeoutex INTO DATA(lo_timeout_ex).
        DATA(lv_timeout_error) = lo_timeout_ex->if_message~get_longtext( ).
        MESSAGE lv_timeout_error TYPE 'E'.
      CATCH /aws1/cx_gluresrcnumlmtexcdex INTO DATA(lo_limit_ex).
        DATA(lv_limit_error) = lo_limit_ex->if_message~get_longtext( ).
        MESSAGE lv_limit_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StartJobRun](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した HealthImaging の例
<a name="sap-abap_1_medical-imaging_code_examples"></a>

次のコード例は、HealthImaging で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CopyImageSet`
<a name="medical-imaging_CopyImageSet_sap-abap_1_topic"></a>

次の例は、`CopyImageSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_source_image_set_id = '1234567890123456789012345678901234567890'
        " iv_source_version_id = '1'
        " iv_destination_image_set_id = '1234567890123456789012345678901234567890' (optional)
        " iv_destination_version_id = '1' (optional)
        " iv_force = abap_false
        DATA(lo_source_info) = NEW /aws1/cl_migcpsrcimagesetinf00(
          iv_latestversionid = iv_source_version_id ).
        DATA(lo_copy_info) = NEW /aws1/cl_migcpimagesetinfmtion(
          io_sourceimageset = lo_source_info ).
        IF iv_destination_image_set_id IS NOT INITIAL AND
           iv_destination_version_id IS NOT INITIAL.
          DATA(lo_dest_info) = NEW /aws1/cl_migcopydstimageset(
            iv_imagesetid = iv_destination_image_set_id
            iv_latestversionid = iv_destination_version_id ).
          lo_copy_info = NEW /aws1/cl_migcpimagesetinfmtion(
            io_sourceimageset = lo_source_info
            io_destinationimageset = lo_dest_info ).
        ENDIF.
        oo_result = lo_mig->copyimageset(
          iv_datastoreid = iv_datastore_id
          iv_sourceimagesetid = iv_source_image_set_id
          io_copyimagesetinformation = lo_copy_info
          iv_force = iv_force ).
        DATA(lo_dest_props) = oo_result->get_dstimagesetproperties( ).
        DATA(lv_new_id) = lo_dest_props->get_imagesetid( ).
        MESSAGE |Image set copied with new ID: { lv_new_id }.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Image set not found.' TYPE 'I'.
      CATCH /aws1/cx_migservicequotaexcdex.
        MESSAGE 'Service quota exceeded.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[CopyImageSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `CreateDatastore`
<a name="medical-imaging_CreateDatastore_sap-abap_1_topic"></a>

次の例は、`CreateDatastore` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_name = 'my-datastore-name'
        oo_result = lo_mig->createdatastore( iv_datastorename = iv_datastore_name ).
        DATA(lv_datastore_id) = oo_result->get_datastoreid( ).
        MESSAGE 'Data store created.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict. Data store may already exist.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migservicequotaexcdex.
        MESSAGE 'Service quota exceeded.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateDatastore](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `DeleteDatastore`
<a name="medical-imaging_DeleteDatastore_sap-abap_1_topic"></a>

次の例は、`DeleteDatastore` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        oo_result = lo_mig->deletedatastore( iv_datastoreid = iv_datastore_id ).
        MESSAGE 'Data store deleted.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict. Data store may contain resources.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Data store not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteDatastore](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `DeleteImageSet`
<a name="medical-imaging_DeleteImageSet_sap-abap_1_topic"></a>

次の例は、`DeleteImageSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_image_set_id = '1234567890123456789012345678901234567890'
        oo_result = lo_mig->deleteimageset(
          iv_datastoreid = iv_datastore_id
          iv_imagesetid = iv_image_set_id ).
        MESSAGE 'Image set deleted.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Image set not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteImageSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `GetDICOMImportJob`
<a name="medical-imaging_GetDICOMImportJob_sap-abap_1_topic"></a>

次の例は、`GetDICOMImportJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_job_id = '12345678901234567890123456789012'
        oo_result = lo_mig->getdicomimportjob(
          iv_datastoreid = iv_datastore_id
          iv_jobid = iv_job_id ).
        DATA(lo_job_props) = oo_result->get_jobproperties( ).
        DATA(lv_job_status) = lo_job_props->get_jobstatus( ).
        MESSAGE |Job status: { lv_job_status }.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Job not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetDICOMImportJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `GetDatastore`
<a name="medical-imaging_GetDatastore_sap-abap_1_topic"></a>

次の例は、`GetDatastore` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        oo_result = lo_mig->getdatastore( iv_datastoreid = iv_datastore_id ).
        DATA(lo_properties) = oo_result->get_datastoreproperties( ).
        DATA(lv_name) = lo_properties->get_datastorename( ).
        DATA(lv_status) = lo_properties->get_datastorestatus( ).
        MESSAGE 'Data store properties retrieved.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Data store not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetDatastore](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `GetImageFrame`
<a name="medical-imaging_GetImageFrame_sap-abap_1_topic"></a>

次の例は、`GetImageFrame` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_image_set_id = '1234567890123456789012345678901234567890'
        " iv_image_frame_id = '1234567890123456789012345678901234567890'
        oo_result = lo_mig->getimageframe(
          iv_datastoreid = iv_datastore_id
          iv_imagesetid = iv_image_set_id
          io_imageframeinformation = NEW /aws1/cl_migimageframeinfmtion(
            iv_imageframeid = iv_image_frame_id ) ).
        DATA(lv_frame_blob) = oo_result->get_imageframeblob( ).
        MESSAGE 'Image frame retrieved.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Image frame not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetImageFrame](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `GetImageSet`
<a name="medical-imaging_GetImageSet_sap-abap_1_topic"></a>

次の例は、`GetImageSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_image_set_id = '1234567890123456789012345678901234567890'
        " iv_version_id = '1' (optional)
        IF iv_version_id IS NOT INITIAL.
          oo_result = lo_mig->getimageset(
            iv_datastoreid = iv_datastore_id
            iv_imagesetid = iv_image_set_id
            iv_versionid = iv_version_id ).
        ELSE.
          oo_result = lo_mig->getimageset(
            iv_datastoreid = iv_datastore_id
            iv_imagesetid = iv_image_set_id ).
        ENDIF.
        DATA(lv_state) = oo_result->get_imagesetstate( ).
        MESSAGE |Image set retrieved with state: { lv_state }.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Image set not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetImageSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `GetImageSetMetadata`
<a name="medical-imaging_GetImageSetMetadata_sap-abap_1_topic"></a>

次の例は、`GetImageSetMetadata` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_image_set_id = '1234567890123456789012345678901234567890'
        " iv_version_id = '1' (optional)
        IF iv_version_id IS NOT INITIAL.
          oo_result = lo_mig->getimagesetmetadata(
            iv_datastoreid = iv_datastore_id
            iv_imagesetid = iv_image_set_id
            iv_versionid = iv_version_id ).
        ELSE.
          oo_result = lo_mig->getimagesetmetadata(
            iv_datastoreid = iv_datastore_id
            iv_imagesetid = iv_image_set_id ).
        ENDIF.
        DATA(lv_metadata_blob) = oo_result->get_imagesetmetadatablob( ).
        MESSAGE 'Image set metadata retrieved.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Image set not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetImageSetMetadata](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `ListDICOMImportJobs`
<a name="medical-imaging_ListDICOMImportJobs_sap-abap_1_topic"></a>

次の例は、`ListDICOMImportJobs` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        oo_result = lo_mig->listdicomimportjobs( iv_datastoreid = iv_datastore_id ).
        DATA(lt_jobs) = oo_result->get_jobsummaries( ).
        DATA(lv_count) = lines( lt_jobs ).
        MESSAGE |Found { lv_count } DICOM import jobs.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListDICOMImportJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `ListDatastores`
<a name="medical-imaging_ListDatastores_sap-abap_1_topic"></a>

次の例は、`ListDatastores` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        oo_result = lo_mig->listdatastores( ).
        DATA(lt_datastores) = oo_result->get_datastoresummaries( ).
        DATA(lv_count) = lines( lt_datastores ).
        MESSAGE |Found { lv_count } data stores.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListDatastores](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `ListImageSetVersions`
<a name="medical-imaging_ListImageSetVersions_sap-abap_1_topic"></a>

次の例は、`ListImageSetVersions` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_image_set_id = '1234567890123456789012345678901234567890'
        oo_result = lo_mig->listimagesetversions(
          iv_datastoreid = iv_datastore_id
          iv_imagesetid = iv_image_set_id ).
        DATA(lt_versions) = oo_result->get_imagesetpropertieslist( ).
        DATA(lv_count) = lines( lt_versions ).
        MESSAGE |Found { lv_count } image set versions.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Image set not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListImageSetVersions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `ListTagsForResource`
<a name="medical-imaging_ListTagsForResource_sap-abap_1_topic"></a>

次の例は、`ListTagsForResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_resource_arn = 'arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012'
        oo_result = lo_mig->listtagsforresource( iv_resourcearn = iv_resource_arn ).
        DATA(lt_tags) = oo_result->get_tags( ).
        DATA(lv_count) = lines( lt_tags ).
        MESSAGE |Found { lv_count } tags for resource.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListTagsForResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `SearchImageSets`
<a name="medical-imaging_SearchImageSets_sap-abap_1_topic"></a>

次の例は、`SearchImageSets` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        oo_result = lo_mig->searchimagesets(
          iv_datastoreid = iv_datastore_id
          io_searchcriteria = io_search_criteria ).
        DATA(lt_imagesets) = oo_result->get_imagesetsmetadatasums( ).
        DATA(lv_count) = lines( lt_imagesets ).
        MESSAGE |Found { lv_count } image sets.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SearchImageSets](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `StartDICOMImportJob`
<a name="medical-imaging_StartDICOMImportJob_sap-abap_1_topic"></a>

次の例は、`StartDICOMImportJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_job_name = 'import-job-1'
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_role_arn = 'arn:aws:iam::123456789012:role/ImportJobRole'
        " iv_input_s3_uri = 's3://my-bucket/input/'
        " iv_output_s3_uri = 's3://my-bucket/output/'
        oo_result = lo_mig->startdicomimportjob(
          iv_jobname = iv_job_name
          iv_datastoreid = iv_datastore_id
          iv_dataaccessrolearn = iv_role_arn
          iv_inputs3uri = iv_input_s3_uri
          iv_outputs3uri = iv_output_s3_uri ).
        DATA(lv_job_id) = oo_result->get_jobid( ).
        MESSAGE |DICOM import job started with ID: { lv_job_id }.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'I'.
      CATCH /aws1/cx_migservicequotaexcdex.
        MESSAGE 'Service quota exceeded.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartDICOMImportJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `TagResource`
<a name="medical-imaging_TagResource_sap-abap_1_topic"></a>

次の例は、`TagResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_resource_arn = 'arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012'
        lo_mig->tagresource(
          iv_resourcearn = iv_resource_arn
          it_tags = it_tags ).
        MESSAGE 'Resource tagged successfully.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[TagResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `UntagResource`
<a name="medical-imaging_UntagResource_sap-abap_1_topic"></a>

次の例は、`UntagResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_resource_arn = 'arn:aws:medical-imaging:us-east-1:123456789012:datastore/12345678901234567890123456789012'
        lo_mig->untagresource(
          iv_resourcearn = iv_resource_arn
          it_tagkeys = it_tag_keys ).
        MESSAGE 'Resource untagged successfully.' TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [UntagResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

### `UpdateImageSetMetadata`
<a name="medical-imaging_UpdateImageSetMetadata_sap-abap_1_topic"></a>

次の例は、`UpdateImageSetMetadata` を使用する方法を説明しています。

**SDK for SAP ABAP**  

```
    TRY.
        " iv_datastore_id = '1234567890123456789012345678901234567890'
        " iv_image_set_id = '1234567890123456789012345678901234567890'
        " iv_latest_version_id = '1'
        " iv_force = abap_false
        oo_result = lo_mig->updateimagesetmetadata(
          iv_datastoreid = iv_datastore_id
          iv_imagesetid = iv_image_set_id
          iv_latestversionid = iv_latest_version_id
          io_updateimagesetmetupdates = io_metadata_updates
          iv_force = iv_force ).
        DATA(lv_new_version) = oo_result->get_latestversionid( ).
        MESSAGE |Image set metadata updated to version: { lv_new_version }.| TYPE 'I'.
      CATCH /aws1/cx_migaccessdeniedex.
        MESSAGE 'Access denied.' TYPE 'I'.
      CATCH /aws1/cx_migconflictexception.
        MESSAGE 'Conflict error.' TYPE 'I'.
      CATCH /aws1/cx_miginternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
      CATCH /aws1/cx_migresourcenotfoundex.
        MESSAGE 'Image set not found.' TYPE 'I'.
      CATCH /aws1/cx_migservicequotaexcdex.
        MESSAGE 'Service quota exceeded.' TYPE 'I'.
      CATCH /aws1/cx_migthrottlingex.
        MESSAGE 'Request throttled.' TYPE 'I'.
      CATCH /aws1/cx_migvalidationex.
        MESSAGE 'Validation error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateImageSetMetadata](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/mig#code-examples)での設定と実行の方法を確認してください。

# SDK for SAP ABAP を使用した HealthLake の例
<a name="sap-abap_1_healthlake_code_examples"></a>

次のコード例は、HealthLake で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateFHIRDatastore`
<a name="healthlake_CreateFHIRDatastore_sap-abap_1_topic"></a>

次の例は、`CreateFHIRDatastore` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_datastore_name = 'MyHealthLakeDataStore'
        oo_result = lo_hll->createfhirdatastore(
          iv_datastorename = iv_datastore_name
          iv_datastoretypeversion = 'R4'
        ).
        MESSAGE 'Data store created successfully.' TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllinternalserverex INTO DATA(lo_internal_ex).
        lv_error = |Internal server error: { lo_internal_ex->av_err_code }-{ lo_internal_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
      CATCH /aws1/cx_hllthrottlingex INTO DATA(lo_throttling_ex).
        lv_error = |Throttling error: { lo_throttling_ex->av_err_code }-{ lo_throttling_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_throttling_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateFHIRDatastore](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteFHIRDatastore`
<a name="healthlake_DeleteFHIRDatastore_sap-abap_1_topic"></a>

次の例は、`DeleteFHIRDatastore` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_datastore_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        oo_result = lo_hll->deletefhirdatastore(
          iv_datastoreid = iv_datastore_id
        ).
        MESSAGE 'Data store deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_hllaccessdeniedex INTO DATA(lo_access_ex).
        DATA(lv_error) = |Access denied: { lo_access_ex->av_err_code }-{ lo_access_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_access_ex.
      CATCH /aws1/cx_hllconflictexception INTO DATA(lo_conflict_ex).
        lv_error = |Conflict error: { lo_conflict_ex->av_err_code }-{ lo_conflict_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_conflict_ex.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        lv_error = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteFHIRDatastore](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeFHIRDatastore`
<a name="healthlake_DescribeFHIRDatastore_sap-abap_1_topic"></a>

次の例は、`DescribeFHIRDatastore` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_datastore_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        oo_result = lo_hll->describefhirdatastore(
          iv_datastoreid = iv_datastore_id
        ).
        DATA(lo_datastore_properties) = oo_result->get_datastoreproperties( ).
        IF lo_datastore_properties IS BOUND.
          DATA(lv_datastore_name) = lo_datastore_properties->get_datastorename( ).
          DATA(lv_datastore_status) = lo_datastore_properties->get_datastorestatus( ).
          MESSAGE 'Data store described successfully.' TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        DATA(lv_error) = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        lv_error = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeFHIRDatastore](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeFHIRExportJob`
<a name="healthlake_DescribeFHIRExportJob_sap-abap_1_topic"></a>

次の例は、`DescribeFHIRExportJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_datastore_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        " iv_job_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        oo_result = lo_hll->describefhirexportjob(
          iv_datastoreid = iv_datastore_id
          iv_jobid = iv_job_id
        ).
        DATA(lo_export_job_properties) = oo_result->get_exportjobproperties( ).
        IF lo_export_job_properties IS BOUND.
          DATA(lv_job_status) = lo_export_job_properties->get_jobstatus( ).
          MESSAGE |Export job status: { lv_job_status }.| TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        DATA(lv_error) = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        lv_error = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeFHIRExportJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeFHIRImportJob`
<a name="healthlake_DescribeFHIRImportJob_sap-abap_1_topic"></a>

次の例は、`DescribeFHIRImportJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_datastore_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        " iv_job_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        oo_result = lo_hll->describefhirimportjob(
          iv_datastoreid = iv_datastore_id
          iv_jobid = iv_job_id
        ).
        DATA(lo_import_job_properties) = oo_result->get_importjobproperties( ).
        IF lo_import_job_properties IS BOUND.
          DATA(lv_job_status) = lo_import_job_properties->get_jobstatus( ).
          MESSAGE |Import job status: { lv_job_status }.| TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        DATA(lv_error) = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        lv_error = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeFHIRImportJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListFHIRDatastores`
<a name="healthlake_ListFHIRDatastores_sap-abap_1_topic"></a>

次の例は、`ListFHIRDatastores` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_hll->listfhirdatastores( ).
        DATA(lt_datastores) = oo_result->get_datastorepropertieslist( ).
        DATA(lv_datastore_count) = lines( lt_datastores ).
        MESSAGE |Found { lv_datastore_count } data store(s).| TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllthrottlingex INTO DATA(lo_throttling_ex).
        lv_error = |Throttling error: { lo_throttling_ex->av_err_code }-{ lo_throttling_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_throttling_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListFHIRDatastores](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListFHIRExportJobs`
<a name="healthlake_ListFHIRExportJobs_sap-abap_1_topic"></a>

次の例は、`ListFHIRExportJobs` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_datastore_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        IF iv_submitted_after IS NOT INITIAL.
          oo_result = lo_hll->listfhirexportjobs(
            iv_datastoreid = iv_datastore_id
            iv_submittedafter = iv_submitted_after
          ).
        ELSE.
          oo_result = lo_hll->listfhirexportjobs(
            iv_datastoreid = iv_datastore_id
          ).
        ENDIF.
        DATA(lt_export_jobs) = oo_result->get_exportjobpropertieslist( ).
        DATA(lv_job_count) = lines( lt_export_jobs ).
        MESSAGE |Found { lv_job_count } export job(s).| TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        lv_error = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListFHIRExportJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListFHIRImportJobs`
<a name="healthlake_ListFHIRImportJobs_sap-abap_1_topic"></a>

次の例は、`ListFHIRImportJobs` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_datastore_id = 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        IF iv_submitted_after IS NOT INITIAL.
          oo_result = lo_hll->listfhirimportjobs(
            iv_datastoreid = iv_datastore_id
            iv_submittedafter = iv_submitted_after
          ).
        ELSE.
          oo_result = lo_hll->listfhirimportjobs(
            iv_datastoreid = iv_datastore_id
          ).
        ENDIF.
        DATA(lt_import_jobs) = oo_result->get_importjobpropertieslist( ).
        DATA(lv_job_count) = lines( lt_import_jobs ).
        MESSAGE |Found { lv_job_count } import job(s).| TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        lv_error = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListFHIRImportJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTagsForResource`
<a name="healthlake_ListTagsForResource_sap-abap_1_topic"></a>

次の例は、`ListTagsForResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_resource_arn = 'arn:aws:healthlake:us-east-1:123456789012:datastore/fhir/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        DATA(lo_result) = lo_hll->listtagsforresource(
          iv_resourcearn = iv_resource_arn
        ).
        ot_tags = lo_result->get_tags( ).
        DATA(lv_tag_count) = lines( ot_tags ).
        MESSAGE |Found { lv_tag_count } tag(s).| TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        lv_error = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListTagsForResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartFHIRExportJob`
<a name="healthlake_StartFHIRExportJob_sap-abap_1_topic"></a>

次の例は、`StartFHIRExportJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_job_name = 'MyExportJob'
        " iv_output_s3_uri = 's3://my-bucket/export/output/'
        " iv_kms_key_id = 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
        " iv_data_access_role_arn = 'arn:aws:iam::123456789012:role/HealthLakeExportRole'
        oo_result = lo_hll->startfhirexportjob(
          iv_jobname = iv_job_name
          io_outputdataconfig = NEW /aws1/cl_hlloutputdataconfig(
            io_s3configuration = NEW /aws1/cl_hlls3configuration(
              iv_s3uri = iv_output_s3_uri
              iv_kmskeyid = iv_kms_key_id
            )
          )
          iv_dataaccessrolearn = iv_data_access_role_arn
          iv_datastoreid = iv_datastore_id
        ).
        DATA(lv_job_id) = oo_result->get_jobid( ).
        MESSAGE |Export job started with ID { lv_job_id }.| TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllthrottlingex INTO DATA(lo_throttling_ex).
        lv_error = |Throttling error: { lo_throttling_ex->av_err_code }-{ lo_throttling_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_throttling_ex.
      CATCH /aws1/cx_hllaccessdeniedex INTO DATA(lo_access_ex).
        lv_error = |Access denied: { lo_access_ex->av_err_code }-{ lo_access_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_access_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartFHIRExportJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartFHIRImportJob`
<a name="healthlake_StartFHIRImportJob_sap-abap_1_topic"></a>

次の例は、`StartFHIRImportJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_job_name = 'MyImportJob'
        " iv_input_s3_uri = 's3://my-bucket/import/data.ndjson'
        " iv_job_output_s3_uri = 's3://my-bucket/import/output/'
        " iv_kms_key_id = 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012'
        " iv_data_access_role_arn = 'arn:aws:iam::123456789012:role/HealthLakeImportRole'
        oo_result = lo_hll->startfhirimportjob(
          iv_jobname = iv_job_name
          io_inputdataconfig = NEW /aws1/cl_hllinputdataconfig( iv_s3uri = iv_input_s3_uri )
          io_joboutputdataconfig = NEW /aws1/cl_hlloutputdataconfig(
            io_s3configuration = NEW /aws1/cl_hlls3configuration(
              iv_s3uri = iv_job_output_s3_uri
              iv_kmskeyid = iv_kms_key_id
            )
          )
          iv_dataaccessrolearn = iv_data_access_role_arn
          iv_datastoreid = iv_datastore_id
        ).
        DATA(lv_job_id) = oo_result->get_jobid( ).
        MESSAGE |Import job started with ID { lv_job_id }.| TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllthrottlingex INTO DATA(lo_throttling_ex).
        lv_error = |Throttling error: { lo_throttling_ex->av_err_code }-{ lo_throttling_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_throttling_ex.
      CATCH /aws1/cx_hllaccessdeniedex INTO DATA(lo_access_ex).
        lv_error = |Access denied: { lo_access_ex->av_err_code }-{ lo_access_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_access_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartFHIRImportJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `TagResource`
<a name="healthlake_TagResource_sap-abap_1_topic"></a>

次の例は、`TagResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_resource_arn = 'arn:aws:healthlake:us-east-1:123456789012:datastore/fhir/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        lo_hll->tagresource(
          iv_resourcearn = iv_resource_arn
          it_tags = it_tags
        ).
        MESSAGE 'Resource tagged successfully.' TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        lv_error = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[TagResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UntagResource`
<a name="healthlake_UntagResource_sap-abap_1_topic"></a>

次の例は、`UntagResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/hll#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_resource_arn = 'arn:aws:healthlake:us-east-1:123456789012:datastore/fhir/a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'
        lo_hll->untagresource(
          iv_resourcearn = iv_resource_arn
          it_tagkeys = it_tag_keys
        ).
        MESSAGE 'Resource untagged successfully.' TYPE 'I'.
      CATCH /aws1/cx_hllvalidationex INTO DATA(lo_validation_ex).
        DATA(lv_error) = |Validation error: { lo_validation_ex->av_err_code }-{ lo_validation_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_validation_ex.
      CATCH /aws1/cx_hllresourcenotfoundex INTO DATA(lo_notfound_ex).
        lv_error = |Resource not found: { lo_notfound_ex->av_err_code }-{ lo_notfound_ex->av_err_msg }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_notfound_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [UntagResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した IAM の例
<a name="sap-abap_1_iam_code_examples"></a>

次のコード例は、IAM で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_sap-abap_1_topic"></a>

次の例は、`AttachRolePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->attachrolepolicy(
          iv_rolename = iv_role_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy attached to role successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role or policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy attachment limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[AttachRolePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `AttachUserPolicy`
<a name="iam_AttachUserPolicy_sap-abap_1_topic"></a>

次の例は、`AttachUserPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->attachuserpolicy(
          iv_username = iv_user_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy attached to user successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User or policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy attachment limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[AttachUserPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_sap-abap_1_topic"></a>

次の例は、`CreateAccessKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->createaccesskey(
          iv_username = iv_user_name ).
        MESSAGE 'Access key created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Maximum number of access keys reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateAccessKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateAccountAlias`
<a name="iam_CreateAccountAlias_sap-abap_1_topic"></a>

次の例は、`CreateAccountAlias` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->createaccountalias(
          iv_accountalias = iv_account_alias ).
        MESSAGE 'Account alias created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'Account alias already exists.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Account alias limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateAccountAlias](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_sap-abap_1_topic"></a>

次の例は、`CreatePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->createpolicy(
          iv_policyname = iv_policy_name
          iv_policydocument = iv_policy_document
          iv_description = iv_description ).
        MESSAGE 'Policy created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'Policy already exists.' TYPE 'E'.
      CATCH /aws1/cx_iammalformedplydocex.
        MESSAGE 'Policy document is malformed.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreatePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreatePolicyVersion`
<a name="iam_CreatePolicyVersion_sap-abap_1_topic"></a>

次の例は、`CreatePolicyVersion` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->createpolicyversion(
          iv_policyarn = iv_policy_arn
          iv_policydocument = iv_policy_document
          iv_setasdefault = iv_set_as_default ).
        MESSAGE 'Policy version created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iammalformedplydocex.
        MESSAGE 'Policy document is malformed.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Policy version limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreatePolicyVersion](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_sap-abap_1_topic"></a>

次の例は、`CreateRole` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->createrole(
          iv_rolename = iv_role_name
          iv_assumerolepolicydocument = iv_assume_role_policy_document ).
        MESSAGE 'Role created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'Role already exists.' TYPE 'E'.
      CATCH /aws1/cx_iammalformedplydocex.
        MESSAGE 'Assume role policy document is malformed.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Role limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_sap-abap_1_topic"></a>

次の例は、`CreateServiceLinkedRole` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listpolicyversions(
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Retrieved policy versions list.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing policy versions.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateServiceLinkedRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_sap-abap_1_topic"></a>

次の例は、`CreateUser` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->createuser(
          iv_username = iv_user_name ).
        MESSAGE 'User created successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'User already exists.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Limit exceeded for IAM users.' TYPE 'E'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Entity does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateUser](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_sap-abap_1_topic"></a>

次の例は、`DeleteAccessKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->deleteaccesskey(
          iv_accesskeyid = iv_access_key_id
          iv_username = iv_user_name ).
        MESSAGE 'Access key deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Access key or user does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「[AWS SDK for SAP ABAP API リファレンス](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」の「*DeleteAccessKey*」を参照してください。

### `DeleteAccountAlias`
<a name="iam_DeleteAccountAlias_sap-abap_1_topic"></a>

次の例は、`DeleteAccountAlias` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->deleteaccountalias(
          iv_accountalias = iv_account_alias ).
        MESSAGE 'Account alias deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Account alias does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteAccountAlias](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_sap-abap_1_topic"></a>

次の例は、`DeletePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->deletepolicy( iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'Policy cannot be deleted due to attachments.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeletePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeletePolicyVersion`
<a name="iam_DeletePolicyVersion_sap-abap_1_topic"></a>

次の例は、`DeletePolicyVersion` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->deletepolicyversion(
          iv_policyarn = iv_policy_arn
          iv_versionid = iv_version_id ).
        MESSAGE 'Policy version deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy or version does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'Cannot delete default policy version.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeletePolicyVersion](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_sap-abap_1_topic"></a>

次の例は、`DeleteRole` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->deleterole( iv_rolename = iv_role_name ).
        MESSAGE 'Role deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'Role cannot be deleted due to attached resources.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_sap-abap_1_topic"></a>

次の例は、`DeleteUser` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->deleteuser( iv_username = iv_user_name ).
        MESSAGE 'User deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamdeleteconflictex.
        MESSAGE 'User cannot be deleted due to attached resources.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteUser](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_sap-abap_1_topic"></a>

次の例は、`DetachRolePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->detachrolepolicy(
          iv_rolename = iv_role_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy detached from role successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role or policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DetachRolePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetachUserPolicy`
<a name="iam_DetachUserPolicy_sap-abap_1_topic"></a>

次の例は、`DetachUserPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->detachuserpolicy(
          iv_username = iv_user_name
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Policy detached from user successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User or policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DetachUserPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GenerateCredentialReport`
<a name="iam_GenerateCredentialReport_sap-abap_1_topic"></a>

次の例は、`GenerateCredentialReport` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->generatecredentialreport( ).
        MESSAGE 'Credential report generation started.' TYPE 'I'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Report generation limit exceeded.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when generating credential report.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GenerateCredentialReport](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetAccessKeyLastUsed`
<a name="iam_GetAccessKeyLastUsed_sap-abap_1_topic"></a>

次の例は、`GetAccessKeyLastUsed` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->getaccesskeylastused(
          iv_accesskeyid = iv_access_key_id ).
        MESSAGE 'Retrieved access key last used information.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Access key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetAccessKeyLastUsed](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetAccountAuthorizationDetails`
<a name="iam_GetAccountAuthorizationDetails_sap-abap_1_topic"></a>

次の例は、`GetAccountAuthorizationDetails` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->getaccountauthdetails( ).
        MESSAGE 'Retrieved account authorization details.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting account authorization details.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetAccountAuthorizationDetails](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetAccountPasswordPolicy`
<a name="iam_GetAccountPasswordPolicy_sap-abap_1_topic"></a>

次の例は、`GetAccountPasswordPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->getaccountpasswordpolicy( ).
        MESSAGE 'Retrieved account password policy.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'No password policy exists.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting password policy.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetAccountPasswordPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetAccountSummary`
<a name="iam_GetAccountSummary_sap-abap_1_topic"></a>

次の例は、`GetAccountSummary` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->getaccountsummary( ).
        MESSAGE 'Retrieved account summary.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting account summary.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetAccountSummary](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetCredentialReport`
<a name="iam_GetCredentialReport_sap-abap_1_topic"></a>

次の例は、`GetCredentialReport` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->getcredentialreport( ).
        MESSAGE 'Retrieved credential report.' TYPE 'I'.
      CATCH /aws1/cx_iamcredrptnotpresen00.
        MESSAGE 'Credential report not present.' TYPE 'E'.
      CATCH /aws1/cx_iamcredrptexpiredex.
        MESSAGE 'Credential report expired.' TYPE 'E'.
      CATCH /aws1/cx_iamcredrptnotreadyex.
        MESSAGE 'Credential report not ready.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when getting credential report.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetCredentialReport](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_sap-abap_1_topic"></a>

次の例は、`GetPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->getpolicy( iv_policyarn = iv_policy_arn ).
        MESSAGE 'Retrieved policy information.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetRole`
<a name="iam_GetRole_sap-abap_1_topic"></a>

次の例は、`GetRole` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->getrole( iv_rolename = iv_role_name ).
        MESSAGE 'Retrieved role information.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetRole](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListAccessKeys`
<a name="iam_ListAccessKeys_sap-abap_1_topic"></a>

次の例は、`ListAccessKeys` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listaccesskeys(
          iv_username = iv_user_name ).
        MESSAGE 'Retrieved access key list.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListAccessKeys](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListAccountAliases`
<a name="iam_ListAccountAliases_sap-abap_1_topic"></a>

次の例は、`ListAccountAliases` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listaccountaliases( ).
        MESSAGE 'Retrieved account alias list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing account aliases.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListAccountAliases](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_sap-abap_1_topic"></a>

次の例は、`ListAttachedRolePolicies` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listattachedrolepolicies(
          iv_rolename = iv_role_name ).
        MESSAGE 'Retrieved attached policy list for role.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListAttachedRolePolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_sap-abap_1_topic"></a>

次の例は、`ListGroups` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listgroups( ).
        MESSAGE 'Retrieved group list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing groups.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_sap-abap_1_topic"></a>

次の例は、`ListPolicies` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listpolicies( iv_scope = iv_scope ).
        MESSAGE 'Retrieved policy list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing policies.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListPolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListPolicyVersions`
<a name="iam_ListPolicyVersions_sap-abap_1_topic"></a>

次の例は、`ListPolicyVersions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listpolicyversions(
          iv_policyarn = iv_policy_arn ).
        MESSAGE 'Retrieved policy versions list.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing policy versions.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListPolicyVersions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_sap-abap_1_topic"></a>

次の例は、`ListRolePolicies` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listrolepolicies(
          iv_rolename = iv_role_name ).
        MESSAGE 'Retrieved inline policy list for role.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Role does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListRolePolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_sap-abap_1_topic"></a>

次の例は、`ListRoles` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listroles( ).
        MESSAGE 'Retrieved role list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing roles.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListRoles](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListSAMLProviders`
<a name="iam_ListSAMLProviders_sap-abap_1_topic"></a>

次の例は、`ListSAMLProviders` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listsamlproviders( ).
        MESSAGE 'Retrieved SAML provider list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing SAML providers.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListSAMLProviders](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_sap-abap_1_topic"></a>

次の例は、`ListUsers` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_iam->listusers( ).
        MESSAGE 'Retrieved user list.' TYPE 'I'.
      CATCH /aws1/cx_iamservicefailureex.
        MESSAGE 'Service failure when listing users.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListUsers](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SetDefaultPolicyVersion`
<a name="iam_SetDefaultPolicyVersion_sap-abap_1_topic"></a>

次の例は、`SetDefaultPolicyVersion` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->setdefaultpolicyversion(
          iv_policyarn = iv_policy_arn
          iv_versionid = iv_version_id ).
        MESSAGE 'Default policy version set successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Policy or version does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iaminvalidinputex.
        MESSAGE 'Invalid input provided.' TYPE 'E'.
      CATCH /aws1/cx_iamlimitexceededex.
        MESSAGE 'Limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[SetDefaultPolicyVersion](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateAccessKey`
<a name="iam_UpdateAccessKey_sap-abap_1_topic"></a>

次の例は、`UpdateAccessKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->updateaccesskey(
          iv_accesskeyid = iv_access_key_id
          iv_status = iv_status
          iv_username = iv_user_name ).
        MESSAGE 'Access key updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'Access key or user does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[UpdateAccessKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateUser`
<a name="iam_UpdateUser_sap-abap_1_topic"></a>

次の例は、`UpdateUser` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/iam#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_iam->updateuser(
          iv_username = iv_user_name
          iv_newusername = iv_new_user_name ).
        MESSAGE 'User updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_iamnosuchentityex.
        MESSAGE 'User does not exist.' TYPE 'E'.
      CATCH /aws1/cx_iamentityalrdyexex.
        MESSAGE 'New user name already exists.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[UpdateUser](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# AWS IoT SiteWise SDK for SAP ABAP を使用した例
<a name="sap-abap_1_iotsitewise_code_examples"></a>

次のコード例は、 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS IoT SiteWise。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS IoT SiteWiseは
<a name="iotsitewise_Hello_sap-abap_1_topic"></a>

次のコード例は、 AWS IoT SiteWiseの使用を開始する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->listassetmodels( ). " oo_result is returned for testing purposes. "
        DATA(lt_asset_models) = oo_result->get_assetmodelsummaries( ).
        MESSAGE 'Retrieved list of asset models.' TYPE 'I'.
      CATCH /aws1/cx_rt_generic.
        MESSAGE 'Unable to list asset models.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListAssetModels](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## アクション
<a name="actions"></a>

### `BatchPutAssetPropertyValue`
<a name="iotsitewise_BatchPutAssetPropertyValue_sap-abap_1_topic"></a>

次の例は、`BatchPutAssetPropertyValue` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ios->batchputassetpropertyvalue(
          it_entries = it_entries
        ).
        MESSAGE 'Data sent to IoT SiteWise asset successfully.' TYPE 'I'.
      CATCH /aws1/cx_iosresourcenotfoundex.
        MESSAGE 'Asset does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[BatchPutAssetPropertyValue](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateAsset`
<a name="iotsitewise_CreateAsset_sap-abap_1_topic"></a>

次の例は、`CreateAsset` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->createasset(
          iv_assetname = iv_asset_name
          iv_assetmodelid = iv_asset_model_id
        ). " oo_result is returned for testing purposes. "
        MESSAGE 'IoT SiteWise asset created' TYPE 'I'.
      CATCH /aws1/cx_iosresourcenotfoundex.
        MESSAGE 'Asset model does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateAsset](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateAssetModel`
<a name="iotsitewise_CreateAssetModel_sap-abap_1_topic"></a>

次の例は、`CreateAssetModel` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->createassetmodel(
          iv_assetmodelname = iv_asset_model_name
          iv_assetmodeldescription = 'This is a sample asset model description.'
          it_assetmodelproperties = it_properties
        ). " oo_result is returned for testing purposes. "
        MESSAGE 'IoT SiteWise asset model created' TYPE 'I'.
      CATCH /aws1/cx_iosresrcalrdyexistsex.
        MESSAGE 'Asset model already exists.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateAssetModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateGateway`
<a name="iotsitewise_CreateGateway_sap-abap_1_topic"></a>

次の例は、`CreateGateway` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->creategateway(
          iv_gatewayname = iv_gateway_name
          io_gatewayplatform = NEW /aws1/cl_iosgatewayplatform(
            io_greengrassv2 = NEW /aws1/cl_iosgreengrassv2(
              iv_coredevicethingname = iv_core_device_thing_name
            )
          )
          it_tags = VALUE /aws1/cl_iostagmap_w=>tt_tagmap(
            (
              VALUE /aws1/cl_iostagmap_w=>ts_tagmap_maprow(
                key = 'Environment'
                value = NEW /aws1/cl_iostagmap_w( 'Production' )
              )
            )
          )
        ). " oo_result is returned for testing purposes. "
        MESSAGE 'IoT SiteWise gateway created' TYPE 'I'.
      CATCH /aws1/cx_iosresrcalrdyexistsex.
        MESSAGE 'Gateway already exists.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateGateway](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteAsset`
<a name="iotsitewise_DeleteAsset_sap-abap_1_topic"></a>

次の例は、`DeleteAsset` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ios->deleteasset(
          iv_assetid = iv_asset_id
        ).
        MESSAGE 'IoT SiteWise asset deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_generic.
        MESSAGE 'Unable to delete asset.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteAsset](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteAssetModel`
<a name="iotsitewise_DeleteAssetModel_sap-abap_1_topic"></a>

次の例は、`DeleteAssetModel` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ios->deleteassetmodel(
          iv_assetmodelid = iv_asset_model_id
        ).
        MESSAGE 'IoT SiteWise asset model deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_generic.
        MESSAGE 'Unable to delete asset model.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteAssetModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteGateway`
<a name="iotsitewise_DeleteGateway_sap-abap_1_topic"></a>

次の例は、`DeleteGateway` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ios->deletegateway(
          iv_gatewayid = iv_gateway_id
        ).
        MESSAGE 'IoT SiteWise gateway deleted.' TYPE 'I'.
      CATCH /aws1/cx_iosresourcenotfoundex.
        MESSAGE 'Gateway does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteGateway](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeGateway`
<a name="iotsitewise_DescribeGateway_sap-abap_1_topic"></a>

次の例は、`DescribeGateway` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->describegateway(
          iv_gatewayid = iv_gateway_id
        ). " oo_result is returned for testing purposes. "
        MESSAGE 'Retrieved gateway description.' TYPE 'I'.
      CATCH /aws1/cx_iosresourcenotfoundex.
        MESSAGE 'Gateway does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeGateway](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetAssetPropertyValue`
<a name="iotsitewise_GetAssetPropertyValue_sap-abap_1_topic"></a>

次の例は、`GetAssetPropertyValue` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->getassetpropertyvalue(
          iv_assetid = iv_asset_id
          iv_propertyid = iv_property_id
        ). " oo_result is returned for testing purposes. "
        MESSAGE 'Retrieved asset property value.' TYPE 'I'.
      CATCH /aws1/cx_iosresourcenotfoundex.
        MESSAGE 'Asset or property does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetAssetPropertyValue](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListAssetModelProperties`
<a name="iotsitewise_ListAssetModelProperties_sap-abap_1_topic"></a>

次の例は、`ListAssetModelProperties` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->listassetmodelproperties(
          iv_assetmodelid = iv_asset_model_id
        ). " oo_result is returned for testing purposes. "
        DATA(lt_properties) = oo_result->get_assetmodelpropertysums( ).
        MESSAGE 'Retrieved list of asset model properties.' TYPE 'I'.
      CATCH /aws1/cx_rt_generic.
        MESSAGE 'Unable to list asset model properties.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListAssetModelProperties](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListAssetModels`
<a name="iotsitewise_ListAssetModels_sap-abap_1_topic"></a>

次の例は、`ListAssetModels` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ios#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ios->listassetmodels( ). " oo_result is returned for testing purposes. "
        DATA(lt_asset_models) = oo_result->get_assetmodelsummaries( ).
        MESSAGE 'Retrieved list of asset models.' TYPE 'I'.
      CATCH /aws1/cx_rt_generic.
        MESSAGE 'Unable to list asset models.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListAssetModels](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Keyspaces の例
<a name="sap-abap_1_keyspaces_code_examples"></a>

次のコード例は、Amazon Keyspaces で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateKeyspace`
<a name="keyspaces_CreateKeyspace_sap-abap_1_topic"></a>

次の例は、`CreateKeyspace` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kys->createkeyspace(
          iv_keyspacename = iv_keyspace_name ).
        MESSAGE 'Keyspace created successfully.' TYPE 'I'.
      CATCH /aws1/cx_kysconflictexception.
        MESSAGE 'Keyspace already exists.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateKeyspace](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateTable`
<a name="keyspaces_CreateTable_sap-abap_1_topic"></a>

次の例は、`CreateTable` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Define schema with columns
        DATA(lt_columns) = VALUE /aws1/cl_kyscolumndefinition=>tt_columndefinitionlist(
          ( NEW /aws1/cl_kyscolumndefinition( iv_name = 'title' iv_type = 'text' ) )
          ( NEW /aws1/cl_kyscolumndefinition( iv_name = 'year' iv_type = 'int' ) )
          ( NEW /aws1/cl_kyscolumndefinition( iv_name = 'release_date' iv_type = 'timestamp' ) )
          ( NEW /aws1/cl_kyscolumndefinition( iv_name = 'plot' iv_type = 'text' ) )
        ).

        " Define partition keys
        DATA(lt_partition_keys) = VALUE /aws1/cl_kyspartitionkey=>tt_partitionkeylist(
          ( NEW /aws1/cl_kyspartitionkey( iv_name = 'year' ) )
          ( NEW /aws1/cl_kyspartitionkey( iv_name = 'title' ) )
        ).

        " Create schema definition
        DATA(lo_schema) = NEW /aws1/cl_kysschemadefinition(
          it_allcolumns = lt_columns
          it_partitionkeys = lt_partition_keys ).

        " Enable point-in-time recovery
        DATA(lo_pitr) = NEW /aws1/cl_kyspointintimerec(
          iv_status = 'ENABLED' ).

        oo_result = lo_kys->createtable(
          iv_keyspacename = iv_keyspace_name
          iv_tablename = iv_table_name
          io_schemadefinition = lo_schema
          io_pointintimerecovery = lo_pitr ).
        MESSAGE 'Table created successfully.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteKeyspace`
<a name="keyspaces_DeleteKeyspace_sap-abap_1_topic"></a>

次の例は、`DeleteKeyspace` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_kys->deletekeyspace(
          iv_keyspacename = iv_keyspace_name ).
        MESSAGE 'Keyspace deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteKeyspace](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteTable`
<a name="keyspaces_DeleteTable_sap-abap_1_topic"></a>

次の例は、`DeleteTable` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_kys->deletetable(
          iv_keyspacename = iv_keyspace_name
          iv_tablename = iv_table_name ).
        MESSAGE 'Table deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetKeyspace`
<a name="keyspaces_GetKeyspace_sap-abap_1_topic"></a>

次の例は、`GetKeyspace` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kys->getkeyspace(
          iv_keyspacename = iv_keyspace_name ).
        MESSAGE 'Keyspace retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_kysresourcenotfoundex.
        MESSAGE 'Keyspace does not exist.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetKeyspace](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetTable`
<a name="keyspaces_GetTable_sap-abap_1_topic"></a>

次の例は、`GetTable` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kys->gettable(
          iv_keyspacename = iv_keyspace_name
          iv_tablename = iv_table_name ).
        MESSAGE 'Table information retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_kysresourcenotfoundex.
        MESSAGE 'Table does not exist.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListKeyspaces`
<a name="keyspaces_ListKeyspaces_sap-abap_1_topic"></a>

次の例は、`ListKeyspaces` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kys->listkeyspaces(
          iv_maxresults = iv_max_results ).
        MESSAGE 'Keyspaces listed successfully.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListKeyspaces](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTables`
<a name="keyspaces_ListTables_sap-abap_1_topic"></a>

次の例は、`ListTables` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kys->listtables(
          iv_keyspacename = iv_keyspace_name ).
        MESSAGE 'Tables listed successfully.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[ListTables](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RestoreTable`
<a name="keyspaces_RestoreTable_sap-abap_1_topic"></a>

次の例は、`RestoreTable` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kys->restoretable(
          iv_sourcekeyspacename = iv_source_keyspace_name
          iv_sourcetablename = iv_source_table_name
          iv_targetkeyspacename = iv_target_keyspace_name
          iv_targettablename = iv_target_table_name
          iv_restoretimestamp = iv_restore_timestamp ).
        MESSAGE 'Table restore initiated successfully.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[RestoreTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateTable`
<a name="keyspaces_UpdateTable_sap-abap_1_topic"></a>

次の例は、`UpdateTable` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kys#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Add a new column to track watched movies
        DATA(lt_add_columns) = VALUE /aws1/cl_kyscolumndefinition=>tt_columndefinitionlist(
          ( NEW /aws1/cl_kyscolumndefinition( iv_name = 'watched' iv_type = 'boolean' ) )
        ).

        oo_result = lo_kys->updatetable(
          iv_keyspacename = iv_keyspace_name
          iv_tablename = iv_table_name
          it_addcolumns = lt_add_columns ).
        MESSAGE 'Table updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateTable](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Kinesis の例
<a name="sap-abap_1_kinesis_code_examples"></a>

次のコード例は、Kinesis で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="kinesis_Scenario_GettingStarted_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ストリームを作成し、そのストリームにレコードを挿入します。
+ シャードイテレーターを作成します。
+ レコードを読み取り、リソースをクリーンアップします。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    DATA lo_stream_describe_result TYPE REF TO /aws1/cl_knsdescrstreamoutput.
    DATA lo_stream_description TYPE REF TO /aws1/cl_knsstreamdescription.
    DATA lo_sharditerator TYPE REF TO /aws1/cl_knsgetsharditerator01.
    DATA lo_record_result TYPE REF TO /aws1/cl_knsputrecordoutput.

    "Create stream."
    TRY.
        lo_kns->createstream(
            iv_streamname = iv_stream_name
            iv_shardcount = iv_shard_count ).
        MESSAGE 'Stream created.' TYPE 'I'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_knslimitexceededex.
        MESSAGE 'The request processing has failed because of a limit exceeded exception.' TYPE 'E'.
      CATCH /aws1/cx_knsresourceinuseex.
        MESSAGE 'The request processing has failed because the resource is in use.' TYPE 'E'.
    ENDTRY.

    "Wait for stream to becomes active."
    lo_stream_describe_result = lo_kns->describestream( iv_streamname = iv_stream_name ).
    lo_stream_description = lo_stream_describe_result->get_streamdescription( ).
    WHILE lo_stream_description->get_streamstatus( ) <> 'ACTIVE'.
      IF sy-index = 30.
        EXIT.               "maximum 5 minutes"
      ENDIF.
      WAIT UP TO 10 SECONDS.
      lo_stream_describe_result = lo_kns->describestream( iv_streamname = iv_stream_name ).
      lo_stream_description = lo_stream_describe_result->get_streamdescription( ).
    ENDWHILE.

    "Create record."
    TRY.
        lo_record_result = lo_kns->putrecord(
            iv_streamname = iv_stream_name
            iv_data       = iv_data
            iv_partitionkey = iv_partition_key ).
        MESSAGE 'Record created.' TYPE 'I'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_knskmsaccessdeniedex.
        MESSAGE 'You do not have permission to perform this AWS KMS action.' TYPE 'E'.
      CATCH /aws1/cx_knskmsdisabledex.
        MESSAGE 'KMS key used is disabled.' TYPE 'E'.
      CATCH /aws1/cx_knskmsinvalidstateex.
        MESSAGE 'KMS key used is in an invalid state. ' TYPE 'E'.
      CATCH /aws1/cx_knskmsnotfoundex.
        MESSAGE 'KMS key used is not found.' TYPE 'E'.
      CATCH /aws1/cx_knskmsoptinrequired.
        MESSAGE 'KMS key option is required.' TYPE 'E'.
      CATCH /aws1/cx_knskmsthrottlingex.
        MESSAGE 'The rate of requests to AWS KMS is exceeding the request quotas.' TYPE 'E'.
      CATCH /aws1/cx_knsprovthruputexcdex.
        MESSAGE 'The request rate for the stream is too high, or the requested data is too large for the available throughput.' TYPE 'E'.
      CATCH /aws1/cx_knsresourcenotfoundex.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.

    "Create a shard iterator in order to read the record."
    TRY.
        lo_sharditerator = lo_kns->getsharditerator(
          iv_shardid = lo_record_result->get_shardid( )
          iv_sharditeratortype = iv_sharditeratortype
          iv_streamname = iv_stream_name ).
        MESSAGE 'Shard iterator created.' TYPE 'I'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_knsprovthruputexcdex.
        MESSAGE 'The request rate for the stream is too high, or the requested data is too large for the available throughput.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcenotfound.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.

    "Read the record."
    TRY.
        oo_result = lo_kns->getrecords(                    " oo_result is returned for testing purposes. "
            iv_sharditerator   = lo_sharditerator->get_sharditerator( ) ).
        MESSAGE 'Shard iterator created.' TYPE 'I'.
      CATCH /aws1/cx_knsexpirediteratorex.
        MESSAGE 'Iterator expired.' TYPE 'E'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_knskmsaccessdeniedex.
        MESSAGE 'You do not have permission to perform this AWS KMS action.' TYPE 'E'.
      CATCH /aws1/cx_knskmsdisabledex.
        MESSAGE 'KMS key used is disabled.' TYPE 'E'.
      CATCH /aws1/cx_knskmsinvalidstateex.
        MESSAGE 'KMS key used is in an invalid state. ' TYPE 'E'.
      CATCH /aws1/cx_knskmsnotfoundex.
        MESSAGE 'KMS key used is not found.' TYPE 'E'.
      CATCH /aws1/cx_knskmsoptinrequired.
        MESSAGE 'KMS key option is required.' TYPE 'E'.
      CATCH /aws1/cx_knskmsthrottlingex.
        MESSAGE 'The rate of requests to AWS KMS is exceeding the request quotas.' TYPE 'E'.
      CATCH /aws1/cx_knsprovthruputexcdex.
        MESSAGE 'The request rate for the stream is too high, or the requested data is too large for the available throughput.' TYPE 'E'.
      CATCH /aws1/cx_knsresourcenotfoundex.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.

    "Delete stream."
    TRY.
        lo_kns->deletestream(
            iv_streamname = iv_stream_name ).
        MESSAGE 'Stream deleted.' TYPE 'I'.
      CATCH /aws1/cx_knslimitexceededex.
        MESSAGE 'The request processing has failed because of a limit exceeded exception.' TYPE 'E'.
      CATCH /aws1/cx_knsresourceinuseex.
        MESSAGE 'The request processing has failed because the resource is in use.' TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [CreateStream](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteStream](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [GetRecords](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [GetShardIterator](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [PutRecord](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateStream`
<a name="kinesis_CreateStream_sap-abap_1_topic"></a>

次のコード例は、`CreateStream` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_kns->createstream(
            iv_streamname = iv_stream_name
            iv_shardcount = iv_shard_count ).
        MESSAGE 'Stream created.' TYPE 'I'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_knslimitexceededex.
        MESSAGE 'The request processing has failed because of a limit exceed exception.' TYPE 'E'.
      CATCH /aws1/cx_knsresourceinuseex.
        MESSAGE 'The request processing has failed because the resource is in use.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateStream](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteStream`
<a name="kinesis_DeleteStream_sap-abap_1_topic"></a>

次のコード例は、`DeleteStream` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_kns->deletestream(
            iv_streamname = iv_stream_name ).
        MESSAGE 'Stream deleted.' TYPE 'I'.
      CATCH /aws1/cx_knslimitexceededex.
        MESSAGE 'The request processing has failed because of a limit exceed exception.' TYPE 'E'.
      CATCH /aws1/cx_knsresourceinuseex.
        MESSAGE 'The request processing has failed because the resource is in use.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteStream](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeStream`
<a name="kinesis_DescribeStream_sap-abap_1_topic"></a>

次のコード例は、`DescribeStream` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kns->describestream(
            iv_streamname = iv_stream_name ).
        DATA(lt_stream_description) = oo_result->get_streamdescription( ).
        MESSAGE 'Streams retrieved.' TYPE 'I'.
      CATCH /aws1/cx_knslimitexceededex.
        MESSAGE 'The request processing has failed because of a limit exceed exception.' TYPE 'E'.
      CATCH /aws1/cx_knsresourcenotfoundex.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeStream](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetRecords`
<a name="kinesis_GetRecords_sap-abap_1_topic"></a>

次のコード例は、`GetRecords` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kns->getrecords(             " oo_result is returned for testing purposes. "
            iv_sharditerator = iv_shard_iterator ).
        DATA(lt_records) = oo_result->get_records( ).
        MESSAGE 'Record retrieved.' TYPE 'I'.
      CATCH /aws1/cx_knsexpirediteratorex.
        MESSAGE 'Iterator expired.' TYPE 'E'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_knskmsaccessdeniedex.
        MESSAGE 'You do not have permission to perform this AWS KMS action.' TYPE 'E'.
      CATCH /aws1/cx_knskmsdisabledex.
        MESSAGE 'KMS key used is disabled.' TYPE 'E'.
      CATCH /aws1/cx_knskmsinvalidstateex.
        MESSAGE 'KMS key used is in an invalid state. ' TYPE 'E'.
      CATCH /aws1/cx_knskmsnotfoundex.
        MESSAGE 'KMS key used is not found.' TYPE 'E'.
      CATCH /aws1/cx_knskmsoptinrequired.
        MESSAGE 'KMS key option is required.' TYPE 'E'.
      CATCH /aws1/cx_knskmsthrottlingex.
        MESSAGE 'The rate of requests to AWS KMS is exceeding the request quotas.' TYPE 'E'.
      CATCH /aws1/cx_knsprovthruputexcdex.
        MESSAGE 'The request rate for the stream is too high, or the requested data is too large for the available throughput.' TYPE 'E'.
      CATCH /aws1/cx_knsresourcenotfoundex.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[GetRecords](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `ListStreams`
<a name="kinesis_ListStreams_sap-abap_1_topic"></a>

次のコード例は、`ListStreams` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kns->liststreams(        " oo_result is returned for testing purposes. "
            "Set Limit to specify that a maximum of streams should be returned."
            iv_limit = iv_limit ).
        DATA(lt_streams) = oo_result->get_streamnames( ).
        MESSAGE 'Streams listed.' TYPE 'I'.
      CATCH /aws1/cx_knslimitexceededex.
        MESSAGE 'The request processing has failed because of a limit exceed exception.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListStreams](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutRecord`
<a name="kinesis_PutRecord_sap-abap_1_topic"></a>

次のコード例は、`PutRecord` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kns->putrecord(            " oo_result is returned for testing purposes. "
            iv_streamname = iv_stream_name
            iv_data       = iv_data
            iv_partitionkey = iv_partition_key ).
        MESSAGE 'Record created.' TYPE 'I'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_knskmsaccessdeniedex.
        MESSAGE 'You do not have permission to perform this AWS KMS action.' TYPE 'E'.
      CATCH /aws1/cx_knskmsdisabledex.
        MESSAGE 'KMS key used is disabled.' TYPE 'E'.
      CATCH /aws1/cx_knskmsinvalidstateex.
        MESSAGE 'KMS key used is in an invalid state. ' TYPE 'E'.
      CATCH /aws1/cx_knskmsnotfoundex.
        MESSAGE 'KMS key used is not found.' TYPE 'E'.
      CATCH /aws1/cx_knskmsoptinrequired.
        MESSAGE 'KMS key option is required.' TYPE 'E'.
      CATCH /aws1/cx_knskmsthrottlingex.
        MESSAGE 'The rate of requests to AWS KMS is exceeding the request quotas.' TYPE 'E'.
      CATCH /aws1/cx_knsprovthruputexcdex.
        MESSAGE 'The request rate for the stream is too high, or the requested data is too large for the available throughput.' TYPE 'E'.
      CATCH /aws1/cx_knsresourcenotfoundex.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[PutRecord](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RegisterStreamConsumer`
<a name="kinesis_RegisterStreamConsumer_sap-abap_1_topic"></a>

次のコード例は、`RegisterStreamConsumer` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kns->registerstreamconsumer(       " oo_result is returned for testing purposes. "
            iv_streamarn = iv_stream_arn
            iv_consumername = iv_consumer_name ).
        MESSAGE 'Stream consumer registered.' TYPE 'I'.
      CATCH /aws1/cx_knsinvalidargumentex.
        MESSAGE 'The specified argument was not valid.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourceinuse.
        MESSAGE 'Resource being accessed is in use.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcenotfound.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[RegisterStreamConsumer](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# AWS KMS SDK for SAP ABAP を使用した例
<a name="sap-abap_1_kms_code_examples"></a>

次のコード例は、 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS KMS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### こんにち AWS KMSは
<a name="kms_Hello_sap-abap_1_topic"></a>

次のコード例は、 AWS Key Management Serviceの使用を開始する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kms->listkeys( ).
        MESSAGE 'Retrieved KMS keys list.' TYPE 'I'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListKeys](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## アクション
<a name="actions"></a>

### `CreateAlias`
<a name="kms_CreateAlias_sap-abap_1_topic"></a>

次の例は、`CreateAlias` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_alias_name = 'alias/my-key-alias'
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        lo_kms->createalias(
          iv_aliasname = iv_alias_name
          iv_targetkeyid = iv_key_id
        ).
        MESSAGE 'Alias created successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsalreadyexistsex.
        MESSAGE 'Alias already exists.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmsinvalidaliasnameex.
        MESSAGE 'Invalid alias name.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateAlias](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateGrant`
<a name="kms_CreateGrant_sap-abap_1_topic"></a>

次の例は、`CreateGrant` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_grantee_principal = 'arn:aws:iam::123456789012:role/my-role'
        " it_operations contains 'Encrypt', 'Decrypt', 'GenerateDataKey'
        oo_result = lo_kms->creategrant(
          iv_keyid = iv_key_id
          iv_granteeprincipal = iv_grantee_principal
          it_operations = it_operations
        ).
        MESSAGE 'Grant created successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateGrant](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateKey`
<a name="kms_CreateKey_sap-abap_1_topic"></a>

次の例は、`CreateKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_description = 'Created by the AWS SDK for SAP ABAP'
        oo_result = lo_kms->createkey( iv_description = iv_description ).
        MESSAGE 'KMS key created successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
      CATCH /aws1/cx_kmslimitexceededex.
        MESSAGE 'Limit exceeded for KMS resources.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Decrypt`
<a name="kms_Decrypt_sap-abap_1_topic"></a>

次の例は、`Decrypt` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_ciphertext_blob contains the encrypted data
        oo_result = lo_kms->decrypt(
          iv_keyid = iv_key_id
          iv_ciphertextblob = iv_ciphertext_blob
        ).
        MESSAGE 'Text decrypted successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsincorrectkeyex.
        MESSAGE 'Incorrect key for decryption.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[「復号](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteAlias`
<a name="kms_DeleteAlias_sap-abap_1_topic"></a>

次の例は、`DeleteAlias` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_alias_name = 'alias/my-key-alias'
        lo_kms->deletealias( iv_aliasname = iv_alias_name ).
        MESSAGE 'Alias deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Alias not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteAlias](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeKey`
<a name="kms_DescribeKey_sap-abap_1_topic"></a>

次の例は、`DescribeKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        oo_result = lo_kms->describekey( iv_keyid = iv_key_id ).
        DATA(lo_key) = oo_result->get_keymetadata( ).
        MESSAGE 'Retrieved key information successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DisableKey`
<a name="kms_DisableKey_sap-abap_1_topic"></a>

次の例は、`DisableKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        lo_kms->disablekey( iv_keyid = iv_key_id ).
        MESSAGE 'KMS key disabled successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DisableKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `EnableKey`
<a name="kms_EnableKey_sap-abap_1_topic"></a>

次の例は、`EnableKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        lo_kms->enablekey( iv_keyid = iv_key_id ).
        MESSAGE 'KMS key enabled successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[EnableKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `EnableKeyRotation`
<a name="kms_EnableKeyRotation_sap-abap_1_topic"></a>

次の例は、`EnableKeyRotation` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        lo_kms->enablekeyrotation( iv_keyid = iv_key_id ).
        MESSAGE 'Key rotation enabled successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmsunsupportedopex.
        MESSAGE 'Operation not supported for this key.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[EnableKeyRotation](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Encrypt`
<a name="kms_Encrypt_sap-abap_1_topic"></a>

次の例は、`Encrypt` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_plaintext contains the data to encrypt
        oo_result = lo_kms->encrypt(
          iv_keyid = iv_key_id
          iv_plaintext = iv_plaintext
        ).
        MESSAGE 'Text encrypted successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS 「 SDK for SAP ABAP API リファレンス*」の[「Encrypt](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GenerateDataKey`
<a name="kms_GenerateDataKey_sap-abap_1_topic"></a>

次の例は、`GenerateDataKey` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_keyspec = 'AES_256'
        oo_result = lo_kms->generatedatakey(
          iv_keyid = iv_key_id
          iv_keyspec = 'AES_256'
        ).
        MESSAGE 'Data key generated successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GenerateDataKey](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetKeyPolicy`
<a name="kms_GetKeyPolicy_sap-abap_1_topic"></a>

次の例は、`GetKeyPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        oo_result = lo_kms->getkeypolicy(
          iv_keyid = iv_key_id
          iv_policyname = 'default'
        ).
        MESSAGE 'Retrieved key policy successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetKeyPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListAliases`
<a name="kms_ListAliases_sap-abap_1_topic"></a>

次の例は、`ListAliases` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kms->listaliases( ).
        MESSAGE 'Retrieved KMS aliases list.' TYPE 'I'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListAliases](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListGrants`
<a name="kms_ListGrants_sap-abap_1_topic"></a>

次の例は、`ListGrants` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        oo_result = lo_kms->listgrants( iv_keyid = iv_key_id ).
        MESSAGE 'Retrieved grants list.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListGrants](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListKeyPolicies`
<a name="kms_ListKeyPolicies_sap-abap_1_topic"></a>

次の例は、`ListKeyPolicies` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        oo_result = lo_kms->listkeypolicies( iv_keyid = iv_key_id ).
        MESSAGE 'Retrieved key policies list.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListKeyPolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListKeys`
<a name="kms_ListKeys_sap-abap_1_topic"></a>

次の例は、`ListKeys` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_kms->listkeys( ).
        MESSAGE 'Retrieved KMS keys list.' TYPE 'I'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListKeys](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutKeyPolicy`
<a name="kms_PutKeyPolicy_sap-abap_1_topic"></a>

次の例は、`PutKeyPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_policy = '{"Version":"2012-10-17",		 	 	  "Statement": [...]}'
        lo_kms->putkeypolicy(
          iv_keyid = iv_key_id
          iv_policyname = 'default'
          iv_policy = iv_policy
        ).
        MESSAGE 'Key policy updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmsmalformedplydocex.
        MESSAGE 'Malformed policy document.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutKeyPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ReEncrypt`
<a name="kms_ReEncrypt_sap-abap_1_topic"></a>

次の例は、`ReEncrypt` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_source_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_destination_key_id = 'arn:aws:kms:us-east-1:123456789012:key/5678dcba-56cd-78ef-90ab-5678901234cd'
        " iv_ciphertext_blob contains the encrypted data
        oo_result = lo_kms->reencrypt(
          iv_sourcekeyid = iv_source_key_id
          iv_destinationkeyid = iv_destination_key_id
          iv_ciphertextblob = iv_ciphertext_blob
        ).
        MESSAGE 'Ciphertext reencrypted successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsincorrectkeyex.
        MESSAGE 'Incorrect source key for decryption.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [ReEncrypt](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RetireGrant`
<a name="kms_RetireGrant_sap-abap_1_topic"></a>

次の例は、`RetireGrant` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_grant_token = 'AQpAM2RhZ...'
        lo_kms->retiregrant( iv_granttoken = iv_grant_token ).
        MESSAGE 'Grant retired successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Grant not found.' TYPE 'E'.
      CATCH /aws1/cx_kmsinvgranttokenex.
        MESSAGE 'Invalid grant token.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [RetireGrant](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RevokeGrant`
<a name="kms_RevokeGrant_sap-abap_1_topic"></a>

次の例は、`RevokeGrant` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_grant_id = '1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p'
        lo_kms->revokegrant(
          iv_keyid = iv_key_id
          iv_grantid = iv_grant_id
        ).
        MESSAGE 'Grant revoked successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Grant or key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmsinvalidgrantidex.
        MESSAGE 'Invalid grant ID.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [RevokeGrant](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ScheduleKeyDeletion`
<a name="kms_ScheduleKeyDeletion_sap-abap_1_topic"></a>

次の例は、`ScheduleKeyDeletion` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_pending_window_days = 7
        oo_result = lo_kms->schedulekeydeletion(
          iv_keyid = iv_key_id
          iv_pendingwindowindays = iv_pending_window_days
        ).
        MESSAGE 'Key scheduled for deletion.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ScheduleKeyDeletion](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Sign`
<a name="kms_Sign_sap-abap_1_topic"></a>

次の例は、`Sign` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab' (asymmetric key)
        " iv_message contains the message to sign
        " iv_signing_algorithm = 'RSASSA_PSS_SHA_256'
        oo_result = lo_kms->sign(
          iv_keyid = iv_key_id
          iv_message = iv_message
          iv_signingalgorithm = iv_signing_algorithm
        ).
        MESSAGE 'Message signed successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmsinvalidkeyusageex.
        MESSAGE 'Key cannot be used for signing.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS 「 SDK for SAP ABAP API リファレンス*で[サインイン](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `TagResource`
<a name="kms_TagResource_sap-abap_1_topic"></a>

次の例は、`TagResource` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_tags TYPE /aws1/cl_kmstag=>tt_taglist.

    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab'
        " iv_tag_key = 'Environment'
        " iv_tag_value = 'Production'
        APPEND NEW /aws1/cl_kmstag(
          iv_tagkey = iv_tag_key
          iv_tagvalue = iv_tag_value
        ) TO lt_tags.

        lo_kms->tagresource(
          iv_keyid = iv_key_id
          it_tags = lt_tags
        ).
        MESSAGE 'Tag added to KMS key successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmstagexception.
        MESSAGE 'Invalid tag format.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[TagResource](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateAlias`
<a name="kms_UpdateAlias_sap-abap_1_topic"></a>

次の例は、`UpdateAlias` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_alias_name = 'alias/my-key-alias'
        " iv_target_key_id = 'arn:aws:kms:us-east-1:123456789012:key/5678dcba-56cd-78ef-90ab-5678901234cd'
        lo_kms->updatealias(
          iv_aliasname = iv_alias_name
          iv_targetkeyid = iv_target_key_id
        ).
        MESSAGE 'Alias updated successfully.' TYPE 'I'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Alias or key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateAlias](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Verify`
<a name="kms_Verify_sap-abap_1_topic"></a>

次の例は、`Verify` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/kms#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_key_id = 'arn:aws:kms:us-east-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab' (asymmetric key)
        " iv_message contains the original message
        " iv_signature contains the signature to verify
        " iv_signing_algorithm = 'RSASSA_PSS_SHA_256'
        oo_result = lo_kms->verify(
          iv_keyid = iv_key_id
          iv_message = iv_message
          iv_signature = iv_signature
          iv_signingalgorithm = iv_signing_algorithm
        ).
        DATA(lv_valid) = oo_result->get_signaturevalid( ).
        IF lv_valid = abap_true.
          MESSAGE 'Signature is valid.' TYPE 'I'.
        ELSE.
          MESSAGE 'Signature is invalid.' TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_kmsdisabledexception.
        MESSAGE 'The key is disabled.' TYPE 'E'.
      CATCH /aws1/cx_kmsnotfoundexception.
        MESSAGE 'Key not found.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinvalidsigex.
        MESSAGE 'Invalid signature.' TYPE 'E'.
      CATCH /aws1/cx_kmskmsinternalex.
        MESSAGE 'An internal error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS 「 SDK for SAP ABAP API リファレンス*」の[「Verify](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Lambda の例
<a name="sap-abap_1_lambda_code_examples"></a>

次のコード例は、Lambda で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        "Create an AWS Identity and Access Management (IAM) role that grants AWS Lambda permission to write to logs."
        DATA(lv_policy_document) = `{` &&
            `"Version":"2012-10-17",		 	 	 ` &&
                  `"Statement": [` &&
                    `{` &&
                      `"Effect": "Allow",` &&
                      `"Action": [` &&
                        `"sts:AssumeRole"` &&
                      `],` &&
                      `"Principal": {` &&
                        `"Service": [` &&
                          `"lambda.amazonaws.com"` &&
                        `]` &&
                      `}` &&
                    `}` &&
                  `]` &&
                `}`.
        TRY.
            DATA(lo_create_role_output) = lo_iam->createrole(
                    iv_rolename = iv_role_name
                    iv_assumerolepolicydocument = lv_policy_document
                    iv_description = 'Grant lambda permission to write to logs' ).
            DATA(lv_role_arn) = lo_create_role_output->get_role( )->get_arn( ).
            MESSAGE 'IAM role created.' TYPE 'I'.
            WAIT UP TO 10 SECONDS.            " Make sure that the IAM role is ready for use. "
          CATCH /aws1/cx_iamentityalrdyexex.
            DATA(lo_role) = lo_iam->getrole( iv_rolename = iv_role_name ).
            lv_role_arn = lo_role->get_role( )->get_arn( ).
          CATCH /aws1/cx_iaminvalidinputex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_iammalformedplydocex.
            MESSAGE 'Policy document in the request is malformed.' TYPE 'E'.
        ENDTRY.

        TRY.
            lo_iam->attachrolepolicy(
                iv_rolename  = iv_role_name
                iv_policyarn = 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole' ).
            MESSAGE 'Attached policy to the IAM role.' TYPE 'I'.
          CATCH /aws1/cx_iaminvalidinputex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_iamnosuchentityex.
            MESSAGE 'The requested resource entity does not exist.' TYPE 'E'.
          CATCH /aws1/cx_iamplynotattachableex.
            MESSAGE 'Service role policies can only be attached to the service-linked role for their service.' TYPE 'E'.
          CATCH /aws1/cx_iamunmodableentityex.
            MESSAGE 'Service that depends on the service-linked role is not modifiable.' TYPE 'E'.
        ENDTRY.

        " Create a Lambda function and upload handler code. "
        " Lambda function performs 'increment' action on a number. "
        TRY.
            lo_lmd->createfunction(
                 iv_functionname = iv_function_name
                 iv_runtime = `python3.9`
                 iv_role = lv_role_arn
                 iv_handler = iv_handler
                 io_code = io_initial_zip_file
                 iv_description = 'AWS Lambda code example' ).
            MESSAGE 'Lambda function created.' TYPE 'I'.
          CATCH /aws1/cx_lmdcodestorageexcdex.
            MESSAGE 'Maximum total code size per account exceeded.' TYPE 'E'.
          CATCH /aws1/cx_lmdinvparamvalueex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_lmdresourcenotfoundex.
            MESSAGE 'The requested resource does not exist.' TYPE 'E'.
        ENDTRY.

        " Verify the function is in Active state "
        WHILE lo_lmd->getfunction( iv_functionname = iv_function_name )->get_configuration( )->ask_state( ) <> 'Active'.
          IF sy-index = 10.
            EXIT.               " Maximum 10 seconds. "
          ENDIF.
          WAIT UP TO 1 SECONDS.
        ENDWHILE.

        "Invoke the function with a single parameter and get results."
        TRY.
            DATA(lv_json) = /aws1/cl_rt_util=>string_to_xstring(
              `{`  &&
                `"action": "increment",`  &&
                `"number": 10` &&
              `}` ).
            DATA(lo_initial_invoke_output) = lo_lmd->invoke(
                       iv_functionname = iv_function_name
                       iv_payload = lv_json ).
            ov_initial_invoke_payload = lo_initial_invoke_output->get_payload( ).           " ov_initial_invoke_payload is returned for testing purposes. "
            DATA(lo_writer_json) = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
            CALL TRANSFORMATION id SOURCE XML ov_initial_invoke_payload RESULT XML lo_writer_json.
            DATA(lv_result) = cl_abap_codepage=>convert_from( lo_writer_json->get_output( ) ).
            MESSAGE 'Lambda function invoked.' TYPE 'I'.
          CATCH /aws1/cx_lmdinvparamvalueex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_lmdinvrequestcontex.
            MESSAGE 'Unable to parse request body as JSON.' TYPE 'E'.
          CATCH /aws1/cx_lmdresourcenotfoundex.
            MESSAGE 'The requested resource does not exist.' TYPE 'E'.
          CATCH /aws1/cx_lmdunsuppedmediatyp00.
            MESSAGE 'Invoke request body does not have JSON as its content type.' TYPE 'E'.
        ENDTRY.

        " Update the function code and configure its Lambda environment with an environment variable. "
        " Lambda function is updated to perform 'decrement' action also. "
        TRY.
            lo_lmd->updatefunctioncode(
                  iv_functionname = iv_function_name
                  iv_zipfile = io_updated_zip_file ).
            WAIT UP TO 10 SECONDS.            " Make sure that the update is completed. "
            MESSAGE 'Lambda function code updated.' TYPE 'I'.
          CATCH /aws1/cx_lmdcodestorageexcdex.
            MESSAGE 'Maximum total code size per account exceeded.' TYPE 'E'.
          CATCH /aws1/cx_lmdinvparamvalueex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_lmdresourcenotfoundex.
            MESSAGE 'The requested resource does not exist.' TYPE 'E'.
        ENDTRY.

        TRY.
            DATA lt_variables TYPE /aws1/cl_lmdenvironmentvaria00=>tt_environmentvariables.
            DATA ls_variable LIKE LINE OF lt_variables.
            ls_variable-key = 'LOG_LEVEL'.
            ls_variable-value = NEW /aws1/cl_lmdenvironmentvaria00( iv_value = 'info' ).
            INSERT ls_variable INTO TABLE lt_variables.

            lo_lmd->updatefunctionconfiguration(
                  iv_functionname = iv_function_name
                  io_environment = NEW /aws1/cl_lmdenvironment( it_variables = lt_variables ) ).
            WAIT UP TO 10 SECONDS.            " Make sure that the update is completed. "
            MESSAGE 'Lambda function configuration/settings updated.' TYPE 'I'.
          CATCH /aws1/cx_lmdinvparamvalueex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_lmdresourceconflictex.
            MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'.
          CATCH /aws1/cx_lmdresourcenotfoundex.
            MESSAGE 'The requested resource does not exist.' TYPE 'E'.
        ENDTRY.

        "Invoke the function with new parameters and get results. Display the execution log that's returned from the invocation."
        TRY.
            lv_json = /aws1/cl_rt_util=>string_to_xstring(
              `{`  &&
                `"action": "decrement",`  &&
                `"number": 10` &&
              `}` ).
            DATA(lo_updated_invoke_output) = lo_lmd->invoke(
                       iv_functionname = iv_function_name
                       iv_payload = lv_json ).
            ov_updated_invoke_payload = lo_updated_invoke_output->get_payload( ).           " ov_updated_invoke_payload is returned for testing purposes. "
            lo_writer_json = cl_sxml_string_writer=>create( type = if_sxml=>co_xt_json ).
            CALL TRANSFORMATION id SOURCE XML ov_updated_invoke_payload RESULT XML lo_writer_json.
            lv_result = cl_abap_codepage=>convert_from( lo_writer_json->get_output( ) ).
            MESSAGE 'Lambda function invoked.' TYPE 'I'.
          CATCH /aws1/cx_lmdinvparamvalueex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_lmdinvrequestcontex.
            MESSAGE 'Unable to parse request body as JSON.' TYPE 'E'.
          CATCH /aws1/cx_lmdresourcenotfoundex.
            MESSAGE 'The requested resource does not exist.' TYPE 'E'.
          CATCH /aws1/cx_lmdunsuppedmediatyp00.
            MESSAGE 'Invoke request body does not have JSON as its content type.' TYPE 'E'.
        ENDTRY.

        " List the functions for your account. "
        TRY.
            DATA(lo_list_output) = lo_lmd->listfunctions( ).
            DATA(lt_functions) = lo_list_output->get_functions( ).
            MESSAGE 'Retrieved list of Lambda functions.' TYPE 'I'.
          CATCH /aws1/cx_lmdinvparamvalueex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
        ENDTRY.

        " Delete the Lambda function. "
        TRY.
            lo_lmd->deletefunction( iv_functionname = iv_function_name ).
            MESSAGE 'Lambda function deleted.' TYPE 'I'.
          CATCH /aws1/cx_lmdinvparamvalueex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_lmdresourcenotfoundex.
            MESSAGE 'The requested resource does not exist.' TYPE 'W'.
        ENDTRY.

        " Detach role policy. "
        TRY.
            lo_iam->detachrolepolicy(
                iv_rolename  = iv_role_name
                iv_policyarn = 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole' ).
            MESSAGE 'Detached policy from the IAM role.' TYPE 'I'.
          CATCH /aws1/cx_iaminvalidinputex.
            MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
          CATCH /aws1/cx_iamnosuchentityex.
            MESSAGE 'The requested resource entity does not exist.' TYPE 'W'.
          CATCH /aws1/cx_iamplynotattachableex.
            MESSAGE 'Service role policies can only be attached to the service-linked role for their service.' TYPE 'E'.
          CATCH /aws1/cx_iamunmodableentityex.
            MESSAGE 'Service that depends on the service-linked role is not modifiable.' TYPE 'E'.
        ENDTRY.

        " Delete the IAM role. "
        TRY.
            lo_iam->deleterole( iv_rolename = iv_role_name ).
            MESSAGE 'IAM role deleted.' TYPE 'I'.
          CATCH /aws1/cx_iamnosuchentityex.
            MESSAGE 'The requested resource entity does not exist.' TYPE 'W'.
          CATCH /aws1/cx_iamunmodableentityex.
            MESSAGE 'Service that depends on the service-linked role is not modifiable.' TYPE 'E'.
        ENDTRY.

      CATCH /aws1/cx_rt_service_generic INTO lo_exception.
        DATA(lv_error) = lo_exception->get_longtext( ).
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [CreateFunction](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteFunction](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [GetFunction](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [Invoke](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [ListFunctions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [UpdateFunctionCode](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [UpdateFunctionConfiguration](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_sap-abap_1_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_lmd->createfunction(
            iv_functionname = iv_function_name
            iv_runtime = `python3.9`
            iv_role = iv_role_arn
            iv_handler = iv_handler
            io_code = io_zip_file
            iv_description = 'AWS Lambda code example' ).
        MESSAGE 'Lambda function created.' TYPE 'I'.
      CATCH /aws1/cx_lmdcodesigningcfgno00.
        MESSAGE 'Code signing configuration does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdcodestorageexcdex.
        MESSAGE 'Maximum total code size per account exceeded.' TYPE 'E'.
      CATCH /aws1/cx_lmdcodeverification00.
        MESSAGE 'Code signature failed one or more validation checks for signature mismatch or expiration.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvalidcodesigex.
        MESSAGE 'Code signature failed the integrity check.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourceconflictex.
        MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourcenotfoundex.
        MESSAGE 'The requested resource does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdserviceexception.
        MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'.
      CATCH /aws1/cx_lmdtoomanyrequestsex.
        MESSAGE 'The maximum request throughput was reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[CreateFunction](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteFunction`
<a name="lambda_DeleteFunction_sap-abap_1_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_lmd->deletefunction( iv_functionname = iv_function_name ).
        MESSAGE 'Lambda function deleted.' TYPE 'I'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourceconflictex.
        MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourcenotfoundex.
        MESSAGE 'The requested resource does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdserviceexception.
        MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'.
      CATCH /aws1/cx_lmdtoomanyrequestsex.
        MESSAGE 'The maximum request throughput was reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[DeleteFunction](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_sap-abap_1_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_lmd->getfunction( iv_functionname = iv_function_name ).       " oo_result is returned for testing purposes. "
        MESSAGE 'Lambda function information retrieved.' TYPE 'I'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdserviceexception.
        MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'.
      CATCH /aws1/cx_lmdtoomanyrequestsex.
        MESSAGE 'The maximum request throughput was reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[GetFunction](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Invoke`
<a name="lambda_Invoke_sap-abap_1_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lv_json) = /aws1/cl_rt_util=>string_to_xstring(
          `{`  &&
            `"action": "increment",`  &&
            `"number": 10` &&
          `}` ).
        oo_result = lo_lmd->invoke(                  " oo_result is returned for testing purposes. "
                 iv_functionname = iv_function_name
                 iv_payload = lv_json ).
        MESSAGE 'Lambda function invoked.' TYPE 'I'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvrequestcontex.
        MESSAGE 'Unable to parse request body as JSON.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvalidzipfileex.
        MESSAGE 'The deployment package could not be unzipped.' TYPE 'E'.
      CATCH /aws1/cx_lmdrequesttoolargeex.
        MESSAGE 'Invoke request body JSON input limit was exceeded by the request payload.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourceconflictex.
        MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourcenotfoundex.
        MESSAGE 'The requested resource does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdserviceexception.
        MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'.
      CATCH /aws1/cx_lmdtoomanyrequestsex.
        MESSAGE 'The maximum request throughput was reached.' TYPE 'E'.
      CATCH /aws1/cx_lmdunsuppedmediatyp00.
        MESSAGE 'Invoke request body does not have JSON as its content type.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[呼び出し](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_sap-abap_1_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_lmd->listfunctions( ).       " oo_result is returned for testing purposes. "
        DATA(lt_functions) = oo_result->get_functions( ).
        MESSAGE 'Retrieved list of Lambda functions.' TYPE 'I'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdserviceexception.
        MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'.
      CATCH /aws1/cx_lmdtoomanyrequestsex.
        MESSAGE 'The maximum request throughput was reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[ListFunctions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_sap-abap_1_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_lmd->updatefunctioncode(     " oo_result is returned for testing purposes. "
              iv_functionname = iv_function_name
              iv_zipfile = io_zip_file ).

        MESSAGE 'Lambda function code updated.' TYPE 'I'.
      CATCH /aws1/cx_lmdcodesigningcfgno00.
        MESSAGE 'Code signing configuration does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdcodestorageexcdex.
        MESSAGE 'Maximum total code size per account exceeded.' TYPE 'E'.
      CATCH /aws1/cx_lmdcodeverification00.
        MESSAGE 'Code signature failed one or more validation checks for signature mismatch or expiration.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvalidcodesigex.
        MESSAGE 'Code signature failed the integrity check.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourceconflictex.
        MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourcenotfoundex.
        MESSAGE 'The requested resource does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdserviceexception.
        MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'.
      CATCH /aws1/cx_lmdtoomanyrequestsex.
        MESSAGE 'The maximum request throughput was reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[UpdateFunctionCode](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_sap-abap_1_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/lmd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_lmd->updatefunctionconfiguration(     " oo_result is returned for testing purposes. "
              iv_functionname = iv_function_name
              iv_runtime = iv_runtime
              iv_description  = 'Updated Lambda function'
              iv_memorysize  = iv_memory_size ).

        MESSAGE 'Lambda function configuration/settings updated.' TYPE 'I'.
      CATCH /aws1/cx_lmdcodesigningcfgno00.
        MESSAGE 'Code signing configuration does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdcodeverification00.
        MESSAGE 'Code signature failed one or more validation checks for signature mismatch or expiration.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvalidcodesigex.
        MESSAGE 'Code signature failed the integrity check.' TYPE 'E'.
      CATCH /aws1/cx_lmdinvparamvalueex.
        MESSAGE 'The request contains a non-valid parameter.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourceconflictex.
        MESSAGE 'Resource already exists or another operation is in progress.' TYPE 'E'.
      CATCH /aws1/cx_lmdresourcenotfoundex.
        MESSAGE 'The requested resource does not exist.' TYPE 'E'.
      CATCH /aws1/cx_lmdserviceexception.
        MESSAGE 'An internal problem was encountered by the AWS Lambda service.' TYPE 'E'.
      CATCH /aws1/cx_lmdtoomanyrequestsex.
        MESSAGE 'The maximum request throughput was reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP の API リファレンス*」の「[UpdateFunctionConfiguration](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Organizations の例
<a name="sap-abap_1_organizations_code_examples"></a>

次のコード例は、 AWS SDK for SAP ABAP with Organizations を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AttachPolicy`
<a name="organizations_AttachPolicy_sap-abap_1_topic"></a>

次の例は、`AttachPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_org->attachpolicy(
          iv_policyid = iv_policy_id
          iv_targetid = iv_target_id ).
        MESSAGE 'Policy attached to target.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to attach the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgtargetnotfoundex.
        MESSAGE 'The specified target does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgduplicateplyatta00.
        MESSAGE 'The policy is already attached to the target.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[AttachPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreatePolicy`
<a name="organizations_CreatePolicy_sap-abap_1_topic"></a>

次の例は、`CreatePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_org->createpolicy(       " oo_result is returned for testing purposes. "
          iv_name        = iv_policy_name
          iv_description = iv_policy_description
          iv_content     = iv_policy_content
          iv_type        = iv_policy_type ).
        MESSAGE 'Policy created.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to create a policy.' TYPE 'E'.
      CATCH /aws1/cx_orgduplicatepolicyex.
        MESSAGE 'A policy with this name already exists.' TYPE 'E'.
      CATCH /aws1/cx_orgmalformedplydocex.
        MESSAGE 'The policy content is malformed.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreatePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeletePolicy`
<a name="organizations_DeletePolicy_sap-abap_1_topic"></a>

次の例は、`DeletePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_org->deletepolicy(
          iv_policyid = iv_policy_id ).
        MESSAGE 'Policy deleted.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to delete the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicyinuseex.
        MESSAGE 'The policy is still attached to one or more targets.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeletePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribePolicy`
<a name="organizations_DescribePolicy_sap-abap_1_topic"></a>

次の例は、`DescribePolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_org->describepolicy(     " oo_result is returned for testing purposes. "
          iv_policyid = iv_policy_id ).
        DATA(lo_policy) = oo_result->get_policy( ).
        MESSAGE 'Retrieved policy details.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to describe the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribePolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetachPolicy`
<a name="organizations_DetachPolicy_sap-abap_1_topic"></a>

次の例は、`DetachPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_org->detachpolicy(
          iv_policyid = iv_policy_id
          iv_targetid = iv_target_id ).
        MESSAGE 'Policy detached from target.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to detach the policy.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotfoundex.
        MESSAGE 'The specified policy does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgtargetnotfoundex.
        MESSAGE 'The specified target does not exist.' TYPE 'E'.
      CATCH /aws1/cx_orgpolicynotattex.
        MESSAGE 'The policy is not attached to the target.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetachPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListPolicies`
<a name="organizations_ListPolicies_sap-abap_1_topic"></a>

次の例は、`ListPolicies` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/org#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_org->listpolicies(       " oo_result is returned for testing purposes. "
          iv_filter = iv_filter ).
        DATA(lt_policies) = oo_result->get_policies( ).
        MESSAGE 'Retrieved list of policies.' TYPE 'I'.
      CATCH /aws1/cx_orgaccessdeniedex.
        MESSAGE 'You do not have permission to list policies.' TYPE 'E'.
      CATCH /aws1/cx_orgawsorgsnotinuseex.
        MESSAGE 'Your account is not a member of an organization.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListPolicies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Pinpoint の例
<a name="sap-abap_1_pinpoint_code_examples"></a>

次のコード例は、Amazon Pinpoint で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `SendMessages`
<a name="pinpoint_SendMessages_sap-abap_1_topic"></a>

次の例は、`SendMessages` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ppt#code-examples)での設定と実行の方法を確認してください。
E メールメッセージを送信します。  

```
    " Build the addresses map from the list of to_addresses
    DATA lt_addresses TYPE /aws1/cl_pptaddressconf=>tt_mapofaddressconfiguration.
    LOOP AT it_to_addresses INTO DATA(lo_address).
      INSERT VALUE /aws1/cl_pptaddressconf=>ts_mapofaddressconf_maprow(
        key = lo_address->get_value( )
        value = NEW /aws1/cl_pptaddressconf( iv_channeltype = 'EMAIL' )
      ) INTO TABLE lt_addresses.
    ENDLOOP.

    " Send the email message
    DATA(lo_result) = lo_ppt->sendmessages(
      iv_applicationid = iv_app_id
      io_messagerequest = NEW /aws1/cl_pptmessagerequest(
        it_addresses = lt_addresses
        io_messageconfiguration = NEW /aws1/cl_pptdirectmessageconf(
          io_emailmessage = NEW /aws1/cl_pptemailmessage(
            iv_fromaddress = iv_sender
            io_simpleemail = NEW /aws1/cl_pptsimpleemail(
              io_subject = NEW /aws1/cl_pptsimpleemailpart(
                iv_charset = iv_char_set
                iv_data = iv_subject
              )
              io_htmlpart = NEW /aws1/cl_pptsimpleemailpart(
                iv_charset = iv_char_set
                iv_data = iv_html_message
              )
              io_textpart = NEW /aws1/cl_pptsimpleemailpart(
                iv_charset = iv_char_set
                iv_data = iv_text_message
              )
            )
          )
        )
      )
    ).

    " Extract message IDs from response
    DATA(lo_message_response) = lo_result->get_messageresponse( ).
    ot_message_ids = lo_message_response->get_result( ).

    MESSAGE 'Email message sent successfully.' TYPE 'I'.
```
SMS メッセージを送信します。  

```
    " Build the addresses map for the destination number
    DATA lt_addresses TYPE /aws1/cl_pptaddressconf=>tt_mapofaddressconfiguration.
    INSERT VALUE /aws1/cl_pptaddressconf=>ts_mapofaddressconf_maprow(
      key = iv_destination_number
      value = NEW /aws1/cl_pptaddressconf( iv_channeltype = 'SMS' )
    ) INTO TABLE lt_addresses.

    " Send the SMS message
    DATA(lo_result) = lo_ppt->sendmessages(
      iv_applicationid = iv_app_id
      io_messagerequest = NEW /aws1/cl_pptmessagerequest(
        it_addresses = lt_addresses
        io_messageconfiguration = NEW /aws1/cl_pptdirectmessageconf(
          io_smsmessage = NEW /aws1/cl_pptsmsmessage(
            iv_body = iv_message
            iv_messagetype = iv_message_type
            iv_originationnumber = iv_origination_number
          )
        )
      )
    ).

    " Extract message ID from response
    DATA(lo_message_response) = lo_result->get_messageresponse( ).
    DATA(lt_results) = lo_message_response->get_result( ).
    LOOP AT lt_results INTO DATA(ls_result).
      IF ls_result-key = iv_destination_number.
        ov_message_id = ls_result-value->get_messageid( ).
        EXIT.
      ENDIF.
    ENDLOOP.

    MESSAGE 'SMS message sent successfully.' TYPE 'I'.
```
既存の E メールテンプレートを使用して E メールメッセージを送信します。  

```
    " Build the addresses map from the list of to_addresses
    DATA lt_addresses TYPE /aws1/cl_pptaddressconf=>tt_mapofaddressconfiguration.
    LOOP AT it_to_addresses INTO DATA(lo_address).
      INSERT VALUE /aws1/cl_pptaddressconf=>ts_mapofaddressconf_maprow(
        key = lo_address->get_value( )
        value = NEW /aws1/cl_pptaddressconf( iv_channeltype = 'EMAIL' )
      ) INTO TABLE lt_addresses.
    ENDLOOP.

    " Send the email message using a template
    DATA(lo_result) = lo_ppt->sendmessages(
      iv_applicationid = iv_app_id
      io_messagerequest = NEW /aws1/cl_pptmessagerequest(
        it_addresses = lt_addresses
        io_messageconfiguration = NEW /aws1/cl_pptdirectmessageconf(
          io_emailmessage = NEW /aws1/cl_pptemailmessage(
            iv_fromaddress = iv_sender
          )
        )
        io_templateconfiguration = NEW /aws1/cl_ppttemplateconf(
          io_emailtemplate = NEW /aws1/cl_ppttemplate(
            iv_name = iv_template_name
            iv_version = iv_template_version
          )
        )
      )
    ).

    " Extract message IDs from response
    DATA(lo_message_response) = lo_result->get_messageresponse( ).
    ot_message_ids = lo_message_response->get_result( ).

    MESSAGE 'Templated email message sent successfully.' TYPE 'I'.
```
既存の SMS テンプレートを使用してテキストメッセージを送信します。  

```
    " Build the addresses map for the destination number
    DATA lt_addresses TYPE /aws1/cl_pptaddressconf=>tt_mapofaddressconfiguration.
    INSERT VALUE /aws1/cl_pptaddressconf=>ts_mapofaddressconf_maprow(
      key = iv_destination_number
      value = NEW /aws1/cl_pptaddressconf( iv_channeltype = 'SMS' )
    ) INTO TABLE lt_addresses.

    " Send the SMS message using a template
    DATA(lo_result) = lo_ppt->sendmessages(
      iv_applicationid = iv_app_id
      io_messagerequest = NEW /aws1/cl_pptmessagerequest(
        it_addresses = lt_addresses
        io_messageconfiguration = NEW /aws1/cl_pptdirectmessageconf(
          io_smsmessage = NEW /aws1/cl_pptsmsmessage(
            iv_messagetype = iv_message_type
            iv_originationnumber = iv_origination_number
          )
        )
        io_templateconfiguration = NEW /aws1/cl_ppttemplateconf(
          io_smstemplate = NEW /aws1/cl_ppttemplate(
            iv_name = iv_template_name
            iv_version = iv_template_version
          )
        )
      )
    ).

    " Extract message ID from response
    DATA(lo_message_response) = lo_result->get_messageresponse( ).
    DATA(lt_results) = lo_message_response->get_result( ).
    LOOP AT lt_results INTO DATA(ls_result).
      IF ls_result-key = iv_destination_number.
        ov_message_id = ls_result-value->get_messageid( ).
        EXIT.
      ENDIF.
    ENDLOOP.

    MESSAGE 'Templated SMS message sent successfully.' TYPE 'I'.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SendMessages](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Pinpoint SMS および音声 API の例
<a name="sap-abap_1_pinpoint-sms-voice_code_examples"></a>

次のコード例は、Amazon Pinpoint SMS および音声 API で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateConfigurationSet`
<a name="pinpoint-sms-voice_CreateConfigurationSet_sap-abap_1_topic"></a>

次の例は、`CreateConfigurationSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create a new configuration set
        lo_pps->createconfigurationset(
          iv_configurationsetname = iv_configuration_set_name    " e.g., 'my-config-set'
        ).

        MESSAGE 'Configuration set created successfully.' TYPE 'I'.

      CATCH /aws1/cx_ppsalreadyexistsex INTO DATA(lo_already_exists_ex).
        MESSAGE lo_already_exists_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_already_exists_ex.
      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppslimitexceededex INTO DATA(lo_limit_exceeded_ex).
        MESSAGE lo_limit_exceeded_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_limit_exceeded_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateConfigurationSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateConfigurationSetEventDestination`
<a name="pinpoint-sms-voice_CreateConfigurationSetEventDestination_sap-abap_1_topic"></a>

次の例は、`CreateConfigurationSetEventDestination` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create event destination for the configuration set
        lo_pps->createconfseteventdst(
          iv_configurationsetname = iv_configuration_set_name    " e.g., 'my-config-set'
          iv_eventdestinationname = iv_event_destination_name    " e.g., 'my-event-dest'
          io_eventdestination = io_event_destination
        ).

        MESSAGE 'Event destination created successfully.' TYPE 'I'.

      CATCH /aws1/cx_ppsalreadyexistsex INTO DATA(lo_already_exists_ex).
        MESSAGE lo_already_exists_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_already_exists_ex.
      CATCH /aws1/cx_ppsnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found_ex.
      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppslimitexceededex INTO DATA(lo_limit_exceeded_ex).
        MESSAGE lo_limit_exceeded_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_limit_exceeded_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateConfigurationSetEventDestination](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteConfigurationSet`
<a name="pinpoint-sms-voice_DeleteConfigurationSet_sap-abap_1_topic"></a>

次の例は、`DeleteConfigurationSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Delete the configuration set
        lo_pps->deleteconfigurationset(
          iv_configurationsetname = iv_configuration_set_name    " e.g., 'my-config-set'
        ).

        MESSAGE 'Configuration set deleted successfully.' TYPE 'I'.

      CATCH /aws1/cx_ppsnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found_ex.
      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteConfigurationSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteConfigurationSetEventDestination`
<a name="pinpoint-sms-voice_DeleteConfigurationSetEventDestination_sap-abap_1_topic"></a>

次の例は、`DeleteConfigurationSetEventDestination` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Delete the event destination
        lo_pps->deleteconfseteventdst(
          iv_configurationsetname = iv_configuration_set_name    " e.g., 'my-config-set'
          iv_eventdestinationname = iv_event_destination_name    " e.g., 'my-event-dest'
        ).

        MESSAGE 'Event destination deleted successfully.' TYPE 'I'.

      CATCH /aws1/cx_ppsnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found_ex.
      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteConfigurationSetEventDestination](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetConfigurationSetEventDestinations`
<a name="pinpoint-sms-voice_GetConfigurationSetEventDestinations_sap-abap_1_topic"></a>

次の例は、`GetConfigurationSetEventDestinations` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Get event destinations for the configuration set
        oo_result = lo_pps->getconfseteventdestinations(
          iv_configurationsetname = iv_configuration_set_name    " e.g., 'my-config-set'
        ).

        " Process the event destinations
        LOOP AT oo_result->get_eventdestinations( ) INTO DATA(lo_event_dest).
          DATA(lv_dest_name) = lo_event_dest->get_name( ).
          DATA(lv_enabled) = lo_event_dest->get_enabled( ).

          MESSAGE |Event destination: { lv_dest_name }, Enabled: { lv_enabled }| TYPE 'I'.

          " Check for CloudWatch Logs destination
          DATA(lo_cloudwatch_dest) = lo_event_dest->get_cloudwatchlogsdst( ).
          IF lo_cloudwatch_dest IS NOT INITIAL.
            DATA(lv_log_group_arn) = lo_cloudwatch_dest->get_loggrouparn( ).
            MESSAGE |  CloudWatch Logs destination: { lv_log_group_arn }| TYPE 'I'.
          ENDIF.

          " Check for Kinesis Firehose destination
          DATA(lo_firehose_dest) = lo_event_dest->get_kinesisfirehosedst( ).
          IF lo_firehose_dest IS NOT INITIAL.
            DATA(lv_delivery_stream) = lo_firehose_dest->get_deliverystreamarn( ).
            MESSAGE |  Kinesis Firehose destination: { lv_delivery_stream }| TYPE 'I'.
          ENDIF.

          " Check for SNS destination
          DATA(lo_sns_dest) = lo_event_dest->get_snsdestination( ).
          IF lo_sns_dest IS NOT INITIAL.
            DATA(lv_topic_arn) = lo_sns_dest->get_topicarn( ).
            MESSAGE |  SNS destination: { lv_topic_arn }| TYPE 'I'.
          ENDIF.
        ENDLOOP.

      CATCH /aws1/cx_ppsnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found_ex.
      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetConfigurationSetEventDestinations](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListConfigurationSets`
<a name="pinpoint-sms-voice_ListConfigurationSets_sap-abap_1_topic"></a>

次の例は、`ListConfigurationSets` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " List all configuration sets
        oo_result = lo_pps->listconfigurationsets(
          iv_nexttoken = iv_next_token    " Optional: Token for pagination
          iv_pagesize = iv_page_size      " Optional: Number of results per page, e.g., '10'
        ).

        " Process the configuration sets
        LOOP AT oo_result->get_configurationsets( ) INTO DATA(lo_config_set).
          DATA(lv_config_set_name) = lo_config_set->get_value( ).
          MESSAGE |Configuration set: { lv_config_set_name }| TYPE 'I'.
        ENDLOOP.

        " Check if there are more results
        DATA(lv_next_token) = oo_result->get_nexttoken( ).
        IF lv_next_token IS NOT INITIAL.
          MESSAGE |More results available. Next token: { lv_next_token }| TYPE 'I'.
        ENDIF.

      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListConfigurationSets](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendVoiceMessage`
<a name="pinpoint-sms-voice_SendVoiceMessage_sap-abap_1_topic"></a>

次の例は、`SendVoiceMessage` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create SSML message type object with voice parameters
        DATA(lo_ssml_message) = NEW /aws1/cl_ppsssmlmessagetype(
          iv_languagecode = iv_language_code    " e.g., 'en-US'
          iv_voiceid = iv_voice_id              " e.g., 'Matthew'
          iv_text = iv_ssml_message             " SSML formatted message text
        ).

        " Create voice message content with the SSML message
        DATA(lo_content) = NEW /aws1/cl_ppsvoicemessagecont(
          io_ssmlmessage = lo_ssml_message
        ).

        " Send the voice message
        DATA(lo_result) = lo_pps->sendvoicemessage(
          iv_originationphonenumber = iv_origination_number  " e.g., '+12065550110'
          iv_callerid = iv_caller_id                         " e.g., '+12065550199'
          iv_destinationphonenumber = iv_destination_number  " e.g., '+12065550142'
          io_content = lo_content
        ).

        " Retrieve the message ID from the response
        ov_message_id = lo_result->get_messageid( ).

        MESSAGE 'Voice message sent successfully.' TYPE 'I'.

      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[SendVoiceMessage](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateConfigurationSetEventDestination`
<a name="pinpoint-sms-voice_UpdateConfigurationSetEventDestination_sap-abap_1_topic"></a>

次の例は、`UpdateConfigurationSetEventDestination` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/pps#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Update the event destination
        lo_pps->updateconfseteventdst(
          iv_configurationsetname = iv_configuration_set_name    " e.g., 'my-config-set'
          iv_eventdestinationname = iv_event_destination_name    " e.g., 'my-event-dest'
          io_eventdestination = io_event_destination
        ).

        MESSAGE 'Event destination updated successfully.' TYPE 'I'.

      CATCH /aws1/cx_ppsnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_not_found_ex.
      CATCH /aws1/cx_ppsbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_ppsinternalsvcerrorex INTO DATA(lo_internal_error_ex).
        MESSAGE lo_internal_error_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_internal_error_ex.
      CATCH /aws1/cx_ppstoomanyrequestsex INTO DATA(lo_too_many_requests_ex).
        MESSAGE lo_too_many_requests_ex->get_text( ) TYPE 'I'.
        RAISE EXCEPTION lo_too_many_requests_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateConfigurationSetEventDestination](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Polly の例
<a name="sap-abap_1_polly_code_examples"></a>

次のコード例は、Amazon Polly で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `DeleteLexicon`
<a name="polly_DeleteLexicon_sap-abap_1_topic"></a>

次の例は、`DeleteLexicon` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ply->deletelexicon( iv_name ).
        MESSAGE 'Lexicon deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_plylexiconnotfoundex.
        MESSAGE 'Lexicon not found.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteLexicon](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeVoices`
<a name="polly_DescribeVoices_sap-abap_1_topic"></a>

次の例は、`DescribeVoices` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Only pass optional parameters if they have values
        IF iv_engine IS NOT INITIAL AND iv_language IS NOT INITIAL.
          oo_result = lo_ply->describevoices(
            iv_engine = iv_engine
            iv_languagecode = iv_language ).
        ELSEIF iv_engine IS NOT INITIAL.
          oo_result = lo_ply->describevoices(
            iv_engine = iv_engine ).
        ELSEIF iv_language IS NOT INITIAL.
          oo_result = lo_ply->describevoices(
            iv_languagecode = iv_language ).
        ELSE.
          oo_result = lo_ply->describevoices( ).
        ENDIF.
        MESSAGE 'Retrieved voice metadata.' TYPE 'I'.
      CATCH /aws1/cx_plyinvalidnexttokenex.
        MESSAGE 'The NextToken is invalid.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeVoices](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetLexicon`
<a name="polly_GetLexicon_sap-abap_1_topic"></a>

次の例は、`GetLexicon` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ply->getlexicon( iv_name ).
        DATA(lo_lexicon) = oo_result->get_lexicon( ).
        IF lo_lexicon IS BOUND.
          DATA(lv_lex_name) = lo_lexicon->get_name( ).
          MESSAGE |Retrieved lexicon: { lv_lex_name }| TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_plylexiconnotfoundex.
        MESSAGE 'Lexicon not found.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetLexicon](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetSpeechSynthesisTask`
<a name="polly_GetSpeechSynthesisTask_sap-abap_1_topic"></a>

次の例は、`GetSpeechSynthesisTask` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ply->getspeechsynthesistask( iv_task_id ).
        DATA(lo_task) = oo_result->get_synthesistask( ).
        IF lo_task IS BOUND.
          DATA(lv_status) = lo_task->get_taskstatus( ).
          MESSAGE |Task status: { lv_status }| TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_plyinvalidtaskidex.
        MESSAGE 'Invalid task ID.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
      CATCH /aws1/cx_plysynthesistsknotf00.
        MESSAGE 'Synthesis task not found.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetSpeechSynthesisTask](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListLexicons`
<a name="polly_ListLexicons_sap-abap_1_topic"></a>

次の例は、`ListLexicons` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ply->listlexicons( ).
        DATA(lt_lexicons) = oo_result->get_lexicons( ).
        DATA(lv_count) = lines( lt_lexicons ).
        MESSAGE |Found { lv_count } lexicons| TYPE 'I'.
      CATCH /aws1/cx_plyinvalidnexttokenex.
        MESSAGE 'Invalid NextToken.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListLexicons](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListSpeechSynthesisTasks`
<a name="polly_ListSpeechSynthesisTasks_sap-abap_1_topic"></a>

次の例は、`ListSpeechSynthesisTasks` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Only pass optional parameters if they have values
        IF iv_max_results IS NOT INITIAL AND iv_status IS NOT INITIAL.
          oo_result = lo_ply->listspeechsynthesistasks(
            iv_maxresults = iv_max_results
            iv_status = iv_status ).
        ELSEIF iv_max_results IS NOT INITIAL.
          oo_result = lo_ply->listspeechsynthesistasks(
            iv_maxresults = iv_max_results ).
        ELSEIF iv_status IS NOT INITIAL.
          oo_result = lo_ply->listspeechsynthesistasks(
            iv_status = iv_status ).
        ELSE.
          oo_result = lo_ply->listspeechsynthesistasks( ).
        ENDIF.
        DATA(lt_tasks) = oo_result->get_synthesistasks( ).
        DATA(lv_count) = lines( lt_tasks ).
        MESSAGE |Found { lv_count } synthesis tasks| TYPE 'I'.
      CATCH /aws1/cx_plyinvalidnexttokenex.
        MESSAGE 'Invalid NextToken.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListSpeechSynthesisTasks](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutLexicon`
<a name="polly_PutLexicon_sap-abap_1_topic"></a>

次の例は、`PutLexicon` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ply->putlexicon(
          iv_name = iv_name
          iv_content = iv_content ).
        MESSAGE 'Lexicon created successfully.' TYPE 'I'.
      CATCH /aws1/cx_plyinvalidlexiconex.
        MESSAGE 'Invalid lexicon.' TYPE 'E'.
      CATCH /aws1/cx_plylexiconsizeexcdex.
        MESSAGE 'Lexicon size exceeded.' TYPE 'E'.
      CATCH /aws1/cx_plymaxlexemelengthe00.
        MESSAGE 'Maximum lexeme length exceeded.' TYPE 'E'.
      CATCH /aws1/cx_plymaxlexiconsnoexc00.
        MESSAGE 'Maximum number of lexicons exceeded.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
      CATCH /aws1/cx_plyunsuppedplsalpha00.
        MESSAGE 'Unsupported PLS alphabet.' TYPE 'E'.
      CATCH /aws1/cx_plyunsuppedplslangu00.
        MESSAGE 'Unsupported PLS language.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutLexicon](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartSpeechSynthesisTask`
<a name="polly_StartSpeechSynthesisTask_sap-abap_1_topic"></a>

次の例は、`StartSpeechSynthesisTask` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Only pass optional parameters if they have values
        IF iv_lang_code IS NOT INITIAL AND iv_s3_key_prefix IS NOT INITIAL.
          oo_result = lo_ply->startspeechsynthesistask(
            iv_engine = iv_engine
            iv_outputformat = iv_audio_format
            iv_outputs3bucketname = iv_s3_bucket
            iv_outputs3keyprefix = iv_s3_key_prefix
            iv_text = iv_text
            iv_voiceid = iv_voice_id
            iv_languagecode = iv_lang_code ).
        ELSEIF iv_lang_code IS NOT INITIAL.
          oo_result = lo_ply->startspeechsynthesistask(
            iv_engine = iv_engine
            iv_outputformat = iv_audio_format
            iv_outputs3bucketname = iv_s3_bucket
            iv_text = iv_text
            iv_voiceid = iv_voice_id
            iv_languagecode = iv_lang_code ).
        ELSEIF iv_s3_key_prefix IS NOT INITIAL.
          oo_result = lo_ply->startspeechsynthesistask(
            iv_engine = iv_engine
            iv_outputformat = iv_audio_format
            iv_outputs3bucketname = iv_s3_bucket
            iv_outputs3keyprefix = iv_s3_key_prefix
            iv_text = iv_text
            iv_voiceid = iv_voice_id ).
        ELSE.
          oo_result = lo_ply->startspeechsynthesistask(
            iv_engine = iv_engine
            iv_outputformat = iv_audio_format
            iv_outputs3bucketname = iv_s3_bucket
            iv_text = iv_text
            iv_voiceid = iv_voice_id ).
        ENDIF.
        MESSAGE 'Speech synthesis task started.' TYPE 'I'.
      CATCH /aws1/cx_plyinvalids3bucketex.
        MESSAGE 'Invalid S3 bucket.' TYPE 'E'.
      CATCH /aws1/cx_plyinvalidssmlex.
        MESSAGE 'Invalid SSML.' TYPE 'E'.
      CATCH /aws1/cx_plylexiconnotfoundex.
        MESSAGE 'Lexicon not found.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
      CATCH /aws1/cx_plytextlengthexcdex.
        MESSAGE 'Text length exceeded maximum.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartSpeechSynthesisTask](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SynthesizeSpeech`
<a name="polly_SynthesizeSpeech_sap-abap_1_topic"></a>

次の例は、`SynthesizeSpeech` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ply#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Only pass optional language code if it has a value
        IF iv_lang_code IS NOT INITIAL.
          oo_result = lo_ply->synthesizespeech(
            iv_engine = iv_engine
            iv_outputformat = iv_output_fmt
            iv_text = iv_text
            iv_voiceid = iv_voice_id
            iv_languagecode = iv_lang_code ).
        ELSE.
          oo_result = lo_ply->synthesizespeech(
            iv_engine = iv_engine
            iv_outputformat = iv_output_fmt
            iv_text = iv_text
            iv_voiceid = iv_voice_id ).
        ENDIF.
        MESSAGE 'Speech synthesized successfully.' TYPE 'I'.
      CATCH /aws1/cx_plyinvalidssmlex.
        MESSAGE 'Invalid SSML.' TYPE 'E'.
      CATCH /aws1/cx_plylexiconnotfoundex.
        MESSAGE 'Lexicon not found.' TYPE 'E'.
      CATCH /aws1/cx_plyservicefailureex.
        MESSAGE 'Service failure occurred.' TYPE 'E'.
      CATCH /aws1/cx_plytextlengthexcdex.
        MESSAGE 'Text length exceeded maximum.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SynthesizeSpeech](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon RDS の例
<a name="sap-abap_1_rds_code_examples"></a>

次のコード例は、Amazon RDS で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDBParameterGroup`
<a name="rds_CreateDBParameterGroup_sap-abap_1_topic"></a>

次の例は、`CreateDBParameterGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_dbparametergroupname   = 'mydbparametergroup'
    " iv_dbparametergroupfamily = 'mysql8.0'
    " iv_description            = 'My custom DB parameter group for MySQL 8.0'
    TRY.
        oo_result = lo_rds->createdbparametergroup(
          iv_dbparametergroupname   = iv_dbparametergroupname
          iv_dbparametergroupfamily = iv_dbparametergroupfamily
          iv_description            = iv_description ).
        MESSAGE 'DB parameter group created.' TYPE 'I'.
      CATCH /aws1/cx_rdsdbparmgralrexfault.
        MESSAGE 'DB parameter group already exists.' TYPE 'I'.
      CATCH /aws1/cx_rdsdbprmgrquotaexcd00.
        MESSAGE 'DB parameter group quota exceeded.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateDBParameterGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteDBParameterGroup`
<a name="rds_DeleteDBParameterGroup_sap-abap_1_topic"></a>

次の例は、`DeleteDBParameterGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_dbparametergroupname = 'mydbparametergroup'
    TRY.
        lo_rds->deletedbparametergroup(
          iv_dbparametergroupname = iv_dbparametergroupname ).
        MESSAGE 'DB parameter group deleted.' TYPE 'I'.
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
        MESSAGE 'DB parameter group not found.' TYPE 'I'.
      CATCH /aws1/cx_rdsinvdbprmgrstatef00.
        MESSAGE 'DB parameter group is in an invalid state.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteDBParameterGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDBEngineVersions`
<a name="rds_DescribeDBEngineVersions_sap-abap_1_topic"></a>

次の例は、`DescribeDBEngineVersions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_engine                 = 'mysql'
    " iv_dbparametergroupfamily = 'mysql8.0' (optional - filters by parameter group family)
    TRY.
        oo_result = lo_rds->describedbengineversions(
          iv_engine                 = iv_engine
          iv_dbparametergroupfamily = iv_dbparametergroupfamily ).
        DATA(lv_version_count) = lines( oo_result->get_dbengineversions( ) ).
        MESSAGE |Retrieved { lv_version_count } engine versions.| TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeDBEngineVersions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_sap-abap_1_topic"></a>

次の例は、`DescribeDBParameterGroups` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_dbparametergroupname = 'mydbparametergroup'
    TRY.
        oo_result = lo_rds->describedbparametergroups(
          iv_dbparametergroupname = iv_dbparametergroupname ).
        MESSAGE 'DB parameter group retrieved.' TYPE 'I'.
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
        MESSAGE 'DB parameter group not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeDBParameterGroups](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_sap-abap_1_topic"></a>

次の例は、`DescribeDBParameters` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_dbparametergroupname = 'mydbparametergroup'
    " iv_source               = 'user' (optional - filters by parameter source)
    TRY.
        oo_result = lo_rds->describedbparameters(
          iv_dbparametergroupname = iv_dbparametergroupname
          iv_source               = iv_source ).
        DATA(lv_param_count) = lines( oo_result->get_parameters( ) ).
        MESSAGE |Retrieved { lv_param_count } parameters.| TYPE 'I'.
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
        MESSAGE 'DB parameter group not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeDBParameters](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="rds_DescribeOrderableDBInstanceOptions_sap-abap_1_topic"></a>

次の例は、`DescribeOrderableDBInstanceOptions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_engine        = 'mysql'
    " iv_engineversion = '8.0.35'
    TRY.
        oo_result = lo_rds->descrorderabledbinstoptions(
          iv_engine        = iv_engine
          iv_engineversion = iv_engineversion ).
        DATA(lv_option_count) = lines( oo_result->get_orderabledbinstoptions( ) ).
        MESSAGE |Retrieved { lv_option_count } orderable DB instance options.| TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeOrderableDBInstanceOptions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ModifyDBParameterGroup`
<a name="rds_ModifyDBParameterGroup_sap-abap_1_topic"></a>

次の例は、`ModifyDBParameterGroup` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rds#code-examples)での設定と実行の方法を確認してください。

```
    " iv_dbparametergroupname = 'mydbparametergroup'
    " it_parameters - table containing parameter objects with:
    "   - parametername = 'max_connections'
    "   - parametervalue = '100'
    "   - applymethod = 'immediate' or 'pending-reboot'
    TRY.
        oo_result = lo_rds->modifydbparametergroup(
          iv_dbparametergroupname = iv_dbparametergroupname
          it_parameters           = it_parameters ).
        MESSAGE 'DB parameter group modified.' TYPE 'I'.
      CATCH /aws1/cx_rdsdbprmgrnotfndfault.
        MESSAGE 'DB parameter group not found.' TYPE 'I'.
      CATCH /aws1/cx_rdsinvdbprmgrstatef00.
        MESSAGE 'DB parameter group is in an invalid state.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ModifyDBParameterGroup](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Redshift の例
<a name="sap-abap_1_redshift_code_examples"></a>

次のコード例は、Amazon Redshift で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateCluster`
<a name="redshift_CreateCluster_sap-abap_1_topic"></a>

次の例は、`CreateCluster` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsh#code-examples)での設定と実行の方法を確認してください。
クラスターを作成します。  

```
    TRY.
        " Example values: iv_cluster_identifier = 'my-redshift-cluster'
        " Example values: iv_node_type = 'ra3.4xlarge'
        " Example values: iv_master_username = 'awsuser'
        " Example values: iv_master_password = 'AwsUser1000'
        " Example values: iv_publicly_accessible = abap_true
        " Example values: iv_number_of_nodes = 2
        oo_result = lo_rsh->createcluster(
          iv_clusteridentifier = iv_cluster_identifier
          iv_nodetype = iv_node_type
          iv_masterusername = iv_master_username
          iv_masteruserpassword = iv_master_password
          iv_publiclyaccessible = iv_publicly_accessible
          iv_numberofnodes = iv_number_of_nodes
        ).
        MESSAGE 'Redshift cluster created successfully.' TYPE 'I'.
      CATCH /aws1/cx_rshclustalrdyexfault.
        MESSAGE 'Cluster already exists.' TYPE 'I'.
      CATCH /aws1/cx_rshclstquotaexcdfault.
        MESSAGE 'Cluster quota exceeded.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateCluster](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteCluster`
<a name="redshift_DeleteCluster_sap-abap_1_topic"></a>

次の例は、`DeleteCluster` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsh#code-examples)での設定と実行の方法を確認してください。
クラスターを削除します。  

```
    TRY.
        " Example values: iv_cluster_identifier = 'my-redshift-cluster'
        lo_rsh->deletecluster(
          iv_clusteridentifier = iv_cluster_identifier
          iv_skipfinalclustersnapshot = abap_true
        ).
        MESSAGE 'Redshift cluster deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_rshclustnotfoundfault.
        MESSAGE 'Cluster not found.' TYPE 'I'.
      CATCH /aws1/cx_rshinvcluststatefault.
        MESSAGE 'Invalid cluster state for deletion.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteCluster](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeClusters`
<a name="redshift_DescribeClusters_sap-abap_1_topic"></a>

次の例は、`DescribeClusters` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsh#code-examples)での設定と実行の方法を確認してください。
クラスターを記述する  

```
    TRY.
        " Example values: iv_cluster_identifier = 'my-redshift-cluster' (optional)
        oo_result = lo_rsh->describeclusters(
          iv_clusteridentifier = iv_cluster_identifier
        ).
        lt_clusters = oo_result->get_clusters( ).
        lv_cluster_count = lines( lt_clusters ).
        MESSAGE |Retrieved { lv_cluster_count } cluster(s).| TYPE 'I'.
      CATCH /aws1/cx_rshclustnotfoundfault.
        MESSAGE 'Cluster not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeClusters](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeStatement`
<a name="redshift_DescribeStatement_sap-abap_1_topic"></a>

次の例は、`DescribeStatement` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example values: iv_statement_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
        oo_result = lo_rsd->describestatement(
          iv_id = iv_statement_id
        ).
        lv_status = oo_result->get_status( ).
        MESSAGE |Statement status: { lv_status }| TYPE 'I'.
      CATCH /aws1/cx_rsdresourcenotfoundex.
        MESSAGE 'Statement not found.' TYPE 'I'.
      CATCH /aws1/cx_rsdinternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeStatement](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ExecuteStatement`
<a name="redshift_ExecuteStatement_sap-abap_1_topic"></a>

次の例は、`ExecuteStatement` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example values: iv_cluster_identifier = 'redshift-cluster-movies'
        " Example values: iv_database_name = 'dev'
        " Example values: iv_user_name = 'awsuser'
        " Example values: iv_sql = 'SELECT * FROM movies WHERE year = :year'
        " Example values: it_parameter_list - SQL parameters for parameterized queries
        
        " Only pass parameters if the list is not empty
        IF it_parameter_list IS NOT INITIAL.
          oo_result = lo_rsd->executestatement(
            iv_clusteridentifier = iv_cluster_identifier
            iv_database = iv_database_name
            iv_dbuser = iv_user_name
            iv_sql = iv_sql
            it_parameters = it_parameter_list
          ).
        ELSE.
          oo_result = lo_rsd->executestatement(
            iv_clusteridentifier = iv_cluster_identifier
            iv_database = iv_database_name
            iv_dbuser = iv_user_name
            iv_sql = iv_sql
          ).
        ENDIF.
        
        lv_statement_id = oo_result->get_id( ).
        MESSAGE |Statement executed. ID: { lv_statement_id }| TYPE 'I'.
      CATCH /aws1/cx_rsdexecutestatementex.
        MESSAGE 'Statement execution error.' TYPE 'I'.
      CATCH /aws1/cx_rsdresourcenotfoundex.
        MESSAGE 'Resource not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ExecuteStatement](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetStatementResult`
<a name="redshift_GetStatementResult_sap-abap_1_topic"></a>

次の例は、`GetStatementResult` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsd#code-examples)での設定と実行の方法を確認してください。
ステートメントの結果を確認します。  

```
    TRY.
        " Example values: iv_statement_id = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
        " Handle pagination for large result sets

        DO.
          lo_result_page = lo_rsd->getstatementresult(
            iv_id = iv_statement_id
            iv_nexttoken = lv_next_token
          ).

          " Collect records from this page
          lt_page_records = lo_result_page->get_records( ).
          APPEND LINES OF lt_page_records TO lt_all_records.

          " Check if there are more pages
          lv_next_token = lo_result_page->get_nexttoken( ).
          IF lv_next_token IS INITIAL.
            EXIT. " No more pages
          ENDIF.
        ENDDO.

        " For the last call, set oo_result for return value
        oo_result = lo_result_page.
        lv_record_count = lines( lt_all_records ).
        MESSAGE |Retrieved { lv_record_count } record(s).| TYPE 'I'.
      CATCH /aws1/cx_rsdresourcenotfoundex.
        MESSAGE 'Statement not found or results not available.' TYPE 'I'.
      CATCH /aws1/cx_rsdinternalserverex.
        MESSAGE 'Internal server error.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetStatementResult](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListDatabases`
<a name="redshift_ListDatabases_sap-abap_1_topic"></a>

次の例は、`ListDatabases` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsd#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example values: iv_cluster_identifier = 'redshift-cluster-movies'
        " Example values: iv_database_name = 'dev'
        " Example values: iv_database_user = 'awsuser'
        oo_result = lo_rsd->listdatabases(
          iv_clusteridentifier = iv_cluster_identifier
          iv_database = iv_database_name
          iv_dbuser = iv_database_user
        ).
        lt_databases = oo_result->get_databases( ).
        lv_db_count = lines( lt_databases ).
        MESSAGE |Retrieved { lv_db_count } database(s).| TYPE 'I'.
      CATCH /aws1/cx_rsddatabaseconnex.
        MESSAGE 'Database connection error.' TYPE 'I'.
      CATCH /aws1/cx_rsdresourcenotfoundex.
        MESSAGE 'Cluster not found.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListDatabases](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ModifyCluster`
<a name="redshift_ModifyCluster_sap-abap_1_topic"></a>

次の例は、`ModifyCluster` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rsh#code-examples)での設定と実行の方法を確認してください。
クラスターを変更します。  

```
    TRY.
        " Example values: iv_cluster_identifier = 'my-redshift-cluster'
        " Example values: iv_pref_maintenance_wn = 'wed:07:30-wed:08:00'
        lo_rsh->modifycluster(
          iv_clusteridentifier = iv_cluster_identifier
          iv_preferredmaintenancewin00 = iv_pref_maintenance_wn
        ).
        MESSAGE 'Redshift cluster modified successfully.' TYPE 'I'.
      CATCH /aws1/cx_rshclustnotfoundfault.
        MESSAGE 'Cluster not found.' TYPE 'I'.
      CATCH /aws1/cx_rshinvcluststatefault.
        MESSAGE 'Invalid cluster state for modification.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ModifyCluster](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Rekognition の例
<a name="sap-abap_1_rekognition_code_examples"></a>

次のコード例は、Amazon Rekognition で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CompareFaces`
<a name="rekognition_CompareFaces_sap-abap_1_topic"></a>

次のコード例は、`CompareFaces` を使用する方法を示しています。

詳細については、「[イメージ内の顔を比較する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-comparefaces.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the source image
        DATA(lo_source_s3obj) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_source_s3_bucket
          iv_name = iv_source_s3_key ).

        " Create source image object
        DATA(lo_source_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_source_s3obj ).

        " Create S3 object reference for the target image
        DATA(lo_target_s3obj) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_target_s3_bucket
          iv_name = iv_target_s3_key ).

        " Create target image object
        DATA(lo_target_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_target_s3obj ).

        " Compare faces
        oo_result = lo_rek->comparefaces(
          io_sourceimage = lo_source_image
          io_targetimage = lo_target_image
          iv_similaritythreshold = iv_similarity ).

        DATA(lt_face_matches) = oo_result->get_facematches( ).
        DATA(lt_unmatched_faces) = oo_result->get_unmatchedfaces( ).

        " Get counts of matched and unmatched faces
        DATA(lv_matched_count) = lines( lt_face_matches ).
        DATA(lv_unmatched_count) = lines( lt_unmatched_faces ).

        " Output detailed comparison results
        DATA(lv_message) = |Face comparison completed: | &&
                           |{ lv_matched_count } matched face(s), | &&
                           |{ lv_unmatched_count } unmatched face(s).|.
        MESSAGE lv_message TYPE 'I'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[CompareFaces](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateCollection`
<a name="rekognition_CreateCollection_sap-abap_1_topic"></a>

次の例は、`CreateCollection` を使用する方法を説明しています。

詳細については、「[コレクションを作成する](https://docs.aws.amazon.com/rekognition/latest/dg/create-collection-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_rek->createcollection(
          iv_collectionid = iv_collection_id ).
        MESSAGE 'Collection created successfully.' TYPE 'I'.
      CATCH /aws1/cx_rekresrcalrdyexistsex.
        MESSAGE 'Collection already exists.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteCollection`
<a name="rekognition_DeleteCollection_sap-abap_1_topic"></a>

次の例は、`DeleteCollection` を使用する方法を説明しています。

詳細については、「[コレクションを削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-collection-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_rek->deletecollection(
          iv_collectionid = iv_collection_id ).
        MESSAGE 'Collection deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_rekresourcenotfoundex.
        MESSAGE 'Collection not found.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteFaces`
<a name="rekognition_DeleteFaces_sap-abap_1_topic"></a>

次の例は、`DeleteFaces` を使用する方法を説明しています。

詳細については、「[コレクションから顔を削除する](https://docs.aws.amazon.com/rekognition/latest/dg/delete-faces-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_rek->deletefaces(
          iv_collectionid = iv_collection_id
          it_faceids = it_face_ids ).

        DATA(lt_deleted_faces) = oo_result->get_deletedfaces( ).
        DATA(lv_deleted_count) = lines( lt_deleted_faces ).
        DATA(lv_msg6) = |{ lv_deleted_count } face(s) deleted successfully.|.
        MESSAGE lv_msg6 TYPE 'I'.
      CATCH /aws1/cx_rekresourcenotfoundex.
        MESSAGE 'Collection not found.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteFaces](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeCollection`
<a name="rekognition_DescribeCollection_sap-abap_1_topic"></a>

次の例は、`DescribeCollection` を使用する方法を説明しています。

詳細については、「[コレクションを定義する](https://docs.aws.amazon.com/rekognition/latest/dg/describe-collection-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_rek->describecollection(
          iv_collectionid = iv_collection_id ).
        DATA(lv_face_count) = oo_result->get_facecount( ).
        DATA(lv_msg) = |Collection described: { lv_face_count } face(s) indexed.|.
        MESSAGE lv_msg TYPE 'I'.
      CATCH /aws1/cx_rekresourcenotfoundex.
        MESSAGE 'Collection not found.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeCollection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectFaces`
<a name="rekognition_DetectFaces_sap-abap_1_topic"></a>

次の例は、`DetectFaces` を使用する方法を説明しています。

詳細については、「[イメージ内の顔を検出する](https://docs.aws.amazon.com/rekognition/latest/dg/faces-detect-images.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the image
        DATA(lo_s3object) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_s3_bucket
          iv_name = iv_s3_key ).

        " Create image object
        DATA(lo_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_s3object ).

        " Detect faces in the image with all attributes
        DATA(lt_attributes) = VALUE /aws1/cl_rekattributes_w=>tt_attributes( ).
        DATA(lo_attr_wrapper) = NEW /aws1/cl_rekattributes_w( iv_value = 'ALL' ).
        INSERT lo_attr_wrapper INTO TABLE lt_attributes.

        oo_result = lo_rek->detectfaces(
          io_image = lo_image
          it_attributes = lt_attributes ).

        DATA(lt_face_details) = oo_result->get_facedetails( ).
        DATA(lv_detected_count) = lines( lt_face_details ).
        DATA(lv_msg8) = |{ lv_detected_count } face(s) detected in image.|.
        MESSAGE lv_msg8 TYPE 'I'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectFaces](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectLabels`
<a name="rekognition_DetectLabels_sap-abap_1_topic"></a>

次の例は、`DetectLabels` を使用する方法を説明しています。

詳細については、「[イメージ内のラベルを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/labels-detect-labels-image.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the image
        DATA(lo_s3object) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_s3_bucket
          iv_name = iv_s3_key ).

        " Create image object
        DATA(lo_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_s3object ).

        " Detect labels in the image
        oo_result = lo_rek->detectlabels(
          io_image = lo_image
          iv_maxlabels = iv_max_labels ).

        DATA(lt_labels) = oo_result->get_labels( ).
        DATA(lv_label_count) = lines( lt_labels ).
        DATA(lv_msg9) = |{ lv_label_count } label(s) detected in image.|.
        MESSAGE lv_msg9 TYPE 'I'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectLabels](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectModerationLabels`
<a name="rekognition_DetectModerationLabels_sap-abap_1_topic"></a>

次の例は、`DetectModerationLabels` を使用する方法を説明しています。

詳細については、「[不適切なイメージを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/procedure-moderate-images.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the image
        DATA(lo_s3object) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_s3_bucket
          iv_name = iv_s3_key ).

        " Create image object
        DATA(lo_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_s3object ).

        " Detect moderation labels
        oo_result = lo_rek->detectmoderationlabels(
          io_image = lo_image ).

        DATA(lt_moderation_labels) = oo_result->get_moderationlabels( ).
        DATA(lv_mod_count) = lines( lt_moderation_labels ).
        DATA(lv_msg10) = |{ lv_mod_count } moderation label(s) detected.|.
        MESSAGE lv_msg10 TYPE 'I'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectModerationLabels](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectText`
<a name="rekognition_DetectText_sap-abap_1_topic"></a>

次の例は、`DetectText` を使用する方法を説明しています。

詳細については、「[イメージ内のテキストを検出する](https://docs.aws.amazon.com/rekognition/latest/dg/text-detecting-text-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the image
        DATA(lo_s3object) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_s3_bucket
          iv_name = iv_s3_key ).

        " Create image object
        DATA(lo_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_s3object ).

        " Detect text in the image
        oo_result = lo_rek->detecttext(
          io_image = lo_image ).

        DATA(lt_text_detections) = oo_result->get_textdetections( ).
        DATA(lv_text_count) = lines( lt_text_detections ).
        DATA(lv_msg11) = |{ lv_text_count } text detection(s) found.|.
        MESSAGE lv_msg11 TYPE 'I'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DetectText](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `IndexFaces`
<a name="rekognition_IndexFaces_sap-abap_1_topic"></a>

次の例は、`IndexFaces` を使用する方法を説明しています。

詳細については、「[コレクションに顔を追加する](https://docs.aws.amazon.com/rekognition/latest/dg/add-faces-to-collection-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the image
        DATA(lo_s3object) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_s3_bucket
          iv_name = iv_s3_key ).

        " Create image object
        DATA(lo_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_s3object ).

        " Index faces in the image
        oo_result = lo_rek->indexfaces(
          iv_collectionid = iv_collection_id
          io_image = lo_image
          iv_externalimageid = iv_external_id
          iv_maxfaces = iv_max_faces ).

        DATA(lt_face_records) = oo_result->get_facerecords( ).
        DATA(lv_indexed_count) = lines( lt_face_records ).
        DATA(lv_msg2) = |{ lv_indexed_count } face(s) indexed successfully.|.
        MESSAGE lv_msg2 TYPE 'I'.
      CATCH /aws1/cx_rekresourcenotfoundex.
        MESSAGE 'Collection not found.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[IndexFaces](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListCollections`
<a name="rekognition_ListCollections_sap-abap_1_topic"></a>

次の例は、`ListCollections` を使用する方法を説明しています。

コレクションの詳細については、「[コレクションを一覧表示する](https://docs.aws.amazon.com/rekognition/latest/dg/list-collection-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_rek->listcollections(
          iv_maxresults = iv_max_results ).

        DATA(lt_collection_ids) = oo_result->get_collectionids( ).
        DATA(lv_coll_count) = lines( lt_collection_ids ).
        DATA(lv_msg7) = |{ lv_coll_count } collection(s) found.|.
        MESSAGE lv_msg7 TYPE 'I'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListCollections](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListFaces`
<a name="rekognition_ListFaces_sap-abap_1_topic"></a>

次の例は、`ListFaces` を使用する方法を説明しています。

詳細については、「[コレクションに顔を保存する](https://docs.aws.amazon.com/rekognition/latest/dg/list-faces-in-collection-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_rek->listfaces(
          iv_collectionid = iv_collection_id
          iv_maxresults = iv_max_results ).

        DATA(lt_faces) = oo_result->get_faces( ).
        DATA(lv_face_count2) = lines( lt_faces ).
        DATA(lv_msg3) = |{ lv_face_count2 } face(s) found in collection.|.
        MESSAGE lv_msg3 TYPE 'I'.
      CATCH /aws1/cx_rekresourcenotfoundex.
        MESSAGE 'Collection not found.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListFaces](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `RecognizeCelebrities`
<a name="rekognition_RecognizeCelebrities_sap-abap_1_topic"></a>

次の例は、`RecognizeCelebrities` を使用する方法を説明しています。

詳細については、「[イメージ内で有名人を認識する](https://docs.aws.amazon.com/rekognition/latest/dg/celebrities-procedure-image.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the image
        DATA(lo_s3object) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_s3_bucket
          iv_name = iv_s3_key ).

        " Create image object
        DATA(lo_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_s3object ).

        " Recognize celebrities
        oo_result = lo_rek->recognizecelebrities(
          io_image = lo_image ).

        DATA(lt_celebrity_faces) = oo_result->get_celebrityfaces( ).
        DATA(lv_celeb_count) = lines( lt_celebrity_faces ).
        DATA(lv_msg12) = |{ lv_celeb_count } celebrity/celebrities recognized.|.
        MESSAGE lv_msg12 TYPE 'I'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [RecognizeCelebrities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SearchFaces`
<a name="rekognition_SearchFaces_sap-abap_1_topic"></a>

次の例は、`SearchFaces` を使用する方法を説明しています。

詳細については、[顔 (フェイス ID) を検索する](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-id-procedure.html) を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_rek->searchfaces(
          iv_collectionid = iv_collection_id
          iv_faceid = iv_face_id
          iv_facematchthreshold = iv_threshold
          iv_maxfaces = iv_max_faces ).

        DATA(lt_face_matches) = oo_result->get_facematches( ).
        DATA(lv_match_count2) = lines( lt_face_matches ).
        DATA(lv_msg5) = |Face search completed: { lv_match_count2 } match(es) found.|.
        MESSAGE lv_msg5 TYPE 'I'.
      CATCH /aws1/cx_rekresourcenotfoundex.
        MESSAGE 'Collection or face not found.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SearchFaces](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SearchFacesByImage`
<a name="rekognition_SearchFacesByImage_sap-abap_1_topic"></a>

次の例は、`SearchFacesByImage` を使用する方法を説明しています。

詳細については、「[顔を検索する (イメージ)](https://docs.aws.amazon.com/rekognition/latest/dg/search-face-with-image-procedure.html)」を参照してください。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/rek#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create S3 object reference for the image
        DATA(lo_s3object) = NEW /aws1/cl_reks3object(
          iv_bucket = iv_s3_bucket
          iv_name = iv_s3_key ).

        " Create image object
        DATA(lo_image) = NEW /aws1/cl_rekimage(
          io_s3object = lo_s3object ).

        " Search for matching faces
        oo_result = lo_rek->searchfacesbyimage(
          iv_collectionid = iv_collection_id
          io_image = lo_image
          iv_facematchthreshold = iv_threshold
          iv_maxfaces = iv_max_faces ).

        DATA(lt_face_matches) = oo_result->get_facematches( ).
        DATA(lv_match_count) = lines( lt_face_matches ).
        DATA(lv_msg4) = |Face search completed: { lv_match_count } match(es) found.|.
        MESSAGE lv_msg4 TYPE 'I'.
      CATCH /aws1/cx_rekresourcenotfoundex.
        MESSAGE 'Collection not found.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalids3objectex.
        MESSAGE 'Invalid S3 object.' TYPE 'E'.
      CATCH /aws1/cx_rekinvalidparameterex.
        MESSAGE 'Invalid parameter value.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SearchFacesByImage](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon S3 の例
<a name="sap-abap_1_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    DATA(lo_session) = /aws1/cl_rt_session_aws=>create( cv_pfl ).
    DATA(lo_s3) = /aws1/cl_s3_factory=>create( lo_session ).

    " Create an Amazon Simple Storage Service (Amazon S3) bucket. "
    TRY.
        " determine our region from our session
        DATA(lv_region) = CONV /aws1/s3_bucketlocationcnstrnt( lo_session->get_region( ) ).
        DATA lo_constraint TYPE REF TO /aws1/cl_s3_createbucketconf.
        " When in the us-east-1 region, you must not specify a constraint
        " In all other regions, specify the region as the constraint
        IF lv_region = 'us-east-1'.
          CLEAR lo_constraint.
        ELSE.
          lo_constraint = NEW /aws1/cl_s3_createbucketconf( lv_region ).
        ENDIF.

        lo_s3->createbucket(
            iv_bucket = iv_bucket_name
            io_createbucketconfiguration  = lo_constraint ).
        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.


    "Upload an object to an S3 bucket."
    TRY.
        "Get contents of file from application server."
        DATA lv_file_content TYPE xstring.
        OPEN DATASET iv_key FOR INPUT IN BINARY MODE.
        READ DATASET iv_key INTO lv_file_content.
        CLOSE DATASET iv_key.

        lo_s3->putobject(
            iv_bucket = iv_bucket_name
            iv_key = iv_key
            iv_body = lv_file_content ).
        MESSAGE 'Object uploaded to S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.

    " Get an object from a bucket. "
    TRY.
        DATA(lo_result) = lo_s3->getobject(
                   iv_bucket = iv_bucket_name
                   iv_key = iv_key ).
        DATA(lv_object_data) = lo_result->get_body( ).
        MESSAGE 'Object retrieved from S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.

    " Copy an object to a subfolder in a bucket. "
    TRY.
        lo_s3->copyobject(
          iv_bucket = iv_bucket_name
          iv_key = |{ iv_copy_to_folder }/{ iv_key }|
          iv_copysource = |{ iv_bucket_name }/{ iv_key }| ).
        MESSAGE 'Object copied to a subfolder.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.

    " List objects in the bucket. "
    TRY.
        DATA(lo_list) = lo_s3->listobjects(
           iv_bucket = iv_bucket_name ).
        MESSAGE 'Retrieved list of objects in S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
    DATA text TYPE string VALUE 'Object List - '.
    DATA lv_object_key TYPE /aws1/s3_objectkey.
    LOOP AT lo_list->get_contents( ) INTO DATA(lo_object).
      lv_object_key = lo_object->get_key( ).
      CONCATENATE lv_object_key ', ' INTO text.
    ENDLOOP.
    MESSAGE text TYPE'I'.

    " Delete the objects in a bucket. "
    TRY.
        lo_s3->deleteobject(
            iv_bucket = iv_bucket_name
            iv_key = iv_key ).
        lo_s3->deleteobject(
            iv_bucket = iv_bucket_name
            iv_key = |{ iv_copy_to_folder }/{ iv_key }| ).
        MESSAGE 'Objects deleted from S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.


    " Delete the bucket. "
    TRY.
        lo_s3->deletebucket(
            iv_bucket = iv_bucket_name ).
        MESSAGE 'Deleted S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の以下のトピックを参照してください。
  + [CopyObject](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [CreateBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteObjects](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [GetObject](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [ListObjectsV2](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [PutObject](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_sap-abap_1_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_s3->copyobject(
          iv_bucket = iv_dest_bucket
          iv_key = iv_dest_object
          iv_copysource = |{ iv_src_bucket }/{ iv_src_object }| ).
        MESSAGE 'Object copied to another bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CopyObject](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_sap-abap_1_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " determine our region from our session
        DATA(lv_region) = CONV /aws1/s3_bucketlocationcnstrnt( lo_session->get_region( ) ).
        DATA lo_constraint TYPE REF TO /aws1/cl_s3_createbucketconf.
        " When in the us-east-1 region, you must not specify a constraint
        " In all other regions, specify the region as the constraint
        IF lv_region = 'us-east-1'.
          CLEAR lo_constraint.
        ELSE.
          lo_constraint = NEW /aws1/cl_s3_createbucketconf( lv_region ).
        ENDIF.

        lo_s3->createbucket(
            iv_bucket = iv_bucket_name
            io_createbucketconfiguration  = lo_constraint ).
        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.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_sap-abap_1_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.

        lo_s3->deletebucket(
            iv_bucket = iv_bucket_name ).
        MESSAGE 'Deleted S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteBucketCors`
<a name="s3_DeleteBucketCors_sap-abap_1_topic"></a>

次の例は、`DeleteBucketCors` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_s3->deletebucketcors(
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Bucket CORS configuration deleted.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteBucketCors](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteBucketLifecycle`
<a name="s3_DeleteBucketLifecycle_sap-abap_1_topic"></a>

次の例は、`DeleteBucketLifecycle` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_s3->deletebucketlifecycle(
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Bucket lifecycle configuration deleted.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteBucketLifecycle](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteBucketPolicy`
<a name="s3_DeleteBucketPolicy_sap-abap_1_topic"></a>

次の例は、`DeleteBucketPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_s3->deletebucketpolicy(
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Bucket policy deleted.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteBucketPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_sap-abap_1_topic"></a>

次の例は、`DeleteObject` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_s3->deleteobject(
            iv_bucket = iv_bucket_name
            iv_key = iv_object_key ).
        MESSAGE 'Object deleted from S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteObject](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_sap-abap_1_topic"></a>

次の例は、`DeleteObjects` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->deleteobjects(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name
          io_delete = NEW /aws1/cl_s3_delete( it_objects = it_object_keys ) ).
        MESSAGE 'Objects deleted from S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteObjects](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetBucketAcl`
<a name="s3_GetBucketAcl_sap-abap_1_topic"></a>

次の例は、`GetBucketAcl` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getbucketacl(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Retrieved bucket ACL.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetBucketAcl](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetBucketCors`
<a name="s3_GetBucketCors_sap-abap_1_topic"></a>

次の例は、`GetBucketCors` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getbucketcors(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Retrieved bucket CORS configuration.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetBucketCors](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetBucketLifecycleConfiguration`
<a name="s3_GetBucketLifecycleConfiguration_sap-abap_1_topic"></a>

次の例は、`GetBucketLifecycleConfiguration` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getbucketlifecycleconf(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Retrieved bucket lifecycle configuration.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetBucketLifecycleConfiguration](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetBucketPolicy`
<a name="s3_GetBucketPolicy_sap-abap_1_topic"></a>

次の例は、`GetBucketPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getbucketpolicy(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        DATA(lv_policy) = oo_result->get_policy( ).
        MESSAGE 'Retrieved bucket policy.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetBucketPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetObject`
<a name="s3_GetObject_sap-abap_1_topic"></a>

次の例は、`GetObject` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getobject(           " oo_result is returned for testing purposes. "
                  iv_bucket = iv_bucket_name
                  iv_key = iv_object_key ).
        DATA(lv_object_data) = oo_result->get_body( ).
        MESSAGE 'Object retrieved from S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetObject](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetObjectAcl`
<a name="s3_GetObjectAcl_sap-abap_1_topic"></a>

次の例は、`GetObjectAcl` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getobjectacl(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name
          iv_key = iv_object_key ).
        MESSAGE 'Retrieved object ACL.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetObjectAcl](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetObjectLegalHold`
<a name="s3_GetObjectLegalHold_sap-abap_1_topic"></a>

次の例は、`GetObjectLegalHold` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getobjectlegalhold(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name
          iv_key = iv_object_key ).
        MESSAGE 'Retrieved object legal hold status.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetObjectLegalHold](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetObjectLockConfiguration`
<a name="s3_GetObjectLockConfiguration_sap-abap_1_topic"></a>

次の例は、`GetObjectLockConfiguration` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->getobjectlockconfiguration(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Retrieved object lock configuration.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetObjectLockConfiguration](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `HeadBucket`
<a name="s3_HeadBucket_sap-abap_1_topic"></a>

次の例は、`HeadBucket` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->headbucket(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Bucket exists and you have access to it.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[HeadBucket](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListObjectVersions`
<a name="s3_ListObjectVersions_sap-abap_1_topic"></a>

次の例は、`ListObjectVersions` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->listobjectversions(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name
          iv_prefix = iv_prefix ).
        MESSAGE 'Retrieved object versions.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListObjectVersions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListObjectsV2`
<a name="s3_ListObjectsV2_sap-abap_1_topic"></a>

次の例は、`ListObjectsV2` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_s3->listobjectsv2(         " oo_result is returned for testing purposes. "
          iv_bucket = iv_bucket_name ).
        MESSAGE 'Retrieved list of objects in S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の「[ListObjectsV2](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutBucketAcl`
<a name="s3_PutBucketAcl_sap-abap_1_topic"></a>

次の例は、`PutBucketAcl` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Grant log delivery access to a bucket
        " iv_grantwrite = 'uri=http://acs.amazonaws.com/groups/s3/LogDelivery'
        lo_s3->putbucketacl(
          iv_bucket = iv_bucket_name
          iv_grantwrite = iv_grantwrite ).
        MESSAGE 'Bucket ACL updated.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutBucketAcl](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutBucketCors`
<a name="s3_PutBucketCors_sap-abap_1_topic"></a>

次の例は、`PutBucketCors` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Allow PUT, POST, DELETE methods from http://www.example.com
        lo_s3->putbucketcors(
          iv_bucket = iv_bucket_name
          io_corsconfiguration = NEW /aws1/cl_s3_corsconfiguration(
            it_corsrules = it_cors_rules ) ).
        MESSAGE 'Bucket CORS configuration set.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutBucketCors](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutBucketLifecycleConfiguration`
<a name="s3_PutBucketLifecycleConfiguration_sap-abap_1_topic"></a>

次の例は、`PutBucketLifecycleConfiguration` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Expire objects with prefix 'logs/' after 30 days
        lo_s3->putbucketlifecycleconf(
          iv_bucket = iv_bucket_name
          io_lifecycleconfiguration = NEW /aws1/cl_s3_bucketlcconf(
            it_rules = it_lifecycle_rule ) ).
        MESSAGE 'Bucket lifecycle configuration set.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutBucketPolicy`
<a name="s3_PutBucketPolicy_sap-abap_1_topic"></a>

次の例は、`PutBucketPolicy` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example policy JSON string
        " iv_policy = '{"Version":"2012-10-17",		 	 	 "Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:user/user"},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucketname/*"]}]}'
        lo_s3->putbucketpolicy(
          iv_bucket = iv_bucket_name
          iv_policy = iv_policy ).
        MESSAGE 'Bucket policy set.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutBucketPolicy](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutBucketVersioning`
<a name="s3_PutBucketVersioning_sap-abap_1_topic"></a>

次の例は、`PutBucketVersioning` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Enable versioning on a bucket
        " iv_status = 'Enabled'
        lo_s3->putbucketversioning(
          iv_bucket = iv_bucket_name
          io_versioningconfiguration = NEW /aws1/cl_s3_versioningconf(
            iv_status = iv_status ) ).
        MESSAGE 'Bucket versioning enabled.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[PutBucketVersioning](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutObject`
<a name="s3_PutObject_sap-abap_1_topic"></a>

次の例は、`PutObject` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    "Get contents of file from application server."
    DATA lv_body TYPE xstring.
    OPEN DATASET iv_file_name FOR INPUT IN BINARY MODE.
    READ DATASET iv_file_name INTO lv_body.
    CLOSE DATASET iv_file_name.

    "Upload/put an object to an S3 bucket."
    TRY.
        lo_s3->putobject(
            iv_bucket = iv_bucket_name
            iv_key = iv_file_name
            iv_body = lv_body ).
        MESSAGE 'Object uploaded to S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[PutObject](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutObjectAcl`
<a name="s3_PutObjectAcl_sap-abap_1_topic"></a>

次の例は、`PutObjectAcl` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Grant read access to an AWS user
        " iv_grantread = 'emailAddress=user@example.com'
        lo_s3->putobjectacl(
          iv_bucket = iv_bucket_name
          iv_key = iv_object_key
          iv_grantread = iv_grantread ).
        MESSAGE 'Object ACL updated.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[PutObjectAcl](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutObjectLegalHold`
<a name="s3_PutObjectLegalHold_sap-abap_1_topic"></a>

次の例は、`PutObjectLegalHold` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Set legal hold status to ON
        " iv_status = 'ON'
        lo_s3->putobjectlegalhold(
          iv_bucket = iv_bucket_name
          iv_key = iv_object_key
          io_legalhold = NEW /aws1/cl_s3_objlocklegalhold(
            iv_status = iv_status ) ).
        MESSAGE 'Object legal hold status set.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[PutObjectLegalHold](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutObjectLockConfiguration`
<a name="s3_PutObjectLockConfiguration_sap-abap_1_topic"></a>

次の例は、`PutObjectLockConfiguration` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Enable object lock with default retention
        " iv_enabled = 'Enabled'
        lo_s3->putobjectlockconfiguration(
          iv_bucket = iv_bucket_name
          io_objectlockconfiguration = NEW /aws1/cl_s3_objectlockconf(
            iv_objectlockenabled = iv_enabled ) ).
        MESSAGE 'Object lock configuration set.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[PutObjectLockConfiguration](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `PutObjectRetention`
<a name="s3_PutObjectRetention_sap-abap_1_topic"></a>

次の例は、`PutObjectRetention` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Example: Set retention mode to GOVERNANCE for 30 days
        " iv_mode = 'GOVERNANCE'
        " iv_retain_date should be a timestamp in the future
        lo_s3->putobjectretention(
          iv_bucket = iv_bucket_name
          iv_key = iv_object_key
          io_retention = NEW /aws1/cl_s3_objectlockret(
            iv_mode = iv_mode
            iv_retainuntildate = iv_retain_date )
          iv_bypassgovernanceretention = abap_true ).
        MESSAGE 'Object retention set.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
      CATCH /aws1/cx_s3_nosuchkey.
        MESSAGE 'Object key does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[PutObjectRetention](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 署名付き URL を作成する
<a name="s3_Scenario_PresignedUrl_sap-abap_1_topic"></a>

次のコード例は、Amazon S3 の署名付き URL を作成し、オブジェクトをアップロードする方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/s3#code-examples)での設定と実行の方法を確認してください。
署名付きリクエストを作成してS3 オブジェクトを取得します。  

```
    " iv_bucket_name is the bucket name
    " iv_key is the object name like "myfile.txt"

    DATA(lo_session) = /aws1/cl_rt_session_aws=>create( cv_pfl ).
    DATA(lo_s3) = /aws1/cl_s3_factory=>create( lo_session ).

    "Upload a nice Hello World file to an S3 bucket."
    TRY.
        DATA(lv_contents) = cl_abap_codepage=>convert_to( 'Hello, World' ).
        lo_s3->putobject(
            iv_bucket = iv_bucket_name
            iv_key = iv_key
            iv_body = lv_contents
            iv_contenttype = 'text/plain' ).
        MESSAGE 'Object uploaded to S3 bucket.' TYPE 'I'.
      CATCH /aws1/cx_s3_nosuchbucket.
        MESSAGE 'Bucket does not exist.' TYPE 'E'.
    ENDTRY.

    " now generate a presigned URL with a 600-second expiration
    DATA(lo_presigner) = lo_s3->get_presigner( iv_expires_sec = 600 ).
    " the presigner getobject() method has the same signature as
    " lo_s3->getobject(), but it doesn't actually make the call.
    " to the service.  It just prepares a presigned URL for a future call
    DATA(lo_presigned_req) = lo_presigner->getobject(
      iv_bucket = iv_bucket_name
      iv_key = iv_key ).

    " You can provide this URL to a web page, user, email etc so they
    " can retrieve the file.  The URL will expire in 10 minutes.
    ov_url = lo_presigned_req->get_url( ).
```

# SDK for SAP ABAP を使用した SageMaker AI の例
<a name="sap-abap_1_sagemaker_code_examples"></a>

次のコード例は、SageMaker AI で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateEndpoint`
<a name="sagemaker_CreateEndpoint_sap-abap_1_topic"></a>

次のコード例は、`CreateEndpoint` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_production_variants TYPE /aws1/cl_sgmproductionvariant=>tt_productionvariantlist.
    DATA lo_production_variants TYPE REF TO /aws1/cl_sgmproductionvariant.
    DATA oo_ep_config_result TYPE REF TO /aws1/cl_sgmcreateendptcfgout.

    "Create a production variant as an ABAP object."
    "Identifies a model that you want to host and the resources chosen to deploy for hosting it."
    lo_production_variants = NEW #( iv_variantname = iv_variant_name
                                    iv_modelname = iv_model_name
                                    iv_initialinstancecount = iv_initial_instance_count
                                    iv_instancetype = iv_instance_type ).

    INSERT lo_production_variants INTO TABLE lt_production_variants.

    "Create an endpoint configuration."
    TRY.
        oo_ep_config_result = lo_sgm->createendpointconfig(
          iv_endpointconfigname = iv_endpoint_config_name
          it_productionvariants = lt_production_variants ).
        MESSAGE 'Endpoint configuration created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.

    "Create an endpoint."
    TRY.
        oo_result = lo_sgm->createendpoint(     " oo_result is returned for testing purposes. "
            iv_endpointconfigname = iv_endpoint_config_name
            iv_endpointname = iv_endpoint_name ).
        MESSAGE 'Endpoint created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[CreateEndpoint](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `CreateModel`
<a name="sagemaker_CreateModel_sap-abap_1_topic"></a>

次のコード例は、`CreateModel` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    DATA lo_primarycontainer TYPE REF TO /aws1/cl_sgmcontainerdefn.

    "Create an ABAP object for the container image based on input variables."
    lo_primarycontainer = NEW #( iv_image = iv_container_image
                                 iv_modeldataurl = iv_model_data_url ).

    "Create an Amazon SageMaker model."
    TRY.
        oo_result = lo_sgm->createmodel(        " oo_result is returned for testing purposes. "
          iv_executionrolearn = iv_execution_role_arn
          iv_modelname = iv_model_name
          io_primarycontainer = lo_primarycontainer ).
        MESSAGE 'Model created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateTrainingJob`
<a name="sagemaker_CreateTrainingJob_sap-abap_1_topic"></a>

次のコード例は、`CreateTrainingJob` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    DATA lo_hyperparameters_w TYPE REF TO /aws1/cl_sgmhyperparameters_w.
    DATA lt_hyperparameters TYPE /aws1/cl_sgmhyperparameters_w=>tt_hyperparameters.
    DATA lt_input_data_config TYPE /aws1/cl_sgmchannel=>tt_inputdataconfig.
    DATA lo_trn_channel TYPE REF TO /aws1/cl_sgmchannel.
    DATA lo_trn_datasource TYPE REF TO /aws1/cl_sgmdatasource.
    DATA lo_trn_s3datasource TYPE REF TO /aws1/cl_sgms3datasource.
    DATA lo_val_channel TYPE REF TO /aws1/cl_sgmchannel.
    DATA lo_val_datasource TYPE REF TO /aws1/cl_sgmdatasource.
    DATA lo_val_s3datasource TYPE REF TO /aws1/cl_sgms3datasource.
    DATA lo_algorithm_specification TYPE REF TO /aws1/cl_sgmalgorithmspec.
    DATA lo_resource_config  TYPE REF TO /aws1/cl_sgmresourceconfig.
    DATA lo_output_data_config TYPE REF TO /aws1/cl_sgmoutputdataconfig.
    DATA lo_stopping_condition TYPE REF TO /aws1/cl_sgmstoppingcondition.

    "Create ABAP internal table for hyperparameters based on input variables."
    "These hyperparameters are based on the Amazon SageMaker built-in algorithm, XGBoost."
    lo_hyperparameters_w = NEW #( iv_value = iv_hp_max_depth ).
    INSERT VALUE #( key = 'max_depth' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_eta ).
    INSERT VALUE #( key = 'eta' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_eval_metric ).
    INSERT VALUE #( key = 'eval_metric' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_scale_pos_weight ).
    INSERT VALUE #( key = 'scale_pos_weight' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_subsample ).
    INSERT VALUE #( key = 'subsample' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_objective ).
    INSERT VALUE #( key = 'objective' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_num_round ).
    INSERT VALUE #( key = 'num_round' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    "Create ABAP objects for training data sources."
    lo_trn_s3datasource = NEW #( iv_s3datatype = iv_trn_data_s3datatype
                                 iv_s3datadistributiontype = iv_trn_data_s3datadistribution
                                 iv_s3uri = iv_trn_data_s3uri ).

    lo_trn_datasource = NEW #( io_s3datasource = lo_trn_s3datasource ).

    lo_trn_channel = NEW #( iv_channelname = 'train'
                            io_datasource = lo_trn_datasource
                            iv_compressiontype = iv_trn_data_compressiontype
                            iv_contenttype = iv_trn_data_contenttype ).

    INSERT lo_trn_channel INTO TABLE lt_input_data_config.

    "Create ABAP objects for validation data sources."
    lo_val_s3datasource = NEW #( iv_s3datatype = iv_val_data_s3datatype
                                 iv_s3datadistributiontype = iv_val_data_s3datadistribution
                                 iv_s3uri = iv_val_data_s3uri ).

    lo_val_datasource = NEW #( io_s3datasource = lo_val_s3datasource ).

    lo_val_channel = NEW #( iv_channelname = 'validation'
                            io_datasource = lo_val_datasource
                            iv_compressiontype = iv_val_data_compressiontype
                            iv_contenttype = iv_val_data_contenttype ).

    INSERT lo_val_channel INTO TABLE lt_input_data_config.

    "Create an ABAP object for algorithm specification."
    lo_algorithm_specification = NEW #( iv_trainingimage = iv_training_image
                                        iv_traininginputmode = iv_training_input_mode ).

    "Create an ABAP object for resource configuration."
    lo_resource_config = NEW #( iv_instancecount = iv_instance_count
                                iv_instancetype = iv_instance_type
                                iv_volumesizeingb = iv_volume_sizeingb ).

    "Create an ABAP object for output data configuration."
    lo_output_data_config = NEW #( iv_s3outputpath = iv_s3_output_path ).

    "Create an ABAP object for stopping condition."
    lo_stopping_condition = NEW #( iv_maxruntimeinseconds = iv_max_runtime_in_seconds ).

    "Create a training job."
    TRY.
        oo_result = lo_sgm->createtrainingjob(    " oo_result is returned for testing purposes. "
          iv_trainingjobname           = iv_training_job_name
          iv_rolearn                   = iv_role_arn
          it_hyperparameters           = lt_hyperparameters
          it_inputdataconfig           = lt_input_data_config
          io_algorithmspecification    = lo_algorithm_specification
          io_outputdataconfig          = lo_output_data_config
          io_resourceconfig            = lo_resource_config
          io_stoppingcondition         = lo_stopping_condition ).
        MESSAGE 'Training job created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourceinuse.
        MESSAGE 'Resource being accessed is in use.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcenotfound.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateTrainingJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateTransformJob`
<a name="sagemaker_CreateTransformJob_sap-abap_1_topic"></a>

次のコード例は、`CreateTransformJob` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    DATA lo_transforminput TYPE REF TO /aws1/cl_sgmtransforminput.
    DATA lo_transformoutput TYPE REF TO /aws1/cl_sgmtransformoutput.
    DATA lo_transformresources TYPE REF TO /aws1/cl_sgmtransformresources.
    DATA lo_datasource  TYPE REF TO /aws1/cl_sgmtransformdatasrc.
    DATA lo_s3datasource  TYPE REF TO /aws1/cl_sgmtransforms3datasrc.

    "Create an ABAP object for an Amazon Simple Storage Service (Amazon S3) data source."
    lo_s3datasource = NEW #( iv_s3uri = iv_tf_data_s3uri
                             iv_s3datatype = iv_tf_data_s3datatype ).

    "Create an ABAP object for data source."
    lo_datasource = NEW #( io_s3datasource = lo_s3datasource ).

    "Create an ABAP object for transform data source."
    lo_transforminput = NEW #( io_datasource = lo_datasource
                               iv_contenttype = iv_tf_data_contenttype
                               iv_compressiontype = iv_tf_data_compressiontype ).

    "Create an ABAP object for resource configuration."
    lo_transformresources = NEW #( iv_instancecount = iv_instance_count
                                   iv_instancetype = iv_instance_type ).

    "Create an ABAP object for output data configuration."
    lo_transformoutput = NEW #( iv_s3outputpath = iv_s3_output_path ).

    "Create a transform job."
    TRY.
        oo_result = lo_sgm->createtransformjob(     " oo_result is returned for testing purposes. "
            iv_modelname = iv_tf_model_name
            iv_transformjobname = iv_tf_job_name
            io_transforminput = lo_transforminput
            io_transformoutput = lo_transformoutput
            io_transformresources = lo_transformresources ).
        MESSAGE 'Transform job created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourceinuse.
        MESSAGE 'Resource being accessed is in use.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcenotfound.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateTransformJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteEndpoint`
<a name="sagemaker_DeleteEndpoint_sap-abap_1_topic"></a>

次のコード例は、`DeleteEndpoint` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    "Delete an endpoint."
    TRY.
        lo_sgm->deleteendpoint(
            iv_endpointname = iv_endpoint_name ).
        MESSAGE 'Endpoint configuration deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_endpoint_exception).
        DATA(lv_endpoint_error) = |"{ lo_endpoint_exception->av_err_code }" - { lo_endpoint_exception->av_err_msg }|.
        MESSAGE lv_endpoint_error TYPE 'E'.
    ENDTRY.

    "Delete an endpoint configuration."
    TRY.
        lo_sgm->deleteendpointconfig(
          iv_endpointconfigname = iv_endpoint_config_name ).
        MESSAGE 'Endpoint deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_endpointconfig_exception).
        DATA(lv_endpointconfig_error) = |"{ lo_endpointconfig_exception->av_err_code }" - { lo_endpointconfig_exception->av_err_msg }|.
        MESSAGE lv_endpointconfig_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DeleteEndpoint](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `DeleteModel`
<a name="sagemaker_DeleteModel_sap-abap_1_topic"></a>

次のコード例は、`DeleteModel` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sgm->deletemodel(
                  iv_modelname = iv_model_name ).
        MESSAGE 'Model deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeTrainingJob`
<a name="sagemaker_DescribeTrainingJob_sap-abap_1_topic"></a>

次のコード例は、`DescribeTrainingJob` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sgm->describetrainingjob(      " oo_result is returned for testing purposes. "
          iv_trainingjobname = iv_training_job_name ).
        MESSAGE 'Retrieved description of training job.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeTrainingJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListAlgorithms`
<a name="sagemaker_ListAlgorithms_sap-abap_1_topic"></a>

次のコード例は、`ListAlgorithms` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sgm->listalgorithms(         " oo_result is returned for testing purposes. "
          iv_namecontains = iv_name_contains ).
        MESSAGE 'Retrieved list of algorithms.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListAlgorithms](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListModels`
<a name="sagemaker_ListModels_sap-abap_1_topic"></a>

次のコード例は、`ListModels` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sgm->listmodels(           " oo_result is returned for testing purposes. "
          iv_namecontains = iv_name_contains ).
        MESSAGE 'Retrieved list of models.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListModels](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListNotebookInstances`
<a name="sagemaker_ListNotebookInstances_sap-abap_1_topic"></a>

次のコード例は、`ListNotebookInstances` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sgm->listnotebookinstances(        " oo_result is returned for testing purposes. "
          iv_namecontains = iv_name_contains ).
        MESSAGE 'Retrieved list of notebook instances.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListNotebookInstances](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTrainingJobs`
<a name="sagemaker_ListTrainingJobs_sap-abap_1_topic"></a>

次のコード例は、`ListTrainingJobs` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sgm->listtrainingjobs(       " oo_result is returned for testing purposes. "
          iv_namecontains = iv_name_contains
          iv_maxresults = iv_max_results ).
        MESSAGE 'Retrieved list of training jobs.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception).
        DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|.
        MESSAGE lv_error TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListTrainingJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### モデルとエンドポイントの使用を開始する
<a name="sagemaker_Scenario_GettingStarted_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トレーニングジョブを開始し、SageMaker AI モデルを作成します。
+ エンドポイント設定を作成する
+ エンドポイントを作成して、リソースをクリーンアップします。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sgm#code-examples)での設定と実行の方法を確認してください。

```
    DATA lo_hyperparameters_w TYPE REF TO /aws1/cl_sgmhyperparameters_w.
    DATA lo_trn_channel TYPE REF TO /aws1/cl_sgmchannel.
    DATA lo_trn_datasource TYPE REF TO /aws1/cl_sgmdatasource.
    DATA lo_trn_s3datasource TYPE REF TO /aws1/cl_sgms3datasource.
    DATA lo_val_channel TYPE REF TO /aws1/cl_sgmchannel.
    DATA lo_val_datasource TYPE REF TO /aws1/cl_sgmdatasource.
    DATA lo_val_s3datasource TYPE REF TO /aws1/cl_sgms3datasource.
    DATA lo_algorithm_specification TYPE REF TO /aws1/cl_sgmalgorithmspec.
    DATA lo_resource_config  TYPE REF TO /aws1/cl_sgmresourceconfig.
    DATA lo_output_data_config TYPE REF TO /aws1/cl_sgmoutputdataconfig.
    DATA lo_stopping_condition TYPE REF TO /aws1/cl_sgmstoppingcondition.
    DATA lo_primarycontainer TYPE REF TO /aws1/cl_sgmcontainerdefn.
    DATA lo_production_variants TYPE REF TO /aws1/cl_sgmproductionvariant.
    DATA lo_ep_config_result TYPE REF TO /aws1/cl_sgmcreateendptcfgout.
    DATA lo_training_result TYPE REF TO /aws1/cl_sgmdescrtrnjobrsp.
    DATA lt_production_variants TYPE /aws1/cl_sgmproductionvariant=>tt_productionvariantlist.
    DATA lt_input_data_config TYPE /aws1/cl_sgmchannel=>tt_inputdataconfig.
    DATA lt_hyperparameters TYPE /aws1/cl_sgmhyperparameters_w=>tt_hyperparameters.
    DATA lv_model_data_url TYPE /aws1/sgmurl.

    lv_model_data_url = iv_s3_output_path && iv_training_job_name && '/output/model.tar.gz'.

    "Create ABAP internal table for hyperparameters based on input variables."
    "These hyperparameters are based on Amazon SageMaker built-in algorithm - XGBoost"
    lo_hyperparameters_w = NEW #( iv_value = iv_hp_max_depth ).
    INSERT VALUE #( key = 'max_depth' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_eta ).
    INSERT VALUE #( key = 'eta' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_eval_metric ).
    INSERT VALUE #( key = 'eval_metric' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_scale_pos_weight ).
    INSERT VALUE #( key = 'scale_pos_weight' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_subsample ).
    INSERT VALUE #( key = 'subsample' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_objective ).
    INSERT VALUE #( key = 'objective' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    lo_hyperparameters_w = NEW #( iv_value = iv_hp_num_round ).
    INSERT VALUE #( key = 'num_round' value = lo_hyperparameters_w )  INTO TABLE lt_hyperparameters.

    "Create ABAP internal table for data based on input variables."
    "Training data."
    lo_trn_s3datasource = NEW #( iv_s3datatype = iv_trn_data_s3datatype
                                 iv_s3datadistributiontype = iv_trn_data_s3datadistribution
                                 iv_s3uri = iv_trn_data_s3uri ).

    lo_trn_datasource = NEW #( io_s3datasource = lo_trn_s3datasource ).

    lo_trn_channel = NEW #( iv_channelname = 'train'
                            io_datasource = lo_trn_datasource
                            iv_compressiontype = iv_trn_data_compressiontype
                            iv_contenttype = iv_trn_data_contenttype ).
    INSERT lo_trn_channel INTO TABLE lt_input_data_config.

    "Validation data."
    lo_val_s3datasource = NEW #( iv_s3datatype = iv_val_data_s3datatype
                                 iv_s3datadistributiontype = iv_val_data_s3datadistribution
                                 iv_s3uri = iv_val_data_s3uri ).

    lo_val_datasource = NEW #( io_s3datasource = lo_val_s3datasource ).

    lo_val_channel = NEW #( iv_channelname = 'validation'
                            io_datasource = lo_val_datasource
                            iv_compressiontype = iv_val_data_compressiontype
                            iv_contenttype = iv_val_data_contenttype ).
    INSERT lo_val_channel INTO TABLE lt_input_data_config.

    "Create an ABAP object for algorithm specification based on input variables."
    lo_algorithm_specification = NEW #( iv_trainingimage = iv_training_image
                                        iv_traininginputmode = iv_training_input_mode ).

    "Create an ABAP object for resource configuration."
    lo_resource_config = NEW #( iv_instancecount = iv_instance_count
                                iv_instancetype = iv_instance_type
                                iv_volumesizeingb = iv_volume_sizeingb ).

    "Create an ABAP object for output data configuration."
    lo_output_data_config = NEW #( iv_s3outputpath = iv_s3_output_path ).

    "Create an ABAP object for stopping condition."
    lo_stopping_condition = NEW #( iv_maxruntimeinseconds = iv_max_runtime_in_seconds ).

    TRY.
        lo_sgm->createtrainingjob(
          iv_trainingjobname           = iv_training_job_name
          iv_rolearn                   = iv_role_arn
          it_hyperparameters           = lt_hyperparameters
          it_inputdataconfig           = lt_input_data_config
          io_algorithmspecification    = lo_algorithm_specification
          io_outputdataconfig          = lo_output_data_config
          io_resourceconfig            = lo_resource_config
          io_stoppingcondition         = lo_stopping_condition ).
        MESSAGE 'Training job created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourceinuse.
        MESSAGE 'Resource being accessed is in use.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcenotfound.
        MESSAGE 'Resource being accessed is not found.' TYPE 'E'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.

    "Wait for training job to be completed."
    lo_training_result = lo_sgm->describetrainingjob( iv_trainingjobname = iv_training_job_name ).
    WHILE lo_training_result->get_trainingjobstatus( ) <> 'Completed'.
      IF sy-index = 30.
        EXIT.               "Maximum 900 seconds."
      ENDIF.
      WAIT UP TO 30 SECONDS.
      lo_training_result = lo_sgm->describetrainingjob( iv_trainingjobname = iv_training_job_name ).
    ENDWHILE.

    "Create ABAP object for the container image based on input variables."
    lo_primarycontainer = NEW #( iv_image = iv_training_image
                                 iv_modeldataurl = lv_model_data_url ).

    "Create an Amazon SageMaker model."
    TRY.
        lo_sgm->createmodel(
          iv_executionrolearn = iv_role_arn
          iv_modelname = iv_model_name
          io_primarycontainer = lo_primarycontainer ).
        MESSAGE 'Model created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.

    "Create an endpoint production variant."
    lo_production_variants = NEW #( iv_variantname = iv_ep_variant_name
                                    iv_modelname = iv_model_name
                                    iv_initialinstancecount = iv_ep_initial_instance_count
                                    iv_instancetype = iv_ep_instance_type ).
    INSERT lo_production_variants INTO TABLE lt_production_variants.

    TRY.
        "Create an endpoint configuration."
        lo_ep_config_result = lo_sgm->createendpointconfig(
          iv_endpointconfigname = iv_ep_cfg_name
          it_productionvariants = lt_production_variants ).
        MESSAGE 'Endpoint configuration created.' TYPE 'I'.

        "Create an endpoint."
        oo_ep_output = lo_sgm->createendpoint(        " oo_ep_output is returned for testing purposes. "
            iv_endpointconfigname = iv_ep_cfg_name
            iv_endpointname = iv_ep_name ).
        MESSAGE 'Endpoint created.' TYPE 'I'.
      CATCH /aws1/cx_sgmresourcelimitexcd.
        MESSAGE 'You have reached the limit on the number of resources.' TYPE 'E'.
    ENDTRY.

    "Wait for endpoint creation to be completed."
    DATA(lo_endpoint_result) = lo_sgm->describeendpoint( iv_endpointname = iv_ep_name ).
    WHILE lo_endpoint_result->get_endpointstatus( ) <> 'InService'.
      IF sy-index = 30.
        EXIT.               "Maximum 900 seconds."
      ENDIF.
      WAIT UP TO 30 SECONDS.
      lo_endpoint_result = lo_sgm->describeendpoint( iv_endpointname = iv_ep_name ).
    ENDWHILE.

    TRY.
        "Delete an endpoint."
        lo_sgm->deleteendpoint(
            iv_endpointname = iv_ep_name ).
        MESSAGE 'Endpoint deleted' TYPE 'I'.

        "Delete an endpoint configuration."
        lo_sgm->deleteendpointconfig(
          iv_endpointconfigname = iv_ep_cfg_name ).
        MESSAGE 'Endpoint configuration deleted.' TYPE 'I'.

        "Delete model."
        lo_sgm->deletemodel(
                  iv_modelname = iv_model_name ).
        MESSAGE 'Model deleted.' TYPE 'I'.
      CATCH /aws1/cx_rt_service_generic INTO DATA(lo_endpointconfig_exception).
        DATA(lv_endpointconfig_error) = |"{ lo_endpointconfig_exception->av_err_code }" - { lo_endpointconfig_exception->av_err_msg }|.
        MESSAGE lv_endpointconfig_error TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [CreateEndpoint](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [CreateEndpointConfig](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [CreateModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [CreateTrainingJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteEndpoint](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteEndpointConfig](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DeleteModel](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DescribeEndpoint](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [DescribeTrainingJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

# SDK for SAP ABAP を使用した Secrets Manager の例
<a name="sap-abap_1_secrets-manager_code_examples"></a>

次のコード例は、Secrets Manager で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `BatchGetSecretValue`
<a name="secrets-manager_BatchGetSecretValue_sap-abap_1_topic"></a>

次の例は、`BatchGetSecretValue` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/smr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_filter_name = 'mySecret'
        DATA(lo_result) = lo_smr->batchgetsecretvalue(
          it_filters = VALUE /aws1/cl_smrfilter=>tt_filterslisttype(
            (
              NEW /aws1/cl_smrfilter(
                iv_key = 'name'
                it_values = VALUE /aws1/cl_smrfiltvalsstrlist_w=>tt_filtervaluesstringlist(
                  ( NEW /aws1/cl_smrfiltvalsstrlist_w( iv_value = iv_filter_name ) )
                )
              )
            )
          )
        ).
        ot_secret_values = lo_result->get_secretvalues( ).
        MESSAGE 'Secrets retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_smrresourcenotfoundex.
        MESSAGE 'One or more requested secrets were not found.' TYPE 'E'.
      CATCH /aws1/cx_smrdecryptionfailure.
        MESSAGE 'Failed to decrypt one or more secrets.' TYPE 'E'.
      CATCH /aws1/cx_smrinvalidparameterex.
        MESSAGE 'Invalid parameter provided.' TYPE 'E'.
      CATCH /aws1/cx_smrinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[BatchGetSecretValue](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetSecretValue`
<a name="secrets-manager_GetSecretValue_sap-abap_1_topic"></a>

次の例は、`GetSecretValue` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/smr#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " iv_secret_name = 'MySecretName'
        DATA(lo_result) = lo_smr->getsecretvalue( iv_secretid = iv_secret_name ).
        ov_secret_value = lo_result->get_secretstring( ).
        MESSAGE 'Secret value retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_smrresourcenotfoundex.
        MESSAGE 'The requested secret was not found.' TYPE 'E'.
      CATCH /aws1/cx_smrdecryptionfailure.
        MESSAGE 'Failed to decrypt the secret.' TYPE 'E'.
      CATCH /aws1/cx_smrinvalidparameterex.
        MESSAGE 'Invalid parameter provided.' TYPE 'E'.
      CATCH /aws1/cx_smrinvalidrequestex.
        MESSAGE 'Invalid request.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetSecretValue](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon SES の例
<a name="sap-abap_1_ses_code_examples"></a>

次のコード例は、Amazon SES で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateReceiptFilter`
<a name="ses_CreateReceiptFilter_sap-abap_1_topic"></a>

次の例は、`CreateReceiptFilter` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    " iv_allow = abap_true means 'Allow', abap_false means 'Block'
    DATA(lv_policy) = COND /aws1/sesreceiptfilterpolicy(
      WHEN iv_allow = abap_true THEN 'Allow'
      ELSE 'Block'
    ).

    DATA(lo_ip_filter) = NEW /aws1/cl_sesreceiptipfilter(
      iv_policy = lv_policy
      iv_cidr = iv_ip_address_or_range
    ).

    DATA(lo_filter) = NEW /aws1/cl_sesreceiptfilter(
      iv_name = iv_filter_name
      io_ipfilter = lo_ip_filter
    ).

    TRY.
        lo_ses->createreceiptfilter( io_filter = lo_filter ).
        MESSAGE 'Receipt filter created successfully' TYPE 'I'.
      CATCH /aws1/cx_sesalreadyexistsex INTO DATA(lo_ex1).
        DATA(lv_error) = |Filter already exists: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateReceiptFilter](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateReceiptRule`
<a name="ses_CreateReceiptRule_sap-abap_1_topic"></a>

次の例は、`CreateReceiptRule` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    " Create S3 action for copying emails to S3
    DATA(lo_s3_action) = NEW /aws1/cl_sess3action(
      iv_bucketname = iv_bucket_name
      iv_objectkeyprefix = iv_prefix
    ).

    " Create receipt action with S3 action
    DATA(lo_action) = NEW /aws1/cl_sesreceiptaction(
      io_s3action = lo_s3_action
    ).

    " Create list of actions
    DATA lt_actions TYPE /aws1/cl_sesreceiptaction=>tt_receiptactionslist.
    APPEND lo_action TO lt_actions.

    " Create receipt rule
    DATA(lo_rule) = NEW /aws1/cl_sesreceiptrule(
      iv_name = iv_rule_name
      iv_enabled = abap_true
      it_recipients = it_recipients
      it_actions = lt_actions
    ).

    TRY.
        lo_ses->createreceiptrule(
          iv_rulesetname = iv_rule_set_name
          io_rule = lo_rule
        ).
        MESSAGE 'Receipt rule created successfully' TYPE 'I'.
      CATCH /aws1/cx_sesinvalids3confex INTO DATA(lo_ex1).
        DATA(lv_error) = |Invalid S3 configuration: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateReceiptRule](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateReceiptRuleSet`
<a name="ses_CreateReceiptRuleSet_sap-abap_1_topic"></a>

次の例は、`CreateReceiptRuleSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ses->createreceiptruleset( iv_rulesetname = iv_rule_set_name ).
        MESSAGE 'Receipt rule set created successfully' TYPE 'I'.
      CATCH /aws1/cx_sesalreadyexistsex INTO DATA(lo_ex1).
        DATA(lv_error) = |Rule set already exists: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateReceiptRuleSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateTemplate`
<a name="ses_CreateTemplate_sap-abap_1_topic"></a>

次の例は、`CreateTemplate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    DATA(lo_template) = NEW /aws1/cl_sestemplate(
      iv_templatename = iv_name
      iv_subjectpart = iv_subject
      iv_textpart = iv_text
      iv_htmlpart = iv_html
    ).

    TRY.
        lo_ses->createtemplate( io_template = lo_template ).
        MESSAGE 'Template created successfully' TYPE 'I'.
      CATCH /aws1/cx_sesalreadyexistsex INTO DATA(lo_ex1).
        DATA(lv_error) = |Template already exists: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_sesinvalidtemplateex INTO DATA(lo_ex2).
        lv_error = |Invalid template: { lo_ex2->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex2.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateTemplate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteIdentity`
<a name="ses_DeleteIdentity_sap-abap_1_topic"></a>

次の例は、`DeleteIdentity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ses->deleteidentity( iv_identity = iv_identity ).
        MESSAGE 'Identity deleted successfully' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteIdentity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteReceiptFilter`
<a name="ses_DeleteReceiptFilter_sap-abap_1_topic"></a>

次の例は、`DeleteReceiptFilter` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ses->deletereceiptfilter( iv_filtername = iv_filter_name ).
        MESSAGE 'Receipt filter deleted successfully' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteReceiptFilter](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteReceiptRule`
<a name="ses_DeleteReceiptRule_sap-abap_1_topic"></a>

次の例は、`DeleteReceiptRule` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ses->deletereceiptrule(
          iv_rulesetname = iv_rule_set_name
          iv_rulename = iv_rule_name
        ).
        MESSAGE 'Receipt rule deleted successfully' TYPE 'I'.
      CATCH /aws1/cx_sesrulesetdoesnotexex INTO DATA(lo_ex1).
        DATA(lv_error) = |Rule set does not exist: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteReceiptRule](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteReceiptRuleSet`
<a name="ses_DeleteReceiptRuleSet_sap-abap_1_topic"></a>

次の例は、`DeleteReceiptRuleSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ses->deletereceiptruleset( iv_rulesetname = iv_rule_set_name ).
        MESSAGE 'Receipt rule set deleted successfully' TYPE 'I'.
      CATCH /aws1/cx_sescannotdeleteex INTO DATA(lo_ex1).
        DATA(lv_error) = |Cannot delete rule set: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteReceiptRuleSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteTemplate`
<a name="ses_DeleteTemplate_sap-abap_1_topic"></a>

次の例は、`DeleteTemplate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ses->deletetemplate( iv_templatename = iv_template_name ).
        MESSAGE 'Template deleted successfully' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteTemplate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeReceiptRuleSet`
<a name="ses_DescribeReceiptRuleSet_sap-abap_1_topic"></a>

次の例は、`DescribeReceiptRuleSet` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ses->describereceiptruleset(
          iv_rulesetname = iv_rule_set_name
        ).
        MESSAGE 'Receipt rule set described successfully' TYPE 'I'.
      CATCH /aws1/cx_sesrulesetdoesnotexex INTO DATA(lo_ex1).
        DATA(lv_error) = |Rule set does not exist: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeReceiptRuleSet](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetIdentityVerificationAttributes`
<a name="ses_GetIdentityVerificationAttributes_sap-abap_1_topic"></a>

次の例は、`GetIdentityVerificationAttributes` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    DATA lt_identities TYPE /aws1/cl_sesidentitylist_w=>tt_identitylist.
    APPEND NEW /aws1/cl_sesidentitylist_w( iv_value = iv_identity ) TO lt_identities.

    TRY.
        DATA(lo_result) = lo_ses->getidentityverificationattrs(
          it_identities = lt_identities
        ).

        DATA(lt_attrs) = lo_result->get_verificationattributes( ).
        IF lt_attrs IS NOT INITIAL.
          LOOP AT lt_attrs ASSIGNING FIELD-SYMBOL(<ls_attr>).
            ov_status = <ls_attr>-value->get_verificationstatus( ).
            EXIT.
          ENDLOOP.
        ELSE.
          ov_status = 'NotFound'.
        ENDIF.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetIdentityVerificationAttributes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetTemplate`
<a name="ses_GetTemplate_sap-abap_1_topic"></a>

次の例は、`GetTemplate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ses->gettemplate( iv_templatename = iv_template_name ).
        oo_template = lo_result->get_template( ).
        MESSAGE 'Template retrieved successfully' TYPE 'I'.
      CATCH /aws1/cx_sestmpldoesnotexistex INTO DATA(lo_ex1).
        DATA(lv_error) = |Template does not exist: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetTemplate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListIdentities`
<a name="ses_ListIdentities_sap-abap_1_topic"></a>

次の例は、`ListIdentities` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ses->listidentities(
          iv_identitytype = iv_identity_type
          iv_maxitems = iv_max_items
        ).
        ot_identities = lo_result->get_identities( ).
        MESSAGE 'Identities retrieved successfully' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListIdentities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListReceiptFilters`
<a name="ses_ListReceiptFilters_sap-abap_1_topic"></a>

次の例は、`ListReceiptFilters` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ses->listreceiptfilters( ).
        ot_filters = lo_result->get_filters( ).
        MESSAGE 'Receipt filters retrieved successfully' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListReceiptFilters](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTemplates`
<a name="ses_ListTemplates_sap-abap_1_topic"></a>

次の例は、`ListTemplates` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ses->listtemplates( iv_maxitems = iv_max_items ).
        ot_templates = lo_result->get_templatesmetadata( ).
        MESSAGE 'Templates retrieved successfully' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListTemplates](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendEmail`
<a name="ses_SendEmail_sap-abap_1_topic"></a>

次の例は、`SendEmail` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    " Create message object
    DATA(lo_subject) = NEW /aws1/cl_sescontent( iv_data = iv_subject ).
    DATA(lo_text_body) = NEW /aws1/cl_sescontent( iv_data = iv_text ).
    DATA(lo_html_body) = NEW /aws1/cl_sescontent( iv_data = iv_html ).
    DATA(lo_body) = NEW /aws1/cl_sesbody(
      io_text = lo_text_body
      io_html = lo_html_body
    ).
    DATA(lo_message) = NEW /aws1/cl_sesmessage(
      io_subject = lo_subject
      io_body = lo_body
    ).

    TRY.
        " Send email
        DATA(lo_result) = lo_ses->sendemail(
          iv_source = iv_source
          io_destination = io_destination
          io_message = lo_message
          it_replytoaddresses = it_reply_tos
        ).
        ov_msg_id = lo_result->get_messageid( ).
        MESSAGE 'Email sent successfully' TYPE 'I'.
      CATCH /aws1/cx_sesacctsendingpause00 INTO DATA(lo_ex1).
        DATA(lv_error) = |Account sending paused: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_sesmessagerejected INTO DATA(lo_ex2).
        lv_error = |Message rejected: { lo_ex2->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex2.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[SendEmail](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendTemplatedEmail`
<a name="ses_SendTemplatedEmail_sap-abap_1_topic"></a>

次の例は、`SendTemplatedEmail` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Send templated email
        DATA(lo_result) = lo_ses->sendtemplatedemail(
          iv_source = iv_source
          io_destination = io_destination
          iv_template = iv_template_name
          iv_templatedata = iv_template_data
          it_replytoaddresses = it_reply_tos
        ).
        ov_msg_id = lo_result->get_messageid( ).
        MESSAGE 'Templated email sent successfully' TYPE 'I'.
      CATCH /aws1/cx_sestmpldoesnotexistex INTO DATA(lo_ex1).
        DATA(lv_error) = |Template does not exist: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SendTemplatedEmail](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateTemplate`
<a name="ses_UpdateTemplate_sap-abap_1_topic"></a>

次の例は、`UpdateTemplate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    DATA(lo_template) = NEW /aws1/cl_sestemplate(
      iv_templatename = iv_name
      iv_subjectpart = iv_subject
      iv_textpart = iv_text
      iv_htmlpart = iv_html
    ).

    TRY.
        lo_ses->updatetemplate( io_template = lo_template ).
        MESSAGE 'Template updated successfully' TYPE 'I'.
      CATCH /aws1/cx_sestmpldoesnotexistex INTO DATA(lo_ex1).
        DATA(lv_error) = |Template does not exist: { lo_ex1->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex1.
      CATCH /aws1/cx_sesinvalidtemplateex INTO DATA(lo_ex2).
        lv_error = |Invalid template: { lo_ex2->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex2.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex_generic).
        lv_error = |An error occurred: { lo_ex_generic->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex_generic.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateTemplate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `VerifyDomainIdentity`
<a name="ses_VerifyDomainIdentity_sap-abap_1_topic"></a>

次の例は、`VerifyDomainIdentity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ses->verifydomainidentity( iv_domain = iv_domain_name ).
        ov_token = lo_result->get_verificationtoken( ).
        MESSAGE 'Domain verification initiated' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[VerifyDomainIdentity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `VerifyEmailIdentity`
<a name="ses_VerifyEmailIdentity_sap-abap_1_topic"></a>

次の例は、`VerifyEmailIdentity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ses#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ses->verifyemailidentity( iv_emailaddress = iv_email_address ).
        MESSAGE 'Email verification initiated' TYPE 'I'.
      CATCH /aws1/cx_rt_generic INTO DATA(lo_ex).
        DATA(lv_error) = |An error occurred: { lo_ex->get_text( ) }|.
        MESSAGE lv_error TYPE 'I'.
        RAISE EXCEPTION lo_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[VerifyEmailIdentity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon SES API v2 の例
<a name="sap-abap_1_sesv2_code_examples"></a>

次のコード例は、Amazon SES API v2 で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateContact`
<a name="sesv2_CreateContact_sap-abap_1_topic"></a>

次の例は、`CreateContact` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_se2->createcontact(
          iv_contactlistname = iv_contact_list_name
          iv_emailaddress = iv_email_address ).
        MESSAGE 'Contact created successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2alreadyexistsex.
        MESSAGE 'Contact already exists.' TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex.
        MESSAGE 'Bad request.' TYPE 'E'.
      CATCH /aws1/cx_se2notfoundexception.
        MESSAGE 'Contact list not found.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateContact](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateContactList`
<a name="sesv2_CreateContactList_sap-abap_1_topic"></a>

次の例は、`CreateContactList` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_se2->createcontactlist(
          iv_contactlistname = iv_contact_list_name ).
        MESSAGE 'Contact list created successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2alreadyexistsex.
        MESSAGE 'Contact list already exists.' TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE 'Bad request - contact list limit may be reached.' TYPE 'I'.
        " Re-raise the exception so the caller can handle it
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_se2limitexceededex INTO DATA(lo_limit_exceeded).
        MESSAGE 'Limit exceeded - contact list limit reached.' TYPE 'I'.
        " Re-raise the exception so the caller can handle it
        RAISE EXCEPTION lo_limit_exceeded.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateContactList](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateEmailIdentity`
<a name="sesv2_CreateEmailIdentity_sap-abap_1_topic"></a>

次の例は、`CreateEmailIdentity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_se2->createemailidentity(
          iv_emailidentity = iv_email_identity ).
        MESSAGE 'Email identity created successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2alreadyexistsex.
        MESSAGE 'Email identity already exists.' TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE lo_bad_request TYPE 'I' DISPLAY LIKE 'E'.
      CATCH /aws1/cx_se2limitexceededex INTO DATA(lo_limit_exceeded).
        MESSAGE lo_limit_exceeded TYPE 'I' DISPLAY LIKE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [CreateEmailIdentity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateEmailTemplate`
<a name="sesv2_CreateEmailTemplate_sap-abap_1_topic"></a>

次の例は、`CreateEmailTemplate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_template_content) = NEW /aws1/cl_se2emailtmplcontent(
          iv_subject = iv_subject
          iv_html = iv_html
          iv_text = iv_text ).

        lo_se2->createemailtemplate(
          iv_templatename = iv_template_name
          io_templatecontent = lo_template_content ).
        MESSAGE 'Email template created successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2alreadyexistsex.
        MESSAGE 'Email template already exists.' TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex.
        MESSAGE 'Bad request.' TYPE 'E'.
      CATCH /aws1/cx_se2limitexceededex.
        MESSAGE 'Limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP* [CreateEmailTemplate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteContactList`
<a name="sesv2_DeleteContactList_sap-abap_1_topic"></a>

次の例は、`DeleteContactList` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_se2->deletecontactlist(
          iv_contactlistname = iv_contact_list_name ).
        MESSAGE 'Contact list deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2notfoundexception.
        MESSAGE 'Contact list not found.' TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE 'Bad request.' TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteContactList](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteEmailIdentity`
<a name="sesv2_DeleteEmailIdentity_sap-abap_1_topic"></a>

次の例は、`DeleteEmailIdentity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_se2->deleteemailidentity(
          iv_emailidentity = iv_email_identity ).
        MESSAGE 'Email identity deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2notfoundexception.
        MESSAGE 'Email identity not found.' TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE 'Bad request.' TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteEmailIdentity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteEmailTemplate`
<a name="sesv2_DeleteEmailTemplate_sap-abap_1_topic"></a>

次の例は、`DeleteEmailTemplate` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_se2->deleteemailtemplate(
          iv_templatename = iv_template_name ).
        MESSAGE 'Email template deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2notfoundexception.
        MESSAGE 'Email template not found.' TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE 'Bad request.' TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteEmailTemplate](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListContacts`
<a name="sesv2_ListContacts_sap-abap_1_topic"></a>

次の例は、`ListContacts` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_se2->listcontacts(
          iv_contactlistname = iv_contact_list_name ).
        DATA(lv_count) = lines( oo_result->get_contacts( ) ).
        MESSAGE |Retrieved { lv_count } contacts from list.| TYPE 'I'.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE 'Bad request.' TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_se2notfoundexception INTO DATA(lo_not_found).
        MESSAGE 'Contact list not found.' TYPE 'I'.
        RAISE EXCEPTION lo_not_found.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListContacts](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendEmail`
<a name="sesv2_SendEmail_sap-abap_1_topic"></a>

次の例は、`SendEmail` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/se2#code-examples)での設定と実行の方法を確認してください。
メッセージを送信します。  

```
    TRY.
        " Create destination with recipient address
        DATA lt_to_addresses TYPE /aws1/cl_se2emailaddresslist_w=>tt_emailaddresslist.
        APPEND NEW /aws1/cl_se2emailaddresslist_w( iv_value = iv_to_email_address ) TO lt_to_addresses.
        DATA(lo_destination) = NEW /aws1/cl_se2destination(
          it_toaddresses = lt_to_addresses ).

        " Create message content
        DATA(lo_subject) = NEW /aws1/cl_se2content( iv_data = iv_subject ).
        DATA(lo_text_body) = NEW /aws1/cl_se2content( iv_data = iv_text_body ).
        DATA(lo_html_body) = NEW /aws1/cl_se2content( iv_data = iv_html_body ).
        DATA(lo_body) = NEW /aws1/cl_se2body(
          io_text = lo_text_body
          io_html = lo_html_body ).
        DATA(lo_message) = NEW /aws1/cl_se2message(
          io_subject = lo_subject
          io_body = lo_body ).

        DATA(lo_content) = NEW /aws1/cl_se2emailcontent(
          io_simple = lo_message ).

        " Send the email
        lo_se2->sendemail(
          iv_fromemailaddress = iv_from_email_address
          io_destination = lo_destination
          io_content = lo_content ).
        MESSAGE 'Email sent successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2accountsuspendedex INTO DATA(lo_account_suspended).
        MESSAGE 'Account suspended.' TYPE 'I'.
        RAISE EXCEPTION lo_account_suspended.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE 'Bad request.' TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_se2messagerejected INTO DATA(lo_message_rejected).
        MESSAGE 'Message rejected - check email verification.' TYPE 'I'.
        RAISE EXCEPTION lo_message_rejected.
    ENDTRY.
```
テンプレートを使用してメッセージを送信します。  

```
    TRY.
        " Create destination with recipient address
        DATA lt_to_addresses TYPE /aws1/cl_se2emailaddresslist_w=>tt_emailaddresslist.
        APPEND NEW /aws1/cl_se2emailaddresslist_w( iv_value = iv_to_email_address ) TO lt_to_addresses.
        DATA(lo_destination) = NEW /aws1/cl_se2destination(
          it_toaddresses = lt_to_addresses ).

        " Create template reference
        DATA(lo_template) = NEW /aws1/cl_se2template(
          iv_templatename = iv_template_name
          iv_templatedata = iv_template_data ).

        DATA(lo_content) = NEW /aws1/cl_se2emailcontent(
          io_template = lo_template ).

        " Create list management options
        DATA(lo_list_mgmt) = NEW /aws1/cl_se2listmanagementopts(
          iv_contactlistname = iv_contact_list_name ).

        " Send the email using template
        lo_se2->sendemail(
          iv_fromemailaddress = iv_from_email_address
          io_destination = lo_destination
          io_content = lo_content
          io_listmanagementoptions = lo_list_mgmt ).
        MESSAGE 'Email sent using template successfully.' TYPE 'I'.
      CATCH /aws1/cx_se2accountsuspendedex INTO DATA(lo_account_suspended).
        MESSAGE 'Account suspended.' TYPE 'I'.
        RAISE EXCEPTION lo_account_suspended.
      CATCH /aws1/cx_se2badrequestex INTO DATA(lo_bad_request).
        MESSAGE 'Bad request.' TYPE 'I'.
        RAISE EXCEPTION lo_bad_request.
      CATCH /aws1/cx_se2messagerejected INTO DATA(lo_message_rejected).
        MESSAGE 'Message rejected - check email verification.' TYPE 'I'.
        RAISE EXCEPTION lo_message_rejected.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[SendEmail](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon SNS の例
<a name="sap-abap_1_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_sap-abap_1_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    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](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteTopic`
<a name="sns_DeleteTopic_sap-abap_1_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sns->deletetopic( iv_topicarn = iv_topic_arn ).
        MESSAGE 'SNS topic deleted.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[DeleteTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetTopicAttributes`
<a name="sns_GetTopicAttributes_sap-abap_1_topic"></a>

次のコード例は、`GetTopicAttributes` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sns->gettopicattributes( iv_topicarn = iv_topic_arn ). " oo_result is returned for testing purposes. "
        DATA(lt_attributes) = oo_result->get_attributes( ).
        MESSAGE 'Retrieved attributes/properties of a topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[GetTopicAttributes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListSubscriptions`
<a name="sns_ListSubscriptions_sap-abap_1_topic"></a>

次のコード例は、`ListSubscriptions` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sns->listsubscriptions( ).                " oo_result is returned for testing purposes. "
        DATA(lt_subscriptions) = oo_result->get_subscriptions( ).
        MESSAGE 'Retrieved list of subscribers.' TYPE 'I'.
      CATCH /aws1/cx_rt_generic.
        MESSAGE 'Unable to list subscribers.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[ListSubscriptions](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTopics`
<a name="sns_ListTopics_sap-abap_1_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sns->listtopics( ).            " oo_result is returned for testing purposes. "
        DATA(lt_topics) = oo_result->get_topics( ).
        MESSAGE 'Retrieved list of topics.' TYPE 'I'.
      CATCH /aws1/cx_rt_generic.
        MESSAGE 'Unable to list topics.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[ListTopics](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Publish`
<a name="sns_Publish_sap-abap_1_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = iv_message ).
        MESSAGE 'Message published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
属性を含むメッセージをトピックに発行します。  

```
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = iv_message
          it_messageattributes = it_msg_attrs ).
        MESSAGE 'Message with attributes published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
マルチフォーマットメッセージをトピックに発行します。  

```
    " Build JSON message structure for multi-format message
    DATA(lv_json_message) = |\{ "default": "{ iv_default_message }", "sms": "{ iv_sms_message }", "email": "{ iv_email_message }" \}|.

    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = lv_json_message
          iv_subject = iv_subject
          iv_messagestructure = 'json' ).
        MESSAGE 'Multi-format message published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[Publish](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SetSubscriptionAttributes`
<a name="sns_SetSubscriptionAttributes_sap-abap_1_topic"></a>

次の例は、`SetSubscriptionAttributes` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sns->setsubscriptionattributes(
            iv_subscriptionarn = iv_subscription_arn
            iv_attributename  = 'FilterPolicy'
            iv_attributevalue = iv_filter_policy ).
        MESSAGE 'Added filter policy to subscription.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Subscription does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[SetSubscriptionAttributes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SetTopicAttributes`
<a name="sns_SetTopicAttributes_sap-abap_1_topic"></a>

次の例は、`SetTopicAttributes` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sns->settopicattributes(
            iv_topicarn = iv_topic_arn
            iv_attributename  = iv_attribute_name
            iv_attributevalue = iv_attribute_value ).
        MESSAGE 'Set/updated SNS topic attributes.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[SetTopicAttributes](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Subscribe`
<a name="sns_Subscribe_sap-abap_1_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
    TRY.
        oo_result = lo_sns->subscribe(                      "oo_result is returned for testing purposes."
                iv_topicarn = iv_topic_arn
                iv_protocol = 'email'
                iv_endpoint = iv_email_address
                iv_returnsubscriptionarn = abap_true ).
        MESSAGE 'Email address subscribed to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
      CATCH /aws1/cx_snssubscriptionlmte00.
        MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[Subscribe](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `Unsubscribe`
<a name="sns_Unsubscribe_sap-abap_1_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sns->unsubscribe( iv_subscriptionarn = iv_subscription_arn ).
        MESSAGE 'Subscription deleted.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Subscription does not exist.' TYPE 'E'.
      CATCH /aws1/cx_snsinvalidparameterex.
        MESSAGE 'Subscription with "PendingConfirmation" status cannot be deleted/unsubscribed. Confirm subscription before performing unsubscribe operation.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、**「AWS SDK for SAP ABAP API リファレンス」の「[Unsubscribe](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### FIFO トピックを作成して発行する
<a name="sns_PublishFifoTopic_sap-abap_1_topic"></a>

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。
FIFO トピックを作成し、そのトピックに Amazon SQS FIFO キューをサブスクライブして、Amazon SNS トピックにメッセージを発行します。  

```
    " Creates a FIFO topic. "
    DATA lt_tpc_attributes TYPE /aws1/cl_snstopicattrsmap_w=>tt_topicattributesmap.
    DATA ls_tpc_attributes TYPE /aws1/cl_snstopicattrsmap_w=>ts_topicattributesmap_maprow.
    ls_tpc_attributes-key = 'FifoTopic'.
    ls_tpc_attributes-value = NEW /aws1/cl_snstopicattrsmap_w( iv_value = 'true' ).
    INSERT ls_tpc_attributes INTO TABLE lt_tpc_attributes.

    TRY.
        DATA(lo_create_result) = lo_sns->createtopic(
               iv_name = iv_topic_name
               it_attributes = lt_tpc_attributes ).
        DATA(lv_topic_arn) = lo_create_result->get_topicarn( ).
        ov_topic_arn = lv_topic_arn.                                    " ov_topic_arn is returned for testing purposes. "
        MESSAGE 'FIFO 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.

    " Subscribes an endpoint to an Amazon Simple Notification Service (Amazon SNS) topic. "
    " Only Amazon Simple Queue Service (Amazon SQS) FIFO queues can be subscribed to an SNS FIFO topic. "
    TRY.
        DATA(lo_subscribe_result) = lo_sns->subscribe(
               iv_topicarn = lv_topic_arn
               iv_protocol = 'sqs'
               iv_endpoint = iv_queue_arn ).
        DATA(lv_subscription_arn) = lo_subscribe_result->get_subscriptionarn( ).
        ov_subscription_arn = lv_subscription_arn.                      " ov_subscription_arn is returned for testing purposes. "
        MESSAGE 'SQS queue was subscribed to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
      CATCH /aws1/cx_snssubscriptionlmte00.
        MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'.
    ENDTRY.

    " Publish message to SNS topic. "
    TRY.
        DATA lt_msg_attributes TYPE /aws1/cl_snsmessageattrvalue=>tt_messageattributemap.
        DATA ls_msg_attributes TYPE /aws1/cl_snsmessageattrvalue=>ts_messageattributemap_maprow.
        ls_msg_attributes-key = 'Importance'.
        ls_msg_attributes-value = NEW /aws1/cl_snsmessageattrvalue( iv_datatype = 'String'
                                                                    iv_stringvalue = 'High' ).
        INSERT ls_msg_attributes INTO TABLE lt_msg_attributes.

        DATA(lo_result) = lo_sns->publish(
             iv_topicarn = lv_topic_arn
             iv_message = 'The price of your mobile plan has been increased from $19 to $23'
             iv_subject = 'Changes to mobile plan'
             iv_messagegroupid = 'Update-2'
             iv_messagededuplicationid = 'Update-2.1'
             it_messageattributes = lt_msg_attributes ).
        ov_message_id = lo_result->get_messageid( ).                    " ov_message_id is returned for testing purposes. "
        MESSAGE 'Message was published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [CreateTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [Publish](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [Subscribe](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

### SMS テキストメッセージを発行する
<a name="sns_PublishTextSMS_sap-abap_1_topic"></a>

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    " iv_phone_number = '+12065550101' - Phone number in E.164 format
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_phonenumber = iv_phone_number
          iv_message = iv_message ).
        MESSAGE 'Message published to phone number.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Phone number does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、*AWS SDK for SAP ABAP API リファレンス*の「[Publish](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon SQS の例
<a name="sap-abap_1_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `CreateQueue`
<a name="sqs_CreateQueue_sap-abap_1_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS 標準キューを作成します。  

```
    TRY.
        oo_result = lo_sqs->createqueue( iv_queuename = iv_queue_name ).        " oo_result is returned for testing purposes. "
        MESSAGE 'SQS queue created.' TYPE 'I'.
      CATCH /aws1/cx_sqsqueuedeldrecently.
        MESSAGE 'After deleting a queue, wait 60 seconds before creating another queue with the same name.' TYPE 'E'.
      CATCH /aws1/cx_sqsqueuenameexists.
        MESSAGE 'A queue with this name already exists.' TYPE 'E'.
    ENDTRY.
```
メッセージが到着するまで待機する Amazon SQS キューを作成します。  

```
    TRY.
        DATA lt_attributes TYPE /aws1/cl_sqsqueueattrmap_w=>tt_queueattributemap.
        DATA ls_attribute TYPE /aws1/cl_sqsqueueattrmap_w=>ts_queueattributemap_maprow.
        ls_attribute-key = 'ReceiveMessageWaitTimeSeconds'.               " Time in seconds for long polling, such as how long the call waits for a message to arrive in the queue before returning. "
        ls_attribute-value = NEW /aws1/cl_sqsqueueattrmap_w( iv_value = iv_wait_time ).
        INSERT ls_attribute INTO TABLE lt_attributes.
        oo_result = lo_sqs->createqueue(                  " oo_result is returned for testing purposes. "
                iv_queuename = iv_queue_name
                it_attributes = lt_attributes ).
        MESSAGE 'SQS queue created.' TYPE 'I'.
      CATCH /aws1/cx_sqsqueuedeldrecently.
        MESSAGE 'After deleting a queue, wait 60 seconds before creating another queue with the same name.' TYPE 'E'.
      CATCH /aws1/cx_sqsqueuenameexists.
        MESSAGE 'A queue with this name already exists.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[CreateQueue](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteMessage`
<a name="sqs_DeleteMessage_sap-abap_1_topic"></a>

次の例は、`DeleteMessage` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sqs->deletemessage(
           iv_queueurl = iv_queue_url
           iv_receipthandle = iv_receipt_handle ).
        MESSAGE 'Message deleted from SQS queue.' TYPE 'I'.
      CATCH /aws1/cx_sqsinvalididformat.
        MESSAGE 'The specified receipt handle is not valid.' TYPE 'E'.
      CATCH /aws1/cx_sqsreceipthandleisinv.
        MESSAGE 'The specified receipt handle is not valid for the current version.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteMessage](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteMessageBatch`
<a name="sqs_DeleteMessageBatch_sap-abap_1_topic"></a>

次の例は、`DeleteMessageBatch` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sqs->deletemessagebatch(       " oo_result is returned for testing purposes. "
           iv_queueurl = iv_queue_url
           it_entries = it_entries ).
        MESSAGE 'Messages deleted from SQS queue.' TYPE 'I'.
      CATCH /aws1/cx_sqsbtcentidsnotdist00.
        MESSAGE 'Two or more batch entries in the request have the same ID.' TYPE 'E'.
      CATCH /aws1/cx_sqsemptybatchrequest.
        MESSAGE 'The batch request does not contain any entries.' TYPE 'E'.
      CATCH /aws1/cx_sqsinvbatchentryid.
        MESSAGE 'The ID of a batch entry in a batch request is not valid.' TYPE 'E'.
      CATCH /aws1/cx_sqstoomanyentriesin00.
        MESSAGE 'The batch request contains more entries than allowed.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteMessageBatch](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteQueue`
<a name="sqs_DeleteQueue_sap-abap_1_topic"></a>

次の例は、`DeleteQueue` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sqs->deletequeue( iv_queueurl = iv_queue_url ).
        MESSAGE 'SQS queue deleted' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DeleteQueue](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetQueueUrl`
<a name="sqs_GetQueueUrl_sap-abap_1_topic"></a>

次のコード例は、`GetQueueUrl` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sqs->getqueueurl( iv_queuename = iv_queue_name ).        " oo_result is returned for testing purposes. "
        MESSAGE 'Queue URL retrieved.' TYPE 'I'.
      CATCH /aws1/cx_sqsqueuedoesnotexist.
        MESSAGE 'The requested queue does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetQueueUrl](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListQueues`
<a name="sqs_ListQueues_sap-abap_1_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sqs->listqueues( ).        " oo_result is returned for testing purposes. "
        MESSAGE 'Retrieved list of queues.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListQueues](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_sap-abap_1_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。
Amazon SQS キューからメッセージを受信します。  

```
    TRY.
        oo_result = lo_sqs->receivemessage( iv_queueurl = iv_queue_url ).    " oo_result is returned for testing purposes. "
        DATA(lt_messages) = oo_result->get_messages( ).
        MESSAGE 'Message received from SQS queue.' TYPE 'I'.
      CATCH /aws1/cx_sqsoverlimit.
        MESSAGE 'Maximum number of in-flight messages reached.' TYPE 'E'.
    ENDTRY.
```
ロングポーリングサポートを使用して Amazon SQS キューからメッセージを受信します。  

```
    TRY.
        oo_result = lo_sqs->receivemessage(           " oo_result is returned for testing purposes. "
                iv_queueurl = iv_queue_url
                iv_waittimeseconds = iv_wait_time ).    " Time in seconds for long polling, such as how long the call waits for a message to arrive in the queue before returning. " ).
        DATA(lt_messages) = oo_result->get_messages( ).
        MESSAGE 'Message received from SQS queue.' TYPE 'I'.
      CATCH /aws1/cx_sqsoverlimit.
        MESSAGE 'Maximum number of in-flight messages reached.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ReceiveMessage](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendMessage`
<a name="sqs_SendMessage_sap-abap_1_topic"></a>

次のコード例は、`SendMessage` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sqs->sendmessage(              " oo_result is returned for testing purposes. "
           iv_queueurl = iv_queue_url
           iv_messagebody = iv_message ).
        MESSAGE 'Message sent to SQS queue.' TYPE 'I'.
      CATCH /aws1/cx_sqsinvalidmsgconts.
        MESSAGE 'Message contains non-valid characters.' TYPE 'E'.
      CATCH /aws1/cx_sqsunsupportedop.
        MESSAGE 'Operation not supported.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[SendMessage](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendMessageBatch`
<a name="sqs_SendMessageBatch_sap-abap_1_topic"></a>

次の例は、`SendMessageBatch` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sqs#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sqs->sendmessagebatch(         " oo_result is returned for testing purposes. "
           iv_queueurl = iv_queue_url
           it_entries = it_messages ).
        MESSAGE 'Messages sent to SQS queue.' TYPE 'I'.
      CATCH /aws1/cx_sqsbtcentidsnotdist00.
        MESSAGE 'Two or more batch entries in the request have the same ID.' TYPE 'E'.
      CATCH /aws1/cx_sqsbatchreqtoolong.
        MESSAGE 'The length of all the messages put together is more than the limit.' TYPE 'E'.
      CATCH /aws1/cx_sqsemptybatchrequest.
        MESSAGE 'The batch request does not contain any entries.' TYPE 'E'.
      CATCH /aws1/cx_sqsinvbatchentryid.
        MESSAGE 'The ID of a batch entry in a batch request is not valid.' TYPE 'E'.
      CATCH /aws1/cx_sqstoomanyentriesin00.
        MESSAGE 'The batch request contains more entries than allowed.' TYPE 'E'.
      CATCH /aws1/cx_sqsunsupportedop.
        MESSAGE 'Operation not supported.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SendMessageBatch](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### FIFO トピックを作成して発行する
<a name="sns_PublishFifoTopic_sap-abap_1_topic"></a>

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

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。
FIFO トピックを作成し、そのトピックに Amazon SQS FIFO キューをサブスクライブして、Amazon SNS トピックにメッセージを発行します。  

```
    " Creates a FIFO topic. "
    DATA lt_tpc_attributes TYPE /aws1/cl_snstopicattrsmap_w=>tt_topicattributesmap.
    DATA ls_tpc_attributes TYPE /aws1/cl_snstopicattrsmap_w=>ts_topicattributesmap_maprow.
    ls_tpc_attributes-key = 'FifoTopic'.
    ls_tpc_attributes-value = NEW /aws1/cl_snstopicattrsmap_w( iv_value = 'true' ).
    INSERT ls_tpc_attributes INTO TABLE lt_tpc_attributes.

    TRY.
        DATA(lo_create_result) = lo_sns->createtopic(
               iv_name = iv_topic_name
               it_attributes = lt_tpc_attributes ).
        DATA(lv_topic_arn) = lo_create_result->get_topicarn( ).
        ov_topic_arn = lv_topic_arn.                                    " ov_topic_arn is returned for testing purposes. "
        MESSAGE 'FIFO 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.

    " Subscribes an endpoint to an Amazon Simple Notification Service (Amazon SNS) topic. "
    " Only Amazon Simple Queue Service (Amazon SQS) FIFO queues can be subscribed to an SNS FIFO topic. "
    TRY.
        DATA(lo_subscribe_result) = lo_sns->subscribe(
               iv_topicarn = lv_topic_arn
               iv_protocol = 'sqs'
               iv_endpoint = iv_queue_arn ).
        DATA(lv_subscription_arn) = lo_subscribe_result->get_subscriptionarn( ).
        ov_subscription_arn = lv_subscription_arn.                      " ov_subscription_arn is returned for testing purposes. "
        MESSAGE 'SQS queue was subscribed to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
      CATCH /aws1/cx_snssubscriptionlmte00.
        MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'.
    ENDTRY.

    " Publish message to SNS topic. "
    TRY.
        DATA lt_msg_attributes TYPE /aws1/cl_snsmessageattrvalue=>tt_messageattributemap.
        DATA ls_msg_attributes TYPE /aws1/cl_snsmessageattrvalue=>ts_messageattributemap_maprow.
        ls_msg_attributes-key = 'Importance'.
        ls_msg_attributes-value = NEW /aws1/cl_snsmessageattrvalue( iv_datatype = 'String'
                                                                    iv_stringvalue = 'High' ).
        INSERT ls_msg_attributes INTO TABLE lt_msg_attributes.

        DATA(lo_result) = lo_sns->publish(
             iv_topicarn = lv_topic_arn
             iv_message = 'The price of your mobile plan has been increased from $19 to $23'
             iv_subject = 'Changes to mobile plan'
             iv_messagegroupid = 'Update-2'
             iv_messagededuplicationid = 'Update-2.1'
             it_messageattributes = lt_msg_attributes ).
        ov_message_id = lo_result->get_messageid( ).                    " ov_message_id is returned for testing purposes. "
        MESSAGE 'Message was published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [CreateTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [Publish](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [Subscribe](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

# SDK for SAP ABAP を使用した Step Functions の例
<a name="sap-abap_1_sfn_code_examples"></a>

次のコード例は、Step Functions で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateActivity`
<a name="sfn_CreateActivity_sap-abap_1_topic"></a>

次の例は、`CreateActivity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_sfn->createactivity(
          iv_name = iv_name
        ).
        ov_activity_arn = lo_result->get_activityarn( ).
        MESSAGE 'Activity created successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfnactivityalrdyex.
        MESSAGE 'Activity already exists.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidname.
        MESSAGE 'Invalid activity name.' TYPE 'E'.
      CATCH /aws1/cx_sfnactivitylimitexcd.
        MESSAGE 'Activity limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateActivity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateStateMachine`
<a name="sfn_CreateStateMachine_sap-abap_1_topic"></a>

次の例は、`CreateStateMachine` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_sfn->createstatemachine(
          iv_name = iv_name
          iv_definition = iv_definition
          iv_rolearn = iv_role_arn
        ).
        ov_state_machine_arn = lo_result->get_statemachinearn( ).
        MESSAGE 'State machine created successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfnstatemachinealrex.
        MESSAGE 'State machine already exists.' TYPE 'E'.
      CATCH /aws1/cx_sfninvaliddefinition.
        MESSAGE 'Invalid state machine definition.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidname.
        MESSAGE 'Invalid state machine name.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidarn.
        MESSAGE 'Invalid role ARN.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateStateMachine](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteActivity`
<a name="sfn_DeleteActivity_sap-abap_1_topic"></a>

次の例は、`DeleteActivity` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sfn->deleteactivity(
          iv_activityarn = iv_activity_arn
        ).
        MESSAGE 'Activity deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfninvalidarn.
        MESSAGE 'Invalid activity ARN.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteActivity](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteStateMachine`
<a name="sfn_DeleteStateMachine_sap-abap_1_topic"></a>

次の例は、`DeleteStateMachine` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sfn->deletestatemachine(
          iv_statemachinearn = iv_state_machine_arn
        ).
        MESSAGE 'State machine deleted successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfninvalidarn.
        MESSAGE 'Invalid state machine ARN.' TYPE 'E'.
      CATCH /aws1/cx_sfnvalidationex.
        MESSAGE 'Validation error occurred.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteStateMachine](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeExecution`
<a name="sfn_DescribeExecution_sap-abap_1_topic"></a>

次の例は、`DescribeExecution` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sfn->describeexecution(
          iv_executionarn = iv_execution_arn
        ).
        MESSAGE 'Execution described successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfnexecdoesnotexist.
        MESSAGE 'Execution does not exist.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidarn.
        MESSAGE 'Invalid execution ARN.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeExecution](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeStateMachine`
<a name="sfn_DescribeStateMachine_sap-abap_1_topic"></a>

次の例は、`DescribeStateMachine` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sfn->describestatemachine(
          iv_statemachinearn = iv_state_machine_arn
        ).
        MESSAGE 'State machine described successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfnstatemachinedoes00.
        MESSAGE 'State machine does not exist.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidarn.
        MESSAGE 'Invalid state machine ARN.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[DescribeStateMachine](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetActivityTask`
<a name="sfn_GetActivityTask_sap-abap_1_topic"></a>

次の例は、`GetActivityTask` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_sfn->getactivitytask(
          iv_activityarn = iv_activity_arn
        ).
        MESSAGE 'Activity task retrieved successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfnactivitydoesnotex.
        MESSAGE 'Activity does not exist.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidarn.
        MESSAGE 'Invalid activity ARN.' TYPE 'E'.
      CATCH /aws1/cx_sfnactivityworkerlm00.
        MESSAGE 'Activity worker limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetActivityTask](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListActivities`
<a name="sfn_ListActivities_sap-abap_1_topic"></a>

次の例は、`ListActivities` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_sfn->listactivities( ).
        DATA(lt_activities) = lo_result->get_activities( ).
        LOOP AT lt_activities INTO DATA(lo_activity).
          IF lo_activity->get_name( ) = iv_name.
            ov_activity_arn = lo_activity->get_activityarn( ).
            EXIT.
          ENDIF.
        ENDLOOP.
        MESSAGE 'Activities listed successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfninvalidtoken.
        MESSAGE 'Invalid pagination token.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListActivities](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListStateMachines`
<a name="sfn_ListStateMachines_sap-abap_1_topic"></a>

次の例は、`ListStateMachines` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_sfn->liststatemachines( ).
        DATA(lt_state_machines) = lo_result->get_statemachines( ).
        LOOP AT lt_state_machines INTO DATA(lo_state_machine).
          IF lo_state_machine->get_name( ) = iv_name.
            ov_state_machine_arn = lo_state_machine->get_statemachinearn( ).
            EXIT.
          ENDIF.
        ENDLOOP.
        MESSAGE 'State machines listed successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfninvalidtoken.
        MESSAGE 'Invalid pagination token.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListStateMachines](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendTaskSuccess`
<a name="sfn_SendTaskSuccess_sap-abap_1_topic"></a>

次の例は、`SendTaskSuccess` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_sfn->sendtasksuccess(
          iv_tasktoken = iv_task_token
          iv_output = iv_task_response
        ).
        MESSAGE 'Task success sent successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfninvalidtoken.
        MESSAGE 'Invalid task token.' TYPE 'E'.
      CATCH /aws1/cx_sfntaskdoesnotexist.
        MESSAGE 'Task does not exist.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidoutput.
        MESSAGE 'Invalid task output.' TYPE 'E'.
      CATCH /aws1/cx_sfntasktimedout.
        MESSAGE 'Task timed out.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[SendTaskSuccess](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartExecution`
<a name="sfn_StartExecution_sap-abap_1_topic"></a>

次の例は、`StartExecution` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sfn#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_sfn->startexecution(
          iv_statemachinearn = iv_state_machine_arn
          iv_input = iv_input
        ).
        ov_execution_arn = lo_result->get_executionarn( ).
        MESSAGE 'Execution started successfully.' TYPE 'I'.
      CATCH /aws1/cx_sfnstatemachinedoes00.
        MESSAGE 'State machine does not exist.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidarn.
        MESSAGE 'Invalid state machine ARN.' TYPE 'E'.
      CATCH /aws1/cx_sfninvalidexecinput.
        MESSAGE 'Invalid execution input.' TYPE 'E'.
      CATCH /aws1/cx_sfnexeclimitexceeded.
        MESSAGE 'Execution limit exceeded.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartExecution](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Systems Manager の例
<a name="sap-abap_1_ssm_code_examples"></a>

次のコード例は、Systems Manager で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateDocument`
<a name="ssm_CreateDocument_sap-abap_1_topic"></a>

次の例は、`CreateDocument` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ssm->createdocument(
            iv_name = iv_name
            iv_content = iv_content
            iv_documenttype = 'Command' ).
        MESSAGE 'Document created.' TYPE 'I'.
      CATCH /aws1/cx_ssmdocalreadyexists.
        MESSAGE 'Document already exists.' TYPE 'I'.
      CATCH /aws1/cx_ssminvaliddoccontent.
        MESSAGE 'Invalid document content.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[CreateDocument](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateMaintenanceWindow`
<a name="ssm_CreateMaintenanceWindow_sap-abap_1_topic"></a>

次の例は、`CreateMaintenanceWindow` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ssm->createmaintenancewindow(
            iv_name = iv_name
            iv_schedule = iv_schedule
            iv_duration = iv_duration
            iv_cutoff = iv_cutoff
            iv_allowunassociatedtargets = iv_allow_unassociated_targets ).
        MESSAGE 'Maintenance window created.' TYPE 'I'.
      CATCH /aws1/cx_ssmresrclimitexcdex.
        MESSAGE 'Resource limit exceeded.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[CreateMaintenanceWindow](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `CreateOpsItem`
<a name="ssm_CreateOpsItem_sap-abap_1_topic"></a>

次の例は、`CreateOpsItem` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_ssm->createopsitem(
            iv_title = iv_title
            iv_source = iv_source
            iv_category = iv_category
            iv_severity = iv_severity
            iv_description = iv_description ).
        MESSAGE 'OpsItem created.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsitemlimitexcdex.
        MESSAGE 'You have exceeded your open OpsItem limit.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsitemalrdyexex.
        MESSAGE 'OpsItem already exists.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[CreateOpsItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteDocument`
<a name="ssm_DeleteDocument_sap-abap_1_topic"></a>

次の例は、`DeleteDocument` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ssm->deletedocument( iv_name = iv_name ).
        MESSAGE 'Document deleted.' TYPE 'I'.
      CATCH /aws1/cx_ssminvaliddocument.
        MESSAGE 'Invalid document.' TYPE 'I'.
      CATCH /aws1/cx_ssmassocdinstances.
        MESSAGE 'Document has associated instances.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DeleteDocument](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `DeleteMaintenanceWindow`
<a name="ssm_DeleteMaintenanceWindow_sap-abap_1_topic"></a>

次の例は、`DeleteMaintenanceWindow` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ssm->deletemaintenancewindow( iv_windowid = iv_window_id ).
        MESSAGE 'Maintenance window deleted.' TYPE 'I'.
      CATCH /aws1/cx_ssminternalservererr.
        MESSAGE 'Internal server error occurred.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DeleteMaintenanceWindow](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteOpsItem`
<a name="ssm_DeleteOpsItem_sap-abap_1_topic"></a>

次の例は、`DeleteOpsItem` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ssm->deleteopsitem( iv_opsitemid = iv_ops_item_id ).
        MESSAGE 'OpsItem deleted.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsiteminvparamex.
        MESSAGE 'Invalid OpsItem parameter.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DeleteOpsItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。**

### `DescribeDocument`
<a name="ssm_DescribeDocument_sap-abap_1_topic"></a>

次の例は、`DescribeDocument` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ssm->describedocument( iv_name = iv_name ).
        DATA(lo_document) = lo_result->get_document( ).
        IF lo_document IS BOUND.
          rv_status = lo_document->get_status( ).
          MESSAGE |Document status: { rv_status }| TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_ssminvaliddocument.
        MESSAGE 'Invalid document.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DescribeDocument](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DescribeOpsItems`
<a name="ssm_DescribeOpsItems_sap-abap_1_topic"></a>

次の例は、`DescribeOpsItems` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Create filter for OpsItem ID
        DATA(lt_filters) = VALUE /aws1/cl_ssmopsitemfilter=>tt_opsitemfilters(
          ( NEW /aws1/cl_ssmopsitemfilter(
              iv_key = 'OpsItemId'
              it_values = VALUE /aws1/cl_ssmopsitemfiltvals_w=>tt_opsitemfiltervalues(
                ( NEW /aws1/cl_ssmopsitemfiltvals_w( iv_value = iv_ops_item_id ) )
              )
              iv_operator = 'Equal'
            ) )
        ).

        " Use paginator to get all results
        DATA(lo_paginator) = lo_ssm->get_paginator( ).
        DATA(lo_iterator) = lo_paginator->describeopsitems(
          it_opsitemfilters = lt_filters ).

        rv_found = abap_false.

        WHILE lo_iterator->has_next( ).
          DATA(lo_result) = CAST /aws1/cl_ssmdescropsitemsrsp( lo_iterator->get_next( ) ).
          LOOP AT lo_result->get_opsitemsummaries( ) INTO DATA(lo_item).
            DATA(lv_title) = lo_item->get_title( ).
            DATA(lv_status) = lo_item->get_status( ).
            MESSAGE |The OpsItem title is { lv_title } and the status is { lv_status }| TYPE 'I'.
            rv_found = abap_true.
          ENDLOOP.
        ENDWHILE.
      CATCH /aws1/cx_ssminternalservererr.
        MESSAGE 'Internal server error occurred.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[DescribeOpsItems](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListCommandInvocations`
<a name="ssm_ListCommandInvocations_sap-abap_1_topic"></a>

次の例は、`ListCommandInvocations` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        " Use paginator to get all results
        DATA(lo_paginator) = lo_ssm->get_paginator( ).
        DATA(lo_iterator) = lo_paginator->listcommandinvocations(
          iv_instanceid = iv_instance_id ).

        DATA lv_count TYPE i VALUE 0.

        WHILE lo_iterator->has_next( ).
          DATA(lo_result) = CAST /aws1/cl_ssmlistcmdinvcsresult( lo_iterator->get_next( ) ).
          LOOP AT lo_result->get_commandinvocations( ) INTO DATA(lo_invocation).
            lv_count = lv_count + 1.
            DATA(lv_requested_datetime) = lo_invocation->get_requesteddatetime( ).
            MESSAGE |Command invocation requested at: { lv_requested_datetime }| TYPE 'I'.
          ENDLOOP.
        ENDWHILE.

        MESSAGE |{ lv_count } command invocation(s) found for instance { iv_instance_id }.| TYPE 'I'.
      CATCH /aws1/cx_ssminvalidinstanceid.
        MESSAGE 'Invalid instance ID.' TYPE 'I'.
      CATCH /aws1/cx_ssminvalidcommandid.
        MESSAGE 'Invalid command ID.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[ListCommandInvocations](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `SendCommand`
<a name="ssm_SendCommand_sap-abap_1_topic"></a>

次の例は、`SendCommand` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_result) = lo_ssm->sendcommand(
            it_instanceids = it_instance_ids
            iv_documentname = iv_document_name
            iv_timeoutseconds = 3600 ).
        DATA(lo_command) = lo_result->get_command( ).
        IF lo_command IS BOUND.
          rv_command_id = lo_command->get_commandid( ).
          MESSAGE 'Command sent successfully.' TYPE 'I'.
        ENDIF.
      CATCH /aws1/cx_ssminvaliddocument.
        MESSAGE 'Invalid document.' TYPE 'I'.
      CATCH /aws1/cx_ssminvalidinstanceid.
        MESSAGE 'Invalid instance ID.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[SendCommand](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateMaintenanceWindow`
<a name="ssm_UpdateMaintenanceWindow_sap-abap_1_topic"></a>

次の例は、`UpdateMaintenanceWindow` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ssm->updatemaintenancewindow(
            iv_windowid = iv_window_id
            iv_name = iv_name
            iv_enabled = iv_enabled
            iv_schedule = iv_schedule
            iv_duration = iv_duration
            iv_cutoff = iv_cutoff
            iv_allowunassociatedtargets = iv_allow_unassociated_targets ).
        MESSAGE 'Maintenance window updated.' TYPE 'I'.
      CATCH /aws1/cx_ssmdoesnotexistex.
        MESSAGE 'Maintenance window does not exist.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[UpdateMaintenanceWindow](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateOpsItem`
<a name="ssm_UpdateOpsItem_sap-abap_1_topic"></a>

次の例は、`UpdateOpsItem` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/ssm#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_ssm->updateopsitem(
            iv_opsitemid = iv_ops_item_id
            iv_title = iv_title
            iv_description = iv_description
            iv_status = iv_status ).
        MESSAGE 'OpsItem updated.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsitemnotfoundex.
        MESSAGE 'OpsItem not found.' TYPE 'I'.
      CATCH /aws1/cx_ssmopsiteminvparamex.
        MESSAGE 'Invalid OpsItem parameter.' TYPE 'I'.
    ENDTRY.
```
+  API の詳細については、AWS SDK for SAP ABAP API リファレンスの「[UpdateOpsItem](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Textract の例
<a name="sap-abap_1_textract_code_examples"></a>

次のコード例は、Amazon Textract で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AnalyzeDocument`
<a name="textract_AnalyzeDocument_sap-abap_1_topic"></a>

次のコード例は、`AnalyzeDocument` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tex#code-examples)での設定と実行の方法を確認してください。

```
    "Detects text and additional elements, such as forms or tables,"
    "in a local image file or from in-memory byte data."
    "The image must be in PNG or JPG format."


    "Create ABAP objects for feature type."
    "Add TABLES to return information about the tables."
    "Add FORMS to return detected form data."
    "To perform both types of analysis, add TABLES and FORMS to FeatureTypes."

    DATA(lt_featuretypes) = VALUE /aws1/cl_texfeaturetypes_w=>tt_featuretypes(
      ( NEW /aws1/cl_texfeaturetypes_w( iv_value = 'FORMS' ) )
      ( NEW /aws1/cl_texfeaturetypes_w( iv_value = 'TABLES' ) ) ).

    "Create an ABAP object for the Amazon Simple Storage Service (Amazon S3) object."
    DATA(lo_s3object) = NEW /aws1/cl_texs3object( iv_bucket = iv_s3bucket
      iv_name   = iv_s3object ).

    "Create an ABAP object for the document."
    DATA(lo_document) = NEW /aws1/cl_texdocument( io_s3object = lo_s3object ).

    "Analyze document stored in Amazon S3."
    TRY.
        oo_result = lo_tex->analyzedocument(      "oo_result is returned for testing purposes."
          io_document        = lo_document
          it_featuretypes    = lt_featuretypes ).
        LOOP AT oo_result->get_blocks( ) INTO DATA(lo_block).
          IF lo_block->get_text( ) = 'INGREDIENTS: POWDERED SUGAR* (CANE SUGAR,'.
            MESSAGE 'Found text in the doc: ' && lo_block->get_text( ) TYPE 'I'.
          ENDIF.
        ENDLOOP.
        MESSAGE 'Analyze document completed.' TYPE 'I'.
      CATCH /aws1/cx_texaccessdeniedex.
        MESSAGE 'You do not have permission to perform this action.' TYPE 'E'.
      CATCH /aws1/cx_texbaddocumentex.
        MESSAGE 'Amazon Textract is not able to read the document.' TYPE 'E'.
      CATCH /aws1/cx_texdocumenttoolargeex.
        MESSAGE 'The document is too large.' TYPE 'E'.
      CATCH /aws1/cx_texhlquotaexceededex.
        MESSAGE 'Human loop quota exceeded.' TYPE 'E'.
      CATCH /aws1/cx_texinternalservererr.
        MESSAGE 'Internal server error.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidparameterex.
        MESSAGE 'Request has non-valid parameters.' TYPE 'E'.

      CATCH /aws1/cx_texinvalids3objectex.
        MESSAGE 'Amazon S3 object is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texprovthruputexcdex.
        MESSAGE 'Provisioned throughput exceeded limit.' TYPE 'E'.
      CATCH /aws1/cx_texthrottlingex.
        MESSAGE 'The request processing exceeded the limit.' TYPE 'E'.
      CATCH /aws1/cx_texunsupporteddocex.
        MESSAGE 'The document is not supported.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[AnalyzeDocument](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DetectDocumentText`
<a name="textract_DetectDocumentText_sap-abap_1_topic"></a>

次のコード例は、`DetectDocumentText` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tex#code-examples)での設定と実行の方法を確認してください。

```
    "Detects text in the input document."
    "Amazon Textract can detect lines of text and the words that make up a line of text."
    "The input document must be in one of the following image formats: JPEG, PNG, PDF, or TIFF."

    "Create an ABAP object for the Amazon S3 object."
    DATA(lo_s3object) = NEW /aws1/cl_texs3object( iv_bucket = iv_s3bucket
      iv_name   = iv_s3object ).

    "Create an ABAP object for the document."
    DATA(lo_document) = NEW /aws1/cl_texdocument( io_s3object = lo_s3object ).
    "Analyze document stored in Amazon S3."
    TRY.
        oo_result = lo_tex->detectdocumenttext( io_document = lo_document ).         "oo_result is returned for testing purposes."
        LOOP AT oo_result->get_blocks( ) INTO DATA(lo_block).
          IF lo_block->get_text( ) = 'INGREDIENTS: POWDERED SUGAR* (CANE SUGAR,'.
            MESSAGE 'Found text in the doc: ' && lo_block->get_text( ) TYPE 'I'.
          ENDIF.
        ENDLOOP.
        DATA(lo_metadata) = oo_result->get_documentmetadata( ).
        MESSAGE 'The number of pages in the document is ' && lo_metadata->ask_pages( ) TYPE 'I'.
        MESSAGE 'Detect document text completed.' TYPE 'I'.
      CATCH /aws1/cx_texaccessdeniedex.
        MESSAGE 'You do not have permission to perform this action.' TYPE 'E'.
      CATCH /aws1/cx_texbaddocumentex.
        MESSAGE 'Amazon Textract is not able to read the document.' TYPE 'E'.
      CATCH /aws1/cx_texdocumenttoolargeex.
        MESSAGE 'The document is too large.' TYPE 'E'.
      CATCH /aws1/cx_texinternalservererr.
        MESSAGE 'Internal server error.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidparameterex.
        MESSAGE 'Request has non-valid parameters.' TYPE 'E'.
      CATCH /aws1/cx_texinvalids3objectex.
        MESSAGE 'Amazon S3 object is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texprovthruputexcdex.
        MESSAGE 'Provisioned throughput exceeded limit.' TYPE 'E'.
      CATCH /aws1/cx_texthrottlingex.
        MESSAGE 'The request processing exceeded the limit' TYPE 'E'.
      CATCH /aws1/cx_texunsupporteddocex.
        MESSAGE 'The document is not supported.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DetectDocumentText](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetDocumentAnalysis`
<a name="textract_GetDocumentAnalysis_sap-abap_1_topic"></a>

次のコード例は、`GetDocumentAnalysis` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tex#code-examples)での設定と実行の方法を確認してください。

```
    "Gets the results for an Amazon Textract"
    "asynchronous operation that analyzes text in a document."
    TRY.
        oo_result = lo_tex->getdocumentanalysis( iv_jobid = iv_jobid ).    "oo_result is returned for testing purposes."
        WHILE oo_result->get_jobstatus( ) <> 'SUCCEEDED'.
          IF sy-index = 10.
            EXIT.               "Maximum 300 seconds.
          ENDIF.
          WAIT UP TO 30 SECONDS.
          oo_result = lo_tex->getdocumentanalysis( iv_jobid = iv_jobid ).
        ENDWHILE.

        DATA(lt_blocks) = oo_result->get_blocks( ).
        LOOP AT lt_blocks INTO DATA(lo_block).
          IF lo_block->get_text( ) = 'INGREDIENTS: POWDERED SUGAR* (CANE SUGAR,'.
            MESSAGE 'Found text in the doc: ' && lo_block->get_text( ) TYPE 'I'.
          ENDIF.
        ENDLOOP.
        MESSAGE 'Document analysis retrieved.' TYPE 'I'.
      CATCH /aws1/cx_texaccessdeniedex.
        MESSAGE 'You do not have permission to perform this action.' TYPE 'E'.
      CATCH /aws1/cx_texinternalservererr.
        MESSAGE 'Internal server error.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidjobidex.
        MESSAGE 'Job ID is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidkmskeyex.
        MESSAGE 'AWS KMS key is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidparameterex.
        MESSAGE 'Request has non-valid parameters.' TYPE 'E'.
      CATCH /aws1/cx_texinvalids3objectex.
        MESSAGE 'Amazon S3 object is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texprovthruputexcdex.
        MESSAGE 'Provisioned throughput exceeded limit.' TYPE 'E'.
      CATCH /aws1/cx_texthrottlingex.
        MESSAGE 'The request processing exceeded the limit.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[GetDocumentAnalysis](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartDocumentAnalysis`
<a name="textract_StartDocumentAnalysis_sap-abap_1_topic"></a>

次のコード例は、`StartDocumentAnalysis` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tex#code-examples)での設定と実行の方法を確認してください。

```
    "Starts the asynchronous analysis of an input document for relationships"
    "between detected items such as key-value pairs, tables, and selection elements."

    "Create ABAP objects for feature type."
    "Add TABLES to return information about the tables."
    "Add FORMS to return detected form data."
    "To perform both types of analysis, add TABLES and FORMS to FeatureTypes."

    DATA(lt_featuretypes) = VALUE /aws1/cl_texfeaturetypes_w=>tt_featuretypes(
      ( NEW /aws1/cl_texfeaturetypes_w( iv_value = 'FORMS' ) )
      ( NEW /aws1/cl_texfeaturetypes_w( iv_value = 'TABLES' ) ) ).
    "Create an ABAP object for the Amazon S3 object."
    DATA(lo_s3object) = NEW /aws1/cl_texs3object( iv_bucket = iv_s3bucket
      iv_name   = iv_s3object ).
    "Create an ABAP object for the document."
    DATA(lo_documentlocation) = NEW /aws1/cl_texdocumentlocation( io_s3object = lo_s3object ).

    "Start async document analysis."
    TRY.
        oo_result = lo_tex->startdocumentanalysis(      "oo_result is returned for testing purposes."
          io_documentlocation     = lo_documentlocation
          it_featuretypes         = lt_featuretypes ).
        DATA(lv_jobid) = oo_result->get_jobid( ).

        MESSAGE 'Document analysis started.' TYPE 'I'.
      CATCH /aws1/cx_texaccessdeniedex.
        MESSAGE 'You do not have permission to perform this action.' TYPE 'E'.
      CATCH /aws1/cx_texbaddocumentex.
        MESSAGE 'Amazon Textract is not able to read the document.' TYPE 'E'.
      CATCH /aws1/cx_texdocumenttoolargeex.
        MESSAGE 'The document is too large.' TYPE 'E'.
      CATCH /aws1/cx_texidempotentprmmis00.
        MESSAGE 'Idempotent parameter mismatch exception.' TYPE 'E'.
      CATCH /aws1/cx_texinternalservererr.
        MESSAGE 'Internal server error.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidkmskeyex.
        MESSAGE 'AWS KMS key is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidparameterex.
        MESSAGE 'Request has non-valid parameters.' TYPE 'E'.
      CATCH /aws1/cx_texinvalids3objectex.
        MESSAGE 'Amazon S3 object is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texlimitexceededex.
        MESSAGE 'An Amazon Textract service limit was exceeded.' TYPE 'E'.
      CATCH /aws1/cx_texprovthruputexcdex.
        MESSAGE 'Provisioned throughput exceeded limit.' TYPE 'E'.
      CATCH /aws1/cx_texthrottlingex.
        MESSAGE 'The request processing exceeded the limit.' TYPE 'E'.
      CATCH /aws1/cx_texunsupporteddocex.
        MESSAGE 'The document is not supported.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StartDocumentAnalysis](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartDocumentTextDetection`
<a name="textract_StartDocumentTextDetection_sap-abap_1_topic"></a>

次のコード例は、`StartDocumentTextDetection` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tex#code-examples)での設定と実行の方法を確認してください。

```
    "Starts the asynchronous detection of text in a document."
    "Amazon Textract can detect lines of text and the words that make up a line of text."

    "Create an ABAP object for the Amazon S3 object."
    DATA(lo_s3object) = NEW /aws1/cl_texs3object( iv_bucket = iv_s3bucket
      iv_name   = iv_s3object ).
    "Create an ABAP object for the document."
    DATA(lo_documentlocation) = NEW /aws1/cl_texdocumentlocation( io_s3object = lo_s3object ).
    "Start document analysis."
    TRY.
        oo_result = lo_tex->startdocumenttextdetection( io_documentlocation = lo_documentlocation ).
        DATA(lv_jobid) = oo_result->get_jobid( ).             "oo_result is returned for testing purposes."
        MESSAGE 'Document analysis started.' TYPE 'I'.
      CATCH /aws1/cx_texaccessdeniedex.
        MESSAGE 'You do not have permission to perform this action.' TYPE 'E'.
      CATCH /aws1/cx_texbaddocumentex.
        MESSAGE 'Amazon Textract is not able to read the document.' TYPE 'E'.
      CATCH /aws1/cx_texdocumenttoolargeex.
        MESSAGE 'The document is too large.' TYPE 'E'.
      CATCH /aws1/cx_texidempotentprmmis00.
        MESSAGE 'Idempotent parameter mismatch exception.' TYPE 'E'.
      CATCH /aws1/cx_texinternalservererr.
        MESSAGE 'Internal server error.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidkmskeyex.
        MESSAGE 'AWS KMS key is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidparameterex.
        MESSAGE 'Request has non-valid parameters.' TYPE 'E'.
      CATCH /aws1/cx_texinvalids3objectex.
        MESSAGE 'Amazon S3 object is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texlimitexceededex.
        MESSAGE 'An Amazon Textract service limit was exceeded.' TYPE 'E'.
      CATCH /aws1/cx_texprovthruputexcdex.
        MESSAGE 'Provisioned throughput exceeded limit.' TYPE 'E'.
      CATCH /aws1/cx_texthrottlingex.
        MESSAGE 'The request processing exceeded the limit.' TYPE 'E'.
      CATCH /aws1/cx_texunsupporteddocex.
        MESSAGE 'The document is not supported.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StartDocumentTextDetection](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### ドキュメント分析を開始する
<a name="textract_Scenario_GettingStarted_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 非同期分析を開始します。
+ ドキュメント分析を取得します。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tex#code-examples)での設定と実行の方法を確認してください。

```
    "Create ABAP objects for feature type."
    "Add TABLES to return information about the tables."
    "Add FORMS to return detected form data."
    "To perform both types of analysis, add TABLES and FORMS to FeatureTypes."

    DATA(lt_featuretypes) = VALUE /aws1/cl_texfeaturetypes_w=>tt_featuretypes(
      ( NEW /aws1/cl_texfeaturetypes_w( iv_value = 'FORMS' ) )
      ( NEW /aws1/cl_texfeaturetypes_w( iv_value = 'TABLES' ) ) ).

    "Create an ABAP object for the Amazon Simple Storage Service (Amazon S3) object."
    DATA(lo_s3object) = NEW /aws1/cl_texs3object( iv_bucket = iv_s3bucket
      iv_name   = iv_s3object ).

    "Create an ABAP object for the document."
    DATA(lo_documentlocation) = NEW /aws1/cl_texdocumentlocation( io_s3object = lo_s3object ).

    "Start document analysis."
    TRY.
        DATA(lo_start_result) = lo_tex->startdocumentanalysis(
          io_documentlocation     = lo_documentlocation
          it_featuretypes         = lt_featuretypes ).
        MESSAGE 'Document analysis started.' TYPE 'I'.
      CATCH /aws1/cx_texaccessdeniedex.
        MESSAGE 'You do not have permission to perform this action.' TYPE 'E'.
      CATCH /aws1/cx_texbaddocumentex.
        MESSAGE 'Amazon Textract is not able to read the document.' TYPE 'E'.
      CATCH /aws1/cx_texdocumenttoolargeex.
        MESSAGE 'The document is too large.' TYPE 'E'.
      CATCH /aws1/cx_texidempotentprmmis00.
        MESSAGE 'Idempotent parameter mismatch exception.' TYPE 'E'.
      CATCH /aws1/cx_texinternalservererr.
        MESSAGE 'Internal server error.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidkmskeyex.
        MESSAGE 'AWS KMS key is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texinvalidparameterex.
        MESSAGE 'Request has non-valid parameters.' TYPE 'E'.
      CATCH /aws1/cx_texinvalids3objectex.
        MESSAGE 'Amazon S3 object is not valid.' TYPE 'E'.
      CATCH /aws1/cx_texlimitexceededex.
        MESSAGE 'An Amazon Textract service limit was exceeded.' TYPE 'E'.
      CATCH /aws1/cx_texprovthruputexcdex.
        MESSAGE 'Provisioned throughput exceeded limit.' TYPE 'E'.
      CATCH /aws1/cx_texthrottlingex.
        MESSAGE 'The request processing exceeded the limit.' TYPE 'E'.
      CATCH /aws1/cx_texunsupporteddocex.
        MESSAGE 'The document is not supported.' TYPE 'E'.
    ENDTRY.

    "Get job ID from the output."
    DATA(lv_jobid) = lo_start_result->get_jobid( ).

    "Wait for job to complete."
    oo_result = lo_tex->getdocumentanalysis( iv_jobid = lv_jobid ).     " oo_result is returned for testing purposes. "
    WHILE oo_result->get_jobstatus( ) <> 'SUCCEEDED'.
      IF sy-index = 10.
        EXIT.               "Maximum 300 seconds."
      ENDIF.
      WAIT UP TO 30 SECONDS.
      oo_result = lo_tex->getdocumentanalysis( iv_jobid = lv_jobid ).
    ENDWHILE.

    DATA(lt_blocks) = oo_result->get_blocks( ).
    LOOP AT lt_blocks INTO DATA(lo_block).
      IF lo_block->get_text( ) = 'INGREDIENTS: POWDERED SUGAR* (CANE SUGAR,'.
        MESSAGE 'Found text in the doc: ' && lo_block->get_text( ) TYPE 'I'.
      ENDIF.
    ENDLOOP.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [GetDocumentAnalysis](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [StartDocumentAnalysis](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

# SDK for SAP ABAP を使用した Amazon Transcribe の例
<a name="sap-abap_1_transcribe_code_examples"></a>

次のコード例は、Amazon Transcribe で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateVocabulary`
<a name="transcribe_CreateVocabulary_sap-abap_1_topic"></a>

次の例は、`CreateVocabulary` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        IF it_phrases IS NOT INITIAL.
          oo_result = lo_tnb->createvocabulary(
            iv_vocabularyname = iv_vocabulary_name
            iv_languagecode = iv_language_code
            it_phrases = it_phrases ).
        ELSEIF iv_vocab_file_uri IS NOT INITIAL.
          oo_result = lo_tnb->createvocabulary(
            iv_vocabularyname = iv_vocabulary_name
            iv_languagecode = iv_language_code
            iv_vocabularyfileuri = iv_vocab_file_uri ).
        ENDIF.
        MESSAGE 'Custom vocabulary created.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_tnblimitexceededex INTO DATA(lo_limit_ex).
        MESSAGE lo_limit_ex TYPE 'I'.
        RAISE EXCEPTION lo_limit_ex.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
      CATCH /aws1/cx_tnbconflictexception INTO DATA(lo_conflict_ex).
        MESSAGE lo_conflict_ex TYPE 'I'.
        RAISE EXCEPTION lo_conflict_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の「[CreateVocabulary](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteTranscriptionJob`
<a name="transcribe_DeleteTranscriptionJob_sap-abap_1_topic"></a>

次の例は、`DeleteTranscriptionJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_tnb->deletetranscriptionjob( iv_job_name ).
        MESSAGE 'Transcription job deleted.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_tnblimitexceededex INTO DATA(lo_limit_ex).
        MESSAGE lo_limit_ex TYPE 'I'.
        RAISE EXCEPTION lo_limit_ex.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteTranscriptionJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `DeleteVocabulary`
<a name="transcribe_DeleteVocabulary_sap-abap_1_topic"></a>

次の例は、`DeleteVocabulary` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        lo_tnb->deletevocabulary( iv_vocabulary_name ).
        MESSAGE 'Vocabulary deleted.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
      CATCH /aws1/cx_tnblimitexceededex INTO DATA(lo_limit_ex).
        MESSAGE lo_limit_ex TYPE 'I'.
        RAISE EXCEPTION lo_limit_ex.
      CATCH /aws1/cx_tnbnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex TYPE 'I'.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[DeleteVocabulary](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetTranscriptionJob`
<a name="transcribe_GetTranscriptionJob_sap-abap_1_topic"></a>

次の例は、`GetTranscriptionJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_tnb->gettranscriptionjob( iv_job_name ).
        DATA(lo_job) = oo_result->get_transcriptionjob( ).
        MESSAGE 'Retrieved transcription job details.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_tnbnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex TYPE 'I'.
        RAISE EXCEPTION lo_not_found_ex.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetTranscriptionJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `GetVocabulary`
<a name="transcribe_GetVocabulary_sap-abap_1_topic"></a>

次の例は、`GetVocabulary` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        oo_result = lo_tnb->getvocabulary( iv_vocabulary_name ).
        MESSAGE 'Retrieved vocabulary details.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_tnbnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex TYPE 'I'.
        RAISE EXCEPTION lo_not_found_ex.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[GetVocabulary](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTranscriptionJobs`
<a name="transcribe_ListTranscriptionJobs_sap-abap_1_topic"></a>

次の例は、`ListTranscriptionJobs` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        IF iv_job_filter IS NOT INITIAL.
          oo_result = lo_tnb->listtranscriptionjobs( iv_jobnamecontains = iv_job_filter ).
        ELSE.
          oo_result = lo_tnb->listtranscriptionjobs( ).
        ENDIF.
        MESSAGE 'Retrieved transcription jobs list.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListTranscriptionJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListVocabularies`
<a name="transcribe_ListVocabularies_sap-abap_1_topic"></a>

次の例は、`ListVocabularies` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        IF iv_vocab_filter IS NOT INITIAL.
          oo_result = lo_tnb->listvocabularies( iv_namecontains = iv_vocab_filter ).
        ELSE.
          oo_result = lo_tnb->listvocabularies( ).
        ENDIF.
        MESSAGE 'Retrieved vocabularies list.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[ListVocabularies](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartTranscriptionJob`
<a name="transcribe_StartTranscriptionJob_sap-abap_1_topic"></a>

次の例は、`StartTranscriptionJob` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        DATA(lo_media) = NEW /aws1/cl_tnbmedia( iv_mediafileuri = iv_media_uri ).
        DATA(lo_settings) = NEW /aws1/cl_tnbsettings( ).
        IF iv_vocabulary_name IS NOT INITIAL.
          lo_settings = NEW /aws1/cl_tnbsettings( iv_vocabularyname = iv_vocabulary_name ).
        ENDIF.

        oo_result = lo_tnb->starttranscriptionjob(
          iv_transcriptionjobname = iv_job_name
          io_media = lo_media
          iv_mediaformat = iv_media_format
          iv_languagecode = iv_language_code
          io_settings = lo_settings ).

        MESSAGE 'Transcription job started.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
        RAISE EXCEPTION lo_bad_request_ex.
      CATCH /aws1/cx_tnblimitexceededex INTO DATA(lo_limit_ex).
        MESSAGE lo_limit_ex TYPE 'I'.
        RAISE EXCEPTION lo_limit_ex.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
      CATCH /aws1/cx_tnbconflictexception INTO DATA(lo_conflict_ex).
        MESSAGE lo_conflict_ex TYPE 'I'.
        RAISE EXCEPTION lo_conflict_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[StartTranscriptionJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `UpdateVocabulary`
<a name="transcribe_UpdateVocabulary_sap-abap_1_topic"></a>

次の例は、`UpdateVocabulary` を使用する方法を説明しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/tnb#code-examples)での設定と実行の方法を確認してください。

```
    TRY.
        IF it_phrases IS NOT INITIAL.
          oo_result = lo_tnb->updatevocabulary(
            iv_vocabularyname = iv_vocabulary_name
            iv_languagecode = iv_language_code
            it_phrases = it_phrases ).
        ELSEIF iv_vocab_file_uri IS NOT INITIAL.
          oo_result = lo_tnb->updatevocabulary(
            iv_vocabularyname = iv_vocabulary_name
            iv_languagecode = iv_language_code
            iv_vocabularyfileuri = iv_vocab_file_uri ).
        ENDIF.
        MESSAGE 'Vocabulary updated.' TYPE 'I'.
      CATCH /aws1/cx_tnbbadrequestex INTO DATA(lo_bad_request_ex).
        MESSAGE lo_bad_request_ex TYPE 'I'.
      CATCH /aws1/cx_tnblimitexceededex INTO DATA(lo_limit_ex).
        MESSAGE lo_limit_ex TYPE 'I'.
        RAISE EXCEPTION lo_limit_ex.
      CATCH /aws1/cx_tnbnotfoundexception INTO DATA(lo_not_found_ex).
        MESSAGE lo_not_found_ex TYPE 'I'.
      CATCH /aws1/cx_tnbinternalfailureex INTO DATA(lo_internal_ex).
        MESSAGE lo_internal_ex TYPE 'I'.
        RAISE EXCEPTION lo_internal_ex.
      CATCH /aws1/cx_tnbconflictexception INTO DATA(lo_conflict_ex).
        MESSAGE lo_conflict_ex TYPE 'I'.
        RAISE EXCEPTION lo_conflict_ex.
    ENDTRY.
```
+  API の詳細については、 *AWS SDK for SAP ABAP API リファレンス*の[UpdateVocabulary](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

# SDK for SAP ABAP を使用した Amazon Translate の例
<a name="sap-abap_1_translate_code_examples"></a>

次のコード例は、Amazon Translate で AWS SDK for SAP ABAP を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `DescribeTextTranslationJob`
<a name="translate_DescribeTextTranslationJob_sap-abap_1_topic"></a>

次のコード例は、`DescribeTextTranslationJob` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/xl8#code-examples)での設定と実行の方法を確認してください。

```
    "Gets the properties associated with an asynchronous batch translation job."
    "Includes properties such as name, ID, status, source and target languages, and input/output Amazon Simple Storage Service (Amazon S3) buckets."
    TRY.
        oo_result = lo_xl8->describetexttranslationjob(      "oo_result is returned for testing purposes."
          iv_jobid        = iv_jobid ).
        MESSAGE 'Job description retrieved.' TYPE 'I'.
      CATCH /aws1/cx_xl8internalserverex.
        MESSAGE 'An internal server error occurred. Retry your request.' TYPE 'E'.
      CATCH /aws1/cx_xl8resourcenotfoundex.
        MESSAGE 'The resource you are looking for has not been found.' TYPE 'E'.
      CATCH /aws1/cx_xl8toomanyrequestsex.
        MESSAGE 'You have made too many requests within a short period of time.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[DescribeTextTranslationJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `ListTextTranslationJobs`
<a name="translate_ListTextTranslationJobs_sap-abap_1_topic"></a>

次のコード例は、`ListTextTranslationJobs` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/xl8#code-examples)での設定と実行の方法を確認してください。

```
    "Gets a list of the batch translation jobs that you have submitted."

    DATA lo_filter TYPE REF TO /aws1/cl_xl8textxlationjobfilt.

    "Create an ABAP object for filtering using jobname."
    lo_filter = NEW #( iv_jobname = iv_jobname ).

    TRY.
        oo_result = lo_xl8->listtexttranslationjobs(      "oo_result is returned for testing purposes."
          io_filter        = lo_filter ).
        MESSAGE 'Jobs retrieved.' TYPE 'I'.
      CATCH /aws1/cx_xl8internalserverex.
        MESSAGE 'An internal server error occurred. Retry your request.' TYPE 'E'.
      CATCH /aws1/cx_xl8invalidfilterex.
        MESSAGE 'The filter specified for the operation is not valid. Specify a different filter.' TYPE 'E'.
      CATCH /aws1/cx_xl8invalidrequestex.
        MESSAGE 'The request that you made is not valid.' TYPE 'E'.
      CATCH /aws1/cx_xl8toomanyrequestsex.
        MESSAGE 'You have made too many requests within a short period of time.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[ListTextTranslationJobs](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StartTextTranslationJob`
<a name="translate_StartTextTranslationJob_sap-abap_1_topic"></a>

次のコード例は、`StartTextTranslationJob` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/xl8#code-examples)での設定と実行の方法を確認してください。

```
    "Starts an asynchronous batch translation job."
    "Use batch translation jobs to translate large volumes of text across multiple documents at once."

    DATA lo_inputdataconfig  TYPE REF TO /aws1/cl_xl8inputdataconfig.
    DATA lo_outputdataconfig TYPE REF TO /aws1/cl_xl8outputdataconfig.
    DATA lt_targetlanguagecodes TYPE /aws1/cl_xl8tgtlanguagecodes00=>tt_targetlanguagecodestrlist.
    DATA lo_targetlanguagecodes TYPE REF TO /aws1/cl_xl8tgtlanguagecodes00.

    "Create an ABAP object for the input data config."
    lo_inputdataconfig = NEW #( iv_s3uri = iv_input_data_s3uri
                                iv_contenttype = iv_input_data_contenttype ).

    "Create an ABAP object for the output data config."
    lo_outputdataconfig = NEW #( iv_s3uri = iv_output_data_s3uri ).

    "Create an internal table for target languages."
    lo_targetlanguagecodes = NEW #( iv_value = iv_targetlanguagecode ).
    INSERT lo_targetlanguagecodes  INTO TABLE lt_targetlanguagecodes.

    TRY.
        oo_result = lo_xl8->starttexttranslationjob(      "oo_result is returned for testing purposes."
          io_inputdataconfig = lo_inputdataconfig
            io_outputdataconfig = lo_outputdataconfig
            it_targetlanguagecodes = lt_targetlanguagecodes
            iv_dataaccessrolearn = iv_dataaccessrolearn
            iv_jobname = iv_jobname
            iv_sourcelanguagecode = iv_sourcelanguagecode ).
        MESSAGE 'Translation job started.' TYPE 'I'.
      CATCH /aws1/cx_xl8internalserverex.
        MESSAGE 'An internal server error occurred. Retry your request.' TYPE 'E'.
      CATCH /aws1/cx_xl8invparamvalueex.
        MESSAGE 'The value of the parameter is not valid.' TYPE 'E'.
      CATCH /aws1/cx_xl8invalidrequestex.
        MESSAGE 'The request that you made is not valid.' TYPE 'E'.
      CATCH /aws1/cx_xl8resourcenotfoundex.
        MESSAGE 'The resource you are looking for has not been found.' TYPE 'E'.
      CATCH /aws1/cx_xl8toomanyrequestsex.
        MESSAGE 'You have made too many requests within a short period of time.' TYPE 'E'.
      CATCH /aws1/cx_xl8unsuppedlanguage00.
        MESSAGE 'Amazon Translate does not support translation from the language of the source text into the requested target language.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StartTextTranslationJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `StopTextTranslationJob`
<a name="translate_StopTextTranslationJob_sap-abap_1_topic"></a>

次のコード例は、`StopTextTranslationJob` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/xl8#code-examples)での設定と実行の方法を確認してください。

```
    "Stops an asynchronous batch translation job that is in progress."

    TRY.
        oo_result = lo_xl8->stoptexttranslationjob(      "oo_result is returned for testing purposes."
          iv_jobid        = iv_jobid ).
        MESSAGE 'Translation job stopped.' TYPE 'I'.
      CATCH /aws1/cx_xl8internalserverex.
        MESSAGE 'An internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_xl8resourcenotfoundex.
        MESSAGE 'The resource you are looking for has not been found.' TYPE 'E'.
      CATCH /aws1/cx_xl8toomanyrequestsex.
        MESSAGE 'You have made too many requests within a short period of time.' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[StopTextTranslationJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

### `TranslateText`
<a name="translate_TranslateText_sap-abap_1_topic"></a>

次のコード例は、`TranslateText` を使用する方法を示しています。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/xl8#code-examples)での設定と実行の方法を確認してください。

```
    "Translates input text from the source language to the target language."
    TRY.
        oo_result = lo_xl8->translatetext(      "oo_result is returned for testing purposes."
          iv_text        = iv_text
            iv_sourcelanguagecode = iv_sourcelanguagecode
            iv_targetlanguagecode = iv_targetlanguagecode ).
        MESSAGE 'Translation completed.' TYPE 'I'.
      CATCH /aws1/cx_xl8detectedlanguage00.
        MESSAGE 'The confidence that Amazon Comprehend accurately detected the source language is low.' TYPE 'E'.
      CATCH /aws1/cx_xl8internalserverex.
        MESSAGE 'An internal server error occurred.' TYPE 'E'.
      CATCH /aws1/cx_xl8invalidrequestex.
        MESSAGE 'The request that you made is not valid.' TYPE 'E'.
      CATCH /aws1/cx_xl8resourcenotfoundex.
        MESSAGE 'The resource you are looking for has not been found.' TYPE 'E'.
      CATCH /aws1/cx_xl8serviceunavailex.
        MESSAGE 'The Amazon Translate service is temporarily unavailable.' TYPE 'E'.
      CATCH /aws1/cx_xl8textsizelmtexcdex.
        MESSAGE 'The size of the text you submitted exceeds the size limit. ' TYPE 'E'.
      CATCH /aws1/cx_xl8toomanyrequestsex.
        MESSAGE 'You have made too many requests within a short period of time.' TYPE 'E'.
      CATCH /aws1/cx_xl8unsuppedlanguage00.
        MESSAGE 'Amazon Translate does not support translation from the language of the source text into the requested target language. ' TYPE 'E'.
    ENDTRY.
```
+  API の詳細については、「*AWS SDK for SAP ABAP API リファレンス*」の「[TranslateText](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

## シナリオ
<a name="scenarios"></a>

### 翻訳ジョブを開始する
<a name="translate_Scenario_GettingStarted_sap-abap_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 非同期バッチ翻訳ジョブを開始します。
+ 非同期ジョブが完了するまで待ちます。
+ 非同期ジョブを記述します。

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/xl8#code-examples)での設定と実行の方法を確認してください。

```
    DATA lo_inputdataconfig  TYPE REF TO /aws1/cl_xl8inputdataconfig.
    DATA lo_outputdataconfig TYPE REF TO /aws1/cl_xl8outputdataconfig.
    DATA lt_targetlanguagecodes TYPE /aws1/cl_xl8tgtlanguagecodes00=>tt_targetlanguagecodestrlist.
    DATA lo_targetlanguagecodes TYPE REF TO /aws1/cl_xl8tgtlanguagecodes00.

    "Create an ABAP object for the input data config."
    lo_inputdataconfig = NEW #( iv_s3uri = iv_input_data_s3uri
                                iv_contenttype = iv_input_data_contenttype ).

    "Create an ABAP object for the output data config."
    lo_outputdataconfig = NEW #( iv_s3uri = iv_output_data_s3uri ).

    "Create an internal table for target languages."
    lo_targetlanguagecodes = NEW #( iv_value = iv_targetlanguagecode ).
    INSERT lo_targetlanguagecodes  INTO TABLE lt_targetlanguagecodes.

    TRY.
        DATA(lo_translationjob_result) = lo_xl8->starttexttranslationjob(
          io_inputdataconfig = lo_inputdataconfig
            io_outputdataconfig = lo_outputdataconfig
            it_targetlanguagecodes = lt_targetlanguagecodes
            iv_dataaccessrolearn = iv_dataaccessrolearn
            iv_jobname = iv_jobname
            iv_sourcelanguagecode = iv_sourcelanguagecode ).
        MESSAGE 'Translation job started.' TYPE 'I'.
      CATCH /aws1/cx_xl8internalserverex.
        MESSAGE 'An internal server error occurred. Retry your request.' TYPE 'E'.
      CATCH /aws1/cx_xl8invparamvalueex.
        MESSAGE 'The value of the parameter is not valid.' TYPE 'E'.
      CATCH /aws1/cx_xl8invalidrequestex.
        MESSAGE 'The request that you made is not valid.' TYPE 'E'.
      CATCH /aws1/cx_xl8resourcenotfoundex.
        MESSAGE 'The resource you are looking for has not been found.' TYPE 'E'.
      CATCH /aws1/cx_xl8toomanyrequestsex.
        MESSAGE 'You have made too many requests within a short period of time. ' TYPE 'E'.
      CATCH /aws1/cx_xl8unsuppedlanguage00.
        MESSAGE 'Amazon Translate does not support translation from the language of the source text into the requested target language.' TYPE 'E'.
    ENDTRY.

    "Get the job ID."
    DATA(lv_jobid) = lo_translationjob_result->get_jobid( ).

    "Wait for translate job to complete."
    DATA(lo_des_translation_result) = lo_xl8->describetexttranslationjob( iv_jobid = lv_jobid ).
    WHILE lo_des_translation_result->get_textxlationjobproperties( )->get_jobstatus( ) <> 'COMPLETED'.
      IF sy-index = 30.
        EXIT.               "Maximum 900 seconds."
      ENDIF.
      WAIT UP TO 30 SECONDS.
      lo_des_translation_result = lo_xl8->describetexttranslationjob( iv_jobid = lv_jobid ).
    ENDWHILE.

    TRY.
        oo_result = lo_xl8->describetexttranslationjob(      "oo_result is returned for testing purposes."
          iv_jobid        = lv_jobid ).
        MESSAGE 'Job description retrieved.' TYPE 'I'.
      CATCH /aws1/cx_xl8internalserverex.
        MESSAGE 'An internal server error occurred. Retry your request.' TYPE 'E'.
      CATCH /aws1/cx_xl8resourcenotfoundex.
        MESSAGE 'The resource you are looking for has not been found.' TYPE 'E'.
      CATCH /aws1/cx_xl8toomanyrequestsex.
        MESSAGE 'You have made too many requests within a short period of time.' TYPE 'E'.
    ENDTRY.
```
+ API の詳細については、「AWS SDK for SAP ABAP API リファレンス」の以下のトピックを参照してください。
  + [DescribeTextTranslationJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)
  + [StartTextTranslationJob](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)

# SDK for Swift のコード例
<a name="swift_1_code_examples"></a>

次のコード例は、 で AWS SDK for Swift を使用する方法を示しています AWS。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

一部のサービスには、サービス固有のライブラリや関数の活用方法を示す追加のカテゴリ例が含まれています。

**その他のリソース**
+  ** [ SDK for Swift デベロッパーガイド ](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/home.html) ** – Swift の使用に関する詳細 AWS。
+  **[AWS デベロッパーセンター](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-programming-language=programming-language%23swift)** — カテゴリまたは全文検索でフィルタリングできるコード例。
+  **[AWS SDK の例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 推奨言語の完全なコードを含む GitHub リポジトリ。コードの設定と実行に関する説明が記載されています。

**Topics**
+ [Amazon Bedrock](swift_1_bedrock_code_examples.md)
+ [Amazon Bedrock ランタイム](swift_1_bedrock-runtime_code_examples.md)
+ [Amazon Cognito ID](swift_1_cognito-identity_code_examples.md)
+ [Amazon Cognito ID プロバイダー](swift_1_cognito-identity-provider_code_examples.md)
+ [DynamoDB](swift_1_dynamodb_code_examples.md)
+ [Amazon EC2](swift_1_ec2_code_examples.md)
+ [AWS Glue](swift_1_glue_code_examples.md)
+ [IAM](swift_1_iam_code_examples.md)
+ [Lambda](swift_1_lambda_code_examples.md)
+ [Amazon RDS](swift_1_rds_code_examples.md)
+ [Amazon S3](swift_1_s3_code_examples.md)
+ [Amazon SNS](swift_1_sns_code_examples.md)
+ [Amazon SQS](swift_1_sqs_code_examples.md)
+ [AWS STS](swift_1_sts_code_examples.md)
+ [Amazon Transcribe ストリーミング](swift_1_transcribe-streaming_code_examples.md)

# SDK for Swift を使用した Amazon Bedrock の例
<a name="swift_1_bedrock_code_examples"></a>

次のコード例は、Amazon Bedrock で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon Bedrock
<a name="bedrock_Hello_swift_1_topic"></a>

次のコード例は、Amazon Bedrock の使用を開始する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。

```
import ArgumentParser
import AWSClientRuntime
import Foundation

import AWSBedrock

struct ExampleCommand: ParsableCommand {
    static var configuration = CommandConfiguration(
        commandName: "ListFoundationModels",
        abstract: """
        This example demonstrates how to retrieve a list of the available
        foundation models from Amazon Bedrock.
        """,
        discussion: """
        """
    )

    /// Construct a string listing the specified modalities.
    /// 
    /// - Parameter modalities: An array of the modalities to list.
    ///
    /// - Returns: A string with a human-readable list of modalities.
    func buildModalityList(modalities: [BedrockClientTypes.ModelModality]?) -> String {
        var first = true
        var str = ""

        if modalities == nil {
            return "<none>"
        }

        for modality in modalities! {
            if !first {
                str += ", "
            }
            first = false
            str += modality.rawValue
        }

        return str
    }

    /// Construct a string listing the specified customizations.
    /// 
    /// - Parameter customizations: An array of the customizations to list.
    /// 
    /// - Returns: A string listing the customizations.
    func buildCustomizationList(customizations: [BedrockClientTypes.ModelCustomization]?) -> String {
        var first = true
        var str = ""

        if customizations == nil {
            return "<none>"
        }

        for customization in customizations! {
            if !first {
                str += ", "
            }
            first = false
            str += customization.rawValue
        }

        return str
    }

    /// Construct a string listing the specified inferences.
    /// 
    /// - Parameter inferences: An array of inferences to list.
    /// 
    /// - Returns: A string listing the specified inferences.
    func buildInferenceList(inferences: [BedrockClientTypes.InferenceType]?) -> String {
        var first = true
        var str = ""

        if inferences == nil {
            return "<none>"
        }

        for inference in inferences! {
            if !first {
                str += ", "
            }
            first = false
            str += inference.rawValue
        }

        return str
    }

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        // Always use the Region "us-east-1" to have access to the most models.
        let config = try await BedrockClient.BedrockClientConfiguration(region: "us-east-1")
        let bedrockClient = BedrockClient(config: config)

        let output = try await bedrockClient.listFoundationModels(
            input: ListFoundationModelsInput()
        )

        guard let summaries = output.modelSummaries else {
            print("No models returned.")
            return
        }
        
        // Output a list of the models with their details.
        for summary in summaries {
            print("==========================================")
            print(" Model ID: \(summary.modelId ?? "<unknown>")")
            print("------------------------------------------")
            print(" Name: \(summary.modelName ?? "<unknown>")")
            print(" Provider: \(summary.providerName ?? "<unknown>")")
            print(" Input modalities: \(buildModalityList(modalities: summary.inputModalities))")
            print(" Output modalities: \(buildModalityList(modalities: summary.outputModalities))")
            print(" Supported customizations: \(buildCustomizationList(customizations: summary.customizationsSupported ))")
            print(" Supported inference types: \(buildInferenceList(inferences: summary.inferenceTypesSupported))")
            print("------------------------------------------\n")
        }
        
        print("\(summaries.count) models available.")
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ListFoundationModels](https://sdk.amazonaws.com/swift/api/awsbedrock/latest/documentation/awsbedrock/bedrockclient/listfoundationmodels(input:))」を参照してください。**

## アクション
<a name="actions"></a>

### `ListFoundationModels`
<a name="bedrock_ListFoundationModels_swift_1_topic"></a>

次のコード例は、`ListFoundationModels` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock#code-examples)での設定と実行の方法を確認してください。

```
import AWSBedrock

        // Always use the Region "us-east-1" to have access to the most models.
        let config = try await BedrockClient.BedrockClientConfiguration(region: "us-east-1")
        let bedrockClient = BedrockClient(config: config)

        let output = try await bedrockClient.listFoundationModels(
            input: ListFoundationModelsInput()
        )

        guard let summaries = output.modelSummaries else {
            print("No models returned.")
            return
        }
        
        // Output a list of the models with their details.
        for summary in summaries {
            print("==========================================")
            print(" Model ID: \(summary.modelId ?? "<unknown>")")
            print("------------------------------------------")
            print(" Name: \(summary.modelName ?? "<unknown>")")
            print(" Provider: \(summary.providerName ?? "<unknown>")")
            print(" Input modalities: \(buildModalityList(modalities: summary.inputModalities))")
            print(" Output modalities: \(buildModalityList(modalities: summary.outputModalities))")
            print(" Supported customizations: \(buildCustomizationList(customizations: summary.customizationsSupported ))")
            print(" Supported inference types: \(buildInferenceList(inferences: summary.inferenceTypesSupported))")
            print("------------------------------------------\n")
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ListFoundationModels](https://sdk.amazonaws.com/swift/api/awsbedrock/latest/documentation/awsbedrock/bedrockclient/listfoundationmodels(input:))」を参照してください。**

# SDK for Swift を使用した Amazon Bedrock ランタイムの例
<a name="swift_1_bedrock-runtime_code_examples"></a>

次のコード例は、Amazon Bedrock ランタイムで AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [Amazon Nova](#amazon_nova)
+ [Amazon Nova Canvas](#amazon_nova_canvas)
+ [Amazon Nova Reel](#amazon_nova_reel)
+ [Anthropic Claude](#anthropic_claude)
+ [Meta Llama](#meta_llama)

## Amazon Nova
<a name="amazon_nova"></a>

### Converse
<a name="bedrock-runtime_Converse_AmazonNovaText_swift_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信します。  

```
// An example demonstrating how to use the Conversation API to send 
// a text message to Amazon Nova.

import AWSBedrockRuntime

func converse(_ textPrompt: String) async throws -> String {

    // Create a Bedrock Runtime client in the AWS Region you want to use.
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    let client = BedrockRuntimeClient(config: config)

    // Set the model ID.
    let modelId = "amazon.nova-micro-v1:0"

    // Start a conversation with the user message.
    let message = BedrockRuntimeClientTypes.Message(
        content: [.text(textPrompt)],
        role: .user
    )

    // Optionally use inference parameters
    let inferenceConfig =
        BedrockRuntimeClientTypes.InferenceConfiguration(
            maxTokens: 512,
            stopSequences: ["END"],
            temperature: 0.5,
            topp: 0.9
        )

    // Create the ConverseInput to send to the model
    let input = ConverseInput(
        inferenceConfig: inferenceConfig, messages: [message], modelId: modelId)

    // Send the ConverseInput to the model
    let response = try await client.converse(input: input)

    // Extract and return the response text.
    if case let .message(msg) = response.output {
        if case let .text(textResponse) = msg.content![0] {
            return textResponse
        } else {
            return "No text response found in message content"
        }
    } else {
        return "No message found in converse output"
    }
}
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Converse](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/converse(input:))」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AmazonNovaText_swift_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Amazon Nova にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// An example demonstrating how to use the Conversation API to send a text message
// to Amazon Nova and print the response stream

import AWSBedrockRuntime

func printConverseStream(_ textPrompt: String) async throws {

    // Create a Bedrock Runtime client in the AWS Region you want to use.
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    let client = BedrockRuntimeClient(config: config)

    // Set the model ID.
    let modelId = "amazon.nova-lite-v1:0"

    // Start a conversation with the user message.
    let message = BedrockRuntimeClientTypes.Message(
        content: [.text(textPrompt)],
        role: .user
    )

    // Optionally use inference parameters.
    let inferenceConfig =
        BedrockRuntimeClientTypes.InferenceConfiguration(
            maxTokens: 512,
            stopSequences: ["END"],
            temperature: 0.5,
            topp: 0.9
        )

    // Create the ConverseStreamInput to send to the model.
    let input = ConverseStreamInput(
        inferenceConfig: inferenceConfig, messages: [message], modelId: modelId)

    // Send the ConverseStreamInput to the model.
    let response = try await client.converseStream(input: input)

    // Extract the streaming response.
    guard let stream = response.stream else {
        print("No stream available")
        return
    }

    // Extract and print the streamed response text in real-time.
    for try await event in stream {
        switch event {
        case .messagestart(_):
            print("\nNova Lite:")

        case .contentblockdelta(let deltaEvent):
            if case .text(let text) = deltaEvent.delta {
                print(text, terminator: "")
            }

        default:
            break
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ConverseStream](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/conversestream(input:))」を参照してください。

## Amazon Nova Canvas
<a name="amazon_nova_canvas"></a>

### InvokeModel
<a name="bedrock-runtime_InvokeModel_AmazonNovaImageGeneration_swift_1_topic"></a>

以下のコード例は、Amazon Bedrock で Amazon Nova Canvas を呼び出して画像を生成する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Nova Canvas で画像を作成します。  

```
// Use the native inference API to create an image with Amazon Nova Canvas

import AWSBedrockRuntime
import AWSSDKIdentity
import Foundation

struct NovaImageOutput: Decodable {
    let images: [Data]
}

func generateImage(_ textPrompt: String) async throws {
    // Create a Bedrock Runtime client in the AWS Region you want to use.
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    config.awsCredentialIdentityResolver = try SSOAWSCredentialIdentityResolver()

    let client = BedrockRuntimeClient(config: config)

    // Set the model ID.
    let modelId = "amazon.nova-canvas-v1:0"

    //  Format the request payload using the model's native structure.
    let input = InvokeModelInput(
        accept: "application/json",
        body: """
            {
                "textToImageParams": {
                    "text": "\(textPrompt)"
                },
                "taskType": "TEXT_IMAGE",
                "imageGenerationConfig": {
                    "seed": 42,
                    "quality": "standard",
                    "width": 512,
                    "height": 512,
                    "numberOfImages": 1
                }
            }
            """.data(using: .utf8),
        modelId: modelId
    )

    // Invoke the model with the request.
    let response = try await client.invokeModel(input: input)

    // Decode the response body.
    let output = try JSONDecoder().decode(NovaImageOutput.self, from: response.body!)

    // Extract the image data.
    guard let data = output.images.first else {
        print("No image data found")
        return
    }

    // Save the generated image to a local folder.
    let fileURL = URL.documentsDirectory.appending(path: "nova_canvas.png")
    print(fileURL)
    try data.write(to: fileURL)
    print("Image is saved at \(fileURL)")
}
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[InvokeModel](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/invokemodel(input:))」を参照してください。

## Amazon Nova Reel
<a name="amazon_nova_reel"></a>

### Text-to-video
<a name="bedrock-runtime_Scenario_AmazonNova_TextToVideo_swift_1_topic"></a>

次のコード例では、Amazon Nova Reel を使用してテキストプロンプトで動画を生成する方法について示します。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Amazon Nova Reel を使用してテキストプロンプトで動画を生成します。  

```
// This example demonstrates how to use Amazon Nova Reel to generate a video from a text prompt.
// It shows how to:
// - Set up the Amazon Bedrock runtime client
// - Configure a text-to-video request
// - Submit an asynchronous job for video generation
// - Poll for job completion status
// - Access the generated video from S3

import AWSBedrockRuntime
import Foundation
import Smithy

func startTextToVideoGenerationJob(
    bedrockRuntimeClient: BedrockRuntimeClient, prompt: String, outputS3Uri: String
) async throws -> String? {
    // Specify the model ID for text-to-video generation
    let modelId = "amazon.nova-reel-v1:0"

    // Configure the video generation request with additional parameters
    let modelInputSource: [String: Any] = [
        "taskType": "TEXT_VIDEO",
        "textToVideoParams": [
            "text": "\(prompt)"
        ],
        "videoGenerationConfig": [
            "durationSeconds": 6,
            "fps": 24,
            "dimension": "1280x720",
        ],
    ]

    let modelInput = try Document.make(from: modelInputSource)

    let input = StartAsyncInvokeInput(
        modelId: modelId,
        modelInput: modelInput,
        outputDataConfig: .s3outputdataconfig(
            BedrockRuntimeClientTypes.AsyncInvokeS3OutputDataConfig(
                s3Uri: outputS3Uri
            )
        )
    )

    // Invoke the model asynchronously
    let output = try await bedrockRuntimeClient.startAsyncInvoke(input: input)
    return output.invocationArn
}

func queryJobStatus(
    bedrockRuntimeClient: BedrockRuntimeClient, 
    invocationArn: String?
) async throws -> GetAsyncInvokeOutput {
    try await bedrockRuntimeClient.getAsyncInvoke(
        input: GetAsyncInvokeInput(invocationArn: invocationArn))
}

func main() async throws {
    // Create a Bedrock Runtime client
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    let client = BedrockRuntimeClient(config: config)

    // Specify the S3 location for the output video
    let bucket = "s3://REPLACE-WITH-YOUR-S3-BUCKET-NAM"

    print("Submitting video generation job...")
    let invocationArn = try await startTextToVideoGenerationJob(
        bedrockRuntimeClient: client,
        prompt: "A pomegranate juice in a railway station",
        outputS3Uri: bucket
    )
    print("Job started with invocation ARN: \(String(describing:invocationArn))")

    // Poll for job completion
    var status: BedrockRuntimeClientTypes.AsyncInvokeStatus?
    var isReady = false
    var hasFailed = false

    while !isReady && !hasFailed {
        print("\nPolling job status...")
        status = try await queryJobStatus(
            bedrockRuntimeClient: client, invocationArn: invocationArn
        ).status
        switch status {
        case .completed:
            isReady = true
            print("Video is ready\nCheck S3 bucket: \(bucket)")
        case .failed:
            hasFailed = true
            print("Something went wrong")
        case .inProgress:
            print("Job is in progress...")
            try await Task.sleep(nanoseconds: 15 * 1_000_000_000)  // 15 seconds
        default:
            isReady = true
        }
    }
}

do {
    try await main()
} catch {
    print("An error occurred: \(error)")
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [GetAsyncInvoke](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/getasyncinvoke(input:))
  + [StartAsyncInvoke](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/startasyncinvoke(input:))

## Anthropic Claude
<a name="anthropic_claude"></a>

### Converse
<a name="bedrock-runtime_Converse_AnthropicClaude_swift_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。  

```
// An example demonstrating how to use the Conversation API to send 
// a text message to Anthropic Claude.

import AWSBedrockRuntime

func converse(_ textPrompt: String) async throws -> String {

    // Create a Bedrock Runtime client in the AWS Region you want to use.
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    let client = BedrockRuntimeClient(config: config)

    // Set the model ID.
    let modelId = "anthropic.claude-3-haiku-20240307-v1:0"

    // Start a conversation with the user message.
    let message = BedrockRuntimeClientTypes.Message(
        content: [.text(textPrompt)],
        role: .user
    )

    // Optionally use inference parameters
    let inferenceConfig =
        BedrockRuntimeClientTypes.InferenceConfiguration(
            maxTokens: 512,
            stopSequences: ["END"],
            temperature: 0.5,
            topp: 0.9
        )

    // Create the ConverseInput to send to the model
    let input = ConverseInput(
        inferenceConfig: inferenceConfig, messages: [message], modelId: modelId)

    // Send the ConverseInput to the model
    let response = try await client.converse(input: input)

    // Extract and return the response text.
    if case let .message(msg) = response.output {
        if case let .text(textResponse) = msg.content![0] {
            return textResponse
        } else {
            return "No text response found in message content"
        }
    } else {
        return "No message found in converse output"
    }
}
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Converse](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/converse(input:))」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_AnthropicClaude_swift_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// An example demonstrating how to use the Conversation API to send a text message
// to Anthropic Claude and print the response stream

import AWSBedrockRuntime

func printConverseStream(_ textPrompt: String) async throws {

    // Create a Bedrock Runtime client in the AWS Region you want to use.
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    let client = BedrockRuntimeClient(config: config)

    // Set the model ID.
    let modelId = "anthropic.claude-3-haiku-20240307-v1:0"

    // Start a conversation with the user message.
    let message = BedrockRuntimeClientTypes.Message(
        content: [.text(textPrompt)],
        role: .user
    )

    // Optionally use inference parameters.
    let inferenceConfig =
        BedrockRuntimeClientTypes.InferenceConfiguration(
            maxTokens: 512,
            stopSequences: ["END"],
            temperature: 0.5,
            topp: 0.9
        )

    // Create the ConverseStreamInput to send to the model.
    let input = ConverseStreamInput(
        inferenceConfig: inferenceConfig, messages: [message], modelId: modelId)

    // Send the ConverseStreamInput to the model.
    let response = try await client.converseStream(input: input)

    // Extract the streaming response.
    guard let stream = response.stream else {
        print("No stream available")
        return
    }

    // Extract and print the streamed response text in real-time.
    for try await event in stream {
        switch event {
        case .messagestart(_):
            print("\nAnthropic Claude:")

        case .contentblockdelta(let deltaEvent):
            if case .text(let text) = deltaEvent.delta {
                print(text, terminator: "")
            }

        default:
            break
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ConverseStream](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/conversestream(input:))」を参照してください。

## Meta Llama
<a name="meta_llama"></a>

### Converse
<a name="bedrock-runtime_Converse_MetaLlama_swift_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信します。  

```
// An example demonstrating how to use the Conversation API to send 
// a text message to Meta Llama.

import AWSBedrockRuntime

func converse(_ textPrompt: String) async throws -> String {

    // Create a Bedrock Runtime client in the AWS Region you want to use.
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    let client = BedrockRuntimeClient(config: config)

    // Set the model ID.
    let modelId = "meta.llama3-8b-instruct-v1:0"

    // Start a conversation with the user message.
    let message = BedrockRuntimeClientTypes.Message(
        content: [.text(textPrompt)],
        role: .user
    )

    // Optionally use inference parameters
    let inferenceConfig =
        BedrockRuntimeClientTypes.InferenceConfiguration(
            maxTokens: 512,
            stopSequences: ["END"],
            temperature: 0.5,
            topp: 0.9
        )

    // Create the ConverseInput to send to the model
    let input = ConverseInput(
        inferenceConfig: inferenceConfig, messages: [message], modelId: modelId)

    // Send the ConverseInput to the model
    let response = try await client.converse(input: input)

    // Extract and return the response text.
    if case let .message(msg) = response.output {
        if case let .text(textResponse) = msg.content![0] {
            return textResponse
        } else {
            return "No text response found in message content"
        }
    } else {
        return "No message found in converse output"
    }
}
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Converse](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/converse(input:))」を参照してください。

### ConverseStream
<a name="bedrock-runtime_ConverseStream_MetaLlama_swift_1_topic"></a>

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/bedrock-runtime#code-examples)での設定と実行の方法を確認してください。
Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。  

```
// An example demonstrating how to use the Conversation API to send a text message
// to Meta Llama and print the response stream.

import AWSBedrockRuntime

func printConverseStream(_ textPrompt: String) async throws {

    // Create a Bedrock Runtime client in the AWS Region you want to use.
    let config =
        try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration(
            region: "us-east-1"
        )
    let client = BedrockRuntimeClient(config: config)

    // Set the model ID.
    let modelId = "meta.llama3-8b-instruct-v1:0"

    // Start a conversation with the user message.
    let message = BedrockRuntimeClientTypes.Message(
        content: [.text(textPrompt)],
        role: .user
    )

    // Optionally use inference parameters.
    let inferenceConfig =
        BedrockRuntimeClientTypes.InferenceConfiguration(
            maxTokens: 512,
            stopSequences: ["END"],
            temperature: 0.5,
            topp: 0.9
        )

    // Create the ConverseStreamInput to send to the model.
    let input = ConverseStreamInput(
        inferenceConfig: inferenceConfig, messages: [message], modelId: modelId)

    // Send the ConverseStreamInput to the model.
    let response = try await client.converseStream(input: input)

    // Extract the streaming response.
    guard let stream = response.stream else {
        print("No stream available")
        return
    }

    // Extract and print the streamed response text in real-time.
    for try await event in stream {
        switch event {
        case .messagestart(_):
            print("\nMeta Llama:")

        case .contentblockdelta(let deltaEvent):
            if case .text(let text) = deltaEvent.delta {
                print(text, terminator: "")
            }

        default:
            break
        }
    }
}
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ConverseStream](https://sdk.amazonaws.com/swift/api/awsbedrockruntime/latest/documentation/awsbedrockruntime/bedrockruntimeclient/conversestream(input:))」を参照してください。

# SDK for Swift を使用する Amazon Cognito ID のコード例
<a name="swift_1_cognito-identity_code_examples"></a>

次のコード例は、Amazon Cognito Identity で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `CreateIdentityPool`
<a name="cognito-identity_CreateIdentityPool_swift_1_topic"></a>

次のコード例は、`CreateIdentityPool` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity/FindOrCreateIdentityPool#code-examples)での設定と実行の方法を確認してください。

```
import AWSCognitoIdentity


    /// Create a new identity pool and return its ID.
    ///
    /// - Parameters:
    ///     - name: The name to give the new identity pool.
    ///
    /// - Returns: A string containing the newly created pool's ID, or `nil`
    ///   if an error occurred.
    ///
    func createIdentityPool(name: String) async throws -> String? {
        do {
            let cognitoInputCall = CreateIdentityPoolInput(developerProviderName: "com.exampleco.CognitoIdentityDemo",
                                                           identityPoolName: name)
            
            let result = try await cognitoIdentityClient.createIdentityPool(input: cognitoInputCall)
            guard let poolId = result.identityPoolId else {
                return nil
            }
            
            return poolId
        } catch {
            print("ERROR: createIdentityPool:", dump(error))
            throw error
        }
    }
```
+  詳細については、「[AWS SDK for Swift デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/getting-started.html)」を参照してください。
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[CreateIdentityPool](https://sdk.amazonaws.com/swift/api/awscognitoidentity/latest/documentation/awscognitoidentity/cognitoidentityclient/createidentitypool(input:))」を参照してください。

### `DeleteIdentityPool`
<a name="cognito-identity_DeleteIdentityPool_swift_1_topic"></a>

次のコード例は、`DeleteIdentityPool` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity/FindOrCreateIdentityPool#code-examples)での設定と実行の方法を確認してください。

```
import AWSCognitoIdentity


    /// Delete the specified identity pool.
    ///
    /// - Parameters:
    ///   - id: The ID of the identity pool to delete.
    ///
    func deleteIdentityPool(id: String) async throws {
        do {
            let input = DeleteIdentityPoolInput(
                identityPoolId: id
            )
            
            _ = try await cognitoIdentityClient.deleteIdentityPool(input: input)
        } catch {
            print("ERROR: deleteIdentityPool:", dump(error))
            throw error
        }
    }
```
+  詳細については、「[AWS SDK for Swift デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/getting-started.html)」を参照してください。
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[DeleteIdentityPool](https://sdk.amazonaws.com/swift/api/awscognitoidentity/latest/documentation/awscognitoidentity/cognitoidentityclient/deleteidentitypool(input:))」を参照してください。

### `ListIdentityPools`
<a name="cognito-identity_ListIdentityPools_swift_1_topic"></a>

次のコード例は、`ListIdentityPools` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity/FindOrCreateIdentityPool#code-examples)での設定と実行の方法を確認してください。

```
import AWSCognitoIdentity


    /// Return the ID of the identity pool with the specified name.
    ///
    /// - Parameters:
    ///   - name: The name of the identity pool whose ID should be returned.
    ///
    /// - Returns: A string containing the ID of the specified identity pool
    ///   or `nil` on error or if not found.
    ///
    func getIdentityPoolID(name: String) async throws -> String? {
        let listPoolsInput = ListIdentityPoolsInput(maxResults: 25)
        // Use "Paginated" to get all the objects.
        // This lets the SDK handle the 'nextToken' field in "ListIdentityPoolsOutput".
        let pages = cognitoIdentityClient.listIdentityPoolsPaginated(input: listPoolsInput)

        do {
            for try await page in pages {
                guard let identityPools = page.identityPools else {
                    print("ERROR: listIdentityPoolsPaginated returned nil contents.")
                    continue
                }
                
                /// Read pages of identity pools from Cognito until one is found
                /// whose name matches the one specified in the `name` parameter.
                /// Return the matching pool's ID.

                for pool in identityPools {
                    if pool.identityPoolName == name {
                        return pool.identityPoolId!
                    }
                }
            }
        } catch {
            print("ERROR: getIdentityPoolID:", dump(error))
            throw error
        }
        
        return nil
    }
```
既存のアイデンティティプールの ID を取得します。存在しない場合は、作成します。  

```
import AWSCognitoIdentity


    /// Return the ID of the identity pool with the specified name.
    ///
    /// - Parameters:
    ///   - name: The name of the identity pool whose ID should be returned
    ///
    /// - Returns: A string containing the ID of the specified identity pool.
    ///   Returns `nil` if there's an error or if the pool isn't found.
    ///
    public func getOrCreateIdentityPoolID(name: String) async throws -> String? {
        // See if the pool already exists. If it doesn't, create it.
        
        do {
            guard let poolId = try await getIdentityPoolID(name: name) else {
                return try await createIdentityPool(name: name)
            }
            
            return poolId
        } catch {
            print("ERROR: getOrCreateIdentityPoolID:", dump(error))
            throw error
        }
    }
```
+  詳細については、「[AWS SDK for Swift デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-swift/latest/developer-guide/getting-started.html)」を参照してください。
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ListIdentityPools](https://sdk.amazonaws.com/swift/api/awscognitoidentity/latest/documentation/awscognitoidentity/cognitoidentityclient/listidentitypools(input:))」を参照してください。

# SDK for Swift を使用する Amazon Cognito ID プロバイダーの例
<a name="swift_1_cognito-identity-provider_code_examples"></a>

次のコード例は、Amazon Cognito ID プロバイダーで AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `AdminGetUser`
<a name="cognito-identity-provider_AdminGetUser_swift_1_topic"></a>

次のコード例は、`AdminGetUser` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Get information about a specific user in a user pool.
    /// 
    /// - Parameters:
    ///   - cipClient: The Amazon Cognito Identity Provider client to use.
    ///   - userName: The user to retrieve information about.
    ///   - userPoolId: The user pool to search for the specified user.
    ///
    /// - Returns: `true` if the user's information was successfully
    ///   retrieved. Otherwise returns `false`.
    func adminGetUser(cipClient: CognitoIdentityProviderClient, userName: String,
                      userPoolId: String) async -> Bool {
        do {
            let output = try await cipClient.adminGetUser(
                input: AdminGetUserInput(
                    userPoolId: userPoolId,
                    username: userName
                )
            )

            guard let userStatus = output.userStatus else {
                print("*** Unable to get the user's status.")
                return false
            }

            print("User status: \(userStatus)")
            return true
        } catch {
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[AdminGetUser](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/admingetuser(input:))」を参照してください。**

### `AdminInitiateAuth`
<a name="cognito-identity-provider_AdminInitiateAuth_swift_1_topic"></a>

次のコード例は、`AdminInitiateAuth` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Begin an authentication session.
    ///
    /// - Parameters:
    ///   - cipClient: The `CongitoIdentityProviderClient` to use.
    ///   - clientId: The app client ID to use.
    ///   - userName: The username to check.
    ///   - password: The user's password.
    ///   - userPoolId: The user pool to use.
    ///
    /// - Returns: The session token associated with this authentication
    ///   session.
    func initiateAuth(cipClient: CognitoIdentityProviderClient, clientId: String,
                         userName: String, password: String,
                         userPoolId: String) async -> String? {
        var authParams: [String: String] = [:]

        authParams["USERNAME"] = userName
        authParams["PASSWORD"] = password

        do {
            let output = try await cipClient.adminInitiateAuth(
                input: AdminInitiateAuthInput(
                    authFlow: CognitoIdentityProviderClientTypes.AuthFlowType.adminUserPasswordAuth,
                    authParameters: authParams,
                    clientId: clientId,
                    userPoolId: userPoolId
                )
            )

            guard let challengeName = output.challengeName else {
                print("*** Invalid response from the auth service.")
                return nil
            }

            print("=====> Response challenge is \(challengeName)")

            return output.session
        } catch _ as UserNotFoundException {
            print("*** The specified username, \(userName), doesn't exist.")
            return nil
        } catch _ as UserNotConfirmedException {
            print("*** The user \(userName) has not been confirmed.")
            return nil
        } catch {
            print("*** An unexpected error occurred.")
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[AdminInitiateAuth](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/admininitiateauth(input:))」を参照してください。

### `AdminRespondToAuthChallenge`
<a name="cognito-identity-provider_AdminRespondToAuthChallenge_swift_1_topic"></a>

次のコード例は、`AdminRespondToAuthChallenge` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Respond to the authentication challenge received from Cognito after
    /// initiating an authentication session. This involves sending a current
    /// MFA code to the service.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - userName: The user's username.
    ///   - clientId: The app client ID.
    ///   - userPoolId: The user pool to sign into.
    ///   - mfaCode: The 6-digit MFA code currently displayed by the user's
    ///     authenticator.
    ///   - session: The authentication session to continue processing.
    func adminRespondToAuthChallenge(cipClient: CognitoIdentityProviderClient, userName: String,
                                     clientId: String, userPoolId: String, mfaCode: String,
                                     session: String) async {
        print("=====> SOFTWARE_TOKEN_MFA challenge is generated...")

        var challengeResponsesOb: [String: String] = [:]
        challengeResponsesOb["USERNAME"] = userName
        challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode

        do {
            let output = try await cipClient.adminRespondToAuthChallenge(
                input: AdminRespondToAuthChallengeInput(
                    challengeName: CognitoIdentityProviderClientTypes.ChallengeNameType.softwareTokenMfa,
                    challengeResponses: challengeResponsesOb,
                    clientId: clientId,
                    session: session,
                    userPoolId: userPoolId
                )
            )

            guard let authenticationResult = output.authenticationResult else {
                print("*** Unable to get authentication result.")
                return
            }

            print("=====> Authentication result (JWTs are redacted):")
            print(authenticationResult)
        } catch _ as SoftwareTokenMFANotFoundException {
            print("*** The specified user pool isn't configured for MFA.")
            return
        } catch _ as CodeMismatchException {
            print("*** The specified MFA code doesn't match the expected value.")
            return
        } catch _ as UserNotFoundException {
            print("*** The specified username, \(userName), doesn't exist.")
            return
        } catch _ as UserNotConfirmedException {
            print("*** The user \(userName) has not been confirmed.")
            return
        } catch let error as NotAuthorizedException {
            print("*** Unauthorized access. Reason: \(error.properties.message ?? "<unknown>")")
        } catch {
            print("*** Error responding to the MFA challenge.")
            return
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[AdminRespondToAuthChallenge](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/adminrespondtoauthchallenge(input:))」を参照してください。**

### `AssociateSoftwareToken`
<a name="cognito-identity-provider_AssociateSoftwareToken_swift_1_topic"></a>

次のコード例は、`AssociateSoftwareToken` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Request and display an MFA secret token that the user should enter
    /// into their authenticator to set it up for the user account.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - authSession: The authentication session to request an MFA secret
    ///     for.
    ///
    /// - Returns: A string containing the MFA secret token that should be
    ///   entered into the authenticator software.
    func getSecretForAppMFA(cipClient: CognitoIdentityProviderClient, authSession: String?) async -> String? {
        do {
            let output = try await cipClient.associateSoftwareToken(
                input: AssociateSoftwareTokenInput(
                    session: authSession
                )
            )

            guard let secretCode = output.secretCode else {
                print("*** Unable to get the secret code")
                return nil
            }

            print("=====> Enter this token into Google Authenticator: \(secretCode)")
            return output.session
        } catch _ as SoftwareTokenMFANotFoundException {
            print("*** The specified user pool isn't configured for MFA.")
            return nil
        } catch {
            print("*** An unexpected error occurred getting the secret for the app's MFA.")
            return nil
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[AssociateSoftwareToken](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/associatesoftwaretoken(input:))」を参照してください。**

### `ConfirmSignUp`
<a name="cognito-identity-provider_ConfirmSignUp_swift_1_topic"></a>

次のコード例は、`ConfirmSignUp` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Submit a confirmation code for the specified user. This is the code as
    /// entered by the user after they've received it by email or text
    /// message.
    ///
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - clientId: The app client ID the user is signing up for.
    ///   - userName: The username of the user whose code is being sent.
    ///   - code: The user's confirmation code.
    /// 
    /// - Returns: `true` if the code was successfully confirmed; otherwise `false`.
    func confirmSignUp(cipClient: CognitoIdentityProviderClient, clientId: String,
                       userName: String, code: String) async -> Bool {
        do {
            _ = try await cipClient.confirmSignUp(
                input: ConfirmSignUpInput(
                    clientId: clientId,
                    confirmationCode: code,
                    username: userName
                )
            )

            print("=====> \(userName) has been confirmed.")
            return true
        } catch {
            print("=====> \(userName)'s code was entered incorrectly.")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ConfirmSignUp](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/confirmsignup(input:))」を参照してください。**

### `ListUsers`
<a name="cognito-identity-provider_ListUsers_swift_1_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
        do {
            let output = try await cognitoClient.listUsers(
                input: ListUsersInput(
                    userPoolId: poolId
                )
            )
            
            guard let users = output.users else {
                print("No users found.")
                return
            }

            print("\(users.count) user(s) found.")
            for user in users {
                print("  \(user.username ?? "<unknown>")")
            }
        } catch _ as NotAuthorizedException {
            print("*** Please authenticate with AWS before using this command.")
            return
        } catch _ as ResourceNotFoundException {
            print("*** The specified User Pool was not found.")
            return
        } catch {
            print("*** An unexpected type of error occurred.")
            return
        }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ListUsers](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/listusers(input:))」を参照してください。

### `ResendConfirmationCode`
<a name="cognito-identity-provider_ResendConfirmationCode_swift_1_topic"></a>

次のコード例は、`ResendConfirmationCode` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Requests a new confirmation code be sent to the given user's contact
    /// method.
    ///
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - clientId: The application client ID.
    ///   - userName: The user to resend a code for.
    ///
    /// - Returns: `true` if a new code was sent successfully, otherwise
    ///   `false`.
    func resendConfirmationCode(cipClient: CognitoIdentityProviderClient, clientId: String,
                                userName: String) async -> Bool {
        do {
            let output = try await cipClient.resendConfirmationCode(
                input: ResendConfirmationCodeInput(
                    clientId: clientId,
                    username: userName
                )
            )

            guard let deliveryMedium = output.codeDeliveryDetails?.deliveryMedium else {
                print("*** Unable to get the delivery method for the resent code.")
                return false
            }

            print("=====> A new code has been sent by \(deliveryMedium)")
            return true
        } catch {
            print("*** Unable to resend the confirmation code to user \(userName).")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ResendConfirmationCode](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/resendconfirmationcode(input:))」を参照してください。**

### `SignUp`
<a name="cognito-identity-provider_SignUp_swift_1_topic"></a>

次のコード例は、`SignUp` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Create a new user in a user pool.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - clientId: The ID of the app client to create a user for.
    ///   - userName: The username for the new user.
    ///   - password: The new user's password.
    ///   - email: The new user's email address.
    ///
    /// - Returns: `true` if successful; otherwise `false`.
    func signUp(cipClient: CognitoIdentityProviderClient, clientId: String, userName: String, password: String, email: String) async -> Bool {
        let emailAttr = CognitoIdentityProviderClientTypes.AttributeType(
            name: "email",
            value: email
        )

        let userAttrsList = [emailAttr]

        do {
            _ = try await cipClient.signUp(
                input: SignUpInput(
                    clientId: clientId,
                    password: password,
                    userAttributes: userAttrsList,
                    username: userName
                )

            )

            print("=====> User \(userName) signed up.")
        } catch _ as AWSCognitoIdentityProvider.UsernameExistsException {
            print("*** The username \(userName) already exists. Please use a different one.")
            return false
        } catch let error as AWSCognitoIdentityProvider.InvalidPasswordException {
            print("*** Error: The specified password is invalid. Reason: \(error.properties.message ?? "<none available>").")
            return false
        } catch _ as AWSCognitoIdentityProvider.ResourceNotFoundException {
            print("*** Error: The specified client ID (\(clientId)) doesn't exist.")
            return false
        } catch {
            print("*** Unexpected error: \(error)")
            return false
        }

        return true
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[SignUp](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/signup(input:))」を参照してください。**

### `VerifySoftwareToken`
<a name="cognito-identity-provider_VerifySoftwareToken_swift_1_topic"></a>

次のコード例は、`VerifySoftwareToken` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSCognitoIdentityProvider

    /// Confirm that the user's TOTP authenticator is configured correctly by
    /// sending a code to it to check that it matches successfully.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CongnitoIdentityProviderClient` to use.
    ///   - session: An authentication session previously returned by an
    ///     `associateSoftwareToken()` call.
    ///   - mfaCode: The 6-digit code currently displayed by the user's
    ///     authenticator, as provided by the user.
    func verifyTOTP(cipClient: CognitoIdentityProviderClient, session: String?, mfaCode: String?) async {
        do {
            let output = try await cipClient.verifySoftwareToken(
                input: VerifySoftwareTokenInput(
                    session: session,
                    userCode: mfaCode
                )
            )

            guard let tokenStatus = output.status else {
                print("*** Unable to get the token's status.")
                return
            }
            print("=====> The token's status is: \(tokenStatus)")
        } catch _ as SoftwareTokenMFANotFoundException {
            print("*** The specified user pool isn't configured for MFA.")
            return
        } catch _ as CodeMismatchException {
            print("*** The specified MFA code doesn't match the expected value.")
            return
        } catch _ as UserNotFoundException {
            print("*** The specified username doesn't exist.")
            return
        } catch _ as UserNotConfirmedException {
            print("*** The user has not been confirmed.")
            return
        } catch {
            print("*** Error verifying the MFA token!")
            return
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[VerifySoftwareToken](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/verifysoftwaretoken(input:))」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### MFA を必要とするユーザープールでユーザーをサインアップする
<a name="cognito-identity-provider_Scenario_SignUpUserWithMfa_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ ユーザー名、パスワード、E メールアドレスでサインアップしてユーザーを確認します。
+ MFA アプリケーションをユーザーに関連付けて、多要素認証を設定します。
+ パスワードと MFA コードを使用してサインインします。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/cognito-identity-provider#code-examples)での設定と実行の方法を確認してください。
`Package.swift` ファイル。  

```
// swift-tools-version: 5.9
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "cognito-scenario",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13),
        .iOS(.v15)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.0.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "cognito-scenario",
            dependencies: [
                .product(name: "AWSCognitoIdentityProvider", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources")

    ]
)
```
Swift コードファイル。  

```
// An example demonstrating various features of Amazon Cognito. Before running
// this Swift code example, set up your development environment, including
// your credentials.
//
// For more information, see the following documentation:
// https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
//
// TIP: To set up the required user pool, run the AWS Cloud Development Kit
// (AWS CDK) script provided in this GitHub repo at
// resources/cdk/cognito_scenario_user_pool_with_mfa.
//
// This example performs the following functions:
//
// 1. Invokes the signUp method to sign up a user.
// 2. Invokes the adminGetUser method to get the user's confirmation status.
// 3. Invokes the ResendConfirmationCode method if the user requested another
//    code.
// 4. Invokes the confirmSignUp method.
// 5. Invokes the initiateAuth to sign in. This results in being prompted to
//    set up TOTP (time-based one-time password). (The response is
//    “ChallengeName”: “MFA_SETUP”).
// 6. Invokes the AssociateSoftwareToken method to generate a TOTP MFA private
//    key. This can be used with Google Authenticator.
// 7. Invokes the VerifySoftwareToken method to verify the TOTP and register
//    for MFA.
// 8. Invokes the AdminInitiateAuth to sign in again. This results in being
//    prompted to submit a TOTP (Response: “ChallengeName”:
//    “SOFTWARE_TOKEN_MFA”).
// 9. Invokes the AdminRespondToAuthChallenge to get back a token.

import ArgumentParser
import Foundation

import AWSClientRuntime
import AWSCognitoIdentityProvider

struct ExampleCommand: ParsableCommand {
    @Argument(help: "The application clientId.")
    var clientId: String
    @Argument(help: "The user pool ID to use.")
    var poolId: String
    @Option(help: "Name of the Amazon Region to use")
    var region = "us-east-1"

    static var configuration = CommandConfiguration(
        commandName: "cognito-scenario",
        abstract: """
        Demonstrates various features of Amazon Cognito.
        """,
        discussion: """
        """
    )

    /// Prompt for an input string of at least a minimum length.  
    /// 
    /// - Parameters:
    ///   - prompt: The prompt string to display.
    ///   - minLength: The minimum number of characters to allow in the
    ///     response. Default value is 0.
    ///
    /// - Returns: The entered string.
    func stringRequest(_ prompt: String, minLength: Int = 1) -> String {
        while true {
            print(prompt, terminator: "")
            let str = readLine()

            guard let str else {
                continue
            }
            if str.count >= minLength {
                return str
            } else {
                print("*** Response must be at least \(minLength) character(s) long.")
            }
        }
    }

    /// Ask a yes/no question.
    /// 
    /// - Parameter prompt: A prompt string to print.
    ///
    /// - Returns: `true` if the user answered "Y", otherwise `false`.
    func yesNoRequest(_ prompt: String) -> Bool {
        while true {
            let answer = stringRequest(prompt).lowercased()
            if answer == "y" || answer == "n" {
                return answer == "y"
            }
        }
    }

    /// Get information about a specific user in a user pool.
    /// 
    /// - Parameters:
    ///   - cipClient: The Amazon Cognito Identity Provider client to use.
    ///   - userName: The user to retrieve information about.
    ///   - userPoolId: The user pool to search for the specified user.
    ///
    /// - Returns: `true` if the user's information was successfully
    ///   retrieved. Otherwise returns `false`.
    func adminGetUser(cipClient: CognitoIdentityProviderClient, userName: String,
                      userPoolId: String) async -> Bool {
        do {
            let output = try await cipClient.adminGetUser(
                input: AdminGetUserInput(
                    userPoolId: userPoolId,
                    username: userName
                )
            )

            guard let userStatus = output.userStatus else {
                print("*** Unable to get the user's status.")
                return false
            }

            print("User status: \(userStatus)")
            return true
        } catch {
            return false
        }
    }

    /// Create a new user in a user pool.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - clientId: The ID of the app client to create a user for.
    ///   - userName: The username for the new user.
    ///   - password: The new user's password.
    ///   - email: The new user's email address.
    ///
    /// - Returns: `true` if successful; otherwise `false`.
    func signUp(cipClient: CognitoIdentityProviderClient, clientId: String, userName: String, password: String, email: String) async -> Bool {
        let emailAttr = CognitoIdentityProviderClientTypes.AttributeType(
            name: "email",
            value: email
        )

        let userAttrsList = [emailAttr]

        do {
            _ = try await cipClient.signUp(
                input: SignUpInput(
                    clientId: clientId,
                    password: password,
                    userAttributes: userAttrsList,
                    username: userName
                )

            )

            print("=====> User \(userName) signed up.")
        } catch _ as AWSCognitoIdentityProvider.UsernameExistsException {
            print("*** The username \(userName) already exists. Please use a different one.")
            return false
        } catch let error as AWSCognitoIdentityProvider.InvalidPasswordException {
            print("*** Error: The specified password is invalid. Reason: \(error.properties.message ?? "<none available>").")
            return false
        } catch _ as AWSCognitoIdentityProvider.ResourceNotFoundException {
            print("*** Error: The specified client ID (\(clientId)) doesn't exist.")
            return false
        } catch {
            print("*** Unexpected error: \(error)")
            return false
        }

        return true
    }

    /// Requests a new confirmation code be sent to the given user's contact
    /// method.
    ///
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - clientId: The application client ID.
    ///   - userName: The user to resend a code for.
    ///
    /// - Returns: `true` if a new code was sent successfully, otherwise
    ///   `false`.
    func resendConfirmationCode(cipClient: CognitoIdentityProviderClient, clientId: String,
                                userName: String) async -> Bool {
        do {
            let output = try await cipClient.resendConfirmationCode(
                input: ResendConfirmationCodeInput(
                    clientId: clientId,
                    username: userName
                )
            )

            guard let deliveryMedium = output.codeDeliveryDetails?.deliveryMedium else {
                print("*** Unable to get the delivery method for the resent code.")
                return false
            }

            print("=====> A new code has been sent by \(deliveryMedium)")
            return true
        } catch {
            print("*** Unable to resend the confirmation code to user \(userName).")
            return false
        }
    }

    /// Submit a confirmation code for the specified user. This is the code as
    /// entered by the user after they've received it by email or text
    /// message.
    ///
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - clientId: The app client ID the user is signing up for.
    ///   - userName: The username of the user whose code is being sent.
    ///   - code: The user's confirmation code.
    /// 
    /// - Returns: `true` if the code was successfully confirmed; otherwise `false`.
    func confirmSignUp(cipClient: CognitoIdentityProviderClient, clientId: String,
                       userName: String, code: String) async -> Bool {
        do {
            _ = try await cipClient.confirmSignUp(
                input: ConfirmSignUpInput(
                    clientId: clientId,
                    confirmationCode: code,
                    username: userName
                )
            )

            print("=====> \(userName) has been confirmed.")
            return true
        } catch {
            print("=====> \(userName)'s code was entered incorrectly.")
            return false
        }
    }

    /// Begin an authentication session.
    ///
    /// - Parameters:
    ///   - cipClient: The `CongitoIdentityProviderClient` to use.
    ///   - clientId: The app client ID to use.
    ///   - userName: The username to check.
    ///   - password: The user's password.
    ///   - userPoolId: The user pool to use.
    ///
    /// - Returns: The session token associated with this authentication
    ///   session.
    func initiateAuth(cipClient: CognitoIdentityProviderClient, clientId: String,
                         userName: String, password: String,
                         userPoolId: String) async -> String? {
        var authParams: [String: String] = [:]

        authParams["USERNAME"] = userName
        authParams["PASSWORD"] = password

        do {
            let output = try await cipClient.adminInitiateAuth(
                input: AdminInitiateAuthInput(
                    authFlow: CognitoIdentityProviderClientTypes.AuthFlowType.adminUserPasswordAuth,
                    authParameters: authParams,
                    clientId: clientId,
                    userPoolId: userPoolId
                )
            )

            guard let challengeName = output.challengeName else {
                print("*** Invalid response from the auth service.")
                return nil
            }

            print("=====> Response challenge is \(challengeName)")

            return output.session
        } catch _ as UserNotFoundException {
            print("*** The specified username, \(userName), doesn't exist.")
            return nil
        } catch _ as UserNotConfirmedException {
            print("*** The user \(userName) has not been confirmed.")
            return nil
        } catch {
            print("*** An unexpected error occurred.")
            return nil
        }
    }

    /// Request and display an MFA secret token that the user should enter
    /// into their authenticator to set it up for the user account.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - authSession: The authentication session to request an MFA secret
    ///     for.
    ///
    /// - Returns: A string containing the MFA secret token that should be
    ///   entered into the authenticator software.
    func getSecretForAppMFA(cipClient: CognitoIdentityProviderClient, authSession: String?) async -> String? {
        do {
            let output = try await cipClient.associateSoftwareToken(
                input: AssociateSoftwareTokenInput(
                    session: authSession
                )
            )

            guard let secretCode = output.secretCode else {
                print("*** Unable to get the secret code")
                return nil
            }

            print("=====> Enter this token into Google Authenticator: \(secretCode)")
            return output.session
        } catch _ as SoftwareTokenMFANotFoundException {
            print("*** The specified user pool isn't configured for MFA.")
            return nil
        } catch {
            print("*** An unexpected error occurred getting the secret for the app's MFA.")
            return nil
        }
    }

    /// Confirm that the user's TOTP authenticator is configured correctly by
    /// sending a code to it to check that it matches successfully.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CongnitoIdentityProviderClient` to use.
    ///   - session: An authentication session previously returned by an
    ///     `associateSoftwareToken()` call.
    ///   - mfaCode: The 6-digit code currently displayed by the user's
    ///     authenticator, as provided by the user.
    func verifyTOTP(cipClient: CognitoIdentityProviderClient, session: String?, mfaCode: String?) async {
        do {
            let output = try await cipClient.verifySoftwareToken(
                input: VerifySoftwareTokenInput(
                    session: session,
                    userCode: mfaCode
                )
            )

            guard let tokenStatus = output.status else {
                print("*** Unable to get the token's status.")
                return
            }
            print("=====> The token's status is: \(tokenStatus)")
        } catch _ as SoftwareTokenMFANotFoundException {
            print("*** The specified user pool isn't configured for MFA.")
            return
        } catch _ as CodeMismatchException {
            print("*** The specified MFA code doesn't match the expected value.")
            return
        } catch _ as UserNotFoundException {
            print("*** The specified username doesn't exist.")
            return
        } catch _ as UserNotConfirmedException {
            print("*** The user has not been confirmed.")
            return
        } catch {
            print("*** Error verifying the MFA token!")
            return
        }
    }

    /// Respond to the authentication challenge received from Cognito after
    /// initiating an authentication session. This involves sending a current
    /// MFA code to the service.
    /// 
    /// - Parameters:
    ///   - cipClient: The `CognitoIdentityProviderClient` to use.
    ///   - userName: The user's username.
    ///   - clientId: The app client ID.
    ///   - userPoolId: The user pool to sign into.
    ///   - mfaCode: The 6-digit MFA code currently displayed by the user's
    ///     authenticator.
    ///   - session: The authentication session to continue processing.
    func adminRespondToAuthChallenge(cipClient: CognitoIdentityProviderClient, userName: String,
                                     clientId: String, userPoolId: String, mfaCode: String,
                                     session: String) async {
        print("=====> SOFTWARE_TOKEN_MFA challenge is generated...")

        var challengeResponsesOb: [String: String] = [:]
        challengeResponsesOb["USERNAME"] = userName
        challengeResponsesOb["SOFTWARE_TOKEN_MFA_CODE"] = mfaCode

        do {
            let output = try await cipClient.adminRespondToAuthChallenge(
                input: AdminRespondToAuthChallengeInput(
                    challengeName: CognitoIdentityProviderClientTypes.ChallengeNameType.softwareTokenMfa,
                    challengeResponses: challengeResponsesOb,
                    clientId: clientId,
                    session: session,
                    userPoolId: userPoolId
                )
            )

            guard let authenticationResult = output.authenticationResult else {
                print("*** Unable to get authentication result.")
                return
            }

            print("=====> Authentication result (JWTs are redacted):")
            print(authenticationResult)
        } catch _ as SoftwareTokenMFANotFoundException {
            print("*** The specified user pool isn't configured for MFA.")
            return
        } catch _ as CodeMismatchException {
            print("*** The specified MFA code doesn't match the expected value.")
            return
        } catch _ as UserNotFoundException {
            print("*** The specified username, \(userName), doesn't exist.")
            return
        } catch _ as UserNotConfirmedException {
            print("*** The user \(userName) has not been confirmed.")
            return
        } catch let error as NotAuthorizedException {
            print("*** Unauthorized access. Reason: \(error.properties.message ?? "<unknown>")")
        } catch {
            print("*** Error responding to the MFA challenge.")
            return
        }
    }

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let config = try await CognitoIdentityProviderClient.CognitoIdentityProviderClientConfiguration(region: region)
        let cipClient = CognitoIdentityProviderClient(config: config)

        print("""
              This example collects information about a user, then creates that user in the
              specified user pool. Then, it enables Multi-Factor Authentication (MFA) for that
              user by associating an authenticator application (such as Google Authenticator
              or a password manager that supports TOTP). Then, the user uses a code from their
              authenticator application to sign in.

              """)

        let userName = stringRequest("Please enter a new username: ")
        let password = stringRequest("Enter a password: ")
        let email = stringRequest("Enter your email address: ", minLength: 5)

        // Submit the sign-up request to AWS.

        print("==> Signing up user \(userName)...")
        if await signUp(cipClient: cipClient, clientId: clientId,
                        userName: userName, password: password,
                        email: email) == false {
            return
        }

        // Check the user's status. This time, it should come back "unconfirmed".

        print("==> Getting the status of user \(userName) from the user pool (should be 'unconfirmed')...")
        if await adminGetUser(cipClient: cipClient, userName: userName, userPoolId: poolId) == false {
            return
        }

        // Ask the user if they want a replacement code sent, such as if the
        // code hasn't arrived yet. If the user responds with a "yes," send a
        // new code.

        if yesNoRequest("==> A confirmation code was sent to \(userName). Would you like to send a new code (Y/N)? ") {
            print("==> Sending a new confirmation code...")
            if await resendConfirmationCode(cipClient: cipClient, clientId: clientId, userName: userName) == false {
                return
            }
        }

        // Ask the user to enter the confirmation code, then send it to Amazon
        // Cognito to verify it.

        let code = stringRequest("==> Enter the confirmation code sent to \(userName): ")
        if await confirmSignUp(cipClient: cipClient, clientId: clientId, userName: userName, code: code) == false {
            // The code didn't match. Your application may wish to offer to
            // re-send the confirmation code here and try again.
            return
        }

        // Check the user's status again. This time it should come back
        // "confirmed".

        print("==> Rechecking status of user \(userName) in the user pool (should be 'confirmed')...")
        if await adminGetUser(cipClient: cipClient, userName: userName, userPoolId: poolId) == false {
            return
        }
        // Check the challenge mode. Here, it should be "mfaSetup", indicating
        // that the user needs to add MFA before using it. This returns a
        // session that can be used to register MFA, or nil if an error occurs.

        let authSession = await initiateAuth(cipClient: cipClient, clientId: clientId,
                                                userName: userName, password: password,
                                                userPoolId: poolId)
        if authSession == nil {
            return
        }

        // Ask Cognito for an MFA secret token that the user should enter into
        // their authenticator software (such as Google Authenticator) or
        // password manager to configure it for this user account. This
        // returns a new session that should be used for the new stage of the
        // authentication process.

        let newSession = await getSecretForAppMFA(cipClient: cipClient, authSession: authSession)
        if newSession == nil {
            return
        }

        // Ask the user to enter the current 6-digit code displayed by their
        // authenticator. Then verify that it matches the value expected for
        // the session.

        let mfaCode1 = stringRequest("==> Enter the 6-digit code displayed in your authenticator: ",
                                    minLength: 6)
        await verifyTOTP(cipClient: cipClient, session: newSession, mfaCode: mfaCode1)

        // Ask the user to authenticate now that the authenticator has been
        // configured. This creates a new session using the user's username
        // and password as already entered.

        print("\nNow starting the sign-in process for user \(userName)...\n")
        
        let session2 = await initiateAuth(cipClient: cipClient, clientId: clientId,
                                    userName: userName, password: password, userPoolId: poolId)
        guard let session2 else {
            return
        }

        // Now that we have a new auth session, `session2`, ask the user for a
        // new 6-digit code from their authenticator, and send it to the auth
        // session.

        let mfaCode2 = stringRequest("==> Wait for your authenticator to show a new 6-digit code, then enter it: ",
                                    minLength: 6)
        await adminRespondToAuthChallenge(cipClient: cipClient, userName: userName,
                                          clientId: clientId, userPoolId: poolId,
                                          mfaCode: mfaCode2, session: session2)
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [AdminGetUser](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/admingetuser(input:))
  + [AdminInitiateAuth](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/admininitiateauth(input:))
  + [AdminRespondToAuthChallenge](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/adminrespondtoauthchallenge(input:))
  + [AssociateSoftwareToken](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/associatesoftwaretoken(input:))
  + [ConfirmDevice](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/confirmdevice(input:))
  + [ConfirmSignUp](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/confirmsignup(input:))
  + [InitiateAuth](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/initiateauth(input:))
  + [ListUsers](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/listusers(input:))
  + [ResendConfirmationCode](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/resendconfirmationcode(input:))
  + [RespondToAuthChallenge](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/respondtoauthchallenge(input:))
  + [SignUp](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/signup(input:))
  + [VerifySoftwareToken](https://sdk.amazonaws.com/swift/api/awscognitoidentityprovider/latest/documentation/awscognitoidentityprovider/cognitoidentityproviderclient/verifysoftwaretoken(input:))

# SDK for Swift を使用した DynamoDB の例
<a name="swift_1_dynamodb_code_examples"></a>

次のコード例は、DynamoDB で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="dynamodb_Scenario_GettingStartedMovies_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ 映画データを保持できるテーブルを作成します。
+ テーブルに 1 つの映画を入れ、取得して更新する。
+ サンプル JSON ファイルから映画データをテーブルに書き込む。
+ 特定の年にリリースされた映画を照会する。
+ 一定期間内に公開された映画をスキャンします。
+ テーブルから映画を削除し、テーブルを削除します。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。
SDK for Swift への DynamoDB 呼び出しを処理する Swift クラス。  

```
import AWSDynamoDB
import Foundation

/// An enumeration of error codes representing issues that can arise when using
/// the `MovieTable` class.
enum MoviesError: Error {
    /// The specified table wasn't found or couldn't be created.
    case TableNotFound
    /// The specified item wasn't found or couldn't be created.
    case ItemNotFound
    /// The Amazon DynamoDB client is not properly initialized.
    case UninitializedClient
    /// The table status reported by Amazon DynamoDB is not recognized.
    case StatusUnknown
    /// One or more specified attribute values are invalid or missing.
    case InvalidAttributes
}

/// A class representing an Amazon DynamoDB table containing movie
/// information.
public class MovieTable {
    var ddbClient: DynamoDBClient?
    let tableName: String

    /// Create an object representing a movie table in an Amazon DynamoDB
    /// database.
    ///
    /// - Parameters:
    ///   - region: The optional Amazon Region to create the database in.
    ///   - tableName: The name to assign to the table. If not specified, a
    ///     random table name is generated automatically.
    ///
    /// > Note: The table is not necessarily available when this function
    /// returns. Use `tableExists()` to check for its availability, or
    /// `awaitTableActive()` to wait until the table's status is reported as
    /// ready to use by Amazon DynamoDB.
    ///
    init(region: String? = nil, tableName: String) async throws {
        do {
            let config = try await DynamoDBClient.DynamoDBClientConfiguration()
            if let region = region {
                config.region = region
            }

            self.ddbClient = DynamoDBClient(config: config)
            self.tableName = tableName

            try await self.createTable()
        } catch {
            print("ERROR: ", dump(error, name: "Initializing Amazon DynamoDBClient client"))
            throw error
        }
    }

    ///
    /// Create a movie table in the Amazon DynamoDB data store.
    ///
    private func createTable() async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = CreateTableInput(
                attributeDefinitions: [
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "year", attributeType: .n),
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "title", attributeType: .s)
                ],
                billingMode: DynamoDBClientTypes.BillingMode.payPerRequest,
                keySchema: [
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "year", keyType: .hash),
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "title", keyType: .range)
                ],
                tableName: self.tableName
            )
            let output = try await client.createTable(input: input)
            if output.tableDescription == nil {
                throw MoviesError.TableNotFound
            }
        } catch {
            print("ERROR: createTable:", dump(error))
            throw error
        }
    }


    /// Check to see if the table exists online yet.
    ///
    /// - Returns: `true` if the table exists, or `false` if not.
    ///
    func tableExists() async throws -> Bool {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DescribeTableInput(
                tableName: tableName
            )
            let output = try await client.describeTable(input: input)
            guard let description = output.table else {
                throw MoviesError.TableNotFound
            }

            return description.tableName == self.tableName
        } catch {
            print("ERROR: tableExists:", dump(error))
            throw error
        }
    }


    ///
    /// Waits for the table to exist and for its status to be active.
    ///
    func awaitTableActive() async throws {
        while try (await self.tableExists() == false) {
            do {
                let duration = UInt64(0.25 * 1_000_000_000) // Convert .25 seconds to nanoseconds.
                try await Task.sleep(nanoseconds: duration)
            } catch {
                print("Sleep error:", dump(error))
            }
        }

        while try (await self.getTableStatus() != .active) {
            do {
                let duration = UInt64(0.25 * 1_000_000_000) // Convert .25 seconds to nanoseconds.
                try await Task.sleep(nanoseconds: duration)
            } catch {
                print("Sleep error:", dump(error))
            }
        }
    }


    ///
    /// Deletes the table from Amazon DynamoDB.
    ///
    func deleteTable() async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DeleteTableInput(
                tableName: self.tableName
            )
            _ = try await client.deleteTable(input: input)
        } catch {
            print("ERROR: deleteTable:", dump(error))
            throw error
        }
    }


    /// Get the table's status.
    ///
    /// - Returns: The table status, as defined by the
    ///   `DynamoDBClientTypes.TableStatus` enum.
    ///
    func getTableStatus() async throws -> DynamoDBClientTypes.TableStatus {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DescribeTableInput(
                tableName: self.tableName
            )
            let output = try await client.describeTable(input: input)
            guard let description = output.table else {
                throw MoviesError.TableNotFound
            }
            guard let status = description.tableStatus else {
                throw MoviesError.StatusUnknown
            }
            return status
        } catch {
            print("ERROR: getTableStatus:", dump(error))
            throw error
        }
    }


    /// Populate the movie database from the specified JSON file.
    ///
    /// - Parameter jsonPath: Path to a JSON file containing movie data.
    ///
    func populate(jsonPath: String) async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Create a Swift `URL` and use it to load the file into a `Data`
            // object. Then decode the JSON into an array of `Movie` objects.

            let fileUrl = URL(fileURLWithPath: jsonPath)
            let jsonData = try Data(contentsOf: fileUrl)

            var movieList = try JSONDecoder().decode([Movie].self, from: jsonData)

            // Truncate the list to the first 200 entries or so for this example.

            if movieList.count > 200 {
                movieList = Array(movieList[...199])
            }

            // Before sending records to the database, break the movie list into
            // 25-entry chunks, which is the maximum size of a batch item request.

            let count = movieList.count
            let chunks = stride(from: 0, to: count, by: 25).map {
                Array(movieList[$0 ..< Swift.min($0 + 25, count)])
            }

            // For each chunk, create a list of write request records and populate
            // them with `PutRequest` requests, each specifying one movie from the
            // chunk. Once the chunk's items are all in the `PutRequest` list,
            // send them to Amazon DynamoDB using the
            // `DynamoDBClient.batchWriteItem()` function.

            for chunk in chunks {
                var requestList: [DynamoDBClientTypes.WriteRequest] = []

                for movie in chunk {
                    let item = try await movie.getAsItem()
                    let request = DynamoDBClientTypes.WriteRequest(
                        putRequest: .init(
                            item: item
                        )
                    )
                    requestList.append(request)
                }

                let input = BatchWriteItemInput(requestItems: [tableName: requestList])
                _ = try await client.batchWriteItem(input: input)
            }
        } catch {
            print("ERROR: populate:", dump(error))
            throw error
        }
    }


    /// Add a movie specified as a `Movie` structure to the Amazon DynamoDB
    /// table.
    ///
    /// - Parameter movie: The `Movie` to add to the table.
    ///
    func add(movie: Movie) async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Get a DynamoDB item containing the movie data.
            let item = try await movie.getAsItem()

            // Send the `PutItem` request to Amazon DynamoDB.

            let input = PutItemInput(
                item: item,
                tableName: self.tableName
            )
            _ = try await client.putItem(input: input)
        } catch {
            print("ERROR: add movie:", dump(error))
            throw error
        }
    }


    /// Given a movie's details, add a movie to the Amazon DynamoDB table.
    ///
    /// - Parameters:
    ///   - title: The movie's title as a `String`.
    ///   - year: The release year of the movie (`Int`).
    ///   - rating: The movie's rating if available (`Double`; default is
    ///     `nil`).
    ///   - plot: A summary of the movie's plot (`String`; default is `nil`,
    ///     indicating no plot summary is available).
    ///
    func add(title: String, year: Int, rating: Double? = nil,
             plot: String? = nil) async throws
    {
        do {
            let movie = Movie(title: title, year: year, rating: rating, plot: plot)
            try await self.add(movie: movie)
        } catch {
            print("ERROR: add with fields:", dump(error))
            throw error
        }
    }


    /// Return a `Movie` record describing the specified movie from the Amazon
    /// DynamoDB table.
    ///
    /// - Parameters:
    ///   - title: The movie's title (`String`).
    ///   - year: The movie's release year (`Int`).
    ///
    /// - Throws: `MoviesError.ItemNotFound` if the movie isn't in the table.
    ///
    /// - Returns: A `Movie` record with the movie's details.
    func get(title: String, year: Int) async throws -> Movie {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = GetItemInput(
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                tableName: self.tableName
            )
            let output = try await client.getItem(input: input)
            guard let item = output.item else {
                throw MoviesError.ItemNotFound
            }

            let movie = try Movie(withItem: item)
            return movie
        } catch {
            print("ERROR: get:", dump(error))
            throw error
        }
    }


    /// Get all the movies released in the specified year.
    ///
    /// - Parameter year: The release year of the movies to return.
    ///
    /// - Returns: An array of `Movie` objects describing each matching movie.
    ///
    func getMovies(fromYear year: Int) async throws -> [Movie] {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = QueryInput(
                expressionAttributeNames: [
                    "#y": "year"
                ],
                expressionAttributeValues: [
                    ":y": .n(String(year))
                ],
                keyConditionExpression: "#y = :y",
                tableName: self.tableName
            )
            // Use "Paginated" to get all the movies.
            // This lets the SDK handle the 'lastEvaluatedKey' property in "QueryOutput".

            let pages = client.queryPaginated(input: input)

            var movieList: [Movie] = []
            for try await page in pages {
                guard let items = page.items else {
                    print("Error: no items returned.")
                    continue
                }

                // Convert the found movies into `Movie` objects and return an array
                // of them.

                for item in items {
                    let movie = try Movie(withItem: item)
                    movieList.append(movie)
                }
            }
            return movieList
        } catch {
            print("ERROR: getMovies:", dump(error))
            throw error
        }
    }


    /// Return an array of `Movie` objects released in the specified range of
    /// years.
    ///
    /// - Parameters:
    ///   - firstYear: The first year of movies to return.
    ///   - lastYear: The last year of movies to return.
    ///   - startKey: A starting point to resume processing; always use `nil`.
    ///
    /// - Returns: An array of `Movie` objects describing the matching movies.
    ///
    /// > Note: The `startKey` parameter is used by this function when
    ///   recursively calling itself, and should always be `nil` when calling
    ///   directly.
    ///
    func getMovies(firstYear: Int, lastYear: Int,
                   startKey: [Swift.String: DynamoDBClientTypes.AttributeValue]? = nil)
        async throws -> [Movie]
    {
        do {
            var movieList: [Movie] = []

            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = ScanInput(
                consistentRead: true,
                exclusiveStartKey: startKey,
                expressionAttributeNames: [
                    "#y": "year" // `year` is a reserved word, so use `#y` instead.
                ],
                expressionAttributeValues: [
                    ":y1": .n(String(firstYear)),
                    ":y2": .n(String(lastYear))
                ],
                filterExpression: "#y BETWEEN :y1 AND :y2",
                tableName: self.tableName
            )

            let pages = client.scanPaginated(input: input)

            for try await page in pages {
                guard let items = page.items else {
                    print("Error: no items returned.")
                    continue
                }

                // Build an array of `Movie` objects for the returned items.

                for item in items {
                    let movie = try Movie(withItem: item)
                    movieList.append(movie)
                }
            }
            return movieList

        } catch {
            print("ERROR: getMovies with scan:", dump(error))
            throw error
        }
    }


    /// Update the specified movie with new `rating` and `plot` information.
    ///
    /// - Parameters:
    ///   - title: The title of the movie to update.
    ///   - year: The release year of the movie to update.
    ///   - rating: The new rating for the movie.
    ///   - plot: The new plot summary string for the movie.
    ///
    /// - Returns: An array of mappings of attribute names to their new
    ///   listing each item actually changed. Items that didn't need to change
    ///   aren't included in this list. `nil` if no changes were made.
    ///
    func update(title: String, year: Int, rating: Double? = nil, plot: String? = nil) async throws
        -> [Swift.String: DynamoDBClientTypes.AttributeValue]?
    {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Build the update expression and the list of expression attribute
            // values. Include only the information that's changed.

            var expressionParts: [String] = []
            var attrValues: [Swift.String: DynamoDBClientTypes.AttributeValue] = [:]

            if rating != nil {
                expressionParts.append("info.rating=:r")
                attrValues[":r"] = .n(String(rating!))
            }
            if plot != nil {
                expressionParts.append("info.plot=:p")
                attrValues[":p"] = .s(plot!)
            }
            let expression = "set \(expressionParts.joined(separator: ", "))"

            let input = UpdateItemInput(
                // Create substitution tokens for the attribute values, to ensure
                // no conflicts in expression syntax.
                expressionAttributeValues: attrValues,
                // The key identifying the movie to update consists of the release
                // year and title.
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                returnValues: .updatedNew,
                tableName: self.tableName,
                updateExpression: expression
            )
            let output = try await client.updateItem(input: input)

            guard let attributes: [Swift.String: DynamoDBClientTypes.AttributeValue] = output.attributes else {
                throw MoviesError.InvalidAttributes
            }
            return attributes
        } catch {
            print("ERROR: update:", dump(error))
            throw error
        }
    }


    /// Delete a movie, given its title and release year.
    ///
    /// - Parameters:
    ///   - title: The movie's title.
    ///   - year: The movie's release year.
    ///
    func delete(title: String, year: Int) async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DeleteItemInput(
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                tableName: self.tableName
            )
            _ = try await client.deleteItem(input: input)
        } catch {
            print("ERROR: delete:", dump(error))
            throw error
        }
    }
}
```
MovieTable クラスがムービーを表現するために使用する構造。  

```
import Foundation
import AWSDynamoDB

/// The optional details about a movie.
public struct Details: Codable {
    /// The movie's rating, if available.
    var rating: Double?
    /// The movie's plot, if available.
    var plot: String?
}

/// A structure describing a movie. The `year` and `title` properties are
/// required and are used as the key for Amazon DynamoDB operations. The
/// `info` sub-structure's two properties, `rating` and `plot`, are optional.
public struct Movie: Codable {
    /// The year in which the movie was released.
    var year: Int
    /// The movie's title.
    var title: String
    /// A `Details` object providing the optional movie rating and plot
    /// information.
    var info: Details

    /// Create a `Movie` object representing a movie, given the movie's
    /// details.
    ///
    /// - Parameters:
    ///   - title: The movie's title (`String`).
    ///   - year: The year in which the movie was released (`Int`).
    ///   - rating: The movie's rating (optional `Double`).
    ///   - plot: The movie's plot (optional `String`)
    init(title: String, year: Int, rating: Double? = nil, plot: String? = nil) {
        self.title = title
        self.year = year

        self.info = Details(rating: rating, plot: plot)
    }

    /// Create a `Movie` object representing a movie, given the movie's
    /// details.
    ///
    /// - Parameters:
    ///   - title: The movie's title (`String`).
    ///   - year: The year in which the movie was released (`Int`).
    ///   - info: The optional rating and plot information for the movie in a
    ///     `Details` object.
    init(title: String, year: Int, info: Details?){
        self.title = title
        self.year = year

        if info != nil {
            self.info = info!
        } else {
            self.info = Details(rating: nil, plot: nil)
        }
    }

    ///
    /// Return a new `MovieTable` object, given an array mapping string to Amazon
    /// DynamoDB attribute values.
    /// 
    /// - Parameter item: The item information provided to the form used by
    ///   DynamoDB. This is an array of strings mapped to
    ///   `DynamoDBClientTypes.AttributeValue` values.
    init(withItem item: [Swift.String:DynamoDBClientTypes.AttributeValue]) throws  {
        // Read the attributes.

        guard let titleAttr = item["title"],
              let yearAttr = item["year"] else {
            throw MoviesError.ItemNotFound
        }
        let infoAttr = item["info"] ?? nil

        // Extract the values of the title and year attributes.

        if case .s(let titleVal) = titleAttr {
            self.title = titleVal
        } else {
            throw MoviesError.InvalidAttributes
        }

        if case .n(let yearVal) = yearAttr {
            self.year = Int(yearVal)!
        } else {
            throw MoviesError.InvalidAttributes
        }

        // Extract the rating and/or plot from the `info` attribute, if
        // they're present.

        var rating: Double? = nil
        var plot: String? = nil

        if infoAttr != nil, case .m(let infoVal) = infoAttr {
            let ratingAttr = infoVal["rating"] ?? nil
            let plotAttr = infoVal["plot"] ?? nil

            if ratingAttr != nil, case .n(let ratingVal) = ratingAttr {
                rating = Double(ratingVal) ?? nil
            }
            if plotAttr != nil, case .s(let plotVal) = plotAttr {
                plot = plotVal
            }
        }

        self.info = Details(rating: rating, plot: plot)
    }

    ///
    /// Return an array mapping attribute names to Amazon DynamoDB attribute
    /// values, representing the contents of the `Movie` record as a DynamoDB
    /// item.
    ///
    /// - Returns: The movie item as an array of type
    ///   `[Swift.String:DynamoDBClientTypes.AttributeValue]`.
    ///
    func getAsItem() async throws -> [Swift.String:DynamoDBClientTypes.AttributeValue]  {
        // Build the item record, starting with the year and title, which are
        // always present.

        var item: [Swift.String:DynamoDBClientTypes.AttributeValue] = [
            "year": .n(String(self.year)),
            "title": .s(self.title)
        ]

        // Add the `info` field with the rating and/or plot if they're
        // available.

        var details: [Swift.String:DynamoDBClientTypes.AttributeValue] = [:]
        if (self.info.rating != nil || self.info.plot != nil) {
            if self.info.rating != nil {
                details["rating"] = .n(String(self.info.rating!))
            }
            if self.info.plot != nil {
                details["plot"] = .s(self.info.plot!)
            }
        }
        item["info"] = .m(details)

        return item
    }
 }
```
MovieTable クラスを使用して DynamoDB データベースにアクセスするプログラム。  

```
import ArgumentParser
import ClientRuntime
import Foundation

import AWSDynamoDB


@testable import MovieList

extension String {
    // Get the directory if the string is a file path.
    func directory() -> String {
        guard let lastIndex = lastIndex(of: "/") else {
            print("Error: String directory separator not found.")
            return ""
        }
        return String(self[...lastIndex])
    }
}

struct ExampleCommand: ParsableCommand {
    @Argument(help: "The path of the sample movie data JSON file.")
    var jsonPath: String = #file.directory() + "../../../../../resources/sample_files/movies.json"

    @Option(help: "The AWS Region to run AWS API calls in.")
    var awsRegion: String?

    @Option(
        help: ArgumentHelp("The level of logging for the Swift SDK to perform."),
        completion: .list([
            "critical",
            "debug",
            "error",
            "info",
            "notice",
            "trace",
            "warning"
        ])
    )
    var logLevel: String = "error"

    /// Configuration details for the command.
    static var configuration = CommandConfiguration(
        commandName: "basics",
        abstract: "A basic scenario demonstrating the usage of Amazon DynamoDB.",
        discussion: """
        An example showing how to use Amazon DynamoDB to perform a series of
        common database activities on a simple movie database.
        """
    )

    /// Called by ``main()`` to asynchronously run the AWS example.
    func runAsync() async throws {
        print("Welcome to the AWS SDK for Swift basic scenario for Amazon DynamoDB!")

        //=====================================================================
        // 1. Create the table. The Amazon DynamoDB table is represented by
        //    the `MovieTable` class.
        //=====================================================================

        let tableName = "ddb-movies-sample-\(Int.random(in: 1 ... Int.max))"

        print("Creating table \"\(tableName)\"...")

        let movieDatabase = try await MovieTable(region: awsRegion,
                                                 tableName: tableName)

        print("\nWaiting for table to be ready to use...")
        try await movieDatabase.awaitTableActive()

        //=====================================================================
        // 2. Add a movie to the table.
        //=====================================================================

        print("\nAdding a movie...")
        try await movieDatabase.add(title: "Avatar: The Way of Water", year: 2022)
        try await movieDatabase.add(title: "Not a Real Movie", year: 2023)

        //=====================================================================
        // 3. Update the plot and rating of the movie using an update
        //    expression.
        //=====================================================================

        print("\nAdding details to the added movie...")
        _ = try await movieDatabase.update(title: "Avatar: The Way of Water", year: 2022,
                                           rating: 9.2, plot: "It's a sequel.")

        //=====================================================================
        // 4. Populate the table from the JSON file.
        //=====================================================================

        print("\nPopulating the movie database from JSON...")
        try await movieDatabase.populate(jsonPath: jsonPath)

        //=====================================================================
        // 5. Get a specific movie by key. In this example, the key is a
        //    combination of `title` and `year`.
        //=====================================================================

        print("\nLooking for a movie in the table...")
        let gotMovie = try await movieDatabase.get(title: "This Is the End", year: 2013)

        print("Found the movie \"\(gotMovie.title)\", released in \(gotMovie.year).")
        print("Rating: \(gotMovie.info.rating ?? 0.0).")
        print("Plot summary: \(gotMovie.info.plot ?? "None.")")

        //=====================================================================
        // 6. Delete a movie.
        //=====================================================================

        print("\nDeleting the added movie...")
        try await movieDatabase.delete(title: "Avatar: The Way of Water", year: 2022)

        //=====================================================================
        // 7. Use a query with a key condition expression to return all movies
        //    released in a given year.
        //=====================================================================

        print("\nGetting movies released in 1994...")
        let movieList = try await movieDatabase.getMovies(fromYear: 1994)
        for movie in movieList {
            print("    \(movie.title)")
        }

        //=====================================================================
        // 8. Use `scan()` to return movies released in a range of years.
        //=====================================================================

        print("\nGetting movies released between 1993 and 1997...")
        let scannedMovies = try await movieDatabase.getMovies(firstYear: 1993, lastYear: 1997)
        for movie in scannedMovies {
            print("    \(movie.title) (\(movie.year))")
        }

        //=====================================================================
        // 9. Delete the table.
        //=====================================================================

        print("\nDeleting the table...")
        try await movieDatabase.deleteTable()
    }
}

@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [BatchWriteItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/batchwriteitem(input:))
  + [CreateTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/createtable(input:))
  + [DeleteItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deleteitem(input:))
  + [DeleteTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deletetable(input:))
  + [DescribeTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/describetable(input:))
  + [GetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/getitem(input:))
  + [PutItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/putitem(input:))
  + [Query](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/query(input:))
  + [Scan](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/scan(input:))
  + [UpdateItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/updateitem(input:))

## アクション
<a name="actions"></a>

### `BatchGetItem`
<a name="dynamodb_BatchGetItem_swift_1_topic"></a>

次のコード例は、`BatchGetItem` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Gets an array of `Movie` objects describing all the movies in the
    /// specified list. Any movies that aren't found in the list have no
    /// corresponding entry in the resulting array.
    ///
    /// - Parameters
    ///     - keys: An array of tuples, each of which specifies the title and
    ///       release year of a movie to fetch from the table.
    ///
    /// - Returns:
    ///     - An array of `Movie` objects describing each match found in the
    ///     table.
    ///
    /// - Throws:
    ///     - `MovieError.ClientUninitialized` if the DynamoDB client has not
    ///     been initialized.
    ///     - DynamoDB errors are thrown without change.
    func batchGet(keys: [(title: String, year: Int)]) async throws -> [Movie] {
        do {
            guard let client = self.ddbClient else {
                throw MovieError.ClientUninitialized
            }
            
            var movieList: [Movie] = []
            var keyItems: [[Swift.String: DynamoDBClientTypes.AttributeValue]] = []
            
            // Convert the list of keys into the form used by DynamoDB.
            
            for key in keys {
                let item: [Swift.String: DynamoDBClientTypes.AttributeValue] = [
                    "title": .s(key.title),
                    "year": .n(String(key.year))
                ]
                keyItems.append(item)
            }
            
            // Create the input record for `batchGetItem()`. The list of requested
            // items is in the `requestItems` property. This array contains one
            // entry for each table from which items are to be fetched. In this
            // example, there's only one table containing the movie data.
            //
            // If we wanted this program to also support searching for matches
            // in a table of book data, we could add a second `requestItem`
            // mapping the name of the book table to the list of items we want to
            // find in it.
            let input = BatchGetItemInput(
                requestItems: [
                    self.tableName: .init(
                        consistentRead: true,
                        keys: keyItems
                    )
                ]
            )
            
            // Fetch the matching movies from the table.
            
            let output = try await client.batchGetItem(input: input)
            
            // Get the set of responses. If there aren't any, return the empty
            // movie list.
            
            guard let responses = output.responses else {
                return movieList
            }
            
            // Get the list of matching items for the table with the name
            // `tableName`.
            
            guard let responseList = responses[self.tableName] else {
                return movieList
            }
            
            // Create `Movie` items for each of the matching movies in the table
            // and add them to the `MovieList` array.
            
            for response in responseList {
                try movieList.append(Movie(withItem: response))
            }
            
            return movieList
        } catch {
            print("ERROR: batchGet", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[BatchGetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/batchgetitem(input:))」を参照してください。

### `BatchWriteItem`
<a name="dynamodb_BatchWriteItem_swift_1_topic"></a>

次のコード例は、`BatchWriteItem` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb/#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Populate the movie database from the specified JSON file.
    ///
    /// - Parameter jsonPath: Path to a JSON file containing movie data.
    ///
    func populate(jsonPath: String) async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Create a Swift `URL` and use it to load the file into a `Data`
            // object. Then decode the JSON into an array of `Movie` objects.

            let fileUrl = URL(fileURLWithPath: jsonPath)
            let jsonData = try Data(contentsOf: fileUrl)

            var movieList = try JSONDecoder().decode([Movie].self, from: jsonData)

            // Truncate the list to the first 200 entries or so for this example.

            if movieList.count > 200 {
                movieList = Array(movieList[...199])
            }

            // Before sending records to the database, break the movie list into
            // 25-entry chunks, which is the maximum size of a batch item request.

            let count = movieList.count
            let chunks = stride(from: 0, to: count, by: 25).map {
                Array(movieList[$0 ..< Swift.min($0 + 25, count)])
            }

            // For each chunk, create a list of write request records and populate
            // them with `PutRequest` requests, each specifying one movie from the
            // chunk. Once the chunk's items are all in the `PutRequest` list,
            // send them to Amazon DynamoDB using the
            // `DynamoDBClient.batchWriteItem()` function.

            for chunk in chunks {
                var requestList: [DynamoDBClientTypes.WriteRequest] = []

                for movie in chunk {
                    let item = try await movie.getAsItem()
                    let request = DynamoDBClientTypes.WriteRequest(
                        putRequest: .init(
                            item: item
                        )
                    )
                    requestList.append(request)
                }

                let input = BatchWriteItemInput(requestItems: [tableName: requestList])
                _ = try await client.batchWriteItem(input: input)
            }
        } catch {
            print("ERROR: populate:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[BatchWriteItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/batchwriteitem(input:))」を参照してください。

### `CreateTable`
<a name="dynamodb_CreateTable_swift_1_topic"></a>

次のコード例は、`CreateTable` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    ///
    /// Create a movie table in the Amazon DynamoDB data store.
    ///
    private func createTable() async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = CreateTableInput(
                attributeDefinitions: [
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "year", attributeType: .n),
                    DynamoDBClientTypes.AttributeDefinition(attributeName: "title", attributeType: .s)
                ],
                billingMode: DynamoDBClientTypes.BillingMode.payPerRequest,
                keySchema: [
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "year", keyType: .hash),
                    DynamoDBClientTypes.KeySchemaElement(attributeName: "title", keyType: .range)
                ],
                tableName: self.tableName
            )
            let output = try await client.createTable(input: input)
            if output.tableDescription == nil {
                throw MoviesError.TableNotFound
            }
        } catch {
            print("ERROR: createTable:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[CreateTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/createtable(input:))」を参照してください。

### `DeleteItem`
<a name="dynamodb_DeleteItem_swift_1_topic"></a>

次のコード例は、`DeleteItem` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Delete a movie, given its title and release year.
    ///
    /// - Parameters:
    ///   - title: The movie's title.
    ///   - year: The movie's release year.
    ///
    func delete(title: String, year: Int) async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DeleteItemInput(
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                tableName: self.tableName
            )
            _ = try await client.deleteItem(input: input)
        } catch {
            print("ERROR: delete:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[DeleteItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deleteitem(input:))」を参照してください。

### `DeleteTable`
<a name="dynamodb_DeleteTable_swift_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    ///
    /// Deletes the table from Amazon DynamoDB.
    ///
    func deleteTable() async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = DeleteTableInput(
                tableName: self.tableName
            )
            _ = try await client.deleteTable(input: input)
        } catch {
            print("ERROR: deleteTable:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[DeleteTable](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/deletetable(input:))」を参照してください。

### `GetItem`
<a name="dynamodb_GetItem_swift_1_topic"></a>

次のコード例は、`GetItem` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Return a `Movie` record describing the specified movie from the Amazon
    /// DynamoDB table.
    ///
    /// - Parameters:
    ///   - title: The movie's title (`String`).
    ///   - year: The movie's release year (`Int`).
    ///
    /// - Throws: `MoviesError.ItemNotFound` if the movie isn't in the table.
    ///
    /// - Returns: A `Movie` record with the movie's details.
    func get(title: String, year: Int) async throws -> Movie {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = GetItemInput(
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                tableName: self.tableName
            )
            let output = try await client.getItem(input: input)
            guard let item = output.item else {
                throw MoviesError.ItemNotFound
            }

            let movie = try Movie(withItem: item)
            return movie
        } catch {
            print("ERROR: get:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[GetItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/getitem(input:))」を参照してください。

### `ListTables`
<a name="dynamodb_ListTables_swift_1_topic"></a>

次のコード例は、`ListTables` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Get a list of the DynamoDB tables available in the specified Region.
    ///
    /// - Returns: An array of strings listing all of the tables available
    ///   in the Region specified when the session was created.
    public func getTableList() async throws -> [String] {
        let input = ListTablesInput(
        )
        return try await session.listTables(input: input)
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ListTables](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/listtables(input:))」を参照してください。

### `PutItem`
<a name="dynamodb_PutItem_swift_1_topic"></a>

次のコード例は、`PutItem` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Add a movie specified as a `Movie` structure to the Amazon DynamoDB
    /// table.
    ///
    /// - Parameter movie: The `Movie` to add to the table.
    ///
    func add(movie: Movie) async throws {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Get a DynamoDB item containing the movie data.
            let item = try await movie.getAsItem()

            // Send the `PutItem` request to Amazon DynamoDB.

            let input = PutItemInput(
                item: item,
                tableName: self.tableName
            )
            _ = try await client.putItem(input: input)
        } catch {
            print("ERROR: add movie:", dump(error))
            throw error
        }
    }


    ///
    /// Return an array mapping attribute names to Amazon DynamoDB attribute
    /// values, representing the contents of the `Movie` record as a DynamoDB
    /// item.
    ///
    /// - Returns: The movie item as an array of type
    ///   `[Swift.String:DynamoDBClientTypes.AttributeValue]`.
    ///
    func getAsItem() async throws -> [Swift.String:DynamoDBClientTypes.AttributeValue]  {
        // Build the item record, starting with the year and title, which are
        // always present.

        var item: [Swift.String:DynamoDBClientTypes.AttributeValue] = [
            "year": .n(String(self.year)),
            "title": .s(self.title)
        ]

        // Add the `info` field with the rating and/or plot if they're
        // available.

        var details: [Swift.String:DynamoDBClientTypes.AttributeValue] = [:]
        if (self.info.rating != nil || self.info.plot != nil) {
            if self.info.rating != nil {
                details["rating"] = .n(String(self.info.rating!))
            }
            if self.info.plot != nil {
                details["plot"] = .s(self.info.plot!)
            }
        }
        item["info"] = .m(details)

        return item
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[PutItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/putitem(input:))」を参照してください。

### `Query`
<a name="dynamodb_Query_swift_1_topic"></a>

次のコード例は、`Query` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Get all the movies released in the specified year.
    ///
    /// - Parameter year: The release year of the movies to return.
    ///
    /// - Returns: An array of `Movie` objects describing each matching movie.
    ///
    func getMovies(fromYear year: Int) async throws -> [Movie] {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = QueryInput(
                expressionAttributeNames: [
                    "#y": "year"
                ],
                expressionAttributeValues: [
                    ":y": .n(String(year))
                ],
                keyConditionExpression: "#y = :y",
                tableName: self.tableName
            )
            // Use "Paginated" to get all the movies.
            // This lets the SDK handle the 'lastEvaluatedKey' property in "QueryOutput".

            let pages = client.queryPaginated(input: input)

            var movieList: [Movie] = []
            for try await page in pages {
                guard let items = page.items else {
                    print("Error: no items returned.")
                    continue
                }

                // Convert the found movies into `Movie` objects and return an array
                // of them.

                for item in items {
                    let movie = try Movie(withItem: item)
                    movieList.append(movie)
                }
            }
            return movieList
        } catch {
            print("ERROR: getMovies:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Query](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/query(input:))」を参照してください。

### `Scan`
<a name="dynamodb_Scan_swift_1_topic"></a>

次のコード例は、`Scan` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Return an array of `Movie` objects released in the specified range of
    /// years.
    ///
    /// - Parameters:
    ///   - firstYear: The first year of movies to return.
    ///   - lastYear: The last year of movies to return.
    ///   - startKey: A starting point to resume processing; always use `nil`.
    ///
    /// - Returns: An array of `Movie` objects describing the matching movies.
    ///
    /// > Note: The `startKey` parameter is used by this function when
    ///   recursively calling itself, and should always be `nil` when calling
    ///   directly.
    ///
    func getMovies(firstYear: Int, lastYear: Int,
                   startKey: [Swift.String: DynamoDBClientTypes.AttributeValue]? = nil)
        async throws -> [Movie]
    {
        do {
            var movieList: [Movie] = []

            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            let input = ScanInput(
                consistentRead: true,
                exclusiveStartKey: startKey,
                expressionAttributeNames: [
                    "#y": "year" // `year` is a reserved word, so use `#y` instead.
                ],
                expressionAttributeValues: [
                    ":y1": .n(String(firstYear)),
                    ":y2": .n(String(lastYear))
                ],
                filterExpression: "#y BETWEEN :y1 AND :y2",
                tableName: self.tableName
            )

            let pages = client.scanPaginated(input: input)

            for try await page in pages {
                guard let items = page.items else {
                    print("Error: no items returned.")
                    continue
                }

                // Build an array of `Movie` objects for the returned items.

                for item in items {
                    let movie = try Movie(withItem: item)
                    movieList.append(movie)
                }
            }
            return movieList

        } catch {
            print("ERROR: getMovies with scan:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Scan](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/scan(input:))」を参照してください。

### `UpdateItem`
<a name="dynamodb_UpdateItem_swift_1_topic"></a>

次のコード例は、`UpdateItem` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/dynamodb#code-examples)での設定と実行の方法を確認してください。

```
import AWSDynamoDB


    /// Update the specified movie with new `rating` and `plot` information.
    ///
    /// - Parameters:
    ///   - title: The title of the movie to update.
    ///   - year: The release year of the movie to update.
    ///   - rating: The new rating for the movie.
    ///   - plot: The new plot summary string for the movie.
    ///
    /// - Returns: An array of mappings of attribute names to their new
    ///   listing each item actually changed. Items that didn't need to change
    ///   aren't included in this list. `nil` if no changes were made.
    ///
    func update(title: String, year: Int, rating: Double? = nil, plot: String? = nil) async throws
        -> [Swift.String: DynamoDBClientTypes.AttributeValue]?
    {
        do {
            guard let client = self.ddbClient else {
                throw MoviesError.UninitializedClient
            }

            // Build the update expression and the list of expression attribute
            // values. Include only the information that's changed.

            var expressionParts: [String] = []
            var attrValues: [Swift.String: DynamoDBClientTypes.AttributeValue] = [:]

            if rating != nil {
                expressionParts.append("info.rating=:r")
                attrValues[":r"] = .n(String(rating!))
            }
            if plot != nil {
                expressionParts.append("info.plot=:p")
                attrValues[":p"] = .s(plot!)
            }
            let expression = "set \(expressionParts.joined(separator: ", "))"

            let input = UpdateItemInput(
                // Create substitution tokens for the attribute values, to ensure
                // no conflicts in expression syntax.
                expressionAttributeValues: attrValues,
                // The key identifying the movie to update consists of the release
                // year and title.
                key: [
                    "year": .n(String(year)),
                    "title": .s(title)
                ],
                returnValues: .updatedNew,
                tableName: self.tableName,
                updateExpression: expression
            )
            let output = try await client.updateItem(input: input)

            guard let attributes: [Swift.String: DynamoDBClientTypes.AttributeValue] = output.attributes else {
                throw MoviesError.InvalidAttributes
            }
            return attributes
        } catch {
            print("ERROR: update:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[UpdateItem](https://sdk.amazonaws.com/swift/api/awsdynamodb/latest/documentation/awsdynamodb/dynamodbclient/updateitem(input:))」を参照してください。

# SDK for Swift を使用した Amazon EC2の例
<a name="swift_1_ec2_code_examples"></a>

次のコード例は、Amazon EC2 で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [基本](#basics)
+ [アクション](#actions)

## はじめに
<a name="get_started"></a>

### Hello Amazon EC2
<a name="ec2_Hello_swift_1_topic"></a>

次のコード例は、Amazon EC2 の使用を開始する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
`Package.swift` ファイル。  

```
// swift-tools-version: 5.9
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "hello-ec2",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13),
        .iOS(.v15)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.0.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "hello-ec2",
            dependencies: [
                .product(name: "AWSEC2", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources")

    ]
)
```
`entry.swift` ファイル。  

```
// An example that shows how to use the AWS SDK for Swift to perform a simple
// operation using Amazon Elastic Compute Cloud (EC2).
//

import ArgumentParser
import Foundation

import AWSEC2

struct ExampleCommand: ParsableCommand {
    @Option(help: "The AWS Region to run AWS API calls in.")
    var awsRegion = "us-east-1"

    @Option(
        help: ArgumentHelp("The level of logging for the Swift SDK to perform."),
        completion: .list([
            "critical",
            "debug",
            "error",
            "info",
            "notice",
            "trace",
            "warning"
        ])
    )
    var logLevel: String = "error"

    static var configuration = CommandConfiguration(
        commandName: "hello-ec2",
        abstract: """
        Demonstrates a simple operation using Amazon EC2.
        """,
        discussion: """
        An example showing how to make a call to Amazon EC2 using the AWS SDK for Swift.
        """
    )

    /// Return an array of strings giving the names of every security group
    /// the user is a member of.
    ///
    /// - Parameter ec2Client: The `EC2Client` to use when calling
    ///   `describeSecurityGroupsPaginated()`.
    ///
    /// - Returns: An array of strings giving the names of every security
    ///   group the user is a member of.
    func getSecurityGroupNames(ec2Client: EC2Client) async -> [String] {
        let pages = ec2Client.describeSecurityGroupsPaginated(
            input: DescribeSecurityGroupsInput()
        )

        var groupNames: [String] = []

        do {
            for try await page in pages {
                guard let groups = page.securityGroups else {
                    print("*** Error: No groups returned.")
                    continue
                }

                for group in groups {
                    groupNames.append(group.groupName ?? "<unknown>")
                }
            }
        } catch {
            print("*** Error: \(error.localizedDescription)")
        }

        return groupNames
    }

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let ec2Config = try await EC2Client.EC2ClientConfiguration(region: awsRegion)
        let ec2Client = EC2Client(config: ec2Config)

        let groupNames = await getSecurityGroupNames(ec2Client: ec2Client)

        print("Found \(groupNames.count) security group(s):")

        for group in groupNames {
            print("    \(group)")
        }
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DescribeSecurityGroups](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describesecuritygroups(input:))」を参照してください。**

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="ec2_Scenario_GetStartedInstances_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ キーペアとセキュリティグループを作成します。
+ Amazon マシンイメージ (AMI)と互換性のあるインスタンスタイプを選択し、インスタンスを作成します。
+ インスタンスを停止し、再起動します。
+ Elastic IP アドレスをインスタンスに関連付けます。
+ SSH を使用してインスタンスに接続し、リソースをクリーンアップします。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
`Package.swift` ファイル。  

```
// swift-tools-version: 5.9
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "ec2-scenario",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13),
        .iOS(.v15)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.4.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "ec2-scenario",
            dependencies: [
                .product(name: "AWSEC2", package: "aws-sdk-swift"),
                .product(name: "AWSSSM", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources")

    ]
)
```
`entry.swift` ファイル。  

```
// An example that shows how to use the AWS SDK for Swift to perform a variety
// of operations using Amazon Elastic Compute Cloud (EC2).
//

import ArgumentParser
import Foundation
import AWSEC2

// Allow waiters to be used.

import class SmithyWaitersAPI.Waiter
import struct SmithyWaitersAPI.WaiterOptions

import AWSSSM

struct ExampleCommand: ParsableCommand {
    @Option(help: "The AWS Region to run AWS API calls in.")
    var awsRegion = "us-east-1"

    @Option(
        help: ArgumentHelp("The level of logging for the Swift SDK to perform."),
        completion: .list([
            "critical",
            "debug",
            "error",
            "info",
            "notice",
            "trace",
            "warning"
        ])
    )
    var logLevel: String = "error"

    static var configuration = CommandConfiguration(
        commandName: "ec2-scenario",
        abstract: """
        Performs various operations to demonstrate the use of Amazon EC2 using the
        AWS SDK for Swift.
        """,
        discussion: """
        """
    )

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let ssmConfig = try await SSMClient.SSMClientConfiguration(region: awsRegion)
        let ssmClient = SSMClient(config: ssmConfig)

        let ec2Config = try await EC2Client.EC2ClientConfiguration(region: awsRegion)
        let ec2Client = EC2Client(config: ec2Config)

        let example = Example(ec2Client: ec2Client, ssmClient: ssmClient)

        await example.run()
    }
}

class Example {
    let ec2Client: EC2Client
    let ssmClient: SSMClient

    // Storage for AWS EC2 properties.

    var keyName: String? = nil
    var securityGroupId: String? = nil
    var instanceId: String? = nil
    var allocationId: String? = nil
    var associationId: String? = nil

    init(ec2Client: EC2Client, ssmClient: SSMClient) {
        self.ec2Client = ec2Client
        self.ssmClient = ssmClient
    }

    /// The example's main body.
    func run() async {
        //=====================================================================
        // 1. Create an RSA key pair, saving the private key as a `.pem` file.
        //    Create a `defer` block that will delete the private key when the
        //    program exits.
        //=====================================================================

        print("Creating an RSA key pair...")

        keyName = self.tempName(prefix: "ExampleKeyName")
        let keyUrl = await self.createKeyPair(name: keyName!)

        guard let keyUrl else {
            print("*** Failed to create the key pair!")
            return
        }

        print("Created the private key at: \(keyUrl.absoluteString)")

        // Schedule deleting the private key file to occur automatically when
        // the program exits, no matter how it exits.

        defer {
            do {
                try FileManager.default.removeItem(at: keyUrl)
            } catch {
                print("*** Failed to delete the private key at \(keyUrl.absoluteString)")
            }
        }

        //=====================================================================
        // 2. List the key pairs by calling `DescribeKeyPairs`.
        //=====================================================================

        print("Describing available key pairs...")
        await self.describeKeyPairs()

        //=====================================================================
        // 3. Create a security group for the default VPC, and add an inbound
        //    rule to allow SSH from the current computer's public IPv4
        //    address.
        //=====================================================================

        print("Creating the security group...")

        let secGroupName = self.tempName(prefix: "ExampleSecurityGroup")
        let ipAddress = self.getMyIPAddress()

        guard let ipAddress else {
            print("*** Unable to get the device's IP address.")
            return
        }

        print("IP address is: \(ipAddress)")

        securityGroupId = await self.createSecurityGroup(
            name: secGroupName,
            description: "An example security group created using the AWS SDK for Swift"
        )

        if securityGroupId == nil {
            await cleanUp()
            return
        }

        print("Created security group: \(securityGroupId ?? "<unknown>")")

        if !(await self.authorizeSecurityGroupIngress(groupId: securityGroupId!, ipAddress: ipAddress)) {
            await cleanUp()
            return
        }

        //=====================================================================
        // 4. Display security group information for the new security group
        //    using DescribeSecurityGroups.
        //=====================================================================

        if !(await self.describeSecurityGroups(groupId: securityGroupId!)) {
            await cleanUp()
            return
        }

        //=====================================================================
        // 5. Get a list of Amazon Linux 2023 AMIs and pick one (SSM is the
        //    best practice), using path and then filter the list after the
        //    fact to include "al2023" in the Name field
        //    (ssm.GetParametersByPath). Paginate to get all images.
        //=====================================================================

        print("Searching available images for Amazon Linux 2023 images...")

        let options = await self.findAMIsMatchingFilter("al2023")

        //=====================================================================
        // 6. The information in the AMI options isn't great, so make a list
        //    of the image IDs (the "Value" field in the AMI options) and get
        //    more information about them from EC2. Display the Description
        //    field and select one of them (DescribeImages with ImageIds
        //    filter).
        //=====================================================================

        print("Images matching Amazon Linux 2023:")

        var imageIds: [String] = []
        for option in options {
            guard let id = option.value else {
                continue
            }
            imageIds.append(id)
        }
        
        let images = await self.describeImages(imageIds)

        // This is where you would normally let the user choose which AMI to
        // use. However, for this example, we're just going to use the first
        // one, whatever it is.

        let chosenImage = images[0]

        //=====================================================================
        // 7. Get a list of instance types that are compatible with the
        //    selected AMI's architecture (such as "x86_64") and are either
        //    small or micro. Select one (DescribeInstanceTypes).
        //=====================================================================

        print("Getting the instance types compatible with the selected image...")

        guard let arch = chosenImage.architecture else {
            print("*** The selected image doesn't have a valid architecture.")
            await cleanUp()
            return
        }

        let imageTypes = await self.getMatchingInstanceTypes(architecture: arch)

        for type in imageTypes {
            guard let instanceType = type.instanceType else {
                continue
            }
            print("    \(instanceType.rawValue)")
        }

        // This example selects the first returned instance type. A real-world
        // application would probably ask the user to select one here.

        let chosenInstanceType = imageTypes[0]

        //=====================================================================
        // 8. Create an instance with the key pair, security group, AMI, and
        //    instance type (RunInstances).
        //=====================================================================

        print("Creating an instance...")

        guard let imageId = chosenImage.imageId else {
            print("*** Cannot start image without a valid image ID.")
            await cleanUp()
            return
        }
        guard let instanceType = chosenInstanceType.instanceType else {
            print("*** Unable to start image without a valid image type.")
            await cleanUp()
            return
        }

        let instance = await self.runInstance(
            imageId: imageId,
            instanceType: instanceType,
            keyPairName: keyName!,
            securityGroups: [securityGroupId!]
        )

        guard let instance else {
            await cleanUp()
            return
        }

        instanceId = instance.instanceId
        if instanceId == nil {
            print("*** Instance is missing an ID. Canceling.")
            await cleanUp()
            return
        }

        //=====================================================================
        // 9. Wait for the instance to be ready and then display its
        //    information (DescribeInstances).
        //=====================================================================

        print("Waiting a few seconds to let the instance come up...")
        
        do {
            try await Task.sleep(for: .seconds(20))
        } catch {
            print("*** Error pausing the task.")
        }
        print("Success! Your new instance is ready:")

        //=====================================================================
        // 10. Display SSH connection info for the instance.
        //=====================================================================

        var runningInstance = await self.describeInstance(instanceId: instanceId!)

        if (runningInstance != nil) && (runningInstance!.publicIpAddress != nil) {
            print("\nYou can SSH to this instance using the following command:")
            print("ssh -i \(keyUrl.path) ec2-user@\(runningInstance!.publicIpAddress!)")
        }

        //=====================================================================
        // 11. Stop the instance and wait for it to stop (StopInstances).
        //=====================================================================

        print("Stopping the instance...")

        if !(await self.stopInstance(instanceId: instanceId!, waitUntilStopped: true)) {
            await cleanUp()
            return
        }

        //=====================================================================
        // 12. Start the instance and wait for it to start (StartInstances).
        //=====================================================================

        print("Starting the instance again...")

        if !(await self.startInstance(instanceId: instanceId!, waitUntilStarted: true)) {
            await cleanUp()
            return
        }

        //=====================================================================
        // 13. Display SSH connection info for the instance. Note that it's
        //     changed.
        //=====================================================================

        runningInstance = await self.describeInstance(instanceId: instanceId!)
        if (runningInstance != nil) && (runningInstance!.publicIpAddress != nil) {
            print("\nYou can SSH to this instance using the following command.")
            print("This is probably different from when the instance was running before.")
            print("ssh -i \(keyUrl.path) ec2-user@\(runningInstance!.publicIpAddress!)")
        }

        //=====================================================================
        // 14. Allocate an elastic IP and associate it with the instance
        //     (AllocateAddress and AssociateAddress).
        //=====================================================================

        allocationId = await self.allocateAddress()

        if allocationId == nil {
            await cleanUp()
            return
        }

        associationId = await self.associateAddress(instanceId: instanceId!, allocationId: allocationId)

        if associationId == nil {
            await cleanUp()
            return
        }

        //=====================================================================
        // 15. Display SSH connection info for the connection. Note that the
        //     public IP is now the Elastic IP, which stays constant.
        //=====================================================================

        runningInstance = await self.describeInstance(instanceId: instanceId!)
        if (runningInstance != nil) && (runningInstance!.publicIpAddress != nil) {
            print("\nYou can SSH to this instance using the following command.")
            print("This has changed again, and is now the Elastic IP.")
            print("ssh -i \(keyUrl.path) ec2-user@\(runningInstance!.publicIpAddress!)")
        }

        //=====================================================================
        // Handle all cleanup tasks
        //=====================================================================

        await cleanUp()
    }

    /// Clean up by discarding and closing down all allocated EC2 items:
    /// 
    /// * Elastic IP allocation and association
    /// * Terminate the instance
    /// * Delete the security group
    /// * Delete the key pair
    func cleanUp() async {
        //=====================================================================
        // 16. Disassociate and delete the Elastic IP (DisassociateAddress and
        //     ReleaseAddress).
        //=====================================================================

        if associationId != nil {
            await self.disassociateAddress(associationId: associationId!)
        }

        if allocationId != nil {
            await self.releaseAddress(allocationId: allocationId!)
        }

        //=====================================================================
        // 17. Terminate the instance and wait for it to terminate
        //     (TerminateInstances).
        //=====================================================================

        if instanceId != nil {
            print("Terminating the instance...")
            _ = await self.terminateInstance(instanceId: instanceId!, waitUntilTerminated: true)
        }

        //=====================================================================
        // 18. Delete the security group (DeleteSecurityGroup).
        //=====================================================================

        if securityGroupId != nil {
            print("Deleting the security group...")
            _ = await self.deleteSecurityGroup(groupId: securityGroupId!)
        }

        //=====================================================================
        // 19. Delete the key pair (DeleteKeyPair).
        //=====================================================================

        if keyName != nil {
            print("Deleting the key pair...")
            _ = await self.deleteKeyPair(keyPair: keyName!)
        }
    }

    /// Create a new RSA key pair and save the private key to a randomly-named
    /// file in the temporary directory.
    ///
    /// - Parameter name: The name of the key pair to create.
    ///
    /// - Returns: The URL of the newly created `.pem` file or `nil` if unable
    ///   to create the key pair.
    func createKeyPair(name: String) async -> URL? {
        do {
            let output = try await ec2Client.createKeyPair(
                input: CreateKeyPairInput(
                    keyName: name
                )
            )

            guard let keyMaterial = output.keyMaterial else {
                return nil
            }

            // Build the URL of the temporary private key file.

            let fileURL = URL.temporaryDirectory
                                  .appendingPathComponent(name)
                                  .appendingPathExtension("pem")

            do {
                try keyMaterial.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
                return fileURL
            } catch {
                print("*** Failed to write the private key.")
                return nil
            }
        } catch {
            print("*** Unable to create the key pair.")
            return nil
        }
    }

    /// Describe the key pairs associated with the user by outputting each key
    /// pair's name and fingerprint.
    func describeKeyPairs() async {
        do {
            let output = try await ec2Client.describeKeyPairs(
                input: DescribeKeyPairsInput()
            )

            guard let keyPairs = output.keyPairs else {
                print("*** No key pairs list available.")
                return
            }

            for keyPair in keyPairs {
                print(keyPair.keyName ?? "<unknown>", ":", keyPair.keyFingerprint ?? "<unknown>")
            }
        } catch {
            print("*** Error: Unable to obtain a key pair list.")
        }
    }

    /// Delete an EC2 key pair.
    /// 
    /// - Parameter keyPair: The name of the key pair to delete.
    /// 
    /// - Returns: `true` if the key pair is deleted successfully; otherwise
    ///   `false`.
    func deleteKeyPair(keyPair: String) async -> Bool {
        do {
            _ = try await ec2Client.deleteKeyPair(
                input: DeleteKeyPairInput(
                    keyName: keyPair
                )
            )

            return true
        } catch {
            print("*** Error deleting the key pair: \(error.localizedDescription)")
            return false
        }
    }

    /// Return a list of AMI names that contain the specified string.
    /// 
    /// - Parameter filter: A string that must be contained in all returned
    ///   AMI names.
    ///
    /// - Returns: An array of the parameters matching the specified substring.
    func findAMIsMatchingFilter(_ filter: String) async -> [SSMClientTypes.Parameter] {
        var parameterList: [SSMClientTypes.Parameter] = []
        var matchingAMIs: [SSMClientTypes.Parameter] = []

        do {
            let pages = ssmClient.getParametersByPathPaginated(
                input: GetParametersByPathInput(
                    path: "/aws/service/ami-amazon-linux-latest"
                )
            )

            for try await page in pages {
                guard let parameters = page.parameters else {
                    return matchingAMIs
                }

                for parameter in parameters {
                    parameterList.append(parameter)
                }
            }

            print("Found \(parameterList.count) images total:")
            for parameter in parameterList {
                guard let name = parameter.name else {
                    continue
                }
                print("    \(name)")

                if name.contains(filter) {
                    matchingAMIs.append(parameter)
                }
            }
        } catch {
            return matchingAMIs
        }

        return matchingAMIs
    }

    /// Return a list of instance types matching the specified architecture
    /// and instance sizes.
    /// 
    /// - Parameters:
    ///   - architecture: The architecture of the instance types to return, as
    ///     a member of `EC2ClientTypes.ArchitectureValues`.
    ///   - sizes: An array of one or more strings identifying sizes of
    ///     instance type to accept.
    /// 
    /// - Returns: An array of `EC2ClientTypes.InstanceTypeInfo` records
    ///   describing the instance types matching the given requirements.
    func getMatchingInstanceTypes(architecture: EC2ClientTypes.ArchitectureValues = EC2ClientTypes.ArchitectureValues.x8664,
                          sizes: [String] = ["*.micro", "*.small"]) async
                          -> [EC2ClientTypes.InstanceTypeInfo] {
        var instanceTypes: [EC2ClientTypes.InstanceTypeInfo] = []    

        let archFilter = EC2ClientTypes.Filter(
            name: "processor-info.supported-architecture",
            values: [architecture.rawValue]
        )
        let sizeFilter = EC2ClientTypes.Filter(
            name: "instance-type",
            values: sizes
        )

        do {
            let pages = ec2Client.describeInstanceTypesPaginated(
                input: DescribeInstanceTypesInput(
                    filters: [archFilter, sizeFilter]
                )
            )

            for try await page in pages {
                guard let types = page.instanceTypes else {
                    return []
                }

                instanceTypes += types
            }
        } catch {
            print("*** Error getting image types: \(error.localizedDescription)")
            return []
        }

        return instanceTypes
    }

    /// Get the latest information about the specified instance and output it
    /// to the screen, returning the instance details to the caller.
    /// 
    /// - Parameters:
    ///   - instanceId: The ID of the instance to provide details about.
    ///   - stateFilter: The state to require the instance to be in.
    ///
    /// - Returns: The instance's details as an `EC2ClientTypes.Instance` object.
    func describeInstance(instanceId: String,
                          stateFilter: EC2ClientTypes.InstanceStateName? = EC2ClientTypes.InstanceStateName.running) async
                          -> EC2ClientTypes.Instance? {
        do {
            let pages = ec2Client.describeInstancesPaginated(
                input: DescribeInstancesInput(
                    instanceIds: [instanceId]
                )
            )

            for try await page in pages {
                guard let reservations = page.reservations else {
                    continue
                }

                for reservation in reservations {
                    guard let instances = reservation.instances else {
                        continue
                    }

                    for instance in instances {
                        guard let state = instance.state else {
                            print("*** Instance is missing its state...")
                            continue
                        }
                        let instanceState = state.name

                        if stateFilter != nil && (instanceState != stateFilter) {
                            continue
                        }

                        let instanceTypeName: String
                        if instance.instanceType == nil {
                            instanceTypeName = "<N/A>"
                        } else {
                            instanceTypeName = instance.instanceType?.rawValue ?? "<N/A>"
                        }

                        let instanceStateName: String
                        if instanceState == nil {
                            instanceStateName = "<N/A>"
                        } else {
                            instanceStateName = instanceState?.rawValue ?? "<N/A>"
                        }

                        print("""
                        Instance: \(instance.instanceId ?? "<N/A>")
                                • Image ID: \(instance.imageId ?? "<N/A>")
                                • Instance type: \(instanceTypeName)
                                • Key name: \(instance.keyName ?? "<N/A>")
                                • VPC ID: \(instance.vpcId ?? "<N/A>")
                                • Public IP: \(instance.publicIpAddress ?? "N/A")
                                • State: \(instanceStateName)
                        """)

                        return instance
                    }
                }
            }
        } catch {
            print("*** Error retrieving instance information to display: \(error.localizedDescription)")
            return nil
        }

        return nil
    }

    /// Stop the specified instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The ID of the instance to stop.
    ///   - waitUntilStopped: If `true`, execution waits until the instance
    ///     has stopped. Otherwise, execution continues and the instance stops
    ///     asynchronously.
    ///
    /// - Returns: `true` if the image is successfully stopped (or is left to
    ///   stop asynchronously). `false` if the instance doesn't stop.
    func stopInstance(instanceId: String, waitUntilStopped: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.stopInstances(
                input: StopInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilStopped {
                print("Waiting for the instance to stop. Please be patient!")

                let waitOptions = WaiterOptions(maxWaitTime: 600)
                let output = try await ec2Client.waitUntilInstanceStopped(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )

                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to stop the instance: \(error.localizedDescription)")
            return false
        }
    }

    /// Start the specified instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The ID of the instance to start.
    ///   - waitUntilStarted: If `true`, execution waits until the instance
    ///     has started. Otherwise, execution continues and the instance starts
    ///     asynchronously.
    ///
    /// - Returns: `true` if the image is successfully started (or is left to
    ///   start asynchronously). `false` if the instance doesn't start.
    func startInstance(instanceId: String, waitUntilStarted: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.startInstances(
                input: StartInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilStarted {
                print("Waiting for the instance to start...")

                let waitOptions = WaiterOptions(maxWaitTime: 60.0)
                let output = try await ec2Client.waitUntilInstanceRunning(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )
                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to start the instance: \(error.localizedDescription)")
            return false
        }
    }

    /// Terminate the specified instance.
    ///
    /// - Parameters:
    ///   - instanceId: The instance to terminate.
    ///   - waitUntilTerminated: Whether or not to wait until the instance is
    ///     terminated before returning.
    /// 
    /// - Returns: `true` if terminated successfully. `false` if not or if an
    ///   error occurs.
    func terminateInstance(instanceId: String, waitUntilTerminated: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.terminateInstances(
                input: TerminateInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilTerminated {
                print("Waiting for the instance to terminate...")

                let waitOptions = WaiterOptions(maxWaitTime: 600.0)
                let output = try await ec2Client.waitUntilInstanceTerminated(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )

                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to terminate the instance: \(error.localizedDescription)")
            return false
        }
    }

    /// Return an array of `EC2ClientTypes.Image` objects describing all of
    /// the images in the specified array.
    /// 
    /// - Parameter idList: A list of image ID strings indicating the images
    ///   to return details about.
    ///
    /// - Returns: An array of the images.
    func describeImages(_ idList: [String]) async -> [EC2ClientTypes.Image] {
        do {
            let output = try await ec2Client.describeImages(
                input: DescribeImagesInput(
                    imageIds: idList
                )
            )

            guard let images = output.images else {
                print("*** No images found.")
                return []
            }

            for image in images {
                guard let id = image.imageId else {
                    continue
                }
                print("   \(id): \(image.description ?? "<no description>")")
            }

            return images
        } catch {
            print("*** Error getting image descriptions: \(error.localizedDescription)")
            return []
        }
    }

    /// Create and return a new EC2 instance.
    /// 
    /// - Parameters:
    ///   - imageId: The image ID of the AMI to use when creating the instance.
    ///   - instanceType: The type of instance to create.
    ///   - keyPairName: The RSA key pair's name to use to secure the instance.
    ///   - securityGroups: The security group or groups to add the instance
    ///     to.
    ///
    /// - Returns: The EC2 instance as an `EC2ClientTypes.Instance` object.
    func runInstance(imageId: String, instanceType: EC2ClientTypes.InstanceType,
                        keyPairName: String, securityGroups: [String]?) async -> EC2ClientTypes.Instance? {
        do {
            let output = try await ec2Client.runInstances(
                input: RunInstancesInput(
                    imageId: imageId,
                    instanceType: instanceType,
                    keyName: keyPairName,
                    maxCount: 1,
                    minCount: 1,
                    securityGroupIds: securityGroups
                )
            )

            guard let instances = output.instances else {
                print("*** Unable to create the instance.")
                return nil
            }

            return instances[0]
        } catch {
            print("*** Error creating the instance: \(error.localizedDescription)")
            return nil
        }
    }

    /// Return the device's external IP address.
    /// 
    /// - Returns: A string containing the device's IP address.
    func getMyIPAddress() -> String? {
        guard let url = URL(string: "http://checkip.amazonaws.com") else {
            print("Couldn't create the URL")
            return nil
        }

        do {
            print("Getting the IP address...")
            return try String(contentsOf: url, encoding: String.Encoding.utf8).trim()
        } catch {
            print("*** Unable to get your public IP address.")
            return nil
        }
    }

    /// Create a new security group.
    /// 
    /// - Parameters:
    ///   - groupName: The name of the group to create.
    ///   - groupDescription: A description of the new security group.
    ///
    /// - Returns: The ID string of the new security group.
    func createSecurityGroup(name groupName: String, description groupDescription: String) async -> String? {
        do {
            let output = try await ec2Client.createSecurityGroup(
                input: CreateSecurityGroupInput(
                    description: groupDescription,
                    groupName: groupName
                )
            )

            return output.groupId
        } catch {
            print("*** Error creating the security group: \(error.localizedDescription)")
            return nil
        }
    }

    /// Authorize ingress of connections for the security group.
    /// 
    /// - Parameters:
    ///   - groupId: The group ID of the security group to authorize access for.
    ///   - ipAddress: The IP address of the device to grant access to.
    ///
    /// - Returns: `true` if access is successfully granted; otherwise `false`.
    func authorizeSecurityGroupIngress(groupId: String, ipAddress: String) async -> Bool {
        let ipRange = EC2ClientTypes.IpRange(cidrIp: "\(ipAddress)/0")
        let httpPermission = EC2ClientTypes.IpPermission(
            fromPort: 80,
            ipProtocol: "tcp",
            ipRanges: [ipRange],
            toPort: 80
        )

        let sshPermission = EC2ClientTypes.IpPermission(
            fromPort: 22,
            ipProtocol: "tcp",
            ipRanges: [ipRange],
            toPort: 22
        )

        do {
            _ = try await ec2Client.authorizeSecurityGroupIngress(
                input: AuthorizeSecurityGroupIngressInput(
                    groupId: groupId,
                    ipPermissions: [httpPermission, sshPermission]
                )
            )

            return true
        } catch {
            print("*** Error authorizing ingress for the security group: \(error.localizedDescription)")
            return false
        }
    }

    func describeSecurityGroups(groupId: String) async -> Bool {
        do {
            let output = try await ec2Client.describeSecurityGroups(
                input: DescribeSecurityGroupsInput(
                    groupIds: [groupId]
                )
            )

            guard let securityGroups = output.securityGroups else {
                print("No security groups found.")
                return true
            }

            for group in securityGroups {
                print("Group \(group.groupId ?? "<unknown>") found with VPC \(group.vpcId ?? "<unknown>")")
            }
            return true
        } catch {
            print("*** Error getting security group details: \(error.localizedDescription)")
            return false
        }
    }

    /// Delete a security group.
    /// 
    /// - Parameter groupId: The ID of the security group to delete.
    /// 
    /// - Returns: `true` on successful deletion; `false` on error.
    func deleteSecurityGroup(groupId: String) async -> Bool {
        do {
            _ = try await ec2Client.deleteSecurityGroup(
                input: DeleteSecurityGroupInput(
                    groupId: groupId
                )
            )

            return true
        } catch {
            print("*** Error deleting the security group: \(error.localizedDescription)")
            return false
        }
    }

    /// Allocate an Elastic IP address.
    ///
    /// - Returns: A string containing the ID of the Elastic IP.
    func allocateAddress() async -> String? {
        do {
            let output = try await ec2Client.allocateAddress(
                input: AllocateAddressInput(
                    domain: EC2ClientTypes.DomainType.vpc
                )
            )

            guard let allocationId = output.allocationId else {
                return nil
            }

            return allocationId
        } catch {
            print("*** Unable to allocate the IP address: \(error.localizedDescription)")
            return nil
        }
    }

    /// Associate the specified allocated Elastic IP to a given instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The instance to associate the Elastic IP with.
    ///   - allocationId: The ID of the allocated Elastic IP to associate with
    ///     the instance.
    ///
    /// - Returns: The association ID of the association.
    func associateAddress(instanceId: String?, allocationId: String?) async -> String? {
        do {
            let output = try await ec2Client.associateAddress(
                input: AssociateAddressInput(
                    allocationId: allocationId,
                    instanceId: instanceId
                )
            )

            return output.associationId
        } catch {
            print("*** Unable to associate the IP address: \(error.localizedDescription)")
            return nil
        }
    }

    /// Disassociate an Elastic IP.
    /// 
    /// - Parameter associationId: The ID of the association to end.
    func disassociateAddress(associationId: String?) async {
        do {
            _ = try await ec2Client.disassociateAddress(
                input: DisassociateAddressInput(
                    associationId: associationId
                )
            )
        } catch {
            print("*** Unable to disassociate the IP address: \(error.localizedDescription)")
        }
    }

    /// Release an allocated Elastic IP.
    /// 
    /// - Parameter allocationId: The allocation ID of the Elastic IP to
    ///   release.
    func releaseAddress(allocationId: String?) async {
        do {
            _ = try await ec2Client.releaseAddress(
                input: ReleaseAddressInput(
                    allocationId: allocationId
                )
            )
        } catch {
            print("*** Unable to release the IP address: \(error.localizedDescription)")
        }
    }

    /// Generate and return a unique file name that begins with the specified
    /// string.
    ///
    /// - Parameters:
    ///   - prefix: Text to use at the beginning of the returned name.
    ///
    /// - Returns: A string containing a unique filename that begins with the
    ///   specified `prefix`.
    ///
    /// The returned name uses a random number between 1 million and 1 billion to
    /// provide reasonable certainty of uniqueness for the purposes of this
    /// example.
    func tempName(prefix: String) -> String {
        return "\(prefix)-\(Int.random(in: 1000000..<1000000000))"
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [AllocateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/allocateaddress(input:))
  + [AssociateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/associateaddress(input:))
  + [AuthorizeSecurityGroupIngress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/authorizesecuritygroupingress(input:))
  + [CreateKeyPair](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/createkeypair(input:))
  + [CreateSecurityGroup](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/createsecuritygroup(input:))
  + [DeleteKeyPair](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/deletekeypair(input:))
  + [DeleteSecurityGroup](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/deletesecuritygroup(input:))
  + [DescribeImages](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describeimages(input:))
  + [DescribeInstanceTypes](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describeinstancetypes(input:))
  + [DescribeInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describeinstances(input:))
  + [DescribeKeyPairs](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describekeypairs(input:))
  + [DescribeSecurityGroups](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describesecuritygroups(input:))
  + [DisassociateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/disassociateaddress(input:))
  + [ReleaseAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/releaseaddress(input:))
  + [RunInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/runinstances(input:))
  + [StartInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/startinstances(input:))
  + [StopInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/stopinstances(input:))
  + [TerminateInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/terminateinstances(input:))
  + [UnmonitorInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/unmonitorinstances(input:))

## アクション
<a name="actions"></a>

### `AllocateAddress`
<a name="ec2_AllocateAddress_swift_1_topic"></a>

次のコード例は、`AllocateAddress` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Allocate an Elastic IP address.
    ///
    /// - Returns: A string containing the ID of the Elastic IP.
    func allocateAddress() async -> String? {
        do {
            let output = try await ec2Client.allocateAddress(
                input: AllocateAddressInput(
                    domain: EC2ClientTypes.DomainType.vpc
                )
            )

            guard let allocationId = output.allocationId else {
                return nil
            }

            return allocationId
        } catch {
            print("*** Unable to allocate the IP address: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[AllocateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/allocateaddress(input:))」を参照してください。**

### `AssociateAddress`
<a name="ec2_AssociateAddress_swift_1_topic"></a>

次のコード例は、`AssociateAddress` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Associate the specified allocated Elastic IP to a given instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The instance to associate the Elastic IP with.
    ///   - allocationId: The ID of the allocated Elastic IP to associate with
    ///     the instance.
    ///
    /// - Returns: The association ID of the association.
    func associateAddress(instanceId: String?, allocationId: String?) async -> String? {
        do {
            let output = try await ec2Client.associateAddress(
                input: AssociateAddressInput(
                    allocationId: allocationId,
                    instanceId: instanceId
                )
            )

            return output.associationId
        } catch {
            print("*** Unable to associate the IP address: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[AssociateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/associateaddress(input:))」を参照してください。**

### `AuthorizeSecurityGroupIngress`
<a name="ec2_AuthorizeSecurityGroupIngress_swift_1_topic"></a>

次のコード例は、`AuthorizeSecurityGroupIngress` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Authorize ingress of connections for the security group.
    /// 
    /// - Parameters:
    ///   - groupId: The group ID of the security group to authorize access for.
    ///   - ipAddress: The IP address of the device to grant access to.
    ///
    /// - Returns: `true` if access is successfully granted; otherwise `false`.
    func authorizeSecurityGroupIngress(groupId: String, ipAddress: String) async -> Bool {
        let ipRange = EC2ClientTypes.IpRange(cidrIp: "\(ipAddress)/0")
        let httpPermission = EC2ClientTypes.IpPermission(
            fromPort: 80,
            ipProtocol: "tcp",
            ipRanges: [ipRange],
            toPort: 80
        )

        let sshPermission = EC2ClientTypes.IpPermission(
            fromPort: 22,
            ipProtocol: "tcp",
            ipRanges: [ipRange],
            toPort: 22
        )

        do {
            _ = try await ec2Client.authorizeSecurityGroupIngress(
                input: AuthorizeSecurityGroupIngressInput(
                    groupId: groupId,
                    ipPermissions: [httpPermission, sshPermission]
                )
            )

            return true
        } catch {
            print("*** Error authorizing ingress for the security group: \(error.localizedDescription)")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[AuthorizeSecurityGroupIngress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/authorizesecuritygroupingress(input:))」を参照してください。**

### `CreateKeyPair`
<a name="ec2_CreateKeyPair_swift_1_topic"></a>

次のコード例は、`CreateKeyPair` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Create a new RSA key pair and save the private key to a randomly-named
    /// file in the temporary directory.
    ///
    /// - Parameter name: The name of the key pair to create.
    ///
    /// - Returns: The URL of the newly created `.pem` file or `nil` if unable
    ///   to create the key pair.
    func createKeyPair(name: String) async -> URL? {
        do {
            let output = try await ec2Client.createKeyPair(
                input: CreateKeyPairInput(
                    keyName: name
                )
            )

            guard let keyMaterial = output.keyMaterial else {
                return nil
            }

            // Build the URL of the temporary private key file.

            let fileURL = URL.temporaryDirectory
                                  .appendingPathComponent(name)
                                  .appendingPathExtension("pem")

            do {
                try keyMaterial.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
                return fileURL
            } catch {
                print("*** Failed to write the private key.")
                return nil
            }
        } catch {
            print("*** Unable to create the key pair.")
            return nil
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[CreateKeyPair](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/createkeypair(input:))」を参照してください。**

### `CreateSecurityGroup`
<a name="ec2_CreateSecurityGroup_swift_1_topic"></a>

次のコード例は、`CreateSecurityGroup` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Create a new security group.
    /// 
    /// - Parameters:
    ///   - groupName: The name of the group to create.
    ///   - groupDescription: A description of the new security group.
    ///
    /// - Returns: The ID string of the new security group.
    func createSecurityGroup(name groupName: String, description groupDescription: String) async -> String? {
        do {
            let output = try await ec2Client.createSecurityGroup(
                input: CreateSecurityGroupInput(
                    description: groupDescription,
                    groupName: groupName
                )
            )

            return output.groupId
        } catch {
            print("*** Error creating the security group: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[CreateSecurityGroup](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/createsecuritygroup(input:))」を参照してください。**

### `DeleteKeyPair`
<a name="ec2_DeleteKeyPair_swift_1_topic"></a>

次のコード例は、`DeleteKeyPair` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Delete an EC2 key pair.
    /// 
    /// - Parameter keyPair: The name of the key pair to delete.
    /// 
    /// - Returns: `true` if the key pair is deleted successfully; otherwise
    ///   `false`.
    func deleteKeyPair(keyPair: String) async -> Bool {
        do {
            _ = try await ec2Client.deleteKeyPair(
                input: DeleteKeyPairInput(
                    keyName: keyPair
                )
            )

            return true
        } catch {
            print("*** Error deleting the key pair: \(error.localizedDescription)")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DeleteKeyPair](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/deletekeypair(input:))」を参照してください。**

### `DeleteSecurityGroup`
<a name="ec2_DeleteSecurityGroup_swift_1_topic"></a>

次のコード例は、`DeleteSecurityGroup` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Delete a security group.
    /// 
    /// - Parameter groupId: The ID of the security group to delete.
    /// 
    /// - Returns: `true` on successful deletion; `false` on error.
    func deleteSecurityGroup(groupId: String) async -> Bool {
        do {
            _ = try await ec2Client.deleteSecurityGroup(
                input: DeleteSecurityGroupInput(
                    groupId: groupId
                )
            )

            return true
        } catch {
            print("*** Error deleting the security group: \(error.localizedDescription)")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DeleteSecurityGroup](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/deletesecuritygroup(input:))」を参照してください。**

### `DescribeImages`
<a name="ec2_DescribeImages_swift_1_topic"></a>

次のコード例は、`DescribeImages` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Return an array of `EC2ClientTypes.Image` objects describing all of
    /// the images in the specified array.
    /// 
    /// - Parameter idList: A list of image ID strings indicating the images
    ///   to return details about.
    ///
    /// - Returns: An array of the images.
    func describeImages(_ idList: [String]) async -> [EC2ClientTypes.Image] {
        do {
            let output = try await ec2Client.describeImages(
                input: DescribeImagesInput(
                    imageIds: idList
                )
            )

            guard let images = output.images else {
                print("*** No images found.")
                return []
            }

            for image in images {
                guard let id = image.imageId else {
                    continue
                }
                print("   \(id): \(image.description ?? "<no description>")")
            }

            return images
        } catch {
            print("*** Error getting image descriptions: \(error.localizedDescription)")
            return []
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DescribeImages](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describeimages(input:))」を参照してください。**

### `DescribeInstanceTypes`
<a name="ec2_DescribeInstanceTypes_swift_1_topic"></a>

次のコード例は、`DescribeInstanceTypes` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Return a list of instance types matching the specified architecture
    /// and instance sizes.
    /// 
    /// - Parameters:
    ///   - architecture: The architecture of the instance types to return, as
    ///     a member of `EC2ClientTypes.ArchitectureValues`.
    ///   - sizes: An array of one or more strings identifying sizes of
    ///     instance type to accept.
    /// 
    /// - Returns: An array of `EC2ClientTypes.InstanceTypeInfo` records
    ///   describing the instance types matching the given requirements.
    func getMatchingInstanceTypes(architecture: EC2ClientTypes.ArchitectureValues = EC2ClientTypes.ArchitectureValues.x8664,
                          sizes: [String] = ["*.micro", "*.small"]) async
                          -> [EC2ClientTypes.InstanceTypeInfo] {
        var instanceTypes: [EC2ClientTypes.InstanceTypeInfo] = []    

        let archFilter = EC2ClientTypes.Filter(
            name: "processor-info.supported-architecture",
            values: [architecture.rawValue]
        )
        let sizeFilter = EC2ClientTypes.Filter(
            name: "instance-type",
            values: sizes
        )

        do {
            let pages = ec2Client.describeInstanceTypesPaginated(
                input: DescribeInstanceTypesInput(
                    filters: [archFilter, sizeFilter]
                )
            )

            for try await page in pages {
                guard let types = page.instanceTypes else {
                    return []
                }

                instanceTypes += types
            }
        } catch {
            print("*** Error getting image types: \(error.localizedDescription)")
            return []
        }

        return instanceTypes
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DescribeInstanceTypes](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describeinstancetypes(input:))」を参照してください。**

### `DescribeKeyPairs`
<a name="ec2_DescribeKeyPairs_swift_1_topic"></a>

次のコード例は、`DescribeKeyPairs` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Describe the key pairs associated with the user by outputting each key
    /// pair's name and fingerprint.
    func describeKeyPairs() async {
        do {
            let output = try await ec2Client.describeKeyPairs(
                input: DescribeKeyPairsInput()
            )

            guard let keyPairs = output.keyPairs else {
                print("*** No key pairs list available.")
                return
            }

            for keyPair in keyPairs {
                print(keyPair.keyName ?? "<unknown>", ":", keyPair.keyFingerprint ?? "<unknown>")
            }
        } catch {
            print("*** Error: Unable to obtain a key pair list.")
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DescribeKeyPairs](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describekeypairs(input:))」を参照してください。**

### `DescribeSecurityGroups`
<a name="ec2_DescribeSecurityGroups_swift_1_topic"></a>

次のコード例は、`DescribeSecurityGroups` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。
`describeSecurityGroupsPaginated()` を使ったページ分割の使用。  

```
import AWSEC2

    /// Return an array of strings giving the names of every security group
    /// the user is a member of.
    ///
    /// - Parameter ec2Client: The `EC2Client` to use when calling
    ///   `describeSecurityGroupsPaginated()`.
    ///
    /// - Returns: An array of strings giving the names of every security
    ///   group the user is a member of.
    func getSecurityGroupNames(ec2Client: EC2Client) async -> [String] {
        let pages = ec2Client.describeSecurityGroupsPaginated(
            input: DescribeSecurityGroupsInput()
        )

        var groupNames: [String] = []

        do {
            for try await page in pages {
                guard let groups = page.securityGroups else {
                    print("*** Error: No groups returned.")
                    continue
                }

                for group in groups {
                    groupNames.append(group.groupName ?? "<unknown>")
                }
            }
        } catch {
            print("*** Error: \(error.localizedDescription)")
        }

        return groupNames
    }
```
ページ分割なし。  

```
import AWSEC2

    func describeSecurityGroups(groupId: String) async -> Bool {
        do {
            let output = try await ec2Client.describeSecurityGroups(
                input: DescribeSecurityGroupsInput(
                    groupIds: [groupId]
                )
            )

            guard let securityGroups = output.securityGroups else {
                print("No security groups found.")
                return true
            }

            for group in securityGroups {
                print("Group \(group.groupId ?? "<unknown>") found with VPC \(group.vpcId ?? "<unknown>")")
            }
            return true
        } catch {
            print("*** Error getting security group details: \(error.localizedDescription)")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DescribeSecurityGroups](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/describesecuritygroups(input:))」を参照してください。**

### `DisassociateAddress`
<a name="ec2_DisassociateAddress_swift_1_topic"></a>

次のコード例は、`DisassociateAddress` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Disassociate an Elastic IP.
    /// 
    /// - Parameter associationId: The ID of the association to end.
    func disassociateAddress(associationId: String?) async {
        do {
            _ = try await ec2Client.disassociateAddress(
                input: DisassociateAddressInput(
                    associationId: associationId
                )
            )
        } catch {
            print("*** Unable to disassociate the IP address: \(error.localizedDescription)")
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DisassociateAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/disassociateaddress(input:))」を参照してください。**

### `ReleaseAddress`
<a name="ec2_ReleaseAddress_swift_1_topic"></a>

次のコード例は、`ReleaseAddress` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Release an allocated Elastic IP.
    /// 
    /// - Parameter allocationId: The allocation ID of the Elastic IP to
    ///   release.
    func releaseAddress(allocationId: String?) async {
        do {
            _ = try await ec2Client.releaseAddress(
                input: ReleaseAddressInput(
                    allocationId: allocationId
                )
            )
        } catch {
            print("*** Unable to release the IP address: \(error.localizedDescription)")
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ReleaseAddress](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/releaseaddress(input:))」を参照してください。**

### `RunInstances`
<a name="ec2_RunInstances_swift_1_topic"></a>

次のコード例は、`RunInstances` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Create and return a new EC2 instance.
    /// 
    /// - Parameters:
    ///   - imageId: The image ID of the AMI to use when creating the instance.
    ///   - instanceType: The type of instance to create.
    ///   - keyPairName: The RSA key pair's name to use to secure the instance.
    ///   - securityGroups: The security group or groups to add the instance
    ///     to.
    ///
    /// - Returns: The EC2 instance as an `EC2ClientTypes.Instance` object.
    func runInstance(imageId: String, instanceType: EC2ClientTypes.InstanceType,
                        keyPairName: String, securityGroups: [String]?) async -> EC2ClientTypes.Instance? {
        do {
            let output = try await ec2Client.runInstances(
                input: RunInstancesInput(
                    imageId: imageId,
                    instanceType: instanceType,
                    keyName: keyPairName,
                    maxCount: 1,
                    minCount: 1,
                    securityGroupIds: securityGroups
                )
            )

            guard let instances = output.instances else {
                print("*** Unable to create the instance.")
                return nil
            }

            return instances[0]
        } catch {
            print("*** Error creating the instance: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[RunInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/runinstances(input:))」を参照してください。**

### `StartInstances`
<a name="ec2_StartInstances_swift_1_topic"></a>

次のコード例は、`StartInstances` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Start the specified instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The ID of the instance to start.
    ///   - waitUntilStarted: If `true`, execution waits until the instance
    ///     has started. Otherwise, execution continues and the instance starts
    ///     asynchronously.
    ///
    /// - Returns: `true` if the image is successfully started (or is left to
    ///   start asynchronously). `false` if the instance doesn't start.
    func startInstance(instanceId: String, waitUntilStarted: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.startInstances(
                input: StartInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilStarted {
                print("Waiting for the instance to start...")

                let waitOptions = WaiterOptions(maxWaitTime: 60.0)
                let output = try await ec2Client.waitUntilInstanceRunning(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )
                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to start the instance: \(error.localizedDescription)")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[StartInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/startinstances(input:))」を参照してください。**

### `StopInstances`
<a name="ec2_StopInstances_swift_1_topic"></a>

次のコード例は、`StopInstances` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Stop the specified instance.
    /// 
    /// - Parameters:
    ///   - instanceId: The ID of the instance to stop.
    ///   - waitUntilStopped: If `true`, execution waits until the instance
    ///     has stopped. Otherwise, execution continues and the instance stops
    ///     asynchronously.
    ///
    /// - Returns: `true` if the image is successfully stopped (or is left to
    ///   stop asynchronously). `false` if the instance doesn't stop.
    func stopInstance(instanceId: String, waitUntilStopped: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.stopInstances(
                input: StopInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilStopped {
                print("Waiting for the instance to stop. Please be patient!")

                let waitOptions = WaiterOptions(maxWaitTime: 600)
                let output = try await ec2Client.waitUntilInstanceStopped(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )

                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to stop the instance: \(error.localizedDescription)")
            return false
        }
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[StopInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/stopinstances(input:))」を参照してください。**

### `TerminateInstances`
<a name="ec2_TerminateInstances_swift_1_topic"></a>

次のコード例は、`TerminateInstances` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/ec2#code-examples)での設定と実行の方法を確認してください。

```
import AWSEC2

    /// Terminate the specified instance.
    ///
    /// - Parameters:
    ///   - instanceId: The instance to terminate.
    ///   - waitUntilTerminated: Whether or not to wait until the instance is
    ///     terminated before returning.
    /// 
    /// - Returns: `true` if terminated successfully. `false` if not or if an
    ///   error occurs.
    func terminateInstance(instanceId: String, waitUntilTerminated: Bool = false) async -> Bool {
        let instanceList = [instanceId]

        do {
            _ = try await ec2Client.terminateInstances(
                input: TerminateInstancesInput(
                    instanceIds: instanceList
                )
            )

            if waitUntilTerminated {
                print("Waiting for the instance to terminate...")

                let waitOptions = WaiterOptions(maxWaitTime: 600.0)
                let output = try await ec2Client.waitUntilInstanceTerminated(
                    options: waitOptions,
                    input: DescribeInstancesInput(
                        instanceIds: instanceList
                    )
                )

                switch output.result {
                case .success:
                    return true
                case .failure:
                    return false
                }
            } else {
                return true
            }
        } catch {
            print("*** Unable to terminate the instance: \(error.localizedDescription)")
            return false
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[TerminateInstances](https://sdk.amazonaws.com/swift/api/awsec2/latest/documentation/awsec2/ec2client/terminateinstances(input:))」を参照してください。

# AWS Glue SDK for Swift を使用した の例
<a name="swift_1_glue_code_examples"></a>

次のコード例は、 で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS Glue。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="glue_Scenario_GetStartedCrawlersJobs_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ パブリック Amazon S3 バケットをクロールし、CSV 形式のメタデータのデータベースを生成するクローラーを作成します。
+ のデータベースとテーブルに関する情報を一覧表示します AWS Glue Data Catalog。
+ S3 バケットから CSV 形式のデータを抽出するジョブを作成し、そのデータを変換して JSON 形式の出力を別の S3 バケットにロードする。
+ ジョブ実行に関する情報を一覧表示し、変換されたデータを表示してリソースをクリーンアップします。

詳細については、[「チュートリアル: AWS Glue Studio の開始方法](https://docs.aws.amazon.com/glue/latest/ug/tutorial-create-job.html)」を参照してください。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。
`Package.swift` ファイル。  

```
// swift-tools-version: 5.9
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "glue-scenario",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13),
        .iOS(.v15)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.0.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "glue-scenario",
            dependencies: [
                .product(name: "AWSGlue", package: "aws-sdk-swift"),
                .product(name: "AWSS3", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources")

    ]
)
```
Swift コードファイル、`entry.swift`。  

```
// An example that shows how to use the AWS SDK for Swift to demonstrate
// creating and using crawlers and jobs using AWS Glue.
//
// 0. Upload the Python job script to Amazon S3 so it can be used when
//    calling `startJobRun()` later.
// 1. Create a crawler, pass it the IAM role and the URL of the public Amazon
//    S3 bucket that contains the source data:
//    s3://crawler-public-us-east-1/flight/2016/csv.
// 2. Start the crawler. This takes time, so after starting it, use a loop
//    that calls `getCrawler()` until the state is "READY".
// 3. Get the database created by the crawler, and the tables in the
//    database. Display them to the user.
// 4. Create a job. Pass it the IAM role and the URL to a Python ETL script
//    previously uploaded to the user's S3 bucket.
// 5. Start a job run, passing the following custom arguments. These are
//    expected by the ETL script, so must exactly match.
//    * `--input_database: <name of the database created by the crawler>`
//    * `--input_table: <name of the table created by the crawler>`
//    * `--output_bucket_url: <URL to the scaffold bucket created for the
//      user>`
// 6. Loop and get the job run until it returns one of the following states:
//    "SUCCEEDED", "STOPPED", "FAILED", or "TIMEOUT".
// 7. Output data is stored in a group of files in the user's S3 bucket.
//    Either direct the user to their location or download a file and display
//    the results inline.
// 8. List the jobs for the user's account.
// 9. Get job run details for a job run.
// 10. Delete the demo job.
// 11. Delete the database and tables created by the example.
// 12. Delete the crawler created by the example.

import ArgumentParser
import AWSS3
import Foundation
import Smithy

import AWSClientRuntime
import AWSGlue

struct ExampleCommand: ParsableCommand {
    @Option(help: "The AWS IAM role to use for AWS Glue calls.")
    var role: String

    @Option(help: "The Amazon S3 bucket to use for this example.")
    var bucket: String

    @Option(help: "The Amazon S3 URL of the data to crawl.")
    var s3url: String = "s3://crawler-public-us-east-1/flight/2016/csv"

    @Option(help: "The Python script to run as a job with AWS Glue.")
    var script: String = "./flight_etl_job_script.py"

    @Option(help: "The AWS Region to run AWS API calls in.")
    var awsRegion = "us-east-1"

    @Option(help: "A prefix string to use when naming tables.")
    var tablePrefix = "swift-glue-basics-table"

    @Option(
        help: ArgumentHelp("The level of logging for the Swift SDK to perform."),
        completion: .list([
            "critical",
            "debug",
            "error",
            "info",
            "notice",
            "trace",
            "warning"
        ])
    )
    var logLevel: String = "error"

    static var configuration = CommandConfiguration(
        commandName: "glue-scenario",
        abstract: """
        Demonstrates various features of AWS Glue.
        """,
        discussion: """
        An example showing how to use AWS Glue to create, run, and monitor
        crawlers and jobs.
        """
    )

    /// Generate and return a unique file name that begins with the specified
    /// string.
    ///
    /// - Parameters:
    ///   - prefix: Text to use at the beginning of the returned name.
    ///
    /// - Returns: A string containing a unique filename that begins with the
    ///   specified `prefix`.
    ///
    /// The returned name uses a random number between 1 million and 1 billion to
    /// provide reasonable certainty of uniqueness for the purposes of this
    /// example.
    func tempName(prefix: String) -> String {
        return "\(prefix)-\(Int.random(in: 1000000..<1000000000))"
    }

    /// Upload a file to an Amazon S3 bucket.
    /// 
    /// - Parameters:
    ///   - s3Client: The S3 client to use when uploading the file.
    ///   - path: The local path of the source file to upload.
    ///   - toBucket: The name of the S3 bucket into which to upload the file.
    ///   - key: The key (name) to give the file in the S3 bucket.
    ///
    /// - Returns: `true` if the file is uploaded successfully, otherwise `false`.
    func uploadFile(s3Client: S3Client, path: String, toBucket: String, key: String) async -> Bool {
        do {
            let fileData: Data = try Data(contentsOf: URL(fileURLWithPath: path))
            let dataStream = ByteStream.data(fileData)
            _ = try await s3Client.putObject(
                input: PutObjectInput(
                    body: dataStream,
                    bucket: toBucket,
                    key: key
                )
            )
        } catch {
            print("*** An unexpected error occurred uploading the script to the Amazon S3 bucket \"\(bucket)\".")
            return false
        }

        return true
    }

    /// Create a new AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: An AWS Glue client to use for the crawler.
    ///   - crawlerName: A name for the new crawler.
    ///   - iamRole: The name of an Amazon IAM role for the crawler to use.
    ///   - s3Path: The path of an Amazon S3 folder to use as a target location.
    ///   - cronSchedule: A `cron` schedule indicating when to run the crawler.
    ///   - databaseName: The name of an AWS Glue database to operate on.
    ///
    /// - Returns: `true` if the crawler is created successfully, otherwise `false`.
    func createCrawler(glueClient: GlueClient, crawlerName: String, iamRole: String,
                       s3Path: String, cronSchedule: String, databaseName: String) async -> Bool {
        let s3Target = GlueClientTypes.S3Target(path: s3url)
        let targetList = GlueClientTypes.CrawlerTargets(s3Targets: [s3Target])

        do {
            _ = try await glueClient.createCrawler(
                input: CreateCrawlerInput(
                    databaseName: databaseName,
                    description: "Created by the AWS SDK for Swift Scenario Example for AWS Glue.",
                    name: crawlerName,
                    role: iamRole,
                    schedule: cronSchedule,
                    tablePrefix: tablePrefix,
                    targets: targetList
                )
            )
        } catch _ as AlreadyExistsException {
            print("*** A crawler named \"\(crawlerName)\" already exists.")
            return false
        } catch _ as OperationTimeoutException {
            print("*** The attempt to create the AWS Glue crawler timed out.")
            return false
        } catch {
            print("*** An unexpected error occurred creating the AWS Glue crawler: \(error.localizedDescription)")
            return false
        }

        return true
    }

    /// Delete an AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - name: The name of the crawler to delete.
    ///
    /// - Returns: `true` if successful, otherwise `false`.
    func deleteCrawler(glueClient: GlueClient, name: String) async -> Bool {
        do {
            _ = try await glueClient.deleteCrawler(
                input: DeleteCrawlerInput(name: name)
            )
        } catch {
            return false
        }
        return true
    }

    /// Start running an AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use when starting the crawler.
    ///   - name: The name of the crawler to start running.
    ///
    /// - Returns: `true` if the crawler is started successfully, otherwise `false`.
    func startCrawler(glueClient: GlueClient, name: String) async -> Bool {
        do {
            _ = try await glueClient.startCrawler(
                input: StartCrawlerInput(name: name)
            )
        } catch {
            print("*** An unexpected error occurred starting the crawler.")
            return false
        }

        return true
    }

    /// Get the state of the specified AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - name: The name of the crawler whose state should be returned.
    ///
    /// - Returns: A `GlueClientTypes.CrawlerState` value describing the
    ///   state of the crawler.
    func getCrawlerState(glueClient: GlueClient, name: String) async -> GlueClientTypes.CrawlerState {
        do {
            let output = try await glueClient.getCrawler(
                input: GetCrawlerInput(name: name)
            )

            // If the crawler or its state is `nil`, report that the crawler
            // is stopping. This may not be what you want for your
            // application but it works for this one!
            
            guard let crawler = output.crawler else {
                return GlueClientTypes.CrawlerState.stopping
            }
            guard let state = crawler.state else {
                return GlueClientTypes.CrawlerState.stopping            
            }
            return state
        } catch {
            return GlueClientTypes.CrawlerState.stopping
        }
    }

    /// Wait until the specified crawler is ready to run.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - name: The name of the crawler to wait for.
    ///
    /// - Returns: `true` if the crawler is ready, `false` if the client is
    ///   stopping (and will therefore never be ready).
    func waitUntilCrawlerReady(glueClient: GlueClient, name: String) async -> Bool {
        while true {
            let state = await getCrawlerState(glueClient: glueClient, name: name)

            if state == .ready {
                return true
            } else if state == .stopping {
                return false
            }
            
            // Wait four seconds before trying again.

            do {
                try await Task.sleep(for: .seconds(4))
            } catch {
                print("*** Error pausing the task.")
            }
        }
    }

    /// Create a new AWS Glue job.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name to give the new job.
    ///   - role: The IAM role for the job to use when accessing AWS services.
    ///   - scriptLocation: The AWS S3 URI of the script to be run by the job.
    /// 
    /// - Returns: `true` if the job is created successfully, otherwise `false`.
    func createJob(glueClient: GlueClient, name jobName: String, role: String,
                   scriptLocation: String) async -> Bool {
        let command = GlueClientTypes.JobCommand(
            name: "glueetl",
            pythonVersion: "3",
            scriptLocation: scriptLocation
        )

        do {
            _ = try await glueClient.createJob(
                input: CreateJobInput(
                    command: command,
                    description: "Created by the AWS SDK for Swift Glue basic scenario example.",
                    glueVersion: "3.0",
                    name: jobName,
                    numberOfWorkers: 10,
                    role: role,
                    workerType: .g1x
                )
            )
        } catch {
            return false
        }
        return true
    }

    /// Return a list of the AWS Glue jobs listed on the user's account.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - maxJobs: The maximum number of jobs to return (default: 100).
    /// 
    /// - Returns: An array of strings listing the names of all available AWS
    ///   Glue jobs.
    func listJobs(glueClient: GlueClient, maxJobs: Int = 100) async -> [String] {
        var jobList: [String] = []
        var nextToken: String?

        repeat {
            do {
                let output = try await glueClient.listJobs(
                    input: ListJobsInput(
                        maxResults: maxJobs,
                        nextToken: nextToken
                    )
                )

                guard let jobs = output.jobNames else {
                    return jobList
                }

                jobList = jobList + jobs
                nextToken = output.nextToken
            } catch {
                return jobList
            }
        } while (nextToken != nil)

        return jobList
    }

    /// Delete an AWS Glue job.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job to delete.
    ///
    /// - Returns: `true` if the job is successfully deleted, otherwise `false`.
    func deleteJob(glueClient: GlueClient, name jobName: String) async -> Bool {
        do {
            _ = try await glueClient.deleteJob(
                input: DeleteJobInput(jobName: jobName)
            )
        } catch {
            return false
        }
        return true
    }

    /// Create an AWS Glue database.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - databaseName: The name to give the new database.
    ///   - location: The URL of the source data to use with AWS Glue.
    ///
    /// - Returns: `true` if the database is created successfully, otherwise `false`.
    func createDatabase(glueClient: GlueClient, name databaseName: String, location: String) async -> Bool {
        let databaseInput = GlueClientTypes.DatabaseInput(
            description: "Created by the AWS SDK for Swift Glue basic scenario example.",
            locationUri: location,
            name: databaseName
        )

        do {
            _ = try await glueClient.createDatabase(
                input: CreateDatabaseInput(
                    databaseInput: databaseInput
                )
            )
        } catch {
            return false
        }

        return true
    }

    /// Get the AWS Glue database with the specified name.
    ///
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - name: The name of the database to return.
    ///
    /// - Returns: The `GlueClientTypes.Database` object describing the
    ///   specified database, or `nil` if an error occurs or the database
    ///   isn't found.
    func getDatabase(glueClient: GlueClient, name: String) async -> GlueClientTypes.Database? {
        do {
            let output = try await glueClient.getDatabase(
                input: GetDatabaseInput(name: name)
            )

            return output.database
        } catch {
            return nil
        }
    }

    /// Returns a list of the tables in the specified database.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - databaseName: The name of the database whose tables are to be
    ///     returned.
    ///
    /// - Returns: An array of `GlueClientTypes.Table` objects, each
    ///   describing one table in the named database. An empty array indicates
    ///   that there are either no tables in the database, or an error
    ///   occurred before any tables could be found.
    func getTablesInDatabase(glueClient: GlueClient, databaseName: String) async -> [GlueClientTypes.Table] {
        var tables: [GlueClientTypes.Table] = []
        var nextToken: String?

        repeat {
            do {
                let output = try await glueClient.getTables(
                    input: GetTablesInput(
                        databaseName: databaseName,
                        nextToken: nextToken
                    )
                )

                guard let tableList = output.tableList else {
                    return tables
                }

                tables = tables + tableList
                nextToken = output.nextToken
            } catch {
                return tables
            }
        } while nextToken != nil

        return tables
    }

    /// Delete the specified database.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - databaseName: The name of the database to delete.
    ///   - deleteTables: A Bool indicating whether or not to delete the
    ///     tables in the database before attempting to delete the database.
    /// 
    /// - Returns: `true` if the database (and optionally its tables) are
    ///   deleted, otherwise `false`.
    func deleteDatabase(glueClient: GlueClient, name databaseName: String,
                        withTables deleteTables: Bool = false) async -> Bool {
        if deleteTables {
            var tableNames: [String] = []

            // Get a list of the names of all of the tables in the database.

            let tableList = await self.getTablesInDatabase(glueClient: glueClient, databaseName: databaseName)
            for table in tableList {
                guard let name = table.name else {
                    continue
                }
                tableNames.append(name)
            }

            // Delete the tables. If there's only one table, use
            // `deleteTable()`, otherwise, use `batchDeleteTable()`. You can
            // use `batchDeleteTable()` for a single table, but this
            // demonstrates the use of `deleteTable()`.

            if tableNames.count == 1 {
                do {
                    print("    Deleting table...")
                    _ = try await glueClient.deleteTable(
                        input: DeleteTableInput(
                            databaseName: databaseName,
                            name: tableNames[0]
                        )
                    )
                } catch {
                    print("*** Unable to delete the table.")
                }
            } else {
                do {
                    print("    Deleting tables...")
                    _ = try await glueClient.batchDeleteTable(
                        input: BatchDeleteTableInput(
                            databaseName: databaseName,
                            tablesToDelete: tableNames
                        )
                    )
                } catch {
                    print("*** Unable to delete the tables.")
                }
            }
        }

        // Delete the database itself.

        do {
            print("    Deleting the database itself...")
            _ = try await glueClient.deleteDatabase(
                input: DeleteDatabaseInput(name: databaseName)
            )
        } catch {
            print("*** Unable to delete the database.")
            return false
        }
        return true
    }

    /// Start an AWS Glue job run.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job to run.
    ///   - databaseName: The name of the AWS Glue database to run the job against.
    ///   - tableName: The name of the table in the database to run the job against.
    ///   - outputURL: The AWS S3 URI of the bucket location into which to
    ///     write the resulting output.
    ///
    /// - Returns: `true` if the job run is started successfully, otherwise `false`.
    func startJobRun(glueClient: GlueClient, name jobName: String, databaseName: String,
                     tableName: String, outputURL: String) async -> String? {
        do {
            let output = try await glueClient.startJobRun(
                input: StartJobRunInput(
                    arguments: [
                        "--input_database": databaseName,
                        "--input_table": tableName,
                        "--output_bucket_url": outputURL
                    ],
                    jobName: jobName,
                    numberOfWorkers: 10,
                    workerType: .g1x
                )
            )

            guard let id = output.jobRunId else {
                return nil
            }

            return id
        } catch {
            return nil
        }
    }

    /// Return a list of the job runs for the specified job.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job for which to return its job runs.
    ///   - maxResults: The maximum number of job runs to return (default:
    ///     1000).
    ///
    /// - Returns: An array of `GlueClientTypes.JobRun` objects describing
    ///   each job run.
    func getJobRuns(glueClient: GlueClient, name jobName: String, maxResults: Int? = nil) async -> [GlueClientTypes.JobRun] {
        do {
            let output = try await glueClient.getJobRuns(
                input: GetJobRunsInput(
                    jobName: jobName,
                    maxResults: maxResults
                )
            )

            guard let jobRuns = output.jobRuns else {
                print("*** No job runs found.")
                return []
            }

            return jobRuns
        } catch is EntityNotFoundException {
            print("*** The specified job name, \(jobName), doesn't exist.")
            return []
        } catch {
            print("*** Unexpected error getting job runs:")
            dump(error)
            return []
        }
    }

    /// Get information about a specific AWS Glue job run.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job to return job run data for.
    ///   - id: The run ID of the specific job run to return.
    ///
    /// - Returns: A `GlueClientTypes.JobRun` object describing the state of
    ///   the job run, or `nil` if an error occurs.
    func getJobRun(glueClient: GlueClient, name jobName: String, id: String) async -> GlueClientTypes.JobRun? {
        do {
            let output = try await glueClient.getJobRun(
                input: GetJobRunInput(
                    jobName: jobName,
                    runId: id
                )
            )

            return output.jobRun
        } catch {
            return nil
        }
    }

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        // A name to give the Python script upon upload to the Amazon S3
        // bucket.
        let scriptName = "jobscript.py"

        // Schedule string in `cron` format, as described here:
        // https://docs.aws.amazon.com/glue/latest/dg/monitor-data-warehouse-schedule.html
        let cron = "cron(15 12 * * ? *)"

        let glueConfig = try await GlueClient.GlueClientConfiguration(region: awsRegion)
        let glueClient = GlueClient(config: glueConfig)

        let s3Config = try await S3Client.S3ClientConfiguration(region: awsRegion)
        let s3Client = S3Client(config: s3Config)

        // Create random names for things that need them.

        let crawlerName = tempName(prefix: "swift-glue-basics-crawler")
        let databaseName = tempName(prefix: "swift-glue-basics-db")

        // Create a name for the AWS Glue job.

        let jobName = tempName(prefix: "scenario-job")

        // The URL of the Python script on S3.

        let scriptURL = "s3://\(bucket)/\(scriptName)"

        print("Welcome to the AWS SDK for Swift basic scenario for AWS Glue!")

        //=====================================================================
        // 0. Upload the Python script to the target bucket so it's available
        //    for use by the Amazon Glue service.
        //=====================================================================

        print("Uploading the Python script: \(script) as key \(scriptName)")
        print("Destination bucket: \(bucket)")
        if !(await uploadFile(s3Client: s3Client, path: script, toBucket: bucket, key: scriptName)) {
            return
        }

        //=====================================================================
        // 1. Create the database and crawler using the randomized names
        //    generated previously.
        //=====================================================================

        print("Creating database \"\(databaseName)\"...")
        if !(await createDatabase(glueClient: glueClient, name: databaseName, location: s3url)) {
            print("*** Unable to create the database.")
            return
        }

        print("Creating crawler \"\(crawlerName)\"...")
        if !(await createCrawler(glueClient: glueClient, crawlerName: crawlerName,
                                 iamRole: role, s3Path: s3url, cronSchedule: cron,
                                 databaseName: databaseName)) {
            return
        }

        //=====================================================================
        // 2. Start the crawler, then wait for it to be ready.
        //=====================================================================

        print("Starting the crawler and waiting until it's ready...")
        if !(await startCrawler(glueClient: glueClient, name: crawlerName)) {
            _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
            return
        }

        if !(await waitUntilCrawlerReady(glueClient: glueClient, name: crawlerName)) {
            _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
        }

        //=====================================================================
        // 3. Get the database and table created by the crawler.
        //=====================================================================

        print("Getting the crawler's database...")
        let database = await getDatabase(glueClient: glueClient, name: databaseName)

        guard let database else {
            print("*** Unable to get the database.")
            return
        }
        print("Database URI: \(database.locationUri ?? "<unknown>")")

        let tableList = await getTablesInDatabase(glueClient: glueClient, databaseName: databaseName)

        print("Found \(tableList.count) table(s):")
        for table in tableList {
            print("  \(table.name ?? "<unnamed>")")
        }

        if tableList.count != 1 {
            print("*** Incorrect number of tables found. There should only be one.")
            _ = await deleteDatabase(glueClient: glueClient, name: databaseName, withTables: true)
            _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
            return
        }

        guard let tableName = tableList[0].name else {
            print("*** Table is unnamed.")
            _ = await deleteDatabase(glueClient: glueClient, name: databaseName, withTables: true)
            _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
            return
        }

        //=====================================================================
        // 4. Create a job.
        //=====================================================================

        print("Creating a job...")
        if !(await createJob(glueClient: glueClient, name: jobName, role: role,
                             scriptLocation: scriptURL)) {
            _ = await deleteDatabase(glueClient: glueClient, name: databaseName, withTables: true)
            _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
            return
        }

        //=====================================================================
        // 5. Start a job run.
        //=====================================================================

        print("Starting the job...")

        // Construct the Amazon S3 URL for the job run's output. This is in
        // the bucket specified on the command line, with a folder name that's
        // unique for this job run.

        let timeStamp = Date().timeIntervalSince1970
        let jobPath = "\(jobName)-\(Int(timeStamp))"
        let outputURL = "s3://\(bucket)/\(jobPath)"

        // Start the job run.

        let jobRunID = await startJobRun(glueClient: glueClient, name: jobName,
                                         databaseName: databaseName,
                                         tableName: tableName,
                                         outputURL: outputURL)

        guard let jobRunID else {
            print("*** Job run ID is invalid.")
            _ = await deleteJob(glueClient: glueClient, name: jobName)
            _ = await deleteDatabase(glueClient: glueClient, name: databaseName, withTables: true)
            _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
            return
        }

        //=====================================================================
        // 6. Wait for the job run to indicate that the run is complete.
        //=====================================================================

        print("Waiting for job run to end...")

        var jobRunFinished = false
        var jobRunState: GlueClientTypes.JobRunState

        repeat {
            let jobRun = await getJobRun(glueClient: glueClient, name: jobName, id: jobRunID)
            guard let jobRun else {
                print("*** Unable to get the job run.")
                _ = await deleteJob(glueClient: glueClient, name: jobName)
                _ = await deleteDatabase(glueClient: glueClient, name: databaseName, withTables: true)
                _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
                return
            }
            jobRunState = jobRun.jobRunState ?? .failed

            //=====================================================================
            // 7. Output where to find the data if the job run was successful.
            //    If the job run failed for any reason, output an appropriate
            //    error message.
            //=====================================================================

            switch jobRunState {
                case .succeeded:
                    print("Job run succeeded. JSON files are in the Amazon S3 path:")
                    print("    \(outputURL)")
                    jobRunFinished = true
                case .stopped:
                    jobRunFinished = true
                case .error:
                    print("*** Error: Job run ended in an error. \(jobRun.errorMessage ?? "")")
                    jobRunFinished = true
                case .failed:
                    print("*** Error: Job run failed. \(jobRun.errorMessage ?? "")")
                    jobRunFinished = true
                case .timeout:
                    print("*** Warning: Job run timed out.")
                    jobRunFinished = true
                default:
                    do {
                        try await Task.sleep(for: .milliseconds(250))
                    } catch {
                        print("*** Error pausing the task.")
                    }
            }
        } while jobRunFinished != true

        //=====================================================================
        // 7.5. List the job runs for this job, showing each job run's ID and
        // its execution time.
        //=====================================================================

        print("Getting all job runs for the job \(jobName):")
        let jobRuns = await getJobRuns(glueClient: glueClient, name: jobName)

        if jobRuns.count == 0 {
            print("    <no job runs found>")
        } else {
            print("Found \(jobRuns.count) job runs... listing execution times:")
            for jobRun in jobRuns {
                print("    \(jobRun.id ?? "<unnamed>"): \(jobRun.executionTime) seconds")
            }
        }

        //=====================================================================
        // 8. List the jobs for the user's account.
        //=====================================================================

        print("\nThe account has the following jobs:")
        let jobs = await listJobs(glueClient: glueClient)

        if jobs.count == 0 {
            print("    <no jobs found>")
        } else {
            for job in jobs {
                print("    \(job)")
            }
        }

        //=====================================================================
        // 9. Get the job run details for a job run.
        //=====================================================================

        print("Information about the job run:")
        let jobRun = await getJobRun(glueClient: glueClient, name: jobName, id: jobRunID)

        guard let jobRun else {
            print("*** Unable to retrieve the job run.")
            _ = await deleteJob(glueClient: glueClient, name: jobName)
            _ = await deleteDatabase(glueClient: glueClient, name: databaseName, withTables: true)
            _ = await deleteCrawler(glueClient: glueClient, name: crawlerName)
            return
        }

        let startDate = jobRun.startedOn ?? Date(timeIntervalSince1970: 0)
        let endDate = jobRun.completedOn ?? Date(timeIntervalSince1970: 0)
        let dateFormatter: DateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .long

        print("    Started at: \(dateFormatter.string(from: startDate))")
        print("  Completed at: \(dateFormatter.string(from: endDate))")

        //=====================================================================
        // 10. Delete the job.
        //=====================================================================

        print("\nDeleting the job...")
        _ = await deleteJob(glueClient: glueClient, name: jobName)

        //=====================================================================
        // 11. Delete the database and tables created by this example.
        //=====================================================================

        print("Deleting the database...")
        _ = await deleteDatabase(glueClient: glueClient, name: databaseName, withTables: true)

        //=====================================================================
        // 12. Delete the crawler.
        //=====================================================================

        print("Deleting the crawler...")
        if !(await deleteCrawler(glueClient: glueClient, name: crawlerName)) {
            return
        }
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [CreateCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/createcrawler(input:))
  + [CreateJob](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/createjob(input:))
  + [DeleteCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletecrawler(input:))
  + [DeleteDatabase](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletedatabase(input:))
  + [DeleteJob](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletejob(input:))
  + [DeleteTable](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletetable(input:))
  + [GetCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getcrawler(input:))
  + [GetDatabase](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getdatabase(input:))
  + [GetDatabases](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getdatabases(input:))
  + [GetJob](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getjob(input:))
  + [GetJobRun](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getjobrun(input:))
  + [GetJobRuns](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getjobruns(input:))
  + [GetTables](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/gettables(input:))
  + [ListJobs](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/listjobs(input:))
  + [StartCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/startcrawler(input:))
  + [StartJobRun](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/startjobrun(input:))

## アクション
<a name="actions"></a>

### `CreateCrawler`
<a name="glue_CreateCrawler_swift_1_topic"></a>

次のコード例は、`CreateCrawler` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Create a new AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: An AWS Glue client to use for the crawler.
    ///   - crawlerName: A name for the new crawler.
    ///   - iamRole: The name of an Amazon IAM role for the crawler to use.
    ///   - s3Path: The path of an Amazon S3 folder to use as a target location.
    ///   - cronSchedule: A `cron` schedule indicating when to run the crawler.
    ///   - databaseName: The name of an AWS Glue database to operate on.
    ///
    /// - Returns: `true` if the crawler is created successfully, otherwise `false`.
    func createCrawler(glueClient: GlueClient, crawlerName: String, iamRole: String,
                       s3Path: String, cronSchedule: String, databaseName: String) async -> Bool {
        let s3Target = GlueClientTypes.S3Target(path: s3url)
        let targetList = GlueClientTypes.CrawlerTargets(s3Targets: [s3Target])

        do {
            _ = try await glueClient.createCrawler(
                input: CreateCrawlerInput(
                    databaseName: databaseName,
                    description: "Created by the AWS SDK for Swift Scenario Example for AWS Glue.",
                    name: crawlerName,
                    role: iamRole,
                    schedule: cronSchedule,
                    tablePrefix: tablePrefix,
                    targets: targetList
                )
            )
        } catch _ as AlreadyExistsException {
            print("*** A crawler named \"\(crawlerName)\" already exists.")
            return false
        } catch _ as OperationTimeoutException {
            print("*** The attempt to create the AWS Glue crawler timed out.")
            return false
        } catch {
            print("*** An unexpected error occurred creating the AWS Glue crawler: \(error.localizedDescription)")
            return false
        }

        return true
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[CreateCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/createcrawler(input:))」を参照してください。

### `CreateJob`
<a name="glue_CreateJob_swift_1_topic"></a>

次のコード例は、`CreateJob` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Create a new AWS Glue job.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name to give the new job.
    ///   - role: The IAM role for the job to use when accessing AWS services.
    ///   - scriptLocation: The AWS S3 URI of the script to be run by the job.
    /// 
    /// - Returns: `true` if the job is created successfully, otherwise `false`.
    func createJob(glueClient: GlueClient, name jobName: String, role: String,
                   scriptLocation: String) async -> Bool {
        let command = GlueClientTypes.JobCommand(
            name: "glueetl",
            pythonVersion: "3",
            scriptLocation: scriptLocation
        )

        do {
            _ = try await glueClient.createJob(
                input: CreateJobInput(
                    command: command,
                    description: "Created by the AWS SDK for Swift Glue basic scenario example.",
                    glueVersion: "3.0",
                    name: jobName,
                    numberOfWorkers: 10,
                    role: role,
                    workerType: .g1x
                )
            )
        } catch {
            return false
        }
        return true
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[CreateJob](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/createjob(input:))」を参照してください。

### `DeleteCrawler`
<a name="glue_DeleteCrawler_swift_1_topic"></a>

次のコード例は、`DeleteCrawler` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Delete an AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - name: The name of the crawler to delete.
    ///
    /// - Returns: `true` if successful, otherwise `false`.
    func deleteCrawler(glueClient: GlueClient, name: String) async -> Bool {
        do {
            _ = try await glueClient.deleteCrawler(
                input: DeleteCrawlerInput(name: name)
            )
        } catch {
            return false
        }
        return true
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[DeleteCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletecrawler(input:))」を参照してください。

### `DeleteDatabase`
<a name="glue_DeleteDatabase_swift_1_topic"></a>

次のコード例は、`DeleteDatabase` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Delete the specified database.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - databaseName: The name of the database to delete.
    ///   - deleteTables: A Bool indicating whether or not to delete the
    ///     tables in the database before attempting to delete the database.
    /// 
    /// - Returns: `true` if the database (and optionally its tables) are
    ///   deleted, otherwise `false`.
    func deleteDatabase(glueClient: GlueClient, name databaseName: String,
                        withTables deleteTables: Bool = false) async -> Bool {
        if deleteTables {
            var tableNames: [String] = []

            // Get a list of the names of all of the tables in the database.

            let tableList = await self.getTablesInDatabase(glueClient: glueClient, databaseName: databaseName)
            for table in tableList {
                guard let name = table.name else {
                    continue
                }
                tableNames.append(name)
            }

            // Delete the tables. If there's only one table, use
            // `deleteTable()`, otherwise, use `batchDeleteTable()`. You can
            // use `batchDeleteTable()` for a single table, but this
            // demonstrates the use of `deleteTable()`.

            if tableNames.count == 1 {
                do {
                    print("    Deleting table...")
                    _ = try await glueClient.deleteTable(
                        input: DeleteTableInput(
                            databaseName: databaseName,
                            name: tableNames[0]
                        )
                    )
                } catch {
                    print("*** Unable to delete the table.")
                }
            } else {
                do {
                    print("    Deleting tables...")
                    _ = try await glueClient.batchDeleteTable(
                        input: BatchDeleteTableInput(
                            databaseName: databaseName,
                            tablesToDelete: tableNames
                        )
                    )
                } catch {
                    print("*** Unable to delete the tables.")
                }
            }
        }

        // Delete the database itself.

        do {
            print("    Deleting the database itself...")
            _ = try await glueClient.deleteDatabase(
                input: DeleteDatabaseInput(name: databaseName)
            )
        } catch {
            print("*** Unable to delete the database.")
            return false
        }
        return true
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[DeleteDatabase](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletedatabase(input:))」を参照してください。

### `DeleteJob`
<a name="glue_DeleteJob_swift_1_topic"></a>

次のコード例は、`DeleteJob` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Delete an AWS Glue job.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job to delete.
    ///
    /// - Returns: `true` if the job is successfully deleted, otherwise `false`.
    func deleteJob(glueClient: GlueClient, name jobName: String) async -> Bool {
        do {
            _ = try await glueClient.deleteJob(
                input: DeleteJobInput(jobName: jobName)
            )
        } catch {
            return false
        }
        return true
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[DeleteJob](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletejob(input:))」を参照してください。

### `DeleteTable`
<a name="glue_DeleteTable_swift_1_topic"></a>

次のコード例は、`DeleteTable` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

                do {
                    print("    Deleting table...")
                    _ = try await glueClient.deleteTable(
                        input: DeleteTableInput(
                            databaseName: databaseName,
                            name: tableNames[0]
                        )
                    )
                } catch {
                    print("*** Unable to delete the table.")
                }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[DeleteTable](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/deletetable(input:))」を参照してください。

### `GetCrawler`
<a name="glue_GetCrawler_swift_1_topic"></a>

次のコード例は、`GetCrawler` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Get the state of the specified AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - name: The name of the crawler whose state should be returned.
    ///
    /// - Returns: A `GlueClientTypes.CrawlerState` value describing the
    ///   state of the crawler.
    func getCrawlerState(glueClient: GlueClient, name: String) async -> GlueClientTypes.CrawlerState {
        do {
            let output = try await glueClient.getCrawler(
                input: GetCrawlerInput(name: name)
            )

            // If the crawler or its state is `nil`, report that the crawler
            // is stopping. This may not be what you want for your
            // application but it works for this one!
            
            guard let crawler = output.crawler else {
                return GlueClientTypes.CrawlerState.stopping
            }
            guard let state = crawler.state else {
                return GlueClientTypes.CrawlerState.stopping            
            }
            return state
        } catch {
            return GlueClientTypes.CrawlerState.stopping
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[GetCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getcrawler(input:))」を参照してください。

### `GetDatabase`
<a name="glue_GetDatabase_swift_1_topic"></a>

次のコード例は、`GetDatabase` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Get the AWS Glue database with the specified name.
    ///
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - name: The name of the database to return.
    ///
    /// - Returns: The `GlueClientTypes.Database` object describing the
    ///   specified database, or `nil` if an error occurs or the database
    ///   isn't found.
    func getDatabase(glueClient: GlueClient, name: String) async -> GlueClientTypes.Database? {
        do {
            let output = try await glueClient.getDatabase(
                input: GetDatabaseInput(name: name)
            )

            return output.database
        } catch {
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[GetDatabase](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getdatabase(input:))」を参照してください。

### `GetJobRun`
<a name="glue_GetJobRun_swift_1_topic"></a>

次のコード例は、`GetJobRun` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Get information about a specific AWS Glue job run.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job to return job run data for.
    ///   - id: The run ID of the specific job run to return.
    ///
    /// - Returns: A `GlueClientTypes.JobRun` object describing the state of
    ///   the job run, or `nil` if an error occurs.
    func getJobRun(glueClient: GlueClient, name jobName: String, id: String) async -> GlueClientTypes.JobRun? {
        do {
            let output = try await glueClient.getJobRun(
                input: GetJobRunInput(
                    jobName: jobName,
                    runId: id
                )
            )

            return output.jobRun
        } catch {
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[GetJobRun](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getjobrun(input:))」を参照してください。

### `GetJobRuns`
<a name="glue_GetJobRuns_swift_1_topic"></a>

次のコード例は、`GetJobRuns` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Return a list of the job runs for the specified job.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job for which to return its job runs.
    ///   - maxResults: The maximum number of job runs to return (default:
    ///     1000).
    ///
    /// - Returns: An array of `GlueClientTypes.JobRun` objects describing
    ///   each job run.
    func getJobRuns(glueClient: GlueClient, name jobName: String, maxResults: Int? = nil) async -> [GlueClientTypes.JobRun] {
        do {
            let output = try await glueClient.getJobRuns(
                input: GetJobRunsInput(
                    jobName: jobName,
                    maxResults: maxResults
                )
            )

            guard let jobRuns = output.jobRuns else {
                print("*** No job runs found.")
                return []
            }

            return jobRuns
        } catch is EntityNotFoundException {
            print("*** The specified job name, \(jobName), doesn't exist.")
            return []
        } catch {
            print("*** Unexpected error getting job runs:")
            dump(error)
            return []
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API reference* の「[GetJobRun](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/getjobruns(input:))」を参照してください。

### `GetTables`
<a name="glue_GetTables_swift_1_topic"></a>

次のコード例は、`GetTables` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Returns a list of the tables in the specified database.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - databaseName: The name of the database whose tables are to be
    ///     returned.
    ///
    /// - Returns: An array of `GlueClientTypes.Table` objects, each
    ///   describing one table in the named database. An empty array indicates
    ///   that there are either no tables in the database, or an error
    ///   occurred before any tables could be found.
    func getTablesInDatabase(glueClient: GlueClient, databaseName: String) async -> [GlueClientTypes.Table] {
        var tables: [GlueClientTypes.Table] = []
        var nextToken: String?

        repeat {
            do {
                let output = try await glueClient.getTables(
                    input: GetTablesInput(
                        databaseName: databaseName,
                        nextToken: nextToken
                    )
                )

                guard let tableList = output.tableList else {
                    return tables
                }

                tables = tables + tableList
                nextToken = output.nextToken
            } catch {
                return tables
            }
        } while nextToken != nil

        return tables
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[GetTables](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/gettables(input:))」を参照してください。

### `ListJobs`
<a name="glue_ListJobs_swift_1_topic"></a>

次のコード例は、`ListJobs` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Return a list of the AWS Glue jobs listed on the user's account.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - maxJobs: The maximum number of jobs to return (default: 100).
    /// 
    /// - Returns: An array of strings listing the names of all available AWS
    ///   Glue jobs.
    func listJobs(glueClient: GlueClient, maxJobs: Int = 100) async -> [String] {
        var jobList: [String] = []
        var nextToken: String?

        repeat {
            do {
                let output = try await glueClient.listJobs(
                    input: ListJobsInput(
                        maxResults: maxJobs,
                        nextToken: nextToken
                    )
                )

                guard let jobs = output.jobNames else {
                    return jobList
                }

                jobList = jobList + jobs
                nextToken = output.nextToken
            } catch {
                return jobList
            }
        } while (nextToken != nil)

        return jobList
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[ListJobs](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/listjobs(input:))」を参照してください。

### `StartCrawler`
<a name="glue_StartCrawler_swift_1_topic"></a>

次のコード例は、`StartCrawler` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Start running an AWS Glue crawler.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use when starting the crawler.
    ///   - name: The name of the crawler to start running.
    ///
    /// - Returns: `true` if the crawler is started successfully, otherwise `false`.
    func startCrawler(glueClient: GlueClient, name: String) async -> Bool {
        do {
            _ = try await glueClient.startCrawler(
                input: StartCrawlerInput(name: name)
            )
        } catch {
            print("*** An unexpected error occurred starting the crawler.")
            return false
        }

        return true
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[StartCrawler](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/startcrawler(input:))」を参照してください。

### `StartJobRun`
<a name="glue_StartJobRun_swift_1_topic"></a>

次のコード例は、`StartJobRun` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/glue#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSGlue

    /// Start an AWS Glue job run.
    /// 
    /// - Parameters:
    ///   - glueClient: The AWS Glue client to use.
    ///   - jobName: The name of the job to run.
    ///   - databaseName: The name of the AWS Glue database to run the job against.
    ///   - tableName: The name of the table in the database to run the job against.
    ///   - outputURL: The AWS S3 URI of the bucket location into which to
    ///     write the resulting output.
    ///
    /// - Returns: `true` if the job run is started successfully, otherwise `false`.
    func startJobRun(glueClient: GlueClient, name jobName: String, databaseName: String,
                     tableName: String, outputURL: String) async -> String? {
        do {
            let output = try await glueClient.startJobRun(
                input: StartJobRunInput(
                    arguments: [
                        "--input_database": databaseName,
                        "--input_table": tableName,
                        "--output_bucket_url": outputURL
                    ],
                    jobName: jobName,
                    numberOfWorkers: 10,
                    workerType: .g1x
                )
            )

            guard let id = output.jobRunId else {
                return nil
            }

            return id
        } catch {
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス* の「[StartJobRun](https://sdk.amazonaws.com/swift/api/awsglue/latest/documentation/awsglue/glueclient/startjobrun(input:))」を参照してください。

# SDK for Swift を使用した IAM の例
<a name="swift_1_iam_code_examples"></a>

次のコード例は、IAM で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AttachRolePolicy`
<a name="iam_AttachRolePolicy_swift_1_topic"></a>

次のコード例は、`AttachRolePolicy` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func attachRolePolicy(role: String, policyArn: String) async throws {
        let input = AttachRolePolicyInput(
            policyArn: policyArn,
            roleName: role
        )
        do {
            _ = try await client.attachRolePolicy(input: input)
        } catch {
            print("ERROR: Attaching a role policy:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[AttachRolePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/attachrolepolicy(input:))」を参照してください。

### `CreateAccessKey`
<a name="iam_CreateAccessKey_swift_1_topic"></a>

次のコード例は、`CreateAccessKey` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func createAccessKey(userName: String) async throws -> IAMClientTypes.AccessKey {
        let input = CreateAccessKeyInput(
            userName: userName
        )
        do {
            let output = try await iamClient.createAccessKey(input: input)
            guard let accessKey = output.accessKey else {
                throw ServiceHandlerError.keyError
            }
            return accessKey
        } catch {
            print("ERROR: createAccessKey:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[CreateAccessKey](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createaccesskey(input:))」を参照してください。

### `CreatePolicy`
<a name="iam_CreatePolicy_swift_1_topic"></a>

次のコード例は、`CreatePolicy` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func createPolicy(name: String, policyDocument: String) async throws -> IAMClientTypes.Policy {
        let input = CreatePolicyInput(
            policyDocument: policyDocument,
            policyName: name
        )
        do {
            let output = try await iamClient.createPolicy(input: input)
            guard let policy = output.policy else {
                throw ServiceHandlerError.noSuchPolicy
            }
            return policy
        } catch {
            print("ERROR: createPolicy:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[CreatePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createpolicy(input:))」を参照してください。

### `CreateRole`
<a name="iam_CreateRole_swift_1_topic"></a>

次のコード例は、`CreateRole` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    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 {
            print("ERROR: createRole:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[CreateRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createrole(input:))」を参照してください。

### `CreateServiceLinkedRole`
<a name="iam_CreateServiceLinkedRole_swift_1_topic"></a>

次のコード例は、`CreateServiceLinkedRole` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func createServiceLinkedRole(service: String, suffix: String? = nil, description: String?)
                    async throws -> IAMClientTypes.Role {
        let input = CreateServiceLinkedRoleInput(
            awsServiceName: service,
            customSuffix: suffix,
            description: description
        )
        do {
            let output = try await client.createServiceLinkedRole(input: input)
            guard let role = output.role else {
                throw ServiceHandlerError.noSuchRole
            }
            return role
        } catch {
            print("ERROR: createServiceLinkedRole:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[CreateServiceLinkedRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createservicelinkedrole(input:))」を参照してください。

### `CreateUser`
<a name="iam_CreateUser_swift_1_topic"></a>

次のコード例は、`CreateUser` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func createUser(name: String) async throws -> String {
        let input = CreateUserInput(
            userName: name
        )
        do {
            let output = try await client.createUser(input: input)
            guard let user = output.user else {
                throw ServiceHandlerError.noSuchUser
            }
            guard let id = user.userId else {
                throw ServiceHandlerError.noSuchUser
            }
            return id
        } catch {
            print("ERROR: createUser:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[CreateUser](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/createuser(input:))」を参照してください。

### `DeleteAccessKey`
<a name="iam_DeleteAccessKey_swift_1_topic"></a>

次のコード例は、`DeleteAccessKey` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func deleteAccessKey(user: IAMClientTypes.User? = nil,
                                key: IAMClientTypes.AccessKey) async throws
    {
        let userName: String?

        if user != nil {
            userName = user!.userName
        } else {
            userName = nil
        }

        let input = DeleteAccessKeyInput(
            accessKeyId: key.accessKeyId,
            userName: userName
        )
        do {
            _ = try await iamClient.deleteAccessKey(input: input)
        } catch {
            print("ERROR: deleteAccessKey:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[DeleteAccessKey](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleteaccesskey(input:))」を参照してください。

### `DeletePolicy`
<a name="iam_DeletePolicy_swift_1_topic"></a>

次のコード例は、`DeletePolicy` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func deletePolicy(policy: IAMClientTypes.Policy) async throws {
        let input = DeletePolicyInput(
            policyArn: policy.arn
        )
        do {
            _ = try await iamClient.deletePolicy(input: input)
        } catch {
            print("ERROR: deletePolicy:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[DeletePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deletepolicy(input:))」を参照してください。

### `DeleteRole`
<a name="iam_DeleteRole_swift_1_topic"></a>

次のコード例は、`DeleteRole` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func deleteRole(role: IAMClientTypes.Role) async throws {
        let input = DeleteRoleInput(
            roleName: role.roleName
        )
        do {
            _ = try await iamClient.deleteRole(input: input)
        } catch {
            print("ERROR: deleteRole:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[DeleteRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleterole(input:))」を参照してください。

### `DeleteUser`
<a name="iam_DeleteUser_swift_1_topic"></a>

次のコード例は、`DeleteUser` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func deleteUser(user: IAMClientTypes.User) async throws {
        let input = DeleteUserInput(
            userName: user.userName
        )
        do {
            _ = try await iamClient.deleteUser(input: input)
        } catch {
            print("ERROR: deleteUser:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[DeleteUser](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleteuser(input:))」を参照してください。

### `DeleteUserPolicy`
<a name="iam_DeleteUserPolicy_swift_1_topic"></a>

次のコード例は、`DeleteUserPolicy` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    func deleteUserPolicy(user: IAMClientTypes.User, policyName: String) async throws {
        let input = DeleteUserPolicyInput(
            policyName: policyName,
            userName: user.userName
        )
        do {
            _ = try await iamClient.deleteUserPolicy(input: input)
        } catch {
            print("ERROR: deleteUserPolicy:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[DeleteUserPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/deleteuserpolicy(input:))」を参照してください。

### `DetachRolePolicy`
<a name="iam_DetachRolePolicy_swift_1_topic"></a>

次のコード例は、`DetachRolePolicy` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func detachRolePolicy(policy: IAMClientTypes.Policy, role: IAMClientTypes.Role) async throws {
        let input = DetachRolePolicyInput(
            policyArn: policy.arn,
            roleName: role.roleName
        )

        do {
            _ = try await iamClient.detachRolePolicy(input: input)
        } catch {
            print("ERROR: detachRolePolicy:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[DetachRolePolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/detachrolepolicy(input:))」を参照してください。

### `GetPolicy`
<a name="iam_GetPolicy_swift_1_topic"></a>

次のコード例は、`GetPolicy` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func getPolicy(arn: String) async throws -> IAMClientTypes.Policy {
        let input = GetPolicyInput(
            policyArn: arn
        )
        do {
            let output = try await client.getPolicy(input: input)
            guard let policy = output.policy else {
                throw ServiceHandlerError.noSuchPolicy
            }
            return policy
        } catch {
            print("ERROR: getPolicy:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[GetPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/getpolicy(input:))」を参照してください。

### `GetRole`
<a name="iam_GetRole_swift_1_topic"></a>

次のコード例は、`GetRole` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func getRole(name: String) async throws -> IAMClientTypes.Role {
        let input = GetRoleInput(
            roleName: name
        )
        do {
            let output = try await client.getRole(input: input)
            guard let role = output.role else {
                throw ServiceHandlerError.noSuchRole
            }
            return role
        } catch {
            print("ERROR: getRole:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[GetRole](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/getrole(input:))」を参照してください。

### `GetUser`
<a name="iam_GetUser_swift_1_topic"></a>

次のコード例は、`GetUser` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func getUser(name: String? = nil) async throws -> IAMClientTypes.User {
        let input = GetUserInput(
            userName: name
        )
        do {
            let output = try await iamClient.getUser(input: input)
            guard let user = output.user else {
                throw ServiceHandlerError.noSuchUser
            }
            return user
        } catch {
            print("ERROR: getUser:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[GetUser](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/getuser(input:))」を参照してください。

### `ListAttachedRolePolicies`
<a name="iam_ListAttachedRolePolicies_swift_1_topic"></a>

次のコード例は、`ListAttachedRolePolicies` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3



    /// Returns a list of AWS Identity and Access Management (IAM) policies
    /// that are attached to the role.
    ///
    /// - Parameter role: The IAM role to return the policy list for.
    ///
    /// - Returns: An array of `IAMClientTypes.AttachedPolicy` objects
    ///   describing each managed policy that's attached to the role.
    public func listAttachedRolePolicies(role: String) async throws -> [IAMClientTypes.AttachedPolicy] {
        var policyList: [IAMClientTypes.AttachedPolicy] = []

        // Use "Paginated" to get all the attached role polices.
        // This lets the SDK handle the 'isTruncated' in "ListAttachedRolePoliciesOutput".
        let input = ListAttachedRolePoliciesInput(
            roleName: role
        )
        let output = client.listAttachedRolePoliciesPaginated(input: input)

        do {
            for try await page in output {
                guard let attachedPolicies = page.attachedPolicies else {
                    print("Error: no attached policies returned.")
                    continue
                }
                for attachedPolicy in attachedPolicies {
                    policyList.append(attachedPolicy)
                }
            }
        } catch {
            print("ERROR: listAttachedRolePolicies:", dump(error))
            throw error
        }

        return policyList
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[ListAttachedRolePolicies](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listattachedrolepolicies(input:))」を参照してください。

### `ListGroups`
<a name="iam_ListGroups_swift_1_topic"></a>

次のコード例は、`ListGroups` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func listGroups() async throws -> [String] {
        var groupList: [String] = []

        // Use "Paginated" to get all the groups.
        // This lets the SDK handle the 'isTruncated' property in "ListGroupsOutput".
        let input = ListGroupsInput()

        let pages = client.listGroupsPaginated(input: input)
        do {
            for try await page in pages {
                guard let groups = page.groups else {
                    print("Error: no groups returned.")
                    continue
                }

                for group in groups {
                    if let name = group.groupName {
                        groupList.append(name)
                    }
                }
            }
        } catch {
            print("ERROR: listGroups:", dump(error))
            throw error
        }
        return groupList
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[ListGroups](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listgroups(input:))」を参照してください。

### `ListPolicies`
<a name="iam_ListPolicies_swift_1_topic"></a>

次のコード例は、`ListPolicies` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func listPolicies() async throws -> [MyPolicyRecord] {
        var policyList: [MyPolicyRecord] = []

        // Use "Paginated" to get all the policies.
        // This lets the SDK handle the 'isTruncated' in "ListPoliciesOutput".
        let input = ListPoliciesInput()
        let output = client.listPoliciesPaginated(input: input)

        do {
            for try await page in output {
                guard let policies = page.policies else {
                    print("Error: no policies returned.")
                    continue
                }

                for policy in policies {
                    guard let name = policy.policyName,
                          let id = policy.policyId,
                          let arn = policy.arn
                    else {
                        throw ServiceHandlerError.noSuchPolicy
                    }
                    policyList.append(MyPolicyRecord(name: name, id: id, arn: arn))
                }
            }
        } catch {
            print("ERROR: listPolicies:", dump(error))
            throw error
        }

        return policyList
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[ListPolicies](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listpolicies(input:))」を参照してください。

### `ListRolePolicies`
<a name="iam_ListRolePolicies_swift_1_topic"></a>

次のコード例は、`ListRolePolicies` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func listRolePolicies(role: String) async throws -> [String] {
        var policyList: [String] = []

        // Use "Paginated" to get all the role policies.
        // This lets the SDK handle the 'isTruncated' in "ListRolePoliciesOutput".
        let input = ListRolePoliciesInput(
            roleName: role
        )
        let pages = client.listRolePoliciesPaginated(input: input)

        do {
            for try await page in pages {
                guard let policies = page.policyNames else {
                    print("Error: no role policies returned.")
                    continue
                }

                for policy in policies {
                    policyList.append(policy)
                }
            }
        } catch {
            print("ERROR: listRolePolicies:", dump(error))
            throw error
        }
        return policyList
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[ListRolePolicies](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listrolepolicies(input:))」を参照してください。

### `ListRoles`
<a name="iam_ListRoles_swift_1_topic"></a>

次のコード例は、`ListRoles` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func listRoles() async throws -> [String] {
        var roleList: [String] = []

        // Use "Paginated" to get all the roles.
        // This lets the SDK handle the 'isTruncated' in "ListRolesOutput".
        let input = ListRolesInput()
        let pages = client.listRolesPaginated(input: input)

        do {
            for try await page in pages {
                guard let roles = page.roles else {
                    print("Error: no roles returned.")
                    continue
                }

                for role in roles {
                    if let name = role.roleName {
                        roleList.append(name)
                    }
                }
            }
        } catch {
            print("ERROR: listRoles:", dump(error))
            throw error
        }
        return roleList
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[ListRoles](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listroles(input:))」を参照してください。

### `ListUsers`
<a name="iam_ListUsers_swift_1_topic"></a>

次のコード例は、`ListUsers` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    public func listUsers() async throws -> [MyUserRecord] {
        var userList: [MyUserRecord] = []
        
        // Use "Paginated" to get all the users.
        // This lets the SDK handle the 'isTruncated' in "ListUsersOutput".
        let input = ListUsersInput()
        let output = client.listUsersPaginated(input: input)

        do {
            for try await page in output {
                guard let users = page.users else {
                    continue
                }
                for user in users {
                    if let id = user.userId, let name = user.userName {
                        userList.append(MyUserRecord(id: id, name: name))
                    }
                }
            }
        }
        catch {
            print("ERROR: listUsers:", dump(error))
            throw error
        }
       return userList
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ListUsers](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/listusers(input:))」を参照してください。

### `PutUserPolicy`
<a name="iam_PutUserPolicy_swift_1_topic"></a>

次のコード例は、`PutUserPolicy` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSIAM
import AWSS3


    func putUserPolicy(policyDocument: String, policyName: String, user: IAMClientTypes.User) async throws {
        let input = PutUserPolicyInput(
            policyDocument: policyDocument,
            policyName: policyName,
            userName: user.userName
        )
        do {
            _ = try await iamClient.putUserPolicy(input: input)
        } catch {
            print("ERROR: putUserPolicy:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[PutUserPolicy](https://sdk.amazonaws.com/swift/api/awsiam/latest/documentation/awsiam/iamclient/putuserpolicy(input:))」を参照してください。

# SDK for Swift を使用した Lambda の例
<a name="swift_1_lambda_code_examples"></a>

次のコード例は、Lambda で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="lambda_Scenario_GettingStartedFunctions_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ IAM ロールと Lambda 関数を作成し、ハンドラーコードをアップロードします。
+ 1 つのパラメータで関数を呼び出して、結果を取得します。
+ 関数コードを更新し、環境変数で設定します。
+ 新しいパラメータで関数を呼び出して、結果を取得します。返された実行ログを表示します。
+ アカウントの関数を一覧表示し、リソースをクリーンアップします。

詳細については、「[コンソールで Lambda 関数を作成する](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)」を参照してください。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。
最初の Lambda 関数を定義します。これにより、指定した値が増分されます。  

```
// swift-tools-version: 5.9
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "increment",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/swift-server/swift-aws-lambda-runtime.git",
            branch: "main"),
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "increment",
            dependencies: [
                .product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
            ],
            path: "Sources"
        )
    ]
)

import Foundation
import AWSLambdaRuntime

/// Represents the contents of the requests being received from the client.
/// This structure must be `Decodable` to indicate that its initializer
/// converts an external representation into this type.
struct Request: Decodable, Sendable {
    /// The action to perform.
    let action: String
    /// The number to act upon.
    let number: Int
}

/// The contents of the response sent back to the client. This must be
/// `Encodable`.
struct Response: Encodable, Sendable {
    /// The resulting value after performing the action.
    let answer: Int?
}


/// The Lambda function body.
///
/// - Parameters:
///   - event: The `Request` describing the request made by the
///     client.
///   - context: A `LambdaContext` describing the context in
///     which the lambda function is running.
///
/// - Returns: A `Response` object that will be encoded to JSON and sent
///   to the client by the Lambda runtime.
let incrementLambdaRuntime = LambdaRuntime {
        (event: Request, context: LambdaContext) -> Response in
    let action = event.action
    var answer: Int?

    if action != "increment" {
        context.logger.error("Unrecognized operation: \"\(action)\". The only supported action is \"increment\".")
    } else {
        answer = event.number + 1
        context.logger.info("The calculated answer is \(answer!).")
    }

    let response = Response(answer: answer)
    return response
}

// Run the Lambda runtime code.

try await incrementLambdaRuntime.run()
```
2 番目の Lambda 関数を定義します。この関数は、2 つの数値に対して算術演算を実行します。  

```
// swift-tools-version: 5.9
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "calculator",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/swift-server/swift-aws-lambda-runtime.git",
            branch: "main"),
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "calculator",
            dependencies: [
                .product(name: "AWSLambdaRuntime", package: "swift-aws-lambda-runtime"),
            ],
            path: "Sources"
        )
    ]
)

import Foundation
import AWSLambdaRuntime

/// Represents the contents of the requests being received from the client.
/// This structure must be `Decodable` to indicate that its initializer
/// converts an external representation into this type.
struct Request: Decodable, Sendable {
    /// The action to perform.
    let action: String
    /// The first number to act upon.
    let x: Int
    /// The second number to act upon.
    let y: Int
}

/// A dictionary mapping operation names to closures that perform that
/// operation and return the result.
let actions = [
    "plus": { (x: Int, y: Int) -> Int in
        return x + y
    },
    "minus": { (x: Int, y: Int) -> Int in
        return x - y
    },
    "times": { (x: Int, y: Int) -> Int in
        return x * y
    },
    "divided-by": { (x: Int, y: Int) -> Int in
        return x / y
    }
]

/// The contents of the response sent back to the client. This must be
/// `Encodable`.
struct Response: Encodable, Sendable {
    /// The resulting value after performing the action.
    let answer: Int?
}


/// The Lambda function's entry point. Called by the Lambda runtime.
///
/// - Parameters:
///   - event: The `Request` describing the request made by the
///     client.
///   - context: A `LambdaContext` describing the context in
///     which the lambda function is running.
///
/// - Returns: A `Response` object that will be encoded to JSON and sent
///   to the client by the Lambda runtime.
let calculatorLambdaRuntime = LambdaRuntime {
        (_ event: Request, context: LambdaContext) -> Response in
    let action = event.action
    var answer: Int?
    var actionFunc: ((Int, Int) -> Int)?

    // Get the closure to run to perform the calculation.

    actionFunc = await actions[action]

    guard let actionFunc else {
        context.logger.error("Unrecognized operation '\(action)\'")
        return Response(answer: nil)
    }

    // Perform the calculation and return the answer.

    answer = actionFunc(event.x, event.y)

    guard let answer else {
        context.logger.error("Error computing \(event.x) \(action) \(event.y)")
    }
    context.logger.info("\(event.x) \(action) \(event.y) = \(answer)")

    return Response(answer: answer)
}

try await calculatorLambdaRuntime.run()
```
2 つの Lambda 関数を呼び出すメインプログラムを定義します。  

```
// swift-tools-version: 5.9
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "lambda-basics",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.0.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "lambda-basics",
            dependencies: [
                .product(name: "AWSLambda", package: "aws-sdk-swift"),
                .product(name: "AWSIAM", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources"
        )
    ]
)

//
/// An example demonstrating a variety of important AWS Lambda functions.

import ArgumentParser
import AWSIAM
import SmithyWaitersAPI
import AWSClientRuntime
import AWSLambda
import Foundation

/// Represents the contents of the requests being received from the client.
/// This structure must be `Decodable` to indicate that its initializer
/// converts an external representation into this type.
struct IncrementRequest: Encodable, Decodable, Sendable {
    /// The action to perform.
    let action: String
    /// The number to act upon.
    let number: Int
}

struct Response: Encodable, Decodable, Sendable {
    /// The resulting value after performing the action.
    let answer: Int?
}

struct CalculatorRequest: Encodable, Decodable, Sendable {
    /// The action to perform.
    let action: String
    /// The first number to act upon.
    let x: Int
    /// The second number to act upon.
    let y: Int
}

let exampleName = "SwiftLambdaRoleExample"
let basicsFunctionName = "lambda-basics-function"

/// The ARN of the standard IAM policy for execution of Lambda functions.
let policyARN = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"

struct ExampleCommand: ParsableCommand {
    // -MARK: Command arguments
    @Option(help: "Name of the IAM Role to use for the Lambda functions")
    var role = exampleName
    @Option(help: "Zip archive containing the 'increment' lambda function")
    var incpath: String
    @Option(help: "Zip archive containing the 'calculator' lambda function")
    var calcpath: String
    @Option(help: "Name of the Amazon S3 Region to use (default: us-east-1)")
    var region = "us-east-1"

    static var configuration = CommandConfiguration(
        commandName: "lambda-basics",
        abstract: """
        This example demonstrates several common operations using AWS Lambda.
        """,
        discussion: """
        """
    )

    /// Returns the specified IAM role object.
    /// 
    /// - Parameters:
    ///   - iamClient: `IAMClient` to use when looking for the role.
    ///   - roleName: The name of the role to check.
    ///
    /// - Returns: The `IAMClientTypes.Role` representing the specified role.
    func getRole(iamClient: IAMClient, roleName: String) async throws
                 -> IAMClientTypes.Role {
        do {
            let roleOutput = try await iamClient.getRole(
                input: GetRoleInput(
                    roleName: roleName
                )
            )

            guard let role = roleOutput.role else {
                throw ExampleError.roleNotFound
            }
            return role
        } catch {
            throw ExampleError.roleNotFound
        }
    }

    /// Create the AWS IAM role that will be used to access AWS Lambda.
    /// 
    /// - Parameters:
    ///   - iamClient: The AWS `IAMClient` to use.
    ///   - roleName: The name of the AWS IAM role to use for Lambda.
    ///
    /// - Throws: `ExampleError.roleCreateError`
    ///
    /// - Returns: The `IAMClientTypes.Role` struct that describes the new role.
    func createRoleForLambda(iamClient: IAMClient, roleName: String) async throws -> IAMClientTypes.Role {
        let output = try await iamClient.createRole(
            input: CreateRoleInput(
                assumeRolePolicyDocument:
                """
                {
                    "Version":"2012-10-17",		 	 	 
                    "Statement": [
                        {
                            "Effect": "Allow",
                            "Principal": {"Service": "lambda.amazonaws.com"},
                            "Action": "sts:AssumeRole"
                        }
                    ]
                }
                """,
                roleName: roleName
            )
        )

        guard let role = output.role else {
            throw ExampleError.roleCreateError
        }

        // Wait for the role to be ready for use.

        _ = try await iamClient.waitUntilRoleExists(
            options: WaiterOptions(
                maxWaitTime: 20,
                minDelay: 0.5,
                maxDelay: 2
            ),
            input: GetRoleInput(roleName: roleName)
        )

        return role
    }

    /// Detect whether or not the AWS Lambda function with the specified name
    /// exists, by requesting its function information.
    ///
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - name: The name of the AWS Lambda function to find.
    ///
    /// - Returns: `true` if the Lambda function exists. Otherwise `false`.
    func doesLambdaFunctionExist(lambdaClient: LambdaClient, name: String) async -> Bool {
        do {
            _ = try await lambdaClient.getFunction(
                input: GetFunctionInput(functionName: name)
            )
        } catch {
            return false
        }

        return true
    }

    /// Create the specified AWS Lambda function.
    /// 
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - functionName: The name of the AWS Lambda function to create.
    ///   - roleArn: The ARN of the role to apply to the function.
    ///   - path: The path of the Zip archive containing the function.
    /// 
    /// - Returns: `true` if the AWS Lambda was successfully created; `false`
    ///   if it wasn't.
    func createFunction(lambdaClient: LambdaClient, functionName: String,
                                roleArn: String?, path: String) async throws -> Bool {
        do {
            // Read the Zip archive containing the AWS Lambda function.

            let zipUrl = URL(fileURLWithPath: path)
            let zipData = try Data(contentsOf: zipUrl)

            // Create the AWS Lambda function that runs the specified code,
            // using the name given on the command line. The Lambda function
            // will run using the Amazon Linux 2 runtime.

            _ = try await lambdaClient.createFunction(
                input: CreateFunctionInput(
                    code: LambdaClientTypes.FunctionCode(zipFile: zipData),
                    functionName: functionName,
                    handler: "handle",
                    role: roleArn,
                    runtime: .providedal2
                )
            )
        } catch {
            print("*** Error creating Lambda function:")
            dump(error)
            return false
        }

        // Wait for a while to be sure the function is done being created.

        let output = try await lambdaClient.waitUntilFunctionActiveV2(
            options: WaiterOptions(
                maxWaitTime: 20,
                minDelay: 0.5,
                maxDelay: 2
            ),
            input: GetFunctionInput(functionName: functionName)
        )

        switch output.result {
            case .success:
                return true
            case .failure:
                return false
        }
    }

    /// Update the AWS Lambda function with new code to run when the function
    /// is invoked.
    /// 
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - functionName: The name of the AWS Lambda function to update.
    ///   - path: The pathname of the Zip file containing the packaged Lambda
    ///     function.
    /// - Throws: `ExampleError.zipFileReadError`
    /// - Returns: `true` if the function's code is updated successfully.
    ///   Otherwise, returns `false`.
    func updateFunctionCode(lambdaClient: LambdaClient, functionName: String,
                            path: String) async throws -> Bool {
        let zipUrl = URL(fileURLWithPath: path)
        let zipData: Data

        // Read the function's Zip file.

        do {
            zipData = try Data(contentsOf: zipUrl)
        } catch {
            throw ExampleError.zipFileReadError
        }

        // Update the function's code and wait for the updated version to be
        // ready for use.

        do {
            _ = try await lambdaClient.updateFunctionCode(
                input: UpdateFunctionCodeInput(
                    functionName: functionName,
                    zipFile: zipData
                )
            )
        } catch {
            return false
        }

        let output = try await lambdaClient.waitUntilFunctionUpdatedV2(
            options: WaiterOptions(
                maxWaitTime: 20,
                minDelay: 0.5,
                maxDelay: 2
            ),
            input: GetFunctionInput(
                functionName: functionName
            )
        )

        switch output.result {
            case .success:
                return true
            case .failure:
                return false
        }
    }

    /// Tell the server-side component to log debug output by setting its
    /// environment's `LOG_LEVEL` to `DEBUG`.
    ///
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - functionName: The name of the AWS Lambda function to enable debug
    ///     logging for.
    ///
    /// - Throws: `ExampleError.environmentResponseMissingError`,
    ///   `ExampleError.updateFunctionConfigurationError`,
    ///   `ExampleError.environmentVariablesMissingError`,
    ///   `ExampleError.logLevelIncorrectError`,
    ///   `ExampleError.updateFunctionConfigurationError`
    func enableDebugLogging(lambdaClient: LambdaClient, functionName: String) async throws {
        let envVariables = [
            "LOG_LEVEL": "DEBUG"
        ]
        let environment = LambdaClientTypes.Environment(variables: envVariables)

        do {
            let output = try await lambdaClient.updateFunctionConfiguration(
                input: UpdateFunctionConfigurationInput(
                    environment: environment,
                    functionName: functionName
                )
            )

            guard let response = output.environment else {
                throw ExampleError.environmentResponseMissingError
            }

            if response.error != nil {
                throw ExampleError.updateFunctionConfigurationError
            }

            guard let retVariables = response.variables else {
                throw ExampleError.environmentVariablesMissingError
            }

            for envVar in retVariables {
                if envVar.key == "LOG_LEVEL" && envVar.value != "DEBUG" {
                    print("*** Log level is not set to DEBUG!")
                    throw ExampleError.logLevelIncorrectError
                }
            }
        } catch {
            throw ExampleError.updateFunctionConfigurationError
        }
    }

    /// Returns an array containing the names of all AWS Lambda functions
    /// available to the user.
    ///
    /// - Parameter lambdaClient: The `IAMClient` to use.
    ///
    /// - Throws: `ExampleError.listFunctionsError`
    ///
    /// - Returns: An array of lambda function name strings.
    func getFunctionNames(lambdaClient: LambdaClient) async throws -> [String] {
        let pages = lambdaClient.listFunctionsPaginated(
            input: ListFunctionsInput()
        )

        var functionNames: [String] = []

        for try await page in pages {
            guard let functions = page.functions else {
                throw ExampleError.listFunctionsError
            }

            for function in functions {
                functionNames.append(function.functionName ?? "<unknown>")
            }
        }

        return functionNames
    }

    /// Invoke the Lambda function to increment a value.
    /// 
    /// - Parameters:
    ///   - lambdaClient: The `IAMClient` to use.
    ///   - number: The number to increment.
    ///
    /// - Throws: `ExampleError.noAnswerReceived`, `ExampleError.invokeError`
    ///
    /// - Returns: An integer number containing the incremented value.
    func invokeIncrement(lambdaClient: LambdaClient, number: Int) async throws -> Int {
        do {
            let incRequest = IncrementRequest(action: "increment", number: number)
            let incData = try! JSONEncoder().encode(incRequest)

            // Invoke the lambda function.

            let invokeOutput = try await lambdaClient.invoke(
                input: InvokeInput(
                    functionName: "lambda-basics-function",
                    payload: incData
                )
            )

            let response = try! JSONDecoder().decode(Response.self, from:invokeOutput.payload!)

            guard let answer = response.answer else {
                throw ExampleError.noAnswerReceived
            }
            return answer

        } catch {
            throw ExampleError.invokeError
        }
    }

    /// Invoke the calculator Lambda function.
    /// 
    /// - Parameters:
    ///   - lambdaClient: The `IAMClient` to use.
    ///   - action: Which arithmetic operation to perform: "plus", "minus",
    ///     "times", or "divided-by".
    ///   - x: The first number to use in the computation.
    ///   - y: The second number to use in the computation.
    ///
    /// - Throws: `ExampleError.noAnswerReceived`, `ExampleError.invokeError`
    ///
    /// - Returns: The computed answer as an `Int`.
    func invokeCalculator(lambdaClient: LambdaClient, action: String, x: Int, y: Int) async throws -> Int {
        do {
            let calcRequest = CalculatorRequest(action: action, x: x, y: y)
            let calcData = try! JSONEncoder().encode(calcRequest)

            // Invoke the lambda function.

            let invokeOutput = try await lambdaClient.invoke(
                input: InvokeInput(
                    functionName: "lambda-basics-function",
                    payload: calcData
                )
            )

            let response = try! JSONDecoder().decode(Response.self, from:invokeOutput.payload!)
            
            guard let answer = response.answer else {
                throw ExampleError.noAnswerReceived
            }
            return answer

        } catch {
            throw ExampleError.invokeError
        }

    }

    /// Perform the example's tasks.
    func basics() async throws {
        let iamClient = try await IAMClient(
            config: IAMClient.IAMClientConfiguration(region: region)
        )

        let lambdaClient = try await LambdaClient(
            config: LambdaClient.LambdaClientConfiguration(region: region)
        )

        /// The IAM role to use for the example.
        var iamRole: IAMClientTypes.Role
        
        // Look for the specified role. If it already exists, use it. If not,
        // create it and attach the desired policy to it.

        do {
            iamRole = try await getRole(iamClient: iamClient, roleName: role)
        } catch ExampleError.roleNotFound {
            // The role wasn't found, so create it and attach the needed
            // policy.
            
            iamRole = try await createRoleForLambda(iamClient: iamClient, roleName: role)

            do {
                _ = try await iamClient.attachRolePolicy(
                    input: AttachRolePolicyInput(policyArn: policyARN, roleName: role)
                )
            } catch {
                throw ExampleError.policyError
            }
        }

        // Give the policy time to attach to the role.

        sleep(5)

        // Look to see if the function already exists. If it does, throw an
        // error.

        if await doesLambdaFunctionExist(lambdaClient: lambdaClient, name: basicsFunctionName) {
            throw ExampleError.functionAlreadyExists
        }

        // Create, then invoke, the "increment" version of the calculator
        // function.

        print("Creating the increment Lambda function...")
        if try await createFunction(lambdaClient: lambdaClient, functionName: basicsFunctionName, 
                                  roleArn: iamRole.arn, path: incpath) {
            print("Running increment function calls...")
            for number in 0...4 {
                do {
                    let answer = try await invokeIncrement(lambdaClient: lambdaClient, number: number)
                    print("Increment \(number) = \(answer)")
                } catch {
                    print("Error incrementing \(number): ", error.localizedDescription)
                }
            }
        } else {
            print("*** Failed to create the increment function.")
        }
        
        // Enable debug logging.

        print("\nEnabling debug logging...")
        try await enableDebugLogging(lambdaClient: lambdaClient, functionName: basicsFunctionName)

        // Change it to a basic arithmetic calculator. Then invoke it a few
        // times.

        print("\nReplacing the Lambda function with a calculator...")

        if try await updateFunctionCode(lambdaClient: lambdaClient, functionName: basicsFunctionName, 
                                    path: calcpath) {
            print("Running calculator function calls...")
            for x in [6, 10] {
                for y in [2, 4] {
                    for action in ["plus", "minus", "times", "divided-by"] {
                        do {
                            let answer = try await invokeCalculator(lambdaClient: lambdaClient, action: action, x: x, y: y)
                            print("\(x) \(action) \(y) = \(answer)")
                        } catch {
                            print("Error calculating \(x) \(action) \(y): ", error.localizedDescription)
                        }
                    }
                }
            }
        }

        // List all lambda functions.

        let functionNames = try await getFunctionNames(lambdaClient: lambdaClient)

        if functionNames.count > 0 {
            print("\nAWS Lambda functions available on your account:")
            for name in functionNames {
                print("  \(name)")
            }
        }

        // Delete the lambda function.

        print("Deleting lambda function...")
        
        do {
            _ = try await lambdaClient.deleteFunction(
                input: DeleteFunctionInput(
                    functionName: "lambda-basics-function"
                )
            )
        } catch {
            print("Error: Unable to delete the function.")
        }
        
        // Detach the role from the policy, then delete the role.

        print("Deleting the AWS IAM role...")

        do {
            _ = try await iamClient.detachRolePolicy(
                input: DetachRolePolicyInput(
                    policyArn: policyARN,
                    roleName: role
                )
            )
            _ = try await iamClient.deleteRole(
                input: DeleteRoleInput(
                    roleName: role
                )
            )
        } catch {
            throw ExampleError.deleteRoleError
        }
    }
}

// -MARK: - Entry point

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.basics()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}


/// Errors thrown by the example's functions.
enum ExampleError: Error {
    /// An AWS Lambda function with the specified name already exists.
    case functionAlreadyExists
    /// The specified role doesn't exist.
    case roleNotFound
    /// Unable to create the role.
    case roleCreateError
    /// Unable to delete the role.
    case deleteRoleError
    /// Unable to attach a policy to the role.
    case policyError
    /// Unable to get the executable directory.
    case executableNotFound
    /// An error occurred creating a lambda function.
    case createLambdaError
    /// An error occurred invoking the lambda function.
    case invokeError
    /// No answer received from the invocation.
    case noAnswerReceived
    /// Unable to list the AWS Lambda functions.
    case listFunctionsError
    /// Unable to update the AWS Lambda function.
    case updateFunctionError
    /// Unable to update the function configuration.
    case updateFunctionConfigurationError
    /// The environment response is missing after an
    /// UpdateEnvironmentConfiguration attempt.
    case environmentResponseMissingError
    /// The environment variables are missing from the EnvironmentResponse and
    /// no errors occurred.
    case environmentVariablesMissingError
    /// The log level is incorrect after attempting to set it.
    case logLevelIncorrectError
    /// Unable to load the AWS Lambda function's Zip file.
    case zipFileReadError

    var errorDescription: String? {
        switch self {
        case .functionAlreadyExists:
            return "An AWS Lambda function with that name already exists."
        case .roleNotFound:
            return "The specified role doesn't exist."
        case .deleteRoleError:
            return "Unable to delete the AWS IAM role."
        case .roleCreateError:
            return "Unable to create the specified role."
        case .policyError:
            return "An error occurred attaching the policy to the role."
        case .executableNotFound:
            return "Unable to find the executable program directory."
        case .createLambdaError:
            return "An error occurred creating a lambda function."
        case .invokeError:
            return "An error occurred invoking a lambda function."
        case .noAnswerReceived:
            return "No answer received from the lambda function."
        case .listFunctionsError:
            return "Unable to list the AWS Lambda functions."
        case .updateFunctionError:
            return "Unable to update the AWS lambda function."
        case .updateFunctionConfigurationError:
            return "Unable to update the AWS lambda function configuration."
        case .environmentResponseMissingError:
            return "The environment is missing from the response after updating the function configuration."
        case .environmentVariablesMissingError:
            return "While no error occurred, no environment variables were returned following function configuration."
        case .logLevelIncorrectError:
            return "The log level is incorrect after attempting to set it to DEBUG."
        case .zipFileReadError:
            return "Unable to read the AWS Lambda function."
        }
    }
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [CreateFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/createfunction(input:))
  + [DeleteFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/deletefunction(input:))
  + [GetFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/getfunction(input:))
  + [Invoke](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/invoke(input:))
  + [ListFunctions](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/listfunctions(input:))
  + [UpdateFunctionCode](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/updatefunctioncode(input:))
  + [UpdateFunctionConfiguration](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/updatefunctionconfiguration(input:))

## アクション
<a name="actions"></a>

### `CreateFunction`
<a name="lambda_CreateFunction_swift_1_topic"></a>

次のコード例は、`CreateFunction` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSLambda
import Foundation

        do {
            // Read the Zip archive containing the AWS Lambda function.

            let zipUrl = URL(fileURLWithPath: path)
            let zipData = try Data(contentsOf: zipUrl)

            // Create the AWS Lambda function that runs the specified code,
            // using the name given on the command line. The Lambda function
            // will run using the Amazon Linux 2 runtime.

            _ = try await lambdaClient.createFunction(
                input: CreateFunctionInput(
                    code: LambdaClientTypes.FunctionCode(zipFile: zipData),
                    functionName: functionName,
                    handler: "handle",
                    role: roleArn,
                    runtime: .providedal2
                )
            )
        } catch {
            print("*** Error creating Lambda function:")
            dump(error)
            return false
        }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[CreateFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/createfunction(input:))」を参照してください。

### `DeleteFunction`
<a name="lambda_DeleteFunction_swift_1_topic"></a>

次のコード例は、`DeleteFunction` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSLambda
import Foundation

        do {
            _ = try await lambdaClient.deleteFunction(
                input: DeleteFunctionInput(
                    functionName: "lambda-basics-function"
                )
            )
        } catch {
            print("Error: Unable to delete the function.")
        }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[DeleteFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/deletefunction(input:))」を参照してください。

### `GetFunction`
<a name="lambda_GetFunction_swift_1_topic"></a>

次のコード例は、`GetFunction` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Detect whether or not the AWS Lambda function with the specified name
    /// exists, by requesting its function information.
    ///
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - name: The name of the AWS Lambda function to find.
    ///
    /// - Returns: `true` if the Lambda function exists. Otherwise `false`.
    func doesLambdaFunctionExist(lambdaClient: LambdaClient, name: String) async -> Bool {
        do {
            _ = try await lambdaClient.getFunction(
                input: GetFunctionInput(functionName: name)
            )
        } catch {
            return false
        }

        return true
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[GetFunction](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/getfunction(input:))」を参照してください。

### `Invoke`
<a name="lambda_Invoke_swift_1_topic"></a>

次のコード例は、`Invoke` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Invoke the Lambda function to increment a value.
    /// 
    /// - Parameters:
    ///   - lambdaClient: The `IAMClient` to use.
    ///   - number: The number to increment.
    ///
    /// - Throws: `ExampleError.noAnswerReceived`, `ExampleError.invokeError`
    ///
    /// - Returns: An integer number containing the incremented value.
    func invokeIncrement(lambdaClient: LambdaClient, number: Int) async throws -> Int {
        do {
            let incRequest = IncrementRequest(action: "increment", number: number)
            let incData = try! JSONEncoder().encode(incRequest)

            // Invoke the lambda function.

            let invokeOutput = try await lambdaClient.invoke(
                input: InvokeInput(
                    functionName: "lambda-basics-function",
                    payload: incData
                )
            )

            let response = try! JSONDecoder().decode(Response.self, from:invokeOutput.payload!)

            guard let answer = response.answer else {
                throw ExampleError.noAnswerReceived
            }
            return answer

        } catch {
            throw ExampleError.invokeError
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Invoke](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/invoke(input:))」を参照してください。

### `ListFunctions`
<a name="lambda_ListFunctions_swift_1_topic"></a>

次のコード例は、`ListFunctions` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Returns an array containing the names of all AWS Lambda functions
    /// available to the user.
    ///
    /// - Parameter lambdaClient: The `IAMClient` to use.
    ///
    /// - Throws: `ExampleError.listFunctionsError`
    ///
    /// - Returns: An array of lambda function name strings.
    func getFunctionNames(lambdaClient: LambdaClient) async throws -> [String] {
        let pages = lambdaClient.listFunctionsPaginated(
            input: ListFunctionsInput()
        )

        var functionNames: [String] = []

        for try await page in pages {
            guard let functions = page.functions else {
                throw ExampleError.listFunctionsError
            }

            for function in functions {
                functionNames.append(function.functionName ?? "<unknown>")
            }
        }

        return functionNames
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[ListFunctions](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/listfunctions(input:))」を参照してください。

### `UpdateFunctionCode`
<a name="lambda_UpdateFunctionCode_swift_1_topic"></a>

次のコード例は、`UpdateFunctionCode` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSLambda
import Foundation

        let zipUrl = URL(fileURLWithPath: path)
        let zipData: Data

        // Read the function's Zip file.

        do {
            zipData = try Data(contentsOf: zipUrl)
        } catch {
            throw ExampleError.zipFileReadError
        }

        // Update the function's code and wait for the updated version to be
        // ready for use.

        do {
            _ = try await lambdaClient.updateFunctionCode(
                input: UpdateFunctionCodeInput(
                    functionName: functionName,
                    zipFile: zipData
                )
            )
        } catch {
            return false
        }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[UpdateFunctionCode](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/updatefunctioncode(input:))」を参照してください。

### `UpdateFunctionConfiguration`
<a name="lambda_UpdateFunctionConfiguration_swift_1_topic"></a>

次のコード例は、`UpdateFunctionConfiguration` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/lambda/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSClientRuntime
import AWSLambda
import Foundation

    /// Tell the server-side component to log debug output by setting its
    /// environment's `LOG_LEVEL` to `DEBUG`.
    ///
    /// - Parameters:
    ///   - lambdaClient: The `LambdaClient` to use.
    ///   - functionName: The name of the AWS Lambda function to enable debug
    ///     logging for.
    ///
    /// - Throws: `ExampleError.environmentResponseMissingError`,
    ///   `ExampleError.updateFunctionConfigurationError`,
    ///   `ExampleError.environmentVariablesMissingError`,
    ///   `ExampleError.logLevelIncorrectError`,
    ///   `ExampleError.updateFunctionConfigurationError`
    func enableDebugLogging(lambdaClient: LambdaClient, functionName: String) async throws {
        let envVariables = [
            "LOG_LEVEL": "DEBUG"
        ]
        let environment = LambdaClientTypes.Environment(variables: envVariables)

        do {
            let output = try await lambdaClient.updateFunctionConfiguration(
                input: UpdateFunctionConfigurationInput(
                    environment: environment,
                    functionName: functionName
                )
            )

            guard let response = output.environment else {
                throw ExampleError.environmentResponseMissingError
            }

            if response.error != nil {
                throw ExampleError.updateFunctionConfigurationError
            }

            guard let retVariables = response.variables else {
                throw ExampleError.environmentVariablesMissingError
            }

            for envVar in retVariables {
                if envVar.key == "LOG_LEVEL" && envVar.value != "DEBUG" {
                    print("*** Log level is not set to DEBUG!")
                    throw ExampleError.logLevelIncorrectError
                }
            }
        } catch {
            throw ExampleError.updateFunctionConfigurationError
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[UpdateFunctionConfiguration](https://sdk.amazonaws.com/swift/api/awslambda/latest/documentation/awslambda/lambdaclient/updatefunctionconfiguration(input:))」を参照してください。

# SDK for Swift を使用した Amazon RDS の例
<a name="swift_1_rds_code_examples"></a>

次のコード例は、Amazon RDS で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="rds_Scenario_GetStartedInstances_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ カスタム DB パラメータグループを作成し、パラメータ値を設定します。
+ パラメータグループを使用するように設定した DB インスタンスを作成します。DB インスタンスにはデータベースも含まれています。
+ インスタンスのスナップショットを取得します。
+ インスタンスとパラメータグループを削除します。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。
`Package.swift` ファイル。  

```
// swift-tools-version: 5.9
//
// The swift-tools-version declares the minimum version of Swift required to
// build this package.

import PackageDescription

let package = Package(
    name: "rds-scenario",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13),
        .iOS(.v15)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.4.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "rds-scenario",
            dependencies: [
                .product(name: "AWSRDS", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources")

    ]
)
```
Swift コードファイル、`entry.swift`。  

```
// An example that shows how to use the AWS SDK for Swift to perform a variety
// of operations using Amazon Relational Database Service (RDS).
//

import ArgumentParser
import Foundation
import AWSRDS

struct ExampleCommand: ParsableCommand {
    @Option(help: "The AWS Region to run AWS API calls in.")
    var awsRegion = "us-east-1"
    @Option(help: "The username to use for the database administrator.")
    var dbUsername = "admin"
    @Option(help: "The password to use for the database administrator.")
    var dbPassword: String

    static var configuration = CommandConfiguration(
        commandName: "rds-scenario",
        abstract: """
        Performs various operations to demonstrate the use of Amazon RDS Instances
        using the AWS SDK for Swift.
        """,
        discussion: """
        """
    )

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let example = try await Example(region: awsRegion, username: dbUsername, password: dbPassword)

        await example.run()
    }
}

class Example {
    let rdsClient: RDSClient

    // Storage for AWS RDS properties

    let dbUsername: String
    let dbPassword: String
    var dbInstanceIdentifier: String
    var dbSnapshotIdentifier: String
    var dbParameterGroupName: String
    var dbParameterGroup: RDSClientTypes.DBParameterGroup?
    var selectedEngineVersion: String?

    init(region: String, username: String, password: String) async throws{
        let rdsConfig = try await RDSClient.RDSClientConfiguration(region: region)
        rdsClient = RDSClient(config: rdsConfig)

        dbUsername = username
        dbPassword = password
        dbParameterGroupName = ""
        dbInstanceIdentifier = ""
        dbSnapshotIdentifier = ""
    }

    /// The example's main body.
    func run() async {
        var parameterGroupFamilies: Set<String> = []

        //=====================================================================
        // 1. Get available database engine families for MySQL.
        //=====================================================================

        let engineVersions = await getDBEngineVersions(engineName: "mysql")

        for version in engineVersions {
            if version.dbParameterGroupFamily != nil {
                parameterGroupFamilies.insert(version.dbParameterGroupFamily!)
            }
        }

        if engineVersions.count > 0 {
            selectedEngineVersion = engineVersions.last!.engineVersion
        } else {
            print("*** Unable to find a valid database engine version. Canceling operations.")
            await cleanUp()
            return
        }

        print("Found \(parameterGroupFamilies.count) parameter group families:")
        for family in parameterGroupFamilies {
            print("    \(family)")
        }

        //=====================================================================
        // 2. Select an engine family and create a custom DB parameter group.
        //    We select a family by sorting the set of family names, then
        //    choosing the last one.
        //=====================================================================

        let sortedFamilies = parameterGroupFamilies.sorted()

        guard let selectedFamily = sortedFamilies.last else {
            print("*** Unable to find a database engine family. Canceling operations.")
            await cleanUp()
            return
        }

        print("Selected database engine family \(selectedFamily)")

        dbParameterGroupName = tempName(prefix: "rds-example")
        print("Creating a database parameter group named \(dbParameterGroupName) using \(selectedFamily)")
        dbParameterGroup = await createDBParameterGroup(groupName: dbParameterGroupName,
                                                        familyName: selectedFamily)

        //=====================================================================
        // 3. Get the parameter group's details.
        //=====================================================================

        print("Getting the database parameter group list...")
        let dbParameterGroupList = await describeDBParameterGroups(groupName: dbParameterGroupName)
        guard let dbParameterGroupList else {
            await cleanUp()
            return
        }

        print("Found \(dbParameterGroupList.count) parameter groups...")
        for group in dbParameterGroupList {
            print("    \(group.dbParameterGroupName ?? "<unknown>")")
        }
        print()

        //=====================================================================
        // 4. Get a list of the parameter group's parameters. This list is
        //    likely to be long, so use pagination. Find the
        //    auto_increment_offset and auto_increment_increment parameters.
        //=====================================================================

        let parameters = await describeDBParameters(groupName: dbParameterGroupName)
        
        //=====================================================================
        // 5. Parse and display each parameter's name, description, and
        //    allowed values.
        //=====================================================================

        for parameter in parameters {
            let name = parameter.parameterName
            guard let name else {
                print("*** Unable to get parameter name!")
                continue
            }

            if name == "auto_increment_offset" || name == "auto_increment_increment" {
                print("Parameter \(name):")
                print("          Value: \(parameter.parameterValue ?? "<undefined>")")
                print("      Data type: \(parameter.dataType ?? "<unknown>")")
                print("    Description: \(parameter.description ?? "")")
                print(" Allowed values: \(parameter.allowedValues ?? "<unspecified")")
                print(String(repeating: "=", count: 78))
            }
        }

        //=====================================================================
        // 6. Modify both the auto_increment_offset and
        //    auto_increment_increment parameters in one call in the custom
        //    parameter group. Set their parameterValue fields to a new
        //    permitted value.
        //=====================================================================

        print("Setting auto_increment_offset and auto_increment_increment both to 5...")
        await modifyDBParameters(groupName: dbParameterGroupName)

        //=====================================================================
        // 7. Get and display the updated parameters, specifying a source of
        //    "user" to get only the modified parameters.
        //=====================================================================

        let updatedParameters = await describeDBParameters(groupName: dbParameterGroupName, source: "user")

        for parameter in updatedParameters {
            let name = parameter.parameterName
            guard let name else {
                print("*** Unable to get parameter name!")
                continue
            }

            print("Parameter \(name):")
            print("          Value: \(parameter.parameterValue ?? "<undefined>")")
            print("      Data type: \(parameter.dataType ?? "<unknown>")")
            print("    Description: \(parameter.description ?? "")")
            print(" Allowed values: \(parameter.allowedValues ?? "<unspecified")")
            print(String(repeating: "=", count: 78))
        }

        //=====================================================================
        // 8. Get a list of allowed engine versions using
        //    DescribeRDSEngineVersions.
        //=====================================================================

        await listAllowedEngines(family: selectedFamily)

        //=====================================================================
        // 9. Get a list of micro instance classes available for the selected
        //    engine and engine version.
        //=====================================================================

        let dbInstanceClass = await chooseMicroInstance(engine: "mysql", engineVersion: selectedEngineVersion)
        guard let dbInstanceClass else {
            print("Did not get a valid instance class. Canceling operations.")
            await cleanUp()
            return
        }

        //=====================================================================
        // 10. Create an RDS database that contains a MySQL database and uses
        //     the parameter group we created.
        //=====================================================================
        
        print("Creating the database instance...")

        guard let instanceClass = dbInstanceClass.dbInstanceClass else {
            print("Instance class name is unknown. Canceling operations.")
            await cleanUp()
            return
        }

        dbInstanceIdentifier = tempName(prefix: "sample-identifier")
        let dbInstanceArn = await createDBInstance(
            name: "SampleDatabase\(Int.random(in: 1000000..<1000000000))",
            instanceIdentifier: dbInstanceIdentifier,
            parameterGroupName: dbParameterGroupName,
            engine: "mysql",
            engineVersion: selectedEngineVersion!,
            instanceClass: instanceClass,
            username: dbUsername,
            password: dbPassword
        )

        if dbInstanceArn == nil {
            await cleanUp()
            return
        }

        //=====================================================================
        // 11. Wait for the database instance to be ready by calling
        //     DescribeDBInstances repeatedly until it reports
        //     dbInstanceStatus as "available". This can take upwards of 10
        //     minutes, let the user know that.
        //=====================================================================

        guard let endpoint = await waitUntilDBInstanceReady(instanceIdentifier: dbInstanceIdentifier) else {
            print("\nDid not get a valid endpoint from AWS RDS.")
            await cleanUp()
            return
        }
        
        guard let endpointAddress = endpoint.address else {
            print("\nNo endpoint address returned.")
            await cleanUp()
            return
        }
        guard let endpointPort = endpoint.port else {
            print("\nNo endpoint port returned.")
            await cleanUp()
            return
        }

        //=====================================================================
        // 12. Display connection information for the database instance.
        //=====================================================================

        print("\nTo connect to the new database instance using 'mysql' from the shell:")
        print("    mysql -h \(endpointAddress) -P \(endpointPort) -u \(self.dbUsername)")

        //=====================================================================
        // 13. Create a snapshot of the database instance.
        //=====================================================================

        dbSnapshotIdentifier = tempName(prefix: "sample-snapshot")
        await createDBSnapshot(instanceIdentifier: dbInstanceIdentifier, snapshotIdentifier: dbSnapshotIdentifier)

        //=====================================================================
        // 14. Wait for the snapshot to be ready.
        //=====================================================================

        await waitUntilDBSnapshotReady(instanceIdentifier: dbInstanceIdentifier, snapshotIdentifier: dbSnapshotIdentifier)

        // That's it! Clean up and exit!

        print("Example complete! Cleaning up...")
        await cleanUp()
    }

    /// Clean up by discarding and closing down all allocated EC2 items. 
    func cleanUp() async {
        print("Deleting the database instance \(dbInstanceIdentifier)...")
        await deleteDBInstance(instanceIdentifier: dbInstanceIdentifier)
        await waitUntilDBInstanceDeleted(instanceIdentifier: dbInstanceIdentifier)

        print("Deleting the database parameter group \(dbParameterGroupName)...")
        await deleteDBParameterGroup(groupName: dbParameterGroupName)
    }

    /// Get all the database engine versions available for the specified
    /// database engine.
    /// 
    /// - Parameter engineName: The name of the database engine to query.
    /// 
    /// - Returns: An array of `RDSClientTypes.DBEngineVersion` structures,
    ///   each describing one supported version of the specified database.
    func getDBEngineVersions(engineName: String) async -> [RDSClientTypes.DBEngineVersion] {
        do {
            let output = try await rdsClient.describeDBEngineVersions(
                input: DescribeDBEngineVersionsInput(
                    engine: engineName
                )
            )

            return output.dbEngineVersions ?? []
        } catch {
            return []
        }
    }

    /// Create a new database parameter group with the specified name.
    /// 
    /// - Parameters:
    ///   - groupName: The name of the new parameter group.
    ///   - familyName: The name of the parameter group family.
    /// - Returns: 
    func createDBParameterGroup(groupName: String, familyName: String) async -> RDSClientTypes.DBParameterGroup? {
        do {
            let output = try await rdsClient.createDBParameterGroup(
                input: CreateDBParameterGroupInput(
                    dbParameterGroupFamily: familyName,
                    dbParameterGroupName: groupName,
                    description: "Created using the AWS SDK for Swift"
                )
            )
            return output.dbParameterGroup
        } catch {
            print("*** Error creating the parameter group: \(error.localizedDescription)")
            return nil
        }
    }

    /// Get descriptions of the database parameter groups matching the given
    /// name.
    ///
    /// - Parameter groupName: The name of the parameter group to describe.
    /// 
    /// - Returns: An array of [RDSClientTypes.DBParameterGroup] objects
    ///   describing the parameter group.
    func describeDBParameterGroups(groupName: String) async -> [RDSClientTypes.DBParameterGroup]? {
        do {
            let output = try await rdsClient.describeDBParameterGroups(
                input: DescribeDBParameterGroupsInput(
                    dbParameterGroupName: groupName
                )
            )
            return output.dbParameterGroups
        } catch {
            print("*** Error getting the database parameter group's details: \(error.localizedDescription)")
            return nil
        }
    }

    /// Returns the detailed parameter list for the specified database
    /// parameter group.
    /// 
    /// - Parameters:
    ///   - groupName: The name of the parameter group to return parameters for.
    ///   - source: The types of parameters to return (`user`, `system`, or
    ///     `engine-default`).
    /// 
    /// - Returns: An array of `RdSClientTypes.Parameter` objects, each
    ///   describing one of the group's parameters.
    func describeDBParameters(groupName: String, source: String? = nil) async -> [RDSClientTypes.Parameter] {
        var parameterList: [RDSClientTypes.Parameter] = []

        do {
            let pages = rdsClient.describeDBParametersPaginated(
                input: DescribeDBParametersInput(
                    dbParameterGroupName: groupName,
                    source: source
                )
            )

            for try await page in pages {
                guard let parameters = page.parameters else {
                    return []
                }

                parameterList += parameters
            }
        } catch {
            print("*** Error getting database parameters: \(error.localizedDescription)")
            return []
        }

        return parameterList
    }

    /// Demonstrates modifying two of the specified database parameter group's
    /// parameters.
    /// 
    /// - Parameter groupName: The name of the parameter group to change
    ///   parameters for.
    func modifyDBParameters(groupName: String) async {
        let parameter1 = RDSClientTypes.Parameter(
            applyMethod: RDSClientTypes.ApplyMethod.immediate,
            parameterName: "auto_increment_offset",
            parameterValue: "5"
        )
        let parameter2 = RDSClientTypes.Parameter(
            applyMethod: RDSClientTypes.ApplyMethod.immediate,
            parameterName: "auto_increment_increment",
            parameterValue: "5"
        )

        let parameterList = [parameter1, parameter2]

        do {
            _ = try await rdsClient.modifyDBParameterGroup(
                input: ModifyDBParameterGroupInput(
                    dbParameterGroupName: groupName,
                    parameters: parameterList
                )
            )

            print("Successfully modified the parameter group \(groupName).")
        } catch {
            print("*** Error modifying the parameter group \(groupName): \(error.localizedDescription)")
        }
    }

    /// Output a list of the database engine versions supported by the
    /// specified family.
    /// 
    /// - Parameter family: The family for which to list allowed database
    ///   engines.
    func listAllowedEngines(family: String?) async {
        do {
            let output = try await rdsClient.describeDBEngineVersions(
                input: DescribeDBEngineVersionsInput(
                    dbParameterGroupFamily: family,
                    engine: "mysql"
                )
            )

            guard let engineVersions = output.dbEngineVersions else {
                print("No engine versions returned.")
                return
            }

            print("Found \(engineVersions.count) database engine versions:")
            for version in engineVersions {
                print("    \(version.engineVersion ?? "<unknown>"): \(version.dbEngineDescription ?? "")")
            }
        } catch {
            print("*** Error getting database engine version list: \(error.localizedDescription)")
            return
        }
    }

    /// Print a list of available database instances with "micro" in the class
    /// name, then return one of them to be used by other code.
    /// 
    /// - Parameters:
    ///   - engine: The database engine for which to list database instance
    ///     classes.
    ///   - engineVersion: The database version for which to list instances.
    /// 
    /// - Returns: An `RDSClientTypes.OrderableDBInstanceOption` describing
    ///   the selected instance type.
    func chooseMicroInstance(engine: String = "mysql", engineVersion: String? = nil) async -> RDSClientTypes.OrderableDBInstanceOption? {
        do {
            let pages = rdsClient.describeOrderableDBInstanceOptionsPaginated(
                input: DescribeOrderableDBInstanceOptionsInput(
                    engine: engine,
                    engineVersion: engineVersion
                )
            )

            var optionsList: [RDSClientTypes.OrderableDBInstanceOption] = []

            for try await page in pages {
                guard let orderableDBInstanceOptions = page.orderableDBInstanceOptions else {
                    continue
                }

                for dbInstanceOption in orderableDBInstanceOptions {
                    guard let className = dbInstanceOption.dbInstanceClass else {
                        continue
                    }
                    if className.contains("micro") {
                        optionsList.append(dbInstanceOption)
                    }
                }
            }

            print("Found \(optionsList.count) database instances of 'micro' class types:")
            for dbInstanceOption in optionsList {
                print("    \(dbInstanceOption.engine ?? "<unknown>") \(dbInstanceOption.engineVersion ?? "<unknown>") (\(dbInstanceOption.dbInstanceClass ?? "<unknown class>"))")
            }

            return optionsList[0]
        } catch {
            print("*** Error getting a list of orderable instance options: \(error.localizedDescription)")
            return nil
        }
    }

    /// Create a new database instance.
    /// 
    /// - Parameters:
    ///   - name: The name of the database to create.
    ///   - instanceIdentifier: The identifier to give the new database
    ///     instance.
    ///   - parameterGroupName: The name of the parameter group to associate
    ///     with the new database instance.
    ///   - engine: The database engine to use.
    ///   - engineVersion: The version of the database given by `engine` to
    ///     use.
    ///   - instanceClass: The memory and compute capacity of the database
    ///     instance, such as `db.m5.large``.
    ///   - username: The admin user's username to establish for the new
    ///     instance.
    ///   - password: The password to use for the specified user's access.
    /// 
    /// - Returns: A string indicating the ARN of the newly created database
    ///   instance, or nil if the instance couldn't be created.
    func createDBInstance(name: String, instanceIdentifier: String, parameterGroupName: String,
                          engine: String, engineVersion: String, instanceClass: String,
                          username: String, password: String) async -> String? {
        do {
            let output = try await rdsClient.createDBInstance(
                input: CreateDBInstanceInput(
                    allocatedStorage: 100,
                    dbInstanceClass: instanceClass,
                    dbInstanceIdentifier: instanceIdentifier,
                    dbName: name,
                    dbParameterGroupName: parameterGroupName,
                    engine: engine,
                    engineVersion: engineVersion,
                    masterUserPassword: password,
                    masterUsername: username,
                    storageType: "gp2"
                )
            )

            guard let dbInstance = output.dbInstance else {
                print("*** Unable to get the database instance.")
                return nil
            }

            return dbInstance.dbInstanceArn
        } catch {
            print("*** An error occurred while creating the database instance: \(error.localizedDescription)")
            return nil
        }
    }

    /// Wait until the specified database is available to use.
    ///
    /// - Parameter instanceIdentifier: The database instance identifier of the
    ///   database to wait for.
    func waitUntilDBInstanceReady(instanceIdentifier: String) async -> RDSClientTypes.Endpoint? {
        do {
            putString("Waiting for the database instance to be ready to use. This may take 10 minutes or more...")
            while true {
                let output = try await rdsClient.describeDBInstances(
                    input: DescribeDBInstancesInput(
                        dbInstanceIdentifier: instanceIdentifier
                    )
                )

                guard let instanceList = output.dbInstances else {
                    continue
                }

                for instance in instanceList {
                    let status = instance.dbInstanceStatus

                    guard let status else {
                        print("\nUnable to determine the status.")
                        continue
                    }

                    if status.contains("available") {
                        return instance.endpoint
                    } else {
                        putString(".")
                        do {
                            try await Task.sleep(for: .seconds(15))
                        } catch {
                            print("*** Error pausing the task!")
                        }
                    }
                }
            }
        } catch {
            print("*** Unable to wait until the database is ready: \(error.localizedDescription)")
            return nil
        }
    }

    /// Create a snapshot of the specified name.
    /// 
    /// - Parameters:
    ///   - instanceIdentifier: The identifier of the database instance to
    ///     snapshot.
    ///   - snapshotIdentifier: A unique identifier to give the newly-created
    ///     snapshot.
    func createDBSnapshot(instanceIdentifier: String, snapshotIdentifier: String) async {
        do {
            let output = try await rdsClient.createDBSnapshot(
                input: CreateDBSnapshotInput(
                    dbInstanceIdentifier: instanceIdentifier,
                    dbSnapshotIdentifier: snapshotIdentifier
                )
            )

            guard let snapshot = output.dbSnapshot else {
                print("No snapshot returned.")
                return
            }

            print("The snapshot has been created with ID \(snapshot.dbiResourceId ?? "<unknown>")")
        } catch {
            print("*** Unable to create the database snapshot named \(snapshotIdentifier): \(error.localizedDescription)")
        }
    }

    /// Wait until the specified database snapshot is available to use.
    /// 
    /// - Parameters:
    ///   - instanceIdentifier: The identifier of the database for which the
    ///     snapshot was taken.
    ///   - snapshotIdentifier: The identifier of the snapshot to wait for.
    func waitUntilDBSnapshotReady(instanceIdentifier: String, snapshotIdentifier: String) async {
        var snapshotReady = false

        putString("Waiting for the snapshot to be ready...")

        do {
            while !snapshotReady {
                let output = try await rdsClient.describeDBSnapshots(
                    input: DescribeDBSnapshotsInput(
                        dbInstanceIdentifier: instanceIdentifier,
                        dbSnapshotIdentifier: snapshotIdentifier
                    )
                )

                guard let snapshotList = output.dbSnapshots else {
                    return
                }

                for snapshot in snapshotList {
                    guard let snapshotReadyStr = snapshot.status else {
                        return
                    }

                    if snapshotReadyStr.contains("available") {
                        snapshotReady = true
                        print()
                    } else {
                        putString(".")
                        do {
                            try await Task.sleep(for: .seconds(15))
                        } catch {
                            print("\n*** Error pausing the task!")
                        }
                    }
                }
            }
        } catch {
            print("\n*** Unable to wait for the database snapshot to be ready: \(error.localizedDescription)")
        }
    }

    /// Delete the specified database instance.
    /// 
    /// - Parameter instanceIdentifier: The identifier of the database
    ///   instance to delete.
    func deleteDBInstance(instanceIdentifier: String) async {
        do {
            _ = try await rdsClient.deleteDBInstance(
                input: DeleteDBInstanceInput(
                    dbInstanceIdentifier: instanceIdentifier,
                    deleteAutomatedBackups: true,
                    skipFinalSnapshot: true
                )
            )
        } catch {
            print("*** Error deleting the database instance \(instanceIdentifier): \(error.localizedDescription)")
        }
    }

    /// Wait until the specified database instance has been deleted.
    /// 
    /// - Parameter instanceIdentifier: The identifier of the database
    ///   instance to wait for.
    func waitUntilDBInstanceDeleted(instanceIdentifier: String) async {
        putString("Waiting for the database instance to be deleted. This may take a few minutes...")
        do {
            var isDatabaseDeleted = false
            var foundInstance = false

            while !isDatabaseDeleted {
                let output = try await rdsClient.describeDBInstances(input: DescribeDBInstancesInput())
                guard let instanceList = output.dbInstances else {
                    return
                }

                foundInstance = false

                for instance in instanceList {
                    guard let foundInstanceIdentifier = instance.dbInstanceIdentifier else {
                        continue
                    }

                    if instanceIdentifier == foundInstanceIdentifier {
                        foundInstance = true
                        break
                    } else {
                        putString(".")
                        do {
                            try await Task.sleep(for: .seconds(15))
                        } catch {
                            print("\n*** Error pausing the task!")
                        }
                    }
                }
                if !foundInstance {
                    isDatabaseDeleted = true
                    print()
                }
            }
        } catch {
            print("\n*** Error waiting for the database instance to be deleted: \(error.localizedDescription)")
        }
    }

    /// Delete the specified database parameter group.
    /// 
    /// - Parameter groupName: The name of the parameter group to delete.
    func deleteDBParameterGroup(groupName: String) async {
        do {
            _ = try await rdsClient.deleteDBParameterGroup(
                input: DeleteDBParameterGroupInput(
                    dbParameterGroupName: groupName
                )
            )
        } catch {
            print("*** Error deleting the database parameter group \(groupName): \(error.localizedDescription)")
        }
    }

    /// Generate and return a unique file name that begins with the specified
    /// string.
    ///
    /// - Parameters:
    ///   - prefix: Text to use at the beginning of the returned name.
    ///
    /// - Returns: A string containing a unique filename that begins with the
    ///   specified `prefix`.
    ///
    /// The returned name uses a random number between 1 million and 1 billion to
    /// provide reasonable certainty of uniqueness for the purposes of this
    /// example.
    func tempName(prefix: String) -> String {
        return "\(prefix)-\(Int.random(in: 1000000..<1000000000))"
    }

    /// Print a string to standard output without a trailing newline, and
    /// without buffering.
    /// 
    /// - Parameter str: The string to output.
    func putString(_ str: String = "") {
        if str.length >= 1 {
            let data = str.data(using: .utf8)
            guard let data else {
                return
            }
            FileHandle.standardOutput.write(data)
        }
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [CreateDBInstance](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/createdbinstance(input:))
  + [CreateDBParameterGroup](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/createdbparametergroup(input:))
  + [CreateDBSnapshot](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/createdbsnapshot(input:))
  + [DeleteDBInstance](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/deletedbinstance(input:))
  + [DeleteDBParameterGroup](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/deletedbparametergroup(input:))
  + [DescribeDBEngineVersions](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbengineversions(input:))
  + [DescribeDBInstances](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbinstances(input:))
  + [DescribeDBParameterGroups](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbparametergroups(input:))
  + [DescribeDBParameters](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbparameters(input:))
  + [DescribeDBSnapshots](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbsnapshots(input:))
  + [DescribeOrderableDBInstanceOptions](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describeorderabledbinstanceoptions(input:))
  + [ModifyDBParameterGroup](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/modifydbparametergroup(input:))

## アクション
<a name="actions"></a>

### `CreateDBInstance`
<a name="rds_CreateDBInstance_swift_1_topic"></a>

次のコード例は、`CreateDBInstance` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Create a new database instance.
    /// 
    /// - Parameters:
    ///   - name: The name of the database to create.
    ///   - instanceIdentifier: The identifier to give the new database
    ///     instance.
    ///   - parameterGroupName: The name of the parameter group to associate
    ///     with the new database instance.
    ///   - engine: The database engine to use.
    ///   - engineVersion: The version of the database given by `engine` to
    ///     use.
    ///   - instanceClass: The memory and compute capacity of the database
    ///     instance, such as `db.m5.large``.
    ///   - username: The admin user's username to establish for the new
    ///     instance.
    ///   - password: The password to use for the specified user's access.
    /// 
    /// - Returns: A string indicating the ARN of the newly created database
    ///   instance, or nil if the instance couldn't be created.
    func createDBInstance(name: String, instanceIdentifier: String, parameterGroupName: String,
                          engine: String, engineVersion: String, instanceClass: String,
                          username: String, password: String) async -> String? {
        do {
            let output = try await rdsClient.createDBInstance(
                input: CreateDBInstanceInput(
                    allocatedStorage: 100,
                    dbInstanceClass: instanceClass,
                    dbInstanceIdentifier: instanceIdentifier,
                    dbName: name,
                    dbParameterGroupName: parameterGroupName,
                    engine: engine,
                    engineVersion: engineVersion,
                    masterUserPassword: password,
                    masterUsername: username,
                    storageType: "gp2"
                )
            )

            guard let dbInstance = output.dbInstance else {
                print("*** Unable to get the database instance.")
                return nil
            }

            return dbInstance.dbInstanceArn
        } catch {
            print("*** An error occurred while creating the database instance: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[CreateDBInstance](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/createdbinstance(input:))」を参照してください。

### `CreateDBParameterGroup`
<a name="rds_CreateDBParameterGroup_swift_1_topic"></a>

次のコード例は、`CreateDBParameterGroup` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Create a new database parameter group with the specified name.
    /// 
    /// - Parameters:
    ///   - groupName: The name of the new parameter group.
    ///   - familyName: The name of the parameter group family.
    /// - Returns: 
    func createDBParameterGroup(groupName: String, familyName: String) async -> RDSClientTypes.DBParameterGroup? {
        do {
            let output = try await rdsClient.createDBParameterGroup(
                input: CreateDBParameterGroupInput(
                    dbParameterGroupFamily: familyName,
                    dbParameterGroupName: groupName,
                    description: "Created using the AWS SDK for Swift"
                )
            )
            return output.dbParameterGroup
        } catch {
            print("*** Error creating the parameter group: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[CreateDBParameterGroup](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/createdbparametergroup(input:))」を参照してください。

### `CreateDBSnapshot`
<a name="rds_CreateDBSnapshot_swift_1_topic"></a>

次のコード例は、`CreateDBSnapshot` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Create a snapshot of the specified name.
    /// 
    /// - Parameters:
    ///   - instanceIdentifier: The identifier of the database instance to
    ///     snapshot.
    ///   - snapshotIdentifier: A unique identifier to give the newly-created
    ///     snapshot.
    func createDBSnapshot(instanceIdentifier: String, snapshotIdentifier: String) async {
        do {
            let output = try await rdsClient.createDBSnapshot(
                input: CreateDBSnapshotInput(
                    dbInstanceIdentifier: instanceIdentifier,
                    dbSnapshotIdentifier: snapshotIdentifier
                )
            )

            guard let snapshot = output.dbSnapshot else {
                print("No snapshot returned.")
                return
            }

            print("The snapshot has been created with ID \(snapshot.dbiResourceId ?? "<unknown>")")
        } catch {
            print("*** Unable to create the database snapshot named \(snapshotIdentifier): \(error.localizedDescription)")
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[CreateDBSnapshot](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/createdbsnapshot(input:))」を参照してください。

### `DeleteDBInstance`
<a name="rds_DeleteDBInstance_swift_1_topic"></a>

次のコード例は、`DeleteDBInstance` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Delete the specified database instance.
    /// 
    /// - Parameter instanceIdentifier: The identifier of the database
    ///   instance to delete.
    func deleteDBInstance(instanceIdentifier: String) async {
        do {
            _ = try await rdsClient.deleteDBInstance(
                input: DeleteDBInstanceInput(
                    dbInstanceIdentifier: instanceIdentifier,
                    deleteAutomatedBackups: true,
                    skipFinalSnapshot: true
                )
            )
        } catch {
            print("*** Error deleting the database instance \(instanceIdentifier): \(error.localizedDescription)")
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DeleteDBInstance](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/deletedbinstance(input:))」を参照してください。

### `DeleteDBParameterGroup`
<a name="rds_DeleteDBParameterGroup_swift_1_topic"></a>

次のコード例は、`DeleteDBParameterGroup` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Delete the specified database parameter group.
    /// 
    /// - Parameter groupName: The name of the parameter group to delete.
    func deleteDBParameterGroup(groupName: String) async {
        do {
            _ = try await rdsClient.deleteDBParameterGroup(
                input: DeleteDBParameterGroupInput(
                    dbParameterGroupName: groupName
                )
            )
        } catch {
            print("*** Error deleting the database parameter group \(groupName): \(error.localizedDescription)")
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DeleteDBParameterGroup](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/deletedbparametergroup(input:))」を参照してください。

### `DescribeDBEngineVersions`
<a name="rds_DescribeDBEngineVersions_swift_1_topic"></a>

次のコード例は、`DescribeDBEngineVersions` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Get all the database engine versions available for the specified
    /// database engine.
    /// 
    /// - Parameter engineName: The name of the database engine to query.
    /// 
    /// - Returns: An array of `RDSClientTypes.DBEngineVersion` structures,
    ///   each describing one supported version of the specified database.
    func getDBEngineVersions(engineName: String) async -> [RDSClientTypes.DBEngineVersion] {
        do {
            let output = try await rdsClient.describeDBEngineVersions(
                input: DescribeDBEngineVersionsInput(
                    engine: engineName
                )
            )

            return output.dbEngineVersions ?? []
        } catch {
            return []
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DescribeDBEngineVersions](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbengineversions(input:))」を参照してください。

### `DescribeDBInstances`
<a name="rds_DescribeDBInstances_swift_1_topic"></a>

次のコード例は、`DescribeDBInstances` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Wait until the specified database is available to use.
    ///
    /// - Parameter instanceIdentifier: The database instance identifier of the
    ///   database to wait for.
    func waitUntilDBInstanceReady(instanceIdentifier: String) async -> RDSClientTypes.Endpoint? {
        do {
            putString("Waiting for the database instance to be ready to use. This may take 10 minutes or more...")
            while true {
                let output = try await rdsClient.describeDBInstances(
                    input: DescribeDBInstancesInput(
                        dbInstanceIdentifier: instanceIdentifier
                    )
                )

                guard let instanceList = output.dbInstances else {
                    continue
                }

                for instance in instanceList {
                    let status = instance.dbInstanceStatus

                    guard let status else {
                        print("\nUnable to determine the status.")
                        continue
                    }

                    if status.contains("available") {
                        return instance.endpoint
                    } else {
                        putString(".")
                        do {
                            try await Task.sleep(for: .seconds(15))
                        } catch {
                            print("*** Error pausing the task!")
                        }
                    }
                }
            }
        } catch {
            print("*** Unable to wait until the database is ready: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DescribeDBInstances](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbinstances(input:))」を参照してください。

### `DescribeDBParameterGroups`
<a name="rds_DescribeDBParameterGroups_swift_1_topic"></a>

次のコード例は、`DescribeDBParameterGroups` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Get descriptions of the database parameter groups matching the given
    /// name.
    ///
    /// - Parameter groupName: The name of the parameter group to describe.
    /// 
    /// - Returns: An array of [RDSClientTypes.DBParameterGroup] objects
    ///   describing the parameter group.
    func describeDBParameterGroups(groupName: String) async -> [RDSClientTypes.DBParameterGroup]? {
        do {
            let output = try await rdsClient.describeDBParameterGroups(
                input: DescribeDBParameterGroupsInput(
                    dbParameterGroupName: groupName
                )
            )
            return output.dbParameterGroups
        } catch {
            print("*** Error getting the database parameter group's details: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DescribeDBParameterGroups](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbparametergroups(input:))」を参照してください。

### `DescribeDBParameters`
<a name="rds_DescribeDBParameters_swift_1_topic"></a>

次のコード例は、`DescribeDBParameters` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Returns the detailed parameter list for the specified database
    /// parameter group.
    /// 
    /// - Parameters:
    ///   - groupName: The name of the parameter group to return parameters for.
    ///   - source: The types of parameters to return (`user`, `system`, or
    ///     `engine-default`).
    /// 
    /// - Returns: An array of `RdSClientTypes.Parameter` objects, each
    ///   describing one of the group's parameters.
    func describeDBParameters(groupName: String, source: String? = nil) async -> [RDSClientTypes.Parameter] {
        var parameterList: [RDSClientTypes.Parameter] = []

        do {
            let pages = rdsClient.describeDBParametersPaginated(
                input: DescribeDBParametersInput(
                    dbParameterGroupName: groupName,
                    source: source
                )
            )

            for try await page in pages {
                guard let parameters = page.parameters else {
                    return []
                }

                parameterList += parameters
            }
        } catch {
            print("*** Error getting database parameters: \(error.localizedDescription)")
            return []
        }

        return parameterList
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DescribeDBParameters](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbparameters(input:))」を参照してください。

### `DescribeDBSnapshots`
<a name="rds_DescribeDBSnapshots_swift_1_topic"></a>

次のコード例は、`DescribeDBSnapshots` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Wait until the specified database snapshot is available to use.
    /// 
    /// - Parameters:
    ///   - instanceIdentifier: The identifier of the database for which the
    ///     snapshot was taken.
    ///   - snapshotIdentifier: The identifier of the snapshot to wait for.
    func waitUntilDBSnapshotReady(instanceIdentifier: String, snapshotIdentifier: String) async {
        var snapshotReady = false

        putString("Waiting for the snapshot to be ready...")

        do {
            while !snapshotReady {
                let output = try await rdsClient.describeDBSnapshots(
                    input: DescribeDBSnapshotsInput(
                        dbInstanceIdentifier: instanceIdentifier,
                        dbSnapshotIdentifier: snapshotIdentifier
                    )
                )

                guard let snapshotList = output.dbSnapshots else {
                    return
                }

                for snapshot in snapshotList {
                    guard let snapshotReadyStr = snapshot.status else {
                        return
                    }

                    if snapshotReadyStr.contains("available") {
                        snapshotReady = true
                        print()
                    } else {
                        putString(".")
                        do {
                            try await Task.sleep(for: .seconds(15))
                        } catch {
                            print("\n*** Error pausing the task!")
                        }
                    }
                }
            }
        } catch {
            print("\n*** Unable to wait for the database snapshot to be ready: \(error.localizedDescription)")
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DescribeDBSnapshots](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describedbsnapshots(input:))」を参照してください。

### `DescribeOrderableDBInstanceOptions`
<a name="rds_DescribeOrderableDBInstanceOptions_swift_1_topic"></a>

次のコード例は、`DescribeOrderableDBInstanceOptions` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Print a list of available database instances with "micro" in the class
    /// name, then return one of them to be used by other code.
    /// 
    /// - Parameters:
    ///   - engine: The database engine for which to list database instance
    ///     classes.
    ///   - engineVersion: The database version for which to list instances.
    /// 
    /// - Returns: An `RDSClientTypes.OrderableDBInstanceOption` describing
    ///   the selected instance type.
    func chooseMicroInstance(engine: String = "mysql", engineVersion: String? = nil) async -> RDSClientTypes.OrderableDBInstanceOption? {
        do {
            let pages = rdsClient.describeOrderableDBInstanceOptionsPaginated(
                input: DescribeOrderableDBInstanceOptionsInput(
                    engine: engine,
                    engineVersion: engineVersion
                )
            )

            var optionsList: [RDSClientTypes.OrderableDBInstanceOption] = []

            for try await page in pages {
                guard let orderableDBInstanceOptions = page.orderableDBInstanceOptions else {
                    continue
                }

                for dbInstanceOption in orderableDBInstanceOptions {
                    guard let className = dbInstanceOption.dbInstanceClass else {
                        continue
                    }
                    if className.contains("micro") {
                        optionsList.append(dbInstanceOption)
                    }
                }
            }

            print("Found \(optionsList.count) database instances of 'micro' class types:")
            for dbInstanceOption in optionsList {
                print("    \(dbInstanceOption.engine ?? "<unknown>") \(dbInstanceOption.engineVersion ?? "<unknown>") (\(dbInstanceOption.dbInstanceClass ?? "<unknown class>"))")
            }

            return optionsList[0]
        } catch {
            print("*** Error getting a list of orderable instance options: \(error.localizedDescription)")
            return nil
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DescribeOrderableDBInstanceOptions](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/describeorderabledbinstanceoptions(input:))」を参照してください。

### `ModifyDBParameterGroup`
<a name="rds_ModifyDBParameterGroup_swift_1_topic"></a>

次のコード例は、`ModifyDBParameterGroup` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/rds#code-examples)での設定と実行の方法を確認してください。

```
import AWSRDS

    /// Demonstrates modifying two of the specified database parameter group's
    /// parameters.
    /// 
    /// - Parameter groupName: The name of the parameter group to change
    ///   parameters for.
    func modifyDBParameters(groupName: String) async {
        let parameter1 = RDSClientTypes.Parameter(
            applyMethod: RDSClientTypes.ApplyMethod.immediate,
            parameterName: "auto_increment_offset",
            parameterValue: "5"
        )
        let parameter2 = RDSClientTypes.Parameter(
            applyMethod: RDSClientTypes.ApplyMethod.immediate,
            parameterName: "auto_increment_increment",
            parameterValue: "5"
        )

        let parameterList = [parameter1, parameter2]

        do {
            _ = try await rdsClient.modifyDBParameterGroup(
                input: ModifyDBParameterGroupInput(
                    dbParameterGroupName: groupName,
                    parameters: parameterList
                )
            )

            print("Successfully modified the parameter group \(groupName).")
        } catch {
            print("*** Error modifying the parameter group \(groupName): \(error.localizedDescription)")
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[ModifyDBParameterGroup](https://sdk.amazonaws.com/swift/api/awsrds/latest/documentation/awsrds/rdsclient/modifydbparametergroup(input:))」を参照してください。

# SDK for Swift を使用した Amazon S3 のコードサンプル
<a name="swift_1_s3_code_examples"></a>

次のコード例は、Amazon S3 で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*基本* は、重要なオペレーションをサービス内で実行する方法を示すコード例です。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には、完全なソースコードへのリンクが含まれており、そこからコードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [基本](#basics)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## 基本
<a name="basics"></a>

### 基本を学ぶ
<a name="s3_Scenario_GettingStarted_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ バケットを作成し、そこにファイルをアップロードします。
+ バケットからオブジェクトをダウンロードします。
+ バケット内のサブフォルダにオブジェクトをコピーします。
+ バケット内のオブジェクトを一覧表示します。
+ バケットオブジェクトとバケットを削除します。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

import Foundation
import AWSS3
import Smithy
import ClientRuntime

/// A class containing all the code that interacts with the AWS SDK for Swift.
public class ServiceHandler {
    let configuration: S3Client.S3ClientConfiguration
    let client: S3Client

    enum HandlerError: Error {
        case getObjectBody(String)
        case readGetObjectBody(String)
        case missingContents(String)
    }

    /// Initialize and return a new ``ServiceHandler`` object, which is used to drive the AWS calls
    /// used for the example.
    ///
    /// - Returns: A new ``ServiceHandler`` object, ready to be called to
    ///            execute AWS operations.
    public init() async throws {
        do {
            configuration = try await S3Client.S3ClientConfiguration() 
         //   configuration.region = "us-east-2" // Uncomment this to set the region programmatically.
            client = S3Client(config: configuration)
        }
        catch {
            print("ERROR: ", dump(error, name: "Initializing S3 client"))
            throw error
        }
    }


    /// Create a new user given the specified name.
    ///
    /// - Parameters:
    ///   - name: Name of the bucket to create.
    /// Throws an exception if an error occurs.
    public func createBucket(name: String) async throws {
        var input = CreateBucketInput(
            bucket: name
        )
        
        // For regions other than "us-east-1", you must set the locationConstraint in the createBucketConfiguration.
        // For more information, see LocationConstraint in the S3 API guide.
        // https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html#API_CreateBucket_RequestBody
        if let region = configuration.region {
            if region != "us-east-1" {
                input.createBucketConfiguration = S3ClientTypes.CreateBucketConfiguration(locationConstraint: S3ClientTypes.BucketLocationConstraint(rawValue: region))
            }
        }

        do {
            _ = try await client.createBucket(input: input)
        }
        catch let error as BucketAlreadyOwnedByYou {
            print("The bucket '\(name)' already exists and is owned by you. You may wish to ignore this exception.")
            throw error
        }
        catch {
            print("ERROR: ", dump(error, name: "Creating a bucket"))
            throw error
        }
    }

    /// Delete a bucket.
    /// - Parameter name: Name of the bucket to delete.
    public func deleteBucket(name: String) async throws {
        let input = DeleteBucketInput(
            bucket: name
        )
        do {
            _ = try await client.deleteBucket(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Deleting a bucket"))
            throw error
        }
    }

    /// Upload a file from local storage to the bucket.
    /// - Parameters:
    ///   - bucket: Name of the bucket to upload the file to.
    ///   - key: Name of the file to create.
    ///   - file: Path name of the file to upload.
    public func uploadFile(bucket: String, key: String, file: String) async throws {
        let fileUrl = URL(fileURLWithPath: file)
        do {
            let fileData = try Data(contentsOf: fileUrl)
            let dataStream = ByteStream.data(fileData)

            let input = PutObjectInput(
                body: dataStream,
                bucket: bucket,
                key: key
            )

            _ = try await client.putObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Putting an object."))
            throw error
        }
    }

    /// Create a file in the specified bucket with the given name. The new
    /// file's contents are uploaded from a `Data` object.
    ///
    /// - Parameters:
    ///   - bucket: Name of the bucket to create a file in.
    ///   - key: Name of the file to create.
    ///   - data: A `Data` object to write into the new file.
    public func createFile(bucket: String, key: String, withData data: Data) async throws {
        let dataStream = ByteStream.data(data)

        let input = PutObjectInput(
            body: dataStream,
            bucket: bucket,
            key: key
        )

        do {
            _ = try await client.putObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Putting an object."))
            throw error
        }
    }

    /// Download the named file to the given directory on the local device.
    ///
    /// - Parameters:
    ///   - bucket: Name of the bucket that contains the file to be copied.
    ///   - key: The name of the file to copy from the bucket.
    ///   - to: The path of the directory on the local device where you want to
    ///     download the file.
    public func downloadFile(bucket: String, key: String, to: String) async throws {
        let fileUrl = URL(fileURLWithPath: to).appendingPathComponent(key)

        let input = GetObjectInput(
            bucket: bucket,
            key: key
        )
        do {
            let output = try await client.getObject(input: input)

            guard let body = output.body else {
                throw HandlerError.getObjectBody("GetObjectInput missing body.")
            }

            guard let data = try await body.readData() else {
                throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.")
            }

            try data.write(to: fileUrl)
        }
        catch {
            print("ERROR: ", dump(error, name: "Downloading a file."))
            throw error
        }
    }

    /// Read the specified file from the given S3 bucket into a Swift
    /// `Data` object.
    ///
    /// - Parameters:
    ///   - bucket: Name of the bucket containing the file to read.
    ///   - key: Name of the file within the bucket to read.
    ///
    /// - Returns: A `Data` object containing the complete file data.
    public func readFile(bucket: String, key: String) async throws -> Data {
        let input = GetObjectInput(
            bucket: bucket,
            key: key
        )
        do {
            let output = try await client.getObject(input: input)
            
            guard let body = output.body else {
                throw HandlerError.getObjectBody("GetObjectInput missing body.")
            }

            guard let data = try await body.readData() else {
                throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.")
            }

            return data
        }
        catch {
            print("ERROR: ", dump(error, name: "Reading a file."))
            throw error
        }
   }


    /// Copy a file from one bucket to another.
    ///
    /// - Parameters:
    ///   - sourceBucket: Name of the bucket containing the source file.
    ///   - name: Name of the source file.
    ///   - destBucket: Name of the bucket to copy the file into.
    public func copyFile(from sourceBucket: String, name: String, to destBucket: String) async throws {
        let srcUrl = ("\(sourceBucket)/\(name)").addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)

        let input = CopyObjectInput(
            bucket: destBucket,
            copySource: srcUrl,
            key: name
        )
        do {
            _ = try await client.copyObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Copying an object."))
            throw error
        }
    }

    /// Deletes the specified file from Amazon S3.
    ///
    /// - Parameters:
    ///   - bucket: Name of the bucket containing the file to delete.
    ///   - key: Name of the file to delete.
    ///
    public func deleteFile(bucket: String, key: String) async throws {
        let input = DeleteObjectInput(
            bucket: bucket,
            key: key
        )

        do {
            _ = try await client.deleteObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Deleting a file."))
            throw error
        }
    }

    /// Returns an array of strings, each naming one file in the
    /// specified bucket.
    ///
    /// - Parameter bucket: Name of the bucket to get a file listing for.
    /// - Returns: An array of `String` objects, each giving the name of
    ///            one file contained in the bucket.
    public func listBucketFiles(bucket: String) async throws -> [String] {
        do {
            let input = ListObjectsV2Input(
                bucket: bucket
            )
            
            // Use "Paginated" to get all the objects.
            // This lets the SDK handle the 'continuationToken' in "ListObjectsV2Output".
            let output = client.listObjectsV2Paginated(input: input)
            var names: [String] = []
            
            for try await page in output {
                guard let objList = page.contents else {
                    print("ERROR: listObjectsV2Paginated returned nil contents.")
                    continue
                }
                
                for obj in objList {
                    if let objName = obj.key {
                        names.append(objName)
                    }
                }
            }
            
            
            return names
        }
        catch {
            print("ERROR: ", dump(error, name: "Listing objects."))
            throw error
        }
    }
}
```

```
import AWSS3

import Foundation
import ServiceHandler
import ArgumentParser

/// The command-line arguments and options available for this
/// example command.
struct ExampleCommand: ParsableCommand {
    @Argument(help: "Name of the S3 bucket to create")
    var bucketName: String

    @Argument(help: "Pathname of the file to upload to the S3 bucket")
    var uploadSource: String

    @Argument(help: "The name (key) to give the file in the S3 bucket")
    var objName: String

    @Argument(help: "S3 bucket to copy the object to")
    var destBucket: String

    @Argument(help: "Directory where you want to download the file from the S3 bucket")
    var downloadDir: String

    static var configuration = CommandConfiguration(
        commandName: "s3-basics",
        abstract: "Demonstrates a series of basic AWS S3 functions.",
        discussion: """
        Performs the following Amazon S3 commands:

        * `CreateBucket`
        * `PutObject`
        * `GetObject`
        * `CopyObject`
        * `ListObjects`
        * `DeleteObjects`
        * `DeleteBucket`
        """
    )

    /// Called by ``main()`` to do the actual running of the AWS
    /// example.
    func runAsync() async throws {
        let serviceHandler = try await ServiceHandler()

        // 1. Create the bucket.
        print("Creating the bucket \(bucketName)...")
        try await serviceHandler.createBucket(name: bucketName)

        // 2. Upload a file to the bucket.
        print("Uploading the file \(uploadSource)...")
        try await serviceHandler.uploadFile(bucket: bucketName, key: objName, file: uploadSource)

        // 3. Download the file.
        print("Downloading the file \(objName) to \(downloadDir)...")
        try await serviceHandler.downloadFile(bucket: bucketName, key: objName, to: downloadDir)

        // 4. Copy the file to another bucket.
        print("Copying the file to the bucket \(destBucket)...")
        try await serviceHandler.copyFile(from: bucketName, name: objName, to: destBucket)

        // 5. List the contents of the bucket.

        print("Getting a list of the files in the bucket \(bucketName)")
        let fileList = try await serviceHandler.listBucketFiles(bucket: bucketName)
        let numFiles = fileList.count
        if numFiles != 0 {
            print("\(numFiles) file\((numFiles > 1) ? "s" : "") in bucket \(bucketName):")
            for name in fileList {
                print("  \(name)")
            }
        } else {
            print("No files found in bucket \(bucketName)")
        }

        // 6. Delete the objects from the bucket.

        print("Deleting the file \(objName) from the bucket \(bucketName)...")
        try await serviceHandler.deleteFile(bucket: bucketName, key: objName)
        print("Deleting the file \(objName) from the bucket \(destBucket)...")
        try await serviceHandler.deleteFile(bucket: destBucket, key: objName)

        // 7. Delete the bucket.
        print("Deleting the bucket \(bucketName)...")
        try await serviceHandler.deleteBucket(name: bucketName)

        print("Done.")
    }
}

//
// Main program entry point.
//
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [CopyObject](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/copyobject(input:))
  + [CreateBucket](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/createbucket(input:))
  + [DeleteBucket](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/deletebucket(input:))
  + [DeleteObjects](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/deleteobjects(input:))
  + [GetObject](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/getobject(input:))
  + [ListObjectsV2](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/listobjectsv2(input:))
  + [PutObject](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/putobject(input:))

## アクション
<a name="actions"></a>

### `CopyObject`
<a name="s3_CopyObject_swift_1_topic"></a>

次のコード例は、`CopyObject` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    public func copyFile(from sourceBucket: String, name: String, to destBucket: String) async throws {
        let srcUrl = ("\(sourceBucket)/\(name)").addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)

        let input = CopyObjectInput(
            bucket: destBucket,
            copySource: srcUrl,
            key: name
        )
        do {
            _ = try await client.copyObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Copying an object."))
            throw error
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[CopyObject](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/copyobject(input:))」を参照してください。

### `CreateBucket`
<a name="s3_CreateBucket_swift_1_topic"></a>

次のコード例は、`CreateBucket` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    public func createBucket(name: String) async throws {
        var input = CreateBucketInput(
            bucket: name
        )
        
        // For regions other than "us-east-1", you must set the locationConstraint in the createBucketConfiguration.
        // For more information, see LocationConstraint in the S3 API guide.
        // https://docs.aws.amazon.com/AmazonS3/latest/API/API_CreateBucket.html#API_CreateBucket_RequestBody
        if let region = configuration.region {
            if region != "us-east-1" {
                input.createBucketConfiguration = S3ClientTypes.CreateBucketConfiguration(locationConstraint: S3ClientTypes.BucketLocationConstraint(rawValue: region))
            }
        }

        do {
            _ = try await client.createBucket(input: input)
        }
        catch let error as BucketAlreadyOwnedByYou {
            print("The bucket '\(name)' already exists and is owned by you. You may wish to ignore this exception.")
            throw error
        }
        catch {
            print("ERROR: ", dump(error, name: "Creating a bucket"))
            throw error
        }
    }
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[CreateBucket](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/createbucket(input:))」を参照してください。

### `DeleteBucket`
<a name="s3_DeleteBucket_swift_1_topic"></a>

次のコード例は、`DeleteBucket` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    public func deleteBucket(name: String) async throws {
        let input = DeleteBucketInput(
            bucket: name
        )
        do {
            _ = try await client.deleteBucket(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Deleting a bucket"))
            throw error
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DeleteBucket](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/deletebucket(input:))」を参照してください。

### `DeleteObject`
<a name="s3_DeleteObject_swift_1_topic"></a>

次のコード例は、`DeleteObject` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    public func deleteFile(bucket: String, key: String) async throws {
        let input = DeleteObjectInput(
            bucket: bucket,
            key: key
        )

        do {
            _ = try await client.deleteObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Deleting a file."))
            throw error
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DeleteObject](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/deleteobject(input:))」を参照してください。

### `DeleteObjects`
<a name="s3_DeleteObjects_swift_1_topic"></a>

次のコード例は、`DeleteObjects` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/DeleteObjects#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    public func deleteObjects(bucket: String, keys: [String]) async throws {
        let input = DeleteObjectsInput(
            bucket: bucket,
            delete: S3ClientTypes.Delete(
                objects: keys.map { S3ClientTypes.ObjectIdentifier(key: $0) },
                quiet: true
            )
        )

        do {
            _ = try await client.deleteObjects(input: input)
        } catch {
            print("ERROR: deleteObjects:", dump(error))
            throw error
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[DeleteObjects](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/deleteobjects(input:))」を参照してください。

### `GetObject`
<a name="s3_GetObject_swift_1_topic"></a>

次のコード例は、`GetObject` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    public func downloadFile(bucket: String, key: String, to: String) async throws {
        let fileUrl = URL(fileURLWithPath: to).appendingPathComponent(key)

        let input = GetObjectInput(
            bucket: bucket,
            key: key
        )
        do {
            let output = try await client.getObject(input: input)

            guard let body = output.body else {
                throw HandlerError.getObjectBody("GetObjectInput missing body.")
            }

            guard let data = try await body.readData() else {
                throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.")
            }

            try data.write(to: fileUrl)
        }
        catch {
            print("ERROR: ", dump(error, name: "Downloading a file."))
            throw error
        }
    }
```

```
import AWSS3

    public func readFile(bucket: String, key: String) async throws -> Data {
        let input = GetObjectInput(
            bucket: bucket,
            key: key
        )
        do {
            let output = try await client.getObject(input: input)
            
            guard let body = output.body else {
                throw HandlerError.getObjectBody("GetObjectInput missing body.")
            }

            guard let data = try await body.readData() else {
                throw HandlerError.readGetObjectBody("GetObjectInput unable to read data.")
            }

            return data
        }
        catch {
            print("ERROR: ", dump(error, name: "Reading a file."))
            throw error
        }
   }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[GetObject](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/getobject(input:))」を参照してください。

### `ListBuckets`
<a name="s3_ListBuckets_swift_1_topic"></a>

次のコード例は、`ListBuckets` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    /// Return an array containing information about every available bucket.
    ///
    /// - Returns: An array of ``S3ClientTypes.Bucket`` objects describing
    ///   each bucket.
    public func getAllBuckets() async throws -> [S3ClientTypes.Bucket] {
        return try await client.listBuckets(input: ListBucketsInput())
    }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ListBuckets](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/listbuckets(input:))」を参照してください。**

### `ListObjectsV2`
<a name="s3_ListObjectsV2_swift_1_topic"></a>

次のコード例は、`ListObjectsV2` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3

    public func listBucketFiles(bucket: String) async throws -> [String] {
        do {
            let input = ListObjectsV2Input(
                bucket: bucket
            )
            
            // Use "Paginated" to get all the objects.
            // This lets the SDK handle the 'continuationToken' in "ListObjectsV2Output".
            let output = client.listObjectsV2Paginated(input: input)
            var names: [String] = []
            
            for try await page in output {
                guard let objList = page.contents else {
                    print("ERROR: listObjectsV2Paginated returned nil contents.")
                    continue
                }
                
                for obj in objList {
                    if let objName = obj.key {
                        names.append(objName)
                    }
                }
            }
            
            
            return names
        }
        catch {
            print("ERROR: ", dump(error, name: "Listing objects."))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[ListObjectsV2](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/listobjectsv2(input:))」を参照してください。**

### `PutObject`
<a name="s3_PutObject_swift_1_topic"></a>

次のコード例は、`PutObject` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSS3
import Smithy

    public func uploadFile(bucket: String, key: String, file: String) async throws {
        let fileUrl = URL(fileURLWithPath: file)
        do {
            let fileData = try Data(contentsOf: fileUrl)
            let dataStream = ByteStream.data(fileData)

            let input = PutObjectInput(
                body: dataStream,
                bucket: bucket,
                key: key
            )

            _ = try await client.putObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Putting an object."))
            throw error
        }
    }
```

```
import AWSS3
import Smithy

    public func createFile(bucket: String, key: String, withData data: Data) async throws {
        let dataStream = ByteStream.data(data)

        let input = PutObjectInput(
            body: dataStream,
            bucket: bucket,
            key: key
        )

        do {
            _ = try await client.putObject(input: input)
        }
        catch {
            print("ERROR: ", dump(error, name: "Putting an object."))
            throw error
        }
    }
```
+  API の詳細については、*AWS SDK for Swift API リファレンス*の「[PutObject](https://sdk.amazonaws.com/swift/api/awss3/latest/documentation/awss3/s3client/putobject(input:))」を参照してください。

## シナリオ
<a name="scenarios"></a>

### サイズが不明なストリームをダウンロードする
<a name="s3_Scenario_DownloadStream_swift_1_topic"></a>

次のコード例は、サイズが不明なストリームを Amazon S3 オブジェクトからダウンロードする方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/binary-streaming#code-examples)での設定と実行の方法を確認してください。

```
import ArgumentParser
import AWSClientRuntime
import AWSS3
import Foundation
import Smithy
import SmithyHTTPAPI
import SmithyStreams


    /// Download a file from the specified bucket.
    ///
    /// - Parameters:
    ///   - bucket: The Amazon S3 bucket name to get the file from.
    ///   - key: The name (or path) of the file to download from the bucket.
    ///   - destPath: The pathname on the local filesystem at which to store
    ///     the downloaded file.
    func downloadFile(bucket: String, key: String, destPath: String?) async throws {
        let fileURL: URL

        // If no destination path was provided, use the key as the name to use
        // for the file in the downloads folder.
        
        if destPath == nil {
            do {
                try fileURL = FileManager.default.url(
                    for: .downloadsDirectory,
                    in: .userDomainMask,
                    appropriateFor: URL(string: key),
                    create: true
                ).appendingPathComponent(key)
            } catch {
                throw TransferError.directoryError
            }
        } else {
            fileURL = URL(fileURLWithPath: destPath!)
        }
                
        let config = try await S3Client.S3ClientConfiguration(region: region)
        let s3Client = S3Client(config: config)

        // Create a `FileHandle` referencing the local destination. Then
        // create a `ByteStream` from that.

        FileManager.default.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
        let fileHandle = try FileHandle(forWritingTo: fileURL)

        // Download the file using `GetObject`.
        
        let getInput = GetObjectInput(
            bucket: bucket,
            key: key
        )

        do {
            let getOutput = try await s3Client.getObject(input: getInput)

            guard let body = getOutput.body else {
                throw TransferError.downloadError("Error: No data returned for download")
            }

            // If the body is returned as a `Data` object, write that to the
            // file. If it's a stream, read the stream chunk by chunk,
            // appending each chunk to the destination file.

            switch body {
            case .data:
                guard let data = try await body.readData() else {
                    throw TransferError.downloadError("Download error")
                }

                // Write the `Data` to the file.

                do {
                    try data.write(to: fileURL)
                } catch {
                    throw TransferError.writeError
                }
                break

            case .stream(let stream as ReadableStream):
                while (true) {
                    let chunk = try await stream.readAsync(upToCount: 5 * 1024 * 1024)
                    guard let chunk = chunk else {
                        break
                    }

                    // Write the chunk to the destination file.

                    do {
                        try fileHandle.write(contentsOf: chunk)
                    } catch {
                        throw TransferError.writeError
                    }
                }

                break
            default:
                throw TransferError.downloadError("Received data is unknown object type")
            }
        } catch {
            throw TransferError.downloadError("Error downloading the file: \(error)")
        }

        print("File downloaded to \(fileURL.path).")
    }
```

### サイズが不明なストリームをアップロードする
<a name="s3_Scenario_UploadStream_swift_1_topic"></a>

次のコード例は、サイズが不明なストリームを Amazon S3 オブジェクトにアップロードする方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/s3/binary-streaming#code-examples)での設定と実行の方法を確認してください。

```
import ArgumentParser
import AWSClientRuntime
import AWSS3
import Foundation
import Smithy
import SmithyHTTPAPI
import SmithyStreams


    /// Upload a file to the specified bucket.
    ///
    /// - Parameters:
    ///   - bucket: The Amazon S3 bucket name to store the file into.
    ///   - key: The name (or path) of the file to upload to in the `bucket`.
    ///   - sourcePath: The pathname on the local filesystem of the file to
    ///     upload.
    func uploadFile(sourcePath: String, bucket: String, key: String?) async throws {
        let fileURL: URL = URL(fileURLWithPath: sourcePath)
        let fileName: String

        // If no key was provided, use the last component of the filename.
        
        if key == nil {
            fileName = fileURL.lastPathComponent
        } else {
            fileName = key!
        }
                
        let s3Client = try await S3Client()

        // Create a FileHandle for the source file.

        let fileHandle = FileHandle(forReadingAtPath: sourcePath)
        guard let fileHandle = fileHandle else {
            throw TransferError.readError
        }

        // Create a byte stream to retrieve the file's contents. This uses the
        // Smithy FileStream and ByteStream types.

        let stream = FileStream(fileHandle: fileHandle)
        let body = ByteStream.stream(stream)

        // Create a `PutObjectInput` with the ByteStream as the body of the
        // request's data. The AWS SDK for Swift will handle sending the
        // entire file in chunks, regardless of its size.
        
        let putInput = PutObjectInput(
            body: body,
            bucket: bucket,
            key: fileName
        )

        do {
            _ = try await s3Client.putObject(input: putInput)
        } catch {
            throw TransferError.uploadError("Error uploading the file: \(error)")
        }

        print("File uploaded to \(fileURL.path).")
    }
```

# SDK for Swift を使用した Amazon SNS の例
<a name="swift_1_sns_code_examples"></a>

次のコード例は、Amazon SNS で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon SNS
<a name="sns_Hello_swift_1_topic"></a>

次のコード例は、Amazon SNS の使用を開始する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns/basics#code-examples)での設定と実行の方法を確認してください。
Package.swift ファイル。  

```
import PackageDescription

let package = Package(
    name: "sns-basics",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13),
        .iOS(.v15)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.0.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "sns-basics",
            dependencies: [
                .product(name: "AWSSNS", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources")

    ]
)
```
メイン Swift プログラム。  

```
import ArgumentParser
import AWSClientRuntime
import AWSSNS
import Foundation

struct ExampleCommand: ParsableCommand {
    @Option(help: "Name of the Amazon Region to use (default: us-east-1)")
    var region = "us-east-1"

    static var configuration = CommandConfiguration(
        commandName: "sns-basics",
        abstract: """
        This example shows how to list all of your available Amazon SNS topics.
        """,
        discussion: """
        """
    )
    
    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        var topics: [String] = []
        let outputPages = snsClient.listTopicsPaginated(
            input: ListTopicsInput()
        )

        // Each time a page of results arrives, process its contents.

        for try await output in outputPages {
            guard let topicList = output.topics else {
                print("Unable to get a page of Amazon SNS topics.")
                return
            }

            // Iterate over the topics listed on this page, adding their ARNs
            // to the `topics` array.

            for topic in topicList {
                guard let arn = topic.topicArn else {
                    print("Topic has no ARN.")
                    return
                }
                topics.append(arn)
            }
        }

        print("You have \(topics.count) topics:")
        for topic in topics {
            print("   \(topic)")
        }
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ListTopics](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/listtopics(input:))」を参照してください。**

## アクション
<a name="actions"></a>

### `CreateTopic`
<a name="sns_CreateTopic_swift_1_topic"></a>

次のコード例は、`CreateTopic` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.createTopic(
            input: CreateTopicInput(name: name)
        )

        guard let arn = output.topicArn else {
            print("No topic ARN returned by Amazon SNS.")
            return
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[CreateTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/createtopic(input:))」を参照してください。**

### `DeleteTopic`
<a name="sns_DeleteTopic_swift_1_topic"></a>

次のコード例は、`DeleteTopic` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        _ = try await snsClient.deleteTopic(
            input: DeleteTopicInput(topicArn: arn)
        )
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DeleteTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/deletetopic(input:))」を参照してください。**

### `ListTopics`
<a name="sns_ListTopics_swift_1_topic"></a>

次のコード例は、`ListTopics` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns/basics#code-examples)での設定と実行の方法を確認してください。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        var topics: [String] = []
        let outputPages = snsClient.listTopicsPaginated(
            input: ListTopicsInput()
        )

        // Each time a page of results arrives, process its contents.

        for try await output in outputPages {
            guard let topicList = output.topics else {
                print("Unable to get a page of Amazon SNS topics.")
                return
            }

            // Iterate over the topics listed on this page, adding their ARNs
            // to the `topics` array.

            for topic in topicList {
                guard let arn = topic.topicArn else {
                    print("Topic has no ARN.")
                    return
                }
                topics.append(arn)
            }
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ListTopics](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/listtopics(input:))」を参照してください。**

### `Publish`
<a name="sns_Publish_swift_1_topic"></a>

次のコード例は、`Publish` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.publish(
            input: PublishInput(
                message: message,
                topicArn: arn
            )
        )

        guard let messageId = output.messageId else {
            print("No message ID received from Amazon SNS.")
            return
        }
        
        print("Published message with ID \(messageId)")
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[Publish](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/publish(input:))」を参照してください。**

### `Subscribe`
<a name="sns_Subscribe_swift_1_topic"></a>

次のコード例は、`Subscribe` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)での設定と実行の方法を確認してください。
E メールアドレスをトピックにサブスクライブします。  

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.subscribe(
            input: SubscribeInput(
                endpoint: email,
                protocol: "email",
                returnSubscriptionArn: true,
                topicArn: arn
            )
        )

        guard let subscriptionArn = output.subscriptionArn else {
            print("No subscription ARN received from Amazon SNS.")
            return
        }
        
        print("Subscription \(subscriptionArn) created.")
```
SMS で通知を受け取るには、電話番号をトピックに登録します。  

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.subscribe(
            input: SubscribeInput(
                endpoint: phone,
                protocol: "sms",
                returnSubscriptionArn: true,
                topicArn: arn
            )
        )

        guard let subscriptionArn = output.subscriptionArn else {
            print("No subscription ARN received from Amazon SNS.")
            return
        }
        
        print("Subscription \(subscriptionArn) created.")
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[Subscribe](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/subscribe(input:))」を参照してください。**

### `Unsubscribe`
<a name="sns_Unsubscribe_swift_1_topic"></a>

次のコード例は、`Unsubscribe` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        _ = try await snsClient.unsubscribe(
            input: UnsubscribeInput(
                subscriptionArn: arn
            )
        )

        print("Unsubscribed.")
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[Unsubscribe](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/unsubscribe(input:))」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs/scenario#code-examples)での設定と実行の方法を確認してください。

```
import ArgumentParser
import AWSClientRuntime
import AWSSNS
import AWSSQS
import Foundation

struct ExampleCommand: ParsableCommand {
    @Option(help: "Name of the Amazon Region to use")
    var region = "us-east-1"

    static var configuration = CommandConfiguration(
        commandName: "queue-scenario",
        abstract: """
        This example interactively demonstrates how to use Amazon Simple
        Notification Service (Amazon SNS) and Amazon Simple Queue Service
        (Amazon SQS) together to publish and receive messages using queues.
        """,
        discussion: """
        Supports filtering using a "tone" attribute.
        """
    )

    /// Prompt for an input string. Only non-empty strings are allowed.
    /// 
    /// - Parameter prompt: The prompt to display.
    ///
    /// - Returns: The string input by the user.
    func stringRequest(prompt: String) -> String {
        var str: String?

        while str == nil {
            print(prompt, terminator: "")
            str = readLine()

            if str != nil && str?.count == 0 {
                str = nil
            }
        }

        return str!
    }

    /// Ask a yes/no question.
    /// 
    /// - Parameter prompt: A prompt string to print.
    ///
    /// - Returns: `true` if the user answered "Y", otherwise `false`.
    func yesNoRequest(prompt: String) -> Bool {
        while true {
            let answer = stringRequest(prompt: prompt).lowercased()
            if answer == "y" || answer == "n" {
                return answer == "y"
            }
        }
    }

    /// Display a menu of options then request a selection.
    /// 
    /// - Parameters:
    ///   - prompt: A prompt string to display before the menu.
    ///   - options: An array of strings giving the menu options.
    ///
    /// - Returns: The index number of the selected option or 0 if no item was
    ///   selected.
    func menuRequest(prompt: String, options: [String]) -> Int {
        let numOptions = options.count

        if numOptions == 0 {
            return 0
        }

        print(prompt)

        for (index, value) in options.enumerated() {
            print("(\(index)) \(value)")
        }

        repeat {
            print("Enter your selection (0 - \(numOptions-1)): ", terminator: "")
            if let answer = readLine() {
                guard let answer = Int(answer) else {
                    print("Please enter the number matching your selection.")
                    continue
                }

                if answer >= 0 && answer < numOptions {
                    return answer
                } else {
                    print("Please enter the number matching your selection.")
                }
            }
        } while true
    }
    
    /// Ask the user too press RETURN. Accepts any input but ignores it.
    /// 
    /// - Parameter prompt: The text prompt to display.
    func returnRequest(prompt: String) {
        print(prompt, terminator: "")
        _ = readLine()
    }

    var attrValues = [
        "<none>",
        "cheerful",
        "funny",
        "serious",
        "sincere"
    ]

    /// Ask the user to choose one of the attribute values to use as a filter.
    /// 
    /// - Parameters:
    ///   - message: A message to display before the menu of values.
    ///   - attrValues: An array of strings giving the values to choose from.
    /// 
    /// - Returns: The string corresponding to the selected option.
    func askForFilter(message: String, attrValues: [String]) -> String? {
        print(message)
        for (index, value) in attrValues.enumerated() {
            print("  [\(index)] \(value)")
        }

        var answer: Int?
        repeat {
            answer = Int(stringRequest(prompt: "Select an value for the 'tone' attribute or 0 to end: "))
        } while answer == nil || answer! < 0 || answer! > attrValues.count + 1

        if answer == 0 {
            return nil
        }
        return attrValues[answer!]
    }

    /// Prompts the user for filter terms and constructs the attribute
    /// record that specifies them.
    /// 
    /// - Returns: A mapping of "FilterPolicy" to a JSON string representing
    ///   the user-defined filter.
    func buildFilterAttributes() -> [String:String] {
        var attr: [String:String] = [:]
        var filterString = ""

        var first = true

        while let ans = askForFilter(message: "Choose a value to apply to the 'tone' attribute.",
                                    attrValues: attrValues) {
            if !first {
                filterString += ","
            }
            first = false

            filterString += "\"\(ans)\""
        }

        let filterJSON = "{ \"tone\": [\(filterString)]}"
        attr["FilterPolicy"] = filterJSON

        return attr
    }
    /// Create a queue, returning its URL string.
    ///
    /// - Parameters:
    ///   - prompt: A prompt to ask for the queue name.
    ///   - isFIFO: Whether or not to create a FIFO queue.
    ///
    /// - Returns: The URL of the queue.
    func createQueue(prompt: String, sqsClient: SQSClient, isFIFO: Bool) async throws -> String? {
        repeat {
            var queueName = stringRequest(prompt: prompt)
            var attributes: [String: String] = [:]

            if isFIFO {
                queueName += ".fifo"
                attributes["FifoQueue"] = "true"
            }

            do {
                let output = try await sqsClient.createQueue(
                    input: CreateQueueInput(
                        attributes: attributes,
                        queueName: queueName
                    )
                )
                guard let url = output.queueUrl else {
                    return nil
                }

                return url
            } catch _ as QueueDeletedRecently {
                print("You need to use a different queue name. A queue by that name was recently deleted.")
                continue
            }
        } while true
    }

    /// Return the ARN of a queue given its URL.
    ///
    /// - Parameter queueUrl: The URL of the queue for which to return the
    ///   ARN.
    ///
    /// - Returns: The ARN of the specified queue.
    func getQueueARN(sqsClient: SQSClient, queueUrl: String) async throws -> String? {
        let output = try await sqsClient.getQueueAttributes(
            input: GetQueueAttributesInput(
                attributeNames: [.queuearn],
                queueUrl: queueUrl
            )
        )

        guard let attributes = output.attributes else {
            return nil
        }
        
        return attributes["QueueArn"]
    }

    /// Applies the needed policy to the specified queue.
    /// 
    /// - Parameters:
    ///   - sqsClient: The Amazon SQS client to use.
    ///   - queueUrl: The queue to apply the policy to.
    ///   - queueArn: The ARN of the queue to apply the policy to.
    ///   - topicArn: The topic that should have access via the policy.
    ///
    /// - Throws: Errors from the SQS `SetQueueAttributes` action.
    func setQueuePolicy(sqsClient: SQSClient, queueUrl: String,
                        queueArn: String, topicArn: String) async throws {
        _ = try await sqsClient.setQueueAttributes(
            input: SetQueueAttributesInput(
                attributes: [
                    "Policy":
                        """
                        {
                            "Statement": [
                                {
                                    "Effect": "Allow",
                                    "Principal": {
                                        "Service": "sns.amazonaws.com"
                                    },
                                    "Action": "sqs:SendMessage",
                                    "Resource": "\(queueArn)",
                                    "Condition": {
                                        "ArnEquals": {
                                            "aws:SourceArn": "\(topicArn)"
                                        }
                                    }
                                }
                            ]
                        }
                        """

                ],
                queueUrl: queueUrl
            )
        )
    }

    /// Receive the available messages on a queue, outputting them to the
    /// screen. Returns a dictionary you pass to DeleteMessageBatch to delete
    /// all the received messages.
    /// 
    /// - Parameters:
    ///   - sqsClient: The Amazon SQS client to use.
    ///   - queueUrl: The SQS queue on which to receive messages.
    /// 
    /// - Throws: Errors from `SQSClient.receiveMessage()`
    ///
    /// - Returns: An array of SQSClientTypes.DeleteMessageBatchRequestEntry
    ///   items, each describing one received message in the format needed to
    ///   delete it.
    func receiveAndListMessages(sqsClient: SQSClient, queueUrl: String) async throws
                                -> [SQSClientTypes.DeleteMessageBatchRequestEntry] {
        let output = try await sqsClient.receiveMessage(
            input: ReceiveMessageInput(
                maxNumberOfMessages: 10,
                queueUrl: queueUrl
            )
        )

        guard let messages = output.messages else {
            print("No messages received.")
            return []
        }

        var deleteList: [SQSClientTypes.DeleteMessageBatchRequestEntry] = []

        // Print out all the messages that were received, including their
        // attributes, if any.

        for message in messages {
            print("Message ID:     \(message.messageId ?? "<unknown>")")
            print("Receipt handle: \(message.receiptHandle ?? "<unknown>")")
            print("Message JSON:   \(message.body ?? "<body missing>")")
            
            if message.receiptHandle != nil {
                deleteList.append(
                    SQSClientTypes.DeleteMessageBatchRequestEntry(
                        id: message.messageId,
                        receiptHandle: message.receiptHandle
                    )
                )
            }
        }

        return deleteList
    }

    /// Delete all the messages in the specified list.
    /// 
    /// - Parameters:
    ///   - sqsClient: The Amazon SQS client to use.
    ///   - queueUrl: The SQS queue to delete messages from.
    ///   - deleteList: A list of `DeleteMessageBatchRequestEntry` objects
    ///     describing the messages to delete.
    ///
    /// - Throws: Errors from `SQSClient.deleteMessageBatch()`.
    func deleteMessageList(sqsClient: SQSClient, queueUrl: String,
                           deleteList: [SQSClientTypes.DeleteMessageBatchRequestEntry]) async throws {
        let output = try await sqsClient.deleteMessageBatch(
            input: DeleteMessageBatchInput(entries: deleteList, queueUrl: queueUrl)
        )

        if let failed = output.failed {
            print("\(failed.count) errors occurred deleting messages from the queue.")
            for message in failed {
                print("---> Failed to delete message \(message.id ?? "<unknown ID>") with error: \(message.code ?? "<unknown>") (\(message.message ?? "..."))")
            }
        }
    }

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let rowOfStars = String(repeating: "*", count: 75)

        print("""
              \(rowOfStars)
              Welcome to the cross-service messaging with topics and queues example.
              In this workflow, you'll create an SNS topic, then create two SQS
              queues which will be subscribed to that topic.

              You can specify several options for configuring the topic, as well as
              the queue subscriptions. You can then post messages to the topic and
              receive the results on the queues.
              \(rowOfStars)\n
              """
        )

        // 0. Create SNS and SQS clients.

        let snsConfig = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: snsConfig)

        let sqsConfig = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: sqsConfig)

        // 1. Ask the user whether to create a FIFO topic. If so, ask whether
        //    to use content-based deduplication instead of requiring a
        //    deduplication ID.

        let isFIFO = yesNoRequest(prompt: "Do you want to create a FIFO topic (Y/N)? ")
        var isContentBasedDeduplication = false

        if isFIFO {
            print("""
                  \(rowOfStars)
                  Because you've chosen to create a FIFO topic, deduplication is
                  supported.

                  Deduplication IDs are either set in the message or are automatically
                  generated from the content using a hash function.

                  If a message is successfully published to an SNS FIFO topic, any
                  message published and found to have the same deduplication ID
                  (within a five-minute deduplication interval), is accepted but
                  not delivered.

                  For more information about deduplication, see:
                  https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.
                  """
            )

            isContentBasedDeduplication = yesNoRequest(
                prompt: "Use content-based deduplication instead of entering a deduplication ID (Y/N)? ")
            print(rowOfStars)
        }

        var topicName = stringRequest(prompt: "Enter the name of the topic to create: ")
        
        // 2. Create the topic. Append ".fifo" to the name if FIFO was
        //    requested, and set the "FifoTopic" attribute to "true" if so as
        //    well. Set the "ContentBasedDeduplication" attribute to "true" if
        //    content-based deduplication was requested.

        if isFIFO {
            topicName += ".fifo"
        }

        print("Topic name: \(topicName)")

        var attributes = [
            "FifoTopic": (isFIFO ? "true" : "false")
        ]

        // If it's a FIFO topic with content-based deduplication, set the
        // "ContentBasedDeduplication" attribute.

        if isContentBasedDeduplication {
            attributes["ContentBasedDeduplication"] = "true"
        }

        // Create the topic and retrieve the ARN.

        let output = try await snsClient.createTopic(
            input: CreateTopicInput(
                attributes: attributes,
                name: topicName
            )
        )

        guard let topicArn = output.topicArn else {
            print("No topic ARN returned!")
            return
        }

        print("""
              Topic '\(topicName) has been created with the
              topic ARN \(topicArn)."
              """
        )
        
        print(rowOfStars)

        // 3. Create an SQS queue. Append ".fifo" to the name if one of the
        //    FIFO topic configurations was chosen, and set "FifoQueue" to
        //    "true" if the topic is FIFO.

        print("""
              Next, you will create two SQS queues that will be subscribed
              to the topic you just created.\n
              """
        )

        let q1Url = try await createQueue(prompt: "Enter the name of the first queue: ",
                                          sqsClient: sqsClient, isFIFO: isFIFO)
        guard let q1Url else {
            print("Unable to create queue 1!")
            return
        }
        
        // 4. Get the SQS queue's ARN attribute using `GetQueueAttributes`.

        let q1Arn = try await getQueueARN(sqsClient: sqsClient, queueUrl: q1Url)

        guard let q1Arn else {
            print("Unable to get ARN of queue 1!")
            return
        }
        print("Got queue 1 ARN: \(q1Arn)")

        // 5. Attach an AWS IAM policy to the queue using
        //    `SetQueueAttributes`.

        try await setQueuePolicy(sqsClient: sqsClient, queueUrl: q1Url,
                                 queueArn: q1Arn, topicArn: topicArn)

        // 6. Subscribe the SQS queue to the SNS topic. Set the topic ARN in
        //    the request. Set the protocol to "sqs". Set the queue ARN to the
        //    ARN just received in step 5. For FIFO topics, give the option to
        //    apply a filter. A filter allows only matching messages to enter
        //    the queue.

        var q1Attributes: [String:String]? = nil

        if isFIFO {
            print(
                """

                If you add a filter to this subscription, then only the filtered messages will
                be received in the queue. For information about message filtering, see
                https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html
                For this example, you can filter messages by a 'tone' attribute.

                """
            )

            let subPrompt = """
                Would you like to filter messages for the first queue's subscription to the
                topic \(topicName) (Y/N)? 
                """
            if (yesNoRequest(prompt: subPrompt)) {
                q1Attributes = buildFilterAttributes()
            }
        }

        let sub1Output = try await snsClient.subscribe(
            input: SubscribeInput(
                attributes: q1Attributes,
                endpoint: q1Arn,
                protocol: "sqs",
                topicArn: topicArn
            )
        )

        guard let q1SubscriptionArn = sub1Output.subscriptionArn else {
            print("Invalid subscription ARN returned for queue 1!")
            return
        }

        // 7. Repeat steps 3-6 for the second queue.

        let q2Url = try await createQueue(prompt: "Enter the name of the second queue: ",
                                sqsClient: sqsClient, isFIFO: isFIFO)
    
        guard let q2Url else {
            print("Unable to create queue 2!")
            return
        }

        let q2Arn = try await getQueueARN(sqsClient: sqsClient, queueUrl: q2Url)

        guard let q2Arn else {
            print("Unable to get ARN of queue 2!")
            return
        }
        print("Got queue 2 ARN: \(q2Arn)")

        try await setQueuePolicy(sqsClient: sqsClient, queueUrl: q2Url,
                                 queueArn: q2Arn, topicArn: topicArn)

        var q2Attributes: [String:String]? = nil

        if isFIFO {
            let subPrompt = """
                Would you like to filter messages for the second queue's subscription to the
                topic \(topicName) (Y/N)? 
                """
            if (yesNoRequest(prompt: subPrompt)) {
                q2Attributes = buildFilterAttributes()
            }
        }

        let sub2Output = try await snsClient.subscribe(
            input: SubscribeInput(
                attributes: q2Attributes,
                endpoint: q2Arn,
                protocol: "sqs",
                topicArn: topicArn
            )
        )

        guard let q2SubscriptionArn = sub2Output.subscriptionArn else {
            print("Invalid subscription ARN returned for queue 1!")
            return
        }

        // 8. Let the user publish messages to the topic, asking for a message
        //    body for each message. Handle the types of topic correctly (SEE
        //    MVP INFORMATION AND FIX THESE COMMENTS!!!

        print("\n\(rowOfStars)\n")

        var first = true

        repeat {
            var publishInput = PublishInput(
                topicArn: topicArn
            )

            publishInput.message = stringRequest(prompt: "Enter message text to publish: ")

            // If using a FIFO topic, a message group ID must be set on the
            // message.

            if isFIFO {
                if first {
                    print("""
                        Because you're using a FIFO topic, you must set a message
                        group ID. All messages within the same group will be
                        received in the same order in which they were published.\n
                        """
                    )
                }
                publishInput.messageGroupId = stringRequest(prompt: "Enter a message group ID for this message: ")

                if !isContentBasedDeduplication {
                    if first {
                        print("""
                              Because you're not using content-based deduplication, you
                              must enter a deduplication ID. If other messages with the
                              same deduplication ID are published within the same
                              deduplication interval, they will not be delivered.
                              """
                        )
                    }
                    publishInput.messageDeduplicationId = stringRequest(prompt: "Enter a deduplication ID for this message: ")
                }
            }

            // Allow the user to add a value for the "tone" attribute if they
            // wish to do so.

            var messageAttributes: [String:SNSClientTypes.MessageAttributeValue] = [:]
            let attrValSelection = menuRequest(prompt: "Choose a tone to apply to this message.", options: attrValues)

            if attrValSelection != 0 {
                let val = SNSClientTypes.MessageAttributeValue(dataType: "String", stringValue: attrValues[attrValSelection])
                messageAttributes["tone"] = val
            }

            publishInput.messageAttributes = messageAttributes
            
            // Publish the message and display its ID.

            let publishOutput = try await snsClient.publish(input: publishInput)

            guard let messageID = publishOutput.messageId else {
                print("Unable to get the published message's ID!")
                return
            }

            print("Message published with ID \(messageID).")
            first = false

            // 9. Repeat step 8 until the user says they don't want to post
            //    another.
        
        } while (yesNoRequest(prompt: "Post another message (Y/N)? "))

        // 10. Display a list of the messages in each queue by using
        //     `ReceiveMessage`. Show at least the body and the attributes.

        print(rowOfStars)
        print("Contents of queue 1:")
        let q1DeleteList = try await receiveAndListMessages(sqsClient: sqsClient, queueUrl: q1Url)
        print("\n\nContents of queue 2:")
        let q2DeleteList = try await receiveAndListMessages(sqsClient: sqsClient, queueUrl: q2Url)
        print(rowOfStars)

        returnRequest(prompt: "\nPress return to clean up: ")

        // 11. Delete the received messages using `DeleteMessageBatch`.

        print("Deleting the messages from queue 1...")
        try await deleteMessageList(sqsClient: sqsClient, queueUrl: q1Url, deleteList: q1DeleteList)
        print("\nDeleting the messages from queue 2...")
        try await deleteMessageList(sqsClient: sqsClient, queueUrl: q2Url, deleteList: q2DeleteList)

        // 12. Unsubscribe and delete both queues.

        print("\nUnsubscribing from queue 1...")
        _ = try await snsClient.unsubscribe(
            input: UnsubscribeInput(subscriptionArn: q1SubscriptionArn)
        )

        print("Unsubscribing from queue 2...")
        _ = try await snsClient.unsubscribe(
            input: UnsubscribeInput(subscriptionArn: q2SubscriptionArn)
        )

        print("Deleting queue 1...")
        _ = try await sqsClient.deleteQueue(
            input: DeleteQueueInput(queueUrl: q1Url)
        )

        print("Deleting queue 2...")
        _ = try await sqsClient.deleteQueue(
            input: DeleteQueueInput(queueUrl: q2Url)
        )
        
        // 13. Delete the topic.

        print("Deleting the SNS topic...")
        _ = try await snsClient.deleteTopic(
            input: DeleteTopicInput(topicArn: topicArn)
        )
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [CreateQueue](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/createqueue(input:))
  + [CreateTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/createtopic(input:))
  + [DeleteMessageBatch](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/deletemessagebatch(input:))
  + [DeleteQueue](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/deletequeue(input:))
  + [DeleteTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/deletetopic(input:))
  + [GetQueueAttributes](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/getqueueattributes(input:))
  + [Publish](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/publish(input:))
  + [ReceiveMessage](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/receivemessage(input:))
  + [SetQueueAttributes](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/setqueueattributes(input:))
  + [Subscribe](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/subscribe(input:))
  + [Unsubscribe](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/unsubscribe(input:))

# SDK for Swift を使用した Amazon SQS の例
<a name="swift_1_sqs_code_examples"></a>

次のコード例は、Amazon SQS で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

**Topics**
+ [はじめに](#get_started)
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## はじめに
<a name="get_started"></a>

### Hello Amazon SQS
<a name="sqs_Hello_swift_1_topic"></a>

次のコード例は、Amazon SQS の使用を開始する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。
`Package.swift` ファイル。  

```
import PackageDescription

let package = Package(
    name: "sqs-basics",
    // Let Xcode know the minimum Apple platforms supported.
    platforms: [
        .macOS(.v13),
        .iOS(.v15)
    ],
    dependencies: [
        // Dependencies declare other packages that this package depends on.
        .package(
            url: "https://github.com/awslabs/aws-sdk-swift",
            from: "1.0.0"),
        .package(
            url: "https://github.com/apple/swift-argument-parser.git",
            branch: "main"
        )
    ],
    targets: [
        // Targets are the basic building blocks of a package, defining a module or a test suite.
        // Targets can depend on other targets in this package and products
        // from dependencies.
        .executableTarget(
            name: "sqs-basics",
            dependencies: [
                .product(name: "AWSSQS", package: "aws-sdk-swift"),
                .product(name: "ArgumentParser", package: "swift-argument-parser")
            ],
            path: "Sources")

    ]
)
```
Swift ソースコード、`entry.swift`。  

```
import ArgumentParser
import AWSClientRuntime
import AWSSQS
import Foundation

struct ExampleCommand: ParsableCommand {
    @Option(help: "Name of the Amazon Region to use (default: us-east-1)")
    var region = "us-east-1"

    static var configuration = CommandConfiguration(
        commandName: "sqs-basics",
        abstract: """
        This example shows how to list all of your available Amazon SQS queues.
        """,
        discussion: """
        """
    )
    
    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        var queues: [String] = []
        let outputPages = sqsClient.listQueuesPaginated(
            input: ListQueuesInput()
        )

        // Each time a page of results arrives, process its contents.

        for try await output in outputPages {
            guard let urls = output.queueUrls else {
                print("No queues found.")
                return
            }

            // Iterate over the queue URLs listed on this page, adding them
            // to the `queues` array.

            for queueUrl in urls {
                queues.append(queueUrl)
            }
        }

        print("You have \(queues.count) queues:")
        for queue in queues {
            print("   \(queue)")
        }
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ListQueues](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/listqueues(input:))」を参照してください。**

## アクション
<a name="actions"></a>

### `CreateQueue`
<a name="sqs_CreateQueue_swift_1_topic"></a>

次のコード例は、`CreateQueue` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import AWSSQS

        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        let output = try await sqsClient.createQueue(
            input: CreateQueueInput(
                queueName: queueName
            )
        )

        guard let queueUrl = output.queueUrl else {
            print("No queue URL returned.")
            return
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[CreateQueue](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/createqueue(input:))」を参照してください。**

### `DeleteMessageBatch`
<a name="sqs_DeleteMessageBatch_swift_1_topic"></a>

次のコード例は、`DeleteMessageBatch` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import AWSSQS

        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        // Create the list of message entries.

        var entries: [SQSClientTypes.DeleteMessageBatchRequestEntry] = []
        var messageNumber = 1

        for handle in handles {
            let entry = SQSClientTypes.DeleteMessageBatchRequestEntry(
                id: "\(messageNumber)",
                receiptHandle: handle
            )
            entries.append(entry)
            messageNumber += 1
        }

        // Delete the messages.

        let output = try await sqsClient.deleteMessageBatch(
            input: DeleteMessageBatchInput(
                entries: entries,
                queueUrl: queue
            )
        )

        // Get the lists of failed and successful deletions from the output.

        guard let failedEntries = output.failed else {
            print("Failed deletion list is missing!")
            return
        }
        guard let successfulEntries = output.successful else {
            print("Successful deletion list is missing!")
            return
        }

        // Display a list of the failed deletions along with their
        // corresponding explanation messages.

        if failedEntries.count != 0 {
            print("Failed deletions:")

            for entry in failedEntries {
                print("Message #\(entry.id ?? "<unknown>") failed: \(entry.message ?? "<unknown>")")
            }
        } else {
            print("No failed deletions.")
        }

        // Output a list of the message numbers that were successfully deleted.

        if successfulEntries.count != 0 {
            var successes = ""

            for entry in successfulEntries {
                if successes.count == 0 {
                    successes = entry.id ?? "<unknown>"
                } else {
                    successes = "\(successes), \(entry.id ?? "<unknown>")"
                }
            }
            print("Succeeded: ", successes)
        } else {
            print("No successful deletions.")
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DeleteMessageBatch](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/deletemessagebatch(input:))」を参照してください。**

### `DeleteQueue`
<a name="sqs_DeleteQueue_swift_1_topic"></a>

次のコード例は、`DeleteQueue` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import AWSSQS

        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        do {
            _ = try await sqsClient.deleteQueue(
                input: DeleteQueueInput(
                    queueUrl: queueUrl
                )
            )
        } catch _ as AWSSQS.QueueDoesNotExist {
            print("Error: The specified queue doesn't exist.")
            return
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[DeleteQueue](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/deletequeue(input:))」を参照してください。**

### `GetQueueAttributes`
<a name="sqs_GetQueueAttributes_swift_1_topic"></a>

次のコード例は、`GetQueueAttributes` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import AWSSQS

        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        let output = try await sqsClient.getQueueAttributes(
            input: GetQueueAttributesInput(
                attributeNames: [
                    .approximatenumberofmessages,
                    .maximummessagesize
                ],
                queueUrl: url
            )
        )

        guard let attributes = output.attributes else {
            print("No queue attributes returned.")
            return
        }
        
        for (attr, value) in attributes {
            switch(attr) {
            case "ApproximateNumberOfMessages":
                print("Approximate message count: \(value)")    
            case "MaximumMessageSize":
                print("Maximum message size: \(value)kB")
            default:
                continue
            }
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[GetQueueAttributes](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/getqueueattributes(input:))」を参照してください。**

### `ListQueues`
<a name="sqs_ListQueues_swift_1_topic"></a>

次のコード例は、`ListQueues` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import AWSSQS

        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        var queues: [String] = []
        let outputPages = sqsClient.listQueuesPaginated(
            input: ListQueuesInput()
        )

        // Each time a page of results arrives, process its contents.

        for try await output in outputPages {
            guard let urls = output.queueUrls else {
                print("No queues found.")
                return
            }

            // Iterate over the queue URLs listed on this page, adding them
            // to the `queues` array.

            for queueUrl in urls {
                queues.append(queueUrl)
            }
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ListQueues](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/listqueues(input:))」を参照してください。**

### `ReceiveMessage`
<a name="sqs_ReceiveMessage_swift_1_topic"></a>

次のコード例は、`ReceiveMessage` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import AWSSQS

        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        let output = try await sqsClient.receiveMessage(
            input: ReceiveMessageInput(
                maxNumberOfMessages: maxMessages,
                queueUrl: url
            )
        )

        guard let messages = output.messages else {
            print("No messages received.")
            return
        }
    
        for message in messages {
            print("Message ID:     \(message.messageId ?? "<unknown>")")
            print("Receipt handle: \(message.receiptHandle ?? "<unknown>")")
            print(message.body ?? "<body missing>")
            print("---")
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[ReceiveMessage](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/receivemessage(input:))」を参照してください。**

### `SetQueueAttributes`
<a name="sqs_SetQueueAttributes_swift_1_topic"></a>

次のコード例は、`SetQueueAttributes` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs#code-examples)での設定と実行の方法を確認してください。

```
import AWSSQS

        let config = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: config)

        do {
            _ = try await sqsClient.setQueueAttributes(
                input: SetQueueAttributesInput(
                    attributes: [
                        "MaximumMessageSize": "\(maxSize)"
                    ],
                    queueUrl: url
                )
            )
        } catch _ as AWSSQS.InvalidAttributeValue {
            print("Invalid maximum message size: \(maxSize) kB.")
        }
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[SetQueueAttributes](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/setqueueattributes(input:))」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### メッセージをキューに発行する
<a name="sqs_Scenario_TopicsAndQueues_swift_1_topic"></a>

次のコード例は、以下の操作方法を示しています。
+ トピック (FIFO または非 FIFO) を作成します。
+ フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。
+ メッセージをトピックに発行します。
+ 受信したメッセージのキューをポーリングします。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sqs/scenario#code-examples)での設定と実行の方法を確認してください。

```
import ArgumentParser
import AWSClientRuntime
import AWSSNS
import AWSSQS
import Foundation

struct ExampleCommand: ParsableCommand {
    @Option(help: "Name of the Amazon Region to use")
    var region = "us-east-1"

    static var configuration = CommandConfiguration(
        commandName: "queue-scenario",
        abstract: """
        This example interactively demonstrates how to use Amazon Simple
        Notification Service (Amazon SNS) and Amazon Simple Queue Service
        (Amazon SQS) together to publish and receive messages using queues.
        """,
        discussion: """
        Supports filtering using a "tone" attribute.
        """
    )

    /// Prompt for an input string. Only non-empty strings are allowed.
    /// 
    /// - Parameter prompt: The prompt to display.
    ///
    /// - Returns: The string input by the user.
    func stringRequest(prompt: String) -> String {
        var str: String?

        while str == nil {
            print(prompt, terminator: "")
            str = readLine()

            if str != nil && str?.count == 0 {
                str = nil
            }
        }

        return str!
    }

    /// Ask a yes/no question.
    /// 
    /// - Parameter prompt: A prompt string to print.
    ///
    /// - Returns: `true` if the user answered "Y", otherwise `false`.
    func yesNoRequest(prompt: String) -> Bool {
        while true {
            let answer = stringRequest(prompt: prompt).lowercased()
            if answer == "y" || answer == "n" {
                return answer == "y"
            }
        }
    }

    /// Display a menu of options then request a selection.
    /// 
    /// - Parameters:
    ///   - prompt: A prompt string to display before the menu.
    ///   - options: An array of strings giving the menu options.
    ///
    /// - Returns: The index number of the selected option or 0 if no item was
    ///   selected.
    func menuRequest(prompt: String, options: [String]) -> Int {
        let numOptions = options.count

        if numOptions == 0 {
            return 0
        }

        print(prompt)

        for (index, value) in options.enumerated() {
            print("(\(index)) \(value)")
        }

        repeat {
            print("Enter your selection (0 - \(numOptions-1)): ", terminator: "")
            if let answer = readLine() {
                guard let answer = Int(answer) else {
                    print("Please enter the number matching your selection.")
                    continue
                }

                if answer >= 0 && answer < numOptions {
                    return answer
                } else {
                    print("Please enter the number matching your selection.")
                }
            }
        } while true
    }
    
    /// Ask the user too press RETURN. Accepts any input but ignores it.
    /// 
    /// - Parameter prompt: The text prompt to display.
    func returnRequest(prompt: String) {
        print(prompt, terminator: "")
        _ = readLine()
    }

    var attrValues = [
        "<none>",
        "cheerful",
        "funny",
        "serious",
        "sincere"
    ]

    /// Ask the user to choose one of the attribute values to use as a filter.
    /// 
    /// - Parameters:
    ///   - message: A message to display before the menu of values.
    ///   - attrValues: An array of strings giving the values to choose from.
    /// 
    /// - Returns: The string corresponding to the selected option.
    func askForFilter(message: String, attrValues: [String]) -> String? {
        print(message)
        for (index, value) in attrValues.enumerated() {
            print("  [\(index)] \(value)")
        }

        var answer: Int?
        repeat {
            answer = Int(stringRequest(prompt: "Select an value for the 'tone' attribute or 0 to end: "))
        } while answer == nil || answer! < 0 || answer! > attrValues.count + 1

        if answer == 0 {
            return nil
        }
        return attrValues[answer!]
    }

    /// Prompts the user for filter terms and constructs the attribute
    /// record that specifies them.
    /// 
    /// - Returns: A mapping of "FilterPolicy" to a JSON string representing
    ///   the user-defined filter.
    func buildFilterAttributes() -> [String:String] {
        var attr: [String:String] = [:]
        var filterString = ""

        var first = true

        while let ans = askForFilter(message: "Choose a value to apply to the 'tone' attribute.",
                                    attrValues: attrValues) {
            if !first {
                filterString += ","
            }
            first = false

            filterString += "\"\(ans)\""
        }

        let filterJSON = "{ \"tone\": [\(filterString)]}"
        attr["FilterPolicy"] = filterJSON

        return attr
    }
    /// Create a queue, returning its URL string.
    ///
    /// - Parameters:
    ///   - prompt: A prompt to ask for the queue name.
    ///   - isFIFO: Whether or not to create a FIFO queue.
    ///
    /// - Returns: The URL of the queue.
    func createQueue(prompt: String, sqsClient: SQSClient, isFIFO: Bool) async throws -> String? {
        repeat {
            var queueName = stringRequest(prompt: prompt)
            var attributes: [String: String] = [:]

            if isFIFO {
                queueName += ".fifo"
                attributes["FifoQueue"] = "true"
            }

            do {
                let output = try await sqsClient.createQueue(
                    input: CreateQueueInput(
                        attributes: attributes,
                        queueName: queueName
                    )
                )
                guard let url = output.queueUrl else {
                    return nil
                }

                return url
            } catch _ as QueueDeletedRecently {
                print("You need to use a different queue name. A queue by that name was recently deleted.")
                continue
            }
        } while true
    }

    /// Return the ARN of a queue given its URL.
    ///
    /// - Parameter queueUrl: The URL of the queue for which to return the
    ///   ARN.
    ///
    /// - Returns: The ARN of the specified queue.
    func getQueueARN(sqsClient: SQSClient, queueUrl: String) async throws -> String? {
        let output = try await sqsClient.getQueueAttributes(
            input: GetQueueAttributesInput(
                attributeNames: [.queuearn],
                queueUrl: queueUrl
            )
        )

        guard let attributes = output.attributes else {
            return nil
        }
        
        return attributes["QueueArn"]
    }

    /// Applies the needed policy to the specified queue.
    /// 
    /// - Parameters:
    ///   - sqsClient: The Amazon SQS client to use.
    ///   - queueUrl: The queue to apply the policy to.
    ///   - queueArn: The ARN of the queue to apply the policy to.
    ///   - topicArn: The topic that should have access via the policy.
    ///
    /// - Throws: Errors from the SQS `SetQueueAttributes` action.
    func setQueuePolicy(sqsClient: SQSClient, queueUrl: String,
                        queueArn: String, topicArn: String) async throws {
        _ = try await sqsClient.setQueueAttributes(
            input: SetQueueAttributesInput(
                attributes: [
                    "Policy":
                        """
                        {
                            "Statement": [
                                {
                                    "Effect": "Allow",
                                    "Principal": {
                                        "Service": "sns.amazonaws.com"
                                    },
                                    "Action": "sqs:SendMessage",
                                    "Resource": "\(queueArn)",
                                    "Condition": {
                                        "ArnEquals": {
                                            "aws:SourceArn": "\(topicArn)"
                                        }
                                    }
                                }
                            ]
                        }
                        """

                ],
                queueUrl: queueUrl
            )
        )
    }

    /// Receive the available messages on a queue, outputting them to the
    /// screen. Returns a dictionary you pass to DeleteMessageBatch to delete
    /// all the received messages.
    /// 
    /// - Parameters:
    ///   - sqsClient: The Amazon SQS client to use.
    ///   - queueUrl: The SQS queue on which to receive messages.
    /// 
    /// - Throws: Errors from `SQSClient.receiveMessage()`
    ///
    /// - Returns: An array of SQSClientTypes.DeleteMessageBatchRequestEntry
    ///   items, each describing one received message in the format needed to
    ///   delete it.
    func receiveAndListMessages(sqsClient: SQSClient, queueUrl: String) async throws
                                -> [SQSClientTypes.DeleteMessageBatchRequestEntry] {
        let output = try await sqsClient.receiveMessage(
            input: ReceiveMessageInput(
                maxNumberOfMessages: 10,
                queueUrl: queueUrl
            )
        )

        guard let messages = output.messages else {
            print("No messages received.")
            return []
        }

        var deleteList: [SQSClientTypes.DeleteMessageBatchRequestEntry] = []

        // Print out all the messages that were received, including their
        // attributes, if any.

        for message in messages {
            print("Message ID:     \(message.messageId ?? "<unknown>")")
            print("Receipt handle: \(message.receiptHandle ?? "<unknown>")")
            print("Message JSON:   \(message.body ?? "<body missing>")")
            
            if message.receiptHandle != nil {
                deleteList.append(
                    SQSClientTypes.DeleteMessageBatchRequestEntry(
                        id: message.messageId,
                        receiptHandle: message.receiptHandle
                    )
                )
            }
        }

        return deleteList
    }

    /// Delete all the messages in the specified list.
    /// 
    /// - Parameters:
    ///   - sqsClient: The Amazon SQS client to use.
    ///   - queueUrl: The SQS queue to delete messages from.
    ///   - deleteList: A list of `DeleteMessageBatchRequestEntry` objects
    ///     describing the messages to delete.
    ///
    /// - Throws: Errors from `SQSClient.deleteMessageBatch()`.
    func deleteMessageList(sqsClient: SQSClient, queueUrl: String,
                           deleteList: [SQSClientTypes.DeleteMessageBatchRequestEntry]) async throws {
        let output = try await sqsClient.deleteMessageBatch(
            input: DeleteMessageBatchInput(entries: deleteList, queueUrl: queueUrl)
        )

        if let failed = output.failed {
            print("\(failed.count) errors occurred deleting messages from the queue.")
            for message in failed {
                print("---> Failed to delete message \(message.id ?? "<unknown ID>") with error: \(message.code ?? "<unknown>") (\(message.message ?? "..."))")
            }
        }
    }

    /// Called by ``main()`` to run the bulk of the example.
    func runAsync() async throws {
        let rowOfStars = String(repeating: "*", count: 75)

        print("""
              \(rowOfStars)
              Welcome to the cross-service messaging with topics and queues example.
              In this workflow, you'll create an SNS topic, then create two SQS
              queues which will be subscribed to that topic.

              You can specify several options for configuring the topic, as well as
              the queue subscriptions. You can then post messages to the topic and
              receive the results on the queues.
              \(rowOfStars)\n
              """
        )

        // 0. Create SNS and SQS clients.

        let snsConfig = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: snsConfig)

        let sqsConfig = try await SQSClient.SQSClientConfiguration(region: region)
        let sqsClient = SQSClient(config: sqsConfig)

        // 1. Ask the user whether to create a FIFO topic. If so, ask whether
        //    to use content-based deduplication instead of requiring a
        //    deduplication ID.

        let isFIFO = yesNoRequest(prompt: "Do you want to create a FIFO topic (Y/N)? ")
        var isContentBasedDeduplication = false

        if isFIFO {
            print("""
                  \(rowOfStars)
                  Because you've chosen to create a FIFO topic, deduplication is
                  supported.

                  Deduplication IDs are either set in the message or are automatically
                  generated from the content using a hash function.

                  If a message is successfully published to an SNS FIFO topic, any
                  message published and found to have the same deduplication ID
                  (within a five-minute deduplication interval), is accepted but
                  not delivered.

                  For more information about deduplication, see:
                  https://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.
                  """
            )

            isContentBasedDeduplication = yesNoRequest(
                prompt: "Use content-based deduplication instead of entering a deduplication ID (Y/N)? ")
            print(rowOfStars)
        }

        var topicName = stringRequest(prompt: "Enter the name of the topic to create: ")
        
        // 2. Create the topic. Append ".fifo" to the name if FIFO was
        //    requested, and set the "FifoTopic" attribute to "true" if so as
        //    well. Set the "ContentBasedDeduplication" attribute to "true" if
        //    content-based deduplication was requested.

        if isFIFO {
            topicName += ".fifo"
        }

        print("Topic name: \(topicName)")

        var attributes = [
            "FifoTopic": (isFIFO ? "true" : "false")
        ]

        // If it's a FIFO topic with content-based deduplication, set the
        // "ContentBasedDeduplication" attribute.

        if isContentBasedDeduplication {
            attributes["ContentBasedDeduplication"] = "true"
        }

        // Create the topic and retrieve the ARN.

        let output = try await snsClient.createTopic(
            input: CreateTopicInput(
                attributes: attributes,
                name: topicName
            )
        )

        guard let topicArn = output.topicArn else {
            print("No topic ARN returned!")
            return
        }

        print("""
              Topic '\(topicName) has been created with the
              topic ARN \(topicArn)."
              """
        )
        
        print(rowOfStars)

        // 3. Create an SQS queue. Append ".fifo" to the name if one of the
        //    FIFO topic configurations was chosen, and set "FifoQueue" to
        //    "true" if the topic is FIFO.

        print("""
              Next, you will create two SQS queues that will be subscribed
              to the topic you just created.\n
              """
        )

        let q1Url = try await createQueue(prompt: "Enter the name of the first queue: ",
                                          sqsClient: sqsClient, isFIFO: isFIFO)
        guard let q1Url else {
            print("Unable to create queue 1!")
            return
        }
        
        // 4. Get the SQS queue's ARN attribute using `GetQueueAttributes`.

        let q1Arn = try await getQueueARN(sqsClient: sqsClient, queueUrl: q1Url)

        guard let q1Arn else {
            print("Unable to get ARN of queue 1!")
            return
        }
        print("Got queue 1 ARN: \(q1Arn)")

        // 5. Attach an AWS IAM policy to the queue using
        //    `SetQueueAttributes`.

        try await setQueuePolicy(sqsClient: sqsClient, queueUrl: q1Url,
                                 queueArn: q1Arn, topicArn: topicArn)

        // 6. Subscribe the SQS queue to the SNS topic. Set the topic ARN in
        //    the request. Set the protocol to "sqs". Set the queue ARN to the
        //    ARN just received in step 5. For FIFO topics, give the option to
        //    apply a filter. A filter allows only matching messages to enter
        //    the queue.

        var q1Attributes: [String:String]? = nil

        if isFIFO {
            print(
                """

                If you add a filter to this subscription, then only the filtered messages will
                be received in the queue. For information about message filtering, see
                https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html
                For this example, you can filter messages by a 'tone' attribute.

                """
            )

            let subPrompt = """
                Would you like to filter messages for the first queue's subscription to the
                topic \(topicName) (Y/N)? 
                """
            if (yesNoRequest(prompt: subPrompt)) {
                q1Attributes = buildFilterAttributes()
            }
        }

        let sub1Output = try await snsClient.subscribe(
            input: SubscribeInput(
                attributes: q1Attributes,
                endpoint: q1Arn,
                protocol: "sqs",
                topicArn: topicArn
            )
        )

        guard let q1SubscriptionArn = sub1Output.subscriptionArn else {
            print("Invalid subscription ARN returned for queue 1!")
            return
        }

        // 7. Repeat steps 3-6 for the second queue.

        let q2Url = try await createQueue(prompt: "Enter the name of the second queue: ",
                                sqsClient: sqsClient, isFIFO: isFIFO)
    
        guard let q2Url else {
            print("Unable to create queue 2!")
            return
        }

        let q2Arn = try await getQueueARN(sqsClient: sqsClient, queueUrl: q2Url)

        guard let q2Arn else {
            print("Unable to get ARN of queue 2!")
            return
        }
        print("Got queue 2 ARN: \(q2Arn)")

        try await setQueuePolicy(sqsClient: sqsClient, queueUrl: q2Url,
                                 queueArn: q2Arn, topicArn: topicArn)

        var q2Attributes: [String:String]? = nil

        if isFIFO {
            let subPrompt = """
                Would you like to filter messages for the second queue's subscription to the
                topic \(topicName) (Y/N)? 
                """
            if (yesNoRequest(prompt: subPrompt)) {
                q2Attributes = buildFilterAttributes()
            }
        }

        let sub2Output = try await snsClient.subscribe(
            input: SubscribeInput(
                attributes: q2Attributes,
                endpoint: q2Arn,
                protocol: "sqs",
                topicArn: topicArn
            )
        )

        guard let q2SubscriptionArn = sub2Output.subscriptionArn else {
            print("Invalid subscription ARN returned for queue 1!")
            return
        }

        // 8. Let the user publish messages to the topic, asking for a message
        //    body for each message. Handle the types of topic correctly (SEE
        //    MVP INFORMATION AND FIX THESE COMMENTS!!!

        print("\n\(rowOfStars)\n")

        var first = true

        repeat {
            var publishInput = PublishInput(
                topicArn: topicArn
            )

            publishInput.message = stringRequest(prompt: "Enter message text to publish: ")

            // If using a FIFO topic, a message group ID must be set on the
            // message.

            if isFIFO {
                if first {
                    print("""
                        Because you're using a FIFO topic, you must set a message
                        group ID. All messages within the same group will be
                        received in the same order in which they were published.\n
                        """
                    )
                }
                publishInput.messageGroupId = stringRequest(prompt: "Enter a message group ID for this message: ")

                if !isContentBasedDeduplication {
                    if first {
                        print("""
                              Because you're not using content-based deduplication, you
                              must enter a deduplication ID. If other messages with the
                              same deduplication ID are published within the same
                              deduplication interval, they will not be delivered.
                              """
                        )
                    }
                    publishInput.messageDeduplicationId = stringRequest(prompt: "Enter a deduplication ID for this message: ")
                }
            }

            // Allow the user to add a value for the "tone" attribute if they
            // wish to do so.

            var messageAttributes: [String:SNSClientTypes.MessageAttributeValue] = [:]
            let attrValSelection = menuRequest(prompt: "Choose a tone to apply to this message.", options: attrValues)

            if attrValSelection != 0 {
                let val = SNSClientTypes.MessageAttributeValue(dataType: "String", stringValue: attrValues[attrValSelection])
                messageAttributes["tone"] = val
            }

            publishInput.messageAttributes = messageAttributes
            
            // Publish the message and display its ID.

            let publishOutput = try await snsClient.publish(input: publishInput)

            guard let messageID = publishOutput.messageId else {
                print("Unable to get the published message's ID!")
                return
            }

            print("Message published with ID \(messageID).")
            first = false

            // 9. Repeat step 8 until the user says they don't want to post
            //    another.
        
        } while (yesNoRequest(prompt: "Post another message (Y/N)? "))

        // 10. Display a list of the messages in each queue by using
        //     `ReceiveMessage`. Show at least the body and the attributes.

        print(rowOfStars)
        print("Contents of queue 1:")
        let q1DeleteList = try await receiveAndListMessages(sqsClient: sqsClient, queueUrl: q1Url)
        print("\n\nContents of queue 2:")
        let q2DeleteList = try await receiveAndListMessages(sqsClient: sqsClient, queueUrl: q2Url)
        print(rowOfStars)

        returnRequest(prompt: "\nPress return to clean up: ")

        // 11. Delete the received messages using `DeleteMessageBatch`.

        print("Deleting the messages from queue 1...")
        try await deleteMessageList(sqsClient: sqsClient, queueUrl: q1Url, deleteList: q1DeleteList)
        print("\nDeleting the messages from queue 2...")
        try await deleteMessageList(sqsClient: sqsClient, queueUrl: q2Url, deleteList: q2DeleteList)

        // 12. Unsubscribe and delete both queues.

        print("\nUnsubscribing from queue 1...")
        _ = try await snsClient.unsubscribe(
            input: UnsubscribeInput(subscriptionArn: q1SubscriptionArn)
        )

        print("Unsubscribing from queue 2...")
        _ = try await snsClient.unsubscribe(
            input: UnsubscribeInput(subscriptionArn: q2SubscriptionArn)
        )

        print("Deleting queue 1...")
        _ = try await sqsClient.deleteQueue(
            input: DeleteQueueInput(queueUrl: q1Url)
        )

        print("Deleting queue 2...")
        _ = try await sqsClient.deleteQueue(
            input: DeleteQueueInput(queueUrl: q2Url)
        )
        
        // 13. Delete the topic.

        print("Deleting the SNS topic...")
        _ = try await snsClient.deleteTopic(
            input: DeleteTopicInput(topicArn: topicArn)
        )
    }
}

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.runAsync()
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}
```
+ API の詳細については、*AWS SDK for Swift API リファレンス*の以下のトピックを参照してください。
  + [CreateQueue](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/createqueue(input:))
  + [CreateTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/createtopic(input:))
  + [DeleteMessageBatch](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/deletemessagebatch(input:))
  + [DeleteQueue](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/deletequeue(input:))
  + [DeleteTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/deletetopic(input:))
  + [GetQueueAttributes](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/getqueueattributes(input:))
  + [Publish](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/publish(input:))
  + [ReceiveMessage](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/receivemessage(input:))
  + [SetQueueAttributes](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs/sqsclient/setqueueattributes(input:))
  + [Subscribe](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/subscribe(input:))
  + [Unsubscribe](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/unsubscribe(input:))

# AWS STS SDK for Swift を使用した の例
<a name="swift_1_sts_code_examples"></a>

次のコード例は、 で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています AWS STS。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)

## アクション
<a name="actions"></a>

### `AssumeRole`
<a name="sts_AssumeRole_swift_1_topic"></a>

次のコード例は、`AssumeRole` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/iam#code-examples)での設定と実行の方法を確認してください。

```
import AWSSTS

    public func assumeRole(role: IAMClientTypes.Role, sessionName: String)
        async throws -> STSClientTypes.Credentials
    {
        let input = AssumeRoleInput(
            roleArn: role.arn,
            roleSessionName: sessionName
        )
        do {
            let output = try await stsClient.assumeRole(input: input)

            guard let credentials = output.credentials else {
                throw ServiceHandlerError.authError
            }

            return credentials
        } catch {
            print("Error assuming role: ", dump(error))
            throw error
        }
    }
```
+  API の詳細については、「AWS SDK for Swift API リファレンス」の「[AssumeRole](https://sdk.amazonaws.com/swift/api/awssts/latest/documentation/awssts/stsclient/assumerole(input:))」を参照してください。

# SDK for Swift を使用した Amazon Transcribe ストリーミングの例
<a name="swift_1_transcribe-streaming_code_examples"></a>

次のコード例は、Amazon Transcribe Streaming で AWS SDK for Swift を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

*アクション*はより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、コンテキスト内のアクションは、関連するシナリオで確認できます。

*シナリオ*は、1 つのサービス内から、または他の AWS のサービスと組み合わせて複数の関数を呼び出し、特定のタスクを実行する方法を示すコード例です。

各例には完全なソースコードへのリンクが含まれており、コードの設定方法と実行方法に関する手順を確認できます。

**Topics**
+ [アクション](#actions)
+ [シナリオ](#scenarios)

## アクション
<a name="actions"></a>

### `StartStreamTranscription`
<a name="transcribe-streaming_StartStreamTranscription_swift_1_topic"></a>

次のコード例は、`StartStreamTranscription` を使用する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。

```
        let client = TranscribeStreamingClient(
            config: try await TranscribeStreamingClient.TranscribeStreamingClientConfiguration(
                region: region
            )
        )

        // Start the transcription running on the audio stream.

        let output = try await client.startStreamTranscription(
            input: StartStreamTranscriptionInput(
                audioStream: try await createAudioStream(),
                languageCode: TranscribeStreamingClientTypes.LanguageCode(rawValue: lang),
                mediaEncoding: encoding,
                mediaSampleRateHertz: sampleRate
            )
        )
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[StartStreamTranscription](https://sdk.amazonaws.com/swift/api/awstranscribestreaming/latest/documentation/awstranscribestreaming/transcribestreamingclient/startstreamtranscription(input:))」を参照してください。**

## シナリオ
<a name="scenarios"></a>

### 音声ファイルの文字起こし
<a name="transcribe-streaming_Scenario_StreamEvents_File_swift_1_topic"></a>

次のコード例は、Amazon Transcribe ストリーミングを使用してソース音声ファイルの文字起こしを生成する方法を示しています。

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/transcribe-streaming#code-examples)での設定と実行の方法を確認してください。
Amazon Transcribe ストリーミングを使用して、音声ファイル内の音声言語を文字起こしします。  

```
/// An example that demonstrates how to watch an transcribe event stream to
/// transcribe audio from a file to the console.

import ArgumentParser
import AWSClientRuntime
import AWSTranscribeStreaming
import Foundation

/// Identify one of the media file formats supported by Amazon Transcribe.
enum TranscribeFormat: String, ExpressibleByArgument {
    case ogg = "ogg"
    case pcm = "pcm"
    case flac = "flac"
}

// -MARK: - Async command line tool

struct ExampleCommand: ParsableCommand {
    // -MARK: Command arguments
    @Flag(help: "Show partial results")
    var showPartial = false
    @Option(help: "Language code to transcribe into")
    var lang: String = "en-US"
    @Option(help: "Format of the source audio file")
    var format: TranscribeFormat
    @Option(help: "Sample rate of the source audio file in Hertz")
    var sampleRate: Int = 16000
    @Option(help: "Path of the source audio file")
    var path: String
    @Option(help: "Name of the Amazon S3 Region to use (default: us-east-1)")
    var region = "us-east-1"

    static var configuration = CommandConfiguration(
        commandName: "tsevents",
        abstract: """
        This example shows how to use event streaming with Amazon Transcribe.
        """,
        discussion: """
        """
    )

    /// Create and return an Amazon Transcribe audio stream from the file
    /// specified in the arguments.
    /// 
    /// - Throws: Errors from `TranscribeError`.
    ///
    /// - Returns: `AsyncThrowingStream<TranscribeStreamingClientTypes.AudioStream, Error>`
    func createAudioStream() async throws
                -> AsyncThrowingStream<TranscribeStreamingClientTypes.AudioStream, Error> {

        let fileURL: URL = URL(fileURLWithPath: path)
        let audioData = try Data(contentsOf: fileURL)

        // Properties defining the size of audio chunks and the total size of
        // the audio file in bytes. You should try to send chunks that last on
        // average 125 milliseconds.

        let chunkSizeInMilliseconds = 125.0
        let chunkSize = Int(chunkSizeInMilliseconds  / 1000.0 * Double(sampleRate) * 2.0)
        let audioDataSize = audioData.count

        // Create an audio stream from the source data. The stream's job is
        // to send the audio in chunks to Amazon Transcribe as
        // `AudioStream.audioevent` events.

        let audioStream = AsyncThrowingStream<TranscribeStreamingClientTypes.AudioStream,
                                Error> { continuation in
            Task {
                var currentStart = 0
                var currentEnd = min(chunkSize, audioDataSize - currentStart)

                // Generate and send chunks of audio data as `audioevent`
                // events until the entire file has been sent. Each event is
                // yielded to the SDK after being created.

                while currentStart < audioDataSize {
                    let dataChunk = audioData[currentStart ..< currentEnd]
                    
                    let audioEvent = TranscribeStreamingClientTypes.AudioStream.audioevent(
                        .init(audioChunk: dataChunk)
                    )
                    let yieldResult = continuation.yield(audioEvent)
                    switch yieldResult {
                        case .enqueued(_):
                            // The chunk was successfully enqueued into the
                            // stream. The `remaining` parameter estimates how
                            // much room is left in the queue, but is ignored here.
                            break
                        case .dropped(_):
                            // The chunk was dropped because the queue buffer
                            // is full. This will cause transcription errors.
                            print("Warning: Dropped audio! The transcription will be incomplete.")
                        case .terminated:
                            print("Audio stream terminated.")
                            continuation.finish()
                            return
                        default:
                            print("Warning: Unrecognized response during audio streaming.")
                    }

                    currentStart = currentEnd
                    currentEnd = min(currentStart + chunkSize, audioDataSize)
                }

                // Let the SDK's continuation block know the stream is over.

                continuation.finish()
            }
        }

        return audioStream
    }

    /// Run the transcription process.
    ///
    /// - Throws: An error from `TranscribeError`.
    func transcribe(encoding: TranscribeStreamingClientTypes.MediaEncoding) async throws {
        // Create the Transcribe Streaming client.

        let client = TranscribeStreamingClient(
            config: try await TranscribeStreamingClient.TranscribeStreamingClientConfiguration(
                region: region
            )
        )

        // Start the transcription running on the audio stream.

        let output = try await client.startStreamTranscription(
            input: StartStreamTranscriptionInput(
                audioStream: try await createAudioStream(),
                languageCode: TranscribeStreamingClientTypes.LanguageCode(rawValue: lang),
                mediaEncoding: encoding,
                mediaSampleRateHertz: sampleRate
            )
        )

        // Iterate over the events in the returned transcript result stream.
        // Each `transcriptevent` contains a list of result fragments which
        // need to be concatenated together to build the final transcript.
        for try await event in output.transcriptResultStream! {
            switch event {
            case .transcriptevent(let event):
            for result in event.transcript?.results ?? [] {
                guard let transcript = result.alternatives?.first?.transcript else {
                    continue
                }

                // If showing partial results is enabled and the result is
                // partial, show it. Partial results may be incomplete, and
                // may be inaccurate, with upcoming audio making the
                // transcription complete or by giving more context to make
                // transcription make more sense.

                if (result.isPartial && showPartial) {
                    print("[Partial] \(transcript)")
                }

                // When the complete fragment of transcribed text is ready,
                // print it. This could just as easily be used to draw the
                // text as a subtitle over a playing video, though timing
                // would need to be managed.

                if !result.isPartial {
                    if (showPartial) {
                        print("[Final  ] ", terminator: "")
                    }
                    print(transcript)
                }
            }
            default:
                print("Error: Unexpected message from Amazon Transcribe:")
            }
        }
    }

    /// Convert the value of the `--format` command line option into the
    /// corresponding Transcribe Streaming `MediaEncoding` type.
    ///
    /// - Returns: The `MediaEncoding` equivalent of the format specified on
    ///   the command line.
    func getMediaEncoding() -> TranscribeStreamingClientTypes.MediaEncoding {
        let mediaEncoding: TranscribeStreamingClientTypes.MediaEncoding
        
        switch format {
        case .flac:
            mediaEncoding = .flac
        case .ogg:
            mediaEncoding = .oggOpus
        case .pcm:
            mediaEncoding = .pcm
        }

        return mediaEncoding
    }
}

// -MARK: - Entry point

/// The program's asynchronous entry point.
@main
struct Main {
    static func main() async {
        let args = Array(CommandLine.arguments.dropFirst())

        do {
            let command = try ExampleCommand.parse(args)
            try await command.transcribe(encoding: command.getMediaEncoding())
        } catch let error as TranscribeError {
            print("ERROR: \(error.errorDescription ?? "Unknown error")")
        } catch {
            ExampleCommand.exit(withError: error)
        }
    }    
}

/// Errors thrown by the example's functions.
enum TranscribeError: Error {
    /// No transcription stream available.
    case noTranscriptionStream
    /// The source media file couldn't be read.
    case readError

    var errorDescription: String? {
        switch self {
        case .noTranscriptionStream:
            return "No transcription stream returned by Amazon Transcribe."
        case .readError:
            return "Unable to read the source audio file."
        }
    }
}
```
+  API の詳細については、AWS SDK for Swift API リファレンスの「[StartStreamTranscription](https://sdk.amazonaws.com/swift/api/awstranscribestreaming/latest/documentation/awstranscribestreaming/transcribestreamingclient/startstreamtranscription(input:))」を参照してください。**